diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000..a13e76de --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,54 @@ +import js from '@eslint/js'; +import tseslint from 'typescript-eslint'; + +export default tseslint.config( + { + ignores: [ + "node_modules/**", + "dist/**", + "build/**", + "**/*.js", + "**/dist/**", + "launchdarkly/**/dist/**" + ] + }, + js.configs.recommended, + ...tseslint.configs.recommended, + { + languageOptions: { + parser: tseslint.parser, + parserOptions: { + ecmaVersion: 2020, + sourceType: "module", + project: [ + "./tsconfig.json", + "./launchdarkly/tsconfig.json", + "./launchdarkly/node/tsconfig.json", + "./launchdarkly/react/tsconfig.json" + ] + }, + globals: { + console: "readonly", + process: "readonly" + } + }, + rules: { + "@typescript-eslint/explicit-function-return-type": "warn", + "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/prefer-nullish-coalescing": "warn", + "@typescript-eslint/explicit-member-accessibility": [ + "error", + { + "accessibility": "explicit", + "overrides": { + "accessors": "explicit", + "constructors": "explicit", + "methods": "explicit", + "properties": "explicit", + "parameterProperties": "explicit" + } + } + ] + } + } +); \ No newline at end of file diff --git a/launchdarkly/node/EVENT_SYSTEM_README.md b/launchdarkly/node/EVENT_SYSTEM_README.md new file mode 100644 index 00000000..7197b43a --- /dev/null +++ b/launchdarkly/node/EVENT_SYSTEM_README.md @@ -0,0 +1,436 @@ +# Type-Safe Event System Implementation + +This document describes the comprehensive type-safe event system that has been implemented with mapped types for event payload definitions and generic event handler functions with proper type inference. + +## Overview + +The event system provides: +- **Mapped types** for event payload definitions +- **Generic event handler functions** with proper type inference +- **Type-safe event emitter** with subscription management +- **Integration** with existing FlagEvent entity structure +- **Comprehensive error handling** and logging capabilities + +## Core Components + +### 1. Event Payload Definitions (`events.ts`) + +The system uses mapped types to define event payloads: + +```typescript +// Base event payload that all events extend +interface BaseEventPayload { + readonly timestamp: Date; + readonly source?: string; + readonly context?: Record; +} + +// Event payload mapping using mapped types +interface EventPayloadMap { + 'flag:evaluation': FlagEvaluationPayload; + 'flag:update': FlagUpdatePayload; + 'flag:create': FlagCreatePayload; + 'flag:delete': FlagDeletePayload; + 'flag:toggle': FlagTogglePayload; + 'session:start': UserSessionStartPayload; + 'session:end': UserSessionEndPayload; + 'system:error': SystemErrorPayload; + 'system:health': SystemHealthPayload; +} +``` + +### 2. Generic Event Handler Functions + +Event handlers are fully type-safe with proper inference: + +```typescript +// Generic event handler with type inference +type EventHandler = (payload: EventPayload) => void | Promise; + +// Example usage - TypeScript infers the payload type automatically +const flagHandler: EventHandler<'flag:evaluation'> = async (payload) => { + // payload is automatically typed as FlagEvaluationPayload + console.log(`Flag ${payload.flagId} evaluated with value: ${payload.value}`); +}; +``` + +### 3. Type-Safe Event Emitter (`event-emitter.ts`) + +The event emitter provides full type safety: + +```typescript +const emitter = new TypeSafeEventEmitterImpl(); + +// Type-safe registration +emitter.on('flag:evaluation', flagHandler); + +// Type-safe emission - payload must match event type +await emitter.emit('flag:evaluation', { + timestamp: new Date(), + flagId: 'feature-x', + value: true, + userId: 'user-123' +}); +``` + +## Key Features + +### 1. Mapped Types for Event Categories + +Events are categorized using mapped types: + +```typescript +type FlagEventNames = { + [K in EventName]: EventPayloadMap[K] extends FlagEvaluationPayload | FlagUpdatePayload | FlagCreatePayload | FlagDeletePayload | FlagTogglePayload + ? K + : never; +}[EventName]; +``` + +### 2. Advanced Handler Utilities + +The system provides utility functions for creating sophisticated handlers: + +```typescript +// Safe handler with retry logic +const safeHandler = createSafeHandler(baseHandler, { + retries: 3, + timeout: 5000, + onError: (error, payload) => console.error('Handler failed:', error) +}); + +// Conditional handler +const conditionalHandler = createConditionalHandler( + (payload) => payload.value === true, + async (payload) => console.log('Flag is enabled!') +); + +// Debounced handler +const debouncedHandler = createDebouncedHandler(baseHandler, 1000); + +// Throttled handler +const throttledHandler = createThrottledHandler(baseHandler, 2000); +``` + +### 3. Event Factory with Validation + +Type-safe event creation: + +```typescript +const factory = new EventFactoryImpl(); + +// Automatically adds timestamp and validates event structure +const event = factory.createFlagEvent('flag:evaluation', { + flagId: 'premium-feature', + value: { enabled: true, plan: 'pro' }, + userId: 'user-123' +}); +``` + +### 4. Subscription Management + +Comprehensive subscription handling: + +```typescript +// Create subscription with metadata +const subscription = emitter.subscribe('flag:evaluation', handler, { + priority: 10 +}); + +// One-time handlers +emitter.once('flag:update', handler); + +// Unsubscribe +subscription.unsubscribe(); + +// Get statistics +const stats = emitter.getStats(); +console.log(`Total handlers: ${stats.totalHandlers}`); +``` + +## Integration with Existing Code + +### 1. FlagEvent Entity Integration + +The event system integrates seamlessly with the existing `FlagEvent` entity: + +```typescript +// Handler that persists events to database +const persistHandler: EventHandler<'flag:evaluation'> = async (payload) => { + const flagEvent = { + id: generateId(), + featureFlagId: payload.flagId, + userId: payload.userId, + eventType: 'evaluation' as const, + newValue: payload.value, + context: payload.context, + createdAt: payload.timestamp + }; + + // Save to database using existing repository + await flagEventRepository.create(flagEvent); +}; +``` + +### 2. Type Compatibility + +All event types are compatible with existing utility types: + +```typescript +// Convert FlagEvent entity to event payload +type FlagEventToPayload = T extends 'flag:evaluation' + ? FlagEvaluationPayload + : T extends 'flag:update' + ? FlagUpdatePayload + : // ... other mappings + never; +``` + +## Usage Examples + +### Basic Usage + +```typescript +import { + TypeSafeEventEmitterImpl, + EventFactoryImpl, + EventHandler +} from './event-emitter.js'; + +const emitter = new TypeSafeEventEmitterImpl(); +const factory = new EventFactoryImpl(); + +// Register handler with automatic type inference +const handler: EventHandler<'flag:evaluation'> = async (payload) => { + console.log(`Flag ${payload.flagId} evaluated: ${payload.value}`); +}; + +emitter.on('flag:evaluation', handler); + +// Emit type-safe event +await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'dark-mode', + value: true, + userId: 'user-456' +})); +``` + +### Global Event Emitter + +```typescript +import { getGlobalEventEmitter, getEventFactory } from './event-emitter.js'; + +const globalEmitter = getGlobalEventEmitter(); +const factory = getEventFactory(); + +// Global error handler +globalEmitter.on('system:error', async (payload) => { + // Send to monitoring service + await monitoringService.reportError(payload.error, { + severity: payload.severity, + operation: payload.operation + }); +}); +``` + +### Event Categories + +```typescript +import { EVENT_CATEGORIES } from './events.js'; + +// Register handler for all flag events +EVENT_CATEGORIES.flag.forEach(eventName => { + emitter.on(eventName, flagEventHandler); +}); + +// Register handler for all system events +EVENT_CATEGORIES.system.forEach(eventName => { + emitter.on(eventName, systemEventHandler); +}); +``` + +## Type Safety Benefits + +### 1. Compile-Time Validation + +```typescript +// ✅ Valid - TypeScript knows payload must have flagId +emitter.on('flag:evaluation', async (payload) => { + console.log(payload.flagId); // Type: string +}); + +// ❌ Invalid - TypeScript error: flagId doesn't exist on SystemErrorPayload +emitter.on('system:error', async (payload) => { + console.log(payload.flagId); // TypeScript error! +}); +``` + +### 2. Auto-Completion + +IDEs provide full auto-completion for: +- Event names +- Payload properties +- Handler signatures +- Return types + +### 3. Refactoring Safety + +When event structures change: +- TypeScript will highlight all affected code +- Compiler errors prevent runtime issues +- IDE refactoring tools work correctly + +## Performance Considerations + +### 1. Handler Execution + +- Handlers execute in priority order (higher priority first) +- Async handlers run concurrently +- Error in one handler doesn't affect others +- One-time handlers are automatically removed + +### 2. Memory Management + +- Weak references prevent memory leaks +- Statistics tracking with configurable limits +- Automatic cleanup of expired subscriptions + +### 3. Error Handling + +- Safe handlers with retry logic +- Global error reporting +- Graceful degradation on handler failures + +## Best Practices + +### 1. Event Design + +```typescript +// ✅ Good - Specific, immutable event data +interface FlagEvaluationPayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly value: unknown; + readonly reason?: string; +} + +// ❌ Avoid - Mutable, generic event data +interface GenericEventPayload { + data: any; + type: string; +} +``` + +### 2. Handler Implementation + +```typescript +// ✅ Good - Specific, async handler with error handling +const flagHandler: EventHandler<'flag:evaluation'> = async (payload) => { + try { + await processFlag(payload.flagId, payload.value); + } catch (error) { + logger.error('Flag processing failed', { flagId: payload.flagId, error }); + throw error; // Re-throw to trigger error handling + } +}; + +// ❌ Avoid - Generic handler without error handling +const genericHandler = (payload: any) => { + processFlag(payload.flagId, payload.value); // No error handling +}; +``` + +### 3. Subscription Management + +```typescript +// ✅ Good - Clean up subscriptions +class ComponentWithEvents { + private subscriptions: EventSubscription[] = []; + + constructor(emitter: TypeSafeEventEmitter) { + this.subscriptions.push( + emitter.subscribe('flag:evaluation', this.handleFlagEvaluation) + ); + } + + destroy(): void { + this.subscriptions.forEach(sub => sub.unsubscribe()); + this.subscriptions = []; + } + + private handleFlagEvaluation = async (payload: FlagEvaluationPayload) => { + // Handle event + }; +} +``` + +## Exported APIs + +The event system exports all necessary types and implementations: + +```typescript +// From events.ts +export { + EventName, + EventPayload, + EventHandler, + EventPayloadMap, + FlagEventNames, + SessionEventNames, + SystemEventNames, + // ... all event payload interfaces +}; + +// From event-emitter.ts +export { + TypeSafeEventEmitterImpl, + EventFactoryImpl, + createSafeHandler, + createConditionalHandler, + createDebouncedHandler, + createThrottledHandler, + composeHandlers, + createLoggingHandler, + getGlobalEventEmitter, + getEventFactory +}; +``` + +## Testing + +The event system includes comprehensive examples in `event-examples.ts`: + +```typescript +import { runEventExamples } from './event-examples.js'; + +// Run all examples to see the event system in action +await runEventExamples(); +``` + +Individual examples can be run separately: + +```typescript +import { + basicEventEmitterExample, + multipleEventTypesExample, + advancedHandlerUtilitiesExample, + eventSubscriptionExample +} from './event-examples.js'; + +await basicEventEmitterExample(); +``` + +## Conclusion + +This type-safe event system provides: + +1. **Complete type safety** with compile-time validation +2. **Mapped types** for maintainable event definitions +3. **Generic handlers** with proper type inference +4. **Advanced utilities** for sophisticated event handling +5. **Seamless integration** with existing codebase +6. **Comprehensive error handling** and logging +7. **Performance optimizations** and memory management +8. **Extensive examples** and documentation + +The implementation follows TypeScript best practices and provides a robust foundation for event-driven architecture with full type safety. \ No newline at end of file diff --git a/launchdarkly/node/README.md b/launchdarkly/node/README.md new file mode 100644 index 00000000..2896ccab --- /dev/null +++ b/launchdarkly/node/README.md @@ -0,0 +1,396 @@ +# Type-Safe Database Entity Definitions with TypeORM + +This module provides comprehensive type-safe database entity definitions using TypeORM decorators with advanced utility types for create/update input types. It demonstrates best practices for building type-safe database layers in TypeScript applications. + +## Features + +- ✅ **TypeORM Entity Definitions**: Complete entity definitions with proper decorators +- ✅ **Advanced Utility Types**: Comprehensive utility types for CRUD operations +- ✅ **Type-Safe Repositories**: Repository pattern with full type safety +- ✅ **Database Connection Management**: Connection pooling and configuration +- ✅ **Transaction Support**: Unit of Work pattern with transaction management +- ✅ **Validation Schemas**: Zod schemas for runtime validation +- ✅ **Relation Loading**: Type-safe eager loading of entity relations +- ✅ **Pagination Support**: Built-in pagination with type safety +- ✅ **Error Handling**: Comprehensive error handling with custom error types +- ✅ **Complete Examples**: Working examples demonstrating all features + +## Quick Start + +```typescript +import { quickStart, createServiceLayer } from './index.js'; + +// Initialize database and services +const { connection, repositories, unitOfWork } = await quickStart({ + type: 'postgres', + host: 'localhost', + port: 5432, + username: 'postgres', + password: 'password', + database: 'myapp' +}); + +const services = createServiceLayer(unitOfWork); + +// Create an organization +const orgResult = await services.organizations.createOrganization({ + name: 'Acme Corporation', + description: 'Example organization', + isActive: true +}); + +if (orgResult.success) { + console.log('Created organization:', orgResult.data.name); +} +``` + +## Entity Definitions + +The module includes comprehensive entity definitions for a feature flag system: + +### Core Entities + +- **Organization**: Multi-tenant organization management +- **User**: User management with LaunchDarkly context compatibility +- **FeatureFlag**: Feature flag definitions with targeting rules +- **UserFlag**: User-specific flag overrides +- **UserSession**: Session tracking +- **FlagEvent**: Event logging for audit trails + +### Entity Features + +Each entity includes: +- Primary keys with branded types for type safety +- Proper column definitions with constraints +- Indexes for performance +- Relationships with foreign keys +- Timestamps (createdAt, updatedAt) +- Validation rules + +## Utility Types + +The module provides advanced TypeScript utility types for type-safe database operations: + +### Create/Update Input Types + +```typescript +// Automatically excludes database-managed fields (id, createdAt, updatedAt) +type CreateUserInput = CreateInput; + +// Makes all fields optional except ID for updates +type UpdateUserInput = UpdateInput; + +// Partial update with ID required +type PatchUserInput = PatchInput; +``` + +### Advanced Utility Types + +```typescript +// Deep partial for nested objects +type DeepPartial + +// Make only specific keys required +type RequireOnly + +// Extract relation fields +type RelationFields + +// Type-safe relation loading +type WithRelations> + +// Filter input for queries +type FilterInput +``` + +## Repository Pattern + +Type-safe repository implementations with comprehensive CRUD operations: + +```typescript +// Get repository +const userRepo = repositories.getUserRepository(); + +// Type-safe operations +const user = await userRepo.create({ + key: 'user123', + name: 'John Doe', + email: 'john@example.com', + kind: 'user', + isActive: true +}); + +// Query with relations +const userWithOrg = await userRepo.findById(user.id, ['organization']); + +// Filtered queries +const activeUsers = await userRepo.findAll({ isActive: true }); + +// Pagination +const paginatedUsers = await userRepo.findPaginated( + { isActive: true }, + { page: 1, limit: 10 } +); +``` + +## Transaction Support + +Unit of Work pattern for managing database transactions: + +```typescript +const result = await unitOfWork.executeTransaction(async (uow) => { + // All operations within this block are in the same transaction + const org = await uow.Organizations.create({ name: 'Test Org', isActive: true }); + const user = await uow.Users.create({ + key: 'test-user', + name: 'Test User', + organizationId: org.id, + kind: 'user', + isActive: true + }); + + return { org, user }; +}); +``` + +## Validation + +Runtime validation using Zod schemas: + +```typescript +import { validateEntity } from './entities.js'; + +try { + const validatedInput = validateEntity.user({ + key: 'user123', + name: 'John Doe', + email: 'invalid-email', // This will throw + kind: 'user' + }); +} catch (error) { + if (error instanceof ValidationError) { + console.log('Validation failed:', error.getFormattedErrors()); + } +} +``` + +## Service Layer + +High-level services with business logic: + +```typescript +const userService = new UserService(unitOfWork.Users, unitOfWork.Organizations); + +// Create user with validation +const result = await userService.createUser({ + key: 'user123', + name: 'John Doe', + email: 'john@example.com', + kind: 'user', + organizationId: 'org-123', + isActive: true +}); + +if (result.success) { + console.log('User created:', result.data.name); +} else { + console.error('Failed to create user:', result.error.message); +} +``` + +## Feature Flag Management + +Comprehensive feature flag management with user overrides: + +```typescript +const flagService = new FeatureFlagService( + unitOfWork.FeatureFlags, + unitOfWork.UserFlags, + unitOfWork.Organizations +); + +// Create feature flag +await flagService.createFeatureFlag({ + key: 'dark-mode', + name: 'Dark Mode', + description: 'Enable dark mode theme', + valueType: 'boolean', + defaultValue: false, + isEnabled: true, + category: 'ui', + environment: 'production' +}); + +// Get flag value for user (checks user overrides first) +const flagValue = await flagService.getFlagValueForUser('user-123', 'dark-mode'); + +// Set user-specific override +await flagService.setUserFlagOverride( + 'user-123', + 'dark-mode', + true, + 'User prefers dark mode' +); +``` + +## Data Transformation + +Type-safe transformations between entities and DTOs: + +```typescript +import { userTransform, organizationTransform } from './examples.js'; + +// Transform entity to DTO +const userDto = userTransform(user); + +// Bi-directional transform +const orgDto = organizationTransform.toDto(organization); +const orgEntity = organizationTransform.fromDto(orgDto); +``` + +## Configuration + +Database configuration with environment variable support: + +```typescript +import { createDatabaseConfig } from './database.js'; + +const config = createDatabaseConfig({ + DB_TYPE: 'postgres', + DB_HOST: 'localhost', + DB_PORT: '5432', + DB_USERNAME: 'postgres', + DB_PASSWORD: 'password', + DB_DATABASE: 'myapp', + NODE_ENV: 'production' +}); +``` + +## Error Handling + +Comprehensive error handling with custom error types: + +```typescript +try { + const user = await userRepo.create(invalidInput); +} catch (error) { + if (error instanceof DatabaseError) { + console.log('Database error:', error.code, error.message); + } else if (error instanceof ValidationError) { + console.log('Validation error:', error.getFormattedErrors()); + } +} +``` + +## Advanced Queries + +Type-safe advanced querying with filters and aggregations: + +```typescript +// Advanced filtering +const users = await userRepo.find({ + where: { + isActive: true, + email: { like: '%@acme.com' } + }, + relations: ['organization', 'userFlags'], + order: { createdAt: 'DESC' }, + take: 10 +}); + +// Aggregation +const stats = await flagRepo.getFlagUsageStats('flag-123'); +``` + +## Migration Support + +Type-safe migration definitions: + +```typescript +interface MigrationOperation { + type: 'CREATE_TABLE' | 'ALTER_TABLE' | 'DROP_TABLE'; + // ... additional properties +} +``` + +## Examples + +Run the complete example application: + +```typescript +import { runExamples } from './examples.js'; + +// Runs complete examples including: +// - Database setup +// - Entity creation +// - Relationship management +// - Transaction usage +// - Query demonstrations +await runExamples(); +``` + +## File Structure + +``` +launchdarkly/node/ +├── entities.ts # Entity definitions with TypeORM decorators +├── database.ts # Database connection and configuration +├── repositories.ts # Repository interfaces and implementations +├── types.ts # Advanced utility types +├── examples.ts # Complete working examples +├── index.ts # Main exports +└── README.md # This documentation +``` + +## TypeScript Configuration + +Ensure your TypeScript configuration supports: + +```json +{ + "compilerOptions": { + "target": "ES2020", + "module": "ES2020", + "moduleResolution": "Node", + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "strict": true, + "skipLibCheck": true + } +} +``` + +## Dependencies + +```json +{ + "dependencies": { + "zod": "^3.25.64" + }, + "devDependencies": { + "typescript": "^5.8.3" + } +} +``` + +Note: This implementation uses mock TypeORM decorators for demonstration. In a real application, you would install and import from the actual `typeorm` package. + +## Best Practices + +1. **Type Safety**: Always use branded types for IDs to prevent mixing different entity IDs +2. **Validation**: Validate all inputs at service boundaries using Zod schemas +3. **Error Handling**: Use Result types to handle operations that can fail +4. **Transactions**: Use Unit of Work pattern for operations that span multiple entities +5. **Relations**: Explicitly specify which relations to load to avoid N+1 queries +6. **Pagination**: Always paginate large result sets +7. **Indexing**: Add appropriate indexes on frequently queried columns + +## License + +Licensed under the Apache License, Version 2.0. See the LICENSE file for details. + +## Contributing + +This is a demonstration module. For production use, adapt the patterns to your specific needs and install the actual TypeORM package. \ No newline at end of file diff --git a/launchdarkly/node/database.ts b/launchdarkly/node/database.ts new file mode 100644 index 00000000..8d82f333 --- /dev/null +++ b/launchdarkly/node/database.ts @@ -0,0 +1,671 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * TypeORM database configuration and connection setup + * with type-safe query builders and connection management + */ + +import { z } from "zod"; +import { + Organization, + User, + FeatureFlag, + UserFlag, + UserSession, + FlagEvent, + CreateOrganizationInput, + CreateUserInput, + CreateFeatureFlagInput, + CreateUserFlagInput, + OrganizationFilters, + UserFilters, + FeatureFlagFilters, + UserFlagFilters, + EntityRelations +} from "./entities.js"; + +// ===== MOCK TYPEORM INTERFACES ===== + +/** + * Mock TypeORM interfaces for demonstration purposes + * In actual implementation, these would be imported from 'typeorm' + */ + +interface DataSourceOptions { + type: 'postgres' | 'mysql' | 'sqlite' | 'mongodb'; + host?: string; + port?: number; + username?: string; + password?: string; + database?: string; + entities: Function[]; + synchronize?: boolean; + logging?: boolean; + ssl?: boolean | object; + migrations?: string[]; + migrationsRun?: boolean; +} + +interface QueryRunner { + connect(): Promise; + release(): Promise; + startTransaction(): Promise; + commitTransaction(): Promise; + rollbackTransaction(): Promise; +} + +interface Repository { + find(options?: FindManyOptions): Promise; + findOne(options?: FindOneOptions): Promise; + findOneBy(where: Partial): Promise; + save(entity: Partial): Promise; + update(criteria: any, partialEntity: Partial): Promise; + delete(criteria: any): Promise; + create(entityData: Partial): Entity; + count(options?: FindManyOptions): Promise; +} + +interface FindManyOptions { + where?: Partial | Partial[]; + relations?: string[] | Record>; + order?: Record; + skip?: number; + take?: number; + select?: (keyof Entity)[]; +} + +interface FindOneOptions { + where?: Partial; + relations?: string[] | Record>; + select?: (keyof Entity)[]; +} + +class MockDataSource { + constructor(private options: DataSourceOptions) {} + + async initialize(): Promise { + console.log('Mock DataSource initialized'); + return this; + } + + async destroy(): Promise { + console.log('Mock DataSource destroyed'); + } + + getRepository(entityClass: Function): Repository { + return new MockRepository(); + } + + createQueryRunner(): QueryRunner { + return new MockQueryRunner(); + } + + get isInitialized(): boolean { + return true; + } +} + +class MockRepository implements Repository { + async find(options?: FindManyOptions): Promise { + console.log('Mock find:', options); + return []; + } + + async findOne(options?: FindOneOptions): Promise { + console.log('Mock findOne:', options); + return null; + } + + async findOneBy(where: Partial): Promise { + console.log('Mock findOneBy:', where); + return null; + } + + async save(entity: Partial): Promise { + console.log('Mock save:', entity); + return entity as Entity; + } + + async update(criteria: any, partialEntity: Partial): Promise { + console.log('Mock update:', criteria, partialEntity); + return { affected: 1 }; + } + + async delete(criteria: any): Promise { + console.log('Mock delete:', criteria); + return { affected: 1 }; + } + + create(entityData: Partial): Entity { + console.log('Mock create:', entityData); + return entityData as Entity; + } + + async count(options?: FindManyOptions): Promise { + console.log('Mock count:', options); + return 0; + } +} + +class MockQueryRunner implements QueryRunner { + async connect(): Promise { + console.log('Mock QueryRunner connected'); + } + + async release(): Promise { + console.log('Mock QueryRunner released'); + } + + async startTransaction(): Promise { + console.log('Mock transaction started'); + } + + async commitTransaction(): Promise { + console.log('Mock transaction committed'); + } + + async rollbackTransaction(): Promise { + console.log('Mock transaction rolled back'); + } +} + +// ===== DATABASE CONFIGURATION ===== + +/** + * Database configuration schema with validation + */ +const DatabaseConfigSchema = z.object({ + type: z.enum(['postgres', 'mysql', 'sqlite', 'mongodb']).default('postgres'), + host: z.string().default('localhost'), + port: z.number().min(1).max(65535).default(5432), + username: z.string().min(1, "Database username is required"), + password: z.string().min(1, "Database password is required"), + database: z.string().min(1, "Database name is required"), + synchronize: z.boolean().default(false), + logging: z.boolean().default(false), + ssl: z.union([z.boolean(), z.record(z.unknown())]).default(false), + maxConnections: z.number().min(1).max(100).default(10), + acquireTimeout: z.number().min(1000).default(60000), + timeout: z.number().min(1000).default(60000), + migrationsRun: z.boolean().default(true) +}); + +type DatabaseConfig = z.infer; + +/** + * Environment-based database configuration + */ +export function createDatabaseConfig(env: Record = process.env): DatabaseConfig { + const config = { + type: env.DB_TYPE || 'postgres', + host: env.DB_HOST || 'localhost', + port: env.DB_PORT ? parseInt(env.DB_PORT, 10) : 5432, + username: env.DB_USERNAME || env.DB_USER || 'postgres', + password: env.DB_PASSWORD || '', + database: env.DB_DATABASE || env.DB_NAME || 'launchdarkly', + synchronize: env.NODE_ENV !== 'production' && env.DB_SYNCHRONIZE !== 'false', + logging: env.DB_LOGGING === 'true' || env.NODE_ENV === 'development', + ssl: env.DB_SSL === 'true' || (env.NODE_ENV === 'production' && env.DB_SSL !== 'false'), + maxConnections: env.DB_MAX_CONNECTIONS ? parseInt(env.DB_MAX_CONNECTIONS, 10) : 10, + acquireTimeout: env.DB_ACQUIRE_TIMEOUT ? parseInt(env.DB_ACQUIRE_TIMEOUT, 10) : 60000, + timeout: env.DB_TIMEOUT ? parseInt(env.DB_TIMEOUT, 10) : 60000, + migrationsRun: env.DB_MIGRATIONS_RUN !== 'false' + }; + + return DatabaseConfigSchema.parse(config); +} + +/** + * Database connection class with connection pooling and error handling + */ +export class DatabaseConnection { + private dataSource: MockDataSource | null = null; + private config: DatabaseConfig; + + constructor(config?: Partial) { + this.config = DatabaseConfigSchema.parse({ + ...createDatabaseConfig(), + ...config + }); + } + + /** + * Initialize database connection + */ + async connect(): Promise { + if (this.dataSource?.isInitialized) { + return; + } + + const dataSourceOptions: DataSourceOptions = { + type: this.config.type, + host: this.config.host, + port: this.config.port, + username: this.config.username, + password: this.config.password, + database: this.config.database, + entities: [Organization, User, FeatureFlag, UserFlag, UserSession, FlagEvent], + synchronize: this.config.synchronize, + logging: this.config.logging, + ssl: this.config.ssl, + migrationsRun: this.config.migrationsRun, + migrations: ['src/migrations/*.ts'] + }; + + try { + this.dataSource = new MockDataSource(dataSourceOptions); + await this.dataSource.initialize(); + console.log('Database connected successfully'); + } catch (error) { + console.error('Database connection failed:', error); + throw new Error(`Failed to connect to database: ${error instanceof Error ? error.message : String(error)}`); + } + } + + /** + * Close database connection + */ + async disconnect(): Promise { + if (this.dataSource?.isInitialized) { + await this.dataSource.destroy(); + this.dataSource = null; + console.log('Database disconnected successfully'); + } + } + + /** + * Get database data source + */ + getDataSource(): MockDataSource { + if (!this.dataSource?.isInitialized) { + throw new Error('Database not connected. Call connect() first.'); + } + return this.dataSource; + } + + /** + * Get repository for an entity + */ + getRepository(entityClass: Function): Repository { + return this.getDataSource().getRepository(entityClass); + } + + /** + * Execute database operations within a transaction + */ + async transaction(callback: (queryRunner: QueryRunner) => Promise): Promise { + const queryRunner = this.getDataSource().createQueryRunner(); + + try { + await queryRunner.connect(); + await queryRunner.startTransaction(); + + const result = await callback(queryRunner); + + await queryRunner.commitTransaction(); + return result; + } catch (error) { + await queryRunner.rollbackTransaction(); + throw error; + } finally { + await queryRunner.release(); + } + } + + /** + * Health check for database connection + */ + async healthCheck(): Promise<{ healthy: boolean; latency?: number; error?: string }> { + if (!this.dataSource?.isInitialized) { + return { healthy: false, error: 'Database not connected' }; + } + + try { + const startTime = Date.now(); + + // Simple query to check connection + const organizationRepo = this.getRepository(Organization); + await organizationRepo.count(); + + const latency = Date.now() - startTime; + return { healthy: true, latency }; + } catch (error) { + return { + healthy: false, + error: error instanceof Error ? error.message : String(error) + }; + } + } +} + +// ===== TYPE-SAFE QUERY BUILDERS ===== + +/** + * Type-safe query builder for entities + */ +export class TypeSafeQueryBuilder { + constructor( + private repository: Repository, + private entityName: string + ) {} + + /** + * Find entities with type-safe filters and relations + */ + async find(options: { + where?: Partial; + relations?: string[]; + order?: Record; + skip?: number; + take?: number; + select?: (keyof T)[]; + } = {}): Promise { + const findOptions: FindManyOptions = { + where: options.where, + relations: options.relations, + order: options.order, + skip: options.skip, + take: options.take, + select: options.select + }; + + return this.repository.find(findOptions); + } + + /** + * Find one entity with type-safe options + */ + async findOne(options: { + where?: Partial; + relations?: string[]; + select?: (keyof T)[]; + }): Promise { + const findOptions: FindOneOptions = { + where: options.where, + relations: options.relations, + select: options.select + }; + + return this.repository.findOne(findOptions); + } + + /** + * Find entity by ID with relations + */ + async findById(id: any, relations?: string[]): Promise { + return this.repository.findOne({ + where: { id } as any, + relations + }); + } + + /** + * Create new entity + */ + async create(data: Partial): Promise { + const entity = this.repository.create(data); + return this.repository.save(entity); + } + + /** + * Update entity by ID + */ + async update(id: any, data: Partial): Promise { + const result = await this.repository.update(id, data); + return result.affected > 0; + } + + /** + * Delete entity by ID + */ + async delete(id: any): Promise { + const result = await this.repository.delete(id); + return result.affected > 0; + } + + /** + * Count entities with filters + */ + async count(where?: Partial): Promise { + return this.repository.count({ where }); + } + + /** + * Check if entity exists + */ + async exists(where: Partial): Promise { + const count = await this.repository.count({ where }); + return count > 0; + } +} + +// ===== REPOSITORY FACTORY ===== + +/** + * Factory for creating type-safe repositories + */ +export class RepositoryFactory { + constructor(private connection: DatabaseConnection) {} + + /** + * Get Organization repository + */ + getOrganizationRepository(): TypeSafeQueryBuilder { + const repo = this.connection.getRepository(Organization); + return new TypeSafeQueryBuilder(repo, 'Organization'); + } + + /** + * Get User repository + */ + getUserRepository(): TypeSafeQueryBuilder { + const repo = this.connection.getRepository(User); + return new TypeSafeQueryBuilder(repo, 'User'); + } + + /** + * Get FeatureFlag repository + */ + getFeatureFlagRepository(): TypeSafeQueryBuilder { + const repo = this.connection.getRepository(FeatureFlag); + return new TypeSafeQueryBuilder(repo, 'FeatureFlag'); + } + + /** + * Get UserFlag repository + */ + getUserFlagRepository(): TypeSafeQueryBuilder { + const repo = this.connection.getRepository(UserFlag); + return new TypeSafeQueryBuilder(repo, 'UserFlag'); + } + + /** + * Get UserSession repository + */ + getUserSessionRepository(): TypeSafeQueryBuilder { + const repo = this.connection.getRepository(UserSession); + return new TypeSafeQueryBuilder(repo, 'UserSession'); + } + + /** + * Get FlagEvent repository + */ + getFlagEventRepository(): TypeSafeQueryBuilder { + const repo = this.connection.getRepository(FlagEvent); + return new TypeSafeQueryBuilder(repo, 'FlagEvent'); + } +} + +// ===== PAGINATION UTILITIES ===== + +/** + * Pagination options with validation + */ +const PaginationSchema = z.object({ + page: z.number().min(1).default(1), + limit: z.number().min(1).max(1000).default(20), + sortBy: z.string().optional(), + sortOrder: z.enum(['ASC', 'DESC']).default('ASC') +}); + +export type PaginationOptions = z.infer; + +export interface PaginatedResult { + data: T[]; + pagination: { + page: number; + limit: number; + total: number; + totalPages: number; + hasNext: boolean; + hasPrev: boolean; + }; +} + +/** + * Create paginated query + */ +export function createPaginatedQuery( + queryBuilder: TypeSafeQueryBuilder, + options: Partial = {} +) { + const paginationOptions = PaginationSchema.parse(options); + + return { + async execute(where?: Partial, relations?: string[]): Promise> { + const skip = (paginationOptions.page - 1) * paginationOptions.limit; + const take = paginationOptions.limit; + + const order = paginationOptions.sortBy ? { + [paginationOptions.sortBy]: paginationOptions.sortOrder + } as Record : undefined; + + const [data, total] = await Promise.all([ + queryBuilder.find({ + where, + relations, + order, + skip, + take + }), + queryBuilder.count(where) + ]); + + const totalPages = Math.ceil(total / paginationOptions.limit); + + return { + data, + pagination: { + page: paginationOptions.page, + limit: paginationOptions.limit, + total, + totalPages, + hasNext: paginationOptions.page < totalPages, + hasPrev: paginationOptions.page > 1 + } + }; + } + }; +} + +// ===== GLOBAL DATABASE INSTANCE ===== + +let globalDatabaseConnection: DatabaseConnection | null = null; + +/** + * Get or create global database connection + */ +export function getDatabase(config?: Partial): DatabaseConnection { + if (!globalDatabaseConnection) { + globalDatabaseConnection = new DatabaseConnection(config); + } + return globalDatabaseConnection; +} + +/** + * Initialize global database connection + */ +export async function initializeDatabase(config?: Partial): Promise { + const db = getDatabase(config); + await db.connect(); + return db; +} + +/** + * Close global database connection + */ +export async function closeDatabase(): Promise { + if (globalDatabaseConnection) { + await globalDatabaseConnection.disconnect(); + globalDatabaseConnection = null; + } +} + +// ===== ERROR HANDLING ===== + +/** + * Database-specific error types + */ +export class DatabaseError extends Error { + constructor( + message: string, + public readonly code?: string, + public readonly details?: unknown + ) { + super(message); + this.name = 'DatabaseError'; + } +} + +export class ValidationError extends Error { + constructor( + message: string, + public readonly field?: string, + public readonly value?: unknown + ) { + super(message); + this.name = 'ValidationError'; + } +} + +/** + * Handle database errors with proper typing + */ +export function handleDatabaseError(error: unknown): never { + if (error instanceof DatabaseError) { + throw error; + } + + if (error instanceof Error) { + // Map common database errors + if (error.message.includes('duplicate key')) { + throw new DatabaseError('Duplicate entry found', 'DUPLICATE_ENTRY', error); + } + + if (error.message.includes('foreign key')) { + throw new DatabaseError('Foreign key constraint violation', 'FOREIGN_KEY_VIOLATION', error); + } + + if (error.message.includes('not null')) { + throw new DatabaseError('Required field is missing', 'NOT_NULL_VIOLATION', error); + } + + throw new DatabaseError(error.message, 'UNKNOWN_ERROR', error); + } + + throw new DatabaseError('Unknown database error occurred', 'UNKNOWN_ERROR', error); +} \ No newline at end of file diff --git a/launchdarkly/node/dist/.tsbuildinfo b/launchdarkly/node/dist/.tsbuildinfo new file mode 100644 index 00000000..0ef98409 --- /dev/null +++ b/launchdarkly/node/dist/.tsbuildinfo @@ -0,0 +1 @@ +{"fileNames":["../../../node_modules/typescript/lib/lib.es5.d.ts","../../../node_modules/typescript/lib/lib.es2015.d.ts","../../../node_modules/typescript/lib/lib.es2016.d.ts","../../../node_modules/typescript/lib/lib.es2017.d.ts","../../../node_modules/typescript/lib/lib.es2018.d.ts","../../../node_modules/typescript/lib/lib.es2019.d.ts","../../../node_modules/typescript/lib/lib.es2020.d.ts","../../../node_modules/typescript/lib/lib.dom.d.ts","../../../node_modules/typescript/lib/lib.dom.iterable.d.ts","../../../node_modules/typescript/lib/lib.es2015.core.d.ts","../../../node_modules/typescript/lib/lib.es2015.collection.d.ts","../../../node_modules/typescript/lib/lib.es2015.generator.d.ts","../../../node_modules/typescript/lib/lib.es2015.iterable.d.ts","../../../node_modules/typescript/lib/lib.es2015.promise.d.ts","../../../node_modules/typescript/lib/lib.es2015.proxy.d.ts","../../../node_modules/typescript/lib/lib.es2015.reflect.d.ts","../../../node_modules/typescript/lib/lib.es2015.symbol.d.ts","../../../node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts","../../../node_modules/typescript/lib/lib.es2016.array.include.d.ts","../../../node_modules/typescript/lib/lib.es2016.intl.d.ts","../../../node_modules/typescript/lib/lib.es2017.arraybuffer.d.ts","../../../node_modules/typescript/lib/lib.es2017.date.d.ts","../../../node_modules/typescript/lib/lib.es2017.object.d.ts","../../../node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts","../../../node_modules/typescript/lib/lib.es2017.string.d.ts","../../../node_modules/typescript/lib/lib.es2017.intl.d.ts","../../../node_modules/typescript/lib/lib.es2017.typedarrays.d.ts","../../../node_modules/typescript/lib/lib.es2018.asyncgenerator.d.ts","../../../node_modules/typescript/lib/lib.es2018.asynciterable.d.ts","../../../node_modules/typescript/lib/lib.es2018.intl.d.ts","../../../node_modules/typescript/lib/lib.es2018.promise.d.ts","../../../node_modules/typescript/lib/lib.es2018.regexp.d.ts","../../../node_modules/typescript/lib/lib.es2019.array.d.ts","../../../node_modules/typescript/lib/lib.es2019.object.d.ts","../../../node_modules/typescript/lib/lib.es2019.string.d.ts","../../../node_modules/typescript/lib/lib.es2019.symbol.d.ts","../../../node_modules/typescript/lib/lib.es2019.intl.d.ts","../../../node_modules/typescript/lib/lib.es2020.bigint.d.ts","../../../node_modules/typescript/lib/lib.es2020.date.d.ts","../../../node_modules/typescript/lib/lib.es2020.promise.d.ts","../../../node_modules/typescript/lib/lib.es2020.sharedmemory.d.ts","../../../node_modules/typescript/lib/lib.es2020.string.d.ts","../../../node_modules/typescript/lib/lib.es2020.symbol.wellknown.d.ts","../../../node_modules/typescript/lib/lib.es2020.intl.d.ts","../../../node_modules/typescript/lib/lib.es2020.number.d.ts","../../../node_modules/typescript/lib/lib.decorators.d.ts","../../../node_modules/typescript/lib/lib.decorators.legacy.d.ts","../../../node_modules/@types/react/global.d.ts","../../../node_modules/csstype/index.d.ts","../../../node_modules/@types/react/index.d.ts","../../../node_modules/@types/react/jsx-runtime.d.ts","../../../node_modules/zod/dist/types/v3/helpers/typeAliases.d.ts","../../../node_modules/zod/dist/types/v3/helpers/util.d.ts","../../../node_modules/zod/dist/types/v3/ZodError.d.ts","../../../node_modules/zod/dist/types/v3/locales/en.d.ts","../../../node_modules/zod/dist/types/v3/errors.d.ts","../../../node_modules/zod/dist/types/v3/helpers/parseUtil.d.ts","../../../node_modules/zod/dist/types/v3/helpers/enumUtil.d.ts","../../../node_modules/zod/dist/types/v3/helpers/errorUtil.d.ts","../../../node_modules/zod/dist/types/v3/helpers/partialUtil.d.ts","../../../node_modules/zod/dist/types/v3/standard-schema.d.ts","../../../node_modules/zod/dist/types/v3/types.d.ts","../../../node_modules/zod/dist/types/v3/external.d.ts","../../../node_modules/zod/dist/types/v3/index.d.ts","../../../node_modules/zod/dist/types/index.d.ts","../entities.ts","../database.ts","../types.ts","../events.ts","../event-emitter.ts","../event-examples.ts","../repositories.ts","../examples.ts","../index.ts","../sample.ts","../../../node_modules/@types/estree/index.d.ts","../../../node_modules/@types/json-schema/index.d.ts","../../../node_modules/@types/react-dom/index.d.ts"],"fileIdsList":[[51,65,66],[51,65],[51,69],[51,68,69,70],[51,68],[51,65,66,67,68,72],[51,66,67,68,69,70,71,72,73],[51,65,66,67],[50],[48,49],[64],[52,53,64],[54,55],[52,53,54,56,57,62],[53,54],[62],[63],[54],[52,53,54,57,58,59,60,61]],"fileInfos":[{"version":"69684132aeb9b5642cbcd9e22dff7818ff0ee1aa831728af0ecf97d3364d5546","affectsGlobalScope":true,"impliedFormat":1},{"version":"45b7ab580deca34ae9729e97c13cfd999df04416a79116c3bfb483804f85ded4","impliedFormat":1},{"version":"3facaf05f0c5fc569c5649dd359892c98a85557e3e0c847964caeb67076f4d75","impliedFormat":1},{"version":"e44bb8bbac7f10ecc786703fe0a6a4b952189f908707980ba8f3c8975a760962","impliedFormat":1},{"version":"5e1c4c362065a6b95ff952c0eab010f04dcd2c3494e813b493ecfd4fcb9fc0d8","impliedFormat":1},{"version":"68d73b4a11549f9c0b7d352d10e91e5dca8faa3322bfb77b661839c42b1ddec7","impliedFormat":1},{"version":"5efce4fc3c29ea84e8928f97adec086e3dc876365e0982cc8479a07954a3efd4","impliedFormat":1},{"version":"092c2bfe125ce69dbb1223c85d68d4d2397d7d8411867b5cc03cec902c233763","affectsGlobalScope":true,"impliedFormat":1},{"version":"07f073f19d67f74d732b1adea08e1dc66b1b58d77cb5b43931dee3d798a2fd53","affectsGlobalScope":true,"impliedFormat":1},{"version":"c57796738e7f83dbc4b8e65132f11a377649c00dd3eee333f672b8f0a6bea671","affectsGlobalScope":true,"impliedFormat":1},{"version":"dc2df20b1bcdc8c2d34af4926e2c3ab15ffe1160a63e58b7e09833f616efff44","affectsGlobalScope":true,"impliedFormat":1},{"version":"515d0b7b9bea2e31ea4ec968e9edd2c39d3eebf4a2d5cbd04e88639819ae3b71","affectsGlobalScope":true,"impliedFormat":1},{"version":"0559b1f683ac7505ae451f9a96ce4c3c92bdc71411651ca6ddb0e88baaaad6a3","affectsGlobalScope":true,"impliedFormat":1},{"version":"0dc1e7ceda9b8b9b455c3a2d67b0412feab00bd2f66656cd8850e8831b08b537","affectsGlobalScope":true,"impliedFormat":1},{"version":"ce691fb9e5c64efb9547083e4a34091bcbe5bdb41027e310ebba8f7d96a98671","affectsGlobalScope":true,"impliedFormat":1},{"version":"8d697a2a929a5fcb38b7a65594020fcef05ec1630804a33748829c5ff53640d0","affectsGlobalScope":true,"impliedFormat":1},{"version":"4ff2a353abf8a80ee399af572debb8faab2d33ad38c4b4474cff7f26e7653b8d","affectsGlobalScope":true,"impliedFormat":1},{"version":"936e80ad36a2ee83fc3caf008e7c4c5afe45b3cf3d5c24408f039c1d47bdc1df","affectsGlobalScope":true,"impliedFormat":1},{"version":"d15bea3d62cbbdb9797079416b8ac375ae99162a7fba5de2c6c505446486ac0a","affectsGlobalScope":true,"impliedFormat":1},{"version":"68d18b664c9d32a7336a70235958b8997ebc1c3b8505f4f1ae2b7e7753b87618","affectsGlobalScope":true,"impliedFormat":1},{"version":"eb3d66c8327153d8fa7dd03f9c58d351107fe824c79e9b56b462935176cdf12a","affectsGlobalScope":true,"impliedFormat":1},{"version":"38f0219c9e23c915ef9790ab1d680440d95419ad264816fa15009a8851e79119","affectsGlobalScope":true,"impliedFormat":1},{"version":"69ab18c3b76cd9b1be3d188eaf8bba06112ebbe2f47f6c322b5105a6fbc45a2e","affectsGlobalScope":true,"impliedFormat":1},{"version":"fef8cfad2e2dc5f5b3d97a6f4f2e92848eb1b88e897bb7318cef0e2820bceaab","affectsGlobalScope":true,"impliedFormat":1},{"version":"2f11ff796926e0832f9ae148008138ad583bd181899ab7dd768a2666700b1893","affectsGlobalScope":true,"impliedFormat":1},{"version":"4de680d5bb41c17f7f68e0419412ca23c98d5749dcaaea1896172f06435891fc","affectsGlobalScope":true,"impliedFormat":1},{"version":"954296b30da6d508a104a3a0b5d96b76495c709785c1d11610908e63481ee667","affectsGlobalScope":true,"impliedFormat":1},{"version":"ac9538681b19688c8eae65811b329d3744af679e0bdfa5d842d0e32524c73e1c","affectsGlobalScope":true,"impliedFormat":1},{"version":"0a969edff4bd52585473d24995c5ef223f6652d6ef46193309b3921d65dd4376","affectsGlobalScope":true,"impliedFormat":1},{"version":"9e9fbd7030c440b33d021da145d3232984c8bb7916f277e8ffd3dc2e3eae2bdb","affectsGlobalScope":true,"impliedFormat":1},{"version":"811ec78f7fefcabbda4bfa93b3eb67d9ae166ef95f9bff989d964061cbf81a0c","affectsGlobalScope":true,"impliedFormat":1},{"version":"717937616a17072082152a2ef351cb51f98802fb4b2fdabd32399843875974ca","affectsGlobalScope":true,"impliedFormat":1},{"version":"d7e7d9b7b50e5f22c915b525acc5a49a7a6584cf8f62d0569e557c5cfc4b2ac2","affectsGlobalScope":true,"impliedFormat":1},{"version":"71c37f4c9543f31dfced6c7840e068c5a5aacb7b89111a4364b1d5276b852557","affectsGlobalScope":true,"impliedFormat":1},{"version":"576711e016cf4f1804676043e6a0a5414252560eb57de9faceee34d79798c850","affectsGlobalScope":true,"impliedFormat":1},{"version":"89c1b1281ba7b8a96efc676b11b264de7a8374c5ea1e6617f11880a13fc56dc6","affectsGlobalScope":true,"impliedFormat":1},{"version":"74f7fa2d027d5b33eb0471c8e82a6c87216223181ec31247c357a3e8e2fddc5b","affectsGlobalScope":true,"impliedFormat":1},{"version":"d6d7ae4d1f1f3772e2a3cde568ed08991a8ae34a080ff1151af28b7f798e22ca","affectsGlobalScope":true,"impliedFormat":1},{"version":"063600664504610fe3e99b717a1223f8b1900087fab0b4cad1496a114744f8df","affectsGlobalScope":true,"impliedFormat":1},{"version":"934019d7e3c81950f9a8426d093458b65d5aff2c7c1511233c0fd5b941e608ab","affectsGlobalScope":true,"impliedFormat":1},{"version":"52ada8e0b6e0482b728070b7639ee42e83a9b1c22d205992756fe020fd9f4a47","affectsGlobalScope":true,"impliedFormat":1},{"version":"3bdefe1bfd4d6dee0e26f928f93ccc128f1b64d5d501ff4a8cf3c6371200e5e6","affectsGlobalScope":true,"impliedFormat":1},{"version":"59fb2c069260b4ba00b5643b907ef5d5341b167e7d1dbf58dfd895658bda2867","affectsGlobalScope":true,"impliedFormat":1},{"version":"639e512c0dfc3fad96a84caad71b8834d66329a1f28dc95e3946c9b58176c73a","affectsGlobalScope":true,"impliedFormat":1},{"version":"368af93f74c9c932edd84c58883e736c9e3d53cec1fe24c0b0ff451f529ceab1","affectsGlobalScope":true,"impliedFormat":1},{"version":"8e7f8264d0fb4c5339605a15daadb037bf238c10b654bb3eee14208f860a32ea","affectsGlobalScope":true,"impliedFormat":1},{"version":"782dec38049b92d4e85c1585fbea5474a219c6984a35b004963b00beb1aab538","affectsGlobalScope":true,"impliedFormat":1},{"version":"170d4db14678c68178ee8a3d5a990d5afb759ecb6ec44dbd885c50f6da6204f6","affectsGlobalScope":true,"impliedFormat":1},{"version":"8a8eb4ebffd85e589a1cc7c178e291626c359543403d58c9cd22b81fab5b1fb9","impliedFormat":1},{"version":"d4d7d3f832882a4b2d611a7eaaa80c780c3342b5732090130fa9af4a40bd051e","impliedFormat":1},{"version":"42c169fb8c2d42f4f668c624a9a11e719d5d07dacbebb63cbcf7ef365b0a75b3","impliedFormat":1},{"version":"d3cfde44f8089768ebb08098c96d01ca260b88bccf238d55eee93f1c620ff5a5","impliedFormat":1},{"version":"293eadad9dead44c6fd1db6de552663c33f215c55a1bfa2802a1bceed88ff0ec","impliedFormat":1},{"version":"54f6ec6ea75acea6eb23635617252d249145edbc7bcd9d53f2d70280d2aef953","impliedFormat":1},{"version":"c25ce98cca43a3bfa885862044be0d59557be4ecd06989b2001a83dcf69620fd","impliedFormat":1},{"version":"8e71e53b02c152a38af6aec45e288cc65bede077b92b9b43b3cb54a37978bb33","impliedFormat":1},{"version":"754a9396b14ca3a4241591afb4edc644b293ccc8a3397f49be4dfd520c08acb3","impliedFormat":1},{"version":"f672c876c1a04a223cf2023b3d91e8a52bb1544c576b81bf64a8fec82be9969c","impliedFormat":1},{"version":"e4b03ddcf8563b1c0aee782a185286ed85a255ce8a30df8453aade2188bbc904","impliedFormat":1},{"version":"de2316e90fc6d379d83002f04ad9698bc1e5285b4d52779778f454dd12ce9f44","impliedFormat":1},{"version":"25b3f581e12ede11e5739f57a86e8668fbc0124f6649506def306cad2c59d262","impliedFormat":1},{"version":"2da997a01a6aa5c5c09de5d28f0f4407b597c5e1aecfd32f1815809c532650a2","impliedFormat":1},{"version":"5d26d2e47e2352def36f89a3e8bf8581da22b7f857e07ef3114cd52cf4813445","impliedFormat":1},{"version":"3db2efd285e7328d8014b54a7fce3f4861ebcdc655df40517092ed0050983617","impliedFormat":1},{"version":"d5d39a24c759df40480a4bfc0daffd364489702fdbcbdfc1711cde34f8739995","impliedFormat":1},{"version":"758c9e645df582803d8139912b3824dbe1821aad6abf25cc5bc2d3c96ff76191","signature":"e84b0457b2c9ca4fcca3d3e2e136fed5802593d1410e0a19f9a3df6866e1be3e"},{"version":"45acda6f0879fde3db8ebd6403e50b3fbda7405668422fb086e17fc683282dca","signature":"8a8b4ea9de187718cd708cd029a03069b9fb93966c1b9e3c8930ead2e8a07d7a"},{"version":"e1cb843a24258f9a8870df8c6f2f7ae5d25419fe42c96354aa4a1e0506f378b0","signature":"f560512d097ffaad340c3613bbb04b482ed4ec2805fa4675d1bb8db83d4f2a3b"},{"version":"5ca09927cb20cc34701fd9ea8ff097a2fa4179af9e2b49ff696d3489d45e7064","signature":"b311a3a966a69f18fb3a95b012ec9731bd4d3bfa4803d1bcef821f487a07a6dc"},{"version":"3d3d0b9cc3318b474df15479b93d6e955d3f035190c5cb4588611add4a6afe31","signature":"40e20bfaa53cf766128e6dc9ac0bcf402c96e3f7e3743d89f12fc99be91b7cf9"},{"version":"0133649594563a71a0d30d83e3fe3cdbf443fc2d101898562a07cef5540961ca","signature":"ca6a5aaa46094b79f934641c0161a53caeda84bdb61dd0f9a954fd05c9f1847e"},{"version":"87fef3c3ea4fe1171775b0b7bd8270d27d6370a65718a0bf4a8d378c5ea5739d","signature":"daf8c778b76e219a8a39a3ea31316254f4e824576cf0322af764460c55a49462"},{"version":"df83c9a47ed71bbf3ce5b066b8b23e2d21eff75f1ea7bdc28a23eba9e8b538d1","signature":"8c30828f895b19b1889f848ef4c991e8278fb88daac1decbc3d0a4faa2f34f6c"},{"version":"032267e68578e8f961d1716fc93f963070b298226f858b2e77a55730785ec8f7","signature":"f255a8a4dfeeea59d48ca42743fadc7d0738acd3650d72f8ff6a17aa74eb9c73"},{"version":"9d607af3553339ed81728291145877be24e64c320df9f5dba29f8890cf1f3c36","signature":"1d9c8910d05babee8aa55f2b2a52d419d7ca90ae7afc0620f21409eb1418c16a"},{"version":"151ff381ef9ff8da2da9b9663ebf657eac35c4c9a19183420c05728f31a6761d","impliedFormat":1},{"version":"f3d8c757e148ad968f0d98697987db363070abada5f503da3c06aefd9d4248c1","impliedFormat":1},{"version":"a0acca63c9e39580f32a10945df231815f0fe554c074da96ba6564010ffbd2d8","impliedFormat":1}],"root":[[66,75]],"options":{"allowJs":true,"allowSyntheticDefaultImports":true,"composite":true,"declaration":true,"declarationMap":true,"esModuleInterop":true,"jsx":4,"module":1,"noFallthroughCasesInSwitch":true,"noImplicitAny":true,"noImplicitReturns":true,"outDir":"./","rootDir":"..","skipLibCheck":true,"sourceMap":true,"strict":true,"strictFunctionTypes":true,"target":7,"tsBuildInfoFile":"./.tsbuildinfo"},"referencedMap":[[67,1],[66,2],[70,3],[71,4],[69,5],[73,6],[74,7],[72,8],[75,2],[68,2],[78,9],[50,10],[51,9],[65,11],[54,12],[56,13],[63,14],[57,15],[60,16],[64,17],[55,18],[62,19]],"semanticDiagnosticsPerFile":[[66,[{"start":5399,"length":51,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":5485,"length":57,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":5546,"length":48,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":5623,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":5715,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":5802,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":5892,"length":42,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":5968,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6018,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6083,"length":48,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6118,"length":12,"code":2339,"category":1,"messageText":"Property 'organization' does not exist on type 'typeof User'."},{"start":6161,"length":55,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6203,"length":12,"code":2339,"category":1,"messageText":"Property 'organization' does not exist on type 'typeof FeatureFlag'."},{"start":6353,"length":51,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6431,"length":57,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6492,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6559,"length":57,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6645,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6705,"length":23,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6758,"length":83,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":6781,"length":4,"code":2353,"category":1,"messageText":"Object literal may only specify known properties, and 'enum' does not exist in type '{ type?: string | undefined; length?: number | undefined; nullable?: boolean | undefined; unique?: boolean | undefined; default?: any; comment?: string | undefined; }'."},{"start":6898,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7004,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7064,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7150,"length":42,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7226,"length":45,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7305,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7355,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7420,"length":91,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7450,"length":12,"messageText":"Parameter 'organization' implicitly has an 'any' type.","category":1,"code":7006},{"start":7486,"length":24,"messageText":"Expected 1-2 arguments, but got 3.","category":1,"code":2554},{"start":7515,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7597,"length":52,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7644,"length":4,"code":2339,"category":1,"messageText":"Property 'user' does not exist on type 'typeof UserFlag'."},{"start":7687,"length":53,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7735,"length":4,"code":2339,"category":1,"messageText":"Property 'user' does not exist on type 'typeof UserSession'."},{"start":7885,"length":51,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":7963,"length":57,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":8024,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":8092,"length":57,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":8178,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":8254,"length":91,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":8277,"length":4,"code":2353,"category":1,"messageText":"Object literal may only specify known properties, and 'enum' does not exist in type '{ type?: string | undefined; length?: number | undefined; nullable?: boolean | undefined; unique?: boolean | undefined; default?: any; comment?: string | undefined; }'."},{"start":8413,"length":41,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":8536,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":8725,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":8999,"length":43,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9077,"length":43,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9156,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9245,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9316,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9376,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9462,"length":80,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9546,"length":29,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9619,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9669,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9734,"length":97,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9764,"length":12,"messageText":"Parameter 'organization' implicitly has an 'any' type.","category":1,"code":7006},{"start":9807,"length":23,"messageText":"Expected 1-2 arguments, but got 3.","category":1,"code":2554},{"start":9835,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9917,"length":59,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":9964,"length":11,"code":2339,"category":1,"messageText":"Property 'featureFlag' does not exist on type 'typeof UserFlag'."},{"start":10014,"length":54,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10056,"length":11,"code":2339,"category":1,"messageText":"Property 'featureFlag' does not exist on type 'typeof FlagEvent'."},{"start":10192,"length":51,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10270,"length":57,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10331,"length":31,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10393,"length":57,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10454,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10531,"length":41,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10647,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10718,"length":42,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10794,"length":45,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10871,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10921,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":10986,"length":70,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11008,"length":4,"messageText":"Parameter 'user' implicitly has an 'any' type.","category":1,"code":7006},{"start":11032,"length":23,"messageText":"Expected 1-2 arguments, but got 3.","category":1,"code":2554},{"start":11060,"length":31,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11118,"length":77,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11147,"length":4,"messageText":"Parameter 'flag' implicitly has an 'any' type.","category":1,"code":7006},{"start":11171,"length":23,"messageText":"Expected 1-2 arguments, but got 3.","category":1,"code":2554},{"start":11199,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11333,"length":47,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11533,"length":51,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11614,"length":57,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11675,"length":31,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11737,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11826,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11916,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":11990,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12079,"length":42,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12155,"length":45,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12237,"length":45,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12314,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12364,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12429,"length":69,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12451,"length":4,"messageText":"Parameter 'user' implicitly has an 'any' type.","category":1,"code":7006},{"start":12474,"length":23,"messageText":"Expected 1-2 arguments, but got 3.","category":1,"code":2554},{"start":12502,"length":31,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12649,"length":51,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12727,"length":57,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12788,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12865,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12925,"length":31,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":12987,"length":103,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13010,"length":4,"code":2353,"category":1,"messageText":"Object literal may only specify known properties, and 'enum' does not exist in type '{ type?: string | undefined; length?: number | undefined; nullable?: boolean | undefined; unique?: boolean | undefined; default?: any; comment?: string | undefined; }'."},{"start":13094,"length":23,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13201,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13280,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13354,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13443,"length":40,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13514,"length":56,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13601,"length":18,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13666,"length":74,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13695,"length":4,"messageText":"Parameter 'flag' implicitly has an 'any' type.","category":1,"code":7006},{"start":13716,"length":23,"messageText":"Expected 1-2 arguments, but got 3.","category":1,"code":2554},{"start":13744,"length":39,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13824,"length":47,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":13875,"length":31,"code":1240,"category":1,"messageText":{"messageText":"Unable to resolve signature of property decorator when called as an expression.","category":1,"code":1240,"next":[{"messageText":"Argument of type 'undefined' is not assignable to parameter of type 'Object'.","category":1,"code":2345}]}},{"start":18245,"length":6,"code":2739,"category":1,"messageText":"Type '{ name: string; isActive: boolean; description?: string | undefined; domain?: string | undefined; settings?: Record | undefined; }' is missing the following properties from type 'CreateOrganizationInput': users, featureFlags","canonicalHead":{"code":2322,"messageText":"Type '{ name: string; isActive: boolean; description?: string | undefined; domain?: string | undefined; settings?: Record | undefined; }' is not assignable to type 'CreateOrganizationInput'."}},{"start":18360,"length":6,"code":2739,"category":1,"messageText":"Type '{ name: string; isActive: boolean; key: string; kind: \"user\" | \"organization\" | \"device\"; email?: string | undefined; custom?: Record | undefined; organizationId?: string | undefined; }' is missing the following properties from type 'CreateUserInput': userFlags, sessions","canonicalHead":{"code":2322,"messageText":"Type '{ name: string; isActive: boolean; key: string; kind: \"user\" | \"organization\" | \"device\"; email?: string | undefined; custom?: Record | undefined; organizationId?: string | undefined; }' is not assignable to type 'CreateUserInput'."}},{"start":18481,"length":6,"code":2739,"category":1,"messageText":"Type '{ name: string; key: string; valueType: \"string\" | \"number\" | \"boolean\" | \"json\"; isEnabled: boolean; isArchived: boolean; environment: string; description?: string | undefined; organizationId?: string | undefined; ... 4 more ...; tags?: string[] | undefined; }' is missing the following properties from type 'CreateFeatureFlagInput': userFlags, events","canonicalHead":{"code":2322,"messageText":"Type '{ name: string; key: string; valueType: \"string\" | \"number\" | \"boolean\" | \"json\"; isEnabled: boolean; isArchived: boolean; environment: string; description?: string | undefined; organizationId?: string | undefined; ... 4 more ...; tags?: string[] | undefined; }' is not assignable to type 'CreateFeatureFlagInput'."}},{"start":18603,"length":6,"code":2739,"category":1,"messageText":"Type '{ userId: string; featureFlagId: string; isActive: boolean; value?: unknown; reason?: string | undefined; expiresAt?: Date | undefined; }' is missing the following properties from type 'CreateUserFlagInput': user, featureFlag","canonicalHead":{"code":2322,"messageText":"Type '{ userId: string; featureFlagId: string; isActive: boolean; value?: unknown; reason?: string | undefined; expiresAt?: Date | undefined; }' is not assignable to type 'CreateUserFlagInput'."}}]],[67,[{"start":5920,"length":7,"messageText":"Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.","category":1,"code":2580}]],[68,[{"start":4596,"length":4,"messageText":"Type 'K' cannot be used to index type 'T'.","category":1,"code":2536},{"start":4633,"length":4,"messageText":"Type 'K' cannot be used to index type 'T'.","category":1,"code":2536},{"start":4721,"length":4,"messageText":"Type 'K' cannot be used to index type 'T'.","category":1,"code":2536},{"start":4739,"length":4,"messageText":"Type 'K' cannot be used to index type 'T'.","category":1,"code":2536},{"start":13619,"length":14,"code":2339,"category":1,"messageText":"Property 'hasOwnProperty' does not exist on type 'U'."}]],[69,[{"start":1027,"length":6,"messageText":"Module '\"./types.js\"' has no exported member 'UserId'.","category":1,"code":2305}]],[70,[{"start":8057,"length":12,"messageText":"Cannot find name 'setImmediate'.","category":1,"code":2304},{"start":11290,"length":6,"messageText":"Cannot find namespace 'NodeJS'.","category":1,"code":2503},{"start":11926,"length":6,"messageText":"Cannot find namespace 'NodeJS'.","category":1,"code":2503}]],[71,[{"start":1115,"length":6,"messageText":"Module '\"./types.js\"' has no exported member 'UserId'.","category":1,"code":2305},{"start":1268,"length":24,"messageText":"Cannot redeclare exported variable 'basicEventEmitterExample'.","category":1,"code":2323},{"start":2452,"length":25,"messageText":"Cannot redeclare exported variable 'multipleEventTypesExample'.","category":1,"code":2323},{"start":4623,"length":31,"messageText":"Cannot redeclare exported variable 'advancedHandlerUtilitiesExample'.","category":1,"code":2323},{"start":7724,"length":24,"messageText":"Cannot redeclare exported variable 'eventSubscriptionExample'.","category":1,"code":2323},{"start":9849,"length":27,"messageText":"Cannot redeclare exported variable 'flagEventIntegrationExample'.","category":1,"code":2323},{"start":11793,"length":25,"messageText":"Cannot redeclare exported variable 'globalEventEmitterExample'.","category":1,"code":2323},{"start":13160,"length":22,"messageText":"Cannot redeclare exported variable 'eventCategoriesExample'.","category":1,"code":2323},{"start":15310,"length":24,"messageText":"Cannot redeclare exported variable 'basicEventEmitterExample'.","category":1,"code":2323},{"start":15310,"length":24,"messageText":"Export declaration conflicts with exported declaration of 'basicEventEmitterExample'.","category":1,"code":2484},{"start":15338,"length":25,"messageText":"Cannot redeclare exported variable 'multipleEventTypesExample'.","category":1,"code":2323},{"start":15338,"length":25,"messageText":"Export declaration conflicts with exported declaration of 'multipleEventTypesExample'.","category":1,"code":2484},{"start":15367,"length":31,"messageText":"Cannot redeclare exported variable 'advancedHandlerUtilitiesExample'.","category":1,"code":2323},{"start":15367,"length":31,"messageText":"Export declaration conflicts with exported declaration of 'advancedHandlerUtilitiesExample'.","category":1,"code":2484},{"start":15402,"length":24,"messageText":"Cannot redeclare exported variable 'eventSubscriptionExample'.","category":1,"code":2323},{"start":15402,"length":24,"messageText":"Export declaration conflicts with exported declaration of 'eventSubscriptionExample'.","category":1,"code":2484},{"start":15430,"length":27,"messageText":"Cannot redeclare exported variable 'flagEventIntegrationExample'.","category":1,"code":2323},{"start":15430,"length":27,"messageText":"Export declaration conflicts with exported declaration of 'flagEventIntegrationExample'.","category":1,"code":2484},{"start":15461,"length":25,"messageText":"Cannot redeclare exported variable 'globalEventEmitterExample'.","category":1,"code":2323},{"start":15461,"length":25,"messageText":"Export declaration conflicts with exported declaration of 'globalEventEmitterExample'.","category":1,"code":2484},{"start":15490,"length":22,"messageText":"Cannot redeclare exported variable 'eventCategoriesExample'.","category":1,"code":2323},{"start":15490,"length":22,"messageText":"Export declaration conflicts with exported declaration of 'eventCategoriesExample'.","category":1,"code":2484}]],[72,[{"start":9357,"length":26,"code":2352,"category":1,"messageText":"Conversion of type '{ id: string; }' to type 'Partial' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."},{"start":18610,"length":5,"code":2322,"category":1,"messageText":"Type 'unknown' is not assignable to type 'string | number | boolean | Record'.","relatedInformation":[{"file":"../entities.ts","start":10582,"length":5,"messageText":"The expected type comes from property 'value' which is declared here on type 'CreateUserFlagInput'","category":3,"code":6500}]},{"start":23054,"length":130,"code":2345,"category":1,"messageText":{"messageText":"Argument of type '{ featureFlagId: string; userId: UserId; eventType: \"evaluation\"; newValue: unknown; context: Record | undefined; }' is not assignable to parameter of type 'CreateFlagEventInput'.","category":1,"code":2345,"next":[{"messageText":"Property 'featureFlag' is missing in type '{ featureFlagId: string; userId: UserId; eventType: \"evaluation\"; newValue: unknown; context: Record | undefined; }' but required in type 'CreateFlagEventInput'.","category":1,"code":2741}]},"relatedInformation":[{"file":"../entities.ts","start":13793,"length":11,"messageText":"'featureFlag' is declared here.","category":3,"code":2728}]},{"start":23431,"length":141,"code":2345,"category":1,"messageText":{"messageText":"Argument of type '{ featureFlagId: string; userId: UserId; eventType: \"update\"; previousValue: unknown; newValue: unknown; reason: string | undefined; }' is not assignable to parameter of type 'CreateFlagEventInput'.","category":1,"code":2345,"next":[{"messageText":"Property 'featureFlag' is missing in type '{ featureFlagId: string; userId: UserId; eventType: \"update\"; previousValue: unknown; newValue: unknown; reason: string | undefined; }' but required in type 'CreateFlagEventInput'.","category":1,"code":2741}]},"relatedInformation":[{"file":"../entities.ts","start":13793,"length":11,"messageText":"'featureFlag' is declared here.","category":3,"code":2728}]}]],[73,[{"start":16106,"length":244,"code":2345,"category":1,"messageText":{"messageText":"Argument of type '{ name: string; description: string; domain: string; isActive: true; settings: { theme: string; notifications: boolean; }; }' is not assignable to parameter of type 'CreateOrganizationInput'.","category":1,"code":2345,"next":[{"messageText":"Type '{ name: string; description: string; domain: string; isActive: true; settings: { theme: string; notifications: boolean; }; }' is missing the following properties from type 'CreateOrganizationInput': users, featureFlags","category":1,"code":2739}]}},{"start":16609,"length":291,"code":2739,"category":1,"messageText":"Type '{ key: string; name: string; email: string; kind: \"user\"; organizationId: OrganizationId; isActive: true; custom: { department: string; role: string; }; }' is missing the following properties from type 'CreateUserInput': userFlags, sessions","canonicalHead":{"code":2322,"messageText":"Type '{ key: string; name: string; email: string; kind: \"user\"; organizationId: OrganizationId; isActive: true; custom: { department: string; role: string; }; }' is not assignable to type 'CreateUserInput'."}},{"start":16910,"length":287,"code":2739,"category":1,"messageText":"Type '{ key: string; name: string; email: string; kind: \"user\"; organizationId: OrganizationId; isActive: true; custom: { department: string; role: string; }; }' is missing the following properties from type 'CreateUserInput': userFlags, sessions","canonicalHead":{"code":2322,"messageText":"Type '{ key: string; name: string; email: string; kind: \"user\"; organizationId: OrganizationId; isActive: true; custom: { department: string; role: string; }; }' is not assignable to type 'CreateUserInput'."}},{"start":17795,"length":11,"code":2322,"category":1,"messageText":{"messageText":"Type 'string' is not assignable to type 'EnvironmentKey'.","category":1,"code":2322,"next":[{"messageText":"Type 'string' is not assignable to type '{ readonly __brand: \"EnvironmentKey\"; }'.","category":1,"code":2322}]},"relatedInformation":[{"file":"../entities.ts","start":9585,"length":11,"messageText":"The expected type comes from property 'environment' which is declared here on type 'CreateFeatureFlagInput'","category":3,"code":6500}]},{"start":18195,"length":11,"code":2322,"category":1,"messageText":{"messageText":"Type 'string' is not assignable to type 'EnvironmentKey'.","category":1,"code":2322,"next":[{"messageText":"Type 'string' is not assignable to type '{ readonly __brand: \"EnvironmentKey\"; }'.","category":1,"code":2322}]},"relatedInformation":[{"file":"../entities.ts","start":9585,"length":11,"messageText":"The expected type comes from property 'environment' which is declared here on type 'CreateFeatureFlagInput'","category":3,"code":6500}]},{"start":21803,"length":125,"code":2345,"category":1,"messageText":{"messageText":"Argument of type '{ name: string; description: string; isActive: true; }' is not assignable to parameter of type 'CreateOrganizationInput'.","category":1,"code":2345,"next":[{"messageText":"Type '{ name: string; description: string; isActive: true; }' is missing the following properties from type 'CreateOrganizationInput': users, featureFlags","category":1,"code":2739}]}},{"start":22019,"length":206,"code":2345,"category":1,"messageText":{"messageText":"Argument of type '{ key: string; name: string; email: string; kind: \"user\"; organizationId: OrganizationId; isActive: true; }' is not assignable to parameter of type 'CreateUserInput'.","category":1,"code":2345,"next":[{"messageText":"Type '{ key: string; name: string; email: string; kind: \"user\"; organizationId: OrganizationId; isActive: true; }' is missing the following properties from type 'CreateUserInput': userFlags, sessions","category":1,"code":2739}]}},{"start":22598,"length":11,"code":2322,"category":1,"messageText":{"messageText":"Type 'string' is not assignable to type 'EnvironmentKey'.","category":1,"code":2322,"next":[{"messageText":"Type 'string' is not assignable to type '{ readonly __brand: \"EnvironmentKey\"; }'.","category":1,"code":2322}]},"relatedInformation":[{"file":"../entities.ts","start":9585,"length":11,"messageText":"The expected type comes from property 'environment' which is declared here on type 'CreateFeatureFlagInput'","category":3,"code":6500}]},{"start":24364,"length":11,"messageText":"The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', 'node18', or 'nodenext'.","category":1,"code":1343},{"start":24394,"length":7,"messageText":"Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.","category":1,"code":2580}]],[74,[{"start":5347,"length":20,"messageText":"Duplicate identifier 'TypeSafeEventEmitter'.","category":1,"code":2300},{"start":5718,"length":20,"messageText":"Duplicate identifier 'TypeSafeEventEmitter'.","category":1,"code":2300},{"start":5413,"length":12,"messageText":"Duplicate identifier 'EventFactory'.","category":1,"code":2300},{"start":5762,"length":12,"messageText":"Duplicate identifier 'EventFactory'.","category":1,"code":2300},{"start":1303,"length":23,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1330,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1349,"length":22,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1375,"length":19,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1398,"length":22,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1424,"length":20,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1475,"length":23,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1502,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1521,"length":22,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1547,"length":19,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1570,"length":22,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1617,"length":19,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1640,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1655,"length":18,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1677,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":1719,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2378,"length":23,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2405,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2424,"length":22,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2450,"length":19,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2473,"length":22,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2499,"length":20,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2928,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2944,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2960,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2975,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":2991,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3006,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3022,"length":21,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3047,"length":19,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3102,"length":21,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3127,"length":14,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3145,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3160,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3175,"length":10,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3189,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3205,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3220,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3235,"length":9,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3248,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3290,"length":14,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3308,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3327,"length":13,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3369,"length":14,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3387,"length":16,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3407,"length":9,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3420,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3470,"length":14,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3488,"length":21,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3513,"length":9,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3526,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3542,"length":6,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3552,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3599,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3618,"length":20,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3642,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3661,"length":19,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3712,"length":18,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3734,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3749,"length":19,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3772,"length":19,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3825,"length":20,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3849,"length":17,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3870,"length":14,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3912,"length":16,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3932,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3951,"length":18,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":3973,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4019,"length":11,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4034,"length":13,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4051,"length":8,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4099,"length":13,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4116,"length":18,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4138,"length":18,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4160,"length":18,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4182,"length":22,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4692,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4711,"length":7,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4722,"length":14,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4831,"length":16,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4851,"length":21,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4876,"length":17,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4897,"length":17,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4918,"length":17,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4939,"length":17,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4960,"length":23,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":4987,"length":21,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5012,"length":18,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5034,"length":19,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5084,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5103,"length":9,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5116,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5132,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5148,"length":16,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5168,"length":22,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5194,"length":23,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5221,"length":15,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5240,"length":18,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5262,"length":20,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5286,"length":24,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5347,"length":20,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5371,"length":17,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5392,"length":17,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5413,"length":12,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5454,"length":14,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5472,"length":17,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":5493,"length":16,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":7554,"length":18,"messageText":"Cannot find name 'DatabaseConnection'.","category":1,"code":2304},{"start":7590,"length":18,"messageText":"Cannot find name 'RepositoryProvider'.","category":1,"code":2304},{"start":7624,"length":10,"messageText":"Cannot find name 'UnitOfWork'.","category":1,"code":2304},{"start":7668,"length":18,"messageText":"Cannot find name 'initializeDatabase'.","category":1,"code":2304},{"start":7719,"length":24,"messageText":"Cannot find name 'createRepositoryProvider'.","category":1,"code":2304},{"start":7778,"length":16,"messageText":"Cannot find name 'createUnitOfWork'.","category":1,"code":2304},{"start":7977,"length":10,"messageText":"Cannot find name 'UnitOfWork'.","category":1,"code":2304},{"start":8025,"length":19,"messageText":"Cannot find name 'OrganizationService'.","category":1,"code":2304},{"start":8087,"length":11,"messageText":"Cannot find name 'UserService'.","category":1,"code":2304},{"start":8166,"length":18,"messageText":"Cannot find name 'FeatureFlagService'.","category":1,"code":2304}]],[75,[{"start":6877,"length":19,"messageText":"Cannot find name 'GetFeatureFlagInput'.","category":1,"code":2304},{"start":6931,"length":19,"messageText":"Cannot find name 'GetFeatureFlagInput'.","category":1,"code":2304},{"start":7148,"length":19,"messageText":"Cannot find name 'GetFeatureFlagInput'.","category":1,"code":2304},{"start":8303,"length":22,"messageText":"Cannot find name 'UpdateFeatureFlagInput'.","category":1,"code":2304},{"start":8360,"length":22,"messageText":"Cannot find name 'UpdateFeatureFlagInput'.","category":1,"code":2304},{"start":8580,"length":22,"messageText":"Cannot find name 'UpdateFeatureFlagInput'.","category":1,"code":2304},{"start":12498,"length":11,"messageText":"Cannot find name 'UserContext'.","category":1,"code":2304},{"start":12592,"length":11,"messageText":"Cannot find name 'UserContext'.","category":1,"code":2304},{"start":12817,"length":11,"messageText":"Cannot find name 'UserContext'.","category":1,"code":2304},{"start":12923,"length":11,"messageText":"Cannot find name 'UserContext'.","category":1,"code":2304},{"start":13315,"length":6,"messageText":"Cannot find name 'LDUser'.","category":1,"code":2304},{"start":13402,"length":6,"messageText":"Cannot find name 'LDUser'.","category":1,"code":2304},{"start":13620,"length":6,"messageText":"Cannot find name 'LDUser'.","category":1,"code":2304},{"start":13719,"length":6,"messageText":"Cannot find name 'LDUser'.","category":1,"code":2304},{"start":21542,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":21553,"length":6,"messageText":"Namespace 'API' has no exported member 'LDUser'.","category":1,"code":2694},{"start":21807,"length":11,"messageText":"Namespace 'Domain' has no exported member 'UserContext'.","category":1,"code":2694},{"start":21825,"length":6,"messageText":"Namespace 'API' has no exported member 'LDUser'.","category":1,"code":2694},{"start":22186,"length":12,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlags'.","category":1,"code":2694},{"start":22205,"length":20,"messageText":"Namespace 'API' has no exported member 'FeatureFlagsResponse'.","category":1,"code":2694},{"start":22459,"length":19,"messageText":"Namespace 'Domain' has no exported member 'GetFeatureFlagInput'.","category":1,"code":2694},{"start":22485,"length":21,"messageText":"Namespace 'API' has no exported member 'GetFeatureFlagRequest'.","category":1,"code":2694},{"start":22738,"length":6,"messageText":"Namespace 'API' has no exported member 'LDUser'.","category":1,"code":2694},{"start":22754,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":23022,"length":20,"messageText":"Namespace 'API' has no exported member 'FeatureFlagsResponse'.","category":1,"code":2694},{"start":23052,"length":12,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlags'.","category":1,"code":2694},{"start":23307,"length":22,"messageText":"Namespace 'API' has no exported member 'FeatureFlagApiResponse'.","category":1,"code":2694},{"start":23339,"length":11,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlag'.","category":1,"code":2694},{"start":23729,"length":11,"messageText":"Namespace 'API' has no exported member 'ApiResponse'.","category":1,"code":2694},{"start":24271,"length":19,"messageText":"Cannot find name 'GetFeatureFlagInput'.","category":1,"code":2304},{"start":24313,"length":11,"messageText":"Cannot find name 'FeatureFlag'.","category":1,"code":2304},{"start":24356,"length":23,"messageText":"Cannot find name 'GetAllFeatureFlagsInput'.","category":1,"code":2304},{"start":24480,"length":22,"messageText":"Cannot find name 'UpdateFeatureFlagInput'.","category":1,"code":2304},{"start":24558,"length":11,"messageText":"Cannot find name 'FeatureFlag'.","category":1,"code":2304},{"start":24602,"length":22,"messageText":"Cannot find name 'DeleteFeatureFlagInput'.","category":1,"code":2304},{"start":25095,"length":21,"messageText":"Cannot find name 'GetFeatureFlagRequest'.","category":1,"code":2304},{"start":25139,"length":22,"messageText":"Cannot find name 'FeatureFlagApiResponse'.","category":1,"code":2304},{"start":25195,"length":25,"messageText":"Cannot find name 'GetAllFeatureFlagsRequest'.","category":1,"code":2304},{"start":25243,"length":20,"messageText":"Cannot find name 'FeatureFlagsResponse'.","category":1,"code":2304},{"start":25296,"length":24,"messageText":"Cannot find name 'UpdateFeatureFlagRequest'.","category":1,"code":2304},{"start":25413,"length":24,"messageText":"Cannot find name 'DeleteFeatureFlagRequest'.","category":1,"code":2304},{"start":25638,"length":19,"messageText":"Cannot find name 'GetFeatureFlagInput'.","category":1,"code":2304},{"start":25670,"length":11,"messageText":"Cannot find name 'FeatureFlag'.","category":1,"code":2304},{"start":25746,"length":23,"messageText":"Cannot find name 'GetAllFeatureFlagsInput'.","category":1,"code":2304},{"start":25858,"length":22,"messageText":"Cannot find name 'UpdateFeatureFlagInput'.","category":1,"code":2304},{"start":25926,"length":11,"messageText":"Cannot find name 'FeatureFlag'.","category":1,"code":2304},{"start":26041,"length":22,"messageText":"Cannot find name 'DeleteFeatureFlagInput'.","category":1,"code":2304},{"start":26213,"length":17,"messageText":"Cannot find name 'GetUserFlagsInput'.","category":1,"code":2304},{"start":26316,"length":19,"messageText":"Cannot find name 'UpdateUserFlagInput'.","category":1,"code":2304},{"start":26483,"length":21,"messageText":"Cannot find name 'FeatureFlagProcedures'.","category":1,"code":2304},{"start":26567,"length":21,"messageText":"Cannot find name 'FeatureFlagProcedures'.","category":1,"code":2304},{"start":26629,"length":21,"messageText":"Cannot find name 'FeatureFlagProcedures'.","category":1,"code":2304},{"start":26720,"length":21,"messageText":"Cannot find name 'FeatureFlagProcedures'.","category":1,"code":2304},{"start":27143,"length":21,"messageText":"Cannot find name 'FeatureFlagProcedures'.","category":1,"code":2304},{"start":29381,"length":11,"messageText":"Cannot find name 'UserContext'.","category":1,"code":2304},{"start":29467,"length":11,"messageText":"Cannot find name 'UserContext'.","category":1,"code":2304},{"start":29958,"length":21,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlagRepository'.","category":1,"code":2694},{"start":30055,"length":19,"messageText":"Namespace 'Domain' has no exported member 'IFeatureFlagService'.","category":1,"code":2694},{"start":30248,"length":20,"messageText":"Namespace 'API' has no exported member 'FeatureFlagApiClient'.","category":1,"code":2694},{"start":30361,"length":19,"messageText":"Namespace 'Domain' has no exported member 'IFeatureFlagService'.","category":1,"code":2694},{"start":30476,"length":21,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlagRepository'.","category":1,"code":2694},{"start":30523,"length":20,"messageText":"Namespace 'API' has no exported member 'FeatureFlagApiClient'.","category":1,"code":2694},{"start":30585,"length":21,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlagRepository'.","category":1,"code":2694},{"start":30623,"length":20,"messageText":"Namespace 'API' has no exported member 'FeatureFlagApiClient'.","category":1,"code":2694},{"start":30767,"length":11,"messageText":"Namespace 'Domain' has no exported member 'UserContext'.","category":1,"code":2694},{"start":30808,"length":12,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlags'.","category":1,"code":2694},{"start":32141,"length":11,"messageText":"Namespace 'Domain' has no exported member 'UserContext'.","category":1,"code":2694},{"start":32796,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":32837,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":34577,"length":21,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlagRepository'.","category":1,"code":2694},{"start":34837,"length":19,"messageText":"Namespace 'Domain' has no exported member 'GetFeatureFlagInput'.","category":1,"code":2694},{"start":34886,"length":11,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlag'.","category":1,"code":2694},{"start":35505,"length":11,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlag'.","category":1,"code":2694},{"start":35837,"length":23,"messageText":"Namespace 'Domain' has no exported member 'GetAllFeatureFlagsInput'.","category":1,"code":2694},{"start":35890,"length":12,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlags'.","category":1,"code":2694},{"start":36919,"length":3,"messageText":"Parameter 'tag' implicitly has an 'any' type.","category":1,"code":7006},{"start":37532,"length":12,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlags'.","category":1,"code":2694},{"start":37896,"length":22,"messageText":"Namespace 'Domain' has no exported member 'UpdateFeatureFlagInput'.","category":1,"code":2694},{"start":37981,"length":11,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlag'.","category":1,"code":2694},{"start":38271,"length":22,"messageText":"Namespace 'Domain' has no exported member 'DeleteFeatureFlagInput'.","category":1,"code":2694},{"start":39157,"length":19,"messageText":"Cannot find name 'IFeatureFlagService'.","category":1,"code":2304},{"start":39208,"length":19,"messageText":"Cannot find name 'IFeatureFlagService'.","category":1,"code":2304},{"start":43866,"length":34,"messageText":"Expected 2 arguments, but got 1.","category":1,"code":2554,"relatedInformation":[{"start":30608,"length":35,"messageText":"An argument for 'apiClient' was not provided.","category":3,"code":6210}]},{"start":44891,"length":25,"code":2345,"category":1,"messageText":"Argument of type 'unknown' is not assignable to parameter of type 'boolean'."},{"start":45398,"length":29,"code":2345,"category":1,"messageText":"Argument of type 'unknown' is not assignable to parameter of type 'boolean'."},{"start":45856,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":45913,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":45933,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":45993,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":46013,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":46126,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":46221,"length":12,"messageText":"Namespace 'Domain' has no exported member 'FeatureFlags'.","category":1,"code":2694},{"start":46310,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":46377,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":47419,"length":6,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":47428,"length":3,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205}]]],"latestChangedDtsFile":"./sample.d.ts","version":"5.8.3"} \ No newline at end of file diff --git a/launchdarkly/node/dist/database.d.ts b/launchdarkly/node/dist/database.d.ts new file mode 100644 index 00000000..7e915f2a --- /dev/null +++ b/launchdarkly/node/dist/database.d.ts @@ -0,0 +1,300 @@ +/** + * TypeORM database configuration and connection setup + * with type-safe query builders and connection management + */ +import { z } from "zod"; +import { Organization, User, FeatureFlag, UserFlag, UserSession, FlagEvent } from "./entities.js"; +/** + * Mock TypeORM interfaces for demonstration purposes + * In actual implementation, these would be imported from 'typeorm' + */ +interface DataSourceOptions { + type: 'postgres' | 'mysql' | 'sqlite' | 'mongodb'; + host?: string; + port?: number; + username?: string; + password?: string; + database?: string; + entities: Function[]; + synchronize?: boolean; + logging?: boolean; + ssl?: boolean | object; + migrations?: string[]; + migrationsRun?: boolean; +} +interface QueryRunner { + connect(): Promise; + release(): Promise; + startTransaction(): Promise; + commitTransaction(): Promise; + rollbackTransaction(): Promise; +} +interface Repository { + find(options?: FindManyOptions): Promise; + findOne(options?: FindOneOptions): Promise; + findOneBy(where: Partial): Promise; + save(entity: Partial): Promise; + update(criteria: any, partialEntity: Partial): Promise; + delete(criteria: any): Promise; + create(entityData: Partial): Entity; + count(options?: FindManyOptions): Promise; +} +interface FindManyOptions { + where?: Partial | Partial[]; + relations?: string[] | Record>; + order?: Record; + skip?: number; + take?: number; + select?: (keyof Entity)[]; +} +interface FindOneOptions { + where?: Partial; + relations?: string[] | Record>; + select?: (keyof Entity)[]; +} +declare class MockDataSource { + private options; + constructor(options: DataSourceOptions); + initialize(): Promise; + destroy(): Promise; + getRepository(entityClass: Function): Repository; + createQueryRunner(): QueryRunner; + get isInitialized(): boolean; +} +/** + * Database configuration schema with validation + */ +declare const DatabaseConfigSchema: z.ZodObject<{ + type: z.ZodDefault>; + host: z.ZodDefault; + port: z.ZodDefault; + username: z.ZodString; + password: z.ZodString; + database: z.ZodString; + synchronize: z.ZodDefault; + logging: z.ZodDefault; + ssl: z.ZodDefault]>>; + maxConnections: z.ZodDefault; + acquireTimeout: z.ZodDefault; + timeout: z.ZodDefault; + migrationsRun: z.ZodDefault; +}, "strip", z.ZodTypeAny, { + type: "postgres" | "mysql" | "sqlite" | "mongodb"; + host: string; + port: number; + username: string; + password: string; + database: string; + synchronize: boolean; + logging: boolean; + ssl: boolean | Record; + maxConnections: number; + acquireTimeout: number; + timeout: number; + migrationsRun: boolean; +}, { + username: string; + password: string; + database: string; + type?: "postgres" | "mysql" | "sqlite" | "mongodb" | undefined; + host?: string | undefined; + port?: number | undefined; + synchronize?: boolean | undefined; + logging?: boolean | undefined; + ssl?: boolean | Record | undefined; + maxConnections?: number | undefined; + acquireTimeout?: number | undefined; + timeout?: number | undefined; + migrationsRun?: boolean | undefined; +}>; +type DatabaseConfig = z.infer; +/** + * Environment-based database configuration + */ +export declare function createDatabaseConfig(env?: Record): DatabaseConfig; +/** + * Database connection class with connection pooling and error handling + */ +export declare class DatabaseConnection { + private dataSource; + private config; + constructor(config?: Partial); + /** + * Initialize database connection + */ + connect(): Promise; + /** + * Close database connection + */ + disconnect(): Promise; + /** + * Get database data source + */ + getDataSource(): MockDataSource; + /** + * Get repository for an entity + */ + getRepository(entityClass: Function): Repository; + /** + * Execute database operations within a transaction + */ + transaction(callback: (queryRunner: QueryRunner) => Promise): Promise; + /** + * Health check for database connection + */ + healthCheck(): Promise<{ + healthy: boolean; + latency?: number; + error?: string; + }>; +} +/** + * Type-safe query builder for entities + */ +export declare class TypeSafeQueryBuilder { + private repository; + private entityName; + constructor(repository: Repository, entityName: string); + /** + * Find entities with type-safe filters and relations + */ + find(options?: { + where?: Partial; + relations?: string[]; + order?: Record; + skip?: number; + take?: number; + select?: (keyof T)[]; + }): Promise; + /** + * Find one entity with type-safe options + */ + findOne(options: { + where?: Partial; + relations?: string[]; + select?: (keyof T)[]; + }): Promise; + /** + * Find entity by ID with relations + */ + findById(id: any, relations?: string[]): Promise; + /** + * Create new entity + */ + create(data: Partial): Promise; + /** + * Update entity by ID + */ + update(id: any, data: Partial): Promise; + /** + * Delete entity by ID + */ + delete(id: any): Promise; + /** + * Count entities with filters + */ + count(where?: Partial): Promise; + /** + * Check if entity exists + */ + exists(where: Partial): Promise; +} +/** + * Factory for creating type-safe repositories + */ +export declare class RepositoryFactory { + private connection; + constructor(connection: DatabaseConnection); + /** + * Get Organization repository + */ + getOrganizationRepository(): TypeSafeQueryBuilder; + /** + * Get User repository + */ + getUserRepository(): TypeSafeQueryBuilder; + /** + * Get FeatureFlag repository + */ + getFeatureFlagRepository(): TypeSafeQueryBuilder; + /** + * Get UserFlag repository + */ + getUserFlagRepository(): TypeSafeQueryBuilder; + /** + * Get UserSession repository + */ + getUserSessionRepository(): TypeSafeQueryBuilder; + /** + * Get FlagEvent repository + */ + getFlagEventRepository(): TypeSafeQueryBuilder; +} +/** + * Pagination options with validation + */ +declare const PaginationSchema: z.ZodObject<{ + page: z.ZodDefault; + limit: z.ZodDefault; + sortBy: z.ZodOptional; + sortOrder: z.ZodDefault>; +}, "strip", z.ZodTypeAny, { + page: number; + limit: number; + sortOrder: "ASC" | "DESC"; + sortBy?: string | undefined; +}, { + page?: number | undefined; + limit?: number | undefined; + sortBy?: string | undefined; + sortOrder?: "ASC" | "DESC" | undefined; +}>; +export type PaginationOptions = z.infer; +export interface PaginatedResult { + data: T[]; + pagination: { + page: number; + limit: number; + total: number; + totalPages: number; + hasNext: boolean; + hasPrev: boolean; + }; +} +/** + * Create paginated query + */ +export declare function createPaginatedQuery(queryBuilder: TypeSafeQueryBuilder, options?: Partial): { + execute(where?: Partial, relations?: string[]): Promise>; +}; +/** + * Get or create global database connection + */ +export declare function getDatabase(config?: Partial): DatabaseConnection; +/** + * Initialize global database connection + */ +export declare function initializeDatabase(config?: Partial): Promise; +/** + * Close global database connection + */ +export declare function closeDatabase(): Promise; +/** + * Database-specific error types + */ +export declare class DatabaseError extends Error { + readonly code?: string | undefined; + readonly details?: unknown | undefined; + constructor(message: string, code?: string | undefined, details?: unknown | undefined); +} +export declare class ValidationError extends Error { + readonly field?: string | undefined; + readonly value?: unknown | undefined; + constructor(message: string, field?: string | undefined, value?: unknown | undefined); +} +/** + * Handle database errors with proper typing + */ +export declare function handleDatabaseError(error: unknown): never; +export {}; +//# sourceMappingURL=database.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/database.d.ts.map b/launchdarkly/node/dist/database.d.ts.map new file mode 100644 index 00000000..17ecd7a4 --- /dev/null +++ b/launchdarkly/node/dist/database.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../database.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,YAAY,EACZ,IAAI,EACJ,WAAW,EACX,QAAQ,EACR,WAAW,EACX,SAAS,EAUV,MAAM,eAAe,CAAC;AAIvB;;;GAGG;AAEH,UAAU,iBAAiB;IACzB,IAAI,EAAE,UAAU,GAAG,OAAO,GAAG,QAAQ,GAAG,SAAS,CAAC;IAClD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,QAAQ,EAAE,CAAC;IACrB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,GAAG,CAAC,EAAE,OAAO,GAAG,MAAM,CA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OAAO;gBAFjC,OAAO,EAAE,MAAM,EACC,IAAI,CAAC,EAAE,MAAM,YAAA,EACb,OAAO,CAAC,EAAE,OAAO,YAAA;CAKpC;AAED,qBAAa,eAAgB,SAAQ,KAAK;aAGtB,KAAK,CAAC,EAAE,MAAM;aACd,KAAK,CAAC,EAAE,OAAO;gBAF/B,OAAO,EAAE,MAAM,EACC,KAAK,CAAC,EAAE,MAAM,YAAA,EACd,KAAK,CAAC,EAAE,OAAO,YAAA;CAKlC;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,CAuBzD"} \ No newline at end of file diff --git a/launchdarkly/node/dist/database.js b/launchdarkly/node/dist/database.js new file mode 100644 index 00000000..cc37cd91 --- /dev/null +++ b/launchdarkly/node/dist/database.js @@ -0,0 +1,504 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValidationError = exports.DatabaseError = exports.RepositoryFactory = exports.TypeSafeQueryBuilder = exports.DatabaseConnection = void 0; +exports.createDatabaseConfig = createDatabaseConfig; +exports.createPaginatedQuery = createPaginatedQuery; +exports.getDatabase = getDatabase; +exports.initializeDatabase = initializeDatabase; +exports.closeDatabase = closeDatabase; +exports.handleDatabaseError = handleDatabaseError; +/** + * TypeORM database configuration and connection setup + * with type-safe query builders and connection management + */ +const zod_1 = require("zod"); +const entities_js_1 = require("./entities.js"); +class MockDataSource { + constructor(options) { + this.options = options; + } + async initialize() { + console.log('Mock DataSource initialized'); + return this; + } + async destroy() { + console.log('Mock DataSource destroyed'); + } + getRepository(entityClass) { + return new MockRepository(); + } + createQueryRunner() { + return new MockQueryRunner(); + } + get isInitialized() { + return true; + } +} +class MockRepository { + async find(options) { + console.log('Mock find:', options); + return []; + } + async findOne(options) { + console.log('Mock findOne:', options); + return null; + } + async findOneBy(where) { + console.log('Mock findOneBy:', where); + return null; + } + async save(entity) { + console.log('Mock save:', entity); + return entity; + } + async update(criteria, partialEntity) { + console.log('Mock update:', criteria, partialEntity); + return { affected: 1 }; + } + async delete(criteria) { + console.log('Mock delete:', criteria); + return { affected: 1 }; + } + create(entityData) { + console.log('Mock create:', entityData); + return entityData; + } + async count(options) { + console.log('Mock count:', options); + return 0; + } +} +class MockQueryRunner { + async connect() { + console.log('Mock QueryRunner connected'); + } + async release() { + console.log('Mock QueryRunner released'); + } + async startTransaction() { + console.log('Mock transaction started'); + } + async commitTransaction() { + console.log('Mock transaction committed'); + } + async rollbackTransaction() { + console.log('Mock transaction rolled back'); + } +} +// ===== DATABASE CONFIGURATION ===== +/** + * Database configuration schema with validation + */ +const DatabaseConfigSchema = zod_1.z.object({ + type: zod_1.z.enum(['postgres', 'mysql', 'sqlite', 'mongodb']).default('postgres'), + host: zod_1.z.string().default('localhost'), + port: zod_1.z.number().min(1).max(65535).default(5432), + username: zod_1.z.string().min(1, "Database username is required"), + password: zod_1.z.string().min(1, "Database password is required"), + database: zod_1.z.string().min(1, "Database name is required"), + synchronize: zod_1.z.boolean().default(false), + logging: zod_1.z.boolean().default(false), + ssl: zod_1.z.union([zod_1.z.boolean(), zod_1.z.record(zod_1.z.unknown())]).default(false), + maxConnections: zod_1.z.number().min(1).max(100).default(10), + acquireTimeout: zod_1.z.number().min(1000).default(60000), + timeout: zod_1.z.number().min(1000).default(60000), + migrationsRun: zod_1.z.boolean().default(true) +}); +/** + * Environment-based database configuration + */ +function createDatabaseConfig(env = process.env) { + const config = { + type: env.DB_TYPE || 'postgres', + host: env.DB_HOST || 'localhost', + port: env.DB_PORT ? parseInt(env.DB_PORT, 10) : 5432, + username: env.DB_USERNAME || env.DB_USER || 'postgres', + password: env.DB_PASSWORD || '', + database: env.DB_DATABASE || env.DB_NAME || 'launchdarkly', + synchronize: env.NODE_ENV !== 'production' && env.DB_SYNCHRONIZE !== 'false', + logging: env.DB_LOGGING === 'true' || env.NODE_ENV === 'development', + ssl: env.DB_SSL === 'true' || (env.NODE_ENV === 'production' && env.DB_SSL !== 'false'), + maxConnections: env.DB_MAX_CONNECTIONS ? parseInt(env.DB_MAX_CONNECTIONS, 10) : 10, + acquireTimeout: env.DB_ACQUIRE_TIMEOUT ? parseInt(env.DB_ACQUIRE_TIMEOUT, 10) : 60000, + timeout: env.DB_TIMEOUT ? parseInt(env.DB_TIMEOUT, 10) : 60000, + migrationsRun: env.DB_MIGRATIONS_RUN !== 'false' + }; + return DatabaseConfigSchema.parse(config); +} +/** + * Database connection class with connection pooling and error handling + */ +class DatabaseConnection { + constructor(config) { + this.dataSource = null; + this.config = DatabaseConfigSchema.parse({ + ...createDatabaseConfig(), + ...config + }); + } + /** + * Initialize database connection + */ + async connect() { + if (this.dataSource?.isInitialized) { + return; + } + const dataSourceOptions = { + type: this.config.type, + host: this.config.host, + port: this.config.port, + username: this.config.username, + password: this.config.password, + database: this.config.database, + entities: [entities_js_1.Organization, entities_js_1.User, entities_js_1.FeatureFlag, entities_js_1.UserFlag, entities_js_1.UserSession, entities_js_1.FlagEvent], + synchronize: this.config.synchronize, + logging: this.config.logging, + ssl: this.config.ssl, + migrationsRun: this.config.migrationsRun, + migrations: ['src/migrations/*.ts'] + }; + try { + this.dataSource = new MockDataSource(dataSourceOptions); + await this.dataSource.initialize(); + console.log('Database connected successfully'); + } + catch (error) { + console.error('Database connection failed:', error); + throw new Error(`Failed to connect to database: ${error instanceof Error ? error.message : String(error)}`); + } + } + /** + * Close database connection + */ + async disconnect() { + if (this.dataSource?.isInitialized) { + await this.dataSource.destroy(); + this.dataSource = null; + console.log('Database disconnected successfully'); + } + } + /** + * Get database data source + */ + getDataSource() { + if (!this.dataSource?.isInitialized) { + throw new Error('Database not connected. Call connect() first.'); + } + return this.dataSource; + } + /** + * Get repository for an entity + */ + getRepository(entityClass) { + return this.getDataSource().getRepository(entityClass); + } + /** + * Execute database operations within a transaction + */ + async transaction(callback) { + const queryRunner = this.getDataSource().createQueryRunner(); + try { + await queryRunner.connect(); + await queryRunner.startTransaction(); + const result = await callback(queryRunner); + await queryRunner.commitTransaction(); + return result; + } + catch (error) { + await queryRunner.rollbackTransaction(); + throw error; + } + finally { + await queryRunner.release(); + } + } + /** + * Health check for database connection + */ + async healthCheck() { + if (!this.dataSource?.isInitialized) { + return { healthy: false, error: 'Database not connected' }; + } + try { + const startTime = Date.now(); + // Simple query to check connection + const organizationRepo = this.getRepository(entities_js_1.Organization); + await organizationRepo.count(); + const latency = Date.now() - startTime; + return { healthy: true, latency }; + } + catch (error) { + return { + healthy: false, + error: error instanceof Error ? error.message : String(error) + }; + } + } +} +exports.DatabaseConnection = DatabaseConnection; +// ===== TYPE-SAFE QUERY BUILDERS ===== +/** + * Type-safe query builder for entities + */ +class TypeSafeQueryBuilder { + constructor(repository, entityName) { + this.repository = repository; + this.entityName = entityName; + } + /** + * Find entities with type-safe filters and relations + */ + async find(options = {}) { + const findOptions = { + where: options.where, + relations: options.relations, + order: options.order, + skip: options.skip, + take: options.take, + select: options.select + }; + return this.repository.find(findOptions); + } + /** + * Find one entity with type-safe options + */ + async findOne(options) { + const findOptions = { + where: options.where, + relations: options.relations, + select: options.select + }; + return this.repository.findOne(findOptions); + } + /** + * Find entity by ID with relations + */ + async findById(id, relations) { + return this.repository.findOne({ + where: { id }, + relations + }); + } + /** + * Create new entity + */ + async create(data) { + const entity = this.repository.create(data); + return this.repository.save(entity); + } + /** + * Update entity by ID + */ + async update(id, data) { + const result = await this.repository.update(id, data); + return result.affected > 0; + } + /** + * Delete entity by ID + */ + async delete(id) { + const result = await this.repository.delete(id); + return result.affected > 0; + } + /** + * Count entities with filters + */ + async count(where) { + return this.repository.count({ where }); + } + /** + * Check if entity exists + */ + async exists(where) { + const count = await this.repository.count({ where }); + return count > 0; + } +} +exports.TypeSafeQueryBuilder = TypeSafeQueryBuilder; +// ===== REPOSITORY FACTORY ===== +/** + * Factory for creating type-safe repositories + */ +class RepositoryFactory { + constructor(connection) { + this.connection = connection; + } + /** + * Get Organization repository + */ + getOrganizationRepository() { + const repo = this.connection.getRepository(entities_js_1.Organization); + return new TypeSafeQueryBuilder(repo, 'Organization'); + } + /** + * Get User repository + */ + getUserRepository() { + const repo = this.connection.getRepository(entities_js_1.User); + return new TypeSafeQueryBuilder(repo, 'User'); + } + /** + * Get FeatureFlag repository + */ + getFeatureFlagRepository() { + const repo = this.connection.getRepository(entities_js_1.FeatureFlag); + return new TypeSafeQueryBuilder(repo, 'FeatureFlag'); + } + /** + * Get UserFlag repository + */ + getUserFlagRepository() { + const repo = this.connection.getRepository(entities_js_1.UserFlag); + return new TypeSafeQueryBuilder(repo, 'UserFlag'); + } + /** + * Get UserSession repository + */ + getUserSessionRepository() { + const repo = this.connection.getRepository(entities_js_1.UserSession); + return new TypeSafeQueryBuilder(repo, 'UserSession'); + } + /** + * Get FlagEvent repository + */ + getFlagEventRepository() { + const repo = this.connection.getRepository(entities_js_1.FlagEvent); + return new TypeSafeQueryBuilder(repo, 'FlagEvent'); + } +} +exports.RepositoryFactory = RepositoryFactory; +// ===== PAGINATION UTILITIES ===== +/** + * Pagination options with validation + */ +const PaginationSchema = zod_1.z.object({ + page: zod_1.z.number().min(1).default(1), + limit: zod_1.z.number().min(1).max(1000).default(20), + sortBy: zod_1.z.string().optional(), + sortOrder: zod_1.z.enum(['ASC', 'DESC']).default('ASC') +}); +/** + * Create paginated query + */ +function createPaginatedQuery(queryBuilder, options = {}) { + const paginationOptions = PaginationSchema.parse(options); + return { + async execute(where, relations) { + const skip = (paginationOptions.page - 1) * paginationOptions.limit; + const take = paginationOptions.limit; + const order = paginationOptions.sortBy ? { + [paginationOptions.sortBy]: paginationOptions.sortOrder + } : undefined; + const [data, total] = await Promise.all([ + queryBuilder.find({ + where, + relations, + order, + skip, + take + }), + queryBuilder.count(where) + ]); + const totalPages = Math.ceil(total / paginationOptions.limit); + return { + data, + pagination: { + page: paginationOptions.page, + limit: paginationOptions.limit, + total, + totalPages, + hasNext: paginationOptions.page < totalPages, + hasPrev: paginationOptions.page > 1 + } + }; + } + }; +} +// ===== GLOBAL DATABASE INSTANCE ===== +let globalDatabaseConnection = null; +/** + * Get or create global database connection + */ +function getDatabase(config) { + if (!globalDatabaseConnection) { + globalDatabaseConnection = new DatabaseConnection(config); + } + return globalDatabaseConnection; +} +/** + * Initialize global database connection + */ +async function initializeDatabase(config) { + const db = getDatabase(config); + await db.connect(); + return db; +} +/** + * Close global database connection + */ +async function closeDatabase() { + if (globalDatabaseConnection) { + await globalDatabaseConnection.disconnect(); + globalDatabaseConnection = null; + } +} +// ===== ERROR HANDLING ===== +/** + * Database-specific error types + */ +class DatabaseError extends Error { + constructor(message, code, details) { + super(message); + this.code = code; + this.details = details; + this.name = 'DatabaseError'; + } +} +exports.DatabaseError = DatabaseError; +class ValidationError extends Error { + constructor(message, field, value) { + super(message); + this.field = field; + this.value = value; + this.name = 'ValidationError'; + } +} +exports.ValidationError = ValidationError; +/** + * Handle database errors with proper typing + */ +function handleDatabaseError(error) { + if (error instanceof DatabaseError) { + throw error; + } + if (error instanceof Error) { + // Map common database errors + if (error.message.includes('duplicate key')) { + throw new DatabaseError('Duplicate entry found', 'DUPLICATE_ENTRY', error); + } + if (error.message.includes('foreign key')) { + throw new DatabaseError('Foreign key constraint violation', 'FOREIGN_KEY_VIOLATION', error); + } + if (error.message.includes('not null')) { + throw new DatabaseError('Required field is missing', 'NOT_NULL_VIOLATION', error); + } + throw new DatabaseError(error.message, 'UNKNOWN_ERROR', error); + } + throw new DatabaseError('Unknown database error occurred', 'UNKNOWN_ERROR', error); +} +//# sourceMappingURL=database.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/database.js.map b/launchdarkly/node/dist/database.js.map new file mode 100644 index 00000000..db952d06 --- /dev/null +++ b/launchdarkly/node/dist/database.js.map @@ -0,0 +1 @@ +{"version":3,"file":"database.js","sourceRoot":"","sources":["../database.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAqMH,oDAkBC;AAwTD,oDAyCC;AASD,kCAKC;AAKD,gDAIC;AAKD,sCAKC;AAgCD,kDAuBC;AA9oBD;;;GAGG;AAEH,6BAAwB;AACxB,+CAgBuB;AA0DvB,MAAM,cAAc;IAClB,YAAoB,OAA0B;QAA1B,YAAO,GAAP,OAAO,CAAmB;IAAG,CAAC;IAElD,KAAK,CAAC,UAAU;QACd,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;QAC3C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,OAAO;QACX,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IAC3C,CAAC;IAED,aAAa,CAAS,WAAqB;QACzC,OAAO,IAAI,cAAc,EAAU,CAAC;IACtC,CAAC;IAED,iBAAiB;QACf,OAAO,IAAI,eAAe,EAAE,CAAC;IAC/B,CAAC;IAED,IAAI,aAAa;QACf,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAED,MAAM,cAAc;IAClB,KAAK,CAAC,IAAI,CAAC,OAAiC;QAC1C,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;QACnC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,OAAgC;QAC5C,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,KAAsB;QACpC,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,MAAuB;QAChC,OAAO,CA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,KAAK,CAAC,CAAC;QAC7E,CAAC;QAED,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,aAAa,CAAC,kCAAkC,EAAE,uBAAuB,EAAE,KAAK,CAAC,CAAC;QAC9F,CAAC;QAED,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;YACvC,MAAM,IAAI,aAAa,CAAC,2BAA2B,EAAE,oBAAoB,EAAE,KAAK,CAAC,CAAC;QACpF,CAAC;QAED,MAAM,IAAI,aAAa,CAAC,KAAK,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,CAAC,CAAC;IACjE,CAAC;IAED,MAAM,IAAI,aAAa,CAAC,iCAAiC,EAAE,eAAe,EAAE,KAAK,CAAC,CAAC;AACrF,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/entities.d.ts b/launchdarkly/node/dist/entities.d.ts new file mode 100644 index 00000000..9aef2f8a --- /dev/null +++ b/launchdarkly/node/dist/entities.d.ts @@ -0,0 +1,450 @@ +/** + * Type-safe database entity definitions using TypeORM decorators + * with proper utility types for create/update input types. + */ +import { z } from "zod"; +/** + * Omit specific fields for create operations + */ +type CreateInput = Omit; +/** + * Extract only the fields that can be updated (excludes readonly fields) + */ +type UpdatableFields = Omit; +/** + * Partial update input with only updatable fields + */ +type PartialUpdateInput = Partial> & { + id: string; +}; +type BrandedString = string & { + readonly __brand: T; +}; +type UserId = BrandedString<'UserId'>; +type FlagKey = BrandedString<'FlagKey'>; +type OrganizationId = BrandedString<'OrganizationId'>; +type SessionId = BrandedString<'SessionId'>; +type EnvironmentKey = BrandedString<'EnvironmentKey'>; +/** + * Organization entity for multi-tenant support + */ +export declare class Organization { + id: OrganizationId; + name: string; + description?: string; + domain?: string; + settings?: Record; + isActive: boolean; + createdAt: Date; + updatedAt: Date; + users: User[]; + featureFlags: FeatureFlag[]; +} +/** + * User entity extending LaunchDarkly context + */ +export declare class User { + id: UserId; + key: string; + name: string; + email?: string; + kind: 'user' | 'organization' | 'device'; + custom?: Record; + organizationId?: OrganizationId; + isActive: boolean; + lastLoginAt?: Date; + createdAt: Date; + updatedAt: Date; + organization?: Organization; + userFlags: UserFlag[]; + sessions: UserSession[]; +} +/** + * Feature flag entity for flag management + */ +export declare class FeatureFlag { + id: string; + key: FlagKey; + name: string; + description?: string; + valueType: 'boolean' | 'string' | 'number' | 'json'; + defaultValue: boolean | string | number | Record; + variations?: Array<{ + value: boolean | string | number | Record; + name: string; + description?: string; + }>; + targeting?: { + rules?: Array<{ + clauses: Array<{ + attribute: string; + op: string; + values: unknown[]; + }>; + variation: number; + }>; + fallthrough?: { + variation: number; + }; + }; + isEnabled: boolean; + isArchived: boolean; + category?: string; + tags?: string[]; + organizationId?: OrganizationId; + environment: EnvironmentKey; + createdAt: Date; + updatedAt: Date; + organization?: Organization; + userFlags: UserFlag[]; + events: FlagEvent[]; +} +/** + * User-specific flag overrides + */ +export declare class UserFlag { + id: string; + userId: UserId; + featureFlagId: string; + value: boolean | string | number | Record; + reason?: string; + isActive: boolean; + expiresAt?: Date; + createdAt: Date; + updatedAt: Date; + user: User; + featureFlag: FeatureFlag; + static userFlagIndex: string[]; +} +/** + * User session tracking + */ +export declare class UserSession { + id: SessionId; + userId: UserId; + deviceId?: string; + userAgent?: string; + ipAddress?: string; + context?: Record; + isActive: boolean; + lastActivityAt?: Date; + expiresAt?: Date; + createdAt: Date; + updatedAt: Date; + user: User; +} +/** + * Feature flag event tracking + */ +export declare class FlagEvent { + id: string; + featureFlagId: string; + userId?: UserId; + eventType: 'evaluation' | 'update' | 'create' | 'delete' | 'toggle'; + previousValue?: unknown; + newValue?: unknown; + context?: Record; + reason?: string; + source?: string; + createdAt: Date; + featureFlag: FeatureFlag; + user?: User; +} +/** + * Create input types for each entity + */ +export type CreateOrganizationInput = CreateInput; +export type CreateUserInput = CreateInput; +export type CreateFeatureFlagInput = CreateInput; +export type CreateUserFlagInput = CreateInput; +export type CreateUserSessionInput = CreateInput; +export type CreateFlagEventInput = CreateInput; +/** + * Update input types for each entity + */ +export type UpdateOrganizationInput = PartialUpdateInput; +export type UpdateUserInput = PartialUpdateInput; +export type UpdateFeatureFlagInput = PartialUpdateInput; +export type UpdateUserFlagInput = PartialUpdateInput; +export type UpdateUserSessionInput = PartialUpdateInput; +/** + * Query filter types for type-safe queries + */ +export interface OrganizationFilters { + name?: string; + domain?: string; + isActive?: boolean; +} +export interface UserFilters { + organizationId?: OrganizationId; + email?: string; + kind?: 'user' | 'organization' | 'device'; + isActive?: boolean; +} +export interface FeatureFlagFilters { + organizationId?: OrganizationId; + environment?: EnvironmentKey; + category?: string; + tags?: string[]; + isEnabled?: boolean; + isArchived?: boolean; +} +export interface UserFlagFilters { + userId?: UserId; + featureFlagId?: string; + isActive?: boolean; +} +/** + * Relation loading options for type-safe eager loading + */ +export interface EntityRelations { + Organization: { + users?: boolean; + featureFlags?: boolean; + }; + User: { + organization?: boolean; + userFlags?: boolean; + sessions?: boolean; + }; + FeatureFlag: { + organization?: boolean; + userFlags?: boolean; + events?: boolean; + }; + UserFlag: { + user?: boolean; + featureFlag?: boolean; + }; +} +/** + * Zod schemas for runtime validation + */ +export declare const EntityValidationSchemas: { + readonly Organization: z.ZodObject<{ + name: z.ZodString; + description: z.ZodOptional; + domain: z.ZodOptional; + settings: z.ZodOptional>; + isActive: z.ZodDefault; + }, "strip", z.ZodTypeAny, { + name: string; + isActive: boolean; + description?: string | undefined; + domain?: string | undefined; + settings?: Record | undefined; + }, { + name: string; + description?: string | undefined; + domain?: string | undefined; + settings?: Record | undefined; + isActive?: boolean | undefined; + }>; + readonly User: z.ZodObject<{ + key: z.ZodString; + name: z.ZodString; + email: z.ZodOptional; + kind: z.ZodDefault>; + custom: z.ZodOptional>>; + organizationId: z.ZodOptional; + isActive: z.ZodDefault; + }, "strip", z.ZodTypeAny, { + name: string; + isActive: boolean; + key: string; + kind: "user" | "organization" | "device"; + email?: string | undefined; + custom?: Record | undefined; + organizationId?: string | undefined; + }, { + name: string; + key: string; + isActive?: boolean | undefined; + email?: string | undefined; + kind?: "user" | "organization" | "device" | undefined; + custom?: Record | undefined; + organizationId?: string | undefined; + }>; + readonly FeatureFlag: z.ZodObject<{ + key: z.ZodString; + name: z.ZodString; + description: z.ZodOptional; + valueType: z.ZodDefault>; + defaultValue: z.ZodUnknown; + variations: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name: string; + description?: string | undefined; + value?: unknown; + }, { + name: string; + description?: string | undefined; + value?: unknown; + }>, "many">>; + targeting: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + values: unknown[]; + attribute: string; + op: string; + }, { + values: unknown[]; + attribute: string; + op: string; + }>, "many">; + variation: z.ZodNumber; + }, "strip", z.ZodTypeAny, { + clauses: { + values: unknown[]; + attribute: string; + op: string; + }[]; + variation: number; + }, { + clauses: { + values: unknown[]; + attribute: string; + op: string; + }[]; + variation: number; + }>, "many">>; + fallthrough: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + rules?: { + clauses: { + values: unknown[]; + attribute: string; + op: string; + }[]; + variation: number; + }[] | undefined; + fallthrough?: { + variation: number; + } | undefined; + }, { + rules?: { + clauses: { + values: unknown[]; + attribute: string; + op: string; + }[]; + variation: number; + }[] | undefined; + fallthrough?: { + variation: number; + } | undefined; + }>>; + isEnabled: z.ZodDefault; + isArchived: z.ZodDefault; + category: z.ZodOptional; + tags: z.ZodOptional>; + organizationId: z.ZodOptional; + environment: z.ZodDefault; + }, "strip", z.ZodTypeAny, { + name: string; + key: string; + valueType: "string" | "number" | "boolean" | "json"; + isEnabled: boolean; + isArchived: boolean; + environment: string; + description?: string | undefined; + organizationId?: string | undefined; + defaultValue?: unknown; + variations?: { + name: string; + description?: string | undefined; + value?: unknown; + }[] | undefined; + targeting?: { + rules?: { + clauses: { + values: unknown[]; + attribute: string; + op: string; + }[]; + variation: number; + }[] | undefined; + fallthrough?: { + variation: number; + } | undefined; + } | undefined; + category?: string | undefined; + tags?: string[] | undefined; + }, { + name: string; + key: string; + description?: string | undefined; + organizationId?: string | undefined; + valueType?: "string" | "number" | "boolean" | "json" | undefined; + defaultValue?: unknown; + variations?: { + name: string; + description?: string | undefined; + value?: unknown; + }[] | undefined; + targeting?: { + rules?: { + clauses: { + values: unknown[]; + attribute: string; + op: string; + }[]; + variation: number; + }[] | undefined; + fallthrough?: { + variation: number; + } | undefined; + } | undefined; + isEnabled?: boolean | undefined; + isArchived?: boolean | undefined; + category?: string | undefined; + tags?: string[] | undefined; + environment?: string | undefined; + }>; + readonly UserFlag: z.ZodObject<{ + userId: z.ZodString; + featureFlagId: z.ZodString; + value: z.ZodUnknown; + reason: z.ZodOptional; + isActive: z.ZodDefault; + expiresAt: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + userId: string; + featureFlagId: string; + isActive: boolean; + value?: unknown; + reason?: string | undefined; + expiresAt?: Date | undefined; + }, { + userId: string; + featureFlagId: string; + value?: unknown; + isActive?: boolean | undefined; + reason?: string | undefined; + expiresAt?: Date | undefined; + }>; +}; +/** + * Type-safe entity validation functions + */ +export declare const validateEntity: { + readonly organization: (data: unknown) => CreateOrganizationInput; + readonly user: (data: unknown) => CreateUserInput; + readonly featureFlag: (data: unknown) => CreateFeatureFlagInput; + readonly userFlag: (data: unknown) => CreateUserFlagInput; +}; +export {}; +//# sourceMappingURL=entities.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/entities.d.ts.map b/launchdarkly/node/dist/entities.d.ts.map new file mode 100644 index 00000000..259580f0 --- /dev/null +++ b/launchdarkly/node/dist/entities.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"entities.d.ts","sourceRoot":"","sources":["../entities.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB;;GAEG;AACH,KAAK,WAAW,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,IAAI,GAAG,WAAW,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C,EAAE,OAAO,CAAC;KACpB,CAAC;IACF,WAAW,EAAE;QACX,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,MAAM,CAAC,EAAE,OAAO,CAAC;KAClB,CAAC;IACF,QAAQ,EAAE;QACR,IAAI,CAAC,EAAE,OAAO,CAAC;QACf,WAAW,CAAC,EAAE,OAAO,CAAC;KACvB,CAAC;CACH;AAID;;GAEG;AACH,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8D1B,CAAC;AAEX;;GAEG;AACH,eAAO,MAAM,cAAc;kCACJ,OAAO,KAAG,uBAAuB;0BAIzC,OAAO,KAAG,eAAe;iCAIlB,OAAO,KAAG,sBAAsB;8BAInC,OAAO,KAAG,mBAAmB;CAGtC,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/entities.js b/launchdarkly/node/dist/entities.js new file mode 100644 index 00000000..92495e41 --- /dev/null +++ b/launchdarkly/node/dist/entities.js @@ -0,0 +1,854 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateEntity = exports.EntityValidationSchemas = exports.FlagEvent = exports.UserSession = exports.UserFlag = exports.FeatureFlag = exports.User = exports.Organization = void 0; +/** + * Type-safe database entity definitions using TypeORM decorators + * with proper utility types for create/update input types. + */ +const zod_1 = require("zod"); +// ===== MOCK TYPEORM DECORATORS (since TypeORM is not installed) ===== +/** + * Mock TypeORM decorators for demonstration purposes + * In actual implementation, these would be imported from 'typeorm' + */ +// Entity decorator +function Entity(name) { + return function (target) { + target.__entityName = name || target.name; + return target; + }; +} +// Primary key decorator +function PrimaryColumn(options) { + return function (target, propertyKey) { + target.__primaryKey = propertyKey; + }; +} +// Column decorator +function Column(options) { + return function (target, propertyKey) { + if (!target.__columns) + target.__columns = []; + target.__columns.push({ property: propertyKey, options }); + }; +} +// Index decorator +function Index(name, options) { + return function (target, propertyKey) { + if (!target.__indexes) + target.__indexes = []; + target.__indexes.push({ property: propertyKey, name, options }); + }; +} +// Relation decorators +function ManyToOne(type, options) { + return function (target, propertyKey) { + if (!target.__relations) + target.__relations = []; + target.__relations.push({ type: 'many-to-one', property: propertyKey, target: type, options }); + }; +} +function OneToMany(type, inverseSide) { + return function (target, propertyKey) { + if (!target.__relations) + target.__relations = []; + target.__relations.push({ type: 'one-to-many', property: propertyKey, target: type, inverseSide }); + }; +} +function ManyToMany(type, options) { + return function (target, propertyKey) { + if (!target.__relations) + target.__relations = []; + target.__relations.push({ type: 'many-to-many', property: propertyKey, target: type, options }); + }; +} +function JoinTable(options) { + return function (target, propertyKey) { + if (!target.__joinTables) + target.__joinTables = []; + target.__joinTables.push({ property: propertyKey, options }); + }; +} +function JoinColumn(options) { + return function (target, propertyKey) { + if (!target.__joinColumns) + target.__joinColumns = []; + target.__joinColumns.push({ property: propertyKey, options }); + }; +} +// Timestamp decorators +function CreateDateColumn() { + return function (target, propertyKey) { + if (!target.__timestamps) + target.__timestamps = []; + target.__timestamps.push({ property: propertyKey, type: 'create' }); + }; +} +function UpdateDateColumn() { + return function (target, propertyKey) { + if (!target.__timestamps) + target.__timestamps = []; + target.__timestamps.push({ property: propertyKey, type: 'update' }); + }; +} +// ===== ENTITY DEFINITIONS ===== +/** + * Organization entity for multi-tenant support + */ +let Organization = (() => { + let _classDecorators = [Entity('organizations')]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + let _id_decorators; + let _id_initializers = []; + let _id_extraInitializers = []; + let _name_decorators; + let _name_initializers = []; + let _name_extraInitializers = []; + let _description_decorators; + let _description_initializers = []; + let _description_extraInitializers = []; + let _domain_decorators; + let _domain_initializers = []; + let _domain_extraInitializers = []; + let _settings_decorators; + let _settings_initializers = []; + let _settings_extraInitializers = []; + let _isActive_decorators; + let _isActive_initializers = []; + let _isActive_extraInitializers = []; + let _createdAt_decorators; + let _createdAt_initializers = []; + let _createdAt_extraInitializers = []; + let _updatedAt_decorators; + let _updatedAt_initializers = []; + let _updatedAt_extraInitializers = []; + let _users_decorators; + let _users_initializers = []; + let _users_extraInitializers = []; + let _featureFlags_decorators; + let _featureFlags_initializers = []; + let _featureFlags_extraInitializers = []; + var Organization = _classThis = class { + constructor() { + this.id = __runInitializers(this, _id_initializers, void 0); + this.name = (__runInitializers(this, _id_extraInitializers), __runInitializers(this, _name_initializers, void 0)); + this.description = (__runInitializers(this, _name_extraInitializers), __runInitializers(this, _description_initializers, void 0)); + this.domain = (__runInitializers(this, _description_extraInitializers), __runInitializers(this, _domain_initializers, void 0)); + this.settings = (__runInitializers(this, _domain_extraInitializers), __runInitializers(this, _settings_initializers, void 0)); + this.isActive = (__runInitializers(this, _settings_extraInitializers), __runInitializers(this, _isActive_initializers, void 0)); + this.createdAt = (__runInitializers(this, _isActive_extraInitializers), __runInitializers(this, _createdAt_initializers, void 0)); + this.updatedAt = (__runInitializers(this, _createdAt_extraInitializers), __runInitializers(this, _updatedAt_initializers, void 0)); + // Relations + this.users = (__runInitializers(this, _updatedAt_extraInitializers), __runInitializers(this, _users_initializers, void 0)); + this.featureFlags = (__runInitializers(this, _users_extraInitializers), __runInitializers(this, _featureFlags_initializers, void 0)); + __runInitializers(this, _featureFlags_extraInitializers); + } + }; + __setFunctionName(_classThis, "Organization"); + (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [PrimaryColumn({ type: 'varchar', generated: true })]; + _name_decorators = [Column({ type: 'varchar', length: 255, nullable: false }), Index('idx_organization_name', { unique: true })]; + _description_decorators = [Column({ type: 'varchar', length: 500, nullable: true })]; + _domain_decorators = [Column({ type: 'varchar', length: 255, nullable: true })]; + _settings_decorators = [Column({ type: 'json', nullable: true })]; + _isActive_decorators = [Column({ type: 'boolean', default: true })]; + _createdAt_decorators = [CreateDateColumn()]; + _updatedAt_decorators = [UpdateDateColumn()]; + _users_decorators = [OneToMany(() => User, user => user.organization)]; + _featureFlags_decorators = [OneToMany(() => FeatureFlag, flag => flag.organization)]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: obj => "id" in obj, get: obj => obj.id, set: (obj, value) => { obj.id = value; } }, metadata: _metadata }, _id_initializers, _id_extraInitializers); + __esDecorate(null, null, _name_decorators, { kind: "field", name: "name", static: false, private: false, access: { has: obj => "name" in obj, get: obj => obj.name, set: (obj, value) => { obj.name = value; } }, metadata: _metadata }, _name_initializers, _name_extraInitializers); + __esDecorate(null, null, _description_decorators, { kind: "field", name: "description", static: false, private: false, access: { has: obj => "description" in obj, get: obj => obj.description, set: (obj, value) => { obj.description = value; } }, metadata: _metadata }, _description_initializers, _description_extraInitializers); + __esDecorate(null, null, _domain_decorators, { kind: "field", name: "domain", static: false, private: false, access: { has: obj => "domain" in obj, get: obj => obj.domain, set: (obj, value) => { obj.domain = value; } }, metadata: _metadata }, _domain_initializers, _domain_extraInitializers); + __esDecorate(null, null, _settings_decorators, { kind: "field", name: "settings", static: false, private: false, access: { has: obj => "settings" in obj, get: obj => obj.settings, set: (obj, value) => { obj.settings = value; } }, metadata: _metadata }, _settings_initializers, _settings_extraInitializers); + __esDecorate(null, null, _isActive_decorators, { kind: "field", name: "isActive", static: false, private: false, access: { has: obj => "isActive" in obj, get: obj => obj.isActive, set: (obj, value) => { obj.isActive = value; } }, metadata: _metadata }, _isActive_initializers, _isActive_extraInitializers); + __esDecorate(null, null, _createdAt_decorators, { kind: "field", name: "createdAt", static: false, private: false, access: { has: obj => "createdAt" in obj, get: obj => obj.createdAt, set: (obj, value) => { obj.createdAt = value; } }, metadata: _metadata }, _createdAt_initializers, _createdAt_extraInitializers); + __esDecorate(null, null, _updatedAt_decorators, { kind: "field", name: "updatedAt", static: false, private: false, access: { has: obj => "updatedAt" in obj, get: obj => obj.updatedAt, set: (obj, value) => { obj.updatedAt = value; } }, metadata: _metadata }, _updatedAt_initializers, _updatedAt_extraInitializers); + __esDecorate(null, null, _users_decorators, { kind: "field", name: "users", static: false, private: false, access: { has: obj => "users" in obj, get: obj => obj.users, set: (obj, value) => { obj.users = value; } }, metadata: _metadata }, _users_initializers, _users_extraInitializers); + __esDecorate(null, null, _featureFlags_decorators, { kind: "field", name: "featureFlags", static: false, private: false, access: { has: obj => "featureFlags" in obj, get: obj => obj.featureFlags, set: (obj, value) => { obj.featureFlags = value; } }, metadata: _metadata }, _featureFlags_initializers, _featureFlags_extraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + Organization = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return Organization = _classThis; +})(); +exports.Organization = Organization; +/** + * User entity extending LaunchDarkly context + */ +let User = (() => { + let _classDecorators = [Entity('users')]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + let _id_decorators; + let _id_initializers = []; + let _id_extraInitializers = []; + let _key_decorators; + let _key_initializers = []; + let _key_extraInitializers = []; + let _name_decorators; + let _name_initializers = []; + let _name_extraInitializers = []; + let _email_decorators; + let _email_initializers = []; + let _email_extraInitializers = []; + let _kind_decorators; + let _kind_initializers = []; + let _kind_extraInitializers = []; + let _custom_decorators; + let _custom_initializers = []; + let _custom_extraInitializers = []; + let _organizationId_decorators; + let _organizationId_initializers = []; + let _organizationId_extraInitializers = []; + let _isActive_decorators; + let _isActive_initializers = []; + let _isActive_extraInitializers = []; + let _lastLoginAt_decorators; + let _lastLoginAt_initializers = []; + let _lastLoginAt_extraInitializers = []; + let _createdAt_decorators; + let _createdAt_initializers = []; + let _createdAt_extraInitializers = []; + let _updatedAt_decorators; + let _updatedAt_initializers = []; + let _updatedAt_extraInitializers = []; + let _organization_decorators; + let _organization_initializers = []; + let _organization_extraInitializers = []; + let _userFlags_decorators; + let _userFlags_initializers = []; + let _userFlags_extraInitializers = []; + let _sessions_decorators; + let _sessions_initializers = []; + let _sessions_extraInitializers = []; + var User = _classThis = class { + constructor() { + this.id = __runInitializers(this, _id_initializers, void 0); + this.key = (__runInitializers(this, _id_extraInitializers), __runInitializers(this, _key_initializers, void 0)); + this.name = (__runInitializers(this, _key_extraInitializers), __runInitializers(this, _name_initializers, void 0)); + this.email = (__runInitializers(this, _name_extraInitializers), __runInitializers(this, _email_initializers, void 0)); + this.kind = (__runInitializers(this, _email_extraInitializers), __runInitializers(this, _kind_initializers, void 0)); + this.custom = (__runInitializers(this, _kind_extraInitializers), __runInitializers(this, _custom_initializers, void 0)); + this.organizationId = (__runInitializers(this, _custom_extraInitializers), __runInitializers(this, _organizationId_initializers, void 0)); + this.isActive = (__runInitializers(this, _organizationId_extraInitializers), __runInitializers(this, _isActive_initializers, void 0)); + this.lastLoginAt = (__runInitializers(this, _isActive_extraInitializers), __runInitializers(this, _lastLoginAt_initializers, void 0)); + this.createdAt = (__runInitializers(this, _lastLoginAt_extraInitializers), __runInitializers(this, _createdAt_initializers, void 0)); + this.updatedAt = (__runInitializers(this, _createdAt_extraInitializers), __runInitializers(this, _updatedAt_initializers, void 0)); + // Relations + this.organization = (__runInitializers(this, _updatedAt_extraInitializers), __runInitializers(this, _organization_initializers, void 0)); + this.userFlags = (__runInitializers(this, _organization_extraInitializers), __runInitializers(this, _userFlags_initializers, void 0)); + this.sessions = (__runInitializers(this, _userFlags_extraInitializers), __runInitializers(this, _sessions_initializers, void 0)); + __runInitializers(this, _sessions_extraInitializers); + } + }; + __setFunctionName(_classThis, "User"); + (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [PrimaryColumn({ type: 'varchar', generated: true })]; + _key_decorators = [Column({ type: 'varchar', length: 255, nullable: false }), Index('idx_user_key', { unique: true })]; + _name_decorators = [Column({ type: 'varchar', length: 255, nullable: false })]; + _email_decorators = [Column({ type: 'varchar', length: 255, nullable: true }), Index('idx_user_email')]; + _kind_decorators = [Column({ type: 'enum', enum: ['user', 'organization', 'device'], default: 'user' })]; + _custom_decorators = [Column({ type: 'json', nullable: true })]; + _organizationId_decorators = [Column({ type: 'varchar', length: 255, nullable: true }), JoinColumn({ name: 'organization_id' })]; + _isActive_decorators = [Column({ type: 'boolean', default: true })]; + _lastLoginAt_decorators = [Column({ type: 'timestamp', nullable: true })]; + _createdAt_decorators = [CreateDateColumn()]; + _updatedAt_decorators = [UpdateDateColumn()]; + _organization_decorators = [ManyToOne(() => Organization, organization => organization.users, { onDelete: 'SET NULL' }), JoinColumn({ name: 'organization_id' })]; + _userFlags_decorators = [OneToMany(() => UserFlag, userFlag => userFlag.user)]; + _sessions_decorators = [OneToMany(() => UserSession, session => session.user)]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: obj => "id" in obj, get: obj => obj.id, set: (obj, value) => { obj.id = value; } }, metadata: _metadata }, _id_initializers, _id_extraInitializers); + __esDecorate(null, null, _key_decorators, { kind: "field", name: "key", static: false, private: false, access: { has: obj => "key" in obj, get: obj => obj.key, set: (obj, value) => { obj.key = value; } }, metadata: _metadata }, _key_initializers, _key_extraInitializers); + __esDecorate(null, null, _name_decorators, { kind: "field", name: "name", static: false, private: false, access: { has: obj => "name" in obj, get: obj => obj.name, set: (obj, value) => { obj.name = value; } }, metadata: _metadata }, _name_initializers, _name_extraInitializers); + __esDecorate(null, null, _email_decorators, { kind: "field", name: "email", static: false, private: false, access: { has: obj => "email" in obj, get: obj => obj.email, set: (obj, value) => { obj.email = value; } }, metadata: _metadata }, _email_initializers, _email_extraInitializers); + __esDecorate(null, null, _kind_decorators, { kind: "field", name: "kind", static: false, private: false, access: { has: obj => "kind" in obj, get: obj => obj.kind, set: (obj, value) => { obj.kind = value; } }, metadata: _metadata }, _kind_initializers, _kind_extraInitializers); + __esDecorate(null, null, _custom_decorators, { kind: "field", name: "custom", static: false, private: false, access: { has: obj => "custom" in obj, get: obj => obj.custom, set: (obj, value) => { obj.custom = value; } }, metadata: _metadata }, _custom_initializers, _custom_extraInitializers); + __esDecorate(null, null, _organizationId_decorators, { kind: "field", name: "organizationId", static: false, private: false, access: { has: obj => "organizationId" in obj, get: obj => obj.organizationId, set: (obj, value) => { obj.organizationId = value; } }, metadata: _metadata }, _organizationId_initializers, _organizationId_extraInitializers); + __esDecorate(null, null, _isActive_decorators, { kind: "field", name: "isActive", static: false, private: false, access: { has: obj => "isActive" in obj, get: obj => obj.isActive, set: (obj, value) => { obj.isActive = value; } }, metadata: _metadata }, _isActive_initializers, _isActive_extraInitializers); + __esDecorate(null, null, _lastLoginAt_decorators, { kind: "field", name: "lastLoginAt", static: false, private: false, access: { has: obj => "lastLoginAt" in obj, get: obj => obj.lastLoginAt, set: (obj, value) => { obj.lastLoginAt = value; } }, metadata: _metadata }, _lastLoginAt_initializers, _lastLoginAt_extraInitializers); + __esDecorate(null, null, _createdAt_decorators, { kind: "field", name: "createdAt", static: false, private: false, access: { has: obj => "createdAt" in obj, get: obj => obj.createdAt, set: (obj, value) => { obj.createdAt = value; } }, metadata: _metadata }, _createdAt_initializers, _createdAt_extraInitializers); + __esDecorate(null, null, _updatedAt_decorators, { kind: "field", name: "updatedAt", static: false, private: false, access: { has: obj => "updatedAt" in obj, get: obj => obj.updatedAt, set: (obj, value) => { obj.updatedAt = value; } }, metadata: _metadata }, _updatedAt_initializers, _updatedAt_extraInitializers); + __esDecorate(null, null, _organization_decorators, { kind: "field", name: "organization", static: false, private: false, access: { has: obj => "organization" in obj, get: obj => obj.organization, set: (obj, value) => { obj.organization = value; } }, metadata: _metadata }, _organization_initializers, _organization_extraInitializers); + __esDecorate(null, null, _userFlags_decorators, { kind: "field", name: "userFlags", static: false, private: false, access: { has: obj => "userFlags" in obj, get: obj => obj.userFlags, set: (obj, value) => { obj.userFlags = value; } }, metadata: _metadata }, _userFlags_initializers, _userFlags_extraInitializers); + __esDecorate(null, null, _sessions_decorators, { kind: "field", name: "sessions", static: false, private: false, access: { has: obj => "sessions" in obj, get: obj => obj.sessions, set: (obj, value) => { obj.sessions = value; } }, metadata: _metadata }, _sessions_initializers, _sessions_extraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + User = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return User = _classThis; +})(); +exports.User = User; +/** + * Feature flag entity for flag management + */ +let FeatureFlag = (() => { + let _classDecorators = [Entity('feature_flags')]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + let _id_decorators; + let _id_initializers = []; + let _id_extraInitializers = []; + let _key_decorators; + let _key_initializers = []; + let _key_extraInitializers = []; + let _name_decorators; + let _name_initializers = []; + let _name_extraInitializers = []; + let _description_decorators; + let _description_initializers = []; + let _description_extraInitializers = []; + let _valueType_decorators; + let _valueType_initializers = []; + let _valueType_extraInitializers = []; + let _defaultValue_decorators; + let _defaultValue_initializers = []; + let _defaultValue_extraInitializers = []; + let _variations_decorators; + let _variations_initializers = []; + let _variations_extraInitializers = []; + let _targeting_decorators; + let _targeting_initializers = []; + let _targeting_extraInitializers = []; + let _isEnabled_decorators; + let _isEnabled_initializers = []; + let _isEnabled_extraInitializers = []; + let _isArchived_decorators; + let _isArchived_initializers = []; + let _isArchived_extraInitializers = []; + let _category_decorators; + let _category_initializers = []; + let _category_extraInitializers = []; + let _tags_decorators; + let _tags_initializers = []; + let _tags_extraInitializers = []; + let _organizationId_decorators; + let _organizationId_initializers = []; + let _organizationId_extraInitializers = []; + let _environment_decorators; + let _environment_initializers = []; + let _environment_extraInitializers = []; + let _createdAt_decorators; + let _createdAt_initializers = []; + let _createdAt_extraInitializers = []; + let _updatedAt_decorators; + let _updatedAt_initializers = []; + let _updatedAt_extraInitializers = []; + let _organization_decorators; + let _organization_initializers = []; + let _organization_extraInitializers = []; + let _userFlags_decorators; + let _userFlags_initializers = []; + let _userFlags_extraInitializers = []; + let _events_decorators; + let _events_initializers = []; + let _events_extraInitializers = []; + var FeatureFlag = _classThis = class { + constructor() { + this.id = __runInitializers(this, _id_initializers, void 0); + this.key = (__runInitializers(this, _id_extraInitializers), __runInitializers(this, _key_initializers, void 0)); + this.name = (__runInitializers(this, _key_extraInitializers), __runInitializers(this, _name_initializers, void 0)); + this.description = (__runInitializers(this, _name_extraInitializers), __runInitializers(this, _description_initializers, void 0)); + this.valueType = (__runInitializers(this, _description_extraInitializers), __runInitializers(this, _valueType_initializers, void 0)); + this.defaultValue = (__runInitializers(this, _valueType_extraInitializers), __runInitializers(this, _defaultValue_initializers, void 0)); + this.variations = (__runInitializers(this, _defaultValue_extraInitializers), __runInitializers(this, _variations_initializers, void 0)); + this.targeting = (__runInitializers(this, _variations_extraInitializers), __runInitializers(this, _targeting_initializers, void 0)); + this.isEnabled = (__runInitializers(this, _targeting_extraInitializers), __runInitializers(this, _isEnabled_initializers, void 0)); + this.isArchived = (__runInitializers(this, _isEnabled_extraInitializers), __runInitializers(this, _isArchived_initializers, void 0)); + this.category = (__runInitializers(this, _isArchived_extraInitializers), __runInitializers(this, _category_initializers, void 0)); + this.tags = (__runInitializers(this, _category_extraInitializers), __runInitializers(this, _tags_initializers, void 0)); + this.organizationId = (__runInitializers(this, _tags_extraInitializers), __runInitializers(this, _organizationId_initializers, void 0)); + this.environment = (__runInitializers(this, _organizationId_extraInitializers), __runInitializers(this, _environment_initializers, void 0)); + this.createdAt = (__runInitializers(this, _environment_extraInitializers), __runInitializers(this, _createdAt_initializers, void 0)); + this.updatedAt = (__runInitializers(this, _createdAt_extraInitializers), __runInitializers(this, _updatedAt_initializers, void 0)); + // Relations + this.organization = (__runInitializers(this, _updatedAt_extraInitializers), __runInitializers(this, _organization_initializers, void 0)); + this.userFlags = (__runInitializers(this, _organization_extraInitializers), __runInitializers(this, _userFlags_initializers, void 0)); + this.events = (__runInitializers(this, _userFlags_extraInitializers), __runInitializers(this, _events_initializers, void 0)); + __runInitializers(this, _events_extraInitializers); + } + }; + __setFunctionName(_classThis, "FeatureFlag"); + (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [PrimaryColumn({ type: 'varchar', generated: true })]; + _key_decorators = [Column({ type: 'varchar', length: 255, nullable: false }), Index('idx_flag_key', { unique: true })]; + _name_decorators = [Column({ type: 'varchar', length: 255, nullable: false })]; + _description_decorators = [Column({ type: 'text', nullable: true })]; + _valueType_decorators = [Column({ type: 'enum', enum: ['boolean', 'string', 'number', 'json'], default: 'boolean' })]; + _defaultValue_decorators = [Column({ type: 'json', nullable: false })]; + _variations_decorators = [Column({ type: 'json', nullable: true })]; + _targeting_decorators = [Column({ type: 'json', nullable: true })]; + _isEnabled_decorators = [Column({ type: 'boolean', default: false })]; + _isArchived_decorators = [Column({ type: 'boolean', default: false })]; + _category_decorators = [Column({ type: 'varchar', length: 255, nullable: true })]; + _tags_decorators = [Column({ type: 'json', nullable: true })]; + _organizationId_decorators = [Column({ type: 'varchar', length: 255, nullable: true }), JoinColumn({ name: 'organization_id' })]; + _environment_decorators = [Column({ type: 'varchar', length: 255, nullable: false, default: 'production' }), Index('idx_flag_environment')]; + _createdAt_decorators = [CreateDateColumn()]; + _updatedAt_decorators = [UpdateDateColumn()]; + _organization_decorators = [ManyToOne(() => Organization, organization => organization.featureFlags, { onDelete: 'CASCADE' }), JoinColumn({ name: 'organization_id' })]; + _userFlags_decorators = [OneToMany(() => UserFlag, userFlag => userFlag.featureFlag)]; + _events_decorators = [OneToMany(() => FlagEvent, event => event.featureFlag)]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: obj => "id" in obj, get: obj => obj.id, set: (obj, value) => { obj.id = value; } }, metadata: _metadata }, _id_initializers, _id_extraInitializers); + __esDecorate(null, null, _key_decorators, { kind: "field", name: "key", static: false, private: false, access: { has: obj => "key" in obj, get: obj => obj.key, set: (obj, value) => { obj.key = value; } }, metadata: _metadata }, _key_initializers, _key_extraInitializers); + __esDecorate(null, null, _name_decorators, { kind: "field", name: "name", static: false, private: false, access: { has: obj => "name" in obj, get: obj => obj.name, set: (obj, value) => { obj.name = value; } }, metadata: _metadata }, _name_initializers, _name_extraInitializers); + __esDecorate(null, null, _description_decorators, { kind: "field", name: "description", static: false, private: false, access: { has: obj => "description" in obj, get: obj => obj.description, set: (obj, value) => { obj.description = value; } }, metadata: _metadata }, _description_initializers, _description_extraInitializers); + __esDecorate(null, null, _valueType_decorators, { kind: "field", name: "valueType", static: false, private: false, access: { has: obj => "valueType" in obj, get: obj => obj.valueType, set: (obj, value) => { obj.valueType = value; } }, metadata: _metadata }, _valueType_initializers, _valueType_extraInitializers); + __esDecorate(null, null, _defaultValue_decorators, { kind: "field", name: "defaultValue", static: false, private: false, access: { has: obj => "defaultValue" in obj, get: obj => obj.defaultValue, set: (obj, value) => { obj.defaultValue = value; } }, metadata: _metadata }, _defaultValue_initializers, _defaultValue_extraInitializers); + __esDecorate(null, null, _variations_decorators, { kind: "field", name: "variations", static: false, private: false, access: { has: obj => "variations" in obj, get: obj => obj.variations, set: (obj, value) => { obj.variations = value; } }, metadata: _metadata }, _variations_initializers, _variations_extraInitializers); + __esDecorate(null, null, _targeting_decorators, { kind: "field", name: "targeting", static: false, private: false, access: { has: obj => "targeting" in obj, get: obj => obj.targeting, set: (obj, value) => { obj.targeting = value; } }, metadata: _metadata }, _targeting_initializers, _targeting_extraInitializers); + __esDecorate(null, null, _isEnabled_decorators, { kind: "field", name: "isEnabled", static: false, private: false, access: { has: obj => "isEnabled" in obj, get: obj => obj.isEnabled, set: (obj, value) => { obj.isEnabled = value; } }, metadata: _metadata }, _isEnabled_initializers, _isEnabled_extraInitializers); + __esDecorate(null, null, _isArchived_decorators, { kind: "field", name: "isArchived", static: false, private: false, access: { has: obj => "isArchived" in obj, get: obj => obj.isArchived, set: (obj, value) => { obj.isArchived = value; } }, metadata: _metadata }, _isArchived_initializers, _isArchived_extraInitializers); + __esDecorate(null, null, _category_decorators, { kind: "field", name: "category", static: false, private: false, access: { has: obj => "category" in obj, get: obj => obj.category, set: (obj, value) => { obj.category = value; } }, metadata: _metadata }, _category_initializers, _category_extraInitializers); + __esDecorate(null, null, _tags_decorators, { kind: "field", name: "tags", static: false, private: false, access: { has: obj => "tags" in obj, get: obj => obj.tags, set: (obj, value) => { obj.tags = value; } }, metadata: _metadata }, _tags_initializers, _tags_extraInitializers); + __esDecorate(null, null, _organizationId_decorators, { kind: "field", name: "organizationId", static: false, private: false, access: { has: obj => "organizationId" in obj, get: obj => obj.organizationId, set: (obj, value) => { obj.organizationId = value; } }, metadata: _metadata }, _organizationId_initializers, _organizationId_extraInitializers); + __esDecorate(null, null, _environment_decorators, { kind: "field", name: "environment", static: false, private: false, access: { has: obj => "environment" in obj, get: obj => obj.environment, set: (obj, value) => { obj.environment = value; } }, metadata: _metadata }, _environment_initializers, _environment_extraInitializers); + __esDecorate(null, null, _createdAt_decorators, { kind: "field", name: "createdAt", static: false, private: false, access: { has: obj => "createdAt" in obj, get: obj => obj.createdAt, set: (obj, value) => { obj.createdAt = value; } }, metadata: _metadata }, _createdAt_initializers, _createdAt_extraInitializers); + __esDecorate(null, null, _updatedAt_decorators, { kind: "field", name: "updatedAt", static: false, private: false, access: { has: obj => "updatedAt" in obj, get: obj => obj.updatedAt, set: (obj, value) => { obj.updatedAt = value; } }, metadata: _metadata }, _updatedAt_initializers, _updatedAt_extraInitializers); + __esDecorate(null, null, _organization_decorators, { kind: "field", name: "organization", static: false, private: false, access: { has: obj => "organization" in obj, get: obj => obj.organization, set: (obj, value) => { obj.organization = value; } }, metadata: _metadata }, _organization_initializers, _organization_extraInitializers); + __esDecorate(null, null, _userFlags_decorators, { kind: "field", name: "userFlags", static: false, private: false, access: { has: obj => "userFlags" in obj, get: obj => obj.userFlags, set: (obj, value) => { obj.userFlags = value; } }, metadata: _metadata }, _userFlags_initializers, _userFlags_extraInitializers); + __esDecorate(null, null, _events_decorators, { kind: "field", name: "events", static: false, private: false, access: { has: obj => "events" in obj, get: obj => obj.events, set: (obj, value) => { obj.events = value; } }, metadata: _metadata }, _events_initializers, _events_extraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + FeatureFlag = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return FeatureFlag = _classThis; +})(); +exports.FeatureFlag = FeatureFlag; +/** + * User-specific flag overrides + */ +let UserFlag = (() => { + let _classDecorators = [Entity('user_flags')]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + let _static_userFlagIndex_decorators; + let _static_userFlagIndex_initializers = []; + let _static_userFlagIndex_extraInitializers = []; + let _id_decorators; + let _id_initializers = []; + let _id_extraInitializers = []; + let _userId_decorators; + let _userId_initializers = []; + let _userId_extraInitializers = []; + let _featureFlagId_decorators; + let _featureFlagId_initializers = []; + let _featureFlagId_extraInitializers = []; + let _value_decorators; + let _value_initializers = []; + let _value_extraInitializers = []; + let _reason_decorators; + let _reason_initializers = []; + let _reason_extraInitializers = []; + let _isActive_decorators; + let _isActive_initializers = []; + let _isActive_extraInitializers = []; + let _expiresAt_decorators; + let _expiresAt_initializers = []; + let _expiresAt_extraInitializers = []; + let _createdAt_decorators; + let _createdAt_initializers = []; + let _createdAt_extraInitializers = []; + let _updatedAt_decorators; + let _updatedAt_initializers = []; + let _updatedAt_extraInitializers = []; + let _user_decorators; + let _user_initializers = []; + let _user_extraInitializers = []; + let _featureFlag_decorators; + let _featureFlag_initializers = []; + let _featureFlag_extraInitializers = []; + var UserFlag = _classThis = class { + constructor() { + this.id = __runInitializers(this, _id_initializers, void 0); + this.userId = (__runInitializers(this, _id_extraInitializers), __runInitializers(this, _userId_initializers, void 0)); + this.featureFlagId = (__runInitializers(this, _userId_extraInitializers), __runInitializers(this, _featureFlagId_initializers, void 0)); + this.value = (__runInitializers(this, _featureFlagId_extraInitializers), __runInitializers(this, _value_initializers, void 0)); + this.reason = (__runInitializers(this, _value_extraInitializers), __runInitializers(this, _reason_initializers, void 0)); + this.isActive = (__runInitializers(this, _reason_extraInitializers), __runInitializers(this, _isActive_initializers, void 0)); + this.expiresAt = (__runInitializers(this, _isActive_extraInitializers), __runInitializers(this, _expiresAt_initializers, void 0)); + this.createdAt = (__runInitializers(this, _expiresAt_extraInitializers), __runInitializers(this, _createdAt_initializers, void 0)); + this.updatedAt = (__runInitializers(this, _createdAt_extraInitializers), __runInitializers(this, _updatedAt_initializers, void 0)); + // Relations + this.user = (__runInitializers(this, _updatedAt_extraInitializers), __runInitializers(this, _user_initializers, void 0)); + this.featureFlag = (__runInitializers(this, _user_extraInitializers), __runInitializers(this, _featureFlag_initializers, void 0)); + __runInitializers(this, _featureFlag_extraInitializers); + } + }; + __setFunctionName(_classThis, "UserFlag"); + (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [PrimaryColumn({ type: 'varchar', generated: true })]; + _userId_decorators = [Column({ type: 'varchar', length: 255, nullable: false }), JoinColumn({ name: 'user_id' })]; + _featureFlagId_decorators = [Column({ type: 'varchar', length: 255, nullable: false }), JoinColumn({ name: 'feature_flag_id' })]; + _value_decorators = [Column({ type: 'json', nullable: false })]; + _reason_decorators = [Column({ type: 'text', nullable: true })]; + _isActive_decorators = [Column({ type: 'boolean', default: true })]; + _expiresAt_decorators = [Column({ type: 'timestamp', nullable: true })]; + _createdAt_decorators = [CreateDateColumn()]; + _updatedAt_decorators = [UpdateDateColumn()]; + _user_decorators = [ManyToOne(() => User, user => user.userFlags, { onDelete: 'CASCADE' }), JoinColumn({ name: 'user_id' })]; + _featureFlag_decorators = [ManyToOne(() => FeatureFlag, flag => flag.userFlags, { onDelete: 'CASCADE' }), JoinColumn({ name: 'feature_flag_id' })]; + _static_userFlagIndex_decorators = [Index('idx_user_flag_unique', { unique: true })]; + __esDecorate(null, null, _static_userFlagIndex_decorators, { kind: "field", name: "userFlagIndex", static: true, private: false, access: { has: obj => "userFlagIndex" in obj, get: obj => obj.userFlagIndex, set: (obj, value) => { obj.userFlagIndex = value; } }, metadata: _metadata }, _static_userFlagIndex_initializers, _static_userFlagIndex_extraInitializers); + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: obj => "id" in obj, get: obj => obj.id, set: (obj, value) => { obj.id = value; } }, metadata: _metadata }, _id_initializers, _id_extraInitializers); + __esDecorate(null, null, _userId_decorators, { kind: "field", name: "userId", static: false, private: false, access: { has: obj => "userId" in obj, get: obj => obj.userId, set: (obj, value) => { obj.userId = value; } }, metadata: _metadata }, _userId_initializers, _userId_extraInitializers); + __esDecorate(null, null, _featureFlagId_decorators, { kind: "field", name: "featureFlagId", static: false, private: false, access: { has: obj => "featureFlagId" in obj, get: obj => obj.featureFlagId, set: (obj, value) => { obj.featureFlagId = value; } }, metadata: _metadata }, _featureFlagId_initializers, _featureFlagId_extraInitializers); + __esDecorate(null, null, _value_decorators, { kind: "field", name: "value", static: false, private: false, access: { has: obj => "value" in obj, get: obj => obj.value, set: (obj, value) => { obj.value = value; } }, metadata: _metadata }, _value_initializers, _value_extraInitializers); + __esDecorate(null, null, _reason_decorators, { kind: "field", name: "reason", static: false, private: false, access: { has: obj => "reason" in obj, get: obj => obj.reason, set: (obj, value) => { obj.reason = value; } }, metadata: _metadata }, _reason_initializers, _reason_extraInitializers); + __esDecorate(null, null, _isActive_decorators, { kind: "field", name: "isActive", static: false, private: false, access: { has: obj => "isActive" in obj, get: obj => obj.isActive, set: (obj, value) => { obj.isActive = value; } }, metadata: _metadata }, _isActive_initializers, _isActive_extraInitializers); + __esDecorate(null, null, _expiresAt_decorators, { kind: "field", name: "expiresAt", static: false, private: false, access: { has: obj => "expiresAt" in obj, get: obj => obj.expiresAt, set: (obj, value) => { obj.expiresAt = value; } }, metadata: _metadata }, _expiresAt_initializers, _expiresAt_extraInitializers); + __esDecorate(null, null, _createdAt_decorators, { kind: "field", name: "createdAt", static: false, private: false, access: { has: obj => "createdAt" in obj, get: obj => obj.createdAt, set: (obj, value) => { obj.createdAt = value; } }, metadata: _metadata }, _createdAt_initializers, _createdAt_extraInitializers); + __esDecorate(null, null, _updatedAt_decorators, { kind: "field", name: "updatedAt", static: false, private: false, access: { has: obj => "updatedAt" in obj, get: obj => obj.updatedAt, set: (obj, value) => { obj.updatedAt = value; } }, metadata: _metadata }, _updatedAt_initializers, _updatedAt_extraInitializers); + __esDecorate(null, null, _user_decorators, { kind: "field", name: "user", static: false, private: false, access: { has: obj => "user" in obj, get: obj => obj.user, set: (obj, value) => { obj.user = value; } }, metadata: _metadata }, _user_initializers, _user_extraInitializers); + __esDecorate(null, null, _featureFlag_decorators, { kind: "field", name: "featureFlag", static: false, private: false, access: { has: obj => "featureFlag" in obj, get: obj => obj.featureFlag, set: (obj, value) => { obj.featureFlag = value; } }, metadata: _metadata }, _featureFlag_initializers, _featureFlag_extraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + UserFlag = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + })(); + // Composite index for unique user-flag combination + _classThis.userFlagIndex = __runInitializers(_classThis, _static_userFlagIndex_initializers, ['userId', 'featureFlagId']); + (() => { + __runInitializers(_classThis, _static_userFlagIndex_extraInitializers); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return UserFlag = _classThis; +})(); +exports.UserFlag = UserFlag; +/** + * User session tracking + */ +let UserSession = (() => { + let _classDecorators = [Entity('user_sessions')]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + let _id_decorators; + let _id_initializers = []; + let _id_extraInitializers = []; + let _userId_decorators; + let _userId_initializers = []; + let _userId_extraInitializers = []; + let _deviceId_decorators; + let _deviceId_initializers = []; + let _deviceId_extraInitializers = []; + let _userAgent_decorators; + let _userAgent_initializers = []; + let _userAgent_extraInitializers = []; + let _ipAddress_decorators; + let _ipAddress_initializers = []; + let _ipAddress_extraInitializers = []; + let _context_decorators; + let _context_initializers = []; + let _context_extraInitializers = []; + let _isActive_decorators; + let _isActive_initializers = []; + let _isActive_extraInitializers = []; + let _lastActivityAt_decorators; + let _lastActivityAt_initializers = []; + let _lastActivityAt_extraInitializers = []; + let _expiresAt_decorators; + let _expiresAt_initializers = []; + let _expiresAt_extraInitializers = []; + let _createdAt_decorators; + let _createdAt_initializers = []; + let _createdAt_extraInitializers = []; + let _updatedAt_decorators; + let _updatedAt_initializers = []; + let _updatedAt_extraInitializers = []; + let _user_decorators; + let _user_initializers = []; + let _user_extraInitializers = []; + var UserSession = _classThis = class { + constructor() { + this.id = __runInitializers(this, _id_initializers, void 0); + this.userId = (__runInitializers(this, _id_extraInitializers), __runInitializers(this, _userId_initializers, void 0)); + this.deviceId = (__runInitializers(this, _userId_extraInitializers), __runInitializers(this, _deviceId_initializers, void 0)); + this.userAgent = (__runInitializers(this, _deviceId_extraInitializers), __runInitializers(this, _userAgent_initializers, void 0)); + this.ipAddress = (__runInitializers(this, _userAgent_extraInitializers), __runInitializers(this, _ipAddress_initializers, void 0)); + this.context = (__runInitializers(this, _ipAddress_extraInitializers), __runInitializers(this, _context_initializers, void 0)); + this.isActive = (__runInitializers(this, _context_extraInitializers), __runInitializers(this, _isActive_initializers, void 0)); + this.lastActivityAt = (__runInitializers(this, _isActive_extraInitializers), __runInitializers(this, _lastActivityAt_initializers, void 0)); + this.expiresAt = (__runInitializers(this, _lastActivityAt_extraInitializers), __runInitializers(this, _expiresAt_initializers, void 0)); + this.createdAt = (__runInitializers(this, _expiresAt_extraInitializers), __runInitializers(this, _createdAt_initializers, void 0)); + this.updatedAt = (__runInitializers(this, _createdAt_extraInitializers), __runInitializers(this, _updatedAt_initializers, void 0)); + // Relations + this.user = (__runInitializers(this, _updatedAt_extraInitializers), __runInitializers(this, _user_initializers, void 0)); + __runInitializers(this, _user_extraInitializers); + } + }; + __setFunctionName(_classThis, "UserSession"); + (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [PrimaryColumn({ type: 'varchar', generated: true })]; + _userId_decorators = [Column({ type: 'varchar', length: 255, nullable: false }), JoinColumn({ name: 'user_id' })]; + _deviceId_decorators = [Column({ type: 'varchar', length: 255, nullable: true })]; + _userAgent_decorators = [Column({ type: 'varchar', length: 255, nullable: true })]; + _ipAddress_decorators = [Column({ type: 'inet', nullable: true })]; + _context_decorators = [Column({ type: 'json', nullable: true })]; + _isActive_decorators = [Column({ type: 'boolean', default: true })]; + _lastActivityAt_decorators = [Column({ type: 'timestamp', nullable: true })]; + _expiresAt_decorators = [Column({ type: 'timestamp', nullable: true })]; + _createdAt_decorators = [CreateDateColumn()]; + _updatedAt_decorators = [UpdateDateColumn()]; + _user_decorators = [ManyToOne(() => User, user => user.sessions, { onDelete: 'CASCADE' }), JoinColumn({ name: 'user_id' })]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: obj => "id" in obj, get: obj => obj.id, set: (obj, value) => { obj.id = value; } }, metadata: _metadata }, _id_initializers, _id_extraInitializers); + __esDecorate(null, null, _userId_decorators, { kind: "field", name: "userId", static: false, private: false, access: { has: obj => "userId" in obj, get: obj => obj.userId, set: (obj, value) => { obj.userId = value; } }, metadata: _metadata }, _userId_initializers, _userId_extraInitializers); + __esDecorate(null, null, _deviceId_decorators, { kind: "field", name: "deviceId", static: false, private: false, access: { has: obj => "deviceId" in obj, get: obj => obj.deviceId, set: (obj, value) => { obj.deviceId = value; } }, metadata: _metadata }, _deviceId_initializers, _deviceId_extraInitializers); + __esDecorate(null, null, _userAgent_decorators, { kind: "field", name: "userAgent", static: false, private: false, access: { has: obj => "userAgent" in obj, get: obj => obj.userAgent, set: (obj, value) => { obj.userAgent = value; } }, metadata: _metadata }, _userAgent_initializers, _userAgent_extraInitializers); + __esDecorate(null, null, _ipAddress_decorators, { kind: "field", name: "ipAddress", static: false, private: false, access: { has: obj => "ipAddress" in obj, get: obj => obj.ipAddress, set: (obj, value) => { obj.ipAddress = value; } }, metadata: _metadata }, _ipAddress_initializers, _ipAddress_extraInitializers); + __esDecorate(null, null, _context_decorators, { kind: "field", name: "context", static: false, private: false, access: { has: obj => "context" in obj, get: obj => obj.context, set: (obj, value) => { obj.context = value; } }, metadata: _metadata }, _context_initializers, _context_extraInitializers); + __esDecorate(null, null, _isActive_decorators, { kind: "field", name: "isActive", static: false, private: false, access: { has: obj => "isActive" in obj, get: obj => obj.isActive, set: (obj, value) => { obj.isActive = value; } }, metadata: _metadata }, _isActive_initializers, _isActive_extraInitializers); + __esDecorate(null, null, _lastActivityAt_decorators, { kind: "field", name: "lastActivityAt", static: false, private: false, access: { has: obj => "lastActivityAt" in obj, get: obj => obj.lastActivityAt, set: (obj, value) => { obj.lastActivityAt = value; } }, metadata: _metadata }, _lastActivityAt_initializers, _lastActivityAt_extraInitializers); + __esDecorate(null, null, _expiresAt_decorators, { kind: "field", name: "expiresAt", static: false, private: false, access: { has: obj => "expiresAt" in obj, get: obj => obj.expiresAt, set: (obj, value) => { obj.expiresAt = value; } }, metadata: _metadata }, _expiresAt_initializers, _expiresAt_extraInitializers); + __esDecorate(null, null, _createdAt_decorators, { kind: "field", name: "createdAt", static: false, private: false, access: { has: obj => "createdAt" in obj, get: obj => obj.createdAt, set: (obj, value) => { obj.createdAt = value; } }, metadata: _metadata }, _createdAt_initializers, _createdAt_extraInitializers); + __esDecorate(null, null, _updatedAt_decorators, { kind: "field", name: "updatedAt", static: false, private: false, access: { has: obj => "updatedAt" in obj, get: obj => obj.updatedAt, set: (obj, value) => { obj.updatedAt = value; } }, metadata: _metadata }, _updatedAt_initializers, _updatedAt_extraInitializers); + __esDecorate(null, null, _user_decorators, { kind: "field", name: "user", static: false, private: false, access: { has: obj => "user" in obj, get: obj => obj.user, set: (obj, value) => { obj.user = value; } }, metadata: _metadata }, _user_initializers, _user_extraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + UserSession = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return UserSession = _classThis; +})(); +exports.UserSession = UserSession; +/** + * Feature flag event tracking + */ +let FlagEvent = (() => { + let _classDecorators = [Entity('flag_events')]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + let _id_decorators; + let _id_initializers = []; + let _id_extraInitializers = []; + let _featureFlagId_decorators; + let _featureFlagId_initializers = []; + let _featureFlagId_extraInitializers = []; + let _userId_decorators; + let _userId_initializers = []; + let _userId_extraInitializers = []; + let _eventType_decorators; + let _eventType_initializers = []; + let _eventType_extraInitializers = []; + let _previousValue_decorators; + let _previousValue_initializers = []; + let _previousValue_extraInitializers = []; + let _newValue_decorators; + let _newValue_initializers = []; + let _newValue_extraInitializers = []; + let _context_decorators; + let _context_initializers = []; + let _context_extraInitializers = []; + let _reason_decorators; + let _reason_initializers = []; + let _reason_extraInitializers = []; + let _source_decorators; + let _source_initializers = []; + let _source_extraInitializers = []; + let _createdAt_decorators; + let _createdAt_initializers = []; + let _createdAt_extraInitializers = []; + let _featureFlag_decorators; + let _featureFlag_initializers = []; + let _featureFlag_extraInitializers = []; + let _user_decorators; + let _user_initializers = []; + let _user_extraInitializers = []; + var FlagEvent = _classThis = class { + constructor() { + this.id = __runInitializers(this, _id_initializers, void 0); + this.featureFlagId = (__runInitializers(this, _id_extraInitializers), __runInitializers(this, _featureFlagId_initializers, void 0)); + this.userId = (__runInitializers(this, _featureFlagId_extraInitializers), __runInitializers(this, _userId_initializers, void 0)); + this.eventType = (__runInitializers(this, _userId_extraInitializers), __runInitializers(this, _eventType_initializers, void 0)); + this.previousValue = (__runInitializers(this, _eventType_extraInitializers), __runInitializers(this, _previousValue_initializers, void 0)); + this.newValue = (__runInitializers(this, _previousValue_extraInitializers), __runInitializers(this, _newValue_initializers, void 0)); + this.context = (__runInitializers(this, _newValue_extraInitializers), __runInitializers(this, _context_initializers, void 0)); + this.reason = (__runInitializers(this, _context_extraInitializers), __runInitializers(this, _reason_initializers, void 0)); + this.source = (__runInitializers(this, _reason_extraInitializers), __runInitializers(this, _source_initializers, void 0)); + this.createdAt = (__runInitializers(this, _source_extraInitializers), __runInitializers(this, _createdAt_initializers, void 0)); + // Relations + this.featureFlag = (__runInitializers(this, _createdAt_extraInitializers), __runInitializers(this, _featureFlag_initializers, void 0)); + this.user = (__runInitializers(this, _featureFlag_extraInitializers), __runInitializers(this, _user_initializers, void 0)); + __runInitializers(this, _user_extraInitializers); + } + }; + __setFunctionName(_classThis, "FlagEvent"); + (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _id_decorators = [PrimaryColumn({ type: 'varchar', generated: true })]; + _featureFlagId_decorators = [Column({ type: 'varchar', length: 255, nullable: false }), JoinColumn({ name: 'feature_flag_id' })]; + _userId_decorators = [Column({ type: 'varchar', length: 255, nullable: true }), JoinColumn({ name: 'user_id' })]; + _eventType_decorators = [Column({ type: 'enum', enum: ['evaluation', 'update', 'create', 'delete', 'toggle'], nullable: false }), Index('idx_event_type')]; + _previousValue_decorators = [Column({ type: 'json', nullable: true })]; + _newValue_decorators = [Column({ type: 'json', nullable: true })]; + _context_decorators = [Column({ type: 'json', nullable: true })]; + _reason_decorators = [Column({ type: 'text', nullable: true })]; + _source_decorators = [Column({ type: 'varchar', length: 255, nullable: true })]; + _createdAt_decorators = [CreateDateColumn()]; + _featureFlag_decorators = [ManyToOne(() => FeatureFlag, flag => flag.events, { onDelete: 'CASCADE' }), JoinColumn({ name: 'feature_flag_id' })]; + _user_decorators = [ManyToOne(() => User, { onDelete: 'SET NULL' }), JoinColumn({ name: 'user_id' })]; + __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: obj => "id" in obj, get: obj => obj.id, set: (obj, value) => { obj.id = value; } }, metadata: _metadata }, _id_initializers, _id_extraInitializers); + __esDecorate(null, null, _featureFlagId_decorators, { kind: "field", name: "featureFlagId", static: false, private: false, access: { has: obj => "featureFlagId" in obj, get: obj => obj.featureFlagId, set: (obj, value) => { obj.featureFlagId = value; } }, metadata: _metadata }, _featureFlagId_initializers, _featureFlagId_extraInitializers); + __esDecorate(null, null, _userId_decorators, { kind: "field", name: "userId", static: false, private: false, access: { has: obj => "userId" in obj, get: obj => obj.userId, set: (obj, value) => { obj.userId = value; } }, metadata: _metadata }, _userId_initializers, _userId_extraInitializers); + __esDecorate(null, null, _eventType_decorators, { kind: "field", name: "eventType", static: false, private: false, access: { has: obj => "eventType" in obj, get: obj => obj.eventType, set: (obj, value) => { obj.eventType = value; } }, metadata: _metadata }, _eventType_initializers, _eventType_extraInitializers); + __esDecorate(null, null, _previousValue_decorators, { kind: "field", name: "previousValue", static: false, private: false, access: { has: obj => "previousValue" in obj, get: obj => obj.previousValue, set: (obj, value) => { obj.previousValue = value; } }, metadata: _metadata }, _previousValue_initializers, _previousValue_extraInitializers); + __esDecorate(null, null, _newValue_decorators, { kind: "field", name: "newValue", static: false, private: false, access: { has: obj => "newValue" in obj, get: obj => obj.newValue, set: (obj, value) => { obj.newValue = value; } }, metadata: _metadata }, _newValue_initializers, _newValue_extraInitializers); + __esDecorate(null, null, _context_decorators, { kind: "field", name: "context", static: false, private: false, access: { has: obj => "context" in obj, get: obj => obj.context, set: (obj, value) => { obj.context = value; } }, metadata: _metadata }, _context_initializers, _context_extraInitializers); + __esDecorate(null, null, _reason_decorators, { kind: "field", name: "reason", static: false, private: false, access: { has: obj => "reason" in obj, get: obj => obj.reason, set: (obj, value) => { obj.reason = value; } }, metadata: _metadata }, _reason_initializers, _reason_extraInitializers); + __esDecorate(null, null, _source_decorators, { kind: "field", name: "source", static: false, private: false, access: { has: obj => "source" in obj, get: obj => obj.source, set: (obj, value) => { obj.source = value; } }, metadata: _metadata }, _source_initializers, _source_extraInitializers); + __esDecorate(null, null, _createdAt_decorators, { kind: "field", name: "createdAt", static: false, private: false, access: { has: obj => "createdAt" in obj, get: obj => obj.createdAt, set: (obj, value) => { obj.createdAt = value; } }, metadata: _metadata }, _createdAt_initializers, _createdAt_extraInitializers); + __esDecorate(null, null, _featureFlag_decorators, { kind: "field", name: "featureFlag", static: false, private: false, access: { has: obj => "featureFlag" in obj, get: obj => obj.featureFlag, set: (obj, value) => { obj.featureFlag = value; } }, metadata: _metadata }, _featureFlag_initializers, _featureFlag_extraInitializers); + __esDecorate(null, null, _user_decorators, { kind: "field", name: "user", static: false, private: false, access: { has: obj => "user" in obj, get: obj => obj.user, set: (obj, value) => { obj.user = value; } }, metadata: _metadata }, _user_initializers, _user_extraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); + FlagEvent = _classThis = _classDescriptor.value; + if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + __runInitializers(_classThis, _classExtraInitializers); + })(); + return FlagEvent = _classThis; +})(); +exports.FlagEvent = FlagEvent; +// ===== VALIDATION SCHEMAS ===== +/** + * Zod schemas for runtime validation + */ +exports.EntityValidationSchemas = { + Organization: zod_1.z.object({ + name: zod_1.z.string().min(1, "Organization name is required"), + description: zod_1.z.string().optional(), + domain: zod_1.z.string().optional(), + settings: zod_1.z.record(zod_1.z.unknown()).optional(), + isActive: zod_1.z.boolean().default(true) + }), + User: zod_1.z.object({ + key: zod_1.z.string().min(1, "User key is required"), + name: zod_1.z.string().min(1, "User name is required"), + email: zod_1.z.string().email().optional(), + kind: zod_1.z.enum(['user', 'organization', 'device']).default('user'), + custom: zod_1.z.record(zod_1.z.union([zod_1.z.string(), zod_1.z.number(), zod_1.z.boolean()])).optional(), + organizationId: zod_1.z.string().optional(), + isActive: zod_1.z.boolean().default(true) + }), + FeatureFlag: zod_1.z.object({ + key: zod_1.z.string().min(1, "Feature flag key is required").regex(/^[a-zA-Z0-9._-]+$/, "Feature flag key must contain only alphanumeric characters, dots, underscores, and hyphens"), + name: zod_1.z.string().min(1, "Feature flag name is required"), + description: zod_1.z.string().optional(), + valueType: zod_1.z.enum(['boolean', 'string', 'number', 'json']).default('boolean'), + defaultValue: zod_1.z.unknown(), + variations: zod_1.z.array(zod_1.z.object({ + value: zod_1.z.unknown(), + name: zod_1.z.string(), + description: zod_1.z.string().optional() + })).optional(), + targeting: zod_1.z.object({ + rules: zod_1.z.array(zod_1.z.object({ + clauses: zod_1.z.array(zod_1.z.object({ + attribute: zod_1.z.string(), + op: zod_1.z.string(), + values: zod_1.z.array(zod_1.z.unknown()) + })), + variation: zod_1.z.number() + })).optional(), + fallthrough: zod_1.z.object({ + variation: zod_1.z.number() + }).optional() + }).optional(), + isEnabled: zod_1.z.boolean().default(false), + isArchived: zod_1.z.boolean().default(false), + category: zod_1.z.string().optional(), + tags: zod_1.z.array(zod_1.z.string()).optional(), + organizationId: zod_1.z.string().optional(), + environment: zod_1.z.string().default('production') + }), + UserFlag: zod_1.z.object({ + userId: zod_1.z.string().min(1, "User ID is required"), + featureFlagId: zod_1.z.string().min(1, "Feature flag ID is required"), + value: zod_1.z.unknown(), + reason: zod_1.z.string().optional(), + isActive: zod_1.z.boolean().default(true), + expiresAt: zod_1.z.date().optional() + }) +}; +/** + * Type-safe entity validation functions + */ +exports.validateEntity = { + organization: (data) => { + return exports.EntityValidationSchemas.Organization.parse(data); + }, + user: (data) => { + return exports.EntityValidationSchemas.User.parse(data); + }, + featureFlag: (data) => { + return exports.EntityValidationSchemas.FeatureFlag.parse(data); + }, + userFlag: (data) => { + return exports.EntityValidationSchemas.UserFlag.parse(data); + } +}; +//# sourceMappingURL=entities.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/entities.js.map b/launchdarkly/node/dist/entities.js.map new file mode 100644 index 00000000..b3a2feed --- /dev/null +++ b/launchdarkly/node/dist/entities.js.map @@ -0,0 +1 @@ +{"version":3,"file":"entities.js","sourceRoot":"","sources":["../entities.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH;;;GAGG;AAEH,6BAAwB;AAyCxB,uEAAuE;AAEvE;;;GAGG;AAEH,mBAAmB;AACnB,SAAS,MAAM,CAAC,IAAa;IAC3B,OAAO,UAAU,MAAW;QAC1B,MAAM,CAAC,YAAY,GAAG,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC;QAC1C,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC;AAED,wBAAwB;AACxB,SAAS,aAAa,CAAC,OAAgD;IACrE,OAAO,UAAU,MAAW,EAAE,WAA4B;QACxD,MAAM,CAAC,YAAY,GAAG,WAAW,CAAC;IACpC,CAAC,CAAC;AACJ,CAAC;AAED,mBAAmB;AACnB,SAAS,MAAM,CAAC,OAOf;IACC,OAAO,UAAU,MAAW,EAAE,WAA4B;QACxD,IAAI,CAAC,MAAM,CAAC,SAAS;YAAE,MAAM,CAAC,SAAS,GAAG,EAAE,CAAC;QAC7C,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC;IAC5D,CAAC,CAA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AM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,qBAAqB,CAAC;QAChD,aAAa,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,6BAA6B,CAAC;QAC/D,KAAK,EAAE,OAAC,CAAC,OAAO,EAAE;QAClB,MAAM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;QAC7B,QAAQ,EAAE,OAAC,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;QACnC,SAAS,EAAE,OAAC,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE;KAC/B,CAAC;CACM,CAAC;AAEX;;GAEG;AACU,QAAA,cAAc,GAAG;IAC5B,YAAY,EAAE,CAAC,IAAa,EAA2B,EAAE;QACvD,OAAO,+BAAuB,CAAC,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1D,CAAC;IAED,IAAI,EAAE,CAAC,IAAa,EAAmB,EAAE;QACvC,OAAO,+BAAuB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAClD,CAAC;IAED,WAAW,EAAE,CAAC,IAAa,EAA0B,EAAE;QACrD,OAAO,+BAAuB,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzD,CAAC;IAED,QAAQ,EAAE,CAAC,IAAa,EAAuB,EAAE;QAC/C,OAAO,+BAAuB,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACtD,CAAC;CACO,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/event-emitter.d.ts b/launchdarkly/node/dist/event-emitter.d.ts new file mode 100644 index 00000000..f903e5c0 --- /dev/null +++ b/launchdarkly/node/dist/event-emitter.d.ts @@ -0,0 +1,109 @@ +/** + * Type-safe event emitter implementation with proper subscription management, + * generic event handler functions, and comprehensive error handling. + */ +import { EventName, EventPayload, EventHandler, TypeSafeEventEmitter, EventSubscription, EventEmitterStats, EventFactory, FlagEventNames, SessionEventNames, SystemEventNames } from "./events.js"; +/** + * Type-safe event emitter with comprehensive subscription management + */ +export declare class TypeSafeEventEmitterImpl implements TypeSafeEventEmitter { + private readonly handlers; + private readonly stats; + /** + * Register an event handler for a specific event type with proper type inference + */ + on(eventName: T, handler: EventHandler, options?: { + priority?: number; + once?: boolean; + }): () => void; + /** + * Register a one-time event handler + */ + once(eventName: T, handler: EventHandler): void; + /** + * Remove a specific event handler + */ + off(eventName: T, handler: EventHandler): void; + /** + * Remove all handlers for an event type + */ + removeAllListeners(eventName: T): void; + /** + * Emit an event with proper type checking and error handling + */ + emit(eventName: T, payload: EventPayload): Promise; + /** + * Get the number of handlers for an event type + */ + listenerCount(eventName: T): number; + /** + * Get all event names that have handlers + */ + eventNames(): EventName[]; + /** + * Get event emitter statistics + */ + getStats(): EventEmitterStats; + /** + * Clear all handlers and reset stats + */ + clear(): void; + /** + * Create a scoped event subscription + */ + subscribe(eventName: T, handler: EventHandler, options?: { + priority?: number; + }): EventSubscription; + private generateHandlerId; + private removeHandler; + private handleError; +} +/** + * Factory for creating type-safe events with validation + */ +export declare class EventFactoryImpl implements EventFactory { + create(eventName: T, payload: Omit, 'timestamp'>): EventPayload; + createFlagEvent(eventName: T, payload: Omit, 'timestamp'>): EventPayload; + createSessionEvent(eventName: T, payload: Omit, 'timestamp'>): EventPayload; + createSystemEvent(eventName: T, payload: Omit, 'timestamp'>): EventPayload; +} +/** + * Create a safe event handler that catches and logs errors + */ +export declare function createSafeHandler(handler: EventHandler, options?: { + onError?: (error: Error, payload: EventPayload) => void; + retries?: number; + timeout?: number; +}): EventHandler; +/** + * Create a conditional event handler + */ +export declare function createConditionalHandler(condition: (payload: EventPayload) => boolean, handler: EventHandler): EventHandler; +/** + * Create a debounced event handler + */ +export declare function createDebouncedHandler(handler: EventHandler, delay: number): EventHandler; +/** + * Create a throttled event handler + */ +export declare function createThrottledHandler(handler: EventHandler, interval: number): EventHandler; +/** + * Compose multiple event handlers into a single handler + */ +export declare function composeHandlers(...handlers: EventHandler[]): EventHandler; +/** + * Create an event handler with logging + */ +export declare function createLoggingHandler(handler: EventHandler, logger: { + log: (level: 'info' | 'warn' | 'error', message: string, meta?: any) => void; +}): EventHandler; +/** + * Get the global event emitter instance + */ +export declare function getGlobalEventEmitter(): TypeSafeEventEmitterImpl; +/** + * Get the global event factory instance + */ +export declare function getEventFactory(): EventFactoryImpl; +export { TypeSafeEventEmitterImpl as TypeSafeEventEmitter, EventFactoryImpl as EventFactory }; +//# sourceMappingURL=event-emitter.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/event-emitter.d.ts.map b/launchdarkly/node/dist/event-emitter.d.ts.map new file mode 100644 index 00000000..d699d1ed --- /dev/null +++ b/launchdarkly/node/dist/event-emitter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"event-emitter.d.ts","sourceRoot":"","sources":["../event-emitter.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AAEH,OAAO,EACL,SAAS,EACT,YAAY,EACZ,YAAY,EAEZ,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,EACjB,YAAY,EACZ,cAAc,EACd,iBAAiB,EACjB,gBAAgB,EAIjB,MAAM,aAAa,CAAC;AAIrB;;GAEG;AACH,qBAAa,wBAAyB,YAAW,oBAAoB;IACnE,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA+D;IACxF,OAAO,CAAC,QAAQ,CAAC,KAAK,CAMpB;IAEF;;OAEG;IACI,EAAE,CAAC,CAAC,SAAS,SAAS,EAC3B,SAAS,EAAE,CAAC,EACZ,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,EACxB,OAAO,GAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,OAAO,CAAA;KAAO,GAClD,MAAM,IAAI;IAoCb;;OAEG;IACI,IAAI,CAAC,CAAC,SAAS,SAAS,EAAE,SAAS,EAAE,CAAC,EAAE,OAA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YAAY,CAAC,CAAC,CAAC,CAuBjB;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,SAAS,EACjD,GAAG,QAAQ,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,GAC7B,YAAY,CAAC,CAAC,CAAC,CAKjB;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,SAAS,EACtD,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,EACxB,MAAM,EAAE;IACN,GAAG,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG,KAAK,IAAI,CAAC;CAC9E,GACA,YAAY,CAAC,CAAC,CAAC,CAmBjB;AASD;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,wBAAwB,CAKhE;AAED;;GAEG;AACH,wBAAgB,eAAe,IAAI,gBAAgB,CAElD;AAID,OAAO,EACL,wBAAwB,IAAI,oBAAoB,EAChD,gBAAgB,IAAI,YAAY,EACjC,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/event-emitter.js b/launchdarkly/node/dist/event-emitter.js new file mode 100644 index 00000000..b876c48b --- /dev/null +++ b/launchdarkly/node/dist/event-emitter.js @@ -0,0 +1,411 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EventFactory = exports.TypeSafeEventEmitter = exports.EventFactoryImpl = exports.TypeSafeEventEmitterImpl = void 0; +exports.createSafeHandler = createSafeHandler; +exports.createConditionalHandler = createConditionalHandler; +exports.createDebouncedHandler = createDebouncedHandler; +exports.createThrottledHandler = createThrottledHandler; +exports.composeHandlers = composeHandlers; +exports.createLoggingHandler = createLoggingHandler; +exports.getGlobalEventEmitter = getGlobalEventEmitter; +exports.getEventFactory = getEventFactory; +/** + * Type-safe event emitter implementation with proper subscription management, + * generic event handler functions, and comprehensive error handling. + */ +const events_js_1 = require("./events.js"); +// ===== EVENT EMITTER IMPLEMENTATION ===== +/** + * Type-safe event emitter with comprehensive subscription management + */ +class TypeSafeEventEmitterImpl { + constructor() { + this.handlers = new Map(); + this.stats = { + totalHandlers: 0, + handlersByEvent: {}, + totalEmissions: 0, + emissionsByEvent: {}, + errors: [] + }; + } + /** + * Register an event handler for a specific event type with proper type inference + */ + on(eventName, handler, options = {}) { + if (!(0, events_js_1.isValidEventName)(eventName)) { + throw new Error(`Invalid event name: ${String(eventName)}`); + } + if (!(0, events_js_1.isCompatibleHandler)(eventName, handler)) { + throw new Error(`Invalid handler for event: ${eventName}`); + } + const handlerWithMetadata = { + handler, + id: this.generateHandlerId(), + priority: options.priority !== undefined ? options.priority : 0, + once: options.once !== undefined ? options.once : false, + createdAt: new Date() + }; + // Initialize handlers array if it doesn't exist + if (!this.handlers.has(eventName)) { + this.handlers.set(eventName, []); + this.stats.handlersByEvent[eventName] = 0; + } + // Add handler and sort by priority (higher priority first) + const eventHandlers = this.handlers.get(eventName); + eventHandlers.push(handlerWithMetadata); + eventHandlers.sort((a, b) => (b.priority || 0) - (a.priority || 0)); + // Update stats + this.stats.totalHandlers++; + this.stats.handlersByEvent[eventName]++; + // Return unsubscribe function + return () => this.removeHandler(eventName, handlerWithMetadata.id); + } + /** + * Register a one-time event handler + */ + once(eventName, handler) { + this.on(eventName, handler, { once: true }); + } + /** + * Remove a specific event handler + */ + off(eventName, handler) { + const eventHandlers = this.handlers.get(eventName); + if (!eventHandlers) + return; + const index = eventHandlers.findIndex(h => h.handler === handler); + if (index !== -1) { + eventHandlers.splice(index, 1); + this.stats.totalHandlers--; + this.stats.handlersByEvent[eventName]--; + if (eventHandlers.length === 0) { + this.handlers.delete(eventName); + delete this.stats.handlersByEvent[eventName]; + } + } + } + /** + * Remove all handlers for an event type + */ + removeAllListeners(eventName) { + const eventHandlers = this.handlers.get(eventName); + if (!eventHandlers) + return; + const handlerCount = eventHandlers.length; + this.handlers.delete(eventName); + this.stats.totalHandlers -= handlerCount; + delete this.stats.handlersByEvent[eventName]; + } + /** + * Emit an event with proper type checking and error handling + */ + async emit(eventName, payload) { + if (!(0, events_js_1.isValidEventName)(eventName)) { + throw new Error(`Invalid event name: ${String(eventName)}`); + } + const eventHandlers = this.handlers.get(eventName); + if (!eventHandlers || eventHandlers.length === 0) { + return; + } + // Update emission stats + this.stats.totalEmissions++; + this.stats.emissionsByEvent[eventName] = (this.stats.emissionsByEvent[eventName] || 0) + 1; + // Execute handlers + const handlerPromises = []; + const handlersToRemove = []; + for (const handlerWithMetadata of eventHandlers) { + try { + // Check condition if specified + if (handlerWithMetadata.condition && !handlerWithMetadata.condition(payload)) { + continue; + } + // Execute handler + const result = handlerWithMetadata.handler(payload); + if (result instanceof Promise) { + handlerPromises.push(result.catch(error => this.handleError(eventName, error))); + } + // Mark for removal if it's a one-time handler + if (handlerWithMetadata.once) { + handlersToRemove.push(handlerWithMetadata.id); + } + } + catch (error) { + this.handleError(eventName, error instanceof Error ? error : new Error(String(error))); + } + } + // Wait for all async handlers + if (handlerPromises.length > 0) { + await Promise.all(handlerPromises); + } + // Remove one-time handlers + for (const handlerId of handlersToRemove) { + this.removeHandler(eventName, handlerId); + } + } + /** + * Get the number of handlers for an event type + */ + listenerCount(eventName) { + return this.handlers.get(eventName)?.length !== undefined ? this.handlers.get(eventName).length : 0; + } + /** + * Get all event names that have handlers + */ + eventNames() { + return Array.from(this.handlers.keys()); + } + /** + * Get event emitter statistics + */ + getStats() { + return { ...this.stats }; + } + /** + * Clear all handlers and reset stats + */ + clear() { + this.handlers.clear(); + this.stats.totalHandlers = 0; + this.stats.handlersByEvent = {}; + this.stats.errors = []; + } + /** + * Create a scoped event subscription + */ + subscribe(eventName, handler, options) { + const unsubscribe = this.on(eventName, handler, options); + const handlerId = this.generateHandlerId(); + return { + eventName, + handlerId, + createdAt: new Date(), + unsubscribe + }; + } + // ===== PRIVATE METHODS ===== + generateHandlerId() { + return `handler_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + } + removeHandler(eventName, handlerId) { + const eventHandlers = this.handlers.get(eventName); + if (!eventHandlers) + return; + const index = eventHandlers.findIndex(h => h.id === handlerId); + if (index !== -1) { + eventHandlers.splice(index, 1); + this.stats.totalHandlers--; + this.stats.handlersByEvent[eventName]--; + if (eventHandlers.length === 0) { + this.handlers.delete(eventName); + delete this.stats.handlersByEvent[eventName]; + } + } + } + handleError(eventName, error) { + this.stats.errors.push({ + eventName, + error, + timestamp: new Date() + }); + // Emit system error event if this isn't already a system error + if (eventName !== 'system:error') { + setImmediate(() => { + this.emit('system:error', { + timestamp: new Date(), + error, + operation: `event_handler_${eventName}`, + severity: 'medium' + }).catch(() => { + // Prevent infinite error loops + }); + }); + } + } +} +exports.TypeSafeEventEmitterImpl = TypeSafeEventEmitterImpl; +exports.TypeSafeEventEmitter = TypeSafeEventEmitterImpl; +// ===== EVENT FACTORY IMPLEMENTATION ===== +/** + * Factory for creating type-safe events with validation + */ +class EventFactoryImpl { + create(eventName, payload) { + if (!(0, events_js_1.isValidEventName)(eventName)) { + throw new Error(`Invalid event name: ${String(eventName)}`); + } + return { + ...payload, + timestamp: new Date() + }; + } + createFlagEvent(eventName, payload) { + return this.create(eventName, payload); + } + createSessionEvent(eventName, payload) { + return this.create(eventName, payload); + } + createSystemEvent(eventName, payload) { + return this.create(eventName, payload); + } +} +exports.EventFactoryImpl = EventFactoryImpl; +exports.EventFactory = EventFactoryImpl; +// ===== GENERIC EVENT HANDLER UTILITIES ===== +/** + * Create a safe event handler that catches and logs errors + */ +function createSafeHandler(handler, options = {}) { + return async (payload) => { + const { onError, retries = 0, timeout } = options; + let lastError = null; + for (let attempt = 0; attempt <= retries; attempt++) { + try { + if (timeout) { + await Promise.race([ + Promise.resolve(handler(payload)), + new Promise((_, reject) => setTimeout(() => reject(new Error('Handler timeout')), timeout)) + ]); + } + else { + await Promise.resolve(handler(payload)); + } + return; // Success + } + catch (error) { + lastError = error instanceof Error ? error : new Error(String(error)); + if (attempt < retries) { + // Wait before retry with exponential backoff + await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 100)); + } + } + } + // All attempts failed + if (onError && lastError) { + onError(lastError, payload); + } + }; +} +/** + * Create a conditional event handler + */ +function createConditionalHandler(condition, handler) { + return async (payload) => { + if (condition(payload)) { + await Promise.resolve(handler(payload)); + } + }; +} +/** + * Create a debounced event handler + */ +function createDebouncedHandler(handler, delay) { + let timeoutId = null; + let latestPayload = null; + return (payload) => { + latestPayload = payload; + if (timeoutId) { + clearTimeout(timeoutId); + } + timeoutId = setTimeout(async () => { + if (latestPayload) { + await Promise.resolve(handler(latestPayload)); + latestPayload = null; + } + timeoutId = null; + }, delay); + }; +} +/** + * Create a throttled event handler + */ +function createThrottledHandler(handler, interval) { + let lastExecution = 0; + let timeoutId = null; + return async (payload) => { + const now = Date.now(); + const timeSinceLastExecution = now - lastExecution; + if (timeSinceLastExecution >= interval) { + lastExecution = now; + await Promise.resolve(handler(payload)); + } + else { + if (timeoutId) { + clearTimeout(timeoutId); + } + timeoutId = setTimeout(async () => { + lastExecution = Date.now(); + await Promise.resolve(handler(payload)); + timeoutId = null; + }, interval - timeSinceLastExecution); + } + }; +} +/** + * Compose multiple event handlers into a single handler + */ +function composeHandlers(...handlers) { + return async (payload) => { + const promises = handlers.map(handler => Promise.resolve(handler(payload))); + await Promise.all(promises); + }; +} +/** + * Create an event handler with logging + */ +function createLoggingHandler(handler, logger) { + return async (payload) => { + const startTime = Date.now(); + try { + logger.log('info', 'Event handler starting', { payload }); + await Promise.resolve(handler(payload)); + const duration = Date.now() - startTime; + logger.log('info', 'Event handler completed', { duration, payload }); + } + catch (error) { + const duration = Date.now() - startTime; + logger.log('error', 'Event handler failed', { + error: error instanceof Error ? error.message : String(error), + duration, + payload + }); + throw error; + } + }; +} +// ===== SINGLETON INSTANCE ===== +/** + * Global event emitter instance + */ +let globalEventEmitter = null; +/** + * Get the global event emitter instance + */ +function getGlobalEventEmitter() { + if (globalEventEmitter === null) { + globalEventEmitter = new TypeSafeEventEmitterImpl(); + } + return globalEventEmitter; +} +/** + * Get the global event factory instance + */ +function getEventFactory() { + return new EventFactoryImpl(); +} +//# sourceMappingURL=event-emitter.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/event-emitter.js.map b/launchdarkly/node/dist/event-emitter.js.map new file mode 100644 index 00000000..6d737daf --- /dev/null +++ b/launchdarkly/node/dist/event-emitter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"event-emitter.js","sourceRoot":"","sources":["../event-emitter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAkUH,8CAuCC;AAKD,4DASC;AAKD,wDAsBC;AAKD,wDA0BC;AAKD,0CAOC;AAKD,oDAwBC;AAYD,sDAKC;AAKD,0CAEC;AAhfD;;;GAGG;AAEH,2CAeqB;AAErB,2CAA2C;AAE3C;;GAEG;AACH,MAAa,wBAAwB;IAArC;QACmB,aAAQ,GAAG,IAAI,GAAG,EAAoD,CAAC;QACvE,UAAK,GAAsB;YAC1C,aAAa,EAAE,CAAC;YAChB,eAAe,EAAE,EAA+B;YAChD,cAAc,EAAE,CAAC;YACjB,gBAAgB,EAAE,EAA+B;YACjD,MAAM,EAAE,EAAE;SACX,CAAC;IA4OJ,CAAC;IA1OC;;OAEG;IACI,EAAE,CACP,SAAY,EACZ,OAAwB,EACxB,UAAiD,EAAE;QAEnD,IAAI,CAAC,IAAA,4BAAgB,EAAC,SAAS,CAAC,EAAE,CAAC;YACjC,MAAM,IAAI,KAAK,CAAC,uBAAuB,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;QAC9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arkly/node/dist/event-examples.d.ts b/launchdarkly/node/dist/event-examples.d.ts new file mode 100644 index 00000000..f1020cb5 --- /dev/null +++ b/launchdarkly/node/dist/event-examples.d.ts @@ -0,0 +1,34 @@ +/** + * Example 1: Basic event emitter usage with type safety + */ +export declare function basicEventEmitterExample(): Promise; +/** + * Example 2: Multiple event types with different handlers + */ +export declare function multipleEventTypesExample(): Promise; +/** + * Example 3: Advanced handler utilities + */ +export declare function advancedHandlerUtilitiesExample(): Promise; +/** + * Example 4: Event subscriptions and management + */ +export declare function eventSubscriptionExample(): Promise; +/** + * Example 5: Integration with existing FlagEvent entity + */ +export declare function flagEventIntegrationExample(): Promise; +/** + * Example 6: Global event emitter usage + */ +export declare function globalEventEmitterExample(): Promise; +/** + * Example 7: Event categories and filtering + */ +export declare function eventCategoriesExample(): Promise; +/** + * Run all event system examples + */ +export declare function runEventExamples(): Promise; +export { basicEventEmitterExample, multipleEventTypesExample, advancedHandlerUtilitiesExample, eventSubscriptionExample, flagEventIntegrationExample, globalEventEmitterExample, eventCategoriesExample }; +//# sourceMappingURL=event-examples.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/event-examples.d.ts.map b/launchdarkly/node/dist/event-examples.d.ts.map new file mode 100644 index 00000000..4e8b33d0 --- /dev/null +++ b/launchdarkly/node/dist/event-examples.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"event-examples.d.ts","sourceRoot":"","sources":["../event-examples.ts"],"names":[],"mappings":"AA4CA;;GAEG;AACH,wBAAsB,wBAAwB,IAAI,OAAO,CAAC,IAAI,CAAC,CAiC9D;AAED;;GAEG;AACH,wBAAsB,yBAAyB,IAAI,OAAO,CAAC,IAAI,CAAC,CA6D/D;AAED;;GAEG;AACH,wBAAsB,+BAA+B,IAAI,OAAO,CAAC,IAAI,CAAC,CA6FrE;AAED;;GAEG;AACH,wBAAsB,wBAAwB,IAAI,OAAO,CAAC,IAAI,CAAC,CA6D9D;AAED;;GAEG;AACH,wBAAsB,2BAA2B,IAAI,OAAO,CAAC,IAAI,CAAC,CAsDjE;AAED;;GAEG;AACH,wBAAsB,yBAAyB,IAAI,OAAO,CAAC,IAAI,CAAC,CAmC/D;AAED;;GAEG;AACH,wBAAsB,sBAAsB,IAAI,OAAO,CAAC,IAAI,CAAC,CA+C5D;AAED;;GAEG;AACH,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CAiBtD;AAGD,OAAO,EACL,wBAAwB,EACxB,yBAAyB,EACzB,+BAA+B,EAC/B,wBAAwB,EACxB,2BAA2B,EAC3B,yBAAyB,EACzB,sBAAsB,EACvB,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/event-examples.js b/launchdarkly/node/dist/event-examples.js new file mode 100644 index 00000000..41221d6d --- /dev/null +++ b/launchdarkly/node/dist/event-examples.js @@ -0,0 +1,385 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.basicEventEmitterExample = basicEventEmitterExample; +exports.multipleEventTypesExample = multipleEventTypesExample; +exports.advancedHandlerUtilitiesExample = advancedHandlerUtilitiesExample; +exports.eventSubscriptionExample = eventSubscriptionExample; +exports.flagEventIntegrationExample = flagEventIntegrationExample; +exports.globalEventEmitterExample = globalEventEmitterExample; +exports.eventCategoriesExample = eventCategoriesExample; +exports.runEventExamples = runEventExamples; +/** + * Comprehensive examples demonstrating the type-safe event system with + * mapped types, generic event handlers, and proper type inference. + */ +const events_js_1 = require("./events.js"); +const event_emitter_js_1 = require("./event-emitter.js"); +// ===== BASIC USAGE EXAMPLES ===== +/** + * Example 1: Basic event emitter usage with type safety + */ +async function basicEventEmitterExample() { + console.log('=== Basic Event Emitter Example ==='); + const emitter = new event_emitter_js_1.TypeSafeEventEmitterImpl(); + const factory = new event_emitter_js_1.EventFactoryImpl(); + // Type-safe event handler with proper inference + const flagEvaluationHandler = async (payload) => { + console.log(`Flag ${payload.flagId} evaluated with value:`, payload.value); + console.log(`Timestamp: ${payload.timestamp.toISOString()}`); + if (payload.userId) { + console.log(`User: ${payload.userId}`); + } + }; + // Register handler with automatic type inference + const unsubscribe = emitter.on('flag:evaluation', flagEvaluationHandler); + // Create type-safe event payload + const evaluationEvent = factory.createFlagEvent('flag:evaluation', { + flagId: 'feature-x', + userId: 'user-123', + value: true, + reason: 'targeting rule matched' + }); + // Emit event with full type safety + await emitter.emit('flag:evaluation', evaluationEvent); + // Clean up + unsubscribe(); + console.log('Basic example completed\n'); +} +/** + * Example 2: Multiple event types with different handlers + */ +async function multipleEventTypesExample() { + console.log('=== Multiple Event Types Example ==='); + const emitter = new event_emitter_js_1.TypeSafeEventEmitterImpl(); + const factory = new event_emitter_js_1.EventFactoryImpl(); + // Handler for flag updates + const flagUpdateHandler = async (payload) => { + console.log(`Flag ${payload.flagId} updated:`); + console.log(` Previous: ${JSON.stringify(payload.previousValue)}`); + console.log(` New: ${JSON.stringify(payload.newValue)}`); + if (payload.reason) { + console.log(` Reason: ${payload.reason}`); + } + }; + // Handler for session starts + const sessionStartHandler = async (payload) => { + console.log(`Session ${payload.sessionId} started for user ${payload.userId}`); + if (payload.userAgent) { + console.log(` User Agent: ${payload.userAgent}`); + } + }; + // Handler for system errors + const errorHandler = async (payload) => { + console.error(`System error [${payload.severity}]:`, payload.error.message); + if (payload.operation) { + console.error(` Operation: ${payload.operation}`); + } + }; + // Register all handlers + emitter.on('flag:update', flagUpdateHandler); + emitter.on('session:start', sessionStartHandler); + emitter.on('system:error', errorHandler); + // Emit various events + await emitter.emit('flag:update', factory.createFlagEvent('flag:update', { + flagId: 'dark-mode', + userId: 'user-456', + previousValue: false, + newValue: true, + reason: 'user preference changed' + })); + await emitter.emit('session:start', factory.createSessionEvent('session:start', { + sessionId: 'session-789', + userId: 'user-456', + userAgent: 'Mozilla/5.0...', + ipAddress: '192.168.1.1' + })); + await emitter.emit('system:error', factory.createSystemEvent('system:error', { + error: new Error('Database connection failed'), + operation: 'user_authentication', + userId: 'user-456', + severity: 'high' + })); + console.log('Multiple event types example completed\n'); +} +/** + * Example 3: Advanced handler utilities + */ +async function advancedHandlerUtilitiesExample() { + console.log('=== Advanced Handler Utilities Example ==='); + const emitter = new event_emitter_js_1.TypeSafeEventEmitterImpl(); + const factory = new event_emitter_js_1.EventFactoryImpl(); + // Mock logger for demonstration + const logger = { + log: (level, message, meta) => { + console.log(`[${level.toUpperCase()}] ${message}`, meta ? JSON.stringify(meta) : ''); + } + }; + // Basic handler + const basicHandler = async (payload) => { + console.log(`Processing flag evaluation: ${payload.flagId}`); + }; + // Safe handler with retry logic + const safeHandler = (0, event_emitter_js_1.createSafeHandler)(basicHandler, { + retries: 2, + timeout: 1000, + onError: (error, payload) => { + console.error(`Handler failed for ${payload.flagId}:`, error.message); + } + }); + // Conditional handler + const conditionalHandler = (0, event_emitter_js_1.createConditionalHandler)((payload) => payload.value === true, // Only handle when flag is true + async (payload) => { + console.log(`Flag ${payload.flagId} is enabled!`); + }); + // Debounced handler (waits 500ms after last event) + const debouncedHandler = (0, event_emitter_js_1.createDebouncedHandler)(async (payload) => { + console.log(`Debounced processing for ${payload.flagId}`); + }, 500); + // Throttled handler (executes at most once per second) + const throttledHandler = (0, event_emitter_js_1.createThrottledHandler)(async (payload) => { + console.log(`Throttled processing for ${payload.flagId}`); + }, 1000); + // Composed handler (executes multiple handlers) + const composedHandler = (0, event_emitter_js_1.composeHandlers)(async (payload) => console.log(`Handler 1: ${payload.flagId}`), async (payload) => console.log(`Handler 2: ${payload.flagId}`), async (payload) => console.log(`Handler 3: ${payload.flagId}`)); + // Logging handler + const loggingHandler = (0, event_emitter_js_1.createLoggingHandler)(async (payload) => { + console.log(`Business logic for ${payload.flagId}`); + }, logger); + // Register handlers + emitter.on('flag:evaluation', safeHandler); + emitter.on('flag:evaluation', conditionalHandler); + emitter.on('flag:evaluation', debouncedHandler); + emitter.on('flag:evaluation', throttledHandler); + emitter.on('flag:evaluation', composedHandler); + emitter.on('flag:evaluation', loggingHandler); + // Emit test events + console.log('Emitting events...'); + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'test-flag-1', + value: true, + userId: 'user-test' + })); + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'test-flag-2', + value: false, + userId: 'user-test' + })); + // Wait a moment for debounced handlers + await new Promise(resolve => setTimeout(resolve, 600)); + console.log('Advanced handler utilities example completed\n'); +} +/** + * Example 4: Event subscriptions and management + */ +async function eventSubscriptionExample() { + console.log('=== Event Subscription Example ==='); + const emitter = new event_emitter_js_1.TypeSafeEventEmitterImpl(); + const factory = new event_emitter_js_1.EventFactoryImpl(); + // Create multiple subscriptions + const subscription1 = emitter.subscribe('flag:evaluation', async (payload) => { + console.log(`Subscription 1: Flag ${payload.flagId} evaluated`); + }, { priority: 10 }); + const subscription2 = emitter.subscribe('flag:evaluation', async (payload) => { + console.log(`Subscription 2: Flag ${payload.flagId} evaluated`); + }, { priority: 5 }); + // One-time handler + emitter.once('flag:update', async (payload) => { + console.log(`One-time handler: Flag ${payload.flagId} updated (this will only run once)`); + }); + console.log(`Event names with handlers: ${emitter.eventNames().join(', ')}`); + console.log(`Flag evaluation listener count: ${emitter.listenerCount('flag:evaluation')}`); + // Emit events + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'subscription-test', + value: 42, + userId: 'user-sub' + })); + await emitter.emit('flag:update', factory.createFlagEvent('flag:update', { + flagId: 'update-test', + previousValue: 'old', + newValue: 'new', + userId: 'user-sub' + })); + // Try to emit flag:update again (one-time handler won't run) + await emitter.emit('flag:update', factory.createFlagEvent('flag:update', { + flagId: 'update-test-2', + previousValue: 'old2', + newValue: 'new2', + userId: 'user-sub' + })); + // Unsubscribe + subscription1.unsubscribe(); + console.log(`After unsubscribing: ${emitter.listenerCount('flag:evaluation')} listeners`); + // Get stats + const stats = emitter.getStats(); + console.log('Event emitter stats:', { + totalHandlers: stats.totalHandlers, + totalEmissions: stats.totalEmissions, + errorCount: stats.errors.length + }); + // Clean up + subscription2.unsubscribe(); + console.log('Event subscription example completed\n'); +} +/** + * Example 5: Integration with existing FlagEvent entity + */ +async function flagEventIntegrationExample() { + console.log('=== Flag Event Integration Example ==='); + const emitter = new event_emitter_js_1.TypeSafeEventEmitterImpl(); + const factory = new event_emitter_js_1.EventFactoryImpl(); + // Handler that could persist events to database + const persistEventHandler = async (payload) => { + // This would typically use the repository to save to database + console.log('Persisting flag evaluation event:'); + console.log(` Flag ID: ${payload.flagId}`); + console.log(` User ID: ${payload.userId}`); + console.log(` Value: ${JSON.stringify(payload.value)}`); + console.log(` Timestamp: ${payload.timestamp.toISOString()}`); + console.log(` Context: ${JSON.stringify(payload.context)}`); + // Simulate database save + const flagEvent = { + id: `event_${Date.now()}`, + featureFlagId: payload.flagId, + userId: payload.userId, + eventType: 'evaluation', + newValue: payload.value, + context: payload.context, + createdAt: payload.timestamp + }; + console.log('Saved to database:', flagEvent); + }; + // Register the persistence handler + emitter.on('flag:evaluation', persistEventHandler); + // Emit events that would be persisted + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'premium-features', + userId: 'user-premium', + value: { enabled: true, plan: 'pro' }, + context: { + userAgent: 'Chrome/91.0', + location: 'US-East', + experiment: 'premium-rollout-v2' + } + })); + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'dark-theme', + userId: 'user-premium', + value: true, + defaultValue: false, + reason: 'user setting override' + })); + console.log('Flag event integration example completed\n'); +} +/** + * Example 6: Global event emitter usage + */ +async function globalEventEmitterExample() { + console.log('=== Global Event Emitter Example ==='); + // Use global singleton + const globalEmitter = (0, event_emitter_js_1.getGlobalEventEmitter)(); + const factory = (0, event_emitter_js_1.getEventFactory)(); + // Global handler for all system errors + globalEmitter.on('system:error', async (payload) => { + // This could send alerts, log to external services, etc. + console.log(`🚨 GLOBAL ERROR HANDLER: ${payload.error.message}`); + console.log(` Severity: ${payload.severity}`); + console.log(` Timestamp: ${payload.timestamp.toISOString()}`); + }); + // Global handler for all flag evaluations (for analytics) + globalEmitter.on('flag:evaluation', async (payload) => { + console.log(`📊 ANALYTICS: Flag ${payload.flagId} evaluated`); + // This could send to analytics service + }); + // Simulate some events + await globalEmitter.emit('system:error', factory.createSystemEvent('system:error', { + error: new Error('Redis connection timeout'), + severity: 'critical', + operation: 'cache_read' + })); + await globalEmitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'new-ui-rollout', + userId: 'analytics-user', + value: 'variant-b' + })); + console.log('Global event emitter example completed\n'); +} +/** + * Example 7: Event categories and filtering + */ +async function eventCategoriesExample() { + console.log('=== Event Categories Example ==='); + const emitter = new event_emitter_js_1.TypeSafeEventEmitterImpl(); + const factory = new event_emitter_js_1.EventFactoryImpl(); + console.log('Available event categories:'); + Object.entries(events_js_1.EVENT_CATEGORIES).forEach(([category, events]) => { + console.log(` ${category}: ${events.join(', ')}`); + }); + // Handler for all flag events + const flagEventHandler = async (payload) => { + console.log(`Flag event detected: ${JSON.stringify({ + type: 'flag_event', + flagId: payload.flagId, + timestamp: payload.timestamp + })}`); + }; + // Register handler for all flag event types + events_js_1.EVENT_CATEGORIES.flag.forEach((eventName) => { + emitter.on(eventName, flagEventHandler); + }); + // Emit various flag events + await emitter.emit('flag:create', factory.createFlagEvent('flag:create', { + flagId: 'new-feature', + initialValue: false, + userId: 'admin-user' + })); + await emitter.emit('flag:toggle', factory.createFlagEvent('flag:toggle', { + flagId: 'new-feature', + enabled: true, + previousState: false, + userId: 'admin-user' + })); + await emitter.emit('flag:delete', factory.createFlagEvent('flag:delete', { + flagId: 'old-feature', + finalValue: false, + reason: 'feature sunset', + userId: 'admin-user' + })); + console.log('Event categories example completed\n'); +} +/** + * Run all event system examples + */ +async function runEventExamples() { + console.log('🎯 Running Type-Safe Event System Examples\n'); + try { + await basicEventEmitterExample(); + await multipleEventTypesExample(); + await advancedHandlerUtilitiesExample(); + await eventSubscriptionExample(); + await flagEventIntegrationExample(); + await globalEventEmitterExample(); + await eventCategoriesExample(); + console.log('✅ All event system examples completed successfully!'); + } + catch (error) { + console.error('❌ Error running event examples:', error); + throw error; + } +} +//# sourceMappingURL=event-examples.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/event-examples.js.map b/launchdarkly/node/dist/event-examples.js.map new file mode 100644 index 00000000..5cf9e948 --- /dev/null +++ b/launchdarkly/node/dist/event-examples.js.map @@ -0,0 +1 @@ +{"version":3,"file":"event-examples.js","sourceRoot":"","sources":["../event-examples.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAiCH,4DAiCC;AAKD,8DA6DC;AAKD,0EA6FC;AAKD,4DA6DC;AAKD,kEAsDC;AAKD,8DAmCC;AAKD,wDA+CC;AAKD,4CAiBC;AAndD;;;GAGG;AAEH,2CAIqB;AAErB,yDAW4B;AAI5B,mCAAmC;AAEnC;;GAEG;AACI,KAAK,UAAU,wBAAwB;IAC5C,OAAO,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC;IAEnD,MAAM,OAAO,GAAG,IAAI,2CAAwB,EAAE,CAAC;IAC/C,MAAM,OAAO,GAAG,IAAI,mCAAgB,EAAE,CAAC;IAEvC,gDAAgD;IAChD,MAAM,qBAAqB,GAAoC,KAAK,EAAE,OAAO,EAAE,EAAE;QAC/E,OAAO,CAAC,GAAG,CAAC,QAAQ,OAAO,CAAC,MAAM,wBAAwB,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;QAC3E,OAAO,CAAC,GAAG,CAAC,cAAc,OAAO,CAAC,SAAS,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QAC7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CAAC,CAAC;IACrE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;QACxD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/events.d.ts b/launchdarkly/node/dist/events.d.ts new file mode 100644 index 00000000..dc4b7239 --- /dev/null +++ b/launchdarkly/node/dist/events.d.ts @@ -0,0 +1,321 @@ +/** + * Type-safe event system interfaces with mapped types for event payload definitions + * and generic event handler functions with proper type inference. + * + * This module provides: + * - Mapped types for event payload definitions + * - Generic event handler functions with proper type inference + * - Type-safe event emitter with subscription management + * - Integration with existing FlagEvent entity structure + */ +import { UserId } from "./types.js"; +/** + * Base event payload interface that all events must extend + */ +export interface BaseEventPayload { + readonly timestamp: Date; + readonly source?: string; + readonly context?: Record; +} +/** + * Feature flag related event payloads + */ +export interface FlagEvaluationPayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly value: unknown; + readonly defaultValue?: unknown; + readonly reason?: string; +} +export interface FlagUpdatePayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly previousValue: unknown; + readonly newValue: unknown; + readonly reason?: string; +} +export interface FlagCreatePayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly initialValue: unknown; + readonly configuration?: Record; +} +export interface FlagDeletePayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly finalValue?: unknown; + readonly reason?: string; +} +export interface FlagTogglePayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly enabled: boolean; + readonly previousState: boolean; +} +/** + * User session related event payloads + */ +export interface UserSessionStartPayload extends BaseEventPayload { + readonly sessionId: string; + readonly userId: UserId; + readonly userAgent?: string; + readonly ipAddress?: string; +} +export interface UserSessionEndPayload extends BaseEventPayload { + readonly sessionId: string; + readonly userId: UserId; + readonly duration: number; + readonly reason?: 'logout' | 'timeout' | 'error'; +} +/** + * System level event payloads + */ +export interface SystemErrorPayload extends BaseEventPayload { + readonly error: Error; + readonly operation?: string; + readonly userId?: UserId; + readonly severity: 'low' | 'medium' | 'high' | 'critical'; +} +export interface SystemHealthPayload extends BaseEventPayload { + readonly status: 'healthy' | 'degraded' | 'unhealthy'; + readonly metrics?: Record; + readonly checks?: Array<{ + name: string; + status: 'pass' | 'fail' | 'warn'; + duration?: number; + }>; +} +/** + * Complete event payload mapping using mapped types + * This ensures type safety for all event types and their corresponding payloads + */ +export interface EventPayloadMap { + 'flag:evaluation': FlagEvaluationPayload; + 'flag:update': FlagUpdatePayload; + 'flag:create': FlagCreatePayload; + 'flag:delete': FlagDeletePayload; + 'flag:toggle': FlagTogglePayload; + 'session:start': UserSessionStartPayload; + 'session:end': UserSessionEndPayload; + 'system:error': SystemErrorPayload; + 'system:health': SystemHealthPayload; +} +/** + * Extract event names from the payload map + */ +export type EventName = keyof EventPayloadMap; +/** + * Extract payload type for a specific event name + */ +export type EventPayload = EventPayloadMap[T]; +/** + * Utility type to check if an event name is valid + */ +export type IsValidEventName = T extends EventName ? true : false; +/** + * Extract event names by payload type category + */ +export type FlagEventNames = { + [K in EventName]: EventPayloadMap[K] extends FlagEvaluationPayload | FlagUpdatePayload | FlagCreatePayload | FlagDeletePayload | FlagTogglePayload ? K : never; +}[EventName]; +export type SessionEventNames = { + [K in EventName]: EventPayloadMap[K] extends UserSessionStartPayload | UserSessionEndPayload ? K : never; +}[EventName]; +export type SystemEventNames = { + [K in EventName]: EventPayloadMap[K] extends SystemErrorPayload | SystemHealthPayload ? K : never; +}[EventName]; +/** + * Generic event handler function with proper type inference + */ +export type EventHandler = (payload: EventPayload) => void | Promise; +/** + * Event handler with error handling capability + */ +export type SafeEventHandler = (payload: EventPayload) => Promise<{ + success: boolean; + error?: Error; +}>; +/** + * Event handler that can return a result + */ +export type EventHandlerWithResult = (payload: EventPayload) => R | Promise; +/** + * Conditional event handler based on payload properties + */ +export type ConditionalEventHandler = { + condition: (payload: EventPayload) => boolean; + handler: EventHandler; +}; +/** + * Map of event handlers for multiple event types + */ +export type EventHandlerMap = { + [K in EventName]?: EventHandler[]; +}; +/** + * Typed event handler collection with proper inference + */ +export type TypedEventHandlers> = { + [K in keyof T]?: EventHandler[]; +}; +/** + * Event handler registry with categorized handlers + */ +export interface EventHandlerRegistry { + flag: { + [K in FlagEventNames]?: EventHandler[]; + }; + session: { + [K in SessionEventNames]?: EventHandler[]; + }; + system: { + [K in SystemEventNames]?: EventHandler[]; + }; + global: EventHandler[]; +} +/** + * Extract handler function parameters for type checking + */ +export type HandlerParameters = Parameters>; +/** + * Extract handler return type + */ +export type HandlerReturnType = ReturnType>; +/** + * Ensure handler compatibility with event type + */ +export type EnsureHandlerCompatibility = H extends EventHandler ? H : never; +/** + * Create a union of all possible event handler functions + */ +export type AnyEventHandler = { + [K in EventName]: EventHandler; +}[EventName]; +/** + * Event handler with metadata + */ +export interface EventHandlerWithMetadata { + handler: EventHandler; + id: string; + priority?: number; + once?: boolean; + condition?: (payload: EventPayload) => boolean; + createdAt: Date; +} +/** + * Type-safe event emitter interface + */ +export interface TypeSafeEventEmitter { + /** + * Register an event handler for a specific event type + */ + on(eventName: T, handler: EventHandler, options?: { + priority?: number; + once?: boolean; + }): () => void; + /** + * Register a one-time event handler + */ + once(eventName: T, handler: EventHandler): void; + /** + * Remove a specific event handler + */ + off(eventName: T, handler: EventHandler): void; + /** + * Remove all handlers for an event type + */ + removeAllListeners(eventName: T): void; + /** + * Emit an event with proper type checking + */ + emit(eventName: T, payload: EventPayload): Promise; + /** + * Get the number of handlers for an event type + */ + listenerCount(eventName: T): number; + /** + * Get all event names that have handlers + */ + eventNames(): EventName[]; +} +/** + * Event subscription interface + */ +export interface EventSubscription { + readonly eventName: EventName; + readonly handlerId: string; + readonly createdAt: Date; + unsubscribe(): void; +} +/** + * Event emitter statistics + */ +export interface EventEmitterStats { + totalHandlers: number; + handlersByEvent: Record; + totalEmissions: number; + emissionsByEvent: Record; + errors: Array<{ + eventName: EventName; + error: Error; + timestamp: Date; + }>; +} +/** + * Event payload builder for type-safe event creation + */ +export interface EventPayloadBuilder { + build(): EventPayload; +} +/** + * Fluent event builder + */ +export type FluentEventBuilder = { + [K in keyof EventPayload]: (value: EventPayload[K]) => FluentEventBuilder; +} & EventPayloadBuilder; +/** + * Event factory for creating events with validation + */ +export interface EventFactory { + create(eventName: T, payload: Omit, 'timestamp'>): EventPayload; + createFlagEvent(eventName: T, payload: Omit, 'timestamp'>): EventPayload; + createSessionEvent(eventName: T, payload: Omit, 'timestamp'>): EventPayload; + createSystemEvent(eventName: T, payload: Omit, 'timestamp'>): EventPayload; +} +/** + * Convert FlagEvent entity to event payload + */ +export type FlagEventToPayload = T extends 'flag:evaluation' ? FlagEvaluationPayload : T extends 'flag:update' ? FlagUpdatePayload : T extends 'flag:create' ? FlagCreatePayload : T extends 'flag:delete' ? FlagDeletePayload : T extends 'flag:toggle' ? FlagTogglePayload : never; +/** + * Event payload validation result + */ +export interface EventPayloadValidationResult { + valid: boolean; + payload?: EventPayload; + errors?: string[]; +} +/** + * Event payload validator function + */ +export type EventPayloadValidator = (data: unknown) => EventPayloadValidationResult; +/** + * Type guard to check if a value is a valid event name + */ +export declare function isValidEventName(value: unknown): value is EventName; +/** + * Type guard to check if a handler is compatible with an event type + */ +export declare function isCompatibleHandler(eventName: T, handler: unknown): handler is EventHandler; +/** + * All valid event names for runtime validation + */ +export declare const EVENT_NAMES: Record; +/** + * Event name categories for easier filtering + */ +export declare const EVENT_CATEGORIES: { + readonly flag: readonly ["flag:evaluation", "flag:update", "flag:create", "flag:delete", "flag:toggle"]; + readonly session: readonly ["session:start", "session:end"]; + readonly system: readonly ["system:error", "system:health"]; +}; +//# sourceMappingURL=events.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/events.d.ts.map b/launchdarkly/node/dist/events.d.ts.map new file mode 100644 index 00000000..7d98e530 --- /dev/null +++ b/launchdarkly/node/dist/events.d.ts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AM,CAAC,SAAS,EAAE,IAAI,CAUtC,CAAC;AAEX;;GAEG;AACH,eAAO,MAAM,gBAAgB;;;;CAInB,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/events.js b/launchdarkly/node/dist/events.js new file mode 100644 index 00000000..7edb5e11 --- /dev/null +++ b/launchdarkly/node/dist/events.js @@ -0,0 +1,56 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EVENT_CATEGORIES = exports.EVENT_NAMES = void 0; +exports.isValidEventName = isValidEventName; +exports.isCompatibleHandler = isCompatibleHandler; +// ===== TYPE GUARDS AND UTILITIES ===== +/** + * Type guard to check if a value is a valid event name + */ +function isValidEventName(value) { + return typeof value === 'string' && value in exports.EVENT_NAMES; +} +/** + * Type guard to check if a handler is compatible with an event type + */ +function isCompatibleHandler(eventName, handler) { + return typeof handler === 'function'; +} +/** + * All valid event names for runtime validation + */ +exports.EVENT_NAMES = { + 'flag:evaluation': true, + 'flag:update': true, + 'flag:create': true, + 'flag:delete': true, + 'flag:toggle': true, + 'session:start': true, + 'session:end': true, + 'system:error': true, + 'system:health': true, +}; +/** + * Event name categories for easier filtering + */ +exports.EVENT_CATEGORIES = { + flag: ['flag:evaluation', 'flag:update', 'flag:create', 'flag:delete', 'flag:toggle'], + session: ['session:start', 'session:end'], + system: ['system:error', 'system:health'], +}; +//# sourceMappingURL=events.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/events.js.map b/launchdarkly/node/dist/events.js.map new file mode 100644 index 00000000..7101578c --- /dev/null +++ b/launchdarkly/node/dist/events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events.js","sourceRoot":"","sources":["../events.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAsZH,4CAEC;AAKD,kDAKC;AAjBD,wCAAwC;AAExC;;GAEG;AACH,SAAgB,gBAAgB,CAAC,KAAc;IAC7C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,IAAI,mBAAW,CAAC;AAC3D,CAAC;AAED;;GAEG;AACH,SAAgB,mBAAmB,CACjC,SAAY,EACZ,OAAgB;IAEhB,OAAO,OAAO,OAAO,KAAK,UAAU,CAAC;AACvC,CAAC;AAED;;GAEG;AACU,QAAA,WAAW,GAA4B;IAClD,iBAAiB,EAAE,IAAI;IACvB,aAAa,EAAE,IAAI;IACnB,aAAa,EAAE,IAAI;IACnB,aAAa,EAAE,IAAI;IACnB,aAAa,EAAE,IAAI;IACnB,eAAe,EAAE,IAAI;IACrB,aAAa,EAAE,IAAI;IACnB,cAAc,EAAE,IAAI;IACpB,eAAe,EAAE,IAAI;CACb,CAAC;AAEX;;GAEG;AACU,QAAA,gBAAgB,GAAG;IAC9B,IAAI,EAAE,CAAC,iBAAiB,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,CAAU;IAC9F,OAAO,EAAE,CAAC,eAAe,EAAE,aAAa,CAAU;IAClD,MAAM,EAAE,CAAC,cAAc,EAAE,eAAe,CAAU;CAC1C,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/examples.d.ts b/launchdarkly/node/dist/examples.d.ts new file mode 100644 index 00000000..72255978 --- /dev/null +++ b/launchdarkly/node/dist/examples.d.ts @@ -0,0 +1,161 @@ +import { Organization, User, FeatureFlag, UserFlag, CreateOrganizationInput, CreateUserInput, CreateFeatureFlagInput, UpdateOrganizationInput } from "./entities.js"; +import { DatabaseConnection } from "./database.js"; +import { IOrganizationRepository, IUserRepository, IFeatureFlagRepository, IUserFlagRepository } from "./repositories.js"; +import { WithRelations, OperationResult, BulkOperationResult } from "./types.js"; +type BrandedString = string & { + readonly __brand: T; +}; +type UserId = BrandedString<'UserId'>; +type FlagKey = BrandedString<'FlagKey'>; +type OrganizationId = BrandedString<'OrganizationId'>; +/** + * Organization service demonstrating type-safe CRUD operations + */ +declare class OrganizationService { + private organizationRepo; + constructor(organizationRepo: IOrganizationRepository); + /** + * Create a new organization with type-safe input validation + */ + createOrganization(input: CreateOrganizationInput): Promise>; + /** + * Update organization with partial input + */ + updateOrganization(id: OrganizationId, input: UpdateOrganizationInput): Promise>; + /** + * Get organization with related data + */ + getOrganizationWithStats(id: OrganizationId): Promise>; +} +/** + * User service with comprehensive user management + */ +declare class UserService { + private userRepo; + private organizationRepo; + constructor(userRepo: IUserRepository, organizationRepo: IOrganizationRepository); + /** + * Create user with organization validation + */ + createUser(input: CreateUserInput): Promise>; + /** + * Get user with all related data using type-safe relations + */ + getUserWithRelations(userId: UserId): Promise>>; + /** + * Bulk create users with validation + */ + createUsers(inputs: CreateUserInput[]): Promise>; +} +/** + * Feature flag service with advanced flag management + */ +declare class FeatureFlagService { + private flagRepo; + private userFlagRepo; + private organizationRepo; + constructor(flagRepo: IFeatureFlagRepository, userFlagRepo: IUserFlagRepository, organizationRepo: IOrganizationRepository); + /** + * Create feature flag with comprehensive validation + */ + createFeatureFlag(input: CreateFeatureFlagInput): Promise>; + /** + * Get flag value for user with fallback logic + */ + getFlagValueForUser(userId: UserId, flagKey: FlagKey): Promise>; + /** + * Set user-specific flag override + */ + setUserFlagOverride(userId: UserId, flagKey: FlagKey, value: unknown, reason?: string): Promise>; + /** + * Get flag usage statistics + */ + getFlagStats(flagId: string): Promise>; +} +/** + * DTO (Data Transfer Object) types for API responses + */ +interface OrganizationDto { + id: string; + name: string; + description?: string; + userCount: number; + flagCount: number; + isActive: boolean; + createdAt: string; +} +interface UserDto { + id: string; + key: string; + name: string; + email?: string; + kind: string; + organizationName?: string; + isActive: boolean; + lastLoginAt?: string; + createdAt: string; +} +interface FeatureFlagDto { + id: string; + key: string; + name: string; + description?: string; + valueType: string; + defaultValue: unknown; + isEnabled: boolean; + category?: string; + tags?: string[]; + environment: string; + createdAt: string; +} +/** + * Type-safe transformations between entities and DTOs + */ +declare const organizationTransform: import("./types.js").BiTransform; +declare const userTransform: import("./types.js").Transform; +declare const featureFlagTransform: import("./types.js").Transform; +/** + * Example application demonstrating complete type-safe database operations + */ +declare class FeatureFlagApplication { + private dbConnection; + private uow; + private organizationService; + private userService; + private flagService; + constructor(dbConnection: DatabaseConnection); + /** + * Complete example: Create organization, users, and feature flags + */ + setupExample(): Promise; + /** + * Demonstrate querying with relations and transformations + */ + demonstrateQueries(): Promise; + /** + * Demonstrate transaction usage + */ + demonstrateTransaction(): Promise; +} +/** + * Main function to run all examples + */ +export declare function runExamples(): Promise; +export { OrganizationService, UserService, FeatureFlagService, FeatureFlagApplication, organizationTransform, userTransform, featureFlagTransform }; +export type { OrganizationDto, UserDto, FeatureFlagDto }; +//# sourceMappingURL=examples.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/examples.d.ts.map b/launchdarkly/node/dist/examples.d.ts.map new file mode 100644 index 00000000..65b9d86f --- /dev/null +++ b/launchdarkly/node/dist/examples.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"examples.d.ts","sourceRoot":"","sources":["../examples.ts"],"names":[],"mappings":"AAsBA,OAAO,EACL,YAAY,EACZ,IAAI,EACJ,WAAW,EACX,QAAQ,EAGR,uBAAuB,EACvB,eAAe,EACf,sBAAsB,EAEtB,uBAAuB,EAKxB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,kBAAkB,EAInB,MAAM,eAAe,CAAC;AAEvB,OAAO,EAIL,uBAAuB,EACvB,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAKL,aAAa,EACb,eAAe,EAEf,mBAAmB,EAKpB,MAAM,YAAY,CAAC;AAIpB,KAAK,aAAa,CAAC,CAAC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9C;AAID;;GAEG;AACH,wBAAsB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAmCjD;AAGD,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,aAAa,EACb,oBAAoB,EACrB,CAAC;AAGF,YAAY,EACV,eAAe,EACf,OAAO,EACP,cAAc,EACf,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/examples.js b/launchdarkly/node/dist/examples.js new file mode 100644 index 00000000..bb9cf042 --- /dev/null +++ b/launchdarkly/node/dist/examples.js @@ -0,0 +1,682 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.featureFlagTransform = exports.userTransform = exports.organizationTransform = exports.FeatureFlagApplication = exports.FeatureFlagService = exports.UserService = exports.OrganizationService = void 0; +exports.runExamples = runExamples; +const entities_js_1 = require("./entities.js"); +const database_js_1 = require("./database.js"); +const repositories_js_1 = require("./repositories.js"); +const types_js_1 = require("./types.js"); +// ===== EXAMPLE SERVICES ===== +/** + * Organization service demonstrating type-safe CRUD operations + */ +class OrganizationService { + constructor(organizationRepo) { + this.organizationRepo = organizationRepo; + } + /** + * Create a new organization with type-safe input validation + */ + async createOrganization(input) { + try { + // Validate input using Zod schema + const validatedInput = entities_js_1.validateEntity.organization(input); + // Check if organization with same name already exists + const existing = await this.organizationRepo.findByName(validatedInput.name); + if (existing) { + return { + success: false, + error: new Error(`Organization with name '${validatedInput.name}' already exists`) + }; + } + // Create organization + const organization = await this.organizationRepo.create(validatedInput); + return { success: true, data: organization }; + } + catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to create organization') + }; + } + } + /** + * Update organization with partial input + */ + async updateOrganization(id, input) { + try { + // Validate that organization exists + const existing = await this.organizationRepo.findById(id); + if (!existing) { + return { + success: false, + error: new Error(`Organization with id '${id}' not found`) + }; + } + // Validate input if provided + if (input.name) { + const nameExists = await this.organizationRepo.findByName(input.name); + if (nameExists && nameExists.id !== id) { + return { + success: false, + error: new Error(`Organization with name '${input.name}' already exists`) + }; + } + } + // Update organization + const updated = await this.organizationRepo.update(id, input); + return { success: true, data: updated }; + } + catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to update organization') + }; + } + } + /** + * Get organization with related data + */ + async getOrganizationWithStats(id) { + try { + const organization = await this.organizationRepo.findById(id, ['users', 'featureFlags']); + if (!organization) { + return { + success: false, + error: new Error(`Organization with id '${id}' not found`) + }; + } + const [userCount, flagCount] = await Promise.all([ + this.organizationRepo.getUserCount(id), + this.organizationRepo.getFeatureFlagCount(id) + ]); + return { + success: true, + data: { ...organization, userCount, flagCount } + }; + } + catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to get organization') + }; + } + } +} +exports.OrganizationService = OrganizationService; +/** + * User service with comprehensive user management + */ +class UserService { + constructor(userRepo, organizationRepo) { + this.userRepo = userRepo; + this.organizationRepo = organizationRepo; + } + /** + * Create user with organization validation + */ + async createUser(input) { + try { + // Validate input + const validatedInput = entities_js_1.validateEntity.user(input); + // Validate organization if provided + if (validatedInput.organizationId) { + const orgExists = await this.organizationRepo.exists(validatedInput.organizationId); + if (!orgExists) { + return { + success: false, + error: new Error(`Organization with id '${validatedInput.organizationId}' not found`) + }; + } + } + // Check for duplicate key + const existingByKey = await this.userRepo.findByKey(validatedInput.key); + if (existingByKey) { + return { + success: false, + error: new Error(`User with key '${validatedInput.key}' already exists`) + }; + } + // Check for duplicate email + if (validatedInput.email) { + const existingByEmail = await this.userRepo.findByEmail(validatedInput.email); + if (existingByEmail) { + return { + success: false, + error: new Error(`User with email '${validatedInput.email}' already exists`) + }; + } + } + const user = await this.userRepo.create(validatedInput); + return { success: true, data: user }; + } + catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to create user') + }; + } + } + /** + * Get user with all related data using type-safe relations + */ + async getUserWithRelations(userId) { + try { + const user = await this.userRepo.findById(userId, [ + 'organization', + 'userFlags', + 'userFlags.featureFlag', + 'sessions' + ]); + if (!user) { + return { + success: false, + error: new Error(`User with id '${userId}' not found`) + }; + } + return { success: true, data: user }; + } + catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to get user') + }; + } + } + /** + * Bulk create users with validation + */ + async createUsers(inputs) { + const result = { + successful: [], + failed: [], + totalProcessed: inputs.length, + successCount: 0, + failureCount: 0 + }; + for (const input of inputs) { + try { + const userResult = await this.createUser(input); + if (userResult.success) { + result.successful.push(userResult.data); + result.successCount++; + } + else { + result.failed.push({ + item: input, + error: userResult.error + }); + result.failureCount++; + } + } + catch (error) { + result.failed.push({ + item: input, + error: error instanceof Error ? error : new Error('Unknown error') + }); + result.failureCount++; + } + } + return result; + } +} +exports.UserService = UserService; +/** + * Feature flag service with advanced flag management + */ +class FeatureFlagService { + constructor(flagRepo, userFlagRepo, organizationRepo) { + this.flagRepo = flagRepo; + this.userFlagRepo = userFlagRepo; + this.organizationRepo = organizationRepo; + } + /** + * Create feature flag with comprehensive validation + */ + async createFeatureFlag(input) { + try { + // Validate input + const validatedInput = entities_js_1.validateEntity.featureFlag(input); + // Validate organization if provided + if (validatedInput.organizationId) { + const orgExists = await this.organizationRepo.exists(validatedInput.organizationId); + if (!orgExists) { + return { + success: false, + error: new Error(`Organization with id '${validatedInput.organizationId}' not found`) + }; + } + } + // Check for duplicate key + const existingFlag = await this.flagRepo.findByKey(validatedInput.key); + if (existingFlag) { + return { + success: false, + error: new Error(`Feature flag with key '${validatedInput.key}' already exists`) + }; + } + const flag = await this.flagRepo.create(validatedInput); + return { success: true, data: flag }; + } + catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to create feature flag') + }; + } + } + /** + * Get flag value for user with fallback logic + */ + async getFlagValueForUser(userId, flagKey) { + try { + // First check for user-specific override + const userFlag = await this.flagRepo.getUserFlagValue(userId, flagKey); + if (userFlag && userFlag.isActive) { + return { + success: true, + data: { value: userFlag.value, source: 'user-override' } + }; + } + // Fallback to flag default value + const flag = await this.flagRepo.findByKey(flagKey); + if (!flag) { + return { + success: false, + error: new Error(`Feature flag with key '${flagKey}' not found`) + }; + } + if (!flag.isEnabled) { + return { + success: true, + data: { value: flag.defaultValue, source: 'flag-default' } + }; + } + return { + success: true, + data: { value: flag.defaultValue, source: 'flag-default' } + }; + } + catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to get flag value') + }; + } + } + /** + * Set user-specific flag override + */ + async setUserFlagOverride(userId, flagKey, value, reason) { + try { + // Validate that flag exists + const flag = await this.flagRepo.findByKey(flagKey); + if (!flag) { + return { + success: false, + error: new Error(`Feature flag with key '${flagKey}' not found`) + }; + } + // Set user flag override + const userFlag = await this.userFlagRepo.setUserFlag(userId, flag.id, value, reason); + return { success: true, data: userFlag }; + } + catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to set user flag override') + }; + } + } + /** + * Get flag usage statistics + */ + async getFlagStats(flagId) { + try { + const [stats, userFlags] = await Promise.all([ + this.flagRepo.getFlagUsageStats(flagId), + this.userFlagRepo.findByFlag(flagId) + ]); + return { + success: true, + data: { + ...stats, + userOverrides: userFlags.filter(uf => uf.isActive).length + } + }; + } + catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to get flag statistics') + }; + } + } +} +exports.FeatureFlagService = FeatureFlagService; +/** + * Type-safe transformations between entities and DTOs + */ +const organizationTransform = (0, types_js_1.createBiTransform)( +// To DTO +(entity) => ({ + id: entity.id, + name: entity.name, + description: entity.description, + userCount: entity.users?.length || 0, + flagCount: entity.featureFlags?.length || 0, + isActive: entity.isActive, + createdAt: entity.createdAt.toISOString() +}), +// From DTO (not typically used, but shows bi-directional capability) +(dto) => ({ + id: dto.id, + name: dto.name, + description: dto.description, + isActive: dto.isActive, + createdAt: new Date(dto.createdAt), + updatedAt: new Date(), + users: [], + featureFlags: [], + settings: undefined, + domain: undefined +})); +exports.organizationTransform = organizationTransform; +const userTransform = (0, types_js_1.createTransform)((entity) => ({ + id: entity.id, + key: entity.key, + name: entity.name, + email: entity.email, + kind: entity.kind, + organizationName: entity.organization?.name, + isActive: entity.isActive, + lastLoginAt: entity.lastLoginAt?.toISOString(), + createdAt: entity.createdAt.toISOString() +})); +exports.userTransform = userTransform; +const featureFlagTransform = (0, types_js_1.createTransform)((entity) => ({ + id: entity.id, + key: entity.key, + name: entity.name, + description: entity.description, + valueType: entity.valueType, + defaultValue: entity.defaultValue, + isEnabled: entity.isEnabled, + category: entity.category, + tags: entity.tags, + environment: entity.environment, + createdAt: entity.createdAt.toISOString() +})); +exports.featureFlagTransform = featureFlagTransform; +// ===== COMPLETE EXAMPLE APPLICATION ===== +/** + * Example application demonstrating complete type-safe database operations + */ +class FeatureFlagApplication { + constructor(dbConnection) { + this.dbConnection = dbConnection; + this.uow = (0, repositories_js_1.createUnitOfWork)(dbConnection); + this.organizationService = new OrganizationService(this.uow.Organizations); + this.userService = new UserService(this.uow.Users, this.uow.Organizations); + this.flagService = new FeatureFlagService(this.uow.FeatureFlags, this.uow.UserFlags, this.uow.Organizations); + } + /** + * Complete example: Create organization, users, and feature flags + */ + async setupExample() { + try { + console.log('Setting up example data...'); + // Create organization + const orgResult = await this.organizationService.createOrganization({ + name: 'Acme Corporation', + description: 'Example organization for demonstration', + domain: 'acme.com', + isActive: true, + settings: { + theme: 'light', + notifications: true + } + }); + if (!orgResult.success) { + throw orgResult.error; + } + const organization = orgResult.data; + console.log('Created organization:', organization.name); + // Create users + const userInputs = [ + { + key: 'user1', + name: 'John Doe', + email: 'john@acme.com', + kind: 'user', + organizationId: organization.id, + isActive: true, + custom: { + department: 'Engineering', + role: 'Developer' + } + }, + { + key: 'user2', + name: 'Jane Smith', + email: 'jane@acme.com', + kind: 'user', + organizationId: organization.id, + isActive: true, + custom: { + department: 'Product', + role: 'Manager' + } + } + ]; + const usersResult = await this.userService.createUsers(userInputs); + console.log(`Created ${usersResult.successCount} users, ${usersResult.failureCount} failed`); + // Create feature flags + const flagInputs = [ + { + key: 'dark-mode', + name: 'Dark Mode', + description: 'Enable dark mode theme', + valueType: 'boolean', + defaultValue: false, + isEnabled: true, + category: 'ui', + tags: ['theme', 'ui'], + organizationId: organization.id, + environment: 'production' + }, + { + key: 'beta-features', + name: 'Beta Features', + description: 'Enable beta features for testing', + valueType: 'boolean', + defaultValue: false, + isEnabled: false, + category: 'features', + tags: ['beta', 'experimental'], + organizationId: organization.id, + environment: 'staging' + } + ]; + for (const flagInput of flagInputs) { + const flagResult = await this.flagService.createFeatureFlag(flagInput); + if (flagResult.success) { + console.log('Created feature flag:', flagResult.data.name); + } + else { + console.error('Failed to create flag:', flagResult.error.message); + } + } + // Set user-specific overrides + if (usersResult.successful.length > 0) { + const user = usersResult.successful[0]; + const overrideResult = await this.flagService.setUserFlagOverride(user.id, 'dark-mode', true, 'User preference for dark mode'); + if (overrideResult.success) { + console.log('Set user flag override for dark mode'); + } + } + console.log('Example setup completed successfully!'); + } + catch (error) { + console.error('Failed to setup example:', error); + throw error; + } + } + /** + * Demonstrate querying with relations and transformations + */ + async demonstrateQueries() { + try { + console.log('Demonstrating type-safe queries...'); + // Get organizations with stats + const organizations = await this.uow.Organizations.findAll({}, ['users', 'featureFlags']); + console.log(`Found ${organizations.length} organizations`); + for (const org of organizations) { + const orgDto = organizationTransform.toDto(org); + console.log('Organization DTO:', JSON.stringify(orgDto, null, 2)); + // Get organization stats + const statsResult = await this.organizationService.getOrganizationWithStats(org.id); + if (statsResult.success) { + console.log('Organization stats:', { + userCount: statsResult.data.userCount, + flagCount: statsResult.data.flagCount + }); + } + } + // Query users with filters + const activeUsers = await this.uow.Users.findAll({ isActive: true }, ['organization']); + console.log(`Found ${activeUsers.length} active users`); + for (const user of activeUsers) { + const userDto = userTransform(user); + console.log('User DTO:', JSON.stringify(userDto, null, 2)); + // Get user with all relations + const userWithRelationsResult = await this.userService.getUserWithRelations(user.id); + if (userWithRelationsResult.success) { + console.log(`User ${user.name} has ${userWithRelationsResult.data.userFlags?.length || 0} flag overrides`); + } + } + // Query feature flags + const enabledFlags = await this.uow.FeatureFlags.findEnabledFlags(); + console.log(`Found ${enabledFlags.length} enabled flags`); + for (const flag of enabledFlags) { + const flagDto = featureFlagTransform(flag); + console.log('Flag DTO:', JSON.stringify(flagDto, null, 2)); + // Get flag statistics + const statsResult = await this.flagService.getFlagStats(flag.id); + if (statsResult.success) { + console.log('Flag stats:', statsResult.data); + } + } + console.log('Query demonstration completed!'); + } + catch (error) { + console.error('Failed to demonstrate queries:', error); + throw error; + } + } + /** + * Demonstrate transaction usage + */ + async demonstrateTransaction() { + try { + console.log('Demonstrating database transactions...'); + const result = await this.uow.executeTransaction(async (uow) => { + // Create organization + const org = await uow.Organizations.create({ + name: 'Transaction Test Org', + description: 'Created in transaction', + isActive: true + }); + // Create user in same transaction + const user = await uow.Users.create({ + key: 'transaction-user', + name: 'Transaction User', + email: 'transaction@test.com', + kind: 'user', + organizationId: org.id, + isActive: true + }); + // Create feature flag in same transaction + const flag = await uow.FeatureFlags.create({ + key: 'transaction-flag', + name: 'Transaction Flag', + description: 'Created in transaction', + valueType: 'boolean', + defaultValue: false, + isEnabled: true, + organizationId: org.id, + environment: 'test' + }); + return { org, user, flag }; + }); + console.log('Transaction completed successfully:', { + organizationId: result.org.id, + userId: result.user.id, + flagId: result.flag.id + }); + } + catch (error) { + console.error('Transaction failed:', error); + throw error; + } + } +} +exports.FeatureFlagApplication = FeatureFlagApplication; +// ===== MAIN EXAMPLE RUNNER ===== +/** + * Main function to run all examples + */ +async function runExamples() { + let dbConnection = null; + try { + // Initialize database + console.log('Initializing database connection...'); + dbConnection = await (0, database_js_1.initializeDatabase)((0, database_js_1.createDatabaseConfig)({ + DB_TYPE: 'postgres', + DB_HOST: 'localhost', + DB_PORT: '5432', + DB_USERNAME: 'postgres', + DB_PASSWORD: 'password', + DB_DATABASE: 'launchdarkly_example', + NODE_ENV: 'development' + })); + // Create application + const app = new FeatureFlagApplication(dbConnection); + // Run examples + await app.setupExample(); + await app.demonstrateQueries(); + await app.demonstrateTransaction(); + console.log('All examples completed successfully!'); + } + catch (error) { + console.error('Examples failed:', error); + throw error; + } + finally { + // Clean up + if (dbConnection) { + await (0, database_js_1.closeDatabase)(); + console.log('Database connection closed'); + } + } +} +// Run examples if this file is executed directly +if (import.meta.url === `file://${process.argv[1]}`) { + runExamples().catch(console.error); +} +//# sourceMappingURL=examples.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/examples.js.map b/launchdarkly/node/dist/examples.js.map new file mode 100644 index 00000000..080b7b93 --- /dev/null +++ b/launchdarkly/node/dist/examples.js.map @@ -0,0 +1 @@ +{"version":3,"file":"examples.js","sourceRoot":"","sources":["../examples.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAyyBH,kCAmCC;AAp0BD,+CAgBuB;AAEvB,+CAKuB;AAEvB,uDAQ2B;AAE3B,yCAaoB;AASpB,+BAA+B;AAE/B;;GAEG;AACH,MAAM,mBAAmB;IACvB,YAAoB,gBAAyC;QAAzC,qBAAgB,GAAhB,gBAAgB,CAAyB;IAAG,CAAC;IAEjE;;OAEG;IACH,KAAK,CAAC,kBAAkB,CAAC,KAA8B;QACrD,IAAI,CAAC;YACH,kCAAkC;YAClC,MAAM,cAAc,GAAG,4BAAc,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;YAE1D,sDAAsD;YACtD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,UAAU,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;YAC7E,IAAI,QAAQ,EAAE,CAAC;gBACb,OAAO;oBACL,OAAO,EAAE,KAAK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AAC,CAAC;QACnD,YAAY,GAAG,MAAM,IAAA,gCAAkB,EAAC,IAAA,kCAAoB,EAAC;YAC3D,OAAO,EAAE,UAAU;YACnB,OAAO,EAAE,WAAW;YACpB,OAAO,EAAE,MAAM;YACf,WAAW,EAAE,UAAU;YACvB,WAAW,EAAE,UAAU;YACvB,WAAW,EAAE,sBAAsB;YACnC,QAAQ,EAAE,aAAa;SACxB,CAAC,CAAC,CAAC;QAEJ,qBAAqB;QACrB,MAAM,GAAG,GAAG,IAAI,sBAAsB,CAAC,YAAY,CAAC,CAAC;QAErD,eAAe;QACf,MAAM,GAAG,CAAC,YAAY,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,kBAAkB,EAAE,CAAC;QAC/B,MAAM,GAAG,CAAC,sBAAsB,EAAE,CAAC;QAEnC,OAAO,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;IACtD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;QACzC,MAAM,KAAK,CAAC;IACd,CAAC;YAAS,CAAC;QACT,WAAW;QACX,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,IAAA,2BAAa,GAAE,CAAC;YACtB,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;AACH,CAAC;AAoBD,iDAAiD;AACjD,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,UAAU,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IACpD,WAAW,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/index.d.ts b/launchdarkly/node/dist/index.d.ts new file mode 100644 index 00000000..a98cfe1f --- /dev/null +++ b/launchdarkly/node/dist/index.d.ts @@ -0,0 +1,141 @@ +/** + * Type-safe database entity definitions using TypeORM decorators + * with comprehensive utility types for create/update input types. + * + * This module provides: + * - TypeORM entity definitions with proper decorators + * - Type-safe repository patterns + * - Advanced utility types for CRUD operations + * - Database connection management + * - Transaction support + * - Validation schemas using Zod + * - Type-safe event system with mapped types + * - Generic event handler functions with proper type inference + * - Comprehensive examples + */ +export { Organization, User, FeatureFlag, UserFlag, UserSession, FlagEvent, CreateOrganizationInput, CreateUserInput, CreateFeatureFlagInput, CreateUserFlagInput, CreateUserSessionInput, CreateFlagEventInput, UpdateOrganizationInput, UpdateUserInput, UpdateFeatureFlagInput, UpdateUserFlagInput, UpdateUserSessionInput, OrganizationFilters, UserFilters, FeatureFlagFilters, UserFlagFilters, EntityRelations, EntityValidationSchemas, validateEntity } from "./entities.js"; +export { DatabaseConnection, createDatabaseConfig, initializeDatabase, closeDatabase, getDatabase, TypeSafeQueryBuilder, RepositoryFactory, createPaginatedQuery, DatabaseError, ValidationError, handleDatabaseError } from "./database.js"; +export { IOrganizationRepository, IUserRepository, IFeatureFlagRepository, IUserFlagRepository, IUserSessionRepository, IFlagEventRepository, OrganizationRepository, UserRepository, FeatureFlagRepository, UserFlagRepository, UserSessionRepository, FlagEventRepository, RepositoryProvider, createRepositoryProvider, UnitOfWork, createUnitOfWork } from "./repositories.js"; +export { OptionalKeys, RequiredKeys, RequireOnly, OptionalOnly, DeepPartial, DeepRequired, NonFunctionProperties, PrimitiveProperties, DatabaseManagedFields, ReadonlyFields, CreateInput, UpdateInput, PatchInput, ReplaceInput, UpsertInput, FilterInput, SortInput, ProjectionInput, RelationFields, RelationOptions, WithRelations, InferZodSchema, ValidationSchema, Transform, BiTransform, NullableFields, OptionalNullableInput, DeepMerge, ArrayElement, Lookup, KeyValuePair, OperationResult, AsyncOperationResult, PaginatedResult, BulkOperationResult, ComparisonOperator, FieldFilter, AdvancedFilterInput, AggregationPipeline, EntityFromRepository, EntityConstructor, EntityMetadata, ColumnDefinition, TableDefinition, MigrationOperation, TableChange, AssertEqual, AssertExtends, TypeTest, ExampleEntity, ExampleCreateInput, ExampleUpdateInput, ExampleFilterInput, ExampleRelationOptions, isDefined, isNonEmptyString, isPositiveNumber, createTransform, createBiTransform, deepMerge, pickDefined, createLookup } from "./types.js"; +export { OrganizationService, UserService, FeatureFlagService, FeatureFlagApplication, organizationTransform, userTransform, featureFlagTransform, runExamples, OrganizationDto, UserDto, FeatureFlagDto } from "./examples.js"; +export { BaseEventPayload, FlagEvaluationPayload, FlagUpdatePayload, FlagCreatePayload, FlagDeletePayload, FlagTogglePayload, UserSessionStartPayload, UserSessionEndPayload, SystemErrorPayload, SystemHealthPayload, EventPayloadMap, EventName, EventPayload, EventHandler, SafeEventHandler, EventHandlerWithResult, ConditionalEventHandler, EventHandlerMap, TypedEventHandlers, EventHandlerRegistry, EventHandlerWithMetadata, TypeSafeEventEmitter, EventSubscription, EventEmitterStats, EventFactory, FlagEventNames, SessionEventNames, SystemEventNames, isValidEventName, isCompatibleHandler, EVENT_NAMES, EVENT_CATEGORIES } from "./events.js"; +export { TypeSafeEventEmitterImpl as TypeSafeEventEmitter, EventFactoryImpl as EventFactory, createSafeHandler, createConditionalHandler, createDebouncedHandler, createThrottledHandler, composeHandlers, createLoggingHandler, getGlobalEventEmitter, getEventFactory } from "./event-emitter.js"; +export { runEventExamples, basicEventEmitterExample, multipleEventTypesExample, advancedHandlerUtilitiesExample, eventSubscriptionExample, flagEventIntegrationExample, globalEventEmitterExample, eventCategoriesExample } from "./event-examples.js"; +/** + * Branded types for type safety + */ +export type BrandedString = string & { + readonly __brand: T; +}; +export type UserId = BrandedString<'UserId'>; +export type FlagKey = BrandedString<'FlagKey'>; +export type OrganizationId = BrandedString<'OrganizationId'>; +export type SessionId = BrandedString<'SessionId'>; +export type EnvironmentKey = BrandedString<'EnvironmentKey'>; +/** + * Common pagination options + */ +export interface PaginationOptions { + page: number; + limit: number; + sortBy?: string; + sortOrder: 'ASC' | 'DESC'; +} +/** + * Database configuration type + */ +export interface DatabaseConfig { + type: 'postgres' | 'mysql' | 'sqlite' | 'mongodb'; + host: string; + port: number; + username: string; + password: string; + database: string; + synchronize: boolean; + logging: boolean; + ssl: boolean | Record; + maxConnections: number; + acquireTimeout: number; + timeout: number; + migrationsRun: boolean; +} +/** + * Quick start function to initialize a complete type-safe database setup + */ +export declare function quickStart(config?: Partial): Promise<{ + connection: DatabaseConnection; + repositories: RepositoryProvider; + unitOfWork: UnitOfWork; +}>; +/** + * Create a complete service layer with all repositories + */ +export declare function createServiceLayer(unitOfWork: UnitOfWork): { + organizations: any; + users: any; + featureFlags: any; +}; +/** + * Usage example: + * + * ```typescript + * import { quickStart, createServiceLayer, runExamples } from './index.js'; + * + * // Quick start + * const { connection, repositories, unitOfWork } = await quickStart({ + * type: 'postgres', + * host: 'localhost', + * port: 5432, + * username: 'postgres', + * password: 'password', + * database: 'myapp' + * }); + * + * // Create services + * const services = createServiceLayer(unitOfWork); + * + * // Use type-safe operations + * const orgResult = await services.organizations.createOrganization({ + * name: 'My Company', + * description: 'My awesome company', + * isActive: true + * }); + * + * if (orgResult.success) { + * console.log('Created organization:', orgResult.data.name); + * } + * + * // Run complete examples + * await runExamples(); + * ``` + */ +/** + * Package metadata + */ +export declare const VERSION = "1.0.0"; +export declare const DESCRIPTION = "Type-safe database entity definitions using TypeORM decorators with comprehensive utility types and type-safe event system"; +export declare const AUTHOR = "Gitar, Inc."; +export declare const LICENSE = "Apache-2.0"; +/** + * Feature flags for the module + */ +export declare const FEATURES: { + readonly TYPEORM_DECORATORS: true; + readonly TYPE_SAFE_REPOSITORIES: true; + readonly ADVANCED_UTILITY_TYPES: true; + readonly VALIDATION_SCHEMAS: true; + readonly TRANSACTION_SUPPORT: true; + readonly RELATION_LOADING: true; + readonly PAGINATION_SUPPORT: true; + readonly ERROR_HANDLING: true; + readonly EXAMPLES_INCLUDED: true; + readonly TYPE_SAFE_EVENT_SYSTEM: true; + readonly EVENT_EMITTER: true; + readonly EVENT_SUBSCRIPTIONS: true; + readonly GENERIC_EVENT_HANDLERS: true; +}; +/** + * Export all features as a constant for runtime checks + */ +export declare const SUPPORTED_FEATURES: Array; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/index.d.ts.map b/launchdarkly/node/dist/index.d.ts.map new file mode 100644 index 00000000..d1d9a88b --- /dev/null +++ b/launchdarkly/node/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAgBA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAEL,YAAY,EACZ,IAAI,EACJ,WAAW,EACX,QAAQ,EACR,WAAW,EACX,SAAS,EAGT,uBAAuB,EACvB,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EACtB,oBAAoB,EAGpB,uBAAuB,EACvB,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EAGtB,mBAAmB,EACnB,WAAW,EACX,kBAAkB,EAClB,eAAe,EAGf,eAAe,EAGf,uBAAuB,EACvB,cAAc,EACf,MAAM,eAAe,CAAC;AAGvB,OAAO,EAEL,kBAAkB,EAGlB,oBAAoB,EAGpB,kBAAkB,EAClB,aAAa,EACb,WAAW,EAGX,oBAAoB,EAGpB,iBAAiB,EAGjB,oBAAoB,EAGpB,aAAa,EACb,eAAe,EACf,mBAAmB,EACpB,MAAM,eAAe,CAAC;AAGvB,OAAO,EAEL,uBAAuB,EACvB,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EACtB,oBAAoB,EAGpB,sBAAsB,EACtB,cAAc,EACd,qBAAqB,EACrB,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EAGnB,kBAAkB,EAClB,wBAAwB,EAGxB,UAAU,EACV,gBAAgB,EACjB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAEL,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,qBAAqB,EACrB,mBAAmB,EAGnB,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,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,OAAO,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,GAAG,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACvC,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,OAAO,CAAC;CACxB;AAID;;GAEG;AACH,wBAAsB,UAAU,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC;IAC1E,UAAU,EAAE,kBAAkB,CAAC;IAC/B,YAAY,EAAE,kBAAkB,CAAC;IACjC,UAAU,EAAE,UAAU,CAAC;CACxB,CAAC,CAMD;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU;;;;EAUxD;AAID;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAIH;;GAEG;AACH,eAAO,MAAM,OAAO,UAAU,CAAC;AAC/B,eAAO,MAAM,WAAW,+HAA+H,CAAC;AACxJ,eAAO,MAAM,MAAM,gBAAgB,CAAC;AACpC,eAAO,MAAM,OAAO,eAAe,CAAC;AAEpC;;GAEG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;CAcX,CAAC;AAEX;;GAEG;AACH,eAAO,MAAM,kBAAkB,EAA4B,KAAK,CAAC,MAAM,OAAO,QAAQ,CAAC,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/index.js b/launchdarkly/node/dist/index.js new file mode 100644 index 00000000..88790239 --- /dev/null +++ b/launchdarkly/node/dist/index.js @@ -0,0 +1,224 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeSafeEventEmitter = exports.EVENT_CATEGORIES = exports.EVENT_NAMES = exports.isCompatibleHandler = exports.isValidEventName = exports.runExamples = exports.featureFlagTransform = exports.userTransform = exports.organizationTransform = exports.FeatureFlagApplication = exports.FeatureFlagService = exports.UserService = exports.OrganizationService = exports.createLookup = exports.pickDefined = exports.deepMerge = exports.createBiTransform = exports.createTransform = exports.isPositiveNumber = exports.isNonEmptyString = exports.isDefined = exports.createUnitOfWork = exports.UnitOfWork = exports.createRepositoryProvider = exports.RepositoryProvider = exports.FlagEventRepository = exports.UserSessionRepository = exports.UserFlagRepository = exports.FeatureFlagRepository = exports.UserRepository = exports.OrganizationRepository = exports.handleDatabaseError = exports.ValidationError = exports.DatabaseError = exports.createPaginatedQuery = exports.RepositoryFactory = exports.TypeSafeQueryBuilder = exports.getDatabase = exports.closeDatabase = exports.initializeDatabase = exports.createDatabaseConfig = exports.DatabaseConnection = exports.validateEntity = exports.EntityValidationSchemas = exports.FlagEvent = exports.UserSession = exports.UserFlag = exports.FeatureFlag = exports.User = exports.Organization = void 0; +exports.SUPPORTED_FEATURES = exports.FEATURES = exports.LICENSE = exports.AUTHOR = exports.DESCRIPTION = exports.VERSION = exports.eventCategoriesExample = exports.globalEventEmitterExample = exports.flagEventIntegrationExample = exports.eventSubscriptionExample = exports.advancedHandlerUtilitiesExample = exports.multipleEventTypesExample = exports.basicEventEmitterExample = exports.runEventExamples = exports.getEventFactory = exports.getGlobalEventEmitter = exports.createLoggingHandler = exports.composeHandlers = exports.createThrottledHandler = exports.createDebouncedHandler = exports.createConditionalHandler = exports.createSafeHandler = exports.EventFactory = void 0; +exports.quickStart = quickStart; +exports.createServiceLayer = createServiceLayer; +/** + * Type-safe database entity definitions using TypeORM decorators + * with comprehensive utility types for create/update input types. + * + * This module provides: + * - TypeORM entity definitions with proper decorators + * - Type-safe repository patterns + * - Advanced utility types for CRUD operations + * - Database connection management + * - Transaction support + * - Validation schemas using Zod + * - Type-safe event system with mapped types + * - Generic event handler functions with proper type inference + * - Comprehensive examples + */ +// ===== ENTITIES ===== +var entities_js_1 = require("./entities.js"); +// Entity classes +Object.defineProperty(exports, "Organization", { enumerable: true, get: function () { return entities_js_1.Organization; } }); +Object.defineProperty(exports, "User", { enumerable: true, get: function () { return entities_js_1.User; } }); +Object.defineProperty(exports, "FeatureFlag", { enumerable: true, get: function () { return entities_js_1.FeatureFlag; } }); +Object.defineProperty(exports, "UserFlag", { enumerable: true, get: function () { return entities_js_1.UserFlag; } }); +Object.defineProperty(exports, "UserSession", { enumerable: true, get: function () { return entities_js_1.UserSession; } }); +Object.defineProperty(exports, "FlagEvent", { enumerable: true, get: function () { return entities_js_1.FlagEvent; } }); +// Validation schemas +Object.defineProperty(exports, "EntityValidationSchemas", { enumerable: true, get: function () { return entities_js_1.EntityValidationSchemas; } }); +Object.defineProperty(exports, "validateEntity", { enumerable: true, get: function () { return entities_js_1.validateEntity; } }); +// ===== DATABASE CONNECTION ===== +var database_js_1 = require("./database.js"); +// Database connection class +Object.defineProperty(exports, "DatabaseConnection", { enumerable: true, get: function () { return database_js_1.DatabaseConnection; } }); +// Configuration +Object.defineProperty(exports, "createDatabaseConfig", { enumerable: true, get: function () { return database_js_1.createDatabaseConfig; } }); +// Connection management +Object.defineProperty(exports, "initializeDatabase", { enumerable: true, get: function () { return database_js_1.initializeDatabase; } }); +Object.defineProperty(exports, "closeDatabase", { enumerable: true, get: function () { return database_js_1.closeDatabase; } }); +Object.defineProperty(exports, "getDatabase", { enumerable: true, get: function () { return database_js_1.getDatabase; } }); +// Query builder +Object.defineProperty(exports, "TypeSafeQueryBuilder", { enumerable: true, get: function () { return database_js_1.TypeSafeQueryBuilder; } }); +// Repository factory +Object.defineProperty(exports, "RepositoryFactory", { enumerable: true, get: function () { return database_js_1.RepositoryFactory; } }); +// Pagination utilities +Object.defineProperty(exports, "createPaginatedQuery", { enumerable: true, get: function () { return database_js_1.createPaginatedQuery; } }); +// Error handling +Object.defineProperty(exports, "DatabaseError", { enumerable: true, get: function () { return database_js_1.DatabaseError; } }); +Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return database_js_1.ValidationError; } }); +Object.defineProperty(exports, "handleDatabaseError", { enumerable: true, get: function () { return database_js_1.handleDatabaseError; } }); +// ===== REPOSITORIES ===== +var repositories_js_1 = require("./repositories.js"); +// Repository implementations +Object.defineProperty(exports, "OrganizationRepository", { enumerable: true, get: function () { return repositories_js_1.OrganizationRepository; } }); +Object.defineProperty(exports, "UserRepository", { enumerable: true, get: function () { return repositories_js_1.UserRepository; } }); +Object.defineProperty(exports, "FeatureFlagRepository", { enumerable: true, get: function () { return repositories_js_1.FeatureFlagRepository; } }); +Object.defineProperty(exports, "UserFlagRepository", { enumerable: true, get: function () { return repositories_js_1.UserFlagRepository; } }); +Object.defineProperty(exports, "UserSessionRepository", { enumerable: true, get: function () { return repositories_js_1.UserSessionRepository; } }); +Object.defineProperty(exports, "FlagEventRepository", { enumerable: true, get: function () { return repositories_js_1.FlagEventRepository; } }); +// Repository provider +Object.defineProperty(exports, "RepositoryProvider", { enumerable: true, get: function () { return repositories_js_1.RepositoryProvider; } }); +Object.defineProperty(exports, "createRepositoryProvider", { enumerable: true, get: function () { return repositories_js_1.createRepositoryProvider; } }); +// Unit of work pattern +Object.defineProperty(exports, "UnitOfWork", { enumerable: true, get: function () { return repositories_js_1.UnitOfWork; } }); +Object.defineProperty(exports, "createUnitOfWork", { enumerable: true, get: function () { return repositories_js_1.createUnitOfWork; } }); +// ===== UTILITY TYPES ===== +var types_js_1 = require("./types.js"); +// Utility functions +Object.defineProperty(exports, "isDefined", { enumerable: true, get: function () { return types_js_1.isDefined; } }); +Object.defineProperty(exports, "isNonEmptyString", { enumerable: true, get: function () { return types_js_1.isNonEmptyString; } }); +Object.defineProperty(exports, "isPositiveNumber", { enumerable: true, get: function () { return types_js_1.isPositiveNumber; } }); +Object.defineProperty(exports, "createTransform", { enumerable: true, get: function () { return types_js_1.createTransform; } }); +Object.defineProperty(exports, "createBiTransform", { enumerable: true, get: function () { return types_js_1.createBiTransform; } }); +Object.defineProperty(exports, "deepMerge", { enumerable: true, get: function () { return types_js_1.deepMerge; } }); +Object.defineProperty(exports, "pickDefined", { enumerable: true, get: function () { return types_js_1.pickDefined; } }); +Object.defineProperty(exports, "createLookup", { enumerable: true, get: function () { return types_js_1.createLookup; } }); +// ===== EXAMPLES ===== +var examples_js_1 = require("./examples.js"); +// Service classes +Object.defineProperty(exports, "OrganizationService", { enumerable: true, get: function () { return examples_js_1.OrganizationService; } }); +Object.defineProperty(exports, "UserService", { enumerable: true, get: function () { return examples_js_1.UserService; } }); +Object.defineProperty(exports, "FeatureFlagService", { enumerable: true, get: function () { return examples_js_1.FeatureFlagService; } }); +Object.defineProperty(exports, "FeatureFlagApplication", { enumerable: true, get: function () { return examples_js_1.FeatureFlagApplication; } }); +// Transformation functions +Object.defineProperty(exports, "organizationTransform", { enumerable: true, get: function () { return examples_js_1.organizationTransform; } }); +Object.defineProperty(exports, "userTransform", { enumerable: true, get: function () { return examples_js_1.userTransform; } }); +Object.defineProperty(exports, "featureFlagTransform", { enumerable: true, get: function () { return examples_js_1.featureFlagTransform; } }); +// Main example runner +Object.defineProperty(exports, "runExamples", { enumerable: true, get: function () { return examples_js_1.runExamples; } }); +// ===== EVENT SYSTEM ===== +var events_js_1 = require("./events.js"); +// Type guards and utilities +Object.defineProperty(exports, "isValidEventName", { enumerable: true, get: function () { return events_js_1.isValidEventName; } }); +Object.defineProperty(exports, "isCompatibleHandler", { enumerable: true, get: function () { return events_js_1.isCompatibleHandler; } }); +Object.defineProperty(exports, "EVENT_NAMES", { enumerable: true, get: function () { return events_js_1.EVENT_NAMES; } }); +Object.defineProperty(exports, "EVENT_CATEGORIES", { enumerable: true, get: function () { return events_js_1.EVENT_CATEGORIES; } }); +var event_emitter_js_1 = require("./event-emitter.js"); +// Event emitter implementation +Object.defineProperty(exports, "TypeSafeEventEmitter", { enumerable: true, get: function () { return event_emitter_js_1.TypeSafeEventEmitterImpl; } }); +Object.defineProperty(exports, "EventFactory", { enumerable: true, get: function () { return event_emitter_js_1.EventFactoryImpl; } }); +// Event handler utilities +Object.defineProperty(exports, "createSafeHandler", { enumerable: true, get: function () { return event_emitter_js_1.createSafeHandler; } }); +Object.defineProperty(exports, "createConditionalHandler", { enumerable: true, get: function () { return event_emitter_js_1.createConditionalHandler; } }); +Object.defineProperty(exports, "createDebouncedHandler", { enumerable: true, get: function () { return event_emitter_js_1.createDebouncedHandler; } }); +Object.defineProperty(exports, "createThrottledHandler", { enumerable: true, get: function () { return event_emitter_js_1.createThrottledHandler; } }); +Object.defineProperty(exports, "composeHandlers", { enumerable: true, get: function () { return event_emitter_js_1.composeHandlers; } }); +Object.defineProperty(exports, "createLoggingHandler", { enumerable: true, get: function () { return event_emitter_js_1.createLoggingHandler; } }); +// Global instances +Object.defineProperty(exports, "getGlobalEventEmitter", { enumerable: true, get: function () { return event_emitter_js_1.getGlobalEventEmitter; } }); +Object.defineProperty(exports, "getEventFactory", { enumerable: true, get: function () { return event_emitter_js_1.getEventFactory; } }); +var event_examples_js_1 = require("./event-examples.js"); +// Event system examples +Object.defineProperty(exports, "runEventExamples", { enumerable: true, get: function () { return event_examples_js_1.runEventExamples; } }); +Object.defineProperty(exports, "basicEventEmitterExample", { enumerable: true, get: function () { return event_examples_js_1.basicEventEmitterExample; } }); +Object.defineProperty(exports, "multipleEventTypesExample", { enumerable: true, get: function () { return event_examples_js_1.multipleEventTypesExample; } }); +Object.defineProperty(exports, "advancedHandlerUtilitiesExample", { enumerable: true, get: function () { return event_examples_js_1.advancedHandlerUtilitiesExample; } }); +Object.defineProperty(exports, "eventSubscriptionExample", { enumerable: true, get: function () { return event_examples_js_1.eventSubscriptionExample; } }); +Object.defineProperty(exports, "flagEventIntegrationExample", { enumerable: true, get: function () { return event_examples_js_1.flagEventIntegrationExample; } }); +Object.defineProperty(exports, "globalEventEmitterExample", { enumerable: true, get: function () { return event_examples_js_1.globalEventEmitterExample; } }); +Object.defineProperty(exports, "eventCategoriesExample", { enumerable: true, get: function () { return event_examples_js_1.eventCategoriesExample; } }); +// ===== QUICK START FUNCTIONS ===== +/** + * Quick start function to initialize a complete type-safe database setup + */ +async function quickStart(config) { + const connection = await initializeDatabase(config); + const repositories = createRepositoryProvider(connection); + const unitOfWork = createUnitOfWork(connection); + return { connection, repositories, unitOfWork }; +} +/** + * Create a complete service layer with all repositories + */ +function createServiceLayer(unitOfWork) { + return { + organizations: new OrganizationService(unitOfWork.Organizations), + users: new UserService(unitOfWork.Users, unitOfWork.Organizations), + featureFlags: new FeatureFlagService(unitOfWork.FeatureFlags, unitOfWork.UserFlags, unitOfWork.Organizations) + }; +} +// ===== DOCUMENTATION AND EXAMPLES ===== +/** + * Usage example: + * + * ```typescript + * import { quickStart, createServiceLayer, runExamples } from './index.js'; + * + * // Quick start + * const { connection, repositories, unitOfWork } = await quickStart({ + * type: 'postgres', + * host: 'localhost', + * port: 5432, + * username: 'postgres', + * password: 'password', + * database: 'myapp' + * }); + * + * // Create services + * const services = createServiceLayer(unitOfWork); + * + * // Use type-safe operations + * const orgResult = await services.organizations.createOrganization({ + * name: 'My Company', + * description: 'My awesome company', + * isActive: true + * }); + * + * if (orgResult.success) { + * console.log('Created organization:', orgResult.data.name); + * } + * + * // Run complete examples + * await runExamples(); + * ``` + */ +// ===== VERSION AND METADATA ===== +/** + * Package metadata + */ +exports.VERSION = '1.0.0'; +exports.DESCRIPTION = 'Type-safe database entity definitions using TypeORM decorators with comprehensive utility types and type-safe event system'; +exports.AUTHOR = 'Gitar, Inc.'; +exports.LICENSE = 'Apache-2.0'; +/** + * Feature flags for the module + */ +exports.FEATURES = { + TYPEORM_DECORATORS: true, + TYPE_SAFE_REPOSITORIES: true, + ADVANCED_UTILITY_TYPES: true, + VALIDATION_SCHEMAS: true, + TRANSACTION_SUPPORT: true, + RELATION_LOADING: true, + PAGINATION_SUPPORT: true, + ERROR_HANDLING: true, + EXAMPLES_INCLUDED: true, + TYPE_SAFE_EVENT_SYSTEM: true, + EVENT_EMITTER: true, + EVENT_SUBSCRIPTIONS: true, + GENERIC_EVENT_HANDLERS: true +}; +/** + * Export all features as a constant for runtime checks + */ +exports.SUPPORTED_FEATURES = Object.keys(exports.FEATURES); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/index.js.map b/launchdarkly/node/dist/index.js.map new file mode 100644 index 00000000..865e85cb --- /dev/null +++ b/launchdarkly/node/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;AAwVH,gCAUC;AAKD,gDAUC;AA/WD;;;;;;;;;;;;;;GAcG;AAEH,uBAAuB;AACvB,6CAoCuB;AAnCrB,iBAAiB;AACjB,2GAAA,YAAY,OAAA;AACZ,mGAAA,IAAI,OAAA;AACJ,0GAAA,WAAW,OAAA;AACX,uGAAA,QAAQ,OAAA;AACR,0GAAA,WAAW,OAAA;AACX,wGAAA,SAAS,OAAA;AA0BT,qBAAqB;AACrB,sHAAA,uBAAuB,OAAA;AACvB,6GAAA,cAAc,OAAA;AAGhB,kCAAkC;AAClC,6CAyBuB;AAxBrB,4BAA4B;AAC5B,iHAAA,kBAAkB,OAAA;AAElB,gBAAgB;AAChB,mHAAA,oBAAoB,OAAA;AAEpB,wBAAwB;AACxB,iHAAA,kBAAkB,OAAA;AAClB,4GAAA,aAAa,OAAA;AACb,0GAAA,WAAW,OAAA;AAEX,gBAAgB;AAChB,mHAAA,oBAAoB,OAAA;AAEpB,qBAAqB;AACrB,g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AAEzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,mCAAmC;AAEnC;;GAEG;AACU,QAAA,OAAO,GAAG,OAAO,CAAC;AAClB,QAAA,WAAW,GAAG,4HAA4H,CAAC;AAC3I,QAAA,MAAM,GAAG,aAAa,CAAC;AACvB,QAAA,OAAO,GAAG,YAAY,CAAC;AAEpC;;GAEG;AACU,QAAA,QAAQ,GAAG;IACtB,kBAAkB,EAAE,IAAI;IACxB,sBAAsB,EAAE,IAAI;IAC5B,sBAAsB,EAAE,IAAI;IAC5B,kBAAkB,EAAE,IAAI;IACxB,mBAAmB,EAAE,IAAI;IACzB,gBAAgB,EAAE,IAAI;IACtB,kBAAkB,EAAE,IAAI;IACxB,cAAc,EAAE,IAAI;IACpB,iBAAiB,EAAE,IAAI;IACvB,sBAAsB,EAAE,IAAI;IAC5B,aAAa,EAAE,IAAI;IACnB,mBAAmB,EAAE,IAAI;IACzB,sBAAsB,EAAE,IAAI;CACpB,CAAC;AAEX;;GAEG;AACU,QAAA,kBAAkB,GAAG,MAAM,CAAC,IAAI,CAAC,gBAAQ,CAAiC,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/repositories.d.ts b/launchdarkly/node/dist/repositories.d.ts new file mode 100644 index 00000000..fa19b9ab --- /dev/null +++ b/launchdarkly/node/dist/repositories.d.ts @@ -0,0 +1,257 @@ +import { Organization, User, FeatureFlag, UserFlag, UserSession, FlagEvent, CreateOrganizationInput, CreateUserInput, CreateFeatureFlagInput, CreateUserFlagInput, CreateUserSessionInput, CreateFlagEventInput, UpdateOrganizationInput, UpdateUserInput, UpdateFeatureFlagInput, UpdateUserFlagInput, UpdateUserSessionInput, OrganizationFilters, UserFilters, FeatureFlagFilters, UserFlagFilters } from "./entities.js"; +import { DatabaseConnection, TypeSafeQueryBuilder, PaginatedResult, PaginationOptions } from "./database.js"; +type BrandedString = string & { + readonly __brand: T; +}; +type UserId = BrandedString<'UserId'>; +type FlagKey = BrandedString<'FlagKey'>; +type OrganizationId = BrandedString<'OrganizationId'>; +type SessionId = BrandedString<'SessionId'>; +/** + * Generic repository interface with type-safe CRUD operations + */ +interface BaseRepository { + findById(id: string, relations?: string[]): Promise; + findAll(filters?: TFilters, relations?: string[]): Promise; + findPaginated(filters?: TFilters, pagination?: Partial, relations?: string[]): Promise>; + create(input: TCreateInput): Promise; + update(id: string, input: TUpdateInput): Promise; + delete(id: string): Promise; + count(filters?: TFilters): Promise; + exists(id: string): Promise; + createMany(inputs: TCreateInput[]): Promise; + updateMany(updates: Array<{ + id: string; + data: TUpdateInput; + }>): Promise; + deleteMany(ids: string[]): Promise; + search(query: string, filters?: TFilters): Promise; +} +/** + * Organization repository interface + */ +export interface IOrganizationRepository extends BaseRepository { + findByName(name: string): Promise; + findByDomain(domain: string): Promise; + findActiveOrganizations(): Promise; + getUserCount(organizationId: OrganizationId): Promise; + getFeatureFlagCount(organizationId: OrganizationId): Promise; +} +/** + * User repository interface + */ +export interface IUserRepository extends BaseRepository { + findByKey(key: string): Promise; + findByEmail(email: string): Promise; + findByOrganization(organizationId: OrganizationId): Promise; + findActiveUsers(): Promise; + updateLastLogin(userId: UserId): Promise; + deactivateUser(userId: UserId): Promise; + getUserFlags(userId: UserId): Promise; + getUserSessions(userId: UserId): Promise; +} +/** + * Feature flag repository interface + */ +export interface IFeatureFlagRepository extends BaseRepository { + findByKey(key: FlagKey): Promise; + findEnabledFlags(organizationId?: OrganizationId): Promise; + findByCategory(category: string): Promise; + findByTags(tags: string[]): Promise; + toggleFlag(flagId: string, enabled: boolean): Promise; + archiveFlag(flagId: string): Promise; + getUserFlagValue(userId: UserId, flagKey: FlagKey): Promise; + getFlagUsageStats(flagId: string): Promise<{ + totalUsers: number; + enabledForUsers: number; + lastEvaluated: Date | null; + }>; +} +/** + * User flag repository interface + */ +export interface IUserFlagRepository extends BaseRepository { + findByUserAndFlag(userId: UserId, flagId: string): Promise; + findByUser(userId: UserId): Promise; + findByFlag(flagId: string): Promise; + setUserFlag(userId: UserId, flagId: string, value: unknown, reason?: string): Promise; + removeUserFlag(userId: UserId, flagId: string): Promise; + getActiveFlags(userId: UserId): Promise; + cleanupExpiredFlags(): Promise; +} +/** + * User session repository interface + */ +export interface IUserSessionRepository extends BaseRepository { + findByUser(userId: UserId): Promise; + findActiveByUser(userId: UserId): Promise; + createSession(userId: UserId, sessionData: Omit): Promise; + updateActivity(sessionId: SessionId): Promise; + expireSession(sessionId: SessionId): Promise; + expireAllUserSessions(userId: UserId): Promise; + cleanupExpiredSessions(): Promise; +} +/** + * Flag event repository interface + */ +export interface IFlagEventRepository extends BaseRepository { + findByFlag(flagId: string): Promise; + findByUser(userId: UserId): Promise; + findByEventType(eventType: string): Promise; + logFlagEvaluation(flagId: string, userId: UserId, value: unknown, context?: Record): Promise; + logFlagUpdate(flagId: string, userId: UserId, previousValue: unknown, newValue: unknown, reason?: string): Promise; + getEventStats(flagId: string, from: Date, to: Date): Promise<{ + totalEvaluations: number; + uniqueUsers: number; + eventsByType: Record; + }>; +} +/** + * Base repository implementation with common functionality + */ +declare abstract class BaseRepositoryImpl implements BaseRepository { + protected queryBuilder: TypeSafeQueryBuilder; + protected entityName: string; + protected constructor(queryBuilder: TypeSafeQueryBuilder, entityName: string); + findById(id: string, relations?: string[]): Promise; + findAll(filters?: TFilters, relations?: string[]): Promise; + findPaginated(filters?: TFilters, pagination?: Partial, relations?: string[]): Promise>; + create(input: TCreateInput): Promise; + update(id: string, input: TUpdateInput): Promise; + delete(id: string): Promise; + count(filters?: TFilters): Promise; + exists(id: string): Promise; + createMany(inputs: TCreateInput[]): Promise; + updateMany(updates: Array<{ + id: string; + data: TUpdateInput; + }>): Promise; + deleteMany(ids: string[]): Promise; + search(query: string, filters?: TFilters): Promise; +} +/** + * Organization repository implementation + */ +export declare class OrganizationRepository extends BaseRepositoryImpl implements IOrganizationRepository { + constructor(queryBuilder: TypeSafeQueryBuilder); + findByName(name: string): Promise; + findByDomain(domain: string): Promise; + findActiveOrganizations(): Promise; + getUserCount(organizationId: OrganizationId): Promise; + getFeatureFlagCount(organizationId: OrganizationId): Promise; +} +/** + * User repository implementation + */ +export declare class UserRepository extends BaseRepositoryImpl implements IUserRepository { + constructor(queryBuilder: TypeSafeQueryBuilder); + findByKey(key: string): Promise; + findByEmail(email: string): Promise; + findByOrganization(organizationId: OrganizationId): Promise; + findActiveUsers(): Promise; + updateLastLogin(userId: UserId): Promise; + deactivateUser(userId: UserId): Promise; + getUserFlags(userId: UserId): Promise; + getUserSessions(userId: UserId): Promise; +} +/** + * Feature flag repository implementation + */ +export declare class FeatureFlagRepository extends BaseRepositoryImpl implements IFeatureFlagRepository { + constructor(queryBuilder: TypeSafeQueryBuilder); + findByKey(key: FlagKey): Promise; + findEnabledFlags(organizationId?: OrganizationId): Promise; + findByCategory(category: string): Promise; + findByTags(tags: string[]): Promise; + toggleFlag(flagId: string, enabled: boolean): Promise; + archiveFlag(flagId: string): Promise; + getUserFlagValue(userId: UserId, flagKey: FlagKey): Promise; + getFlagUsageStats(flagId: string): Promise<{ + totalUsers: number; + enabledForUsers: number; + lastEvaluated: Date | null; + }>; +} +/** + * User flag repository implementation + */ +export declare class UserFlagRepository extends BaseRepositoryImpl implements IUserFlagRepository { + constructor(queryBuilder: TypeSafeQueryBuilder); + findByUserAndFlag(userId: UserId, flagId: string): Promise; + findByUser(userId: UserId): Promise; + findByFlag(flagId: string): Promise; + setUserFlag(userId: UserId, flagId: string, value: unknown, reason?: string): Promise; + removeUserFlag(userId: UserId, flagId: string): Promise; + getActiveFlags(userId: UserId): Promise; + cleanupExpiredFlags(): Promise; +} +/** + * User session repository implementation + */ +export declare class UserSessionRepository extends BaseRepositoryImpl implements IUserSessionRepository { + constructor(queryBuilder: TypeSafeQueryBuilder); + findByUser(userId: UserId): Promise; + findActiveByUser(userId: UserId): Promise; + createSession(userId: UserId, sessionData: Omit): Promise; + updateActivity(sessionId: SessionId): Promise; + expireSession(sessionId: SessionId): Promise; + expireAllUserSessions(userId: UserId): Promise; + cleanupExpiredSessions(): Promise; +} +/** + * Flag event repository implementation + */ +export declare class FlagEventRepository extends BaseRepositoryImpl implements IFlagEventRepository { + constructor(queryBuilder: TypeSafeQueryBuilder); + findByFlag(flagId: string): Promise; + findByUser(userId: UserId): Promise; + findByEventType(eventType: string): Promise; + logFlagEvaluation(flagId: string, userId: UserId, value: unknown, context?: Record): Promise; + logFlagUpdate(flagId: string, userId: UserId, previousValue: unknown, newValue: unknown, reason?: string): Promise; + getEventStats(flagId: string, from: Date, to: Date): Promise<{ + totalEvaluations: number; + uniqueUsers: number; + eventsByType: Record; + }>; +} +/** + * Repository provider with dependency injection + */ +export declare class RepositoryProvider { + private repositoryFactory; + constructor(connection: DatabaseConnection); + getOrganizationRepository(): IOrganizationRepository; + getUserRepository(): IUserRepository; + getFeatureFlagRepository(): IFeatureFlagRepository; + getUserFlagRepository(): IUserFlagRepository; + getUserSessionRepository(): IUserSessionRepository; + getFlagEventRepository(): IFlagEventRepository; +} +/** + * Unit of Work pattern for managing database transactions + */ +export declare class UnitOfWork { + private connection; + private repositories; + constructor(connection: DatabaseConnection); + get Organizations(): IOrganizationRepository; + get Users(): IUserRepository; + get FeatureFlags(): IFeatureFlagRepository; + get UserFlags(): IUserFlagRepository; + get UserSessions(): IUserSessionRepository; + get FlagEvents(): IFlagEventRepository; + /** + * Execute operations within a transaction + */ + executeTransaction(operations: (uow: UnitOfWork) => Promise): Promise; +} +/** + * Create repository provider from database connection + */ +export declare function createRepositoryProvider(connection: DatabaseConnection): RepositoryProvider; +/** + * Create unit of work from database connection + */ +export declare function createUnitOfWork(connection: DatabaseConnection): UnitOfWork; +export {}; +//# sourceMappingURL=repositories.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/repositories.d.ts.map b/launchdarkly/node/dist/repositories.d.ts.map new file mode 100644 index 00000000..ed1738b0 --- /dev/null +++ b/launchdarkly/node/dist/repositories.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"repositories.d.ts","sourceRoot":"","s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AAC,CAAC;CAKrF;AAID;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,kBAAkB,GAAG,kBAAkB,CAE3F;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,kBAAkB,GAAG,UAAU,CAE3E"} \ No newline at end of file diff --git a/launchdarkly/node/dist/repositories.js b/launchdarkly/node/dist/repositories.js new file mode 100644 index 00000000..5c55c13d --- /dev/null +++ b/launchdarkly/node/dist/repositories.js @@ -0,0 +1,692 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnitOfWork = exports.RepositoryProvider = exports.FlagEventRepository = exports.UserSessionRepository = exports.UserFlagRepository = exports.FeatureFlagRepository = exports.UserRepository = exports.OrganizationRepository = void 0; +exports.createRepositoryProvider = createRepositoryProvider; +exports.createUnitOfWork = createUnitOfWork; +const database_js_1 = require("./database.js"); +// ===== REPOSITORY IMPLEMENTATIONS ===== +/** + * Base repository implementation with common functionality + */ +class BaseRepositoryImpl { + constructor(queryBuilder, entityName) { + this.queryBuilder = queryBuilder; + this.entityName = entityName; + } + async findById(id, relations) { + try { + return await this.queryBuilder.findById(id, relations); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findAll(filters, relations) { + try { + return await this.queryBuilder.find({ + where: filters, + relations + }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findPaginated(filters, pagination, relations) { + try { + const paginatedQuery = (0, database_js_1.createPaginatedQuery)(this.queryBuilder, pagination); + return await paginatedQuery.execute(filters, relations); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async create(input) { + try { + return await this.queryBuilder.create(input); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async update(id, input) { + try { + const success = await this.queryBuilder.update(id, input); + if (!success) { + throw new database_js_1.DatabaseError(`${this.entityName} with id ${id} not found`, 'NOT_FOUND'); + } + const updated = await this.findById(id); + if (!updated) { + throw new database_js_1.DatabaseError(`Failed to retrieve updated ${this.entityName}`, 'UPDATE_FAILED'); + } + return updated; + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async delete(id) { + try { + return await this.queryBuilder.delete(id); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async count(filters) { + try { + return await this.queryBuilder.count(filters); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async exists(id) { + try { + return await this.queryBuilder.exists({ id }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async createMany(inputs) { + try { + const results = []; + for (const input of inputs) { + const entity = await this.create(input); + results.push(entity); + } + return results; + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async updateMany(updates) { + try { + const results = []; + for (const update of updates) { + const entity = await this.update(update.id, update.data); + results.push(entity); + } + return results; + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async deleteMany(ids) { + try { + let deleted = 0; + for (const id of ids) { + const success = await this.delete(id); + if (success) + deleted++; + } + return deleted; + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async search(query, filters) { + try { + // Basic search implementation - would be enhanced with full-text search in real TypeORM + return await this.findAll(filters); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } +} +/** + * Organization repository implementation + */ +class OrganizationRepository extends BaseRepositoryImpl { + constructor(queryBuilder) { + super(queryBuilder, 'Organization'); + } + async findByName(name) { + try { + return await this.queryBuilder.findOne({ where: { name } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findByDomain(domain) { + try { + return await this.queryBuilder.findOne({ where: { domain } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findActiveOrganizations() { + try { + return await this.queryBuilder.find({ where: { isActive: true } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async getUserCount(organizationId) { + try { + // In real implementation, would use JOIN query + return 0; // Mock implementation + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async getFeatureFlagCount(organizationId) { + try { + // In real implementation, would use JOIN query + return 0; // Mock implementation + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } +} +exports.OrganizationRepository = OrganizationRepository; +/** + * User repository implementation + */ +class UserRepository extends BaseRepositoryImpl { + constructor(queryBuilder) { + super(queryBuilder, 'User'); + } + async findByKey(key) { + try { + return await this.queryBuilder.findOne({ where: { key } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findByEmail(email) { + try { + return await this.queryBuilder.findOne({ where: { email } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findByOrganization(organizationId) { + try { + return await this.queryBuilder.find({ where: { organizationId } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findActiveUsers() { + try { + return await this.queryBuilder.find({ where: { isActive: true } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async updateLastLogin(userId) { + try { + await this.queryBuilder.update(userId, { lastLoginAt: new Date() }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async deactivateUser(userId) { + try { + return await this.queryBuilder.update(userId, { isActive: false }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async getUserFlags(userId) { + try { + // In real implementation, would use relation loading + return []; // Mock implementation + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async getUserSessions(userId) { + try { + // In real implementation, would use relation loading + return []; // Mock implementation + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } +} +exports.UserRepository = UserRepository; +/** + * Feature flag repository implementation + */ +class FeatureFlagRepository extends BaseRepositoryImpl { + constructor(queryBuilder) { + super(queryBuilder, 'FeatureFlag'); + } + async findByKey(key) { + try { + return await this.queryBuilder.findOne({ where: { key } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findEnabledFlags(organizationId) { + try { + const where = { isEnabled: true }; + if (organizationId) { + where.organizationId = organizationId; + } + return await this.queryBuilder.find({ where }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findByCategory(category) { + try { + return await this.queryBuilder.find({ where: { category } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findByTags(tags) { + try { + // In real implementation, would use array contains query + return []; // Mock implementation + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async toggleFlag(flagId, enabled) { + try { + return await this.queryBuilder.update(flagId, { isEnabled: enabled }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async archiveFlag(flagId) { + try { + return await this.queryBuilder.update(flagId, { isArchived: true }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async getUserFlagValue(userId, flagKey) { + try { + // In real implementation, would use JOIN query + return null; // Mock implementation + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async getFlagUsageStats(flagId) { + try { + // In real implementation, would use aggregation queries + return { + totalUsers: 0, + enabledForUsers: 0, + lastEvaluated: null + }; + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } +} +exports.FeatureFlagRepository = FeatureFlagRepository; +/** + * User flag repository implementation + */ +class UserFlagRepository extends BaseRepositoryImpl { + constructor(queryBuilder) { + super(queryBuilder, 'UserFlag'); + } + async findByUserAndFlag(userId, flagId) { + try { + return await this.queryBuilder.findOne({ + where: { userId, featureFlagId: flagId } + }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findByUser(userId) { + try { + return await this.queryBuilder.find({ where: { userId } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findByFlag(flagId) { + try { + return await this.queryBuilder.find({ where: { featureFlagId: flagId } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async setUserFlag(userId, flagId, value, reason) { + try { + const existing = await this.findByUserAndFlag(userId, flagId); + if (existing) { + return await this.update(existing.id, { + value, + reason, + isActive: true + }); + } + else { + return await this.create({ + userId, + featureFlagId: flagId, + value, + reason, + isActive: true + }); + } + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async removeUserFlag(userId, flagId) { + try { + const existing = await this.findByUserAndFlag(userId, flagId); + if (existing) { + return await this.delete(existing.id); + } + return false; + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async getActiveFlags(userId) { + try { + return await this.queryBuilder.find({ + where: { userId, isActive: true } + }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async cleanupExpiredFlags() { + try { + const now = new Date(); + // In real implementation, would use bulk delete query + return 0; // Mock implementation + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } +} +exports.UserFlagRepository = UserFlagRepository; +/** + * User session repository implementation + */ +class UserSessionRepository extends BaseRepositoryImpl { + constructor(queryBuilder) { + super(queryBuilder, 'UserSession'); + } + async findByUser(userId) { + try { + return await this.queryBuilder.find({ where: { userId } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findActiveByUser(userId) { + try { + return await this.queryBuilder.find({ + where: { userId, isActive: true } + }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async createSession(userId, sessionData) { + try { + return await this.create({ userId, ...sessionData }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async updateActivity(sessionId) { + try { + return await this.queryBuilder.update(sessionId, { + lastActivityAt: new Date() + }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async expireSession(sessionId) { + try { + return await this.queryBuilder.update(sessionId, { + isActive: false, + expiresAt: new Date() + }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async expireAllUserSessions(userId) { + try { + const sessions = await this.findActiveByUser(userId); + let expired = 0; + for (const session of sessions) { + const success = await this.expireSession(session.id); + if (success) + expired++; + } + return expired; + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async cleanupExpiredSessions() { + try { + const now = new Date(); + // In real implementation, would use bulk delete query + return 0; // Mock implementation + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } +} +exports.UserSessionRepository = UserSessionRepository; +/** + * Flag event repository implementation + */ +class FlagEventRepository extends BaseRepositoryImpl { + constructor(queryBuilder) { + super(queryBuilder, 'FlagEvent'); + } + async findByFlag(flagId) { + try { + return await this.queryBuilder.find({ where: { featureFlagId: flagId } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findByUser(userId) { + try { + return await this.queryBuilder.find({ where: { userId } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async findByEventType(eventType) { + try { + return await this.queryBuilder.find({ where: { eventType } }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async logFlagEvaluation(flagId, userId, value, context) { + try { + return await this.create({ + featureFlagId: flagId, + userId, + eventType: 'evaluation', + newValue: value, + context + }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async logFlagUpdate(flagId, userId, previousValue, newValue, reason) { + try { + return await this.create({ + featureFlagId: flagId, + userId, + eventType: 'update', + previousValue, + newValue, + reason + }); + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } + async getEventStats(flagId, from, to) { + try { + // In real implementation, would use aggregation queries + return { + totalEvaluations: 0, + uniqueUsers: 0, + eventsByType: {} + }; + } + catch (error) { + (0, database_js_1.handleDatabaseError)(error); + } + } +} +exports.FlagEventRepository = FlagEventRepository; +// ===== REPOSITORY PROVIDER ===== +/** + * Repository provider with dependency injection + */ +class RepositoryProvider { + constructor(connection) { + this.repositoryFactory = new database_js_1.RepositoryFactory(connection); + } + getOrganizationRepository() { + return new OrganizationRepository(this.repositoryFactory.getOrganizationRepository()); + } + getUserRepository() { + return new UserRepository(this.repositoryFactory.getUserRepository()); + } + getFeatureFlagRepository() { + return new FeatureFlagRepository(this.repositoryFactory.getFeatureFlagRepository()); + } + getUserFlagRepository() { + return new UserFlagRepository(this.repositoryFactory.getUserFlagRepository()); + } + getUserSessionRepository() { + return new UserSessionRepository(this.repositoryFactory.getUserSessionRepository()); + } + getFlagEventRepository() { + return new FlagEventRepository(this.repositoryFactory.getFlagEventRepository()); + } +} +exports.RepositoryProvider = RepositoryProvider; +// ===== UNIT OF WORK PATTERN ===== +/** + * Unit of Work pattern for managing database transactions + */ +class UnitOfWork { + constructor(connection) { + this.connection = connection; + this.repositories = new RepositoryProvider(connection); + } + get Organizations() { + return this.repositories.getOrganizationRepository(); + } + get Users() { + return this.repositories.getUserRepository(); + } + get FeatureFlags() { + return this.repositories.getFeatureFlagRepository(); + } + get UserFlags() { + return this.repositories.getUserFlagRepository(); + } + get UserSessions() { + return this.repositories.getUserSessionRepository(); + } + get FlagEvents() { + return this.repositories.getFlagEventRepository(); + } + /** + * Execute operations within a transaction + */ + async executeTransaction(operations) { + return await this.connection.transaction(async () => { + return await operations(this); + }); + } +} +exports.UnitOfWork = UnitOfWork; +// ===== EXPORT FUNCTIONS ===== +/** + * Create repository provider from database connection + */ +function createRepositoryProvider(connection) { + return new RepositoryProvider(connection); +} +/** + * Create unit of work from database connection + */ +function createUnitOfWork(connection) { + return new UnitOfWork(connection); +} +//# sourceMappingURL=repositories.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/repositories.js.map b/launchdarkly/node/dist/repositories.js.map new file mode 100644 index 00000000..a51b40f9 --- /dev/null +++ b/launchdarkly/node/dist/repositories.js.map @@ -0,0 +1 @@ +{"version":3,"file":"repositories.js","sourceRoot":"","sources":["../repositories.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAm5BH,4DAEC;AAKD,4CAEC;AA53BD,+CAUu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Y;QACd,OAAO,IAAI,CAAC,YAAY,CAAC,wBAAwB,EAAE,CAAC;IACtD,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,YAAY,CAAC,sBAAsB,EAAE,CAAC;IACpD,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,kBAAkB,CAAI,UAA2C;QACrE,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,KAAK,IAAI,EAAE;YAClD,OAAO,MAAM,UAAU,CAAC,IAAI,CAAC,CAAC;QAChC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAvCD,gCAuCC;AAED,+BAA+B;AAE/B;;GAEG;AACH,SAAgB,wBAAwB,CAAC,UAA8B;IACrE,OAAO,IAAI,kBAAkB,CAAC,UAAU,CAAC,CAAC;AAC5C,CAAC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,UAA8B;IAC7D,OAAO,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;AACpC,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/sample.d.ts b/launchdarkly/node/dist/sample.d.ts new file mode 100644 index 00000000..3abcd666 --- /dev/null +++ b/launchdarkly/node/dist/sample.d.ts @@ -0,0 +1,349 @@ +/** + * Example of using the LaunchDarkly JavaScript SDK to evaluate feature flags. + * Demonstrates proper TypeScript return type annotations for API boundaries, + * service layers, and repository interfaces. + * + * https://docs.launchdarkly.com/sdk/client-side/javascript + */ +import { z } from "zod"; +interface LDContext { + key: string; + name?: string; + kind?: string; + [key: string]: unknown; +} +interface LDFlagValue { + [key: string]: boolean | string | number; +} +interface LDFlagsState { + allValues(): Record; + valid: boolean; +} +type LDVariationCallback = (err: Error | null, result: T) => void; +type LDFlagsStateCallback = (err: Error | null, result: LDFlagsState) => void; +export declare class ValidationError extends Error { + readonly validationErrors: z.ZodError; + readonly context: string; + constructor(zodError: z.ZodError, context?: string); + getFormattedErrors(): Record; +} +export declare const isValidLDContext: (data: unknown) => data is { + key: string; + name?: string | undefined; + email?: string | undefined; + kind?: "user" | "organization" | "device" | undefined; + custom?: Record | undefined; +}; +export declare const isValidFeatureFlagKey: (data: unknown) => data is string; +export declare const isValidSDKKey: (data: unknown) => data is string; +export declare const isValidFlagValue: (data: unknown) => data is string | number | boolean | Record; +declare namespace LaunchDarkly { + interface LDClient { + variation(key: string, context: LDContext, defaultValue: T, callback: LDVariationCallback): void; + allFlagsState(context: LDContext, callback: LDFlagsStateCallback): void; + waitForInitialization(): Promise; + } + function init(sdkKey: string): LDClient; +} +interface User extends LDContext { + kind: string; + name: string; + key: string; +} +interface FeatureFlags { + isDarkModeEnabled: boolean; + enableHighContrast: boolean; +} +interface ApiResponse { + data: T | null; + success: boolean; + error?: string | null; +} +type RPCErrorCode = 'PARSE_ERROR' | 'BAD_REQUEST' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | 'METHOD_NOT_SUPPORTED' | 'TIMEOUT' | 'CONFLICT' | 'PRECONDITION_FAILED' | 'PAYLOAD_TOO_LARGE' | 'UNPROCESSABLE_CONTENT' | 'TOO_MANY_REQUESTS' | 'CLIENT_CLOSED_REQUEST' | 'INTERNAL_SERVER_ERROR'; +interface RPCError { + code: RPCErrorCode; + message: string; + data?: unknown; + cause?: Error; +} +type RPCResponse = { + success: true; + data: TData; + error?: never; +} | { + success: false; + data?: never; + error: RPCError; +}; +interface RPCInputSchema { + parse(input: unknown): T; + safeParse(input: unknown): { + success: true; + data: T; + } | { + success: false; + error: RPCError; + }; +} +declare class GetFeatureFlagInputSchema implements RPCInputSchema { + parse(input: unknown): GetFeatureFlagInput; + safeParse(input: unknown): { + success: true; + data: GetFeatureFlagInput; + } | { + success: false; + error: RPCError; + }; +} +declare class UpdateFeatureFlagInputSchema implements RPCInputSchema { + parse(input: unknown): UpdateFeatureFlagInput; + safeParse(input: unknown): { + success: true; + data: UpdateFeatureFlagInput; + } | { + success: false; + error: RPCError; + }; +} +interface RPCContext { + user?: User | null; + session?: { + id: string; + expiresAt: Date; + permissions: string[]; + }; + request?: { + userAgent?: string; + ip?: string; + headers?: Record; + }; +} +type MiddlewareBrand = string & { + readonly __middlewareBrand: T; +}; +type AuthMiddleware = MiddlewareBrand<'auth'>; +type RateLimitMiddleware = MiddlewareBrand<'rateLimit'>; +type AdminOnlyMiddleware = MiddlewareBrand<'adminOnly'>; +type CorsMiddleware = MiddlewareBrand<'cors'>; +type LoggingMiddleware = MiddlewareBrand<'logging'>; +type ValidationMiddleware = MiddlewareBrand<'validation'>; +type MiddlewareName = AuthMiddleware | RateLimitMiddleware | AdminOnlyMiddleware | CorsMiddleware | LoggingMiddleware | ValidationMiddleware; +declare const MIDDLEWARE_TYPES: { + readonly auth: AuthMiddleware; + readonly rateLimit: RateLimitMiddleware; + readonly adminOnly: AdminOnlyMiddleware; + readonly cors: CorsMiddleware; + readonly logging: LoggingMiddleware; + readonly validation: ValidationMiddleware; +}; +interface MiddlewareConfig { + auth: { + required: boolean; + roles?: string[]; + permissions?: string[]; + }; + rateLimit: { + windowMs: number; + maxRequests: number; + skipSuccessfulRequests?: boolean; + }; + adminOnly: { + requireSuperAdmin?: boolean; + allowedRoles: string[]; + }; + cors: { + origins: string[]; + methods: string[]; + credentials?: boolean; + }; + logging: { + level: 'debug' | 'info' | 'warn' | 'error'; + includeRequestBody?: boolean; + includeResponseBody?: boolean; + }; + validation: { + validateInput: boolean; + validateOutput: boolean; + sanitizeInput?: boolean; + }; +} +interface MiddlewareExecutionContext { + name: T; + config: MiddlewareConfig[T]; + context: RPCContext; + input: unknown; + startTime: Date; + readonly __executionBrand: `${T}Execution`; +} +interface MiddlewareResult { + success: boolean; + error?: RPCError; + modifiedContext?: Partial; + modifiedInput?: unknown; +} +type MiddlewareFunction = (ctx: MiddlewareExecutionContext) => Promise | MiddlewareResult; +interface MiddlewareStack { + auth: MiddlewareFunction<'auth'>; + rateLimit: MiddlewareFunction<'rateLimit'>; + adminOnly: MiddlewareFunction<'adminOnly'>; + cors: MiddlewareFunction<'cors'>; + logging: MiddlewareFunction<'logging'>; + validation: MiddlewareFunction<'validation'>; +} +declare namespace Domain { +} +declare namespace API { +} +type BrandedString = string & { + readonly __brand: T; +}; +type UserId = BrandedString<'UserId'>; +type FlagKey = BrandedString<'FlagKey'>; +type SessionId = BrandedString<'SessionId'>; +type SdkKey = BrandedString<'SdkKey'>; +type ClientSideId = BrandedString<'ClientSideId'>; +type ApiKey = BrandedString<'ApiKey'>; +type SecretKey = BrandedString<'SecretKey'>; +type RequestId = BrandedString<'RequestId'>; +type TraceId = BrandedString<'TraceId'>; +type CorrelationId = BrandedString<'CorrelationId'>; +type EnvironmentKey = BrandedString<'EnvironmentKey'>; +type ProjectKey = BrandedString<'ProjectKey'>; +type FeatureFlagName = BrandedString<'FeatureFlagName'>; +type UserContextKey = BrandedString<'UserContextKey'>; +type TenantId = BrandedString<'TenantId'>; +type OrganizationId = BrandedString<'OrganizationId'>; +declare const createUserId: (value: string) => UserId | null; +declare const createFlagKey: (value: string) => FlagKey | null; +declare const createSessionId: (value: string) => SessionId | null; +declare const createSdkKey: (value: string) => SdkKey | null; +declare const createClientSideId: (value: string) => ClientSideId | null; +declare const createApiKey: (value: string) => ApiKey | null; +declare const createSecretKey: (value: string) => SecretKey | null; +declare const createRequestId: (value: string) => RequestId | null; +declare const createTraceId: (value: string) => TraceId | null; +declare const createCorrelationId: (value: string) => CorrelationId | null; +declare const createEnvironmentKey: (value: string) => EnvironmentKey | null; +declare const createProjectKey: (value: string) => ProjectKey | null; +declare const createFeatureFlagName: (value: string) => FeatureFlagName | null; +declare const createUserContextKey: (value: string) => UserContextKey | null; +declare const createTenantId: (value: string) => TenantId | null; +declare const createOrganizationId: (value: string) => OrganizationId | null; +declare const isUserId: (value: unknown) => value is UserId; +declare const isFlagKey: (value: unknown) => value is FlagKey; +declare const isSessionId: (value: unknown) => value is SessionId; +declare const isSdkKey: (value: unknown) => value is SdkKey; +declare const isClientSideId: (value: unknown) => value is ClientSideId; +declare const isApiKey: (value: unknown) => value is ApiKey; +declare const isSecretKey: (value: unknown) => value is SecretKey; +declare const isRequestId: (value: unknown) => value is RequestId; +declare const isTraceId: (value: unknown) => value is TraceId; +declare const isCorrelationId: (value: unknown) => value is CorrelationId; +declare const isEnvironmentKey: (value: unknown) => value is EnvironmentKey; +declare const isProjectKey: (value: unknown) => value is ProjectKey; +declare const isFeatureFlagName: (value: unknown) => value is FeatureFlagName; +declare const isUserContextKey: (value: unknown) => value is UserContextKey; +declare const isTenantId: (value: unknown) => value is TenantId; +declare const isOrganizationId: (value: unknown) => value is OrganizationId; +declare namespace Transform { + function domainUserToApiUser(domainUser: Domain.User): API.LDUser; + function domainUserContextToApiContext(userContext: Domain.UserContext): API.LDUser; + function domainFeatureFlagsToApiResponse(domainFlags: Domain.FeatureFlags): API.FeatureFlagsResponse; + function domainGetFeatureFlagInputToApiRequest(input: Domain.GetFeatureFlagInput): API.GetFeatureFlagRequest; + function apiUserToDomainUser(apiUser: API.LDUser): Domain.User; + function apiFeatureFlagsResponseToDomainFlags(apiResponse: API.FeatureFlagsResponse): Domain.FeatureFlags; + function apiFeatureFlagResponseToDomainFlag(apiResponse: API.FeatureFlagApiResponse): Domain.FeatureFlag; + function apiResponseToDomainResult(apiResponse: API.ApiResponse, transformer: (apiData: TApiData) => TDomainData): RPCResponse; +} +declare namespace Domain { +} +declare namespace API { +} +declare namespace Domain { +} +type ServiceToken = symbol & { + readonly __serviceType: T; +}; +interface IDependencyContainer { + register(token: ServiceToken, factory: () => T): void; + registerSingleton(token: ServiceToken, factory: () => T): void; + resolve(token: ServiceToken): T; + isRegistered(token: ServiceToken): boolean; + readonly __containerBrand: 'DependencyContainer'; +} +declare class DependencyContainer implements IDependencyContainer { + readonly __containerBrand: "DependencyContainer"; + private services; + private singletons; + private factories; + register(token: ServiceToken, factory: () => T): void; + registerSingleton(token: ServiceToken, factory: () => T): void; + resolve(token: ServiceToken): T; + isRegistered(token: ServiceToken): boolean; +} +declare namespace Domain { +} +declare const SERVICE_TOKENS: { + readonly LaunchDarklyClient: ServiceToken; + readonly FeatureFlagRepository: ServiceToken; + readonly FeatureFlagService: ServiceToken; + readonly FeatureFlagController: ServiceToken; + readonly FeatureFlagApiClient: ServiceToken; +}; +declare class FeatureFlagService implements Domain.IFeatureFlagService { + readonly __serviceBrand: "FeatureFlagService"; + private repository; + private apiClient; + constructor(repository: Domain.FeatureFlagRepository, apiClient: API.FeatureFlagApiClient); + getUserFeatureFlags(userContext: Domain.UserContext): Promise>; + updateUserPreference(userContext: Domain.UserContext, flagKey: string, value: boolean): Promise>; + validateUser(user: Domain.User | null | undefined): Promise; + private isValidUser; + private isValidLDContext; + private parseLDContext; + private validateFeatureFlagKey; +} +declare class LaunchDarklyRepository implements Domain.FeatureFlagRepository { + readonly __repositoryBrand: "FeatureFlagRepository"; + private client; + constructor(client: LaunchDarkly.LDClient); + getFeatureFlag(input: Domain.GetFeatureFlagInput): Promise>; + getAllFeatureFlags(input: Domain.GetAllFeatureFlagsInput): Promise>; + updateFeatureFlag(input: Domain.UpdateFeatureFlagInput): Promise>; + deleteFeatureFlag(input: Domain.DeleteFeatureFlagInput): Promise>; +} +interface IFeatureFlagController { + getUserFlags(userId: string): Promise>; + updateUserFlag(userId: string, flagKey: string, value: boolean): Promise>; + readonly __controllerBrand: 'FeatureFlagController'; +} +declare class FeatureFlagController implements IFeatureFlagController { + readonly __controllerBrand: "FeatureFlagController"; + private service; + constructor(service: IFeatureFlagService); + getUserFlags(userId: string): Promise>; + updateUserFlag(userId: string, flagKey: string, value: boolean): Promise>; +} +declare function createUser(key: string | null | undefined, name: string | null | undefined): User | null; +declare function isValidApiResponse(data: unknown): data is ApiResponse; +declare function validateExternalUserData(data: unknown): User | null; +declare function initializeClient(sdkKey: string): Promise; +declare function logFeatureFlag(flagName: string, value: boolean): void; +declare function main(): Promise; +export type DomainUserPartial = Partial; +export type DomainUserPick = Pick; +export type DomainUserOmit = Omit; +export type FlagRecord = Record; +export type DomainUserRecord = Record; +export type FeatureFlagConfig = Pick; +export type DomainUserIdentity = Pick; +export type DomainUserMetadata = Omit; +export type { LDContext, LDFlagsState, LDFlagValue, IDependencyContainer, ServiceToken, BrandedString, UserId, FlagKey, SessionId, SdkKey, ClientSideId, ApiKey, SecretKey, RequestId, TraceId, CorrelationId, EnvironmentKey, ProjectKey, FeatureFlagName, UserContextKey, TenantId, OrganizationId, MiddlewareBrand, AuthMiddleware, RateLimitMiddleware, AdminOnlyMiddleware, CorsMiddleware, LoggingMiddleware, ValidationMiddleware, RPCError, RPCErrorCode, RPCResponse, RPCInputSchema, RPCContext, MiddlewareName, MiddlewareConfig, MiddlewareExecutionContext, MiddlewareResult, MiddlewareFunction, MiddlewareStack, }; +export { Domain, API, Transform, FeatureFlagService, LaunchDarklyRepository, FeatureFlagController, DependencyContainer, SERVICE_TOKENS, MIDDLEWARE_TYPES, createUser, initializeClient, logFeatureFlag, main, isValidApiResponse, validateExternalUserData, createUserId, createFlagKey, createSessionId, createSdkKey, createClientSideId, createApiKey, createSecretKey, createRequestId, createTraceId, createCorrelationId, createEnvironmentKey, createProjectKey, createFeatureFlagName, createUserContextKey, createTenantId, createOrganizationId, isUserId, isFlagKey, isSessionId, isSdkKey, isClientSideId, isApiKey, isSecretKey, isRequestId, isTraceId, isCorrelationId, isEnvironmentKey, isProjectKey, isFeatureFlagName, isUserContextKey, isTenantId, isOrganizationId, GetFeatureFlagInputSchema, UpdateFeatureFlagInputSchema, }; +//# sourceMappingURL=sample.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/sample.d.ts.map b/launchdarkly/node/dist/sample.d.ts.map new file mode 100644 index 00000000..b7e56799 --- /dev/null +++ b/launchdarkly/node/dist/sample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sample.d.ts","sourceRoot":"","sources":["../sample.ts"],"names":[],"mappings":"AAgBA;;;;;;GAMG;AAIH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,UAAU,SAAS;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ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AEV,cAAc,EACd,gBAAgB,EAChB,0BAA0B,EAC1B,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,GACf,CAAC;AAEF,OAAO,EAEN,MAAM,EACN,GAAG,EACH,SAAS,EAET,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EAEnB,cAAc,EACd,gBAAgB,EAEhB,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,IAAI,EACJ,kBAAkB,EAClB,wBAAwB,EAExB,YAAY,EACZ,aAAa,EACb,eAAe,EAEf,YAAY,EACZ,kBAAkB,EAClB,YAAY,EACZ,eAAe,EAEf,eAAe,EACf,aAAa,EACb,mBAAmB,EAEnB,oBAAoB,EACpB,gBAAgB,EAChB,qBAAqB,EAErB,oBAAoB,EACpB,cAAc,EACd,oBAAoB,EAEpB,QAAQ,EACR,SAAS,EACT,WAAW,EACX,QAAQ,EACR,cAAc,EACd,QAAQ,EACR,WAAW,EACX,WAAW,EACX,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,gBAAgB,EAChB,UAAU,EACV,gBAAgB,EAEhB,yBAAyB,EACzB,4BAA4B,GAC5B,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/sample.js b/launchdarkly/node/dist/sample.js new file mode 100644 index 00000000..a8ef0f62 --- /dev/null +++ b/launchdarkly/node/dist/sample.js @@ -0,0 +1,1015 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UpdateFeatureFlagInputSchema = exports.GetFeatureFlagInputSchema = exports.isOrganizationId = exports.isTenantId = exports.isUserContextKey = exports.isFeatureFlagName = exports.isProjectKey = exports.isEnvironmentKey = exports.isCorrelationId = exports.isTraceId = exports.isRequestId = exports.isSecretKey = exports.isApiKey = exports.isClientSideId = exports.isSdkKey = exports.isSessionId = exports.isFlagKey = exports.isUserId = exports.createOrganizationId = exports.createTenantId = exports.createUserContextKey = exports.createFeatureFlagName = exports.createProjectKey = exports.createEnvironmentKey = exports.createCorrelationId = exports.createTraceId = exports.createRequestId = exports.createSecretKey = exports.createApiKey = exports.createClientSideId = exports.createSdkKey = exports.createSessionId = exports.createFlagKey = exports.createUserId = exports.MIDDLEWARE_TYPES = exports.SERVICE_TOKENS = exports.DependencyContainer = exports.FeatureFlagController = exports.LaunchDarklyRepository = exports.FeatureFlagService = exports.Transform = exports.isValidFlagValue = exports.isValidSDKKey = exports.isValidFeatureFlagKey = exports.isValidLDContext = exports.ValidationError = void 0; +exports.createUser = createUser; +exports.initializeClient = initializeClient; +exports.logFeatureFlag = logFeatureFlag; +exports.main = main; +exports.isValidApiResponse = isValidApiResponse; +exports.validateExternalUserData = validateExternalUserData; +/** + * Example of using the LaunchDarkly JavaScript SDK to evaluate feature flags. + * Demonstrates proper TypeScript return type annotations for API boundaries, + * service layers, and repository interfaces. + * + * https://docs.launchdarkly.com/sdk/client-side/javascript + */ +// Note: Install @launchdarkly/node-server-sdk for actual implementation +// import * as LaunchDarkly from "@launchdarkly/node-server-sdk"; +const zod_1 = require("zod"); +// === ZOD VALIDATION SCHEMAS FOR API BOUNDARIES === +const ValidationSchemas = { + // Context validation with proper typing + LDContext: zod_1.z.object({ + key: zod_1.z.string().min(1, "Context key is required"), + name: zod_1.z.string().optional(), + kind: zod_1.z.enum(["user", "organization", "device"]).optional().default("user"), + email: zod_1.z.string().email().optional(), + custom: zod_1.z.record(zod_1.z.union([zod_1.z.string(), zod_1.z.number(), zod_1.z.boolean()])).optional() + }).strict(), + // Feature flag key validation + FeatureFlagKey: zod_1.z.string().min(1, "Feature flag key cannot be empty").refine((val) => /^[a-zA-Z0-9-_.]+$/.test(val), "Feature flag key must contain only alphanumeric characters, hyphens, underscores, and dots"), + // SDK key validation + SDKKey: zod_1.z.string().min(1, "SDK key cannot be empty").refine((val) => !val.includes("<") && !val.includes(">"), "SDK key must be a valid key, not a placeholder"), + // Flag value validation (supports common types) + FlagValue: zod_1.z.union([ + zod_1.z.boolean(), + zod_1.z.string(), + zod_1.z.number(), + zod_1.z.record(zod_1.z.unknown()) + ]), + // Variation result with metadata + VariationResult: zod_1.z.object({ + key: zod_1.z.string(), + value: zod_1.z.unknown(), + variationIndex: zod_1.z.number().optional(), + reason: zod_1.z.object({ + kind: zod_1.z.string(), + ruleIndex: zod_1.z.number().optional(), + ruleId: zod_1.z.string().optional() + }).optional(), + trackEvents: zod_1.z.boolean().optional(), + debugEventsUntilDate: zod_1.z.number().optional() + }), + // Flags state validation + FlagsState: zod_1.z.object({ + valid: zod_1.z.boolean(), + flags: zod_1.z.record(zod_1.z.unknown()) + }) +}; +// === VALIDATION ERROR HANDLING === +class ValidationError extends Error { + constructor(zodError, context = "Validation") { + const errorMessage = `${context} failed: ${zodError.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`; + super(errorMessage); + this.name = "ValidationError"; + this.validationErrors = zodError; + this.context = context; + } + getFormattedErrors() { + const errors = {}; + for (const error of this.validationErrors.errors) { + const path = error.path.join('.') || 'root'; + if (!errors[path]) { + errors[path] = []; + } + errors[path].push(error.message); + } + return errors; + } +} +exports.ValidationError = ValidationError; +// === VALIDATION UTILITY FUNCTIONS === +const ValidationUtils = { + // Safe parsing with detailed error handling + safeParse(schema, data, context) { + try { + const result = schema.parse(data); + return { success: true, data: result }; + } + catch (error) { + if (error instanceof zod_1.z.ZodError) { + return { + success: false, + error: new ValidationError(error, context || "Data validation") + }; + } + throw error; + } + }, + // Strict parsing that throws on validation failure + parse(schema, data, context) { + try { + return schema.parse(data); + } + catch (error) { + if (error instanceof zod_1.z.ZodError) { + throw new ValidationError(error, context || "Data parsing"); + } + throw error; + } + }, + // Type guard factory + createTypeGuard(schema) { + return (data) => { + try { + schema.parse(data); + return true; + } + catch { + return false; + } + }; + } +}; +// === EXPORTED TYPE GUARDS === +exports.isValidLDContext = ValidationUtils.createTypeGuard(ValidationSchemas.LDContext); +exports.isValidFeatureFlagKey = ValidationUtils.createTypeGuard(ValidationSchemas.FeatureFlagKey); +exports.isValidSDKKey = ValidationUtils.createTypeGuard(ValidationSchemas.SDKKey); +exports.isValidFlagValue = ValidationUtils.createTypeGuard(ValidationSchemas.FlagValue); +// Concrete validation schemas for each input type +class GetFeatureFlagInputSchema { + parse(input) { + const result = this.safeParse(input); + if (!result.success) { + throw new Error(result.error.message); + } + return result.data; + } + safeParse(input) { + if (!input || typeof input !== 'object') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'Input must be an object' + } + }; + } + const obj = input; + if (!obj.flagKey || typeof obj.flagKey !== 'string') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'flagKey is required and must be a string' + } + }; + } + if (!obj.context || typeof obj.context !== 'object') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'context is required and must be a User object' + } + }; + } + if (obj.defaultValue !== undefined && typeof obj.defaultValue !== 'boolean') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'defaultValue must be a boolean if provided' + } + }; + } + return { + success: true, + data: { + flagKey: obj.flagKey, + context: obj.context, + defaultValue: obj.defaultValue ?? false + } + }; + } +} +exports.GetFeatureFlagInputSchema = GetFeatureFlagInputSchema; +class UpdateFeatureFlagInputSchema { + parse(input) { + const result = this.safeParse(input); + if (!result.success) { + throw new Error(result.error.message); + } + return result.data; + } + safeParse(input) { + if (!input || typeof input !== 'object') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'Input must be an object' + } + }; + } + const obj = input; + if (!obj.flagKey || typeof obj.flagKey !== 'string') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'flagKey is required and must be a string' + } + }; + } + if (typeof obj.value !== 'boolean') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'value is required and must be a boolean' + } + }; + } + if (!obj.context || typeof obj.context !== 'object') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'context is required and must be a User object' + } + }; + } + return { + success: true, + data: { + flagKey: obj.flagKey, + value: obj.value, + context: obj.context, + reason: typeof obj.reason === 'string' ? obj.reason : undefined + } + }; + } +} +exports.UpdateFeatureFlagInputSchema = UpdateFeatureFlagInputSchema; +// Middleware type constructors +const MIDDLEWARE_TYPES = { + auth: 'auth', + rateLimit: 'rateLimit', + adminOnly: 'adminOnly', + cors: 'cors', + logging: 'logging', + validation: 'validation', +}; +exports.MIDDLEWARE_TYPES = MIDDLEWARE_TYPES; +// Create branded type constructors with validation +const createUserId = (value) => { + return value && value.length > 0 ? value : null; +}; +exports.createUserId = createUserId; +const createFlagKey = (value) => { + return value && value.length > 0 && /^[a-zA-Z0-9._-]+$/.test(value) ? value : null; +}; +exports.createFlagKey = createFlagKey; +const createSessionId = (value) => { + return value && value.length > 0 ? value : null; +}; +exports.createSessionId = createSessionId; +// Security-critical type constructors with strict validation +const createSdkKey = (value) => { + // SDK keys typically have a specific format: sdk-{environment}-{key} + return value && value.length > 0 && value.startsWith('sdk-') ? value : null; +}; +exports.createSdkKey = createSdkKey; +const createClientSideId = (value) => { + // Client-side IDs are typically shorter and different format than SDK keys + return value && value.length > 0 && !value.startsWith('sdk-') ? value : null; +}; +exports.createClientSideId = createClientSideId; +const createApiKey = (value) => { + // API keys should be non-empty strings with minimum length for security + return value && value.length >= 20 ? value : null; +}; +exports.createApiKey = createApiKey; +const createSecretKey = (value) => { + // Secret keys require even stricter validation + return value && value.length >= 32 ? value : null; +}; +exports.createSecretKey = createSecretKey; +// Request tracking constructors +const createRequestId = (value) => { + // Request IDs should be valid UUIDs or similar format + return value && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value) ? value : null; +}; +exports.createRequestId = createRequestId; +const createTraceId = (value) => { + // Trace IDs for distributed tracing + return value && value.length > 0 && /^[a-fA-F0-9]+$/.test(value) ? value : null; +}; +exports.createTraceId = createTraceId; +const createCorrelationId = (value) => { + // Correlation IDs for request correlation + return value && value.length > 0 ? value : null; +}; +exports.createCorrelationId = createCorrelationId; +// Configuration type constructors +const createEnvironmentKey = (value) => { + // Environment keys: production, staging, development, etc. + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value : null; +}; +exports.createEnvironmentKey = createEnvironmentKey; +const createProjectKey = (value) => { + // Project keys for LaunchDarkly projects + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value : null; +}; +exports.createProjectKey = createProjectKey; +const createFeatureFlagName = (value) => { + // Feature flag names with kebab-case convention + return value && value.length > 0 && /^[a-z0-9-]+$/.test(value) ? value : null; +}; +exports.createFeatureFlagName = createFeatureFlagName; +// Identity management constructors +const createUserContextKey = (value) => { + // User context keys for LaunchDarkly contexts + return value && value.length > 0 ? value : null; +}; +exports.createUserContextKey = createUserContextKey; +const createTenantId = (value) => { + // Tenant IDs for multi-tenant applications + return value && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value) ? value : null; +}; +exports.createTenantId = createTenantId; +const createOrganizationId = (value) => { + // Organization IDs for organizational boundaries + return value && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value) ? value : null; +}; +exports.createOrganizationId = createOrganizationId; +// Type guards for runtime validation of branded types +const isUserId = (value) => { + return typeof value === 'string' && value.length > 0; +}; +exports.isUserId = isUserId; +const isFlagKey = (value) => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9._-]+$/.test(value); +}; +exports.isFlagKey = isFlagKey; +const isSessionId = (value) => { + return typeof value === 'string' && value.length > 0; +}; +exports.isSessionId = isSessionId; +const isSdkKey = (value) => { + return typeof value === 'string' && value.length > 0 && value.startsWith('sdk-'); +}; +exports.isSdkKey = isSdkKey; +const isClientSideId = (value) => { + return typeof value === 'string' && value.length > 0 && !value.startsWith('sdk-'); +}; +exports.isClientSideId = isClientSideId; +const isApiKey = (value) => { + return typeof value === 'string' && value.length >= 20; +}; +exports.isApiKey = isApiKey; +const isSecretKey = (value) => { + return typeof value === 'string' && value.length >= 32; +}; +exports.isSecretKey = isSecretKey; +const isRequestId = (value) => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value); +}; +exports.isRequestId = isRequestId; +const isTraceId = (value) => { + return typeof value === 'string' && value.length > 0 && /^[a-fA-F0-9]+$/.test(value); +}; +exports.isTraceId = isTraceId; +const isCorrelationId = (value) => { + return typeof value === 'string' && value.length > 0; +}; +exports.isCorrelationId = isCorrelationId; +const isEnvironmentKey = (value) => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value); +}; +exports.isEnvironmentKey = isEnvironmentKey; +const isProjectKey = (value) => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value); +}; +exports.isProjectKey = isProjectKey; +const isFeatureFlagName = (value) => { + return typeof value === 'string' && value.length > 0 && /^[a-z0-9-]+$/.test(value); +}; +exports.isFeatureFlagName = isFeatureFlagName; +const isUserContextKey = (value) => { + return typeof value === 'string' && value.length > 0; +}; +exports.isUserContextKey = isUserContextKey; +const isTenantId = (value) => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value); +}; +exports.isTenantId = isTenantId; +const isOrganizationId = (value) => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value); +}; +exports.isOrganizationId = isOrganizationId; +// === TRANSFORMATION FUNCTIONS - Convert between Domain and API types === +var Transform; +(function (Transform) { + // Domain to API transformations + function domainUserToApiUser(domainUser) { + return { + key: domainUser.id, + name: domainUser.name, + kind: 'user', + custom: { + organizationId: domainUser.organizationId, + ...domainUser.metadata + } + }; + } + Transform.domainUserToApiUser = domainUserToApiUser; + function domainUserContextToApiContext(userContext) { + const apiUser = domainUserToApiUser(userContext.user); + return { + ...apiUser, + custom: { + ...apiUser.custom, + environment: userContext.environment, + sessionId: userContext.session?.id, + sessionStartedAt: userContext.session?.startedAt?.toISOString() + } + }; + } + Transform.domainUserContextToApiContext = domainUserContextToApiContext; + function domainFeatureFlagsToApiResponse(domainFlags) { + return { + isDarkModeEnabled: domainFlags.darkMode, + enableHighContrast: domainFlags.highContrast, + betaFeaturesEnabled: domainFlags.betaFeatures + }; + } + Transform.domainFeatureFlagsToApiResponse = domainFeatureFlagsToApiResponse; + function domainGetFeatureFlagInputToApiRequest(input) { + return { + flagKey: input.flagKey, + context: domainUserContextToApiContext(input.userContext), + defaultValue: input.defaultValue + }; + } + Transform.domainGetFeatureFlagInputToApiRequest = domainGetFeatureFlagInputToApiRequest; + // API to Domain transformations + function apiUserToDomainUser(apiUser) { + return { + id: apiUser.key, + name: apiUser.name, + organizationId: apiUser.custom?.organizationId, + metadata: { + kind: apiUser.kind, + ...apiUser.custom + } + }; + } + Transform.apiUserToDomainUser = apiUserToDomainUser; + function apiFeatureFlagsResponseToDomainFlags(apiResponse) { + return { + darkMode: apiResponse.isDarkModeEnabled, + highContrast: apiResponse.enableHighContrast, + betaFeatures: apiResponse.betaFeaturesEnabled ?? false + }; + } + Transform.apiFeatureFlagsResponseToDomainFlags = apiFeatureFlagsResponseToDomainFlags; + function apiFeatureFlagResponseToDomainFlag(apiResponse) { + return { + key: apiResponse.key, + value: apiResponse.value, + name: apiResponse.key, // Assuming key is the name for now + enabled: true, // Assuming if returned, it's enabled + variation: apiResponse.flagVersion?.toString() + }; + } + Transform.apiFeatureFlagResponseToDomainFlag = apiFeatureFlagResponseToDomainFlag; + // Wrapper for API responses to Domain results + function apiResponseToDomainResult(apiResponse, transformer) { + if (apiResponse.success && apiResponse.data) { + return { + success: true, + data: transformer(apiResponse.data) + }; + } + else { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: apiResponse.error || 'Unknown error occurred' + } + }; + } + } + Transform.apiResponseToDomainResult = apiResponseToDomainResult; +})(Transform || (exports.Transform = Transform = {})); +class DependencyContainer { + constructor() { + this.__containerBrand = 'DependencyContainer'; + this.services = new Map(); + this.singletons = new Map(); + this.factories = new Map(); + } + register(token, factory) { + this.factories.set(token, factory); + } + registerSingleton(token, factory) { + this.factories.set(token, factory); + this.singletons.set(token, null); // Mark as singleton + } + resolve(token) { + if (this.singletons.has(token)) { + let instance = this.singletons.get(token); + if (!instance) { + const factory = this.factories.get(token); + if (!factory) { + throw new Error(`Service not registered: ${String(token)}`); + } + instance = factory(); + this.singletons.set(token, instance); + } + return instance; + } + if (this.services.has(token)) { + return this.services.get(token); + } + const factory = this.factories.get(token); + if (!factory) { + throw new Error(`Service not registered: ${String(token)}`); + } + return factory(); + } + isRegistered(token) { + return this.factories.has(token); + } +} +exports.DependencyContainer = DependencyContainer; +// Service tokens for type-safe dependency injection +const SERVICE_TOKENS = { + LaunchDarklyClient: Symbol('LaunchDarklyClient'), + FeatureFlagRepository: Symbol('FeatureFlagRepository'), + FeatureFlagService: Symbol('FeatureFlagService'), + FeatureFlagController: Symbol('FeatureFlagController'), + FeatureFlagApiClient: Symbol('FeatureFlagApiClient'), +}; +exports.SERVICE_TOKENS = SERVICE_TOKENS; +// Service Layer - Business Logic +class FeatureFlagService { + constructor(repository, apiClient) { + this.__serviceBrand = 'FeatureFlagService'; + this.repository = repository; + this.apiClient = apiClient; + } + async getUserFeatureFlags(userContext) { + try { + // Use domain types internally + const darkModeResponse = await this.repository.getFeatureFlag({ + flagKey: "is-dark-mode-enabled", + userContext, + defaultValue: false + }); + if (!darkModeResponse.success) { + return { success: false, error: darkModeResponse.error }; + } + const contrastResponse = await this.repository.getFeatureFlag({ + flagKey: "enable-high-contrast", + userContext, + defaultValue: true + }); + if (!contrastResponse.success) { + return { success: false, error: contrastResponse.error }; + } + // Extract boolean values from FeatureFlag domain objects + const darkModeValue = typeof darkModeResponse.data.value === 'boolean' ? darkModeResponse.data.value : false; + const contrastValue = typeof contrastResponse.data.value === 'boolean' ? contrastResponse.data.value : true; + return { + success: true, + data: { + darkMode: darkModeValue, + highContrast: contrastValue, + betaFeatures: false // Default for now + } + }; + } + catch (error) { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to retrieve user feature flags', + cause: error instanceof Error ? error : new Error(String(error)) + } + }; + } + } + async updateUserPreference(userContext, flagKey, value) { + try { + const response = await this.repository.updateFeatureFlag({ + flagKey, + value, + userContext, + reason: 'User preference update' + }); + return response.success + ? { success: true, data: response.data.success } + : { success: false, error: response.error }; + } + catch (error) { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to update user preference', + cause: error instanceof Error ? error : new Error(String(error)) + } + }; + } + } + async validateUser(user) { + if (!user?.id || !user?.name) { + return null; + } + // Additional validation using Zod for user context structure + try { + // Create a context-like object to validate structure + const contextLike = { + key: user.id, + name: user.name, + kind: "user" + }; + ValidationUtils.parse(ValidationSchemas.LDContext, contextLike, "User validation"); + return user; + } + catch (error) { + if (error instanceof ValidationError) { + console.warn("User validation failed:", error.message); + return null; + } + throw error; + } + } + // Type guard for runtime validation of external data using Zod + isValidUser(data) { + return (0, exports.isValidLDContext)(data); + } + // Enhanced LDContext validation with detailed error logging + isValidLDContext(data) { + const result = ValidationUtils.safeParse(ValidationSchemas.LDContext, data, "LDContext validation"); + if (!result.success) { + console.warn("LDContext validation failed:", result.error.message); + return false; + } + return true; + } + // Parse LDContext with comprehensive error handling + parseLDContext(data) { + return ValidationUtils.parse(ValidationSchemas.LDContext, data, "LDContext parsing"); + } + // Validate feature flag key + validateFeatureFlagKey(key) { + const result = ValidationUtils.safeParse(ValidationSchemas.FeatureFlagKey, key, "Feature flag key validation"); + if (!result.success) { + console.warn("Feature flag key validation failed:", result.error.message); + return false; + } + return true; + } +} +exports.FeatureFlagService = FeatureFlagService; +// === REPOSITORY IMPLEMENTATION - Bridge between Domain and API === +class LaunchDarklyRepository { + constructor(client) { + this.__repositoryBrand = 'FeatureFlagRepository'; + this.client = client; + } + async getFeatureFlag(input) { + return new Promise((resolve) => { + // Transform domain input to API request + const apiContext = Transform.domainUserContextToApiContext(input.userContext); + this.client.variation(input.flagKey, apiContext, input.defaultValue, (err, result) => { + if (err) { + resolve({ + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: `Failed to get feature flag: ${input.flagKey}`, + cause: err + } + }); + } + else { + // Transform API response to domain model + const domainFlag = { + key: input.flagKey, + value: result, + name: input.flagKey, + enabled: true, + description: `Feature flag: ${input.flagKey}` + }; + resolve({ + success: true, + data: domainFlag + }); + } + }); + }); + } + async getAllFeatureFlags(input) { + return new Promise((resolve) => { + // Transform domain input to API request + const apiContext = Transform.domainUserContextToApiContext(input.userContext); + this.client.allFlagsState(apiContext, (err, flagsState) => { + if (err) { + resolve({ + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to retrieve all feature flags', + cause: err + } + }); + } + else { + const values = flagsState?.allValues() ?? {}; + const booleanValues = {}; + let count = 0; + for (const [key, value] of Object.entries(values)) { + if (typeof value === 'boolean') { + // Apply filters if provided + if (input.filters?.enabled !== undefined && value !== input.filters.enabled) { + continue; + } + if (input.filters?.category && !key.includes(input.filters.category)) { + continue; + } + if (input.filters?.tags && !input.filters.tags.some(tag => key.includes(tag))) { + continue; + } + // Apply pagination + if (input.offset && count < input.offset) { + count++; + continue; + } + if (input.limit && Object.keys(booleanValues).length >= input.limit) { + break; + } + booleanValues[key] = value; + count++; + } + } + const totalCount = Object.keys(values).filter(key => typeof values[key] === 'boolean').length; + const returnedCount = Object.keys(booleanValues).length; + // Transform to domain FeatureFlags type + const domainFlags = { + darkMode: booleanValues['is-dark-mode-enabled'] ?? false, + highContrast: booleanValues['enable-high-contrast'] ?? false, + betaFeatures: booleanValues['beta-features-enabled'] ?? false + }; + resolve({ + success: true, + data: domainFlags + }); + } + }); + }); + } + async updateFeatureFlag(input) { + return { + success: false, + error: { + code: 'METHOD_NOT_SUPPORTED', + message: 'Feature flag updates not supported in client-side SDK', + data: { flagKey: input.flagKey, attemptedValue: input.value } + } + }; + } + async deleteFeatureFlag(input) { + return { + success: false, + error: { + code: 'METHOD_NOT_SUPPORTED', + message: 'Feature flag deletion not supported in client-side SDK', + data: { flagKey: input.flagKey } + } + }; + } +} +exports.LaunchDarklyRepository = LaunchDarklyRepository; +// API Boundary - Controllers/Handlers with explicit interface conformance +class FeatureFlagController { + constructor(service) { + this.__controllerBrand = 'FeatureFlagController'; + this.service = service; + } + async getUserFlags(userId) { + try { + const user = { + kind: "user", + name: "User Name", + key: userId, + }; + const validatedUser = await this.service.validateUser(user); + if (!validatedUser) { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'Invalid user data provided', + data: { userId } + } + }; + } + const response = await this.service.getUserFeatureFlags(validatedUser); + return response; + } + catch (error) { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to retrieve user flags', + cause: error instanceof Error ? error : new Error(String(error)) + } + }; + } + } + async updateUserFlag(userId, flagKey, value) { + try { + const user = { + kind: "user", + name: "User Name", + key: userId, + }; + const response = await this.service.updateUserPreference(user, flagKey, value); + return response; + } + catch (error) { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to update user flag', + cause: error instanceof Error ? error : new Error(String(error)) + } + }; + } + } +} +exports.FeatureFlagController = FeatureFlagController; +// Utility functions with explicit return types and validation +function createUser(key, name) { + if (!key || !name) { + return null; + } + return { + kind: "user", + name, + key, + }; +} +// Type guard utility functions for external data validation +function isValidApiResponse(data) { + return (typeof data === 'object' && + data !== null && + data !== undefined && + 'data' in data && + 'success' in data && + typeof data.success === 'boolean'); +} +function validateExternalUserData(data) { + if (typeof data === 'object' && + data !== null && + data !== undefined && + 'key' in data && + 'name' in data && + typeof data.key === 'string' && + typeof data.name === 'string') { + return { + kind: data.kind ?? 'user', + name: data.name, + key: data.key, + }; + } + return null; +} +async function initializeClient(sdkKey) { + const client = LaunchDarkly.init(sdkKey); + await client.waitForInitialization(); + return client; +} +function logFeatureFlag(flagName, value) { + if (value) { + console.log(`${flagName} is enabled`); + } + else { + console.log(`${flagName} is disabled`); + } +} +// Main execution with dependency injection container +async function main() { + const SDK_KEY = ""; + // === VALIDATION OF INPUTS === + console.log("🔍 Validating SDK key and context..."); + // Validate SDK key before using it + try { + ValidationUtils.parse(ValidationSchemas.SDKKey, SDK_KEY, "SDK key validation"); + console.log("✓ SDK key validation passed"); + } + catch (error) { + if (error instanceof ValidationError) { + console.error("❌ SDK key validation failed:", error.message); + console.error("Please replace '' with your actual LaunchDarkly SDK key"); + return; + } + throw error; + } + const context = createUser("example-context-key", "Sandy"); + if (!context) { + console.error("❌ Failed to create user context"); + return; + } + // Validate the created context + try { + const validatedContext = ValidationUtils.parse(ValidationSchemas.LDContext, context, "Context validation"); + console.log("✓ Context validation passed:", { + key: validatedContext.key, + name: validatedContext.name, + kind: validatedContext.kind + }); + } + catch (error) { + if (error instanceof ValidationError) { + console.error("❌ Context validation failed:", error.message); + console.error("Formatted errors:", error.getFormattedErrors()); + return; + } + throw error; + } + try { + // Initialize dependency injection container + const container = new DependencyContainer(); + // Register services with explicit typing + container.registerSingleton(SERVICE_TOKENS.LaunchDarklyClient, () => { + return LaunchDarkly.init(SDK_KEY); + }); + container.register(SERVICE_TOKENS.FeatureFlagRepository, () => { + const client = container.resolve(SERVICE_TOKENS.LaunchDarklyClient); + return new LaunchDarklyRepository(client); + }); + container.register(SERVICE_TOKENS.FeatureFlagService, () => { + const repository = container.resolve(SERVICE_TOKENS.FeatureFlagRepository); + return new FeatureFlagService(repository); + }); + container.register(SERVICE_TOKENS.FeatureFlagController, () => { + const service = container.resolve(SERVICE_TOKENS.FeatureFlagService); + return new FeatureFlagController(service); + }); + // Wait for LaunchDarkly client initialization + const client = container.resolve(SERVICE_TOKENS.LaunchDarklyClient); + await client.waitForInitialization(); + // Use the container to resolve dependencies + const controller = container.resolve(SERVICE_TOKENS.FeatureFlagController); + const response = await controller.getUserFlags(context.key); + if (response.success && response.data) { + console.log("🚀 Feature flags retrieved successfully"); + // Validate individual flag results + const darkModeResult = ValidationUtils.safeParse(ValidationSchemas.VariationResult, { + key: "is-dark-mode-enabled", + value: response.data.isDarkModeEnabled + }, "Dark mode flag validation"); + if (darkModeResult.success) { + logFeatureFlag("Dark mode", darkModeResult.data.value); + } + else { + console.warn("Dark mode flag validation failed:", darkModeResult.error.message); + logFeatureFlag("Dark mode", response.data.isDarkModeEnabled); + } + const highContrastResult = ValidationUtils.safeParse(ValidationSchemas.VariationResult, { + key: "enable-high-contrast", + value: response.data.enableHighContrast + }, "High contrast flag validation"); + if (highContrastResult.success) { + logFeatureFlag("High contrast", highContrastResult.data.value); + } + else { + console.warn("High contrast flag validation failed:", highContrastResult.error.message); + logFeatureFlag("High contrast", response.data.enableHighContrast); + } + } + else { + console.error("❌ Failed to get user flags:", response.error); + } + } + catch (error) { + console.error("Application failed to start:", error); + } +} +//# sourceMappingURL=sample.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/sample.js.map b/launchdarkly/node/dist/sample.js.map new file mode 100644 index 00000000..4934d7c4 --- /dev/null +++ b/launchdarkly/node/dist/sample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sample.js","sourceRoot":"","sources":["../sample.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AA8lDF,gCAAU;AACV,4CAAgB;AAChB,wCAAc;AACd,oBAAI;AACJ,gDAAkB;AAClB,4DAAwB;AAjmDzB;;;;;;GAMG;AAEH,wEAAwE;AACxE,iEAAiE;AACjE,6BAAwB;AAsBxB,oDAAoD;AACpD,MAAM,iBAAiB,GAAG;IACzB,wCAAwC;IACxC,SAAS,EAAE,OAAC,CAAC,MAAM,CAAC;QACnB,GAAG,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,yBAAyB,CAAC;QACjD,IAAI,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;QAC3B,IAAI,EAAE,OAAC,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- /dev/null +++ b/launchdarkly/node/dist/types.d.ts @@ -0,0 +1,436 @@ +/** + * Advanced TypeScript utility types for type-safe database operations + * with comprehensive create/update input types and conditional type transformations + */ +import { z } from "zod"; +/** + * Extract keys that are optional in a type + */ +type OptionalKeys = { + [K in keyof T]-?: {} extends Pick ? K : never; +}[keyof T]; +/** + * Extract keys that are required in a type + */ +type RequiredKeys = { + [K in keyof T]-?: {} extends Pick ? never : K; +}[keyof T]; +/** + * Make only specific keys required + */ +type RequireOnly = Partial & Required>; +/** + * Make only specific keys optional + */ +type OptionalOnly = Omit & Partial>; +/** + * Deep partial type for nested objects + */ +type DeepPartial = { + [P in keyof T]?: T[P] extends Array ? Array> : T[P] extends ReadonlyArray ? ReadonlyArray> : T[P] extends object ? DeepPartial : T[P]; +}; +/** + * Deep required type for nested objects + */ +type DeepRequired = { + [P in keyof T]-?: T[P] extends Array ? Array> : T[P] extends ReadonlyArray ? ReadonlyArray> : T[P] extends object ? DeepRequired : T[P]; +}; +/** + * Extract non-function properties from a type + */ +type NonFunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? never : K; +}[keyof T]; +type NonFunctionProperties = Pick>; +/** + * Extract only primitive properties (exclude objects and arrays) + */ +type PrimitivePropertyNames = { + [K in keyof T]: T[K] extends string | number | boolean | null | undefined ? K : never; +}[keyof T]; +type PrimitiveProperties = Pick>; +/** + * Standard database fields that should be excluded from input types + */ +type DatabaseManagedFields = 'id' | 'createdAt' | 'updatedAt' | 'deletedAt'; +/** + * Readonly fields that cannot be updated after creation + */ +type ReadonlyFields = 'id' | 'createdAt'; +/** + * Create input type that excludes database-managed fields + */ +type CreateInput = Omit; +/** + * Update input type that excludes readonly fields and makes all others optional + */ +type UpdateInput = Partial>; +/** + * Patch input type for partial updates with ID required + */ +type PatchInput = UpdateInput & { + id: T extends { + id: infer ID; + } ? ID : string; +}; +/** + * Replace input type for full entity replacement (all fields required except database-managed) + */ +type ReplaceInput = Required>; +/** + * Upsert input type that allows either create or update operations + */ +type UpsertInput = CreateInput | (UpdateInput & { + id: T extends { + id: infer ID; + } ? ID : string; +}); +/** + * Filter input type for queries (all fields optional, supports nested filtering) + */ +type FilterInput = DeepPartial>; +/** + * Sort input type for ordering results + */ +type SortInput = { + [K in keyof NonFunctionProperties]?: 'ASC' | 'DESC'; +}; +/** + * Projection type for selecting specific fields + */ +type ProjectionInput = { + [K in keyof NonFunctionProperties]?: boolean; +}; +/** + * Extract relation fields from an entity + */ +type RelationFields = { + [K in keyof T]: T[K] extends Array ? K : T[K] extends object ? T[K] extends Date | string | number | boolean ? never : K : never; +}[keyof T]; +/** + * Type for specifying which relations to load + */ +type RelationOptions = { + [K in RelationFields]?: boolean | (T[K] extends Array ? RelationOptions : RelationOptions); +}; +/** + * Entity with relations loaded + */ +type WithRelations> = T & { + [K in keyof R]: R[K] extends true ? T[K] : R[K] extends object ? T[K] extends Array ? Array> : WithRelations : T[K]; +}; +/** + * Extract Zod schema type from a schema + */ +type InferZodSchema = T extends z.ZodSchema ? U : never; +/** + * Create a validation schema type from an entity + */ +type ValidationSchema = z.ZodSchema>; +/** + * Transform type for converting between different representations + */ +type Transform = (input: TInput) => TOutput; +/** + * Bi-directional transform + */ +interface BiTransform { + toDto: Transform; + fromDto: Transform; +} +/** + * Conditional type for handling nullable fields + */ +type NullableFields = { + [K in keyof T]: null extends T[K] ? K : never; +}[keyof T]; +/** + * Make nullable fields optional in input types + */ +type OptionalNullableInput = OptionalOnly>; +/** + * Type-safe deep merge utility type + */ +type DeepMerge = { + [K in keyof T | keyof U]: K extends keyof U ? K extends keyof T ? T[K] extends object ? U[K] extends object ? DeepMerge : U[K] : U[K] : U[K] : K extends keyof T ? T[K] : never; +}; +/** + * Extract array element type + */ +type ArrayElement = T extends Array ? U : never; +/** + * Create lookup type from array of objects + */ +type Lookup> = { + [P in ArrayElement[K]]: Extract, Record>; +}; +/** + * Type-safe key-value pair + */ +type KeyValuePair = { + key: K; + value: T[K]; +}; +/** + * Standard operation result with success/error states + */ +type OperationResult = { + success: true; + data: TData; + error?: never; +} | { + success: false; + data?: never; + error: TError; +}; +/** + * Async operation result + */ +type AsyncOperationResult = Promise>; +/** + * Paginated result wrapper + */ +interface PaginatedResult { + data: T[]; + pagination: { + page: number; + limit: number; + total: number; + totalPages: number; + hasNext: boolean; + hasPrev: boolean; + }; +} +/** + * Bulk operation result + */ +interface BulkOperationResult { + successful: T[]; + failed: Array<{ + item: T; + error: Error; + }>; + totalProcessed: number; + successCount: number; + failureCount: number; +} +/** + * Comparison operators for filtering + */ +type ComparisonOperator = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'nin' | 'like' | 'ilike' | 'regex' | 'exists' | 'nexists'; +/** + * Filter condition for a single field + */ +type FieldFilter = { + [K in ComparisonOperator]?: T; +} | T; +/** + * Advanced filter input with operators + */ +type AdvancedFilterInput = { + [K in keyof NonFunctionProperties]?: FieldFilter; +} & { + $and?: AdvancedFilterInput[]; + $or?: AdvancedFilterInput[]; + $not?: AdvancedFilterInput; +}; +/** + * Aggregation pipeline type + */ +interface AggregationPipeline { + match?: FilterInput; + group?: { + by: keyof T | Array; + count?: boolean; + sum?: keyof T | Array; + avg?: keyof T | Array; + min?: keyof T | Array; + max?: keyof T | Array; + }; + sort?: SortInput; + limit?: number; + skip?: number; +} +/** + * Extract entity type from repository type + */ +type EntityFromRepository = T extends { + create(input: infer U): any; +} ? U extends CreateInput ? E : never : never; +/** + * Type-safe entity constructor + */ +type EntityConstructor = new (...args: any[]) => T; +/** + * Entity metadata for reflection + */ +interface EntityMetadata { + name: string; + tableName: string; + primaryKey: keyof T; + columns: Array<{ + property: keyof T; + type: string; + nullable: boolean; + unique: boolean; + default?: any; + }>; + relations: Array<{ + property: keyof T; + type: 'one-to-one' | 'one-to-many' | 'many-to-one' | 'many-to-many'; + target: string; + inverseSide?: string; + }>; + indexes: Array<{ + name: string; + columns: Array; + unique: boolean; + }>; +} +/** + * Database column definition + */ +interface ColumnDefinition { + name: string; + type: string; + length?: number; + precision?: number; + scale?: number; + nullable: boolean; + unique: boolean; + primaryKey: boolean; + autoIncrement: boolean; + default?: any; + comment?: string; +} +/** + * Database table definition + */ +interface TableDefinition { + name: string; + columns: ColumnDefinition[]; + indexes: Array<{ + name: string; + columns: string[]; + unique: boolean; + }>; + foreignKeys: Array<{ + columnNames: string[]; + referencedTableName: string; + referencedColumnNames: string[]; + onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT'; + onUpdate?: 'CASCADE' | 'SET NULL' | 'RESTRICT'; + }>; +} +/** + * Migration operation types + */ +type MigrationOperation = { + type: 'CREATE_TABLE'; + table: TableDefinition; +} | { + type: 'DROP_TABLE'; + tableName: string; +} | { + type: 'ALTER_TABLE'; + tableName: string; + changes: TableChange[]; +} | { + type: 'CREATE_INDEX'; + tableName: string; + index: { + name: string; + columns: string[]; + unique: boolean; + }; +} | { + type: 'DROP_INDEX'; + indexName: string; +} | { + type: 'EXECUTE_SQL'; + sql: string; +}; +type TableChange = { + type: 'ADD_COLUMN'; + column: ColumnDefinition; +} | { + type: 'DROP_COLUMN'; + columnName: string; +} | { + type: 'ALTER_COLUMN'; + columnName: string; + changes: Partial; +} | { + type: 'RENAME_COLUMN'; + oldName: string; + newName: string; +}; +/** + * Assert that two types are exactly equal + */ +type AssertEqual = T extends U ? U extends T ? true : false : false; +/** + * Assert that T extends U + */ +type AssertExtends = T extends U ? true : false; +/** + * Test type for compile-time type checking + */ +type TypeTest = T; +export type { OptionalKeys, RequiredKeys, RequireOnly, OptionalOnly, DeepPartial, DeepRequired, NonFunctionProperties, PrimitiveProperties, DatabaseManagedFields, ReadonlyFields, CreateInput, UpdateInput, PatchInput, ReplaceInput, UpsertInput, FilterInput, SortInput, ProjectionInput, RelationFields, RelationOptions, WithRelations, InferZodSchema, ValidationSchema, Transform, BiTransform, NullableFields, OptionalNullableInput, DeepMerge, ArrayElement, Lookup, KeyValuePair, OperationResult, AsyncOperationResult, PaginatedResult, BulkOperationResult, ComparisonOperator, FieldFilter, AdvancedFilterInput, AggregationPipeline, EntityFromRepository, EntityConstructor, EntityMetadata, ColumnDefinition, TableDefinition, MigrationOperation, TableChange, AssertEqual, AssertExtends, TypeTest }; +/** + * Type guard to check if a value is defined + */ +export declare function isDefined(value: T | undefined | null): value is T; +/** + * Type guard to check if a value is a non-empty string + */ +export declare function isNonEmptyString(value: unknown): value is string; +/** + * Type guard to check if a value is a positive number + */ +export declare function isPositiveNumber(value: unknown): value is number; +/** + * Create a type-safe object transformation function + */ +export declare function createTransform(transformFn: (input: TInput) => TOutput): Transform; +/** + * Create a bi-directional transformation + */ +export declare function createBiTransform(toDto: Transform, fromDto: Transform): BiTransform; +/** + * Deep merge two objects with type safety + */ +export declare function deepMerge(target: T, source: U): DeepMerge; +/** + * Pick only defined values from an object + */ +export declare function pickDefined>(obj: T): { + [K in keyof T]: T[K] extends undefined ? never : T[K]; +}; +/** + * Create a lookup table from an array of objects + */ +export declare function createLookup, K extends keyof T>(array: readonly T[], key: K): Lookup; +type ExampleEntity = { + id: string; + name: string; + email?: string; + isActive: boolean; + createdAt: Date; + updatedAt: Date; + organization?: { + id: string; + name: string; + }; + roles: Array<{ + id: string; + name: string; + }>; +}; +type ExampleCreateInput = CreateInput; +type ExampleUpdateInput = UpdateInput; +type ExampleFilterInput = FilterInput; +type ExampleRelationOptions = RelationOptions; +export type { ExampleEntity, ExampleCreateInput, ExampleUpdateInput, ExampleFilterInput, ExampleRelationOptions }; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/launchdarkly/node/dist/types.d.ts.map b/launchdarkly/node/dist/types.d.ts.map new file mode 100644 index 00000000..acd0659e --- /dev/null +++ b/launchdarkly/node/dist/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../types.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB;;GAEG;AACH,KAAK,YAAY,CAAC,CAAC,I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,GAAG,eAAe,CAAC,aAAa,CAAC,CAAC;AAS7D,YAAY,EACV,aAAa,EACb,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,EAClB,sBAAsB,EACvB,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/dist/types.js b/launchdarkly/node/dist/types.js new file mode 100644 index 00000000..f13158eb --- /dev/null +++ b/launchdarkly/node/dist/types.js @@ -0,0 +1,103 @@ +"use strict"; +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isDefined = isDefined; +exports.isNonEmptyString = isNonEmptyString; +exports.isPositiveNumber = isPositiveNumber; +exports.createTransform = createTransform; +exports.createBiTransform = createBiTransform; +exports.deepMerge = deepMerge; +exports.pickDefined = pickDefined; +exports.createLookup = createLookup; +// ===== UTILITY FUNCTIONS ===== +/** + * Type guard to check if a value is defined + */ +function isDefined(value) { + return value !== undefined && value !== null; +} +/** + * Type guard to check if a value is a non-empty string + */ +function isNonEmptyString(value) { + return typeof value === 'string' && value.length > 0; +} +/** + * Type guard to check if a value is a positive number + */ +function isPositiveNumber(value) { + return typeof value === 'number' && value > 0 && !isNaN(value); +} +/** + * Create a type-safe object transformation function + */ +function createTransform(transformFn) { + return transformFn; +} +/** + * Create a bi-directional transformation + */ +function createBiTransform(toDto, fromDto) { + return { toDto, fromDto }; +} +/** + * Deep merge two objects with type safety + */ +function deepMerge(target, source) { + const result = { ...target }; + for (const key in source) { + if (source.hasOwnProperty(key)) { + const sourceValue = source[key]; + const targetValue = result[key]; + if (typeof sourceValue === 'object' && + sourceValue !== null && + !Array.isArray(sourceValue) && + typeof targetValue === 'object' && + targetValue !== null && + !Array.isArray(targetValue)) { + result[key] = deepMerge(targetValue, sourceValue); + } + else { + result[key] = sourceValue; + } + } + } + return result; +} +/** + * Pick only defined values from an object + */ +function pickDefined(obj) { + const result = {}; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key] !== undefined) { + result[key] = obj[key]; + } + } + return result; +} +/** + * Create a lookup table from an array of objects + */ +function createLookup(array, key) { + const lookup = {}; + for (const item of array) { + lookup[item[key]] = item; + } + return lookup; +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/launchdarkly/node/dist/types.js.map b/launchdarkly/node/dist/types.js.map new file mode 100644 index 00000000..da04b9bc --- /dev/null +++ b/launchdarkly/node/dist/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AA2hBH,8BAEC;AAKD,4CAEC;AAKD,4CAEC;AAKD,0CAIC;AAKD,8CAKC;AAKD,8BAwBC;AAKD,kCAYC;AAKD,oCAWC;AAtGD,gCAAgC;AAEhC;;GAEG;AACH,SAAgB,SAAS,CAAI,KAA2B;IACtD,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,CAAC;AAC/C,CAAC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,KAAc;IAC7C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AACvD,CAAC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,KAAc;IAC7C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACjE,CAAC;AAED;;GAEG;AACH,SAAgB,eAAe,CAC7B,WAAuC;IAEvC,OAAO,WAAW,CAAC;AACrB,CAAC;AAED;;GAEG;AACH,SAAgB,iBAAiB,CA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;GAEG;AACH,SAAgB,YAAY,CAC1B,KAAmB,EACnB,GAAM;IAEN,MAAM,MAAM,GAAG,EAAS,CAAC;IAEzB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC;IAC3B,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/launchdarkly/node/entities.ts b/launchdarkly/node/entities.ts new file mode 100644 index 00000000..d452d099 --- /dev/null +++ b/launchdarkly/node/entities.ts @@ -0,0 +1,639 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Type-safe database entity definitions using TypeORM decorators + * with proper utility types for create/update input types. + */ + +import { z } from "zod"; + +// ===== UTILITY TYPES FOR CREATE/UPDATE OPERATIONS ===== + +/** + * Omit specific fields for create operations + */ +type CreateInput = Omit; + +/** + * Make all fields optional except id for update operations + */ +type UpdateInput = Partial> & { id: string }; + +/** + * Extract only the fields that can be updated (excludes readonly fields) + */ +type UpdatableFields = Omit; + +/** + * Partial update input with only updatable fields + */ +type PartialUpdateInput = Partial> & { id: string }; + +/** + * Relations type for handling entity relationships + */ +type Relations = { + [K in keyof T]: T[K] extends Array ? U[] : T[K] extends object ? T[K] : never; +}; + +// ===== BRANDED TYPES FOR TYPE SAFETY ===== + +type BrandedString = string & { readonly __brand: T }; + +type UserId = BrandedString<'UserId'>; +type FlagKey = BrandedString<'FlagKey'>; +type OrganizationId = BrandedString<'OrganizationId'>; +type SessionId = BrandedString<'SessionId'>; +type EnvironmentKey = BrandedString<'EnvironmentKey'>; + +// ===== MOCK TYPEORM DECORATORS (since TypeORM is not installed) ===== + +/** + * Mock TypeORM decorators for demonstration purposes + * In actual implementation, these would be imported from 'typeorm' + */ + +// Entity decorator +function Entity(name?: string): ClassDecorator { + return function (target: any) { + target.__entityName = name || target.name; + return target; + }; +} + +// Primary key decorator +function PrimaryColumn(options?: { type?: string; generated?: boolean }): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + target.__primaryKey = propertyKey; + }; +} + +// Column decorator +function Column(options?: { + type?: string; + length?: number; + nullable?: boolean; + unique?: boolean; + default?: any; + comment?: string; +}): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + if (!target.__columns) target.__columns = []; + target.__columns.push({ property: propertyKey, options }); + }; +} + +// Index decorator +function Index(name?: string, options?: { unique?: boolean }): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + if (!target.__indexes) target.__indexes = []; + target.__indexes.push({ property: propertyKey, name, options }); + }; +} + +// Relation decorators +function ManyToOne(type: () => T, options?: { onDelete?: string; onUpdate?: string }): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + if (!target.__relations) target.__relations = []; + target.__relations.push({ type: 'many-to-one', property: propertyKey, target: type, options }); + }; +} + +function OneToMany(type: () => T, inverseSide: (obj: T) => any): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + if (!target.__relations) target.__relations = []; + target.__relations.push({ type: 'one-to-many', property: propertyKey, target: type, inverseSide }); + }; +} + +function ManyToMany(type: () => T, options?: { cascade?: boolean }): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + if (!target.__relations) target.__relations = []; + target.__relations.push({ type: 'many-to-many', property: propertyKey, target: type, options }); + }; +} + +function JoinTable(options?: { name?: string }): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + if (!target.__joinTables) target.__joinTables = []; + target.__joinTables.push({ property: propertyKey, options }); + }; +} + +function JoinColumn(options?: { name?: string; referencedColumnName?: string }): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + if (!target.__joinColumns) target.__joinColumns = []; + target.__joinColumns.push({ property: propertyKey, options }); + }; +} + +// Timestamp decorators +function CreateDateColumn(): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + if (!target.__timestamps) target.__timestamps = []; + target.__timestamps.push({ property: propertyKey, type: 'create' }); + }; +} + +function UpdateDateColumn(): PropertyDecorator { + return function (target: any, propertyKey: string | symbol) { + if (!target.__timestamps) target.__timestamps = []; + target.__timestamps.push({ property: propertyKey, type: 'update' }); + }; +} + +// ===== ENTITY DEFINITIONS ===== + +/** + * Organization entity for multi-tenant support + */ +@Entity('organizations') +export class Organization { + @PrimaryColumn({ type: 'varchar', generated: true }) + public id!: OrganizationId; + + @Column({ type: 'varchar', length: 255, nullable: false }) + @Index('idx_organization_name', { unique: true }) + public name!: string; + + @Column({ type: 'varchar', length: 500, nullable: true }) + public description?: string; + + @Column({ type: 'varchar', length: 255, nullable: true }) + public domain?: string; + + @Column({ type: 'json', nullable: true }) + public settings?: Record; + + @Column({ type: 'boolean', default: true }) + public isActive!: boolean; + + @CreateDateColumn() + public createdAt!: Date; + + @UpdateDateColumn() + public updatedAt!: Date; + + // Relations + @OneToMany(() => User, user => user.organization) + public users!: User[]; + + @OneToMany(() => FeatureFlag, flag => flag.organization) + public featureFlags!: FeatureFlag[]; +} + +/** + * User entity extending LaunchDarkly context + */ +@Entity('users') +export class User { + @PrimaryColumn({ type: 'varchar', generated: true }) + public id!: UserId; + + @Column({ type: 'varchar', length: 255, nullable: false }) + @Index('idx_user_key', { unique: true }) + public key!: string; + + @Column({ type: 'varchar', length: 255, nullable: false }) + public name!: string; + + @Column({ type: 'varchar', length: 255, nullable: true }) + @Index('idx_user_email') + public email?: string; + + @Column({ type: 'enum', enum: ['user', 'organization', 'device'], default: 'user' }) + public kind!: 'user' | 'organization' | 'device'; + + @Column({ type: 'json', nullable: true }) + public custom?: Record; + + @Column({ type: 'varchar', length: 255, nullable: true }) + @JoinColumn({ name: 'organization_id' }) + public organizationId?: OrganizationId; + + @Column({ type: 'boolean', default: true }) + public isActive!: boolean; + + @Column({ type: 'timestamp', nullable: true }) + public lastLoginAt?: Date; + + @CreateDateColumn() + public createdAt!: Date; + + @UpdateDateColumn() + public updatedAt!: Date; + + // Relations + @ManyToOne(() => Organization, organization => organization.users, { onDelete: 'SET NULL' }) + @JoinColumn({ name: 'organization_id' }) + public organization?: Organization; + + @OneToMany(() => UserFlag, userFlag => userFlag.user) + public userFlags!: UserFlag[]; + + @OneToMany(() => UserSession, session => session.user) + public sessions!: UserSession[]; +} + +/** + * Feature flag entity for flag management + */ +@Entity('feature_flags') +export class FeatureFlag { + @PrimaryColumn({ type: 'varchar', generated: true }) + public id!: string; + + @Column({ type: 'varchar', length: 255, nullable: false }) + @Index('idx_flag_key', { unique: true }) + public key!: FlagKey; + + @Column({ type: 'varchar', length: 255, nullable: false }) + public name!: string; + + @Column({ type: 'text', nullable: true }) + public description?: string; + + @Column({ type: 'enum', enum: ['boolean', 'string', 'number', 'json'], default: 'boolean' }) + public valueType!: 'boolean' | 'string' | 'number' | 'json'; + + @Column({ type: 'json', nullable: false }) + public defaultValue!: boolean | string | number | Record; + + @Column({ type: 'json', nullable: true }) + public variations?: Array<{ + value: boolean | string | number | Record; + name: string; + description?: string; + }>; + + @Column({ type: 'json', nullable: true }) + public targeting?: { + rules?: Array<{ + clauses: Array<{ + attribute: string; + op: string; + values: unknown[]; + }>; + variation: number; + }>; + fallthrough?: { variation: number }; + }; + + @Column({ type: 'boolean', default: false }) + public isEnabled!: boolean; + + @Column({ type: 'boolean', default: false }) + public isArchived!: boolean; + + @Column({ type: 'varchar', length: 255, nullable: true }) + public category?: string; + + @Column({ type: 'json', nullable: true }) + public tags?: string[]; + + @Column({ type: 'varchar', length: 255, nullable: true }) + @JoinColumn({ name: 'organization_id' }) + public organizationId?: OrganizationId; + + @Column({ type: 'varchar', length: 255, nullable: false, default: 'production' }) + @Index('idx_flag_environment') + public environment!: EnvironmentKey; + + @CreateDateColumn() + public createdAt!: Date; + + @UpdateDateColumn() + public updatedAt!: Date; + + // Relations + @ManyToOne(() => Organization, organization => organization.featureFlags, { onDelete: 'CASCADE' }) + @JoinColumn({ name: 'organization_id' }) + public organization?: Organization; + + @OneToMany(() => UserFlag, userFlag => userFlag.featureFlag) + public userFlags!: UserFlag[]; + + @OneToMany(() => FlagEvent, event => event.featureFlag) + public events!: FlagEvent[]; +} + +/** + * User-specific flag overrides + */ +@Entity('user_flags') +export class UserFlag { + @PrimaryColumn({ type: 'varchar', generated: true }) + public id!: string; + + @Column({ type: 'varchar', length: 255, nullable: false }) + @JoinColumn({ name: 'user_id' }) + public userId!: UserId; + + @Column({ type: 'varchar', length: 255, nullable: false }) + @JoinColumn({ name: 'feature_flag_id' }) + public featureFlagId!: string; + + @Column({ type: 'json', nullable: false }) + public value!: boolean | string | number | Record; + + @Column({ type: 'text', nullable: true }) + public reason?: string; + + @Column({ type: 'boolean', default: true }) + public isActive!: boolean; + + @Column({ type: 'timestamp', nullable: true }) + public expiresAt?: Date; + + @CreateDateColumn() + public createdAt!: Date; + + @UpdateDateColumn() + public updatedAt!: Date; + + // Relations + @ManyToOne(() => User, user => user.userFlags, { onDelete: 'CASCADE' }) + @JoinColumn({ name: 'user_id' }) + public user!: User; + + @ManyToOne(() => FeatureFlag, flag => flag.userFlags, { onDelete: 'CASCADE' }) + @JoinColumn({ name: 'feature_flag_id' }) + public featureFlag!: FeatureFlag; + + // Composite index for unique user-flag combination + @Index('idx_user_flag_unique', { unique: true }) + public static userFlagIndex = ['userId', 'featureFlagId']; +} + +/** + * User session tracking + */ +@Entity('user_sessions') +export class UserSession { + @PrimaryColumn({ type: 'varchar', generated: true }) + public id!: SessionId; + + @Column({ type: 'varchar', length: 255, nullable: false }) + @JoinColumn({ name: 'user_id' }) + public userId!: UserId; + + @Column({ type: 'varchar', length: 255, nullable: true }) + public deviceId?: string; + + @Column({ type: 'varchar', length: 255, nullable: true }) + public userAgent?: string; + + @Column({ type: 'inet', nullable: true }) + public ipAddress?: string; + + @Column({ type: 'json', nullable: true }) + public context?: Record; + + @Column({ type: 'boolean', default: true }) + public isActive!: boolean; + + @Column({ type: 'timestamp', nullable: true }) + public lastActivityAt?: Date; + + @Column({ type: 'timestamp', nullable: true }) + public expiresAt?: Date; + + @CreateDateColumn() + public createdAt!: Date; + + @UpdateDateColumn() + public updatedAt!: Date; + + // Relations + @ManyToOne(() => User, user => user.sessions, { onDelete: 'CASCADE' }) + @JoinColumn({ name: 'user_id' }) + public user!: User; +} + +/** + * Feature flag event tracking + */ +@Entity('flag_events') +export class FlagEvent { + @PrimaryColumn({ type: 'varchar', generated: true }) + public id!: string; + + @Column({ type: 'varchar', length: 255, nullable: false }) + @JoinColumn({ name: 'feature_flag_id' }) + public featureFlagId!: string; + + @Column({ type: 'varchar', length: 255, nullable: true }) + @JoinColumn({ name: 'user_id' }) + public userId?: UserId; + + @Column({ type: 'enum', enum: ['evaluation', 'update', 'create', 'delete', 'toggle'], nullable: false }) + @Index('idx_event_type') + public eventType!: 'evaluation' | 'update' | 'create' | 'delete' | 'toggle'; + + @Column({ type: 'json', nullable: true }) + public previousValue?: unknown; + + @Column({ type: 'json', nullable: true }) + public newValue?: unknown; + + @Column({ type: 'json', nullable: true }) + public context?: Record; + + @Column({ type: 'text', nullable: true }) + public reason?: string; + + @Column({ type: 'varchar', length: 255, nullable: true }) + public source?: string; + + @CreateDateColumn() + public createdAt!: Date; + + // Relations + @ManyToOne(() => FeatureFlag, flag => flag.events, { onDelete: 'CASCADE' }) + @JoinColumn({ name: 'feature_flag_id' }) + public featureFlag!: FeatureFlag; + + @ManyToOne(() => User, { onDelete: 'SET NULL' }) + @JoinColumn({ name: 'user_id' }) + public user?: User; +} + +// ===== UTILITY TYPES FOR ENTITY OPERATIONS ===== + +/** + * Create input types for each entity + */ +export type CreateOrganizationInput = CreateInput; +export type CreateUserInput = CreateInput; +export type CreateFeatureFlagInput = CreateInput; +export type CreateUserFlagInput = CreateInput; +export type CreateUserSessionInput = CreateInput; +export type CreateFlagEventInput = CreateInput; + +/** + * Update input types for each entity + */ +export type UpdateOrganizationInput = PartialUpdateInput; +export type UpdateUserInput = PartialUpdateInput; +export type UpdateFeatureFlagInput = PartialUpdateInput; +export type UpdateUserFlagInput = PartialUpdateInput; +export type UpdateUserSessionInput = PartialUpdateInput; + +/** + * Query filter types for type-safe queries + */ +export interface OrganizationFilters { + name?: string; + domain?: string; + isActive?: boolean; +} + +export interface UserFilters { + organizationId?: OrganizationId; + email?: string; + kind?: 'user' | 'organization' | 'device'; + isActive?: boolean; +} + +export interface FeatureFlagFilters { + organizationId?: OrganizationId; + environment?: EnvironmentKey; + category?: string; + tags?: string[]; + isEnabled?: boolean; + isArchived?: boolean; +} + +export interface UserFlagFilters { + userId?: UserId; + featureFlagId?: string; + isActive?: boolean; +} + +/** + * Relation loading options for type-safe eager loading + */ +export interface EntityRelations { + Organization: { + users?: boolean; + featureFlags?: boolean; + }; + User: { + organization?: boolean; + userFlags?: boolean; + sessions?: boolean; + }; + FeatureFlag: { + organization?: boolean; + userFlags?: boolean; + events?: boolean; + }; + UserFlag: { + user?: boolean; + featureFlag?: boolean; + }; +} + +// ===== VALIDATION SCHEMAS ===== + +/** + * Zod schemas for runtime validation + */ +export const EntityValidationSchemas = { + Organization: z.object({ + name: z.string().min(1, "Organization name is required"), + description: z.string().optional(), + domain: z.string().optional(), + settings: z.record(z.unknown()).optional(), + isActive: z.boolean().default(true) + }), + + User: z.object({ + key: z.string().min(1, "User key is required"), + name: z.string().min(1, "User name is required"), + email: z.string().email().optional(), + kind: z.enum(['user', 'organization', 'device']).default('user'), + custom: z.record(z.union([z.string(), z.number(), z.boolean()])).optional(), + organizationId: z.string().optional(), + isActive: z.boolean().default(true) + }), + + FeatureFlag: z.object({ + key: z.string().min(1, "Feature flag key is required").regex( + /^[a-zA-Z0-9._-]+$/, + "Feature flag key must contain only alphanumeric characters, dots, underscores, and hyphens" + ), + name: z.string().min(1, "Feature flag name is required"), + description: z.string().optional(), + valueType: z.enum(['boolean', 'string', 'number', 'json']).default('boolean'), + defaultValue: z.unknown(), + variations: z.array(z.object({ + value: z.unknown(), + name: z.string(), + description: z.string().optional() + })).optional(), + targeting: z.object({ + rules: z.array(z.object({ + clauses: z.array(z.object({ + attribute: z.string(), + op: z.string(), + values: z.array(z.unknown()) + })), + variation: z.number() + })).optional(), + fallthrough: z.object({ + variation: z.number() + }).optional() + }).optional(), + isEnabled: z.boolean().default(false), + isArchived: z.boolean().default(false), + category: z.string().optional(), + tags: z.array(z.string()).optional(), + organizationId: z.string().optional(), + environment: z.string().default('production') + }), + + UserFlag: z.object({ + userId: z.string().min(1, "User ID is required"), + featureFlagId: z.string().min(1, "Feature flag ID is required"), + value: z.unknown(), + reason: z.string().optional(), + isActive: z.boolean().default(true), + expiresAt: z.date().optional() + }) +} as const; + +/** + * Type-safe entity validation functions + */ +export const validateEntity = { + organization: (data: unknown): CreateOrganizationInput => { + return EntityValidationSchemas.Organization.parse(data); + }, + + user: (data: unknown): CreateUserInput => { + return EntityValidationSchemas.User.parse(data); + }, + + featureFlag: (data: unknown): CreateFeatureFlagInput => { + return EntityValidationSchemas.FeatureFlag.parse(data); + }, + + userFlag: (data: unknown): CreateUserFlagInput => { + return EntityValidationSchemas.UserFlag.parse(data); + } +} as const; \ No newline at end of file diff --git a/launchdarkly/node/event-emitter.ts b/launchdarkly/node/event-emitter.ts new file mode 100644 index 00000000..10ef830c --- /dev/null +++ b/launchdarkly/node/event-emitter.ts @@ -0,0 +1,520 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Type-safe event emitter implementation with proper subscription management, + * generic event handler functions, and comprehensive error handling. + */ + +import { + EventName, + EventPayload, + EventHandler, + EventHandlerWithMetadata, + TypeSafeEventEmitter, + EventSubscription, + EventEmitterStats, + EventFactory, + FlagEventNames, + SessionEventNames, + SystemEventNames, + isValidEventName, + isCompatibleHandler, + +} from "./events.js"; + +// ===== EVENT EMITTER IMPLEMENTATION ===== + +/** + * Type-safe event emitter with comprehensive subscription management + */ +export class TypeSafeEventEmitterImpl implements TypeSafeEventEmitter { + private readonly handlers = new Map[]>(); + private readonly stats: EventEmitterStats = { + totalHandlers: 0, + handlersByEvent: {} as Record, + totalEmissions: 0, + emissionsByEvent: {} as Record, + errors: [] + }; + + /** + * Register an event handler for a specific event type with proper type inference + */ + public on( + eventName: T, + handler: EventHandler, + options: { priority?: number; once?: boolean } = {} + ): () => void { + if (!isValidEventName(eventName)) { + throw new Error(`Invalid event name: ${String(eventName)}`); + } + + if (!isCompatibleHandler(eventName, handler)) { + throw new Error(`Invalid handler for event: ${eventName}`); + } + + const handlerWithMetadata: EventHandlerWithMetadata = { + handler, + id: this.generateHandlerId(), + priority: options.priority !== undefined ? options.priority : 0, + once: options.once !== undefined ? options.once : false, + createdAt: new Date() + }; + + // Initialize handlers array if it doesn't exist + if (!this.handlers.has(eventName)) { + this.handlers.set(eventName, []); + this.stats.handlersByEvent[eventName] = 0; + } + + // Add handler and sort by priority (higher priority first) + const eventHandlers = this.handlers.get(eventName)!; + eventHandlers.push(handlerWithMetadata as EventHandlerWithMetadata); + eventHandlers.sort((a, b) => (b.priority || 0) - (a.priority || 0)); + + // Update stats + this.stats.totalHandlers++; + this.stats.handlersByEvent[eventName]++; + + // Return unsubscribe function + return () => this.removeHandler(eventName, handlerWithMetadata.id); + } + + /** + * Register a one-time event handler + */ + public once(eventName: T, handler: EventHandler): void { + this.on(eventName, handler, { once: true }); + } + + /** + * Remove a specific event handler + */ + public off(eventName: T, handler: EventHandler): void { + const eventHandlers = this.handlers.get(eventName); + if (!eventHandlers) return; + + const index = eventHandlers.findIndex(h => h.handler === handler); + if (index !== -1) { + eventHandlers.splice(index, 1); + this.stats.totalHandlers--; + this.stats.handlersByEvent[eventName]--; + + if (eventHandlers.length === 0) { + this.handlers.delete(eventName); + delete this.stats.handlersByEvent[eventName]; + } + } + } + + /** + * Remove all handlers for an event type + */ + public removeAllListeners(eventName: T): void { + const eventHandlers = this.handlers.get(eventName); + if (!eventHandlers) return; + + const handlerCount = eventHandlers.length; + this.handlers.delete(eventName); + this.stats.totalHandlers -= handlerCount; + delete this.stats.handlersByEvent[eventName]; + } + + /** + * Emit an event with proper type checking and error handling + */ + public async emit(eventName: T, payload: EventPayload): Promise { + if (!isValidEventName(eventName)) { + throw new Error(`Invalid event name: ${String(eventName)}`); + } + + const eventHandlers = this.handlers.get(eventName); + if (!eventHandlers || eventHandlers.length === 0) { + return; + } + + // Update emission stats + this.stats.totalEmissions++; + this.stats.emissionsByEvent[eventName] = (this.stats.emissionsByEvent[eventName] || 0) + 1; + + // Execute handlers + const handlerPromises: Promise[] = []; + const handlersToRemove: string[] = []; + + for (const handlerWithMetadata of eventHandlers) { + try { + // Check condition if specified + if (handlerWithMetadata.condition && !handlerWithMetadata.condition(payload)) { + continue; + } + + // Execute handler + const result = handlerWithMetadata.handler(payload); + + if (result instanceof Promise) { + handlerPromises.push( + result.catch(error => this.handleError(eventName, error)) + ); + } + + // Mark for removal if it's a one-time handler + if (handlerWithMetadata.once) { + handlersToRemove.push(handlerWithMetadata.id); + } + } catch (error) { + this.handleError(eventName, error instanceof Error ? error : new Error(String(error))); + } + } + + // Wait for all async handlers + if (handlerPromises.length > 0) { + await Promise.all(handlerPromises); + } + + // Remove one-time handlers + for (const handlerId of handlersToRemove) { + this.removeHandler(eventName, handlerId); + } + } + + /** + * Get the number of handlers for an event type + */ + public listenerCount(eventName: T): number { + return this.handlers.get(eventName)?.length !== undefined ? this.handlers.get(eventName)!.length : 0; + } + + /** + * Get all event names that have handlers + */ + public eventNames(): EventName[] { + return Array.from(this.handlers.keys()); + } + + /** + * Get event emitter statistics + */ + public getStats(): EventEmitterStats { + return { ...this.stats }; + } + + /** + * Clear all handlers and reset stats + */ + public clear(): void { + this.handlers.clear(); + this.stats.totalHandlers = 0; + this.stats.handlersByEvent = {} as Record; + this.stats.errors = []; + } + + /** + * Create a scoped event subscription + */ + public subscribe( + eventName: T, + handler: EventHandler, + options?: { priority?: number } + ): EventSubscription { + const unsubscribe = this.on(eventName, handler, options); + const handlerId = this.generateHandlerId(); + + return { + eventName, + handlerId, + createdAt: new Date(), + unsubscribe + }; + } + + // ===== PRIVATE METHODS ===== + + private generateHandlerId(): string { + return `handler_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + } + + private removeHandler(eventName: EventName, handlerId: string): void { + const eventHandlers = this.handlers.get(eventName); + if (!eventHandlers) return; + + const index = eventHandlers.findIndex(h => h.id === handlerId); + if (index !== -1) { + eventHandlers.splice(index, 1); + this.stats.totalHandlers--; + this.stats.handlersByEvent[eventName]--; + + if (eventHandlers.length === 0) { + this.handlers.delete(eventName); + delete this.stats.handlersByEvent[eventName]; + } + } + } + + private handleError(eventName: EventName, error: Error): void { + this.stats.errors.push({ + eventName, + error, + timestamp: new Date() + }); + + // Emit system error event if this isn't already a system error + if (eventName !== 'system:error') { + setImmediate(() => { + this.emit('system:error', { + timestamp: new Date(), + error, + operation: `event_handler_${eventName}`, + severity: 'medium' + }).catch(() => { + // Prevent infinite error loops + }); + }); + } + } +} + +// ===== EVENT FACTORY IMPLEMENTATION ===== + +/** + * Factory for creating type-safe events with validation + */ +export class EventFactoryImpl implements EventFactory { + public create( + eventName: T, + payload: Omit, 'timestamp'> + ): EventPayload { + if (!isValidEventName(eventName)) { + throw new Error(`Invalid event name: ${String(eventName)}`); + } + + return { + ...payload, + timestamp: new Date() + } as EventPayload; + } + + public createFlagEvent( + eventName: T, + payload: Omit, 'timestamp'> + ): EventPayload { + return this.create(eventName, payload); + } + + public createSessionEvent( + eventName: T, + payload: Omit, 'timestamp'> + ): EventPayload { + return this.create(eventName, payload); + } + + public createSystemEvent( + eventName: T, + payload: Omit, 'timestamp'> + ): EventPayload { + return this.create(eventName, payload); + } +} + +// ===== GENERIC EVENT HANDLER UTILITIES ===== + +/** + * Create a safe event handler that catches and logs errors + */ +export function createSafeHandler( + handler: EventHandler, + options: { + onError?: (error: Error, payload: EventPayload) => void; + retries?: number; + timeout?: number; + } = {} +): EventHandler { + return async (payload: EventPayload) => { + const { onError, retries = 0, timeout } = options; + let lastError: Error | null = null; + + for (let attempt = 0; attempt <= retries; attempt++) { + try { + if (timeout) { + await Promise.race([ + Promise.resolve(handler(payload)), + new Promise((_, reject) => + setTimeout(() => reject(new Error('Handler timeout')), timeout) + ) + ]); + } else { + await Promise.resolve(handler(payload)); + } + return; // Success + } catch (error) { + lastError = error instanceof Error ? error : new Error(String(error)); + if (attempt < retries) { + // Wait before retry with exponential backoff + await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 100)); + } + } + } + + // All attempts failed + if (onError && lastError) { + onError(lastError, payload); + } + }; +} + +/** + * Create a conditional event handler + */ +export function createConditionalHandler( + condition: (payload: EventPayload) => boolean, + handler: EventHandler +): EventHandler { + return async (payload: EventPayload) => { + if (condition(payload)) { + await Promise.resolve(handler(payload)); + } + }; +} + +/** + * Create a debounced event handler + */ +export function createDebouncedHandler( + handler: EventHandler, + delay: number +): EventHandler { + let timeoutId: NodeJS.Timeout | null = null; + let latestPayload: EventPayload | null = null; + + return (payload: EventPayload) => { + latestPayload = payload; + + if (timeoutId) { + clearTimeout(timeoutId); + } + + timeoutId = setTimeout(async () => { + if (latestPayload) { + await Promise.resolve(handler(latestPayload)); + latestPayload = null; + } + timeoutId = null; + }, delay); + }; +} + +/** + * Create a throttled event handler + */ +export function createThrottledHandler( + handler: EventHandler, + interval: number +): EventHandler { + let lastExecution = 0; + let timeoutId: NodeJS.Timeout | null = null; + + return async (payload: EventPayload) => { + const now = Date.now(); + const timeSinceLastExecution = now - lastExecution; + + if (timeSinceLastExecution >= interval) { + lastExecution = now; + await Promise.resolve(handler(payload)); + } else { + if (timeoutId) { + clearTimeout(timeoutId); + } + + timeoutId = setTimeout(async () => { + lastExecution = Date.now(); + await Promise.resolve(handler(payload)); + timeoutId = null; + }, interval - timeSinceLastExecution); + } + }; +} + +/** + * Compose multiple event handlers into a single handler + */ +export function composeHandlers( + ...handlers: EventHandler[] +): EventHandler { + return async (payload: EventPayload) => { + const promises = handlers.map(handler => Promise.resolve(handler(payload))); + await Promise.all(promises); + }; +} + +/** + * Create an event handler with logging + */ +export function createLoggingHandler( + handler: EventHandler, + logger: { + log: (level: 'info' | 'warn' | 'error', message: string, meta?: any) => void; + } +): EventHandler { + return async (payload: EventPayload) => { + const startTime = Date.now(); + + try { + logger.log('info', 'Event handler starting', { payload }); + await Promise.resolve(handler(payload)); + const duration = Date.now() - startTime; + logger.log('info', 'Event handler completed', { duration, payload }); + } catch (error) { + const duration = Date.now() - startTime; + logger.log('error', 'Event handler failed', { + error: error instanceof Error ? error.message : String(error), + duration, + payload + }); + throw error; + } + }; +} + +// ===== SINGLETON INSTANCE ===== + +/** + * Global event emitter instance + */ +let globalEventEmitter: TypeSafeEventEmitterImpl | null = null; + +/** + * Get the global event emitter instance + */ +export function getGlobalEventEmitter(): TypeSafeEventEmitterImpl { + if (globalEventEmitter === null) { + globalEventEmitter = new TypeSafeEventEmitterImpl(); + } + return globalEventEmitter; +} + +/** + * Get the global event factory instance + */ +export function getEventFactory(): EventFactoryImpl { + return new EventFactoryImpl(); +} + +// ===== EXPORTS ===== + +export { + TypeSafeEventEmitterImpl as TypeSafeEventEmitter, + EventFactoryImpl as EventFactory +}; \ No newline at end of file diff --git a/launchdarkly/node/event-examples.ts b/launchdarkly/node/event-examples.ts new file mode 100644 index 00000000..fa504701 --- /dev/null +++ b/launchdarkly/node/event-examples.ts @@ -0,0 +1,495 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Comprehensive examples demonstrating the type-safe event system with + * mapped types, generic event handlers, and proper type inference. + */ + +import { + EventPayload, + EventHandler, + EVENT_CATEGORIES +} from "./events.js"; + +import { + TypeSafeEventEmitterImpl, + EventFactoryImpl, + createSafeHandler, + createConditionalHandler, + createDebouncedHandler, + createThrottledHandler, + composeHandlers, + createLoggingHandler, + getGlobalEventEmitter, + getEventFactory +} from "./event-emitter.js"; + +import { UserId } from "./types.js"; + +// ===== BASIC USAGE EXAMPLES ===== + +/** + * Example 1: Basic event emitter usage with type safety + */ +export async function basicEventEmitterExample(): Promise { + console.log('=== Basic Event Emitter Example ==='); + + const emitter = new TypeSafeEventEmitterImpl(); + const factory = new EventFactoryImpl(); + + // Type-safe event handler with proper inference + const flagEvaluationHandler: EventHandler<'flag:evaluation'> = async (payload) => { + console.log(`Flag ${payload.flagId} evaluated with value:`, payload.value); + console.log(`Timestamp: ${payload.timestamp.toISOString()}`); + if (payload.userId) { + console.log(`User: ${payload.userId}`); + } + }; + + // Register handler with automatic type inference + const unsubscribe = emitter.on('flag:evaluation', flagEvaluationHandler); + + // Create type-safe event payload + const evaluationEvent = factory.createFlagEvent('flag:evaluation', { + flagId: 'feature-x', + userId: 'user-123' as UserId, + value: true, + reason: 'targeting rule matched' + }); + + // Emit event with full type safety + await emitter.emit('flag:evaluation', evaluationEvent); + + // Clean up + unsubscribe(); + + console.log('Basic example completed\n'); +} + +/** + * Example 2: Multiple event types with different handlers + */ +export async function multipleEventTypesExample(): Promise { + console.log('=== Multiple Event Types Example ==='); + + const emitter = new TypeSafeEventEmitterImpl(); + const factory = new EventFactoryImpl(); + + // Handler for flag updates + const flagUpdateHandler: EventHandler<'flag:update'> = async (payload) => { + console.log(`Flag ${payload.flagId} updated:`); + console.log(` Previous: ${JSON.stringify(payload.previousValue)}`); + console.log(` New: ${JSON.stringify(payload.newValue)}`); + if (payload.reason) { + console.log(` Reason: ${payload.reason}`); + } + }; + + // Handler for session starts + const sessionStartHandler: EventHandler<'session:start'> = async (payload) => { + console.log(`Session ${payload.sessionId} started for user ${payload.userId}`); + if (payload.userAgent) { + console.log(` User Agent: ${payload.userAgent}`); + } + }; + + // Handler for system errors + const errorHandler: EventHandler<'system:error'> = async (payload) => { + console.error(`System error [${payload.severity}]:`, payload.error.message); + if (payload.operation) { + console.error(` Operation: ${payload.operation}`); + } + }; + + // Register all handlers + emitter.on('flag:update', flagUpdateHandler); + emitter.on('session:start', sessionStartHandler); + emitter.on('system:error', errorHandler); + + // Emit various events + await emitter.emit('flag:update', factory.createFlagEvent('flag:update', { + flagId: 'dark-mode', + userId: 'user-456' as UserId, + previousValue: false, + newValue: true, + reason: 'user preference changed' + })); + + await emitter.emit('session:start', factory.createSessionEvent('session:start', { + sessionId: 'session-789', + userId: 'user-456' as UserId, + userAgent: 'Mozilla/5.0...', + ipAddress: '192.168.1.1' + })); + + await emitter.emit('system:error', factory.createSystemEvent('system:error', { + error: new Error('Database connection failed'), + operation: 'user_authentication', + userId: 'user-456' as UserId, + severity: 'high' + })); + + console.log('Multiple event types example completed\n'); +} + +/** + * Example 3: Advanced handler utilities + */ +export async function advancedHandlerUtilitiesExample(): Promise { + console.log('=== Advanced Handler Utilities Example ==='); + + const emitter = new TypeSafeEventEmitterImpl(); + const factory = new EventFactoryImpl(); + + // Mock logger for demonstration + const logger = { + log: (level: 'info' | 'warn' | 'error', message: string, meta?: any) => { + console.log(`[${level.toUpperCase()}] ${message}`, meta ? JSON.stringify(meta) : ''); + } + }; + + // Basic handler + const basicHandler: EventHandler<'flag:evaluation'> = async (payload) => { + console.log(`Processing flag evaluation: ${payload.flagId}`); + }; + + // Safe handler with retry logic + const safeHandler = createSafeHandler(basicHandler, { + retries: 2, + timeout: 1000, + onError: (error, payload) => { + console.error(`Handler failed for ${payload.flagId}:`, error.message); + } + }); + + // Conditional handler + const conditionalHandler = createConditionalHandler<'flag:evaluation'>( + (payload) => payload.value === true, // Only handle when flag is true + async (payload) => { + console.log(`Flag ${payload.flagId} is enabled!`); + } + ); + + // Debounced handler (waits 500ms after last event) + const debouncedHandler = createDebouncedHandler<'flag:evaluation'>( + async (payload) => { + console.log(`Debounced processing for ${payload.flagId}`); + }, + 500 + ); + + // Throttled handler (executes at most once per second) + const throttledHandler = createThrottledHandler<'flag:evaluation'>( + async (payload) => { + console.log(`Throttled processing for ${payload.flagId}`); + }, + 1000 + ); + + // Composed handler (executes multiple handlers) + const composedHandler = composeHandlers<'flag:evaluation'>( + async (payload) => console.log(`Handler 1: ${payload.flagId}`), + async (payload) => console.log(`Handler 2: ${payload.flagId}`), + async (payload) => console.log(`Handler 3: ${payload.flagId}`) + ); + + // Logging handler + const loggingHandler = createLoggingHandler<'flag:evaluation'>( + async (payload) => { + console.log(`Business logic for ${payload.flagId}`); + }, + logger + ); + + // Register handlers + emitter.on('flag:evaluation', safeHandler); + emitter.on('flag:evaluation', conditionalHandler); + emitter.on('flag:evaluation', debouncedHandler); + emitter.on('flag:evaluation', throttledHandler); + emitter.on('flag:evaluation', composedHandler); + emitter.on('flag:evaluation', loggingHandler); + + // Emit test events + console.log('Emitting events...'); + + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'test-flag-1', + value: true, + userId: 'user-test' as UserId + })); + + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'test-flag-2', + value: false, + userId: 'user-test' as UserId + })); + + // Wait a moment for debounced handlers + await new Promise(resolve => setTimeout(resolve, 600)); + + console.log('Advanced handler utilities example completed\n'); +} + +/** + * Example 4: Event subscriptions and management + */ +export async function eventSubscriptionExample(): Promise { + console.log('=== Event Subscription Example ==='); + + const emitter = new TypeSafeEventEmitterImpl(); + const factory = new EventFactoryImpl(); + + // Create multiple subscriptions + const subscription1 = emitter.subscribe('flag:evaluation', async (payload) => { + console.log(`Subscription 1: Flag ${payload.flagId} evaluated`); + }, { priority: 10 }); + + const subscription2 = emitter.subscribe('flag:evaluation', async (payload) => { + console.log(`Subscription 2: Flag ${payload.flagId} evaluated`); + }, { priority: 5 }); + + // One-time handler + emitter.once('flag:update', async (payload) => { + console.log(`One-time handler: Flag ${payload.flagId} updated (this will only run once)`); + }); + + console.log(`Event names with handlers: ${emitter.eventNames().join(', ')}`); + console.log(`Flag evaluation listener count: ${emitter.listenerCount('flag:evaluation')}`); + + // Emit events + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'subscription-test', + value: 42, + userId: 'user-sub' as UserId + })); + + await emitter.emit('flag:update', factory.createFlagEvent('flag:update', { + flagId: 'update-test', + previousValue: 'old', + newValue: 'new', + userId: 'user-sub' as UserId + })); + + // Try to emit flag:update again (one-time handler won't run) + await emitter.emit('flag:update', factory.createFlagEvent('flag:update', { + flagId: 'update-test-2', + previousValue: 'old2', + newValue: 'new2', + userId: 'user-sub' as UserId + })); + + // Unsubscribe + subscription1.unsubscribe(); + console.log(`After unsubscribing: ${emitter.listenerCount('flag:evaluation')} listeners`); + + // Get stats + const stats = emitter.getStats(); + console.log('Event emitter stats:', { + totalHandlers: stats.totalHandlers, + totalEmissions: stats.totalEmissions, + errorCount: stats.errors.length + }); + + // Clean up + subscription2.unsubscribe(); + + console.log('Event subscription example completed\n'); +} + +/** + * Example 5: Integration with existing FlagEvent entity + */ +export async function flagEventIntegrationExample(): Promise { + console.log('=== Flag Event Integration Example ==='); + + const emitter = new TypeSafeEventEmitterImpl(); + const factory = new EventFactoryImpl(); + + // Handler that could persist events to database + const persistEventHandler: EventHandler<'flag:evaluation'> = async (payload) => { + // This would typically use the repository to save to database + console.log('Persisting flag evaluation event:'); + console.log(` Flag ID: ${payload.flagId}`); + console.log(` User ID: ${payload.userId}`); + console.log(` Value: ${JSON.stringify(payload.value)}`); + console.log(` Timestamp: ${payload.timestamp.toISOString()}`); + console.log(` Context: ${JSON.stringify(payload.context)}`); + + // Simulate database save + const flagEvent = { + id: `event_${Date.now()}`, + featureFlagId: payload.flagId, + userId: payload.userId, + eventType: 'evaluation' as const, + newValue: payload.value, + context: payload.context, + createdAt: payload.timestamp + }; + + console.log('Saved to database:', flagEvent); + }; + + // Register the persistence handler + emitter.on('flag:evaluation', persistEventHandler); + + // Emit events that would be persisted + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'premium-features', + userId: 'user-premium' as UserId, + value: { enabled: true, plan: 'pro' }, + context: { + userAgent: 'Chrome/91.0', + location: 'US-East', + experiment: 'premium-rollout-v2' + } + })); + + await emitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'dark-theme', + userId: 'user-premium' as UserId, + value: true, + defaultValue: false, + reason: 'user setting override' + })); + + console.log('Flag event integration example completed\n'); +} + +/** + * Example 6: Global event emitter usage + */ +export async function globalEventEmitterExample(): Promise { + console.log('=== Global Event Emitter Example ==='); + + // Use global singleton + const globalEmitter = getGlobalEventEmitter(); + const factory = getEventFactory(); + + // Global handler for all system errors + globalEmitter.on('system:error', async (payload) => { + // This could send alerts, log to external services, etc. + console.log(`🚨 GLOBAL ERROR HANDLER: ${payload.error.message}`); + console.log(` Severity: ${payload.severity}`); + console.log(` Timestamp: ${payload.timestamp.toISOString()}`); + }); + + // Global handler for all flag evaluations (for analytics) + globalEmitter.on('flag:evaluation', async (payload) => { + console.log(`📊 ANALYTICS: Flag ${payload.flagId} evaluated`); + // This could send to analytics service + }); + + // Simulate some events + await globalEmitter.emit('system:error', factory.createSystemEvent('system:error', { + error: new Error('Redis connection timeout'), + severity: 'critical', + operation: 'cache_read' + })); + + await globalEmitter.emit('flag:evaluation', factory.createFlagEvent('flag:evaluation', { + flagId: 'new-ui-rollout', + userId: 'analytics-user' as UserId, + value: 'variant-b' + })); + + console.log('Global event emitter example completed\n'); +} + +/** + * Example 7: Event categories and filtering + */ +export async function eventCategoriesExample(): Promise { + console.log('=== Event Categories Example ==='); + + const emitter = new TypeSafeEventEmitterImpl(); + const factory = new EventFactoryImpl(); + + console.log('Available event categories:'); + Object.entries(EVENT_CATEGORIES).forEach(([category, events]) => { + console.log(` ${category}: ${events.join(', ')}`); + }); + + // Handler for all flag events + const flagEventHandler = async (payload: EventPayload): Promise => { + console.log(`Flag event detected: ${JSON.stringify({ + type: 'flag_event', + flagId: payload.flagId, + timestamp: payload.timestamp + })}`); + }; + + // Register handler for all flag event types + EVENT_CATEGORIES.flag.forEach((eventName): void => { + emitter.on(eventName, flagEventHandler); + }); + + // Emit various flag events + await emitter.emit('flag:create', factory.createFlagEvent('flag:create', { + flagId: 'new-feature', + initialValue: false, + userId: 'admin-user' as UserId + })); + + await emitter.emit('flag:toggle', factory.createFlagEvent('flag:toggle', { + flagId: 'new-feature', + enabled: true, + previousState: false, + userId: 'admin-user' as UserId + })); + + await emitter.emit('flag:delete', factory.createFlagEvent('flag:delete', { + flagId: 'old-feature', + finalValue: false, + reason: 'feature sunset', + userId: 'admin-user' as UserId + })); + + console.log('Event categories example completed\n'); +} + +/** + * Run all event system examples + */ +export async function runEventExamples(): Promise { + console.log('🎯 Running Type-Safe Event System Examples\n'); + + try { + await basicEventEmitterExample(); + await multipleEventTypesExample(); + await advancedHandlerUtilitiesExample(); + await eventSubscriptionExample(); + await flagEventIntegrationExample(); + await globalEventEmitterExample(); + await eventCategoriesExample(); + + console.log('✅ All event system examples completed successfully!'); + } catch (error) { + console.error('❌ Error running event examples:', error); + throw error; + } +} + +// Export individual examples for selective testing +export { + basicEventEmitterExample, + multipleEventTypesExample, + advancedHandlerUtilitiesExample, + eventSubscriptionExample, + flagEventIntegrationExample, + globalEventEmitterExample, + eventCategoriesExample +}; \ No newline at end of file diff --git a/launchdarkly/node/event-test.ts b/launchdarkly/node/event-test.ts new file mode 100644 index 00000000..c98ed542 --- /dev/null +++ b/launchdarkly/node/event-test.ts @@ -0,0 +1,43 @@ +/* + * Simple test to validate the type-safe event system works correctly + */ + +import { + EventName, + EventPayload, + EventHandler, + FlagEvaluationPayload, + isValidEventName +} from "./events.js"; + +import { + TypeSafeEventEmitterImpl, + EventFactoryImpl, + getGlobalEventEmitter +} from "./event-emitter.js"; + +// Test type inference +const testHandler: EventHandler<'flag:evaluation'> = async (payload: FlagEvaluationPayload) => { + console.log(`Flag ${payload.flagId} evaluated: ${payload.value}`); +}; + +// Test event emitter +const emitter = new TypeSafeEventEmitterImpl(); +const factory = new EventFactoryImpl(); + +// Test registration and emission +emitter.on('flag:evaluation', testHandler); + +const event = factory.createFlagEvent('flag:evaluation', { + flagId: 'test-flag', + value: true +}); + +// Test type checking +const eventName: EventName = 'flag:evaluation'; +const isValid = isValidEventName(eventName); + +console.log('Event system test compiled successfully!'); +console.log('Type inference working:', typeof testHandler); +console.log('Event name valid:', isValid); +console.log('Event created:', event.flagId); \ No newline at end of file diff --git a/launchdarkly/node/events.ts b/launchdarkly/node/events.ts new file mode 100644 index 00000000..40dc24c7 --- /dev/null +++ b/launchdarkly/node/events.ts @@ -0,0 +1,457 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Type-safe event system interfaces with mapped types for event payload definitions + * and generic event handler functions with proper type inference. + * + * This module provides: + * - Mapped types for event payload definitions + * - Generic event handler functions with proper type inference + * - Type-safe event emitter with subscription management + * - Integration with existing FlagEvent entity structure + */ + +import { UserId } from "./types.js"; + +// ===== CORE EVENT PAYLOAD DEFINITIONS ===== + +/** + * Base event payload interface that all events must extend + */ +export interface BaseEventPayload { + readonly timestamp: Date; + readonly source?: string; + readonly context?: Record; +} + +/** + * Feature flag related event payloads + */ +export interface FlagEvaluationPayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly value: unknown; + readonly defaultValue?: unknown; + readonly reason?: string; +} + +export interface FlagUpdatePayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly previousValue: unknown; + readonly newValue: unknown; + readonly reason?: string; +} + +export interface FlagCreatePayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly initialValue: unknown; + readonly configuration?: Record; +} + +export interface FlagDeletePayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly finalValue?: unknown; + readonly reason?: string; +} + +export interface FlagTogglePayload extends BaseEventPayload { + readonly flagId: string; + readonly userId?: UserId; + readonly enabled: boolean; + readonly previousState: boolean; +} + +/** + * User session related event payloads + */ +export interface UserSessionStartPayload extends BaseEventPayload { + readonly sessionId: string; + readonly userId: UserId; + readonly userAgent?: string; + readonly ipAddress?: string; +} + +export interface UserSessionEndPayload extends BaseEventPayload { + readonly sessionId: string; + readonly userId: UserId; + readonly duration: number; + readonly reason?: 'logout' | 'timeout' | 'error'; +} + +/** + * System level event payloads + */ +export interface SystemErrorPayload extends BaseEventPayload { + readonly error: Error; + readonly operation?: string; + readonly userId?: UserId; + readonly severity: 'low' | 'medium' | 'high' | 'critical'; +} + +export interface SystemHealthPayload extends BaseEventPayload { + readonly status: 'healthy' | 'degraded' | 'unhealthy'; + readonly metrics?: Record; + readonly checks?: Array<{ + name: string; + status: 'pass' | 'fail' | 'warn'; + duration?: number; + }>; +} + +// ===== EVENT TYPE MAPPING ===== + +/** + * Complete event payload mapping using mapped types + * This ensures type safety for all event types and their corresponding payloads + */ +export interface EventPayloadMap { + // Flag-related events + 'flag:evaluation': FlagEvaluationPayload; + 'flag:update': FlagUpdatePayload; + 'flag:create': FlagCreatePayload; + 'flag:delete': FlagDeletePayload; + 'flag:toggle': FlagTogglePayload; + + // User session events + 'session:start': UserSessionStartPayload; + 'session:end': UserSessionEndPayload; + + // System events + 'system:error': SystemErrorPayload; + 'system:health': SystemHealthPayload; +} + +/** + * Extract event names from the payload map + */ +export type EventName = keyof EventPayloadMap; + +/** + * Extract payload type for a specific event name + */ +export type EventPayload = EventPayloadMap[T]; + +/** + * Utility type to check if an event name is valid + */ +export type IsValidEventName = T extends EventName ? true : false; + +/** + * Extract event names by payload type category + */ +export type FlagEventNames = { + [K in EventName]: EventPayloadMap[K] extends FlagEvaluationPayload | FlagUpdatePayload | FlagCreatePayload | FlagDeletePayload | FlagTogglePayload + ? K + : never; +}[EventName]; + +export type SessionEventNames = { + [K in EventName]: EventPayloadMap[K] extends UserSessionStartPayload | UserSessionEndPayload + ? K + : never; +}[EventName]; + +export type SystemEventNames = { + [K in EventName]: EventPayloadMap[K] extends SystemErrorPayload | SystemHealthPayload + ? K + : never; +}[EventName]; + +// ===== GENERIC EVENT HANDLER FUNCTIONS ===== + +/** + * Generic event handler function with proper type inference + */ +export type EventHandler = (payload: EventPayload) => void | Promise; + +/** + * Event handler with error handling capability + */ +export type SafeEventHandler = (payload: EventPayload) => Promise<{ success: boolean; error?: Error }>; + +/** + * Event handler that can return a result + */ +export type EventHandlerWithResult = (payload: EventPayload) => R | Promise; + +/** + * Conditional event handler based on payload properties + */ +export type ConditionalEventHandler = { + condition: (payload: EventPayload) => boolean; + handler: EventHandler; +}; + +// ===== EVENT HANDLER COLLECTIONS ===== + +/** + * Map of event handlers for multiple event types + */ +export type EventHandlerMap = { + [K in EventName]?: EventHandler[]; +}; + +/** + * Typed event handler collection with proper inference + */ +export type TypedEventHandlers> = { + [K in keyof T]?: EventHandler[]; +}; + +/** + * Event handler registry with categorized handlers + */ +export interface EventHandlerRegistry { + flag: { + [K in FlagEventNames]?: EventHandler[]; + }; + session: { + [K in SessionEventNames]?: EventHandler[]; + }; + system: { + [K in SystemEventNames]?: EventHandler[]; + }; + global: EventHandler[]; +} + +// ===== ADVANCED TYPE UTILITIES ===== + +/** + * Extract handler function parameters for type checking + */ +export type HandlerParameters = Parameters>; + +/** + * Extract handler return type + */ +export type HandlerReturnType = ReturnType>; + +/** + * Ensure handler compatibility with event type + */ +export type EnsureHandlerCompatibility = + H extends EventHandler ? H : never; + +/** + * Create a union of all possible event handler functions + */ +export type AnyEventHandler = { + [K in EventName]: EventHandler; +}[EventName]; + +/** + * Event handler with metadata + */ +export interface EventHandlerWithMetadata { + handler: EventHandler; + id: string; + priority?: number; + once?: boolean; + condition?: (payload: EventPayload) => boolean; + createdAt: Date; +} + +// ===== EVENT EMITTER INTERFACES ===== + +/** + * Type-safe event emitter interface + */ +export interface TypeSafeEventEmitter { + /** + * Register an event handler for a specific event type + */ + on( + eventName: T, + handler: EventHandler, + options?: { priority?: number; once?: boolean } + ): () => void; + + /** + * Register a one-time event handler + */ + once(eventName: T, handler: EventHandler): void; + + /** + * Remove a specific event handler + */ + off(eventName: T, handler: EventHandler): void; + + /** + * Remove all handlers for an event type + */ + removeAllListeners(eventName: T): void; + + /** + * Emit an event with proper type checking + */ + emit(eventName: T, payload: EventPayload): Promise; + + /** + * Get the number of handlers for an event type + */ + listenerCount(eventName: T): number; + + /** + * Get all event names that have handlers + */ + eventNames(): EventName[]; +} + +/** + * Event subscription interface + */ +export interface EventSubscription { + readonly eventName: EventName; + readonly handlerId: string; + readonly createdAt: Date; + unsubscribe(): void; +} + +/** + * Event emitter statistics + */ +export interface EventEmitterStats { + totalHandlers: number; + handlersByEvent: Record; + totalEmissions: number; + emissionsByEvent: Record; + errors: Array<{ + eventName: EventName; + error: Error; + timestamp: Date; + }>; +} + +// ===== EVENT BUILDER PATTERNS ===== + +/** + * Event payload builder for type-safe event creation + */ +export interface EventPayloadBuilder { + build(): EventPayload; +} + +/** + * Fluent event builder + */ +export type FluentEventBuilder = { + [K in keyof EventPayload]: (value: EventPayload[K]) => FluentEventBuilder; +} & EventPayloadBuilder; + +/** + * Event factory for creating events with validation + */ +export interface EventFactory { + create( + eventName: T, + payload: Omit, 'timestamp'> + ): EventPayload; + + createFlagEvent( + eventName: T, + payload: Omit, 'timestamp'> + ): EventPayload; + + createSessionEvent( + eventName: T, + payload: Omit, 'timestamp'> + ): EventPayload; + + createSystemEvent( + eventName: T, + payload: Omit, 'timestamp'> + ): EventPayload; +} + +// ===== INTEGRATION WITH EXISTING TYPES ===== + +/** + * Convert FlagEvent entity to event payload + */ +export type FlagEventToPayload = T extends 'flag:evaluation' + ? FlagEvaluationPayload + : T extends 'flag:update' + ? FlagUpdatePayload + : T extends 'flag:create' + ? FlagCreatePayload + : T extends 'flag:delete' + ? FlagDeletePayload + : T extends 'flag:toggle' + ? FlagTogglePayload + : never; + +/** + * Event payload validation result + */ +export interface EventPayloadValidationResult { + valid: boolean; + payload?: EventPayload; + errors?: string[]; +} + +/** + * Event payload validator function + */ +export type EventPayloadValidator = ( + data: unknown +) => EventPayloadValidationResult; + +// ===== TYPE GUARDS AND UTILITIES ===== + +/** + * Type guard to check if a value is a valid event name + */ +export function isValidEventName(value: unknown): value is EventName { + return typeof value === 'string' && value in EVENT_NAMES; +} + +/** + * Type guard to check if a handler is compatible with an event type + */ +export function isCompatibleHandler( + eventName: T, + handler: unknown +): handler is EventHandler { + return typeof handler === 'function'; +} + +/** + * All valid event names for runtime validation + */ +export const EVENT_NAMES: Record = { + 'flag:evaluation': true, + 'flag:update': true, + 'flag:create': true, + 'flag:delete': true, + 'flag:toggle': true, + 'session:start': true, + 'session:end': true, + 'system:error': true, + 'system:health': true, +} as const; + +/** + * Event name categories for easier filtering + */ +export const EVENT_CATEGORIES = { + flag: ['flag:evaluation', 'flag:update', 'flag:create', 'flag:delete', 'flag:toggle'] as const, + session: ['session:start', 'session:end'] as const, + system: ['system:error', 'system:health'] as const, +} as const; \ No newline at end of file diff --git a/launchdarkly/node/examples.ts b/launchdarkly/node/examples.ts new file mode 100644 index 00000000..5c40a3f1 --- /dev/null +++ b/launchdarkly/node/examples.ts @@ -0,0 +1,882 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Comprehensive examples demonstrating type-safe database entity operations + * using TypeORM decorators with proper utility types for create/update operations + */ + +import { z } from "zod"; +import { + Organization, + User, + FeatureFlag, + UserFlag, + UserSession, + FlagEvent, + CreateOrganizationInput, + CreateUserInput, + CreateFeatureFlagInput, + CreateUserFlagInput, + UpdateOrganizationInput, + UpdateUserInput, + UpdateFeatureFlagInput, + EntityValidationSchemas, + validateEntity +} from "./entities.js"; + +import { + DatabaseConnection, + initializeDatabase, + closeDatabase, + createDatabaseConfig +} from "./database.js"; + +import { + RepositoryProvider, + UnitOfWork, + createUnitOfWork, + IOrganizationRepository, + IUserRepository, + IFeatureFlagRepository, + IUserFlagRepository +} from "./repositories.js"; + +import { + CreateInput, + UpdateInput, + FilterInput, + RelationOptions, + WithRelations, + OperationResult, + PaginatedResult, + BulkOperationResult, + createTransform, + createBiTransform, + deepMerge, + isDefined +} from "./types.js"; + +// ===== BRANDED TYPES FOR EXAMPLES ===== + +type BrandedString = string & { readonly __brand: T }; +type UserId = BrandedString<'UserId'>; +type FlagKey = BrandedString<'FlagKey'>; +type OrganizationId = BrandedString<'OrganizationId'>; + +// ===== EXAMPLE SERVICES ===== + +/** + * Organization service demonstrating type-safe CRUD operations + */ +class OrganizationService { + constructor(private organizationRepo: IOrganizationRepository) {} + + /** + * Create a new organization with type-safe input validation + */ + async createOrganization(input: CreateOrganizationInput): Promise> { + try { + // Validate input using Zod schema + const validatedInput = validateEntity.organization(input); + + // Check if organization with same name already exists + const existing = await this.organizationRepo.findByName(validatedInput.name); + if (existing) { + return { + success: false, + error: new Error(`Organization with name '${validatedInput.name}' already exists`) + }; + } + + // Create organization + const organization = await this.organizationRepo.create(validatedInput); + + return { success: true, data: organization }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to create organization') + }; + } + } + + /** + * Update organization with partial input + */ + async updateOrganization( + id: OrganizationId, + input: UpdateOrganizationInput + ): Promise> { + try { + // Validate that organization exists + const existing = await this.organizationRepo.findById(id); + if (!existing) { + return { + success: false, + error: new Error(`Organization with id '${id}' not found`) + }; + } + + // Validate input if provided + if (input.name) { + const nameExists = await this.organizationRepo.findByName(input.name); + if (nameExists && nameExists.id !== id) { + return { + success: false, + error: new Error(`Organization with name '${input.name}' already exists`) + }; + } + } + + // Update organization + const updated = await this.organizationRepo.update(id, input); + + return { success: true, data: updated }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to update organization') + }; + } + } + + /** + * Get organization with related data + */ + async getOrganizationWithStats( + id: OrganizationId + ): Promise> { + try { + const organization = await this.organizationRepo.findById(id, ['users', 'featureFlags']); + if (!organization) { + return { + success: false, + error: new Error(`Organization with id '${id}' not found`) + }; + } + + const [userCount, flagCount] = await Promise.all([ + this.organizationRepo.getUserCount(id), + this.organizationRepo.getFeatureFlagCount(id) + ]); + + return { + success: true, + data: { ...organization, userCount, flagCount } + }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to get organization') + }; + } + } +} + +/** + * User service with comprehensive user management + */ +class UserService { + constructor( + private userRepo: IUserRepository, + private organizationRepo: IOrganizationRepository + ) {} + + /** + * Create user with organization validation + */ + async createUser(input: CreateUserInput): Promise> { + try { + // Validate input + const validatedInput = validateEntity.user(input); + + // Validate organization if provided + if (validatedInput.organizationId) { + const orgExists = await this.organizationRepo.exists(validatedInput.organizationId); + if (!orgExists) { + return { + success: false, + error: new Error(`Organization with id '${validatedInput.organizationId}' not found`) + }; + } + } + + // Check for duplicate key + const existingByKey = await this.userRepo.findByKey(validatedInput.key); + if (existingByKey) { + return { + success: false, + error: new Error(`User with key '${validatedInput.key}' already exists`) + }; + } + + // Check for duplicate email + if (validatedInput.email) { + const existingByEmail = await this.userRepo.findByEmail(validatedInput.email); + if (existingByEmail) { + return { + success: false, + error: new Error(`User with email '${validatedInput.email}' already exists`) + }; + } + } + + const user = await this.userRepo.create(validatedInput); + return { success: true, data: user }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to create user') + }; + } + } + + /** + * Get user with all related data using type-safe relations + */ + async getUserWithRelations( + userId: UserId + ): Promise>> { + try { + const user = await this.userRepo.findById(userId, [ + 'organization', + 'userFlags', + 'userFlags.featureFlag', + 'sessions' + ]); + + if (!user) { + return { + success: false, + error: new Error(`User with id '${userId}' not found`) + }; + } + + return { success: true, data: user as any }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to get user') + }; + } + } + + /** + * Bulk create users with validation + */ + async createUsers(inputs: CreateUserInput[]): Promise> { + const result: BulkOperationResult = { + successful: [], + failed: [], + totalProcessed: inputs.length, + successCount: 0, + failureCount: 0 + }; + + for (const input of inputs) { + try { + const userResult = await this.createUser(input); + if (userResult.success) { + result.successful.push(userResult.data); + result.successCount++; + } else { + result.failed.push({ + item: input as any, + error: userResult.error + }); + result.failureCount++; + } + } catch (error) { + result.failed.push({ + item: input as any, + error: error instanceof Error ? error : new Error('Unknown error') + }); + result.failureCount++; + } + } + + return result; + } +} + +/** + * Feature flag service with advanced flag management + */ +class FeatureFlagService { + constructor( + private flagRepo: IFeatureFlagRepository, + private userFlagRepo: IUserFlagRepository, + private organizationRepo: IOrganizationRepository + ) {} + + /** + * Create feature flag with comprehensive validation + */ + async createFeatureFlag(input: CreateFeatureFlagInput): Promise> { + try { + // Validate input + const validatedInput = validateEntity.featureFlag(input); + + // Validate organization if provided + if (validatedInput.organizationId) { + const orgExists = await this.organizationRepo.exists(validatedInput.organizationId); + if (!orgExists) { + return { + success: false, + error: new Error(`Organization with id '${validatedInput.organizationId}' not found`) + }; + } + } + + // Check for duplicate key + const existingFlag = await this.flagRepo.findByKey(validatedInput.key as FlagKey); + if (existingFlag) { + return { + success: false, + error: new Error(`Feature flag with key '${validatedInput.key}' already exists`) + }; + } + + const flag = await this.flagRepo.create(validatedInput); + return { success: true, data: flag }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to create feature flag') + }; + } + } + + /** + * Get flag value for user with fallback logic + */ + async getFlagValueForUser( + userId: UserId, + flagKey: FlagKey + ): Promise> { + try { + // First check for user-specific override + const userFlag = await this.flagRepo.getUserFlagValue(userId, flagKey); + if (userFlag && userFlag.isActive) { + return { + success: true, + data: { value: userFlag.value, source: 'user-override' } + }; + } + + // Fallback to flag default value + const flag = await this.flagRepo.findByKey(flagKey); + if (!flag) { + return { + success: false, + error: new Error(`Feature flag with key '${flagKey}' not found`) + }; + } + + if (!flag.isEnabled) { + return { + success: true, + data: { value: flag.defaultValue, source: 'flag-default' } + }; + } + + return { + success: true, + data: { value: flag.defaultValue, source: 'flag-default' } + }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to get flag value') + }; + } + } + + /** + * Set user-specific flag override + */ + async setUserFlagOverride( + userId: UserId, + flagKey: FlagKey, + value: unknown, + reason?: string + ): Promise> { + try { + // Validate that flag exists + const flag = await this.flagRepo.findByKey(flagKey); + if (!flag) { + return { + success: false, + error: new Error(`Feature flag with key '${flagKey}' not found`) + }; + } + + // Set user flag override + const userFlag = await this.userFlagRepo.setUserFlag(userId, flag.id, value, reason); + + return { success: true, data: userFlag }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to set user flag override') + }; + } + } + + /** + * Get flag usage statistics + */ + async getFlagStats(flagId: string): Promise> { + try { + const [stats, userFlags] = await Promise.all([ + this.flagRepo.getFlagUsageStats(flagId), + this.userFlagRepo.findByFlag(flagId) + ]); + + return { + success: true, + data: { + ...stats, + userOverrides: userFlags.filter(uf => uf.isActive).length + } + }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error : new Error('Failed to get flag statistics') + }; + } + } +} + +// ===== DATA TRANSFORMATION EXAMPLES ===== + +/** + * DTO (Data Transfer Object) types for API responses + */ +interface OrganizationDto { + id: string; + name: string; + description?: string; + userCount: number; + flagCount: number; + isActive: boolean; + createdAt: string; +} + +interface UserDto { + id: string; + key: string; + name: string; + email?: string; + kind: string; + organizationName?: string; + isActive: boolean; + lastLoginAt?: string; + createdAt: string; +} + +interface FeatureFlagDto { + id: string; + key: string; + name: string; + description?: string; + valueType: string; + defaultValue: unknown; + isEnabled: boolean; + category?: string; + tags?: string[]; + environment: string; + createdAt: string; +} + +/** + * Type-safe transformations between entities and DTOs + */ +const organizationTransform = createBiTransform( + // To DTO + (entity) => ({ + id: entity.id, + name: entity.name, + description: entity.description, + userCount: entity.users?.length || 0, + flagCount: entity.featureFlags?.length || 0, + isActive: entity.isActive, + createdAt: entity.createdAt.toISOString() + }), + // From DTO (not typically used, but shows bi-directional capability) + (dto) => ({ + id: dto.id as OrganizationId, + name: dto.name, + description: dto.description, + isActive: dto.isActive, + createdAt: new Date(dto.createdAt), + updatedAt: new Date(), + users: [], + featureFlags: [], + settings: undefined, + domain: undefined + }) +); + +const userTransform = createTransform((entity) => ({ + id: entity.id, + key: entity.key, + name: entity.name, + email: entity.email, + kind: entity.kind, + organizationName: entity.organization?.name, + isActive: entity.isActive, + lastLoginAt: entity.lastLoginAt?.toISOString(), + createdAt: entity.createdAt.toISOString() +})); + +const featureFlagTransform = createTransform((entity) => ({ + id: entity.id, + key: entity.key, + name: entity.name, + description: entity.description, + valueType: entity.valueType, + defaultValue: entity.defaultValue, + isEnabled: entity.isEnabled, + category: entity.category, + tags: entity.tags, + environment: entity.environment, + createdAt: entity.createdAt.toISOString() +})); + +// ===== COMPLETE EXAMPLE APPLICATION ===== + +/** + * Example application demonstrating complete type-safe database operations + */ +class FeatureFlagApplication { + private uow: UnitOfWork; + private organizationService: OrganizationService; + private userService: UserService; + private flagService: FeatureFlagService; + + constructor(private dbConnection: DatabaseConnection) { + this.uow = createUnitOfWork(dbConnection); + this.organizationService = new OrganizationService(this.uow.Organizations); + this.userService = new UserService(this.uow.Users, this.uow.Organizations); + this.flagService = new FeatureFlagService( + this.uow.FeatureFlags, + this.uow.UserFlags, + this.uow.Organizations + ); + } + + /** + * Complete example: Create organization, users, and feature flags + */ + async setupExample(): Promise { + try { + console.log('Setting up example data...'); + + // Create organization + const orgResult = await this.organizationService.createOrganization({ + name: 'Acme Corporation', + description: 'Example organization for demonstration', + domain: 'acme.com', + isActive: true, + settings: { + theme: 'light', + notifications: true + } + }); + + if (!orgResult.success) { + throw orgResult.error; + } + + const organization = orgResult.data; + console.log('Created organization:', organization.name); + + // Create users + const userInputs: CreateUserInput[] = [ + { + key: 'user1', + name: 'John Doe', + email: 'john@acme.com', + kind: 'user', + organizationId: organization.id, + isActive: true, + custom: { + department: 'Engineering', + role: 'Developer' + } + }, + { + key: 'user2', + name: 'Jane Smith', + email: 'jane@acme.com', + kind: 'user', + organizationId: organization.id, + isActive: true, + custom: { + department: 'Product', + role: 'Manager' + } + } + ]; + + const usersResult = await this.userService.createUsers(userInputs); + console.log(`Created ${usersResult.successCount} users, ${usersResult.failureCount} failed`); + + // Create feature flags + const flagInputs: CreateFeatureFlagInput[] = [ + { + key: 'dark-mode' as FlagKey, + name: 'Dark Mode', + description: 'Enable dark mode theme', + valueType: 'boolean', + defaultValue: false, + isEnabled: true, + category: 'ui', + tags: ['theme', 'ui'], + organizationId: organization.id, + environment: 'production' + }, + { + key: 'beta-features' as FlagKey, + name: 'Beta Features', + description: 'Enable beta features for testing', + valueType: 'boolean', + defaultValue: false, + isEnabled: false, + category: 'features', + tags: ['beta', 'experimental'], + organizationId: organization.id, + environment: 'staging' + } + ]; + + for (const flagInput of flagInputs) { + const flagResult = await this.flagService.createFeatureFlag(flagInput); + if (flagResult.success) { + console.log('Created feature flag:', flagResult.data.name); + } else { + console.error('Failed to create flag:', flagResult.error.message); + } + } + + // Set user-specific overrides + if (usersResult.successful.length > 0) { + const user = usersResult.successful[0]; + const overrideResult = await this.flagService.setUserFlagOverride( + user.id, + 'dark-mode' as FlagKey, + true, + 'User preference for dark mode' + ); + + if (overrideResult.success) { + console.log('Set user flag override for dark mode'); + } + } + + console.log('Example setup completed successfully!'); + } catch (error) { + console.error('Failed to setup example:', error); + throw error; + } + } + + /** + * Demonstrate querying with relations and transformations + */ + async demonstrateQueries(): Promise { + try { + console.log('Demonstrating type-safe queries...'); + + // Get organizations with stats + const organizations = await this.uow.Organizations.findAll({}, ['users', 'featureFlags']); + console.log(`Found ${organizations.length} organizations`); + + for (const org of organizations) { + const orgDto = organizationTransform.toDto(org); + console.log('Organization DTO:', JSON.stringify(orgDto, null, 2)); + + // Get organization stats + const statsResult = await this.organizationService.getOrganizationWithStats(org.id); + if (statsResult.success) { + console.log('Organization stats:', { + userCount: statsResult.data.userCount, + flagCount: statsResult.data.flagCount + }); + } + } + + // Query users with filters + const activeUsers = await this.uow.Users.findAll({ isActive: true }, ['organization']); + console.log(`Found ${activeUsers.length} active users`); + + for (const user of activeUsers) { + const userDto = userTransform(user); + console.log('User DTO:', JSON.stringify(userDto, null, 2)); + + // Get user with all relations + const userWithRelationsResult = await this.userService.getUserWithRelations(user.id); + if (userWithRelationsResult.success) { + console.log(`User ${user.name} has ${userWithRelationsResult.data.userFlags?.length || 0} flag overrides`); + } + } + + // Query feature flags + const enabledFlags = await this.uow.FeatureFlags.findEnabledFlags(); + console.log(`Found ${enabledFlags.length} enabled flags`); + + for (const flag of enabledFlags) { + const flagDto = featureFlagTransform(flag); + console.log('Flag DTO:', JSON.stringify(flagDto, null, 2)); + + // Get flag statistics + const statsResult = await this.flagService.getFlagStats(flag.id); + if (statsResult.success) { + console.log('Flag stats:', statsResult.data); + } + } + + console.log('Query demonstration completed!'); + } catch (error) { + console.error('Failed to demonstrate queries:', error); + throw error; + } + } + + /** + * Demonstrate transaction usage + */ + async demonstrateTransaction(): Promise { + try { + console.log('Demonstrating database transactions...'); + + const result = await this.uow.executeTransaction(async (uow) => { + // Create organization + const org = await uow.Organizations.create({ + name: 'Transaction Test Org', + description: 'Created in transaction', + isActive: true + }); + + // Create user in same transaction + const user = await uow.Users.create({ + key: 'transaction-user', + name: 'Transaction User', + email: 'transaction@test.com', + kind: 'user', + organizationId: org.id, + isActive: true + }); + + // Create feature flag in same transaction + const flag = await uow.FeatureFlags.create({ + key: 'transaction-flag' as FlagKey, + name: 'Transaction Flag', + description: 'Created in transaction', + valueType: 'boolean', + defaultValue: false, + isEnabled: true, + organizationId: org.id, + environment: 'test' + }); + + return { org, user, flag }; + }); + + console.log('Transaction completed successfully:', { + organizationId: result.org.id, + userId: result.user.id, + flagId: result.flag.id + }); + } catch (error) { + console.error('Transaction failed:', error); + throw error; + } + } +} + +// ===== MAIN EXAMPLE RUNNER ===== + +/** + * Main function to run all examples + */ +export async function runExamples(): Promise { + let dbConnection: DatabaseConnection | null = null; + + try { + // Initialize database + console.log('Initializing database connection...'); + dbConnection = await initializeDatabase(createDatabaseConfig({ + DB_TYPE: 'postgres', + DB_HOST: 'localhost', + DB_PORT: '5432', + DB_USERNAME: 'postgres', + DB_PASSWORD: 'password', + DB_DATABASE: 'launchdarkly_example', + NODE_ENV: 'development' + })); + + // Create application + const app = new FeatureFlagApplication(dbConnection); + + // Run examples + await app.setupExample(); + await app.demonstrateQueries(); + await app.demonstrateTransaction(); + + console.log('All examples completed successfully!'); + } catch (error) { + console.error('Examples failed:', error); + throw error; + } finally { + // Clean up + if (dbConnection) { + await closeDatabase(); + console.log('Database connection closed'); + } + } +} + +// Export example classes and functions +export { + OrganizationService, + UserService, + FeatureFlagService, + FeatureFlagApplication, + organizationTransform, + userTransform, + featureFlagTransform +}; + +// Export DTO types +export type { + OrganizationDto, + UserDto, + FeatureFlagDto +}; + +// Run examples if this file is executed directly +if (import.meta.url === `file://${process.argv[1]}`) { + runExamples().catch(console.error); +} \ No newline at end of file diff --git a/launchdarkly/node/index.ts b/launchdarkly/node/index.ts new file mode 100644 index 00000000..7e4a1ab5 --- /dev/null +++ b/launchdarkly/node/index.ts @@ -0,0 +1,455 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Type-safe database entity definitions using TypeORM decorators + * with comprehensive utility types for create/update input types. + * + * This module provides: + * - TypeORM entity definitions with proper decorators + * - Type-safe repository patterns + * - Advanced utility types for CRUD operations + * - Database connection management + * - Transaction support + * - Validation schemas using Zod + * - Type-safe event system with mapped types + * - Generic event handler functions with proper type inference + * - Comprehensive examples + */ + +// ===== ENTITIES ===== +export { + // Entity classes + Organization, + User, + FeatureFlag, + UserFlag, + UserSession, + FlagEvent, + + // Create input types + CreateOrganizationInput, + CreateUserInput, + CreateFeatureFlagInput, + CreateUserFlagInput, + CreateUserSessionInput, + CreateFlagEventInput, + + // Update input types + UpdateOrganizationInput, + UpdateUserInput, + UpdateFeatureFlagInput, + UpdateUserFlagInput, + UpdateUserSessionInput, + + // Filter types + OrganizationFilters, + UserFilters, + FeatureFlagFilters, + UserFlagFilters, + + // Relation types + EntityRelations, + + // Validation schemas + EntityValidationSchemas, + validateEntity +} from "./entities.js"; + +// ===== DATABASE CONNECTION ===== +export { + // Database connection class + DatabaseConnection, + + // Configuration + createDatabaseConfig, + + // Connection management + initializeDatabase, + closeDatabase, + getDatabase, + + // Query builder + TypeSafeQueryBuilder, + + // Repository factory + RepositoryFactory, + + // Pagination utilities + createPaginatedQuery, + + // Error handling + DatabaseError, + ValidationError, + handleDatabaseError +} from "./database.js"; + +// ===== REPOSITORIES ===== +export { + // Repository interfaces + IOrganizationRepository, + IUserRepository, + IFeatureFlagRepository, + IUserFlagRepository, + IUserSessionRepository, + IFlagEventRepository, + + // Repository implementations + OrganizationRepository, + UserRepository, + FeatureFlagRepository, + UserFlagRepository, + UserSessionRepository, + FlagEventRepository, + + // Repository provider + RepositoryProvider, + createRepositoryProvider, + + // Unit of work pattern + UnitOfWork, + createUnitOfWork +} from "./repositories.js"; + +// ===== UTILITY TYPES ===== +export { + // Core utility types + OptionalKeys, + RequiredKeys, + RequireOnly, + OptionalOnly, + DeepPartial, + DeepRequired, + NonFunctionProperties, + PrimitiveProperties, + + // Database-specific types + DatabaseManagedFields, + ReadonlyFields, + CreateInput, + UpdateInput, + PatchInput, + ReplaceInput, + UpsertInput, + FilterInput, + SortInput, + ProjectionInput, + + // Relation types + RelationFields, + RelationOptions, + WithRelations, + + // Validation types + InferZodSchema, + ValidationSchema, + Transform, + BiTransform, + + // Advanced conditional types + NullableFields, + OptionalNullableInput, + DeepMerge, + ArrayElement, + Lookup, + KeyValuePair, + + // Operation result types + OperationResult, + AsyncOperationResult, + PaginatedResult, + BulkOperationResult, + + // Query builder types + ComparisonOperator, + FieldFilter, + AdvancedFilterInput, + AggregationPipeline, + + // Entity-specific types + EntityFromRepository, + EntityConstructor, + EntityMetadata, + + // Migration types + ColumnDefinition, + TableDefinition, + MigrationOperation, + TableChange, + + // Type testing utilities + AssertEqual, + AssertExtends, + TypeTest, + + // Example types for reference + ExampleEntity, + ExampleCreateInput, + ExampleUpdateInput, + ExampleFilterInput, + ExampleRelationOptions, + + // Utility functions + isDefined, + isNonEmptyString, + isPositiveNumber, + createTransform, + createBiTransform, + deepMerge, + pickDefined, + createLookup +} from "./types.js"; + +// ===== EXAMPLES ===== +export { + // Service classes + OrganizationService, + UserService, + FeatureFlagService, + FeatureFlagApplication, + + // Transformation functions + organizationTransform, + userTransform, + featureFlagTransform, + + // Main example runner + runExamples, + + // DTO types + OrganizationDto, + UserDto, + FeatureFlagDto +} from "./examples.js"; + +// ===== EVENT SYSTEM ===== +export { + // Event payload interfaces + BaseEventPayload, + FlagEvaluationPayload, + FlagUpdatePayload, + FlagCreatePayload, + FlagDeletePayload, + FlagTogglePayload, + UserSessionStartPayload, + UserSessionEndPayload, + SystemErrorPayload, + SystemHealthPayload, + + // Event system types + EventPayloadMap, + EventName, + EventPayload, + EventHandler, + SafeEventHandler, + EventHandlerWithResult, + ConditionalEventHandler, + EventHandlerMap, + TypedEventHandlers, + EventHandlerRegistry, + EventHandlerWithMetadata, + + // Event emitter interfaces + TypeSafeEventEmitter, + EventSubscription, + EventEmitterStats, + EventFactory, + + // Event categories + FlagEventNames, + SessionEventNames, + SystemEventNames, + + // Type guards and utilities + isValidEventName, + isCompatibleHandler, + EVENT_NAMES, + EVENT_CATEGORIES +} from "./events.js"; + +export { + // Event emitter implementation + TypeSafeEventEmitterImpl as TypeSafeEventEmitter, + EventFactoryImpl as EventFactory, + + // Event handler utilities + createSafeHandler, + createConditionalHandler, + createDebouncedHandler, + createThrottledHandler, + composeHandlers, + createLoggingHandler, + + // Global instances + getGlobalEventEmitter, + getEventFactory +} from "./event-emitter.js"; + +export { + // Event system examples + runEventExamples, + basicEventEmitterExample, + multipleEventTypesExample, + advancedHandlerUtilitiesExample, + eventSubscriptionExample, + flagEventIntegrationExample, + globalEventEmitterExample, + eventCategoriesExample +} from "./event-examples.js"; + +// ===== TYPE EXPORTS FOR EXTERNAL USE ===== + +/** + * Branded types for type safety + */ +export type BrandedString = string & { readonly __brand: T }; +export type UserId = BrandedString<'UserId'>; +export type FlagKey = BrandedString<'FlagKey'>; +export type OrganizationId = BrandedString<'OrganizationId'>; +export type SessionId = BrandedString<'SessionId'>; +export type EnvironmentKey = BrandedString<'EnvironmentKey'>; + +/** + * Common pagination options + */ +export interface PaginationOptions { + page: number; + limit: number; + sortBy?: string; + sortOrder: 'ASC' | 'DESC'; +} + +/** + * Database configuration type + */ +export interface DatabaseConfig { + type: 'postgres' | 'mysql' | 'sqlite' | 'mongodb'; + host: string; + port: number; + username: string; + password: string; + database: string; + synchronize: boolean; + logging: boolean; + ssl: boolean | Record; + maxConnections: number; + acquireTimeout: number; + timeout: number; + migrationsRun: boolean; +} + +// ===== QUICK START FUNCTIONS ===== + +/** + * Quick start function to initialize a complete type-safe database setup + */ +export async function quickStart(config?: Partial): Promise<{ + connection: DatabaseConnection; + repositories: RepositoryProvider; + unitOfWork: UnitOfWork; +}> { + const connection = await initializeDatabase(config); + const repositories = createRepositoryProvider(connection); + const unitOfWork = createUnitOfWork(connection); + + return { connection, repositories, unitOfWork }; +} + +/** + * Create a complete service layer with all repositories + */ +export function createServiceLayer(unitOfWork: UnitOfWork) { + return { + organizations: new OrganizationService(unitOfWork.Organizations), + users: new UserService(unitOfWork.Users, unitOfWork.Organizations), + featureFlags: new FeatureFlagService( + unitOfWork.FeatureFlags, + unitOfWork.UserFlags, + unitOfWork.Organizations + ) + }; +} + +// ===== DOCUMENTATION AND EXAMPLES ===== + +/** + * Usage example: + * + * ```typescript + * import { quickStart, createServiceLayer, runExamples } from './index.js'; + * + * // Quick start + * const { connection, repositories, unitOfWork } = await quickStart({ + * type: 'postgres', + * host: 'localhost', + * port: 5432, + * username: 'postgres', + * password: 'password', + * database: 'myapp' + * }); + * + * // Create services + * const services = createServiceLayer(unitOfWork); + * + * // Use type-safe operations + * const orgResult = await services.organizations.createOrganization({ + * name: 'My Company', + * description: 'My awesome company', + * isActive: true + * }); + * + * if (orgResult.success) { + * console.log('Created organization:', orgResult.data.name); + * } + * + * // Run complete examples + * await runExamples(); + * ``` + */ + +// ===== VERSION AND METADATA ===== + +/** + * Package metadata + */ +export const VERSION = '1.0.0'; +export const DESCRIPTION = 'Type-safe database entity definitions using TypeORM decorators with comprehensive utility types and type-safe event system'; +export const AUTHOR = 'Gitar, Inc.'; +export const LICENSE = 'Apache-2.0'; + +/** + * Feature flags for the module + */ +export const FEATURES = { + TYPEORM_DECORATORS: true, + TYPE_SAFE_REPOSITORIES: true, + ADVANCED_UTILITY_TYPES: true, + VALIDATION_SCHEMAS: true, + TRANSACTION_SUPPORT: true, + RELATION_LOADING: true, + PAGINATION_SUPPORT: true, + ERROR_HANDLING: true, + EXAMPLES_INCLUDED: true, + TYPE_SAFE_EVENT_SYSTEM: true, + EVENT_EMITTER: true, + EVENT_SUBSCRIPTIONS: true, + GENERIC_EVENT_HANDLERS: true +} as const; + +/** + * Export all features as a constant for runtime checks + */ +export const SUPPORTED_FEATURES = Object.keys(FEATURES) as Array; \ No newline at end of file diff --git a/launchdarkly/node/repositories.ts b/launchdarkly/node/repositories.ts new file mode 100644 index 00000000..fd069eee --- /dev/null +++ b/launchdarkly/node/repositories.ts @@ -0,0 +1,939 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Type-safe repository interfaces and implementations using TypeORM Repository pattern + * with comprehensive CRUD operations and relationship handling + */ + +import { z } from "zod"; +import { + Organization, + User, + FeatureFlag, + UserFlag, + UserSession, + FlagEvent, + CreateOrganizationInput, + CreateUserInput, + CreateFeatureFlagInput, + CreateUserFlagInput, + CreateUserSessionInput, + CreateFlagEventInput, + UpdateOrganizationInput, + UpdateUserInput, + UpdateFeatureFlagInput, + UpdateUserFlagInput, + UpdateUserSessionInput, + OrganizationFilters, + UserFilters, + FeatureFlagFilters, + UserFlagFilters +} from "./entities.js"; + +import { + DatabaseConnection, + TypeSafeQueryBuilder, + RepositoryFactory, + PaginatedResult, + PaginationOptions, + createPaginatedQuery, + DatabaseError, + ValidationError, + handleDatabaseError +} from "./database.js"; + +// ===== BRANDED TYPES FOR REPOSITORY OPERATIONS ===== + +type BrandedString = string & { readonly __brand: T }; + +type UserId = BrandedString<'UserId'>; +type FlagKey = BrandedString<'FlagKey'>; +type OrganizationId = BrandedString<'OrganizationId'>; +type SessionId = BrandedString<'SessionId'>; + +// ===== BASE REPOSITORY INTERFACE ===== + +/** + * Generic repository interface with type-safe CRUD operations + */ +interface BaseRepository { + // Basic CRUD operations + findById(id: string, relations?: string[]): Promise; + findAll(filters?: TFilters, relations?: string[]): Promise; + findPaginated( + filters?: TFilters, + pagination?: Partial, + relations?: string[] + ): Promise>; + create(input: TCreateInput): Promise; + update(id: string, input: TUpdateInput): Promise; + delete(id: string): Promise; + count(filters?: TFilters): Promise; + exists(id: string): Promise; + + // Batch operations + createMany(inputs: TCreateInput[]): Promise; + updateMany(updates: Array<{ id: string; data: TUpdateInput }>): Promise; + deleteMany(ids: string[]): Promise; + + // Search operations + search(query: string, filters?: TFilters): Promise; +} + +// ===== REPOSITORY INTERFACES ===== + +/** + * Organization repository interface + */ +export interface IOrganizationRepository extends BaseRepository< + Organization, + CreateOrganizationInput, + UpdateOrganizationInput, + OrganizationFilters +> { + findByName(name: string): Promise; + findByDomain(domain: string): Promise; + findActiveOrganizations(): Promise; + getUserCount(organizationId: OrganizationId): Promise; + getFeatureFlagCount(organizationId: OrganizationId): Promise; +} + +/** + * User repository interface + */ +export interface IUserRepository extends BaseRepository< + User, + CreateUserInput, + UpdateUserInput, + UserFilters +> { + findByKey(key: string): Promise; + findByEmail(email: string): Promise; + findByOrganization(organizationId: OrganizationId): Promise; + findActiveUsers(): Promise; + updateLastLogin(userId: UserId): Promise; + deactivateUser(userId: UserId): Promise; + getUserFlags(userId: UserId): Promise; + getUserSessions(userId: UserId): Promise; +} + +/** + * Feature flag repository interface + */ +export interface IFeatureFlagRepository extends BaseRepository< + FeatureFlag, + CreateFeatureFlagInput, + UpdateFeatureFlagInput, + FeatureFlagFilters +> { + findByKey(key: FlagKey): Promise; + findEnabledFlags(organizationId?: OrganizationId): Promise; + findByCategory(category: string): Promise; + findByTags(tags: string[]): Promise; + toggleFlag(flagId: string, enabled: boolean): Promise; + archiveFlag(flagId: string): Promise; + getUserFlagValue(userId: UserId, flagKey: FlagKey): Promise; + getFlagUsageStats(flagId: string): Promise<{ + totalUsers: number; + enabledForUsers: number; + lastEvaluated: Date | null; + }>; +} + +/** + * User flag repository interface + */ +export interface IUserFlagRepository extends BaseRepository< + UserFlag, + CreateUserFlagInput, + UpdateUserFlagInput, + UserFlagFilters +> { + findByUserAndFlag(userId: UserId, flagId: string): Promise; + findByUser(userId: UserId): Promise; + findByFlag(flagId: string): Promise; + setUserFlag(userId: UserId, flagId: string, value: unknown, reason?: string): Promise; + removeUserFlag(userId: UserId, flagId: string): Promise; + getActiveFlags(userId: UserId): Promise; + cleanupExpiredFlags(): Promise; +} + +/** + * User session repository interface + */ +export interface IUserSessionRepository extends BaseRepository< + UserSession, + CreateUserSessionInput, + UpdateUserSessionInput, + never +> { + findByUser(userId: UserId): Promise; + findActiveByUser(userId: UserId): Promise; + createSession(userId: UserId, sessionData: Omit): Promise; + updateActivity(sessionId: SessionId): Promise; + expireSession(sessionId: SessionId): Promise; + expireAllUserSessions(userId: UserId): Promise; + cleanupExpiredSessions(): Promise; +} + +/** + * Flag event repository interface + */ +export interface IFlagEventRepository extends BaseRepository< + FlagEvent, + CreateFlagEventInput, + never, + never +> { + findByFlag(flagId: string): Promise; + findByUser(userId: UserId): Promise; + findByEventType(eventType: string): Promise; + logFlagEvaluation(flagId: string, userId: UserId, value: unknown, context?: Record): Promise; + logFlagUpdate(flagId: string, userId: UserId, previousValue: unknown, newValue: unknown, reason?: string): Promise; + getEventStats(flagId: string, from: Date, to: Date): Promise<{ + totalEvaluations: number; + uniqueUsers: number; + eventsByType: Record; + }>; +} + +// ===== REPOSITORY IMPLEMENTATIONS ===== + +/** + * Base repository implementation with common functionality + */ +abstract class BaseRepositoryImpl + implements BaseRepository { + + protected constructor( + protected queryBuilder: TypeSafeQueryBuilder, + protected entityName: string + ) {} + + public async findById(id: string, relations?: string[]): Promise { + try { + return await this.queryBuilder.findById(id, relations); + } catch (error) { + handleDatabaseError(error); + } + } + + public async findAll(filters?: TFilters, relations?: string[]): Promise { + try { + return await this.queryBuilder.find({ + where: filters as Partial, + relations + }); + } catch (error) { + handleDatabaseError(error); + } + } + + public async findPaginated( + filters?: TFilters, + pagination?: Partial, + relations?: string[] + ): Promise> { + try { + const paginatedQuery = createPaginatedQuery(this.queryBuilder, pagination); + return await paginatedQuery.execute(filters as Partial, relations); + } catch (error) { + handleDatabaseError(error); + } + } + + public async create(input: TCreateInput): Promise { + try { + return await this.queryBuilder.create(input as Partial); + } catch (error) { + handleDatabaseError(error); + } + } + + public async update(id: string, input: TUpdateInput): Promise { + try { + const success = await this.queryBuilder.update(id, input as Partial); + if (!success) { + throw new DatabaseError(`${this.entityName} with id ${id} not found`, 'NOT_FOUND'); + } + + const updated = await this.findById(id); + if (!updated) { + throw new DatabaseError(`Failed to retrieve updated ${this.entityName}`, 'UPDATE_FAILED'); + } + + return updated; + } catch (error) { + handleDatabaseError(error); + } + } + + public async delete(id: string): Promise { + try { + return await this.queryBuilder.delete(id); + } catch (error) { + handleDatabaseError(error); + } + } + + public async count(filters?: TFilters): Promise { + try { + return await this.queryBuilder.count(filters as Partial); + } catch (error) { + handleDatabaseError(error); + } + } + + public async exists(id: string): Promise { + try { + return await this.queryBuilder.exists({ id } as Partial); + } catch (error) { + handleDatabaseError(error); + } + } + + public async createMany(inputs: TCreateInput[]): Promise { + try { + const results: TEntity[] = []; + for (const input of inputs) { + const entity = await this.create(input); + results.push(entity); + } + return results; + } catch (error) { + handleDatabaseError(error); + } + } + + public async updateMany(updates: Array<{ id: string; data: TUpdateInput }>): Promise { + try { + const results: TEntity[] = []; + for (const update of updates) { + const entity = await this.update(update.id, update.data); + results.push(entity); + } + return results; + } catch (error) { + handleDatabaseError(error); + } + } + + public async deleteMany(ids: string[]): Promise { + try { + let deleted = 0; + for (const id of ids) { + const success = await this.delete(id); + if (success) deleted++; + } + return deleted; + } catch (error) { + handleDatabaseError(error); + } + } + + public async search(query: string, filters?: TFilters): Promise { + try { + // Basic search implementation - would be enhanced with full-text search in real TypeORM + return await this.findAll(filters); + } catch (error) { + handleDatabaseError(error); + } + } +} + +/** + * Organization repository implementation + */ +export class OrganizationRepository + extends BaseRepositoryImpl + implements IOrganizationRepository { + + public constructor(queryBuilder: TypeSafeQueryBuilder) { + super(queryBuilder, 'Organization'); + } + + public async findByName(name: string): Promise { + try { + return await this.queryBuilder.findOne({ where: { name } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + public async findByDomain(domain: string): Promise { + try { + return await this.queryBuilder.findOne({ where: { domain } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + public async findActiveOrganizations(): Promise { + try { + return await this.queryBuilder.find({ where: { isActive: true } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + public async getUserCount(organizationId: OrganizationId): Promise { + try { + // In real implementation, would use JOIN query + return 0; // Mock implementation + } catch (error) { + handleDatabaseError(error); + } + } + + public async getFeatureFlagCount(organizationId: OrganizationId): Promise { + try { + // In real implementation, would use JOIN query + return 0; // Mock implementation + } catch (error) { + handleDatabaseError(error); + } + } +} + +/** + * User repository implementation + */ +export class UserRepository + extends BaseRepositoryImpl + implements IUserRepository { + + public constructor(queryBuilder: TypeSafeQueryBuilder) { + super(queryBuilder, 'User'); + } + + public async findByKey(key: string): Promise { + try { + return await this.queryBuilder.findOne({ where: { key } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + public async findByEmail(email: string): Promise { + try { + return await this.queryBuilder.findOne({ where: { email } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + public async findByOrganization(organizationId: OrganizationId): Promise { + try { + return await this.queryBuilder.find({ where: { organizationId } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + public async findActiveUsers(): Promise { + try { + return await this.queryBuilder.find({ where: { isActive: true } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + public async updateLastLogin(userId: UserId): Promise { + try { + await this.queryBuilder.update(userId, { lastLoginAt: new Date() } as Partial); + } catch (error) { + handleDatabaseError(error); + } + } + + public async deactivateUser(userId: UserId): Promise { + try { + return await this.queryBuilder.update(userId, { isActive: false } as Partial); + } catch (error) { + handleDatabaseError(error); + } + } + + public async getUserFlags(userId: UserId): Promise { + try { + // In real implementation, would use relation loading + return []; // Mock implementation + } catch (error) { + handleDatabaseError(error); + } + } + + async getUserSessions(userId: UserId): Promise { + try { + // In real implementation, would use relation loading + return []; // Mock implementation + } catch (error) { + handleDatabaseError(error); + } + } +} + +/** + * Feature flag repository implementation + */ +export class FeatureFlagRepository + extends BaseRepositoryImpl + implements IFeatureFlagRepository { + + constructor(queryBuilder: TypeSafeQueryBuilder) { + super(queryBuilder, 'FeatureFlag'); + } + + async findByKey(key: FlagKey): Promise { + try { + return await this.queryBuilder.findOne({ where: { key } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + async findEnabledFlags(organizationId?: OrganizationId): Promise { + try { + const where: Partial = { isEnabled: true }; + if (organizationId) { + where.organizationId = organizationId; + } + return await this.queryBuilder.find({ where }); + } catch (error) { + handleDatabaseError(error); + } + } + + async findByCategory(category: string): Promise { + try { + return await this.queryBuilder.find({ where: { category } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + async findByTags(tags: string[]): Promise { + try { + // In real implementation, would use array contains query + return []; // Mock implementation + } catch (error) { + handleDatabaseError(error); + } + } + + async toggleFlag(flagId: string, enabled: boolean): Promise { + try { + return await this.queryBuilder.update(flagId, { isEnabled: enabled } as Partial); + } catch (error) { + handleDatabaseError(error); + } + } + + async archiveFlag(flagId: string): Promise { + try { + return await this.queryBuilder.update(flagId, { isArchived: true } as Partial); + } catch (error) { + handleDatabaseError(error); + } + } + + async getUserFlagValue(userId: UserId, flagKey: FlagKey): Promise { + try { + // In real implementation, would use JOIN query + return null; // Mock implementation + } catch (error) { + handleDatabaseError(error); + } + } + + async getFlagUsageStats(flagId: string): Promise<{ + totalUsers: number; + enabledForUsers: number; + lastEvaluated: Date | null; + }> { + try { + // In real implementation, would use aggregation queries + return { + totalUsers: 0, + enabledForUsers: 0, + lastEvaluated: null + }; + } catch (error) { + handleDatabaseError(error); + } + } +} + +/** + * User flag repository implementation + */ +export class UserFlagRepository + extends BaseRepositoryImpl + implements IUserFlagRepository { + + constructor(queryBuilder: TypeSafeQueryBuilder) { + super(queryBuilder, 'UserFlag'); + } + + async findByUserAndFlag(userId: UserId, flagId: string): Promise { + try { + return await this.queryBuilder.findOne({ + where: { userId, featureFlagId: flagId } as Partial + }); + } catch (error) { + handleDatabaseError(error); + } + } + + async findByUser(userId: UserId): Promise { + try { + return await this.queryBuilder.find({ where: { userId } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + async findByFlag(flagId: string): Promise { + try { + return await this.queryBuilder.find({ where: { featureFlagId: flagId } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + async setUserFlag(userId: UserId, flagId: string, value: unknown, reason?: string): Promise { + try { + const existing = await this.findByUserAndFlag(userId, flagId); + + if (existing) { + return await this.update(existing.id, { + value, + reason, + isActive: true + } as UpdateUserFlagInput); + } else { + return await this.create({ + userId, + featureFlagId: flagId, + value, + reason, + isActive: true + }); + } + } catch (error) { + handleDatabaseError(error); + } + } + + async removeUserFlag(userId: UserId, flagId: string): Promise { + try { + const existing = await this.findByUserAndFlag(userId, flagId); + if (existing) { + return await this.delete(existing.id); + } + return false; + } catch (error) { + handleDatabaseError(error); + } + } + + async getActiveFlags(userId: UserId): Promise { + try { + return await this.queryBuilder.find({ + where: { userId, isActive: true } as Partial + }); + } catch (error) { + handleDatabaseError(error); + } + } + + async cleanupExpiredFlags(): Promise { + try { + const now = new Date(); + // In real implementation, would use bulk delete query + return 0; // Mock implementation + } catch (error) { + handleDatabaseError(error); + } + } +} + +/** + * User session repository implementation + */ +export class UserSessionRepository + extends BaseRepositoryImpl + implements IUserSessionRepository { + + constructor(queryBuilder: TypeSafeQueryBuilder) { + super(queryBuilder, 'UserSession'); + } + + async findByUser(userId: UserId): Promise { + try { + return await this.queryBuilder.find({ where: { userId } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + async findActiveByUser(userId: UserId): Promise { + try { + return await this.queryBuilder.find({ + where: { userId, isActive: true } as Partial + }); + } catch (error) { + handleDatabaseError(error); + } + } + + async createSession(userId: UserId, sessionData: Omit): Promise { + try { + return await this.create({ userId, ...sessionData }); + } catch (error) { + handleDatabaseError(error); + } + } + + async updateActivity(sessionId: SessionId): Promise { + try { + return await this.queryBuilder.update(sessionId, { + lastActivityAt: new Date() + } as Partial); + } catch (error) { + handleDatabaseError(error); + } + } + + async expireSession(sessionId: SessionId): Promise { + try { + return await this.queryBuilder.update(sessionId, { + isActive: false, + expiresAt: new Date() + } as Partial); + } catch (error) { + handleDatabaseError(error); + } + } + + async expireAllUserSessions(userId: UserId): Promise { + try { + const sessions = await this.findActiveByUser(userId); + let expired = 0; + + for (const session of sessions) { + const success = await this.expireSession(session.id); + if (success) expired++; + } + + return expired; + } catch (error) { + handleDatabaseError(error); + } + } + + async cleanupExpiredSessions(): Promise { + try { + const now = new Date(); + // In real implementation, would use bulk delete query + return 0; // Mock implementation + } catch (error) { + handleDatabaseError(error); + } + } +} + +/** + * Flag event repository implementation + */ +export class FlagEventRepository + extends BaseRepositoryImpl + implements IFlagEventRepository { + + constructor(queryBuilder: TypeSafeQueryBuilder) { + super(queryBuilder, 'FlagEvent'); + } + + async findByFlag(flagId: string): Promise { + try { + return await this.queryBuilder.find({ where: { featureFlagId: flagId } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + async findByUser(userId: UserId): Promise { + try { + return await this.queryBuilder.find({ where: { userId } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + async findByEventType(eventType: string): Promise { + try { + return await this.queryBuilder.find({ where: { eventType } as Partial }); + } catch (error) { + handleDatabaseError(error); + } + } + + async logFlagEvaluation(flagId: string, userId: UserId, value: unknown, context?: Record): Promise { + try { + return await this.create({ + featureFlagId: flagId, + userId, + eventType: 'evaluation', + newValue: value, + context + }); + } catch (error) { + handleDatabaseError(error); + } + } + + async logFlagUpdate(flagId: string, userId: UserId, previousValue: unknown, newValue: unknown, reason?: string): Promise { + try { + return await this.create({ + featureFlagId: flagId, + userId, + eventType: 'update', + previousValue, + newValue, + reason + }); + } catch (error) { + handleDatabaseError(error); + } + } + + async getEventStats(flagId: string, from: Date, to: Date): Promise<{ + totalEvaluations: number; + uniqueUsers: number; + eventsByType: Record; + }> { + try { + // In real implementation, would use aggregation queries + return { + totalEvaluations: 0, + uniqueUsers: 0, + eventsByType: {} + }; + } catch (error) { + handleDatabaseError(error); + } + } +} + +// ===== REPOSITORY PROVIDER ===== + +/** + * Repository provider with dependency injection + */ +export class RepositoryProvider { + private repositoryFactory: RepositoryFactory; + + constructor(connection: DatabaseConnection) { + this.repositoryFactory = new RepositoryFactory(connection); + } + + getOrganizationRepository(): IOrganizationRepository { + return new OrganizationRepository(this.repositoryFactory.getOrganizationRepository()); + } + + getUserRepository(): IUserRepository { + return new UserRepository(this.repositoryFactory.getUserRepository()); + } + + getFeatureFlagRepository(): IFeatureFlagRepository { + return new FeatureFlagRepository(this.repositoryFactory.getFeatureFlagRepository()); + } + + getUserFlagRepository(): IUserFlagRepository { + return new UserFlagRepository(this.repositoryFactory.getUserFlagRepository()); + } + + getUserSessionRepository(): IUserSessionRepository { + return new UserSessionRepository(this.repositoryFactory.getUserSessionRepository()); + } + + getFlagEventRepository(): IFlagEventRepository { + return new FlagEventRepository(this.repositoryFactory.getFlagEventRepository()); + } +} + +// ===== UNIT OF WORK PATTERN ===== + +/** + * Unit of Work pattern for managing database transactions + */ +export class UnitOfWork { + private repositories: RepositoryProvider; + + constructor(private connection: DatabaseConnection) { + this.repositories = new RepositoryProvider(connection); + } + + get Organizations(): IOrganizationRepository { + return this.repositories.getOrganizationRepository(); + } + + get Users(): IUserRepository { + return this.repositories.getUserRepository(); + } + + get FeatureFlags(): IFeatureFlagRepository { + return this.repositories.getFeatureFlagRepository(); + } + + get UserFlags(): IUserFlagRepository { + return this.repositories.getUserFlagRepository(); + } + + get UserSessions(): IUserSessionRepository { + return this.repositories.getUserSessionRepository(); + } + + get FlagEvents(): IFlagEventRepository { + return this.repositories.getFlagEventRepository(); + } + + /** + * Execute operations within a transaction + */ + async executeTransaction(operations: (uow: UnitOfWork) => Promise): Promise { + return await this.connection.transaction(async () => { + return await operations(this); + }); + } +} + +// ===== EXPORT FUNCTIONS ===== + +/** + * Create repository provider from database connection + */ +export function createRepositoryProvider(connection: DatabaseConnection): RepositoryProvider { + return new RepositoryProvider(connection); +} + +/** + * Create unit of work from database connection + */ +export function createUnitOfWork(connection: DatabaseConnection): UnitOfWork { + return new UnitOfWork(connection); +} \ No newline at end of file diff --git a/launchdarkly/node/sample.js b/launchdarkly/node/sample.js index 0c255162..d4885251 100644 --- a/launchdarkly/node/sample.js +++ b/launchdarkly/node/sample.js @@ -21,26 +21,191 @@ */ import * as LaunchDarkly from "@launchdarkly/node-server-sdk"; +import { z } from "zod"; +// === VALIDATION SCHEMAS === +const SDKKeySchema = z.string().min(1, "SDK key cannot be empty").refine( + (val) => val !== "", + "SDK key must be a valid key, not placeholder" +); + +const ContextSchema = z.object({ + kind: z.enum(["user", "organization", "device"], { + errorMap: () => ({ message: "Context kind must be 'user', 'organization', or 'device'" }) + }), + key: z.string().min(1, "Context key is required"), + name: z.string().optional(), + email: z.string().email().optional(), + custom: z.record(z.union([z.string(), z.number(), z.boolean()])).optional() +}); + +const FeatureFlagResultSchema = z.object({ + flagKey: z.string(), + value: z.unknown(), + variationIndex: z.number().optional(), + reason: z.object({ + kind: z.string(), + ruleIndex: z.number().optional(), + ruleId: z.string().optional() + }).optional() +}); + +// === VALIDATION ERROR HANDLING === +class ValidationError extends Error { + constructor(zodError, context = "Validation") { + const errorMessage = `${context} failed: ${zodError.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`; + super(errorMessage); + this.name = "ValidationError"; + this.validationErrors = zodError; + this.context = context; + } + + getFormattedErrors() { + const errors = {}; + for (const error of this.validationErrors.errors) { + const path = error.path.join('.') || 'root'; + if (!errors[path]) { + errors[path] = []; + } + errors[path].push(error.message); + } + return errors; + } +} + +// === VALIDATION FUNCTIONS === +function validateSDKKey(key) { + try { + return SDKKeySchema.parse(key); + } catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'SDK Key validation'); + } + throw error; + } +} + +function validateContext(context) { + try { + return ContextSchema.parse(context); + } catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'Context validation'); + } + throw error; + } +} + +function validateFeatureFlagResult(flagKey, value, metadata = {}) { + try { + return FeatureFlagResultSchema.parse({ + flagKey, + value, + ...metadata + }); + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('Feature flag result validation failed:', new ValidationError(error, 'Feature flag result validation').message); + } + return { flagKey, value, validated: false }; + } +} + +// === CONFIGURATION === const SDK_KEY = ""; const context = { kind: "user", name: "Sandy", key: "example-context-key", }; +// === INITIALIZATION WITH VALIDATION === +try { + // Validate SDK key before initialization + validateSDKKey(SDK_KEY); + console.log("SDK key validation passed"); +} catch (error) { + console.error("SDK key validation failed:", error.message); + console.error("Please replace with your actual LaunchDarkly SDK key"); + process.exit(1); +} + +try { + // Validate context before using it + const validatedContext = validateContext(context); + console.log("Context validation passed:", validatedContext); +} catch (error) { + console.error("Context validation failed:", error.message); + if (error instanceof ValidationError) { + console.error("Validation errors:", error.getFormattedErrors()); + } + process.exit(1); +} + const client = LaunchDarkly.init(SDK_KEY); client.once("ready", () => { - client.variation( - "is-dark-mode-enabled", - context, - false, - (err, useDarkMode) => { - if (useDarkMode) { - console.log("Dark mode is enabled"); - } else { - console.log("Dark mode is disabled"); - } - }, - ); + console.log("LaunchDarkly client is ready"); + + // Validate context again before feature flag evaluation + try { + const validatedContext = validateContext(context); + + client.variation( + "is-dark-mode-enabled", + validatedContext, + false, + (err, useDarkMode) => { + if (err) { + console.error("Feature flag evaluation error:", err); + return; + } + + // Validate the feature flag result + const flagResult = validateFeatureFlagResult("is-dark-mode-enabled", useDarkMode, { + variationIndex: undefined, // LaunchDarkly callback doesn't provide this + reason: undefined // LaunchDarkly callback doesn't provide this + }); + + console.log("Feature flag result:", flagResult); + + if (useDarkMode) { + console.log("✓ Dark mode is enabled"); + } else { + console.log("✗ Dark mode is disabled"); + } + + // Additional feature flag with validation + client.variation( + "enable-high-contrast", + validatedContext, + true, + (err, enableHighContrast) => { + if (err) { + console.error("High contrast flag evaluation error:", err); + return; + } + + const contrastFlagResult = validateFeatureFlagResult("enable-high-contrast", enableHighContrast); + console.log("High contrast flag result:", contrastFlagResult); + + if (enableHighContrast) { + console.log("✓ High contrast mode is enabled"); + } else { + console.log("✗ High contrast mode is disabled"); + } + + // Close client after evaluation + client.close(); + } + ); + }, + ); + } catch (error) { + console.error("Context validation failed during flag evaluation:", error.message); + client.close(); + } +}); + +client.once("failed", (error) => { + console.error("LaunchDarkly client failed to initialize:", error); }); diff --git a/launchdarkly/node/sample.ts b/launchdarkly/node/sample.ts new file mode 100644 index 00000000..51b95bec --- /dev/null +++ b/launchdarkly/node/sample.ts @@ -0,0 +1,1692 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Example of using the LaunchDarkly JavaScript SDK to evaluate feature flags. + * Demonstrates proper TypeScript return type annotations for API boundaries, + * service layers, and repository interfaces. + * + * https://docs.launchdarkly.com/sdk/client-side/javascript + */ + +// Note: Install @launchdarkly/node-server-sdk for actual implementation +// import * as LaunchDarkly from "@launchdarkly/node-server-sdk"; +import { z } from "zod"; + +// Mock LaunchDarkly types for demonstration +interface LDContext { + key: string; + name?: string; + kind?: string; + [key: string]: unknown; +} + +interface LDFlagValue { + [key: string]: boolean | string | number; +} + +interface LDFlagsState { + allValues(): Record; + valid: boolean; +} + +type LDVariationCallback = (err: Error | null, result: T) => void; +type LDFlagsStateCallback = (err: Error | null, result: LDFlagsState) => void; + +// === ZOD VALIDATION SCHEMAS FOR API BOUNDARIES === +const ValidationSchemas = { + // Context validation with proper typing + LDContext: z.object({ + key: z.string().min(1, "Context key is required"), + name: z.string().optional(), + kind: z.enum(["user", "organization", "device"]).optional().default("user"), + email: z.string().email().optional(), + custom: z.record(z.union([z.string(), z.number(), z.boolean()])).optional() + }).strict(), + + // Feature flag key validation + FeatureFlagKey: z.string().min(1, "Feature flag key cannot be empty").refine( + (val) => /^[a-zA-Z0-9-_.]+$/.test(val), + "Feature flag key must contain only alphanumeric characters, hyphens, underscores, and dots" + ), + + // SDK key validation + SDKKey: z.string().min(1, "SDK key cannot be empty").refine( + (val) => !val.includes("<") && !val.includes(">"), + "SDK key must be a valid key, not a placeholder" + ), + + // Flag value validation (supports common types) + FlagValue: z.union([ + z.boolean(), + z.string(), + z.number(), + z.record(z.unknown()) + ]), + + // Variation result with metadata + VariationResult: z.object({ + key: z.string(), + value: z.unknown(), + variationIndex: z.number().optional(), + reason: z.object({ + kind: z.string(), + ruleIndex: z.number().optional(), + ruleId: z.string().optional() + }).optional(), + trackEvents: z.boolean().optional(), + debugEventsUntilDate: z.number().optional() + }), + + // Flags state validation + FlagsState: z.object({ + valid: z.boolean(), + flags: z.record(z.unknown()) + }) +} as const; + +// === VALIDATION ERROR HANDLING === +export class ValidationError extends Error { + public readonly validationErrors: z.ZodError; + public readonly context: string; + + constructor(zodError: z.ZodError, context: string = "Validation") { + const errorMessage = `${context} failed: ${zodError.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`; + super(errorMessage); + this.name = "ValidationError"; + this.validationErrors = zodError; + this.context = context; + } + + public getFormattedErrors(): Record { + const errors: Record = {}; + for (const error of this.validationErrors.errors) { + const path = error.path.join('.') || 'root'; + if (!errors[path]) { + errors[path] = []; + } + errors[path].push(error.message); + } + return errors; + } +} + +// === VALIDATION UTILITY FUNCTIONS === +const ValidationUtils = { + // Safe parsing with detailed error handling + safeParse(schema: z.ZodSchema, data: unknown, context?: string): { + success: true; + data: T; + } | { + success: false; + error: ValidationError; + } { + try { + const result = schema.parse(data); + return { success: true, data: result }; + } catch (error) { + if (error instanceof z.ZodError) { + return { + success: false, + error: new ValidationError(error, context || "Data validation") + }; + } + throw error; + } + }, + + // Strict parsing that throws on validation failure + parse(schema: z.ZodSchema, data: unknown, context?: string): T { + try { + return schema.parse(data); + } catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, context || "Data parsing"); + } + throw error; + } + }, + + // Type guard factory + createTypeGuard(schema: z.ZodSchema) { + return (data: unknown): data is T => { + try { + schema.parse(data); + return true; + } catch { + return false; + } + }; + } +} as const; + +// === EXPORTED TYPE GUARDS === +export const isValidLDContext = ValidationUtils.createTypeGuard(ValidationSchemas.LDContext); +export const isValidFeatureFlagKey = ValidationUtils.createTypeGuard(ValidationSchemas.FeatureFlagKey); +export const isValidSDKKey = ValidationUtils.createTypeGuard(ValidationSchemas.SDKKey); +export const isValidFlagValue = ValidationUtils.createTypeGuard(ValidationSchemas.FlagValue); + +declare namespace LaunchDarkly { + interface LDClient { + variation(key: string, context: LDContext, defaultValue: T, callback: LDVariationCallback): void; + allFlagsState(context: LDContext, callback: LDFlagsStateCallback): void; + waitForInitialization(): Promise; + } + function init(sdkKey: string): LDClient; +} + +interface User extends LDContext { + kind: string; + name: string; + key: string; +} + +interface FeatureFlags { + isDarkModeEnabled: boolean; + enableHighContrast: boolean; +} + +interface ApiResponse { + data: T | null; + success: boolean; + error?: string | null; +} + +// Strict RPC Error Types following tRPC patterns +type RPCErrorCode = + | 'PARSE_ERROR' + | 'BAD_REQUEST' + | 'UNAUTHORIZED' + | 'FORBIDDEN' + | 'NOT_FOUND' + | 'METHOD_NOT_SUPPORTED' + | 'TIMEOUT' + | 'CONFLICT' + | 'PRECONDITION_FAILED' + | 'PAYLOAD_TOO_LARGE' + | 'UNPROCESSABLE_CONTENT' + | 'TOO_MANY_REQUESTS' + | 'CLIENT_CLOSED_REQUEST' + | 'INTERNAL_SERVER_ERROR'; + +interface RPCError { + code: RPCErrorCode; + message: string; + data?: unknown; + cause?: Error; +} + +// RPC Response wrapper with strict typing +type RPCResponse = + | { success: true; data: TData; error?: never } + | { success: false; data?: never; error: RPCError }; + +// Input validation schema types +interface RPCInputSchema { + parse(input: unknown): T; + safeParse(input: unknown): { success: true; data: T } | { success: false; error: RPCError }; +} + +// Concrete validation schemas for each input type +class GetFeatureFlagInputSchema implements RPCInputSchema { + public parse(input: unknown): GetFeatureFlagInput { + const result = this.safeParse(input); + if (!result.success) { + throw new Error(result.error.message); + } + return result.data; + } + + public safeParse(input: unknown): { success: true; data: GetFeatureFlagInput } | { success: false; error: RPCError } { + if (!input || typeof input !== 'object') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'Input must be an object' + } + }; + } + + const obj = input as Record; + + if (!obj.flagKey || typeof obj.flagKey !== 'string') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'flagKey is required and must be a string' + } + }; + } + + if (!obj.context || typeof obj.context !== 'object') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'context is required and must be a User object' + } + }; + } + + if (obj.defaultValue !== undefined && typeof obj.defaultValue !== 'boolean') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'defaultValue must be a boolean if provided' + } + }; + } + + return { + success: true, + data: { + flagKey: obj.flagKey, + context: obj.context as User, + defaultValue: obj.defaultValue as boolean ?? false + } + }; + } +} + +class UpdateFeatureFlagInputSchema implements RPCInputSchema { + public parse(input: unknown): UpdateFeatureFlagInput { + const result = this.safeParse(input); + if (!result.success) { + throw new Error(result.error.message); + } + return result.data; + } + + public safeParse(input: unknown): { success: true; data: UpdateFeatureFlagInput } | { success: false; error: RPCError } { + if (!input || typeof input !== 'object') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'Input must be an object' + } + }; + } + + const obj = input as Record; + + if (!obj.flagKey || typeof obj.flagKey !== 'string') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'flagKey is required and must be a string' + } + }; + } + + if (typeof obj.value !== 'boolean') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'value is required and must be a boolean' + } + }; + } + + if (!obj.context || typeof obj.context !== 'object') { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'context is required and must be a User object' + } + }; + } + + return { + success: true, + data: { + flagKey: obj.flagKey, + value: obj.value, + context: obj.context as User, + reason: typeof obj.reason === 'string' ? obj.reason : undefined + } + }; + } +} + +// Context types for RPC procedures +interface RPCContext { + user?: User | null; + session?: { + id: string; + expiresAt: Date; + permissions: string[]; + }; + request?: { + userAgent?: string; + ip?: string; + headers?: Record; + }; +} + +// Branded middleware types for better compile-time safety +type MiddlewareBrand = string & { readonly __middlewareBrand: T }; +type AuthMiddleware = MiddlewareBrand<'auth'>; +type RateLimitMiddleware = MiddlewareBrand<'rateLimit'>; +type AdminOnlyMiddleware = MiddlewareBrand<'adminOnly'>; +type CorsMiddleware = MiddlewareBrand<'cors'>; +type LoggingMiddleware = MiddlewareBrand<'logging'>; +type ValidationMiddleware = MiddlewareBrand<'validation'>; + +// Middleware types for RPC procedures with branded types +type MiddlewareName = AuthMiddleware | RateLimitMiddleware | AdminOnlyMiddleware | CorsMiddleware | LoggingMiddleware | ValidationMiddleware; + +// Middleware type constructors +const MIDDLEWARE_TYPES = { + auth: 'auth' as AuthMiddleware, + rateLimit: 'rateLimit' as RateLimitMiddleware, + adminOnly: 'adminOnly' as AdminOnlyMiddleware, + cors: 'cors' as CorsMiddleware, + logging: 'logging' as LoggingMiddleware, + validation: 'validation' as ValidationMiddleware, +} as const; + +interface MiddlewareConfig { + auth: { + required: boolean; + roles?: string[]; + permissions?: string[]; + }; + rateLimit: { + windowMs: number; + maxRequests: number; + skipSuccessfulRequests?: boolean; + }; + adminOnly: { + requireSuperAdmin?: boolean; + allowedRoles: string[]; + }; + cors: { + origins: string[]; + methods: string[]; + credentials?: boolean; + }; + logging: { + level: 'debug' | 'info' | 'warn' | 'error'; + includeRequestBody?: boolean; + includeResponseBody?: boolean; + }; + validation: { + validateInput: boolean; + validateOutput: boolean; + sanitizeInput?: boolean; + }; +} + +interface MiddlewareExecutionContext { + name: T; + config: MiddlewareConfig[T]; + context: RPCContext; + input: unknown; + startTime: Date; + // Branded type for middleware execution tracking + readonly __executionBrand: `${T}Execution`; +} + +interface MiddlewareResult { + success: boolean; + error?: RPCError; + modifiedContext?: Partial; + modifiedInput?: unknown; +} + +type MiddlewareFunction = ( + ctx: MiddlewareExecutionContext +) => Promise | MiddlewareResult; + +interface MiddlewareStack { + auth: MiddlewareFunction<'auth'>; + rateLimit: MiddlewareFunction<'rateLimit'>; + adminOnly: MiddlewareFunction<'adminOnly'>; + cors: MiddlewareFunction<'cors'>; + logging: MiddlewareFunction<'logging'>; + validation: MiddlewareFunction<'validation'>; +} + +// === DOMAIN OPERATION TYPES - Business operation contracts === +namespace Domain { + interface GetFeatureFlagInput { + flagKey: string; + userContext: UserContext; + defaultValue: boolean; + } + + interface GetAllFeatureFlagsInput { + userContext: UserContext; + filters?: { + enabled?: boolean; + category?: string; + tags?: string[]; + }; + limit?: number; + offset?: number; + } + + interface UpdateFeatureFlagInput { + flagKey: string; + value: boolean; + userContext: UserContext; + reason?: string; + } + + interface DeleteFeatureFlagInput { + flagKey: string; + userContext: UserContext; + force?: boolean; + } + + interface GetUserFlagsInput { + userId: string; + includeMetadata?: boolean; + } + + interface UpdateUserFlagInput { + userId: string; + flagKey: string; + value: boolean; + validatePermissions?: boolean; + } +} + +// === API OPERATION TYPES - External API operation contracts === +namespace API { + interface GetFeatureFlagRequest { + flagKey: string; + context: LDUser; + defaultValue: boolean; + } + + interface GetAllFeatureFlagsRequest { + context: LDUser; + filters?: { + enabled?: boolean; + category?: string; + tags?: string[]; + }; + limit?: number; + offset?: number; + } + + interface UpdateFeatureFlagRequest { + flagKey: string; + value: boolean; + context: LDUser; + reason?: string; + } + + interface DeleteFeatureFlagRequest { + flagKey: string; + context: LDUser; + force?: boolean; + } + + interface GetUserFlagsRequest { + userId: string; + includeMetadata?: boolean; + } + + interface UpdateUserFlagRequest { + userId: string; + flagKey: string; + value: boolean; + validatePermissions?: boolean; + } +} + +// Strict RPC Procedure Output Types +interface GetFeatureFlagOutput { + value: boolean; + source: 'default' | 'override' | 'experiment'; + lastModified?: Date; + version?: string; +} + +interface GetAllFeatureFlagsOutput { + flags: Record; + metadata: { + total: number; + returnedCount: number; + hasMore: boolean; + nextOffset?: number; + }; + lastSync?: Date; +} + +interface UpdateFeatureFlagOutput { + success: boolean; + previousValue?: boolean; + newValue: boolean; + timestamp: Date; + version: string; +} + +interface DeleteFeatureFlagOutput { + deleted: boolean; + flagKey: string; + timestamp: Date; +} + +// Branded types for stronger type safety at boundaries +type BrandedString = string & { readonly __brand: T }; +type UserId = BrandedString<'UserId'>; +type FlagKey = BrandedString<'FlagKey'>; +type SessionId = BrandedString<'SessionId'>; +// Security-critical branded types to prevent key confusion +type SdkKey = BrandedString<'SdkKey'>; +type ClientSideId = BrandedString<'ClientSideId'>; +type ApiKey = BrandedString<'ApiKey'>; +type SecretKey = BrandedString<'SecretKey'>; +// Request tracking and system observability +type RequestId = BrandedString<'RequestId'>; +type TraceId = BrandedString<'TraceId'>; +type CorrelationId = BrandedString<'CorrelationId'>; +// Configuration and feature management +type EnvironmentKey = BrandedString<'EnvironmentKey'>; +type ProjectKey = BrandedString<'ProjectKey'>; +type FeatureFlagName = BrandedString<'FeatureFlagName'>; +// User context and identity management +type UserContextKey = BrandedString<'UserContextKey'>; +type TenantId = BrandedString<'TenantId'>; +type OrganizationId = BrandedString<'OrganizationId'>; + +// Create branded type constructors with validation +const createUserId = (value: string): UserId | null => { + return value && value.length > 0 ? value as UserId : null; +}; + +const createFlagKey = (value: string): FlagKey | null => { + return value && value.length > 0 && /^[a-zA-Z0-9._-]+$/.test(value) ? value as FlagKey : null; +}; + +const createSessionId = (value: string): SessionId | null => { + return value && value.length > 0 ? value as SessionId : null; +}; + +// Security-critical type constructors with strict validation +const createSdkKey = (value: string): SdkKey | null => { + // SDK keys typically have a specific format: sdk-{environment}-{key} + return value && value.length > 0 && value.startsWith('sdk-') ? value as SdkKey : null; +}; + +const createClientSideId = (value: string): ClientSideId | null => { + // Client-side IDs are typically shorter and different format than SDK keys + return value && value.length > 0 && !value.startsWith('sdk-') ? value as ClientSideId : null; +}; + +const createApiKey = (value: string): ApiKey | null => { + // API keys should be non-empty strings with minimum length for security + return value && value.length >= 20 ? value as ApiKey : null; +}; + +const createSecretKey = (value: string): SecretKey | null => { + // Secret keys require even stricter validation + return value && value.length >= 32 ? value as SecretKey : null; +}; + +// Request tracking constructors +const createRequestId = (value: string): RequestId | null => { + // Request IDs should be valid UUIDs or similar format + return value && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value) ? value as RequestId : null; +}; + +const createTraceId = (value: string): TraceId | null => { + // Trace IDs for distributed tracing + return value && value.length > 0 && /^[a-fA-F0-9]+$/.test(value) ? value as TraceId : null; +}; + +const createCorrelationId = (value: string): CorrelationId | null => { + // Correlation IDs for request correlation + return value && value.length > 0 ? value as CorrelationId : null; +}; + +// Configuration type constructors +const createEnvironmentKey = (value: string): EnvironmentKey | null => { + // Environment keys: production, staging, development, etc. + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value as EnvironmentKey : null; +}; + +const createProjectKey = (value: string): ProjectKey | null => { + // Project keys for LaunchDarkly projects + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value as ProjectKey : null; +}; + +const createFeatureFlagName = (value: string): FeatureFlagName | null => { + // Feature flag names with kebab-case convention + return value && value.length > 0 && /^[a-z0-9-]+$/.test(value) ? value as FeatureFlagName : null; +}; + +// Identity management constructors +const createUserContextKey = (value: string): UserContextKey | null => { + // User context keys for LaunchDarkly contexts + return value && value.length > 0 ? value as UserContextKey : null; +}; + +const createTenantId = (value: string): TenantId | null => { + // Tenant IDs for multi-tenant applications + return value && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value) ? value as TenantId : null; +}; + +const createOrganizationId = (value: string): OrganizationId | null => { + // Organization IDs for organizational boundaries + return value && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value) ? value as OrganizationId : null; +}; + +// Type guards for runtime validation of branded types +const isUserId = (value: unknown): value is UserId => { + return typeof value === 'string' && value.length > 0; +}; + +const isFlagKey = (value: unknown): value is FlagKey => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9._-]+$/.test(value); +}; + +const isSessionId = (value: unknown): value is SessionId => { + return typeof value === 'string' && value.length > 0; +}; + +const isSdkKey = (value: unknown): value is SdkKey => { + return typeof value === 'string' && value.length > 0 && value.startsWith('sdk-'); +}; + +const isClientSideId = (value: unknown): value is ClientSideId => { + return typeof value === 'string' && value.length > 0 && !value.startsWith('sdk-'); +}; + +const isApiKey = (value: unknown): value is ApiKey => { + return typeof value === 'string' && value.length >= 20; +}; + +const isSecretKey = (value: unknown): value is SecretKey => { + return typeof value === 'string' && value.length >= 32; +}; + +const isRequestId = (value: unknown): value is RequestId => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value); +}; + +const isTraceId = (value: unknown): value is TraceId => { + return typeof value === 'string' && value.length > 0 && /^[a-fA-F0-9]+$/.test(value); +}; + +const isCorrelationId = (value: unknown): value is CorrelationId => { + return typeof value === 'string' && value.length > 0; +}; + +const isEnvironmentKey = (value: unknown): value is EnvironmentKey => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value); +}; + +const isProjectKey = (value: unknown): value is ProjectKey => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value); +}; + +const isFeatureFlagName = (value: unknown): value is FeatureFlagName => { + return typeof value === 'string' && value.length > 0 && /^[a-z0-9-]+$/.test(value); +}; + +const isUserContextKey = (value: unknown): value is UserContextKey => { + return typeof value === 'string' && value.length > 0; +}; + +const isTenantId = (value: unknown): value is TenantId => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value); +}; + +const isOrganizationId = (value: unknown): value is OrganizationId => { + return typeof value === 'string' && value.length > 0 && /^[a-zA-Z0-9-]+$/.test(value); +}; + +// === TRANSFORMATION FUNCTIONS - Convert between Domain and API types === +namespace Transform { + // Domain to API transformations + export function domainUserToApiUser(domainUser: Domain.User): API.LDUser { + return { + key: domainUser.id, + name: domainUser.name, + kind: 'user', + custom: { + organizationId: domainUser.organizationId, + ...domainUser.metadata + } + }; + } + + export function domainUserContextToApiContext(userContext: Domain.UserContext): API.LDUser { + const apiUser = domainUserToApiUser(userContext.user); + return { + ...apiUser, + custom: { + ...apiUser.custom, + environment: userContext.environment, + sessionId: userContext.session?.id, + sessionStartedAt: userContext.session?.startedAt?.toISOString() + } + }; + } + + export function domainFeatureFlagsToApiResponse(domainFlags: Domain.FeatureFlags): API.FeatureFlagsResponse { + return { + isDarkModeEnabled: domainFlags.darkMode, + enableHighContrast: domainFlags.highContrast, + betaFeaturesEnabled: domainFlags.betaFeatures + }; + } + + export function domainGetFeatureFlagInputToApiRequest(input: Domain.GetFeatureFlagInput): API.GetFeatureFlagRequest { + return { + flagKey: input.flagKey, + context: domainUserContextToApiContext(input.userContext), + defaultValue: input.defaultValue + }; + } + + // API to Domain transformations + export function apiUserToDomainUser(apiUser: API.LDUser): Domain.User { + return { + id: apiUser.key, + name: apiUser.name, + organizationId: apiUser.custom?.organizationId as string, + metadata: { + kind: apiUser.kind, + ...apiUser.custom + } + }; + } + + export function apiFeatureFlagsResponseToDomainFlags(apiResponse: API.FeatureFlagsResponse): Domain.FeatureFlags { + return { + darkMode: apiResponse.isDarkModeEnabled, + highContrast: apiResponse.enableHighContrast, + betaFeatures: apiResponse.betaFeaturesEnabled ?? false + }; + } + + export function apiFeatureFlagResponseToDomainFlag(apiResponse: API.FeatureFlagApiResponse): Domain.FeatureFlag { + return { + key: apiResponse.key, + value: apiResponse.value, + name: apiResponse.key, // Assuming key is the name for now + enabled: true, // Assuming if returned, it's enabled + variation: apiResponse.flagVersion?.toString() + }; + } + + // Wrapper for API responses to Domain results + export function apiResponseToDomainResult( + apiResponse: API.ApiResponse, + transformer: (apiData: TApiData) => TDomainData + ): RPCResponse { + if (apiResponse.success && apiResponse.data) { + return { + success: true, + data: transformer(apiResponse.data) + }; + } else { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: apiResponse.error || 'Unknown error occurred' + } + }; + } + } +} + +// === DOMAIN SERVICE INTERFACES - Business logic contracts === +namespace Domain { + interface FeatureFlagReader { + getFeatureFlag(input: GetFeatureFlagInput): Promise>; + getAllFeatureFlags(input: GetAllFeatureFlagsInput): Promise>; + } + + interface FeatureFlagWriter { + updateFeatureFlag(input: UpdateFeatureFlagInput): Promise>; + deleteFeatureFlag(input: DeleteFeatureFlagInput): Promise>; + } + + // Repository Interface - Data Access Layer with domain types + interface FeatureFlagRepository extends FeatureFlagReader, FeatureFlagWriter { + // Explicit interface marker for compile-time verification + readonly __repositoryBrand: 'FeatureFlagRepository'; + } +} + +// === API SERVICE INTERFACES - External API contracts === +namespace API { + interface FeatureFlagApiClient { + getFeatureFlag(request: GetFeatureFlagRequest): Promise>; + getAllFeatureFlags(request: GetAllFeatureFlagsRequest): Promise>; + updateFeatureFlag(request: UpdateFeatureFlagRequest): Promise>; + deleteFeatureFlag(request: DeleteFeatureFlagRequest): Promise>; + } +} + +// === DOMAIN RPC PROCEDURE DEFINITIONS === +namespace Domain { + interface FeatureFlagProcedures { + getFeatureFlag: { + input: GetFeatureFlagInput; + output: FeatureFlag; + context: RPCContext; + }; + getAllFeatureFlags: { + input: GetAllFeatureFlagsInput; + output: FeatureFlags; + context: RPCContext; + }; + updateFeatureFlag: { + input: UpdateFeatureFlagInput; + output: { success: boolean; updatedFlag: FeatureFlag }; + context: RPCContext; + middleware: ['auth', 'rateLimit']; + }; + deleteFeatureFlag: { + input: DeleteFeatureFlagInput; + output: { success: boolean; deletedKey: string }; + context: RPCContext; + middleware: ['auth', 'adminOnly']; + }; + getUserFlags: { + input: GetUserFlagsInput; + output: FeatureFlags; + context: RPCContext; + }; + updateUserFlag: { + input: UpdateUserFlagInput; + output: boolean; + context: RPCContext; + middleware: ['auth']; + }; + } +} + +// tRPC-style Router Interface +interface RPCRouter { + procedures: FeatureFlagProcedures; + middleware: MiddlewareStack; + call( + procedureName: TProcedure, + input: FeatureFlagProcedures[TProcedure]['input'], + context?: RPCContext + ): Promise>; +} + +// Strongly-typed procedure caller +type ProcedureCaller> = { + [K in keyof TProcedures]: TProcedures[K] extends { input: infer TInput; output: infer TOutput } + ? (input: TInput, context?: RPCContext) => Promise> + : never; +}; + +// Type-safe feature flag client +interface FeatureFlagClient extends ProcedureCaller { + // Additional client-specific methods + createContext(user: User, request?: { ip?: string; userAgent?: string }): RPCContext; + validatePermissions(context: RPCContext, requiredPermissions: string[]): boolean; +} + +// Dependency Injection Container with explicit interface conformance +type ServiceToken = symbol & { readonly __serviceType: T }; + +interface IDependencyContainer { + register(token: ServiceToken, factory: () => T): void; + registerSingleton(token: ServiceToken, factory: () => T): void; + resolve(token: ServiceToken): T; + isRegistered(token: ServiceToken): boolean; + // Explicit interface marker for compile-time verification + readonly __containerBrand: 'DependencyContainer'; +} + +class DependencyContainer implements IDependencyContainer { + public readonly __containerBrand = 'DependencyContainer' as const; + private services = new Map, any>(); + private singletons = new Map, any>(); + private factories = new Map, () => any>(); + + public register(token: ServiceToken, factory: () => T): void { + this.factories.set(token, factory); + } + + public registerSingleton(token: ServiceToken, factory: () => T): void { + this.factories.set(token, factory); + this.singletons.set(token, null); // Mark as singleton + } + + public resolve(token: ServiceToken): T { + if (this.singletons.has(token)) { + let instance = this.singletons.get(token); + if (!instance) { + const factory = this.factories.get(token); + if (!factory) { + throw new Error(`Service not registered: ${String(token)}`); + } + instance = factory(); + this.singletons.set(token, instance); + } + return instance; + } + + if (this.services.has(token)) { + return this.services.get(token); + } + + const factory = this.factories.get(token); + if (!factory) { + throw new Error(`Service not registered: ${String(token)}`); + } + + return factory(); + } + + isRegistered(token: ServiceToken): boolean { + return this.factories.has(token); + } +} + +// === DOMAIN SERVICE IMPLEMENTATIONS === +namespace Domain { + // Service Layer Interface with explicit contract definition + interface IFeatureFlagService { + getUserFeatureFlags(userContext: UserContext): Promise>; + updateUserPreference(userContext: UserContext, flagKey: string, value: boolean): Promise>; + validateUser(user: User): Promise; + // Explicit interface marker for compile-time verification + readonly __serviceBrand: 'FeatureFlagService'; + } +} + +// Service tokens for type-safe dependency injection +const SERVICE_TOKENS = { + LaunchDarklyClient: Symbol('LaunchDarklyClient') as ServiceToken, + FeatureFlagRepository: Symbol('FeatureFlagRepository') as ServiceToken, + FeatureFlagService: Symbol('FeatureFlagService') as ServiceToken, + FeatureFlagController: Symbol('FeatureFlagController') as ServiceToken, + FeatureFlagApiClient: Symbol('FeatureFlagApiClient') as ServiceToken, +} as const; + +// Service Layer - Business Logic +class FeatureFlagService implements Domain.IFeatureFlagService { + public readonly __serviceBrand = 'FeatureFlagService' as const; + private repository: Domain.FeatureFlagRepository; + private apiClient: API.FeatureFlagApiClient; + + public constructor(repository: Domain.FeatureFlagRepository, apiClient: API.FeatureFlagApiClient) { + this.repository = repository; + this.apiClient = apiClient; + } + + public async getUserFeatureFlags(userContext: Domain.UserContext): Promise> { + try { + // Use domain types internally + const darkModeResponse = await this.repository.getFeatureFlag({ + flagKey: "is-dark-mode-enabled", + userContext, + defaultValue: false + }); + + if (!darkModeResponse.success) { + return { success: false, error: darkModeResponse.error }; + } + + const contrastResponse = await this.repository.getFeatureFlag({ + flagKey: "enable-high-contrast", + userContext, + defaultValue: true + }); + + if (!contrastResponse.success) { + return { success: false, error: contrastResponse.error }; + } + + // Extract boolean values from FeatureFlag domain objects + const darkModeValue = typeof darkModeResponse.data.value === 'boolean' ? darkModeResponse.data.value : false; + const contrastValue = typeof contrastResponse.data.value === 'boolean' ? contrastResponse.data.value : true; + + return { + success: true, + data: { + darkMode: darkModeValue, + highContrast: contrastValue, + betaFeatures: false // Default for now + } + }; + } catch (error) { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to retrieve user feature flags', + cause: error instanceof Error ? error : new Error(String(error)) + } + }; + } + } + + public async updateUserPreference( + userContext: Domain.UserContext, + flagKey: string, + value: boolean + ): Promise> { + try { + const response = await this.repository.updateFeatureFlag({ + flagKey, + value, + userContext, + reason: 'User preference update' + }); + + return response.success + ? { success: true, data: response.data.success } + : { success: false, error: response.error }; + } catch (error) { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to update user preference', + cause: error instanceof Error ? error : new Error(String(error)) + } + }; + } + } + + public async validateUser(user: Domain.User | null | undefined): Promise { + if (!user?.id || !user?.name) { + return null; + } + + // Additional validation using Zod for user context structure + try { + // Create a context-like object to validate structure + const contextLike = { + key: user.id, + name: user.name, + kind: "user" + }; + + ValidationUtils.parse(ValidationSchemas.LDContext, contextLike, "User validation"); + return user; + } catch (error) { + if (error instanceof ValidationError) { + console.warn("User validation failed:", error.message); + return null; + } + throw error; + } + } + + // Type guard for runtime validation of external data using Zod + private isValidUser(data: unknown): data is User { + return isValidLDContext(data); + } + + // Enhanced LDContext validation with detailed error logging + private isValidLDContext(data: unknown): data is LDContext { + const result = ValidationUtils.safeParse(ValidationSchemas.LDContext, data, "LDContext validation"); + if (!result.success) { + console.warn("LDContext validation failed:", result.error.message); + return false; + } + return true; + } + + // Parse LDContext with comprehensive error handling + private parseLDContext(data: unknown): LDContext { + return ValidationUtils.parse(ValidationSchemas.LDContext, data, "LDContext parsing"); + } + + // Validate feature flag key + private validateFeatureFlagKey(key: string): boolean { + const result = ValidationUtils.safeParse(ValidationSchemas.FeatureFlagKey, key, "Feature flag key validation"); + if (!result.success) { + console.warn("Feature flag key validation failed:", result.error.message); + return false; + } + return true; + } +} + +// === REPOSITORY IMPLEMENTATION - Bridge between Domain and API === +class LaunchDarklyRepository implements Domain.FeatureFlagRepository { + public readonly __repositoryBrand = 'FeatureFlagRepository' as const; + private client: LaunchDarkly.LDClient; + + public constructor(client: LaunchDarkly.LDClient) { + this.client = client; + } + + public async getFeatureFlag(input: Domain.GetFeatureFlagInput): Promise> { + return new Promise((resolve) => { + // Transform domain input to API request + const apiContext = Transform.domainUserContextToApiContext(input.userContext); + + this.client.variation( + input.flagKey, + apiContext, + input.defaultValue, + (err: Error | null, result: boolean) => { + if (err) { + resolve({ + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: `Failed to get feature flag: ${input.flagKey}`, + cause: err + } + }); + } else { + // Transform API response to domain model + const domainFlag: Domain.FeatureFlag = { + key: input.flagKey, + value: result, + name: input.flagKey, + enabled: true, + description: `Feature flag: ${input.flagKey}` + }; + + resolve({ + success: true, + data: domainFlag + }); + } + } + ); + }); + } + + public async getAllFeatureFlags(input: Domain.GetAllFeatureFlagsInput): Promise> { + return new Promise((resolve) => { + // Transform domain input to API request + const apiContext = Transform.domainUserContextToApiContext(input.userContext); + + this.client.allFlagsState(apiContext, (err: Error | null, flagsState: LDFlagsState) => { + if (err) { + resolve({ + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to retrieve all feature flags', + cause: err + } + }); + } else { + const values = flagsState?.allValues() ?? {}; + const booleanValues: Record = {}; + let count = 0; + + for (const [key, value] of Object.entries(values)) { + if (typeof value === 'boolean') { + // Apply filters if provided + if (input.filters?.enabled !== undefined && value !== input.filters.enabled) { + continue; + } + if (input.filters?.category && !key.includes(input.filters.category)) { + continue; + } + if (input.filters?.tags && !input.filters.tags.some(tag => key.includes(tag))) { + continue; + } + + // Apply pagination + if (input.offset && count < input.offset) { + count++; + continue; + } + if (input.limit && Object.keys(booleanValues).length >= input.limit) { + break; + } + + booleanValues[key] = value; + count++; + } + } + + const totalCount = Object.keys(values).filter(key => typeof values[key] === 'boolean').length; + const returnedCount = Object.keys(booleanValues).length; + + // Transform to domain FeatureFlags type + const domainFlags: Domain.FeatureFlags = { + darkMode: booleanValues['is-dark-mode-enabled'] ?? false, + highContrast: booleanValues['enable-high-contrast'] ?? false, + betaFeatures: booleanValues['beta-features-enabled'] ?? false + }; + + resolve({ + success: true, + data: domainFlags + }); + } + }); + }); + } + + public async updateFeatureFlag(input: Domain.UpdateFeatureFlagInput): Promise> { + return { + success: false, + error: { + code: 'METHOD_NOT_SUPPORTED', + message: 'Feature flag updates not supported in client-side SDK', + data: { flagKey: input.flagKey, attemptedValue: input.value } + } + }; + } + + public async deleteFeatureFlag(input: Domain.DeleteFeatureFlagInput): Promise> { + return { + success: false, + error: { + code: 'METHOD_NOT_SUPPORTED', + message: 'Feature flag deletion not supported in client-side SDK', + data: { flagKey: input.flagKey } + } + }; + } +} + +// Controller Interface for API boundary definition +interface IFeatureFlagController { + getUserFlags(userId: string): Promise>; + updateUserFlag(userId: string, flagKey: string, value: boolean): Promise>; + // Explicit interface marker for compile-time verification + readonly __controllerBrand: 'FeatureFlagController'; +} + +// API Boundary - Controllers/Handlers with explicit interface conformance +class FeatureFlagController implements IFeatureFlagController { + public readonly __controllerBrand = 'FeatureFlagController' as const; + private service: IFeatureFlagService; + + public constructor(service: IFeatureFlagService) { + this.service = service; + } + + public async getUserFlags(userId: string): Promise> { + try { + const user: User = { + kind: "user", + name: "User Name", + key: userId, + }; + + const validatedUser = await this.service.validateUser(user); + if (!validatedUser) { + return { + success: false, + error: { + code: 'BAD_REQUEST', + message: 'Invalid user data provided', + data: { userId } + } + }; + } + + const response = await this.service.getUserFeatureFlags(validatedUser); + return response; + } catch (error) { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to retrieve user flags', + cause: error instanceof Error ? error : new Error(String(error)) + } + }; + } + } + + public async updateUserFlag( + userId: string, + flagKey: string, + value: boolean + ): Promise> { + try { + const user: User = { + kind: "user", + name: "User Name", + key: userId, + }; + + const response = await this.service.updateUserPreference(user, flagKey, value); + return response; + } catch (error) { + return { + success: false, + error: { + code: 'INTERNAL_SERVER_ERROR', + message: 'Failed to update user flag', + cause: error instanceof Error ? error : new Error(String(error)) + } + }; + } + } +} + +// Utility functions with explicit return types and validation +function createUser(key: string | null | undefined, name: string | null | undefined): User | null { + if (!key || !name) { + return null; + } + return { + kind: "user", + name, + key, + }; +} + +// Type guard utility functions for external data validation +function isValidApiResponse(data: unknown): data is ApiResponse { + return ( + typeof data === 'object' && + data !== null && + data !== undefined && + 'data' in data && + 'success' in data && + typeof (data as ApiResponse).success === 'boolean' + ); +} + +function validateExternalUserData(data: unknown): User | null { + if ( + typeof data === 'object' && + data !== null && + data !== undefined && + 'key' in data && + 'name' in data && + typeof (data as Partial).key === 'string' && + typeof (data as Partial).name === 'string' + ) { + return { + kind: (data as Partial).kind ?? 'user', + name: (data as User).name, + key: (data as User).key, + }; + } + return null; +} + +async function initializeClient(sdkKey: string): Promise { + const client = LaunchDarkly.init(sdkKey); + await client.waitForInitialization(); + return client; +} + +function logFeatureFlag(flagName: string, value: boolean): void { + if (value) { + console.log(`${flagName} is enabled`); + } else { + console.log(`${flagName} is disabled`); + } +} + +// Main execution with dependency injection container +async function main(): Promise { + const SDK_KEY = ""; + + // === VALIDATION OF INPUTS === + console.log("🔍 Validating SDK key and context..."); + + // Validate SDK key before using it + try { + ValidationUtils.parse(ValidationSchemas.SDKKey, SDK_KEY, "SDK key validation"); + console.log("✓ SDK key validation passed"); + } catch (error) { + if (error instanceof ValidationError) { + console.error("❌ SDK key validation failed:", error.message); + console.error("Please replace '' with your actual LaunchDarkly SDK key"); + return; + } + throw error; + } + + const context = createUser("example-context-key", "Sandy"); + + if (!context) { + console.error("❌ Failed to create user context"); + return; + } + + // Validate the created context + try { + const validatedContext = ValidationUtils.parse(ValidationSchemas.LDContext, context, "Context validation"); + console.log("✓ Context validation passed:", { + key: validatedContext.key, + name: validatedContext.name, + kind: validatedContext.kind + }); + } catch (error) { + if (error instanceof ValidationError) { + console.error("❌ Context validation failed:", error.message); + console.error("Formatted errors:", error.getFormattedErrors()); + return; + } + throw error; + } + + try { + // Initialize dependency injection container + const container = new DependencyContainer(); + + // Register services with explicit typing + container.registerSingleton(SERVICE_TOKENS.LaunchDarklyClient, () => { + return LaunchDarkly.init(SDK_KEY); + }); + + container.register(SERVICE_TOKENS.FeatureFlagRepository, () => { + const client = container.resolve(SERVICE_TOKENS.LaunchDarklyClient); + return new LaunchDarklyRepository(client); + }); + + container.register(SERVICE_TOKENS.FeatureFlagService, () => { + const repository = container.resolve(SERVICE_TOKENS.FeatureFlagRepository); + return new FeatureFlagService(repository); + }); + + container.register(SERVICE_TOKENS.FeatureFlagController, () => { + const service = container.resolve(SERVICE_TOKENS.FeatureFlagService); + return new FeatureFlagController(service); + }); + + // Wait for LaunchDarkly client initialization + const client = container.resolve(SERVICE_TOKENS.LaunchDarklyClient); + await client.waitForInitialization(); + + // Use the container to resolve dependencies + const controller = container.resolve(SERVICE_TOKENS.FeatureFlagController); + const response = await controller.getUserFlags(context.key); + + if (response.success && response.data) { + console.log("🚀 Feature flags retrieved successfully"); + + // Validate individual flag results + const darkModeResult = ValidationUtils.safeParse( + ValidationSchemas.VariationResult, + { + key: "is-dark-mode-enabled", + value: response.data.isDarkModeEnabled + }, + "Dark mode flag validation" + ); + + if (darkModeResult.success) { + logFeatureFlag("Dark mode", darkModeResult.data.value); + } else { + console.warn("Dark mode flag validation failed:", darkModeResult.error.message); + logFeatureFlag("Dark mode", response.data.isDarkModeEnabled); + } + + const highContrastResult = ValidationUtils.safeParse( + ValidationSchemas.VariationResult, + { + key: "enable-high-contrast", + value: response.data.enableHighContrast + }, + "High contrast flag validation" + ); + + if (highContrastResult.success) { + logFeatureFlag("High contrast", highContrastResult.data.value); + } else { + console.warn("High contrast flag validation failed:", highContrastResult.error.message); + logFeatureFlag("High contrast", response.data.enableHighContrast); + } + } else { + console.error("❌ Failed to get user flags:", response.error); + } + } catch (error) { + console.error("Application failed to start:", error); + } +} + +// Utility types for common patterns +export type DomainUserPartial = Partial; +export type DomainUserPick = Pick; +export type DomainUserOmit = Omit; +export type FlagRecord = Record; +export type DomainUserRecord = Record; + +// Configuration types using utility types +export type FeatureFlagConfig = Pick; +export type DomainUserIdentity = Pick; +export type DomainUserMetadata = Omit; + +// Export types and classes for use in other modules +export type { + // LaunchDarkly SDK types + LDContext, + LDFlagsState, + LDFlagValue, + // Dependency injection + IDependencyContainer, + ServiceToken, + // Branded Types + BrandedString, + UserId, + FlagKey, + SessionId, + // Security-critical branded types + SdkKey, + ClientSideId, + ApiKey, + SecretKey, + // Request tracking and system observability + RequestId, + TraceId, + CorrelationId, + // Configuration and feature management + EnvironmentKey, + ProjectKey, + FeatureFlagName, + // User context and identity management + UserContextKey, + TenantId, + OrganizationId, + // Middleware Branded Types + MiddlewareBrand, + AuthMiddleware, + RateLimitMiddleware, + AdminOnlyMiddleware, + CorsMiddleware, + LoggingMiddleware, + ValidationMiddleware, + // RPC Types + RPCError, + RPCErrorCode, + RPCResponse, + RPCInputSchema, + RPCContext, + // Middleware Types + MiddlewareName, + MiddlewareConfig, + MiddlewareExecutionContext, + MiddlewareResult, + MiddlewareFunction, + MiddlewareStack, +}; + +export { + // Namespaces + Domain, + API, + Transform, + // Classes + FeatureFlagService, + LaunchDarklyRepository, + FeatureFlagController, + DependencyContainer, + // Constants + SERVICE_TOKENS, + MIDDLEWARE_TYPES, + // Functions + createUser, + initializeClient, + logFeatureFlag, + main, + isValidApiResponse, + validateExternalUserData, + // Branded type constructors + createUserId, + createFlagKey, + createSessionId, + // Security-critical type constructors + createSdkKey, + createClientSideId, + createApiKey, + createSecretKey, + // Request tracking constructors + createRequestId, + createTraceId, + createCorrelationId, + // Configuration type constructors + createEnvironmentKey, + createProjectKey, + createFeatureFlagName, + // Identity management constructors + createUserContextKey, + createTenantId, + createOrganizationId, + // Type guards for runtime validation + isUserId, + isFlagKey, + isSessionId, + isSdkKey, + isClientSideId, + isApiKey, + isSecretKey, + isRequestId, + isTraceId, + isCorrelationId, + isEnvironmentKey, + isProjectKey, + isFeatureFlagName, + isUserContextKey, + isTenantId, + isOrganizationId, + // Validation Schema Classes + GetFeatureFlagInputSchema, + UpdateFeatureFlagInputSchema, +}; \ No newline at end of file diff --git a/launchdarkly/node/tsconfig.json b/launchdarkly/node/tsconfig.json new file mode 100644 index 00000000..524e393e --- /dev/null +++ b/launchdarkly/node/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./", + "tsBuildInfoFile": "./dist/.tsbuildinfo", + "target": "ES2020", + "module": "CommonJS", + "moduleResolution": "node" + }, + "include": [ + "*.ts" + ], + "references": [] +} \ No newline at end of file diff --git a/launchdarkly/node/types.ts b/launchdarkly/node/types.ts new file mode 100644 index 00000000..9a6124aa --- /dev/null +++ b/launchdarkly/node/types.ts @@ -0,0 +1,701 @@ +/* + * Copyright (c) 2024 Gitar, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Advanced TypeScript utility types for type-safe database operations + * with comprehensive create/update input types and conditional type transformations + */ + +import { z } from "zod"; + +// ===== CORE UTILITY TYPES ===== + +/** + * Extract keys that are optional in a type + */ +type OptionalKeys = { + [K in keyof T]-?: {} extends Pick ? K : never; +}[keyof T]; + +/** + * Extract keys that are required in a type + */ +type RequiredKeys = { + [K in keyof T]-?: {} extends Pick ? never : K; +}[keyof T]; + +/** + * Make only specific keys required + */ +type RequireOnly = Partial & Required>; + +/** + * Make only specific keys optional + */ +type OptionalOnly = Omit & Partial>; + +/** + * Deep partial type for nested objects + */ +type DeepPartial = { + [P in keyof T]?: T[P] extends Array + ? Array> + : T[P] extends ReadonlyArray + ? ReadonlyArray> + : T[P] extends object + ? DeepPartial + : T[P]; +}; + +/** + * Deep required type for nested objects + */ +type DeepRequired = { + [P in keyof T]-?: T[P] extends Array + ? Array> + : T[P] extends ReadonlyArray + ? ReadonlyArray> + : T[P] extends object + ? DeepRequired + : T[P]; +}; + +/** + * Extract non-function properties from a type + */ +type NonFunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? never : K; +}[keyof T]; + +type NonFunctionProperties = Pick>; + +/** + * Extract only primitive properties (exclude objects and arrays) + */ +type PrimitivePropertyNames = { + [K in keyof T]: T[K] extends string | number | boolean | null | undefined + ? K + : never; +}[keyof T]; + +type PrimitiveProperties = Pick>; + +// ===== DATABASE-SPECIFIC UTILITY TYPES ===== + +/** + * Standard database fields that should be excluded from input types + */ +type DatabaseManagedFields = 'id' | 'createdAt' | 'updatedAt' | 'deletedAt'; + +/** + * Readonly fields that cannot be updated after creation + */ +type ReadonlyFields = 'id' | 'createdAt'; + +/** + * Create input type that excludes database-managed fields + */ +type CreateInput = Omit; + +/** + * Update input type that excludes readonly fields and makes all others optional + */ +type UpdateInput = Partial>; + +/** + * Patch input type for partial updates with ID required + */ +type PatchInput = UpdateInput & { id: T extends { id: infer ID } ? ID : string }; + +/** + * Replace input type for full entity replacement (all fields required except database-managed) + */ +type ReplaceInput = Required>; + +/** + * Upsert input type that allows either create or update operations + */ +type UpsertInput = CreateInput | (UpdateInput & { id: T extends { id: infer ID } ? ID : string }); + +/** + * Filter input type for queries (all fields optional, supports nested filtering) + */ +type FilterInput = DeepPartial>; + +/** + * Sort input type for ordering results + */ +type SortInput = { + [K in keyof NonFunctionProperties]?: 'ASC' | 'DESC'; +}; + +/** + * Projection type for selecting specific fields + */ +type ProjectionInput = { + [K in keyof NonFunctionProperties]?: boolean; +}; + +// ===== RELATION HANDLING TYPES ===== + +/** + * Extract relation fields from an entity + */ +type RelationFields = { + [K in keyof T]: T[K] extends Array + ? K + : T[K] extends object + ? T[K] extends Date | string | number | boolean + ? never + : K + : never; +}[keyof T]; + +/** + * Type for specifying which relations to load + */ +type RelationOptions = { + [K in RelationFields]?: boolean | (T[K] extends Array ? RelationOptions : RelationOptions); +}; + +/** + * Entity with relations loaded + */ +type WithRelations> = T & { + [K in keyof R]: R[K] extends true + ? T[K] + : R[K] extends object + ? T[K] extends Array + ? Array> + : WithRelations + : T[K]; +}; + +// ===== VALIDATION AND TRANSFORMATION TYPES ===== + +/** + * Extract Zod schema type from a schema + */ +type InferZodSchema = T extends z.ZodSchema ? U : never; + +/** + * Create a validation schema type from an entity + */ +type ValidationSchema = z.ZodSchema>; + +/** + * Transform type for converting between different representations + */ +type Transform = (input: TInput) => TOutput; + +/** + * Bi-directional transform + */ +interface BiTransform { + toDto: Transform; + fromDto: Transform; +} + +// ===== ADVANCED CONDITIONAL TYPES ===== + +/** + * Conditional type for handling nullable fields + */ +type NullableFields = { + [K in keyof T]: null extends T[K] ? K : never; +}[keyof T]; + +/** + * Make nullable fields optional in input types + */ +type OptionalNullableInput = OptionalOnly>; + +/** + * Type-safe deep merge utility type + */ +type DeepMerge = { + [K in keyof T | keyof U]: K extends keyof U + ? K extends keyof T + ? T[K] extends object + ? U[K] extends object + ? DeepMerge + : U[K] + : U[K] + : U[K] + : K extends keyof T + ? T[K] + : never; +}; + +/** + * Extract array element type + */ +type ArrayElement = T extends Array ? U : never; + +/** + * Create lookup type from array of objects + */ +type Lookup> = { + [P in ArrayElement[K]]: Extract, Record>; +}; + +/** + * Type-safe key-value pair + */ +type KeyValuePair = { + key: K; + value: T[K]; +}; + +// ===== OPERATION RESULT TYPES ===== + +/** + * Standard operation result with success/error states + */ +type OperationResult = + | { success: true; data: TData; error?: never } + | { success: false; data?: never; error: TError }; + +/** + * Async operation result + */ +type AsyncOperationResult = Promise>; + +/** + * Paginated result wrapper + */ +interface PaginatedResult { + data: T[]; + pagination: { + page: number; + limit: number; + total: number; + totalPages: number; + hasNext: boolean; + hasPrev: boolean; + }; +} + +/** + * Bulk operation result + */ +interface BulkOperationResult { + successful: T[]; + failed: Array<{ + item: T; + error: Error; + }>; + totalProcessed: number; + successCount: number; + failureCount: number; +} + +// ===== QUERY BUILDER TYPES ===== + +/** + * Comparison operators for filtering + */ +type ComparisonOperator = + | 'eq' // equals + | 'ne' // not equals + | 'gt' // greater than + | 'gte' // greater than or equals + | 'lt' // less than + | 'lte' // less than or equals + | 'in' // in array + | 'nin' // not in array + | 'like' // SQL LIKE + | 'ilike' // case insensitive LIKE + | 'regex' // regular expression + | 'exists' // field exists + | 'nexists'; // field does not exist + +/** + * Filter condition for a single field + */ +type FieldFilter = { + [K in ComparisonOperator]?: T; +} | T; + +/** + * Advanced filter input with operators + */ +type AdvancedFilterInput = { + [K in keyof NonFunctionProperties]?: FieldFilter; +} & { + $and?: AdvancedFilterInput[]; + $or?: AdvancedFilterInput[]; + $not?: AdvancedFilterInput; +}; + +/** + * Aggregation pipeline type + */ +interface AggregationPipeline { + match?: FilterInput; + group?: { + by: keyof T | Array; + count?: boolean; + sum?: keyof T | Array; + avg?: keyof T | Array; + min?: keyof T | Array; + max?: keyof T | Array; + }; + sort?: SortInput; + limit?: number; + skip?: number; +} + +// ===== ENTITY-SPECIFIC TYPE HELPERS ===== + +/** + * Extract entity type from repository type + */ +type EntityFromRepository = T extends { + create(input: infer U): any; +} ? U extends CreateInput ? E : never : never; + +/** + * Type-safe entity constructor + */ +type EntityConstructor = new (...args: any[]) => T; + +/** + * Entity metadata for reflection + */ +interface EntityMetadata { + name: string; + tableName: string; + primaryKey: keyof T; + columns: Array<{ + property: keyof T; + type: string; + nullable: boolean; + unique: boolean; + default?: any; + }>; + relations: Array<{ + property: keyof T; + type: 'one-to-one' | 'one-to-many' | 'many-to-one' | 'many-to-many'; + target: string; + inverseSide?: string; + }>; + indexes: Array<{ + name: string; + columns: Array; + unique: boolean; + }>; +} + +// ===== MIGRATION AND SCHEMA TYPES ===== + +/** + * Database column definition + */ +interface ColumnDefinition { + name: string; + type: string; + length?: number; + precision?: number; + scale?: number; + nullable: boolean; + unique: boolean; + primaryKey: boolean; + autoIncrement: boolean; + default?: any; + comment?: string; +} + +/** + * Database table definition + */ +interface TableDefinition { + name: string; + columns: ColumnDefinition[]; + indexes: Array<{ + name: string; + columns: string[]; + unique: boolean; + }>; + foreignKeys: Array<{ + columnNames: string[]; + referencedTableName: string; + referencedColumnNames: string[]; + onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT'; + onUpdate?: 'CASCADE' | 'SET NULL' | 'RESTRICT'; + }>; +} + +/** + * Migration operation types + */ +type MigrationOperation = + | { type: 'CREATE_TABLE'; table: TableDefinition } + | { type: 'DROP_TABLE'; tableName: string } + | { type: 'ALTER_TABLE'; tableName: string; changes: TableChange[] } + | { type: 'CREATE_INDEX'; tableName: string; index: { name: string; columns: string[]; unique: boolean } } + | { type: 'DROP_INDEX'; indexName: string } + | { type: 'EXECUTE_SQL'; sql: string }; + +type TableChange = + | { type: 'ADD_COLUMN'; column: ColumnDefinition } + | { type: 'DROP_COLUMN'; columnName: string } + | { type: 'ALTER_COLUMN'; columnName: string; changes: Partial } + | { type: 'RENAME_COLUMN'; oldName: string; newName: string }; + +// ===== TYPE TESTING UTILITIES ===== + +/** + * Assert that two types are exactly equal + */ +type AssertEqual = T extends U ? U extends T ? true : false : false; + +/** + * Assert that T extends U + */ +type AssertExtends = T extends U ? true : false; + +/** + * Test type for compile-time type checking + */ +type TypeTest = T; + +// ===== EXPORT TYPES ===== + +export type { + // Core utility types + OptionalKeys, + RequiredKeys, + RequireOnly, + OptionalOnly, + DeepPartial, + DeepRequired, + NonFunctionProperties, + PrimitiveProperties, + + // Database-specific types + DatabaseManagedFields, + ReadonlyFields, + CreateInput, + UpdateInput, + PatchInput, + ReplaceInput, + UpsertInput, + FilterInput, + SortInput, + ProjectionInput, + + // Relation types + RelationFields, + RelationOptions, + WithRelations, + + // Validation types + InferZodSchema, + ValidationSchema, + Transform, + BiTransform, + + // Advanced conditional types + NullableFields, + OptionalNullableInput, + DeepMerge, + ArrayElement, + Lookup, + KeyValuePair, + + // Operation result types + OperationResult, + AsyncOperationResult, + PaginatedResult, + BulkOperationResult, + + // Query builder types + ComparisonOperator, + FieldFilter, + AdvancedFilterInput, + AggregationPipeline, + + // Entity-specific types + EntityFromRepository, + EntityConstructor, + EntityMetadata, + + // Migration types + ColumnDefinition, + TableDefinition, + MigrationOperation, + TableChange, + + // Type testing utilities + AssertEqual, + AssertExtends, + TypeTest +}; + +// ===== UTILITY FUNCTIONS ===== + +/** + * Type guard to check if a value is defined + */ +export function isDefined(value: T | undefined | null): value is T { + return value !== undefined && value !== null; +} + +/** + * Type guard to check if a value is a non-empty string + */ +export function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} + +/** + * Type guard to check if a value is a positive number + */ +export function isPositiveNumber(value: unknown): value is number { + return typeof value === 'number' && value > 0 && !isNaN(value); +} + +/** + * Create a type-safe object transformation function + */ +export function createTransform( + transformFn: (input: TInput) => TOutput +): Transform { + return transformFn; +} + +/** + * Create a bi-directional transformation + */ +export function createBiTransform( + toDto: Transform, + fromDto: Transform +): BiTransform { + return { toDto, fromDto }; +} + +/** + * Deep merge two objects with type safety + */ +export function deepMerge(target: T, source: U): DeepMerge { + const result = { ...target } as any; + + for (const key in source) { + if (source.hasOwnProperty(key)) { + const sourceValue = source[key]; + const targetValue = result[key]; + + if ( + typeof sourceValue === 'object' && + sourceValue !== null && + !Array.isArray(sourceValue) && + typeof targetValue === 'object' && + targetValue !== null && + !Array.isArray(targetValue) + ) { + result[key] = deepMerge(targetValue, sourceValue); + } else { + result[key] = sourceValue; + } + } + } + + return result; +} + +/** + * Pick only defined values from an object + */ +export function pickDefined>( + obj: T +): { [K in keyof T]: T[K] extends undefined ? never : T[K] } { + const result = {} as any; + + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key] !== undefined) { + result[key] = obj[key]; + } + } + + return result; +} + +/** + * Create a lookup table from an array of objects + */ +export function createLookup, K extends keyof T>( + array: readonly T[], + key: K +): Lookup { + const lookup = {} as any; + + for (const item of array) { + lookup[item[key]] = item; + } + + return lookup; +} + +// ===== TYPE EXAMPLES AND TESTS ===== + +// Example usage with compile-time type checking +type ExampleEntity = { + id: string; + name: string; + email?: string; + isActive: boolean; + createdAt: Date; + updatedAt: Date; + organization?: { + id: string; + name: string; + }; + roles: Array<{ + id: string; + name: string; + }>; +}; + +// Test create input type +type ExampleCreateInput = CreateInput; +// Should be: { name: string; email?: string; isActive: boolean; organization?: { id: string; name: string; }; roles: Array<{ id: string; name: string; }>; } + +// Test update input type +type ExampleUpdateInput = UpdateInput; +// Should be: { name?: string; email?: string; isActive?: boolean; updatedAt?: Date; organization?: { id: string; name: string; }; roles?: Array<{ id: string; name: string; }>; } + +// Test filter input type +type ExampleFilterInput = FilterInput; +// Should allow partial matching on all fields + +// Test relation options +type ExampleRelationOptions = RelationOptions; +// Should be: { organization?: boolean | RelationOptions<{ id: string; name: string; }>; roles?: boolean | RelationOptions<{ id: string; name: string; }>; } + +// Compile-time type tests +type _TestCreateInput = TypeTest>; +type _TestUpdateInput = TypeTest>; +type _TestFilterInput = TypeTest>; + +// Export test types for verification +export type { + ExampleEntity, + ExampleCreateInput, + ExampleUpdateInput, + ExampleFilterInput, + ExampleRelationOptions +}; \ No newline at end of file diff --git a/launchdarkly/react/dist/.tsbuildinfo b/launchdarkly/react/dist/.tsbuildinfo new file mode 100644 index 00000000..4a5a5417 --- /dev/null +++ b/launchdarkly/react/dist/.tsbuildinfo @@ -0,0 +1 @@ +{"fileNames":["../../../node_modules/typescript/lib/lib.es5.d.ts","../../../node_modules/typescript/lib/lib.es2015.d.ts","../../../node_modules/typescript/lib/lib.es2016.d.ts","../../../node_modules/typescript/lib/lib.es2017.d.ts","../../../node_modules/typescript/lib/lib.es2018.d.ts","../../../node_modules/typescript/lib/lib.es2019.d.ts","../../../node_modules/typescript/lib/lib.es2020.d.ts","../../../node_modules/typescript/lib/lib.dom.d.ts","../../../node_modules/typescript/lib/lib.dom.iterable.d.ts","../../../node_modules/typescript/lib/lib.es2015.core.d.ts","../../../node_modules/typescript/lib/lib.es2015.collection.d.ts","../../../node_modules/typescript/lib/lib.es2015.generator.d.ts","../../../node_modules/typescript/lib/lib.es2015.iterable.d.ts","../../../node_modules/typescript/lib/lib.es2015.promise.d.ts","../../../node_modules/typescript/lib/lib.es2015.proxy.d.ts","../../../node_modules/typescript/lib/lib.es2015.reflect.d.ts","../../../node_modules/typescript/lib/lib.es2015.symbol.d.ts","../../../node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts","../../../node_modules/typescript/lib/lib.es2016.array.include.d.ts","../../../node_modules/typescript/lib/lib.es2016.intl.d.ts","../../../node_modules/typescript/lib/lib.es2017.arraybuffer.d.ts","../../../node_modules/typescript/lib/lib.es2017.date.d.ts","../../../node_modules/typescript/lib/lib.es2017.object.d.ts","../../../node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts","../../../node_modules/typescript/lib/lib.es2017.string.d.ts","../../../node_modules/typescript/lib/lib.es2017.intl.d.ts","../../../node_modules/typescript/lib/lib.es2017.typedarrays.d.ts","../../../node_modules/typescript/lib/lib.es2018.asyncgenerator.d.ts","../../../node_modules/typescript/lib/lib.es2018.asynciterable.d.ts","../../../node_modules/typescript/lib/lib.es2018.intl.d.ts","../../../node_modules/typescript/lib/lib.es2018.promise.d.ts","../../../node_modules/typescript/lib/lib.es2018.regexp.d.ts","../../../node_modules/typescript/lib/lib.es2019.array.d.ts","../../../node_modules/typescript/lib/lib.es2019.object.d.ts","../../../node_modules/typescript/lib/lib.es2019.string.d.ts","../../../node_modules/typescript/lib/lib.es2019.symbol.d.ts","../../../node_modules/typescript/lib/lib.es2019.intl.d.ts","../../../node_modules/typescript/lib/lib.es2020.bigint.d.ts","../../../node_modules/typescript/lib/lib.es2020.date.d.ts","../../../node_modules/typescript/lib/lib.es2020.promise.d.ts","../../../node_modules/typescript/lib/lib.es2020.sharedmemory.d.ts","../../../node_modules/typescript/lib/lib.es2020.string.d.ts","../../../node_modules/typescript/lib/lib.es2020.symbol.wellknown.d.ts","../../../node_modules/typescript/lib/lib.es2020.intl.d.ts","../../../node_modules/typescript/lib/lib.es2020.number.d.ts","../../../node_modules/typescript/lib/lib.decorators.d.ts","../../../node_modules/typescript/lib/lib.decorators.legacy.d.ts","../../../node_modules/@types/react/global.d.ts","../../../node_modules/csstype/index.d.ts","../../../node_modules/@types/react/index.d.ts","../../../node_modules/@types/react/jsx-runtime.d.ts","../../../node_modules/launchdarkly-js-sdk-common/typings.d.ts","../../../node_modules/launchdarkly-js-client-sdk/typings.d.ts","../../../node_modules/zod/dist/types/v3/helpers/typeAliases.d.ts","../../../node_modules/zod/dist/types/v3/helpers/util.d.ts","../../../node_modules/zod/dist/types/v3/ZodError.d.ts","../../../node_modules/zod/dist/types/v3/locales/en.d.ts","../../../node_modules/zod/dist/types/v3/errors.d.ts","../../../node_modules/zod/dist/types/v3/helpers/parseUtil.d.ts","../../../node_modules/zod/dist/types/v3/helpers/enumUtil.d.ts","../../../node_modules/zod/dist/types/v3/helpers/errorUtil.d.ts","../../../node_modules/zod/dist/types/v3/helpers/partialUtil.d.ts","../../../node_modules/zod/dist/types/v3/standard-schema.d.ts","../../../node_modules/zod/dist/types/v3/types.d.ts","../../../node_modules/zod/dist/types/v3/external.d.ts","../../../node_modules/zod/dist/types/v3/index.d.ts","../../../node_modules/zod/dist/types/index.d.ts","../sample.tsx","../../../node_modules/@types/estree/index.d.ts","../../../node_modules/@types/json-schema/index.d.ts","../../../node_modules/@types/react-dom/index.d.ts"],"fileIdsList":[[50,51,53,67],[50],[48,49],[52],[66],[54,55,66],[56,57],[54,55,56,58,59,64],[55,56],[64],[65],[56],[54,55,56,59,60,61,62,63]],"fileInfos":[{"version":"69684132aeb9b5642cbcd9e22dff7818ff0ee1aa831728af0ecf97d3364d5546","affectsGlobalScope":true,"impliedFormat":1},{"version":"45b7ab580deca34ae9729e97c13cfd999df04416a79116c3bfb483804f85ded4","impliedFormat":1},{"version":"3facaf05f0c5fc569c5649dd359892c98a85557e3e0c847964caeb67076f4d75","impliedFormat":1},{"version":"e44bb8bbac7f10ecc786703fe0a6a4b952189f908707980ba8f3c8975a760962","impliedFormat":1},{"version":"5e1c4c362065a6b95ff952c0eab010f04dcd2c3494e813b493ecfd4fcb9fc0d8","impliedFormat":1},{"version":"68d73b4a11549f9c0b7d352d10e91e5dca8faa3322bfb77b661839c42b1ddec7","impliedFormat":1},{"version":"5efce4fc3c29ea84e8928f97adec086e3dc876365e0982cc8479a07954a3efd4","impliedFormat":1},{"version":"092c2bfe125ce69dbb1223c85d68d4d2397d7d8411867b5cc03cec902c233763","affectsGlobalScope":true,"impliedFormat":1},{"version":"07f073f19d67f74d732b1adea08e1dc66b1b58d77cb5b43931dee3d798a2fd53","affectsGlobalScope":true,"impliedFormat":1},{"version":"c57796738e7f83dbc4b8e65132f11a377649c00dd3eee333f672b8f0a6bea671","affectsGlobalScope":true,"impliedFormat":1},{"version":"dc2df20b1bcdc8c2d34af4926e2c3ab15ffe1160a63e58b7e09833f616efff44","affectsGlobalScope":true,"impliedFormat":1},{"version":"515d0b7b9bea2e31ea4ec968e9edd2c39d3eebf4a2d5cbd04e88639819ae3b71","affectsGlobalScope":true,"impliedFormat":1},{"version":"0559b1f683ac7505ae451f9a96ce4c3c92bdc71411651ca6ddb0e88baaaad6a3","affectsGlobalScope":true,"impliedFormat":1},{"version":"0dc1e7ceda9b8b9b455c3a2d67b0412feab00bd2f66656cd8850e8831b08b537","affectsGlobalScope":true,"impliedFormat":1},{"version":"ce691fb9e5c64efb9547083e4a34091bcbe5bdb41027e310ebba8f7d96a98671","affectsGlobalScope":true,"impliedFormat":1},{"version":"8d697a2a929a5fcb38b7a65594020fcef05ec1630804a33748829c5ff53640d0","affectsGlobalScope":true,"impliedFormat":1},{"version":"4ff2a353abf8a80ee399af572debb8faab2d33ad38c4b4474cff7f26e7653b8d","affectsGlobalScope":true,"impliedFormat":1},{"version":"936e80ad36a2ee83fc3caf008e7c4c5afe45b3cf3d5c24408f039c1d47bdc1df","affectsGlobalScope":true,"impliedFormat":1},{"version":"d15bea3d62cbbdb9797079416b8ac375ae99162a7fba5de2c6c505446486ac0a","affectsGlobalScope":true,"impliedFormat":1},{"version":"68d18b664c9d32a7336a70235958b8997ebc1c3b8505f4f1ae2b7e7753b87618","affectsGlobalScope":true,"impliedFormat":1},{"version":"eb3d66c8327153d8fa7dd03f9c58d351107fe824c79e9b56b462935176cdf12a","affectsGlobalScope":true,"impliedFormat":1},{"version":"38f0219c9e23c915ef9790ab1d680440d95419ad264816fa15009a8851e79119","affectsGlobalScope":true,"impliedFormat":1},{"version":"69ab18c3b76cd9b1be3d188eaf8bba06112ebbe2f47f6c322b5105a6fbc45a2e","affectsGlobalScope":true,"impliedFormat":1},{"version":"fef8cfad2e2dc5f5b3d97a6f4f2e92848eb1b88e897bb7318cef0e2820bceaab","affectsGlobalScope":true,"impliedFormat":1},{"version":"2f11ff796926e0832f9ae148008138ad583bd181899ab7dd768a2666700b1893","affectsGlobalScope":true,"impliedFormat":1},{"version":"4de680d5bb41c17f7f68e0419412ca23c98d5749dcaaea1896172f06435891fc","affectsGlobalScope":true,"impliedFormat":1},{"version":"954296b30da6d508a104a3a0b5d96b76495c709785c1d11610908e63481ee667","affectsGlobalScope":true,"impliedFormat":1},{"version":"ac9538681b19688c8eae65811b329d3744af679e0bdfa5d842d0e32524c73e1c","affectsGlobalScope":true,"impliedFormat":1},{"version":"0a969edff4bd52585473d24995c5ef223f6652d6ef46193309b3921d65dd4376","affectsGlobalScope":true,"impliedFormat":1},{"version":"9e9fbd7030c440b33d021da145d3232984c8bb7916f277e8ffd3dc2e3eae2bdb","affectsGlobalScope":true,"impliedFormat":1},{"version":"811ec78f7fefcabbda4bfa93b3eb67d9ae166ef95f9bff989d964061cbf81a0c","affectsGlobalScope":true,"impliedFormat":1},{"version":"717937616a17072082152a2ef351cb51f98802fb4b2fdabd32399843875974ca","affectsGlobalScope":true,"impliedFormat":1},{"version":"d7e7d9b7b50e5f22c915b525acc5a49a7a6584cf8f62d0569e557c5cfc4b2ac2","affectsGlobalScope":true,"impliedFormat":1},{"version":"71c37f4c9543f31dfced6c7840e068c5a5aacb7b89111a4364b1d5276b852557","affectsGlobalScope":true,"impliedFormat":1},{"version":"576711e016cf4f1804676043e6a0a5414252560eb57de9faceee34d79798c850","affectsGlobalScope":true,"impliedFormat":1},{"version":"89c1b1281ba7b8a96efc676b11b264de7a8374c5ea1e6617f11880a13fc56dc6","affectsGlobalScope":true,"impliedFormat":1},{"version":"74f7fa2d027d5b33eb0471c8e82a6c87216223181ec31247c357a3e8e2fddc5b","affectsGlobalScope":true,"impliedFormat":1},{"version":"d6d7ae4d1f1f3772e2a3cde568ed08991a8ae34a080ff1151af28b7f798e22ca","affectsGlobalScope":true,"impliedFormat":1},{"version":"063600664504610fe3e99b717a1223f8b1900087fab0b4cad1496a114744f8df","affectsGlobalScope":true,"impliedFormat":1},{"version":"934019d7e3c81950f9a8426d093458b65d5aff2c7c1511233c0fd5b941e608ab","affectsGlobalScope":true,"impliedFormat":1},{"version":"52ada8e0b6e0482b728070b7639ee42e83a9b1c22d205992756fe020fd9f4a47","affectsGlobalScope":true,"impliedFormat":1},{"version":"3bdefe1bfd4d6dee0e26f928f93ccc128f1b64d5d501ff4a8cf3c6371200e5e6","affectsGlobalScope":true,"impliedFormat":1},{"version":"59fb2c069260b4ba00b5643b907ef5d5341b167e7d1dbf58dfd895658bda2867","affectsGlobalScope":true,"impliedFormat":1},{"version":"639e512c0dfc3fad96a84caad71b8834d66329a1f28dc95e3946c9b58176c73a","affectsGlobalScope":true,"impliedFormat":1},{"version":"368af93f74c9c932edd84c58883e736c9e3d53cec1fe24c0b0ff451f529ceab1","affectsGlobalScope":true,"impliedFormat":1},{"version":"8e7f8264d0fb4c5339605a15daadb037bf238c10b654bb3eee14208f860a32ea","affectsGlobalScope":true,"impliedFormat":1},{"version":"782dec38049b92d4e85c1585fbea5474a219c6984a35b004963b00beb1aab538","affectsGlobalScope":true,"impliedFormat":1},{"version":"170d4db14678c68178ee8a3d5a990d5afb759ecb6ec44dbd885c50f6da6204f6","affectsGlobalScope":true,"impliedFormat":1},{"version":"8a8eb4ebffd85e589a1cc7c178e291626c359543403d58c9cd22b81fab5b1fb9","impliedFormat":1},{"version":"d4d7d3f832882a4b2d611a7eaaa80c780c3342b5732090130fa9af4a40bd051e","impliedFormat":1},{"version":"42c169fb8c2d42f4f668c624a9a11e719d5d07dacbebb63cbcf7ef365b0a75b3","impliedFormat":1},{"version":"d11dce7174230cebdd56adc17a1631b7da169236a59c9af4d19205c3b3b7b72c","impliedFormat":1},{"version":"682cb078e636dd42e52e4273c9dad33105a1947f335f2c629cdb30585437a9ac","impliedFormat":1},{"version":"d3cfde44f8089768ebb08098c96d01ca260b88bccf238d55eee93f1c620ff5a5","impliedFormat":1},{"version":"293eadad9dead44c6fd1db6de552663c33f215c55a1bfa2802a1bceed88ff0ec","impliedFormat":1},{"version":"54f6ec6ea75acea6eb23635617252d249145edbc7bcd9d53f2d70280d2aef953","impliedFormat":1},{"version":"c25ce98cca43a3bfa885862044be0d59557be4ecd06989b2001a83dcf69620fd","impliedFormat":1},{"version":"8e71e53b02c152a38af6aec45e288cc65bede077b92b9b43b3cb54a37978bb33","impliedFormat":1},{"version":"754a9396b14ca3a4241591afb4edc644b293ccc8a3397f49be4dfd520c08acb3","impliedFormat":1},{"version":"f672c876c1a04a223cf2023b3d91e8a52bb1544c576b81bf64a8fec82be9969c","impliedFormat":1},{"version":"e4b03ddcf8563b1c0aee782a185286ed85a255ce8a30df8453aade2188bbc904","impliedFormat":1},{"version":"de2316e90fc6d379d83002f04ad9698bc1e5285b4d52779778f454dd12ce9f44","impliedFormat":1},{"version":"25b3f581e12ede11e5739f57a86e8668fbc0124f6649506def306cad2c59d262","impliedFormat":1},{"version":"2da997a01a6aa5c5c09de5d28f0f4407b597c5e1aecfd32f1815809c532650a2","impliedFormat":1},{"version":"5d26d2e47e2352def36f89a3e8bf8581da22b7f857e07ef3114cd52cf4813445","impliedFormat":1},{"version":"3db2efd285e7328d8014b54a7fce3f4861ebcdc655df40517092ed0050983617","impliedFormat":1},{"version":"d5d39a24c759df40480a4bfc0daffd364489702fdbcbdfc1711cde34f8739995","impliedFormat":1},{"version":"a6fd425ccc3580add39051642c3bf2c70eee9ff9f9ae84560bc0a8d91fcd3948","signature":"14a9ea2bf9c4164db8921f5187e68368e0a6f2a0ca7a9de1533f46da37f139ca"},{"version":"151ff381ef9ff8da2da9b9663ebf657eac35c4c9a19183420c05728f31a6761d","impliedFormat":1},{"version":"f3d8c757e148ad968f0d98697987db363070abada5f503da3c06aefd9d4248c1","impliedFormat":1},{"version":"a0acca63c9e39580f32a10945df231815f0fe554c074da96ba6564010ffbd2d8","impliedFormat":1}],"root":[68],"options":{"allowJs":true,"allowSyntheticDefaultImports":true,"composite":true,"declaration":true,"declarationMap":true,"esModuleInterop":true,"jsx":4,"module":99,"noFallthroughCasesInSwitch":true,"noImplicitAny":true,"noImplicitReturns":true,"outDir":"./","rootDir":"..","skipLibCheck":true,"sourceMap":true,"strict":true,"strictFunctionTypes":true,"target":7,"tsBuildInfoFile":"./.tsbuildinfo"},"referencedMap":[[68,1],[71,2],[50,3],[51,2],[53,4],[67,5],[56,6],[58,7],[65,8],[59,9],[62,10],[66,11],[57,12],[64,13]],"semanticDiagnosticsPerFile":[[68,[{"start":7124,"length":15,"messageText":"Cannot redeclare exported variable 'ValidationError'.","category":1,"code":2323},{"start":9336,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":9347,"length":6,"messageText":"Namespace 'API' has no exported member 'LDUser'.","category":1,"code":2694},{"start":9615,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":9627,"length":11,"messageText":"Namespace 'API' has no exported member 'ThemeConfig'.","category":1,"code":2694},{"start":9856,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":9868,"length":11,"messageText":"Namespace 'API' has no exported member 'ThemeStyles'.","category":1,"code":2694},{"start":10088,"length":6,"messageText":"Namespace 'API' has no exported member 'LDUser'.","category":1,"code":2694},{"start":10104,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":10322,"length":11,"messageText":"Namespace 'API' has no exported member 'ThemeConfig'.","category":1,"code":2694},{"start":10348,"length":11,"messageText":"Namespace 'API' has no exported member 'ThemeStyles'.","category":1,"code":2694},{"start":10369,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":10741,"length":10,"messageText":"Namespace 'API' has no exported member 'ThemeFlags'.","category":1,"code":2694},{"start":10761,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":11153,"length":4,"messageText":"Cannot find name 'User'.","category":1,"code":2304},{"start":11168,"length":5,"messageText":"Cannot find name 'Theme'. Did you mean 'ThemeId'?","category":1,"code":2552,"canonicalHead":{"code":2304,"messageText":"Cannot find name 'Theme'."}},{"start":11196,"length":4,"messageText":"Cannot find name 'User'.","category":1,"code":2304},{"start":11217,"length":5,"messageText":"Cannot find name 'Theme'. Did you mean 'ThemeId'?","category":1,"code":2552,"canonicalHead":{"code":2304,"messageText":"Cannot find name 'Theme'."}},{"start":11234,"length":5,"messageText":"Cannot find name 'Theme'. Did you mean 'ThemeId'?","category":1,"code":2552,"canonicalHead":{"code":2304,"messageText":"Cannot find name 'Theme'."}},{"start":11284,"length":5,"messageText":"Cannot find name 'Theme'. Did you mean 'ThemeId'?","category":1,"code":2552,"canonicalHead":{"code":2304,"messageText":"Cannot find name 'Theme'."}},{"start":11389,"length":14,"messageText":"Cannot find name 'ComponentState'. Did you mean 'ComponentName'?","category":1,"code":2552,"canonicalHead":{"code":2304,"messageText":"Cannot find name 'ComponentState'."}},{"start":11450,"length":5,"messageText":"Cannot find name 'Theme'. Did you mean 'ThemeId'?","category":1,"code":2552,"canonicalHead":{"code":2304,"messageText":"Cannot find name 'Theme'."}},{"start":11770,"length":11,"messageText":"Namespace 'API' has no exported member 'ThemeConfig'.","category":1,"code":2694},{"start":12067,"length":11,"messageText":"Namespace 'API' has no exported member 'ThemeConfig'.","category":1,"code":2694},{"start":12402,"length":11,"messageText":"Namespace 'API' has no exported member 'ThemeConfig'.","category":1,"code":2694},{"start":12714,"length":13,"messageText":"Namespace 'Domain' has no exported member 'IThemeService'.","category":1,"code":2694},{"start":12974,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":12996,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":13168,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":13196,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":13220,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":13445,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":13770,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":14093,"length":16,"messageText":"Namespace 'Domain' has no exported member 'IHeaderComponent'.","category":1,"code":2694},{"start":14206,"length":13,"messageText":"Namespace 'Domain' has no exported member 'IThemeService'.","category":1,"code":2694},{"start":14263,"length":13,"messageText":"Namespace 'Domain' has no exported member 'IThemeService'.","category":1,"code":2694},{"start":14357,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":14525,"length":14,"messageText":"Namespace 'Domain' has no exported member 'ComponentState'.","category":1,"code":2694},{"start":14709,"length":14,"messageText":"Namespace 'Domain' has no exported member 'ComponentState'.","category":1,"code":2694},{"start":15963,"length":16,"messageText":"Namespace 'Domain' has no exported member 'IHeaderComponent'.","category":1,"code":2694},{"start":16469,"length":14,"messageText":"Namespace 'Domain' has no exported member 'ComponentState'.","category":1,"code":2694},{"start":16811,"length":14,"messageText":"Cannot redeclare exported variable 'validateLDUser'.","category":1,"code":2323},{"start":16857,"length":6,"messageText":"Namespace 'API' has no exported member 'LDUser'.","category":1,"code":2694},{"start":17136,"length":18,"messageText":"Cannot redeclare exported variable 'validateDomainUser'.","category":1,"code":2323},{"start":17189,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":17480,"length":11,"messageText":"Cannot redeclare exported variable 'parseLDUser'.","category":1,"code":2323},{"start":17515,"length":6,"messageText":"Namespace 'API' has no exported member 'LDUser'.","category":1,"code":2694},{"start":17737,"length":15,"messageText":"Cannot redeclare exported variable 'parseDomainUser'.","category":1,"code":2323},{"start":17779,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":18008,"length":19,"messageText":"Cannot redeclare exported variable 'parseComponentState'.","category":1,"code":2323},{"start":18054,"length":14,"messageText":"Namespace 'Domain' has no exported member 'ComponentState'.","category":1,"code":2694},{"start":18365,"length":21,"messageText":"Cannot redeclare exported variable 'createValidatedLDUser'.","category":1,"code":2323},{"start":18409,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":18420,"length":6,"messageText":"Namespace 'API' has no exported member 'LDUser'.","category":1,"code":2694},{"start":18554,"length":17,"messageText":"Cannot redeclare exported variable 'createDomainTheme'.","category":1,"code":2323},{"start":18663,"length":5,"messageText":"Namespace 'Domain' has no exported member 'Theme'.","category":1,"code":2694},{"start":19060,"length":4,"messageText":"Namespace 'Domain' has no exported member 'User'.","category":1,"code":2694},{"start":19571,"length":6,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":19579,"length":3,"messageText":"Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.","category":1,"code":1205},{"start":19817,"length":14,"messageText":"Cannot redeclare exported variable 'validateLDUser'.","category":1,"code":2323},{"start":19817,"length":14,"messageText":"Export declaration conflicts with exported declaration of 'validateLDUser'.","category":1,"code":2484},{"start":19835,"length":18,"messageText":"Cannot redeclare exported variable 'validateDomainUser'.","category":1,"code":2323},{"start":19835,"length":18,"messageText":"Export declaration conflicts with exported declaration of 'validateDomainUser'.","category":1,"code":2484},{"start":19856,"length":21,"messageText":"Cannot redeclare exported variable 'createValidatedLDUser'.","category":1,"code":2323},{"start":19856,"length":21,"messageText":"Export declaration conflicts with exported declaration of 'createValidatedLDUser'.","category":1,"code":2484},{"start":19924,"length":11,"messageText":"Cannot redeclare exported variable 'parseLDUser'.","category":1,"code":2323},{"start":19924,"length":11,"messageText":"Export declaration conflicts with exported declaration of 'parseLDUser'.","category":1,"code":2484},{"start":19938,"length":15,"messageText":"Cannot redeclare exported variable 'parseDomainUser'.","category":1,"code":2323},{"start":19938,"length":15,"messageText":"Export declaration conflicts with exported declaration of 'parseDomainUser'.","category":1,"code":2484},{"start":19956,"length":19,"messageText":"Cannot redeclare exported variable 'parseComponentState'.","category":1,"code":2323},{"start":19956,"length":19,"messageText":"Export declaration conflicts with exported declaration of 'parseComponentState'.","category":1,"code":2484},{"start":20040,"length":15,"messageText":"Cannot redeclare exported variable 'ValidationError'.","category":1,"code":2323},{"start":20040,"length":15,"messageText":"Export declaration conflicts with exported declaration of 'ValidationError'.","category":1,"code":2484},{"start":20104,"length":17,"messageText":"Cannot redeclare exported variable 'createDomainTheme'.","category":1,"code":2323},{"start":20104,"length":17,"messageText":"Export declaration conflicts with exported declaration of 'createDomainTheme'.","category":1,"code":2484}]]],"latestChangedDtsFile":"./sample.d.ts","version":"5.8.3"} \ No newline at end of file diff --git a/launchdarkly/react/dist/sample.d.ts b/launchdarkly/react/dist/sample.d.ts new file mode 100644 index 00000000..73dd8f37 --- /dev/null +++ b/launchdarkly/react/dist/sample.d.ts @@ -0,0 +1,280 @@ +import React from "react"; +import { z } from "zod"; +type BrandedString = string & { + readonly __brand: T; +}; +type UserKey = BrandedString<'UserKey'>; +type UserEmail = BrandedString<'UserEmail'>; +type ComponentId = BrandedString<'ComponentId'>; +type ClientSideId = BrandedString<'ClientSideId'>; +type FeatureFlagKey = BrandedString<'FeatureFlagKey'>; +type ThemeId = BrandedString<'ThemeId'>; +type RouteId = BrandedString<'RouteId'>; +type EventId = BrandedString<'EventId'>; +type ComponentName = BrandedString<'ComponentName'>; +type StyleToken = BrandedString<'StyleToken'>; +type LocalStorageKey = BrandedString<'LocalStorageKey'>; +declare const createUserKey: (value: string) => UserKey | null; +declare const createUserEmail: (value: string) => UserEmail | null; +declare const createComponentId: (value: string) => ComponentId | null; +declare const createClientSideId: (value: string) => ClientSideId | null; +declare const createFeatureFlagKey: (value: string) => FeatureFlagKey | null; +declare const createThemeId: (value: string) => ThemeId | null; +declare const createRouteId: (value: string) => RouteId | null; +declare const createEventId: (value: string) => EventId | null; +declare const createComponentName: (value: string) => ComponentName | null; +declare const createStyleToken: (value: string) => StyleToken | null; +declare const createLocalStorageKey: (value: string) => LocalStorageKey | null; +declare namespace ValidationSchemas { + const UserKeySchema: z.ZodEffects; + const UserEmailSchema: z.ZodUnion<[z.ZodString, z.ZodUndefined]>; + const ComponentIdSchema: z.ZodEffects; + const ClientSideIdSchema: z.ZodEffects; + const FeatureFlagKeySchema: z.ZodEffects; + const DomainUserSchema: z.ZodObject<{ + id: z.ZodString; + name: z.ZodOptional; + email: z.ZodUnion<[z.ZodString, z.ZodUndefined]>; + preferences: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + id: string; + name?: string | undefined; + email?: string | undefined; + preferences?: Record | undefined; + }, { + id: string; + name?: string | undefined; + email?: string | undefined; + preferences?: Record | undefined; + }>; + const DomainThemeSchema: z.ZodObject<{ + darkMode: z.ZodBoolean; + highContrast: z.ZodBoolean; + primaryColor: z.ZodString; + backgroundColor: z.ZodString; + }, "strip", z.ZodTypeAny, { + darkMode: boolean; + highContrast: boolean; + primaryColor: string; + backgroundColor: string; + }, { + darkMode: boolean; + highContrast: boolean; + primaryColor: string; + backgroundColor: string; + }>; + const ComponentStateSchema: z.ZodObject<{ + isLoading: z.ZodBoolean; + theme: z.ZodObject<{ + darkMode: z.ZodBoolean; + highContrast: z.ZodBoolean; + primaryColor: z.ZodString; + backgroundColor: z.ZodString; + }, "strip", z.ZodTypeAny, { + darkMode: boolean; + highContrast: boolean; + primaryColor: string; + backgroundColor: string; + }, { + darkMode: boolean; + highContrast: boolean; + primaryColor: string; + backgroundColor: string; + }>; + user: z.ZodOptional; + email: z.ZodUnion<[z.ZodString, z.ZodUndefined]>; + preferences: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + id: string; + name?: string | undefined; + email?: string | undefined; + preferences?: Record | undefined; + }, { + id: string; + name?: string | undefined; + email?: string | undefined; + preferences?: Record | undefined; + }>>; + errors: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + isLoading: boolean; + theme: { + darkMode: boolean; + highContrast: boolean; + primaryColor: string; + backgroundColor: string; + }; + user?: { + id: string; + name?: string | undefined; + email?: string | undefined; + preferences?: Record | undefined; + } | undefined; + errors?: string[] | undefined; + }, { + isLoading: boolean; + theme: { + darkMode: boolean; + highContrast: boolean; + primaryColor: string; + backgroundColor: string; + }; + user?: { + id: string; + name?: string | undefined; + email?: string | undefined; + preferences?: Record | undefined; + } | undefined; + errors?: string[] | undefined; + }>; + const UserIdentitySchema: z.ZodObject<{ + key: z.ZodString; + kind: z.ZodString; + }, "strip", z.ZodTypeAny, { + key: string; + kind: string; + }, { + key: string; + kind: string; + }>; + const UserProfileSchema: z.ZodObject<{ + name: z.ZodOptional; + email: z.ZodUnion<[z.ZodString, z.ZodUndefined]>; + }, "strip", z.ZodTypeAny, { + name?: string | undefined; + email?: string | undefined; + }, { + name?: string | undefined; + email?: string | undefined; + }>; + const UserMetadataSchema: z.ZodObject<{ + custom: z.ZodOptional>>; + }, "strip", z.ZodTypeAny, { + custom?: Record | undefined; + }, { + custom?: Record | undefined; + }>; + const LDUserSchema: z.ZodObject<{ + key: z.ZodString; + kind: z.ZodString; + } & { + name: z.ZodOptional; + email: z.ZodUnion<[z.ZodString, z.ZodUndefined]>; + } & { + custom: z.ZodOptional>>; + } & { + __userBrand: z.ZodLiteral<"LDUser">; + }, "strip", z.ZodTypeAny, { + key: string; + kind: string; + __userBrand: "LDUser"; + name?: string | undefined; + email?: string | undefined; + custom?: Record | undefined; + }, { + key: string; + kind: string; + __userBrand: "LDUser"; + name?: string | undefined; + email?: string | undefined; + custom?: Record | undefined; + }>; + const ThemeFlagsSchema: z.ZodObject<{ + isDarkModeEnabled: z.ZodBoolean; + enableHighContrast: z.ZodBoolean; + }, "strip", z.ZodTypeAny, { + isDarkModeEnabled: boolean; + enableHighContrast: boolean; + }, { + isDarkModeEnabled: boolean; + enableHighContrast: boolean; + }>; + const ThemeStylesSchema: z.ZodObject<{ + backgroundColor: z.ZodString; + color: z.ZodString; + }, "strip", z.ZodTypeAny, { + backgroundColor: string; + color: string; + }, { + backgroundColor: string; + color: string; + }>; + const ThemeConfigSchema: z.ZodObject<{ + isDarkModeEnabled: z.ZodBoolean; + enableHighContrast: z.ZodBoolean; + } & { + __themeBrand: z.ZodLiteral<"ThemeConfig">; + }, "strip", z.ZodTypeAny, { + isDarkModeEnabled: boolean; + enableHighContrast: boolean; + __themeBrand: "ThemeConfig"; + }, { + isDarkModeEnabled: boolean; + enableHighContrast: boolean; + __themeBrand: "ThemeConfig"; + }>; +} +export declare class ValidationError extends Error { + readonly validationErrors: z.ZodError; + readonly context: string; + constructor(zodError: z.ZodError, context?: string); + getFormattedErrors(): Record; +} +declare namespace Domain { +} +declare namespace API { +} +declare namespace Transform { + function domainUserToLDUser(domainUser: Domain.User): API.LDUser; + function domainThemeToThemeConfig(domainTheme: Domain.Theme): API.ThemeConfig; + function domainThemeToThemeStyles(domainTheme: Domain.Theme): API.ThemeStyles; + function ldUserToDomainUser(ldUser: API.LDUser): Domain.User; + function themeConfigToDomainTheme(themeConfig: API.ThemeConfig, styles?: API.ThemeStyles): Domain.Theme; + function themeFlagsToDomainTheme(themeFlags: API.ThemeFlags): Domain.Theme; +} +declare namespace Domain { +} +declare class LaunchDarklyThemeService { + private client; + constructor(client: any); + getThemeConfig(): API.ThemeConfig; + validateThemeConfig(config: unknown): config is API.ThemeConfig; + parseThemeConfig(config: unknown): API.ThemeConfig; +} +declare class ThemeService implements Domain.IThemeService { + readonly __themeServiceBrand: "ThemeService"; + private apiService; + constructor(apiService: LaunchDarklyThemeService); + getTheme(user: Domain.User): Promise; + updateTheme(user: Domain.User, theme: Partial): Promise; + validateTheme(theme: unknown): theme is Domain.Theme; + parseTheme(theme: unknown): Domain.Theme; +} +declare class HeaderComponent implements Domain.IHeaderComponent { + readonly __componentBrand: "HeaderComponent"; + private themeService; + constructor(themeService: Domain.IThemeService); + getThemeStyles(theme: Domain.Theme): { + backgroundColor: string; + color: string; + }; + render(state: Domain.ComponentState): React.ReactElement; + private renderContent; +} +declare const createHeaderComponent: (clientSideId: string) => Domain.IHeaderComponent; +declare const Header: () => React.ReactElement; +export declare const validateLDUser: (data: unknown) => data is API.LDUser; +export declare const validateDomainUser: (data: unknown) => data is Domain.User; +export declare const parseLDUser: (data: unknown) => API.LDUser; +export declare const parseDomainUser: (data: unknown) => Domain.User; +export declare const parseComponentState: (data: unknown) => Domain.ComponentState; +export declare const createValidatedLDUser: (domainUser: Domain.User) => API.LDUser; +export declare const createDomainTheme: (isDark: boolean | null | undefined, isHighContrast: boolean | null | undefined) => Domain.Theme; +export type { UserKey, UserEmail, ComponentId, ClientSideId, FeatureFlagKey, ThemeId, RouteId, EventId, ComponentName, StyleToken, LocalStorageKey, }; +export { Domain, API, Transform }; +export { ThemeService, HeaderComponent, LaunchDarklyThemeService, }; +export { validateLDUser, validateDomainUser, createValidatedLDUser, parseLDUser, parseDomainUser, parseComponentState, ValidationSchemas, ValidationError, createHeaderComponent, createDomainTheme, createUserKey, createUserEmail, createComponentId, createClientSideId, createFeatureFlagKey, createThemeId, createRouteId, createEventId, createComponentName, createStyleToken, createLocalStorageKey }; +export default Header; +//# sourceMappingURL=sample.d.ts.map \ No newline at end of file diff --git a/launchdarkly/react/dist/sample.d.ts.map b/launchdarkly/react/dist/sample.d.ts.map new file mode 100644 index 00000000..61e2c770 --- /dev/null +++ b/launchdarkly/react/dist/sample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sample.d.ts","sourceRoot":"","sources":["../sample.tsx"],"names":[],"mappings":"AAgBA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,KAAK,aAAa,CAAC,CAAC,SAAS,MAAM,IAAI,MAAM,GAAG;IAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAA;CAAE,CAAC;AACxE,KAAK,OAAO,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC;AACxC,KAAK,SAAS,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;AAC5C,KAAK,WAAW,GAAG,aAAa,CAAC,aAAa,CAAC,CAAC;AAEhD,KAAK,YAAY,GAAG,aAAa,CAAC,cAAc,CAAC,CAAC;AAClD,KAAK,cAAc,GAAG,aAAa,CAAC,gBAAgB,CAAC,CAAC;AACtD,KAAK,OAAO,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC;AACxC,KAAK,OAAO,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC;AACxC,KAAK,OAAO,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC;AAExC,KAAK,aAAa,GAAG,aAAa,CAAC,eAAe,CAAC,CAAC;AACpD,KAAK,UAAU,GAAG,aAAa,CAAC,YAAY,CAAC,CAAC;AAC9C,KAAK,eAAe,GAAG,aAAa,CAAC,iBAAiB,CAAC,CAAC;AAExD,QAAA,MAAM,aAAa,GAAI,OAAO,MAAM,KAAG,OAAO,GAAG,IAUhD,CAAC;AAEF,QAAA,MAAM,eAAe,GAAI,OAAO,MAAM,KAAG,SAAS,GAAG,IAUpD,CAAC;AAEF,QAAA,MAAM,iBAAiB,GAAI,OAAO,MAAM,KAAG,WAAW,GAAG,IAUxD,CAAC;AAGF,QAAA,MA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B,GAAI,MAAM,OAAO,KAAG,IAAI,IAAI,MAAM,CAAC,IAUjE,CAAC;AAEF,eAAO,MAAM,WAAW,GAAI,MAAM,OAAO,KAAG,GAAG,CAAC,MAS/C,CAAC;AAEF,eAAO,MAAM,eAAe,GAAI,MAAM,OAAO,KAAG,MAAM,CAAC,IAStD,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAAI,MAAM,OAAO,KAAG,MAAM,CAAC,cAS1D,CAAC;AAGF,eAAO,MAAM,qBAAqB,GAAI,YAAY,MAAM,CAAC,IAAI,KAAG,GAAG,CAAC,MAEnE,CAAC;AAGF,eAAO,MAAM,iBAAiB,GAAI,QAAQ,OAAO,GAAG,IAAI,GAAG,SAAS,EAAE,gBAAgB,OAAO,GAAG,IAAI,GAAG,SAAS,KAAG,MAAM,CAAC,KAKxH,CAAC;AAgBH,YAAY,EAEX,OAAO,EACP,SAAS,EACT,WAAW,EAEX,YAAY,EACZ,cAAc,EACd,OAAO,EACP,OAAO,EACP,OAAO,EAEP,aAAa,EACb,UAAU,EACV,eAAe,GACf,CAAC;AAGF,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC;AAGlC,OAAO,EAEN,YAAY,EACZ,eAAe,EACf,wBAAwB,GACxB,CAAC;AAGF,OAAO,EAEN,cAAc,EACd,kBAAkB,EAClB,qBAAqB,EAErB,WAAW,EACX,eAAe,EACf,mBAAmB,EAEnB,iBAAiB,EAEjB,eAAe,EAEf,qBAAqB,EACrB,iBAAiB,EAEjB,aAAa,EACb,eAAe,EACf,iBAAiB,EAEjB,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,aAAa,EACb,mBAAmB,EACnB,gBAAgB,EAChB,qBAAqB,EACrB,CAAC;AAEF,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/launchdarkly/react/dist/sample.js b/launchdarkly/react/dist/sample.js new file mode 100644 index 00000000..fd35a2b0 --- /dev/null +++ b/launchdarkly/react/dist/sample.js @@ -0,0 +1,448 @@ +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +import { z } from "zod"; +const createUserKey = (value) => { + try { + ValidationSchemas.UserKeySchema.parse(value); + return value; + } + catch (error) { + if (error instanceof z.ZodError) { + console.warn('UserKey creation failed:', new ValidationError(error, 'UserKey creation').message); + } + return null; + } +}; +const createUserEmail = (value) => { + try { + ValidationSchemas.UserEmailSchema.parse(value); + return value; + } + catch (error) { + if (error instanceof z.ZodError) { + console.warn('UserEmail creation failed:', new ValidationError(error, 'UserEmail creation').message); + } + return null; + } +}; +const createComponentId = (value) => { + try { + ValidationSchemas.ComponentIdSchema.parse(value); + return value; + } + catch (error) { + if (error instanceof z.ZodError) { + console.warn('ComponentId creation failed:', new ValidationError(error, 'ComponentId creation').message); + } + return null; + } +}; +// Additional constructor functions for React-specific branded types +const createClientSideId = (value) => { + try { + ValidationSchemas.ClientSideIdSchema.parse(value); + return value; + } + catch (error) { + if (error instanceof z.ZodError) { + console.warn('ClientSideId creation failed:', new ValidationError(error, 'ClientSideId creation').message); + } + return null; + } +}; +const createFeatureFlagKey = (value) => { + try { + ValidationSchemas.FeatureFlagKeySchema.parse(value); + return value; + } + catch (error) { + if (error instanceof z.ZodError) { + console.warn('FeatureFlagKey creation failed:', new ValidationError(error, 'FeatureFlagKey creation').message); + } + return null; + } +}; +const createThemeId = (value) => { + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value : null; +}; +const createRouteId = (value) => { + return value && value.length > 0 && /^[a-zA-Z0-9-_/]+$/.test(value) ? value : null; +}; +const createEventId = (value) => { + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value : null; +}; +const createComponentName = (value) => { + return value && value.length > 0 && /^[A-Z][a-zA-Z0-9]*$/.test(value) ? value : null; +}; +const createStyleToken = (value) => { + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value : null; +}; +const createLocalStorageKey = (value) => { + return value && value.length > 0 && /^[a-zA-Z0-9-_.]+$/.test(value) ? value : null; +}; +// === ZOD VALIDATION SCHEMAS - Runtime Type Validation === +var ValidationSchemas; +(function (ValidationSchemas) { + // Branded type validation schemas + ValidationSchemas.UserKeySchema = z.string().min(1, "User key cannot be empty").refine((val) => /^[a-zA-Z0-9-_]+$/.test(val), "User key must contain only alphanumeric characters, hyphens, and underscores"); + ValidationSchemas.UserEmailSchema = z.string().email("Invalid email format").or(z.undefined()); + ValidationSchemas.ComponentIdSchema = z.string().min(1, "Component ID cannot be empty").refine((val) => /^[a-zA-Z0-9-_]+$/.test(val), "Component ID must contain only alphanumeric characters, hyphens, and underscores"); + ValidationSchemas.ClientSideIdSchema = z.string().min(1, "Client side ID cannot be empty").refine((val) => !val.startsWith('sdk-'), "Client side ID cannot start with 'sdk-'"); + ValidationSchemas.FeatureFlagKeySchema = z.string().min(1, "Feature flag key cannot be empty").refine((val) => /^[a-z0-9-]+$/.test(val), "Feature flag key must contain only lowercase letters, numbers, and hyphens"); + // Domain validation schemas + ValidationSchemas.DomainUserSchema = z.object({ + id: z.string().min(1, "User ID is required"), + name: z.string().optional(), + email: ValidationSchemas.UserEmailSchema, + preferences: z.record(z.unknown()).optional() + }); + ValidationSchemas.DomainThemeSchema = z.object({ + darkMode: z.boolean(), + highContrast: z.boolean(), + primaryColor: z.string().regex(/^#[0-9A-Fa-f]{6}$/, "Primary color must be a valid hex color"), + backgroundColor: z.string().regex(/^#[0-9A-Fa-f]{6}$/, "Background color must be a valid hex color") + }); + ValidationSchemas.ComponentStateSchema = z.object({ + isLoading: z.boolean(), + theme: ValidationSchemas.DomainThemeSchema, + user: ValidationSchemas.DomainUserSchema.optional(), + errors: z.array(z.string()).optional() + }); + // API validation schemas + ValidationSchemas.UserIdentitySchema = z.object({ + key: z.string().min(1, "User key is required"), + kind: z.string().min(1, "User kind is required") + }); + ValidationSchemas.UserProfileSchema = z.object({ + name: z.string().optional(), + email: ValidationSchemas.UserEmailSchema + }); + ValidationSchemas.UserMetadataSchema = z.object({ + custom: z.record(z.union([z.string(), z.number(), z.boolean()])).optional() + }); + ValidationSchemas.LDUserSchema = ValidationSchemas.UserIdentitySchema.merge(ValidationSchemas.UserProfileSchema).merge(ValidationSchemas.UserMetadataSchema).extend({ + __userBrand: z.literal('LDUser') + }); + ValidationSchemas.ThemeFlagsSchema = z.object({ + isDarkModeEnabled: z.boolean(), + enableHighContrast: z.boolean() + }); + ValidationSchemas.ThemeStylesSchema = z.object({ + backgroundColor: z.string().regex(/^#[0-9A-Fa-f]{6}$/, "Background color must be a valid hex color"), + color: z.string().regex(/^#[0-9A-Fa-f]{6}$/, "Color must be a valid hex color") + }); + ValidationSchemas.ThemeConfigSchema = ValidationSchemas.ThemeFlagsSchema.extend({ + __themeBrand: z.literal('ThemeConfig') + }); +})(ValidationSchemas || (ValidationSchemas = {})); +// === VALIDATION ERROR HANDLING === +export class ValidationError extends Error { + constructor(zodError, context = "Validation") { + const errorMessage = `${context} failed: ${zodError.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`; + super(errorMessage); + this.name = "ValidationError"; + this.validationErrors = zodError; + this.context = context; + } + getFormattedErrors() { + const errors = {}; + for (const error of this.validationErrors.errors) { + const path = error.path.join('.') || 'root'; + if (!errors[path]) { + errors[path] = []; + } + errors[path].push(error.message); + } + return errors; + } +} +// === TRANSFORMATION FUNCTIONS - React Component Transformations === +var Transform; +(function (Transform) { + // Domain to API transformations + function domainUserToLDUser(domainUser) { + return { + key: domainUser.id, + name: domainUser.name, + email: domainUser.email, + kind: 'user', + custom: { + ...domainUser.preferences + }, + __userBrand: 'LDUser' + }; + } + Transform.domainUserToLDUser = domainUserToLDUser; + function domainThemeToThemeConfig(domainTheme) { + return { + isDarkModeEnabled: domainTheme.darkMode, + enableHighContrast: domainTheme.highContrast, + __themeBrand: 'ThemeConfig' + }; + } + Transform.domainThemeToThemeConfig = domainThemeToThemeConfig; + function domainThemeToThemeStyles(domainTheme) { + return { + backgroundColor: domainTheme.backgroundColor, + color: domainTheme.darkMode ? '#ffffff' : '#000000' + }; + } + Transform.domainThemeToThemeStyles = domainThemeToThemeStyles; + // API to Domain transformations + function ldUserToDomainUser(ldUser) { + return { + id: ldUser.key, + name: ldUser.name, + email: ldUser.email, + preferences: { + kind: ldUser.kind, + ...ldUser.custom + } + }; + } + Transform.ldUserToDomainUser = ldUserToDomainUser; + function themeConfigToDomainTheme(themeConfig, styles) { + return { + darkMode: themeConfig.isDarkModeEnabled, + highContrast: themeConfig.enableHighContrast, + primaryColor: styles?.color || (themeConfig.isDarkModeEnabled ? '#ffffff' : '#000000'), + backgroundColor: styles?.backgroundColor || (themeConfig.isDarkModeEnabled ? '#1a1a1a' : '#ffffff') + }; + } + Transform.themeConfigToDomainTheme = themeConfigToDomainTheme; + function themeFlagsToDomainTheme(themeFlags) { + return { + darkMode: themeFlags.isDarkModeEnabled, + highContrast: themeFlags.enableHighContrast, + primaryColor: themeFlags.isDarkModeEnabled ? '#ffffff' : '#000000', + backgroundColor: themeFlags.isDarkModeEnabled ? '#1a1a1a' : '#ffffff' + }; + } + Transform.themeFlagsToDomainTheme = themeFlagsToDomainTheme; +})(Transform || (Transform = {})); +// === API SERVICE IMPLEMENTATIONS - LaunchDarkly API Bridge === +class LaunchDarklyThemeService { + constructor(client) { + this.client = client; + } + getThemeConfig() { + return { + isDarkModeEnabled: this.client.variation("is-dark-mode-enabled", false) ?? false, + enableHighContrast: this.client.variation("enable-high-contrast", true) ?? true, + __themeBrand: 'ThemeConfig', + }; + } + validateThemeConfig(config) { + try { + ValidationSchemas.ThemeConfigSchema.parse(config); + return true; + } + catch (error) { + if (error instanceof z.ZodError) { + console.warn('Theme config validation failed:', new ValidationError(error, 'ThemeConfig validation').message); + } + return false; + } + } + parseThemeConfig(config) { + try { + return ValidationSchemas.ThemeConfigSchema.parse(config); + } + catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'ThemeConfig parsing'); + } + throw error; + } + } +} +// === DOMAIN SERVICE IMPLEMENTATIONS === +class ThemeService { + constructor(apiService) { + this.__themeServiceBrand = 'ThemeService'; + this.apiService = apiService; + } + async getTheme(user) { + const apiThemeConfig = this.apiService.getThemeConfig(); + return Transform.themeConfigToDomainTheme(apiThemeConfig); + } + async updateTheme(user, theme) { + // In a real implementation, this would call an API to update the theme + const currentTheme = await this.getTheme(user); + return { ...currentTheme, ...theme }; + } + validateTheme(theme) { + try { + ValidationSchemas.DomainThemeSchema.parse(theme); + return true; + } + catch (error) { + if (error instanceof z.ZodError) { + console.warn('Domain theme validation failed:', new ValidationError(error, 'Domain theme validation').message); + } + return false; + } + } + parseTheme(theme) { + try { + return ValidationSchemas.DomainThemeSchema.parse(theme); + } + catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'Domain theme parsing'); + } + throw error; + } + } +} +// Header component with explicit interface conformance +class HeaderComponent { + constructor(themeService) { + this.__componentBrand = 'HeaderComponent'; + this.themeService = themeService; + } + getThemeStyles(theme) { + return { + backgroundColor: theme.backgroundColor, + color: theme.primaryColor, + }; + } + render(state) { + const themeStyles = this.getThemeStyles(state.theme); + return this.renderContent(state, themeStyles); + } + renderContent(state, themeStyles) { + const { theme, user, isLoading, errors } = state; + if (isLoading) { + return _jsx("div", { style: themeStyles, children: "Loading..." }); + } + if (errors && errors.length > 0) { + return (_jsxs("div", { style: { ...themeStyles, color: 'red' }, children: ["Error: ", errors.join(', ')] })); + } + return (_jsxs("div", { style: themeStyles, children: [user && _jsxs("p", { children: ["Welcome, ", user.name || user.id, "!"] }), theme.darkMode ? (_jsxs("div", { children: ["Dark Mode is enabled.", _jsx("p", { children: "Welcome to a darker, more soothing interface!" }), theme.highContrast ? (_jsx("div", { children: "High Contrast mode is enabled, enhancing visual accessibility." })) : (_jsx("div", { children: "High Contrast mode is disabled." }))] })) : (_jsxs("div", { children: ["Dark Mode is disabled.", _jsx("p", { children: "Enjoy the default light theme." }), theme.highContrast ? (_jsx("div", { children: "High Contrast mode is enabled, enhancing visual accessibility." })) : (_jsx("div", { children: "High Contrast mode is disabled." }))] }))] })); + } +} +// === FACTORY FUNCTIONS - Dependency Injection === +const createHeaderComponent = (clientSideId) => { + // Create API client and services + const dummyClient = { variation: (key, defaultValue) => defaultValue }; // Mock for example + const apiService = new LaunchDarklyThemeService(dummyClient); + const themeService = new ThemeService(apiService); + return new HeaderComponent(themeService); +}; +const Header = () => { + const headerComponent = createHeaderComponent("YOUR_CLIENT_SIDE_ID"); + // Create a sample component state + const sampleState = { + isLoading: false, + theme: { + darkMode: false, + highContrast: false, + primaryColor: '#000000', + backgroundColor: '#ffffff' + }, + user: { + id: 'user123', + name: 'Sample User', + email: 'user@example.com' + } + }; + return headerComponent.render(sampleState); +}; +// === VALIDATION FUNCTIONS === +export const validateLDUser = (data) => { + try { + ValidationSchemas.LDUserSchema.parse(data); + return true; + } + catch (error) { + if (error instanceof z.ZodError) { + console.warn('LDUser validation failed:', new ValidationError(error, 'LDUser validation').message); + } + return false; + } +}; +export const validateDomainUser = (data) => { + try { + ValidationSchemas.DomainUserSchema.parse(data); + return true; + } + catch (error) { + if (error instanceof z.ZodError) { + console.warn('Domain user validation failed:', new ValidationError(error, 'Domain user validation').message); + } + return false; + } +}; +export const parseLDUser = (data) => { + try { + return ValidationSchemas.LDUserSchema.parse(data); + } + catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'LDUser parsing'); + } + throw error; + } +}; +export const parseDomainUser = (data) => { + try { + return ValidationSchemas.DomainUserSchema.parse(data); + } + catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'Domain user parsing'); + } + throw error; + } +}; +export const parseComponentState = (data) => { + try { + return ValidationSchemas.ComponentStateSchema.parse(data); + } + catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'Component state parsing'); + } + throw error; + } +}; +// Utility function to create validated LDUser from domain user +export const createValidatedLDUser = (domainUser) => { + return Transform.domainUserToLDUser(domainUser); +}; +// Utility function with explicit types and validation +export const createDomainTheme = (isDark, isHighContrast) => ({ + darkMode: isDark ?? false, + highContrast: isHighContrast ?? true, + primaryColor: (isDark ?? false) ? '#ffffff' : '#000000', + backgroundColor: (isDark ?? false) ? '#1a1a1a' : '#ffffff', +}); +// Utility function to create a domain user with validation +const createDomainUser = (id, name, email) => { + if (!id) { + return null; + } + return { + id, + name: name || undefined, + email: email || undefined, + }; +}; +// Export namespaces for domain and API types +export { Transform }; +// Export classes and services +export { +// Component classes +ThemeService, HeaderComponent, LaunchDarklyThemeService, }; +// Export utility functions and factories +export { +// Validation schemas +ValidationSchemas, +// Factory functions +createHeaderComponent, +// Branded type constructors +createUserKey, createUserEmail, createComponentId, +// Additional constructor functions +createClientSideId, createFeatureFlagKey, createThemeId, createRouteId, createEventId, createComponentName, createStyleToken, createLocalStorageKey }; +export default Header; +//# sourceMappingURL=sample.js.map \ No newline at end of file diff --git a/launchdarkly/react/dist/sample.js.map b/launchdarkly/react/dist/sample.js.map new file mode 100644 index 00000000..834a444d --- /dev/null +++ b/launchdarkly/react/dist/sample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sample.js","sourceRoot":"","sources":["../sample.tsx"],"names":[],"mappings":";AAkBA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAkBxB,MAAM,aAAa,GAAG,CAAC,KAAa,EAAkB,EAAE;IACvD,IAAI,CAAC;QACJ,iBAAiB,CAAC,aAAa,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC7C,OAAO,KAAgB,CAAC;IACzB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,KAAK,YAAY,CAAC,CAAC,QAAQ,EAAE,CAAC;YACjC,OAAO,CAAC,IAAI,CAAC,0BAA0B,EAAE,IAAI,eAAe,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC,OAAO,CAAC,CAAC;QAClG,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC;AACF,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG,CAAC,KAAa,EAAoB,EAAE;IAC3D,I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AM,CAAC"} \ No newline at end of file diff --git a/launchdarkly/react/sample.tsx b/launchdarkly/react/sample.tsx index ab8c13c4..623c4302 100644 --- a/launchdarkly/react/sample.tsx +++ b/launchdarkly/react/sample.tsx @@ -14,63 +14,688 @@ * limitations under the License. */ -import { LDClient } from "launchdarkly-js-client-sdk"; +import React from "react"; +import { initialize } from "launchdarkly-js-client-sdk"; +import { z } from "zod"; -const Header = () => { - const ldClient = LDClient.initialize("YOUR_CLIENT_SIDE_ID", { - key: "user_key", - name: "User Name", - }); - const user = LDClient.User({ - key: "user_key", - name: "User Name", - }); - const isDarkModeEnabled = ldClient.variation( - "is-dark-mode-enabled", - user, - false, +// Branded types for stronger component boundary typing +type BrandedString = string & { readonly __brand: T }; +type UserKey = BrandedString<'UserKey'>; +type UserEmail = BrandedString<'UserEmail'>; +type ComponentId = BrandedString<'ComponentId'>; +// Additional security-critical branded types for React components +type ClientSideId = BrandedString<'ClientSideId'>; +type FeatureFlagKey = BrandedString<'FeatureFlagKey'>; +type ThemeId = BrandedString<'ThemeId'>; +type RouteId = BrandedString<'RouteId'>; +type EventId = BrandedString<'EventId'>; +// Component-specific branded types +type ComponentName = BrandedString<'ComponentName'>; +type StyleToken = BrandedString<'StyleToken'>; +type LocalStorageKey = BrandedString<'LocalStorageKey'>; + +const createUserKey = (value: string): UserKey | null => { + try { + ValidationSchemas.UserKeySchema.parse(value); + return value as UserKey; + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('UserKey creation failed:', new ValidationError(error, 'UserKey creation').message); + } + return null; + } +}; + +const createUserEmail = (value: string): UserEmail | null => { + try { + ValidationSchemas.UserEmailSchema.parse(value); + return value as UserEmail; + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('UserEmail creation failed:', new ValidationError(error, 'UserEmail creation').message); + } + return null; + } +}; + +const createComponentId = (value: string): ComponentId | null => { + try { + ValidationSchemas.ComponentIdSchema.parse(value); + return value as ComponentId; + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('ComponentId creation failed:', new ValidationError(error, 'ComponentId creation').message); + } + return null; + } +}; + +// Additional constructor functions for React-specific branded types +const createClientSideId = (value: string): ClientSideId | null => { + try { + ValidationSchemas.ClientSideIdSchema.parse(value); + return value as ClientSideId; + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('ClientSideId creation failed:', new ValidationError(error, 'ClientSideId creation').message); + } + return null; + } +}; + +const createFeatureFlagKey = (value: string): FeatureFlagKey | null => { + try { + ValidationSchemas.FeatureFlagKeySchema.parse(value); + return value as FeatureFlagKey; + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('FeatureFlagKey creation failed:', new ValidationError(error, 'FeatureFlagKey creation').message); + } + return null; + } +}; + +const createThemeId = (value: string): ThemeId | null => { + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value as ThemeId : null; +}; + +const createRouteId = (value: string): RouteId | null => { + return value && value.length > 0 && /^[a-zA-Z0-9-_/]+$/.test(value) ? value as RouteId : null; +}; + +const createEventId = (value: string): EventId | null => { + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value as EventId : null; +}; + +const createComponentName = (value: string): ComponentName | null => { + return value && value.length > 0 && /^[A-Z][a-zA-Z0-9]*$/.test(value) ? value as ComponentName : null; +}; + +const createStyleToken = (value: string): StyleToken | null => { + return value && value.length > 0 && /^[a-zA-Z0-9-_]+$/.test(value) ? value as StyleToken : null; +}; + +const createLocalStorageKey = (value: string): LocalStorageKey | null => { + return value && value.length > 0 && /^[a-zA-Z0-9-_.]+$/.test(value) ? value as LocalStorageKey : null; +}; + +// === ZOD VALIDATION SCHEMAS - Runtime Type Validation === +namespace ValidationSchemas { + // Branded type validation schemas + export const UserKeySchema = z.string().min(1, "User key cannot be empty").refine( + (val) => /^[a-zA-Z0-9-_]+$/.test(val), + "User key must contain only alphanumeric characters, hyphens, and underscores" + ); + + export const UserEmailSchema = z.string().email("Invalid email format").or(z.undefined()); + + export const ComponentIdSchema = z.string().min(1, "Component ID cannot be empty").refine( + (val) => /^[a-zA-Z0-9-_]+$/.test(val), + "Component ID must contain only alphanumeric characters, hyphens, and underscores" ); - const enableHighContrast = ldClient.variation( - "enable-high-contrast", - user, - true, + + export const ClientSideIdSchema = z.string().min(1, "Client side ID cannot be empty").refine( + (val) => !val.startsWith('sdk-'), + "Client side ID cannot start with 'sdk-'" + ); + + export const FeatureFlagKeySchema = z.string().min(1, "Feature flag key cannot be empty").refine( + (val) => /^[a-z0-9-]+$/.test(val), + "Feature flag key must contain only lowercase letters, numbers, and hyphens" ); - return ( -
`${e.path.join('.')}: ${e.message}`).join(', ')}`; + super(errorMessage); + this.name = "ValidationError"; + this.validationErrors = zodError; + this.context = context; + } + + public getFormattedErrors(): Record { + const errors: Record = {}; + for (const error of this.validationErrors.errors) { + const path = error.path.join('.') || 'root'; + if (!errors[path]) { + errors[path] = []; } - > - {isDarkModeEnabled ? ( -
- Dark Mode is enabled. -

Welcome to a darker, more soothing interface!

- {enableHighContrast ? ( -
- High Contrast mode is enabled, enhancing visual accessibility. -
- ) : ( -
High Contrast mode is disabled.
- )} -
- ) : ( -
- Dark Mode is disabled. -

Enjoy the default light theme.

- {enableHighContrast ? ( -
- High Contrast mode is enabled, enhancing visual accessibility. -
- ) : ( -
High Contrast mode is disabled.
- )} + errors[path].push(error.message); + } + return errors; + } +} + +// === DOMAIN TYPES - React Component Domain Models === +namespace Domain { + interface User { + id: string; + name?: string; + email?: string; + preferences?: Record; + } + + interface Theme { + darkMode: boolean; + highContrast: boolean; + primaryColor: string; + backgroundColor: string; + } + + interface ComponentState { + isLoading: boolean; + theme: Theme; + user?: User; + errors?: string[]; + } +} + +// === API TYPES - LaunchDarkly React API contracts === +namespace API { + interface UserIdentity { + key: string; + kind: string; + } + + interface UserProfile { + name?: string; + email?: string; + } + + interface UserMetadata { + custom?: Record; + } + + // Type definitions for LaunchDarkly React integration with explicit interface conformance + interface LDUser extends UserIdentity, UserProfile, UserMetadata { + // Explicit interface marker for compile-time verification + readonly __userBrand: 'LDUser'; + } + + // Interface segregation for theme concerns + interface ThemeFlags { + isDarkModeEnabled: boolean; + enableHighContrast: boolean; + } + + interface ThemeStyles { + backgroundColor: string; + color: string; + } + + interface ThemeConfig extends ThemeFlags { + // Explicit interface marker + readonly __themeBrand: 'ThemeConfig'; + } +} + +// === TRANSFORMATION FUNCTIONS - React Component Transformations === +namespace Transform { + // Domain to API transformations + export function domainUserToLDUser(domainUser: Domain.User): API.LDUser { + return { + key: domainUser.id, + name: domainUser.name, + email: domainUser.email, + kind: 'user', + custom: { + ...domainUser.preferences + }, + __userBrand: 'LDUser' as const + }; + } + + export function domainThemeToThemeConfig(domainTheme: Domain.Theme): API.ThemeConfig { + return { + isDarkModeEnabled: domainTheme.darkMode, + enableHighContrast: domainTheme.highContrast, + __themeBrand: 'ThemeConfig' as const + }; + } + + export function domainThemeToThemeStyles(domainTheme: Domain.Theme): API.ThemeStyles { + return { + backgroundColor: domainTheme.backgroundColor, + color: domainTheme.darkMode ? '#ffffff' : '#000000' + }; + } + + // API to Domain transformations + export function ldUserToDomainUser(ldUser: API.LDUser): Domain.User { + return { + id: ldUser.key, + name: ldUser.name, + email: ldUser.email, + preferences: { + kind: ldUser.kind, + ...ldUser.custom + } + }; + } + + export function themeConfigToDomainTheme(themeConfig: API.ThemeConfig, styles?: API.ThemeStyles): Domain.Theme { + return { + darkMode: themeConfig.isDarkModeEnabled, + highContrast: themeConfig.enableHighContrast, + primaryColor: styles?.color || (themeConfig.isDarkModeEnabled ? '#ffffff' : '#000000'), + backgroundColor: styles?.backgroundColor || (themeConfig.isDarkModeEnabled ? '#1a1a1a' : '#ffffff') + }; + } + + export function themeFlagsToDomainTheme(themeFlags: API.ThemeFlags): Domain.Theme { + return { + darkMode: themeFlags.isDarkModeEnabled, + highContrast: themeFlags.enableHighContrast, + primaryColor: themeFlags.isDarkModeEnabled ? '#ffffff' : '#000000', + backgroundColor: themeFlags.isDarkModeEnabled ? '#1a1a1a' : '#ffffff' + }; + } +} + +// === DOMAIN SERVICE INTERFACES - React Component Services === +namespace Domain { + interface IThemeService { + getTheme(user: User): Promise; + updateTheme(user: User, theme: Partial): Promise; + validateTheme(theme: unknown): theme is Theme; + readonly __themeServiceBrand: 'ThemeService'; + } + + interface IHeaderComponent { + render(state: ComponentState): React.ReactElement; + getThemeStyles(theme: Theme): { backgroundColor: string; color: string }; + readonly __componentBrand: 'HeaderComponent'; + } +} + +// === API SERVICE IMPLEMENTATIONS - LaunchDarkly API Bridge === +class LaunchDarklyThemeService { + private client: any; + + public constructor(client: any) { + this.client = client; + } + + public getThemeConfig(): API.ThemeConfig { + return { + isDarkModeEnabled: this.client.variation("is-dark-mode-enabled", false) ?? false, + enableHighContrast: this.client.variation("enable-high-contrast", true) ?? true, + __themeBrand: 'ThemeConfig' as const, + }; + } + + validateThemeConfig(config: unknown): config is API.ThemeConfig { + try { + ValidationSchemas.ThemeConfigSchema.parse(config); + return true; + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('Theme config validation failed:', new ValidationError(error, 'ThemeConfig validation').message); + } + return false; + } + } + + parseThemeConfig(config: unknown): API.ThemeConfig { + try { + return ValidationSchemas.ThemeConfigSchema.parse(config); + } catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'ThemeConfig parsing'); + } + throw error; + } + } +} + +// === DOMAIN SERVICE IMPLEMENTATIONS === +class ThemeService implements Domain.IThemeService { + public readonly __themeServiceBrand = 'ThemeService' as const; + private apiService: LaunchDarklyThemeService; + + public constructor(apiService: LaunchDarklyThemeService) { + this.apiService = apiService; + } + + public async getTheme(user: Domain.User): Promise { + const apiThemeConfig = this.apiService.getThemeConfig(); + return Transform.themeConfigToDomainTheme(apiThemeConfig); + } + + public async updateTheme(user: Domain.User, theme: Partial): Promise { + // In a real implementation, this would call an API to update the theme + const currentTheme = await this.getTheme(user); + return { ...currentTheme, ...theme }; + } + + validateTheme(theme: unknown): theme is Domain.Theme { + try { + ValidationSchemas.DomainThemeSchema.parse(theme); + return true; + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('Domain theme validation failed:', new ValidationError(error, 'Domain theme validation').message); + } + return false; + } + } + + parseTheme(theme: unknown): Domain.Theme { + try { + return ValidationSchemas.DomainThemeSchema.parse(theme); + } catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'Domain theme parsing'); + } + throw error; + } + } +} + +// Header component with explicit interface conformance +class HeaderComponent implements Domain.IHeaderComponent { + public readonly __componentBrand = 'HeaderComponent' as const; + private themeService: Domain.IThemeService; + + public constructor(themeService: Domain.IThemeService) { + this.themeService = themeService; + } + + public getThemeStyles(theme: Domain.Theme): { backgroundColor: string; color: string } { + return { + backgroundColor: theme.backgroundColor, + color: theme.primaryColor, + }; + } + + render(state: Domain.ComponentState): React.ReactElement { + const themeStyles = this.getThemeStyles(state.theme); + return this.renderContent(state, themeStyles); + } + + private renderContent(state: Domain.ComponentState, themeStyles: { backgroundColor: string; color: string }): React.ReactElement { + const { theme, user, isLoading, errors } = state; + + if (isLoading) { + return
Loading...
; + } + + if (errors && errors.length > 0) { + return ( +
+ Error: {errors.join(', ')}
- )} -
- ); + ); + } + + return ( +
+ {user &&

Welcome, {user.name || user.id}!

} + {theme.darkMode ? ( +
+ Dark Mode is enabled. +

Welcome to a darker, more soothing interface!

+ {theme.highContrast ? ( +
+ High Contrast mode is enabled, enhancing visual accessibility. +
+ ) : ( +
High Contrast mode is disabled.
+ )} +
+ ) : ( +
+ Dark Mode is disabled. +

Enjoy the default light theme.

+ {theme.highContrast ? ( +
+ High Contrast mode is enabled, enhancing visual accessibility. +
+ ) : ( +
High Contrast mode is disabled.
+ )} +
+ )} +
+ ); + } +} + +// === FACTORY FUNCTIONS - Dependency Injection === +const createHeaderComponent = (clientSideId: string): Domain.IHeaderComponent => { + // Create API client and services + const dummyClient = { variation: (key: string, defaultValue: any) => defaultValue }; // Mock for example + const apiService = new LaunchDarklyThemeService(dummyClient); + const themeService = new ThemeService(apiService); + + return new HeaderComponent(themeService); +}; + +const Header = (): React.ReactElement => { + const headerComponent = createHeaderComponent("YOUR_CLIENT_SIDE_ID"); + + // Create a sample component state + const sampleState: Domain.ComponentState = { + isLoading: false, + theme: { + darkMode: false, + highContrast: false, + primaryColor: '#000000', + backgroundColor: '#ffffff' + }, + user: { + id: 'user123', + name: 'Sample User', + email: 'user@example.com' + } + }; + + return headerComponent.render(sampleState); +}; + +// === VALIDATION FUNCTIONS === +export const validateLDUser = (data: unknown): data is API.LDUser => { + try { + ValidationSchemas.LDUserSchema.parse(data); + return true; + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('LDUser validation failed:', new ValidationError(error, 'LDUser validation').message); + } + return false; + } +}; + +export const validateDomainUser = (data: unknown): data is Domain.User => { + try { + ValidationSchemas.DomainUserSchema.parse(data); + return true; + } catch (error) { + if (error instanceof z.ZodError) { + console.warn('Domain user validation failed:', new ValidationError(error, 'Domain user validation').message); + } + return false; + } +}; + +export const parseLDUser = (data: unknown): API.LDUser => { + try { + return ValidationSchemas.LDUserSchema.parse(data); + } catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'LDUser parsing'); + } + throw error; + } +}; + +export const parseDomainUser = (data: unknown): Domain.User => { + try { + return ValidationSchemas.DomainUserSchema.parse(data); + } catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'Domain user parsing'); + } + throw error; + } +}; + +export const parseComponentState = (data: unknown): Domain.ComponentState => { + try { + return ValidationSchemas.ComponentStateSchema.parse(data); + } catch (error) { + if (error instanceof z.ZodError) { + throw new ValidationError(error, 'Component state parsing'); + } + throw error; + } +}; + +// Utility function to create validated LDUser from domain user +export const createValidatedLDUser = (domainUser: Domain.User): API.LDUser => { + return Transform.domainUserToLDUser(domainUser); +}; + +// Utility function with explicit types and validation +export const createDomainTheme = (isDark: boolean | null | undefined, isHighContrast: boolean | null | undefined): Domain.Theme => ({ + darkMode: isDark ?? false, + highContrast: isHighContrast ?? true, + primaryColor: (isDark ?? false) ? '#ffffff' : '#000000', + backgroundColor: (isDark ?? false) ? '#1a1a1a' : '#ffffff', +}); + +// Utility function to create a domain user with validation +const createDomainUser = (id: string | null | undefined, name?: string | null | undefined, email?: string | null | undefined): Domain.User | null => { + if (!id) { + return null; + } + return { + id, + name: name || undefined, + email: email || undefined, + }; +}; + +// === EXPORTS === +// Export types for use in other components +export type { + // Branded types + UserKey, + UserEmail, + ComponentId, + // Additional security-critical branded types + ClientSideId, + FeatureFlagKey, + ThemeId, + RouteId, + EventId, + // Component-specific branded types + ComponentName, + StyleToken, + LocalStorageKey, +}; + +// Export namespaces for domain and API types +export { Domain, API, Transform }; + +// Export classes and services +export { + // Component classes + ThemeService, + HeaderComponent, + LaunchDarklyThemeService, +}; + +// Export utility functions and factories +export { + // Validation functions (type guards) + validateLDUser, + validateDomainUser, + createValidatedLDUser, + // Parsing functions (with error throwing) + parseLDUser, + parseDomainUser, + parseComponentState, + // Validation schemas + ValidationSchemas, + // Error handling + ValidationError, + // Factory functions + createHeaderComponent, + createDomainTheme, + // Branded type constructors + createUserKey, + createUserEmail, + createComponentId, + // Additional constructor functions + createClientSideId, + createFeatureFlagKey, + createThemeId, + createRouteId, + createEventId, + createComponentName, + createStyleToken, + createLocalStorageKey }; export default Header; diff --git a/launchdarkly/react/tsconfig.json b/launchdarkly/react/tsconfig.json new file mode 100644 index 00000000..953a3c12 --- /dev/null +++ b/launchdarkly/react/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./", + "tsBuildInfoFile": "./dist/.tsbuildinfo", + "jsx": "react-jsx" + }, + "include": [ + "*.ts", + "*.tsx" + ], + "references": [] +} \ No newline at end of file diff --git a/launchdarkly/tsconfig.json b/launchdarkly/tsconfig.json new file mode 100644 index 00000000..8da68a7c --- /dev/null +++ b/launchdarkly/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./", + "tsBuildInfoFile": "./dist/.tsbuildinfo" + }, + "files": [], + "references": [ + { "path": "./react" }, + { "path": "./node" } + ] +} \ No newline at end of file diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 120000 index 00000000..cf767603 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/node_modules/.bin/eslint b/node_modules/.bin/eslint new file mode 120000 index 00000000..810e4bcb --- /dev/null +++ b/node_modules/.bin/eslint @@ -0,0 +1 @@ +../eslint/bin/eslint.js \ No newline at end of file diff --git a/node_modules/.bin/js-yaml b/node_modules/.bin/js-yaml new file mode 120000 index 00000000..9dbd010d --- /dev/null +++ b/node_modules/.bin/js-yaml @@ -0,0 +1 @@ +../js-yaml/bin/js-yaml.js \ No newline at end of file diff --git a/node_modules/.bin/node-which b/node_modules/.bin/node-which new file mode 120000 index 00000000..6f8415ec --- /dev/null +++ b/node_modules/.bin/node-which @@ -0,0 +1 @@ +../which/bin/node-which \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 00000000..5aaadf42 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/.bin/tsc b/node_modules/.bin/tsc new file mode 120000 index 00000000..0863208a --- /dev/null +++ b/node_modules/.bin/tsc @@ -0,0 +1 @@ +../typescript/bin/tsc \ No newline at end of file diff --git a/node_modules/.bin/tsserver b/node_modules/.bin/tsserver new file mode 120000 index 00000000..f8f8f1a0 --- /dev/null +++ b/node_modules/.bin/tsserver @@ -0,0 +1 @@ +../typescript/bin/tsserver \ No newline at end of file diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid new file mode 120000 index 00000000..588f70ec --- /dev/null +++ b/node_modules/.bin/uuid @@ -0,0 +1 @@ +../uuid/dist/bin/uuid \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 00000000..6f44f81f --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1826 @@ +{ + "name": "01976b50-0a9e-7772-9ce0-c405c55467f0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@eslint-community/eslint-utils": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz", + "integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.1", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.1.tgz", + "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.20.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.20.1.tgz", + "integrity": "sha512-OL0RJzC/CBzli0DrrR31qzj6d6i6Mm3HByuhflhl4LOBiWxN+3i6/t/ZQQNii4tjksXi8r2CRW1wMpWA2ULUEw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.6", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-array/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.2.3.tgz", + "integrity": "sha512-u180qk2Um1le4yf0ruXH3PYFeEZeYC3p/4wCTKrr2U1CmGdzGi3KtY0nuPDH48UJxlKCC5RDzbcbh4X0XlqgHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.14.0.tgz", + "integrity": "sha512-qIbV0/JZr7iSDjqAc60IqbLdsj9GDt16xQtWD+B78d/HAlvysGdZZ6rpJHGAc2T0FQx1X6thsSPdnoiGKdNtdg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.1.tgz", + "integrity": "sha512-gtF186CXhIl1p4pJNGZw8Yc6RlshoePRvE0X91oPGb3vZ8pM3qOS9W9NGPat9LziaBV7XrJWGylNQXkGcnM3IQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/js": { + "version": "9.29.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.29.0.tgz", + "integrity": "sha512-3PIF4cBw/y+1u2EazflInpV+lYsSG0aByVIQzAgb1m1MhHFSbqTyNqtBKHgWf/9Ykud+DhILS9EGkmekVhbKoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.6.tgz", + "integrity": "sha512-RBMg5FRL0I0gs51M/guSAj5/e14VQ4tpZnQNWwuDT66P14I43ItmPfIZRhO9fUVIPOAQXU47atlywZ/czoqFPA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.3.2.tgz", + "integrity": "sha512-4SaFZCNfJqvk/kenHpI8xvN42DMaoycy4PzKc5otHxRswww1kAt82OlBuwRVLofCACCTZEcla2Ydxv8scMXaTg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.15.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit/node_modules/@eslint/core": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.15.0.tgz", + "integrity": "sha512-b7ePw78tEWWkpgZCDYkbqDOP8dmM6qe+AOC6iuJqlq1R/0ahMAeH3qynpnqKFGkMltrp44ohV4ubGyvLX28tzw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.6", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.6.tgz", + "integrity": "sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.3.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node/node_modules/@humanwhocodes/retry": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.1.tgz", + "integrity": "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.1.8", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.8.tgz", + "integrity": "sha512-AwAfQ2Wa5bCx9WP8nZL2uMZWod7J7/JSplxbTmBQ5ms6QpqNYm672H0Vu9ZVKVngQ+ii4R/byguVEUZQyeg44g==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.0.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.1.6", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.1.6.tgz", + "integrity": "sha512-4hOiT/dwO8Ko0gV1m/TJZYk3y0KBnY9vzDh7W+DH17b2HFSOGgdj33dhihPeuy3l0q23+4e+hoXHV6hCC4dCXw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.0.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.34.0.tgz", + "integrity": "sha512-QXwAlHlbcAwNlEEMKQS2RCgJsgXrTJdjXT08xEgbPFa2yYQgVjBymxP5DrfrE7X7iodSzd9qBUHUycdyVJTW1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.10.0", + "@typescript-eslint/scope-manager": "8.34.0", + "@typescript-eslint/type-utils": "8.34.0", + "@typescript-eslint/utils": "8.34.0", + "@typescript-eslint/visitor-keys": "8.34.0", + "graphemer": "^1.4.0", + "ignore": "^7.0.0", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.34.0", + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.34.0.tgz", + "integrity": "sha512-vxXJV1hVFx3IXz/oy2sICsJukaBrtDEQSBiV48/YIV5KWjX1dO+bcIr/kCPrW6weKXvsaGKFNlwH0v2eYdRRbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.34.0", + "@typescript-eslint/types": "8.34.0", + "@typescript-eslint/typescript-estree": "8.34.0", + "@typescript-eslint/visitor-keys": "8.34.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.34.0.tgz", + "integrity": "sha512-iEgDALRf970/B2YExmtPMPF54NenZUf4xpL3wsCRx/lgjz6ul/l13R81ozP/ZNuXfnLCS+oPmG7JIxfdNYKELw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.34.0", + "@typescript-eslint/types": "^8.34.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.34.0.tgz", + "integrity": "sha512-9Ac0X8WiLykl0aj1oYQNcLZjHgBojT6cW68yAgZ19letYu+Hxd0rE0veI1XznSSst1X5lwnxhPbVdwjDRIomRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.34.0", + "@typescript-eslint/visitor-keys": "8.34.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.34.0.tgz", + "integrity": "sha512-+W9VYHKFIzA5cBeooqQxqNriAP0QeQ7xTiDuIOr71hzgffm3EL2hxwWBIIj4GuofIbKxGNarpKqIq6Q6YrShOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.34.0.tgz", + "integrity": "sha512-n7zSmOcUVhcRYC75W2pnPpbO1iwhJY3NLoHEtbJwJSNlVAZuwqu05zY3f3s2SDWWDSo9FdN5szqc73DCtDObAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/typescript-estree": "8.34.0", + "@typescript-eslint/utils": "8.34.0", + "debug": "^4.3.4", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.34.0.tgz", + "integrity": "sha512-9V24k/paICYPniajHfJ4cuAWETnt7Ssy+R0Rbcqo5sSFr3QEZ/8TSoUi9XeXVBGXCaLtwTOKSLGcInCAvyZeMA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.34.0.tgz", + "integrity": "sha512-rOi4KZxI7E0+BMqG7emPSK1bB4RICCpF7QD3KCLXn9ZvWoESsOMlHyZPAHyG04ujVplPaHbmEvs34m+wjgtVtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.34.0", + "@typescript-eslint/tsconfig-utils": "8.34.0", + "@typescript-eslint/types": "8.34.0", + "@typescript-eslint/visitor-keys": "8.34.0", + "debug": "^4.3.4", + "fast-glob": "^3.3.2", + "is-glob": "^4.0.3", + "minimatch": "^9.0.4", + "semver": "^7.6.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.34.0.tgz", + "integrity": "sha512-8L4tWatGchV9A1cKbjaavS6mwYwp39jql8xUmIIKJdm+qiaeHy5KMKlBrf30akXAWBzn2SqKsNOtSENWUwg7XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.7.0", + "@typescript-eslint/scope-manager": "8.34.0", + "@typescript-eslint/types": "8.34.0", + "@typescript-eslint/typescript-estree": "8.34.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.34.0.tgz", + "integrity": "sha512-qHV7pW7E85A0x6qyrFn+O+q1k1p3tQCsqIZ1KZ5ESLXY57aTvUd3/a4rdPTeXisvhXn2VQG0VSKUqs8KHF2zcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.34.0", + "eslint-visitor-keys": "^4.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv/node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.29.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.29.0.tgz", + "integrity": "sha512-GsGizj2Y1rCWDu6XoEekL3RLilp0voSePurjZIkxL3wlm5o5EC9VpgaP7lrCvjnkuLvzFBQWB3vWB3K5KQTveQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.20.1", + "@eslint/config-helpers": "^0.2.1", + "@eslint/core": "^0.14.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.29.0", + "@eslint/plugin-kit": "^0.3.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "@types/json-schema": "^7.0.15", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha512-bCK/2Z4zLidyB4ReuIsvALH6w31YfAQDmXMqMx6FyfHqvBxtjC0eRumeSu4Bs3XtXwpyIywtSTrVT99BxY1f9w==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.19.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", + "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "dev": true, + "license": "ISC" + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", + "dev": true, + "license": "MIT" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/launchdarkly-js-client-sdk": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/launchdarkly-js-client-sdk/-/launchdarkly-js-client-sdk-3.8.1.tgz", + "integrity": "sha512-Y05FXM8FAXAMbbJqeI+ffr6a4m2M/TBUccgI9ejWPSxQS+/b2t+FBWZzfmc7wXuOOYzgGkpHHfQ6bFDU9NKPWQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "escape-string-regexp": "^4.0.0", + "launchdarkly-js-sdk-common": "5.7.1" + } + }, + "node_modules/launchdarkly-js-sdk-common": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/launchdarkly-js-sdk-common/-/launchdarkly-js-sdk-common-5.7.1.tgz", + "integrity": "sha512-RFFeoYVL764zarFpU16lDt1yHzUCt0rnYYKlX5LLtZ5Nhq+2fzE33xRolP/sjxAYVInD0o5z6jKTlDe8gtcDYg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "fast-deep-equal": "^2.0.1", + "uuid": "^8.0.0" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-api-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", + "integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typescript": { + "version": "5.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", + "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.34.0.tgz", + "integrity": "sha512-MRpfN7uYjTrTGigFCt8sRyNqJFhjN0WwZecldaqhWm+wy0gaRt8Edb/3cuUy0zdq2opJWT6iXINKAtewnDOltQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.34.0", + "@typescript-eslint/parser": "8.34.0", + "@typescript-eslint/utils": "8.34.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "3.25.64", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.64.tgz", + "integrity": "sha512-hbP9FpSZf7pkS7hRVUrOjhwKJNyampPgtXKc3AN6DsWtoHsg2Sb4SQaS4Tcay380zSwd2VPo9G9180emBACp5g==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/node_modules/@eslint-community/eslint-utils/LICENSE b/node_modules/@eslint-community/eslint-utils/LICENSE new file mode 100644 index 00000000..883ee1f6 --- /dev/null +++ b/node_modules/@eslint-community/eslint-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Toru Nagashima + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@eslint-community/eslint-utils/README.md b/node_modules/@eslint-community/eslint-utils/README.md new file mode 100644 index 00000000..257954c9 --- /dev/null +++ b/node_modules/@eslint-community/eslint-utils/README.md @@ -0,0 +1,37 @@ +# @eslint-community/eslint-utils + +[![npm version](https://img.shields.io/npm/v/@eslint-community/eslint-utils.svg)](https://www.npmjs.com/package/@eslint-community/eslint-utils) +[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/eslint-utils.svg)](http://www.npmtrends.com/@eslint-community/eslint-utils) +[![Build Status](https://github.com/eslint-community/eslint-utils/workflows/CI/badge.svg)](https://github.com/eslint-community/eslint-utils/actions) +[![Coverage Status](https://codecov.io/gh/eslint-community/eslint-utils/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/eslint-utils) + +## 🏁 Goal + +This package provides utility functions and classes for make ESLint custom rules. + +For examples: + +- [`getStaticValue`](https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstaticvalue) evaluates static value on AST. +- [`ReferenceTracker`](https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring. + +## 📖 Usage + +See [documentation](https://eslint-community.github.io/eslint-utils). + +## 📰 Changelog + +See [releases](https://github.com/eslint-community/eslint-utils/releases). + +## ❤️ Contributing + +Welcome contributing! + +Please use GitHub's Issues/PRs. + +### Development Tools + +- `npm run test-coverage` runs tests and measures coverage. +- `npm run clean` removes the coverage result of `npm run test-coverage` command. +- `npm run coverage` shows the coverage result of the last `npm run test-coverage` command. +- `npm run lint` runs ESLint. +- `npm run watch` runs tests on each file change. diff --git a/node_modules/@eslint-community/eslint-utils/index.d.mts b/node_modules/@eslint-community/eslint-utils/index.d.mts new file mode 100644 index 00000000..8ad6f5c9 --- /dev/null +++ b/node_modules/@eslint-community/eslint-utils/index.d.mts @@ -0,0 +1,217 @@ +import * as eslint from 'eslint'; +import { Rule, AST } from 'eslint'; +import * as estree from 'estree'; + +declare const READ: unique symbol; +declare const CALL: unique symbol; +declare const CONSTRUCT: unique symbol; +declare const ESM: unique symbol; +declare class ReferenceTracker { + constructor(globalScope: Scope$2, options?: { + mode?: "legacy" | "strict" | undefined; + globalObjectNames?: string[] | undefined; + } | undefined); + private variableStack; + private globalScope; + private mode; + private globalObjectNames; + iterateGlobalReferences(traceMap: TraceMap$2): IterableIterator>; + iterateCjsReferences(traceMap: TraceMap$2): IterableIterator>; + iterateEsmReferences(traceMap: TraceMap$2): IterableIterator>; + iteratePropertyReferences(node: Expression, traceMap: TraceMap$2): IterableIterator>; + private _iterateVariableReferences; + private _iteratePropertyReferences; + private _iterateLhsReferences; + private _iterateImportReferences; +} +declare namespace ReferenceTracker { + export { READ }; + export { CALL }; + export { CONSTRUCT }; + export { ESM }; +} +type Scope$2 = eslint.Scope.Scope; +type Expression = estree.Expression; +type TraceMap$2 = TraceMap$1; +type TrackedReferences$2 = TrackedReferences$1; + +type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1; +type StaticValueProvided$1 = { + optional?: undefined; + value: unknown; +}; +type StaticValueOptional$1 = { + optional?: true; + value: undefined; +}; +type ReferenceTrackerOptions$1 = { + globalObjectNames?: string[]; + mode?: "legacy" | "strict"; +}; +type TraceMap$1 = { + [i: string]: TraceMapObject; +}; +type TraceMapObject = { + [i: string]: TraceMapObject; + [CALL]?: T; + [CONSTRUCT]?: T; + [READ]?: T; + [ESM]?: boolean; +}; +type TrackedReferences$1 = { + info: T; + node: Rule.Node; + path: string[]; + type: typeof CALL | typeof CONSTRUCT | typeof READ; +}; +type HasSideEffectOptions$1 = { + considerGetters?: boolean; + considerImplicitTypeConversion?: boolean; +}; +type PunctuatorToken = AST.Token & { + type: "Punctuator"; + value: Value; +}; +type ArrowToken$1 = PunctuatorToken<"=>">; +type CommaToken$1 = PunctuatorToken<",">; +type SemicolonToken$1 = PunctuatorToken<";">; +type ColonToken$1 = PunctuatorToken<":">; +type OpeningParenToken$1 = PunctuatorToken<"(">; +type ClosingParenToken$1 = PunctuatorToken<")">; +type OpeningBracketToken$1 = PunctuatorToken<"[">; +type ClosingBracketToken$1 = PunctuatorToken<"]">; +type OpeningBraceToken$1 = PunctuatorToken<"{">; +type ClosingBraceToken$1 = PunctuatorToken<"}">; + +declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null; +type Scope$1 = eslint.Scope.Scope; +type Variable = eslint.Scope.Variable; +type Identifier = estree.Identifier; + +declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null; +type SourceCode$2 = eslint.SourceCode; +type FunctionNode$1 = estree.Function; +type SourceLocation = estree.SourceLocation; + +declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string; +type FunctionNode = estree.Function; + +declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope; +type Scope = eslint.Scope.Scope; +type Node$4 = estree.Node; + +declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined; +type MemberExpression = estree.MemberExpression; +type MethodDefinition = estree.MethodDefinition; +type Property = estree.Property; +type PropertyDefinition = estree.PropertyDefinition; + +declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null; +type StaticValue$1 = StaticValue$2; +type Node$3 = estree.Node; + +declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null; +type Node$2 = estree.Node; + +declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean; +type Node$1 = estree.Node; +type SourceCode$1 = eslint.SourceCode; + +declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1; +declare function isCommaToken(token: CommentOrToken): token is CommaToken$1; +declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1; +declare function isColonToken(token: CommentOrToken): token is ColonToken$1; +declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1; +declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1; +declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1; +declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1; +declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1; +declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1; +declare function isCommentToken(token: CommentOrToken): token is estree.Comment; +declare function isNotArrowToken(arg0: CommentOrToken): boolean; +declare function isNotCommaToken(arg0: CommentOrToken): boolean; +declare function isNotSemicolonToken(arg0: CommentOrToken): boolean; +declare function isNotColonToken(arg0: CommentOrToken): boolean; +declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean; +declare function isNotClosingParenToken(arg0: CommentOrToken): boolean; +declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean; +declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean; +declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean; +declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean; +declare function isNotCommentToken(arg0: CommentOrToken): boolean; +type Token = eslint.AST.Token; +type Comment = estree.Comment; +type CommentOrToken = Comment | Token; + +declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean; +type Node = estree.Node; +type SourceCode = eslint.SourceCode; + +declare class PatternMatcher { + constructor(pattern: RegExp, options?: { + escaped?: boolean | undefined; + } | undefined); + execAll(str: string): IterableIterator; + test(str: string): boolean; + [Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string; +} + +declare namespace _default { + export { CALL }; + export { CONSTRUCT }; + export { ESM }; + export { findVariable }; + export { getFunctionHeadLocation }; + export { getFunctionNameWithKind }; + export { getInnermostScope }; + export { getPropertyName }; + export { getStaticValue }; + export { getStringIfConstant }; + export { hasSideEffect }; + export { isArrowToken }; + export { isClosingBraceToken }; + export { isClosingBracketToken }; + export { isClosingParenToken }; + export { isColonToken }; + export { isCommaToken }; + export { isCommentToken }; + export { isNotArrowToken }; + export { isNotClosingBraceToken }; + export { isNotClosingBracketToken }; + export { isNotClosingParenToken }; + export { isNotColonToken }; + export { isNotCommaToken }; + export { isNotCommentToken }; + export { isNotOpeningBraceToken }; + export { isNotOpeningBracketToken }; + export { isNotOpeningParenToken }; + export { isNotSemicolonToken }; + export { isOpeningBraceToken }; + export { isOpeningBracketToken }; + export { isOpeningParenToken }; + export { isParenthesized }; + export { isSemicolonToken }; + export { PatternMatcher }; + export { READ }; + export { ReferenceTracker }; +} + +type StaticValue = StaticValue$2; +type StaticValueOptional = StaticValueOptional$1; +type StaticValueProvided = StaticValueProvided$1; +type ReferenceTrackerOptions = ReferenceTrackerOptions$1; +type TraceMap = TraceMap$1; +type TrackedReferences = TrackedReferences$1; +type HasSideEffectOptions = HasSideEffectOptions$1; +type ArrowToken = ArrowToken$1; +type CommaToken = CommaToken$1; +type SemicolonToken = SemicolonToken$1; +type ColonToken = ColonToken$1; +type OpeningParenToken = OpeningParenToken$1; +type ClosingParenToken = ClosingParenToken$1; +type OpeningBracketToken = OpeningBracketToken$1; +type ClosingBracketToken = ClosingBracketToken$1; +type OpeningBraceToken = OpeningBraceToken$1; +type ClosingBraceToken = ClosingBraceToken$1; + +export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken }; diff --git a/node_modules/@eslint-community/eslint-utils/index.d.ts b/node_modules/@eslint-community/eslint-utils/index.d.ts new file mode 100644 index 00000000..8ad6f5c9 --- /dev/null +++ b/node_modules/@eslint-community/eslint-utils/index.d.ts @@ -0,0 +1,217 @@ +import * as eslint from 'eslint'; +import { Rule, AST } from 'eslint'; +import * as estree from 'estree'; + +declare const READ: unique symbol; +declare const CALL: unique symbol; +declare const CONSTRUCT: unique symbol; +declare const ESM: unique symbol; +declare class ReferenceTracker { + constructor(globalScope: Scope$2, options?: { + mode?: "legacy" | "strict" | undefined; + globalObjectNames?: string[] | undefined; + } | undefined); + private variableStack; + private globalScope; + private mode; + private globalObjectNames; + iterateGlobalReferences(traceMap: TraceMap$2): IterableIterator>; + iterateCjsReferences(traceMap: TraceMap$2): IterableIterator>; + iterateEsmReferences(traceMap: TraceMap$2): IterableIterator>; + iteratePropertyReferences(node: Expression, traceMap: TraceMap$2): IterableIterator>; + private _iterateVariableReferences; + private _iteratePropertyReferences; + private _iterateLhsReferences; + private _iterateImportReferences; +} +declare namespace ReferenceTracker { + export { READ }; + export { CALL }; + export { CONSTRUCT }; + export { ESM }; +} +type Scope$2 = eslint.Scope.Scope; +type Expression = estree.Expression; +type TraceMap$2 = TraceMap$1; +type TrackedReferences$2 = TrackedReferences$1; + +type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1; +type StaticValueProvided$1 = { + optional?: undefined; + value: unknown; +}; +type StaticValueOptional$1 = { + optional?: true; + value: undefined; +}; +type ReferenceTrackerOptions$1 = { + globalObjectNames?: string[]; + mode?: "legacy" | "strict"; +}; +type TraceMap$1 = { + [i: string]: TraceMapObject; +}; +type TraceMapObject = { + [i: string]: TraceMapObject; + [CALL]?: T; + [CONSTRUCT]?: T; + [READ]?: T; + [ESM]?: boolean; +}; +type TrackedReferences$1 = { + info: T; + node: Rule.Node; + path: string[]; + type: typeof CALL | typeof CONSTRUCT | typeof READ; +}; +type HasSideEffectOptions$1 = { + considerGetters?: boolean; + considerImplicitTypeConversion?: boolean; +}; +type PunctuatorToken = AST.Token & { + type: "Punctuator"; + value: Value; +}; +type ArrowToken$1 = PunctuatorToken<"=>">; +type CommaToken$1 = PunctuatorToken<",">; +type SemicolonToken$1 = PunctuatorToken<";">; +type ColonToken$1 = PunctuatorToken<":">; +type OpeningParenToken$1 = PunctuatorToken<"(">; +type ClosingParenToken$1 = PunctuatorToken<")">; +type OpeningBracketToken$1 = PunctuatorToken<"[">; +type ClosingBracketToken$1 = PunctuatorToken<"]">; +type OpeningBraceToken$1 = PunctuatorToken<"{">; +type ClosingBraceToken$1 = PunctuatorToken<"}">; + +declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null; +type Scope$1 = eslint.Scope.Scope; +type Variable = eslint.Scope.Variable; +type Identifier = estree.Identifier; + +declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null; +type SourceCode$2 = eslint.SourceCode; +type FunctionNode$1 = estree.Function; +type SourceLocation = estree.SourceLocation; + +declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string; +type FunctionNode = estree.Function; + +declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope; +type Scope = eslint.Scope.Scope; +type Node$4 = estree.Node; + +declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined; +type MemberExpression = estree.MemberExpression; +type MethodDefinition = estree.MethodDefinition; +type Property = estree.Property; +type PropertyDefinition = estree.PropertyDefinition; + +declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null; +type StaticValue$1 = StaticValue$2; +type Node$3 = estree.Node; + +declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null; +type Node$2 = estree.Node; + +declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean; +type Node$1 = estree.Node; +type SourceCode$1 = eslint.SourceCode; + +declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1; +declare function isCommaToken(token: CommentOrToken): token is CommaToken$1; +declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1; +declare function isColonToken(token: CommentOrToken): token is ColonToken$1; +declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1; +declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1; +declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1; +declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1; +declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1; +declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1; +declare function isCommentToken(token: CommentOrToken): token is estree.Comment; +declare function isNotArrowToken(arg0: CommentOrToken): boolean; +declare function isNotCommaToken(arg0: CommentOrToken): boolean; +declare function isNotSemicolonToken(arg0: CommentOrToken): boolean; +declare function isNotColonToken(arg0: CommentOrToken): boolean; +declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean; +declare function isNotClosingParenToken(arg0: CommentOrToken): boolean; +declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean; +declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean; +declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean; +declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean; +declare function isNotCommentToken(arg0: CommentOrToken): boolean; +type Token = eslint.AST.Token; +type Comment = estree.Comment; +type CommentOrToken = Comment | Token; + +declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean; +type Node = estree.Node; +type SourceCode = eslint.SourceCode; + +declare class PatternMatcher { + constructor(pattern: RegExp, options?: { + escaped?: boolean | undefined; + } | undefined); + execAll(str: string): IterableIterator; + test(str: string): boolean; + [Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string; +} + +declare namespace _default { + export { CALL }; + export { CONSTRUCT }; + export { ESM }; + export { findVariable }; + export { getFunctionHeadLocation }; + export { getFunctionNameWithKind }; + export { getInnermostScope }; + export { getPropertyName }; + export { getStaticValue }; + export { getStringIfConstant }; + export { hasSideEffect }; + export { isArrowToken }; + export { isClosingBraceToken }; + export { isClosingBracketToken }; + export { isClosingParenToken }; + export { isColonToken }; + export { isCommaToken }; + export { isCommentToken }; + export { isNotArrowToken }; + export { isNotClosingBraceToken }; + export { isNotClosingBracketToken }; + export { isNotClosingParenToken }; + export { isNotColonToken }; + export { isNotCommaToken }; + export { isNotCommentToken }; + export { isNotOpeningBraceToken }; + export { isNotOpeningBracketToken }; + export { isNotOpeningParenToken }; + export { isNotSemicolonToken }; + export { isOpeningBraceToken }; + export { isOpeningBracketToken }; + export { isOpeningParenToken }; + export { isParenthesized }; + export { isSemicolonToken }; + export { PatternMatcher }; + export { READ }; + export { ReferenceTracker }; +} + +type StaticValue = StaticValue$2; +type StaticValueOptional = StaticValueOptional$1; +type StaticValueProvided = StaticValueProvided$1; +type ReferenceTrackerOptions = ReferenceTrackerOptions$1; +type TraceMap = TraceMap$1; +type TrackedReferences = TrackedReferences$1; +type HasSideEffectOptions = HasSideEffectOptions$1; +type ArrowToken = ArrowToken$1; +type CommaToken = CommaToken$1; +type SemicolonToken = SemicolonToken$1; +type ColonToken = ColonToken$1; +type OpeningParenToken = OpeningParenToken$1; +type ClosingParenToken = ClosingParenToken$1; +type OpeningBracketToken = OpeningBracketToken$1; +type ClosingBracketToken = ClosingBracketToken$1; +type OpeningBraceToken = OpeningBraceToken$1; +type ClosingBraceToken = ClosingBraceToken$1; + +export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken }; diff --git a/node_modules/@eslint-community/eslint-utils/index.js b/node_modules/@eslint-community/eslint-utils/index.js new file mode 100644 index 00000000..979cf214 --- /dev/null +++ b/node_modules/@eslint-community/eslint-utils/index.js @@ -0,0 +1,2494 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var eslintVisitorKeys = require('eslint-visitor-keys'); + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("estree").Node} Node */ + +/** + * Get the innermost scope which contains a given location. + * @param {Scope} initialScope The initial scope to search. + * @param {Node} node The location to search. + * @returns {Scope} The innermost scope. + */ +function getInnermostScope(initialScope, node) { + const location = /** @type {[number, number]} */ (node.range)[0]; + + let scope = initialScope; + let found = false; + do { + found = false; + for (const childScope of scope.childScopes) { + const range = /** @type {[number, number]} */ ( + childScope.block.range + ); + + if (range[0] <= location && location < range[1]) { + scope = childScope; + found = true; + break + } + } + } while (found) + + return scope +} + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("eslint").Scope.Variable} Variable */ +/** @typedef {import("estree").Identifier} Identifier */ + +/** + * Find the variable of a given name. + * @param {Scope} initialScope The scope to start finding. + * @param {string|Identifier} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node. + * @returns {Variable|null} The found variable or null. + */ +function findVariable(initialScope, nameOrNode) { + let name = ""; + /** @type {Scope|null} */ + let scope = initialScope; + + if (typeof nameOrNode === "string") { + name = nameOrNode; + } else { + name = nameOrNode.name; + scope = getInnermostScope(scope, nameOrNode); + } + + while (scope != null) { + const variable = scope.set.get(name); + if (variable != null) { + return variable + } + scope = scope.upper; + } + + return null +} + +/** @typedef {import("eslint").AST.Token} Token */ +/** @typedef {import("estree").Comment} Comment */ +/** @typedef {import("./types.mjs").ArrowToken} ArrowToken */ +/** @typedef {import("./types.mjs").CommaToken} CommaToken */ +/** @typedef {import("./types.mjs").SemicolonToken} SemicolonToken */ +/** @typedef {import("./types.mjs").ColonToken} ColonToken */ +/** @typedef {import("./types.mjs").OpeningParenToken} OpeningParenToken */ +/** @typedef {import("./types.mjs").ClosingParenToken} ClosingParenToken */ +/** @typedef {import("./types.mjs").OpeningBracketToken} OpeningBracketToken */ +/** @typedef {import("./types.mjs").ClosingBracketToken} ClosingBracketToken */ +/** @typedef {import("./types.mjs").OpeningBraceToken} OpeningBraceToken */ +/** @typedef {import("./types.mjs").ClosingBraceToken} ClosingBraceToken */ +/** + * @template {string} Value + * @typedef {import("./types.mjs").PunctuatorToken} PunctuatorToken + */ + +/** @typedef {Comment | Token} CommentOrToken */ + +/** + * Creates the negate function of the given function. + * @param {function(CommentOrToken):boolean} f - The function to negate. + * @returns {function(CommentOrToken):boolean} Negated function. + */ +function negate(f) { + return (token) => !f(token) +} + +/** + * Checks if the given token is a PunctuatorToken with the given value + * @template {string} Value + * @param {CommentOrToken} token - The token to check. + * @param {Value} value - The value to check. + * @returns {token is PunctuatorToken} `true` if the token is a PunctuatorToken with the given value. + */ +function isPunctuatorTokenWithValue(token, value) { + return token.type === "Punctuator" && token.value === value +} + +/** + * Checks if the given token is an arrow token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ArrowToken} `true` if the token is an arrow token. + */ +function isArrowToken(token) { + return isPunctuatorTokenWithValue(token, "=>") +} + +/** + * Checks if the given token is a comma token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is CommaToken} `true` if the token is a comma token. + */ +function isCommaToken(token) { + return isPunctuatorTokenWithValue(token, ",") +} + +/** + * Checks if the given token is a semicolon token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is SemicolonToken} `true` if the token is a semicolon token. + */ +function isSemicolonToken(token) { + return isPunctuatorTokenWithValue(token, ";") +} + +/** + * Checks if the given token is a colon token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ColonToken} `true` if the token is a colon token. + */ +function isColonToken(token) { + return isPunctuatorTokenWithValue(token, ":") +} + +/** + * Checks if the given token is an opening parenthesis token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is OpeningParenToken} `true` if the token is an opening parenthesis token. + */ +function isOpeningParenToken(token) { + return isPunctuatorTokenWithValue(token, "(") +} + +/** + * Checks if the given token is a closing parenthesis token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ClosingParenToken} `true` if the token is a closing parenthesis token. + */ +function isClosingParenToken(token) { + return isPunctuatorTokenWithValue(token, ")") +} + +/** + * Checks if the given token is an opening square bracket token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is OpeningBracketToken} `true` if the token is an opening square bracket token. + */ +function isOpeningBracketToken(token) { + return isPunctuatorTokenWithValue(token, "[") +} + +/** + * Checks if the given token is a closing square bracket token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ClosingBracketToken} `true` if the token is a closing square bracket token. + */ +function isClosingBracketToken(token) { + return isPunctuatorTokenWithValue(token, "]") +} + +/** + * Checks if the given token is an opening brace token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is OpeningBraceToken} `true` if the token is an opening brace token. + */ +function isOpeningBraceToken(token) { + return isPunctuatorTokenWithValue(token, "{") +} + +/** + * Checks if the given token is a closing brace token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ClosingBraceToken} `true` if the token is a closing brace token. + */ +function isClosingBraceToken(token) { + return isPunctuatorTokenWithValue(token, "}") +} + +/** + * Checks if the given token is a comment token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is Comment} `true` if the token is a comment token. + */ +function isCommentToken(token) { + return ["Block", "Line", "Shebang"].includes(token.type) +} + +const isNotArrowToken = negate(isArrowToken); +const isNotCommaToken = negate(isCommaToken); +const isNotSemicolonToken = negate(isSemicolonToken); +const isNotColonToken = negate(isColonToken); +const isNotOpeningParenToken = negate(isOpeningParenToken); +const isNotClosingParenToken = negate(isClosingParenToken); +const isNotOpeningBracketToken = negate(isOpeningBracketToken); +const isNotClosingBracketToken = negate(isClosingBracketToken); +const isNotOpeningBraceToken = negate(isOpeningBraceToken); +const isNotClosingBraceToken = negate(isClosingBraceToken); +const isNotCommentToken = negate(isCommentToken); + +/** @typedef {import("eslint").Rule.Node} RuleNode */ +/** @typedef {import("eslint").SourceCode} SourceCode */ +/** @typedef {import("eslint").AST.Token} Token */ +/** @typedef {import("estree").Function} FunctionNode */ +/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */ +/** @typedef {import("estree").FunctionExpression} FunctionExpression */ +/** @typedef {import("estree").SourceLocation} SourceLocation */ +/** @typedef {import("estree").Position} Position */ + +/** + * Get the `(` token of the given function node. + * @param {FunctionExpression | FunctionDeclaration} node - The function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {Token} `(` token. + */ +function getOpeningParenOfParams(node, sourceCode) { + return node.id + ? /** @type {Token} */ ( + sourceCode.getTokenAfter(node.id, isOpeningParenToken) + ) + : /** @type {Token} */ ( + sourceCode.getFirstToken(node, isOpeningParenToken) + ) +} + +/** + * Get the location of the given function node for reporting. + * @param {FunctionNode} node - The function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {SourceLocation|null} The location of the function node for reporting. + */ +function getFunctionHeadLocation(node, sourceCode) { + const parent = /** @type {RuleNode} */ (node).parent; + + /** @type {Position|null} */ + let start = null; + /** @type {Position|null} */ + let end = null; + + if (node.type === "ArrowFunctionExpression") { + const arrowToken = /** @type {Token} */ ( + sourceCode.getTokenBefore(node.body, isArrowToken) + ); + + start = arrowToken.loc.start; + end = arrowToken.loc.end; + } else if ( + parent.type === "Property" || + parent.type === "MethodDefinition" || + parent.type === "PropertyDefinition" + ) { + start = /** @type {SourceLocation} */ (parent.loc).start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } else { + start = /** @type {SourceLocation} */ (node.loc).start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + + return { + start: { ...start }, + end: { ...end }, + } +} + +/* globals globalThis, global, self, window */ +/** @typedef {import("./types.mjs").StaticValue} StaticValue */ +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */ +/** @typedef {import("@typescript-eslint/types").TSESTree.AST_NODE_TYPES} TSESTreeNodeTypes */ +/** @typedef {import("@typescript-eslint/types").TSESTree.MemberExpression} MemberExpression */ +/** @typedef {import("@typescript-eslint/types").TSESTree.Property} Property */ +/** @typedef {import("@typescript-eslint/types").TSESTree.RegExpLiteral} RegExpLiteral */ +/** @typedef {import("@typescript-eslint/types").TSESTree.BigIntLiteral} BigIntLiteral */ +/** @typedef {import("@typescript-eslint/types").TSESTree.Literal} Literal */ + +const globalObject = + typeof globalThis !== "undefined" + ? globalThis + : // @ts-ignore + typeof self !== "undefined" + ? // @ts-ignore + self + : // @ts-ignore + typeof window !== "undefined" + ? // @ts-ignore + window + : typeof global !== "undefined" + ? global + : {}; + +const builtinNames = Object.freeze( + new Set([ + "Array", + "ArrayBuffer", + "BigInt", + "BigInt64Array", + "BigUint64Array", + "Boolean", + "DataView", + "Date", + "decodeURI", + "decodeURIComponent", + "encodeURI", + "encodeURIComponent", + "escape", + "Float32Array", + "Float64Array", + "Function", + "Infinity", + "Int16Array", + "Int32Array", + "Int8Array", + "isFinite", + "isNaN", + "isPrototypeOf", + "JSON", + "Map", + "Math", + "NaN", + "Number", + "Object", + "parseFloat", + "parseInt", + "Promise", + "Proxy", + "Reflect", + "RegExp", + "Set", + "String", + "Symbol", + "Uint16Array", + "Uint32Array", + "Uint8Array", + "Uint8ClampedArray", + "undefined", + "unescape", + "WeakMap", + "WeakSet", + ]), +); +const callAllowed = new Set( + [ + Array.isArray, + Array.of, + Array.prototype.at, + Array.prototype.concat, + Array.prototype.entries, + Array.prototype.every, + Array.prototype.filter, + Array.prototype.find, + Array.prototype.findIndex, + Array.prototype.flat, + Array.prototype.includes, + Array.prototype.indexOf, + Array.prototype.join, + Array.prototype.keys, + Array.prototype.lastIndexOf, + Array.prototype.slice, + Array.prototype.some, + Array.prototype.toString, + Array.prototype.values, + typeof BigInt === "function" ? BigInt : undefined, + Boolean, + Date, + Date.parse, + decodeURI, + decodeURIComponent, + encodeURI, + encodeURIComponent, + escape, + isFinite, + isNaN, + // @ts-ignore + isPrototypeOf, + Map, + Map.prototype.entries, + Map.prototype.get, + Map.prototype.has, + Map.prototype.keys, + Map.prototype.values, + .../** @type {(keyof typeof Math)[]} */ ( + Object.getOwnPropertyNames(Math) + ) + .filter((k) => k !== "random") + .map((k) => Math[k]) + .filter((f) => typeof f === "function"), + Number, + Number.isFinite, + Number.isNaN, + Number.parseFloat, + Number.parseInt, + Number.prototype.toExponential, + Number.prototype.toFixed, + Number.prototype.toPrecision, + Number.prototype.toString, + Object, + Object.entries, + Object.is, + Object.isExtensible, + Object.isFrozen, + Object.isSealed, + Object.keys, + Object.values, + parseFloat, + parseInt, + RegExp, + Set, + Set.prototype.entries, + Set.prototype.has, + Set.prototype.keys, + Set.prototype.values, + String, + String.fromCharCode, + String.fromCodePoint, + String.raw, + String.prototype.at, + String.prototype.charAt, + String.prototype.charCodeAt, + String.prototype.codePointAt, + String.prototype.concat, + String.prototype.endsWith, + String.prototype.includes, + String.prototype.indexOf, + String.prototype.lastIndexOf, + String.prototype.normalize, + String.prototype.padEnd, + String.prototype.padStart, + String.prototype.slice, + String.prototype.startsWith, + String.prototype.substr, + String.prototype.substring, + String.prototype.toLowerCase, + String.prototype.toString, + String.prototype.toUpperCase, + String.prototype.trim, + String.prototype.trimEnd, + String.prototype.trimLeft, + String.prototype.trimRight, + String.prototype.trimStart, + Symbol.for, + Symbol.keyFor, + unescape, + ].filter((f) => typeof f === "function"), +); +const callPassThrough = new Set([ + Object.freeze, + Object.preventExtensions, + Object.seal, +]); + +/** @type {ReadonlyArray]>} */ +const getterAllowed = [ + [Map, new Set(["size"])], + [ + RegExp, + new Set([ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "multiline", + "source", + "sticky", + "unicode", + ]), + ], + [Set, new Set(["size"])], +]; + +/** + * Get the property descriptor. + * @param {object} object The object to get. + * @param {string|number|symbol} name The property name to get. + */ +function getPropertyDescriptor(object, name) { + let x = object; + while ((typeof x === "object" || typeof x === "function") && x !== null) { + const d = Object.getOwnPropertyDescriptor(x, name); + if (d) { + return d + } + x = Object.getPrototypeOf(x); + } + return null +} + +/** + * Check if a property is getter or not. + * @param {object} object The object to check. + * @param {string|number|symbol} name The property name to check. + */ +function isGetter(object, name) { + const d = getPropertyDescriptor(object, name); + return d != null && d.get != null +} + +/** + * Get the element values of a given node list. + * @param {(Node|TSESTreeNode|null)[]} nodeList The node list to get values. + * @param {Scope|undefined|null} initialScope The initial scope to find variables. + * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null. + */ +function getElementValues(nodeList, initialScope) { + const valueList = []; + + for (let i = 0; i < nodeList.length; ++i) { + const elementNode = nodeList[i]; + + if (elementNode == null) { + valueList.length = i + 1; + } else if (elementNode.type === "SpreadElement") { + const argument = getStaticValueR(elementNode.argument, initialScope); + if (argument == null) { + return null + } + valueList.push(.../** @type {Iterable} */ (argument.value)); + } else { + const element = getStaticValueR(elementNode, initialScope); + if (element == null) { + return null + } + valueList.push(element.value); + } + } + + return valueList +} + +/** + * Returns whether the given variable is never written to after initialization. + * @param {import("eslint").Scope.Variable} variable + * @returns {boolean} + */ +function isEffectivelyConst(variable) { + const refs = variable.references; + + const inits = refs.filter((r) => r.init).length; + const reads = refs.filter((r) => r.isReadOnly()).length; + if (inits === 1 && reads + inits === refs.length) { + // there is only one init and all other references only read + return true + } + return false +} + +/** + * @template {TSESTreeNodeTypes} T + * @callback VisitorCallback + * @param {TSESTreeNode & { type: T }} node + * @param {Scope|undefined|null} initialScope + * @returns {StaticValue | null} + */ +/** + * @typedef { { [K in TSESTreeNodeTypes]?: VisitorCallback } } Operations + */ +/** + * @type {Operations} + */ +const operations = Object.freeze({ + ArrayExpression(node, initialScope) { + const elements = getElementValues(node.elements, initialScope); + return elements != null ? { value: elements } : null + }, + + AssignmentExpression(node, initialScope) { + if (node.operator === "=") { + return getStaticValueR(node.right, initialScope) + } + return null + }, + + //eslint-disable-next-line complexity + BinaryExpression(node, initialScope) { + if (node.operator === "in" || node.operator === "instanceof") { + // Not supported. + return null + } + + const left = getStaticValueR(node.left, initialScope); + const right = getStaticValueR(node.right, initialScope); + if (left != null && right != null) { + switch (node.operator) { + case "==": + return { value: left.value == right.value } //eslint-disable-line eqeqeq + case "!=": + return { value: left.value != right.value } //eslint-disable-line eqeqeq + case "===": + return { value: left.value === right.value } + case "!==": + return { value: left.value !== right.value } + case "<": + return { + value: + /** @type {any} */ (left.value) < + /** @type {any} */ (right.value), + } + case "<=": + return { + value: + /** @type {any} */ (left.value) <= + /** @type {any} */ (right.value), + } + case ">": + return { + value: + /** @type {any} */ (left.value) > + /** @type {any} */ (right.value), + } + case ">=": + return { + value: + /** @type {any} */ (left.value) >= + /** @type {any} */ (right.value), + } + case "<<": + return { + value: + /** @type {any} */ (left.value) << + /** @type {any} */ (right.value), + } + case ">>": + return { + value: + /** @type {any} */ (left.value) >> + /** @type {any} */ (right.value), + } + case ">>>": + return { + value: + /** @type {any} */ (left.value) >>> + /** @type {any} */ (right.value), + } + case "+": + return { + value: + /** @type {any} */ (left.value) + + /** @type {any} */ (right.value), + } + case "-": + return { + value: + /** @type {any} */ (left.value) - + /** @type {any} */ (right.value), + } + case "*": + return { + value: + /** @type {any} */ (left.value) * + /** @type {any} */ (right.value), + } + case "/": + return { + value: + /** @type {any} */ (left.value) / + /** @type {any} */ (right.value), + } + case "%": + return { + value: + /** @type {any} */ (left.value) % + /** @type {any} */ (right.value), + } + case "**": + return { + value: + /** @type {any} */ (left.value) ** + /** @type {any} */ (right.value), + } + case "|": + return { + value: + /** @type {any} */ (left.value) | + /** @type {any} */ (right.value), + } + case "^": + return { + value: + /** @type {any} */ (left.value) ^ + /** @type {any} */ (right.value), + } + case "&": + return { + value: + /** @type {any} */ (left.value) & + /** @type {any} */ (right.value), + } + + // no default + } + } + + return null + }, + + CallExpression(node, initialScope) { + const calleeNode = node.callee; + const args = getElementValues(node.arguments, initialScope); + + if (args != null) { + if (calleeNode.type === "MemberExpression") { + if (calleeNode.property.type === "PrivateIdentifier") { + return null + } + const object = getStaticValueR(calleeNode.object, initialScope); + if (object != null) { + if ( + object.value == null && + (object.optional || node.optional) + ) { + return { value: undefined, optional: true } + } + const property = getStaticPropertyNameValue( + calleeNode, + initialScope, + ); + + if (property != null) { + const receiver = + /** @type {Record any>} */ ( + object.value + ); + const methodName = /** @type {PropertyKey} */ ( + property.value + ); + if (callAllowed.has(receiver[methodName])) { + return { + value: receiver[methodName](...args), + } + } + if (callPassThrough.has(receiver[methodName])) { + return { value: args[0] } + } + } + } + } else { + const callee = getStaticValueR(calleeNode, initialScope); + if (callee != null) { + if (callee.value == null && node.optional) { + return { value: undefined, optional: true } + } + const func = /** @type {(...args: any[]) => any} */ ( + callee.value + ); + if (callAllowed.has(func)) { + return { value: func(...args) } + } + if (callPassThrough.has(func)) { + return { value: args[0] } + } + } + } + } + + return null + }, + + ConditionalExpression(node, initialScope) { + const test = getStaticValueR(node.test, initialScope); + if (test != null) { + return test.value + ? getStaticValueR(node.consequent, initialScope) + : getStaticValueR(node.alternate, initialScope) + } + return null + }, + + ExpressionStatement(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + + Identifier(node, initialScope) { + if (initialScope != null) { + const variable = findVariable(initialScope, node); + + // Built-in globals. + if ( + variable != null && + variable.defs.length === 0 && + builtinNames.has(variable.name) && + variable.name in globalObject + ) { + return { value: globalObject[variable.name] } + } + + // Constants. + if (variable != null && variable.defs.length === 1) { + const def = variable.defs[0]; + if ( + def.parent && + def.type === "Variable" && + (def.parent.kind === "const" || + isEffectivelyConst(variable)) && + // TODO(mysticatea): don't support destructuring here. + def.node.id.type === "Identifier" + ) { + return getStaticValueR(def.node.init, initialScope) + } + } + } + return null + }, + + Literal(node) { + const literal = + /** @type {Partial & Partial & Partial} */ ( + node + ); + //istanbul ignore if : this is implementation-specific behavior. + if ( + (literal.regex != null || literal.bigint != null) && + literal.value == null + ) { + // It was a RegExp/BigInt literal, but Node.js didn't support it. + return null + } + return { value: literal.value } + }, + + LogicalExpression(node, initialScope) { + const left = getStaticValueR(node.left, initialScope); + if (left != null) { + if ( + (node.operator === "||" && Boolean(left.value) === true) || + (node.operator === "&&" && Boolean(left.value) === false) || + (node.operator === "??" && left.value != null) + ) { + return left + } + + const right = getStaticValueR(node.right, initialScope); + if (right != null) { + return right + } + } + + return null + }, + + MemberExpression(node, initialScope) { + if (node.property.type === "PrivateIdentifier") { + return null + } + const object = getStaticValueR(node.object, initialScope); + if (object != null) { + if (object.value == null && (object.optional || node.optional)) { + return { value: undefined, optional: true } + } + const property = getStaticPropertyNameValue(node, initialScope); + + if (property != null) { + if ( + !isGetter( + /** @type {object} */ (object.value), + /** @type {PropertyKey} */ (property.value), + ) + ) { + return { + value: /** @type {Record} */ ( + object.value + )[/** @type {PropertyKey} */ (property.value)], + } + } + + for (const [classFn, allowed] of getterAllowed) { + if ( + object.value instanceof classFn && + allowed.has(/** @type {string} */ (property.value)) + ) { + return { + value: /** @type {Record} */ ( + object.value + )[/** @type {PropertyKey} */ (property.value)], + } + } + } + } + } + return null + }, + + ChainExpression(node, initialScope) { + const expression = getStaticValueR(node.expression, initialScope); + if (expression != null) { + return { value: expression.value } + } + return null + }, + + NewExpression(node, initialScope) { + const callee = getStaticValueR(node.callee, initialScope); + const args = getElementValues(node.arguments, initialScope); + + if (callee != null && args != null) { + const Func = /** @type {new (...args: any[]) => any} */ ( + callee.value + ); + if (callAllowed.has(Func)) { + return { value: new Func(...args) } + } + } + + return null + }, + + ObjectExpression(node, initialScope) { + /** @type {Record} */ + const object = {}; + + for (const propertyNode of node.properties) { + if (propertyNode.type === "Property") { + if (propertyNode.kind !== "init") { + return null + } + const key = getStaticPropertyNameValue( + propertyNode, + initialScope, + ); + const value = getStaticValueR(propertyNode.value, initialScope); + if (key == null || value == null) { + return null + } + object[/** @type {PropertyKey} */ (key.value)] = value.value; + } else if ( + propertyNode.type === "SpreadElement" || + // @ts-expect-error -- Backward compatibility + propertyNode.type === "ExperimentalSpreadProperty" + ) { + const argument = getStaticValueR( + propertyNode.argument, + initialScope, + ); + if (argument == null) { + return null + } + Object.assign(object, argument.value); + } else { + return null + } + } + + return { value: object } + }, + + SequenceExpression(node, initialScope) { + const last = node.expressions[node.expressions.length - 1]; + return getStaticValueR(last, initialScope) + }, + + TaggedTemplateExpression(node, initialScope) { + const tag = getStaticValueR(node.tag, initialScope); + const expressions = getElementValues( + node.quasi.expressions, + initialScope, + ); + + if (tag != null && expressions != null) { + const func = /** @type {(...args: any[]) => any} */ (tag.value); + /** @type {any[] & { raw?: string[] }} */ + const strings = node.quasi.quasis.map((q) => q.value.cooked); + strings.raw = node.quasi.quasis.map((q) => q.value.raw); + + if (func === String.raw) { + return { value: func(strings, ...expressions) } + } + } + + return null + }, + + TemplateLiteral(node, initialScope) { + const expressions = getElementValues(node.expressions, initialScope); + if (expressions != null) { + let value = node.quasis[0].value.cooked; + for (let i = 0; i < expressions.length; ++i) { + value += expressions[i]; + value += /** @type {string} */ (node.quasis[i + 1].value.cooked); + } + return { value } + } + return null + }, + + UnaryExpression(node, initialScope) { + if (node.operator === "delete") { + // Not supported. + return null + } + if (node.operator === "void") { + return { value: undefined } + } + + const arg = getStaticValueR(node.argument, initialScope); + if (arg != null) { + switch (node.operator) { + case "-": + return { value: -(/** @type {any} */ (arg.value)) } + case "+": + return { value: +(/** @type {any} */ (arg.value)) } //eslint-disable-line no-implicit-coercion + case "!": + return { value: !arg.value } + case "~": + return { value: ~(/** @type {any} */ (arg.value)) } + case "typeof": + return { value: typeof arg.value } + + // no default + } + } + + return null + }, + TSAsExpression(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + TSSatisfiesExpression(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + TSTypeAssertion(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + TSNonNullExpression(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + TSInstantiationExpression(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, +}); + +/** + * Get the value of a given node if it's a static value. + * @param {Node|TSESTreeNode|null|undefined} node The node to get. + * @param {Scope|undefined|null} initialScope The scope to start finding variable. + * @returns {StaticValue|null} The static value of the node, or `null`. + */ +function getStaticValueR(node, initialScope) { + if (node != null && Object.hasOwnProperty.call(operations, node.type)) { + return /** @type {VisitorCallback} */ (operations[node.type])( + /** @type {TSESTreeNode} */ (node), + initialScope, + ) + } + return null +} + +/** + * Get the static value of property name from a MemberExpression node or a Property node. + * @param {MemberExpression|Property} node The node to get. + * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it. + * @returns {StaticValue|null} The static value of the property name of the node, or `null`. + */ +function getStaticPropertyNameValue(node, initialScope) { + const nameNode = node.type === "Property" ? node.key : node.property; + + if (node.computed) { + return getStaticValueR(nameNode, initialScope) + } + + if (nameNode.type === "Identifier") { + return { value: nameNode.name } + } + + if (nameNode.type === "Literal") { + if (/** @type {Partial} */ (nameNode).bigint) { + return { value: /** @type {BigIntLiteral} */ (nameNode).bigint } + } + return { value: String(nameNode.value) } + } + + return null +} + +/** + * Get the value of a given node if it's a static value. + * @param {Node} node The node to get. + * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible. + * @returns {StaticValue | null} The static value of the node, or `null`. + */ +function getStaticValue(node, initialScope = null) { + try { + return getStaticValueR(node, initialScope) + } catch (_error) { + return null + } +} + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").RegExpLiteral} RegExpLiteral */ +/** @typedef {import("estree").BigIntLiteral} BigIntLiteral */ +/** @typedef {import("estree").SimpleLiteral} SimpleLiteral */ + +/** + * Get the value of a given node if it's a literal or a template literal. + * @param {Node} node The node to get. + * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant. + * @returns {string|null} The value of the node, or `null`. + */ +function getStringIfConstant(node, initialScope = null) { + // Handle the literals that the platform doesn't support natively. + if (node && node.type === "Literal" && node.value === null) { + const literal = + /** @type {Partial & Partial & Partial} */ ( + node + ); + if (literal.regex) { + return `/${literal.regex.pattern}/${literal.regex.flags}` + } + if (literal.bigint) { + return literal.bigint + } + } + + const evaluated = getStaticValue(node, initialScope); + + if (evaluated) { + // `String(Symbol.prototype)` throws error + try { + return String(evaluated.value) + } catch { + // No op + } + } + + return null +} + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("estree").MethodDefinition} MethodDefinition */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */ +/** @typedef {import("estree").Identifier} Identifier */ + +/** + * Get the property name from a MemberExpression node or a Property node. + * @param {MemberExpression | MethodDefinition | Property | PropertyDefinition} node The node to get. + * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it. + * @returns {string|null|undefined} The property name of the node. + */ +function getPropertyName(node, initialScope) { + switch (node.type) { + case "MemberExpression": + if (node.computed) { + return getStringIfConstant(node.property, initialScope) + } + if (node.property.type === "PrivateIdentifier") { + return null + } + return /** @type {Partial} */ (node.property).name + + case "Property": + case "MethodDefinition": + case "PropertyDefinition": + if (node.computed) { + return getStringIfConstant(node.key, initialScope) + } + if (node.key.type === "Literal") { + return String(node.key.value) + } + if (node.key.type === "PrivateIdentifier") { + return null + } + return /** @type {Partial} */ (node.key).name + } + + return null +} + +/** @typedef {import("eslint").Rule.Node} RuleNode */ +/** @typedef {import("eslint").SourceCode} SourceCode */ +/** @typedef {import("estree").Function} FunctionNode */ +/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */ +/** @typedef {import("estree").FunctionExpression} FunctionExpression */ +/** @typedef {import("estree").Identifier} Identifier */ + +/** + * Get the name and kind of the given function node. + * @param {FunctionNode} node - The function node to get. + * @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys. + * @returns {string} The name and kind of the function node. + */ +// eslint-disable-next-line complexity +function getFunctionNameWithKind(node, sourceCode) { + const parent = /** @type {RuleNode} */ (node).parent; + const tokens = []; + const isObjectMethod = parent.type === "Property" && parent.value === node; + const isClassMethod = + parent.type === "MethodDefinition" && parent.value === node; + const isClassFieldMethod = + parent.type === "PropertyDefinition" && parent.value === node; + + // Modifiers. + if (isClassMethod || isClassFieldMethod) { + if (parent.static) { + tokens.push("static"); + } + if (parent.key.type === "PrivateIdentifier") { + tokens.push("private"); + } + } + if (node.async) { + tokens.push("async"); + } + if (node.generator) { + tokens.push("generator"); + } + + // Kinds. + if (isObjectMethod || isClassMethod) { + if (parent.kind === "constructor") { + return "constructor" + } + if (parent.kind === "get") { + tokens.push("getter"); + } else if (parent.kind === "set") { + tokens.push("setter"); + } else { + tokens.push("method"); + } + } else if (isClassFieldMethod) { + tokens.push("method"); + } else { + if (node.type === "ArrowFunctionExpression") { + tokens.push("arrow"); + } + tokens.push("function"); + } + + // Names. + if (isObjectMethod || isClassMethod || isClassFieldMethod) { + if (parent.key.type === "PrivateIdentifier") { + tokens.push(`#${parent.key.name}`); + } else { + const name = getPropertyName(parent); + if (name) { + tokens.push(`'${name}'`); + } else if (sourceCode) { + const keyText = sourceCode.getText(parent.key); + if (!keyText.includes("\n")) { + tokens.push(`[${keyText}]`); + } + } + } + } else if (hasId(node)) { + tokens.push(`'${node.id.name}'`); + } else if ( + parent.type === "VariableDeclarator" && + parent.id && + parent.id.type === "Identifier" + ) { + tokens.push(`'${parent.id.name}'`); + } else if ( + (parent.type === "AssignmentExpression" || + parent.type === "AssignmentPattern") && + parent.left && + parent.left.type === "Identifier" + ) { + tokens.push(`'${parent.left.name}'`); + } else if ( + parent.type === "ExportDefaultDeclaration" && + parent.declaration === node + ) { + tokens.push("'default'"); + } + + return tokens.join(" ") +} + +/** + * @param {FunctionNode} node + * @returns {node is FunctionDeclaration | FunctionExpression & { id: Identifier }} + */ +function hasId(node) { + return Boolean( + /** @type {Partial} */ (node) + .id, + ) +} + +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("eslint").SourceCode} SourceCode */ +/** @typedef {import("./types.mjs").HasSideEffectOptions} HasSideEffectOptions */ +/** @typedef {import("estree").BinaryExpression} BinaryExpression */ +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("estree").MethodDefinition} MethodDefinition */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */ +/** @typedef {import("estree").UnaryExpression} UnaryExpression */ + +const typeConversionBinaryOps = Object.freeze( + new Set([ + "==", + "!=", + "<", + "<=", + ">", + ">=", + "<<", + ">>", + ">>>", + "+", + "-", + "*", + "/", + "%", + "|", + "^", + "&", + "in", + ]), +); +const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"])); + +/** + * Check whether the given value is an ASTNode or not. + * @param {any} x The value to check. + * @returns {x is Node} `true` if the value is an ASTNode. + */ +function isNode(x) { + return x !== null && typeof x === "object" && typeof x.type === "string" +} + +const visitor = Object.freeze( + Object.assign(Object.create(null), { + /** + * @param {Node} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + $visit(node, options, visitorKeys) { + const { type } = node; + + if (typeof (/** @type {any} */ (this)[type]) === "function") { + return /** @type {any} */ (this)[type]( + node, + options, + visitorKeys, + ) + } + + return this.$visitChildren(node, options, visitorKeys) + }, + + /** + * @param {Node} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + $visitChildren(node, options, visitorKeys) { + const { type } = node; + + for (const key of /** @type {(keyof Node)[]} */ ( + visitorKeys[type] || eslintVisitorKeys.getKeys(node) + )) { + const value = node[key]; + + if (Array.isArray(value)) { + for (const element of value) { + if ( + isNode(element) && + this.$visit(element, options, visitorKeys) + ) { + return true + } + } + } else if ( + isNode(value) && + this.$visit(value, options, visitorKeys) + ) { + return true + } + } + + return false + }, + + ArrowFunctionExpression() { + return false + }, + AssignmentExpression() { + return true + }, + AwaitExpression() { + return true + }, + /** + * @param {BinaryExpression} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + BinaryExpression(node, options, visitorKeys) { + if ( + options.considerImplicitTypeConversion && + typeConversionBinaryOps.has(node.operator) && + (node.left.type !== "Literal" || node.right.type !== "Literal") + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + CallExpression() { + return true + }, + FunctionExpression() { + return false + }, + ImportExpression() { + return true + }, + /** + * @param {MemberExpression} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + MemberExpression(node, options, visitorKeys) { + if (options.considerGetters) { + return true + } + if ( + options.considerImplicitTypeConversion && + node.computed && + node.property.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + /** + * @param {MethodDefinition} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + MethodDefinition(node, options, visitorKeys) { + if ( + options.considerImplicitTypeConversion && + node.computed && + node.key.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + NewExpression() { + return true + }, + /** + * @param {Property} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + Property(node, options, visitorKeys) { + if ( + options.considerImplicitTypeConversion && + node.computed && + node.key.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + /** + * @param {PropertyDefinition} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + PropertyDefinition(node, options, visitorKeys) { + if ( + options.considerImplicitTypeConversion && + node.computed && + node.key.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + /** + * @param {UnaryExpression} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + UnaryExpression(node, options, visitorKeys) { + if (node.operator === "delete") { + return true + } + if ( + options.considerImplicitTypeConversion && + typeConversionUnaryOps.has(node.operator) && + node.argument.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + UpdateExpression() { + return true + }, + YieldExpression() { + return true + }, + }), +); + +/** + * Check whether a given node has any side effect or not. + * @param {Node} node The node to get. + * @param {SourceCode} sourceCode The source code object. + * @param {HasSideEffectOptions} [options] The option object. + * @returns {boolean} `true` if the node has a certain side effect. + */ +function hasSideEffect(node, sourceCode, options = {}) { + const { considerGetters = false, considerImplicitTypeConversion = false } = + options; + return visitor.$visit( + node, + { considerGetters, considerImplicitTypeConversion }, + sourceCode.visitorKeys || eslintVisitorKeys.KEYS, + ) +} + +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("eslint").SourceCode} SourceCode */ +/** @typedef {import("eslint").AST.Token} Token */ +/** @typedef {import("eslint").Rule.Node} RuleNode */ + +/** + * Get the left parenthesis of the parent node syntax if it exists. + * E.g., `if (a) {}` then the `(`. + * @param {Node} node The AST node to check. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token|null} The left parenthesis of the parent node syntax + */ +function getParentSyntaxParen(node, sourceCode) { + const parent = /** @type {RuleNode} */ (node).parent; + + switch (parent.type) { + case "CallExpression": + case "NewExpression": + if (parent.arguments.length === 1 && parent.arguments[0] === node) { + return sourceCode.getTokenAfter( + parent.callee, + isOpeningParenToken, + ) + } + return null + + case "DoWhileStatement": + if (parent.test === node) { + return sourceCode.getTokenAfter( + parent.body, + isOpeningParenToken, + ) + } + return null + + case "IfStatement": + case "WhileStatement": + if (parent.test === node) { + return sourceCode.getFirstToken(parent, 1) + } + return null + + case "ImportExpression": + if (parent.source === node) { + return sourceCode.getFirstToken(parent, 1) + } + return null + + case "SwitchStatement": + if (parent.discriminant === node) { + return sourceCode.getFirstToken(parent, 1) + } + return null + + case "WithStatement": + if (parent.object === node) { + return sourceCode.getFirstToken(parent, 1) + } + return null + + default: + return null + } +} + +/** + * Check whether a given node is parenthesized or not. + * @param {number} times The number of parantheses. + * @param {Node} node The AST node to check. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {boolean} `true` if the node is parenthesized the given times. + */ +/** + * Check whether a given node is parenthesized or not. + * @param {Node} node The AST node to check. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {boolean} `true` if the node is parenthesized. + */ +/** + * Check whether a given node is parenthesized or not. + * @param {Node|number} timesOrNode The first parameter. + * @param {Node|SourceCode} nodeOrSourceCode The second parameter. + * @param {SourceCode} [optionalSourceCode] The third parameter. + * @returns {boolean} `true` if the node is parenthesized. + */ +function isParenthesized( + timesOrNode, + nodeOrSourceCode, + optionalSourceCode, +) { + /** @type {number} */ + let times, + /** @type {RuleNode} */ + node, + /** @type {SourceCode} */ + sourceCode, + maybeLeftParen, + maybeRightParen; + if (typeof timesOrNode === "number") { + times = timesOrNode | 0; + node = /** @type {RuleNode} */ (nodeOrSourceCode); + sourceCode = /** @type {SourceCode} */ (optionalSourceCode); + if (!(times >= 1)) { + throw new TypeError("'times' should be a positive integer.") + } + } else { + times = 1; + node = /** @type {RuleNode} */ (timesOrNode); + sourceCode = /** @type {SourceCode} */ (nodeOrSourceCode); + } + + if ( + node == null || + // `Program` can't be parenthesized + node.parent == null || + // `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}` + (node.parent.type === "CatchClause" && node.parent.param === node) + ) { + return false + } + + maybeLeftParen = maybeRightParen = node; + do { + maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen); + maybeRightParen = sourceCode.getTokenAfter(maybeRightParen); + } while ( + maybeLeftParen != null && + maybeRightParen != null && + isOpeningParenToken(maybeLeftParen) && + isClosingParenToken(maybeRightParen) && + // Avoid false positive such as `if (a) {}` + maybeLeftParen !== getParentSyntaxParen(node, sourceCode) && + --times > 0 + ) + + return times === 0 +} + +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ + +const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu; + +/** @type {WeakMap} */ +const internal = new WeakMap(); + +/** + * Check whether a given character is escaped or not. + * @param {string} str The string to check. + * @param {number} index The location of the character to check. + * @returns {boolean} `true` if the character is escaped. + */ +function isEscaped(str, index) { + let escaped = false; + for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) { + escaped = !escaped; + } + return escaped +} + +/** + * Replace a given string by a given matcher. + * @param {PatternMatcher} matcher The pattern matcher. + * @param {string} str The string to be replaced. + * @param {string} replacement The new substring to replace each matched part. + * @returns {string} The replaced string. + */ +function replaceS(matcher, str, replacement) { + const chunks = []; + let index = 0; + + /** + * @param {string} key The placeholder. + * @param {RegExpExecArray} match The matched information. + * @returns {string} The replaced string. + */ + function replacer(key, match) { + switch (key) { + case "$$": + return "$" + case "$&": + return match[0] + case "$`": + return str.slice(0, match.index) + case "$'": + return str.slice(match.index + match[0].length) + default: { + const i = key.slice(1); + if (i in match) { + return match[/** @type {any} */ (i)] + } + return key + } + } + } + + for (const match of matcher.execAll(str)) { + chunks.push(str.slice(index, match.index)); + chunks.push( + replacement.replace(placeholder, (key) => replacer(key, match)), + ); + index = match.index + match[0].length; + } + chunks.push(str.slice(index)); + + return chunks.join("") +} + +/** + * Replace a given string by a given matcher. + * @param {PatternMatcher} matcher The pattern matcher. + * @param {string} str The string to be replaced. + * @param {(substring: string, ...args: any[]) => string} replace The function to replace each matched part. + * @returns {string} The replaced string. + */ +function replaceF(matcher, str, replace) { + const chunks = []; + let index = 0; + + for (const match of matcher.execAll(str)) { + chunks.push(str.slice(index, match.index)); + chunks.push( + String( + replace( + .../** @type {[string, ...string[]]} */ ( + /** @type {string[]} */ (match) + ), + match.index, + match.input, + ), + ), + ); + index = match.index + match[0].length; + } + chunks.push(str.slice(index)); + + return chunks.join("") +} + +/** + * The class to find patterns as considering escape sequences. + */ +class PatternMatcher { + /** + * Initialize this matcher. + * @param {RegExp} pattern The pattern to match. + * @param {{escaped?:boolean}} [options] The options. + */ + constructor(pattern, options = {}) { + const { escaped = false } = options; + if (!(pattern instanceof RegExp)) { + throw new TypeError("'pattern' should be a RegExp instance.") + } + if (!pattern.flags.includes("g")) { + throw new Error("'pattern' should contains 'g' flag.") + } + + internal.set(this, { + pattern: new RegExp(pattern.source, pattern.flags), + escaped: Boolean(escaped), + }); + } + + /** + * Find the pattern in a given string. + * @param {string} str The string to find. + * @returns {IterableIterator} The iterator which iterate the matched information. + */ + *execAll(str) { + const { pattern, escaped } = + /** @type {{pattern:RegExp,escaped:boolean}} */ (internal.get(this)); + let match = null; + let lastIndex = 0; + + pattern.lastIndex = 0; + while ((match = pattern.exec(str)) != null) { + if (escaped || !isEscaped(str, match.index)) { + lastIndex = pattern.lastIndex; + yield match; + pattern.lastIndex = lastIndex; + } + } + } + + /** + * Check whether the pattern is found in a given string. + * @param {string} str The string to check. + * @returns {boolean} `true` if the pattern was found in the string. + */ + test(str) { + const it = this.execAll(str); + const ret = it.next(); + return !ret.done + } + + /** + * Replace a given string. + * @param {string} str The string to be replaced. + * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`. + * @returns {string} The replaced string. + */ + [Symbol.replace](str, replacer) { + return typeof replacer === "function" + ? replaceF(this, String(str), replacer) + : replaceS(this, String(str), String(replacer)) + } +} + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("eslint").Scope.Variable} Variable */ +/** @typedef {import("eslint").Rule.Node} RuleNode */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").Pattern} Pattern */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").SimpleCallExpression} CallExpression */ +/** @typedef {import("estree").Program} Program */ +/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */ +/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */ +/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */ +/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */ +/** @typedef {import("estree").ImportSpecifier} ImportSpecifier */ +/** @typedef {import("estree").ImportDefaultSpecifier} ImportDefaultSpecifier */ +/** @typedef {import("estree").ImportNamespaceSpecifier} ImportNamespaceSpecifier */ +/** @typedef {import("estree").ExportSpecifier} ExportSpecifier */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */ +/** @typedef {import("estree").Literal} Literal */ +/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */ +/** @typedef {import("./types.mjs").ReferenceTrackerOptions} ReferenceTrackerOptions */ +/** + * @template T + * @typedef {import("./types.mjs").TraceMap} TraceMap + */ +/** + * @template T + * @typedef {import("./types.mjs").TraceMapObject} TraceMapObject + */ +/** + * @template T + * @typedef {import("./types.mjs").TrackedReferences} TrackedReferences + */ + +const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u; + +/** + * Check whether a given node is an import node or not. + * @param {Node} node + * @returns {node is ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration&{source: Literal}} `true` if the node is an import node. + */ +function isHasSource(node) { + return ( + IMPORT_TYPE.test(node.type) && + /** @type {ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration} */ ( + node + ).source != null + ) +} +const has = + /** @type {(traceMap: TraceMap, v: T) => v is (string extends T ? string : T)} */ ( + Function.call.bind(Object.hasOwnProperty) + ); + +const READ = Symbol("read"); +const CALL = Symbol("call"); +const CONSTRUCT = Symbol("construct"); +const ESM = Symbol("esm"); + +const requireCall = { require: { [CALL]: true } }; + +/** + * Check whether a given variable is modified or not. + * @param {Variable|undefined} variable The variable to check. + * @returns {boolean} `true` if the variable is modified. + */ +function isModifiedGlobal(variable) { + return ( + variable == null || + variable.defs.length !== 0 || + variable.references.some((r) => r.isWrite()) + ) +} + +/** + * Check if the value of a given node is passed through to the parent syntax as-is. + * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through. + * @param {Node} node A node to check. + * @returns {node is RuleNode & {parent: Expression}} `true` if the node is passed through. + */ +function isPassThrough(node) { + const parent = /** @type {TSESTreeNode} */ (node).parent; + + if (parent) { + switch (parent.type) { + case "ConditionalExpression": + return parent.consequent === node || parent.alternate === node + case "LogicalExpression": + return true + case "SequenceExpression": + return ( + parent.expressions[parent.expressions.length - 1] === node + ) + case "ChainExpression": + return true + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + case "TSInstantiationExpression": + return true + + default: + return false + } + } + return false +} + +/** + * The reference tracker. + */ +class ReferenceTracker { + /** + * Initialize this tracker. + * @param {Scope} globalScope The global scope. + * @param {object} [options] The options. + * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules. + * @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object. + */ + constructor(globalScope, options = {}) { + const { + mode = "strict", + globalObjectNames = ["global", "globalThis", "self", "window"], + } = options; + /** @private @type {Variable[]} */ + this.variableStack = []; + /** @private */ + this.globalScope = globalScope; + /** @private */ + this.mode = mode; + /** @private */ + this.globalObjectNames = globalObjectNames.slice(0); + } + + /** + * Iterate the references of global variables. + * @template T + * @param {TraceMap} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *iterateGlobalReferences(traceMap) { + for (const key of Object.keys(traceMap)) { + const nextTraceMap = traceMap[key]; + const path = [key]; + const variable = this.globalScope.set.get(key); + + if (isModifiedGlobal(variable)) { + continue + } + + yield* this._iterateVariableReferences( + /** @type {Variable} */ (variable), + path, + nextTraceMap, + true, + ); + } + + for (const key of this.globalObjectNames) { + /** @type {string[]} */ + const path = []; + const variable = this.globalScope.set.get(key); + + if (isModifiedGlobal(variable)) { + continue + } + + yield* this._iterateVariableReferences( + /** @type {Variable} */ (variable), + path, + traceMap, + false, + ); + } + } + + /** + * Iterate the references of CommonJS modules. + * @template T + * @param {TraceMap} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *iterateCjsReferences(traceMap) { + for (const { node } of this.iterateGlobalReferences(requireCall)) { + const key = getStringIfConstant( + /** @type {CallExpression} */ (node).arguments[0], + ); + if (key == null || !has(traceMap, key)) { + continue + } + + const nextTraceMap = traceMap[key]; + const path = [key]; + + if (nextTraceMap[READ]) { + yield { + node, + path, + type: READ, + info: nextTraceMap[READ], + }; + } + yield* this._iteratePropertyReferences( + /** @type {CallExpression} */ (node), + path, + nextTraceMap, + ); + } + } + + /** + * Iterate the references of ES modules. + * @template T + * @param {TraceMap} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *iterateEsmReferences(traceMap) { + const programNode = /** @type {Program} */ (this.globalScope.block); + + for (const node of programNode.body) { + if (!isHasSource(node)) { + continue + } + const moduleId = /** @type {string} */ (node.source.value); + + if (!has(traceMap, moduleId)) { + continue + } + const nextTraceMap = traceMap[moduleId]; + const path = [moduleId]; + + if (nextTraceMap[READ]) { + yield { + // eslint-disable-next-line object-shorthand -- apply type + node: /** @type {RuleNode} */ (node), + path, + type: READ, + info: nextTraceMap[READ], + }; + } + + if (node.type === "ExportAllDeclaration") { + for (const key of Object.keys(nextTraceMap)) { + const exportTraceMap = nextTraceMap[key]; + if (exportTraceMap[READ]) { + yield { + // eslint-disable-next-line object-shorthand -- apply type + node: /** @type {RuleNode} */ (node), + path: path.concat(key), + type: READ, + info: exportTraceMap[READ], + }; + } + } + } else { + for (const specifier of node.specifiers) { + const esm = has(nextTraceMap, ESM); + const it = this._iterateImportReferences( + specifier, + path, + esm + ? nextTraceMap + : this.mode === "legacy" + ? { default: nextTraceMap, ...nextTraceMap } + : { default: nextTraceMap }, + ); + + if (esm) { + yield* it; + } else { + for (const report of it) { + report.path = report.path.filter(exceptDefault); + if ( + report.path.length >= 2 || + report.type !== READ + ) { + yield report; + } + } + } + } + } + } + } + + /** + * Iterate the property references for a given expression AST node. + * @template T + * @param {Expression} node The expression AST node to iterate property references. + * @param {TraceMap} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate property references. + */ + *iteratePropertyReferences(node, traceMap) { + yield* this._iteratePropertyReferences(node, [], traceMap); + } + + /** + * Iterate the references for a given variable. + * @private + * @template T + * @param {Variable} variable The variable to iterate that references. + * @param {string[]} path The current path. + * @param {TraceMapObject} traceMap The trace map. + * @param {boolean} shouldReport = The flag to report those references. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *_iterateVariableReferences(variable, path, traceMap, shouldReport) { + if (this.variableStack.includes(variable)) { + return + } + this.variableStack.push(variable); + try { + for (const reference of variable.references) { + if (!reference.isRead()) { + continue + } + const node = /** @type {RuleNode & Identifier} */ ( + reference.identifier + ); + + if (shouldReport && traceMap[READ]) { + yield { node, path, type: READ, info: traceMap[READ] }; + } + yield* this._iteratePropertyReferences(node, path, traceMap); + } + } finally { + this.variableStack.pop(); + } + } + + /** + * Iterate the references for a given AST node. + * @private + * @template T + * @param {Expression} rootNode The AST node to iterate references. + * @param {string[]} path The current path. + * @param {TraceMapObject} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + //eslint-disable-next-line complexity + *_iteratePropertyReferences(rootNode, path, traceMap) { + let node = rootNode; + while (isPassThrough(node)) { + node = node.parent; + } + + const parent = /** @type {RuleNode} */ (node).parent; + if (parent.type === "MemberExpression") { + if (parent.object === node) { + const key = getPropertyName(parent); + if (key == null || !has(traceMap, key)) { + return + } + + path = path.concat(key); //eslint-disable-line no-param-reassign + const nextTraceMap = traceMap[key]; + if (nextTraceMap[READ]) { + yield { + node: parent, + path, + type: READ, + info: nextTraceMap[READ], + }; + } + yield* this._iteratePropertyReferences( + parent, + path, + nextTraceMap, + ); + } + return + } + if (parent.type === "CallExpression") { + if (parent.callee === node && traceMap[CALL]) { + yield { node: parent, path, type: CALL, info: traceMap[CALL] }; + } + return + } + if (parent.type === "NewExpression") { + if (parent.callee === node && traceMap[CONSTRUCT]) { + yield { + node: parent, + path, + type: CONSTRUCT, + info: traceMap[CONSTRUCT], + }; + } + return + } + if (parent.type === "AssignmentExpression") { + if (parent.right === node) { + yield* this._iterateLhsReferences(parent.left, path, traceMap); + yield* this._iteratePropertyReferences(parent, path, traceMap); + } + return + } + if (parent.type === "AssignmentPattern") { + if (parent.right === node) { + yield* this._iterateLhsReferences(parent.left, path, traceMap); + } + return + } + if (parent.type === "VariableDeclarator") { + if (parent.init === node) { + yield* this._iterateLhsReferences(parent.id, path, traceMap); + } + } + } + + /** + * Iterate the references for a given Pattern node. + * @private + * @template T + * @param {Pattern} patternNode The Pattern node to iterate references. + * @param {string[]} path The current path. + * @param {TraceMapObject} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *_iterateLhsReferences(patternNode, path, traceMap) { + if (patternNode.type === "Identifier") { + const variable = findVariable(this.globalScope, patternNode); + if (variable != null) { + yield* this._iterateVariableReferences( + variable, + path, + traceMap, + false, + ); + } + return + } + if (patternNode.type === "ObjectPattern") { + for (const property of patternNode.properties) { + const key = getPropertyName( + /** @type {AssignmentProperty} */ (property), + ); + + if (key == null || !has(traceMap, key)) { + continue + } + + const nextPath = path.concat(key); + const nextTraceMap = traceMap[key]; + if (nextTraceMap[READ]) { + yield { + node: /** @type {RuleNode} */ (property), + path: nextPath, + type: READ, + info: nextTraceMap[READ], + }; + } + yield* this._iterateLhsReferences( + /** @type {AssignmentProperty} */ (property).value, + nextPath, + nextTraceMap, + ); + } + return + } + if (patternNode.type === "AssignmentPattern") { + yield* this._iterateLhsReferences(patternNode.left, path, traceMap); + } + } + + /** + * Iterate the references for a given ModuleSpecifier node. + * @private + * @template T + * @param {ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier} specifierNode The ModuleSpecifier node to iterate references. + * @param {string[]} path The current path. + * @param {TraceMapObject} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *_iterateImportReferences(specifierNode, path, traceMap) { + const type = specifierNode.type; + + if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") { + const key = + type === "ImportDefaultSpecifier" + ? "default" + : specifierNode.imported.type === "Identifier" + ? specifierNode.imported.name + : specifierNode.imported.value; + if (!has(traceMap, key)) { + return + } + + path = path.concat(key); //eslint-disable-line no-param-reassign + const nextTraceMap = traceMap[key]; + if (nextTraceMap[READ]) { + yield { + node: /** @type {RuleNode} */ (specifierNode), + path, + type: READ, + info: nextTraceMap[READ], + }; + } + yield* this._iterateVariableReferences( + /** @type {Variable} */ ( + findVariable(this.globalScope, specifierNode.local) + ), + path, + nextTraceMap, + false, + ); + + return + } + + if (type === "ImportNamespaceSpecifier") { + yield* this._iterateVariableReferences( + /** @type {Variable} */ ( + findVariable(this.globalScope, specifierNode.local) + ), + path, + traceMap, + false, + ); + return + } + + if (type === "ExportSpecifier") { + const key = + specifierNode.local.type === "Identifier" + ? specifierNode.local.name + : specifierNode.local.value; + if (!has(traceMap, key)) { + return + } + + path = path.concat(key); //eslint-disable-line no-param-reassign + const nextTraceMap = traceMap[key]; + if (nextTraceMap[READ]) { + yield { + node: /** @type {RuleNode} */ (specifierNode), + path, + type: READ, + info: nextTraceMap[READ], + }; + } + } + } +} + +ReferenceTracker.READ = READ; +ReferenceTracker.CALL = CALL; +ReferenceTracker.CONSTRUCT = CONSTRUCT; +ReferenceTracker.ESM = ESM; + +/** + * This is a predicate function for Array#filter. + * @param {string} name A name part. + * @param {number} index The index of the name. + * @returns {boolean} `false` if it's default. + */ +function exceptDefault(name, index) { + return !(index === 1 && name === "default") +} + +/** @typedef {import("./types.mjs").StaticValue} StaticValue */ + +var index = { + CALL, + CONSTRUCT, + ESM, + findVariable, + getFunctionHeadLocation, + getFunctionNameWithKind, + getInnermostScope, + getPropertyName, + getStaticValue, + getStringIfConstant, + hasSideEffect, + isArrowToken, + isClosingBraceToken, + isClosingBracketToken, + isClosingParenToken, + isColonToken, + isCommaToken, + isCommentToken, + isNotArrowToken, + isNotClosingBraceToken, + isNotClosingBracketToken, + isNotClosingParenToken, + isNotColonToken, + isNotCommaToken, + isNotCommentToken, + isNotOpeningBraceToken, + isNotOpeningBracketToken, + isNotOpeningParenToken, + isNotSemicolonToken, + isOpeningBraceToken, + isOpeningBracketToken, + isOpeningParenToken, + isParenthesized, + isSemicolonToken, + PatternMatcher, + READ, + ReferenceTracker, +}; + +exports.CALL = CALL; +exports.CONSTRUCT = CONSTRUCT; +exports.ESM = ESM; +exports.PatternMatcher = PatternMatcher; +exports.READ = READ; +exports.ReferenceTracker = ReferenceTracker; +exports["default"] = index; +exports.findVariable = findVariable; +exports.getFunctionHeadLocation = getFunctionHeadLocation; +exports.getFunctionNameWithKind = getFunctionNameWithKind; +exports.getInnermostScope = getInnermostScope; +exports.getPropertyName = getPropertyName; +exports.getStaticValue = getStaticValue; +exports.getStringIfConstant = getStringIfConstant; +exports.hasSideEffect = hasSideEffect; +exports.isArrowToken = isArrowToken; +exports.isClosingBraceToken = isClosingBraceToken; +exports.isClosingBracketToken = isClosingBracketToken; +exports.isClosingParenToken = isClosingParenToken; +exports.isColonToken = isColonToken; +exports.isCommaToken = isCommaToken; +exports.isCommentToken = isCommentToken; +exports.isNotArrowToken = isNotArrowToken; +exports.isNotClosingBraceToken = isNotClosingBraceToken; +exports.isNotClosingBracketToken = isNotClosingBracketToken; +exports.isNotClosingParenToken = isNotClosingParenToken; +exports.isNotColonToken = isNotColonToken; +exports.isNotCommaToken = isNotCommaToken; +exports.isNotCommentToken = isNotCommentToken; +exports.isNotOpeningBraceToken = isNotOpeningBraceToken; +exports.isNotOpeningBracketToken = isNotOpeningBracketToken; +exports.isNotOpeningParenToken = isNotOpeningParenToken; +exports.isNotSemicolonToken = isNotSemicolonToken; +exports.isOpeningBraceToken = isOpeningBraceToken; +exports.isOpeningBracketToken = isOpeningBracketToken; +exports.isOpeningParenToken = isOpeningParenToken; +exports.isParenthesized = isParenthesized; +exports.isSemicolonToken = isSemicolonToken; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@eslint-community/eslint-utils/index.js.map b/node_modules/@eslint-community/eslint-utils/index.js.map new file mode 100644 index 00000000..ba72594c --- /dev/null +++ b/node_modules/@eslint-community/eslint-utils/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["src/get-innermost-scope.mjs","src/find-variable.mjs","src/token-predicate.mjs","src/get-function-head-location.mjs","src/get-static-value.mjs","src/get-string-if-constant.mjs","src/get-property-name.mjs","src/get-function-name-with-kind.mjs","src/has-side-effect.mjs","src/is-parenthesized.mjs","src/pattern-matcher.mjs","src/reference-tracker.mjs","src/index.mjs"],"sourcesContent":["/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"estree\").Node} Node */\n\n/**\n * Get the innermost scope which contains a given location.\n * @param {Scope} initialScope The initial scope to search.\n * @param {Node} node The location to search.\n * @returns {Scope} The innermost scope.\n */\nexport function getInnermostScope(initialScope, node) {\n const location = /** @type {[number, number]} */ (node.range)[0]\n\n let scope = initialScope\n let found = false\n do {\n found = false\n for (const childScope of scope.childScopes) {\n const range = /** @type {[number, number]} */ (\n childScope.block.range\n )\n\n if (range[0] <= location && location < range[1]) {\n scope = childScope\n found = true\n break\n }\n }\n } while (found)\n\n return scope\n}\n","import { getInnermostScope } from \"./get-innermost-scope.mjs\"\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"eslint\").Scope.Variable} Variable */\n/** @typedef {import(\"estree\").Identifier} Identifier */\n\n/**\n * Find the variable of a given name.\n * @param {Scope} initialScope The scope to start finding.\n * @param {string|Identifier} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.\n * @returns {Variable|null} The found variable or null.\n */\nexport function findVariable(initialScope, nameOrNode) {\n let name = \"\"\n /** @type {Scope|null} */\n let scope = initialScope\n\n if (typeof nameOrNode === \"string\") {\n name = nameOrNode\n } else {\n name = nameOrNode.name\n scope = getInnermostScope(scope, nameOrNode)\n }\n\n while (scope != null) {\n const variable = scope.set.get(name)\n if (variable != null) {\n return variable\n }\n scope = scope.upper\n }\n\n return null\n}\n","/** @typedef {import(\"eslint\").AST.Token} Token */\n/** @typedef {import(\"estree\").Comment} Comment */\n/** @typedef {import(\"./types.mjs\").ArrowToken} ArrowToken */\n/** @typedef {import(\"./types.mjs\").CommaToken} CommaToken */\n/** @typedef {import(\"./types.mjs\").SemicolonToken} SemicolonToken */\n/** @typedef {import(\"./types.mjs\").ColonToken} ColonToken */\n/** @typedef {import(\"./types.mjs\").OpeningParenToken} OpeningParenToken */\n/** @typedef {import(\"./types.mjs\").ClosingParenToken} ClosingParenToken */\n/** @typedef {import(\"./types.mjs\").OpeningBracketToken} OpeningBracketToken */\n/** @typedef {import(\"./types.mjs\").ClosingBracketToken} ClosingBracketToken */\n/** @typedef {import(\"./types.mjs\").OpeningBraceToken} OpeningBraceToken */\n/** @typedef {import(\"./types.mjs\").ClosingBraceToken} ClosingBraceToken */\n/**\n * @template {string} Value\n * @typedef {import(\"./types.mjs\").PunctuatorToken} PunctuatorToken\n */\n\n/** @typedef {Comment | Token} CommentOrToken */\n\n/**\n * Creates the negate function of the given function.\n * @param {function(CommentOrToken):boolean} f - The function to negate.\n * @returns {function(CommentOrToken):boolean} Negated function.\n */\nfunction negate(f) {\n return (token) => !f(token)\n}\n\n/**\n * Checks if the given token is a PunctuatorToken with the given value\n * @template {string} Value\n * @param {CommentOrToken} token - The token to check.\n * @param {Value} value - The value to check.\n * @returns {token is PunctuatorToken} `true` if the token is a PunctuatorToken with the given value.\n */\nfunction isPunctuatorTokenWithValue(token, value) {\n return token.type === \"Punctuator\" && token.value === value\n}\n\n/**\n * Checks if the given token is an arrow token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ArrowToken} `true` if the token is an arrow token.\n */\nexport function isArrowToken(token) {\n return isPunctuatorTokenWithValue(token, \"=>\")\n}\n\n/**\n * Checks if the given token is a comma token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is CommaToken} `true` if the token is a comma token.\n */\nexport function isCommaToken(token) {\n return isPunctuatorTokenWithValue(token, \",\")\n}\n\n/**\n * Checks if the given token is a semicolon token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is SemicolonToken} `true` if the token is a semicolon token.\n */\nexport function isSemicolonToken(token) {\n return isPunctuatorTokenWithValue(token, \";\")\n}\n\n/**\n * Checks if the given token is a colon token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ColonToken} `true` if the token is a colon token.\n */\nexport function isColonToken(token) {\n return isPunctuatorTokenWithValue(token, \":\")\n}\n\n/**\n * Checks if the given token is an opening parenthesis token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is OpeningParenToken} `true` if the token is an opening parenthesis token.\n */\nexport function isOpeningParenToken(token) {\n return isPunctuatorTokenWithValue(token, \"(\")\n}\n\n/**\n * Checks if the given token is a closing parenthesis token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ClosingParenToken} `true` if the token is a closing parenthesis token.\n */\nexport function isClosingParenToken(token) {\n return isPunctuatorTokenWithValue(token, \")\")\n}\n\n/**\n * Checks if the given token is an opening square bracket token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is OpeningBracketToken} `true` if the token is an opening square bracket token.\n */\nexport function isOpeningBracketToken(token) {\n return isPunctuatorTokenWithValue(token, \"[\")\n}\n\n/**\n * Checks if the given token is a closing square bracket token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ClosingBracketToken} `true` if the token is a closing square bracket token.\n */\nexport function isClosingBracketToken(token) {\n return isPunctuatorTokenWithValue(token, \"]\")\n}\n\n/**\n * Checks if the given token is an opening brace token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is OpeningBraceToken} `true` if the token is an opening brace token.\n */\nexport function isOpeningBraceToken(token) {\n return isPunctuatorTokenWithValue(token, \"{\")\n}\n\n/**\n * Checks if the given token is a closing brace token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ClosingBraceToken} `true` if the token is a closing brace token.\n */\nexport function isClosingBraceToken(token) {\n return isPunctuatorTokenWithValue(token, \"}\")\n}\n\n/**\n * Checks if the given token is a comment token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is Comment} `true` if the token is a comment token.\n */\nexport function isCommentToken(token) {\n return [\"Block\", \"Line\", \"Shebang\"].includes(token.type)\n}\n\nexport const isNotArrowToken = negate(isArrowToken)\nexport const isNotCommaToken = negate(isCommaToken)\nexport const isNotSemicolonToken = negate(isSemicolonToken)\nexport const isNotColonToken = negate(isColonToken)\nexport const isNotOpeningParenToken = negate(isOpeningParenToken)\nexport const isNotClosingParenToken = negate(isClosingParenToken)\nexport const isNotOpeningBracketToken = negate(isOpeningBracketToken)\nexport const isNotClosingBracketToken = negate(isClosingBracketToken)\nexport const isNotOpeningBraceToken = negate(isOpeningBraceToken)\nexport const isNotClosingBraceToken = negate(isClosingBraceToken)\nexport const isNotCommentToken = negate(isCommentToken)\n","import { isArrowToken, isOpeningParenToken } from \"./token-predicate.mjs\"\n/** @typedef {import(\"eslint\").Rule.Node} RuleNode */\n/** @typedef {import(\"eslint\").SourceCode} SourceCode */\n/** @typedef {import(\"eslint\").AST.Token} Token */\n/** @typedef {import(\"estree\").Function} FunctionNode */\n/** @typedef {import(\"estree\").FunctionDeclaration} FunctionDeclaration */\n/** @typedef {import(\"estree\").FunctionExpression} FunctionExpression */\n/** @typedef {import(\"estree\").SourceLocation} SourceLocation */\n/** @typedef {import(\"estree\").Position} Position */\n\n/**\n * Get the `(` token of the given function node.\n * @param {FunctionExpression | FunctionDeclaration} node - The function node to get.\n * @param {SourceCode} sourceCode - The source code object to get tokens.\n * @returns {Token} `(` token.\n */\nfunction getOpeningParenOfParams(node, sourceCode) {\n return node.id\n ? /** @type {Token} */ (\n sourceCode.getTokenAfter(node.id, isOpeningParenToken)\n )\n : /** @type {Token} */ (\n sourceCode.getFirstToken(node, isOpeningParenToken)\n )\n}\n\n/**\n * Get the location of the given function node for reporting.\n * @param {FunctionNode} node - The function node to get.\n * @param {SourceCode} sourceCode - The source code object to get tokens.\n * @returns {SourceLocation|null} The location of the function node for reporting.\n */\nexport function getFunctionHeadLocation(node, sourceCode) {\n const parent = /** @type {RuleNode} */ (node).parent\n\n /** @type {Position|null} */\n let start = null\n /** @type {Position|null} */\n let end = null\n\n if (node.type === \"ArrowFunctionExpression\") {\n const arrowToken = /** @type {Token} */ (\n sourceCode.getTokenBefore(node.body, isArrowToken)\n )\n\n start = arrowToken.loc.start\n end = arrowToken.loc.end\n } else if (\n parent.type === \"Property\" ||\n parent.type === \"MethodDefinition\" ||\n parent.type === \"PropertyDefinition\"\n ) {\n start = /** @type {SourceLocation} */ (parent.loc).start\n end = getOpeningParenOfParams(node, sourceCode).loc.start\n } else {\n start = /** @type {SourceLocation} */ (node.loc).start\n end = getOpeningParenOfParams(node, sourceCode).loc.start\n }\n\n return {\n start: { ...start },\n end: { ...end },\n }\n}\n","/* globals globalThis, global, self, window */\n\nimport { findVariable } from \"./find-variable.mjs\"\n/** @typedef {import(\"./types.mjs\").StaticValue} StaticValue */\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.Node} TSESTreeNode */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.AST_NODE_TYPES} TSESTreeNodeTypes */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.MemberExpression} MemberExpression */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.Property} Property */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.RegExpLiteral} RegExpLiteral */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.BigIntLiteral} BigIntLiteral */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.Literal} Literal */\n\nconst globalObject =\n typeof globalThis !== \"undefined\"\n ? globalThis\n : // @ts-ignore\n typeof self !== \"undefined\"\n ? // @ts-ignore\n self\n : // @ts-ignore\n typeof window !== \"undefined\"\n ? // @ts-ignore\n window\n : typeof global !== \"undefined\"\n ? global\n : {}\n\nconst builtinNames = Object.freeze(\n new Set([\n \"Array\",\n \"ArrayBuffer\",\n \"BigInt\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n \"Boolean\",\n \"DataView\",\n \"Date\",\n \"decodeURI\",\n \"decodeURIComponent\",\n \"encodeURI\",\n \"encodeURIComponent\",\n \"escape\",\n \"Float32Array\",\n \"Float64Array\",\n \"Function\",\n \"Infinity\",\n \"Int16Array\",\n \"Int32Array\",\n \"Int8Array\",\n \"isFinite\",\n \"isNaN\",\n \"isPrototypeOf\",\n \"JSON\",\n \"Map\",\n \"Math\",\n \"NaN\",\n \"Number\",\n \"Object\",\n \"parseFloat\",\n \"parseInt\",\n \"Promise\",\n \"Proxy\",\n \"Reflect\",\n \"RegExp\",\n \"Set\",\n \"String\",\n \"Symbol\",\n \"Uint16Array\",\n \"Uint32Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"undefined\",\n \"unescape\",\n \"WeakMap\",\n \"WeakSet\",\n ]),\n)\nconst callAllowed = new Set(\n [\n Array.isArray,\n Array.of,\n Array.prototype.at,\n Array.prototype.concat,\n Array.prototype.entries,\n Array.prototype.every,\n Array.prototype.filter,\n Array.prototype.find,\n Array.prototype.findIndex,\n Array.prototype.flat,\n Array.prototype.includes,\n Array.prototype.indexOf,\n Array.prototype.join,\n Array.prototype.keys,\n Array.prototype.lastIndexOf,\n Array.prototype.slice,\n Array.prototype.some,\n Array.prototype.toString,\n Array.prototype.values,\n typeof BigInt === \"function\" ? BigInt : undefined,\n Boolean,\n Date,\n Date.parse,\n decodeURI,\n decodeURIComponent,\n encodeURI,\n encodeURIComponent,\n escape,\n isFinite,\n isNaN,\n // @ts-ignore\n isPrototypeOf,\n Map,\n Map.prototype.entries,\n Map.prototype.get,\n Map.prototype.has,\n Map.prototype.keys,\n Map.prototype.values,\n .../** @type {(keyof typeof Math)[]} */ (\n Object.getOwnPropertyNames(Math)\n )\n .filter((k) => k !== \"random\")\n .map((k) => Math[k])\n .filter((f) => typeof f === \"function\"),\n Number,\n Number.isFinite,\n Number.isNaN,\n Number.parseFloat,\n Number.parseInt,\n Number.prototype.toExponential,\n Number.prototype.toFixed,\n Number.prototype.toPrecision,\n Number.prototype.toString,\n Object,\n Object.entries,\n Object.is,\n Object.isExtensible,\n Object.isFrozen,\n Object.isSealed,\n Object.keys,\n Object.values,\n parseFloat,\n parseInt,\n RegExp,\n Set,\n Set.prototype.entries,\n Set.prototype.has,\n Set.prototype.keys,\n Set.prototype.values,\n String,\n String.fromCharCode,\n String.fromCodePoint,\n String.raw,\n String.prototype.at,\n String.prototype.charAt,\n String.prototype.charCodeAt,\n String.prototype.codePointAt,\n String.prototype.concat,\n String.prototype.endsWith,\n String.prototype.includes,\n String.prototype.indexOf,\n String.prototype.lastIndexOf,\n String.prototype.normalize,\n String.prototype.padEnd,\n String.prototype.padStart,\n String.prototype.slice,\n String.prototype.startsWith,\n String.prototype.substr,\n String.prototype.substring,\n String.prototype.toLowerCase,\n String.prototype.toString,\n String.prototype.toUpperCase,\n String.prototype.trim,\n String.prototype.trimEnd,\n String.prototype.trimLeft,\n String.prototype.trimRight,\n String.prototype.trimStart,\n Symbol.for,\n Symbol.keyFor,\n unescape,\n ].filter((f) => typeof f === \"function\"),\n)\nconst callPassThrough = new Set([\n Object.freeze,\n Object.preventExtensions,\n Object.seal,\n])\n\n/** @type {ReadonlyArray]>} */\nconst getterAllowed = [\n [Map, new Set([\"size\"])],\n [\n RegExp,\n new Set([\n \"dotAll\",\n \"flags\",\n \"global\",\n \"hasIndices\",\n \"ignoreCase\",\n \"multiline\",\n \"source\",\n \"sticky\",\n \"unicode\",\n ]),\n ],\n [Set, new Set([\"size\"])],\n]\n\n/**\n * Get the property descriptor.\n * @param {object} object The object to get.\n * @param {string|number|symbol} name The property name to get.\n */\nfunction getPropertyDescriptor(object, name) {\n let x = object\n while ((typeof x === \"object\" || typeof x === \"function\") && x !== null) {\n const d = Object.getOwnPropertyDescriptor(x, name)\n if (d) {\n return d\n }\n x = Object.getPrototypeOf(x)\n }\n return null\n}\n\n/**\n * Check if a property is getter or not.\n * @param {object} object The object to check.\n * @param {string|number|symbol} name The property name to check.\n */\nfunction isGetter(object, name) {\n const d = getPropertyDescriptor(object, name)\n return d != null && d.get != null\n}\n\n/**\n * Get the element values of a given node list.\n * @param {(Node|TSESTreeNode|null)[]} nodeList The node list to get values.\n * @param {Scope|undefined|null} initialScope The initial scope to find variables.\n * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.\n */\nfunction getElementValues(nodeList, initialScope) {\n const valueList = []\n\n for (let i = 0; i < nodeList.length; ++i) {\n const elementNode = nodeList[i]\n\n if (elementNode == null) {\n valueList.length = i + 1\n } else if (elementNode.type === \"SpreadElement\") {\n const argument = getStaticValueR(elementNode.argument, initialScope)\n if (argument == null) {\n return null\n }\n valueList.push(.../** @type {Iterable} */ (argument.value))\n } else {\n const element = getStaticValueR(elementNode, initialScope)\n if (element == null) {\n return null\n }\n valueList.push(element.value)\n }\n }\n\n return valueList\n}\n\n/**\n * Returns whether the given variable is never written to after initialization.\n * @param {import(\"eslint\").Scope.Variable} variable\n * @returns {boolean}\n */\nfunction isEffectivelyConst(variable) {\n const refs = variable.references\n\n const inits = refs.filter((r) => r.init).length\n const reads = refs.filter((r) => r.isReadOnly()).length\n if (inits === 1 && reads + inits === refs.length) {\n // there is only one init and all other references only read\n return true\n }\n return false\n}\n\n/**\n * @template {TSESTreeNodeTypes} T\n * @callback VisitorCallback\n * @param {TSESTreeNode & { type: T }} node\n * @param {Scope|undefined|null} initialScope\n * @returns {StaticValue | null}\n */\n/**\n * @typedef { { [K in TSESTreeNodeTypes]?: VisitorCallback } } Operations\n */\n/**\n * @type {Operations}\n */\nconst operations = Object.freeze({\n ArrayExpression(node, initialScope) {\n const elements = getElementValues(node.elements, initialScope)\n return elements != null ? { value: elements } : null\n },\n\n AssignmentExpression(node, initialScope) {\n if (node.operator === \"=\") {\n return getStaticValueR(node.right, initialScope)\n }\n return null\n },\n\n //eslint-disable-next-line complexity\n BinaryExpression(node, initialScope) {\n if (node.operator === \"in\" || node.operator === \"instanceof\") {\n // Not supported.\n return null\n }\n\n const left = getStaticValueR(node.left, initialScope)\n const right = getStaticValueR(node.right, initialScope)\n if (left != null && right != null) {\n switch (node.operator) {\n case \"==\":\n return { value: left.value == right.value } //eslint-disable-line eqeqeq\n case \"!=\":\n return { value: left.value != right.value } //eslint-disable-line eqeqeq\n case \"===\":\n return { value: left.value === right.value }\n case \"!==\":\n return { value: left.value !== right.value }\n case \"<\":\n return {\n value:\n /** @type {any} */ (left.value) <\n /** @type {any} */ (right.value),\n }\n case \"<=\":\n return {\n value:\n /** @type {any} */ (left.value) <=\n /** @type {any} */ (right.value),\n }\n case \">\":\n return {\n value:\n /** @type {any} */ (left.value) >\n /** @type {any} */ (right.value),\n }\n case \">=\":\n return {\n value:\n /** @type {any} */ (left.value) >=\n /** @type {any} */ (right.value),\n }\n case \"<<\":\n return {\n value:\n /** @type {any} */ (left.value) <<\n /** @type {any} */ (right.value),\n }\n case \">>\":\n return {\n value:\n /** @type {any} */ (left.value) >>\n /** @type {any} */ (right.value),\n }\n case \">>>\":\n return {\n value:\n /** @type {any} */ (left.value) >>>\n /** @type {any} */ (right.value),\n }\n case \"+\":\n return {\n value:\n /** @type {any} */ (left.value) +\n /** @type {any} */ (right.value),\n }\n case \"-\":\n return {\n value:\n /** @type {any} */ (left.value) -\n /** @type {any} */ (right.value),\n }\n case \"*\":\n return {\n value:\n /** @type {any} */ (left.value) *\n /** @type {any} */ (right.value),\n }\n case \"/\":\n return {\n value:\n /** @type {any} */ (left.value) /\n /** @type {any} */ (right.value),\n }\n case \"%\":\n return {\n value:\n /** @type {any} */ (left.value) %\n /** @type {any} */ (right.value),\n }\n case \"**\":\n return {\n value:\n /** @type {any} */ (left.value) **\n /** @type {any} */ (right.value),\n }\n case \"|\":\n return {\n value:\n /** @type {any} */ (left.value) |\n /** @type {any} */ (right.value),\n }\n case \"^\":\n return {\n value:\n /** @type {any} */ (left.value) ^\n /** @type {any} */ (right.value),\n }\n case \"&\":\n return {\n value:\n /** @type {any} */ (left.value) &\n /** @type {any} */ (right.value),\n }\n\n // no default\n }\n }\n\n return null\n },\n\n CallExpression(node, initialScope) {\n const calleeNode = node.callee\n const args = getElementValues(node.arguments, initialScope)\n\n if (args != null) {\n if (calleeNode.type === \"MemberExpression\") {\n if (calleeNode.property.type === \"PrivateIdentifier\") {\n return null\n }\n const object = getStaticValueR(calleeNode.object, initialScope)\n if (object != null) {\n if (\n object.value == null &&\n (object.optional || node.optional)\n ) {\n return { value: undefined, optional: true }\n }\n const property = getStaticPropertyNameValue(\n calleeNode,\n initialScope,\n )\n\n if (property != null) {\n const receiver =\n /** @type {Record any>} */ (\n object.value\n )\n const methodName = /** @type {PropertyKey} */ (\n property.value\n )\n if (callAllowed.has(receiver[methodName])) {\n return {\n value: receiver[methodName](...args),\n }\n }\n if (callPassThrough.has(receiver[methodName])) {\n return { value: args[0] }\n }\n }\n }\n } else {\n const callee = getStaticValueR(calleeNode, initialScope)\n if (callee != null) {\n if (callee.value == null && node.optional) {\n return { value: undefined, optional: true }\n }\n const func = /** @type {(...args: any[]) => any} */ (\n callee.value\n )\n if (callAllowed.has(func)) {\n return { value: func(...args) }\n }\n if (callPassThrough.has(func)) {\n return { value: args[0] }\n }\n }\n }\n }\n\n return null\n },\n\n ConditionalExpression(node, initialScope) {\n const test = getStaticValueR(node.test, initialScope)\n if (test != null) {\n return test.value\n ? getStaticValueR(node.consequent, initialScope)\n : getStaticValueR(node.alternate, initialScope)\n }\n return null\n },\n\n ExpressionStatement(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n\n Identifier(node, initialScope) {\n if (initialScope != null) {\n const variable = findVariable(initialScope, node)\n\n // Built-in globals.\n if (\n variable != null &&\n variable.defs.length === 0 &&\n builtinNames.has(variable.name) &&\n variable.name in globalObject\n ) {\n return { value: globalObject[variable.name] }\n }\n\n // Constants.\n if (variable != null && variable.defs.length === 1) {\n const def = variable.defs[0]\n if (\n def.parent &&\n def.type === \"Variable\" &&\n (def.parent.kind === \"const\" ||\n isEffectivelyConst(variable)) &&\n // TODO(mysticatea): don't support destructuring here.\n def.node.id.type === \"Identifier\"\n ) {\n return getStaticValueR(def.node.init, initialScope)\n }\n }\n }\n return null\n },\n\n Literal(node) {\n const literal =\n /** @type {Partial & Partial & Partial} */ (\n node\n )\n //istanbul ignore if : this is implementation-specific behavior.\n if (\n (literal.regex != null || literal.bigint != null) &&\n literal.value == null\n ) {\n // It was a RegExp/BigInt literal, but Node.js didn't support it.\n return null\n }\n return { value: literal.value }\n },\n\n LogicalExpression(node, initialScope) {\n const left = getStaticValueR(node.left, initialScope)\n if (left != null) {\n if (\n (node.operator === \"||\" && Boolean(left.value) === true) ||\n (node.operator === \"&&\" && Boolean(left.value) === false) ||\n (node.operator === \"??\" && left.value != null)\n ) {\n return left\n }\n\n const right = getStaticValueR(node.right, initialScope)\n if (right != null) {\n return right\n }\n }\n\n return null\n },\n\n MemberExpression(node, initialScope) {\n if (node.property.type === \"PrivateIdentifier\") {\n return null\n }\n const object = getStaticValueR(node.object, initialScope)\n if (object != null) {\n if (object.value == null && (object.optional || node.optional)) {\n return { value: undefined, optional: true }\n }\n const property = getStaticPropertyNameValue(node, initialScope)\n\n if (property != null) {\n if (\n !isGetter(\n /** @type {object} */ (object.value),\n /** @type {PropertyKey} */ (property.value),\n )\n ) {\n return {\n value: /** @type {Record} */ (\n object.value\n )[/** @type {PropertyKey} */ (property.value)],\n }\n }\n\n for (const [classFn, allowed] of getterAllowed) {\n if (\n object.value instanceof classFn &&\n allowed.has(/** @type {string} */ (property.value))\n ) {\n return {\n value: /** @type {Record} */ (\n object.value\n )[/** @type {PropertyKey} */ (property.value)],\n }\n }\n }\n }\n }\n return null\n },\n\n ChainExpression(node, initialScope) {\n const expression = getStaticValueR(node.expression, initialScope)\n if (expression != null) {\n return { value: expression.value }\n }\n return null\n },\n\n NewExpression(node, initialScope) {\n const callee = getStaticValueR(node.callee, initialScope)\n const args = getElementValues(node.arguments, initialScope)\n\n if (callee != null && args != null) {\n const Func = /** @type {new (...args: any[]) => any} */ (\n callee.value\n )\n if (callAllowed.has(Func)) {\n return { value: new Func(...args) }\n }\n }\n\n return null\n },\n\n ObjectExpression(node, initialScope) {\n /** @type {Record} */\n const object = {}\n\n for (const propertyNode of node.properties) {\n if (propertyNode.type === \"Property\") {\n if (propertyNode.kind !== \"init\") {\n return null\n }\n const key = getStaticPropertyNameValue(\n propertyNode,\n initialScope,\n )\n const value = getStaticValueR(propertyNode.value, initialScope)\n if (key == null || value == null) {\n return null\n }\n object[/** @type {PropertyKey} */ (key.value)] = value.value\n } else if (\n propertyNode.type === \"SpreadElement\" ||\n // @ts-expect-error -- Backward compatibility\n propertyNode.type === \"ExperimentalSpreadProperty\"\n ) {\n const argument = getStaticValueR(\n propertyNode.argument,\n initialScope,\n )\n if (argument == null) {\n return null\n }\n Object.assign(object, argument.value)\n } else {\n return null\n }\n }\n\n return { value: object }\n },\n\n SequenceExpression(node, initialScope) {\n const last = node.expressions[node.expressions.length - 1]\n return getStaticValueR(last, initialScope)\n },\n\n TaggedTemplateExpression(node, initialScope) {\n const tag = getStaticValueR(node.tag, initialScope)\n const expressions = getElementValues(\n node.quasi.expressions,\n initialScope,\n )\n\n if (tag != null && expressions != null) {\n const func = /** @type {(...args: any[]) => any} */ (tag.value)\n /** @type {any[] & { raw?: string[] }} */\n const strings = node.quasi.quasis.map((q) => q.value.cooked)\n strings.raw = node.quasi.quasis.map((q) => q.value.raw)\n\n if (func === String.raw) {\n return { value: func(strings, ...expressions) }\n }\n }\n\n return null\n },\n\n TemplateLiteral(node, initialScope) {\n const expressions = getElementValues(node.expressions, initialScope)\n if (expressions != null) {\n let value = node.quasis[0].value.cooked\n for (let i = 0; i < expressions.length; ++i) {\n value += expressions[i]\n value += /** @type {string} */ (node.quasis[i + 1].value.cooked)\n }\n return { value }\n }\n return null\n },\n\n UnaryExpression(node, initialScope) {\n if (node.operator === \"delete\") {\n // Not supported.\n return null\n }\n if (node.operator === \"void\") {\n return { value: undefined }\n }\n\n const arg = getStaticValueR(node.argument, initialScope)\n if (arg != null) {\n switch (node.operator) {\n case \"-\":\n return { value: -(/** @type {any} */ (arg.value)) }\n case \"+\":\n return { value: +(/** @type {any} */ (arg.value)) } //eslint-disable-line no-implicit-coercion\n case \"!\":\n return { value: !arg.value }\n case \"~\":\n return { value: ~(/** @type {any} */ (arg.value)) }\n case \"typeof\":\n return { value: typeof arg.value }\n\n // no default\n }\n }\n\n return null\n },\n TSAsExpression(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n TSSatisfiesExpression(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n TSTypeAssertion(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n TSNonNullExpression(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n TSInstantiationExpression(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n})\n\n/**\n * Get the value of a given node if it's a static value.\n * @param {Node|TSESTreeNode|null|undefined} node The node to get.\n * @param {Scope|undefined|null} initialScope The scope to start finding variable.\n * @returns {StaticValue|null} The static value of the node, or `null`.\n */\nfunction getStaticValueR(node, initialScope) {\n if (node != null && Object.hasOwnProperty.call(operations, node.type)) {\n return /** @type {VisitorCallback} */ (operations[node.type])(\n /** @type {TSESTreeNode} */ (node),\n initialScope,\n )\n }\n return null\n}\n\n/**\n * Get the static value of property name from a MemberExpression node or a Property node.\n * @param {MemberExpression|Property} node The node to get.\n * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.\n * @returns {StaticValue|null} The static value of the property name of the node, or `null`.\n */\nfunction getStaticPropertyNameValue(node, initialScope) {\n const nameNode = node.type === \"Property\" ? node.key : node.property\n\n if (node.computed) {\n return getStaticValueR(nameNode, initialScope)\n }\n\n if (nameNode.type === \"Identifier\") {\n return { value: nameNode.name }\n }\n\n if (nameNode.type === \"Literal\") {\n if (/** @type {Partial} */ (nameNode).bigint) {\n return { value: /** @type {BigIntLiteral} */ (nameNode).bigint }\n }\n return { value: String(nameNode.value) }\n }\n\n return null\n}\n\n/**\n * Get the value of a given node if it's a static value.\n * @param {Node} node The node to get.\n * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.\n * @returns {StaticValue | null} The static value of the node, or `null`.\n */\nexport function getStaticValue(node, initialScope = null) {\n try {\n return getStaticValueR(node, initialScope)\n } catch (_error) {\n return null\n }\n}\n","import { getStaticValue } from \"./get-static-value.mjs\"\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"estree\").RegExpLiteral} RegExpLiteral */\n/** @typedef {import(\"estree\").BigIntLiteral} BigIntLiteral */\n/** @typedef {import(\"estree\").SimpleLiteral} SimpleLiteral */\n\n/**\n * Get the value of a given node if it's a literal or a template literal.\n * @param {Node} node The node to get.\n * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.\n * @returns {string|null} The value of the node, or `null`.\n */\nexport function getStringIfConstant(node, initialScope = null) {\n // Handle the literals that the platform doesn't support natively.\n if (node && node.type === \"Literal\" && node.value === null) {\n const literal =\n /** @type {Partial & Partial & Partial} */ (\n node\n )\n if (literal.regex) {\n return `/${literal.regex.pattern}/${literal.regex.flags}`\n }\n if (literal.bigint) {\n return literal.bigint\n }\n }\n\n const evaluated = getStaticValue(node, initialScope)\n\n if (evaluated) {\n // `String(Symbol.prototype)` throws error\n try {\n return String(evaluated.value)\n } catch {\n // No op\n }\n }\n\n return null\n}\n","import { getStringIfConstant } from \"./get-string-if-constant.mjs\"\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"estree\").MemberExpression} MemberExpression */\n/** @typedef {import(\"estree\").MethodDefinition} MethodDefinition */\n/** @typedef {import(\"estree\").Property} Property */\n/** @typedef {import(\"estree\").PropertyDefinition} PropertyDefinition */\n/** @typedef {import(\"estree\").Identifier} Identifier */\n\n/**\n * Get the property name from a MemberExpression node or a Property node.\n * @param {MemberExpression | MethodDefinition | Property | PropertyDefinition} node The node to get.\n * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.\n * @returns {string|null|undefined} The property name of the node.\n */\nexport function getPropertyName(node, initialScope) {\n switch (node.type) {\n case \"MemberExpression\":\n if (node.computed) {\n return getStringIfConstant(node.property, initialScope)\n }\n if (node.property.type === \"PrivateIdentifier\") {\n return null\n }\n return /** @type {Partial} */ (node.property).name\n\n case \"Property\":\n case \"MethodDefinition\":\n case \"PropertyDefinition\":\n if (node.computed) {\n return getStringIfConstant(node.key, initialScope)\n }\n if (node.key.type === \"Literal\") {\n return String(node.key.value)\n }\n if (node.key.type === \"PrivateIdentifier\") {\n return null\n }\n return /** @type {Partial} */ (node.key).name\n\n default:\n break\n }\n\n return null\n}\n","import { getPropertyName } from \"./get-property-name.mjs\"\n/** @typedef {import(\"eslint\").Rule.Node} RuleNode */\n/** @typedef {import(\"eslint\").SourceCode} SourceCode */\n/** @typedef {import(\"estree\").Function} FunctionNode */\n/** @typedef {import(\"estree\").FunctionDeclaration} FunctionDeclaration */\n/** @typedef {import(\"estree\").FunctionExpression} FunctionExpression */\n/** @typedef {import(\"estree\").Identifier} Identifier */\n\n/**\n * Get the name and kind of the given function node.\n * @param {FunctionNode} node - The function node to get.\n * @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys.\n * @returns {string} The name and kind of the function node.\n */\n// eslint-disable-next-line complexity\nexport function getFunctionNameWithKind(node, sourceCode) {\n const parent = /** @type {RuleNode} */ (node).parent\n const tokens = []\n const isObjectMethod = parent.type === \"Property\" && parent.value === node\n const isClassMethod =\n parent.type === \"MethodDefinition\" && parent.value === node\n const isClassFieldMethod =\n parent.type === \"PropertyDefinition\" && parent.value === node\n\n // Modifiers.\n if (isClassMethod || isClassFieldMethod) {\n if (parent.static) {\n tokens.push(\"static\")\n }\n if (parent.key.type === \"PrivateIdentifier\") {\n tokens.push(\"private\")\n }\n }\n if (node.async) {\n tokens.push(\"async\")\n }\n if (node.generator) {\n tokens.push(\"generator\")\n }\n\n // Kinds.\n if (isObjectMethod || isClassMethod) {\n if (parent.kind === \"constructor\") {\n return \"constructor\"\n }\n if (parent.kind === \"get\") {\n tokens.push(\"getter\")\n } else if (parent.kind === \"set\") {\n tokens.push(\"setter\")\n } else {\n tokens.push(\"method\")\n }\n } else if (isClassFieldMethod) {\n tokens.push(\"method\")\n } else {\n if (node.type === \"ArrowFunctionExpression\") {\n tokens.push(\"arrow\")\n }\n tokens.push(\"function\")\n }\n\n // Names.\n if (isObjectMethod || isClassMethod || isClassFieldMethod) {\n if (parent.key.type === \"PrivateIdentifier\") {\n tokens.push(`#${parent.key.name}`)\n } else {\n const name = getPropertyName(parent)\n if (name) {\n tokens.push(`'${name}'`)\n } else if (sourceCode) {\n const keyText = sourceCode.getText(parent.key)\n if (!keyText.includes(\"\\n\")) {\n tokens.push(`[${keyText}]`)\n }\n }\n }\n } else if (hasId(node)) {\n tokens.push(`'${node.id.name}'`)\n } else if (\n parent.type === \"VariableDeclarator\" &&\n parent.id &&\n parent.id.type === \"Identifier\"\n ) {\n tokens.push(`'${parent.id.name}'`)\n } else if (\n (parent.type === \"AssignmentExpression\" ||\n parent.type === \"AssignmentPattern\") &&\n parent.left &&\n parent.left.type === \"Identifier\"\n ) {\n tokens.push(`'${parent.left.name}'`)\n } else if (\n parent.type === \"ExportDefaultDeclaration\" &&\n parent.declaration === node\n ) {\n tokens.push(\"'default'\")\n }\n\n return tokens.join(\" \")\n}\n\n/**\n * @param {FunctionNode} node\n * @returns {node is FunctionDeclaration | FunctionExpression & { id: Identifier }}\n */\nfunction hasId(node) {\n return Boolean(\n /** @type {Partial} */ (node)\n .id,\n )\n}\n","import { getKeys, KEYS } from \"eslint-visitor-keys\"\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"eslint\").SourceCode} SourceCode */\n/** @typedef {import(\"./types.mjs\").HasSideEffectOptions} HasSideEffectOptions */\n/** @typedef {import(\"estree\").BinaryExpression} BinaryExpression */\n/** @typedef {import(\"estree\").MemberExpression} MemberExpression */\n/** @typedef {import(\"estree\").MethodDefinition} MethodDefinition */\n/** @typedef {import(\"estree\").Property} Property */\n/** @typedef {import(\"estree\").PropertyDefinition} PropertyDefinition */\n/** @typedef {import(\"estree\").UnaryExpression} UnaryExpression */\n\nconst typeConversionBinaryOps = Object.freeze(\n new Set([\n \"==\",\n \"!=\",\n \"<\",\n \"<=\",\n \">\",\n \">=\",\n \"<<\",\n \">>\",\n \">>>\",\n \"+\",\n \"-\",\n \"*\",\n \"/\",\n \"%\",\n \"|\",\n \"^\",\n \"&\",\n \"in\",\n ]),\n)\nconst typeConversionUnaryOps = Object.freeze(new Set([\"-\", \"+\", \"!\", \"~\"]))\n\n/**\n * Check whether the given value is an ASTNode or not.\n * @param {any} x The value to check.\n * @returns {x is Node} `true` if the value is an ASTNode.\n */\nfunction isNode(x) {\n return x !== null && typeof x === \"object\" && typeof x.type === \"string\"\n}\n\nconst visitor = Object.freeze(\n Object.assign(Object.create(null), {\n /**\n * @param {Node} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n $visit(node, options, visitorKeys) {\n const { type } = node\n\n if (typeof (/** @type {any} */ (this)[type]) === \"function\") {\n return /** @type {any} */ (this)[type](\n node,\n options,\n visitorKeys,\n )\n }\n\n return this.$visitChildren(node, options, visitorKeys)\n },\n\n /**\n * @param {Node} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n $visitChildren(node, options, visitorKeys) {\n const { type } = node\n\n for (const key of /** @type {(keyof Node)[]} */ (\n visitorKeys[type] || getKeys(node)\n )) {\n const value = node[key]\n\n if (Array.isArray(value)) {\n for (const element of value) {\n if (\n isNode(element) &&\n this.$visit(element, options, visitorKeys)\n ) {\n return true\n }\n }\n } else if (\n isNode(value) &&\n this.$visit(value, options, visitorKeys)\n ) {\n return true\n }\n }\n\n return false\n },\n\n ArrowFunctionExpression() {\n return false\n },\n AssignmentExpression() {\n return true\n },\n AwaitExpression() {\n return true\n },\n /**\n * @param {BinaryExpression} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n BinaryExpression(node, options, visitorKeys) {\n if (\n options.considerImplicitTypeConversion &&\n typeConversionBinaryOps.has(node.operator) &&\n (node.left.type !== \"Literal\" || node.right.type !== \"Literal\")\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n CallExpression() {\n return true\n },\n FunctionExpression() {\n return false\n },\n ImportExpression() {\n return true\n },\n /**\n * @param {MemberExpression} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n MemberExpression(node, options, visitorKeys) {\n if (options.considerGetters) {\n return true\n }\n if (\n options.considerImplicitTypeConversion &&\n node.computed &&\n node.property.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n /**\n * @param {MethodDefinition} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n MethodDefinition(node, options, visitorKeys) {\n if (\n options.considerImplicitTypeConversion &&\n node.computed &&\n node.key.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n NewExpression() {\n return true\n },\n /**\n * @param {Property} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n Property(node, options, visitorKeys) {\n if (\n options.considerImplicitTypeConversion &&\n node.computed &&\n node.key.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n /**\n * @param {PropertyDefinition} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n PropertyDefinition(node, options, visitorKeys) {\n if (\n options.considerImplicitTypeConversion &&\n node.computed &&\n node.key.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n /**\n * @param {UnaryExpression} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n UnaryExpression(node, options, visitorKeys) {\n if (node.operator === \"delete\") {\n return true\n }\n if (\n options.considerImplicitTypeConversion &&\n typeConversionUnaryOps.has(node.operator) &&\n node.argument.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n UpdateExpression() {\n return true\n },\n YieldExpression() {\n return true\n },\n }),\n)\n\n/**\n * Check whether a given node has any side effect or not.\n * @param {Node} node The node to get.\n * @param {SourceCode} sourceCode The source code object.\n * @param {HasSideEffectOptions} [options] The option object.\n * @returns {boolean} `true` if the node has a certain side effect.\n */\nexport function hasSideEffect(node, sourceCode, options = {}) {\n const { considerGetters = false, considerImplicitTypeConversion = false } =\n options\n return visitor.$visit(\n node,\n { considerGetters, considerImplicitTypeConversion },\n sourceCode.visitorKeys || KEYS,\n )\n}\n","import { isClosingParenToken, isOpeningParenToken } from \"./token-predicate.mjs\"\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"eslint\").SourceCode} SourceCode */\n/** @typedef {import(\"eslint\").AST.Token} Token */\n/** @typedef {import(\"eslint\").Rule.Node} RuleNode */\n\n/**\n * Get the left parenthesis of the parent node syntax if it exists.\n * E.g., `if (a) {}` then the `(`.\n * @param {Node} node The AST node to check.\n * @param {SourceCode} sourceCode The source code object to get tokens.\n * @returns {Token|null} The left parenthesis of the parent node syntax\n */\nfunction getParentSyntaxParen(node, sourceCode) {\n const parent = /** @type {RuleNode} */ (node).parent\n\n switch (parent.type) {\n case \"CallExpression\":\n case \"NewExpression\":\n if (parent.arguments.length === 1 && parent.arguments[0] === node) {\n return sourceCode.getTokenAfter(\n parent.callee,\n isOpeningParenToken,\n )\n }\n return null\n\n case \"DoWhileStatement\":\n if (parent.test === node) {\n return sourceCode.getTokenAfter(\n parent.body,\n isOpeningParenToken,\n )\n }\n return null\n\n case \"IfStatement\":\n case \"WhileStatement\":\n if (parent.test === node) {\n return sourceCode.getFirstToken(parent, 1)\n }\n return null\n\n case \"ImportExpression\":\n if (parent.source === node) {\n return sourceCode.getFirstToken(parent, 1)\n }\n return null\n\n case \"SwitchStatement\":\n if (parent.discriminant === node) {\n return sourceCode.getFirstToken(parent, 1)\n }\n return null\n\n case \"WithStatement\":\n if (parent.object === node) {\n return sourceCode.getFirstToken(parent, 1)\n }\n return null\n\n default:\n return null\n }\n}\n\n/**\n * Check whether a given node is parenthesized or not.\n * @param {number} times The number of parantheses.\n * @param {Node} node The AST node to check.\n * @param {SourceCode} sourceCode The source code object to get tokens.\n * @returns {boolean} `true` if the node is parenthesized the given times.\n */\n/**\n * Check whether a given node is parenthesized or not.\n * @param {Node} node The AST node to check.\n * @param {SourceCode} sourceCode The source code object to get tokens.\n * @returns {boolean} `true` if the node is parenthesized.\n */\n/**\n * Check whether a given node is parenthesized or not.\n * @param {Node|number} timesOrNode The first parameter.\n * @param {Node|SourceCode} nodeOrSourceCode The second parameter.\n * @param {SourceCode} [optionalSourceCode] The third parameter.\n * @returns {boolean} `true` if the node is parenthesized.\n */\nexport function isParenthesized(\n timesOrNode,\n nodeOrSourceCode,\n optionalSourceCode,\n) {\n /** @type {number} */\n let times,\n /** @type {RuleNode} */\n node,\n /** @type {SourceCode} */\n sourceCode,\n maybeLeftParen,\n maybeRightParen\n if (typeof timesOrNode === \"number\") {\n times = timesOrNode | 0\n node = /** @type {RuleNode} */ (nodeOrSourceCode)\n sourceCode = /** @type {SourceCode} */ (optionalSourceCode)\n if (!(times >= 1)) {\n throw new TypeError(\"'times' should be a positive integer.\")\n }\n } else {\n times = 1\n node = /** @type {RuleNode} */ (timesOrNode)\n sourceCode = /** @type {SourceCode} */ (nodeOrSourceCode)\n }\n\n if (\n node == null ||\n // `Program` can't be parenthesized\n node.parent == null ||\n // `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}`\n (node.parent.type === \"CatchClause\" && node.parent.param === node)\n ) {\n return false\n }\n\n maybeLeftParen = maybeRightParen = node\n do {\n maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen)\n maybeRightParen = sourceCode.getTokenAfter(maybeRightParen)\n } while (\n maybeLeftParen != null &&\n maybeRightParen != null &&\n isOpeningParenToken(maybeLeftParen) &&\n isClosingParenToken(maybeRightParen) &&\n // Avoid false positive such as `if (a) {}`\n maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&\n --times > 0\n )\n\n return times === 0\n}\n","/**\n * @author Toru Nagashima \n * See LICENSE file in root directory for full license.\n */\n\nconst placeholder = /\\$(?:[$&`']|[1-9][0-9]?)/gu\n\n/** @type {WeakMap} */\nconst internal = new WeakMap()\n\n/**\n * Check whether a given character is escaped or not.\n * @param {string} str The string to check.\n * @param {number} index The location of the character to check.\n * @returns {boolean} `true` if the character is escaped.\n */\nfunction isEscaped(str, index) {\n let escaped = false\n for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {\n escaped = !escaped\n }\n return escaped\n}\n\n/**\n * Replace a given string by a given matcher.\n * @param {PatternMatcher} matcher The pattern matcher.\n * @param {string} str The string to be replaced.\n * @param {string} replacement The new substring to replace each matched part.\n * @returns {string} The replaced string.\n */\nfunction replaceS(matcher, str, replacement) {\n const chunks = []\n let index = 0\n\n /**\n * @param {string} key The placeholder.\n * @param {RegExpExecArray} match The matched information.\n * @returns {string} The replaced string.\n */\n function replacer(key, match) {\n switch (key) {\n case \"$$\":\n return \"$\"\n case \"$&\":\n return match[0]\n case \"$`\":\n return str.slice(0, match.index)\n case \"$'\":\n return str.slice(match.index + match[0].length)\n default: {\n const i = key.slice(1)\n if (i in match) {\n return match[/** @type {any} */ (i)]\n }\n return key\n }\n }\n }\n\n for (const match of matcher.execAll(str)) {\n chunks.push(str.slice(index, match.index))\n chunks.push(\n replacement.replace(placeholder, (key) => replacer(key, match)),\n )\n index = match.index + match[0].length\n }\n chunks.push(str.slice(index))\n\n return chunks.join(\"\")\n}\n\n/**\n * Replace a given string by a given matcher.\n * @param {PatternMatcher} matcher The pattern matcher.\n * @param {string} str The string to be replaced.\n * @param {(substring: string, ...args: any[]) => string} replace The function to replace each matched part.\n * @returns {string} The replaced string.\n */\nfunction replaceF(matcher, str, replace) {\n const chunks = []\n let index = 0\n\n for (const match of matcher.execAll(str)) {\n chunks.push(str.slice(index, match.index))\n chunks.push(\n String(\n replace(\n .../** @type {[string, ...string[]]} */ (\n /** @type {string[]} */ (match)\n ),\n match.index,\n match.input,\n ),\n ),\n )\n index = match.index + match[0].length\n }\n chunks.push(str.slice(index))\n\n return chunks.join(\"\")\n}\n\n/**\n * The class to find patterns as considering escape sequences.\n */\nexport class PatternMatcher {\n /**\n * Initialize this matcher.\n * @param {RegExp} pattern The pattern to match.\n * @param {{escaped?:boolean}} [options] The options.\n */\n constructor(pattern, options = {}) {\n const { escaped = false } = options\n if (!(pattern instanceof RegExp)) {\n throw new TypeError(\"'pattern' should be a RegExp instance.\")\n }\n if (!pattern.flags.includes(\"g\")) {\n throw new Error(\"'pattern' should contains 'g' flag.\")\n }\n\n internal.set(this, {\n pattern: new RegExp(pattern.source, pattern.flags),\n escaped: Boolean(escaped),\n })\n }\n\n /**\n * Find the pattern in a given string.\n * @param {string} str The string to find.\n * @returns {IterableIterator} The iterator which iterate the matched information.\n */\n *execAll(str) {\n const { pattern, escaped } =\n /** @type {{pattern:RegExp,escaped:boolean}} */ (internal.get(this))\n let match = null\n let lastIndex = 0\n\n pattern.lastIndex = 0\n while ((match = pattern.exec(str)) != null) {\n if (escaped || !isEscaped(str, match.index)) {\n lastIndex = pattern.lastIndex\n yield match\n pattern.lastIndex = lastIndex\n }\n }\n }\n\n /**\n * Check whether the pattern is found in a given string.\n * @param {string} str The string to check.\n * @returns {boolean} `true` if the pattern was found in the string.\n */\n test(str) {\n const it = this.execAll(str)\n const ret = it.next()\n return !ret.done\n }\n\n /**\n * Replace a given string.\n * @param {string} str The string to be replaced.\n * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.\n * @returns {string} The replaced string.\n */\n [Symbol.replace](str, replacer) {\n return typeof replacer === \"function\"\n ? replaceF(this, String(str), replacer)\n : replaceS(this, String(str), String(replacer))\n }\n}\n","import { findVariable } from \"./find-variable.mjs\"\nimport { getPropertyName } from \"./get-property-name.mjs\"\nimport { getStringIfConstant } from \"./get-string-if-constant.mjs\"\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"eslint\").Scope.Variable} Variable */\n/** @typedef {import(\"eslint\").Rule.Node} RuleNode */\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"estree\").Expression} Expression */\n/** @typedef {import(\"estree\").Pattern} Pattern */\n/** @typedef {import(\"estree\").Identifier} Identifier */\n/** @typedef {import(\"estree\").SimpleCallExpression} CallExpression */\n/** @typedef {import(\"estree\").Program} Program */\n/** @typedef {import(\"estree\").ImportDeclaration} ImportDeclaration */\n/** @typedef {import(\"estree\").ExportAllDeclaration} ExportAllDeclaration */\n/** @typedef {import(\"estree\").ExportDefaultDeclaration} ExportDefaultDeclaration */\n/** @typedef {import(\"estree\").ExportNamedDeclaration} ExportNamedDeclaration */\n/** @typedef {import(\"estree\").ImportSpecifier} ImportSpecifier */\n/** @typedef {import(\"estree\").ImportDefaultSpecifier} ImportDefaultSpecifier */\n/** @typedef {import(\"estree\").ImportNamespaceSpecifier} ImportNamespaceSpecifier */\n/** @typedef {import(\"estree\").ExportSpecifier} ExportSpecifier */\n/** @typedef {import(\"estree\").Property} Property */\n/** @typedef {import(\"estree\").AssignmentProperty} AssignmentProperty */\n/** @typedef {import(\"estree\").Literal} Literal */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.Node} TSESTreeNode */\n/** @typedef {import(\"./types.mjs\").ReferenceTrackerOptions} ReferenceTrackerOptions */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TraceMap} TraceMap\n */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TraceMapObject} TraceMapObject\n */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TrackedReferences} TrackedReferences\n */\n\nconst IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u\n\n/**\n * Check whether a given node is an import node or not.\n * @param {Node} node\n * @returns {node is ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration&{source: Literal}} `true` if the node is an import node.\n */\nfunction isHasSource(node) {\n return (\n IMPORT_TYPE.test(node.type) &&\n /** @type {ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration} */ (\n node\n ).source != null\n )\n}\nconst has =\n /** @type {(traceMap: TraceMap, v: T) => v is (string extends T ? string : T)} */ (\n Function.call.bind(Object.hasOwnProperty)\n )\n\nexport const READ = Symbol(\"read\")\nexport const CALL = Symbol(\"call\")\nexport const CONSTRUCT = Symbol(\"construct\")\nexport const ESM = Symbol(\"esm\")\n\nconst requireCall = { require: { [CALL]: true } }\n\n/**\n * Check whether a given variable is modified or not.\n * @param {Variable|undefined} variable The variable to check.\n * @returns {boolean} `true` if the variable is modified.\n */\nfunction isModifiedGlobal(variable) {\n return (\n variable == null ||\n variable.defs.length !== 0 ||\n variable.references.some((r) => r.isWrite())\n )\n}\n\n/**\n * Check if the value of a given node is passed through to the parent syntax as-is.\n * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.\n * @param {Node} node A node to check.\n * @returns {node is RuleNode & {parent: Expression}} `true` if the node is passed through.\n */\nfunction isPassThrough(node) {\n const parent = /** @type {TSESTreeNode} */ (node).parent\n\n if (parent) {\n switch (parent.type) {\n case \"ConditionalExpression\":\n return parent.consequent === node || parent.alternate === node\n case \"LogicalExpression\":\n return true\n case \"SequenceExpression\":\n return (\n parent.expressions[parent.expressions.length - 1] === node\n )\n case \"ChainExpression\":\n return true\n case \"TSAsExpression\":\n case \"TSSatisfiesExpression\":\n case \"TSTypeAssertion\":\n case \"TSNonNullExpression\":\n case \"TSInstantiationExpression\":\n return true\n\n default:\n return false\n }\n }\n return false\n}\n\n/**\n * The reference tracker.\n */\nexport class ReferenceTracker {\n /**\n * Initialize this tracker.\n * @param {Scope} globalScope The global scope.\n * @param {object} [options] The options.\n * @param {\"legacy\"|\"strict\"} [options.mode=\"strict\"] The mode to determine the ImportDeclaration's behavior for CJS modules.\n * @param {string[]} [options.globalObjectNames=[\"global\",\"globalThis\",\"self\",\"window\"]] The variable names for Global Object.\n */\n constructor(globalScope, options = {}) {\n const {\n mode = \"strict\",\n globalObjectNames = [\"global\", \"globalThis\", \"self\", \"window\"],\n } = options\n /** @private @type {Variable[]} */\n this.variableStack = []\n /** @private */\n this.globalScope = globalScope\n /** @private */\n this.mode = mode\n /** @private */\n this.globalObjectNames = globalObjectNames.slice(0)\n }\n\n /**\n * Iterate the references of global variables.\n * @template T\n * @param {TraceMap} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *iterateGlobalReferences(traceMap) {\n for (const key of Object.keys(traceMap)) {\n const nextTraceMap = traceMap[key]\n const path = [key]\n const variable = this.globalScope.set.get(key)\n\n if (isModifiedGlobal(variable)) {\n continue\n }\n\n yield* this._iterateVariableReferences(\n /** @type {Variable} */ (variable),\n path,\n nextTraceMap,\n true,\n )\n }\n\n for (const key of this.globalObjectNames) {\n /** @type {string[]} */\n const path = []\n const variable = this.globalScope.set.get(key)\n\n if (isModifiedGlobal(variable)) {\n continue\n }\n\n yield* this._iterateVariableReferences(\n /** @type {Variable} */ (variable),\n path,\n traceMap,\n false,\n )\n }\n }\n\n /**\n * Iterate the references of CommonJS modules.\n * @template T\n * @param {TraceMap} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *iterateCjsReferences(traceMap) {\n for (const { node } of this.iterateGlobalReferences(requireCall)) {\n const key = getStringIfConstant(\n /** @type {CallExpression} */ (node).arguments[0],\n )\n if (key == null || !has(traceMap, key)) {\n continue\n }\n\n const nextTraceMap = traceMap[key]\n const path = [key]\n\n if (nextTraceMap[READ]) {\n yield {\n node,\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n yield* this._iteratePropertyReferences(\n /** @type {CallExpression} */ (node),\n path,\n nextTraceMap,\n )\n }\n }\n\n /**\n * Iterate the references of ES modules.\n * @template T\n * @param {TraceMap} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *iterateEsmReferences(traceMap) {\n const programNode = /** @type {Program} */ (this.globalScope.block)\n\n for (const node of programNode.body) {\n if (!isHasSource(node)) {\n continue\n }\n const moduleId = /** @type {string} */ (node.source.value)\n\n if (!has(traceMap, moduleId)) {\n continue\n }\n const nextTraceMap = traceMap[moduleId]\n const path = [moduleId]\n\n if (nextTraceMap[READ]) {\n yield {\n // eslint-disable-next-line object-shorthand -- apply type\n node: /** @type {RuleNode} */ (node),\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n\n if (node.type === \"ExportAllDeclaration\") {\n for (const key of Object.keys(nextTraceMap)) {\n const exportTraceMap = nextTraceMap[key]\n if (exportTraceMap[READ]) {\n yield {\n // eslint-disable-next-line object-shorthand -- apply type\n node: /** @type {RuleNode} */ (node),\n path: path.concat(key),\n type: READ,\n info: exportTraceMap[READ],\n }\n }\n }\n } else {\n for (const specifier of node.specifiers) {\n const esm = has(nextTraceMap, ESM)\n const it = this._iterateImportReferences(\n specifier,\n path,\n esm\n ? nextTraceMap\n : this.mode === \"legacy\"\n ? { default: nextTraceMap, ...nextTraceMap }\n : { default: nextTraceMap },\n )\n\n if (esm) {\n yield* it\n } else {\n for (const report of it) {\n report.path = report.path.filter(exceptDefault)\n if (\n report.path.length >= 2 ||\n report.type !== READ\n ) {\n yield report\n }\n }\n }\n }\n }\n }\n }\n\n /**\n * Iterate the property references for a given expression AST node.\n * @template T\n * @param {Expression} node The expression AST node to iterate property references.\n * @param {TraceMap} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate property references.\n */\n *iteratePropertyReferences(node, traceMap) {\n yield* this._iteratePropertyReferences(node, [], traceMap)\n }\n\n /**\n * Iterate the references for a given variable.\n * @private\n * @template T\n * @param {Variable} variable The variable to iterate that references.\n * @param {string[]} path The current path.\n * @param {TraceMapObject} traceMap The trace map.\n * @param {boolean} shouldReport = The flag to report those references.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *_iterateVariableReferences(variable, path, traceMap, shouldReport) {\n if (this.variableStack.includes(variable)) {\n return\n }\n this.variableStack.push(variable)\n try {\n for (const reference of variable.references) {\n if (!reference.isRead()) {\n continue\n }\n const node = /** @type {RuleNode & Identifier} */ (\n reference.identifier\n )\n\n if (shouldReport && traceMap[READ]) {\n yield { node, path, type: READ, info: traceMap[READ] }\n }\n yield* this._iteratePropertyReferences(node, path, traceMap)\n }\n } finally {\n this.variableStack.pop()\n }\n }\n\n /**\n * Iterate the references for a given AST node.\n * @private\n * @template T\n * @param {Expression} rootNode The AST node to iterate references.\n * @param {string[]} path The current path.\n * @param {TraceMapObject} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n //eslint-disable-next-line complexity\n *_iteratePropertyReferences(rootNode, path, traceMap) {\n let node = rootNode\n while (isPassThrough(node)) {\n node = node.parent\n }\n\n const parent = /** @type {RuleNode} */ (node).parent\n if (parent.type === \"MemberExpression\") {\n if (parent.object === node) {\n const key = getPropertyName(parent)\n if (key == null || !has(traceMap, key)) {\n return\n }\n\n path = path.concat(key) //eslint-disable-line no-param-reassign\n const nextTraceMap = traceMap[key]\n if (nextTraceMap[READ]) {\n yield {\n node: parent,\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n yield* this._iteratePropertyReferences(\n parent,\n path,\n nextTraceMap,\n )\n }\n return\n }\n if (parent.type === \"CallExpression\") {\n if (parent.callee === node && traceMap[CALL]) {\n yield { node: parent, path, type: CALL, info: traceMap[CALL] }\n }\n return\n }\n if (parent.type === \"NewExpression\") {\n if (parent.callee === node && traceMap[CONSTRUCT]) {\n yield {\n node: parent,\n path,\n type: CONSTRUCT,\n info: traceMap[CONSTRUCT],\n }\n }\n return\n }\n if (parent.type === \"AssignmentExpression\") {\n if (parent.right === node) {\n yield* this._iterateLhsReferences(parent.left, path, traceMap)\n yield* this._iteratePropertyReferences(parent, path, traceMap)\n }\n return\n }\n if (parent.type === \"AssignmentPattern\") {\n if (parent.right === node) {\n yield* this._iterateLhsReferences(parent.left, path, traceMap)\n }\n return\n }\n if (parent.type === \"VariableDeclarator\") {\n if (parent.init === node) {\n yield* this._iterateLhsReferences(parent.id, path, traceMap)\n }\n }\n }\n\n /**\n * Iterate the references for a given Pattern node.\n * @private\n * @template T\n * @param {Pattern} patternNode The Pattern node to iterate references.\n * @param {string[]} path The current path.\n * @param {TraceMapObject} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *_iterateLhsReferences(patternNode, path, traceMap) {\n if (patternNode.type === \"Identifier\") {\n const variable = findVariable(this.globalScope, patternNode)\n if (variable != null) {\n yield* this._iterateVariableReferences(\n variable,\n path,\n traceMap,\n false,\n )\n }\n return\n }\n if (patternNode.type === \"ObjectPattern\") {\n for (const property of patternNode.properties) {\n const key = getPropertyName(\n /** @type {AssignmentProperty} */ (property),\n )\n\n if (key == null || !has(traceMap, key)) {\n continue\n }\n\n const nextPath = path.concat(key)\n const nextTraceMap = traceMap[key]\n if (nextTraceMap[READ]) {\n yield {\n node: /** @type {RuleNode} */ (property),\n path: nextPath,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n yield* this._iterateLhsReferences(\n /** @type {AssignmentProperty} */ (property).value,\n nextPath,\n nextTraceMap,\n )\n }\n return\n }\n if (patternNode.type === \"AssignmentPattern\") {\n yield* this._iterateLhsReferences(patternNode.left, path, traceMap)\n }\n }\n\n /**\n * Iterate the references for a given ModuleSpecifier node.\n * @private\n * @template T\n * @param {ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier} specifierNode The ModuleSpecifier node to iterate references.\n * @param {string[]} path The current path.\n * @param {TraceMapObject} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *_iterateImportReferences(specifierNode, path, traceMap) {\n const type = specifierNode.type\n\n if (type === \"ImportSpecifier\" || type === \"ImportDefaultSpecifier\") {\n const key =\n type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifierNode.imported.type === \"Identifier\"\n ? specifierNode.imported.name\n : specifierNode.imported.value\n if (!has(traceMap, key)) {\n return\n }\n\n path = path.concat(key) //eslint-disable-line no-param-reassign\n const nextTraceMap = traceMap[key]\n if (nextTraceMap[READ]) {\n yield {\n node: /** @type {RuleNode} */ (specifierNode),\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n yield* this._iterateVariableReferences(\n /** @type {Variable} */ (\n findVariable(this.globalScope, specifierNode.local)\n ),\n path,\n nextTraceMap,\n false,\n )\n\n return\n }\n\n if (type === \"ImportNamespaceSpecifier\") {\n yield* this._iterateVariableReferences(\n /** @type {Variable} */ (\n findVariable(this.globalScope, specifierNode.local)\n ),\n path,\n traceMap,\n false,\n )\n return\n }\n\n if (type === \"ExportSpecifier\") {\n const key =\n specifierNode.local.type === \"Identifier\"\n ? specifierNode.local.name\n : specifierNode.local.value\n if (!has(traceMap, key)) {\n return\n }\n\n path = path.concat(key) //eslint-disable-line no-param-reassign\n const nextTraceMap = traceMap[key]\n if (nextTraceMap[READ]) {\n yield {\n node: /** @type {RuleNode} */ (specifierNode),\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n }\n }\n}\n\nReferenceTracker.READ = READ\nReferenceTracker.CALL = CALL\nReferenceTracker.CONSTRUCT = CONSTRUCT\nReferenceTracker.ESM = ESM\n\n/**\n * This is a predicate function for Array#filter.\n * @param {string} name A name part.\n * @param {number} index The index of the name.\n * @returns {boolean} `false` if it's default.\n */\nfunction exceptDefault(name, index) {\n return !(index === 1 && name === \"default\")\n}\n","/** @typedef {import(\"./types.mjs\").StaticValue} StaticValue */\n/** @typedef {import(\"./types.mjs\").StaticValueOptional} StaticValueOptional */\n/** @typedef {import(\"./types.mjs\").StaticValueProvided} StaticValueProvided */\n/** @typedef {import(\"./types.mjs\").ReferenceTrackerOptions} ReferenceTrackerOptions */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TraceMap} TraceMap\n */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TrackedReferences} TrackedReferences\n */\n/** @typedef {import(\"./types.mjs\").HasSideEffectOptions} HasSideEffectOptions */\n/** @typedef {import(\"./types.mjs\").ArrowToken} ArrowToken */\n/** @typedef {import(\"./types.mjs\").CommaToken} CommaToken */\n/** @typedef {import(\"./types.mjs\").SemicolonToken} SemicolonToken */\n/** @typedef {import(\"./types.mjs\").ColonToken} ColonToken */\n/** @typedef {import(\"./types.mjs\").OpeningParenToken} OpeningParenToken */\n/** @typedef {import(\"./types.mjs\").ClosingParenToken} ClosingParenToken */\n/** @typedef {import(\"./types.mjs\").OpeningBracketToken} OpeningBracketToken */\n/** @typedef {import(\"./types.mjs\").ClosingBracketToken} ClosingBracketToken */\n/** @typedef {import(\"./types.mjs\").OpeningBraceToken} OpeningBraceToken */\n/** @typedef {import(\"./types.mjs\").ClosingBraceToken} ClosingBraceToken */\n\nimport { findVariable } from \"./find-variable.mjs\"\nimport { getFunctionHeadLocation } from \"./get-function-head-location.mjs\"\nimport { getFunctionNameWithKind } from \"./get-function-name-with-kind.mjs\"\nimport { getInnermostScope } from \"./get-innermost-scope.mjs\"\nimport { getPropertyName } from \"./get-property-name.mjs\"\nimport { getStaticValue } from \"./get-static-value.mjs\"\nimport { getStringIfConstant } from \"./get-string-if-constant.mjs\"\nimport { hasSideEffect } from \"./has-side-effect.mjs\"\nimport { isParenthesized } from \"./is-parenthesized.mjs\"\nimport { PatternMatcher } from \"./pattern-matcher.mjs\"\nimport {\n CALL,\n CONSTRUCT,\n ESM,\n READ,\n ReferenceTracker,\n} from \"./reference-tracker.mjs\"\nimport {\n isArrowToken,\n isClosingBraceToken,\n isClosingBracketToken,\n isClosingParenToken,\n isColonToken,\n isCommaToken,\n isCommentToken,\n isNotArrowToken,\n isNotClosingBraceToken,\n isNotClosingBracketToken,\n isNotClosingParenToken,\n isNotColonToken,\n isNotCommaToken,\n isNotCommentToken,\n isNotOpeningBraceToken,\n isNotOpeningBracketToken,\n isNotOpeningParenToken,\n isNotSemicolonToken,\n isOpeningBraceToken,\n isOpeningBracketToken,\n isOpeningParenToken,\n isSemicolonToken,\n} from \"./token-predicate.mjs\"\n\nexport default {\n CALL,\n CONSTRUCT,\n ESM,\n findVariable,\n getFunctionHeadLocation,\n getFunctionNameWithKind,\n getInnermostScope,\n getPropertyName,\n getStaticValue,\n getStringIfConstant,\n hasSideEffect,\n isArrowToken,\n isClosingBraceToken,\n isClosingBracketToken,\n isClosingParenToken,\n isColonToken,\n isCommaToken,\n isCommentToken,\n isNotArrowToken,\n isNotClosingBraceToken,\n isNotClosingBracketToken,\n isNotClosingParenToken,\n isNotColonToken,\n isNotCommaToken,\n isNotCommentToken,\n isNotOpeningBraceToken,\n isNotOpeningBracketToken,\n isNotOpeningParenToken,\n isNotSemicolonToken,\n isOpeningBraceToken,\n isOpeningBracketToken,\n isOpeningParenToken,\n isParenthesized,\n isSemicolonToken,\n PatternMatcher,\n READ,\n ReferenceTracker,\n}\nexport {\n CALL,\n CONSTRUCT,\n ESM,\n findVariable,\n getFunctionHeadLocation,\n getFunctionNameWithKind,\n getInnermostScope,\n getPropertyName,\n getStaticValue,\n getStringIfConstant,\n hasSideEffect,\n isArrowToken,\n isClosingBraceToken,\n isClosingBracketToken,\n isClosingParenToken,\n isColonToken,\n isCommaToken,\n isCommentToken,\n isNotArrowToken,\n isNotClosingBraceToken,\n isNotClosingBracketToken,\n isNotClosingParenToken,\n isNotColonToken,\n isNotCommaToken,\n isNotCommentToken,\n isNotOpeningBraceToken,\n isNotOpeningBracketToken,\n isNotOpeningParenToken,\n isNotSemicolonToken,\n isOpeningBraceToken,\n isOpeningBracketToken,\n isOpeningParenToken,\n isParenthesized,\n isSemicolonToken,\n PatternMatcher,\n READ,\n ReferenceTracker,\n}\n"],"names":["getKeys","KEYS"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,iBAAiB,CAAC,YAAY,EAAE,IAAI,EAAE;AACtD,IAAI,MAAM,QAAQ,mCAAmC,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,EAAC;AACpE;AACA,IAAI,IAAI,KAAK,GAAG,aAAY;AAC5B,IAAI,IAAI,KAAK,GAAG,MAAK;AACrB,IAAI,GAAG;AACP,QAAQ,KAAK,GAAG,MAAK;AACrB,QAAQ,KAAK,MAAM,UAAU,IAAI,KAAK,CAAC,WAAW,EAAE;AACpD,YAAY,MAAM,KAAK;AACvB,gBAAgB,UAAU,CAAC,KAAK,CAAC,KAAK;AACtC,cA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AI,uBAAuB;AAC3B,IAAI,uBAAuB;AAC3B,IAAI,iBAAiB;AACrB,IAAI,eAAe;AACnB,IAAI,cAAc;AAClB,IAAI,mBAAmB;AACvB,IAAI,aAAa;AACjB,IAAI,YAAY;AAChB,IAAI,mBAAmB;AACvB,IAAI,qBAAqB;AACzB,IAAI,mBAAmB;AACvB,IAAI,YAAY;AAChB,IAAI,YAAY;AAChB,IAAI,cAAc;AAClB,IAAI,eAAe;AACnB,IAAI,sBAAsB;AAC1B,IAAI,wBAAwB;AAC5B,IAAI,sBAAsB;AAC1B,IAAI,eAAe;AACnB,IAAI,eAAe;AACnB,IAAI,iBAAiB;AACrB,IAAI,sBAAsB;AAC1B,IAAI,wBAAwB;AAC5B,IAAI,sBAAsB;AAC1B,IAAI,mBAAmB;AACvB,IAAI,mBAAmB;AACvB,IAAI,qBAAqB;AACzB,IAAI,mBAAmB;AACvB,IAAI,eAAe;AACnB,IAAI,gBAAgB;AACpB,IAAI,cAAc;AAClB,IAAI,IAAI;AACR,IAAI,gBAAgB;AACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@eslint-community/eslint-utils/index.mjs b/node_modules/@eslint-community/eslint-utils/index.mjs new file mode 100644 index 00000000..6f1e894a --- /dev/null +++ b/node_modules/@eslint-community/eslint-utils/index.mjs @@ -0,0 +1,2453 @@ +import { getKeys, KEYS } from 'eslint-visitor-keys'; + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("estree").Node} Node */ + +/** + * Get the innermost scope which contains a given location. + * @param {Scope} initialScope The initial scope to search. + * @param {Node} node The location to search. + * @returns {Scope} The innermost scope. + */ +function getInnermostScope(initialScope, node) { + const location = /** @type {[number, number]} */ (node.range)[0]; + + let scope = initialScope; + let found = false; + do { + found = false; + for (const childScope of scope.childScopes) { + const range = /** @type {[number, number]} */ ( + childScope.block.range + ); + + if (range[0] <= location && location < range[1]) { + scope = childScope; + found = true; + break + } + } + } while (found) + + return scope +} + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("eslint").Scope.Variable} Variable */ +/** @typedef {import("estree").Identifier} Identifier */ + +/** + * Find the variable of a given name. + * @param {Scope} initialScope The scope to start finding. + * @param {string|Identifier} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node. + * @returns {Variable|null} The found variable or null. + */ +function findVariable(initialScope, nameOrNode) { + let name = ""; + /** @type {Scope|null} */ + let scope = initialScope; + + if (typeof nameOrNode === "string") { + name = nameOrNode; + } else { + name = nameOrNode.name; + scope = getInnermostScope(scope, nameOrNode); + } + + while (scope != null) { + const variable = scope.set.get(name); + if (variable != null) { + return variable + } + scope = scope.upper; + } + + return null +} + +/** @typedef {import("eslint").AST.Token} Token */ +/** @typedef {import("estree").Comment} Comment */ +/** @typedef {import("./types.mjs").ArrowToken} ArrowToken */ +/** @typedef {import("./types.mjs").CommaToken} CommaToken */ +/** @typedef {import("./types.mjs").SemicolonToken} SemicolonToken */ +/** @typedef {import("./types.mjs").ColonToken} ColonToken */ +/** @typedef {import("./types.mjs").OpeningParenToken} OpeningParenToken */ +/** @typedef {import("./types.mjs").ClosingParenToken} ClosingParenToken */ +/** @typedef {import("./types.mjs").OpeningBracketToken} OpeningBracketToken */ +/** @typedef {import("./types.mjs").ClosingBracketToken} ClosingBracketToken */ +/** @typedef {import("./types.mjs").OpeningBraceToken} OpeningBraceToken */ +/** @typedef {import("./types.mjs").ClosingBraceToken} ClosingBraceToken */ +/** + * @template {string} Value + * @typedef {import("./types.mjs").PunctuatorToken} PunctuatorToken + */ + +/** @typedef {Comment | Token} CommentOrToken */ + +/** + * Creates the negate function of the given function. + * @param {function(CommentOrToken):boolean} f - The function to negate. + * @returns {function(CommentOrToken):boolean} Negated function. + */ +function negate(f) { + return (token) => !f(token) +} + +/** + * Checks if the given token is a PunctuatorToken with the given value + * @template {string} Value + * @param {CommentOrToken} token - The token to check. + * @param {Value} value - The value to check. + * @returns {token is PunctuatorToken} `true` if the token is a PunctuatorToken with the given value. + */ +function isPunctuatorTokenWithValue(token, value) { + return token.type === "Punctuator" && token.value === value +} + +/** + * Checks if the given token is an arrow token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ArrowToken} `true` if the token is an arrow token. + */ +function isArrowToken(token) { + return isPunctuatorTokenWithValue(token, "=>") +} + +/** + * Checks if the given token is a comma token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is CommaToken} `true` if the token is a comma token. + */ +function isCommaToken(token) { + return isPunctuatorTokenWithValue(token, ",") +} + +/** + * Checks if the given token is a semicolon token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is SemicolonToken} `true` if the token is a semicolon token. + */ +function isSemicolonToken(token) { + return isPunctuatorTokenWithValue(token, ";") +} + +/** + * Checks if the given token is a colon token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ColonToken} `true` if the token is a colon token. + */ +function isColonToken(token) { + return isPunctuatorTokenWithValue(token, ":") +} + +/** + * Checks if the given token is an opening parenthesis token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is OpeningParenToken} `true` if the token is an opening parenthesis token. + */ +function isOpeningParenToken(token) { + return isPunctuatorTokenWithValue(token, "(") +} + +/** + * Checks if the given token is a closing parenthesis token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ClosingParenToken} `true` if the token is a closing parenthesis token. + */ +function isClosingParenToken(token) { + return isPunctuatorTokenWithValue(token, ")") +} + +/** + * Checks if the given token is an opening square bracket token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is OpeningBracketToken} `true` if the token is an opening square bracket token. + */ +function isOpeningBracketToken(token) { + return isPunctuatorTokenWithValue(token, "[") +} + +/** + * Checks if the given token is a closing square bracket token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ClosingBracketToken} `true` if the token is a closing square bracket token. + */ +function isClosingBracketToken(token) { + return isPunctuatorTokenWithValue(token, "]") +} + +/** + * Checks if the given token is an opening brace token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is OpeningBraceToken} `true` if the token is an opening brace token. + */ +function isOpeningBraceToken(token) { + return isPunctuatorTokenWithValue(token, "{") +} + +/** + * Checks if the given token is a closing brace token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is ClosingBraceToken} `true` if the token is a closing brace token. + */ +function isClosingBraceToken(token) { + return isPunctuatorTokenWithValue(token, "}") +} + +/** + * Checks if the given token is a comment token or not. + * @param {CommentOrToken} token - The token to check. + * @returns {token is Comment} `true` if the token is a comment token. + */ +function isCommentToken(token) { + return ["Block", "Line", "Shebang"].includes(token.type) +} + +const isNotArrowToken = negate(isArrowToken); +const isNotCommaToken = negate(isCommaToken); +const isNotSemicolonToken = negate(isSemicolonToken); +const isNotColonToken = negate(isColonToken); +const isNotOpeningParenToken = negate(isOpeningParenToken); +const isNotClosingParenToken = negate(isClosingParenToken); +const isNotOpeningBracketToken = negate(isOpeningBracketToken); +const isNotClosingBracketToken = negate(isClosingBracketToken); +const isNotOpeningBraceToken = negate(isOpeningBraceToken); +const isNotClosingBraceToken = negate(isClosingBraceToken); +const isNotCommentToken = negate(isCommentToken); + +/** @typedef {import("eslint").Rule.Node} RuleNode */ +/** @typedef {import("eslint").SourceCode} SourceCode */ +/** @typedef {import("eslint").AST.Token} Token */ +/** @typedef {import("estree").Function} FunctionNode */ +/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */ +/** @typedef {import("estree").FunctionExpression} FunctionExpression */ +/** @typedef {import("estree").SourceLocation} SourceLocation */ +/** @typedef {import("estree").Position} Position */ + +/** + * Get the `(` token of the given function node. + * @param {FunctionExpression | FunctionDeclaration} node - The function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {Token} `(` token. + */ +function getOpeningParenOfParams(node, sourceCode) { + return node.id + ? /** @type {Token} */ ( + sourceCode.getTokenAfter(node.id, isOpeningParenToken) + ) + : /** @type {Token} */ ( + sourceCode.getFirstToken(node, isOpeningParenToken) + ) +} + +/** + * Get the location of the given function node for reporting. + * @param {FunctionNode} node - The function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {SourceLocation|null} The location of the function node for reporting. + */ +function getFunctionHeadLocation(node, sourceCode) { + const parent = /** @type {RuleNode} */ (node).parent; + + /** @type {Position|null} */ + let start = null; + /** @type {Position|null} */ + let end = null; + + if (node.type === "ArrowFunctionExpression") { + const arrowToken = /** @type {Token} */ ( + sourceCode.getTokenBefore(node.body, isArrowToken) + ); + + start = arrowToken.loc.start; + end = arrowToken.loc.end; + } else if ( + parent.type === "Property" || + parent.type === "MethodDefinition" || + parent.type === "PropertyDefinition" + ) { + start = /** @type {SourceLocation} */ (parent.loc).start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } else { + start = /** @type {SourceLocation} */ (node.loc).start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + + return { + start: { ...start }, + end: { ...end }, + } +} + +/* globals globalThis, global, self, window */ +/** @typedef {import("./types.mjs").StaticValue} StaticValue */ +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */ +/** @typedef {import("@typescript-eslint/types").TSESTree.AST_NODE_TYPES} TSESTreeNodeTypes */ +/** @typedef {import("@typescript-eslint/types").TSESTree.MemberExpression} MemberExpression */ +/** @typedef {import("@typescript-eslint/types").TSESTree.Property} Property */ +/** @typedef {import("@typescript-eslint/types").TSESTree.RegExpLiteral} RegExpLiteral */ +/** @typedef {import("@typescript-eslint/types").TSESTree.BigIntLiteral} BigIntLiteral */ +/** @typedef {import("@typescript-eslint/types").TSESTree.Literal} Literal */ + +const globalObject = + typeof globalThis !== "undefined" + ? globalThis + : // @ts-ignore + typeof self !== "undefined" + ? // @ts-ignore + self + : // @ts-ignore + typeof window !== "undefined" + ? // @ts-ignore + window + : typeof global !== "undefined" + ? global + : {}; + +const builtinNames = Object.freeze( + new Set([ + "Array", + "ArrayBuffer", + "BigInt", + "BigInt64Array", + "BigUint64Array", + "Boolean", + "DataView", + "Date", + "decodeURI", + "decodeURIComponent", + "encodeURI", + "encodeURIComponent", + "escape", + "Float32Array", + "Float64Array", + "Function", + "Infinity", + "Int16Array", + "Int32Array", + "Int8Array", + "isFinite", + "isNaN", + "isPrototypeOf", + "JSON", + "Map", + "Math", + "NaN", + "Number", + "Object", + "parseFloat", + "parseInt", + "Promise", + "Proxy", + "Reflect", + "RegExp", + "Set", + "String", + "Symbol", + "Uint16Array", + "Uint32Array", + "Uint8Array", + "Uint8ClampedArray", + "undefined", + "unescape", + "WeakMap", + "WeakSet", + ]), +); +const callAllowed = new Set( + [ + Array.isArray, + Array.of, + Array.prototype.at, + Array.prototype.concat, + Array.prototype.entries, + Array.prototype.every, + Array.prototype.filter, + Array.prototype.find, + Array.prototype.findIndex, + Array.prototype.flat, + Array.prototype.includes, + Array.prototype.indexOf, + Array.prototype.join, + Array.prototype.keys, + Array.prototype.lastIndexOf, + Array.prototype.slice, + Array.prototype.some, + Array.prototype.toString, + Array.prototype.values, + typeof BigInt === "function" ? BigInt : undefined, + Boolean, + Date, + Date.parse, + decodeURI, + decodeURIComponent, + encodeURI, + encodeURIComponent, + escape, + isFinite, + isNaN, + // @ts-ignore + isPrototypeOf, + Map, + Map.prototype.entries, + Map.prototype.get, + Map.prototype.has, + Map.prototype.keys, + Map.prototype.values, + .../** @type {(keyof typeof Math)[]} */ ( + Object.getOwnPropertyNames(Math) + ) + .filter((k) => k !== "random") + .map((k) => Math[k]) + .filter((f) => typeof f === "function"), + Number, + Number.isFinite, + Number.isNaN, + Number.parseFloat, + Number.parseInt, + Number.prototype.toExponential, + Number.prototype.toFixed, + Number.prototype.toPrecision, + Number.prototype.toString, + Object, + Object.entries, + Object.is, + Object.isExtensible, + Object.isFrozen, + Object.isSealed, + Object.keys, + Object.values, + parseFloat, + parseInt, + RegExp, + Set, + Set.prototype.entries, + Set.prototype.has, + Set.prototype.keys, + Set.prototype.values, + String, + String.fromCharCode, + String.fromCodePoint, + String.raw, + String.prototype.at, + String.prototype.charAt, + String.prototype.charCodeAt, + String.prototype.codePointAt, + String.prototype.concat, + String.prototype.endsWith, + String.prototype.includes, + String.prototype.indexOf, + String.prototype.lastIndexOf, + String.prototype.normalize, + String.prototype.padEnd, + String.prototype.padStart, + String.prototype.slice, + String.prototype.startsWith, + String.prototype.substr, + String.prototype.substring, + String.prototype.toLowerCase, + String.prototype.toString, + String.prototype.toUpperCase, + String.prototype.trim, + String.prototype.trimEnd, + String.prototype.trimLeft, + String.prototype.trimRight, + String.prototype.trimStart, + Symbol.for, + Symbol.keyFor, + unescape, + ].filter((f) => typeof f === "function"), +); +const callPassThrough = new Set([ + Object.freeze, + Object.preventExtensions, + Object.seal, +]); + +/** @type {ReadonlyArray]>} */ +const getterAllowed = [ + [Map, new Set(["size"])], + [ + RegExp, + new Set([ + "dotAll", + "flags", + "global", + "hasIndices", + "ignoreCase", + "multiline", + "source", + "sticky", + "unicode", + ]), + ], + [Set, new Set(["size"])], +]; + +/** + * Get the property descriptor. + * @param {object} object The object to get. + * @param {string|number|symbol} name The property name to get. + */ +function getPropertyDescriptor(object, name) { + let x = object; + while ((typeof x === "object" || typeof x === "function") && x !== null) { + const d = Object.getOwnPropertyDescriptor(x, name); + if (d) { + return d + } + x = Object.getPrototypeOf(x); + } + return null +} + +/** + * Check if a property is getter or not. + * @param {object} object The object to check. + * @param {string|number|symbol} name The property name to check. + */ +function isGetter(object, name) { + const d = getPropertyDescriptor(object, name); + return d != null && d.get != null +} + +/** + * Get the element values of a given node list. + * @param {(Node|TSESTreeNode|null)[]} nodeList The node list to get values. + * @param {Scope|undefined|null} initialScope The initial scope to find variables. + * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null. + */ +function getElementValues(nodeList, initialScope) { + const valueList = []; + + for (let i = 0; i < nodeList.length; ++i) { + const elementNode = nodeList[i]; + + if (elementNode == null) { + valueList.length = i + 1; + } else if (elementNode.type === "SpreadElement") { + const argument = getStaticValueR(elementNode.argument, initialScope); + if (argument == null) { + return null + } + valueList.push(.../** @type {Iterable} */ (argument.value)); + } else { + const element = getStaticValueR(elementNode, initialScope); + if (element == null) { + return null + } + valueList.push(element.value); + } + } + + return valueList +} + +/** + * Returns whether the given variable is never written to after initialization. + * @param {import("eslint").Scope.Variable} variable + * @returns {boolean} + */ +function isEffectivelyConst(variable) { + const refs = variable.references; + + const inits = refs.filter((r) => r.init).length; + const reads = refs.filter((r) => r.isReadOnly()).length; + if (inits === 1 && reads + inits === refs.length) { + // there is only one init and all other references only read + return true + } + return false +} + +/** + * @template {TSESTreeNodeTypes} T + * @callback VisitorCallback + * @param {TSESTreeNode & { type: T }} node + * @param {Scope|undefined|null} initialScope + * @returns {StaticValue | null} + */ +/** + * @typedef { { [K in TSESTreeNodeTypes]?: VisitorCallback } } Operations + */ +/** + * @type {Operations} + */ +const operations = Object.freeze({ + ArrayExpression(node, initialScope) { + const elements = getElementValues(node.elements, initialScope); + return elements != null ? { value: elements } : null + }, + + AssignmentExpression(node, initialScope) { + if (node.operator === "=") { + return getStaticValueR(node.right, initialScope) + } + return null + }, + + //eslint-disable-next-line complexity + BinaryExpression(node, initialScope) { + if (node.operator === "in" || node.operator === "instanceof") { + // Not supported. + return null + } + + const left = getStaticValueR(node.left, initialScope); + const right = getStaticValueR(node.right, initialScope); + if (left != null && right != null) { + switch (node.operator) { + case "==": + return { value: left.value == right.value } //eslint-disable-line eqeqeq + case "!=": + return { value: left.value != right.value } //eslint-disable-line eqeqeq + case "===": + return { value: left.value === right.value } + case "!==": + return { value: left.value !== right.value } + case "<": + return { + value: + /** @type {any} */ (left.value) < + /** @type {any} */ (right.value), + } + case "<=": + return { + value: + /** @type {any} */ (left.value) <= + /** @type {any} */ (right.value), + } + case ">": + return { + value: + /** @type {any} */ (left.value) > + /** @type {any} */ (right.value), + } + case ">=": + return { + value: + /** @type {any} */ (left.value) >= + /** @type {any} */ (right.value), + } + case "<<": + return { + value: + /** @type {any} */ (left.value) << + /** @type {any} */ (right.value), + } + case ">>": + return { + value: + /** @type {any} */ (left.value) >> + /** @type {any} */ (right.value), + } + case ">>>": + return { + value: + /** @type {any} */ (left.value) >>> + /** @type {any} */ (right.value), + } + case "+": + return { + value: + /** @type {any} */ (left.value) + + /** @type {any} */ (right.value), + } + case "-": + return { + value: + /** @type {any} */ (left.value) - + /** @type {any} */ (right.value), + } + case "*": + return { + value: + /** @type {any} */ (left.value) * + /** @type {any} */ (right.value), + } + case "/": + return { + value: + /** @type {any} */ (left.value) / + /** @type {any} */ (right.value), + } + case "%": + return { + value: + /** @type {any} */ (left.value) % + /** @type {any} */ (right.value), + } + case "**": + return { + value: + /** @type {any} */ (left.value) ** + /** @type {any} */ (right.value), + } + case "|": + return { + value: + /** @type {any} */ (left.value) | + /** @type {any} */ (right.value), + } + case "^": + return { + value: + /** @type {any} */ (left.value) ^ + /** @type {any} */ (right.value), + } + case "&": + return { + value: + /** @type {any} */ (left.value) & + /** @type {any} */ (right.value), + } + + // no default + } + } + + return null + }, + + CallExpression(node, initialScope) { + const calleeNode = node.callee; + const args = getElementValues(node.arguments, initialScope); + + if (args != null) { + if (calleeNode.type === "MemberExpression") { + if (calleeNode.property.type === "PrivateIdentifier") { + return null + } + const object = getStaticValueR(calleeNode.object, initialScope); + if (object != null) { + if ( + object.value == null && + (object.optional || node.optional) + ) { + return { value: undefined, optional: true } + } + const property = getStaticPropertyNameValue( + calleeNode, + initialScope, + ); + + if (property != null) { + const receiver = + /** @type {Record any>} */ ( + object.value + ); + const methodName = /** @type {PropertyKey} */ ( + property.value + ); + if (callAllowed.has(receiver[methodName])) { + return { + value: receiver[methodName](...args), + } + } + if (callPassThrough.has(receiver[methodName])) { + return { value: args[0] } + } + } + } + } else { + const callee = getStaticValueR(calleeNode, initialScope); + if (callee != null) { + if (callee.value == null && node.optional) { + return { value: undefined, optional: true } + } + const func = /** @type {(...args: any[]) => any} */ ( + callee.value + ); + if (callAllowed.has(func)) { + return { value: func(...args) } + } + if (callPassThrough.has(func)) { + return { value: args[0] } + } + } + } + } + + return null + }, + + ConditionalExpression(node, initialScope) { + const test = getStaticValueR(node.test, initialScope); + if (test != null) { + return test.value + ? getStaticValueR(node.consequent, initialScope) + : getStaticValueR(node.alternate, initialScope) + } + return null + }, + + ExpressionStatement(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + + Identifier(node, initialScope) { + if (initialScope != null) { + const variable = findVariable(initialScope, node); + + // Built-in globals. + if ( + variable != null && + variable.defs.length === 0 && + builtinNames.has(variable.name) && + variable.name in globalObject + ) { + return { value: globalObject[variable.name] } + } + + // Constants. + if (variable != null && variable.defs.length === 1) { + const def = variable.defs[0]; + if ( + def.parent && + def.type === "Variable" && + (def.parent.kind === "const" || + isEffectivelyConst(variable)) && + // TODO(mysticatea): don't support destructuring here. + def.node.id.type === "Identifier" + ) { + return getStaticValueR(def.node.init, initialScope) + } + } + } + return null + }, + + Literal(node) { + const literal = + /** @type {Partial & Partial & Partial} */ ( + node + ); + //istanbul ignore if : this is implementation-specific behavior. + if ( + (literal.regex != null || literal.bigint != null) && + literal.value == null + ) { + // It was a RegExp/BigInt literal, but Node.js didn't support it. + return null + } + return { value: literal.value } + }, + + LogicalExpression(node, initialScope) { + const left = getStaticValueR(node.left, initialScope); + if (left != null) { + if ( + (node.operator === "||" && Boolean(left.value) === true) || + (node.operator === "&&" && Boolean(left.value) === false) || + (node.operator === "??" && left.value != null) + ) { + return left + } + + const right = getStaticValueR(node.right, initialScope); + if (right != null) { + return right + } + } + + return null + }, + + MemberExpression(node, initialScope) { + if (node.property.type === "PrivateIdentifier") { + return null + } + const object = getStaticValueR(node.object, initialScope); + if (object != null) { + if (object.value == null && (object.optional || node.optional)) { + return { value: undefined, optional: true } + } + const property = getStaticPropertyNameValue(node, initialScope); + + if (property != null) { + if ( + !isGetter( + /** @type {object} */ (object.value), + /** @type {PropertyKey} */ (property.value), + ) + ) { + return { + value: /** @type {Record} */ ( + object.value + )[/** @type {PropertyKey} */ (property.value)], + } + } + + for (const [classFn, allowed] of getterAllowed) { + if ( + object.value instanceof classFn && + allowed.has(/** @type {string} */ (property.value)) + ) { + return { + value: /** @type {Record} */ ( + object.value + )[/** @type {PropertyKey} */ (property.value)], + } + } + } + } + } + return null + }, + + ChainExpression(node, initialScope) { + const expression = getStaticValueR(node.expression, initialScope); + if (expression != null) { + return { value: expression.value } + } + return null + }, + + NewExpression(node, initialScope) { + const callee = getStaticValueR(node.callee, initialScope); + const args = getElementValues(node.arguments, initialScope); + + if (callee != null && args != null) { + const Func = /** @type {new (...args: any[]) => any} */ ( + callee.value + ); + if (callAllowed.has(Func)) { + return { value: new Func(...args) } + } + } + + return null + }, + + ObjectExpression(node, initialScope) { + /** @type {Record} */ + const object = {}; + + for (const propertyNode of node.properties) { + if (propertyNode.type === "Property") { + if (propertyNode.kind !== "init") { + return null + } + const key = getStaticPropertyNameValue( + propertyNode, + initialScope, + ); + const value = getStaticValueR(propertyNode.value, initialScope); + if (key == null || value == null) { + return null + } + object[/** @type {PropertyKey} */ (key.value)] = value.value; + } else if ( + propertyNode.type === "SpreadElement" || + // @ts-expect-error -- Backward compatibility + propertyNode.type === "ExperimentalSpreadProperty" + ) { + const argument = getStaticValueR( + propertyNode.argument, + initialScope, + ); + if (argument == null) { + return null + } + Object.assign(object, argument.value); + } else { + return null + } + } + + return { value: object } + }, + + SequenceExpression(node, initialScope) { + const last = node.expressions[node.expressions.length - 1]; + return getStaticValueR(last, initialScope) + }, + + TaggedTemplateExpression(node, initialScope) { + const tag = getStaticValueR(node.tag, initialScope); + const expressions = getElementValues( + node.quasi.expressions, + initialScope, + ); + + if (tag != null && expressions != null) { + const func = /** @type {(...args: any[]) => any} */ (tag.value); + /** @type {any[] & { raw?: string[] }} */ + const strings = node.quasi.quasis.map((q) => q.value.cooked); + strings.raw = node.quasi.quasis.map((q) => q.value.raw); + + if (func === String.raw) { + return { value: func(strings, ...expressions) } + } + } + + return null + }, + + TemplateLiteral(node, initialScope) { + const expressions = getElementValues(node.expressions, initialScope); + if (expressions != null) { + let value = node.quasis[0].value.cooked; + for (let i = 0; i < expressions.length; ++i) { + value += expressions[i]; + value += /** @type {string} */ (node.quasis[i + 1].value.cooked); + } + return { value } + } + return null + }, + + UnaryExpression(node, initialScope) { + if (node.operator === "delete") { + // Not supported. + return null + } + if (node.operator === "void") { + return { value: undefined } + } + + const arg = getStaticValueR(node.argument, initialScope); + if (arg != null) { + switch (node.operator) { + case "-": + return { value: -(/** @type {any} */ (arg.value)) } + case "+": + return { value: +(/** @type {any} */ (arg.value)) } //eslint-disable-line no-implicit-coercion + case "!": + return { value: !arg.value } + case "~": + return { value: ~(/** @type {any} */ (arg.value)) } + case "typeof": + return { value: typeof arg.value } + + // no default + } + } + + return null + }, + TSAsExpression(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + TSSatisfiesExpression(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + TSTypeAssertion(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + TSNonNullExpression(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, + TSInstantiationExpression(node, initialScope) { + return getStaticValueR(node.expression, initialScope) + }, +}); + +/** + * Get the value of a given node if it's a static value. + * @param {Node|TSESTreeNode|null|undefined} node The node to get. + * @param {Scope|undefined|null} initialScope The scope to start finding variable. + * @returns {StaticValue|null} The static value of the node, or `null`. + */ +function getStaticValueR(node, initialScope) { + if (node != null && Object.hasOwnProperty.call(operations, node.type)) { + return /** @type {VisitorCallback} */ (operations[node.type])( + /** @type {TSESTreeNode} */ (node), + initialScope, + ) + } + return null +} + +/** + * Get the static value of property name from a MemberExpression node or a Property node. + * @param {MemberExpression|Property} node The node to get. + * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it. + * @returns {StaticValue|null} The static value of the property name of the node, or `null`. + */ +function getStaticPropertyNameValue(node, initialScope) { + const nameNode = node.type === "Property" ? node.key : node.property; + + if (node.computed) { + return getStaticValueR(nameNode, initialScope) + } + + if (nameNode.type === "Identifier") { + return { value: nameNode.name } + } + + if (nameNode.type === "Literal") { + if (/** @type {Partial} */ (nameNode).bigint) { + return { value: /** @type {BigIntLiteral} */ (nameNode).bigint } + } + return { value: String(nameNode.value) } + } + + return null +} + +/** + * Get the value of a given node if it's a static value. + * @param {Node} node The node to get. + * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible. + * @returns {StaticValue | null} The static value of the node, or `null`. + */ +function getStaticValue(node, initialScope = null) { + try { + return getStaticValueR(node, initialScope) + } catch (_error) { + return null + } +} + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").RegExpLiteral} RegExpLiteral */ +/** @typedef {import("estree").BigIntLiteral} BigIntLiteral */ +/** @typedef {import("estree").SimpleLiteral} SimpleLiteral */ + +/** + * Get the value of a given node if it's a literal or a template literal. + * @param {Node} node The node to get. + * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant. + * @returns {string|null} The value of the node, or `null`. + */ +function getStringIfConstant(node, initialScope = null) { + // Handle the literals that the platform doesn't support natively. + if (node && node.type === "Literal" && node.value === null) { + const literal = + /** @type {Partial & Partial & Partial} */ ( + node + ); + if (literal.regex) { + return `/${literal.regex.pattern}/${literal.regex.flags}` + } + if (literal.bigint) { + return literal.bigint + } + } + + const evaluated = getStaticValue(node, initialScope); + + if (evaluated) { + // `String(Symbol.prototype)` throws error + try { + return String(evaluated.value) + } catch { + // No op + } + } + + return null +} + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("estree").MethodDefinition} MethodDefinition */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */ +/** @typedef {import("estree").Identifier} Identifier */ + +/** + * Get the property name from a MemberExpression node or a Property node. + * @param {MemberExpression | MethodDefinition | Property | PropertyDefinition} node The node to get. + * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it. + * @returns {string|null|undefined} The property name of the node. + */ +function getPropertyName(node, initialScope) { + switch (node.type) { + case "MemberExpression": + if (node.computed) { + return getStringIfConstant(node.property, initialScope) + } + if (node.property.type === "PrivateIdentifier") { + return null + } + return /** @type {Partial} */ (node.property).name + + case "Property": + case "MethodDefinition": + case "PropertyDefinition": + if (node.computed) { + return getStringIfConstant(node.key, initialScope) + } + if (node.key.type === "Literal") { + return String(node.key.value) + } + if (node.key.type === "PrivateIdentifier") { + return null + } + return /** @type {Partial} */ (node.key).name + } + + return null +} + +/** @typedef {import("eslint").Rule.Node} RuleNode */ +/** @typedef {import("eslint").SourceCode} SourceCode */ +/** @typedef {import("estree").Function} FunctionNode */ +/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */ +/** @typedef {import("estree").FunctionExpression} FunctionExpression */ +/** @typedef {import("estree").Identifier} Identifier */ + +/** + * Get the name and kind of the given function node. + * @param {FunctionNode} node - The function node to get. + * @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys. + * @returns {string} The name and kind of the function node. + */ +// eslint-disable-next-line complexity +function getFunctionNameWithKind(node, sourceCode) { + const parent = /** @type {RuleNode} */ (node).parent; + const tokens = []; + const isObjectMethod = parent.type === "Property" && parent.value === node; + const isClassMethod = + parent.type === "MethodDefinition" && parent.value === node; + const isClassFieldMethod = + parent.type === "PropertyDefinition" && parent.value === node; + + // Modifiers. + if (isClassMethod || isClassFieldMethod) { + if (parent.static) { + tokens.push("static"); + } + if (parent.key.type === "PrivateIdentifier") { + tokens.push("private"); + } + } + if (node.async) { + tokens.push("async"); + } + if (node.generator) { + tokens.push("generator"); + } + + // Kinds. + if (isObjectMethod || isClassMethod) { + if (parent.kind === "constructor") { + return "constructor" + } + if (parent.kind === "get") { + tokens.push("getter"); + } else if (parent.kind === "set") { + tokens.push("setter"); + } else { + tokens.push("method"); + } + } else if (isClassFieldMethod) { + tokens.push("method"); + } else { + if (node.type === "ArrowFunctionExpression") { + tokens.push("arrow"); + } + tokens.push("function"); + } + + // Names. + if (isObjectMethod || isClassMethod || isClassFieldMethod) { + if (parent.key.type === "PrivateIdentifier") { + tokens.push(`#${parent.key.name}`); + } else { + const name = getPropertyName(parent); + if (name) { + tokens.push(`'${name}'`); + } else if (sourceCode) { + const keyText = sourceCode.getText(parent.key); + if (!keyText.includes("\n")) { + tokens.push(`[${keyText}]`); + } + } + } + } else if (hasId(node)) { + tokens.push(`'${node.id.name}'`); + } else if ( + parent.type === "VariableDeclarator" && + parent.id && + parent.id.type === "Identifier" + ) { + tokens.push(`'${parent.id.name}'`); + } else if ( + (parent.type === "AssignmentExpression" || + parent.type === "AssignmentPattern") && + parent.left && + parent.left.type === "Identifier" + ) { + tokens.push(`'${parent.left.name}'`); + } else if ( + parent.type === "ExportDefaultDeclaration" && + parent.declaration === node + ) { + tokens.push("'default'"); + } + + return tokens.join(" ") +} + +/** + * @param {FunctionNode} node + * @returns {node is FunctionDeclaration | FunctionExpression & { id: Identifier }} + */ +function hasId(node) { + return Boolean( + /** @type {Partial} */ (node) + .id, + ) +} + +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("eslint").SourceCode} SourceCode */ +/** @typedef {import("./types.mjs").HasSideEffectOptions} HasSideEffectOptions */ +/** @typedef {import("estree").BinaryExpression} BinaryExpression */ +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("estree").MethodDefinition} MethodDefinition */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */ +/** @typedef {import("estree").UnaryExpression} UnaryExpression */ + +const typeConversionBinaryOps = Object.freeze( + new Set([ + "==", + "!=", + "<", + "<=", + ">", + ">=", + "<<", + ">>", + ">>>", + "+", + "-", + "*", + "/", + "%", + "|", + "^", + "&", + "in", + ]), +); +const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"])); + +/** + * Check whether the given value is an ASTNode or not. + * @param {any} x The value to check. + * @returns {x is Node} `true` if the value is an ASTNode. + */ +function isNode(x) { + return x !== null && typeof x === "object" && typeof x.type === "string" +} + +const visitor = Object.freeze( + Object.assign(Object.create(null), { + /** + * @param {Node} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + $visit(node, options, visitorKeys) { + const { type } = node; + + if (typeof (/** @type {any} */ (this)[type]) === "function") { + return /** @type {any} */ (this)[type]( + node, + options, + visitorKeys, + ) + } + + return this.$visitChildren(node, options, visitorKeys) + }, + + /** + * @param {Node} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + $visitChildren(node, options, visitorKeys) { + const { type } = node; + + for (const key of /** @type {(keyof Node)[]} */ ( + visitorKeys[type] || getKeys(node) + )) { + const value = node[key]; + + if (Array.isArray(value)) { + for (const element of value) { + if ( + isNode(element) && + this.$visit(element, options, visitorKeys) + ) { + return true + } + } + } else if ( + isNode(value) && + this.$visit(value, options, visitorKeys) + ) { + return true + } + } + + return false + }, + + ArrowFunctionExpression() { + return false + }, + AssignmentExpression() { + return true + }, + AwaitExpression() { + return true + }, + /** + * @param {BinaryExpression} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + BinaryExpression(node, options, visitorKeys) { + if ( + options.considerImplicitTypeConversion && + typeConversionBinaryOps.has(node.operator) && + (node.left.type !== "Literal" || node.right.type !== "Literal") + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + CallExpression() { + return true + }, + FunctionExpression() { + return false + }, + ImportExpression() { + return true + }, + /** + * @param {MemberExpression} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + MemberExpression(node, options, visitorKeys) { + if (options.considerGetters) { + return true + } + if ( + options.considerImplicitTypeConversion && + node.computed && + node.property.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + /** + * @param {MethodDefinition} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + MethodDefinition(node, options, visitorKeys) { + if ( + options.considerImplicitTypeConversion && + node.computed && + node.key.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + NewExpression() { + return true + }, + /** + * @param {Property} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + Property(node, options, visitorKeys) { + if ( + options.considerImplicitTypeConversion && + node.computed && + node.key.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + /** + * @param {PropertyDefinition} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + PropertyDefinition(node, options, visitorKeys) { + if ( + options.considerImplicitTypeConversion && + node.computed && + node.key.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + /** + * @param {UnaryExpression} node + * @param {HasSideEffectOptions} options + * @param {Record} visitorKeys + */ + UnaryExpression(node, options, visitorKeys) { + if (node.operator === "delete") { + return true + } + if ( + options.considerImplicitTypeConversion && + typeConversionUnaryOps.has(node.operator) && + node.argument.type !== "Literal" + ) { + return true + } + return this.$visitChildren(node, options, visitorKeys) + }, + UpdateExpression() { + return true + }, + YieldExpression() { + return true + }, + }), +); + +/** + * Check whether a given node has any side effect or not. + * @param {Node} node The node to get. + * @param {SourceCode} sourceCode The source code object. + * @param {HasSideEffectOptions} [options] The option object. + * @returns {boolean} `true` if the node has a certain side effect. + */ +function hasSideEffect(node, sourceCode, options = {}) { + const { considerGetters = false, considerImplicitTypeConversion = false } = + options; + return visitor.$visit( + node, + { considerGetters, considerImplicitTypeConversion }, + sourceCode.visitorKeys || KEYS, + ) +} + +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("eslint").SourceCode} SourceCode */ +/** @typedef {import("eslint").AST.Token} Token */ +/** @typedef {import("eslint").Rule.Node} RuleNode */ + +/** + * Get the left parenthesis of the parent node syntax if it exists. + * E.g., `if (a) {}` then the `(`. + * @param {Node} node The AST node to check. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token|null} The left parenthesis of the parent node syntax + */ +function getParentSyntaxParen(node, sourceCode) { + const parent = /** @type {RuleNode} */ (node).parent; + + switch (parent.type) { + case "CallExpression": + case "NewExpression": + if (parent.arguments.length === 1 && parent.arguments[0] === node) { + return sourceCode.getTokenAfter( + parent.callee, + isOpeningParenToken, + ) + } + return null + + case "DoWhileStatement": + if (parent.test === node) { + return sourceCode.getTokenAfter( + parent.body, + isOpeningParenToken, + ) + } + return null + + case "IfStatement": + case "WhileStatement": + if (parent.test === node) { + return sourceCode.getFirstToken(parent, 1) + } + return null + + case "ImportExpression": + if (parent.source === node) { + return sourceCode.getFirstToken(parent, 1) + } + return null + + case "SwitchStatement": + if (parent.discriminant === node) { + return sourceCode.getFirstToken(parent, 1) + } + return null + + case "WithStatement": + if (parent.object === node) { + return sourceCode.getFirstToken(parent, 1) + } + return null + + default: + return null + } +} + +/** + * Check whether a given node is parenthesized or not. + * @param {number} times The number of parantheses. + * @param {Node} node The AST node to check. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {boolean} `true` if the node is parenthesized the given times. + */ +/** + * Check whether a given node is parenthesized or not. + * @param {Node} node The AST node to check. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {boolean} `true` if the node is parenthesized. + */ +/** + * Check whether a given node is parenthesized or not. + * @param {Node|number} timesOrNode The first parameter. + * @param {Node|SourceCode} nodeOrSourceCode The second parameter. + * @param {SourceCode} [optionalSourceCode] The third parameter. + * @returns {boolean} `true` if the node is parenthesized. + */ +function isParenthesized( + timesOrNode, + nodeOrSourceCode, + optionalSourceCode, +) { + /** @type {number} */ + let times, + /** @type {RuleNode} */ + node, + /** @type {SourceCode} */ + sourceCode, + maybeLeftParen, + maybeRightParen; + if (typeof timesOrNode === "number") { + times = timesOrNode | 0; + node = /** @type {RuleNode} */ (nodeOrSourceCode); + sourceCode = /** @type {SourceCode} */ (optionalSourceCode); + if (!(times >= 1)) { + throw new TypeError("'times' should be a positive integer.") + } + } else { + times = 1; + node = /** @type {RuleNode} */ (timesOrNode); + sourceCode = /** @type {SourceCode} */ (nodeOrSourceCode); + } + + if ( + node == null || + // `Program` can't be parenthesized + node.parent == null || + // `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}` + (node.parent.type === "CatchClause" && node.parent.param === node) + ) { + return false + } + + maybeLeftParen = maybeRightParen = node; + do { + maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen); + maybeRightParen = sourceCode.getTokenAfter(maybeRightParen); + } while ( + maybeLeftParen != null && + maybeRightParen != null && + isOpeningParenToken(maybeLeftParen) && + isClosingParenToken(maybeRightParen) && + // Avoid false positive such as `if (a) {}` + maybeLeftParen !== getParentSyntaxParen(node, sourceCode) && + --times > 0 + ) + + return times === 0 +} + +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ + +const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu; + +/** @type {WeakMap} */ +const internal = new WeakMap(); + +/** + * Check whether a given character is escaped or not. + * @param {string} str The string to check. + * @param {number} index The location of the character to check. + * @returns {boolean} `true` if the character is escaped. + */ +function isEscaped(str, index) { + let escaped = false; + for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) { + escaped = !escaped; + } + return escaped +} + +/** + * Replace a given string by a given matcher. + * @param {PatternMatcher} matcher The pattern matcher. + * @param {string} str The string to be replaced. + * @param {string} replacement The new substring to replace each matched part. + * @returns {string} The replaced string. + */ +function replaceS(matcher, str, replacement) { + const chunks = []; + let index = 0; + + /** + * @param {string} key The placeholder. + * @param {RegExpExecArray} match The matched information. + * @returns {string} The replaced string. + */ + function replacer(key, match) { + switch (key) { + case "$$": + return "$" + case "$&": + return match[0] + case "$`": + return str.slice(0, match.index) + case "$'": + return str.slice(match.index + match[0].length) + default: { + const i = key.slice(1); + if (i in match) { + return match[/** @type {any} */ (i)] + } + return key + } + } + } + + for (const match of matcher.execAll(str)) { + chunks.push(str.slice(index, match.index)); + chunks.push( + replacement.replace(placeholder, (key) => replacer(key, match)), + ); + index = match.index + match[0].length; + } + chunks.push(str.slice(index)); + + return chunks.join("") +} + +/** + * Replace a given string by a given matcher. + * @param {PatternMatcher} matcher The pattern matcher. + * @param {string} str The string to be replaced. + * @param {(substring: string, ...args: any[]) => string} replace The function to replace each matched part. + * @returns {string} The replaced string. + */ +function replaceF(matcher, str, replace) { + const chunks = []; + let index = 0; + + for (const match of matcher.execAll(str)) { + chunks.push(str.slice(index, match.index)); + chunks.push( + String( + replace( + .../** @type {[string, ...string[]]} */ ( + /** @type {string[]} */ (match) + ), + match.index, + match.input, + ), + ), + ); + index = match.index + match[0].length; + } + chunks.push(str.slice(index)); + + return chunks.join("") +} + +/** + * The class to find patterns as considering escape sequences. + */ +class PatternMatcher { + /** + * Initialize this matcher. + * @param {RegExp} pattern The pattern to match. + * @param {{escaped?:boolean}} [options] The options. + */ + constructor(pattern, options = {}) { + const { escaped = false } = options; + if (!(pattern instanceof RegExp)) { + throw new TypeError("'pattern' should be a RegExp instance.") + } + if (!pattern.flags.includes("g")) { + throw new Error("'pattern' should contains 'g' flag.") + } + + internal.set(this, { + pattern: new RegExp(pattern.source, pattern.flags), + escaped: Boolean(escaped), + }); + } + + /** + * Find the pattern in a given string. + * @param {string} str The string to find. + * @returns {IterableIterator} The iterator which iterate the matched information. + */ + *execAll(str) { + const { pattern, escaped } = + /** @type {{pattern:RegExp,escaped:boolean}} */ (internal.get(this)); + let match = null; + let lastIndex = 0; + + pattern.lastIndex = 0; + while ((match = pattern.exec(str)) != null) { + if (escaped || !isEscaped(str, match.index)) { + lastIndex = pattern.lastIndex; + yield match; + pattern.lastIndex = lastIndex; + } + } + } + + /** + * Check whether the pattern is found in a given string. + * @param {string} str The string to check. + * @returns {boolean} `true` if the pattern was found in the string. + */ + test(str) { + const it = this.execAll(str); + const ret = it.next(); + return !ret.done + } + + /** + * Replace a given string. + * @param {string} str The string to be replaced. + * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`. + * @returns {string} The replaced string. + */ + [Symbol.replace](str, replacer) { + return typeof replacer === "function" + ? replaceF(this, String(str), replacer) + : replaceS(this, String(str), String(replacer)) + } +} + +/** @typedef {import("eslint").Scope.Scope} Scope */ +/** @typedef {import("eslint").Scope.Variable} Variable */ +/** @typedef {import("eslint").Rule.Node} RuleNode */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").Pattern} Pattern */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").SimpleCallExpression} CallExpression */ +/** @typedef {import("estree").Program} Program */ +/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */ +/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */ +/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */ +/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */ +/** @typedef {import("estree").ImportSpecifier} ImportSpecifier */ +/** @typedef {import("estree").ImportDefaultSpecifier} ImportDefaultSpecifier */ +/** @typedef {import("estree").ImportNamespaceSpecifier} ImportNamespaceSpecifier */ +/** @typedef {import("estree").ExportSpecifier} ExportSpecifier */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */ +/** @typedef {import("estree").Literal} Literal */ +/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */ +/** @typedef {import("./types.mjs").ReferenceTrackerOptions} ReferenceTrackerOptions */ +/** + * @template T + * @typedef {import("./types.mjs").TraceMap} TraceMap + */ +/** + * @template T + * @typedef {import("./types.mjs").TraceMapObject} TraceMapObject + */ +/** + * @template T + * @typedef {import("./types.mjs").TrackedReferences} TrackedReferences + */ + +const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u; + +/** + * Check whether a given node is an import node or not. + * @param {Node} node + * @returns {node is ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration&{source: Literal}} `true` if the node is an import node. + */ +function isHasSource(node) { + return ( + IMPORT_TYPE.test(node.type) && + /** @type {ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration} */ ( + node + ).source != null + ) +} +const has = + /** @type {(traceMap: TraceMap, v: T) => v is (string extends T ? string : T)} */ ( + Function.call.bind(Object.hasOwnProperty) + ); + +const READ = Symbol("read"); +const CALL = Symbol("call"); +const CONSTRUCT = Symbol("construct"); +const ESM = Symbol("esm"); + +const requireCall = { require: { [CALL]: true } }; + +/** + * Check whether a given variable is modified or not. + * @param {Variable|undefined} variable The variable to check. + * @returns {boolean} `true` if the variable is modified. + */ +function isModifiedGlobal(variable) { + return ( + variable == null || + variable.defs.length !== 0 || + variable.references.some((r) => r.isWrite()) + ) +} + +/** + * Check if the value of a given node is passed through to the parent syntax as-is. + * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through. + * @param {Node} node A node to check. + * @returns {node is RuleNode & {parent: Expression}} `true` if the node is passed through. + */ +function isPassThrough(node) { + const parent = /** @type {TSESTreeNode} */ (node).parent; + + if (parent) { + switch (parent.type) { + case "ConditionalExpression": + return parent.consequent === node || parent.alternate === node + case "LogicalExpression": + return true + case "SequenceExpression": + return ( + parent.expressions[parent.expressions.length - 1] === node + ) + case "ChainExpression": + return true + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + case "TSInstantiationExpression": + return true + + default: + return false + } + } + return false +} + +/** + * The reference tracker. + */ +class ReferenceTracker { + /** + * Initialize this tracker. + * @param {Scope} globalScope The global scope. + * @param {object} [options] The options. + * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules. + * @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object. + */ + constructor(globalScope, options = {}) { + const { + mode = "strict", + globalObjectNames = ["global", "globalThis", "self", "window"], + } = options; + /** @private @type {Variable[]} */ + this.variableStack = []; + /** @private */ + this.globalScope = globalScope; + /** @private */ + this.mode = mode; + /** @private */ + this.globalObjectNames = globalObjectNames.slice(0); + } + + /** + * Iterate the references of global variables. + * @template T + * @param {TraceMap} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *iterateGlobalReferences(traceMap) { + for (const key of Object.keys(traceMap)) { + const nextTraceMap = traceMap[key]; + const path = [key]; + const variable = this.globalScope.set.get(key); + + if (isModifiedGlobal(variable)) { + continue + } + + yield* this._iterateVariableReferences( + /** @type {Variable} */ (variable), + path, + nextTraceMap, + true, + ); + } + + for (const key of this.globalObjectNames) { + /** @type {string[]} */ + const path = []; + const variable = this.globalScope.set.get(key); + + if (isModifiedGlobal(variable)) { + continue + } + + yield* this._iterateVariableReferences( + /** @type {Variable} */ (variable), + path, + traceMap, + false, + ); + } + } + + /** + * Iterate the references of CommonJS modules. + * @template T + * @param {TraceMap} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *iterateCjsReferences(traceMap) { + for (const { node } of this.iterateGlobalReferences(requireCall)) { + const key = getStringIfConstant( + /** @type {CallExpression} */ (node).arguments[0], + ); + if (key == null || !has(traceMap, key)) { + continue + } + + const nextTraceMap = traceMap[key]; + const path = [key]; + + if (nextTraceMap[READ]) { + yield { + node, + path, + type: READ, + info: nextTraceMap[READ], + }; + } + yield* this._iteratePropertyReferences( + /** @type {CallExpression} */ (node), + path, + nextTraceMap, + ); + } + } + + /** + * Iterate the references of ES modules. + * @template T + * @param {TraceMap} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *iterateEsmReferences(traceMap) { + const programNode = /** @type {Program} */ (this.globalScope.block); + + for (const node of programNode.body) { + if (!isHasSource(node)) { + continue + } + const moduleId = /** @type {string} */ (node.source.value); + + if (!has(traceMap, moduleId)) { + continue + } + const nextTraceMap = traceMap[moduleId]; + const path = [moduleId]; + + if (nextTraceMap[READ]) { + yield { + // eslint-disable-next-line object-shorthand -- apply type + node: /** @type {RuleNode} */ (node), + path, + type: READ, + info: nextTraceMap[READ], + }; + } + + if (node.type === "ExportAllDeclaration") { + for (const key of Object.keys(nextTraceMap)) { + const exportTraceMap = nextTraceMap[key]; + if (exportTraceMap[READ]) { + yield { + // eslint-disable-next-line object-shorthand -- apply type + node: /** @type {RuleNode} */ (node), + path: path.concat(key), + type: READ, + info: exportTraceMap[READ], + }; + } + } + } else { + for (const specifier of node.specifiers) { + const esm = has(nextTraceMap, ESM); + const it = this._iterateImportReferences( + specifier, + path, + esm + ? nextTraceMap + : this.mode === "legacy" + ? { default: nextTraceMap, ...nextTraceMap } + : { default: nextTraceMap }, + ); + + if (esm) { + yield* it; + } else { + for (const report of it) { + report.path = report.path.filter(exceptDefault); + if ( + report.path.length >= 2 || + report.type !== READ + ) { + yield report; + } + } + } + } + } + } + } + + /** + * Iterate the property references for a given expression AST node. + * @template T + * @param {Expression} node The expression AST node to iterate property references. + * @param {TraceMap} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate property references. + */ + *iteratePropertyReferences(node, traceMap) { + yield* this._iteratePropertyReferences(node, [], traceMap); + } + + /** + * Iterate the references for a given variable. + * @private + * @template T + * @param {Variable} variable The variable to iterate that references. + * @param {string[]} path The current path. + * @param {TraceMapObject} traceMap The trace map. + * @param {boolean} shouldReport = The flag to report those references. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *_iterateVariableReferences(variable, path, traceMap, shouldReport) { + if (this.variableStack.includes(variable)) { + return + } + this.variableStack.push(variable); + try { + for (const reference of variable.references) { + if (!reference.isRead()) { + continue + } + const node = /** @type {RuleNode & Identifier} */ ( + reference.identifier + ); + + if (shouldReport && traceMap[READ]) { + yield { node, path, type: READ, info: traceMap[READ] }; + } + yield* this._iteratePropertyReferences(node, path, traceMap); + } + } finally { + this.variableStack.pop(); + } + } + + /** + * Iterate the references for a given AST node. + * @private + * @template T + * @param {Expression} rootNode The AST node to iterate references. + * @param {string[]} path The current path. + * @param {TraceMapObject} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + //eslint-disable-next-line complexity + *_iteratePropertyReferences(rootNode, path, traceMap) { + let node = rootNode; + while (isPassThrough(node)) { + node = node.parent; + } + + const parent = /** @type {RuleNode} */ (node).parent; + if (parent.type === "MemberExpression") { + if (parent.object === node) { + const key = getPropertyName(parent); + if (key == null || !has(traceMap, key)) { + return + } + + path = path.concat(key); //eslint-disable-line no-param-reassign + const nextTraceMap = traceMap[key]; + if (nextTraceMap[READ]) { + yield { + node: parent, + path, + type: READ, + info: nextTraceMap[READ], + }; + } + yield* this._iteratePropertyReferences( + parent, + path, + nextTraceMap, + ); + } + return + } + if (parent.type === "CallExpression") { + if (parent.callee === node && traceMap[CALL]) { + yield { node: parent, path, type: CALL, info: traceMap[CALL] }; + } + return + } + if (parent.type === "NewExpression") { + if (parent.callee === node && traceMap[CONSTRUCT]) { + yield { + node: parent, + path, + type: CONSTRUCT, + info: traceMap[CONSTRUCT], + }; + } + return + } + if (parent.type === "AssignmentExpression") { + if (parent.right === node) { + yield* this._iterateLhsReferences(parent.left, path, traceMap); + yield* this._iteratePropertyReferences(parent, path, traceMap); + } + return + } + if (parent.type === "AssignmentPattern") { + if (parent.right === node) { + yield* this._iterateLhsReferences(parent.left, path, traceMap); + } + return + } + if (parent.type === "VariableDeclarator") { + if (parent.init === node) { + yield* this._iterateLhsReferences(parent.id, path, traceMap); + } + } + } + + /** + * Iterate the references for a given Pattern node. + * @private + * @template T + * @param {Pattern} patternNode The Pattern node to iterate references. + * @param {string[]} path The current path. + * @param {TraceMapObject} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *_iterateLhsReferences(patternNode, path, traceMap) { + if (patternNode.type === "Identifier") { + const variable = findVariable(this.globalScope, patternNode); + if (variable != null) { + yield* this._iterateVariableReferences( + variable, + path, + traceMap, + false, + ); + } + return + } + if (patternNode.type === "ObjectPattern") { + for (const property of patternNode.properties) { + const key = getPropertyName( + /** @type {AssignmentProperty} */ (property), + ); + + if (key == null || !has(traceMap, key)) { + continue + } + + const nextPath = path.concat(key); + const nextTraceMap = traceMap[key]; + if (nextTraceMap[READ]) { + yield { + node: /** @type {RuleNode} */ (property), + path: nextPath, + type: READ, + info: nextTraceMap[READ], + }; + } + yield* this._iterateLhsReferences( + /** @type {AssignmentProperty} */ (property).value, + nextPath, + nextTraceMap, + ); + } + return + } + if (patternNode.type === "AssignmentPattern") { + yield* this._iterateLhsReferences(patternNode.left, path, traceMap); + } + } + + /** + * Iterate the references for a given ModuleSpecifier node. + * @private + * @template T + * @param {ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier} specifierNode The ModuleSpecifier node to iterate references. + * @param {string[]} path The current path. + * @param {TraceMapObject} traceMap The trace map. + * @returns {IterableIterator>} The iterator to iterate references. + */ + *_iterateImportReferences(specifierNode, path, traceMap) { + const type = specifierNode.type; + + if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") { + const key = + type === "ImportDefaultSpecifier" + ? "default" + : specifierNode.imported.type === "Identifier" + ? specifierNode.imported.name + : specifierNode.imported.value; + if (!has(traceMap, key)) { + return + } + + path = path.concat(key); //eslint-disable-line no-param-reassign + const nextTraceMap = traceMap[key]; + if (nextTraceMap[READ]) { + yield { + node: /** @type {RuleNode} */ (specifierNode), + path, + type: READ, + info: nextTraceMap[READ], + }; + } + yield* this._iterateVariableReferences( + /** @type {Variable} */ ( + findVariable(this.globalScope, specifierNode.local) + ), + path, + nextTraceMap, + false, + ); + + return + } + + if (type === "ImportNamespaceSpecifier") { + yield* this._iterateVariableReferences( + /** @type {Variable} */ ( + findVariable(this.globalScope, specifierNode.local) + ), + path, + traceMap, + false, + ); + return + } + + if (type === "ExportSpecifier") { + const key = + specifierNode.local.type === "Identifier" + ? specifierNode.local.name + : specifierNode.local.value; + if (!has(traceMap, key)) { + return + } + + path = path.concat(key); //eslint-disable-line no-param-reassign + const nextTraceMap = traceMap[key]; + if (nextTraceMap[READ]) { + yield { + node: /** @type {RuleNode} */ (specifierNode), + path, + type: READ, + info: nextTraceMap[READ], + }; + } + } + } +} + +ReferenceTracker.READ = READ; +ReferenceTracker.CALL = CALL; +ReferenceTracker.CONSTRUCT = CONSTRUCT; +ReferenceTracker.ESM = ESM; + +/** + * This is a predicate function for Array#filter. + * @param {string} name A name part. + * @param {number} index The index of the name. + * @returns {boolean} `false` if it's default. + */ +function exceptDefault(name, index) { + return !(index === 1 && name === "default") +} + +/** @typedef {import("./types.mjs").StaticValue} StaticValue */ + +var index = { + CALL, + CONSTRUCT, + ESM, + findVariable, + getFunctionHeadLocation, + getFunctionNameWithKind, + getInnermostScope, + getPropertyName, + getStaticValue, + getStringIfConstant, + hasSideEffect, + isArrowToken, + isClosingBraceToken, + isClosingBracketToken, + isClosingParenToken, + isColonToken, + isCommaToken, + isCommentToken, + isNotArrowToken, + isNotClosingBraceToken, + isNotClosingBracketToken, + isNotClosingParenToken, + isNotColonToken, + isNotCommaToken, + isNotCommentToken, + isNotOpeningBraceToken, + isNotOpeningBracketToken, + isNotOpeningParenToken, + isNotSemicolonToken, + isOpeningBraceToken, + isOpeningBracketToken, + isOpeningParenToken, + isParenthesized, + isSemicolonToken, + PatternMatcher, + READ, + ReferenceTracker, +}; + +export { CALL, CONSTRUCT, ESM, PatternMatcher, READ, ReferenceTracker, index as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/@eslint-community/eslint-utils/index.mjs.map b/node_modules/@eslint-community/eslint-utils/index.mjs.map new file mode 100644 index 00000000..687a6f71 --- /dev/null +++ b/node_modules/@eslint-community/eslint-utils/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["src/get-innermost-scope.mjs","src/find-variable.mjs","src/token-predicate.mjs","src/get-function-head-location.mjs","src/get-static-value.mjs","src/get-string-if-constant.mjs","src/get-property-name.mjs","src/get-function-name-with-kind.mjs","src/has-side-effect.mjs","src/is-parenthesized.mjs","src/pattern-matcher.mjs","src/reference-tracker.mjs","src/index.mjs"],"sourcesContent":["/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"estree\").Node} Node */\n\n/**\n * Get the innermost scope which contains a given location.\n * @param {Scope} initialScope The initial scope to search.\n * @param {Node} node The location to search.\n * @returns {Scope} The innermost scope.\n */\nexport function getInnermostScope(initialScope, node) {\n const location = /** @type {[number, number]} */ (node.range)[0]\n\n let scope = initialScope\n let found = false\n do {\n found = false\n for (const childScope of scope.childScopes) {\n const range = /** @type {[number, number]} */ (\n childScope.block.range\n )\n\n if (range[0] <= location && location < range[1]) {\n scope = childScope\n found = true\n break\n }\n }\n } while (found)\n\n return scope\n}\n","import { getInnermostScope } from \"./get-innermost-scope.mjs\"\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"eslint\").Scope.Variable} Variable */\n/** @typedef {import(\"estree\").Identifier} Identifier */\n\n/**\n * Find the variable of a given name.\n * @param {Scope} initialScope The scope to start finding.\n * @param {string|Identifier} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.\n * @returns {Variable|null} The found variable or null.\n */\nexport function findVariable(initialScope, nameOrNode) {\n let name = \"\"\n /** @type {Scope|null} */\n let scope = initialScope\n\n if (typeof nameOrNode === \"string\") {\n name = nameOrNode\n } else {\n name = nameOrNode.name\n scope = getInnermostScope(scope, nameOrNode)\n }\n\n while (scope != null) {\n const variable = scope.set.get(name)\n if (variable != null) {\n return variable\n }\n scope = scope.upper\n }\n\n return null\n}\n","/** @typedef {import(\"eslint\").AST.Token} Token */\n/** @typedef {import(\"estree\").Comment} Comment */\n/** @typedef {import(\"./types.mjs\").ArrowToken} ArrowToken */\n/** @typedef {import(\"./types.mjs\").CommaToken} CommaToken */\n/** @typedef {import(\"./types.mjs\").SemicolonToken} SemicolonToken */\n/** @typedef {import(\"./types.mjs\").ColonToken} ColonToken */\n/** @typedef {import(\"./types.mjs\").OpeningParenToken} OpeningParenToken */\n/** @typedef {import(\"./types.mjs\").ClosingParenToken} ClosingParenToken */\n/** @typedef {import(\"./types.mjs\").OpeningBracketToken} OpeningBracketToken */\n/** @typedef {import(\"./types.mjs\").ClosingBracketToken} ClosingBracketToken */\n/** @typedef {import(\"./types.mjs\").OpeningBraceToken} OpeningBraceToken */\n/** @typedef {import(\"./types.mjs\").ClosingBraceToken} ClosingBraceToken */\n/**\n * @template {string} Value\n * @typedef {import(\"./types.mjs\").PunctuatorToken} PunctuatorToken\n */\n\n/** @typedef {Comment | Token} CommentOrToken */\n\n/**\n * Creates the negate function of the given function.\n * @param {function(CommentOrToken):boolean} f - The function to negate.\n * @returns {function(CommentOrToken):boolean} Negated function.\n */\nfunction negate(f) {\n return (token) => !f(token)\n}\n\n/**\n * Checks if the given token is a PunctuatorToken with the given value\n * @template {string} Value\n * @param {CommentOrToken} token - The token to check.\n * @param {Value} value - The value to check.\n * @returns {token is PunctuatorToken} `true` if the token is a PunctuatorToken with the given value.\n */\nfunction isPunctuatorTokenWithValue(token, value) {\n return token.type === \"Punctuator\" && token.value === value\n}\n\n/**\n * Checks if the given token is an arrow token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ArrowToken} `true` if the token is an arrow token.\n */\nexport function isArrowToken(token) {\n return isPunctuatorTokenWithValue(token, \"=>\")\n}\n\n/**\n * Checks if the given token is a comma token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is CommaToken} `true` if the token is a comma token.\n */\nexport function isCommaToken(token) {\n return isPunctuatorTokenWithValue(token, \",\")\n}\n\n/**\n * Checks if the given token is a semicolon token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is SemicolonToken} `true` if the token is a semicolon token.\n */\nexport function isSemicolonToken(token) {\n return isPunctuatorTokenWithValue(token, \";\")\n}\n\n/**\n * Checks if the given token is a colon token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ColonToken} `true` if the token is a colon token.\n */\nexport function isColonToken(token) {\n return isPunctuatorTokenWithValue(token, \":\")\n}\n\n/**\n * Checks if the given token is an opening parenthesis token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is OpeningParenToken} `true` if the token is an opening parenthesis token.\n */\nexport function isOpeningParenToken(token) {\n return isPunctuatorTokenWithValue(token, \"(\")\n}\n\n/**\n * Checks if the given token is a closing parenthesis token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ClosingParenToken} `true` if the token is a closing parenthesis token.\n */\nexport function isClosingParenToken(token) {\n return isPunctuatorTokenWithValue(token, \")\")\n}\n\n/**\n * Checks if the given token is an opening square bracket token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is OpeningBracketToken} `true` if the token is an opening square bracket token.\n */\nexport function isOpeningBracketToken(token) {\n return isPunctuatorTokenWithValue(token, \"[\")\n}\n\n/**\n * Checks if the given token is a closing square bracket token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ClosingBracketToken} `true` if the token is a closing square bracket token.\n */\nexport function isClosingBracketToken(token) {\n return isPunctuatorTokenWithValue(token, \"]\")\n}\n\n/**\n * Checks if the given token is an opening brace token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is OpeningBraceToken} `true` if the token is an opening brace token.\n */\nexport function isOpeningBraceToken(token) {\n return isPunctuatorTokenWithValue(token, \"{\")\n}\n\n/**\n * Checks if the given token is a closing brace token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is ClosingBraceToken} `true` if the token is a closing brace token.\n */\nexport function isClosingBraceToken(token) {\n return isPunctuatorTokenWithValue(token, \"}\")\n}\n\n/**\n * Checks if the given token is a comment token or not.\n * @param {CommentOrToken} token - The token to check.\n * @returns {token is Comment} `true` if the token is a comment token.\n */\nexport function isCommentToken(token) {\n return [\"Block\", \"Line\", \"Shebang\"].includes(token.type)\n}\n\nexport const isNotArrowToken = negate(isArrowToken)\nexport const isNotCommaToken = negate(isCommaToken)\nexport const isNotSemicolonToken = negate(isSemicolonToken)\nexport const isNotColonToken = negate(isColonToken)\nexport const isNotOpeningParenToken = negate(isOpeningParenToken)\nexport const isNotClosingParenToken = negate(isClosingParenToken)\nexport const isNotOpeningBracketToken = negate(isOpeningBracketToken)\nexport const isNotClosingBracketToken = negate(isClosingBracketToken)\nexport const isNotOpeningBraceToken = negate(isOpeningBraceToken)\nexport const isNotClosingBraceToken = negate(isClosingBraceToken)\nexport const isNotCommentToken = negate(isCommentToken)\n","import { isArrowToken, isOpeningParenToken } from \"./token-predicate.mjs\"\n/** @typedef {import(\"eslint\").Rule.Node} RuleNode */\n/** @typedef {import(\"eslint\").SourceCode} SourceCode */\n/** @typedef {import(\"eslint\").AST.Token} Token */\n/** @typedef {import(\"estree\").Function} FunctionNode */\n/** @typedef {import(\"estree\").FunctionDeclaration} FunctionDeclaration */\n/** @typedef {import(\"estree\").FunctionExpression} FunctionExpression */\n/** @typedef {import(\"estree\").SourceLocation} SourceLocation */\n/** @typedef {import(\"estree\").Position} Position */\n\n/**\n * Get the `(` token of the given function node.\n * @param {FunctionExpression | FunctionDeclaration} node - The function node to get.\n * @param {SourceCode} sourceCode - The source code object to get tokens.\n * @returns {Token} `(` token.\n */\nfunction getOpeningParenOfParams(node, sourceCode) {\n return node.id\n ? /** @type {Token} */ (\n sourceCode.getTokenAfter(node.id, isOpeningParenToken)\n )\n : /** @type {Token} */ (\n sourceCode.getFirstToken(node, isOpeningParenToken)\n )\n}\n\n/**\n * Get the location of the given function node for reporting.\n * @param {FunctionNode} node - The function node to get.\n * @param {SourceCode} sourceCode - The source code object to get tokens.\n * @returns {SourceLocation|null} The location of the function node for reporting.\n */\nexport function getFunctionHeadLocation(node, sourceCode) {\n const parent = /** @type {RuleNode} */ (node).parent\n\n /** @type {Position|null} */\n let start = null\n /** @type {Position|null} */\n let end = null\n\n if (node.type === \"ArrowFunctionExpression\") {\n const arrowToken = /** @type {Token} */ (\n sourceCode.getTokenBefore(node.body, isArrowToken)\n )\n\n start = arrowToken.loc.start\n end = arrowToken.loc.end\n } else if (\n parent.type === \"Property\" ||\n parent.type === \"MethodDefinition\" ||\n parent.type === \"PropertyDefinition\"\n ) {\n start = /** @type {SourceLocation} */ (parent.loc).start\n end = getOpeningParenOfParams(node, sourceCode).loc.start\n } else {\n start = /** @type {SourceLocation} */ (node.loc).start\n end = getOpeningParenOfParams(node, sourceCode).loc.start\n }\n\n return {\n start: { ...start },\n end: { ...end },\n }\n}\n","/* globals globalThis, global, self, window */\n\nimport { findVariable } from \"./find-variable.mjs\"\n/** @typedef {import(\"./types.mjs\").StaticValue} StaticValue */\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.Node} TSESTreeNode */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.AST_NODE_TYPES} TSESTreeNodeTypes */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.MemberExpression} MemberExpression */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.Property} Property */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.RegExpLiteral} RegExpLiteral */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.BigIntLiteral} BigIntLiteral */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.Literal} Literal */\n\nconst globalObject =\n typeof globalThis !== \"undefined\"\n ? globalThis\n : // @ts-ignore\n typeof self !== \"undefined\"\n ? // @ts-ignore\n self\n : // @ts-ignore\n typeof window !== \"undefined\"\n ? // @ts-ignore\n window\n : typeof global !== \"undefined\"\n ? global\n : {}\n\nconst builtinNames = Object.freeze(\n new Set([\n \"Array\",\n \"ArrayBuffer\",\n \"BigInt\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n \"Boolean\",\n \"DataView\",\n \"Date\",\n \"decodeURI\",\n \"decodeURIComponent\",\n \"encodeURI\",\n \"encodeURIComponent\",\n \"escape\",\n \"Float32Array\",\n \"Float64Array\",\n \"Function\",\n \"Infinity\",\n \"Int16Array\",\n \"Int32Array\",\n \"Int8Array\",\n \"isFinite\",\n \"isNaN\",\n \"isPrototypeOf\",\n \"JSON\",\n \"Map\",\n \"Math\",\n \"NaN\",\n \"Number\",\n \"Object\",\n \"parseFloat\",\n \"parseInt\",\n \"Promise\",\n \"Proxy\",\n \"Reflect\",\n \"RegExp\",\n \"Set\",\n \"String\",\n \"Symbol\",\n \"Uint16Array\",\n \"Uint32Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"undefined\",\n \"unescape\",\n \"WeakMap\",\n \"WeakSet\",\n ]),\n)\nconst callAllowed = new Set(\n [\n Array.isArray,\n Array.of,\n Array.prototype.at,\n Array.prototype.concat,\n Array.prototype.entries,\n Array.prototype.every,\n Array.prototype.filter,\n Array.prototype.find,\n Array.prototype.findIndex,\n Array.prototype.flat,\n Array.prototype.includes,\n Array.prototype.indexOf,\n Array.prototype.join,\n Array.prototype.keys,\n Array.prototype.lastIndexOf,\n Array.prototype.slice,\n Array.prototype.some,\n Array.prototype.toString,\n Array.prototype.values,\n typeof BigInt === \"function\" ? BigInt : undefined,\n Boolean,\n Date,\n Date.parse,\n decodeURI,\n decodeURIComponent,\n encodeURI,\n encodeURIComponent,\n escape,\n isFinite,\n isNaN,\n // @ts-ignore\n isPrototypeOf,\n Map,\n Map.prototype.entries,\n Map.prototype.get,\n Map.prototype.has,\n Map.prototype.keys,\n Map.prototype.values,\n .../** @type {(keyof typeof Math)[]} */ (\n Object.getOwnPropertyNames(Math)\n )\n .filter((k) => k !== \"random\")\n .map((k) => Math[k])\n .filter((f) => typeof f === \"function\"),\n Number,\n Number.isFinite,\n Number.isNaN,\n Number.parseFloat,\n Number.parseInt,\n Number.prototype.toExponential,\n Number.prototype.toFixed,\n Number.prototype.toPrecision,\n Number.prototype.toString,\n Object,\n Object.entries,\n Object.is,\n Object.isExtensible,\n Object.isFrozen,\n Object.isSealed,\n Object.keys,\n Object.values,\n parseFloat,\n parseInt,\n RegExp,\n Set,\n Set.prototype.entries,\n Set.prototype.has,\n Set.prototype.keys,\n Set.prototype.values,\n String,\n String.fromCharCode,\n String.fromCodePoint,\n String.raw,\n String.prototype.at,\n String.prototype.charAt,\n String.prototype.charCodeAt,\n String.prototype.codePointAt,\n String.prototype.concat,\n String.prototype.endsWith,\n String.prototype.includes,\n String.prototype.indexOf,\n String.prototype.lastIndexOf,\n String.prototype.normalize,\n String.prototype.padEnd,\n String.prototype.padStart,\n String.prototype.slice,\n String.prototype.startsWith,\n String.prototype.substr,\n String.prototype.substring,\n String.prototype.toLowerCase,\n String.prototype.toString,\n String.prototype.toUpperCase,\n String.prototype.trim,\n String.prototype.trimEnd,\n String.prototype.trimLeft,\n String.prototype.trimRight,\n String.prototype.trimStart,\n Symbol.for,\n Symbol.keyFor,\n unescape,\n ].filter((f) => typeof f === \"function\"),\n)\nconst callPassThrough = new Set([\n Object.freeze,\n Object.preventExtensions,\n Object.seal,\n])\n\n/** @type {ReadonlyArray]>} */\nconst getterAllowed = [\n [Map, new Set([\"size\"])],\n [\n RegExp,\n new Set([\n \"dotAll\",\n \"flags\",\n \"global\",\n \"hasIndices\",\n \"ignoreCase\",\n \"multiline\",\n \"source\",\n \"sticky\",\n \"unicode\",\n ]),\n ],\n [Set, new Set([\"size\"])],\n]\n\n/**\n * Get the property descriptor.\n * @param {object} object The object to get.\n * @param {string|number|symbol} name The property name to get.\n */\nfunction getPropertyDescriptor(object, name) {\n let x = object\n while ((typeof x === \"object\" || typeof x === \"function\") && x !== null) {\n const d = Object.getOwnPropertyDescriptor(x, name)\n if (d) {\n return d\n }\n x = Object.getPrototypeOf(x)\n }\n return null\n}\n\n/**\n * Check if a property is getter or not.\n * @param {object} object The object to check.\n * @param {string|number|symbol} name The property name to check.\n */\nfunction isGetter(object, name) {\n const d = getPropertyDescriptor(object, name)\n return d != null && d.get != null\n}\n\n/**\n * Get the element values of a given node list.\n * @param {(Node|TSESTreeNode|null)[]} nodeList The node list to get values.\n * @param {Scope|undefined|null} initialScope The initial scope to find variables.\n * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.\n */\nfunction getElementValues(nodeList, initialScope) {\n const valueList = []\n\n for (let i = 0; i < nodeList.length; ++i) {\n const elementNode = nodeList[i]\n\n if (elementNode == null) {\n valueList.length = i + 1\n } else if (elementNode.type === \"SpreadElement\") {\n const argument = getStaticValueR(elementNode.argument, initialScope)\n if (argument == null) {\n return null\n }\n valueList.push(.../** @type {Iterable} */ (argument.value))\n } else {\n const element = getStaticValueR(elementNode, initialScope)\n if (element == null) {\n return null\n }\n valueList.push(element.value)\n }\n }\n\n return valueList\n}\n\n/**\n * Returns whether the given variable is never written to after initialization.\n * @param {import(\"eslint\").Scope.Variable} variable\n * @returns {boolean}\n */\nfunction isEffectivelyConst(variable) {\n const refs = variable.references\n\n const inits = refs.filter((r) => r.init).length\n const reads = refs.filter((r) => r.isReadOnly()).length\n if (inits === 1 && reads + inits === refs.length) {\n // there is only one init and all other references only read\n return true\n }\n return false\n}\n\n/**\n * @template {TSESTreeNodeTypes} T\n * @callback VisitorCallback\n * @param {TSESTreeNode & { type: T }} node\n * @param {Scope|undefined|null} initialScope\n * @returns {StaticValue | null}\n */\n/**\n * @typedef { { [K in TSESTreeNodeTypes]?: VisitorCallback } } Operations\n */\n/**\n * @type {Operations}\n */\nconst operations = Object.freeze({\n ArrayExpression(node, initialScope) {\n const elements = getElementValues(node.elements, initialScope)\n return elements != null ? { value: elements } : null\n },\n\n AssignmentExpression(node, initialScope) {\n if (node.operator === \"=\") {\n return getStaticValueR(node.right, initialScope)\n }\n return null\n },\n\n //eslint-disable-next-line complexity\n BinaryExpression(node, initialScope) {\n if (node.operator === \"in\" || node.operator === \"instanceof\") {\n // Not supported.\n return null\n }\n\n const left = getStaticValueR(node.left, initialScope)\n const right = getStaticValueR(node.right, initialScope)\n if (left != null && right != null) {\n switch (node.operator) {\n case \"==\":\n return { value: left.value == right.value } //eslint-disable-line eqeqeq\n case \"!=\":\n return { value: left.value != right.value } //eslint-disable-line eqeqeq\n case \"===\":\n return { value: left.value === right.value }\n case \"!==\":\n return { value: left.value !== right.value }\n case \"<\":\n return {\n value:\n /** @type {any} */ (left.value) <\n /** @type {any} */ (right.value),\n }\n case \"<=\":\n return {\n value:\n /** @type {any} */ (left.value) <=\n /** @type {any} */ (right.value),\n }\n case \">\":\n return {\n value:\n /** @type {any} */ (left.value) >\n /** @type {any} */ (right.value),\n }\n case \">=\":\n return {\n value:\n /** @type {any} */ (left.value) >=\n /** @type {any} */ (right.value),\n }\n case \"<<\":\n return {\n value:\n /** @type {any} */ (left.value) <<\n /** @type {any} */ (right.value),\n }\n case \">>\":\n return {\n value:\n /** @type {any} */ (left.value) >>\n /** @type {any} */ (right.value),\n }\n case \">>>\":\n return {\n value:\n /** @type {any} */ (left.value) >>>\n /** @type {any} */ (right.value),\n }\n case \"+\":\n return {\n value:\n /** @type {any} */ (left.value) +\n /** @type {any} */ (right.value),\n }\n case \"-\":\n return {\n value:\n /** @type {any} */ (left.value) -\n /** @type {any} */ (right.value),\n }\n case \"*\":\n return {\n value:\n /** @type {any} */ (left.value) *\n /** @type {any} */ (right.value),\n }\n case \"/\":\n return {\n value:\n /** @type {any} */ (left.value) /\n /** @type {any} */ (right.value),\n }\n case \"%\":\n return {\n value:\n /** @type {any} */ (left.value) %\n /** @type {any} */ (right.value),\n }\n case \"**\":\n return {\n value:\n /** @type {any} */ (left.value) **\n /** @type {any} */ (right.value),\n }\n case \"|\":\n return {\n value:\n /** @type {any} */ (left.value) |\n /** @type {any} */ (right.value),\n }\n case \"^\":\n return {\n value:\n /** @type {any} */ (left.value) ^\n /** @type {any} */ (right.value),\n }\n case \"&\":\n return {\n value:\n /** @type {any} */ (left.value) &\n /** @type {any} */ (right.value),\n }\n\n // no default\n }\n }\n\n return null\n },\n\n CallExpression(node, initialScope) {\n const calleeNode = node.callee\n const args = getElementValues(node.arguments, initialScope)\n\n if (args != null) {\n if (calleeNode.type === \"MemberExpression\") {\n if (calleeNode.property.type === \"PrivateIdentifier\") {\n return null\n }\n const object = getStaticValueR(calleeNode.object, initialScope)\n if (object != null) {\n if (\n object.value == null &&\n (object.optional || node.optional)\n ) {\n return { value: undefined, optional: true }\n }\n const property = getStaticPropertyNameValue(\n calleeNode,\n initialScope,\n )\n\n if (property != null) {\n const receiver =\n /** @type {Record any>} */ (\n object.value\n )\n const methodName = /** @type {PropertyKey} */ (\n property.value\n )\n if (callAllowed.has(receiver[methodName])) {\n return {\n value: receiver[methodName](...args),\n }\n }\n if (callPassThrough.has(receiver[methodName])) {\n return { value: args[0] }\n }\n }\n }\n } else {\n const callee = getStaticValueR(calleeNode, initialScope)\n if (callee != null) {\n if (callee.value == null && node.optional) {\n return { value: undefined, optional: true }\n }\n const func = /** @type {(...args: any[]) => any} */ (\n callee.value\n )\n if (callAllowed.has(func)) {\n return { value: func(...args) }\n }\n if (callPassThrough.has(func)) {\n return { value: args[0] }\n }\n }\n }\n }\n\n return null\n },\n\n ConditionalExpression(node, initialScope) {\n const test = getStaticValueR(node.test, initialScope)\n if (test != null) {\n return test.value\n ? getStaticValueR(node.consequent, initialScope)\n : getStaticValueR(node.alternate, initialScope)\n }\n return null\n },\n\n ExpressionStatement(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n\n Identifier(node, initialScope) {\n if (initialScope != null) {\n const variable = findVariable(initialScope, node)\n\n // Built-in globals.\n if (\n variable != null &&\n variable.defs.length === 0 &&\n builtinNames.has(variable.name) &&\n variable.name in globalObject\n ) {\n return { value: globalObject[variable.name] }\n }\n\n // Constants.\n if (variable != null && variable.defs.length === 1) {\n const def = variable.defs[0]\n if (\n def.parent &&\n def.type === \"Variable\" &&\n (def.parent.kind === \"const\" ||\n isEffectivelyConst(variable)) &&\n // TODO(mysticatea): don't support destructuring here.\n def.node.id.type === \"Identifier\"\n ) {\n return getStaticValueR(def.node.init, initialScope)\n }\n }\n }\n return null\n },\n\n Literal(node) {\n const literal =\n /** @type {Partial & Partial & Partial} */ (\n node\n )\n //istanbul ignore if : this is implementation-specific behavior.\n if (\n (literal.regex != null || literal.bigint != null) &&\n literal.value == null\n ) {\n // It was a RegExp/BigInt literal, but Node.js didn't support it.\n return null\n }\n return { value: literal.value }\n },\n\n LogicalExpression(node, initialScope) {\n const left = getStaticValueR(node.left, initialScope)\n if (left != null) {\n if (\n (node.operator === \"||\" && Boolean(left.value) === true) ||\n (node.operator === \"&&\" && Boolean(left.value) === false) ||\n (node.operator === \"??\" && left.value != null)\n ) {\n return left\n }\n\n const right = getStaticValueR(node.right, initialScope)\n if (right != null) {\n return right\n }\n }\n\n return null\n },\n\n MemberExpression(node, initialScope) {\n if (node.property.type === \"PrivateIdentifier\") {\n return null\n }\n const object = getStaticValueR(node.object, initialScope)\n if (object != null) {\n if (object.value == null && (object.optional || node.optional)) {\n return { value: undefined, optional: true }\n }\n const property = getStaticPropertyNameValue(node, initialScope)\n\n if (property != null) {\n if (\n !isGetter(\n /** @type {object} */ (object.value),\n /** @type {PropertyKey} */ (property.value),\n )\n ) {\n return {\n value: /** @type {Record} */ (\n object.value\n )[/** @type {PropertyKey} */ (property.value)],\n }\n }\n\n for (const [classFn, allowed] of getterAllowed) {\n if (\n object.value instanceof classFn &&\n allowed.has(/** @type {string} */ (property.value))\n ) {\n return {\n value: /** @type {Record} */ (\n object.value\n )[/** @type {PropertyKey} */ (property.value)],\n }\n }\n }\n }\n }\n return null\n },\n\n ChainExpression(node, initialScope) {\n const expression = getStaticValueR(node.expression, initialScope)\n if (expression != null) {\n return { value: expression.value }\n }\n return null\n },\n\n NewExpression(node, initialScope) {\n const callee = getStaticValueR(node.callee, initialScope)\n const args = getElementValues(node.arguments, initialScope)\n\n if (callee != null && args != null) {\n const Func = /** @type {new (...args: any[]) => any} */ (\n callee.value\n )\n if (callAllowed.has(Func)) {\n return { value: new Func(...args) }\n }\n }\n\n return null\n },\n\n ObjectExpression(node, initialScope) {\n /** @type {Record} */\n const object = {}\n\n for (const propertyNode of node.properties) {\n if (propertyNode.type === \"Property\") {\n if (propertyNode.kind !== \"init\") {\n return null\n }\n const key = getStaticPropertyNameValue(\n propertyNode,\n initialScope,\n )\n const value = getStaticValueR(propertyNode.value, initialScope)\n if (key == null || value == null) {\n return null\n }\n object[/** @type {PropertyKey} */ (key.value)] = value.value\n } else if (\n propertyNode.type === \"SpreadElement\" ||\n // @ts-expect-error -- Backward compatibility\n propertyNode.type === \"ExperimentalSpreadProperty\"\n ) {\n const argument = getStaticValueR(\n propertyNode.argument,\n initialScope,\n )\n if (argument == null) {\n return null\n }\n Object.assign(object, argument.value)\n } else {\n return null\n }\n }\n\n return { value: object }\n },\n\n SequenceExpression(node, initialScope) {\n const last = node.expressions[node.expressions.length - 1]\n return getStaticValueR(last, initialScope)\n },\n\n TaggedTemplateExpression(node, initialScope) {\n const tag = getStaticValueR(node.tag, initialScope)\n const expressions = getElementValues(\n node.quasi.expressions,\n initialScope,\n )\n\n if (tag != null && expressions != null) {\n const func = /** @type {(...args: any[]) => any} */ (tag.value)\n /** @type {any[] & { raw?: string[] }} */\n const strings = node.quasi.quasis.map((q) => q.value.cooked)\n strings.raw = node.quasi.quasis.map((q) => q.value.raw)\n\n if (func === String.raw) {\n return { value: func(strings, ...expressions) }\n }\n }\n\n return null\n },\n\n TemplateLiteral(node, initialScope) {\n const expressions = getElementValues(node.expressions, initialScope)\n if (expressions != null) {\n let value = node.quasis[0].value.cooked\n for (let i = 0; i < expressions.length; ++i) {\n value += expressions[i]\n value += /** @type {string} */ (node.quasis[i + 1].value.cooked)\n }\n return { value }\n }\n return null\n },\n\n UnaryExpression(node, initialScope) {\n if (node.operator === \"delete\") {\n // Not supported.\n return null\n }\n if (node.operator === \"void\") {\n return { value: undefined }\n }\n\n const arg = getStaticValueR(node.argument, initialScope)\n if (arg != null) {\n switch (node.operator) {\n case \"-\":\n return { value: -(/** @type {any} */ (arg.value)) }\n case \"+\":\n return { value: +(/** @type {any} */ (arg.value)) } //eslint-disable-line no-implicit-coercion\n case \"!\":\n return { value: !arg.value }\n case \"~\":\n return { value: ~(/** @type {any} */ (arg.value)) }\n case \"typeof\":\n return { value: typeof arg.value }\n\n // no default\n }\n }\n\n return null\n },\n TSAsExpression(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n TSSatisfiesExpression(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n TSTypeAssertion(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n TSNonNullExpression(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n TSInstantiationExpression(node, initialScope) {\n return getStaticValueR(node.expression, initialScope)\n },\n})\n\n/**\n * Get the value of a given node if it's a static value.\n * @param {Node|TSESTreeNode|null|undefined} node The node to get.\n * @param {Scope|undefined|null} initialScope The scope to start finding variable.\n * @returns {StaticValue|null} The static value of the node, or `null`.\n */\nfunction getStaticValueR(node, initialScope) {\n if (node != null && Object.hasOwnProperty.call(operations, node.type)) {\n return /** @type {VisitorCallback} */ (operations[node.type])(\n /** @type {TSESTreeNode} */ (node),\n initialScope,\n )\n }\n return null\n}\n\n/**\n * Get the static value of property name from a MemberExpression node or a Property node.\n * @param {MemberExpression|Property} node The node to get.\n * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.\n * @returns {StaticValue|null} The static value of the property name of the node, or `null`.\n */\nfunction getStaticPropertyNameValue(node, initialScope) {\n const nameNode = node.type === \"Property\" ? node.key : node.property\n\n if (node.computed) {\n return getStaticValueR(nameNode, initialScope)\n }\n\n if (nameNode.type === \"Identifier\") {\n return { value: nameNode.name }\n }\n\n if (nameNode.type === \"Literal\") {\n if (/** @type {Partial} */ (nameNode).bigint) {\n return { value: /** @type {BigIntLiteral} */ (nameNode).bigint }\n }\n return { value: String(nameNode.value) }\n }\n\n return null\n}\n\n/**\n * Get the value of a given node if it's a static value.\n * @param {Node} node The node to get.\n * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.\n * @returns {StaticValue | null} The static value of the node, or `null`.\n */\nexport function getStaticValue(node, initialScope = null) {\n try {\n return getStaticValueR(node, initialScope)\n } catch (_error) {\n return null\n }\n}\n","import { getStaticValue } from \"./get-static-value.mjs\"\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"estree\").RegExpLiteral} RegExpLiteral */\n/** @typedef {import(\"estree\").BigIntLiteral} BigIntLiteral */\n/** @typedef {import(\"estree\").SimpleLiteral} SimpleLiteral */\n\n/**\n * Get the value of a given node if it's a literal or a template literal.\n * @param {Node} node The node to get.\n * @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.\n * @returns {string|null} The value of the node, or `null`.\n */\nexport function getStringIfConstant(node, initialScope = null) {\n // Handle the literals that the platform doesn't support natively.\n if (node && node.type === \"Literal\" && node.value === null) {\n const literal =\n /** @type {Partial & Partial & Partial} */ (\n node\n )\n if (literal.regex) {\n return `/${literal.regex.pattern}/${literal.regex.flags}`\n }\n if (literal.bigint) {\n return literal.bigint\n }\n }\n\n const evaluated = getStaticValue(node, initialScope)\n\n if (evaluated) {\n // `String(Symbol.prototype)` throws error\n try {\n return String(evaluated.value)\n } catch {\n // No op\n }\n }\n\n return null\n}\n","import { getStringIfConstant } from \"./get-string-if-constant.mjs\"\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"estree\").MemberExpression} MemberExpression */\n/** @typedef {import(\"estree\").MethodDefinition} MethodDefinition */\n/** @typedef {import(\"estree\").Property} Property */\n/** @typedef {import(\"estree\").PropertyDefinition} PropertyDefinition */\n/** @typedef {import(\"estree\").Identifier} Identifier */\n\n/**\n * Get the property name from a MemberExpression node or a Property node.\n * @param {MemberExpression | MethodDefinition | Property | PropertyDefinition} node The node to get.\n * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.\n * @returns {string|null|undefined} The property name of the node.\n */\nexport function getPropertyName(node, initialScope) {\n switch (node.type) {\n case \"MemberExpression\":\n if (node.computed) {\n return getStringIfConstant(node.property, initialScope)\n }\n if (node.property.type === \"PrivateIdentifier\") {\n return null\n }\n return /** @type {Partial} */ (node.property).name\n\n case \"Property\":\n case \"MethodDefinition\":\n case \"PropertyDefinition\":\n if (node.computed) {\n return getStringIfConstant(node.key, initialScope)\n }\n if (node.key.type === \"Literal\") {\n return String(node.key.value)\n }\n if (node.key.type === \"PrivateIdentifier\") {\n return null\n }\n return /** @type {Partial} */ (node.key).name\n\n default:\n break\n }\n\n return null\n}\n","import { getPropertyName } from \"./get-property-name.mjs\"\n/** @typedef {import(\"eslint\").Rule.Node} RuleNode */\n/** @typedef {import(\"eslint\").SourceCode} SourceCode */\n/** @typedef {import(\"estree\").Function} FunctionNode */\n/** @typedef {import(\"estree\").FunctionDeclaration} FunctionDeclaration */\n/** @typedef {import(\"estree\").FunctionExpression} FunctionExpression */\n/** @typedef {import(\"estree\").Identifier} Identifier */\n\n/**\n * Get the name and kind of the given function node.\n * @param {FunctionNode} node - The function node to get.\n * @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys.\n * @returns {string} The name and kind of the function node.\n */\n// eslint-disable-next-line complexity\nexport function getFunctionNameWithKind(node, sourceCode) {\n const parent = /** @type {RuleNode} */ (node).parent\n const tokens = []\n const isObjectMethod = parent.type === \"Property\" && parent.value === node\n const isClassMethod =\n parent.type === \"MethodDefinition\" && parent.value === node\n const isClassFieldMethod =\n parent.type === \"PropertyDefinition\" && parent.value === node\n\n // Modifiers.\n if (isClassMethod || isClassFieldMethod) {\n if (parent.static) {\n tokens.push(\"static\")\n }\n if (parent.key.type === \"PrivateIdentifier\") {\n tokens.push(\"private\")\n }\n }\n if (node.async) {\n tokens.push(\"async\")\n }\n if (node.generator) {\n tokens.push(\"generator\")\n }\n\n // Kinds.\n if (isObjectMethod || isClassMethod) {\n if (parent.kind === \"constructor\") {\n return \"constructor\"\n }\n if (parent.kind === \"get\") {\n tokens.push(\"getter\")\n } else if (parent.kind === \"set\") {\n tokens.push(\"setter\")\n } else {\n tokens.push(\"method\")\n }\n } else if (isClassFieldMethod) {\n tokens.push(\"method\")\n } else {\n if (node.type === \"ArrowFunctionExpression\") {\n tokens.push(\"arrow\")\n }\n tokens.push(\"function\")\n }\n\n // Names.\n if (isObjectMethod || isClassMethod || isClassFieldMethod) {\n if (parent.key.type === \"PrivateIdentifier\") {\n tokens.push(`#${parent.key.name}`)\n } else {\n const name = getPropertyName(parent)\n if (name) {\n tokens.push(`'${name}'`)\n } else if (sourceCode) {\n const keyText = sourceCode.getText(parent.key)\n if (!keyText.includes(\"\\n\")) {\n tokens.push(`[${keyText}]`)\n }\n }\n }\n } else if (hasId(node)) {\n tokens.push(`'${node.id.name}'`)\n } else if (\n parent.type === \"VariableDeclarator\" &&\n parent.id &&\n parent.id.type === \"Identifier\"\n ) {\n tokens.push(`'${parent.id.name}'`)\n } else if (\n (parent.type === \"AssignmentExpression\" ||\n parent.type === \"AssignmentPattern\") &&\n parent.left &&\n parent.left.type === \"Identifier\"\n ) {\n tokens.push(`'${parent.left.name}'`)\n } else if (\n parent.type === \"ExportDefaultDeclaration\" &&\n parent.declaration === node\n ) {\n tokens.push(\"'default'\")\n }\n\n return tokens.join(\" \")\n}\n\n/**\n * @param {FunctionNode} node\n * @returns {node is FunctionDeclaration | FunctionExpression & { id: Identifier }}\n */\nfunction hasId(node) {\n return Boolean(\n /** @type {Partial} */ (node)\n .id,\n )\n}\n","import { getKeys, KEYS } from \"eslint-visitor-keys\"\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"eslint\").SourceCode} SourceCode */\n/** @typedef {import(\"./types.mjs\").HasSideEffectOptions} HasSideEffectOptions */\n/** @typedef {import(\"estree\").BinaryExpression} BinaryExpression */\n/** @typedef {import(\"estree\").MemberExpression} MemberExpression */\n/** @typedef {import(\"estree\").MethodDefinition} MethodDefinition */\n/** @typedef {import(\"estree\").Property} Property */\n/** @typedef {import(\"estree\").PropertyDefinition} PropertyDefinition */\n/** @typedef {import(\"estree\").UnaryExpression} UnaryExpression */\n\nconst typeConversionBinaryOps = Object.freeze(\n new Set([\n \"==\",\n \"!=\",\n \"<\",\n \"<=\",\n \">\",\n \">=\",\n \"<<\",\n \">>\",\n \">>>\",\n \"+\",\n \"-\",\n \"*\",\n \"/\",\n \"%\",\n \"|\",\n \"^\",\n \"&\",\n \"in\",\n ]),\n)\nconst typeConversionUnaryOps = Object.freeze(new Set([\"-\", \"+\", \"!\", \"~\"]))\n\n/**\n * Check whether the given value is an ASTNode or not.\n * @param {any} x The value to check.\n * @returns {x is Node} `true` if the value is an ASTNode.\n */\nfunction isNode(x) {\n return x !== null && typeof x === \"object\" && typeof x.type === \"string\"\n}\n\nconst visitor = Object.freeze(\n Object.assign(Object.create(null), {\n /**\n * @param {Node} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n $visit(node, options, visitorKeys) {\n const { type } = node\n\n if (typeof (/** @type {any} */ (this)[type]) === \"function\") {\n return /** @type {any} */ (this)[type](\n node,\n options,\n visitorKeys,\n )\n }\n\n return this.$visitChildren(node, options, visitorKeys)\n },\n\n /**\n * @param {Node} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n $visitChildren(node, options, visitorKeys) {\n const { type } = node\n\n for (const key of /** @type {(keyof Node)[]} */ (\n visitorKeys[type] || getKeys(node)\n )) {\n const value = node[key]\n\n if (Array.isArray(value)) {\n for (const element of value) {\n if (\n isNode(element) &&\n this.$visit(element, options, visitorKeys)\n ) {\n return true\n }\n }\n } else if (\n isNode(value) &&\n this.$visit(value, options, visitorKeys)\n ) {\n return true\n }\n }\n\n return false\n },\n\n ArrowFunctionExpression() {\n return false\n },\n AssignmentExpression() {\n return true\n },\n AwaitExpression() {\n return true\n },\n /**\n * @param {BinaryExpression} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n BinaryExpression(node, options, visitorKeys) {\n if (\n options.considerImplicitTypeConversion &&\n typeConversionBinaryOps.has(node.operator) &&\n (node.left.type !== \"Literal\" || node.right.type !== \"Literal\")\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n CallExpression() {\n return true\n },\n FunctionExpression() {\n return false\n },\n ImportExpression() {\n return true\n },\n /**\n * @param {MemberExpression} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n MemberExpression(node, options, visitorKeys) {\n if (options.considerGetters) {\n return true\n }\n if (\n options.considerImplicitTypeConversion &&\n node.computed &&\n node.property.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n /**\n * @param {MethodDefinition} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n MethodDefinition(node, options, visitorKeys) {\n if (\n options.considerImplicitTypeConversion &&\n node.computed &&\n node.key.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n NewExpression() {\n return true\n },\n /**\n * @param {Property} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n Property(node, options, visitorKeys) {\n if (\n options.considerImplicitTypeConversion &&\n node.computed &&\n node.key.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n /**\n * @param {PropertyDefinition} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n PropertyDefinition(node, options, visitorKeys) {\n if (\n options.considerImplicitTypeConversion &&\n node.computed &&\n node.key.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n /**\n * @param {UnaryExpression} node\n * @param {HasSideEffectOptions} options\n * @param {Record} visitorKeys\n */\n UnaryExpression(node, options, visitorKeys) {\n if (node.operator === \"delete\") {\n return true\n }\n if (\n options.considerImplicitTypeConversion &&\n typeConversionUnaryOps.has(node.operator) &&\n node.argument.type !== \"Literal\"\n ) {\n return true\n }\n return this.$visitChildren(node, options, visitorKeys)\n },\n UpdateExpression() {\n return true\n },\n YieldExpression() {\n return true\n },\n }),\n)\n\n/**\n * Check whether a given node has any side effect or not.\n * @param {Node} node The node to get.\n * @param {SourceCode} sourceCode The source code object.\n * @param {HasSideEffectOptions} [options] The option object.\n * @returns {boolean} `true` if the node has a certain side effect.\n */\nexport function hasSideEffect(node, sourceCode, options = {}) {\n const { considerGetters = false, considerImplicitTypeConversion = false } =\n options\n return visitor.$visit(\n node,\n { considerGetters, considerImplicitTypeConversion },\n sourceCode.visitorKeys || KEYS,\n )\n}\n","import { isClosingParenToken, isOpeningParenToken } from \"./token-predicate.mjs\"\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"eslint\").SourceCode} SourceCode */\n/** @typedef {import(\"eslint\").AST.Token} Token */\n/** @typedef {import(\"eslint\").Rule.Node} RuleNode */\n\n/**\n * Get the left parenthesis of the parent node syntax if it exists.\n * E.g., `if (a) {}` then the `(`.\n * @param {Node} node The AST node to check.\n * @param {SourceCode} sourceCode The source code object to get tokens.\n * @returns {Token|null} The left parenthesis of the parent node syntax\n */\nfunction getParentSyntaxParen(node, sourceCode) {\n const parent = /** @type {RuleNode} */ (node).parent\n\n switch (parent.type) {\n case \"CallExpression\":\n case \"NewExpression\":\n if (parent.arguments.length === 1 && parent.arguments[0] === node) {\n return sourceCode.getTokenAfter(\n parent.callee,\n isOpeningParenToken,\n )\n }\n return null\n\n case \"DoWhileStatement\":\n if (parent.test === node) {\n return sourceCode.getTokenAfter(\n parent.body,\n isOpeningParenToken,\n )\n }\n return null\n\n case \"IfStatement\":\n case \"WhileStatement\":\n if (parent.test === node) {\n return sourceCode.getFirstToken(parent, 1)\n }\n return null\n\n case \"ImportExpression\":\n if (parent.source === node) {\n return sourceCode.getFirstToken(parent, 1)\n }\n return null\n\n case \"SwitchStatement\":\n if (parent.discriminant === node) {\n return sourceCode.getFirstToken(parent, 1)\n }\n return null\n\n case \"WithStatement\":\n if (parent.object === node) {\n return sourceCode.getFirstToken(parent, 1)\n }\n return null\n\n default:\n return null\n }\n}\n\n/**\n * Check whether a given node is parenthesized or not.\n * @param {number} times The number of parantheses.\n * @param {Node} node The AST node to check.\n * @param {SourceCode} sourceCode The source code object to get tokens.\n * @returns {boolean} `true` if the node is parenthesized the given times.\n */\n/**\n * Check whether a given node is parenthesized or not.\n * @param {Node} node The AST node to check.\n * @param {SourceCode} sourceCode The source code object to get tokens.\n * @returns {boolean} `true` if the node is parenthesized.\n */\n/**\n * Check whether a given node is parenthesized or not.\n * @param {Node|number} timesOrNode The first parameter.\n * @param {Node|SourceCode} nodeOrSourceCode The second parameter.\n * @param {SourceCode} [optionalSourceCode] The third parameter.\n * @returns {boolean} `true` if the node is parenthesized.\n */\nexport function isParenthesized(\n timesOrNode,\n nodeOrSourceCode,\n optionalSourceCode,\n) {\n /** @type {number} */\n let times,\n /** @type {RuleNode} */\n node,\n /** @type {SourceCode} */\n sourceCode,\n maybeLeftParen,\n maybeRightParen\n if (typeof timesOrNode === \"number\") {\n times = timesOrNode | 0\n node = /** @type {RuleNode} */ (nodeOrSourceCode)\n sourceCode = /** @type {SourceCode} */ (optionalSourceCode)\n if (!(times >= 1)) {\n throw new TypeError(\"'times' should be a positive integer.\")\n }\n } else {\n times = 1\n node = /** @type {RuleNode} */ (timesOrNode)\n sourceCode = /** @type {SourceCode} */ (nodeOrSourceCode)\n }\n\n if (\n node == null ||\n // `Program` can't be parenthesized\n node.parent == null ||\n // `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}`\n (node.parent.type === \"CatchClause\" && node.parent.param === node)\n ) {\n return false\n }\n\n maybeLeftParen = maybeRightParen = node\n do {\n maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen)\n maybeRightParen = sourceCode.getTokenAfter(maybeRightParen)\n } while (\n maybeLeftParen != null &&\n maybeRightParen != null &&\n isOpeningParenToken(maybeLeftParen) &&\n isClosingParenToken(maybeRightParen) &&\n // Avoid false positive such as `if (a) {}`\n maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&\n --times > 0\n )\n\n return times === 0\n}\n","/**\n * @author Toru Nagashima \n * See LICENSE file in root directory for full license.\n */\n\nconst placeholder = /\\$(?:[$&`']|[1-9][0-9]?)/gu\n\n/** @type {WeakMap} */\nconst internal = new WeakMap()\n\n/**\n * Check whether a given character is escaped or not.\n * @param {string} str The string to check.\n * @param {number} index The location of the character to check.\n * @returns {boolean} `true` if the character is escaped.\n */\nfunction isEscaped(str, index) {\n let escaped = false\n for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {\n escaped = !escaped\n }\n return escaped\n}\n\n/**\n * Replace a given string by a given matcher.\n * @param {PatternMatcher} matcher The pattern matcher.\n * @param {string} str The string to be replaced.\n * @param {string} replacement The new substring to replace each matched part.\n * @returns {string} The replaced string.\n */\nfunction replaceS(matcher, str, replacement) {\n const chunks = []\n let index = 0\n\n /**\n * @param {string} key The placeholder.\n * @param {RegExpExecArray} match The matched information.\n * @returns {string} The replaced string.\n */\n function replacer(key, match) {\n switch (key) {\n case \"$$\":\n return \"$\"\n case \"$&\":\n return match[0]\n case \"$`\":\n return str.slice(0, match.index)\n case \"$'\":\n return str.slice(match.index + match[0].length)\n default: {\n const i = key.slice(1)\n if (i in match) {\n return match[/** @type {any} */ (i)]\n }\n return key\n }\n }\n }\n\n for (const match of matcher.execAll(str)) {\n chunks.push(str.slice(index, match.index))\n chunks.push(\n replacement.replace(placeholder, (key) => replacer(key, match)),\n )\n index = match.index + match[0].length\n }\n chunks.push(str.slice(index))\n\n return chunks.join(\"\")\n}\n\n/**\n * Replace a given string by a given matcher.\n * @param {PatternMatcher} matcher The pattern matcher.\n * @param {string} str The string to be replaced.\n * @param {(substring: string, ...args: any[]) => string} replace The function to replace each matched part.\n * @returns {string} The replaced string.\n */\nfunction replaceF(matcher, str, replace) {\n const chunks = []\n let index = 0\n\n for (const match of matcher.execAll(str)) {\n chunks.push(str.slice(index, match.index))\n chunks.push(\n String(\n replace(\n .../** @type {[string, ...string[]]} */ (\n /** @type {string[]} */ (match)\n ),\n match.index,\n match.input,\n ),\n ),\n )\n index = match.index + match[0].length\n }\n chunks.push(str.slice(index))\n\n return chunks.join(\"\")\n}\n\n/**\n * The class to find patterns as considering escape sequences.\n */\nexport class PatternMatcher {\n /**\n * Initialize this matcher.\n * @param {RegExp} pattern The pattern to match.\n * @param {{escaped?:boolean}} [options] The options.\n */\n constructor(pattern, options = {}) {\n const { escaped = false } = options\n if (!(pattern instanceof RegExp)) {\n throw new TypeError(\"'pattern' should be a RegExp instance.\")\n }\n if (!pattern.flags.includes(\"g\")) {\n throw new Error(\"'pattern' should contains 'g' flag.\")\n }\n\n internal.set(this, {\n pattern: new RegExp(pattern.source, pattern.flags),\n escaped: Boolean(escaped),\n })\n }\n\n /**\n * Find the pattern in a given string.\n * @param {string} str The string to find.\n * @returns {IterableIterator} The iterator which iterate the matched information.\n */\n *execAll(str) {\n const { pattern, escaped } =\n /** @type {{pattern:RegExp,escaped:boolean}} */ (internal.get(this))\n let match = null\n let lastIndex = 0\n\n pattern.lastIndex = 0\n while ((match = pattern.exec(str)) != null) {\n if (escaped || !isEscaped(str, match.index)) {\n lastIndex = pattern.lastIndex\n yield match\n pattern.lastIndex = lastIndex\n }\n }\n }\n\n /**\n * Check whether the pattern is found in a given string.\n * @param {string} str The string to check.\n * @returns {boolean} `true` if the pattern was found in the string.\n */\n test(str) {\n const it = this.execAll(str)\n const ret = it.next()\n return !ret.done\n }\n\n /**\n * Replace a given string.\n * @param {string} str The string to be replaced.\n * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.\n * @returns {string} The replaced string.\n */\n [Symbol.replace](str, replacer) {\n return typeof replacer === \"function\"\n ? replaceF(this, String(str), replacer)\n : replaceS(this, String(str), String(replacer))\n }\n}\n","import { findVariable } from \"./find-variable.mjs\"\nimport { getPropertyName } from \"./get-property-name.mjs\"\nimport { getStringIfConstant } from \"./get-string-if-constant.mjs\"\n/** @typedef {import(\"eslint\").Scope.Scope} Scope */\n/** @typedef {import(\"eslint\").Scope.Variable} Variable */\n/** @typedef {import(\"eslint\").Rule.Node} RuleNode */\n/** @typedef {import(\"estree\").Node} Node */\n/** @typedef {import(\"estree\").Expression} Expression */\n/** @typedef {import(\"estree\").Pattern} Pattern */\n/** @typedef {import(\"estree\").Identifier} Identifier */\n/** @typedef {import(\"estree\").SimpleCallExpression} CallExpression */\n/** @typedef {import(\"estree\").Program} Program */\n/** @typedef {import(\"estree\").ImportDeclaration} ImportDeclaration */\n/** @typedef {import(\"estree\").ExportAllDeclaration} ExportAllDeclaration */\n/** @typedef {import(\"estree\").ExportDefaultDeclaration} ExportDefaultDeclaration */\n/** @typedef {import(\"estree\").ExportNamedDeclaration} ExportNamedDeclaration */\n/** @typedef {import(\"estree\").ImportSpecifier} ImportSpecifier */\n/** @typedef {import(\"estree\").ImportDefaultSpecifier} ImportDefaultSpecifier */\n/** @typedef {import(\"estree\").ImportNamespaceSpecifier} ImportNamespaceSpecifier */\n/** @typedef {import(\"estree\").ExportSpecifier} ExportSpecifier */\n/** @typedef {import(\"estree\").Property} Property */\n/** @typedef {import(\"estree\").AssignmentProperty} AssignmentProperty */\n/** @typedef {import(\"estree\").Literal} Literal */\n/** @typedef {import(\"@typescript-eslint/types\").TSESTree.Node} TSESTreeNode */\n/** @typedef {import(\"./types.mjs\").ReferenceTrackerOptions} ReferenceTrackerOptions */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TraceMap} TraceMap\n */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TraceMapObject} TraceMapObject\n */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TrackedReferences} TrackedReferences\n */\n\nconst IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u\n\n/**\n * Check whether a given node is an import node or not.\n * @param {Node} node\n * @returns {node is ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration&{source: Literal}} `true` if the node is an import node.\n */\nfunction isHasSource(node) {\n return (\n IMPORT_TYPE.test(node.type) &&\n /** @type {ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration} */ (\n node\n ).source != null\n )\n}\nconst has =\n /** @type {(traceMap: TraceMap, v: T) => v is (string extends T ? string : T)} */ (\n Function.call.bind(Object.hasOwnProperty)\n )\n\nexport const READ = Symbol(\"read\")\nexport const CALL = Symbol(\"call\")\nexport const CONSTRUCT = Symbol(\"construct\")\nexport const ESM = Symbol(\"esm\")\n\nconst requireCall = { require: { [CALL]: true } }\n\n/**\n * Check whether a given variable is modified or not.\n * @param {Variable|undefined} variable The variable to check.\n * @returns {boolean} `true` if the variable is modified.\n */\nfunction isModifiedGlobal(variable) {\n return (\n variable == null ||\n variable.defs.length !== 0 ||\n variable.references.some((r) => r.isWrite())\n )\n}\n\n/**\n * Check if the value of a given node is passed through to the parent syntax as-is.\n * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.\n * @param {Node} node A node to check.\n * @returns {node is RuleNode & {parent: Expression}} `true` if the node is passed through.\n */\nfunction isPassThrough(node) {\n const parent = /** @type {TSESTreeNode} */ (node).parent\n\n if (parent) {\n switch (parent.type) {\n case \"ConditionalExpression\":\n return parent.consequent === node || parent.alternate === node\n case \"LogicalExpression\":\n return true\n case \"SequenceExpression\":\n return (\n parent.expressions[parent.expressions.length - 1] === node\n )\n case \"ChainExpression\":\n return true\n case \"TSAsExpression\":\n case \"TSSatisfiesExpression\":\n case \"TSTypeAssertion\":\n case \"TSNonNullExpression\":\n case \"TSInstantiationExpression\":\n return true\n\n default:\n return false\n }\n }\n return false\n}\n\n/**\n * The reference tracker.\n */\nexport class ReferenceTracker {\n /**\n * Initialize this tracker.\n * @param {Scope} globalScope The global scope.\n * @param {object} [options] The options.\n * @param {\"legacy\"|\"strict\"} [options.mode=\"strict\"] The mode to determine the ImportDeclaration's behavior for CJS modules.\n * @param {string[]} [options.globalObjectNames=[\"global\",\"globalThis\",\"self\",\"window\"]] The variable names for Global Object.\n */\n constructor(globalScope, options = {}) {\n const {\n mode = \"strict\",\n globalObjectNames = [\"global\", \"globalThis\", \"self\", \"window\"],\n } = options\n /** @private @type {Variable[]} */\n this.variableStack = []\n /** @private */\n this.globalScope = globalScope\n /** @private */\n this.mode = mode\n /** @private */\n this.globalObjectNames = globalObjectNames.slice(0)\n }\n\n /**\n * Iterate the references of global variables.\n * @template T\n * @param {TraceMap} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *iterateGlobalReferences(traceMap) {\n for (const key of Object.keys(traceMap)) {\n const nextTraceMap = traceMap[key]\n const path = [key]\n const variable = this.globalScope.set.get(key)\n\n if (isModifiedGlobal(variable)) {\n continue\n }\n\n yield* this._iterateVariableReferences(\n /** @type {Variable} */ (variable),\n path,\n nextTraceMap,\n true,\n )\n }\n\n for (const key of this.globalObjectNames) {\n /** @type {string[]} */\n const path = []\n const variable = this.globalScope.set.get(key)\n\n if (isModifiedGlobal(variable)) {\n continue\n }\n\n yield* this._iterateVariableReferences(\n /** @type {Variable} */ (variable),\n path,\n traceMap,\n false,\n )\n }\n }\n\n /**\n * Iterate the references of CommonJS modules.\n * @template T\n * @param {TraceMap} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *iterateCjsReferences(traceMap) {\n for (const { node } of this.iterateGlobalReferences(requireCall)) {\n const key = getStringIfConstant(\n /** @type {CallExpression} */ (node).arguments[0],\n )\n if (key == null || !has(traceMap, key)) {\n continue\n }\n\n const nextTraceMap = traceMap[key]\n const path = [key]\n\n if (nextTraceMap[READ]) {\n yield {\n node,\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n yield* this._iteratePropertyReferences(\n /** @type {CallExpression} */ (node),\n path,\n nextTraceMap,\n )\n }\n }\n\n /**\n * Iterate the references of ES modules.\n * @template T\n * @param {TraceMap} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *iterateEsmReferences(traceMap) {\n const programNode = /** @type {Program} */ (this.globalScope.block)\n\n for (const node of programNode.body) {\n if (!isHasSource(node)) {\n continue\n }\n const moduleId = /** @type {string} */ (node.source.value)\n\n if (!has(traceMap, moduleId)) {\n continue\n }\n const nextTraceMap = traceMap[moduleId]\n const path = [moduleId]\n\n if (nextTraceMap[READ]) {\n yield {\n // eslint-disable-next-line object-shorthand -- apply type\n node: /** @type {RuleNode} */ (node),\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n\n if (node.type === \"ExportAllDeclaration\") {\n for (const key of Object.keys(nextTraceMap)) {\n const exportTraceMap = nextTraceMap[key]\n if (exportTraceMap[READ]) {\n yield {\n // eslint-disable-next-line object-shorthand -- apply type\n node: /** @type {RuleNode} */ (node),\n path: path.concat(key),\n type: READ,\n info: exportTraceMap[READ],\n }\n }\n }\n } else {\n for (const specifier of node.specifiers) {\n const esm = has(nextTraceMap, ESM)\n const it = this._iterateImportReferences(\n specifier,\n path,\n esm\n ? nextTraceMap\n : this.mode === \"legacy\"\n ? { default: nextTraceMap, ...nextTraceMap }\n : { default: nextTraceMap },\n )\n\n if (esm) {\n yield* it\n } else {\n for (const report of it) {\n report.path = report.path.filter(exceptDefault)\n if (\n report.path.length >= 2 ||\n report.type !== READ\n ) {\n yield report\n }\n }\n }\n }\n }\n }\n }\n\n /**\n * Iterate the property references for a given expression AST node.\n * @template T\n * @param {Expression} node The expression AST node to iterate property references.\n * @param {TraceMap} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate property references.\n */\n *iteratePropertyReferences(node, traceMap) {\n yield* this._iteratePropertyReferences(node, [], traceMap)\n }\n\n /**\n * Iterate the references for a given variable.\n * @private\n * @template T\n * @param {Variable} variable The variable to iterate that references.\n * @param {string[]} path The current path.\n * @param {TraceMapObject} traceMap The trace map.\n * @param {boolean} shouldReport = The flag to report those references.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *_iterateVariableReferences(variable, path, traceMap, shouldReport) {\n if (this.variableStack.includes(variable)) {\n return\n }\n this.variableStack.push(variable)\n try {\n for (const reference of variable.references) {\n if (!reference.isRead()) {\n continue\n }\n const node = /** @type {RuleNode & Identifier} */ (\n reference.identifier\n )\n\n if (shouldReport && traceMap[READ]) {\n yield { node, path, type: READ, info: traceMap[READ] }\n }\n yield* this._iteratePropertyReferences(node, path, traceMap)\n }\n } finally {\n this.variableStack.pop()\n }\n }\n\n /**\n * Iterate the references for a given AST node.\n * @private\n * @template T\n * @param {Expression} rootNode The AST node to iterate references.\n * @param {string[]} path The current path.\n * @param {TraceMapObject} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n //eslint-disable-next-line complexity\n *_iteratePropertyReferences(rootNode, path, traceMap) {\n let node = rootNode\n while (isPassThrough(node)) {\n node = node.parent\n }\n\n const parent = /** @type {RuleNode} */ (node).parent\n if (parent.type === \"MemberExpression\") {\n if (parent.object === node) {\n const key = getPropertyName(parent)\n if (key == null || !has(traceMap, key)) {\n return\n }\n\n path = path.concat(key) //eslint-disable-line no-param-reassign\n const nextTraceMap = traceMap[key]\n if (nextTraceMap[READ]) {\n yield {\n node: parent,\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n yield* this._iteratePropertyReferences(\n parent,\n path,\n nextTraceMap,\n )\n }\n return\n }\n if (parent.type === \"CallExpression\") {\n if (parent.callee === node && traceMap[CALL]) {\n yield { node: parent, path, type: CALL, info: traceMap[CALL] }\n }\n return\n }\n if (parent.type === \"NewExpression\") {\n if (parent.callee === node && traceMap[CONSTRUCT]) {\n yield {\n node: parent,\n path,\n type: CONSTRUCT,\n info: traceMap[CONSTRUCT],\n }\n }\n return\n }\n if (parent.type === \"AssignmentExpression\") {\n if (parent.right === node) {\n yield* this._iterateLhsReferences(parent.left, path, traceMap)\n yield* this._iteratePropertyReferences(parent, path, traceMap)\n }\n return\n }\n if (parent.type === \"AssignmentPattern\") {\n if (parent.right === node) {\n yield* this._iterateLhsReferences(parent.left, path, traceMap)\n }\n return\n }\n if (parent.type === \"VariableDeclarator\") {\n if (parent.init === node) {\n yield* this._iterateLhsReferences(parent.id, path, traceMap)\n }\n }\n }\n\n /**\n * Iterate the references for a given Pattern node.\n * @private\n * @template T\n * @param {Pattern} patternNode The Pattern node to iterate references.\n * @param {string[]} path The current path.\n * @param {TraceMapObject} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *_iterateLhsReferences(patternNode, path, traceMap) {\n if (patternNode.type === \"Identifier\") {\n const variable = findVariable(this.globalScope, patternNode)\n if (variable != null) {\n yield* this._iterateVariableReferences(\n variable,\n path,\n traceMap,\n false,\n )\n }\n return\n }\n if (patternNode.type === \"ObjectPattern\") {\n for (const property of patternNode.properties) {\n const key = getPropertyName(\n /** @type {AssignmentProperty} */ (property),\n )\n\n if (key == null || !has(traceMap, key)) {\n continue\n }\n\n const nextPath = path.concat(key)\n const nextTraceMap = traceMap[key]\n if (nextTraceMap[READ]) {\n yield {\n node: /** @type {RuleNode} */ (property),\n path: nextPath,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n yield* this._iterateLhsReferences(\n /** @type {AssignmentProperty} */ (property).value,\n nextPath,\n nextTraceMap,\n )\n }\n return\n }\n if (patternNode.type === \"AssignmentPattern\") {\n yield* this._iterateLhsReferences(patternNode.left, path, traceMap)\n }\n }\n\n /**\n * Iterate the references for a given ModuleSpecifier node.\n * @private\n * @template T\n * @param {ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier} specifierNode The ModuleSpecifier node to iterate references.\n * @param {string[]} path The current path.\n * @param {TraceMapObject} traceMap The trace map.\n * @returns {IterableIterator>} The iterator to iterate references.\n */\n *_iterateImportReferences(specifierNode, path, traceMap) {\n const type = specifierNode.type\n\n if (type === \"ImportSpecifier\" || type === \"ImportDefaultSpecifier\") {\n const key =\n type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifierNode.imported.type === \"Identifier\"\n ? specifierNode.imported.name\n : specifierNode.imported.value\n if (!has(traceMap, key)) {\n return\n }\n\n path = path.concat(key) //eslint-disable-line no-param-reassign\n const nextTraceMap = traceMap[key]\n if (nextTraceMap[READ]) {\n yield {\n node: /** @type {RuleNode} */ (specifierNode),\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n yield* this._iterateVariableReferences(\n /** @type {Variable} */ (\n findVariable(this.globalScope, specifierNode.local)\n ),\n path,\n nextTraceMap,\n false,\n )\n\n return\n }\n\n if (type === \"ImportNamespaceSpecifier\") {\n yield* this._iterateVariableReferences(\n /** @type {Variable} */ (\n findVariable(this.globalScope, specifierNode.local)\n ),\n path,\n traceMap,\n false,\n )\n return\n }\n\n if (type === \"ExportSpecifier\") {\n const key =\n specifierNode.local.type === \"Identifier\"\n ? specifierNode.local.name\n : specifierNode.local.value\n if (!has(traceMap, key)) {\n return\n }\n\n path = path.concat(key) //eslint-disable-line no-param-reassign\n const nextTraceMap = traceMap[key]\n if (nextTraceMap[READ]) {\n yield {\n node: /** @type {RuleNode} */ (specifierNode),\n path,\n type: READ,\n info: nextTraceMap[READ],\n }\n }\n }\n }\n}\n\nReferenceTracker.READ = READ\nReferenceTracker.CALL = CALL\nReferenceTracker.CONSTRUCT = CONSTRUCT\nReferenceTracker.ESM = ESM\n\n/**\n * This is a predicate function for Array#filter.\n * @param {string} name A name part.\n * @param {number} index The index of the name.\n * @returns {boolean} `false` if it's default.\n */\nfunction exceptDefault(name, index) {\n return !(index === 1 && name === \"default\")\n}\n","/** @typedef {import(\"./types.mjs\").StaticValue} StaticValue */\n/** @typedef {import(\"./types.mjs\").StaticValueOptional} StaticValueOptional */\n/** @typedef {import(\"./types.mjs\").StaticValueProvided} StaticValueProvided */\n/** @typedef {import(\"./types.mjs\").ReferenceTrackerOptions} ReferenceTrackerOptions */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TraceMap} TraceMap\n */\n/**\n * @template T\n * @typedef {import(\"./types.mjs\").TrackedReferences} TrackedReferences\n */\n/** @typedef {import(\"./types.mjs\").HasSideEffectOptions} HasSideEffectOptions */\n/** @typedef {import(\"./types.mjs\").ArrowToken} ArrowToken */\n/** @typedef {import(\"./types.mjs\").CommaToken} CommaToken */\n/** @typedef {import(\"./types.mjs\").SemicolonToken} SemicolonToken */\n/** @typedef {import(\"./types.mjs\").ColonToken} ColonToken */\n/** @typedef {import(\"./types.mjs\").OpeningParenToken} OpeningParenToken */\n/** @typedef {import(\"./types.mjs\").ClosingParenToken} ClosingParenToken */\n/** @typedef {import(\"./types.mjs\").OpeningBracketToken} OpeningBracketToken */\n/** @typedef {import(\"./types.mjs\").ClosingBracketToken} ClosingBracketToken */\n/** @typedef {import(\"./types.mjs\").OpeningBraceToken} OpeningBraceToken */\n/** @typedef {import(\"./types.mjs\").ClosingBraceToken} ClosingBraceToken */\n\nimport { findVariable } from \"./find-variable.mjs\"\nimport { getFunctionHeadLocation } from \"./get-function-head-location.mjs\"\nimport { getFunctionNameWithKind } from \"./get-function-name-with-kind.mjs\"\nimport { getInnermostScope } from \"./get-innermost-scope.mjs\"\nimport { getPropertyName } from \"./get-property-name.mjs\"\nimport { getStaticValue } from \"./get-static-value.mjs\"\nimport { getStringIfConstant } from \"./get-string-if-constant.mjs\"\nimport { hasSideEffect } from \"./has-side-effect.mjs\"\nimport { isParenthesized } from \"./is-parenthesized.mjs\"\nimport { PatternMatcher } from \"./pattern-matcher.mjs\"\nimport {\n CALL,\n CONSTRUCT,\n ESM,\n READ,\n ReferenceTracker,\n} from \"./reference-tracker.mjs\"\nimport {\n isArrowToken,\n isClosingBraceToken,\n isClosingBracketToken,\n isClosingParenToken,\n isColonToken,\n isCommaToken,\n isCommentToken,\n isNotArrowToken,\n isNotClosingBraceToken,\n isNotClosingBracketToken,\n isNotClosingParenToken,\n isNotColonToken,\n isNotCommaToken,\n isNotCommentToken,\n isNotOpeningBraceToken,\n isNotOpeningBracketToken,\n isNotOpeningParenToken,\n isNotSemicolonToken,\n isOpeningBraceToken,\n isOpeningBracketToken,\n isOpeningParenToken,\n isSemicolonToken,\n} from \"./token-predicate.mjs\"\n\nexport default {\n CALL,\n CONSTRUCT,\n ESM,\n findVariable,\n getFunctionHeadLocation,\n getFunctionNameWithKind,\n getInnermostScope,\n getPropertyName,\n getStaticValue,\n getStringIfConstant,\n hasSideEffect,\n isArrowToken,\n isClosingBraceToken,\n isClosingBracketToken,\n isClosingParenToken,\n isColonToken,\n isCommaToken,\n isCommentToken,\n isNotArrowToken,\n isNotClosingBraceToken,\n isNotClosingBracketToken,\n isNotClosingParenToken,\n isNotColonToken,\n isNotCommaToken,\n isNotCommentToken,\n isNotOpeningBraceToken,\n isNotOpeningBracketToken,\n isNotOpeningParenToken,\n isNotSemicolonToken,\n isOpeningBraceToken,\n isOpeningBracketToken,\n isOpeningParenToken,\n isParenthesized,\n isSemicolonToken,\n PatternMatcher,\n READ,\n ReferenceTracker,\n}\nexport {\n CALL,\n CONSTRUCT,\n ESM,\n findVariable,\n getFunctionHeadLocation,\n getFunctionNameWithKind,\n getInnermostScope,\n getPropertyName,\n getStaticValue,\n getStringIfConstant,\n hasSideEffect,\n isArrowToken,\n isClosingBraceToken,\n isClosingBracketToken,\n isClosingParenToken,\n isColonToken,\n isCommaToken,\n isCommentToken,\n isNotArrowToken,\n isNotClosingBraceToken,\n isNotClosingBracketToken,\n isNotClosingParenToken,\n isNotColonToken,\n isNotCommaToken,\n isNotCommentToken,\n isNotOpeningBraceToken,\n isNotOpeningBracketToken,\n isNotOpeningParenToken,\n isNotSemicolonToken,\n isOpeningBraceToken,\n isOpeningBracketToken,\n isOpeningParenToken,\n is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,CAAC,IAAI,CAAC;AAC5C,kBAAiB;AACjB,aAAa;AACb,SAAS;AACT,KAAK;AACL,CAAC;AACD;AACA,gBAAgB,CAAC,IAAI,GAAG,KAAI;AAC5B,gBAAgB,CAAC,IAAI,GAAG,KAAI;AAC5B,gBAAgB,CAAC,SAAS,GAAG,UAAS;AACtC,gBAAgB,CAAC,GAAG,GAAG,IAAG;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,IAAI,EAAE,KAAK,EAAE;AACpC,IAAI,OAAO,EAAE,KAAK,KAAK,CAAC,IAAI,IAAI,KAAK,SAAS,CAAC;AAC/C;;ACljBA;AAiEA;AACA,YAAe;AACf,IAAI,IAAI;AACR,IAAI,SAAS;AACb,IAAI,GAAG;AACP,IAAI,YAAY;AAChB,IAAI,uBAAuB;AAC3B,IAAI,uBAAuB;AAC3B,IAAI,iBAAiB;AACrB,IAAI,eAAe;AACnB,IAAI,cAAc;AAClB,IAAI,mBAAmB;AACvB,IAAI,aAAa;AACjB,IAAI,YAAY;AAChB,IAAI,mBAAmB;AACvB,IAAI,qBAAqB;AACzB,IAAI,mBAAmB;AACvB,IAAI,YAAY;AAChB,IAAI,YAAY;AAChB,IAAI,cAAc;AAClB,IAAI,eAAe;AACnB,IAAI,sBAAsB;AAC1B,IAAI,wBAAwB;AAC5B,IAAI,sBAAsB;AAC1B,IAAI,eAAe;AACnB,IAAI,eAAe;AACnB,IAAI,iBAAiB;AACrB,IAAI,sBAAsB;AAC1B,IAAI,wBAAwB;AAC5B,IAAI,sBAAsB;AAC1B,IAAI,mBAAmB;AACvB,IAAI,mBAAmB;AACvB,IAAI,qBAAqB;AACzB,IAAI,mBAAmB;AACvB,IAAI,eAAe;AACnB,IAAI,gBAAgB;AACpB,IAAI,cAAc;AAClB,IAAI,IAAI;AACR,IAAI,gBAAgB;AACpB;;;;"} \ No newline at end of file diff --git a/node_modules/@eslint-community/eslint-utils/package.json b/node_modules/@eslint-community/eslint-utils/package.json new file mode 100644 index 00000000..0f876bf1 --- /dev/null +++ b/node_modules/@eslint-community/eslint-utils/package.json @@ -0,0 +1,89 @@ +{ + "name": "@eslint-community/eslint-utils", + "version": "4.7.0", + "description": "Utilities for ESLint plugins.", + "keywords": [ + "eslint" + ], + "homepage": "https://github.com/eslint-community/eslint-utils#readme", + "bugs": { + "url": "https://github.com/eslint-community/eslint-utils/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint-community/eslint-utils" + }, + "license": "MIT", + "author": "Toru Nagashima", + "sideEffects": false, + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "main": "index", + "module": "index.mjs", + "files": [ + "index.*" + ], + "scripts": { + "prebuild": "npm run -s clean", + "build": "npm run build:dts && npm run build:rollup", + "build:dts": "tsc -p tsconfig.build.json", + "build:rollup": "rollup -c", + "clean": "rimraf .nyc_output coverage index.* dist", + "coverage": "opener ./coverage/lcov-report/index.html", + "docs:build": "vitepress build docs", + "docs:watch": "vitepress dev docs", + "format": "npm run -s format:prettier -- --write", + "format:prettier": "prettier .", + "format:check": "npm run -s format:prettier -- --check", + "lint:eslint": "eslint .", + "lint:format": "npm run -s format:check", + "lint:installed-check": "installed-check -v -i installed-check -i npm-run-all2 -i knip -i rollup-plugin-dts", + "lint:knip": "knip", + "lint": "run-p lint:*", + "test-coverage": "c8 mocha --reporter dot \"test/*.mjs\"", + "test": "mocha --reporter dot \"test/*.mjs\"", + "preversion": "npm run test-coverage && npm run -s build", + "postversion": "git push && git push --tags", + "prewatch": "npm run -s clean", + "watch": "warun \"{src,test}/**/*.mjs\" -- npm run -s test:mocha" + }, + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "devDependencies": { + "@eslint-community/eslint-plugin-mysticatea": "^15.6.1", + "@types/eslint": "^9.6.1", + "@types/estree": "^1.0.7", + "@typescript-eslint/parser": "^5.62.0", + "@typescript-eslint/types": "^5.62.0", + "c8": "^8.0.1", + "dot-prop": "^7.2.0", + "eslint": "^8.57.1", + "installed-check": "^8.0.1", + "knip": "^5.33.3", + "mocha": "^9.2.2", + "npm-run-all2": "^6.2.3", + "opener": "^1.5.2", + "prettier": "2.8.8", + "rimraf": "^3.0.2", + "rollup": "^2.79.2", + "rollup-plugin-dts": "^4.2.3", + "rollup-plugin-sourcemaps": "^0.6.3", + "semver": "^7.6.3", + "typescript": "^4.9.5", + "vitepress": "^1.4.1", + "warun": "^1.0.0" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": "https://opencollective.com/eslint" +} diff --git a/node_modules/@eslint-community/regexpp/LICENSE b/node_modules/@eslint-community/regexpp/LICENSE new file mode 100644 index 00000000..883ee1f6 --- /dev/null +++ b/node_modules/@eslint-community/regexpp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Toru Nagashima + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@eslint-community/regexpp/README.md b/node_modules/@eslint-community/regexpp/README.md new file mode 100644 index 00000000..9728af51 --- /dev/null +++ b/node_modules/@eslint-community/regexpp/README.md @@ -0,0 +1,177 @@ +# @eslint-community/regexpp + +[![npm version](https://img.shields.io/npm/v/@eslint-community/regexpp.svg)](https://www.npmjs.com/package/@eslint-community/regexpp) +[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/regexpp.svg)](http://www.npmtrends.com/@eslint-community/regexpp) +[![Build Status](https://github.com/eslint-community/regexpp/workflows/CI/badge.svg)](https://github.com/eslint-community/regexpp/actions) +[![codecov](https://codecov.io/gh/eslint-community/regexpp/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/regexpp) + +A regular expression parser for ECMAScript. + +## 💿 Installation + +```bash +$ npm install @eslint-community/regexpp +``` + +- require Node@^12.0.0 || ^14.0.0 || >=16.0.0. + +## 📖 Usage + +```ts +import { + AST, + RegExpParser, + RegExpValidator, + RegExpVisitor, + parseRegExpLiteral, + validateRegExpLiteral, + visitRegExpAST +} from "@eslint-community/regexpp" +``` + +### parseRegExpLiteral(source, options?) + +Parse a given regular expression literal then make AST object. + +This is equivalent to `new RegExpParser(options).parseLiteral(source)`. + +- **Parameters:** + - `source` (`string | RegExp`) The source code to parse. + - `options?` ([`RegExpParser.Options`]) The options to parse. +- **Return:** + - The AST of the regular expression. + +### validateRegExpLiteral(source, options?) + +Validate a given regular expression literal. + +This is equivalent to `new RegExpValidator(options).validateLiteral(source)`. + +- **Parameters:** + - `source` (`string`) The source code to validate. + - `options?` ([`RegExpValidator.Options`]) The options to validate. + +### visitRegExpAST(ast, handlers) + +Visit each node of a given AST. + +This is equivalent to `new RegExpVisitor(handlers).visit(ast)`. + +- **Parameters:** + - `ast` ([`AST.Node`]) The AST to visit. + - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. + +### RegExpParser + +#### new RegExpParser(options?) + +- **Parameters:** + - `options?` ([`RegExpParser.Options`]) The options to parse. + +#### parser.parseLiteral(source, start?, end?) + +Parse a regular expression literal. + +- **Parameters:** + - `source` (`string`) The source code to parse. E.g. `"/abc/g"`. + - `start?` (`number`) The start index in the source code. Default is `0`. + - `end?` (`number`) The end index in the source code. Default is `source.length`. +- **Return:** + - The AST of the regular expression. + +#### parser.parsePattern(source, start?, end?, flags?) + +Parse a regular expression pattern. + +- **Parameters:** + - `source` (`string`) The source code to parse. E.g. `"abc"`. + - `start?` (`number`) The start index in the source code. Default is `0`. + - `end?` (`number`) The end index in the source code. Default is `source.length`. + - `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode. +- **Return:** + - The AST of the regular expression pattern. + +#### parser.parseFlags(source, start?, end?) + +Parse a regular expression flags. + +- **Parameters:** + - `source` (`string`) The source code to parse. E.g. `"gim"`. + - `start?` (`number`) The start index in the source code. Default is `0`. + - `end?` (`number`) The end index in the source code. Default is `source.length`. +- **Return:** + - The AST of the regular expression flags. + +### RegExpValidator + +#### new RegExpValidator(options) + +- **Parameters:** + - `options` ([`RegExpValidator.Options`]) The options to validate. + +#### validator.validateLiteral(source, start, end) + +Validate a regular expression literal. + +- **Parameters:** + - `source` (`string`) The source code to validate. + - `start?` (`number`) The start index in the source code. Default is `0`. + - `end?` (`number`) The end index in the source code. Default is `source.length`. + +#### validator.validatePattern(source, start, end, flags) + +Validate a regular expression pattern. + +- **Parameters:** + - `source` (`string`) The source code to validate. + - `start?` (`number`) The start index in the source code. Default is `0`. + - `end?` (`number`) The end index in the source code. Default is `source.length`. + - `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode. + +#### validator.validateFlags(source, start, end) + +Validate a regular expression flags. + +- **Parameters:** + - `source` (`string`) The source code to validate. + - `start?` (`number`) The start index in the source code. Default is `0`. + - `end?` (`number`) The end index in the source code. Default is `source.length`. + +### RegExpVisitor + +#### new RegExpVisitor(handlers) + +- **Parameters:** + - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. + +#### visitor.visit(ast) + +Validate a regular expression literal. + +- **Parameters:** + - `ast` ([`AST.Node`]) The AST to visit. + +## 📰 Changelog + +- [GitHub Releases](https://github.com/eslint-community/regexpp/releases) + +## 🍻 Contributing + +Welcome contributing! + +Please use GitHub's Issues/PRs. + +### Development Tools + +- `npm test` runs tests and measures coverage. +- `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`. +- `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`. +- `npm run lint` runs ESLint. +- `npm run update:test` updates test fixtures. +- `npm run update:ids` updates `src/unicode/ids.ts`. +- `npm run watch` runs tests with `--watch` option. + +[`AST.Node`]: src/ast.ts#L4 +[`RegExpParser.Options`]: src/parser.ts#L743 +[`RegExpValidator.Options`]: src/validator.ts#L220 +[`RegExpVisitor.Handlers`]: src/visitor.ts#L291 diff --git a/node_modules/@eslint-community/regexpp/index.d.ts b/node_modules/@eslint-community/regexpp/index.d.ts new file mode 100644 index 00000000..c75657aa --- /dev/null +++ b/node_modules/@eslint-community/regexpp/index.d.ts @@ -0,0 +1,1163 @@ +// Generated by dts-bundle v0.7.3 + +declare module "@eslint-community/regexpp" { + import * as AST from "@eslint-community/regexpp/ast"; + import { RegExpParser } from "@eslint-community/regexpp/parser"; + import { RegExpValidator } from "@eslint-community/regexpp/validator"; + import { RegExpVisitor } from "@eslint-community/regexpp/visitor"; + export { RegExpSyntaxError } from "@eslint-community/regexpp/regexp-syntax-error"; + export { AST, RegExpParser, RegExpValidator }; + /** + * Parse a given regular expression literal then make AST object. + * @param source The source code to parse. + * @param options The options to parse. + * @returns The AST of the regular expression. + */ + export function parseRegExpLiteral( + source: RegExp | string, + options?: RegExpParser.Options + ): AST.RegExpLiteral; + /** + * Validate a given regular expression literal. + * @param source The source code to validate. + * @param options The options to validate. + */ + export function validateRegExpLiteral( + source: string, + options?: RegExpValidator.Options + ): void; + export function visitRegExpAST( + node: AST.Node, + handlers: RegExpVisitor.Handlers + ): void; +} + +declare module "@eslint-community/regexpp/ast" { + /** + * The type which includes all nodes. + */ + export type Node = BranchNode | LeafNode; + /** + * The type which includes all branch nodes. + */ + export type BranchNode = + | Alternative + | CapturingGroup + | CharacterClass + | CharacterClassRange + | ClassIntersection + | ClassStringDisjunction + | ClassSubtraction + | ExpressionCharacterClass + | Group + | LookaroundAssertion + | Modifiers + | Pattern + | Quantifier + | RegExpLiteral + | StringAlternative; + /** + * The type which includes all leaf nodes. + */ + export type LeafNode = + | Backreference + | BoundaryAssertion + | Character + | CharacterSet + | Flags + | ModifierFlags; + /** + * The type which includes all atom nodes. + */ + export type Element = Assertion | QuantifiableElement | Quantifier; + /** + * The type which includes all atom nodes that Quantifier node can have as children. + */ + export type QuantifiableElement = + | Backreference + | CapturingGroup + | Character + | CharacterClass + | CharacterSet + | ExpressionCharacterClass + | Group + | LookaheadAssertion; + /** + * The type which includes all character class atom nodes. + */ + export type CharacterClassElement = + | ClassRangesCharacterClassElement + | UnicodeSetsCharacterClassElement; + export type ClassRangesCharacterClassElement = + | Character + | CharacterClassRange + | CharacterUnicodePropertyCharacterSet + | EscapeCharacterSet; + export type UnicodeSetsCharacterClassElement = + | Character + | CharacterClassRange + | ClassStringDisjunction + | EscapeCharacterSet + | ExpressionCharacterClass + | UnicodePropertyCharacterSet + | UnicodeSetsCharacterClass; + /** + * The type which defines common properties for all node types. + */ + export interface NodeBase { + /** The node type. */ + type: Node["type"]; + /** The parent node. */ + parent: Node["parent"]; + /** The 0-based index that this node starts. */ + start: number; + /** The 0-based index that this node ends. */ + end: number; + /** The raw text of this node. */ + raw: string; + } + /** + * The root node. + */ + export interface RegExpLiteral extends NodeBase { + type: "RegExpLiteral"; + parent: null; + pattern: Pattern; + flags: Flags; + } + /** + * The pattern. + */ + export interface Pattern extends NodeBase { + type: "Pattern"; + parent: RegExpLiteral | null; + alternatives: Alternative[]; + } + /** + * The alternative. + * E.g. `a|b` + */ + export interface Alternative extends NodeBase { + type: "Alternative"; + parent: CapturingGroup | Group | LookaroundAssertion | Pattern; + elements: Element[]; + } + /** + * The uncapturing group. + * E.g. `(?:ab)` + */ + export interface Group extends NodeBase { + type: "Group"; + parent: Alternative | Quantifier; + modifiers: Modifiers | null; + alternatives: Alternative[]; + } + /** + * The capturing group. + * E.g. `(ab)`, `(?ab)` + */ + export interface CapturingGroup extends NodeBase { + type: "CapturingGroup"; + parent: Alternative | Quantifier; + name: string | null; + alternatives: Alternative[]; + references: Backreference[]; + } + /** + * The lookaround assertion. + */ + export type LookaroundAssertion = LookaheadAssertion | LookbehindAssertion; + /** + * The lookahead assertion. + * E.g. `(?=ab)`, `(?!ab)` + */ + export interface LookaheadAssertion extends NodeBase { + type: "Assertion"; + parent: Alternative | Quantifier; + kind: "lookahead"; + negate: boolean; + alternatives: Alternative[]; + } + /** + * The lookbehind assertion. + * E.g. `(?<=ab)`, `(?` + */ + export type Backreference = AmbiguousBackreference | UnambiguousBackreference; + interface BaseBackreference extends NodeBase { + type: "Backreference"; + parent: Alternative | Quantifier; + ref: number | string; + ambiguous: boolean; + resolved: CapturingGroup | CapturingGroup[]; + } + export interface AmbiguousBackreference extends BaseBackreference { + ref: string; + ambiguous: true; + resolved: CapturingGroup[]; + } + export interface UnambiguousBackreference extends BaseBackreference { + ambiguous: false; + resolved: CapturingGroup; + } + /** + * The modifiers. + */ + export interface Modifiers extends NodeBase { + type: "Modifiers"; + parent: Group; + /** + * The add modifier flags. + */ + add: ModifierFlags; + /** + * The remove modifier flags. + * + * `null` means no remove modifier flags. e.g. `(?ims:x)` + * The reason for `null` is that there is no position where the remove modifier flags appears. Must be behind the minus mark. + */ + remove: ModifierFlags | null; + } + /** + * The modifier flags. + */ + export interface ModifierFlags extends NodeBase { + type: "ModifierFlags"; + parent: Modifiers; + dotAll: boolean; + ignoreCase: boolean; + multiline: boolean; + } + /** + * The flags. + */ + export interface Flags extends NodeBase { + type: "Flags"; + parent: RegExpLiteral | null; + dotAll: boolean; + global: boolean; + hasIndices: boolean; + ignoreCase: boolean; + multiline: boolean; + sticky: boolean; + unicode: boolean; + unicodeSets: boolean; + } + export {}; +} + +declare module "@eslint-community/regexpp/parser" { + import type { + Flags, + RegExpLiteral, + Pattern, + } from "@eslint-community/regexpp/ast"; + import type { EcmaVersion } from "@eslint-community/regexpp/ecma-versions"; + export namespace RegExpParser { + /** + * The options for RegExpParser construction. + */ + interface Options { + /** + * The flag to disable Annex B syntax. Default is `false`. + */ + strict?: boolean; + /** + * ECMAScript version. Default is `2025`. + * - `2015` added `u` and `y` flags. + * - `2018` added `s` flag, Named Capturing Group, Lookbehind Assertion, + * and Unicode Property Escape. + * - `2019`, `2020`, and `2021` added more valid Unicode Property Escapes. + * - `2022` added `d` flag. + * - `2023` added more valid Unicode Property Escapes. + * - `2024` added `v` flag. + * - `2025` added duplicate named capturing groups, modifiers. + */ + ecmaVersion?: EcmaVersion; + } + } + export class RegExpParser { + /** + * Initialize this parser. + * @param options The options of parser. + */ + constructor(options?: RegExpParser.Options); + /** + * Parse a regular expression literal. E.g. "/abc/g" + * @param source The source code to parse. + * @param start The start index in the source code. + * @param end The end index in the source code. + * @returns The AST of the given regular expression. + */ + parseLiteral(source: string, start?: number, end?: number): RegExpLiteral; + /** + * Parse a regular expression flags. E.g. "gim" + * @param source The source code to parse. + * @param start The start index in the source code. + * @param end The end index in the source code. + * @returns The AST of the given flags. + */ + parseFlags(source: string, start?: number, end?: number): Flags; + /** + * Parse a regular expression pattern. E.g. "abc" + * @param source The source code to parse. + * @param start The start index in the source code. + * @param end The end index in the source code. + * @param flags The flags. + * @returns The AST of the given pattern. + */ + parsePattern( + source: string, + start?: number, + end?: number, + flags?: { + unicode?: boolean; + unicodeSets?: boolean; + } + ): Pattern; + /** + * @deprecated Backward compatibility + * Use object `flags` instead of boolean `uFlag`. + * + * @param source The source code to parse. + * @param start The start index in the source code. + * @param end The end index in the source code. + * @param uFlag The flag to set unicode mode. + * @returns The AST of the given pattern. + */ + parsePattern( + source: string, + start?: number, + end?: number, + uFlag?: boolean + ): Pattern; + } +} + +declare module "@eslint-community/regexpp/validator" { + import type { EcmaVersion } from "@eslint-community/regexpp/ecma-versions"; + export type RegExpValidatorSourceContext = { + readonly source: string; + readonly start: number; + readonly end: number; + readonly kind: "flags" | "literal" | "pattern"; + }; + export namespace RegExpValidator { + /** + * The options for RegExpValidator construction. + */ + interface Options { + /** + * The flag to disable Annex B syntax. Default is `false`. + */ + strict?: boolean; + /** + * ECMAScript version. Default is `2025`. + * - `2015` added `u` and `y` flags. + * - `2018` added `s` flag, Named Capturing Group, Lookbehind Assertion, + * and Unicode Property Escape. + * - `2019`, `2020`, and `2021` added more valid Unicode Property Escapes. + * - `2022` added `d` flag. + * - `2023` added more valid Unicode Property Escapes. + * - `2024` added `v` flag. + * - `2025` added duplicate named capturing groups, modifiers. + */ + ecmaVersion?: EcmaVersion; + /** + * A function that is called when the validator entered a RegExp literal. + * @param start The 0-based index of the first character. + */ + onLiteralEnter?: (start: number) => void; + /** + * A function that is called when the validator left a RegExp literal. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + */ + onLiteralLeave?: (start: number, end: number) => void; + /** + * A function that is called when the validator found flags. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param flags.global `g` flag. + * @param flags.ignoreCase `i` flag. + * @param flags.multiline `m` flag. + * @param flags.unicode `u` flag. + * @param flags.sticky `y` flag. + * @param flags.dotAll `s` flag. + * @param flags.hasIndices `d` flag. + * @param flags.unicodeSets `v` flag. + */ + onRegExpFlags?: ( + start: number, + end: number, + flags: { + global: boolean; + ignoreCase: boolean; + multiline: boolean; + unicode: boolean; + sticky: boolean; + dotAll: boolean; + hasIndices: boolean; + unicodeSets: boolean; + } + ) => void; + /** + * A function that is called when the validator found flags. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param global `g` flag. + * @param ignoreCase `i` flag. + * @param multiline `m` flag. + * @param unicode `u` flag. + * @param sticky `y` flag. + * @param dotAll `s` flag. + * @param hasIndices `d` flag. + * + * @deprecated Use `onRegExpFlags` instead. + */ + onFlags?: ( + start: number, + end: number, + global: boolean, + ignoreCase: boolean, + multiline: boolean, + unicode: boolean, + sticky: boolean, + dotAll: boolean, + hasIndices: boolean + ) => void; + /** + * A function that is called when the validator entered a pattern. + * @param start The 0-based index of the first character. + */ + onPatternEnter?: (start: number) => void; + /** + * A function that is called when the validator left a pattern. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + */ + onPatternLeave?: (start: number, end: number) => void; + /** + * A function that is called when the validator entered a disjunction. + * @param start The 0-based index of the first character. + */ + onDisjunctionEnter?: (start: number) => void; + /** + * A function that is called when the validator left a disjunction. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + */ + onDisjunctionLeave?: (start: number, end: number) => void; + /** + * A function that is called when the validator entered an alternative. + * @param start The 0-based index of the first character. + * @param index The 0-based index of alternatives in a disjunction. + */ + onAlternativeEnter?: (start: number, index: number) => void; + /** + * A function that is called when the validator left an alternative. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param index The 0-based index of alternatives in a disjunction. + */ + onAlternativeLeave?: (start: number, end: number, index: number) => void; + /** + * A function that is called when the validator entered an uncapturing group. + * @param start The 0-based index of the first character. + */ + onGroupEnter?: (start: number) => void; + /** + * A function that is called when the validator left an uncapturing group. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + */ + onGroupLeave?: (start: number, end: number) => void; + /** + * A function that is called when the validator entered a modifiers. + * @param start The 0-based index of the first character. + */ + onModifiersEnter?: (start: number) => void; + /** + * A function that is called when the validator left a modifiers. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + */ + onModifiersLeave?: (start: number, end: number) => void; + /** + * A function that is called when the validator found an add modifiers. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param flags flags. + * @param flags.ignoreCase `i` flag. + * @param flags.multiline `m` flag. + * @param flags.dotAll `s` flag. + */ + onAddModifiers?: ( + start: number, + end: number, + flags: { + ignoreCase: boolean; + multiline: boolean; + dotAll: boolean; + } + ) => void; + /** + * A function that is called when the validator found a remove modifiers. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param flags flags. + * @param flags.ignoreCase `i` flag. + * @param flags.multiline `m` flag. + * @param flags.dotAll `s` flag. + */ + onRemoveModifiers?: ( + start: number, + end: number, + flags: { + ignoreCase: boolean; + multiline: boolean; + dotAll: boolean; + } + ) => void; + /** + * A function that is called when the validator entered a capturing group. + * @param start The 0-based index of the first character. + * @param name The group name. + */ + onCapturingGroupEnter?: (start: number, name: string | null) => void; + /** + * A function that is called when the validator left a capturing group. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param name The group name. + */ + onCapturingGroupLeave?: ( + start: number, + end: number, + name: string | null + ) => void; + /** + * A function that is called when the validator found a quantifier. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param min The minimum number of repeating. + * @param max The maximum number of repeating. + * @param greedy The flag to choose the longest matching. + */ + onQuantifier?: ( + start: number, + end: number, + min: number, + max: number, + greedy: boolean + ) => void; + /** + * A function that is called when the validator entered a lookahead/lookbehind assertion. + * @param start The 0-based index of the first character. + * @param kind The kind of the assertion. + * @param negate The flag which represents that the assertion is negative. + */ + onLookaroundAssertionEnter?: ( + start: number, + kind: "lookahead" | "lookbehind", + negate: boolean + ) => void; + /** + * A function that is called when the validator left a lookahead/lookbehind assertion. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param kind The kind of the assertion. + * @param negate The flag which represents that the assertion is negative. + */ + onLookaroundAssertionLeave?: ( + start: number, + end: number, + kind: "lookahead" | "lookbehind", + negate: boolean + ) => void; + /** + * A function that is called when the validator found an edge boundary assertion. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param kind The kind of the assertion. + */ + onEdgeAssertion?: ( + start: number, + end: number, + kind: "end" | "start" + ) => void; + /** + * A function that is called when the validator found a word boundary assertion. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param kind The kind of the assertion. + * @param negate The flag which represents that the assertion is negative. + */ + onWordBoundaryAssertion?: ( + start: number, + end: number, + kind: "word", + negate: boolean + ) => void; + /** + * A function that is called when the validator found a dot. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param kind The kind of the character set. + */ + onAnyCharacterSet?: (start: number, end: number, kind: "any") => void; + /** + * A function that is called when the validator found a character set escape. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param kind The kind of the character set. + * @param negate The flag which represents that the character set is negative. + */ + onEscapeCharacterSet?: ( + start: number, + end: number, + kind: "digit" | "space" | "word", + negate: boolean + ) => void; + /** + * A function that is called when the validator found a Unicode proerty escape. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param kind The kind of the character set. + * @param key The property name. + * @param value The property value. + * @param negate The flag which represents that the character set is negative. + * @param strings If true, the given property is property of strings. + */ + onUnicodePropertyCharacterSet?: ( + start: number, + end: number, + kind: "property", + key: string, + value: string | null, + negate: boolean, + strings: boolean + ) => void; + /** + * A function that is called when the validator found a character. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param value The code point of the character. + */ + onCharacter?: (start: number, end: number, value: number) => void; + /** + * A function that is called when the validator found a backreference. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param ref The key of the referred capturing group. + */ + onBackreference?: ( + start: number, + end: number, + ref: number | string + ) => void; + /** + * A function that is called when the validator entered a character class. + * @param start The 0-based index of the first character. + * @param negate The flag which represents that the character class is negative. + * @param unicodeSets `true` if unicodeSets mode. + */ + onCharacterClassEnter?: ( + start: number, + negate: boolean, + unicodeSets: boolean + ) => void; + /** + * A function that is called when the validator left a character class. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param negate The flag which represents that the character class is negative. + */ + onCharacterClassLeave?: ( + start: number, + end: number, + negate: boolean + ) => void; + /** + * A function that is called when the validator found a character class range. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param min The minimum code point of the range. + * @param max The maximum code point of the range. + */ + onCharacterClassRange?: ( + start: number, + end: number, + min: number, + max: number + ) => void; + /** + * A function that is called when the validator found a class intersection. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + */ + onClassIntersection?: (start: number, end: number) => void; + /** + * A function that is called when the validator found a class subtraction. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + */ + onClassSubtraction?: (start: number, end: number) => void; + /** + * A function that is called when the validator entered a class string disjunction. + * @param start The 0-based index of the first character. + */ + onClassStringDisjunctionEnter?: (start: number) => void; + /** + * A function that is called when the validator left a class string disjunction. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + */ + onClassStringDisjunctionLeave?: (start: number, end: number) => void; + /** + * A function that is called when the validator entered a string alternative. + * @param start The 0-based index of the first character. + * @param index The 0-based index of alternatives in a disjunction. + */ + onStringAlternativeEnter?: (start: number, index: number) => void; + /** + * A function that is called when the validator left a string alternative. + * @param start The 0-based index of the first character. + * @param end The next 0-based index of the last character. + * @param index The 0-based index of alternatives in a disjunction. + */ + onStringAlternativeLeave?: ( + start: number, + end: number, + index: number + ) => void; + } + } + /** + * The regular expression validator. + */ + export class RegExpValidator { + /** + * Initialize this validator. + * @param options The options of validator. + */ + constructor(options?: RegExpValidator.Options); + /** + * Validate a regular expression literal. E.g. "/abc/g" + * @param source The source code to validate. + * @param start The start index in the source code. + * @param end The end index in the source code. + */ + validateLiteral(source: string, start?: number, end?: number): void; + /** + * Validate a regular expression flags. E.g. "gim" + * @param source The source code to validate. + * @param start The start index in the source code. + * @param end The end index in the source code. + */ + validateFlags(source: string, start?: number, end?: number): void; + /** + * Validate a regular expression pattern. E.g. "abc" + * @param source The source code to validate. + * @param start The start index in the source code. + * @param end The end index in the source code. + * @param flags The flags. + */ + validatePattern( + source: string, + start?: number, + end?: number, + flags?: { + unicode?: boolean; + unicodeSets?: boolean; + } + ): void; + /** + * @deprecated Backward compatibility + * Use object `flags` instead of boolean `uFlag`. + * @param source The source code to validate. + * @param start The start index in the source code. + * @param end The end index in the source code. + * @param uFlag The flag to set unicode mode. + */ + validatePattern( + source: string, + start?: number, + end?: number, + uFlag?: boolean + ): void; + } +} + +declare module "@eslint-community/regexpp/visitor" { + import type { + Alternative, + Assertion, + Backreference, + CapturingGroup, + Character, + CharacterClass, + CharacterClassRange, + CharacterSet, + ClassIntersection, + ClassStringDisjunction, + ClassSubtraction, + ExpressionCharacterClass, + Flags, + Group, + ModifierFlags, + Modifiers, + Node, + Pattern, + Quantifier, + RegExpLiteral, + StringAlternative, + } from "@eslint-community/regexpp/ast"; + /** + * The visitor to walk on AST. + */ + export class RegExpVisitor { + /** + * Initialize this visitor. + * @param handlers Callbacks for each node. + */ + constructor(handlers: RegExpVisitor.Handlers); + /** + * Visit a given node and descendant nodes. + * @param node The root node to visit tree. + */ + visit(node: Node): void; + } + export namespace RegExpVisitor { + interface Handlers { + onAlternativeEnter?: (node: Alternative) => void; + onAlternativeLeave?: (node: Alternative) => void; + onAssertionEnter?: (node: Assertion) => void; + onAssertionLeave?: (node: Assertion) => void; + onBackreferenceEnter?: (node: Backreference) => void; + onBackreferenceLeave?: (node: Backreference) => void; + onCapturingGroupEnter?: (node: CapturingGroup) => void; + onCapturingGroupLeave?: (node: CapturingGroup) => void; + onCharacterEnter?: (node: Character) => void; + onCharacterLeave?: (node: Character) => void; + onCharacterClassEnter?: (node: CharacterClass) => void; + onCharacterClassLeave?: (node: CharacterClass) => void; + onCharacterClassRangeEnter?: (node: CharacterClassRange) => void; + onCharacterClassRangeLeave?: (node: CharacterClassRange) => void; + onCharacterSetEnter?: (node: CharacterSet) => void; + onCharacterSetLeave?: (node: CharacterSet) => void; + onClassIntersectionEnter?: (node: ClassIntersection) => void; + onClassIntersectionLeave?: (node: ClassIntersection) => void; + onClassStringDisjunctionEnter?: (node: ClassStringDisjunction) => void; + onClassStringDisjunctionLeave?: (node: ClassStringDisjunction) => void; + onClassSubtractionEnter?: (node: ClassSubtraction) => void; + onClassSubtractionLeave?: (node: ClassSubtraction) => void; + onExpressionCharacterClassEnter?: ( + node: ExpressionCharacterClass + ) => void; + onExpressionCharacterClassLeave?: ( + node: ExpressionCharacterClass + ) => void; + onFlagsEnter?: (node: Flags) => void; + onFlagsLeave?: (node: Flags) => void; + onGroupEnter?: (node: Group) => void; + onGroupLeave?: (node: Group) => void; + onModifierFlagsEnter?: (node: ModifierFlags) => void; + onModifierFlagsLeave?: (node: ModifierFlags) => void; + onModifiersEnter?: (node: Modifiers) => void; + onModifiersLeave?: (node: Modifiers) => void; + onPatternEnter?: (node: Pattern) => void; + onPatternLeave?: (node: Pattern) => void; + onQuantifierEnter?: (node: Quantifier) => void; + onQuantifierLeave?: (node: Quantifier) => void; + onRegExpLiteralEnter?: (node: RegExpLiteral) => void; + onRegExpLiteralLeave?: (node: RegExpLiteral) => void; + onStringAlternativeEnter?: (node: StringAlternative) => void; + onStringAlternativeLeave?: (node: StringAlternative) => void; + } + } +} + +declare module "@eslint-community/regexpp/regexp-syntax-error" { + import type { RegExpValidatorSourceContext } from "@eslint-community/regexpp/validator"; + export class RegExpSyntaxError extends SyntaxError { + index: number; + constructor(message: string, index: number); + } + export function newRegExpSyntaxError( + srcCtx: RegExpValidatorSourceContext, + flags: { + unicode: boolean; + unicodeSets: boolean; + }, + index: number, + message: string + ): RegExpSyntaxError; +} + +declare module "@eslint-community/regexpp/ecma-versions" { + export type EcmaVersion = + | 5 + | 2015 + | 2016 + | 2017 + | 2018 + | 2019 + | 2020 + | 2021 + | 2022 + | 2023 + | 2024 + | 2025; + export const latestEcmaVersion = 2025; +} diff --git a/node_modules/@eslint-community/regexpp/index.js b/node_modules/@eslint-community/regexpp/index.js new file mode 100644 index 00000000..ac5d686e --- /dev/null +++ b/node_modules/@eslint-community/regexpp/index.js @@ -0,0 +1,3037 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var ast = /*#__PURE__*/Object.freeze({ + __proto__: null +}); + +const latestEcmaVersion = 2025; + +let largeIdStartRanges = undefined; +let largeIdContinueRanges = undefined; +function isIdStart(cp) { + if (cp < 0x41) + return false; + if (cp < 0x5b) + return true; + if (cp < 0x61) + return false; + if (cp < 0x7b) + return true; + return isLargeIdStart(cp); +} +function isIdContinue(cp) { + if (cp < 0x30) + return false; + if (cp < 0x3a) + return true; + if (cp < 0x41) + return false; + if (cp < 0x5b) + return true; + if (cp === 0x5f) + return true; + if (cp < 0x61) + return false; + if (cp < 0x7b) + return true; + return isLargeIdStart(cp) || isLargeIdContinue(cp); +} +function isLargeIdStart(cp) { + return isInRange(cp, largeIdStartRanges !== null && largeIdStartRanges !== void 0 ? largeIdStartRanges : (largeIdStartRanges = initLargeIdStartRanges())); +} +function isLargeIdContinue(cp) { + return isInRange(cp, largeIdContinueRanges !== null && largeIdContinueRanges !== void 0 ? largeIdContinueRanges : (largeIdContinueRanges = initLargeIdContinueRanges())); +} +function initLargeIdStartRanges() { + return restoreRanges("4q 0 b 0 5 0 6 m 2 u 2 cp 5 b f 4 8 0 2 0 3m 4 2 1 3 3 2 0 7 0 2 2 2 0 2 j 2 2a 2 3u 9 4l 2 11 3 0 7 14 20 q 5 3 1a 16 10 1 2 2q 2 0 g 1 8 1 b 2 3 0 h 0 2 t u 2g c 0 p w a 1 5 0 6 l 5 0 a 0 4 0 o o 8 a 6 n 2 5 i 15 1n 1h 4 0 j 0 8 9 g f 5 7 3 1 3 l 2 6 2 0 4 3 4 0 h 0 e 1 2 2 f 1 b 0 9 5 5 1 3 l 2 6 2 1 2 1 2 1 w 3 2 0 k 2 h 8 2 2 2 l 2 6 2 1 2 4 4 0 j 0 g 1 o 0 c 7 3 1 3 l 2 6 2 1 2 4 4 0 v 1 2 2 g 0 i 0 2 5 4 2 2 3 4 1 2 0 2 1 4 1 4 2 4 b n 0 1h 7 2 2 2 m 2 f 4 0 r 2 3 0 3 1 v 0 5 7 2 2 2 m 2 9 2 4 4 0 w 1 2 1 g 1 i 8 2 2 2 14 3 0 h 0 6 2 9 2 p 5 6 h 4 n 2 8 2 0 3 6 1n 1b 2 1 d 6 1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5 13 9 1f d a 2 e 2 6 2 1 2 a 2 e 2 6 2 1 4 1f d 8m a l b 7 p 5 2 15 2 8 1y 5 3 0 2 17 2 1 4 0 3 m b m a u 1u i 2 1 b l b p 1z 1j 7 1 1t 0 g 3 2 2 2 s 17 s 4 s 10 7 2 r s 1h b l b i e h 33 20 1k 1e e 1e e z 13 r a m 6z 15 7 1 h 2 1o s b 0 9 l 17 h 1b k s m d 1g 1m 1 3 0 e 18 x o r z u 0 3 0 9 y 4 0 d 1b f 3 m 0 2 0 10 h 2 o k 1 1s 6 2 0 2 3 2 e 2 9 8 1a 13 7 3 1 3 l 2 6 2 1 2 4 4 0 j 0 d 4 v 9 2 0 3 0 2 11 2 0 q 0 2 0 19 1g j 3 l 2 v 1b l 1 2 0 55 1a 16 3 11 1b l 0 1o 16 e 0 20 q 12 6 56 17 39 1r w 7 3 0 3 7 2 1 2 n g 0 2 0 2n 7 3 12 h 0 2 0 t 0 b 13 8 0 m 0 c 19 k 0 j 20 5k w w 8 2 10 i 0 1e t 35 6 2 1 2 11 m 0 q 5 2 1 2 v f 0 94 i g 0 2 c 2 x 3h 0 28 pl 2v 32 i 5f 219 2o g tr i 5 q 32y 6 g6 5a2 t 1cz fs 8 u i 26 i t j 1b h 3 w k 6 i c1 18 5w 1r 3l 22 6 0 1v c 1t 1 2 0 t 4qf 9 yd 16 9 6w8 3 2 6 2 1 2 82 g 0 u 2 3 0 f 3 9 az 1s5 2y 6 c 4 8 8 9 4mf 2c 2 1y 2 1 3 0 3 1 3 3 2 b 2 0 2 6 2 1s 2 3 3 7 2 6 2 r 2 3 2 4 2 0 4 6 2 9f 3 o 2 o 2 u 2 o 2 u 2 o 2 u 2 o 2 u 2 o 2 7 1f9 u 7 5 7a 1p 43 18 b 6 h 0 8y t j 17 dh r 6d t 3 0 ds 6 2 3 2 1 2 e 2 5g 1o 1v 8 0 xh 3 2 q 2 1 2 0 3 0 2 9 2 3 2 0 2 0 7 0 5 0 2 0 2 0 2 2 2 1 2 0 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 1 6 1 2 0 16 4 6 1 6l 7 2 1 3 9 fmt 0 ki f h f 4 1 p 2 5d 9 12 0 12 0 ig 0 6b 0 46 4 86 9 120 2 2 1 6 3 15 2 5 0 4m 1 fy 3 9 9 7 9 w 4 8u 1 28 3 1z a 1e 3 3f 2 1i e w a 3 1 b 3 1a a 8 0 1a 9 7 2 11 d 2 9 6 1 19 0 d 2 1d d 9 3 2 b 2b b 7 0 3 0 4e b 6 9 7 3 1k 1 2 6 3 1 3 2 a 0 b 1 3 6 4 4 1w 8 2 0 3 0 2 3 2 4 2 0 f 1 2b h a 9 5 0 2a j d 9 5y 6 3 8 s 1 2b g g 9 2a c 9 9 7 j 1m e 5 9 6r e 4m 9 1z 5 2 1 3 3 2 0 2 1 d 9 3c 6 3 6 4 0 t 9 15 6 2 3 9 0 a a 1b f 9j 9 1i 7 2 7 h 9 1l l 2 d 3f 5 4 0 2 1 2 6 2 0 9 9 1d 4 2 1 2 4 9 9 96 3 a 1 2 0 1d 6 4 4 e a 44m 0 7 e 8uh r 1t3 9 2f 9 13 4 1o 6 q 9 ev 9 d2 0 2 1i 8 3 2a 0 c 1 f58 1 382 9 ef 19 3 m f3 4 4 5 9 7 3 6 v 3 45 2 13e 1d e9 1i 5 1d 9 0 f 0 n 4 2 e 11t 6 2 g 3 6 2 1 2 4 2t 0 4h 6 a 9 9x 0 1q d dv d 6t 1 2 9 k6 6 32 6 6 9 3o7 9 gvt3 6n"); +} +function isInRange(cp, ranges) { + let l = 0, r = (ranges.length / 2) | 0, i = 0, min = 0, max = 0; + while (l < r) { + i = ((l + r) / 2) | 0; + min = ranges[2 * i]; + max = ranges[2 * i + 1]; + if (cp < min) { + r = i; + } + else if (cp > max) { + l = i + 1; + } + else { + return true; + } + } + return false; +} +function restoreRanges(data) { + let last = 0; + return data.split(" ").map((s) => (last += parseInt(s, 36) | 0)); +} + +class DataSet { + constructor(raw2018, raw2019, raw2020, raw2021, raw2022, raw2023, raw2024, raw2025) { + this._raw2018 = raw2018; + this._raw2019 = raw2019; + this._raw2020 = raw2020; + this._raw2021 = raw2021; + this._raw2022 = raw2022; + this._raw2023 = raw2023; + this._raw2024 = raw2024; + this._raw2025 = raw2025; + } + get es2018() { + var _a; + return ((_a = this._set2018) !== null && _a !== void 0 ? _a : (this._set2018 = new Set(this._raw2018.split(" ")))); + } + get es2019() { + var _a; + return ((_a = this._set2019) !== null && _a !== void 0 ? _a : (this._set2019 = new Set(this._raw2019.split(" ")))); + } + get es2020() { + var _a; + return ((_a = this._set2020) !== null && _a !== void 0 ? _a : (this._set2020 = new Set(this._raw2020.split(" ")))); + } + get es2021() { + var _a; + return ((_a = this._set2021) !== null && _a !== void 0 ? _a : (this._set2021 = new Set(this._raw2021.split(" ")))); + } + get es2022() { + var _a; + return ((_a = this._set2022) !== null && _a !== void 0 ? _a : (this._set2022 = new Set(this._raw2022.split(" ")))); + } + get es2023() { + var _a; + return ((_a = this._set2023) !== null && _a !== void 0 ? _a : (this._set2023 = new Set(this._raw2023.split(" ")))); + } + get es2024() { + var _a; + return ((_a = this._set2024) !== null && _a !== void 0 ? _a : (this._set2024 = new Set(this._raw2024.split(" ")))); + } + get es2025() { + var _a; + return ((_a = this._set2025) !== null && _a !== void 0 ? _a : (this._set2025 = new Set(this._raw2025.split(" ")))); + } +} +const gcNameSet = new Set(["General_Category", "gc"]); +const scNameSet = new Set(["Script", "Script_Extensions", "sc", "scx"]); +const gcValueSets = new DataSet("C Cased_Letter Cc Cf Close_Punctuation Cn Co Combining_Mark Connector_Punctuation Control Cs Currency_Symbol Dash_Punctuation Decimal_Number Enclosing_Mark Final_Punctuation Format Initial_Punctuation L LC Letter Letter_Number Line_Separator Ll Lm Lo Lowercase_Letter Lt Lu M Mark Math_Symbol Mc Me Mn Modifier_Letter Modifier_Symbol N Nd Nl No Nonspacing_Mark Number Open_Punctuation Other Other_Letter Other_Number Other_Punctuation Other_Symbol P Paragraph_Separator Pc Pd Pe Pf Pi Po Private_Use Ps Punctuation S Sc Separator Sk Sm So Space_Separator Spacing_Mark Surrogate Symbol Titlecase_Letter Unassigned Uppercase_Letter Z Zl Zp Zs cntrl digit punct", "", "", "", "", "", "", ""); +const scValueSets = new DataSet("Adlam Adlm Aghb Ahom Anatolian_Hieroglyphs Arab Arabic Armenian Armi Armn Avestan Avst Bali Balinese Bamu Bamum Bass Bassa_Vah Batak Batk Beng Bengali Bhaiksuki Bhks Bopo Bopomofo Brah Brahmi Brai Braille Bugi Buginese Buhd Buhid Cakm Canadian_Aboriginal Cans Cari Carian Caucasian_Albanian Chakma Cham Cher Cherokee Common Copt Coptic Cprt Cuneiform Cypriot Cyrillic Cyrl Deseret Deva Devanagari Dsrt Dupl Duployan Egyp Egyptian_Hieroglyphs Elba Elbasan Ethi Ethiopic Geor Georgian Glag Glagolitic Gonm Goth Gothic Gran Grantha Greek Grek Gujarati Gujr Gurmukhi Guru Han Hang Hangul Hani Hano Hanunoo Hatr Hatran Hebr Hebrew Hira Hiragana Hluw Hmng Hung Imperial_Aramaic Inherited Inscriptional_Pahlavi Inscriptional_Parthian Ital Java Javanese Kaithi Kali Kana Kannada Katakana Kayah_Li Khar Kharoshthi Khmer Khmr Khoj Khojki Khudawadi Knda Kthi Lana Lao Laoo Latin Latn Lepc Lepcha Limb Limbu Lina Linb Linear_A Linear_B Lisu Lyci Lycian Lydi Lydian Mahajani Mahj Malayalam Mand Mandaic Mani Manichaean Marc Marchen Masaram_Gondi Meetei_Mayek Mend Mende_Kikakui Merc Mero Meroitic_Cursive Meroitic_Hieroglyphs Miao Mlym Modi Mong Mongolian Mro Mroo Mtei Mult Multani Myanmar Mymr Nabataean Narb Nbat New_Tai_Lue Newa Nko Nkoo Nshu Nushu Ogam Ogham Ol_Chiki Olck Old_Hungarian Old_Italic Old_North_Arabian Old_Permic Old_Persian Old_South_Arabian Old_Turkic Oriya Orkh Orya Osage Osge Osma Osmanya Pahawh_Hmong Palm Palmyrene Pau_Cin_Hau Pauc Perm Phag Phags_Pa Phli Phlp Phnx Phoenician Plrd Prti Psalter_Pahlavi Qaac Qaai Rejang Rjng Runic Runr Samaritan Samr Sarb Saur Saurashtra Sgnw Sharada Shavian Shaw Shrd Sidd Siddham SignWriting Sind Sinh Sinhala Sora Sora_Sompeng Soyo Soyombo Sund Sundanese Sylo Syloti_Nagri Syrc Syriac Tagalog Tagb Tagbanwa Tai_Le Tai_Tham Tai_Viet Takr Takri Tale Talu Tamil Taml Tang Tangut Tavt Telu Telugu Tfng Tglg Thaa Thaana Thai Tibetan Tibt Tifinagh Tirh Tirhuta Ugar Ugaritic Vai Vaii Wara Warang_Citi Xpeo Xsux Yi Yiii Zanabazar_Square Zanb Zinh Zyyy", "Dogr Dogra Gong Gunjala_Gondi Hanifi_Rohingya Maka Makasar Medefaidrin Medf Old_Sogdian Rohg Sogd Sogdian Sogo", "Elym Elymaic Hmnp Nand Nandinagari Nyiakeng_Puachue_Hmong Wancho Wcho", "Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi", "Cpmn Cypro_Minoan Old_Uyghur Ougr Tangsa Tnsa Toto Vith Vithkuqi", "Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz", "", ""); +const binPropertySets = new DataSet("AHex ASCII ASCII_Hex_Digit Alpha Alphabetic Any Assigned Bidi_C Bidi_Control Bidi_M Bidi_Mirrored CI CWCF CWCM CWKCF CWL CWT CWU Case_Ignorable Cased Changes_When_Casefolded Changes_When_Casemapped Changes_When_Lowercased Changes_When_NFKC_Casefolded Changes_When_Titlecased Changes_When_Uppercased DI Dash Default_Ignorable_Code_Point Dep Deprecated Dia Diacritic Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Ext Extender Gr_Base Gr_Ext Grapheme_Base Grapheme_Extend Hex Hex_Digit IDC IDS IDSB IDST IDS_Binary_Operator IDS_Trinary_Operator ID_Continue ID_Start Ideo Ideographic Join_C Join_Control LOE Logical_Order_Exception Lower Lowercase Math NChar Noncharacter_Code_Point Pat_Syn Pat_WS Pattern_Syntax Pattern_White_Space QMark Quotation_Mark RI Radical Regional_Indicator SD STerm Sentence_Terminal Soft_Dotted Term Terminal_Punctuation UIdeo Unified_Ideograph Upper Uppercase VS Variation_Selector White_Space XIDC XIDS XID_Continue XID_Start space", "Extended_Pictographic", "", "EBase EComp EMod EPres ExtPict", "", "", "", ""); +const binPropertyOfStringsSets = new DataSet("", "", "", "", "", "", "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji RGI_Emoji_Flag_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence", ""); +function isValidUnicodeProperty(version, name, value) { + if (gcNameSet.has(name)) { + return version >= 2018 && gcValueSets.es2018.has(value); + } + if (scNameSet.has(name)) { + return ((version >= 2018 && scValueSets.es2018.has(value)) || + (version >= 2019 && scValueSets.es2019.has(value)) || + (version >= 2020 && scValueSets.es2020.has(value)) || + (version >= 2021 && scValueSets.es2021.has(value)) || + (version >= 2022 && scValueSets.es2022.has(value)) || + (version >= 2023 && scValueSets.es2023.has(value))); + } + return false; +} +function isValidLoneUnicodeProperty(version, value) { + return ((version >= 2018 && binPropertySets.es2018.has(value)) || + (version >= 2019 && binPropertySets.es2019.has(value)) || + (version >= 2021 && binPropertySets.es2021.has(value))); +} +function isValidLoneUnicodePropertyOfString(version, value) { + return version >= 2024 && binPropertyOfStringsSets.es2024.has(value); +} + +const BACKSPACE = 0x08; +const CHARACTER_TABULATION = 0x09; +const LINE_FEED = 0x0a; +const LINE_TABULATION = 0x0b; +const FORM_FEED = 0x0c; +const CARRIAGE_RETURN = 0x0d; +const EXCLAMATION_MARK = 0x21; +const NUMBER_SIGN = 0x23; +const DOLLAR_SIGN = 0x24; +const PERCENT_SIGN = 0x25; +const AMPERSAND = 0x26; +const LEFT_PARENTHESIS = 0x28; +const RIGHT_PARENTHESIS = 0x29; +const ASTERISK = 0x2a; +const PLUS_SIGN = 0x2b; +const COMMA = 0x2c; +const HYPHEN_MINUS = 0x2d; +const FULL_STOP = 0x2e; +const SOLIDUS = 0x2f; +const DIGIT_ZERO = 0x30; +const DIGIT_ONE = 0x31; +const DIGIT_SEVEN = 0x37; +const DIGIT_NINE = 0x39; +const COLON = 0x3a; +const SEMICOLON = 0x3b; +const LESS_THAN_SIGN = 0x3c; +const EQUALS_SIGN = 0x3d; +const GREATER_THAN_SIGN = 0x3e; +const QUESTION_MARK = 0x3f; +const COMMERCIAL_AT = 0x40; +const LATIN_CAPITAL_LETTER_A = 0x41; +const LATIN_CAPITAL_LETTER_B = 0x42; +const LATIN_CAPITAL_LETTER_D = 0x44; +const LATIN_CAPITAL_LETTER_F = 0x46; +const LATIN_CAPITAL_LETTER_P = 0x50; +const LATIN_CAPITAL_LETTER_S = 0x53; +const LATIN_CAPITAL_LETTER_W = 0x57; +const LATIN_CAPITAL_LETTER_Z = 0x5a; +const LOW_LINE = 0x5f; +const LATIN_SMALL_LETTER_A = 0x61; +const LATIN_SMALL_LETTER_B = 0x62; +const LATIN_SMALL_LETTER_C = 0x63; +const LATIN_SMALL_LETTER_D = 0x64; +const LATIN_SMALL_LETTER_F = 0x66; +const LATIN_SMALL_LETTER_G = 0x67; +const LATIN_SMALL_LETTER_I = 0x69; +const LATIN_SMALL_LETTER_K = 0x6b; +const LATIN_SMALL_LETTER_M = 0x6d; +const LATIN_SMALL_LETTER_N = 0x6e; +const LATIN_SMALL_LETTER_P = 0x70; +const LATIN_SMALL_LETTER_Q = 0x71; +const LATIN_SMALL_LETTER_R = 0x72; +const LATIN_SMALL_LETTER_S = 0x73; +const LATIN_SMALL_LETTER_T = 0x74; +const LATIN_SMALL_LETTER_U = 0x75; +const LATIN_SMALL_LETTER_V = 0x76; +const LATIN_SMALL_LETTER_W = 0x77; +const LATIN_SMALL_LETTER_X = 0x78; +const LATIN_SMALL_LETTER_Y = 0x79; +const LATIN_SMALL_LETTER_Z = 0x7a; +const LEFT_SQUARE_BRACKET = 0x5b; +const REVERSE_SOLIDUS = 0x5c; +const RIGHT_SQUARE_BRACKET = 0x5d; +const CIRCUMFLEX_ACCENT = 0x5e; +const GRAVE_ACCENT = 0x60; +const LEFT_CURLY_BRACKET = 0x7b; +const VERTICAL_LINE = 0x7c; +const RIGHT_CURLY_BRACKET = 0x7d; +const TILDE = 0x7e; +const ZERO_WIDTH_NON_JOINER = 0x200c; +const ZERO_WIDTH_JOINER = 0x200d; +const LINE_SEPARATOR = 0x2028; +const PARAGRAPH_SEPARATOR = 0x2029; +const MIN_CODE_POINT = 0x00; +const MAX_CODE_POINT = 0x10ffff; +function isLatinLetter(code) { + return ((code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_Z) || + (code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_Z)); +} +function isDecimalDigit(code) { + return code >= DIGIT_ZERO && code <= DIGIT_NINE; +} +function isOctalDigit(code) { + return code >= DIGIT_ZERO && code <= DIGIT_SEVEN; +} +function isHexDigit(code) { + return ((code >= DIGIT_ZERO && code <= DIGIT_NINE) || + (code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_F) || + (code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_F)); +} +function isLineTerminator(code) { + return (code === LINE_FEED || + code === CARRIAGE_RETURN || + code === LINE_SEPARATOR || + code === PARAGRAPH_SEPARATOR); +} +function isValidUnicode(code) { + return code >= MIN_CODE_POINT && code <= MAX_CODE_POINT; +} +function digitToInt(code) { + if (code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_F) { + return code - LATIN_SMALL_LETTER_A + 10; + } + if (code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_F) { + return code - LATIN_CAPITAL_LETTER_A + 10; + } + return code - DIGIT_ZERO; +} +function isLeadSurrogate(code) { + return code >= 0xd800 && code <= 0xdbff; +} +function isTrailSurrogate(code) { + return code >= 0xdc00 && code <= 0xdfff; +} +function combineSurrogatePair(lead, trail) { + return (lead - 0xd800) * 0x400 + (trail - 0xdc00) + 0x10000; +} + +class GroupSpecifiersAsES2018 { + constructor() { + this.groupName = new Set(); + } + clear() { + this.groupName.clear(); + } + isEmpty() { + return !this.groupName.size; + } + hasInPattern(name) { + return this.groupName.has(name); + } + hasInScope(name) { + return this.hasInPattern(name); + } + addToScope(name) { + this.groupName.add(name); + } + enterDisjunction() { + } + enterAlternative() { + } + leaveDisjunction() { + } +} +class BranchID { + constructor(parent, base) { + this.parent = parent; + this.base = base !== null && base !== void 0 ? base : this; + } + separatedFrom(other) { + var _a, _b; + if (this.base === other.base && this !== other) { + return true; + } + if (other.parent && this.separatedFrom(other.parent)) { + return true; + } + return (_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.separatedFrom(other)) !== null && _b !== void 0 ? _b : false; + } + child() { + return new BranchID(this, null); + } + sibling() { + return new BranchID(this.parent, this.base); + } +} +class GroupSpecifiersAsES2025 { + constructor() { + this.branchID = new BranchID(null, null); + this.groupNames = new Map(); + } + clear() { + this.branchID = new BranchID(null, null); + this.groupNames.clear(); + } + isEmpty() { + return !this.groupNames.size; + } + enterDisjunction() { + this.branchID = this.branchID.child(); + } + enterAlternative(index) { + if (index === 0) { + return; + } + this.branchID = this.branchID.sibling(); + } + leaveDisjunction() { + this.branchID = this.branchID.parent; + } + hasInPattern(name) { + return this.groupNames.has(name); + } + hasInScope(name) { + const branches = this.groupNames.get(name); + if (!branches) { + return false; + } + for (const branch of branches) { + if (!branch.separatedFrom(this.branchID)) { + return true; + } + } + return false; + } + addToScope(name) { + const branches = this.groupNames.get(name); + if (branches) { + branches.push(this.branchID); + return; + } + this.groupNames.set(name, [this.branchID]); + } +} + +const legacyImpl = { + at(s, end, i) { + return i < end ? s.charCodeAt(i) : -1; + }, + width(c) { + return 1; + }, +}; +const unicodeImpl = { + at(s, end, i) { + return i < end ? s.codePointAt(i) : -1; + }, + width(c) { + return c > 0xffff ? 2 : 1; + }, +}; +class Reader { + constructor() { + this._impl = legacyImpl; + this._s = ""; + this._i = 0; + this._end = 0; + this._cp1 = -1; + this._w1 = 1; + this._cp2 = -1; + this._w2 = 1; + this._cp3 = -1; + this._w3 = 1; + this._cp4 = -1; + } + get source() { + return this._s; + } + get index() { + return this._i; + } + get currentCodePoint() { + return this._cp1; + } + get nextCodePoint() { + return this._cp2; + } + get nextCodePoint2() { + return this._cp3; + } + get nextCodePoint3() { + return this._cp4; + } + reset(source, start, end, uFlag) { + this._impl = uFlag ? unicodeImpl : legacyImpl; + this._s = source; + this._end = end; + this.rewind(start); + } + rewind(index) { + const impl = this._impl; + this._i = index; + this._cp1 = impl.at(this._s, this._end, index); + this._w1 = impl.width(this._cp1); + this._cp2 = impl.at(this._s, this._end, index + this._w1); + this._w2 = impl.width(this._cp2); + this._cp3 = impl.at(this._s, this._end, index + this._w1 + this._w2); + this._w3 = impl.width(this._cp3); + this._cp4 = impl.at(this._s, this._end, index + this._w1 + this._w2 + this._w3); + } + advance() { + if (this._cp1 !== -1) { + const impl = this._impl; + this._i += this._w1; + this._cp1 = this._cp2; + this._w1 = this._w2; + this._cp2 = this._cp3; + this._w2 = impl.width(this._cp2); + this._cp3 = this._cp4; + this._w3 = impl.width(this._cp3); + this._cp4 = impl.at(this._s, this._end, this._i + this._w1 + this._w2 + this._w3); + } + } + eat(cp) { + if (this._cp1 === cp) { + this.advance(); + return true; + } + return false; + } + eat2(cp1, cp2) { + if (this._cp1 === cp1 && this._cp2 === cp2) { + this.advance(); + this.advance(); + return true; + } + return false; + } + eat3(cp1, cp2, cp3) { + if (this._cp1 === cp1 && this._cp2 === cp2 && this._cp3 === cp3) { + this.advance(); + this.advance(); + this.advance(); + return true; + } + return false; + } +} + +class RegExpSyntaxError extends SyntaxError { + constructor(message, index) { + super(message); + this.index = index; + } +} +function newRegExpSyntaxError(srcCtx, flags, index, message) { + let source = ""; + if (srcCtx.kind === "literal") { + const literal = srcCtx.source.slice(srcCtx.start, srcCtx.end); + if (literal) { + source = `: ${literal}`; + } + } + else if (srcCtx.kind === "pattern") { + const pattern = srcCtx.source.slice(srcCtx.start, srcCtx.end); + const flagsText = `${flags.unicode ? "u" : ""}${flags.unicodeSets ? "v" : ""}`; + source = `: /${pattern}/${flagsText}`; + } + return new RegExpSyntaxError(`Invalid regular expression${source}: ${message}`, index); +} + +const SYNTAX_CHARACTER = new Set([ + CIRCUMFLEX_ACCENT, + DOLLAR_SIGN, + REVERSE_SOLIDUS, + FULL_STOP, + ASTERISK, + PLUS_SIGN, + QUESTION_MARK, + LEFT_PARENTHESIS, + RIGHT_PARENTHESIS, + LEFT_SQUARE_BRACKET, + RIGHT_SQUARE_BRACKET, + LEFT_CURLY_BRACKET, + RIGHT_CURLY_BRACKET, + VERTICAL_LINE, +]); +const CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR_CHARACTER = new Set([ + AMPERSAND, + EXCLAMATION_MARK, + NUMBER_SIGN, + DOLLAR_SIGN, + PERCENT_SIGN, + ASTERISK, + PLUS_SIGN, + COMMA, + FULL_STOP, + COLON, + SEMICOLON, + LESS_THAN_SIGN, + EQUALS_SIGN, + GREATER_THAN_SIGN, + QUESTION_MARK, + COMMERCIAL_AT, + CIRCUMFLEX_ACCENT, + GRAVE_ACCENT, + TILDE, +]); +const CLASS_SET_SYNTAX_CHARACTER = new Set([ + LEFT_PARENTHESIS, + RIGHT_PARENTHESIS, + LEFT_SQUARE_BRACKET, + RIGHT_SQUARE_BRACKET, + LEFT_CURLY_BRACKET, + RIGHT_CURLY_BRACKET, + SOLIDUS, + HYPHEN_MINUS, + REVERSE_SOLIDUS, + VERTICAL_LINE, +]); +const CLASS_SET_RESERVED_PUNCTUATOR = new Set([ + AMPERSAND, + HYPHEN_MINUS, + EXCLAMATION_MARK, + NUMBER_SIGN, + PERCENT_SIGN, + COMMA, + COLON, + SEMICOLON, + LESS_THAN_SIGN, + EQUALS_SIGN, + GREATER_THAN_SIGN, + COMMERCIAL_AT, + GRAVE_ACCENT, + TILDE, +]); +const FLAG_PROP_TO_CODEPOINT = { + global: LATIN_SMALL_LETTER_G, + ignoreCase: LATIN_SMALL_LETTER_I, + multiline: LATIN_SMALL_LETTER_M, + unicode: LATIN_SMALL_LETTER_U, + sticky: LATIN_SMALL_LETTER_Y, + dotAll: LATIN_SMALL_LETTER_S, + hasIndices: LATIN_SMALL_LETTER_D, + unicodeSets: LATIN_SMALL_LETTER_V, +}; +const FLAG_CODEPOINT_TO_PROP = Object.fromEntries(Object.entries(FLAG_PROP_TO_CODEPOINT).map(([k, v]) => [v, k])); +function isSyntaxCharacter(cp) { + return SYNTAX_CHARACTER.has(cp); +} +function isClassSetReservedDoublePunctuatorCharacter(cp) { + return CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR_CHARACTER.has(cp); +} +function isClassSetSyntaxCharacter(cp) { + return CLASS_SET_SYNTAX_CHARACTER.has(cp); +} +function isClassSetReservedPunctuator(cp) { + return CLASS_SET_RESERVED_PUNCTUATOR.has(cp); +} +function isIdentifierStartChar(cp) { + return isIdStart(cp) || cp === DOLLAR_SIGN || cp === LOW_LINE; +} +function isIdentifierPartChar(cp) { + return (isIdContinue(cp) || + cp === DOLLAR_SIGN || + cp === ZERO_WIDTH_NON_JOINER || + cp === ZERO_WIDTH_JOINER); +} +function isUnicodePropertyNameCharacter(cp) { + return isLatinLetter(cp) || cp === LOW_LINE; +} +function isUnicodePropertyValueCharacter(cp) { + return isUnicodePropertyNameCharacter(cp) || isDecimalDigit(cp); +} +function isRegularExpressionModifier(ch) { + return (ch === LATIN_SMALL_LETTER_I || + ch === LATIN_SMALL_LETTER_M || + ch === LATIN_SMALL_LETTER_S); +} +class RegExpValidator { + constructor(options) { + this._reader = new Reader(); + this._unicodeMode = false; + this._unicodeSetsMode = false; + this._nFlag = false; + this._lastIntValue = 0; + this._lastRange = { + min: 0, + max: Number.POSITIVE_INFINITY, + }; + this._lastStrValue = ""; + this._lastAssertionIsQuantifiable = false; + this._numCapturingParens = 0; + this._backreferenceNames = new Set(); + this._srcCtx = null; + this._options = options !== null && options !== void 0 ? options : {}; + this._groupSpecifiers = + this.ecmaVersion >= 2025 + ? new GroupSpecifiersAsES2025() + : new GroupSpecifiersAsES2018(); + } + validateLiteral(source, start = 0, end = source.length) { + this._srcCtx = { source, start, end, kind: "literal" }; + this._unicodeSetsMode = this._unicodeMode = this._nFlag = false; + this.reset(source, start, end); + this.onLiteralEnter(start); + if (this.eat(SOLIDUS) && this.eatRegExpBody() && this.eat(SOLIDUS)) { + const flagStart = this.index; + const unicode = source.includes("u", flagStart); + const unicodeSets = source.includes("v", flagStart); + this.validateFlagsInternal(source, flagStart, end); + this.validatePatternInternal(source, start + 1, flagStart - 1, { + unicode, + unicodeSets, + }); + } + else if (start >= end) { + this.raise("Empty"); + } + else { + const c = String.fromCodePoint(this.currentCodePoint); + this.raise(`Unexpected character '${c}'`); + } + this.onLiteralLeave(start, end); + } + validateFlags(source, start = 0, end = source.length) { + this._srcCtx = { source, start, end, kind: "flags" }; + this.validateFlagsInternal(source, start, end); + } + validatePattern(source, start = 0, end = source.length, uFlagOrFlags = undefined) { + this._srcCtx = { source, start, end, kind: "pattern" }; + this.validatePatternInternal(source, start, end, uFlagOrFlags); + } + validatePatternInternal(source, start = 0, end = source.length, uFlagOrFlags = undefined) { + const mode = this._parseFlagsOptionToMode(uFlagOrFlags, end); + this._unicodeMode = mode.unicodeMode; + this._nFlag = mode.nFlag; + this._unicodeSetsMode = mode.unicodeSetsMode; + this.reset(source, start, end); + this.consumePattern(); + if (!this._nFlag && + this.ecmaVersion >= 2018 && + !this._groupSpecifiers.isEmpty()) { + this._nFlag = true; + this.rewind(start); + this.consumePattern(); + } + } + validateFlagsInternal(source, start, end) { + const flags = this.parseFlags(source, start, end); + this.onRegExpFlags(start, end, flags); + } + _parseFlagsOptionToMode(uFlagOrFlags, sourceEnd) { + let unicode = false; + let unicodeSets = false; + if (uFlagOrFlags && this.ecmaVersion >= 2015) { + if (typeof uFlagOrFlags === "object") { + unicode = Boolean(uFlagOrFlags.unicode); + if (this.ecmaVersion >= 2024) { + unicodeSets = Boolean(uFlagOrFlags.unicodeSets); + } + } + else { + unicode = uFlagOrFlags; + } + } + if (unicode && unicodeSets) { + this.raise("Invalid regular expression flags", { + index: sourceEnd + 1, + unicode, + unicodeSets, + }); + } + const unicodeMode = unicode || unicodeSets; + const nFlag = (unicode && this.ecmaVersion >= 2018) || + unicodeSets || + Boolean(this._options.strict && this.ecmaVersion >= 2023); + const unicodeSetsMode = unicodeSets; + return { unicodeMode, nFlag, unicodeSetsMode }; + } + get strict() { + return Boolean(this._options.strict) || this._unicodeMode; + } + get ecmaVersion() { + var _a; + return (_a = this._options.ecmaVersion) !== null && _a !== void 0 ? _a : latestEcmaVersion; + } + onLiteralEnter(start) { + if (this._options.onLiteralEnter) { + this._options.onLiteralEnter(start); + } + } + onLiteralLeave(start, end) { + if (this._options.onLiteralLeave) { + this._options.onLiteralLeave(start, end); + } + } + onRegExpFlags(start, end, flags) { + if (this._options.onRegExpFlags) { + this._options.onRegExpFlags(start, end, flags); + } + if (this._options.onFlags) { + this._options.onFlags(start, end, flags.global, flags.ignoreCase, flags.multiline, flags.unicode, flags.sticky, flags.dotAll, flags.hasIndices); + } + } + onPatternEnter(start) { + if (this._options.onPatternEnter) { + this._options.onPatternEnter(start); + } + } + onPatternLeave(start, end) { + if (this._options.onPatternLeave) { + this._options.onPatternLeave(start, end); + } + } + onDisjunctionEnter(start) { + if (this._options.onDisjunctionEnter) { + this._options.onDisjunctionEnter(start); + } + } + onDisjunctionLeave(start, end) { + if (this._options.onDisjunctionLeave) { + this._options.onDisjunctionLeave(start, end); + } + } + onAlternativeEnter(start, index) { + if (this._options.onAlternativeEnter) { + this._options.onAlternativeEnter(start, index); + } + } + onAlternativeLeave(start, end, index) { + if (this._options.onAlternativeLeave) { + this._options.onAlternativeLeave(start, end, index); + } + } + onGroupEnter(start) { + if (this._options.onGroupEnter) { + this._options.onGroupEnter(start); + } + } + onGroupLeave(start, end) { + if (this._options.onGroupLeave) { + this._options.onGroupLeave(start, end); + } + } + onModifiersEnter(start) { + if (this._options.onModifiersEnter) { + this._options.onModifiersEnter(start); + } + } + onModifiersLeave(start, end) { + if (this._options.onModifiersLeave) { + this._options.onModifiersLeave(start, end); + } + } + onAddModifiers(start, end, flags) { + if (this._options.onAddModifiers) { + this._options.onAddModifiers(start, end, flags); + } + } + onRemoveModifiers(start, end, flags) { + if (this._options.onRemoveModifiers) { + this._options.onRemoveModifiers(start, end, flags); + } + } + onCapturingGroupEnter(start, name) { + if (this._options.onCapturingGroupEnter) { + this._options.onCapturingGroupEnter(start, name); + } + } + onCapturingGroupLeave(start, end, name) { + if (this._options.onCapturingGroupLeave) { + this._options.onCapturingGroupLeave(start, end, name); + } + } + onQuantifier(start, end, min, max, greedy) { + if (this._options.onQuantifier) { + this._options.onQuantifier(start, end, min, max, greedy); + } + } + onLookaroundAssertionEnter(start, kind, negate) { + if (this._options.onLookaroundAssertionEnter) { + this._options.onLookaroundAssertionEnter(start, kind, negate); + } + } + onLookaroundAssertionLeave(start, end, kind, negate) { + if (this._options.onLookaroundAssertionLeave) { + this._options.onLookaroundAssertionLeave(start, end, kind, negate); + } + } + onEdgeAssertion(start, end, kind) { + if (this._options.onEdgeAssertion) { + this._options.onEdgeAssertion(start, end, kind); + } + } + onWordBoundaryAssertion(start, end, kind, negate) { + if (this._options.onWordBoundaryAssertion) { + this._options.onWordBoundaryAssertion(start, end, kind, negate); + } + } + onAnyCharacterSet(start, end, kind) { + if (this._options.onAnyCharacterSet) { + this._options.onAnyCharacterSet(start, end, kind); + } + } + onEscapeCharacterSet(start, end, kind, negate) { + if (this._options.onEscapeCharacterSet) { + this._options.onEscapeCharacterSet(start, end, kind, negate); + } + } + onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings) { + if (this._options.onUnicodePropertyCharacterSet) { + this._options.onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings); + } + } + onCharacter(start, end, value) { + if (this._options.onCharacter) { + this._options.onCharacter(start, end, value); + } + } + onBackreference(start, end, ref) { + if (this._options.onBackreference) { + this._options.onBackreference(start, end, ref); + } + } + onCharacterClassEnter(start, negate, unicodeSets) { + if (this._options.onCharacterClassEnter) { + this._options.onCharacterClassEnter(start, negate, unicodeSets); + } + } + onCharacterClassLeave(start, end, negate) { + if (this._options.onCharacterClassLeave) { + this._options.onCharacterClassLeave(start, end, negate); + } + } + onCharacterClassRange(start, end, min, max) { + if (this._options.onCharacterClassRange) { + this._options.onCharacterClassRange(start, end, min, max); + } + } + onClassIntersection(start, end) { + if (this._options.onClassIntersection) { + this._options.onClassIntersection(start, end); + } + } + onClassSubtraction(start, end) { + if (this._options.onClassSubtraction) { + this._options.onClassSubtraction(start, end); + } + } + onClassStringDisjunctionEnter(start) { + if (this._options.onClassStringDisjunctionEnter) { + this._options.onClassStringDisjunctionEnter(start); + } + } + onClassStringDisjunctionLeave(start, end) { + if (this._options.onClassStringDisjunctionLeave) { + this._options.onClassStringDisjunctionLeave(start, end); + } + } + onStringAlternativeEnter(start, index) { + if (this._options.onStringAlternativeEnter) { + this._options.onStringAlternativeEnter(start, index); + } + } + onStringAlternativeLeave(start, end, index) { + if (this._options.onStringAlternativeLeave) { + this._options.onStringAlternativeLeave(start, end, index); + } + } + get index() { + return this._reader.index; + } + get currentCodePoint() { + return this._reader.currentCodePoint; + } + get nextCodePoint() { + return this._reader.nextCodePoint; + } + get nextCodePoint2() { + return this._reader.nextCodePoint2; + } + get nextCodePoint3() { + return this._reader.nextCodePoint3; + } + reset(source, start, end) { + this._reader.reset(source, start, end, this._unicodeMode); + } + rewind(index) { + this._reader.rewind(index); + } + advance() { + this._reader.advance(); + } + eat(cp) { + return this._reader.eat(cp); + } + eat2(cp1, cp2) { + return this._reader.eat2(cp1, cp2); + } + eat3(cp1, cp2, cp3) { + return this._reader.eat3(cp1, cp2, cp3); + } + raise(message, context) { + var _a, _b, _c; + throw newRegExpSyntaxError(this._srcCtx, { + unicode: (_a = context === null || context === void 0 ? void 0 : context.unicode) !== null && _a !== void 0 ? _a : (this._unicodeMode && !this._unicodeSetsMode), + unicodeSets: (_b = context === null || context === void 0 ? void 0 : context.unicodeSets) !== null && _b !== void 0 ? _b : this._unicodeSetsMode, + }, (_c = context === null || context === void 0 ? void 0 : context.index) !== null && _c !== void 0 ? _c : this.index, message); + } + eatRegExpBody() { + const start = this.index; + let inClass = false; + let escaped = false; + for (;;) { + const cp = this.currentCodePoint; + if (cp === -1 || isLineTerminator(cp)) { + const kind = inClass ? "character class" : "regular expression"; + this.raise(`Unterminated ${kind}`); + } + if (escaped) { + escaped = false; + } + else if (cp === REVERSE_SOLIDUS) { + escaped = true; + } + else if (cp === LEFT_SQUARE_BRACKET) { + inClass = true; + } + else if (cp === RIGHT_SQUARE_BRACKET) { + inClass = false; + } + else if ((cp === SOLIDUS && !inClass) || + (cp === ASTERISK && this.index === start)) { + break; + } + this.advance(); + } + return this.index !== start; + } + consumePattern() { + const start = this.index; + this._numCapturingParens = this.countCapturingParens(); + this._groupSpecifiers.clear(); + this._backreferenceNames.clear(); + this.onPatternEnter(start); + this.consumeDisjunction(); + const cp = this.currentCodePoint; + if (this.currentCodePoint !== -1) { + if (cp === RIGHT_PARENTHESIS) { + this.raise("Unmatched ')'"); + } + if (cp === REVERSE_SOLIDUS) { + this.raise("\\ at end of pattern"); + } + if (cp === RIGHT_SQUARE_BRACKET || cp === RIGHT_CURLY_BRACKET) { + this.raise("Lone quantifier brackets"); + } + const c = String.fromCodePoint(cp); + this.raise(`Unexpected character '${c}'`); + } + for (const name of this._backreferenceNames) { + if (!this._groupSpecifiers.hasInPattern(name)) { + this.raise("Invalid named capture referenced"); + } + } + this.onPatternLeave(start, this.index); + } + countCapturingParens() { + const start = this.index; + let inClass = false; + let escaped = false; + let count = 0; + let cp = 0; + while ((cp = this.currentCodePoint) !== -1) { + if (escaped) { + escaped = false; + } + else if (cp === REVERSE_SOLIDUS) { + escaped = true; + } + else if (cp === LEFT_SQUARE_BRACKET) { + inClass = true; + } + else if (cp === RIGHT_SQUARE_BRACKET) { + inClass = false; + } + else if (cp === LEFT_PARENTHESIS && + !inClass && + (this.nextCodePoint !== QUESTION_MARK || + (this.nextCodePoint2 === LESS_THAN_SIGN && + this.nextCodePoint3 !== EQUALS_SIGN && + this.nextCodePoint3 !== EXCLAMATION_MARK))) { + count += 1; + } + this.advance(); + } + this.rewind(start); + return count; + } + consumeDisjunction() { + const start = this.index; + let i = 0; + this._groupSpecifiers.enterDisjunction(); + this.onDisjunctionEnter(start); + do { + this.consumeAlternative(i++); + } while (this.eat(VERTICAL_LINE)); + if (this.consumeQuantifier(true)) { + this.raise("Nothing to repeat"); + } + if (this.eat(LEFT_CURLY_BRACKET)) { + this.raise("Lone quantifier brackets"); + } + this.onDisjunctionLeave(start, this.index); + this._groupSpecifiers.leaveDisjunction(); + } + consumeAlternative(i) { + const start = this.index; + this._groupSpecifiers.enterAlternative(i); + this.onAlternativeEnter(start, i); + while (this.currentCodePoint !== -1 && this.consumeTerm()) { + } + this.onAlternativeLeave(start, this.index, i); + } + consumeTerm() { + if (this._unicodeMode || this.strict) { + return (this.consumeAssertion() || + (this.consumeAtom() && this.consumeOptionalQuantifier())); + } + return ((this.consumeAssertion() && + (!this._lastAssertionIsQuantifiable || + this.consumeOptionalQuantifier())) || + (this.consumeExtendedAtom() && this.consumeOptionalQuantifier())); + } + consumeOptionalQuantifier() { + this.consumeQuantifier(); + return true; + } + consumeAssertion() { + const start = this.index; + this._lastAssertionIsQuantifiable = false; + if (this.eat(CIRCUMFLEX_ACCENT)) { + this.onEdgeAssertion(start, this.index, "start"); + return true; + } + if (this.eat(DOLLAR_SIGN)) { + this.onEdgeAssertion(start, this.index, "end"); + return true; + } + if (this.eat2(REVERSE_SOLIDUS, LATIN_CAPITAL_LETTER_B)) { + this.onWordBoundaryAssertion(start, this.index, "word", true); + return true; + } + if (this.eat2(REVERSE_SOLIDUS, LATIN_SMALL_LETTER_B)) { + this.onWordBoundaryAssertion(start, this.index, "word", false); + return true; + } + if (this.eat2(LEFT_PARENTHESIS, QUESTION_MARK)) { + const lookbehind = this.ecmaVersion >= 2018 && this.eat(LESS_THAN_SIGN); + let negate = false; + if (this.eat(EQUALS_SIGN) || + (negate = this.eat(EXCLAMATION_MARK))) { + const kind = lookbehind ? "lookbehind" : "lookahead"; + this.onLookaroundAssertionEnter(start, kind, negate); + this.consumeDisjunction(); + if (!this.eat(RIGHT_PARENTHESIS)) { + this.raise("Unterminated group"); + } + this._lastAssertionIsQuantifiable = !lookbehind && !this.strict; + this.onLookaroundAssertionLeave(start, this.index, kind, negate); + return true; + } + this.rewind(start); + } + return false; + } + consumeQuantifier(noConsume = false) { + const start = this.index; + let min = 0; + let max = 0; + let greedy = false; + if (this.eat(ASTERISK)) { + min = 0; + max = Number.POSITIVE_INFINITY; + } + else if (this.eat(PLUS_SIGN)) { + min = 1; + max = Number.POSITIVE_INFINITY; + } + else if (this.eat(QUESTION_MARK)) { + min = 0; + max = 1; + } + else if (this.eatBracedQuantifier(noConsume)) { + ({ min, max } = this._lastRange); + } + else { + return false; + } + greedy = !this.eat(QUESTION_MARK); + if (!noConsume) { + this.onQuantifier(start, this.index, min, max, greedy); + } + return true; + } + eatBracedQuantifier(noError) { + const start = this.index; + if (this.eat(LEFT_CURLY_BRACKET)) { + if (this.eatDecimalDigits()) { + const min = this._lastIntValue; + let max = min; + if (this.eat(COMMA)) { + max = this.eatDecimalDigits() + ? this._lastIntValue + : Number.POSITIVE_INFINITY; + } + if (this.eat(RIGHT_CURLY_BRACKET)) { + if (!noError && max < min) { + this.raise("numbers out of order in {} quantifier"); + } + this._lastRange = { min, max }; + return true; + } + } + if (!noError && (this._unicodeMode || this.strict)) { + this.raise("Incomplete quantifier"); + } + this.rewind(start); + } + return false; + } + consumeAtom() { + return (this.consumePatternCharacter() || + this.consumeDot() || + this.consumeReverseSolidusAtomEscape() || + Boolean(this.consumeCharacterClass()) || + this.consumeCapturingGroup() || + this.consumeUncapturingGroup()); + } + consumeDot() { + if (this.eat(FULL_STOP)) { + this.onAnyCharacterSet(this.index - 1, this.index, "any"); + return true; + } + return false; + } + consumeReverseSolidusAtomEscape() { + const start = this.index; + if (this.eat(REVERSE_SOLIDUS)) { + if (this.consumeAtomEscape()) { + return true; + } + this.rewind(start); + } + return false; + } + consumeUncapturingGroup() { + const start = this.index; + if (this.eat2(LEFT_PARENTHESIS, QUESTION_MARK)) { + this.onGroupEnter(start); + if (this.ecmaVersion >= 2025) { + this.consumeModifiers(); + } + if (!this.eat(COLON)) { + this.rewind(start + 1); + this.raise("Invalid group"); + } + this.consumeDisjunction(); + if (!this.eat(RIGHT_PARENTHESIS)) { + this.raise("Unterminated group"); + } + this.onGroupLeave(start, this.index); + return true; + } + return false; + } + consumeModifiers() { + const start = this.index; + const hasAddModifiers = this.eatModifiers(); + const addModifiersEnd = this.index; + const hasHyphen = this.eat(HYPHEN_MINUS); + if (!hasAddModifiers && !hasHyphen) { + return false; + } + this.onModifiersEnter(start); + const addModifiers = this.parseModifiers(start, addModifiersEnd); + this.onAddModifiers(start, addModifiersEnd, addModifiers); + if (hasHyphen) { + const modifiersStart = this.index; + if (!this.eatModifiers() && + !hasAddModifiers && + this.currentCodePoint === COLON) { + this.raise("Invalid empty flags"); + } + const modifiers = this.parseModifiers(modifiersStart, this.index); + for (const [flagName] of Object.entries(modifiers).filter(([, enable]) => enable)) { + if (addModifiers[flagName]) { + this.raise(`Duplicated flag '${String.fromCodePoint(FLAG_PROP_TO_CODEPOINT[flagName])}'`); + } + } + this.onRemoveModifiers(modifiersStart, this.index, modifiers); + } + this.onModifiersLeave(start, this.index); + return true; + } + consumeCapturingGroup() { + const start = this.index; + if (this.eat(LEFT_PARENTHESIS)) { + let name = null; + if (this.ecmaVersion >= 2018) { + if (this.consumeGroupSpecifier()) { + name = this._lastStrValue; + } + else if (this.currentCodePoint === QUESTION_MARK) { + this.rewind(start); + return false; + } + } + else if (this.currentCodePoint === QUESTION_MARK) { + this.rewind(start); + return false; + } + this.onCapturingGroupEnter(start, name); + this.consumeDisjunction(); + if (!this.eat(RIGHT_PARENTHESIS)) { + this.raise("Unterminated group"); + } + this.onCapturingGroupLeave(start, this.index, name); + return true; + } + return false; + } + consumeExtendedAtom() { + return (this.consumeDot() || + this.consumeReverseSolidusAtomEscape() || + this.consumeReverseSolidusFollowedByC() || + Boolean(this.consumeCharacterClass()) || + this.consumeCapturingGroup() || + this.consumeUncapturingGroup() || + this.consumeInvalidBracedQuantifier() || + this.consumeExtendedPatternCharacter()); + } + consumeReverseSolidusFollowedByC() { + const start = this.index; + if (this.currentCodePoint === REVERSE_SOLIDUS && + this.nextCodePoint === LATIN_SMALL_LETTER_C) { + this._lastIntValue = this.currentCodePoint; + this.advance(); + this.onCharacter(start, this.index, REVERSE_SOLIDUS); + return true; + } + return false; + } + consumeInvalidBracedQuantifier() { + if (this.eatBracedQuantifier(true)) { + this.raise("Nothing to repeat"); + } + return false; + } + consumePatternCharacter() { + const start = this.index; + const cp = this.currentCodePoint; + if (cp !== -1 && !isSyntaxCharacter(cp)) { + this.advance(); + this.onCharacter(start, this.index, cp); + return true; + } + return false; + } + consumeExtendedPatternCharacter() { + const start = this.index; + const cp = this.currentCodePoint; + if (cp !== -1 && + cp !== CIRCUMFLEX_ACCENT && + cp !== DOLLAR_SIGN && + cp !== REVERSE_SOLIDUS && + cp !== FULL_STOP && + cp !== ASTERISK && + cp !== PLUS_SIGN && + cp !== QUESTION_MARK && + cp !== LEFT_PARENTHESIS && + cp !== RIGHT_PARENTHESIS && + cp !== LEFT_SQUARE_BRACKET && + cp !== VERTICAL_LINE) { + this.advance(); + this.onCharacter(start, this.index, cp); + return true; + } + return false; + } + consumeGroupSpecifier() { + const start = this.index; + if (this.eat(QUESTION_MARK)) { + if (this.eatGroupName()) { + if (!this._groupSpecifiers.hasInScope(this._lastStrValue)) { + this._groupSpecifiers.addToScope(this._lastStrValue); + return true; + } + this.raise("Duplicate capture group name"); + } + this.rewind(start); + } + return false; + } + consumeAtomEscape() { + if (this.consumeBackreference() || + this.consumeCharacterClassEscape() || + this.consumeCharacterEscape() || + (this._nFlag && this.consumeKGroupName())) { + return true; + } + if (this.strict || this._unicodeMode) { + this.raise("Invalid escape"); + } + return false; + } + consumeBackreference() { + const start = this.index; + if (this.eatDecimalEscape()) { + const n = this._lastIntValue; + if (n <= this._numCapturingParens) { + this.onBackreference(start - 1, this.index, n); + return true; + } + if (this.strict || this._unicodeMode) { + this.raise("Invalid escape"); + } + this.rewind(start); + } + return false; + } + consumeCharacterClassEscape() { + var _a; + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_D)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "digit", false); + return {}; + } + if (this.eat(LATIN_CAPITAL_LETTER_D)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "digit", true); + return {}; + } + if (this.eat(LATIN_SMALL_LETTER_S)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "space", false); + return {}; + } + if (this.eat(LATIN_CAPITAL_LETTER_S)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "space", true); + return {}; + } + if (this.eat(LATIN_SMALL_LETTER_W)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "word", false); + return {}; + } + if (this.eat(LATIN_CAPITAL_LETTER_W)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "word", true); + return {}; + } + let negate = false; + if (this._unicodeMode && + this.ecmaVersion >= 2018 && + (this.eat(LATIN_SMALL_LETTER_P) || + (negate = this.eat(LATIN_CAPITAL_LETTER_P)))) { + this._lastIntValue = -1; + let result = null; + if (this.eat(LEFT_CURLY_BRACKET) && + (result = this.eatUnicodePropertyValueExpression()) && + this.eat(RIGHT_CURLY_BRACKET)) { + if (negate && result.strings) { + this.raise("Invalid property name"); + } + this.onUnicodePropertyCharacterSet(start - 1, this.index, "property", result.key, result.value, negate, (_a = result.strings) !== null && _a !== void 0 ? _a : false); + return { mayContainStrings: result.strings }; + } + this.raise("Invalid property name"); + } + return null; + } + consumeCharacterEscape() { + const start = this.index; + if (this.eatControlEscape() || + this.eatCControlLetter() || + this.eatZero() || + this.eatHexEscapeSequence() || + this.eatRegExpUnicodeEscapeSequence() || + (!this.strict && + !this._unicodeMode && + this.eatLegacyOctalEscapeSequence()) || + this.eatIdentityEscape()) { + this.onCharacter(start - 1, this.index, this._lastIntValue); + return true; + } + return false; + } + consumeKGroupName() { + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_K)) { + if (this.eatGroupName()) { + const groupName = this._lastStrValue; + this._backreferenceNames.add(groupName); + this.onBackreference(start - 1, this.index, groupName); + return true; + } + this.raise("Invalid named reference"); + } + return false; + } + consumeCharacterClass() { + const start = this.index; + if (this.eat(LEFT_SQUARE_BRACKET)) { + const negate = this.eat(CIRCUMFLEX_ACCENT); + this.onCharacterClassEnter(start, negate, this._unicodeSetsMode); + const result = this.consumeClassContents(); + if (!this.eat(RIGHT_SQUARE_BRACKET)) { + if (this.currentCodePoint === -1) { + this.raise("Unterminated character class"); + } + this.raise("Invalid character in character class"); + } + if (negate && result.mayContainStrings) { + this.raise("Negated character class may contain strings"); + } + this.onCharacterClassLeave(start, this.index, negate); + return result; + } + return null; + } + consumeClassContents() { + if (this._unicodeSetsMode) { + if (this.currentCodePoint === RIGHT_SQUARE_BRACKET) { + return {}; + } + const result = this.consumeClassSetExpression(); + return result; + } + const strict = this.strict || this._unicodeMode; + for (;;) { + const rangeStart = this.index; + if (!this.consumeClassAtom()) { + break; + } + const min = this._lastIntValue; + if (!this.eat(HYPHEN_MINUS)) { + continue; + } + this.onCharacter(this.index - 1, this.index, HYPHEN_MINUS); + if (!this.consumeClassAtom()) { + break; + } + const max = this._lastIntValue; + if (min === -1 || max === -1) { + if (strict) { + this.raise("Invalid character class"); + } + continue; + } + if (min > max) { + this.raise("Range out of order in character class"); + } + this.onCharacterClassRange(rangeStart, this.index, min, max); + } + return {}; + } + consumeClassAtom() { + const start = this.index; + const cp = this.currentCodePoint; + if (cp !== -1 && + cp !== REVERSE_SOLIDUS && + cp !== RIGHT_SQUARE_BRACKET) { + this.advance(); + this._lastIntValue = cp; + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + if (this.eat(REVERSE_SOLIDUS)) { + if (this.consumeClassEscape()) { + return true; + } + if (!this.strict && + this.currentCodePoint === LATIN_SMALL_LETTER_C) { + this._lastIntValue = REVERSE_SOLIDUS; + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + if (this.strict || this._unicodeMode) { + this.raise("Invalid escape"); + } + this.rewind(start); + } + return false; + } + consumeClassEscape() { + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_B)) { + this._lastIntValue = BACKSPACE; + this.onCharacter(start - 1, this.index, this._lastIntValue); + return true; + } + if (this._unicodeMode && this.eat(HYPHEN_MINUS)) { + this._lastIntValue = HYPHEN_MINUS; + this.onCharacter(start - 1, this.index, this._lastIntValue); + return true; + } + let cp = 0; + if (!this.strict && + !this._unicodeMode && + this.currentCodePoint === LATIN_SMALL_LETTER_C && + (isDecimalDigit((cp = this.nextCodePoint)) || cp === LOW_LINE)) { + this.advance(); + this.advance(); + this._lastIntValue = cp % 0x20; + this.onCharacter(start - 1, this.index, this._lastIntValue); + return true; + } + return (Boolean(this.consumeCharacterClassEscape()) || + this.consumeCharacterEscape()); + } + consumeClassSetExpression() { + const start = this.index; + let mayContainStrings = false; + let result = null; + if (this.consumeClassSetCharacter()) { + if (this.consumeClassSetRangeFromOperator(start)) { + this.consumeClassUnionRight({}); + return {}; + } + mayContainStrings = false; + } + else if ((result = this.consumeClassSetOperand())) { + mayContainStrings = result.mayContainStrings; + } + else { + const cp = this.currentCodePoint; + if (cp === REVERSE_SOLIDUS) { + this.advance(); + this.raise("Invalid escape"); + } + if (cp === this.nextCodePoint && + isClassSetReservedDoublePunctuatorCharacter(cp)) { + this.raise("Invalid set operation in character class"); + } + this.raise("Invalid character in character class"); + } + if (this.eat2(AMPERSAND, AMPERSAND)) { + while (this.currentCodePoint !== AMPERSAND && + (result = this.consumeClassSetOperand())) { + this.onClassIntersection(start, this.index); + if (!result.mayContainStrings) { + mayContainStrings = false; + } + if (this.eat2(AMPERSAND, AMPERSAND)) { + continue; + } + return { mayContainStrings }; + } + this.raise("Invalid character in character class"); + } + if (this.eat2(HYPHEN_MINUS, HYPHEN_MINUS)) { + while (this.consumeClassSetOperand()) { + this.onClassSubtraction(start, this.index); + if (this.eat2(HYPHEN_MINUS, HYPHEN_MINUS)) { + continue; + } + return { mayContainStrings }; + } + this.raise("Invalid character in character class"); + } + return this.consumeClassUnionRight({ mayContainStrings }); + } + consumeClassUnionRight(leftResult) { + let mayContainStrings = leftResult.mayContainStrings; + for (;;) { + const start = this.index; + if (this.consumeClassSetCharacter()) { + this.consumeClassSetRangeFromOperator(start); + continue; + } + const result = this.consumeClassSetOperand(); + if (result) { + if (result.mayContainStrings) { + mayContainStrings = true; + } + continue; + } + break; + } + return { mayContainStrings }; + } + consumeClassSetRangeFromOperator(start) { + const currentStart = this.index; + const min = this._lastIntValue; + if (this.eat(HYPHEN_MINUS)) { + if (this.consumeClassSetCharacter()) { + const max = this._lastIntValue; + if (min === -1 || max === -1) { + this.raise("Invalid character class"); + } + if (min > max) { + this.raise("Range out of order in character class"); + } + this.onCharacterClassRange(start, this.index, min, max); + return true; + } + this.rewind(currentStart); + } + return false; + } + consumeClassSetOperand() { + let result = null; + if ((result = this.consumeNestedClass())) { + return result; + } + if ((result = this.consumeClassStringDisjunction())) { + return result; + } + if (this.consumeClassSetCharacter()) { + return {}; + } + return null; + } + consumeNestedClass() { + const start = this.index; + if (this.eat(LEFT_SQUARE_BRACKET)) { + const negate = this.eat(CIRCUMFLEX_ACCENT); + this.onCharacterClassEnter(start, negate, true); + const result = this.consumeClassContents(); + if (!this.eat(RIGHT_SQUARE_BRACKET)) { + this.raise("Unterminated character class"); + } + if (negate && result.mayContainStrings) { + this.raise("Negated character class may contain strings"); + } + this.onCharacterClassLeave(start, this.index, negate); + return result; + } + if (this.eat(REVERSE_SOLIDUS)) { + const result = this.consumeCharacterClassEscape(); + if (result) { + return result; + } + this.rewind(start); + } + return null; + } + consumeClassStringDisjunction() { + const start = this.index; + if (this.eat3(REVERSE_SOLIDUS, LATIN_SMALL_LETTER_Q, LEFT_CURLY_BRACKET)) { + this.onClassStringDisjunctionEnter(start); + let i = 0; + let mayContainStrings = false; + do { + if (this.consumeClassString(i++).mayContainStrings) { + mayContainStrings = true; + } + } while (this.eat(VERTICAL_LINE)); + if (this.eat(RIGHT_CURLY_BRACKET)) { + this.onClassStringDisjunctionLeave(start, this.index); + return { mayContainStrings }; + } + this.raise("Unterminated class string disjunction"); + } + return null; + } + consumeClassString(i) { + const start = this.index; + let count = 0; + this.onStringAlternativeEnter(start, i); + while (this.currentCodePoint !== -1 && + this.consumeClassSetCharacter()) { + count++; + } + this.onStringAlternativeLeave(start, this.index, i); + return { mayContainStrings: count !== 1 }; + } + consumeClassSetCharacter() { + const start = this.index; + const cp = this.currentCodePoint; + if (cp !== this.nextCodePoint || + !isClassSetReservedDoublePunctuatorCharacter(cp)) { + if (cp !== -1 && !isClassSetSyntaxCharacter(cp)) { + this._lastIntValue = cp; + this.advance(); + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + } + if (this.eat(REVERSE_SOLIDUS)) { + if (this.consumeCharacterEscape()) { + return true; + } + if (isClassSetReservedPunctuator(this.currentCodePoint)) { + this._lastIntValue = this.currentCodePoint; + this.advance(); + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + if (this.eat(LATIN_SMALL_LETTER_B)) { + this._lastIntValue = BACKSPACE; + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + this.rewind(start); + } + return false; + } + eatGroupName() { + if (this.eat(LESS_THAN_SIGN)) { + if (this.eatRegExpIdentifierName() && this.eat(GREATER_THAN_SIGN)) { + return true; + } + this.raise("Invalid capture group name"); + } + return false; + } + eatRegExpIdentifierName() { + if (this.eatRegExpIdentifierStart()) { + this._lastStrValue = String.fromCodePoint(this._lastIntValue); + while (this.eatRegExpIdentifierPart()) { + this._lastStrValue += String.fromCodePoint(this._lastIntValue); + } + return true; + } + return false; + } + eatRegExpIdentifierStart() { + const start = this.index; + const forceUFlag = !this._unicodeMode && this.ecmaVersion >= 2020; + let cp = this.currentCodePoint; + this.advance(); + if (cp === REVERSE_SOLIDUS && + this.eatRegExpUnicodeEscapeSequence(forceUFlag)) { + cp = this._lastIntValue; + } + else if (forceUFlag && + isLeadSurrogate(cp) && + isTrailSurrogate(this.currentCodePoint)) { + cp = combineSurrogatePair(cp, this.currentCodePoint); + this.advance(); + } + if (isIdentifierStartChar(cp)) { + this._lastIntValue = cp; + return true; + } + if (this.index !== start) { + this.rewind(start); + } + return false; + } + eatRegExpIdentifierPart() { + const start = this.index; + const forceUFlag = !this._unicodeMode && this.ecmaVersion >= 2020; + let cp = this.currentCodePoint; + this.advance(); + if (cp === REVERSE_SOLIDUS && + this.eatRegExpUnicodeEscapeSequence(forceUFlag)) { + cp = this._lastIntValue; + } + else if (forceUFlag && + isLeadSurrogate(cp) && + isTrailSurrogate(this.currentCodePoint)) { + cp = combineSurrogatePair(cp, this.currentCodePoint); + this.advance(); + } + if (isIdentifierPartChar(cp)) { + this._lastIntValue = cp; + return true; + } + if (this.index !== start) { + this.rewind(start); + } + return false; + } + eatCControlLetter() { + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_C)) { + if (this.eatControlLetter()) { + return true; + } + this.rewind(start); + } + return false; + } + eatZero() { + if (this.currentCodePoint === DIGIT_ZERO && + !isDecimalDigit(this.nextCodePoint)) { + this._lastIntValue = 0; + this.advance(); + return true; + } + return false; + } + eatControlEscape() { + if (this.eat(LATIN_SMALL_LETTER_F)) { + this._lastIntValue = FORM_FEED; + return true; + } + if (this.eat(LATIN_SMALL_LETTER_N)) { + this._lastIntValue = LINE_FEED; + return true; + } + if (this.eat(LATIN_SMALL_LETTER_R)) { + this._lastIntValue = CARRIAGE_RETURN; + return true; + } + if (this.eat(LATIN_SMALL_LETTER_T)) { + this._lastIntValue = CHARACTER_TABULATION; + return true; + } + if (this.eat(LATIN_SMALL_LETTER_V)) { + this._lastIntValue = LINE_TABULATION; + return true; + } + return false; + } + eatControlLetter() { + const cp = this.currentCodePoint; + if (isLatinLetter(cp)) { + this.advance(); + this._lastIntValue = cp % 0x20; + return true; + } + return false; + } + eatRegExpUnicodeEscapeSequence(forceUFlag = false) { + const start = this.index; + const uFlag = forceUFlag || this._unicodeMode; + if (this.eat(LATIN_SMALL_LETTER_U)) { + if ((uFlag && this.eatRegExpUnicodeSurrogatePairEscape()) || + this.eatFixedHexDigits(4) || + (uFlag && this.eatRegExpUnicodeCodePointEscape())) { + return true; + } + if (this.strict || uFlag) { + this.raise("Invalid unicode escape"); + } + this.rewind(start); + } + return false; + } + eatRegExpUnicodeSurrogatePairEscape() { + const start = this.index; + if (this.eatFixedHexDigits(4)) { + const lead = this._lastIntValue; + if (isLeadSurrogate(lead) && + this.eat(REVERSE_SOLIDUS) && + this.eat(LATIN_SMALL_LETTER_U) && + this.eatFixedHexDigits(4)) { + const trail = this._lastIntValue; + if (isTrailSurrogate(trail)) { + this._lastIntValue = combineSurrogatePair(lead, trail); + return true; + } + } + this.rewind(start); + } + return false; + } + eatRegExpUnicodeCodePointEscape() { + const start = this.index; + if (this.eat(LEFT_CURLY_BRACKET) && + this.eatHexDigits() && + this.eat(RIGHT_CURLY_BRACKET) && + isValidUnicode(this._lastIntValue)) { + return true; + } + this.rewind(start); + return false; + } + eatIdentityEscape() { + const cp = this.currentCodePoint; + if (this.isValidIdentityEscape(cp)) { + this._lastIntValue = cp; + this.advance(); + return true; + } + return false; + } + isValidIdentityEscape(cp) { + if (cp === -1) { + return false; + } + if (this._unicodeMode) { + return isSyntaxCharacter(cp) || cp === SOLIDUS; + } + if (this.strict) { + return !isIdContinue(cp); + } + if (this._nFlag) { + return !(cp === LATIN_SMALL_LETTER_C || cp === LATIN_SMALL_LETTER_K); + } + return cp !== LATIN_SMALL_LETTER_C; + } + eatDecimalEscape() { + this._lastIntValue = 0; + let cp = this.currentCodePoint; + if (cp >= DIGIT_ONE && cp <= DIGIT_NINE) { + do { + this._lastIntValue = 10 * this._lastIntValue + (cp - DIGIT_ZERO); + this.advance(); + } while ((cp = this.currentCodePoint) >= DIGIT_ZERO && + cp <= DIGIT_NINE); + return true; + } + return false; + } + eatUnicodePropertyValueExpression() { + const start = this.index; + if (this.eatUnicodePropertyName() && this.eat(EQUALS_SIGN)) { + const key = this._lastStrValue; + if (this.eatUnicodePropertyValue()) { + const value = this._lastStrValue; + if (isValidUnicodeProperty(this.ecmaVersion, key, value)) { + return { + key, + value: value || null, + }; + } + this.raise("Invalid property name"); + } + } + this.rewind(start); + if (this.eatLoneUnicodePropertyNameOrValue()) { + const nameOrValue = this._lastStrValue; + if (isValidUnicodeProperty(this.ecmaVersion, "General_Category", nameOrValue)) { + return { + key: "General_Category", + value: nameOrValue || null, + }; + } + if (isValidLoneUnicodeProperty(this.ecmaVersion, nameOrValue)) { + return { + key: nameOrValue, + value: null, + }; + } + if (this._unicodeSetsMode && + isValidLoneUnicodePropertyOfString(this.ecmaVersion, nameOrValue)) { + return { + key: nameOrValue, + value: null, + strings: true, + }; + } + this.raise("Invalid property name"); + } + return null; + } + eatUnicodePropertyName() { + this._lastStrValue = ""; + while (isUnicodePropertyNameCharacter(this.currentCodePoint)) { + this._lastStrValue += String.fromCodePoint(this.currentCodePoint); + this.advance(); + } + return this._lastStrValue !== ""; + } + eatUnicodePropertyValue() { + this._lastStrValue = ""; + while (isUnicodePropertyValueCharacter(this.currentCodePoint)) { + this._lastStrValue += String.fromCodePoint(this.currentCodePoint); + this.advance(); + } + return this._lastStrValue !== ""; + } + eatLoneUnicodePropertyNameOrValue() { + return this.eatUnicodePropertyValue(); + } + eatHexEscapeSequence() { + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_X)) { + if (this.eatFixedHexDigits(2)) { + return true; + } + if (this._unicodeMode || this.strict) { + this.raise("Invalid escape"); + } + this.rewind(start); + } + return false; + } + eatDecimalDigits() { + const start = this.index; + this._lastIntValue = 0; + while (isDecimalDigit(this.currentCodePoint)) { + this._lastIntValue = + 10 * this._lastIntValue + digitToInt(this.currentCodePoint); + this.advance(); + } + return this.index !== start; + } + eatHexDigits() { + const start = this.index; + this._lastIntValue = 0; + while (isHexDigit(this.currentCodePoint)) { + this._lastIntValue = + 16 * this._lastIntValue + digitToInt(this.currentCodePoint); + this.advance(); + } + return this.index !== start; + } + eatLegacyOctalEscapeSequence() { + if (this.eatOctalDigit()) { + const n1 = this._lastIntValue; + if (this.eatOctalDigit()) { + const n2 = this._lastIntValue; + if (n1 <= 3 && this.eatOctalDigit()) { + this._lastIntValue = n1 * 64 + n2 * 8 + this._lastIntValue; + } + else { + this._lastIntValue = n1 * 8 + n2; + } + } + else { + this._lastIntValue = n1; + } + return true; + } + return false; + } + eatOctalDigit() { + const cp = this.currentCodePoint; + if (isOctalDigit(cp)) { + this.advance(); + this._lastIntValue = cp - DIGIT_ZERO; + return true; + } + this._lastIntValue = 0; + return false; + } + eatFixedHexDigits(length) { + const start = this.index; + this._lastIntValue = 0; + for (let i = 0; i < length; ++i) { + const cp = this.currentCodePoint; + if (!isHexDigit(cp)) { + this.rewind(start); + return false; + } + this._lastIntValue = 16 * this._lastIntValue + digitToInt(cp); + this.advance(); + } + return true; + } + eatModifiers() { + let ate = false; + while (isRegularExpressionModifier(this.currentCodePoint)) { + this.advance(); + ate = true; + } + return ate; + } + parseModifiers(start, end) { + const { ignoreCase, multiline, dotAll } = this.parseFlags(this._reader.source, start, end); + return { ignoreCase, multiline, dotAll }; + } + parseFlags(source, start, end) { + const flags = { + global: false, + ignoreCase: false, + multiline: false, + unicode: false, + sticky: false, + dotAll: false, + hasIndices: false, + unicodeSets: false, + }; + const validFlags = new Set(); + validFlags.add(LATIN_SMALL_LETTER_G); + validFlags.add(LATIN_SMALL_LETTER_I); + validFlags.add(LATIN_SMALL_LETTER_M); + if (this.ecmaVersion >= 2015) { + validFlags.add(LATIN_SMALL_LETTER_U); + validFlags.add(LATIN_SMALL_LETTER_Y); + if (this.ecmaVersion >= 2018) { + validFlags.add(LATIN_SMALL_LETTER_S); + if (this.ecmaVersion >= 2022) { + validFlags.add(LATIN_SMALL_LETTER_D); + if (this.ecmaVersion >= 2024) { + validFlags.add(LATIN_SMALL_LETTER_V); + } + } + } + } + for (let i = start; i < end; ++i) { + const flag = source.charCodeAt(i); + if (validFlags.has(flag)) { + const prop = FLAG_CODEPOINT_TO_PROP[flag]; + if (flags[prop]) { + this.raise(`Duplicated flag '${source[i]}'`, { + index: start, + }); + } + flags[prop] = true; + } + else { + this.raise(`Invalid flag '${source[i]}'`, { index: start }); + } + } + return flags; + } +} + +const DUMMY_PATTERN = {}; +const DUMMY_FLAGS = {}; +const DUMMY_CAPTURING_GROUP = {}; +function isClassSetOperand(node) { + return (node.type === "Character" || + node.type === "CharacterSet" || + node.type === "CharacterClass" || + node.type === "ExpressionCharacterClass" || + node.type === "ClassStringDisjunction"); +} +class RegExpParserState { + constructor(options) { + var _a; + this._node = DUMMY_PATTERN; + this._expressionBufferMap = new Map(); + this._flags = DUMMY_FLAGS; + this._backreferences = []; + this._capturingGroups = []; + this.source = ""; + this.strict = Boolean(options === null || options === void 0 ? void 0 : options.strict); + this.ecmaVersion = (_a = options === null || options === void 0 ? void 0 : options.ecmaVersion) !== null && _a !== void 0 ? _a : latestEcmaVersion; + } + get pattern() { + if (this._node.type !== "Pattern") { + throw new Error("UnknownError"); + } + return this._node; + } + get flags() { + if (this._flags.type !== "Flags") { + throw new Error("UnknownError"); + } + return this._flags; + } + onRegExpFlags(start, end, { global, ignoreCase, multiline, unicode, sticky, dotAll, hasIndices, unicodeSets, }) { + this._flags = { + type: "Flags", + parent: null, + start, + end, + raw: this.source.slice(start, end), + global, + ignoreCase, + multiline, + unicode, + sticky, + dotAll, + hasIndices, + unicodeSets, + }; + } + onPatternEnter(start) { + this._node = { + type: "Pattern", + parent: null, + start, + end: start, + raw: "", + alternatives: [], + }; + this._backreferences.length = 0; + this._capturingGroups.length = 0; + } + onPatternLeave(start, end) { + this._node.end = end; + this._node.raw = this.source.slice(start, end); + for (const reference of this._backreferences) { + const ref = reference.ref; + const groups = typeof ref === "number" + ? [this._capturingGroups[ref - 1]] + : this._capturingGroups.filter((g) => g.name === ref); + if (groups.length === 1) { + const group = groups[0]; + reference.ambiguous = false; + reference.resolved = group; + } + else { + reference.ambiguous = true; + reference.resolved = groups; + } + for (const group of groups) { + group.references.push(reference); + } + } + } + onAlternativeEnter(start) { + const parent = this._node; + if (parent.type !== "Assertion" && + parent.type !== "CapturingGroup" && + parent.type !== "Group" && + parent.type !== "Pattern") { + throw new Error("UnknownError"); + } + this._node = { + type: "Alternative", + parent, + start, + end: start, + raw: "", + elements: [], + }; + parent.alternatives.push(this._node); + } + onAlternativeLeave(start, end) { + const node = this._node; + if (node.type !== "Alternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onGroupEnter(start) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + const group = { + type: "Group", + parent, + start, + end: start, + raw: "", + modifiers: null, + alternatives: [], + }; + this._node = group; + parent.elements.push(this._node); + } + onGroupLeave(start, end) { + const node = this._node; + if (node.type !== "Group" || node.parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onModifiersEnter(start) { + const parent = this._node; + if (parent.type !== "Group") { + throw new Error("UnknownError"); + } + this._node = { + type: "Modifiers", + parent, + start, + end: start, + raw: "", + add: null, + remove: null, + }; + parent.modifiers = this._node; + } + onModifiersLeave(start, end) { + const node = this._node; + if (node.type !== "Modifiers" || node.parent.type !== "Group") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onAddModifiers(start, end, { ignoreCase, multiline, dotAll, }) { + const parent = this._node; + if (parent.type !== "Modifiers") { + throw new Error("UnknownError"); + } + parent.add = { + type: "ModifierFlags", + parent, + start, + end, + raw: this.source.slice(start, end), + ignoreCase, + multiline, + dotAll, + }; + } + onRemoveModifiers(start, end, { ignoreCase, multiline, dotAll, }) { + const parent = this._node; + if (parent.type !== "Modifiers") { + throw new Error("UnknownError"); + } + parent.remove = { + type: "ModifierFlags", + parent, + start, + end, + raw: this.source.slice(start, end), + ignoreCase, + multiline, + dotAll, + }; + } + onCapturingGroupEnter(start, name) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + this._node = { + type: "CapturingGroup", + parent, + start, + end: start, + raw: "", + name, + alternatives: [], + references: [], + }; + parent.elements.push(this._node); + this._capturingGroups.push(this._node); + } + onCapturingGroupLeave(start, end) { + const node = this._node; + if (node.type !== "CapturingGroup" || + node.parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onQuantifier(start, end, min, max, greedy) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + const element = parent.elements.pop(); + if (element == null || + element.type === "Quantifier" || + (element.type === "Assertion" && element.kind !== "lookahead")) { + throw new Error("UnknownError"); + } + const node = { + type: "Quantifier", + parent, + start: element.start, + end, + raw: this.source.slice(element.start, end), + min, + max, + greedy, + element, + }; + parent.elements.push(node); + element.parent = node; + } + onLookaroundAssertionEnter(start, kind, negate) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + const node = (this._node = { + type: "Assertion", + parent, + start, + end: start, + raw: "", + kind, + negate, + alternatives: [], + }); + parent.elements.push(node); + } + onLookaroundAssertionLeave(start, end) { + const node = this._node; + if (node.type !== "Assertion" || node.parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onEdgeAssertion(start, end, kind) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "Assertion", + parent, + start, + end, + raw: this.source.slice(start, end), + kind, + }); + } + onWordBoundaryAssertion(start, end, kind, negate) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "Assertion", + parent, + start, + end, + raw: this.source.slice(start, end), + kind, + negate, + }); + } + onAnyCharacterSet(start, end, kind) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "CharacterSet", + parent, + start, + end, + raw: this.source.slice(start, end), + kind, + }); + } + onEscapeCharacterSet(start, end, kind, negate) { + const parent = this._node; + if (parent.type !== "Alternative" && parent.type !== "CharacterClass") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "CharacterSet", + parent, + start, + end, + raw: this.source.slice(start, end), + kind, + negate, + }); + } + onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings) { + const parent = this._node; + if (parent.type !== "Alternative" && parent.type !== "CharacterClass") { + throw new Error("UnknownError"); + } + const base = { + type: "CharacterSet", + parent: null, + start, + end, + raw: this.source.slice(start, end), + kind, + strings: null, + key, + }; + if (strings) { + if ((parent.type === "CharacterClass" && !parent.unicodeSets) || + negate || + value !== null) { + throw new Error("UnknownError"); + } + parent.elements.push(Object.assign(Object.assign({}, base), { parent, strings, value, negate })); + } + else { + parent.elements.push(Object.assign(Object.assign({}, base), { parent, strings, value, negate })); + } + } + onCharacter(start, end, value) { + const parent = this._node; + if (parent.type !== "Alternative" && + parent.type !== "CharacterClass" && + parent.type !== "StringAlternative") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "Character", + parent, + start, + end, + raw: this.source.slice(start, end), + value, + }); + } + onBackreference(start, end, ref) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + const node = { + type: "Backreference", + parent, + start, + end, + raw: this.source.slice(start, end), + ref, + ambiguous: false, + resolved: DUMMY_CAPTURING_GROUP, + }; + parent.elements.push(node); + this._backreferences.push(node); + } + onCharacterClassEnter(start, negate, unicodeSets) { + const parent = this._node; + const base = { + type: "CharacterClass", + parent, + start, + end: start, + raw: "", + unicodeSets, + negate, + elements: [], + }; + if (parent.type === "Alternative") { + const node = Object.assign(Object.assign({}, base), { parent }); + this._node = node; + parent.elements.push(node); + } + else if (parent.type === "CharacterClass" && + parent.unicodeSets && + unicodeSets) { + const node = Object.assign(Object.assign({}, base), { parent, + unicodeSets }); + this._node = node; + parent.elements.push(node); + } + else { + throw new Error("UnknownError"); + } + } + onCharacterClassLeave(start, end) { + const node = this._node; + if (node.type !== "CharacterClass" || + (node.parent.type !== "Alternative" && + node.parent.type !== "CharacterClass")) { + throw new Error("UnknownError"); + } + const parent = node.parent; + node.end = end; + node.raw = this.source.slice(start, end); + this._node = parent; + const expression = this._expressionBufferMap.get(node); + if (!expression) { + return; + } + if (node.elements.length > 0) { + throw new Error("UnknownError"); + } + this._expressionBufferMap.delete(node); + const newNode = { + type: "ExpressionCharacterClass", + parent, + start: node.start, + end: node.end, + raw: node.raw, + negate: node.negate, + expression, + }; + expression.parent = newNode; + if (node !== parent.elements.pop()) { + throw new Error("UnknownError"); + } + parent.elements.push(newNode); + } + onCharacterClassRange(start, end) { + const parent = this._node; + if (parent.type !== "CharacterClass") { + throw new Error("UnknownError"); + } + const elements = parent.elements; + const max = elements.pop(); + if (!max || max.type !== "Character") { + throw new Error("UnknownError"); + } + if (!parent.unicodeSets) { + const hyphen = elements.pop(); + if (!hyphen || + hyphen.type !== "Character" || + hyphen.value !== HYPHEN_MINUS) { + throw new Error("UnknownError"); + } + } + const min = elements.pop(); + if (!min || min.type !== "Character") { + throw new Error("UnknownError"); + } + const node = { + type: "CharacterClassRange", + parent, + start, + end, + raw: this.source.slice(start, end), + min, + max, + }; + min.parent = node; + max.parent = node; + elements.push(node); + } + onClassIntersection(start, end) { + var _a; + const parent = this._node; + if (parent.type !== "CharacterClass" || !parent.unicodeSets) { + throw new Error("UnknownError"); + } + const right = parent.elements.pop(); + const left = (_a = this._expressionBufferMap.get(parent)) !== null && _a !== void 0 ? _a : parent.elements.pop(); + if (!left || + !right || + left.type === "ClassSubtraction" || + (left.type !== "ClassIntersection" && !isClassSetOperand(left)) || + !isClassSetOperand(right)) { + throw new Error("UnknownError"); + } + const node = { + type: "ClassIntersection", + parent: parent, + start, + end, + raw: this.source.slice(start, end), + left, + right, + }; + left.parent = node; + right.parent = node; + this._expressionBufferMap.set(parent, node); + } + onClassSubtraction(start, end) { + var _a; + const parent = this._node; + if (parent.type !== "CharacterClass" || !parent.unicodeSets) { + throw new Error("UnknownError"); + } + const right = parent.elements.pop(); + const left = (_a = this._expressionBufferMap.get(parent)) !== null && _a !== void 0 ? _a : parent.elements.pop(); + if (!left || + !right || + left.type === "ClassIntersection" || + (left.type !== "ClassSubtraction" && !isClassSetOperand(left)) || + !isClassSetOperand(right)) { + throw new Error("UnknownError"); + } + const node = { + type: "ClassSubtraction", + parent: parent, + start, + end, + raw: this.source.slice(start, end), + left, + right, + }; + left.parent = node; + right.parent = node; + this._expressionBufferMap.set(parent, node); + } + onClassStringDisjunctionEnter(start) { + const parent = this._node; + if (parent.type !== "CharacterClass" || !parent.unicodeSets) { + throw new Error("UnknownError"); + } + this._node = { + type: "ClassStringDisjunction", + parent, + start, + end: start, + raw: "", + alternatives: [], + }; + parent.elements.push(this._node); + } + onClassStringDisjunctionLeave(start, end) { + const node = this._node; + if (node.type !== "ClassStringDisjunction" || + node.parent.type !== "CharacterClass") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onStringAlternativeEnter(start) { + const parent = this._node; + if (parent.type !== "ClassStringDisjunction") { + throw new Error("UnknownError"); + } + this._node = { + type: "StringAlternative", + parent, + start, + end: start, + raw: "", + elements: [], + }; + parent.alternatives.push(this._node); + } + onStringAlternativeLeave(start, end) { + const node = this._node; + if (node.type !== "StringAlternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } +} +class RegExpParser { + constructor(options) { + this._state = new RegExpParserState(options); + this._validator = new RegExpValidator(this._state); + } + parseLiteral(source, start = 0, end = source.length) { + this._state.source = source; + this._validator.validateLiteral(source, start, end); + const pattern = this._state.pattern; + const flags = this._state.flags; + const literal = { + type: "RegExpLiteral", + parent: null, + start, + end, + raw: source, + pattern, + flags, + }; + pattern.parent = literal; + flags.parent = literal; + return literal; + } + parseFlags(source, start = 0, end = source.length) { + this._state.source = source; + this._validator.validateFlags(source, start, end); + return this._state.flags; + } + parsePattern(source, start = 0, end = source.length, uFlagOrFlags = undefined) { + this._state.source = source; + this._validator.validatePattern(source, start, end, uFlagOrFlags); + return this._state.pattern; + } +} + +class RegExpVisitor { + constructor(handlers) { + this._handlers = handlers; + } + visit(node) { + switch (node.type) { + case "Alternative": + this.visitAlternative(node); + break; + case "Assertion": + this.visitAssertion(node); + break; + case "Backreference": + this.visitBackreference(node); + break; + case "CapturingGroup": + this.visitCapturingGroup(node); + break; + case "Character": + this.visitCharacter(node); + break; + case "CharacterClass": + this.visitCharacterClass(node); + break; + case "CharacterClassRange": + this.visitCharacterClassRange(node); + break; + case "CharacterSet": + this.visitCharacterSet(node); + break; + case "ClassIntersection": + this.visitClassIntersection(node); + break; + case "ClassStringDisjunction": + this.visitClassStringDisjunction(node); + break; + case "ClassSubtraction": + this.visitClassSubtraction(node); + break; + case "ExpressionCharacterClass": + this.visitExpressionCharacterClass(node); + break; + case "Flags": + this.visitFlags(node); + break; + case "Group": + this.visitGroup(node); + break; + case "Modifiers": + this.visitModifiers(node); + break; + case "ModifierFlags": + this.visitModifierFlags(node); + break; + case "Pattern": + this.visitPattern(node); + break; + case "Quantifier": + this.visitQuantifier(node); + break; + case "RegExpLiteral": + this.visitRegExpLiteral(node); + break; + case "StringAlternative": + this.visitStringAlternative(node); + break; + default: + throw new Error(`Unknown type: ${node.type}`); + } + } + visitAlternative(node) { + if (this._handlers.onAlternativeEnter) { + this._handlers.onAlternativeEnter(node); + } + node.elements.forEach(this.visit, this); + if (this._handlers.onAlternativeLeave) { + this._handlers.onAlternativeLeave(node); + } + } + visitAssertion(node) { + if (this._handlers.onAssertionEnter) { + this._handlers.onAssertionEnter(node); + } + if (node.kind === "lookahead" || node.kind === "lookbehind") { + node.alternatives.forEach(this.visit, this); + } + if (this._handlers.onAssertionLeave) { + this._handlers.onAssertionLeave(node); + } + } + visitBackreference(node) { + if (this._handlers.onBackreferenceEnter) { + this._handlers.onBackreferenceEnter(node); + } + if (this._handlers.onBackreferenceLeave) { + this._handlers.onBackreferenceLeave(node); + } + } + visitCapturingGroup(node) { + if (this._handlers.onCapturingGroupEnter) { + this._handlers.onCapturingGroupEnter(node); + } + node.alternatives.forEach(this.visit, this); + if (this._handlers.onCapturingGroupLeave) { + this._handlers.onCapturingGroupLeave(node); + } + } + visitCharacter(node) { + if (this._handlers.onCharacterEnter) { + this._handlers.onCharacterEnter(node); + } + if (this._handlers.onCharacterLeave) { + this._handlers.onCharacterLeave(node); + } + } + visitCharacterClass(node) { + if (this._handlers.onCharacterClassEnter) { + this._handlers.onCharacterClassEnter(node); + } + node.elements.forEach(this.visit, this); + if (this._handlers.onCharacterClassLeave) { + this._handlers.onCharacterClassLeave(node); + } + } + visitCharacterClassRange(node) { + if (this._handlers.onCharacterClassRangeEnter) { + this._handlers.onCharacterClassRangeEnter(node); + } + this.visitCharacter(node.min); + this.visitCharacter(node.max); + if (this._handlers.onCharacterClassRangeLeave) { + this._handlers.onCharacterClassRangeLeave(node); + } + } + visitCharacterSet(node) { + if (this._handlers.onCharacterSetEnter) { + this._handlers.onCharacterSetEnter(node); + } + if (this._handlers.onCharacterSetLeave) { + this._handlers.onCharacterSetLeave(node); + } + } + visitClassIntersection(node) { + if (this._handlers.onClassIntersectionEnter) { + this._handlers.onClassIntersectionEnter(node); + } + this.visit(node.left); + this.visit(node.right); + if (this._handlers.onClassIntersectionLeave) { + this._handlers.onClassIntersectionLeave(node); + } + } + visitClassStringDisjunction(node) { + if (this._handlers.onClassStringDisjunctionEnter) { + this._handlers.onClassStringDisjunctionEnter(node); + } + node.alternatives.forEach(this.visit, this); + if (this._handlers.onClassStringDisjunctionLeave) { + this._handlers.onClassStringDisjunctionLeave(node); + } + } + visitClassSubtraction(node) { + if (this._handlers.onClassSubtractionEnter) { + this._handlers.onClassSubtractionEnter(node); + } + this.visit(node.left); + this.visit(node.right); + if (this._handlers.onClassSubtractionLeave) { + this._handlers.onClassSubtractionLeave(node); + } + } + visitExpressionCharacterClass(node) { + if (this._handlers.onExpressionCharacterClassEnter) { + this._handlers.onExpressionCharacterClassEnter(node); + } + this.visit(node.expression); + if (this._handlers.onExpressionCharacterClassLeave) { + this._handlers.onExpressionCharacterClassLeave(node); + } + } + visitFlags(node) { + if (this._handlers.onFlagsEnter) { + this._handlers.onFlagsEnter(node); + } + if (this._handlers.onFlagsLeave) { + this._handlers.onFlagsLeave(node); + } + } + visitGroup(node) { + if (this._handlers.onGroupEnter) { + this._handlers.onGroupEnter(node); + } + if (node.modifiers) { + this.visit(node.modifiers); + } + node.alternatives.forEach(this.visit, this); + if (this._handlers.onGroupLeave) { + this._handlers.onGroupLeave(node); + } + } + visitModifiers(node) { + if (this._handlers.onModifiersEnter) { + this._handlers.onModifiersEnter(node); + } + if (node.add) { + this.visit(node.add); + } + if (node.remove) { + this.visit(node.remove); + } + if (this._handlers.onModifiersLeave) { + this._handlers.onModifiersLeave(node); + } + } + visitModifierFlags(node) { + if (this._handlers.onModifierFlagsEnter) { + this._handlers.onModifierFlagsEnter(node); + } + if (this._handlers.onModifierFlagsLeave) { + this._handlers.onModifierFlagsLeave(node); + } + } + visitPattern(node) { + if (this._handlers.onPatternEnter) { + this._handlers.onPatternEnter(node); + } + node.alternatives.forEach(this.visit, this); + if (this._handlers.onPatternLeave) { + this._handlers.onPatternLeave(node); + } + } + visitQuantifier(node) { + if (this._handlers.onQuantifierEnter) { + this._handlers.onQuantifierEnter(node); + } + this.visit(node.element); + if (this._handlers.onQuantifierLeave) { + this._handlers.onQuantifierLeave(node); + } + } + visitRegExpLiteral(node) { + if (this._handlers.onRegExpLiteralEnter) { + this._handlers.onRegExpLiteralEnter(node); + } + this.visitPattern(node.pattern); + this.visitFlags(node.flags); + if (this._handlers.onRegExpLiteralLeave) { + this._handlers.onRegExpLiteralLeave(node); + } + } + visitStringAlternative(node) { + if (this._handlers.onStringAlternativeEnter) { + this._handlers.onStringAlternativeEnter(node); + } + node.elements.forEach(this.visit, this); + if (this._handlers.onStringAlternativeLeave) { + this._handlers.onStringAlternativeLeave(node); + } + } +} + +function parseRegExpLiteral(source, options) { + return new RegExpParser(options).parseLiteral(String(source)); +} +function validateRegExpLiteral(source, options) { + new RegExpValidator(options).validateLiteral(source); +} +function visitRegExpAST(node, handlers) { + new RegExpVisitor(handlers).visit(node); +} + +exports.AST = ast; +exports.RegExpParser = RegExpParser; +exports.RegExpSyntaxError = RegExpSyntaxError; +exports.RegExpValidator = RegExpValidator; +exports.parseRegExpLiteral = parseRegExpLiteral; +exports.validateRegExpLiteral = validateRegExpLiteral; +exports.visitRegExpAST = visitRegExpAST; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@eslint-community/regexpp/index.js.map b/node_modules/@eslint-community/regexpp/index.js.map new file mode 100644 index 00000000..a13b289a --- /dev/null +++ b/node_modules/@eslint-community/regexpp/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js.map","sources":[".temp/src/ecma-versions.ts",".temp/unicode/src/unicode/ids.ts",".temp/unicode/src/unicode/properties.ts",".temp/unicode/src/unicode/index.ts",".temp/src/group-specifiers.ts",".temp/src/reader.ts",".temp/src/regexp-syntax-error.ts",".temp/src/validator.ts",".temp/src/parser.ts",".temp/src/visitor.ts",".temp/src/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null],"names":[],"mappings":";;;;;;;;AAaO,MAAM,iBAAiB,GAAG,IAAI;;ACTrC,IAAI,kBAAkB,GAAyB,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C,CAAA;AACvC,QAAA,IAAI,IAAI,CAAC,SAAS,CAAC,wBAAwB,EAAE;AACzC,YAAA,IAAI,CAAC,SAAS,CAAC,wBAAwB,CAAC,IAAI,CAAC,CAAA;AAChD,SAAA;KACJ;AACJ;;ACpTe,SAAA,kBAAkB,CAC9B,MAAuB,EACvB,OAA8B,EAAA;AAE9B,IAAA,OAAO,IAAI,YAAY,CAAC,OAAO,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAA;AACjE,CAAC;AAOe,SAAA,qBAAqB,CACjC,MAAc,EACd,OAAiC,EAAA;IAEjC,IAAI,eAAe,CAAC,OAAO,CAAC,CAAC,eAAe,CAAC,MAAM,CAAC,CAAA;AACxD,CAAC;AAEe,SAAA,cAAc,CAC1B,IAAc,EACd,QAAgC,EAAA;IAEhC,IAAI,aAAa,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;AAC3C;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@eslint-community/regexpp/index.mjs b/node_modules/@eslint-community/regexpp/index.mjs new file mode 100644 index 00000000..7652c62b --- /dev/null +++ b/node_modules/@eslint-community/regexpp/index.mjs @@ -0,0 +1,3027 @@ +var ast = /*#__PURE__*/Object.freeze({ + __proto__: null +}); + +const latestEcmaVersion = 2025; + +let largeIdStartRanges = undefined; +let largeIdContinueRanges = undefined; +function isIdStart(cp) { + if (cp < 0x41) + return false; + if (cp < 0x5b) + return true; + if (cp < 0x61) + return false; + if (cp < 0x7b) + return true; + return isLargeIdStart(cp); +} +function isIdContinue(cp) { + if (cp < 0x30) + return false; + if (cp < 0x3a) + return true; + if (cp < 0x41) + return false; + if (cp < 0x5b) + return true; + if (cp === 0x5f) + return true; + if (cp < 0x61) + return false; + if (cp < 0x7b) + return true; + return isLargeIdStart(cp) || isLargeIdContinue(cp); +} +function isLargeIdStart(cp) { + return isInRange(cp, largeIdStartRanges !== null && largeIdStartRanges !== void 0 ? largeIdStartRanges : (largeIdStartRanges = initLargeIdStartRanges())); +} +function isLargeIdContinue(cp) { + return isInRange(cp, largeIdContinueRanges !== null && largeIdContinueRanges !== void 0 ? largeIdContinueRanges : (largeIdContinueRanges = initLargeIdContinueRanges())); +} +function initLargeIdStartRanges() { + return restoreRanges("4q 0 b 0 5 0 6 m 2 u 2 cp 5 b f 4 8 0 2 0 3m 4 2 1 3 3 2 0 7 0 2 2 2 0 2 j 2 2a 2 3u 9 4l 2 11 3 0 7 14 20 q 5 3 1a 16 10 1 2 2q 2 0 g 1 8 1 b 2 3 0 h 0 2 t u 2g c 0 p w a 1 5 0 6 l 5 0 a 0 4 0 o o 8 a 6 n 2 5 i 15 1n 1h 4 0 j 0 8 9 g f 5 7 3 1 3 l 2 6 2 0 4 3 4 0 h 0 e 1 2 2 f 1 b 0 9 5 5 1 3 l 2 6 2 1 2 1 2 1 w 3 2 0 k 2 h 8 2 2 2 l 2 6 2 1 2 4 4 0 j 0 g 1 o 0 c 7 3 1 3 l 2 6 2 1 2 4 4 0 v 1 2 2 g 0 i 0 2 5 4 2 2 3 4 1 2 0 2 1 4 1 4 2 4 b n 0 1h 7 2 2 2 m 2 f 4 0 r 2 3 0 3 1 v 0 5 7 2 2 2 m 2 9 2 4 4 0 w 1 2 1 g 1 i 8 2 2 2 14 3 0 h 0 6 2 9 2 p 5 6 h 4 n 2 8 2 0 3 6 1n 1b 2 1 d 6 1n 1 2 0 2 4 2 n 2 0 2 9 2 1 a 0 3 4 2 0 m 3 x 0 1s 7 2 z s 4 38 16 l 0 h 5 5 3 4 0 4 1 8 2 5 c d 0 i 11 2 0 6 0 3 16 2 98 2 3 3 6 2 0 2 3 3 14 2 3 3 w 2 3 3 6 2 0 2 3 3 e 2 1k 2 3 3 1u 12 f h 2d 3 5 4 h7 3 g 2 p 6 22 4 a 8 h e i f h f c 2 2 g 1f 10 0 5 0 1w 2g 8 14 2 0 6 1x b u 1e t 3 4 c 17 5 p 1j m a 1g 2b 0 2m 1a i 7 1j t e 1 b 17 r z 16 2 b z 3 a 6 16 3 2 16 3 2 5 2 1 4 0 6 5b 1t 7p 3 5 3 11 3 5 3 7 2 0 2 0 2 0 2 u 3 1g 2 6 2 0 4 2 2 6 4 3 3 5 5 c 6 2 2 6 39 0 e 0 h c 2u 0 5 0 3 9 2 0 3 5 7 0 2 0 2 0 2 f 3 3 6 4 5 0 i 14 22g 6c 7 3 4 1 d 11 2 0 6 0 3 1j 8 0 h m a 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 fb 2 q 8 8 4 3 4 5 2d 5 4 2 2h 2 3 6 16 2 2l i v 1d f e9 533 1t h3g 1w 19 3 7g 4 f b 1 l 1a h u 3 27 14 8 3 2u 3 1u 3 1 2 0 2 7 m f 2 2 2 3 2 m u 1f f 1d 1r 5 4 0 2 1 c r b m q s 8 1a t 0 h 4 2 9 b 4 2 14 o 2 2 7 l m 4 0 4 1d 2 0 4 1 3 4 3 0 2 0 p 2 3 a 8 2 d 5 3 5 3 5 a 6 2 6 2 16 2 d 7 36 u 8mb d m 5 1c 6it a5 3 2x 13 6 d 4 6 0 2 9 2 c 2 4 2 0 2 1 2 1 2 2z y a2 j 1r 3 1h 15 b 39 4 2 3q 11 p 7 p c 2g 4 5 3 5 3 5 3 2 10 b 2 p 2 i 2 1 2 e 3 d z 3e 1y 1g 7g s 4 1c 1c v e t 6 11 b t 3 z 5 7 2 4 17 4d j z 5 z 5 13 9 1f d a 2 e 2 6 2 1 2 a 2 e 2 6 2 1 4 1f d 8m a l b 7 p 5 2 15 2 8 1y 5 3 0 2 17 2 1 4 0 3 m b m a u 1u i 2 1 b l b p 1z 1j 7 1 1t 0 g 3 2 2 2 s 17 s 4 s 10 7 2 r s 1h b l b i e h 33 20 1k 1e e 1e e z 13 r a m 6z 15 7 1 h 2 1o s b 0 9 l 17 h 1b k s m d 1g 1m 1 3 0 e 18 x o r z u 0 3 0 9 y 4 0 d 1b f 3 m 0 2 0 10 h 2 o k 1 1s 6 2 0 2 3 2 e 2 9 8 1a 13 7 3 1 3 l 2 6 2 1 2 4 4 0 j 0 d 4 v 9 2 0 3 0 2 11 2 0 q 0 2 0 19 1g j 3 l 2 v 1b l 1 2 0 55 1a 16 3 11 1b l 0 1o 16 e 0 20 q 12 6 56 17 39 1r w 7 3 0 3 7 2 1 2 n g 0 2 0 2n 7 3 12 h 0 2 0 t 0 b 13 8 0 m 0 c 19 k 0 j 20 5k w w 8 2 10 i 0 1e t 35 6 2 1 2 11 m 0 q 5 2 1 2 v f 0 94 i g 0 2 c 2 x 3h 0 28 pl 2v 32 i 5f 219 2o g tr i 5 q 32y 6 g6 5a2 t 1cz fs 8 u i 26 i t j 1b h 3 w k 6 i c1 18 5w 1r 3l 22 6 0 1v c 1t 1 2 0 t 4qf 9 yd 16 9 6w8 3 2 6 2 1 2 82 g 0 u 2 3 0 f 3 9 az 1s5 2y 6 c 4 8 8 9 4mf 2c 2 1y 2 1 3 0 3 1 3 3 2 b 2 0 2 6 2 1s 2 3 3 7 2 6 2 r 2 3 2 4 2 0 4 6 2 9f 3 o 2 o 2 u 2 o 2 u 2 o 2 u 2 o 2 u 2 o 2 7 1f9 u 7 5 7a 1p 43 18 b 6 h 0 8y t j 17 dh r 6d t 3 0 ds 6 2 3 2 1 2 e 2 5g 1o 1v 8 0 xh 3 2 q 2 1 2 0 3 0 2 9 2 3 2 0 2 0 7 0 5 0 2 0 2 0 2 2 2 1 2 0 3 0 2 0 2 0 2 0 2 0 2 1 2 0 3 3 2 6 2 3 2 3 2 0 2 9 2 g 6 2 2 4 2 g 3et wyn x 37d 7 65 3 4g1 f 5rk g h9 1wj f1 15v 3t6 6 38f"); +} +function initLargeIdContinueRanges() { + return restoreRanges("53 0 g9 33 o 0 70 4 7e 18 2 0 2 1 2 1 2 0 21 a 1d u 7 0 2u 6 3 5 3 1 2 3 3 9 o 0 v q 2k a g 9 y 8 a 0 p 3 2 8 2 2 2 4 18 2 1o 8 17 n 2 w 1j 2 2 h 2 6 b 1 3 9 i 2 1l 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2b h a 9 5 0 2a j d 9 5y 6 3 8 s 1 2b g g 9 2a c 9 9 7 j 1m e 5 9 6r e 4m 9 1z 5 2 1 3 3 2 0 2 1 d 9 3c 6 3 6 4 0 t 9 15 6 2 3 9 0 a a 1b f 9j 9 1i 7 2 7 h 9 1l l 2 d 3f 5 4 0 2 1 2 6 2 0 9 9 1d 4 2 1 2 4 9 9 96 3 a 1 2 0 1d 6 4 4 e a 44m 0 7 e 8uh r 1t3 9 2f 9 13 4 1o 6 q 9 ev 9 d2 0 2 1i 8 3 2a 0 c 1 f58 1 382 9 ef 19 3 m f3 4 4 5 9 7 3 6 v 3 45 2 13e 1d e9 1i 5 1d 9 0 f 0 n 4 2 e 11t 6 2 g 3 6 2 1 2 4 2t 0 4h 6 a 9 9x 0 1q d dv d 6t 1 2 9 k6 6 32 6 6 9 3o7 9 gvt3 6n"); +} +function isInRange(cp, ranges) { + let l = 0, r = (ranges.length / 2) | 0, i = 0, min = 0, max = 0; + while (l < r) { + i = ((l + r) / 2) | 0; + min = ranges[2 * i]; + max = ranges[2 * i + 1]; + if (cp < min) { + r = i; + } + else if (cp > max) { + l = i + 1; + } + else { + return true; + } + } + return false; +} +function restoreRanges(data) { + let last = 0; + return data.split(" ").map((s) => (last += parseInt(s, 36) | 0)); +} + +class DataSet { + constructor(raw2018, raw2019, raw2020, raw2021, raw2022, raw2023, raw2024, raw2025) { + this._raw2018 = raw2018; + this._raw2019 = raw2019; + this._raw2020 = raw2020; + this._raw2021 = raw2021; + this._raw2022 = raw2022; + this._raw2023 = raw2023; + this._raw2024 = raw2024; + this._raw2025 = raw2025; + } + get es2018() { + var _a; + return ((_a = this._set2018) !== null && _a !== void 0 ? _a : (this._set2018 = new Set(this._raw2018.split(" ")))); + } + get es2019() { + var _a; + return ((_a = this._set2019) !== null && _a !== void 0 ? _a : (this._set2019 = new Set(this._raw2019.split(" ")))); + } + get es2020() { + var _a; + return ((_a = this._set2020) !== null && _a !== void 0 ? _a : (this._set2020 = new Set(this._raw2020.split(" ")))); + } + get es2021() { + var _a; + return ((_a = this._set2021) !== null && _a !== void 0 ? _a : (this._set2021 = new Set(this._raw2021.split(" ")))); + } + get es2022() { + var _a; + return ((_a = this._set2022) !== null && _a !== void 0 ? _a : (this._set2022 = new Set(this._raw2022.split(" ")))); + } + get es2023() { + var _a; + return ((_a = this._set2023) !== null && _a !== void 0 ? _a : (this._set2023 = new Set(this._raw2023.split(" ")))); + } + get es2024() { + var _a; + return ((_a = this._set2024) !== null && _a !== void 0 ? _a : (this._set2024 = new Set(this._raw2024.split(" ")))); + } + get es2025() { + var _a; + return ((_a = this._set2025) !== null && _a !== void 0 ? _a : (this._set2025 = new Set(this._raw2025.split(" ")))); + } +} +const gcNameSet = new Set(["General_Category", "gc"]); +const scNameSet = new Set(["Script", "Script_Extensions", "sc", "scx"]); +const gcValueSets = new DataSet("C Cased_Letter Cc Cf Close_Punctuation Cn Co Combining_Mark Connector_Punctuation Control Cs Currency_Symbol Dash_Punctuation Decimal_Number Enclosing_Mark Final_Punctuation Format Initial_Punctuation L LC Letter Letter_Number Line_Separator Ll Lm Lo Lowercase_Letter Lt Lu M Mark Math_Symbol Mc Me Mn Modifier_Letter Modifier_Symbol N Nd Nl No Nonspacing_Mark Number Open_Punctuation Other Other_Letter Other_Number Other_Punctuation Other_Symbol P Paragraph_Separator Pc Pd Pe Pf Pi Po Private_Use Ps Punctuation S Sc Separator Sk Sm So Space_Separator Spacing_Mark Surrogate Symbol Titlecase_Letter Unassigned Uppercase_Letter Z Zl Zp Zs cntrl digit punct", "", "", "", "", "", "", ""); +const scValueSets = new DataSet("Adlam Adlm Aghb Ahom Anatolian_Hieroglyphs Arab Arabic Armenian Armi Armn Avestan Avst Bali Balinese Bamu Bamum Bass Bassa_Vah Batak Batk Beng Bengali Bhaiksuki Bhks Bopo Bopomofo Brah Brahmi Brai Braille Bugi Buginese Buhd Buhid Cakm Canadian_Aboriginal Cans Cari Carian Caucasian_Albanian Chakma Cham Cher Cherokee Common Copt Coptic Cprt Cuneiform Cypriot Cyrillic Cyrl Deseret Deva Devanagari Dsrt Dupl Duployan Egyp Egyptian_Hieroglyphs Elba Elbasan Ethi Ethiopic Geor Georgian Glag Glagolitic Gonm Goth Gothic Gran Grantha Greek Grek Gujarati Gujr Gurmukhi Guru Han Hang Hangul Hani Hano Hanunoo Hatr Hatran Hebr Hebrew Hira Hiragana Hluw Hmng Hung Imperial_Aramaic Inherited Inscriptional_Pahlavi Inscriptional_Parthian Ital Java Javanese Kaithi Kali Kana Kannada Katakana Kayah_Li Khar Kharoshthi Khmer Khmr Khoj Khojki Khudawadi Knda Kthi Lana Lao Laoo Latin Latn Lepc Lepcha Limb Limbu Lina Linb Linear_A Linear_B Lisu Lyci Lycian Lydi Lydian Mahajani Mahj Malayalam Mand Mandaic Mani Manichaean Marc Marchen Masaram_Gondi Meetei_Mayek Mend Mende_Kikakui Merc Mero Meroitic_Cursive Meroitic_Hieroglyphs Miao Mlym Modi Mong Mongolian Mro Mroo Mtei Mult Multani Myanmar Mymr Nabataean Narb Nbat New_Tai_Lue Newa Nko Nkoo Nshu Nushu Ogam Ogham Ol_Chiki Olck Old_Hungarian Old_Italic Old_North_Arabian Old_Permic Old_Persian Old_South_Arabian Old_Turkic Oriya Orkh Orya Osage Osge Osma Osmanya Pahawh_Hmong Palm Palmyrene Pau_Cin_Hau Pauc Perm Phag Phags_Pa Phli Phlp Phnx Phoenician Plrd Prti Psalter_Pahlavi Qaac Qaai Rejang Rjng Runic Runr Samaritan Samr Sarb Saur Saurashtra Sgnw Sharada Shavian Shaw Shrd Sidd Siddham SignWriting Sind Sinh Sinhala Sora Sora_Sompeng Soyo Soyombo Sund Sundanese Sylo Syloti_Nagri Syrc Syriac Tagalog Tagb Tagbanwa Tai_Le Tai_Tham Tai_Viet Takr Takri Tale Talu Tamil Taml Tang Tangut Tavt Telu Telugu Tfng Tglg Thaa Thaana Thai Tibetan Tibt Tifinagh Tirh Tirhuta Ugar Ugaritic Vai Vaii Wara Warang_Citi Xpeo Xsux Yi Yiii Zanabazar_Square Zanb Zinh Zyyy", "Dogr Dogra Gong Gunjala_Gondi Hanifi_Rohingya Maka Makasar Medefaidrin Medf Old_Sogdian Rohg Sogd Sogdian Sogo", "Elym Elymaic Hmnp Nand Nandinagari Nyiakeng_Puachue_Hmong Wancho Wcho", "Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi", "Cpmn Cypro_Minoan Old_Uyghur Ougr Tangsa Tnsa Toto Vith Vithkuqi", "Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz", "", ""); +const binPropertySets = new DataSet("AHex ASCII ASCII_Hex_Digit Alpha Alphabetic Any Assigned Bidi_C Bidi_Control Bidi_M Bidi_Mirrored CI CWCF CWCM CWKCF CWL CWT CWU Case_Ignorable Cased Changes_When_Casefolded Changes_When_Casemapped Changes_When_Lowercased Changes_When_NFKC_Casefolded Changes_When_Titlecased Changes_When_Uppercased DI Dash Default_Ignorable_Code_Point Dep Deprecated Dia Diacritic Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Ext Extender Gr_Base Gr_Ext Grapheme_Base Grapheme_Extend Hex Hex_Digit IDC IDS IDSB IDST IDS_Binary_Operator IDS_Trinary_Operator ID_Continue ID_Start Ideo Ideographic Join_C Join_Control LOE Logical_Order_Exception Lower Lowercase Math NChar Noncharacter_Code_Point Pat_Syn Pat_WS Pattern_Syntax Pattern_White_Space QMark Quotation_Mark RI Radical Regional_Indicator SD STerm Sentence_Terminal Soft_Dotted Term Terminal_Punctuation UIdeo Unified_Ideograph Upper Uppercase VS Variation_Selector White_Space XIDC XIDS XID_Continue XID_Start space", "Extended_Pictographic", "", "EBase EComp EMod EPres ExtPict", "", "", "", ""); +const binPropertyOfStringsSets = new DataSet("", "", "", "", "", "", "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji RGI_Emoji_Flag_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence", ""); +function isValidUnicodeProperty(version, name, value) { + if (gcNameSet.has(name)) { + return version >= 2018 && gcValueSets.es2018.has(value); + } + if (scNameSet.has(name)) { + return ((version >= 2018 && scValueSets.es2018.has(value)) || + (version >= 2019 && scValueSets.es2019.has(value)) || + (version >= 2020 && scValueSets.es2020.has(value)) || + (version >= 2021 && scValueSets.es2021.has(value)) || + (version >= 2022 && scValueSets.es2022.has(value)) || + (version >= 2023 && scValueSets.es2023.has(value))); + } + return false; +} +function isValidLoneUnicodeProperty(version, value) { + return ((version >= 2018 && binPropertySets.es2018.has(value)) || + (version >= 2019 && binPropertySets.es2019.has(value)) || + (version >= 2021 && binPropertySets.es2021.has(value))); +} +function isValidLoneUnicodePropertyOfString(version, value) { + return version >= 2024 && binPropertyOfStringsSets.es2024.has(value); +} + +const BACKSPACE = 0x08; +const CHARACTER_TABULATION = 0x09; +const LINE_FEED = 0x0a; +const LINE_TABULATION = 0x0b; +const FORM_FEED = 0x0c; +const CARRIAGE_RETURN = 0x0d; +const EXCLAMATION_MARK = 0x21; +const NUMBER_SIGN = 0x23; +const DOLLAR_SIGN = 0x24; +const PERCENT_SIGN = 0x25; +const AMPERSAND = 0x26; +const LEFT_PARENTHESIS = 0x28; +const RIGHT_PARENTHESIS = 0x29; +const ASTERISK = 0x2a; +const PLUS_SIGN = 0x2b; +const COMMA = 0x2c; +const HYPHEN_MINUS = 0x2d; +const FULL_STOP = 0x2e; +const SOLIDUS = 0x2f; +const DIGIT_ZERO = 0x30; +const DIGIT_ONE = 0x31; +const DIGIT_SEVEN = 0x37; +const DIGIT_NINE = 0x39; +const COLON = 0x3a; +const SEMICOLON = 0x3b; +const LESS_THAN_SIGN = 0x3c; +const EQUALS_SIGN = 0x3d; +const GREATER_THAN_SIGN = 0x3e; +const QUESTION_MARK = 0x3f; +const COMMERCIAL_AT = 0x40; +const LATIN_CAPITAL_LETTER_A = 0x41; +const LATIN_CAPITAL_LETTER_B = 0x42; +const LATIN_CAPITAL_LETTER_D = 0x44; +const LATIN_CAPITAL_LETTER_F = 0x46; +const LATIN_CAPITAL_LETTER_P = 0x50; +const LATIN_CAPITAL_LETTER_S = 0x53; +const LATIN_CAPITAL_LETTER_W = 0x57; +const LATIN_CAPITAL_LETTER_Z = 0x5a; +const LOW_LINE = 0x5f; +const LATIN_SMALL_LETTER_A = 0x61; +const LATIN_SMALL_LETTER_B = 0x62; +const LATIN_SMALL_LETTER_C = 0x63; +const LATIN_SMALL_LETTER_D = 0x64; +const LATIN_SMALL_LETTER_F = 0x66; +const LATIN_SMALL_LETTER_G = 0x67; +const LATIN_SMALL_LETTER_I = 0x69; +const LATIN_SMALL_LETTER_K = 0x6b; +const LATIN_SMALL_LETTER_M = 0x6d; +const LATIN_SMALL_LETTER_N = 0x6e; +const LATIN_SMALL_LETTER_P = 0x70; +const LATIN_SMALL_LETTER_Q = 0x71; +const LATIN_SMALL_LETTER_R = 0x72; +const LATIN_SMALL_LETTER_S = 0x73; +const LATIN_SMALL_LETTER_T = 0x74; +const LATIN_SMALL_LETTER_U = 0x75; +const LATIN_SMALL_LETTER_V = 0x76; +const LATIN_SMALL_LETTER_W = 0x77; +const LATIN_SMALL_LETTER_X = 0x78; +const LATIN_SMALL_LETTER_Y = 0x79; +const LATIN_SMALL_LETTER_Z = 0x7a; +const LEFT_SQUARE_BRACKET = 0x5b; +const REVERSE_SOLIDUS = 0x5c; +const RIGHT_SQUARE_BRACKET = 0x5d; +const CIRCUMFLEX_ACCENT = 0x5e; +const GRAVE_ACCENT = 0x60; +const LEFT_CURLY_BRACKET = 0x7b; +const VERTICAL_LINE = 0x7c; +const RIGHT_CURLY_BRACKET = 0x7d; +const TILDE = 0x7e; +const ZERO_WIDTH_NON_JOINER = 0x200c; +const ZERO_WIDTH_JOINER = 0x200d; +const LINE_SEPARATOR = 0x2028; +const PARAGRAPH_SEPARATOR = 0x2029; +const MIN_CODE_POINT = 0x00; +const MAX_CODE_POINT = 0x10ffff; +function isLatinLetter(code) { + return ((code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_Z) || + (code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_Z)); +} +function isDecimalDigit(code) { + return code >= DIGIT_ZERO && code <= DIGIT_NINE; +} +function isOctalDigit(code) { + return code >= DIGIT_ZERO && code <= DIGIT_SEVEN; +} +function isHexDigit(code) { + return ((code >= DIGIT_ZERO && code <= DIGIT_NINE) || + (code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_F) || + (code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_F)); +} +function isLineTerminator(code) { + return (code === LINE_FEED || + code === CARRIAGE_RETURN || + code === LINE_SEPARATOR || + code === PARAGRAPH_SEPARATOR); +} +function isValidUnicode(code) { + return code >= MIN_CODE_POINT && code <= MAX_CODE_POINT; +} +function digitToInt(code) { + if (code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_F) { + return code - LATIN_SMALL_LETTER_A + 10; + } + if (code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_F) { + return code - LATIN_CAPITAL_LETTER_A + 10; + } + return code - DIGIT_ZERO; +} +function isLeadSurrogate(code) { + return code >= 0xd800 && code <= 0xdbff; +} +function isTrailSurrogate(code) { + return code >= 0xdc00 && code <= 0xdfff; +} +function combineSurrogatePair(lead, trail) { + return (lead - 0xd800) * 0x400 + (trail - 0xdc00) + 0x10000; +} + +class GroupSpecifiersAsES2018 { + constructor() { + this.groupName = new Set(); + } + clear() { + this.groupName.clear(); + } + isEmpty() { + return !this.groupName.size; + } + hasInPattern(name) { + return this.groupName.has(name); + } + hasInScope(name) { + return this.hasInPattern(name); + } + addToScope(name) { + this.groupName.add(name); + } + enterDisjunction() { + } + enterAlternative() { + } + leaveDisjunction() { + } +} +class BranchID { + constructor(parent, base) { + this.parent = parent; + this.base = base !== null && base !== void 0 ? base : this; + } + separatedFrom(other) { + var _a, _b; + if (this.base === other.base && this !== other) { + return true; + } + if (other.parent && this.separatedFrom(other.parent)) { + return true; + } + return (_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.separatedFrom(other)) !== null && _b !== void 0 ? _b : false; + } + child() { + return new BranchID(this, null); + } + sibling() { + return new BranchID(this.parent, this.base); + } +} +class GroupSpecifiersAsES2025 { + constructor() { + this.branchID = new BranchID(null, null); + this.groupNames = new Map(); + } + clear() { + this.branchID = new BranchID(null, null); + this.groupNames.clear(); + } + isEmpty() { + return !this.groupNames.size; + } + enterDisjunction() { + this.branchID = this.branchID.child(); + } + enterAlternative(index) { + if (index === 0) { + return; + } + this.branchID = this.branchID.sibling(); + } + leaveDisjunction() { + this.branchID = this.branchID.parent; + } + hasInPattern(name) { + return this.groupNames.has(name); + } + hasInScope(name) { + const branches = this.groupNames.get(name); + if (!branches) { + return false; + } + for (const branch of branches) { + if (!branch.separatedFrom(this.branchID)) { + return true; + } + } + return false; + } + addToScope(name) { + const branches = this.groupNames.get(name); + if (branches) { + branches.push(this.branchID); + return; + } + this.groupNames.set(name, [this.branchID]); + } +} + +const legacyImpl = { + at(s, end, i) { + return i < end ? s.charCodeAt(i) : -1; + }, + width(c) { + return 1; + }, +}; +const unicodeImpl = { + at(s, end, i) { + return i < end ? s.codePointAt(i) : -1; + }, + width(c) { + return c > 0xffff ? 2 : 1; + }, +}; +class Reader { + constructor() { + this._impl = legacyImpl; + this._s = ""; + this._i = 0; + this._end = 0; + this._cp1 = -1; + this._w1 = 1; + this._cp2 = -1; + this._w2 = 1; + this._cp3 = -1; + this._w3 = 1; + this._cp4 = -1; + } + get source() { + return this._s; + } + get index() { + return this._i; + } + get currentCodePoint() { + return this._cp1; + } + get nextCodePoint() { + return this._cp2; + } + get nextCodePoint2() { + return this._cp3; + } + get nextCodePoint3() { + return this._cp4; + } + reset(source, start, end, uFlag) { + this._impl = uFlag ? unicodeImpl : legacyImpl; + this._s = source; + this._end = end; + this.rewind(start); + } + rewind(index) { + const impl = this._impl; + this._i = index; + this._cp1 = impl.at(this._s, this._end, index); + this._w1 = impl.width(this._cp1); + this._cp2 = impl.at(this._s, this._end, index + this._w1); + this._w2 = impl.width(this._cp2); + this._cp3 = impl.at(this._s, this._end, index + this._w1 + this._w2); + this._w3 = impl.width(this._cp3); + this._cp4 = impl.at(this._s, this._end, index + this._w1 + this._w2 + this._w3); + } + advance() { + if (this._cp1 !== -1) { + const impl = this._impl; + this._i += this._w1; + this._cp1 = this._cp2; + this._w1 = this._w2; + this._cp2 = this._cp3; + this._w2 = impl.width(this._cp2); + this._cp3 = this._cp4; + this._w3 = impl.width(this._cp3); + this._cp4 = impl.at(this._s, this._end, this._i + this._w1 + this._w2 + this._w3); + } + } + eat(cp) { + if (this._cp1 === cp) { + this.advance(); + return true; + } + return false; + } + eat2(cp1, cp2) { + if (this._cp1 === cp1 && this._cp2 === cp2) { + this.advance(); + this.advance(); + return true; + } + return false; + } + eat3(cp1, cp2, cp3) { + if (this._cp1 === cp1 && this._cp2 === cp2 && this._cp3 === cp3) { + this.advance(); + this.advance(); + this.advance(); + return true; + } + return false; + } +} + +class RegExpSyntaxError extends SyntaxError { + constructor(message, index) { + super(message); + this.index = index; + } +} +function newRegExpSyntaxError(srcCtx, flags, index, message) { + let source = ""; + if (srcCtx.kind === "literal") { + const literal = srcCtx.source.slice(srcCtx.start, srcCtx.end); + if (literal) { + source = `: ${literal}`; + } + } + else if (srcCtx.kind === "pattern") { + const pattern = srcCtx.source.slice(srcCtx.start, srcCtx.end); + const flagsText = `${flags.unicode ? "u" : ""}${flags.unicodeSets ? "v" : ""}`; + source = `: /${pattern}/${flagsText}`; + } + return new RegExpSyntaxError(`Invalid regular expression${source}: ${message}`, index); +} + +const SYNTAX_CHARACTER = new Set([ + CIRCUMFLEX_ACCENT, + DOLLAR_SIGN, + REVERSE_SOLIDUS, + FULL_STOP, + ASTERISK, + PLUS_SIGN, + QUESTION_MARK, + LEFT_PARENTHESIS, + RIGHT_PARENTHESIS, + LEFT_SQUARE_BRACKET, + RIGHT_SQUARE_BRACKET, + LEFT_CURLY_BRACKET, + RIGHT_CURLY_BRACKET, + VERTICAL_LINE, +]); +const CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR_CHARACTER = new Set([ + AMPERSAND, + EXCLAMATION_MARK, + NUMBER_SIGN, + DOLLAR_SIGN, + PERCENT_SIGN, + ASTERISK, + PLUS_SIGN, + COMMA, + FULL_STOP, + COLON, + SEMICOLON, + LESS_THAN_SIGN, + EQUALS_SIGN, + GREATER_THAN_SIGN, + QUESTION_MARK, + COMMERCIAL_AT, + CIRCUMFLEX_ACCENT, + GRAVE_ACCENT, + TILDE, +]); +const CLASS_SET_SYNTAX_CHARACTER = new Set([ + LEFT_PARENTHESIS, + RIGHT_PARENTHESIS, + LEFT_SQUARE_BRACKET, + RIGHT_SQUARE_BRACKET, + LEFT_CURLY_BRACKET, + RIGHT_CURLY_BRACKET, + SOLIDUS, + HYPHEN_MINUS, + REVERSE_SOLIDUS, + VERTICAL_LINE, +]); +const CLASS_SET_RESERVED_PUNCTUATOR = new Set([ + AMPERSAND, + HYPHEN_MINUS, + EXCLAMATION_MARK, + NUMBER_SIGN, + PERCENT_SIGN, + COMMA, + COLON, + SEMICOLON, + LESS_THAN_SIGN, + EQUALS_SIGN, + GREATER_THAN_SIGN, + COMMERCIAL_AT, + GRAVE_ACCENT, + TILDE, +]); +const FLAG_PROP_TO_CODEPOINT = { + global: LATIN_SMALL_LETTER_G, + ignoreCase: LATIN_SMALL_LETTER_I, + multiline: LATIN_SMALL_LETTER_M, + unicode: LATIN_SMALL_LETTER_U, + sticky: LATIN_SMALL_LETTER_Y, + dotAll: LATIN_SMALL_LETTER_S, + hasIndices: LATIN_SMALL_LETTER_D, + unicodeSets: LATIN_SMALL_LETTER_V, +}; +const FLAG_CODEPOINT_TO_PROP = Object.fromEntries(Object.entries(FLAG_PROP_TO_CODEPOINT).map(([k, v]) => [v, k])); +function isSyntaxCharacter(cp) { + return SYNTAX_CHARACTER.has(cp); +} +function isClassSetReservedDoublePunctuatorCharacter(cp) { + return CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR_CHARACTER.has(cp); +} +function isClassSetSyntaxCharacter(cp) { + return CLASS_SET_SYNTAX_CHARACTER.has(cp); +} +function isClassSetReservedPunctuator(cp) { + return CLASS_SET_RESERVED_PUNCTUATOR.has(cp); +} +function isIdentifierStartChar(cp) { + return isIdStart(cp) || cp === DOLLAR_SIGN || cp === LOW_LINE; +} +function isIdentifierPartChar(cp) { + return (isIdContinue(cp) || + cp === DOLLAR_SIGN || + cp === ZERO_WIDTH_NON_JOINER || + cp === ZERO_WIDTH_JOINER); +} +function isUnicodePropertyNameCharacter(cp) { + return isLatinLetter(cp) || cp === LOW_LINE; +} +function isUnicodePropertyValueCharacter(cp) { + return isUnicodePropertyNameCharacter(cp) || isDecimalDigit(cp); +} +function isRegularExpressionModifier(ch) { + return (ch === LATIN_SMALL_LETTER_I || + ch === LATIN_SMALL_LETTER_M || + ch === LATIN_SMALL_LETTER_S); +} +class RegExpValidator { + constructor(options) { + this._reader = new Reader(); + this._unicodeMode = false; + this._unicodeSetsMode = false; + this._nFlag = false; + this._lastIntValue = 0; + this._lastRange = { + min: 0, + max: Number.POSITIVE_INFINITY, + }; + this._lastStrValue = ""; + this._lastAssertionIsQuantifiable = false; + this._numCapturingParens = 0; + this._backreferenceNames = new Set(); + this._srcCtx = null; + this._options = options !== null && options !== void 0 ? options : {}; + this._groupSpecifiers = + this.ecmaVersion >= 2025 + ? new GroupSpecifiersAsES2025() + : new GroupSpecifiersAsES2018(); + } + validateLiteral(source, start = 0, end = source.length) { + this._srcCtx = { source, start, end, kind: "literal" }; + this._unicodeSetsMode = this._unicodeMode = this._nFlag = false; + this.reset(source, start, end); + this.onLiteralEnter(start); + if (this.eat(SOLIDUS) && this.eatRegExpBody() && this.eat(SOLIDUS)) { + const flagStart = this.index; + const unicode = source.includes("u", flagStart); + const unicodeSets = source.includes("v", flagStart); + this.validateFlagsInternal(source, flagStart, end); + this.validatePatternInternal(source, start + 1, flagStart - 1, { + unicode, + unicodeSets, + }); + } + else if (start >= end) { + this.raise("Empty"); + } + else { + const c = String.fromCodePoint(this.currentCodePoint); + this.raise(`Unexpected character '${c}'`); + } + this.onLiteralLeave(start, end); + } + validateFlags(source, start = 0, end = source.length) { + this._srcCtx = { source, start, end, kind: "flags" }; + this.validateFlagsInternal(source, start, end); + } + validatePattern(source, start = 0, end = source.length, uFlagOrFlags = undefined) { + this._srcCtx = { source, start, end, kind: "pattern" }; + this.validatePatternInternal(source, start, end, uFlagOrFlags); + } + validatePatternInternal(source, start = 0, end = source.length, uFlagOrFlags = undefined) { + const mode = this._parseFlagsOptionToMode(uFlagOrFlags, end); + this._unicodeMode = mode.unicodeMode; + this._nFlag = mode.nFlag; + this._unicodeSetsMode = mode.unicodeSetsMode; + this.reset(source, start, end); + this.consumePattern(); + if (!this._nFlag && + this.ecmaVersion >= 2018 && + !this._groupSpecifiers.isEmpty()) { + this._nFlag = true; + this.rewind(start); + this.consumePattern(); + } + } + validateFlagsInternal(source, start, end) { + const flags = this.parseFlags(source, start, end); + this.onRegExpFlags(start, end, flags); + } + _parseFlagsOptionToMode(uFlagOrFlags, sourceEnd) { + let unicode = false; + let unicodeSets = false; + if (uFlagOrFlags && this.ecmaVersion >= 2015) { + if (typeof uFlagOrFlags === "object") { + unicode = Boolean(uFlagOrFlags.unicode); + if (this.ecmaVersion >= 2024) { + unicodeSets = Boolean(uFlagOrFlags.unicodeSets); + } + } + else { + unicode = uFlagOrFlags; + } + } + if (unicode && unicodeSets) { + this.raise("Invalid regular expression flags", { + index: sourceEnd + 1, + unicode, + unicodeSets, + }); + } + const unicodeMode = unicode || unicodeSets; + const nFlag = (unicode && this.ecmaVersion >= 2018) || + unicodeSets || + Boolean(this._options.strict && this.ecmaVersion >= 2023); + const unicodeSetsMode = unicodeSets; + return { unicodeMode, nFlag, unicodeSetsMode }; + } + get strict() { + return Boolean(this._options.strict) || this._unicodeMode; + } + get ecmaVersion() { + var _a; + return (_a = this._options.ecmaVersion) !== null && _a !== void 0 ? _a : latestEcmaVersion; + } + onLiteralEnter(start) { + if (this._options.onLiteralEnter) { + this._options.onLiteralEnter(start); + } + } + onLiteralLeave(start, end) { + if (this._options.onLiteralLeave) { + this._options.onLiteralLeave(start, end); + } + } + onRegExpFlags(start, end, flags) { + if (this._options.onRegExpFlags) { + this._options.onRegExpFlags(start, end, flags); + } + if (this._options.onFlags) { + this._options.onFlags(start, end, flags.global, flags.ignoreCase, flags.multiline, flags.unicode, flags.sticky, flags.dotAll, flags.hasIndices); + } + } + onPatternEnter(start) { + if (this._options.onPatternEnter) { + this._options.onPatternEnter(start); + } + } + onPatternLeave(start, end) { + if (this._options.onPatternLeave) { + this._options.onPatternLeave(start, end); + } + } + onDisjunctionEnter(start) { + if (this._options.onDisjunctionEnter) { + this._options.onDisjunctionEnter(start); + } + } + onDisjunctionLeave(start, end) { + if (this._options.onDisjunctionLeave) { + this._options.onDisjunctionLeave(start, end); + } + } + onAlternativeEnter(start, index) { + if (this._options.onAlternativeEnter) { + this._options.onAlternativeEnter(start, index); + } + } + onAlternativeLeave(start, end, index) { + if (this._options.onAlternativeLeave) { + this._options.onAlternativeLeave(start, end, index); + } + } + onGroupEnter(start) { + if (this._options.onGroupEnter) { + this._options.onGroupEnter(start); + } + } + onGroupLeave(start, end) { + if (this._options.onGroupLeave) { + this._options.onGroupLeave(start, end); + } + } + onModifiersEnter(start) { + if (this._options.onModifiersEnter) { + this._options.onModifiersEnter(start); + } + } + onModifiersLeave(start, end) { + if (this._options.onModifiersLeave) { + this._options.onModifiersLeave(start, end); + } + } + onAddModifiers(start, end, flags) { + if (this._options.onAddModifiers) { + this._options.onAddModifiers(start, end, flags); + } + } + onRemoveModifiers(start, end, flags) { + if (this._options.onRemoveModifiers) { + this._options.onRemoveModifiers(start, end, flags); + } + } + onCapturingGroupEnter(start, name) { + if (this._options.onCapturingGroupEnter) { + this._options.onCapturingGroupEnter(start, name); + } + } + onCapturingGroupLeave(start, end, name) { + if (this._options.onCapturingGroupLeave) { + this._options.onCapturingGroupLeave(start, end, name); + } + } + onQuantifier(start, end, min, max, greedy) { + if (this._options.onQuantifier) { + this._options.onQuantifier(start, end, min, max, greedy); + } + } + onLookaroundAssertionEnter(start, kind, negate) { + if (this._options.onLookaroundAssertionEnter) { + this._options.onLookaroundAssertionEnter(start, kind, negate); + } + } + onLookaroundAssertionLeave(start, end, kind, negate) { + if (this._options.onLookaroundAssertionLeave) { + this._options.onLookaroundAssertionLeave(start, end, kind, negate); + } + } + onEdgeAssertion(start, end, kind) { + if (this._options.onEdgeAssertion) { + this._options.onEdgeAssertion(start, end, kind); + } + } + onWordBoundaryAssertion(start, end, kind, negate) { + if (this._options.onWordBoundaryAssertion) { + this._options.onWordBoundaryAssertion(start, end, kind, negate); + } + } + onAnyCharacterSet(start, end, kind) { + if (this._options.onAnyCharacterSet) { + this._options.onAnyCharacterSet(start, end, kind); + } + } + onEscapeCharacterSet(start, end, kind, negate) { + if (this._options.onEscapeCharacterSet) { + this._options.onEscapeCharacterSet(start, end, kind, negate); + } + } + onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings) { + if (this._options.onUnicodePropertyCharacterSet) { + this._options.onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings); + } + } + onCharacter(start, end, value) { + if (this._options.onCharacter) { + this._options.onCharacter(start, end, value); + } + } + onBackreference(start, end, ref) { + if (this._options.onBackreference) { + this._options.onBackreference(start, end, ref); + } + } + onCharacterClassEnter(start, negate, unicodeSets) { + if (this._options.onCharacterClassEnter) { + this._options.onCharacterClassEnter(start, negate, unicodeSets); + } + } + onCharacterClassLeave(start, end, negate) { + if (this._options.onCharacterClassLeave) { + this._options.onCharacterClassLeave(start, end, negate); + } + } + onCharacterClassRange(start, end, min, max) { + if (this._options.onCharacterClassRange) { + this._options.onCharacterClassRange(start, end, min, max); + } + } + onClassIntersection(start, end) { + if (this._options.onClassIntersection) { + this._options.onClassIntersection(start, end); + } + } + onClassSubtraction(start, end) { + if (this._options.onClassSubtraction) { + this._options.onClassSubtraction(start, end); + } + } + onClassStringDisjunctionEnter(start) { + if (this._options.onClassStringDisjunctionEnter) { + this._options.onClassStringDisjunctionEnter(start); + } + } + onClassStringDisjunctionLeave(start, end) { + if (this._options.onClassStringDisjunctionLeave) { + this._options.onClassStringDisjunctionLeave(start, end); + } + } + onStringAlternativeEnter(start, index) { + if (this._options.onStringAlternativeEnter) { + this._options.onStringAlternativeEnter(start, index); + } + } + onStringAlternativeLeave(start, end, index) { + if (this._options.onStringAlternativeLeave) { + this._options.onStringAlternativeLeave(start, end, index); + } + } + get index() { + return this._reader.index; + } + get currentCodePoint() { + return this._reader.currentCodePoint; + } + get nextCodePoint() { + return this._reader.nextCodePoint; + } + get nextCodePoint2() { + return this._reader.nextCodePoint2; + } + get nextCodePoint3() { + return this._reader.nextCodePoint3; + } + reset(source, start, end) { + this._reader.reset(source, start, end, this._unicodeMode); + } + rewind(index) { + this._reader.rewind(index); + } + advance() { + this._reader.advance(); + } + eat(cp) { + return this._reader.eat(cp); + } + eat2(cp1, cp2) { + return this._reader.eat2(cp1, cp2); + } + eat3(cp1, cp2, cp3) { + return this._reader.eat3(cp1, cp2, cp3); + } + raise(message, context) { + var _a, _b, _c; + throw newRegExpSyntaxError(this._srcCtx, { + unicode: (_a = context === null || context === void 0 ? void 0 : context.unicode) !== null && _a !== void 0 ? _a : (this._unicodeMode && !this._unicodeSetsMode), + unicodeSets: (_b = context === null || context === void 0 ? void 0 : context.unicodeSets) !== null && _b !== void 0 ? _b : this._unicodeSetsMode, + }, (_c = context === null || context === void 0 ? void 0 : context.index) !== null && _c !== void 0 ? _c : this.index, message); + } + eatRegExpBody() { + const start = this.index; + let inClass = false; + let escaped = false; + for (;;) { + const cp = this.currentCodePoint; + if (cp === -1 || isLineTerminator(cp)) { + const kind = inClass ? "character class" : "regular expression"; + this.raise(`Unterminated ${kind}`); + } + if (escaped) { + escaped = false; + } + else if (cp === REVERSE_SOLIDUS) { + escaped = true; + } + else if (cp === LEFT_SQUARE_BRACKET) { + inClass = true; + } + else if (cp === RIGHT_SQUARE_BRACKET) { + inClass = false; + } + else if ((cp === SOLIDUS && !inClass) || + (cp === ASTERISK && this.index === start)) { + break; + } + this.advance(); + } + return this.index !== start; + } + consumePattern() { + const start = this.index; + this._numCapturingParens = this.countCapturingParens(); + this._groupSpecifiers.clear(); + this._backreferenceNames.clear(); + this.onPatternEnter(start); + this.consumeDisjunction(); + const cp = this.currentCodePoint; + if (this.currentCodePoint !== -1) { + if (cp === RIGHT_PARENTHESIS) { + this.raise("Unmatched ')'"); + } + if (cp === REVERSE_SOLIDUS) { + this.raise("\\ at end of pattern"); + } + if (cp === RIGHT_SQUARE_BRACKET || cp === RIGHT_CURLY_BRACKET) { + this.raise("Lone quantifier brackets"); + } + const c = String.fromCodePoint(cp); + this.raise(`Unexpected character '${c}'`); + } + for (const name of this._backreferenceNames) { + if (!this._groupSpecifiers.hasInPattern(name)) { + this.raise("Invalid named capture referenced"); + } + } + this.onPatternLeave(start, this.index); + } + countCapturingParens() { + const start = this.index; + let inClass = false; + let escaped = false; + let count = 0; + let cp = 0; + while ((cp = this.currentCodePoint) !== -1) { + if (escaped) { + escaped = false; + } + else if (cp === REVERSE_SOLIDUS) { + escaped = true; + } + else if (cp === LEFT_SQUARE_BRACKET) { + inClass = true; + } + else if (cp === RIGHT_SQUARE_BRACKET) { + inClass = false; + } + else if (cp === LEFT_PARENTHESIS && + !inClass && + (this.nextCodePoint !== QUESTION_MARK || + (this.nextCodePoint2 === LESS_THAN_SIGN && + this.nextCodePoint3 !== EQUALS_SIGN && + this.nextCodePoint3 !== EXCLAMATION_MARK))) { + count += 1; + } + this.advance(); + } + this.rewind(start); + return count; + } + consumeDisjunction() { + const start = this.index; + let i = 0; + this._groupSpecifiers.enterDisjunction(); + this.onDisjunctionEnter(start); + do { + this.consumeAlternative(i++); + } while (this.eat(VERTICAL_LINE)); + if (this.consumeQuantifier(true)) { + this.raise("Nothing to repeat"); + } + if (this.eat(LEFT_CURLY_BRACKET)) { + this.raise("Lone quantifier brackets"); + } + this.onDisjunctionLeave(start, this.index); + this._groupSpecifiers.leaveDisjunction(); + } + consumeAlternative(i) { + const start = this.index; + this._groupSpecifiers.enterAlternative(i); + this.onAlternativeEnter(start, i); + while (this.currentCodePoint !== -1 && this.consumeTerm()) { + } + this.onAlternativeLeave(start, this.index, i); + } + consumeTerm() { + if (this._unicodeMode || this.strict) { + return (this.consumeAssertion() || + (this.consumeAtom() && this.consumeOptionalQuantifier())); + } + return ((this.consumeAssertion() && + (!this._lastAssertionIsQuantifiable || + this.consumeOptionalQuantifier())) || + (this.consumeExtendedAtom() && this.consumeOptionalQuantifier())); + } + consumeOptionalQuantifier() { + this.consumeQuantifier(); + return true; + } + consumeAssertion() { + const start = this.index; + this._lastAssertionIsQuantifiable = false; + if (this.eat(CIRCUMFLEX_ACCENT)) { + this.onEdgeAssertion(start, this.index, "start"); + return true; + } + if (this.eat(DOLLAR_SIGN)) { + this.onEdgeAssertion(start, this.index, "end"); + return true; + } + if (this.eat2(REVERSE_SOLIDUS, LATIN_CAPITAL_LETTER_B)) { + this.onWordBoundaryAssertion(start, this.index, "word", true); + return true; + } + if (this.eat2(REVERSE_SOLIDUS, LATIN_SMALL_LETTER_B)) { + this.onWordBoundaryAssertion(start, this.index, "word", false); + return true; + } + if (this.eat2(LEFT_PARENTHESIS, QUESTION_MARK)) { + const lookbehind = this.ecmaVersion >= 2018 && this.eat(LESS_THAN_SIGN); + let negate = false; + if (this.eat(EQUALS_SIGN) || + (negate = this.eat(EXCLAMATION_MARK))) { + const kind = lookbehind ? "lookbehind" : "lookahead"; + this.onLookaroundAssertionEnter(start, kind, negate); + this.consumeDisjunction(); + if (!this.eat(RIGHT_PARENTHESIS)) { + this.raise("Unterminated group"); + } + this._lastAssertionIsQuantifiable = !lookbehind && !this.strict; + this.onLookaroundAssertionLeave(start, this.index, kind, negate); + return true; + } + this.rewind(start); + } + return false; + } + consumeQuantifier(noConsume = false) { + const start = this.index; + let min = 0; + let max = 0; + let greedy = false; + if (this.eat(ASTERISK)) { + min = 0; + max = Number.POSITIVE_INFINITY; + } + else if (this.eat(PLUS_SIGN)) { + min = 1; + max = Number.POSITIVE_INFINITY; + } + else if (this.eat(QUESTION_MARK)) { + min = 0; + max = 1; + } + else if (this.eatBracedQuantifier(noConsume)) { + ({ min, max } = this._lastRange); + } + else { + return false; + } + greedy = !this.eat(QUESTION_MARK); + if (!noConsume) { + this.onQuantifier(start, this.index, min, max, greedy); + } + return true; + } + eatBracedQuantifier(noError) { + const start = this.index; + if (this.eat(LEFT_CURLY_BRACKET)) { + if (this.eatDecimalDigits()) { + const min = this._lastIntValue; + let max = min; + if (this.eat(COMMA)) { + max = this.eatDecimalDigits() + ? this._lastIntValue + : Number.POSITIVE_INFINITY; + } + if (this.eat(RIGHT_CURLY_BRACKET)) { + if (!noError && max < min) { + this.raise("numbers out of order in {} quantifier"); + } + this._lastRange = { min, max }; + return true; + } + } + if (!noError && (this._unicodeMode || this.strict)) { + this.raise("Incomplete quantifier"); + } + this.rewind(start); + } + return false; + } + consumeAtom() { + return (this.consumePatternCharacter() || + this.consumeDot() || + this.consumeReverseSolidusAtomEscape() || + Boolean(this.consumeCharacterClass()) || + this.consumeCapturingGroup() || + this.consumeUncapturingGroup()); + } + consumeDot() { + if (this.eat(FULL_STOP)) { + this.onAnyCharacterSet(this.index - 1, this.index, "any"); + return true; + } + return false; + } + consumeReverseSolidusAtomEscape() { + const start = this.index; + if (this.eat(REVERSE_SOLIDUS)) { + if (this.consumeAtomEscape()) { + return true; + } + this.rewind(start); + } + return false; + } + consumeUncapturingGroup() { + const start = this.index; + if (this.eat2(LEFT_PARENTHESIS, QUESTION_MARK)) { + this.onGroupEnter(start); + if (this.ecmaVersion >= 2025) { + this.consumeModifiers(); + } + if (!this.eat(COLON)) { + this.rewind(start + 1); + this.raise("Invalid group"); + } + this.consumeDisjunction(); + if (!this.eat(RIGHT_PARENTHESIS)) { + this.raise("Unterminated group"); + } + this.onGroupLeave(start, this.index); + return true; + } + return false; + } + consumeModifiers() { + const start = this.index; + const hasAddModifiers = this.eatModifiers(); + const addModifiersEnd = this.index; + const hasHyphen = this.eat(HYPHEN_MINUS); + if (!hasAddModifiers && !hasHyphen) { + return false; + } + this.onModifiersEnter(start); + const addModifiers = this.parseModifiers(start, addModifiersEnd); + this.onAddModifiers(start, addModifiersEnd, addModifiers); + if (hasHyphen) { + const modifiersStart = this.index; + if (!this.eatModifiers() && + !hasAddModifiers && + this.currentCodePoint === COLON) { + this.raise("Invalid empty flags"); + } + const modifiers = this.parseModifiers(modifiersStart, this.index); + for (const [flagName] of Object.entries(modifiers).filter(([, enable]) => enable)) { + if (addModifiers[flagName]) { + this.raise(`Duplicated flag '${String.fromCodePoint(FLAG_PROP_TO_CODEPOINT[flagName])}'`); + } + } + this.onRemoveModifiers(modifiersStart, this.index, modifiers); + } + this.onModifiersLeave(start, this.index); + return true; + } + consumeCapturingGroup() { + const start = this.index; + if (this.eat(LEFT_PARENTHESIS)) { + let name = null; + if (this.ecmaVersion >= 2018) { + if (this.consumeGroupSpecifier()) { + name = this._lastStrValue; + } + else if (this.currentCodePoint === QUESTION_MARK) { + this.rewind(start); + return false; + } + } + else if (this.currentCodePoint === QUESTION_MARK) { + this.rewind(start); + return false; + } + this.onCapturingGroupEnter(start, name); + this.consumeDisjunction(); + if (!this.eat(RIGHT_PARENTHESIS)) { + this.raise("Unterminated group"); + } + this.onCapturingGroupLeave(start, this.index, name); + return true; + } + return false; + } + consumeExtendedAtom() { + return (this.consumeDot() || + this.consumeReverseSolidusAtomEscape() || + this.consumeReverseSolidusFollowedByC() || + Boolean(this.consumeCharacterClass()) || + this.consumeCapturingGroup() || + this.consumeUncapturingGroup() || + this.consumeInvalidBracedQuantifier() || + this.consumeExtendedPatternCharacter()); + } + consumeReverseSolidusFollowedByC() { + const start = this.index; + if (this.currentCodePoint === REVERSE_SOLIDUS && + this.nextCodePoint === LATIN_SMALL_LETTER_C) { + this._lastIntValue = this.currentCodePoint; + this.advance(); + this.onCharacter(start, this.index, REVERSE_SOLIDUS); + return true; + } + return false; + } + consumeInvalidBracedQuantifier() { + if (this.eatBracedQuantifier(true)) { + this.raise("Nothing to repeat"); + } + return false; + } + consumePatternCharacter() { + const start = this.index; + const cp = this.currentCodePoint; + if (cp !== -1 && !isSyntaxCharacter(cp)) { + this.advance(); + this.onCharacter(start, this.index, cp); + return true; + } + return false; + } + consumeExtendedPatternCharacter() { + const start = this.index; + const cp = this.currentCodePoint; + if (cp !== -1 && + cp !== CIRCUMFLEX_ACCENT && + cp !== DOLLAR_SIGN && + cp !== REVERSE_SOLIDUS && + cp !== FULL_STOP && + cp !== ASTERISK && + cp !== PLUS_SIGN && + cp !== QUESTION_MARK && + cp !== LEFT_PARENTHESIS && + cp !== RIGHT_PARENTHESIS && + cp !== LEFT_SQUARE_BRACKET && + cp !== VERTICAL_LINE) { + this.advance(); + this.onCharacter(start, this.index, cp); + return true; + } + return false; + } + consumeGroupSpecifier() { + const start = this.index; + if (this.eat(QUESTION_MARK)) { + if (this.eatGroupName()) { + if (!this._groupSpecifiers.hasInScope(this._lastStrValue)) { + this._groupSpecifiers.addToScope(this._lastStrValue); + return true; + } + this.raise("Duplicate capture group name"); + } + this.rewind(start); + } + return false; + } + consumeAtomEscape() { + if (this.consumeBackreference() || + this.consumeCharacterClassEscape() || + this.consumeCharacterEscape() || + (this._nFlag && this.consumeKGroupName())) { + return true; + } + if (this.strict || this._unicodeMode) { + this.raise("Invalid escape"); + } + return false; + } + consumeBackreference() { + const start = this.index; + if (this.eatDecimalEscape()) { + const n = this._lastIntValue; + if (n <= this._numCapturingParens) { + this.onBackreference(start - 1, this.index, n); + return true; + } + if (this.strict || this._unicodeMode) { + this.raise("Invalid escape"); + } + this.rewind(start); + } + return false; + } + consumeCharacterClassEscape() { + var _a; + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_D)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "digit", false); + return {}; + } + if (this.eat(LATIN_CAPITAL_LETTER_D)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "digit", true); + return {}; + } + if (this.eat(LATIN_SMALL_LETTER_S)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "space", false); + return {}; + } + if (this.eat(LATIN_CAPITAL_LETTER_S)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "space", true); + return {}; + } + if (this.eat(LATIN_SMALL_LETTER_W)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "word", false); + return {}; + } + if (this.eat(LATIN_CAPITAL_LETTER_W)) { + this._lastIntValue = -1; + this.onEscapeCharacterSet(start - 1, this.index, "word", true); + return {}; + } + let negate = false; + if (this._unicodeMode && + this.ecmaVersion >= 2018 && + (this.eat(LATIN_SMALL_LETTER_P) || + (negate = this.eat(LATIN_CAPITAL_LETTER_P)))) { + this._lastIntValue = -1; + let result = null; + if (this.eat(LEFT_CURLY_BRACKET) && + (result = this.eatUnicodePropertyValueExpression()) && + this.eat(RIGHT_CURLY_BRACKET)) { + if (negate && result.strings) { + this.raise("Invalid property name"); + } + this.onUnicodePropertyCharacterSet(start - 1, this.index, "property", result.key, result.value, negate, (_a = result.strings) !== null && _a !== void 0 ? _a : false); + return { mayContainStrings: result.strings }; + } + this.raise("Invalid property name"); + } + return null; + } + consumeCharacterEscape() { + const start = this.index; + if (this.eatControlEscape() || + this.eatCControlLetter() || + this.eatZero() || + this.eatHexEscapeSequence() || + this.eatRegExpUnicodeEscapeSequence() || + (!this.strict && + !this._unicodeMode && + this.eatLegacyOctalEscapeSequence()) || + this.eatIdentityEscape()) { + this.onCharacter(start - 1, this.index, this._lastIntValue); + return true; + } + return false; + } + consumeKGroupName() { + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_K)) { + if (this.eatGroupName()) { + const groupName = this._lastStrValue; + this._backreferenceNames.add(groupName); + this.onBackreference(start - 1, this.index, groupName); + return true; + } + this.raise("Invalid named reference"); + } + return false; + } + consumeCharacterClass() { + const start = this.index; + if (this.eat(LEFT_SQUARE_BRACKET)) { + const negate = this.eat(CIRCUMFLEX_ACCENT); + this.onCharacterClassEnter(start, negate, this._unicodeSetsMode); + const result = this.consumeClassContents(); + if (!this.eat(RIGHT_SQUARE_BRACKET)) { + if (this.currentCodePoint === -1) { + this.raise("Unterminated character class"); + } + this.raise("Invalid character in character class"); + } + if (negate && result.mayContainStrings) { + this.raise("Negated character class may contain strings"); + } + this.onCharacterClassLeave(start, this.index, negate); + return result; + } + return null; + } + consumeClassContents() { + if (this._unicodeSetsMode) { + if (this.currentCodePoint === RIGHT_SQUARE_BRACKET) { + return {}; + } + const result = this.consumeClassSetExpression(); + return result; + } + const strict = this.strict || this._unicodeMode; + for (;;) { + const rangeStart = this.index; + if (!this.consumeClassAtom()) { + break; + } + const min = this._lastIntValue; + if (!this.eat(HYPHEN_MINUS)) { + continue; + } + this.onCharacter(this.index - 1, this.index, HYPHEN_MINUS); + if (!this.consumeClassAtom()) { + break; + } + const max = this._lastIntValue; + if (min === -1 || max === -1) { + if (strict) { + this.raise("Invalid character class"); + } + continue; + } + if (min > max) { + this.raise("Range out of order in character class"); + } + this.onCharacterClassRange(rangeStart, this.index, min, max); + } + return {}; + } + consumeClassAtom() { + const start = this.index; + const cp = this.currentCodePoint; + if (cp !== -1 && + cp !== REVERSE_SOLIDUS && + cp !== RIGHT_SQUARE_BRACKET) { + this.advance(); + this._lastIntValue = cp; + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + if (this.eat(REVERSE_SOLIDUS)) { + if (this.consumeClassEscape()) { + return true; + } + if (!this.strict && + this.currentCodePoint === LATIN_SMALL_LETTER_C) { + this._lastIntValue = REVERSE_SOLIDUS; + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + if (this.strict || this._unicodeMode) { + this.raise("Invalid escape"); + } + this.rewind(start); + } + return false; + } + consumeClassEscape() { + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_B)) { + this._lastIntValue = BACKSPACE; + this.onCharacter(start - 1, this.index, this._lastIntValue); + return true; + } + if (this._unicodeMode && this.eat(HYPHEN_MINUS)) { + this._lastIntValue = HYPHEN_MINUS; + this.onCharacter(start - 1, this.index, this._lastIntValue); + return true; + } + let cp = 0; + if (!this.strict && + !this._unicodeMode && + this.currentCodePoint === LATIN_SMALL_LETTER_C && + (isDecimalDigit((cp = this.nextCodePoint)) || cp === LOW_LINE)) { + this.advance(); + this.advance(); + this._lastIntValue = cp % 0x20; + this.onCharacter(start - 1, this.index, this._lastIntValue); + return true; + } + return (Boolean(this.consumeCharacterClassEscape()) || + this.consumeCharacterEscape()); + } + consumeClassSetExpression() { + const start = this.index; + let mayContainStrings = false; + let result = null; + if (this.consumeClassSetCharacter()) { + if (this.consumeClassSetRangeFromOperator(start)) { + this.consumeClassUnionRight({}); + return {}; + } + mayContainStrings = false; + } + else if ((result = this.consumeClassSetOperand())) { + mayContainStrings = result.mayContainStrings; + } + else { + const cp = this.currentCodePoint; + if (cp === REVERSE_SOLIDUS) { + this.advance(); + this.raise("Invalid escape"); + } + if (cp === this.nextCodePoint && + isClassSetReservedDoublePunctuatorCharacter(cp)) { + this.raise("Invalid set operation in character class"); + } + this.raise("Invalid character in character class"); + } + if (this.eat2(AMPERSAND, AMPERSAND)) { + while (this.currentCodePoint !== AMPERSAND && + (result = this.consumeClassSetOperand())) { + this.onClassIntersection(start, this.index); + if (!result.mayContainStrings) { + mayContainStrings = false; + } + if (this.eat2(AMPERSAND, AMPERSAND)) { + continue; + } + return { mayContainStrings }; + } + this.raise("Invalid character in character class"); + } + if (this.eat2(HYPHEN_MINUS, HYPHEN_MINUS)) { + while (this.consumeClassSetOperand()) { + this.onClassSubtraction(start, this.index); + if (this.eat2(HYPHEN_MINUS, HYPHEN_MINUS)) { + continue; + } + return { mayContainStrings }; + } + this.raise("Invalid character in character class"); + } + return this.consumeClassUnionRight({ mayContainStrings }); + } + consumeClassUnionRight(leftResult) { + let mayContainStrings = leftResult.mayContainStrings; + for (;;) { + const start = this.index; + if (this.consumeClassSetCharacter()) { + this.consumeClassSetRangeFromOperator(start); + continue; + } + const result = this.consumeClassSetOperand(); + if (result) { + if (result.mayContainStrings) { + mayContainStrings = true; + } + continue; + } + break; + } + return { mayContainStrings }; + } + consumeClassSetRangeFromOperator(start) { + const currentStart = this.index; + const min = this._lastIntValue; + if (this.eat(HYPHEN_MINUS)) { + if (this.consumeClassSetCharacter()) { + const max = this._lastIntValue; + if (min === -1 || max === -1) { + this.raise("Invalid character class"); + } + if (min > max) { + this.raise("Range out of order in character class"); + } + this.onCharacterClassRange(start, this.index, min, max); + return true; + } + this.rewind(currentStart); + } + return false; + } + consumeClassSetOperand() { + let result = null; + if ((result = this.consumeNestedClass())) { + return result; + } + if ((result = this.consumeClassStringDisjunction())) { + return result; + } + if (this.consumeClassSetCharacter()) { + return {}; + } + return null; + } + consumeNestedClass() { + const start = this.index; + if (this.eat(LEFT_SQUARE_BRACKET)) { + const negate = this.eat(CIRCUMFLEX_ACCENT); + this.onCharacterClassEnter(start, negate, true); + const result = this.consumeClassContents(); + if (!this.eat(RIGHT_SQUARE_BRACKET)) { + this.raise("Unterminated character class"); + } + if (negate && result.mayContainStrings) { + this.raise("Negated character class may contain strings"); + } + this.onCharacterClassLeave(start, this.index, negate); + return result; + } + if (this.eat(REVERSE_SOLIDUS)) { + const result = this.consumeCharacterClassEscape(); + if (result) { + return result; + } + this.rewind(start); + } + return null; + } + consumeClassStringDisjunction() { + const start = this.index; + if (this.eat3(REVERSE_SOLIDUS, LATIN_SMALL_LETTER_Q, LEFT_CURLY_BRACKET)) { + this.onClassStringDisjunctionEnter(start); + let i = 0; + let mayContainStrings = false; + do { + if (this.consumeClassString(i++).mayContainStrings) { + mayContainStrings = true; + } + } while (this.eat(VERTICAL_LINE)); + if (this.eat(RIGHT_CURLY_BRACKET)) { + this.onClassStringDisjunctionLeave(start, this.index); + return { mayContainStrings }; + } + this.raise("Unterminated class string disjunction"); + } + return null; + } + consumeClassString(i) { + const start = this.index; + let count = 0; + this.onStringAlternativeEnter(start, i); + while (this.currentCodePoint !== -1 && + this.consumeClassSetCharacter()) { + count++; + } + this.onStringAlternativeLeave(start, this.index, i); + return { mayContainStrings: count !== 1 }; + } + consumeClassSetCharacter() { + const start = this.index; + const cp = this.currentCodePoint; + if (cp !== this.nextCodePoint || + !isClassSetReservedDoublePunctuatorCharacter(cp)) { + if (cp !== -1 && !isClassSetSyntaxCharacter(cp)) { + this._lastIntValue = cp; + this.advance(); + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + } + if (this.eat(REVERSE_SOLIDUS)) { + if (this.consumeCharacterEscape()) { + return true; + } + if (isClassSetReservedPunctuator(this.currentCodePoint)) { + this._lastIntValue = this.currentCodePoint; + this.advance(); + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + if (this.eat(LATIN_SMALL_LETTER_B)) { + this._lastIntValue = BACKSPACE; + this.onCharacter(start, this.index, this._lastIntValue); + return true; + } + this.rewind(start); + } + return false; + } + eatGroupName() { + if (this.eat(LESS_THAN_SIGN)) { + if (this.eatRegExpIdentifierName() && this.eat(GREATER_THAN_SIGN)) { + return true; + } + this.raise("Invalid capture group name"); + } + return false; + } + eatRegExpIdentifierName() { + if (this.eatRegExpIdentifierStart()) { + this._lastStrValue = String.fromCodePoint(this._lastIntValue); + while (this.eatRegExpIdentifierPart()) { + this._lastStrValue += String.fromCodePoint(this._lastIntValue); + } + return true; + } + return false; + } + eatRegExpIdentifierStart() { + const start = this.index; + const forceUFlag = !this._unicodeMode && this.ecmaVersion >= 2020; + let cp = this.currentCodePoint; + this.advance(); + if (cp === REVERSE_SOLIDUS && + this.eatRegExpUnicodeEscapeSequence(forceUFlag)) { + cp = this._lastIntValue; + } + else if (forceUFlag && + isLeadSurrogate(cp) && + isTrailSurrogate(this.currentCodePoint)) { + cp = combineSurrogatePair(cp, this.currentCodePoint); + this.advance(); + } + if (isIdentifierStartChar(cp)) { + this._lastIntValue = cp; + return true; + } + if (this.index !== start) { + this.rewind(start); + } + return false; + } + eatRegExpIdentifierPart() { + const start = this.index; + const forceUFlag = !this._unicodeMode && this.ecmaVersion >= 2020; + let cp = this.currentCodePoint; + this.advance(); + if (cp === REVERSE_SOLIDUS && + this.eatRegExpUnicodeEscapeSequence(forceUFlag)) { + cp = this._lastIntValue; + } + else if (forceUFlag && + isLeadSurrogate(cp) && + isTrailSurrogate(this.currentCodePoint)) { + cp = combineSurrogatePair(cp, this.currentCodePoint); + this.advance(); + } + if (isIdentifierPartChar(cp)) { + this._lastIntValue = cp; + return true; + } + if (this.index !== start) { + this.rewind(start); + } + return false; + } + eatCControlLetter() { + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_C)) { + if (this.eatControlLetter()) { + return true; + } + this.rewind(start); + } + return false; + } + eatZero() { + if (this.currentCodePoint === DIGIT_ZERO && + !isDecimalDigit(this.nextCodePoint)) { + this._lastIntValue = 0; + this.advance(); + return true; + } + return false; + } + eatControlEscape() { + if (this.eat(LATIN_SMALL_LETTER_F)) { + this._lastIntValue = FORM_FEED; + return true; + } + if (this.eat(LATIN_SMALL_LETTER_N)) { + this._lastIntValue = LINE_FEED; + return true; + } + if (this.eat(LATIN_SMALL_LETTER_R)) { + this._lastIntValue = CARRIAGE_RETURN; + return true; + } + if (this.eat(LATIN_SMALL_LETTER_T)) { + this._lastIntValue = CHARACTER_TABULATION; + return true; + } + if (this.eat(LATIN_SMALL_LETTER_V)) { + this._lastIntValue = LINE_TABULATION; + return true; + } + return false; + } + eatControlLetter() { + const cp = this.currentCodePoint; + if (isLatinLetter(cp)) { + this.advance(); + this._lastIntValue = cp % 0x20; + return true; + } + return false; + } + eatRegExpUnicodeEscapeSequence(forceUFlag = false) { + const start = this.index; + const uFlag = forceUFlag || this._unicodeMode; + if (this.eat(LATIN_SMALL_LETTER_U)) { + if ((uFlag && this.eatRegExpUnicodeSurrogatePairEscape()) || + this.eatFixedHexDigits(4) || + (uFlag && this.eatRegExpUnicodeCodePointEscape())) { + return true; + } + if (this.strict || uFlag) { + this.raise("Invalid unicode escape"); + } + this.rewind(start); + } + return false; + } + eatRegExpUnicodeSurrogatePairEscape() { + const start = this.index; + if (this.eatFixedHexDigits(4)) { + const lead = this._lastIntValue; + if (isLeadSurrogate(lead) && + this.eat(REVERSE_SOLIDUS) && + this.eat(LATIN_SMALL_LETTER_U) && + this.eatFixedHexDigits(4)) { + const trail = this._lastIntValue; + if (isTrailSurrogate(trail)) { + this._lastIntValue = combineSurrogatePair(lead, trail); + return true; + } + } + this.rewind(start); + } + return false; + } + eatRegExpUnicodeCodePointEscape() { + const start = this.index; + if (this.eat(LEFT_CURLY_BRACKET) && + this.eatHexDigits() && + this.eat(RIGHT_CURLY_BRACKET) && + isValidUnicode(this._lastIntValue)) { + return true; + } + this.rewind(start); + return false; + } + eatIdentityEscape() { + const cp = this.currentCodePoint; + if (this.isValidIdentityEscape(cp)) { + this._lastIntValue = cp; + this.advance(); + return true; + } + return false; + } + isValidIdentityEscape(cp) { + if (cp === -1) { + return false; + } + if (this._unicodeMode) { + return isSyntaxCharacter(cp) || cp === SOLIDUS; + } + if (this.strict) { + return !isIdContinue(cp); + } + if (this._nFlag) { + return !(cp === LATIN_SMALL_LETTER_C || cp === LATIN_SMALL_LETTER_K); + } + return cp !== LATIN_SMALL_LETTER_C; + } + eatDecimalEscape() { + this._lastIntValue = 0; + let cp = this.currentCodePoint; + if (cp >= DIGIT_ONE && cp <= DIGIT_NINE) { + do { + this._lastIntValue = 10 * this._lastIntValue + (cp - DIGIT_ZERO); + this.advance(); + } while ((cp = this.currentCodePoint) >= DIGIT_ZERO && + cp <= DIGIT_NINE); + return true; + } + return false; + } + eatUnicodePropertyValueExpression() { + const start = this.index; + if (this.eatUnicodePropertyName() && this.eat(EQUALS_SIGN)) { + const key = this._lastStrValue; + if (this.eatUnicodePropertyValue()) { + const value = this._lastStrValue; + if (isValidUnicodeProperty(this.ecmaVersion, key, value)) { + return { + key, + value: value || null, + }; + } + this.raise("Invalid property name"); + } + } + this.rewind(start); + if (this.eatLoneUnicodePropertyNameOrValue()) { + const nameOrValue = this._lastStrValue; + if (isValidUnicodeProperty(this.ecmaVersion, "General_Category", nameOrValue)) { + return { + key: "General_Category", + value: nameOrValue || null, + }; + } + if (isValidLoneUnicodeProperty(this.ecmaVersion, nameOrValue)) { + return { + key: nameOrValue, + value: null, + }; + } + if (this._unicodeSetsMode && + isValidLoneUnicodePropertyOfString(this.ecmaVersion, nameOrValue)) { + return { + key: nameOrValue, + value: null, + strings: true, + }; + } + this.raise("Invalid property name"); + } + return null; + } + eatUnicodePropertyName() { + this._lastStrValue = ""; + while (isUnicodePropertyNameCharacter(this.currentCodePoint)) { + this._lastStrValue += String.fromCodePoint(this.currentCodePoint); + this.advance(); + } + return this._lastStrValue !== ""; + } + eatUnicodePropertyValue() { + this._lastStrValue = ""; + while (isUnicodePropertyValueCharacter(this.currentCodePoint)) { + this._lastStrValue += String.fromCodePoint(this.currentCodePoint); + this.advance(); + } + return this._lastStrValue !== ""; + } + eatLoneUnicodePropertyNameOrValue() { + return this.eatUnicodePropertyValue(); + } + eatHexEscapeSequence() { + const start = this.index; + if (this.eat(LATIN_SMALL_LETTER_X)) { + if (this.eatFixedHexDigits(2)) { + return true; + } + if (this._unicodeMode || this.strict) { + this.raise("Invalid escape"); + } + this.rewind(start); + } + return false; + } + eatDecimalDigits() { + const start = this.index; + this._lastIntValue = 0; + while (isDecimalDigit(this.currentCodePoint)) { + this._lastIntValue = + 10 * this._lastIntValue + digitToInt(this.currentCodePoint); + this.advance(); + } + return this.index !== start; + } + eatHexDigits() { + const start = this.index; + this._lastIntValue = 0; + while (isHexDigit(this.currentCodePoint)) { + this._lastIntValue = + 16 * this._lastIntValue + digitToInt(this.currentCodePoint); + this.advance(); + } + return this.index !== start; + } + eatLegacyOctalEscapeSequence() { + if (this.eatOctalDigit()) { + const n1 = this._lastIntValue; + if (this.eatOctalDigit()) { + const n2 = this._lastIntValue; + if (n1 <= 3 && this.eatOctalDigit()) { + this._lastIntValue = n1 * 64 + n2 * 8 + this._lastIntValue; + } + else { + this._lastIntValue = n1 * 8 + n2; + } + } + else { + this._lastIntValue = n1; + } + return true; + } + return false; + } + eatOctalDigit() { + const cp = this.currentCodePoint; + if (isOctalDigit(cp)) { + this.advance(); + this._lastIntValue = cp - DIGIT_ZERO; + return true; + } + this._lastIntValue = 0; + return false; + } + eatFixedHexDigits(length) { + const start = this.index; + this._lastIntValue = 0; + for (let i = 0; i < length; ++i) { + const cp = this.currentCodePoint; + if (!isHexDigit(cp)) { + this.rewind(start); + return false; + } + this._lastIntValue = 16 * this._lastIntValue + digitToInt(cp); + this.advance(); + } + return true; + } + eatModifiers() { + let ate = false; + while (isRegularExpressionModifier(this.currentCodePoint)) { + this.advance(); + ate = true; + } + return ate; + } + parseModifiers(start, end) { + const { ignoreCase, multiline, dotAll } = this.parseFlags(this._reader.source, start, end); + return { ignoreCase, multiline, dotAll }; + } + parseFlags(source, start, end) { + const flags = { + global: false, + ignoreCase: false, + multiline: false, + unicode: false, + sticky: false, + dotAll: false, + hasIndices: false, + unicodeSets: false, + }; + const validFlags = new Set(); + validFlags.add(LATIN_SMALL_LETTER_G); + validFlags.add(LATIN_SMALL_LETTER_I); + validFlags.add(LATIN_SMALL_LETTER_M); + if (this.ecmaVersion >= 2015) { + validFlags.add(LATIN_SMALL_LETTER_U); + validFlags.add(LATIN_SMALL_LETTER_Y); + if (this.ecmaVersion >= 2018) { + validFlags.add(LATIN_SMALL_LETTER_S); + if (this.ecmaVersion >= 2022) { + validFlags.add(LATIN_SMALL_LETTER_D); + if (this.ecmaVersion >= 2024) { + validFlags.add(LATIN_SMALL_LETTER_V); + } + } + } + } + for (let i = start; i < end; ++i) { + const flag = source.charCodeAt(i); + if (validFlags.has(flag)) { + const prop = FLAG_CODEPOINT_TO_PROP[flag]; + if (flags[prop]) { + this.raise(`Duplicated flag '${source[i]}'`, { + index: start, + }); + } + flags[prop] = true; + } + else { + this.raise(`Invalid flag '${source[i]}'`, { index: start }); + } + } + return flags; + } +} + +const DUMMY_PATTERN = {}; +const DUMMY_FLAGS = {}; +const DUMMY_CAPTURING_GROUP = {}; +function isClassSetOperand(node) { + return (node.type === "Character" || + node.type === "CharacterSet" || + node.type === "CharacterClass" || + node.type === "ExpressionCharacterClass" || + node.type === "ClassStringDisjunction"); +} +class RegExpParserState { + constructor(options) { + var _a; + this._node = DUMMY_PATTERN; + this._expressionBufferMap = new Map(); + this._flags = DUMMY_FLAGS; + this._backreferences = []; + this._capturingGroups = []; + this.source = ""; + this.strict = Boolean(options === null || options === void 0 ? void 0 : options.strict); + this.ecmaVersion = (_a = options === null || options === void 0 ? void 0 : options.ecmaVersion) !== null && _a !== void 0 ? _a : latestEcmaVersion; + } + get pattern() { + if (this._node.type !== "Pattern") { + throw new Error("UnknownError"); + } + return this._node; + } + get flags() { + if (this._flags.type !== "Flags") { + throw new Error("UnknownError"); + } + return this._flags; + } + onRegExpFlags(start, end, { global, ignoreCase, multiline, unicode, sticky, dotAll, hasIndices, unicodeSets, }) { + this._flags = { + type: "Flags", + parent: null, + start, + end, + raw: this.source.slice(start, end), + global, + ignoreCase, + multiline, + unicode, + sticky, + dotAll, + hasIndices, + unicodeSets, + }; + } + onPatternEnter(start) { + this._node = { + type: "Pattern", + parent: null, + start, + end: start, + raw: "", + alternatives: [], + }; + this._backreferences.length = 0; + this._capturingGroups.length = 0; + } + onPatternLeave(start, end) { + this._node.end = end; + this._node.raw = this.source.slice(start, end); + for (const reference of this._backreferences) { + const ref = reference.ref; + const groups = typeof ref === "number" + ? [this._capturingGroups[ref - 1]] + : this._capturingGroups.filter((g) => g.name === ref); + if (groups.length === 1) { + const group = groups[0]; + reference.ambiguous = false; + reference.resolved = group; + } + else { + reference.ambiguous = true; + reference.resolved = groups; + } + for (const group of groups) { + group.references.push(reference); + } + } + } + onAlternativeEnter(start) { + const parent = this._node; + if (parent.type !== "Assertion" && + parent.type !== "CapturingGroup" && + parent.type !== "Group" && + parent.type !== "Pattern") { + throw new Error("UnknownError"); + } + this._node = { + type: "Alternative", + parent, + start, + end: start, + raw: "", + elements: [], + }; + parent.alternatives.push(this._node); + } + onAlternativeLeave(start, end) { + const node = this._node; + if (node.type !== "Alternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onGroupEnter(start) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + const group = { + type: "Group", + parent, + start, + end: start, + raw: "", + modifiers: null, + alternatives: [], + }; + this._node = group; + parent.elements.push(this._node); + } + onGroupLeave(start, end) { + const node = this._node; + if (node.type !== "Group" || node.parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onModifiersEnter(start) { + const parent = this._node; + if (parent.type !== "Group") { + throw new Error("UnknownError"); + } + this._node = { + type: "Modifiers", + parent, + start, + end: start, + raw: "", + add: null, + remove: null, + }; + parent.modifiers = this._node; + } + onModifiersLeave(start, end) { + const node = this._node; + if (node.type !== "Modifiers" || node.parent.type !== "Group") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onAddModifiers(start, end, { ignoreCase, multiline, dotAll, }) { + const parent = this._node; + if (parent.type !== "Modifiers") { + throw new Error("UnknownError"); + } + parent.add = { + type: "ModifierFlags", + parent, + start, + end, + raw: this.source.slice(start, end), + ignoreCase, + multiline, + dotAll, + }; + } + onRemoveModifiers(start, end, { ignoreCase, multiline, dotAll, }) { + const parent = this._node; + if (parent.type !== "Modifiers") { + throw new Error("UnknownError"); + } + parent.remove = { + type: "ModifierFlags", + parent, + start, + end, + raw: this.source.slice(start, end), + ignoreCase, + multiline, + dotAll, + }; + } + onCapturingGroupEnter(start, name) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + this._node = { + type: "CapturingGroup", + parent, + start, + end: start, + raw: "", + name, + alternatives: [], + references: [], + }; + parent.elements.push(this._node); + this._capturingGroups.push(this._node); + } + onCapturingGroupLeave(start, end) { + const node = this._node; + if (node.type !== "CapturingGroup" || + node.parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onQuantifier(start, end, min, max, greedy) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + const element = parent.elements.pop(); + if (element == null || + element.type === "Quantifier" || + (element.type === "Assertion" && element.kind !== "lookahead")) { + throw new Error("UnknownError"); + } + const node = { + type: "Quantifier", + parent, + start: element.start, + end, + raw: this.source.slice(element.start, end), + min, + max, + greedy, + element, + }; + parent.elements.push(node); + element.parent = node; + } + onLookaroundAssertionEnter(start, kind, negate) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + const node = (this._node = { + type: "Assertion", + parent, + start, + end: start, + raw: "", + kind, + negate, + alternatives: [], + }); + parent.elements.push(node); + } + onLookaroundAssertionLeave(start, end) { + const node = this._node; + if (node.type !== "Assertion" || node.parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onEdgeAssertion(start, end, kind) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "Assertion", + parent, + start, + end, + raw: this.source.slice(start, end), + kind, + }); + } + onWordBoundaryAssertion(start, end, kind, negate) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "Assertion", + parent, + start, + end, + raw: this.source.slice(start, end), + kind, + negate, + }); + } + onAnyCharacterSet(start, end, kind) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "CharacterSet", + parent, + start, + end, + raw: this.source.slice(start, end), + kind, + }); + } + onEscapeCharacterSet(start, end, kind, negate) { + const parent = this._node; + if (parent.type !== "Alternative" && parent.type !== "CharacterClass") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "CharacterSet", + parent, + start, + end, + raw: this.source.slice(start, end), + kind, + negate, + }); + } + onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings) { + const parent = this._node; + if (parent.type !== "Alternative" && parent.type !== "CharacterClass") { + throw new Error("UnknownError"); + } + const base = { + type: "CharacterSet", + parent: null, + start, + end, + raw: this.source.slice(start, end), + kind, + strings: null, + key, + }; + if (strings) { + if ((parent.type === "CharacterClass" && !parent.unicodeSets) || + negate || + value !== null) { + throw new Error("UnknownError"); + } + parent.elements.push(Object.assign(Object.assign({}, base), { parent, strings, value, negate })); + } + else { + parent.elements.push(Object.assign(Object.assign({}, base), { parent, strings, value, negate })); + } + } + onCharacter(start, end, value) { + const parent = this._node; + if (parent.type !== "Alternative" && + parent.type !== "CharacterClass" && + parent.type !== "StringAlternative") { + throw new Error("UnknownError"); + } + parent.elements.push({ + type: "Character", + parent, + start, + end, + raw: this.source.slice(start, end), + value, + }); + } + onBackreference(start, end, ref) { + const parent = this._node; + if (parent.type !== "Alternative") { + throw new Error("UnknownError"); + } + const node = { + type: "Backreference", + parent, + start, + end, + raw: this.source.slice(start, end), + ref, + ambiguous: false, + resolved: DUMMY_CAPTURING_GROUP, + }; + parent.elements.push(node); + this._backreferences.push(node); + } + onCharacterClassEnter(start, negate, unicodeSets) { + const parent = this._node; + const base = { + type: "CharacterClass", + parent, + start, + end: start, + raw: "", + unicodeSets, + negate, + elements: [], + }; + if (parent.type === "Alternative") { + const node = Object.assign(Object.assign({}, base), { parent }); + this._node = node; + parent.elements.push(node); + } + else if (parent.type === "CharacterClass" && + parent.unicodeSets && + unicodeSets) { + const node = Object.assign(Object.assign({}, base), { parent, + unicodeSets }); + this._node = node; + parent.elements.push(node); + } + else { + throw new Error("UnknownError"); + } + } + onCharacterClassLeave(start, end) { + const node = this._node; + if (node.type !== "CharacterClass" || + (node.parent.type !== "Alternative" && + node.parent.type !== "CharacterClass")) { + throw new Error("UnknownError"); + } + const parent = node.parent; + node.end = end; + node.raw = this.source.slice(start, end); + this._node = parent; + const expression = this._expressionBufferMap.get(node); + if (!expression) { + return; + } + if (node.elements.length > 0) { + throw new Error("UnknownError"); + } + this._expressionBufferMap.delete(node); + const newNode = { + type: "ExpressionCharacterClass", + parent, + start: node.start, + end: node.end, + raw: node.raw, + negate: node.negate, + expression, + }; + expression.parent = newNode; + if (node !== parent.elements.pop()) { + throw new Error("UnknownError"); + } + parent.elements.push(newNode); + } + onCharacterClassRange(start, end) { + const parent = this._node; + if (parent.type !== "CharacterClass") { + throw new Error("UnknownError"); + } + const elements = parent.elements; + const max = elements.pop(); + if (!max || max.type !== "Character") { + throw new Error("UnknownError"); + } + if (!parent.unicodeSets) { + const hyphen = elements.pop(); + if (!hyphen || + hyphen.type !== "Character" || + hyphen.value !== HYPHEN_MINUS) { + throw new Error("UnknownError"); + } + } + const min = elements.pop(); + if (!min || min.type !== "Character") { + throw new Error("UnknownError"); + } + const node = { + type: "CharacterClassRange", + parent, + start, + end, + raw: this.source.slice(start, end), + min, + max, + }; + min.parent = node; + max.parent = node; + elements.push(node); + } + onClassIntersection(start, end) { + var _a; + const parent = this._node; + if (parent.type !== "CharacterClass" || !parent.unicodeSets) { + throw new Error("UnknownError"); + } + const right = parent.elements.pop(); + const left = (_a = this._expressionBufferMap.get(parent)) !== null && _a !== void 0 ? _a : parent.elements.pop(); + if (!left || + !right || + left.type === "ClassSubtraction" || + (left.type !== "ClassIntersection" && !isClassSetOperand(left)) || + !isClassSetOperand(right)) { + throw new Error("UnknownError"); + } + const node = { + type: "ClassIntersection", + parent: parent, + start, + end, + raw: this.source.slice(start, end), + left, + right, + }; + left.parent = node; + right.parent = node; + this._expressionBufferMap.set(parent, node); + } + onClassSubtraction(start, end) { + var _a; + const parent = this._node; + if (parent.type !== "CharacterClass" || !parent.unicodeSets) { + throw new Error("UnknownError"); + } + const right = parent.elements.pop(); + const left = (_a = this._expressionBufferMap.get(parent)) !== null && _a !== void 0 ? _a : parent.elements.pop(); + if (!left || + !right || + left.type === "ClassIntersection" || + (left.type !== "ClassSubtraction" && !isClassSetOperand(left)) || + !isClassSetOperand(right)) { + throw new Error("UnknownError"); + } + const node = { + type: "ClassSubtraction", + parent: parent, + start, + end, + raw: this.source.slice(start, end), + left, + right, + }; + left.parent = node; + right.parent = node; + this._expressionBufferMap.set(parent, node); + } + onClassStringDisjunctionEnter(start) { + const parent = this._node; + if (parent.type !== "CharacterClass" || !parent.unicodeSets) { + throw new Error("UnknownError"); + } + this._node = { + type: "ClassStringDisjunction", + parent, + start, + end: start, + raw: "", + alternatives: [], + }; + parent.elements.push(this._node); + } + onClassStringDisjunctionLeave(start, end) { + const node = this._node; + if (node.type !== "ClassStringDisjunction" || + node.parent.type !== "CharacterClass") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } + onStringAlternativeEnter(start) { + const parent = this._node; + if (parent.type !== "ClassStringDisjunction") { + throw new Error("UnknownError"); + } + this._node = { + type: "StringAlternative", + parent, + start, + end: start, + raw: "", + elements: [], + }; + parent.alternatives.push(this._node); + } + onStringAlternativeLeave(start, end) { + const node = this._node; + if (node.type !== "StringAlternative") { + throw new Error("UnknownError"); + } + node.end = end; + node.raw = this.source.slice(start, end); + this._node = node.parent; + } +} +class RegExpParser { + constructor(options) { + this._state = new RegExpParserState(options); + this._validator = new RegExpValidator(this._state); + } + parseLiteral(source, start = 0, end = source.length) { + this._state.source = source; + this._validator.validateLiteral(source, start, end); + const pattern = this._state.pattern; + const flags = this._state.flags; + const literal = { + type: "RegExpLiteral", + parent: null, + start, + end, + raw: source, + pattern, + flags, + }; + pattern.parent = literal; + flags.parent = literal; + return literal; + } + parseFlags(source, start = 0, end = source.length) { + this._state.source = source; + this._validator.validateFlags(source, start, end); + return this._state.flags; + } + parsePattern(source, start = 0, end = source.length, uFlagOrFlags = undefined) { + this._state.source = source; + this._validator.validatePattern(source, start, end, uFlagOrFlags); + return this._state.pattern; + } +} + +class RegExpVisitor { + constructor(handlers) { + this._handlers = handlers; + } + visit(node) { + switch (node.type) { + case "Alternative": + this.visitAlternative(node); + break; + case "Assertion": + this.visitAssertion(node); + break; + case "Backreference": + this.visitBackreference(node); + break; + case "CapturingGroup": + this.visitCapturingGroup(node); + break; + case "Character": + this.visitCharacter(node); + break; + case "CharacterClass": + this.visitCharacterClass(node); + break; + case "CharacterClassRange": + this.visitCharacterClassRange(node); + break; + case "CharacterSet": + this.visitCharacterSet(node); + break; + case "ClassIntersection": + this.visitClassIntersection(node); + break; + case "ClassStringDisjunction": + this.visitClassStringDisjunction(node); + break; + case "ClassSubtraction": + this.visitClassSubtraction(node); + break; + case "ExpressionCharacterClass": + this.visitExpressionCharacterClass(node); + break; + case "Flags": + this.visitFlags(node); + break; + case "Group": + this.visitGroup(node); + break; + case "Modifiers": + this.visitModifiers(node); + break; + case "ModifierFlags": + this.visitModifierFlags(node); + break; + case "Pattern": + this.visitPattern(node); + break; + case "Quantifier": + this.visitQuantifier(node); + break; + case "RegExpLiteral": + this.visitRegExpLiteral(node); + break; + case "StringAlternative": + this.visitStringAlternative(node); + break; + default: + throw new Error(`Unknown type: ${node.type}`); + } + } + visitAlternative(node) { + if (this._handlers.onAlternativeEnter) { + this._handlers.onAlternativeEnter(node); + } + node.elements.forEach(this.visit, this); + if (this._handlers.onAlternativeLeave) { + this._handlers.onAlternativeLeave(node); + } + } + visitAssertion(node) { + if (this._handlers.onAssertionEnter) { + this._handlers.onAssertionEnter(node); + } + if (node.kind === "lookahead" || node.kind === "lookbehind") { + node.alternatives.forEach(this.visit, this); + } + if (this._handlers.onAssertionLeave) { + this._handlers.onAssertionLeave(node); + } + } + visitBackreference(node) { + if (this._handlers.onBackreferenceEnter) { + this._handlers.onBackreferenceEnter(node); + } + if (this._handlers.onBackreferenceLeave) { + this._handlers.onBackreferenceLeave(node); + } + } + visitCapturingGroup(node) { + if (this._handlers.onCapturingGroupEnter) { + this._handlers.onCapturingGroupEnter(node); + } + node.alternatives.forEach(this.visit, this); + if (this._handlers.onCapturingGroupLeave) { + this._handlers.onCapturingGroupLeave(node); + } + } + visitCharacter(node) { + if (this._handlers.onCharacterEnter) { + this._handlers.onCharacterEnter(node); + } + if (this._handlers.onCharacterLeave) { + this._handlers.onCharacterLeave(node); + } + } + visitCharacterClass(node) { + if (this._handlers.onCharacterClassEnter) { + this._handlers.onCharacterClassEnter(node); + } + node.elements.forEach(this.visit, this); + if (this._handlers.onCharacterClassLeave) { + this._handlers.onCharacterClassLeave(node); + } + } + visitCharacterClassRange(node) { + if (this._handlers.onCharacterClassRangeEnter) { + this._handlers.onCharacterClassRangeEnter(node); + } + this.visitCharacter(node.min); + this.visitCharacter(node.max); + if (this._handlers.onCharacterClassRangeLeave) { + this._handlers.onCharacterClassRangeLeave(node); + } + } + visitCharacterSet(node) { + if (this._handlers.onCharacterSetEnter) { + this._handlers.onCharacterSetEnter(node); + } + if (this._handlers.onCharacterSetLeave) { + this._handlers.onCharacterSetLeave(node); + } + } + visitClassIntersection(node) { + if (this._handlers.onClassIntersectionEnter) { + this._handlers.onClassIntersectionEnter(node); + } + this.visit(node.left); + this.visit(node.right); + if (this._handlers.onClassIntersectionLeave) { + this._handlers.onClassIntersectionLeave(node); + } + } + visitClassStringDisjunction(node) { + if (this._handlers.onClassStringDisjunctionEnter) { + this._handlers.onClassStringDisjunctionEnter(node); + } + node.alternatives.forEach(this.visit, this); + if (this._handlers.onClassStringDisjunctionLeave) { + this._handlers.onClassStringDisjunctionLeave(node); + } + } + visitClassSubtraction(node) { + if (this._handlers.onClassSubtractionEnter) { + this._handlers.onClassSubtractionEnter(node); + } + this.visit(node.left); + this.visit(node.right); + if (this._handlers.onClassSubtractionLeave) { + this._handlers.onClassSubtractionLeave(node); + } + } + visitExpressionCharacterClass(node) { + if (this._handlers.onExpressionCharacterClassEnter) { + this._handlers.onExpressionCharacterClassEnter(node); + } + this.visit(node.expression); + if (this._handlers.onExpressionCharacterClassLeave) { + this._handlers.onExpressionCharacterClassLeave(node); + } + } + visitFlags(node) { + if (this._handlers.onFlagsEnter) { + this._handlers.onFlagsEnter(node); + } + if (this._handlers.onFlagsLeave) { + this._handlers.onFlagsLeave(node); + } + } + visitGroup(node) { + if (this._handlers.onGroupEnter) { + this._handlers.onGroupEnter(node); + } + if (node.modifiers) { + this.visit(node.modifiers); + } + node.alternatives.forEach(this.visit, this); + if (this._handlers.onGroupLeave) { + this._handlers.onGroupLeave(node); + } + } + visitModifiers(node) { + if (this._handlers.onModifiersEnter) { + this._handlers.onModifiersEnter(node); + } + if (node.add) { + this.visit(node.add); + } + if (node.remove) { + this.visit(node.remove); + } + if (this._handlers.onModifiersLeave) { + this._handlers.onModifiersLeave(node); + } + } + visitModifierFlags(node) { + if (this._handlers.onModifierFlagsEnter) { + this._handlers.onModifierFlagsEnter(node); + } + if (this._handlers.onModifierFlagsLeave) { + this._handlers.onModifierFlagsLeave(node); + } + } + visitPattern(node) { + if (this._handlers.onPatternEnter) { + this._handlers.onPatternEnter(node); + } + node.alternatives.forEach(this.visit, this); + if (this._handlers.onPatternLeave) { + this._handlers.onPatternLeave(node); + } + } + visitQuantifier(node) { + if (this._handlers.onQuantifierEnter) { + this._handlers.onQuantifierEnter(node); + } + this.visit(node.element); + if (this._handlers.onQuantifierLeave) { + this._handlers.onQuantifierLeave(node); + } + } + visitRegExpLiteral(node) { + if (this._handlers.onRegExpLiteralEnter) { + this._handlers.onRegExpLiteralEnter(node); + } + this.visitPattern(node.pattern); + this.visitFlags(node.flags); + if (this._handlers.onRegExpLiteralLeave) { + this._handlers.onRegExpLiteralLeave(node); + } + } + visitStringAlternative(node) { + if (this._handlers.onStringAlternativeEnter) { + this._handlers.onStringAlternativeEnter(node); + } + node.elements.forEach(this.visit, this); + if (this._handlers.onStringAlternativeLeave) { + this._handlers.onStringAlternativeLeave(node); + } + } +} + +function parseRegExpLiteral(source, options) { + return new RegExpParser(options).parseLiteral(String(source)); +} +function validateRegExpLiteral(source, options) { + new RegExpValidator(options).validateLiteral(source); +} +function visitRegExpAST(node, handlers) { + new RegExpVisitor(handlers).visit(node); +} + +export { ast as AST, RegExpParser, RegExpSyntaxError, RegExpValidator, parseRegExpLiteral, validateRegExpLiteral, visitRegExpAST }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/@eslint-community/regexpp/index.mjs.map b/node_modules/@eslint-community/regexpp/index.mjs.map new file mode 100644 index 00000000..0d1c5f78 --- /dev/null +++ b/node_modules/@eslint-community/regexpp/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs.map","sources":[".temp/src/ecma-versions.ts",".temp/unicode/src/unicode/ids.ts",".temp/unicode/src/unicode/properties.ts",".temp/unicode/src/unicode/index.ts",".temp/src/group-specifiers.ts",".temp/src/reader.ts",".temp/src/regexp-syntax-error.ts",".temp/src/validator.ts",".temp/src/parser.ts",".temp/src/visitor.ts",".temp/src/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null],"names":[],"mappings":";;;;AAaO,MAAM,iBAAiB,GAAG,IAAI;;ACTrC,IAAI,kBAAkB,GAAyB,SAAS,CAAA;AACxD,IAAI,qBAAqB,GAAyB,SAAS,CAAA;AAErD,SAAU,SAAS,CAAC,EAAU,EAAA;IAChC,IAAI,EAAE,GAAG,IAAI;AAAE,QAAA,OAAO,KAAK,CAAA;IAC3B,IAAI,EAAE,GAAG,IAAI;AAAE,QAAA,OAAO,IAAI,CAAA;IAC1B,IAAI,EAAE,GAAG,IAAI;AAAE,QAAA,OAAO,KAAK,CAAA;IAC3B,IAAI,EAAE,GAAG,IAAI;AAAE,QAAA,OAAO,IAAI,CAAA;AAC1B,IAAA,OAAO,cAAc,CAAC,EAAE,CAAC,CAAA;AAC7B,CAAC;AAEK,SAAU,YAAY,CAAC,EAAU,EAAA;IACnC,IAAI,E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AC,CAAA;AACxD,CAAC;AAEe,SAAA,cAAc,CAC1B,IAAc,EACd,QAAgC,EAAA;IAEhC,IAAI,aAAa,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;AAC3C;;;;"} \ No newline at end of file diff --git a/node_modules/@eslint-community/regexpp/package.json b/node_modules/@eslint-community/regexpp/package.json new file mode 100644 index 00000000..39cbfde7 --- /dev/null +++ b/node_modules/@eslint-community/regexpp/package.json @@ -0,0 +1,91 @@ +{ + "name": "@eslint-community/regexpp", + "version": "4.12.1", + "description": "Regular expression parser for ECMAScript.", + "keywords": [ + "regexp", + "regular", + "expression", + "parser", + "validator", + "ast", + "abstract", + "syntax", + "tree", + "ecmascript", + "es2015", + "es2016", + "es2017", + "es2018", + "es2019", + "es2020", + "es2021", + "annexB" + ], + "homepage": "https://github.com/eslint-community/regexpp#readme", + "bugs": { + "url": "https://github.com/eslint-community/regexpp/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint-community/regexpp" + }, + "license": "MIT", + "author": "Toru Nagashima", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.mjs", + "default": "./index.js" + }, + "./package.json": "./package.json" + }, + "main": "index", + "files": [ + "index.*" + ], + "scripts": { + "prebuild": "npm run -s clean", + "build": "run-s build:*", + "build:tsc": "tsc --module es2015", + "build:rollup": "rollup -c", + "build:dts": "npm run -s build:tsc -- --removeComments false && dts-bundle --name @eslint-community/regexpp --main .temp/index.d.ts --out ../index.d.ts && prettier --write index.d.ts", + "clean": "rimraf .temp index.*", + "lint": "eslint . --ext .ts", + "test": "nyc _mocha \"test/*.ts\" --reporter dot --timeout 10000", + "debug": "mocha --require ts-node/register/transpile-only \"test/*.ts\" --reporter dot --timeout 10000", + "update:test": "ts-node scripts/update-fixtures.ts", + "update:unicode": "run-s update:unicode:*", + "update:unicode:ids": "ts-node scripts/update-unicode-ids.ts", + "update:unicode:props": "ts-node scripts/update-unicode-properties.ts", + "update:test262:extract": "ts-node -T scripts/extract-test262.ts", + "preversion": "npm test && npm run -s build", + "postversion": "git push && git push --tags", + "prewatch": "npm run -s clean", + "watch": "_mocha \"test/*.ts\" --require ts-node/register --reporter dot --timeout 10000 --watch-extensions ts --watch --growl" + }, + "dependencies": {}, + "devDependencies": { + "@eslint-community/eslint-plugin-mysticatea": "^15.5.1", + "@rollup/plugin-node-resolve": "^14.1.0", + "@types/eslint": "^8.44.3", + "@types/jsdom": "^16.2.15", + "@types/mocha": "^9.1.1", + "@types/node": "^12.20.55", + "dts-bundle": "^0.7.3", + "eslint": "^8.50.0", + "js-tokens": "^8.0.2", + "jsdom": "^19.0.0", + "mocha": "^9.2.2", + "npm-run-all2": "^6.2.2", + "nyc": "^14.1.1", + "rimraf": "^3.0.2", + "rollup": "^2.79.1", + "rollup-plugin-sourcemaps": "^0.6.3", + "ts-node": "^10.9.1", + "typescript": "~5.0.2" + }, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } +} diff --git a/node_modules/@eslint/config-array/LICENSE b/node_modules/@eslint/config-array/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@eslint/config-array/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@eslint/config-array/README.md b/node_modules/@eslint/config-array/README.md new file mode 100644 index 00000000..5c3feb48 --- /dev/null +++ b/node_modules/@eslint/config-array/README.md @@ -0,0 +1,359 @@ +# Config Array + +## Description + +A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename. + +**Note:** This is a generic package that can be used outside of ESLint. It contains no ESLint-specific functionality. + +## Installation + +For Node.js and compatible runtimes: + +```shell +npm install @eslint/config-array +# or +yarn add @eslint/config-array +# or +pnpm install @eslint/config-array +# or +bun add @eslint/config-array +``` + +For Deno: + +```shell +deno add @eslint/config-array +``` + +## Background + +The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example: + +```js +export default [ + // match all JSON files + { + name: "JSON Handler", + files: ["**/*.json"], + handler: jsonHandler, + }, + + // match only package.json + { + name: "package.json Handler", + files: ["package.json"], + handler: packageJsonHandler, + }, +]; +``` + +In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins). + +## Usage + +First, import the `ConfigArray` constructor: + +```js +import { ConfigArray } from "@eslint/config-array"; + +// or using CommonJS + +const { ConfigArray } = require("@eslint/config-array"); +``` + +When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example: + +```js +const configFilename = path.resolve(process.cwd(), "my.config.js"); +const { default: rawConfigs } = await import(configFilename); +const configs = new ConfigArray(rawConfigs, { + // the path to match filenames from + basePath: process.cwd(), + + // additional items in each config + schema: mySchema, +}); +``` + +This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directory in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, and `name`. + +### Specifying a Schema + +The `schema` option is required for you to use additional properties in config objects. The schema is an object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@eslint/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example: + +```js +const configFilename = path.resolve(process.cwd(), "my.config.js"); +const { default: rawConfigs } = await import(configFilename); + +const mySchema = { + + // define the handler key in configs + handler: { + required: true, + merge(a, b) { + if (!b) return a; + if (!a) return b; + }, + validate(value) { + if (typeof value !== "function") { + throw new TypeError("Function expected."); + } + } + } +}; + +const configs = new ConfigArray(rawConfigs, { + + // the path to match filenames from + basePath: process.cwd(), + + // additional item schemas in each config + schema: mySchema, + + // additional config types supported (default: []) + extraConfigTypes: ["array", "function"]; +}); +``` + +### Config Arrays + +Config arrays can be multidimensional, so it's possible for a config array to contain another config array when `extraConfigTypes` contains `"array"`, such as: + +```js +export default [ + // JS config + { + files: ["**/*.js"], + handler: jsHandler, + }, + + // JSON configs + [ + // match all JSON files + { + name: "JSON Handler", + files: ["**/*.json"], + handler: jsonHandler, + }, + + // match only package.json + { + name: "package.json Handler", + files: ["package.json"], + handler: packageJsonHandler, + }, + ], + + // filename must match function + { + files: [filePath => filePath.endsWith(".md")], + handler: markdownHandler, + }, + + // filename must match all patterns in subarray + { + files: [["*.test.*", "*.js"]], + handler: jsTestHandler, + }, + + // filename must not match patterns beginning with ! + { + name: "Non-JS files", + files: ["!*.js"], + settings: { + js: false, + }, + }, +]; +``` + +In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same. + +If the `files` array contains a function, then that function is called with the path of the file as it was passed in. The function is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.) + +If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used. + +If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically get a `settings.js` property set to `false`. + +You can also specify an `ignores` key that will force files matching those patterns to not be included. If the `ignores` key is in a config object without any other keys, then those ignores will always be applied; otherwise those ignores act as exclusions. Here's an example: + +```js +export default [ + + // Always ignored + { + ignores: ["**/.git/**", "**/node_modules/**"] + }, + + // .eslintrc.js file is ignored only when .js file matches + { + files: ["**/*.js"], + ignores: [".eslintrc.js"] + handler: jsHandler + } +]; +``` + +You can use negated patterns in `ignores` to exclude a file that was already ignored, such as: + +```js +export default [ + // Ignore all JSON files except tsconfig.json + { + files: ["**/*"], + ignores: ["**/*.json", "!tsconfig.json"], + }, +]; +``` + +### Config Functions + +Config arrays can also include config functions when `extraConfigTypes` contains `"function"`. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example: + +```js +export default [ + // JS config + { + files: ["**/*.js"], + handler: jsHandler, + }, + + // JSON configs + function (context) { + return [ + // match all JSON files + { + name: context.name + " JSON Handler", + files: ["**/*.json"], + handler: jsonHandler, + }, + + // match only package.json + { + name: context.name + " package.json Handler", + files: ["package.json"], + handler: packageJsonHandler, + }, + ]; + }, +]; +``` + +When a config array is normalized, each function is executed and replaced in the config array with the return value. + +**Note:** Config functions can also be async. + +### Normalizing Config Arrays + +Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values. + +To normalize a config array, call the `normalize()` method and pass in a context object: + +```js +await configs.normalize({ + name: "MyApp", +}); +``` + +The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable. + +If you want to disallow async config functions, you can call `normalizeSync()` instead. This method is completely synchronous and does not require using the `await` operator as it does not return a promise: + +```js +await configs.normalizeSync({ + name: "MyApp", +}); +``` + +**Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy. + +### Getting Config for a File + +To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for: + +```js +// pass in filename +const fileConfig = configs.getConfig( + path.resolve(process.cwd(), "package.json"), +); +``` + +The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed. + +A few things to keep in mind: + +- If a filename is not an absolute path, it will be resolved relative to the base path directory. +- The returned config object never has `files`, `ignores`, or `name` properties; the only properties on the object will be the other configuration options specified. +- The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation. +- A config will only be generated if the filename matches an entry in a `files` key. A config will not be generated without matching a `files` key (configs without a `files` key are only applied when another config with a `files` key is applied; configs without `files` are never applied on their own). Any config with a `files` key entry that is `*` or ends with `/**` or `/*` will only be applied if another entry in the same `files` key matches or another config matches. + +## Determining Ignored Paths + +You can determine if a file is ignored by using the `isFileIgnored()` method and passing in the path of any file, as in this example: + +```js +const ignored = configs.isFileIgnored("/foo/bar/baz.txt"); +``` + +A file is considered ignored if any of the following is true: + +- **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/a.js` is considered ignored. +- **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/baz/a.js` is considered ignored. +- **It matches an ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. +- **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. +- **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored. + +For directories, use the `isDirectoryIgnored()` method and pass in the path of any directory, as in this example: + +```js +const ignored = configs.isDirectoryIgnored("/foo/bar/"); +``` + +A directory is considered ignored if any of the following is true: + +- **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/baz` is considered ignored. +- **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/bar/baz/a.js` is considered ignored. +- **It matches and ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. +- **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. +- **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored. + +**Important:** A pattern such as `foo/**` means that `foo` and `foo/` are _not_ ignored whereas `foo/bar` is ignored. If you want to ignore `foo` and all of its subdirectories, use the pattern `foo` or `foo/` in `ignores`. + +## Caching Mechanisms + +Each `ConfigArray` aggressively caches configuration objects to avoid unnecessary work. This caching occurs in two ways: + +1. **File-based Caching.** For each filename that is passed into a method, the resulting config is cached against that filename so you're always guaranteed to get the same object returned from `getConfig()` whenever you pass the same filename in. +2. **Index-based Caching.** Whenever a config is calculated, the config elements that were used to create the config are also cached. So if a given filename matches elements 1, 5, and 7, the resulting config is cached with a key of `1,5,7`. That way, if another file is passed that matches the same config elements, the result is already known and doesn't have to be recalculated. That means two files that match all the same elements will return the same config from `getConfig()`. + +## Acknowledgements + +The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from: + +- Teddy Katz (@not-an-aardvark) +- Toru Nagashima (@mysticatea) +- Kai Cataldo (@kaicataldo) + +## License + +Apache 2.0 + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/@eslint/config-array/dist/cjs/index.cjs b/node_modules/@eslint/config-array/dist/cjs/index.cjs new file mode 100644 index 00000000..ef6d4277 --- /dev/null +++ b/node_modules/@eslint/config-array/dist/cjs/index.cjs @@ -0,0 +1,1414 @@ +'use strict'; + +var posixPath = require('./std__path/posix.cjs'); +var windowsPath = require('./std__path/windows.cjs'); +var minimatch = require('minimatch'); +var createDebug = require('debug'); +var objectSchema = require('@eslint/object-schema'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var posixPath__namespace = /*#__PURE__*/_interopNamespaceDefault(posixPath); +var windowsPath__namespace = /*#__PURE__*/_interopNamespaceDefault(windowsPath); + +/** + * @fileoverview ConfigSchema + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("@eslint/object-schema").PropertyDefinition} PropertyDefinition */ +/** @typedef {import("@eslint/object-schema").ObjectDefinition} ObjectDefinition */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * A strategy that does nothing. + * @type {PropertyDefinition} + */ +const NOOP_STRATEGY = { + required: false, + merge() { + return undefined; + }, + validate() {}, +}; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The base schema that every ConfigArray uses. + * @type {ObjectDefinition} + */ +const baseSchema = Object.freeze({ + name: { + required: false, + merge() { + return undefined; + }, + validate(value) { + if (typeof value !== "string") { + throw new TypeError("Property must be a string."); + } + }, + }, + files: NOOP_STRATEGY, + ignores: NOOP_STRATEGY, +}); + +/** + * @fileoverview ConfigSchema + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Asserts that a given value is an array. + * @param {*} value The value to check. + * @returns {void} + * @throws {TypeError} When the value is not an array. + */ +function assertIsArray(value) { + if (!Array.isArray(value)) { + throw new TypeError("Expected value to be an array."); + } +} + +/** + * Asserts that a given value is an array containing only strings and functions. + * @param {*} value The value to check. + * @returns {void} + * @throws {TypeError} When the value is not an array of strings and functions. + */ +function assertIsArrayOfStringsAndFunctions(value) { + assertIsArray(value); + + if ( + value.some( + item => typeof item !== "string" && typeof item !== "function", + ) + ) { + throw new TypeError( + "Expected array to only contain strings and functions.", + ); + } +} + +/** + * Asserts that a given value is a non-empty array. + * @param {*} value The value to check. + * @returns {void} + * @throws {TypeError} When the value is not an array or an empty array. + */ +function assertIsNonEmptyArray(value) { + if (!Array.isArray(value) || value.length === 0) { + throw new TypeError("Expected value to be a non-empty array."); + } +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The schema for `files` and `ignores` that every ConfigArray uses. + * @type {ObjectDefinition} + */ +const filesAndIgnoresSchema = Object.freeze({ + files: { + required: false, + merge() { + return undefined; + }, + validate(value) { + // first check if it's an array + assertIsNonEmptyArray(value); + + // then check each member + value.forEach(item => { + if (Array.isArray(item)) { + assertIsArrayOfStringsAndFunctions(item); + } else if ( + typeof item !== "string" && + typeof item !== "function" + ) { + throw new TypeError( + "Items must be a string, a function, or an array of strings and functions.", + ); + } + }); + }, + }, + ignores: { + required: false, + merge() { + return undefined; + }, + validate: assertIsArrayOfStringsAndFunctions, + }, +}); + +/** + * @fileoverview ConfigArray + * @author Nicholas C. Zakas + */ + + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("./types.ts").ConfigObject} ConfigObject */ +/** @typedef {import("minimatch").IMinimatchStatic} IMinimatchStatic */ +/** @typedef {import("minimatch").IMinimatch} IMinimatch */ +/** @typedef {import("@jsr/std__path")} PathImpl */ + +/* + * This is a bit of a hack to make TypeScript happy with the Rollup-created + * CommonJS file. Rollup doesn't do object destructuring for imported files + * and instead imports the default via `require()`. This messes up type checking + * for `ObjectSchema`. To work around that, we just import the type manually + * and give it a different name to use in the JSDoc comments. + */ +/** @typedef {import("@eslint/object-schema").ObjectSchema} ObjectSchemaInstance */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const Minimatch = minimatch.Minimatch; +const debug = createDebug("@eslint/config-array"); + +/** + * A cache for minimatch instances. + * @type {Map} + */ +const minimatchCache = new Map(); + +/** + * A cache for negated minimatch instances. + * @type {Map} + */ +const negatedMinimatchCache = new Map(); + +/** + * Options to use with minimatch. + * @type {Object} + */ +const MINIMATCH_OPTIONS = { + // matchBase: true, + dot: true, + allowWindowsEscape: true, +}; + +/** + * The types of config objects that are supported. + * @type {Set} + */ +const CONFIG_TYPES = new Set(["array", "function"]); + +/** + * Fields that are considered metadata and not part of the config object. + * @type {Set} + */ +const META_FIELDS = new Set(["name"]); + +/** + * A schema containing just files and ignores for early validation. + * @type {ObjectSchemaInstance} + */ +const FILES_AND_IGNORES_SCHEMA = new objectSchema.ObjectSchema(filesAndIgnoresSchema); + +// Precomputed constant objects returned by `ConfigArray.getConfigWithStatus`. + +const CONFIG_WITH_STATUS_EXTERNAL = Object.freeze({ status: "external" }); +const CONFIG_WITH_STATUS_IGNORED = Object.freeze({ status: "ignored" }); +const CONFIG_WITH_STATUS_UNCONFIGURED = Object.freeze({ + status: "unconfigured", +}); + +// Match two leading dots followed by a slash or the end of input. +const EXTERNAL_PATH_REGEX = /^\.\.(?:\/|$)/u; + +/** + * Wrapper error for config validation errors that adds a name to the front of the + * error message. + */ +class ConfigError extends Error { + /** + * Creates a new instance. + * @param {string} name The config object name causing the error. + * @param {number} index The index of the config object in the array. + * @param {Object} options The options for the error. + * @param {Error} [options.cause] The error that caused this error. + * @param {string} [options.message] The message to use for the error. + */ + constructor(name, index, { cause, message }) { + const finalMessage = message || cause.message; + + super(`Config ${name}: ${finalMessage}`, { cause }); + + // copy over custom properties that aren't represented + if (cause) { + for (const key of Object.keys(cause)) { + if (!(key in this)) { + this[key] = cause[key]; + } + } + } + + /** + * The name of the error. + * @type {string} + * @readonly + */ + this.name = "ConfigError"; + + /** + * The index of the config object in the array. + * @type {number} + * @readonly + */ + this.index = index; + } +} + +/** + * Gets the name of a config object. + * @param {ConfigObject} config The config object to get the name of. + * @returns {string} The name of the config object. + */ +function getConfigName(config) { + if (config && typeof config.name === "string" && config.name) { + return `"${config.name}"`; + } + + return "(unnamed)"; +} + +/** + * Rethrows a config error with additional information about the config object. + * @param {object} config The config object to get the name of. + * @param {number} index The index of the config object in the array. + * @param {Error} error The error to rethrow. + * @throws {ConfigError} When the error is rethrown for a config. + */ +function rethrowConfigError(config, index, error) { + const configName = getConfigName(config); + throw new ConfigError(configName, index, { cause: error }); +} + +/** + * Shorthand for checking if a value is a string. + * @param {any} value The value to check. + * @returns {boolean} True if a string, false if not. + */ +function isString(value) { + return typeof value === "string"; +} + +/** + * Creates a function that asserts that the config is valid + * during normalization. This checks that the config is not nullish + * and that files and ignores keys of a config object are valid as per base schema. + * @param {Object} config The config object to check. + * @param {number} index The index of the config object in the array. + * @returns {void} + * @throws {ConfigError} If the files and ignores keys of a config object are not valid. + */ +function assertValidBaseConfig(config, index) { + if (config === null) { + throw new ConfigError(getConfigName(config), index, { + message: "Unexpected null config.", + }); + } + + if (config === undefined) { + throw new ConfigError(getConfigName(config), index, { + message: "Unexpected undefined config.", + }); + } + + if (typeof config !== "object") { + throw new ConfigError(getConfigName(config), index, { + message: "Unexpected non-object config.", + }); + } + + const validateConfig = {}; + + if ("files" in config) { + validateConfig.files = config.files; + } + + if ("ignores" in config) { + validateConfig.ignores = config.ignores; + } + + try { + FILES_AND_IGNORES_SCHEMA.validate(validateConfig); + } catch (validationError) { + rethrowConfigError(config, index, validationError); + } +} + +/** + * Wrapper around minimatch that caches minimatch patterns for + * faster matching speed over multiple file path evaluations. + * @param {string} filepath The file path to match. + * @param {string} pattern The glob pattern to match against. + * @param {object} options The minimatch options to use. + * @returns + */ +function doMatch(filepath, pattern, options = {}) { + let cache = minimatchCache; + + if (options.flipNegate) { + cache = negatedMinimatchCache; + } + + let matcher = cache.get(pattern); + + if (!matcher) { + matcher = new Minimatch( + pattern, + Object.assign({}, MINIMATCH_OPTIONS, options), + ); + cache.set(pattern, matcher); + } + + return matcher.match(filepath); +} + +/** + * Normalizes a pattern by removing the leading "./" if present. + * @param {string} pattern The pattern to normalize. + * @returns {string} The normalized pattern. + */ +function normalizePattern(pattern) { + if (isString(pattern)) { + if (pattern.startsWith("./")) { + return pattern.slice(2); + } + + if (pattern.startsWith("!./")) { + return `!${pattern.slice(3)}`; + } + } + + return pattern; +} + +/** + * Checks if a given pattern requires normalization. + * @param {any} pattern The pattern to check. + * @returns {boolean} True if the pattern needs normalization, false otherwise. + * + */ +function needsPatternNormalization(pattern) { + return ( + isString(pattern) && + (pattern.startsWith("./") || pattern.startsWith("!./")) + ); +} + +/** + * Normalizes `files` and `ignores` patterns in a config by removing "./" prefixes. + * @param {Object} config The config object to normalize patterns in. + * @returns {Object} The normalized config object. + */ +function normalizeConfigPatterns(config) { + if (!config) { + return config; + } + + let needsNormalization = false; + + if (Array.isArray(config.files)) { + needsNormalization = config.files.some(pattern => { + if (Array.isArray(pattern)) { + return pattern.some(needsPatternNormalization); + } + return needsPatternNormalization(pattern); + }); + } + + if (!needsNormalization && Array.isArray(config.ignores)) { + needsNormalization = config.ignores.some(needsPatternNormalization); + } + + if (!needsNormalization) { + return config; + } + + const newConfig = { ...config }; + + if (Array.isArray(newConfig.files)) { + newConfig.files = newConfig.files.map(pattern => { + if (Array.isArray(pattern)) { + return pattern.map(normalizePattern); + } + return normalizePattern(pattern); + }); + } + + if (Array.isArray(newConfig.ignores)) { + newConfig.ignores = newConfig.ignores.map(normalizePattern); + } + + return newConfig; +} + +/** + * Normalizes a `ConfigArray` by flattening it and executing any functions + * that are found inside. + * @param {Array} items The items in a `ConfigArray`. + * @param {Object} context The context object to pass into any function + * found. + * @param {Array} extraConfigTypes The config types to check. + * @returns {Promise} A flattened array containing only config objects. + * @throws {TypeError} When a config function returns a function. + */ +async function normalize(items, context, extraConfigTypes) { + const allowFunctions = extraConfigTypes.includes("function"); + const allowArrays = extraConfigTypes.includes("array"); + + async function* flatTraverse(array) { + for (let item of array) { + if (typeof item === "function") { + if (!allowFunctions) { + throw new TypeError("Unexpected function."); + } + + item = item(context); + if (item.then) { + item = await item; + } + } + + if (Array.isArray(item)) { + if (!allowArrays) { + throw new TypeError("Unexpected array."); + } + yield* flatTraverse(item); + } else if (typeof item === "function") { + throw new TypeError( + "A config function can only return an object or array.", + ); + } else { + yield item; + } + } + } + + /* + * Async iterables cannot be used with the spread operator, so we need to manually + * create the array to return. + */ + const asyncIterable = await flatTraverse(items); + const configs = []; + + for await (const config of asyncIterable) { + configs.push(normalizeConfigPatterns(config)); + } + + return configs; +} + +/** + * Normalizes a `ConfigArray` by flattening it and executing any functions + * that are found inside. + * @param {Array} items The items in a `ConfigArray`. + * @param {Object} context The context object to pass into any function + * found. + * @param {Array} extraConfigTypes The config types to check. + * @returns {Array} A flattened array containing only config objects. + * @throws {TypeError} When a config function returns a function. + */ +function normalizeSync(items, context, extraConfigTypes) { + const allowFunctions = extraConfigTypes.includes("function"); + const allowArrays = extraConfigTypes.includes("array"); + + function* flatTraverse(array) { + for (let item of array) { + if (typeof item === "function") { + if (!allowFunctions) { + throw new TypeError("Unexpected function."); + } + + item = item(context); + if (item.then) { + throw new TypeError( + "Async config functions are not supported.", + ); + } + } + + if (Array.isArray(item)) { + if (!allowArrays) { + throw new TypeError("Unexpected array."); + } + + yield* flatTraverse(item); + } else if (typeof item === "function") { + throw new TypeError( + "A config function can only return an object or array.", + ); + } else { + yield item; + } + } + } + + const configs = []; + + for (const config of flatTraverse(items)) { + configs.push(normalizeConfigPatterns(config)); + } + + return configs; +} + +/** + * Determines if a given file path should be ignored based on the given + * matcher. + * @param {Array boolean)>} ignores The ignore patterns to check. + * @param {string} filePath The unprocessed file path to check. + * @param {string} relativeFilePath The path of the file to check relative to the base path, + * using forward slash (`"/"`) as a separator. + * @returns {boolean} True if the path should be ignored and false if not. + */ +function shouldIgnorePath(ignores, filePath, relativeFilePath) { + return ignores.reduce((ignored, matcher) => { + if (!ignored) { + if (typeof matcher === "function") { + return matcher(filePath); + } + + // don't check negated patterns because we're not ignored yet + if (!matcher.startsWith("!")) { + return doMatch(relativeFilePath, matcher); + } + + // otherwise we're still not ignored + return false; + } + + // only need to check negated patterns because we're ignored + if (typeof matcher === "string" && matcher.startsWith("!")) { + return !doMatch(relativeFilePath, matcher, { + flipNegate: true, + }); + } + + return ignored; + }, false); +} + +/** + * Determines if a given file path is matched by a config based on + * `ignores` only. + * @param {string} filePath The unprocessed file path to check. + * @param {string} relativeFilePath The path of the file to check relative to the base path, + * using forward slash (`"/"`) as a separator. + * @param {Object} config The config object to check. + * @returns {boolean} True if the file path is matched by the config, + * false if not. + */ +function pathMatchesIgnores(filePath, relativeFilePath, config) { + return ( + Object.keys(config).filter(key => !META_FIELDS.has(key)).length > 1 && + !shouldIgnorePath(config.ignores, filePath, relativeFilePath) + ); +} + +/** + * Determines if a given file path is matched by a config. If the config + * has no `files` field, then it matches; otherwise, if a `files` field + * is present then we match the globs in `files` and exclude any globs in + * `ignores`. + * @param {string} filePath The unprocessed file path to check. + * @param {string} relativeFilePath The path of the file to check relative to the base path, + * using forward slash (`"/"`) as a separator. + * @param {Object} config The config object to check. + * @returns {boolean} True if the file path is matched by the config, + * false if not. + */ +function pathMatches(filePath, relativeFilePath, config) { + // match both strings and functions + function match(pattern) { + if (isString(pattern)) { + return doMatch(relativeFilePath, pattern); + } + + if (typeof pattern === "function") { + return pattern(filePath); + } + + throw new TypeError(`Unexpected matcher type ${pattern}.`); + } + + // check for all matches to config.files + let filePathMatchesPattern = config.files.some(pattern => { + if (Array.isArray(pattern)) { + return pattern.every(match); + } + + return match(pattern); + }); + + /* + * If the file path matches the config.files patterns, then check to see + * if there are any files to ignore. + */ + if (filePathMatchesPattern && config.ignores) { + filePathMatchesPattern = !shouldIgnorePath( + config.ignores, + filePath, + relativeFilePath, + ); + } + + return filePathMatchesPattern; +} + +/** + * Ensures that a ConfigArray has been normalized. + * @param {ConfigArray} configArray The ConfigArray to check. + * @returns {void} + * @throws {Error} When the `ConfigArray` is not normalized. + */ +function assertNormalized(configArray) { + // TODO: Throw more verbose error + if (!configArray.isNormalized()) { + throw new Error( + "ConfigArray must be normalized to perform this operation.", + ); + } +} + +/** + * Ensures that config types are valid. + * @param {Array} extraConfigTypes The config types to check. + * @returns {void} + * @throws {TypeError} When the config types array is invalid. + */ +function assertExtraConfigTypes(extraConfigTypes) { + if (extraConfigTypes.length > 2) { + throw new TypeError( + "configTypes must be an array with at most two items.", + ); + } + + for (const configType of extraConfigTypes) { + if (!CONFIG_TYPES.has(configType)) { + throw new TypeError( + `Unexpected config type "${configType}" found. Expected one of: "object", "array", "function".`, + ); + } + } +} + +/** + * Returns path-handling implementations for Unix or Windows, depending on a given absolute path. + * @param {string} fileOrDirPath The absolute path to check. + * @returns {PathImpl} Path-handling implementations for the specified path. + * @throws {Error} An error is thrown if the specified argument is not an absolute path. + */ +function getPathImpl(fileOrDirPath) { + // Posix absolute paths always start with a slash. + if (fileOrDirPath.startsWith("/")) { + return posixPath__namespace; + } + + // Windows absolute paths start with a letter followed by a colon and at least one backslash, + // or with two backslashes in the case of UNC paths. + // Forward slashed are automatically normalized to backslashes. + if (/^(?:[A-Za-z]:[/\\]|[/\\]{2})/u.test(fileOrDirPath)) { + return windowsPath__namespace; + } + + throw new Error( + `Expected an absolute path but received "${fileOrDirPath}"`, + ); +} + +/** + * Converts a given path to a relative path with all separator characters replaced by forward slashes (`"/"`). + * @param {string} fileOrDirPath The unprocessed path to convert. + * @param {string} namespacedBasePath The namespaced base path of the directory to which the calculated path shall be relative. + * @param {PathImpl} path Path-handling implementations. + * @returns {string} A relative path with all separator characters replaced by forward slashes. + */ +function toRelativePath(fileOrDirPath, namespacedBasePath, path) { + const fullPath = path.resolve(namespacedBasePath, fileOrDirPath); + const namespacedFullPath = path.toNamespacedPath(fullPath); + const relativePath = path.relative(namespacedBasePath, namespacedFullPath); + return relativePath.replaceAll(path.SEPARATOR, "/"); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +const ConfigArraySymbol = { + isNormalized: Symbol("isNormalized"), + configCache: Symbol("configCache"), + schema: Symbol("schema"), + finalizeConfig: Symbol("finalizeConfig"), + preprocessConfig: Symbol("preprocessConfig"), +}; + +// used to store calculate data for faster lookup +const dataCache = new WeakMap(); + +/** + * Represents an array of config objects and provides method for working with + * those config objects. + */ +class ConfigArray extends Array { + /** + * The namespaced path of the config file directory. + * @type {string} + */ + #namespacedBasePath; + + /** + * Path-handling implementations. + * @type {PathImpl} + */ + #path; + + /** + * Creates a new instance of ConfigArray. + * @param {Iterable|Function|Object} configs An iterable yielding config + * objects, or a config function, or a config object. + * @param {Object} options The options for the ConfigArray. + * @param {string} [options.basePath="/"] The absolute path of the config file directory. + * Defaults to `"/"`. + * @param {boolean} [options.normalized=false] Flag indicating if the + * configs have already been normalized. + * @param {Object} [options.schema] The additional schema + * definitions to use for the ConfigArray schema. + * @param {Array} [options.extraConfigTypes] List of config types supported. + * @throws {TypeError} When the `basePath` is not a non-empty string, + */ + constructor( + configs, + { + basePath = "/", + normalized = false, + schema: customSchema, + extraConfigTypes = [], + } = {}, + ) { + super(); + + /** + * Tracks if the array has been normalized. + * @property isNormalized + * @type {boolean} + * @private + */ + this[ConfigArraySymbol.isNormalized] = normalized; + + /** + * The schema used for validating and merging configs. + * @property schema + * @type {ObjectSchemaInstance} + * @private + */ + this[ConfigArraySymbol.schema] = new objectSchema.ObjectSchema( + Object.assign({}, customSchema, baseSchema), + ); + + if (!isString(basePath) || !basePath) { + throw new TypeError("basePath must be a non-empty string"); + } + + /** + * The path of the config file that this array was loaded from. + * This is used to calculate filename matches. + * @property basePath + * @type {string} + */ + this.basePath = basePath; + + assertExtraConfigTypes(extraConfigTypes); + + /** + * The supported config types. + * @type {Array} + */ + this.extraConfigTypes = [...extraConfigTypes]; + Object.freeze(this.extraConfigTypes); + + /** + * A cache to store calculated configs for faster repeat lookup. + * @property configCache + * @type {Map} + * @private + */ + this[ConfigArraySymbol.configCache] = new Map(); + + // init cache + dataCache.set(this, { + explicitMatches: new Map(), + directoryMatches: new Map(), + files: undefined, + ignores: undefined, + }); + + // load the configs into this array + if (Array.isArray(configs)) { + this.push(...configs); + } else { + this.push(configs); + } + + // select path-handling implementations depending on the base path + this.#path = getPathImpl(basePath); + + // On Windows, `path.relative()` returns an absolute path when given two paths on different drives. + // The namespaced base path is useful to make sure that calculated relative paths are always relative. + // On Unix, it is identical to the base path. + this.#namespacedBasePath = this.#path.toNamespacedPath(basePath); + } + + /** + * Prevent normal array methods from creating a new `ConfigArray` instance. + * This is to ensure that methods such as `slice()` won't try to create a + * new instance of `ConfigArray` behind the scenes as doing so may throw + * an error due to the different constructor signature. + * @type {ArrayConstructor} The `Array` constructor. + */ + static get [Symbol.species]() { + return Array; + } + + /** + * Returns the `files` globs from every config object in the array. + * This can be used to determine which files will be matched by a + * config array or to use as a glob pattern when no patterns are provided + * for a command line interface. + * @returns {Array} An array of matchers. + */ + get files() { + assertNormalized(this); + + // if this data has been cached, retrieve it + const cache = dataCache.get(this); + + if (cache.files) { + return cache.files; + } + + // otherwise calculate it + + const result = []; + + for (const config of this) { + if (config.files) { + config.files.forEach(filePattern => { + result.push(filePattern); + }); + } + } + + // store result + cache.files = result; + dataCache.set(this, cache); + + return result; + } + + /** + * Returns ignore matchers that should always be ignored regardless of + * the matching `files` fields in any configs. This is necessary to mimic + * the behavior of things like .gitignore and .eslintignore, allowing a + * globbing operation to be faster. + * @returns {string[]} An array of string patterns and functions to be ignored. + */ + get ignores() { + assertNormalized(this); + + // if this data has been cached, retrieve it + const cache = dataCache.get(this); + + if (cache.ignores) { + return cache.ignores; + } + + // otherwise calculate it + + const result = []; + + for (const config of this) { + /* + * We only count ignores if there are no other keys in the object. + * In this case, it acts list a globally ignored pattern. If there + * are additional keys, then ignores act like exclusions. + */ + if ( + config.ignores && + Object.keys(config).filter(key => !META_FIELDS.has(key)) + .length === 1 + ) { + result.push(...config.ignores); + } + } + + // store result + cache.ignores = result; + dataCache.set(this, cache); + + return result; + } + + /** + * Indicates if the config array has been normalized. + * @returns {boolean} True if the config array is normalized, false if not. + */ + isNormalized() { + return this[ConfigArraySymbol.isNormalized]; + } + + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {Object} [context] The context object for config functions. + * @returns {Promise} The current ConfigArray instance. + */ + async normalize(context = {}) { + if (!this.isNormalized()) { + const normalizedConfigs = await normalize( + this, + context, + this.extraConfigTypes, + ); + this.length = 0; + this.push( + ...normalizedConfigs.map( + this[ConfigArraySymbol.preprocessConfig].bind(this), + ), + ); + this.forEach(assertValidBaseConfig); + this[ConfigArraySymbol.isNormalized] = true; + + // prevent further changes + Object.freeze(this); + } + + return this; + } + + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {Object} [context] The context object for config functions. + * @returns {ConfigArray} The current ConfigArray instance. + */ + normalizeSync(context = {}) { + if (!this.isNormalized()) { + const normalizedConfigs = normalizeSync( + this, + context, + this.extraConfigTypes, + ); + this.length = 0; + this.push( + ...normalizedConfigs.map( + this[ConfigArraySymbol.preprocessConfig].bind(this), + ), + ); + this.forEach(assertValidBaseConfig); + this[ConfigArraySymbol.isNormalized] = true; + + // prevent further changes + Object.freeze(this); + } + + return this; + } + + /* eslint-disable class-methods-use-this -- Desired as instance methods */ + + /** + * Finalizes the state of a config before being cached and returned by + * `getConfig()`. Does nothing by default but is provided to be + * overridden by subclasses as necessary. + * @param {Object} config The config to finalize. + * @returns {Object} The finalized config. + */ + [ConfigArraySymbol.finalizeConfig](config) { + return config; + } + + /** + * Preprocesses a config during the normalization process. This is the + * method to override if you want to convert an array item before it is + * validated for the first time. For example, if you want to replace a + * string with an object, this is the method to override. + * @param {Object} config The config to preprocess. + * @returns {Object} The config to use in place of the argument. + */ + [ConfigArraySymbol.preprocessConfig](config) { + return config; + } + + /* eslint-enable class-methods-use-this -- Desired as instance methods */ + + /** + * Returns the config object for a given file path and a status that can be used to determine why a file has no config. + * @param {string} filePath The path of a file to get a config for. + * @returns {{ config?: Object, status: "ignored"|"external"|"unconfigured"|"matched" }} + * An object with an optional property `config` and property `status`. + * `config` is the config object for the specified file as returned by {@linkcode ConfigArray.getConfig}, + * `status` a is one of the constants returned by {@linkcode ConfigArray.getConfigStatus}. + */ + getConfigWithStatus(filePath) { + assertNormalized(this); + + const cache = this[ConfigArraySymbol.configCache]; + + // first check the cache for a filename match to avoid duplicate work + if (cache.has(filePath)) { + return cache.get(filePath); + } + + // check to see if the file is outside the base path + + const relativeFilePath = toRelativePath( + filePath, + this.#namespacedBasePath, + this.#path, + ); + + if (EXTERNAL_PATH_REGEX.test(relativeFilePath)) { + debug(`No config for file ${filePath} outside of base path`); + + // cache and return result + cache.set(filePath, CONFIG_WITH_STATUS_EXTERNAL); + return CONFIG_WITH_STATUS_EXTERNAL; + } + + // next check to see if the file should be ignored + + // check if this should be ignored due to its directory + if (this.isDirectoryIgnored(this.#path.dirname(filePath))) { + debug(`Ignoring ${filePath} based on directory pattern`); + + // cache and return result + cache.set(filePath, CONFIG_WITH_STATUS_IGNORED); + return CONFIG_WITH_STATUS_IGNORED; + } + + if (shouldIgnorePath(this.ignores, filePath, relativeFilePath)) { + debug(`Ignoring ${filePath} based on file pattern`); + + // cache and return result + cache.set(filePath, CONFIG_WITH_STATUS_IGNORED); + return CONFIG_WITH_STATUS_IGNORED; + } + + // filePath isn't automatically ignored, so try to construct config + + const matchingConfigIndices = []; + let matchFound = false; + const universalPattern = /^\*$|^!|\/\*{1,2}$/u; + + this.forEach((config, index) => { + if (!config.files) { + if (!config.ignores) { + debug(`Universal config found for ${filePath}`); + matchingConfigIndices.push(index); + return; + } + + if (pathMatchesIgnores(filePath, relativeFilePath, config)) { + debug( + `Matching config found for ${filePath} (based on ignores: ${config.ignores})`, + ); + matchingConfigIndices.push(index); + return; + } + + debug( + `Skipped config found for ${filePath} (based on ignores: ${config.ignores})`, + ); + return; + } + + /* + * If a config has a files pattern * or patterns ending in /** or /*, + * and the filePath only matches those patterns, then the config is only + * applied if there is another config where the filePath matches + * a file with a specific extensions such as *.js. + */ + + const nonUniversalFiles = []; + const universalFiles = config.files.filter(element => { + if (Array.isArray(element)) { + /* + * filePath matches an element that is an array only if it matches + * all patterns in it (AND operation). Therefore, if there is at least + * one non-universal pattern in the array, and filePath matches the array, + * then we know for sure that filePath matches at least one non-universal + * pattern, so we can consider the entire array to be non-universal. + * In other words, all patterns in the array need to be universal + * for it to be considered universal. + */ + if ( + element.every(pattern => universalPattern.test(pattern)) + ) { + return true; + } + + nonUniversalFiles.push(element); + return false; + } + + // element is a string + + if (universalPattern.test(element)) { + return true; + } + + nonUniversalFiles.push(element); + return false; + }); + + // universal patterns were found so we need to check the config twice + if (universalFiles.length) { + debug("Universal files patterns found. Checking carefully."); + + // check that the config matches without the non-universal files first + if ( + nonUniversalFiles.length && + pathMatches(filePath, relativeFilePath, { + files: nonUniversalFiles, + ignores: config.ignores, + }) + ) { + debug(`Matching config found for ${filePath}`); + matchingConfigIndices.push(index); + matchFound = true; + return; + } + + // if there wasn't a match then check if it matches with universal files + if ( + universalFiles.length && + pathMatches(filePath, relativeFilePath, { + files: universalFiles, + ignores: config.ignores, + }) + ) { + debug(`Matching config found for ${filePath}`); + matchingConfigIndices.push(index); + return; + } + + // if we make here, then there was no match + return; + } + + // the normal case + if (pathMatches(filePath, relativeFilePath, config)) { + debug(`Matching config found for ${filePath}`); + matchingConfigIndices.push(index); + matchFound = true; + } + }); + + // if matching both files and ignores, there will be no config to create + if (!matchFound) { + debug(`No matching configs found for ${filePath}`); + + // cache and return result + cache.set(filePath, CONFIG_WITH_STATUS_UNCONFIGURED); + return CONFIG_WITH_STATUS_UNCONFIGURED; + } + + // check to see if there is a config cached by indices + const indicesKey = matchingConfigIndices.toString(); + let configWithStatus = cache.get(indicesKey); + + if (configWithStatus) { + // also store for filename for faster lookup next time + cache.set(filePath, configWithStatus); + + return configWithStatus; + } + + // otherwise construct the config + + // eslint-disable-next-line array-callback-return, consistent-return -- rethrowConfigError always throws an error + let finalConfig = matchingConfigIndices.reduce((result, index) => { + try { + return this[ConfigArraySymbol.schema].merge( + result, + this[index], + ); + } catch (validationError) { + rethrowConfigError(this[index], index, validationError); + } + }, {}); + + finalConfig = this[ConfigArraySymbol.finalizeConfig](finalConfig); + + configWithStatus = Object.freeze({ + config: finalConfig, + status: "matched", + }); + cache.set(filePath, configWithStatus); + cache.set(indicesKey, configWithStatus); + + return configWithStatus; + } + + /** + * Returns the config object for a given file path. + * @param {string} filePath The path of a file to get a config for. + * @returns {Object|undefined} The config object for this file or `undefined`. + */ + getConfig(filePath) { + return this.getConfigWithStatus(filePath).config; + } + + /** + * Determines whether a file has a config or why it doesn't. + * @param {string} filePath The path of the file to check. + * @returns {"ignored"|"external"|"unconfigured"|"matched"} One of the following values: + * * `"ignored"`: the file is ignored + * * `"external"`: the file is outside the base path + * * `"unconfigured"`: the file is not matched by any config + * * `"matched"`: the file has a matching config + */ + getConfigStatus(filePath) { + return this.getConfigWithStatus(filePath).status; + } + + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + * @deprecated Use `isFileIgnored` instead. + */ + isIgnored(filePath) { + return this.isFileIgnored(filePath); + } + + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + */ + isFileIgnored(filePath) { + return this.getConfigStatus(filePath) === "ignored"; + } + + /** + * Determines if the given directory is ignored based on the configs. + * This checks only default `ignores` that don't have `files` in the + * same config. A pattern such as `/foo` be considered to ignore the directory + * while a pattern such as `/foo/**` is not considered to ignore the + * directory because it is matching files. + * @param {string} directoryPath The path of a directory to check. + * @returns {boolean} True if the directory is ignored, false if not. Will + * return true for any directory that is not inside of `basePath`. + * @throws {Error} When the `ConfigArray` is not normalized. + */ + isDirectoryIgnored(directoryPath) { + assertNormalized(this); + + const relativeDirectoryPath = toRelativePath( + directoryPath, + this.#namespacedBasePath, + this.#path, + ); + + // basePath directory can never be ignored + if (relativeDirectoryPath === "") { + return false; + } + + if (EXTERNAL_PATH_REGEX.test(relativeDirectoryPath)) { + return true; + } + + // first check the cache + const cache = dataCache.get(this).directoryMatches; + + if (cache.has(relativeDirectoryPath)) { + return cache.get(relativeDirectoryPath); + } + + const directoryParts = relativeDirectoryPath.split("/"); + let relativeDirectoryToCheck = ""; + let result; + + /* + * In order to get the correct gitignore-style ignores, where an + * ignored parent directory cannot have any descendants unignored, + * we need to check every directory starting at the parent all + * the way down to the actual requested directory. + * + * We aggressively cache all of this info to make sure we don't + * have to recalculate everything for every call. + */ + do { + relativeDirectoryToCheck += `${directoryParts.shift()}/`; + + result = shouldIgnorePath( + this.ignores, + this.#path.join(this.basePath, relativeDirectoryToCheck), + relativeDirectoryToCheck, + ); + + cache.set(relativeDirectoryToCheck, result); + } while (!result && directoryParts.length); + + // also cache the result for the requested path + cache.set(relativeDirectoryPath, result); + + return result; + } +} + +Object.defineProperty(exports, "ObjectSchema", { + enumerable: true, + get: function () { return objectSchema.ObjectSchema; } +}); +exports.ConfigArray = ConfigArray; +exports.ConfigArraySymbol = ConfigArraySymbol; diff --git a/node_modules/@eslint/config-array/dist/cjs/index.d.cts b/node_modules/@eslint/config-array/dist/cjs/index.d.cts new file mode 100644 index 00000000..89345c50 --- /dev/null +++ b/node_modules/@eslint/config-array/dist/cjs/index.d.cts @@ -0,0 +1,143 @@ +export { ObjectSchema } from "@eslint/object-schema"; +export type PropertyDefinition = import("@eslint/object-schema").PropertyDefinition; +export type ObjectDefinition = import("@eslint/object-schema").ObjectDefinition; +export type ConfigObject = import("./types.cts").ConfigObject; +export type IMinimatchStatic = import("minimatch").IMinimatchStatic; +export type IMinimatch = import("minimatch").IMinimatch; +export type PathImpl = typeof import("@jsr/std__path"); +export type ObjectSchemaInstance = import("@eslint/object-schema").ObjectSchema; +/** + * Represents an array of config objects and provides method for working with + * those config objects. + */ +export class ConfigArray extends Array { + [x: symbol]: (config: any) => any; + /** + * Creates a new instance of ConfigArray. + * @param {Iterable|Function|Object} configs An iterable yielding config + * objects, or a config function, or a config object. + * @param {Object} options The options for the ConfigArray. + * @param {string} [options.basePath="/"] The absolute path of the config file directory. + * Defaults to `"/"`. + * @param {boolean} [options.normalized=false] Flag indicating if the + * configs have already been normalized. + * @param {Object} [options.schema] The additional schema + * definitions to use for the ConfigArray schema. + * @param {Array} [options.extraConfigTypes] List of config types supported. + * @throws {TypeError} When the `basePath` is not a non-empty string, + */ + constructor(configs: Iterable | Function | any, { basePath, normalized, schema: customSchema, extraConfigTypes, }?: { + basePath?: string; + normalized?: boolean; + schema?: any; + extraConfigTypes?: Array; + }); + /** + * The path of the config file that this array was loaded from. + * This is used to calculate filename matches. + * @property basePath + * @type {string} + */ + basePath: string; + /** + * The supported config types. + * @type {Array} + */ + extraConfigTypes: Array; + /** + * Returns the `files` globs from every config object in the array. + * This can be used to determine which files will be matched by a + * config array or to use as a glob pattern when no patterns are provided + * for a command line interface. + * @returns {Array} An array of matchers. + */ + get files(): Array; + /** + * Returns ignore matchers that should always be ignored regardless of + * the matching `files` fields in any configs. This is necessary to mimic + * the behavior of things like .gitignore and .eslintignore, allowing a + * globbing operation to be faster. + * @returns {string[]} An array of string patterns and functions to be ignored. + */ + get ignores(): string[]; + /** + * Indicates if the config array has been normalized. + * @returns {boolean} True if the config array is normalized, false if not. + */ + isNormalized(): boolean; + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {Object} [context] The context object for config functions. + * @returns {Promise} The current ConfigArray instance. + */ + normalize(context?: any): Promise; + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {Object} [context] The context object for config functions. + * @returns {ConfigArray} The current ConfigArray instance. + */ + normalizeSync(context?: any): ConfigArray; + /** + * Returns the config object for a given file path and a status that can be used to determine why a file has no config. + * @param {string} filePath The path of a file to get a config for. + * @returns {{ config?: Object, status: "ignored"|"external"|"unconfigured"|"matched" }} + * An object with an optional property `config` and property `status`. + * `config` is the config object for the specified file as returned by {@linkcode ConfigArray.getConfig}, + * `status` a is one of the constants returned by {@linkcode ConfigArray.getConfigStatus}. + */ + getConfigWithStatus(filePath: string): { + config?: any; + status: "ignored" | "external" | "unconfigured" | "matched"; + }; + /** + * Returns the config object for a given file path. + * @param {string} filePath The path of a file to get a config for. + * @returns {Object|undefined} The config object for this file or `undefined`. + */ + getConfig(filePath: string): any | undefined; + /** + * Determines whether a file has a config or why it doesn't. + * @param {string} filePath The path of the file to check. + * @returns {"ignored"|"external"|"unconfigured"|"matched"} One of the following values: + * * `"ignored"`: the file is ignored + * * `"external"`: the file is outside the base path + * * `"unconfigured"`: the file is not matched by any config + * * `"matched"`: the file has a matching config + */ + getConfigStatus(filePath: string): "ignored" | "external" | "unconfigured" | "matched"; + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + * @deprecated Use `isFileIgnored` instead. + */ + isIgnored(filePath: string): boolean; + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + */ + isFileIgnored(filePath: string): boolean; + /** + * Determines if the given directory is ignored based on the configs. + * This checks only default `ignores` that don't have `files` in the + * same config. A pattern such as `/foo` be considered to ignore the directory + * while a pattern such as `/foo/**` is not considered to ignore the + * directory because it is matching files. + * @param {string} directoryPath The path of a directory to check. + * @returns {boolean} True if the directory is ignored, false if not. Will + * return true for any directory that is not inside of `basePath`. + * @throws {Error} When the `ConfigArray` is not normalized. + */ + isDirectoryIgnored(directoryPath: string): boolean; + #private; +} +export namespace ConfigArraySymbol { + let isNormalized: symbol; + let configCache: symbol; + let schema: symbol; + let finalizeConfig: symbol; + let preprocessConfig: symbol; +} diff --git a/node_modules/@eslint/config-array/dist/cjs/std__path/posix.cjs b/node_modules/@eslint/config-array/dist/cjs/std__path/posix.cjs new file mode 100644 index 00000000..39530b59 --- /dev/null +++ b/node_modules/@eslint/config-array/dist/cjs/std__path/posix.cjs @@ -0,0 +1,1335 @@ +'use strict'; + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +function assertPath(path) { + if (typeof path !== "string") { + throw new TypeError(`Path must be a string, received "${JSON.stringify(path)}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function stripSuffix(name, suffix) { + if (suffix.length >= name.length) { + return name; + } + const lenDiff = name.length - suffix.length; + for(let i = suffix.length - 1; i >= 0; --i){ + if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) { + return name; + } + } + return name.slice(0, -suffix.length); +} +function lastPathSegment(path, isSep, start = 0) { + let matchedNonSeparator = false; + let end = path.length; + for(let i = path.length - 1; i >= start; --i){ + if (isSep(path.charCodeAt(i))) { + if (matchedNonSeparator) { + start = i + 1; + break; + } + } else if (!matchedNonSeparator) { + matchedNonSeparator = true; + end = i + 1; + } + } + return path.slice(start, end); +} +function assertArgs$1(path, suffix) { + assertPath(path); + if (path.length === 0) return path; + if (typeof suffix !== "string") { + throw new TypeError(`Suffix must be a string, received "${JSON.stringify(suffix)}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg$3(url) { + url = url instanceof URL ? url : new URL(url); + if (url.protocol !== "file:") { + throw new TypeError(`URL must be a file URL: received "${url.protocol}"`); + } + return url; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a file URL to a path string. + * + * @example Usage + * ```ts + * import { fromFileUrl } from "@std/path/posix/from-file-url"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(fromFileUrl(new URL("file:///home/foo")), "/home/foo"); + * ``` + * + * @param url The file URL to convert. + * @returns The path string. + */ function fromFileUrl(url) { + url = assertArg$3(url); + return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25")); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +function stripTrailingSeparators(segment, isSep) { + if (segment.length <= 1) { + return segment; + } + let end = segment.length; + for(let i = segment.length - 1; i > 0; i--){ + if (isSep(segment.charCodeAt(i))) { + end = i; + } else { + break; + } + } + return segment.slice(0, end); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +// Alphabet chars. +// Non-alphabetic chars. +const CHAR_DOT = 46; /* . */ +const CHAR_FORWARD_SLASH = 47; /* / */ + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the last portion of a `path`. + * Trailing directory separators are ignored, and optional suffix is removed. + * + * @example Usage + * ```ts + * import { basename } from "@std/path/posix/basename"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(basename("/home/user/Documents/"), "Documents"); + * assertEquals(basename("/home/user/Documents/image.png"), "image.png"); + * assertEquals(basename("/home/user/Documents/image.png", ".png"), "image"); + * assertEquals(basename(new URL("file:///home/user/Documents/image.png")), "image.png"); + * assertEquals(basename(new URL("file:///home/user/Documents/image.png"), ".png"), "image"); + * ``` + * + * @example Working with URLs + * + * Note: This function doesn't automatically strip hash and query parts from + * URLs. If your URL contains a hash or query, remove them before passing the + * URL to the function. This can be done by passing the URL to `new URL(url)`, + * and setting the `hash` and `search` properties to empty strings. + * + * ```ts + * import { basename } from "@std/path/posix/basename"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(basename("https://deno.land/std/path/mod.ts"), "mod.ts"); + * assertEquals(basename("https://deno.land/std/path/mod.ts", ".ts"), "mod"); + * assertEquals(basename("https://deno.land/std/path/mod.ts?a=b"), "mod.ts?a=b"); + * assertEquals(basename("https://deno.land/std/path/mod.ts#header"), "mod.ts#header"); + * ``` + * + * @param path The path to extract the name from. + * @param suffix The suffix to remove from extracted name. + * @returns The extracted name. + */ function basename(path, suffix = "") { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArgs$1(path, suffix); + const lastSegment = lastPathSegment(path, isPosixPathSeparator); + const strippedSegment = stripTrailingSeparators(lastSegment, isPosixPathSeparator); + return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * The character used to separate entries in the PATH environment variable. + */ const DELIMITER = ":"; +/** + * The character used to separate components of a file path. + */ const SEPARATOR = "/"; +/** + * A regular expression that matches one or more path separators. + */ const SEPARATOR_PATTERN = /\/+/; + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg$2(path) { + assertPath(path); + if (path.length === 0) return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the directory path of a `path`. + * + * @example Usage + * ```ts + * import { dirname } from "@std/path/posix/dirname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(dirname("/home/user/Documents/"), "/home/user"); + * assertEquals(dirname("/home/user/Documents/image.png"), "/home/user/Documents"); + * assertEquals(dirname("https://deno.land/std/path/mod.ts"), "https://deno.land/std/path"); + * assertEquals(dirname(new URL("file:///home/user/Documents/image.png")), "/home/user/Documents"); + * ``` + * + * @example Working with URLs + * + * ```ts + * import { dirname } from "@std/path/posix/dirname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(dirname("https://deno.land/std/path/mod.ts"), "https://deno.land/std/path"); + * assertEquals(dirname("https://deno.land/std/path/mod.ts?a=b"), "https://deno.land/std/path"); + * assertEquals(dirname("https://deno.land/std/path/mod.ts#header"), "https://deno.land/std/path"); + * ``` + * + * @param path The path to get the directory from. + * @returns The directory path. + */ function dirname(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArg$2(path); + let end = -1; + let matchedNonSeparator = false; + for(let i = path.length - 1; i >= 1; --i){ + if (isPosixPathSeparator(path.charCodeAt(i))) { + if (matchedNonSeparator) { + end = i; + break; + } + } else { + matchedNonSeparator = true; + } + } + // No matches. Fallback based on provided path: + // + // - leading slashes paths + // "/foo" => "/" + // "///foo" => "/" + // - no slash path + // "foo" => "." + if (end === -1) { + return isPosixPathSeparator(path.charCodeAt(0)) ? "/" : "."; + } + return stripTrailingSeparators(path.slice(0, end), isPosixPathSeparator); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the extension of the `path` with leading period. + * + * @example Usage + * ```ts + * import { extname } from "@std/path/posix/extname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(extname("/home/user/Documents/file.ts"), ".ts"); + * assertEquals(extname("/home/user/Documents/"), ""); + * assertEquals(extname("/home/user/Documents/image.png"), ".png"); + * assertEquals(extname(new URL("file:///home/user/Documents/file.ts")), ".ts"); + * assertEquals(extname(new URL("file:///home/user/Documents/file.ts?a=b")), ".ts"); + * assertEquals(extname(new URL("file:///home/user/Documents/file.ts#header")), ".ts"); + * ``` + * + * @example Working with URLs + * + * Note: This function doesn't automatically strip hash and query parts from + * URLs. If your URL contains a hash or query, remove them before passing the + * URL to the function. This can be done by passing the URL to `new URL(url)`, + * and setting the `hash` and `search` properties to empty strings. + * + * ```ts + * import { extname } from "@std/path/posix/extname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(extname("https://deno.land/std/path/mod.ts"), ".ts"); + * assertEquals(extname("https://deno.land/std/path/mod.ts?a=b"), ".ts?a=b"); + * assertEquals(extname("https://deno.land/std/path/mod.ts#header"), ".ts#header"); + * ``` + * + * @param path The path to get the extension from. + * @returns The extension (ex. for `file.ts` returns `.ts`). + */ function extname(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertPath(path); + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + for(let i = path.length - 1; i >= 0; --i){ + const code = path.charCodeAt(i); + if (isPosixPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot + preDotState === 0 || // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ""; + } + return path.slice(startDot, end); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function _format(sep, pathObject) { + const dir = pathObject.dir || pathObject.root; + const base = pathObject.base || (pathObject.name ?? "") + (pathObject.ext ?? ""); + if (!dir) return base; + if (base === sep) return dir; + if (dir === pathObject.root) return dir + base; + return dir + sep + base; +} +function assertArg$1(pathObject) { + if (pathObject === null || typeof pathObject !== "object") { + throw new TypeError(`The "pathObject" argument must be of type Object, received type "${typeof pathObject}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Generate a path from `ParsedPath` object. + * + * @example Usage + * ```ts + * import { format } from "@std/path/posix/format"; + * import { assertEquals } from "@std/assert"; + * + * const path = format({ + * root: "/", + * dir: "/path/dir", + * base: "file.txt", + * ext: ".txt", + * name: "file" + * }); + * assertEquals(path, "/path/dir/file.txt"); + * ``` + * + * @param pathObject The path object to format. + * @returns The formatted path. + */ function format(pathObject) { + assertArg$1(pathObject); + return _format("/", pathObject); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Verifies whether provided path is absolute. + * + * @example Usage + * ```ts + * import { isAbsolute } from "@std/path/posix/is-absolute"; + * import { assert, assertFalse } from "@std/assert"; + * + * assert(isAbsolute("/home/user/Documents/")); + * assertFalse(isAbsolute("home/user/Documents/")); + * ``` + * + * @param path The path to verify. + * @returns Whether the path is absolute. + */ function isAbsolute(path) { + assertPath(path); + return path.length > 0 && isPosixPathSeparator(path.charCodeAt(0)); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg(path) { + assertPath(path); + if (path.length === 0) return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +// Resolves . and .. elements in a path with directory names +function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code; + for(let i = 0; i <= path.length; ++i){ + if (i < path.length) code = path.charCodeAt(i); + else if (isPathSeparator(code)) break; + else code = CHAR_FORWARD_SLASH; + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) ; else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf(separator); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } else if (res.length === 2 || res.length === 1) { + res = ""; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) res += `${separator}..`; + else res = ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) res += separator + path.slice(lastSlash + 1, i); + else res = path.slice(lastSlash + 1, i); + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Normalize the `path`, resolving `'..'` and `'.'` segments. + * Note that resolving these segments does not necessarily mean that all will be eliminated. + * A `'..'` at the top-level will be preserved, and an empty path is canonically `'.'`. + * + * @example Usage + * ```ts + * import { normalize } from "@std/path/posix/normalize"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(normalize("/foo/bar//baz/asdf/quux/.."), "/foo/bar/baz/asdf"); + * assertEquals(normalize(new URL("file:///foo/bar//baz/asdf/quux/..")), "/foo/bar/baz/asdf/"); + * ``` + * + * @example Working with URLs + * + * Note: This function will remove the double slashes from a URL's scheme. + * Hence, do not pass a full URL to this function. Instead, pass the pathname of + * the URL. + * + * ```ts + * import { normalize } from "@std/path/posix/normalize"; + * import { assertEquals } from "@std/assert"; + * + * const url = new URL("https://deno.land"); + * url.pathname = normalize("//std//assert//.//mod.ts"); + * assertEquals(url.href, "https://deno.land/std/assert/mod.ts"); + * + * url.pathname = normalize("std/assert/../async/retry.ts"); + * assertEquals(url.href, "https://deno.land/std/async/retry.ts"); + * ``` + * + * @param path The path to normalize. + * @returns The normalized path. + */ function normalize(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArg(path); + const isAbsolute = isPosixPathSeparator(path.charCodeAt(0)); + const trailingSeparator = isPosixPathSeparator(path.charCodeAt(path.length - 1)); + // Normalize the path + path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator); + if (path.length === 0 && !isAbsolute) path = "."; + if (path.length > 0 && trailingSeparator) path += "/"; + if (isAbsolute) return `/${path}`; + return path; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Join all given a sequence of `paths`,then normalizes the resulting path. + * + * @example Usage + * ```ts + * import { join } from "@std/path/posix/join"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(join("/foo", "bar", "baz/asdf", "quux", ".."), "/foo/bar/baz/asdf"); + * assertEquals(join(new URL("file:///foo"), "bar", "baz/asdf", "quux", ".."), "/foo/bar/baz/asdf"); + * ``` + * + * @example Working with URLs + * ```ts + * import { join } from "@std/path/posix/join"; + * import { assertEquals } from "@std/assert"; + * + * const url = new URL("https://deno.land"); + * url.pathname = join("std", "path", "mod.ts"); + * assertEquals(url.href, "https://deno.land/std/path/mod.ts"); + * + * url.pathname = join("//std", "path/", "/mod.ts"); + * assertEquals(url.href, "https://deno.land/std/path/mod.ts"); + * ``` + * + * @param path The path to join. This can be string or file URL. + * @param paths The paths to join. + * @returns The joined path. + */ function join(path, ...paths) { + if (path === undefined) return "."; + if (path instanceof URL) { + path = fromFileUrl(path); + } + paths = path ? [ + path, + ...paths + ] : paths; + paths.forEach((path)=>assertPath(path)); + const joined = paths.filter((path)=>path.length > 0).join("/"); + return joined === "" ? "." : normalize(joined); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return a `ParsedPath` object of the `path`. + * + * @example Usage + * ```ts + * import { parse } from "@std/path/posix/parse"; + * import { assertEquals } from "@std/assert"; + * + * const path = parse("/home/user/file.txt"); + * assertEquals(path, { + * root: "/", + * dir: "/home/user", + * base: "file.txt", + * ext: ".txt", + * name: "file" + * }); + * ``` + * + * @param path The path to parse. + * @returns The parsed path object. + */ function parse(path) { + assertPath(path); + const ret = { + root: "", + dir: "", + base: "", + ext: "", + name: "" + }; + if (path.length === 0) return ret; + const isAbsolute = isPosixPathSeparator(path.charCodeAt(0)); + let start; + if (isAbsolute) { + ret.root = "/"; + start = 1; + } else { + start = 0; + } + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + // Get non-dir info + for(; i >= start; --i){ + const code = path.charCodeAt(i); + if (isPosixPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot + preDotState === 0 || // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) { + ret.base = ret.name = path.slice(1, end); + } else { + ret.base = ret.name = path.slice(startPart, end); + } + } + // Fallback to '/' in case there is no basename + ret.base = ret.base || "/"; + } else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + if (startPart > 0) { + ret.dir = stripTrailingSeparators(path.slice(0, startPart - 1), isPosixPathSeparator); + } else if (isAbsolute) ret.dir = "/"; + return ret; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Resolves path segments into a `path`. + * + * @example Usage + * ```ts + * import { resolve } from "@std/path/posix/resolve"; + * import { assertEquals } from "@std/assert"; + * + * const path = resolve("/foo", "bar", "baz/asdf", "quux", ".."); + * assertEquals(path, "/foo/bar/baz/asdf"); + * ``` + * + * @param pathSegments The path segments to resolve. + * @returns The resolved path. + */ function resolve(...pathSegments) { + let resolvedPath = ""; + let resolvedAbsolute = false; + for(let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--){ + let path; + if (i >= 0) path = pathSegments[i]; + else { + // deno-lint-ignore no-explicit-any + const { Deno } = globalThis; + if (typeof Deno?.cwd !== "function") { + throw new TypeError("Resolved a relative path without a current working directory (CWD)"); + } + path = Deno.cwd(); + } + assertPath(path); + // Skip empty entries + if (path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isPosixPathSeparator(path.charCodeAt(0)); + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when Deno.cwd() fails) + // Normalize the path + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator); + if (resolvedAbsolute) { + if (resolvedPath.length > 0) return `/${resolvedPath}`; + else return "/"; + } else if (resolvedPath.length > 0) return resolvedPath; + else return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArgs(from, to) { + assertPath(from); + assertPath(to); + if (from === to) return ""; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the relative path from `from` to `to` based on current working directory. + * + * If `from` and `to` are the same, return an empty string. + * + * @example Usage + * ```ts + * import { relative } from "@std/path/posix/relative"; + * import { assertEquals } from "@std/assert"; + * + * const path = relative("/data/orandea/test/aaa", "/data/orandea/impl/bbb"); + * assertEquals(path, "../../impl/bbb"); + * ``` + * + * @param from The path to start from. + * @param to The path to reach. + * @returns The relative path. + */ function relative(from, to) { + assertArgs(from, to); + from = resolve(from); + to = resolve(to); + if (from === to) return ""; + // Trim any leading backslashes + let fromStart = 1; + const fromEnd = from.length; + for(; fromStart < fromEnd; ++fromStart){ + if (!isPosixPathSeparator(from.charCodeAt(fromStart))) break; + } + const fromLen = fromEnd - fromStart; + // Trim any leading backslashes + let toStart = 1; + const toEnd = to.length; + for(; toStart < toEnd; ++toStart){ + if (!isPosixPathSeparator(to.charCodeAt(toStart))) break; + } + const toLen = toEnd - toStart; + // Compare paths to find the longest common path from root + const length = fromLen < toLen ? fromLen : toLen; + let lastCommonSep = -1; + let i = 0; + for(; i <= length; ++i){ + if (i === length) { + if (toLen > length) { + if (isPosixPathSeparator(to.charCodeAt(toStart + i))) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } else if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } else if (fromLen > length) { + if (isPosixPathSeparator(from.charCodeAt(fromStart + i))) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo'; to='/' + lastCommonSep = 0; + } + } + break; + } + const fromCode = from.charCodeAt(fromStart + i); + const toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) break; + else if (isPosixPathSeparator(fromCode)) lastCommonSep = i; + } + let out = ""; + // Generate the relative path based on the path difference between `to` + // and `from` + for(i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i){ + if (i === fromEnd || isPosixPathSeparator(from.charCodeAt(i))) { + if (out.length === 0) out += ".."; + else out += "/.."; + } + } + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) return out + to.slice(toStart + lastCommonSep); + else { + toStart += lastCommonSep; + if (isPosixPathSeparator(to.charCodeAt(toStart))) ++toStart; + return to.slice(toStart); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +const WHITESPACE_ENCODINGS = { + "\u0009": "%09", + "\u000A": "%0A", + "\u000B": "%0B", + "\u000C": "%0C", + "\u000D": "%0D", + "\u0020": "%20" +}; +function encodeWhitespace(string) { + return string.replaceAll(/[\s]/g, (c)=>{ + return WHITESPACE_ENCODINGS[c] ?? c; + }); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a path string to a file URL. + * + * @example Usage + * ```ts + * import { toFileUrl } from "@std/path/posix/to-file-url"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(toFileUrl("/home/foo"), new URL("file:///home/foo")); + * assertEquals(toFileUrl("/home/foo bar"), new URL("file:///home/foo%20bar")); + * ``` + * + * @param path The path to convert. + * @returns The file URL. + */ function toFileUrl(path) { + if (!isAbsolute(path)) { + throw new TypeError(`Path must be absolute: received "${path}"`); + } + const url = new URL("file:///"); + url.pathname = encodeWhitespace(path.replace(/%/g, "%25").replace(/\\/g, "%5C")); + return url; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a path to a namespaced path. This function returns the path as is on posix. + * + * @example Usage + * ```ts + * import { toNamespacedPath } from "@std/path/posix/to-namespaced-path"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(toNamespacedPath("/home/foo"), "/home/foo"); + * ``` + * + * @param path The path. + * @returns The namespaced path. + */ function toNamespacedPath(path) { + // Non-op on posix systems + return path; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function common$1(paths, sep) { + const [first = "", ...remaining] = paths; + const parts = first.split(sep); + let endOfPrefix = parts.length; + let append = ""; + for (const path of remaining){ + const compare = path.split(sep); + if (compare.length <= endOfPrefix) { + endOfPrefix = compare.length; + append = ""; + } + for(let i = 0; i < endOfPrefix; i++){ + if (compare[i] !== parts[i]) { + endOfPrefix = i; + append = i === 0 ? "" : sep; + break; + } + } + } + return parts.slice(0, endOfPrefix).join(sep) + append; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** Determines the common path from a set of paths for POSIX systems. + * + * @example Usage + * ```ts + * import { common } from "@std/path/posix/common"; + * import { assertEquals } from "@std/assert"; + * + * const path = common([ + * "./deno/std/path/mod.ts", + * "./deno/std/fs/mod.ts", + * ]); + * assertEquals(path, "./deno/std/"); + * ``` + * + * @param paths The paths to compare. + * @returns The common path. + */ function common(paths) { + return common$1(paths, SEPARATOR); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Options for {@linkcode globToRegExp}, {@linkcode joinGlobs}, + * {@linkcode normalizeGlob} and {@linkcode expandGlob}. + */ const REG_EXP_ESCAPE_CHARS = [ + "!", + "$", + "(", + ")", + "*", + "+", + ".", + "=", + "?", + "[", + "\\", + "^", + "{", + "|" +]; +const RANGE_ESCAPE_CHARS = [ + "-", + "\\", + "]" +]; +function _globToRegExp(c, glob, { extended = true, globstar: globstarOption = true, // os = osType, +caseInsensitive = false } = {}) { + if (glob === "") { + return /(?!)/; + } + // Remove trailing separators. + let newLength = glob.length; + for(; newLength > 1 && c.seps.includes(glob[newLength - 1]); newLength--); + glob = glob.slice(0, newLength); + let regExpString = ""; + // Terminates correctly. Trust that `j` is incremented every iteration. + for(let j = 0; j < glob.length;){ + let segment = ""; + const groupStack = []; + let inRange = false; + let inEscape = false; + let endsWithSep = false; + let i = j; + // Terminates with `i` at the non-inclusive end of the current segment. + for(; i < glob.length && !c.seps.includes(glob[i]); i++){ + if (inEscape) { + inEscape = false; + const escapeChars = inRange ? RANGE_ESCAPE_CHARS : REG_EXP_ESCAPE_CHARS; + segment += escapeChars.includes(glob[i]) ? `\\${glob[i]}` : glob[i]; + continue; + } + if (glob[i] === c.escapePrefix) { + inEscape = true; + continue; + } + if (glob[i] === "[") { + if (!inRange) { + inRange = true; + segment += "["; + if (glob[i + 1] === "!") { + i++; + segment += "^"; + } else if (glob[i + 1] === "^") { + i++; + segment += "\\^"; + } + continue; + } else if (glob[i + 1] === ":") { + let k = i + 1; + let value = ""; + while(glob[k + 1] !== undefined && glob[k + 1] !== ":"){ + value += glob[k + 1]; + k++; + } + if (glob[k + 1] === ":" && glob[k + 2] === "]") { + i = k + 2; + if (value === "alnum") segment += "\\dA-Za-z"; + else if (value === "alpha") segment += "A-Za-z"; + else if (value === "ascii") segment += "\x00-\x7F"; + else if (value === "blank") segment += "\t "; + else if (value === "cntrl") segment += "\x00-\x1F\x7F"; + else if (value === "digit") segment += "\\d"; + else if (value === "graph") segment += "\x21-\x7E"; + else if (value === "lower") segment += "a-z"; + else if (value === "print") segment += "\x20-\x7E"; + else if (value === "punct") { + segment += "!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_‘{|}~"; + } else if (value === "space") segment += "\\s\v"; + else if (value === "upper") segment += "A-Z"; + else if (value === "word") segment += "\\w"; + else if (value === "xdigit") segment += "\\dA-Fa-f"; + continue; + } + } + } + if (glob[i] === "]" && inRange) { + inRange = false; + segment += "]"; + continue; + } + if (inRange) { + segment += glob[i]; + continue; + } + if (glob[i] === ")" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") { + segment += ")"; + const type = groupStack.pop(); + if (type === "!") { + segment += c.wildcard; + } else if (type !== "@") { + segment += type; + } + continue; + } + if (glob[i] === "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") { + segment += "|"; + continue; + } + if (glob[i] === "+" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("+"); + segment += "(?:"; + continue; + } + if (glob[i] === "@" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("@"); + segment += "(?:"; + continue; + } + if (glob[i] === "?") { + if (extended && glob[i + 1] === "(") { + i++; + groupStack.push("?"); + segment += "(?:"; + } else { + segment += "."; + } + continue; + } + if (glob[i] === "!" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("!"); + segment += "(?!"; + continue; + } + if (glob[i] === "{") { + groupStack.push("BRACE"); + segment += "(?:"; + continue; + } + if (glob[i] === "}" && groupStack[groupStack.length - 1] === "BRACE") { + groupStack.pop(); + segment += ")"; + continue; + } + if (glob[i] === "," && groupStack[groupStack.length - 1] === "BRACE") { + segment += "|"; + continue; + } + if (glob[i] === "*") { + if (extended && glob[i + 1] === "(") { + i++; + groupStack.push("*"); + segment += "(?:"; + } else { + const prevChar = glob[i - 1]; + let numStars = 1; + while(glob[i + 1] === "*"){ + i++; + numStars++; + } + const nextChar = glob[i + 1]; + if (globstarOption && numStars === 2 && [ + ...c.seps, + undefined + ].includes(prevChar) && [ + ...c.seps, + undefined + ].includes(nextChar)) { + segment += c.globstar; + endsWithSep = true; + } else { + segment += c.wildcard; + } + } + continue; + } + segment += REG_EXP_ESCAPE_CHARS.includes(glob[i]) ? `\\${glob[i]}` : glob[i]; + } + // Check for unclosed groups or a dangling backslash. + if (groupStack.length > 0 || inRange || inEscape) { + // Parse failure. Take all characters from this segment literally. + segment = ""; + for (const c of glob.slice(j, i)){ + segment += REG_EXP_ESCAPE_CHARS.includes(c) ? `\\${c}` : c; + endsWithSep = false; + } + } + regExpString += segment; + if (!endsWithSep) { + regExpString += i < glob.length ? c.sep : c.sepMaybe; + endsWithSep = true; + } + // Terminates with `i` at the start of the next segment. + while(c.seps.includes(glob[i]))i++; + j = i; + } + regExpString = `^${regExpString}$`; + return new RegExp(regExpString, caseInsensitive ? "i" : ""); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +const constants = { + sep: "/+", + sepMaybe: "/*", + seps: [ + "/" + ], + globstar: "(?:[^/]*(?:/|$)+)*", + wildcard: "[^/]*", + escapePrefix: "\\" +}; +/** Convert a glob string to a regular expression. + * + * Tries to match bash glob expansion as closely as possible. + * + * Basic glob syntax: + * - `*` - Matches everything without leaving the path segment. + * - `?` - Matches any single character. + * - `{foo,bar}` - Matches `foo` or `bar`. + * - `[abcd]` - Matches `a`, `b`, `c` or `d`. + * - `[a-d]` - Matches `a`, `b`, `c` or `d`. + * - `[!abcd]` - Matches any single character besides `a`, `b`, `c` or `d`. + * - `[[::]]` - Matches any character belonging to ``. + * - `[[:alnum:]]` - Matches any digit or letter. + * - `[[:digit:]abc]` - Matches any digit, `a`, `b` or `c`. + * - See https://facelessuser.github.io/wcmatch/glob/#posix-character-classes + * for a complete list of supported character classes. + * - `\` - Escapes the next character for an `os` other than `"windows"`. + * - \` - Escapes the next character for `os` set to `"windows"`. + * - `/` - Path separator. + * - `\` - Additional path separator only for `os` set to `"windows"`. + * + * Extended syntax: + * - Requires `{ extended: true }`. + * - `?(foo|bar)` - Matches 0 or 1 instance of `{foo,bar}`. + * - `@(foo|bar)` - Matches 1 instance of `{foo,bar}`. They behave the same. + * - `*(foo|bar)` - Matches _n_ instances of `{foo,bar}`. + * - `+(foo|bar)` - Matches _n > 0_ instances of `{foo,bar}`. + * - `!(foo|bar)` - Matches anything other than `{foo,bar}`. + * - See https://www.linuxjournal.com/content/bash-extended-globbing. + * + * Globstar syntax: + * - Requires `{ globstar: true }`. + * - `**` - Matches any number of any path segments. + * - Must comprise its entire path segment in the provided glob. + * - See https://www.linuxjournal.com/content/globstar-new-bash-globbing-option. + * + * Note the following properties: + * - The generated `RegExp` is anchored at both start and end. + * - Repeating and trailing separators are tolerated. Trailing separators in the + * provided glob have no meaning and are discarded. + * - Absolute globs will only match absolute paths, etc. + * - Empty globs will match nothing. + * - Any special glob syntax must be contained to one path segment. For example, + * `?(foo|bar/baz)` is invalid. The separator will take precedence and the + * first segment ends with an unclosed group. + * - If a path segment ends with unclosed groups or a dangling escape prefix, a + * parse error has occurred. Every character for that segment is taken + * literally in this event. + * + * Limitations: + * - A negative group like `!(foo|bar)` will wrongly be converted to a negative + * look-ahead followed by a wildcard. This means that `!(foo).js` will wrongly + * fail to match `foobar.js`, even though `foobar` is not `foo`. Effectively, + * `!(foo|bar)` is treated like `!(@(foo|bar)*)`. This will work correctly if + * the group occurs not nested at the end of the segment. + * + * @example Usage + * ```ts + * import { globToRegExp } from "@std/path/posix/glob-to-regexp"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(globToRegExp("*.js"), /^[^/]*\.js\/*$/); + * ``` + * + * @param glob Glob string to convert. + * @param options Conversion options. + * @returns The regular expression equivalent to the glob. + */ function globToRegExp(glob, options = {}) { + return _globToRegExp(constants, glob, options); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Test whether the given string is a glob. + * + * @example Usage + * ```ts + * import { isGlob } from "@std/path/is-glob"; + * import { assert } from "@std/assert"; + * + * assert(!isGlob("foo/bar/../baz")); + * assert(isGlob("foo/*ar/../baz")); + * ``` + * + * @param str String to test. + * @returns `true` if the given string is a glob, otherwise `false` + */ function isGlob(str) { + const chars = { + "{": "}", + "(": ")", + "[": "]" + }; + const regex = /\\(.)|(^!|\*|\?|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; + if (str === "") { + return false; + } + let match; + while(match = regex.exec(str)){ + if (match[2]) return true; + let idx = match.index + match[0].length; + // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + const open = match[1]; + const close = open ? chars[open] : null; + if (open && close) { + const n = str.indexOf(close, idx); + if (n !== -1) { + idx = n + 1; + } + } + str = str.slice(idx); + } + return false; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Like normalize(), but doesn't collapse "**\/.." when `globstar` is true. + * + * @example Usage + * ```ts + * import { normalizeGlob } from "@std/path/posix/normalize-glob"; + * import { assertEquals } from "@std/assert"; + * + * const path = normalizeGlob("foo/bar/../*", { globstar: true }); + * assertEquals(path, "foo/*"); + * ``` + * + * @param glob The glob to normalize. + * @param options The options to use. + * @returns The normalized path. + */ function normalizeGlob(glob, options = {}) { + const { globstar = false } = options; + if (glob.match(/\0/g)) { + throw new Error(`Glob contains invalid characters: "${glob}"`); + } + if (!globstar) { + return normalize(glob); + } + const s = SEPARATOR_PATTERN.source; + const badParentPattern = new RegExp(`(?<=(${s}|^)\\*\\*${s})\\.\\.(?=${s}|$)`, "g"); + return normalize(glob.replace(badParentPattern, "\0")).replace(/\0/g, ".."); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Like join(), but doesn't collapse "**\/.." when `globstar` is true. + * + * @example Usage + * ```ts + * import { joinGlobs } from "@std/path/posix/join-globs"; + * import { assertEquals } from "@std/assert"; + * + * const path = joinGlobs(["foo", "bar", "**"], { globstar: true }); + * assertEquals(path, "foo/bar/**"); + * ``` + * + * @param globs The globs to join. + * @param options The options to use. + * @returns The joined path. + */ function joinGlobs(globs, options = {}) { + const { globstar = false } = options; + if (!globstar || globs.length === 0) { + return join(...globs); + } + let joined; + for (const glob of globs){ + const path = glob; + if (path.length > 0) { + if (!joined) joined = path; + else joined += `${SEPARATOR}${path}`; + } + } + if (!joined) return "."; + return normalizeGlob(joined, { + globstar + }); +} + +exports.DELIMITER = DELIMITER; +exports.SEPARATOR = SEPARATOR; +exports.SEPARATOR_PATTERN = SEPARATOR_PATTERN; +exports.basename = basename; +exports.common = common; +exports.dirname = dirname; +exports.extname = extname; +exports.format = format; +exports.fromFileUrl = fromFileUrl; +exports.globToRegExp = globToRegExp; +exports.isAbsolute = isAbsolute; +exports.isGlob = isGlob; +exports.join = join; +exports.joinGlobs = joinGlobs; +exports.normalize = normalize; +exports.normalizeGlob = normalizeGlob; +exports.parse = parse; +exports.relative = relative; +exports.resolve = resolve; +exports.toFileUrl = toFileUrl; +exports.toNamespacedPath = toNamespacedPath; diff --git a/node_modules/@eslint/config-array/dist/cjs/std__path/windows.cjs b/node_modules/@eslint/config-array/dist/cjs/std__path/windows.cjs new file mode 100644 index 00000000..d6032eff --- /dev/null +++ b/node_modules/@eslint/config-array/dist/cjs/std__path/windows.cjs @@ -0,0 +1,1677 @@ +'use strict'; + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +function assertPath(path) { + if (typeof path !== "string") { + throw new TypeError(`Path must be a string, received "${JSON.stringify(path)}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function stripSuffix(name, suffix) { + if (suffix.length >= name.length) { + return name; + } + const lenDiff = name.length - suffix.length; + for(let i = suffix.length - 1; i >= 0; --i){ + if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) { + return name; + } + } + return name.slice(0, -suffix.length); +} +function lastPathSegment(path, isSep, start = 0) { + let matchedNonSeparator = false; + let end = path.length; + for(let i = path.length - 1; i >= start; --i){ + if (isSep(path.charCodeAt(i))) { + if (matchedNonSeparator) { + start = i + 1; + break; + } + } else if (!matchedNonSeparator) { + matchedNonSeparator = true; + end = i + 1; + } + } + return path.slice(start, end); +} +function assertArgs$1(path, suffix) { + assertPath(path); + if (path.length === 0) return path; + if (typeof suffix !== "string") { + throw new TypeError(`Suffix must be a string, received "${JSON.stringify(suffix)}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +// Alphabet chars. +const CHAR_UPPERCASE_A = 65; /* A */ +const CHAR_LOWERCASE_A = 97; /* a */ +const CHAR_UPPERCASE_Z = 90; /* Z */ +const CHAR_LOWERCASE_Z = 122; /* z */ +// Non-alphabetic chars. +const CHAR_DOT = 46; /* . */ +const CHAR_FORWARD_SLASH = 47; /* / */ +const CHAR_BACKWARD_SLASH = 92; /* \ */ +const CHAR_COLON = 58; /* : */ +const CHAR_QUESTION_MARK = 63; /* ? */ + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +function stripTrailingSeparators(segment, isSep) { + if (segment.length <= 1) { + return segment; + } + let end = segment.length; + for(let i = segment.length - 1; i > 0; i--){ + if (isSep(segment.charCodeAt(i))) { + end = i; + } else { + break; + } + } + return segment.slice(0, end); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; +} +function isPathSeparator(code) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +} +function isWindowsDeviceRoot(code) { + return code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z || code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg$3(url) { + url = url instanceof URL ? url : new URL(url); + if (url.protocol !== "file:") { + throw new TypeError(`URL must be a file URL: received "${url.protocol}"`); + } + return url; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a file URL to a path string. + * + * @example Usage + * ```ts + * import { fromFileUrl } from "@std/path/windows/from-file-url"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(fromFileUrl("file:///home/foo"), "\\home\\foo"); + * assertEquals(fromFileUrl("file:///C:/Users/foo"), "C:\\Users\\foo"); + * assertEquals(fromFileUrl("file://localhost/home/foo"), "\\home\\foo"); + * ``` + * + * @param url The file URL to convert. + * @returns The path string. + */ function fromFileUrl(url) { + url = assertArg$3(url); + let path = decodeURIComponent(url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\"); + if (url.hostname !== "") { + // Note: The `URL` implementation guarantees that the drive letter and + // hostname are mutually exclusive. Otherwise it would not have been valid + // to append the hostname and path like this. + path = `\\\\${url.hostname}${path}`; + } + return path; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the last portion of a `path`. + * Trailing directory separators are ignored, and optional suffix is removed. + * + * @example Usage + * ```ts + * import { basename } from "@std/path/windows/basename"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(basename("C:\\user\\Documents\\"), "Documents"); + * assertEquals(basename("C:\\user\\Documents\\image.png"), "image.png"); + * assertEquals(basename("C:\\user\\Documents\\image.png", ".png"), "image"); + * assertEquals(basename(new URL("file:///C:/user/Documents/image.png")), "image.png"); + * assertEquals(basename(new URL("file:///C:/user/Documents/image.png"), ".png"), "image"); + * ``` + * + * @param path The path to extract the name from. + * @param suffix The suffix to remove from extracted name. + * @returns The extracted name. + */ function basename(path, suffix = "") { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArgs$1(path, suffix); + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + let start = 0; + if (path.length >= 2) { + const drive = path.charCodeAt(0); + if (isWindowsDeviceRoot(drive)) { + if (path.charCodeAt(1) === CHAR_COLON) start = 2; + } + } + const lastSegment = lastPathSegment(path, isPathSeparator, start); + const strippedSegment = stripTrailingSeparators(lastSegment, isPathSeparator); + return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * The character used to separate entries in the PATH environment variable. + */ const DELIMITER = ";"; +/** + * The character used to separate components of a file path. + */ const SEPARATOR = "\\"; +/** + * A regular expression that matches one or more path separators. + */ const SEPARATOR_PATTERN = /[\\/]+/; + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg$2(path) { + assertPath(path); + if (path.length === 0) return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the directory path of a `path`. + * + * @example Usage + * ```ts + * import { dirname } from "@std/path/windows/dirname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(dirname("C:\\foo\\bar\\baz.ext"), "C:\\foo\\bar"); + * assertEquals(dirname(new URL("file:///C:/foo/bar/baz.ext")), "C:\\foo\\bar"); + * ``` + * + * @param path The path to get the directory from. + * @returns The directory path. + */ function dirname(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArg$2(path); + const len = path.length; + let rootEnd = -1; + let end = -1; + let matchedSlash = true; + let offset = 0; + const code = path.charCodeAt(0); + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + rootEnd = offset = 1; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for(; j < len; ++j){ + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + return path; + } + if (j !== last) { + // We matched a UNC root with leftovers + // Offset by 1 to include the separator after the UNC root to + // treat it as a "normal root" on top of a (UNC) root + rootEnd = offset = j + 1; + } + } + } + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (path.charCodeAt(1) === CHAR_COLON) { + rootEnd = offset = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) rootEnd = offset = 3; + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work + return path; + } + for(let i = len - 1; i >= offset; --i){ + if (isPathSeparator(path.charCodeAt(i))) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + if (end === -1) { + if (rootEnd === -1) return "."; + else end = rootEnd; + } + return stripTrailingSeparators(path.slice(0, end), isPosixPathSeparator); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the extension of the `path` with leading period. + * + * @example Usage + * ```ts + * import { extname } from "@std/path/windows/extname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(extname("file.ts"), ".ts"); + * assertEquals(extname(new URL("file:///C:/foo/bar/baz.ext")), ".ext"); + * ``` + * + * @param path The path to get the extension from. + * @returns The extension of the `path`. + */ function extname(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertPath(path); + let start = 0; + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) { + start = startPart = 2; + } + for(let i = path.length - 1; i >= start; --i){ + const code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot + preDotState === 0 || // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ""; + } + return path.slice(startDot, end); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function _format(sep, pathObject) { + const dir = pathObject.dir || pathObject.root; + const base = pathObject.base || (pathObject.name ?? "") + (pathObject.ext ?? ""); + if (!dir) return base; + if (base === sep) return dir; + if (dir === pathObject.root) return dir + base; + return dir + sep + base; +} +function assertArg$1(pathObject) { + if (pathObject === null || typeof pathObject !== "object") { + throw new TypeError(`The "pathObject" argument must be of type Object, received type "${typeof pathObject}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Generate a path from `ParsedPath` object. + * + * @example Usage + * ```ts + * import { format } from "@std/path/windows/format"; + * import { assertEquals } from "@std/assert"; + * + * const path = format({ + * root: "C:\\", + * dir: "C:\\path\\dir", + * base: "file.txt", + * ext: ".txt", + * name: "file" + * }); + * assertEquals(path, "C:\\path\\dir\\file.txt"); + * ``` + * + * @param pathObject The path object to format. + * @returns The formatted path. + */ function format(pathObject) { + assertArg$1(pathObject); + return _format("\\", pathObject); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Verifies whether provided path is absolute. + * + * @example Usage + * ```ts + * import { isAbsolute } from "@std/path/windows/is-absolute"; + * import { assert, assertFalse } from "@std/assert"; + * + * assert(isAbsolute("C:\\foo\\bar")); + * assertFalse(isAbsolute("..\\baz")); + * ``` + * + * @param path The path to verify. + * @returns `true` if the path is absolute, `false` otherwise. + */ function isAbsolute(path) { + assertPath(path); + const len = path.length; + if (len === 0) return false; + const code = path.charCodeAt(0); + if (isPathSeparator(code)) { + return true; + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (len > 2 && path.charCodeAt(1) === CHAR_COLON) { + if (isPathSeparator(path.charCodeAt(2))) return true; + } + } + return false; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg(path) { + assertPath(path); + if (path.length === 0) return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +// Resolves . and .. elements in a path with directory names +function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code; + for(let i = 0; i <= path.length; ++i){ + if (i < path.length) code = path.charCodeAt(i); + else if (isPathSeparator(code)) break; + else code = CHAR_FORWARD_SLASH; + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) ; else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf(separator); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } else if (res.length === 2 || res.length === 1) { + res = ""; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) res += `${separator}..`; + else res = ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) res += separator + path.slice(lastSlash + 1, i); + else res = path.slice(lastSlash + 1, i); + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Normalize the `path`, resolving `'..'` and `'.'` segments. + * Note that resolving these segments does not necessarily mean that all will be eliminated. + * A `'..'` at the top-level will be preserved, and an empty path is canonically `'.'`. + * + * @example Usage + * ```ts + * import { normalize } from "@std/path/windows/normalize"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(normalize("C:\\foo\\..\\bar"), "C:\\bar"); + * assertEquals(normalize(new URL("file:///C:/foo/../bar")), "C:\\bar"); + * ``` + * + * @param path The path to normalize + * @returns The normalized path + */ function normalize(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArg(path); + const len = path.length; + let rootEnd = 0; + let device; + let isAbsolute = false; + const code = path.charCodeAt(0); + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + // If we started with a separator, we know we at least have an absolute + // path of some kind (UNC or otherwise) + isAbsolute = true; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + for(; j < len; ++j){ + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + // Return the normalized version of the UNC root since there + // is nothing left to process + return `\\\\${firstPart}\\${path.slice(last)}\\`; + } else if (j !== last) { + // We matched a UNC root with leftovers + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } else { + rootEnd = 1; + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid unnecessary + // work + return "\\"; + } + let tail; + if (rootEnd < len) { + tail = normalizeString(path.slice(rootEnd), !isAbsolute, "\\", isPathSeparator); + } else { + tail = ""; + } + if (tail.length === 0 && !isAbsolute) tail = "."; + if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) { + tail += "\\"; + } + if (device === undefined) { + if (isAbsolute) { + if (tail.length > 0) return `\\${tail}`; + else return "\\"; + } + return tail; + } else if (isAbsolute) { + if (tail.length > 0) return `${device}\\${tail}`; + else return `${device}\\`; + } + return device + tail; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Join all given a sequence of `paths`,then normalizes the resulting path. + * + * @example Usage + * ```ts + * import { join } from "@std/path/windows/join"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(join("C:\\foo", "bar", "baz\\.."), "C:\\foo\\bar"); + * assertEquals(join(new URL("file:///C:/foo"), "bar", "baz\\.."), "C:\\foo\\bar"); + * ``` + * + * @param path The path to join. This can be string or file URL. + * @param paths The paths to join. + * @returns The joined path. + */ function join(path, ...paths) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + paths = path ? [ + path, + ...paths + ] : paths; + paths.forEach((path)=>assertPath(path)); + paths = paths.filter((path)=>path.length > 0); + if (paths.length === 0) return "."; + // Make sure that the joined path doesn't start with two slashes, because + // normalize() will mistake it for an UNC path then. + // + // This step is skipped when it is very clear that the user actually + // intended to point at an UNC path. This is assumed when the first + // non-empty string arguments starts with exactly two slashes followed by + // at least one more non-slash character. + // + // Note that for normalize() to treat a path as an UNC path it needs to + // have at least 2 components, so we don't filter for that here. + // This means that the user can use join to construct UNC paths from + // a server name and a share name; for example: + // path.join('//server', 'share') -> '\\\\server\\share\\' + let needsReplace = true; + let slashCount = 0; + const firstPart = paths[0]; + if (isPathSeparator(firstPart.charCodeAt(0))) { + ++slashCount; + const firstLen = firstPart.length; + if (firstLen > 1) { + if (isPathSeparator(firstPart.charCodeAt(1))) { + ++slashCount; + if (firstLen > 2) { + if (isPathSeparator(firstPart.charCodeAt(2))) ++slashCount; + else { + // We matched a UNC path in the first part + needsReplace = false; + } + } + } + } + } + let joined = paths.join("\\"); + if (needsReplace) { + // Find any more consecutive slashes we need to replace + for(; slashCount < joined.length; ++slashCount){ + if (!isPathSeparator(joined.charCodeAt(slashCount))) break; + } + // Replace the slashes if needed + if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`; + } + return normalize(joined); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return a `ParsedPath` object of the `path`. + * + * @example Usage + * ```ts + * import { parse } from "@std/path/windows/parse"; + * import { assertEquals } from "@std/assert"; + * + * const parsed = parse("C:\\foo\\bar\\baz.ext"); + * assertEquals(parsed, { + * root: "C:\\", + * dir: "C:\\foo\\bar", + * base: "baz.ext", + * ext: ".ext", + * name: "baz", + * }); + * ``` + * + * @param path The path to parse. + * @returns The `ParsedPath` object. + */ function parse(path) { + assertPath(path); + const ret = { + root: "", + dir: "", + base: "", + ext: "", + name: "" + }; + const len = path.length; + if (len === 0) return ret; + let rootEnd = 0; + let code = path.charCodeAt(0); + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + rootEnd = 1; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for(; j < len; ++j){ + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + rootEnd = j; + } else if (j !== last) { + // We matched a UNC root with leftovers + rootEnd = j + 1; + } + } + } + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (path.charCodeAt(1) === CHAR_COLON) { + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + if (len === 3) { + // `path` contains just a drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + ret.base = "\\"; + return ret; + } + rootEnd = 3; + } + } else { + // `path` contains just a relative drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + ret.base = "\\"; + return ret; + } + if (rootEnd > 0) ret.root = path.slice(0, rootEnd); + let startDot = -1; + let startPart = rootEnd; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + // Get non-dir info + for(; i >= rootEnd; --i){ + code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot + preDotState === 0 || // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + ret.base = ret.name = path.slice(startPart, end); + } + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + ret.ext = path.slice(startDot, end); + } + // Fallback to '\' in case there is no basename + ret.base = ret.base || "\\"; + // If the directory is the root, use the entire root as the `dir` including + // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the + // trailing slash (`C:\abc\def` -> `C:\abc`). + if (startPart > 0 && startPart !== rootEnd) { + ret.dir = path.slice(0, startPart - 1); + } else ret.dir = ret.root; + return ret; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Resolves path segments into a `path`. + * + * @example Usage + * ```ts + * import { resolve } from "@std/path/windows/resolve"; + * import { assertEquals } from "@std/assert"; + * + * const resolved = resolve("C:\\foo\\bar", "..\\baz"); + * assertEquals(resolved, "C:\\foo\\baz"); + * ``` + * + * @param pathSegments The path segments to process to path + * @returns The resolved path + */ function resolve(...pathSegments) { + let resolvedDevice = ""; + let resolvedTail = ""; + let resolvedAbsolute = false; + for(let i = pathSegments.length - 1; i >= -1; i--){ + let path; + // deno-lint-ignore no-explicit-any + const { Deno } = globalThis; + if (i >= 0) { + path = pathSegments[i]; + } else if (!resolvedDevice) { + if (typeof Deno?.cwd !== "function") { + throw new TypeError("Resolved a drive-letter-less path without a current working directory (CWD)"); + } + path = Deno.cwd(); + } else { + if (typeof Deno?.env?.get !== "function" || typeof Deno?.cwd !== "function") { + throw new TypeError("Resolved a relative path without a current working directory (CWD)"); + } + path = Deno.cwd(); + // Verify that a cwd was found and that it actually points + // to our drive. If not, default to the drive's root. + if (path === undefined || path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`) { + path = `${resolvedDevice}\\`; + } + } + assertPath(path); + const len = path.length; + // Skip empty entries + if (len === 0) continue; + let rootEnd = 0; + let device = ""; + let isAbsolute = false; + const code = path.charCodeAt(0); + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + // If we started with a separator, we know we at least have an + // absolute path of some kind (UNC or otherwise) + isAbsolute = true; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + for(; j < len; ++j){ + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + device = `\\\\${firstPart}\\${path.slice(last)}`; + rootEnd = j; + } else if (j !== last) { + // We matched a UNC root with leftovers + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } else { + rootEnd = 1; + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator + rootEnd = 1; + isAbsolute = true; + } + if (device.length > 0 && resolvedDevice.length > 0 && device.toLowerCase() !== resolvedDevice.toLowerCase()) { + continue; + } + if (resolvedDevice.length === 0 && device.length > 0) { + resolvedDevice = device; + } + if (!resolvedAbsolute) { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + } + if (resolvedAbsolute && resolvedDevice.length > 0) break; + } + // At this point the path should be resolved to a full absolute path, + // but handle relative paths to be safe (might happen when Deno.cwd() + // fails) + // Normalize the tail path + resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator); + return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArgs(from, to) { + assertPath(from); + assertPath(to); + if (from === to) return ""; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the relative path from `from` to `to` based on current working directory. + * + * An example in windws, for instance: + * from = 'C:\\orandea\\test\\aaa' + * to = 'C:\\orandea\\impl\\bbb' + * The output of the function should be: '..\\..\\impl\\bbb' + * + * @example Usage + * ```ts + * import { relative } from "@std/path/windows/relative"; + * import { assertEquals } from "@std/assert"; + * + * const relativePath = relative("C:\\foobar\\test\\aaa", "C:\\foobar\\impl\\bbb"); + * assertEquals(relativePath, "..\\..\\impl\\bbb"); + * ``` + * + * @param from The path from which to calculate the relative path + * @param to The path to which to calculate the relative path + * @returns The relative path from `from` to `to` + */ function relative(from, to) { + assertArgs(from, to); + const fromOrig = resolve(from); + const toOrig = resolve(to); + if (fromOrig === toOrig) return ""; + from = fromOrig.toLowerCase(); + to = toOrig.toLowerCase(); + if (from === to) return ""; + // Trim any leading backslashes + let fromStart = 0; + let fromEnd = from.length; + for(; fromStart < fromEnd; ++fromStart){ + if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH) break; + } + // Trim trailing backslashes (applicable to UNC paths only) + for(; fromEnd - 1 > fromStart; --fromEnd){ + if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break; + } + const fromLen = fromEnd - fromStart; + // Trim any leading backslashes + let toStart = 0; + let toEnd = to.length; + for(; toStart < toEnd; ++toStart){ + if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH) break; + } + // Trim trailing backslashes (applicable to UNC paths only) + for(; toEnd - 1 > toStart; --toEnd){ + if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break; + } + const toLen = toEnd - toStart; + // Compare paths to find the longest common path from root + const length = fromLen < toLen ? fromLen : toLen; + let lastCommonSep = -1; + let i = 0; + for(; i <= length; ++i){ + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' + return toOrig.slice(toStart + i + 1); + } else if (i === 2) { + // We get here if `from` is the device root. + // For example: from='C:\\'; to='C:\\foo' + return toOrig.slice(toStart + i); + } + } + if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='C:\\foo\\bar'; to='C:\\foo' + lastCommonSep = i; + } else if (i === 2) { + // We get here if `to` is the device root. + // For example: from='C:\\foo\\bar'; to='C:\\' + lastCommonSep = 3; + } + } + break; + } + const fromCode = from.charCodeAt(fromStart + i); + const toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) break; + else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i; + } + // We found a mismatch before the first common path separator was seen, so + // return the original `to`. + if (i !== length && lastCommonSep === -1) { + return toOrig; + } + let out = ""; + if (lastCommonSep === -1) lastCommonSep = 0; + // Generate the relative path based on the path difference between `to` and + // `from` + for(i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i){ + if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { + if (out.length === 0) out += ".."; + else out += "\\.."; + } + } + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) { + return out + toOrig.slice(toStart + lastCommonSep, toEnd); + } else { + toStart += lastCommonSep; + if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) ++toStart; + return toOrig.slice(toStart, toEnd); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +const WHITESPACE_ENCODINGS = { + "\u0009": "%09", + "\u000A": "%0A", + "\u000B": "%0B", + "\u000C": "%0C", + "\u000D": "%0D", + "\u0020": "%20" +}; +function encodeWhitespace(string) { + return string.replaceAll(/[\s]/g, (c)=>{ + return WHITESPACE_ENCODINGS[c] ?? c; + }); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a path string to a file URL. + * + * @example Usage + * ```ts + * import { toFileUrl } from "@std/path/windows/to-file-url"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(toFileUrl("\\home\\foo"), new URL("file:///home/foo")); + * assertEquals(toFileUrl("C:\\Users\\foo"), new URL("file:///C:/Users/foo")); + * assertEquals(toFileUrl("\\\\127.0.0.1\\home\\foo"), new URL("file://127.0.0.1/home/foo")); + * ``` + * @param path The path to convert. + * @returns The file URL. + */ function toFileUrl(path) { + if (!isAbsolute(path)) { + throw new TypeError(`Path must be absolute: received "${path}"`); + } + const [, hostname, pathname] = path.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/); + const url = new URL("file:///"); + url.pathname = encodeWhitespace(pathname.replace(/%/g, "%25")); + if (hostname !== undefined && hostname !== "localhost") { + url.hostname = hostname; + if (!url.hostname) { + throw new TypeError(`Invalid hostname: "${url.hostname}"`); + } + } + return url; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Resolves path to a namespace path + * + * @example Usage + * ```ts + * import { toNamespacedPath } from "@std/path/windows/to-namespaced-path"; + * import { assertEquals } from "@std/assert"; + * + * const namespaced = toNamespacedPath("C:\\foo\\bar"); + * assertEquals(namespaced, "\\\\?\\C:\\foo\\bar"); + * ``` + * + * @param path The path to resolve to namespaced path + * @returns The resolved namespaced path + */ function toNamespacedPath(path) { + // Note: this will *probably* throw somewhere. + if (typeof path !== "string") return path; + if (path.length === 0) return ""; + const resolvedPath = resolve(path); + if (resolvedPath.length >= 3) { + if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { + // Possible UNC root + if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { + const code = resolvedPath.charCodeAt(2); + if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { + // Matched non-long UNC root, convert the path to a long UNC path + return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; + } + } + } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0))) { + // Possible device root + if (resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) { + // Matched device root, convert the path to a long UNC path + return `\\\\?\\${resolvedPath}`; + } + } + } + return path; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function common$1(paths, sep) { + const [first = "", ...remaining] = paths; + const parts = first.split(sep); + let endOfPrefix = parts.length; + let append = ""; + for (const path of remaining){ + const compare = path.split(sep); + if (compare.length <= endOfPrefix) { + endOfPrefix = compare.length; + append = ""; + } + for(let i = 0; i < endOfPrefix; i++){ + if (compare[i] !== parts[i]) { + endOfPrefix = i; + append = i === 0 ? "" : sep; + break; + } + } + } + return parts.slice(0, endOfPrefix).join(sep) + append; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Determines the common path from a set of paths for Windows systems. + * + * @example Usage + * ```ts + * import { common } from "@std/path/windows/common"; + * import { assertEquals } from "@std/assert"; + * + * const path = common([ + * "C:\\foo\\bar", + * "C:\\foo\\baz", + * ]); + * assertEquals(path, "C:\\foo\\"); + * ``` + * + * @param paths The paths to compare. + * @returns The common path. + */ function common(paths) { + return common$1(paths, SEPARATOR); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Options for {@linkcode globToRegExp}, {@linkcode joinGlobs}, + * {@linkcode normalizeGlob} and {@linkcode expandGlob}. + */ const REG_EXP_ESCAPE_CHARS = [ + "!", + "$", + "(", + ")", + "*", + "+", + ".", + "=", + "?", + "[", + "\\", + "^", + "{", + "|" +]; +const RANGE_ESCAPE_CHARS = [ + "-", + "\\", + "]" +]; +function _globToRegExp(c, glob, { extended = true, globstar: globstarOption = true, // os = osType, +caseInsensitive = false } = {}) { + if (glob === "") { + return /(?!)/; + } + // Remove trailing separators. + let newLength = glob.length; + for(; newLength > 1 && c.seps.includes(glob[newLength - 1]); newLength--); + glob = glob.slice(0, newLength); + let regExpString = ""; + // Terminates correctly. Trust that `j` is incremented every iteration. + for(let j = 0; j < glob.length;){ + let segment = ""; + const groupStack = []; + let inRange = false; + let inEscape = false; + let endsWithSep = false; + let i = j; + // Terminates with `i` at the non-inclusive end of the current segment. + for(; i < glob.length && !c.seps.includes(glob[i]); i++){ + if (inEscape) { + inEscape = false; + const escapeChars = inRange ? RANGE_ESCAPE_CHARS : REG_EXP_ESCAPE_CHARS; + segment += escapeChars.includes(glob[i]) ? `\\${glob[i]}` : glob[i]; + continue; + } + if (glob[i] === c.escapePrefix) { + inEscape = true; + continue; + } + if (glob[i] === "[") { + if (!inRange) { + inRange = true; + segment += "["; + if (glob[i + 1] === "!") { + i++; + segment += "^"; + } else if (glob[i + 1] === "^") { + i++; + segment += "\\^"; + } + continue; + } else if (glob[i + 1] === ":") { + let k = i + 1; + let value = ""; + while(glob[k + 1] !== undefined && glob[k + 1] !== ":"){ + value += glob[k + 1]; + k++; + } + if (glob[k + 1] === ":" && glob[k + 2] === "]") { + i = k + 2; + if (value === "alnum") segment += "\\dA-Za-z"; + else if (value === "alpha") segment += "A-Za-z"; + else if (value === "ascii") segment += "\x00-\x7F"; + else if (value === "blank") segment += "\t "; + else if (value === "cntrl") segment += "\x00-\x1F\x7F"; + else if (value === "digit") segment += "\\d"; + else if (value === "graph") segment += "\x21-\x7E"; + else if (value === "lower") segment += "a-z"; + else if (value === "print") segment += "\x20-\x7E"; + else if (value === "punct") { + segment += "!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_‘{|}~"; + } else if (value === "space") segment += "\\s\v"; + else if (value === "upper") segment += "A-Z"; + else if (value === "word") segment += "\\w"; + else if (value === "xdigit") segment += "\\dA-Fa-f"; + continue; + } + } + } + if (glob[i] === "]" && inRange) { + inRange = false; + segment += "]"; + continue; + } + if (inRange) { + segment += glob[i]; + continue; + } + if (glob[i] === ")" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") { + segment += ")"; + const type = groupStack.pop(); + if (type === "!") { + segment += c.wildcard; + } else if (type !== "@") { + segment += type; + } + continue; + } + if (glob[i] === "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") { + segment += "|"; + continue; + } + if (glob[i] === "+" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("+"); + segment += "(?:"; + continue; + } + if (glob[i] === "@" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("@"); + segment += "(?:"; + continue; + } + if (glob[i] === "?") { + if (extended && glob[i + 1] === "(") { + i++; + groupStack.push("?"); + segment += "(?:"; + } else { + segment += "."; + } + continue; + } + if (glob[i] === "!" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("!"); + segment += "(?!"; + continue; + } + if (glob[i] === "{") { + groupStack.push("BRACE"); + segment += "(?:"; + continue; + } + if (glob[i] === "}" && groupStack[groupStack.length - 1] === "BRACE") { + groupStack.pop(); + segment += ")"; + continue; + } + if (glob[i] === "," && groupStack[groupStack.length - 1] === "BRACE") { + segment += "|"; + continue; + } + if (glob[i] === "*") { + if (extended && glob[i + 1] === "(") { + i++; + groupStack.push("*"); + segment += "(?:"; + } else { + const prevChar = glob[i - 1]; + let numStars = 1; + while(glob[i + 1] === "*"){ + i++; + numStars++; + } + const nextChar = glob[i + 1]; + if (globstarOption && numStars === 2 && [ + ...c.seps, + undefined + ].includes(prevChar) && [ + ...c.seps, + undefined + ].includes(nextChar)) { + segment += c.globstar; + endsWithSep = true; + } else { + segment += c.wildcard; + } + } + continue; + } + segment += REG_EXP_ESCAPE_CHARS.includes(glob[i]) ? `\\${glob[i]}` : glob[i]; + } + // Check for unclosed groups or a dangling backslash. + if (groupStack.length > 0 || inRange || inEscape) { + // Parse failure. Take all characters from this segment literally. + segment = ""; + for (const c of glob.slice(j, i)){ + segment += REG_EXP_ESCAPE_CHARS.includes(c) ? `\\${c}` : c; + endsWithSep = false; + } + } + regExpString += segment; + if (!endsWithSep) { + regExpString += i < glob.length ? c.sep : c.sepMaybe; + endsWithSep = true; + } + // Terminates with `i` at the start of the next segment. + while(c.seps.includes(glob[i]))i++; + j = i; + } + regExpString = `^${regExpString}$`; + return new RegExp(regExpString, caseInsensitive ? "i" : ""); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +const constants = { + sep: "(?:\\\\|/)+", + sepMaybe: "(?:\\\\|/)*", + seps: [ + "\\", + "/" + ], + globstar: "(?:[^\\\\/]*(?:\\\\|/|$)+)*", + wildcard: "[^\\\\/]*", + escapePrefix: "`" +}; +/** Convert a glob string to a regular expression. + * + * Tries to match bash glob expansion as closely as possible. + * + * Basic glob syntax: + * - `*` - Matches everything without leaving the path segment. + * - `?` - Matches any single character. + * - `{foo,bar}` - Matches `foo` or `bar`. + * - `[abcd]` - Matches `a`, `b`, `c` or `d`. + * - `[a-d]` - Matches `a`, `b`, `c` or `d`. + * - `[!abcd]` - Matches any single character besides `a`, `b`, `c` or `d`. + * - `[[::]]` - Matches any character belonging to ``. + * - `[[:alnum:]]` - Matches any digit or letter. + * - `[[:digit:]abc]` - Matches any digit, `a`, `b` or `c`. + * - See https://facelessuser.github.io/wcmatch/glob/#posix-character-classes + * for a complete list of supported character classes. + * - `\` - Escapes the next character for an `os` other than `"windows"`. + * - \` - Escapes the next character for `os` set to `"windows"`. + * - `/` - Path separator. + * - `\` - Additional path separator only for `os` set to `"windows"`. + * + * Extended syntax: + * - Requires `{ extended: true }`. + * - `?(foo|bar)` - Matches 0 or 1 instance of `{foo,bar}`. + * - `@(foo|bar)` - Matches 1 instance of `{foo,bar}`. They behave the same. + * - `*(foo|bar)` - Matches _n_ instances of `{foo,bar}`. + * - `+(foo|bar)` - Matches _n > 0_ instances of `{foo,bar}`. + * - `!(foo|bar)` - Matches anything other than `{foo,bar}`. + * - See https://www.linuxjournal.com/content/bash-extended-globbing. + * + * Globstar syntax: + * - Requires `{ globstar: true }`. + * - `**` - Matches any number of any path segments. + * - Must comprise its entire path segment in the provided glob. + * - See https://www.linuxjournal.com/content/globstar-new-bash-globbing-option. + * + * Note the following properties: + * - The generated `RegExp` is anchored at both start and end. + * - Repeating and trailing separators are tolerated. Trailing separators in the + * provided glob have no meaning and are discarded. + * - Absolute globs will only match absolute paths, etc. + * - Empty globs will match nothing. + * - Any special glob syntax must be contained to one path segment. For example, + * `?(foo|bar/baz)` is invalid. The separator will take precedence and the + * first segment ends with an unclosed group. + * - If a path segment ends with unclosed groups or a dangling escape prefix, a + * parse error has occurred. Every character for that segment is taken + * literally in this event. + * + * Limitations: + * - A negative group like `!(foo|bar)` will wrongly be converted to a negative + * look-ahead followed by a wildcard. This means that `!(foo).js` will wrongly + * fail to match `foobar.js`, even though `foobar` is not `foo`. Effectively, + * `!(foo|bar)` is treated like `!(@(foo|bar)*)`. This will work correctly if + * the group occurs not nested at the end of the segment. + * + * @example Usage + * ```ts + * import { globToRegExp } from "@std/path/windows/glob-to-regexp"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(globToRegExp("*.js"), /^[^\\/]*\.js(?:\\|\/)*$/); + * ``` + * + * @param glob Glob string to convert. + * @param options Conversion options. + * @returns The regular expression equivalent to the glob. + */ function globToRegExp(glob, options = {}) { + return _globToRegExp(constants, glob, options); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Test whether the given string is a glob. + * + * @example Usage + * ```ts + * import { isGlob } from "@std/path/is-glob"; + * import { assert } from "@std/assert"; + * + * assert(!isGlob("foo/bar/../baz")); + * assert(isGlob("foo/*ar/../baz")); + * ``` + * + * @param str String to test. + * @returns `true` if the given string is a glob, otherwise `false` + */ function isGlob(str) { + const chars = { + "{": "}", + "(": ")", + "[": "]" + }; + const regex = /\\(.)|(^!|\*|\?|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; + if (str === "") { + return false; + } + let match; + while(match = regex.exec(str)){ + if (match[2]) return true; + let idx = match.index + match[0].length; + // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + const open = match[1]; + const close = open ? chars[open] : null; + if (open && close) { + const n = str.indexOf(close, idx); + if (n !== -1) { + idx = n + 1; + } + } + str = str.slice(idx); + } + return false; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Like normalize(), but doesn't collapse "**\/.." when `globstar` is true. + * + * @example Usage + * ```ts + * import { normalizeGlob } from "@std/path/windows/normalize-glob"; + * import { assertEquals } from "@std/assert"; + * + * const normalized = normalizeGlob("**\\foo\\..\\bar", { globstar: true }); + * assertEquals(normalized, "**\\bar"); + * ``` + * + * @param glob The glob pattern to normalize. + * @param options The options for glob pattern. + * @returns The normalized glob pattern. + */ function normalizeGlob(glob, options = {}) { + const { globstar = false } = options; + if (glob.match(/\0/g)) { + throw new Error(`Glob contains invalid characters: "${glob}"`); + } + if (!globstar) { + return normalize(glob); + } + const s = SEPARATOR_PATTERN.source; + const badParentPattern = new RegExp(`(?<=(${s}|^)\\*\\*${s})\\.\\.(?=${s}|$)`, "g"); + return normalize(glob.replace(badParentPattern, "\0")).replace(/\0/g, ".."); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Like join(), but doesn't collapse "**\/.." when `globstar` is true. + * + * @example Usage + * + * ```ts + * import { joinGlobs } from "@std/path/windows/join-globs"; + * import { assertEquals } from "@std/assert"; + * + * const joined = joinGlobs(["foo", "**", "bar"], { globstar: true }); + * assertEquals(joined, "foo\\**\\bar"); + * ``` + * + * @param globs The globs to join. + * @param options The options for glob pattern. + * @returns The joined glob pattern. + */ function joinGlobs(globs, options = {}) { + const { globstar = false } = options; + if (!globstar || globs.length === 0) { + return join(...globs); + } + let joined; + for (const glob of globs){ + const path = glob; + if (path.length > 0) { + if (!joined) joined = path; + else joined += `${SEPARATOR}${path}`; + } + } + if (!joined) return "."; + return normalizeGlob(joined, { + globstar + }); +} + +exports.DELIMITER = DELIMITER; +exports.SEPARATOR = SEPARATOR; +exports.SEPARATOR_PATTERN = SEPARATOR_PATTERN; +exports.basename = basename; +exports.common = common; +exports.dirname = dirname; +exports.extname = extname; +exports.format = format; +exports.fromFileUrl = fromFileUrl; +exports.globToRegExp = globToRegExp; +exports.isAbsolute = isAbsolute; +exports.isGlob = isGlob; +exports.join = join; +exports.joinGlobs = joinGlobs; +exports.normalize = normalize; +exports.normalizeGlob = normalizeGlob; +exports.parse = parse; +exports.relative = relative; +exports.resolve = resolve; +exports.toFileUrl = toFileUrl; +exports.toNamespacedPath = toNamespacedPath; diff --git a/node_modules/@eslint/config-array/dist/cjs/types.ts b/node_modules/@eslint/config-array/dist/cjs/types.ts new file mode 100644 index 00000000..1af40113 --- /dev/null +++ b/node_modules/@eslint/config-array/dist/cjs/types.ts @@ -0,0 +1,24 @@ +/** + * @fileoverview Types for the config-array package. + * @author Nicholas C. Zakas + */ + +export interface ConfigObject { + /** + * The files to include. + */ + files?: string[]; + + /** + * The files to exclude. + */ + ignores?: string[]; + + /** + * The name of the config object. + */ + name?: string; + + // may also have any number of other properties + [key: string]: unknown; +} diff --git a/node_modules/@eslint/config-array/dist/esm/index.d.ts b/node_modules/@eslint/config-array/dist/esm/index.d.ts new file mode 100644 index 00000000..29501f73 --- /dev/null +++ b/node_modules/@eslint/config-array/dist/esm/index.d.ts @@ -0,0 +1,143 @@ +export { ObjectSchema } from "@eslint/object-schema"; +export type PropertyDefinition = import("@eslint/object-schema").PropertyDefinition; +export type ObjectDefinition = import("@eslint/object-schema").ObjectDefinition; +export type ConfigObject = import("./types.ts").ConfigObject; +export type IMinimatchStatic = import("minimatch").IMinimatchStatic; +export type IMinimatch = import("minimatch").IMinimatch; +export type PathImpl = typeof import("@jsr/std__path"); +export type ObjectSchemaInstance = import("@eslint/object-schema").ObjectSchema; +/** + * Represents an array of config objects and provides method for working with + * those config objects. + */ +export class ConfigArray extends Array { + [x: symbol]: (config: any) => any; + /** + * Creates a new instance of ConfigArray. + * @param {Iterable|Function|Object} configs An iterable yielding config + * objects, or a config function, or a config object. + * @param {Object} options The options for the ConfigArray. + * @param {string} [options.basePath="/"] The absolute path of the config file directory. + * Defaults to `"/"`. + * @param {boolean} [options.normalized=false] Flag indicating if the + * configs have already been normalized. + * @param {Object} [options.schema] The additional schema + * definitions to use for the ConfigArray schema. + * @param {Array} [options.extraConfigTypes] List of config types supported. + * @throws {TypeError} When the `basePath` is not a non-empty string, + */ + constructor(configs: Iterable | Function | any, { basePath, normalized, schema: customSchema, extraConfigTypes, }?: { + basePath?: string; + normalized?: boolean; + schema?: any; + extraConfigTypes?: Array; + }); + /** + * The path of the config file that this array was loaded from. + * This is used to calculate filename matches. + * @property basePath + * @type {string} + */ + basePath: string; + /** + * The supported config types. + * @type {Array} + */ + extraConfigTypes: Array; + /** + * Returns the `files` globs from every config object in the array. + * This can be used to determine which files will be matched by a + * config array or to use as a glob pattern when no patterns are provided + * for a command line interface. + * @returns {Array} An array of matchers. + */ + get files(): Array; + /** + * Returns ignore matchers that should always be ignored regardless of + * the matching `files` fields in any configs. This is necessary to mimic + * the behavior of things like .gitignore and .eslintignore, allowing a + * globbing operation to be faster. + * @returns {string[]} An array of string patterns and functions to be ignored. + */ + get ignores(): string[]; + /** + * Indicates if the config array has been normalized. + * @returns {boolean} True if the config array is normalized, false if not. + */ + isNormalized(): boolean; + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {Object} [context] The context object for config functions. + * @returns {Promise} The current ConfigArray instance. + */ + normalize(context?: any): Promise; + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {Object} [context] The context object for config functions. + * @returns {ConfigArray} The current ConfigArray instance. + */ + normalizeSync(context?: any): ConfigArray; + /** + * Returns the config object for a given file path and a status that can be used to determine why a file has no config. + * @param {string} filePath The path of a file to get a config for. + * @returns {{ config?: Object, status: "ignored"|"external"|"unconfigured"|"matched" }} + * An object with an optional property `config` and property `status`. + * `config` is the config object for the specified file as returned by {@linkcode ConfigArray.getConfig}, + * `status` a is one of the constants returned by {@linkcode ConfigArray.getConfigStatus}. + */ + getConfigWithStatus(filePath: string): { + config?: any; + status: "ignored" | "external" | "unconfigured" | "matched"; + }; + /** + * Returns the config object for a given file path. + * @param {string} filePath The path of a file to get a config for. + * @returns {Object|undefined} The config object for this file or `undefined`. + */ + getConfig(filePath: string): any | undefined; + /** + * Determines whether a file has a config or why it doesn't. + * @param {string} filePath The path of the file to check. + * @returns {"ignored"|"external"|"unconfigured"|"matched"} One of the following values: + * * `"ignored"`: the file is ignored + * * `"external"`: the file is outside the base path + * * `"unconfigured"`: the file is not matched by any config + * * `"matched"`: the file has a matching config + */ + getConfigStatus(filePath: string): "ignored" | "external" | "unconfigured" | "matched"; + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + * @deprecated Use `isFileIgnored` instead. + */ + isIgnored(filePath: string): boolean; + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + */ + isFileIgnored(filePath: string): boolean; + /** + * Determines if the given directory is ignored based on the configs. + * This checks only default `ignores` that don't have `files` in the + * same config. A pattern such as `/foo` be considered to ignore the directory + * while a pattern such as `/foo/**` is not considered to ignore the + * directory because it is matching files. + * @param {string} directoryPath The path of a directory to check. + * @returns {boolean} True if the directory is ignored, false if not. Will + * return true for any directory that is not inside of `basePath`. + * @throws {Error} When the `ConfigArray` is not normalized. + */ + isDirectoryIgnored(directoryPath: string): boolean; + #private; +} +export namespace ConfigArraySymbol { + let isNormalized: symbol; + let configCache: symbol; + let schema: symbol; + let finalizeConfig: symbol; + let preprocessConfig: symbol; +} diff --git a/node_modules/@eslint/config-array/dist/esm/index.js b/node_modules/@eslint/config-array/dist/esm/index.js new file mode 100644 index 00000000..e2ee9baa --- /dev/null +++ b/node_modules/@eslint/config-array/dist/esm/index.js @@ -0,0 +1,1389 @@ +// @ts-self-types="./index.d.ts" +import * as posixPath from './std__path/posix.js'; +import * as windowsPath from './std__path/windows.js'; +import minimatch from 'minimatch'; +import createDebug from 'debug'; +import { ObjectSchema } from '@eslint/object-schema'; +export { ObjectSchema } from '@eslint/object-schema'; + +/** + * @fileoverview ConfigSchema + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("@eslint/object-schema").PropertyDefinition} PropertyDefinition */ +/** @typedef {import("@eslint/object-schema").ObjectDefinition} ObjectDefinition */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * A strategy that does nothing. + * @type {PropertyDefinition} + */ +const NOOP_STRATEGY = { + required: false, + merge() { + return undefined; + }, + validate() {}, +}; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The base schema that every ConfigArray uses. + * @type {ObjectDefinition} + */ +const baseSchema = Object.freeze({ + name: { + required: false, + merge() { + return undefined; + }, + validate(value) { + if (typeof value !== "string") { + throw new TypeError("Property must be a string."); + } + }, + }, + files: NOOP_STRATEGY, + ignores: NOOP_STRATEGY, +}); + +/** + * @fileoverview ConfigSchema + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Asserts that a given value is an array. + * @param {*} value The value to check. + * @returns {void} + * @throws {TypeError} When the value is not an array. + */ +function assertIsArray(value) { + if (!Array.isArray(value)) { + throw new TypeError("Expected value to be an array."); + } +} + +/** + * Asserts that a given value is an array containing only strings and functions. + * @param {*} value The value to check. + * @returns {void} + * @throws {TypeError} When the value is not an array of strings and functions. + */ +function assertIsArrayOfStringsAndFunctions(value) { + assertIsArray(value); + + if ( + value.some( + item => typeof item !== "string" && typeof item !== "function", + ) + ) { + throw new TypeError( + "Expected array to only contain strings and functions.", + ); + } +} + +/** + * Asserts that a given value is a non-empty array. + * @param {*} value The value to check. + * @returns {void} + * @throws {TypeError} When the value is not an array or an empty array. + */ +function assertIsNonEmptyArray(value) { + if (!Array.isArray(value) || value.length === 0) { + throw new TypeError("Expected value to be a non-empty array."); + } +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The schema for `files` and `ignores` that every ConfigArray uses. + * @type {ObjectDefinition} + */ +const filesAndIgnoresSchema = Object.freeze({ + files: { + required: false, + merge() { + return undefined; + }, + validate(value) { + // first check if it's an array + assertIsNonEmptyArray(value); + + // then check each member + value.forEach(item => { + if (Array.isArray(item)) { + assertIsArrayOfStringsAndFunctions(item); + } else if ( + typeof item !== "string" && + typeof item !== "function" + ) { + throw new TypeError( + "Items must be a string, a function, or an array of strings and functions.", + ); + } + }); + }, + }, + ignores: { + required: false, + merge() { + return undefined; + }, + validate: assertIsArrayOfStringsAndFunctions, + }, +}); + +/** + * @fileoverview ConfigArray + * @author Nicholas C. Zakas + */ + + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("./types.ts").ConfigObject} ConfigObject */ +/** @typedef {import("minimatch").IMinimatchStatic} IMinimatchStatic */ +/** @typedef {import("minimatch").IMinimatch} IMinimatch */ +/** @typedef {import("@jsr/std__path")} PathImpl */ + +/* + * This is a bit of a hack to make TypeScript happy with the Rollup-created + * CommonJS file. Rollup doesn't do object destructuring for imported files + * and instead imports the default via `require()`. This messes up type checking + * for `ObjectSchema`. To work around that, we just import the type manually + * and give it a different name to use in the JSDoc comments. + */ +/** @typedef {import("@eslint/object-schema").ObjectSchema} ObjectSchemaInstance */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const Minimatch = minimatch.Minimatch; +const debug = createDebug("@eslint/config-array"); + +/** + * A cache for minimatch instances. + * @type {Map} + */ +const minimatchCache = new Map(); + +/** + * A cache for negated minimatch instances. + * @type {Map} + */ +const negatedMinimatchCache = new Map(); + +/** + * Options to use with minimatch. + * @type {Object} + */ +const MINIMATCH_OPTIONS = { + // matchBase: true, + dot: true, + allowWindowsEscape: true, +}; + +/** + * The types of config objects that are supported. + * @type {Set} + */ +const CONFIG_TYPES = new Set(["array", "function"]); + +/** + * Fields that are considered metadata and not part of the config object. + * @type {Set} + */ +const META_FIELDS = new Set(["name"]); + +/** + * A schema containing just files and ignores for early validation. + * @type {ObjectSchemaInstance} + */ +const FILES_AND_IGNORES_SCHEMA = new ObjectSchema(filesAndIgnoresSchema); + +// Precomputed constant objects returned by `ConfigArray.getConfigWithStatus`. + +const CONFIG_WITH_STATUS_EXTERNAL = Object.freeze({ status: "external" }); +const CONFIG_WITH_STATUS_IGNORED = Object.freeze({ status: "ignored" }); +const CONFIG_WITH_STATUS_UNCONFIGURED = Object.freeze({ + status: "unconfigured", +}); + +// Match two leading dots followed by a slash or the end of input. +const EXTERNAL_PATH_REGEX = /^\.\.(?:\/|$)/u; + +/** + * Wrapper error for config validation errors that adds a name to the front of the + * error message. + */ +class ConfigError extends Error { + /** + * Creates a new instance. + * @param {string} name The config object name causing the error. + * @param {number} index The index of the config object in the array. + * @param {Object} options The options for the error. + * @param {Error} [options.cause] The error that caused this error. + * @param {string} [options.message] The message to use for the error. + */ + constructor(name, index, { cause, message }) { + const finalMessage = message || cause.message; + + super(`Config ${name}: ${finalMessage}`, { cause }); + + // copy over custom properties that aren't represented + if (cause) { + for (const key of Object.keys(cause)) { + if (!(key in this)) { + this[key] = cause[key]; + } + } + } + + /** + * The name of the error. + * @type {string} + * @readonly + */ + this.name = "ConfigError"; + + /** + * The index of the config object in the array. + * @type {number} + * @readonly + */ + this.index = index; + } +} + +/** + * Gets the name of a config object. + * @param {ConfigObject} config The config object to get the name of. + * @returns {string} The name of the config object. + */ +function getConfigName(config) { + if (config && typeof config.name === "string" && config.name) { + return `"${config.name}"`; + } + + return "(unnamed)"; +} + +/** + * Rethrows a config error with additional information about the config object. + * @param {object} config The config object to get the name of. + * @param {number} index The index of the config object in the array. + * @param {Error} error The error to rethrow. + * @throws {ConfigError} When the error is rethrown for a config. + */ +function rethrowConfigError(config, index, error) { + const configName = getConfigName(config); + throw new ConfigError(configName, index, { cause: error }); +} + +/** + * Shorthand for checking if a value is a string. + * @param {any} value The value to check. + * @returns {boolean} True if a string, false if not. + */ +function isString(value) { + return typeof value === "string"; +} + +/** + * Creates a function that asserts that the config is valid + * during normalization. This checks that the config is not nullish + * and that files and ignores keys of a config object are valid as per base schema. + * @param {Object} config The config object to check. + * @param {number} index The index of the config object in the array. + * @returns {void} + * @throws {ConfigError} If the files and ignores keys of a config object are not valid. + */ +function assertValidBaseConfig(config, index) { + if (config === null) { + throw new ConfigError(getConfigName(config), index, { + message: "Unexpected null config.", + }); + } + + if (config === undefined) { + throw new ConfigError(getConfigName(config), index, { + message: "Unexpected undefined config.", + }); + } + + if (typeof config !== "object") { + throw new ConfigError(getConfigName(config), index, { + message: "Unexpected non-object config.", + }); + } + + const validateConfig = {}; + + if ("files" in config) { + validateConfig.files = config.files; + } + + if ("ignores" in config) { + validateConfig.ignores = config.ignores; + } + + try { + FILES_AND_IGNORES_SCHEMA.validate(validateConfig); + } catch (validationError) { + rethrowConfigError(config, index, validationError); + } +} + +/** + * Wrapper around minimatch that caches minimatch patterns for + * faster matching speed over multiple file path evaluations. + * @param {string} filepath The file path to match. + * @param {string} pattern The glob pattern to match against. + * @param {object} options The minimatch options to use. + * @returns + */ +function doMatch(filepath, pattern, options = {}) { + let cache = minimatchCache; + + if (options.flipNegate) { + cache = negatedMinimatchCache; + } + + let matcher = cache.get(pattern); + + if (!matcher) { + matcher = new Minimatch( + pattern, + Object.assign({}, MINIMATCH_OPTIONS, options), + ); + cache.set(pattern, matcher); + } + + return matcher.match(filepath); +} + +/** + * Normalizes a pattern by removing the leading "./" if present. + * @param {string} pattern The pattern to normalize. + * @returns {string} The normalized pattern. + */ +function normalizePattern(pattern) { + if (isString(pattern)) { + if (pattern.startsWith("./")) { + return pattern.slice(2); + } + + if (pattern.startsWith("!./")) { + return `!${pattern.slice(3)}`; + } + } + + return pattern; +} + +/** + * Checks if a given pattern requires normalization. + * @param {any} pattern The pattern to check. + * @returns {boolean} True if the pattern needs normalization, false otherwise. + * + */ +function needsPatternNormalization(pattern) { + return ( + isString(pattern) && + (pattern.startsWith("./") || pattern.startsWith("!./")) + ); +} + +/** + * Normalizes `files` and `ignores` patterns in a config by removing "./" prefixes. + * @param {Object} config The config object to normalize patterns in. + * @returns {Object} The normalized config object. + */ +function normalizeConfigPatterns(config) { + if (!config) { + return config; + } + + let needsNormalization = false; + + if (Array.isArray(config.files)) { + needsNormalization = config.files.some(pattern => { + if (Array.isArray(pattern)) { + return pattern.some(needsPatternNormalization); + } + return needsPatternNormalization(pattern); + }); + } + + if (!needsNormalization && Array.isArray(config.ignores)) { + needsNormalization = config.ignores.some(needsPatternNormalization); + } + + if (!needsNormalization) { + return config; + } + + const newConfig = { ...config }; + + if (Array.isArray(newConfig.files)) { + newConfig.files = newConfig.files.map(pattern => { + if (Array.isArray(pattern)) { + return pattern.map(normalizePattern); + } + return normalizePattern(pattern); + }); + } + + if (Array.isArray(newConfig.ignores)) { + newConfig.ignores = newConfig.ignores.map(normalizePattern); + } + + return newConfig; +} + +/** + * Normalizes a `ConfigArray` by flattening it and executing any functions + * that are found inside. + * @param {Array} items The items in a `ConfigArray`. + * @param {Object} context The context object to pass into any function + * found. + * @param {Array} extraConfigTypes The config types to check. + * @returns {Promise} A flattened array containing only config objects. + * @throws {TypeError} When a config function returns a function. + */ +async function normalize(items, context, extraConfigTypes) { + const allowFunctions = extraConfigTypes.includes("function"); + const allowArrays = extraConfigTypes.includes("array"); + + async function* flatTraverse(array) { + for (let item of array) { + if (typeof item === "function") { + if (!allowFunctions) { + throw new TypeError("Unexpected function."); + } + + item = item(context); + if (item.then) { + item = await item; + } + } + + if (Array.isArray(item)) { + if (!allowArrays) { + throw new TypeError("Unexpected array."); + } + yield* flatTraverse(item); + } else if (typeof item === "function") { + throw new TypeError( + "A config function can only return an object or array.", + ); + } else { + yield item; + } + } + } + + /* + * Async iterables cannot be used with the spread operator, so we need to manually + * create the array to return. + */ + const asyncIterable = await flatTraverse(items); + const configs = []; + + for await (const config of asyncIterable) { + configs.push(normalizeConfigPatterns(config)); + } + + return configs; +} + +/** + * Normalizes a `ConfigArray` by flattening it and executing any functions + * that are found inside. + * @param {Array} items The items in a `ConfigArray`. + * @param {Object} context The context object to pass into any function + * found. + * @param {Array} extraConfigTypes The config types to check. + * @returns {Array} A flattened array containing only config objects. + * @throws {TypeError} When a config function returns a function. + */ +function normalizeSync(items, context, extraConfigTypes) { + const allowFunctions = extraConfigTypes.includes("function"); + const allowArrays = extraConfigTypes.includes("array"); + + function* flatTraverse(array) { + for (let item of array) { + if (typeof item === "function") { + if (!allowFunctions) { + throw new TypeError("Unexpected function."); + } + + item = item(context); + if (item.then) { + throw new TypeError( + "Async config functions are not supported.", + ); + } + } + + if (Array.isArray(item)) { + if (!allowArrays) { + throw new TypeError("Unexpected array."); + } + + yield* flatTraverse(item); + } else if (typeof item === "function") { + throw new TypeError( + "A config function can only return an object or array.", + ); + } else { + yield item; + } + } + } + + const configs = []; + + for (const config of flatTraverse(items)) { + configs.push(normalizeConfigPatterns(config)); + } + + return configs; +} + +/** + * Determines if a given file path should be ignored based on the given + * matcher. + * @param {Array boolean)>} ignores The ignore patterns to check. + * @param {string} filePath The unprocessed file path to check. + * @param {string} relativeFilePath The path of the file to check relative to the base path, + * using forward slash (`"/"`) as a separator. + * @returns {boolean} True if the path should be ignored and false if not. + */ +function shouldIgnorePath(ignores, filePath, relativeFilePath) { + return ignores.reduce((ignored, matcher) => { + if (!ignored) { + if (typeof matcher === "function") { + return matcher(filePath); + } + + // don't check negated patterns because we're not ignored yet + if (!matcher.startsWith("!")) { + return doMatch(relativeFilePath, matcher); + } + + // otherwise we're still not ignored + return false; + } + + // only need to check negated patterns because we're ignored + if (typeof matcher === "string" && matcher.startsWith("!")) { + return !doMatch(relativeFilePath, matcher, { + flipNegate: true, + }); + } + + return ignored; + }, false); +} + +/** + * Determines if a given file path is matched by a config based on + * `ignores` only. + * @param {string} filePath The unprocessed file path to check. + * @param {string} relativeFilePath The path of the file to check relative to the base path, + * using forward slash (`"/"`) as a separator. + * @param {Object} config The config object to check. + * @returns {boolean} True if the file path is matched by the config, + * false if not. + */ +function pathMatchesIgnores(filePath, relativeFilePath, config) { + return ( + Object.keys(config).filter(key => !META_FIELDS.has(key)).length > 1 && + !shouldIgnorePath(config.ignores, filePath, relativeFilePath) + ); +} + +/** + * Determines if a given file path is matched by a config. If the config + * has no `files` field, then it matches; otherwise, if a `files` field + * is present then we match the globs in `files` and exclude any globs in + * `ignores`. + * @param {string} filePath The unprocessed file path to check. + * @param {string} relativeFilePath The path of the file to check relative to the base path, + * using forward slash (`"/"`) as a separator. + * @param {Object} config The config object to check. + * @returns {boolean} True if the file path is matched by the config, + * false if not. + */ +function pathMatches(filePath, relativeFilePath, config) { + // match both strings and functions + function match(pattern) { + if (isString(pattern)) { + return doMatch(relativeFilePath, pattern); + } + + if (typeof pattern === "function") { + return pattern(filePath); + } + + throw new TypeError(`Unexpected matcher type ${pattern}.`); + } + + // check for all matches to config.files + let filePathMatchesPattern = config.files.some(pattern => { + if (Array.isArray(pattern)) { + return pattern.every(match); + } + + return match(pattern); + }); + + /* + * If the file path matches the config.files patterns, then check to see + * if there are any files to ignore. + */ + if (filePathMatchesPattern && config.ignores) { + filePathMatchesPattern = !shouldIgnorePath( + config.ignores, + filePath, + relativeFilePath, + ); + } + + return filePathMatchesPattern; +} + +/** + * Ensures that a ConfigArray has been normalized. + * @param {ConfigArray} configArray The ConfigArray to check. + * @returns {void} + * @throws {Error} When the `ConfigArray` is not normalized. + */ +function assertNormalized(configArray) { + // TODO: Throw more verbose error + if (!configArray.isNormalized()) { + throw new Error( + "ConfigArray must be normalized to perform this operation.", + ); + } +} + +/** + * Ensures that config types are valid. + * @param {Array} extraConfigTypes The config types to check. + * @returns {void} + * @throws {TypeError} When the config types array is invalid. + */ +function assertExtraConfigTypes(extraConfigTypes) { + if (extraConfigTypes.length > 2) { + throw new TypeError( + "configTypes must be an array with at most two items.", + ); + } + + for (const configType of extraConfigTypes) { + if (!CONFIG_TYPES.has(configType)) { + throw new TypeError( + `Unexpected config type "${configType}" found. Expected one of: "object", "array", "function".`, + ); + } + } +} + +/** + * Returns path-handling implementations for Unix or Windows, depending on a given absolute path. + * @param {string} fileOrDirPath The absolute path to check. + * @returns {PathImpl} Path-handling implementations for the specified path. + * @throws {Error} An error is thrown if the specified argument is not an absolute path. + */ +function getPathImpl(fileOrDirPath) { + // Posix absolute paths always start with a slash. + if (fileOrDirPath.startsWith("/")) { + return posixPath; + } + + // Windows absolute paths start with a letter followed by a colon and at least one backslash, + // or with two backslashes in the case of UNC paths. + // Forward slashed are automatically normalized to backslashes. + if (/^(?:[A-Za-z]:[/\\]|[/\\]{2})/u.test(fileOrDirPath)) { + return windowsPath; + } + + throw new Error( + `Expected an absolute path but received "${fileOrDirPath}"`, + ); +} + +/** + * Converts a given path to a relative path with all separator characters replaced by forward slashes (`"/"`). + * @param {string} fileOrDirPath The unprocessed path to convert. + * @param {string} namespacedBasePath The namespaced base path of the directory to which the calculated path shall be relative. + * @param {PathImpl} path Path-handling implementations. + * @returns {string} A relative path with all separator characters replaced by forward slashes. + */ +function toRelativePath(fileOrDirPath, namespacedBasePath, path) { + const fullPath = path.resolve(namespacedBasePath, fileOrDirPath); + const namespacedFullPath = path.toNamespacedPath(fullPath); + const relativePath = path.relative(namespacedBasePath, namespacedFullPath); + return relativePath.replaceAll(path.SEPARATOR, "/"); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +const ConfigArraySymbol = { + isNormalized: Symbol("isNormalized"), + configCache: Symbol("configCache"), + schema: Symbol("schema"), + finalizeConfig: Symbol("finalizeConfig"), + preprocessConfig: Symbol("preprocessConfig"), +}; + +// used to store calculate data for faster lookup +const dataCache = new WeakMap(); + +/** + * Represents an array of config objects and provides method for working with + * those config objects. + */ +class ConfigArray extends Array { + /** + * The namespaced path of the config file directory. + * @type {string} + */ + #namespacedBasePath; + + /** + * Path-handling implementations. + * @type {PathImpl} + */ + #path; + + /** + * Creates a new instance of ConfigArray. + * @param {Iterable|Function|Object} configs An iterable yielding config + * objects, or a config function, or a config object. + * @param {Object} options The options for the ConfigArray. + * @param {string} [options.basePath="/"] The absolute path of the config file directory. + * Defaults to `"/"`. + * @param {boolean} [options.normalized=false] Flag indicating if the + * configs have already been normalized. + * @param {Object} [options.schema] The additional schema + * definitions to use for the ConfigArray schema. + * @param {Array} [options.extraConfigTypes] List of config types supported. + * @throws {TypeError} When the `basePath` is not a non-empty string, + */ + constructor( + configs, + { + basePath = "/", + normalized = false, + schema: customSchema, + extraConfigTypes = [], + } = {}, + ) { + super(); + + /** + * Tracks if the array has been normalized. + * @property isNormalized + * @type {boolean} + * @private + */ + this[ConfigArraySymbol.isNormalized] = normalized; + + /** + * The schema used for validating and merging configs. + * @property schema + * @type {ObjectSchemaInstance} + * @private + */ + this[ConfigArraySymbol.schema] = new ObjectSchema( + Object.assign({}, customSchema, baseSchema), + ); + + if (!isString(basePath) || !basePath) { + throw new TypeError("basePath must be a non-empty string"); + } + + /** + * The path of the config file that this array was loaded from. + * This is used to calculate filename matches. + * @property basePath + * @type {string} + */ + this.basePath = basePath; + + assertExtraConfigTypes(extraConfigTypes); + + /** + * The supported config types. + * @type {Array} + */ + this.extraConfigTypes = [...extraConfigTypes]; + Object.freeze(this.extraConfigTypes); + + /** + * A cache to store calculated configs for faster repeat lookup. + * @property configCache + * @type {Map} + * @private + */ + this[ConfigArraySymbol.configCache] = new Map(); + + // init cache + dataCache.set(this, { + explicitMatches: new Map(), + directoryMatches: new Map(), + files: undefined, + ignores: undefined, + }); + + // load the configs into this array + if (Array.isArray(configs)) { + this.push(...configs); + } else { + this.push(configs); + } + + // select path-handling implementations depending on the base path + this.#path = getPathImpl(basePath); + + // On Windows, `path.relative()` returns an absolute path when given two paths on different drives. + // The namespaced base path is useful to make sure that calculated relative paths are always relative. + // On Unix, it is identical to the base path. + this.#namespacedBasePath = this.#path.toNamespacedPath(basePath); + } + + /** + * Prevent normal array methods from creating a new `ConfigArray` instance. + * This is to ensure that methods such as `slice()` won't try to create a + * new instance of `ConfigArray` behind the scenes as doing so may throw + * an error due to the different constructor signature. + * @type {ArrayConstructor} The `Array` constructor. + */ + static get [Symbol.species]() { + return Array; + } + + /** + * Returns the `files` globs from every config object in the array. + * This can be used to determine which files will be matched by a + * config array or to use as a glob pattern when no patterns are provided + * for a command line interface. + * @returns {Array} An array of matchers. + */ + get files() { + assertNormalized(this); + + // if this data has been cached, retrieve it + const cache = dataCache.get(this); + + if (cache.files) { + return cache.files; + } + + // otherwise calculate it + + const result = []; + + for (const config of this) { + if (config.files) { + config.files.forEach(filePattern => { + result.push(filePattern); + }); + } + } + + // store result + cache.files = result; + dataCache.set(this, cache); + + return result; + } + + /** + * Returns ignore matchers that should always be ignored regardless of + * the matching `files` fields in any configs. This is necessary to mimic + * the behavior of things like .gitignore and .eslintignore, allowing a + * globbing operation to be faster. + * @returns {string[]} An array of string patterns and functions to be ignored. + */ + get ignores() { + assertNormalized(this); + + // if this data has been cached, retrieve it + const cache = dataCache.get(this); + + if (cache.ignores) { + return cache.ignores; + } + + // otherwise calculate it + + const result = []; + + for (const config of this) { + /* + * We only count ignores if there are no other keys in the object. + * In this case, it acts list a globally ignored pattern. If there + * are additional keys, then ignores act like exclusions. + */ + if ( + config.ignores && + Object.keys(config).filter(key => !META_FIELDS.has(key)) + .length === 1 + ) { + result.push(...config.ignores); + } + } + + // store result + cache.ignores = result; + dataCache.set(this, cache); + + return result; + } + + /** + * Indicates if the config array has been normalized. + * @returns {boolean} True if the config array is normalized, false if not. + */ + isNormalized() { + return this[ConfigArraySymbol.isNormalized]; + } + + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {Object} [context] The context object for config functions. + * @returns {Promise} The current ConfigArray instance. + */ + async normalize(context = {}) { + if (!this.isNormalized()) { + const normalizedConfigs = await normalize( + this, + context, + this.extraConfigTypes, + ); + this.length = 0; + this.push( + ...normalizedConfigs.map( + this[ConfigArraySymbol.preprocessConfig].bind(this), + ), + ); + this.forEach(assertValidBaseConfig); + this[ConfigArraySymbol.isNormalized] = true; + + // prevent further changes + Object.freeze(this); + } + + return this; + } + + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {Object} [context] The context object for config functions. + * @returns {ConfigArray} The current ConfigArray instance. + */ + normalizeSync(context = {}) { + if (!this.isNormalized()) { + const normalizedConfigs = normalizeSync( + this, + context, + this.extraConfigTypes, + ); + this.length = 0; + this.push( + ...normalizedConfigs.map( + this[ConfigArraySymbol.preprocessConfig].bind(this), + ), + ); + this.forEach(assertValidBaseConfig); + this[ConfigArraySymbol.isNormalized] = true; + + // prevent further changes + Object.freeze(this); + } + + return this; + } + + /* eslint-disable class-methods-use-this -- Desired as instance methods */ + + /** + * Finalizes the state of a config before being cached and returned by + * `getConfig()`. Does nothing by default but is provided to be + * overridden by subclasses as necessary. + * @param {Object} config The config to finalize. + * @returns {Object} The finalized config. + */ + [ConfigArraySymbol.finalizeConfig](config) { + return config; + } + + /** + * Preprocesses a config during the normalization process. This is the + * method to override if you want to convert an array item before it is + * validated for the first time. For example, if you want to replace a + * string with an object, this is the method to override. + * @param {Object} config The config to preprocess. + * @returns {Object} The config to use in place of the argument. + */ + [ConfigArraySymbol.preprocessConfig](config) { + return config; + } + + /* eslint-enable class-methods-use-this -- Desired as instance methods */ + + /** + * Returns the config object for a given file path and a status that can be used to determine why a file has no config. + * @param {string} filePath The path of a file to get a config for. + * @returns {{ config?: Object, status: "ignored"|"external"|"unconfigured"|"matched" }} + * An object with an optional property `config` and property `status`. + * `config` is the config object for the specified file as returned by {@linkcode ConfigArray.getConfig}, + * `status` a is one of the constants returned by {@linkcode ConfigArray.getConfigStatus}. + */ + getConfigWithStatus(filePath) { + assertNormalized(this); + + const cache = this[ConfigArraySymbol.configCache]; + + // first check the cache for a filename match to avoid duplicate work + if (cache.has(filePath)) { + return cache.get(filePath); + } + + // check to see if the file is outside the base path + + const relativeFilePath = toRelativePath( + filePath, + this.#namespacedBasePath, + this.#path, + ); + + if (EXTERNAL_PATH_REGEX.test(relativeFilePath)) { + debug(`No config for file ${filePath} outside of base path`); + + // cache and return result + cache.set(filePath, CONFIG_WITH_STATUS_EXTERNAL); + return CONFIG_WITH_STATUS_EXTERNAL; + } + + // next check to see if the file should be ignored + + // check if this should be ignored due to its directory + if (this.isDirectoryIgnored(this.#path.dirname(filePath))) { + debug(`Ignoring ${filePath} based on directory pattern`); + + // cache and return result + cache.set(filePath, CONFIG_WITH_STATUS_IGNORED); + return CONFIG_WITH_STATUS_IGNORED; + } + + if (shouldIgnorePath(this.ignores, filePath, relativeFilePath)) { + debug(`Ignoring ${filePath} based on file pattern`); + + // cache and return result + cache.set(filePath, CONFIG_WITH_STATUS_IGNORED); + return CONFIG_WITH_STATUS_IGNORED; + } + + // filePath isn't automatically ignored, so try to construct config + + const matchingConfigIndices = []; + let matchFound = false; + const universalPattern = /^\*$|^!|\/\*{1,2}$/u; + + this.forEach((config, index) => { + if (!config.files) { + if (!config.ignores) { + debug(`Universal config found for ${filePath}`); + matchingConfigIndices.push(index); + return; + } + + if (pathMatchesIgnores(filePath, relativeFilePath, config)) { + debug( + `Matching config found for ${filePath} (based on ignores: ${config.ignores})`, + ); + matchingConfigIndices.push(index); + return; + } + + debug( + `Skipped config found for ${filePath} (based on ignores: ${config.ignores})`, + ); + return; + } + + /* + * If a config has a files pattern * or patterns ending in /** or /*, + * and the filePath only matches those patterns, then the config is only + * applied if there is another config where the filePath matches + * a file with a specific extensions such as *.js. + */ + + const nonUniversalFiles = []; + const universalFiles = config.files.filter(element => { + if (Array.isArray(element)) { + /* + * filePath matches an element that is an array only if it matches + * all patterns in it (AND operation). Therefore, if there is at least + * one non-universal pattern in the array, and filePath matches the array, + * then we know for sure that filePath matches at least one non-universal + * pattern, so we can consider the entire array to be non-universal. + * In other words, all patterns in the array need to be universal + * for it to be considered universal. + */ + if ( + element.every(pattern => universalPattern.test(pattern)) + ) { + return true; + } + + nonUniversalFiles.push(element); + return false; + } + + // element is a string + + if (universalPattern.test(element)) { + return true; + } + + nonUniversalFiles.push(element); + return false; + }); + + // universal patterns were found so we need to check the config twice + if (universalFiles.length) { + debug("Universal files patterns found. Checking carefully."); + + // check that the config matches without the non-universal files first + if ( + nonUniversalFiles.length && + pathMatches(filePath, relativeFilePath, { + files: nonUniversalFiles, + ignores: config.ignores, + }) + ) { + debug(`Matching config found for ${filePath}`); + matchingConfigIndices.push(index); + matchFound = true; + return; + } + + // if there wasn't a match then check if it matches with universal files + if ( + universalFiles.length && + pathMatches(filePath, relativeFilePath, { + files: universalFiles, + ignores: config.ignores, + }) + ) { + debug(`Matching config found for ${filePath}`); + matchingConfigIndices.push(index); + return; + } + + // if we make here, then there was no match + return; + } + + // the normal case + if (pathMatches(filePath, relativeFilePath, config)) { + debug(`Matching config found for ${filePath}`); + matchingConfigIndices.push(index); + matchFound = true; + } + }); + + // if matching both files and ignores, there will be no config to create + if (!matchFound) { + debug(`No matching configs found for ${filePath}`); + + // cache and return result + cache.set(filePath, CONFIG_WITH_STATUS_UNCONFIGURED); + return CONFIG_WITH_STATUS_UNCONFIGURED; + } + + // check to see if there is a config cached by indices + const indicesKey = matchingConfigIndices.toString(); + let configWithStatus = cache.get(indicesKey); + + if (configWithStatus) { + // also store for filename for faster lookup next time + cache.set(filePath, configWithStatus); + + return configWithStatus; + } + + // otherwise construct the config + + // eslint-disable-next-line array-callback-return, consistent-return -- rethrowConfigError always throws an error + let finalConfig = matchingConfigIndices.reduce((result, index) => { + try { + return this[ConfigArraySymbol.schema].merge( + result, + this[index], + ); + } catch (validationError) { + rethrowConfigError(this[index], index, validationError); + } + }, {}); + + finalConfig = this[ConfigArraySymbol.finalizeConfig](finalConfig); + + configWithStatus = Object.freeze({ + config: finalConfig, + status: "matched", + }); + cache.set(filePath, configWithStatus); + cache.set(indicesKey, configWithStatus); + + return configWithStatus; + } + + /** + * Returns the config object for a given file path. + * @param {string} filePath The path of a file to get a config for. + * @returns {Object|undefined} The config object for this file or `undefined`. + */ + getConfig(filePath) { + return this.getConfigWithStatus(filePath).config; + } + + /** + * Determines whether a file has a config or why it doesn't. + * @param {string} filePath The path of the file to check. + * @returns {"ignored"|"external"|"unconfigured"|"matched"} One of the following values: + * * `"ignored"`: the file is ignored + * * `"external"`: the file is outside the base path + * * `"unconfigured"`: the file is not matched by any config + * * `"matched"`: the file has a matching config + */ + getConfigStatus(filePath) { + return this.getConfigWithStatus(filePath).status; + } + + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + * @deprecated Use `isFileIgnored` instead. + */ + isIgnored(filePath) { + return this.isFileIgnored(filePath); + } + + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + */ + isFileIgnored(filePath) { + return this.getConfigStatus(filePath) === "ignored"; + } + + /** + * Determines if the given directory is ignored based on the configs. + * This checks only default `ignores` that don't have `files` in the + * same config. A pattern such as `/foo` be considered to ignore the directory + * while a pattern such as `/foo/**` is not considered to ignore the + * directory because it is matching files. + * @param {string} directoryPath The path of a directory to check. + * @returns {boolean} True if the directory is ignored, false if not. Will + * return true for any directory that is not inside of `basePath`. + * @throws {Error} When the `ConfigArray` is not normalized. + */ + isDirectoryIgnored(directoryPath) { + assertNormalized(this); + + const relativeDirectoryPath = toRelativePath( + directoryPath, + this.#namespacedBasePath, + this.#path, + ); + + // basePath directory can never be ignored + if (relativeDirectoryPath === "") { + return false; + } + + if (EXTERNAL_PATH_REGEX.test(relativeDirectoryPath)) { + return true; + } + + // first check the cache + const cache = dataCache.get(this).directoryMatches; + + if (cache.has(relativeDirectoryPath)) { + return cache.get(relativeDirectoryPath); + } + + const directoryParts = relativeDirectoryPath.split("/"); + let relativeDirectoryToCheck = ""; + let result; + + /* + * In order to get the correct gitignore-style ignores, where an + * ignored parent directory cannot have any descendants unignored, + * we need to check every directory starting at the parent all + * the way down to the actual requested directory. + * + * We aggressively cache all of this info to make sure we don't + * have to recalculate everything for every call. + */ + do { + relativeDirectoryToCheck += `${directoryParts.shift()}/`; + + result = shouldIgnorePath( + this.ignores, + this.#path.join(this.basePath, relativeDirectoryToCheck), + relativeDirectoryToCheck, + ); + + cache.set(relativeDirectoryToCheck, result); + } while (!result && directoryParts.length); + + // also cache the result for the requested path + cache.set(relativeDirectoryPath, result); + + return result; + } +} + +export { ConfigArray, ConfigArraySymbol }; diff --git a/node_modules/@eslint/config-array/dist/esm/std__path/posix.js b/node_modules/@eslint/config-array/dist/esm/std__path/posix.js new file mode 100644 index 00000000..68e56d35 --- /dev/null +++ b/node_modules/@eslint/config-array/dist/esm/std__path/posix.js @@ -0,0 +1,1313 @@ +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +function assertPath(path) { + if (typeof path !== "string") { + throw new TypeError(`Path must be a string, received "${JSON.stringify(path)}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function stripSuffix(name, suffix) { + if (suffix.length >= name.length) { + return name; + } + const lenDiff = name.length - suffix.length; + for(let i = suffix.length - 1; i >= 0; --i){ + if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) { + return name; + } + } + return name.slice(0, -suffix.length); +} +function lastPathSegment(path, isSep, start = 0) { + let matchedNonSeparator = false; + let end = path.length; + for(let i = path.length - 1; i >= start; --i){ + if (isSep(path.charCodeAt(i))) { + if (matchedNonSeparator) { + start = i + 1; + break; + } + } else if (!matchedNonSeparator) { + matchedNonSeparator = true; + end = i + 1; + } + } + return path.slice(start, end); +} +function assertArgs$1(path, suffix) { + assertPath(path); + if (path.length === 0) return path; + if (typeof suffix !== "string") { + throw new TypeError(`Suffix must be a string, received "${JSON.stringify(suffix)}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg$3(url) { + url = url instanceof URL ? url : new URL(url); + if (url.protocol !== "file:") { + throw new TypeError(`URL must be a file URL: received "${url.protocol}"`); + } + return url; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a file URL to a path string. + * + * @example Usage + * ```ts + * import { fromFileUrl } from "@std/path/posix/from-file-url"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(fromFileUrl(new URL("file:///home/foo")), "/home/foo"); + * ``` + * + * @param url The file URL to convert. + * @returns The path string. + */ function fromFileUrl(url) { + url = assertArg$3(url); + return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25")); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +function stripTrailingSeparators(segment, isSep) { + if (segment.length <= 1) { + return segment; + } + let end = segment.length; + for(let i = segment.length - 1; i > 0; i--){ + if (isSep(segment.charCodeAt(i))) { + end = i; + } else { + break; + } + } + return segment.slice(0, end); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +// Alphabet chars. +// Non-alphabetic chars. +const CHAR_DOT = 46; /* . */ +const CHAR_FORWARD_SLASH = 47; /* / */ + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the last portion of a `path`. + * Trailing directory separators are ignored, and optional suffix is removed. + * + * @example Usage + * ```ts + * import { basename } from "@std/path/posix/basename"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(basename("/home/user/Documents/"), "Documents"); + * assertEquals(basename("/home/user/Documents/image.png"), "image.png"); + * assertEquals(basename("/home/user/Documents/image.png", ".png"), "image"); + * assertEquals(basename(new URL("file:///home/user/Documents/image.png")), "image.png"); + * assertEquals(basename(new URL("file:///home/user/Documents/image.png"), ".png"), "image"); + * ``` + * + * @example Working with URLs + * + * Note: This function doesn't automatically strip hash and query parts from + * URLs. If your URL contains a hash or query, remove them before passing the + * URL to the function. This can be done by passing the URL to `new URL(url)`, + * and setting the `hash` and `search` properties to empty strings. + * + * ```ts + * import { basename } from "@std/path/posix/basename"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(basename("https://deno.land/std/path/mod.ts"), "mod.ts"); + * assertEquals(basename("https://deno.land/std/path/mod.ts", ".ts"), "mod"); + * assertEquals(basename("https://deno.land/std/path/mod.ts?a=b"), "mod.ts?a=b"); + * assertEquals(basename("https://deno.land/std/path/mod.ts#header"), "mod.ts#header"); + * ``` + * + * @param path The path to extract the name from. + * @param suffix The suffix to remove from extracted name. + * @returns The extracted name. + */ function basename(path, suffix = "") { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArgs$1(path, suffix); + const lastSegment = lastPathSegment(path, isPosixPathSeparator); + const strippedSegment = stripTrailingSeparators(lastSegment, isPosixPathSeparator); + return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * The character used to separate entries in the PATH environment variable. + */ const DELIMITER = ":"; +/** + * The character used to separate components of a file path. + */ const SEPARATOR = "/"; +/** + * A regular expression that matches one or more path separators. + */ const SEPARATOR_PATTERN = /\/+/; + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg$2(path) { + assertPath(path); + if (path.length === 0) return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the directory path of a `path`. + * + * @example Usage + * ```ts + * import { dirname } from "@std/path/posix/dirname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(dirname("/home/user/Documents/"), "/home/user"); + * assertEquals(dirname("/home/user/Documents/image.png"), "/home/user/Documents"); + * assertEquals(dirname("https://deno.land/std/path/mod.ts"), "https://deno.land/std/path"); + * assertEquals(dirname(new URL("file:///home/user/Documents/image.png")), "/home/user/Documents"); + * ``` + * + * @example Working with URLs + * + * ```ts + * import { dirname } from "@std/path/posix/dirname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(dirname("https://deno.land/std/path/mod.ts"), "https://deno.land/std/path"); + * assertEquals(dirname("https://deno.land/std/path/mod.ts?a=b"), "https://deno.land/std/path"); + * assertEquals(dirname("https://deno.land/std/path/mod.ts#header"), "https://deno.land/std/path"); + * ``` + * + * @param path The path to get the directory from. + * @returns The directory path. + */ function dirname(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArg$2(path); + let end = -1; + let matchedNonSeparator = false; + for(let i = path.length - 1; i >= 1; --i){ + if (isPosixPathSeparator(path.charCodeAt(i))) { + if (matchedNonSeparator) { + end = i; + break; + } + } else { + matchedNonSeparator = true; + } + } + // No matches. Fallback based on provided path: + // + // - leading slashes paths + // "/foo" => "/" + // "///foo" => "/" + // - no slash path + // "foo" => "." + if (end === -1) { + return isPosixPathSeparator(path.charCodeAt(0)) ? "/" : "."; + } + return stripTrailingSeparators(path.slice(0, end), isPosixPathSeparator); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the extension of the `path` with leading period. + * + * @example Usage + * ```ts + * import { extname } from "@std/path/posix/extname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(extname("/home/user/Documents/file.ts"), ".ts"); + * assertEquals(extname("/home/user/Documents/"), ""); + * assertEquals(extname("/home/user/Documents/image.png"), ".png"); + * assertEquals(extname(new URL("file:///home/user/Documents/file.ts")), ".ts"); + * assertEquals(extname(new URL("file:///home/user/Documents/file.ts?a=b")), ".ts"); + * assertEquals(extname(new URL("file:///home/user/Documents/file.ts#header")), ".ts"); + * ``` + * + * @example Working with URLs + * + * Note: This function doesn't automatically strip hash and query parts from + * URLs. If your URL contains a hash or query, remove them before passing the + * URL to the function. This can be done by passing the URL to `new URL(url)`, + * and setting the `hash` and `search` properties to empty strings. + * + * ```ts + * import { extname } from "@std/path/posix/extname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(extname("https://deno.land/std/path/mod.ts"), ".ts"); + * assertEquals(extname("https://deno.land/std/path/mod.ts?a=b"), ".ts?a=b"); + * assertEquals(extname("https://deno.land/std/path/mod.ts#header"), ".ts#header"); + * ``` + * + * @param path The path to get the extension from. + * @returns The extension (ex. for `file.ts` returns `.ts`). + */ function extname(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertPath(path); + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + for(let i = path.length - 1; i >= 0; --i){ + const code = path.charCodeAt(i); + if (isPosixPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot + preDotState === 0 || // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ""; + } + return path.slice(startDot, end); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function _format(sep, pathObject) { + const dir = pathObject.dir || pathObject.root; + const base = pathObject.base || (pathObject.name ?? "") + (pathObject.ext ?? ""); + if (!dir) return base; + if (base === sep) return dir; + if (dir === pathObject.root) return dir + base; + return dir + sep + base; +} +function assertArg$1(pathObject) { + if (pathObject === null || typeof pathObject !== "object") { + throw new TypeError(`The "pathObject" argument must be of type Object, received type "${typeof pathObject}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Generate a path from `ParsedPath` object. + * + * @example Usage + * ```ts + * import { format } from "@std/path/posix/format"; + * import { assertEquals } from "@std/assert"; + * + * const path = format({ + * root: "/", + * dir: "/path/dir", + * base: "file.txt", + * ext: ".txt", + * name: "file" + * }); + * assertEquals(path, "/path/dir/file.txt"); + * ``` + * + * @param pathObject The path object to format. + * @returns The formatted path. + */ function format(pathObject) { + assertArg$1(pathObject); + return _format("/", pathObject); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Verifies whether provided path is absolute. + * + * @example Usage + * ```ts + * import { isAbsolute } from "@std/path/posix/is-absolute"; + * import { assert, assertFalse } from "@std/assert"; + * + * assert(isAbsolute("/home/user/Documents/")); + * assertFalse(isAbsolute("home/user/Documents/")); + * ``` + * + * @param path The path to verify. + * @returns Whether the path is absolute. + */ function isAbsolute(path) { + assertPath(path); + return path.length > 0 && isPosixPathSeparator(path.charCodeAt(0)); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg(path) { + assertPath(path); + if (path.length === 0) return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +// Resolves . and .. elements in a path with directory names +function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code; + for(let i = 0; i <= path.length; ++i){ + if (i < path.length) code = path.charCodeAt(i); + else if (isPathSeparator(code)) break; + else code = CHAR_FORWARD_SLASH; + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) ; else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf(separator); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } else if (res.length === 2 || res.length === 1) { + res = ""; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) res += `${separator}..`; + else res = ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) res += separator + path.slice(lastSlash + 1, i); + else res = path.slice(lastSlash + 1, i); + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Normalize the `path`, resolving `'..'` and `'.'` segments. + * Note that resolving these segments does not necessarily mean that all will be eliminated. + * A `'..'` at the top-level will be preserved, and an empty path is canonically `'.'`. + * + * @example Usage + * ```ts + * import { normalize } from "@std/path/posix/normalize"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(normalize("/foo/bar//baz/asdf/quux/.."), "/foo/bar/baz/asdf"); + * assertEquals(normalize(new URL("file:///foo/bar//baz/asdf/quux/..")), "/foo/bar/baz/asdf/"); + * ``` + * + * @example Working with URLs + * + * Note: This function will remove the double slashes from a URL's scheme. + * Hence, do not pass a full URL to this function. Instead, pass the pathname of + * the URL. + * + * ```ts + * import { normalize } from "@std/path/posix/normalize"; + * import { assertEquals } from "@std/assert"; + * + * const url = new URL("https://deno.land"); + * url.pathname = normalize("//std//assert//.//mod.ts"); + * assertEquals(url.href, "https://deno.land/std/assert/mod.ts"); + * + * url.pathname = normalize("std/assert/../async/retry.ts"); + * assertEquals(url.href, "https://deno.land/std/async/retry.ts"); + * ``` + * + * @param path The path to normalize. + * @returns The normalized path. + */ function normalize(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArg(path); + const isAbsolute = isPosixPathSeparator(path.charCodeAt(0)); + const trailingSeparator = isPosixPathSeparator(path.charCodeAt(path.length - 1)); + // Normalize the path + path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator); + if (path.length === 0 && !isAbsolute) path = "."; + if (path.length > 0 && trailingSeparator) path += "/"; + if (isAbsolute) return `/${path}`; + return path; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Join all given a sequence of `paths`,then normalizes the resulting path. + * + * @example Usage + * ```ts + * import { join } from "@std/path/posix/join"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(join("/foo", "bar", "baz/asdf", "quux", ".."), "/foo/bar/baz/asdf"); + * assertEquals(join(new URL("file:///foo"), "bar", "baz/asdf", "quux", ".."), "/foo/bar/baz/asdf"); + * ``` + * + * @example Working with URLs + * ```ts + * import { join } from "@std/path/posix/join"; + * import { assertEquals } from "@std/assert"; + * + * const url = new URL("https://deno.land"); + * url.pathname = join("std", "path", "mod.ts"); + * assertEquals(url.href, "https://deno.land/std/path/mod.ts"); + * + * url.pathname = join("//std", "path/", "/mod.ts"); + * assertEquals(url.href, "https://deno.land/std/path/mod.ts"); + * ``` + * + * @param path The path to join. This can be string or file URL. + * @param paths The paths to join. + * @returns The joined path. + */ function join(path, ...paths) { + if (path === undefined) return "."; + if (path instanceof URL) { + path = fromFileUrl(path); + } + paths = path ? [ + path, + ...paths + ] : paths; + paths.forEach((path)=>assertPath(path)); + const joined = paths.filter((path)=>path.length > 0).join("/"); + return joined === "" ? "." : normalize(joined); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return a `ParsedPath` object of the `path`. + * + * @example Usage + * ```ts + * import { parse } from "@std/path/posix/parse"; + * import { assertEquals } from "@std/assert"; + * + * const path = parse("/home/user/file.txt"); + * assertEquals(path, { + * root: "/", + * dir: "/home/user", + * base: "file.txt", + * ext: ".txt", + * name: "file" + * }); + * ``` + * + * @param path The path to parse. + * @returns The parsed path object. + */ function parse(path) { + assertPath(path); + const ret = { + root: "", + dir: "", + base: "", + ext: "", + name: "" + }; + if (path.length === 0) return ret; + const isAbsolute = isPosixPathSeparator(path.charCodeAt(0)); + let start; + if (isAbsolute) { + ret.root = "/"; + start = 1; + } else { + start = 0; + } + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + // Get non-dir info + for(; i >= start; --i){ + const code = path.charCodeAt(i); + if (isPosixPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot + preDotState === 0 || // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) { + ret.base = ret.name = path.slice(1, end); + } else { + ret.base = ret.name = path.slice(startPart, end); + } + } + // Fallback to '/' in case there is no basename + ret.base = ret.base || "/"; + } else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + if (startPart > 0) { + ret.dir = stripTrailingSeparators(path.slice(0, startPart - 1), isPosixPathSeparator); + } else if (isAbsolute) ret.dir = "/"; + return ret; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Resolves path segments into a `path`. + * + * @example Usage + * ```ts + * import { resolve } from "@std/path/posix/resolve"; + * import { assertEquals } from "@std/assert"; + * + * const path = resolve("/foo", "bar", "baz/asdf", "quux", ".."); + * assertEquals(path, "/foo/bar/baz/asdf"); + * ``` + * + * @param pathSegments The path segments to resolve. + * @returns The resolved path. + */ function resolve(...pathSegments) { + let resolvedPath = ""; + let resolvedAbsolute = false; + for(let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--){ + let path; + if (i >= 0) path = pathSegments[i]; + else { + // deno-lint-ignore no-explicit-any + const { Deno } = globalThis; + if (typeof Deno?.cwd !== "function") { + throw new TypeError("Resolved a relative path without a current working directory (CWD)"); + } + path = Deno.cwd(); + } + assertPath(path); + // Skip empty entries + if (path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isPosixPathSeparator(path.charCodeAt(0)); + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when Deno.cwd() fails) + // Normalize the path + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator); + if (resolvedAbsolute) { + if (resolvedPath.length > 0) return `/${resolvedPath}`; + else return "/"; + } else if (resolvedPath.length > 0) return resolvedPath; + else return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArgs(from, to) { + assertPath(from); + assertPath(to); + if (from === to) return ""; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the relative path from `from` to `to` based on current working directory. + * + * If `from` and `to` are the same, return an empty string. + * + * @example Usage + * ```ts + * import { relative } from "@std/path/posix/relative"; + * import { assertEquals } from "@std/assert"; + * + * const path = relative("/data/orandea/test/aaa", "/data/orandea/impl/bbb"); + * assertEquals(path, "../../impl/bbb"); + * ``` + * + * @param from The path to start from. + * @param to The path to reach. + * @returns The relative path. + */ function relative(from, to) { + assertArgs(from, to); + from = resolve(from); + to = resolve(to); + if (from === to) return ""; + // Trim any leading backslashes + let fromStart = 1; + const fromEnd = from.length; + for(; fromStart < fromEnd; ++fromStart){ + if (!isPosixPathSeparator(from.charCodeAt(fromStart))) break; + } + const fromLen = fromEnd - fromStart; + // Trim any leading backslashes + let toStart = 1; + const toEnd = to.length; + for(; toStart < toEnd; ++toStart){ + if (!isPosixPathSeparator(to.charCodeAt(toStart))) break; + } + const toLen = toEnd - toStart; + // Compare paths to find the longest common path from root + const length = fromLen < toLen ? fromLen : toLen; + let lastCommonSep = -1; + let i = 0; + for(; i <= length; ++i){ + if (i === length) { + if (toLen > length) { + if (isPosixPathSeparator(to.charCodeAt(toStart + i))) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } else if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } else if (fromLen > length) { + if (isPosixPathSeparator(from.charCodeAt(fromStart + i))) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo'; to='/' + lastCommonSep = 0; + } + } + break; + } + const fromCode = from.charCodeAt(fromStart + i); + const toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) break; + else if (isPosixPathSeparator(fromCode)) lastCommonSep = i; + } + let out = ""; + // Generate the relative path based on the path difference between `to` + // and `from` + for(i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i){ + if (i === fromEnd || isPosixPathSeparator(from.charCodeAt(i))) { + if (out.length === 0) out += ".."; + else out += "/.."; + } + } + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) return out + to.slice(toStart + lastCommonSep); + else { + toStart += lastCommonSep; + if (isPosixPathSeparator(to.charCodeAt(toStart))) ++toStart; + return to.slice(toStart); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +const WHITESPACE_ENCODINGS = { + "\u0009": "%09", + "\u000A": "%0A", + "\u000B": "%0B", + "\u000C": "%0C", + "\u000D": "%0D", + "\u0020": "%20" +}; +function encodeWhitespace(string) { + return string.replaceAll(/[\s]/g, (c)=>{ + return WHITESPACE_ENCODINGS[c] ?? c; + }); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a path string to a file URL. + * + * @example Usage + * ```ts + * import { toFileUrl } from "@std/path/posix/to-file-url"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(toFileUrl("/home/foo"), new URL("file:///home/foo")); + * assertEquals(toFileUrl("/home/foo bar"), new URL("file:///home/foo%20bar")); + * ``` + * + * @param path The path to convert. + * @returns The file URL. + */ function toFileUrl(path) { + if (!isAbsolute(path)) { + throw new TypeError(`Path must be absolute: received "${path}"`); + } + const url = new URL("file:///"); + url.pathname = encodeWhitespace(path.replace(/%/g, "%25").replace(/\\/g, "%5C")); + return url; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a path to a namespaced path. This function returns the path as is on posix. + * + * @example Usage + * ```ts + * import { toNamespacedPath } from "@std/path/posix/to-namespaced-path"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(toNamespacedPath("/home/foo"), "/home/foo"); + * ``` + * + * @param path The path. + * @returns The namespaced path. + */ function toNamespacedPath(path) { + // Non-op on posix systems + return path; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function common$1(paths, sep) { + const [first = "", ...remaining] = paths; + const parts = first.split(sep); + let endOfPrefix = parts.length; + let append = ""; + for (const path of remaining){ + const compare = path.split(sep); + if (compare.length <= endOfPrefix) { + endOfPrefix = compare.length; + append = ""; + } + for(let i = 0; i < endOfPrefix; i++){ + if (compare[i] !== parts[i]) { + endOfPrefix = i; + append = i === 0 ? "" : sep; + break; + } + } + } + return parts.slice(0, endOfPrefix).join(sep) + append; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** Determines the common path from a set of paths for POSIX systems. + * + * @example Usage + * ```ts + * import { common } from "@std/path/posix/common"; + * import { assertEquals } from "@std/assert"; + * + * const path = common([ + * "./deno/std/path/mod.ts", + * "./deno/std/fs/mod.ts", + * ]); + * assertEquals(path, "./deno/std/"); + * ``` + * + * @param paths The paths to compare. + * @returns The common path. + */ function common(paths) { + return common$1(paths, SEPARATOR); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Options for {@linkcode globToRegExp}, {@linkcode joinGlobs}, + * {@linkcode normalizeGlob} and {@linkcode expandGlob}. + */ const REG_EXP_ESCAPE_CHARS = [ + "!", + "$", + "(", + ")", + "*", + "+", + ".", + "=", + "?", + "[", + "\\", + "^", + "{", + "|" +]; +const RANGE_ESCAPE_CHARS = [ + "-", + "\\", + "]" +]; +function _globToRegExp(c, glob, { extended = true, globstar: globstarOption = true, // os = osType, +caseInsensitive = false } = {}) { + if (glob === "") { + return /(?!)/; + } + // Remove trailing separators. + let newLength = glob.length; + for(; newLength > 1 && c.seps.includes(glob[newLength - 1]); newLength--); + glob = glob.slice(0, newLength); + let regExpString = ""; + // Terminates correctly. Trust that `j` is incremented every iteration. + for(let j = 0; j < glob.length;){ + let segment = ""; + const groupStack = []; + let inRange = false; + let inEscape = false; + let endsWithSep = false; + let i = j; + // Terminates with `i` at the non-inclusive end of the current segment. + for(; i < glob.length && !c.seps.includes(glob[i]); i++){ + if (inEscape) { + inEscape = false; + const escapeChars = inRange ? RANGE_ESCAPE_CHARS : REG_EXP_ESCAPE_CHARS; + segment += escapeChars.includes(glob[i]) ? `\\${glob[i]}` : glob[i]; + continue; + } + if (glob[i] === c.escapePrefix) { + inEscape = true; + continue; + } + if (glob[i] === "[") { + if (!inRange) { + inRange = true; + segment += "["; + if (glob[i + 1] === "!") { + i++; + segment += "^"; + } else if (glob[i + 1] === "^") { + i++; + segment += "\\^"; + } + continue; + } else if (glob[i + 1] === ":") { + let k = i + 1; + let value = ""; + while(glob[k + 1] !== undefined && glob[k + 1] !== ":"){ + value += glob[k + 1]; + k++; + } + if (glob[k + 1] === ":" && glob[k + 2] === "]") { + i = k + 2; + if (value === "alnum") segment += "\\dA-Za-z"; + else if (value === "alpha") segment += "A-Za-z"; + else if (value === "ascii") segment += "\x00-\x7F"; + else if (value === "blank") segment += "\t "; + else if (value === "cntrl") segment += "\x00-\x1F\x7F"; + else if (value === "digit") segment += "\\d"; + else if (value === "graph") segment += "\x21-\x7E"; + else if (value === "lower") segment += "a-z"; + else if (value === "print") segment += "\x20-\x7E"; + else if (value === "punct") { + segment += "!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_‘{|}~"; + } else if (value === "space") segment += "\\s\v"; + else if (value === "upper") segment += "A-Z"; + else if (value === "word") segment += "\\w"; + else if (value === "xdigit") segment += "\\dA-Fa-f"; + continue; + } + } + } + if (glob[i] === "]" && inRange) { + inRange = false; + segment += "]"; + continue; + } + if (inRange) { + segment += glob[i]; + continue; + } + if (glob[i] === ")" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") { + segment += ")"; + const type = groupStack.pop(); + if (type === "!") { + segment += c.wildcard; + } else if (type !== "@") { + segment += type; + } + continue; + } + if (glob[i] === "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") { + segment += "|"; + continue; + } + if (glob[i] === "+" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("+"); + segment += "(?:"; + continue; + } + if (glob[i] === "@" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("@"); + segment += "(?:"; + continue; + } + if (glob[i] === "?") { + if (extended && glob[i + 1] === "(") { + i++; + groupStack.push("?"); + segment += "(?:"; + } else { + segment += "."; + } + continue; + } + if (glob[i] === "!" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("!"); + segment += "(?!"; + continue; + } + if (glob[i] === "{") { + groupStack.push("BRACE"); + segment += "(?:"; + continue; + } + if (glob[i] === "}" && groupStack[groupStack.length - 1] === "BRACE") { + groupStack.pop(); + segment += ")"; + continue; + } + if (glob[i] === "," && groupStack[groupStack.length - 1] === "BRACE") { + segment += "|"; + continue; + } + if (glob[i] === "*") { + if (extended && glob[i + 1] === "(") { + i++; + groupStack.push("*"); + segment += "(?:"; + } else { + const prevChar = glob[i - 1]; + let numStars = 1; + while(glob[i + 1] === "*"){ + i++; + numStars++; + } + const nextChar = glob[i + 1]; + if (globstarOption && numStars === 2 && [ + ...c.seps, + undefined + ].includes(prevChar) && [ + ...c.seps, + undefined + ].includes(nextChar)) { + segment += c.globstar; + endsWithSep = true; + } else { + segment += c.wildcard; + } + } + continue; + } + segment += REG_EXP_ESCAPE_CHARS.includes(glob[i]) ? `\\${glob[i]}` : glob[i]; + } + // Check for unclosed groups or a dangling backslash. + if (groupStack.length > 0 || inRange || inEscape) { + // Parse failure. Take all characters from this segment literally. + segment = ""; + for (const c of glob.slice(j, i)){ + segment += REG_EXP_ESCAPE_CHARS.includes(c) ? `\\${c}` : c; + endsWithSep = false; + } + } + regExpString += segment; + if (!endsWithSep) { + regExpString += i < glob.length ? c.sep : c.sepMaybe; + endsWithSep = true; + } + // Terminates with `i` at the start of the next segment. + while(c.seps.includes(glob[i]))i++; + j = i; + } + regExpString = `^${regExpString}$`; + return new RegExp(regExpString, caseInsensitive ? "i" : ""); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +const constants = { + sep: "/+", + sepMaybe: "/*", + seps: [ + "/" + ], + globstar: "(?:[^/]*(?:/|$)+)*", + wildcard: "[^/]*", + escapePrefix: "\\" +}; +/** Convert a glob string to a regular expression. + * + * Tries to match bash glob expansion as closely as possible. + * + * Basic glob syntax: + * - `*` - Matches everything without leaving the path segment. + * - `?` - Matches any single character. + * - `{foo,bar}` - Matches `foo` or `bar`. + * - `[abcd]` - Matches `a`, `b`, `c` or `d`. + * - `[a-d]` - Matches `a`, `b`, `c` or `d`. + * - `[!abcd]` - Matches any single character besides `a`, `b`, `c` or `d`. + * - `[[::]]` - Matches any character belonging to ``. + * - `[[:alnum:]]` - Matches any digit or letter. + * - `[[:digit:]abc]` - Matches any digit, `a`, `b` or `c`. + * - See https://facelessuser.github.io/wcmatch/glob/#posix-character-classes + * for a complete list of supported character classes. + * - `\` - Escapes the next character for an `os` other than `"windows"`. + * - \` - Escapes the next character for `os` set to `"windows"`. + * - `/` - Path separator. + * - `\` - Additional path separator only for `os` set to `"windows"`. + * + * Extended syntax: + * - Requires `{ extended: true }`. + * - `?(foo|bar)` - Matches 0 or 1 instance of `{foo,bar}`. + * - `@(foo|bar)` - Matches 1 instance of `{foo,bar}`. They behave the same. + * - `*(foo|bar)` - Matches _n_ instances of `{foo,bar}`. + * - `+(foo|bar)` - Matches _n > 0_ instances of `{foo,bar}`. + * - `!(foo|bar)` - Matches anything other than `{foo,bar}`. + * - See https://www.linuxjournal.com/content/bash-extended-globbing. + * + * Globstar syntax: + * - Requires `{ globstar: true }`. + * - `**` - Matches any number of any path segments. + * - Must comprise its entire path segment in the provided glob. + * - See https://www.linuxjournal.com/content/globstar-new-bash-globbing-option. + * + * Note the following properties: + * - The generated `RegExp` is anchored at both start and end. + * - Repeating and trailing separators are tolerated. Trailing separators in the + * provided glob have no meaning and are discarded. + * - Absolute globs will only match absolute paths, etc. + * - Empty globs will match nothing. + * - Any special glob syntax must be contained to one path segment. For example, + * `?(foo|bar/baz)` is invalid. The separator will take precedence and the + * first segment ends with an unclosed group. + * - If a path segment ends with unclosed groups or a dangling escape prefix, a + * parse error has occurred. Every character for that segment is taken + * literally in this event. + * + * Limitations: + * - A negative group like `!(foo|bar)` will wrongly be converted to a negative + * look-ahead followed by a wildcard. This means that `!(foo).js` will wrongly + * fail to match `foobar.js`, even though `foobar` is not `foo`. Effectively, + * `!(foo|bar)` is treated like `!(@(foo|bar)*)`. This will work correctly if + * the group occurs not nested at the end of the segment. + * + * @example Usage + * ```ts + * import { globToRegExp } from "@std/path/posix/glob-to-regexp"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(globToRegExp("*.js"), /^[^/]*\.js\/*$/); + * ``` + * + * @param glob Glob string to convert. + * @param options Conversion options. + * @returns The regular expression equivalent to the glob. + */ function globToRegExp(glob, options = {}) { + return _globToRegExp(constants, glob, options); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Test whether the given string is a glob. + * + * @example Usage + * ```ts + * import { isGlob } from "@std/path/is-glob"; + * import { assert } from "@std/assert"; + * + * assert(!isGlob("foo/bar/../baz")); + * assert(isGlob("foo/*ar/../baz")); + * ``` + * + * @param str String to test. + * @returns `true` if the given string is a glob, otherwise `false` + */ function isGlob(str) { + const chars = { + "{": "}", + "(": ")", + "[": "]" + }; + const regex = /\\(.)|(^!|\*|\?|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; + if (str === "") { + return false; + } + let match; + while(match = regex.exec(str)){ + if (match[2]) return true; + let idx = match.index + match[0].length; + // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + const open = match[1]; + const close = open ? chars[open] : null; + if (open && close) { + const n = str.indexOf(close, idx); + if (n !== -1) { + idx = n + 1; + } + } + str = str.slice(idx); + } + return false; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Like normalize(), but doesn't collapse "**\/.." when `globstar` is true. + * + * @example Usage + * ```ts + * import { normalizeGlob } from "@std/path/posix/normalize-glob"; + * import { assertEquals } from "@std/assert"; + * + * const path = normalizeGlob("foo/bar/../*", { globstar: true }); + * assertEquals(path, "foo/*"); + * ``` + * + * @param glob The glob to normalize. + * @param options The options to use. + * @returns The normalized path. + */ function normalizeGlob(glob, options = {}) { + const { globstar = false } = options; + if (glob.match(/\0/g)) { + throw new Error(`Glob contains invalid characters: "${glob}"`); + } + if (!globstar) { + return normalize(glob); + } + const s = SEPARATOR_PATTERN.source; + const badParentPattern = new RegExp(`(?<=(${s}|^)\\*\\*${s})\\.\\.(?=${s}|$)`, "g"); + return normalize(glob.replace(badParentPattern, "\0")).replace(/\0/g, ".."); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Like join(), but doesn't collapse "**\/.." when `globstar` is true. + * + * @example Usage + * ```ts + * import { joinGlobs } from "@std/path/posix/join-globs"; + * import { assertEquals } from "@std/assert"; + * + * const path = joinGlobs(["foo", "bar", "**"], { globstar: true }); + * assertEquals(path, "foo/bar/**"); + * ``` + * + * @param globs The globs to join. + * @param options The options to use. + * @returns The joined path. + */ function joinGlobs(globs, options = {}) { + const { globstar = false } = options; + if (!globstar || globs.length === 0) { + return join(...globs); + } + let joined; + for (const glob of globs){ + const path = glob; + if (path.length > 0) { + if (!joined) joined = path; + else joined += `${SEPARATOR}${path}`; + } + } + if (!joined) return "."; + return normalizeGlob(joined, { + globstar + }); +} + +export { DELIMITER, SEPARATOR, SEPARATOR_PATTERN, basename, common, dirname, extname, format, fromFileUrl, globToRegExp, isAbsolute, isGlob, join, joinGlobs, normalize, normalizeGlob, parse, relative, resolve, toFileUrl, toNamespacedPath }; diff --git a/node_modules/@eslint/config-array/dist/esm/std__path/windows.js b/node_modules/@eslint/config-array/dist/esm/std__path/windows.js new file mode 100644 index 00000000..fe79e8a3 --- /dev/null +++ b/node_modules/@eslint/config-array/dist/esm/std__path/windows.js @@ -0,0 +1,1655 @@ +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +function assertPath(path) { + if (typeof path !== "string") { + throw new TypeError(`Path must be a string, received "${JSON.stringify(path)}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function stripSuffix(name, suffix) { + if (suffix.length >= name.length) { + return name; + } + const lenDiff = name.length - suffix.length; + for(let i = suffix.length - 1; i >= 0; --i){ + if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) { + return name; + } + } + return name.slice(0, -suffix.length); +} +function lastPathSegment(path, isSep, start = 0) { + let matchedNonSeparator = false; + let end = path.length; + for(let i = path.length - 1; i >= start; --i){ + if (isSep(path.charCodeAt(i))) { + if (matchedNonSeparator) { + start = i + 1; + break; + } + } else if (!matchedNonSeparator) { + matchedNonSeparator = true; + end = i + 1; + } + } + return path.slice(start, end); +} +function assertArgs$1(path, suffix) { + assertPath(path); + if (path.length === 0) return path; + if (typeof suffix !== "string") { + throw new TypeError(`Suffix must be a string, received "${JSON.stringify(suffix)}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +// Alphabet chars. +const CHAR_UPPERCASE_A = 65; /* A */ +const CHAR_LOWERCASE_A = 97; /* a */ +const CHAR_UPPERCASE_Z = 90; /* Z */ +const CHAR_LOWERCASE_Z = 122; /* z */ +// Non-alphabetic chars. +const CHAR_DOT = 46; /* . */ +const CHAR_FORWARD_SLASH = 47; /* / */ +const CHAR_BACKWARD_SLASH = 92; /* \ */ +const CHAR_COLON = 58; /* : */ +const CHAR_QUESTION_MARK = 63; /* ? */ + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +function stripTrailingSeparators(segment, isSep) { + if (segment.length <= 1) { + return segment; + } + let end = segment.length; + for(let i = segment.length - 1; i > 0; i--){ + if (isSep(segment.charCodeAt(i))) { + end = i; + } else { + break; + } + } + return segment.slice(0, end); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; +} +function isPathSeparator(code) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +} +function isWindowsDeviceRoot(code) { + return code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z || code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg$3(url) { + url = url instanceof URL ? url : new URL(url); + if (url.protocol !== "file:") { + throw new TypeError(`URL must be a file URL: received "${url.protocol}"`); + } + return url; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a file URL to a path string. + * + * @example Usage + * ```ts + * import { fromFileUrl } from "@std/path/windows/from-file-url"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(fromFileUrl("file:///home/foo"), "\\home\\foo"); + * assertEquals(fromFileUrl("file:///C:/Users/foo"), "C:\\Users\\foo"); + * assertEquals(fromFileUrl("file://localhost/home/foo"), "\\home\\foo"); + * ``` + * + * @param url The file URL to convert. + * @returns The path string. + */ function fromFileUrl(url) { + url = assertArg$3(url); + let path = decodeURIComponent(url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\"); + if (url.hostname !== "") { + // Note: The `URL` implementation guarantees that the drive letter and + // hostname are mutually exclusive. Otherwise it would not have been valid + // to append the hostname and path like this. + path = `\\\\${url.hostname}${path}`; + } + return path; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the last portion of a `path`. + * Trailing directory separators are ignored, and optional suffix is removed. + * + * @example Usage + * ```ts + * import { basename } from "@std/path/windows/basename"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(basename("C:\\user\\Documents\\"), "Documents"); + * assertEquals(basename("C:\\user\\Documents\\image.png"), "image.png"); + * assertEquals(basename("C:\\user\\Documents\\image.png", ".png"), "image"); + * assertEquals(basename(new URL("file:///C:/user/Documents/image.png")), "image.png"); + * assertEquals(basename(new URL("file:///C:/user/Documents/image.png"), ".png"), "image"); + * ``` + * + * @param path The path to extract the name from. + * @param suffix The suffix to remove from extracted name. + * @returns The extracted name. + */ function basename(path, suffix = "") { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArgs$1(path, suffix); + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + let start = 0; + if (path.length >= 2) { + const drive = path.charCodeAt(0); + if (isWindowsDeviceRoot(drive)) { + if (path.charCodeAt(1) === CHAR_COLON) start = 2; + } + } + const lastSegment = lastPathSegment(path, isPathSeparator, start); + const strippedSegment = stripTrailingSeparators(lastSegment, isPathSeparator); + return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * The character used to separate entries in the PATH environment variable. + */ const DELIMITER = ";"; +/** + * The character used to separate components of a file path. + */ const SEPARATOR = "\\"; +/** + * A regular expression that matches one or more path separators. + */ const SEPARATOR_PATTERN = /[\\/]+/; + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg$2(path) { + assertPath(path); + if (path.length === 0) return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the directory path of a `path`. + * + * @example Usage + * ```ts + * import { dirname } from "@std/path/windows/dirname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(dirname("C:\\foo\\bar\\baz.ext"), "C:\\foo\\bar"); + * assertEquals(dirname(new URL("file:///C:/foo/bar/baz.ext")), "C:\\foo\\bar"); + * ``` + * + * @param path The path to get the directory from. + * @returns The directory path. + */ function dirname(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArg$2(path); + const len = path.length; + let rootEnd = -1; + let end = -1; + let matchedSlash = true; + let offset = 0; + const code = path.charCodeAt(0); + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + rootEnd = offset = 1; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for(; j < len; ++j){ + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + return path; + } + if (j !== last) { + // We matched a UNC root with leftovers + // Offset by 1 to include the separator after the UNC root to + // treat it as a "normal root" on top of a (UNC) root + rootEnd = offset = j + 1; + } + } + } + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (path.charCodeAt(1) === CHAR_COLON) { + rootEnd = offset = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) rootEnd = offset = 3; + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work + return path; + } + for(let i = len - 1; i >= offset; --i){ + if (isPathSeparator(path.charCodeAt(i))) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + if (end === -1) { + if (rootEnd === -1) return "."; + else end = rootEnd; + } + return stripTrailingSeparators(path.slice(0, end), isPosixPathSeparator); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the extension of the `path` with leading period. + * + * @example Usage + * ```ts + * import { extname } from "@std/path/windows/extname"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(extname("file.ts"), ".ts"); + * assertEquals(extname(new URL("file:///C:/foo/bar/baz.ext")), ".ext"); + * ``` + * + * @param path The path to get the extension from. + * @returns The extension of the `path`. + */ function extname(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertPath(path); + let start = 0; + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) { + start = startPart = 2; + } + for(let i = path.length - 1; i >= start; --i){ + const code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot + preDotState === 0 || // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ""; + } + return path.slice(startDot, end); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function _format(sep, pathObject) { + const dir = pathObject.dir || pathObject.root; + const base = pathObject.base || (pathObject.name ?? "") + (pathObject.ext ?? ""); + if (!dir) return base; + if (base === sep) return dir; + if (dir === pathObject.root) return dir + base; + return dir + sep + base; +} +function assertArg$1(pathObject) { + if (pathObject === null || typeof pathObject !== "object") { + throw new TypeError(`The "pathObject" argument must be of type Object, received type "${typeof pathObject}"`); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Generate a path from `ParsedPath` object. + * + * @example Usage + * ```ts + * import { format } from "@std/path/windows/format"; + * import { assertEquals } from "@std/assert"; + * + * const path = format({ + * root: "C:\\", + * dir: "C:\\path\\dir", + * base: "file.txt", + * ext: ".txt", + * name: "file" + * }); + * assertEquals(path, "C:\\path\\dir\\file.txt"); + * ``` + * + * @param pathObject The path object to format. + * @returns The formatted path. + */ function format(pathObject) { + assertArg$1(pathObject); + return _format("\\", pathObject); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Verifies whether provided path is absolute. + * + * @example Usage + * ```ts + * import { isAbsolute } from "@std/path/windows/is-absolute"; + * import { assert, assertFalse } from "@std/assert"; + * + * assert(isAbsolute("C:\\foo\\bar")); + * assertFalse(isAbsolute("..\\baz")); + * ``` + * + * @param path The path to verify. + * @returns `true` if the path is absolute, `false` otherwise. + */ function isAbsolute(path) { + assertPath(path); + const len = path.length; + if (len === 0) return false; + const code = path.charCodeAt(0); + if (isPathSeparator(code)) { + return true; + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (len > 2 && path.charCodeAt(1) === CHAR_COLON) { + if (isPathSeparator(path.charCodeAt(2))) return true; + } + } + return false; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArg(path) { + assertPath(path); + if (path.length === 0) return "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ +// This module is browser compatible. +// Resolves . and .. elements in a path with directory names +function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code; + for(let i = 0; i <= path.length; ++i){ + if (i < path.length) code = path.charCodeAt(i); + else if (isPathSeparator(code)) break; + else code = CHAR_FORWARD_SLASH; + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) ; else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf(separator); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } else if (res.length === 2 || res.length === 1) { + res = ""; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) res += `${separator}..`; + else res = ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) res += separator + path.slice(lastSlash + 1, i); + else res = path.slice(lastSlash + 1, i); + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Normalize the `path`, resolving `'..'` and `'.'` segments. + * Note that resolving these segments does not necessarily mean that all will be eliminated. + * A `'..'` at the top-level will be preserved, and an empty path is canonically `'.'`. + * + * @example Usage + * ```ts + * import { normalize } from "@std/path/windows/normalize"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(normalize("C:\\foo\\..\\bar"), "C:\\bar"); + * assertEquals(normalize(new URL("file:///C:/foo/../bar")), "C:\\bar"); + * ``` + * + * @param path The path to normalize + * @returns The normalized path + */ function normalize(path) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArg(path); + const len = path.length; + let rootEnd = 0; + let device; + let isAbsolute = false; + const code = path.charCodeAt(0); + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + // If we started with a separator, we know we at least have an absolute + // path of some kind (UNC or otherwise) + isAbsolute = true; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + for(; j < len; ++j){ + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + // Return the normalized version of the UNC root since there + // is nothing left to process + return `\\\\${firstPart}\\${path.slice(last)}\\`; + } else if (j !== last) { + // We matched a UNC root with leftovers + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } else { + rootEnd = 1; + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid unnecessary + // work + return "\\"; + } + let tail; + if (rootEnd < len) { + tail = normalizeString(path.slice(rootEnd), !isAbsolute, "\\", isPathSeparator); + } else { + tail = ""; + } + if (tail.length === 0 && !isAbsolute) tail = "."; + if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) { + tail += "\\"; + } + if (device === undefined) { + if (isAbsolute) { + if (tail.length > 0) return `\\${tail}`; + else return "\\"; + } + return tail; + } else if (isAbsolute) { + if (tail.length > 0) return `${device}\\${tail}`; + else return `${device}\\`; + } + return device + tail; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Join all given a sequence of `paths`,then normalizes the resulting path. + * + * @example Usage + * ```ts + * import { join } from "@std/path/windows/join"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(join("C:\\foo", "bar", "baz\\.."), "C:\\foo\\bar"); + * assertEquals(join(new URL("file:///C:/foo"), "bar", "baz\\.."), "C:\\foo\\bar"); + * ``` + * + * @param path The path to join. This can be string or file URL. + * @param paths The paths to join. + * @returns The joined path. + */ function join(path, ...paths) { + if (path instanceof URL) { + path = fromFileUrl(path); + } + paths = path ? [ + path, + ...paths + ] : paths; + paths.forEach((path)=>assertPath(path)); + paths = paths.filter((path)=>path.length > 0); + if (paths.length === 0) return "."; + // Make sure that the joined path doesn't start with two slashes, because + // normalize() will mistake it for an UNC path then. + // + // This step is skipped when it is very clear that the user actually + // intended to point at an UNC path. This is assumed when the first + // non-empty string arguments starts with exactly two slashes followed by + // at least one more non-slash character. + // + // Note that for normalize() to treat a path as an UNC path it needs to + // have at least 2 components, so we don't filter for that here. + // This means that the user can use join to construct UNC paths from + // a server name and a share name; for example: + // path.join('//server', 'share') -> '\\\\server\\share\\' + let needsReplace = true; + let slashCount = 0; + const firstPart = paths[0]; + if (isPathSeparator(firstPart.charCodeAt(0))) { + ++slashCount; + const firstLen = firstPart.length; + if (firstLen > 1) { + if (isPathSeparator(firstPart.charCodeAt(1))) { + ++slashCount; + if (firstLen > 2) { + if (isPathSeparator(firstPart.charCodeAt(2))) ++slashCount; + else { + // We matched a UNC path in the first part + needsReplace = false; + } + } + } + } + } + let joined = paths.join("\\"); + if (needsReplace) { + // Find any more consecutive slashes we need to replace + for(; slashCount < joined.length; ++slashCount){ + if (!isPathSeparator(joined.charCodeAt(slashCount))) break; + } + // Replace the slashes if needed + if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`; + } + return normalize(joined); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return a `ParsedPath` object of the `path`. + * + * @example Usage + * ```ts + * import { parse } from "@std/path/windows/parse"; + * import { assertEquals } from "@std/assert"; + * + * const parsed = parse("C:\\foo\\bar\\baz.ext"); + * assertEquals(parsed, { + * root: "C:\\", + * dir: "C:\\foo\\bar", + * base: "baz.ext", + * ext: ".ext", + * name: "baz", + * }); + * ``` + * + * @param path The path to parse. + * @returns The `ParsedPath` object. + */ function parse(path) { + assertPath(path); + const ret = { + root: "", + dir: "", + base: "", + ext: "", + name: "" + }; + const len = path.length; + if (len === 0) return ret; + let rootEnd = 0; + let code = path.charCodeAt(0); + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + rootEnd = 1; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for(; j < len; ++j){ + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + rootEnd = j; + } else if (j !== last) { + // We matched a UNC root with leftovers + rootEnd = j + 1; + } + } + } + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (path.charCodeAt(1) === CHAR_COLON) { + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + if (len === 3) { + // `path` contains just a drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + ret.base = "\\"; + return ret; + } + rootEnd = 3; + } + } else { + // `path` contains just a relative drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + ret.base = "\\"; + return ret; + } + if (rootEnd > 0) ret.root = path.slice(0, rootEnd); + let startDot = -1; + let startPart = rootEnd; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + // Get non-dir info + for(; i >= rootEnd; --i){ + code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot + preDotState === 0 || // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + ret.base = ret.name = path.slice(startPart, end); + } + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + ret.ext = path.slice(startDot, end); + } + // Fallback to '\' in case there is no basename + ret.base = ret.base || "\\"; + // If the directory is the root, use the entire root as the `dir` including + // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the + // trailing slash (`C:\abc\def` -> `C:\abc`). + if (startPart > 0 && startPart !== rootEnd) { + ret.dir = path.slice(0, startPart - 1); + } else ret.dir = ret.root; + return ret; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Resolves path segments into a `path`. + * + * @example Usage + * ```ts + * import { resolve } from "@std/path/windows/resolve"; + * import { assertEquals } from "@std/assert"; + * + * const resolved = resolve("C:\\foo\\bar", "..\\baz"); + * assertEquals(resolved, "C:\\foo\\baz"); + * ``` + * + * @param pathSegments The path segments to process to path + * @returns The resolved path + */ function resolve(...pathSegments) { + let resolvedDevice = ""; + let resolvedTail = ""; + let resolvedAbsolute = false; + for(let i = pathSegments.length - 1; i >= -1; i--){ + let path; + // deno-lint-ignore no-explicit-any + const { Deno } = globalThis; + if (i >= 0) { + path = pathSegments[i]; + } else if (!resolvedDevice) { + if (typeof Deno?.cwd !== "function") { + throw new TypeError("Resolved a drive-letter-less path without a current working directory (CWD)"); + } + path = Deno.cwd(); + } else { + if (typeof Deno?.env?.get !== "function" || typeof Deno?.cwd !== "function") { + throw new TypeError("Resolved a relative path without a current working directory (CWD)"); + } + path = Deno.cwd(); + // Verify that a cwd was found and that it actually points + // to our drive. If not, default to the drive's root. + if (path === undefined || path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`) { + path = `${resolvedDevice}\\`; + } + } + assertPath(path); + const len = path.length; + // Skip empty entries + if (len === 0) continue; + let rootEnd = 0; + let device = ""; + let isAbsolute = false; + const code = path.charCodeAt(0); + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + // If we started with a separator, we know we at least have an + // absolute path of some kind (UNC or otherwise) + isAbsolute = true; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + for(; j < len; ++j){ + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for(; j < len; ++j){ + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + device = `\\\\${firstPart}\\${path.slice(last)}`; + rootEnd = j; + } else if (j !== last) { + // We matched a UNC root with leftovers + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } else { + rootEnd = 1; + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + if (path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator + rootEnd = 1; + isAbsolute = true; + } + if (device.length > 0 && resolvedDevice.length > 0 && device.toLowerCase() !== resolvedDevice.toLowerCase()) { + continue; + } + if (resolvedDevice.length === 0 && device.length > 0) { + resolvedDevice = device; + } + if (!resolvedAbsolute) { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + } + if (resolvedAbsolute && resolvedDevice.length > 0) break; + } + // At this point the path should be resolved to a full absolute path, + // but handle relative paths to be safe (might happen when Deno.cwd() + // fails) + // Normalize the tail path + resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator); + return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || "."; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function assertArgs(from, to) { + assertPath(from); + assertPath(to); + if (from === to) return ""; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Return the relative path from `from` to `to` based on current working directory. + * + * An example in windws, for instance: + * from = 'C:\\orandea\\test\\aaa' + * to = 'C:\\orandea\\impl\\bbb' + * The output of the function should be: '..\\..\\impl\\bbb' + * + * @example Usage + * ```ts + * import { relative } from "@std/path/windows/relative"; + * import { assertEquals } from "@std/assert"; + * + * const relativePath = relative("C:\\foobar\\test\\aaa", "C:\\foobar\\impl\\bbb"); + * assertEquals(relativePath, "..\\..\\impl\\bbb"); + * ``` + * + * @param from The path from which to calculate the relative path + * @param to The path to which to calculate the relative path + * @returns The relative path from `from` to `to` + */ function relative(from, to) { + assertArgs(from, to); + const fromOrig = resolve(from); + const toOrig = resolve(to); + if (fromOrig === toOrig) return ""; + from = fromOrig.toLowerCase(); + to = toOrig.toLowerCase(); + if (from === to) return ""; + // Trim any leading backslashes + let fromStart = 0; + let fromEnd = from.length; + for(; fromStart < fromEnd; ++fromStart){ + if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH) break; + } + // Trim trailing backslashes (applicable to UNC paths only) + for(; fromEnd - 1 > fromStart; --fromEnd){ + if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break; + } + const fromLen = fromEnd - fromStart; + // Trim any leading backslashes + let toStart = 0; + let toEnd = to.length; + for(; toStart < toEnd; ++toStart){ + if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH) break; + } + // Trim trailing backslashes (applicable to UNC paths only) + for(; toEnd - 1 > toStart; --toEnd){ + if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break; + } + const toLen = toEnd - toStart; + // Compare paths to find the longest common path from root + const length = fromLen < toLen ? fromLen : toLen; + let lastCommonSep = -1; + let i = 0; + for(; i <= length; ++i){ + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' + return toOrig.slice(toStart + i + 1); + } else if (i === 2) { + // We get here if `from` is the device root. + // For example: from='C:\\'; to='C:\\foo' + return toOrig.slice(toStart + i); + } + } + if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='C:\\foo\\bar'; to='C:\\foo' + lastCommonSep = i; + } else if (i === 2) { + // We get here if `to` is the device root. + // For example: from='C:\\foo\\bar'; to='C:\\' + lastCommonSep = 3; + } + } + break; + } + const fromCode = from.charCodeAt(fromStart + i); + const toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) break; + else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i; + } + // We found a mismatch before the first common path separator was seen, so + // return the original `to`. + if (i !== length && lastCommonSep === -1) { + return toOrig; + } + let out = ""; + if (lastCommonSep === -1) lastCommonSep = 0; + // Generate the relative path based on the path difference between `to` and + // `from` + for(i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i){ + if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { + if (out.length === 0) out += ".."; + else out += "\\.."; + } + } + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) { + return out + toOrig.slice(toStart + lastCommonSep, toEnd); + } else { + toStart += lastCommonSep; + if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) ++toStart; + return toOrig.slice(toStart, toEnd); + } +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +const WHITESPACE_ENCODINGS = { + "\u0009": "%09", + "\u000A": "%0A", + "\u000B": "%0B", + "\u000C": "%0C", + "\u000D": "%0D", + "\u0020": "%20" +}; +function encodeWhitespace(string) { + return string.replaceAll(/[\s]/g, (c)=>{ + return WHITESPACE_ENCODINGS[c] ?? c; + }); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Converts a path string to a file URL. + * + * @example Usage + * ```ts + * import { toFileUrl } from "@std/path/windows/to-file-url"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(toFileUrl("\\home\\foo"), new URL("file:///home/foo")); + * assertEquals(toFileUrl("C:\\Users\\foo"), new URL("file:///C:/Users/foo")); + * assertEquals(toFileUrl("\\\\127.0.0.1\\home\\foo"), new URL("file://127.0.0.1/home/foo")); + * ``` + * @param path The path to convert. + * @returns The file URL. + */ function toFileUrl(path) { + if (!isAbsolute(path)) { + throw new TypeError(`Path must be absolute: received "${path}"`); + } + const [, hostname, pathname] = path.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/); + const url = new URL("file:///"); + url.pathname = encodeWhitespace(pathname.replace(/%/g, "%25")); + if (hostname !== undefined && hostname !== "localhost") { + url.hostname = hostname; + if (!url.hostname) { + throw new TypeError(`Invalid hostname: "${url.hostname}"`); + } + } + return url; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Resolves path to a namespace path + * + * @example Usage + * ```ts + * import { toNamespacedPath } from "@std/path/windows/to-namespaced-path"; + * import { assertEquals } from "@std/assert"; + * + * const namespaced = toNamespacedPath("C:\\foo\\bar"); + * assertEquals(namespaced, "\\\\?\\C:\\foo\\bar"); + * ``` + * + * @param path The path to resolve to namespaced path + * @returns The resolved namespaced path + */ function toNamespacedPath(path) { + // Note: this will *probably* throw somewhere. + if (typeof path !== "string") return path; + if (path.length === 0) return ""; + const resolvedPath = resolve(path); + if (resolvedPath.length >= 3) { + if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { + // Possible UNC root + if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { + const code = resolvedPath.charCodeAt(2); + if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { + // Matched non-long UNC root, convert the path to a long UNC path + return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; + } + } + } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0))) { + // Possible device root + if (resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) { + // Matched device root, convert the path to a long UNC path + return `\\\\?\\${resolvedPath}`; + } + } + } + return path; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +function common$1(paths, sep) { + const [first = "", ...remaining] = paths; + const parts = first.split(sep); + let endOfPrefix = parts.length; + let append = ""; + for (const path of remaining){ + const compare = path.split(sep); + if (compare.length <= endOfPrefix) { + endOfPrefix = compare.length; + append = ""; + } + for(let i = 0; i < endOfPrefix; i++){ + if (compare[i] !== parts[i]) { + endOfPrefix = i; + append = i === 0 ? "" : sep; + break; + } + } + } + return parts.slice(0, endOfPrefix).join(sep) + append; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Determines the common path from a set of paths for Windows systems. + * + * @example Usage + * ```ts + * import { common } from "@std/path/windows/common"; + * import { assertEquals } from "@std/assert"; + * + * const path = common([ + * "C:\\foo\\bar", + * "C:\\foo\\baz", + * ]); + * assertEquals(path, "C:\\foo\\"); + * ``` + * + * @param paths The paths to compare. + * @returns The common path. + */ function common(paths) { + return common$1(paths, SEPARATOR); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Options for {@linkcode globToRegExp}, {@linkcode joinGlobs}, + * {@linkcode normalizeGlob} and {@linkcode expandGlob}. + */ const REG_EXP_ESCAPE_CHARS = [ + "!", + "$", + "(", + ")", + "*", + "+", + ".", + "=", + "?", + "[", + "\\", + "^", + "{", + "|" +]; +const RANGE_ESCAPE_CHARS = [ + "-", + "\\", + "]" +]; +function _globToRegExp(c, glob, { extended = true, globstar: globstarOption = true, // os = osType, +caseInsensitive = false } = {}) { + if (glob === "") { + return /(?!)/; + } + // Remove trailing separators. + let newLength = glob.length; + for(; newLength > 1 && c.seps.includes(glob[newLength - 1]); newLength--); + glob = glob.slice(0, newLength); + let regExpString = ""; + // Terminates correctly. Trust that `j` is incremented every iteration. + for(let j = 0; j < glob.length;){ + let segment = ""; + const groupStack = []; + let inRange = false; + let inEscape = false; + let endsWithSep = false; + let i = j; + // Terminates with `i` at the non-inclusive end of the current segment. + for(; i < glob.length && !c.seps.includes(glob[i]); i++){ + if (inEscape) { + inEscape = false; + const escapeChars = inRange ? RANGE_ESCAPE_CHARS : REG_EXP_ESCAPE_CHARS; + segment += escapeChars.includes(glob[i]) ? `\\${glob[i]}` : glob[i]; + continue; + } + if (glob[i] === c.escapePrefix) { + inEscape = true; + continue; + } + if (glob[i] === "[") { + if (!inRange) { + inRange = true; + segment += "["; + if (glob[i + 1] === "!") { + i++; + segment += "^"; + } else if (glob[i + 1] === "^") { + i++; + segment += "\\^"; + } + continue; + } else if (glob[i + 1] === ":") { + let k = i + 1; + let value = ""; + while(glob[k + 1] !== undefined && glob[k + 1] !== ":"){ + value += glob[k + 1]; + k++; + } + if (glob[k + 1] === ":" && glob[k + 2] === "]") { + i = k + 2; + if (value === "alnum") segment += "\\dA-Za-z"; + else if (value === "alpha") segment += "A-Za-z"; + else if (value === "ascii") segment += "\x00-\x7F"; + else if (value === "blank") segment += "\t "; + else if (value === "cntrl") segment += "\x00-\x1F\x7F"; + else if (value === "digit") segment += "\\d"; + else if (value === "graph") segment += "\x21-\x7E"; + else if (value === "lower") segment += "a-z"; + else if (value === "print") segment += "\x20-\x7E"; + else if (value === "punct") { + segment += "!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_‘{|}~"; + } else if (value === "space") segment += "\\s\v"; + else if (value === "upper") segment += "A-Z"; + else if (value === "word") segment += "\\w"; + else if (value === "xdigit") segment += "\\dA-Fa-f"; + continue; + } + } + } + if (glob[i] === "]" && inRange) { + inRange = false; + segment += "]"; + continue; + } + if (inRange) { + segment += glob[i]; + continue; + } + if (glob[i] === ")" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") { + segment += ")"; + const type = groupStack.pop(); + if (type === "!") { + segment += c.wildcard; + } else if (type !== "@") { + segment += type; + } + continue; + } + if (glob[i] === "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") { + segment += "|"; + continue; + } + if (glob[i] === "+" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("+"); + segment += "(?:"; + continue; + } + if (glob[i] === "@" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("@"); + segment += "(?:"; + continue; + } + if (glob[i] === "?") { + if (extended && glob[i + 1] === "(") { + i++; + groupStack.push("?"); + segment += "(?:"; + } else { + segment += "."; + } + continue; + } + if (glob[i] === "!" && extended && glob[i + 1] === "(") { + i++; + groupStack.push("!"); + segment += "(?!"; + continue; + } + if (glob[i] === "{") { + groupStack.push("BRACE"); + segment += "(?:"; + continue; + } + if (glob[i] === "}" && groupStack[groupStack.length - 1] === "BRACE") { + groupStack.pop(); + segment += ")"; + continue; + } + if (glob[i] === "," && groupStack[groupStack.length - 1] === "BRACE") { + segment += "|"; + continue; + } + if (glob[i] === "*") { + if (extended && glob[i + 1] === "(") { + i++; + groupStack.push("*"); + segment += "(?:"; + } else { + const prevChar = glob[i - 1]; + let numStars = 1; + while(glob[i + 1] === "*"){ + i++; + numStars++; + } + const nextChar = glob[i + 1]; + if (globstarOption && numStars === 2 && [ + ...c.seps, + undefined + ].includes(prevChar) && [ + ...c.seps, + undefined + ].includes(nextChar)) { + segment += c.globstar; + endsWithSep = true; + } else { + segment += c.wildcard; + } + } + continue; + } + segment += REG_EXP_ESCAPE_CHARS.includes(glob[i]) ? `\\${glob[i]}` : glob[i]; + } + // Check for unclosed groups or a dangling backslash. + if (groupStack.length > 0 || inRange || inEscape) { + // Parse failure. Take all characters from this segment literally. + segment = ""; + for (const c of glob.slice(j, i)){ + segment += REG_EXP_ESCAPE_CHARS.includes(c) ? `\\${c}` : c; + endsWithSep = false; + } + } + regExpString += segment; + if (!endsWithSep) { + regExpString += i < glob.length ? c.sep : c.sepMaybe; + endsWithSep = true; + } + // Terminates with `i` at the start of the next segment. + while(c.seps.includes(glob[i]))i++; + j = i; + } + regExpString = `^${regExpString}$`; + return new RegExp(regExpString, caseInsensitive ? "i" : ""); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +const constants = { + sep: "(?:\\\\|/)+", + sepMaybe: "(?:\\\\|/)*", + seps: [ + "\\", + "/" + ], + globstar: "(?:[^\\\\/]*(?:\\\\|/|$)+)*", + wildcard: "[^\\\\/]*", + escapePrefix: "`" +}; +/** Convert a glob string to a regular expression. + * + * Tries to match bash glob expansion as closely as possible. + * + * Basic glob syntax: + * - `*` - Matches everything without leaving the path segment. + * - `?` - Matches any single character. + * - `{foo,bar}` - Matches `foo` or `bar`. + * - `[abcd]` - Matches `a`, `b`, `c` or `d`. + * - `[a-d]` - Matches `a`, `b`, `c` or `d`. + * - `[!abcd]` - Matches any single character besides `a`, `b`, `c` or `d`. + * - `[[::]]` - Matches any character belonging to ``. + * - `[[:alnum:]]` - Matches any digit or letter. + * - `[[:digit:]abc]` - Matches any digit, `a`, `b` or `c`. + * - See https://facelessuser.github.io/wcmatch/glob/#posix-character-classes + * for a complete list of supported character classes. + * - `\` - Escapes the next character for an `os` other than `"windows"`. + * - \` - Escapes the next character for `os` set to `"windows"`. + * - `/` - Path separator. + * - `\` - Additional path separator only for `os` set to `"windows"`. + * + * Extended syntax: + * - Requires `{ extended: true }`. + * - `?(foo|bar)` - Matches 0 or 1 instance of `{foo,bar}`. + * - `@(foo|bar)` - Matches 1 instance of `{foo,bar}`. They behave the same. + * - `*(foo|bar)` - Matches _n_ instances of `{foo,bar}`. + * - `+(foo|bar)` - Matches _n > 0_ instances of `{foo,bar}`. + * - `!(foo|bar)` - Matches anything other than `{foo,bar}`. + * - See https://www.linuxjournal.com/content/bash-extended-globbing. + * + * Globstar syntax: + * - Requires `{ globstar: true }`. + * - `**` - Matches any number of any path segments. + * - Must comprise its entire path segment in the provided glob. + * - See https://www.linuxjournal.com/content/globstar-new-bash-globbing-option. + * + * Note the following properties: + * - The generated `RegExp` is anchored at both start and end. + * - Repeating and trailing separators are tolerated. Trailing separators in the + * provided glob have no meaning and are discarded. + * - Absolute globs will only match absolute paths, etc. + * - Empty globs will match nothing. + * - Any special glob syntax must be contained to one path segment. For example, + * `?(foo|bar/baz)` is invalid. The separator will take precedence and the + * first segment ends with an unclosed group. + * - If a path segment ends with unclosed groups or a dangling escape prefix, a + * parse error has occurred. Every character for that segment is taken + * literally in this event. + * + * Limitations: + * - A negative group like `!(foo|bar)` will wrongly be converted to a negative + * look-ahead followed by a wildcard. This means that `!(foo).js` will wrongly + * fail to match `foobar.js`, even though `foobar` is not `foo`. Effectively, + * `!(foo|bar)` is treated like `!(@(foo|bar)*)`. This will work correctly if + * the group occurs not nested at the end of the segment. + * + * @example Usage + * ```ts + * import { globToRegExp } from "@std/path/windows/glob-to-regexp"; + * import { assertEquals } from "@std/assert"; + * + * assertEquals(globToRegExp("*.js"), /^[^\\/]*\.js(?:\\|\/)*$/); + * ``` + * + * @param glob Glob string to convert. + * @param options Conversion options. + * @returns The regular expression equivalent to the glob. + */ function globToRegExp(glob, options = {}) { + return _globToRegExp(constants, glob, options); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Test whether the given string is a glob. + * + * @example Usage + * ```ts + * import { isGlob } from "@std/path/is-glob"; + * import { assert } from "@std/assert"; + * + * assert(!isGlob("foo/bar/../baz")); + * assert(isGlob("foo/*ar/../baz")); + * ``` + * + * @param str String to test. + * @returns `true` if the given string is a glob, otherwise `false` + */ function isGlob(str) { + const chars = { + "{": "}", + "(": ")", + "[": "]" + }; + const regex = /\\(.)|(^!|\*|\?|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; + if (str === "") { + return false; + } + let match; + while(match = regex.exec(str)){ + if (match[2]) return true; + let idx = match.index + match[0].length; + // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + const open = match[1]; + const close = open ? chars[open] : null; + if (open && close) { + const n = str.indexOf(close, idx); + if (n !== -1) { + idx = n + 1; + } + } + str = str.slice(idx); + } + return false; +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Like normalize(), but doesn't collapse "**\/.." when `globstar` is true. + * + * @example Usage + * ```ts + * import { normalizeGlob } from "@std/path/windows/normalize-glob"; + * import { assertEquals } from "@std/assert"; + * + * const normalized = normalizeGlob("**\\foo\\..\\bar", { globstar: true }); + * assertEquals(normalized, "**\\bar"); + * ``` + * + * @param glob The glob pattern to normalize. + * @param options The options for glob pattern. + * @returns The normalized glob pattern. + */ function normalizeGlob(glob, options = {}) { + const { globstar = false } = options; + if (glob.match(/\0/g)) { + throw new Error(`Glob contains invalid characters: "${glob}"`); + } + if (!globstar) { + return normalize(glob); + } + const s = SEPARATOR_PATTERN.source; + const badParentPattern = new RegExp(`(?<=(${s}|^)\\*\\*${s})\\.\\.(?=${s}|$)`, "g"); + return normalize(glob.replace(badParentPattern, "\0")).replace(/\0/g, ".."); +} + +// Copyright 2018-2025 the Deno authors. MIT license. +// This module is browser compatible. +/** + * Like join(), but doesn't collapse "**\/.." when `globstar` is true. + * + * @example Usage + * + * ```ts + * import { joinGlobs } from "@std/path/windows/join-globs"; + * import { assertEquals } from "@std/assert"; + * + * const joined = joinGlobs(["foo", "**", "bar"], { globstar: true }); + * assertEquals(joined, "foo\\**\\bar"); + * ``` + * + * @param globs The globs to join. + * @param options The options for glob pattern. + * @returns The joined glob pattern. + */ function joinGlobs(globs, options = {}) { + const { globstar = false } = options; + if (!globstar || globs.length === 0) { + return join(...globs); + } + let joined; + for (const glob of globs){ + const path = glob; + if (path.length > 0) { + if (!joined) joined = path; + else joined += `${SEPARATOR}${path}`; + } + } + if (!joined) return "."; + return normalizeGlob(joined, { + globstar + }); +} + +export { DELIMITER, SEPARATOR, SEPARATOR_PATTERN, basename, common, dirname, extname, format, fromFileUrl, globToRegExp, isAbsolute, isGlob, join, joinGlobs, normalize, normalizeGlob, parse, relative, resolve, toFileUrl, toNamespacedPath }; diff --git a/node_modules/@eslint/config-array/dist/esm/types.d.ts b/node_modules/@eslint/config-array/dist/esm/types.d.ts new file mode 100644 index 00000000..a495d940 --- /dev/null +++ b/node_modules/@eslint/config-array/dist/esm/types.d.ts @@ -0,0 +1,19 @@ +/** + * @fileoverview Types for the config-array package. + * @author Nicholas C. Zakas + */ +export interface ConfigObject { + /** + * The files to include. + */ + files?: string[]; + /** + * The files to exclude. + */ + ignores?: string[]; + /** + * The name of the config object. + */ + name?: string; + [key: string]: unknown; +} diff --git a/node_modules/@eslint/config-array/dist/esm/types.ts b/node_modules/@eslint/config-array/dist/esm/types.ts new file mode 100644 index 00000000..1af40113 --- /dev/null +++ b/node_modules/@eslint/config-array/dist/esm/types.ts @@ -0,0 +1,24 @@ +/** + * @fileoverview Types for the config-array package. + * @author Nicholas C. Zakas + */ + +export interface ConfigObject { + /** + * The files to include. + */ + files?: string[]; + + /** + * The files to exclude. + */ + ignores?: string[]; + + /** + * The name of the config object. + */ + name?: string; + + // may also have any number of other properties + [key: string]: unknown; +} diff --git a/node_modules/@eslint/config-array/node_modules/brace-expansion/LICENSE b/node_modules/@eslint/config-array/node_modules/brace-expansion/LICENSE new file mode 100644 index 00000000..de322667 --- /dev/null +++ b/node_modules/@eslint/config-array/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@eslint/config-array/node_modules/brace-expansion/README.md b/node_modules/@eslint/config-array/node_modules/brace-expansion/README.md new file mode 100644 index 00000000..6b4e0e16 --- /dev/null +++ b/node_modules/@eslint/config-array/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@eslint/config-array/node_modules/brace-expansion/index.js b/node_modules/@eslint/config-array/node_modules/brace-expansion/index.js new file mode 100644 index 00000000..bd19fe68 --- /dev/null +++ b/node_modules/@eslint/config-array/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/@eslint/config-array/node_modules/brace-expansion/package.json b/node_modules/@eslint/config-array/node_modules/brace-expansion/package.json new file mode 100644 index 00000000..34478881 --- /dev/null +++ b/node_modules/@eslint/config-array/node_modules/brace-expansion/package.json @@ -0,0 +1,50 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "1.1.12", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "publishConfig": { + "tag": "1.x" + } +} diff --git a/node_modules/@eslint/config-array/node_modules/minimatch/LICENSE b/node_modules/@eslint/config-array/node_modules/minimatch/LICENSE new file mode 100644 index 00000000..19129e31 --- /dev/null +++ b/node_modules/@eslint/config-array/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@eslint/config-array/node_modules/minimatch/README.md b/node_modules/@eslint/config-array/node_modules/minimatch/README.md new file mode 100644 index 00000000..33ede1d6 --- /dev/null +++ b/node_modules/@eslint/config-array/node_modules/minimatch/README.md @@ -0,0 +1,230 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` + +### allowWindowsEscape + +Windows path separator `\` is by default converted to `/`, which +prohibits the usage of `\` as a escape character. This flag skips that +behavior and allows using the escape character. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/@eslint/config-array/node_modules/minimatch/minimatch.js b/node_modules/@eslint/config-array/node_modules/minimatch/minimatch.js new file mode 100644 index 00000000..fda45ade --- /dev/null +++ b/node_modules/@eslint/config-array/node_modules/minimatch/minimatch.js @@ -0,0 +1,947 @@ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = (function () { try { return require('path') } catch (e) {}}()) || { + sep: '/' +} +minimatch.sep = path.sep + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + b = b || {} + var t = {} + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch + } + + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) + } + + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + } + + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) + } + + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } + + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + assertValidPattern(pattern) + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + assertValidPattern(pattern) + + if (!options) options = {} + + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + assertValidPattern(pattern) + + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } + + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + assertValidPattern(pattern) + + var options = this.options + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + /* istanbul ignore next */ + case '/': { + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + } + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '[': case '.': case '(': addPatternStart = true + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] + + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') partial = this.partial + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} diff --git a/node_modules/@eslint/config-array/node_modules/minimatch/package.json b/node_modules/@eslint/config-array/node_modules/minimatch/package.json new file mode 100644 index 00000000..566efdfe --- /dev/null +++ b/node_modules/@eslint/config-array/node_modules/minimatch/package.json @@ -0,0 +1,33 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "3.1.2", + "publishConfig": { + "tag": "v3-legacy" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "devDependencies": { + "tap": "^15.1.6" + }, + "license": "ISC", + "files": [ + "minimatch.js" + ] +} diff --git a/node_modules/@eslint/config-array/package.json b/node_modules/@eslint/config-array/package.json new file mode 100644 index 00000000..6bba334c --- /dev/null +++ b/node_modules/@eslint/config-array/package.json @@ -0,0 +1,67 @@ +{ + "name": "@eslint/config-array", + "version": "0.20.1", + "description": "General purpose glob-based configuration matching.", + "author": "Nicholas C. Zakas", + "type": "module", + "main": "dist/esm/index.js", + "types": "dist/esm/index.d.ts", + "exports": { + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + }, + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + } + }, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/rewrite.git", + "directory": "packages/config-array" + }, + "bugs": { + "url": "https://github.com/eslint/rewrite/issues" + }, + "homepage": "https://github.com/eslint/rewrite/tree/main/packages/config-array#readme", + "scripts": { + "build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js", + "build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts", + "build:std__path": "rollup -c rollup.std__path-config.js && node fix-std__path-imports", + "build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts && npm run build:std__path", + "test:jsr": "npx jsr@latest publish --dry-run", + "pretest": "npm run build", + "test": "mocha tests/", + "test:coverage": "c8 npm test" + }, + "keywords": [ + "configuration", + "configarray", + "config file" + ], + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.6", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "devDependencies": { + "@jsr/std__path": "^1.0.4", + "@types/minimatch": "^3.0.5", + "c8": "^9.1.0", + "mocha": "^10.4.0", + "rollup": "^4.16.2", + "rollup-plugin-copy": "^3.5.0", + "typescript": "^5.4.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/node_modules/@eslint/config-helpers/LICENSE b/node_modules/@eslint/config-helpers/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@eslint/config-helpers/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@eslint/config-helpers/README.md b/node_modules/@eslint/config-helpers/README.md new file mode 100644 index 00000000..0e4650de --- /dev/null +++ b/node_modules/@eslint/config-helpers/README.md @@ -0,0 +1,98 @@ +# @eslint/config-helpers + +## Description + +Helper utilities for creating ESLint configuration. + +## Installation + +For Node.js and compatible runtimes: + +```shell +npm install @eslint/config-helpers +# or +yarn add @eslint/config-helpers +# or +pnpm install @eslint/config-helpers +# or +bun add @eslint/config-helpers +``` + +For Deno: + +```shell +deno add @eslint/config-helpers +``` + +## Usage + +### `defineConfig()` + +The `defineConfig()` function allows you to specify an ESLint configuration with full type checking and additional capabilities, such as `extends`. Here's an example: + +```js +// eslint.config.js +import { defineConfig } from "@eslint/config-helpers"; +import js from "@eslint/js"; + +export default defineConfig([ + { + files: ["src/**/*.js"], + plugins: { js }, + extends: ["js/recommended"], + rules: { + semi: "error", + "prefer-const": "error", + }, + }, + { + files: ["test/**/*.js"], + rules: { + "no-console": "off", + }, + }, +]); +``` + +### `globalIgnores()` + +The `globalIgnores()` function allows you to specify patterns for files and directories that should be globally ignored by ESLint. This is useful for excluding files that you don't want to lint, such as build directories or third-party libraries. Here's an example: + +```js +// eslint.config.js +import { defineConfig, globalIgnores } from "@eslint/config-helpers"; + +export default defineConfig([ + { + files: ["src/**/*.js"], + rules: { + semi: "error", + "prefer-const": "error", + }, + }, + globalIgnores(["node_modules/", "dist/", "coverage/"]), +]); +``` + +## License + +Apache 2.0 + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/@eslint/config-helpers/dist/cjs/index.cjs b/node_modules/@eslint/config-helpers/dist/cjs/index.cjs new file mode 100644 index 00000000..ebb425c6 --- /dev/null +++ b/node_modules/@eslint/config-helpers/dist/cjs/index.cjs @@ -0,0 +1,571 @@ +'use strict'; + +/** + * @fileoverview defineConfig helper + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("eslint").Linter.Config} Config */ +/** @typedef {import("eslint").Linter.LegacyConfig} LegacyConfig */ +/** @typedef {import("eslint").ESLint.Plugin} Plugin */ +/** @typedef {import("eslint").Linter.RuleEntry} RuleEntry */ +/** @typedef {import("./types.ts").ExtendsElement} ExtendsElement */ +/** @typedef {import("./types.ts").SimpleExtendsElement} SimpleExtendsElement */ +/** @typedef {import("./types.ts").ConfigWithExtends} ConfigWithExtends */ +/** @typedef {import("./types.ts").InfiniteArray} InfiniteConfigArray */ +/** @typedef {import("./types.ts").ConfigWithExtendsArray} ConfigWithExtendsArray */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const eslintrcKeys = [ + "env", + "extends", + "globals", + "ignorePatterns", + "noInlineConfig", + "overrides", + "parser", + "parserOptions", + "reportUnusedDisableDirectives", + "root", +]; + +const allowedGlobalIgnoreKeys = new Set(["ignores", "name"]); + +/** + * Gets the name of a config object. + * @param {Config} config The config object. + * @param {string} indexPath The index path of the config object. + * @return {string} The name of the config object. + */ +function getConfigName(config, indexPath) { + if (config.name) { + return config.name; + } + + return `UserConfig${indexPath}`; +} + +/** + * Gets the name of an extension. + * @param {SimpleExtendsElement} extension The extension. + * @param {string} indexPath The index of the extension. + * @return {string} The name of the extension. + */ +function getExtensionName(extension, indexPath) { + if (typeof extension === "string") { + return extension; + } + + if (extension.name) { + return extension.name; + } + + return `ExtendedConfig${indexPath}`; +} + +/** + * Determines if a config object is a legacy config. + * @param {Config|LegacyConfig} config The config object to check. + * @return {config is LegacyConfig} `true` if the config object is a legacy config. + */ +function isLegacyConfig(config) { + for (const key of eslintrcKeys) { + if (key in config) { + return true; + } + } + + return false; +} + +/** + * Determines if a config object is a global ignores config. + * @param {Config} config The config object to check. + * @return {boolean} `true` if the config object is a global ignores config. + */ +function isGlobalIgnores(config) { + return Object.keys(config).every(key => allowedGlobalIgnoreKeys.has(key)); +} + +/** + * Parses a plugin member ID (rule, processor, etc.) and returns + * the namespace and member name. + * @param {string} id The ID to parse. + * @returns {{namespace:string, name:string}} The namespace and member name. + */ +function getPluginMember(id) { + const firstSlashIndex = id.indexOf("/"); + + if (firstSlashIndex === -1) { + return { namespace: "", name: id }; + } + + let namespace = id.slice(0, firstSlashIndex); + + /* + * Special cases: + * 1. The namespace is `@`, that means it's referring to the + * core plugin so `@` is the full namespace. + * 2. The namespace starts with `@`, that means it's referring to + * an npm scoped package. That means the namespace is the scope + * and the package name (i.e., `@eslint/core`). + */ + if (namespace[0] === "@" && namespace !== "@") { + const secondSlashIndex = id.indexOf("/", firstSlashIndex + 1); + if (secondSlashIndex !== -1) { + namespace = id.slice(0, secondSlashIndex); + return { namespace, name: id.slice(secondSlashIndex + 1) }; + } + } + + const name = id.slice(firstSlashIndex + 1); + + return { namespace, name }; +} + +/** + * Normalizes the plugin config by replacing the namespace with the plugin namespace. + * @param {string} userNamespace The namespace of the plugin. + * @param {Plugin} plugin The plugin config object. + * @param {Config} config The config object to normalize. + * @return {Config} The normalized config object. + */ +function normalizePluginConfig(userNamespace, plugin, config) { + const pluginNamespace = plugin.meta?.namespace; + + // don't do anything if the plugin doesn't have a namespace or rules + if ( + !pluginNamespace || + pluginNamespace === userNamespace || + (!config.rules && !config.processor && !config.language) + ) { + return config; + } + + const result = { ...config }; + + // update the rules + if (result.rules) { + const ruleIds = Object.keys(result.rules); + + /** @type {Record} */ + const newRules = {}; + + for (let i = 0; i < ruleIds.length; i++) { + const ruleId = ruleIds[i]; + const { namespace: ruleNamespace, name: ruleName } = + getPluginMember(ruleId); + + if (ruleNamespace === pluginNamespace) { + newRules[`${userNamespace}/${ruleName}`] = result.rules[ruleId]; + } else { + newRules[ruleId] = result.rules[ruleId]; + } + } + + result.rules = newRules; + } + + // update the processor + + if (typeof result.processor === "string") { + const { namespace: processorNamespace, name: processorName } = + getPluginMember(result.processor); + + if (processorNamespace) { + if (processorNamespace === pluginNamespace) { + result.processor = `${userNamespace}/${processorName}`; + } + } + } + + // update the language + if (typeof result.language === "string") { + const { namespace: languageNamespace, name: languageName } = + getPluginMember(result.language); + + if (languageNamespace === pluginNamespace) { + result.language = `${userNamespace}/${languageName}`; + } + } + + return result; +} + +/** + * Deeply normalizes a plugin config, traversing recursively into an arrays. + * @param {string} userPluginNamespace The namespace of the plugin. + * @param {Plugin} plugin The plugin object. + * @param {Config|LegacyConfig|(Config|LegacyConfig)[]} pluginConfig The plugin config to normalize. + * @param {string} pluginConfigName The name of the plugin config. + * @return {InfiniteConfigArray} The normalized plugin config. + * @throws {TypeError} If the plugin config is a legacy config. + */ +function deepNormalizePluginConfig( + userPluginNamespace, + plugin, + pluginConfig, + pluginConfigName, +) { + // if it's an array then it's definitely a new config + if (Array.isArray(pluginConfig)) { + return pluginConfig.map(pluginSubConfig => + deepNormalizePluginConfig( + userPluginNamespace, + plugin, + pluginSubConfig, + pluginConfigName, + ), + ); + } + + // if it's a legacy config, throw an error + if (isLegacyConfig(pluginConfig)) { + throw new TypeError( + `Plugin config "${pluginConfigName}" is an eslintrc config and cannot be used in this context.`, + ); + } + + return normalizePluginConfig(userPluginNamespace, plugin, pluginConfig); +} + +/** + * Finds a plugin config by name in the given config. + * @param {Config} config The config object. + * @param {string} pluginConfigName The name of the plugin config. + * @return {InfiniteConfigArray} The plugin config. + * @throws {TypeError} If the plugin config is not found or is a legacy config. + */ +function findPluginConfig(config, pluginConfigName) { + const { namespace: userPluginNamespace, name: configName } = + getPluginMember(pluginConfigName); + const plugin = config.plugins?.[userPluginNamespace]; + + if (!plugin) { + throw new TypeError(`Plugin "${userPluginNamespace}" not found.`); + } + + const directConfig = plugin.configs?.[configName]; + if (directConfig) { + // Arrays are always flat configs, and non-legacy configs can be used directly + if (Array.isArray(directConfig) || !isLegacyConfig(directConfig)) { + return deepNormalizePluginConfig( + userPluginNamespace, + plugin, + directConfig, + pluginConfigName, + ); + } + + // If it's a legacy config, look for the flat version + const flatConfig = plugin.configs?.[`flat/${configName}`]; + + if ( + flatConfig && + (Array.isArray(flatConfig) || !isLegacyConfig(flatConfig)) + ) { + return deepNormalizePluginConfig( + userPluginNamespace, + plugin, + flatConfig, + pluginConfigName, + ); + } + + throw new TypeError( + `Plugin config "${configName}" in plugin "${userPluginNamespace}" is an eslintrc config and cannot be used in this context.`, + ); + } + + throw new TypeError( + `Plugin config "${configName}" not found in plugin "${userPluginNamespace}".`, + ); +} + +/** + * Flattens an array while keeping track of the index path. + * @param {any[]} configList The array to traverse. + * @param {string} indexPath The index path of the value in a multidimensional array. + * @return {IterableIterator<{indexPath:string, value:any}>} The flattened list of values. + */ +function* flatTraverse(configList, indexPath = "") { + for (let i = 0; i < configList.length; i++) { + const newIndexPath = indexPath ? `${indexPath}[${i}]` : `[${i}]`; + + // if it's an array then traverse it as well + if (Array.isArray(configList[i])) { + yield* flatTraverse(configList[i], newIndexPath); + continue; + } + + yield { indexPath: newIndexPath, value: configList[i] }; + } +} + +/** + * Extends a list of config files by creating every combination of base and extension files. + * @param {(string|string[])[]} [baseFiles] The base files. + * @param {(string|string[])[]} [extensionFiles] The extension files. + * @return {(string|string[])[]} The extended files. + */ +function extendConfigFiles(baseFiles = [], extensionFiles = []) { + if (!extensionFiles.length) { + return baseFiles.concat(); + } + + if (!baseFiles.length) { + return extensionFiles.concat(); + } + + /** @type {(string|string[])[]} */ + const result = []; + + for (const baseFile of baseFiles) { + for (const extensionFile of extensionFiles) { + /* + * Each entry can be a string or array of strings. The end result + * needs to be an array of strings, so we need to be sure to include + * all of the items when there's an array. + */ + + const entry = []; + + if (Array.isArray(baseFile)) { + entry.push(...baseFile); + } else { + entry.push(baseFile); + } + + if (Array.isArray(extensionFile)) { + entry.push(...extensionFile); + } else { + entry.push(extensionFile); + } + + result.push(entry); + } + } + + return result; +} + +/** + * Extends a config object with another config object. + * @param {Config} baseConfig The base config object. + * @param {string} baseConfigName The name of the base config object. + * @param {Config} extension The extension config object. + * @param {string} extensionName The index of the extension config object. + * @return {Config} The extended config object. + */ +function extendConfig(baseConfig, baseConfigName, extension, extensionName) { + const result = { ...extension }; + + // for global ignores there is no further work to be done, we just keep everything + if (!isGlobalIgnores(extension)) { + // for files we need to create every combination of base and extension files + if (baseConfig.files) { + result.files = extendConfigFiles(baseConfig.files, extension.files); + } + + // for ignores we just concatenation the extension ignores onto the base ignores + if (baseConfig.ignores) { + result.ignores = baseConfig.ignores.concat(extension.ignores ?? []); + } + } + + result.name = `${baseConfigName} > ${extensionName}`; + + return result; +} + +/** + * Processes a list of extends elements. + * @param {ConfigWithExtends} config The config object. + * @param {WeakMap} configNames The map of config objects to their names. + * @return {Config[]} The flattened list of config objects. + * @throws {TypeError} If the `extends` property is not an array or if nested `extends` is found. + */ +function processExtends(config, configNames) { + if (!config.extends) { + return [config]; + } + + if (!Array.isArray(config.extends)) { + throw new TypeError("The `extends` property must be an array."); + } + + const { + /** @type {Config[]} */ + extends: extendsList, + + /** @type {Config} */ + ...configObject + } = config; + + const extensionNames = new WeakMap(); + + // replace strings with the actual configs + const objectExtends = extendsList.map(extendsElement => { + if (typeof extendsElement === "string") { + const pluginConfig = findPluginConfig(config, extendsElement); + + // assign names + if (Array.isArray(pluginConfig)) { + pluginConfig.forEach((pluginConfigElement, index) => { + extensionNames.set( + pluginConfigElement, + `${extendsElement}[${index}]`, + ); + }); + } else { + extensionNames.set(pluginConfig, extendsElement); + } + + return pluginConfig; + } + + return /** @type {Config} */ (extendsElement); + }); + + const result = []; + + for (const { indexPath, value: extendsElement } of flatTraverse( + objectExtends, + )) { + const extension = /** @type {Config} */ (extendsElement); + + if ("extends" in extension) { + throw new TypeError("Nested 'extends' is not allowed."); + } + + const baseConfigName = /** @type {string} */ (configNames.get(config)); + const extensionName = + extensionNames.get(extendsElement) ?? + getExtensionName(extendsElement, indexPath); + + result.push( + extendConfig( + configObject, + baseConfigName, + extension, + extensionName, + ), + ); + } + + /* + * If the base config object has only `ignores` and `extends`, then + * removing `extends` turns it into a global ignores, which is not what + * we want. So we need to check if the base config object is a global ignores + * and if so, we don't add it to the array. + * + * (The other option would be to add a `files` entry, but that would result + * in a config that didn't actually do anything because there are no + * other keys in the config.) + */ + if (!isGlobalIgnores(configObject)) { + result.push(configObject); + } + + return result.flat(); +} + +/** + * Processes a list of config objects and arrays. + * @param {ConfigWithExtends[]} configList The list of config objects and arrays. + * @param {WeakMap} configNames The map of config objects to their names. + * @return {Config[]} The flattened list of config objects. + */ +function processConfigList(configList, configNames) { + return configList.flatMap(config => processExtends(config, configNames)); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Helper function to define a config array. + * @param {ConfigWithExtendsArray} args The arguments to the function. + * @returns {Config[]} The config array. + * @throws {TypeError} If no arguments are provided or if an argument is not an object. + */ +function defineConfig(...args) { + const configNames = new WeakMap(); + const configs = []; + + if (args.length === 0) { + throw new TypeError("Expected one or more arguments."); + } + + // first flatten the list of configs and get the names + for (const { indexPath, value } of flatTraverse(args)) { + if (typeof value !== "object" || value === null) { + throw new TypeError( + `Expected an object but received ${String(value)}.`, + ); + } + + const config = /** @type {ConfigWithExtends} */ (value); + + // save config name for easy reference later + configNames.set(config, getConfigName(config, indexPath)); + configs.push(config); + } + + return processConfigList(configs, configNames); +} + +/** + * @fileoverview Global ignores helper function. + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +let globalIgnoreCount = 0; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Creates a global ignores config with the given patterns. + * @param {string[]} ignorePatterns The ignore patterns. + * @param {string} [name] The name of the global ignores config. + * @returns {Config} The global ignores config. + * @throws {TypeError} If ignorePatterns is not an array or if it is empty. + */ +function globalIgnores(ignorePatterns, name) { + if (!Array.isArray(ignorePatterns)) { + throw new TypeError("ignorePatterns must be an array"); + } + + if (ignorePatterns.length === 0) { + throw new TypeError("ignorePatterns must contain at least one pattern"); + } + + const id = globalIgnoreCount++; + + return { + name: name || `globalIgnores ${id}`, + ignores: ignorePatterns, + }; +} + +exports.defineConfig = defineConfig; +exports.globalIgnores = globalIgnores; diff --git a/node_modules/@eslint/config-helpers/dist/cjs/index.d.cts b/node_modules/@eslint/config-helpers/dist/cjs/index.d.cts new file mode 100644 index 00000000..b982e7d7 --- /dev/null +++ b/node_modules/@eslint/config-helpers/dist/cjs/index.d.cts @@ -0,0 +1,24 @@ +export type Config = import("eslint").Linter.Config; +export type LegacyConfig = import("eslint").Linter.LegacyConfig; +export type Plugin = import("eslint").ESLint.Plugin; +export type RuleEntry = import("eslint").Linter.RuleEntry; +export type ExtendsElement = import("./types.cts").ExtendsElement; +export type SimpleExtendsElement = import("./types.cts").SimpleExtendsElement; +export type ConfigWithExtends = import("./types.cts").ConfigWithExtends; +export type InfiniteConfigArray = import("./types.cts").InfiniteArray; +export type ConfigWithExtendsArray = import("./types.cts").ConfigWithExtendsArray; +/** + * Helper function to define a config array. + * @param {ConfigWithExtendsArray} args The arguments to the function. + * @returns {Config[]} The config array. + * @throws {TypeError} If no arguments are provided or if an argument is not an object. + */ +export function defineConfig(...args: ConfigWithExtendsArray): Config[]; +/** + * Creates a global ignores config with the given patterns. + * @param {string[]} ignorePatterns The ignore patterns. + * @param {string} [name] The name of the global ignores config. + * @returns {Config} The global ignores config. + * @throws {TypeError} If ignorePatterns is not an array or if it is empty. + */ +export function globalIgnores(ignorePatterns: string[], name?: string): Config; diff --git a/node_modules/@eslint/config-helpers/dist/cjs/types.cts b/node_modules/@eslint/config-helpers/dist/cjs/types.cts new file mode 100644 index 00000000..084f7b28 --- /dev/null +++ b/node_modules/@eslint/config-helpers/dist/cjs/types.cts @@ -0,0 +1,31 @@ +/** + * @fileoverview Types for this package. + */ + +import type { Linter } from "eslint"; + +/** + * Infinite array type. + */ +export type InfiniteArray = T | InfiniteArray[]; + +/** + * The type of array element in the `extends` property after flattening. + */ +export type SimpleExtendsElement = string | Linter.Config; + +/** + * The type of array element in the `extends` property before flattening. + */ +export type ExtendsElement = + | SimpleExtendsElement + | InfiniteArray; + +/** + * Config with extends. Valid only inside of `defineConfig()`. + */ +export interface ConfigWithExtends extends Linter.Config { + extends?: ExtendsElement[]; +} + +export type ConfigWithExtendsArray = InfiniteArray[]; diff --git a/node_modules/@eslint/config-helpers/dist/esm/index.d.ts b/node_modules/@eslint/config-helpers/dist/esm/index.d.ts new file mode 100644 index 00000000..71aa428d --- /dev/null +++ b/node_modules/@eslint/config-helpers/dist/esm/index.d.ts @@ -0,0 +1,24 @@ +export type Config = import("eslint").Linter.Config; +export type LegacyConfig = import("eslint").Linter.LegacyConfig; +export type Plugin = import("eslint").ESLint.Plugin; +export type RuleEntry = import("eslint").Linter.RuleEntry; +export type ExtendsElement = import("./types.ts").ExtendsElement; +export type SimpleExtendsElement = import("./types.ts").SimpleExtendsElement; +export type ConfigWithExtends = import("./types.ts").ConfigWithExtends; +export type InfiniteConfigArray = import("./types.ts").InfiniteArray; +export type ConfigWithExtendsArray = import("./types.ts").ConfigWithExtendsArray; +/** + * Helper function to define a config array. + * @param {ConfigWithExtendsArray} args The arguments to the function. + * @returns {Config[]} The config array. + * @throws {TypeError} If no arguments are provided or if an argument is not an object. + */ +export function defineConfig(...args: ConfigWithExtendsArray): Config[]; +/** + * Creates a global ignores config with the given patterns. + * @param {string[]} ignorePatterns The ignore patterns. + * @param {string} [name] The name of the global ignores config. + * @returns {Config} The global ignores config. + * @throws {TypeError} If ignorePatterns is not an array or if it is empty. + */ +export function globalIgnores(ignorePatterns: string[], name?: string): Config; diff --git a/node_modules/@eslint/config-helpers/dist/esm/index.js b/node_modules/@eslint/config-helpers/dist/esm/index.js new file mode 100644 index 00000000..1d7a76e1 --- /dev/null +++ b/node_modules/@eslint/config-helpers/dist/esm/index.js @@ -0,0 +1,569 @@ +// @ts-self-types="./index.d.ts" +/** + * @fileoverview defineConfig helper + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("eslint").Linter.Config} Config */ +/** @typedef {import("eslint").Linter.LegacyConfig} LegacyConfig */ +/** @typedef {import("eslint").ESLint.Plugin} Plugin */ +/** @typedef {import("eslint").Linter.RuleEntry} RuleEntry */ +/** @typedef {import("./types.ts").ExtendsElement} ExtendsElement */ +/** @typedef {import("./types.ts").SimpleExtendsElement} SimpleExtendsElement */ +/** @typedef {import("./types.ts").ConfigWithExtends} ConfigWithExtends */ +/** @typedef {import("./types.ts").InfiniteArray} InfiniteConfigArray */ +/** @typedef {import("./types.ts").ConfigWithExtendsArray} ConfigWithExtendsArray */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const eslintrcKeys = [ + "env", + "extends", + "globals", + "ignorePatterns", + "noInlineConfig", + "overrides", + "parser", + "parserOptions", + "reportUnusedDisableDirectives", + "root", +]; + +const allowedGlobalIgnoreKeys = new Set(["ignores", "name"]); + +/** + * Gets the name of a config object. + * @param {Config} config The config object. + * @param {string} indexPath The index path of the config object. + * @return {string} The name of the config object. + */ +function getConfigName(config, indexPath) { + if (config.name) { + return config.name; + } + + return `UserConfig${indexPath}`; +} + +/** + * Gets the name of an extension. + * @param {SimpleExtendsElement} extension The extension. + * @param {string} indexPath The index of the extension. + * @return {string} The name of the extension. + */ +function getExtensionName(extension, indexPath) { + if (typeof extension === "string") { + return extension; + } + + if (extension.name) { + return extension.name; + } + + return `ExtendedConfig${indexPath}`; +} + +/** + * Determines if a config object is a legacy config. + * @param {Config|LegacyConfig} config The config object to check. + * @return {config is LegacyConfig} `true` if the config object is a legacy config. + */ +function isLegacyConfig(config) { + for (const key of eslintrcKeys) { + if (key in config) { + return true; + } + } + + return false; +} + +/** + * Determines if a config object is a global ignores config. + * @param {Config} config The config object to check. + * @return {boolean} `true` if the config object is a global ignores config. + */ +function isGlobalIgnores(config) { + return Object.keys(config).every(key => allowedGlobalIgnoreKeys.has(key)); +} + +/** + * Parses a plugin member ID (rule, processor, etc.) and returns + * the namespace and member name. + * @param {string} id The ID to parse. + * @returns {{namespace:string, name:string}} The namespace and member name. + */ +function getPluginMember(id) { + const firstSlashIndex = id.indexOf("/"); + + if (firstSlashIndex === -1) { + return { namespace: "", name: id }; + } + + let namespace = id.slice(0, firstSlashIndex); + + /* + * Special cases: + * 1. The namespace is `@`, that means it's referring to the + * core plugin so `@` is the full namespace. + * 2. The namespace starts with `@`, that means it's referring to + * an npm scoped package. That means the namespace is the scope + * and the package name (i.e., `@eslint/core`). + */ + if (namespace[0] === "@" && namespace !== "@") { + const secondSlashIndex = id.indexOf("/", firstSlashIndex + 1); + if (secondSlashIndex !== -1) { + namespace = id.slice(0, secondSlashIndex); + return { namespace, name: id.slice(secondSlashIndex + 1) }; + } + } + + const name = id.slice(firstSlashIndex + 1); + + return { namespace, name }; +} + +/** + * Normalizes the plugin config by replacing the namespace with the plugin namespace. + * @param {string} userNamespace The namespace of the plugin. + * @param {Plugin} plugin The plugin config object. + * @param {Config} config The config object to normalize. + * @return {Config} The normalized config object. + */ +function normalizePluginConfig(userNamespace, plugin, config) { + const pluginNamespace = plugin.meta?.namespace; + + // don't do anything if the plugin doesn't have a namespace or rules + if ( + !pluginNamespace || + pluginNamespace === userNamespace || + (!config.rules && !config.processor && !config.language) + ) { + return config; + } + + const result = { ...config }; + + // update the rules + if (result.rules) { + const ruleIds = Object.keys(result.rules); + + /** @type {Record} */ + const newRules = {}; + + for (let i = 0; i < ruleIds.length; i++) { + const ruleId = ruleIds[i]; + const { namespace: ruleNamespace, name: ruleName } = + getPluginMember(ruleId); + + if (ruleNamespace === pluginNamespace) { + newRules[`${userNamespace}/${ruleName}`] = result.rules[ruleId]; + } else { + newRules[ruleId] = result.rules[ruleId]; + } + } + + result.rules = newRules; + } + + // update the processor + + if (typeof result.processor === "string") { + const { namespace: processorNamespace, name: processorName } = + getPluginMember(result.processor); + + if (processorNamespace) { + if (processorNamespace === pluginNamespace) { + result.processor = `${userNamespace}/${processorName}`; + } + } + } + + // update the language + if (typeof result.language === "string") { + const { namespace: languageNamespace, name: languageName } = + getPluginMember(result.language); + + if (languageNamespace === pluginNamespace) { + result.language = `${userNamespace}/${languageName}`; + } + } + + return result; +} + +/** + * Deeply normalizes a plugin config, traversing recursively into an arrays. + * @param {string} userPluginNamespace The namespace of the plugin. + * @param {Plugin} plugin The plugin object. + * @param {Config|LegacyConfig|(Config|LegacyConfig)[]} pluginConfig The plugin config to normalize. + * @param {string} pluginConfigName The name of the plugin config. + * @return {InfiniteConfigArray} The normalized plugin config. + * @throws {TypeError} If the plugin config is a legacy config. + */ +function deepNormalizePluginConfig( + userPluginNamespace, + plugin, + pluginConfig, + pluginConfigName, +) { + // if it's an array then it's definitely a new config + if (Array.isArray(pluginConfig)) { + return pluginConfig.map(pluginSubConfig => + deepNormalizePluginConfig( + userPluginNamespace, + plugin, + pluginSubConfig, + pluginConfigName, + ), + ); + } + + // if it's a legacy config, throw an error + if (isLegacyConfig(pluginConfig)) { + throw new TypeError( + `Plugin config "${pluginConfigName}" is an eslintrc config and cannot be used in this context.`, + ); + } + + return normalizePluginConfig(userPluginNamespace, plugin, pluginConfig); +} + +/** + * Finds a plugin config by name in the given config. + * @param {Config} config The config object. + * @param {string} pluginConfigName The name of the plugin config. + * @return {InfiniteConfigArray} The plugin config. + * @throws {TypeError} If the plugin config is not found or is a legacy config. + */ +function findPluginConfig(config, pluginConfigName) { + const { namespace: userPluginNamespace, name: configName } = + getPluginMember(pluginConfigName); + const plugin = config.plugins?.[userPluginNamespace]; + + if (!plugin) { + throw new TypeError(`Plugin "${userPluginNamespace}" not found.`); + } + + const directConfig = plugin.configs?.[configName]; + if (directConfig) { + // Arrays are always flat configs, and non-legacy configs can be used directly + if (Array.isArray(directConfig) || !isLegacyConfig(directConfig)) { + return deepNormalizePluginConfig( + userPluginNamespace, + plugin, + directConfig, + pluginConfigName, + ); + } + + // If it's a legacy config, look for the flat version + const flatConfig = plugin.configs?.[`flat/${configName}`]; + + if ( + flatConfig && + (Array.isArray(flatConfig) || !isLegacyConfig(flatConfig)) + ) { + return deepNormalizePluginConfig( + userPluginNamespace, + plugin, + flatConfig, + pluginConfigName, + ); + } + + throw new TypeError( + `Plugin config "${configName}" in plugin "${userPluginNamespace}" is an eslintrc config and cannot be used in this context.`, + ); + } + + throw new TypeError( + `Plugin config "${configName}" not found in plugin "${userPluginNamespace}".`, + ); +} + +/** + * Flattens an array while keeping track of the index path. + * @param {any[]} configList The array to traverse. + * @param {string} indexPath The index path of the value in a multidimensional array. + * @return {IterableIterator<{indexPath:string, value:any}>} The flattened list of values. + */ +function* flatTraverse(configList, indexPath = "") { + for (let i = 0; i < configList.length; i++) { + const newIndexPath = indexPath ? `${indexPath}[${i}]` : `[${i}]`; + + // if it's an array then traverse it as well + if (Array.isArray(configList[i])) { + yield* flatTraverse(configList[i], newIndexPath); + continue; + } + + yield { indexPath: newIndexPath, value: configList[i] }; + } +} + +/** + * Extends a list of config files by creating every combination of base and extension files. + * @param {(string|string[])[]} [baseFiles] The base files. + * @param {(string|string[])[]} [extensionFiles] The extension files. + * @return {(string|string[])[]} The extended files. + */ +function extendConfigFiles(baseFiles = [], extensionFiles = []) { + if (!extensionFiles.length) { + return baseFiles.concat(); + } + + if (!baseFiles.length) { + return extensionFiles.concat(); + } + + /** @type {(string|string[])[]} */ + const result = []; + + for (const baseFile of baseFiles) { + for (const extensionFile of extensionFiles) { + /* + * Each entry can be a string or array of strings. The end result + * needs to be an array of strings, so we need to be sure to include + * all of the items when there's an array. + */ + + const entry = []; + + if (Array.isArray(baseFile)) { + entry.push(...baseFile); + } else { + entry.push(baseFile); + } + + if (Array.isArray(extensionFile)) { + entry.push(...extensionFile); + } else { + entry.push(extensionFile); + } + + result.push(entry); + } + } + + return result; +} + +/** + * Extends a config object with another config object. + * @param {Config} baseConfig The base config object. + * @param {string} baseConfigName The name of the base config object. + * @param {Config} extension The extension config object. + * @param {string} extensionName The index of the extension config object. + * @return {Config} The extended config object. + */ +function extendConfig(baseConfig, baseConfigName, extension, extensionName) { + const result = { ...extension }; + + // for global ignores there is no further work to be done, we just keep everything + if (!isGlobalIgnores(extension)) { + // for files we need to create every combination of base and extension files + if (baseConfig.files) { + result.files = extendConfigFiles(baseConfig.files, extension.files); + } + + // for ignores we just concatenation the extension ignores onto the base ignores + if (baseConfig.ignores) { + result.ignores = baseConfig.ignores.concat(extension.ignores ?? []); + } + } + + result.name = `${baseConfigName} > ${extensionName}`; + + return result; +} + +/** + * Processes a list of extends elements. + * @param {ConfigWithExtends} config The config object. + * @param {WeakMap} configNames The map of config objects to their names. + * @return {Config[]} The flattened list of config objects. + * @throws {TypeError} If the `extends` property is not an array or if nested `extends` is found. + */ +function processExtends(config, configNames) { + if (!config.extends) { + return [config]; + } + + if (!Array.isArray(config.extends)) { + throw new TypeError("The `extends` property must be an array."); + } + + const { + /** @type {Config[]} */ + extends: extendsList, + + /** @type {Config} */ + ...configObject + } = config; + + const extensionNames = new WeakMap(); + + // replace strings with the actual configs + const objectExtends = extendsList.map(extendsElement => { + if (typeof extendsElement === "string") { + const pluginConfig = findPluginConfig(config, extendsElement); + + // assign names + if (Array.isArray(pluginConfig)) { + pluginConfig.forEach((pluginConfigElement, index) => { + extensionNames.set( + pluginConfigElement, + `${extendsElement}[${index}]`, + ); + }); + } else { + extensionNames.set(pluginConfig, extendsElement); + } + + return pluginConfig; + } + + return /** @type {Config} */ (extendsElement); + }); + + const result = []; + + for (const { indexPath, value: extendsElement } of flatTraverse( + objectExtends, + )) { + const extension = /** @type {Config} */ (extendsElement); + + if ("extends" in extension) { + throw new TypeError("Nested 'extends' is not allowed."); + } + + const baseConfigName = /** @type {string} */ (configNames.get(config)); + const extensionName = + extensionNames.get(extendsElement) ?? + getExtensionName(extendsElement, indexPath); + + result.push( + extendConfig( + configObject, + baseConfigName, + extension, + extensionName, + ), + ); + } + + /* + * If the base config object has only `ignores` and `extends`, then + * removing `extends` turns it into a global ignores, which is not what + * we want. So we need to check if the base config object is a global ignores + * and if so, we don't add it to the array. + * + * (The other option would be to add a `files` entry, but that would result + * in a config that didn't actually do anything because there are no + * other keys in the config.) + */ + if (!isGlobalIgnores(configObject)) { + result.push(configObject); + } + + return result.flat(); +} + +/** + * Processes a list of config objects and arrays. + * @param {ConfigWithExtends[]} configList The list of config objects and arrays. + * @param {WeakMap} configNames The map of config objects to their names. + * @return {Config[]} The flattened list of config objects. + */ +function processConfigList(configList, configNames) { + return configList.flatMap(config => processExtends(config, configNames)); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Helper function to define a config array. + * @param {ConfigWithExtendsArray} args The arguments to the function. + * @returns {Config[]} The config array. + * @throws {TypeError} If no arguments are provided or if an argument is not an object. + */ +function defineConfig(...args) { + const configNames = new WeakMap(); + const configs = []; + + if (args.length === 0) { + throw new TypeError("Expected one or more arguments."); + } + + // first flatten the list of configs and get the names + for (const { indexPath, value } of flatTraverse(args)) { + if (typeof value !== "object" || value === null) { + throw new TypeError( + `Expected an object but received ${String(value)}.`, + ); + } + + const config = /** @type {ConfigWithExtends} */ (value); + + // save config name for easy reference later + configNames.set(config, getConfigName(config, indexPath)); + configs.push(config); + } + + return processConfigList(configs, configNames); +} + +/** + * @fileoverview Global ignores helper function. + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +let globalIgnoreCount = 0; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Creates a global ignores config with the given patterns. + * @param {string[]} ignorePatterns The ignore patterns. + * @param {string} [name] The name of the global ignores config. + * @returns {Config} The global ignores config. + * @throws {TypeError} If ignorePatterns is not an array or if it is empty. + */ +function globalIgnores(ignorePatterns, name) { + if (!Array.isArray(ignorePatterns)) { + throw new TypeError("ignorePatterns must be an array"); + } + + if (ignorePatterns.length === 0) { + throw new TypeError("ignorePatterns must contain at least one pattern"); + } + + const id = globalIgnoreCount++; + + return { + name: name || `globalIgnores ${id}`, + ignores: ignorePatterns, + }; +} + +export { defineConfig, globalIgnores }; diff --git a/node_modules/@eslint/config-helpers/dist/esm/types.d.ts b/node_modules/@eslint/config-helpers/dist/esm/types.d.ts new file mode 100644 index 00000000..b1117ad6 --- /dev/null +++ b/node_modules/@eslint/config-helpers/dist/esm/types.d.ts @@ -0,0 +1,23 @@ +/** + * @fileoverview Types for this package. + */ +import type { Linter } from "eslint"; +/** + * Infinite array type. + */ +export type InfiniteArray = T | InfiniteArray[]; +/** + * The type of array element in the `extends` property after flattening. + */ +export type SimpleExtendsElement = string | Linter.Config; +/** + * The type of array element in the `extends` property before flattening. + */ +export type ExtendsElement = SimpleExtendsElement | InfiniteArray; +/** + * Config with extends. Valid only inside of `defineConfig()`. + */ +export interface ConfigWithExtends extends Linter.Config { + extends?: ExtendsElement[]; +} +export type ConfigWithExtendsArray = InfiniteArray[]; diff --git a/node_modules/@eslint/config-helpers/dist/esm/types.ts b/node_modules/@eslint/config-helpers/dist/esm/types.ts new file mode 100644 index 00000000..084f7b28 --- /dev/null +++ b/node_modules/@eslint/config-helpers/dist/esm/types.ts @@ -0,0 +1,31 @@ +/** + * @fileoverview Types for this package. + */ + +import type { Linter } from "eslint"; + +/** + * Infinite array type. + */ +export type InfiniteArray = T | InfiniteArray[]; + +/** + * The type of array element in the `extends` property after flattening. + */ +export type SimpleExtendsElement = string | Linter.Config; + +/** + * The type of array element in the `extends` property before flattening. + */ +export type ExtendsElement = + | SimpleExtendsElement + | InfiniteArray; + +/** + * Config with extends. Valid only inside of `defineConfig()`. + */ +export interface ConfigWithExtends extends Linter.Config { + extends?: ExtendsElement[]; +} + +export type ConfigWithExtendsArray = InfiniteArray[]; diff --git a/node_modules/@eslint/config-helpers/package.json b/node_modules/@eslint/config-helpers/package.json new file mode 100644 index 00000000..384da890 --- /dev/null +++ b/node_modules/@eslint/config-helpers/package.json @@ -0,0 +1,61 @@ +{ + "name": "@eslint/config-helpers", + "version": "0.2.3", + "description": "Helper utilities for creating ESLint configuration", + "type": "module", + "main": "dist/esm/index.js", + "types": "dist/esm/index.d.ts", + "exports": { + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + }, + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + } + }, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "directories": { + "test": "tests" + }, + "scripts": { + "build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js", + "build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts", + "build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts", + "test:jsr": "npx jsr@latest publish --dry-run", + "test": "mocha tests/*.js", + "test:coverage": "c8 npm test", + "test:types": "tsc -p tests/types/tsconfig.json" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/rewrite.git", + "directory": "packages/config-helpers" + }, + "keywords": [ + "eslint" + ], + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/rewrite/issues" + }, + "homepage": "https://github.com/eslint/rewrite/tree/main/packages/config-helpers#readme", + "devDependencies": { + "@eslint/core": "^0.15.0", + "c8": "^9.1.0", + "eslint": "^9.27.0", + "mocha": "^10.4.0", + "rollup": "^4.16.2", + "rollup-plugin-copy": "^3.5.0", + "typescript": "^5.4.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/node_modules/@eslint/core/LICENSE b/node_modules/@eslint/core/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@eslint/core/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@eslint/core/README.md b/node_modules/@eslint/core/README.md new file mode 100644 index 00000000..a288c3c5 --- /dev/null +++ b/node_modules/@eslint/core/README.md @@ -0,0 +1,30 @@ +# ESLint Core + +## Overview + +This package is the future home of the rewritten, runtime-agnostic ESLint core. + +Right now, it exports the core types necessary to implement language plugins. + +## License + +Apache 2.0 + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express

Bronze Sponsors

+

Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/@eslint/core/dist/cjs/types.d.cts b/node_modules/@eslint/core/dist/cjs/types.d.cts new file mode 100644 index 00000000..247084ce --- /dev/null +++ b/node_modules/@eslint/core/dist/cjs/types.d.cts @@ -0,0 +1,838 @@ +/** + * @fileoverview Shared types for ESLint Core. + */ +import type { JSONSchema4 } from "json-schema"; +/** + * Represents an error inside of a file. + */ +export interface FileError { + message: string; + line: number; + column: number; + endLine?: number; + endColumn?: number; +} +/** + * Represents a problem found in a file. + */ +export interface FileProblem { + ruleId: string | null; + message: string; + loc: SourceLocation; +} +/** + * Represents the start and end coordinates of a node inside the source. + */ +export interface SourceLocation { + start: Position; + end: Position; +} +/** + * Represents the start and end coordinates of a node inside the source with an offset. + */ +export interface SourceLocationWithOffset { + start: PositionWithOffset; + end: PositionWithOffset; +} +/** + * Represents a location coordinate inside the source. ESLint-style formats + * have just `line` and `column` while others may have `offset` as well. + */ +export interface Position { + line: number; + column: number; +} +/** + * Represents a location coordinate inside the source with an offset. + */ +export interface PositionWithOffset extends Position { + offset: number; +} +/** + * Represents a range of characters in the source. + */ +export type SourceRange = [number, number]; +/** + * What the rule is responsible for finding: + * - `problem` means the rule has noticed a potential error. + * - `suggestion` means the rule suggests an alternate or better approach. + * - `layout` means the rule is looking at spacing, indentation, etc. + */ +export type RuleType = "problem" | "suggestion" | "layout"; +/** + * The type of fix the rule can provide: + * - `code` means the rule can fix syntax. + * - `whitespace` means the rule can fix spacing and indentation. + */ +export type RuleFixType = "code" | "whitespace"; +/** + * An object containing visitor information for a rule. Each method is either the + * name of a node type or a selector, or is a method that will be called at specific + * times during the traversal. + */ +export type RuleVisitor = Record void) | undefined>; +/** + * Rule meta information used for documentation. + */ +export interface RulesMetaDocs { + /** + * A short description of the rule. + */ + description?: string | undefined; + /** + * The URL to the documentation for the rule. + */ + url?: string | undefined; + /** + * The category the rule falls under. + * @deprecated No longer used. + */ + category?: string | undefined; + /** + * Indicates if the rule is generally recommended for all users. + */ + recommended?: boolean | undefined; + /** + * Indicates if the rule is frozen (no longer accepting feature requests). + */ + frozen?: boolean | undefined; +} +/** + * Meta information about a rule. + */ +export interface RulesMeta { + /** + * Properties that are used when documenting the rule. + */ + docs?: (RulesMetaDocs & ExtRuleDocs) | undefined; + /** + * The type of rule. + */ + type?: RuleType | undefined; + /** + * The schema for the rule options. Required if the rule has options. + */ + schema?: JSONSchema4 | JSONSchema4[] | false | undefined; + /** + * Any default options to be recursively merged on top of any user-provided options. + **/ + defaultOptions?: RuleOptions; + /** + * The messages that the rule can report. + */ + messages?: Record; + /** + * Indicates whether the rule has been deprecated or provides additional metadata about the deprecation. Omit if not deprecated. + */ + deprecated?: boolean | DeprecatedInfo | undefined; + /** + * @deprecated Use deprecated.replacedBy instead. + * The name of the rule(s) this rule was replaced by, if it was deprecated. + */ + replacedBy?: readonly string[] | undefined; + /** + * Indicates if the rule is fixable, and if so, what type of fix it provides. + */ + fixable?: RuleFixType | undefined; + /** + * Indicates if the rule may provide suggestions. + */ + hasSuggestions?: boolean | undefined; + /** + * The language the rule is intended to lint. + */ + language?: string; + /** + * The dialects of `language` that the rule is intended to lint. + */ + dialects?: string[]; +} +/** + * Provides additional metadata about a deprecation. + */ +export interface DeprecatedInfo { + /** + * General message presented to the user, e.g. for the key rule why the rule + * is deprecated or for info how to replace the rule. + */ + message?: string; + /** + * URL to more information about this deprecation in general. + */ + url?: string; + /** + * An empty array explicitly states that there is no replacement. + */ + replacedBy?: ReplacedByInfo[]; + /** + * The package version since when the rule is deprecated (should use full + * semver without a leading "v"). + */ + deprecatedSince?: string; + /** + * The estimated version when the rule is removed (probably the next major + * version). null means the rule is "frozen" (will be available but will not + * be changed). + */ + availableUntil?: string | null; +} +/** + * Provides metadata about a replacement + */ +export interface ReplacedByInfo { + /** + * General message presented to the user, e.g. how to replace the rule + */ + message?: string; + /** + * URL to more information about this replacement in general + */ + url?: string; + /** + * Name should be "eslint" if the replacement is an ESLint core rule. Omit + * the property if the replacement is in the same plugin. + */ + plugin?: ExternalSpecifier; + /** + * Name and documentation of the replacement rule + */ + rule?: ExternalSpecifier; +} +/** + * Specifies the name and url of an external resource. At least one property + * should be set. + */ +export interface ExternalSpecifier { + /** + * Name of the referenced plugin / rule. + */ + name?: string; + /** + * URL pointing to documentation for the plugin / rule. + */ + url?: string; +} +/** + * Generic type for `RuleContext`. + */ +export interface RuleContextTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RuleOptions: unknown[]; + Node: unknown; + MessageIds: string; +} +/** + * Represents the context object that is passed to a rule. This object contains + * information about the current state of the linting process and is the rule's + * view into the outside world. + */ +export interface RuleContext { + /** + * The current working directory for the session. + */ + cwd: string; + /** + * Returns the current working directory for the session. + * @deprecated Use `cwd` instead. + */ + getCwd(): string; + /** + * The filename of the file being linted. + */ + filename: string; + /** + * Returns the filename of the file being linted. + * @deprecated Use `filename` instead. + */ + getFilename(): string; + /** + * The physical filename of the file being linted. + */ + physicalFilename: string; + /** + * Returns the physical filename of the file being linted. + * @deprecated Use `physicalFilename` instead. + */ + getPhysicalFilename(): string; + /** + * The source code object that the rule is running on. + */ + sourceCode: Options["Code"]; + /** + * Returns the source code object that the rule is running on. + * @deprecated Use `sourceCode` instead. + */ + getSourceCode(): Options["Code"]; + /** + * Shared settings for the configuration. + */ + settings: SettingsConfig; + /** + * Parser-specific options for the configuration. + * @deprecated Use `languageOptions.parserOptions` instead. + */ + parserOptions: Record; + /** + * The language options for the configuration. + */ + languageOptions: Options["LangOptions"]; + /** + * The CommonJS path to the parser used while parsing this file. + * @deprecated No longer used. + */ + parserPath: string | undefined; + /** + * The rule ID. + */ + id: string; + /** + * The rule's configured options. + */ + options: Options["RuleOptions"]; + /** + * The report function that the rule should use to report problems. + * @param violation The violation to report. + */ + report(violation: ViolationReport): void; +} +/** + * Manager of text edits for a rule fix. + */ +export interface RuleTextEditor { + /** + * Inserts text after the specified node or token. + * @param syntaxElement The node or token to insert after. + * @param text The edit to insert after the node or token. + */ + insertTextAfter(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Inserts text after the specified range. + * @param range The range to insert after. + * @param text The edit to insert after the range. + */ + insertTextAfterRange(range: SourceRange, text: string): RuleTextEdit; + /** + * Inserts text before the specified node or token. + * @param syntaxElement A syntax element with location information to insert before. + * @param text The edit to insert before the node or token. + */ + insertTextBefore(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Inserts text before the specified range. + * @param range The range to insert before. + * @param text The edit to insert before the range. + */ + insertTextBeforeRange(range: SourceRange, text: string): RuleTextEdit; + /** + * Removes the specified node or token. + * @param syntaxElement A syntax element with location information to remove. + * @returns The edit to remove the node or token. + */ + remove(syntaxElement: EditableSyntaxElement): RuleTextEdit; + /** + * Removes the specified range. + * @param range The range to remove. + * @returns The edit to remove the range. + */ + removeRange(range: SourceRange): RuleTextEdit; + /** + * Replaces the specified node or token with the given text. + * @param syntaxElement A syntax element with location information to replace. + * @param text The text to replace the node or token with. + * @returns The edit to replace the node or token. + */ + replaceText(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Replaces the specified range with the given text. + * @param range The range to replace. + * @param text The text to replace the range with. + * @returns The edit to replace the range. + */ + replaceTextRange(range: SourceRange, text: string): RuleTextEdit; +} +/** + * Represents a fix for a rule violation implemented as a text edit. + */ +export interface RuleTextEdit { + /** + * The range to replace. + */ + range: SourceRange; + /** + * The text to insert. + */ + text: string; +} +/** + * Fixes a violation. + * @param fixer The text editor to apply the fix. + * @returns The fix(es) for the violation. + */ +type RuleFixer = (fixer: RuleTextEditor) => RuleTextEdit | Iterable | null; +interface ViolationReportBase { + /** + * The type of node that the violation is for. + * @deprecated May be removed in the future. + */ + nodeType?: string | undefined; + /** + * The data to insert into the message. + */ + data?: Record | undefined; + /** + * The fix to be applied for the violation. + */ + fix?: RuleFixer | null | undefined; + /** + * An array of suggested fixes for the problem. These fixes may change the + * behavior of the code, so they are not applied automatically. + */ + suggest?: SuggestedEdit[] | null | undefined; +} +type ViolationMessage = { + message: string; +} | { + messageId: MessageIds; +}; +type ViolationLocation = { + loc: SourceLocation | Position; +} | { + node: Node; +}; +export type ViolationReport = ViolationReportBase & ViolationMessage & ViolationLocation; +interface SuggestedEditBase { + /** + * The data to insert into the message. + */ + data?: Record | undefined; + /** + * The fix to be applied for the suggestion. + */ + fix?: RuleFixer | null | undefined; +} +type SuggestionMessage = { + desc: string; +} | { + messageId: string; +}; +/** + * A suggested edit for a rule violation. + */ +export type SuggestedEdit = SuggestedEditBase & SuggestionMessage; +/** + * Generic options for the `RuleDefinition` type. + */ +export interface RuleDefinitionTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RuleOptions: unknown[]; + Visitor: RuleVisitor; + Node: unknown; + MessageIds: string; + ExtRuleDocs: unknown; +} +/** + * The definition of an ESLint rule. + */ +export interface RuleDefinition { + /** + * The meta information for the rule. + */ + meta?: RulesMeta; + /** + * Creates the visitor that ESLint uses to apply the rule during traversal. + * @param context The rule context. + * @returns The rule visitor. + */ + create(context: RuleContext<{ + LangOptions: Options["LangOptions"]; + Code: Options["Code"]; + RuleOptions: Options["RuleOptions"]; + Node: Options["Node"]; + MessageIds: Options["MessageIds"]; + }>): Options["Visitor"]; +} +/** + * Defaults for non-language-related `RuleDefinition` options. + */ +export interface CustomRuleTypeDefinitions { + RuleOptions: unknown[]; + MessageIds: string; + ExtRuleDocs: Record; +} +/** + * A helper type to define language specific specializations of the `RuleDefinition` type. + * + * @example + * ```ts + * type YourRuleDefinition< + * Options extends Partial = {}, + * > = CustomRuleDefinitionType< + * { + * LangOptions: YourLanguageOptions; + * Code: YourSourceCode; + * Visitor: YourRuleVisitor; + * Node: YourNode; + * }, + * Options + * >; + * ``` + */ +export type CustomRuleDefinitionType, Options extends Partial> = RuleDefinition>>; +/** + * The human readable severity level used in a configuration. + */ +export type SeverityName = "off" | "warn" | "error"; +/** + * The numeric severity level for a rule. + * + * - `0` means off. + * - `1` means warn. + * - `2` means error. + */ +export type SeverityLevel = 0 | 1 | 2; +/** + * The severity of a rule in a configuration. + */ +export type Severity = SeverityName | SeverityLevel; +/** + * Represents the configuration options for the core linter. + */ +export interface LinterOptionsConfig { + /** + * Indicates whether or not inline configuration is evaluated. + */ + noInlineConfig?: boolean; + /** + * Indicates what to do when an unused disable directive is found. + */ + reportUnusedDisableDirectives?: boolean | Severity; +} +/** + * Shared settings that are accessible from within plugins. + */ +export type SettingsConfig = Record; +/** + * The configuration for a rule. + */ +export type RuleConfig = Severity | [Severity, ...unknown[]]; +/** + * A collection of rules and their configurations. + */ +export type RulesConfig = Record; +/** + * Generic options for the `Language` type. + */ +export interface LanguageTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RootNode: unknown; + Node: unknown; +} +/** + * Represents a plugin language. + */ +export interface Language { + /** + * Indicates how ESLint should read the file. + */ + fileType: "text"; + /** + * First line number returned from the parser (text mode only). + */ + lineStart: 0 | 1; + /** + * First column number returned from the parser (text mode only). + */ + columnStart: 0 | 1; + /** + * The property to read the node type from. Used in selector querying. + */ + nodeTypeKey: string; + /** + * The traversal path that tools should take when evaluating the AST + */ + visitorKeys?: Record; + /** + * Default language options. User-defined options are merged with this object. + */ + defaultLanguageOptions?: LanguageOptions; + /** + * Validates languageOptions for this language. + */ + validateLanguageOptions(languageOptions: Options["LangOptions"]): void; + /** + * Normalizes languageOptions for this language. + */ + normalizeLanguageOptions?(languageOptions: Options["LangOptions"]): Options["LangOptions"]; + /** + * Helper for esquery that allows languages to match nodes against + * class. esquery currently has classes like `function` that will + * match all the various function nodes. This method allows languages + * to implement similar shorthands. + */ + matchesSelectorClass?(className: string, node: Options["Node"], ancestry: Options["Node"][]): boolean; + /** + * Parses the given file input into its component parts. This file should not + * throws errors for parsing errors but rather should return any parsing + * errors as parse of the ParseResult object. + */ + parse(file: File, context: LanguageContext): ParseResult; + /** + * Creates SourceCode object that ESLint uses to work with a file. + */ + createSourceCode(file: File, input: OkParseResult, context: LanguageContext): Options["Code"]; +} +/** + * Plugin-defined options for the language. + */ +export type LanguageOptions = Record; +/** + * The context object that is passed to the language plugin methods. + */ +export interface LanguageContext { + languageOptions: LangOptions; +} +/** + * Represents a file read by ESLint. + */ +export interface File { + /** + * The path that ESLint uses for this file. May be a virtual path + * if it was returned by a processor. + */ + path: string; + /** + * The path to the file on disk. This always maps directly to a file + * regardless of whether it was returned from a processor. + */ + physicalPath: string; + /** + * Indicates if the original source contained a byte-order marker. + * ESLint strips the BOM from the `body`, but this info is needed + * to correctly apply autofixing. + */ + bom: boolean; + /** + * The body of the file to parse. + */ + body: string | Uint8Array; +} +/** + * Represents the successful result of parsing a file. + */ +export interface OkParseResult { + /** + * Indicates if the parse was successful. If true, the parse was successful + * and ESLint should continue on to create a SourceCode object and run rules; + * if false, ESLint should just report the error(s) without doing anything + * else. + */ + ok: true; + /** + * The abstract syntax tree created by the parser. (only when ok: true) + */ + ast: RootNode; + /** + * Any additional data that the parser wants to provide. + */ + [key: string]: any; +} +/** + * Represents the unsuccessful result of parsing a file. + */ +export interface NotOkParseResult { + /** + * Indicates if the parse was successful. If true, the parse was successful + * and ESLint should continue on to create a SourceCode object and run rules; + * if false, ESLint should just report the error(s) without doing anything + * else. + */ + ok: false; + /** + * Any parsing errors, whether fatal or not. (only when ok: false) + */ + errors: FileError[]; + /** + * Any additional data that the parser wants to provide. + */ + [key: string]: any; +} +export type ParseResult = OkParseResult | NotOkParseResult; +/** + * Represents inline configuration found in the source code. + */ +interface InlineConfigElement { + /** + * The location of the inline config element. + */ + loc: SourceLocation; + /** + * The interpreted configuration from the inline config element. + */ + config: { + rules: RulesConfig; + }; +} +/** + * Generic options for the `SourceCodeBase` type. + */ +export interface SourceCodeBaseTypeOptions { + LangOptions: LanguageOptions; + RootNode: unknown; + SyntaxElementWithLoc: unknown; + ConfigNode: unknown; +} +/** + * Represents the basic interface for a source code object. + */ +interface SourceCodeBase { + /** + * Root of the AST. + */ + ast: Options["RootNode"]; + /** + * The traversal path that tools should take when evaluating the AST. + * When present, this overrides the `visitorKeys` on the language for + * just this source code object. + */ + visitorKeys?: Record; + /** + * Retrieves the equivalent of `loc` for a given node or token. + * @param syntaxElement The node or token to get the location for. + * @returns The location of the node or token. + */ + getLoc(syntaxElement: Options["SyntaxElementWithLoc"]): SourceLocation; + /** + * Retrieves the equivalent of `range` for a given node or token. + * @param syntaxElement The node or token to get the range for. + * @returns The range of the node or token. + */ + getRange(syntaxElement: Options["SyntaxElementWithLoc"]): SourceRange; + /** + * Traversal of AST. + */ + traverse(): Iterable; + /** + * Applies language options passed in from the ESLint core. + */ + applyLanguageOptions?(languageOptions: Options["LangOptions"]): void; + /** + * Return all of the inline areas where ESLint should be disabled/enabled + * along with any problems found in evaluating the directives. + */ + getDisableDirectives?(): { + directives: Directive[]; + problems: FileProblem[]; + }; + /** + * Returns an array of all inline configuration nodes found in the + * source code. + */ + getInlineConfigNodes?(): Options["ConfigNode"][]; + /** + * Applies configuration found inside of the source code. This method is only + * called when ESLint is running with inline configuration allowed. + */ + applyInlineConfig?(): { + configs: InlineConfigElement[]; + problems: FileProblem[]; + }; + /** + * Called by ESLint core to indicate that it has finished providing + * information. We now add in all the missing variables and ensure that + * state-changing methods cannot be called by rules. + * @returns {void} + */ + finalize?(): void; +} +/** + * Represents the source of a text file being linted. + */ +export interface TextSourceCode extends SourceCodeBase { + /** + * The body of the file that you'd like rule developers to access. + */ + text: string; +} +/** + * Represents the source of a binary file being linted. + */ +export interface BinarySourceCode extends SourceCodeBase { + /** + * The body of the file that you'd like rule developers to access. + */ + body: Uint8Array; +} +export type SourceCode = TextSourceCode | BinarySourceCode; +/** + * Represents a traversal step visiting the AST. + */ +export interface VisitTraversalStep { + kind: 1; + target: unknown; + phase: 1 | 2; + args: unknown[]; +} +/** + * Represents a traversal step calling a function. + */ +export interface CallTraversalStep { + kind: 2; + target: string; + phase?: string; + args: unknown[]; +} +export type TraversalStep = VisitTraversalStep | CallTraversalStep; +/** + * The type of disable directive. This determines how ESLint will disable rules. + */ +export type DirectiveType = "disable" | "enable" | "disable-line" | "disable-next-line"; +/** + * Represents a disable directive. + */ +export interface Directive { + /** + * The type of directive. + */ + type: DirectiveType; + /** + * The node of the directive. May be in the AST or a comment/token. + */ + node: unknown; + /** + * The value of the directive. + */ + value: string; + /** + * The justification for the directive. + */ + justification?: string; +} +export {}; diff --git a/node_modules/@eslint/core/dist/esm/types.d.ts b/node_modules/@eslint/core/dist/esm/types.d.ts new file mode 100644 index 00000000..247084ce --- /dev/null +++ b/node_modules/@eslint/core/dist/esm/types.d.ts @@ -0,0 +1,838 @@ +/** + * @fileoverview Shared types for ESLint Core. + */ +import type { JSONSchema4 } from "json-schema"; +/** + * Represents an error inside of a file. + */ +export interface FileError { + message: string; + line: number; + column: number; + endLine?: number; + endColumn?: number; +} +/** + * Represents a problem found in a file. + */ +export interface FileProblem { + ruleId: string | null; + message: string; + loc: SourceLocation; +} +/** + * Represents the start and end coordinates of a node inside the source. + */ +export interface SourceLocation { + start: Position; + end: Position; +} +/** + * Represents the start and end coordinates of a node inside the source with an offset. + */ +export interface SourceLocationWithOffset { + start: PositionWithOffset; + end: PositionWithOffset; +} +/** + * Represents a location coordinate inside the source. ESLint-style formats + * have just `line` and `column` while others may have `offset` as well. + */ +export interface Position { + line: number; + column: number; +} +/** + * Represents a location coordinate inside the source with an offset. + */ +export interface PositionWithOffset extends Position { + offset: number; +} +/** + * Represents a range of characters in the source. + */ +export type SourceRange = [number, number]; +/** + * What the rule is responsible for finding: + * - `problem` means the rule has noticed a potential error. + * - `suggestion` means the rule suggests an alternate or better approach. + * - `layout` means the rule is looking at spacing, indentation, etc. + */ +export type RuleType = "problem" | "suggestion" | "layout"; +/** + * The type of fix the rule can provide: + * - `code` means the rule can fix syntax. + * - `whitespace` means the rule can fix spacing and indentation. + */ +export type RuleFixType = "code" | "whitespace"; +/** + * An object containing visitor information for a rule. Each method is either the + * name of a node type or a selector, or is a method that will be called at specific + * times during the traversal. + */ +export type RuleVisitor = Record void) | undefined>; +/** + * Rule meta information used for documentation. + */ +export interface RulesMetaDocs { + /** + * A short description of the rule. + */ + description?: string | undefined; + /** + * The URL to the documentation for the rule. + */ + url?: string | undefined; + /** + * The category the rule falls under. + * @deprecated No longer used. + */ + category?: string | undefined; + /** + * Indicates if the rule is generally recommended for all users. + */ + recommended?: boolean | undefined; + /** + * Indicates if the rule is frozen (no longer accepting feature requests). + */ + frozen?: boolean | undefined; +} +/** + * Meta information about a rule. + */ +export interface RulesMeta { + /** + * Properties that are used when documenting the rule. + */ + docs?: (RulesMetaDocs & ExtRuleDocs) | undefined; + /** + * The type of rule. + */ + type?: RuleType | undefined; + /** + * The schema for the rule options. Required if the rule has options. + */ + schema?: JSONSchema4 | JSONSchema4[] | false | undefined; + /** + * Any default options to be recursively merged on top of any user-provided options. + **/ + defaultOptions?: RuleOptions; + /** + * The messages that the rule can report. + */ + messages?: Record; + /** + * Indicates whether the rule has been deprecated or provides additional metadata about the deprecation. Omit if not deprecated. + */ + deprecated?: boolean | DeprecatedInfo | undefined; + /** + * @deprecated Use deprecated.replacedBy instead. + * The name of the rule(s) this rule was replaced by, if it was deprecated. + */ + replacedBy?: readonly string[] | undefined; + /** + * Indicates if the rule is fixable, and if so, what type of fix it provides. + */ + fixable?: RuleFixType | undefined; + /** + * Indicates if the rule may provide suggestions. + */ + hasSuggestions?: boolean | undefined; + /** + * The language the rule is intended to lint. + */ + language?: string; + /** + * The dialects of `language` that the rule is intended to lint. + */ + dialects?: string[]; +} +/** + * Provides additional metadata about a deprecation. + */ +export interface DeprecatedInfo { + /** + * General message presented to the user, e.g. for the key rule why the rule + * is deprecated or for info how to replace the rule. + */ + message?: string; + /** + * URL to more information about this deprecation in general. + */ + url?: string; + /** + * An empty array explicitly states that there is no replacement. + */ + replacedBy?: ReplacedByInfo[]; + /** + * The package version since when the rule is deprecated (should use full + * semver without a leading "v"). + */ + deprecatedSince?: string; + /** + * The estimated version when the rule is removed (probably the next major + * version). null means the rule is "frozen" (will be available but will not + * be changed). + */ + availableUntil?: string | null; +} +/** + * Provides metadata about a replacement + */ +export interface ReplacedByInfo { + /** + * General message presented to the user, e.g. how to replace the rule + */ + message?: string; + /** + * URL to more information about this replacement in general + */ + url?: string; + /** + * Name should be "eslint" if the replacement is an ESLint core rule. Omit + * the property if the replacement is in the same plugin. + */ + plugin?: ExternalSpecifier; + /** + * Name and documentation of the replacement rule + */ + rule?: ExternalSpecifier; +} +/** + * Specifies the name and url of an external resource. At least one property + * should be set. + */ +export interface ExternalSpecifier { + /** + * Name of the referenced plugin / rule. + */ + name?: string; + /** + * URL pointing to documentation for the plugin / rule. + */ + url?: string; +} +/** + * Generic type for `RuleContext`. + */ +export interface RuleContextTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RuleOptions: unknown[]; + Node: unknown; + MessageIds: string; +} +/** + * Represents the context object that is passed to a rule. This object contains + * information about the current state of the linting process and is the rule's + * view into the outside world. + */ +export interface RuleContext { + /** + * The current working directory for the session. + */ + cwd: string; + /** + * Returns the current working directory for the session. + * @deprecated Use `cwd` instead. + */ + getCwd(): string; + /** + * The filename of the file being linted. + */ + filename: string; + /** + * Returns the filename of the file being linted. + * @deprecated Use `filename` instead. + */ + getFilename(): string; + /** + * The physical filename of the file being linted. + */ + physicalFilename: string; + /** + * Returns the physical filename of the file being linted. + * @deprecated Use `physicalFilename` instead. + */ + getPhysicalFilename(): string; + /** + * The source code object that the rule is running on. + */ + sourceCode: Options["Code"]; + /** + * Returns the source code object that the rule is running on. + * @deprecated Use `sourceCode` instead. + */ + getSourceCode(): Options["Code"]; + /** + * Shared settings for the configuration. + */ + settings: SettingsConfig; + /** + * Parser-specific options for the configuration. + * @deprecated Use `languageOptions.parserOptions` instead. + */ + parserOptions: Record; + /** + * The language options for the configuration. + */ + languageOptions: Options["LangOptions"]; + /** + * The CommonJS path to the parser used while parsing this file. + * @deprecated No longer used. + */ + parserPath: string | undefined; + /** + * The rule ID. + */ + id: string; + /** + * The rule's configured options. + */ + options: Options["RuleOptions"]; + /** + * The report function that the rule should use to report problems. + * @param violation The violation to report. + */ + report(violation: ViolationReport): void; +} +/** + * Manager of text edits for a rule fix. + */ +export interface RuleTextEditor { + /** + * Inserts text after the specified node or token. + * @param syntaxElement The node or token to insert after. + * @param text The edit to insert after the node or token. + */ + insertTextAfter(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Inserts text after the specified range. + * @param range The range to insert after. + * @param text The edit to insert after the range. + */ + insertTextAfterRange(range: SourceRange, text: string): RuleTextEdit; + /** + * Inserts text before the specified node or token. + * @param syntaxElement A syntax element with location information to insert before. + * @param text The edit to insert before the node or token. + */ + insertTextBefore(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Inserts text before the specified range. + * @param range The range to insert before. + * @param text The edit to insert before the range. + */ + insertTextBeforeRange(range: SourceRange, text: string): RuleTextEdit; + /** + * Removes the specified node or token. + * @param syntaxElement A syntax element with location information to remove. + * @returns The edit to remove the node or token. + */ + remove(syntaxElement: EditableSyntaxElement): RuleTextEdit; + /** + * Removes the specified range. + * @param range The range to remove. + * @returns The edit to remove the range. + */ + removeRange(range: SourceRange): RuleTextEdit; + /** + * Replaces the specified node or token with the given text. + * @param syntaxElement A syntax element with location information to replace. + * @param text The text to replace the node or token with. + * @returns The edit to replace the node or token. + */ + replaceText(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Replaces the specified range with the given text. + * @param range The range to replace. + * @param text The text to replace the range with. + * @returns The edit to replace the range. + */ + replaceTextRange(range: SourceRange, text: string): RuleTextEdit; +} +/** + * Represents a fix for a rule violation implemented as a text edit. + */ +export interface RuleTextEdit { + /** + * The range to replace. + */ + range: SourceRange; + /** + * The text to insert. + */ + text: string; +} +/** + * Fixes a violation. + * @param fixer The text editor to apply the fix. + * @returns The fix(es) for the violation. + */ +type RuleFixer = (fixer: RuleTextEditor) => RuleTextEdit | Iterable | null; +interface ViolationReportBase { + /** + * The type of node that the violation is for. + * @deprecated May be removed in the future. + */ + nodeType?: string | undefined; + /** + * The data to insert into the message. + */ + data?: Record | undefined; + /** + * The fix to be applied for the violation. + */ + fix?: RuleFixer | null | undefined; + /** + * An array of suggested fixes for the problem. These fixes may change the + * behavior of the code, so they are not applied automatically. + */ + suggest?: SuggestedEdit[] | null | undefined; +} +type ViolationMessage = { + message: string; +} | { + messageId: MessageIds; +}; +type ViolationLocation = { + loc: SourceLocation | Position; +} | { + node: Node; +}; +export type ViolationReport = ViolationReportBase & ViolationMessage & ViolationLocation; +interface SuggestedEditBase { + /** + * The data to insert into the message. + */ + data?: Record | undefined; + /** + * The fix to be applied for the suggestion. + */ + fix?: RuleFixer | null | undefined; +} +type SuggestionMessage = { + desc: string; +} | { + messageId: string; +}; +/** + * A suggested edit for a rule violation. + */ +export type SuggestedEdit = SuggestedEditBase & SuggestionMessage; +/** + * Generic options for the `RuleDefinition` type. + */ +export interface RuleDefinitionTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RuleOptions: unknown[]; + Visitor: RuleVisitor; + Node: unknown; + MessageIds: string; + ExtRuleDocs: unknown; +} +/** + * The definition of an ESLint rule. + */ +export interface RuleDefinition { + /** + * The meta information for the rule. + */ + meta?: RulesMeta; + /** + * Creates the visitor that ESLint uses to apply the rule during traversal. + * @param context The rule context. + * @returns The rule visitor. + */ + create(context: RuleContext<{ + LangOptions: Options["LangOptions"]; + Code: Options["Code"]; + RuleOptions: Options["RuleOptions"]; + Node: Options["Node"]; + MessageIds: Options["MessageIds"]; + }>): Options["Visitor"]; +} +/** + * Defaults for non-language-related `RuleDefinition` options. + */ +export interface CustomRuleTypeDefinitions { + RuleOptions: unknown[]; + MessageIds: string; + ExtRuleDocs: Record; +} +/** + * A helper type to define language specific specializations of the `RuleDefinition` type. + * + * @example + * ```ts + * type YourRuleDefinition< + * Options extends Partial = {}, + * > = CustomRuleDefinitionType< + * { + * LangOptions: YourLanguageOptions; + * Code: YourSourceCode; + * Visitor: YourRuleVisitor; + * Node: YourNode; + * }, + * Options + * >; + * ``` + */ +export type CustomRuleDefinitionType, Options extends Partial> = RuleDefinition>>; +/** + * The human readable severity level used in a configuration. + */ +export type SeverityName = "off" | "warn" | "error"; +/** + * The numeric severity level for a rule. + * + * - `0` means off. + * - `1` means warn. + * - `2` means error. + */ +export type SeverityLevel = 0 | 1 | 2; +/** + * The severity of a rule in a configuration. + */ +export type Severity = SeverityName | SeverityLevel; +/** + * Represents the configuration options for the core linter. + */ +export interface LinterOptionsConfig { + /** + * Indicates whether or not inline configuration is evaluated. + */ + noInlineConfig?: boolean; + /** + * Indicates what to do when an unused disable directive is found. + */ + reportUnusedDisableDirectives?: boolean | Severity; +} +/** + * Shared settings that are accessible from within plugins. + */ +export type SettingsConfig = Record; +/** + * The configuration for a rule. + */ +export type RuleConfig = Severity | [Severity, ...unknown[]]; +/** + * A collection of rules and their configurations. + */ +export type RulesConfig = Record; +/** + * Generic options for the `Language` type. + */ +export interface LanguageTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RootNode: unknown; + Node: unknown; +} +/** + * Represents a plugin language. + */ +export interface Language { + /** + * Indicates how ESLint should read the file. + */ + fileType: "text"; + /** + * First line number returned from the parser (text mode only). + */ + lineStart: 0 | 1; + /** + * First column number returned from the parser (text mode only). + */ + columnStart: 0 | 1; + /** + * The property to read the node type from. Used in selector querying. + */ + nodeTypeKey: string; + /** + * The traversal path that tools should take when evaluating the AST + */ + visitorKeys?: Record; + /** + * Default language options. User-defined options are merged with this object. + */ + defaultLanguageOptions?: LanguageOptions; + /** + * Validates languageOptions for this language. + */ + validateLanguageOptions(languageOptions: Options["LangOptions"]): void; + /** + * Normalizes languageOptions for this language. + */ + normalizeLanguageOptions?(languageOptions: Options["LangOptions"]): Options["LangOptions"]; + /** + * Helper for esquery that allows languages to match nodes against + * class. esquery currently has classes like `function` that will + * match all the various function nodes. This method allows languages + * to implement similar shorthands. + */ + matchesSelectorClass?(className: string, node: Options["Node"], ancestry: Options["Node"][]): boolean; + /** + * Parses the given file input into its component parts. This file should not + * throws errors for parsing errors but rather should return any parsing + * errors as parse of the ParseResult object. + */ + parse(file: File, context: LanguageContext): ParseResult; + /** + * Creates SourceCode object that ESLint uses to work with a file. + */ + createSourceCode(file: File, input: OkParseResult, context: LanguageContext): Options["Code"]; +} +/** + * Plugin-defined options for the language. + */ +export type LanguageOptions = Record; +/** + * The context object that is passed to the language plugin methods. + */ +export interface LanguageContext { + languageOptions: LangOptions; +} +/** + * Represents a file read by ESLint. + */ +export interface File { + /** + * The path that ESLint uses for this file. May be a virtual path + * if it was returned by a processor. + */ + path: string; + /** + * The path to the file on disk. This always maps directly to a file + * regardless of whether it was returned from a processor. + */ + physicalPath: string; + /** + * Indicates if the original source contained a byte-order marker. + * ESLint strips the BOM from the `body`, but this info is needed + * to correctly apply autofixing. + */ + bom: boolean; + /** + * The body of the file to parse. + */ + body: string | Uint8Array; +} +/** + * Represents the successful result of parsing a file. + */ +export interface OkParseResult { + /** + * Indicates if the parse was successful. If true, the parse was successful + * and ESLint should continue on to create a SourceCode object and run rules; + * if false, ESLint should just report the error(s) without doing anything + * else. + */ + ok: true; + /** + * The abstract syntax tree created by the parser. (only when ok: true) + */ + ast: RootNode; + /** + * Any additional data that the parser wants to provide. + */ + [key: string]: any; +} +/** + * Represents the unsuccessful result of parsing a file. + */ +export interface NotOkParseResult { + /** + * Indicates if the parse was successful. If true, the parse was successful + * and ESLint should continue on to create a SourceCode object and run rules; + * if false, ESLint should just report the error(s) without doing anything + * else. + */ + ok: false; + /** + * Any parsing errors, whether fatal or not. (only when ok: false) + */ + errors: FileError[]; + /** + * Any additional data that the parser wants to provide. + */ + [key: string]: any; +} +export type ParseResult = OkParseResult | NotOkParseResult; +/** + * Represents inline configuration found in the source code. + */ +interface InlineConfigElement { + /** + * The location of the inline config element. + */ + loc: SourceLocation; + /** + * The interpreted configuration from the inline config element. + */ + config: { + rules: RulesConfig; + }; +} +/** + * Generic options for the `SourceCodeBase` type. + */ +export interface SourceCodeBaseTypeOptions { + LangOptions: LanguageOptions; + RootNode: unknown; + SyntaxElementWithLoc: unknown; + ConfigNode: unknown; +} +/** + * Represents the basic interface for a source code object. + */ +interface SourceCodeBase { + /** + * Root of the AST. + */ + ast: Options["RootNode"]; + /** + * The traversal path that tools should take when evaluating the AST. + * When present, this overrides the `visitorKeys` on the language for + * just this source code object. + */ + visitorKeys?: Record; + /** + * Retrieves the equivalent of `loc` for a given node or token. + * @param syntaxElement The node or token to get the location for. + * @returns The location of the node or token. + */ + getLoc(syntaxElement: Options["SyntaxElementWithLoc"]): SourceLocation; + /** + * Retrieves the equivalent of `range` for a given node or token. + * @param syntaxElement The node or token to get the range for. + * @returns The range of the node or token. + */ + getRange(syntaxElement: Options["SyntaxElementWithLoc"]): SourceRange; + /** + * Traversal of AST. + */ + traverse(): Iterable; + /** + * Applies language options passed in from the ESLint core. + */ + applyLanguageOptions?(languageOptions: Options["LangOptions"]): void; + /** + * Return all of the inline areas where ESLint should be disabled/enabled + * along with any problems found in evaluating the directives. + */ + getDisableDirectives?(): { + directives: Directive[]; + problems: FileProblem[]; + }; + /** + * Returns an array of all inline configuration nodes found in the + * source code. + */ + getInlineConfigNodes?(): Options["ConfigNode"][]; + /** + * Applies configuration found inside of the source code. This method is only + * called when ESLint is running with inline configuration allowed. + */ + applyInlineConfig?(): { + configs: InlineConfigElement[]; + problems: FileProblem[]; + }; + /** + * Called by ESLint core to indicate that it has finished providing + * information. We now add in all the missing variables and ensure that + * state-changing methods cannot be called by rules. + * @returns {void} + */ + finalize?(): void; +} +/** + * Represents the source of a text file being linted. + */ +export interface TextSourceCode extends SourceCodeBase { + /** + * The body of the file that you'd like rule developers to access. + */ + text: string; +} +/** + * Represents the source of a binary file being linted. + */ +export interface BinarySourceCode extends SourceCodeBase { + /** + * The body of the file that you'd like rule developers to access. + */ + body: Uint8Array; +} +export type SourceCode = TextSourceCode | BinarySourceCode; +/** + * Represents a traversal step visiting the AST. + */ +export interface VisitTraversalStep { + kind: 1; + target: unknown; + phase: 1 | 2; + args: unknown[]; +} +/** + * Represents a traversal step calling a function. + */ +export interface CallTraversalStep { + kind: 2; + target: string; + phase?: string; + args: unknown[]; +} +export type TraversalStep = VisitTraversalStep | CallTraversalStep; +/** + * The type of disable directive. This determines how ESLint will disable rules. + */ +export type DirectiveType = "disable" | "enable" | "disable-line" | "disable-next-line"; +/** + * Represents a disable directive. + */ +export interface Directive { + /** + * The type of directive. + */ + type: DirectiveType; + /** + * The node of the directive. May be in the AST or a comment/token. + */ + node: unknown; + /** + * The value of the directive. + */ + value: string; + /** + * The justification for the directive. + */ + justification?: string; +} +export {}; diff --git a/node_modules/@eslint/core/package.json b/node_modules/@eslint/core/package.json new file mode 100644 index 00000000..35b58f05 --- /dev/null +++ b/node_modules/@eslint/core/package.json @@ -0,0 +1,48 @@ +{ + "name": "@eslint/core", + "version": "0.14.0", + "description": "Runtime-agnostic core of ESLint", + "type": "module", + "types": "./dist/esm/types.d.ts", + "exports": { + "types": { + "import": "./dist/esm/types.d.ts", + "require": "./dist/cjs/types.d.cts" + } + }, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "scripts": { + "build:cts": "node -e \"fs.cpSync('dist/esm/types.d.ts', 'dist/cjs/types.d.cts')\"", + "build": "tsc && npm run build:cts", + "test:jsr": "npx jsr@latest publish --dry-run", + "test:types": "tsc -p tests/types/tsconfig.json" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/rewrite.git" + }, + "keywords": [ + "eslint", + "core" + ], + "author": "Nicholas C. Zakas", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/rewrite/issues" + }, + "homepage": "https://github.com/eslint/rewrite#readme", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "devDependencies": { + "typescript": "^5.8.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/node_modules/@eslint/eslintrc/LICENSE b/node_modules/@eslint/eslintrc/LICENSE new file mode 100644 index 00000000..b607bb36 --- /dev/null +++ b/node_modules/@eslint/eslintrc/LICENSE @@ -0,0 +1,19 @@ +Copyright OpenJS Foundation and other contributors, + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@eslint/eslintrc/README.md b/node_modules/@eslint/eslintrc/README.md new file mode 100644 index 00000000..fc08cb3e --- /dev/null +++ b/node_modules/@eslint/eslintrc/README.md @@ -0,0 +1,128 @@ +# ESLintRC Library + +This repository contains the legacy ESLintRC configuration file format for ESLint. This package is not intended for use outside of the ESLint ecosystem. It is ESLint-specific and not intended for use in other programs. + +**Note:** This package is frozen except for critical bug fixes as ESLint moves to a new config system. + +## Installation + +You can install the package as follows: + +```shell +npm install @eslint/eslintrc -D +# or +yarn add @eslint/eslintrc -D +# or +pnpm install @eslint/eslintrc -D +# or +bun install @eslint/eslintrc -D +``` + +## Usage (ESM) + +The primary class in this package is `FlatCompat`, which is a utility to translate ESLintRC-style configs into flat configs. Here's how you use it inside of your `eslint.config.js` file: + +```js +import { FlatCompat } from "@eslint/eslintrc"; +import js from "@eslint/js"; +import path from "path"; +import { fileURLToPath } from "url"; + +// mimic CommonJS variables -- not needed if using CommonJS +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const compat = new FlatCompat({ + baseDirectory: __dirname, // optional; default: process.cwd() + resolvePluginsRelativeTo: __dirname, // optional + recommendedConfig: js.configs.recommended, // optional unless you're using "eslint:recommended" + allConfig: js.configs.all, // optional unless you're using "eslint:all" +}); + +export default [ + + // mimic ESLintRC-style extends + ...compat.extends("standard", "example", "plugin:react/recommended"), + + // mimic environments + ...compat.env({ + es2020: true, + node: true + }), + + // mimic plugins + ...compat.plugins("jsx-a11y", "react"), + + // translate an entire config + ...compat.config({ + plugins: ["jsx-a11y", "react"], + extends: "standard", + env: { + es2020: true, + node: true + }, + rules: { + semi: "error" + } + }) +]; +``` + +## Usage (CommonJS) + +Using `FlatCompat` in CommonJS files is similar to ESM, but you'll use `require()` and `module.exports` instead of `import` and `export`. Here's how you use it inside of your `eslint.config.js` CommonJS file: + +```js +const { FlatCompat } = require("@eslint/eslintrc"); +const js = require("@eslint/js"); + +const compat = new FlatCompat({ + baseDirectory: __dirname, // optional; default: process.cwd() + resolvePluginsRelativeTo: __dirname, // optional + recommendedConfig: js.configs.recommended, // optional unless using "eslint:recommended" + allConfig: js.configs.all, // optional unless using "eslint:all" +}); + +module.exports = [ + + // mimic ESLintRC-style extends + ...compat.extends("standard", "example", "plugin:react/recommended"), + + // mimic environments + ...compat.env({ + es2020: true, + node: true + }), + + // mimic plugins + ...compat.plugins("jsx-a11y", "react"), + + // translate an entire config + ...compat.config({ + plugins: ["jsx-a11y", "react"], + extends: "standard", + env: { + es2020: true, + node: true + }, + rules: { + semi: "error" + } + }) +]; +``` + +## Troubleshooting + +**TypeError: Missing parameter 'recommendedConfig' in FlatCompat constructor** + +The `recommendedConfig` option is required when any config uses `eslint:recommended`, including any config in an `extends` clause. To fix this, follow the example above using `@eslint/js` to provide the `eslint:recommended` config. + +**TypeError: Missing parameter 'allConfig' in FlatCompat constructor** + +The `allConfig` option is required when any config uses `eslint:all`, including any config in an `extends` clause. To fix this, follow the example above using `@eslint/js` to provide the `eslint:all` config. + + +## License + +MIT License diff --git a/node_modules/@eslint/eslintrc/conf/config-schema.js b/node_modules/@eslint/eslintrc/conf/config-schema.js new file mode 100644 index 00000000..ada90e13 --- /dev/null +++ b/node_modules/@eslint/eslintrc/conf/config-schema.js @@ -0,0 +1,79 @@ +/** + * @fileoverview Defines a schema for configs. + * @author Sylvan Mably + */ + +const baseConfigProperties = { + $schema: { type: "string" }, + env: { type: "object" }, + extends: { $ref: "#/definitions/stringOrStrings" }, + globals: { type: "object" }, + overrides: { + type: "array", + items: { $ref: "#/definitions/overrideConfig" }, + additionalItems: false + }, + parser: { type: ["string", "null"] }, + parserOptions: { type: "object" }, + plugins: { type: "array" }, + processor: { type: "string" }, + rules: { type: "object" }, + settings: { type: "object" }, + noInlineConfig: { type: "boolean" }, + reportUnusedDisableDirectives: { type: "boolean" }, + + ecmaFeatures: { type: "object" } // deprecated; logs a warning when used +}; + +const configSchema = { + definitions: { + stringOrStrings: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false + } + ] + }, + stringOrStringsRequired: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false, + minItems: 1 + } + ] + }, + + // Config at top-level. + objectConfig: { + type: "object", + properties: { + root: { type: "boolean" }, + ignorePatterns: { $ref: "#/definitions/stringOrStrings" }, + ...baseConfigProperties + }, + additionalProperties: false + }, + + // Config in `overrides`. + overrideConfig: { + type: "object", + properties: { + excludedFiles: { $ref: "#/definitions/stringOrStrings" }, + files: { $ref: "#/definitions/stringOrStringsRequired" }, + ...baseConfigProperties + }, + required: ["files"], + additionalProperties: false + } + }, + + $ref: "#/definitions/objectConfig" +}; + +export default configSchema; diff --git a/node_modules/@eslint/eslintrc/conf/environments.js b/node_modules/@eslint/eslintrc/conf/environments.js new file mode 100644 index 00000000..e296fae7 --- /dev/null +++ b/node_modules/@eslint/eslintrc/conf/environments.js @@ -0,0 +1,215 @@ +/** + * @fileoverview Defines environment settings and globals. + * @author Elan Shanker + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import globals from "globals"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Get the object that has difference. + * @param {Record} current The newer object. + * @param {Record} prev The older object. + * @returns {Record} The difference object. + */ +function getDiff(current, prev) { + const retv = {}; + + for (const [key, value] of Object.entries(current)) { + if (!Object.hasOwn(prev, key)) { + retv[key] = value; + } + } + + return retv; +} + +const newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ... +const newGlobals2017 = { + Atomics: false, + SharedArrayBuffer: false +}; +const newGlobals2020 = { + BigInt: false, + BigInt64Array: false, + BigUint64Array: false, + globalThis: false +}; + +const newGlobals2021 = { + AggregateError: false, + FinalizationRegistry: false, + WeakRef: false +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** @type {Map} */ +export default new Map(Object.entries({ + + // Language + builtin: { + globals: globals.es5 + }, + es6: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2015: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2016: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 7 + } + }, + es2017: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 8 + } + }, + es2018: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 9 + } + }, + es2019: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 10 + } + }, + es2020: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 }, + parserOptions: { + ecmaVersion: 11 + } + }, + es2021: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 12 + } + }, + es2022: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 13 + } + }, + es2023: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 14 + } + }, + es2024: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 15 + } + }, + + // Platforms + browser: { + globals: globals.browser + }, + node: { + globals: globals.node, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + "shared-node-browser": { + globals: globals["shared-node-browser"] + }, + worker: { + globals: globals.worker + }, + serviceworker: { + globals: globals.serviceworker + }, + + // Frameworks + commonjs: { + globals: globals.commonjs, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + amd: { + globals: globals.amd + }, + mocha: { + globals: globals.mocha + }, + jasmine: { + globals: globals.jasmine + }, + jest: { + globals: globals.jest + }, + phantomjs: { + globals: globals.phantomjs + }, + jquery: { + globals: globals.jquery + }, + qunit: { + globals: globals.qunit + }, + prototypejs: { + globals: globals.prototypejs + }, + shelljs: { + globals: globals.shelljs + }, + meteor: { + globals: globals.meteor + }, + mongo: { + globals: globals.mongo + }, + protractor: { + globals: globals.protractor + }, + applescript: { + globals: globals.applescript + }, + nashorn: { + globals: globals.nashorn + }, + atomtest: { + globals: globals.atomtest + }, + embertest: { + globals: globals.embertest + }, + webextensions: { + globals: globals.webextensions + }, + greasemonkey: { + globals: globals.greasemonkey + } +})); diff --git a/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs b/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs new file mode 100644 index 00000000..6000445f --- /dev/null +++ b/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs @@ -0,0 +1,1212 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var util = require('node:util'); +var path = require('node:path'); +var Ajv = require('ajv'); +var globals = require('globals'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var util__default = /*#__PURE__*/_interopDefaultLegacy(util); +var path__default = /*#__PURE__*/_interopDefaultLegacy(path); +var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv); +var globals__default = /*#__PURE__*/_interopDefaultLegacy(globals); + +/** + * @fileoverview Config file operations. This file must be usable in the browser, + * so no Node-specific code can be here. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +const RULE_SEVERITY_STRINGS = ["off", "warn", "error"], + RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => { + map[value] = index; + return map; + }, {}), + VALID_SEVERITIES = new Set([0, 1, 2, "off", "warn", "error"]); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Normalizes the severity value of a rule's configuration to a number + * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally + * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0), + * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array + * whose first element is one of the above values. Strings are matched case-insensitively. + * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0. + */ +function getRuleSeverity(ruleConfig) { + const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (severityValue === 0 || severityValue === 1 || severityValue === 2) { + return severityValue; + } + + if (typeof severityValue === "string") { + return RULE_SEVERITY[severityValue.toLowerCase()] || 0; + } + + return 0; +} + +/** + * Converts old-style severity settings (0, 1, 2) into new-style + * severity settings (off, warn, error) for all rules. Assumption is that severity + * values have already been validated as correct. + * @param {Object} config The config object to normalize. + * @returns {void} + */ +function normalizeToStrings(config) { + + if (config.rules) { + Object.keys(config.rules).forEach(ruleId => { + const ruleConfig = config.rules[ruleId]; + + if (typeof ruleConfig === "number") { + config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0]; + } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") { + ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0]; + } + }); + } +} + +/** + * Determines if the severity for the given rule configuration represents an error. + * @param {int|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} True if the rule represents an error, false if not. + */ +function isErrorSeverity(ruleConfig) { + return getRuleSeverity(ruleConfig) === 2; +} + +/** + * Checks whether a given config has valid severity or not. + * @param {number|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isValidSeverity(ruleConfig) { + let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (typeof severity === "string") { + severity = severity.toLowerCase(); + } + return VALID_SEVERITIES.has(severity); +} + +/** + * Checks whether every rule of a given config has valid severity or not. + * @param {Object} config The configuration for rules. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isEverySeverityValid(config) { + return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId])); +} + +/** + * Normalizes a value for a global in a config + * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in + * a global directive comment + * @returns {("readable"|"writeable"|"off")} The value normalized as a string + * @throws Error if global value is invalid + */ +function normalizeConfigGlobal(configuredValue) { + switch (configuredValue) { + case "off": + return "off"; + + case true: + case "true": + case "writeable": + case "writable": + return "writable"; + + case null: + case false: + case "false": + case "readable": + case "readonly": + return "readonly"; + + default: + throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`); + } +} + +var ConfigOps = { + __proto__: null, + getRuleSeverity: getRuleSeverity, + normalizeToStrings: normalizeToStrings, + isErrorSeverity: isErrorSeverity, + isValidSeverity: isValidSeverity, + isEverySeverityValid: isEverySeverityValid, + normalizeConfigGlobal: normalizeConfigGlobal +}; + +/** + * @fileoverview Provide the function that emits deprecation warnings. + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +// Defitions for deprecation warnings. +const deprecationWarningMessages = { + ESLINT_LEGACY_ECMAFEATURES: + "The 'ecmaFeatures' config file property is deprecated and has no effect.", + ESLINT_PERSONAL_CONFIG_LOAD: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please use a config file per project or the '--config' option.", + ESLINT_PERSONAL_CONFIG_SUPPRESS: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please remove it or add 'root:true' to the config files in your " + + "projects in order to avoid loading '~/.eslintrc.*' accidentally." +}; + +const sourceFileErrorCache = new Set(); + +/** + * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted + * for each unique file path, but repeated invocations with the same file path have no effect. + * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active. + * @param {string} source The name of the configuration source to report the warning for. + * @param {string} errorCode The warning message to show. + * @returns {void} + */ +function emitDeprecationWarning(source, errorCode) { + const cacheKey = JSON.stringify({ source, errorCode }); + + if (sourceFileErrorCache.has(cacheKey)) { + return; + } + sourceFileErrorCache.add(cacheKey); + + const rel = path__default["default"].relative(process.cwd(), source); + const message = deprecationWarningMessages[errorCode]; + + process.emitWarning( + `${message} (found in "${rel}")`, + "DeprecationWarning", + errorCode + ); +} + +/** + * @fileoverview The instance of Ajv validator. + * @author Evgeny Poberezkin + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/* + * Copied from ajv/lib/refs/json-schema-draft-04.json + * The MIT License (MIT) + * Copyright (c) 2015-2017 Evgeny Poberezkin + */ +const metaSchema = { + id: "http://json-schema.org/draft-04/schema#", + $schema: "http://json-schema.org/draft-04/schema#", + description: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + positiveInteger: { + type: "integer", + minimum: 0 + }, + positiveIntegerDefault0: { + allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + minItems: 1, + uniqueItems: true + } + }, + type: "object", + properties: { + id: { + type: "string" + }, + $schema: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: { }, + multipleOf: { + type: "number", + minimum: 0, + exclusiveMinimum: true + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "boolean", + default: false + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "boolean", + default: false + }, + maxLength: { $ref: "#/definitions/positiveInteger" }, + minLength: { $ref: "#/definitions/positiveIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + items: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/schemaArray" } + ], + default: { } + }, + maxItems: { $ref: "#/definitions/positiveInteger" }, + minItems: { $ref: "#/definitions/positiveIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + maxProperties: { $ref: "#/definitions/positiveInteger" }, + minProperties: { $ref: "#/definitions/positiveIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/stringArray" } + ] + } + }, + enum: { + type: "array", + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + dependencies: { + exclusiveMaximum: ["maximum"], + exclusiveMinimum: ["minimum"] + }, + default: { } +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +var ajvOrig = (additionalOptions = {}) => { + const ajv = new Ajv__default["default"]({ + meta: false, + useDefaults: true, + validateSchema: false, + missingRefs: "ignore", + verbose: true, + schemaId: "auto", + ...additionalOptions + }); + + ajv.addMetaSchema(metaSchema); + // eslint-disable-next-line no-underscore-dangle -- part of the API + ajv._opts.defaultMeta = metaSchema.id; + + return ajv; +}; + +/** + * @fileoverview Applies default rule options + * @author JoshuaKGoldberg + */ + +/** + * Check if the variable contains an object strictly rejecting arrays + * @param {unknown} value an object + * @returns {boolean} Whether value is an object + */ +function isObjectNotArray(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Deeply merges second on top of first, creating a new {} object if needed. + * @param {T} first Base, default value. + * @param {U} second User-specified value. + * @returns {T | U | (T & U)} Merged equivalent of second on top of first. + */ +function deepMergeObjects(first, second) { + if (second === void 0) { + return first; + } + + if (!isObjectNotArray(first) || !isObjectNotArray(second)) { + return second; + } + + const result = { ...first, ...second }; + + for (const key of Object.keys(second)) { + if (Object.prototype.propertyIsEnumerable.call(first, key)) { + result[key] = deepMergeObjects(first[key], second[key]); + } + } + + return result; +} + +/** + * Deeply merges second on top of first, creating a new [] array if needed. + * @param {T[] | undefined} first Base, default values. + * @param {U[] | undefined} second User-specified values. + * @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first. + */ +function deepMergeArrays(first, second) { + if (!first || !second) { + return second || first || []; + } + + return [ + ...first.map((value, i) => deepMergeObjects(value, second[i])), + ...second.slice(first.length) + ]; +} + +/** + * @fileoverview Defines a schema for configs. + * @author Sylvan Mably + */ + +const baseConfigProperties = { + $schema: { type: "string" }, + env: { type: "object" }, + extends: { $ref: "#/definitions/stringOrStrings" }, + globals: { type: "object" }, + overrides: { + type: "array", + items: { $ref: "#/definitions/overrideConfig" }, + additionalItems: false + }, + parser: { type: ["string", "null"] }, + parserOptions: { type: "object" }, + plugins: { type: "array" }, + processor: { type: "string" }, + rules: { type: "object" }, + settings: { type: "object" }, + noInlineConfig: { type: "boolean" }, + reportUnusedDisableDirectives: { type: "boolean" }, + + ecmaFeatures: { type: "object" } // deprecated; logs a warning when used +}; + +const configSchema = { + definitions: { + stringOrStrings: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false + } + ] + }, + stringOrStringsRequired: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false, + minItems: 1 + } + ] + }, + + // Config at top-level. + objectConfig: { + type: "object", + properties: { + root: { type: "boolean" }, + ignorePatterns: { $ref: "#/definitions/stringOrStrings" }, + ...baseConfigProperties + }, + additionalProperties: false + }, + + // Config in `overrides`. + overrideConfig: { + type: "object", + properties: { + excludedFiles: { $ref: "#/definitions/stringOrStrings" }, + files: { $ref: "#/definitions/stringOrStringsRequired" }, + ...baseConfigProperties + }, + required: ["files"], + additionalProperties: false + } + }, + + $ref: "#/definitions/objectConfig" +}; + +/** + * @fileoverview Defines environment settings and globals. + * @author Elan Shanker + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Get the object that has difference. + * @param {Record} current The newer object. + * @param {Record} prev The older object. + * @returns {Record} The difference object. + */ +function getDiff(current, prev) { + const retv = {}; + + for (const [key, value] of Object.entries(current)) { + if (!Object.hasOwn(prev, key)) { + retv[key] = value; + } + } + + return retv; +} + +const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ... +const newGlobals2017 = { + Atomics: false, + SharedArrayBuffer: false +}; +const newGlobals2020 = { + BigInt: false, + BigInt64Array: false, + BigUint64Array: false, + globalThis: false +}; + +const newGlobals2021 = { + AggregateError: false, + FinalizationRegistry: false, + WeakRef: false +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** @type {Map} */ +var environments = new Map(Object.entries({ + + // Language + builtin: { + globals: globals__default["default"].es5 + }, + es6: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2015: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2016: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 7 + } + }, + es2017: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 8 + } + }, + es2018: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 9 + } + }, + es2019: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 10 + } + }, + es2020: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 }, + parserOptions: { + ecmaVersion: 11 + } + }, + es2021: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 12 + } + }, + es2022: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 13 + } + }, + es2023: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 14 + } + }, + es2024: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 15 + } + }, + + // Platforms + browser: { + globals: globals__default["default"].browser + }, + node: { + globals: globals__default["default"].node, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + "shared-node-browser": { + globals: globals__default["default"]["shared-node-browser"] + }, + worker: { + globals: globals__default["default"].worker + }, + serviceworker: { + globals: globals__default["default"].serviceworker + }, + + // Frameworks + commonjs: { + globals: globals__default["default"].commonjs, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + amd: { + globals: globals__default["default"].amd + }, + mocha: { + globals: globals__default["default"].mocha + }, + jasmine: { + globals: globals__default["default"].jasmine + }, + jest: { + globals: globals__default["default"].jest + }, + phantomjs: { + globals: globals__default["default"].phantomjs + }, + jquery: { + globals: globals__default["default"].jquery + }, + qunit: { + globals: globals__default["default"].qunit + }, + prototypejs: { + globals: globals__default["default"].prototypejs + }, + shelljs: { + globals: globals__default["default"].shelljs + }, + meteor: { + globals: globals__default["default"].meteor + }, + mongo: { + globals: globals__default["default"].mongo + }, + protractor: { + globals: globals__default["default"].protractor + }, + applescript: { + globals: globals__default["default"].applescript + }, + nashorn: { + globals: globals__default["default"].nashorn + }, + atomtest: { + globals: globals__default["default"].atomtest + }, + embertest: { + globals: globals__default["default"].embertest + }, + webextensions: { + globals: globals__default["default"].webextensions + }, + greasemonkey: { + globals: globals__default["default"].greasemonkey + } +})); + +/** + * @fileoverview Validates configs. + * @author Brandon Mills + */ + +const ajv = ajvOrig(); + +const ruleValidators = new WeakMap(); +const noop = Function.prototype; + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ +let validateSchema; +const severityMap = { + error: 2, + warn: 1, + off: 0 +}; + +const validated = new WeakSet(); + +// JSON schema that disallows passing any options +const noOptionsSchema = Object.freeze({ + type: "array", + minItems: 0, + maxItems: 0 +}); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Validator for configuration objects. + */ +class ConfigValidator { + constructor({ builtInRules = new Map() } = {}) { + this.builtInRules = builtInRules; + } + + /** + * Gets a complete options schema for a rule. + * @param {Rule} rule A rule object + * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`. + * @returns {Object|null} JSON Schema for the rule's options. + * `null` if rule wasn't passed or its `meta.schema` is `false`. + */ + getRuleOptionsSchema(rule) { + if (!rule) { + return null; + } + + if (!rule.meta) { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + const schema = rule.meta.schema; + + if (typeof schema === "undefined") { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + // `schema:false` is an allowed explicit opt-out of options validation for the rule + if (schema === false) { + return null; + } + + if (typeof schema !== "object" || schema === null) { + throw new TypeError("Rule's `meta.schema` must be an array or object"); + } + + // ESLint-specific array form needs to be converted into a valid JSON Schema definition + if (Array.isArray(schema)) { + if (schema.length) { + return { + type: "array", + items: schema, + minItems: 0, + maxItems: schema.length + }; + } + + // `schema:[]` is an explicit way to specify that the rule does not accept any options + return { ...noOptionsSchema }; + } + + // `schema:` is assumed to be a valid JSON Schema definition + return schema; + } + + /** + * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid. + * @param {options} options The given options for the rule. + * @returns {number|string} The rule's severity value + * @throws {Error} If the severity is invalid. + */ + validateRuleSeverity(options) { + const severity = Array.isArray(options) ? options[0] : options; + const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity; + + if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) { + return normSeverity; + } + + throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`); + + } + + /** + * Validates the non-severity options passed to a rule, based on its schema. + * @param {{create: Function}} rule The rule to validate + * @param {Array} localOptions The options for the rule, excluding severity + * @returns {void} + * @throws {Error} If the options are invalid. + */ + validateRuleSchema(rule, localOptions) { + if (!ruleValidators.has(rule)) { + try { + const schema = this.getRuleOptionsSchema(rule); + + if (schema) { + ruleValidators.set(rule, ajv.compile(schema)); + } + } catch (err) { + const errorWithCode = new Error(err.message, { cause: err }); + + errorWithCode.code = "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"; + + throw errorWithCode; + } + } + + const validateRule = ruleValidators.get(rule); + + if (validateRule) { + const mergedOptions = deepMergeArrays(rule.meta?.defaultOptions, localOptions); + + validateRule(mergedOptions); + + if (validateRule.errors) { + throw new Error(validateRule.errors.map( + error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n` + ).join("")); + } + } + } + + /** + * Validates a rule's options against its schema. + * @param {{create: Function}|null} rule The rule that the config is being validated for + * @param {string} ruleId The rule's unique name. + * @param {Array|number} options The given options for the rule. + * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined, + * no source is prepended to the message. + * @returns {void} + * @throws {Error} If the options are invalid. + */ + validateRuleOptions(rule, ruleId, options, source = null) { + try { + const severity = this.validateRuleSeverity(options); + + if (severity !== 0) { + this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []); + } + } catch (err) { + let enhancedMessage = err.code === "ESLINT_INVALID_RULE_OPTIONS_SCHEMA" + ? `Error while processing options validation schema of rule '${ruleId}': ${err.message}` + : `Configuration for rule "${ruleId}" is invalid:\n${err.message}`; + + if (typeof source === "string") { + enhancedMessage = `${source}:\n\t${enhancedMessage}`; + } + + const enhancedError = new Error(enhancedMessage, { cause: err }); + + if (err.code) { + enhancedError.code = err.code; + } + + throw enhancedError; + } + } + + /** + * Validates an environment object + * @param {Object} environment The environment config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded environments. + * @returns {void} + * @throws {Error} If the environment is invalid. + */ + validateEnvironment( + environment, + source, + getAdditionalEnv = noop + ) { + + // not having an environment is ok + if (!environment) { + return; + } + + Object.keys(environment).forEach(id => { + const env = getAdditionalEnv(id) || environments.get(id) || null; + + if (!env) { + const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`; + + throw new Error(message); + } + }); + } + + /** + * Validates a rules config object + * @param {Object} rulesConfig The rules config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(ruleId:string) => Object} getAdditionalRule A map from strings to loaded rules + * @returns {void} + */ + validateRules( + rulesConfig, + source, + getAdditionalRule = noop + ) { + if (!rulesConfig) { + return; + } + + Object.keys(rulesConfig).forEach(id => { + const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null; + + this.validateRuleOptions(rule, id, rulesConfig[id], source); + }); + } + + /** + * Validates a `globals` section of a config file + * @param {Object} globalsConfig The `globals` section + * @param {string|null} source The name of the configuration source to report in the event of an error. + * @returns {void} + */ + validateGlobals(globalsConfig, source = null) { + if (!globalsConfig) { + return; + } + + Object.entries(globalsConfig) + .forEach(([configuredGlobal, configuredValue]) => { + try { + normalizeConfigGlobal(configuredValue); + } catch (err) { + throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`); + } + }); + } + + /** + * Validate `processor` configuration. + * @param {string|undefined} processorName The processor name. + * @param {string} source The name of config file. + * @param {(id:string) => Processor} getProcessor The getter of defined processors. + * @returns {void} + * @throws {Error} If the processor is invalid. + */ + validateProcessor(processorName, source, getProcessor) { + if (processorName && !getProcessor(processorName)) { + throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`); + } + } + + /** + * Formats an array of schema validation errors. + * @param {Array} errors An array of error messages to format. + * @returns {string} Formatted error message + */ + formatErrors(errors) { + return errors.map(error => { + if (error.keyword === "additionalProperties") { + const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty; + + return `Unexpected top-level property "${formattedPropertyPath}"`; + } + if (error.keyword === "type") { + const formattedField = error.dataPath.slice(1); + const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema; + const formattedValue = JSON.stringify(error.data); + + return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`; + } + + const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; + + return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`; + }).map(message => `\t- ${message}.\n`).join(""); + } + + /** + * Validates the top level properties of the config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @returns {void} + * @throws {Error} If the config is invalid. + */ + validateConfigSchema(config, source = null) { + validateSchema = validateSchema || ajv.compile(configSchema); + + if (!validateSchema(config)) { + throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`); + } + + if (Object.hasOwn(config, "ecmaFeatures")) { + emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES"); + } + } + + /** + * Validates an entire config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(ruleId:string) => Object} [getAdditionalRule] A map from strings to loaded rules. + * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded envs. + * @returns {void} + */ + validate(config, source, getAdditionalRule, getAdditionalEnv) { + this.validateConfigSchema(config, source); + this.validateRules(config.rules, source, getAdditionalRule); + this.validateEnvironment(config.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + + for (const override of config.overrides || []) { + this.validateRules(override.rules, source, getAdditionalRule); + this.validateEnvironment(override.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + } + } + + /** + * Validate config array object. + * @param {ConfigArray} configArray The config array to validate. + * @returns {void} + */ + validateConfigArray(configArray) { + const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments); + const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors); + const getPluginRule = Map.prototype.get.bind(configArray.pluginRules); + + // Validate. + for (const element of configArray) { + if (validated.has(element)) { + continue; + } + validated.add(element); + + this.validateEnvironment(element.env, element.name, getPluginEnv); + this.validateGlobals(element.globals, element.name); + this.validateProcessor(element.processor, element.name, getPluginProcessor); + this.validateRules(element.rules, element.name, getPluginRule); + } + } + +} + +/** + * @fileoverview Common helpers for naming of plugins, formatters and configs + */ + +const NAMESPACE_REGEX = /^@.*\//iu; + +/** + * Brings package name to correct format based on prefix + * @param {string} name The name of the package. + * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter" + * @returns {string} Normalized name of the package + * @private + */ +function normalizePackageName(name, prefix) { + let normalizedName = name; + + /** + * On Windows, name can come in with Windows slashes instead of Unix slashes. + * Normalize to Unix first to avoid errors later on. + * https://github.com/eslint/eslint/issues/5644 + */ + if (normalizedName.includes("\\")) { + normalizedName = normalizedName.replace(/\\/gu, "/"); + } + + if (normalizedName.charAt(0) === "@") { + + /** + * it's a scoped package + * package name is the prefix, or just a username + */ + const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"), + scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u"); + + if (scopedPackageShortcutRegex.test(normalizedName)) { + normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`); + } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) { + + /** + * for scoped packages, insert the prefix after the first / unless + * the path is already @scope/eslint or @scope/eslint-xxx-yyy + */ + normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`); + } + } else if (!normalizedName.startsWith(`${prefix}-`)) { + normalizedName = `${prefix}-${normalizedName}`; + } + + return normalizedName; +} + +/** + * Removes the prefix from a fullname. + * @param {string} fullname The term which may have the prefix. + * @param {string} prefix The prefix to remove. + * @returns {string} The term without prefix. + */ +function getShorthandName(fullname, prefix) { + if (fullname[0] === "@") { + let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname); + + if (matchResult) { + return matchResult[1]; + } + + matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname); + if (matchResult) { + return `${matchResult[1]}/${matchResult[2]}`; + } + } else if (fullname.startsWith(`${prefix}-`)) { + return fullname.slice(prefix.length + 1); + } + + return fullname; +} + +/** + * Gets the scope (namespace) of a term. + * @param {string} term The term which may have the namespace. + * @returns {string} The namespace of the term if it has one. + */ +function getNamespaceFromTerm(term) { + const match = term.match(NAMESPACE_REGEX); + + return match ? match[0] : ""; +} + +var naming = { + __proto__: null, + normalizePackageName: normalizePackageName, + getShorthandName: getShorthandName, + getNamespaceFromTerm: getNamespaceFromTerm +}; + +/** + * @fileoverview Package exports for @eslint/eslintrc + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +const Legacy = { + environments, + + // shared + ConfigOps, + ConfigValidator, + naming +}; + +exports.Legacy = Legacy; +//# sourceMappingURL=eslintrc-universal.cjs.map diff --git a/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs.map b/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs.map new file mode 100644 index 00000000..88429053 --- /dev/null +++ b/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"eslintrc-universal.cjs","sources":["../lib/shared/config-ops.js","../lib/shared/deprecation-warnings.js","../lib/shared/ajv.js","../lib/shared/deep-merge-arrays.js","../conf/config-schema.js","../conf/environments.js","../lib/shared/config-validator.js","../lib/shared/naming.js","../lib/index-universal.js"],"sourcesContent":["/**\n * @fileoverview Config file operations. This file must be usable in the browser,\n * so no Node-specific code can be here.\n * @author Nicholas C. Zakas\n */\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\n\nconst RULE_SEVERITY_STRINGS = [\"off\", \"warn\", \"error\"],\n RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {\n map[value] = index;\n return map;\n }, {}),\n VALID_SEVERITIES = new Set([0, 1, 2, \"off\", \"warn\", \"error\"]);\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * Normalizes the severity value of a rule's configuration to a number\n * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally\n * received from the user. A valid config value is either 0, 1, 2, the string \"off\" (treated the same as 0),\n * the string \"warn\" (treated the same as 1), the string \"error\" (treated the same as 2), or an array\n * whose first element is one of the above values. Strings are matched case-insensitively.\n * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.\n */\nfunction getRuleSeverity(ruleConfig) {\n const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;\n\n if (severityValue === 0 || severityValue === 1 || severityValue === 2) {\n return severityValue;\n }\n\n if (typeof severityValue === \"string\") {\n return RULE_SEVERITY[severityValue.toLowerCase()] || 0;\n }\n\n return 0;\n}\n\n/**\n * Converts old-style severity settings (0, 1, 2) into new-style\n * severity settings (off, warn, error) for all rules. Assumption is that severity\n * values have already been validated as correct.\n * @param {Object} config The config object to normalize.\n * @returns {void}\n */\nfunction normalizeToStrings(config) {\n\n if (config.rules) {\n Object.keys(config.rules).forEach(ruleId => {\n const ruleConfig = config.rules[ruleId];\n\n if (typeof ruleConfig === \"number\") {\n config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];\n } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === \"number\") {\n ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];\n }\n });\n }\n}\n\n/**\n * Determines if the severity for the given rule configuration represents an error.\n * @param {int|string|Array} ruleConfig The configuration for an individual rule.\n * @returns {boolean} True if the rule represents an error, false if not.\n */\nfunction isErrorSeverity(ruleConfig) {\n return getRuleSeverity(ruleConfig) === 2;\n}\n\n/**\n * Checks whether a given config has valid severity or not.\n * @param {number|string|Array} ruleConfig The configuration for an individual rule.\n * @returns {boolean} `true` if the configuration has valid severity.\n */\nfunction isValidSeverity(ruleConfig) {\n let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;\n\n if (typeof severity === \"string\") {\n severity = severity.toLowerCase();\n }\n return VALID_SEVERITIES.has(severity);\n}\n\n/**\n * Checks whether every rule of a given config has valid severity or not.\n * @param {Object} config The configuration for rules.\n * @returns {boolean} `true` if the configuration has valid severity.\n */\nfunction isEverySeverityValid(config) {\n return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));\n}\n\n/**\n * Normalizes a value for a global in a config\n * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in\n * a global directive comment\n * @returns {(\"readable\"|\"writeable\"|\"off\")} The value normalized as a string\n * @throws Error if global value is invalid\n */\nfunction normalizeConfigGlobal(configuredValue) {\n switch (configuredValue) {\n case \"off\":\n return \"off\";\n\n case true:\n case \"true\":\n case \"writeable\":\n case \"writable\":\n return \"writable\";\n\n case null:\n case false:\n case \"false\":\n case \"readable\":\n case \"readonly\":\n return \"readonly\";\n\n default:\n throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);\n }\n}\n\nexport {\n getRuleSeverity,\n normalizeToStrings,\n isErrorSeverity,\n isValidSeverity,\n isEverySeverityValid,\n normalizeConfigGlobal\n};\n","/**\n * @fileoverview Provide the function that emits deprecation warnings.\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport path from \"node:path\";\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\n\n// Defitions for deprecation warnings.\nconst deprecationWarningMessages = {\n ESLINT_LEGACY_ECMAFEATURES:\n \"The 'ecmaFeatures' config file property is deprecated and has no effect.\",\n ESLINT_PERSONAL_CONFIG_LOAD:\n \"'~/.eslintrc.*' config files have been deprecated. \" +\n \"Please use a config file per project or the '--config' option.\",\n ESLINT_PERSONAL_CONFIG_SUPPRESS:\n \"'~/.eslintrc.*' config files have been deprecated. \" +\n \"Please remove it or add 'root:true' to the config files in your \" +\n \"projects in order to avoid loading '~/.eslintrc.*' accidentally.\"\n};\n\nconst sourceFileErrorCache = new Set();\n\n/**\n * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted\n * for each unique file path, but repeated invocations with the same file path have no effect.\n * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.\n * @param {string} source The name of the configuration source to report the warning for.\n * @param {string} errorCode The warning message to show.\n * @returns {void}\n */\nfunction emitDeprecationWarning(source, errorCode) {\n const cacheKey = JSON.stringify({ source, errorCode });\n\n if (sourceFileErrorCache.has(cacheKey)) {\n return;\n }\n sourceFileErrorCache.add(cacheKey);\n\n const rel = path.relative(process.cwd(), source);\n const message = deprecationWarningMessages[errorCode];\n\n process.emitWarning(\n `${message} (found in \"${rel}\")`,\n \"DeprecationWarning\",\n errorCode\n );\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport {\n emitDeprecationWarning\n};\n","/**\n * @fileoverview The instance of Ajv validator.\n * @author Evgeny Poberezkin\n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport Ajv from \"ajv\";\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/*\n * Copied from ajv/lib/refs/json-schema-draft-04.json\n * The MIT License (MIT)\n * Copyright (c) 2015-2017 Evgeny Poberezkin\n */\nconst metaSchema = {\n id: \"http://json-schema.org/draft-04/schema#\",\n $schema: \"http://json-schema.org/draft-04/schema#\",\n description: \"Core schema meta-schema\",\n definitions: {\n schemaArray: {\n type: \"array\",\n minItems: 1,\n items: { $ref: \"#\" }\n },\n positiveInteger: {\n type: \"integer\",\n minimum: 0\n },\n positiveIntegerDefault0: {\n allOf: [{ $ref: \"#/definitions/positiveInteger\" }, { default: 0 }]\n },\n simpleTypes: {\n enum: [\"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"]\n },\n stringArray: {\n type: \"array\",\n items: { type: \"string\" },\n minItems: 1,\n uniqueItems: true\n }\n },\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n $schema: {\n type: \"string\"\n },\n title: {\n type: \"string\"\n },\n description: {\n type: \"string\"\n },\n default: { },\n multipleOf: {\n type: \"number\",\n minimum: 0,\n exclusiveMinimum: true\n },\n maximum: {\n type: \"number\"\n },\n exclusiveMaximum: {\n type: \"boolean\",\n default: false\n },\n minimum: {\n type: \"number\"\n },\n exclusiveMinimum: {\n type: \"boolean\",\n default: false\n },\n maxLength: { $ref: \"#/definitions/positiveInteger\" },\n minLength: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n pattern: {\n type: \"string\",\n format: \"regex\"\n },\n additionalItems: {\n anyOf: [\n { type: \"boolean\" },\n { $ref: \"#\" }\n ],\n default: { }\n },\n items: {\n anyOf: [\n { $ref: \"#\" },\n { $ref: \"#/definitions/schemaArray\" }\n ],\n default: { }\n },\n maxItems: { $ref: \"#/definitions/positiveInteger\" },\n minItems: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n uniqueItems: {\n type: \"boolean\",\n default: false\n },\n maxProperties: { $ref: \"#/definitions/positiveInteger\" },\n minProperties: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n required: { $ref: \"#/definitions/stringArray\" },\n additionalProperties: {\n anyOf: [\n { type: \"boolean\" },\n { $ref: \"#\" }\n ],\n default: { }\n },\n definitions: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n properties: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n patternProperties: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n dependencies: {\n type: \"object\",\n additionalProperties: {\n anyOf: [\n { $ref: \"#\" },\n { $ref: \"#/definitions/stringArray\" }\n ]\n }\n },\n enum: {\n type: \"array\",\n minItems: 1,\n uniqueItems: true\n },\n type: {\n anyOf: [\n { $ref: \"#/definitions/simpleTypes\" },\n {\n type: \"array\",\n items: { $ref: \"#/definitions/simpleTypes\" },\n minItems: 1,\n uniqueItems: true\n }\n ]\n },\n format: { type: \"string\" },\n allOf: { $ref: \"#/definitions/schemaArray\" },\n anyOf: { $ref: \"#/definitions/schemaArray\" },\n oneOf: { $ref: \"#/definitions/schemaArray\" },\n not: { $ref: \"#\" }\n },\n dependencies: {\n exclusiveMaximum: [\"maximum\"],\n exclusiveMinimum: [\"minimum\"]\n },\n default: { }\n};\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport default (additionalOptions = {}) => {\n const ajv = new Ajv({\n meta: false,\n useDefaults: true,\n validateSchema: false,\n missingRefs: \"ignore\",\n verbose: true,\n schemaId: \"auto\",\n ...additionalOptions\n });\n\n ajv.addMetaSchema(metaSchema);\n // eslint-disable-next-line no-underscore-dangle -- part of the API\n ajv._opts.defaultMeta = metaSchema.id;\n\n return ajv;\n};\n","/**\n * @fileoverview Applies default rule options\n * @author JoshuaKGoldberg\n */\n\n/**\n * Check if the variable contains an object strictly rejecting arrays\n * @param {unknown} value an object\n * @returns {boolean} Whether value is an object\n */\nfunction isObjectNotArray(value) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Deeply merges second on top of first, creating a new {} object if needed.\n * @param {T} first Base, default value.\n * @param {U} second User-specified value.\n * @returns {T | U | (T & U)} Merged equivalent of second on top of first.\n */\nfunction deepMergeObjects(first, second) {\n if (second === void 0) {\n return first;\n }\n\n if (!isObjectNotArray(first) || !isObjectNotArray(second)) {\n return second;\n }\n\n const result = { ...first, ...second };\n\n for (const key of Object.keys(second)) {\n if (Object.prototype.propertyIsEnumerable.call(first, key)) {\n result[key] = deepMergeObjects(first[key], second[key]);\n }\n }\n\n return result;\n}\n\n/**\n * Deeply merges second on top of first, creating a new [] array if needed.\n * @param {T[] | undefined} first Base, default values.\n * @param {U[] | undefined} second User-specified values.\n * @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first.\n */\nfunction deepMergeArrays(first, second) {\n if (!first || !second) {\n return second || first || [];\n }\n\n return [\n ...first.map((value, i) => deepMergeObjects(value, second[i])),\n ...second.slice(first.length)\n ];\n}\n\nexport { deepMergeArrays };\n","/**\n * @fileoverview Defines a schema for configs.\n * @author Sylvan Mably\n */\n\nconst baseConfigProperties = {\n $schema: { type: \"string\" },\n env: { type: \"object\" },\n extends: { $ref: \"#/definitions/stringOrStrings\" },\n globals: { type: \"object\" },\n overrides: {\n type: \"array\",\n items: { $ref: \"#/definitions/overrideConfig\" },\n additionalItems: false\n },\n parser: { type: [\"string\", \"null\"] },\n parserOptions: { type: \"object\" },\n plugins: { type: \"array\" },\n processor: { type: \"string\" },\n rules: { type: \"object\" },\n settings: { type: \"object\" },\n noInlineConfig: { type: \"boolean\" },\n reportUnusedDisableDirectives: { type: \"boolean\" },\n\n ecmaFeatures: { type: \"object\" } // deprecated; logs a warning when used\n};\n\nconst configSchema = {\n definitions: {\n stringOrStrings: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"array\",\n items: { type: \"string\" },\n additionalItems: false\n }\n ]\n },\n stringOrStringsRequired: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"array\",\n items: { type: \"string\" },\n additionalItems: false,\n minItems: 1\n }\n ]\n },\n\n // Config at top-level.\n objectConfig: {\n type: \"object\",\n properties: {\n root: { type: \"boolean\" },\n ignorePatterns: { $ref: \"#/definitions/stringOrStrings\" },\n ...baseConfigProperties\n },\n additionalProperties: false\n },\n\n // Config in `overrides`.\n overrideConfig: {\n type: \"object\",\n properties: {\n excludedFiles: { $ref: \"#/definitions/stringOrStrings\" },\n files: { $ref: \"#/definitions/stringOrStringsRequired\" },\n ...baseConfigProperties\n },\n required: [\"files\"],\n additionalProperties: false\n }\n },\n\n $ref: \"#/definitions/objectConfig\"\n};\n\nexport default configSchema;\n","/**\n * @fileoverview Defines environment settings and globals.\n * @author Elan Shanker\n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport globals from \"globals\";\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n/**\n * Get the object that has difference.\n * @param {Record} current The newer object.\n * @param {Record} prev The older object.\n * @returns {Record} The difference object.\n */\nfunction getDiff(current, prev) {\n const retv = {};\n\n for (const [key, value] of Object.entries(current)) {\n if (!Object.hasOwn(prev, key)) {\n retv[key] = value;\n }\n }\n\n return retv;\n}\n\nconst newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...\nconst newGlobals2017 = {\n Atomics: false,\n SharedArrayBuffer: false\n};\nconst newGlobals2020 = {\n BigInt: false,\n BigInt64Array: false,\n BigUint64Array: false,\n globalThis: false\n};\n\nconst newGlobals2021 = {\n AggregateError: false,\n FinalizationRegistry: false,\n WeakRef: false\n};\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/** @type {Map} */\nexport default new Map(Object.entries({\n\n // Language\n builtin: {\n globals: globals.es5\n },\n es6: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 6\n }\n },\n es2015: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 6\n }\n },\n es2016: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 7\n }\n },\n es2017: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 8\n }\n },\n es2018: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 9\n }\n },\n es2019: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 10\n }\n },\n es2020: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },\n parserOptions: {\n ecmaVersion: 11\n }\n },\n es2021: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 12\n }\n },\n es2022: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 13\n }\n },\n es2023: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 14\n }\n },\n es2024: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 15\n }\n },\n\n // Platforms\n browser: {\n globals: globals.browser\n },\n node: {\n globals: globals.node,\n parserOptions: {\n ecmaFeatures: {\n globalReturn: true\n }\n }\n },\n \"shared-node-browser\": {\n globals: globals[\"shared-node-browser\"]\n },\n worker: {\n globals: globals.worker\n },\n serviceworker: {\n globals: globals.serviceworker\n },\n\n // Frameworks\n commonjs: {\n globals: globals.commonjs,\n parserOptions: {\n ecmaFeatures: {\n globalReturn: true\n }\n }\n },\n amd: {\n globals: globals.amd\n },\n mocha: {\n globals: globals.mocha\n },\n jasmine: {\n globals: globals.jasmine\n },\n jest: {\n globals: globals.jest\n },\n phantomjs: {\n globals: globals.phantomjs\n },\n jquery: {\n globals: globals.jquery\n },\n qunit: {\n globals: globals.qunit\n },\n prototypejs: {\n globals: globals.prototypejs\n },\n shelljs: {\n globals: globals.shelljs\n },\n meteor: {\n globals: globals.meteor\n },\n mongo: {\n globals: globals.mongo\n },\n protractor: {\n globals: globals.protractor\n },\n applescript: {\n globals: globals.applescript\n },\n nashorn: {\n globals: globals.nashorn\n },\n atomtest: {\n globals: globals.atomtest\n },\n embertest: {\n globals: globals.embertest\n },\n webextensions: {\n globals: globals.webextensions\n },\n greasemonkey: {\n globals: globals.greasemonkey\n }\n}));\n","/**\n * @fileoverview Validates configs.\n * @author Brandon Mills\n */\n\n/* eslint class-methods-use-this: \"off\" -- not needed in this file */\n\n//------------------------------------------------------------------------------\n// Typedefs\n//------------------------------------------------------------------------------\n\n/** @typedef {import(\"../shared/types\").Rule} Rule */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport util from \"node:util\";\nimport * as ConfigOps from \"./config-ops.js\";\nimport { emitDeprecationWarning } from \"./deprecation-warnings.js\";\nimport ajvOrig from \"./ajv.js\";\nimport { deepMergeArrays } from \"./deep-merge-arrays.js\";\nimport configSchema from \"../../conf/config-schema.js\";\nimport BuiltInEnvironments from \"../../conf/environments.js\";\n\nconst ajv = ajvOrig();\n\nconst ruleValidators = new WeakMap();\nconst noop = Function.prototype;\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\nlet validateSchema;\nconst severityMap = {\n error: 2,\n warn: 1,\n off: 0\n};\n\nconst validated = new WeakSet();\n\n// JSON schema that disallows passing any options\nconst noOptionsSchema = Object.freeze({\n type: \"array\",\n minItems: 0,\n maxItems: 0\n});\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Validator for configuration objects.\n */\nexport default class ConfigValidator {\n constructor({ builtInRules = new Map() } = {}) {\n this.builtInRules = builtInRules;\n }\n\n /**\n * Gets a complete options schema for a rule.\n * @param {Rule} rule A rule object\n * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`.\n * @returns {Object|null} JSON Schema for the rule's options.\n * `null` if rule wasn't passed or its `meta.schema` is `false`.\n */\n getRuleOptionsSchema(rule) {\n if (!rule) {\n return null;\n }\n\n if (!rule.meta) {\n return { ...noOptionsSchema }; // default if `meta.schema` is not specified\n }\n\n const schema = rule.meta.schema;\n\n if (typeof schema === \"undefined\") {\n return { ...noOptionsSchema }; // default if `meta.schema` is not specified\n }\n\n // `schema:false` is an allowed explicit opt-out of options validation for the rule\n if (schema === false) {\n return null;\n }\n\n if (typeof schema !== \"object\" || schema === null) {\n throw new TypeError(\"Rule's `meta.schema` must be an array or object\");\n }\n\n // ESLint-specific array form needs to be converted into a valid JSON Schema definition\n if (Array.isArray(schema)) {\n if (schema.length) {\n return {\n type: \"array\",\n items: schema,\n minItems: 0,\n maxItems: schema.length\n };\n }\n\n // `schema:[]` is an explicit way to specify that the rule does not accept any options\n return { ...noOptionsSchema };\n }\n\n // `schema:` is assumed to be a valid JSON Schema definition\n return schema;\n }\n\n /**\n * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.\n * @param {options} options The given options for the rule.\n * @returns {number|string} The rule's severity value\n * @throws {Error} If the severity is invalid.\n */\n validateRuleSeverity(options) {\n const severity = Array.isArray(options) ? options[0] : options;\n const normSeverity = typeof severity === \"string\" ? severityMap[severity.toLowerCase()] : severity;\n\n if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {\n return normSeverity;\n }\n\n throw new Error(`\\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, \"\\\"\").replace(/\\n/gu, \"\")}').\\n`);\n\n }\n\n /**\n * Validates the non-severity options passed to a rule, based on its schema.\n * @param {{create: Function}} rule The rule to validate\n * @param {Array} localOptions The options for the rule, excluding severity\n * @returns {void}\n * @throws {Error} If the options are invalid.\n */\n validateRuleSchema(rule, localOptions) {\n if (!ruleValidators.has(rule)) {\n try {\n const schema = this.getRuleOptionsSchema(rule);\n\n if (schema) {\n ruleValidators.set(rule, ajv.compile(schema));\n }\n } catch (err) {\n const errorWithCode = new Error(err.message, { cause: err });\n\n errorWithCode.code = \"ESLINT_INVALID_RULE_OPTIONS_SCHEMA\";\n\n throw errorWithCode;\n }\n }\n\n const validateRule = ruleValidators.get(rule);\n\n if (validateRule) {\n const mergedOptions = deepMergeArrays(rule.meta?.defaultOptions, localOptions);\n\n validateRule(mergedOptions);\n\n if (validateRule.errors) {\n throw new Error(validateRule.errors.map(\n error => `\\tValue ${JSON.stringify(error.data)} ${error.message}.\\n`\n ).join(\"\"));\n }\n }\n }\n\n /**\n * Validates a rule's options against its schema.\n * @param {{create: Function}|null} rule The rule that the config is being validated for\n * @param {string} ruleId The rule's unique name.\n * @param {Array|number} options The given options for the rule.\n * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,\n * no source is prepended to the message.\n * @returns {void}\n * @throws {Error} If the options are invalid.\n */\n validateRuleOptions(rule, ruleId, options, source = null) {\n try {\n const severity = this.validateRuleSeverity(options);\n\n if (severity !== 0) {\n this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);\n }\n } catch (err) {\n let enhancedMessage = err.code === \"ESLINT_INVALID_RULE_OPTIONS_SCHEMA\"\n ? `Error while processing options validation schema of rule '${ruleId}': ${err.message}`\n : `Configuration for rule \"${ruleId}\" is invalid:\\n${err.message}`;\n\n if (typeof source === \"string\") {\n enhancedMessage = `${source}:\\n\\t${enhancedMessage}`;\n }\n\n const enhancedError = new Error(enhancedMessage, { cause: err });\n\n if (err.code) {\n enhancedError.code = err.code;\n }\n\n throw enhancedError;\n }\n }\n\n /**\n * Validates an environment object\n * @param {Object} environment The environment config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded environments.\n * @returns {void}\n * @throws {Error} If the environment is invalid.\n */\n validateEnvironment(\n environment,\n source,\n getAdditionalEnv = noop\n ) {\n\n // not having an environment is ok\n if (!environment) {\n return;\n }\n\n Object.keys(environment).forEach(id => {\n const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;\n\n if (!env) {\n const message = `${source}:\\n\\tEnvironment key \"${id}\" is unknown\\n`;\n\n throw new Error(message);\n }\n });\n }\n\n /**\n * Validates a rules config object\n * @param {Object} rulesConfig The rules config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {(ruleId:string) => Object} getAdditionalRule A map from strings to loaded rules\n * @returns {void}\n */\n validateRules(\n rulesConfig,\n source,\n getAdditionalRule = noop\n ) {\n if (!rulesConfig) {\n return;\n }\n\n Object.keys(rulesConfig).forEach(id => {\n const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;\n\n this.validateRuleOptions(rule, id, rulesConfig[id], source);\n });\n }\n\n /**\n * Validates a `globals` section of a config file\n * @param {Object} globalsConfig The `globals` section\n * @param {string|null} source The name of the configuration source to report in the event of an error.\n * @returns {void}\n */\n validateGlobals(globalsConfig, source = null) {\n if (!globalsConfig) {\n return;\n }\n\n Object.entries(globalsConfig)\n .forEach(([configuredGlobal, configuredValue]) => {\n try {\n ConfigOps.normalizeConfigGlobal(configuredValue);\n } catch (err) {\n throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\\n${err.message}`);\n }\n });\n }\n\n /**\n * Validate `processor` configuration.\n * @param {string|undefined} processorName The processor name.\n * @param {string} source The name of config file.\n * @param {(id:string) => Processor} getProcessor The getter of defined processors.\n * @returns {void}\n * @throws {Error} If the processor is invalid.\n */\n validateProcessor(processorName, source, getProcessor) {\n if (processorName && !getProcessor(processorName)) {\n throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);\n }\n }\n\n /**\n * Formats an array of schema validation errors.\n * @param {Array} errors An array of error messages to format.\n * @returns {string} Formatted error message\n */\n formatErrors(errors) {\n return errors.map(error => {\n if (error.keyword === \"additionalProperties\") {\n const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;\n\n return `Unexpected top-level property \"${formattedPropertyPath}\"`;\n }\n if (error.keyword === \"type\") {\n const formattedField = error.dataPath.slice(1);\n const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join(\"/\") : error.schema;\n const formattedValue = JSON.stringify(error.data);\n\n return `Property \"${formattedField}\" is the wrong type (expected ${formattedExpectedType} but got \\`${formattedValue}\\`)`;\n }\n\n const field = error.dataPath[0] === \".\" ? error.dataPath.slice(1) : error.dataPath;\n\n return `\"${field}\" ${error.message}. Value: ${JSON.stringify(error.data)}`;\n }).map(message => `\\t- ${message}.\\n`).join(\"\");\n }\n\n /**\n * Validates the top level properties of the config object.\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @returns {void}\n * @throws {Error} If the config is invalid.\n */\n validateConfigSchema(config, source = null) {\n validateSchema = validateSchema || ajv.compile(configSchema);\n\n if (!validateSchema(config)) {\n throw new Error(`ESLint configuration in ${source} is invalid:\\n${this.formatErrors(validateSchema.errors)}`);\n }\n\n if (Object.hasOwn(config, \"ecmaFeatures\")) {\n emitDeprecationWarning(source, \"ESLINT_LEGACY_ECMAFEATURES\");\n }\n }\n\n /**\n * Validates an entire config object.\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {(ruleId:string) => Object} [getAdditionalRule] A map from strings to loaded rules.\n * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded envs.\n * @returns {void}\n */\n validate(config, source, getAdditionalRule, getAdditionalEnv) {\n this.validateConfigSchema(config, source);\n this.validateRules(config.rules, source, getAdditionalRule);\n this.validateEnvironment(config.env, source, getAdditionalEnv);\n this.validateGlobals(config.globals, source);\n\n for (const override of config.overrides || []) {\n this.validateRules(override.rules, source, getAdditionalRule);\n this.validateEnvironment(override.env, source, getAdditionalEnv);\n this.validateGlobals(config.globals, source);\n }\n }\n\n /**\n * Validate config array object.\n * @param {ConfigArray} configArray The config array to validate.\n * @returns {void}\n */\n validateConfigArray(configArray) {\n const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);\n const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);\n const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);\n\n // Validate.\n for (const element of configArray) {\n if (validated.has(element)) {\n continue;\n }\n validated.add(element);\n\n this.validateEnvironment(element.env, element.name, getPluginEnv);\n this.validateGlobals(element.globals, element.name);\n this.validateProcessor(element.processor, element.name, getPluginProcessor);\n this.validateRules(element.rules, element.name, getPluginRule);\n }\n }\n\n}\n","/**\n * @fileoverview Common helpers for naming of plugins, formatters and configs\n */\n\nconst NAMESPACE_REGEX = /^@.*\\//iu;\n\n/**\n * Brings package name to correct format based on prefix\n * @param {string} name The name of the package.\n * @param {string} prefix Can be either \"eslint-plugin\", \"eslint-config\" or \"eslint-formatter\"\n * @returns {string} Normalized name of the package\n * @private\n */\nfunction normalizePackageName(name, prefix) {\n let normalizedName = name;\n\n /**\n * On Windows, name can come in with Windows slashes instead of Unix slashes.\n * Normalize to Unix first to avoid errors later on.\n * https://github.com/eslint/eslint/issues/5644\n */\n if (normalizedName.includes(\"\\\\\")) {\n normalizedName = normalizedName.replace(/\\\\/gu, \"/\");\n }\n\n if (normalizedName.charAt(0) === \"@\") {\n\n /**\n * it's a scoped package\n * package name is the prefix, or just a username\n */\n const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, \"u\"),\n scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, \"u\");\n\n if (scopedPackageShortcutRegex.test(normalizedName)) {\n normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);\n } else if (!scopedPackageNameRegex.test(normalizedName.split(\"/\")[1])) {\n\n /**\n * for scoped packages, insert the prefix after the first / unless\n * the path is already @scope/eslint or @scope/eslint-xxx-yyy\n */\n normalizedName = normalizedName.replace(/^@([^/]+)\\/(.*)$/u, `@$1/${prefix}-$2`);\n }\n } else if (!normalizedName.startsWith(`${prefix}-`)) {\n normalizedName = `${prefix}-${normalizedName}`;\n }\n\n return normalizedName;\n}\n\n/**\n * Removes the prefix from a fullname.\n * @param {string} fullname The term which may have the prefix.\n * @param {string} prefix The prefix to remove.\n * @returns {string} The term without prefix.\n */\nfunction getShorthandName(fullname, prefix) {\n if (fullname[0] === \"@\") {\n let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, \"u\").exec(fullname);\n\n if (matchResult) {\n return matchResult[1];\n }\n\n matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, \"u\").exec(fullname);\n if (matchResult) {\n return `${matchResult[1]}/${matchResult[2]}`;\n }\n } else if (fullname.startsWith(`${prefix}-`)) {\n return fullname.slice(prefix.length + 1);\n }\n\n return fullname;\n}\n\n/**\n * Gets the scope (namespace) of a term.\n * @param {string} term The term which may have the namespace.\n * @returns {string} The namespace of the term if it has one.\n */\nfunction getNamespaceFromTerm(term) {\n const match = term.match(NAMESPACE_REGEX);\n\n return match ? match[0] : \"\";\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport {\n normalizePackageName,\n getShorthandName,\n getNamespaceFromTerm\n};\n","/**\n * @fileoverview Package exports for @eslint/eslintrc\n * @author Nicholas C. Zakas\n */\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport * as ConfigOps from \"./shared/config-ops.js\";\nimport ConfigValidator from \"./shared/config-validator.js\";\nimport * as naming from \"./shared/naming.js\";\nimport environments from \"../conf/environments.js\";\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\nconst Legacy = {\n environments,\n\n // shared\n ConfigOps,\n ConfigValidator,\n naming\n};\n\nexport {\n Legacy\n};\n"],"names":["path","Ajv","globals","util","BuiltInEnvironments","ConfigOps.normalizeConfigGlobal"],"mappings":";;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,qBAAqB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC;AACtD,IAAI,aAAa,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,KAAK,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AACA;AACA,IAAI,SAAS;AACb,IAAI,eAAe;AACnB,IAAI,MAAM;AACV;;;;"} \ No newline at end of file diff --git a/node_modules/@eslint/eslintrc/dist/eslintrc.cjs b/node_modules/@eslint/eslintrc/dist/eslintrc.cjs new file mode 100644 index 00000000..c50b7208 --- /dev/null +++ b/node_modules/@eslint/eslintrc/dist/eslintrc.cjs @@ -0,0 +1,4456 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var debugOrig = require('debug'); +var fs = require('node:fs'); +var importFresh = require('import-fresh'); +var Module = require('node:module'); +var path = require('node:path'); +var stripComments = require('strip-json-comments'); +var assert = require('node:assert'); +var ignore = require('ignore'); +var util = require('node:util'); +var minimatch = require('minimatch'); +var Ajv = require('ajv'); +var globals = require('globals'); +var os = require('node:os'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var debugOrig__default = /*#__PURE__*/_interopDefaultLegacy(debugOrig); +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); +var importFresh__default = /*#__PURE__*/_interopDefaultLegacy(importFresh); +var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module); +var path__default = /*#__PURE__*/_interopDefaultLegacy(path); +var stripComments__default = /*#__PURE__*/_interopDefaultLegacy(stripComments); +var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert); +var ignore__default = /*#__PURE__*/_interopDefaultLegacy(ignore); +var util__default = /*#__PURE__*/_interopDefaultLegacy(util); +var minimatch__default = /*#__PURE__*/_interopDefaultLegacy(minimatch); +var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv); +var globals__default = /*#__PURE__*/_interopDefaultLegacy(globals); +var os__default = /*#__PURE__*/_interopDefaultLegacy(os); + +/** + * @fileoverview `IgnorePattern` class. + * + * `IgnorePattern` class has the set of glob patterns and the base path. + * + * It provides two static methods. + * + * - `IgnorePattern.createDefaultIgnore(cwd)` + * Create the default predicate function. + * - `IgnorePattern.createIgnore(ignorePatterns)` + * Create the predicate function from multiple `IgnorePattern` objects. + * + * It provides two properties and a method. + * + * - `patterns` + * The glob patterns that ignore to lint. + * - `basePath` + * The base path of the glob patterns. If absolute paths existed in the + * glob patterns, those are handled as relative paths to the base path. + * - `getPatternsRelativeTo(basePath)` + * Get `patterns` as modified for a given base path. It modifies the + * absolute paths in the patterns as prepending the difference of two base + * paths. + * + * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes + * `ignorePatterns` properties. + * + * @author Toru Nagashima + */ + +const debug$3 = debugOrig__default["default"]("eslintrc:ignore-pattern"); + +/** @typedef {ReturnType} Ignore */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Get the path to the common ancestor directory of given paths. + * @param {string[]} sourcePaths The paths to calculate the common ancestor. + * @returns {string} The path to the common ancestor directory. + */ +function getCommonAncestorPath(sourcePaths) { + let result = sourcePaths[0]; + + for (let i = 1; i < sourcePaths.length; ++i) { + const a = result; + const b = sourcePaths[i]; + + // Set the shorter one (it's the common ancestor if one includes the other). + result = a.length < b.length ? a : b; + + // Set the common ancestor. + for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) { + if (a[j] !== b[j]) { + result = a.slice(0, lastSepPos); + break; + } + if (a[j] === path__default["default"].sep) { + lastSepPos = j; + } + } + } + + let resolvedResult = result || path__default["default"].sep; + + // if Windows common ancestor is root of drive must have trailing slash to be absolute. + if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") { + resolvedResult += path__default["default"].sep; + } + return resolvedResult; +} + +/** + * Make relative path. + * @param {string} from The source path to get relative path. + * @param {string} to The destination path to get relative path. + * @returns {string} The relative path. + */ +function relative(from, to) { + const relPath = path__default["default"].relative(from, to); + + if (path__default["default"].sep === "/") { + return relPath; + } + return relPath.split(path__default["default"].sep).join("/"); +} + +/** + * Get the trailing slash if existed. + * @param {string} filePath The path to check. + * @returns {string} The trailing slash if existed. + */ +function dirSuffix(filePath) { + const isDir = ( + filePath.endsWith(path__default["default"].sep) || + (process.platform === "win32" && filePath.endsWith("/")) + ); + + return isDir ? "/" : ""; +} + +const DefaultPatterns = Object.freeze(["/**/node_modules/*"]); +const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]); + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +/** + * Represents a set of glob patterns to ignore against a base path. + */ +class IgnorePattern { + + /** + * The default patterns. + * @type {string[]} + */ + static get DefaultPatterns() { + return DefaultPatterns; + } + + /** + * Create the default predicate function. + * @param {string} cwd The current working directory. + * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}} + * The preficate function. + * The first argument is an absolute path that is checked. + * The second argument is the flag to not ignore dotfiles. + * If the predicate function returned `true`, it means the path should be ignored. + */ + static createDefaultIgnore(cwd) { + return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]); + } + + /** + * Create the predicate function from multiple `IgnorePattern` objects. + * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns. + * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}} + * The preficate function. + * The first argument is an absolute path that is checked. + * The second argument is the flag to not ignore dotfiles. + * If the predicate function returned `true`, it means the path should be ignored. + */ + static createIgnore(ignorePatterns) { + debug$3("Create with: %o", ignorePatterns); + + const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath)); + const patterns = ignorePatterns.flatMap(p => p.getPatternsRelativeTo(basePath)); + const ig = ignore__default["default"]({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]); + const dotIg = ignore__default["default"]({ allowRelativePaths: true }).add(patterns); + + debug$3(" processed: %o", { basePath, patterns }); + + return Object.assign( + (filePath, dot = false) => { + assert__default["default"](path__default["default"].isAbsolute(filePath), "'filePath' should be an absolute path."); + const relPathRaw = relative(basePath, filePath); + const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath)); + const adoptedIg = dot ? dotIg : ig; + const result = relPath !== "" && adoptedIg.ignores(relPath); + + debug$3("Check", { filePath, dot, relativePath: relPath, result }); + return result; + }, + { basePath, patterns } + ); + } + + /** + * Initialize a new `IgnorePattern` instance. + * @param {string[]} patterns The glob patterns that ignore to lint. + * @param {string} basePath The base path of `patterns`. + */ + constructor(patterns, basePath) { + assert__default["default"](path__default["default"].isAbsolute(basePath), "'basePath' should be an absolute path."); + + /** + * The glob patterns that ignore to lint. + * @type {string[]} + */ + this.patterns = patterns; + + /** + * The base path of `patterns`. + * @type {string} + */ + this.basePath = basePath; + + /** + * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`. + * + * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility. + * It's `false` as-is for `ignorePatterns` property in config files. + * @type {boolean} + */ + this.loose = false; + } + + /** + * Get `patterns` as modified for a given base path. It modifies the + * absolute paths in the patterns as prepending the difference of two base + * paths. + * @param {string} newBasePath The base path. + * @returns {string[]} Modifired patterns. + */ + getPatternsRelativeTo(newBasePath) { + assert__default["default"](path__default["default"].isAbsolute(newBasePath), "'newBasePath' should be an absolute path."); + const { basePath, loose, patterns } = this; + + if (newBasePath === basePath) { + return patterns; + } + const prefix = `/${relative(newBasePath, basePath)}`; + + return patterns.map(pattern => { + const negative = pattern.startsWith("!"); + const head = negative ? "!" : ""; + const body = negative ? pattern.slice(1) : pattern; + + if (body.startsWith("/") || body.startsWith("../")) { + return `${head}${prefix}${body}`; + } + return loose ? pattern : `${head}${prefix}/**/${body}`; + }); + } +} + +/** + * @fileoverview `ExtractedConfig` class. + * + * `ExtractedConfig` class expresses a final configuration for a specific file. + * + * It provides one method. + * + * - `toCompatibleObjectAsConfigFileContent()` + * Convert this configuration to the compatible object as the content of + * config files. It converts the loaded parser and plugins to strings. + * `CLIEngine#getConfigForFile(filePath)` method uses this method. + * + * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance. + * + * @author Toru Nagashima + */ + +// For VSCode intellisense +/** @typedef {import("../../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */ +/** @typedef {import("./config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ + +/** + * Check if `xs` starts with `ys`. + * @template T + * @param {T[]} xs The array to check. + * @param {T[]} ys The array that may be the first part of `xs`. + * @returns {boolean} `true` if `xs` starts with `ys`. + */ +function startsWith(xs, ys) { + return xs.length >= ys.length && ys.every((y, i) => y === xs[i]); +} + +/** + * The class for extracted config data. + */ +class ExtractedConfig { + constructor() { + + /** + * The config name what `noInlineConfig` setting came from. + * @type {string} + */ + this.configNameOfNoInlineConfig = ""; + + /** + * Environments. + * @type {Record} + */ + this.env = {}; + + /** + * Global variables. + * @type {Record} + */ + this.globals = {}; + + /** + * The glob patterns that ignore to lint. + * @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined} + */ + this.ignores = void 0; + + /** + * The flag that disables directive comments. + * @type {boolean|undefined} + */ + this.noInlineConfig = void 0; + + /** + * Parser definition. + * @type {DependentParser|null} + */ + this.parser = null; + + /** + * Options for the parser. + * @type {Object} + */ + this.parserOptions = {}; + + /** + * Plugin definitions. + * @type {Record} + */ + this.plugins = {}; + + /** + * Processor ID. + * @type {string|null} + */ + this.processor = null; + + /** + * The flag that reports unused `eslint-disable` directive comments. + * @type {boolean|undefined} + */ + this.reportUnusedDisableDirectives = void 0; + + /** + * Rule settings. + * @type {Record} + */ + this.rules = {}; + + /** + * Shared settings. + * @type {Object} + */ + this.settings = {}; + } + + /** + * Convert this config to the compatible object as a config file content. + * @returns {ConfigData} The converted object. + */ + toCompatibleObjectAsConfigFileContent() { + const { + /* eslint-disable no-unused-vars -- needed to make `config` correct */ + configNameOfNoInlineConfig: _ignore1, + processor: _ignore2, + /* eslint-enable no-unused-vars -- needed to make `config` correct */ + ignores, + ...config + } = this; + + config.parser = config.parser && config.parser.filePath; + config.plugins = Object.keys(config.plugins).filter(Boolean).reverse(); + config.ignorePatterns = ignores ? ignores.patterns : []; + + // Strip the default patterns from `ignorePatterns`. + if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) { + config.ignorePatterns = + config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length); + } + + return config; + } +} + +/** + * @fileoverview `ConfigArray` class. + * + * `ConfigArray` class expresses the full of a configuration. It has the entry + * config file, base config files that were extended, loaded parsers, and loaded + * plugins. + * + * `ConfigArray` class provides three properties and two methods. + * + * - `pluginEnvironments` + * - `pluginProcessors` + * - `pluginRules` + * The `Map` objects that contain the members of all plugins that this + * config array contains. Those map objects don't have mutation methods. + * Those keys are the member ID such as `pluginId/memberName`. + * - `isRoot()` + * If `true` then this configuration has `root:true` property. + * - `extractConfig(filePath)` + * Extract the final configuration for a given file. This means merging + * every config array element which that `criteria` property matched. The + * `filePath` argument must be an absolute path. + * + * `ConfigArrayFactory` provides the loading logic of config files. + * + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Define types for VSCode IntelliSense. +/** @typedef {import("../../shared/types").Environment} Environment */ +/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../../shared/types").RuleConf} RuleConf */ +/** @typedef {import("../../shared/types").Rule} Rule */ +/** @typedef {import("../../shared/types").Plugin} Plugin */ +/** @typedef {import("../../shared/types").Processor} Processor */ +/** @typedef {import("./config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ +/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */ + +/** + * @typedef {Object} ConfigArrayElement + * @property {string} name The name of this config element. + * @property {string} filePath The path to the source file of this config element. + * @property {InstanceType|null} criteria The tester for the `files` and `excludedFiles` of this config element. + * @property {Record|undefined} env The environment settings. + * @property {Record|undefined} globals The global variable settings. + * @property {IgnorePattern|undefined} ignorePattern The ignore patterns. + * @property {boolean|undefined} noInlineConfig The flag that disables directive comments. + * @property {DependentParser|undefined} parser The parser loader. + * @property {Object|undefined} parserOptions The parser options. + * @property {Record|undefined} plugins The plugin loaders. + * @property {string|undefined} processor The processor name to refer plugin's processor. + * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments. + * @property {boolean|undefined} root The flag to express root. + * @property {Record|undefined} rules The rule settings + * @property {Object|undefined} settings The shared settings. + * @property {"config" | "ignore" | "implicit-processor"} type The element type. + */ + +/** + * @typedef {Object} ConfigArrayInternalSlots + * @property {Map} cache The cache to extract configs. + * @property {ReadonlyMap|null} envMap The map from environment ID to environment definition. + * @property {ReadonlyMap|null} processorMap The map from processor ID to environment definition. + * @property {ReadonlyMap|null} ruleMap The map from rule ID to rule definition. + */ + +/** @type {WeakMap} */ +const internalSlotsMap$2 = new class extends WeakMap { + get(key) { + let value = super.get(key); + + if (!value) { + value = { + cache: new Map(), + envMap: null, + processorMap: null, + ruleMap: null + }; + super.set(key, value); + } + + return value; + } +}(); + +/** + * Get the indices which are matched to a given file. + * @param {ConfigArrayElement[]} elements The elements. + * @param {string} filePath The path to a target file. + * @returns {number[]} The indices. + */ +function getMatchedIndices(elements, filePath) { + const indices = []; + + for (let i = elements.length - 1; i >= 0; --i) { + const element = elements[i]; + + if (!element.criteria || (filePath && element.criteria.test(filePath))) { + indices.push(i); + } + } + + return indices; +} + +/** + * Check if a value is a non-null object. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is a non-null object. + */ +function isNonNullObject(x) { + return typeof x === "object" && x !== null; +} + +/** + * Merge two objects. + * + * Assign every property values of `y` to `x` if `x` doesn't have the property. + * If `x`'s property value is an object, it does recursive. + * @param {Object} target The destination to merge + * @param {Object|undefined} source The source to merge. + * @returns {void} + */ +function mergeWithoutOverwrite(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + + if (isNonNullObject(target[key])) { + mergeWithoutOverwrite(target[key], source[key]); + } else if (target[key] === void 0) { + if (isNonNullObject(source[key])) { + target[key] = Array.isArray(source[key]) ? [] : {}; + mergeWithoutOverwrite(target[key], source[key]); + } else if (source[key] !== void 0) { + target[key] = source[key]; + } + } + } +} + +/** + * The error for plugin conflicts. + */ +class PluginConflictError extends Error { + + /** + * Initialize this error object. + * @param {string} pluginId The plugin ID. + * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins. + */ + constructor(pluginId, plugins) { + super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`); + this.messageTemplate = "plugin-conflict"; + this.messageData = { pluginId, plugins }; + } +} + +/** + * Merge plugins. + * `target`'s definition is prior to `source`'s. + * @param {Record} target The destination to merge + * @param {Record|undefined} source The source to merge. + * @returns {void} + * @throws {PluginConflictError} When a plugin was conflicted. + */ +function mergePlugins(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + const targetValue = target[key]; + const sourceValue = source[key]; + + // Adopt the plugin which was found at first. + if (targetValue === void 0) { + if (sourceValue.error) { + throw sourceValue.error; + } + target[key] = sourceValue; + } else if (sourceValue.filePath !== targetValue.filePath) { + throw new PluginConflictError(key, [ + { + filePath: targetValue.filePath, + importerName: targetValue.importerName + }, + { + filePath: sourceValue.filePath, + importerName: sourceValue.importerName + } + ]); + } + } +} + +/** + * Merge rule configs. + * `target`'s definition is prior to `source`'s. + * @param {Record} target The destination to merge + * @param {Record|undefined} source The source to merge. + * @returns {void} + */ +function mergeRuleConfigs(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + const targetDef = target[key]; + const sourceDef = source[key]; + + // Adopt the rule config which was found at first. + if (targetDef === void 0) { + if (Array.isArray(sourceDef)) { + target[key] = [...sourceDef]; + } else { + target[key] = [sourceDef]; + } + + /* + * If the first found rule config is severity only and the current rule + * config has options, merge the severity and the options. + */ + } else if ( + targetDef.length === 1 && + Array.isArray(sourceDef) && + sourceDef.length >= 2 + ) { + targetDef.push(...sourceDef.slice(1)); + } + } +} + +/** + * Create the extracted config. + * @param {ConfigArray} instance The config elements. + * @param {number[]} indices The indices to use. + * @returns {ExtractedConfig} The extracted config. + * @throws {Error} When a plugin is conflicted. + */ +function createConfig(instance, indices) { + const config = new ExtractedConfig(); + const ignorePatterns = []; + + // Merge elements. + for (const index of indices) { + const element = instance[index]; + + // Adopt the parser which was found at first. + if (!config.parser && element.parser) { + if (element.parser.error) { + throw element.parser.error; + } + config.parser = element.parser; + } + + // Adopt the processor which was found at first. + if (!config.processor && element.processor) { + config.processor = element.processor; + } + + // Adopt the noInlineConfig which was found at first. + if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) { + config.noInlineConfig = element.noInlineConfig; + config.configNameOfNoInlineConfig = element.name; + } + + // Adopt the reportUnusedDisableDirectives which was found at first. + if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) { + config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives; + } + + // Collect ignorePatterns + if (element.ignorePattern) { + ignorePatterns.push(element.ignorePattern); + } + + // Merge others. + mergeWithoutOverwrite(config.env, element.env); + mergeWithoutOverwrite(config.globals, element.globals); + mergeWithoutOverwrite(config.parserOptions, element.parserOptions); + mergeWithoutOverwrite(config.settings, element.settings); + mergePlugins(config.plugins, element.plugins); + mergeRuleConfigs(config.rules, element.rules); + } + + // Create the predicate function for ignore patterns. + if (ignorePatterns.length > 0) { + config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse()); + } + + return config; +} + +/** + * Collect definitions. + * @template T, U + * @param {string} pluginId The plugin ID for prefix. + * @param {Record} defs The definitions to collect. + * @param {Map} map The map to output. + * @returns {void} + */ +function collect(pluginId, defs, map) { + if (defs) { + const prefix = pluginId && `${pluginId}/`; + + for (const [key, value] of Object.entries(defs)) { + map.set(`${prefix}${key}`, value); + } + } +} + +/** + * Delete the mutation methods from a given map. + * @param {Map} map The map object to delete. + * @returns {void} + */ +function deleteMutationMethods(map) { + Object.defineProperties(map, { + clear: { configurable: true, value: void 0 }, + delete: { configurable: true, value: void 0 }, + set: { configurable: true, value: void 0 } + }); +} + +/** + * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. + * @param {ConfigArrayElement[]} elements The config elements. + * @param {ConfigArrayInternalSlots} slots The internal slots. + * @returns {void} + */ +function initPluginMemberMaps(elements, slots) { + const processed = new Set(); + + slots.envMap = new Map(); + slots.processorMap = new Map(); + slots.ruleMap = new Map(); + + for (const element of elements) { + if (!element.plugins) { + continue; + } + + for (const [pluginId, value] of Object.entries(element.plugins)) { + const plugin = value.definition; + + if (!plugin || processed.has(pluginId)) { + continue; + } + processed.add(pluginId); + + collect(pluginId, plugin.environments, slots.envMap); + collect(pluginId, plugin.processors, slots.processorMap); + collect(pluginId, plugin.rules, slots.ruleMap); + } + } + + deleteMutationMethods(slots.envMap); + deleteMutationMethods(slots.processorMap); + deleteMutationMethods(slots.ruleMap); +} + +/** + * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. + * @param {ConfigArray} instance The config elements. + * @returns {ConfigArrayInternalSlots} The extracted config. + */ +function ensurePluginMemberMaps(instance) { + const slots = internalSlotsMap$2.get(instance); + + if (!slots.ruleMap) { + initPluginMemberMaps(instance, slots); + } + + return slots; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The Config Array. + * + * `ConfigArray` instance contains all settings, parsers, and plugins. + * You need to call `ConfigArray#extractConfig(filePath)` method in order to + * extract, merge and get only the config data which is related to an arbitrary + * file. + * @extends {Array} + */ +class ConfigArray extends Array { + + /** + * Get the plugin environments. + * The returned map cannot be mutated. + * @type {ReadonlyMap} The plugin environments. + */ + get pluginEnvironments() { + return ensurePluginMemberMaps(this).envMap; + } + + /** + * Get the plugin processors. + * The returned map cannot be mutated. + * @type {ReadonlyMap} The plugin processors. + */ + get pluginProcessors() { + return ensurePluginMemberMaps(this).processorMap; + } + + /** + * Get the plugin rules. + * The returned map cannot be mutated. + * @returns {ReadonlyMap} The plugin rules. + */ + get pluginRules() { + return ensurePluginMemberMaps(this).ruleMap; + } + + /** + * Check if this config has `root` flag. + * @returns {boolean} `true` if this config array is root. + */ + isRoot() { + for (let i = this.length - 1; i >= 0; --i) { + const root = this[i].root; + + if (typeof root === "boolean") { + return root; + } + } + return false; + } + + /** + * Extract the config data which is related to a given file. + * @param {string} filePath The absolute path to the target file. + * @returns {ExtractedConfig} The extracted config data. + */ + extractConfig(filePath) { + const { cache } = internalSlotsMap$2.get(this); + const indices = getMatchedIndices(this, filePath); + const cacheKey = indices.join(","); + + if (!cache.has(cacheKey)) { + cache.set(cacheKey, createConfig(this, indices)); + } + + return cache.get(cacheKey); + } + + /** + * Check if a given path is an additional lint target. + * @param {string} filePath The absolute path to the target file. + * @returns {boolean} `true` if the file is an additional lint target. + */ + isAdditionalTargetPath(filePath) { + for (const { criteria, type } of this) { + if ( + type === "config" && + criteria && + !criteria.endsWithWildcard && + criteria.test(filePath) + ) { + return true; + } + } + return false; + } +} + +/** + * Get the used extracted configs. + * CLIEngine will use this method to collect used deprecated rules. + * @param {ConfigArray} instance The config array object to get. + * @returns {ExtractedConfig[]} The used extracted configs. + * @private + */ +function getUsedExtractedConfigs(instance) { + const { cache } = internalSlotsMap$2.get(instance); + + return Array.from(cache.values()); +} + +/** + * @fileoverview `ConfigDependency` class. + * + * `ConfigDependency` class expresses a loaded parser or plugin. + * + * If the parser or plugin was loaded successfully, it has `definition` property + * and `filePath` property. Otherwise, it has `error` property. + * + * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it + * omits `definition` property. + * + * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers + * or plugins. + * + * @author Toru Nagashima + */ + +/** + * The class is to store parsers or plugins. + * This class hides the loaded object from `JSON.stringify()` and `console.log`. + * @template T + */ +class ConfigDependency { + + /** + * Initialize this instance. + * @param {Object} data The dependency data. + * @param {T} [data.definition] The dependency if the loading succeeded. + * @param {T} [data.original] The original, non-normalized dependency if the loading succeeded. + * @param {Error} [data.error] The error object if the loading failed. + * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded. + * @param {string} data.id The ID of this dependency. + * @param {string} data.importerName The name of the config file which loads this dependency. + * @param {string} data.importerPath The path to the config file which loads this dependency. + */ + constructor({ + definition = null, + original = null, + error = null, + filePath = null, + id, + importerName, + importerPath + }) { + + /** + * The loaded dependency if the loading succeeded. + * @type {T|null} + */ + this.definition = definition; + + /** + * The original dependency as loaded directly from disk if the loading succeeded. + * @type {T|null} + */ + this.original = original; + + /** + * The error object if the loading failed. + * @type {Error|null} + */ + this.error = error; + + /** + * The loaded dependency if the loading succeeded. + * @type {string|null} + */ + this.filePath = filePath; + + /** + * The ID of this dependency. + * @type {string} + */ + this.id = id; + + /** + * The name of the config file which loads this dependency. + * @type {string} + */ + this.importerName = importerName; + + /** + * The path to the config file which loads this dependency. + * @type {string} + */ + this.importerPath = importerPath; + } + + /** + * Converts this instance to a JSON compatible object. + * @returns {Object} a JSON compatible object. + */ + toJSON() { + const obj = this[util__default["default"].inspect.custom](); + + // Display `error.message` (`Error#message` is unenumerable). + if (obj.error instanceof Error) { + obj.error = { ...obj.error, message: obj.error.message }; + } + + return obj; + } + + /** + * Custom inspect method for Node.js `console.log()`. + * @returns {Object} an object to display by `console.log()`. + */ + [util__default["default"].inspect.custom]() { + const { + definition: _ignore1, // eslint-disable-line no-unused-vars -- needed to make `obj` correct + original: _ignore2, // eslint-disable-line no-unused-vars -- needed to make `obj` correct + ...obj + } = this; + + return obj; + } +} + +/** + * @fileoverview `OverrideTester` class. + * + * `OverrideTester` class handles `files` property and `excludedFiles` property + * of `overrides` config. + * + * It provides one method. + * + * - `test(filePath)` + * Test if a file path matches the pair of `files` property and + * `excludedFiles` property. The `filePath` argument must be an absolute + * path. + * + * `ConfigArrayFactory` creates `OverrideTester` objects when it processes + * `overrides` properties. + * + * @author Toru Nagashima + */ + +const { Minimatch } = minimatch__default["default"]; + +const minimatchOpts = { dot: true, matchBase: true }; + +/** + * @typedef {Object} Pattern + * @property {InstanceType[] | null} includes The positive matchers. + * @property {InstanceType[] | null} excludes The negative matchers. + */ + +/** + * Normalize a given pattern to an array. + * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns. + * @returns {string[]|null} Normalized patterns. + * @private + */ +function normalizePatterns(patterns) { + if (Array.isArray(patterns)) { + return patterns.filter(Boolean); + } + if (typeof patterns === "string" && patterns) { + return [patterns]; + } + return []; +} + +/** + * Create the matchers of given patterns. + * @param {string[]} patterns The patterns. + * @returns {InstanceType[] | null} The matchers. + */ +function toMatcher(patterns) { + if (patterns.length === 0) { + return null; + } + return patterns.map(pattern => { + if (/^\.[/\\]/u.test(pattern)) { + return new Minimatch( + pattern.slice(2), + + // `./*.js` should not match with `subdir/foo.js` + { ...minimatchOpts, matchBase: false } + ); + } + return new Minimatch(pattern, minimatchOpts); + }); +} + +/** + * Convert a given matcher to string. + * @param {Pattern} matchers The matchers. + * @returns {string} The string expression of the matcher. + */ +function patternToJson({ includes, excludes }) { + return { + includes: includes && includes.map(m => m.pattern), + excludes: excludes && excludes.map(m => m.pattern) + }; +} + +/** + * The class to test given paths are matched by the patterns. + */ +class OverrideTester { + + /** + * Create a tester with given criteria. + * If there are no criteria, returns `null`. + * @param {string|string[]} files The glob patterns for included files. + * @param {string|string[]} excludedFiles The glob patterns for excluded files. + * @param {string} basePath The path to the base directory to test paths. + * @returns {OverrideTester|null} The created instance or `null`. + * @throws {Error} When invalid patterns are given. + */ + static create(files, excludedFiles, basePath) { + const includePatterns = normalizePatterns(files); + const excludePatterns = normalizePatterns(excludedFiles); + let endsWithWildcard = false; + + if (includePatterns.length === 0) { + return null; + } + + // Rejects absolute paths or relative paths to parents. + for (const pattern of includePatterns) { + if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) { + throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); + } + if (pattern.endsWith("*")) { + endsWithWildcard = true; + } + } + for (const pattern of excludePatterns) { + if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) { + throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); + } + } + + const includes = toMatcher(includePatterns); + const excludes = toMatcher(excludePatterns); + + return new OverrideTester( + [{ includes, excludes }], + basePath, + endsWithWildcard + ); + } + + /** + * Combine two testers by logical and. + * If either of the testers was `null`, returns the other tester. + * The `basePath` property of the two must be the same value. + * @param {OverrideTester|null} a A tester. + * @param {OverrideTester|null} b Another tester. + * @returns {OverrideTester|null} Combined tester. + */ + static and(a, b) { + if (!b) { + return a && new OverrideTester( + a.patterns, + a.basePath, + a.endsWithWildcard + ); + } + if (!a) { + return new OverrideTester( + b.patterns, + b.basePath, + b.endsWithWildcard + ); + } + + assert__default["default"].strictEqual(a.basePath, b.basePath); + return new OverrideTester( + a.patterns.concat(b.patterns), + a.basePath, + a.endsWithWildcard || b.endsWithWildcard + ); + } + + /** + * Initialize this instance. + * @param {Pattern[]} patterns The matchers. + * @param {string} basePath The base path. + * @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`. + */ + constructor(patterns, basePath, endsWithWildcard = false) { + + /** @type {Pattern[]} */ + this.patterns = patterns; + + /** @type {string} */ + this.basePath = basePath; + + /** @type {boolean} */ + this.endsWithWildcard = endsWithWildcard; + } + + /** + * Test if a given path is matched or not. + * @param {string} filePath The absolute path to the target file. + * @returns {boolean} `true` if the path was matched. + * @throws {Error} When invalid `filePath` is given. + */ + test(filePath) { + if (typeof filePath !== "string" || !path__default["default"].isAbsolute(filePath)) { + throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`); + } + const relativePath = path__default["default"].relative(this.basePath, filePath); + + return this.patterns.every(({ includes, excludes }) => ( + (!includes || includes.some(m => m.match(relativePath))) && + (!excludes || !excludes.some(m => m.match(relativePath))) + )); + } + + /** + * Converts this instance to a JSON compatible object. + * @returns {Object} a JSON compatible object. + */ + toJSON() { + if (this.patterns.length === 1) { + return { + ...patternToJson(this.patterns[0]), + basePath: this.basePath + }; + } + return { + AND: this.patterns.map(patternToJson), + basePath: this.basePath + }; + } + + /** + * Custom inspect method for Node.js `console.log()`. + * @returns {Object} an object to display by `console.log()`. + */ + [util__default["default"].inspect.custom]() { + return this.toJSON(); + } +} + +/** + * @fileoverview `ConfigArray` class. + * @author Toru Nagashima + */ + +/** + * @fileoverview Config file operations. This file must be usable in the browser, + * so no Node-specific code can be here. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +const RULE_SEVERITY_STRINGS = ["off", "warn", "error"], + RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => { + map[value] = index; + return map; + }, {}), + VALID_SEVERITIES = new Set([0, 1, 2, "off", "warn", "error"]); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Normalizes the severity value of a rule's configuration to a number + * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally + * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0), + * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array + * whose first element is one of the above values. Strings are matched case-insensitively. + * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0. + */ +function getRuleSeverity(ruleConfig) { + const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (severityValue === 0 || severityValue === 1 || severityValue === 2) { + return severityValue; + } + + if (typeof severityValue === "string") { + return RULE_SEVERITY[severityValue.toLowerCase()] || 0; + } + + return 0; +} + +/** + * Converts old-style severity settings (0, 1, 2) into new-style + * severity settings (off, warn, error) for all rules. Assumption is that severity + * values have already been validated as correct. + * @param {Object} config The config object to normalize. + * @returns {void} + */ +function normalizeToStrings(config) { + + if (config.rules) { + Object.keys(config.rules).forEach(ruleId => { + const ruleConfig = config.rules[ruleId]; + + if (typeof ruleConfig === "number") { + config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0]; + } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") { + ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0]; + } + }); + } +} + +/** + * Determines if the severity for the given rule configuration represents an error. + * @param {int|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} True if the rule represents an error, false if not. + */ +function isErrorSeverity(ruleConfig) { + return getRuleSeverity(ruleConfig) === 2; +} + +/** + * Checks whether a given config has valid severity or not. + * @param {number|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isValidSeverity(ruleConfig) { + let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (typeof severity === "string") { + severity = severity.toLowerCase(); + } + return VALID_SEVERITIES.has(severity); +} + +/** + * Checks whether every rule of a given config has valid severity or not. + * @param {Object} config The configuration for rules. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isEverySeverityValid(config) { + return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId])); +} + +/** + * Normalizes a value for a global in a config + * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in + * a global directive comment + * @returns {("readable"|"writeable"|"off")} The value normalized as a string + * @throws Error if global value is invalid + */ +function normalizeConfigGlobal(configuredValue) { + switch (configuredValue) { + case "off": + return "off"; + + case true: + case "true": + case "writeable": + case "writable": + return "writable"; + + case null: + case false: + case "false": + case "readable": + case "readonly": + return "readonly"; + + default: + throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`); + } +} + +var ConfigOps = { + __proto__: null, + getRuleSeverity: getRuleSeverity, + normalizeToStrings: normalizeToStrings, + isErrorSeverity: isErrorSeverity, + isValidSeverity: isValidSeverity, + isEverySeverityValid: isEverySeverityValid, + normalizeConfigGlobal: normalizeConfigGlobal +}; + +/** + * @fileoverview Provide the function that emits deprecation warnings. + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +// Defitions for deprecation warnings. +const deprecationWarningMessages = { + ESLINT_LEGACY_ECMAFEATURES: + "The 'ecmaFeatures' config file property is deprecated and has no effect.", + ESLINT_PERSONAL_CONFIG_LOAD: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please use a config file per project or the '--config' option.", + ESLINT_PERSONAL_CONFIG_SUPPRESS: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please remove it or add 'root:true' to the config files in your " + + "projects in order to avoid loading '~/.eslintrc.*' accidentally." +}; + +const sourceFileErrorCache = new Set(); + +/** + * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted + * for each unique file path, but repeated invocations with the same file path have no effect. + * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active. + * @param {string} source The name of the configuration source to report the warning for. + * @param {string} errorCode The warning message to show. + * @returns {void} + */ +function emitDeprecationWarning(source, errorCode) { + const cacheKey = JSON.stringify({ source, errorCode }); + + if (sourceFileErrorCache.has(cacheKey)) { + return; + } + sourceFileErrorCache.add(cacheKey); + + const rel = path__default["default"].relative(process.cwd(), source); + const message = deprecationWarningMessages[errorCode]; + + process.emitWarning( + `${message} (found in "${rel}")`, + "DeprecationWarning", + errorCode + ); +} + +/** + * @fileoverview The instance of Ajv validator. + * @author Evgeny Poberezkin + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/* + * Copied from ajv/lib/refs/json-schema-draft-04.json + * The MIT License (MIT) + * Copyright (c) 2015-2017 Evgeny Poberezkin + */ +const metaSchema = { + id: "http://json-schema.org/draft-04/schema#", + $schema: "http://json-schema.org/draft-04/schema#", + description: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + positiveInteger: { + type: "integer", + minimum: 0 + }, + positiveIntegerDefault0: { + allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + minItems: 1, + uniqueItems: true + } + }, + type: "object", + properties: { + id: { + type: "string" + }, + $schema: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: { }, + multipleOf: { + type: "number", + minimum: 0, + exclusiveMinimum: true + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "boolean", + default: false + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "boolean", + default: false + }, + maxLength: { $ref: "#/definitions/positiveInteger" }, + minLength: { $ref: "#/definitions/positiveIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + items: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/schemaArray" } + ], + default: { } + }, + maxItems: { $ref: "#/definitions/positiveInteger" }, + minItems: { $ref: "#/definitions/positiveIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + maxProperties: { $ref: "#/definitions/positiveInteger" }, + minProperties: { $ref: "#/definitions/positiveIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/stringArray" } + ] + } + }, + enum: { + type: "array", + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + dependencies: { + exclusiveMaximum: ["maximum"], + exclusiveMinimum: ["minimum"] + }, + default: { } +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +var ajvOrig = (additionalOptions = {}) => { + const ajv = new Ajv__default["default"]({ + meta: false, + useDefaults: true, + validateSchema: false, + missingRefs: "ignore", + verbose: true, + schemaId: "auto", + ...additionalOptions + }); + + ajv.addMetaSchema(metaSchema); + // eslint-disable-next-line no-underscore-dangle -- part of the API + ajv._opts.defaultMeta = metaSchema.id; + + return ajv; +}; + +/** + * @fileoverview Applies default rule options + * @author JoshuaKGoldberg + */ + +/** + * Check if the variable contains an object strictly rejecting arrays + * @param {unknown} value an object + * @returns {boolean} Whether value is an object + */ +function isObjectNotArray(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Deeply merges second on top of first, creating a new {} object if needed. + * @param {T} first Base, default value. + * @param {U} second User-specified value. + * @returns {T | U | (T & U)} Merged equivalent of second on top of first. + */ +function deepMergeObjects(first, second) { + if (second === void 0) { + return first; + } + + if (!isObjectNotArray(first) || !isObjectNotArray(second)) { + return second; + } + + const result = { ...first, ...second }; + + for (const key of Object.keys(second)) { + if (Object.prototype.propertyIsEnumerable.call(first, key)) { + result[key] = deepMergeObjects(first[key], second[key]); + } + } + + return result; +} + +/** + * Deeply merges second on top of first, creating a new [] array if needed. + * @param {T[] | undefined} first Base, default values. + * @param {U[] | undefined} second User-specified values. + * @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first. + */ +function deepMergeArrays(first, second) { + if (!first || !second) { + return second || first || []; + } + + return [ + ...first.map((value, i) => deepMergeObjects(value, second[i])), + ...second.slice(first.length) + ]; +} + +/** + * @fileoverview Defines a schema for configs. + * @author Sylvan Mably + */ + +const baseConfigProperties = { + $schema: { type: "string" }, + env: { type: "object" }, + extends: { $ref: "#/definitions/stringOrStrings" }, + globals: { type: "object" }, + overrides: { + type: "array", + items: { $ref: "#/definitions/overrideConfig" }, + additionalItems: false + }, + parser: { type: ["string", "null"] }, + parserOptions: { type: "object" }, + plugins: { type: "array" }, + processor: { type: "string" }, + rules: { type: "object" }, + settings: { type: "object" }, + noInlineConfig: { type: "boolean" }, + reportUnusedDisableDirectives: { type: "boolean" }, + + ecmaFeatures: { type: "object" } // deprecated; logs a warning when used +}; + +const configSchema = { + definitions: { + stringOrStrings: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false + } + ] + }, + stringOrStringsRequired: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false, + minItems: 1 + } + ] + }, + + // Config at top-level. + objectConfig: { + type: "object", + properties: { + root: { type: "boolean" }, + ignorePatterns: { $ref: "#/definitions/stringOrStrings" }, + ...baseConfigProperties + }, + additionalProperties: false + }, + + // Config in `overrides`. + overrideConfig: { + type: "object", + properties: { + excludedFiles: { $ref: "#/definitions/stringOrStrings" }, + files: { $ref: "#/definitions/stringOrStringsRequired" }, + ...baseConfigProperties + }, + required: ["files"], + additionalProperties: false + } + }, + + $ref: "#/definitions/objectConfig" +}; + +/** + * @fileoverview Defines environment settings and globals. + * @author Elan Shanker + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Get the object that has difference. + * @param {Record} current The newer object. + * @param {Record} prev The older object. + * @returns {Record} The difference object. + */ +function getDiff(current, prev) { + const retv = {}; + + for (const [key, value] of Object.entries(current)) { + if (!Object.hasOwn(prev, key)) { + retv[key] = value; + } + } + + return retv; +} + +const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ... +const newGlobals2017 = { + Atomics: false, + SharedArrayBuffer: false +}; +const newGlobals2020 = { + BigInt: false, + BigInt64Array: false, + BigUint64Array: false, + globalThis: false +}; + +const newGlobals2021 = { + AggregateError: false, + FinalizationRegistry: false, + WeakRef: false +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** @type {Map} */ +var environments = new Map(Object.entries({ + + // Language + builtin: { + globals: globals__default["default"].es5 + }, + es6: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2015: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2016: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 7 + } + }, + es2017: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 8 + } + }, + es2018: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 9 + } + }, + es2019: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 10 + } + }, + es2020: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 }, + parserOptions: { + ecmaVersion: 11 + } + }, + es2021: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 12 + } + }, + es2022: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 13 + } + }, + es2023: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 14 + } + }, + es2024: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 15 + } + }, + + // Platforms + browser: { + globals: globals__default["default"].browser + }, + node: { + globals: globals__default["default"].node, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + "shared-node-browser": { + globals: globals__default["default"]["shared-node-browser"] + }, + worker: { + globals: globals__default["default"].worker + }, + serviceworker: { + globals: globals__default["default"].serviceworker + }, + + // Frameworks + commonjs: { + globals: globals__default["default"].commonjs, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + amd: { + globals: globals__default["default"].amd + }, + mocha: { + globals: globals__default["default"].mocha + }, + jasmine: { + globals: globals__default["default"].jasmine + }, + jest: { + globals: globals__default["default"].jest + }, + phantomjs: { + globals: globals__default["default"].phantomjs + }, + jquery: { + globals: globals__default["default"].jquery + }, + qunit: { + globals: globals__default["default"].qunit + }, + prototypejs: { + globals: globals__default["default"].prototypejs + }, + shelljs: { + globals: globals__default["default"].shelljs + }, + meteor: { + globals: globals__default["default"].meteor + }, + mongo: { + globals: globals__default["default"].mongo + }, + protractor: { + globals: globals__default["default"].protractor + }, + applescript: { + globals: globals__default["default"].applescript + }, + nashorn: { + globals: globals__default["default"].nashorn + }, + atomtest: { + globals: globals__default["default"].atomtest + }, + embertest: { + globals: globals__default["default"].embertest + }, + webextensions: { + globals: globals__default["default"].webextensions + }, + greasemonkey: { + globals: globals__default["default"].greasemonkey + } +})); + +/** + * @fileoverview Validates configs. + * @author Brandon Mills + */ + +const ajv = ajvOrig(); + +const ruleValidators = new WeakMap(); +const noop = Function.prototype; + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ +let validateSchema; +const severityMap = { + error: 2, + warn: 1, + off: 0 +}; + +const validated = new WeakSet(); + +// JSON schema that disallows passing any options +const noOptionsSchema = Object.freeze({ + type: "array", + minItems: 0, + maxItems: 0 +}); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Validator for configuration objects. + */ +class ConfigValidator { + constructor({ builtInRules = new Map() } = {}) { + this.builtInRules = builtInRules; + } + + /** + * Gets a complete options schema for a rule. + * @param {Rule} rule A rule object + * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`. + * @returns {Object|null} JSON Schema for the rule's options. + * `null` if rule wasn't passed or its `meta.schema` is `false`. + */ + getRuleOptionsSchema(rule) { + if (!rule) { + return null; + } + + if (!rule.meta) { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + const schema = rule.meta.schema; + + if (typeof schema === "undefined") { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + // `schema:false` is an allowed explicit opt-out of options validation for the rule + if (schema === false) { + return null; + } + + if (typeof schema !== "object" || schema === null) { + throw new TypeError("Rule's `meta.schema` must be an array or object"); + } + + // ESLint-specific array form needs to be converted into a valid JSON Schema definition + if (Array.isArray(schema)) { + if (schema.length) { + return { + type: "array", + items: schema, + minItems: 0, + maxItems: schema.length + }; + } + + // `schema:[]` is an explicit way to specify that the rule does not accept any options + return { ...noOptionsSchema }; + } + + // `schema:` is assumed to be a valid JSON Schema definition + return schema; + } + + /** + * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid. + * @param {options} options The given options for the rule. + * @returns {number|string} The rule's severity value + * @throws {Error} If the severity is invalid. + */ + validateRuleSeverity(options) { + const severity = Array.isArray(options) ? options[0] : options; + const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity; + + if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) { + return normSeverity; + } + + throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`); + + } + + /** + * Validates the non-severity options passed to a rule, based on its schema. + * @param {{create: Function}} rule The rule to validate + * @param {Array} localOptions The options for the rule, excluding severity + * @returns {void} + * @throws {Error} If the options are invalid. + */ + validateRuleSchema(rule, localOptions) { + if (!ruleValidators.has(rule)) { + try { + const schema = this.getRuleOptionsSchema(rule); + + if (schema) { + ruleValidators.set(rule, ajv.compile(schema)); + } + } catch (err) { + const errorWithCode = new Error(err.message, { cause: err }); + + errorWithCode.code = "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"; + + throw errorWithCode; + } + } + + const validateRule = ruleValidators.get(rule); + + if (validateRule) { + const mergedOptions = deepMergeArrays(rule.meta?.defaultOptions, localOptions); + + validateRule(mergedOptions); + + if (validateRule.errors) { + throw new Error(validateRule.errors.map( + error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n` + ).join("")); + } + } + } + + /** + * Validates a rule's options against its schema. + * @param {{create: Function}|null} rule The rule that the config is being validated for + * @param {string} ruleId The rule's unique name. + * @param {Array|number} options The given options for the rule. + * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined, + * no source is prepended to the message. + * @returns {void} + * @throws {Error} If the options are invalid. + */ + validateRuleOptions(rule, ruleId, options, source = null) { + try { + const severity = this.validateRuleSeverity(options); + + if (severity !== 0) { + this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []); + } + } catch (err) { + let enhancedMessage = err.code === "ESLINT_INVALID_RULE_OPTIONS_SCHEMA" + ? `Error while processing options validation schema of rule '${ruleId}': ${err.message}` + : `Configuration for rule "${ruleId}" is invalid:\n${err.message}`; + + if (typeof source === "string") { + enhancedMessage = `${source}:\n\t${enhancedMessage}`; + } + + const enhancedError = new Error(enhancedMessage, { cause: err }); + + if (err.code) { + enhancedError.code = err.code; + } + + throw enhancedError; + } + } + + /** + * Validates an environment object + * @param {Object} environment The environment config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded environments. + * @returns {void} + * @throws {Error} If the environment is invalid. + */ + validateEnvironment( + environment, + source, + getAdditionalEnv = noop + ) { + + // not having an environment is ok + if (!environment) { + return; + } + + Object.keys(environment).forEach(id => { + const env = getAdditionalEnv(id) || environments.get(id) || null; + + if (!env) { + const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`; + + throw new Error(message); + } + }); + } + + /** + * Validates a rules config object + * @param {Object} rulesConfig The rules config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(ruleId:string) => Object} getAdditionalRule A map from strings to loaded rules + * @returns {void} + */ + validateRules( + rulesConfig, + source, + getAdditionalRule = noop + ) { + if (!rulesConfig) { + return; + } + + Object.keys(rulesConfig).forEach(id => { + const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null; + + this.validateRuleOptions(rule, id, rulesConfig[id], source); + }); + } + + /** + * Validates a `globals` section of a config file + * @param {Object} globalsConfig The `globals` section + * @param {string|null} source The name of the configuration source to report in the event of an error. + * @returns {void} + */ + validateGlobals(globalsConfig, source = null) { + if (!globalsConfig) { + return; + } + + Object.entries(globalsConfig) + .forEach(([configuredGlobal, configuredValue]) => { + try { + normalizeConfigGlobal(configuredValue); + } catch (err) { + throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`); + } + }); + } + + /** + * Validate `processor` configuration. + * @param {string|undefined} processorName The processor name. + * @param {string} source The name of config file. + * @param {(id:string) => Processor} getProcessor The getter of defined processors. + * @returns {void} + * @throws {Error} If the processor is invalid. + */ + validateProcessor(processorName, source, getProcessor) { + if (processorName && !getProcessor(processorName)) { + throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`); + } + } + + /** + * Formats an array of schema validation errors. + * @param {Array} errors An array of error messages to format. + * @returns {string} Formatted error message + */ + formatErrors(errors) { + return errors.map(error => { + if (error.keyword === "additionalProperties") { + const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty; + + return `Unexpected top-level property "${formattedPropertyPath}"`; + } + if (error.keyword === "type") { + const formattedField = error.dataPath.slice(1); + const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema; + const formattedValue = JSON.stringify(error.data); + + return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`; + } + + const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; + + return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`; + }).map(message => `\t- ${message}.\n`).join(""); + } + + /** + * Validates the top level properties of the config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @returns {void} + * @throws {Error} If the config is invalid. + */ + validateConfigSchema(config, source = null) { + validateSchema = validateSchema || ajv.compile(configSchema); + + if (!validateSchema(config)) { + throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`); + } + + if (Object.hasOwn(config, "ecmaFeatures")) { + emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES"); + } + } + + /** + * Validates an entire config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(ruleId:string) => Object} [getAdditionalRule] A map from strings to loaded rules. + * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded envs. + * @returns {void} + */ + validate(config, source, getAdditionalRule, getAdditionalEnv) { + this.validateConfigSchema(config, source); + this.validateRules(config.rules, source, getAdditionalRule); + this.validateEnvironment(config.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + + for (const override of config.overrides || []) { + this.validateRules(override.rules, source, getAdditionalRule); + this.validateEnvironment(override.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + } + } + + /** + * Validate config array object. + * @param {ConfigArray} configArray The config array to validate. + * @returns {void} + */ + validateConfigArray(configArray) { + const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments); + const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors); + const getPluginRule = Map.prototype.get.bind(configArray.pluginRules); + + // Validate. + for (const element of configArray) { + if (validated.has(element)) { + continue; + } + validated.add(element); + + this.validateEnvironment(element.env, element.name, getPluginEnv); + this.validateGlobals(element.globals, element.name); + this.validateProcessor(element.processor, element.name, getPluginProcessor); + this.validateRules(element.rules, element.name, getPluginRule); + } + } + +} + +/** + * @fileoverview Common helpers for naming of plugins, formatters and configs + */ + +const NAMESPACE_REGEX = /^@.*\//iu; + +/** + * Brings package name to correct format based on prefix + * @param {string} name The name of the package. + * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter" + * @returns {string} Normalized name of the package + * @private + */ +function normalizePackageName(name, prefix) { + let normalizedName = name; + + /** + * On Windows, name can come in with Windows slashes instead of Unix slashes. + * Normalize to Unix first to avoid errors later on. + * https://github.com/eslint/eslint/issues/5644 + */ + if (normalizedName.includes("\\")) { + normalizedName = normalizedName.replace(/\\/gu, "/"); + } + + if (normalizedName.charAt(0) === "@") { + + /** + * it's a scoped package + * package name is the prefix, or just a username + */ + const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"), + scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u"); + + if (scopedPackageShortcutRegex.test(normalizedName)) { + normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`); + } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) { + + /** + * for scoped packages, insert the prefix after the first / unless + * the path is already @scope/eslint or @scope/eslint-xxx-yyy + */ + normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`); + } + } else if (!normalizedName.startsWith(`${prefix}-`)) { + normalizedName = `${prefix}-${normalizedName}`; + } + + return normalizedName; +} + +/** + * Removes the prefix from a fullname. + * @param {string} fullname The term which may have the prefix. + * @param {string} prefix The prefix to remove. + * @returns {string} The term without prefix. + */ +function getShorthandName(fullname, prefix) { + if (fullname[0] === "@") { + let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname); + + if (matchResult) { + return matchResult[1]; + } + + matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname); + if (matchResult) { + return `${matchResult[1]}/${matchResult[2]}`; + } + } else if (fullname.startsWith(`${prefix}-`)) { + return fullname.slice(prefix.length + 1); + } + + return fullname; +} + +/** + * Gets the scope (namespace) of a term. + * @param {string} term The term which may have the namespace. + * @returns {string} The namespace of the term if it has one. + */ +function getNamespaceFromTerm(term) { + const match = term.match(NAMESPACE_REGEX); + + return match ? match[0] : ""; +} + +var naming = { + __proto__: null, + normalizePackageName: normalizePackageName, + getShorthandName: getShorthandName, + getNamespaceFromTerm: getNamespaceFromTerm +}; + +/** + * Utility for resolving a module relative to another module + * @author Teddy Katz + */ + +/* + * `Module.createRequire` is added in v12.2.0. It supports URL as well. + * We only support the case where the argument is a filepath, not a URL. + */ +const createRequire = Module__default["default"].createRequire; + +/** + * Resolves a Node module relative to another module + * @param {string} moduleName The name of a Node module, or a path to a Node module. + * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be + * a file rather than a directory, but the file need not actually exist. + * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath` + * @throws {Error} When the module cannot be resolved. + */ +function resolve(moduleName, relativeToPath) { + try { + return createRequire(relativeToPath).resolve(moduleName); + } catch (error) { + + // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future. + if ( + typeof error === "object" && + error !== null && + error.code === "MODULE_NOT_FOUND" && + !error.requireStack && + error.message.includes(moduleName) + ) { + error.message += `\nRequire stack:\n- ${relativeToPath}`; + } + throw error; + } +} + +var ModuleResolver = { + __proto__: null, + resolve: resolve +}; + +/** + * @fileoverview The factory of `ConfigArray` objects. + * + * This class provides methods to create `ConfigArray` instance. + * + * - `create(configData, options)` + * Create a `ConfigArray` instance from a config data. This is to handle CLI + * options except `--config`. + * - `loadFile(filePath, options)` + * Create a `ConfigArray` instance from a config file. This is to handle + * `--config` option. If the file was not found, throws the following error: + * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error. + * - If the filename was `package.json`, an IO error or an + * `ESLINT_CONFIG_FIELD_NOT_FOUND` error. + * - Otherwise, an IO error such as `ENOENT`. + * - `loadInDirectory(directoryPath, options)` + * Create a `ConfigArray` instance from a config file which is on a given + * directory. This tries to load `.eslintrc.*` or `package.json`. If not + * found, returns an empty `ConfigArray`. + * - `loadESLintIgnore(filePath)` + * Create a `ConfigArray` instance from a config file that is `.eslintignore` + * format. This is to handle `--ignore-path` option. + * - `loadDefaultESLintIgnore()` + * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in + * the current working directory. + * + * `ConfigArrayFactory` class has the responsibility that loads configuration + * files, including loading `extends`, `parser`, and `plugins`. The created + * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`. + * + * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class + * handles cascading and hierarchy. + * + * @author Toru Nagashima + */ + +const require$1 = Module.createRequire(require('url').pathToFileURL(__filename).toString()); + +const debug$2 = debugOrig__default["default"]("eslintrc:config-array-factory"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const configFilenames = [ + ".eslintrc.js", + ".eslintrc.cjs", + ".eslintrc.yaml", + ".eslintrc.yml", + ".eslintrc.json", + ".eslintrc", + "package.json" +]; + +// Define types for VSCode IntelliSense. +/** @typedef {import("./shared/types").ConfigData} ConfigData */ +/** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */ +/** @typedef {import("./shared/types").Parser} Parser */ +/** @typedef {import("./shared/types").Plugin} Plugin */ +/** @typedef {import("./shared/types").Rule} Rule */ +/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */ +/** @typedef {ConfigArray[0]} ConfigArrayElement */ + +/** + * @typedef {Object} ConfigArrayFactoryOptions + * @property {Map} [additionalPluginPool] The map for additional plugins. + * @property {string} [cwd] The path to the current working directory. + * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** + * @typedef {Object} ConfigArrayFactoryInternalSlots + * @property {Map} additionalPluginPool The map for additional plugins. + * @property {string} cwd The path to the current working directory. + * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** + * @typedef {Object} ConfigArrayFactoryLoadingContext + * @property {string} filePath The path to the current configuration. + * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @property {string} name The name of the current configuration. + * @property {string} pluginBasePath The base path to resolve plugins. + * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors. + */ + +/** + * @typedef {Object} ConfigArrayFactoryLoadingContext + * @property {string} filePath The path to the current configuration. + * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @property {string} name The name of the current configuration. + * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors. + */ + +/** @type {WeakMap} */ +const internalSlotsMap$1 = new WeakMap(); + +/** @type {WeakMap} */ +const normalizedPlugins = new WeakMap(); + +/** + * Check if a given string is a file path. + * @param {string} nameOrPath A module name or file path. + * @returns {boolean} `true` if the `nameOrPath` is a file path. + */ +function isFilePath(nameOrPath) { + return ( + /^\.{1,2}[/\\]/u.test(nameOrPath) || + path__default["default"].isAbsolute(nameOrPath) + ); +} + +/** + * Convenience wrapper for synchronously reading file contents. + * @param {string} filePath The filename to read. + * @returns {string} The file contents, with the BOM removed. + * @private + */ +function readFile(filePath) { + return fs__default["default"].readFileSync(filePath, "utf8").replace(/^\ufeff/u, ""); +} + +/** + * Loads a YAML configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadYAMLConfigFile(filePath) { + debug$2(`Loading YAML config file: ${filePath}`); + + // lazy load YAML to improve performance when not used + const yaml = require$1("js-yaml"); + + try { + + // empty YAML file can be null, so always use + return yaml.load(readFile(filePath)) || {}; + } catch (e) { + debug$2(`Error reading YAML file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a JSON configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadJSONConfigFile(filePath) { + debug$2(`Loading JSON config file: ${filePath}`); + + try { + return JSON.parse(stripComments__default["default"](readFile(filePath))); + } catch (e) { + debug$2(`Error reading JSON file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + e.messageTemplate = "failed-to-read-json"; + e.messageData = { + path: filePath, + message: e.message + }; + throw e; + } +} + +/** + * Loads a legacy (.eslintrc) configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadLegacyConfigFile(filePath) { + debug$2(`Loading legacy config file: ${filePath}`); + + // lazy load YAML to improve performance when not used + const yaml = require$1("js-yaml"); + + try { + return yaml.load(stripComments__default["default"](readFile(filePath))) || /* istanbul ignore next */ {}; + } catch (e) { + debug$2("Error reading YAML file: %s\n%o", filePath, e); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a JavaScript configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadJSConfigFile(filePath) { + debug$2(`Loading JS config file: ${filePath}`); + try { + return importFresh__default["default"](filePath); + } catch (e) { + debug$2(`Error reading JavaScript file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a configuration from a package.json file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadPackageJSONConfigFile(filePath) { + debug$2(`Loading package.json config file: ${filePath}`); + try { + const packageData = loadJSONConfigFile(filePath); + + if (!Object.hasOwn(packageData, "eslintConfig")) { + throw Object.assign( + new Error("package.json file doesn't have 'eslintConfig' field."), + { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" } + ); + } + + return packageData.eslintConfig; + } catch (e) { + debug$2(`Error reading package.json file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a `.eslintignore` from a file. + * @param {string} filePath The filename to load. + * @returns {string[]} The ignore patterns from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadESLintIgnoreFile(filePath) { + debug$2(`Loading .eslintignore file: ${filePath}`); + + try { + return readFile(filePath) + .split(/\r?\n/gu) + .filter(line => line.trim() !== "" && !line.startsWith("#")); + } catch (e) { + debug$2(`Error reading .eslintignore file: ${filePath}`); + e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Creates an error to notify about a missing config to extend from. + * @param {string} configName The name of the missing config. + * @param {string} importerName The name of the config that imported the missing config + * @param {string} messageTemplate The text template to source error strings from. + * @returns {Error} The error object to throw + * @private + */ +function configInvalidError(configName, importerName, messageTemplate) { + return Object.assign( + new Error(`Failed to load config "${configName}" to extend from.`), + { + messageTemplate, + messageData: { configName, importerName } + } + ); +} + +/** + * Loads a configuration file regardless of the source. Inspects the file path + * to determine the correctly way to load the config file. + * @param {string} filePath The path to the configuration. + * @returns {ConfigData|null} The configuration information. + * @private + */ +function loadConfigFile(filePath) { + switch (path__default["default"].extname(filePath)) { + case ".js": + case ".cjs": + return loadJSConfigFile(filePath); + + case ".json": + if (path__default["default"].basename(filePath) === "package.json") { + return loadPackageJSONConfigFile(filePath); + } + return loadJSONConfigFile(filePath); + + case ".yaml": + case ".yml": + return loadYAMLConfigFile(filePath); + + default: + return loadLegacyConfigFile(filePath); + } +} + +/** + * Write debug log. + * @param {string} request The requested module name. + * @param {string} relativeTo The file path to resolve the request relative to. + * @param {string} filePath The resolved file path. + * @returns {void} + */ +function writeDebugLogForLoading(request, relativeTo, filePath) { + /* istanbul ignore next */ + if (debug$2.enabled) { + let nameAndVersion = null; // eslint-disable-line no-useless-assignment -- known bug in the rule + + try { + const packageJsonPath = resolve( + `${request}/package.json`, + relativeTo + ); + const { version = "unknown" } = require$1(packageJsonPath); + + nameAndVersion = `${request}@${version}`; + } catch (error) { + debug$2("package.json was not found:", error.message); + nameAndVersion = request; + } + + debug$2("Loaded: %s (%s)", nameAndVersion, filePath); + } +} + +/** + * Create a new context with default values. + * @param {ConfigArrayFactoryInternalSlots} slots The internal slots. + * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`. + * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`. + * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string. + * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`. + * @returns {ConfigArrayFactoryLoadingContext} The created context. + */ +function createContext( + { cwd, resolvePluginsRelativeTo }, + providedType, + providedName, + providedFilePath, + providedMatchBasePath +) { + const filePath = providedFilePath + ? path__default["default"].resolve(cwd, providedFilePath) + : ""; + const matchBasePath = + (providedMatchBasePath && path__default["default"].resolve(cwd, providedMatchBasePath)) || + (filePath && path__default["default"].dirname(filePath)) || + cwd; + const name = + providedName || + (filePath && path__default["default"].relative(cwd, filePath)) || + ""; + const pluginBasePath = + resolvePluginsRelativeTo || + (filePath && path__default["default"].dirname(filePath)) || + cwd; + const type = providedType || "config"; + + return { filePath, matchBasePath, name, pluginBasePath, type }; +} + +/** + * Normalize a given plugin. + * - Ensure the object to have four properties: configs, environments, processors, and rules. + * - Ensure the object to not have other properties. + * @param {Plugin} plugin The plugin to normalize. + * @returns {Plugin} The normalized plugin. + */ +function normalizePlugin(plugin) { + + // first check the cache + let normalizedPlugin = normalizedPlugins.get(plugin); + + if (normalizedPlugin) { + return normalizedPlugin; + } + + normalizedPlugin = { + configs: plugin.configs || {}, + environments: plugin.environments || {}, + processors: plugin.processors || {}, + rules: plugin.rules || {} + }; + + // save the reference for later + normalizedPlugins.set(plugin, normalizedPlugin); + + return normalizedPlugin; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The factory of `ConfigArray` objects. + */ +class ConfigArrayFactory { + + /** + * Initialize this instance. + * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins. + */ + constructor({ + additionalPluginPool = new Map(), + cwd = process.cwd(), + resolvePluginsRelativeTo, + builtInRules, + resolver = ModuleResolver, + eslintAllPath, + getEslintAllConfig, + eslintRecommendedPath, + getEslintRecommendedConfig + } = {}) { + internalSlotsMap$1.set(this, { + additionalPluginPool, + cwd, + resolvePluginsRelativeTo: + resolvePluginsRelativeTo && + path__default["default"].resolve(cwd, resolvePluginsRelativeTo), + builtInRules, + resolver, + eslintAllPath, + getEslintAllConfig, + eslintRecommendedPath, + getEslintRecommendedConfig + }); + } + + /** + * Create `ConfigArray` instance from a config data. + * @param {ConfigData|null} configData The config data to create. + * @param {Object} [options] The options. + * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @param {string} [options.filePath] The path to this config data. + * @param {string} [options.name] The config name. + * @returns {ConfigArray} Loaded config. + */ + create(configData, { basePath, filePath, name } = {}) { + if (!configData) { + return new ConfigArray(); + } + + const slots = internalSlotsMap$1.get(this); + const ctx = createContext(slots, "config", name, filePath, basePath); + const elements = this._normalizeConfigData(configData, ctx); + + return new ConfigArray(...elements); + } + + /** + * Load a config file. + * @param {string} filePath The path to a config file. + * @param {Object} [options] The options. + * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @param {string} [options.name] The config name. + * @returns {ConfigArray} Loaded config. + */ + loadFile(filePath, { basePath, name } = {}) { + const slots = internalSlotsMap$1.get(this); + const ctx = createContext(slots, "config", name, filePath, basePath); + + return new ConfigArray(...this._loadConfigData(ctx)); + } + + /** + * Load the config file on a given directory if exists. + * @param {string} directoryPath The path to a directory. + * @param {Object} [options] The options. + * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @param {string} [options.name] The config name. + * @throws {Error} If the config file is invalid. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + */ + loadInDirectory(directoryPath, { basePath, name } = {}) { + const slots = internalSlotsMap$1.get(this); + + for (const filename of configFilenames) { + const ctx = createContext( + slots, + "config", + name, + path__default["default"].join(directoryPath, filename), + basePath + ); + + if (fs__default["default"].existsSync(ctx.filePath) && fs__default["default"].statSync(ctx.filePath).isFile()) { + let configData; + + try { + configData = loadConfigFile(ctx.filePath); + } catch (error) { + if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") { + throw error; + } + } + + if (configData) { + debug$2(`Config file found: ${ctx.filePath}`); + return new ConfigArray( + ...this._normalizeConfigData(configData, ctx) + ); + } + } + } + + debug$2(`Config file not found on ${directoryPath}`); + return new ConfigArray(); + } + + /** + * Check if a config file on a given directory exists or not. + * @param {string} directoryPath The path to a directory. + * @returns {string | null} The path to the found config file. If not found then null. + */ + static getPathToConfigFileInDirectory(directoryPath) { + for (const filename of configFilenames) { + const filePath = path__default["default"].join(directoryPath, filename); + + if (fs__default["default"].existsSync(filePath)) { + if (filename === "package.json") { + try { + loadPackageJSONConfigFile(filePath); + return filePath; + } catch { /* ignore */ } + } else { + return filePath; + } + } + } + return null; + } + + /** + * Load `.eslintignore` file. + * @param {string} filePath The path to a `.eslintignore` file to load. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + */ + loadESLintIgnore(filePath) { + const slots = internalSlotsMap$1.get(this); + const ctx = createContext( + slots, + "ignore", + void 0, + filePath, + slots.cwd + ); + const ignorePatterns = loadESLintIgnoreFile(ctx.filePath); + + return new ConfigArray( + ...this._normalizeESLintIgnoreData(ignorePatterns, ctx) + ); + } + + /** + * Load `.eslintignore` file in the current working directory. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + * @throws {Error} If the ignore file is invalid. + */ + loadDefaultESLintIgnore() { + const slots = internalSlotsMap$1.get(this); + const eslintIgnorePath = path__default["default"].resolve(slots.cwd, ".eslintignore"); + const packageJsonPath = path__default["default"].resolve(slots.cwd, "package.json"); + + if (fs__default["default"].existsSync(eslintIgnorePath)) { + return this.loadESLintIgnore(eslintIgnorePath); + } + if (fs__default["default"].existsSync(packageJsonPath)) { + const data = loadJSONConfigFile(packageJsonPath); + + if (Object.hasOwn(data, "eslintIgnore")) { + if (!Array.isArray(data.eslintIgnore)) { + throw new Error("Package.json eslintIgnore property requires an array of paths"); + } + const ctx = createContext( + slots, + "ignore", + "eslintIgnore in package.json", + packageJsonPath, + slots.cwd + ); + + return new ConfigArray( + ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx) + ); + } + } + + return new ConfigArray(); + } + + /** + * Load a given config file. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} Loaded config. + * @private + */ + _loadConfigData(ctx) { + return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx); + } + + /** + * Normalize a given `.eslintignore` data to config array elements. + * @param {string[]} ignorePatterns The patterns to ignore files. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeESLintIgnoreData(ignorePatterns, ctx) { + const elements = this._normalizeObjectConfigData( + { ignorePatterns }, + ctx + ); + + // Set `ignorePattern.loose` flag for backward compatibility. + for (const element of elements) { + if (element.ignorePattern) { + element.ignorePattern.loose = true; + } + yield element; + } + } + + /** + * Normalize a given config to an array. + * @param {ConfigData} configData The config data to normalize. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + _normalizeConfigData(configData, ctx) { + const validator = new ConfigValidator(); + + validator.validateConfigSchema(configData, ctx.name || ctx.filePath); + return this._normalizeObjectConfigData(configData, ctx); + } + + /** + * Normalize a given config to an array. + * @param {ConfigData|OverrideConfigData} configData The config data to normalize. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeObjectConfigData(configData, ctx) { + const { files, excludedFiles, ...configBody } = configData; + const criteria = OverrideTester.create( + files, + excludedFiles, + ctx.matchBasePath + ); + const elements = this._normalizeObjectConfigDataBody(configBody, ctx); + + // Apply the criteria to every element. + for (const element of elements) { + + /* + * Merge the criteria. + * This is for the `overrides` entries that came from the + * configurations of `overrides[].extends`. + */ + element.criteria = OverrideTester.and(criteria, element.criteria); + + /* + * Remove `root` property to ignore `root` settings which came from + * `extends` in `overrides`. + */ + if (element.criteria) { + element.root = void 0; + } + + yield element; + } + } + + /** + * Normalize a given config to an array. + * @param {ConfigData} configData The config data to normalize. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeObjectConfigDataBody( + { + env, + extends: extend, + globals, + ignorePatterns, + noInlineConfig, + parser: parserName, + parserOptions, + plugins: pluginList, + processor, + reportUnusedDisableDirectives, + root, + rules, + settings, + overrides: overrideList = [] + }, + ctx + ) { + const extendList = Array.isArray(extend) ? extend : [extend]; + const ignorePattern = ignorePatterns && new IgnorePattern( + Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns], + ctx.matchBasePath + ); + + // Flatten `extends`. + for (const extendName of extendList.filter(Boolean)) { + yield* this._loadExtends(extendName, ctx); + } + + // Load parser & plugins. + const parser = parserName && this._loadParser(parserName, ctx); + const plugins = pluginList && this._loadPlugins(pluginList, ctx); + + // Yield pseudo config data for file extension processors. + if (plugins) { + yield* this._takeFileExtensionProcessors(plugins, ctx); + } + + // Yield the config data except `extends` and `overrides`. + yield { + + // Debug information. + type: ctx.type, + name: ctx.name, + filePath: ctx.filePath, + + // Config data. + criteria: null, + env, + globals, + ignorePattern, + noInlineConfig, + parser, + parserOptions, + plugins, + processor, + reportUnusedDisableDirectives, + root, + rules, + settings + }; + + // Flatten `overries`. + for (let i = 0; i < overrideList.length; ++i) { + yield* this._normalizeObjectConfigData( + overrideList[i], + { ...ctx, name: `${ctx.name}#overrides[${i}]` } + ); + } + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @throws {Error} If the extended config file can't be loaded. + * @private + */ + _loadExtends(extendName, ctx) { + debug$2("Loading {extends:%j} relative to %s", extendName, ctx.filePath); + try { + if (extendName.startsWith("eslint:")) { + return this._loadExtendedBuiltInConfig(extendName, ctx); + } + if (extendName.startsWith("plugin:")) { + return this._loadExtendedPluginConfig(extendName, ctx); + } + return this._loadExtendedShareableConfig(extendName, ctx); + } catch (error) { + error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`; + throw error; + } + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @throws {Error} If the extended config file can't be loaded. + * @private + */ + _loadExtendedBuiltInConfig(extendName, ctx) { + const { + eslintAllPath, + getEslintAllConfig, + eslintRecommendedPath, + getEslintRecommendedConfig + } = internalSlotsMap$1.get(this); + + if (extendName === "eslint:recommended") { + const name = `${ctx.name} » ${extendName}`; + + if (getEslintRecommendedConfig) { + if (typeof getEslintRecommendedConfig !== "function") { + throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`); + } + return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: "" }); + } + return this._loadConfigData({ + ...ctx, + name, + filePath: eslintRecommendedPath + }); + } + if (extendName === "eslint:all") { + const name = `${ctx.name} » ${extendName}`; + + if (getEslintAllConfig) { + if (typeof getEslintAllConfig !== "function") { + throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`); + } + return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: "" }); + } + return this._loadConfigData({ + ...ctx, + name, + filePath: eslintAllPath + }); + } + + throw configInvalidError(extendName, ctx.name, "extend-config-missing"); + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @throws {Error} If the extended config file can't be loaded. + * @private + */ + _loadExtendedPluginConfig(extendName, ctx) { + const slashIndex = extendName.lastIndexOf("/"); + + if (slashIndex === -1) { + throw configInvalidError(extendName, ctx.filePath, "plugin-invalid"); + } + + const pluginName = extendName.slice("plugin:".length, slashIndex); + const configName = extendName.slice(slashIndex + 1); + + if (isFilePath(pluginName)) { + throw new Error("'extends' cannot use a file path for plugins."); + } + + const plugin = this._loadPlugin(pluginName, ctx); + const configData = + plugin.definition && + plugin.definition.configs[configName]; + + if (configData) { + return this._normalizeConfigData(configData, { + ...ctx, + filePath: plugin.filePath || ctx.filePath, + name: `${ctx.name} » plugin:${plugin.id}/${configName}` + }); + } + + throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing"); + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @throws {Error} If the extended config file can't be loaded. + * @private + */ + _loadExtendedShareableConfig(extendName, ctx) { + const { cwd, resolver } = internalSlotsMap$1.get(this); + const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js"); + let request; + + if (isFilePath(extendName)) { + request = extendName; + } else if (extendName.startsWith(".")) { + request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior. + } else { + request = normalizePackageName( + extendName, + "eslint-config" + ); + } + + let filePath; + + try { + filePath = resolver.resolve(request, relativeTo); + } catch (error) { + /* istanbul ignore else */ + if (error && error.code === "MODULE_NOT_FOUND") { + throw configInvalidError(extendName, ctx.filePath, "extend-config-missing"); + } + throw error; + } + + writeDebugLogForLoading(request, relativeTo, filePath); + return this._loadConfigData({ + ...ctx, + filePath, + name: `${ctx.name} » ${request}` + }); + } + + /** + * Load given plugins. + * @param {string[]} names The plugin names to load. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {Record} The loaded parser. + * @private + */ + _loadPlugins(names, ctx) { + return names.reduce((map, name) => { + if (isFilePath(name)) { + throw new Error("Plugins array cannot includes file paths."); + } + const plugin = this._loadPlugin(name, ctx); + + map[plugin.id] = plugin; + + return map; + }, {}); + } + + /** + * Load a given parser. + * @param {string} nameOrPath The package name or the path to a parser file. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {DependentParser} The loaded parser. + */ + _loadParser(nameOrPath, ctx) { + debug$2("Loading parser %j from %s", nameOrPath, ctx.filePath); + + const { cwd, resolver } = internalSlotsMap$1.get(this); + const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js"); + + try { + const filePath = resolver.resolve(nameOrPath, relativeTo); + + writeDebugLogForLoading(nameOrPath, relativeTo, filePath); + + return new ConfigDependency({ + definition: require$1(filePath), + filePath, + id: nameOrPath, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } catch (error) { + + // If the parser name is "espree", load the espree of ESLint. + if (nameOrPath === "espree") { + debug$2("Fallback espree."); + return new ConfigDependency({ + definition: require$1("espree"), + filePath: require$1.resolve("espree"), + id: nameOrPath, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + debug$2("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name); + error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`; + + return new ConfigDependency({ + error, + id: nameOrPath, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + } + + /** + * Load a given plugin. + * @param {string} name The plugin name to load. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {DependentPlugin} The loaded plugin. + * @private + */ + _loadPlugin(name, ctx) { + debug$2("Loading plugin %j from %s", name, ctx.filePath); + + const { additionalPluginPool, resolver } = internalSlotsMap$1.get(this); + const request = normalizePackageName(name, "eslint-plugin"); + const id = getShorthandName(request, "eslint-plugin"); + const relativeTo = path__default["default"].join(ctx.pluginBasePath, "__placeholder__.js"); + + if (name.match(/\s+/u)) { + const error = Object.assign( + new Error(`Whitespace found in plugin name '${name}'`), + { + messageTemplate: "whitespace-found", + messageData: { pluginName: request } + } + ); + + return new ConfigDependency({ + error, + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + // Check for additional pool. + const plugin = + additionalPluginPool.get(request) || + additionalPluginPool.get(id); + + if (plugin) { + return new ConfigDependency({ + definition: normalizePlugin(plugin), + original: plugin, + filePath: "", // It's unknown where the plugin came from. + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + let filePath; + let error; + + try { + filePath = resolver.resolve(request, relativeTo); + } catch (resolveError) { + error = resolveError; + /* istanbul ignore else */ + if (error && error.code === "MODULE_NOT_FOUND") { + error.messageTemplate = "plugin-missing"; + error.messageData = { + pluginName: request, + resolvePluginsRelativeTo: ctx.pluginBasePath, + importerName: ctx.name + }; + } + } + + if (filePath) { + try { + writeDebugLogForLoading(request, relativeTo, filePath); + + const startTime = Date.now(); + const pluginDefinition = require$1(filePath); + + debug$2(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`); + + return new ConfigDependency({ + definition: normalizePlugin(pluginDefinition), + original: pluginDefinition, + filePath, + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } catch (loadError) { + error = loadError; + } + } + + debug$2("Failed to load plugin '%s' declared in '%s'.", name, ctx.name); + error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`; + return new ConfigDependency({ + error, + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + /** + * Take file expression processors as config array elements. + * @param {Record} plugins The plugin definitions. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The config array elements of file expression processors. + * @private + */ + *_takeFileExtensionProcessors(plugins, ctx) { + for (const pluginId of Object.keys(plugins)) { + const processors = + plugins[pluginId] && + plugins[pluginId].definition && + plugins[pluginId].definition.processors; + + if (!processors) { + continue; + } + + for (const processorId of Object.keys(processors)) { + if (processorId.startsWith(".")) { + yield* this._normalizeObjectConfigData( + { + files: [`*${processorId}`], + processor: `${pluginId}/${processorId}` + }, + { + ...ctx, + type: "implicit-processor", + name: `${ctx.name}#processors["${pluginId}/${processorId}"]` + } + ); + } + } + } + } +} + +/** + * @fileoverview `CascadingConfigArrayFactory` class. + * + * `CascadingConfigArrayFactory` class has a responsibility: + * + * 1. Handles cascading of config files. + * + * It provides two methods: + * + * - `getConfigArrayForFile(filePath)` + * Get the corresponded configuration of a given file. This method doesn't + * throw even if the given file didn't exist. + * - `clearCache()` + * Clear the internal cache. You have to call this method when + * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends + * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.) + * + * @author Toru Nagashima + */ + +const debug$1 = debugOrig__default["default"]("eslintrc:cascading-config-array-factory"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Define types for VSCode IntelliSense. +/** @typedef {import("./shared/types").ConfigData} ConfigData */ +/** @typedef {import("./shared/types").Parser} Parser */ +/** @typedef {import("./shared/types").Plugin} Plugin */ +/** @typedef {import("./shared/types").Rule} Rule */ +/** @typedef {ReturnType} ConfigArray */ + +/** + * @typedef {Object} CascadingConfigArrayFactoryOptions + * @property {Map} [additionalPluginPool] The map for additional plugins. + * @property {ConfigData} [baseConfig] The config by `baseConfig` option. + * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files. + * @property {string} [cwd] The base directory to start lookup. + * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`. + * @property {string[]} [rulePaths] The value of `--rulesdir` option. + * @property {string} [specificConfigPath] The value of `--config` option. + * @property {boolean} [useEslintrc] if `false` then it doesn't load config files. + * @property {Function} loadRules The function to use to load rules. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** + * @typedef {Object} CascadingConfigArrayFactoryInternalSlots + * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option. + * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`. + * @property {ConfigArray} cliConfigArray The config array of CLI options. + * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`. + * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays. + * @property {Map} configCache The cache from directory paths to config arrays. + * @property {string} cwd The base directory to start lookup. + * @property {WeakMap} finalizeCache The cache from config arrays to finalized config arrays. + * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`. + * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`. + * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`. + * @property {boolean} useEslintrc if `false` then it doesn't load config files. + * @property {Function} loadRules The function to use to load rules. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Create the config array from `baseConfig` and `rulePaths`. + * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. + * @returns {ConfigArray} The config array of the base configs. + */ +function createBaseConfigArray({ + configArrayFactory, + baseConfigData, + rulePaths, + cwd, + loadRules +}) { + const baseConfigArray = configArrayFactory.create( + baseConfigData, + { name: "BaseConfig" } + ); + + /* + * Create the config array element for the default ignore patterns. + * This element has `ignorePattern` property that ignores the default + * patterns in the current working directory. + */ + baseConfigArray.unshift(configArrayFactory.create( + { ignorePatterns: IgnorePattern.DefaultPatterns }, + { name: "DefaultIgnorePattern" } + )[0]); + + /* + * Load rules `--rulesdir` option as a pseudo plugin. + * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate + * the rule's options with only information in the config array. + */ + if (rulePaths && rulePaths.length > 0) { + baseConfigArray.push({ + type: "config", + name: "--rulesdir", + filePath: "", + plugins: { + "": new ConfigDependency({ + definition: { + rules: rulePaths.reduce( + (map, rulesPath) => Object.assign( + map, + loadRules(rulesPath, cwd) + ), + {} + ) + }, + filePath: "", + id: "", + importerName: "--rulesdir", + importerPath: "" + }) + } + }); + } + + return baseConfigArray; +} + +/** + * Create the config array from CLI options. + * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. + * @returns {ConfigArray} The config array of the base configs. + */ +function createCLIConfigArray({ + cliConfigData, + configArrayFactory, + cwd, + ignorePath, + specificConfigPath +}) { + const cliConfigArray = configArrayFactory.create( + cliConfigData, + { name: "CLIOptions" } + ); + + cliConfigArray.unshift( + ...(ignorePath + ? configArrayFactory.loadESLintIgnore(ignorePath) + : configArrayFactory.loadDefaultESLintIgnore()) + ); + + if (specificConfigPath) { + cliConfigArray.unshift( + ...configArrayFactory.loadFile( + specificConfigPath, + { name: "--config", basePath: cwd } + ) + ); + } + + return cliConfigArray; +} + +/** + * The error type when there are files matched by a glob, but all of them have been ignored. + */ +class ConfigurationNotFoundError extends Error { + + + /** + * @param {string} directoryPath The directory path. + */ + constructor(directoryPath) { + super(`No ESLint configuration found in ${directoryPath}.`); + this.messageTemplate = "no-config-found"; + this.messageData = { directoryPath }; + } +} + +/** + * This class provides the functionality that enumerates every file which is + * matched by given glob patterns and that configuration. + */ +class CascadingConfigArrayFactory { + + /** + * Initialize this enumerator. + * @param {CascadingConfigArrayFactoryOptions} options The options. + */ + constructor({ + additionalPluginPool = new Map(), + baseConfig: baseConfigData = null, + cliConfig: cliConfigData = null, + cwd = process.cwd(), + ignorePath, + resolvePluginsRelativeTo, + rulePaths = [], + specificConfigPath = null, + useEslintrc = true, + builtInRules = new Map(), + loadRules, + resolver, + eslintRecommendedPath, + getEslintRecommendedConfig, + eslintAllPath, + getEslintAllConfig + } = {}) { + const configArrayFactory = new ConfigArrayFactory({ + additionalPluginPool, + cwd, + resolvePluginsRelativeTo, + builtInRules, + resolver, + eslintRecommendedPath, + getEslintRecommendedConfig, + eslintAllPath, + getEslintAllConfig + }); + + internalSlotsMap.set(this, { + baseConfigArray: createBaseConfigArray({ + baseConfigData, + configArrayFactory, + cwd, + rulePaths, + loadRules + }), + baseConfigData, + cliConfigArray: createCLIConfigArray({ + cliConfigData, + configArrayFactory, + cwd, + ignorePath, + specificConfigPath + }), + cliConfigData, + configArrayFactory, + configCache: new Map(), + cwd, + finalizeCache: new WeakMap(), + ignorePath, + rulePaths, + specificConfigPath, + useEslintrc, + builtInRules, + loadRules + }); + } + + /** + * The path to the current working directory. + * This is used by tests. + * @type {string} + */ + get cwd() { + const { cwd } = internalSlotsMap.get(this); + + return cwd; + } + + /** + * Get the config array of a given file. + * If `filePath` was not given, it returns the config which contains only + * `baseConfigData` and `cliConfigData`. + * @param {string} [filePath] The file path to a file. + * @param {Object} [options] The options. + * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`. + * @returns {ConfigArray} The config array of the file. + */ + getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) { + const { + baseConfigArray, + cliConfigArray, + cwd + } = internalSlotsMap.get(this); + + if (!filePath) { + return new ConfigArray(...baseConfigArray, ...cliConfigArray); + } + + const directoryPath = path__default["default"].dirname(path__default["default"].resolve(cwd, filePath)); + + debug$1(`Load config files for ${directoryPath}.`); + + return this._finalizeConfigArray( + this._loadConfigInAncestors(directoryPath), + directoryPath, + ignoreNotFoundError + ); + } + + /** + * Set the config data to override all configs. + * Require to call `clearCache()` method after this method is called. + * @param {ConfigData} configData The config data to override all configs. + * @returns {void} + */ + setOverrideConfig(configData) { + const slots = internalSlotsMap.get(this); + + slots.cliConfigData = configData; + } + + /** + * Clear config cache. + * @returns {void} + */ + clearCache() { + const slots = internalSlotsMap.get(this); + + slots.baseConfigArray = createBaseConfigArray(slots); + slots.cliConfigArray = createCLIConfigArray(slots); + slots.configCache.clear(); + } + + /** + * Load and normalize config files from the ancestor directories. + * @param {string} directoryPath The path to a leaf directory. + * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories. + * @returns {ConfigArray} The loaded config. + * @throws {Error} If a config file is invalid. + * @private + */ + _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) { + const { + baseConfigArray, + configArrayFactory, + configCache, + cwd, + useEslintrc + } = internalSlotsMap.get(this); + + if (!useEslintrc) { + return baseConfigArray; + } + + let configArray = configCache.get(directoryPath); + + // Hit cache. + if (configArray) { + debug$1(`Cache hit: ${directoryPath}.`); + return configArray; + } + debug$1(`No cache found: ${directoryPath}.`); + + const homePath = os__default["default"].homedir(); + + // Consider this is root. + if (directoryPath === homePath && cwd !== homePath) { + debug$1("Stop traversing because of considered root."); + if (configsExistInSubdirs) { + const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath); + + if (filePath) { + emitDeprecationWarning( + filePath, + "ESLINT_PERSONAL_CONFIG_SUPPRESS" + ); + } + } + return this._cacheConfig(directoryPath, baseConfigArray); + } + + // Load the config on this directory. + try { + configArray = configArrayFactory.loadInDirectory(directoryPath); + } catch (error) { + /* istanbul ignore next */ + if (error.code === "EACCES") { + debug$1("Stop traversing because of 'EACCES' error."); + return this._cacheConfig(directoryPath, baseConfigArray); + } + throw error; + } + + if (configArray.length > 0 && configArray.isRoot()) { + debug$1("Stop traversing because of 'root:true'."); + configArray.unshift(...baseConfigArray); + return this._cacheConfig(directoryPath, configArray); + } + + // Load from the ancestors and merge it. + const parentPath = path__default["default"].dirname(directoryPath); + const parentConfigArray = parentPath && parentPath !== directoryPath + ? this._loadConfigInAncestors( + parentPath, + configsExistInSubdirs || configArray.length > 0 + ) + : baseConfigArray; + + if (configArray.length > 0) { + configArray.unshift(...parentConfigArray); + } else { + configArray = parentConfigArray; + } + + // Cache and return. + return this._cacheConfig(directoryPath, configArray); + } + + /** + * Freeze and cache a given config. + * @param {string} directoryPath The path to a directory as a cache key. + * @param {ConfigArray} configArray The config array as a cache value. + * @returns {ConfigArray} The `configArray` (frozen). + */ + _cacheConfig(directoryPath, configArray) { + const { configCache } = internalSlotsMap.get(this); + + Object.freeze(configArray); + configCache.set(directoryPath, configArray); + + return configArray; + } + + /** + * Finalize a given config array. + * Concatenate `--config` and other CLI options. + * @param {ConfigArray} configArray The parent config array. + * @param {string} directoryPath The path to the leaf directory to find config files. + * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`. + * @returns {ConfigArray} The loaded config. + * @throws {Error} If a config file is invalid. + * @private + */ + _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) { + const { + cliConfigArray, + configArrayFactory, + finalizeCache, + useEslintrc, + builtInRules + } = internalSlotsMap.get(this); + + let finalConfigArray = finalizeCache.get(configArray); + + if (!finalConfigArray) { + finalConfigArray = configArray; + + // Load the personal config if there are no regular config files. + if ( + useEslintrc && + configArray.every(c => !c.filePath) && + cliConfigArray.every(c => !c.filePath) // `--config` option can be a file. + ) { + const homePath = os__default["default"].homedir(); + + debug$1("Loading the config file of the home directory:", homePath); + + const personalConfigArray = configArrayFactory.loadInDirectory( + homePath, + { name: "PersonalConfig" } + ); + + if ( + personalConfigArray.length > 0 && + !directoryPath.startsWith(homePath) + ) { + const lastElement = + personalConfigArray.at(-1); + + emitDeprecationWarning( + lastElement.filePath, + "ESLINT_PERSONAL_CONFIG_LOAD" + ); + } + + finalConfigArray = finalConfigArray.concat(personalConfigArray); + } + + // Apply CLI options. + if (cliConfigArray.length > 0) { + finalConfigArray = finalConfigArray.concat(cliConfigArray); + } + + // Validate rule settings and environments. + const validator = new ConfigValidator({ + builtInRules + }); + + validator.validateConfigArray(finalConfigArray); + + // Cache it. + Object.freeze(finalConfigArray); + finalizeCache.set(configArray, finalConfigArray); + + debug$1( + "Configuration was determined: %o on %s", + finalConfigArray, + directoryPath + ); + } + + // At least one element (the default ignore patterns) exists. + if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) { + throw new ConfigurationNotFoundError(directoryPath); + } + + return finalConfigArray; + } +} + +/** + * @fileoverview Compatibility class for flat config. + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** @typedef {import("../../shared/types").Environment} Environment */ +/** @typedef {import("../../shared/types").Processor} Processor */ + +const debug = debugOrig__default["default"]("eslintrc:flat-compat"); +const cafactory = Symbol("cafactory"); + +/** + * Translates an ESLintRC-style config object into a flag-config-style config + * object. + * @param {Object} eslintrcConfig An ESLintRC-style config object. + * @param {Object} options Options to help translate the config. + * @param {string} options.resolveConfigRelativeTo To the directory to resolve + * configs from. + * @param {string} options.resolvePluginsRelativeTo The directory to resolve + * plugins from. + * @param {ReadOnlyMap} options.pluginEnvironments A map of plugin environment + * names to objects. + * @param {ReadOnlyMap} options.pluginProcessors A map of plugin processor + * names to objects. + * @returns {Object} A flag-config-style config object. + * @throws {Error} If a plugin or environment cannot be resolved. + */ +function translateESLintRC(eslintrcConfig, { + resolveConfigRelativeTo, + resolvePluginsRelativeTo, + pluginEnvironments, + pluginProcessors +}) { + + const flatConfig = {}; + const configs = []; + const languageOptions = {}; + const linterOptions = {}; + const keysToCopy = ["settings", "rules", "processor"]; + const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"]; + const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"]; + + // copy over simple translations + for (const key of keysToCopy) { + if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") { + flatConfig[key] = eslintrcConfig[key]; + } + } + + // copy over languageOptions + for (const key of languageOptionsKeysToCopy) { + if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") { + + // create the languageOptions key in the flat config + flatConfig.languageOptions = languageOptions; + + if (key === "parser") { + debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`); + + if (eslintrcConfig[key].error) { + throw eslintrcConfig[key].error; + } + + languageOptions[key] = eslintrcConfig[key].definition; + continue; + } + + // clone any object values that are in the eslintrc config + if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") { + languageOptions[key] = { + ...eslintrcConfig[key] + }; + } else { + languageOptions[key] = eslintrcConfig[key]; + } + } + } + + // copy over linterOptions + for (const key of linterOptionsKeysToCopy) { + if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") { + flatConfig.linterOptions = linterOptions; + linterOptions[key] = eslintrcConfig[key]; + } + } + + // move ecmaVersion a level up + if (languageOptions.parserOptions) { + + if ("ecmaVersion" in languageOptions.parserOptions) { + languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion; + delete languageOptions.parserOptions.ecmaVersion; + } + + if ("sourceType" in languageOptions.parserOptions) { + languageOptions.sourceType = languageOptions.parserOptions.sourceType; + delete languageOptions.parserOptions.sourceType; + } + + // check to see if we even need parserOptions anymore and remove it if not + if (Object.keys(languageOptions.parserOptions).length === 0) { + delete languageOptions.parserOptions; + } + } + + // overrides + if (eslintrcConfig.criteria) { + flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)]; + } + + // translate plugins + if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") { + debug(`Translating plugins: ${eslintrcConfig.plugins}`); + + flatConfig.plugins = {}; + + for (const pluginName of Object.keys(eslintrcConfig.plugins)) { + + debug(`Translating plugin: ${pluginName}`); + debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`); + + const { original: plugin, error } = eslintrcConfig.plugins[pluginName]; + + if (error) { + throw error; + } + + flatConfig.plugins[pluginName] = plugin; + + // create a config for any processors + if (plugin.processors) { + for (const processorName of Object.keys(plugin.processors)) { + if (processorName.startsWith(".")) { + debug(`Assigning processor: ${pluginName}/${processorName}`); + + configs.unshift({ + files: [`**/*${processorName}`], + processor: pluginProcessors.get(`${pluginName}/${processorName}`) + }); + } + + } + } + } + } + + // translate env - must come after plugins + if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") { + for (const envName of Object.keys(eslintrcConfig.env)) { + + // only add environments that are true + if (eslintrcConfig.env[envName]) { + debug(`Translating environment: ${envName}`); + + if (environments.has(envName)) { + + // built-in environments should be defined first + configs.unshift(...translateESLintRC({ + criteria: eslintrcConfig.criteria, + ...environments.get(envName) + }, { + resolveConfigRelativeTo, + resolvePluginsRelativeTo + })); + } else if (pluginEnvironments.has(envName)) { + + // if the environment comes from a plugin, it should come after the plugin config + configs.push(...translateESLintRC({ + criteria: eslintrcConfig.criteria, + ...pluginEnvironments.get(envName) + }, { + resolveConfigRelativeTo, + resolvePluginsRelativeTo + })); + } + } + } + } + + // only add if there are actually keys in the config + if (Object.keys(flatConfig).length > 0) { + configs.push(flatConfig); + } + + return configs; +} + + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A compatibility class for working with configs. + */ +class FlatCompat { + + constructor({ + baseDirectory = process.cwd(), + resolvePluginsRelativeTo = baseDirectory, + recommendedConfig, + allConfig + } = {}) { + this.baseDirectory = baseDirectory; + this.resolvePluginsRelativeTo = resolvePluginsRelativeTo; + this[cafactory] = new ConfigArrayFactory({ + cwd: baseDirectory, + resolvePluginsRelativeTo, + getEslintAllConfig() { + + if (!allConfig) { + throw new TypeError("Missing parameter 'allConfig' in FlatCompat constructor."); + } + + return allConfig; + }, + getEslintRecommendedConfig() { + + if (!recommendedConfig) { + throw new TypeError("Missing parameter 'recommendedConfig' in FlatCompat constructor."); + } + + return recommendedConfig; + } + }); + } + + /** + * Translates an ESLintRC-style config into a flag-config-style config. + * @param {Object} eslintrcConfig The ESLintRC-style config object. + * @returns {Object} A flag-config-style config object. + */ + config(eslintrcConfig) { + const eslintrcArray = this[cafactory].create(eslintrcConfig, { + basePath: this.baseDirectory + }); + + const flatArray = []; + let hasIgnorePatterns = false; + + eslintrcArray.forEach(configData => { + if (configData.type === "config") { + hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern; + flatArray.push(...translateESLintRC(configData, { + resolveConfigRelativeTo: path__default["default"].join(this.baseDirectory, "__placeholder.js"), + resolvePluginsRelativeTo: path__default["default"].join(this.resolvePluginsRelativeTo, "__placeholder.js"), + pluginEnvironments: eslintrcArray.pluginEnvironments, + pluginProcessors: eslintrcArray.pluginProcessors + })); + } + }); + + // combine ignorePatterns to emulate ESLintRC behavior better + if (hasIgnorePatterns) { + flatArray.unshift({ + ignores: [filePath => { + + // Compute the final config for this file. + // This filters config array elements by `files`/`excludedFiles` then merges the elements. + const finalConfig = eslintrcArray.extractConfig(filePath); + + // Test the `ignorePattern` properties of the final config. + return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath); + }] + }); + } + + return flatArray; + } + + /** + * Translates the `env` section of an ESLintRC-style config. + * @param {Object} envConfig The `env` section of an ESLintRC config. + * @returns {Object[]} An array of flag-config objects representing the environments. + */ + env(envConfig) { + return this.config({ + env: envConfig + }); + } + + /** + * Translates the `extends` section of an ESLintRC-style config. + * @param {...string} configsToExtend The names of the configs to load. + * @returns {Object[]} An array of flag-config objects representing the config. + */ + extends(...configsToExtend) { + return this.config({ + extends: configsToExtend + }); + } + + /** + * Translates the `plugins` section of an ESLintRC-style config. + * @param {...string} plugins The names of the plugins to load. + * @returns {Object[]} An array of flag-config objects representing the plugins. + */ + plugins(...plugins) { + return this.config({ + plugins + }); + } +} + +/** + * @fileoverview Package exports for @eslint/eslintrc + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +const Legacy = { + ConfigArray, + createConfigArrayFactoryContext: createContext, + CascadingConfigArrayFactory, + ConfigArrayFactory, + ConfigDependency, + ExtractedConfig, + IgnorePattern, + OverrideTester, + getUsedExtractedConfigs, + environments, + loadConfigFile, + + // shared + ConfigOps, + ConfigValidator, + ModuleResolver, + naming +}; + +exports.FlatCompat = FlatCompat; +exports.Legacy = Legacy; +//# sourceMappingURL=eslintrc.cjs.map diff --git a/node_modules/@eslint/eslintrc/dist/eslintrc.cjs.map b/node_modules/@eslint/eslintrc/dist/eslintrc.cjs.map new file mode 100644 index 00000000..3c5800e2 --- /dev/null +++ b/node_modules/@eslint/eslintrc/dist/eslintrc.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"eslintrc.cjs","sources":["../lib/config-array/ignore-pattern.js","../lib/config-array/extracted-config.js","../lib/config-array/config-array.js","../lib/config-array/config-dependency.js","../lib/config-array/override-tester.js","../lib/config-array/index.js","../lib/shared/config-ops.js","../lib/shared/deprecation-warnings.js","../lib/shared/ajv.js","../lib/shared/deep-merge-arrays.js","../conf/config-schema.js","../conf/environments.js","../lib/shared/config-validator.js","../lib/shared/naming.js","../lib/shared/relative-module-resolver.js","../lib/config-array-factory.js","../lib/cascading-config-array-factory.js","../lib/flat-compat.js","../lib/index.js"],"sourcesContent":["/**\n * @fileoverview `IgnorePattern` class.\n *\n * `IgnorePattern` class has the set of glob patterns and the base path.\n *\n * It provides two static methods.\n *\n * - `IgnorePattern.createDefaultIgnore(cwd)`\n * Create the default predicate function.\n * - `IgnorePattern.createIgnore(ignorePatterns)`\n * Create the predicate function from multiple `IgnorePattern` objects.\n *\n * It provides two properties and a method.\n *\n * - `patterns`\n * The glob patterns that ignore to lint.\n * - `basePath`\n * The base path of the glob patterns. If absolute paths existed in the\n * glob patterns, those are handled as relative paths to the base path.\n * - `getPatternsRelativeTo(basePath)`\n * Get `patterns` as modified for a given base path. It modifies the\n * absolute paths in the patterns as prepending the difference of two base\n * paths.\n *\n * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes\n * `ignorePatterns` properties.\n *\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport assert from \"node:assert\";\nimport path from \"node:path\";\nimport ignore from \"ignore\";\nimport debugOrig from \"debug\";\n\nconst debug = debugOrig(\"eslintrc:ignore-pattern\");\n\n/** @typedef {ReturnType} Ignore */\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n/**\n * Get the path to the common ancestor directory of given paths.\n * @param {string[]} sourcePaths The paths to calculate the common ancestor.\n * @returns {string} The path to the common ancestor directory.\n */\nfunction getCommonAncestorPath(sourcePaths) {\n let result = sourcePaths[0];\n\n for (let i = 1; i < sourcePaths.length; ++i) {\n const a = result;\n const b = sourcePaths[i];\n\n // Set the shorter one (it's the common ancestor if one includes the other).\n result = a.length < b.length ? a : b;\n\n // Set the common ancestor.\n for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {\n if (a[j] !== b[j]) {\n result = a.slice(0, lastSepPos);\n break;\n }\n if (a[j] === path.sep) {\n lastSepPos = j;\n }\n }\n }\n\n let resolvedResult = result || path.sep;\n\n // if Windows common ancestor is root of drive must have trailing slash to be absolute.\n if (resolvedResult && resolvedResult.endsWith(\":\") && process.platform === \"win32\") {\n resolvedResult += path.sep;\n }\n return resolvedResult;\n}\n\n/**\n * Make relative path.\n * @param {string} from The source path to get relative path.\n * @param {string} to The destination path to get relative path.\n * @returns {string} The relative path.\n */\nfunction relative(from, to) {\n const relPath = path.relative(from, to);\n\n if (path.sep === \"/\") {\n return relPath;\n }\n return relPath.split(path.sep).join(\"/\");\n}\n\n/**\n * Get the trailing slash if existed.\n * @param {string} filePath The path to check.\n * @returns {string} The trailing slash if existed.\n */\nfunction dirSuffix(filePath) {\n const isDir = (\n filePath.endsWith(path.sep) ||\n (process.platform === \"win32\" && filePath.endsWith(\"/\"))\n );\n\n return isDir ? \"/\" : \"\";\n}\n\nconst DefaultPatterns = Object.freeze([\"/**/node_modules/*\"]);\nconst DotPatterns = Object.freeze([\".*\", \"!.eslintrc.*\", \"!../\"]);\n\n//------------------------------------------------------------------------------\n// Public\n//------------------------------------------------------------------------------\n\n/**\n * Represents a set of glob patterns to ignore against a base path.\n */\nclass IgnorePattern {\n\n /**\n * The default patterns.\n * @type {string[]}\n */\n static get DefaultPatterns() {\n return DefaultPatterns;\n }\n\n /**\n * Create the default predicate function.\n * @param {string} cwd The current working directory.\n * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}\n * The preficate function.\n * The first argument is an absolute path that is checked.\n * The second argument is the flag to not ignore dotfiles.\n * If the predicate function returned `true`, it means the path should be ignored.\n */\n static createDefaultIgnore(cwd) {\n return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);\n }\n\n /**\n * Create the predicate function from multiple `IgnorePattern` objects.\n * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.\n * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}\n * The preficate function.\n * The first argument is an absolute path that is checked.\n * The second argument is the flag to not ignore dotfiles.\n * If the predicate function returned `true`, it means the path should be ignored.\n */\n static createIgnore(ignorePatterns) {\n debug(\"Create with: %o\", ignorePatterns);\n\n const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));\n const patterns = ignorePatterns.flatMap(p => p.getPatternsRelativeTo(basePath));\n const ig = ignore({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]);\n const dotIg = ignore({ allowRelativePaths: true }).add(patterns);\n\n debug(\" processed: %o\", { basePath, patterns });\n\n return Object.assign(\n (filePath, dot = false) => {\n assert(path.isAbsolute(filePath), \"'filePath' should be an absolute path.\");\n const relPathRaw = relative(basePath, filePath);\n const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));\n const adoptedIg = dot ? dotIg : ig;\n const result = relPath !== \"\" && adoptedIg.ignores(relPath);\n\n debug(\"Check\", { filePath, dot, relativePath: relPath, result });\n return result;\n },\n { basePath, patterns }\n );\n }\n\n /**\n * Initialize a new `IgnorePattern` instance.\n * @param {string[]} patterns The glob patterns that ignore to lint.\n * @param {string} basePath The base path of `patterns`.\n */\n constructor(patterns, basePath) {\n assert(path.isAbsolute(basePath), \"'basePath' should be an absolute path.\");\n\n /**\n * The glob patterns that ignore to lint.\n * @type {string[]}\n */\n this.patterns = patterns;\n\n /**\n * The base path of `patterns`.\n * @type {string}\n */\n this.basePath = basePath;\n\n /**\n * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.\n *\n * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.\n * It's `false` as-is for `ignorePatterns` property in config files.\n * @type {boolean}\n */\n this.loose = false;\n }\n\n /**\n * Get `patterns` as modified for a given base path. It modifies the\n * absolute paths in the patterns as prepending the difference of two base\n * paths.\n * @param {string} newBasePath The base path.\n * @returns {string[]} Modifired patterns.\n */\n getPatternsRelativeTo(newBasePath) {\n assert(path.isAbsolute(newBasePath), \"'newBasePath' should be an absolute path.\");\n const { basePath, loose, patterns } = this;\n\n if (newBasePath === basePath) {\n return patterns;\n }\n const prefix = `/${relative(newBasePath, basePath)}`;\n\n return patterns.map(pattern => {\n const negative = pattern.startsWith(\"!\");\n const head = negative ? \"!\" : \"\";\n const body = negative ? pattern.slice(1) : pattern;\n\n if (body.startsWith(\"/\") || body.startsWith(\"../\")) {\n return `${head}${prefix}${body}`;\n }\n return loose ? pattern : `${head}${prefix}/**/${body}`;\n });\n }\n}\n\nexport { IgnorePattern };\n","/**\n * @fileoverview `ExtractedConfig` class.\n *\n * `ExtractedConfig` class expresses a final configuration for a specific file.\n *\n * It provides one method.\n *\n * - `toCompatibleObjectAsConfigFileContent()`\n * Convert this configuration to the compatible object as the content of\n * config files. It converts the loaded parser and plugins to strings.\n * `CLIEngine#getConfigForFile(filePath)` method uses this method.\n *\n * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.\n *\n * @author Toru Nagashima \n */\n\nimport { IgnorePattern } from \"./ignore-pattern.js\";\n\n// For VSCode intellisense\n/** @typedef {import(\"../../shared/types\").ConfigData} ConfigData */\n/** @typedef {import(\"../../shared/types\").GlobalConf} GlobalConf */\n/** @typedef {import(\"../../shared/types\").SeverityConf} SeverityConf */\n/** @typedef {import(\"./config-dependency\").DependentParser} DependentParser */\n/** @typedef {import(\"./config-dependency\").DependentPlugin} DependentPlugin */\n\n/**\n * Check if `xs` starts with `ys`.\n * @template T\n * @param {T[]} xs The array to check.\n * @param {T[]} ys The array that may be the first part of `xs`.\n * @returns {boolean} `true` if `xs` starts with `ys`.\n */\nfunction startsWith(xs, ys) {\n return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);\n}\n\n/**\n * The class for extracted config data.\n */\nclass ExtractedConfig {\n constructor() {\n\n /**\n * The config name what `noInlineConfig` setting came from.\n * @type {string}\n */\n this.configNameOfNoInlineConfig = \"\";\n\n /**\n * Environments.\n * @type {Record}\n */\n this.env = {};\n\n /**\n * Global variables.\n * @type {Record}\n */\n this.globals = {};\n\n /**\n * The glob patterns that ignore to lint.\n * @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}\n */\n this.ignores = void 0;\n\n /**\n * The flag that disables directive comments.\n * @type {boolean|undefined}\n */\n this.noInlineConfig = void 0;\n\n /**\n * Parser definition.\n * @type {DependentParser|null}\n */\n this.parser = null;\n\n /**\n * Options for the parser.\n * @type {Object}\n */\n this.parserOptions = {};\n\n /**\n * Plugin definitions.\n * @type {Record}\n */\n this.plugins = {};\n\n /**\n * Processor ID.\n * @type {string|null}\n */\n this.processor = null;\n\n /**\n * The flag that reports unused `eslint-disable` directive comments.\n * @type {boolean|undefined}\n */\n this.reportUnusedDisableDirectives = void 0;\n\n /**\n * Rule settings.\n * @type {Record}\n */\n this.rules = {};\n\n /**\n * Shared settings.\n * @type {Object}\n */\n this.settings = {};\n }\n\n /**\n * Convert this config to the compatible object as a config file content.\n * @returns {ConfigData} The converted object.\n */\n toCompatibleObjectAsConfigFileContent() {\n const {\n /* eslint-disable no-unused-vars -- needed to make `config` correct */\n configNameOfNoInlineConfig: _ignore1,\n processor: _ignore2,\n /* eslint-enable no-unused-vars -- needed to make `config` correct */\n ignores,\n ...config\n } = this;\n\n config.parser = config.parser && config.parser.filePath;\n config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();\n config.ignorePatterns = ignores ? ignores.patterns : [];\n\n // Strip the default patterns from `ignorePatterns`.\n if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {\n config.ignorePatterns =\n config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);\n }\n\n return config;\n }\n}\n\nexport { ExtractedConfig };\n","/**\n * @fileoverview `ConfigArray` class.\n *\n * `ConfigArray` class expresses the full of a configuration. It has the entry\n * config file, base config files that were extended, loaded parsers, and loaded\n * plugins.\n *\n * `ConfigArray` class provides three properties and two methods.\n *\n * - `pluginEnvironments`\n * - `pluginProcessors`\n * - `pluginRules`\n * The `Map` objects that contain the members of all plugins that this\n * config array contains. Those map objects don't have mutation methods.\n * Those keys are the member ID such as `pluginId/memberName`.\n * - `isRoot()`\n * If `true` then this configuration has `root:true` property.\n * - `extractConfig(filePath)`\n * Extract the final configuration for a given file. This means merging\n * every config array element which that `criteria` property matched. The\n * `filePath` argument must be an absolute path.\n *\n * `ConfigArrayFactory` provides the loading logic of config files.\n *\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport { ExtractedConfig } from \"./extracted-config.js\";\nimport { IgnorePattern } from \"./ignore-pattern.js\";\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n// Define types for VSCode IntelliSense.\n/** @typedef {import(\"../../shared/types\").Environment} Environment */\n/** @typedef {import(\"../../shared/types\").GlobalConf} GlobalConf */\n/** @typedef {import(\"../../shared/types\").RuleConf} RuleConf */\n/** @typedef {import(\"../../shared/types\").Rule} Rule */\n/** @typedef {import(\"../../shared/types\").Plugin} Plugin */\n/** @typedef {import(\"../../shared/types\").Processor} Processor */\n/** @typedef {import(\"./config-dependency\").DependentParser} DependentParser */\n/** @typedef {import(\"./config-dependency\").DependentPlugin} DependentPlugin */\n/** @typedef {import(\"./override-tester\")[\"OverrideTester\"]} OverrideTester */\n\n/**\n * @typedef {Object} ConfigArrayElement\n * @property {string} name The name of this config element.\n * @property {string} filePath The path to the source file of this config element.\n * @property {InstanceType|null} criteria The tester for the `files` and `excludedFiles` of this config element.\n * @property {Record|undefined} env The environment settings.\n * @property {Record|undefined} globals The global variable settings.\n * @property {IgnorePattern|undefined} ignorePattern The ignore patterns.\n * @property {boolean|undefined} noInlineConfig The flag that disables directive comments.\n * @property {DependentParser|undefined} parser The parser loader.\n * @property {Object|undefined} parserOptions The parser options.\n * @property {Record|undefined} plugins The plugin loaders.\n * @property {string|undefined} processor The processor name to refer plugin's processor.\n * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.\n * @property {boolean|undefined} root The flag to express root.\n * @property {Record|undefined} rules The rule settings\n * @property {Object|undefined} settings The shared settings.\n * @property {\"config\" | \"ignore\" | \"implicit-processor\"} type The element type.\n */\n\n/**\n * @typedef {Object} ConfigArrayInternalSlots\n * @property {Map} cache The cache to extract configs.\n * @property {ReadonlyMap|null} envMap The map from environment ID to environment definition.\n * @property {ReadonlyMap|null} processorMap The map from processor ID to environment definition.\n * @property {ReadonlyMap|null} ruleMap The map from rule ID to rule definition.\n */\n\n/** @type {WeakMap} */\nconst internalSlotsMap = new class extends WeakMap {\n get(key) {\n let value = super.get(key);\n\n if (!value) {\n value = {\n cache: new Map(),\n envMap: null,\n processorMap: null,\n ruleMap: null\n };\n super.set(key, value);\n }\n\n return value;\n }\n}();\n\n/**\n * Get the indices which are matched to a given file.\n * @param {ConfigArrayElement[]} elements The elements.\n * @param {string} filePath The path to a target file.\n * @returns {number[]} The indices.\n */\nfunction getMatchedIndices(elements, filePath) {\n const indices = [];\n\n for (let i = elements.length - 1; i >= 0; --i) {\n const element = elements[i];\n\n if (!element.criteria || (filePath && element.criteria.test(filePath))) {\n indices.push(i);\n }\n }\n\n return indices;\n}\n\n/**\n * Check if a value is a non-null object.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is a non-null object.\n */\nfunction isNonNullObject(x) {\n return typeof x === \"object\" && x !== null;\n}\n\n/**\n * Merge two objects.\n *\n * Assign every property values of `y` to `x` if `x` doesn't have the property.\n * If `x`'s property value is an object, it does recursive.\n * @param {Object} target The destination to merge\n * @param {Object|undefined} source The source to merge.\n * @returns {void}\n */\nfunction mergeWithoutOverwrite(target, source) {\n if (!isNonNullObject(source)) {\n return;\n }\n\n for (const key of Object.keys(source)) {\n if (key === \"__proto__\") {\n continue;\n }\n\n if (isNonNullObject(target[key])) {\n mergeWithoutOverwrite(target[key], source[key]);\n } else if (target[key] === void 0) {\n if (isNonNullObject(source[key])) {\n target[key] = Array.isArray(source[key]) ? [] : {};\n mergeWithoutOverwrite(target[key], source[key]);\n } else if (source[key] !== void 0) {\n target[key] = source[key];\n }\n }\n }\n}\n\n/**\n * The error for plugin conflicts.\n */\nclass PluginConflictError extends Error {\n\n /**\n * Initialize this error object.\n * @param {string} pluginId The plugin ID.\n * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.\n */\n constructor(pluginId, plugins) {\n super(`Plugin \"${pluginId}\" was conflicted between ${plugins.map(p => `\"${p.importerName}\"`).join(\" and \")}.`);\n this.messageTemplate = \"plugin-conflict\";\n this.messageData = { pluginId, plugins };\n }\n}\n\n/**\n * Merge plugins.\n * `target`'s definition is prior to `source`'s.\n * @param {Record} target The destination to merge\n * @param {Record|undefined} source The source to merge.\n * @returns {void}\n * @throws {PluginConflictError} When a plugin was conflicted.\n */\nfunction mergePlugins(target, source) {\n if (!isNonNullObject(source)) {\n return;\n }\n\n for (const key of Object.keys(source)) {\n if (key === \"__proto__\") {\n continue;\n }\n const targetValue = target[key];\n const sourceValue = source[key];\n\n // Adopt the plugin which was found at first.\n if (targetValue === void 0) {\n if (sourceValue.error) {\n throw sourceValue.error;\n }\n target[key] = sourceValue;\n } else if (sourceValue.filePath !== targetValue.filePath) {\n throw new PluginConflictError(key, [\n {\n filePath: targetValue.filePath,\n importerName: targetValue.importerName\n },\n {\n filePath: sourceValue.filePath,\n importerName: sourceValue.importerName\n }\n ]);\n }\n }\n}\n\n/**\n * Merge rule configs.\n * `target`'s definition is prior to `source`'s.\n * @param {Record} target The destination to merge\n * @param {Record|undefined} source The source to merge.\n * @returns {void}\n */\nfunction mergeRuleConfigs(target, source) {\n if (!isNonNullObject(source)) {\n return;\n }\n\n for (const key of Object.keys(source)) {\n if (key === \"__proto__\") {\n continue;\n }\n const targetDef = target[key];\n const sourceDef = source[key];\n\n // Adopt the rule config which was found at first.\n if (targetDef === void 0) {\n if (Array.isArray(sourceDef)) {\n target[key] = [...sourceDef];\n } else {\n target[key] = [sourceDef];\n }\n\n /*\n * If the first found rule config is severity only and the current rule\n * config has options, merge the severity and the options.\n */\n } else if (\n targetDef.length === 1 &&\n Array.isArray(sourceDef) &&\n sourceDef.length >= 2\n ) {\n targetDef.push(...sourceDef.slice(1));\n }\n }\n}\n\n/**\n * Create the extracted config.\n * @param {ConfigArray} instance The config elements.\n * @param {number[]} indices The indices to use.\n * @returns {ExtractedConfig} The extracted config.\n * @throws {Error} When a plugin is conflicted.\n */\nfunction createConfig(instance, indices) {\n const config = new ExtractedConfig();\n const ignorePatterns = [];\n\n // Merge elements.\n for (const index of indices) {\n const element = instance[index];\n\n // Adopt the parser which was found at first.\n if (!config.parser && element.parser) {\n if (element.parser.error) {\n throw element.parser.error;\n }\n config.parser = element.parser;\n }\n\n // Adopt the processor which was found at first.\n if (!config.processor && element.processor) {\n config.processor = element.processor;\n }\n\n // Adopt the noInlineConfig which was found at first.\n if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {\n config.noInlineConfig = element.noInlineConfig;\n config.configNameOfNoInlineConfig = element.name;\n }\n\n // Adopt the reportUnusedDisableDirectives which was found at first.\n if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {\n config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;\n }\n\n // Collect ignorePatterns\n if (element.ignorePattern) {\n ignorePatterns.push(element.ignorePattern);\n }\n\n // Merge others.\n mergeWithoutOverwrite(config.env, element.env);\n mergeWithoutOverwrite(config.globals, element.globals);\n mergeWithoutOverwrite(config.parserOptions, element.parserOptions);\n mergeWithoutOverwrite(config.settings, element.settings);\n mergePlugins(config.plugins, element.plugins);\n mergeRuleConfigs(config.rules, element.rules);\n }\n\n // Create the predicate function for ignore patterns.\n if (ignorePatterns.length > 0) {\n config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());\n }\n\n return config;\n}\n\n/**\n * Collect definitions.\n * @template T, U\n * @param {string} pluginId The plugin ID for prefix.\n * @param {Record} defs The definitions to collect.\n * @param {Map} map The map to output.\n * @returns {void}\n */\nfunction collect(pluginId, defs, map) {\n if (defs) {\n const prefix = pluginId && `${pluginId}/`;\n\n for (const [key, value] of Object.entries(defs)) {\n map.set(`${prefix}${key}`, value);\n }\n }\n}\n\n/**\n * Delete the mutation methods from a given map.\n * @param {Map} map The map object to delete.\n * @returns {void}\n */\nfunction deleteMutationMethods(map) {\n Object.defineProperties(map, {\n clear: { configurable: true, value: void 0 },\n delete: { configurable: true, value: void 0 },\n set: { configurable: true, value: void 0 }\n });\n}\n\n/**\n * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.\n * @param {ConfigArrayElement[]} elements The config elements.\n * @param {ConfigArrayInternalSlots} slots The internal slots.\n * @returns {void}\n */\nfunction initPluginMemberMaps(elements, slots) {\n const processed = new Set();\n\n slots.envMap = new Map();\n slots.processorMap = new Map();\n slots.ruleMap = new Map();\n\n for (const element of elements) {\n if (!element.plugins) {\n continue;\n }\n\n for (const [pluginId, value] of Object.entries(element.plugins)) {\n const plugin = value.definition;\n\n if (!plugin || processed.has(pluginId)) {\n continue;\n }\n processed.add(pluginId);\n\n collect(pluginId, plugin.environments, slots.envMap);\n collect(pluginId, plugin.processors, slots.processorMap);\n collect(pluginId, plugin.rules, slots.ruleMap);\n }\n }\n\n deleteMutationMethods(slots.envMap);\n deleteMutationMethods(slots.processorMap);\n deleteMutationMethods(slots.ruleMap);\n}\n\n/**\n * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.\n * @param {ConfigArray} instance The config elements.\n * @returns {ConfigArrayInternalSlots} The extracted config.\n */\nfunction ensurePluginMemberMaps(instance) {\n const slots = internalSlotsMap.get(instance);\n\n if (!slots.ruleMap) {\n initPluginMemberMaps(instance, slots);\n }\n\n return slots;\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * The Config Array.\n *\n * `ConfigArray` instance contains all settings, parsers, and plugins.\n * You need to call `ConfigArray#extractConfig(filePath)` method in order to\n * extract, merge and get only the config data which is related to an arbitrary\n * file.\n * @extends {Array}\n */\nclass ConfigArray extends Array {\n\n /**\n * Get the plugin environments.\n * The returned map cannot be mutated.\n * @type {ReadonlyMap} The plugin environments.\n */\n get pluginEnvironments() {\n return ensurePluginMemberMaps(this).envMap;\n }\n\n /**\n * Get the plugin processors.\n * The returned map cannot be mutated.\n * @type {ReadonlyMap} The plugin processors.\n */\n get pluginProcessors() {\n return ensurePluginMemberMaps(this).processorMap;\n }\n\n /**\n * Get the plugin rules.\n * The returned map cannot be mutated.\n * @returns {ReadonlyMap} The plugin rules.\n */\n get pluginRules() {\n return ensurePluginMemberMaps(this).ruleMap;\n }\n\n /**\n * Check if this config has `root` flag.\n * @returns {boolean} `true` if this config array is root.\n */\n isRoot() {\n for (let i = this.length - 1; i >= 0; --i) {\n const root = this[i].root;\n\n if (typeof root === \"boolean\") {\n return root;\n }\n }\n return false;\n }\n\n /**\n * Extract the config data which is related to a given file.\n * @param {string} filePath The absolute path to the target file.\n * @returns {ExtractedConfig} The extracted config data.\n */\n extractConfig(filePath) {\n const { cache } = internalSlotsMap.get(this);\n const indices = getMatchedIndices(this, filePath);\n const cacheKey = indices.join(\",\");\n\n if (!cache.has(cacheKey)) {\n cache.set(cacheKey, createConfig(this, indices));\n }\n\n return cache.get(cacheKey);\n }\n\n /**\n * Check if a given path is an additional lint target.\n * @param {string} filePath The absolute path to the target file.\n * @returns {boolean} `true` if the file is an additional lint target.\n */\n isAdditionalTargetPath(filePath) {\n for (const { criteria, type } of this) {\n if (\n type === \"config\" &&\n criteria &&\n !criteria.endsWithWildcard &&\n criteria.test(filePath)\n ) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Get the used extracted configs.\n * CLIEngine will use this method to collect used deprecated rules.\n * @param {ConfigArray} instance The config array object to get.\n * @returns {ExtractedConfig[]} The used extracted configs.\n * @private\n */\nfunction getUsedExtractedConfigs(instance) {\n const { cache } = internalSlotsMap.get(instance);\n\n return Array.from(cache.values());\n}\n\n\nexport {\n ConfigArray,\n getUsedExtractedConfigs\n};\n","/**\n * @fileoverview `ConfigDependency` class.\n *\n * `ConfigDependency` class expresses a loaded parser or plugin.\n *\n * If the parser or plugin was loaded successfully, it has `definition` property\n * and `filePath` property. Otherwise, it has `error` property.\n *\n * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it\n * omits `definition` property.\n *\n * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers\n * or plugins.\n *\n * @author Toru Nagashima \n */\n\nimport util from \"node:util\";\n\n/**\n * The class is to store parsers or plugins.\n * This class hides the loaded object from `JSON.stringify()` and `console.log`.\n * @template T\n */\nclass ConfigDependency {\n\n /**\n * Initialize this instance.\n * @param {Object} data The dependency data.\n * @param {T} [data.definition] The dependency if the loading succeeded.\n * @param {T} [data.original] The original, non-normalized dependency if the loading succeeded.\n * @param {Error} [data.error] The error object if the loading failed.\n * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.\n * @param {string} data.id The ID of this dependency.\n * @param {string} data.importerName The name of the config file which loads this dependency.\n * @param {string} data.importerPath The path to the config file which loads this dependency.\n */\n constructor({\n definition = null,\n original = null,\n error = null,\n filePath = null,\n id,\n importerName,\n importerPath\n }) {\n\n /**\n * The loaded dependency if the loading succeeded.\n * @type {T|null}\n */\n this.definition = definition;\n\n /**\n * The original dependency as loaded directly from disk if the loading succeeded.\n * @type {T|null}\n */\n this.original = original;\n\n /**\n * The error object if the loading failed.\n * @type {Error|null}\n */\n this.error = error;\n\n /**\n * The loaded dependency if the loading succeeded.\n * @type {string|null}\n */\n this.filePath = filePath;\n\n /**\n * The ID of this dependency.\n * @type {string}\n */\n this.id = id;\n\n /**\n * The name of the config file which loads this dependency.\n * @type {string}\n */\n this.importerName = importerName;\n\n /**\n * The path to the config file which loads this dependency.\n * @type {string}\n */\n this.importerPath = importerPath;\n }\n\n /**\n * Converts this instance to a JSON compatible object.\n * @returns {Object} a JSON compatible object.\n */\n toJSON() {\n const obj = this[util.inspect.custom]();\n\n // Display `error.message` (`Error#message` is unenumerable).\n if (obj.error instanceof Error) {\n obj.error = { ...obj.error, message: obj.error.message };\n }\n\n return obj;\n }\n\n /**\n * Custom inspect method for Node.js `console.log()`.\n * @returns {Object} an object to display by `console.log()`.\n */\n [util.inspect.custom]() {\n const {\n definition: _ignore1, // eslint-disable-line no-unused-vars -- needed to make `obj` correct\n original: _ignore2, // eslint-disable-line no-unused-vars -- needed to make `obj` correct\n ...obj\n } = this;\n\n return obj;\n }\n}\n\n/** @typedef {ConfigDependency} DependentParser */\n/** @typedef {ConfigDependency} DependentPlugin */\n\nexport { ConfigDependency };\n","/**\n * @fileoverview `OverrideTester` class.\n *\n * `OverrideTester` class handles `files` property and `excludedFiles` property\n * of `overrides` config.\n *\n * It provides one method.\n *\n * - `test(filePath)`\n * Test if a file path matches the pair of `files` property and\n * `excludedFiles` property. The `filePath` argument must be an absolute\n * path.\n *\n * `ConfigArrayFactory` creates `OverrideTester` objects when it processes\n * `overrides` properties.\n *\n * @author Toru Nagashima \n */\n\nimport assert from \"node:assert\";\nimport path from \"node:path\";\nimport util from \"node:util\";\nimport minimatch from \"minimatch\";\n\nconst { Minimatch } = minimatch;\n\nconst minimatchOpts = { dot: true, matchBase: true };\n\n/**\n * @typedef {Object} Pattern\n * @property {InstanceType[] | null} includes The positive matchers.\n * @property {InstanceType[] | null} excludes The negative matchers.\n */\n\n/**\n * Normalize a given pattern to an array.\n * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.\n * @returns {string[]|null} Normalized patterns.\n * @private\n */\nfunction normalizePatterns(patterns) {\n if (Array.isArray(patterns)) {\n return patterns.filter(Boolean);\n }\n if (typeof patterns === \"string\" && patterns) {\n return [patterns];\n }\n return [];\n}\n\n/**\n * Create the matchers of given patterns.\n * @param {string[]} patterns The patterns.\n * @returns {InstanceType[] | null} The matchers.\n */\nfunction toMatcher(patterns) {\n if (patterns.length === 0) {\n return null;\n }\n return patterns.map(pattern => {\n if (/^\\.[/\\\\]/u.test(pattern)) {\n return new Minimatch(\n pattern.slice(2),\n\n // `./*.js` should not match with `subdir/foo.js`\n { ...minimatchOpts, matchBase: false }\n );\n }\n return new Minimatch(pattern, minimatchOpts);\n });\n}\n\n/**\n * Convert a given matcher to string.\n * @param {Pattern} matchers The matchers.\n * @returns {string} The string expression of the matcher.\n */\nfunction patternToJson({ includes, excludes }) {\n return {\n includes: includes && includes.map(m => m.pattern),\n excludes: excludes && excludes.map(m => m.pattern)\n };\n}\n\n/**\n * The class to test given paths are matched by the patterns.\n */\nclass OverrideTester {\n\n /**\n * Create a tester with given criteria.\n * If there are no criteria, returns `null`.\n * @param {string|string[]} files The glob patterns for included files.\n * @param {string|string[]} excludedFiles The glob patterns for excluded files.\n * @param {string} basePath The path to the base directory to test paths.\n * @returns {OverrideTester|null} The created instance or `null`.\n * @throws {Error} When invalid patterns are given.\n */\n static create(files, excludedFiles, basePath) {\n const includePatterns = normalizePatterns(files);\n const excludePatterns = normalizePatterns(excludedFiles);\n let endsWithWildcard = false;\n\n if (includePatterns.length === 0) {\n return null;\n }\n\n // Rejects absolute paths or relative paths to parents.\n for (const pattern of includePatterns) {\n if (path.isAbsolute(pattern) || pattern.includes(\"..\")) {\n throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);\n }\n if (pattern.endsWith(\"*\")) {\n endsWithWildcard = true;\n }\n }\n for (const pattern of excludePatterns) {\n if (path.isAbsolute(pattern) || pattern.includes(\"..\")) {\n throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);\n }\n }\n\n const includes = toMatcher(includePatterns);\n const excludes = toMatcher(excludePatterns);\n\n return new OverrideTester(\n [{ includes, excludes }],\n basePath,\n endsWithWildcard\n );\n }\n\n /**\n * Combine two testers by logical and.\n * If either of the testers was `null`, returns the other tester.\n * The `basePath` property of the two must be the same value.\n * @param {OverrideTester|null} a A tester.\n * @param {OverrideTester|null} b Another tester.\n * @returns {OverrideTester|null} Combined tester.\n */\n static and(a, b) {\n if (!b) {\n return a && new OverrideTester(\n a.patterns,\n a.basePath,\n a.endsWithWildcard\n );\n }\n if (!a) {\n return new OverrideTester(\n b.patterns,\n b.basePath,\n b.endsWithWildcard\n );\n }\n\n assert.strictEqual(a.basePath, b.basePath);\n return new OverrideTester(\n a.patterns.concat(b.patterns),\n a.basePath,\n a.endsWithWildcard || b.endsWithWildcard\n );\n }\n\n /**\n * Initialize this instance.\n * @param {Pattern[]} patterns The matchers.\n * @param {string} basePath The base path.\n * @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.\n */\n constructor(patterns, basePath, endsWithWildcard = false) {\n\n /** @type {Pattern[]} */\n this.patterns = patterns;\n\n /** @type {string} */\n this.basePath = basePath;\n\n /** @type {boolean} */\n this.endsWithWildcard = endsWithWildcard;\n }\n\n /**\n * Test if a given path is matched or not.\n * @param {string} filePath The absolute path to the target file.\n * @returns {boolean} `true` if the path was matched.\n * @throws {Error} When invalid `filePath` is given.\n */\n test(filePath) {\n if (typeof filePath !== \"string\" || !path.isAbsolute(filePath)) {\n throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);\n }\n const relativePath = path.relative(this.basePath, filePath);\n\n return this.patterns.every(({ includes, excludes }) => (\n (!includes || includes.some(m => m.match(relativePath))) &&\n (!excludes || !excludes.some(m => m.match(relativePath)))\n ));\n }\n\n /**\n * Converts this instance to a JSON compatible object.\n * @returns {Object} a JSON compatible object.\n */\n toJSON() {\n if (this.patterns.length === 1) {\n return {\n ...patternToJson(this.patterns[0]),\n basePath: this.basePath\n };\n }\n return {\n AND: this.patterns.map(patternToJson),\n basePath: this.basePath\n };\n }\n\n /**\n * Custom inspect method for Node.js `console.log()`.\n * @returns {Object} an object to display by `console.log()`.\n */\n [util.inspect.custom]() {\n return this.toJSON();\n }\n}\n\nexport { OverrideTester };\n","/**\n * @fileoverview `ConfigArray` class.\n * @author Toru Nagashima \n */\n\nimport { ConfigArray, getUsedExtractedConfigs } from \"./config-array.js\";\nimport { ConfigDependency } from \"./config-dependency.js\";\nimport { ExtractedConfig } from \"./extracted-config.js\";\nimport { IgnorePattern } from \"./ignore-pattern.js\";\nimport { OverrideTester } from \"./override-tester.js\";\n\nexport {\n ConfigArray,\n ConfigDependency,\n ExtractedConfig,\n IgnorePattern,\n OverrideTester,\n getUsedExtractedConfigs\n};\n","/**\n * @fileoverview Config file operations. This file must be usable in the browser,\n * so no Node-specific code can be here.\n * @author Nicholas C. Zakas\n */\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\n\nconst RULE_SEVERITY_STRINGS = [\"off\", \"warn\", \"error\"],\n RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {\n map[value] = index;\n return map;\n }, {}),\n VALID_SEVERITIES = new Set([0, 1, 2, \"off\", \"warn\", \"error\"]);\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * Normalizes the severity value of a rule's configuration to a number\n * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally\n * received from the user. A valid config value is either 0, 1, 2, the string \"off\" (treated the same as 0),\n * the string \"warn\" (treated the same as 1), the string \"error\" (treated the same as 2), or an array\n * whose first element is one of the above values. Strings are matched case-insensitively.\n * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.\n */\nfunction getRuleSeverity(ruleConfig) {\n const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;\n\n if (severityValue === 0 || severityValue === 1 || severityValue === 2) {\n return severityValue;\n }\n\n if (typeof severityValue === \"string\") {\n return RULE_SEVERITY[severityValue.toLowerCase()] || 0;\n }\n\n return 0;\n}\n\n/**\n * Converts old-style severity settings (0, 1, 2) into new-style\n * severity settings (off, warn, error) for all rules. Assumption is that severity\n * values have already been validated as correct.\n * @param {Object} config The config object to normalize.\n * @returns {void}\n */\nfunction normalizeToStrings(config) {\n\n if (config.rules) {\n Object.keys(config.rules).forEach(ruleId => {\n const ruleConfig = config.rules[ruleId];\n\n if (typeof ruleConfig === \"number\") {\n config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];\n } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === \"number\") {\n ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];\n }\n });\n }\n}\n\n/**\n * Determines if the severity for the given rule configuration represents an error.\n * @param {int|string|Array} ruleConfig The configuration for an individual rule.\n * @returns {boolean} True if the rule represents an error, false if not.\n */\nfunction isErrorSeverity(ruleConfig) {\n return getRuleSeverity(ruleConfig) === 2;\n}\n\n/**\n * Checks whether a given config has valid severity or not.\n * @param {number|string|Array} ruleConfig The configuration for an individual rule.\n * @returns {boolean} `true` if the configuration has valid severity.\n */\nfunction isValidSeverity(ruleConfig) {\n let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;\n\n if (typeof severity === \"string\") {\n severity = severity.toLowerCase();\n }\n return VALID_SEVERITIES.has(severity);\n}\n\n/**\n * Checks whether every rule of a given config has valid severity or not.\n * @param {Object} config The configuration for rules.\n * @returns {boolean} `true` if the configuration has valid severity.\n */\nfunction isEverySeverityValid(config) {\n return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));\n}\n\n/**\n * Normalizes a value for a global in a config\n * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in\n * a global directive comment\n * @returns {(\"readable\"|\"writeable\"|\"off\")} The value normalized as a string\n * @throws Error if global value is invalid\n */\nfunction normalizeConfigGlobal(configuredValue) {\n switch (configuredValue) {\n case \"off\":\n return \"off\";\n\n case true:\n case \"true\":\n case \"writeable\":\n case \"writable\":\n return \"writable\";\n\n case null:\n case false:\n case \"false\":\n case \"readable\":\n case \"readonly\":\n return \"readonly\";\n\n default:\n throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);\n }\n}\n\nexport {\n getRuleSeverity,\n normalizeToStrings,\n isErrorSeverity,\n isValidSeverity,\n isEverySeverityValid,\n normalizeConfigGlobal\n};\n","/**\n * @fileoverview Provide the function that emits deprecation warnings.\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport path from \"node:path\";\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\n\n// Defitions for deprecation warnings.\nconst deprecationWarningMessages = {\n ESLINT_LEGACY_ECMAFEATURES:\n \"The 'ecmaFeatures' config file property is deprecated and has no effect.\",\n ESLINT_PERSONAL_CONFIG_LOAD:\n \"'~/.eslintrc.*' config files have been deprecated. \" +\n \"Please use a config file per project or the '--config' option.\",\n ESLINT_PERSONAL_CONFIG_SUPPRESS:\n \"'~/.eslintrc.*' config files have been deprecated. \" +\n \"Please remove it or add 'root:true' to the config files in your \" +\n \"projects in order to avoid loading '~/.eslintrc.*' accidentally.\"\n};\n\nconst sourceFileErrorCache = new Set();\n\n/**\n * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted\n * for each unique file path, but repeated invocations with the same file path have no effect.\n * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.\n * @param {string} source The name of the configuration source to report the warning for.\n * @param {string} errorCode The warning message to show.\n * @returns {void}\n */\nfunction emitDeprecationWarning(source, errorCode) {\n const cacheKey = JSON.stringify({ source, errorCode });\n\n if (sourceFileErrorCache.has(cacheKey)) {\n return;\n }\n sourceFileErrorCache.add(cacheKey);\n\n const rel = path.relative(process.cwd(), source);\n const message = deprecationWarningMessages[errorCode];\n\n process.emitWarning(\n `${message} (found in \"${rel}\")`,\n \"DeprecationWarning\",\n errorCode\n );\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport {\n emitDeprecationWarning\n};\n","/**\n * @fileoverview The instance of Ajv validator.\n * @author Evgeny Poberezkin\n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport Ajv from \"ajv\";\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/*\n * Copied from ajv/lib/refs/json-schema-draft-04.json\n * The MIT License (MIT)\n * Copyright (c) 2015-2017 Evgeny Poberezkin\n */\nconst metaSchema = {\n id: \"http://json-schema.org/draft-04/schema#\",\n $schema: \"http://json-schema.org/draft-04/schema#\",\n description: \"Core schema meta-schema\",\n definitions: {\n schemaArray: {\n type: \"array\",\n minItems: 1,\n items: { $ref: \"#\" }\n },\n positiveInteger: {\n type: \"integer\",\n minimum: 0\n },\n positiveIntegerDefault0: {\n allOf: [{ $ref: \"#/definitions/positiveInteger\" }, { default: 0 }]\n },\n simpleTypes: {\n enum: [\"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"]\n },\n stringArray: {\n type: \"array\",\n items: { type: \"string\" },\n minItems: 1,\n uniqueItems: true\n }\n },\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n $schema: {\n type: \"string\"\n },\n title: {\n type: \"string\"\n },\n description: {\n type: \"string\"\n },\n default: { },\n multipleOf: {\n type: \"number\",\n minimum: 0,\n exclusiveMinimum: true\n },\n maximum: {\n type: \"number\"\n },\n exclusiveMaximum: {\n type: \"boolean\",\n default: false\n },\n minimum: {\n type: \"number\"\n },\n exclusiveMinimum: {\n type: \"boolean\",\n default: false\n },\n maxLength: { $ref: \"#/definitions/positiveInteger\" },\n minLength: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n pattern: {\n type: \"string\",\n format: \"regex\"\n },\n additionalItems: {\n anyOf: [\n { type: \"boolean\" },\n { $ref: \"#\" }\n ],\n default: { }\n },\n items: {\n anyOf: [\n { $ref: \"#\" },\n { $ref: \"#/definitions/schemaArray\" }\n ],\n default: { }\n },\n maxItems: { $ref: \"#/definitions/positiveInteger\" },\n minItems: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n uniqueItems: {\n type: \"boolean\",\n default: false\n },\n maxProperties: { $ref: \"#/definitions/positiveInteger\" },\n minProperties: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n required: { $ref: \"#/definitions/stringArray\" },\n additionalProperties: {\n anyOf: [\n { type: \"boolean\" },\n { $ref: \"#\" }\n ],\n default: { }\n },\n definitions: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n properties: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n patternProperties: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n dependencies: {\n type: \"object\",\n additionalProperties: {\n anyOf: [\n { $ref: \"#\" },\n { $ref: \"#/definitions/stringArray\" }\n ]\n }\n },\n enum: {\n type: \"array\",\n minItems: 1,\n uniqueItems: true\n },\n type: {\n anyOf: [\n { $ref: \"#/definitions/simpleTypes\" },\n {\n type: \"array\",\n items: { $ref: \"#/definitions/simpleTypes\" },\n minItems: 1,\n uniqueItems: true\n }\n ]\n },\n format: { type: \"string\" },\n allOf: { $ref: \"#/definitions/schemaArray\" },\n anyOf: { $ref: \"#/definitions/schemaArray\" },\n oneOf: { $ref: \"#/definitions/schemaArray\" },\n not: { $ref: \"#\" }\n },\n dependencies: {\n exclusiveMaximum: [\"maximum\"],\n exclusiveMinimum: [\"minimum\"]\n },\n default: { }\n};\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport default (additionalOptions = {}) => {\n const ajv = new Ajv({\n meta: false,\n useDefaults: true,\n validateSchema: false,\n missingRefs: \"ignore\",\n verbose: true,\n schemaId: \"auto\",\n ...additionalOptions\n });\n\n ajv.addMetaSchema(metaSchema);\n // eslint-disable-next-line no-underscore-dangle -- part of the API\n ajv._opts.defaultMeta = metaSchema.id;\n\n return ajv;\n};\n","/**\n * @fileoverview Applies default rule options\n * @author JoshuaKGoldberg\n */\n\n/**\n * Check if the variable contains an object strictly rejecting arrays\n * @param {unknown} value an object\n * @returns {boolean} Whether value is an object\n */\nfunction isObjectNotArray(value) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Deeply merges second on top of first, creating a new {} object if needed.\n * @param {T} first Base, default value.\n * @param {U} second User-specified value.\n * @returns {T | U | (T & U)} Merged equivalent of second on top of first.\n */\nfunction deepMergeObjects(first, second) {\n if (second === void 0) {\n return first;\n }\n\n if (!isObjectNotArray(first) || !isObjectNotArray(second)) {\n return second;\n }\n\n const result = { ...first, ...second };\n\n for (const key of Object.keys(second)) {\n if (Object.prototype.propertyIsEnumerable.call(first, key)) {\n result[key] = deepMergeObjects(first[key], second[key]);\n }\n }\n\n return result;\n}\n\n/**\n * Deeply merges second on top of first, creating a new [] array if needed.\n * @param {T[] | undefined} first Base, default values.\n * @param {U[] | undefined} second User-specified values.\n * @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first.\n */\nfunction deepMergeArrays(first, second) {\n if (!first || !second) {\n return second || first || [];\n }\n\n return [\n ...first.map((value, i) => deepMergeObjects(value, second[i])),\n ...second.slice(first.length)\n ];\n}\n\nexport { deepMergeArrays };\n","/**\n * @fileoverview Defines a schema for configs.\n * @author Sylvan Mably\n */\n\nconst baseConfigProperties = {\n $schema: { type: \"string\" },\n env: { type: \"object\" },\n extends: { $ref: \"#/definitions/stringOrStrings\" },\n globals: { type: \"object\" },\n overrides: {\n type: \"array\",\n items: { $ref: \"#/definitions/overrideConfig\" },\n additionalItems: false\n },\n parser: { type: [\"string\", \"null\"] },\n parserOptions: { type: \"object\" },\n plugins: { type: \"array\" },\n processor: { type: \"string\" },\n rules: { type: \"object\" },\n settings: { type: \"object\" },\n noInlineConfig: { type: \"boolean\" },\n reportUnusedDisableDirectives: { type: \"boolean\" },\n\n ecmaFeatures: { type: \"object\" } // deprecated; logs a warning when used\n};\n\nconst configSchema = {\n definitions: {\n stringOrStrings: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"array\",\n items: { type: \"string\" },\n additionalItems: false\n }\n ]\n },\n stringOrStringsRequired: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"array\",\n items: { type: \"string\" },\n additionalItems: false,\n minItems: 1\n }\n ]\n },\n\n // Config at top-level.\n objectConfig: {\n type: \"object\",\n properties: {\n root: { type: \"boolean\" },\n ignorePatterns: { $ref: \"#/definitions/stringOrStrings\" },\n ...baseConfigProperties\n },\n additionalProperties: false\n },\n\n // Config in `overrides`.\n overrideConfig: {\n type: \"object\",\n properties: {\n excludedFiles: { $ref: \"#/definitions/stringOrStrings\" },\n files: { $ref: \"#/definitions/stringOrStringsRequired\" },\n ...baseConfigProperties\n },\n required: [\"files\"],\n additionalProperties: false\n }\n },\n\n $ref: \"#/definitions/objectConfig\"\n};\n\nexport default configSchema;\n","/**\n * @fileoverview Defines environment settings and globals.\n * @author Elan Shanker\n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport globals from \"globals\";\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n/**\n * Get the object that has difference.\n * @param {Record} current The newer object.\n * @param {Record} prev The older object.\n * @returns {Record} The difference object.\n */\nfunction getDiff(current, prev) {\n const retv = {};\n\n for (const [key, value] of Object.entries(current)) {\n if (!Object.hasOwn(prev, key)) {\n retv[key] = value;\n }\n }\n\n return retv;\n}\n\nconst newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...\nconst newGlobals2017 = {\n Atomics: false,\n SharedArrayBuffer: false\n};\nconst newGlobals2020 = {\n BigInt: false,\n BigInt64Array: false,\n BigUint64Array: false,\n globalThis: false\n};\n\nconst newGlobals2021 = {\n AggregateError: false,\n FinalizationRegistry: false,\n WeakRef: false\n};\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/** @type {Map} */\nexport default new Map(Object.entries({\n\n // Language\n builtin: {\n globals: globals.es5\n },\n es6: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 6\n }\n },\n es2015: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 6\n }\n },\n es2016: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 7\n }\n },\n es2017: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 8\n }\n },\n es2018: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 9\n }\n },\n es2019: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 10\n }\n },\n es2020: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },\n parserOptions: {\n ecmaVersion: 11\n }\n },\n es2021: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 12\n }\n },\n es2022: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 13\n }\n },\n es2023: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 14\n }\n },\n es2024: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 15\n }\n },\n\n // Platforms\n browser: {\n globals: globals.browser\n },\n node: {\n globals: globals.node,\n parserOptions: {\n ecmaFeatures: {\n globalReturn: true\n }\n }\n },\n \"shared-node-browser\": {\n globals: globals[\"shared-node-browser\"]\n },\n worker: {\n globals: globals.worker\n },\n serviceworker: {\n globals: globals.serviceworker\n },\n\n // Frameworks\n commonjs: {\n globals: globals.commonjs,\n parserOptions: {\n ecmaFeatures: {\n globalReturn: true\n }\n }\n },\n amd: {\n globals: globals.amd\n },\n mocha: {\n globals: globals.mocha\n },\n jasmine: {\n globals: globals.jasmine\n },\n jest: {\n globals: globals.jest\n },\n phantomjs: {\n globals: globals.phantomjs\n },\n jquery: {\n globals: globals.jquery\n },\n qunit: {\n globals: globals.qunit\n },\n prototypejs: {\n globals: globals.prototypejs\n },\n shelljs: {\n globals: globals.shelljs\n },\n meteor: {\n globals: globals.meteor\n },\n mongo: {\n globals: globals.mongo\n },\n protractor: {\n globals: globals.protractor\n },\n applescript: {\n globals: globals.applescript\n },\n nashorn: {\n globals: globals.nashorn\n },\n atomtest: {\n globals: globals.atomtest\n },\n embertest: {\n globals: globals.embertest\n },\n webextensions: {\n globals: globals.webextensions\n },\n greasemonkey: {\n globals: globals.greasemonkey\n }\n}));\n","/**\n * @fileoverview Validates configs.\n * @author Brandon Mills\n */\n\n/* eslint class-methods-use-this: \"off\" -- not needed in this file */\n\n//------------------------------------------------------------------------------\n// Typedefs\n//------------------------------------------------------------------------------\n\n/** @typedef {import(\"../shared/types\").Rule} Rule */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport util from \"node:util\";\nimport * as ConfigOps from \"./config-ops.js\";\nimport { emitDeprecationWarning } from \"./deprecation-warnings.js\";\nimport ajvOrig from \"./ajv.js\";\nimport { deepMergeArrays } from \"./deep-merge-arrays.js\";\nimport configSchema from \"../../conf/config-schema.js\";\nimport BuiltInEnvironments from \"../../conf/environments.js\";\n\nconst ajv = ajvOrig();\n\nconst ruleValidators = new WeakMap();\nconst noop = Function.prototype;\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\nlet validateSchema;\nconst severityMap = {\n error: 2,\n warn: 1,\n off: 0\n};\n\nconst validated = new WeakSet();\n\n// JSON schema that disallows passing any options\nconst noOptionsSchema = Object.freeze({\n type: \"array\",\n minItems: 0,\n maxItems: 0\n});\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Validator for configuration objects.\n */\nexport default class ConfigValidator {\n constructor({ builtInRules = new Map() } = {}) {\n this.builtInRules = builtInRules;\n }\n\n /**\n * Gets a complete options schema for a rule.\n * @param {Rule} rule A rule object\n * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`.\n * @returns {Object|null} JSON Schema for the rule's options.\n * `null` if rule wasn't passed or its `meta.schema` is `false`.\n */\n getRuleOptionsSchema(rule) {\n if (!rule) {\n return null;\n }\n\n if (!rule.meta) {\n return { ...noOptionsSchema }; // default if `meta.schema` is not specified\n }\n\n const schema = rule.meta.schema;\n\n if (typeof schema === \"undefined\") {\n return { ...noOptionsSchema }; // default if `meta.schema` is not specified\n }\n\n // `schema:false` is an allowed explicit opt-out of options validation for the rule\n if (schema === false) {\n return null;\n }\n\n if (typeof schema !== \"object\" || schema === null) {\n throw new TypeError(\"Rule's `meta.schema` must be an array or object\");\n }\n\n // ESLint-specific array form needs to be converted into a valid JSON Schema definition\n if (Array.isArray(schema)) {\n if (schema.length) {\n return {\n type: \"array\",\n items: schema,\n minItems: 0,\n maxItems: schema.length\n };\n }\n\n // `schema:[]` is an explicit way to specify that the rule does not accept any options\n return { ...noOptionsSchema };\n }\n\n // `schema:` is assumed to be a valid JSON Schema definition\n return schema;\n }\n\n /**\n * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.\n * @param {options} options The given options for the rule.\n * @returns {number|string} The rule's severity value\n * @throws {Error} If the severity is invalid.\n */\n validateRuleSeverity(options) {\n const severity = Array.isArray(options) ? options[0] : options;\n const normSeverity = typeof severity === \"string\" ? severityMap[severity.toLowerCase()] : severity;\n\n if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {\n return normSeverity;\n }\n\n throw new Error(`\\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, \"\\\"\").replace(/\\n/gu, \"\")}').\\n`);\n\n }\n\n /**\n * Validates the non-severity options passed to a rule, based on its schema.\n * @param {{create: Function}} rule The rule to validate\n * @param {Array} localOptions The options for the rule, excluding severity\n * @returns {void}\n * @throws {Error} If the options are invalid.\n */\n validateRuleSchema(rule, localOptions) {\n if (!ruleValidators.has(rule)) {\n try {\n const schema = this.getRuleOptionsSchema(rule);\n\n if (schema) {\n ruleValidators.set(rule, ajv.compile(schema));\n }\n } catch (err) {\n const errorWithCode = new Error(err.message, { cause: err });\n\n errorWithCode.code = \"ESLINT_INVALID_RULE_OPTIONS_SCHEMA\";\n\n throw errorWithCode;\n }\n }\n\n const validateRule = ruleValidators.get(rule);\n\n if (validateRule) {\n const mergedOptions = deepMergeArrays(rule.meta?.defaultOptions, localOptions);\n\n validateRule(mergedOptions);\n\n if (validateRule.errors) {\n throw new Error(validateRule.errors.map(\n error => `\\tValue ${JSON.stringify(error.data)} ${error.message}.\\n`\n ).join(\"\"));\n }\n }\n }\n\n /**\n * Validates a rule's options against its schema.\n * @param {{create: Function}|null} rule The rule that the config is being validated for\n * @param {string} ruleId The rule's unique name.\n * @param {Array|number} options The given options for the rule.\n * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,\n * no source is prepended to the message.\n * @returns {void}\n * @throws {Error} If the options are invalid.\n */\n validateRuleOptions(rule, ruleId, options, source = null) {\n try {\n const severity = this.validateRuleSeverity(options);\n\n if (severity !== 0) {\n this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);\n }\n } catch (err) {\n let enhancedMessage = err.code === \"ESLINT_INVALID_RULE_OPTIONS_SCHEMA\"\n ? `Error while processing options validation schema of rule '${ruleId}': ${err.message}`\n : `Configuration for rule \"${ruleId}\" is invalid:\\n${err.message}`;\n\n if (typeof source === \"string\") {\n enhancedMessage = `${source}:\\n\\t${enhancedMessage}`;\n }\n\n const enhancedError = new Error(enhancedMessage, { cause: err });\n\n if (err.code) {\n enhancedError.code = err.code;\n }\n\n throw enhancedError;\n }\n }\n\n /**\n * Validates an environment object\n * @param {Object} environment The environment config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded environments.\n * @returns {void}\n * @throws {Error} If the environment is invalid.\n */\n validateEnvironment(\n environment,\n source,\n getAdditionalEnv = noop\n ) {\n\n // not having an environment is ok\n if (!environment) {\n return;\n }\n\n Object.keys(environment).forEach(id => {\n const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;\n\n if (!env) {\n const message = `${source}:\\n\\tEnvironment key \"${id}\" is unknown\\n`;\n\n throw new Error(message);\n }\n });\n }\n\n /**\n * Validates a rules config object\n * @param {Object} rulesConfig The rules config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {(ruleId:string) => Object} getAdditionalRule A map from strings to loaded rules\n * @returns {void}\n */\n validateRules(\n rulesConfig,\n source,\n getAdditionalRule = noop\n ) {\n if (!rulesConfig) {\n return;\n }\n\n Object.keys(rulesConfig).forEach(id => {\n const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;\n\n this.validateRuleOptions(rule, id, rulesConfig[id], source);\n });\n }\n\n /**\n * Validates a `globals` section of a config file\n * @param {Object} globalsConfig The `globals` section\n * @param {string|null} source The name of the configuration source to report in the event of an error.\n * @returns {void}\n */\n validateGlobals(globalsConfig, source = null) {\n if (!globalsConfig) {\n return;\n }\n\n Object.entries(globalsConfig)\n .forEach(([configuredGlobal, configuredValue]) => {\n try {\n ConfigOps.normalizeConfigGlobal(configuredValue);\n } catch (err) {\n throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\\n${err.message}`);\n }\n });\n }\n\n /**\n * Validate `processor` configuration.\n * @param {string|undefined} processorName The processor name.\n * @param {string} source The name of config file.\n * @param {(id:string) => Processor} getProcessor The getter of defined processors.\n * @returns {void}\n * @throws {Error} If the processor is invalid.\n */\n validateProcessor(processorName, source, getProcessor) {\n if (processorName && !getProcessor(processorName)) {\n throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);\n }\n }\n\n /**\n * Formats an array of schema validation errors.\n * @param {Array} errors An array of error messages to format.\n * @returns {string} Formatted error message\n */\n formatErrors(errors) {\n return errors.map(error => {\n if (error.keyword === \"additionalProperties\") {\n const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;\n\n return `Unexpected top-level property \"${formattedPropertyPath}\"`;\n }\n if (error.keyword === \"type\") {\n const formattedField = error.dataPath.slice(1);\n const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join(\"/\") : error.schema;\n const formattedValue = JSON.stringify(error.data);\n\n return `Property \"${formattedField}\" is the wrong type (expected ${formattedExpectedType} but got \\`${formattedValue}\\`)`;\n }\n\n const field = error.dataPath[0] === \".\" ? error.dataPath.slice(1) : error.dataPath;\n\n return `\"${field}\" ${error.message}. Value: ${JSON.stringify(error.data)}`;\n }).map(message => `\\t- ${message}.\\n`).join(\"\");\n }\n\n /**\n * Validates the top level properties of the config object.\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @returns {void}\n * @throws {Error} If the config is invalid.\n */\n validateConfigSchema(config, source = null) {\n validateSchema = validateSchema || ajv.compile(configSchema);\n\n if (!validateSchema(config)) {\n throw new Error(`ESLint configuration in ${source} is invalid:\\n${this.formatErrors(validateSchema.errors)}`);\n }\n\n if (Object.hasOwn(config, \"ecmaFeatures\")) {\n emitDeprecationWarning(source, \"ESLINT_LEGACY_ECMAFEATURES\");\n }\n }\n\n /**\n * Validates an entire config object.\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {(ruleId:string) => Object} [getAdditionalRule] A map from strings to loaded rules.\n * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded envs.\n * @returns {void}\n */\n validate(config, source, getAdditionalRule, getAdditionalEnv) {\n this.validateConfigSchema(config, source);\n this.validateRules(config.rules, source, getAdditionalRule);\n this.validateEnvironment(config.env, source, getAdditionalEnv);\n this.validateGlobals(config.globals, source);\n\n for (const override of config.overrides || []) {\n this.validateRules(override.rules, source, getAdditionalRule);\n this.validateEnvironment(override.env, source, getAdditionalEnv);\n this.validateGlobals(config.globals, source);\n }\n }\n\n /**\n * Validate config array object.\n * @param {ConfigArray} configArray The config array to validate.\n * @returns {void}\n */\n validateConfigArray(configArray) {\n const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);\n const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);\n const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);\n\n // Validate.\n for (const element of configArray) {\n if (validated.has(element)) {\n continue;\n }\n validated.add(element);\n\n this.validateEnvironment(element.env, element.name, getPluginEnv);\n this.validateGlobals(element.globals, element.name);\n this.validateProcessor(element.processor, element.name, getPluginProcessor);\n this.validateRules(element.rules, element.name, getPluginRule);\n }\n }\n\n}\n","/**\n * @fileoverview Common helpers for naming of plugins, formatters and configs\n */\n\nconst NAMESPACE_REGEX = /^@.*\\//iu;\n\n/**\n * Brings package name to correct format based on prefix\n * @param {string} name The name of the package.\n * @param {string} prefix Can be either \"eslint-plugin\", \"eslint-config\" or \"eslint-formatter\"\n * @returns {string} Normalized name of the package\n * @private\n */\nfunction normalizePackageName(name, prefix) {\n let normalizedName = name;\n\n /**\n * On Windows, name can come in with Windows slashes instead of Unix slashes.\n * Normalize to Unix first to avoid errors later on.\n * https://github.com/eslint/eslint/issues/5644\n */\n if (normalizedName.includes(\"\\\\\")) {\n normalizedName = normalizedName.replace(/\\\\/gu, \"/\");\n }\n\n if (normalizedName.charAt(0) === \"@\") {\n\n /**\n * it's a scoped package\n * package name is the prefix, or just a username\n */\n const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, \"u\"),\n scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, \"u\");\n\n if (scopedPackageShortcutRegex.test(normalizedName)) {\n normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);\n } else if (!scopedPackageNameRegex.test(normalizedName.split(\"/\")[1])) {\n\n /**\n * for scoped packages, insert the prefix after the first / unless\n * the path is already @scope/eslint or @scope/eslint-xxx-yyy\n */\n normalizedName = normalizedName.replace(/^@([^/]+)\\/(.*)$/u, `@$1/${prefix}-$2`);\n }\n } else if (!normalizedName.startsWith(`${prefix}-`)) {\n normalizedName = `${prefix}-${normalizedName}`;\n }\n\n return normalizedName;\n}\n\n/**\n * Removes the prefix from a fullname.\n * @param {string} fullname The term which may have the prefix.\n * @param {string} prefix The prefix to remove.\n * @returns {string} The term without prefix.\n */\nfunction getShorthandName(fullname, prefix) {\n if (fullname[0] === \"@\") {\n let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, \"u\").exec(fullname);\n\n if (matchResult) {\n return matchResult[1];\n }\n\n matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, \"u\").exec(fullname);\n if (matchResult) {\n return `${matchResult[1]}/${matchResult[2]}`;\n }\n } else if (fullname.startsWith(`${prefix}-`)) {\n return fullname.slice(prefix.length + 1);\n }\n\n return fullname;\n}\n\n/**\n * Gets the scope (namespace) of a term.\n * @param {string} term The term which may have the namespace.\n * @returns {string} The namespace of the term if it has one.\n */\nfunction getNamespaceFromTerm(term) {\n const match = term.match(NAMESPACE_REGEX);\n\n return match ? match[0] : \"\";\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport {\n normalizePackageName,\n getShorthandName,\n getNamespaceFromTerm\n};\n","/**\n * Utility for resolving a module relative to another module\n * @author Teddy Katz\n */\n\nimport Module from \"node:module\";\n\n/*\n * `Module.createRequire` is added in v12.2.0. It supports URL as well.\n * We only support the case where the argument is a filepath, not a URL.\n */\nconst createRequire = Module.createRequire;\n\n/**\n * Resolves a Node module relative to another module\n * @param {string} moduleName The name of a Node module, or a path to a Node module.\n * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be\n * a file rather than a directory, but the file need not actually exist.\n * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`\n * @throws {Error} When the module cannot be resolved.\n */\nfunction resolve(moduleName, relativeToPath) {\n try {\n return createRequire(relativeToPath).resolve(moduleName);\n } catch (error) {\n\n // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.\n if (\n typeof error === \"object\" &&\n error !== null &&\n error.code === \"MODULE_NOT_FOUND\" &&\n !error.requireStack &&\n error.message.includes(moduleName)\n ) {\n error.message += `\\nRequire stack:\\n- ${relativeToPath}`;\n }\n throw error;\n }\n}\n\nexport {\n resolve\n};\n","/**\n * @fileoverview The factory of `ConfigArray` objects.\n *\n * This class provides methods to create `ConfigArray` instance.\n *\n * - `create(configData, options)`\n * Create a `ConfigArray` instance from a config data. This is to handle CLI\n * options except `--config`.\n * - `loadFile(filePath, options)`\n * Create a `ConfigArray` instance from a config file. This is to handle\n * `--config` option. If the file was not found, throws the following error:\n * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.\n * - If the filename was `package.json`, an IO error or an\n * `ESLINT_CONFIG_FIELD_NOT_FOUND` error.\n * - Otherwise, an IO error such as `ENOENT`.\n * - `loadInDirectory(directoryPath, options)`\n * Create a `ConfigArray` instance from a config file which is on a given\n * directory. This tries to load `.eslintrc.*` or `package.json`. If not\n * found, returns an empty `ConfigArray`.\n * - `loadESLintIgnore(filePath)`\n * Create a `ConfigArray` instance from a config file that is `.eslintignore`\n * format. This is to handle `--ignore-path` option.\n * - `loadDefaultESLintIgnore()`\n * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in\n * the current working directory.\n *\n * `ConfigArrayFactory` class has the responsibility that loads configuration\n * files, including loading `extends`, `parser`, and `plugins`. The created\n * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.\n *\n * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class\n * handles cascading and hierarchy.\n *\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport debugOrig from \"debug\";\nimport fs from \"node:fs\";\nimport importFresh from \"import-fresh\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport stripComments from \"strip-json-comments\";\n\nimport {\n ConfigArray,\n ConfigDependency,\n IgnorePattern,\n OverrideTester\n} from \"./config-array/index.js\";\nimport ConfigValidator from \"./shared/config-validator.js\";\nimport * as naming from \"./shared/naming.js\";\nimport * as ModuleResolver from \"./shared/relative-module-resolver.js\";\n\nconst require = createRequire(import.meta.url);\n\nconst debug = debugOrig(\"eslintrc:config-array-factory\");\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\nconst configFilenames = [\n \".eslintrc.js\",\n \".eslintrc.cjs\",\n \".eslintrc.yaml\",\n \".eslintrc.yml\",\n \".eslintrc.json\",\n \".eslintrc\",\n \"package.json\"\n];\n\n// Define types for VSCode IntelliSense.\n/** @typedef {import(\"./shared/types\").ConfigData} ConfigData */\n/** @typedef {import(\"./shared/types\").OverrideConfigData} OverrideConfigData */\n/** @typedef {import(\"./shared/types\").Parser} Parser */\n/** @typedef {import(\"./shared/types\").Plugin} Plugin */\n/** @typedef {import(\"./shared/types\").Rule} Rule */\n/** @typedef {import(\"./config-array/config-dependency\").DependentParser} DependentParser */\n/** @typedef {import(\"./config-array/config-dependency\").DependentPlugin} DependentPlugin */\n/** @typedef {ConfigArray[0]} ConfigArrayElement */\n\n/**\n * @typedef {Object} ConfigArrayFactoryOptions\n * @property {Map} [additionalPluginPool] The map for additional plugins.\n * @property {string} [cwd] The path to the current working directory.\n * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.\n * @property {Map} builtInRules The rules that are built in to ESLint.\n * @property {Object} [resolver=ModuleResolver] The module resolver object.\n * @property {string} eslintAllPath The path to the definitions for eslint:all.\n * @property {Function} getEslintAllConfig Returns the config data for eslint:all.\n * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.\n * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.\n */\n\n/**\n * @typedef {Object} ConfigArrayFactoryInternalSlots\n * @property {Map} additionalPluginPool The map for additional plugins.\n * @property {string} cwd The path to the current working directory.\n * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.\n * @property {Map} builtInRules The rules that are built in to ESLint.\n * @property {Object} [resolver=ModuleResolver] The module resolver object.\n * @property {string} eslintAllPath The path to the definitions for eslint:all.\n * @property {Function} getEslintAllConfig Returns the config data for eslint:all.\n * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.\n * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.\n */\n\n/**\n * @typedef {Object} ConfigArrayFactoryLoadingContext\n * @property {string} filePath The path to the current configuration.\n * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @property {string} name The name of the current configuration.\n * @property {string} pluginBasePath The base path to resolve plugins.\n * @property {\"config\" | \"ignore\" | \"implicit-processor\"} type The type of the current configuration. This is `\"config\"` in normal. This is `\"ignore\"` if it came from `.eslintignore`. This is `\"implicit-processor\"` if it came from legacy file-extension processors.\n */\n\n/**\n * @typedef {Object} ConfigArrayFactoryLoadingContext\n * @property {string} filePath The path to the current configuration.\n * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @property {string} name The name of the current configuration.\n * @property {\"config\" | \"ignore\" | \"implicit-processor\"} type The type of the current configuration. This is `\"config\"` in normal. This is `\"ignore\"` if it came from `.eslintignore`. This is `\"implicit-processor\"` if it came from legacy file-extension processors.\n */\n\n/** @type {WeakMap} */\nconst internalSlotsMap = new WeakMap();\n\n/** @type {WeakMap} */\nconst normalizedPlugins = new WeakMap();\n\n/**\n * Check if a given string is a file path.\n * @param {string} nameOrPath A module name or file path.\n * @returns {boolean} `true` if the `nameOrPath` is a file path.\n */\nfunction isFilePath(nameOrPath) {\n return (\n /^\\.{1,2}[/\\\\]/u.test(nameOrPath) ||\n path.isAbsolute(nameOrPath)\n );\n}\n\n/**\n * Convenience wrapper for synchronously reading file contents.\n * @param {string} filePath The filename to read.\n * @returns {string} The file contents, with the BOM removed.\n * @private\n */\nfunction readFile(filePath) {\n return fs.readFileSync(filePath, \"utf8\").replace(/^\\ufeff/u, \"\");\n}\n\n/**\n * Loads a YAML configuration from a file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadYAMLConfigFile(filePath) {\n debug(`Loading YAML config file: ${filePath}`);\n\n // lazy load YAML to improve performance when not used\n const yaml = require(\"js-yaml\");\n\n try {\n\n // empty YAML file can be null, so always use\n return yaml.load(readFile(filePath)) || {};\n } catch (e) {\n debug(`Error reading YAML file: ${filePath}`);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Loads a JSON configuration from a file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadJSONConfigFile(filePath) {\n debug(`Loading JSON config file: ${filePath}`);\n\n try {\n return JSON.parse(stripComments(readFile(filePath)));\n } catch (e) {\n debug(`Error reading JSON file: ${filePath}`);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n e.messageTemplate = \"failed-to-read-json\";\n e.messageData = {\n path: filePath,\n message: e.message\n };\n throw e;\n }\n}\n\n/**\n * Loads a legacy (.eslintrc) configuration from a file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadLegacyConfigFile(filePath) {\n debug(`Loading legacy config file: ${filePath}`);\n\n // lazy load YAML to improve performance when not used\n const yaml = require(\"js-yaml\");\n\n try {\n return yaml.load(stripComments(readFile(filePath))) || /* istanbul ignore next */ {};\n } catch (e) {\n debug(\"Error reading YAML file: %s\\n%o\", filePath, e);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Loads a JavaScript configuration from a file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadJSConfigFile(filePath) {\n debug(`Loading JS config file: ${filePath}`);\n try {\n return importFresh(filePath);\n } catch (e) {\n debug(`Error reading JavaScript file: ${filePath}`);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Loads a configuration from a package.json file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadPackageJSONConfigFile(filePath) {\n debug(`Loading package.json config file: ${filePath}`);\n try {\n const packageData = loadJSONConfigFile(filePath);\n\n if (!Object.hasOwn(packageData, \"eslintConfig\")) {\n throw Object.assign(\n new Error(\"package.json file doesn't have 'eslintConfig' field.\"),\n { code: \"ESLINT_CONFIG_FIELD_NOT_FOUND\" }\n );\n }\n\n return packageData.eslintConfig;\n } catch (e) {\n debug(`Error reading package.json file: ${filePath}`);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Loads a `.eslintignore` from a file.\n * @param {string} filePath The filename to load.\n * @returns {string[]} The ignore patterns from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadESLintIgnoreFile(filePath) {\n debug(`Loading .eslintignore file: ${filePath}`);\n\n try {\n return readFile(filePath)\n .split(/\\r?\\n/gu)\n .filter(line => line.trim() !== \"\" && !line.startsWith(\"#\"));\n } catch (e) {\n debug(`Error reading .eslintignore file: ${filePath}`);\n e.message = `Cannot read .eslintignore file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Creates an error to notify about a missing config to extend from.\n * @param {string} configName The name of the missing config.\n * @param {string} importerName The name of the config that imported the missing config\n * @param {string} messageTemplate The text template to source error strings from.\n * @returns {Error} The error object to throw\n * @private\n */\nfunction configInvalidError(configName, importerName, messageTemplate) {\n return Object.assign(\n new Error(`Failed to load config \"${configName}\" to extend from.`),\n {\n messageTemplate,\n messageData: { configName, importerName }\n }\n );\n}\n\n/**\n * Loads a configuration file regardless of the source. Inspects the file path\n * to determine the correctly way to load the config file.\n * @param {string} filePath The path to the configuration.\n * @returns {ConfigData|null} The configuration information.\n * @private\n */\nfunction loadConfigFile(filePath) {\n switch (path.extname(filePath)) {\n case \".js\":\n case \".cjs\":\n return loadJSConfigFile(filePath);\n\n case \".json\":\n if (path.basename(filePath) === \"package.json\") {\n return loadPackageJSONConfigFile(filePath);\n }\n return loadJSONConfigFile(filePath);\n\n case \".yaml\":\n case \".yml\":\n return loadYAMLConfigFile(filePath);\n\n default:\n return loadLegacyConfigFile(filePath);\n }\n}\n\n/**\n * Write debug log.\n * @param {string} request The requested module name.\n * @param {string} relativeTo The file path to resolve the request relative to.\n * @param {string} filePath The resolved file path.\n * @returns {void}\n */\nfunction writeDebugLogForLoading(request, relativeTo, filePath) {\n /* istanbul ignore next */\n if (debug.enabled) {\n let nameAndVersion = null; // eslint-disable-line no-useless-assignment -- known bug in the rule\n\n try {\n const packageJsonPath = ModuleResolver.resolve(\n `${request}/package.json`,\n relativeTo\n );\n const { version = \"unknown\" } = require(packageJsonPath);\n\n nameAndVersion = `${request}@${version}`;\n } catch (error) {\n debug(\"package.json was not found:\", error.message);\n nameAndVersion = request;\n }\n\n debug(\"Loaded: %s (%s)\", nameAndVersion, filePath);\n }\n}\n\n/**\n * Create a new context with default values.\n * @param {ConfigArrayFactoryInternalSlots} slots The internal slots.\n * @param {\"config\" | \"ignore\" | \"implicit-processor\" | undefined} providedType The type of the current configuration. Default is `\"config\"`.\n * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.\n * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.\n * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.\n * @returns {ConfigArrayFactoryLoadingContext} The created context.\n */\nfunction createContext(\n { cwd, resolvePluginsRelativeTo },\n providedType,\n providedName,\n providedFilePath,\n providedMatchBasePath\n) {\n const filePath = providedFilePath\n ? path.resolve(cwd, providedFilePath)\n : \"\";\n const matchBasePath =\n (providedMatchBasePath && path.resolve(cwd, providedMatchBasePath)) ||\n (filePath && path.dirname(filePath)) ||\n cwd;\n const name =\n providedName ||\n (filePath && path.relative(cwd, filePath)) ||\n \"\";\n const pluginBasePath =\n resolvePluginsRelativeTo ||\n (filePath && path.dirname(filePath)) ||\n cwd;\n const type = providedType || \"config\";\n\n return { filePath, matchBasePath, name, pluginBasePath, type };\n}\n\n/**\n * Normalize a given plugin.\n * - Ensure the object to have four properties: configs, environments, processors, and rules.\n * - Ensure the object to not have other properties.\n * @param {Plugin} plugin The plugin to normalize.\n * @returns {Plugin} The normalized plugin.\n */\nfunction normalizePlugin(plugin) {\n\n // first check the cache\n let normalizedPlugin = normalizedPlugins.get(plugin);\n\n if (normalizedPlugin) {\n return normalizedPlugin;\n }\n\n normalizedPlugin = {\n configs: plugin.configs || {},\n environments: plugin.environments || {},\n processors: plugin.processors || {},\n rules: plugin.rules || {}\n };\n\n // save the reference for later\n normalizedPlugins.set(plugin, normalizedPlugin);\n\n return normalizedPlugin;\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * The factory of `ConfigArray` objects.\n */\nclass ConfigArrayFactory {\n\n /**\n * Initialize this instance.\n * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.\n */\n constructor({\n additionalPluginPool = new Map(),\n cwd = process.cwd(),\n resolvePluginsRelativeTo,\n builtInRules,\n resolver = ModuleResolver,\n eslintAllPath,\n getEslintAllConfig,\n eslintRecommendedPath,\n getEslintRecommendedConfig\n } = {}) {\n internalSlotsMap.set(this, {\n additionalPluginPool,\n cwd,\n resolvePluginsRelativeTo:\n resolvePluginsRelativeTo &&\n path.resolve(cwd, resolvePluginsRelativeTo),\n builtInRules,\n resolver,\n eslintAllPath,\n getEslintAllConfig,\n eslintRecommendedPath,\n getEslintRecommendedConfig\n });\n }\n\n /**\n * Create `ConfigArray` instance from a config data.\n * @param {ConfigData|null} configData The config data to create.\n * @param {Object} [options] The options.\n * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @param {string} [options.filePath] The path to this config data.\n * @param {string} [options.name] The config name.\n * @returns {ConfigArray} Loaded config.\n */\n create(configData, { basePath, filePath, name } = {}) {\n if (!configData) {\n return new ConfigArray();\n }\n\n const slots = internalSlotsMap.get(this);\n const ctx = createContext(slots, \"config\", name, filePath, basePath);\n const elements = this._normalizeConfigData(configData, ctx);\n\n return new ConfigArray(...elements);\n }\n\n /**\n * Load a config file.\n * @param {string} filePath The path to a config file.\n * @param {Object} [options] The options.\n * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @param {string} [options.name] The config name.\n * @returns {ConfigArray} Loaded config.\n */\n loadFile(filePath, { basePath, name } = {}) {\n const slots = internalSlotsMap.get(this);\n const ctx = createContext(slots, \"config\", name, filePath, basePath);\n\n return new ConfigArray(...this._loadConfigData(ctx));\n }\n\n /**\n * Load the config file on a given directory if exists.\n * @param {string} directoryPath The path to a directory.\n * @param {Object} [options] The options.\n * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @param {string} [options.name] The config name.\n * @throws {Error} If the config file is invalid.\n * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.\n */\n loadInDirectory(directoryPath, { basePath, name } = {}) {\n const slots = internalSlotsMap.get(this);\n\n for (const filename of configFilenames) {\n const ctx = createContext(\n slots,\n \"config\",\n name,\n path.join(directoryPath, filename),\n basePath\n );\n\n if (fs.existsSync(ctx.filePath) && fs.statSync(ctx.filePath).isFile()) {\n let configData;\n\n try {\n configData = loadConfigFile(ctx.filePath);\n } catch (error) {\n if (!error || error.code !== \"ESLINT_CONFIG_FIELD_NOT_FOUND\") {\n throw error;\n }\n }\n\n if (configData) {\n debug(`Config file found: ${ctx.filePath}`);\n return new ConfigArray(\n ...this._normalizeConfigData(configData, ctx)\n );\n }\n }\n }\n\n debug(`Config file not found on ${directoryPath}`);\n return new ConfigArray();\n }\n\n /**\n * Check if a config file on a given directory exists or not.\n * @param {string} directoryPath The path to a directory.\n * @returns {string | null} The path to the found config file. If not found then null.\n */\n static getPathToConfigFileInDirectory(directoryPath) {\n for (const filename of configFilenames) {\n const filePath = path.join(directoryPath, filename);\n\n if (fs.existsSync(filePath)) {\n if (filename === \"package.json\") {\n try {\n loadPackageJSONConfigFile(filePath);\n return filePath;\n } catch { /* ignore */ }\n } else {\n return filePath;\n }\n }\n }\n return null;\n }\n\n /**\n * Load `.eslintignore` file.\n * @param {string} filePath The path to a `.eslintignore` file to load.\n * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.\n */\n loadESLintIgnore(filePath) {\n const slots = internalSlotsMap.get(this);\n const ctx = createContext(\n slots,\n \"ignore\",\n void 0,\n filePath,\n slots.cwd\n );\n const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);\n\n return new ConfigArray(\n ...this._normalizeESLintIgnoreData(ignorePatterns, ctx)\n );\n }\n\n /**\n * Load `.eslintignore` file in the current working directory.\n * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.\n * @throws {Error} If the ignore file is invalid.\n */\n loadDefaultESLintIgnore() {\n const slots = internalSlotsMap.get(this);\n const eslintIgnorePath = path.resolve(slots.cwd, \".eslintignore\");\n const packageJsonPath = path.resolve(slots.cwd, \"package.json\");\n\n if (fs.existsSync(eslintIgnorePath)) {\n return this.loadESLintIgnore(eslintIgnorePath);\n }\n if (fs.existsSync(packageJsonPath)) {\n const data = loadJSONConfigFile(packageJsonPath);\n\n if (Object.hasOwn(data, \"eslintIgnore\")) {\n if (!Array.isArray(data.eslintIgnore)) {\n throw new Error(\"Package.json eslintIgnore property requires an array of paths\");\n }\n const ctx = createContext(\n slots,\n \"ignore\",\n \"eslintIgnore in package.json\",\n packageJsonPath,\n slots.cwd\n );\n\n return new ConfigArray(\n ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)\n );\n }\n }\n\n return new ConfigArray();\n }\n\n /**\n * Load a given config file.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} Loaded config.\n * @private\n */\n _loadConfigData(ctx) {\n return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);\n }\n\n /**\n * Normalize a given `.eslintignore` data to config array elements.\n * @param {string[]} ignorePatterns The patterns to ignore files.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n *_normalizeESLintIgnoreData(ignorePatterns, ctx) {\n const elements = this._normalizeObjectConfigData(\n { ignorePatterns },\n ctx\n );\n\n // Set `ignorePattern.loose` flag for backward compatibility.\n for (const element of elements) {\n if (element.ignorePattern) {\n element.ignorePattern.loose = true;\n }\n yield element;\n }\n }\n\n /**\n * Normalize a given config to an array.\n * @param {ConfigData} configData The config data to normalize.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n _normalizeConfigData(configData, ctx) {\n const validator = new ConfigValidator();\n\n validator.validateConfigSchema(configData, ctx.name || ctx.filePath);\n return this._normalizeObjectConfigData(configData, ctx);\n }\n\n /**\n * Normalize a given config to an array.\n * @param {ConfigData|OverrideConfigData} configData The config data to normalize.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n *_normalizeObjectConfigData(configData, ctx) {\n const { files, excludedFiles, ...configBody } = configData;\n const criteria = OverrideTester.create(\n files,\n excludedFiles,\n ctx.matchBasePath\n );\n const elements = this._normalizeObjectConfigDataBody(configBody, ctx);\n\n // Apply the criteria to every element.\n for (const element of elements) {\n\n /*\n * Merge the criteria.\n * This is for the `overrides` entries that came from the\n * configurations of `overrides[].extends`.\n */\n element.criteria = OverrideTester.and(criteria, element.criteria);\n\n /*\n * Remove `root` property to ignore `root` settings which came from\n * `extends` in `overrides`.\n */\n if (element.criteria) {\n element.root = void 0;\n }\n\n yield element;\n }\n }\n\n /**\n * Normalize a given config to an array.\n * @param {ConfigData} configData The config data to normalize.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n *_normalizeObjectConfigDataBody(\n {\n env,\n extends: extend,\n globals,\n ignorePatterns,\n noInlineConfig,\n parser: parserName,\n parserOptions,\n plugins: pluginList,\n processor,\n reportUnusedDisableDirectives,\n root,\n rules,\n settings,\n overrides: overrideList = []\n },\n ctx\n ) {\n const extendList = Array.isArray(extend) ? extend : [extend];\n const ignorePattern = ignorePatterns && new IgnorePattern(\n Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],\n ctx.matchBasePath\n );\n\n // Flatten `extends`.\n for (const extendName of extendList.filter(Boolean)) {\n yield* this._loadExtends(extendName, ctx);\n }\n\n // Load parser & plugins.\n const parser = parserName && this._loadParser(parserName, ctx);\n const plugins = pluginList && this._loadPlugins(pluginList, ctx);\n\n // Yield pseudo config data for file extension processors.\n if (plugins) {\n yield* this._takeFileExtensionProcessors(plugins, ctx);\n }\n\n // Yield the config data except `extends` and `overrides`.\n yield {\n\n // Debug information.\n type: ctx.type,\n name: ctx.name,\n filePath: ctx.filePath,\n\n // Config data.\n criteria: null,\n env,\n globals,\n ignorePattern,\n noInlineConfig,\n parser,\n parserOptions,\n plugins,\n processor,\n reportUnusedDisableDirectives,\n root,\n rules,\n settings\n };\n\n // Flatten `overries`.\n for (let i = 0; i < overrideList.length; ++i) {\n yield* this._normalizeObjectConfigData(\n overrideList[i],\n { ...ctx, name: `${ctx.name}#overrides[${i}]` }\n );\n }\n }\n\n /**\n * Load configs of an element in `extends`.\n * @param {string} extendName The name of a base config.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @throws {Error} If the extended config file can't be loaded.\n * @private\n */\n _loadExtends(extendName, ctx) {\n debug(\"Loading {extends:%j} relative to %s\", extendName, ctx.filePath);\n try {\n if (extendName.startsWith(\"eslint:\")) {\n return this._loadExtendedBuiltInConfig(extendName, ctx);\n }\n if (extendName.startsWith(\"plugin:\")) {\n return this._loadExtendedPluginConfig(extendName, ctx);\n }\n return this._loadExtendedShareableConfig(extendName, ctx);\n } catch (error) {\n error.message += `\\nReferenced from: ${ctx.filePath || ctx.name}`;\n throw error;\n }\n }\n\n /**\n * Load configs of an element in `extends`.\n * @param {string} extendName The name of a base config.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @throws {Error} If the extended config file can't be loaded.\n * @private\n */\n _loadExtendedBuiltInConfig(extendName, ctx) {\n const {\n eslintAllPath,\n getEslintAllConfig,\n eslintRecommendedPath,\n getEslintRecommendedConfig\n } = internalSlotsMap.get(this);\n\n if (extendName === \"eslint:recommended\") {\n const name = `${ctx.name} » ${extendName}`;\n\n if (getEslintRecommendedConfig) {\n if (typeof getEslintRecommendedConfig !== \"function\") {\n throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`);\n }\n return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: \"\" });\n }\n return this._loadConfigData({\n ...ctx,\n name,\n filePath: eslintRecommendedPath\n });\n }\n if (extendName === \"eslint:all\") {\n const name = `${ctx.name} » ${extendName}`;\n\n if (getEslintAllConfig) {\n if (typeof getEslintAllConfig !== \"function\") {\n throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`);\n }\n return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: \"\" });\n }\n return this._loadConfigData({\n ...ctx,\n name,\n filePath: eslintAllPath\n });\n }\n\n throw configInvalidError(extendName, ctx.name, \"extend-config-missing\");\n }\n\n /**\n * Load configs of an element in `extends`.\n * @param {string} extendName The name of a base config.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @throws {Error} If the extended config file can't be loaded.\n * @private\n */\n _loadExtendedPluginConfig(extendName, ctx) {\n const slashIndex = extendName.lastIndexOf(\"/\");\n\n if (slashIndex === -1) {\n throw configInvalidError(extendName, ctx.filePath, \"plugin-invalid\");\n }\n\n const pluginName = extendName.slice(\"plugin:\".length, slashIndex);\n const configName = extendName.slice(slashIndex + 1);\n\n if (isFilePath(pluginName)) {\n throw new Error(\"'extends' cannot use a file path for plugins.\");\n }\n\n const plugin = this._loadPlugin(pluginName, ctx);\n const configData =\n plugin.definition &&\n plugin.definition.configs[configName];\n\n if (configData) {\n return this._normalizeConfigData(configData, {\n ...ctx,\n filePath: plugin.filePath || ctx.filePath,\n name: `${ctx.name} » plugin:${plugin.id}/${configName}`\n });\n }\n\n throw plugin.error || configInvalidError(extendName, ctx.filePath, \"extend-config-missing\");\n }\n\n /**\n * Load configs of an element in `extends`.\n * @param {string} extendName The name of a base config.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @throws {Error} If the extended config file can't be loaded.\n * @private\n */\n _loadExtendedShareableConfig(extendName, ctx) {\n const { cwd, resolver } = internalSlotsMap.get(this);\n const relativeTo = ctx.filePath || path.join(cwd, \"__placeholder__.js\");\n let request;\n\n if (isFilePath(extendName)) {\n request = extendName;\n } else if (extendName.startsWith(\".\")) {\n request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.\n } else {\n request = naming.normalizePackageName(\n extendName,\n \"eslint-config\"\n );\n }\n\n let filePath;\n\n try {\n filePath = resolver.resolve(request, relativeTo);\n } catch (error) {\n /* istanbul ignore else */\n if (error && error.code === \"MODULE_NOT_FOUND\") {\n throw configInvalidError(extendName, ctx.filePath, \"extend-config-missing\");\n }\n throw error;\n }\n\n writeDebugLogForLoading(request, relativeTo, filePath);\n return this._loadConfigData({\n ...ctx,\n filePath,\n name: `${ctx.name} » ${request}`\n });\n }\n\n /**\n * Load given plugins.\n * @param {string[]} names The plugin names to load.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {Record} The loaded parser.\n * @private\n */\n _loadPlugins(names, ctx) {\n return names.reduce((map, name) => {\n if (isFilePath(name)) {\n throw new Error(\"Plugins array cannot includes file paths.\");\n }\n const plugin = this._loadPlugin(name, ctx);\n\n map[plugin.id] = plugin;\n\n return map;\n }, {});\n }\n\n /**\n * Load a given parser.\n * @param {string} nameOrPath The package name or the path to a parser file.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {DependentParser} The loaded parser.\n */\n _loadParser(nameOrPath, ctx) {\n debug(\"Loading parser %j from %s\", nameOrPath, ctx.filePath);\n\n const { cwd, resolver } = internalSlotsMap.get(this);\n const relativeTo = ctx.filePath || path.join(cwd, \"__placeholder__.js\");\n\n try {\n const filePath = resolver.resolve(nameOrPath, relativeTo);\n\n writeDebugLogForLoading(nameOrPath, relativeTo, filePath);\n\n return new ConfigDependency({\n definition: require(filePath),\n filePath,\n id: nameOrPath,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n } catch (error) {\n\n // If the parser name is \"espree\", load the espree of ESLint.\n if (nameOrPath === \"espree\") {\n debug(\"Fallback espree.\");\n return new ConfigDependency({\n definition: require(\"espree\"),\n filePath: require.resolve(\"espree\"),\n id: nameOrPath,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n\n debug(\"Failed to load parser '%s' declared in '%s'.\", nameOrPath, ctx.name);\n error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;\n\n return new ConfigDependency({\n error,\n id: nameOrPath,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n }\n\n /**\n * Load a given plugin.\n * @param {string} name The plugin name to load.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {DependentPlugin} The loaded plugin.\n * @private\n */\n _loadPlugin(name, ctx) {\n debug(\"Loading plugin %j from %s\", name, ctx.filePath);\n\n const { additionalPluginPool, resolver } = internalSlotsMap.get(this);\n const request = naming.normalizePackageName(name, \"eslint-plugin\");\n const id = naming.getShorthandName(request, \"eslint-plugin\");\n const relativeTo = path.join(ctx.pluginBasePath, \"__placeholder__.js\");\n\n if (name.match(/\\s+/u)) {\n const error = Object.assign(\n new Error(`Whitespace found in plugin name '${name}'`),\n {\n messageTemplate: \"whitespace-found\",\n messageData: { pluginName: request }\n }\n );\n\n return new ConfigDependency({\n error,\n id,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n\n // Check for additional pool.\n const plugin =\n additionalPluginPool.get(request) ||\n additionalPluginPool.get(id);\n\n if (plugin) {\n return new ConfigDependency({\n definition: normalizePlugin(plugin),\n original: plugin,\n filePath: \"\", // It's unknown where the plugin came from.\n id,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n\n let filePath;\n let error;\n\n try {\n filePath = resolver.resolve(request, relativeTo);\n } catch (resolveError) {\n error = resolveError;\n /* istanbul ignore else */\n if (error && error.code === \"MODULE_NOT_FOUND\") {\n error.messageTemplate = \"plugin-missing\";\n error.messageData = {\n pluginName: request,\n resolvePluginsRelativeTo: ctx.pluginBasePath,\n importerName: ctx.name\n };\n }\n }\n\n if (filePath) {\n try {\n writeDebugLogForLoading(request, relativeTo, filePath);\n\n const startTime = Date.now();\n const pluginDefinition = require(filePath);\n\n debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);\n\n return new ConfigDependency({\n definition: normalizePlugin(pluginDefinition),\n original: pluginDefinition,\n filePath,\n id,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n } catch (loadError) {\n error = loadError;\n }\n }\n\n debug(\"Failed to load plugin '%s' declared in '%s'.\", name, ctx.name);\n error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;\n return new ConfigDependency({\n error,\n id,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n\n /**\n * Take file expression processors as config array elements.\n * @param {Record} plugins The plugin definitions.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The config array elements of file expression processors.\n * @private\n */\n *_takeFileExtensionProcessors(plugins, ctx) {\n for (const pluginId of Object.keys(plugins)) {\n const processors =\n plugins[pluginId] &&\n plugins[pluginId].definition &&\n plugins[pluginId].definition.processors;\n\n if (!processors) {\n continue;\n }\n\n for (const processorId of Object.keys(processors)) {\n if (processorId.startsWith(\".\")) {\n yield* this._normalizeObjectConfigData(\n {\n files: [`*${processorId}`],\n processor: `${pluginId}/${processorId}`\n },\n {\n ...ctx,\n type: \"implicit-processor\",\n name: `${ctx.name}#processors[\"${pluginId}/${processorId}\"]`\n }\n );\n }\n }\n }\n }\n}\n\nexport {\n ConfigArrayFactory,\n createContext,\n loadConfigFile\n};\n","/**\n * @fileoverview `CascadingConfigArrayFactory` class.\n *\n * `CascadingConfigArrayFactory` class has a responsibility:\n *\n * 1. Handles cascading of config files.\n *\n * It provides two methods:\n *\n * - `getConfigArrayForFile(filePath)`\n * Get the corresponded configuration of a given file. This method doesn't\n * throw even if the given file didn't exist.\n * - `clearCache()`\n * Clear the internal cache. You have to call this method when\n * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends\n * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)\n *\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport debugOrig from \"debug\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nimport { ConfigArrayFactory } from \"./config-array-factory.js\";\nimport {\n ConfigArray,\n ConfigDependency,\n IgnorePattern\n} from \"./config-array/index.js\";\nimport ConfigValidator from \"./shared/config-validator.js\";\nimport { emitDeprecationWarning } from \"./shared/deprecation-warnings.js\";\n\nconst debug = debugOrig(\"eslintrc:cascading-config-array-factory\");\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n// Define types for VSCode IntelliSense.\n/** @typedef {import(\"./shared/types\").ConfigData} ConfigData */\n/** @typedef {import(\"./shared/types\").Parser} Parser */\n/** @typedef {import(\"./shared/types\").Plugin} Plugin */\n/** @typedef {import(\"./shared/types\").Rule} Rule */\n/** @typedef {ReturnType} ConfigArray */\n\n/**\n * @typedef {Object} CascadingConfigArrayFactoryOptions\n * @property {Map} [additionalPluginPool] The map for additional plugins.\n * @property {ConfigData} [baseConfig] The config by `baseConfig` option.\n * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.\n * @property {string} [cwd] The base directory to start lookup.\n * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.\n * @property {string[]} [rulePaths] The value of `--rulesdir` option.\n * @property {string} [specificConfigPath] The value of `--config` option.\n * @property {boolean} [useEslintrc] if `false` then it doesn't load config files.\n * @property {Function} loadRules The function to use to load rules.\n * @property {Map} builtInRules The rules that are built in to ESLint.\n * @property {Object} [resolver=ModuleResolver] The module resolver object.\n * @property {string} eslintAllPath The path to the definitions for eslint:all.\n * @property {Function} getEslintAllConfig Returns the config data for eslint:all.\n * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.\n * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.\n */\n\n/**\n * @typedef {Object} CascadingConfigArrayFactoryInternalSlots\n * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.\n * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.\n * @property {ConfigArray} cliConfigArray The config array of CLI options.\n * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.\n * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.\n * @property {Map} configCache The cache from directory paths to config arrays.\n * @property {string} cwd The base directory to start lookup.\n * @property {WeakMap} finalizeCache The cache from config arrays to finalized config arrays.\n * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.\n * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.\n * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.\n * @property {boolean} useEslintrc if `false` then it doesn't load config files.\n * @property {Function} loadRules The function to use to load rules.\n * @property {Map} builtInRules The rules that are built in to ESLint.\n * @property {Object} [resolver=ModuleResolver] The module resolver object.\n * @property {string} eslintAllPath The path to the definitions for eslint:all.\n * @property {Function} getEslintAllConfig Returns the config data for eslint:all.\n * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.\n * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.\n */\n\n/** @type {WeakMap} */\nconst internalSlotsMap = new WeakMap();\n\n/**\n * Create the config array from `baseConfig` and `rulePaths`.\n * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.\n * @returns {ConfigArray} The config array of the base configs.\n */\nfunction createBaseConfigArray({\n configArrayFactory,\n baseConfigData,\n rulePaths,\n cwd,\n loadRules\n}) {\n const baseConfigArray = configArrayFactory.create(\n baseConfigData,\n { name: \"BaseConfig\" }\n );\n\n /*\n * Create the config array element for the default ignore patterns.\n * This element has `ignorePattern` property that ignores the default\n * patterns in the current working directory.\n */\n baseConfigArray.unshift(configArrayFactory.create(\n { ignorePatterns: IgnorePattern.DefaultPatterns },\n { name: \"DefaultIgnorePattern\" }\n )[0]);\n\n /*\n * Load rules `--rulesdir` option as a pseudo plugin.\n * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate\n * the rule's options with only information in the config array.\n */\n if (rulePaths && rulePaths.length > 0) {\n baseConfigArray.push({\n type: \"config\",\n name: \"--rulesdir\",\n filePath: \"\",\n plugins: {\n \"\": new ConfigDependency({\n definition: {\n rules: rulePaths.reduce(\n (map, rulesPath) => Object.assign(\n map,\n loadRules(rulesPath, cwd)\n ),\n {}\n )\n },\n filePath: \"\",\n id: \"\",\n importerName: \"--rulesdir\",\n importerPath: \"\"\n })\n }\n });\n }\n\n return baseConfigArray;\n}\n\n/**\n * Create the config array from CLI options.\n * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.\n * @returns {ConfigArray} The config array of the base configs.\n */\nfunction createCLIConfigArray({\n cliConfigData,\n configArrayFactory,\n cwd,\n ignorePath,\n specificConfigPath\n}) {\n const cliConfigArray = configArrayFactory.create(\n cliConfigData,\n { name: \"CLIOptions\" }\n );\n\n cliConfigArray.unshift(\n ...(ignorePath\n ? configArrayFactory.loadESLintIgnore(ignorePath)\n : configArrayFactory.loadDefaultESLintIgnore())\n );\n\n if (specificConfigPath) {\n cliConfigArray.unshift(\n ...configArrayFactory.loadFile(\n specificConfigPath,\n { name: \"--config\", basePath: cwd }\n )\n );\n }\n\n return cliConfigArray;\n}\n\n/**\n * The error type when there are files matched by a glob, but all of them have been ignored.\n */\nclass ConfigurationNotFoundError extends Error {\n\n\n /**\n * @param {string} directoryPath The directory path.\n */\n constructor(directoryPath) {\n super(`No ESLint configuration found in ${directoryPath}.`);\n this.messageTemplate = \"no-config-found\";\n this.messageData = { directoryPath };\n }\n}\n\n/**\n * This class provides the functionality that enumerates every file which is\n * matched by given glob patterns and that configuration.\n */\nclass CascadingConfigArrayFactory {\n\n /**\n * Initialize this enumerator.\n * @param {CascadingConfigArrayFactoryOptions} options The options.\n */\n constructor({\n additionalPluginPool = new Map(),\n baseConfig: baseConfigData = null,\n cliConfig: cliConfigData = null,\n cwd = process.cwd(),\n ignorePath,\n resolvePluginsRelativeTo,\n rulePaths = [],\n specificConfigPath = null,\n useEslintrc = true,\n builtInRules = new Map(),\n loadRules,\n resolver,\n eslintRecommendedPath,\n getEslintRecommendedConfig,\n eslintAllPath,\n getEslintAllConfig\n } = {}) {\n const configArrayFactory = new ConfigArrayFactory({\n additionalPluginPool,\n cwd,\n resolvePluginsRelativeTo,\n builtInRules,\n resolver,\n eslintRecommendedPath,\n getEslintRecommendedConfig,\n eslintAllPath,\n getEslintAllConfig\n });\n\n internalSlotsMap.set(this, {\n baseConfigArray: createBaseConfigArray({\n baseConfigData,\n configArrayFactory,\n cwd,\n rulePaths,\n loadRules\n }),\n baseConfigData,\n cliConfigArray: createCLIConfigArray({\n cliConfigData,\n configArrayFactory,\n cwd,\n ignorePath,\n specificConfigPath\n }),\n cliConfigData,\n configArrayFactory,\n configCache: new Map(),\n cwd,\n finalizeCache: new WeakMap(),\n ignorePath,\n rulePaths,\n specificConfigPath,\n useEslintrc,\n builtInRules,\n loadRules\n });\n }\n\n /**\n * The path to the current working directory.\n * This is used by tests.\n * @type {string}\n */\n get cwd() {\n const { cwd } = internalSlotsMap.get(this);\n\n return cwd;\n }\n\n /**\n * Get the config array of a given file.\n * If `filePath` was not given, it returns the config which contains only\n * `baseConfigData` and `cliConfigData`.\n * @param {string} [filePath] The file path to a file.\n * @param {Object} [options] The options.\n * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.\n * @returns {ConfigArray} The config array of the file.\n */\n getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {\n const {\n baseConfigArray,\n cliConfigArray,\n cwd\n } = internalSlotsMap.get(this);\n\n if (!filePath) {\n return new ConfigArray(...baseConfigArray, ...cliConfigArray);\n }\n\n const directoryPath = path.dirname(path.resolve(cwd, filePath));\n\n debug(`Load config files for ${directoryPath}.`);\n\n return this._finalizeConfigArray(\n this._loadConfigInAncestors(directoryPath),\n directoryPath,\n ignoreNotFoundError\n );\n }\n\n /**\n * Set the config data to override all configs.\n * Require to call `clearCache()` method after this method is called.\n * @param {ConfigData} configData The config data to override all configs.\n * @returns {void}\n */\n setOverrideConfig(configData) {\n const slots = internalSlotsMap.get(this);\n\n slots.cliConfigData = configData;\n }\n\n /**\n * Clear config cache.\n * @returns {void}\n */\n clearCache() {\n const slots = internalSlotsMap.get(this);\n\n slots.baseConfigArray = createBaseConfigArray(slots);\n slots.cliConfigArray = createCLIConfigArray(slots);\n slots.configCache.clear();\n }\n\n /**\n * Load and normalize config files from the ancestor directories.\n * @param {string} directoryPath The path to a leaf directory.\n * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.\n * @returns {ConfigArray} The loaded config.\n * @throws {Error} If a config file is invalid.\n * @private\n */\n _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {\n const {\n baseConfigArray,\n configArrayFactory,\n configCache,\n cwd,\n useEslintrc\n } = internalSlotsMap.get(this);\n\n if (!useEslintrc) {\n return baseConfigArray;\n }\n\n let configArray = configCache.get(directoryPath);\n\n // Hit cache.\n if (configArray) {\n debug(`Cache hit: ${directoryPath}.`);\n return configArray;\n }\n debug(`No cache found: ${directoryPath}.`);\n\n const homePath = os.homedir();\n\n // Consider this is root.\n if (directoryPath === homePath && cwd !== homePath) {\n debug(\"Stop traversing because of considered root.\");\n if (configsExistInSubdirs) {\n const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);\n\n if (filePath) {\n emitDeprecationWarning(\n filePath,\n \"ESLINT_PERSONAL_CONFIG_SUPPRESS\"\n );\n }\n }\n return this._cacheConfig(directoryPath, baseConfigArray);\n }\n\n // Load the config on this directory.\n try {\n configArray = configArrayFactory.loadInDirectory(directoryPath);\n } catch (error) {\n /* istanbul ignore next */\n if (error.code === \"EACCES\") {\n debug(\"Stop traversing because of 'EACCES' error.\");\n return this._cacheConfig(directoryPath, baseConfigArray);\n }\n throw error;\n }\n\n if (configArray.length > 0 && configArray.isRoot()) {\n debug(\"Stop traversing because of 'root:true'.\");\n configArray.unshift(...baseConfigArray);\n return this._cacheConfig(directoryPath, configArray);\n }\n\n // Load from the ancestors and merge it.\n const parentPath = path.dirname(directoryPath);\n const parentConfigArray = parentPath && parentPath !== directoryPath\n ? this._loadConfigInAncestors(\n parentPath,\n configsExistInSubdirs || configArray.length > 0\n )\n : baseConfigArray;\n\n if (configArray.length > 0) {\n configArray.unshift(...parentConfigArray);\n } else {\n configArray = parentConfigArray;\n }\n\n // Cache and return.\n return this._cacheConfig(directoryPath, configArray);\n }\n\n /**\n * Freeze and cache a given config.\n * @param {string} directoryPath The path to a directory as a cache key.\n * @param {ConfigArray} configArray The config array as a cache value.\n * @returns {ConfigArray} The `configArray` (frozen).\n */\n _cacheConfig(directoryPath, configArray) {\n const { configCache } = internalSlotsMap.get(this);\n\n Object.freeze(configArray);\n configCache.set(directoryPath, configArray);\n\n return configArray;\n }\n\n /**\n * Finalize a given config array.\n * Concatenate `--config` and other CLI options.\n * @param {ConfigArray} configArray The parent config array.\n * @param {string} directoryPath The path to the leaf directory to find config files.\n * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.\n * @returns {ConfigArray} The loaded config.\n * @throws {Error} If a config file is invalid.\n * @private\n */\n _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {\n const {\n cliConfigArray,\n configArrayFactory,\n finalizeCache,\n useEslintrc,\n builtInRules\n } = internalSlotsMap.get(this);\n\n let finalConfigArray = finalizeCache.get(configArray);\n\n if (!finalConfigArray) {\n finalConfigArray = configArray;\n\n // Load the personal config if there are no regular config files.\n if (\n useEslintrc &&\n configArray.every(c => !c.filePath) &&\n cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.\n ) {\n const homePath = os.homedir();\n\n debug(\"Loading the config file of the home directory:\", homePath);\n\n const personalConfigArray = configArrayFactory.loadInDirectory(\n homePath,\n { name: \"PersonalConfig\" }\n );\n\n if (\n personalConfigArray.length > 0 &&\n !directoryPath.startsWith(homePath)\n ) {\n const lastElement =\n personalConfigArray.at(-1);\n\n emitDeprecationWarning(\n lastElement.filePath,\n \"ESLINT_PERSONAL_CONFIG_LOAD\"\n );\n }\n\n finalConfigArray = finalConfigArray.concat(personalConfigArray);\n }\n\n // Apply CLI options.\n if (cliConfigArray.length > 0) {\n finalConfigArray = finalConfigArray.concat(cliConfigArray);\n }\n\n // Validate rule settings and environments.\n const validator = new ConfigValidator({\n builtInRules\n });\n\n validator.validateConfigArray(finalConfigArray);\n\n // Cache it.\n Object.freeze(finalConfigArray);\n finalizeCache.set(configArray, finalConfigArray);\n\n debug(\n \"Configuration was determined: %o on %s\",\n finalConfigArray,\n directoryPath\n );\n }\n\n // At least one element (the default ignore patterns) exists.\n if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {\n throw new ConfigurationNotFoundError(directoryPath);\n }\n\n return finalConfigArray;\n }\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport { CascadingConfigArrayFactory };\n","/**\n * @fileoverview Compatibility class for flat config.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Requirements\n//-----------------------------------------------------------------------------\n\nimport createDebug from \"debug\";\nimport path from \"node:path\";\n\nimport environments from \"../conf/environments.js\";\nimport { ConfigArrayFactory } from \"./config-array-factory.js\";\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"../../shared/types\").Environment} Environment */\n/** @typedef {import(\"../../shared/types\").Processor} Processor */\n\nconst debug = createDebug(\"eslintrc:flat-compat\");\nconst cafactory = Symbol(\"cafactory\");\n\n/**\n * Translates an ESLintRC-style config object into a flag-config-style config\n * object.\n * @param {Object} eslintrcConfig An ESLintRC-style config object.\n * @param {Object} options Options to help translate the config.\n * @param {string} options.resolveConfigRelativeTo To the directory to resolve\n * configs from.\n * @param {string} options.resolvePluginsRelativeTo The directory to resolve\n * plugins from.\n * @param {ReadOnlyMap} options.pluginEnvironments A map of plugin environment\n * names to objects.\n * @param {ReadOnlyMap} options.pluginProcessors A map of plugin processor\n * names to objects.\n * @returns {Object} A flag-config-style config object.\n * @throws {Error} If a plugin or environment cannot be resolved.\n */\nfunction translateESLintRC(eslintrcConfig, {\n resolveConfigRelativeTo,\n resolvePluginsRelativeTo,\n pluginEnvironments,\n pluginProcessors\n}) {\n\n const flatConfig = {};\n const configs = [];\n const languageOptions = {};\n const linterOptions = {};\n const keysToCopy = [\"settings\", \"rules\", \"processor\"];\n const languageOptionsKeysToCopy = [\"globals\", \"parser\", \"parserOptions\"];\n const linterOptionsKeysToCopy = [\"noInlineConfig\", \"reportUnusedDisableDirectives\"];\n\n // copy over simple translations\n for (const key of keysToCopy) {\n if (key in eslintrcConfig && typeof eslintrcConfig[key] !== \"undefined\") {\n flatConfig[key] = eslintrcConfig[key];\n }\n }\n\n // copy over languageOptions\n for (const key of languageOptionsKeysToCopy) {\n if (key in eslintrcConfig && typeof eslintrcConfig[key] !== \"undefined\") {\n\n // create the languageOptions key in the flat config\n flatConfig.languageOptions = languageOptions;\n\n if (key === \"parser\") {\n debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);\n\n if (eslintrcConfig[key].error) {\n throw eslintrcConfig[key].error;\n }\n\n languageOptions[key] = eslintrcConfig[key].definition;\n continue;\n }\n\n // clone any object values that are in the eslintrc config\n if (eslintrcConfig[key] && typeof eslintrcConfig[key] === \"object\") {\n languageOptions[key] = {\n ...eslintrcConfig[key]\n };\n } else {\n languageOptions[key] = eslintrcConfig[key];\n }\n }\n }\n\n // copy over linterOptions\n for (const key of linterOptionsKeysToCopy) {\n if (key in eslintrcConfig && typeof eslintrcConfig[key] !== \"undefined\") {\n flatConfig.linterOptions = linterOptions;\n linterOptions[key] = eslintrcConfig[key];\n }\n }\n\n // move ecmaVersion a level up\n if (languageOptions.parserOptions) {\n\n if (\"ecmaVersion\" in languageOptions.parserOptions) {\n languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;\n delete languageOptions.parserOptions.ecmaVersion;\n }\n\n if (\"sourceType\" in languageOptions.parserOptions) {\n languageOptions.sourceType = languageOptions.parserOptions.sourceType;\n delete languageOptions.parserOptions.sourceType;\n }\n\n // check to see if we even need parserOptions anymore and remove it if not\n if (Object.keys(languageOptions.parserOptions).length === 0) {\n delete languageOptions.parserOptions;\n }\n }\n\n // overrides\n if (eslintrcConfig.criteria) {\n flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];\n }\n\n // translate plugins\n if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === \"object\") {\n debug(`Translating plugins: ${eslintrcConfig.plugins}`);\n\n flatConfig.plugins = {};\n\n for (const pluginName of Object.keys(eslintrcConfig.plugins)) {\n\n debug(`Translating plugin: ${pluginName}`);\n debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);\n\n const { original: plugin, error } = eslintrcConfig.plugins[pluginName];\n\n if (error) {\n throw error;\n }\n\n flatConfig.plugins[pluginName] = plugin;\n\n // create a config for any processors\n if (plugin.processors) {\n for (const processorName of Object.keys(plugin.processors)) {\n if (processorName.startsWith(\".\")) {\n debug(`Assigning processor: ${pluginName}/${processorName}`);\n\n configs.unshift({\n files: [`**/*${processorName}`],\n processor: pluginProcessors.get(`${pluginName}/${processorName}`)\n });\n }\n\n }\n }\n }\n }\n\n // translate env - must come after plugins\n if (eslintrcConfig.env && typeof eslintrcConfig.env === \"object\") {\n for (const envName of Object.keys(eslintrcConfig.env)) {\n\n // only add environments that are true\n if (eslintrcConfig.env[envName]) {\n debug(`Translating environment: ${envName}`);\n\n if (environments.has(envName)) {\n\n // built-in environments should be defined first\n configs.unshift(...translateESLintRC({\n criteria: eslintrcConfig.criteria,\n ...environments.get(envName)\n }, {\n resolveConfigRelativeTo,\n resolvePluginsRelativeTo\n }));\n } else if (pluginEnvironments.has(envName)) {\n\n // if the environment comes from a plugin, it should come after the plugin config\n configs.push(...translateESLintRC({\n criteria: eslintrcConfig.criteria,\n ...pluginEnvironments.get(envName)\n }, {\n resolveConfigRelativeTo,\n resolvePluginsRelativeTo\n }));\n }\n }\n }\n }\n\n // only add if there are actually keys in the config\n if (Object.keys(flatConfig).length > 0) {\n configs.push(flatConfig);\n }\n\n return configs;\n}\n\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * A compatibility class for working with configs.\n */\nclass FlatCompat {\n\n constructor({\n baseDirectory = process.cwd(),\n resolvePluginsRelativeTo = baseDirectory,\n recommendedConfig,\n allConfig\n } = {}) {\n this.baseDirectory = baseDirectory;\n this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;\n this[cafactory] = new ConfigArrayFactory({\n cwd: baseDirectory,\n resolvePluginsRelativeTo,\n getEslintAllConfig() {\n\n if (!allConfig) {\n throw new TypeError(\"Missing parameter 'allConfig' in FlatCompat constructor.\");\n }\n\n return allConfig;\n },\n getEslintRecommendedConfig() {\n\n if (!recommendedConfig) {\n throw new TypeError(\"Missing parameter 'recommendedConfig' in FlatCompat constructor.\");\n }\n\n return recommendedConfig;\n }\n });\n }\n\n /**\n * Translates an ESLintRC-style config into a flag-config-style config.\n * @param {Object} eslintrcConfig The ESLintRC-style config object.\n * @returns {Object} A flag-config-style config object.\n */\n config(eslintrcConfig) {\n const eslintrcArray = this[cafactory].create(eslintrcConfig, {\n basePath: this.baseDirectory\n });\n\n const flatArray = [];\n let hasIgnorePatterns = false;\n\n eslintrcArray.forEach(configData => {\n if (configData.type === \"config\") {\n hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;\n flatArray.push(...translateESLintRC(configData, {\n resolveConfigRelativeTo: path.join(this.baseDirectory, \"__placeholder.js\"),\n resolvePluginsRelativeTo: path.join(this.resolvePluginsRelativeTo, \"__placeholder.js\"),\n pluginEnvironments: eslintrcArray.pluginEnvironments,\n pluginProcessors: eslintrcArray.pluginProcessors\n }));\n }\n });\n\n // combine ignorePatterns to emulate ESLintRC behavior better\n if (hasIgnorePatterns) {\n flatArray.unshift({\n ignores: [filePath => {\n\n // Compute the final config for this file.\n // This filters config array elements by `files`/`excludedFiles` then merges the elements.\n const finalConfig = eslintrcArray.extractConfig(filePath);\n\n // Test the `ignorePattern` properties of the final config.\n return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);\n }]\n });\n }\n\n return flatArray;\n }\n\n /**\n * Translates the `env` section of an ESLintRC-style config.\n * @param {Object} envConfig The `env` section of an ESLintRC config.\n * @returns {Object[]} An array of flag-config objects representing the environments.\n */\n env(envConfig) {\n return this.config({\n env: envConfig\n });\n }\n\n /**\n * Translates the `extends` section of an ESLintRC-style config.\n * @param {...string} configsToExtend The names of the configs to load.\n * @returns {Object[]} An array of flag-config objects representing the config.\n */\n extends(...configsToExtend) {\n return this.config({\n extends: configsToExtend\n });\n }\n\n /**\n * Translates the `plugins` section of an ESLintRC-style config.\n * @param {...string} plugins The names of the plugins to load.\n * @returns {Object[]} An array of flag-config objects representing the plugins.\n */\n plugins(...plugins) {\n return this.config({\n plugins\n });\n }\n}\n\nexport { FlatCompat };\n","/**\n * @fileoverview Package exports for @eslint/eslintrc\n * @author Nicholas C. Zakas\n */\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport {\n ConfigArrayFactory,\n createContext as createConfigArrayFactoryContext,\n loadConfigFile\n} from \"./config-array-factory.js\";\n\nimport { CascadingConfigArrayFactory } from \"./cascading-config-array-factory.js\";\nimport * as ModuleResolver from \"./shared/relative-module-resolver.js\";\nimport { ConfigArray, getUsedExtractedConfigs } from \"./config-array/index.js\";\nimport { ConfigDependency } from \"./config-array/config-dependency.js\";\nimport { ExtractedConfig } from \"./config-array/extracted-config.js\";\nimport { IgnorePattern } from \"./config-array/ignore-pattern.js\";\nimport { OverrideTester } from \"./config-array/override-tester.js\";\nimport * as ConfigOps from \"./shared/config-ops.js\";\nimport ConfigValidator from \"./shared/config-validator.js\";\nimport * as naming from \"./shared/naming.js\";\nimport { FlatCompat } from \"./flat-compat.js\";\nimport environments from \"../conf/environments.js\";\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\nconst Legacy = {\n ConfigArray,\n createConfigArrayFactoryContext,\n CascadingConfigArrayFactory,\n ConfigArrayFactory,\n ConfigDependency,\n ExtractedConfig,\n IgnorePattern,\n OverrideTester,\n getUsedExtractedConfigs,\n environments,\n loadConfigFile,\n\n // shared\n ConfigOps,\n ConfigValidator,\n ModuleResolver,\n naming\n};\n\nexport {\n\n Legacy,\n\n FlatCompat\n\n};\n"],"names":["debug","debugOrig","path","ignore","assert","internalSlotsMap","util","minimatch","Ajv","globals","BuiltInEnvironments","ConfigOps.normalizeConfigGlobal","Module","require","createRequire","fs","stripComments","importFresh","ModuleResolver.resolve","naming.normalizePackageName","naming.getShorthandName","os","createDebug","createConfigArrayFactoryContext"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAUA;AACA,MAAMA,OAAK,GAAGC,6BAAS,CAAC,yBAAyB,CAAC,CAAC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,qBAAqB,CAAC,WAAW,EAAE;AAC5C,IAAI,IAAI,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;AAChC;AACA,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE;AACjD,QAAQ,MAAM,CAAC,GAAG,MAAM,CAAC;AACzB,QAAQ,MAAM,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;AACjC;AACA;AACA,QAAQ,MAAM,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC;AAC7C;AACA;AACA,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,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O,IAAI,CAAC,oBAAoB,EAAE,cAAc,CAAC,CAAC,CAAC;AACrE,SAAS;AACT,QAAQ,MAAM,KAAK,CAAC;AACpB,KAAK;AACL;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAsBA;AACA,MAAMC,SAAO,GAAGC,oBAAa,CAAC,mDAAe,CAAC,CAAC;AAC/C;AACA,MAAMd,OAAK,GAAGC,6BAAS,CAAC,+BAA+B,CAAC,CAAC;AACzD;AACA;AACA;AACA;AACA;AACA,MAAM,eAAe,GAAG;AACxB,IAAI,cAAc;AAClB,IAAI,eAAe;AACnB,IAAI,gBAAgB;AACpB,IAAI,eAAe;AACnB,IAAI,gBAAgB;AACpB,IAAI,WAAW;AACf,IAAI,cAAc;AAClB,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMI,kBAAgB,GAAG,IAAI,OAAO,EAAE,CAAC;AACvC;AACA;AACA,MAAM,iBAAiB,GAAG,IAAI,OAAO,EAAE,CAAC;AACxC;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,UAAU,CAAC,UAAU,EAAE;AAChC,IAAI;AACJ,QAAQ,gBAAgB,CAAC,IAAI,CAAC,UAAU,CAAC;AACzC,QAAQH,wBAAI,CAAC,UAAU,CAAC,UAAU,CAAC;AACnC,MAAM;AACN,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA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S,CAAC;AACzB,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,GAAG,CAAC,SAAS,EAAE;AACnB,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC;AAC3B,YAAY,GAAG,EAAE,SAAS;AAC1B,SAAS,CAAC,CAAC;AACX,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,CAAC,GAAG,eAAe,EAAE;AAChC,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC;AAC3B,YAAY,OAAO,EAAE,eAAe;AACpC,SAAS,CAAC,CAAC;AACX,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,CAAC,GAAG,OAAO,EAAE;AACxB,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC;AAC3B,YAAY,OAAO;AACnB,SAAS,CAAC,CAAC;AACX,KAAK;AACL;;AC5TA;AACA;AACA;AACA;AAuBA;AACA;AACA;AACA;AACA;AACK,MAAC,MAAM,GAAG;AACf,IAAI,WAAW;AACf,qCAAIqB,aAA+B;AACnC,IAAI,2BAA2B;AAC/B,IAAI,kBAAkB;AACtB,IAAI,gBAAgB;AACpB,IAAI,eAAe;AACnB,IAAI,aAAa;AACjB,IAAI,cAAc;AAClB,IAAI,uBAAuB;AAC3B,IAAI,YAAY;AAChB,IAAI,cAAc;AAClB;AACA;AACA,IAAI,SAAS;AACb,IAAI,eAAe;AACnB,IAAI,cAAc;AAClB,IAAI,MAAM;AACV;;;;;"} \ No newline at end of file diff --git a/node_modules/@eslint/eslintrc/dist/eslintrc.d.cts b/node_modules/@eslint/eslintrc/dist/eslintrc.d.cts new file mode 100644 index 00000000..258d3a5f --- /dev/null +++ b/node_modules/@eslint/eslintrc/dist/eslintrc.d.cts @@ -0,0 +1,76 @@ +/** + * @fileoverview This file contains the core types for ESLint. It was initially extracted + * from the `@types/eslint__eslintrc` package. + */ + +/* + * MIT License + * Copyright (c) Microsoft Corporation. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE + */ + +import type { Linter } from "eslint"; + +/** + * A compatibility class for working with configs. + */ +export class FlatCompat { + constructor({ + baseDirectory, + resolvePluginsRelativeTo, + recommendedConfig, + allConfig, + }?: { + /** + * default: process.cwd() + */ + baseDirectory?: string; + resolvePluginsRelativeTo?: string; + recommendedConfig?: Linter.LegacyConfig; + allConfig?: Linter.LegacyConfig; + }); + + /** + * Translates an ESLintRC-style config into a flag-config-style config. + * @param eslintrcConfig The ESLintRC-style config object. + * @returns A flag-config-style config object. + */ + config(eslintrcConfig: Linter.LegacyConfig): Linter.Config[]; + + /** + * Translates the `env` section of an ESLintRC-style config. + * @param envConfig The `env` section of an ESLintRC config. + * @returns An array of flag-config objects representing the environments. + */ + env(envConfig: { [name: string]: boolean }): Linter.Config[]; + + /** + * Translates the `extends` section of an ESLintRC-style config. + * @param configsToExtend The names of the configs to load. + * @returns An array of flag-config objects representing the config. + */ + extends(...configsToExtend: string[]): Linter.Config[]; + + /** + * Translates the `plugins` section of an ESLintRC-style config. + * @param plugins The names of the plugins to load. + * @returns An array of flag-config objects representing the plugins. + */ + plugins(...plugins: string[]): Linter.Config[]; +} diff --git a/node_modules/@eslint/eslintrc/lib/cascading-config-array-factory.js b/node_modules/@eslint/eslintrc/lib/cascading-config-array-factory.js new file mode 100644 index 00000000..71549107 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/cascading-config-array-factory.js @@ -0,0 +1,534 @@ +/** + * @fileoverview `CascadingConfigArrayFactory` class. + * + * `CascadingConfigArrayFactory` class has a responsibility: + * + * 1. Handles cascading of config files. + * + * It provides two methods: + * + * - `getConfigArrayForFile(filePath)` + * Get the corresponded configuration of a given file. This method doesn't + * throw even if the given file didn't exist. + * - `clearCache()` + * Clear the internal cache. You have to call this method when + * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends + * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.) + * + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import debugOrig from "debug"; +import os from "node:os"; +import path from "node:path"; + +import { ConfigArrayFactory } from "./config-array-factory.js"; +import { + ConfigArray, + ConfigDependency, + IgnorePattern +} from "./config-array/index.js"; +import ConfigValidator from "./shared/config-validator.js"; +import { emitDeprecationWarning } from "./shared/deprecation-warnings.js"; + +const debug = debugOrig("eslintrc:cascading-config-array-factory"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Define types for VSCode IntelliSense. +/** @typedef {import("./shared/types").ConfigData} ConfigData */ +/** @typedef {import("./shared/types").Parser} Parser */ +/** @typedef {import("./shared/types").Plugin} Plugin */ +/** @typedef {import("./shared/types").Rule} Rule */ +/** @typedef {ReturnType} ConfigArray */ + +/** + * @typedef {Object} CascadingConfigArrayFactoryOptions + * @property {Map} [additionalPluginPool] The map for additional plugins. + * @property {ConfigData} [baseConfig] The config by `baseConfig` option. + * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files. + * @property {string} [cwd] The base directory to start lookup. + * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`. + * @property {string[]} [rulePaths] The value of `--rulesdir` option. + * @property {string} [specificConfigPath] The value of `--config` option. + * @property {boolean} [useEslintrc] if `false` then it doesn't load config files. + * @property {Function} loadRules The function to use to load rules. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** + * @typedef {Object} CascadingConfigArrayFactoryInternalSlots + * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option. + * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`. + * @property {ConfigArray} cliConfigArray The config array of CLI options. + * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`. + * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays. + * @property {Map} configCache The cache from directory paths to config arrays. + * @property {string} cwd The base directory to start lookup. + * @property {WeakMap} finalizeCache The cache from config arrays to finalized config arrays. + * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`. + * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`. + * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`. + * @property {boolean} useEslintrc if `false` then it doesn't load config files. + * @property {Function} loadRules The function to use to load rules. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Create the config array from `baseConfig` and `rulePaths`. + * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. + * @returns {ConfigArray} The config array of the base configs. + */ +function createBaseConfigArray({ + configArrayFactory, + baseConfigData, + rulePaths, + cwd, + loadRules +}) { + const baseConfigArray = configArrayFactory.create( + baseConfigData, + { name: "BaseConfig" } + ); + + /* + * Create the config array element for the default ignore patterns. + * This element has `ignorePattern` property that ignores the default + * patterns in the current working directory. + */ + baseConfigArray.unshift(configArrayFactory.create( + { ignorePatterns: IgnorePattern.DefaultPatterns }, + { name: "DefaultIgnorePattern" } + )[0]); + + /* + * Load rules `--rulesdir` option as a pseudo plugin. + * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate + * the rule's options with only information in the config array. + */ + if (rulePaths && rulePaths.length > 0) { + baseConfigArray.push({ + type: "config", + name: "--rulesdir", + filePath: "", + plugins: { + "": new ConfigDependency({ + definition: { + rules: rulePaths.reduce( + (map, rulesPath) => Object.assign( + map, + loadRules(rulesPath, cwd) + ), + {} + ) + }, + filePath: "", + id: "", + importerName: "--rulesdir", + importerPath: "" + }) + } + }); + } + + return baseConfigArray; +} + +/** + * Create the config array from CLI options. + * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. + * @returns {ConfigArray} The config array of the base configs. + */ +function createCLIConfigArray({ + cliConfigData, + configArrayFactory, + cwd, + ignorePath, + specificConfigPath +}) { + const cliConfigArray = configArrayFactory.create( + cliConfigData, + { name: "CLIOptions" } + ); + + cliConfigArray.unshift( + ...(ignorePath + ? configArrayFactory.loadESLintIgnore(ignorePath) + : configArrayFactory.loadDefaultESLintIgnore()) + ); + + if (specificConfigPath) { + cliConfigArray.unshift( + ...configArrayFactory.loadFile( + specificConfigPath, + { name: "--config", basePath: cwd } + ) + ); + } + + return cliConfigArray; +} + +/** + * The error type when there are files matched by a glob, but all of them have been ignored. + */ +class ConfigurationNotFoundError extends Error { + + + /** + * @param {string} directoryPath The directory path. + */ + constructor(directoryPath) { + super(`No ESLint configuration found in ${directoryPath}.`); + this.messageTemplate = "no-config-found"; + this.messageData = { directoryPath }; + } +} + +/** + * This class provides the functionality that enumerates every file which is + * matched by given glob patterns and that configuration. + */ +class CascadingConfigArrayFactory { + + /** + * Initialize this enumerator. + * @param {CascadingConfigArrayFactoryOptions} options The options. + */ + constructor({ + additionalPluginPool = new Map(), + baseConfig: baseConfigData = null, + cliConfig: cliConfigData = null, + cwd = process.cwd(), + ignorePath, + resolvePluginsRelativeTo, + rulePaths = [], + specificConfigPath = null, + useEslintrc = true, + builtInRules = new Map(), + loadRules, + resolver, + eslintRecommendedPath, + getEslintRecommendedConfig, + eslintAllPath, + getEslintAllConfig + } = {}) { + const configArrayFactory = new ConfigArrayFactory({ + additionalPluginPool, + cwd, + resolvePluginsRelativeTo, + builtInRules, + resolver, + eslintRecommendedPath, + getEslintRecommendedConfig, + eslintAllPath, + getEslintAllConfig + }); + + internalSlotsMap.set(this, { + baseConfigArray: createBaseConfigArray({ + baseConfigData, + configArrayFactory, + cwd, + rulePaths, + loadRules + }), + baseConfigData, + cliConfigArray: createCLIConfigArray({ + cliConfigData, + configArrayFactory, + cwd, + ignorePath, + specificConfigPath + }), + cliConfigData, + configArrayFactory, + configCache: new Map(), + cwd, + finalizeCache: new WeakMap(), + ignorePath, + rulePaths, + specificConfigPath, + useEslintrc, + builtInRules, + loadRules + }); + } + + /** + * The path to the current working directory. + * This is used by tests. + * @type {string} + */ + get cwd() { + const { cwd } = internalSlotsMap.get(this); + + return cwd; + } + + /** + * Get the config array of a given file. + * If `filePath` was not given, it returns the config which contains only + * `baseConfigData` and `cliConfigData`. + * @param {string} [filePath] The file path to a file. + * @param {Object} [options] The options. + * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`. + * @returns {ConfigArray} The config array of the file. + */ + getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) { + const { + baseConfigArray, + cliConfigArray, + cwd + } = internalSlotsMap.get(this); + + if (!filePath) { + return new ConfigArray(...baseConfigArray, ...cliConfigArray); + } + + const directoryPath = path.dirname(path.resolve(cwd, filePath)); + + debug(`Load config files for ${directoryPath}.`); + + return this._finalizeConfigArray( + this._loadConfigInAncestors(directoryPath), + directoryPath, + ignoreNotFoundError + ); + } + + /** + * Set the config data to override all configs. + * Require to call `clearCache()` method after this method is called. + * @param {ConfigData} configData The config data to override all configs. + * @returns {void} + */ + setOverrideConfig(configData) { + const slots = internalSlotsMap.get(this); + + slots.cliConfigData = configData; + } + + /** + * Clear config cache. + * @returns {void} + */ + clearCache() { + const slots = internalSlotsMap.get(this); + + slots.baseConfigArray = createBaseConfigArray(slots); + slots.cliConfigArray = createCLIConfigArray(slots); + slots.configCache.clear(); + } + + /** + * Load and normalize config files from the ancestor directories. + * @param {string} directoryPath The path to a leaf directory. + * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories. + * @returns {ConfigArray} The loaded config. + * @throws {Error} If a config file is invalid. + * @private + */ + _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) { + const { + baseConfigArray, + configArrayFactory, + configCache, + cwd, + useEslintrc + } = internalSlotsMap.get(this); + + if (!useEslintrc) { + return baseConfigArray; + } + + let configArray = configCache.get(directoryPath); + + // Hit cache. + if (configArray) { + debug(`Cache hit: ${directoryPath}.`); + return configArray; + } + debug(`No cache found: ${directoryPath}.`); + + const homePath = os.homedir(); + + // Consider this is root. + if (directoryPath === homePath && cwd !== homePath) { + debug("Stop traversing because of considered root."); + if (configsExistInSubdirs) { + const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath); + + if (filePath) { + emitDeprecationWarning( + filePath, + "ESLINT_PERSONAL_CONFIG_SUPPRESS" + ); + } + } + return this._cacheConfig(directoryPath, baseConfigArray); + } + + // Load the config on this directory. + try { + configArray = configArrayFactory.loadInDirectory(directoryPath); + } catch (error) { + /* istanbul ignore next */ + if (error.code === "EACCES") { + debug("Stop traversing because of 'EACCES' error."); + return this._cacheConfig(directoryPath, baseConfigArray); + } + throw error; + } + + if (configArray.length > 0 && configArray.isRoot()) { + debug("Stop traversing because of 'root:true'."); + configArray.unshift(...baseConfigArray); + return this._cacheConfig(directoryPath, configArray); + } + + // Load from the ancestors and merge it. + const parentPath = path.dirname(directoryPath); + const parentConfigArray = parentPath && parentPath !== directoryPath + ? this._loadConfigInAncestors( + parentPath, + configsExistInSubdirs || configArray.length > 0 + ) + : baseConfigArray; + + if (configArray.length > 0) { + configArray.unshift(...parentConfigArray); + } else { + configArray = parentConfigArray; + } + + // Cache and return. + return this._cacheConfig(directoryPath, configArray); + } + + /** + * Freeze and cache a given config. + * @param {string} directoryPath The path to a directory as a cache key. + * @param {ConfigArray} configArray The config array as a cache value. + * @returns {ConfigArray} The `configArray` (frozen). + */ + _cacheConfig(directoryPath, configArray) { + const { configCache } = internalSlotsMap.get(this); + + Object.freeze(configArray); + configCache.set(directoryPath, configArray); + + return configArray; + } + + /** + * Finalize a given config array. + * Concatenate `--config` and other CLI options. + * @param {ConfigArray} configArray The parent config array. + * @param {string} directoryPath The path to the leaf directory to find config files. + * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`. + * @returns {ConfigArray} The loaded config. + * @throws {Error} If a config file is invalid. + * @private + */ + _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) { + const { + cliConfigArray, + configArrayFactory, + finalizeCache, + useEslintrc, + builtInRules + } = internalSlotsMap.get(this); + + let finalConfigArray = finalizeCache.get(configArray); + + if (!finalConfigArray) { + finalConfigArray = configArray; + + // Load the personal config if there are no regular config files. + if ( + useEslintrc && + configArray.every(c => !c.filePath) && + cliConfigArray.every(c => !c.filePath) // `--config` option can be a file. + ) { + const homePath = os.homedir(); + + debug("Loading the config file of the home directory:", homePath); + + const personalConfigArray = configArrayFactory.loadInDirectory( + homePath, + { name: "PersonalConfig" } + ); + + if ( + personalConfigArray.length > 0 && + !directoryPath.startsWith(homePath) + ) { + const lastElement = + personalConfigArray.at(-1); + + emitDeprecationWarning( + lastElement.filePath, + "ESLINT_PERSONAL_CONFIG_LOAD" + ); + } + + finalConfigArray = finalConfigArray.concat(personalConfigArray); + } + + // Apply CLI options. + if (cliConfigArray.length > 0) { + finalConfigArray = finalConfigArray.concat(cliConfigArray); + } + + // Validate rule settings and environments. + const validator = new ConfigValidator({ + builtInRules + }); + + validator.validateConfigArray(finalConfigArray); + + // Cache it. + Object.freeze(finalConfigArray); + finalizeCache.set(configArray, finalConfigArray); + + debug( + "Configuration was determined: %o on %s", + finalConfigArray, + directoryPath + ); + } + + // At least one element (the default ignore patterns) exists. + if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) { + throw new ConfigurationNotFoundError(directoryPath); + } + + return finalConfigArray; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +export { CascadingConfigArrayFactory }; diff --git a/node_modules/@eslint/eslintrc/lib/config-array-factory.js b/node_modules/@eslint/eslintrc/lib/config-array-factory.js new file mode 100644 index 00000000..5c7c3ef0 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/config-array-factory.js @@ -0,0 +1,1162 @@ +/** + * @fileoverview The factory of `ConfigArray` objects. + * + * This class provides methods to create `ConfigArray` instance. + * + * - `create(configData, options)` + * Create a `ConfigArray` instance from a config data. This is to handle CLI + * options except `--config`. + * - `loadFile(filePath, options)` + * Create a `ConfigArray` instance from a config file. This is to handle + * `--config` option. If the file was not found, throws the following error: + * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error. + * - If the filename was `package.json`, an IO error or an + * `ESLINT_CONFIG_FIELD_NOT_FOUND` error. + * - Otherwise, an IO error such as `ENOENT`. + * - `loadInDirectory(directoryPath, options)` + * Create a `ConfigArray` instance from a config file which is on a given + * directory. This tries to load `.eslintrc.*` or `package.json`. If not + * found, returns an empty `ConfigArray`. + * - `loadESLintIgnore(filePath)` + * Create a `ConfigArray` instance from a config file that is `.eslintignore` + * format. This is to handle `--ignore-path` option. + * - `loadDefaultESLintIgnore()` + * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in + * the current working directory. + * + * `ConfigArrayFactory` class has the responsibility that loads configuration + * files, including loading `extends`, `parser`, and `plugins`. The created + * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`. + * + * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class + * handles cascading and hierarchy. + * + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import debugOrig from "debug"; +import fs from "node:fs"; +import importFresh from "import-fresh"; +import { createRequire } from "node:module"; +import path from "node:path"; +import stripComments from "strip-json-comments"; + +import { + ConfigArray, + ConfigDependency, + IgnorePattern, + OverrideTester +} from "./config-array/index.js"; +import ConfigValidator from "./shared/config-validator.js"; +import * as naming from "./shared/naming.js"; +import * as ModuleResolver from "./shared/relative-module-resolver.js"; + +const require = createRequire(import.meta.url); + +const debug = debugOrig("eslintrc:config-array-factory"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const configFilenames = [ + ".eslintrc.js", + ".eslintrc.cjs", + ".eslintrc.yaml", + ".eslintrc.yml", + ".eslintrc.json", + ".eslintrc", + "package.json" +]; + +// Define types for VSCode IntelliSense. +/** @typedef {import("./shared/types").ConfigData} ConfigData */ +/** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */ +/** @typedef {import("./shared/types").Parser} Parser */ +/** @typedef {import("./shared/types").Plugin} Plugin */ +/** @typedef {import("./shared/types").Rule} Rule */ +/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */ +/** @typedef {ConfigArray[0]} ConfigArrayElement */ + +/** + * @typedef {Object} ConfigArrayFactoryOptions + * @property {Map} [additionalPluginPool] The map for additional plugins. + * @property {string} [cwd] The path to the current working directory. + * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** + * @typedef {Object} ConfigArrayFactoryInternalSlots + * @property {Map} additionalPluginPool The map for additional plugins. + * @property {string} cwd The path to the current working directory. + * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** + * @typedef {Object} ConfigArrayFactoryLoadingContext + * @property {string} filePath The path to the current configuration. + * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @property {string} name The name of the current configuration. + * @property {string} pluginBasePath The base path to resolve plugins. + * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors. + */ + +/** + * @typedef {Object} ConfigArrayFactoryLoadingContext + * @property {string} filePath The path to the current configuration. + * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @property {string} name The name of the current configuration. + * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** @type {WeakMap} */ +const normalizedPlugins = new WeakMap(); + +/** + * Check if a given string is a file path. + * @param {string} nameOrPath A module name or file path. + * @returns {boolean} `true` if the `nameOrPath` is a file path. + */ +function isFilePath(nameOrPath) { + return ( + /^\.{1,2}[/\\]/u.test(nameOrPath) || + path.isAbsolute(nameOrPath) + ); +} + +/** + * Convenience wrapper for synchronously reading file contents. + * @param {string} filePath The filename to read. + * @returns {string} The file contents, with the BOM removed. + * @private + */ +function readFile(filePath) { + return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, ""); +} + +/** + * Loads a YAML configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadYAMLConfigFile(filePath) { + debug(`Loading YAML config file: ${filePath}`); + + // lazy load YAML to improve performance when not used + const yaml = require("js-yaml"); + + try { + + // empty YAML file can be null, so always use + return yaml.load(readFile(filePath)) || {}; + } catch (e) { + debug(`Error reading YAML file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a JSON configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadJSONConfigFile(filePath) { + debug(`Loading JSON config file: ${filePath}`); + + try { + return JSON.parse(stripComments(readFile(filePath))); + } catch (e) { + debug(`Error reading JSON file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + e.messageTemplate = "failed-to-read-json"; + e.messageData = { + path: filePath, + message: e.message + }; + throw e; + } +} + +/** + * Loads a legacy (.eslintrc) configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadLegacyConfigFile(filePath) { + debug(`Loading legacy config file: ${filePath}`); + + // lazy load YAML to improve performance when not used + const yaml = require("js-yaml"); + + try { + return yaml.load(stripComments(readFile(filePath))) || /* istanbul ignore next */ {}; + } catch (e) { + debug("Error reading YAML file: %s\n%o", filePath, e); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a JavaScript configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadJSConfigFile(filePath) { + debug(`Loading JS config file: ${filePath}`); + try { + return importFresh(filePath); + } catch (e) { + debug(`Error reading JavaScript file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a configuration from a package.json file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadPackageJSONConfigFile(filePath) { + debug(`Loading package.json config file: ${filePath}`); + try { + const packageData = loadJSONConfigFile(filePath); + + if (!Object.hasOwn(packageData, "eslintConfig")) { + throw Object.assign( + new Error("package.json file doesn't have 'eslintConfig' field."), + { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" } + ); + } + + return packageData.eslintConfig; + } catch (e) { + debug(`Error reading package.json file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a `.eslintignore` from a file. + * @param {string} filePath The filename to load. + * @returns {string[]} The ignore patterns from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadESLintIgnoreFile(filePath) { + debug(`Loading .eslintignore file: ${filePath}`); + + try { + return readFile(filePath) + .split(/\r?\n/gu) + .filter(line => line.trim() !== "" && !line.startsWith("#")); + } catch (e) { + debug(`Error reading .eslintignore file: ${filePath}`); + e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Creates an error to notify about a missing config to extend from. + * @param {string} configName The name of the missing config. + * @param {string} importerName The name of the config that imported the missing config + * @param {string} messageTemplate The text template to source error strings from. + * @returns {Error} The error object to throw + * @private + */ +function configInvalidError(configName, importerName, messageTemplate) { + return Object.assign( + new Error(`Failed to load config "${configName}" to extend from.`), + { + messageTemplate, + messageData: { configName, importerName } + } + ); +} + +/** + * Loads a configuration file regardless of the source. Inspects the file path + * to determine the correctly way to load the config file. + * @param {string} filePath The path to the configuration. + * @returns {ConfigData|null} The configuration information. + * @private + */ +function loadConfigFile(filePath) { + switch (path.extname(filePath)) { + case ".js": + case ".cjs": + return loadJSConfigFile(filePath); + + case ".json": + if (path.basename(filePath) === "package.json") { + return loadPackageJSONConfigFile(filePath); + } + return loadJSONConfigFile(filePath); + + case ".yaml": + case ".yml": + return loadYAMLConfigFile(filePath); + + default: + return loadLegacyConfigFile(filePath); + } +} + +/** + * Write debug log. + * @param {string} request The requested module name. + * @param {string} relativeTo The file path to resolve the request relative to. + * @param {string} filePath The resolved file path. + * @returns {void} + */ +function writeDebugLogForLoading(request, relativeTo, filePath) { + /* istanbul ignore next */ + if (debug.enabled) { + let nameAndVersion = null; // eslint-disable-line no-useless-assignment -- known bug in the rule + + try { + const packageJsonPath = ModuleResolver.resolve( + `${request}/package.json`, + relativeTo + ); + const { version = "unknown" } = require(packageJsonPath); + + nameAndVersion = `${request}@${version}`; + } catch (error) { + debug("package.json was not found:", error.message); + nameAndVersion = request; + } + + debug("Loaded: %s (%s)", nameAndVersion, filePath); + } +} + +/** + * Create a new context with default values. + * @param {ConfigArrayFactoryInternalSlots} slots The internal slots. + * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`. + * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`. + * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string. + * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`. + * @returns {ConfigArrayFactoryLoadingContext} The created context. + */ +function createContext( + { cwd, resolvePluginsRelativeTo }, + providedType, + providedName, + providedFilePath, + providedMatchBasePath +) { + const filePath = providedFilePath + ? path.resolve(cwd, providedFilePath) + : ""; + const matchBasePath = + (providedMatchBasePath && path.resolve(cwd, providedMatchBasePath)) || + (filePath && path.dirname(filePath)) || + cwd; + const name = + providedName || + (filePath && path.relative(cwd, filePath)) || + ""; + const pluginBasePath = + resolvePluginsRelativeTo || + (filePath && path.dirname(filePath)) || + cwd; + const type = providedType || "config"; + + return { filePath, matchBasePath, name, pluginBasePath, type }; +} + +/** + * Normalize a given plugin. + * - Ensure the object to have four properties: configs, environments, processors, and rules. + * - Ensure the object to not have other properties. + * @param {Plugin} plugin The plugin to normalize. + * @returns {Plugin} The normalized plugin. + */ +function normalizePlugin(plugin) { + + // first check the cache + let normalizedPlugin = normalizedPlugins.get(plugin); + + if (normalizedPlugin) { + return normalizedPlugin; + } + + normalizedPlugin = { + configs: plugin.configs || {}, + environments: plugin.environments || {}, + processors: plugin.processors || {}, + rules: plugin.rules || {} + }; + + // save the reference for later + normalizedPlugins.set(plugin, normalizedPlugin); + + return normalizedPlugin; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The factory of `ConfigArray` objects. + */ +class ConfigArrayFactory { + + /** + * Initialize this instance. + * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins. + */ + constructor({ + additionalPluginPool = new Map(), + cwd = process.cwd(), + resolvePluginsRelativeTo, + builtInRules, + resolver = ModuleResolver, + eslintAllPath, + getEslintAllConfig, + eslintRecommendedPath, + getEslintRecommendedConfig + } = {}) { + internalSlotsMap.set(this, { + additionalPluginPool, + cwd, + resolvePluginsRelativeTo: + resolvePluginsRelativeTo && + path.resolve(cwd, resolvePluginsRelativeTo), + builtInRules, + resolver, + eslintAllPath, + getEslintAllConfig, + eslintRecommendedPath, + getEslintRecommendedConfig + }); + } + + /** + * Create `ConfigArray` instance from a config data. + * @param {ConfigData|null} configData The config data to create. + * @param {Object} [options] The options. + * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @param {string} [options.filePath] The path to this config data. + * @param {string} [options.name] The config name. + * @returns {ConfigArray} Loaded config. + */ + create(configData, { basePath, filePath, name } = {}) { + if (!configData) { + return new ConfigArray(); + } + + const slots = internalSlotsMap.get(this); + const ctx = createContext(slots, "config", name, filePath, basePath); + const elements = this._normalizeConfigData(configData, ctx); + + return new ConfigArray(...elements); + } + + /** + * Load a config file. + * @param {string} filePath The path to a config file. + * @param {Object} [options] The options. + * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @param {string} [options.name] The config name. + * @returns {ConfigArray} Loaded config. + */ + loadFile(filePath, { basePath, name } = {}) { + const slots = internalSlotsMap.get(this); + const ctx = createContext(slots, "config", name, filePath, basePath); + + return new ConfigArray(...this._loadConfigData(ctx)); + } + + /** + * Load the config file on a given directory if exists. + * @param {string} directoryPath The path to a directory. + * @param {Object} [options] The options. + * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @param {string} [options.name] The config name. + * @throws {Error} If the config file is invalid. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + */ + loadInDirectory(directoryPath, { basePath, name } = {}) { + const slots = internalSlotsMap.get(this); + + for (const filename of configFilenames) { + const ctx = createContext( + slots, + "config", + name, + path.join(directoryPath, filename), + basePath + ); + + if (fs.existsSync(ctx.filePath) && fs.statSync(ctx.filePath).isFile()) { + let configData; + + try { + configData = loadConfigFile(ctx.filePath); + } catch (error) { + if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") { + throw error; + } + } + + if (configData) { + debug(`Config file found: ${ctx.filePath}`); + return new ConfigArray( + ...this._normalizeConfigData(configData, ctx) + ); + } + } + } + + debug(`Config file not found on ${directoryPath}`); + return new ConfigArray(); + } + + /** + * Check if a config file on a given directory exists or not. + * @param {string} directoryPath The path to a directory. + * @returns {string | null} The path to the found config file. If not found then null. + */ + static getPathToConfigFileInDirectory(directoryPath) { + for (const filename of configFilenames) { + const filePath = path.join(directoryPath, filename); + + if (fs.existsSync(filePath)) { + if (filename === "package.json") { + try { + loadPackageJSONConfigFile(filePath); + return filePath; + } catch { /* ignore */ } + } else { + return filePath; + } + } + } + return null; + } + + /** + * Load `.eslintignore` file. + * @param {string} filePath The path to a `.eslintignore` file to load. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + */ + loadESLintIgnore(filePath) { + const slots = internalSlotsMap.get(this); + const ctx = createContext( + slots, + "ignore", + void 0, + filePath, + slots.cwd + ); + const ignorePatterns = loadESLintIgnoreFile(ctx.filePath); + + return new ConfigArray( + ...this._normalizeESLintIgnoreData(ignorePatterns, ctx) + ); + } + + /** + * Load `.eslintignore` file in the current working directory. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + * @throws {Error} If the ignore file is invalid. + */ + loadDefaultESLintIgnore() { + const slots = internalSlotsMap.get(this); + const eslintIgnorePath = path.resolve(slots.cwd, ".eslintignore"); + const packageJsonPath = path.resolve(slots.cwd, "package.json"); + + if (fs.existsSync(eslintIgnorePath)) { + return this.loadESLintIgnore(eslintIgnorePath); + } + if (fs.existsSync(packageJsonPath)) { + const data = loadJSONConfigFile(packageJsonPath); + + if (Object.hasOwn(data, "eslintIgnore")) { + if (!Array.isArray(data.eslintIgnore)) { + throw new Error("Package.json eslintIgnore property requires an array of paths"); + } + const ctx = createContext( + slots, + "ignore", + "eslintIgnore in package.json", + packageJsonPath, + slots.cwd + ); + + return new ConfigArray( + ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx) + ); + } + } + + return new ConfigArray(); + } + + /** + * Load a given config file. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} Loaded config. + * @private + */ + _loadConfigData(ctx) { + return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx); + } + + /** + * Normalize a given `.eslintignore` data to config array elements. + * @param {string[]} ignorePatterns The patterns to ignore files. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeESLintIgnoreData(ignorePatterns, ctx) { + const elements = this._normalizeObjectConfigData( + { ignorePatterns }, + ctx + ); + + // Set `ignorePattern.loose` flag for backward compatibility. + for (const element of elements) { + if (element.ignorePattern) { + element.ignorePattern.loose = true; + } + yield element; + } + } + + /** + * Normalize a given config to an array. + * @param {ConfigData} configData The config data to normalize. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + _normalizeConfigData(configData, ctx) { + const validator = new ConfigValidator(); + + validator.validateConfigSchema(configData, ctx.name || ctx.filePath); + return this._normalizeObjectConfigData(configData, ctx); + } + + /** + * Normalize a given config to an array. + * @param {ConfigData|OverrideConfigData} configData The config data to normalize. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeObjectConfigData(configData, ctx) { + const { files, excludedFiles, ...configBody } = configData; + const criteria = OverrideTester.create( + files, + excludedFiles, + ctx.matchBasePath + ); + const elements = this._normalizeObjectConfigDataBody(configBody, ctx); + + // Apply the criteria to every element. + for (const element of elements) { + + /* + * Merge the criteria. + * This is for the `overrides` entries that came from the + * configurations of `overrides[].extends`. + */ + element.criteria = OverrideTester.and(criteria, element.criteria); + + /* + * Remove `root` property to ignore `root` settings which came from + * `extends` in `overrides`. + */ + if (element.criteria) { + element.root = void 0; + } + + yield element; + } + } + + /** + * Normalize a given config to an array. + * @param {ConfigData} configData The config data to normalize. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeObjectConfigDataBody( + { + env, + extends: extend, + globals, + ignorePatterns, + noInlineConfig, + parser: parserName, + parserOptions, + plugins: pluginList, + processor, + reportUnusedDisableDirectives, + root, + rules, + settings, + overrides: overrideList = [] + }, + ctx + ) { + const extendList = Array.isArray(extend) ? extend : [extend]; + const ignorePattern = ignorePatterns && new IgnorePattern( + Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns], + ctx.matchBasePath + ); + + // Flatten `extends`. + for (const extendName of extendList.filter(Boolean)) { + yield* this._loadExtends(extendName, ctx); + } + + // Load parser & plugins. + const parser = parserName && this._loadParser(parserName, ctx); + const plugins = pluginList && this._loadPlugins(pluginList, ctx); + + // Yield pseudo config data for file extension processors. + if (plugins) { + yield* this._takeFileExtensionProcessors(plugins, ctx); + } + + // Yield the config data except `extends` and `overrides`. + yield { + + // Debug information. + type: ctx.type, + name: ctx.name, + filePath: ctx.filePath, + + // Config data. + criteria: null, + env, + globals, + ignorePattern, + noInlineConfig, + parser, + parserOptions, + plugins, + processor, + reportUnusedDisableDirectives, + root, + rules, + settings + }; + + // Flatten `overries`. + for (let i = 0; i < overrideList.length; ++i) { + yield* this._normalizeObjectConfigData( + overrideList[i], + { ...ctx, name: `${ctx.name}#overrides[${i}]` } + ); + } + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @throws {Error} If the extended config file can't be loaded. + * @private + */ + _loadExtends(extendName, ctx) { + debug("Loading {extends:%j} relative to %s", extendName, ctx.filePath); + try { + if (extendName.startsWith("eslint:")) { + return this._loadExtendedBuiltInConfig(extendName, ctx); + } + if (extendName.startsWith("plugin:")) { + return this._loadExtendedPluginConfig(extendName, ctx); + } + return this._loadExtendedShareableConfig(extendName, ctx); + } catch (error) { + error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`; + throw error; + } + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @throws {Error} If the extended config file can't be loaded. + * @private + */ + _loadExtendedBuiltInConfig(extendName, ctx) { + const { + eslintAllPath, + getEslintAllConfig, + eslintRecommendedPath, + getEslintRecommendedConfig + } = internalSlotsMap.get(this); + + if (extendName === "eslint:recommended") { + const name = `${ctx.name} » ${extendName}`; + + if (getEslintRecommendedConfig) { + if (typeof getEslintRecommendedConfig !== "function") { + throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`); + } + return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: "" }); + } + return this._loadConfigData({ + ...ctx, + name, + filePath: eslintRecommendedPath + }); + } + if (extendName === "eslint:all") { + const name = `${ctx.name} » ${extendName}`; + + if (getEslintAllConfig) { + if (typeof getEslintAllConfig !== "function") { + throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`); + } + return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: "" }); + } + return this._loadConfigData({ + ...ctx, + name, + filePath: eslintAllPath + }); + } + + throw configInvalidError(extendName, ctx.name, "extend-config-missing"); + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @throws {Error} If the extended config file can't be loaded. + * @private + */ + _loadExtendedPluginConfig(extendName, ctx) { + const slashIndex = extendName.lastIndexOf("/"); + + if (slashIndex === -1) { + throw configInvalidError(extendName, ctx.filePath, "plugin-invalid"); + } + + const pluginName = extendName.slice("plugin:".length, slashIndex); + const configName = extendName.slice(slashIndex + 1); + + if (isFilePath(pluginName)) { + throw new Error("'extends' cannot use a file path for plugins."); + } + + const plugin = this._loadPlugin(pluginName, ctx); + const configData = + plugin.definition && + plugin.definition.configs[configName]; + + if (configData) { + return this._normalizeConfigData(configData, { + ...ctx, + filePath: plugin.filePath || ctx.filePath, + name: `${ctx.name} » plugin:${plugin.id}/${configName}` + }); + } + + throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing"); + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @throws {Error} If the extended config file can't be loaded. + * @private + */ + _loadExtendedShareableConfig(extendName, ctx) { + const { cwd, resolver } = internalSlotsMap.get(this); + const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js"); + let request; + + if (isFilePath(extendName)) { + request = extendName; + } else if (extendName.startsWith(".")) { + request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior. + } else { + request = naming.normalizePackageName( + extendName, + "eslint-config" + ); + } + + let filePath; + + try { + filePath = resolver.resolve(request, relativeTo); + } catch (error) { + /* istanbul ignore else */ + if (error && error.code === "MODULE_NOT_FOUND") { + throw configInvalidError(extendName, ctx.filePath, "extend-config-missing"); + } + throw error; + } + + writeDebugLogForLoading(request, relativeTo, filePath); + return this._loadConfigData({ + ...ctx, + filePath, + name: `${ctx.name} » ${request}` + }); + } + + /** + * Load given plugins. + * @param {string[]} names The plugin names to load. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {Record} The loaded parser. + * @private + */ + _loadPlugins(names, ctx) { + return names.reduce((map, name) => { + if (isFilePath(name)) { + throw new Error("Plugins array cannot includes file paths."); + } + const plugin = this._loadPlugin(name, ctx); + + map[plugin.id] = plugin; + + return map; + }, {}); + } + + /** + * Load a given parser. + * @param {string} nameOrPath The package name or the path to a parser file. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {DependentParser} The loaded parser. + */ + _loadParser(nameOrPath, ctx) { + debug("Loading parser %j from %s", nameOrPath, ctx.filePath); + + const { cwd, resolver } = internalSlotsMap.get(this); + const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js"); + + try { + const filePath = resolver.resolve(nameOrPath, relativeTo); + + writeDebugLogForLoading(nameOrPath, relativeTo, filePath); + + return new ConfigDependency({ + definition: require(filePath), + filePath, + id: nameOrPath, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } catch (error) { + + // If the parser name is "espree", load the espree of ESLint. + if (nameOrPath === "espree") { + debug("Fallback espree."); + return new ConfigDependency({ + definition: require("espree"), + filePath: require.resolve("espree"), + id: nameOrPath, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name); + error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`; + + return new ConfigDependency({ + error, + id: nameOrPath, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + } + + /** + * Load a given plugin. + * @param {string} name The plugin name to load. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {DependentPlugin} The loaded plugin. + * @private + */ + _loadPlugin(name, ctx) { + debug("Loading plugin %j from %s", name, ctx.filePath); + + const { additionalPluginPool, resolver } = internalSlotsMap.get(this); + const request = naming.normalizePackageName(name, "eslint-plugin"); + const id = naming.getShorthandName(request, "eslint-plugin"); + const relativeTo = path.join(ctx.pluginBasePath, "__placeholder__.js"); + + if (name.match(/\s+/u)) { + const error = Object.assign( + new Error(`Whitespace found in plugin name '${name}'`), + { + messageTemplate: "whitespace-found", + messageData: { pluginName: request } + } + ); + + return new ConfigDependency({ + error, + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + // Check for additional pool. + const plugin = + additionalPluginPool.get(request) || + additionalPluginPool.get(id); + + if (plugin) { + return new ConfigDependency({ + definition: normalizePlugin(plugin), + original: plugin, + filePath: "", // It's unknown where the plugin came from. + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + let filePath; + let error; + + try { + filePath = resolver.resolve(request, relativeTo); + } catch (resolveError) { + error = resolveError; + /* istanbul ignore else */ + if (error && error.code === "MODULE_NOT_FOUND") { + error.messageTemplate = "plugin-missing"; + error.messageData = { + pluginName: request, + resolvePluginsRelativeTo: ctx.pluginBasePath, + importerName: ctx.name + }; + } + } + + if (filePath) { + try { + writeDebugLogForLoading(request, relativeTo, filePath); + + const startTime = Date.now(); + const pluginDefinition = require(filePath); + + debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`); + + return new ConfigDependency({ + definition: normalizePlugin(pluginDefinition), + original: pluginDefinition, + filePath, + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } catch (loadError) { + error = loadError; + } + } + + debug("Failed to load plugin '%s' declared in '%s'.", name, ctx.name); + error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`; + return new ConfigDependency({ + error, + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + /** + * Take file expression processors as config array elements. + * @param {Record} plugins The plugin definitions. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The config array elements of file expression processors. + * @private + */ + *_takeFileExtensionProcessors(plugins, ctx) { + for (const pluginId of Object.keys(plugins)) { + const processors = + plugins[pluginId] && + plugins[pluginId].definition && + plugins[pluginId].definition.processors; + + if (!processors) { + continue; + } + + for (const processorId of Object.keys(processors)) { + if (processorId.startsWith(".")) { + yield* this._normalizeObjectConfigData( + { + files: [`*${processorId}`], + processor: `${pluginId}/${processorId}` + }, + { + ...ctx, + type: "implicit-processor", + name: `${ctx.name}#processors["${pluginId}/${processorId}"]` + } + ); + } + } + } + } +} + +export { + ConfigArrayFactory, + createContext, + loadConfigFile +}; diff --git a/node_modules/@eslint/eslintrc/lib/config-array/config-array.js b/node_modules/@eslint/eslintrc/lib/config-array/config-array.js new file mode 100644 index 00000000..8b3ec28c --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/config-array/config-array.js @@ -0,0 +1,512 @@ +/** + * @fileoverview `ConfigArray` class. + * + * `ConfigArray` class expresses the full of a configuration. It has the entry + * config file, base config files that were extended, loaded parsers, and loaded + * plugins. + * + * `ConfigArray` class provides three properties and two methods. + * + * - `pluginEnvironments` + * - `pluginProcessors` + * - `pluginRules` + * The `Map` objects that contain the members of all plugins that this + * config array contains. Those map objects don't have mutation methods. + * Those keys are the member ID such as `pluginId/memberName`. + * - `isRoot()` + * If `true` then this configuration has `root:true` property. + * - `extractConfig(filePath)` + * Extract the final configuration for a given file. This means merging + * every config array element which that `criteria` property matched. The + * `filePath` argument must be an absolute path. + * + * `ConfigArrayFactory` provides the loading logic of config files. + * + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import { ExtractedConfig } from "./extracted-config.js"; +import { IgnorePattern } from "./ignore-pattern.js"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Define types for VSCode IntelliSense. +/** @typedef {import("../../shared/types").Environment} Environment */ +/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../../shared/types").RuleConf} RuleConf */ +/** @typedef {import("../../shared/types").Rule} Rule */ +/** @typedef {import("../../shared/types").Plugin} Plugin */ +/** @typedef {import("../../shared/types").Processor} Processor */ +/** @typedef {import("./config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ +/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */ + +/** + * @typedef {Object} ConfigArrayElement + * @property {string} name The name of this config element. + * @property {string} filePath The path to the source file of this config element. + * @property {InstanceType|null} criteria The tester for the `files` and `excludedFiles` of this config element. + * @property {Record|undefined} env The environment settings. + * @property {Record|undefined} globals The global variable settings. + * @property {IgnorePattern|undefined} ignorePattern The ignore patterns. + * @property {boolean|undefined} noInlineConfig The flag that disables directive comments. + * @property {DependentParser|undefined} parser The parser loader. + * @property {Object|undefined} parserOptions The parser options. + * @property {Record|undefined} plugins The plugin loaders. + * @property {string|undefined} processor The processor name to refer plugin's processor. + * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments. + * @property {boolean|undefined} root The flag to express root. + * @property {Record|undefined} rules The rule settings + * @property {Object|undefined} settings The shared settings. + * @property {"config" | "ignore" | "implicit-processor"} type The element type. + */ + +/** + * @typedef {Object} ConfigArrayInternalSlots + * @property {Map} cache The cache to extract configs. + * @property {ReadonlyMap|null} envMap The map from environment ID to environment definition. + * @property {ReadonlyMap|null} processorMap The map from processor ID to environment definition. + * @property {ReadonlyMap|null} ruleMap The map from rule ID to rule definition. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new class extends WeakMap { + get(key) { + let value = super.get(key); + + if (!value) { + value = { + cache: new Map(), + envMap: null, + processorMap: null, + ruleMap: null + }; + super.set(key, value); + } + + return value; + } +}(); + +/** + * Get the indices which are matched to a given file. + * @param {ConfigArrayElement[]} elements The elements. + * @param {string} filePath The path to a target file. + * @returns {number[]} The indices. + */ +function getMatchedIndices(elements, filePath) { + const indices = []; + + for (let i = elements.length - 1; i >= 0; --i) { + const element = elements[i]; + + if (!element.criteria || (filePath && element.criteria.test(filePath))) { + indices.push(i); + } + } + + return indices; +} + +/** + * Check if a value is a non-null object. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is a non-null object. + */ +function isNonNullObject(x) { + return typeof x === "object" && x !== null; +} + +/** + * Merge two objects. + * + * Assign every property values of `y` to `x` if `x` doesn't have the property. + * If `x`'s property value is an object, it does recursive. + * @param {Object} target The destination to merge + * @param {Object|undefined} source The source to merge. + * @returns {void} + */ +function mergeWithoutOverwrite(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + + if (isNonNullObject(target[key])) { + mergeWithoutOverwrite(target[key], source[key]); + } else if (target[key] === void 0) { + if (isNonNullObject(source[key])) { + target[key] = Array.isArray(source[key]) ? [] : {}; + mergeWithoutOverwrite(target[key], source[key]); + } else if (source[key] !== void 0) { + target[key] = source[key]; + } + } + } +} + +/** + * The error for plugin conflicts. + */ +class PluginConflictError extends Error { + + /** + * Initialize this error object. + * @param {string} pluginId The plugin ID. + * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins. + */ + constructor(pluginId, plugins) { + super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`); + this.messageTemplate = "plugin-conflict"; + this.messageData = { pluginId, plugins }; + } +} + +/** + * Merge plugins. + * `target`'s definition is prior to `source`'s. + * @param {Record} target The destination to merge + * @param {Record|undefined} source The source to merge. + * @returns {void} + * @throws {PluginConflictError} When a plugin was conflicted. + */ +function mergePlugins(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + const targetValue = target[key]; + const sourceValue = source[key]; + + // Adopt the plugin which was found at first. + if (targetValue === void 0) { + if (sourceValue.error) { + throw sourceValue.error; + } + target[key] = sourceValue; + } else if (sourceValue.filePath !== targetValue.filePath) { + throw new PluginConflictError(key, [ + { + filePath: targetValue.filePath, + importerName: targetValue.importerName + }, + { + filePath: sourceValue.filePath, + importerName: sourceValue.importerName + } + ]); + } + } +} + +/** + * Merge rule configs. + * `target`'s definition is prior to `source`'s. + * @param {Record} target The destination to merge + * @param {Record|undefined} source The source to merge. + * @returns {void} + */ +function mergeRuleConfigs(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + const targetDef = target[key]; + const sourceDef = source[key]; + + // Adopt the rule config which was found at first. + if (targetDef === void 0) { + if (Array.isArray(sourceDef)) { + target[key] = [...sourceDef]; + } else { + target[key] = [sourceDef]; + } + + /* + * If the first found rule config is severity only and the current rule + * config has options, merge the severity and the options. + */ + } else if ( + targetDef.length === 1 && + Array.isArray(sourceDef) && + sourceDef.length >= 2 + ) { + targetDef.push(...sourceDef.slice(1)); + } + } +} + +/** + * Create the extracted config. + * @param {ConfigArray} instance The config elements. + * @param {number[]} indices The indices to use. + * @returns {ExtractedConfig} The extracted config. + * @throws {Error} When a plugin is conflicted. + */ +function createConfig(instance, indices) { + const config = new ExtractedConfig(); + const ignorePatterns = []; + + // Merge elements. + for (const index of indices) { + const element = instance[index]; + + // Adopt the parser which was found at first. + if (!config.parser && element.parser) { + if (element.parser.error) { + throw element.parser.error; + } + config.parser = element.parser; + } + + // Adopt the processor which was found at first. + if (!config.processor && element.processor) { + config.processor = element.processor; + } + + // Adopt the noInlineConfig which was found at first. + if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) { + config.noInlineConfig = element.noInlineConfig; + config.configNameOfNoInlineConfig = element.name; + } + + // Adopt the reportUnusedDisableDirectives which was found at first. + if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) { + config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives; + } + + // Collect ignorePatterns + if (element.ignorePattern) { + ignorePatterns.push(element.ignorePattern); + } + + // Merge others. + mergeWithoutOverwrite(config.env, element.env); + mergeWithoutOverwrite(config.globals, element.globals); + mergeWithoutOverwrite(config.parserOptions, element.parserOptions); + mergeWithoutOverwrite(config.settings, element.settings); + mergePlugins(config.plugins, element.plugins); + mergeRuleConfigs(config.rules, element.rules); + } + + // Create the predicate function for ignore patterns. + if (ignorePatterns.length > 0) { + config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse()); + } + + return config; +} + +/** + * Collect definitions. + * @template T, U + * @param {string} pluginId The plugin ID for prefix. + * @param {Record} defs The definitions to collect. + * @param {Map} map The map to output. + * @returns {void} + */ +function collect(pluginId, defs, map) { + if (defs) { + const prefix = pluginId && `${pluginId}/`; + + for (const [key, value] of Object.entries(defs)) { + map.set(`${prefix}${key}`, value); + } + } +} + +/** + * Delete the mutation methods from a given map. + * @param {Map} map The map object to delete. + * @returns {void} + */ +function deleteMutationMethods(map) { + Object.defineProperties(map, { + clear: { configurable: true, value: void 0 }, + delete: { configurable: true, value: void 0 }, + set: { configurable: true, value: void 0 } + }); +} + +/** + * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. + * @param {ConfigArrayElement[]} elements The config elements. + * @param {ConfigArrayInternalSlots} slots The internal slots. + * @returns {void} + */ +function initPluginMemberMaps(elements, slots) { + const processed = new Set(); + + slots.envMap = new Map(); + slots.processorMap = new Map(); + slots.ruleMap = new Map(); + + for (const element of elements) { + if (!element.plugins) { + continue; + } + + for (const [pluginId, value] of Object.entries(element.plugins)) { + const plugin = value.definition; + + if (!plugin || processed.has(pluginId)) { + continue; + } + processed.add(pluginId); + + collect(pluginId, plugin.environments, slots.envMap); + collect(pluginId, plugin.processors, slots.processorMap); + collect(pluginId, plugin.rules, slots.ruleMap); + } + } + + deleteMutationMethods(slots.envMap); + deleteMutationMethods(slots.processorMap); + deleteMutationMethods(slots.ruleMap); +} + +/** + * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. + * @param {ConfigArray} instance The config elements. + * @returns {ConfigArrayInternalSlots} The extracted config. + */ +function ensurePluginMemberMaps(instance) { + const slots = internalSlotsMap.get(instance); + + if (!slots.ruleMap) { + initPluginMemberMaps(instance, slots); + } + + return slots; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The Config Array. + * + * `ConfigArray` instance contains all settings, parsers, and plugins. + * You need to call `ConfigArray#extractConfig(filePath)` method in order to + * extract, merge and get only the config data which is related to an arbitrary + * file. + * @extends {Array} + */ +class ConfigArray extends Array { + + /** + * Get the plugin environments. + * The returned map cannot be mutated. + * @type {ReadonlyMap} The plugin environments. + */ + get pluginEnvironments() { + return ensurePluginMemberMaps(this).envMap; + } + + /** + * Get the plugin processors. + * The returned map cannot be mutated. + * @type {ReadonlyMap} The plugin processors. + */ + get pluginProcessors() { + return ensurePluginMemberMaps(this).processorMap; + } + + /** + * Get the plugin rules. + * The returned map cannot be mutated. + * @returns {ReadonlyMap} The plugin rules. + */ + get pluginRules() { + return ensurePluginMemberMaps(this).ruleMap; + } + + /** + * Check if this config has `root` flag. + * @returns {boolean} `true` if this config array is root. + */ + isRoot() { + for (let i = this.length - 1; i >= 0; --i) { + const root = this[i].root; + + if (typeof root === "boolean") { + return root; + } + } + return false; + } + + /** + * Extract the config data which is related to a given file. + * @param {string} filePath The absolute path to the target file. + * @returns {ExtractedConfig} The extracted config data. + */ + extractConfig(filePath) { + const { cache } = internalSlotsMap.get(this); + const indices = getMatchedIndices(this, filePath); + const cacheKey = indices.join(","); + + if (!cache.has(cacheKey)) { + cache.set(cacheKey, createConfig(this, indices)); + } + + return cache.get(cacheKey); + } + + /** + * Check if a given path is an additional lint target. + * @param {string} filePath The absolute path to the target file. + * @returns {boolean} `true` if the file is an additional lint target. + */ + isAdditionalTargetPath(filePath) { + for (const { criteria, type } of this) { + if ( + type === "config" && + criteria && + !criteria.endsWithWildcard && + criteria.test(filePath) + ) { + return true; + } + } + return false; + } +} + +/** + * Get the used extracted configs. + * CLIEngine will use this method to collect used deprecated rules. + * @param {ConfigArray} instance The config array object to get. + * @returns {ExtractedConfig[]} The used extracted configs. + * @private + */ +function getUsedExtractedConfigs(instance) { + const { cache } = internalSlotsMap.get(instance); + + return Array.from(cache.values()); +} + + +export { + ConfigArray, + getUsedExtractedConfigs +}; diff --git a/node_modules/@eslint/eslintrc/lib/config-array/config-dependency.js b/node_modules/@eslint/eslintrc/lib/config-array/config-dependency.js new file mode 100644 index 00000000..80968950 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/config-array/config-dependency.js @@ -0,0 +1,124 @@ +/** + * @fileoverview `ConfigDependency` class. + * + * `ConfigDependency` class expresses a loaded parser or plugin. + * + * If the parser or plugin was loaded successfully, it has `definition` property + * and `filePath` property. Otherwise, it has `error` property. + * + * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it + * omits `definition` property. + * + * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers + * or plugins. + * + * @author Toru Nagashima + */ + +import util from "node:util"; + +/** + * The class is to store parsers or plugins. + * This class hides the loaded object from `JSON.stringify()` and `console.log`. + * @template T + */ +class ConfigDependency { + + /** + * Initialize this instance. + * @param {Object} data The dependency data. + * @param {T} [data.definition] The dependency if the loading succeeded. + * @param {T} [data.original] The original, non-normalized dependency if the loading succeeded. + * @param {Error} [data.error] The error object if the loading failed. + * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded. + * @param {string} data.id The ID of this dependency. + * @param {string} data.importerName The name of the config file which loads this dependency. + * @param {string} data.importerPath The path to the config file which loads this dependency. + */ + constructor({ + definition = null, + original = null, + error = null, + filePath = null, + id, + importerName, + importerPath + }) { + + /** + * The loaded dependency if the loading succeeded. + * @type {T|null} + */ + this.definition = definition; + + /** + * The original dependency as loaded directly from disk if the loading succeeded. + * @type {T|null} + */ + this.original = original; + + /** + * The error object if the loading failed. + * @type {Error|null} + */ + this.error = error; + + /** + * The loaded dependency if the loading succeeded. + * @type {string|null} + */ + this.filePath = filePath; + + /** + * The ID of this dependency. + * @type {string} + */ + this.id = id; + + /** + * The name of the config file which loads this dependency. + * @type {string} + */ + this.importerName = importerName; + + /** + * The path to the config file which loads this dependency. + * @type {string} + */ + this.importerPath = importerPath; + } + + /** + * Converts this instance to a JSON compatible object. + * @returns {Object} a JSON compatible object. + */ + toJSON() { + const obj = this[util.inspect.custom](); + + // Display `error.message` (`Error#message` is unenumerable). + if (obj.error instanceof Error) { + obj.error = { ...obj.error, message: obj.error.message }; + } + + return obj; + } + + /** + * Custom inspect method for Node.js `console.log()`. + * @returns {Object} an object to display by `console.log()`. + */ + [util.inspect.custom]() { + const { + definition: _ignore1, // eslint-disable-line no-unused-vars -- needed to make `obj` correct + original: _ignore2, // eslint-disable-line no-unused-vars -- needed to make `obj` correct + ...obj + } = this; + + return obj; + } +} + +/** @typedef {ConfigDependency} DependentParser */ +/** @typedef {ConfigDependency} DependentPlugin */ + +export { ConfigDependency }; diff --git a/node_modules/@eslint/eslintrc/lib/config-array/extracted-config.js b/node_modules/@eslint/eslintrc/lib/config-array/extracted-config.js new file mode 100644 index 00000000..65206f27 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/config-array/extracted-config.js @@ -0,0 +1,145 @@ +/** + * @fileoverview `ExtractedConfig` class. + * + * `ExtractedConfig` class expresses a final configuration for a specific file. + * + * It provides one method. + * + * - `toCompatibleObjectAsConfigFileContent()` + * Convert this configuration to the compatible object as the content of + * config files. It converts the loaded parser and plugins to strings. + * `CLIEngine#getConfigForFile(filePath)` method uses this method. + * + * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance. + * + * @author Toru Nagashima + */ + +import { IgnorePattern } from "./ignore-pattern.js"; + +// For VSCode intellisense +/** @typedef {import("../../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */ +/** @typedef {import("./config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ + +/** + * Check if `xs` starts with `ys`. + * @template T + * @param {T[]} xs The array to check. + * @param {T[]} ys The array that may be the first part of `xs`. + * @returns {boolean} `true` if `xs` starts with `ys`. + */ +function startsWith(xs, ys) { + return xs.length >= ys.length && ys.every((y, i) => y === xs[i]); +} + +/** + * The class for extracted config data. + */ +class ExtractedConfig { + constructor() { + + /** + * The config name what `noInlineConfig` setting came from. + * @type {string} + */ + this.configNameOfNoInlineConfig = ""; + + /** + * Environments. + * @type {Record} + */ + this.env = {}; + + /** + * Global variables. + * @type {Record} + */ + this.globals = {}; + + /** + * The glob patterns that ignore to lint. + * @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined} + */ + this.ignores = void 0; + + /** + * The flag that disables directive comments. + * @type {boolean|undefined} + */ + this.noInlineConfig = void 0; + + /** + * Parser definition. + * @type {DependentParser|null} + */ + this.parser = null; + + /** + * Options for the parser. + * @type {Object} + */ + this.parserOptions = {}; + + /** + * Plugin definitions. + * @type {Record} + */ + this.plugins = {}; + + /** + * Processor ID. + * @type {string|null} + */ + this.processor = null; + + /** + * The flag that reports unused `eslint-disable` directive comments. + * @type {boolean|undefined} + */ + this.reportUnusedDisableDirectives = void 0; + + /** + * Rule settings. + * @type {Record} + */ + this.rules = {}; + + /** + * Shared settings. + * @type {Object} + */ + this.settings = {}; + } + + /** + * Convert this config to the compatible object as a config file content. + * @returns {ConfigData} The converted object. + */ + toCompatibleObjectAsConfigFileContent() { + const { + /* eslint-disable no-unused-vars -- needed to make `config` correct */ + configNameOfNoInlineConfig: _ignore1, + processor: _ignore2, + /* eslint-enable no-unused-vars -- needed to make `config` correct */ + ignores, + ...config + } = this; + + config.parser = config.parser && config.parser.filePath; + config.plugins = Object.keys(config.plugins).filter(Boolean).reverse(); + config.ignorePatterns = ignores ? ignores.patterns : []; + + // Strip the default patterns from `ignorePatterns`. + if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) { + config.ignorePatterns = + config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length); + } + + return config; + } +} + +export { ExtractedConfig }; diff --git a/node_modules/@eslint/eslintrc/lib/config-array/ignore-pattern.js b/node_modules/@eslint/eslintrc/lib/config-array/ignore-pattern.js new file mode 100644 index 00000000..edb52872 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/config-array/ignore-pattern.js @@ -0,0 +1,239 @@ +/** + * @fileoverview `IgnorePattern` class. + * + * `IgnorePattern` class has the set of glob patterns and the base path. + * + * It provides two static methods. + * + * - `IgnorePattern.createDefaultIgnore(cwd)` + * Create the default predicate function. + * - `IgnorePattern.createIgnore(ignorePatterns)` + * Create the predicate function from multiple `IgnorePattern` objects. + * + * It provides two properties and a method. + * + * - `patterns` + * The glob patterns that ignore to lint. + * - `basePath` + * The base path of the glob patterns. If absolute paths existed in the + * glob patterns, those are handled as relative paths to the base path. + * - `getPatternsRelativeTo(basePath)` + * Get `patterns` as modified for a given base path. It modifies the + * absolute paths in the patterns as prepending the difference of two base + * paths. + * + * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes + * `ignorePatterns` properties. + * + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import assert from "node:assert"; +import path from "node:path"; +import ignore from "ignore"; +import debugOrig from "debug"; + +const debug = debugOrig("eslintrc:ignore-pattern"); + +/** @typedef {ReturnType} Ignore */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Get the path to the common ancestor directory of given paths. + * @param {string[]} sourcePaths The paths to calculate the common ancestor. + * @returns {string} The path to the common ancestor directory. + */ +function getCommonAncestorPath(sourcePaths) { + let result = sourcePaths[0]; + + for (let i = 1; i < sourcePaths.length; ++i) { + const a = result; + const b = sourcePaths[i]; + + // Set the shorter one (it's the common ancestor if one includes the other). + result = a.length < b.length ? a : b; + + // Set the common ancestor. + for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) { + if (a[j] !== b[j]) { + result = a.slice(0, lastSepPos); + break; + } + if (a[j] === path.sep) { + lastSepPos = j; + } + } + } + + let resolvedResult = result || path.sep; + + // if Windows common ancestor is root of drive must have trailing slash to be absolute. + if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") { + resolvedResult += path.sep; + } + return resolvedResult; +} + +/** + * Make relative path. + * @param {string} from The source path to get relative path. + * @param {string} to The destination path to get relative path. + * @returns {string} The relative path. + */ +function relative(from, to) { + const relPath = path.relative(from, to); + + if (path.sep === "/") { + return relPath; + } + return relPath.split(path.sep).join("/"); +} + +/** + * Get the trailing slash if existed. + * @param {string} filePath The path to check. + * @returns {string} The trailing slash if existed. + */ +function dirSuffix(filePath) { + const isDir = ( + filePath.endsWith(path.sep) || + (process.platform === "win32" && filePath.endsWith("/")) + ); + + return isDir ? "/" : ""; +} + +const DefaultPatterns = Object.freeze(["/**/node_modules/*"]); +const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]); + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +/** + * Represents a set of glob patterns to ignore against a base path. + */ +class IgnorePattern { + + /** + * The default patterns. + * @type {string[]} + */ + static get DefaultPatterns() { + return DefaultPatterns; + } + + /** + * Create the default predicate function. + * @param {string} cwd The current working directory. + * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}} + * The preficate function. + * The first argument is an absolute path that is checked. + * The second argument is the flag to not ignore dotfiles. + * If the predicate function returned `true`, it means the path should be ignored. + */ + static createDefaultIgnore(cwd) { + return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]); + } + + /** + * Create the predicate function from multiple `IgnorePattern` objects. + * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns. + * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}} + * The preficate function. + * The first argument is an absolute path that is checked. + * The second argument is the flag to not ignore dotfiles. + * If the predicate function returned `true`, it means the path should be ignored. + */ + static createIgnore(ignorePatterns) { + debug("Create with: %o", ignorePatterns); + + const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath)); + const patterns = ignorePatterns.flatMap(p => p.getPatternsRelativeTo(basePath)); + const ig = ignore({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]); + const dotIg = ignore({ allowRelativePaths: true }).add(patterns); + + debug(" processed: %o", { basePath, patterns }); + + return Object.assign( + (filePath, dot = false) => { + assert(path.isAbsolute(filePath), "'filePath' should be an absolute path."); + const relPathRaw = relative(basePath, filePath); + const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath)); + const adoptedIg = dot ? dotIg : ig; + const result = relPath !== "" && adoptedIg.ignores(relPath); + + debug("Check", { filePath, dot, relativePath: relPath, result }); + return result; + }, + { basePath, patterns } + ); + } + + /** + * Initialize a new `IgnorePattern` instance. + * @param {string[]} patterns The glob patterns that ignore to lint. + * @param {string} basePath The base path of `patterns`. + */ + constructor(patterns, basePath) { + assert(path.isAbsolute(basePath), "'basePath' should be an absolute path."); + + /** + * The glob patterns that ignore to lint. + * @type {string[]} + */ + this.patterns = patterns; + + /** + * The base path of `patterns`. + * @type {string} + */ + this.basePath = basePath; + + /** + * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`. + * + * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility. + * It's `false` as-is for `ignorePatterns` property in config files. + * @type {boolean} + */ + this.loose = false; + } + + /** + * Get `patterns` as modified for a given base path. It modifies the + * absolute paths in the patterns as prepending the difference of two base + * paths. + * @param {string} newBasePath The base path. + * @returns {string[]} Modifired patterns. + */ + getPatternsRelativeTo(newBasePath) { + assert(path.isAbsolute(newBasePath), "'newBasePath' should be an absolute path."); + const { basePath, loose, patterns } = this; + + if (newBasePath === basePath) { + return patterns; + } + const prefix = `/${relative(newBasePath, basePath)}`; + + return patterns.map(pattern => { + const negative = pattern.startsWith("!"); + const head = negative ? "!" : ""; + const body = negative ? pattern.slice(1) : pattern; + + if (body.startsWith("/") || body.startsWith("../")) { + return `${head}${prefix}${body}`; + } + return loose ? pattern : `${head}${prefix}/**/${body}`; + }); + } +} + +export { IgnorePattern }; diff --git a/node_modules/@eslint/eslintrc/lib/config-array/index.js b/node_modules/@eslint/eslintrc/lib/config-array/index.js new file mode 100644 index 00000000..647f02b7 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/config-array/index.js @@ -0,0 +1,19 @@ +/** + * @fileoverview `ConfigArray` class. + * @author Toru Nagashima + */ + +import { ConfigArray, getUsedExtractedConfigs } from "./config-array.js"; +import { ConfigDependency } from "./config-dependency.js"; +import { ExtractedConfig } from "./extracted-config.js"; +import { IgnorePattern } from "./ignore-pattern.js"; +import { OverrideTester } from "./override-tester.js"; + +export { + ConfigArray, + ConfigDependency, + ExtractedConfig, + IgnorePattern, + OverrideTester, + getUsedExtractedConfigs +}; diff --git a/node_modules/@eslint/eslintrc/lib/config-array/override-tester.js b/node_modules/@eslint/eslintrc/lib/config-array/override-tester.js new file mode 100644 index 00000000..3a445b1a --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/config-array/override-tester.js @@ -0,0 +1,227 @@ +/** + * @fileoverview `OverrideTester` class. + * + * `OverrideTester` class handles `files` property and `excludedFiles` property + * of `overrides` config. + * + * It provides one method. + * + * - `test(filePath)` + * Test if a file path matches the pair of `files` property and + * `excludedFiles` property. The `filePath` argument must be an absolute + * path. + * + * `ConfigArrayFactory` creates `OverrideTester` objects when it processes + * `overrides` properties. + * + * @author Toru Nagashima + */ + +import assert from "node:assert"; +import path from "node:path"; +import util from "node:util"; +import minimatch from "minimatch"; + +const { Minimatch } = minimatch; + +const minimatchOpts = { dot: true, matchBase: true }; + +/** + * @typedef {Object} Pattern + * @property {InstanceType[] | null} includes The positive matchers. + * @property {InstanceType[] | null} excludes The negative matchers. + */ + +/** + * Normalize a given pattern to an array. + * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns. + * @returns {string[]|null} Normalized patterns. + * @private + */ +function normalizePatterns(patterns) { + if (Array.isArray(patterns)) { + return patterns.filter(Boolean); + } + if (typeof patterns === "string" && patterns) { + return [patterns]; + } + return []; +} + +/** + * Create the matchers of given patterns. + * @param {string[]} patterns The patterns. + * @returns {InstanceType[] | null} The matchers. + */ +function toMatcher(patterns) { + if (patterns.length === 0) { + return null; + } + return patterns.map(pattern => { + if (/^\.[/\\]/u.test(pattern)) { + return new Minimatch( + pattern.slice(2), + + // `./*.js` should not match with `subdir/foo.js` + { ...minimatchOpts, matchBase: false } + ); + } + return new Minimatch(pattern, minimatchOpts); + }); +} + +/** + * Convert a given matcher to string. + * @param {Pattern} matchers The matchers. + * @returns {string} The string expression of the matcher. + */ +function patternToJson({ includes, excludes }) { + return { + includes: includes && includes.map(m => m.pattern), + excludes: excludes && excludes.map(m => m.pattern) + }; +} + +/** + * The class to test given paths are matched by the patterns. + */ +class OverrideTester { + + /** + * Create a tester with given criteria. + * If there are no criteria, returns `null`. + * @param {string|string[]} files The glob patterns for included files. + * @param {string|string[]} excludedFiles The glob patterns for excluded files. + * @param {string} basePath The path to the base directory to test paths. + * @returns {OverrideTester|null} The created instance or `null`. + * @throws {Error} When invalid patterns are given. + */ + static create(files, excludedFiles, basePath) { + const includePatterns = normalizePatterns(files); + const excludePatterns = normalizePatterns(excludedFiles); + let endsWithWildcard = false; + + if (includePatterns.length === 0) { + return null; + } + + // Rejects absolute paths or relative paths to parents. + for (const pattern of includePatterns) { + if (path.isAbsolute(pattern) || pattern.includes("..")) { + throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); + } + if (pattern.endsWith("*")) { + endsWithWildcard = true; + } + } + for (const pattern of excludePatterns) { + if (path.isAbsolute(pattern) || pattern.includes("..")) { + throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); + } + } + + const includes = toMatcher(includePatterns); + const excludes = toMatcher(excludePatterns); + + return new OverrideTester( + [{ includes, excludes }], + basePath, + endsWithWildcard + ); + } + + /** + * Combine two testers by logical and. + * If either of the testers was `null`, returns the other tester. + * The `basePath` property of the two must be the same value. + * @param {OverrideTester|null} a A tester. + * @param {OverrideTester|null} b Another tester. + * @returns {OverrideTester|null} Combined tester. + */ + static and(a, b) { + if (!b) { + return a && new OverrideTester( + a.patterns, + a.basePath, + a.endsWithWildcard + ); + } + if (!a) { + return new OverrideTester( + b.patterns, + b.basePath, + b.endsWithWildcard + ); + } + + assert.strictEqual(a.basePath, b.basePath); + return new OverrideTester( + a.patterns.concat(b.patterns), + a.basePath, + a.endsWithWildcard || b.endsWithWildcard + ); + } + + /** + * Initialize this instance. + * @param {Pattern[]} patterns The matchers. + * @param {string} basePath The base path. + * @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`. + */ + constructor(patterns, basePath, endsWithWildcard = false) { + + /** @type {Pattern[]} */ + this.patterns = patterns; + + /** @type {string} */ + this.basePath = basePath; + + /** @type {boolean} */ + this.endsWithWildcard = endsWithWildcard; + } + + /** + * Test if a given path is matched or not. + * @param {string} filePath The absolute path to the target file. + * @returns {boolean} `true` if the path was matched. + * @throws {Error} When invalid `filePath` is given. + */ + test(filePath) { + if (typeof filePath !== "string" || !path.isAbsolute(filePath)) { + throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`); + } + const relativePath = path.relative(this.basePath, filePath); + + return this.patterns.every(({ includes, excludes }) => ( + (!includes || includes.some(m => m.match(relativePath))) && + (!excludes || !excludes.some(m => m.match(relativePath))) + )); + } + + /** + * Converts this instance to a JSON compatible object. + * @returns {Object} a JSON compatible object. + */ + toJSON() { + if (this.patterns.length === 1) { + return { + ...patternToJson(this.patterns[0]), + basePath: this.basePath + }; + } + return { + AND: this.patterns.map(patternToJson), + basePath: this.basePath + }; + } + + /** + * Custom inspect method for Node.js `console.log()`. + * @returns {Object} an object to display by `console.log()`. + */ + [util.inspect.custom]() { + return this.toJSON(); + } +} + +export { OverrideTester }; diff --git a/node_modules/@eslint/eslintrc/lib/flat-compat.js b/node_modules/@eslint/eslintrc/lib/flat-compat.js new file mode 100644 index 00000000..caaca204 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/flat-compat.js @@ -0,0 +1,319 @@ +/** + * @fileoverview Compatibility class for flat config. + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +import createDebug from "debug"; +import path from "node:path"; + +import environments from "../conf/environments.js"; +import { ConfigArrayFactory } from "./config-array-factory.js"; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** @typedef {import("../../shared/types").Environment} Environment */ +/** @typedef {import("../../shared/types").Processor} Processor */ + +const debug = createDebug("eslintrc:flat-compat"); +const cafactory = Symbol("cafactory"); + +/** + * Translates an ESLintRC-style config object into a flag-config-style config + * object. + * @param {Object} eslintrcConfig An ESLintRC-style config object. + * @param {Object} options Options to help translate the config. + * @param {string} options.resolveConfigRelativeTo To the directory to resolve + * configs from. + * @param {string} options.resolvePluginsRelativeTo The directory to resolve + * plugins from. + * @param {ReadOnlyMap} options.pluginEnvironments A map of plugin environment + * names to objects. + * @param {ReadOnlyMap} options.pluginProcessors A map of plugin processor + * names to objects. + * @returns {Object} A flag-config-style config object. + * @throws {Error} If a plugin or environment cannot be resolved. + */ +function translateESLintRC(eslintrcConfig, { + resolveConfigRelativeTo, + resolvePluginsRelativeTo, + pluginEnvironments, + pluginProcessors +}) { + + const flatConfig = {}; + const configs = []; + const languageOptions = {}; + const linterOptions = {}; + const keysToCopy = ["settings", "rules", "processor"]; + const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"]; + const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"]; + + // copy over simple translations + for (const key of keysToCopy) { + if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") { + flatConfig[key] = eslintrcConfig[key]; + } + } + + // copy over languageOptions + for (const key of languageOptionsKeysToCopy) { + if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") { + + // create the languageOptions key in the flat config + flatConfig.languageOptions = languageOptions; + + if (key === "parser") { + debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`); + + if (eslintrcConfig[key].error) { + throw eslintrcConfig[key].error; + } + + languageOptions[key] = eslintrcConfig[key].definition; + continue; + } + + // clone any object values that are in the eslintrc config + if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") { + languageOptions[key] = { + ...eslintrcConfig[key] + }; + } else { + languageOptions[key] = eslintrcConfig[key]; + } + } + } + + // copy over linterOptions + for (const key of linterOptionsKeysToCopy) { + if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") { + flatConfig.linterOptions = linterOptions; + linterOptions[key] = eslintrcConfig[key]; + } + } + + // move ecmaVersion a level up + if (languageOptions.parserOptions) { + + if ("ecmaVersion" in languageOptions.parserOptions) { + languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion; + delete languageOptions.parserOptions.ecmaVersion; + } + + if ("sourceType" in languageOptions.parserOptions) { + languageOptions.sourceType = languageOptions.parserOptions.sourceType; + delete languageOptions.parserOptions.sourceType; + } + + // check to see if we even need parserOptions anymore and remove it if not + if (Object.keys(languageOptions.parserOptions).length === 0) { + delete languageOptions.parserOptions; + } + } + + // overrides + if (eslintrcConfig.criteria) { + flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)]; + } + + // translate plugins + if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") { + debug(`Translating plugins: ${eslintrcConfig.plugins}`); + + flatConfig.plugins = {}; + + for (const pluginName of Object.keys(eslintrcConfig.plugins)) { + + debug(`Translating plugin: ${pluginName}`); + debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`); + + const { original: plugin, error } = eslintrcConfig.plugins[pluginName]; + + if (error) { + throw error; + } + + flatConfig.plugins[pluginName] = plugin; + + // create a config for any processors + if (plugin.processors) { + for (const processorName of Object.keys(plugin.processors)) { + if (processorName.startsWith(".")) { + debug(`Assigning processor: ${pluginName}/${processorName}`); + + configs.unshift({ + files: [`**/*${processorName}`], + processor: pluginProcessors.get(`${pluginName}/${processorName}`) + }); + } + + } + } + } + } + + // translate env - must come after plugins + if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") { + for (const envName of Object.keys(eslintrcConfig.env)) { + + // only add environments that are true + if (eslintrcConfig.env[envName]) { + debug(`Translating environment: ${envName}`); + + if (environments.has(envName)) { + + // built-in environments should be defined first + configs.unshift(...translateESLintRC({ + criteria: eslintrcConfig.criteria, + ...environments.get(envName) + }, { + resolveConfigRelativeTo, + resolvePluginsRelativeTo + })); + } else if (pluginEnvironments.has(envName)) { + + // if the environment comes from a plugin, it should come after the plugin config + configs.push(...translateESLintRC({ + criteria: eslintrcConfig.criteria, + ...pluginEnvironments.get(envName) + }, { + resolveConfigRelativeTo, + resolvePluginsRelativeTo + })); + } + } + } + } + + // only add if there are actually keys in the config + if (Object.keys(flatConfig).length > 0) { + configs.push(flatConfig); + } + + return configs; +} + + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A compatibility class for working with configs. + */ +class FlatCompat { + + constructor({ + baseDirectory = process.cwd(), + resolvePluginsRelativeTo = baseDirectory, + recommendedConfig, + allConfig + } = {}) { + this.baseDirectory = baseDirectory; + this.resolvePluginsRelativeTo = resolvePluginsRelativeTo; + this[cafactory] = new ConfigArrayFactory({ + cwd: baseDirectory, + resolvePluginsRelativeTo, + getEslintAllConfig() { + + if (!allConfig) { + throw new TypeError("Missing parameter 'allConfig' in FlatCompat constructor."); + } + + return allConfig; + }, + getEslintRecommendedConfig() { + + if (!recommendedConfig) { + throw new TypeError("Missing parameter 'recommendedConfig' in FlatCompat constructor."); + } + + return recommendedConfig; + } + }); + } + + /** + * Translates an ESLintRC-style config into a flag-config-style config. + * @param {Object} eslintrcConfig The ESLintRC-style config object. + * @returns {Object} A flag-config-style config object. + */ + config(eslintrcConfig) { + const eslintrcArray = this[cafactory].create(eslintrcConfig, { + basePath: this.baseDirectory + }); + + const flatArray = []; + let hasIgnorePatterns = false; + + eslintrcArray.forEach(configData => { + if (configData.type === "config") { + hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern; + flatArray.push(...translateESLintRC(configData, { + resolveConfigRelativeTo: path.join(this.baseDirectory, "__placeholder.js"), + resolvePluginsRelativeTo: path.join(this.resolvePluginsRelativeTo, "__placeholder.js"), + pluginEnvironments: eslintrcArray.pluginEnvironments, + pluginProcessors: eslintrcArray.pluginProcessors + })); + } + }); + + // combine ignorePatterns to emulate ESLintRC behavior better + if (hasIgnorePatterns) { + flatArray.unshift({ + ignores: [filePath => { + + // Compute the final config for this file. + // This filters config array elements by `files`/`excludedFiles` then merges the elements. + const finalConfig = eslintrcArray.extractConfig(filePath); + + // Test the `ignorePattern` properties of the final config. + return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath); + }] + }); + } + + return flatArray; + } + + /** + * Translates the `env` section of an ESLintRC-style config. + * @param {Object} envConfig The `env` section of an ESLintRC config. + * @returns {Object[]} An array of flag-config objects representing the environments. + */ + env(envConfig) { + return this.config({ + env: envConfig + }); + } + + /** + * Translates the `extends` section of an ESLintRC-style config. + * @param {...string} configsToExtend The names of the configs to load. + * @returns {Object[]} An array of flag-config objects representing the config. + */ + extends(...configsToExtend) { + return this.config({ + extends: configsToExtend + }); + } + + /** + * Translates the `plugins` section of an ESLintRC-style config. + * @param {...string} plugins The names of the plugins to load. + * @returns {Object[]} An array of flag-config objects representing the plugins. + */ + plugins(...plugins) { + return this.config({ + plugins + }); + } +} + +export { FlatCompat }; diff --git a/node_modules/@eslint/eslintrc/lib/index-universal.js b/node_modules/@eslint/eslintrc/lib/index-universal.js new file mode 100644 index 00000000..6f6b3026 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/index-universal.js @@ -0,0 +1,29 @@ +/** + * @fileoverview Package exports for @eslint/eslintrc + * @author Nicholas C. Zakas + */ +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import * as ConfigOps from "./shared/config-ops.js"; +import ConfigValidator from "./shared/config-validator.js"; +import * as naming from "./shared/naming.js"; +import environments from "../conf/environments.js"; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +const Legacy = { + environments, + + // shared + ConfigOps, + ConfigValidator, + naming +}; + +export { + Legacy +}; diff --git a/node_modules/@eslint/eslintrc/lib/index.js b/node_modules/@eslint/eslintrc/lib/index.js new file mode 100644 index 00000000..a37e5746 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/index.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Package exports for @eslint/eslintrc + * @author Nicholas C. Zakas + */ +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import { + ConfigArrayFactory, + createContext as createConfigArrayFactoryContext, + loadConfigFile +} from "./config-array-factory.js"; + +import { CascadingConfigArrayFactory } from "./cascading-config-array-factory.js"; +import * as ModuleResolver from "./shared/relative-module-resolver.js"; +import { ConfigArray, getUsedExtractedConfigs } from "./config-array/index.js"; +import { ConfigDependency } from "./config-array/config-dependency.js"; +import { ExtractedConfig } from "./config-array/extracted-config.js"; +import { IgnorePattern } from "./config-array/ignore-pattern.js"; +import { OverrideTester } from "./config-array/override-tester.js"; +import * as ConfigOps from "./shared/config-ops.js"; +import ConfigValidator from "./shared/config-validator.js"; +import * as naming from "./shared/naming.js"; +import { FlatCompat } from "./flat-compat.js"; +import environments from "../conf/environments.js"; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +const Legacy = { + ConfigArray, + createConfigArrayFactoryContext, + CascadingConfigArrayFactory, + ConfigArrayFactory, + ConfigDependency, + ExtractedConfig, + IgnorePattern, + OverrideTester, + getUsedExtractedConfigs, + environments, + loadConfigFile, + + // shared + ConfigOps, + ConfigValidator, + ModuleResolver, + naming +}; + +export { + + Legacy, + + FlatCompat + +}; diff --git a/node_modules/@eslint/eslintrc/lib/shared/ajv.js b/node_modules/@eslint/eslintrc/lib/shared/ajv.js new file mode 100644 index 00000000..7e53d12a --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/shared/ajv.js @@ -0,0 +1,191 @@ +/** + * @fileoverview The instance of Ajv validator. + * @author Evgeny Poberezkin + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import Ajv from "ajv"; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/* + * Copied from ajv/lib/refs/json-schema-draft-04.json + * The MIT License (MIT) + * Copyright (c) 2015-2017 Evgeny Poberezkin + */ +const metaSchema = { + id: "http://json-schema.org/draft-04/schema#", + $schema: "http://json-schema.org/draft-04/schema#", + description: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + positiveInteger: { + type: "integer", + minimum: 0 + }, + positiveIntegerDefault0: { + allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + minItems: 1, + uniqueItems: true + } + }, + type: "object", + properties: { + id: { + type: "string" + }, + $schema: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: { }, + multipleOf: { + type: "number", + minimum: 0, + exclusiveMinimum: true + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "boolean", + default: false + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "boolean", + default: false + }, + maxLength: { $ref: "#/definitions/positiveInteger" }, + minLength: { $ref: "#/definitions/positiveIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + items: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/schemaArray" } + ], + default: { } + }, + maxItems: { $ref: "#/definitions/positiveInteger" }, + minItems: { $ref: "#/definitions/positiveIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + maxProperties: { $ref: "#/definitions/positiveInteger" }, + minProperties: { $ref: "#/definitions/positiveIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/stringArray" } + ] + } + }, + enum: { + type: "array", + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + dependencies: { + exclusiveMaximum: ["maximum"], + exclusiveMinimum: ["minimum"] + }, + default: { } +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +export default (additionalOptions = {}) => { + const ajv = new Ajv({ + meta: false, + useDefaults: true, + validateSchema: false, + missingRefs: "ignore", + verbose: true, + schemaId: "auto", + ...additionalOptions + }); + + ajv.addMetaSchema(metaSchema); + // eslint-disable-next-line no-underscore-dangle -- part of the API + ajv._opts.defaultMeta = metaSchema.id; + + return ajv; +}; diff --git a/node_modules/@eslint/eslintrc/lib/shared/config-ops.js b/node_modules/@eslint/eslintrc/lib/shared/config-ops.js new file mode 100644 index 00000000..465d9b86 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/shared/config-ops.js @@ -0,0 +1,135 @@ +/** + * @fileoverview Config file operations. This file must be usable in the browser, + * so no Node-specific code can be here. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +const RULE_SEVERITY_STRINGS = ["off", "warn", "error"], + RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => { + map[value] = index; + return map; + }, {}), + VALID_SEVERITIES = new Set([0, 1, 2, "off", "warn", "error"]); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Normalizes the severity value of a rule's configuration to a number + * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally + * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0), + * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array + * whose first element is one of the above values. Strings are matched case-insensitively. + * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0. + */ +function getRuleSeverity(ruleConfig) { + const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (severityValue === 0 || severityValue === 1 || severityValue === 2) { + return severityValue; + } + + if (typeof severityValue === "string") { + return RULE_SEVERITY[severityValue.toLowerCase()] || 0; + } + + return 0; +} + +/** + * Converts old-style severity settings (0, 1, 2) into new-style + * severity settings (off, warn, error) for all rules. Assumption is that severity + * values have already been validated as correct. + * @param {Object} config The config object to normalize. + * @returns {void} + */ +function normalizeToStrings(config) { + + if (config.rules) { + Object.keys(config.rules).forEach(ruleId => { + const ruleConfig = config.rules[ruleId]; + + if (typeof ruleConfig === "number") { + config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0]; + } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") { + ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0]; + } + }); + } +} + +/** + * Determines if the severity for the given rule configuration represents an error. + * @param {int|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} True if the rule represents an error, false if not. + */ +function isErrorSeverity(ruleConfig) { + return getRuleSeverity(ruleConfig) === 2; +} + +/** + * Checks whether a given config has valid severity or not. + * @param {number|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isValidSeverity(ruleConfig) { + let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (typeof severity === "string") { + severity = severity.toLowerCase(); + } + return VALID_SEVERITIES.has(severity); +} + +/** + * Checks whether every rule of a given config has valid severity or not. + * @param {Object} config The configuration for rules. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isEverySeverityValid(config) { + return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId])); +} + +/** + * Normalizes a value for a global in a config + * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in + * a global directive comment + * @returns {("readable"|"writeable"|"off")} The value normalized as a string + * @throws Error if global value is invalid + */ +function normalizeConfigGlobal(configuredValue) { + switch (configuredValue) { + case "off": + return "off"; + + case true: + case "true": + case "writeable": + case "writable": + return "writable"; + + case null: + case false: + case "false": + case "readable": + case "readonly": + return "readonly"; + + default: + throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`); + } +} + +export { + getRuleSeverity, + normalizeToStrings, + isErrorSeverity, + isValidSeverity, + isEverySeverityValid, + normalizeConfigGlobal +}; diff --git a/node_modules/@eslint/eslintrc/lib/shared/config-validator.js b/node_modules/@eslint/eslintrc/lib/shared/config-validator.js new file mode 100644 index 00000000..6857e7a0 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/shared/config-validator.js @@ -0,0 +1,383 @@ +/** + * @fileoverview Validates configs. + * @author Brandon Mills + */ + +/* eslint class-methods-use-this: "off" -- not needed in this file */ + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../shared/types").Rule} Rule */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import util from "node:util"; +import * as ConfigOps from "./config-ops.js"; +import { emitDeprecationWarning } from "./deprecation-warnings.js"; +import ajvOrig from "./ajv.js"; +import { deepMergeArrays } from "./deep-merge-arrays.js"; +import configSchema from "../../conf/config-schema.js"; +import BuiltInEnvironments from "../../conf/environments.js"; + +const ajv = ajvOrig(); + +const ruleValidators = new WeakMap(); +const noop = Function.prototype; + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ +let validateSchema; +const severityMap = { + error: 2, + warn: 1, + off: 0 +}; + +const validated = new WeakSet(); + +// JSON schema that disallows passing any options +const noOptionsSchema = Object.freeze({ + type: "array", + minItems: 0, + maxItems: 0 +}); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Validator for configuration objects. + */ +export default class ConfigValidator { + constructor({ builtInRules = new Map() } = {}) { + this.builtInRules = builtInRules; + } + + /** + * Gets a complete options schema for a rule. + * @param {Rule} rule A rule object + * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`. + * @returns {Object|null} JSON Schema for the rule's options. + * `null` if rule wasn't passed or its `meta.schema` is `false`. + */ + getRuleOptionsSchema(rule) { + if (!rule) { + return null; + } + + if (!rule.meta) { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + const schema = rule.meta.schema; + + if (typeof schema === "undefined") { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + // `schema:false` is an allowed explicit opt-out of options validation for the rule + if (schema === false) { + return null; + } + + if (typeof schema !== "object" || schema === null) { + throw new TypeError("Rule's `meta.schema` must be an array or object"); + } + + // ESLint-specific array form needs to be converted into a valid JSON Schema definition + if (Array.isArray(schema)) { + if (schema.length) { + return { + type: "array", + items: schema, + minItems: 0, + maxItems: schema.length + }; + } + + // `schema:[]` is an explicit way to specify that the rule does not accept any options + return { ...noOptionsSchema }; + } + + // `schema:` is assumed to be a valid JSON Schema definition + return schema; + } + + /** + * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid. + * @param {options} options The given options for the rule. + * @returns {number|string} The rule's severity value + * @throws {Error} If the severity is invalid. + */ + validateRuleSeverity(options) { + const severity = Array.isArray(options) ? options[0] : options; + const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity; + + if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) { + return normSeverity; + } + + throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`); + + } + + /** + * Validates the non-severity options passed to a rule, based on its schema. + * @param {{create: Function}} rule The rule to validate + * @param {Array} localOptions The options for the rule, excluding severity + * @returns {void} + * @throws {Error} If the options are invalid. + */ + validateRuleSchema(rule, localOptions) { + if (!ruleValidators.has(rule)) { + try { + const schema = this.getRuleOptionsSchema(rule); + + if (schema) { + ruleValidators.set(rule, ajv.compile(schema)); + } + } catch (err) { + const errorWithCode = new Error(err.message, { cause: err }); + + errorWithCode.code = "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"; + + throw errorWithCode; + } + } + + const validateRule = ruleValidators.get(rule); + + if (validateRule) { + const mergedOptions = deepMergeArrays(rule.meta?.defaultOptions, localOptions); + + validateRule(mergedOptions); + + if (validateRule.errors) { + throw new Error(validateRule.errors.map( + error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n` + ).join("")); + } + } + } + + /** + * Validates a rule's options against its schema. + * @param {{create: Function}|null} rule The rule that the config is being validated for + * @param {string} ruleId The rule's unique name. + * @param {Array|number} options The given options for the rule. + * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined, + * no source is prepended to the message. + * @returns {void} + * @throws {Error} If the options are invalid. + */ + validateRuleOptions(rule, ruleId, options, source = null) { + try { + const severity = this.validateRuleSeverity(options); + + if (severity !== 0) { + this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []); + } + } catch (err) { + let enhancedMessage = err.code === "ESLINT_INVALID_RULE_OPTIONS_SCHEMA" + ? `Error while processing options validation schema of rule '${ruleId}': ${err.message}` + : `Configuration for rule "${ruleId}" is invalid:\n${err.message}`; + + if (typeof source === "string") { + enhancedMessage = `${source}:\n\t${enhancedMessage}`; + } + + const enhancedError = new Error(enhancedMessage, { cause: err }); + + if (err.code) { + enhancedError.code = err.code; + } + + throw enhancedError; + } + } + + /** + * Validates an environment object + * @param {Object} environment The environment config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded environments. + * @returns {void} + * @throws {Error} If the environment is invalid. + */ + validateEnvironment( + environment, + source, + getAdditionalEnv = noop + ) { + + // not having an environment is ok + if (!environment) { + return; + } + + Object.keys(environment).forEach(id => { + const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null; + + if (!env) { + const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`; + + throw new Error(message); + } + }); + } + + /** + * Validates a rules config object + * @param {Object} rulesConfig The rules config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(ruleId:string) => Object} getAdditionalRule A map from strings to loaded rules + * @returns {void} + */ + validateRules( + rulesConfig, + source, + getAdditionalRule = noop + ) { + if (!rulesConfig) { + return; + } + + Object.keys(rulesConfig).forEach(id => { + const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null; + + this.validateRuleOptions(rule, id, rulesConfig[id], source); + }); + } + + /** + * Validates a `globals` section of a config file + * @param {Object} globalsConfig The `globals` section + * @param {string|null} source The name of the configuration source to report in the event of an error. + * @returns {void} + */ + validateGlobals(globalsConfig, source = null) { + if (!globalsConfig) { + return; + } + + Object.entries(globalsConfig) + .forEach(([configuredGlobal, configuredValue]) => { + try { + ConfigOps.normalizeConfigGlobal(configuredValue); + } catch (err) { + throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`); + } + }); + } + + /** + * Validate `processor` configuration. + * @param {string|undefined} processorName The processor name. + * @param {string} source The name of config file. + * @param {(id:string) => Processor} getProcessor The getter of defined processors. + * @returns {void} + * @throws {Error} If the processor is invalid. + */ + validateProcessor(processorName, source, getProcessor) { + if (processorName && !getProcessor(processorName)) { + throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`); + } + } + + /** + * Formats an array of schema validation errors. + * @param {Array} errors An array of error messages to format. + * @returns {string} Formatted error message + */ + formatErrors(errors) { + return errors.map(error => { + if (error.keyword === "additionalProperties") { + const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty; + + return `Unexpected top-level property "${formattedPropertyPath}"`; + } + if (error.keyword === "type") { + const formattedField = error.dataPath.slice(1); + const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema; + const formattedValue = JSON.stringify(error.data); + + return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`; + } + + const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; + + return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`; + }).map(message => `\t- ${message}.\n`).join(""); + } + + /** + * Validates the top level properties of the config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @returns {void} + * @throws {Error} If the config is invalid. + */ + validateConfigSchema(config, source = null) { + validateSchema = validateSchema || ajv.compile(configSchema); + + if (!validateSchema(config)) { + throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`); + } + + if (Object.hasOwn(config, "ecmaFeatures")) { + emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES"); + } + } + + /** + * Validates an entire config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {(ruleId:string) => Object} [getAdditionalRule] A map from strings to loaded rules. + * @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded envs. + * @returns {void} + */ + validate(config, source, getAdditionalRule, getAdditionalEnv) { + this.validateConfigSchema(config, source); + this.validateRules(config.rules, source, getAdditionalRule); + this.validateEnvironment(config.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + + for (const override of config.overrides || []) { + this.validateRules(override.rules, source, getAdditionalRule); + this.validateEnvironment(override.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + } + } + + /** + * Validate config array object. + * @param {ConfigArray} configArray The config array to validate. + * @returns {void} + */ + validateConfigArray(configArray) { + const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments); + const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors); + const getPluginRule = Map.prototype.get.bind(configArray.pluginRules); + + // Validate. + for (const element of configArray) { + if (validated.has(element)) { + continue; + } + validated.add(element); + + this.validateEnvironment(element.env, element.name, getPluginEnv); + this.validateGlobals(element.globals, element.name); + this.validateProcessor(element.processor, element.name, getPluginProcessor); + this.validateRules(element.rules, element.name, getPluginRule); + } + } + +} diff --git a/node_modules/@eslint/eslintrc/lib/shared/deep-merge-arrays.js b/node_modules/@eslint/eslintrc/lib/shared/deep-merge-arrays.js new file mode 100644 index 00000000..0c7ec349 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/shared/deep-merge-arrays.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Applies default rule options + * @author JoshuaKGoldberg + */ + +/** + * Check if the variable contains an object strictly rejecting arrays + * @param {unknown} value an object + * @returns {boolean} Whether value is an object + */ +function isObjectNotArray(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Deeply merges second on top of first, creating a new {} object if needed. + * @param {T} first Base, default value. + * @param {U} second User-specified value. + * @returns {T | U | (T & U)} Merged equivalent of second on top of first. + */ +function deepMergeObjects(first, second) { + if (second === void 0) { + return first; + } + + if (!isObjectNotArray(first) || !isObjectNotArray(second)) { + return second; + } + + const result = { ...first, ...second }; + + for (const key of Object.keys(second)) { + if (Object.prototype.propertyIsEnumerable.call(first, key)) { + result[key] = deepMergeObjects(first[key], second[key]); + } + } + + return result; +} + +/** + * Deeply merges second on top of first, creating a new [] array if needed. + * @param {T[] | undefined} first Base, default values. + * @param {U[] | undefined} second User-specified values. + * @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first. + */ +function deepMergeArrays(first, second) { + if (!first || !second) { + return second || first || []; + } + + return [ + ...first.map((value, i) => deepMergeObjects(value, second[i])), + ...second.slice(first.length) + ]; +} + +export { deepMergeArrays }; diff --git a/node_modules/@eslint/eslintrc/lib/shared/deprecation-warnings.js b/node_modules/@eslint/eslintrc/lib/shared/deprecation-warnings.js new file mode 100644 index 00000000..39cfe2c6 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/shared/deprecation-warnings.js @@ -0,0 +1,63 @@ +/** + * @fileoverview Provide the function that emits deprecation warnings. + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +import path from "node:path"; + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +// Defitions for deprecation warnings. +const deprecationWarningMessages = { + ESLINT_LEGACY_ECMAFEATURES: + "The 'ecmaFeatures' config file property is deprecated and has no effect.", + ESLINT_PERSONAL_CONFIG_LOAD: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please use a config file per project or the '--config' option.", + ESLINT_PERSONAL_CONFIG_SUPPRESS: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please remove it or add 'root:true' to the config files in your " + + "projects in order to avoid loading '~/.eslintrc.*' accidentally." +}; + +const sourceFileErrorCache = new Set(); + +/** + * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted + * for each unique file path, but repeated invocations with the same file path have no effect. + * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active. + * @param {string} source The name of the configuration source to report the warning for. + * @param {string} errorCode The warning message to show. + * @returns {void} + */ +function emitDeprecationWarning(source, errorCode) { + const cacheKey = JSON.stringify({ source, errorCode }); + + if (sourceFileErrorCache.has(cacheKey)) { + return; + } + sourceFileErrorCache.add(cacheKey); + + const rel = path.relative(process.cwd(), source); + const message = deprecationWarningMessages[errorCode]; + + process.emitWarning( + `${message} (found in "${rel}")`, + "DeprecationWarning", + errorCode + ); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +export { + emitDeprecationWarning +}; diff --git a/node_modules/@eslint/eslintrc/lib/shared/naming.js b/node_modules/@eslint/eslintrc/lib/shared/naming.js new file mode 100644 index 00000000..93df5fc4 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/shared/naming.js @@ -0,0 +1,96 @@ +/** + * @fileoverview Common helpers for naming of plugins, formatters and configs + */ + +const NAMESPACE_REGEX = /^@.*\//iu; + +/** + * Brings package name to correct format based on prefix + * @param {string} name The name of the package. + * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter" + * @returns {string} Normalized name of the package + * @private + */ +function normalizePackageName(name, prefix) { + let normalizedName = name; + + /** + * On Windows, name can come in with Windows slashes instead of Unix slashes. + * Normalize to Unix first to avoid errors later on. + * https://github.com/eslint/eslint/issues/5644 + */ + if (normalizedName.includes("\\")) { + normalizedName = normalizedName.replace(/\\/gu, "/"); + } + + if (normalizedName.charAt(0) === "@") { + + /** + * it's a scoped package + * package name is the prefix, or just a username + */ + const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"), + scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u"); + + if (scopedPackageShortcutRegex.test(normalizedName)) { + normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`); + } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) { + + /** + * for scoped packages, insert the prefix after the first / unless + * the path is already @scope/eslint or @scope/eslint-xxx-yyy + */ + normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`); + } + } else if (!normalizedName.startsWith(`${prefix}-`)) { + normalizedName = `${prefix}-${normalizedName}`; + } + + return normalizedName; +} + +/** + * Removes the prefix from a fullname. + * @param {string} fullname The term which may have the prefix. + * @param {string} prefix The prefix to remove. + * @returns {string} The term without prefix. + */ +function getShorthandName(fullname, prefix) { + if (fullname[0] === "@") { + let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname); + + if (matchResult) { + return matchResult[1]; + } + + matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname); + if (matchResult) { + return `${matchResult[1]}/${matchResult[2]}`; + } + } else if (fullname.startsWith(`${prefix}-`)) { + return fullname.slice(prefix.length + 1); + } + + return fullname; +} + +/** + * Gets the scope (namespace) of a term. + * @param {string} term The term which may have the namespace. + * @returns {string} The namespace of the term if it has one. + */ +function getNamespaceFromTerm(term) { + const match = term.match(NAMESPACE_REGEX); + + return match ? match[0] : ""; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +export { + normalizePackageName, + getShorthandName, + getNamespaceFromTerm +}; diff --git a/node_modules/@eslint/eslintrc/lib/shared/relative-module-resolver.js b/node_modules/@eslint/eslintrc/lib/shared/relative-module-resolver.js new file mode 100644 index 00000000..81415b42 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/shared/relative-module-resolver.js @@ -0,0 +1,43 @@ +/** + * Utility for resolving a module relative to another module + * @author Teddy Katz + */ + +import Module from "node:module"; + +/* + * `Module.createRequire` is added in v12.2.0. It supports URL as well. + * We only support the case where the argument is a filepath, not a URL. + */ +const createRequire = Module.createRequire; + +/** + * Resolves a Node module relative to another module + * @param {string} moduleName The name of a Node module, or a path to a Node module. + * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be + * a file rather than a directory, but the file need not actually exist. + * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath` + * @throws {Error} When the module cannot be resolved. + */ +function resolve(moduleName, relativeToPath) { + try { + return createRequire(relativeToPath).resolve(moduleName); + } catch (error) { + + // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future. + if ( + typeof error === "object" && + error !== null && + error.code === "MODULE_NOT_FOUND" && + !error.requireStack && + error.message.includes(moduleName) + ) { + error.message += `\nRequire stack:\n- ${relativeToPath}`; + } + throw error; + } +} + +export { + resolve +}; diff --git a/node_modules/@eslint/eslintrc/lib/shared/types.js b/node_modules/@eslint/eslintrc/lib/shared/types.js new file mode 100644 index 00000000..a32c35e3 --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/shared/types.js @@ -0,0 +1,149 @@ +/** + * @fileoverview Define common types for input completion. + * @author Toru Nagashima + */ + +/** @type {any} */ +export default {}; + +/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */ +/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */ +/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */ + +/** + * @typedef {Object} EcmaFeatures + * @property {boolean} [globalReturn] Enabling `return` statements at the top-level. + * @property {boolean} [jsx] Enabling JSX syntax. + * @property {boolean} [impliedStrict] Enabling strict mode always. + */ + +/** + * @typedef {Object} ParserOptions + * @property {EcmaFeatures} [ecmaFeatures] The optional features. + * @property {3|5|6|7|8|9|10|11|12|2015|2016|2017|2018|2019|2020|2021} [ecmaVersion] The ECMAScript version (or revision number). + * @property {"script"|"module"} [sourceType] The source code type. + */ + +/** + * @typedef {Object} ConfigData + * @property {Record} [env] The environment settings. + * @property {string | string[]} [extends] The path to other config files or the package name of shareable configs. + * @property {Record} [globals] The global variable settings. + * @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint. + * @property {boolean} [noInlineConfig] The flag that disables directive comments. + * @property {OverrideConfigData[]} [overrides] The override settings per kind of files. + * @property {string} [parser] The path to a parser or the package name of a parser. + * @property {ParserOptions} [parserOptions] The parser options. + * @property {string[]} [plugins] The plugin specifiers. + * @property {string} [processor] The processor specifier. + * @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments. + * @property {boolean} [root] The root flag. + * @property {Record} [rules] The rule settings. + * @property {Object} [settings] The shared settings. + */ + +/** + * @typedef {Object} OverrideConfigData + * @property {Record} [env] The environment settings. + * @property {string | string[]} [excludedFiles] The glob pattarns for excluded files. + * @property {string | string[]} [extends] The path to other config files or the package name of shareable configs. + * @property {string | string[]} files The glob patterns for target files. + * @property {Record} [globals] The global variable settings. + * @property {boolean} [noInlineConfig] The flag that disables directive comments. + * @property {OverrideConfigData[]} [overrides] The override settings per kind of files. + * @property {string} [parser] The path to a parser or the package name of a parser. + * @property {ParserOptions} [parserOptions] The parser options. + * @property {string[]} [plugins] The plugin specifiers. + * @property {string} [processor] The processor specifier. + * @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments. + * @property {Record} [rules] The rule settings. + * @property {Object} [settings] The shared settings. + */ + +/** + * @typedef {Object} ParseResult + * @property {Object} ast The AST. + * @property {ScopeManager} [scopeManager] The scope manager of the AST. + * @property {Record} [services] The services that the parser provides. + * @property {Record} [visitorKeys] The visitor keys of the AST. + */ + +/** + * @typedef {Object} Parser + * @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables. + * @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment. + */ + +/** + * @typedef {Object} Environment + * @property {Record} [globals] The definition of global variables. + * @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment. + */ + +/** + * @typedef {Object} LintMessage + * @property {number} column The 1-based column number. + * @property {number} [endColumn] The 1-based column number of the end location. + * @property {number} [endLine] The 1-based line number of the end location. + * @property {boolean} fatal If `true` then this is a fatal error. + * @property {{range:[number,number], text:string}} [fix] Information for autofix. + * @property {number} line The 1-based line number. + * @property {string} message The error message. + * @property {string|null} ruleId The ID of the rule which makes this message. + * @property {0|1|2} severity The severity of this message. + * @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions. + */ + +/** + * @typedef {Object} SuggestionResult + * @property {string} desc A short description. + * @property {string} [messageId] Id referencing a message for the description. + * @property {{ text: string, range: number[] }} fix fix result info + */ + +/** + * @typedef {Object} Processor + * @property {(text:string, filename:string) => Array} [preprocess] The function to extract code blocks. + * @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages. + * @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix. + */ + +/** + * @typedef {Object} RuleMetaDocs + * @property {string} category The category of the rule. + * @property {string} description The description of the rule. + * @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset. + * @property {string} url The URL of the rule documentation. + */ + +/** + * @typedef {Object} RuleMeta + * @property {boolean} [deprecated] If `true` then the rule has been deprecated. + * @property {RuleMetaDocs} docs The document information of the rule. + * @property {"code"|"whitespace"} [fixable] The autofix type. + * @property {Record} [messages] The messages the rule reports. + * @property {string[]} [replacedBy] The IDs of the alternative rules. + * @property {Array|Object} schema The option schema of the rule. + * @property {"problem"|"suggestion"|"layout"} type The rule type. + */ + +/** + * @typedef {Object} Rule + * @property {Function} create The factory of the rule. + * @property {RuleMeta} meta The meta data of the rule. + */ + +/** + * @typedef {Object} Plugin + * @property {Record} [configs] The definition of plugin configs. + * @property {Record} [environments] The definition of plugin environments. + * @property {Record} [processors] The definition of plugin processors. + * @property {Record} [rules] The definition of plugin rules. + */ + +/** + * Information of deprecated rules. + * @typedef {Object} DeprecatedRuleInfo + * @property {string} ruleId The rule ID. + * @property {string[]} replacedBy The rule IDs that replace this deprecated rule. + */ diff --git a/node_modules/@eslint/eslintrc/lib/types/index.d.ts b/node_modules/@eslint/eslintrc/lib/types/index.d.ts new file mode 100644 index 00000000..258d3a5f --- /dev/null +++ b/node_modules/@eslint/eslintrc/lib/types/index.d.ts @@ -0,0 +1,76 @@ +/** + * @fileoverview This file contains the core types for ESLint. It was initially extracted + * from the `@types/eslint__eslintrc` package. + */ + +/* + * MIT License + * Copyright (c) Microsoft Corporation. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE + */ + +import type { Linter } from "eslint"; + +/** + * A compatibility class for working with configs. + */ +export class FlatCompat { + constructor({ + baseDirectory, + resolvePluginsRelativeTo, + recommendedConfig, + allConfig, + }?: { + /** + * default: process.cwd() + */ + baseDirectory?: string; + resolvePluginsRelativeTo?: string; + recommendedConfig?: Linter.LegacyConfig; + allConfig?: Linter.LegacyConfig; + }); + + /** + * Translates an ESLintRC-style config into a flag-config-style config. + * @param eslintrcConfig The ESLintRC-style config object. + * @returns A flag-config-style config object. + */ + config(eslintrcConfig: Linter.LegacyConfig): Linter.Config[]; + + /** + * Translates the `env` section of an ESLintRC-style config. + * @param envConfig The `env` section of an ESLintRC config. + * @returns An array of flag-config objects representing the environments. + */ + env(envConfig: { [name: string]: boolean }): Linter.Config[]; + + /** + * Translates the `extends` section of an ESLintRC-style config. + * @param configsToExtend The names of the configs to load. + * @returns An array of flag-config objects representing the config. + */ + extends(...configsToExtend: string[]): Linter.Config[]; + + /** + * Translates the `plugins` section of an ESLintRC-style config. + * @param plugins The names of the plugins to load. + * @returns An array of flag-config objects representing the plugins. + */ + plugins(...plugins: string[]): Linter.Config[]; +} diff --git a/node_modules/@eslint/eslintrc/node_modules/brace-expansion/LICENSE b/node_modules/@eslint/eslintrc/node_modules/brace-expansion/LICENSE new file mode 100644 index 00000000..de322667 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@eslint/eslintrc/node_modules/brace-expansion/README.md b/node_modules/@eslint/eslintrc/node_modules/brace-expansion/README.md new file mode 100644 index 00000000..6b4e0e16 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@eslint/eslintrc/node_modules/brace-expansion/index.js b/node_modules/@eslint/eslintrc/node_modules/brace-expansion/index.js new file mode 100644 index 00000000..bd19fe68 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/@eslint/eslintrc/node_modules/brace-expansion/package.json b/node_modules/@eslint/eslintrc/node_modules/brace-expansion/package.json new file mode 100644 index 00000000..34478881 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/brace-expansion/package.json @@ -0,0 +1,50 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "1.1.12", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "publishConfig": { + "tag": "1.x" + } +} diff --git a/node_modules/@eslint/eslintrc/node_modules/ignore/LICENSE-MIT b/node_modules/@eslint/eslintrc/node_modules/ignore/LICENSE-MIT new file mode 100644 index 00000000..825533e3 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/ignore/LICENSE-MIT @@ -0,0 +1,21 @@ +Copyright (c) 2013 Kael Zhang , contributors +http://kael.me/ + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@eslint/eslintrc/node_modules/ignore/README.md b/node_modules/@eslint/eslintrc/node_modules/ignore/README.md new file mode 100644 index 00000000..50d88822 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/ignore/README.md @@ -0,0 +1,412 @@ + + + + + + + + + + + + + +
LinuxOS XWindowsCoverageDownloads
+ + Build Status + + + Windows Build Status + + + Coverage Status + + + npm module downloads per month +
+ +# ignore + +`ignore` is a manager, filter and parser which implemented in pure JavaScript according to the [.gitignore spec 2.22.1](http://git-scm.com/docs/gitignore). + +`ignore` is used by eslint, gitbook and [many others](https://www.npmjs.com/browse/depended/ignore). + +Pay **ATTENTION** that [`minimatch`](https://www.npmjs.org/package/minimatch) (which used by `fstream-ignore`) does not follow the gitignore spec. + +To filter filenames according to a .gitignore file, I recommend this npm package, `ignore`. + +To parse an `.npmignore` file, you should use `minimatch`, because an `.npmignore` file is parsed by npm using `minimatch` and it does not work in the .gitignore way. + +### Tested on + +`ignore` is fully tested, and has more than **five hundreds** of unit tests. + +- Linux + Node: `0.8` - `7.x` +- Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. + +Actually, `ignore` does not rely on any versions of node specially. + +Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). + +## Table Of Main Contents + +- [Usage](#usage) +- [`Pathname` Conventions](#pathname-conventions) +- See Also: + - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. +- [Upgrade Guide](#upgrade-guide) + +## Install + +```sh +npm i ignore +``` + +## Usage + +```js +import ignore from 'ignore' +const ig = ignore().add(['.abc/*', '!.abc/d/']) +``` + +### Filter the given paths + +```js +const paths = [ + '.abc/a.js', // filtered out + '.abc/d/e.js' // included +] + +ig.filter(paths) // ['.abc/d/e.js'] +ig.ignores('.abc/a.js') // true +``` + +### As the filter function + +```js +paths.filter(ig.createFilter()); // ['.abc/d/e.js'] +``` + +### Win32 paths will be handled + +```js +ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) +// if the code above runs on windows, the result will be +// ['.abc\\d\\e.js'] +``` + +## Why another ignore? + +- `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. + +- `ignore` only contains utility methods to filter paths according to the specified ignore rules, so + - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. + - `ignore` don't cares about sub-modules of git projects. + +- Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: + - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. + - '`**/foo`' should match '`foo`' anywhere. + - Prevent re-including a file if a parent directory of that file is excluded. + - Handle trailing whitespaces: + - `'a '`(one space) should not match `'a '`(two spaces). + - `'a \ '` matches `'a '` + - All test cases are verified with the result of `git check-ignore`. + +# Methods + +## .add(pattern: string | Ignore): this +## .add(patterns: Array): this + +- **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance +- **patterns** `Array` Array of ignore patterns. + +Adds a rule or several rules to the current manager. + +Returns `this` + +Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. + +```js +ignore().add('#abc').ignores('#abc') // false +ignore().add('\\#abc').ignores('#abc') // true +``` + +`pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: + +```js +ignore() +.add(fs.readFileSync(filenameOfGitignore).toString()) +.filter(filenames) +``` + +`pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. + +## .addIgnoreFile(path) + +REMOVED in `3.x` for now. + +To upgrade `ignore@2.x` up to `3.x`, use + +```js +import fs from 'fs' + +if (fs.existsSync(filename)) { + ignore().add(fs.readFileSync(filename).toString()) +} +``` + +instead. + +## .filter(paths: Array<Pathname>): Array<Pathname> + +```ts +type Pathname = string +``` + +Filters the given array of pathnames, and returns the filtered array. + +- **paths** `Array.` The array of `pathname`s to be filtered. + +### `Pathname` Conventions: + +#### 1. `Pathname` should be a `path.relative()`d pathname + +`Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory, + +```js +// WRONG, an error will be thrown +ig.ignores('./abc') + +// WRONG, for it will never happen, and an error will be thrown +// If the gitignore rule locates at the root directory, +// `'/abc'` should be changed to `'abc'`. +// ``` +// path.relative('/', '/abc') -> 'abc' +// ``` +ig.ignores('/abc') + +// WRONG, that it is an absolute path on Windows, an error will be thrown +ig.ignores('C:\\abc') + +// Right +ig.ignores('abc') + +// Right +ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' +``` + +In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. + +Suppose the dir structure is: + +``` +/path/to/your/repo + |-- a + | |-- a.js + | + |-- .b + | + |-- .c + |-- .DS_store +``` + +Then the `paths` might be like this: + +```js +[ + 'a/a.js' + '.b', + '.c/.DS_store' +] +``` + +#### 2. filenames and dirnames + +`node-ignore` does NO `fs.stat` during path matching, so for the example below: + +```js +// First, we add a ignore pattern to ignore a directory +ig.add('config/') + +// `ig` does NOT know if 'config', in the real world, +// is a normal file, directory or something. + +ig.ignores('config') +// `ig` treats `config` as a file, so it returns `false` + +ig.ignores('config/') +// returns `true` +``` + +Specially for people who develop some library based on `node-ignore`, it is important to understand that. + +Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: + +```js +import glob from 'glob' + +glob('**', { + // Adds a / character to directory matches. + mark: true +}, (err, files) => { + if (err) { + return console.error(err) + } + + let filtered = ignore().add(patterns).filter(files) + console.log(filtered) +}) +``` + +## .ignores(pathname: Pathname): boolean + +> new in 3.2.0 + +Returns `Boolean` whether `pathname` should be ignored. + +```js +ig.ignores('.abc/a.js') // true +``` + +## .createFilter() + +Creates a filter function which could filter an array of paths with `Array.prototype.filter`. + +Returns `function(path)` the filter function. + +## .test(pathname: Pathname) since 5.0.0 + +Returns `TestResult` + +```ts +interface TestResult { + ignored: boolean + // true if the `pathname` is finally unignored by some negative pattern + unignored: boolean +} +``` + +- `{ignored: true, unignored: false}`: the `pathname` is ignored +- `{ignored: false, unignored: true}`: the `pathname` is unignored +- `{ignored: false, unignored: false}`: the `pathname` is never matched by any ignore rules. + +## static `ignore.isPathValid(pathname): boolean` since 5.0.0 + +Check whether the `pathname` is an valid `path.relative()`d path according to the [convention](#1-pathname-should-be-a-pathrelatived-pathname). + +This method is **NOT** used to check if an ignore pattern is valid. + +```js +ignore.isPathValid('./foo') // false +``` + +## ignore(options) + +### `options.ignorecase` since 4.0.0 + +Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (the default value), otherwise case sensitive. + +```js +const ig = ignore({ + ignorecase: false +}) + +ig.add('*.png') + +ig.ignores('*.PNG') // false +``` + +### `options.ignoreCase?: boolean` since 5.2.0 + +Which is alternative to `options.ignoreCase` + +### `options.allowRelativePaths?: boolean` since 5.2.0 + +This option brings backward compatibility with projects which based on `ignore@4.x`. If `options.allowRelativePaths` is `true`, `ignore` will not check whether the given path to be tested is [`path.relative()`d](#pathname-conventions). + +However, passing a relative path, such as `'./foo'` or `'../foo'`, to test if it is ignored or not is not a good practise, which might lead to unexpected behavior + +```js +ignore({ + allowRelativePaths: true +}).ignores('../foo/bar.js') // And it will not throw +``` + +**** + +# Upgrade Guide + +## Upgrade 4.x -> 5.x + +Since `5.0.0`, if an invalid `Pathname` passed into `ig.ignores()`, an error will be thrown, unless `options.allowRelative = true` is passed to the `Ignore` factory. + +While `ignore < 5.0.0` did not make sure what the return value was, as well as + +```ts +.ignores(pathname: Pathname): boolean + +.filter(pathnames: Array): Array + +.createFilter(): (pathname: Pathname) => boolean + +.test(pathname: Pathname): {ignored: boolean, unignored: boolean} +``` + +See the convention [here](#1-pathname-should-be-a-pathrelatived-pathname) for details. + +If there are invalid pathnames, the conversion and filtration should be done by users. + +```js +import {isPathValid} from 'ignore' // introduced in 5.0.0 + +const paths = [ + // invalid + ////////////////// + '', + false, + '../foo', + '.', + ////////////////// + + // valid + 'foo' +] +.filter(isValidPath) + +ig.filter(paths) +``` + +## Upgrade 3.x -> 4.x + +Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: + +```js +var ignore = require('ignore/legacy') +``` + +## Upgrade 2.x -> 3.x + +- All `options` of 2.x are unnecessary and removed, so just remove them. +- `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. +- `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. + +**** + +# Collaborators + +- [@whitecolor](https://github.com/whitecolor) *Alex* +- [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* +- [@azproduction](https://github.com/azproduction) *Mikhail Davydov* +- [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* +- [@JanMattner](https://github.com/JanMattner) *Jan Mattner* +- [@ntwb](https://github.com/ntwb) *Stephen Edgar* +- [@kasperisager](https://github.com/kasperisager) *Kasper Isager* +- [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* diff --git a/node_modules/@eslint/eslintrc/node_modules/ignore/index.d.ts b/node_modules/@eslint/eslintrc/node_modules/ignore/index.d.ts new file mode 100644 index 00000000..970631e2 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/ignore/index.d.ts @@ -0,0 +1,61 @@ +type Pathname = string + +interface TestResult { + ignored: boolean + unignored: boolean +} + +export interface Ignore { + /** + * Adds one or several rules to the current manager. + * @param {string[]} patterns + * @returns IgnoreBase + */ + add(patterns: string | Ignore | readonly (string | Ignore)[]): this + + /** + * Filters the given array of pathnames, and returns the filtered array. + * NOTICE that each path here should be a relative path to the root of your repository. + * @param paths the array of paths to be filtered. + * @returns The filtered array of paths + */ + filter(pathnames: readonly Pathname[]): Pathname[] + + /** + * Creates a filter function which could filter + * an array of paths with Array.prototype.filter. + */ + createFilter(): (pathname: Pathname) => boolean + + /** + * Returns Boolean whether pathname should be ignored. + * @param {string} pathname a path to check + * @returns boolean + */ + ignores(pathname: Pathname): boolean + + /** + * Returns whether pathname should be ignored or unignored + * @param {string} pathname a path to check + * @returns TestResult + */ + test(pathname: Pathname): TestResult +} + +export interface Options { + ignorecase?: boolean + // For compatibility + ignoreCase?: boolean + allowRelativePaths?: boolean +} + +/** + * Creates new ignore manager. + */ +declare function ignore(options?: Options): Ignore + +declare namespace ignore { + export function isPathValid (pathname: string): boolean +} + +export default ignore diff --git a/node_modules/@eslint/eslintrc/node_modules/ignore/index.js b/node_modules/@eslint/eslintrc/node_modules/ignore/index.js new file mode 100644 index 00000000..9f0dbfeb --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/ignore/index.js @@ -0,0 +1,636 @@ +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} + +const EMPTY = '' +const SPACE = ' ' +const ESCAPE = '\\' +const REGEX_TEST_BLANK_LINE = /^\s+$/ +const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/ +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ +const REGEX_SPLITALL_CRLF = /\r?\n/g +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ + +const SLASH = '/' + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +let TMP_KEY_IGNORE = 'node-ignore' +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol.for('node-ignore') +} +const KEY_IGNORE = TMP_KEY_IGNORE + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}) + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g + +const RETURN_FALSE = () => false + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY +) + +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes + return slashes.slice(0, length - length % 2) +} + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ + + [ + // remove BOM + // TODO: + // Other similar zero-width characters? + /^\uFEFF/, + () => EMPTY + ], + + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a ) -> (a) + // (a \ ) -> (a ) + /((?:\\\\)*?)(\\?\s+)$/, + (_, m1, m2) => m1 + ( + m2.indexOf('\\') === 0 + ? SPACE + : EMPTY + ) + ], + + // replace (\ ) with ' ' + // (\ ) -> ' ' + // (\\ ) -> '\\ ' + // (\\\ ) -> '\\ ' + [ + /(\\+?)\s/g, + (_, m1) => { + const {length} = m1 + return m1.slice(0, length - length % 2) + SPACE + } + ], + + // Escape metacharacters + // which is written down by users but means special for regular expressions. + + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + match => `\\${match}` + ], + + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], + + // leading slash + [ + + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], + + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], + + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], + + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], + + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, + + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer + + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], + + // normal intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' + + // 'abc.*/' -> go + // 'abc.*' -> skip this rule, + // coz trailing single wildcard will be handed by [trailing wildcard] + /(^|[^\\]+)(\\\*)+(?=.+)/g, + + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1, p2) => { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + const unescaped = p2.replace(/\\\*/g, '[^\\/]*') + return p1 + unescaped + } + ], + + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], + + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], + + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. + + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` + : close === ']' + ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? `[${sanitizeRange(range)}${endEscape}]` + // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' + : '[]' + ], + + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, + + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' + + return `${prefix}(?=$|\\/$)` + } + ], +] + +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null) + +// @param {pattern} +const makeRegex = (pattern, ignoreCase) => { + let source = regexCache[pattern] + + if (!source) { + source = REPLACERS.reduce( + (prev, [matcher, replacer]) => + prev.replace(matcher, replacer.bind(pattern)), + pattern + ) + regexCache[pattern] = source + } + + return ignoreCase + ? new RegExp(source, 'i') + : new RegExp(source) +} + +const isString = subject => typeof subject === 'string' + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0 + +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) + +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin + this.pattern = pattern + this.negative = negative + this.regex = regex + } +} + +const createRule = (pattern, ignoreCase) => { + const origin = pattern + let negative = false + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true + pattern = pattern.substr(1) + } + + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') + + const regex = makeRegex(pattern, ignoreCase) + + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +} + +const throwError = (message, Ctor) => { + throw new Ctor(message) +} + +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d' + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + + return true +} + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + +checkPath.isNotRelative = isNotRelative +checkPath.convert = p => p + +class Ignore { + constructor ({ + ignorecase = true, + ignoreCase = ignorecase, + allowRelativePaths = false + } = {}) { + define(this, KEY_IGNORE, true) + + this._rules = [] + this._ignoreCase = ignoreCase + this._allowRelativePaths = allowRelativePaths + this._initCache() + } + + _initCache () { + this._ignoreCache = Object.create(null) + this._testCache = Object.create(null) + } + + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules) + this._added = true + return + } + + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignoreCase) + this._added = true + this._rules.push(rule) + } + } + + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false + + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this) + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache() + } + + return this + } + + // legacy + addPattern (pattern) { + return this.add(pattern) + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false + let unignored = false + + this._rules.forEach(rule => { + const {negative} = rule + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } + + const matched = rule.regex.test(path) + + if (matched) { + ignored = !negative + unignored = negative + } + }) + + return { + ignored, + unignored + } + } + + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath) + + checkPath( + path, + originalPath, + this._allowRelativePaths + ? RETURN_FALSE + : throwError + ) + + return this._t(path, cache, checkUnignored, slices) + } + + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH) + } + + slices.pop() + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ) + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } + + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + + createFilter () { + return path => !this.ignores(path) + } + + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } + + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} + +const factory = options => new Ignore(options) + +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, RETURN_FALSE) + +factory.isPathValid = isPathValid + +// Fixes typescript +factory.default = factory + +module.exports = factory + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/') + + checkPath.convert = makePosix + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path) +} diff --git a/node_modules/@eslint/eslintrc/node_modules/ignore/legacy.js b/node_modules/@eslint/eslintrc/node_modules/ignore/legacy.js new file mode 100644 index 00000000..de3f66ce --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/ignore/legacy.js @@ -0,0 +1,559 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +// A simple implementation of make-array +function makeArray(subject) { + return Array.isArray(subject) ? subject : [subject]; +} +var EMPTY = ''; +var SPACE = ' '; +var ESCAPE = '\\'; +var REGEX_TEST_BLANK_LINE = /^\s+$/; +var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/; +var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; +var REGEX_SPLITALL_CRLF = /\r?\n/g; +// /foo, +// ./foo, +// ../foo, +// . +// .. +var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; +var SLASH = '/'; + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +var TMP_KEY_IGNORE = 'node-ignore'; +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol["for"]('node-ignore'); +} +var KEY_IGNORE = TMP_KEY_IGNORE; +var define = function define(object, key, value) { + return Object.defineProperty(object, key, { + value: value + }); +}; +var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; +var RETURN_FALSE = function RETURN_FALSE() { + return false; +}; + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +var sanitizeRange = function sanitizeRange(range) { + return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) { + return from.charCodeAt(0) <= to.charCodeAt(0) ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY; + }); +}; + +// See fixtures #59 +var cleanRangeBackSlash = function cleanRangeBackSlash(slashes) { + var length = slashes.length; + return slashes.slice(0, length - length % 2); +}; + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +var REPLACERS = [[ +// remove BOM +// TODO: +// Other similar zero-width characters? +/^\uFEFF/, function () { + return EMPTY; +}], +// > Trailing spaces are ignored unless they are quoted with backslash ("\") +[ +// (a\ ) -> (a ) +// (a ) -> (a) +// (a ) -> (a) +// (a \ ) -> (a ) +/((?:\\\\)*?)(\\?\s+)$/, function (_, m1, m2) { + return m1 + (m2.indexOf('\\') === 0 ? SPACE : EMPTY); +}], +// replace (\ ) with ' ' +// (\ ) -> ' ' +// (\\ ) -> '\\ ' +// (\\\ ) -> '\\ ' +[/(\\+?)\s/g, function (_, m1) { + var length = m1.length; + return m1.slice(0, length - length % 2) + SPACE; +}], +// Escape metacharacters +// which is written down by users but means special for regular expressions. + +// > There are 12 characters with special meanings: +// > - the backslash \, +// > - the caret ^, +// > - the dollar sign $, +// > - the period or dot ., +// > - the vertical bar or pipe symbol |, +// > - the question mark ?, +// > - the asterisk or star *, +// > - the plus sign +, +// > - the opening parenthesis (, +// > - the closing parenthesis ), +// > - and the opening square bracket [, +// > - the opening curly brace {, +// > These special characters are often called "metacharacters". +[/[\\$.|*+(){^]/g, function (match) { + return "\\".concat(match); +}], [ +// > a question mark (?) matches a single character +/(?!\\)\?/g, function () { + return '[^/]'; +}], +// leading slash +[ +// > A leading slash matches the beginning of the pathname. +// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". +// A leading slash matches the beginning of the pathname +/^\//, function () { + return '^'; +}], +// replace special metacharacter slash after the leading slash +[/\//g, function () { + return '\\/'; +}], [ +// > A leading "**" followed by a slash means match in all directories. +// > For example, "**/foo" matches file or directory "foo" anywhere, +// > the same as pattern "foo". +// > "**/foo/bar" matches file or directory "bar" anywhere that is directly +// > under directory "foo". +// Notice that the '*'s have been replaced as '\\*' +/^\^*\\\*\\\*\\\//, +// '**/foo' <-> 'foo' +function () { + return '^(?:.*\\/)?'; +}], +// starting +[ +// there will be no leading '/' +// (which has been replaced by section "leading slash") +// If starts with '**', adding a '^' to the regular expression also works +/^(?=[^^])/, function startingReplacer() { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^'; +}], +// two globstars +[ +// Use lookahead assertions so that we could match more than one `'/**'` +/\\\/\\\*\\\*(?=\\\/|$)/g, +// Zero, one or several directories +// should not use '*', or it will be replaced by the next replacer + +// Check if it is not the last `'/**'` +function (_, index, str) { + return index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+'; +}], +// normal intermediate wildcards +[ +// Never replace escaped '*' +// ignore rule '\*' will match the path '*' + +// 'abc.*/' -> go +// 'abc.*' -> skip this rule, +// coz trailing single wildcard will be handed by [trailing wildcard] +/(^|[^\\]+)(\\\*)+(?=.+)/g, +// '*.js' matches '.js' +// '*.js' doesn't match 'abc' +function (_, p1, p2) { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + var unescaped = p2.replace(/\\\*/g, '[^\\/]*'); + return p1 + unescaped; +}], [ +// unescape, revert step 3 except for back slash +// For example, if a user escape a '\\*', +// after step 3, the result will be '\\\\\\*' +/\\\\\\(?=[$.|*+(){^])/g, function () { + return ESCAPE; +}], [ +// '\\\\' -> '\\' +/\\\\/g, function () { + return ESCAPE; +}], [ +// > The range notation, e.g. [a-zA-Z], +// > can be used to match one of the characters in a range. + +// `\` is escaped by step 3 +/(\\)?\[([^\]/]*?)(\\*)($|\])/g, function (match, leadEscape, range, endEscape, close) { + return leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? "\\[".concat(range).concat(cleanRangeBackSlash(endEscape)).concat(close) : close === ']' ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? "[".concat(sanitizeRange(range)).concat(endEscape, "]") // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' : '[]'; +}], +// ending +[ +// 'js' will not match 'js.' +// 'ab' will not match 'abc' +/(?:[^*])$/, +// WTF! +// https://git-scm.com/docs/gitignore +// changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) +// which re-fixes #24, #38 + +// > If there is a separator at the end of the pattern then the pattern +// > will only match directories, otherwise the pattern can match both +// > files and directories. + +// 'js*' will not match 'a.js' +// 'js/' will not match 'a.js' +// 'js' will match 'a.js' and 'a.js/' +function (match) { + return /\/$/.test(match) + // foo/ will not match 'foo' + ? "".concat(match, "$") // foo matches 'foo' and 'foo/' + : "".concat(match, "(?=$|\\/$)"); +}], +// trailing wildcard +[/(\^|\\\/)?\\\*$/, function (_, p1) { + var prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? "".concat(p1, "[^/]+") // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + return "".concat(prefix, "(?=$|\\/$)"); +}]]; + +// A simple cache, because an ignore rule only has only one certain meaning +var regexCache = Object.create(null); + +// @param {pattern} +var makeRegex = function makeRegex(pattern, ignoreCase) { + var source = regexCache[pattern]; + if (!source) { + source = REPLACERS.reduce(function (prev, _ref) { + var _ref2 = _slicedToArray(_ref, 2), + matcher = _ref2[0], + replacer = _ref2[1]; + return prev.replace(matcher, replacer.bind(pattern)); + }, pattern); + regexCache[pattern] = source; + } + return ignoreCase ? new RegExp(source, 'i') : new RegExp(source); +}; +var isString = function isString(subject) { + return typeof subject === 'string'; +}; + +// > A blank line matches no files, so it can serve as a separator for readability. +var checkPattern = function checkPattern(pattern) { + return pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0; +}; +var splitPattern = function splitPattern(pattern) { + return pattern.split(REGEX_SPLITALL_CRLF); +}; +var IgnoreRule = /*#__PURE__*/_createClass(function IgnoreRule(origin, pattern, negative, regex) { + _classCallCheck(this, IgnoreRule); + this.origin = origin; + this.pattern = pattern; + this.negative = negative; + this.regex = regex; +}); +var createRule = function createRule(pattern, ignoreCase) { + var origin = pattern; + var negative = false; + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); + var regex = makeRegex(pattern, ignoreCase); + return new IgnoreRule(origin, pattern, negative, regex); +}; +var throwError = function throwError(message, Ctor) { + throw new Ctor(message); +}; +var checkPath = function checkPath(path, originalPath, doThrow) { + if (!isString(path)) { + return doThrow("path must be a string, but got `".concat(originalPath, "`"), TypeError); + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow("path must not be empty", TypeError); + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + var r = '`path.relative()`d'; + return doThrow("path should be a ".concat(r, " string, but got \"").concat(originalPath, "\""), RangeError); + } + return true; +}; +var isNotRelative = function isNotRelative(path) { + return REGEX_TEST_INVALID_PATH.test(path); +}; +checkPath.isNotRelative = isNotRelative; +checkPath.convert = function (p) { + return p; +}; +var Ignore = /*#__PURE__*/function () { + function Ignore() { + var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref3$ignorecase = _ref3.ignorecase, + ignorecase = _ref3$ignorecase === void 0 ? true : _ref3$ignorecase, + _ref3$ignoreCase = _ref3.ignoreCase, + ignoreCase = _ref3$ignoreCase === void 0 ? ignorecase : _ref3$ignoreCase, + _ref3$allowRelativePa = _ref3.allowRelativePaths, + allowRelativePaths = _ref3$allowRelativePa === void 0 ? false : _ref3$allowRelativePa; + _classCallCheck(this, Ignore); + define(this, KEY_IGNORE, true); + this._rules = []; + this._ignoreCase = ignoreCase; + this._allowRelativePaths = allowRelativePaths; + this._initCache(); + } + _createClass(Ignore, [{ + key: "_initCache", + value: function _initCache() { + this._ignoreCache = Object.create(null); + this._testCache = Object.create(null); + } + }, { + key: "_addPattern", + value: function _addPattern(pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } + if (checkPattern(pattern)) { + var rule = createRule(pattern, this._ignoreCase); + this._added = true; + this._rules.push(rule); + } + } + + // @param {Array | string | Ignore} pattern + }, { + key: "add", + value: function add(pattern) { + this._added = false; + makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache(); + } + return this; + } + + // legacy + }, { + key: "addPattern", + value: function addPattern(pattern) { + return this.add(pattern); + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + }, { + key: "_testOne", + value: function _testOne(path, checkUnignored) { + var ignored = false; + var unignored = false; + this._rules.forEach(function (rule) { + var negative = rule.negative; + if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) { + return; + } + var matched = rule.regex.test(path); + if (matched) { + ignored = !negative; + unignored = negative; + } + }); + return { + ignored: ignored, + unignored: unignored + }; + } + + // @returns {TestResult} + }, { + key: "_test", + value: function _test(originalPath, cache, checkUnignored, slices) { + var path = originalPath + // Supports nullable path + && checkPath.convert(originalPath); + checkPath(path, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError); + return this._t(path, cache, checkUnignored, slices); + } + }, { + key: "_t", + value: function _t(path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path]; + } + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH); + } + slices.pop(); + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored); + } + var parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices); + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent : this._testOne(path, checkUnignored); + } + }, { + key: "ignores", + value: function ignores(path) { + return this._test(path, this._ignoreCache, false).ignored; + } + }, { + key: "createFilter", + value: function createFilter() { + var _this = this; + return function (path) { + return !_this.ignores(path); + }; + } + }, { + key: "filter", + value: function filter(paths) { + return makeArray(paths).filter(this.createFilter()); + } + + // @returns {TestResult} + }, { + key: "test", + value: function test(path) { + return this._test(path, this._testCache, true); + } + }]); + return Ignore; +}(); +var factory = function factory(options) { + return new Ignore(options); +}; +var isPathValid = function isPathValid(path) { + return checkPath(path && checkPath.convert(path), path, RETURN_FALSE); +}; +factory.isPathValid = isPathValid; + +// Fixes typescript +factory["default"] = factory; +module.exports = factory; + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( +// Detect `process` so that it can run in browsers. +typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) { + /* eslint no-control-regex: "off" */ + var makePosix = function makePosix(str) { + return /^\\\\\?\\/.test(str) || /[\0-\x1F"<>\|]+/.test(str) ? str : str.replace(/\\/g, '/'); + }; + checkPath.convert = makePosix; + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + var REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + checkPath.isNotRelative = function (path) { + return REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path); + }; +} diff --git a/node_modules/@eslint/eslintrc/node_modules/ignore/package.json b/node_modules/@eslint/eslintrc/node_modules/ignore/package.json new file mode 100644 index 00000000..b7f684e9 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/ignore/package.json @@ -0,0 +1,74 @@ +{ + "name": "ignore", + "version": "5.3.2", + "description": "Ignore is a manager and filter for .gitignore rules, the one used by eslint, gitbook and many others.", + "files": [ + "legacy.js", + "index.js", + "index.d.ts", + "LICENSE-MIT" + ], + "scripts": { + "prepublishOnly": "npm run build", + "build": "babel -o legacy.js index.js", + "test:lint": "eslint .", + "test:tsc": "tsc ./test/ts/simple.ts --lib ES6", + "test:ts": "node ./test/ts/simple.js", + "tap": "tap --reporter classic", + "test:git": "npm run tap test/git-check-ignore.js", + "test:ignore": "npm run tap test/ignore.js", + "test:ignore:only": "IGNORE_ONLY_IGNORES=1 npm run tap test/ignore.js", + "test:others": "npm run tap test/others.js", + "test:cases": "npm run tap test/*.js -- --coverage", + "test:no-coverage": "npm run tap test/*.js -- --no-check-coverage", + "test:only": "npm run test:lint && npm run test:tsc && npm run test:ts && npm run test:cases", + "test": "npm run test:only", + "test:win32": "IGNORE_TEST_WIN32=1 npm run test", + "report": "tap --coverage-report=html", + "posttest": "npm run report && codecov" + }, + "repository": { + "type": "git", + "url": "git@github.com:kaelzhang/node-ignore.git" + }, + "keywords": [ + "ignore", + ".gitignore", + "gitignore", + "npmignore", + "rules", + "manager", + "filter", + "regexp", + "regex", + "fnmatch", + "glob", + "asterisks", + "regular-expression" + ], + "author": "kael", + "license": "MIT", + "bugs": { + "url": "https://github.com/kaelzhang/node-ignore/issues" + }, + "devDependencies": { + "@babel/cli": "^7.22.9", + "@babel/core": "^7.22.9", + "@babel/preset-env": "^7.22.9", + "codecov": "^3.8.2", + "debug": "^4.3.4", + "eslint": "^8.46.0", + "eslint-config-ostai": "^3.0.0", + "eslint-plugin-import": "^2.28.0", + "mkdirp": "^3.0.1", + "pre-suf": "^1.1.1", + "rimraf": "^6.0.1", + "spawn-sync": "^2.0.0", + "tap": "^16.3.9", + "tmp": "0.2.3", + "typescript": "^5.1.6" + }, + "engines": { + "node": ">= 4" + } +} diff --git a/node_modules/@eslint/eslintrc/node_modules/minimatch/LICENSE b/node_modules/@eslint/eslintrc/node_modules/minimatch/LICENSE new file mode 100644 index 00000000..19129e31 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@eslint/eslintrc/node_modules/minimatch/README.md b/node_modules/@eslint/eslintrc/node_modules/minimatch/README.md new file mode 100644 index 00000000..33ede1d6 --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/minimatch/README.md @@ -0,0 +1,230 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` + +### allowWindowsEscape + +Windows path separator `\` is by default converted to `/`, which +prohibits the usage of `\` as a escape character. This flag skips that +behavior and allows using the escape character. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/@eslint/eslintrc/node_modules/minimatch/minimatch.js b/node_modules/@eslint/eslintrc/node_modules/minimatch/minimatch.js new file mode 100644 index 00000000..fda45ade --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/minimatch/minimatch.js @@ -0,0 +1,947 @@ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = (function () { try { return require('path') } catch (e) {}}()) || { + sep: '/' +} +minimatch.sep = path.sep + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + b = b || {} + var t = {} + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch + } + + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) + } + + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + } + + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) + } + + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } + + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + assertValidPattern(pattern) + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + assertValidPattern(pattern) + + if (!options) options = {} + + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + assertValidPattern(pattern) + + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } + + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + assertValidPattern(pattern) + + var options = this.options + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + /* istanbul ignore next */ + case '/': { + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + } + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '[': case '.': case '(': addPatternStart = true + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] + + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') partial = this.partial + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} diff --git a/node_modules/@eslint/eslintrc/node_modules/minimatch/package.json b/node_modules/@eslint/eslintrc/node_modules/minimatch/package.json new file mode 100644 index 00000000..566efdfe --- /dev/null +++ b/node_modules/@eslint/eslintrc/node_modules/minimatch/package.json @@ -0,0 +1,33 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "3.1.2", + "publishConfig": { + "tag": "v3-legacy" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "devDependencies": { + "tap": "^15.1.6" + }, + "license": "ISC", + "files": [ + "minimatch.js" + ] +} diff --git a/node_modules/@eslint/eslintrc/package.json b/node_modules/@eslint/eslintrc/package.json new file mode 100644 index 00000000..29a9089d --- /dev/null +++ b/node_modules/@eslint/eslintrc/package.json @@ -0,0 +1,84 @@ +{ + "name": "@eslint/eslintrc", + "version": "3.3.1", + "description": "The legacy ESLintRC config file format for ESLint", + "type": "module", + "main": "./dist/eslintrc.cjs", + "types": "./dist/eslintrc.d.cts", + "exports": { + ".": { + "import": "./lib/index.js", + "require": "./dist/eslintrc.cjs", + "types": "./lib/types/index.d.ts" + }, + "./package.json": "./package.json", + "./universal": { + "import": "./lib/index-universal.js", + "require": "./dist/eslintrc-universal.cjs" + } + }, + "files": [ + "lib", + "conf", + "LICENSE", + "dist", + "universal.js" + ], + "publishConfig": { + "access": "public" + }, + "scripts": { + "build": "rollup -c && node -e \"fs.copyFileSync('./lib/types/index.d.ts', './dist/eslintrc.d.cts')\"", + "lint": "eslint . --report-unused-disable-directives", + "lint:fix": "npm run lint -- --fix", + "prepare": "npm run build", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "mocha -R progress -c 'tests/lib/*.cjs' && c8 mocha -R progress -c 'tests/lib/**/*.js'", + "test:types": "tsc -p tests/lib/types/tsconfig.json" + }, + "repository": "eslint/eslintrc", + "funding": "https://opencollective.com/eslint", + "keywords": [ + "ESLint", + "ESLintRC", + "Configuration" + ], + "author": "Nicholas C. Zakas", + "license": "MIT", + "bugs": { + "url": "https://github.com/eslint/eslintrc/issues" + }, + "homepage": "https://github.com/eslint/eslintrc#readme", + "devDependencies": { + "c8": "^7.7.3", + "chai": "^4.3.4", + "eslint": "^9.20.1", + "eslint-config-eslint": "^11.0.0", + "eslint-release": "^3.2.0", + "fs-teardown": "^0.1.3", + "mocha": "^9.0.3", + "rollup": "^2.70.1", + "shelljs": "^0.8.5", + "sinon": "^11.1.2", + "temp-dir": "^2.0.0", + "typescript": "^5.7.3" + }, + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/node_modules/@eslint/eslintrc/universal.js b/node_modules/@eslint/eslintrc/universal.js new file mode 100644 index 00000000..2257383e --- /dev/null +++ b/node_modules/@eslint/eslintrc/universal.js @@ -0,0 +1,10 @@ +/* global module, require -- required for CJS file */ + +// Jest (and probably some other runtimes with custom implementations of +// `require`) doesn't support `exports` in `package.json`, so this file is here +// to help them load this module. Note that it is also `.js` and not `.cjs` for +// the same reason - `cjs` files requires to be loaded with an extension, but +// since Jest doesn't respect `module` outside of ESM mode it still works in +// this case (and the `require` in _this_ file does specify the extension). + +module.exports = require("./dist/eslintrc-universal.cjs"); diff --git a/node_modules/@eslint/js/LICENSE b/node_modules/@eslint/js/LICENSE new file mode 100644 index 00000000..b607bb36 --- /dev/null +++ b/node_modules/@eslint/js/LICENSE @@ -0,0 +1,19 @@ +Copyright OpenJS Foundation and other contributors, + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@eslint/js/README.md b/node_modules/@eslint/js/README.md new file mode 100644 index 00000000..f697dda7 --- /dev/null +++ b/node_modules/@eslint/js/README.md @@ -0,0 +1,69 @@ +[![npm version](https://img.shields.io/npm/v/@eslint/js.svg)](https://www.npmjs.com/package/@eslint/js) + +# ESLint JavaScript Plugin + +[Website](https://eslint.org) | [Configure ESLint](https://eslint.org/docs/latest/use/configure) | [Rules](https://eslint.org/docs/rules/) | [Contributing](https://eslint.org/docs/latest/contribute) | [Twitter](https://twitter.com/geteslint) | [Chatroom](https://eslint.org/chat) + +The beginnings of separating out JavaScript-specific functionality from ESLint. + +Right now, this plugin contains two configurations: + +- `recommended` - enables the rules recommended by the ESLint team (the replacement for `"eslint:recommended"`) +- `all` - enables all ESLint rules (the replacement for `"eslint:all"`) + +## Installation + +```shell +npm install @eslint/js -D +``` + +## Usage + +Use in your `eslint.config.js` file anytime you want to extend one of the configs: + +```js +import { defineConfig } from "eslint/config"; +import js from "@eslint/js"; + +export default defineConfig([ + // apply recommended rules to JS files + { + name: "your-project/recommended-rules", + files: ["**/*.js"], + plugins: { + js, + }, + extends: ["js/recommended"], + }, + + // apply recommended rules to JS files with an override + { + name: "your-project/recommended-rules-with-override", + files: ["**/*.js"], + plugins: { + js, + }, + extends: ["js/recommended"], + rules: { + "no-unused-vars": "warn", + }, + }, + + // apply all rules to JS files + { + name: "your-project/all-rules", + files: ["**/*.js"], + plugins: { + js, + }, + extends: ["js/all"], + rules: { + "no-unused-vars": "warn", + }, + }, +]); +``` + +## License + +MIT diff --git a/node_modules/@eslint/js/package.json b/node_modules/@eslint/js/package.json new file mode 100644 index 00000000..f366c13b --- /dev/null +++ b/node_modules/@eslint/js/package.json @@ -0,0 +1,36 @@ +{ + "name": "@eslint/js", + "version": "9.29.0", + "description": "ESLint JavaScript language implementation", + "funding": "https://eslint.org/donate", + "main": "./src/index.js", + "types": "./types/index.d.ts", + "scripts": { + "test:types": "tsc -p tests/types/tsconfig.json" + }, + "files": [ + "LICENSE", + "README.md", + "src", + "types" + ], + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/eslint.git", + "directory": "packages/js" + }, + "homepage": "https://eslint.org", + "bugs": "https://github.com/eslint/eslint/issues/", + "keywords": [ + "javascript", + "eslint-plugin", + "eslint" + ], + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/node_modules/@eslint/js/src/configs/eslint-all.js b/node_modules/@eslint/js/src/configs/eslint-all.js new file mode 100644 index 00000000..aee729eb --- /dev/null +++ b/node_modules/@eslint/js/src/configs/eslint-all.js @@ -0,0 +1,216 @@ +/* + * WARNING: This file is autogenerated using the tools/update-eslint-all.js + * script. Do not edit manually. + */ +"use strict"; + +/* + * IMPORTANT! + * + * We cannot add a "name" property to this object because it's still used in eslintrc + * which doesn't support the "name" property. If we add a "name" property, it will + * cause an error. + */ + +module.exports = Object.freeze({ + "rules": { + "accessor-pairs": "error", + "array-callback-return": "error", + "arrow-body-style": "error", + "block-scoped-var": "error", + "camelcase": "error", + "capitalized-comments": "error", + "class-methods-use-this": "error", + "complexity": "error", + "consistent-return": "error", + "consistent-this": "error", + "constructor-super": "error", + "curly": "error", + "default-case": "error", + "default-case-last": "error", + "default-param-last": "error", + "dot-notation": "error", + "eqeqeq": "error", + "for-direction": "error", + "func-name-matching": "error", + "func-names": "error", + "func-style": "error", + "getter-return": "error", + "grouped-accessor-pairs": "error", + "guard-for-in": "error", + "id-denylist": "error", + "id-length": "error", + "id-match": "error", + "init-declarations": "error", + "logical-assignment-operators": "error", + "max-classes-per-file": "error", + "max-depth": "error", + "max-lines": "error", + "max-lines-per-function": "error", + "max-nested-callbacks": "error", + "max-params": "error", + "max-statements": "error", + "new-cap": "error", + "no-alert": "error", + "no-array-constructor": "error", + "no-async-promise-executor": "error", + "no-await-in-loop": "error", + "no-bitwise": "error", + "no-caller": "error", + "no-case-declarations": "error", + "no-class-assign": "error", + "no-compare-neg-zero": "error", + "no-cond-assign": "error", + "no-console": "error", + "no-const-assign": "error", + "no-constant-binary-expression": "error", + "no-constant-condition": "error", + "no-constructor-return": "error", + "no-continue": "error", + "no-control-regex": "error", + "no-debugger": "error", + "no-delete-var": "error", + "no-div-regex": "error", + "no-dupe-args": "error", + "no-dupe-class-members": "error", + "no-dupe-else-if": "error", + "no-dupe-keys": "error", + "no-duplicate-case": "error", + "no-duplicate-imports": "error", + "no-else-return": "error", + "no-empty": "error", + "no-empty-character-class": "error", + "no-empty-function": "error", + "no-empty-pattern": "error", + "no-empty-static-block": "error", + "no-eq-null": "error", + "no-eval": "error", + "no-ex-assign": "error", + "no-extend-native": "error", + "no-extra-bind": "error", + "no-extra-boolean-cast": "error", + "no-extra-label": "error", + "no-fallthrough": "error", + "no-func-assign": "error", + "no-global-assign": "error", + "no-implicit-coercion": "error", + "no-implicit-globals": "error", + "no-implied-eval": "error", + "no-import-assign": "error", + "no-inline-comments": "error", + "no-inner-declarations": "error", + "no-invalid-regexp": "error", + "no-invalid-this": "error", + "no-irregular-whitespace": "error", + "no-iterator": "error", + "no-label-var": "error", + "no-labels": "error", + "no-lone-blocks": "error", + "no-lonely-if": "error", + "no-loop-func": "error", + "no-loss-of-precision": "error", + "no-magic-numbers": "error", + "no-misleading-character-class": "error", + "no-multi-assign": "error", + "no-multi-str": "error", + "no-negated-condition": "error", + "no-nested-ternary": "error", + "no-new": "error", + "no-new-func": "error", + "no-new-native-nonconstructor": "error", + "no-new-wrappers": "error", + "no-nonoctal-decimal-escape": "error", + "no-obj-calls": "error", + "no-object-constructor": "error", + "no-octal": "error", + "no-octal-escape": "error", + "no-param-reassign": "error", + "no-plusplus": "error", + "no-promise-executor-return": "error", + "no-proto": "error", + "no-prototype-builtins": "error", + "no-redeclare": "error", + "no-regex-spaces": "error", + "no-restricted-exports": "error", + "no-restricted-globals": "error", + "no-restricted-imports": "error", + "no-restricted-properties": "error", + "no-restricted-syntax": "error", + "no-return-assign": "error", + "no-script-url": "error", + "no-self-assign": "error", + "no-self-compare": "error", + "no-sequences": "error", + "no-setter-return": "error", + "no-shadow": "error", + "no-shadow-restricted-names": "error", + "no-sparse-arrays": "error", + "no-template-curly-in-string": "error", + "no-ternary": "error", + "no-this-before-super": "error", + "no-throw-literal": "error", + "no-unassigned-vars": "error", + "no-undef": "error", + "no-undef-init": "error", + "no-undefined": "error", + "no-underscore-dangle": "error", + "no-unexpected-multiline": "error", + "no-unmodified-loop-condition": "error", + "no-unneeded-ternary": "error", + "no-unreachable": "error", + "no-unreachable-loop": "error", + "no-unsafe-finally": "error", + "no-unsafe-negation": "error", + "no-unsafe-optional-chaining": "error", + "no-unused-expressions": "error", + "no-unused-labels": "error", + "no-unused-private-class-members": "error", + "no-unused-vars": "error", + "no-use-before-define": "error", + "no-useless-assignment": "error", + "no-useless-backreference": "error", + "no-useless-call": "error", + "no-useless-catch": "error", + "no-useless-computed-key": "error", + "no-useless-concat": "error", + "no-useless-constructor": "error", + "no-useless-escape": "error", + "no-useless-rename": "error", + "no-useless-return": "error", + "no-var": "error", + "no-void": "error", + "no-warning-comments": "error", + "no-with": "error", + "object-shorthand": "error", + "one-var": "error", + "operator-assignment": "error", + "prefer-arrow-callback": "error", + "prefer-const": "error", + "prefer-destructuring": "error", + "prefer-exponentiation-operator": "error", + "prefer-named-capture-group": "error", + "prefer-numeric-literals": "error", + "prefer-object-has-own": "error", + "prefer-object-spread": "error", + "prefer-promise-reject-errors": "error", + "prefer-regex-literals": "error", + "prefer-rest-params": "error", + "prefer-spread": "error", + "prefer-template": "error", + "radix": "error", + "require-atomic-updates": "error", + "require-await": "error", + "require-unicode-regexp": "error", + "require-yield": "error", + "sort-imports": "error", + "sort-keys": "error", + "sort-vars": "error", + "strict": "error", + "symbol-description": "error", + "unicode-bom": "error", + "use-isnan": "error", + "valid-typeof": "error", + "vars-on-top": "error", + "yoda": "error" + } +}); diff --git a/node_modules/@eslint/js/src/configs/eslint-recommended.js b/node_modules/@eslint/js/src/configs/eslint-recommended.js new file mode 100644 index 00000000..d4105c1e --- /dev/null +++ b/node_modules/@eslint/js/src/configs/eslint-recommended.js @@ -0,0 +1,83 @@ +/** + * @fileoverview Configuration applied when a user configuration extends from + * eslint:recommended. + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* eslint sort-keys: ["error", "asc"] -- Long, so make more readable */ + +/* + * IMPORTANT! + * + * We cannot add a "name" property to this object because it's still used in eslintrc + * which doesn't support the "name" property. If we add a "name" property, it will + * cause an error. + */ + +module.exports = Object.freeze({ + rules: Object.freeze({ + "constructor-super": "error", + "for-direction": "error", + "getter-return": "error", + "no-async-promise-executor": "error", + "no-case-declarations": "error", + "no-class-assign": "error", + "no-compare-neg-zero": "error", + "no-cond-assign": "error", + "no-const-assign": "error", + "no-constant-binary-expression": "error", + "no-constant-condition": "error", + "no-control-regex": "error", + "no-debugger": "error", + "no-delete-var": "error", + "no-dupe-args": "error", + "no-dupe-class-members": "error", + "no-dupe-else-if": "error", + "no-dupe-keys": "error", + "no-duplicate-case": "error", + "no-empty": "error", + "no-empty-character-class": "error", + "no-empty-pattern": "error", + "no-empty-static-block": "error", + "no-ex-assign": "error", + "no-extra-boolean-cast": "error", + "no-fallthrough": "error", + "no-func-assign": "error", + "no-global-assign": "error", + "no-import-assign": "error", + "no-invalid-regexp": "error", + "no-irregular-whitespace": "error", + "no-loss-of-precision": "error", + "no-misleading-character-class": "error", + "no-new-native-nonconstructor": "error", + "no-nonoctal-decimal-escape": "error", + "no-obj-calls": "error", + "no-octal": "error", + "no-prototype-builtins": "error", + "no-redeclare": "error", + "no-regex-spaces": "error", + "no-self-assign": "error", + "no-setter-return": "error", + "no-shadow-restricted-names": "error", + "no-sparse-arrays": "error", + "no-this-before-super": "error", + "no-undef": "error", + "no-unexpected-multiline": "error", + "no-unreachable": "error", + "no-unsafe-finally": "error", + "no-unsafe-negation": "error", + "no-unsafe-optional-chaining": "error", + "no-unused-labels": "error", + "no-unused-private-class-members": "error", + "no-unused-vars": "error", + "no-useless-backreference": "error", + "no-useless-catch": "error", + "no-useless-escape": "error", + "no-with": "error", + "require-yield": "error", + "use-isnan": "error", + "valid-typeof": "error", + }), +}); diff --git a/node_modules/@eslint/js/src/index.js b/node_modules/@eslint/js/src/index.js new file mode 100644 index 00000000..ff6a21d8 --- /dev/null +++ b/node_modules/@eslint/js/src/index.js @@ -0,0 +1,23 @@ +/** + * @fileoverview Main package entrypoint. + * @author Nicholas C. Zakas + */ + +"use strict"; + +const { name, version } = require("../package.json"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + name, + version, + }, + configs: { + all: require("./configs/eslint-all"), + recommended: require("./configs/eslint-recommended"), + }, +}; diff --git a/node_modules/@eslint/js/types/index.d.ts b/node_modules/@eslint/js/types/index.d.ts new file mode 100644 index 00000000..d4921d8b --- /dev/null +++ b/node_modules/@eslint/js/types/index.d.ts @@ -0,0 +1,14 @@ +import type { Linter } from "eslint"; + +declare const js: { + readonly meta: { + readonly name: string; + readonly version: string; + }; + readonly configs: { + readonly recommended: { readonly rules: Readonly }; + readonly all: { readonly rules: Readonly }; + }; +}; + +export = js; diff --git a/node_modules/@eslint/object-schema/LICENSE b/node_modules/@eslint/object-schema/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@eslint/object-schema/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@eslint/object-schema/README.md b/node_modules/@eslint/object-schema/README.md new file mode 100644 index 00000000..57191afb --- /dev/null +++ b/node_modules/@eslint/object-schema/README.md @@ -0,0 +1,242 @@ +# ObjectSchema Package + +## Overview + +A JavaScript object merge/validation utility where you can define a different merge and validation strategy for each key. This is helpful when you need to validate complex data structures and then merge them in a way that is more complex than `Object.assign()`. This is used in the [`@eslint/config-array`](https://npmjs.com/package/@eslint/config-array) package but can also be used on its own. + +## Installation + +For Node.js and compatible runtimes: + +```shell +npm install @eslint/object-schema +# or +yarn add @eslint/object-schema +# or +pnpm install @eslint/object-schema +# or +bun install @eslint/object-schema +``` + +For Deno: + +```shell +deno add @eslint/object-schema +``` + +## Usage + +Import the `ObjectSchema` constructor: + +```js +// using ESM +import { ObjectSchema } from "@eslint/object-schema"; + +// using CommonJS +const { ObjectSchema } = require("@eslint/object-schema"); + +const schema = new ObjectSchema({ + // define a definition for the "downloads" key + downloads: { + required: true, + merge(value1, value2) { + return value1 + value2; + }, + validate(value) { + if (typeof value !== "number") { + throw new Error("Expected downloads to be a number."); + } + }, + }, + + // define a strategy for the "versions" key + version: { + required: true, + merge(value1, value2) { + return value1.concat(value2); + }, + validate(value) { + if (!Array.isArray(value)) { + throw new Error("Expected versions to be an array."); + } + }, + }, +}); + +const record1 = { + downloads: 25, + versions: ["v1.0.0", "v1.1.0", "v1.2.0"], +}; + +const record2 = { + downloads: 125, + versions: ["v2.0.0", "v2.1.0", "v3.0.0"], +}; + +// make sure the records are valid +schema.validate(record1); +schema.validate(record2); + +// merge together (schema.merge() accepts any number of objects) +const result = schema.merge(record1, record2); + +// result looks like this: + +const result = { + downloads: 75, + versions: ["v1.0.0", "v1.1.0", "v1.2.0", "v2.0.0", "v2.1.0", "v3.0.0"], +}; +``` + +## Tips and Tricks + +### Named merge strategies + +Instead of specifying a `merge()` method, you can specify one of the following strings to use a default merge strategy: + +- `"assign"` - use `Object.assign()` to merge the two values into one object. +- `"overwrite"` - the second value always replaces the first. +- `"replace"` - the second value replaces the first if the second is not `undefined`. + +For example: + +```js +const schema = new ObjectSchema({ + name: { + merge: "replace", + validate() {}, + }, +}); +``` + +### Named validation strategies + +Instead of specifying a `validate()` method, you can specify one of the following strings to use a default validation strategy: + +- `"array"` - value must be an array. +- `"boolean"` - value must be a boolean. +- `"number"` - value must be a number. +- `"object"` - value must be an object. +- `"object?"` - value must be an object or null. +- `"string"` - value must be a string. +- `"string!"` - value must be a non-empty string. + +For example: + +```js +const schema = new ObjectSchema({ + name: { + merge: "replace", + validate: "string", + }, +}); +``` + +### Subschemas + +If you are defining a key that is, itself, an object, you can simplify the process by using a subschema. Instead of defining `merge()` and `validate()`, assign a `schema` key that contains a schema definition, like this: + +```js +const schema = new ObjectSchema({ + name: { + schema: { + first: { + merge: "replace", + validate: "string", + }, + last: { + merge: "replace", + validate: "string", + }, + }, + }, +}); + +schema.validate({ + name: { + first: "n", + last: "z", + }, +}); +``` + +### Remove Keys During Merge + +If the merge strategy for a key returns `undefined`, then the key will not appear in the final object. For example: + +```js +const schema = new ObjectSchema({ + date: { + merge() { + return undefined; + }, + validate(value) { + Date.parse(value); // throws an error when invalid + }, + }, +}); + +const object1 = { date: "5/5/2005" }; +const object2 = { date: "6/6/2006" }; + +const result = schema.merge(object1, object2); + +console.log("date" in result); // false +``` + +### Requiring Another Key Be Present + +If you'd like the presence of one key to require the presence of another key, you can use the `requires` property to specify an array of other properties that any key requires. For example: + +```js +const schema = new ObjectSchema(); + +const schema = new ObjectSchema({ + date: { + merge() { + return undefined; + }, + validate(value) { + Date.parse(value); // throws an error when invalid + }, + }, + time: { + requires: ["date"], + merge(first, second) { + return second; + }, + validate(value) { + // ... + }, + }, +}); + +// throws error: Key "time" requires keys "date" +schema.validate({ + time: "13:45", +}); +``` + +In this example, even though `date` is an optional key, it is required to be present whenever `time` is present. + +## License + +Apache 2.0 + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io

Silver Sponsors

+

SERP Triumph JetBrains Liftoff American Express

Bronze Sponsors

+

Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/@eslint/object-schema/dist/cjs/index.cjs b/node_modules/@eslint/object-schema/dist/cjs/index.cjs new file mode 100644 index 00000000..a9687a5f --- /dev/null +++ b/node_modules/@eslint/object-schema/dist/cjs/index.cjs @@ -0,0 +1,455 @@ +'use strict'; + +/** + * @fileoverview Merge Strategy + */ + +//----------------------------------------------------------------------------- +// Class +//----------------------------------------------------------------------------- + +/** + * Container class for several different merge strategies. + */ +class MergeStrategy { + /** + * Merges two keys by overwriting the first with the second. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} The second value. + */ + static overwrite(value1, value2) { + return value2; + } + + /** + * Merges two keys by replacing the first with the second only if the + * second is defined. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} The second value if it is defined. + */ + static replace(value1, value2) { + if (typeof value2 !== "undefined") { + return value2; + } + + return value1; + } + + /** + * Merges two properties by assigning properties from the second to the first. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} A new object containing properties from both value1 and + * value2. + */ + static assign(value1, value2) { + return Object.assign({}, value1, value2); + } +} + +/** + * @fileoverview Validation Strategy + */ + +//----------------------------------------------------------------------------- +// Class +//----------------------------------------------------------------------------- + +/** + * Container class for several different validation strategies. + */ +class ValidationStrategy { + /** + * Validates that a value is an array. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static array(value) { + if (!Array.isArray(value)) { + throw new TypeError("Expected an array."); + } + } + + /** + * Validates that a value is a boolean. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static boolean(value) { + if (typeof value !== "boolean") { + throw new TypeError("Expected a Boolean."); + } + } + + /** + * Validates that a value is a number. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static number(value) { + if (typeof value !== "number") { + throw new TypeError("Expected a number."); + } + } + + /** + * Validates that a value is a object. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static object(value) { + if (!value || typeof value !== "object") { + throw new TypeError("Expected an object."); + } + } + + /** + * Validates that a value is a object or null. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static "object?"(value) { + if (typeof value !== "object") { + throw new TypeError("Expected an object or null."); + } + } + + /** + * Validates that a value is a string. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static string(value) { + if (typeof value !== "string") { + throw new TypeError("Expected a string."); + } + } + + /** + * Validates that a value is a non-empty string. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static "string!"(value) { + if (typeof value !== "string" || value.length === 0) { + throw new TypeError("Expected a non-empty string."); + } + } +} + +/** + * @fileoverview Object Schema + */ + + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("./types.ts").ObjectDefinition} ObjectDefinition */ +/** @typedef {import("./types.ts").PropertyDefinition} PropertyDefinition */ + +//----------------------------------------------------------------------------- +// Private +//----------------------------------------------------------------------------- + +/** + * Validates a schema strategy. + * @param {string} name The name of the key this strategy is for. + * @param {PropertyDefinition} definition The strategy for the object key. + * @returns {void} + * @throws {Error} When the strategy is missing a name. + * @throws {Error} When the strategy is missing a merge() method. + * @throws {Error} When the strategy is missing a validate() method. + */ +function validateDefinition(name, definition) { + let hasSchema = false; + if (definition.schema) { + if (typeof definition.schema === "object") { + hasSchema = true; + } else { + throw new TypeError("Schema must be an object."); + } + } + + if (typeof definition.merge === "string") { + if (!(definition.merge in MergeStrategy)) { + throw new TypeError( + `Definition for key "${name}" missing valid merge strategy.`, + ); + } + } else if (!hasSchema && typeof definition.merge !== "function") { + throw new TypeError( + `Definition for key "${name}" must have a merge property.`, + ); + } + + if (typeof definition.validate === "string") { + if (!(definition.validate in ValidationStrategy)) { + throw new TypeError( + `Definition for key "${name}" missing valid validation strategy.`, + ); + } + } else if (!hasSchema && typeof definition.validate !== "function") { + throw new TypeError( + `Definition for key "${name}" must have a validate() method.`, + ); + } +} + +//----------------------------------------------------------------------------- +// Errors +//----------------------------------------------------------------------------- + +/** + * Error when an unexpected key is found. + */ +class UnexpectedKeyError extends Error { + /** + * Creates a new instance. + * @param {string} key The key that was unexpected. + */ + constructor(key) { + super(`Unexpected key "${key}" found.`); + } +} + +/** + * Error when a required key is missing. + */ +class MissingKeyError extends Error { + /** + * Creates a new instance. + * @param {string} key The key that was missing. + */ + constructor(key) { + super(`Missing required key "${key}".`); + } +} + +/** + * Error when a key requires other keys that are missing. + */ +class MissingDependentKeysError extends Error { + /** + * Creates a new instance. + * @param {string} key The key that was unexpected. + * @param {Array} requiredKeys The keys that are required. + */ + constructor(key, requiredKeys) { + super(`Key "${key}" requires keys "${requiredKeys.join('", "')}".`); + } +} + +/** + * Wrapper error for errors occuring during a merge or validate operation. + */ +class WrapperError extends Error { + /** + * Creates a new instance. + * @param {string} key The object key causing the error. + * @param {Error} source The source error. + */ + constructor(key, source) { + super(`Key "${key}": ${source.message}`, { cause: source }); + + // copy over custom properties that aren't represented + for (const sourceKey of Object.keys(source)) { + if (!(sourceKey in this)) { + this[sourceKey] = source[sourceKey]; + } + } + } +} + +//----------------------------------------------------------------------------- +// Main +//----------------------------------------------------------------------------- + +/** + * Represents an object validation/merging schema. + */ +class ObjectSchema { + /** + * Track all definitions in the schema by key. + * @type {Map} + */ + #definitions = new Map(); + + /** + * Separately track any keys that are required for faster validtion. + * @type {Map} + */ + #requiredKeys = new Map(); + + /** + * Creates a new instance. + * @param {ObjectDefinition} definitions The schema definitions. + */ + constructor(definitions) { + if (!definitions) { + throw new Error("Schema definitions missing."); + } + + // add in all strategies + for (const key of Object.keys(definitions)) { + validateDefinition(key, definitions[key]); + + // normalize merge and validate methods if subschema is present + if (typeof definitions[key].schema === "object") { + const schema = new ObjectSchema(definitions[key].schema); + definitions[key] = { + ...definitions[key], + merge(first = {}, second = {}) { + return schema.merge(first, second); + }, + validate(value) { + ValidationStrategy.object(value); + schema.validate(value); + }, + }; + } + + // normalize the merge method in case there's a string + if (typeof definitions[key].merge === "string") { + definitions[key] = { + ...definitions[key], + merge: MergeStrategy[ + /** @type {string} */ (definitions[key].merge) + ], + }; + } + + // normalize the validate method in case there's a string + if (typeof definitions[key].validate === "string") { + definitions[key] = { + ...definitions[key], + validate: + ValidationStrategy[ + /** @type {string} */ (definitions[key].validate) + ], + }; + } + + this.#definitions.set(key, definitions[key]); + + if (definitions[key].required) { + this.#requiredKeys.set(key, definitions[key]); + } + } + } + + /** + * Determines if a strategy has been registered for the given object key. + * @param {string} key The object key to find a strategy for. + * @returns {boolean} True if the key has a strategy registered, false if not. + */ + hasKey(key) { + return this.#definitions.has(key); + } + + /** + * Merges objects together to create a new object comprised of the keys + * of the all objects. Keys are merged based on the each key's merge + * strategy. + * @param {...Object} objects The objects to merge. + * @returns {Object} A new object with a mix of all objects' keys. + * @throws {Error} If any object is invalid. + */ + merge(...objects) { + // double check arguments + if (objects.length < 2) { + throw new TypeError("merge() requires at least two arguments."); + } + + if ( + objects.some( + object => object === null || typeof object !== "object", + ) + ) { + throw new TypeError("All arguments must be objects."); + } + + return objects.reduce((result, object) => { + this.validate(object); + + for (const [key, strategy] of this.#definitions) { + try { + if (key in result || key in object) { + const merge = /** @type {Function} */ (strategy.merge); + const value = merge.call( + this, + result[key], + object[key], + ); + if (value !== undefined) { + result[key] = value; + } + } + } catch (ex) { + throw new WrapperError(key, ex); + } + } + return result; + }, {}); + } + + /** + * Validates an object's keys based on the validate strategy for each key. + * @param {Object} object The object to validate. + * @returns {void} + * @throws {Error} When the object is invalid. + */ + validate(object) { + // check existing keys first + for (const key of Object.keys(object)) { + // check to see if the key is defined + if (!this.hasKey(key)) { + throw new UnexpectedKeyError(key); + } + + // validate existing keys + const definition = this.#definitions.get(key); + + // first check to see if any other keys are required + if (Array.isArray(definition.requires)) { + if ( + !definition.requires.every(otherKey => otherKey in object) + ) { + throw new MissingDependentKeysError( + key, + definition.requires, + ); + } + } + + // now apply remaining validation strategy + try { + const validate = /** @type {Function} */ (definition.validate); + validate.call(definition, object[key]); + } catch (ex) { + throw new WrapperError(key, ex); + } + } + + // ensure required keys aren't missing + for (const [key] of this.#requiredKeys) { + if (!(key in object)) { + throw new MissingKeyError(key); + } + } + } +} + +exports.MergeStrategy = MergeStrategy; +exports.ObjectSchema = ObjectSchema; +exports.ValidationStrategy = ValidationStrategy; diff --git a/node_modules/@eslint/object-schema/dist/cjs/index.d.cts b/node_modules/@eslint/object-schema/dist/cjs/index.d.cts new file mode 100644 index 00000000..80c2d945 --- /dev/null +++ b/node_modules/@eslint/object-schema/dist/cjs/index.d.cts @@ -0,0 +1,123 @@ +export type ObjectDefinition = import("./types.cts").ObjectDefinition; +export type PropertyDefinition = import("./types.cts").PropertyDefinition; +/** + * @fileoverview Merge Strategy + */ +/** + * Container class for several different merge strategies. + */ +export class MergeStrategy { + /** + * Merges two keys by overwriting the first with the second. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} The second value. + */ + static overwrite(value1: any, value2: any): any; + /** + * Merges two keys by replacing the first with the second only if the + * second is defined. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} The second value if it is defined. + */ + static replace(value1: any, value2: any): any; + /** + * Merges two properties by assigning properties from the second to the first. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} A new object containing properties from both value1 and + * value2. + */ + static assign(value1: any, value2: any): any; +} +/** + * Represents an object validation/merging schema. + */ +export class ObjectSchema { + /** + * Creates a new instance. + * @param {ObjectDefinition} definitions The schema definitions. + */ + constructor(definitions: ObjectDefinition); + /** + * Determines if a strategy has been registered for the given object key. + * @param {string} key The object key to find a strategy for. + * @returns {boolean} True if the key has a strategy registered, false if not. + */ + hasKey(key: string): boolean; + /** + * Merges objects together to create a new object comprised of the keys + * of the all objects. Keys are merged based on the each key's merge + * strategy. + * @param {...Object} objects The objects to merge. + * @returns {Object} A new object with a mix of all objects' keys. + * @throws {Error} If any object is invalid. + */ + merge(...objects: any[]): any; + /** + * Validates an object's keys based on the validate strategy for each key. + * @param {Object} object The object to validate. + * @returns {void} + * @throws {Error} When the object is invalid. + */ + validate(object: any): void; + #private; +} +/** + * @fileoverview Validation Strategy + */ +/** + * Container class for several different validation strategies. + */ +export class ValidationStrategy { + /** + * Validates that a value is an array. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static array(value: any): void; + /** + * Validates that a value is a boolean. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static boolean(value: any): void; + /** + * Validates that a value is a number. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static number(value: any): void; + /** + * Validates that a value is a object. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static object(value: any): void; + /** + * Validates that a value is a object or null. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static "object?"(value: any): void; + /** + * Validates that a value is a string. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static string(value: any): void; + /** + * Validates that a value is a non-empty string. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static "string!"(value: any): void; +} diff --git a/node_modules/@eslint/object-schema/dist/cjs/types.ts b/node_modules/@eslint/object-schema/dist/cjs/types.ts new file mode 100644 index 00000000..c409a6ed --- /dev/null +++ b/node_modules/@eslint/object-schema/dist/cjs/types.ts @@ -0,0 +1,57 @@ +/** + * @fileoverview Types for object-schema package. + */ + +/** + * Built-in validation strategies. + */ +export type BuiltInValidationStrategy = + | "array" + | "boolean" + | "number" + | "object" + | "object?" + | "string" + | "string!"; + +/** + * Built-in merge strategies. + */ +export type BuiltInMergeStrategy = "assign" | "overwrite" | "replace"; + +/** + * Property definition. + */ +export interface PropertyDefinition { + /** + * Indicates if the property is required. + */ + required: boolean; + + /** + * The other properties that must be present when this property is used. + */ + requires?: string[]; + + /** + * The strategy to merge the property. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/eslint/rewrite/pull/90#discussion_r1687206213 + merge: BuiltInMergeStrategy | ((target: any, source: any) => any); + + /** + * The strategy to validate the property. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/eslint/rewrite/pull/90#discussion_r1687206213 + validate: BuiltInValidationStrategy | ((value: any) => void); + + /** + * The schema for the object value of this property. + */ + schema?: ObjectDefinition; +} + +/** + * Object definition. + */ +export type ObjectDefinition = Record; diff --git a/node_modules/@eslint/object-schema/dist/esm/index.d.ts b/node_modules/@eslint/object-schema/dist/esm/index.d.ts new file mode 100644 index 00000000..0775e9a6 --- /dev/null +++ b/node_modules/@eslint/object-schema/dist/esm/index.d.ts @@ -0,0 +1,123 @@ +export type ObjectDefinition = import("./types.ts").ObjectDefinition; +export type PropertyDefinition = import("./types.ts").PropertyDefinition; +/** + * @fileoverview Merge Strategy + */ +/** + * Container class for several different merge strategies. + */ +export class MergeStrategy { + /** + * Merges two keys by overwriting the first with the second. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} The second value. + */ + static overwrite(value1: any, value2: any): any; + /** + * Merges two keys by replacing the first with the second only if the + * second is defined. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} The second value if it is defined. + */ + static replace(value1: any, value2: any): any; + /** + * Merges two properties by assigning properties from the second to the first. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} A new object containing properties from both value1 and + * value2. + */ + static assign(value1: any, value2: any): any; +} +/** + * Represents an object validation/merging schema. + */ +export class ObjectSchema { + /** + * Creates a new instance. + * @param {ObjectDefinition} definitions The schema definitions. + */ + constructor(definitions: ObjectDefinition); + /** + * Determines if a strategy has been registered for the given object key. + * @param {string} key The object key to find a strategy for. + * @returns {boolean} True if the key has a strategy registered, false if not. + */ + hasKey(key: string): boolean; + /** + * Merges objects together to create a new object comprised of the keys + * of the all objects. Keys are merged based on the each key's merge + * strategy. + * @param {...Object} objects The objects to merge. + * @returns {Object} A new object with a mix of all objects' keys. + * @throws {Error} If any object is invalid. + */ + merge(...objects: any[]): any; + /** + * Validates an object's keys based on the validate strategy for each key. + * @param {Object} object The object to validate. + * @returns {void} + * @throws {Error} When the object is invalid. + */ + validate(object: any): void; + #private; +} +/** + * @fileoverview Validation Strategy + */ +/** + * Container class for several different validation strategies. + */ +export class ValidationStrategy { + /** + * Validates that a value is an array. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static array(value: any): void; + /** + * Validates that a value is a boolean. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static boolean(value: any): void; + /** + * Validates that a value is a number. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static number(value: any): void; + /** + * Validates that a value is a object. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static object(value: any): void; + /** + * Validates that a value is a object or null. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static "object?"(value: any): void; + /** + * Validates that a value is a string. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static string(value: any): void; + /** + * Validates that a value is a non-empty string. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static "string!"(value: any): void; +} diff --git a/node_modules/@eslint/object-schema/dist/esm/index.js b/node_modules/@eslint/object-schema/dist/esm/index.js new file mode 100644 index 00000000..2e7bcd42 --- /dev/null +++ b/node_modules/@eslint/object-schema/dist/esm/index.js @@ -0,0 +1,452 @@ +// @ts-self-types="./index.d.ts" +/** + * @fileoverview Merge Strategy + */ + +//----------------------------------------------------------------------------- +// Class +//----------------------------------------------------------------------------- + +/** + * Container class for several different merge strategies. + */ +class MergeStrategy { + /** + * Merges two keys by overwriting the first with the second. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} The second value. + */ + static overwrite(value1, value2) { + return value2; + } + + /** + * Merges two keys by replacing the first with the second only if the + * second is defined. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} The second value if it is defined. + */ + static replace(value1, value2) { + if (typeof value2 !== "undefined") { + return value2; + } + + return value1; + } + + /** + * Merges two properties by assigning properties from the second to the first. + * @param {*} value1 The value from the first object key. + * @param {*} value2 The value from the second object key. + * @returns {*} A new object containing properties from both value1 and + * value2. + */ + static assign(value1, value2) { + return Object.assign({}, value1, value2); + } +} + +/** + * @fileoverview Validation Strategy + */ + +//----------------------------------------------------------------------------- +// Class +//----------------------------------------------------------------------------- + +/** + * Container class for several different validation strategies. + */ +class ValidationStrategy { + /** + * Validates that a value is an array. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static array(value) { + if (!Array.isArray(value)) { + throw new TypeError("Expected an array."); + } + } + + /** + * Validates that a value is a boolean. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static boolean(value) { + if (typeof value !== "boolean") { + throw new TypeError("Expected a Boolean."); + } + } + + /** + * Validates that a value is a number. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static number(value) { + if (typeof value !== "number") { + throw new TypeError("Expected a number."); + } + } + + /** + * Validates that a value is a object. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static object(value) { + if (!value || typeof value !== "object") { + throw new TypeError("Expected an object."); + } + } + + /** + * Validates that a value is a object or null. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static "object?"(value) { + if (typeof value !== "object") { + throw new TypeError("Expected an object or null."); + } + } + + /** + * Validates that a value is a string. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static string(value) { + if (typeof value !== "string") { + throw new TypeError("Expected a string."); + } + } + + /** + * Validates that a value is a non-empty string. + * @param {*} value The value to validate. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ + static "string!"(value) { + if (typeof value !== "string" || value.length === 0) { + throw new TypeError("Expected a non-empty string."); + } + } +} + +/** + * @fileoverview Object Schema + */ + + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("./types.ts").ObjectDefinition} ObjectDefinition */ +/** @typedef {import("./types.ts").PropertyDefinition} PropertyDefinition */ + +//----------------------------------------------------------------------------- +// Private +//----------------------------------------------------------------------------- + +/** + * Validates a schema strategy. + * @param {string} name The name of the key this strategy is for. + * @param {PropertyDefinition} definition The strategy for the object key. + * @returns {void} + * @throws {Error} When the strategy is missing a name. + * @throws {Error} When the strategy is missing a merge() method. + * @throws {Error} When the strategy is missing a validate() method. + */ +function validateDefinition(name, definition) { + let hasSchema = false; + if (definition.schema) { + if (typeof definition.schema === "object") { + hasSchema = true; + } else { + throw new TypeError("Schema must be an object."); + } + } + + if (typeof definition.merge === "string") { + if (!(definition.merge in MergeStrategy)) { + throw new TypeError( + `Definition for key "${name}" missing valid merge strategy.`, + ); + } + } else if (!hasSchema && typeof definition.merge !== "function") { + throw new TypeError( + `Definition for key "${name}" must have a merge property.`, + ); + } + + if (typeof definition.validate === "string") { + if (!(definition.validate in ValidationStrategy)) { + throw new TypeError( + `Definition for key "${name}" missing valid validation strategy.`, + ); + } + } else if (!hasSchema && typeof definition.validate !== "function") { + throw new TypeError( + `Definition for key "${name}" must have a validate() method.`, + ); + } +} + +//----------------------------------------------------------------------------- +// Errors +//----------------------------------------------------------------------------- + +/** + * Error when an unexpected key is found. + */ +class UnexpectedKeyError extends Error { + /** + * Creates a new instance. + * @param {string} key The key that was unexpected. + */ + constructor(key) { + super(`Unexpected key "${key}" found.`); + } +} + +/** + * Error when a required key is missing. + */ +class MissingKeyError extends Error { + /** + * Creates a new instance. + * @param {string} key The key that was missing. + */ + constructor(key) { + super(`Missing required key "${key}".`); + } +} + +/** + * Error when a key requires other keys that are missing. + */ +class MissingDependentKeysError extends Error { + /** + * Creates a new instance. + * @param {string} key The key that was unexpected. + * @param {Array} requiredKeys The keys that are required. + */ + constructor(key, requiredKeys) { + super(`Key "${key}" requires keys "${requiredKeys.join('", "')}".`); + } +} + +/** + * Wrapper error for errors occuring during a merge or validate operation. + */ +class WrapperError extends Error { + /** + * Creates a new instance. + * @param {string} key The object key causing the error. + * @param {Error} source The source error. + */ + constructor(key, source) { + super(`Key "${key}": ${source.message}`, { cause: source }); + + // copy over custom properties that aren't represented + for (const sourceKey of Object.keys(source)) { + if (!(sourceKey in this)) { + this[sourceKey] = source[sourceKey]; + } + } + } +} + +//----------------------------------------------------------------------------- +// Main +//----------------------------------------------------------------------------- + +/** + * Represents an object validation/merging schema. + */ +class ObjectSchema { + /** + * Track all definitions in the schema by key. + * @type {Map} + */ + #definitions = new Map(); + + /** + * Separately track any keys that are required for faster validtion. + * @type {Map} + */ + #requiredKeys = new Map(); + + /** + * Creates a new instance. + * @param {ObjectDefinition} definitions The schema definitions. + */ + constructor(definitions) { + if (!definitions) { + throw new Error("Schema definitions missing."); + } + + // add in all strategies + for (const key of Object.keys(definitions)) { + validateDefinition(key, definitions[key]); + + // normalize merge and validate methods if subschema is present + if (typeof definitions[key].schema === "object") { + const schema = new ObjectSchema(definitions[key].schema); + definitions[key] = { + ...definitions[key], + merge(first = {}, second = {}) { + return schema.merge(first, second); + }, + validate(value) { + ValidationStrategy.object(value); + schema.validate(value); + }, + }; + } + + // normalize the merge method in case there's a string + if (typeof definitions[key].merge === "string") { + definitions[key] = { + ...definitions[key], + merge: MergeStrategy[ + /** @type {string} */ (definitions[key].merge) + ], + }; + } + + // normalize the validate method in case there's a string + if (typeof definitions[key].validate === "string") { + definitions[key] = { + ...definitions[key], + validate: + ValidationStrategy[ + /** @type {string} */ (definitions[key].validate) + ], + }; + } + + this.#definitions.set(key, definitions[key]); + + if (definitions[key].required) { + this.#requiredKeys.set(key, definitions[key]); + } + } + } + + /** + * Determines if a strategy has been registered for the given object key. + * @param {string} key The object key to find a strategy for. + * @returns {boolean} True if the key has a strategy registered, false if not. + */ + hasKey(key) { + return this.#definitions.has(key); + } + + /** + * Merges objects together to create a new object comprised of the keys + * of the all objects. Keys are merged based on the each key's merge + * strategy. + * @param {...Object} objects The objects to merge. + * @returns {Object} A new object with a mix of all objects' keys. + * @throws {Error} If any object is invalid. + */ + merge(...objects) { + // double check arguments + if (objects.length < 2) { + throw new TypeError("merge() requires at least two arguments."); + } + + if ( + objects.some( + object => object === null || typeof object !== "object", + ) + ) { + throw new TypeError("All arguments must be objects."); + } + + return objects.reduce((result, object) => { + this.validate(object); + + for (const [key, strategy] of this.#definitions) { + try { + if (key in result || key in object) { + const merge = /** @type {Function} */ (strategy.merge); + const value = merge.call( + this, + result[key], + object[key], + ); + if (value !== undefined) { + result[key] = value; + } + } + } catch (ex) { + throw new WrapperError(key, ex); + } + } + return result; + }, {}); + } + + /** + * Validates an object's keys based on the validate strategy for each key. + * @param {Object} object The object to validate. + * @returns {void} + * @throws {Error} When the object is invalid. + */ + validate(object) { + // check existing keys first + for (const key of Object.keys(object)) { + // check to see if the key is defined + if (!this.hasKey(key)) { + throw new UnexpectedKeyError(key); + } + + // validate existing keys + const definition = this.#definitions.get(key); + + // first check to see if any other keys are required + if (Array.isArray(definition.requires)) { + if ( + !definition.requires.every(otherKey => otherKey in object) + ) { + throw new MissingDependentKeysError( + key, + definition.requires, + ); + } + } + + // now apply remaining validation strategy + try { + const validate = /** @type {Function} */ (definition.validate); + validate.call(definition, object[key]); + } catch (ex) { + throw new WrapperError(key, ex); + } + } + + // ensure required keys aren't missing + for (const [key] of this.#requiredKeys) { + if (!(key in object)) { + throw new MissingKeyError(key); + } + } + } +} + +export { MergeStrategy, ObjectSchema, ValidationStrategy }; diff --git a/node_modules/@eslint/object-schema/dist/esm/types.d.ts b/node_modules/@eslint/object-schema/dist/esm/types.d.ts new file mode 100644 index 00000000..5a5f9206 --- /dev/null +++ b/node_modules/@eslint/object-schema/dist/esm/types.d.ts @@ -0,0 +1,40 @@ +/** + * @fileoverview Types for object-schema package. + */ +/** + * Built-in validation strategies. + */ +export type BuiltInValidationStrategy = "array" | "boolean" | "number" | "object" | "object?" | "string" | "string!"; +/** + * Built-in merge strategies. + */ +export type BuiltInMergeStrategy = "assign" | "overwrite" | "replace"; +/** + * Property definition. + */ +export interface PropertyDefinition { + /** + * Indicates if the property is required. + */ + required: boolean; + /** + * The other properties that must be present when this property is used. + */ + requires?: string[]; + /** + * The strategy to merge the property. + */ + merge: BuiltInMergeStrategy | ((target: any, source: any) => any); + /** + * The strategy to validate the property. + */ + validate: BuiltInValidationStrategy | ((value: any) => void); + /** + * The schema for the object value of this property. + */ + schema?: ObjectDefinition; +} +/** + * Object definition. + */ +export type ObjectDefinition = Record; diff --git a/node_modules/@eslint/object-schema/dist/esm/types.ts b/node_modules/@eslint/object-schema/dist/esm/types.ts new file mode 100644 index 00000000..c409a6ed --- /dev/null +++ b/node_modules/@eslint/object-schema/dist/esm/types.ts @@ -0,0 +1,57 @@ +/** + * @fileoverview Types for object-schema package. + */ + +/** + * Built-in validation strategies. + */ +export type BuiltInValidationStrategy = + | "array" + | "boolean" + | "number" + | "object" + | "object?" + | "string" + | "string!"; + +/** + * Built-in merge strategies. + */ +export type BuiltInMergeStrategy = "assign" | "overwrite" | "replace"; + +/** + * Property definition. + */ +export interface PropertyDefinition { + /** + * Indicates if the property is required. + */ + required: boolean; + + /** + * The other properties that must be present when this property is used. + */ + requires?: string[]; + + /** + * The strategy to merge the property. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/eslint/rewrite/pull/90#discussion_r1687206213 + merge: BuiltInMergeStrategy | ((target: any, source: any) => any); + + /** + * The strategy to validate the property. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/eslint/rewrite/pull/90#discussion_r1687206213 + validate: BuiltInValidationStrategy | ((value: any) => void); + + /** + * The schema for the object value of this property. + */ + schema?: ObjectDefinition; +} + +/** + * Object definition. + */ +export type ObjectDefinition = Record; diff --git a/node_modules/@eslint/object-schema/package.json b/node_modules/@eslint/object-schema/package.json new file mode 100644 index 00000000..65a6def6 --- /dev/null +++ b/node_modules/@eslint/object-schema/package.json @@ -0,0 +1,60 @@ +{ + "name": "@eslint/object-schema", + "version": "2.1.6", + "description": "An object schema merger/validator", + "type": "module", + "main": "dist/esm/index.js", + "types": "dist/esm/index.d.ts", + "exports": { + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + }, + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + } + }, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "directories": { + "test": "tests" + }, + "scripts": { + "build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts", + "build": "rollup -c && tsc -p tsconfig.esm.json && npm run build:cts", + "test:jsr": "npx jsr@latest publish --dry-run", + "test": "mocha tests/", + "test:coverage": "c8 npm test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/rewrite.git" + }, + "keywords": [ + "object", + "validation", + "schema", + "merge" + ], + "author": "Nicholas C. Zakas", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/rewrite/issues" + }, + "homepage": "https://github.com/eslint/rewrite#readme", + "devDependencies": { + "c8": "^9.1.0", + "mocha": "^10.4.0", + "rollup": "^4.16.2", + "rollup-plugin-copy": "^3.5.0", + "typescript": "^5.4.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/node_modules/@eslint/plugin-kit/LICENSE b/node_modules/@eslint/plugin-kit/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@eslint/plugin-kit/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@eslint/plugin-kit/README.md b/node_modules/@eslint/plugin-kit/README.md new file mode 100644 index 00000000..61ac6c32 --- /dev/null +++ b/node_modules/@eslint/plugin-kit/README.md @@ -0,0 +1,272 @@ +# ESLint Plugin Kit + +## Description + +A collection of utilities to help build ESLint plugins. + +## Installation + +For Node.js and compatible runtimes: + +```shell +npm install @eslint/plugin-kit +# or +yarn add @eslint/plugin-kit +# or +pnpm install @eslint/plugin-kit +# or +bun add @eslint/plugin-kit +``` + +For Deno: + +```shell +deno add @eslint/plugin-kit +``` + +## Usage + +This package exports the following utilities: + +- [`ConfigCommentParser`](#configcommentparser) - used to parse ESLint configuration comments (i.e., `/* eslint-disable rule */`) +- [`VisitNodeStep` and `CallMethodStep`](#visitnodestep-and-callmethodstep) - used to help implement `SourceCode#traverse()` +- [`Directive`](#directive) - used to help implement `SourceCode#getDisableDirectives()` +- [`TextSourceCodeBase`](#textsourcecodebase) - base class to help implement the `SourceCode` interface + +### `ConfigCommentParser` + +To use the `ConfigCommentParser` class, import it from the package and create a new instance, such as: + +```js +import { ConfigCommentParser } from "@eslint/plugin-kit"; + +// create a new instance +const commentParser = new ConfigCommentParser(); + +// pass in a comment string without the comment delimiters +const directive = commentParser.parseDirective( + "eslint-disable prefer-const, semi -- I don't want to use these.", +); + +// will be undefined when a directive can't be parsed +if (directive) { + console.log(directive.label); // "eslint-disable" + console.log(directive.value); // "prefer-const, semi" + console.log(directive.justification); // "I don't want to use these." +} +``` + +There are different styles of directive values that you'll need to parse separately to get the correct format: + +```js +import { ConfigCommentParser } from "@eslint/plugin-kit"; + +// create a new instance +const commentParser = new ConfigCommentParser(); + +// list format +const list = commentParser.parseListConfig("prefer-const, semi"); +console.log(Object.entries(list)); // [["prefer-const", true], ["semi", true]] + +// string format +const strings = commentParser.parseStringConfig("foo:off, bar"); +console.log(Object.entries(strings)); // [["foo", "off"], ["bar", null]] + +// JSON-like config format +const jsonLike = commentParser.parseJSONLikeConfig( + "semi:[error, never], prefer-const: warn", +); +console.log(Object.entries(jsonLike.config)); // [["semi", ["error", "never"]], ["prefer-const", "warn"]] +``` + +### `VisitNodeStep` and `CallMethodStep` + +The `VisitNodeStep` and `CallMethodStep` classes represent steps in the traversal of source code. They implement the correct interfaces to return from the `SourceCode#traverse()` method. + +The `VisitNodeStep` class is the more common of the two, where you are describing a visit to a particular node during the traversal. The constructor accepts three arguments: + +- `target` - the node being visited. This is used to determine the method to call inside of a rule. For instance, if the node's type is `Literal` then ESLint will call a method named `Literal()` on the rule (if present). +- `phase` - either 1 for enter or 2 for exit. +- `args` - an array of arguments to pass into the visitor method of a rule. + +For example: + +```js +import { VisitNodeStep } from "@eslint/plugin-kit"; + +class MySourceCode { + traverse() { + const steps = []; + + for (const { node, parent, phase } of iterator(this.ast)) { + steps.push( + new VisitNodeStep({ + target: node, + phase: phase === "enter" ? 1 : 2, + args: [node, parent], + }), + ); + } + + return steps; + } +} +``` + +The `CallMethodStep` class is less common and is used to tell ESLint to call a specific method on the rule. The constructor accepts two arguments: + +- `target` - the name of the method to call, frequently beginning with `"on"` such as `"onCodePathStart"`. +- `args` - an array of arguments to pass to the method. + +For example: + +```js +import { VisitNodeStep, CallMethodStep } from "@eslint/plugin-kit"; + +class MySourceCode { + traverse() { + const steps = []; + + for (const { node, parent, phase } of iterator(this.ast)) { + steps.push( + new VisitNodeStep({ + target: node, + phase: phase === "enter" ? 1 : 2, + args: [node, parent], + }), + ); + + // call a method indicating how many times we've been through the loop + steps.push( + new CallMethodStep({ + target: "onIteration", + args: [steps.length] + }); + ) + } + + return steps; + } +} +``` + +### `Directive` + +The `Directive` class represents a disable directive in the source code and implements the `Directive` interface from `@eslint/core`. You can tell ESLint about disable directives using the `SourceCode#getDisableDirectives()` method, where part of the return value is an array of `Directive` objects. Here's an example: + +```js +import { Directive, ConfigCommentParser } from "@eslint/plugin-kit"; + +class MySourceCode { + getDisableDirectives() { + const directives = []; + const problems = []; + const commentParser = new ConfigCommentParser(); + + // read in the inline config nodes to check each one + this.getInlineConfigNodes().forEach(comment => { + // Step 1: Parse the directive + const { label, value, justification } = + commentParser.parseDirective(comment.value); + + // Step 2: Extract the directive value and create the `Directive` object + switch (label) { + case "eslint-disable": + case "eslint-enable": + case "eslint-disable-next-line": + case "eslint-disable-line": { + const directiveType = label.slice("eslint-".length); + + directives.push( + new Directive({ + type: directiveType, + node: comment, + value, + justification, + }), + ); + } + + // ignore any comments that don't begin with known labels + } + }); + + return { + directives, + problems, + }; + } +} +``` + +### `TextSourceCodeBase` + +The `TextSourceCodeBase` class is intended to be a base class that has several of the common members found in `SourceCode` objects already implemented. Those members are: + +- `lines` - an array of text lines that is created automatically when the constructor is called. +- `getLoc(node)` - gets the location of a node. Works for nodes that have the ESLint-style `loc` property and nodes that have the Unist-style [`position` property](https://github.com/syntax-tree/unist?tab=readme-ov-file#position). If you're using an AST with a different location format, you'll still need to implement this method yourself. +- `getRange(node)` - gets the range of a node within the source text. Works for nodes that have the ESLint-style `range` property and nodes that have the Unist-style [`position` property](https://github.com/syntax-tree/unist?tab=readme-ov-file#position). If you're using an AST with a different range format, you'll still need to implement this method yourself. +- `getText(nodeOrToken, charsBefore, charsAfter)` - gets the source text for the given node or token that has range information attached. Optionally, can return additional characters before and after the given node or token. As long as `getRange()` is properly implemented, this method will just work. +- `getAncestors(node)` - returns the ancestry of the node. In order for this to work, you must implement the `getParent()` method yourself. + +Here's an example: + +```js +import { TextSourceCodeBase } from "@eslint/plugin-kit"; + +export class MySourceCode extends TextSourceCodeBase { + #parents = new Map(); + + constructor({ ast, text }) { + super({ ast, text }); + } + + getParent(node) { + return this.#parents.get(node); + } + + traverse() { + const steps = []; + + for (const { node, parent, phase } of iterator(this.ast)) { + //save the parent information + this.#parent.set(node, parent); + + steps.push( + new VisitNodeStep({ + target: node, + phase: phase === "enter" ? 1 : 2, + args: [node, parent], + }), + ); + } + + return steps; + } +} +``` + +In general, it's safe to collect the parent information during the `traverse()` method as `getParent()` and `getAncestor()` will only be called from rules once the AST has been traversed at least once. + +## License + +Apache 2.0 + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/@eslint/plugin-kit/dist/cjs/index.cjs b/node_modules/@eslint/plugin-kit/dist/cjs/index.cjs new file mode 100644 index 00000000..7674a99b --- /dev/null +++ b/node_modules/@eslint/plugin-kit/dist/cjs/index.cjs @@ -0,0 +1,620 @@ +'use strict'; + +var levn = require('levn'); + +/** + * @fileoverview Config Comment Parser + * @author Nicholas C. Zakas + */ + + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").RuleConfig} RuleConfig */ +/** @typedef {import("@eslint/core").RulesConfig} RulesConfig */ +/** @typedef {import("./types.ts").StringConfig} StringConfig */ +/** @typedef {import("./types.ts").BooleanConfig} BooleanConfig */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const directivesPattern = /^([a-z]+(?:-[a-z]+)*)(?:\s|$)/u; +const validSeverities = new Set([0, 1, 2, "off", "warn", "error"]); + +/** + * Determines if the severity in the rule configuration is valid. + * @param {RuleConfig} ruleConfig A rule's configuration. + * @returns {boolean} `true` if the severity is valid, otherwise `false`. + */ +function isSeverityValid(ruleConfig) { + const severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + return validSeverities.has(severity); +} + +/** + * Determines if all severities in the rules configuration are valid. + * @param {RulesConfig} rulesConfig The rules configuration to check. + * @returns {boolean} `true` if all severities are valid, otherwise `false`. + */ +function isEverySeverityValid(rulesConfig) { + return Object.values(rulesConfig).every(isSeverityValid); +} + +/** + * Represents a directive comment. + */ +class DirectiveComment { + /** + * The label of the directive, such as "eslint", "eslint-disable", etc. + * @type {string} + */ + label = ""; + + /** + * The value of the directive (the string after the label). + * @type {string} + */ + value = ""; + + /** + * The justification of the directive (the string after the --). + * @type {string} + */ + justification = ""; + + /** + * Creates a new directive comment. + * @param {string} label The label of the directive. + * @param {string} value The value of the directive. + * @param {string} justification The justification of the directive. + */ + constructor(label, value, justification) { + this.label = label; + this.value = value; + this.justification = justification; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Object to parse ESLint configuration comments. + */ +class ConfigCommentParser { + /** + * Parses a list of "name:string_value" or/and "name" options divided by comma or + * whitespace. Used for "global" comments. + * @param {string} string The string to parse. + * @returns {StringConfig} Result map object of names and string values, or null values if no value was provided. + */ + parseStringConfig(string) { + const items = /** @type {StringConfig} */ ({}); + + // Collapse whitespace around `:` and `,` to make parsing easier + const trimmedString = string + .trim() + .replace(/(? { + if (!name) { + return; + } + + // value defaults to null (if not provided), e.g: "foo" => ["foo", null] + const [key, value = null] = name.split(":"); + + items[key] = value; + }); + + return items; + } + + /** + * Parses a JSON-like config. + * @param {string} string The string to parse. + * @returns {({ok: true, config: RulesConfig}|{ok: false, error: {message: string}})} Result map object + */ + parseJSONLikeConfig(string) { + // Parses a JSON-like comment by the same way as parsing CLI option. + try { + const items = + /** @type {RulesConfig} */ (levn.parse("Object", string)) || {}; + + /* + * When the configuration has any invalid severities, it should be completely + * ignored. This is because the configuration is not valid and should not be + * applied. + * + * For example, the following configuration is invalid: + * + * "no-alert: 2 no-console: 2" + * + * This results in a configuration of { "no-alert": "2 no-console: 2" }, which is + * not valid. In this case, the configuration should be ignored. + */ + if (isEverySeverityValid(items)) { + return { + ok: true, + config: items, + }; + } + } catch { + // levn parsing error: ignore to parse the string by a fallback. + } + + /* + * Optionator cannot parse commaless notations. + * But we are supporting that. So this is a fallback for that. + */ + const normalizedString = string + .replace(/([-a-zA-Z0-9/]+):/gu, '"$1":') + .replace(/(\]|[0-9])\s+(?=")/u, "$1,"); + + try { + const items = JSON.parse(`{${normalizedString}}`); + + return { + ok: true, + config: items, + }; + } catch (ex) { + const errorMessage = ex instanceof Error ? ex.message : String(ex); + + return { + ok: false, + error: { + message: `Failed to parse JSON from '${normalizedString}': ${errorMessage}`, + }, + }; + } + } + + /** + * Parses a config of values separated by comma. + * @param {string} string The string to parse. + * @returns {BooleanConfig} Result map of values and true values + */ + parseListConfig(string) { + const items = /** @type {BooleanConfig} */ ({}); + + string.split(",").forEach(name => { + const trimmedName = name + .trim() + .replace( + /^(?['"]?)(?.*)\k$/su, + "$", + ); + + if (trimmedName) { + items[trimmedName] = true; + } + }); + + return items; + } + + /** + * Extract the directive and the justification from a given directive comment and trim them. + * @param {string} value The comment text to extract. + * @returns {{directivePart: string, justificationPart: string}} The extracted directive and justification. + */ + #extractDirectiveComment(value) { + const match = /\s-{2,}\s/u.exec(value); + + if (!match) { + return { directivePart: value.trim(), justificationPart: "" }; + } + + const directive = value.slice(0, match.index).trim(); + const justification = value.slice(match.index + match[0].length).trim(); + + return { directivePart: directive, justificationPart: justification }; + } + + /** + * Parses a directive comment into directive text and value. + * @param {string} string The string with the directive to be parsed. + * @returns {DirectiveComment|undefined} The parsed directive or `undefined` if the directive is invalid. + */ + parseDirective(string) { + const { directivePart, justificationPart } = + this.#extractDirectiveComment(string); + const match = directivesPattern.exec(directivePart); + + if (!match) { + return undefined; + } + + const directiveText = match[1]; + const directiveValue = directivePart.slice( + match.index + directiveText.length, + ); + + return new DirectiveComment( + directiveText, + directiveValue.trim(), + justificationPart, + ); + } +} + +/** + * @fileoverview A collection of helper classes for implementing `SourceCode`. + * @author Nicholas C. Zakas + */ + +/* eslint class-methods-use-this: off -- Required to complete interface. */ + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").VisitTraversalStep} VisitTraversalStep */ +/** @typedef {import("@eslint/core").CallTraversalStep} CallTraversalStep */ +/** @typedef {import("@eslint/core").TraversalStep} TraversalStep */ +/** @typedef {import("@eslint/core").SourceLocation} SourceLocation */ +/** @typedef {import("@eslint/core").SourceLocationWithOffset} SourceLocationWithOffset */ +/** @typedef {import("@eslint/core").SourceRange} SourceRange */ +/** @typedef {import("@eslint/core").Directive} IDirective */ +/** @typedef {import("@eslint/core").DirectiveType} DirectiveType */ +/** @typedef {import("@eslint/core").SourceCodeBaseTypeOptions} SourceCodeBaseTypeOptions */ +/** + * @typedef {import("@eslint/core").TextSourceCode} TextSourceCode + * @template {SourceCodeBaseTypeOptions} [Options=SourceCodeBaseTypeOptions] + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Determines if a node has ESTree-style loc information. + * @param {object} node The node to check. + * @returns {node is {loc:SourceLocation}} `true` if the node has ESTree-style loc information, `false` if not. + */ +function hasESTreeStyleLoc(node) { + return "loc" in node; +} + +/** + * Determines if a node has position-style loc information. + * @param {object} node The node to check. + * @returns {node is {position:SourceLocation}} `true` if the node has position-style range information, `false` if not. + */ +function hasPosStyleLoc(node) { + return "position" in node; +} + +/** + * Determines if a node has ESTree-style range information. + * @param {object} node The node to check. + * @returns {node is {range:SourceRange}} `true` if the node has ESTree-style range information, `false` if not. + */ +function hasESTreeStyleRange(node) { + return "range" in node; +} + +/** + * Determines if a node has position-style range information. + * @param {object} node The node to check. + * @returns {node is {position:SourceLocationWithOffset}} `true` if the node has position-style range information, `false` if not. + */ +function hasPosStyleRange(node) { + return "position" in node; +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class to represent a step in the traversal process where a node is visited. + * @implements {VisitTraversalStep} + */ +class VisitNodeStep { + /** + * The type of the step. + * @type {"visit"} + * @readonly + */ + type = "visit"; + + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {1} + * @readonly + */ + kind = 1; + + /** + * The target of the step. + * @type {object} + */ + target; + + /** + * The phase of the step. + * @type {1|2} + */ + phase; + + /** + * The arguments of the step. + * @type {Array} + */ + args; + + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {object} options.target The target of the step. + * @param {1|2} options.phase The phase of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, phase, args }) { + this.target = target; + this.phase = phase; + this.args = args; + } +} + +/** + * A class to represent a step in the traversal process where a + * method is called. + * @implements {CallTraversalStep} + */ +class CallMethodStep { + /** + * The type of the step. + * @type {"call"} + * @readonly + */ + type = "call"; + + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {2} + * @readonly + */ + kind = 2; + + /** + * The name of the method to call. + * @type {string} + */ + target; + + /** + * The arguments to pass to the method. + * @type {Array} + */ + args; + + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {string} options.target The target of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, args }) { + this.target = target; + this.args = args; + } +} + +/** + * A class to represent a directive comment. + * @implements {IDirective} + */ +class Directive { + /** + * The type of directive. + * @type {DirectiveType} + * @readonly + */ + type; + + /** + * The node representing the directive. + * @type {unknown} + * @readonly + */ + node; + + /** + * Everything after the "eslint-disable" portion of the directive, + * but before the "--" that indicates the justification. + * @type {string} + * @readonly + */ + value; + + /** + * The justification for the directive. + * @type {string} + * @readonly + */ + justification; + + /** + * Creates a new instance. + * @param {Object} options The options for the directive. + * @param {"disable"|"enable"|"disable-next-line"|"disable-line"} options.type The type of directive. + * @param {unknown} options.node The node representing the directive. + * @param {string} options.value The value of the directive. + * @param {string} options.justification The justification for the directive. + */ + constructor({ type, node, value, justification }) { + this.type = type; + this.node = node; + this.value = value; + this.justification = justification; + } +} + +/** + * Source Code Base Object + * @template {SourceCodeBaseTypeOptions & {SyntaxElementWithLoc: object}} [Options=SourceCodeBaseTypeOptions & {SyntaxElementWithLoc: object}] + * @implements {TextSourceCode} + */ +class TextSourceCodeBase { + /** + * The lines of text in the source code. + * @type {Array} + */ + #lines; + + /** + * The AST of the source code. + * @type {Options['RootNode']} + */ + ast; + + /** + * The text of the source code. + * @type {string} + */ + text; + + /** + * Creates a new instance. + * @param {Object} options The options for the instance. + * @param {string} options.text The source code text. + * @param {Options['RootNode']} options.ast The root AST node. + * @param {RegExp} [options.lineEndingPattern] The pattern to match lineEndings in the source code. + */ + constructor({ text, ast, lineEndingPattern = /\r?\n/u }) { + this.ast = ast; + this.text = text; + this.#lines = text.split(lineEndingPattern); + } + + /** + * Returns the loc information for the given node or token. + * @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the loc information for. + * @returns {SourceLocation} The loc information for the node or token. + * @throws {Error} If the node or token does not have loc information. + */ + getLoc(nodeOrToken) { + if (hasESTreeStyleLoc(nodeOrToken)) { + return nodeOrToken.loc; + } + + if (hasPosStyleLoc(nodeOrToken)) { + return nodeOrToken.position; + } + + throw new Error( + "Custom getLoc() method must be implemented in the subclass.", + ); + } + + /** + * Returns the range information for the given node or token. + * @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the range information for. + * @returns {SourceRange} The range information for the node or token. + * @throws {Error} If the node or token does not have range information. + */ + getRange(nodeOrToken) { + if (hasESTreeStyleRange(nodeOrToken)) { + return nodeOrToken.range; + } + + if (hasPosStyleRange(nodeOrToken)) { + return [ + nodeOrToken.position.start.offset, + nodeOrToken.position.end.offset, + ]; + } + + throw new Error( + "Custom getRange() method must be implemented in the subclass.", + ); + } + + /* eslint-disable no-unused-vars -- Required to complete interface. */ + /** + * Returns the parent of the given node. + * @param {Options['SyntaxElementWithLoc']} node The node to get the parent of. + * @returns {Options['SyntaxElementWithLoc']|undefined} The parent of the node. + * @throws {Error} If the method is not implemented in the subclass. + */ + getParent(node) { + throw new Error("Not implemented."); + } + /* eslint-enable no-unused-vars -- Required to complete interface. */ + + /** + * Gets all the ancestors of a given node + * @param {Options['SyntaxElementWithLoc']} node The node + * @returns {Array} All the ancestor nodes in the AST, not including the provided node, starting + * from the root node at index 0 and going inwards to the parent node. + * @throws {TypeError} When `node` is missing. + */ + getAncestors(node) { + if (!node) { + throw new TypeError("Missing required argument: node."); + } + + const ancestorsStartingAtParent = []; + + for ( + let ancestor = this.getParent(node); + ancestor; + ancestor = this.getParent(ancestor) + ) { + ancestorsStartingAtParent.push(ancestor); + } + + return ancestorsStartingAtParent.reverse(); + } + + /** + * Gets the source code for the given node. + * @param {Options['SyntaxElementWithLoc']} [node] The AST node to get the text for. + * @param {number} [beforeCount] The number of characters before the node to retrieve. + * @param {number} [afterCount] The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + * @public + */ + getText(node, beforeCount, afterCount) { + if (node) { + const range = this.getRange(node); + return this.text.slice( + Math.max(range[0] - (beforeCount || 0), 0), + range[1] + (afterCount || 0), + ); + } + return this.text; + } + + /** + * Gets the entire source text split into an array of lines. + * @returns {Array} The source text as an array of lines. + * @public + */ + get lines() { + return this.#lines; + } + + /** + * Traverse the source code and return the steps that were taken. + * @returns {Iterable} The steps that were taken while traversing the source code. + */ + traverse() { + throw new Error("Not implemented."); + } +} + +exports.CallMethodStep = CallMethodStep; +exports.ConfigCommentParser = ConfigCommentParser; +exports.Directive = Directive; +exports.TextSourceCodeBase = TextSourceCodeBase; +exports.VisitNodeStep = VisitNodeStep; diff --git a/node_modules/@eslint/plugin-kit/dist/cjs/index.d.cts b/node_modules/@eslint/plugin-kit/dist/cjs/index.d.cts new file mode 100644 index 00000000..9920229d --- /dev/null +++ b/node_modules/@eslint/plugin-kit/dist/cjs/index.d.cts @@ -0,0 +1,298 @@ +export type VisitTraversalStep = import("@eslint/core").VisitTraversalStep; +export type CallTraversalStep = import("@eslint/core").CallTraversalStep; +export type TraversalStep = import("@eslint/core").TraversalStep; +export type SourceLocation = import("@eslint/core").SourceLocation; +export type SourceLocationWithOffset = import("@eslint/core").SourceLocationWithOffset; +export type SourceRange = import("@eslint/core").SourceRange; +export type IDirective = import("@eslint/core").Directive; +export type DirectiveType = import("@eslint/core").DirectiveType; +export type SourceCodeBaseTypeOptions = import("@eslint/core").SourceCodeBaseTypeOptions; +/** + * + */ +export type TextSourceCode = import("@eslint/core").TextSourceCode; +export type RuleConfig = import("@eslint/core").RuleConfig; +export type RulesConfig = import("@eslint/core").RulesConfig; +export type StringConfig = import("./types.cts").StringConfig; +export type BooleanConfig = import("./types.cts").BooleanConfig; +/** + * A class to represent a step in the traversal process where a + * method is called. + * @implements {CallTraversalStep} + */ +export class CallMethodStep implements CallTraversalStep { + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {string} options.target The target of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, args }: { + target: string; + args: Array; + }); + /** + * The type of the step. + * @type {"call"} + * @readonly + */ + readonly type: "call"; + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {2} + * @readonly + */ + readonly kind: 2; + /** + * The name of the method to call. + * @type {string} + */ + target: string; + /** + * The arguments to pass to the method. + * @type {Array} + */ + args: Array; +} +/** + * Object to parse ESLint configuration comments. + */ +export class ConfigCommentParser { + /** + * Parses a list of "name:string_value" or/and "name" options divided by comma or + * whitespace. Used for "global" comments. + * @param {string} string The string to parse. + * @returns {StringConfig} Result map object of names and string values, or null values if no value was provided. + */ + parseStringConfig(string: string): StringConfig; + /** + * Parses a JSON-like config. + * @param {string} string The string to parse. + * @returns {({ok: true, config: RulesConfig}|{ok: false, error: {message: string}})} Result map object + */ + parseJSONLikeConfig(string: string): ({ + ok: true; + config: RulesConfig; + } | { + ok: false; + error: { + message: string; + }; + }); + /** + * Parses a config of values separated by comma. + * @param {string} string The string to parse. + * @returns {BooleanConfig} Result map of values and true values + */ + parseListConfig(string: string): BooleanConfig; + /** + * Parses a directive comment into directive text and value. + * @param {string} string The string with the directive to be parsed. + * @returns {DirectiveComment|undefined} The parsed directive or `undefined` if the directive is invalid. + */ + parseDirective(string: string): DirectiveComment | undefined; + #private; +} +/** + * A class to represent a directive comment. + * @implements {IDirective} + */ +export class Directive implements IDirective { + /** + * Creates a new instance. + * @param {Object} options The options for the directive. + * @param {"disable"|"enable"|"disable-next-line"|"disable-line"} options.type The type of directive. + * @param {unknown} options.node The node representing the directive. + * @param {string} options.value The value of the directive. + * @param {string} options.justification The justification for the directive. + */ + constructor({ type, node, value, justification }: { + type: "disable" | "enable" | "disable-next-line" | "disable-line"; + node: unknown; + value: string; + justification: string; + }); + /** + * The type of directive. + * @type {DirectiveType} + * @readonly + */ + readonly type: DirectiveType; + /** + * The node representing the directive. + * @type {unknown} + * @readonly + */ + readonly node: unknown; + /** + * Everything after the "eslint-disable" portion of the directive, + * but before the "--" that indicates the justification. + * @type {string} + * @readonly + */ + readonly value: string; + /** + * The justification for the directive. + * @type {string} + * @readonly + */ + readonly justification: string; +} +/** + * Source Code Base Object + * @template {SourceCodeBaseTypeOptions & {SyntaxElementWithLoc: object}} [Options=SourceCodeBaseTypeOptions & {SyntaxElementWithLoc: object}] + * @implements {TextSourceCode} + */ +export class TextSourceCodeBase implements TextSourceCode { + /** + * Creates a new instance. + * @param {Object} options The options for the instance. + * @param {string} options.text The source code text. + * @param {Options['RootNode']} options.ast The root AST node. + * @param {RegExp} [options.lineEndingPattern] The pattern to match lineEndings in the source code. + */ + constructor({ text, ast, lineEndingPattern }: { + text: string; + ast: Options["RootNode"]; + lineEndingPattern?: RegExp; + }); + /** + * The AST of the source code. + * @type {Options['RootNode']} + */ + ast: Options["RootNode"]; + /** + * The text of the source code. + * @type {string} + */ + text: string; + /** + * Returns the loc information for the given node or token. + * @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the loc information for. + * @returns {SourceLocation} The loc information for the node or token. + * @throws {Error} If the node or token does not have loc information. + */ + getLoc(nodeOrToken: Options["SyntaxElementWithLoc"]): SourceLocation; + /** + * Returns the range information for the given node or token. + * @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the range information for. + * @returns {SourceRange} The range information for the node or token. + * @throws {Error} If the node or token does not have range information. + */ + getRange(nodeOrToken: Options["SyntaxElementWithLoc"]): SourceRange; + /** + * Returns the parent of the given node. + * @param {Options['SyntaxElementWithLoc']} node The node to get the parent of. + * @returns {Options['SyntaxElementWithLoc']|undefined} The parent of the node. + * @throws {Error} If the method is not implemented in the subclass. + */ + getParent(node: Options["SyntaxElementWithLoc"]): Options["SyntaxElementWithLoc"] | undefined; + /** + * Gets all the ancestors of a given node + * @param {Options['SyntaxElementWithLoc']} node The node + * @returns {Array} All the ancestor nodes in the AST, not including the provided node, starting + * from the root node at index 0 and going inwards to the parent node. + * @throws {TypeError} When `node` is missing. + */ + getAncestors(node: Options["SyntaxElementWithLoc"]): Array; + /** + * Gets the source code for the given node. + * @param {Options['SyntaxElementWithLoc']} [node] The AST node to get the text for. + * @param {number} [beforeCount] The number of characters before the node to retrieve. + * @param {number} [afterCount] The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + * @public + */ + public getText(node?: Options["SyntaxElementWithLoc"], beforeCount?: number, afterCount?: number): string; + /** + * Gets the entire source text split into an array of lines. + * @returns {Array} The source text as an array of lines. + * @public + */ + public get lines(): Array; + /** + * Traverse the source code and return the steps that were taken. + * @returns {Iterable} The steps that were taken while traversing the source code. + */ + traverse(): Iterable; + #private; +} +/** + * A class to represent a step in the traversal process where a node is visited. + * @implements {VisitTraversalStep} + */ +export class VisitNodeStep implements VisitTraversalStep { + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {object} options.target The target of the step. + * @param {1|2} options.phase The phase of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, phase, args }: { + target: object; + phase: 1 | 2; + args: Array; + }); + /** + * The type of the step. + * @type {"visit"} + * @readonly + */ + readonly type: "visit"; + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {1} + * @readonly + */ + readonly kind: 1; + /** + * The target of the step. + * @type {object} + */ + target: object; + /** + * The phase of the step. + * @type {1|2} + */ + phase: 1 | 2; + /** + * The arguments of the step. + * @type {Array} + */ + args: Array; +} +/** + * Represents a directive comment. + */ +declare class DirectiveComment { + /** + * Creates a new directive comment. + * @param {string} label The label of the directive. + * @param {string} value The value of the directive. + * @param {string} justification The justification of the directive. + */ + constructor(label: string, value: string, justification: string); + /** + * The label of the directive, such as "eslint", "eslint-disable", etc. + * @type {string} + */ + label: string; + /** + * The value of the directive (the string after the label). + * @type {string} + */ + value: string; + /** + * The justification of the directive (the string after the --). + * @type {string} + */ + justification: string; +} +export {}; diff --git a/node_modules/@eslint/plugin-kit/dist/cjs/types.cts b/node_modules/@eslint/plugin-kit/dist/cjs/types.cts new file mode 100644 index 00000000..d3f6a888 --- /dev/null +++ b/node_modules/@eslint/plugin-kit/dist/cjs/types.cts @@ -0,0 +1,7 @@ +/** + * @fileoverview Types for the plugin-kit package. + * @author Nicholas C. Zakas + */ + +export type StringConfig = Record; +export type BooleanConfig = Record; diff --git a/node_modules/@eslint/plugin-kit/dist/esm/index.d.ts b/node_modules/@eslint/plugin-kit/dist/esm/index.d.ts new file mode 100644 index 00000000..bce5cdb8 --- /dev/null +++ b/node_modules/@eslint/plugin-kit/dist/esm/index.d.ts @@ -0,0 +1,298 @@ +export type VisitTraversalStep = import("@eslint/core").VisitTraversalStep; +export type CallTraversalStep = import("@eslint/core").CallTraversalStep; +export type TraversalStep = import("@eslint/core").TraversalStep; +export type SourceLocation = import("@eslint/core").SourceLocation; +export type SourceLocationWithOffset = import("@eslint/core").SourceLocationWithOffset; +export type SourceRange = import("@eslint/core").SourceRange; +export type IDirective = import("@eslint/core").Directive; +export type DirectiveType = import("@eslint/core").DirectiveType; +export type SourceCodeBaseTypeOptions = import("@eslint/core").SourceCodeBaseTypeOptions; +/** + * + */ +export type TextSourceCode = import("@eslint/core").TextSourceCode; +export type RuleConfig = import("@eslint/core").RuleConfig; +export type RulesConfig = import("@eslint/core").RulesConfig; +export type StringConfig = import("./types.ts").StringConfig; +export type BooleanConfig = import("./types.ts").BooleanConfig; +/** + * A class to represent a step in the traversal process where a + * method is called. + * @implements {CallTraversalStep} + */ +export class CallMethodStep implements CallTraversalStep { + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {string} options.target The target of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, args }: { + target: string; + args: Array; + }); + /** + * The type of the step. + * @type {"call"} + * @readonly + */ + readonly type: "call"; + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {2} + * @readonly + */ + readonly kind: 2; + /** + * The name of the method to call. + * @type {string} + */ + target: string; + /** + * The arguments to pass to the method. + * @type {Array} + */ + args: Array; +} +/** + * Object to parse ESLint configuration comments. + */ +export class ConfigCommentParser { + /** + * Parses a list of "name:string_value" or/and "name" options divided by comma or + * whitespace. Used for "global" comments. + * @param {string} string The string to parse. + * @returns {StringConfig} Result map object of names and string values, or null values if no value was provided. + */ + parseStringConfig(string: string): StringConfig; + /** + * Parses a JSON-like config. + * @param {string} string The string to parse. + * @returns {({ok: true, config: RulesConfig}|{ok: false, error: {message: string}})} Result map object + */ + parseJSONLikeConfig(string: string): ({ + ok: true; + config: RulesConfig; + } | { + ok: false; + error: { + message: string; + }; + }); + /** + * Parses a config of values separated by comma. + * @param {string} string The string to parse. + * @returns {BooleanConfig} Result map of values and true values + */ + parseListConfig(string: string): BooleanConfig; + /** + * Parses a directive comment into directive text and value. + * @param {string} string The string with the directive to be parsed. + * @returns {DirectiveComment|undefined} The parsed directive or `undefined` if the directive is invalid. + */ + parseDirective(string: string): DirectiveComment | undefined; + #private; +} +/** + * A class to represent a directive comment. + * @implements {IDirective} + */ +export class Directive implements IDirective { + /** + * Creates a new instance. + * @param {Object} options The options for the directive. + * @param {"disable"|"enable"|"disable-next-line"|"disable-line"} options.type The type of directive. + * @param {unknown} options.node The node representing the directive. + * @param {string} options.value The value of the directive. + * @param {string} options.justification The justification for the directive. + */ + constructor({ type, node, value, justification }: { + type: "disable" | "enable" | "disable-next-line" | "disable-line"; + node: unknown; + value: string; + justification: string; + }); + /** + * The type of directive. + * @type {DirectiveType} + * @readonly + */ + readonly type: DirectiveType; + /** + * The node representing the directive. + * @type {unknown} + * @readonly + */ + readonly node: unknown; + /** + * Everything after the "eslint-disable" portion of the directive, + * but before the "--" that indicates the justification. + * @type {string} + * @readonly + */ + readonly value: string; + /** + * The justification for the directive. + * @type {string} + * @readonly + */ + readonly justification: string; +} +/** + * Source Code Base Object + * @template {SourceCodeBaseTypeOptions & {SyntaxElementWithLoc: object}} [Options=SourceCodeBaseTypeOptions & {SyntaxElementWithLoc: object}] + * @implements {TextSourceCode} + */ +export class TextSourceCodeBase implements TextSourceCode { + /** + * Creates a new instance. + * @param {Object} options The options for the instance. + * @param {string} options.text The source code text. + * @param {Options['RootNode']} options.ast The root AST node. + * @param {RegExp} [options.lineEndingPattern] The pattern to match lineEndings in the source code. + */ + constructor({ text, ast, lineEndingPattern }: { + text: string; + ast: Options["RootNode"]; + lineEndingPattern?: RegExp; + }); + /** + * The AST of the source code. + * @type {Options['RootNode']} + */ + ast: Options["RootNode"]; + /** + * The text of the source code. + * @type {string} + */ + text: string; + /** + * Returns the loc information for the given node or token. + * @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the loc information for. + * @returns {SourceLocation} The loc information for the node or token. + * @throws {Error} If the node or token does not have loc information. + */ + getLoc(nodeOrToken: Options["SyntaxElementWithLoc"]): SourceLocation; + /** + * Returns the range information for the given node or token. + * @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the range information for. + * @returns {SourceRange} The range information for the node or token. + * @throws {Error} If the node or token does not have range information. + */ + getRange(nodeOrToken: Options["SyntaxElementWithLoc"]): SourceRange; + /** + * Returns the parent of the given node. + * @param {Options['SyntaxElementWithLoc']} node The node to get the parent of. + * @returns {Options['SyntaxElementWithLoc']|undefined} The parent of the node. + * @throws {Error} If the method is not implemented in the subclass. + */ + getParent(node: Options["SyntaxElementWithLoc"]): Options["SyntaxElementWithLoc"] | undefined; + /** + * Gets all the ancestors of a given node + * @param {Options['SyntaxElementWithLoc']} node The node + * @returns {Array} All the ancestor nodes in the AST, not including the provided node, starting + * from the root node at index 0 and going inwards to the parent node. + * @throws {TypeError} When `node` is missing. + */ + getAncestors(node: Options["SyntaxElementWithLoc"]): Array; + /** + * Gets the source code for the given node. + * @param {Options['SyntaxElementWithLoc']} [node] The AST node to get the text for. + * @param {number} [beforeCount] The number of characters before the node to retrieve. + * @param {number} [afterCount] The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + * @public + */ + public getText(node?: Options["SyntaxElementWithLoc"], beforeCount?: number, afterCount?: number): string; + /** + * Gets the entire source text split into an array of lines. + * @returns {Array} The source text as an array of lines. + * @public + */ + public get lines(): Array; + /** + * Traverse the source code and return the steps that were taken. + * @returns {Iterable} The steps that were taken while traversing the source code. + */ + traverse(): Iterable; + #private; +} +/** + * A class to represent a step in the traversal process where a node is visited. + * @implements {VisitTraversalStep} + */ +export class VisitNodeStep implements VisitTraversalStep { + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {object} options.target The target of the step. + * @param {1|2} options.phase The phase of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, phase, args }: { + target: object; + phase: 1 | 2; + args: Array; + }); + /** + * The type of the step. + * @type {"visit"} + * @readonly + */ + readonly type: "visit"; + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {1} + * @readonly + */ + readonly kind: 1; + /** + * The target of the step. + * @type {object} + */ + target: object; + /** + * The phase of the step. + * @type {1|2} + */ + phase: 1 | 2; + /** + * The arguments of the step. + * @type {Array} + */ + args: Array; +} +/** + * Represents a directive comment. + */ +declare class DirectiveComment { + /** + * Creates a new directive comment. + * @param {string} label The label of the directive. + * @param {string} value The value of the directive. + * @param {string} justification The justification of the directive. + */ + constructor(label: string, value: string, justification: string); + /** + * The label of the directive, such as "eslint", "eslint-disable", etc. + * @type {string} + */ + label: string; + /** + * The value of the directive (the string after the label). + * @type {string} + */ + value: string; + /** + * The justification of the directive (the string after the --). + * @type {string} + */ + justification: string; +} +export {}; diff --git a/node_modules/@eslint/plugin-kit/dist/esm/index.js b/node_modules/@eslint/plugin-kit/dist/esm/index.js new file mode 100644 index 00000000..bf8ab565 --- /dev/null +++ b/node_modules/@eslint/plugin-kit/dist/esm/index.js @@ -0,0 +1,615 @@ +// @ts-self-types="./index.d.ts" +import levn from 'levn'; + +/** + * @fileoverview Config Comment Parser + * @author Nicholas C. Zakas + */ + + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").RuleConfig} RuleConfig */ +/** @typedef {import("@eslint/core").RulesConfig} RulesConfig */ +/** @typedef {import("./types.ts").StringConfig} StringConfig */ +/** @typedef {import("./types.ts").BooleanConfig} BooleanConfig */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const directivesPattern = /^([a-z]+(?:-[a-z]+)*)(?:\s|$)/u; +const validSeverities = new Set([0, 1, 2, "off", "warn", "error"]); + +/** + * Determines if the severity in the rule configuration is valid. + * @param {RuleConfig} ruleConfig A rule's configuration. + * @returns {boolean} `true` if the severity is valid, otherwise `false`. + */ +function isSeverityValid(ruleConfig) { + const severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + return validSeverities.has(severity); +} + +/** + * Determines if all severities in the rules configuration are valid. + * @param {RulesConfig} rulesConfig The rules configuration to check. + * @returns {boolean} `true` if all severities are valid, otherwise `false`. + */ +function isEverySeverityValid(rulesConfig) { + return Object.values(rulesConfig).every(isSeverityValid); +} + +/** + * Represents a directive comment. + */ +class DirectiveComment { + /** + * The label of the directive, such as "eslint", "eslint-disable", etc. + * @type {string} + */ + label = ""; + + /** + * The value of the directive (the string after the label). + * @type {string} + */ + value = ""; + + /** + * The justification of the directive (the string after the --). + * @type {string} + */ + justification = ""; + + /** + * Creates a new directive comment. + * @param {string} label The label of the directive. + * @param {string} value The value of the directive. + * @param {string} justification The justification of the directive. + */ + constructor(label, value, justification) { + this.label = label; + this.value = value; + this.justification = justification; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Object to parse ESLint configuration comments. + */ +class ConfigCommentParser { + /** + * Parses a list of "name:string_value" or/and "name" options divided by comma or + * whitespace. Used for "global" comments. + * @param {string} string The string to parse. + * @returns {StringConfig} Result map object of names and string values, or null values if no value was provided. + */ + parseStringConfig(string) { + const items = /** @type {StringConfig} */ ({}); + + // Collapse whitespace around `:` and `,` to make parsing easier + const trimmedString = string + .trim() + .replace(/(? { + if (!name) { + return; + } + + // value defaults to null (if not provided), e.g: "foo" => ["foo", null] + const [key, value = null] = name.split(":"); + + items[key] = value; + }); + + return items; + } + + /** + * Parses a JSON-like config. + * @param {string} string The string to parse. + * @returns {({ok: true, config: RulesConfig}|{ok: false, error: {message: string}})} Result map object + */ + parseJSONLikeConfig(string) { + // Parses a JSON-like comment by the same way as parsing CLI option. + try { + const items = + /** @type {RulesConfig} */ (levn.parse("Object", string)) || {}; + + /* + * When the configuration has any invalid severities, it should be completely + * ignored. This is because the configuration is not valid and should not be + * applied. + * + * For example, the following configuration is invalid: + * + * "no-alert: 2 no-console: 2" + * + * This results in a configuration of { "no-alert": "2 no-console: 2" }, which is + * not valid. In this case, the configuration should be ignored. + */ + if (isEverySeverityValid(items)) { + return { + ok: true, + config: items, + }; + } + } catch { + // levn parsing error: ignore to parse the string by a fallback. + } + + /* + * Optionator cannot parse commaless notations. + * But we are supporting that. So this is a fallback for that. + */ + const normalizedString = string + .replace(/([-a-zA-Z0-9/]+):/gu, '"$1":') + .replace(/(\]|[0-9])\s+(?=")/u, "$1,"); + + try { + const items = JSON.parse(`{${normalizedString}}`); + + return { + ok: true, + config: items, + }; + } catch (ex) { + const errorMessage = ex instanceof Error ? ex.message : String(ex); + + return { + ok: false, + error: { + message: `Failed to parse JSON from '${normalizedString}': ${errorMessage}`, + }, + }; + } + } + + /** + * Parses a config of values separated by comma. + * @param {string} string The string to parse. + * @returns {BooleanConfig} Result map of values and true values + */ + parseListConfig(string) { + const items = /** @type {BooleanConfig} */ ({}); + + string.split(",").forEach(name => { + const trimmedName = name + .trim() + .replace( + /^(?['"]?)(?.*)\k$/su, + "$", + ); + + if (trimmedName) { + items[trimmedName] = true; + } + }); + + return items; + } + + /** + * Extract the directive and the justification from a given directive comment and trim them. + * @param {string} value The comment text to extract. + * @returns {{directivePart: string, justificationPart: string}} The extracted directive and justification. + */ + #extractDirectiveComment(value) { + const match = /\s-{2,}\s/u.exec(value); + + if (!match) { + return { directivePart: value.trim(), justificationPart: "" }; + } + + const directive = value.slice(0, match.index).trim(); + const justification = value.slice(match.index + match[0].length).trim(); + + return { directivePart: directive, justificationPart: justification }; + } + + /** + * Parses a directive comment into directive text and value. + * @param {string} string The string with the directive to be parsed. + * @returns {DirectiveComment|undefined} The parsed directive or `undefined` if the directive is invalid. + */ + parseDirective(string) { + const { directivePart, justificationPart } = + this.#extractDirectiveComment(string); + const match = directivesPattern.exec(directivePart); + + if (!match) { + return undefined; + } + + const directiveText = match[1]; + const directiveValue = directivePart.slice( + match.index + directiveText.length, + ); + + return new DirectiveComment( + directiveText, + directiveValue.trim(), + justificationPart, + ); + } +} + +/** + * @fileoverview A collection of helper classes for implementing `SourceCode`. + * @author Nicholas C. Zakas + */ + +/* eslint class-methods-use-this: off -- Required to complete interface. */ + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").VisitTraversalStep} VisitTraversalStep */ +/** @typedef {import("@eslint/core").CallTraversalStep} CallTraversalStep */ +/** @typedef {import("@eslint/core").TraversalStep} TraversalStep */ +/** @typedef {import("@eslint/core").SourceLocation} SourceLocation */ +/** @typedef {import("@eslint/core").SourceLocationWithOffset} SourceLocationWithOffset */ +/** @typedef {import("@eslint/core").SourceRange} SourceRange */ +/** @typedef {import("@eslint/core").Directive} IDirective */ +/** @typedef {import("@eslint/core").DirectiveType} DirectiveType */ +/** @typedef {import("@eslint/core").SourceCodeBaseTypeOptions} SourceCodeBaseTypeOptions */ +/** + * @typedef {import("@eslint/core").TextSourceCode} TextSourceCode + * @template {SourceCodeBaseTypeOptions} [Options=SourceCodeBaseTypeOptions] + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Determines if a node has ESTree-style loc information. + * @param {object} node The node to check. + * @returns {node is {loc:SourceLocation}} `true` if the node has ESTree-style loc information, `false` if not. + */ +function hasESTreeStyleLoc(node) { + return "loc" in node; +} + +/** + * Determines if a node has position-style loc information. + * @param {object} node The node to check. + * @returns {node is {position:SourceLocation}} `true` if the node has position-style range information, `false` if not. + */ +function hasPosStyleLoc(node) { + return "position" in node; +} + +/** + * Determines if a node has ESTree-style range information. + * @param {object} node The node to check. + * @returns {node is {range:SourceRange}} `true` if the node has ESTree-style range information, `false` if not. + */ +function hasESTreeStyleRange(node) { + return "range" in node; +} + +/** + * Determines if a node has position-style range information. + * @param {object} node The node to check. + * @returns {node is {position:SourceLocationWithOffset}} `true` if the node has position-style range information, `false` if not. + */ +function hasPosStyleRange(node) { + return "position" in node; +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class to represent a step in the traversal process where a node is visited. + * @implements {VisitTraversalStep} + */ +class VisitNodeStep { + /** + * The type of the step. + * @type {"visit"} + * @readonly + */ + type = "visit"; + + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {1} + * @readonly + */ + kind = 1; + + /** + * The target of the step. + * @type {object} + */ + target; + + /** + * The phase of the step. + * @type {1|2} + */ + phase; + + /** + * The arguments of the step. + * @type {Array} + */ + args; + + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {object} options.target The target of the step. + * @param {1|2} options.phase The phase of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, phase, args }) { + this.target = target; + this.phase = phase; + this.args = args; + } +} + +/** + * A class to represent a step in the traversal process where a + * method is called. + * @implements {CallTraversalStep} + */ +class CallMethodStep { + /** + * The type of the step. + * @type {"call"} + * @readonly + */ + type = "call"; + + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {2} + * @readonly + */ + kind = 2; + + /** + * The name of the method to call. + * @type {string} + */ + target; + + /** + * The arguments to pass to the method. + * @type {Array} + */ + args; + + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {string} options.target The target of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, args }) { + this.target = target; + this.args = args; + } +} + +/** + * A class to represent a directive comment. + * @implements {IDirective} + */ +class Directive { + /** + * The type of directive. + * @type {DirectiveType} + * @readonly + */ + type; + + /** + * The node representing the directive. + * @type {unknown} + * @readonly + */ + node; + + /** + * Everything after the "eslint-disable" portion of the directive, + * but before the "--" that indicates the justification. + * @type {string} + * @readonly + */ + value; + + /** + * The justification for the directive. + * @type {string} + * @readonly + */ + justification; + + /** + * Creates a new instance. + * @param {Object} options The options for the directive. + * @param {"disable"|"enable"|"disable-next-line"|"disable-line"} options.type The type of directive. + * @param {unknown} options.node The node representing the directive. + * @param {string} options.value The value of the directive. + * @param {string} options.justification The justification for the directive. + */ + constructor({ type, node, value, justification }) { + this.type = type; + this.node = node; + this.value = value; + this.justification = justification; + } +} + +/** + * Source Code Base Object + * @template {SourceCodeBaseTypeOptions & {SyntaxElementWithLoc: object}} [Options=SourceCodeBaseTypeOptions & {SyntaxElementWithLoc: object}] + * @implements {TextSourceCode} + */ +class TextSourceCodeBase { + /** + * The lines of text in the source code. + * @type {Array} + */ + #lines; + + /** + * The AST of the source code. + * @type {Options['RootNode']} + */ + ast; + + /** + * The text of the source code. + * @type {string} + */ + text; + + /** + * Creates a new instance. + * @param {Object} options The options for the instance. + * @param {string} options.text The source code text. + * @param {Options['RootNode']} options.ast The root AST node. + * @param {RegExp} [options.lineEndingPattern] The pattern to match lineEndings in the source code. + */ + constructor({ text, ast, lineEndingPattern = /\r?\n/u }) { + this.ast = ast; + this.text = text; + this.#lines = text.split(lineEndingPattern); + } + + /** + * Returns the loc information for the given node or token. + * @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the loc information for. + * @returns {SourceLocation} The loc information for the node or token. + * @throws {Error} If the node or token does not have loc information. + */ + getLoc(nodeOrToken) { + if (hasESTreeStyleLoc(nodeOrToken)) { + return nodeOrToken.loc; + } + + if (hasPosStyleLoc(nodeOrToken)) { + return nodeOrToken.position; + } + + throw new Error( + "Custom getLoc() method must be implemented in the subclass.", + ); + } + + /** + * Returns the range information for the given node or token. + * @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the range information for. + * @returns {SourceRange} The range information for the node or token. + * @throws {Error} If the node or token does not have range information. + */ + getRange(nodeOrToken) { + if (hasESTreeStyleRange(nodeOrToken)) { + return nodeOrToken.range; + } + + if (hasPosStyleRange(nodeOrToken)) { + return [ + nodeOrToken.position.start.offset, + nodeOrToken.position.end.offset, + ]; + } + + throw new Error( + "Custom getRange() method must be implemented in the subclass.", + ); + } + + /* eslint-disable no-unused-vars -- Required to complete interface. */ + /** + * Returns the parent of the given node. + * @param {Options['SyntaxElementWithLoc']} node The node to get the parent of. + * @returns {Options['SyntaxElementWithLoc']|undefined} The parent of the node. + * @throws {Error} If the method is not implemented in the subclass. + */ + getParent(node) { + throw new Error("Not implemented."); + } + /* eslint-enable no-unused-vars -- Required to complete interface. */ + + /** + * Gets all the ancestors of a given node + * @param {Options['SyntaxElementWithLoc']} node The node + * @returns {Array} All the ancestor nodes in the AST, not including the provided node, starting + * from the root node at index 0 and going inwards to the parent node. + * @throws {TypeError} When `node` is missing. + */ + getAncestors(node) { + if (!node) { + throw new TypeError("Missing required argument: node."); + } + + const ancestorsStartingAtParent = []; + + for ( + let ancestor = this.getParent(node); + ancestor; + ancestor = this.getParent(ancestor) + ) { + ancestorsStartingAtParent.push(ancestor); + } + + return ancestorsStartingAtParent.reverse(); + } + + /** + * Gets the source code for the given node. + * @param {Options['SyntaxElementWithLoc']} [node] The AST node to get the text for. + * @param {number} [beforeCount] The number of characters before the node to retrieve. + * @param {number} [afterCount] The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + * @public + */ + getText(node, beforeCount, afterCount) { + if (node) { + const range = this.getRange(node); + return this.text.slice( + Math.max(range[0] - (beforeCount || 0), 0), + range[1] + (afterCount || 0), + ); + } + return this.text; + } + + /** + * Gets the entire source text split into an array of lines. + * @returns {Array} The source text as an array of lines. + * @public + */ + get lines() { + return this.#lines; + } + + /** + * Traverse the source code and return the steps that were taken. + * @returns {Iterable} The steps that were taken while traversing the source code. + */ + traverse() { + throw new Error("Not implemented."); + } +} + +export { CallMethodStep, ConfigCommentParser, Directive, TextSourceCodeBase, VisitNodeStep }; diff --git a/node_modules/@eslint/plugin-kit/dist/esm/types.d.ts b/node_modules/@eslint/plugin-kit/dist/esm/types.d.ts new file mode 100644 index 00000000..e4a442a4 --- /dev/null +++ b/node_modules/@eslint/plugin-kit/dist/esm/types.d.ts @@ -0,0 +1,6 @@ +/** + * @fileoverview Types for the plugin-kit package. + * @author Nicholas C. Zakas + */ +export type StringConfig = Record; +export type BooleanConfig = Record; diff --git a/node_modules/@eslint/plugin-kit/dist/esm/types.ts b/node_modules/@eslint/plugin-kit/dist/esm/types.ts new file mode 100644 index 00000000..d3f6a888 --- /dev/null +++ b/node_modules/@eslint/plugin-kit/dist/esm/types.ts @@ -0,0 +1,7 @@ +/** + * @fileoverview Types for the plugin-kit package. + * @author Nicholas C. Zakas + */ + +export type StringConfig = Record; +export type BooleanConfig = Record; diff --git a/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/LICENSE b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/README.md b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/README.md new file mode 100644 index 00000000..19e8222c --- /dev/null +++ b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/README.md @@ -0,0 +1,30 @@ +# ESLint Core + +## Overview + +This package is the future home of the rewritten, runtime-agnostic ESLint core. + +Right now, it exports the core types necessary to implement language plugins. + +## License + +Apache 2.0 + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/dist/cjs/types.d.cts b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/dist/cjs/types.d.cts new file mode 100644 index 00000000..c296063d --- /dev/null +++ b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/dist/cjs/types.d.cts @@ -0,0 +1,847 @@ +/** + * @fileoverview Shared types for ESLint Core. + */ +import type { JSONSchema4 } from "json-schema"; +/** + * Represents an error inside of a file. + */ +export interface FileError { + message: string; + line: number; + column: number; + endLine?: number; + endColumn?: number; +} +/** + * Represents a problem found in a file. + */ +export interface FileProblem { + ruleId: string | null; + message: string; + loc: SourceLocation; +} +/** + * Represents the start and end coordinates of a node inside the source. + */ +export interface SourceLocation { + start: Position; + end: Position; +} +/** + * Represents the start and end coordinates of a node inside the source with an offset. + */ +export interface SourceLocationWithOffset { + start: PositionWithOffset; + end: PositionWithOffset; +} +/** + * Represents a location coordinate inside the source. ESLint-style formats + * have just `line` and `column` while others may have `offset` as well. + */ +export interface Position { + line: number; + column: number; +} +/** + * Represents a location coordinate inside the source with an offset. + */ +export interface PositionWithOffset extends Position { + offset: number; +} +/** + * Represents a range of characters in the source. + */ +export type SourceRange = [number, number]; +/** + * What the rule is responsible for finding: + * - `problem` means the rule has noticed a potential error. + * - `suggestion` means the rule suggests an alternate or better approach. + * - `layout` means the rule is looking at spacing, indentation, etc. + */ +export type RuleType = "problem" | "suggestion" | "layout"; +/** + * The type of fix the rule can provide: + * - `code` means the rule can fix syntax. + * - `whitespace` means the rule can fix spacing and indentation. + */ +export type RuleFixType = "code" | "whitespace"; +/** + * An object containing visitor information for a rule. Each method is either the + * name of a node type or a selector, or is a method that will be called at specific + * times during the traversal. + */ +export type RuleVisitor = Record void) | undefined>; +/** + * Rule meta information used for documentation. + */ +export interface RulesMetaDocs { + /** + * A short description of the rule. + */ + description?: string | undefined; + /** + * The URL to the documentation for the rule. + */ + url?: string | undefined; + /** + * The category the rule falls under. + * @deprecated No longer used. + */ + category?: string | undefined; + /** + * Indicates if the rule is generally recommended for all users. + */ + recommended?: boolean | undefined; + /** + * Indicates if the rule is frozen (no longer accepting feature requests). + */ + frozen?: boolean | undefined; +} +/** + * Meta information about a rule. + */ +export interface RulesMeta { + /** + * Properties that are used when documenting the rule. + */ + docs?: (RulesMetaDocs & ExtRuleDocs) | undefined; + /** + * The type of rule. + */ + type?: RuleType | undefined; + /** + * The schema for the rule options. Required if the rule has options. + */ + schema?: JSONSchema4 | JSONSchema4[] | false | undefined; + /** + * Any default options to be recursively merged on top of any user-provided options. + **/ + defaultOptions?: RuleOptions; + /** + * The messages that the rule can report. + */ + messages?: Record; + /** + * Indicates whether the rule has been deprecated or provides additional metadata about the deprecation. Omit if not deprecated. + */ + deprecated?: boolean | DeprecatedInfo | undefined; + /** + * @deprecated Use deprecated.replacedBy instead. + * The name of the rule(s) this rule was replaced by, if it was deprecated. + */ + replacedBy?: readonly string[] | undefined; + /** + * Indicates if the rule is fixable, and if so, what type of fix it provides. + */ + fixable?: RuleFixType | undefined; + /** + * Indicates if the rule may provide suggestions. + */ + hasSuggestions?: boolean | undefined; + /** + * The language the rule is intended to lint. + */ + language?: string; + /** + * The dialects of `language` that the rule is intended to lint. + */ + dialects?: string[]; +} +/** + * Provides additional metadata about a deprecation. + */ +export interface DeprecatedInfo { + /** + * General message presented to the user, e.g. for the key rule why the rule + * is deprecated or for info how to replace the rule. + */ + message?: string; + /** + * URL to more information about this deprecation in general. + */ + url?: string; + /** + * An empty array explicitly states that there is no replacement. + */ + replacedBy?: ReplacedByInfo[]; + /** + * The package version since when the rule is deprecated (should use full + * semver without a leading "v"). + */ + deprecatedSince?: string; + /** + * The estimated version when the rule is removed (probably the next major + * version). null means the rule is "frozen" (will be available but will not + * be changed). + */ + availableUntil?: string | null; +} +/** + * Provides metadata about a replacement + */ +export interface ReplacedByInfo { + /** + * General message presented to the user, e.g. how to replace the rule + */ + message?: string; + /** + * URL to more information about this replacement in general + */ + url?: string; + /** + * Name should be "eslint" if the replacement is an ESLint core rule. Omit + * the property if the replacement is in the same plugin. + */ + plugin?: ExternalSpecifier; + /** + * Name and documentation of the replacement rule + */ + rule?: ExternalSpecifier; +} +/** + * Specifies the name and url of an external resource. At least one property + * should be set. + */ +export interface ExternalSpecifier { + /** + * Name of the referenced plugin / rule. + */ + name?: string; + /** + * URL pointing to documentation for the plugin / rule. + */ + url?: string; +} +/** + * Generic type for `RuleContext`. + */ +export interface RuleContextTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RuleOptions: unknown[]; + Node: unknown; + MessageIds: string; +} +/** + * Represents the context object that is passed to a rule. This object contains + * information about the current state of the linting process and is the rule's + * view into the outside world. + */ +export interface RuleContext { + /** + * The current working directory for the session. + */ + cwd: string; + /** + * Returns the current working directory for the session. + * @deprecated Use `cwd` instead. + */ + getCwd(): string; + /** + * The filename of the file being linted. + */ + filename: string; + /** + * Returns the filename of the file being linted. + * @deprecated Use `filename` instead. + */ + getFilename(): string; + /** + * The physical filename of the file being linted. + */ + physicalFilename: string; + /** + * Returns the physical filename of the file being linted. + * @deprecated Use `physicalFilename` instead. + */ + getPhysicalFilename(): string; + /** + * The source code object that the rule is running on. + */ + sourceCode: Options["Code"]; + /** + * Returns the source code object that the rule is running on. + * @deprecated Use `sourceCode` instead. + */ + getSourceCode(): Options["Code"]; + /** + * Shared settings for the configuration. + */ + settings: SettingsConfig; + /** + * Parser-specific options for the configuration. + * @deprecated Use `languageOptions.parserOptions` instead. + */ + parserOptions: Record; + /** + * The language options for the configuration. + */ + languageOptions: Options["LangOptions"]; + /** + * The CommonJS path to the parser used while parsing this file. + * @deprecated No longer used. + */ + parserPath: string | undefined; + /** + * The rule ID. + */ + id: string; + /** + * The rule's configured options. + */ + options: Options["RuleOptions"]; + /** + * The report function that the rule should use to report problems. + * @param violation The violation to report. + */ + report(violation: ViolationReport): void; +} +/** + * Manager of text edits for a rule fix. + */ +export interface RuleTextEditor { + /** + * Inserts text after the specified node or token. + * @param syntaxElement The node or token to insert after. + * @param text The edit to insert after the node or token. + */ + insertTextAfter(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Inserts text after the specified range. + * @param range The range to insert after. + * @param text The edit to insert after the range. + */ + insertTextAfterRange(range: SourceRange, text: string): RuleTextEdit; + /** + * Inserts text before the specified node or token. + * @param syntaxElement A syntax element with location information to insert before. + * @param text The edit to insert before the node or token. + */ + insertTextBefore(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Inserts text before the specified range. + * @param range The range to insert before. + * @param text The edit to insert before the range. + */ + insertTextBeforeRange(range: SourceRange, text: string): RuleTextEdit; + /** + * Removes the specified node or token. + * @param syntaxElement A syntax element with location information to remove. + * @returns The edit to remove the node or token. + */ + remove(syntaxElement: EditableSyntaxElement): RuleTextEdit; + /** + * Removes the specified range. + * @param range The range to remove. + * @returns The edit to remove the range. + */ + removeRange(range: SourceRange): RuleTextEdit; + /** + * Replaces the specified node or token with the given text. + * @param syntaxElement A syntax element with location information to replace. + * @param text The text to replace the node or token with. + * @returns The edit to replace the node or token. + */ + replaceText(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Replaces the specified range with the given text. + * @param range The range to replace. + * @param text The text to replace the range with. + * @returns The edit to replace the range. + */ + replaceTextRange(range: SourceRange, text: string): RuleTextEdit; +} +/** + * Represents a fix for a rule violation implemented as a text edit. + */ +export interface RuleTextEdit { + /** + * The range to replace. + */ + range: SourceRange; + /** + * The text to insert. + */ + text: string; +} +/** + * Fixes a violation. + * @param fixer The text editor to apply the fix. + * @returns The fix(es) for the violation. + */ +type RuleFixer = (fixer: RuleTextEditor) => RuleTextEdit | Iterable | null; +interface ViolationReportBase { + /** + * The type of node that the violation is for. + * @deprecated May be removed in the future. + */ + nodeType?: string | undefined; + /** + * The data to insert into the message. + */ + data?: Record | undefined; + /** + * The fix to be applied for the violation. + */ + fix?: RuleFixer | null | undefined; + /** + * An array of suggested fixes for the problem. These fixes may change the + * behavior of the code, so they are not applied automatically. + */ + suggest?: SuggestedEdit[] | null | undefined; +} +type ViolationMessage = { + message: string; +} | { + messageId: MessageIds; +}; +type ViolationLocation = { + loc: SourceLocation | Position; +} | { + node: Node; +}; +export type ViolationReport = ViolationReportBase & ViolationMessage & ViolationLocation; +interface SuggestedEditBase { + /** + * The data to insert into the message. + */ + data?: Record | undefined; + /** + * The fix to be applied for the suggestion. + */ + fix?: RuleFixer | null | undefined; +} +type SuggestionMessage = { + desc: string; +} | { + messageId: string; +}; +/** + * A suggested edit for a rule violation. + */ +export type SuggestedEdit = SuggestedEditBase & SuggestionMessage; +/** + * Generic options for the `RuleDefinition` type. + */ +export interface RuleDefinitionTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RuleOptions: unknown[]; + Visitor: RuleVisitor; + Node: unknown; + MessageIds: string; + ExtRuleDocs: unknown; +} +/** + * The definition of an ESLint rule. + */ +export interface RuleDefinition { + /** + * The meta information for the rule. + */ + meta?: RulesMeta; + /** + * Creates the visitor that ESLint uses to apply the rule during traversal. + * @param context The rule context. + * @returns The rule visitor. + */ + create(context: RuleContext<{ + LangOptions: Options["LangOptions"]; + Code: Options["Code"]; + RuleOptions: Options["RuleOptions"]; + Node: Options["Node"]; + MessageIds: Options["MessageIds"]; + }>): Options["Visitor"]; +} +/** + * Defaults for non-language-related `RuleDefinition` options. + */ +export interface CustomRuleTypeDefinitions { + RuleOptions: unknown[]; + MessageIds: string; + ExtRuleDocs: Record; +} +/** + * A helper type to define language specific specializations of the `RuleDefinition` type. + * + * @example + * ```ts + * type YourRuleDefinition< + * Options extends Partial = {}, + * > = CustomRuleDefinitionType< + * { + * LangOptions: YourLanguageOptions; + * Code: YourSourceCode; + * Visitor: YourRuleVisitor; + * Node: YourNode; + * }, + * Options + * >; + * ``` + */ +export type CustomRuleDefinitionType, Options extends Partial> = RuleDefinition>>; +/** + * The human readable severity level used in a configuration. + */ +export type SeverityName = "off" | "warn" | "error"; +/** + * The numeric severity level for a rule. + * + * - `0` means off. + * - `1` means warn. + * - `2` means error. + */ +export type SeverityLevel = 0 | 1 | 2; +/** + * The severity of a rule in a configuration. + */ +export type Severity = SeverityName | SeverityLevel; +/** + * Represents the configuration options for the core linter. + */ +export interface LinterOptionsConfig { + /** + * Indicates whether or not inline configuration is evaluated. + */ + noInlineConfig?: boolean; + /** + * Indicates what to do when an unused disable directive is found. + */ + reportUnusedDisableDirectives?: boolean | Severity; + /** + * A severity value indicating if and how unused inline configs should be + * tracked and reported. + */ + reportUnusedInlineConfigs?: Severity; +} +/** + * The configuration for a rule. + */ +export type RuleConfig = Severity | [Severity, ...RuleOptions]; +/** + * A collection of rules and their configurations. + */ +export interface RulesConfig { + [key: string]: RuleConfig; +} +/** + * A collection of settings. + */ +export interface SettingsConfig { + [key: string]: unknown; +} +/** + * Generic options for the `Language` type. + */ +export interface LanguageTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RootNode: unknown; + Node: unknown; +} +/** + * Represents a plugin language. + */ +export interface Language { + /** + * Indicates how ESLint should read the file. + */ + fileType: "text"; + /** + * First line number returned from the parser (text mode only). + */ + lineStart: 0 | 1; + /** + * First column number returned from the parser (text mode only). + */ + columnStart: 0 | 1; + /** + * The property to read the node type from. Used in selector querying. + */ + nodeTypeKey: string; + /** + * The traversal path that tools should take when evaluating the AST + */ + visitorKeys?: Record; + /** + * Default language options. User-defined options are merged with this object. + */ + defaultLanguageOptions?: LanguageOptions; + /** + * Validates languageOptions for this language. + */ + validateLanguageOptions(languageOptions: Options["LangOptions"]): void; + /** + * Normalizes languageOptions for this language. + */ + normalizeLanguageOptions?(languageOptions: Options["LangOptions"]): Options["LangOptions"]; + /** + * Helper for esquery that allows languages to match nodes against + * class. esquery currently has classes like `function` that will + * match all the various function nodes. This method allows languages + * to implement similar shorthands. + */ + matchesSelectorClass?(className: string, node: Options["Node"], ancestry: Options["Node"][]): boolean; + /** + * Parses the given file input into its component parts. This file should not + * throws errors for parsing errors but rather should return any parsing + * errors as parse of the ParseResult object. + */ + parse(file: File, context: LanguageContext): ParseResult; + /** + * Creates SourceCode object that ESLint uses to work with a file. + */ + createSourceCode(file: File, input: OkParseResult, context: LanguageContext): Options["Code"]; +} +/** + * Plugin-defined options for the language. + */ +export type LanguageOptions = Record; +/** + * The context object that is passed to the language plugin methods. + */ +export interface LanguageContext { + languageOptions: LangOptions; +} +/** + * Represents a file read by ESLint. + */ +export interface File { + /** + * The path that ESLint uses for this file. May be a virtual path + * if it was returned by a processor. + */ + path: string; + /** + * The path to the file on disk. This always maps directly to a file + * regardless of whether it was returned from a processor. + */ + physicalPath: string; + /** + * Indicates if the original source contained a byte-order marker. + * ESLint strips the BOM from the `body`, but this info is needed + * to correctly apply autofixing. + */ + bom: boolean; + /** + * The body of the file to parse. + */ + body: string | Uint8Array; +} +/** + * Represents the successful result of parsing a file. + */ +export interface OkParseResult { + /** + * Indicates if the parse was successful. If true, the parse was successful + * and ESLint should continue on to create a SourceCode object and run rules; + * if false, ESLint should just report the error(s) without doing anything + * else. + */ + ok: true; + /** + * The abstract syntax tree created by the parser. (only when ok: true) + */ + ast: RootNode; + /** + * Any additional data that the parser wants to provide. + */ + [key: string]: any; +} +/** + * Represents the unsuccessful result of parsing a file. + */ +export interface NotOkParseResult { + /** + * Indicates if the parse was successful. If true, the parse was successful + * and ESLint should continue on to create a SourceCode object and run rules; + * if false, ESLint should just report the error(s) without doing anything + * else. + */ + ok: false; + /** + * Any parsing errors, whether fatal or not. (only when ok: false) + */ + errors: FileError[]; + /** + * Any additional data that the parser wants to provide. + */ + [key: string]: any; +} +export type ParseResult = OkParseResult | NotOkParseResult; +/** + * Represents inline configuration found in the source code. + */ +interface InlineConfigElement { + /** + * The location of the inline config element. + */ + loc: SourceLocation; + /** + * The interpreted configuration from the inline config element. + */ + config: { + rules: RulesConfig; + }; +} +/** + * Generic options for the `SourceCodeBase` type. + */ +export interface SourceCodeBaseTypeOptions { + LangOptions: LanguageOptions; + RootNode: unknown; + SyntaxElementWithLoc: unknown; + ConfigNode: unknown; +} +/** + * Represents the basic interface for a source code object. + */ +interface SourceCodeBase { + /** + * Root of the AST. + */ + ast: Options["RootNode"]; + /** + * The traversal path that tools should take when evaluating the AST. + * When present, this overrides the `visitorKeys` on the language for + * just this source code object. + */ + visitorKeys?: Record; + /** + * Retrieves the equivalent of `loc` for a given node or token. + * @param syntaxElement The node or token to get the location for. + * @returns The location of the node or token. + */ + getLoc(syntaxElement: Options["SyntaxElementWithLoc"]): SourceLocation; + /** + * Retrieves the equivalent of `range` for a given node or token. + * @param syntaxElement The node or token to get the range for. + * @returns The range of the node or token. + */ + getRange(syntaxElement: Options["SyntaxElementWithLoc"]): SourceRange; + /** + * Traversal of AST. + */ + traverse(): Iterable; + /** + * Applies language options passed in from the ESLint core. + */ + applyLanguageOptions?(languageOptions: Options["LangOptions"]): void; + /** + * Return all of the inline areas where ESLint should be disabled/enabled + * along with any problems found in evaluating the directives. + */ + getDisableDirectives?(): { + directives: Directive[]; + problems: FileProblem[]; + }; + /** + * Returns an array of all inline configuration nodes found in the + * source code. + */ + getInlineConfigNodes?(): Options["ConfigNode"][]; + /** + * Applies configuration found inside of the source code. This method is only + * called when ESLint is running with inline configuration allowed. + */ + applyInlineConfig?(): { + configs: InlineConfigElement[]; + problems: FileProblem[]; + }; + /** + * Called by ESLint core to indicate that it has finished providing + * information. We now add in all the missing variables and ensure that + * state-changing methods cannot be called by rules. + * @returns {void} + */ + finalize?(): void; +} +/** + * Represents the source of a text file being linted. + */ +export interface TextSourceCode extends SourceCodeBase { + /** + * The body of the file that you'd like rule developers to access. + */ + text: string; +} +/** + * Represents the source of a binary file being linted. + */ +export interface BinarySourceCode extends SourceCodeBase { + /** + * The body of the file that you'd like rule developers to access. + */ + body: Uint8Array; +} +export type SourceCode = TextSourceCode | BinarySourceCode; +/** + * Represents a traversal step visiting the AST. + */ +export interface VisitTraversalStep { + kind: 1; + target: unknown; + phase: 1 | 2; + args: unknown[]; +} +/** + * Represents a traversal step calling a function. + */ +export interface CallTraversalStep { + kind: 2; + target: string; + phase?: string; + args: unknown[]; +} +export type TraversalStep = VisitTraversalStep | CallTraversalStep; +/** + * The type of disable directive. This determines how ESLint will disable rules. + */ +export type DirectiveType = "disable" | "enable" | "disable-line" | "disable-next-line"; +/** + * Represents a disable directive. + */ +export interface Directive { + /** + * The type of directive. + */ + type: DirectiveType; + /** + * The node of the directive. May be in the AST or a comment/token. + */ + node: unknown; + /** + * The value of the directive. + */ + value: string; + /** + * The justification for the directive. + */ + justification?: string; +} +export {}; diff --git a/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/dist/esm/types.d.ts b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/dist/esm/types.d.ts new file mode 100644 index 00000000..c296063d --- /dev/null +++ b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/dist/esm/types.d.ts @@ -0,0 +1,847 @@ +/** + * @fileoverview Shared types for ESLint Core. + */ +import type { JSONSchema4 } from "json-schema"; +/** + * Represents an error inside of a file. + */ +export interface FileError { + message: string; + line: number; + column: number; + endLine?: number; + endColumn?: number; +} +/** + * Represents a problem found in a file. + */ +export interface FileProblem { + ruleId: string | null; + message: string; + loc: SourceLocation; +} +/** + * Represents the start and end coordinates of a node inside the source. + */ +export interface SourceLocation { + start: Position; + end: Position; +} +/** + * Represents the start and end coordinates of a node inside the source with an offset. + */ +export interface SourceLocationWithOffset { + start: PositionWithOffset; + end: PositionWithOffset; +} +/** + * Represents a location coordinate inside the source. ESLint-style formats + * have just `line` and `column` while others may have `offset` as well. + */ +export interface Position { + line: number; + column: number; +} +/** + * Represents a location coordinate inside the source with an offset. + */ +export interface PositionWithOffset extends Position { + offset: number; +} +/** + * Represents a range of characters in the source. + */ +export type SourceRange = [number, number]; +/** + * What the rule is responsible for finding: + * - `problem` means the rule has noticed a potential error. + * - `suggestion` means the rule suggests an alternate or better approach. + * - `layout` means the rule is looking at spacing, indentation, etc. + */ +export type RuleType = "problem" | "suggestion" | "layout"; +/** + * The type of fix the rule can provide: + * - `code` means the rule can fix syntax. + * - `whitespace` means the rule can fix spacing and indentation. + */ +export type RuleFixType = "code" | "whitespace"; +/** + * An object containing visitor information for a rule. Each method is either the + * name of a node type or a selector, or is a method that will be called at specific + * times during the traversal. + */ +export type RuleVisitor = Record void) | undefined>; +/** + * Rule meta information used for documentation. + */ +export interface RulesMetaDocs { + /** + * A short description of the rule. + */ + description?: string | undefined; + /** + * The URL to the documentation for the rule. + */ + url?: string | undefined; + /** + * The category the rule falls under. + * @deprecated No longer used. + */ + category?: string | undefined; + /** + * Indicates if the rule is generally recommended for all users. + */ + recommended?: boolean | undefined; + /** + * Indicates if the rule is frozen (no longer accepting feature requests). + */ + frozen?: boolean | undefined; +} +/** + * Meta information about a rule. + */ +export interface RulesMeta { + /** + * Properties that are used when documenting the rule. + */ + docs?: (RulesMetaDocs & ExtRuleDocs) | undefined; + /** + * The type of rule. + */ + type?: RuleType | undefined; + /** + * The schema for the rule options. Required if the rule has options. + */ + schema?: JSONSchema4 | JSONSchema4[] | false | undefined; + /** + * Any default options to be recursively merged on top of any user-provided options. + **/ + defaultOptions?: RuleOptions; + /** + * The messages that the rule can report. + */ + messages?: Record; + /** + * Indicates whether the rule has been deprecated or provides additional metadata about the deprecation. Omit if not deprecated. + */ + deprecated?: boolean | DeprecatedInfo | undefined; + /** + * @deprecated Use deprecated.replacedBy instead. + * The name of the rule(s) this rule was replaced by, if it was deprecated. + */ + replacedBy?: readonly string[] | undefined; + /** + * Indicates if the rule is fixable, and if so, what type of fix it provides. + */ + fixable?: RuleFixType | undefined; + /** + * Indicates if the rule may provide suggestions. + */ + hasSuggestions?: boolean | undefined; + /** + * The language the rule is intended to lint. + */ + language?: string; + /** + * The dialects of `language` that the rule is intended to lint. + */ + dialects?: string[]; +} +/** + * Provides additional metadata about a deprecation. + */ +export interface DeprecatedInfo { + /** + * General message presented to the user, e.g. for the key rule why the rule + * is deprecated or for info how to replace the rule. + */ + message?: string; + /** + * URL to more information about this deprecation in general. + */ + url?: string; + /** + * An empty array explicitly states that there is no replacement. + */ + replacedBy?: ReplacedByInfo[]; + /** + * The package version since when the rule is deprecated (should use full + * semver without a leading "v"). + */ + deprecatedSince?: string; + /** + * The estimated version when the rule is removed (probably the next major + * version). null means the rule is "frozen" (will be available but will not + * be changed). + */ + availableUntil?: string | null; +} +/** + * Provides metadata about a replacement + */ +export interface ReplacedByInfo { + /** + * General message presented to the user, e.g. how to replace the rule + */ + message?: string; + /** + * URL to more information about this replacement in general + */ + url?: string; + /** + * Name should be "eslint" if the replacement is an ESLint core rule. Omit + * the property if the replacement is in the same plugin. + */ + plugin?: ExternalSpecifier; + /** + * Name and documentation of the replacement rule + */ + rule?: ExternalSpecifier; +} +/** + * Specifies the name and url of an external resource. At least one property + * should be set. + */ +export interface ExternalSpecifier { + /** + * Name of the referenced plugin / rule. + */ + name?: string; + /** + * URL pointing to documentation for the plugin / rule. + */ + url?: string; +} +/** + * Generic type for `RuleContext`. + */ +export interface RuleContextTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RuleOptions: unknown[]; + Node: unknown; + MessageIds: string; +} +/** + * Represents the context object that is passed to a rule. This object contains + * information about the current state of the linting process and is the rule's + * view into the outside world. + */ +export interface RuleContext { + /** + * The current working directory for the session. + */ + cwd: string; + /** + * Returns the current working directory for the session. + * @deprecated Use `cwd` instead. + */ + getCwd(): string; + /** + * The filename of the file being linted. + */ + filename: string; + /** + * Returns the filename of the file being linted. + * @deprecated Use `filename` instead. + */ + getFilename(): string; + /** + * The physical filename of the file being linted. + */ + physicalFilename: string; + /** + * Returns the physical filename of the file being linted. + * @deprecated Use `physicalFilename` instead. + */ + getPhysicalFilename(): string; + /** + * The source code object that the rule is running on. + */ + sourceCode: Options["Code"]; + /** + * Returns the source code object that the rule is running on. + * @deprecated Use `sourceCode` instead. + */ + getSourceCode(): Options["Code"]; + /** + * Shared settings for the configuration. + */ + settings: SettingsConfig; + /** + * Parser-specific options for the configuration. + * @deprecated Use `languageOptions.parserOptions` instead. + */ + parserOptions: Record; + /** + * The language options for the configuration. + */ + languageOptions: Options["LangOptions"]; + /** + * The CommonJS path to the parser used while parsing this file. + * @deprecated No longer used. + */ + parserPath: string | undefined; + /** + * The rule ID. + */ + id: string; + /** + * The rule's configured options. + */ + options: Options["RuleOptions"]; + /** + * The report function that the rule should use to report problems. + * @param violation The violation to report. + */ + report(violation: ViolationReport): void; +} +/** + * Manager of text edits for a rule fix. + */ +export interface RuleTextEditor { + /** + * Inserts text after the specified node or token. + * @param syntaxElement The node or token to insert after. + * @param text The edit to insert after the node or token. + */ + insertTextAfter(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Inserts text after the specified range. + * @param range The range to insert after. + * @param text The edit to insert after the range. + */ + insertTextAfterRange(range: SourceRange, text: string): RuleTextEdit; + /** + * Inserts text before the specified node or token. + * @param syntaxElement A syntax element with location information to insert before. + * @param text The edit to insert before the node or token. + */ + insertTextBefore(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Inserts text before the specified range. + * @param range The range to insert before. + * @param text The edit to insert before the range. + */ + insertTextBeforeRange(range: SourceRange, text: string): RuleTextEdit; + /** + * Removes the specified node or token. + * @param syntaxElement A syntax element with location information to remove. + * @returns The edit to remove the node or token. + */ + remove(syntaxElement: EditableSyntaxElement): RuleTextEdit; + /** + * Removes the specified range. + * @param range The range to remove. + * @returns The edit to remove the range. + */ + removeRange(range: SourceRange): RuleTextEdit; + /** + * Replaces the specified node or token with the given text. + * @param syntaxElement A syntax element with location information to replace. + * @param text The text to replace the node or token with. + * @returns The edit to replace the node or token. + */ + replaceText(syntaxElement: EditableSyntaxElement, text: string): RuleTextEdit; + /** + * Replaces the specified range with the given text. + * @param range The range to replace. + * @param text The text to replace the range with. + * @returns The edit to replace the range. + */ + replaceTextRange(range: SourceRange, text: string): RuleTextEdit; +} +/** + * Represents a fix for a rule violation implemented as a text edit. + */ +export interface RuleTextEdit { + /** + * The range to replace. + */ + range: SourceRange; + /** + * The text to insert. + */ + text: string; +} +/** + * Fixes a violation. + * @param fixer The text editor to apply the fix. + * @returns The fix(es) for the violation. + */ +type RuleFixer = (fixer: RuleTextEditor) => RuleTextEdit | Iterable | null; +interface ViolationReportBase { + /** + * The type of node that the violation is for. + * @deprecated May be removed in the future. + */ + nodeType?: string | undefined; + /** + * The data to insert into the message. + */ + data?: Record | undefined; + /** + * The fix to be applied for the violation. + */ + fix?: RuleFixer | null | undefined; + /** + * An array of suggested fixes for the problem. These fixes may change the + * behavior of the code, so they are not applied automatically. + */ + suggest?: SuggestedEdit[] | null | undefined; +} +type ViolationMessage = { + message: string; +} | { + messageId: MessageIds; +}; +type ViolationLocation = { + loc: SourceLocation | Position; +} | { + node: Node; +}; +export type ViolationReport = ViolationReportBase & ViolationMessage & ViolationLocation; +interface SuggestedEditBase { + /** + * The data to insert into the message. + */ + data?: Record | undefined; + /** + * The fix to be applied for the suggestion. + */ + fix?: RuleFixer | null | undefined; +} +type SuggestionMessage = { + desc: string; +} | { + messageId: string; +}; +/** + * A suggested edit for a rule violation. + */ +export type SuggestedEdit = SuggestedEditBase & SuggestionMessage; +/** + * Generic options for the `RuleDefinition` type. + */ +export interface RuleDefinitionTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RuleOptions: unknown[]; + Visitor: RuleVisitor; + Node: unknown; + MessageIds: string; + ExtRuleDocs: unknown; +} +/** + * The definition of an ESLint rule. + */ +export interface RuleDefinition { + /** + * The meta information for the rule. + */ + meta?: RulesMeta; + /** + * Creates the visitor that ESLint uses to apply the rule during traversal. + * @param context The rule context. + * @returns The rule visitor. + */ + create(context: RuleContext<{ + LangOptions: Options["LangOptions"]; + Code: Options["Code"]; + RuleOptions: Options["RuleOptions"]; + Node: Options["Node"]; + MessageIds: Options["MessageIds"]; + }>): Options["Visitor"]; +} +/** + * Defaults for non-language-related `RuleDefinition` options. + */ +export interface CustomRuleTypeDefinitions { + RuleOptions: unknown[]; + MessageIds: string; + ExtRuleDocs: Record; +} +/** + * A helper type to define language specific specializations of the `RuleDefinition` type. + * + * @example + * ```ts + * type YourRuleDefinition< + * Options extends Partial = {}, + * > = CustomRuleDefinitionType< + * { + * LangOptions: YourLanguageOptions; + * Code: YourSourceCode; + * Visitor: YourRuleVisitor; + * Node: YourNode; + * }, + * Options + * >; + * ``` + */ +export type CustomRuleDefinitionType, Options extends Partial> = RuleDefinition>>; +/** + * The human readable severity level used in a configuration. + */ +export type SeverityName = "off" | "warn" | "error"; +/** + * The numeric severity level for a rule. + * + * - `0` means off. + * - `1` means warn. + * - `2` means error. + */ +export type SeverityLevel = 0 | 1 | 2; +/** + * The severity of a rule in a configuration. + */ +export type Severity = SeverityName | SeverityLevel; +/** + * Represents the configuration options for the core linter. + */ +export interface LinterOptionsConfig { + /** + * Indicates whether or not inline configuration is evaluated. + */ + noInlineConfig?: boolean; + /** + * Indicates what to do when an unused disable directive is found. + */ + reportUnusedDisableDirectives?: boolean | Severity; + /** + * A severity value indicating if and how unused inline configs should be + * tracked and reported. + */ + reportUnusedInlineConfigs?: Severity; +} +/** + * The configuration for a rule. + */ +export type RuleConfig = Severity | [Severity, ...RuleOptions]; +/** + * A collection of rules and their configurations. + */ +export interface RulesConfig { + [key: string]: RuleConfig; +} +/** + * A collection of settings. + */ +export interface SettingsConfig { + [key: string]: unknown; +} +/** + * Generic options for the `Language` type. + */ +export interface LanguageTypeOptions { + LangOptions: LanguageOptions; + Code: SourceCode; + RootNode: unknown; + Node: unknown; +} +/** + * Represents a plugin language. + */ +export interface Language { + /** + * Indicates how ESLint should read the file. + */ + fileType: "text"; + /** + * First line number returned from the parser (text mode only). + */ + lineStart: 0 | 1; + /** + * First column number returned from the parser (text mode only). + */ + columnStart: 0 | 1; + /** + * The property to read the node type from. Used in selector querying. + */ + nodeTypeKey: string; + /** + * The traversal path that tools should take when evaluating the AST + */ + visitorKeys?: Record; + /** + * Default language options. User-defined options are merged with this object. + */ + defaultLanguageOptions?: LanguageOptions; + /** + * Validates languageOptions for this language. + */ + validateLanguageOptions(languageOptions: Options["LangOptions"]): void; + /** + * Normalizes languageOptions for this language. + */ + normalizeLanguageOptions?(languageOptions: Options["LangOptions"]): Options["LangOptions"]; + /** + * Helper for esquery that allows languages to match nodes against + * class. esquery currently has classes like `function` that will + * match all the various function nodes. This method allows languages + * to implement similar shorthands. + */ + matchesSelectorClass?(className: string, node: Options["Node"], ancestry: Options["Node"][]): boolean; + /** + * Parses the given file input into its component parts. This file should not + * throws errors for parsing errors but rather should return any parsing + * errors as parse of the ParseResult object. + */ + parse(file: File, context: LanguageContext): ParseResult; + /** + * Creates SourceCode object that ESLint uses to work with a file. + */ + createSourceCode(file: File, input: OkParseResult, context: LanguageContext): Options["Code"]; +} +/** + * Plugin-defined options for the language. + */ +export type LanguageOptions = Record; +/** + * The context object that is passed to the language plugin methods. + */ +export interface LanguageContext { + languageOptions: LangOptions; +} +/** + * Represents a file read by ESLint. + */ +export interface File { + /** + * The path that ESLint uses for this file. May be a virtual path + * if it was returned by a processor. + */ + path: string; + /** + * The path to the file on disk. This always maps directly to a file + * regardless of whether it was returned from a processor. + */ + physicalPath: string; + /** + * Indicates if the original source contained a byte-order marker. + * ESLint strips the BOM from the `body`, but this info is needed + * to correctly apply autofixing. + */ + bom: boolean; + /** + * The body of the file to parse. + */ + body: string | Uint8Array; +} +/** + * Represents the successful result of parsing a file. + */ +export interface OkParseResult { + /** + * Indicates if the parse was successful. If true, the parse was successful + * and ESLint should continue on to create a SourceCode object and run rules; + * if false, ESLint should just report the error(s) without doing anything + * else. + */ + ok: true; + /** + * The abstract syntax tree created by the parser. (only when ok: true) + */ + ast: RootNode; + /** + * Any additional data that the parser wants to provide. + */ + [key: string]: any; +} +/** + * Represents the unsuccessful result of parsing a file. + */ +export interface NotOkParseResult { + /** + * Indicates if the parse was successful. If true, the parse was successful + * and ESLint should continue on to create a SourceCode object and run rules; + * if false, ESLint should just report the error(s) without doing anything + * else. + */ + ok: false; + /** + * Any parsing errors, whether fatal or not. (only when ok: false) + */ + errors: FileError[]; + /** + * Any additional data that the parser wants to provide. + */ + [key: string]: any; +} +export type ParseResult = OkParseResult | NotOkParseResult; +/** + * Represents inline configuration found in the source code. + */ +interface InlineConfigElement { + /** + * The location of the inline config element. + */ + loc: SourceLocation; + /** + * The interpreted configuration from the inline config element. + */ + config: { + rules: RulesConfig; + }; +} +/** + * Generic options for the `SourceCodeBase` type. + */ +export interface SourceCodeBaseTypeOptions { + LangOptions: LanguageOptions; + RootNode: unknown; + SyntaxElementWithLoc: unknown; + ConfigNode: unknown; +} +/** + * Represents the basic interface for a source code object. + */ +interface SourceCodeBase { + /** + * Root of the AST. + */ + ast: Options["RootNode"]; + /** + * The traversal path that tools should take when evaluating the AST. + * When present, this overrides the `visitorKeys` on the language for + * just this source code object. + */ + visitorKeys?: Record; + /** + * Retrieves the equivalent of `loc` for a given node or token. + * @param syntaxElement The node or token to get the location for. + * @returns The location of the node or token. + */ + getLoc(syntaxElement: Options["SyntaxElementWithLoc"]): SourceLocation; + /** + * Retrieves the equivalent of `range` for a given node or token. + * @param syntaxElement The node or token to get the range for. + * @returns The range of the node or token. + */ + getRange(syntaxElement: Options["SyntaxElementWithLoc"]): SourceRange; + /** + * Traversal of AST. + */ + traverse(): Iterable; + /** + * Applies language options passed in from the ESLint core. + */ + applyLanguageOptions?(languageOptions: Options["LangOptions"]): void; + /** + * Return all of the inline areas where ESLint should be disabled/enabled + * along with any problems found in evaluating the directives. + */ + getDisableDirectives?(): { + directives: Directive[]; + problems: FileProblem[]; + }; + /** + * Returns an array of all inline configuration nodes found in the + * source code. + */ + getInlineConfigNodes?(): Options["ConfigNode"][]; + /** + * Applies configuration found inside of the source code. This method is only + * called when ESLint is running with inline configuration allowed. + */ + applyInlineConfig?(): { + configs: InlineConfigElement[]; + problems: FileProblem[]; + }; + /** + * Called by ESLint core to indicate that it has finished providing + * information. We now add in all the missing variables and ensure that + * state-changing methods cannot be called by rules. + * @returns {void} + */ + finalize?(): void; +} +/** + * Represents the source of a text file being linted. + */ +export interface TextSourceCode extends SourceCodeBase { + /** + * The body of the file that you'd like rule developers to access. + */ + text: string; +} +/** + * Represents the source of a binary file being linted. + */ +export interface BinarySourceCode extends SourceCodeBase { + /** + * The body of the file that you'd like rule developers to access. + */ + body: Uint8Array; +} +export type SourceCode = TextSourceCode | BinarySourceCode; +/** + * Represents a traversal step visiting the AST. + */ +export interface VisitTraversalStep { + kind: 1; + target: unknown; + phase: 1 | 2; + args: unknown[]; +} +/** + * Represents a traversal step calling a function. + */ +export interface CallTraversalStep { + kind: 2; + target: string; + phase?: string; + args: unknown[]; +} +export type TraversalStep = VisitTraversalStep | CallTraversalStep; +/** + * The type of disable directive. This determines how ESLint will disable rules. + */ +export type DirectiveType = "disable" | "enable" | "disable-line" | "disable-next-line"; +/** + * Represents a disable directive. + */ +export interface Directive { + /** + * The type of directive. + */ + type: DirectiveType; + /** + * The node of the directive. May be in the AST or a comment/token. + */ + node: unknown; + /** + * The value of the directive. + */ + value: string; + /** + * The justification for the directive. + */ + justification?: string; +} +export {}; diff --git a/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/package.json b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/package.json new file mode 100644 index 00000000..8952f32d --- /dev/null +++ b/node_modules/@eslint/plugin-kit/node_modules/@eslint/core/package.json @@ -0,0 +1,50 @@ +{ + "name": "@eslint/core", + "version": "0.15.0", + "description": "Runtime-agnostic core of ESLint", + "type": "module", + "types": "./dist/esm/types.d.ts", + "exports": { + "types": { + "import": "./dist/esm/types.d.ts", + "require": "./dist/cjs/types.d.cts" + } + }, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "scripts": { + "build:cts": "node -e \"fs.cpSync('dist/esm/types.d.ts', 'dist/cjs/types.d.cts')\"", + "build": "tsc && npm run build:cts", + "test:jsr": "npx jsr@latest publish --dry-run", + "test:types": "tsc -p tests/types/tsconfig.json" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/rewrite.git", + "directory": "packages/core" + }, + "keywords": [ + "eslint", + "core" + ], + "author": "Nicholas C. Zakas", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/rewrite/issues" + }, + "homepage": "https://github.com/eslint/rewrite/tree/main/packages/core#readme", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "devDependencies": { + "json-schema": "^0.4.0", + "typescript": "^5.8.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/node_modules/@eslint/plugin-kit/package.json b/node_modules/@eslint/plugin-kit/package.json new file mode 100644 index 00000000..54e4446d --- /dev/null +++ b/node_modules/@eslint/plugin-kit/package.json @@ -0,0 +1,65 @@ +{ + "name": "@eslint/plugin-kit", + "version": "0.3.2", + "description": "Utilities for building ESLint plugins.", + "author": "Nicholas C. Zakas", + "type": "module", + "main": "dist/esm/index.js", + "types": "dist/esm/index.d.ts", + "exports": { + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + }, + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + } + }, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/rewrite.git", + "directory": "packages/plugin-kit" + }, + "bugs": { + "url": "https://github.com/eslint/rewrite/issues" + }, + "homepage": "https://github.com/eslint/rewrite/tree/main/packages/plugin-kit#readme", + "scripts": { + "build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js", + "build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts", + "build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts", + "pretest": "npm run build", + "test": "mocha tests/", + "test:coverage": "c8 npm test", + "test:jsr": "npx jsr@latest publish --dry-run", + "test:types": "tsc -p tests/types/tsconfig.json" + }, + "keywords": [ + "eslint", + "eslintplugin", + "eslint-plugin" + ], + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.15.0", + "levn": "^0.4.1" + }, + "devDependencies": { + "@types/levn": "^0.4.0", + "c8": "^9.1.0", + "mocha": "^10.4.0", + "rollup": "^4.16.2", + "rollup-plugin-copy": "^3.5.0", + "typescript": "^5.4.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/node_modules/@humanfs/core/LICENSE b/node_modules/@humanfs/core/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@humanfs/core/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@humanfs/core/README.md b/node_modules/@humanfs/core/README.md new file mode 100644 index 00000000..4f86d14d --- /dev/null +++ b/node_modules/@humanfs/core/README.md @@ -0,0 +1,140 @@ +# `@humanfs/core` + +by [Nicholas C. Zakas](https://humanwhocodes.com) + +If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate) or [nominate me](https://stars.github.com/nominate/) for a GitHub Star. + +## Description + +The core functionality for humanfs that is shared across all implementations for all runtimes. The contents of this package are intentionally runtime agnostic and are not intended to be used alone. + +Currently, this package simply exports the `Hfs` class, which is an abstract base class intended to be inherited from in runtime-specific hfs packages (like `@humanfs/node`). + +> [!WARNING] +> This project is **experimental** and may change significantly before v1.0.0. Use at your own caution and definitely not in production! + +## Installation + +### Node.js + +Install using your favorite package manager for Node.js: + +```shell +npm install @humanfs/core + +# or + +pnpm install @humanfs/core + +# or + +yarn add @humanfs/core + +# or + +bun install @humanfs/core +``` + +Then you can import the `Hfs` and `Path` classes like this: + +```js +import { Hfs, Path } from "@humanfs/core"; +``` + +### Deno + +Install using [JSR](https://jsr.io): + +```shell +deno add @humanfs/core + +# or + +jsr add @humanfs/core +``` + +Then you can import the `Hfs` class like this: + +```js +import { Hfs, Path } from "@humanfs/core"; +``` + +### Browser + +It's recommended to import the minified version to save bandwidth: + +```js +import { Hfs, Path } from "https://cdn.skypack.dev/@humanfs/core?min"; +``` + +However, you can also import the unminified version for debugging purposes: + +```js +import { Hfs, Path } from "https://cdn.skypack.dev/@humanfs/core"; +``` + +## Usage + +### `Hfs` Class + +The `Hfs` class contains all of the basic functionality for an `Hfs` instance *without* a predefined impl. This class is mostly used for creating runtime-specific impls, such as `NodeHfs` and `DenoHfs`. + +You can create your own instance by providing an `impl` directly: + +```js +const hfs = new Hfs({ impl: { async text() {} }}); +``` + +The specified `impl` becomes the base impl for the instance, meaning you can always reset back to it using `resetImpl()`. + +You can also inherit from `Hfs` to create your own class with a preconfigured impl, such as: + +```js +class MyHfs extends Hfs { + constructor() { + super({ + impl: myImpl + }); + } +} +``` + +### `Path` Class + +The `Path` class represents the path to a directory or file within a file system. It's an abstract representation that can be used even outside of traditional file systems where string paths might not make sense. + +```js +const myPath = new Path(["dir", "subdir"]); +console.log(myPath.toString()); // "dir/subdir" + +// add another step +myPath.push("file.txt"); +console.log(myPath.toString()); // "dir/subdir/file.txt" + +// get just the last step +console.log(myPath.name); // "file.txt" + +// change just the last step +myPath.name = "file.json"; +console.log(myPath.name); // "file.json" +console.log(myPath.toString()); // "dir/subdir/file.json" + +// get the size of the path +console.log(myPath.size); // 3 + +// remove the last step +myPath.pop(); +console.log(myPath.toString()); // "dir/subdir" + +// iterate over the steps +for (const step of myPath) { + // do something +} + +// create a new path from a string +const newPath = Path.fromString("/foo/bar"); +``` + +## License + +Apache 2.0 diff --git a/node_modules/@humanfs/core/dist/errors.d.ts b/node_modules/@humanfs/core/dist/errors.d.ts new file mode 100644 index 00000000..c885bbf4 --- /dev/null +++ b/node_modules/@humanfs/core/dist/errors.d.ts @@ -0,0 +1,64 @@ +/** + * @fileoverview Common error classes + * @author Nicholas C. Zakas + */ +/** + * Error thrown when a file or directory is not found. + */ +export class NotFoundError extends Error { + /** + * Creates a new instance. + * @param {string} message The error message. + */ + constructor(message: string); + /** + * Error code. + * @type {string} + */ + code: string; +} +/** + * Error thrown when an operation is not permitted. + */ +export class PermissionError extends Error { + /** + * Creates a new instance. + * @param {string} message The error message. + */ + constructor(message: string); + /** + * Error code. + * @type {string} + */ + code: string; +} +/** + * Error thrown when an operation is not allowed on a directory. + */ +export class DirectoryError extends Error { + /** + * Creates a new instance. + * @param {string} message The error message. + */ + constructor(message: string); + /** + * Error code. + * @type {string} + */ + code: string; +} +/** + * Error thrown when a directory is not empty. + */ +export class NotEmptyError extends Error { + /** + * Creates a new instance. + * @param {string} message The error message. + */ + constructor(message: string); + /** + * Error code. + * @type {string} + */ + code: string; +} diff --git a/node_modules/@humanfs/core/dist/fsx.d.ts b/node_modules/@humanfs/core/dist/fsx.d.ts new file mode 100644 index 00000000..ef85093a --- /dev/null +++ b/node_modules/@humanfs/core/dist/fsx.d.ts @@ -0,0 +1,193 @@ +/** + * @fileoverview The main file for the hfs package. + * @author Nicholas C. Zakas + */ +/** @typedef{import("@humanfs/types").HfsImpl} HfsImpl */ +/** @typedef{import("@humanfs/types").HfsDirectoryEntry} HfsDirectoryEntry */ +/** + * Error to represent when a method is missing on an impl. + */ +export class NoSuchMethodError extends Error { + /** + * Creates a new instance. + * @param {string} methodName The name of the method that was missing. + */ + constructor(methodName: string); +} +/** + * Error to represent when an impl is already set. + */ +export class ImplAlreadySetError extends Error { + /** + * Creates a new instance. + */ + constructor(); +} +/** + * A class representing a log entry. + */ +export class LogEntry { + /** + * Creates a new instance. + * @param {string} type The type of log entry. + * @param {any} [data] The data associated with the log entry. + */ + constructor(type: string, data?: any); + /** + * The time at which the log entry was created. + * @type {number} + */ + timestamp: number; + methodName: string; + data: any; + #private; +} +/** + * A class representing a file system utility library. + * @implements {HfsImpl} + */ +export class Hfs implements HfsImpl { + /** + * Creates a new instance. + * @param {object} options The options for the instance. + * @param {HfsImpl} options.impl The implementation to use. + */ + constructor({ impl }: { + impl: HfsImpl; + }); + /** + * Starts a new log with the given name. + * @param {string} name The name of the log to start; + * @returns {void} + * @throws {Error} When the log already exists. + * @throws {TypeError} When the name is not a non-empty string. + */ + logStart(name: string): void; + /** + * Ends a log with the given name and returns the entries. + * @param {string} name The name of the log to end. + * @returns {Array} The entries in the log. + * @throws {Error} When the log does not exist. + */ + logEnd(name: string): Array; + /** + * Determines if the current implementation is the base implementation. + * @returns {boolean} True if the current implementation is the base implementation. + */ + isBaseImpl(): boolean; + /** + * Sets the implementation for this instance. + * @param {object} impl The implementation to use. + * @returns {void} + */ + setImpl(impl: object): void; + /** + * Resets the implementation for this instance back to its original. + * @returns {void} + */ + resetImpl(): void; + /** + * Reads the given file and returns the contents as text. Assumes UTF-8 encoding. + * @param {string} filePath The file to read. + * @returns {Promise} The contents of the file. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + text(filePath: string): Promise; + /** + * Reads the given file and returns the contents as JSON. Assumes UTF-8 encoding. + * @param {string} filePath The file to read. + * @returns {Promise} The contents of the file as JSON. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {SyntaxError} When the file contents are not valid JSON. + * @throws {TypeError} When the file path is not a non-empty string. + */ + json(filePath: string): Promise; + /** + * Reads the given file and returns the contents as an ArrayBuffer. + * @param {string} filePath The file to read. + * @returns {Promise} The contents of the file as an ArrayBuffer. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + * @deprecated Use bytes() instead. + */ + arrayBuffer(filePath: string): Promise; + /** + * Reads the given file and returns the contents as an Uint8Array. + * @param {string} filePath The file to read. + * @returns {Promise} The contents of the file as an Uint8Array. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + bytes(filePath: string): Promise; + /** + * Writes the given data to the given file. Creates any necessary directories along the way. + * If the data is a string, UTF-8 encoding is used. + * @param {string} filePath The file to write. + * @param {any} contents The data to write. + * @returns {Promise} A promise that resolves when the file is written. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + write(filePath: string, contents: any): Promise; + /** + * Determines if the given file exists. + * @param {string} filePath The file to check. + * @returns {Promise} True if the file exists. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + isFile(filePath: string): Promise; + /** + * Determines if the given directory exists. + * @param {string} dirPath The directory to check. + * @returns {Promise} True if the directory exists. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the directory path is not a non-empty string. + */ + isDirectory(dirPath: string): Promise; + /** + * Creates the given directory. + * @param {string} dirPath The directory to create. + * @returns {Promise} A promise that resolves when the directory is created. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the directory path is not a non-empty string. + */ + createDirectory(dirPath: string): Promise; + /** + * Deletes the given file. + * @param {string} filePath The file to delete. + * @returns {Promise} A promise that resolves when the file is deleted. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + delete(filePath: string): Promise; + /** + * Deletes the given directory. + * @param {string} dirPath The directory to delete. + * @returns {Promise} A promise that resolves when the directory is deleted. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the directory path is not a non-empty string. + */ + deleteAll(dirPath: string): Promise; + /** + * Returns a list of directory entries for the given path. + * @param {string} dirPath The path to the directory to read. + * @returns {AsyncIterable} A promise that resolves with the + * directory entries. + * @throws {TypeError} If the directory path is not a string. + * @throws {Error} If the directory cannot be read. + */ + list(dirPath: string): AsyncIterable; + /** + * Returns the size of the given file. + * @param {string} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the size of the file. + * @throws {TypeError} If the file path is not a string. + * @throws {Error} If the file cannot be read. + */ + size(filePath: string): Promise; + #private; +} +export type HfsImpl = import("@humanfs/types").HfsImpl; +export type HfsDirectoryEntry = import("@humanfs/types").HfsDirectoryEntry; diff --git a/node_modules/@humanfs/core/dist/hfs.d.ts b/node_modules/@humanfs/core/dist/hfs.d.ts new file mode 100644 index 00000000..69ec3681 --- /dev/null +++ b/node_modules/@humanfs/core/dist/hfs.d.ts @@ -0,0 +1,288 @@ +/** + * Error to represent when a method is missing on an impl. + */ +export class NoSuchMethodError extends Error { + /** + * Creates a new instance. + * @param {string} methodName The name of the method that was missing. + */ + constructor(methodName: string); +} +/** + * Error to represent when a method is not supported on an impl. This happens + * when a method on `Hfs` is called with one name and the corresponding method + * on the impl has a different name. (Example: `text()` and `bytes()`.) + */ +export class MethodNotSupportedError extends Error { + /** + * Creates a new instance. + * @param {string} methodName The name of the method that was missing. + */ + constructor(methodName: string); +} +/** + * Error to represent when an impl is already set. + */ +export class ImplAlreadySetError extends Error { + /** + * Creates a new instance. + */ + constructor(); +} +/** + * A class representing a log entry. + */ +export class LogEntry { + /** + * Creates a new instance. + * @param {string} type The type of log entry. + * @param {any} [data] The data associated with the log entry. + */ + constructor(type: string, data?: any); + /** + * The type of log entry. + * @type {string} + */ + type: string; + /** + * The data associated with the log entry. + * @type {any} + */ + data: any; + /** + * The time at which the log entry was created. + * @type {number} + */ + timestamp: number; +} +/** + * A class representing a file system utility library. + * @implements {HfsImpl} + */ +export class Hfs implements HfsImpl { + /** + * Creates a new instance. + * @param {object} options The options for the instance. + * @param {HfsImpl} options.impl The implementation to use. + */ + constructor({ impl }: { + impl: HfsImpl; + }); + /** + * Starts a new log with the given name. + * @param {string} name The name of the log to start; + * @returns {void} + * @throws {Error} When the log already exists. + * @throws {TypeError} When the name is not a non-empty string. + */ + logStart(name: string): void; + /** + * Ends a log with the given name and returns the entries. + * @param {string} name The name of the log to end. + * @returns {Array} The entries in the log. + * @throws {Error} When the log does not exist. + */ + logEnd(name: string): Array; + /** + * Determines if the current implementation is the base implementation. + * @returns {boolean} True if the current implementation is the base implementation. + */ + isBaseImpl(): boolean; + /** + * Sets the implementation for this instance. + * @param {object} impl The implementation to use. + * @returns {void} + */ + setImpl(impl: object): void; + /** + * Resets the implementation for this instance back to its original. + * @returns {void} + */ + resetImpl(): void; + /** + * Reads the given file and returns the contents as text. Assumes UTF-8 encoding. + * @param {string|URL} filePath The file to read. + * @returns {Promise} The contents of the file. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + text(filePath: string | URL): Promise; + /** + * Reads the given file and returns the contents as JSON. Assumes UTF-8 encoding. + * @param {string|URL} filePath The file to read. + * @returns {Promise} The contents of the file as JSON. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {SyntaxError} When the file contents are not valid JSON. + * @throws {TypeError} When the file path is not a non-empty string. + */ + json(filePath: string | URL): Promise; + /** + * Reads the given file and returns the contents as an ArrayBuffer. + * @param {string|URL} filePath The file to read. + * @returns {Promise} The contents of the file as an ArrayBuffer. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + * @deprecated Use bytes() instead. + */ + arrayBuffer(filePath: string | URL): Promise; + /** + * Reads the given file and returns the contents as an Uint8Array. + * @param {string|URL} filePath The file to read. + * @returns {Promise} The contents of the file as an Uint8Array. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + bytes(filePath: string | URL): Promise; + /** + * Writes the given data to the given file. Creates any necessary directories along the way. + * If the data is a string, UTF-8 encoding is used. + * @param {string|URL} filePath The file to write. + * @param {string|ArrayBuffer|ArrayBufferView} contents The data to write. + * @returns {Promise} A promise that resolves when the file is written. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + write(filePath: string | URL, contents: string | ArrayBuffer | ArrayBufferView): Promise; + /** + * Appends the given data to the given file. Creates any necessary directories along the way. + * If the data is a string, UTF-8 encoding is used. + * @param {string|URL} filePath The file to append to. + * @param {string|ArrayBuffer|ArrayBufferView} contents The data to append. + * @returns {Promise} A promise that resolves when the file is appended to. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + * @throws {TypeError} When the file contents are not a string or ArrayBuffer. + * @throws {Error} When the file cannot be appended to. + */ + append(filePath: string | URL, contents: string | ArrayBuffer | ArrayBufferView): Promise; + /** + * Determines if the given file exists. + * @param {string|URL} filePath The file to check. + * @returns {Promise} True if the file exists. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + isFile(filePath: string | URL): Promise; + /** + * Determines if the given directory exists. + * @param {string|URL} dirPath The directory to check. + * @returns {Promise} True if the directory exists. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the directory path is not a non-empty string. + */ + isDirectory(dirPath: string | URL): Promise; + /** + * Creates the given directory. + * @param {string|URL} dirPath The directory to create. + * @returns {Promise} A promise that resolves when the directory is created. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the directory path is not a non-empty string. + */ + createDirectory(dirPath: string | URL): Promise; + /** + * Deletes the given file or empty directory. + * @param {string|URL} filePath The file to delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted, true if the file or directory is deleted, false + * if the file or directory does not exist. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + delete(filePath: string | URL): Promise; + /** + * Deletes the given file or directory recursively. + * @param {string|URL} dirPath The directory to delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted, true if the file or directory is deleted, false + * if the file or directory does not exist. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the directory path is not a non-empty string. + */ + deleteAll(dirPath: string | URL): Promise; + /** + * Returns a list of directory entries for the given path. + * @param {string|URL} dirPath The path to the directory to read. + * @returns {AsyncIterable} A promise that resolves with the + * directory entries. + * @throws {TypeError} If the directory path is not a string or URL. + * @throws {Error} If the directory cannot be read. + */ + list(dirPath: string | URL): AsyncIterable; + /** + * Walks a directory using a depth-first traversal and returns the entries + * from the traversal. + * @param {string|URL} dirPath The path to the directory to walk. + * @param {Object} [options] The options for the walk. + * @param {(entry:HfsWalkEntry) => Promise|boolean} [options.directoryFilter] A filter function to determine + * if a directory's entries should be included in the walk. + * @param {(entry:HfsWalkEntry) => Promise|boolean} [options.entryFilter] A filter function to determine if + * an entry should be included in the walk. + * @returns {AsyncIterable} A promise that resolves with the + * directory entries. + * @throws {TypeError} If the directory path is not a string or URL. + * @throws {Error} If the directory cannot be read. + */ + walk(dirPath: string | URL, { directoryFilter, entryFilter }?: { + directoryFilter?: (entry: HfsWalkEntry) => Promise | boolean; + entryFilter?: (entry: HfsWalkEntry) => Promise | boolean; + }): AsyncIterable; + /** + * Returns the size of the given file. + * @param {string|URL} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the size of the file. + * @throws {TypeError} If the file path is not a string or URL. + * @throws {Error} If the file cannot be read. + */ + size(filePath: string | URL): Promise; + /** + * Returns the last modified timestamp of the given file or directory. + * @param {string|URL} fileOrDirPath The path to the file or directory. + * @returns {Promise} A promise that resolves with the last modified date + * or undefined if the file or directory does not exist. + * @throws {TypeError} If the path is not a string or URL. + */ + lastModified(fileOrDirPath: string | URL): Promise; + /** + * Copys a file from one location to another. + * @param {string|URL} source The path to the file to copy. + * @param {string|URL} destination The path to the new file. + * @returns {Promise} A promise that resolves when the file is copied. + * @throws {TypeError} If the file path is not a string or URL. + * @throws {Error} If the file cannot be copied. + */ + copy(source: string | URL, destination: string | URL): Promise; + /** + * Copies a file or directory from one location to another. + * @param {string|URL} source The path to the file or directory to copy. + * @param {string|URL} destination The path to copy the file or directory to. + * @returns {Promise} A promise that resolves when the file or directory is + * copied. + * @throws {TypeError} If the directory path is not a string or URL. + * @throws {Error} If the directory cannot be copied. + */ + copyAll(source: string | URL, destination: string | URL): Promise; + /** + * Moves a file from the source path to the destination path. + * @param {string|URL} source The location of the file to move. + * @param {string|URL} destination The destination of the file to move. + * @returns {Promise} A promise that resolves when the move is complete. + * @throws {TypeError} If the file or directory paths are not strings. + * @throws {Error} If the file or directory cannot be moved. + */ + move(source: string | URL, destination: string | URL): Promise; + /** + * Moves a file or directory from one location to another. + * @param {string|URL} source The path to the file or directory to move. + * @param {string|URL} destination The path to move the file or directory to. + * @returns {Promise} A promise that resolves when the file or directory is + * moved. + * @throws {TypeError} If the source is not a string or URL. + * @throws {TypeError} If the destination is not a string or URL. + * @throws {Error} If the file or directory cannot be moved. + */ + moveAll(source: string | URL, destination: string | URL): Promise; + #private; +} +export type HfsImpl = import("@humanfs/types").HfsImpl; +export type HfsDirectoryEntry = import("@humanfs/types").HfsDirectoryEntry; +export type HfsWalkEntry = import("@humanfs/types").HfsWalkEntry; diff --git a/node_modules/@humanfs/core/dist/index.d.ts b/node_modules/@humanfs/core/dist/index.d.ts new file mode 100644 index 00000000..d2dd30f1 --- /dev/null +++ b/node_modules/@humanfs/core/dist/index.d.ts @@ -0,0 +1,3 @@ +export { Hfs } from "./hfs.js"; +export { Path } from "./path.js"; +export * from "./errors.js"; diff --git a/node_modules/@humanfs/core/dist/path.d.ts b/node_modules/@humanfs/core/dist/path.d.ts new file mode 100644 index 00000000..6e29395b --- /dev/null +++ b/node_modules/@humanfs/core/dist/path.d.ts @@ -0,0 +1,82 @@ +export class Path { + /** + * Creates a new path based on the argument type. If the argument is a string, + * it is assumed to be a file or directory path and is converted to a Path + * instance. If the argument is a URL, it is assumed to be a file URL and is + * converted to a Path instance. If the argument is a Path instance, it is + * copied into a new Path instance. If the argument is an array, it is assumed + * to be the steps of a path and is used to create a new Path instance. + * @param {string|URL|Path|Array} pathish The value to convert to a Path instance. + * @returns {Path} A new Path instance. + * @throws {TypeError} When pathish is not a string, URL, Path, or Array. + * @throws {TypeError} When pathish is a string and is empty. + */ + static from(pathish: string | URL | Path | Array): Path; + /** + * Creates a new Path instance from a string. + * @param {string} fileOrDirPath The file or directory path to convert. + * @returns {Path} A new Path instance. + * @deprecated Use Path.from() instead. + */ + static fromString(fileOrDirPath: string): Path; + /** + * Creates a new Path instance from a URL. + * @param {URL} url The URL to convert. + * @returns {Path} A new Path instance. + * @throws {TypeError} When url is not a URL instance. + * @throws {TypeError} When url.pathname is empty. + * @throws {TypeError} When url.protocol is not "file:". + * @deprecated Use Path.from() instead. + */ + static fromURL(url: URL): Path; + /** + * Creates a new instance. + * @param {Iterable} [steps] The steps to use for the path. + * @throws {TypeError} When steps is not iterable. + */ + constructor(steps?: Iterable); + /** + * Adds steps to the end of the path. + * @param {...string} steps The steps to add to the path. + * @returns {void} + */ + push(...steps: string[]): void; + /** + * Removes the last step from the path. + * @returns {string} The last step in the path. + */ + pop(): string; + /** + * Returns an iterator for steps in the path. + * @returns {IterableIterator} An iterator for the steps in the path. + */ + steps(): IterableIterator; + /** + * Sets the name (the last step) of the path. + * @type {string} + */ + set name(value: string); + /** + * Retrieves the name (the last step) of the path. + * @type {string} + */ + get name(): string; + /** + * Retrieves the size of the path. + * @type {number} + */ + get size(): number; + /** + * Returns the path as a string. + * @returns {string} The path as a string. + */ + toString(): string; + /** + * Returns an iterator for the steps in the path. + * @returns {IterableIterator} An iterator for the steps in the path. + */ + [Symbol.iterator](): IterableIterator; + #private; +} +export type HfsImpl = import("@humanfs/types").HfsImpl; +export type HfsDirectoryEntry = import("@humanfs/types").HfsDirectoryEntry; diff --git a/node_modules/@humanfs/core/package.json b/node_modules/@humanfs/core/package.json new file mode 100644 index 00000000..e1f9f40f --- /dev/null +++ b/node_modules/@humanfs/core/package.json @@ -0,0 +1,52 @@ +{ + "name": "@humanfs/core", + "version": "0.19.1", + "description": "The core of the humanfs library.", + "type": "module", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + "import": { + "types": "./dist/index.d.ts", + "default": "./src/index.js" + } + }, + "files": [ + "dist", + "src" + ], + "scripts": { + "build": "tsc", + "prepare": "npm run build", + "pretest": "npm run build", + "test": "c8 mocha tests" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/humanwhocodes/humanfs.git" + }, + "publishConfig": { + "access": "public" + }, + "keywords": [ + "filesystem", + "fs", + "hfs", + "files" + ], + "author": "Nicholas C. Zakas", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/humanwhocodes/humanfs/issues" + }, + "homepage": "https://github.com/humanwhocodes/humanfs#readme", + "engines": { + "node": ">=18.18.0" + }, + "devDependencies": { + "@humanfs/types": "^0.15.0", + "c8": "^9.0.0", + "mocha": "^10.2.0", + "typescript": "^5.2.2" + } +} diff --git a/node_modules/@humanfs/core/src/errors.js b/node_modules/@humanfs/core/src/errors.js new file mode 100644 index 00000000..8fb35be7 --- /dev/null +++ b/node_modules/@humanfs/core/src/errors.js @@ -0,0 +1,105 @@ +/** + * @fileoverview Common error classes + * @author Nicholas C. Zakas + */ + +/** + * Error thrown when a file or directory is not found. + */ +export class NotFoundError extends Error { + /** + * Name of the error class. + * @type {string} + */ + name = "NotFoundError"; + + /** + * Error code. + * @type {string} + */ + code = "ENOENT"; + + /** + * Creates a new instance. + * @param {string} message The error message. + */ + constructor(message) { + super(`ENOENT: No such file or directory, ${message}`); + } +} + +/** + * Error thrown when an operation is not permitted. + */ +export class PermissionError extends Error { + /** + * Name of the error class. + * @type {string} + */ + name = "PermissionError"; + + /** + * Error code. + * @type {string} + */ + code = "EPERM"; + + /** + * Creates a new instance. + * @param {string} message The error message. + */ + constructor(message) { + super(`EPERM: Operation not permitted, ${message}`); + } +} + +/** + * Error thrown when an operation is not allowed on a directory. + */ + +export class DirectoryError extends Error { + /** + * Name of the error class. + * @type {string} + */ + name = "DirectoryError"; + + /** + * Error code. + * @type {string} + */ + code = "EISDIR"; + + /** + * Creates a new instance. + * @param {string} message The error message. + */ + constructor(message) { + super(`EISDIR: Illegal operation on a directory, ${message}`); + } +} + +/** + * Error thrown when a directory is not empty. + */ +export class NotEmptyError extends Error { + /** + * Name of the error class. + * @type {string} + */ + name = "NotEmptyError"; + + /** + * Error code. + * @type {string} + */ + code = "ENOTEMPTY"; + + /** + * Creates a new instance. + * @param {string} message The error message. + */ + constructor(message) { + super(`ENOTEMPTY: Directory not empty, ${message}`); + } +} diff --git a/node_modules/@humanfs/core/src/hfs.js b/node_modules/@humanfs/core/src/hfs.js new file mode 100644 index 00000000..38ee31c5 --- /dev/null +++ b/node_modules/@humanfs/core/src/hfs.js @@ -0,0 +1,699 @@ +/** + * @fileoverview The main file for the humanfs package. + * @author Nicholas C. Zakas + */ + +/* global URL, TextDecoder, TextEncoder */ + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("@humanfs/types").HfsImpl} HfsImpl */ +/** @typedef {import("@humanfs/types").HfsDirectoryEntry} HfsDirectoryEntry */ +/** @typedef {import("@humanfs/types").HfsWalkEntry} HfsWalkEntry */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); + +/** + * Error to represent when a method is missing on an impl. + */ +export class NoSuchMethodError extends Error { + /** + * Creates a new instance. + * @param {string} methodName The name of the method that was missing. + */ + constructor(methodName) { + super(`Method "${methodName}" does not exist on impl.`); + } +} + +/** + * Error to represent when a method is not supported on an impl. This happens + * when a method on `Hfs` is called with one name and the corresponding method + * on the impl has a different name. (Example: `text()` and `bytes()`.) + */ +export class MethodNotSupportedError extends Error { + /** + * Creates a new instance. + * @param {string} methodName The name of the method that was missing. + */ + constructor(methodName) { + super(`Method "${methodName}" is not supported on this impl.`); + } +} + +/** + * Error to represent when an impl is already set. + */ +export class ImplAlreadySetError extends Error { + /** + * Creates a new instance. + */ + constructor() { + super(`Implementation already set.`); + } +} + +/** + * Asserts that the given path is a valid file path. + * @param {any} fileOrDirPath The path to check. + * @returns {void} + * @throws {TypeError} When the path is not a non-empty string. + */ +function assertValidFileOrDirPath(fileOrDirPath) { + if ( + !fileOrDirPath || + (!(fileOrDirPath instanceof URL) && typeof fileOrDirPath !== "string") + ) { + throw new TypeError("Path must be a non-empty string or URL."); + } +} + +/** + * Asserts that the given file contents are valid. + * @param {any} contents The contents to check. + * @returns {void} + * @throws {TypeError} When the contents are not a string or ArrayBuffer. + */ +function assertValidFileContents(contents) { + if ( + typeof contents !== "string" && + !(contents instanceof ArrayBuffer) && + !ArrayBuffer.isView(contents) + ) { + throw new TypeError( + "File contents must be a string, ArrayBuffer, or ArrayBuffer view.", + ); + } +} + +/** + * Converts the given contents to Uint8Array. + * @param {any} contents The data to convert. + * @returns {Uint8Array} The converted Uint8Array. + * @throws {TypeError} When the contents are not a string or ArrayBuffer. + */ +function toUint8Array(contents) { + if (contents instanceof Uint8Array) { + return contents; + } + + if (typeof contents === "string") { + return encoder.encode(contents); + } + + if (contents instanceof ArrayBuffer) { + return new Uint8Array(contents); + } + + if (ArrayBuffer.isView(contents)) { + const bytes = contents.buffer.slice( + contents.byteOffset, + contents.byteOffset + contents.byteLength, + ); + return new Uint8Array(bytes); + } + throw new TypeError( + "Invalid contents type. Expected string or ArrayBuffer.", + ); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class representing a log entry. + */ +export class LogEntry { + /** + * The type of log entry. + * @type {string} + */ + type; + + /** + * The data associated with the log entry. + * @type {any} + */ + data; + + /** + * The time at which the log entry was created. + * @type {number} + */ + timestamp = Date.now(); + + /** + * Creates a new instance. + * @param {string} type The type of log entry. + * @param {any} [data] The data associated with the log entry. + */ + constructor(type, data) { + this.type = type; + this.data = data; + } +} + +/** + * A class representing a file system utility library. + * @implements {HfsImpl} + */ +export class Hfs { + /** + * The base implementation for this instance. + * @type {HfsImpl} + */ + #baseImpl; + + /** + * The current implementation for this instance. + * @type {HfsImpl} + */ + #impl; + + /** + * A map of log names to their corresponding entries. + * @type {Map>} + */ + #logs = new Map(); + + /** + * Creates a new instance. + * @param {object} options The options for the instance. + * @param {HfsImpl} options.impl The implementation to use. + */ + constructor({ impl }) { + this.#baseImpl = impl; + this.#impl = impl; + } + + /** + * Logs an entry onto all currently open logs. + * @param {string} methodName The name of the method being called. + * @param {...*} args The arguments to the method. + * @returns {void} + */ + #log(methodName, ...args) { + for (const logs of this.#logs.values()) { + logs.push(new LogEntry("call", { methodName, args })); + } + } + + /** + * Starts a new log with the given name. + * @param {string} name The name of the log to start; + * @returns {void} + * @throws {Error} When the log already exists. + * @throws {TypeError} When the name is not a non-empty string. + */ + logStart(name) { + if (!name || typeof name !== "string") { + throw new TypeError("Log name must be a non-empty string."); + } + + if (this.#logs.has(name)) { + throw new Error(`Log "${name}" already exists.`); + } + + this.#logs.set(name, []); + } + + /** + * Ends a log with the given name and returns the entries. + * @param {string} name The name of the log to end. + * @returns {Array} The entries in the log. + * @throws {Error} When the log does not exist. + */ + logEnd(name) { + if (this.#logs.has(name)) { + const logs = this.#logs.get(name); + this.#logs.delete(name); + return logs; + } + + throw new Error(`Log "${name}" does not exist.`); + } + + /** + * Determines if the current implementation is the base implementation. + * @returns {boolean} True if the current implementation is the base implementation. + */ + isBaseImpl() { + return this.#impl === this.#baseImpl; + } + + /** + * Sets the implementation for this instance. + * @param {object} impl The implementation to use. + * @returns {void} + */ + setImpl(impl) { + this.#log("implSet", impl); + + if (this.#impl !== this.#baseImpl) { + throw new ImplAlreadySetError(); + } + + this.#impl = impl; + } + + /** + * Resets the implementation for this instance back to its original. + * @returns {void} + */ + resetImpl() { + this.#log("implReset"); + this.#impl = this.#baseImpl; + } + + /** + * Asserts that the given method exists on the current implementation. + * @param {string} methodName The name of the method to check. + * @returns {void} + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + */ + #assertImplMethod(methodName) { + if (typeof this.#impl[methodName] !== "function") { + throw new NoSuchMethodError(methodName); + } + } + + /** + * Asserts that the given method exists on the current implementation, and if not, + * throws an error with a different method name. + * @param {string} methodName The name of the method to check. + * @param {string} targetMethodName The name of the method that should be reported + * as an error when methodName does not exist. + * @returns {void} + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + */ + #assertImplMethodAlt(methodName, targetMethodName) { + if (typeof this.#impl[methodName] !== "function") { + throw new MethodNotSupportedError(targetMethodName); + } + } + + /** + * Calls the given method on the current implementation. + * @param {string} methodName The name of the method to call. + * @param {...any} args The arguments to the method. + * @returns {any} The return value from the method. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + */ + #callImplMethod(methodName, ...args) { + this.#log(methodName, ...args); + this.#assertImplMethod(methodName); + return this.#impl[methodName](...args); + } + + /** + * Calls the given method on the current implementation and doesn't log the call. + * @param {string} methodName The name of the method to call. + * @param {...any} args The arguments to the method. + * @returns {any} The return value from the method. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + */ + #callImplMethodWithoutLog(methodName, ...args) { + this.#assertImplMethod(methodName); + return this.#impl[methodName](...args); + } + + /** + * Calls the given method on the current implementation but logs a different method name. + * @param {string} methodName The name of the method to call. + * @param {string} targetMethodName The name of the method to log. + * @param {...any} args The arguments to the method. + * @returns {any} The return value from the method. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + */ + #callImplMethodAlt(methodName, targetMethodName, ...args) { + this.#log(targetMethodName, ...args); + this.#assertImplMethodAlt(methodName, targetMethodName); + return this.#impl[methodName](...args); + } + + /** + * Reads the given file and returns the contents as text. Assumes UTF-8 encoding. + * @param {string|URL} filePath The file to read. + * @returns {Promise} The contents of the file. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + async text(filePath) { + assertValidFileOrDirPath(filePath); + + const result = await this.#callImplMethodAlt("bytes", "text", filePath); + return result ? decoder.decode(result) : undefined; + } + + /** + * Reads the given file and returns the contents as JSON. Assumes UTF-8 encoding. + * @param {string|URL} filePath The file to read. + * @returns {Promise} The contents of the file as JSON. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {SyntaxError} When the file contents are not valid JSON. + * @throws {TypeError} When the file path is not a non-empty string. + */ + async json(filePath) { + assertValidFileOrDirPath(filePath); + + const result = await this.#callImplMethodAlt("bytes", "json", filePath); + return result ? JSON.parse(decoder.decode(result)) : undefined; + } + + /** + * Reads the given file and returns the contents as an ArrayBuffer. + * @param {string|URL} filePath The file to read. + * @returns {Promise} The contents of the file as an ArrayBuffer. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + * @deprecated Use bytes() instead. + */ + async arrayBuffer(filePath) { + assertValidFileOrDirPath(filePath); + + const result = await this.#callImplMethodAlt( + "bytes", + "arrayBuffer", + filePath, + ); + return result?.buffer; + } + + /** + * Reads the given file and returns the contents as an Uint8Array. + * @param {string|URL} filePath The file to read. + * @returns {Promise} The contents of the file as an Uint8Array. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + async bytes(filePath) { + assertValidFileOrDirPath(filePath); + return this.#callImplMethod("bytes", filePath); + } + + /** + * Writes the given data to the given file. Creates any necessary directories along the way. + * If the data is a string, UTF-8 encoding is used. + * @param {string|URL} filePath The file to write. + * @param {string|ArrayBuffer|ArrayBufferView} contents The data to write. + * @returns {Promise} A promise that resolves when the file is written. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + async write(filePath, contents) { + assertValidFileOrDirPath(filePath); + assertValidFileContents(contents); + this.#log("write", filePath, contents); + + let value = toUint8Array(contents); + return this.#callImplMethodWithoutLog("write", filePath, value); + } + + /** + * Appends the given data to the given file. Creates any necessary directories along the way. + * If the data is a string, UTF-8 encoding is used. + * @param {string|URL} filePath The file to append to. + * @param {string|ArrayBuffer|ArrayBufferView} contents The data to append. + * @returns {Promise} A promise that resolves when the file is appended to. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + * @throws {TypeError} When the file contents are not a string or ArrayBuffer. + * @throws {Error} When the file cannot be appended to. + */ + async append(filePath, contents) { + assertValidFileOrDirPath(filePath); + assertValidFileContents(contents); + this.#log("append", filePath, contents); + + let value = toUint8Array(contents); + return this.#callImplMethodWithoutLog("append", filePath, value); + } + + /** + * Determines if the given file exists. + * @param {string|URL} filePath The file to check. + * @returns {Promise} True if the file exists. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + async isFile(filePath) { + assertValidFileOrDirPath(filePath); + return this.#callImplMethod("isFile", filePath); + } + + /** + * Determines if the given directory exists. + * @param {string|URL} dirPath The directory to check. + * @returns {Promise} True if the directory exists. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the directory path is not a non-empty string. + */ + async isDirectory(dirPath) { + assertValidFileOrDirPath(dirPath); + return this.#callImplMethod("isDirectory", dirPath); + } + + /** + * Creates the given directory. + * @param {string|URL} dirPath The directory to create. + * @returns {Promise} A promise that resolves when the directory is created. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the directory path is not a non-empty string. + */ + async createDirectory(dirPath) { + assertValidFileOrDirPath(dirPath); + return this.#callImplMethod("createDirectory", dirPath); + } + + /** + * Deletes the given file or empty directory. + * @param {string|URL} filePath The file to delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted, true if the file or directory is deleted, false + * if the file or directory does not exist. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the file path is not a non-empty string. + */ + async delete(filePath) { + assertValidFileOrDirPath(filePath); + return this.#callImplMethod("delete", filePath); + } + + /** + * Deletes the given file or directory recursively. + * @param {string|URL} dirPath The directory to delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted, true if the file or directory is deleted, false + * if the file or directory does not exist. + * @throws {NoSuchMethodError} When the method does not exist on the current implementation. + * @throws {TypeError} When the directory path is not a non-empty string. + */ + async deleteAll(dirPath) { + assertValidFileOrDirPath(dirPath); + return this.#callImplMethod("deleteAll", dirPath); + } + + /** + * Returns a list of directory entries for the given path. + * @param {string|URL} dirPath The path to the directory to read. + * @returns {AsyncIterable} A promise that resolves with the + * directory entries. + * @throws {TypeError} If the directory path is not a string or URL. + * @throws {Error} If the directory cannot be read. + */ + async *list(dirPath) { + assertValidFileOrDirPath(dirPath); + yield* await this.#callImplMethod("list", dirPath); + } + + /** + * Walks a directory using a depth-first traversal and returns the entries + * from the traversal. + * @param {string|URL} dirPath The path to the directory to walk. + * @param {Object} [options] The options for the walk. + * @param {(entry:HfsWalkEntry) => Promise|boolean} [options.directoryFilter] A filter function to determine + * if a directory's entries should be included in the walk. + * @param {(entry:HfsWalkEntry) => Promise|boolean} [options.entryFilter] A filter function to determine if + * an entry should be included in the walk. + * @returns {AsyncIterable} A promise that resolves with the + * directory entries. + * @throws {TypeError} If the directory path is not a string or URL. + * @throws {Error} If the directory cannot be read. + */ + async *walk( + dirPath, + { directoryFilter = () => true, entryFilter = () => true } = {}, + ) { + assertValidFileOrDirPath(dirPath); + this.#log("walk", dirPath, { directoryFilter, entryFilter }); + + // inner function for recursion without additional logging + const walk = async function* ( + dirPath, + { directoryFilter, entryFilter, parentPath = "", depth = 1 }, + ) { + let dirEntries; + + try { + dirEntries = await this.#callImplMethodWithoutLog( + "list", + dirPath, + ); + } catch (error) { + // if the directory does not exist then return an empty array + if (error.code === "ENOENT") { + return; + } + + // otherwise, rethrow the error + throw error; + } + + for await (const listEntry of dirEntries) { + const walkEntry = { + path: listEntry.name, + depth, + ...listEntry, + }; + + if (parentPath) { + walkEntry.path = `${parentPath}/${walkEntry.path}`; + } + + // first emit the entry but only if the entry filter returns true + let shouldEmitEntry = entryFilter(walkEntry); + if (shouldEmitEntry.then) { + shouldEmitEntry = await shouldEmitEntry; + } + + if (shouldEmitEntry) { + yield walkEntry; + } + + // if it's a directory then yield the entry and walk the directory + if (listEntry.isDirectory) { + // if the directory filter returns false, skip the directory + let shouldWalkDirectory = directoryFilter(walkEntry); + if (shouldWalkDirectory.then) { + shouldWalkDirectory = await shouldWalkDirectory; + } + + if (!shouldWalkDirectory) { + continue; + } + + // make sure there's a trailing slash on the directory path before appending + const directoryPath = + dirPath instanceof URL + ? new URL( + listEntry.name, + dirPath.href.endsWith("/") + ? dirPath.href + : `${dirPath.href}/`, + ) + : `${dirPath.endsWith("/") ? dirPath : `${dirPath}/`}${listEntry.name}`; + + yield* walk(directoryPath, { + directoryFilter, + entryFilter, + parentPath: walkEntry.path, + depth: depth + 1, + }); + } + } + }.bind(this); + + yield* walk(dirPath, { directoryFilter, entryFilter }); + } + + /** + * Returns the size of the given file. + * @param {string|URL} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the size of the file. + * @throws {TypeError} If the file path is not a string or URL. + * @throws {Error} If the file cannot be read. + */ + async size(filePath) { + assertValidFileOrDirPath(filePath); + return this.#callImplMethod("size", filePath); + } + + /** + * Returns the last modified timestamp of the given file or directory. + * @param {string|URL} fileOrDirPath The path to the file or directory. + * @returns {Promise} A promise that resolves with the last modified date + * or undefined if the file or directory does not exist. + * @throws {TypeError} If the path is not a string or URL. + */ + async lastModified(fileOrDirPath) { + assertValidFileOrDirPath(fileOrDirPath); + return this.#callImplMethod("lastModified", fileOrDirPath); + } + + /** + * Copys a file from one location to another. + * @param {string|URL} source The path to the file to copy. + * @param {string|URL} destination The path to the new file. + * @returns {Promise} A promise that resolves when the file is copied. + * @throws {TypeError} If the file path is not a string or URL. + * @throws {Error} If the file cannot be copied. + */ + async copy(source, destination) { + assertValidFileOrDirPath(source); + assertValidFileOrDirPath(destination); + return this.#callImplMethod("copy", source, destination); + } + + /** + * Copies a file or directory from one location to another. + * @param {string|URL} source The path to the file or directory to copy. + * @param {string|URL} destination The path to copy the file or directory to. + * @returns {Promise} A promise that resolves when the file or directory is + * copied. + * @throws {TypeError} If the directory path is not a string or URL. + * @throws {Error} If the directory cannot be copied. + */ + async copyAll(source, destination) { + assertValidFileOrDirPath(source); + assertValidFileOrDirPath(destination); + return this.#callImplMethod("copyAll", source, destination); + } + + /** + * Moves a file from the source path to the destination path. + * @param {string|URL} source The location of the file to move. + * @param {string|URL} destination The destination of the file to move. + * @returns {Promise} A promise that resolves when the move is complete. + * @throws {TypeError} If the file or directory paths are not strings. + * @throws {Error} If the file or directory cannot be moved. + */ + async move(source, destination) { + assertValidFileOrDirPath(source); + assertValidFileOrDirPath(destination); + return this.#callImplMethod("move", source, destination); + } + + /** + * Moves a file or directory from one location to another. + * @param {string|URL} source The path to the file or directory to move. + * @param {string|URL} destination The path to move the file or directory to. + * @returns {Promise} A promise that resolves when the file or directory is + * moved. + * @throws {TypeError} If the source is not a string or URL. + * @throws {TypeError} If the destination is not a string or URL. + * @throws {Error} If the file or directory cannot be moved. + */ + async moveAll(source, destination) { + assertValidFileOrDirPath(source); + assertValidFileOrDirPath(destination); + return this.#callImplMethod("moveAll", source, destination); + } +} diff --git a/node_modules/@humanfs/core/src/index.js b/node_modules/@humanfs/core/src/index.js new file mode 100644 index 00000000..1b662d48 --- /dev/null +++ b/node_modules/@humanfs/core/src/index.js @@ -0,0 +1,8 @@ +/** + * @fileoverview API entrypoint for hfs/core + * @author Nicholas C. Zakas + */ + +export { Hfs } from "./hfs.js"; +export { Path } from "./path.js"; +export * from "./errors.js"; diff --git a/node_modules/@humanfs/core/src/path.js b/node_modules/@humanfs/core/src/path.js new file mode 100644 index 00000000..4798091b --- /dev/null +++ b/node_modules/@humanfs/core/src/path.js @@ -0,0 +1,237 @@ +/** + * @fileoverview The Path class. + * @author Nicholas C. Zakas + */ + +/* globals URL */ + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef{import("@humanfs/types").HfsImpl} HfsImpl */ +/** @typedef{import("@humanfs/types").HfsDirectoryEntry} HfsDirectoryEntry */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Normalizes a path to use forward slashes. + * @param {string} filePath The path to normalize. + * @returns {string} The normalized path. + */ +function normalizePath(filePath) { + let startIndex = 0; + let endIndex = filePath.length; + + if (/[a-z]:\//i.test(filePath)) { + startIndex = 3; + } + + if (filePath.startsWith("./")) { + startIndex = 2; + } + + if (filePath.startsWith("/")) { + startIndex = 1; + } + + if (filePath.endsWith("/")) { + endIndex = filePath.length - 1; + } + + return filePath.slice(startIndex, endIndex).replace(/\\/g, "/"); +} + +/** + * Asserts that the given name is a non-empty string, no equal to "." or "..", + * and does not contain a forward slash or backslash. + * @param {string} name The name to check. + * @returns {void} + * @throws {TypeError} When name is not valid. + */ +function assertValidName(name) { + if (typeof name !== "string") { + throw new TypeError("name must be a string"); + } + + if (!name) { + throw new TypeError("name cannot be empty"); + } + + if (name === ".") { + throw new TypeError(`name cannot be "."`); + } + + if (name === "..") { + throw new TypeError(`name cannot be ".."`); + } + + if (name.includes("/") || name.includes("\\")) { + throw new TypeError( + `name cannot contain a slash or backslash: "${name}"`, + ); + } +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +export class Path { + /** + * The steps in the path. + * @type {Array} + */ + #steps; + + /** + * Creates a new instance. + * @param {Iterable} [steps] The steps to use for the path. + * @throws {TypeError} When steps is not iterable. + */ + constructor(steps = []) { + if (typeof steps[Symbol.iterator] !== "function") { + throw new TypeError("steps must be iterable"); + } + + this.#steps = [...steps]; + this.#steps.forEach(assertValidName); + } + + /** + * Adds steps to the end of the path. + * @param {...string} steps The steps to add to the path. + * @returns {void} + */ + push(...steps) { + steps.forEach(assertValidName); + this.#steps.push(...steps); + } + + /** + * Removes the last step from the path. + * @returns {string} The last step in the path. + */ + pop() { + return this.#steps.pop(); + } + + /** + * Returns an iterator for steps in the path. + * @returns {IterableIterator} An iterator for the steps in the path. + */ + steps() { + return this.#steps.values(); + } + + /** + * Returns an iterator for the steps in the path. + * @returns {IterableIterator} An iterator for the steps in the path. + */ + [Symbol.iterator]() { + return this.steps(); + } + + /** + * Retrieves the name (the last step) of the path. + * @type {string} + */ + get name() { + return this.#steps[this.#steps.length - 1]; + } + + /** + * Sets the name (the last step) of the path. + * @type {string} + */ + set name(value) { + assertValidName(value); + this.#steps[this.#steps.length - 1] = value; + } + + /** + * Retrieves the size of the path. + * @type {number} + */ + get size() { + return this.#steps.length; + } + + /** + * Returns the path as a string. + * @returns {string} The path as a string. + */ + toString() { + return this.#steps.join("/"); + } + + /** + * Creates a new path based on the argument type. If the argument is a string, + * it is assumed to be a file or directory path and is converted to a Path + * instance. If the argument is a URL, it is assumed to be a file URL and is + * converted to a Path instance. If the argument is a Path instance, it is + * copied into a new Path instance. If the argument is an array, it is assumed + * to be the steps of a path and is used to create a new Path instance. + * @param {string|URL|Path|Array} pathish The value to convert to a Path instance. + * @returns {Path} A new Path instance. + * @throws {TypeError} When pathish is not a string, URL, Path, or Array. + * @throws {TypeError} When pathish is a string and is empty. + */ + static from(pathish) { + if (typeof pathish === "string") { + if (!pathish) { + throw new TypeError("argument cannot be empty"); + } + + return Path.fromString(pathish); + } + + if (pathish instanceof URL) { + return Path.fromURL(pathish); + } + + if (pathish instanceof Path || Array.isArray(pathish)) { + return new Path(pathish); + } + + throw new TypeError("argument must be a string, URL, Path, or Array"); + } + + /** + * Creates a new Path instance from a string. + * @param {string} fileOrDirPath The file or directory path to convert. + * @returns {Path} A new Path instance. + * @deprecated Use Path.from() instead. + */ + static fromString(fileOrDirPath) { + return new Path(normalizePath(fileOrDirPath).split("/")); + } + + /** + * Creates a new Path instance from a URL. + * @param {URL} url The URL to convert. + * @returns {Path} A new Path instance. + * @throws {TypeError} When url is not a URL instance. + * @throws {TypeError} When url.pathname is empty. + * @throws {TypeError} When url.protocol is not "file:". + * @deprecated Use Path.from() instead. + */ + static fromURL(url) { + if (!(url instanceof URL)) { + throw new TypeError("url must be a URL instance"); + } + + if (!url.pathname || url.pathname === "/") { + throw new TypeError("url.pathname cannot be empty"); + } + + if (url.protocol !== "file:") { + throw new TypeError(`url.protocol must be "file:"`); + } + + // Remove leading slash in pathname + return new Path(normalizePath(url.pathname.slice(1)).split("/")); + } +} diff --git a/node_modules/@humanfs/node/LICENSE b/node_modules/@humanfs/node/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@humanfs/node/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@humanfs/node/README.md b/node_modules/@humanfs/node/README.md new file mode 100644 index 00000000..c3e4be47 --- /dev/null +++ b/node_modules/@humanfs/node/README.md @@ -0,0 +1,141 @@ +# `@humanfs/node` + +by [Nicholas C. Zakas](https://humanwhocodes.com) + +If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate) or [nominate me](https://stars.github.com/nominate/) for a GitHub Star. + +## Description + +The `hfs` bindings for use in Node.js and Node.js-compatible runtimes. + +> [!WARNING] +> This project is **experimental** and may change significantly before v1.0.0. Use at your own caution and definitely not in production! + +## Installation + +Install using your favorite package manager: + +```shell +npm install @humanfs/node + +# or + +pnpm install @humanfs/node + +# or + +yarn add @humanfs/node + +# or + +bun install @humanfs/node +``` + +## Usage + +The easiest way to use hfs in your project is to import the `hfs` object: + +```js +import { hfs } from "@humanfs/node"; +``` + +Then, you can use the API methods: + +```js +// 1. Files + +// read from a text file +const text = await hfs.text("file.txt"); + +// read from a JSON file +const json = await hfs.json("file.json"); + +// read raw bytes from a text file +const arrayBuffer = await hfs.arrayBuffer("file.txt"); + +// write text to a file +await hfs.write("file.txt", "Hello world!"); + +// write bytes to a file +await hfs.write("file.txt", new TextEncoder().encode("Hello world!")); + +// append text to a file +await hfs.append("file.txt", "Hello world!"); + +// append bytes to a file +await hfs.append("file.txt", new TextEncoder().encode("Hello world!")); + +// does the file exist? +const found = await hfs.isFile("file.txt"); + +// how big is the file? +const size = await hfs.size("file.txt"); + +// when was the file modified? +const mtime = await hfs.lastModified("file.txt"); + +// copy a file from one location to another +await hfs.copy("file.txt", "file-copy.txt"); + +// move a file from one location to another +await hfs.move("file.txt", "renamed.txt"); + +// delete a file +await hfs.delete("file.txt"); + +// 2. Directories + +// create a directory +await hfs.createDirectory("dir"); + +// create a directory recursively +await hfs.createDirectory("dir/subdir"); + +// does the directory exist? +const dirFound = await hfs.isDirectory("dir"); + +// copy the entire directory +hfs.copyAll("from-dir", "to-dir"); + +// move the entire directory +hfs.moveAll("from-dir", "to-dir"); + +// delete a directory +await hfs.delete("dir"); + +// delete a non-empty directory +await hfs.deleteAll("dir"); +``` + +If you'd like to create your own instance, import the `NodeHfs` constructor: + +```js +import { NodeHfs } from "@humanfs/node"; +import fsp from "fs/promises"; + +const hfs = new NodeHfs(); + +// optionally specify the fs/promises object to use +const hfs = new NodeHfs({ fsp }); +``` + +If you'd like to use just the impl, import the `NodeHfsImpl` constructor: + +```js +import { NodeHfsImpl } from "@humanfs/node"; +import fsp from "fs/promises"; + +const hfs = new NodeHfsImpl(); + +// optionally specify the fs/promises object to use +const hfs = new NodeHfsImpl({ fsp }); +``` + +## Errors Handled + +* `ENOENT` - in most cases, these errors are handled silently. +* `ENFILE` and `EMFILE` - calls that result in these errors are retried for up to 60 seconds before giving up for good. + +## License + +Apache 2.0 diff --git a/node_modules/@humanfs/node/dist/index.d.ts b/node_modules/@humanfs/node/dist/index.d.ts new file mode 100644 index 00000000..c2d1d306 --- /dev/null +++ b/node_modules/@humanfs/node/dist/index.d.ts @@ -0,0 +1,2 @@ +export * from "./node-hfs.js"; +export { Hfs } from "@humanfs/core"; diff --git a/node_modules/@humanfs/node/dist/node-fsx.d.ts b/node_modules/@humanfs/node/dist/node-fsx.d.ts new file mode 100644 index 00000000..78e8dbd9 --- /dev/null +++ b/node_modules/@humanfs/node/dist/node-fsx.d.ts @@ -0,0 +1,150 @@ +/// +/** + * A class representing the Node.js implementation of Hfs. + * @implements {HfsImpl} + */ +export class NodeHfsImpl implements HfsImpl { + /** + * Creates a new instance. + * @param {object} [options] The options for the instance. + * @param {Fsp} [options.fsp] The file system module to use. + */ + constructor({ fsp }?: { + fsp?: Fsp; + }); + /** + * Reads a file and returns the contents as a string. Assumes UTF-8 encoding. + * @param {string} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the contents of + * the file or undefined if the file doesn't exist. + * @throws {TypeError} If the file path is not a string. + * @throws {RangeError} If the file path is empty. + * @throws {RangeError} If the file path is not absolute. + * @throws {RangeError} If the file path is not a file. + * @throws {RangeError} If the file path is not readable. + */ + text(filePath: string): Promise; + /** + * Reads a file and returns the contents as a JSON object. Assumes UTF-8 encoding. + * @param {string} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the contents of + * the file or undefined if the file doesn't exist. + * @throws {SyntaxError} If the file contents are not valid JSON. + * @throws {Error} If the file cannot be read. + * @throws {TypeError} If the file path is not a string. + */ + json(filePath: string): Promise; + /** + * Reads a file and returns the contents as an ArrayBuffer. + * @param {string} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the contents + * of the file or undefined if the file doesn't exist. + * @throws {Error} If the file cannot be read. + * @throws {TypeError} If the file path is not a string. + * @deprecated Use bytes() instead. + */ + arrayBuffer(filePath: string): Promise; + /** + * Reads a file and returns the contents as an Uint8Array. + * @param {string} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the contents + * of the file or undefined if the file doesn't exist. + * @throws {Error} If the file cannot be read. + * @throws {TypeError} If the file path is not a string. + */ + bytes(filePath: string): Promise; + /** + * Writes a value to a file. If the value is a string, UTF-8 encoding is used. + * @param {string} filePath The path to the file to write. + * @param {string|ArrayBuffer|ArrayBufferView} contents The contents to write to the + * file. + * @returns {Promise} A promise that resolves when the file is + * written. + * @throws {TypeError} If the file path is not a string. + * @throws {Error} If the file cannot be written. + */ + write(filePath: string, contents: string | ArrayBuffer | ArrayBufferView): Promise; + /** + * Checks if a file exists. + * @param {string} filePath The path to the file to check. + * @returns {Promise} A promise that resolves with true if the + * file exists or false if it does not. + * @throws {Error} If the operation fails with a code other than ENOENT. + */ + isFile(filePath: string): Promise; + /** + * Checks if a directory exists. + * @param {string} dirPath The path to the directory to check. + * @returns {Promise} A promise that resolves with true if the + * directory exists or false if it does not. + * @throws {Error} If the operation fails with a code other than ENOENT. + */ + isDirectory(dirPath: string): Promise; + /** + * Creates a directory recursively. + * @param {string} dirPath The path to the directory to create. + * @returns {Promise} A promise that resolves when the directory is + * created. + */ + createDirectory(dirPath: string): Promise; + /** + * Deletes a file or empty directory. + * @param {string} fileOrDirPath The path to the file or directory to + * delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted. + * @throws {TypeError} If the file or directory path is not a string. + * @throws {Error} If the file or directory cannot be deleted. + * @throws {Error} If the file or directory is not found. + */ + delete(fileOrDirPath: string): Promise; + /** + * Deletes a file or directory recursively. + * @param {string} fileOrDirPath The path to the file or directory to + * delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted. + * @throws {TypeError} If the file or directory path is not a string. + * @throws {Error} If the file or directory cannot be deleted. + * @throws {Error} If the file or directory is not found. + */ + deleteAll(fileOrDirPath: string): Promise; + /** + * Returns a list of directory entries for the given path. + * @param {string} dirPath The path to the directory to read. + * @returns {AsyncIterable} A promise that resolves with the + * directory entries. + * @throws {TypeError} If the directory path is not a string. + * @throws {Error} If the directory cannot be read. + */ + list(dirPath: string): AsyncIterable; + /** + * Returns the size of a file. + * @param {string} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the size of the + * file in bytes or undefined if the file doesn't exist. + */ + size(filePath: string): Promise; + #private; +} +/** + * A class representing a file system utility library. + * @implements {HfsImpl} + */ +export class NodeHfs extends Hfs implements HfsImpl { + /** + * Creates a new instance. + * @param {object} [options] The options for the instance. + * @param {Fsp} [options.fsp] The file system module to use. + */ + constructor({ fsp }?: { + fsp?: Fsp; + }); +} +export const hfs: NodeHfs; +export type HfsImpl = import("@humanfs/types").HfsImpl; +export type HfsDirectoryEntry = import("@humanfs/types").HfsDirectoryEntry; +export type Fsp = typeof nativeFsp; +export type Dirent = import("fs").Dirent; +import { Hfs } from "@humanfs/core"; +import nativeFsp from "node:fs/promises"; diff --git a/node_modules/@humanfs/node/dist/node-hfs.d.ts b/node_modules/@humanfs/node/dist/node-hfs.d.ts new file mode 100644 index 00000000..1fd63222 --- /dev/null +++ b/node_modules/@humanfs/node/dist/node-hfs.d.ts @@ -0,0 +1,176 @@ +/// +/** + * A class representing the Node.js implementation of Hfs. + * @implements {HfsImpl} + */ +export class NodeHfsImpl implements HfsImpl { + /** + * Creates a new instance. + * @param {object} [options] The options for the instance. + * @param {Fsp} [options.fsp] The file system module to use. + */ + constructor({ fsp }?: { + fsp?: Fsp; + }); + /** + * Reads a file and returns the contents as an Uint8Array. + * @param {string|URL} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the contents + * of the file or undefined if the file doesn't exist. + * @throws {Error} If the file cannot be read. + * @throws {TypeError} If the file path is not a string. + */ + bytes(filePath: string | URL): Promise; + /** + * Writes a value to a file. If the value is a string, UTF-8 encoding is used. + * @param {string|URL} filePath The path to the file to write. + * @param {Uint8Array} contents The contents to write to the + * file. + * @returns {Promise} A promise that resolves when the file is + * written. + * @throws {TypeError} If the file path is not a string. + * @throws {Error} If the file cannot be written. + */ + write(filePath: string | URL, contents: Uint8Array): Promise; + /** + * Appends a value to a file. If the value is a string, UTF-8 encoding is used. + * @param {string|URL} filePath The path to the file to append to. + * @param {Uint8Array} contents The contents to append to the + * file. + * @returns {Promise} A promise that resolves when the file is + * written. + * @throws {TypeError} If the file path is not a string. + * @throws {Error} If the file cannot be appended to. + */ + append(filePath: string | URL, contents: Uint8Array): Promise; + /** + * Checks if a file exists. + * @param {string|URL} filePath The path to the file to check. + * @returns {Promise} A promise that resolves with true if the + * file exists or false if it does not. + * @throws {Error} If the operation fails with a code other than ENOENT. + */ + isFile(filePath: string | URL): Promise; + /** + * Checks if a directory exists. + * @param {string|URL} dirPath The path to the directory to check. + * @returns {Promise} A promise that resolves with true if the + * directory exists or false if it does not. + * @throws {Error} If the operation fails with a code other than ENOENT. + */ + isDirectory(dirPath: string | URL): Promise; + /** + * Creates a directory recursively. + * @param {string|URL} dirPath The path to the directory to create. + * @returns {Promise} A promise that resolves when the directory is + * created. + */ + createDirectory(dirPath: string | URL): Promise; + /** + * Deletes a file or empty directory. + * @param {string|URL} fileOrDirPath The path to the file or directory to + * delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted, true if the file or directory is deleted, false + * if the file or directory does not exist. + * @throws {TypeError} If the file or directory path is not a string. + * @throws {Error} If the file or directory cannot be deleted. + */ + delete(fileOrDirPath: string | URL): Promise; + /** + * Deletes a file or directory recursively. + * @param {string|URL} fileOrDirPath The path to the file or directory to + * delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted, true if the file or directory is deleted, false + * if the file or directory does not exist. + * @throws {TypeError} If the file or directory path is not a string. + * @throws {Error} If the file or directory cannot be deleted. + */ + deleteAll(fileOrDirPath: string | URL): Promise; + /** + * Returns a list of directory entries for the given path. + * @param {string|URL} dirPath The path to the directory to read. + * @returns {AsyncIterable} A promise that resolves with the + * directory entries. + * @throws {TypeError} If the directory path is not a string. + * @throws {Error} If the directory cannot be read. + */ + list(dirPath: string | URL): AsyncIterable; + /** + * Returns the size of a file. This method handles ENOENT errors + * and returns undefined in that case. + * @param {string|URL} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the size of the + * file in bytes or undefined if the file doesn't exist. + */ + size(filePath: string | URL): Promise; + /** + * Returns the last modified date of a file or directory. This method handles ENOENT errors + * and returns undefined in that case. + * @param {string|URL} fileOrDirPath The path to the file to read. + * @returns {Promise} A promise that resolves with the last modified + * date of the file or directory, or undefined if the file doesn't exist. + */ + lastModified(fileOrDirPath: string | URL): Promise; + /** + * Copies a file from one location to another. + * @param {string|URL} source The path to the file to copy. + * @param {string|URL} destination The path to copy the file to. + * @returns {Promise} A promise that resolves when the file is copied. + * @throws {Error} If the source file does not exist. + * @throws {Error} If the source file is a directory. + * @throws {Error} If the destination file is a directory. + */ + copy(source: string | URL, destination: string | URL): Promise; + /** + * Copies a file or directory from one location to another. + * @param {string|URL} source The path to the file or directory to copy. + * @param {string|URL} destination The path to copy the file or directory to. + * @returns {Promise} A promise that resolves when the file or directory is + * copied. + * @throws {Error} If the source file or directory does not exist. + * @throws {Error} If the destination file or directory is a directory. + */ + copyAll(source: string | URL, destination: string | URL): Promise; + /** + * Moves a file from the source path to the destination path. + * @param {string|URL} source The location of the file to move. + * @param {string|URL} destination The destination of the file to move. + * @returns {Promise} A promise that resolves when the move is complete. + * @throws {TypeError} If the file paths are not strings. + * @throws {Error} If the file cannot be moved. + */ + move(source: string | URL, destination: string | URL): Promise; + /** + * Moves a file or directory from the source path to the destination path. + * @param {string|URL} source The location of the file or directory to move. + * @param {string|URL} destination The destination of the file or directory to move. + * @returns {Promise} A promise that resolves when the move is complete. + * @throws {TypeError} If the file paths are not strings. + * @throws {Error} If the file or directory cannot be moved. + */ + moveAll(source: string | URL, destination: string | URL): Promise; + #private; +} +/** + * A class representing a file system utility library. + * @implements {HfsImpl} + */ +export class NodeHfs extends Hfs implements HfsImpl { + /** + * Creates a new instance. + * @param {object} [options] The options for the instance. + * @param {Fsp} [options.fsp] The file system module to use. + */ + constructor({ fsp }?: { + fsp?: Fsp; + }); +} +export const hfs: NodeHfs; +export type HfsImpl = import("@humanfs/types").HfsImpl; +export type HfsDirectoryEntry = import("@humanfs/types").HfsDirectoryEntry; +export type Fsp = typeof nativeFsp; +export type Dirent = import("fs").Dirent; +import { Hfs } from "@humanfs/core"; +import nativeFsp from "node:fs/promises"; diff --git a/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/LICENSE b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/README.md b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/README.md new file mode 100644 index 00000000..c419ef13 --- /dev/null +++ b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/README.md @@ -0,0 +1,138 @@ +# Retry utility + +by [Nicholas C. Zakas](https://humanwhocodes.com) + +If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate) or [nominate me](https://stars.github.com/nominate/) for a GitHub Star. + +## Description + +A utility for retrying failed async JavaScript calls based on the error returned. + +## Usage + +### Node.js + +Install using [npm][npm] or [yarn][yarn]: + +``` +npm install @humanwhocodes/retry + +# or + +yarn add @humanwhocodes/retry +``` + +Import into your Node.js project: + +```js +// CommonJS +const { Retrier } = require("@humanwhocodes/retry"); + +// ESM +import { Retrier } from "@humanwhocodes/retry"; +``` + +### Deno + +Install using [JSR](https://jsr.io): + +```shell +deno add @humanwhocodes/retry + +#or + +jsr add @humanwhocodes/retry +``` + +Then import into your Deno project: + +```js +import { Retrier } from "@humanwhocodes/retry"; +``` + +### Bun + +Install using this command: + +``` +bun add @humanwhocodes/retry +``` + +Import into your Bun project: + +```js +import { Retrier } from "@humanwhocodes/retry"; +``` + +### Browser + +It's recommended to import the minified version to save bandwidth: + +```js +import { Retrier } from "https://cdn.skypack.dev/@humanwhocodes/retry?min"; +``` + +However, you can also import the unminified version for debugging purposes: + +```js +import { Retrier } from "https://cdn.skypack.dev/@humanwhocodes/retry"; +``` + +## API + +After importing, create a new instance of `Retrier` and specify the function to run on the error. This function should return `true` if you want the call retried and `false` if not. + +```js +// this instance will retry if the specific error code is found +const retrier = new Retrier(error => { + return error.code === "ENFILE" || error.code === "EMFILE"; +}); +``` + +Then, call the `retry()` method around the function you'd like to retry, such as: + +```js +import fs from "fs/promises"; + +const retrier = new Retrier(error => { + return error.code === "ENFILE" || error.code === "EMFILE"; +}); + +const text = await retrier.retry(() => fs.readFile("README.md", "utf8")); +``` + +The `retry()` method will either pass through the result on success or wait and retry on failure. Any error that isn't caught by the retrier is automatically rejected so the end result is a transparent passing through of both success and failure. + +You can also pass an `AbortSignal` to cancel a retry: + +```js +import fs from "fs/promises"; + +const controller = new AbortController(); +const retrier = new Retrier(error => { + return error.code === "ENFILE" || error.code === "EMFILE"; +}); + +const text = await retrier.retry( + () => fs.readFile("README.md", "utf8"), + { signal: controller.signal } +); +``` + +## Developer Setup + +1. Fork the repository +2. Clone your fork +3. Run `npm install` to setup dependencies +4. Run `npm test` to run tests + +## License + +Apache 2.0 + +## Prior Art + +This utility is inspired by, and contains code from [`graceful-fs`](https://github.com/isaacs/node-graceful-fs). + +[npm]: https://npmjs.com/ +[yarn]: https://yarnpkg.com/ diff --git a/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.cjs b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.cjs new file mode 100644 index 00000000..5e06a42c --- /dev/null +++ b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.cjs @@ -0,0 +1,303 @@ +'use strict'; + +/** + * @fileoverview A utility for retrying failed async method calls. + */ + +/* global setTimeout, clearTimeout */ + +//----------------------------------------------------------------------------- +// Constants +//----------------------------------------------------------------------------- + +const MAX_TASK_TIMEOUT = 60000; +const MAX_TASK_DELAY = 100; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/* + * The following logic has been extracted from graceful-fs. + * + * The ISC License + * + * Copyright (c) 2011-2023 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR + * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/** + * Checks if it is time to retry a task based on the timestamp and last attempt time. + * @param {RetryTask} task The task to check. + * @param {number} maxDelay The maximum delay for the queue. + * @returns {boolean} true if it is time to retry, false otherwise. + */ +function isTimeToRetry(task, maxDelay) { + const timeSinceLastAttempt = Date.now() - task.lastAttempt; + const timeSinceStart = Math.max(task.lastAttempt - task.timestamp, 1); + const desiredDelay = Math.min(timeSinceStart * 1.2, maxDelay); + + return timeSinceLastAttempt >= desiredDelay; +} + +/** + * Checks if it is time to bail out based on the given timestamp. + * @param {RetryTask} task The task to check. + * @param {number} timeout The timeout for the queue. + * @returns {boolean} true if it is time to bail, false otherwise. + */ +function isTimeToBail(task, timeout) { + return task.age > timeout; +} + + +/** + * A class to represent a task in the retry queue. + */ +class RetryTask { + + /** + * The unique ID for the task. + * @type {string} + */ + id = Math.random().toString(36).slice(2); + + /** + * The function to call. + * @type {Function} + */ + fn; + + /** + * The error that was thrown. + * @type {Error} + */ + error; + + /** + * The timestamp of the task. + * @type {number} + */ + timestamp = Date.now(); + + /** + * The timestamp of the last attempt. + * @type {number} + */ + lastAttempt = this.timestamp; + + /** + * The resolve function for the promise. + * @type {Function} + */ + resolve; + + /** + * The reject function for the promise. + * @type {Function} + */ + reject; + + /** + * The AbortSignal to monitor for cancellation. + * @type {AbortSignal|undefined} + */ + signal; + + /** + * Creates a new instance. + * @param {Function} fn The function to call. + * @param {Error} error The error that was thrown. + * @param {Function} resolve The resolve function for the promise. + * @param {Function} reject The reject function for the promise. + * @param {AbortSignal|undefined} signal The AbortSignal to monitor for cancellation. + */ + constructor(fn, error, resolve, reject, signal) { + this.fn = fn; + this.error = error; + this.timestamp = Date.now(); + this.lastAttempt = Date.now(); + this.resolve = resolve; + this.reject = reject; + this.signal = signal; + } + + /** + * Gets the age of the task. + * @returns {number} The age of the task in milliseconds. + * @readonly + */ + get age() { + return Date.now() - this.timestamp; + } +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class that manages a queue of retry jobs. + */ +class Retrier { + + /** + * Represents the queue for processing tasks. + * @type {Array} + */ + #queue = []; + + /** + * The timeout for the queue. + * @type {number} + */ + #timeout; + + /** + * The maximum delay for the queue. + * @type {number} + */ + #maxDelay; + + /** + * The setTimeout() timer ID. + * @type {NodeJS.Timeout|undefined} + */ + #timerId; + + /** + * The function to call. + * @type {Function} + */ + #check; + + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + */ + constructor(check, { timeout = MAX_TASK_TIMEOUT, maxDelay = MAX_TASK_DELAY } = {}) { + + if (typeof check !== "function") { + throw new Error("Missing function to check errors"); + } + + this.#check = check; + this.#timeout = timeout; + this.#maxDelay = maxDelay; + } + + /** + * Adds a new retry job to the queue. + * @param {Function} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is + * processed. + */ + retry(fn, { signal } = {}) { + + signal?.throwIfAborted(); + + let result; + + try { + result = fn(); + } catch (/** @type {any} */ error) { + return Promise.reject(new Error(`Synchronous error: ${error.message}`, { cause: error })); + } + + // if the result is not a promise then reject an error + if (!result || typeof result.then !== "function") { + return Promise.reject(new Error("Result is not a promise.")); + } + + // call the original function and catch any ENFILE or EMFILE errors + // @ts-ignore because we know it's any + return Promise.resolve(result).catch(error => { + if (!this.#check(error)) { + throw error; + } + + return new Promise((resolve, reject) => { + this.#queue.push(new RetryTask(fn, error, resolve, reject, signal)); + + signal?.addEventListener("abort", () => { + reject(signal.reason); + }); + + this.#processQueue(); + }); + }); + } + + /** + * Processes the queue. + * @returns {void} + */ + #processQueue() { + // clear any timer because we're going to check right now + clearTimeout(this.#timerId); + this.#timerId = undefined; + + // if there's nothing in the queue, we're done + const task = this.#queue.shift(); + if (!task) { + return; + } + const processAgain = () => { + this.#timerId = setTimeout(() => this.#processQueue(), 0); + }; + + // if it's time to bail, then bail + if (isTimeToBail(task, this.#timeout)) { + task.reject(task.error); + processAgain(); + return; + } + + // if it's not time to retry, then wait and try again + if (!isTimeToRetry(task, this.#maxDelay)) { + this.#queue.push(task); + processAgain(); + return; + } + + // otherwise, try again + task.lastAttempt = Date.now(); + + // Promise.resolve needed in case it's a thenable but not a Promise + Promise.resolve(task.fn()) + // @ts-ignore because we know it's any + .then(result => task.resolve(result)) + + // @ts-ignore because we know it's any + .catch(error => { + if (!this.#check(error)) { + task.reject(error); + return; + } + + // update the task timestamp and push to back of queue to try again + task.lastAttempt = Date.now(); + this.#queue.push(task); + + }) + .finally(() => this.#processQueue()); + } +} + +exports.Retrier = Retrier; diff --git a/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.d.cts b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.d.cts new file mode 100644 index 00000000..f1529650 --- /dev/null +++ b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.d.cts @@ -0,0 +1,28 @@ +/** + * A class that manages a queue of retry jobs. + */ +export class Retrier { + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + */ + constructor(check: Function, { timeout, maxDelay }?: { + timeout?: number | undefined; + maxDelay?: number | undefined; + } | undefined); + /** + * Adds a new retry job to the queue. + * @param {Function} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is + * processed. + */ + retry(fn: Function, { signal }?: { + signal?: AbortSignal | undefined; + } | undefined): Promise; + #private; +} diff --git a/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.d.ts b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.d.ts new file mode 100644 index 00000000..f1529650 --- /dev/null +++ b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.d.ts @@ -0,0 +1,28 @@ +/** + * A class that manages a queue of retry jobs. + */ +export class Retrier { + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + */ + constructor(check: Function, { timeout, maxDelay }?: { + timeout?: number | undefined; + maxDelay?: number | undefined; + } | undefined); + /** + * Adds a new retry job to the queue. + * @param {Function} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is + * processed. + */ + retry(fn: Function, { signal }?: { + signal?: AbortSignal | undefined; + } | undefined): Promise; + #private; +} diff --git a/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.js b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.js new file mode 100644 index 00000000..4343d58c --- /dev/null +++ b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.js @@ -0,0 +1,302 @@ +// @ts-self-types="./retrier.d.ts" +/** + * @fileoverview A utility for retrying failed async method calls. + */ + +/* global setTimeout, clearTimeout */ + +//----------------------------------------------------------------------------- +// Constants +//----------------------------------------------------------------------------- + +const MAX_TASK_TIMEOUT = 60000; +const MAX_TASK_DELAY = 100; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/* + * The following logic has been extracted from graceful-fs. + * + * The ISC License + * + * Copyright (c) 2011-2023 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR + * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/** + * Checks if it is time to retry a task based on the timestamp and last attempt time. + * @param {RetryTask} task The task to check. + * @param {number} maxDelay The maximum delay for the queue. + * @returns {boolean} true if it is time to retry, false otherwise. + */ +function isTimeToRetry(task, maxDelay) { + const timeSinceLastAttempt = Date.now() - task.lastAttempt; + const timeSinceStart = Math.max(task.lastAttempt - task.timestamp, 1); + const desiredDelay = Math.min(timeSinceStart * 1.2, maxDelay); + + return timeSinceLastAttempt >= desiredDelay; +} + +/** + * Checks if it is time to bail out based on the given timestamp. + * @param {RetryTask} task The task to check. + * @param {number} timeout The timeout for the queue. + * @returns {boolean} true if it is time to bail, false otherwise. + */ +function isTimeToBail(task, timeout) { + return task.age > timeout; +} + + +/** + * A class to represent a task in the retry queue. + */ +class RetryTask { + + /** + * The unique ID for the task. + * @type {string} + */ + id = Math.random().toString(36).slice(2); + + /** + * The function to call. + * @type {Function} + */ + fn; + + /** + * The error that was thrown. + * @type {Error} + */ + error; + + /** + * The timestamp of the task. + * @type {number} + */ + timestamp = Date.now(); + + /** + * The timestamp of the last attempt. + * @type {number} + */ + lastAttempt = this.timestamp; + + /** + * The resolve function for the promise. + * @type {Function} + */ + resolve; + + /** + * The reject function for the promise. + * @type {Function} + */ + reject; + + /** + * The AbortSignal to monitor for cancellation. + * @type {AbortSignal|undefined} + */ + signal; + + /** + * Creates a new instance. + * @param {Function} fn The function to call. + * @param {Error} error The error that was thrown. + * @param {Function} resolve The resolve function for the promise. + * @param {Function} reject The reject function for the promise. + * @param {AbortSignal|undefined} signal The AbortSignal to monitor for cancellation. + */ + constructor(fn, error, resolve, reject, signal) { + this.fn = fn; + this.error = error; + this.timestamp = Date.now(); + this.lastAttempt = Date.now(); + this.resolve = resolve; + this.reject = reject; + this.signal = signal; + } + + /** + * Gets the age of the task. + * @returns {number} The age of the task in milliseconds. + * @readonly + */ + get age() { + return Date.now() - this.timestamp; + } +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class that manages a queue of retry jobs. + */ +class Retrier { + + /** + * Represents the queue for processing tasks. + * @type {Array} + */ + #queue = []; + + /** + * The timeout for the queue. + * @type {number} + */ + #timeout; + + /** + * The maximum delay for the queue. + * @type {number} + */ + #maxDelay; + + /** + * The setTimeout() timer ID. + * @type {NodeJS.Timeout|undefined} + */ + #timerId; + + /** + * The function to call. + * @type {Function} + */ + #check; + + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + */ + constructor(check, { timeout = MAX_TASK_TIMEOUT, maxDelay = MAX_TASK_DELAY } = {}) { + + if (typeof check !== "function") { + throw new Error("Missing function to check errors"); + } + + this.#check = check; + this.#timeout = timeout; + this.#maxDelay = maxDelay; + } + + /** + * Adds a new retry job to the queue. + * @param {Function} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is + * processed. + */ + retry(fn, { signal } = {}) { + + signal?.throwIfAborted(); + + let result; + + try { + result = fn(); + } catch (/** @type {any} */ error) { + return Promise.reject(new Error(`Synchronous error: ${error.message}`, { cause: error })); + } + + // if the result is not a promise then reject an error + if (!result || typeof result.then !== "function") { + return Promise.reject(new Error("Result is not a promise.")); + } + + // call the original function and catch any ENFILE or EMFILE errors + // @ts-ignore because we know it's any + return Promise.resolve(result).catch(error => { + if (!this.#check(error)) { + throw error; + } + + return new Promise((resolve, reject) => { + this.#queue.push(new RetryTask(fn, error, resolve, reject, signal)); + + signal?.addEventListener("abort", () => { + reject(signal.reason); + }); + + this.#processQueue(); + }); + }); + } + + /** + * Processes the queue. + * @returns {void} + */ + #processQueue() { + // clear any timer because we're going to check right now + clearTimeout(this.#timerId); + this.#timerId = undefined; + + // if there's nothing in the queue, we're done + const task = this.#queue.shift(); + if (!task) { + return; + } + const processAgain = () => { + this.#timerId = setTimeout(() => this.#processQueue(), 0); + }; + + // if it's time to bail, then bail + if (isTimeToBail(task, this.#timeout)) { + task.reject(task.error); + processAgain(); + return; + } + + // if it's not time to retry, then wait and try again + if (!isTimeToRetry(task, this.#maxDelay)) { + this.#queue.push(task); + processAgain(); + return; + } + + // otherwise, try again + task.lastAttempt = Date.now(); + + // Promise.resolve needed in case it's a thenable but not a Promise + Promise.resolve(task.fn()) + // @ts-ignore because we know it's any + .then(result => task.resolve(result)) + + // @ts-ignore because we know it's any + .catch(error => { + if (!this.#check(error)) { + task.reject(error); + return; + } + + // update the task timestamp and push to back of queue to try again + task.lastAttempt = Date.now(); + this.#queue.push(task); + + }) + .finally(() => this.#processQueue()); + } +} + +export { Retrier }; diff --git a/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.min.js b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.min.js new file mode 100644 index 00000000..6021e1a0 --- /dev/null +++ b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.min.js @@ -0,0 +1 @@ +class RetryTask{id=Math.random().toString(36).slice(2);fn;error;timestamp=Date.now();lastAttempt=this.timestamp;resolve;reject;signal;constructor(t,e,r,s,i){this.fn=t,this.error=e,this.timestamp=Date.now(),this.lastAttempt=Date.now(),this.resolve=r,this.reject=s,this.signal=i}get age(){return Date.now()-this.timestamp}}class Retrier{#t=[];#e;#r;#s;#i;constructor(t,{timeout:e=6e4,maxDelay:r=100}={}){if("function"!=typeof t)throw new Error("Missing function to check errors");this.#i=t,this.#e=e,this.#r=r}retry(t,{signal:e}={}){let r;e?.throwIfAborted();try{r=t()}catch(t){return Promise.reject(new Error(`Synchronous error: ${t.message}`,{cause:t}))}return r&&"function"==typeof r.then?Promise.resolve(r).catch((r=>{if(!this.#i(r))throw r;return new Promise(((s,i)=>{this.#t.push(new RetryTask(t,r,s,i,e)),e?.addEventListener("abort",(()=>{i(e.reason)})),this.#o()}))})):Promise.reject(new Error("Result is not a promise."))}#o(){clearTimeout(this.#s),this.#s=void 0;const t=this.#t.shift();if(!t)return;const e=()=>{this.#s=setTimeout((()=>this.#o()),0)};return function(t,e){return t.age>e}(t,this.#e)?(t.reject(t.error),void e()):function(t,e){const r=Date.now()-t.lastAttempt,s=Math.max(t.lastAttempt-t.timestamp,1);return r>=Math.min(1.2*s,e)}(t,this.#r)?(t.lastAttempt=Date.now(),void Promise.resolve(t.fn()).then((e=>t.resolve(e))).catch((e=>{this.#i(e)?(t.lastAttempt=Date.now(),this.#t.push(t)):t.reject(e)})).finally((()=>this.#o()))):(this.#t.push(t),void e())}}export{Retrier}; diff --git a/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.mjs b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.mjs new file mode 100644 index 00000000..6794621a --- /dev/null +++ b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/dist/retrier.mjs @@ -0,0 +1,301 @@ +/** + * @fileoverview A utility for retrying failed async method calls. + */ + +/* global setTimeout, clearTimeout */ + +//----------------------------------------------------------------------------- +// Constants +//----------------------------------------------------------------------------- + +const MAX_TASK_TIMEOUT = 60000; +const MAX_TASK_DELAY = 100; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/* + * The following logic has been extracted from graceful-fs. + * + * The ISC License + * + * Copyright (c) 2011-2023 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR + * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/** + * Checks if it is time to retry a task based on the timestamp and last attempt time. + * @param {RetryTask} task The task to check. + * @param {number} maxDelay The maximum delay for the queue. + * @returns {boolean} true if it is time to retry, false otherwise. + */ +function isTimeToRetry(task, maxDelay) { + const timeSinceLastAttempt = Date.now() - task.lastAttempt; + const timeSinceStart = Math.max(task.lastAttempt - task.timestamp, 1); + const desiredDelay = Math.min(timeSinceStart * 1.2, maxDelay); + + return timeSinceLastAttempt >= desiredDelay; +} + +/** + * Checks if it is time to bail out based on the given timestamp. + * @param {RetryTask} task The task to check. + * @param {number} timeout The timeout for the queue. + * @returns {boolean} true if it is time to bail, false otherwise. + */ +function isTimeToBail(task, timeout) { + return task.age > timeout; +} + + +/** + * A class to represent a task in the retry queue. + */ +class RetryTask { + + /** + * The unique ID for the task. + * @type {string} + */ + id = Math.random().toString(36).slice(2); + + /** + * The function to call. + * @type {Function} + */ + fn; + + /** + * The error that was thrown. + * @type {Error} + */ + error; + + /** + * The timestamp of the task. + * @type {number} + */ + timestamp = Date.now(); + + /** + * The timestamp of the last attempt. + * @type {number} + */ + lastAttempt = this.timestamp; + + /** + * The resolve function for the promise. + * @type {Function} + */ + resolve; + + /** + * The reject function for the promise. + * @type {Function} + */ + reject; + + /** + * The AbortSignal to monitor for cancellation. + * @type {AbortSignal|undefined} + */ + signal; + + /** + * Creates a new instance. + * @param {Function} fn The function to call. + * @param {Error} error The error that was thrown. + * @param {Function} resolve The resolve function for the promise. + * @param {Function} reject The reject function for the promise. + * @param {AbortSignal|undefined} signal The AbortSignal to monitor for cancellation. + */ + constructor(fn, error, resolve, reject, signal) { + this.fn = fn; + this.error = error; + this.timestamp = Date.now(); + this.lastAttempt = Date.now(); + this.resolve = resolve; + this.reject = reject; + this.signal = signal; + } + + /** + * Gets the age of the task. + * @returns {number} The age of the task in milliseconds. + * @readonly + */ + get age() { + return Date.now() - this.timestamp; + } +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class that manages a queue of retry jobs. + */ +class Retrier { + + /** + * Represents the queue for processing tasks. + * @type {Array} + */ + #queue = []; + + /** + * The timeout for the queue. + * @type {number} + */ + #timeout; + + /** + * The maximum delay for the queue. + * @type {number} + */ + #maxDelay; + + /** + * The setTimeout() timer ID. + * @type {NodeJS.Timeout|undefined} + */ + #timerId; + + /** + * The function to call. + * @type {Function} + */ + #check; + + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + */ + constructor(check, { timeout = MAX_TASK_TIMEOUT, maxDelay = MAX_TASK_DELAY } = {}) { + + if (typeof check !== "function") { + throw new Error("Missing function to check errors"); + } + + this.#check = check; + this.#timeout = timeout; + this.#maxDelay = maxDelay; + } + + /** + * Adds a new retry job to the queue. + * @param {Function} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is + * processed. + */ + retry(fn, { signal } = {}) { + + signal?.throwIfAborted(); + + let result; + + try { + result = fn(); + } catch (/** @type {any} */ error) { + return Promise.reject(new Error(`Synchronous error: ${error.message}`, { cause: error })); + } + + // if the result is not a promise then reject an error + if (!result || typeof result.then !== "function") { + return Promise.reject(new Error("Result is not a promise.")); + } + + // call the original function and catch any ENFILE or EMFILE errors + // @ts-ignore because we know it's any + return Promise.resolve(result).catch(error => { + if (!this.#check(error)) { + throw error; + } + + return new Promise((resolve, reject) => { + this.#queue.push(new RetryTask(fn, error, resolve, reject, signal)); + + signal?.addEventListener("abort", () => { + reject(signal.reason); + }); + + this.#processQueue(); + }); + }); + } + + /** + * Processes the queue. + * @returns {void} + */ + #processQueue() { + // clear any timer because we're going to check right now + clearTimeout(this.#timerId); + this.#timerId = undefined; + + // if there's nothing in the queue, we're done + const task = this.#queue.shift(); + if (!task) { + return; + } + const processAgain = () => { + this.#timerId = setTimeout(() => this.#processQueue(), 0); + }; + + // if it's time to bail, then bail + if (isTimeToBail(task, this.#timeout)) { + task.reject(task.error); + processAgain(); + return; + } + + // if it's not time to retry, then wait and try again + if (!isTimeToRetry(task, this.#maxDelay)) { + this.#queue.push(task); + processAgain(); + return; + } + + // otherwise, try again + task.lastAttempt = Date.now(); + + // Promise.resolve needed in case it's a thenable but not a Promise + Promise.resolve(task.fn()) + // @ts-ignore because we know it's any + .then(result => task.resolve(result)) + + // @ts-ignore because we know it's any + .catch(error => { + if (!this.#check(error)) { + task.reject(error); + return; + } + + // update the task timestamp and push to back of queue to try again + task.lastAttempt = Date.now(); + this.#queue.push(task); + + }) + .finally(() => this.#processQueue()); + } +} + +export { Retrier }; diff --git a/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/package.json b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/package.json new file mode 100644 index 00000000..a33e7490 --- /dev/null +++ b/node_modules/@humanfs/node/node_modules/@humanwhocodes/retry/package.json @@ -0,0 +1,77 @@ +{ + "name": "@humanwhocodes/retry", + "version": "0.3.1", + "description": "A utility to retry failed async methods.", + "type": "module", + "main": "dist/retrier.cjs", + "module": "dist/retrier.js", + "types": "dist/retrier.d.ts", + "exports": { + "require": { + "types": "./dist/retrier.d.cts", + "default": "./dist/retrier.cjs" + }, + "import": { + "types": "./dist/retrier.d.ts", + "default": "./dist/retrier.js" + } + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=18.18" + }, + "publishConfig": { + "access": "public" + }, + "gitHooks": { + "pre-commit": "lint-staged" + }, + "lint-staged": { + "*.js": [ + "eslint --fix" + ] + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + }, + "scripts": { + "build:cts-types": "node -e \"fs.copyFileSync('dist/retrier.d.ts', 'dist/retrier.d.cts')\"", + "build": "rollup -c && tsc && npm run build:cts-types", + "prepare": "npm run build", + "lint": "eslint src/ tests/", + "pretest": "npm run build", + "test:unit": "mocha tests/retrier.test.js", + "test:build": "node tests/pkg.test.cjs && node tests/pkg.test.mjs", + "test:jsr": "npx jsr@latest publish --dry-run", + "test:emfile": "node tools/check-emfile-handling.js", + "test": "npm run test:unit && npm run test:build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/humanwhocodes/retry.git" + }, + "keywords": [ + "nodejs", + "retry", + "async", + "promises" + ], + "author": "Nicholas C. Zaks", + "license": "Apache-2.0", + "devDependencies": { + "@eslint/js": "^8.49.0", + "@rollup/plugin-terser": "0.4.4", + "@tsconfig/node16": "^16.1.1", + "@types/mocha": "^10.0.3", + "@types/node": "20.12.6", + "eslint": "^8.21.0", + "lint-staged": "15.2.1", + "mocha": "^10.3.0", + "rollup": "3.29.4", + "typescript": "5.4.4", + "yorkie": "2.0.0" + } +} diff --git a/node_modules/@humanfs/node/package.json b/node_modules/@humanfs/node/package.json new file mode 100644 index 00000000..5b303fa1 --- /dev/null +++ b/node_modules/@humanfs/node/package.json @@ -0,0 +1,57 @@ +{ + "name": "@humanfs/node", + "version": "0.16.6", + "description": "The Node.js bindings of the humanfs library.", + "type": "module", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + "import": { + "types": "./dist/index.d.ts", + "default": "./src/index.js" + } + }, + "files": [ + "dist", + "src" + ], + "scripts": { + "build": "tsc", + "prepare": "npm run build", + "pretest": "npm run build", + "test": "mocha ./tests/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/humanwhocodes/humanfs.git" + }, + "publishConfig": { + "access": "public" + }, + "keywords": [ + "filesystem", + "fs", + "hfs", + "files" + ], + "author": "Nicholas C. Zakas", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/humanwhocodes/humanfs/issues" + }, + "homepage": "https://github.com/humanwhocodes/humanfs#readme", + "engines": { + "node": ">=18.18.0" + }, + "devDependencies": { + "@types/node": "^20.9.4", + "@humanfs/test": "^0.15.0", + "@humanfs/types": "^0.15.0", + "mocha": "^10.2.0", + "typescript": "^5.2.2" + }, + "dependencies": { + "@humanwhocodes/retry": "^0.3.0", + "@humanfs/core": "^0.19.1" + } +} diff --git a/node_modules/@humanfs/node/src/index.js b/node_modules/@humanfs/node/src/index.js new file mode 100644 index 00000000..6d551aa7 --- /dev/null +++ b/node_modules/@humanfs/node/src/index.js @@ -0,0 +1,7 @@ +/** + * @fileoverview This file exports everything for this package. + * @author Nicholas C. Zakas + */ + +export * from "./node-hfs.js"; +export { Hfs } from "@humanfs/core"; diff --git a/node_modules/@humanfs/node/src/node-hfs.js b/node_modules/@humanfs/node/src/node-hfs.js new file mode 100644 index 00000000..7840c872 --- /dev/null +++ b/node_modules/@humanfs/node/src/node-hfs.js @@ -0,0 +1,452 @@ +/** + * @fileoverview The main file for the hfs package. + * @author Nicholas C. Zakas + */ +/* global Buffer:readonly, URL */ + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("@humanfs/types").HfsImpl} HfsImpl */ +/** @typedef {import("@humanfs/types").HfsDirectoryEntry} HfsDirectoryEntry */ +/** @typedef {import("node:fs/promises")} Fsp */ +/** @typedef {import("fs").Dirent} Dirent */ + +//----------------------------------------------------------------------------- +// Imports +//----------------------------------------------------------------------------- + +import { Hfs } from "@humanfs/core"; +import path from "node:path"; +import { Retrier } from "@humanwhocodes/retry"; +import nativeFsp from "node:fs/promises"; +import { fileURLToPath } from "node:url"; + +//----------------------------------------------------------------------------- +// Constants +//----------------------------------------------------------------------------- + +const RETRY_ERROR_CODES = new Set(["ENFILE", "EMFILE"]); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * A class representing a directory entry. + * @implements {HfsDirectoryEntry} + */ +class NodeHfsDirectoryEntry { + /** + * The name of the directory entry. + * @type {string} + */ + name; + + /** + * True if the entry is a file. + * @type {boolean} + */ + isFile; + + /** + * True if the entry is a directory. + * @type {boolean} + */ + isDirectory; + + /** + * True if the entry is a symbolic link. + * @type {boolean} + */ + isSymlink; + + /** + * Creates a new instance. + * @param {Dirent} dirent The directory entry to wrap. + */ + constructor(dirent) { + this.name = dirent.name; + this.isFile = dirent.isFile(); + this.isDirectory = dirent.isDirectory(); + this.isSymlink = dirent.isSymbolicLink(); + } +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class representing the Node.js implementation of Hfs. + * @implements {HfsImpl} + */ +export class NodeHfsImpl { + /** + * The file system module to use. + * @type {Fsp} + */ + #fsp; + + /** + * The retryer object used for retrying operations. + * @type {Retrier} + */ + #retrier; + + /** + * Creates a new instance. + * @param {object} [options] The options for the instance. + * @param {Fsp} [options.fsp] The file system module to use. + */ + constructor({ fsp = nativeFsp } = {}) { + this.#fsp = fsp; + this.#retrier = new Retrier(error => RETRY_ERROR_CODES.has(error.code)); + } + + /** + * Reads a file and returns the contents as an Uint8Array. + * @param {string|URL} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the contents + * of the file or undefined if the file doesn't exist. + * @throws {Error} If the file cannot be read. + * @throws {TypeError} If the file path is not a string. + */ + bytes(filePath) { + return this.#retrier + .retry(() => this.#fsp.readFile(filePath)) + .then(buffer => new Uint8Array(buffer.buffer)) + .catch(error => { + if (error.code === "ENOENT") { + return undefined; + } + + throw error; + }); + } + + /** + * Writes a value to a file. If the value is a string, UTF-8 encoding is used. + * @param {string|URL} filePath The path to the file to write. + * @param {Uint8Array} contents The contents to write to the + * file. + * @returns {Promise} A promise that resolves when the file is + * written. + * @throws {TypeError} If the file path is not a string. + * @throws {Error} If the file cannot be written. + */ + async write(filePath, contents) { + const value = Buffer.from(contents); + + return this.#retrier + .retry(() => this.#fsp.writeFile(filePath, value)) + .catch(error => { + // the directory may not exist, so create it + if (error.code === "ENOENT") { + const dirPath = path.dirname( + filePath instanceof URL + ? fileURLToPath(filePath) + : filePath, + ); + + return this.#fsp + .mkdir(dirPath, { recursive: true }) + .then(() => this.#fsp.writeFile(filePath, value)); + } + + throw error; + }); + } + + /** + * Appends a value to a file. If the value is a string, UTF-8 encoding is used. + * @param {string|URL} filePath The path to the file to append to. + * @param {Uint8Array} contents The contents to append to the + * file. + * @returns {Promise} A promise that resolves when the file is + * written. + * @throws {TypeError} If the file path is not a string. + * @throws {Error} If the file cannot be appended to. + */ + async append(filePath, contents) { + const value = Buffer.from(contents); + + return this.#retrier + .retry(() => this.#fsp.appendFile(filePath, value)) + .catch(error => { + // the directory may not exist, so create it + if (error.code === "ENOENT") { + const dirPath = path.dirname( + filePath instanceof URL + ? fileURLToPath(filePath) + : filePath, + ); + + return this.#fsp + .mkdir(dirPath, { recursive: true }) + .then(() => this.#fsp.appendFile(filePath, value)); + } + + throw error; + }); + } + + /** + * Checks if a file exists. + * @param {string|URL} filePath The path to the file to check. + * @returns {Promise} A promise that resolves with true if the + * file exists or false if it does not. + * @throws {Error} If the operation fails with a code other than ENOENT. + */ + isFile(filePath) { + return this.#fsp + .stat(filePath) + .then(stat => stat.isFile()) + .catch(error => { + if (error.code === "ENOENT") { + return false; + } + + throw error; + }); + } + + /** + * Checks if a directory exists. + * @param {string|URL} dirPath The path to the directory to check. + * @returns {Promise} A promise that resolves with true if the + * directory exists or false if it does not. + * @throws {Error} If the operation fails with a code other than ENOENT. + */ + isDirectory(dirPath) { + return this.#fsp + .stat(dirPath) + .then(stat => stat.isDirectory()) + .catch(error => { + if (error.code === "ENOENT") { + return false; + } + + throw error; + }); + } + + /** + * Creates a directory recursively. + * @param {string|URL} dirPath The path to the directory to create. + * @returns {Promise} A promise that resolves when the directory is + * created. + */ + async createDirectory(dirPath) { + await this.#fsp.mkdir(dirPath, { recursive: true }); + } + + /** + * Deletes a file or empty directory. + * @param {string|URL} fileOrDirPath The path to the file or directory to + * delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted, true if the file or directory is deleted, false + * if the file or directory does not exist. + * @throws {TypeError} If the file or directory path is not a string. + * @throws {Error} If the file or directory cannot be deleted. + */ + delete(fileOrDirPath) { + return this.#fsp + .rm(fileOrDirPath) + .then(() => true) + .catch(error => { + if (error.code === "ERR_FS_EISDIR") { + return this.#fsp.rmdir(fileOrDirPath).then(() => true); + } + + if (error.code === "ENOENT") { + return false; + } + + throw error; + }); + } + + /** + * Deletes a file or directory recursively. + * @param {string|URL} fileOrDirPath The path to the file or directory to + * delete. + * @returns {Promise} A promise that resolves when the file or + * directory is deleted, true if the file or directory is deleted, false + * if the file or directory does not exist. + * @throws {TypeError} If the file or directory path is not a string. + * @throws {Error} If the file or directory cannot be deleted. + */ + deleteAll(fileOrDirPath) { + return this.#fsp + .rm(fileOrDirPath, { recursive: true }) + .then(() => true) + .catch(error => { + if (error.code === "ENOENT") { + return false; + } + + throw error; + }); + } + + /** + * Returns a list of directory entries for the given path. + * @param {string|URL} dirPath The path to the directory to read. + * @returns {AsyncIterable} A promise that resolves with the + * directory entries. + * @throws {TypeError} If the directory path is not a string. + * @throws {Error} If the directory cannot be read. + */ + async *list(dirPath) { + const entries = await this.#fsp.readdir(dirPath, { + withFileTypes: true, + }); + + for (const entry of entries) { + yield new NodeHfsDirectoryEntry(entry); + } + } + + /** + * Returns the size of a file. This method handles ENOENT errors + * and returns undefined in that case. + * @param {string|URL} filePath The path to the file to read. + * @returns {Promise} A promise that resolves with the size of the + * file in bytes or undefined if the file doesn't exist. + */ + size(filePath) { + return this.#fsp + .stat(filePath) + .then(stat => stat.size) + .catch(error => { + if (error.code === "ENOENT") { + return undefined; + } + + throw error; + }); + } + + /** + * Returns the last modified date of a file or directory. This method handles ENOENT errors + * and returns undefined in that case. + * @param {string|URL} fileOrDirPath The path to the file to read. + * @returns {Promise} A promise that resolves with the last modified + * date of the file or directory, or undefined if the file doesn't exist. + */ + lastModified(fileOrDirPath) { + return this.#fsp + .stat(fileOrDirPath) + .then(stat => stat.mtime) + .catch(error => { + if (error.code === "ENOENT") { + return undefined; + } + + throw error; + }); + } + + /** + * Copies a file from one location to another. + * @param {string|URL} source The path to the file to copy. + * @param {string|URL} destination The path to copy the file to. + * @returns {Promise} A promise that resolves when the file is copied. + * @throws {Error} If the source file does not exist. + * @throws {Error} If the source file is a directory. + * @throws {Error} If the destination file is a directory. + */ + copy(source, destination) { + return this.#fsp.copyFile(source, destination); + } + + /** + * Copies a file or directory from one location to another. + * @param {string|URL} source The path to the file or directory to copy. + * @param {string|URL} destination The path to copy the file or directory to. + * @returns {Promise} A promise that resolves when the file or directory is + * copied. + * @throws {Error} If the source file or directory does not exist. + * @throws {Error} If the destination file or directory is a directory. + */ + async copyAll(source, destination) { + // for files use copy() and exit + if (await this.isFile(source)) { + return this.copy(source, destination); + } + + const sourceStr = + source instanceof URL ? fileURLToPath(source) : source; + + const destinationStr = + destination instanceof URL + ? fileURLToPath(destination) + : destination; + + // for directories, create the destination directory and copy each entry + await this.createDirectory(destination); + + for await (const entry of this.list(source)) { + const fromEntryPath = path.join(sourceStr, entry.name); + const toEntryPath = path.join(destinationStr, entry.name); + + if (entry.isDirectory) { + await this.copyAll(fromEntryPath, toEntryPath); + } else { + await this.copy(fromEntryPath, toEntryPath); + } + } + } + + /** + * Moves a file from the source path to the destination path. + * @param {string|URL} source The location of the file to move. + * @param {string|URL} destination The destination of the file to move. + * @returns {Promise} A promise that resolves when the move is complete. + * @throws {TypeError} If the file paths are not strings. + * @throws {Error} If the file cannot be moved. + */ + move(source, destination) { + return this.#fsp.stat(source).then(stat => { + if (stat.isDirectory()) { + throw new Error( + `EISDIR: illegal operation on a directory, move '${source}' -> '${destination}'`, + ); + } + + return this.#fsp.rename(source, destination); + }); + } + + /** + * Moves a file or directory from the source path to the destination path. + * @param {string|URL} source The location of the file or directory to move. + * @param {string|URL} destination The destination of the file or directory to move. + * @returns {Promise} A promise that resolves when the move is complete. + * @throws {TypeError} If the file paths are not strings. + * @throws {Error} If the file or directory cannot be moved. + */ + async moveAll(source, destination) { + return this.#fsp.rename(source, destination); + } +} + +/** + * A class representing a file system utility library. + * @implements {HfsImpl} + */ +export class NodeHfs extends Hfs { + /** + * Creates a new instance. + * @param {object} [options] The options for the instance. + * @param {Fsp} [options.fsp] The file system module to use. + */ + constructor({ fsp } = {}) { + super({ impl: new NodeHfsImpl({ fsp }) }); + } +} + +export const hfs = new NodeHfs(); diff --git a/node_modules/@humanwhocodes/module-importer/CHANGELOG.md b/node_modules/@humanwhocodes/module-importer/CHANGELOG.md new file mode 100644 index 00000000..1b442a19 --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +## [1.0.1](https://github.com/humanwhocodes/module-importer/compare/v1.0.0...v1.0.1) (2022-08-18) + + +### Bug Fixes + +* Ensure CommonJS mode works correctly. ([cf54a0b](https://github.com/humanwhocodes/module-importer/commit/cf54a0b998085066fbe1776dd0b4cacd808cc192)), closes [#6](https://github.com/humanwhocodes/module-importer/issues/6) + +## 1.0.0 (2022-08-17) + + +### Features + +* Implement ModuleImporter ([3ce4e82](https://www.github.com/humanwhocodes/module-importer/commit/3ce4e820c30c114e787bfed00a0966ac4772f563)) diff --git a/node_modules/@humanwhocodes/module-importer/LICENSE b/node_modules/@humanwhocodes/module-importer/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@humanwhocodes/module-importer/README.md b/node_modules/@humanwhocodes/module-importer/README.md new file mode 100644 index 00000000..3de07a7f --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/README.md @@ -0,0 +1,80 @@ +# ModuleImporter + +by [Nicholas C. Zakas](https://humanwhocodes.com) + +If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate). + +## Description + +A utility for seamlessly importing modules in Node.js regardless if they are CommonJS or ESM format. Under the hood, this uses `import()` and relies on Node.js's CommonJS compatibility to work correctly. This ensures that the correct locations and formats are used for CommonJS so you can call one method and not worry about any compatibility issues. + +The problem with the default `import()` is that it always resolves relative to the file location in which it is called. If you want to resolve from a different location, you need to jump through a few hoops to achieve that. This package makes it easy to both resolve and import modules from any directory. + +## Usage + +### Node.js + +Install using [npm][npm] or [yarn][yarn]: + +``` +npm install @humanwhocodes/module-importer + +# or + +yarn add @humanwhocodes/module-importer +``` + +Import into your Node.js project: + +```js +// CommonJS +const { ModuleImporter } = require("@humanwhocodes/module-importer"); + +// ESM +import { ModuleImporter } from "@humanwhocodes/module-importer"; +``` + +### Bun + +Install using this command: + +``` +bun add @humanwhocodes/module-importer +``` + +Import into your Bun project: + +```js +import { ModuleImporter } from "@humanwhocodes/module-importer"; +``` + +## API + +After importing, create a new instance of `ModuleImporter` to start emitting events: + +```js +// cwd can be omitted to use process.cwd() +const importer = new ModuleImporter(cwd); + +// you can resolve the location of any package +const location = importer.resolve("./some-file.cjs"); + +// you can also import directly +const module = importer.import("./some-file.cjs"); +``` + +For both `resolve()` and `import()`, you can pass in package names and filenames. + +## Developer Setup + +1. Fork the repository +2. Clone your fork +3. Run `npm install` to setup dependencies +4. Run `npm test` to run tests + +## License + +Apache 2.0 + +[npm]: https://npmjs.com/ +[yarn]: https://yarnpkg.com/ diff --git a/node_modules/@humanwhocodes/module-importer/dist/module-importer.cjs b/node_modules/@humanwhocodes/module-importer/dist/module-importer.cjs new file mode 100644 index 00000000..779e0cf6 --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/dist/module-importer.cjs @@ -0,0 +1,22 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var module$1 = require('module'); +var url = require('url'); +var path = require('path'); + +/** + * @fileoverview Universal module importer + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const __filename$1 = url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('module-importer.cjs', document.baseURI).href))); +const __dirname$1 = path.dirname(__filename$1); +const require$1 = module$1.createRequire(__dirname$1 + "/"); +const { ModuleImporter } = require$1("./module-importer.cjs"); + +exports.ModuleImporter = ModuleImporter; diff --git a/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.cts b/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.cts new file mode 100644 index 00000000..a1acbb6d --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.cts @@ -0,0 +1,27 @@ +export class ModuleImporter { + /** + * Creates a new instance. + * @param {string} [cwd] The current working directory to resolve from. + */ + constructor(cwd?: string); + /** + * The base directory from which paths should be resolved. + * @type {string} + */ + cwd: string; + /** + * Resolves a module based on its name or location. + * @param {string} specifier Either an npm package name or + * relative file path. + * @returns {string|undefined} The location of the import. + * @throws {Error} If specifier cannot be located. + */ + resolve(specifier: string): string | undefined; + /** + * Imports a module based on its name or location. + * @param {string} specifier Either an npm package name or + * relative file path. + * @returns {Promise} The module's object. + */ + import(specifier: string): Promise; +} diff --git a/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.ts b/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.ts new file mode 100644 index 00000000..498f0a24 --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.ts @@ -0,0 +1,2 @@ +export { ModuleImporter }; +import { ModuleImporter } from "./module-importer.cjs"; diff --git a/node_modules/@humanwhocodes/module-importer/dist/module-importer.js b/node_modules/@humanwhocodes/module-importer/dist/module-importer.js new file mode 100644 index 00000000..26e052da --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/dist/module-importer.js @@ -0,0 +1,18 @@ +import { createRequire } from 'module'; +import { fileURLToPath } from 'url'; +import { dirname } from 'path'; + +/** + * @fileoverview Universal module importer + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const require = createRequire(__dirname + "/"); +const { ModuleImporter } = require("./module-importer.cjs"); + +export { ModuleImporter }; diff --git a/node_modules/@humanwhocodes/module-importer/package.json b/node_modules/@humanwhocodes/module-importer/package.json new file mode 100644 index 00000000..8ece071e --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/package.json @@ -0,0 +1,65 @@ +{ + "name": "@humanwhocodes/module-importer", + "version": "1.0.1", + "description": "Universal module importer for Node.js", + "main": "src/module-importer.cjs", + "module": "src/module-importer.js", + "type": "module", + "types": "dist/module-importer.d.ts", + "exports": { + "require": "./src/module-importer.cjs", + "import": "./src/module-importer.js" + }, + "files": [ + "dist", + "src" + ], + "publishConfig": { + "access": "public" + }, + "gitHooks": { + "pre-commit": "lint-staged" + }, + "lint-staged": { + "*.js": [ + "eslint --fix" + ] + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + }, + "scripts": { + "build": "rollup -c && tsc", + "prepare": "npm run build", + "lint": "eslint src/ tests/", + "test:unit": "c8 mocha tests/module-importer.test.js", + "test:build": "node tests/pkg.test.cjs && node tests/pkg.test.mjs", + "test": "npm run test:unit && npm run test:build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/humanwhocodes/module-importer.git" + }, + "keywords": [ + "modules", + "esm", + "commonjs" + ], + "engines": { + "node": ">=12.22" + }, + "author": "Nicholas C. Zaks", + "license": "Apache-2.0", + "devDependencies": { + "@types/node": "^18.7.6", + "c8": "7.12.0", + "chai": "4.3.6", + "eslint": "8.22.0", + "lint-staged": "13.0.3", + "mocha": "9.2.2", + "rollup": "2.78.0", + "typescript": "4.7.4", + "yorkie": "2.0.0" + } +} diff --git a/node_modules/@humanwhocodes/module-importer/src/module-importer.cjs b/node_modules/@humanwhocodes/module-importer/src/module-importer.cjs new file mode 100644 index 00000000..3efb095e --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/src/module-importer.cjs @@ -0,0 +1,81 @@ +/** + * @fileoverview Universal module importer + */ + +//----------------------------------------------------------------------------- +// Imports +//----------------------------------------------------------------------------- + +const { createRequire } = require("module"); +const { pathToFileURL } = require("url"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const SLASHES = new Set(["/", "\\"]); + +/** + * Normalizes directories to have a trailing slash. + * Resolve is pretty finicky -- if the directory name doesn't have + * a trailing slash then it tries to look in the parent directory. + * i.e., if the directory is "/usr/nzakas/foo" it will start the + * search in /usr/nzakas. However, if the directory is "/user/nzakas/foo/", + * then it will start the search in /user/nzakas/foo. + * @param {string} directory The directory to check. + * @returns {string} The normalized directory. + */ +function normalizeDirectory(directory) { + if (!SLASHES.has(directory[directory.length-1])) { + return directory + "/"; + } + + return directory; +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Class for importing both CommonJS and ESM modules in Node.js. + */ +exports.ModuleImporter = class ModuleImporter { + + /** + * Creates a new instance. + * @param {string} [cwd] The current working directory to resolve from. + */ + constructor(cwd = process.cwd()) { + + /** + * The base directory from which paths should be resolved. + * @type {string} + */ + this.cwd = normalizeDirectory(cwd); + } + + /** + * Resolves a module based on its name or location. + * @param {string} specifier Either an npm package name or + * relative file path. + * @returns {string|undefined} The location of the import. + * @throws {Error} If specifier cannot be located. + */ + resolve(specifier) { + const require = createRequire(this.cwd); + return require.resolve(specifier); + } + + /** + * Imports a module based on its name or location. + * @param {string} specifier Either an npm package name or + * relative file path. + * @returns {Promise} The module's object. + */ + import(specifier) { + const location = this.resolve(specifier); + return import(pathToFileURL(location).href); + } + +} diff --git a/node_modules/@humanwhocodes/module-importer/src/module-importer.js b/node_modules/@humanwhocodes/module-importer/src/module-importer.js new file mode 100644 index 00000000..f5464e18 --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/src/module-importer.js @@ -0,0 +1,22 @@ +/** + * @fileoverview Universal module importer + */ + +//----------------------------------------------------------------------------- +// Imports +//----------------------------------------------------------------------------- + +import { createRequire } from "module"; +import { fileURLToPath } from "url"; +import { dirname } from "path"; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const require = createRequire(__dirname + "/"); +const { ModuleImporter } = require("./module-importer.cjs"); + +export { ModuleImporter }; diff --git a/node_modules/@humanwhocodes/retry/LICENSE b/node_modules/@humanwhocodes/retry/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/node_modules/@humanwhocodes/retry/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@humanwhocodes/retry/README.md b/node_modules/@humanwhocodes/retry/README.md new file mode 100644 index 00000000..0ec7a471 --- /dev/null +++ b/node_modules/@humanwhocodes/retry/README.md @@ -0,0 +1,177 @@ +# Retry utility + +by [Nicholas C. Zakas](https://humanwhocodes.com) + +If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate) or [nominate me](https://stars.github.com/nominate/) for a GitHub Star. + +## Description + +A utility for retrying failed async JavaScript calls based on the error returned. + +## Usage + +### Node.js + +Install using [npm][npm] or [yarn][yarn]: + +``` +npm install @humanwhocodes/retry + +# or + +yarn add @humanwhocodes/retry +``` + +Import into your Node.js project: + +```js +// CommonJS +const { Retrier } = require("@humanwhocodes/retry"); + +// ESM +import { Retrier } from "@humanwhocodes/retry"; +``` + +### Deno + +Install using [JSR](https://jsr.io): + +```shell +deno add @humanwhocodes/retry + +#or + +jsr add @humanwhocodes/retry +``` + +Then import into your Deno project: + +```js +import { Retrier } from "@humanwhocodes/retry"; +``` + +### Bun + +Install using this command: + +``` +bun add @humanwhocodes/retry +``` + +Import into your Bun project: + +```js +import { Retrier } from "@humanwhocodes/retry"; +``` + +### Browser + +It's recommended to import the minified version to save bandwidth: + +```js +import { Retrier } from "https://cdn.skypack.dev/@humanwhocodes/retry?min"; +``` + +However, you can also import the unminified version for debugging purposes: + +```js +import { Retrier } from "https://cdn.skypack.dev/@humanwhocodes/retry"; +``` + +## API + +After importing, create a new instance of `Retrier` and specify the function to run on the error. This function should return `true` if you want the call retried and `false` if not. + +```js +// this instance will retry if the specific error code is found +const retrier = new Retrier(error => { + return error.code === "ENFILE" || error.code === "EMFILE"; +}); +``` + +Then, call the `retry()` method around the function you'd like to retry, such as: + +```js +import fs from "fs/promises"; + +const retrier = new Retrier(error => { + return error.code === "ENFILE" || error.code === "EMFILE"; +}); + +const text = await retrier.retry(() => fs.readFile("README.md", "utf8")); +``` + +The `retry()` method will either pass through the result on success or wait and retry on failure. Any error that isn't caught by the retrier is automatically rejected so the end result is a transparent passing through of both success and failure. + +### Setting a Timeout + +You can control how long a task will attempt to retry before giving up by passing the `timeout` option to the `Retrier` constructor. By default, the timeout is one minute. + +```js +import fs from "fs/promises"; + +const retrier = new Retrier(error => { + return error.code === "ENFILE" || error.code === "EMFILE"; +}, { timeout: 100_000 }); + +const text = await retrier.retry(() => fs.readFile("README.md", "utf8")); +``` + +When a call times out, it rejects the first error that was received from calling the function. + +### Setting a Concurrency Limit + +When processing a large number of function calls, you can limit the number of concurrent function calls by passing the `concurrency` option to the `Retrier` constructor. By default, `concurrency` is 1000. + +```js +import fs from "fs/promises"; + +const retrier = new Retrier(error => { + return error.code === "ENFILE" || error.code === "EMFILE"; +}, { concurrency: 100 }); + +const filenames = getFilenames(); +const contents = await Promise.all( + filenames.map(filename => retrier.retry(() => fs.readFile(filename, "utf8")) +); +``` + +### Aborting with `AbortSignal` + +You can also pass an `AbortSignal` to cancel a retry: + +```js +import fs from "fs/promises"; + +const controller = new AbortController(); +const retrier = new Retrier(error => { + return error.code === "ENFILE" || error.code === "EMFILE"; +}); + +const text = await retrier.retry( + () => fs.readFile("README.md", "utf8"), + { signal: controller.signal } +); +``` + +## Developer Setup + +1. Fork the repository +2. Clone your fork +3. Run `npm install` to setup dependencies +4. Run `npm test` to run tests + +### Debug Output + +Enable debugging output by setting the `DEBUG` environment variable to `"@hwc/retry"` before running. + +## License + +Apache 2.0 + +## Prior Art + +This utility is inspired by, and contains code from [`graceful-fs`](https://github.com/isaacs/node-graceful-fs). + +[npm]: https://npmjs.com/ +[yarn]: https://yarnpkg.com/ diff --git a/node_modules/@humanwhocodes/retry/dist/retrier.cjs b/node_modules/@humanwhocodes/retry/dist/retrier.cjs new file mode 100644 index 00000000..635e1e08 --- /dev/null +++ b/node_modules/@humanwhocodes/retry/dist/retrier.cjs @@ -0,0 +1,478 @@ +'use strict'; + +/** + * @fileoverview A utility for retrying failed async method calls. + */ + +/* global setTimeout, clearTimeout */ + +//----------------------------------------------------------------------------- +// Constants +//----------------------------------------------------------------------------- + +const MAX_TASK_TIMEOUT = 60000; +const MAX_TASK_DELAY = 100; +const MAX_CONCURRENCY = 1000; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Logs a message to the console if the DEBUG environment variable is set. + * @param {string} message The message to log. + * @returns {void} + */ +function debug(message) { + if (globalThis?.process?.env.DEBUG === "@hwc/retry") { + console.debug(message); + } +} + +/* + * The following logic has been extracted from graceful-fs. + * + * The ISC License + * + * Copyright (c) 2011-2023 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR + * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/** + * Checks if it is time to retry a task based on the timestamp and last attempt time. + * @param {RetryTask} task The task to check. + * @param {number} maxDelay The maximum delay for the queue. + * @returns {boolean} true if it is time to retry, false otherwise. + */ +function isTimeToRetry(task, maxDelay) { + const timeSinceLastAttempt = Date.now() - task.lastAttempt; + const timeSinceStart = Math.max(task.lastAttempt - task.timestamp, 1); + const desiredDelay = Math.min(timeSinceStart * 1.2, maxDelay); + + return timeSinceLastAttempt >= desiredDelay; +} + +/** + * Checks if it is time to bail out based on the given timestamp. + * @param {RetryTask} task The task to check. + * @param {number} timeout The timeout for the queue. + * @returns {boolean} true if it is time to bail, false otherwise. + */ +function isTimeToBail(task, timeout) { + return task.age > timeout; +} + +/** + * Creates a new promise with resolve and reject functions. + * @returns {{promise:Promise, resolve:(value:any) => any, reject: (value:any) => any}} A new promise. + */ +function createPromise() { + if (Promise.withResolvers) { + return Promise.withResolvers(); + } + + let resolve, reject; + + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + + if (resolve === undefined || reject === undefined) { + throw new Error("Promise executor did not initialize resolve or reject."); + } + + return { promise, resolve, reject }; +} + + +/** + * A class to represent a task in the retry queue. + */ +class RetryTask { + + /** + * The unique ID for the task. + * @type {string} + */ + id = Math.random().toString(36).slice(2); + + /** + * The function to call. + * @type {Function} + */ + fn; + + /** + * The error that was thrown. + * @type {Error} + */ + error; + + /** + * The timestamp of the task. + * @type {number} + */ + timestamp = Date.now(); + + /** + * The timestamp of the last attempt. + * @type {number} + */ + lastAttempt = this.timestamp; + + /** + * The resolve function for the promise. + * @type {Function} + */ + resolve; + + /** + * The reject function for the promise. + * @type {Function} + */ + reject; + + /** + * The AbortSignal to monitor for cancellation. + * @type {AbortSignal|undefined} + */ + signal; + + /** + * Creates a new instance. + * @param {Function} fn The function to call. + * @param {Error} error The error that was thrown. + * @param {Function} resolve The resolve function for the promise. + * @param {Function} reject The reject function for the promise. + * @param {AbortSignal|undefined} signal The AbortSignal to monitor for cancellation. + */ + constructor(fn, error, resolve, reject, signal) { + this.fn = fn; + this.error = error; + this.timestamp = Date.now(); + this.lastAttempt = Date.now(); + this.resolve = resolve; + this.reject = reject; + this.signal = signal; + } + + /** + * Gets the age of the task. + * @returns {number} The age of the task in milliseconds. + * @readonly + */ + get age() { + return Date.now() - this.timestamp; + } +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class that manages a queue of retry jobs. + */ +class Retrier { + + /** + * Represents the queue for processing tasks. + * @type {Array} + */ + #retrying = []; + + /** + * Represents the queue for pending tasks. + * @type {Array} + */ + #pending = []; + + /** + * The number of tasks currently being processed. + * @type {number} + */ + #working = 0; + + /** + * The timeout for the queue. + * @type {number} + */ + #timeout; + + /** + * The maximum delay for the queue. + * @type {number} + */ + #maxDelay; + + /** + * The setTimeout() timer ID. + * @type {NodeJS.Timeout|undefined} + */ + #timerId; + + /** + * The function to call. + * @type {Function} + */ + #check; + + /** + * The maximum number of concurrent tasks. + * @type {number} + */ + #concurrency; + + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + * @param {number} [options.concurrency] The maximum number of concurrent tasks. + */ + constructor(check, { timeout = MAX_TASK_TIMEOUT, maxDelay = MAX_TASK_DELAY, concurrency = MAX_CONCURRENCY } = {}) { + + if (typeof check !== "function") { + throw new Error("Missing function to check errors"); + } + + this.#check = check; + this.#timeout = timeout; + this.#maxDelay = maxDelay; + this.#concurrency = concurrency; + } + + /** + * Gets the number of tasks waiting to be retried. + * @returns {number} The number of tasks in the retry queue. + */ + get retrying() { + return this.#retrying.length; + } + + /** + * Gets the number of tasks waiting to be processed in the pending queue. + * @returns {number} The number of tasks in the pending queue. + */ + get pending() { + return this.#pending.length; + } + + /** + * Gets the number of tasks currently being processed. + * @returns {number} The number of tasks currently being processed. + */ + get working() { + return this.#working; + } + + /** + * Calls the function and retries if it fails. + * @param {Function} fn The function to call. + * @param {Object} options The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @param {Promise} options.promise The promise to return when the function settles. + * @param {Function} options.resolve The resolve function for the promise. + * @param {Function} options.reject The reject function for the promise. + * @returns {Promise} A promise that resolves when the function is + * called successfully. + */ + #call(fn, { signal, promise, resolve, reject }) { + + let result; + + try { + result = fn(); + } catch (/** @type {any} */ error) { + reject(new Error(`Synchronous error: ${error.message}`, { cause: error })); + return promise; + } + + // if the result is not a promise then reject an error + if (!result || typeof result.then !== "function") { + reject(new Error("Result is not a promise.")); + return promise; + } + + this.#working++; + promise.finally(() => { + this.#working--; + this.#processPending(); + }) + // `promise.finally` creates a new promise that may be rejected, so it must be handled. + .catch(() => { }); + + // call the original function and catch any ENFILE or EMFILE errors + Promise.resolve(result) + .then(value => { + debug("Function called successfully without retry."); + resolve(value); + }) + .catch(error => { + if (!this.#check(error)) { + reject(error); + return; + } + + const task = new RetryTask(fn, error, resolve, reject, signal); + + debug(`Function failed, queuing for retry with task ${task.id}.`); + this.#retrying.push(task); + + signal?.addEventListener("abort", () => { + debug(`Task ${task.id} was aborted due to AbortSignal.`); + reject(signal.reason); + }); + + this.#processQueue(); + }); + + return promise; + } + + /** + * Adds a new retry job to the queue. + * @template {(...args: unknown[]) => Promise} Func + * @template {Awaited>} RetVal + * @param {Func} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is processed. + */ + retry(fn, { signal } = {}) { + + signal?.throwIfAborted(); + + const { promise, resolve, reject } = createPromise(); + + this.#pending.push(() => this.#call(fn, { signal, promise, resolve, reject })); + this.#processPending(); + + return promise; + } + + + /** + * Processes the pending queue and the retry queue. + * @returns {void} + */ + #processAll() { + if (this.pending) { + this.#processPending(); + } + + if (this.retrying) { + this.#processQueue(); + } + } + + /** + * Processes the pending queue to see which tasks can be started. + * @returns {void} + */ + #processPending() { + + debug(`Processing pending tasks: ${this.pending} pending, ${this.working} working.`); + + const available = this.#concurrency - this.working; + + if (available <= 0) { + return; + } + + const count = Math.min(this.pending, available); + + for (let i = 0; i < count; i++) { + const task = this.#pending.shift(); + task?.(); + } + + debug(`Processed pending tasks: ${this.pending} pending, ${this.working} working.`); + } + + /** + * Processes the queue. + * @returns {void} + */ + #processQueue() { + // clear any timer because we're going to check right now + clearTimeout(this.#timerId); + this.#timerId = undefined; + + debug(`Processing retry queue: ${this.retrying} retrying, ${this.working} working.`); + + const processAgain = () => { + this.#timerId = setTimeout(() => this.#processAll(), 0); + }; + + // if there's nothing in the queue, we're done + const task = this.#retrying.shift(); + if (!task) { + debug("Queue is empty, exiting."); + + if (this.pending) { + processAgain(); + } + return; + } + + // if it's time to bail, then bail + if (isTimeToBail(task, this.#timeout)) { + debug(`Task ${task.id} was abandoned due to timeout.`); + task.reject(task.error); + processAgain(); + return; + } + + // if it's not time to retry, then wait and try again + if (!isTimeToRetry(task, this.#maxDelay)) { + debug(`Task ${task.id} is not ready to retry, skipping.`); + this.#retrying.push(task); + processAgain(); + return; + } + + // otherwise, try again + task.lastAttempt = Date.now(); + + // Promise.resolve needed in case it's a thenable but not a Promise + Promise.resolve(task.fn()) + // @ts-ignore because we know it's any + .then(result => { + debug(`Task ${task.id} succeeded after ${task.age}ms.`); + task.resolve(result); + }) + + // @ts-ignore because we know it's any + .catch(error => { + if (!this.#check(error)) { + debug(`Task ${task.id} failed with non-retryable error: ${error.message}.`); + task.reject(error); + return; + } + + // update the task timestamp and push to back of queue to try again + task.lastAttempt = Date.now(); + this.#retrying.push(task); + debug(`Task ${task.id} failed, requeueing to try again.`); + }) + .finally(() => { + this.#processAll(); + }); + } +} + +exports.Retrier = Retrier; diff --git a/node_modules/@humanwhocodes/retry/dist/retrier.d.cts b/node_modules/@humanwhocodes/retry/dist/retrier.d.cts new file mode 100644 index 00000000..2d3811ef --- /dev/null +++ b/node_modules/@humanwhocodes/retry/dist/retrier.d.cts @@ -0,0 +1,46 @@ +/** + * A class that manages a queue of retry jobs. + */ +export class Retrier { + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + * @param {number} [options.concurrency] The maximum number of concurrent tasks. + */ + constructor(check: Function, { timeout, maxDelay, concurrency }?: { + timeout?: number | undefined; + maxDelay?: number | undefined; + concurrency?: number | undefined; + } | undefined); + /** + * Gets the number of tasks waiting to be retried. + * @returns {number} The number of tasks in the retry queue. + */ + get retrying(): number; + /** + * Gets the number of tasks waiting to be processed in the pending queue. + * @returns {number} The number of tasks in the pending queue. + */ + get pending(): number; + /** + * Gets the number of tasks currently being processed. + * @returns {number} The number of tasks currently being processed. + */ + get working(): number; + /** + * Adds a new retry job to the queue. + * @template {(...args: unknown[]) => Promise} Func + * @template {Awaited>} RetVal + * @param {Func} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is processed. + */ + retry Promise, RetVal extends Awaited>>(fn: Func, { signal }?: { + signal?: AbortSignal | undefined; + } | undefined): Promise; + #private; +} diff --git a/node_modules/@humanwhocodes/retry/dist/retrier.d.ts b/node_modules/@humanwhocodes/retry/dist/retrier.d.ts new file mode 100644 index 00000000..2d3811ef --- /dev/null +++ b/node_modules/@humanwhocodes/retry/dist/retrier.d.ts @@ -0,0 +1,46 @@ +/** + * A class that manages a queue of retry jobs. + */ +export class Retrier { + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + * @param {number} [options.concurrency] The maximum number of concurrent tasks. + */ + constructor(check: Function, { timeout, maxDelay, concurrency }?: { + timeout?: number | undefined; + maxDelay?: number | undefined; + concurrency?: number | undefined; + } | undefined); + /** + * Gets the number of tasks waiting to be retried. + * @returns {number} The number of tasks in the retry queue. + */ + get retrying(): number; + /** + * Gets the number of tasks waiting to be processed in the pending queue. + * @returns {number} The number of tasks in the pending queue. + */ + get pending(): number; + /** + * Gets the number of tasks currently being processed. + * @returns {number} The number of tasks currently being processed. + */ + get working(): number; + /** + * Adds a new retry job to the queue. + * @template {(...args: unknown[]) => Promise} Func + * @template {Awaited>} RetVal + * @param {Func} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is processed. + */ + retry Promise, RetVal extends Awaited>>(fn: Func, { signal }?: { + signal?: AbortSignal | undefined; + } | undefined): Promise; + #private; +} diff --git a/node_modules/@humanwhocodes/retry/dist/retrier.js b/node_modules/@humanwhocodes/retry/dist/retrier.js new file mode 100644 index 00000000..29c9d3ea --- /dev/null +++ b/node_modules/@humanwhocodes/retry/dist/retrier.js @@ -0,0 +1,477 @@ +// @ts-self-types="./retrier.d.ts" +/** + * @fileoverview A utility for retrying failed async method calls. + */ + +/* global setTimeout, clearTimeout */ + +//----------------------------------------------------------------------------- +// Constants +//----------------------------------------------------------------------------- + +const MAX_TASK_TIMEOUT = 60000; +const MAX_TASK_DELAY = 100; +const MAX_CONCURRENCY = 1000; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Logs a message to the console if the DEBUG environment variable is set. + * @param {string} message The message to log. + * @returns {void} + */ +function debug(message) { + if (globalThis?.process?.env.DEBUG === "@hwc/retry") { + console.debug(message); + } +} + +/* + * The following logic has been extracted from graceful-fs. + * + * The ISC License + * + * Copyright (c) 2011-2023 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR + * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/** + * Checks if it is time to retry a task based on the timestamp and last attempt time. + * @param {RetryTask} task The task to check. + * @param {number} maxDelay The maximum delay for the queue. + * @returns {boolean} true if it is time to retry, false otherwise. + */ +function isTimeToRetry(task, maxDelay) { + const timeSinceLastAttempt = Date.now() - task.lastAttempt; + const timeSinceStart = Math.max(task.lastAttempt - task.timestamp, 1); + const desiredDelay = Math.min(timeSinceStart * 1.2, maxDelay); + + return timeSinceLastAttempt >= desiredDelay; +} + +/** + * Checks if it is time to bail out based on the given timestamp. + * @param {RetryTask} task The task to check. + * @param {number} timeout The timeout for the queue. + * @returns {boolean} true if it is time to bail, false otherwise. + */ +function isTimeToBail(task, timeout) { + return task.age > timeout; +} + +/** + * Creates a new promise with resolve and reject functions. + * @returns {{promise:Promise, resolve:(value:any) => any, reject: (value:any) => any}} A new promise. + */ +function createPromise() { + if (Promise.withResolvers) { + return Promise.withResolvers(); + } + + let resolve, reject; + + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + + if (resolve === undefined || reject === undefined) { + throw new Error("Promise executor did not initialize resolve or reject."); + } + + return { promise, resolve, reject }; +} + + +/** + * A class to represent a task in the retry queue. + */ +class RetryTask { + + /** + * The unique ID for the task. + * @type {string} + */ + id = Math.random().toString(36).slice(2); + + /** + * The function to call. + * @type {Function} + */ + fn; + + /** + * The error that was thrown. + * @type {Error} + */ + error; + + /** + * The timestamp of the task. + * @type {number} + */ + timestamp = Date.now(); + + /** + * The timestamp of the last attempt. + * @type {number} + */ + lastAttempt = this.timestamp; + + /** + * The resolve function for the promise. + * @type {Function} + */ + resolve; + + /** + * The reject function for the promise. + * @type {Function} + */ + reject; + + /** + * The AbortSignal to monitor for cancellation. + * @type {AbortSignal|undefined} + */ + signal; + + /** + * Creates a new instance. + * @param {Function} fn The function to call. + * @param {Error} error The error that was thrown. + * @param {Function} resolve The resolve function for the promise. + * @param {Function} reject The reject function for the promise. + * @param {AbortSignal|undefined} signal The AbortSignal to monitor for cancellation. + */ + constructor(fn, error, resolve, reject, signal) { + this.fn = fn; + this.error = error; + this.timestamp = Date.now(); + this.lastAttempt = Date.now(); + this.resolve = resolve; + this.reject = reject; + this.signal = signal; + } + + /** + * Gets the age of the task. + * @returns {number} The age of the task in milliseconds. + * @readonly + */ + get age() { + return Date.now() - this.timestamp; + } +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class that manages a queue of retry jobs. + */ +class Retrier { + + /** + * Represents the queue for processing tasks. + * @type {Array} + */ + #retrying = []; + + /** + * Represents the queue for pending tasks. + * @type {Array} + */ + #pending = []; + + /** + * The number of tasks currently being processed. + * @type {number} + */ + #working = 0; + + /** + * The timeout for the queue. + * @type {number} + */ + #timeout; + + /** + * The maximum delay for the queue. + * @type {number} + */ + #maxDelay; + + /** + * The setTimeout() timer ID. + * @type {NodeJS.Timeout|undefined} + */ + #timerId; + + /** + * The function to call. + * @type {Function} + */ + #check; + + /** + * The maximum number of concurrent tasks. + * @type {number} + */ + #concurrency; + + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + * @param {number} [options.concurrency] The maximum number of concurrent tasks. + */ + constructor(check, { timeout = MAX_TASK_TIMEOUT, maxDelay = MAX_TASK_DELAY, concurrency = MAX_CONCURRENCY } = {}) { + + if (typeof check !== "function") { + throw new Error("Missing function to check errors"); + } + + this.#check = check; + this.#timeout = timeout; + this.#maxDelay = maxDelay; + this.#concurrency = concurrency; + } + + /** + * Gets the number of tasks waiting to be retried. + * @returns {number} The number of tasks in the retry queue. + */ + get retrying() { + return this.#retrying.length; + } + + /** + * Gets the number of tasks waiting to be processed in the pending queue. + * @returns {number} The number of tasks in the pending queue. + */ + get pending() { + return this.#pending.length; + } + + /** + * Gets the number of tasks currently being processed. + * @returns {number} The number of tasks currently being processed. + */ + get working() { + return this.#working; + } + + /** + * Calls the function and retries if it fails. + * @param {Function} fn The function to call. + * @param {Object} options The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @param {Promise} options.promise The promise to return when the function settles. + * @param {Function} options.resolve The resolve function for the promise. + * @param {Function} options.reject The reject function for the promise. + * @returns {Promise} A promise that resolves when the function is + * called successfully. + */ + #call(fn, { signal, promise, resolve, reject }) { + + let result; + + try { + result = fn(); + } catch (/** @type {any} */ error) { + reject(new Error(`Synchronous error: ${error.message}`, { cause: error })); + return promise; + } + + // if the result is not a promise then reject an error + if (!result || typeof result.then !== "function") { + reject(new Error("Result is not a promise.")); + return promise; + } + + this.#working++; + promise.finally(() => { + this.#working--; + this.#processPending(); + }) + // `promise.finally` creates a new promise that may be rejected, so it must be handled. + .catch(() => { }); + + // call the original function and catch any ENFILE or EMFILE errors + Promise.resolve(result) + .then(value => { + debug("Function called successfully without retry."); + resolve(value); + }) + .catch(error => { + if (!this.#check(error)) { + reject(error); + return; + } + + const task = new RetryTask(fn, error, resolve, reject, signal); + + debug(`Function failed, queuing for retry with task ${task.id}.`); + this.#retrying.push(task); + + signal?.addEventListener("abort", () => { + debug(`Task ${task.id} was aborted due to AbortSignal.`); + reject(signal.reason); + }); + + this.#processQueue(); + }); + + return promise; + } + + /** + * Adds a new retry job to the queue. + * @template {(...args: unknown[]) => Promise} Func + * @template {Awaited>} RetVal + * @param {Func} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is processed. + */ + retry(fn, { signal } = {}) { + + signal?.throwIfAborted(); + + const { promise, resolve, reject } = createPromise(); + + this.#pending.push(() => this.#call(fn, { signal, promise, resolve, reject })); + this.#processPending(); + + return promise; + } + + + /** + * Processes the pending queue and the retry queue. + * @returns {void} + */ + #processAll() { + if (this.pending) { + this.#processPending(); + } + + if (this.retrying) { + this.#processQueue(); + } + } + + /** + * Processes the pending queue to see which tasks can be started. + * @returns {void} + */ + #processPending() { + + debug(`Processing pending tasks: ${this.pending} pending, ${this.working} working.`); + + const available = this.#concurrency - this.working; + + if (available <= 0) { + return; + } + + const count = Math.min(this.pending, available); + + for (let i = 0; i < count; i++) { + const task = this.#pending.shift(); + task?.(); + } + + debug(`Processed pending tasks: ${this.pending} pending, ${this.working} working.`); + } + + /** + * Processes the queue. + * @returns {void} + */ + #processQueue() { + // clear any timer because we're going to check right now + clearTimeout(this.#timerId); + this.#timerId = undefined; + + debug(`Processing retry queue: ${this.retrying} retrying, ${this.working} working.`); + + const processAgain = () => { + this.#timerId = setTimeout(() => this.#processAll(), 0); + }; + + // if there's nothing in the queue, we're done + const task = this.#retrying.shift(); + if (!task) { + debug("Queue is empty, exiting."); + + if (this.pending) { + processAgain(); + } + return; + } + + // if it's time to bail, then bail + if (isTimeToBail(task, this.#timeout)) { + debug(`Task ${task.id} was abandoned due to timeout.`); + task.reject(task.error); + processAgain(); + return; + } + + // if it's not time to retry, then wait and try again + if (!isTimeToRetry(task, this.#maxDelay)) { + debug(`Task ${task.id} is not ready to retry, skipping.`); + this.#retrying.push(task); + processAgain(); + return; + } + + // otherwise, try again + task.lastAttempt = Date.now(); + + // Promise.resolve needed in case it's a thenable but not a Promise + Promise.resolve(task.fn()) + // @ts-ignore because we know it's any + .then(result => { + debug(`Task ${task.id} succeeded after ${task.age}ms.`); + task.resolve(result); + }) + + // @ts-ignore because we know it's any + .catch(error => { + if (!this.#check(error)) { + debug(`Task ${task.id} failed with non-retryable error: ${error.message}.`); + task.reject(error); + return; + } + + // update the task timestamp and push to back of queue to try again + task.lastAttempt = Date.now(); + this.#retrying.push(task); + debug(`Task ${task.id} failed, requeueing to try again.`); + }) + .finally(() => { + this.#processAll(); + }); + } +} + +export { Retrier }; diff --git a/node_modules/@humanwhocodes/retry/dist/retrier.min.js b/node_modules/@humanwhocodes/retry/dist/retrier.min.js new file mode 100644 index 00000000..37609265 --- /dev/null +++ b/node_modules/@humanwhocodes/retry/dist/retrier.min.js @@ -0,0 +1 @@ +function e(e){"@hwc/retry"===globalThis?.process?.env.DEBUG&&console.debug(e)}class RetryTask{id=Math.random().toString(36).slice(2);fn;error;timestamp=Date.now();lastAttempt=this.timestamp;resolve;reject;signal;constructor(e,t,r,i,s){this.fn=e,this.error=t,this.timestamp=Date.now(),this.lastAttempt=Date.now(),this.resolve=r,this.reject=i,this.signal=s}get age(){return Date.now()-this.timestamp}}class Retrier{#e=[];#t=[];#r=0;#i;#s;#n;#o;#c;constructor(e,{timeout:t=6e4,maxDelay:r=100,concurrency:i=1e3}={}){if("function"!=typeof e)throw new Error("Missing function to check errors");this.#o=e,this.#i=t,this.#s=r,this.#c=i}get retrying(){return this.#e.length}get pending(){return this.#t.length}get working(){return this.#r}#a(t,{signal:r,promise:i,resolve:s,reject:n}){let o;try{o=t()}catch(e){return n(new Error(`Synchronous error: ${e.message}`,{cause:e})),i}return o&&"function"==typeof o.then?(this.#r++,i.finally((()=>{this.#r--,this.#h()})).catch((()=>{})),Promise.resolve(o).then((t=>{e("Function called successfully without retry."),s(t)})).catch((i=>{if(!this.#o(i))return void n(i);const o=new RetryTask(t,i,s,n,r);e(`Function failed, queuing for retry with task ${o.id}.`),this.#e.push(o),r?.addEventListener("abort",(()=>{e(`Task ${o.id} was aborted due to AbortSignal.`),n(r.reason)})),this.#g()})),i):(n(new Error("Result is not a promise.")),i)}retry(e,{signal:t}={}){t?.throwIfAborted();const{promise:r,resolve:i,reject:s}=function(){if(Promise.withResolvers)return Promise.withResolvers();let e,t;const r=new Promise(((r,i)=>{e=r,t=i}));if(void 0===e||void 0===t)throw new Error("Promise executor did not initialize resolve or reject.");return{promise:r,resolve:e,reject:t}}();return this.#t.push((()=>this.#a(e,{signal:t,promise:r,resolve:i,reject:s}))),this.#h(),r}#u(){this.pending&&this.#h(),this.retrying&&this.#g()}#h(){e(`Processing pending tasks: ${this.pending} pending, ${this.working} working.`);const t=this.#c-this.working;if(t<=0)return;const r=Math.min(this.pending,t);for(let e=0;e{this.#n=setTimeout((()=>this.#u()),0)},r=this.#e.shift();return r?function(e,t){return e.age>t}(r,this.#i)?(e(`Task ${r.id} was abandoned due to timeout.`),r.reject(r.error),void t()):function(e,t){const r=Date.now()-e.lastAttempt,i=Math.max(e.lastAttempt-e.timestamp,1);return r>=Math.min(1.2*i,t)}(r,this.#s)?(r.lastAttempt=Date.now(),void Promise.resolve(r.fn()).then((t=>{e(`Task ${r.id} succeeded after ${r.age}ms.`),r.resolve(t)})).catch((t=>{if(!this.#o(t))return e(`Task ${r.id} failed with non-retryable error: ${t.message}.`),void r.reject(t);r.lastAttempt=Date.now(),this.#e.push(r),e(`Task ${r.id} failed, requeueing to try again.`)})).finally((()=>{this.#u()}))):(e(`Task ${r.id} is not ready to retry, skipping.`),this.#e.push(r),void t()):(e("Queue is empty, exiting."),void(this.pending&&t()))}}export{Retrier}; diff --git a/node_modules/@humanwhocodes/retry/dist/retrier.mjs b/node_modules/@humanwhocodes/retry/dist/retrier.mjs new file mode 100644 index 00000000..a05cd0d1 --- /dev/null +++ b/node_modules/@humanwhocodes/retry/dist/retrier.mjs @@ -0,0 +1,476 @@ +/** + * @fileoverview A utility for retrying failed async method calls. + */ + +/* global setTimeout, clearTimeout */ + +//----------------------------------------------------------------------------- +// Constants +//----------------------------------------------------------------------------- + +const MAX_TASK_TIMEOUT = 60000; +const MAX_TASK_DELAY = 100; +const MAX_CONCURRENCY = 1000; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Logs a message to the console if the DEBUG environment variable is set. + * @param {string} message The message to log. + * @returns {void} + */ +function debug(message) { + if (globalThis?.process?.env.DEBUG === "@hwc/retry") { + console.debug(message); + } +} + +/* + * The following logic has been extracted from graceful-fs. + * + * The ISC License + * + * Copyright (c) 2011-2023 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR + * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/** + * Checks if it is time to retry a task based on the timestamp and last attempt time. + * @param {RetryTask} task The task to check. + * @param {number} maxDelay The maximum delay for the queue. + * @returns {boolean} true if it is time to retry, false otherwise. + */ +function isTimeToRetry(task, maxDelay) { + const timeSinceLastAttempt = Date.now() - task.lastAttempt; + const timeSinceStart = Math.max(task.lastAttempt - task.timestamp, 1); + const desiredDelay = Math.min(timeSinceStart * 1.2, maxDelay); + + return timeSinceLastAttempt >= desiredDelay; +} + +/** + * Checks if it is time to bail out based on the given timestamp. + * @param {RetryTask} task The task to check. + * @param {number} timeout The timeout for the queue. + * @returns {boolean} true if it is time to bail, false otherwise. + */ +function isTimeToBail(task, timeout) { + return task.age > timeout; +} + +/** + * Creates a new promise with resolve and reject functions. + * @returns {{promise:Promise, resolve:(value:any) => any, reject: (value:any) => any}} A new promise. + */ +function createPromise() { + if (Promise.withResolvers) { + return Promise.withResolvers(); + } + + let resolve, reject; + + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + + if (resolve === undefined || reject === undefined) { + throw new Error("Promise executor did not initialize resolve or reject."); + } + + return { promise, resolve, reject }; +} + + +/** + * A class to represent a task in the retry queue. + */ +class RetryTask { + + /** + * The unique ID for the task. + * @type {string} + */ + id = Math.random().toString(36).slice(2); + + /** + * The function to call. + * @type {Function} + */ + fn; + + /** + * The error that was thrown. + * @type {Error} + */ + error; + + /** + * The timestamp of the task. + * @type {number} + */ + timestamp = Date.now(); + + /** + * The timestamp of the last attempt. + * @type {number} + */ + lastAttempt = this.timestamp; + + /** + * The resolve function for the promise. + * @type {Function} + */ + resolve; + + /** + * The reject function for the promise. + * @type {Function} + */ + reject; + + /** + * The AbortSignal to monitor for cancellation. + * @type {AbortSignal|undefined} + */ + signal; + + /** + * Creates a new instance. + * @param {Function} fn The function to call. + * @param {Error} error The error that was thrown. + * @param {Function} resolve The resolve function for the promise. + * @param {Function} reject The reject function for the promise. + * @param {AbortSignal|undefined} signal The AbortSignal to monitor for cancellation. + */ + constructor(fn, error, resolve, reject, signal) { + this.fn = fn; + this.error = error; + this.timestamp = Date.now(); + this.lastAttempt = Date.now(); + this.resolve = resolve; + this.reject = reject; + this.signal = signal; + } + + /** + * Gets the age of the task. + * @returns {number} The age of the task in milliseconds. + * @readonly + */ + get age() { + return Date.now() - this.timestamp; + } +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class that manages a queue of retry jobs. + */ +class Retrier { + + /** + * Represents the queue for processing tasks. + * @type {Array} + */ + #retrying = []; + + /** + * Represents the queue for pending tasks. + * @type {Array} + */ + #pending = []; + + /** + * The number of tasks currently being processed. + * @type {number} + */ + #working = 0; + + /** + * The timeout for the queue. + * @type {number} + */ + #timeout; + + /** + * The maximum delay for the queue. + * @type {number} + */ + #maxDelay; + + /** + * The setTimeout() timer ID. + * @type {NodeJS.Timeout|undefined} + */ + #timerId; + + /** + * The function to call. + * @type {Function} + */ + #check; + + /** + * The maximum number of concurrent tasks. + * @type {number} + */ + #concurrency; + + /** + * Creates a new instance. + * @param {Function} check The function to call. + * @param {object} [options] The options for the instance. + * @param {number} [options.timeout] The timeout for the queue. + * @param {number} [options.maxDelay] The maximum delay for the queue. + * @param {number} [options.concurrency] The maximum number of concurrent tasks. + */ + constructor(check, { timeout = MAX_TASK_TIMEOUT, maxDelay = MAX_TASK_DELAY, concurrency = MAX_CONCURRENCY } = {}) { + + if (typeof check !== "function") { + throw new Error("Missing function to check errors"); + } + + this.#check = check; + this.#timeout = timeout; + this.#maxDelay = maxDelay; + this.#concurrency = concurrency; + } + + /** + * Gets the number of tasks waiting to be retried. + * @returns {number} The number of tasks in the retry queue. + */ + get retrying() { + return this.#retrying.length; + } + + /** + * Gets the number of tasks waiting to be processed in the pending queue. + * @returns {number} The number of tasks in the pending queue. + */ + get pending() { + return this.#pending.length; + } + + /** + * Gets the number of tasks currently being processed. + * @returns {number} The number of tasks currently being processed. + */ + get working() { + return this.#working; + } + + /** + * Calls the function and retries if it fails. + * @param {Function} fn The function to call. + * @param {Object} options The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @param {Promise} options.promise The promise to return when the function settles. + * @param {Function} options.resolve The resolve function for the promise. + * @param {Function} options.reject The reject function for the promise. + * @returns {Promise} A promise that resolves when the function is + * called successfully. + */ + #call(fn, { signal, promise, resolve, reject }) { + + let result; + + try { + result = fn(); + } catch (/** @type {any} */ error) { + reject(new Error(`Synchronous error: ${error.message}`, { cause: error })); + return promise; + } + + // if the result is not a promise then reject an error + if (!result || typeof result.then !== "function") { + reject(new Error("Result is not a promise.")); + return promise; + } + + this.#working++; + promise.finally(() => { + this.#working--; + this.#processPending(); + }) + // `promise.finally` creates a new promise that may be rejected, so it must be handled. + .catch(() => { }); + + // call the original function and catch any ENFILE or EMFILE errors + Promise.resolve(result) + .then(value => { + debug("Function called successfully without retry."); + resolve(value); + }) + .catch(error => { + if (!this.#check(error)) { + reject(error); + return; + } + + const task = new RetryTask(fn, error, resolve, reject, signal); + + debug(`Function failed, queuing for retry with task ${task.id}.`); + this.#retrying.push(task); + + signal?.addEventListener("abort", () => { + debug(`Task ${task.id} was aborted due to AbortSignal.`); + reject(signal.reason); + }); + + this.#processQueue(); + }); + + return promise; + } + + /** + * Adds a new retry job to the queue. + * @template {(...args: unknown[]) => Promise} Func + * @template {Awaited>} RetVal + * @param {Func} fn The function to call. + * @param {object} [options] The options for the job. + * @param {AbortSignal} [options.signal] The AbortSignal to monitor for cancellation. + * @returns {Promise} A promise that resolves when the queue is processed. + */ + retry(fn, { signal } = {}) { + + signal?.throwIfAborted(); + + const { promise, resolve, reject } = createPromise(); + + this.#pending.push(() => this.#call(fn, { signal, promise, resolve, reject })); + this.#processPending(); + + return promise; + } + + + /** + * Processes the pending queue and the retry queue. + * @returns {void} + */ + #processAll() { + if (this.pending) { + this.#processPending(); + } + + if (this.retrying) { + this.#processQueue(); + } + } + + /** + * Processes the pending queue to see which tasks can be started. + * @returns {void} + */ + #processPending() { + + debug(`Processing pending tasks: ${this.pending} pending, ${this.working} working.`); + + const available = this.#concurrency - this.working; + + if (available <= 0) { + return; + } + + const count = Math.min(this.pending, available); + + for (let i = 0; i < count; i++) { + const task = this.#pending.shift(); + task?.(); + } + + debug(`Processed pending tasks: ${this.pending} pending, ${this.working} working.`); + } + + /** + * Processes the queue. + * @returns {void} + */ + #processQueue() { + // clear any timer because we're going to check right now + clearTimeout(this.#timerId); + this.#timerId = undefined; + + debug(`Processing retry queue: ${this.retrying} retrying, ${this.working} working.`); + + const processAgain = () => { + this.#timerId = setTimeout(() => this.#processAll(), 0); + }; + + // if there's nothing in the queue, we're done + const task = this.#retrying.shift(); + if (!task) { + debug("Queue is empty, exiting."); + + if (this.pending) { + processAgain(); + } + return; + } + + // if it's time to bail, then bail + if (isTimeToBail(task, this.#timeout)) { + debug(`Task ${task.id} was abandoned due to timeout.`); + task.reject(task.error); + processAgain(); + return; + } + + // if it's not time to retry, then wait and try again + if (!isTimeToRetry(task, this.#maxDelay)) { + debug(`Task ${task.id} is not ready to retry, skipping.`); + this.#retrying.push(task); + processAgain(); + return; + } + + // otherwise, try again + task.lastAttempt = Date.now(); + + // Promise.resolve needed in case it's a thenable but not a Promise + Promise.resolve(task.fn()) + // @ts-ignore because we know it's any + .then(result => { + debug(`Task ${task.id} succeeded after ${task.age}ms.`); + task.resolve(result); + }) + + // @ts-ignore because we know it's any + .catch(error => { + if (!this.#check(error)) { + debug(`Task ${task.id} failed with non-retryable error: ${error.message}.`); + task.reject(error); + return; + } + + // update the task timestamp and push to back of queue to try again + task.lastAttempt = Date.now(); + this.#retrying.push(task); + debug(`Task ${task.id} failed, requeueing to try again.`); + }) + .finally(() => { + this.#processAll(); + }); + } +} + +export { Retrier }; diff --git a/node_modules/@humanwhocodes/retry/package.json b/node_modules/@humanwhocodes/retry/package.json new file mode 100644 index 00000000..df8e9437 --- /dev/null +++ b/node_modules/@humanwhocodes/retry/package.json @@ -0,0 +1,77 @@ +{ + "name": "@humanwhocodes/retry", + "version": "0.4.3", + "description": "A utility to retry failed async methods.", + "type": "module", + "main": "dist/retrier.cjs", + "module": "dist/retrier.js", + "types": "dist/retrier.d.ts", + "exports": { + "require": { + "types": "./dist/retrier.d.cts", + "default": "./dist/retrier.cjs" + }, + "import": { + "types": "./dist/retrier.d.ts", + "default": "./dist/retrier.js" + } + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=18.18" + }, + "publishConfig": { + "access": "public" + }, + "gitHooks": { + "pre-commit": "lint-staged" + }, + "lint-staged": { + "*.js": [ + "eslint --fix" + ] + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + }, + "scripts": { + "build:cts-types": "node -e \"fs.copyFileSync('dist/retrier.d.ts', 'dist/retrier.d.cts')\"", + "build": "rollup -c && tsc && npm run build:cts-types", + "prepare": "npm run build", + "lint": "eslint src/ tests/", + "pretest": "npm run build", + "test:unit": "mocha tests/retrier.test.js", + "test:build": "node tests/pkg.test.cjs && node tests/pkg.test.mjs", + "test:jsr": "npx jsr@latest publish --dry-run", + "test:emfile": "node tools/check-emfile-handling.js", + "test": "npm run test:unit && npm run test:build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/humanwhocodes/retry.git" + }, + "keywords": [ + "nodejs", + "retry", + "async", + "promises" + ], + "author": "Nicholas C. Zaks", + "license": "Apache-2.0", + "devDependencies": { + "@eslint/js": "^8.49.0", + "@rollup/plugin-terser": "0.4.4", + "@tsconfig/node16": "^16.1.1", + "@types/mocha": "^10.0.3", + "@types/node": "20.12.6", + "eslint": "^8.21.0", + "lint-staged": "15.2.1", + "mocha": "^10.3.0", + "rollup": "3.29.4", + "typescript": "5.4.4", + "yorkie": "2.0.0" + } +} diff --git a/node_modules/@nodelib/fs.scandir/LICENSE b/node_modules/@nodelib/fs.scandir/LICENSE new file mode 100644 index 00000000..65a99946 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@nodelib/fs.scandir/README.md b/node_modules/@nodelib/fs.scandir/README.md new file mode 100644 index 00000000..e0b218b9 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/README.md @@ -0,0 +1,171 @@ +# @nodelib/fs.scandir + +> List files and directories inside the specified directory. + +## :bulb: Highlights + +The package is aimed at obtaining information about entries in the directory. + +* :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional). +* :gear: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type. See [`old` and `modern` mode](#old-and-modern-mode). +* :link: Can safely work with broken symbolic links. + +## Install + +```console +npm install @nodelib/fs.scandir +``` + +## Usage + +```ts +import * as fsScandir from '@nodelib/fs.scandir'; + +fsScandir.scandir('path', (error, stats) => { /* … */ }); +``` + +## API + +### .scandir(path, [optionsOrSettings], callback) + +Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path with standard callback-style. + +```ts +fsScandir.scandir('path', (error, entries) => { /* … */ }); +fsScandir.scandir('path', {}, (error, entries) => { /* … */ }); +fsScandir.scandir('path', new fsScandir.Settings(), (error, entries) => { /* … */ }); +``` + +### .scandirSync(path, [optionsOrSettings]) + +Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path. + +```ts +const entries = fsScandir.scandirSync('path'); +const entries = fsScandir.scandirSync('path', {}); +const entries = fsScandir.scandirSync(('path', new fsScandir.Settings()); +``` + +#### path + +* Required: `true` +* Type: `string | Buffer | URL` + +A path to a file. If a URL is provided, it must use the `file:` protocol. + +#### optionsOrSettings + +* Required: `false` +* Type: `Options | Settings` +* Default: An instance of `Settings` class + +An [`Options`](#options) object or an instance of [`Settings`](#settingsoptions) class. + +> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. + +### Settings([options]) + +A class of full settings of the package. + +```ts +const settings = new fsScandir.Settings({ followSymbolicLinks: false }); + +const entries = fsScandir.scandirSync('path', settings); +``` + +## Entry + +* `name` — The name of the entry (`unknown.txt`). +* `path` — The path of the entry relative to call directory (`root/unknown.txt`). +* `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class. On Node.js below 10.10 will be emulated by [`DirentFromStats`](./src/utils/fs.ts) class. +* `stats` (optional) — An instance of `fs.Stats` class. + +For example, the `scandir` call for `tools` directory with one directory inside: + +```ts +{ + dirent: Dirent { name: 'typedoc', /* … */ }, + name: 'typedoc', + path: 'tools/typedoc' +} +``` + +## Options + +### stats + +* Type: `boolean` +* Default: `false` + +Adds an instance of `fs.Stats` class to the [`Entry`](#entry). + +> :book: Always use `fs.readdir` without the `withFileTypes` option. ??TODO?? + +### followSymbolicLinks + +* Type: `boolean` +* Default: `false` + +Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`. + +### `throwErrorOnBrokenSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Throw an error when symbolic link is broken if `true` or safely use `lstat` call if `false`. + +### `pathSegmentSeparator` + +* Type: `string` +* Default: `path.sep` + +By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead. + +### `fs` + +* Type: [`FileSystemAdapter`](./src/adapters/fs.ts) +* Default: A default FS methods + +By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. + +```ts +interface FileSystemAdapter { + lstat?: typeof fs.lstat; + stat?: typeof fs.stat; + lstatSync?: typeof fs.lstatSync; + statSync?: typeof fs.statSync; + readdir?: typeof fs.readdir; + readdirSync?: typeof fs.readdirSync; +} + +const settings = new fsScandir.Settings({ + fs: { lstat: fakeLstat } +}); +``` + +## `old` and `modern` mode + +This package has two modes that are used depending on the environment and parameters of use. + +### old + +* Node.js below `10.10` or when the `stats` option is enabled + +When working in the old mode, the directory is read first (`fs.readdir`), then the type of entries is determined (`fs.lstat` and/or `fs.stat` for symbolic links). + +### modern + +* Node.js 10.10+ and the `stats` option is disabled + +In the modern mode, reading the directory (`fs.readdir` with the `withFileTypes` option) is combined with obtaining information about its entries. An additional call for symbolic links (`fs.stat`) is still present. + +This mode makes fewer calls to the file system. It's faster. + +## Changelog + +See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. diff --git a/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts b/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts new file mode 100644 index 00000000..827f1db0 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts @@ -0,0 +1,20 @@ +import type * as fsStat from '@nodelib/fs.stat'; +import type { Dirent, ErrnoException } from '../types'; +export interface ReaddirAsynchronousMethod { + (filepath: string, options: { + withFileTypes: true; + }, callback: (error: ErrnoException | null, files: Dirent[]) => void): void; + (filepath: string, callback: (error: ErrnoException | null, files: string[]) => void): void; +} +export interface ReaddirSynchronousMethod { + (filepath: string, options: { + withFileTypes: true; + }): Dirent[]; + (filepath: string): string[]; +} +export declare type FileSystemAdapter = fsStat.FileSystemAdapter & { + readdir: ReaddirAsynchronousMethod; + readdirSync: ReaddirSynchronousMethod; +}; +export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter; +export declare function createFileSystemAdapter(fsMethods?: Partial): FileSystemAdapter; diff --git a/node_modules/@nodelib/fs.scandir/out/adapters/fs.js b/node_modules/@nodelib/fs.scandir/out/adapters/fs.js new file mode 100644 index 00000000..f0fe0220 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/adapters/fs.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; +const fs = require("fs"); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; diff --git a/node_modules/@nodelib/fs.scandir/out/constants.d.ts b/node_modules/@nodelib/fs.scandir/out/constants.d.ts new file mode 100644 index 00000000..33f17497 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/constants.d.ts @@ -0,0 +1,4 @@ +/** + * IS `true` for Node.js 10.10 and greater. + */ +export declare const IS_SUPPORT_READDIR_WITH_FILE_TYPES: boolean; diff --git a/node_modules/@nodelib/fs.scandir/out/constants.js b/node_modules/@nodelib/fs.scandir/out/constants.js new file mode 100644 index 00000000..7e3d4411 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/constants.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; +const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); +if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { + throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); +} +const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); +const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); +const SUPPORTED_MAJOR_VERSION = 10; +const SUPPORTED_MINOR_VERSION = 10; +const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; +const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; +/** + * IS `true` for Node.js 10.10 and greater. + */ +exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; diff --git a/node_modules/@nodelib/fs.scandir/out/index.d.ts b/node_modules/@nodelib/fs.scandir/out/index.d.ts new file mode 100644 index 00000000..b9da83ed --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/index.d.ts @@ -0,0 +1,12 @@ +import type { FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod } from './adapters/fs'; +import * as async from './providers/async'; +import Settings, { Options } from './settings'; +import type { Dirent, Entry } from './types'; +declare type AsyncCallback = async.AsyncCallback; +declare function scandir(path: string, callback: AsyncCallback): void; +declare function scandir(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; +declare namespace scandir { + function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise; +} +declare function scandirSync(path: string, optionsOrSettings?: Options | Settings): Entry[]; +export { scandir, scandirSync, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod, Options }; diff --git a/node_modules/@nodelib/fs.scandir/out/index.js b/node_modules/@nodelib/fs.scandir/out/index.js new file mode 100644 index 00000000..99c70d3d --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Settings = exports.scandirSync = exports.scandir = void 0; +const async = require("./providers/async"); +const sync = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.scandirSync = scandirSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts b/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts new file mode 100644 index 00000000..5829676d --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts @@ -0,0 +1,7 @@ +/// +import type Settings from '../settings'; +import type { Entry } from '../types'; +export declare type AsyncCallback = (error: NodeJS.ErrnoException, entries: Entry[]) => void; +export declare function read(directory: string, settings: Settings, callback: AsyncCallback): void; +export declare function readdirWithFileTypes(directory: string, settings: Settings, callback: AsyncCallback): void; +export declare function readdir(directory: string, settings: Settings, callback: AsyncCallback): void; diff --git a/node_modules/@nodelib/fs.scandir/out/providers/async.js b/node_modules/@nodelib/fs.scandir/out/providers/async.js new file mode 100644 index 00000000..e8e2f0a9 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/async.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; +const fsStat = require("@nodelib/fs.stat"); +const rpl = require("run-parallel"); +const constants_1 = require("../constants"); +const utils = require("../utils"); +const common = require("./common"); +function read(directory, settings, callback) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes(directory, settings, callback); + return; + } + readdir(directory, settings, callback); +} +exports.read = read; +function readdirWithFileTypes(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback(callback, entries); + return; + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, rplEntries); + }); + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + done(null, entry); + return; + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + done(statError); + return; + } + done(null, entry); + return; + } + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; +} +function readdir(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + const tasks = names.map((name) => { + const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat.stat(path, settings.fsStatSettings, (error, stats) => { + if (error !== null) { + done(error); + return; + } + const entry = { + name, + path, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + done(null, entry); + }); + }; + }); + rpl(tasks, (rplError, entries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, entries); + }); + }); +} +exports.readdir = readdir; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +} diff --git a/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts b/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts new file mode 100644 index 00000000..2b4d08b5 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts @@ -0,0 +1 @@ +export declare function joinPathSegments(a: string, b: string, separator: string): string; diff --git a/node_modules/@nodelib/fs.scandir/out/providers/common.js b/node_modules/@nodelib/fs.scandir/out/providers/common.js new file mode 100644 index 00000000..8724cb59 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/common.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.joinPathSegments = void 0; +function joinPathSegments(a, b, separator) { + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +exports.joinPathSegments = joinPathSegments; diff --git a/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts b/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts new file mode 100644 index 00000000..e05c8f07 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts @@ -0,0 +1,5 @@ +import type Settings from '../settings'; +import type { Entry } from '../types'; +export declare function read(directory: string, settings: Settings): Entry[]; +export declare function readdirWithFileTypes(directory: string, settings: Settings): Entry[]; +export declare function readdir(directory: string, settings: Settings): Entry[]; diff --git a/node_modules/@nodelib/fs.scandir/out/providers/sync.js b/node_modules/@nodelib/fs.scandir/out/providers/sync.js new file mode 100644 index 00000000..146db343 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/sync.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; +const fsStat = require("@nodelib/fs.stat"); +const constants_1 = require("../constants"); +const utils = require("../utils"); +const common = require("./common"); +function read(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir(directory, settings); +} +exports.read = read; +function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function readdir(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +exports.readdir = readdir; diff --git a/node_modules/@nodelib/fs.scandir/out/settings.d.ts b/node_modules/@nodelib/fs.scandir/out/settings.d.ts new file mode 100644 index 00000000..a0db1155 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/settings.d.ts @@ -0,0 +1,20 @@ +import * as fsStat from '@nodelib/fs.stat'; +import * as fs from './adapters/fs'; +export interface Options { + followSymbolicLinks?: boolean; + fs?: Partial; + pathSegmentSeparator?: string; + stats?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly followSymbolicLinks: boolean; + readonly fs: fs.FileSystemAdapter; + readonly pathSegmentSeparator: string; + readonly stats: boolean; + readonly throwErrorOnBrokenSymbolicLink: boolean; + readonly fsStatSettings: fsStat.Settings; + constructor(_options?: Options); + private _getValue; +} diff --git a/node_modules/@nodelib/fs.scandir/out/settings.js b/node_modules/@nodelib/fs.scandir/out/settings.js new file mode 100644 index 00000000..15a3e8cd --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/settings.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fsStat = require("@nodelib/fs.stat"); +const fs = require("./adapters/fs"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/node_modules/@nodelib/fs.scandir/out/types/index.d.ts b/node_modules/@nodelib/fs.scandir/out/types/index.d.ts new file mode 100644 index 00000000..f326c5e5 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/types/index.d.ts @@ -0,0 +1,20 @@ +/// +import type * as fs from 'fs'; +export interface Entry { + dirent: Dirent; + name: string; + path: string; + stats?: Stats; +} +export declare type Stats = fs.Stats; +export declare type ErrnoException = NodeJS.ErrnoException; +export interface Dirent { + isBlockDevice: () => boolean; + isCharacterDevice: () => boolean; + isDirectory: () => boolean; + isFIFO: () => boolean; + isFile: () => boolean; + isSocket: () => boolean; + isSymbolicLink: () => boolean; + name: string; +} diff --git a/node_modules/@nodelib/fs.scandir/out/types/index.js b/node_modules/@nodelib/fs.scandir/out/types/index.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts b/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts new file mode 100644 index 00000000..bb863f15 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts @@ -0,0 +1,2 @@ +import type { Dirent, Stats } from '../types'; +export declare function createDirentFromStats(name: string, stats: Stats): Dirent; diff --git a/node_modules/@nodelib/fs.scandir/out/utils/fs.js b/node_modules/@nodelib/fs.scandir/out/utils/fs.js new file mode 100644 index 00000000..ace7c74d --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/utils/fs.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats; diff --git a/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts b/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts new file mode 100644 index 00000000..1b41954e --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts @@ -0,0 +1,2 @@ +import * as fs from './fs'; +export { fs }; diff --git a/node_modules/@nodelib/fs.scandir/out/utils/index.js b/node_modules/@nodelib/fs.scandir/out/utils/index.js new file mode 100644 index 00000000..f5de129f --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/utils/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fs = void 0; +const fs = require("./fs"); +exports.fs = fs; diff --git a/node_modules/@nodelib/fs.scandir/package.json b/node_modules/@nodelib/fs.scandir/package.json new file mode 100644 index 00000000..d3a89241 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/package.json @@ -0,0 +1,44 @@ +{ + "name": "@nodelib/fs.scandir", + "version": "2.1.5", + "description": "List files and directories inside the specified directory", + "license": "MIT", + "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.scandir", + "keywords": [ + "NodeLib", + "fs", + "FileSystem", + "file system", + "scandir", + "readdir", + "dirent" + ], + "engines": { + "node": ">= 8" + }, + "files": [ + "out/**", + "!out/**/*.map", + "!out/**/*.spec.*" + ], + "main": "out/index.js", + "typings": "out/index.d.ts", + "scripts": { + "clean": "rimraf {tsconfig.tsbuildinfo,out}", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc -b .", + "compile:watch": "tsc -p . --watch --sourceMap", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile:watch" + }, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "devDependencies": { + "@nodelib/fs.macchiato": "1.0.4", + "@types/run-parallel": "^1.1.0" + }, + "gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562" +} diff --git a/node_modules/@nodelib/fs.stat/LICENSE b/node_modules/@nodelib/fs.stat/LICENSE new file mode 100644 index 00000000..65a99946 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@nodelib/fs.stat/README.md b/node_modules/@nodelib/fs.stat/README.md new file mode 100644 index 00000000..686f0471 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/README.md @@ -0,0 +1,126 @@ +# @nodelib/fs.stat + +> Get the status of a file with some features. + +## :bulb: Highlights + +Wrapper around standard method `fs.lstat` and `fs.stat` with some features. + +* :beginner: Normally follows symbolic link. +* :gear: Can safely work with broken symbolic link. + +## Install + +```console +npm install @nodelib/fs.stat +``` + +## Usage + +```ts +import * as fsStat from '@nodelib/fs.stat'; + +fsStat.stat('path', (error, stats) => { /* … */ }); +``` + +## API + +### .stat(path, [optionsOrSettings], callback) + +Returns an instance of `fs.Stats` class for provided path with standard callback-style. + +```ts +fsStat.stat('path', (error, stats) => { /* … */ }); +fsStat.stat('path', {}, (error, stats) => { /* … */ }); +fsStat.stat('path', new fsStat.Settings(), (error, stats) => { /* … */ }); +``` + +### .statSync(path, [optionsOrSettings]) + +Returns an instance of `fs.Stats` class for provided path. + +```ts +const stats = fsStat.stat('path'); +const stats = fsStat.stat('path', {}); +const stats = fsStat.stat('path', new fsStat.Settings()); +``` + +#### path + +* Required: `true` +* Type: `string | Buffer | URL` + +A path to a file. If a URL is provided, it must use the `file:` protocol. + +#### optionsOrSettings + +* Required: `false` +* Type: `Options | Settings` +* Default: An instance of `Settings` class + +An [`Options`](#options) object or an instance of [`Settings`](#settings) class. + +> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. + +### Settings([options]) + +A class of full settings of the package. + +```ts +const settings = new fsStat.Settings({ followSymbolicLink: false }); + +const stats = fsStat.stat('path', settings); +``` + +## Options + +### `followSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Follow symbolic link or not. Call `fs.stat` on symbolic link if `true`. + +### `markSymbolicLink` + +* Type: `boolean` +* Default: `false` + +Mark symbolic link by setting the return value of `isSymbolicLink` function to always `true` (even after `fs.stat`). + +> :book: Can be used if you want to know what is hidden behind a symbolic link, but still continue to know that it is a symbolic link. + +### `throwErrorOnBrokenSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. + +### `fs` + +* Type: [`FileSystemAdapter`](./src/adapters/fs.ts) +* Default: A default FS methods + +By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. + +```ts +interface FileSystemAdapter { + lstat?: typeof fs.lstat; + stat?: typeof fs.stat; + lstatSync?: typeof fs.lstatSync; + statSync?: typeof fs.statSync; +} + +const settings = new fsStat.Settings({ + fs: { lstat: fakeLstat } +}); +``` + +## Changelog + +See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. diff --git a/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts b/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts new file mode 100644 index 00000000..3af759c9 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts @@ -0,0 +1,13 @@ +/// +import * as fs from 'fs'; +import type { ErrnoException } from '../types'; +export declare type StatAsynchronousMethod = (path: string, callback: (error: ErrnoException | null, stats: fs.Stats) => void) => void; +export declare type StatSynchronousMethod = (path: string) => fs.Stats; +export interface FileSystemAdapter { + lstat: StatAsynchronousMethod; + stat: StatAsynchronousMethod; + lstatSync: StatSynchronousMethod; + statSync: StatSynchronousMethod; +} +export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter; +export declare function createFileSystemAdapter(fsMethods?: Partial): FileSystemAdapter; diff --git a/node_modules/@nodelib/fs.stat/out/adapters/fs.js b/node_modules/@nodelib/fs.stat/out/adapters/fs.js new file mode 100644 index 00000000..8dc08c8c --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/adapters/fs.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; +const fs = require("fs"); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; diff --git a/node_modules/@nodelib/fs.stat/out/index.d.ts b/node_modules/@nodelib/fs.stat/out/index.d.ts new file mode 100644 index 00000000..f95db995 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/index.d.ts @@ -0,0 +1,12 @@ +import type { FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod } from './adapters/fs'; +import * as async from './providers/async'; +import Settings, { Options } from './settings'; +import type { Stats } from './types'; +declare type AsyncCallback = async.AsyncCallback; +declare function stat(path: string, callback: AsyncCallback): void; +declare function stat(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; +declare namespace stat { + function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise; +} +declare function statSync(path: string, optionsOrSettings?: Options | Settings): Stats; +export { Settings, stat, statSync, AsyncCallback, FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod, Options, Stats }; diff --git a/node_modules/@nodelib/fs.stat/out/index.js b/node_modules/@nodelib/fs.stat/out/index.js new file mode 100644 index 00000000..b23f7510 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.statSync = exports.stat = exports.Settings = void 0; +const async = require("./providers/async"); +const sync = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function stat(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.stat = stat; +function statSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.statSync = statSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/node_modules/@nodelib/fs.stat/out/providers/async.d.ts b/node_modules/@nodelib/fs.stat/out/providers/async.d.ts new file mode 100644 index 00000000..85423ce1 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/providers/async.d.ts @@ -0,0 +1,4 @@ +import type Settings from '../settings'; +import type { ErrnoException, Stats } from '../types'; +export declare type AsyncCallback = (error: ErrnoException, stats: Stats) => void; +export declare function read(path: string, settings: Settings, callback: AsyncCallback): void; diff --git a/node_modules/@nodelib/fs.stat/out/providers/async.js b/node_modules/@nodelib/fs.stat/out/providers/async.js new file mode 100644 index 00000000..983ff0e6 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/providers/async.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.read = void 0; +function read(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + callFailureCallback(callback, lstatError); + return; + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + callSuccessCallback(callback, lstat); + return; + } + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + callFailureCallback(callback, statError); + return; + } + callSuccessCallback(callback, lstat); + return; + } + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + callSuccessCallback(callback, stat); + }); + }); +} +exports.read = read; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +} diff --git a/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts b/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts new file mode 100644 index 00000000..428c3d79 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts @@ -0,0 +1,3 @@ +import type Settings from '../settings'; +import type { Stats } from '../types'; +export declare function read(path: string, settings: Settings): Stats; diff --git a/node_modules/@nodelib/fs.stat/out/providers/sync.js b/node_modules/@nodelib/fs.stat/out/providers/sync.js new file mode 100644 index 00000000..1521c361 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/providers/sync.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.read = void 0; +function read(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + return stat; + } + catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + throw error; + } +} +exports.read = read; diff --git a/node_modules/@nodelib/fs.stat/out/settings.d.ts b/node_modules/@nodelib/fs.stat/out/settings.d.ts new file mode 100644 index 00000000..f4b3d444 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/settings.d.ts @@ -0,0 +1,16 @@ +import * as fs from './adapters/fs'; +export interface Options { + followSymbolicLink?: boolean; + fs?: Partial; + markSymbolicLink?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly followSymbolicLink: boolean; + readonly fs: fs.FileSystemAdapter; + readonly markSymbolicLink: boolean; + readonly throwErrorOnBrokenSymbolicLink: boolean; + constructor(_options?: Options); + private _getValue; +} diff --git a/node_modules/@nodelib/fs.stat/out/settings.js b/node_modules/@nodelib/fs.stat/out/settings.js new file mode 100644 index 00000000..111ec09c --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/settings.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = require("./adapters/fs"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/node_modules/@nodelib/fs.stat/out/types/index.d.ts b/node_modules/@nodelib/fs.stat/out/types/index.d.ts new file mode 100644 index 00000000..74c08ed2 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/types/index.d.ts @@ -0,0 +1,4 @@ +/// +import type * as fs from 'fs'; +export declare type Stats = fs.Stats; +export declare type ErrnoException = NodeJS.ErrnoException; diff --git a/node_modules/@nodelib/fs.stat/out/types/index.js b/node_modules/@nodelib/fs.stat/out/types/index.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nodelib/fs.stat/package.json b/node_modules/@nodelib/fs.stat/package.json new file mode 100644 index 00000000..f2540c28 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/package.json @@ -0,0 +1,37 @@ +{ + "name": "@nodelib/fs.stat", + "version": "2.0.5", + "description": "Get the status of a file with some features", + "license": "MIT", + "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat", + "keywords": [ + "NodeLib", + "fs", + "FileSystem", + "file system", + "stat" + ], + "engines": { + "node": ">= 8" + }, + "files": [ + "out/**", + "!out/**/*.map", + "!out/**/*.spec.*" + ], + "main": "out/index.js", + "typings": "out/index.d.ts", + "scripts": { + "clean": "rimraf {tsconfig.tsbuildinfo,out}", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc -b .", + "compile:watch": "tsc -p . --watch --sourceMap", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile:watch" + }, + "devDependencies": { + "@nodelib/fs.macchiato": "1.0.4" + }, + "gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562" +} diff --git a/node_modules/@nodelib/fs.walk/LICENSE b/node_modules/@nodelib/fs.walk/LICENSE new file mode 100644 index 00000000..65a99946 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@nodelib/fs.walk/README.md b/node_modules/@nodelib/fs.walk/README.md new file mode 100644 index 00000000..6ccc08db --- /dev/null +++ b/node_modules/@nodelib/fs.walk/README.md @@ -0,0 +1,215 @@ +# @nodelib/fs.walk + +> A library for efficiently walking a directory recursively. + +## :bulb: Highlights + +* :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional). +* :rocket: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type for performance reasons. See [`old` and `modern` mode](https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode). +* :gear: Built-in directories/files and error filtering system. +* :link: Can safely work with broken symbolic links. + +## Install + +```console +npm install @nodelib/fs.walk +``` + +## Usage + +```ts +import * as fsWalk from '@nodelib/fs.walk'; + +fsWalk.walk('path', (error, entries) => { /* … */ }); +``` + +## API + +### .walk(path, [optionsOrSettings], callback) + +Reads the directory recursively and asynchronously. Requires a callback function. + +> :book: If you want to use the Promise API, use `util.promisify`. + +```ts +fsWalk.walk('path', (error, entries) => { /* … */ }); +fsWalk.walk('path', {}, (error, entries) => { /* … */ }); +fsWalk.walk('path', new fsWalk.Settings(), (error, entries) => { /* … */ }); +``` + +### .walkStream(path, [optionsOrSettings]) + +Reads the directory recursively and asynchronously. [Readable Stream](https://nodejs.org/dist/latest-v12.x/docs/api/stream.html#stream_readable_streams) is used as a provider. + +```ts +const stream = fsWalk.walkStream('path'); +const stream = fsWalk.walkStream('path', {}); +const stream = fsWalk.walkStream('path', new fsWalk.Settings()); +``` + +### .walkSync(path, [optionsOrSettings]) + +Reads the directory recursively and synchronously. Returns an array of entries. + +```ts +const entries = fsWalk.walkSync('path'); +const entries = fsWalk.walkSync('path', {}); +const entries = fsWalk.walkSync('path', new fsWalk.Settings()); +``` + +#### path + +* Required: `true` +* Type: `string | Buffer | URL` + +A path to a file. If a URL is provided, it must use the `file:` protocol. + +#### optionsOrSettings + +* Required: `false` +* Type: `Options | Settings` +* Default: An instance of `Settings` class + +An [`Options`](#options) object or an instance of [`Settings`](#settings) class. + +> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. + +### Settings([options]) + +A class of full settings of the package. + +```ts +const settings = new fsWalk.Settings({ followSymbolicLinks: true }); + +const entries = fsWalk.walkSync('path', settings); +``` + +## Entry + +* `name` — The name of the entry (`unknown.txt`). +* `path` — The path of the entry relative to call directory (`root/unknown.txt`). +* `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class. +* [`stats`] — An instance of `fs.Stats` class. + +## Options + +### basePath + +* Type: `string` +* Default: `undefined` + +By default, all paths are built relative to the root path. You can use this option to set custom root path. + +In the example below we read the files from the `root` directory, but in the results the root path will be `custom`. + +```ts +fsWalk.walkSync('root'); // → ['root/file.txt'] +fsWalk.walkSync('root', { basePath: 'custom' }); // → ['custom/file.txt'] +``` + +### concurrency + +* Type: `number` +* Default: `Infinity` + +The maximum number of concurrent calls to `fs.readdir`. + +> :book: The higher the number, the higher performance and the load on the File System. If you want to read in quiet mode, set the value to `4 * os.cpus().length` (4 is default size of [thread pool work scheduling](http://docs.libuv.org/en/v1.x/threadpool.html#thread-pool-work-scheduling)). + +### deepFilter + +* Type: [`DeepFilterFunction`](./src/settings.ts) +* Default: `undefined` + +A function that indicates whether the directory will be read deep or not. + +```ts +// Skip all directories that starts with `node_modules` +const filter: DeepFilterFunction = (entry) => !entry.path.startsWith('node_modules'); +``` + +### entryFilter + +* Type: [`EntryFilterFunction`](./src/settings.ts) +* Default: `undefined` + +A function that indicates whether the entry will be included to results or not. + +```ts +// Exclude all `.js` files from results +const filter: EntryFilterFunction = (entry) => !entry.name.endsWith('.js'); +``` + +### errorFilter + +* Type: [`ErrorFilterFunction`](./src/settings.ts) +* Default: `undefined` + +A function that allows you to skip errors that occur when reading directories. + +For example, you can skip `ENOENT` errors if required: + +```ts +// Skip all ENOENT errors +const filter: ErrorFilterFunction = (error) => error.code == 'ENOENT'; +``` + +### stats + +* Type: `boolean` +* Default: `false` + +Adds an instance of `fs.Stats` class to the [`Entry`](#entry). + +> :book: Always use `fs.readdir` with additional `fs.lstat/fs.stat` calls to determine the entry type. + +### followSymbolicLinks + +* Type: `boolean` +* Default: `false` + +Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`. + +### `throwErrorOnBrokenSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. + +### `pathSegmentSeparator` + +* Type: `string` +* Default: `path.sep` + +By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead. + +### `fs` + +* Type: `FileSystemAdapter` +* Default: A default FS methods + +By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. + +```ts +interface FileSystemAdapter { + lstat: typeof fs.lstat; + stat: typeof fs.stat; + lstatSync: typeof fs.lstatSync; + statSync: typeof fs.statSync; + readdir: typeof fs.readdir; + readdirSync: typeof fs.readdirSync; +} + +const settings = new fsWalk.Settings({ + fs: { lstat: fakeLstat } +}); +``` + +## Changelog + +See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. diff --git a/node_modules/@nodelib/fs.walk/out/index.d.ts b/node_modules/@nodelib/fs.walk/out/index.d.ts new file mode 100644 index 00000000..8864c7bf --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/index.d.ts @@ -0,0 +1,14 @@ +/// +import type { Readable } from 'stream'; +import type { Dirent, FileSystemAdapter } from '@nodelib/fs.scandir'; +import { AsyncCallback } from './providers/async'; +import Settings, { DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction, Options } from './settings'; +import type { Entry } from './types'; +declare function walk(directory: string, callback: AsyncCallback): void; +declare function walk(directory: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; +declare namespace walk { + function __promisify__(directory: string, optionsOrSettings?: Options | Settings): Promise; +} +declare function walkSync(directory: string, optionsOrSettings?: Options | Settings): Entry[]; +declare function walkStream(directory: string, optionsOrSettings?: Options | Settings): Readable; +export { walk, walkSync, walkStream, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, Options, DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction }; diff --git a/node_modules/@nodelib/fs.walk/out/index.js b/node_modules/@nodelib/fs.walk/out/index.js new file mode 100644 index 00000000..15207874 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/index.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0; +const async_1 = require("./providers/async"); +const stream_1 = require("./providers/stream"); +const sync_1 = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function walk(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + return; + } + new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); +} +exports.walk = walk; +function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync_1.default(directory, settings); + return provider.read(); +} +exports.walkSync = walkSync; +function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream_1.default(directory, settings); + return provider.read(); +} +exports.walkStream = walkStream; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/async.d.ts b/node_modules/@nodelib/fs.walk/out/providers/async.d.ts new file mode 100644 index 00000000..0f6717d7 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/async.d.ts @@ -0,0 +1,12 @@ +import AsyncReader from '../readers/async'; +import type Settings from '../settings'; +import type { Entry, Errno } from '../types'; +export declare type AsyncCallback = (error: Errno, entries: Entry[]) => void; +export default class AsyncProvider { + private readonly _root; + private readonly _settings; + protected readonly _reader: AsyncReader; + private readonly _storage; + constructor(_root: string, _settings: Settings); + read(callback: AsyncCallback): void; +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/async.js b/node_modules/@nodelib/fs.walk/out/providers/async.js new file mode 100644 index 00000000..51d3be51 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/async.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const async_1 = require("../readers/async"); +class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._storage = []; + } + read(callback) { + this._reader.onError((error) => { + callFailureCallback(callback, error); + }); + this._reader.onEntry((entry) => { + this._storage.push(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, this._storage); + }); + this._reader.read(); + } +} +exports.default = AsyncProvider; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, entries) { + callback(null, entries); +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/index.d.ts b/node_modules/@nodelib/fs.walk/out/providers/index.d.ts new file mode 100644 index 00000000..874f60c5 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/index.d.ts @@ -0,0 +1,4 @@ +import AsyncProvider from './async'; +import StreamProvider from './stream'; +import SyncProvider from './sync'; +export { AsyncProvider, StreamProvider, SyncProvider }; diff --git a/node_modules/@nodelib/fs.walk/out/providers/index.js b/node_modules/@nodelib/fs.walk/out/providers/index.js new file mode 100644 index 00000000..4c2529ce --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/index.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SyncProvider = exports.StreamProvider = exports.AsyncProvider = void 0; +const async_1 = require("./async"); +exports.AsyncProvider = async_1.default; +const stream_1 = require("./stream"); +exports.StreamProvider = stream_1.default; +const sync_1 = require("./sync"); +exports.SyncProvider = sync_1.default; diff --git a/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts b/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts new file mode 100644 index 00000000..294185f8 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts @@ -0,0 +1,12 @@ +/// +import { Readable } from 'stream'; +import AsyncReader from '../readers/async'; +import type Settings from '../settings'; +export default class StreamProvider { + private readonly _root; + private readonly _settings; + protected readonly _reader: AsyncReader; + protected readonly _stream: Readable; + constructor(_root: string, _settings: Settings); + read(): Readable; +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/stream.js b/node_modules/@nodelib/fs.walk/out/providers/stream.js new file mode 100644 index 00000000..51298b0f --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/stream.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = require("stream"); +const async_1 = require("../readers/async"); +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._stream = new stream_1.Readable({ + objectMode: true, + read: () => { }, + destroy: () => { + if (!this._reader.isDestroyed) { + this._reader.destroy(); + } + } + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit('error', error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } +} +exports.default = StreamProvider; diff --git a/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts b/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts new file mode 100644 index 00000000..551c42e4 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts @@ -0,0 +1,10 @@ +import SyncReader from '../readers/sync'; +import type Settings from '../settings'; +import type { Entry } from '../types'; +export default class SyncProvider { + private readonly _root; + private readonly _settings; + protected readonly _reader: SyncReader; + constructor(_root: string, _settings: Settings); + read(): Entry[]; +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/sync.js b/node_modules/@nodelib/fs.walk/out/providers/sync.js new file mode 100644 index 00000000..faab6ca2 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/sync.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const sync_1 = require("../readers/sync"); +class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } +} +exports.default = SyncProvider; diff --git a/node_modules/@nodelib/fs.walk/out/readers/async.d.ts b/node_modules/@nodelib/fs.walk/out/readers/async.d.ts new file mode 100644 index 00000000..9acf4e6c --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/async.d.ts @@ -0,0 +1,30 @@ +/// +import { EventEmitter } from 'events'; +import * as fsScandir from '@nodelib/fs.scandir'; +import type Settings from '../settings'; +import type { Entry, Errno } from '../types'; +import Reader from './reader'; +declare type EntryEventCallback = (entry: Entry) => void; +declare type ErrorEventCallback = (error: Errno) => void; +declare type EndEventCallback = () => void; +export default class AsyncReader extends Reader { + protected readonly _settings: Settings; + protected readonly _scandir: typeof fsScandir.scandir; + protected readonly _emitter: EventEmitter; + private readonly _queue; + private _isFatalError; + private _isDestroyed; + constructor(_root: string, _settings: Settings); + read(): EventEmitter; + get isDestroyed(): boolean; + destroy(): void; + onEntry(callback: EntryEventCallback): void; + onError(callback: ErrorEventCallback): void; + onEnd(callback: EndEventCallback): void; + private _pushToQueue; + private _worker; + private _handleError; + private _handleEntry; + private _emitEntry; +} +export {}; diff --git a/node_modules/@nodelib/fs.walk/out/readers/async.js b/node_modules/@nodelib/fs.walk/out/readers/async.js new file mode 100644 index 00000000..ebe8dd57 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/async.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const events_1 = require("events"); +const fsScandir = require("@nodelib/fs.scandir"); +const fastq = require("fastq"); +const common = require("./common"); +const reader_1 = require("./reader"); +class AsyncReader extends reader_1.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir.scandir; + this._emitter = new events_1.EventEmitter(); + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + get isDestroyed() { + return this._isDestroyed; + } + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on('entry', callback); + } + onError(callback) { + this._emitter.once('error', callback); + } + onEnd(callback) { + this._emitter.once('end', callback); + } + _pushToQueue(directory, base) { + const queueItem = { directory, base }; + this._queue.push(queueItem, (error) => { + if (error !== null) { + this._handleError(error); + } + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + done(error, undefined); + return; + } + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + done(null, undefined); + }); + } + _handleError(error) { + if (this._isDestroyed || !common.isFatalError(this._settings, error)) { + return; + } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit('error', error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +exports.default = AsyncReader; diff --git a/node_modules/@nodelib/fs.walk/out/readers/common.d.ts b/node_modules/@nodelib/fs.walk/out/readers/common.d.ts new file mode 100644 index 00000000..5985f97c --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/common.d.ts @@ -0,0 +1,7 @@ +import type { FilterFunction } from '../settings'; +import type Settings from '../settings'; +import type { Errno } from '../types'; +export declare function isFatalError(settings: Settings, error: Errno): boolean; +export declare function isAppliedFilter(filter: FilterFunction | null, value: T): boolean; +export declare function replacePathSegmentSeparator(filepath: string, separator: string): string; +export declare function joinPathSegments(a: string, b: string, separator: string): string; diff --git a/node_modules/@nodelib/fs.walk/out/readers/common.js b/node_modules/@nodelib/fs.walk/out/readers/common.js new file mode 100644 index 00000000..a93572f4 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/common.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0; +function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error); +} +exports.isFatalError = isFatalError; +function isAppliedFilter(filter, value) { + return filter === null || filter(value); +} +exports.isAppliedFilter = isAppliedFilter; +function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[/\\]/).join(separator); +} +exports.replacePathSegmentSeparator = replacePathSegmentSeparator; +function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +exports.joinPathSegments = joinPathSegments; diff --git a/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts b/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts new file mode 100644 index 00000000..e1f383b2 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts @@ -0,0 +1,6 @@ +import type Settings from '../settings'; +export default class Reader { + protected readonly _root: string; + protected readonly _settings: Settings; + constructor(_root: string, _settings: Settings); +} diff --git a/node_modules/@nodelib/fs.walk/out/readers/reader.js b/node_modules/@nodelib/fs.walk/out/readers/reader.js new file mode 100644 index 00000000..782f07cb --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/reader.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const common = require("./common"); +class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } +} +exports.default = Reader; diff --git a/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts b/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts new file mode 100644 index 00000000..af410335 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts @@ -0,0 +1,15 @@ +import * as fsScandir from '@nodelib/fs.scandir'; +import type { Entry } from '../types'; +import Reader from './reader'; +export default class SyncReader extends Reader { + protected readonly _scandir: typeof fsScandir.scandirSync; + private readonly _storage; + private readonly _queue; + read(): Entry[]; + private _pushToQueue; + private _handleQueue; + private _handleDirectory; + private _handleError; + private _handleEntry; + private _pushToStorage; +} diff --git a/node_modules/@nodelib/fs.walk/out/readers/sync.js b/node_modules/@nodelib/fs.walk/out/readers/sync.js new file mode 100644 index 00000000..9a8d5a6f --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/sync.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fsScandir = require("@nodelib/fs.scandir"); +const common = require("./common"); +const reader_1 = require("./reader"); +class SyncReader extends reader_1.default { + constructor() { + super(...arguments); + this._scandir = fsScandir.scandirSync; + this._storage = []; + this._queue = new Set(); + } + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return this._storage; + } + _pushToQueue(directory, base) { + this._queue.add({ directory, base }); + } + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); + } + } + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + for (const entry of entries) { + this._handleEntry(entry, base); + } + } + catch (error) { + this._handleError(error); + } + } + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _pushToStorage(entry) { + this._storage.push(entry); + } +} +exports.default = SyncReader; diff --git a/node_modules/@nodelib/fs.walk/out/settings.d.ts b/node_modules/@nodelib/fs.walk/out/settings.d.ts new file mode 100644 index 00000000..d1c4b45f --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/settings.d.ts @@ -0,0 +1,30 @@ +import * as fsScandir from '@nodelib/fs.scandir'; +import type { Entry, Errno } from './types'; +export declare type FilterFunction = (value: T) => boolean; +export declare type DeepFilterFunction = FilterFunction; +export declare type EntryFilterFunction = FilterFunction; +export declare type ErrorFilterFunction = FilterFunction; +export interface Options { + basePath?: string; + concurrency?: number; + deepFilter?: DeepFilterFunction; + entryFilter?: EntryFilterFunction; + errorFilter?: ErrorFilterFunction; + followSymbolicLinks?: boolean; + fs?: Partial; + pathSegmentSeparator?: string; + stats?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly basePath?: string; + readonly concurrency: number; + readonly deepFilter: DeepFilterFunction | null; + readonly entryFilter: EntryFilterFunction | null; + readonly errorFilter: ErrorFilterFunction | null; + readonly pathSegmentSeparator: string; + readonly fsScandirSettings: fsScandir.Settings; + constructor(_options?: Options); + private _getValue; +} diff --git a/node_modules/@nodelib/fs.walk/out/settings.js b/node_modules/@nodelib/fs.walk/out/settings.js new file mode 100644 index 00000000..d7a85c81 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/settings.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fsScandir = require("@nodelib/fs.scandir"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/node_modules/@nodelib/fs.walk/out/types/index.d.ts b/node_modules/@nodelib/fs.walk/out/types/index.d.ts new file mode 100644 index 00000000..6ee9bd3f --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/types/index.d.ts @@ -0,0 +1,8 @@ +/// +import type * as scandir from '@nodelib/fs.scandir'; +export declare type Entry = scandir.Entry; +export declare type Errno = NodeJS.ErrnoException; +export interface QueueItem { + directory: string; + base?: string; +} diff --git a/node_modules/@nodelib/fs.walk/out/types/index.js b/node_modules/@nodelib/fs.walk/out/types/index.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nodelib/fs.walk/package.json b/node_modules/@nodelib/fs.walk/package.json new file mode 100644 index 00000000..86bfce48 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/package.json @@ -0,0 +1,44 @@ +{ + "name": "@nodelib/fs.walk", + "version": "1.2.8", + "description": "A library for efficiently walking a directory recursively", + "license": "MIT", + "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk", + "keywords": [ + "NodeLib", + "fs", + "FileSystem", + "file system", + "walk", + "scanner", + "crawler" + ], + "engines": { + "node": ">= 8" + }, + "files": [ + "out/**", + "!out/**/*.map", + "!out/**/*.spec.*", + "!out/**/tests/**" + ], + "main": "out/index.js", + "typings": "out/index.d.ts", + "scripts": { + "clean": "rimraf {tsconfig.tsbuildinfo,out}", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc -b .", + "compile:watch": "tsc -p . --watch --sourceMap", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile:watch" + }, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "devDependencies": { + "@nodelib/fs.macchiato": "1.0.4" + }, + "gitHead": "1e5bad48565da2b06b8600e744324ea240bf49d8" +} diff --git a/node_modules/@types/estree/LICENSE b/node_modules/@types/estree/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/node_modules/@types/estree/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/estree/README.md b/node_modules/@types/estree/README.md new file mode 100644 index 00000000..2af760b2 --- /dev/null +++ b/node_modules/@types/estree/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/estree` + +# Summary +This package contains type definitions for estree (https://github.com/estree/estree). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree. + +### Additional Details + * Last updated: Fri, 06 Jun 2025 00:04:33 GMT + * Dependencies: none + +# Credits +These definitions were written by [RReverser](https://github.com/RReverser). diff --git a/node_modules/@types/estree/flow.d.ts b/node_modules/@types/estree/flow.d.ts new file mode 100644 index 00000000..9d001a92 --- /dev/null +++ b/node_modules/@types/estree/flow.d.ts @@ -0,0 +1,167 @@ +declare namespace ESTree { + interface FlowTypeAnnotation extends Node {} + + interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} + + interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {} + + interface FlowDeclaration extends Declaration {} + + interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ArrayTypeAnnotation extends FlowTypeAnnotation { + elementType: FlowTypeAnnotation; + } + + interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ClassImplements extends Node { + id: Identifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface ClassProperty { + key: Expression; + value?: Expression | null; + typeAnnotation?: TypeAnnotation | null; + computed: boolean; + static: boolean; + } + + interface DeclareClass extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + body: ObjectTypeAnnotation; + extends: InterfaceExtends[]; + } + + interface DeclareFunction extends FlowDeclaration { + id: Identifier; + } + + interface DeclareModule extends FlowDeclaration { + id: Literal | Identifier; + body: BlockStatement; + } + + interface DeclareVariable extends FlowDeclaration { + id: Identifier; + } + + interface FunctionTypeAnnotation extends FlowTypeAnnotation { + params: FunctionTypeParam[]; + returnType: FlowTypeAnnotation; + rest?: FunctionTypeParam | null; + typeParameters?: TypeParameterDeclaration | null; + } + + interface FunctionTypeParam { + name: Identifier; + typeAnnotation: FlowTypeAnnotation; + optional: boolean; + } + + interface GenericTypeAnnotation extends FlowTypeAnnotation { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceExtends extends Node { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceDeclaration extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + extends: InterfaceExtends[]; + body: ObjectTypeAnnotation; + } + + interface IntersectionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface NullableTypeAnnotation extends FlowTypeAnnotation { + typeAnnotation: TypeAnnotation; + } + + interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface StringTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface TupleTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface TypeofTypeAnnotation extends FlowTypeAnnotation { + argument: FlowTypeAnnotation; + } + + interface TypeAlias extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + right: FlowTypeAnnotation; + } + + interface TypeAnnotation extends Node { + typeAnnotation: FlowTypeAnnotation; + } + + interface TypeCastExpression extends Expression { + expression: Expression; + typeAnnotation: TypeAnnotation; + } + + interface TypeParameterDeclaration extends Node { + params: Identifier[]; + } + + interface TypeParameterInstantiation extends Node { + params: FlowTypeAnnotation[]; + } + + interface ObjectTypeAnnotation extends FlowTypeAnnotation { + properties: ObjectTypeProperty[]; + indexers: ObjectTypeIndexer[]; + callProperties: ObjectTypeCallProperty[]; + } + + interface ObjectTypeCallProperty extends Node { + value: FunctionTypeAnnotation; + static: boolean; + } + + interface ObjectTypeIndexer extends Node { + id: Identifier; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; + static: boolean; + } + + interface ObjectTypeProperty extends Node { + key: Expression; + value: FlowTypeAnnotation; + optional: boolean; + static: boolean; + } + + interface QualifiedTypeIdentifier extends Node { + qualification: Identifier | QualifiedTypeIdentifier; + id: Identifier; + } + + interface UnionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {} +} diff --git a/node_modules/@types/estree/index.d.ts b/node_modules/@types/estree/index.d.ts new file mode 100644 index 00000000..2bc66fb6 --- /dev/null +++ b/node_modules/@types/estree/index.d.ts @@ -0,0 +1,694 @@ +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +export interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; +} + +export interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Comment[] | undefined; + trailingComments?: Comment[] | undefined; +} + +export interface NodeMap { + AssignmentProperty: AssignmentProperty; + CatchClause: CatchClause; + Class: Class; + ClassBody: ClassBody; + Expression: Expression; + Function: Function; + Identifier: Identifier; + Literal: Literal; + MethodDefinition: MethodDefinition; + ModuleDeclaration: ModuleDeclaration; + ModuleSpecifier: ModuleSpecifier; + Pattern: Pattern; + PrivateIdentifier: PrivateIdentifier; + Program: Program; + Property: Property; + PropertyDefinition: PropertyDefinition; + SpreadElement: SpreadElement; + Statement: Statement; + Super: Super; + SwitchCase: SwitchCase; + TemplateElement: TemplateElement; + VariableDeclarator: VariableDeclarator; +} + +export type Node = NodeMap[keyof NodeMap]; + +export interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +export interface SourceLocation { + source?: string | null | undefined; + start: Position; + end: Position; +} + +export interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +export interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Comment[] | undefined; +} + +export interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +export interface BaseFunction extends BaseNode { + params: Pattern[]; + generator?: boolean | undefined; + async?: boolean | undefined; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +export type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +export type Statement = + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | Declaration; + +export interface BaseStatement extends BaseNode {} + +export interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +export interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Statement[]; + innerComments?: Comment[] | undefined; +} + +export interface StaticBlock extends Omit { + type: "StaticBlock"; +} + +export interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +export interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null | undefined; +} + +export interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +export interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null | undefined; +} + +export interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null | undefined; +} + +export interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +export interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +export interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null | undefined; +} + +export interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +export interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null | undefined; + finalizer?: BlockStatement | null | undefined; +} + +export interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +export interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +export interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null | undefined; + test?: Expression | null | undefined; + update?: Expression | null | undefined; + body: Statement; +} + +export interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +export interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +export interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +export interface BaseDeclaration extends BaseStatement {} + +export interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +export interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { + id: Identifier; +} + +export interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const" | "using" | "await using"; +} + +export interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null | undefined; +} + +export interface ExpressionMap { + ArrayExpression: ArrayExpression; + ArrowFunctionExpression: ArrowFunctionExpression; + AssignmentExpression: AssignmentExpression; + AwaitExpression: AwaitExpression; + BinaryExpression: BinaryExpression; + CallExpression: CallExpression; + ChainExpression: ChainExpression; + ClassExpression: ClassExpression; + ConditionalExpression: ConditionalExpression; + FunctionExpression: FunctionExpression; + Identifier: Identifier; + ImportExpression: ImportExpression; + Literal: Literal; + LogicalExpression: LogicalExpression; + MemberExpression: MemberExpression; + MetaProperty: MetaProperty; + NewExpression: NewExpression; + ObjectExpression: ObjectExpression; + SequenceExpression: SequenceExpression; + TaggedTemplateExpression: TaggedTemplateExpression; + TemplateLiteral: TemplateLiteral; + ThisExpression: ThisExpression; + UnaryExpression: UnaryExpression; + UpdateExpression: UpdateExpression; + YieldExpression: YieldExpression; +} + +export type Expression = ExpressionMap[keyof ExpressionMap]; + +export interface BaseExpression extends BaseNode {} + +export type ChainElement = SimpleCallExpression | MemberExpression; + +export interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +export interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +export interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +export interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +export interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +export interface Property extends BaseNode { + type: "Property"; + key: Expression | PrivateIdentifier; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +export interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null | undefined; + computed: boolean; + static: boolean; +} + +export interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null | undefined; + type: "FunctionExpression"; + body: BlockStatement; +} + +export interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Expression[]; +} + +export interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +export interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression | PrivateIdentifier; + right: Expression; +} + +export interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +export interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +export interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +export interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +export interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +export type CallExpression = SimpleCallExpression | NewExpression; + +export interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +export interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +export interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +export type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; + +export interface BasePattern extends BaseNode {} + +export interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null | undefined; + consequent: Statement[]; +} + +export interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +export interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +export interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string | undefined; +} + +export interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null | undefined; + regex: { + pattern: string; + flags: string; + }; + raw?: string | undefined; +} + +export interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null | undefined; + bigint: string; + raw?: string | undefined; +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +export type BinaryOperator = + | "==" + | "!=" + | "===" + | "!==" + | "<" + | "<=" + | ">" + | ">=" + | "<<" + | ">>" + | ">>>" + | "+" + | "-" + | "*" + | "/" + | "%" + | "**" + | "|" + | "^" + | "&" + | "in" + | "instanceof"; + +export type LogicalOperator = "||" | "&&" | "??"; + +export type AssignmentOperator = + | "=" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "**=" + | "<<=" + | ">>=" + | ">>>=" + | "|=" + | "^=" + | "&=" + | "||=" + | "&&=" + | "??="; + +export type UpdateOperator = "++" | "--"; + +export interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +export interface Super extends BaseNode { + type: "Super"; +} + +export interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +export interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +export interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null | undefined; + delegate: boolean; +} + +export interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +export interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +export interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null | undefined; + raw: string; + }; +} + +export interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +export interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +export interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +export interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +export interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +export type Class = ClassDeclaration | ClassExpression; +export interface BaseClass extends BaseNode { + superClass?: Expression | null | undefined; + body: ClassBody; +} + +export interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +export interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +export interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +export interface ClassDeclaration extends MaybeNamedClassDeclaration { + id: Identifier; +} + +export interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null | undefined; +} + +export interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +export type ModuleDeclaration = + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration; +export interface BaseModuleDeclaration extends BaseNode {} + +export type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; +export interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +export interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + attributes: ImportAttribute[]; + source: Literal; +} + +export interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier | Literal; +} + +export interface ImportAttribute extends BaseNode { + type: "ImportAttribute"; + key: Identifier | Literal; + value: Literal; +} + +export interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; + options?: Expression | null | undefined; +} + +export interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +export interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +export interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null | undefined; + specifiers: ExportSpecifier[]; + attributes: ImportAttribute[]; + source?: Literal | null | undefined; +} + +export interface ExportSpecifier extends Omit { + type: "ExportSpecifier"; + local: Identifier | Literal; + exported: Identifier | Literal; +} + +export interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; +} + +export interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + exported: Identifier | Literal | null; + attributes: ImportAttribute[]; + source: Literal; +} + +export interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} diff --git a/node_modules/@types/estree/package.json b/node_modules/@types/estree/package.json new file mode 100644 index 00000000..68c0782c --- /dev/null +++ b/node_modules/@types/estree/package.json @@ -0,0 +1,27 @@ +{ + "name": "@types/estree", + "version": "1.0.8", + "description": "TypeScript definitions for estree", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree", + "license": "MIT", + "contributors": [ + { + "name": "RReverser", + "githubUsername": "RReverser", + "url": "https://github.com/RReverser" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/estree" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "7a167b6e4a4d9f6e9a2cb9fd3fc45c885f89cbdeb44b3e5961bb057a45c082fd", + "typeScriptVersion": "5.1", + "nonNpm": true +} \ No newline at end of file diff --git a/node_modules/@types/json-schema/LICENSE b/node_modules/@types/json-schema/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/node_modules/@types/json-schema/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/json-schema/README.md b/node_modules/@types/json-schema/README.md new file mode 100644 index 00000000..78c610f0 --- /dev/null +++ b/node_modules/@types/json-schema/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/json-schema` + +# Summary +This package contains type definitions for json-schema (https://github.com/kriszyp/json-schema). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 03:09:37 GMT + * Dependencies: none + +# Credits +These definitions were written by [Boris Cherny](https://github.com/bcherny), [Lucian Buzzo](https://github.com/lucianbuzzo), [Roland Groza](https://github.com/rolandjitsu), and [Jason Kwok](https://github.com/JasonHK). diff --git a/node_modules/@types/json-schema/index.d.ts b/node_modules/@types/json-schema/index.d.ts new file mode 100644 index 00000000..9381e999 --- /dev/null +++ b/node_modules/@types/json-schema/index.d.ts @@ -0,0 +1,749 @@ +// ================================================================================================== +// JSON Schema Draft 04 +// ================================================================================================== + +/** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 + */ +export type JSONSchema4TypeName = + | "string" // + | "number" + | "integer" + | "boolean" + | "object" + | "array" + | "null" + | "any"; + +/** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-3.5 + */ +export type JSONSchema4Type = + | string // + | number + | boolean + | JSONSchema4Object + | JSONSchema4Array + | null; + +// Workaround for infinite type recursion +export interface JSONSchema4Object { + [key: string]: JSONSchema4Type; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchema4Array extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-04/schema#' + * - 'http://json-schema.org/draft-04/hyper-schema#' + * - 'http://json-schema.org/draft-03/schema#' + * - 'http://json-schema.org/draft-03/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema4Version = string; + +/** + * JSON Schema V4 + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04 + */ +export interface JSONSchema4 { + id?: string | undefined; + $ref?: string | undefined; + $schema?: JSONSchema4Version | undefined; + + /** + * This attribute is a string that provides a short description of the + * instance property. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.21 + */ + title?: string | undefined; + + /** + * This attribute is a string that provides a full description of the of + * purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.22 + */ + description?: string | undefined; + + default?: JSONSchema4Type | undefined; + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: boolean | undefined; + minimum?: number | undefined; + exclusiveMinimum?: boolean | undefined; + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + + /** + * May only be defined when "items" is defined, and is a tuple of JSONSchemas. + * + * This provides a definition for additional items in an array instance + * when tuple definitions of the items is provided. This can be false + * to indicate additional items in the array are not allowed, or it can + * be a schema that defines the schema of the additional items. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.6 + */ + additionalItems?: boolean | JSONSchema4 | undefined; + + /** + * This attribute defines the allowed items in an instance array, and + * MUST be a schema or an array of schemas. The default value is an + * empty schema which allows any value for items in the instance array. + * + * When this attribute value is a schema and the instance value is an + * array, then all the items in the array MUST be valid according to the + * schema. + * + * When this attribute value is an array of schemas and the instance + * value is an array, each position in the instance array MUST conform + * to the schema in the corresponding position for this array. This + * called tuple typing. When tuple typing is used, additional items are + * allowed, disallowed, or constrained by the "additionalItems" + * (Section 5.6) attribute using the same rules as + * "additionalProperties" (Section 5.4) for objects. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.5 + */ + items?: JSONSchema4 | JSONSchema4[] | undefined; + + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + maxProperties?: number | undefined; + minProperties?: number | undefined; + + /** + * This attribute indicates if the instance must have a value, and not + * be undefined. This is false by default, making the instance + * optional. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.7 + */ + required?: boolean | string[] | undefined; + + /** + * This attribute defines a schema for all properties that are not + * explicitly defined in an object type definition. If specified, the + * value MUST be a schema or a boolean. If false is provided, no + * additional properties are allowed beyond the properties defined in + * the schema. The default value is an empty schema which allows any + * value for additional properties. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.4 + */ + additionalProperties?: boolean | JSONSchema4 | undefined; + + definitions?: { + [k: string]: JSONSchema4; + } | undefined; + + /** + * This attribute is an object with property definitions that define the + * valid values of instance object property values. When the instance + * value is an object, the property values of the instance object MUST + * conform to the property definitions in this object. In this object, + * each property definition's value MUST be a schema, and the property's + * name MUST be the name of the instance property that it defines. The + * instance property value MUST be valid according to the schema from + * the property definition. Properties are considered unordered, the + * order of the instance properties MAY be in any order. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.2 + */ + properties?: { + [k: string]: JSONSchema4; + } | undefined; + + /** + * This attribute is an object that defines the schema for a set of + * property names of an object instance. The name of each property of + * this attribute's object is a regular expression pattern in the ECMA + * 262/Perl 5 format, while the value is a schema. If the pattern + * matches the name of a property on the instance object, the value of + * the instance's property MUST be valid against the pattern name's + * schema value. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.3 + */ + patternProperties?: { + [k: string]: JSONSchema4; + } | undefined; + dependencies?: { + [k: string]: JSONSchema4 | string[]; + } | undefined; + + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19 + */ + enum?: JSONSchema4Type[] | undefined; + + /** + * A single type, or a union of simple types + */ + type?: JSONSchema4TypeName | JSONSchema4TypeName[] | undefined; + + allOf?: JSONSchema4[] | undefined; + anyOf?: JSONSchema4[] | undefined; + oneOf?: JSONSchema4[] | undefined; + not?: JSONSchema4 | undefined; + + /** + * The value of this property MUST be another schema which will provide + * a base schema which the current schema will inherit from. The + * inheritance rules are such that any instance that is valid according + * to the current schema MUST be valid according to the referenced + * schema. This MAY also be an array, in which case, the instance MUST + * be valid for all the schemas in the array. A schema that extends + * another schema MAY define additional attributes, constrain existing + * attributes, or add other constraints. + * + * Conceptually, the behavior of extends can be seen as validating an + * instance against all constraints in the extending schema as well as + * the extended schema(s). + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.26 + */ + extends?: string | string[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-5.6 + */ + [k: string]: any; + + format?: string | undefined; +} + +// ================================================================================================== +// JSON Schema Draft 06 +// ================================================================================================== + +export type JSONSchema6TypeName = + | "string" // + | "number" + | "integer" + | "boolean" + | "object" + | "array" + | "null" + | "any"; + +export type JSONSchema6Type = + | string // + | number + | boolean + | JSONSchema6Object + | JSONSchema6Array + | null; + +// Workaround for infinite type recursion +export interface JSONSchema6Object { + [key: string]: JSONSchema6Type; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchema6Array extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-06/schema#' + * - 'http://json-schema.org/draft-06/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema6Version = string; + +/** + * JSON Schema V6 + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01 + */ +export type JSONSchema6Definition = JSONSchema6 | boolean; +export interface JSONSchema6 { + $id?: string | undefined; + $ref?: string | undefined; + $schema?: JSONSchema6Version | undefined; + + /** + * Must be strictly greater than 0. + * A numeric instance is valid only if division by this keyword's value results in an integer. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.1 + */ + multipleOf?: number | undefined; + + /** + * Representing an inclusive upper limit for a numeric instance. + * This keyword validates only if the instance is less than or exactly equal to "maximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.2 + */ + maximum?: number | undefined; + + /** + * Representing an exclusive upper limit for a numeric instance. + * This keyword validates only if the instance is strictly less than (not equal to) to "exclusiveMaximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.3 + */ + exclusiveMaximum?: number | undefined; + + /** + * Representing an inclusive lower limit for a numeric instance. + * This keyword validates only if the instance is greater than or exactly equal to "minimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.4 + */ + minimum?: number | undefined; + + /** + * Representing an exclusive lower limit for a numeric instance. + * This keyword validates only if the instance is strictly greater than (not equal to) to "exclusiveMinimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.5 + */ + exclusiveMinimum?: number | undefined; + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.6 + */ + maxLength?: number | undefined; + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.7 + */ + minLength?: number | undefined; + + /** + * Should be a valid regular expression, according to the ECMA 262 regular expression dialect. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.8 + */ + pattern?: string | undefined; + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.9 + */ + items?: JSONSchema6Definition | JSONSchema6Definition[] | undefined; + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * If "items" is an array of schemas, validation succeeds if every instance element + * at a position greater than the size of "items" validates against "additionalItems". + * Otherwise, "additionalItems" MUST be ignored, as the "items" schema + * (possibly the default value of an empty schema) is applied to all elements. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.10 + */ + additionalItems?: JSONSchema6Definition | undefined; + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.11 + */ + maxItems?: number | undefined; + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.12 + */ + minItems?: number | undefined; + + /** + * If this keyword has boolean value false, the instance validates successfully. + * If it has boolean value true, the instance validates successfully if all of its elements are unique. + * Omitting this keyword has the same behavior as a value of false. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.13 + */ + uniqueItems?: boolean | undefined; + + /** + * An array instance is valid against "contains" if at least one of its elements is valid against the given schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.14 + */ + contains?: JSONSchema6Definition | undefined; + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.15 + */ + maxProperties?: number | undefined; + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is greater than, + * or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.16 + */ + minProperties?: number | undefined; + + /** + * Elements of this array must be unique. + * An object instance is valid against this keyword if every item in the array is the name of a property in the instance. + * Omitting this keyword has the same behavior as an empty array. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.17 + */ + required?: string[] | undefined; + + /** + * This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself. + * Validation succeeds if, for each name that appears in both the instance and as a name within this keyword's value, + * the child instance for that name successfully validates against the corresponding schema. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.18 + */ + properties?: { + [k: string]: JSONSchema6Definition; + } | undefined; + + /** + * This attribute is an object that defines the schema for a set of property names of an object instance. + * The name of each property of this attribute's object is a regular expression pattern in the ECMA 262, while the value is a schema. + * If the pattern matches the name of a property on the instance object, the value of the instance's property + * MUST be valid against the pattern name's schema value. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.19 + */ + patternProperties?: { + [k: string]: JSONSchema6Definition; + } | undefined; + + /** + * This attribute defines a schema for all properties that are not explicitly defined in an object type definition. + * If specified, the value MUST be a schema or a boolean. + * If false is provided, no additional properties are allowed beyond the properties defined in the schema. + * The default value is an empty schema which allows any value for additional properties. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.20 + */ + additionalProperties?: JSONSchema6Definition | undefined; + + /** + * This keyword specifies rules that are evaluated if the instance is an object and contains a certain property. + * Each property specifies a dependency. + * If the dependency value is an array, each element in the array must be unique. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.21 + */ + dependencies?: { + [k: string]: JSONSchema6Definition | string[]; + } | undefined; + + /** + * Takes a schema which validates the names of all properties rather than their values. + * Note the property name that the schema is testing will always be a string. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.22 + */ + propertyNames?: JSONSchema6Definition | undefined; + + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.23 + */ + enum?: JSONSchema6Type[] | undefined; + + /** + * More readable form of a one-element "enum" + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.24 + */ + const?: JSONSchema6Type | undefined; + + /** + * A single type, or a union of simple types + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.25 + */ + type?: JSONSchema6TypeName | JSONSchema6TypeName[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.26 + */ + allOf?: JSONSchema6Definition[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.27 + */ + anyOf?: JSONSchema6Definition[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.28 + */ + oneOf?: JSONSchema6Definition[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.29 + */ + not?: JSONSchema6Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.1 + */ + definitions?: { + [k: string]: JSONSchema6Definition; + } | undefined; + + /** + * This attribute is a string that provides a short description of the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + title?: string | undefined; + + /** + * This attribute is a string that provides a full description of the of purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + description?: string | undefined; + + /** + * This keyword can be used to supply a default JSON value associated with a particular schema. + * It is RECOMMENDED that a default value be valid against the associated schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.3 + */ + default?: JSONSchema6Type | undefined; + + /** + * Array of examples with no validation effect the value of "default" is usable as an example without repeating it under this keyword + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.4 + */ + examples?: JSONSchema6Type[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-8 + */ + format?: string | undefined; +} + +// ================================================================================================== +// JSON Schema Draft 07 +// ================================================================================================== +// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 +// -------------------------------------------------------------------------------------------------- + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchema7TypeName = + | "string" // + | "number" + | "integer" + | "boolean" + | "object" + | "array" + | "null"; + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchema7Type = + | string // + | number + | boolean + | JSONSchema7Object + | JSONSchema7Array + | null; + +// Workaround for infinite type recursion +export interface JSONSchema7Object { + [key: string]: JSONSchema7Type; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchema7Array extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-07/schema#' + * - 'http://json-schema.org/draft-07/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema7Version = string; + +/** + * JSON Schema v7 + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 + */ +export type JSONSchema7Definition = JSONSchema7 | boolean; +export interface JSONSchema7 { + $id?: string | undefined; + $ref?: string | undefined; + $schema?: JSONSchema7Version | undefined; + $comment?: string | undefined; + + /** + * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-8.2.4 + * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#appendix-A + */ + $defs?: { + [key: string]: JSONSchema7Definition; + } | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1 + */ + type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined; + enum?: JSONSchema7Type[] | undefined; + const?: JSONSchema7Type | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2 + */ + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: number | undefined; + minimum?: number | undefined; + exclusiveMinimum?: number | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3 + */ + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4 + */ + items?: JSONSchema7Definition | JSONSchema7Definition[] | undefined; + additionalItems?: JSONSchema7Definition | undefined; + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + contains?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5 + */ + maxProperties?: number | undefined; + minProperties?: number | undefined; + required?: string[] | undefined; + properties?: { + [key: string]: JSONSchema7Definition; + } | undefined; + patternProperties?: { + [key: string]: JSONSchema7Definition; + } | undefined; + additionalProperties?: JSONSchema7Definition | undefined; + dependencies?: { + [key: string]: JSONSchema7Definition | string[]; + } | undefined; + propertyNames?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6 + */ + if?: JSONSchema7Definition | undefined; + then?: JSONSchema7Definition | undefined; + else?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7 + */ + allOf?: JSONSchema7Definition[] | undefined; + anyOf?: JSONSchema7Definition[] | undefined; + oneOf?: JSONSchema7Definition[] | undefined; + not?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7 + */ + format?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-8 + */ + contentMediaType?: string | undefined; + contentEncoding?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-9 + */ + definitions?: { + [key: string]: JSONSchema7Definition; + } | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10 + */ + title?: string | undefined; + description?: string | undefined; + default?: JSONSchema7Type | undefined; + readOnly?: boolean | undefined; + writeOnly?: boolean | undefined; + examples?: JSONSchema7Type | undefined; +} + +export interface ValidationResult { + valid: boolean; + errors: ValidationError[]; +} + +export interface ValidationError { + property: string; + message: string; +} + +/** + * To use the validator call JSONSchema.validate with an instance object and an optional schema object. + * If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), + * that schema will be used to validate and the schema parameter is not necessary (if both exist, + * both validations will occur). + */ +export function validate(instance: {}, schema: JSONSchema4 | JSONSchema6 | JSONSchema7): ValidationResult; + +/** + * The checkPropertyChange method will check to see if an value can legally be in property with the given schema + * This is slightly different than the validate method in that it will fail if the schema is readonly and it will + * not check for self-validation, it is assumed that the passed in value is already internally valid. + */ +export function checkPropertyChange( + value: any, + schema: JSONSchema4 | JSONSchema6 | JSONSchema7, + property: string, +): ValidationResult; + +/** + * This checks to ensure that the result is valid and will throw an appropriate error message if it is not. + */ +export function mustBeValid(result: ValidationResult): void; diff --git a/node_modules/@types/json-schema/package.json b/node_modules/@types/json-schema/package.json new file mode 100644 index 00000000..3c41bd7f --- /dev/null +++ b/node_modules/@types/json-schema/package.json @@ -0,0 +1,40 @@ +{ + "name": "@types/json-schema", + "version": "7.0.15", + "description": "TypeScript definitions for json-schema", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema", + "license": "MIT", + "contributors": [ + { + "name": "Boris Cherny", + "githubUsername": "bcherny", + "url": "https://github.com/bcherny" + }, + { + "name": "Lucian Buzzo", + "githubUsername": "lucianbuzzo", + "url": "https://github.com/lucianbuzzo" + }, + { + "name": "Roland Groza", + "githubUsername": "rolandjitsu", + "url": "https://github.com/rolandjitsu" + }, + { + "name": "Jason Kwok", + "githubUsername": "JasonHK", + "url": "https://github.com/JasonHK" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/json-schema" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "79984fd70cd25c3f7d72b84368778c763c89728ea0073832d745d4691b705257", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/node_modules/@types/react-dom/LICENSE b/node_modules/@types/react-dom/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/node_modules/@types/react-dom/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/react-dom/README.md b/node_modules/@types/react-dom/README.md new file mode 100644 index 00000000..29b8f0b9 --- /dev/null +++ b/node_modules/@types/react-dom/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/react-dom` + +# Summary +This package contains type definitions for react-dom (https://react.dev/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react-dom. + +### Additional Details + * Last updated: Wed, 04 Jun 2025 12:44:27 GMT + * Dependencies: none + * Peer dependencies: [@types/react](https://npmjs.com/package/@types/react) + +# Credits +These definitions were written by [Asana](https://asana.com), [AssureSign](http://www.assuresign.com), [Microsoft](https://microsoft.com), [MartynasZilinskas](https://github.com/MartynasZilinskas), [Josh Rutherford](https://github.com/theruther4d), [Jessica Franco](https://github.com/Jessidhia), and [Sebastian Silbermann](https://github.com/eps1lon). diff --git a/node_modules/@types/react-dom/canary.d.ts b/node_modules/@types/react-dom/canary.d.ts new file mode 100644 index 00000000..ba961bf5 --- /dev/null +++ b/node_modules/@types/react-dom/canary.d.ts @@ -0,0 +1,32 @@ +/** + * These are types for things that are present in the upcoming React 18 release. + * + * Once React 18 is released they can just be moved to the main index file. + * + * To load the types declared here in an actual project, there are three ways. The easiest one, + * if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section, + * is to add `"react-dom/canary"` to the `"types"` array. + * + * Alternatively, a specific import syntax can to be used from a typescript file. + * This module does not exist in reality, which is why the {} is important: + * + * ```ts + * import {} from 'react-dom/canary' + * ``` + * + * It is also possible to include it through a triple-slash reference: + * + * ```ts + * /// + * ``` + * + * Either the import or the reference only needs to appear once, anywhere in the project. + */ + +// See https://github.com/facebook/react/blob/main/packages/react-dom/index.js to see how the exports are declared, +// but confirm with published source code (e.g. https://unpkg.com/react-dom@canary) that these exports end up in the published code + +import React = require("react"); +import ReactDOM = require("."); + +export {}; diff --git a/node_modules/@types/react-dom/client.d.ts b/node_modules/@types/react-dom/client.d.ts new file mode 100644 index 00000000..90f941ae --- /dev/null +++ b/node_modules/@types/react-dom/client.d.ts @@ -0,0 +1,105 @@ +/** + * WARNING: This entrypoint is only available starting with `react-dom@18.0.0-rc.1` + */ + +// See https://github.com/facebook/react/blob/main/packages/react-dom/client.js to see how the exports are declared, + +import React = require("react"); + +export {}; + +declare const REACT_FORM_STATE_SIGIL: unique symbol; +export interface ReactFormState { + [REACT_FORM_STATE_SIGIL]: never; +} + +export interface HydrationOptions { + formState?: ReactFormState | null; + /** + * Prefix for `useId`. + */ + identifierPrefix?: string; + onUncaughtError?: + | ((error: unknown, errorInfo: { componentStack?: string | undefined }) => void) + | undefined; + onRecoverableError?: (error: unknown, errorInfo: ErrorInfo) => void; + onCaughtError?: + | (( + error: unknown, + errorInfo: { + componentStack?: string | undefined; + errorBoundary?: React.Component | undefined; + }, + ) => void) + | undefined; +} + +export interface RootOptions { + /** + * Prefix for `useId`. + */ + identifierPrefix?: string; + onUncaughtError?: + | ((error: unknown, errorInfo: { componentStack?: string | undefined }) => void) + | undefined; + onRecoverableError?: (error: unknown, errorInfo: ErrorInfo) => void; + onCaughtError?: + | (( + error: unknown, + errorInfo: { + componentStack?: string | undefined; + errorBoundary?: React.Component | undefined; + }, + ) => void) + | undefined; +} + +export interface ErrorInfo { + componentStack?: string; +} + +export interface Root { + render(children: React.ReactNode): void; + unmount(): void; +} + +/** + * Different release channels declare additional types of ReactNode this particular release channel accepts. + * App or library types should never augment this interface. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_CREATE_ROOT_CONTAINERS {} + +export type Container = + | Element + | DocumentFragment + | Document + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_CREATE_ROOT_CONTAINERS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_CREATE_ROOT_CONTAINERS + ]; + +/** + * createRoot lets you create a root to display React components inside a browser DOM node. + * + * @see {@link https://react.dev/reference/react-dom/client/createRoot API Reference for `createRoot`} + */ +export function createRoot(container: Container, options?: RootOptions): Root; + +/** + * Same as `createRoot()`, but is used to hydrate a container whose HTML contents were rendered by ReactDOMServer. + * + * React will attempt to attach event listeners to the existing markup. + * + * **Example Usage** + * + * ```jsx + * hydrateRoot(document.querySelector('#root'), ) + * ``` + * + * @see https://reactjs.org/docs/react-dom-client.html#hydrateroot + */ +export function hydrateRoot( + container: Element | Document, + initialChildren: React.ReactNode, + options?: HydrationOptions, +): Root; diff --git a/node_modules/@types/react-dom/experimental.d.ts b/node_modules/@types/react-dom/experimental.d.ts new file mode 100644 index 00000000..a0182f2a --- /dev/null +++ b/node_modules/@types/react-dom/experimental.d.ts @@ -0,0 +1,86 @@ +/** + * These are types for things that are present in the `experimental` builds of React but not yet + * on a stable build. + * + * Once they are promoted to stable they can just be moved to the main index file. + * + * To load the types declared here in an actual project, there are three ways. The easiest one, + * if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section, + * is to add `"react-dom/experimental"` to the `"types"` array. + * + * Alternatively, a specific import syntax can to be used from a typescript file. + * This module does not exist in reality, which is why the {} is important: + * + * ```ts + * import {} from 'react-dom/experimental' + * ``` + * + * It is also possible to include it through a triple-slash reference: + * + * ```ts + * /// + * ``` + * + * Either the import or the reference only needs to appear once, anywhere in the project. + */ + +// See https://github.com/facebook/react/blob/main/packages/react-dom/index.experimental.js to see how the exports are declared, +// but confirm with published source code (e.g. https://unpkg.com/react-dom@experimental) that these exports end up in the published code + +import React = require("react"); +import ReactDOM = require("./canary"); + +export {}; + +declare const UNDEFINED_VOID_ONLY: unique symbol; +type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never }; + +declare module "." { +} + +declare module "react" { + interface ViewTransitionPseudoElement extends Animatable { + getComputedStyle: () => CSSStyleDeclaration; + } + + interface ViewTransitionInstance { + group: ViewTransitionPseudoElement; + imagePair: ViewTransitionPseudoElement; + old: ViewTransitionPseudoElement; + new: ViewTransitionPseudoElement; + } + + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface GestureProvider extends AnimationTimeline {} + + // @enableFragmentRefs + interface FragmentInstance { + blur: () => void; + focus: (focusOptions?: FocusOptions | undefined) => void; + focusLast: (focusOptions?: FocusOptions | undefined) => void; + observeUsing(observer: IntersectionObserver | ResizeObserver): void; + unobserveUsing(observer: IntersectionObserver | ResizeObserver): void; + getClientRects(): Array; + getRootNode(getRootNodeOptions?: GetRootNodeOptions | undefined): Document | ShadowRoot | FragmentInstance; + addEventListener( + type: string, + listener: EventListener, + optionsOrUseCapture?: Parameters[2], + ): void; + removeEventListener( + type: string, + listener: EventListener, + optionsOrUseCapture?: Parameters[2], + ): void; + } +} + +declare module "./client" { + type TransitionIndicatorCleanup = () => VoidOrUndefinedOnly; + interface RootOptions { + onDefaultTransitionIndicator?: (() => void | TransitionIndicatorCleanup) | undefined; + } + interface HydrationOptions { + onDefaultTransitionIndicator?: (() => void | TransitionIndicatorCleanup) | undefined; + } +} diff --git a/node_modules/@types/react-dom/index.d.ts b/node_modules/@types/react-dom/index.d.ts new file mode 100644 index 00000000..76efddd2 --- /dev/null +++ b/node_modules/@types/react-dom/index.d.ts @@ -0,0 +1,128 @@ +// NOTE: Users of the `experimental` builds of React should add a reference +// to 'react-dom/experimental' in their project. See experimental.d.ts's top comment +// for reference and documentation on how exactly to do it. + +export as namespace ReactDOM; + +import { Key, ReactNode, ReactPortal } from "react"; + +export function createPortal( + children: ReactNode, + container: Element | DocumentFragment, + key?: Key | null, +): ReactPortal; + +export const version: string; + +export function flushSync(fn: () => R): R; + +export function unstable_batchedUpdates(callback: (a: A) => R, a: A): R; +export function unstable_batchedUpdates(callback: () => R): R; + +export interface FormStatusNotPending { + pending: false; + data: null; + method: null; + action: null; +} + +export interface FormStatusPending { + pending: true; + data: FormData; + method: string; + action: string | ((formData: FormData) => void | Promise); +} + +export type FormStatus = FormStatusPending | FormStatusNotPending; + +export function useFormStatus(): FormStatus; + +export function useFormState( + action: (state: Awaited) => State | Promise, + initialState: Awaited, + permalink?: string, +): [state: Awaited, dispatch: () => void, isPending: boolean]; +export function useFormState( + action: (state: Awaited, payload: Payload) => State | Promise, + initialState: Awaited, + permalink?: string, +): [state: Awaited, dispatch: (payload: Payload) => void, isPending: boolean]; + +export function prefetchDNS(href: string): void; + +export interface PreconnectOptions { + // Don't create a helper type. + // It would have to be in module scope to be inlined in TS tooltips. + // But then it becomes part of the public API. + // TODO: Upstream to microsoft/TypeScript-DOM-lib-generator -> w3c/webref + // since the spec has a notion of a dedicated type: https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attribute + crossOrigin?: "anonymous" | "use-credentials" | "" | undefined; +} +export function preconnect(href: string, options?: PreconnectOptions): void; + +export type PreloadAs = + | "audio" + | "document" + | "embed" + | "fetch" + | "font" + | "image" + | "object" + | "track" + | "script" + | "style" + | "video" + | "worker"; +export interface PreloadOptions { + as: PreloadAs; + crossOrigin?: "anonymous" | "use-credentials" | "" | undefined; + fetchPriority?: "high" | "low" | "auto" | undefined; + // TODO: These should only be allowed with `as: 'image'` but it's not trivial to write tests against the full TS support matrix. + imageSizes?: string | undefined; + imageSrcSet?: string | undefined; + integrity?: string | undefined; + type?: string | undefined; + nonce?: string | undefined; + referrerPolicy?: ReferrerPolicy | undefined; + media?: string | undefined; +} +export function preload(href: string, options?: PreloadOptions): void; + +// https://html.spec.whatwg.org/multipage/links.html#link-type-modulepreload +export type PreloadModuleAs = RequestDestination; +export interface PreloadModuleOptions { + /** + * @default "script" + */ + as: PreloadModuleAs; + crossOrigin?: "anonymous" | "use-credentials" | "" | undefined; + integrity?: string | undefined; + nonce?: string | undefined; +} +export function preloadModule(href: string, options?: PreloadModuleOptions): void; + +export type PreinitAs = "script" | "style"; +export interface PreinitOptions { + as: PreinitAs; + crossOrigin?: "anonymous" | "use-credentials" | "" | undefined; + fetchPriority?: "high" | "low" | "auto" | undefined; + precedence?: string | undefined; + integrity?: string | undefined; + nonce?: string | undefined; +} +export function preinit(href: string, options?: PreinitOptions): void; + +// Will be expanded to include all of https://github.com/tc39/proposal-import-attributes +export type PreinitModuleAs = "script"; +export interface PreinitModuleOptions { + /** + * @default "script" + */ + as?: PreinitModuleAs; + crossOrigin?: "anonymous" | "use-credentials" | "" | undefined; + integrity?: string | undefined; + nonce?: string | undefined; +} +export function preinitModule(href: string, options?: PreinitModuleOptions): void; + +export function requestFormReset(form: HTMLFormElement): void; diff --git a/node_modules/@types/react-dom/package.json b/node_modules/@types/react-dom/package.json new file mode 100644 index 00000000..0b69ec0c --- /dev/null +++ b/node_modules/@types/react-dom/package.json @@ -0,0 +1,128 @@ +{ + "name": "@types/react-dom", + "version": "19.1.6", + "description": "TypeScript definitions for react-dom", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react-dom", + "license": "MIT", + "contributors": [ + { + "name": "Asana", + "url": "https://asana.com" + }, + { + "name": "AssureSign", + "url": "http://www.assuresign.com" + }, + { + "name": "Microsoft", + "url": "https://microsoft.com" + }, + { + "name": "MartynasZilinskas", + "githubUsername": "MartynasZilinskas", + "url": "https://github.com/MartynasZilinskas" + }, + { + "name": "Josh Rutherford", + "githubUsername": "theruther4d", + "url": "https://github.com/theruther4d" + }, + { + "name": "Jessica Franco", + "githubUsername": "Jessidhia", + "url": "https://github.com/Jessidhia" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + } + ], + "main": "", + "types": "index.d.ts", + "exports": { + ".": { + "types": { + "default": "./index.d.ts" + } + }, + "./client": { + "types": { + "default": "./client.d.ts" + } + }, + "./canary": { + "types": { + "default": "./canary.d.ts" + } + }, + "./server": { + "types": { + "default": "./server.d.ts" + } + }, + "./server.browser": { + "types": { + "default": "./server.browser.d.ts" + } + }, + "./server.bun": { + "types": { + "default": "./server.bun.d.ts" + } + }, + "./server.edge": { + "types": { + "default": "./server.edge.d.ts" + } + }, + "./server.node": { + "types": { + "default": "./server.node.d.ts" + } + }, + "./static": { + "types": { + "default": "./static.d.ts" + } + }, + "./static.browser": { + "types": { + "default": "./static.browser.d.ts" + } + }, + "./static.edge": { + "types": { + "default": "./static.edge.d.ts" + } + }, + "./static.node": { + "types": { + "default": "./static.node.d.ts" + } + }, + "./experimental": { + "types": { + "default": "./experimental.d.ts" + } + }, + "./test-utils": { + "types": { + "default": "./test-utils/index.d.ts" + } + }, + "./package.json": "./package.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/react-dom" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": { + "@types/react": "^19.0.0" + }, + "typesPublisherContentHash": "7b56a76f96eb2aa35d120d8e3b6f3d4d931764fe44b89b21cd496919cab0e223", + "typeScriptVersion": "5.1" +} \ No newline at end of file diff --git a/node_modules/@types/react-dom/server.browser.d.ts b/node_modules/@types/react-dom/server.browser.d.ts new file mode 100644 index 00000000..f2e3bc93 --- /dev/null +++ b/node_modules/@types/react-dom/server.browser.d.ts @@ -0,0 +1 @@ +export { renderToReadableStream, renderToStaticMarkup, renderToString } from "./server"; diff --git a/node_modules/@types/react-dom/server.bun.d.ts b/node_modules/@types/react-dom/server.bun.d.ts new file mode 100644 index 00000000..f2e3bc93 --- /dev/null +++ b/node_modules/@types/react-dom/server.bun.d.ts @@ -0,0 +1 @@ +export { renderToReadableStream, renderToStaticMarkup, renderToString } from "./server"; diff --git a/node_modules/@types/react-dom/server.d.ts b/node_modules/@types/react-dom/server.d.ts new file mode 100644 index 00000000..c298f6db --- /dev/null +++ b/node_modules/@types/react-dom/server.d.ts @@ -0,0 +1,114 @@ +// forward declarations +declare global { + namespace NodeJS { + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface ReadableStream {} + + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface WritableStream {} + } + + /** + * Stub for https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal + */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface AbortSignal {} + + /** + * Stub for https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface ReadableStream {} +} + +import { ReactNode } from "react"; +import { ErrorInfo } from "./client"; + +export type BootstrapScriptDescriptor = { + src: string; + integrity?: string | undefined; + crossOrigin?: string | undefined; +}; + +export interface RenderToPipeableStreamOptions { + identifierPrefix?: string; + namespaceURI?: string; + nonce?: string; + bootstrapScriptContent?: string; + bootstrapScripts?: Array; + bootstrapModules?: Array; + progressiveChunkSize?: number; + onShellReady?: () => void; + onShellError?: (error: unknown) => void; + onAllReady?: () => void; + onError?: (error: unknown, errorInfo: ErrorInfo) => string | void; +} + +export interface PipeableStream { + abort: (reason?: unknown) => void; + pipe: (destination: Writable) => Writable; +} + +export interface ServerOptions { + identifierPrefix?: string; +} + +/** + * Only available in the environments with [Node.js Streams](https://nodejs.dev/learn/nodejs-streams). + * + * @see [API](https://reactjs.org/docs/react-dom-server.html#rendertopipeablestream) + * + * @param children + * @param options + */ +export function renderToPipeableStream(children: ReactNode, options?: RenderToPipeableStreamOptions): PipeableStream; + +/** + * Render a React element to its initial HTML. This should only be used on the server. + * React will return an HTML string. You can use this method to generate HTML on the server + * and send the markup down on the initial request for faster page loads and to allow search + * engines to crawl your pages for SEO purposes. + * + * If you call `ReactDOMClient.hydrateRoot()` on a node that already has this server-rendered markup, + * React will preserve it and only attach event handlers, allowing you + * to have a very performant first-load experience. + */ +export function renderToString(element: ReactNode, options?: ServerOptions): string; + +/** + * Similar to `renderToString`, except this doesn't create extra DOM attributes + * such as `data-reactid`, that React uses internally. This is useful if you want + * to use React as a simple static page generator, as stripping away the extra + * attributes can save lots of bytes. + */ +export function renderToStaticMarkup(element: ReactNode, options?: ServerOptions): string; + +export interface RenderToReadableStreamOptions { + identifierPrefix?: string; + namespaceURI?: string; + nonce?: string; + bootstrapScriptContent?: string; + bootstrapScripts?: Array; + bootstrapModules?: Array; + progressiveChunkSize?: number; + signal?: AbortSignal; + onError?: (error: unknown, errorInfo: ErrorInfo) => string | void; +} + +export interface ReactDOMServerReadableStream extends ReadableStream { + allReady: Promise; +} + +/** + * Only available in the environments with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) (this includes browsers, Deno, and some modern edge runtimes). + * + * @see [API](https://reactjs.org/docs/react-dom-server.html#rendertoreadablestream) + */ +export function renderToReadableStream( + children: ReactNode, + options?: RenderToReadableStreamOptions, +): Promise; + +export const version: string; + +export as namespace ReactDOMServer; diff --git a/node_modules/@types/react-dom/server.edge.d.ts b/node_modules/@types/react-dom/server.edge.d.ts new file mode 100644 index 00000000..f2e3bc93 --- /dev/null +++ b/node_modules/@types/react-dom/server.edge.d.ts @@ -0,0 +1 @@ +export { renderToReadableStream, renderToStaticMarkup, renderToString } from "./server"; diff --git a/node_modules/@types/react-dom/server.node.d.ts b/node_modules/@types/react-dom/server.node.d.ts new file mode 100644 index 00000000..5f426f2a --- /dev/null +++ b/node_modules/@types/react-dom/server.node.d.ts @@ -0,0 +1 @@ +export { renderToPipeableStream, renderToStaticMarkup, renderToString } from "./server"; diff --git a/node_modules/@types/react-dom/static.browser.d.ts b/node_modules/@types/react-dom/static.browser.d.ts new file mode 100644 index 00000000..cd2d05ff --- /dev/null +++ b/node_modules/@types/react-dom/static.browser.d.ts @@ -0,0 +1 @@ +export { prerender, version } from "./static"; diff --git a/node_modules/@types/react-dom/static.d.ts b/node_modules/@types/react-dom/static.d.ts new file mode 100644 index 00000000..ef52180c --- /dev/null +++ b/node_modules/@types/react-dom/static.d.ts @@ -0,0 +1,78 @@ +// forward declarations +declare global { + namespace NodeJS { + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface ReadableStream {} + } + + /** + * Stub for https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal + */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface AbortSignal {} + + /** + * Stub for https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface ReadableStream {} + + /** + * Stub for https://developer.mozilla.org/en-US/docs/Web/API/Uint8Array + */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface Uint8Array {} +} + +import { ReactNode } from "react"; +import { ErrorInfo } from "./client"; + +export type BootstrapScriptDescriptor = { + src: string; + integrity?: string | undefined; + crossOrigin?: string | undefined; +}; + +export interface PrerenderOptions { + bootstrapScriptContent?: string; + bootstrapScripts?: Array; + bootstrapModules?: Array; + identifierPrefix?: string; + namespaceURI?: string; + onError?: (error: unknown, errorInfo: ErrorInfo) => string | void; + progressiveChunkSize?: number; + signal?: AbortSignal; +} + +export interface PrerenderResult { + prelude: ReadableStream; +} + +/** + * Only available in the environments with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) (this includes browsers, Deno, and some modern edge runtimes). + * + * @see [API](https://react.dev/reference/react-dom/static/prerender) + */ +export function prerender( + reactNode: ReactNode, + options?: PrerenderOptions, +): Promise; + +export interface PrerenderToNodeStreamResult { + prelude: NodeJS.ReadableStream; +} + +/** + * Only available in the environments with [Node.js Streams](https://nodejs.dev/learn/nodejs-streams). + * + * @see [API](https://react.dev/reference/react-dom/static/prerenderToNodeStream) + * + * @param children + * @param options + */ +export function prerenderToNodeStream( + reactNode: ReactNode, + options?: PrerenderOptions, +): Promise; + +export const version: string; diff --git a/node_modules/@types/react-dom/static.edge.d.ts b/node_modules/@types/react-dom/static.edge.d.ts new file mode 100644 index 00000000..cd2d05ff --- /dev/null +++ b/node_modules/@types/react-dom/static.edge.d.ts @@ -0,0 +1 @@ +export { prerender, version } from "./static"; diff --git a/node_modules/@types/react-dom/static.node.d.ts b/node_modules/@types/react-dom/static.node.d.ts new file mode 100644 index 00000000..cb7017eb --- /dev/null +++ b/node_modules/@types/react-dom/static.node.d.ts @@ -0,0 +1 @@ +export { prerenderToNodeStream, version } from "./static"; diff --git a/node_modules/@types/react-dom/test-utils/index.d.ts b/node_modules/@types/react-dom/test-utils/index.d.ts new file mode 100644 index 00000000..7e211ea0 --- /dev/null +++ b/node_modules/@types/react-dom/test-utils/index.d.ts @@ -0,0 +1,7 @@ +export {}; + +export { + /** + * @deprecated Import `act` from `react` instead. + */ act, +} from "react"; diff --git a/node_modules/@types/react/LICENSE b/node_modules/@types/react/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/node_modules/@types/react/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/react/README.md b/node_modules/@types/react/README.md new file mode 100644 index 00000000..f44aac78 --- /dev/null +++ b/node_modules/@types/react/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/react` + +# Summary +This package contains type definitions for react (https://react.dev/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react. + +### Additional Details + * Last updated: Wed, 11 Jun 2025 13:41:16 GMT + * Dependencies: [csstype](https://npmjs.com/package/csstype) + +# Credits +These definitions were written by [Asana](https://asana.com), [AssureSign](http://www.assuresign.com), [Microsoft](https://microsoft.com), [John Reilly](https://github.com/johnnyreilly), [Benoit Benezech](https://github.com/bbenezech), [Patricio Zavolinsky](https://github.com/pzavolinsky), [Eric Anderson](https://github.com/ericanderson), [Dovydas Navickas](https://github.com/DovydasNavickas), [Josh Rutherford](https://github.com/theruther4d), [Guilherme Hübner](https://github.com/guilhermehubner), [Ferdy Budhidharma](https://github.com/ferdaber), [Johann Rakotoharisoa](https://github.com/jrakotoharisoa), [Olivier Pascal](https://github.com/pascaloliv), [Martin Hochel](https://github.com/hotell), [Frank Li](https://github.com/franklixuefei), [Jessica Franco](https://github.com/Jessidhia), [Saransh Kataria](https://github.com/saranshkataria), [Kanitkorn Sujautra](https://github.com/lukyth), [Sebastian Silbermann](https://github.com/eps1lon), [Kyle Scully](https://github.com/zieka), [Cong Zhang](https://github.com/dancerphil), [Dimitri Mitropoulos](https://github.com/dimitropoulos), [JongChan Choi](https://github.com/disjukr), [Victor Magalhães](https://github.com/vhfmag), [Priyanshu Rav](https://github.com/priyanshurav), [Dmitry Semigradsky](https://github.com/Semigradsky), and [Matt Pocock](https://github.com/mattpocock). diff --git a/node_modules/@types/react/canary.d.ts b/node_modules/@types/react/canary.d.ts new file mode 100644 index 00000000..9215a16b --- /dev/null +++ b/node_modules/@types/react/canary.d.ts @@ -0,0 +1,35 @@ +/** + * These are types for things that are present in the React `canary` release channel. + * + * To load the types declared here in an actual project, there are three ways. The easiest one, + * if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section, + * is to add `"react/canary"` to the `"types"` array. + * + * Alternatively, a specific import syntax can to be used from a typescript file. + * This module does not exist in reality, which is why the {} is important: + * + * ```ts + * import {} from 'react/canary' + * ``` + * + * It is also possible to include it through a triple-slash reference: + * + * ```ts + * /// + * ``` + * + * Either the import or the reference only needs to appear once, anywhere in the project. + */ + +// See https://github.com/facebook/react/blob/main/packages/react/src/React.js to see how the exports are declared, + +import React = require("."); + +export {}; + +declare const UNDEFINED_VOID_ONLY: unique symbol; +type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never }; + +declare module "." { + export function unstable_useCacheRefresh(): () => void; +} diff --git a/node_modules/@types/react/compiler-runtime.d.ts b/node_modules/@types/react/compiler-runtime.d.ts new file mode 100644 index 00000000..a98a26e6 --- /dev/null +++ b/node_modules/@types/react/compiler-runtime.d.ts @@ -0,0 +1,4 @@ +// Not meant to be used directly +// Omitting all exports so that they don't appear in IDE autocomplete. + +export {}; diff --git a/node_modules/@types/react/experimental.d.ts b/node_modules/@types/react/experimental.d.ts new file mode 100644 index 00000000..c690165a --- /dev/null +++ b/node_modules/@types/react/experimental.d.ts @@ -0,0 +1,243 @@ +/** + * These are types for things that are present in the `experimental` builds of React but not yet + * on a stable build. + * + * Once they are promoted to stable they can just be moved to the main index file. + * + * To load the types declared here in an actual project, there are three ways. The easiest one, + * if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section, + * is to add `"react/experimental"` to the `"types"` array. + * + * Alternatively, a specific import syntax can to be used from a typescript file. + * This module does not exist in reality, which is why the {} is important: + * + * ```ts + * import {} from 'react/experimental' + * ``` + * + * It is also possible to include it through a triple-slash reference: + * + * ```ts + * /// + * ``` + * + * Either the import or the reference only needs to appear once, anywhere in the project. + */ + +// See https://github.com/facebook/react/blob/master/packages/react/src/React.js to see how the exports are declared, +// and https://github.com/facebook/react/blob/master/packages/shared/ReactFeatureFlags.js to verify which APIs are +// flagged experimental or not. Experimental APIs will be tagged with `__EXPERIMENTAL__`. +// +// For the inputs of types exported as simply a fiber tag, the `beginWork` function of ReactFiberBeginWork.js +// is a good place to start looking for details; it generally calls prop validation functions or delegates +// all tasks done as part of the render phase (the concurrent part of the React update cycle). +// +// Suspense-related handling can be found in ReactFiberThrow.js. + +import React = require("./canary"); + +export {}; + +declare const UNDEFINED_VOID_ONLY: unique symbol; +type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never }; + +declare module "." { + export interface SuspenseProps { + /** + * The presence of this prop indicates that the content is computationally expensive to render. + * In other words, the tree is CPU bound and not I/O bound (e.g. due to fetching data). + * @see {@link https://github.com/facebook/react/pull/19936} + */ + unstable_expectedLoadTime?: number | undefined; + } + + export type SuspenseListRevealOrder = "forwards" | "backwards" | "together" | "independent"; + export type SuspenseListTailMode = "collapsed" | "hidden" | "visible"; + + export interface SuspenseListCommonProps { + } + + interface DirectionalSuspenseListProps extends SuspenseListCommonProps { + /** + * Note that SuspenseList require more than one child; + * it is a runtime warning to provide only a single child. + * + * It does, however, allow those children to be wrapped inside a single + * level of ``. + */ + children: Iterable | AsyncIterable; + /** + * Defines the order in which the `SuspenseList` children should be revealed. + */ + revealOrder: "forwards" | "backwards" | "unstable_legacy-backwards"; + /** + * Dictates how unloaded items in a SuspenseList is shown. + * + * - By default, `SuspenseList` will show all fallbacks in the list. + * - `collapsed` shows only the next fallback in the list. + * - `hidden` doesn't show any unloaded items. + * - `visible` shows all fallbacks in the list. + */ + tail: SuspenseListTailMode; + } + + interface NonDirectionalSuspenseListProps extends SuspenseListCommonProps { + children: ReactNode; + /** + * Defines the order in which the `SuspenseList` children should be revealed. + */ + revealOrder: Exclude | undefined; + /** + * The tail property is invalid when not using the `forwards` or `backwards` reveal orders. + */ + tail?: never; + } + + export type SuspenseListProps = DirectionalSuspenseListProps | NonDirectionalSuspenseListProps; + + /** + * `SuspenseList` helps coordinate many components that can suspend by orchestrating the order + * in which these components are revealed to the user. + * + * When multiple components need to fetch data, this data may arrive in an unpredictable order. + * However, if you wrap these items in a `SuspenseList`, React will not show an item in the list + * until previous items have been displayed (this behavior is adjustable). + * + * @see https://reactjs.org/docs/concurrent-mode-reference.html#suspenselist + * @see https://reactjs.org/docs/concurrent-mode-patterns.html#suspenselist + */ + export const unstable_SuspenseList: ExoticComponent; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + export function experimental_useEffectEvent(event: T): T; + + type Reference = object; + type TaintableUniqueValue = string | bigint | ArrayBufferView; + function experimental_taintUniqueValue( + message: string | undefined, + lifetime: Reference, + value: TaintableUniqueValue, + ): void; + function experimental_taintObjectReference(message: string | undefined, object: Reference): void; + + export interface ViewTransitionInstance { + /** + * The {@link ViewTransitionProps name} that was used in the corresponding {@link ViewTransition} component or `"auto"` if the `name` prop was omitted. + */ + name: string; + } + + export type ViewTransitionClassPerType = Record<"default" | (string & {}), "none" | "auto" | (string & {})>; + export type ViewTransitionClass = ViewTransitionClassPerType | ViewTransitionClassPerType[string]; + + export interface ViewTransitionProps { + children?: ReactNode | undefined; + /** + * Assigns the {@link https://developer.chrome.com/blog/view-transitions-update-io24#view-transition-class `view-transition-class`} class to the underlying DOM node. + */ + default?: ViewTransitionClass | undefined; + /** + * Combined with {@link className} if this `` or its parent Component is mounted and there's no other with the same name being deleted. + * `"none"` is a special value that deactivates the view transition name under that condition. + */ + enter?: ViewTransitionClass | undefined; + /** + * Combined with {@link className} if this `` or its parent Component is unmounted and there's no other with the same name being deleted. + * `"none"` is a special value that deactivates the view transition name under that condition. + */ + exit?: ViewTransitionClass | undefined; + /** + * "auto" will automatically assign a view-transition-name to the inner DOM node. + * That way you can add a View Transition to a Component without controlling its DOM nodes styling otherwise. + * + * A difference between this and the browser's built-in view-transition-name: auto is that switching the DOM nodes within the `` component preserves the same name so this example cross-fades between the DOM nodes instead of causing an exit and enter. + * @default "auto" + */ + name?: "auto" | (string & {}) | undefined; + /** + * The `` or its parent Component is mounted and there's no other `` with the same name being deleted. + */ + onEnter?: (instance: ViewTransitionInstance, types: Array) => void; + /** + * The `` or its parent Component is unmounted and there's no other `` with the same name being deleted. + */ + onExit?: (instance: ViewTransitionInstance, types: Array) => void; + /** + * This `` is being mounted and another `` instance with the same name is being unmounted elsewhere. + */ + onShare?: (instance: ViewTransitionInstance, types: Array) => void; + /** + * The content of `` has changed either due to DOM mutations or because an inner child `` has resized. + */ + onUpdate?: (instance: ViewTransitionInstance, types: Array) => void; + ref?: Ref | undefined; + /** + * Combined with {@link className} if this `` is being mounted and another instance with the same name is being unmounted elsewhere. + * `"none"` is a special value that deactivates the view transition name under that condition. + */ + share?: ViewTransitionClass | undefined; + /** + * Combined with {@link className} if the content of this `` has changed either due to DOM mutations or because an inner child has resized. + * `"none"` is a special value that deactivates the view transition name under that condition. + */ + update?: ViewTransitionClass | undefined; + } + + /** + * Opt-in for using {@link https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API View Transitions} in React. + * View Transitions only trigger for async updates like {@link startTransition}, {@link useDeferredValue}, Actions or <{@link Suspense}> revealing from fallback to content. + * Synchronous updates provide an opt-out but also guarantee that they commit immediately which View Transitions can't. + * + * @see {@link https://github.com/facebook/react/pull/31975} + */ + export const unstable_ViewTransition: ExoticComponent; + + export function unstable_addTransitionType(type: string): void; + + // @enableGestureTransition + // Implemented by the specific renderer e.g. `react-dom`. + // Keep in mind that augmented interfaces merge their JSDoc so if you put + // JSDoc here and in the renderer, the IDE will display both. + export interface GestureProvider {} + export interface GestureOptions { + rangeStart?: number | undefined; + rangeEnd?: number | undefined; + } + /** */ + export function unstable_startGestureTransition( + provider: GestureProvider, + scope: () => void, + options?: GestureOptions, + ): () => void; + + // @enableFragmentRefs + export interface FragmentInstance {} + + export interface FragmentProps { + ref?: Ref | undefined; + } + + // @enableActivity + export interface ActivityProps { + /** + * @default "visible" + */ + mode?: + | "hidden" + | "visible" + | undefined; + children: ReactNode; + } + + /** */ + export const unstable_Activity: ExoticComponent; + + // @enableSrcObject + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES { + srcObject: Blob; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES { + srcObject: Blob | MediaSource | MediaStream; + } +} diff --git a/node_modules/@types/react/global.d.ts b/node_modules/@types/react/global.d.ts new file mode 100644 index 00000000..6770d08e --- /dev/null +++ b/node_modules/@types/react/global.d.ts @@ -0,0 +1,165 @@ +/* +React projects that don't include the DOM library need these interfaces to compile. +React Native applications use React, but there is no DOM available. The JavaScript runtime +is ES6/ES2015 only. These definitions allow such projects to compile with only `--lib ES6`. + +Warning: all of these interfaces are empty. If you want type definitions for various properties +(such as HTMLInputElement.prototype.value), you need to add `--lib DOM` (via command line or tsconfig.json). +*/ + +interface Event {} +interface AnimationEvent extends Event {} +interface ClipboardEvent extends Event {} +interface CompositionEvent extends Event {} +interface DragEvent extends Event {} +interface FocusEvent extends Event {} +interface InputEvent extends Event {} +interface KeyboardEvent extends Event {} +interface MouseEvent extends Event {} +interface TouchEvent extends Event {} +interface PointerEvent extends Event {} +interface ToggleEvent extends Event {} +interface TransitionEvent extends Event {} +interface UIEvent extends Event {} +interface WheelEvent extends Event {} + +interface EventTarget {} +interface Document {} +interface DataTransfer {} +interface StyleMedia {} + +interface Element {} +interface DocumentFragment {} + +interface HTMLElement extends Element {} +interface HTMLAnchorElement extends HTMLElement {} +interface HTMLAreaElement extends HTMLElement {} +interface HTMLAudioElement extends HTMLElement {} +interface HTMLBaseElement extends HTMLElement {} +interface HTMLBodyElement extends HTMLElement {} +interface HTMLBRElement extends HTMLElement {} +interface HTMLButtonElement extends HTMLElement {} +interface HTMLCanvasElement extends HTMLElement {} +interface HTMLDataElement extends HTMLElement {} +interface HTMLDataListElement extends HTMLElement {} +interface HTMLDetailsElement extends HTMLElement {} +interface HTMLDialogElement extends HTMLElement {} +interface HTMLDivElement extends HTMLElement {} +interface HTMLDListElement extends HTMLElement {} +interface HTMLEmbedElement extends HTMLElement {} +interface HTMLFieldSetElement extends HTMLElement {} +interface HTMLFormElement extends HTMLElement {} +interface HTMLHeadingElement extends HTMLElement {} +interface HTMLHeadElement extends HTMLElement {} +interface HTMLHRElement extends HTMLElement {} +interface HTMLHtmlElement extends HTMLElement {} +interface HTMLIFrameElement extends HTMLElement {} +interface HTMLImageElement extends HTMLElement {} +interface HTMLInputElement extends HTMLElement {} +interface HTMLModElement extends HTMLElement {} +interface HTMLLabelElement extends HTMLElement {} +interface HTMLLegendElement extends HTMLElement {} +interface HTMLLIElement extends HTMLElement {} +interface HTMLLinkElement extends HTMLElement {} +interface HTMLMapElement extends HTMLElement {} +interface HTMLMetaElement extends HTMLElement {} +interface HTMLMeterElement extends HTMLElement {} +interface HTMLObjectElement extends HTMLElement {} +interface HTMLOListElement extends HTMLElement {} +interface HTMLOptGroupElement extends HTMLElement {} +interface HTMLOptionElement extends HTMLElement {} +interface HTMLOutputElement extends HTMLElement {} +interface HTMLParagraphElement extends HTMLElement {} +interface HTMLParamElement extends HTMLElement {} +interface HTMLPreElement extends HTMLElement {} +interface HTMLProgressElement extends HTMLElement {} +interface HTMLQuoteElement extends HTMLElement {} +interface HTMLSlotElement extends HTMLElement {} +interface HTMLScriptElement extends HTMLElement {} +interface HTMLSelectElement extends HTMLElement {} +interface HTMLSourceElement extends HTMLElement {} +interface HTMLSpanElement extends HTMLElement {} +interface HTMLStyleElement extends HTMLElement {} +interface HTMLTableElement extends HTMLElement {} +interface HTMLTableColElement extends HTMLElement {} +interface HTMLTableDataCellElement extends HTMLElement {} +interface HTMLTableHeaderCellElement extends HTMLElement {} +interface HTMLTableRowElement extends HTMLElement {} +interface HTMLTableSectionElement extends HTMLElement {} +interface HTMLTemplateElement extends HTMLElement {} +interface HTMLTextAreaElement extends HTMLElement {} +interface HTMLTimeElement extends HTMLElement {} +interface HTMLTitleElement extends HTMLElement {} +interface HTMLTrackElement extends HTMLElement {} +interface HTMLUListElement extends HTMLElement {} +interface HTMLVideoElement extends HTMLElement {} +interface HTMLWebViewElement extends HTMLElement {} + +interface SVGElement extends Element {} +interface SVGSVGElement extends SVGElement {} +interface SVGCircleElement extends SVGElement {} +interface SVGClipPathElement extends SVGElement {} +interface SVGDefsElement extends SVGElement {} +interface SVGDescElement extends SVGElement {} +interface SVGEllipseElement extends SVGElement {} +interface SVGFEBlendElement extends SVGElement {} +interface SVGFEColorMatrixElement extends SVGElement {} +interface SVGFEComponentTransferElement extends SVGElement {} +interface SVGFECompositeElement extends SVGElement {} +interface SVGFEConvolveMatrixElement extends SVGElement {} +interface SVGFEDiffuseLightingElement extends SVGElement {} +interface SVGFEDisplacementMapElement extends SVGElement {} +interface SVGFEDistantLightElement extends SVGElement {} +interface SVGFEDropShadowElement extends SVGElement {} +interface SVGFEFloodElement extends SVGElement {} +interface SVGFEFuncAElement extends SVGElement {} +interface SVGFEFuncBElement extends SVGElement {} +interface SVGFEFuncGElement extends SVGElement {} +interface SVGFEFuncRElement extends SVGElement {} +interface SVGFEGaussianBlurElement extends SVGElement {} +interface SVGFEImageElement extends SVGElement {} +interface SVGFEMergeElement extends SVGElement {} +interface SVGFEMergeNodeElement extends SVGElement {} +interface SVGFEMorphologyElement extends SVGElement {} +interface SVGFEOffsetElement extends SVGElement {} +interface SVGFEPointLightElement extends SVGElement {} +interface SVGFESpecularLightingElement extends SVGElement {} +interface SVGFESpotLightElement extends SVGElement {} +interface SVGFETileElement extends SVGElement {} +interface SVGFETurbulenceElement extends SVGElement {} +interface SVGFilterElement extends SVGElement {} +interface SVGForeignObjectElement extends SVGElement {} +interface SVGGElement extends SVGElement {} +interface SVGImageElement extends SVGElement {} +interface SVGLineElement extends SVGElement {} +interface SVGLinearGradientElement extends SVGElement {} +interface SVGMarkerElement extends SVGElement {} +interface SVGMaskElement extends SVGElement {} +interface SVGMetadataElement extends SVGElement {} +interface SVGPathElement extends SVGElement {} +interface SVGPatternElement extends SVGElement {} +interface SVGPolygonElement extends SVGElement {} +interface SVGPolylineElement extends SVGElement {} +interface SVGRadialGradientElement extends SVGElement {} +interface SVGRectElement extends SVGElement {} +interface SVGSetElement extends SVGElement {} +interface SVGStopElement extends SVGElement {} +interface SVGSwitchElement extends SVGElement {} +interface SVGSymbolElement extends SVGElement {} +interface SVGTextElement extends SVGElement {} +interface SVGTextPathElement extends SVGElement {} +interface SVGTSpanElement extends SVGElement {} +interface SVGUseElement extends SVGElement {} +interface SVGViewElement extends SVGElement {} + +interface FormData {} +interface Text {} +interface TouchList {} +interface WebGLRenderingContext {} +interface WebGL2RenderingContext {} + +interface TrustedHTML {} + +interface Blob {} +interface MediaStream {} +interface MediaSource {} diff --git a/node_modules/@types/react/index.d.ts b/node_modules/@types/react/index.d.ts new file mode 100644 index 00000000..403c8ec5 --- /dev/null +++ b/node_modules/@types/react/index.d.ts @@ -0,0 +1,4252 @@ +// NOTE: Users of the `experimental` builds of React should add a reference +// to 'react/experimental' in their project. See experimental.d.ts's top comment +// for reference and documentation on how exactly to do it. + +/// + +import * as CSS from "csstype"; + +type NativeAnimationEvent = AnimationEvent; +type NativeClipboardEvent = ClipboardEvent; +type NativeCompositionEvent = CompositionEvent; +type NativeDragEvent = DragEvent; +type NativeFocusEvent = FocusEvent; +type NativeInputEvent = InputEvent; +type NativeKeyboardEvent = KeyboardEvent; +type NativeMouseEvent = MouseEvent; +type NativeTouchEvent = TouchEvent; +type NativePointerEvent = PointerEvent; +type NativeToggleEvent = ToggleEvent; +type NativeTransitionEvent = TransitionEvent; +type NativeUIEvent = UIEvent; +type NativeWheelEvent = WheelEvent; + +/** + * Used to represent DOM API's where users can either pass + * true or false as a boolean or as its equivalent strings. + */ +type Booleanish = boolean | "true" | "false"; + +/** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin MDN} + */ +type CrossOrigin = "anonymous" | "use-credentials" | "" | undefined; + +declare const UNDEFINED_VOID_ONLY: unique symbol; + +/** + * @internal Use `Awaited` instead + */ +// Helper type to enable `Awaited`. +// Must be a copy of the non-thenables of `ReactNode`. +type AwaitedReactNode = + | React.ReactElement + | string + | number + | bigint + | Iterable + | React.ReactPortal + | boolean + | null + | undefined + | React.DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[ + keyof React.DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES + ]; + +/** + * The function returned from an effect passed to {@link React.useEffect useEffect}, + * which can be used to clean up the effect when the component unmounts. + * + * @see {@link https://react.dev/reference/react/useEffect React Docs} + */ +type Destructor = () => void | { [UNDEFINED_VOID_ONLY]: never }; +type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never }; + +// eslint-disable-next-line @definitelytyped/export-just-namespace +export = React; +export as namespace React; + +declare namespace React { + // + // React Elements + // ---------------------------------------------------------------------- + + /** + * Used to retrieve the possible components which accept a given set of props. + * + * Can be passed no type parameters to get a union of all possible components + * and tags. + * + * Is a superset of {@link ComponentType}. + * + * @template P The props to match against. If not passed, defaults to any. + * @template Tag An optional tag to match against. If not passed, attempts to match against all possible tags. + * + * @example + * + * ```tsx + * // All components and tags (img, embed etc.) + * // which accept `src` + * type SrcComponents = ElementType<{ src: any }>; + * ``` + * + * @example + * + * ```tsx + * // All components + * type AllComponents = ElementType; + * ``` + * + * @example + * + * ```tsx + * // All custom components which match `src`, and tags which + * // match `src`, narrowed down to just `audio` and `embed` + * type SrcComponents = ElementType<{ src: any }, 'audio' | 'embed'>; + * ``` + */ + type ElementType

= + | { [K in Tag]: P extends JSX.IntrinsicElements[K] ? K : never }[Tag] + | ComponentType

; + + /** + * Represents any user-defined component, either as a function or a class. + * + * Similar to {@link JSXElementConstructor}, but with extra properties like + * {@link FunctionComponent.defaultProps defaultProps }. + * + * @template P The props the component accepts. + * + * @see {@link ComponentClass} + * @see {@link FunctionComponent} + */ + type ComponentType

= ComponentClass

| FunctionComponent

; + + /** + * Represents any user-defined component, either as a function or a class. + * + * Similar to {@link ComponentType}, but without extra properties like + * {@link FunctionComponent.defaultProps defaultProps }. + * + * @template P The props the component accepts. + */ + type JSXElementConstructor

= + | (( + props: P, + ) => ReactNode | Promise) + // constructor signature must match React.Component + | (new(props: P, context: any) => Component); + + /** + * Created by {@link createRef}, or {@link useRef} when passed `null`. + * + * @template T The type of the ref's value. + * + * @example + * + * ```tsx + * const ref = createRef(); + * + * ref.current = document.createElement('div'); // Error + * ``` + */ + interface RefObject { + /** + * The current value of the ref. + */ + current: T; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES { + } + /** + * A callback fired whenever the ref's value changes. + * + * @template T The type of the ref's value. + * + * @see {@link https://react.dev/reference/react-dom/components/common#ref-callback React Docs} + * + * @example + * + * ```tsx + *

console.log(node)} /> + * ``` + */ + type RefCallback = { + bivarianceHack( + instance: T | null, + ): + | void + | (() => VoidOrUndefinedOnly) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES + ]; + }["bivarianceHack"]; + + /** + * A union type of all possible shapes for React refs. + * + * @see {@link RefCallback} + * @see {@link RefObject} + */ + + type Ref = RefCallback | RefObject | null; + /** + * @deprecated Use `Ref` instead. String refs are no longer supported. + * If you're typing a library with support for React versions with string refs, use `RefAttributes['ref']` instead. + */ + type LegacyRef = Ref; + /** + * @deprecated Use `ComponentRef` instead + * + * Retrieves the type of the 'ref' prop for a given component type or tag name. + * + * @template C The component type. + * + * @example + * + * ```tsx + * type MyComponentRef = React.ElementRef; + * ``` + * + * @example + * + * ```tsx + * type DivRef = React.ElementRef<'div'>; + * ``` + */ + type ElementRef< + C extends + | ForwardRefExoticComponent + | { new(props: any, context: any): Component } + | ((props: any) => ReactNode) + | keyof JSX.IntrinsicElements, + > = ComponentRef; + + type ComponentState = any; + + /** + * A value which uniquely identifies a node among items in an array. + * + * @see {@link https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key React Docs} + */ + type Key = string | number | bigint; + + /** + * @internal The props any component can receive. + * You don't have to add this type. All components automatically accept these props. + * ```tsx + * const Component = () =>
; + * + * ``` + * + * WARNING: The implementation of a component will never have access to these attributes. + * The following example would be incorrect usage because {@link Component} would never have access to `key`: + * ```tsx + * const Component = (props: React.Attributes) => props.key; + * ``` + */ + interface Attributes { + key?: Key | null | undefined; + } + /** + * The props any component accepting refs can receive. + * Class components, built-in browser components (e.g. `div`) and forwardRef components can receive refs and automatically accept these props. + * ```tsx + * const Component = forwardRef(() =>
); + * console.log(current)} /> + * ``` + * + * You only need this type if you manually author the types of props that need to be compatible with legacy refs. + * ```tsx + * interface Props extends React.RefAttributes {} + * declare const Component: React.FunctionComponent; + * ``` + * + * Otherwise it's simpler to directly use {@link Ref} since you can safely use the + * props type to describe to props that a consumer can pass to the component + * as well as describing the props the implementation of a component "sees". + * {@link RefAttributes} is generally not safe to describe both consumer and seen props. + * + * ```tsx + * interface Props extends { + * ref?: React.Ref | undefined; + * } + * declare const Component: React.FunctionComponent; + * ``` + * + * WARNING: The implementation of a component will not have access to the same type in versions of React supporting string refs. + * The following example would be incorrect usage because {@link Component} would never have access to a `ref` with type `string` + * ```tsx + * const Component = (props: React.RefAttributes) => props.ref; + * ``` + */ + interface RefAttributes extends Attributes { + /** + * Allows getting a ref to the component instance. + * Once the component unmounts, React will set `ref.current` to `null` + * (or call the ref with `null` if you passed a callback ref). + * + * @see {@link https://react.dev/learn/referencing-values-with-refs#refs-and-the-dom React Docs} + */ + ref?: Ref | undefined; + } + + /** + * Represents the built-in attributes available to class components. + */ + interface ClassAttributes extends RefAttributes { + } + + /** + * Represents a JSX element. + * + * Where {@link ReactNode} represents everything that can be rendered, `ReactElement` + * only represents JSX. + * + * @template P The type of the props object + * @template T The type of the component or tag + * + * @example + * + * ```tsx + * const element: ReactElement =
; + * ``` + */ + interface ReactElement< + P = unknown, + T extends string | JSXElementConstructor = string | JSXElementConstructor, + > { + type: T; + props: P; + key: string | null; + } + + /** + * @deprecated + */ + interface ReactComponentElement< + T extends keyof JSX.IntrinsicElements | JSXElementConstructor, + P = Pick, Exclude, "key" | "ref">>, + > extends ReactElement> {} + + /** + * @deprecated Use `ReactElement>` + */ + interface FunctionComponentElement

extends ReactElement> { + /** + * @deprecated Use `element.props.ref` instead. + */ + ref?: ("ref" extends keyof P ? P extends { ref?: infer R | undefined } ? R : never : never) | undefined; + } + + /** + * @deprecated Use `ReactElement>` + */ + type CElement> = ComponentElement; + /** + * @deprecated Use `ReactElement>` + */ + interface ComponentElement> extends ReactElement> { + /** + * @deprecated Use `element.props.ref` instead. + */ + ref?: Ref | undefined; + } + + /** + * @deprecated Use {@link ComponentElement} instead. + */ + type ClassicElement

= CElement>; + + // string fallback for custom web-components + /** + * @deprecated Use `ReactElement` + */ + interface DOMElement

| SVGAttributes, T extends Element> + extends ReactElement + { + /** + * @deprecated Use `element.props.ref` instead. + */ + ref: Ref; + } + + // ReactHTML for ReactHTMLElement + interface ReactHTMLElement extends DetailedReactHTMLElement, T> {} + + interface DetailedReactHTMLElement

, T extends HTMLElement> extends DOMElement { + type: HTMLElementType; + } + + // ReactSVG for ReactSVGElement + interface ReactSVGElement extends DOMElement, SVGElement> { + type: SVGElementType; + } + + interface ReactPortal extends ReactElement { + children: ReactNode; + } + + /** + * Different release channels declare additional types of ReactNode this particular release channel accepts. + * App or library types should never augment this interface. + */ + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES {} + + /** + * Represents all of the things React can render. + * + * Where {@link ReactElement} only represents JSX, `ReactNode` represents everything that can be rendered. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/reactnode/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Typing children + * type Props = { children: ReactNode } + * + * const Component = ({ children }: Props) =>

{children}
+ * + * hello + * ``` + * + * @example + * + * ```tsx + * // Typing a custom element + * type Props = { customElement: ReactNode } + * + * const Component = ({ customElement }: Props) =>
{customElement}
+ * + * hello
} /> + * ``` + */ + // non-thenables need to be kept in sync with AwaitedReactNode + type ReactNode = + | ReactElement + | string + | number + | bigint + | Iterable + | ReactPortal + | boolean + | null + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES + ] + | Promise; + + // + // Top Level API + // ---------------------------------------------------------------------- + + // DOM Elements + // TODO: generalize this to everything in `keyof ReactHTML`, not just "input" + function createElement( + type: "input", + props?: InputHTMLAttributes & ClassAttributes | null, + ...children: ReactNode[] + ): DetailedReactHTMLElement, HTMLInputElement>; + function createElement

, T extends HTMLElement>( + type: HTMLElementType, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): DetailedReactHTMLElement; + function createElement

, T extends SVGElement>( + type: SVGElementType, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): ReactSVGElement; + function createElement

, T extends Element>( + type: string, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): DOMElement; + + // Custom components + + function createElement

( + type: FunctionComponent

, + props?: Attributes & P | null, + ...children: ReactNode[] + ): FunctionComponentElement

; + function createElement

, C extends ComponentClass

>( + type: ClassType, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): CElement; + function createElement

( + type: FunctionComponent

| ComponentClass

| string, + props?: Attributes & P | null, + ...children: ReactNode[] + ): ReactElement

; + + // DOM Elements + // ReactHTMLElement + function cloneElement

, T extends HTMLElement>( + element: DetailedReactHTMLElement, + props?: P, + ...children: ReactNode[] + ): DetailedReactHTMLElement; + // ReactHTMLElement, less specific + function cloneElement

, T extends HTMLElement>( + element: ReactHTMLElement, + props?: P, + ...children: ReactNode[] + ): ReactHTMLElement; + // SVGElement + function cloneElement

, T extends SVGElement>( + element: ReactSVGElement, + props?: P, + ...children: ReactNode[] + ): ReactSVGElement; + // DOM Element (has to be the last, because type checking stops at first overload that fits) + function cloneElement

, T extends Element>( + element: DOMElement, + props?: DOMAttributes & P, + ...children: ReactNode[] + ): DOMElement; + + // Custom components + function cloneElement

( + element: FunctionComponentElement

, + props?: Partial

& Attributes, + ...children: ReactNode[] + ): FunctionComponentElement

; + function cloneElement>( + element: CElement, + props?: Partial

& ClassAttributes, + ...children: ReactNode[] + ): CElement; + function cloneElement

( + element: ReactElement

, + props?: Partial

& Attributes, + ...children: ReactNode[] + ): ReactElement

; + + /** + * Describes the props accepted by a Context {@link Provider}. + * + * @template T The type of the value the context provides. + */ + interface ProviderProps { + value: T; + children?: ReactNode | undefined; + } + + /** + * Describes the props accepted by a Context {@link Consumer}. + * + * @template T The type of the value the context provides. + */ + interface ConsumerProps { + children: (value: T) => ReactNode; + } + + /** + * An object masquerading as a component. These are created by functions + * like {@link forwardRef}, {@link memo}, and {@link createContext}. + * + * In order to make TypeScript work, we pretend that they are normal + * components. + * + * But they are, in fact, not callable - instead, they are objects which + * are treated specially by the renderer. + * + * @template P The props the component accepts. + */ + interface ExoticComponent

{ + (props: P): ReactNode; + readonly $$typeof: symbol; + } + + /** + * An {@link ExoticComponent} with a `displayName` property applied to it. + * + * @template P The props the component accepts. + */ + interface NamedExoticComponent

extends ExoticComponent

{ + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * An {@link ExoticComponent} with a `propTypes` property applied to it. + * + * @template P The props the component accepts. + */ + interface ProviderExoticComponent

extends ExoticComponent

{ + } + + /** + * Used to retrieve the type of a context object from a {@link Context}. + * + * @template C The context object. + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const MyContext = createContext({ foo: 'bar' }); + * + * type ContextType = ContextType; + * // ContextType = { foo: string } + * ``` + */ + type ContextType> = C extends Context ? T : never; + + /** + * Wraps your components to specify the value of this context for all components inside. + * + * @see {@link https://react.dev/reference/react/createContext#provider React Docs} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * + * function App() { + * return ( + * + * + * + * ); + * } + * ``` + */ + type Provider = ProviderExoticComponent>; + + /** + * The old way to read context, before {@link useContext} existed. + * + * @see {@link https://react.dev/reference/react/createContext#consumer React Docs} + * + * @example + * + * ```tsx + * import { UserContext } from './user-context'; + * + * function Avatar() { + * return ( + * + * {user => {user.name}} + * + * ); + * } + * ``` + */ + type Consumer = ExoticComponent>; + + /** + * Context lets components pass information deep down without explicitly + * passing props. + * + * Created from {@link createContext} + * + * @see {@link https://react.dev/learn/passing-data-deeply-with-context React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * ``` + */ + interface Context extends Provider { + Provider: Provider; + Consumer: Consumer; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * Lets you create a {@link Context} that components can provide or read. + * + * @param defaultValue The value you want the context to have when there is no matching + * {@link Provider} in the tree above the component reading the context. This is meant + * as a "last resort" fallback. + * + * @see {@link https://react.dev/reference/react/createContext#reference React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * function App() { + * return ( + * + * + * + * ); + * } + * ``` + */ + function createContext( + // If you thought this should be optional, see + // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106 + defaultValue: T, + ): Context; + + function isValidElement

(object: {} | null | undefined): object is ReactElement

; + + const Children: { + map( + children: C | readonly C[], + fn: (child: C, index: number) => T, + ): C extends null | undefined ? C : Array>; + forEach(children: C | readonly C[], fn: (child: C, index: number) => void): void; + count(children: any): number; + only(children: C): C extends any[] ? never : C; + toArray(children: ReactNode | ReactNode[]): Array>; + }; + + export interface FragmentProps { + children?: React.ReactNode; + } + /** + * Lets you group elements without a wrapper node. + * + * @see {@link https://react.dev/reference/react/Fragment React Docs} + * + * @example + * + * ```tsx + * import { Fragment } from 'react'; + * + * + * Hello + * World + * + * ``` + * + * @example + * + * ```tsx + * // Using the <> shorthand syntax: + * + * <> + * Hello + * World + * + * ``` + */ + const Fragment: ExoticComponent; + + /** + * Lets you find common bugs in your components early during development. + * + * @see {@link https://react.dev/reference/react/StrictMode React Docs} + * + * @example + * + * ```tsx + * import { StrictMode } from 'react'; + * + * + * + * + * ``` + */ + const StrictMode: ExoticComponent<{ children?: ReactNode | undefined }>; + + /** + * The props accepted by {@link Suspense}. + * + * @see {@link https://react.dev/reference/react/Suspense React Docs} + */ + interface SuspenseProps { + children?: ReactNode | undefined; + + /** A fallback react tree to show when a Suspense child (like React.lazy) suspends */ + fallback?: ReactNode; + + /** + * A name for this Suspense boundary for instrumentation purposes. + * The name will help identify this boundary in React DevTools. + */ + name?: string | undefined; + } + + /** + * Lets you display a fallback until its children have finished loading. + * + * @see {@link https://react.dev/reference/react/Suspense React Docs} + * + * @example + * + * ```tsx + * import { Suspense } from 'react'; + * + * }> + * + * + * ``` + */ + const Suspense: ExoticComponent; + const version: string; + + /** + * The callback passed to {@link ProfilerProps.onRender}. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + type ProfilerOnRenderCallback = ( + /** + * The string id prop of the {@link Profiler} tree that has just committed. This lets + * you identify which part of the tree was committed if you are using multiple + * profilers. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + id: string, + /** + * This lets you know whether the tree has just been mounted for the first time + * or re-rendered due to a change in props, state, or hooks. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + phase: "mount" | "update" | "nested-update", + /** + * The number of milliseconds spent rendering the {@link Profiler} and its descendants + * for the current update. This indicates how well the subtree makes use of + * memoization (e.g. {@link memo} and {@link useMemo}). Ideally this value should decrease + * significantly after the initial mount as many of the descendants will only need to + * re-render if their specific props change. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + actualDuration: number, + /** + * The number of milliseconds estimating how much time it would take to re-render the entire + * {@link Profiler} subtree without any optimizations. It is calculated by summing up the most + * recent render durations of each component in the tree. This value estimates a worst-case + * cost of rendering (e.g. the initial mount or a tree with no memoization). Compare + * {@link actualDuration} against it to see if memoization is working. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + baseDuration: number, + /** + * A numeric timestamp for when React began rendering the current update. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + startTime: number, + /** + * A numeric timestamp for when React committed the current update. This value is shared + * between all profilers in a commit, enabling them to be grouped if desirable. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + commitTime: number, + ) => void; + + /** + * The props accepted by {@link Profiler}. + * + * @see {@link https://react.dev/reference/react/Profiler React Docs} + */ + interface ProfilerProps { + children?: ReactNode | undefined; + id: string; + onRender: ProfilerOnRenderCallback; + } + + /** + * Lets you measure rendering performance of a React tree programmatically. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + * + * @example + * + * ```tsx + * + * + * + * ``` + */ + const Profiler: ExoticComponent; + + // + // Component API + // ---------------------------------------------------------------------- + + type ReactInstance = Component | Element; + + // Base component for plain JS classes + interface Component

extends ComponentLifecycle {} + class Component { + /** + * If set, `this.context` will be set at runtime to the current value of the given Context. + * + * @example + * + * ```ts + * type MyContext = number + * const Ctx = React.createContext(0) + * + * class Foo extends React.Component { + * static contextType = Ctx + * context!: React.ContextType + * render () { + * return <>My context's value: {this.context}; + * } + * } + * ``` + * + * @see {@link https://react.dev/reference/react/Component#static-contexttype} + */ + static contextType?: Context | undefined; + + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + static propTypes?: any; + + /** + * If using React Context, re-declare this in your class to be the + * `React.ContextType` of your `static contextType`. + * Should be used with type annotation or static contextType. + * + * @example + * ```ts + * static contextType = MyContext + * // For TS pre-3.7: + * context!: React.ContextType + * // For TS 3.7 and above: + * declare context: React.ContextType + * ``` + * + * @see {@link https://react.dev/reference/react/Component#context React Docs} + */ + context: unknown; + + // Keep in sync with constructor signature of JSXElementConstructor and ComponentClass. + constructor(props: P); + /** + * @param props + * @param context value of the parent {@link https://react.dev/reference/react/Component#context Context} specified + * in `contextType`. + */ + // TODO: Ideally we'd infer the constructor signatur from `contextType`. + // Might be hard to ship without breaking existing code. + constructor(props: P, context: any); + + // We MUST keep setState() as a unified signature because it allows proper checking of the method return type. + // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257 + // Also, the ` | S` allows intellisense to not be dumbisense + setState( + state: ((prevState: Readonly, props: Readonly

) => Pick | S | null) | (Pick | S | null), + callback?: () => void, + ): void; + + forceUpdate(callback?: () => void): void; + render(): ReactNode; + + readonly props: Readonly

; + state: Readonly; + } + + class PureComponent

extends Component {} + + /** + * @deprecated Use `ClassicComponent` from `create-react-class` + * + * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs} + * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm} + */ + interface ClassicComponent

extends Component { + replaceState(nextState: S, callback?: () => void): void; + isMounted(): boolean; + getInitialState?(): S; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + /** + * Represents the type of a function component. Can optionally + * receive a type argument that represents the props the component + * receives. + * + * @template P The props the component accepts. + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet} + * @alias for {@link FunctionComponent} + * + * @example + * + * ```tsx + * // With props: + * type Props = { name: string } + * + * const MyComponent: FC = (props) => { + * return

{props.name}
+ * } + * ``` + * + * @example + * + * ```tsx + * // Without props: + * const MyComponentWithoutProps: FC = () => { + * return
MyComponentWithoutProps
+ * } + * ``` + */ + type FC

= FunctionComponent

; + + /** + * Represents the type of a function component. Can optionally + * receive a type argument that represents the props the component + * accepts. + * + * @template P The props the component accepts. + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // With props: + * type Props = { name: string } + * + * const MyComponent: FunctionComponent = (props) => { + * return

{props.name}
+ * } + * ``` + * + * @example + * + * ```tsx + * // Without props: + * const MyComponentWithoutProps: FunctionComponent = () => { + * return
MyComponentWithoutProps
+ * } + * ``` + */ + interface FunctionComponent

{ + (props: P): ReactNode | Promise; + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + propTypes?: any; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + * + * @example + * + * ```tsx + * + * const MyComponent: FC = () => { + * return

Hello!
+ * } + * + * MyComponent.displayName = 'MyAwesomeComponent' + * ``` + */ + displayName?: string | undefined; + } + + /** + * The type of the ref received by a {@link ForwardRefRenderFunction}. + * + * @see {@link ForwardRefRenderFunction} + */ + // Making T nullable is assuming the refs will be managed by React or the component impl will write it somewhere else. + // But this isn't necessarily true. We haven't heard complains about it yet and hopefully `forwardRef` is removed from React before we do. + type ForwardedRef = ((instance: T | null) => void) | RefObject | null; + + /** + * The type of the function passed to {@link forwardRef}. This is considered different + * to a normal {@link FunctionComponent} because it receives an additional argument, + * + * @param props Props passed to the component, if any. + * @param ref A ref forwarded to the component of type {@link ForwardedRef}. + * + * @template T The type of the forwarded ref. + * @template P The type of the props the component accepts. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet} + * @see {@link forwardRef} + */ + interface ForwardRefRenderFunction { + (props: P, ref: ForwardedRef): ReactNode; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * Will show `ForwardRef(${Component.displayName || Component.name})` + * in devtools by default, but can be given its own specific name. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + propTypes?: any; + } + + /** + * Represents a component class in React. + * + * @template P The props the component accepts. + * @template S The internal state of the component. + */ + interface ComponentClass

extends StaticLifecycle { + // constructor signature must match React.Component + new( + props: P, + /** + * Value of the parent {@link https://react.dev/reference/react/Component#context Context} specified + * in `contextType`. + */ + context?: any, + ): Component; + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + propTypes?: any; + contextType?: Context | undefined; + defaultProps?: Partial

| undefined; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * @deprecated Use `ClassicComponentClass` from `create-react-class` + * + * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs} + * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm} + */ + interface ClassicComponentClass

extends ComponentClass

{ + new(props: P): ClassicComponent; + getDefaultProps?(): P; + } + + /** + * Used in {@link createElement} and {@link createFactory} to represent + * a class. + * + * An intersection type is used to infer multiple type parameters from + * a single argument, which is useful for many top-level API defs. + * See {@link https://github.com/Microsoft/TypeScript/issues/7234 this GitHub issue} + * for more info. + */ + type ClassType, C extends ComponentClass

> = + & C + & (new(props: P, context: any) => T); + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + // This should actually be something like `Lifecycle | DeprecatedLifecycle`, + // as React will _not_ call the deprecated lifecycle methods if any of the new lifecycle + // methods are present. + interface ComponentLifecycle extends NewLifecycle, DeprecatedLifecycle { + /** + * Called immediately after a component is mounted. Setting state here will trigger re-rendering. + */ + componentDidMount?(): void; + /** + * Called to determine whether the change in props and state should trigger a re-render. + * + * `Component` always returns true. + * `PureComponent` implements a shallow comparison on props and state and returns true if any + * props or states have changed. + * + * If false is returned, {@link Component.render}, `componentWillUpdate` + * and `componentDidUpdate` will not be called. + */ + shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; + /** + * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as + * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`. + */ + componentWillUnmount?(): void; + /** + * Catches exceptions generated in descendant components. Unhandled exceptions will cause + * the entire component tree to unmount. + */ + componentDidCatch?(error: Error, errorInfo: ErrorInfo): void; + } + + // Unfortunately, we have no way of declaring that the component constructor must implement this + interface StaticLifecycle { + getDerivedStateFromProps?: GetDerivedStateFromProps | undefined; + getDerivedStateFromError?: GetDerivedStateFromError | undefined; + } + + type GetDerivedStateFromProps = + /** + * Returns an update to a component's state based on its new props and old state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (nextProps: Readonly

, prevState: S) => Partial | null; + + type GetDerivedStateFromError = + /** + * This lifecycle is invoked after an error has been thrown by a descendant component. + * It receives the error that was thrown as a parameter and should return a value to update state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (error: any) => Partial | null; + + // This should be "infer SS" but can't use it yet + interface NewLifecycle { + /** + * Runs before React applies the result of {@link Component.render render} to the document, and + * returns an object to be given to {@link componentDidUpdate}. Useful for saving + * things such as scroll position before {@link Component.render render} causes changes to it. + * + * Note: the presence of this method prevents any of the deprecated + * lifecycle events from running. + */ + getSnapshotBeforeUpdate?(prevProps: Readonly

, prevState: Readonly): SS | null; + /** + * Called immediately after updating occurs. Not called for the initial render. + * + * The snapshot is only present if {@link getSnapshotBeforeUpdate} is present and returns non-null. + */ + componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, snapshot?: SS): void; + } + + interface DeprecatedLifecycle { + /** + * Called immediately before mounting occurs, and before {@link Component.render}. + * Avoid introducing any side-effects or subscriptions in this method. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillMount?(): void; + /** + * Called immediately before mounting occurs, and before {@link Component.render}. + * Avoid introducing any side-effects or subscriptions in this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillMount?(): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling {@link Component.setState} generally does not trigger this method. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling {@link Component.setState} generally does not trigger this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call {@link Component.setState} here. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call {@link Component.setState} here. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + } + + function createRef(): RefObject; + + /** + * The type of the component returned from {@link forwardRef}. + * + * @template P The props the component accepts, if any. + * + * @see {@link ExoticComponent} + */ + interface ForwardRefExoticComponent

extends NamedExoticComponent

{ + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + propTypes?: any; + } + + /** + * Lets your component expose a DOM node to a parent component + * using a ref. + * + * @see {@link https://react.dev/reference/react/forwardRef React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet} + * + * @param render See the {@link ForwardRefRenderFunction}. + * + * @template T The type of the DOM node. + * @template P The props the component accepts, if any. + * + * @example + * + * ```tsx + * interface Props { + * children?: ReactNode; + * type: "submit" | "button"; + * } + * + * export const FancyButton = forwardRef((props, ref) => ( + * + * )); + * ``` + */ + function forwardRef( + render: ForwardRefRenderFunction>, + ): ForwardRefExoticComponent & RefAttributes>; + + /** + * Omits the 'ref' attribute from the given props object. + * + * @template Props The props object type. + */ + type PropsWithoutRef = + // Omit would not be sufficient for this. We'd like to avoid unnecessary mapping and need a distributive conditional to support unions. + // see: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types + // https://github.com/Microsoft/TypeScript/issues/28339 + Props extends any ? ("ref" extends keyof Props ? Omit : Props) : Props; + /** + * Ensures that the props do not include string ref, which cannot be forwarded + * @deprecated Use `Props` directly. `PropsWithRef` is just an alias for `Props` + */ + type PropsWithRef = Props; + + type PropsWithChildren

= P & { children?: ReactNode | undefined }; + + /** + * Used to retrieve the props a component accepts. Can either be passed a string, + * indicating a DOM element (e.g. 'div', 'span', etc.) or the type of a React + * component. + * + * It's usually better to use {@link ComponentPropsWithRef} or {@link ComponentPropsWithoutRef} + * instead of this type, as they let you be explicit about whether or not to include + * the `ref` prop. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentProps<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>

; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentProps = React.ComponentProps; + * ``` + */ + type ComponentProps> = T extends + JSXElementConstructor ? Props + : T extends keyof JSX.IntrinsicElements ? JSX.IntrinsicElements[T] + : {}; + + /** + * Used to retrieve the props a component accepts with its ref. Can either be + * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the + * type of a React component. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentPropsWithRef<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>
; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithRef = React.ComponentPropsWithRef; + * ``` + */ + type ComponentPropsWithRef = T extends JSXElementConstructor + // If it's a class i.e. newable we're dealing with a class component + ? T extends abstract new(args: any) => any ? PropsWithoutRef & RefAttributes> + : Props + : ComponentProps; + /** + * Used to retrieve the props a custom component accepts with its ref. + * + * Unlike {@link ComponentPropsWithRef}, this only works with custom + * components, i.e. components you define yourself. This is to improve + * type-checking performance. + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>
; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithRef = React.CustomComponentPropsWithRef; + * ``` + */ + type CustomComponentPropsWithRef = T extends JSXElementConstructor + // If it's a class i.e. newable we're dealing with a class component + ? T extends abstract new(args: any) => any ? PropsWithoutRef & RefAttributes> + : Props + : never; + + /** + * Used to retrieve the props a component accepts without its ref. Can either be + * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the + * type of a React component. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentPropsWithoutRef<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>
; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithoutRef = React.ComponentPropsWithoutRef; + * ``` + */ + type ComponentPropsWithoutRef = PropsWithoutRef>; + + /** + * Retrieves the type of the 'ref' prop for a given component type or tag name. + * + * @template C The component type. + * + * @example + * + * ```tsx + * type MyComponentRef = React.ComponentRef; + * ``` + * + * @example + * + * ```tsx + * type DivRef = React.ComponentRef<'div'>; + * ``` + */ + type ComponentRef = ComponentPropsWithRef extends RefAttributes ? Method + : never; + + // will show `Memo(${Component.displayName || Component.name})` in devtools by default, + // but can be given its own specific name + type MemoExoticComponent> = NamedExoticComponent> & { + readonly type: T; + }; + + /** + * Lets you skip re-rendering a component when its props are unchanged. + * + * @see {@link https://react.dev/reference/react/memo React Docs} + * + * @param Component The component to memoize. + * @param propsAreEqual A function that will be used to determine if the props have changed. + * + * @example + * + * ```tsx + * import { memo } from 'react'; + * + * const SomeComponent = memo(function SomeComponent(props: { foo: string }) { + * // ... + * }); + * ``` + */ + function memo

( + Component: FunctionComponent

, + propsAreEqual?: (prevProps: Readonly

, nextProps: Readonly

) => boolean, + ): NamedExoticComponent

; + function memo>( + Component: T, + propsAreEqual?: (prevProps: Readonly>, nextProps: Readonly>) => boolean, + ): MemoExoticComponent; + + interface LazyExoticComponent> + extends ExoticComponent> + { + readonly _result: T; + } + + /** + * Lets you defer loading a component’s code until it is rendered for the first time. + * + * @see {@link https://react.dev/reference/react/lazy React Docs} + * + * @param load A function that returns a `Promise` or another thenable (a `Promise`-like object with a + * then method). React will not call `load` until the first time you attempt to render the returned + * component. After React first calls load, it will wait for it to resolve, and then render the + * resolved value’s `.default` as a React component. Both the returned `Promise` and the `Promise`’s + * resolved value will be cached, so React will not call load more than once. If the `Promise` rejects, + * React will throw the rejection reason for the nearest Error Boundary to handle. + * + * @example + * + * ```tsx + * import { lazy } from 'react'; + * + * const MarkdownPreview = lazy(() => import('./MarkdownPreview.js')); + * ``` + */ + function lazy>( + load: () => Promise<{ default: T }>, + ): LazyExoticComponent; + + // + // React Hooks + // ---------------------------------------------------------------------- + + /** + * The instruction passed to a {@link Dispatch} function in {@link useState} + * to tell React what the next value of the {@link useState} should be. + * + * Often found wrapped in {@link Dispatch}. + * + * @template S The type of the state. + * + * @example + * + * ```tsx + * // This return type correctly represents the type of + * // `setCount` in the example below. + * const useCustomState = (): Dispatch> => { + * const [count, setCount] = useState(0); + * + * return setCount; + * } + * ``` + */ + type SetStateAction = S | ((prevState: S) => S); + + /** + * A function that can be used to update the state of a {@link useState} + * or {@link useReducer} hook. + */ + type Dispatch = (value: A) => void; + /** + * A {@link Dispatch} function can sometimes be called without any arguments. + */ + type DispatchWithoutAction = () => void; + // Limit the reducer to accept only 0 or 1 action arguments + // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type + type AnyActionArg = [] | [any]; + // Get the dispatch type from the reducer arguments (captures optional action argument correctly) + type ActionDispatch = (...args: ActionArg) => void; + // Unlike redux, the actions _can_ be anything + type Reducer = (prevState: S, action: A) => S; + // If useReducer accepts a reducer without action, dispatch may be called without any parameters. + type ReducerWithoutAction = (prevState: S) => S; + // types used to try and prevent the compiler from reducing S + // to a supertype common with the second argument to useReducer() + type ReducerState> = R extends Reducer ? S : never; + type DependencyList = readonly unknown[]; + + // NOTE: callbacks are _only_ allowed to return either void, or a destructor. + type EffectCallback = () => void | Destructor; + + /** + * @deprecated Use `RefObject` instead. + */ + interface MutableRefObject { + current: T; + } + + // This will technically work if you give a Consumer or Provider but it's deprecated and warns + /** + * Accepts a context object (the value returned from `React.createContext`) and returns the current + * context value, as given by the nearest context provider for the given context. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useContext} + */ + function useContext(context: Context /*, (not public API) observedBits?: number|boolean */): T; + /** + * Returns a stateful value, and a function to update it. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useState} + */ + function useState(initialState: S | (() => S)): [S, Dispatch>]; + // convenience overload when first argument is omitted + /** + * Returns a stateful value, and a function to update it. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useState} + */ + function useState(): [S | undefined, Dispatch>]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + function useReducer( + reducer: (prevState: S, ...args: A) => S, + initialState: S, + ): [S, ActionDispatch]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + function useReducer( + reducer: (prevState: S, ...args: A) => S, + initialArg: I, + init: (i: I) => S, + ): [S, ActionDispatch]; + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T): RefObject; + // convenience overload for refs given as a ref prop as they typically start with a null value + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T | null): RefObject; + // convenience overload for undefined initialValue + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T | undefined): RefObject; + /** + * The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations. + * Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside + * `useLayoutEffect` will be flushed synchronously, before the browser has a chance to paint. + * + * Prefer the standard `useEffect` when possible to avoid blocking visual updates. + * + * If you’re migrating code from a class component, `useLayoutEffect` fires in the same phase as + * `componentDidMount` and `componentDidUpdate`. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useLayoutEffect} + */ + function useLayoutEffect(effect: EffectCallback, deps?: DependencyList): void; + /** + * Accepts a function that contains imperative, possibly effectful code. + * + * @param effect Imperative function that can return a cleanup function + * @param deps If present, effect will only activate if the values in the list change. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useEffect} + */ + function useEffect(effect: EffectCallback, deps?: DependencyList): void; + // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref + /** + * `useImperativeHandle` customizes the instance value that is exposed to parent components when using + * `ref`. As always, imperative code using refs should be avoided in most cases. + * + * `useImperativeHandle` should be used with `React.forwardRef`. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useImperativeHandle} + */ + function useImperativeHandle(ref: Ref | undefined, init: () => R, deps?: DependencyList): void; + // I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key + // useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y. + /** + * `useCallback` will return a memoized version of the callback that only changes if one of the `inputs` + * has changed. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useCallback} + */ + // A specific function type would not trigger implicit any. + // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/52873#issuecomment-845806435 for a comparison between `Function` and more specific types. + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + function useCallback(callback: T, deps: DependencyList): T; + /** + * `useMemo` will only recompute the memoized value when one of the `deps` has changed. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useMemo} + */ + // allow undefined, but don't make it optional as that is very likely a mistake + function useMemo(factory: () => T, deps: DependencyList): T; + /** + * `useDebugValue` can be used to display a label for custom hooks in React DevTools. + * + * NOTE: We don’t recommend adding debug values to every custom hook. + * It’s most valuable for custom hooks that are part of shared libraries. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useDebugValue} + */ + // the name of the custom hook is itself derived from the function name at runtime: + // it's just the function name without the "use" prefix. + function useDebugValue(value: T, format?: (value: T) => any): void; + + export type TransitionFunction = () => VoidOrUndefinedOnly | Promise; + // strange definition to allow vscode to show documentation on the invocation + export interface TransitionStartFunction { + /** + * State updates caused inside the callback are allowed to be deferred. + * + * **If some state update causes a component to suspend, that state update should be wrapped in a transition.** + * + * @param callback A function which causes state updates that can be deferred. + */ + (callback: TransitionFunction): void; + } + + /** + * Returns a deferred version of the value that may “lag behind” it. + * + * This is commonly used to keep the interface responsive when you have something that renders immediately + * based on user input and something that needs to wait for a data fetch. + * + * A good example of this is a text input. + * + * @param value The value that is going to be deferred + * @param initialValue A value to use during the initial render of a component. If this option is omitted, `useDeferredValue` will not defer during the initial render, because there’s no previous version of `value` that it can render instead. + * + * @see {@link https://react.dev/reference/react/useDeferredValue} + */ + export function useDeferredValue(value: T, initialValue?: T): T; + + /** + * Allows components to avoid undesirable loading states by waiting for content to load + * before transitioning to the next screen. It also allows components to defer slower, + * data fetching updates until subsequent renders so that more crucial updates can be + * rendered immediately. + * + * The `useTransition` hook returns two values in an array. + * + * The first is a boolean, React’s way of informing us whether we’re waiting for the transition to finish. + * The second is a function that takes a callback. We can use it to tell React which state we want to defer. + * + * **If some state update causes a component to suspend, that state update should be wrapped in a transition.** + * + * @see {@link https://react.dev/reference/react/useTransition} + */ + export function useTransition(): [boolean, TransitionStartFunction]; + + /** + * Similar to `useTransition` but allows uses where hooks are not available. + * + * @param callback A function which causes state updates that can be deferred. + */ + export function startTransition(scope: TransitionFunction): void; + + /** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ + // NOTES + // - the order of these signatures matters - typescript will check the signatures in source order. + // If the `() => VoidOrUndefinedOnly` signature is first, it'll erroneously match a Promise returning function for users with + // `strictNullChecks: false`. + // - VoidOrUndefinedOnly is there to forbid any non-void return values for users with `strictNullChecks: true` + // While act does always return Thenable, if a void function is passed, we pretend the return value is also void to not trigger dangling Promise lint rules. + export function act(callback: () => VoidOrUndefinedOnly): void; + export function act(callback: () => T | Promise): Promise; + + export function useId(): string; + + /** + * @param effect Imperative function that can return a cleanup function + * @param deps If present, effect will only activate if the values in the list change. + * + * @see {@link https://github.com/facebook/react/pull/21913} + */ + export function useInsertionEffect(effect: EffectCallback, deps?: DependencyList): void; + + /** + * @param subscribe + * @param getSnapshot + * + * @see {@link https://github.com/reactwg/react-18/discussions/86} + */ + // keep in sync with `useSyncExternalStore` from `use-sync-external-store` + export function useSyncExternalStore( + subscribe: (onStoreChange: () => void) => () => void, + getSnapshot: () => Snapshot, + getServerSnapshot?: () => Snapshot, + ): Snapshot; + + export function useOptimistic( + passthrough: State, + ): [State, (action: State | ((pendingState: State) => State)) => void]; + export function useOptimistic( + passthrough: State, + reducer: (state: State, action: Action) => State, + ): [State, (action: Action) => void]; + + export type Usable = PromiseLike | Context; + + export function use(usable: Usable): T; + + export function useActionState( + action: (state: Awaited) => State | Promise, + initialState: Awaited, + permalink?: string, + ): [state: Awaited, dispatch: () => void, isPending: boolean]; + export function useActionState( + action: (state: Awaited, payload: Payload) => State | Promise, + initialState: Awaited, + permalink?: string, + ): [state: Awaited, dispatch: (payload: Payload) => void, isPending: boolean]; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + export function cache(fn: CachedFunction): CachedFunction; + + /** + * Warning: Only available in development builds. + * + * @see {@link https://react.dev/reference/react/captureOwnerStack Reference docs} + */ + function captureOwnerStack(): string | null; + + // + // Event System + // ---------------------------------------------------------------------- + // TODO: change any to unknown when moving to TS v3 + interface BaseSyntheticEvent { + nativeEvent: E; + currentTarget: C; + target: T; + bubbles: boolean; + cancelable: boolean; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + preventDefault(): void; + isDefaultPrevented(): boolean; + stopPropagation(): void; + isPropagationStopped(): boolean; + persist(): void; + timeStamp: number; + type: string; + } + + /** + * currentTarget - a reference to the element on which the event listener is registered. + * + * target - a reference to the element from which the event was originally dispatched. + * This might be a child element to the element on which the event listener is registered. + * If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11508#issuecomment-256045682 + */ + interface SyntheticEvent extends BaseSyntheticEvent {} + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + } + + interface CompositionEvent extends SyntheticEvent { + data: string; + } + + interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + } + + interface PointerEvent extends MouseEvent { + pointerId: number; + pressure: number; + tangentialPressure: number; + tiltX: number; + tiltY: number; + twist: number; + width: number; + height: number; + pointerType: "mouse" | "pen" | "touch"; + isPrimary: boolean; + } + + interface FocusEvent extends SyntheticEvent { + relatedTarget: (EventTarget & RelatedTarget) | null; + target: EventTarget & Target; + } + + interface FormEvent extends SyntheticEvent { + } + + interface InvalidEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface ChangeEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface InputEvent extends SyntheticEvent { + data: string; + } + + export type ModifierKey = + | "Alt" + | "AltGraph" + | "CapsLock" + | "Control" + | "Fn" + | "FnLock" + | "Hyper" + | "Meta" + | "NumLock" + | "ScrollLock" + | "Shift" + | "Super" + | "Symbol" + | "SymbolLock"; + + interface KeyboardEvent extends UIEvent { + altKey: boolean; + /** @deprecated */ + charCode: number; + ctrlKey: boolean; + code: string; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + /** + * See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values + */ + key: string; + /** @deprecated */ + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + repeat: boolean; + shiftKey: boolean; + /** @deprecated */ + which: number; + } + + interface MouseEvent extends UIEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + metaKey: boolean; + movementX: number; + movementY: number; + pageX: number; + pageY: number; + relatedTarget: EventTarget | null; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends UIEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + metaKey: boolean; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + view: AbstractView; + } + + interface WheelEvent extends MouseEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + } + + interface AnimationEvent extends SyntheticEvent { + animationName: string; + elapsedTime: number; + pseudoElement: string; + } + + interface ToggleEvent extends SyntheticEvent { + oldState: "closed" | "open"; + newState: "closed" | "open"; + } + + interface TransitionEvent extends SyntheticEvent { + elapsedTime: number; + propertyName: string; + pseudoElement: string; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + type EventHandler> = { bivarianceHack(event: E): void }["bivarianceHack"]; + + type ReactEventHandler = EventHandler>; + + type ClipboardEventHandler = EventHandler>; + type CompositionEventHandler = EventHandler>; + type DragEventHandler = EventHandler>; + type FocusEventHandler = EventHandler>; + type FormEventHandler = EventHandler>; + type ChangeEventHandler = EventHandler>; + type InputEventHandler = EventHandler>; + type KeyboardEventHandler = EventHandler>; + type MouseEventHandler = EventHandler>; + type TouchEventHandler = EventHandler>; + type PointerEventHandler = EventHandler>; + type UIEventHandler = EventHandler>; + type WheelEventHandler = EventHandler>; + type AnimationEventHandler = EventHandler>; + type ToggleEventHandler = EventHandler>; + type TransitionEventHandler = EventHandler>; + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + interface HTMLProps extends AllHTMLAttributes, ClassAttributes { + } + + type DetailedHTMLProps, T> = ClassAttributes & E; + + interface SVGProps extends SVGAttributes, ClassAttributes { + } + + interface SVGLineElementAttributes extends SVGProps {} + interface SVGTextElementAttributes extends SVGProps {} + + interface DOMAttributes { + children?: ReactNode | undefined; + dangerouslySetInnerHTML?: { + // Should be InnerHTML['innerHTML']. + // But unfortunately we're mixing renderer-specific type declarations. + __html: string | TrustedHTML; + } | undefined; + + // Clipboard Events + onCopy?: ClipboardEventHandler | undefined; + onCopyCapture?: ClipboardEventHandler | undefined; + onCut?: ClipboardEventHandler | undefined; + onCutCapture?: ClipboardEventHandler | undefined; + onPaste?: ClipboardEventHandler | undefined; + onPasteCapture?: ClipboardEventHandler | undefined; + + // Composition Events + onCompositionEnd?: CompositionEventHandler | undefined; + onCompositionEndCapture?: CompositionEventHandler | undefined; + onCompositionStart?: CompositionEventHandler | undefined; + onCompositionStartCapture?: CompositionEventHandler | undefined; + onCompositionUpdate?: CompositionEventHandler | undefined; + onCompositionUpdateCapture?: CompositionEventHandler | undefined; + + // Focus Events + onFocus?: FocusEventHandler | undefined; + onFocusCapture?: FocusEventHandler | undefined; + onBlur?: FocusEventHandler | undefined; + onBlurCapture?: FocusEventHandler | undefined; + + // Form Events + onChange?: FormEventHandler | undefined; + onChangeCapture?: FormEventHandler | undefined; + onBeforeInput?: InputEventHandler | undefined; + onBeforeInputCapture?: FormEventHandler | undefined; + onInput?: FormEventHandler | undefined; + onInputCapture?: FormEventHandler | undefined; + onReset?: FormEventHandler | undefined; + onResetCapture?: FormEventHandler | undefined; + onSubmit?: FormEventHandler | undefined; + onSubmitCapture?: FormEventHandler | undefined; + onInvalid?: FormEventHandler | undefined; + onInvalidCapture?: FormEventHandler | undefined; + + // Image Events + onLoad?: ReactEventHandler | undefined; + onLoadCapture?: ReactEventHandler | undefined; + onError?: ReactEventHandler | undefined; // also a Media Event + onErrorCapture?: ReactEventHandler | undefined; // also a Media Event + + // Keyboard Events + onKeyDown?: KeyboardEventHandler | undefined; + onKeyDownCapture?: KeyboardEventHandler | undefined; + /** @deprecated Use `onKeyUp` or `onKeyDown` instead */ + onKeyPress?: KeyboardEventHandler | undefined; + /** @deprecated Use `onKeyUpCapture` or `onKeyDownCapture` instead */ + onKeyPressCapture?: KeyboardEventHandler | undefined; + onKeyUp?: KeyboardEventHandler | undefined; + onKeyUpCapture?: KeyboardEventHandler | undefined; + + // Media Events + onAbort?: ReactEventHandler | undefined; + onAbortCapture?: ReactEventHandler | undefined; + onCanPlay?: ReactEventHandler | undefined; + onCanPlayCapture?: ReactEventHandler | undefined; + onCanPlayThrough?: ReactEventHandler | undefined; + onCanPlayThroughCapture?: ReactEventHandler | undefined; + onDurationChange?: ReactEventHandler | undefined; + onDurationChangeCapture?: ReactEventHandler | undefined; + onEmptied?: ReactEventHandler | undefined; + onEmptiedCapture?: ReactEventHandler | undefined; + onEncrypted?: ReactEventHandler | undefined; + onEncryptedCapture?: ReactEventHandler | undefined; + onEnded?: ReactEventHandler | undefined; + onEndedCapture?: ReactEventHandler | undefined; + onLoadedData?: ReactEventHandler | undefined; + onLoadedDataCapture?: ReactEventHandler | undefined; + onLoadedMetadata?: ReactEventHandler | undefined; + onLoadedMetadataCapture?: ReactEventHandler | undefined; + onLoadStart?: ReactEventHandler | undefined; + onLoadStartCapture?: ReactEventHandler | undefined; + onPause?: ReactEventHandler | undefined; + onPauseCapture?: ReactEventHandler | undefined; + onPlay?: ReactEventHandler | undefined; + onPlayCapture?: ReactEventHandler | undefined; + onPlaying?: ReactEventHandler | undefined; + onPlayingCapture?: ReactEventHandler | undefined; + onProgress?: ReactEventHandler | undefined; + onProgressCapture?: ReactEventHandler | undefined; + onRateChange?: ReactEventHandler | undefined; + onRateChangeCapture?: ReactEventHandler | undefined; + onSeeked?: ReactEventHandler | undefined; + onSeekedCapture?: ReactEventHandler | undefined; + onSeeking?: ReactEventHandler | undefined; + onSeekingCapture?: ReactEventHandler | undefined; + onStalled?: ReactEventHandler | undefined; + onStalledCapture?: ReactEventHandler | undefined; + onSuspend?: ReactEventHandler | undefined; + onSuspendCapture?: ReactEventHandler | undefined; + onTimeUpdate?: ReactEventHandler | undefined; + onTimeUpdateCapture?: ReactEventHandler | undefined; + onVolumeChange?: ReactEventHandler | undefined; + onVolumeChangeCapture?: ReactEventHandler | undefined; + onWaiting?: ReactEventHandler | undefined; + onWaitingCapture?: ReactEventHandler | undefined; + + // MouseEvents + onAuxClick?: MouseEventHandler | undefined; + onAuxClickCapture?: MouseEventHandler | undefined; + onClick?: MouseEventHandler | undefined; + onClickCapture?: MouseEventHandler | undefined; + onContextMenu?: MouseEventHandler | undefined; + onContextMenuCapture?: MouseEventHandler | undefined; + onDoubleClick?: MouseEventHandler | undefined; + onDoubleClickCapture?: MouseEventHandler | undefined; + onDrag?: DragEventHandler | undefined; + onDragCapture?: DragEventHandler | undefined; + onDragEnd?: DragEventHandler | undefined; + onDragEndCapture?: DragEventHandler | undefined; + onDragEnter?: DragEventHandler | undefined; + onDragEnterCapture?: DragEventHandler | undefined; + onDragExit?: DragEventHandler | undefined; + onDragExitCapture?: DragEventHandler | undefined; + onDragLeave?: DragEventHandler | undefined; + onDragLeaveCapture?: DragEventHandler | undefined; + onDragOver?: DragEventHandler | undefined; + onDragOverCapture?: DragEventHandler | undefined; + onDragStart?: DragEventHandler | undefined; + onDragStartCapture?: DragEventHandler | undefined; + onDrop?: DragEventHandler | undefined; + onDropCapture?: DragEventHandler | undefined; + onMouseDown?: MouseEventHandler | undefined; + onMouseDownCapture?: MouseEventHandler | undefined; + onMouseEnter?: MouseEventHandler | undefined; + onMouseLeave?: MouseEventHandler | undefined; + onMouseMove?: MouseEventHandler | undefined; + onMouseMoveCapture?: MouseEventHandler | undefined; + onMouseOut?: MouseEventHandler | undefined; + onMouseOutCapture?: MouseEventHandler | undefined; + onMouseOver?: MouseEventHandler | undefined; + onMouseOverCapture?: MouseEventHandler | undefined; + onMouseUp?: MouseEventHandler | undefined; + onMouseUpCapture?: MouseEventHandler | undefined; + + // Selection Events + onSelect?: ReactEventHandler | undefined; + onSelectCapture?: ReactEventHandler | undefined; + + // Touch Events + onTouchCancel?: TouchEventHandler | undefined; + onTouchCancelCapture?: TouchEventHandler | undefined; + onTouchEnd?: TouchEventHandler | undefined; + onTouchEndCapture?: TouchEventHandler | undefined; + onTouchMove?: TouchEventHandler | undefined; + onTouchMoveCapture?: TouchEventHandler | undefined; + onTouchStart?: TouchEventHandler | undefined; + onTouchStartCapture?: TouchEventHandler | undefined; + + // Pointer Events + onPointerDown?: PointerEventHandler | undefined; + onPointerDownCapture?: PointerEventHandler | undefined; + onPointerMove?: PointerEventHandler | undefined; + onPointerMoveCapture?: PointerEventHandler | undefined; + onPointerUp?: PointerEventHandler | undefined; + onPointerUpCapture?: PointerEventHandler | undefined; + onPointerCancel?: PointerEventHandler | undefined; + onPointerCancelCapture?: PointerEventHandler | undefined; + onPointerEnter?: PointerEventHandler | undefined; + onPointerLeave?: PointerEventHandler | undefined; + onPointerOver?: PointerEventHandler | undefined; + onPointerOverCapture?: PointerEventHandler | undefined; + onPointerOut?: PointerEventHandler | undefined; + onPointerOutCapture?: PointerEventHandler | undefined; + onGotPointerCapture?: PointerEventHandler | undefined; + onGotPointerCaptureCapture?: PointerEventHandler | undefined; + onLostPointerCapture?: PointerEventHandler | undefined; + onLostPointerCaptureCapture?: PointerEventHandler | undefined; + + // UI Events + onScroll?: UIEventHandler | undefined; + onScrollCapture?: UIEventHandler | undefined; + onScrollEnd?: UIEventHandler | undefined; + onScrollEndCapture?: UIEventHandler | undefined; + + // Wheel Events + onWheel?: WheelEventHandler | undefined; + onWheelCapture?: WheelEventHandler | undefined; + + // Animation Events + onAnimationStart?: AnimationEventHandler | undefined; + onAnimationStartCapture?: AnimationEventHandler | undefined; + onAnimationEnd?: AnimationEventHandler | undefined; + onAnimationEndCapture?: AnimationEventHandler | undefined; + onAnimationIteration?: AnimationEventHandler | undefined; + onAnimationIterationCapture?: AnimationEventHandler | undefined; + + // Toggle Events + onToggle?: ToggleEventHandler | undefined; + onBeforeToggle?: ToggleEventHandler | undefined; + + // Transition Events + onTransitionCancel?: TransitionEventHandler | undefined; + onTransitionCancelCapture?: TransitionEventHandler | undefined; + onTransitionEnd?: TransitionEventHandler | undefined; + onTransitionEndCapture?: TransitionEventHandler | undefined; + onTransitionRun?: TransitionEventHandler | undefined; + onTransitionRunCapture?: TransitionEventHandler | undefined; + onTransitionStart?: TransitionEventHandler | undefined; + onTransitionStartCapture?: TransitionEventHandler | undefined; + } + + export interface CSSProperties extends CSS.Properties { + /** + * The index signature was removed to enable closed typing for style + * using CSSType. You're able to use type assertion or module augmentation + * to add properties or an index signature of your own. + * + * For examples and more information, visit: + * https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors + */ + } + + // All the WAI-ARIA 1.1 attributes from https://www.w3.org/TR/wai-aria-1.1/ + interface AriaAttributes { + /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */ + "aria-activedescendant"?: string | undefined; + /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */ + "aria-atomic"?: Booleanish | undefined; + /** + * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be + * presented if they are made. + */ + "aria-autocomplete"?: "none" | "inline" | "list" | "both" | undefined; + /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */ + /** + * Defines a string value that labels the current element, which is intended to be converted into Braille. + * @see aria-label. + */ + "aria-braillelabel"?: string | undefined; + /** + * Defines a human-readable, author-localized abbreviated description for the role of an element, which is intended to be converted into Braille. + * @see aria-roledescription. + */ + "aria-brailleroledescription"?: string | undefined; + "aria-busy"?: Booleanish | undefined; + /** + * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. + * @see aria-pressed @see aria-selected. + */ + "aria-checked"?: boolean | "false" | "mixed" | "true" | undefined; + /** + * Defines the total number of columns in a table, grid, or treegrid. + * @see aria-colindex. + */ + "aria-colcount"?: number | undefined; + /** + * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. + * @see aria-colcount @see aria-colspan. + */ + "aria-colindex"?: number | undefined; + /** + * Defines a human readable text alternative of aria-colindex. + * @see aria-rowindextext. + */ + "aria-colindextext"?: string | undefined; + /** + * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-colindex @see aria-rowspan. + */ + "aria-colspan"?: number | undefined; + /** + * Identifies the element (or elements) whose contents or presence are controlled by the current element. + * @see aria-owns. + */ + "aria-controls"?: string | undefined; + /** Indicates the element that represents the current item within a container or set of related elements. */ + "aria-current"?: boolean | "false" | "true" | "page" | "step" | "location" | "date" | "time" | undefined; + /** + * Identifies the element (or elements) that describes the object. + * @see aria-labelledby + */ + "aria-describedby"?: string | undefined; + /** + * Defines a string value that describes or annotates the current element. + * @see related aria-describedby. + */ + "aria-description"?: string | undefined; + /** + * Identifies the element that provides a detailed, extended description for the object. + * @see aria-describedby. + */ + "aria-details"?: string | undefined; + /** + * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. + * @see aria-hidden @see aria-readonly. + */ + "aria-disabled"?: Booleanish | undefined; + /** + * Indicates what functions can be performed when a dragged object is released on the drop target. + * @deprecated in ARIA 1.1 + */ + "aria-dropeffect"?: "none" | "copy" | "execute" | "link" | "move" | "popup" | undefined; + /** + * Identifies the element that provides an error message for the object. + * @see aria-invalid @see aria-describedby. + */ + "aria-errormessage"?: string | undefined; + /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */ + "aria-expanded"?: Booleanish | undefined; + /** + * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, + * allows assistive technology to override the general default of reading in document source order. + */ + "aria-flowto"?: string | undefined; + /** + * Indicates an element's "grabbed" state in a drag-and-drop operation. + * @deprecated in ARIA 1.1 + */ + "aria-grabbed"?: Booleanish | undefined; + /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */ + "aria-haspopup"?: boolean | "false" | "true" | "menu" | "listbox" | "tree" | "grid" | "dialog" | undefined; + /** + * Indicates whether the element is exposed to an accessibility API. + * @see aria-disabled. + */ + "aria-hidden"?: Booleanish | undefined; + /** + * Indicates the entered value does not conform to the format expected by the application. + * @see aria-errormessage. + */ + "aria-invalid"?: boolean | "false" | "true" | "grammar" | "spelling" | undefined; + /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */ + "aria-keyshortcuts"?: string | undefined; + /** + * Defines a string value that labels the current element. + * @see aria-labelledby. + */ + "aria-label"?: string | undefined; + /** + * Identifies the element (or elements) that labels the current element. + * @see aria-describedby. + */ + "aria-labelledby"?: string | undefined; + /** Defines the hierarchical level of an element within a structure. */ + "aria-level"?: number | undefined; + /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */ + "aria-live"?: "off" | "assertive" | "polite" | undefined; + /** Indicates whether an element is modal when displayed. */ + "aria-modal"?: Booleanish | undefined; + /** Indicates whether a text box accepts multiple lines of input or only a single line. */ + "aria-multiline"?: Booleanish | undefined; + /** Indicates that the user may select more than one item from the current selectable descendants. */ + "aria-multiselectable"?: Booleanish | undefined; + /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ + "aria-orientation"?: "horizontal" | "vertical" | undefined; + /** + * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship + * between DOM elements where the DOM hierarchy cannot be used to represent the relationship. + * @see aria-controls. + */ + "aria-owns"?: string | undefined; + /** + * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. + * A hint could be a sample value or a brief description of the expected format. + */ + "aria-placeholder"?: string | undefined; + /** + * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-setsize. + */ + "aria-posinset"?: number | undefined; + /** + * Indicates the current "pressed" state of toggle buttons. + * @see aria-checked @see aria-selected. + */ + "aria-pressed"?: boolean | "false" | "mixed" | "true" | undefined; + /** + * Indicates that the element is not editable, but is otherwise operable. + * @see aria-disabled. + */ + "aria-readonly"?: Booleanish | undefined; + /** + * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. + * @see aria-atomic. + */ + "aria-relevant"?: + | "additions" + | "additions removals" + | "additions text" + | "all" + | "removals" + | "removals additions" + | "removals text" + | "text" + | "text additions" + | "text removals" + | undefined; + /** Indicates that user input is required on the element before a form may be submitted. */ + "aria-required"?: Booleanish | undefined; + /** Defines a human-readable, author-localized description for the role of an element. */ + "aria-roledescription"?: string | undefined; + /** + * Defines the total number of rows in a table, grid, or treegrid. + * @see aria-rowindex. + */ + "aria-rowcount"?: number | undefined; + /** + * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. + * @see aria-rowcount @see aria-rowspan. + */ + "aria-rowindex"?: number | undefined; + /** + * Defines a human readable text alternative of aria-rowindex. + * @see aria-colindextext. + */ + "aria-rowindextext"?: string | undefined; + /** + * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-rowindex @see aria-colspan. + */ + "aria-rowspan"?: number | undefined; + /** + * Indicates the current "selected" state of various widgets. + * @see aria-checked @see aria-pressed. + */ + "aria-selected"?: Booleanish | undefined; + /** + * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-posinset. + */ + "aria-setsize"?: number | undefined; + /** Indicates if items in a table or grid are sorted in ascending or descending order. */ + "aria-sort"?: "none" | "ascending" | "descending" | "other" | undefined; + /** Defines the maximum allowed value for a range widget. */ + "aria-valuemax"?: number | undefined; + /** Defines the minimum allowed value for a range widget. */ + "aria-valuemin"?: number | undefined; + /** + * Defines the current value for a range widget. + * @see aria-valuetext. + */ + "aria-valuenow"?: number | undefined; + /** Defines the human readable text alternative of aria-valuenow for a range widget. */ + "aria-valuetext"?: string | undefined; + } + + // All the WAI-ARIA 1.1 role attribute values from https://www.w3.org/TR/wai-aria-1.1/#role_definitions + type AriaRole = + | "alert" + | "alertdialog" + | "application" + | "article" + | "banner" + | "button" + | "cell" + | "checkbox" + | "columnheader" + | "combobox" + | "complementary" + | "contentinfo" + | "definition" + | "dialog" + | "directory" + | "document" + | "feed" + | "figure" + | "form" + | "grid" + | "gridcell" + | "group" + | "heading" + | "img" + | "link" + | "list" + | "listbox" + | "listitem" + | "log" + | "main" + | "marquee" + | "math" + | "menu" + | "menubar" + | "menuitem" + | "menuitemcheckbox" + | "menuitemradio" + | "navigation" + | "none" + | "note" + | "option" + | "presentation" + | "progressbar" + | "radio" + | "radiogroup" + | "region" + | "row" + | "rowgroup" + | "rowheader" + | "scrollbar" + | "search" + | "searchbox" + | "separator" + | "slider" + | "spinbutton" + | "status" + | "switch" + | "tab" + | "table" + | "tablist" + | "tabpanel" + | "term" + | "textbox" + | "timer" + | "toolbar" + | "tooltip" + | "tree" + | "treegrid" + | "treeitem" + | (string & {}); + + interface HTMLAttributes extends AriaAttributes, DOMAttributes { + // React-specific Attributes + defaultChecked?: boolean | undefined; + defaultValue?: string | number | readonly string[] | undefined; + suppressContentEditableWarning?: boolean | undefined; + suppressHydrationWarning?: boolean | undefined; + + // Standard HTML Attributes + accessKey?: string | undefined; + autoCapitalize?: "off" | "none" | "on" | "sentences" | "words" | "characters" | undefined | (string & {}); + autoFocus?: boolean | undefined; + className?: string | undefined; + contentEditable?: Booleanish | "inherit" | "plaintext-only" | undefined; + contextMenu?: string | undefined; + dir?: string | undefined; + draggable?: Booleanish | undefined; + enterKeyHint?: "enter" | "done" | "go" | "next" | "previous" | "search" | "send" | undefined; + hidden?: boolean | undefined; + id?: string | undefined; + lang?: string | undefined; + nonce?: string | undefined; + slot?: string | undefined; + spellCheck?: Booleanish | undefined; + style?: CSSProperties | undefined; + tabIndex?: number | undefined; + title?: string | undefined; + translate?: "yes" | "no" | undefined; + + // Unknown + radioGroup?: string | undefined; // , + + // WAI-ARIA + role?: AriaRole | undefined; + + // RDFa Attributes + about?: string | undefined; + content?: string | undefined; + datatype?: string | undefined; + inlist?: any; + prefix?: string | undefined; + property?: string | undefined; + rel?: string | undefined; + resource?: string | undefined; + rev?: string | undefined; + typeof?: string | undefined; + vocab?: string | undefined; + + // Non-standard Attributes + autoCorrect?: string | undefined; + autoSave?: string | undefined; + color?: string | undefined; + itemProp?: string | undefined; + itemScope?: boolean | undefined; + itemType?: string | undefined; + itemID?: string | undefined; + itemRef?: string | undefined; + results?: number | undefined; + security?: string | undefined; + unselectable?: "on" | "off" | undefined; + + // Popover API + popover?: "" | "auto" | "manual" | undefined; + popoverTargetAction?: "toggle" | "show" | "hide" | undefined; + popoverTarget?: string | undefined; + + // Living Standard + /** + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/inert + */ + inert?: boolean | undefined; + /** + * Hints at the type of data that might be entered by the user while editing the element or its contents + * @see {@link https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute} + */ + inputMode?: "none" | "text" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined; + /** + * Specify that a standard HTML element should behave like a defined custom built-in element + * @see {@link https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is} + */ + is?: string | undefined; + /** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/exportparts} + */ + exportparts?: string | undefined; + /** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/part} + */ + part?: string | undefined; + } + + /** + * For internal usage only. + * Different release channels declare additional types of ReactNode this particular release channel accepts. + * App or library types should never augment this interface. + */ + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS {} + + interface AllHTMLAttributes extends HTMLAttributes { + // Standard HTML Attributes + accept?: string | undefined; + acceptCharset?: string | undefined; + action?: + | string + | undefined + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + allowFullScreen?: boolean | undefined; + allowTransparency?: boolean | undefined; + alt?: string | undefined; + as?: string | undefined; + async?: boolean | undefined; + autoComplete?: string | undefined; + autoPlay?: boolean | undefined; + capture?: boolean | "user" | "environment" | undefined; + cellPadding?: number | string | undefined; + cellSpacing?: number | string | undefined; + charSet?: string | undefined; + challenge?: string | undefined; + checked?: boolean | undefined; + cite?: string | undefined; + classID?: string | undefined; + cols?: number | undefined; + colSpan?: number | undefined; + controls?: boolean | undefined; + coords?: string | undefined; + crossOrigin?: CrossOrigin; + data?: string | undefined; + dateTime?: string | undefined; + default?: boolean | undefined; + defer?: boolean | undefined; + disabled?: boolean | undefined; + download?: any; + encType?: string | undefined; + form?: string | undefined; + formAction?: + | string + | undefined + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + frameBorder?: number | string | undefined; + headers?: string | undefined; + height?: number | string | undefined; + high?: number | undefined; + href?: string | undefined; + hrefLang?: string | undefined; + htmlFor?: string | undefined; + httpEquiv?: string | undefined; + integrity?: string | undefined; + keyParams?: string | undefined; + keyType?: string | undefined; + kind?: string | undefined; + label?: string | undefined; + list?: string | undefined; + loop?: boolean | undefined; + low?: number | undefined; + manifest?: string | undefined; + marginHeight?: number | undefined; + marginWidth?: number | undefined; + max?: number | string | undefined; + maxLength?: number | undefined; + media?: string | undefined; + mediaGroup?: string | undefined; + method?: string | undefined; + min?: number | string | undefined; + minLength?: number | undefined; + multiple?: boolean | undefined; + muted?: boolean | undefined; + name?: string | undefined; + noValidate?: boolean | undefined; + open?: boolean | undefined; + optimum?: number | undefined; + pattern?: string | undefined; + placeholder?: string | undefined; + playsInline?: boolean | undefined; + poster?: string | undefined; + preload?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + reversed?: boolean | undefined; + rows?: number | undefined; + rowSpan?: number | undefined; + sandbox?: string | undefined; + scope?: string | undefined; + scoped?: boolean | undefined; + scrolling?: string | undefined; + seamless?: boolean | undefined; + selected?: boolean | undefined; + shape?: string | undefined; + size?: number | undefined; + sizes?: string | undefined; + span?: number | undefined; + src?: string | undefined; + srcDoc?: string | undefined; + srcLang?: string | undefined; + srcSet?: string | undefined; + start?: number | undefined; + step?: number | string | undefined; + summary?: string | undefined; + target?: string | undefined; + type?: string | undefined; + useMap?: string | undefined; + value?: string | readonly string[] | number | undefined; + width?: number | string | undefined; + wmode?: string | undefined; + wrap?: string | undefined; + } + + type HTMLAttributeReferrerPolicy = + | "" + | "no-referrer" + | "no-referrer-when-downgrade" + | "origin" + | "origin-when-cross-origin" + | "same-origin" + | "strict-origin" + | "strict-origin-when-cross-origin" + | "unsafe-url"; + + type HTMLAttributeAnchorTarget = + | "_self" + | "_blank" + | "_parent" + | "_top" + | (string & {}); + + interface AnchorHTMLAttributes extends HTMLAttributes { + download?: any; + href?: string | undefined; + hrefLang?: string | undefined; + media?: string | undefined; + ping?: string | undefined; + target?: HTMLAttributeAnchorTarget | undefined; + type?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + } + + interface AudioHTMLAttributes extends MediaHTMLAttributes {} + + interface AreaHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + coords?: string | undefined; + download?: any; + href?: string | undefined; + hrefLang?: string | undefined; + media?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + shape?: string | undefined; + target?: string | undefined; + } + + interface BaseHTMLAttributes extends HTMLAttributes { + href?: string | undefined; + target?: string | undefined; + } + + interface BlockquoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + + interface ButtonHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + formAction?: + | string + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ] + | undefined; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + name?: string | undefined; + type?: "submit" | "reset" | "button" | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface CanvasHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + width?: number | string | undefined; + } + + interface ColHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + width?: number | string | undefined; + } + + interface ColgroupHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + } + + interface DataHTMLAttributes extends HTMLAttributes { + value?: string | readonly string[] | number | undefined; + } + + interface DetailsHTMLAttributes extends HTMLAttributes { + open?: boolean | undefined; + name?: string | undefined; + } + + interface DelHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + dateTime?: string | undefined; + } + + interface DialogHTMLAttributes extends HTMLAttributes { + onCancel?: ReactEventHandler | undefined; + onClose?: ReactEventHandler | undefined; + open?: boolean | undefined; + } + + interface EmbedHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + src?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + } + + interface FieldsetHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + name?: string | undefined; + } + + interface FormHTMLAttributes extends HTMLAttributes { + acceptCharset?: string | undefined; + action?: + | string + | undefined + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + autoComplete?: string | undefined; + encType?: string | undefined; + method?: string | undefined; + name?: string | undefined; + noValidate?: boolean | undefined; + target?: string | undefined; + } + + interface HtmlHTMLAttributes extends HTMLAttributes { + manifest?: string | undefined; + } + + interface IframeHTMLAttributes extends HTMLAttributes { + allow?: string | undefined; + allowFullScreen?: boolean | undefined; + allowTransparency?: boolean | undefined; + /** @deprecated */ + frameBorder?: number | string | undefined; + height?: number | string | undefined; + loading?: "eager" | "lazy" | undefined; + /** @deprecated */ + marginHeight?: number | undefined; + /** @deprecated */ + marginWidth?: number | undefined; + name?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sandbox?: string | undefined; + /** @deprecated */ + scrolling?: string | undefined; + seamless?: boolean | undefined; + src?: string | undefined; + srcDoc?: string | undefined; + width?: number | string | undefined; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES {} + + interface ImgHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + crossOrigin?: CrossOrigin; + decoding?: "async" | "auto" | "sync" | undefined; + fetchPriority?: "high" | "low" | "auto"; + height?: number | string | undefined; + loading?: "eager" | "lazy" | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + src?: + | string + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES + ] + | undefined; + srcSet?: string | undefined; + useMap?: string | undefined; + width?: number | string | undefined; + } + + interface InsHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + dateTime?: string | undefined; + } + + type HTMLInputTypeAttribute = + | "button" + | "checkbox" + | "color" + | "date" + | "datetime-local" + | "email" + | "file" + | "hidden" + | "image" + | "month" + | "number" + | "password" + | "radio" + | "range" + | "reset" + | "search" + | "submit" + | "tel" + | "text" + | "time" + | "url" + | "week" + | (string & {}); + + type AutoFillAddressKind = "billing" | "shipping"; + type AutoFillBase = "" | "off" | "on"; + type AutoFillContactField = + | "email" + | "tel" + | "tel-area-code" + | "tel-country-code" + | "tel-extension" + | "tel-local" + | "tel-local-prefix" + | "tel-local-suffix" + | "tel-national"; + type AutoFillContactKind = "home" | "mobile" | "work"; + type AutoFillCredentialField = "webauthn"; + type AutoFillNormalField = + | "additional-name" + | "address-level1" + | "address-level2" + | "address-level3" + | "address-level4" + | "address-line1" + | "address-line2" + | "address-line3" + | "bday-day" + | "bday-month" + | "bday-year" + | "cc-csc" + | "cc-exp" + | "cc-exp-month" + | "cc-exp-year" + | "cc-family-name" + | "cc-given-name" + | "cc-name" + | "cc-number" + | "cc-type" + | "country" + | "country-name" + | "current-password" + | "family-name" + | "given-name" + | "honorific-prefix" + | "honorific-suffix" + | "name" + | "new-password" + | "one-time-code" + | "organization" + | "postal-code" + | "street-address" + | "transaction-amount" + | "transaction-currency" + | "username"; + type OptionalPrefixToken = `${T} ` | ""; + type OptionalPostfixToken = ` ${T}` | ""; + type AutoFillField = AutoFillNormalField | `${OptionalPrefixToken}${AutoFillContactField}`; + type AutoFillSection = `section-${string}`; + type AutoFill = + | AutoFillBase + | `${OptionalPrefixToken}${OptionalPrefixToken< + AutoFillAddressKind + >}${AutoFillField}${OptionalPostfixToken}`; + type HTMLInputAutoCompleteAttribute = AutoFill | (string & {}); + + interface InputHTMLAttributes extends HTMLAttributes { + accept?: string | undefined; + alt?: string | undefined; + autoComplete?: HTMLInputAutoCompleteAttribute | undefined; + capture?: boolean | "user" | "environment" | undefined; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute + checked?: boolean | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + formAction?: + | string + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ] + | undefined; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + height?: number | string | undefined; + list?: string | undefined; + max?: number | string | undefined; + maxLength?: number | undefined; + min?: number | string | undefined; + minLength?: number | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + pattern?: string | undefined; + placeholder?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + size?: number | undefined; + src?: string | undefined; + step?: number | string | undefined; + type?: HTMLInputTypeAttribute | undefined; + value?: string | readonly string[] | number | undefined; + width?: number | string | undefined; + + onChange?: ChangeEventHandler | undefined; + } + + interface KeygenHTMLAttributes extends HTMLAttributes { + challenge?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + keyType?: string | undefined; + keyParams?: string | undefined; + name?: string | undefined; + } + + interface LabelHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + htmlFor?: string | undefined; + } + + interface LiHTMLAttributes extends HTMLAttributes { + value?: string | readonly string[] | number | undefined; + } + + interface LinkHTMLAttributes extends HTMLAttributes { + as?: string | undefined; + blocking?: "render" | (string & {}) | undefined; + crossOrigin?: CrossOrigin; + fetchPriority?: "high" | "low" | "auto"; + href?: string | undefined; + hrefLang?: string | undefined; + integrity?: string | undefined; + media?: string | undefined; + imageSrcSet?: string | undefined; + imageSizes?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + type?: string | undefined; + charSet?: string | undefined; + + // React props + precedence?: string | undefined; + } + + interface MapHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + + interface MenuHTMLAttributes extends HTMLAttributes { + type?: string | undefined; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES {} + + interface MediaHTMLAttributes extends HTMLAttributes { + autoPlay?: boolean | undefined; + controls?: boolean | undefined; + controlsList?: string | undefined; + crossOrigin?: CrossOrigin; + loop?: boolean | undefined; + mediaGroup?: string | undefined; + muted?: boolean | undefined; + playsInline?: boolean | undefined; + preload?: string | undefined; + src?: + | string + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES + ] + | undefined; + } + + interface MetaHTMLAttributes extends HTMLAttributes { + charSet?: string | undefined; + content?: string | undefined; + httpEquiv?: string | undefined; + media?: string | undefined; + name?: string | undefined; + } + + interface MeterHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + high?: number | undefined; + low?: number | undefined; + max?: number | string | undefined; + min?: number | string | undefined; + optimum?: number | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface QuoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + + interface ObjectHTMLAttributes extends HTMLAttributes { + classID?: string | undefined; + data?: string | undefined; + form?: string | undefined; + height?: number | string | undefined; + name?: string | undefined; + type?: string | undefined; + useMap?: string | undefined; + width?: number | string | undefined; + wmode?: string | undefined; + } + + interface OlHTMLAttributes extends HTMLAttributes { + reversed?: boolean | undefined; + start?: number | undefined; + type?: "1" | "a" | "A" | "i" | "I" | undefined; + } + + interface OptgroupHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + } + + interface OptionHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + selected?: boolean | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface OutputHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + htmlFor?: string | undefined; + name?: string | undefined; + } + + interface ParamHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface ProgressHTMLAttributes extends HTMLAttributes { + max?: number | string | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface SlotHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + + interface ScriptHTMLAttributes extends HTMLAttributes { + async?: boolean | undefined; + blocking?: "render" | (string & {}) | undefined; + /** @deprecated */ + charSet?: string | undefined; + crossOrigin?: CrossOrigin; + defer?: boolean | undefined; + integrity?: string | undefined; + noModule?: boolean | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + src?: string | undefined; + type?: string | undefined; + } + + interface SelectHTMLAttributes extends HTMLAttributes { + autoComplete?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + required?: boolean | undefined; + size?: number | undefined; + value?: string | readonly string[] | number | undefined; + onChange?: ChangeEventHandler | undefined; + } + + interface SourceHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + media?: string | undefined; + sizes?: string | undefined; + src?: string | undefined; + srcSet?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + } + + interface StyleHTMLAttributes extends HTMLAttributes { + blocking?: "render" | (string & {}) | undefined; + media?: string | undefined; + scoped?: boolean | undefined; + type?: string | undefined; + + // React props + href?: string | undefined; + precedence?: string | undefined; + } + + interface TableHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | undefined; + bgcolor?: string | undefined; + border?: number | undefined; + cellPadding?: number | string | undefined; + cellSpacing?: number | string | undefined; + frame?: boolean | undefined; + rules?: "none" | "groups" | "rows" | "columns" | "all" | undefined; + summary?: string | undefined; + width?: number | string | undefined; + } + + interface TextareaHTMLAttributes extends HTMLAttributes { + autoComplete?: string | undefined; + cols?: number | undefined; + dirName?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + maxLength?: number | undefined; + minLength?: number | undefined; + name?: string | undefined; + placeholder?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + rows?: number | undefined; + value?: string | readonly string[] | number | undefined; + wrap?: string | undefined; + + onChange?: ChangeEventHandler | undefined; + } + + interface TdHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | "justify" | "char" | undefined; + colSpan?: number | undefined; + headers?: string | undefined; + rowSpan?: number | undefined; + scope?: string | undefined; + abbr?: string | undefined; + height?: number | string | undefined; + width?: number | string | undefined; + valign?: "top" | "middle" | "bottom" | "baseline" | undefined; + } + + interface ThHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | "justify" | "char" | undefined; + colSpan?: number | undefined; + headers?: string | undefined; + rowSpan?: number | undefined; + scope?: string | undefined; + abbr?: string | undefined; + } + + interface TimeHTMLAttributes extends HTMLAttributes { + dateTime?: string | undefined; + } + + interface TrackHTMLAttributes extends HTMLAttributes { + default?: boolean | undefined; + kind?: string | undefined; + label?: string | undefined; + src?: string | undefined; + srcLang?: string | undefined; + } + + interface VideoHTMLAttributes extends MediaHTMLAttributes { + height?: number | string | undefined; + playsInline?: boolean | undefined; + poster?: string | undefined; + width?: number | string | undefined; + disablePictureInPicture?: boolean | undefined; + disableRemotePlayback?: boolean | undefined; + + onResize?: ReactEventHandler | undefined; + onResizeCapture?: ReactEventHandler | undefined; + } + + // this list is "complete" in that it contains every SVG attribute + // that React supports, but the types can be improved. + // Full list here: https://facebook.github.io/react/docs/dom-elements.html + // + // The three broad type categories are (in order of restrictiveness): + // - "number | string" + // - "string" + // - union of string literals + interface SVGAttributes extends AriaAttributes, DOMAttributes { + // React-specific Attributes + suppressHydrationWarning?: boolean | undefined; + + // Attributes which also defined in HTMLAttributes + // See comment in SVGDOMPropertyConfig.js + className?: string | undefined; + color?: string | undefined; + height?: number | string | undefined; + id?: string | undefined; + lang?: string | undefined; + max?: number | string | undefined; + media?: string | undefined; + method?: string | undefined; + min?: number | string | undefined; + name?: string | undefined; + style?: CSSProperties | undefined; + target?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + + // Other HTML properties supported by SVG elements in browsers + role?: AriaRole | undefined; + tabIndex?: number | undefined; + crossOrigin?: CrossOrigin; + + // SVG Specific attributes + accentHeight?: number | string | undefined; + accumulate?: "none" | "sum" | undefined; + additive?: "replace" | "sum" | undefined; + alignmentBaseline?: + | "auto" + | "baseline" + | "before-edge" + | "text-before-edge" + | "middle" + | "central" + | "after-edge" + | "text-after-edge" + | "ideographic" + | "alphabetic" + | "hanging" + | "mathematical" + | "inherit" + | undefined; + allowReorder?: "no" | "yes" | undefined; + alphabetic?: number | string | undefined; + amplitude?: number | string | undefined; + arabicForm?: "initial" | "medial" | "terminal" | "isolated" | undefined; + ascent?: number | string | undefined; + attributeName?: string | undefined; + attributeType?: string | undefined; + autoReverse?: Booleanish | undefined; + azimuth?: number | string | undefined; + baseFrequency?: number | string | undefined; + baselineShift?: number | string | undefined; + baseProfile?: number | string | undefined; + bbox?: number | string | undefined; + begin?: number | string | undefined; + bias?: number | string | undefined; + by?: number | string | undefined; + calcMode?: number | string | undefined; + capHeight?: number | string | undefined; + clip?: number | string | undefined; + clipPath?: string | undefined; + clipPathUnits?: number | string | undefined; + clipRule?: number | string | undefined; + colorInterpolation?: number | string | undefined; + colorInterpolationFilters?: "auto" | "sRGB" | "linearRGB" | "inherit" | undefined; + colorProfile?: number | string | undefined; + colorRendering?: number | string | undefined; + contentScriptType?: number | string | undefined; + contentStyleType?: number | string | undefined; + cursor?: number | string | undefined; + cx?: number | string | undefined; + cy?: number | string | undefined; + d?: string | undefined; + decelerate?: number | string | undefined; + descent?: number | string | undefined; + diffuseConstant?: number | string | undefined; + direction?: number | string | undefined; + display?: number | string | undefined; + divisor?: number | string | undefined; + dominantBaseline?: number | string | undefined; + dur?: number | string | undefined; + dx?: number | string | undefined; + dy?: number | string | undefined; + edgeMode?: number | string | undefined; + elevation?: number | string | undefined; + enableBackground?: number | string | undefined; + end?: number | string | undefined; + exponent?: number | string | undefined; + externalResourcesRequired?: Booleanish | undefined; + fill?: string | undefined; + fillOpacity?: number | string | undefined; + fillRule?: "nonzero" | "evenodd" | "inherit" | undefined; + filter?: string | undefined; + filterRes?: number | string | undefined; + filterUnits?: number | string | undefined; + floodColor?: number | string | undefined; + floodOpacity?: number | string | undefined; + focusable?: Booleanish | "auto" | undefined; + fontFamily?: string | undefined; + fontSize?: number | string | undefined; + fontSizeAdjust?: number | string | undefined; + fontStretch?: number | string | undefined; + fontStyle?: number | string | undefined; + fontVariant?: number | string | undefined; + fontWeight?: number | string | undefined; + format?: number | string | undefined; + fr?: number | string | undefined; + from?: number | string | undefined; + fx?: number | string | undefined; + fy?: number | string | undefined; + g1?: number | string | undefined; + g2?: number | string | undefined; + glyphName?: number | string | undefined; + glyphOrientationHorizontal?: number | string | undefined; + glyphOrientationVertical?: number | string | undefined; + glyphRef?: number | string | undefined; + gradientTransform?: string | undefined; + gradientUnits?: string | undefined; + hanging?: number | string | undefined; + horizAdvX?: number | string | undefined; + horizOriginX?: number | string | undefined; + href?: string | undefined; + ideographic?: number | string | undefined; + imageRendering?: number | string | undefined; + in2?: number | string | undefined; + in?: string | undefined; + intercept?: number | string | undefined; + k1?: number | string | undefined; + k2?: number | string | undefined; + k3?: number | string | undefined; + k4?: number | string | undefined; + k?: number | string | undefined; + kernelMatrix?: number | string | undefined; + kernelUnitLength?: number | string | undefined; + kerning?: number | string | undefined; + keyPoints?: number | string | undefined; + keySplines?: number | string | undefined; + keyTimes?: number | string | undefined; + lengthAdjust?: number | string | undefined; + letterSpacing?: number | string | undefined; + lightingColor?: number | string | undefined; + limitingConeAngle?: number | string | undefined; + local?: number | string | undefined; + markerEnd?: string | undefined; + markerHeight?: number | string | undefined; + markerMid?: string | undefined; + markerStart?: string | undefined; + markerUnits?: number | string | undefined; + markerWidth?: number | string | undefined; + mask?: string | undefined; + maskContentUnits?: number | string | undefined; + maskUnits?: number | string | undefined; + mathematical?: number | string | undefined; + mode?: number | string | undefined; + numOctaves?: number | string | undefined; + offset?: number | string | undefined; + opacity?: number | string | undefined; + operator?: number | string | undefined; + order?: number | string | undefined; + orient?: number | string | undefined; + orientation?: number | string | undefined; + origin?: number | string | undefined; + overflow?: number | string | undefined; + overlinePosition?: number | string | undefined; + overlineThickness?: number | string | undefined; + paintOrder?: number | string | undefined; + panose1?: number | string | undefined; + path?: string | undefined; + pathLength?: number | string | undefined; + patternContentUnits?: string | undefined; + patternTransform?: number | string | undefined; + patternUnits?: string | undefined; + pointerEvents?: number | string | undefined; + points?: string | undefined; + pointsAtX?: number | string | undefined; + pointsAtY?: number | string | undefined; + pointsAtZ?: number | string | undefined; + preserveAlpha?: Booleanish | undefined; + preserveAspectRatio?: string | undefined; + primitiveUnits?: number | string | undefined; + r?: number | string | undefined; + radius?: number | string | undefined; + refX?: number | string | undefined; + refY?: number | string | undefined; + renderingIntent?: number | string | undefined; + repeatCount?: number | string | undefined; + repeatDur?: number | string | undefined; + requiredExtensions?: number | string | undefined; + requiredFeatures?: number | string | undefined; + restart?: number | string | undefined; + result?: string | undefined; + rotate?: number | string | undefined; + rx?: number | string | undefined; + ry?: number | string | undefined; + scale?: number | string | undefined; + seed?: number | string | undefined; + shapeRendering?: number | string | undefined; + slope?: number | string | undefined; + spacing?: number | string | undefined; + specularConstant?: number | string | undefined; + specularExponent?: number | string | undefined; + speed?: number | string | undefined; + spreadMethod?: string | undefined; + startOffset?: number | string | undefined; + stdDeviation?: number | string | undefined; + stemh?: number | string | undefined; + stemv?: number | string | undefined; + stitchTiles?: number | string | undefined; + stopColor?: string | undefined; + stopOpacity?: number | string | undefined; + strikethroughPosition?: number | string | undefined; + strikethroughThickness?: number | string | undefined; + string?: number | string | undefined; + stroke?: string | undefined; + strokeDasharray?: string | number | undefined; + strokeDashoffset?: string | number | undefined; + strokeLinecap?: "butt" | "round" | "square" | "inherit" | undefined; + strokeLinejoin?: "miter" | "round" | "bevel" | "inherit" | undefined; + strokeMiterlimit?: number | string | undefined; + strokeOpacity?: number | string | undefined; + strokeWidth?: number | string | undefined; + surfaceScale?: number | string | undefined; + systemLanguage?: number | string | undefined; + tableValues?: number | string | undefined; + targetX?: number | string | undefined; + targetY?: number | string | undefined; + textAnchor?: string | undefined; + textDecoration?: number | string | undefined; + textLength?: number | string | undefined; + textRendering?: number | string | undefined; + to?: number | string | undefined; + transform?: string | undefined; + u1?: number | string | undefined; + u2?: number | string | undefined; + underlinePosition?: number | string | undefined; + underlineThickness?: number | string | undefined; + unicode?: number | string | undefined; + unicodeBidi?: number | string | undefined; + unicodeRange?: number | string | undefined; + unitsPerEm?: number | string | undefined; + vAlphabetic?: number | string | undefined; + values?: string | undefined; + vectorEffect?: number | string | undefined; + version?: string | undefined; + vertAdvY?: number | string | undefined; + vertOriginX?: number | string | undefined; + vertOriginY?: number | string | undefined; + vHanging?: number | string | undefined; + vIdeographic?: number | string | undefined; + viewBox?: string | undefined; + viewTarget?: number | string | undefined; + visibility?: number | string | undefined; + vMathematical?: number | string | undefined; + widths?: number | string | undefined; + wordSpacing?: number | string | undefined; + writingMode?: number | string | undefined; + x1?: number | string | undefined; + x2?: number | string | undefined; + x?: number | string | undefined; + xChannelSelector?: string | undefined; + xHeight?: number | string | undefined; + xlinkActuate?: string | undefined; + xlinkArcrole?: string | undefined; + xlinkHref?: string | undefined; + xlinkRole?: string | undefined; + xlinkShow?: string | undefined; + xlinkTitle?: string | undefined; + xlinkType?: string | undefined; + xmlBase?: string | undefined; + xmlLang?: string | undefined; + xmlns?: string | undefined; + xmlnsXlink?: string | undefined; + xmlSpace?: string | undefined; + y1?: number | string | undefined; + y2?: number | string | undefined; + y?: number | string | undefined; + yChannelSelector?: string | undefined; + z?: number | string | undefined; + zoomAndPan?: string | undefined; + } + + interface WebViewHTMLAttributes extends HTMLAttributes { + allowFullScreen?: boolean | undefined; + allowpopups?: boolean | undefined; + autosize?: boolean | undefined; + blinkfeatures?: string | undefined; + disableblinkfeatures?: string | undefined; + disableguestresize?: boolean | undefined; + disablewebsecurity?: boolean | undefined; + guestinstance?: string | undefined; + httpreferrer?: string | undefined; + nodeintegration?: boolean | undefined; + partition?: string | undefined; + plugins?: boolean | undefined; + preload?: string | undefined; + src?: string | undefined; + useragent?: string | undefined; + webpreferences?: string | undefined; + } + + // TODO: Move to react-dom + type HTMLElementType = + | "a" + | "abbr" + | "address" + | "area" + | "article" + | "aside" + | "audio" + | "b" + | "base" + | "bdi" + | "bdo" + | "big" + | "blockquote" + | "body" + | "br" + | "button" + | "canvas" + | "caption" + | "center" + | "cite" + | "code" + | "col" + | "colgroup" + | "data" + | "datalist" + | "dd" + | "del" + | "details" + | "dfn" + | "dialog" + | "div" + | "dl" + | "dt" + | "em" + | "embed" + | "fieldset" + | "figcaption" + | "figure" + | "footer" + | "form" + | "h1" + | "h2" + | "h3" + | "h4" + | "h5" + | "h6" + | "head" + | "header" + | "hgroup" + | "hr" + | "html" + | "i" + | "iframe" + | "img" + | "input" + | "ins" + | "kbd" + | "keygen" + | "label" + | "legend" + | "li" + | "link" + | "main" + | "map" + | "mark" + | "menu" + | "menuitem" + | "meta" + | "meter" + | "nav" + | "noscript" + | "object" + | "ol" + | "optgroup" + | "option" + | "output" + | "p" + | "param" + | "picture" + | "pre" + | "progress" + | "q" + | "rp" + | "rt" + | "ruby" + | "s" + | "samp" + | "search" + | "slot" + | "script" + | "section" + | "select" + | "small" + | "source" + | "span" + | "strong" + | "style" + | "sub" + | "summary" + | "sup" + | "table" + | "template" + | "tbody" + | "td" + | "textarea" + | "tfoot" + | "th" + | "thead" + | "time" + | "title" + | "tr" + | "track" + | "u" + | "ul" + | "var" + | "video" + | "wbr" + | "webview"; + + // TODO: Move to react-dom + type SVGElementType = + | "animate" + | "circle" + | "clipPath" + | "defs" + | "desc" + | "ellipse" + | "feBlend" + | "feColorMatrix" + | "feComponentTransfer" + | "feComposite" + | "feConvolveMatrix" + | "feDiffuseLighting" + | "feDisplacementMap" + | "feDistantLight" + | "feDropShadow" + | "feFlood" + | "feFuncA" + | "feFuncB" + | "feFuncG" + | "feFuncR" + | "feGaussianBlur" + | "feImage" + | "feMerge" + | "feMergeNode" + | "feMorphology" + | "feOffset" + | "fePointLight" + | "feSpecularLighting" + | "feSpotLight" + | "feTile" + | "feTurbulence" + | "filter" + | "foreignObject" + | "g" + | "image" + | "line" + | "linearGradient" + | "marker" + | "mask" + | "metadata" + | "path" + | "pattern" + | "polygon" + | "polyline" + | "radialGradient" + | "rect" + | "stop" + | "svg" + | "switch" + | "symbol" + | "text" + | "textPath" + | "tspan" + | "use" + | "view"; + + // + // Browser Interfaces + // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts + // ---------------------------------------------------------------------- + + interface AbstractView { + styleMedia: StyleMedia; + document: Document; + } + + interface Touch { + identifier: number; + target: EventTarget; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + pageX: number; + pageY: number; + } + + interface TouchList { + [index: number]: Touch; + length: number; + item(index: number): Touch; + identifiedTouch(identifier: number): Touch; + } + + // + // Error Interfaces + // ---------------------------------------------------------------------- + interface ErrorInfo { + /** + * Captures which component contained the exception, and its ancestors. + */ + componentStack?: string | null; + digest?: string | null; + } + + // Keep in sync with JSX namespace in ./jsx-runtime.d.ts and ./jsx-dev-runtime.d.ts + namespace JSX { + // We don't just alias React.ElementType because React.ElementType + // historically does more than we need it to. + // E.g. it also contains .propTypes and so TS also verifies the declared + // props type does match the declared .propTypes. + // But if libraries declared their .propTypes but not props type, + // or they mismatch, you won't be able to use the class component + // as a JSX.ElementType. + // We could fix this everywhere but we're ultimately not interested in + // .propTypes assignability so we might as well drop it entirely here to + // reduce the work of the type-checker. + // TODO: Check impact of making React.ElementType

= React.JSXElementConstructor

+ type ElementType = string | React.JSXElementConstructor; + interface Element extends React.ReactElement {} + interface ElementClass extends React.Component { + render(): React.ReactNode; + } + interface ElementAttributesProperty { + props: {}; + } + interface ElementChildrenAttribute { + children: {}; + } + + // We can't recurse forever because `type` can't be self-referential; + // let's assume it's reasonable to do a single React.lazy() around a single React.memo() / vice-versa + type LibraryManagedAttributes = C extends + React.MemoExoticComponent | React.LazyExoticComponent + ? T extends React.MemoExoticComponent | React.LazyExoticComponent + ? ReactManagedAttributes + : ReactManagedAttributes + : ReactManagedAttributes; + + interface IntrinsicAttributes extends React.Attributes {} + interface IntrinsicClassAttributes extends React.ClassAttributes {} + + interface IntrinsicElements { + // HTML + a: React.DetailedHTMLProps, HTMLAnchorElement>; + abbr: React.DetailedHTMLProps, HTMLElement>; + address: React.DetailedHTMLProps, HTMLElement>; + area: React.DetailedHTMLProps, HTMLAreaElement>; + article: React.DetailedHTMLProps, HTMLElement>; + aside: React.DetailedHTMLProps, HTMLElement>; + audio: React.DetailedHTMLProps, HTMLAudioElement>; + b: React.DetailedHTMLProps, HTMLElement>; + base: React.DetailedHTMLProps, HTMLBaseElement>; + bdi: React.DetailedHTMLProps, HTMLElement>; + bdo: React.DetailedHTMLProps, HTMLElement>; + big: React.DetailedHTMLProps, HTMLElement>; + blockquote: React.DetailedHTMLProps, HTMLQuoteElement>; + body: React.DetailedHTMLProps, HTMLBodyElement>; + br: React.DetailedHTMLProps, HTMLBRElement>; + button: React.DetailedHTMLProps, HTMLButtonElement>; + canvas: React.DetailedHTMLProps, HTMLCanvasElement>; + caption: React.DetailedHTMLProps, HTMLElement>; + center: React.DetailedHTMLProps, HTMLElement>; + cite: React.DetailedHTMLProps, HTMLElement>; + code: React.DetailedHTMLProps, HTMLElement>; + col: React.DetailedHTMLProps, HTMLTableColElement>; + colgroup: React.DetailedHTMLProps, HTMLTableColElement>; + data: React.DetailedHTMLProps, HTMLDataElement>; + datalist: React.DetailedHTMLProps, HTMLDataListElement>; + dd: React.DetailedHTMLProps, HTMLElement>; + del: React.DetailedHTMLProps, HTMLModElement>; + details: React.DetailedHTMLProps, HTMLDetailsElement>; + dfn: React.DetailedHTMLProps, HTMLElement>; + dialog: React.DetailedHTMLProps, HTMLDialogElement>; + div: React.DetailedHTMLProps, HTMLDivElement>; + dl: React.DetailedHTMLProps, HTMLDListElement>; + dt: React.DetailedHTMLProps, HTMLElement>; + em: React.DetailedHTMLProps, HTMLElement>; + embed: React.DetailedHTMLProps, HTMLEmbedElement>; + fieldset: React.DetailedHTMLProps, HTMLFieldSetElement>; + figcaption: React.DetailedHTMLProps, HTMLElement>; + figure: React.DetailedHTMLProps, HTMLElement>; + footer: React.DetailedHTMLProps, HTMLElement>; + form: React.DetailedHTMLProps, HTMLFormElement>; + h1: React.DetailedHTMLProps, HTMLHeadingElement>; + h2: React.DetailedHTMLProps, HTMLHeadingElement>; + h3: React.DetailedHTMLProps, HTMLHeadingElement>; + h4: React.DetailedHTMLProps, HTMLHeadingElement>; + h5: React.DetailedHTMLProps, HTMLHeadingElement>; + h6: React.DetailedHTMLProps, HTMLHeadingElement>; + head: React.DetailedHTMLProps, HTMLHeadElement>; + header: React.DetailedHTMLProps, HTMLElement>; + hgroup: React.DetailedHTMLProps, HTMLElement>; + hr: React.DetailedHTMLProps, HTMLHRElement>; + html: React.DetailedHTMLProps, HTMLHtmlElement>; + i: React.DetailedHTMLProps, HTMLElement>; + iframe: React.DetailedHTMLProps, HTMLIFrameElement>; + img: React.DetailedHTMLProps, HTMLImageElement>; + input: React.DetailedHTMLProps, HTMLInputElement>; + ins: React.DetailedHTMLProps, HTMLModElement>; + kbd: React.DetailedHTMLProps, HTMLElement>; + keygen: React.DetailedHTMLProps, HTMLElement>; + label: React.DetailedHTMLProps, HTMLLabelElement>; + legend: React.DetailedHTMLProps, HTMLLegendElement>; + li: React.DetailedHTMLProps, HTMLLIElement>; + link: React.DetailedHTMLProps, HTMLLinkElement>; + main: React.DetailedHTMLProps, HTMLElement>; + map: React.DetailedHTMLProps, HTMLMapElement>; + mark: React.DetailedHTMLProps, HTMLElement>; + menu: React.DetailedHTMLProps, HTMLElement>; + menuitem: React.DetailedHTMLProps, HTMLElement>; + meta: React.DetailedHTMLProps, HTMLMetaElement>; + meter: React.DetailedHTMLProps, HTMLMeterElement>; + nav: React.DetailedHTMLProps, HTMLElement>; + noindex: React.DetailedHTMLProps, HTMLElement>; + noscript: React.DetailedHTMLProps, HTMLElement>; + object: React.DetailedHTMLProps, HTMLObjectElement>; + ol: React.DetailedHTMLProps, HTMLOListElement>; + optgroup: React.DetailedHTMLProps, HTMLOptGroupElement>; + option: React.DetailedHTMLProps, HTMLOptionElement>; + output: React.DetailedHTMLProps, HTMLOutputElement>; + p: React.DetailedHTMLProps, HTMLParagraphElement>; + param: React.DetailedHTMLProps, HTMLParamElement>; + picture: React.DetailedHTMLProps, HTMLElement>; + pre: React.DetailedHTMLProps, HTMLPreElement>; + progress: React.DetailedHTMLProps, HTMLProgressElement>; + q: React.DetailedHTMLProps, HTMLQuoteElement>; + rp: React.DetailedHTMLProps, HTMLElement>; + rt: React.DetailedHTMLProps, HTMLElement>; + ruby: React.DetailedHTMLProps, HTMLElement>; + s: React.DetailedHTMLProps, HTMLElement>; + samp: React.DetailedHTMLProps, HTMLElement>; + search: React.DetailedHTMLProps, HTMLElement>; + slot: React.DetailedHTMLProps, HTMLSlotElement>; + script: React.DetailedHTMLProps, HTMLScriptElement>; + section: React.DetailedHTMLProps, HTMLElement>; + select: React.DetailedHTMLProps, HTMLSelectElement>; + small: React.DetailedHTMLProps, HTMLElement>; + source: React.DetailedHTMLProps, HTMLSourceElement>; + span: React.DetailedHTMLProps, HTMLSpanElement>; + strong: React.DetailedHTMLProps, HTMLElement>; + style: React.DetailedHTMLProps, HTMLStyleElement>; + sub: React.DetailedHTMLProps, HTMLElement>; + summary: React.DetailedHTMLProps, HTMLElement>; + sup: React.DetailedHTMLProps, HTMLElement>; + table: React.DetailedHTMLProps, HTMLTableElement>; + template: React.DetailedHTMLProps, HTMLTemplateElement>; + tbody: React.DetailedHTMLProps, HTMLTableSectionElement>; + td: React.DetailedHTMLProps, HTMLTableDataCellElement>; + textarea: React.DetailedHTMLProps, HTMLTextAreaElement>; + tfoot: React.DetailedHTMLProps, HTMLTableSectionElement>; + th: React.DetailedHTMLProps, HTMLTableHeaderCellElement>; + thead: React.DetailedHTMLProps, HTMLTableSectionElement>; + time: React.DetailedHTMLProps, HTMLTimeElement>; + title: React.DetailedHTMLProps, HTMLTitleElement>; + tr: React.DetailedHTMLProps, HTMLTableRowElement>; + track: React.DetailedHTMLProps, HTMLTrackElement>; + u: React.DetailedHTMLProps, HTMLElement>; + ul: React.DetailedHTMLProps, HTMLUListElement>; + "var": React.DetailedHTMLProps, HTMLElement>; + video: React.DetailedHTMLProps, HTMLVideoElement>; + wbr: React.DetailedHTMLProps, HTMLElement>; + webview: React.DetailedHTMLProps, HTMLWebViewElement>; + + // SVG + svg: React.SVGProps; + + animate: React.SVGProps; // TODO: It is SVGAnimateElement but is not in TypeScript's lib.dom.d.ts for now. + animateMotion: React.SVGProps; + animateTransform: React.SVGProps; // TODO: It is SVGAnimateTransformElement but is not in TypeScript's lib.dom.d.ts for now. + circle: React.SVGProps; + clipPath: React.SVGProps; + defs: React.SVGProps; + desc: React.SVGProps; + ellipse: React.SVGProps; + feBlend: React.SVGProps; + feColorMatrix: React.SVGProps; + feComponentTransfer: React.SVGProps; + feComposite: React.SVGProps; + feConvolveMatrix: React.SVGProps; + feDiffuseLighting: React.SVGProps; + feDisplacementMap: React.SVGProps; + feDistantLight: React.SVGProps; + feDropShadow: React.SVGProps; + feFlood: React.SVGProps; + feFuncA: React.SVGProps; + feFuncB: React.SVGProps; + feFuncG: React.SVGProps; + feFuncR: React.SVGProps; + feGaussianBlur: React.SVGProps; + feImage: React.SVGProps; + feMerge: React.SVGProps; + feMergeNode: React.SVGProps; + feMorphology: React.SVGProps; + feOffset: React.SVGProps; + fePointLight: React.SVGProps; + feSpecularLighting: React.SVGProps; + feSpotLight: React.SVGProps; + feTile: React.SVGProps; + feTurbulence: React.SVGProps; + filter: React.SVGProps; + foreignObject: React.SVGProps; + g: React.SVGProps; + image: React.SVGProps; + line: React.SVGLineElementAttributes; + linearGradient: React.SVGProps; + marker: React.SVGProps; + mask: React.SVGProps; + metadata: React.SVGProps; + mpath: React.SVGProps; + path: React.SVGProps; + pattern: React.SVGProps; + polygon: React.SVGProps; + polyline: React.SVGProps; + radialGradient: React.SVGProps; + rect: React.SVGProps; + set: React.SVGProps; + stop: React.SVGProps; + switch: React.SVGProps; + symbol: React.SVGProps; + text: React.SVGTextElementAttributes; + textPath: React.SVGProps; + tspan: React.SVGProps; + use: React.SVGProps; + view: React.SVGProps; + } + } +} + +type InexactPartial = { [K in keyof T]?: T[K] | undefined }; + +// Any prop that has a default prop becomes optional, but its type is unchanged +// Undeclared default props are augmented into the resulting allowable attributes +// If declared props have indexed properties, ignore default props entirely as keyof gets widened +// Wrap in an outer-level conditional type to allow distribution over props that are unions +type Defaultize = P extends any ? string extends keyof P ? P + : + & Pick> + & InexactPartial>> + & InexactPartial>> + : never; + +type ReactManagedAttributes = C extends { defaultProps: infer D } ? Defaultize + : P; diff --git a/node_modules/@types/react/jsx-dev-runtime.d.ts b/node_modules/@types/react/jsx-dev-runtime.d.ts new file mode 100644 index 00000000..d28644c6 --- /dev/null +++ b/node_modules/@types/react/jsx-dev-runtime.d.ts @@ -0,0 +1,45 @@ +import * as React from "./"; +export { Fragment } from "./"; + +export namespace JSX { + type ElementType = React.JSX.ElementType; + interface Element extends React.JSX.Element {} + interface ElementClass extends React.JSX.ElementClass {} + interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {} + interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {} + type LibraryManagedAttributes = React.JSX.LibraryManagedAttributes; + interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {} + interface IntrinsicClassAttributes extends React.JSX.IntrinsicClassAttributes {} + interface IntrinsicElements extends React.JSX.IntrinsicElements {} +} + +export interface JSXSource { + /** + * The source file where the element originates from. + */ + fileName?: string | undefined; + + /** + * The line number where the element was created. + */ + lineNumber?: number | undefined; + + /** + * The column number where the element was created. + */ + columnNumber?: number | undefined; +} + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsxDEV( + type: React.ElementType, + props: unknown, + key: React.Key | undefined, + isStatic: boolean, + source?: JSXSource, + self?: unknown, +): React.ReactElement; diff --git a/node_modules/@types/react/jsx-runtime.d.ts b/node_modules/@types/react/jsx-runtime.d.ts new file mode 100644 index 00000000..e9fea27d --- /dev/null +++ b/node_modules/@types/react/jsx-runtime.d.ts @@ -0,0 +1,36 @@ +import * as React from "./"; +export { Fragment } from "./"; + +export namespace JSX { + type ElementType = React.JSX.ElementType; + interface Element extends React.JSX.Element {} + interface ElementClass extends React.JSX.ElementClass {} + interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {} + interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {} + type LibraryManagedAttributes = React.JSX.LibraryManagedAttributes; + interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {} + interface IntrinsicClassAttributes extends React.JSX.IntrinsicClassAttributes {} + interface IntrinsicElements extends React.JSX.IntrinsicElements {} +} + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsx( + type: React.ElementType, + props: unknown, + key?: React.Key, +): React.ReactElement; + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsxs( + type: React.ElementType, + props: unknown, + key?: React.Key, +): React.ReactElement; diff --git a/node_modules/@types/react/package.json b/node_modules/@types/react/package.json new file mode 100644 index 00000000..f1151f13 --- /dev/null +++ b/node_modules/@types/react/package.json @@ -0,0 +1,210 @@ +{ + "name": "@types/react", + "version": "19.1.8", + "description": "TypeScript definitions for react", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react", + "license": "MIT", + "contributors": [ + { + "name": "Asana", + "url": "https://asana.com" + }, + { + "name": "AssureSign", + "url": "http://www.assuresign.com" + }, + { + "name": "Microsoft", + "url": "https://microsoft.com" + }, + { + "name": "John Reilly", + "githubUsername": "johnnyreilly", + "url": "https://github.com/johnnyreilly" + }, + { + "name": "Benoit Benezech", + "githubUsername": "bbenezech", + "url": "https://github.com/bbenezech" + }, + { + "name": "Patricio Zavolinsky", + "githubUsername": "pzavolinsky", + "url": "https://github.com/pzavolinsky" + }, + { + "name": "Eric Anderson", + "githubUsername": "ericanderson", + "url": "https://github.com/ericanderson" + }, + { + "name": "Dovydas Navickas", + "githubUsername": "DovydasNavickas", + "url": "https://github.com/DovydasNavickas" + }, + { + "name": "Josh Rutherford", + "githubUsername": "theruther4d", + "url": "https://github.com/theruther4d" + }, + { + "name": "Guilherme Hübner", + "githubUsername": "guilhermehubner", + "url": "https://github.com/guilhermehubner" + }, + { + "name": "Ferdy Budhidharma", + "githubUsername": "ferdaber", + "url": "https://github.com/ferdaber" + }, + { + "name": "Johann Rakotoharisoa", + "githubUsername": "jrakotoharisoa", + "url": "https://github.com/jrakotoharisoa" + }, + { + "name": "Olivier Pascal", + "githubUsername": "pascaloliv", + "url": "https://github.com/pascaloliv" + }, + { + "name": "Martin Hochel", + "githubUsername": "hotell", + "url": "https://github.com/hotell" + }, + { + "name": "Frank Li", + "githubUsername": "franklixuefei", + "url": "https://github.com/franklixuefei" + }, + { + "name": "Jessica Franco", + "githubUsername": "Jessidhia", + "url": "https://github.com/Jessidhia" + }, + { + "name": "Saransh Kataria", + "githubUsername": "saranshkataria", + "url": "https://github.com/saranshkataria" + }, + { + "name": "Kanitkorn Sujautra", + "githubUsername": "lukyth", + "url": "https://github.com/lukyth" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Kyle Scully", + "githubUsername": "zieka", + "url": "https://github.com/zieka" + }, + { + "name": "Cong Zhang", + "githubUsername": "dancerphil", + "url": "https://github.com/dancerphil" + }, + { + "name": "Dimitri Mitropoulos", + "githubUsername": "dimitropoulos", + "url": "https://github.com/dimitropoulos" + }, + { + "name": "JongChan Choi", + "githubUsername": "disjukr", + "url": "https://github.com/disjukr" + }, + { + "name": "Victor Magalhães", + "githubUsername": "vhfmag", + "url": "https://github.com/vhfmag" + }, + { + "name": "Priyanshu Rav", + "githubUsername": "priyanshurav", + "url": "https://github.com/priyanshurav" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + }, + { + "name": "Matt Pocock", + "githubUsername": "mattpocock", + "url": "https://github.com/mattpocock" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=5.0": { + "*": [ + "ts5.0/*" + ] + } + }, + "exports": { + ".": { + "types@<=5.0": { + "default": "./ts5.0/index.d.ts" + }, + "types": { + "default": "./index.d.ts" + } + }, + "./canary": { + "types@<=5.0": { + "default": "./ts5.0/canary.d.ts" + }, + "types": { + "default": "./canary.d.ts" + } + }, + "./compiler-runtime": { + "types": { + "default": "./compiler-runtime.d.ts" + } + }, + "./experimental": { + "types@<=5.0": { + "default": "./ts5.0/experimental.d.ts" + }, + "types": { + "default": "./experimental.d.ts" + } + }, + "./jsx-runtime": { + "types@<=5.0": { + "default": "./ts5.0/jsx-runtime.d.ts" + }, + "types": { + "default": "./jsx-runtime.d.ts" + } + }, + "./jsx-dev-runtime": { + "types@<=5.0": { + "default": "./ts5.0/jsx-dev-runtime.d.ts" + }, + "types": { + "default": "./jsx-dev-runtime.d.ts" + } + }, + "./package.json": "./package.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/react" + }, + "scripts": {}, + "dependencies": { + "csstype": "^3.0.2" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "585a01b49a65d7fbb67c6837bf92323a5aeed126fb67079897cfc5b780c19454", + "typeScriptVersion": "5.1" +} \ No newline at end of file diff --git a/node_modules/@types/react/ts5.0/canary.d.ts b/node_modules/@types/react/ts5.0/canary.d.ts new file mode 100644 index 00000000..9215a16b --- /dev/null +++ b/node_modules/@types/react/ts5.0/canary.d.ts @@ -0,0 +1,35 @@ +/** + * These are types for things that are present in the React `canary` release channel. + * + * To load the types declared here in an actual project, there are three ways. The easiest one, + * if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section, + * is to add `"react/canary"` to the `"types"` array. + * + * Alternatively, a specific import syntax can to be used from a typescript file. + * This module does not exist in reality, which is why the {} is important: + * + * ```ts + * import {} from 'react/canary' + * ``` + * + * It is also possible to include it through a triple-slash reference: + * + * ```ts + * /// + * ``` + * + * Either the import or the reference only needs to appear once, anywhere in the project. + */ + +// See https://github.com/facebook/react/blob/main/packages/react/src/React.js to see how the exports are declared, + +import React = require("."); + +export {}; + +declare const UNDEFINED_VOID_ONLY: unique symbol; +type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never }; + +declare module "." { + export function unstable_useCacheRefresh(): () => void; +} diff --git a/node_modules/@types/react/ts5.0/experimental.d.ts b/node_modules/@types/react/ts5.0/experimental.d.ts new file mode 100644 index 00000000..c690165a --- /dev/null +++ b/node_modules/@types/react/ts5.0/experimental.d.ts @@ -0,0 +1,243 @@ +/** + * These are types for things that are present in the `experimental` builds of React but not yet + * on a stable build. + * + * Once they are promoted to stable they can just be moved to the main index file. + * + * To load the types declared here in an actual project, there are three ways. The easiest one, + * if your `tsconfig.json` already has a `"types"` array in the `"compilerOptions"` section, + * is to add `"react/experimental"` to the `"types"` array. + * + * Alternatively, a specific import syntax can to be used from a typescript file. + * This module does not exist in reality, which is why the {} is important: + * + * ```ts + * import {} from 'react/experimental' + * ``` + * + * It is also possible to include it through a triple-slash reference: + * + * ```ts + * /// + * ``` + * + * Either the import or the reference only needs to appear once, anywhere in the project. + */ + +// See https://github.com/facebook/react/blob/master/packages/react/src/React.js to see how the exports are declared, +// and https://github.com/facebook/react/blob/master/packages/shared/ReactFeatureFlags.js to verify which APIs are +// flagged experimental or not. Experimental APIs will be tagged with `__EXPERIMENTAL__`. +// +// For the inputs of types exported as simply a fiber tag, the `beginWork` function of ReactFiberBeginWork.js +// is a good place to start looking for details; it generally calls prop validation functions or delegates +// all tasks done as part of the render phase (the concurrent part of the React update cycle). +// +// Suspense-related handling can be found in ReactFiberThrow.js. + +import React = require("./canary"); + +export {}; + +declare const UNDEFINED_VOID_ONLY: unique symbol; +type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never }; + +declare module "." { + export interface SuspenseProps { + /** + * The presence of this prop indicates that the content is computationally expensive to render. + * In other words, the tree is CPU bound and not I/O bound (e.g. due to fetching data). + * @see {@link https://github.com/facebook/react/pull/19936} + */ + unstable_expectedLoadTime?: number | undefined; + } + + export type SuspenseListRevealOrder = "forwards" | "backwards" | "together" | "independent"; + export type SuspenseListTailMode = "collapsed" | "hidden" | "visible"; + + export interface SuspenseListCommonProps { + } + + interface DirectionalSuspenseListProps extends SuspenseListCommonProps { + /** + * Note that SuspenseList require more than one child; + * it is a runtime warning to provide only a single child. + * + * It does, however, allow those children to be wrapped inside a single + * level of ``. + */ + children: Iterable | AsyncIterable; + /** + * Defines the order in which the `SuspenseList` children should be revealed. + */ + revealOrder: "forwards" | "backwards" | "unstable_legacy-backwards"; + /** + * Dictates how unloaded items in a SuspenseList is shown. + * + * - By default, `SuspenseList` will show all fallbacks in the list. + * - `collapsed` shows only the next fallback in the list. + * - `hidden` doesn't show any unloaded items. + * - `visible` shows all fallbacks in the list. + */ + tail: SuspenseListTailMode; + } + + interface NonDirectionalSuspenseListProps extends SuspenseListCommonProps { + children: ReactNode; + /** + * Defines the order in which the `SuspenseList` children should be revealed. + */ + revealOrder: Exclude | undefined; + /** + * The tail property is invalid when not using the `forwards` or `backwards` reveal orders. + */ + tail?: never; + } + + export type SuspenseListProps = DirectionalSuspenseListProps | NonDirectionalSuspenseListProps; + + /** + * `SuspenseList` helps coordinate many components that can suspend by orchestrating the order + * in which these components are revealed to the user. + * + * When multiple components need to fetch data, this data may arrive in an unpredictable order. + * However, if you wrap these items in a `SuspenseList`, React will not show an item in the list + * until previous items have been displayed (this behavior is adjustable). + * + * @see https://reactjs.org/docs/concurrent-mode-reference.html#suspenselist + * @see https://reactjs.org/docs/concurrent-mode-patterns.html#suspenselist + */ + export const unstable_SuspenseList: ExoticComponent; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + export function experimental_useEffectEvent(event: T): T; + + type Reference = object; + type TaintableUniqueValue = string | bigint | ArrayBufferView; + function experimental_taintUniqueValue( + message: string | undefined, + lifetime: Reference, + value: TaintableUniqueValue, + ): void; + function experimental_taintObjectReference(message: string | undefined, object: Reference): void; + + export interface ViewTransitionInstance { + /** + * The {@link ViewTransitionProps name} that was used in the corresponding {@link ViewTransition} component or `"auto"` if the `name` prop was omitted. + */ + name: string; + } + + export type ViewTransitionClassPerType = Record<"default" | (string & {}), "none" | "auto" | (string & {})>; + export type ViewTransitionClass = ViewTransitionClassPerType | ViewTransitionClassPerType[string]; + + export interface ViewTransitionProps { + children?: ReactNode | undefined; + /** + * Assigns the {@link https://developer.chrome.com/blog/view-transitions-update-io24#view-transition-class `view-transition-class`} class to the underlying DOM node. + */ + default?: ViewTransitionClass | undefined; + /** + * Combined with {@link className} if this `` or its parent Component is mounted and there's no other with the same name being deleted. + * `"none"` is a special value that deactivates the view transition name under that condition. + */ + enter?: ViewTransitionClass | undefined; + /** + * Combined with {@link className} if this `` or its parent Component is unmounted and there's no other with the same name being deleted. + * `"none"` is a special value that deactivates the view transition name under that condition. + */ + exit?: ViewTransitionClass | undefined; + /** + * "auto" will automatically assign a view-transition-name to the inner DOM node. + * That way you can add a View Transition to a Component without controlling its DOM nodes styling otherwise. + * + * A difference between this and the browser's built-in view-transition-name: auto is that switching the DOM nodes within the `` component preserves the same name so this example cross-fades between the DOM nodes instead of causing an exit and enter. + * @default "auto" + */ + name?: "auto" | (string & {}) | undefined; + /** + * The `` or its parent Component is mounted and there's no other `` with the same name being deleted. + */ + onEnter?: (instance: ViewTransitionInstance, types: Array) => void; + /** + * The `` or its parent Component is unmounted and there's no other `` with the same name being deleted. + */ + onExit?: (instance: ViewTransitionInstance, types: Array) => void; + /** + * This `` is being mounted and another `` instance with the same name is being unmounted elsewhere. + */ + onShare?: (instance: ViewTransitionInstance, types: Array) => void; + /** + * The content of `` has changed either due to DOM mutations or because an inner child `` has resized. + */ + onUpdate?: (instance: ViewTransitionInstance, types: Array) => void; + ref?: Ref | undefined; + /** + * Combined with {@link className} if this `` is being mounted and another instance with the same name is being unmounted elsewhere. + * `"none"` is a special value that deactivates the view transition name under that condition. + */ + share?: ViewTransitionClass | undefined; + /** + * Combined with {@link className} if the content of this `` has changed either due to DOM mutations or because an inner child has resized. + * `"none"` is a special value that deactivates the view transition name under that condition. + */ + update?: ViewTransitionClass | undefined; + } + + /** + * Opt-in for using {@link https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API View Transitions} in React. + * View Transitions only trigger for async updates like {@link startTransition}, {@link useDeferredValue}, Actions or <{@link Suspense}> revealing from fallback to content. + * Synchronous updates provide an opt-out but also guarantee that they commit immediately which View Transitions can't. + * + * @see {@link https://github.com/facebook/react/pull/31975} + */ + export const unstable_ViewTransition: ExoticComponent; + + export function unstable_addTransitionType(type: string): void; + + // @enableGestureTransition + // Implemented by the specific renderer e.g. `react-dom`. + // Keep in mind that augmented interfaces merge their JSDoc so if you put + // JSDoc here and in the renderer, the IDE will display both. + export interface GestureProvider {} + export interface GestureOptions { + rangeStart?: number | undefined; + rangeEnd?: number | undefined; + } + /** */ + export function unstable_startGestureTransition( + provider: GestureProvider, + scope: () => void, + options?: GestureOptions, + ): () => void; + + // @enableFragmentRefs + export interface FragmentInstance {} + + export interface FragmentProps { + ref?: Ref | undefined; + } + + // @enableActivity + export interface ActivityProps { + /** + * @default "visible" + */ + mode?: + | "hidden" + | "visible" + | undefined; + children: ReactNode; + } + + /** */ + export const unstable_Activity: ExoticComponent; + + // @enableSrcObject + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES { + srcObject: Blob; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES { + srcObject: Blob | MediaSource | MediaStream; + } +} diff --git a/node_modules/@types/react/ts5.0/global.d.ts b/node_modules/@types/react/ts5.0/global.d.ts new file mode 100644 index 00000000..6770d08e --- /dev/null +++ b/node_modules/@types/react/ts5.0/global.d.ts @@ -0,0 +1,165 @@ +/* +React projects that don't include the DOM library need these interfaces to compile. +React Native applications use React, but there is no DOM available. The JavaScript runtime +is ES6/ES2015 only. These definitions allow such projects to compile with only `--lib ES6`. + +Warning: all of these interfaces are empty. If you want type definitions for various properties +(such as HTMLInputElement.prototype.value), you need to add `--lib DOM` (via command line or tsconfig.json). +*/ + +interface Event {} +interface AnimationEvent extends Event {} +interface ClipboardEvent extends Event {} +interface CompositionEvent extends Event {} +interface DragEvent extends Event {} +interface FocusEvent extends Event {} +interface InputEvent extends Event {} +interface KeyboardEvent extends Event {} +interface MouseEvent extends Event {} +interface TouchEvent extends Event {} +interface PointerEvent extends Event {} +interface ToggleEvent extends Event {} +interface TransitionEvent extends Event {} +interface UIEvent extends Event {} +interface WheelEvent extends Event {} + +interface EventTarget {} +interface Document {} +interface DataTransfer {} +interface StyleMedia {} + +interface Element {} +interface DocumentFragment {} + +interface HTMLElement extends Element {} +interface HTMLAnchorElement extends HTMLElement {} +interface HTMLAreaElement extends HTMLElement {} +interface HTMLAudioElement extends HTMLElement {} +interface HTMLBaseElement extends HTMLElement {} +interface HTMLBodyElement extends HTMLElement {} +interface HTMLBRElement extends HTMLElement {} +interface HTMLButtonElement extends HTMLElement {} +interface HTMLCanvasElement extends HTMLElement {} +interface HTMLDataElement extends HTMLElement {} +interface HTMLDataListElement extends HTMLElement {} +interface HTMLDetailsElement extends HTMLElement {} +interface HTMLDialogElement extends HTMLElement {} +interface HTMLDivElement extends HTMLElement {} +interface HTMLDListElement extends HTMLElement {} +interface HTMLEmbedElement extends HTMLElement {} +interface HTMLFieldSetElement extends HTMLElement {} +interface HTMLFormElement extends HTMLElement {} +interface HTMLHeadingElement extends HTMLElement {} +interface HTMLHeadElement extends HTMLElement {} +interface HTMLHRElement extends HTMLElement {} +interface HTMLHtmlElement extends HTMLElement {} +interface HTMLIFrameElement extends HTMLElement {} +interface HTMLImageElement extends HTMLElement {} +interface HTMLInputElement extends HTMLElement {} +interface HTMLModElement extends HTMLElement {} +interface HTMLLabelElement extends HTMLElement {} +interface HTMLLegendElement extends HTMLElement {} +interface HTMLLIElement extends HTMLElement {} +interface HTMLLinkElement extends HTMLElement {} +interface HTMLMapElement extends HTMLElement {} +interface HTMLMetaElement extends HTMLElement {} +interface HTMLMeterElement extends HTMLElement {} +interface HTMLObjectElement extends HTMLElement {} +interface HTMLOListElement extends HTMLElement {} +interface HTMLOptGroupElement extends HTMLElement {} +interface HTMLOptionElement extends HTMLElement {} +interface HTMLOutputElement extends HTMLElement {} +interface HTMLParagraphElement extends HTMLElement {} +interface HTMLParamElement extends HTMLElement {} +interface HTMLPreElement extends HTMLElement {} +interface HTMLProgressElement extends HTMLElement {} +interface HTMLQuoteElement extends HTMLElement {} +interface HTMLSlotElement extends HTMLElement {} +interface HTMLScriptElement extends HTMLElement {} +interface HTMLSelectElement extends HTMLElement {} +interface HTMLSourceElement extends HTMLElement {} +interface HTMLSpanElement extends HTMLElement {} +interface HTMLStyleElement extends HTMLElement {} +interface HTMLTableElement extends HTMLElement {} +interface HTMLTableColElement extends HTMLElement {} +interface HTMLTableDataCellElement extends HTMLElement {} +interface HTMLTableHeaderCellElement extends HTMLElement {} +interface HTMLTableRowElement extends HTMLElement {} +interface HTMLTableSectionElement extends HTMLElement {} +interface HTMLTemplateElement extends HTMLElement {} +interface HTMLTextAreaElement extends HTMLElement {} +interface HTMLTimeElement extends HTMLElement {} +interface HTMLTitleElement extends HTMLElement {} +interface HTMLTrackElement extends HTMLElement {} +interface HTMLUListElement extends HTMLElement {} +interface HTMLVideoElement extends HTMLElement {} +interface HTMLWebViewElement extends HTMLElement {} + +interface SVGElement extends Element {} +interface SVGSVGElement extends SVGElement {} +interface SVGCircleElement extends SVGElement {} +interface SVGClipPathElement extends SVGElement {} +interface SVGDefsElement extends SVGElement {} +interface SVGDescElement extends SVGElement {} +interface SVGEllipseElement extends SVGElement {} +interface SVGFEBlendElement extends SVGElement {} +interface SVGFEColorMatrixElement extends SVGElement {} +interface SVGFEComponentTransferElement extends SVGElement {} +interface SVGFECompositeElement extends SVGElement {} +interface SVGFEConvolveMatrixElement extends SVGElement {} +interface SVGFEDiffuseLightingElement extends SVGElement {} +interface SVGFEDisplacementMapElement extends SVGElement {} +interface SVGFEDistantLightElement extends SVGElement {} +interface SVGFEDropShadowElement extends SVGElement {} +interface SVGFEFloodElement extends SVGElement {} +interface SVGFEFuncAElement extends SVGElement {} +interface SVGFEFuncBElement extends SVGElement {} +interface SVGFEFuncGElement extends SVGElement {} +interface SVGFEFuncRElement extends SVGElement {} +interface SVGFEGaussianBlurElement extends SVGElement {} +interface SVGFEImageElement extends SVGElement {} +interface SVGFEMergeElement extends SVGElement {} +interface SVGFEMergeNodeElement extends SVGElement {} +interface SVGFEMorphologyElement extends SVGElement {} +interface SVGFEOffsetElement extends SVGElement {} +interface SVGFEPointLightElement extends SVGElement {} +interface SVGFESpecularLightingElement extends SVGElement {} +interface SVGFESpotLightElement extends SVGElement {} +interface SVGFETileElement extends SVGElement {} +interface SVGFETurbulenceElement extends SVGElement {} +interface SVGFilterElement extends SVGElement {} +interface SVGForeignObjectElement extends SVGElement {} +interface SVGGElement extends SVGElement {} +interface SVGImageElement extends SVGElement {} +interface SVGLineElement extends SVGElement {} +interface SVGLinearGradientElement extends SVGElement {} +interface SVGMarkerElement extends SVGElement {} +interface SVGMaskElement extends SVGElement {} +interface SVGMetadataElement extends SVGElement {} +interface SVGPathElement extends SVGElement {} +interface SVGPatternElement extends SVGElement {} +interface SVGPolygonElement extends SVGElement {} +interface SVGPolylineElement extends SVGElement {} +interface SVGRadialGradientElement extends SVGElement {} +interface SVGRectElement extends SVGElement {} +interface SVGSetElement extends SVGElement {} +interface SVGStopElement extends SVGElement {} +interface SVGSwitchElement extends SVGElement {} +interface SVGSymbolElement extends SVGElement {} +interface SVGTextElement extends SVGElement {} +interface SVGTextPathElement extends SVGElement {} +interface SVGTSpanElement extends SVGElement {} +interface SVGUseElement extends SVGElement {} +interface SVGViewElement extends SVGElement {} + +interface FormData {} +interface Text {} +interface TouchList {} +interface WebGLRenderingContext {} +interface WebGL2RenderingContext {} + +interface TrustedHTML {} + +interface Blob {} +interface MediaStream {} +interface MediaSource {} diff --git a/node_modules/@types/react/ts5.0/index.d.ts b/node_modules/@types/react/ts5.0/index.d.ts new file mode 100644 index 00000000..4832244e --- /dev/null +++ b/node_modules/@types/react/ts5.0/index.d.ts @@ -0,0 +1,4238 @@ +// NOTE: Users of the `experimental` builds of React should add a reference +// to 'react/experimental' in their project. See experimental.d.ts's top comment +// for reference and documentation on how exactly to do it. + +/// + +import * as CSS from "csstype"; + +type NativeAnimationEvent = AnimationEvent; +type NativeClipboardEvent = ClipboardEvent; +type NativeCompositionEvent = CompositionEvent; +type NativeDragEvent = DragEvent; +type NativeFocusEvent = FocusEvent; +type NativeInputEvent = InputEvent; +type NativeKeyboardEvent = KeyboardEvent; +type NativeMouseEvent = MouseEvent; +type NativeTouchEvent = TouchEvent; +type NativePointerEvent = PointerEvent; +type NativeToggleEvent = ToggleEvent; +type NativeTransitionEvent = TransitionEvent; +type NativeUIEvent = UIEvent; +type NativeWheelEvent = WheelEvent; + +/** + * Used to represent DOM API's where users can either pass + * true or false as a boolean or as its equivalent strings. + */ +type Booleanish = boolean | "true" | "false"; + +/** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin MDN} + */ +type CrossOrigin = "anonymous" | "use-credentials" | "" | undefined; + +declare const UNDEFINED_VOID_ONLY: unique symbol; + +/** + * @internal Use `Awaited` instead + */ +// Helper type to enable `Awaited`. +// Must be a copy of the non-thenables of `ReactNode`. +type AwaitedReactNode = + | React.ReactElement + | string + | number + | bigint + | Iterable + | React.ReactPortal + | boolean + | null + | undefined + | React.DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[ + keyof React.DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES + ]; + +/** + * The function returned from an effect passed to {@link React.useEffect useEffect}, + * which can be used to clean up the effect when the component unmounts. + * + * @see {@link https://react.dev/reference/react/useEffect React Docs} + */ +type Destructor = () => void | { [UNDEFINED_VOID_ONLY]: never }; +type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never }; + +// eslint-disable-next-line @definitelytyped/export-just-namespace +export = React; +export as namespace React; + +declare namespace React { + // + // React Elements + // ---------------------------------------------------------------------- + + /** + * Used to retrieve the possible components which accept a given set of props. + * + * Can be passed no type parameters to get a union of all possible components + * and tags. + * + * Is a superset of {@link ComponentType}. + * + * @template P The props to match against. If not passed, defaults to any. + * @template Tag An optional tag to match against. If not passed, attempts to match against all possible tags. + * + * @example + * + * ```tsx + * // All components and tags (img, embed etc.) + * // which accept `src` + * type SrcComponents = ElementType<{ src: any }>; + * ``` + * + * @example + * + * ```tsx + * // All components + * type AllComponents = ElementType; + * ``` + * + * @example + * + * ```tsx + * // All custom components which match `src`, and tags which + * // match `src`, narrowed down to just `audio` and `embed` + * type SrcComponents = ElementType<{ src: any }, 'audio' | 'embed'>; + * ``` + */ + type ElementType

= + | { [K in Tag]: P extends JSX.IntrinsicElements[K] ? K : never }[Tag] + | ComponentType

; + + /** + * Represents any user-defined component, either as a function or a class. + * + * Similar to {@link JSXElementConstructor}, but with extra properties like + * {@link FunctionComponent.defaultProps defaultProps }. + * + * @template P The props the component accepts. + * + * @see {@link ComponentClass} + * @see {@link FunctionComponent} + */ + type ComponentType

= ComponentClass

| FunctionComponent

; + + /** + * Represents any user-defined component, either as a function or a class. + * + * Similar to {@link ComponentType}, but without extra properties like + * {@link FunctionComponent.defaultProps defaultProps }. + * + * @template P The props the component accepts. + */ + type JSXElementConstructor

= + | (( + props: P, + ) => ReactElement | null) + // constructor signature must match React.Component + | (new(props: P, context: any) => Component); + + /** + * Created by {@link createRef}, or {@link useRef} when passed `null`. + * + * @template T The type of the ref's value. + * + * @example + * + * ```tsx + * const ref = createRef(); + * + * ref.current = document.createElement('div'); // Error + * ``` + */ + interface RefObject { + /** + * The current value of the ref. + */ + current: T; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES { + } + /** + * A callback fired whenever the ref's value changes. + * + * @template T The type of the ref's value. + * + * @see {@link https://react.dev/reference/react-dom/components/common#ref-callback React Docs} + * + * @example + * + * ```tsx + *

console.log(node)} /> + * ``` + */ + type RefCallback = { + bivarianceHack( + instance: T | null, + ): + | void + | (() => VoidOrUndefinedOnly) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES + ]; + }["bivarianceHack"]; + + /** + * A union type of all possible shapes for React refs. + * + * @see {@link RefCallback} + * @see {@link RefObject} + */ + + type Ref = RefCallback | RefObject | null; + /** + * @deprecated Use `Ref` instead. String refs are no longer supported. + * If you're typing a library with support for React versions with string refs, use `RefAttributes['ref']` instead. + */ + type LegacyRef = Ref; + /** + * @deprecated Use `ComponentRef` instead + * + * Retrieves the type of the 'ref' prop for a given component type or tag name. + * + * @template C The component type. + * + * @example + * + * ```tsx + * type MyComponentRef = React.ElementRef; + * ``` + * + * @example + * + * ```tsx + * type DivRef = React.ElementRef<'div'>; + * ``` + */ + type ElementRef< + C extends + | ForwardRefExoticComponent + | { new(props: any, context: any): Component } + | ((props: any) => ReactElement | null) + | keyof JSX.IntrinsicElements, + > = ComponentRef; + + type ComponentState = any; + + /** + * A value which uniquely identifies a node among items in an array. + * + * @see {@link https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key React Docs} + */ + type Key = string | number | bigint; + + /** + * @internal The props any component can receive. + * You don't have to add this type. All components automatically accept these props. + * ```tsx + * const Component = () =>
; + * + * ``` + * + * WARNING: The implementation of a component will never have access to these attributes. + * The following example would be incorrect usage because {@link Component} would never have access to `key`: + * ```tsx + * const Component = (props: React.Attributes) => props.key; + * ``` + */ + interface Attributes { + key?: Key | null | undefined; + } + /** + * The props any component accepting refs can receive. + * Class components, built-in browser components (e.g. `div`) and forwardRef components can receive refs and automatically accept these props. + * ```tsx + * const Component = forwardRef(() =>
); + * console.log(current)} /> + * ``` + * + * You only need this type if you manually author the types of props that need to be compatible with legacy refs. + * ```tsx + * interface Props extends React.RefAttributes {} + * declare const Component: React.FunctionComponent; + * ``` + * + * Otherwise it's simpler to directly use {@link Ref} since you can safely use the + * props type to describe to props that a consumer can pass to the component + * as well as describing the props the implementation of a component "sees". + * {@link RefAttributes} is generally not safe to describe both consumer and seen props. + * + * ```tsx + * interface Props extends { + * ref?: React.Ref | undefined; + * } + * declare const Component: React.FunctionComponent; + * ``` + * + * WARNING: The implementation of a component will not have access to the same type in versions of React supporting string refs. + * The following example would be incorrect usage because {@link Component} would never have access to a `ref` with type `string` + * ```tsx + * const Component = (props: React.RefAttributes) => props.ref; + * ``` + */ + interface RefAttributes extends Attributes { + /** + * Allows getting a ref to the component instance. + * Once the component unmounts, React will set `ref.current` to `null` + * (or call the ref with `null` if you passed a callback ref). + * + * @see {@link https://react.dev/learn/referencing-values-with-refs#refs-and-the-dom React Docs} + */ + ref?: Ref | undefined; + } + + /** + * Represents the built-in attributes available to class components. + */ + interface ClassAttributes extends RefAttributes { + } + + /** + * Represents a JSX element. + * + * Where {@link ReactNode} represents everything that can be rendered, `ReactElement` + * only represents JSX. + * + * @template P The type of the props object + * @template T The type of the component or tag + * + * @example + * + * ```tsx + * const element: ReactElement =
; + * ``` + */ + interface ReactElement< + P = unknown, + T extends string | JSXElementConstructor = string | JSXElementConstructor, + > { + type: T; + props: P; + key: string | null; + } + + /** + * @deprecated + */ + interface ReactComponentElement< + T extends keyof JSX.IntrinsicElements | JSXElementConstructor, + P = Pick, Exclude, "key" | "ref">>, + > extends ReactElement> {} + + /** + * @deprecated Use `ReactElement>` + */ + interface FunctionComponentElement

extends ReactElement> { + /** + * @deprecated Use `element.props.ref` instead. + */ + ref?: ("ref" extends keyof P ? P extends { ref?: infer R | undefined } ? R : never : never) | undefined; + } + + /** + * @deprecated Use `ReactElement>` + */ + type CElement> = ComponentElement; + /** + * @deprecated Use `ReactElement>` + */ + interface ComponentElement> extends ReactElement> { + /** + * @deprecated Use `element.props.ref` instead. + */ + ref?: Ref | undefined; + } + + /** + * @deprecated Use {@link ComponentElement} instead. + */ + type ClassicElement

= CElement>; + + // string fallback for custom web-components + /** + * @deprecated Use `ReactElement` + */ + interface DOMElement

| SVGAttributes, T extends Element> + extends ReactElement + { + /** + * @deprecated Use `element.props.ref` instead. + */ + ref: Ref; + } + + // ReactHTML for ReactHTMLElement + interface ReactHTMLElement extends DetailedReactHTMLElement, T> {} + + interface DetailedReactHTMLElement

, T extends HTMLElement> extends DOMElement { + type: HTMLElementType; + } + + // ReactSVG for ReactSVGElement + interface ReactSVGElement extends DOMElement, SVGElement> { + type: SVGElementType; + } + + interface ReactPortal extends ReactElement { + children: ReactNode; + } + + /** + * For internal usage only. + * Different release channels declare additional types of ReactNode this particular release channel accepts. + * App or library types should never augment this interface. + */ + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES {} + + /** + * Represents all of the things React can render. + * + * Where {@link ReactElement} only represents JSX, `ReactNode` represents everything that can be rendered. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/reactnode/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Typing children + * type Props = { children: ReactNode } + * + * const Component = ({ children }: Props) =>

{children}
+ * + * hello + * ``` + * + * @example + * + * ```tsx + * // Typing a custom element + * type Props = { customElement: ReactNode } + * + * const Component = ({ customElement }: Props) =>
{customElement}
+ * + * hello
} /> + * ``` + */ + // non-thenables need to be kept in sync with AwaitedReactNode + type ReactNode = + | ReactElement + | string + | number + | bigint + | Iterable + | ReactPortal + | boolean + | null + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES + ] + | Promise; + + // + // Top Level API + // ---------------------------------------------------------------------- + + // DOM Elements + // TODO: generalize this to everything in `keyof ReactHTML`, not just "input" + function createElement( + type: "input", + props?: InputHTMLAttributes & ClassAttributes | null, + ...children: ReactNode[] + ): DetailedReactHTMLElement, HTMLInputElement>; + function createElement

, T extends HTMLElement>( + type: HTMLElementType, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): DetailedReactHTMLElement; + function createElement

, T extends SVGElement>( + type: SVGElementType, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): ReactSVGElement; + function createElement

, T extends Element>( + type: string, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): DOMElement; + + // Custom components + + function createElement

( + type: FunctionComponent

, + props?: Attributes & P | null, + ...children: ReactNode[] + ): FunctionComponentElement

; + function createElement

, C extends ComponentClass

>( + type: ClassType, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): CElement; + function createElement

( + type: FunctionComponent

| ComponentClass

| string, + props?: Attributes & P | null, + ...children: ReactNode[] + ): ReactElement

; + + // DOM Elements + // ReactHTMLElement + function cloneElement

, T extends HTMLElement>( + element: DetailedReactHTMLElement, + props?: P, + ...children: ReactNode[] + ): DetailedReactHTMLElement; + // ReactHTMLElement, less specific + function cloneElement

, T extends HTMLElement>( + element: ReactHTMLElement, + props?: P, + ...children: ReactNode[] + ): ReactHTMLElement; + // SVGElement + function cloneElement

, T extends SVGElement>( + element: ReactSVGElement, + props?: P, + ...children: ReactNode[] + ): ReactSVGElement; + // DOM Element (has to be the last, because type checking stops at first overload that fits) + function cloneElement

, T extends Element>( + element: DOMElement, + props?: DOMAttributes & P, + ...children: ReactNode[] + ): DOMElement; + + // Custom components + function cloneElement

( + element: FunctionComponentElement

, + props?: Partial

& Attributes, + ...children: ReactNode[] + ): FunctionComponentElement

; + function cloneElement>( + element: CElement, + props?: Partial

& ClassAttributes, + ...children: ReactNode[] + ): CElement; + function cloneElement

( + element: ReactElement

, + props?: Partial

& Attributes, + ...children: ReactNode[] + ): ReactElement

; + + /** + * Describes the props accepted by a Context {@link Provider}. + * + * @template T The type of the value the context provides. + */ + interface ProviderProps { + value: T; + children?: ReactNode | undefined; + } + + /** + * Describes the props accepted by a Context {@link Consumer}. + * + * @template T The type of the value the context provides. + */ + interface ConsumerProps { + children: (value: T) => ReactNode; + } + + /** + * An object masquerading as a component. These are created by functions + * like {@link forwardRef}, {@link memo}, and {@link createContext}. + * + * In order to make TypeScript work, we pretend that they are normal + * components. + * + * But they are, in fact, not callable - instead, they are objects which + * are treated specially by the renderer. + * + * @template P The props the component accepts. + */ + interface ExoticComponent

{ + (props: P): ReactElement | null; + readonly $$typeof: symbol; + } + + /** + * An {@link ExoticComponent} with a `displayName` property applied to it. + * + * @template P The props the component accepts. + */ + interface NamedExoticComponent

extends ExoticComponent

{ + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * An {@link ExoticComponent} with a `propTypes` property applied to it. + * + * @template P The props the component accepts. + */ + interface ProviderExoticComponent

extends ExoticComponent

{ + } + + /** + * Used to retrieve the type of a context object from a {@link Context}. + * + * @template C The context object. + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const MyContext = createContext({ foo: 'bar' }); + * + * type ContextType = ContextType; + * // ContextType = { foo: string } + * ``` + */ + type ContextType> = C extends Context ? T : never; + + /** + * Wraps your components to specify the value of this context for all components inside. + * + * @see {@link https://react.dev/reference/react/createContext#provider React Docs} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * + * function App() { + * return ( + * + * + * + * ); + * } + * ``` + */ + type Provider = ProviderExoticComponent>; + + /** + * The old way to read context, before {@link useContext} existed. + * + * @see {@link https://react.dev/reference/react/createContext#consumer React Docs} + * + * @example + * + * ```tsx + * import { UserContext } from './user-context'; + * + * function Avatar() { + * return ( + * + * {user => {user.name}} + * + * ); + * } + * ``` + */ + type Consumer = ExoticComponent>; + + /** + * Context lets components pass information deep down without explicitly + * passing props. + * + * Created from {@link createContext} + * + * @see {@link https://react.dev/learn/passing-data-deeply-with-context React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * ``` + */ + interface Context extends Provider { + Provider: Provider; + Consumer: Consumer; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * Lets you create a {@link Context} that components can provide or read. + * + * @param defaultValue The value you want the context to have when there is no matching + * {@link Provider} in the tree above the component reading the context. This is meant + * as a "last resort" fallback. + * + * @see {@link https://react.dev/reference/react/createContext#reference React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * function App() { + * return ( + * + * + * + * ); + * } + * ``` + */ + function createContext( + // If you thought this should be optional, see + // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106 + defaultValue: T, + ): Context; + + function isValidElement

(object: {} | null | undefined): object is ReactElement

; + + const Children: { + map( + children: C | readonly C[], + fn: (child: C, index: number) => T, + ): C extends null | undefined ? C : Array>; + forEach(children: C | readonly C[], fn: (child: C, index: number) => void): void; + count(children: any): number; + only(children: C): C extends any[] ? never : C; + toArray(children: ReactNode | ReactNode[]): Array>; + }; + + export interface FragmentProps { + children?: React.ReactNode; + } + /** + * Lets you group elements without a wrapper node. + * + * @see {@link https://react.dev/reference/react/Fragment React Docs} + * + * @example + * + * ```tsx + * import { Fragment } from 'react'; + * + * + * Hello + * World + * + * ``` + * + * @example + * + * ```tsx + * // Using the <> shorthand syntax: + * + * <> + * Hello + * World + * + * ``` + */ + const Fragment: ExoticComponent; + + /** + * Lets you find common bugs in your components early during development. + * + * @see {@link https://react.dev/reference/react/StrictMode React Docs} + * + * @example + * + * ```tsx + * import { StrictMode } from 'react'; + * + * + * + * + * ``` + */ + const StrictMode: ExoticComponent<{ children?: ReactNode | undefined }>; + + /** + * The props accepted by {@link Suspense}. + * + * @see {@link https://react.dev/reference/react/Suspense React Docs} + */ + interface SuspenseProps { + children?: ReactNode | undefined; + + /** A fallback react tree to show when a Suspense child (like React.lazy) suspends */ + fallback?: ReactNode; + + /** + * A name for this Suspense boundary for instrumentation purposes. + * The name will help identify this boundary in React DevTools. + */ + name?: string | undefined; + } + + /** + * Lets you display a fallback until its children have finished loading. + * + * @see {@link https://react.dev/reference/react/Suspense React Docs} + * + * @example + * + * ```tsx + * import { Suspense } from 'react'; + * + * }> + * + * + * ``` + */ + const Suspense: ExoticComponent; + const version: string; + + /** + * The callback passed to {@link ProfilerProps.onRender}. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + type ProfilerOnRenderCallback = ( + /** + * The string id prop of the {@link Profiler} tree that has just committed. This lets + * you identify which part of the tree was committed if you are using multiple + * profilers. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + id: string, + /** + * This lets you know whether the tree has just been mounted for the first time + * or re-rendered due to a change in props, state, or hooks. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + phase: "mount" | "update" | "nested-update", + /** + * The number of milliseconds spent rendering the {@link Profiler} and its descendants + * for the current update. This indicates how well the subtree makes use of + * memoization (e.g. {@link memo} and {@link useMemo}). Ideally this value should decrease + * significantly after the initial mount as many of the descendants will only need to + * re-render if their specific props change. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + actualDuration: number, + /** + * The number of milliseconds estimating how much time it would take to re-render the entire + * {@link Profiler} subtree without any optimizations. It is calculated by summing up the most + * recent render durations of each component in the tree. This value estimates a worst-case + * cost of rendering (e.g. the initial mount or a tree with no memoization). Compare + * {@link actualDuration} against it to see if memoization is working. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + baseDuration: number, + /** + * A numeric timestamp for when React began rendering the current update. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + startTime: number, + /** + * A numeric timestamp for when React committed the current update. This value is shared + * between all profilers in a commit, enabling them to be grouped if desirable. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + commitTime: number, + ) => void; + + /** + * The props accepted by {@link Profiler}. + * + * @see {@link https://react.dev/reference/react/Profiler React Docs} + */ + interface ProfilerProps { + children?: ReactNode | undefined; + id: string; + onRender: ProfilerOnRenderCallback; + } + + /** + * Lets you measure rendering performance of a React tree programmatically. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + * + * @example + * + * ```tsx + * + * + * + * ``` + */ + const Profiler: ExoticComponent; + + // + // Component API + // ---------------------------------------------------------------------- + + type ReactInstance = Component | Element; + + // Base component for plain JS classes + interface Component

extends ComponentLifecycle {} + class Component { + /** + * If set, `this.context` will be set at runtime to the current value of the given Context. + * + * @example + * + * ```ts + * type MyContext = number + * const Ctx = React.createContext(0) + * + * class Foo extends React.Component { + * static contextType = Ctx + * context!: React.ContextType + * render () { + * return <>My context's value: {this.context}; + * } + * } + * ``` + * + * @see {@link https://react.dev/reference/react/Component#static-contexttype} + */ + static contextType?: Context | undefined; + + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + static propTypes?: any; + + /** + * If using React Context, re-declare this in your class to be the + * `React.ContextType` of your `static contextType`. + * Should be used with type annotation or static contextType. + * + * @example + * ```ts + * static contextType = MyContext + * // For TS pre-3.7: + * context!: React.ContextType + * // For TS 3.7 and above: + * declare context: React.ContextType + * ``` + * + * @see {@link https://react.dev/reference/react/Component#context React Docs} + */ + context: unknown; + + // Keep in sync with constructor signature of JSXElementConstructor and ComponentClass. + constructor(props: P); + /** + * @param props + * @param context value of the parent {@link https://react.dev/reference/react/Component#context Context} specified + * in `contextType`. + */ + // TODO: Ideally we'd infer the constructor signatur from `contextType`. + // Might be hard to ship without breaking existing code. + constructor(props: P, context: any); + + // We MUST keep setState() as a unified signature because it allows proper checking of the method return type. + // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257 + // Also, the ` | S` allows intellisense to not be dumbisense + setState( + state: ((prevState: Readonly, props: Readonly

) => Pick | S | null) | (Pick | S | null), + callback?: () => void, + ): void; + + forceUpdate(callback?: () => void): void; + render(): ReactNode; + + readonly props: Readonly

; + state: Readonly; + } + + class PureComponent

extends Component {} + + /** + * @deprecated Use `ClassicComponent` from `create-react-class` + * + * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs} + * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm} + */ + interface ClassicComponent

extends Component { + replaceState(nextState: S, callback?: () => void): void; + isMounted(): boolean; + getInitialState?(): S; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + /** + * Represents the type of a function component. Can optionally + * receive a type argument that represents the props the component + * receives. + * + * @template P The props the component accepts. + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet} + * @alias for {@link FunctionComponent} + * + * @example + * + * ```tsx + * // With props: + * type Props = { name: string } + * + * const MyComponent: FC = (props) => { + * return

{props.name}
+ * } + * ``` + * + * @example + * + * ```tsx + * // Without props: + * const MyComponentWithoutProps: FC = () => { + * return
MyComponentWithoutProps
+ * } + * ``` + */ + type FC

= FunctionComponent

; + + /** + * Represents the type of a function component. Can optionally + * receive a type argument that represents the props the component + * accepts. + * + * @template P The props the component accepts. + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // With props: + * type Props = { name: string } + * + * const MyComponent: FunctionComponent = (props) => { + * return

{props.name}
+ * } + * ``` + * + * @example + * + * ```tsx + * // Without props: + * const MyComponentWithoutProps: FunctionComponent = () => { + * return
MyComponentWithoutProps
+ * } + * ``` + */ + interface FunctionComponent

{ + (props: P): ReactElement | null; + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + propTypes?: any; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + * + * @example + * + * ```tsx + * + * const MyComponent: FC = () => { + * return

Hello!
+ * } + * + * MyComponent.displayName = 'MyAwesomeComponent' + * ``` + */ + displayName?: string | undefined; + } + + /** + * The type of the ref received by a {@link ForwardRefRenderFunction}. + * + * @see {@link ForwardRefRenderFunction} + */ + type ForwardedRef = ((instance: T | null) => void) | MutableRefObject | null; + + /** + * The type of the function passed to {@link forwardRef}. This is considered different + * to a normal {@link FunctionComponent} because it receives an additional argument, + * + * @param props Props passed to the component, if any. + * @param ref A ref forwarded to the component of type {@link ForwardedRef}. + * + * @template T The type of the forwarded ref. + * @template P The type of the props the component accepts. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet} + * @see {@link forwardRef} + */ + interface ForwardRefRenderFunction { + (props: P, ref: ForwardedRef): ReactElement | null; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * Will show `ForwardRef(${Component.displayName || Component.name})` + * in devtools by default, but can be given its own specific name. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + propTypes?: any; + } + + /** + * Represents a component class in React. + * + * @template P The props the component accepts. + * @template S The internal state of the component. + */ + interface ComponentClass

extends StaticLifecycle { + // constructor signature must match React.Component + new( + props: P, /** + * Value of the parent {@link https://react.dev/reference/react/Component#context Context} specified + * in `contextType`. + */ + context?: any, + ): Component; + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + propTypes?: any; + contextType?: Context | undefined; + defaultProps?: Partial

| undefined; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * @deprecated Use `ClassicComponentClass` from `create-react-class` + * + * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs} + * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm} + */ + interface ClassicComponentClass

extends ComponentClass

{ + new(props: P): ClassicComponent; + getDefaultProps?(): P; + } + + /** + * Used in {@link createElement} and {@link createFactory} to represent + * a class. + * + * An intersection type is used to infer multiple type parameters from + * a single argument, which is useful for many top-level API defs. + * See {@link https://github.com/Microsoft/TypeScript/issues/7234 this GitHub issue} + * for more info. + */ + type ClassType, C extends ComponentClass

> = + & C + & (new(props: P, context: any) => T); + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + // This should actually be something like `Lifecycle | DeprecatedLifecycle`, + // as React will _not_ call the deprecated lifecycle methods if any of the new lifecycle + // methods are present. + interface ComponentLifecycle extends NewLifecycle, DeprecatedLifecycle { + /** + * Called immediately after a component is mounted. Setting state here will trigger re-rendering. + */ + componentDidMount?(): void; + /** + * Called to determine whether the change in props and state should trigger a re-render. + * + * `Component` always returns true. + * `PureComponent` implements a shallow comparison on props and state and returns true if any + * props or states have changed. + * + * If false is returned, {@link Component.render}, `componentWillUpdate` + * and `componentDidUpdate` will not be called. + */ + shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; + /** + * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as + * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`. + */ + componentWillUnmount?(): void; + /** + * Catches exceptions generated in descendant components. Unhandled exceptions will cause + * the entire component tree to unmount. + */ + componentDidCatch?(error: Error, errorInfo: ErrorInfo): void; + } + + // Unfortunately, we have no way of declaring that the component constructor must implement this + interface StaticLifecycle { + getDerivedStateFromProps?: GetDerivedStateFromProps | undefined; + getDerivedStateFromError?: GetDerivedStateFromError | undefined; + } + + type GetDerivedStateFromProps = + /** + * Returns an update to a component's state based on its new props and old state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (nextProps: Readonly

, prevState: S) => Partial | null; + + type GetDerivedStateFromError = + /** + * This lifecycle is invoked after an error has been thrown by a descendant component. + * It receives the error that was thrown as a parameter and should return a value to update state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (error: any) => Partial | null; + + // This should be "infer SS" but can't use it yet + interface NewLifecycle { + /** + * Runs before React applies the result of {@link Component.render render} to the document, and + * returns an object to be given to {@link componentDidUpdate}. Useful for saving + * things such as scroll position before {@link Component.render render} causes changes to it. + * + * Note: the presence of this method prevents any of the deprecated + * lifecycle events from running. + */ + getSnapshotBeforeUpdate?(prevProps: Readonly

, prevState: Readonly): SS | null; + /** + * Called immediately after updating occurs. Not called for the initial render. + * + * The snapshot is only present if {@link getSnapshotBeforeUpdate} is present and returns non-null. + */ + componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, snapshot?: SS): void; + } + + interface DeprecatedLifecycle { + /** + * Called immediately before mounting occurs, and before {@link Component.render}. + * Avoid introducing any side-effects or subscriptions in this method. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillMount?(): void; + /** + * Called immediately before mounting occurs, and before {@link Component.render}. + * Avoid introducing any side-effects or subscriptions in this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillMount?(): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling {@link Component.setState} generally does not trigger this method. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling {@link Component.setState} generally does not trigger this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call {@link Component.setState} here. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call {@link Component.setState} here. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + } + + function createRef(): RefObject; + + /** + * The type of the component returned from {@link forwardRef}. + * + * @template P The props the component accepts, if any. + * + * @see {@link ExoticComponent} + */ + interface ForwardRefExoticComponent

extends NamedExoticComponent

{ + /** + * Ignored by React. + * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release. + */ + propTypes?: any; + } + + /** + * Lets your component expose a DOM node to a parent component + * using a ref. + * + * @see {@link https://react.dev/reference/react/forwardRef React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet} + * + * @param render See the {@link ForwardRefRenderFunction}. + * + * @template T The type of the DOM node. + * @template P The props the component accepts, if any. + * + * @example + * + * ```tsx + * interface Props { + * children?: ReactNode; + * type: "submit" | "button"; + * } + * + * export const FancyButton = forwardRef((props, ref) => ( + * + * )); + * ``` + */ + function forwardRef( + render: ForwardRefRenderFunction>, + ): ForwardRefExoticComponent & RefAttributes>; + + /** + * Omits the 'ref' attribute from the given props object. + * + * @template Props The props object type. + */ + type PropsWithoutRef = + // Omit would not be sufficient for this. We'd like to avoid unnecessary mapping and need a distributive conditional to support unions. + // see: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types + // https://github.com/Microsoft/TypeScript/issues/28339 + Props extends any ? ("ref" extends keyof Props ? Omit : Props) : Props; + /** + * Ensures that the props do not include string ref, which cannot be forwarded + * @deprecated Use `Props` directly. `PropsWithRef` is just an alias for `Props` + */ + type PropsWithRef = Props; + + type PropsWithChildren

= P & { children?: ReactNode | undefined }; + + /** + * Used to retrieve the props a component accepts. Can either be passed a string, + * indicating a DOM element (e.g. 'div', 'span', etc.) or the type of a React + * component. + * + * It's usually better to use {@link ComponentPropsWithRef} or {@link ComponentPropsWithoutRef} + * instead of this type, as they let you be explicit about whether or not to include + * the `ref` prop. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentProps<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>

; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentProps = React.ComponentProps; + * ``` + */ + type ComponentProps> = T extends + JSXElementConstructor ? Props + : T extends keyof JSX.IntrinsicElements ? JSX.IntrinsicElements[T] + : {}; + + /** + * Used to retrieve the props a component accepts with its ref. Can either be + * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the + * type of a React component. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentPropsWithRef<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>
; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithRef = React.ComponentPropsWithRef; + * ``` + */ + type ComponentPropsWithRef = T extends JSXElementConstructor + // If it's a class i.e. newable we're dealing with a class component + ? T extends abstract new(args: any) => any ? PropsWithoutRef & RefAttributes> + : Props + : ComponentProps; + /** + * Used to retrieve the props a custom component accepts with its ref. + * + * Unlike {@link ComponentPropsWithRef}, this only works with custom + * components, i.e. components you define yourself. This is to improve + * type-checking performance. + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>
; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithRef = React.CustomComponentPropsWithRef; + * ``` + */ + type CustomComponentPropsWithRef = T extends JSXElementConstructor + // If it's a class i.e. newable we're dealing with a class component + ? T extends abstract new(args: any) => any ? PropsWithoutRef & RefAttributes> + : Props + : never; + + /** + * Used to retrieve the props a component accepts without its ref. Can either be + * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the + * type of a React component. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentPropsWithoutRef<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>
; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithoutRef = React.ComponentPropsWithoutRef; + * ``` + */ + type ComponentPropsWithoutRef = PropsWithoutRef>; + + /** + * Retrieves the type of the 'ref' prop for a given component type or tag name. + * + * @template C The component type. + * + * @example + * + * ```tsx + * type MyComponentRef = React.ComponentRef; + * ``` + * + * @example + * + * ```tsx + * type DivRef = React.ComponentRef<'div'>; + * ``` + */ + type ComponentRef = ComponentPropsWithRef extends RefAttributes ? Method + : never; + + // will show `Memo(${Component.displayName || Component.name})` in devtools by default, + // but can be given its own specific name + type MemoExoticComponent> = NamedExoticComponent> & { + readonly type: T; + }; + + /** + * Lets you skip re-rendering a component when its props are unchanged. + * + * @see {@link https://react.dev/reference/react/memo React Docs} + * + * @param Component The component to memoize. + * @param propsAreEqual A function that will be used to determine if the props have changed. + * + * @example + * + * ```tsx + * import { memo } from 'react'; + * + * const SomeComponent = memo(function SomeComponent(props: { foo: string }) { + * // ... + * }); + * ``` + */ + function memo

( + Component: FunctionComponent

, + propsAreEqual?: (prevProps: Readonly

, nextProps: Readonly

) => boolean, + ): NamedExoticComponent

; + function memo>( + Component: T, + propsAreEqual?: (prevProps: Readonly>, nextProps: Readonly>) => boolean, + ): MemoExoticComponent; + + interface LazyExoticComponent> + extends ExoticComponent> + { + readonly _result: T; + } + + /** + * Lets you defer loading a component’s code until it is rendered for the first time. + * + * @see {@link https://react.dev/reference/react/lazy React Docs} + * + * @param load A function that returns a `Promise` or another thenable (a `Promise`-like object with a + * then method). React will not call `load` until the first time you attempt to render the returned + * component. After React first calls load, it will wait for it to resolve, and then render the + * resolved value’s `.default` as a React component. Both the returned `Promise` and the `Promise`’s + * resolved value will be cached, so React will not call load more than once. If the `Promise` rejects, + * React will throw the rejection reason for the nearest Error Boundary to handle. + * + * @example + * + * ```tsx + * import { lazy } from 'react'; + * + * const MarkdownPreview = lazy(() => import('./MarkdownPreview.js')); + * ``` + */ + function lazy>( + load: () => Promise<{ default: T }>, + ): LazyExoticComponent; + + // + // React Hooks + // ---------------------------------------------------------------------- + + /** + * The instruction passed to a {@link Dispatch} function in {@link useState} + * to tell React what the next value of the {@link useState} should be. + * + * Often found wrapped in {@link Dispatch}. + * + * @template S The type of the state. + * + * @example + * + * ```tsx + * // This return type correctly represents the type of + * // `setCount` in the example below. + * const useCustomState = (): Dispatch> => { + * const [count, setCount] = useState(0); + * + * return setCount; + * } + * ``` + */ + type SetStateAction = S | ((prevState: S) => S); + + /** + * A function that can be used to update the state of a {@link useState} + * or {@link useReducer} hook. + */ + type Dispatch = (value: A) => void; + /** + * A {@link Dispatch} function can sometimes be called without any arguments. + */ + type DispatchWithoutAction = () => void; + // Limit the reducer to accept only 0 or 1 action arguments + // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type + type AnyActionArg = [] | [any]; + // Get the dispatch type from the reducer arguments (captures optional action argument correctly) + type ActionDispatch = (...args: ActionArg) => void; + // Unlike redux, the actions _can_ be anything + type Reducer = (prevState: S, action: A) => S; + // If useReducer accepts a reducer without action, dispatch may be called without any parameters. + type ReducerWithoutAction = (prevState: S) => S; + // types used to try and prevent the compiler from reducing S + // to a supertype common with the second argument to useReducer() + type ReducerState> = R extends Reducer ? S : never; + type DependencyList = readonly unknown[]; + + // NOTE: callbacks are _only_ allowed to return either void, or a destructor. + type EffectCallback = () => void | Destructor; + + /** + * @deprecated Use `RefObject` instead. + */ + interface MutableRefObject { + current: T; + } + + // This will technically work if you give a Consumer or Provider but it's deprecated and warns + /** + * Accepts a context object (the value returned from `React.createContext`) and returns the current + * context value, as given by the nearest context provider for the given context. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useContext} + */ + function useContext(context: Context /*, (not public API) observedBits?: number|boolean */): T; + /** + * Returns a stateful value, and a function to update it. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useState} + */ + function useState(initialState: S | (() => S)): [S, Dispatch>]; + // convenience overload when first argument is omitted + /** + * Returns a stateful value, and a function to update it. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useState} + */ + function useState(): [S | undefined, Dispatch>]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + function useReducer( + reducer: (prevState: S, ...args: A) => S, + initialState: S, + ): [S, ActionDispatch]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + function useReducer( + reducer: (prevState: S, ...args: A) => S, + initialArg: I, + init: (i: I) => S, + ): [S, ActionDispatch]; + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T): RefObject; + // convenience overload for refs given as a ref prop as they typically start with a null value + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T | null): RefObject; + // convenience overload for undefined initialValue + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T | undefined): RefObject; + /** + * The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations. + * Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside + * `useLayoutEffect` will be flushed synchronously, before the browser has a chance to paint. + * + * Prefer the standard `useEffect` when possible to avoid blocking visual updates. + * + * If you’re migrating code from a class component, `useLayoutEffect` fires in the same phase as + * `componentDidMount` and `componentDidUpdate`. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useLayoutEffect} + */ + function useLayoutEffect(effect: EffectCallback, deps?: DependencyList): void; + /** + * Accepts a function that contains imperative, possibly effectful code. + * + * @param effect Imperative function that can return a cleanup function + * @param deps If present, effect will only activate if the values in the list change. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useEffect} + */ + function useEffect(effect: EffectCallback, deps?: DependencyList): void; + // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref + /** + * `useImperativeHandle` customizes the instance value that is exposed to parent components when using + * `ref`. As always, imperative code using refs should be avoided in most cases. + * + * `useImperativeHandle` should be used with `React.forwardRef`. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useImperativeHandle} + */ + function useImperativeHandle(ref: Ref | undefined, init: () => R, deps?: DependencyList): void; + // I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key + // useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y. + /** + * `useCallback` will return a memoized version of the callback that only changes if one of the `inputs` + * has changed. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useCallback} + */ + // A specific function type would not trigger implicit any. + // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/52873#issuecomment-845806435 for a comparison between `Function` and more specific types. + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + function useCallback(callback: T, deps: DependencyList): T; + /** + * `useMemo` will only recompute the memoized value when one of the `deps` has changed. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useMemo} + */ + // allow undefined, but don't make it optional as that is very likely a mistake + function useMemo(factory: () => T, deps: DependencyList): T; + /** + * `useDebugValue` can be used to display a label for custom hooks in React DevTools. + * + * NOTE: We don’t recommend adding debug values to every custom hook. + * It’s most valuable for custom hooks that are part of shared libraries. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useDebugValue} + */ + // the name of the custom hook is itself derived from the function name at runtime: + // it's just the function name without the "use" prefix. + function useDebugValue(value: T, format?: (value: T) => any): void; + + export type TransitionFunction = () => VoidOrUndefinedOnly | Promise; + // strange definition to allow vscode to show documentation on the invocation + export interface TransitionStartFunction { + /** + * State updates caused inside the callback are allowed to be deferred. + * + * **If some state update causes a component to suspend, that state update should be wrapped in a transition.** + * + * @param callback A function which causes state updates that can be deferred. + */ + (callback: TransitionFunction): void; + } + + /** + * Returns a deferred version of the value that may “lag behind” it. + * + * This is commonly used to keep the interface responsive when you have something that renders immediately + * based on user input and something that needs to wait for a data fetch. + * + * A good example of this is a text input. + * + * @param value The value that is going to be deferred + * @param initialValue A value to use during the initial render of a component. If this option is omitted, `useDeferredValue` will not defer during the initial render, because there’s no previous version of `value` that it can render instead. + * + * @see {@link https://react.dev/reference/react/useDeferredValue} + */ + export function useDeferredValue(value: T, initialValue?: T): T; + + /** + * Allows components to avoid undesirable loading states by waiting for content to load + * before transitioning to the next screen. It also allows components to defer slower, + * data fetching updates until subsequent renders so that more crucial updates can be + * rendered immediately. + * + * The `useTransition` hook returns two values in an array. + * + * The first is a boolean, React’s way of informing us whether we’re waiting for the transition to finish. + * The second is a function that takes a callback. We can use it to tell React which state we want to defer. + * + * **If some state update causes a component to suspend, that state update should be wrapped in a transition.** + * + * @see {@link https://react.dev/reference/react/useTransition} + */ + export function useTransition(): [boolean, TransitionStartFunction]; + + /** + * Similar to `useTransition` but allows uses where hooks are not available. + * + * @param callback A function which causes state updates that can be deferred. + */ + export function startTransition(scope: TransitionFunction): void; + + /** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ + // NOTES + // - the order of these signatures matters - typescript will check the signatures in source order. + // If the `() => VoidOrUndefinedOnly` signature is first, it'll erroneously match a Promise returning function for users with + // `strictNullChecks: false`. + // - VoidOrUndefinedOnly is there to forbid any non-void return values for users with `strictNullChecks: true` + // While act does always return Thenable, if a void function is passed, we pretend the return value is also void to not trigger dangling Promise lint rules. + export function act(callback: () => VoidOrUndefinedOnly): void; + export function act(callback: () => T | Promise): Promise; + + export function useId(): string; + + /** + * @param effect Imperative function that can return a cleanup function + * @param deps If present, effect will only activate if the values in the list change. + * + * @see {@link https://github.com/facebook/react/pull/21913} + */ + export function useInsertionEffect(effect: EffectCallback, deps?: DependencyList): void; + + /** + * @param subscribe + * @param getSnapshot + * + * @see {@link https://github.com/reactwg/react-18/discussions/86} + */ + // keep in sync with `useSyncExternalStore` from `use-sync-external-store` + export function useSyncExternalStore( + subscribe: (onStoreChange: () => void) => () => void, + getSnapshot: () => Snapshot, + getServerSnapshot?: () => Snapshot, + ): Snapshot; + + export function useOptimistic( + passthrough: State, + ): [State, (action: State | ((pendingState: State) => State)) => void]; + export function useOptimistic( + passthrough: State, + reducer: (state: State, action: Action) => State, + ): [State, (action: Action) => void]; + + export type Usable = PromiseLike | Context; + + export function use(usable: Usable): T; + + export function useActionState( + action: (state: Awaited) => State | Promise, + initialState: Awaited, + permalink?: string, + ): [state: Awaited, dispatch: () => void, isPending: boolean]; + export function useActionState( + action: (state: Awaited, payload: Payload) => State | Promise, + initialState: Awaited, + permalink?: string, + ): [state: Awaited, dispatch: (payload: Payload) => void, isPending: boolean]; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + export function cache(fn: CachedFunction): CachedFunction; + + /** + * Warning: Only available in development builds. + * + * @see {@link https://react.dev/reference/react/captureOwnerStack Reference docs} + */ + function captureOwnerStack(): string | null; + + // + // Event System + // ---------------------------------------------------------------------- + // TODO: change any to unknown when moving to TS v3 + interface BaseSyntheticEvent { + nativeEvent: E; + currentTarget: C; + target: T; + bubbles: boolean; + cancelable: boolean; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + preventDefault(): void; + isDefaultPrevented(): boolean; + stopPropagation(): void; + isPropagationStopped(): boolean; + persist(): void; + timeStamp: number; + type: string; + } + + /** + * currentTarget - a reference to the element on which the event listener is registered. + * + * target - a reference to the element from which the event was originally dispatched. + * This might be a child element to the element on which the event listener is registered. + * If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11508#issuecomment-256045682 + */ + interface SyntheticEvent extends BaseSyntheticEvent {} + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + } + + interface CompositionEvent extends SyntheticEvent { + data: string; + } + + interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + } + + interface PointerEvent extends MouseEvent { + pointerId: number; + pressure: number; + tangentialPressure: number; + tiltX: number; + tiltY: number; + twist: number; + width: number; + height: number; + pointerType: "mouse" | "pen" | "touch"; + isPrimary: boolean; + } + + interface FocusEvent extends SyntheticEvent { + relatedTarget: (EventTarget & RelatedTarget) | null; + target: EventTarget & Target; + } + + interface FormEvent extends SyntheticEvent { + } + + interface InvalidEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface ChangeEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface InputEvent extends SyntheticEvent { + data: string; + } + + export type ModifierKey = + | "Alt" + | "AltGraph" + | "CapsLock" + | "Control" + | "Fn" + | "FnLock" + | "Hyper" + | "Meta" + | "NumLock" + | "ScrollLock" + | "Shift" + | "Super" + | "Symbol" + | "SymbolLock"; + + interface KeyboardEvent extends UIEvent { + altKey: boolean; + /** @deprecated */ + charCode: number; + ctrlKey: boolean; + code: string; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + /** + * See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values + */ + key: string; + /** @deprecated */ + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + repeat: boolean; + shiftKey: boolean; + /** @deprecated */ + which: number; + } + + interface MouseEvent extends UIEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + metaKey: boolean; + movementX: number; + movementY: number; + pageX: number; + pageY: number; + relatedTarget: EventTarget | null; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends UIEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + metaKey: boolean; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + view: AbstractView; + } + + interface WheelEvent extends MouseEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + } + + interface AnimationEvent extends SyntheticEvent { + animationName: string; + elapsedTime: number; + pseudoElement: string; + } + + interface ToggleEvent extends SyntheticEvent { + oldState: "closed" | "open"; + newState: "closed" | "open"; + } + + interface TransitionEvent extends SyntheticEvent { + elapsedTime: number; + propertyName: string; + pseudoElement: string; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + type EventHandler> = { bivarianceHack(event: E): void }["bivarianceHack"]; + + type ReactEventHandler = EventHandler>; + + type ClipboardEventHandler = EventHandler>; + type CompositionEventHandler = EventHandler>; + type DragEventHandler = EventHandler>; + type FocusEventHandler = EventHandler>; + type FormEventHandler = EventHandler>; + type ChangeEventHandler = EventHandler>; + type InputEventHandler = EventHandler>; + type KeyboardEventHandler = EventHandler>; + type MouseEventHandler = EventHandler>; + type TouchEventHandler = EventHandler>; + type PointerEventHandler = EventHandler>; + type UIEventHandler = EventHandler>; + type WheelEventHandler = EventHandler>; + type AnimationEventHandler = EventHandler>; + type ToggleEventHandler = EventHandler>; + type TransitionEventHandler = EventHandler>; + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + interface HTMLProps extends AllHTMLAttributes, ClassAttributes { + } + + type DetailedHTMLProps, T> = ClassAttributes & E; + + interface SVGProps extends SVGAttributes, ClassAttributes { + } + + interface SVGLineElementAttributes extends SVGProps {} + interface SVGTextElementAttributes extends SVGProps {} + + interface DOMAttributes { + children?: ReactNode | undefined; + dangerouslySetInnerHTML?: { + // Should be InnerHTML['innerHTML']. + // But unfortunately we're mixing renderer-specific type declarations. + __html: string | TrustedHTML; + } | undefined; + + // Clipboard Events + onCopy?: ClipboardEventHandler | undefined; + onCopyCapture?: ClipboardEventHandler | undefined; + onCut?: ClipboardEventHandler | undefined; + onCutCapture?: ClipboardEventHandler | undefined; + onPaste?: ClipboardEventHandler | undefined; + onPasteCapture?: ClipboardEventHandler | undefined; + + // Composition Events + onCompositionEnd?: CompositionEventHandler | undefined; + onCompositionEndCapture?: CompositionEventHandler | undefined; + onCompositionStart?: CompositionEventHandler | undefined; + onCompositionStartCapture?: CompositionEventHandler | undefined; + onCompositionUpdate?: CompositionEventHandler | undefined; + onCompositionUpdateCapture?: CompositionEventHandler | undefined; + + // Focus Events + onFocus?: FocusEventHandler | undefined; + onFocusCapture?: FocusEventHandler | undefined; + onBlur?: FocusEventHandler | undefined; + onBlurCapture?: FocusEventHandler | undefined; + + // Form Events + onChange?: FormEventHandler | undefined; + onChangeCapture?: FormEventHandler | undefined; + onBeforeInput?: InputEventHandler | undefined; + onBeforeInputCapture?: FormEventHandler | undefined; + onInput?: FormEventHandler | undefined; + onInputCapture?: FormEventHandler | undefined; + onReset?: FormEventHandler | undefined; + onResetCapture?: FormEventHandler | undefined; + onSubmit?: FormEventHandler | undefined; + onSubmitCapture?: FormEventHandler | undefined; + onInvalid?: FormEventHandler | undefined; + onInvalidCapture?: FormEventHandler | undefined; + + // Image Events + onLoad?: ReactEventHandler | undefined; + onLoadCapture?: ReactEventHandler | undefined; + onError?: ReactEventHandler | undefined; // also a Media Event + onErrorCapture?: ReactEventHandler | undefined; // also a Media Event + + // Keyboard Events + onKeyDown?: KeyboardEventHandler | undefined; + onKeyDownCapture?: KeyboardEventHandler | undefined; + /** @deprecated Use `onKeyUp` or `onKeyDown` instead */ + onKeyPress?: KeyboardEventHandler | undefined; + /** @deprecated Use `onKeyUpCapture` or `onKeyDownCapture` instead */ + onKeyPressCapture?: KeyboardEventHandler | undefined; + onKeyUp?: KeyboardEventHandler | undefined; + onKeyUpCapture?: KeyboardEventHandler | undefined; + + // Media Events + onAbort?: ReactEventHandler | undefined; + onAbortCapture?: ReactEventHandler | undefined; + onCanPlay?: ReactEventHandler | undefined; + onCanPlayCapture?: ReactEventHandler | undefined; + onCanPlayThrough?: ReactEventHandler | undefined; + onCanPlayThroughCapture?: ReactEventHandler | undefined; + onDurationChange?: ReactEventHandler | undefined; + onDurationChangeCapture?: ReactEventHandler | undefined; + onEmptied?: ReactEventHandler | undefined; + onEmptiedCapture?: ReactEventHandler | undefined; + onEncrypted?: ReactEventHandler | undefined; + onEncryptedCapture?: ReactEventHandler | undefined; + onEnded?: ReactEventHandler | undefined; + onEndedCapture?: ReactEventHandler | undefined; + onLoadedData?: ReactEventHandler | undefined; + onLoadedDataCapture?: ReactEventHandler | undefined; + onLoadedMetadata?: ReactEventHandler | undefined; + onLoadedMetadataCapture?: ReactEventHandler | undefined; + onLoadStart?: ReactEventHandler | undefined; + onLoadStartCapture?: ReactEventHandler | undefined; + onPause?: ReactEventHandler | undefined; + onPauseCapture?: ReactEventHandler | undefined; + onPlay?: ReactEventHandler | undefined; + onPlayCapture?: ReactEventHandler | undefined; + onPlaying?: ReactEventHandler | undefined; + onPlayingCapture?: ReactEventHandler | undefined; + onProgress?: ReactEventHandler | undefined; + onProgressCapture?: ReactEventHandler | undefined; + onRateChange?: ReactEventHandler | undefined; + onRateChangeCapture?: ReactEventHandler | undefined; + onSeeked?: ReactEventHandler | undefined; + onSeekedCapture?: ReactEventHandler | undefined; + onSeeking?: ReactEventHandler | undefined; + onSeekingCapture?: ReactEventHandler | undefined; + onStalled?: ReactEventHandler | undefined; + onStalledCapture?: ReactEventHandler | undefined; + onSuspend?: ReactEventHandler | undefined; + onSuspendCapture?: ReactEventHandler | undefined; + onTimeUpdate?: ReactEventHandler | undefined; + onTimeUpdateCapture?: ReactEventHandler | undefined; + onVolumeChange?: ReactEventHandler | undefined; + onVolumeChangeCapture?: ReactEventHandler | undefined; + onWaiting?: ReactEventHandler | undefined; + onWaitingCapture?: ReactEventHandler | undefined; + + // MouseEvents + onAuxClick?: MouseEventHandler | undefined; + onAuxClickCapture?: MouseEventHandler | undefined; + onClick?: MouseEventHandler | undefined; + onClickCapture?: MouseEventHandler | undefined; + onContextMenu?: MouseEventHandler | undefined; + onContextMenuCapture?: MouseEventHandler | undefined; + onDoubleClick?: MouseEventHandler | undefined; + onDoubleClickCapture?: MouseEventHandler | undefined; + onDrag?: DragEventHandler | undefined; + onDragCapture?: DragEventHandler | undefined; + onDragEnd?: DragEventHandler | undefined; + onDragEndCapture?: DragEventHandler | undefined; + onDragEnter?: DragEventHandler | undefined; + onDragEnterCapture?: DragEventHandler | undefined; + onDragExit?: DragEventHandler | undefined; + onDragExitCapture?: DragEventHandler | undefined; + onDragLeave?: DragEventHandler | undefined; + onDragLeaveCapture?: DragEventHandler | undefined; + onDragOver?: DragEventHandler | undefined; + onDragOverCapture?: DragEventHandler | undefined; + onDragStart?: DragEventHandler | undefined; + onDragStartCapture?: DragEventHandler | undefined; + onDrop?: DragEventHandler | undefined; + onDropCapture?: DragEventHandler | undefined; + onMouseDown?: MouseEventHandler | undefined; + onMouseDownCapture?: MouseEventHandler | undefined; + onMouseEnter?: MouseEventHandler | undefined; + onMouseLeave?: MouseEventHandler | undefined; + onMouseMove?: MouseEventHandler | undefined; + onMouseMoveCapture?: MouseEventHandler | undefined; + onMouseOut?: MouseEventHandler | undefined; + onMouseOutCapture?: MouseEventHandler | undefined; + onMouseOver?: MouseEventHandler | undefined; + onMouseOverCapture?: MouseEventHandler | undefined; + onMouseUp?: MouseEventHandler | undefined; + onMouseUpCapture?: MouseEventHandler | undefined; + + // Selection Events + onSelect?: ReactEventHandler | undefined; + onSelectCapture?: ReactEventHandler | undefined; + + // Touch Events + onTouchCancel?: TouchEventHandler | undefined; + onTouchCancelCapture?: TouchEventHandler | undefined; + onTouchEnd?: TouchEventHandler | undefined; + onTouchEndCapture?: TouchEventHandler | undefined; + onTouchMove?: TouchEventHandler | undefined; + onTouchMoveCapture?: TouchEventHandler | undefined; + onTouchStart?: TouchEventHandler | undefined; + onTouchStartCapture?: TouchEventHandler | undefined; + + // Pointer Events + onPointerDown?: PointerEventHandler | undefined; + onPointerDownCapture?: PointerEventHandler | undefined; + onPointerMove?: PointerEventHandler | undefined; + onPointerMoveCapture?: PointerEventHandler | undefined; + onPointerUp?: PointerEventHandler | undefined; + onPointerUpCapture?: PointerEventHandler | undefined; + onPointerCancel?: PointerEventHandler | undefined; + onPointerCancelCapture?: PointerEventHandler | undefined; + onPointerEnter?: PointerEventHandler | undefined; + onPointerLeave?: PointerEventHandler | undefined; + onPointerOver?: PointerEventHandler | undefined; + onPointerOverCapture?: PointerEventHandler | undefined; + onPointerOut?: PointerEventHandler | undefined; + onPointerOutCapture?: PointerEventHandler | undefined; + onGotPointerCapture?: PointerEventHandler | undefined; + onGotPointerCaptureCapture?: PointerEventHandler | undefined; + onLostPointerCapture?: PointerEventHandler | undefined; + onLostPointerCaptureCapture?: PointerEventHandler | undefined; + + // UI Events + onScroll?: UIEventHandler | undefined; + onScrollCapture?: UIEventHandler | undefined; + onScrollEnd?: UIEventHandler | undefined; + onScrollEndCapture?: UIEventHandler | undefined; + + // Wheel Events + onWheel?: WheelEventHandler | undefined; + onWheelCapture?: WheelEventHandler | undefined; + + // Animation Events + onAnimationStart?: AnimationEventHandler | undefined; + onAnimationStartCapture?: AnimationEventHandler | undefined; + onAnimationEnd?: AnimationEventHandler | undefined; + onAnimationEndCapture?: AnimationEventHandler | undefined; + onAnimationIteration?: AnimationEventHandler | undefined; + onAnimationIterationCapture?: AnimationEventHandler | undefined; + + // Toggle Events + onToggle?: ToggleEventHandler | undefined; + onBeforeToggle?: ToggleEventHandler | undefined; + + // Transition Events + onTransitionCancel?: TransitionEventHandler | undefined; + onTransitionCancelCapture?: TransitionEventHandler | undefined; + onTransitionEnd?: TransitionEventHandler | undefined; + onTransitionEndCapture?: TransitionEventHandler | undefined; + onTransitionRun?: TransitionEventHandler | undefined; + onTransitionRunCapture?: TransitionEventHandler | undefined; + onTransitionStart?: TransitionEventHandler | undefined; + onTransitionStartCapture?: TransitionEventHandler | undefined; + } + + export interface CSSProperties extends CSS.Properties { + /** + * The index signature was removed to enable closed typing for style + * using CSSType. You're able to use type assertion or module augmentation + * to add properties or an index signature of your own. + * + * For examples and more information, visit: + * https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors + */ + } + + // All the WAI-ARIA 1.1 attributes from https://www.w3.org/TR/wai-aria-1.1/ + interface AriaAttributes { + /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */ + "aria-activedescendant"?: string | undefined; + /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */ + "aria-atomic"?: Booleanish | undefined; + /** + * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be + * presented if they are made. + */ + "aria-autocomplete"?: "none" | "inline" | "list" | "both" | undefined; + /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */ + /** + * Defines a string value that labels the current element, which is intended to be converted into Braille. + * @see aria-label. + */ + "aria-braillelabel"?: string | undefined; + /** + * Defines a human-readable, author-localized abbreviated description for the role of an element, which is intended to be converted into Braille. + * @see aria-roledescription. + */ + "aria-brailleroledescription"?: string | undefined; + "aria-busy"?: Booleanish | undefined; + /** + * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. + * @see aria-pressed @see aria-selected. + */ + "aria-checked"?: boolean | "false" | "mixed" | "true" | undefined; + /** + * Defines the total number of columns in a table, grid, or treegrid. + * @see aria-colindex. + */ + "aria-colcount"?: number | undefined; + /** + * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. + * @see aria-colcount @see aria-colspan. + */ + "aria-colindex"?: number | undefined; + /** + * Defines a human readable text alternative of aria-colindex. + * @see aria-rowindextext. + */ + "aria-colindextext"?: string | undefined; + /** + * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-colindex @see aria-rowspan. + */ + "aria-colspan"?: number | undefined; + /** + * Identifies the element (or elements) whose contents or presence are controlled by the current element. + * @see aria-owns. + */ + "aria-controls"?: string | undefined; + /** Indicates the element that represents the current item within a container or set of related elements. */ + "aria-current"?: boolean | "false" | "true" | "page" | "step" | "location" | "date" | "time" | undefined; + /** + * Identifies the element (or elements) that describes the object. + * @see aria-labelledby + */ + "aria-describedby"?: string | undefined; + /** + * Defines a string value that describes or annotates the current element. + * @see related aria-describedby. + */ + "aria-description"?: string | undefined; + /** + * Identifies the element that provides a detailed, extended description for the object. + * @see aria-describedby. + */ + "aria-details"?: string | undefined; + /** + * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. + * @see aria-hidden @see aria-readonly. + */ + "aria-disabled"?: Booleanish | undefined; + /** + * Indicates what functions can be performed when a dragged object is released on the drop target. + * @deprecated in ARIA 1.1 + */ + "aria-dropeffect"?: "none" | "copy" | "execute" | "link" | "move" | "popup" | undefined; + /** + * Identifies the element that provides an error message for the object. + * @see aria-invalid @see aria-describedby. + */ + "aria-errormessage"?: string | undefined; + /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */ + "aria-expanded"?: Booleanish | undefined; + /** + * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, + * allows assistive technology to override the general default of reading in document source order. + */ + "aria-flowto"?: string | undefined; + /** + * Indicates an element's "grabbed" state in a drag-and-drop operation. + * @deprecated in ARIA 1.1 + */ + "aria-grabbed"?: Booleanish | undefined; + /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */ + "aria-haspopup"?: boolean | "false" | "true" | "menu" | "listbox" | "tree" | "grid" | "dialog" | undefined; + /** + * Indicates whether the element is exposed to an accessibility API. + * @see aria-disabled. + */ + "aria-hidden"?: Booleanish | undefined; + /** + * Indicates the entered value does not conform to the format expected by the application. + * @see aria-errormessage. + */ + "aria-invalid"?: boolean | "false" | "true" | "grammar" | "spelling" | undefined; + /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */ + "aria-keyshortcuts"?: string | undefined; + /** + * Defines a string value that labels the current element. + * @see aria-labelledby. + */ + "aria-label"?: string | undefined; + /** + * Identifies the element (or elements) that labels the current element. + * @see aria-describedby. + */ + "aria-labelledby"?: string | undefined; + /** Defines the hierarchical level of an element within a structure. */ + "aria-level"?: number | undefined; + /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */ + "aria-live"?: "off" | "assertive" | "polite" | undefined; + /** Indicates whether an element is modal when displayed. */ + "aria-modal"?: Booleanish | undefined; + /** Indicates whether a text box accepts multiple lines of input or only a single line. */ + "aria-multiline"?: Booleanish | undefined; + /** Indicates that the user may select more than one item from the current selectable descendants. */ + "aria-multiselectable"?: Booleanish | undefined; + /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ + "aria-orientation"?: "horizontal" | "vertical" | undefined; + /** + * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship + * between DOM elements where the DOM hierarchy cannot be used to represent the relationship. + * @see aria-controls. + */ + "aria-owns"?: string | undefined; + /** + * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. + * A hint could be a sample value or a brief description of the expected format. + */ + "aria-placeholder"?: string | undefined; + /** + * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-setsize. + */ + "aria-posinset"?: number | undefined; + /** + * Indicates the current "pressed" state of toggle buttons. + * @see aria-checked @see aria-selected. + */ + "aria-pressed"?: boolean | "false" | "mixed" | "true" | undefined; + /** + * Indicates that the element is not editable, but is otherwise operable. + * @see aria-disabled. + */ + "aria-readonly"?: Booleanish | undefined; + /** + * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. + * @see aria-atomic. + */ + "aria-relevant"?: + | "additions" + | "additions removals" + | "additions text" + | "all" + | "removals" + | "removals additions" + | "removals text" + | "text" + | "text additions" + | "text removals" + | undefined; + /** Indicates that user input is required on the element before a form may be submitted. */ + "aria-required"?: Booleanish | undefined; + /** Defines a human-readable, author-localized description for the role of an element. */ + "aria-roledescription"?: string | undefined; + /** + * Defines the total number of rows in a table, grid, or treegrid. + * @see aria-rowindex. + */ + "aria-rowcount"?: number | undefined; + /** + * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. + * @see aria-rowcount @see aria-rowspan. + */ + "aria-rowindex"?: number | undefined; + /** + * Defines a human readable text alternative of aria-rowindex. + * @see aria-colindextext. + */ + "aria-rowindextext"?: string | undefined; + /** + * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-rowindex @see aria-colspan. + */ + "aria-rowspan"?: number | undefined; + /** + * Indicates the current "selected" state of various widgets. + * @see aria-checked @see aria-pressed. + */ + "aria-selected"?: Booleanish | undefined; + /** + * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-posinset. + */ + "aria-setsize"?: number | undefined; + /** Indicates if items in a table or grid are sorted in ascending or descending order. */ + "aria-sort"?: "none" | "ascending" | "descending" | "other" | undefined; + /** Defines the maximum allowed value for a range widget. */ + "aria-valuemax"?: number | undefined; + /** Defines the minimum allowed value for a range widget. */ + "aria-valuemin"?: number | undefined; + /** + * Defines the current value for a range widget. + * @see aria-valuetext. + */ + "aria-valuenow"?: number | undefined; + /** Defines the human readable text alternative of aria-valuenow for a range widget. */ + "aria-valuetext"?: string | undefined; + } + + // All the WAI-ARIA 1.1 role attribute values from https://www.w3.org/TR/wai-aria-1.1/#role_definitions + type AriaRole = + | "alert" + | "alertdialog" + | "application" + | "article" + | "banner" + | "button" + | "cell" + | "checkbox" + | "columnheader" + | "combobox" + | "complementary" + | "contentinfo" + | "definition" + | "dialog" + | "directory" + | "document" + | "feed" + | "figure" + | "form" + | "grid" + | "gridcell" + | "group" + | "heading" + | "img" + | "link" + | "list" + | "listbox" + | "listitem" + | "log" + | "main" + | "marquee" + | "math" + | "menu" + | "menubar" + | "menuitem" + | "menuitemcheckbox" + | "menuitemradio" + | "navigation" + | "none" + | "note" + | "option" + | "presentation" + | "progressbar" + | "radio" + | "radiogroup" + | "region" + | "row" + | "rowgroup" + | "rowheader" + | "scrollbar" + | "search" + | "searchbox" + | "separator" + | "slider" + | "spinbutton" + | "status" + | "switch" + | "tab" + | "table" + | "tablist" + | "tabpanel" + | "term" + | "textbox" + | "timer" + | "toolbar" + | "tooltip" + | "tree" + | "treegrid" + | "treeitem" + | (string & {}); + + interface HTMLAttributes extends AriaAttributes, DOMAttributes { + // React-specific Attributes + defaultChecked?: boolean | undefined; + defaultValue?: string | number | readonly string[] | undefined; + suppressContentEditableWarning?: boolean | undefined; + suppressHydrationWarning?: boolean | undefined; + + // Standard HTML Attributes + accessKey?: string | undefined; + autoCapitalize?: "off" | "none" | "on" | "sentences" | "words" | "characters" | undefined | (string & {}); + autoFocus?: boolean | undefined; + className?: string | undefined; + contentEditable?: Booleanish | "inherit" | "plaintext-only" | undefined; + contextMenu?: string | undefined; + dir?: string | undefined; + draggable?: Booleanish | undefined; + enterKeyHint?: "enter" | "done" | "go" | "next" | "previous" | "search" | "send" | undefined; + hidden?: boolean | undefined; + id?: string | undefined; + lang?: string | undefined; + nonce?: string | undefined; + slot?: string | undefined; + spellCheck?: Booleanish | undefined; + style?: CSSProperties | undefined; + tabIndex?: number | undefined; + title?: string | undefined; + translate?: "yes" | "no" | undefined; + + // Unknown + radioGroup?: string | undefined; // , + + // WAI-ARIA + role?: AriaRole | undefined; + + // RDFa Attributes + about?: string | undefined; + content?: string | undefined; + datatype?: string | undefined; + inlist?: any; + prefix?: string | undefined; + property?: string | undefined; + rel?: string | undefined; + resource?: string | undefined; + rev?: string | undefined; + typeof?: string | undefined; + vocab?: string | undefined; + + // Non-standard Attributes + autoCorrect?: string | undefined; + autoSave?: string | undefined; + color?: string | undefined; + itemProp?: string | undefined; + itemScope?: boolean | undefined; + itemType?: string | undefined; + itemID?: string | undefined; + itemRef?: string | undefined; + results?: number | undefined; + security?: string | undefined; + unselectable?: "on" | "off" | undefined; + + // Popover API + popover?: "" | "auto" | "manual" | undefined; + popoverTargetAction?: "toggle" | "show" | "hide" | undefined; + popoverTarget?: string | undefined; + + // Living Standard + /** + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/inert + */ + inert?: boolean | undefined; + /** + * Hints at the type of data that might be entered by the user while editing the element or its contents + * @see {@link https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute} + */ + inputMode?: "none" | "text" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined; + /** + * Specify that a standard HTML element should behave like a defined custom built-in element + * @see {@link https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is} + */ + is?: string | undefined; + /** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/exportparts} + */ + exportparts?: string | undefined; + /** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/part} + */ + part?: string | undefined; + } + + /** + * For internal usage only. + * Different release channels declare additional types of ReactNode this particular release channel accepts. + * App or library types should never augment this interface. + */ + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS {} + + interface AllHTMLAttributes extends HTMLAttributes { + // Standard HTML Attributes + accept?: string | undefined; + acceptCharset?: string | undefined; + action?: + | string + | undefined + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + allowFullScreen?: boolean | undefined; + allowTransparency?: boolean | undefined; + alt?: string | undefined; + as?: string | undefined; + async?: boolean | undefined; + autoComplete?: string | undefined; + autoPlay?: boolean | undefined; + capture?: boolean | "user" | "environment" | undefined; + cellPadding?: number | string | undefined; + cellSpacing?: number | string | undefined; + charSet?: string | undefined; + challenge?: string | undefined; + checked?: boolean | undefined; + cite?: string | undefined; + classID?: string | undefined; + cols?: number | undefined; + colSpan?: number | undefined; + controls?: boolean | undefined; + coords?: string | undefined; + crossOrigin?: CrossOrigin; + data?: string | undefined; + dateTime?: string | undefined; + default?: boolean | undefined; + defer?: boolean | undefined; + disabled?: boolean | undefined; + download?: any; + encType?: string | undefined; + form?: string | undefined; + formAction?: + | string + | undefined + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + frameBorder?: number | string | undefined; + headers?: string | undefined; + height?: number | string | undefined; + high?: number | undefined; + href?: string | undefined; + hrefLang?: string | undefined; + htmlFor?: string | undefined; + httpEquiv?: string | undefined; + integrity?: string | undefined; + keyParams?: string | undefined; + keyType?: string | undefined; + kind?: string | undefined; + label?: string | undefined; + list?: string | undefined; + loop?: boolean | undefined; + low?: number | undefined; + manifest?: string | undefined; + marginHeight?: number | undefined; + marginWidth?: number | undefined; + max?: number | string | undefined; + maxLength?: number | undefined; + media?: string | undefined; + mediaGroup?: string | undefined; + method?: string | undefined; + min?: number | string | undefined; + minLength?: number | undefined; + multiple?: boolean | undefined; + muted?: boolean | undefined; + name?: string | undefined; + noValidate?: boolean | undefined; + open?: boolean | undefined; + optimum?: number | undefined; + pattern?: string | undefined; + placeholder?: string | undefined; + playsInline?: boolean | undefined; + poster?: string | undefined; + preload?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + reversed?: boolean | undefined; + rows?: number | undefined; + rowSpan?: number | undefined; + sandbox?: string | undefined; + scope?: string | undefined; + scoped?: boolean | undefined; + scrolling?: string | undefined; + seamless?: boolean | undefined; + selected?: boolean | undefined; + shape?: string | undefined; + size?: number | undefined; + sizes?: string | undefined; + span?: number | undefined; + src?: string | undefined; + srcDoc?: string | undefined; + srcLang?: string | undefined; + srcSet?: string | undefined; + start?: number | undefined; + step?: number | string | undefined; + summary?: string | undefined; + target?: string | undefined; + type?: string | undefined; + useMap?: string | undefined; + value?: string | readonly string[] | number | undefined; + width?: number | string | undefined; + wmode?: string | undefined; + wrap?: string | undefined; + } + + type HTMLAttributeReferrerPolicy = + | "" + | "no-referrer" + | "no-referrer-when-downgrade" + | "origin" + | "origin-when-cross-origin" + | "same-origin" + | "strict-origin" + | "strict-origin-when-cross-origin" + | "unsafe-url"; + + type HTMLAttributeAnchorTarget = + | "_self" + | "_blank" + | "_parent" + | "_top" + | (string & {}); + + interface AnchorHTMLAttributes extends HTMLAttributes { + download?: any; + href?: string | undefined; + hrefLang?: string | undefined; + media?: string | undefined; + ping?: string | undefined; + target?: HTMLAttributeAnchorTarget | undefined; + type?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + } + + interface AudioHTMLAttributes extends MediaHTMLAttributes {} + + interface AreaHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + coords?: string | undefined; + download?: any; + href?: string | undefined; + hrefLang?: string | undefined; + media?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + shape?: string | undefined; + target?: string | undefined; + } + + interface BaseHTMLAttributes extends HTMLAttributes { + href?: string | undefined; + target?: string | undefined; + } + + interface BlockquoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + + interface ButtonHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + formAction?: + | string + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ] + | undefined; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + name?: string | undefined; + type?: "submit" | "reset" | "button" | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface CanvasHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + width?: number | string | undefined; + } + + interface ColHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + width?: number | string | undefined; + } + + interface ColgroupHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + } + + interface DataHTMLAttributes extends HTMLAttributes { + value?: string | readonly string[] | number | undefined; + } + + interface DetailsHTMLAttributes extends HTMLAttributes { + open?: boolean | undefined; + name?: string | undefined; + } + + interface DelHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + dateTime?: string | undefined; + } + + interface DialogHTMLAttributes extends HTMLAttributes { + onCancel?: ReactEventHandler | undefined; + onClose?: ReactEventHandler | undefined; + open?: boolean | undefined; + } + + interface EmbedHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + src?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + } + + interface FieldsetHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + name?: string | undefined; + } + + interface FormHTMLAttributes extends HTMLAttributes { + acceptCharset?: string | undefined; + action?: + | string + | undefined + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + autoComplete?: string | undefined; + encType?: string | undefined; + method?: string | undefined; + name?: string | undefined; + noValidate?: boolean | undefined; + target?: string | undefined; + } + + interface HtmlHTMLAttributes extends HTMLAttributes { + manifest?: string | undefined; + } + + interface IframeHTMLAttributes extends HTMLAttributes { + allow?: string | undefined; + allowFullScreen?: boolean | undefined; + allowTransparency?: boolean | undefined; + /** @deprecated */ + frameBorder?: number | string | undefined; + height?: number | string | undefined; + loading?: "eager" | "lazy" | undefined; + /** @deprecated */ + marginHeight?: number | undefined; + /** @deprecated */ + marginWidth?: number | undefined; + name?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sandbox?: string | undefined; + /** @deprecated */ + scrolling?: string | undefined; + seamless?: boolean | undefined; + src?: string | undefined; + srcDoc?: string | undefined; + width?: number | string | undefined; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES {} + + interface ImgHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + crossOrigin?: CrossOrigin; + decoding?: "async" | "auto" | "sync" | undefined; + fetchPriority?: "high" | "low" | "auto"; + height?: number | string | undefined; + loading?: "eager" | "lazy" | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + src?: + | string + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_IMG_SRC_TYPES + ] + | undefined; + srcSet?: string | undefined; + useMap?: string | undefined; + width?: number | string | undefined; + } + + interface InsHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + dateTime?: string | undefined; + } + + type HTMLInputTypeAttribute = + | "button" + | "checkbox" + | "color" + | "date" + | "datetime-local" + | "email" + | "file" + | "hidden" + | "image" + | "month" + | "number" + | "password" + | "radio" + | "range" + | "reset" + | "search" + | "submit" + | "tel" + | "text" + | "time" + | "url" + | "week" + | (string & {}); + + type AutoFillAddressKind = "billing" | "shipping"; + type AutoFillBase = "" | "off" | "on"; + type AutoFillContactField = + | "email" + | "tel" + | "tel-area-code" + | "tel-country-code" + | "tel-extension" + | "tel-local" + | "tel-local-prefix" + | "tel-local-suffix" + | "tel-national"; + type AutoFillContactKind = "home" | "mobile" | "work"; + type AutoFillCredentialField = "webauthn"; + type AutoFillNormalField = + | "additional-name" + | "address-level1" + | "address-level2" + | "address-level3" + | "address-level4" + | "address-line1" + | "address-line2" + | "address-line3" + | "bday-day" + | "bday-month" + | "bday-year" + | "cc-csc" + | "cc-exp" + | "cc-exp-month" + | "cc-exp-year" + | "cc-family-name" + | "cc-given-name" + | "cc-name" + | "cc-number" + | "cc-type" + | "country" + | "country-name" + | "current-password" + | "family-name" + | "given-name" + | "honorific-prefix" + | "honorific-suffix" + | "name" + | "new-password" + | "one-time-code" + | "organization" + | "postal-code" + | "street-address" + | "transaction-amount" + | "transaction-currency" + | "username"; + type OptionalPrefixToken = `${T} ` | ""; + type OptionalPostfixToken = ` ${T}` | ""; + type AutoFillField = AutoFillNormalField | `${OptionalPrefixToken}${AutoFillContactField}`; + type AutoFillSection = `section-${string}`; + type AutoFill = + | AutoFillBase + | `${OptionalPrefixToken}${OptionalPrefixToken< + AutoFillAddressKind + >}${AutoFillField}${OptionalPostfixToken}`; + type HTMLInputAutoCompleteAttribute = AutoFill | (string & {}); + + interface InputHTMLAttributes extends HTMLAttributes { + accept?: string | undefined; + alt?: string | undefined; + autoComplete?: HTMLInputAutoCompleteAttribute | undefined; + capture?: boolean | "user" | "environment" | undefined; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute + checked?: boolean | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + formAction?: + | string + | ((formData: FormData) => void | Promise) + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ] + | undefined; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + height?: number | string | undefined; + list?: string | undefined; + max?: number | string | undefined; + maxLength?: number | undefined; + min?: number | string | undefined; + minLength?: number | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + pattern?: string | undefined; + placeholder?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + size?: number | undefined; + src?: string | undefined; + step?: number | string | undefined; + type?: HTMLInputTypeAttribute | undefined; + value?: string | readonly string[] | number | undefined; + width?: number | string | undefined; + + onChange?: ChangeEventHandler | undefined; + } + + interface KeygenHTMLAttributes extends HTMLAttributes { + challenge?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + keyType?: string | undefined; + keyParams?: string | undefined; + name?: string | undefined; + } + + interface LabelHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + htmlFor?: string | undefined; + } + + interface LiHTMLAttributes extends HTMLAttributes { + value?: string | readonly string[] | number | undefined; + } + + interface LinkHTMLAttributes extends HTMLAttributes { + as?: string | undefined; + blocking?: "render" | (string & {}) | undefined; + crossOrigin?: CrossOrigin; + fetchPriority?: "high" | "low" | "auto"; + href?: string | undefined; + hrefLang?: string | undefined; + integrity?: string | undefined; + media?: string | undefined; + imageSrcSet?: string | undefined; + imageSizes?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + type?: string | undefined; + charSet?: string | undefined; + + // React props + precedence?: string | undefined; + } + + interface MapHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + + interface MenuHTMLAttributes extends HTMLAttributes { + type?: string | undefined; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES {} + + interface MediaHTMLAttributes extends HTMLAttributes { + autoPlay?: boolean | undefined; + controls?: boolean | undefined; + controlsList?: string | undefined; + crossOrigin?: CrossOrigin; + loop?: boolean | undefined; + mediaGroup?: string | undefined; + muted?: boolean | undefined; + playsInline?: boolean | undefined; + preload?: string | undefined; + src?: + | string + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_MEDIA_SRC_TYPES + ] + | undefined; + } + + interface MetaHTMLAttributes extends HTMLAttributes { + charSet?: string | undefined; + content?: string | undefined; + httpEquiv?: string | undefined; + media?: string | undefined; + name?: string | undefined; + } + + interface MeterHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + high?: number | undefined; + low?: number | undefined; + max?: number | string | undefined; + min?: number | string | undefined; + optimum?: number | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface QuoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + + interface ObjectHTMLAttributes extends HTMLAttributes { + classID?: string | undefined; + data?: string | undefined; + form?: string | undefined; + height?: number | string | undefined; + name?: string | undefined; + type?: string | undefined; + useMap?: string | undefined; + width?: number | string | undefined; + wmode?: string | undefined; + } + + interface OlHTMLAttributes extends HTMLAttributes { + reversed?: boolean | undefined; + start?: number | undefined; + type?: "1" | "a" | "A" | "i" | "I" | undefined; + } + + interface OptgroupHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + } + + interface OptionHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + selected?: boolean | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface OutputHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + htmlFor?: string | undefined; + name?: string | undefined; + } + + interface ParamHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface ProgressHTMLAttributes extends HTMLAttributes { + max?: number | string | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface SlotHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + + interface ScriptHTMLAttributes extends HTMLAttributes { + async?: boolean | undefined; + blocking?: "render" | (string & {}) | undefined; + /** @deprecated */ + charSet?: string | undefined; + crossOrigin?: CrossOrigin; + defer?: boolean | undefined; + integrity?: string | undefined; + noModule?: boolean | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + src?: string | undefined; + type?: string | undefined; + } + + interface SelectHTMLAttributes extends HTMLAttributes { + autoComplete?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + required?: boolean | undefined; + size?: number | undefined; + value?: string | readonly string[] | number | undefined; + onChange?: ChangeEventHandler | undefined; + } + + interface SourceHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + media?: string | undefined; + sizes?: string | undefined; + src?: string | undefined; + srcSet?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + } + + interface StyleHTMLAttributes extends HTMLAttributes { + blocking?: "render" | (string & {}) | undefined; + media?: string | undefined; + scoped?: boolean | undefined; + type?: string | undefined; + + // React props + href?: string | undefined; + precedence?: string | undefined; + } + + interface TableHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | undefined; + bgcolor?: string | undefined; + border?: number | undefined; + cellPadding?: number | string | undefined; + cellSpacing?: number | string | undefined; + frame?: boolean | undefined; + rules?: "none" | "groups" | "rows" | "columns" | "all" | undefined; + summary?: string | undefined; + width?: number | string | undefined; + } + + interface TextareaHTMLAttributes extends HTMLAttributes { + autoComplete?: string | undefined; + cols?: number | undefined; + dirName?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + maxLength?: number | undefined; + minLength?: number | undefined; + name?: string | undefined; + placeholder?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + rows?: number | undefined; + value?: string | readonly string[] | number | undefined; + wrap?: string | undefined; + + onChange?: ChangeEventHandler | undefined; + } + + interface TdHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | "justify" | "char" | undefined; + colSpan?: number | undefined; + headers?: string | undefined; + rowSpan?: number | undefined; + scope?: string | undefined; + abbr?: string | undefined; + height?: number | string | undefined; + width?: number | string | undefined; + valign?: "top" | "middle" | "bottom" | "baseline" | undefined; + } + + interface ThHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | "justify" | "char" | undefined; + colSpan?: number | undefined; + headers?: string | undefined; + rowSpan?: number | undefined; + scope?: string | undefined; + abbr?: string | undefined; + } + + interface TimeHTMLAttributes extends HTMLAttributes { + dateTime?: string | undefined; + } + + interface TrackHTMLAttributes extends HTMLAttributes { + default?: boolean | undefined; + kind?: string | undefined; + label?: string | undefined; + src?: string | undefined; + srcLang?: string | undefined; + } + + interface VideoHTMLAttributes extends MediaHTMLAttributes { + height?: number | string | undefined; + playsInline?: boolean | undefined; + poster?: string | undefined; + width?: number | string | undefined; + disablePictureInPicture?: boolean | undefined; + disableRemotePlayback?: boolean | undefined; + + onResize?: ReactEventHandler | undefined; + onResizeCapture?: ReactEventHandler | undefined; + } + + // this list is "complete" in that it contains every SVG attribute + // that React supports, but the types can be improved. + // Full list here: https://facebook.github.io/react/docs/dom-elements.html + // + // The three broad type categories are (in order of restrictiveness): + // - "number | string" + // - "string" + // - union of string literals + interface SVGAttributes extends AriaAttributes, DOMAttributes { + // React-specific Attributes + suppressHydrationWarning?: boolean | undefined; + + // Attributes which also defined in HTMLAttributes + // See comment in SVGDOMPropertyConfig.js + className?: string | undefined; + color?: string | undefined; + height?: number | string | undefined; + id?: string | undefined; + lang?: string | undefined; + max?: number | string | undefined; + media?: string | undefined; + method?: string | undefined; + min?: number | string | undefined; + name?: string | undefined; + style?: CSSProperties | undefined; + target?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + + // Other HTML properties supported by SVG elements in browsers + role?: AriaRole | undefined; + tabIndex?: number | undefined; + crossOrigin?: CrossOrigin; + + // SVG Specific attributes + accentHeight?: number | string | undefined; + accumulate?: "none" | "sum" | undefined; + additive?: "replace" | "sum" | undefined; + alignmentBaseline?: + | "auto" + | "baseline" + | "before-edge" + | "text-before-edge" + | "middle" + | "central" + | "after-edge" + | "text-after-edge" + | "ideographic" + | "alphabetic" + | "hanging" + | "mathematical" + | "inherit" + | undefined; + allowReorder?: "no" | "yes" | undefined; + alphabetic?: number | string | undefined; + amplitude?: number | string | undefined; + arabicForm?: "initial" | "medial" | "terminal" | "isolated" | undefined; + ascent?: number | string | undefined; + attributeName?: string | undefined; + attributeType?: string | undefined; + autoReverse?: Booleanish | undefined; + azimuth?: number | string | undefined; + baseFrequency?: number | string | undefined; + baselineShift?: number | string | undefined; + baseProfile?: number | string | undefined; + bbox?: number | string | undefined; + begin?: number | string | undefined; + bias?: number | string | undefined; + by?: number | string | undefined; + calcMode?: number | string | undefined; + capHeight?: number | string | undefined; + clip?: number | string | undefined; + clipPath?: string | undefined; + clipPathUnits?: number | string | undefined; + clipRule?: number | string | undefined; + colorInterpolation?: number | string | undefined; + colorInterpolationFilters?: "auto" | "sRGB" | "linearRGB" | "inherit" | undefined; + colorProfile?: number | string | undefined; + colorRendering?: number | string | undefined; + contentScriptType?: number | string | undefined; + contentStyleType?: number | string | undefined; + cursor?: number | string | undefined; + cx?: number | string | undefined; + cy?: number | string | undefined; + d?: string | undefined; + decelerate?: number | string | undefined; + descent?: number | string | undefined; + diffuseConstant?: number | string | undefined; + direction?: number | string | undefined; + display?: number | string | undefined; + divisor?: number | string | undefined; + dominantBaseline?: number | string | undefined; + dur?: number | string | undefined; + dx?: number | string | undefined; + dy?: number | string | undefined; + edgeMode?: number | string | undefined; + elevation?: number | string | undefined; + enableBackground?: number | string | undefined; + end?: number | string | undefined; + exponent?: number | string | undefined; + externalResourcesRequired?: Booleanish | undefined; + fill?: string | undefined; + fillOpacity?: number | string | undefined; + fillRule?: "nonzero" | "evenodd" | "inherit" | undefined; + filter?: string | undefined; + filterRes?: number | string | undefined; + filterUnits?: number | string | undefined; + floodColor?: number | string | undefined; + floodOpacity?: number | string | undefined; + focusable?: Booleanish | "auto" | undefined; + fontFamily?: string | undefined; + fontSize?: number | string | undefined; + fontSizeAdjust?: number | string | undefined; + fontStretch?: number | string | undefined; + fontStyle?: number | string | undefined; + fontVariant?: number | string | undefined; + fontWeight?: number | string | undefined; + format?: number | string | undefined; + fr?: number | string | undefined; + from?: number | string | undefined; + fx?: number | string | undefined; + fy?: number | string | undefined; + g1?: number | string | undefined; + g2?: number | string | undefined; + glyphName?: number | string | undefined; + glyphOrientationHorizontal?: number | string | undefined; + glyphOrientationVertical?: number | string | undefined; + glyphRef?: number | string | undefined; + gradientTransform?: string | undefined; + gradientUnits?: string | undefined; + hanging?: number | string | undefined; + horizAdvX?: number | string | undefined; + horizOriginX?: number | string | undefined; + href?: string | undefined; + ideographic?: number | string | undefined; + imageRendering?: number | string | undefined; + in2?: number | string | undefined; + in?: string | undefined; + intercept?: number | string | undefined; + k1?: number | string | undefined; + k2?: number | string | undefined; + k3?: number | string | undefined; + k4?: number | string | undefined; + k?: number | string | undefined; + kernelMatrix?: number | string | undefined; + kernelUnitLength?: number | string | undefined; + kerning?: number | string | undefined; + keyPoints?: number | string | undefined; + keySplines?: number | string | undefined; + keyTimes?: number | string | undefined; + lengthAdjust?: number | string | undefined; + letterSpacing?: number | string | undefined; + lightingColor?: number | string | undefined; + limitingConeAngle?: number | string | undefined; + local?: number | string | undefined; + markerEnd?: string | undefined; + markerHeight?: number | string | undefined; + markerMid?: string | undefined; + markerStart?: string | undefined; + markerUnits?: number | string | undefined; + markerWidth?: number | string | undefined; + mask?: string | undefined; + maskContentUnits?: number | string | undefined; + maskUnits?: number | string | undefined; + mathematical?: number | string | undefined; + mode?: number | string | undefined; + numOctaves?: number | string | undefined; + offset?: number | string | undefined; + opacity?: number | string | undefined; + operator?: number | string | undefined; + order?: number | string | undefined; + orient?: number | string | undefined; + orientation?: number | string | undefined; + origin?: number | string | undefined; + overflow?: number | string | undefined; + overlinePosition?: number | string | undefined; + overlineThickness?: number | string | undefined; + paintOrder?: number | string | undefined; + panose1?: number | string | undefined; + path?: string | undefined; + pathLength?: number | string | undefined; + patternContentUnits?: string | undefined; + patternTransform?: number | string | undefined; + patternUnits?: string | undefined; + pointerEvents?: number | string | undefined; + points?: string | undefined; + pointsAtX?: number | string | undefined; + pointsAtY?: number | string | undefined; + pointsAtZ?: number | string | undefined; + preserveAlpha?: Booleanish | undefined; + preserveAspectRatio?: string | undefined; + primitiveUnits?: number | string | undefined; + r?: number | string | undefined; + radius?: number | string | undefined; + refX?: number | string | undefined; + refY?: number | string | undefined; + renderingIntent?: number | string | undefined; + repeatCount?: number | string | undefined; + repeatDur?: number | string | undefined; + requiredExtensions?: number | string | undefined; + requiredFeatures?: number | string | undefined; + restart?: number | string | undefined; + result?: string | undefined; + rotate?: number | string | undefined; + rx?: number | string | undefined; + ry?: number | string | undefined; + scale?: number | string | undefined; + seed?: number | string | undefined; + shapeRendering?: number | string | undefined; + slope?: number | string | undefined; + spacing?: number | string | undefined; + specularConstant?: number | string | undefined; + specularExponent?: number | string | undefined; + speed?: number | string | undefined; + spreadMethod?: string | undefined; + startOffset?: number | string | undefined; + stdDeviation?: number | string | undefined; + stemh?: number | string | undefined; + stemv?: number | string | undefined; + stitchTiles?: number | string | undefined; + stopColor?: string | undefined; + stopOpacity?: number | string | undefined; + strikethroughPosition?: number | string | undefined; + strikethroughThickness?: number | string | undefined; + string?: number | string | undefined; + stroke?: string | undefined; + strokeDasharray?: string | number | undefined; + strokeDashoffset?: string | number | undefined; + strokeLinecap?: "butt" | "round" | "square" | "inherit" | undefined; + strokeLinejoin?: "miter" | "round" | "bevel" | "inherit" | undefined; + strokeMiterlimit?: number | string | undefined; + strokeOpacity?: number | string | undefined; + strokeWidth?: number | string | undefined; + surfaceScale?: number | string | undefined; + systemLanguage?: number | string | undefined; + tableValues?: number | string | undefined; + targetX?: number | string | undefined; + targetY?: number | string | undefined; + textAnchor?: string | undefined; + textDecoration?: number | string | undefined; + textLength?: number | string | undefined; + textRendering?: number | string | undefined; + to?: number | string | undefined; + transform?: string | undefined; + u1?: number | string | undefined; + u2?: number | string | undefined; + underlinePosition?: number | string | undefined; + underlineThickness?: number | string | undefined; + unicode?: number | string | undefined; + unicodeBidi?: number | string | undefined; + unicodeRange?: number | string | undefined; + unitsPerEm?: number | string | undefined; + vAlphabetic?: number | string | undefined; + values?: string | undefined; + vectorEffect?: number | string | undefined; + version?: string | undefined; + vertAdvY?: number | string | undefined; + vertOriginX?: number | string | undefined; + vertOriginY?: number | string | undefined; + vHanging?: number | string | undefined; + vIdeographic?: number | string | undefined; + viewBox?: string | undefined; + viewTarget?: number | string | undefined; + visibility?: number | string | undefined; + vMathematical?: number | string | undefined; + widths?: number | string | undefined; + wordSpacing?: number | string | undefined; + writingMode?: number | string | undefined; + x1?: number | string | undefined; + x2?: number | string | undefined; + x?: number | string | undefined; + xChannelSelector?: string | undefined; + xHeight?: number | string | undefined; + xlinkActuate?: string | undefined; + xlinkArcrole?: string | undefined; + xlinkHref?: string | undefined; + xlinkRole?: string | undefined; + xlinkShow?: string | undefined; + xlinkTitle?: string | undefined; + xlinkType?: string | undefined; + xmlBase?: string | undefined; + xmlLang?: string | undefined; + xmlns?: string | undefined; + xmlnsXlink?: string | undefined; + xmlSpace?: string | undefined; + y1?: number | string | undefined; + y2?: number | string | undefined; + y?: number | string | undefined; + yChannelSelector?: string | undefined; + z?: number | string | undefined; + zoomAndPan?: string | undefined; + } + + interface WebViewHTMLAttributes extends HTMLAttributes { + allowFullScreen?: boolean | undefined; + allowpopups?: boolean | undefined; + autosize?: boolean | undefined; + blinkfeatures?: string | undefined; + disableblinkfeatures?: string | undefined; + disableguestresize?: boolean | undefined; + disablewebsecurity?: boolean | undefined; + guestinstance?: string | undefined; + httpreferrer?: string | undefined; + nodeintegration?: boolean | undefined; + partition?: string | undefined; + plugins?: boolean | undefined; + preload?: string | undefined; + src?: string | undefined; + useragent?: string | undefined; + webpreferences?: string | undefined; + } + + // TODO: Move to react-dom + type HTMLElementType = + | "a" + | "abbr" + | "address" + | "area" + | "article" + | "aside" + | "audio" + | "b" + | "base" + | "bdi" + | "bdo" + | "big" + | "blockquote" + | "body" + | "br" + | "button" + | "canvas" + | "caption" + | "center" + | "cite" + | "code" + | "col" + | "colgroup" + | "data" + | "datalist" + | "dd" + | "del" + | "details" + | "dfn" + | "dialog" + | "div" + | "dl" + | "dt" + | "em" + | "embed" + | "fieldset" + | "figcaption" + | "figure" + | "footer" + | "form" + | "h1" + | "h2" + | "h3" + | "h4" + | "h5" + | "h6" + | "head" + | "header" + | "hgroup" + | "hr" + | "html" + | "i" + | "iframe" + | "img" + | "input" + | "ins" + | "kbd" + | "keygen" + | "label" + | "legend" + | "li" + | "link" + | "main" + | "map" + | "mark" + | "menu" + | "menuitem" + | "meta" + | "meter" + | "nav" + | "noscript" + | "object" + | "ol" + | "optgroup" + | "option" + | "output" + | "p" + | "param" + | "picture" + | "pre" + | "progress" + | "q" + | "rp" + | "rt" + | "ruby" + | "s" + | "samp" + | "search" + | "slot" + | "script" + | "section" + | "select" + | "small" + | "source" + | "span" + | "strong" + | "style" + | "sub" + | "summary" + | "sup" + | "table" + | "template" + | "tbody" + | "td" + | "textarea" + | "tfoot" + | "th" + | "thead" + | "time" + | "title" + | "tr" + | "track" + | "u" + | "ul" + | "var" + | "video" + | "wbr" + | "webview"; + + // TODO: Move to react-dom + type SVGElementType = + | "animate" + | "circle" + | "clipPath" + | "defs" + | "desc" + | "ellipse" + | "feBlend" + | "feColorMatrix" + | "feComponentTransfer" + | "feComposite" + | "feConvolveMatrix" + | "feDiffuseLighting" + | "feDisplacementMap" + | "feDistantLight" + | "feDropShadow" + | "feFlood" + | "feFuncA" + | "feFuncB" + | "feFuncG" + | "feFuncR" + | "feGaussianBlur" + | "feImage" + | "feMerge" + | "feMergeNode" + | "feMorphology" + | "feOffset" + | "fePointLight" + | "feSpecularLighting" + | "feSpotLight" + | "feTile" + | "feTurbulence" + | "filter" + | "foreignObject" + | "g" + | "image" + | "line" + | "linearGradient" + | "marker" + | "mask" + | "metadata" + | "path" + | "pattern" + | "polygon" + | "polyline" + | "radialGradient" + | "rect" + | "stop" + | "svg" + | "switch" + | "symbol" + | "text" + | "textPath" + | "tspan" + | "use" + | "view"; + + // + // Browser Interfaces + // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts + // ---------------------------------------------------------------------- + + interface AbstractView { + styleMedia: StyleMedia; + document: Document; + } + + interface Touch { + identifier: number; + target: EventTarget; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + pageX: number; + pageY: number; + } + + interface TouchList { + [index: number]: Touch; + length: number; + item(index: number): Touch; + identifiedTouch(identifier: number): Touch; + } + + // + // Error Interfaces + // ---------------------------------------------------------------------- + interface ErrorInfo { + /** + * Captures which component contained the exception, and its ancestors. + */ + componentStack?: string | null; + digest?: string | null; + } + + // Keep in sync with JSX namespace in ./jsx-runtime.d.ts and ./jsx-dev-runtime.d.ts + namespace JSX { + interface Element extends React.ReactElement {} + interface ElementClass extends React.Component { + render(): React.ReactNode; + } + interface ElementAttributesProperty { + props: {}; + } + interface ElementChildrenAttribute { + children: {}; + } + + // We can't recurse forever because `type` can't be self-referential; + // let's assume it's reasonable to do a single React.lazy() around a single React.memo() / vice-versa + type LibraryManagedAttributes = C extends + React.MemoExoticComponent | React.LazyExoticComponent + ? T extends React.MemoExoticComponent | React.LazyExoticComponent + ? ReactManagedAttributes + : ReactManagedAttributes + : ReactManagedAttributes; + + interface IntrinsicAttributes extends React.Attributes {} + interface IntrinsicClassAttributes extends React.ClassAttributes {} + + interface IntrinsicElements { + // HTML + a: React.DetailedHTMLProps, HTMLAnchorElement>; + abbr: React.DetailedHTMLProps, HTMLElement>; + address: React.DetailedHTMLProps, HTMLElement>; + area: React.DetailedHTMLProps, HTMLAreaElement>; + article: React.DetailedHTMLProps, HTMLElement>; + aside: React.DetailedHTMLProps, HTMLElement>; + audio: React.DetailedHTMLProps, HTMLAudioElement>; + b: React.DetailedHTMLProps, HTMLElement>; + base: React.DetailedHTMLProps, HTMLBaseElement>; + bdi: React.DetailedHTMLProps, HTMLElement>; + bdo: React.DetailedHTMLProps, HTMLElement>; + big: React.DetailedHTMLProps, HTMLElement>; + blockquote: React.DetailedHTMLProps, HTMLQuoteElement>; + body: React.DetailedHTMLProps, HTMLBodyElement>; + br: React.DetailedHTMLProps, HTMLBRElement>; + button: React.DetailedHTMLProps, HTMLButtonElement>; + canvas: React.DetailedHTMLProps, HTMLCanvasElement>; + caption: React.DetailedHTMLProps, HTMLElement>; + center: React.DetailedHTMLProps, HTMLElement>; + cite: React.DetailedHTMLProps, HTMLElement>; + code: React.DetailedHTMLProps, HTMLElement>; + col: React.DetailedHTMLProps, HTMLTableColElement>; + colgroup: React.DetailedHTMLProps, HTMLTableColElement>; + data: React.DetailedHTMLProps, HTMLDataElement>; + datalist: React.DetailedHTMLProps, HTMLDataListElement>; + dd: React.DetailedHTMLProps, HTMLElement>; + del: React.DetailedHTMLProps, HTMLModElement>; + details: React.DetailedHTMLProps, HTMLDetailsElement>; + dfn: React.DetailedHTMLProps, HTMLElement>; + dialog: React.DetailedHTMLProps, HTMLDialogElement>; + div: React.DetailedHTMLProps, HTMLDivElement>; + dl: React.DetailedHTMLProps, HTMLDListElement>; + dt: React.DetailedHTMLProps, HTMLElement>; + em: React.DetailedHTMLProps, HTMLElement>; + embed: React.DetailedHTMLProps, HTMLEmbedElement>; + fieldset: React.DetailedHTMLProps, HTMLFieldSetElement>; + figcaption: React.DetailedHTMLProps, HTMLElement>; + figure: React.DetailedHTMLProps, HTMLElement>; + footer: React.DetailedHTMLProps, HTMLElement>; + form: React.DetailedHTMLProps, HTMLFormElement>; + h1: React.DetailedHTMLProps, HTMLHeadingElement>; + h2: React.DetailedHTMLProps, HTMLHeadingElement>; + h3: React.DetailedHTMLProps, HTMLHeadingElement>; + h4: React.DetailedHTMLProps, HTMLHeadingElement>; + h5: React.DetailedHTMLProps, HTMLHeadingElement>; + h6: React.DetailedHTMLProps, HTMLHeadingElement>; + head: React.DetailedHTMLProps, HTMLHeadElement>; + header: React.DetailedHTMLProps, HTMLElement>; + hgroup: React.DetailedHTMLProps, HTMLElement>; + hr: React.DetailedHTMLProps, HTMLHRElement>; + html: React.DetailedHTMLProps, HTMLHtmlElement>; + i: React.DetailedHTMLProps, HTMLElement>; + iframe: React.DetailedHTMLProps, HTMLIFrameElement>; + img: React.DetailedHTMLProps, HTMLImageElement>; + input: React.DetailedHTMLProps, HTMLInputElement>; + ins: React.DetailedHTMLProps, HTMLModElement>; + kbd: React.DetailedHTMLProps, HTMLElement>; + keygen: React.DetailedHTMLProps, HTMLElement>; + label: React.DetailedHTMLProps, HTMLLabelElement>; + legend: React.DetailedHTMLProps, HTMLLegendElement>; + li: React.DetailedHTMLProps, HTMLLIElement>; + link: React.DetailedHTMLProps, HTMLLinkElement>; + main: React.DetailedHTMLProps, HTMLElement>; + map: React.DetailedHTMLProps, HTMLMapElement>; + mark: React.DetailedHTMLProps, HTMLElement>; + menu: React.DetailedHTMLProps, HTMLElement>; + menuitem: React.DetailedHTMLProps, HTMLElement>; + meta: React.DetailedHTMLProps, HTMLMetaElement>; + meter: React.DetailedHTMLProps, HTMLMeterElement>; + nav: React.DetailedHTMLProps, HTMLElement>; + noindex: React.DetailedHTMLProps, HTMLElement>; + noscript: React.DetailedHTMLProps, HTMLElement>; + object: React.DetailedHTMLProps, HTMLObjectElement>; + ol: React.DetailedHTMLProps, HTMLOListElement>; + optgroup: React.DetailedHTMLProps, HTMLOptGroupElement>; + option: React.DetailedHTMLProps, HTMLOptionElement>; + output: React.DetailedHTMLProps, HTMLOutputElement>; + p: React.DetailedHTMLProps, HTMLParagraphElement>; + param: React.DetailedHTMLProps, HTMLParamElement>; + picture: React.DetailedHTMLProps, HTMLElement>; + pre: React.DetailedHTMLProps, HTMLPreElement>; + progress: React.DetailedHTMLProps, HTMLProgressElement>; + q: React.DetailedHTMLProps, HTMLQuoteElement>; + rp: React.DetailedHTMLProps, HTMLElement>; + rt: React.DetailedHTMLProps, HTMLElement>; + ruby: React.DetailedHTMLProps, HTMLElement>; + s: React.DetailedHTMLProps, HTMLElement>; + samp: React.DetailedHTMLProps, HTMLElement>; + search: React.DetailedHTMLProps, HTMLElement>; + slot: React.DetailedHTMLProps, HTMLSlotElement>; + script: React.DetailedHTMLProps, HTMLScriptElement>; + section: React.DetailedHTMLProps, HTMLElement>; + select: React.DetailedHTMLProps, HTMLSelectElement>; + small: React.DetailedHTMLProps, HTMLElement>; + source: React.DetailedHTMLProps, HTMLSourceElement>; + span: React.DetailedHTMLProps, HTMLSpanElement>; + strong: React.DetailedHTMLProps, HTMLElement>; + style: React.DetailedHTMLProps, HTMLStyleElement>; + sub: React.DetailedHTMLProps, HTMLElement>; + summary: React.DetailedHTMLProps, HTMLElement>; + sup: React.DetailedHTMLProps, HTMLElement>; + table: React.DetailedHTMLProps, HTMLTableElement>; + template: React.DetailedHTMLProps, HTMLTemplateElement>; + tbody: React.DetailedHTMLProps, HTMLTableSectionElement>; + td: React.DetailedHTMLProps, HTMLTableDataCellElement>; + textarea: React.DetailedHTMLProps, HTMLTextAreaElement>; + tfoot: React.DetailedHTMLProps, HTMLTableSectionElement>; + th: React.DetailedHTMLProps, HTMLTableHeaderCellElement>; + thead: React.DetailedHTMLProps, HTMLTableSectionElement>; + time: React.DetailedHTMLProps, HTMLTimeElement>; + title: React.DetailedHTMLProps, HTMLTitleElement>; + tr: React.DetailedHTMLProps, HTMLTableRowElement>; + track: React.DetailedHTMLProps, HTMLTrackElement>; + u: React.DetailedHTMLProps, HTMLElement>; + ul: React.DetailedHTMLProps, HTMLUListElement>; + "var": React.DetailedHTMLProps, HTMLElement>; + video: React.DetailedHTMLProps, HTMLVideoElement>; + wbr: React.DetailedHTMLProps, HTMLElement>; + webview: React.DetailedHTMLProps, HTMLWebViewElement>; + + // SVG + svg: React.SVGProps; + + animate: React.SVGProps; // TODO: It is SVGAnimateElement but is not in TypeScript's lib.dom.d.ts for now. + animateMotion: React.SVGProps; + animateTransform: React.SVGProps; // TODO: It is SVGAnimateTransformElement but is not in TypeScript's lib.dom.d.ts for now. + circle: React.SVGProps; + clipPath: React.SVGProps; + defs: React.SVGProps; + desc: React.SVGProps; + ellipse: React.SVGProps; + feBlend: React.SVGProps; + feColorMatrix: React.SVGProps; + feComponentTransfer: React.SVGProps; + feComposite: React.SVGProps; + feConvolveMatrix: React.SVGProps; + feDiffuseLighting: React.SVGProps; + feDisplacementMap: React.SVGProps; + feDistantLight: React.SVGProps; + feDropShadow: React.SVGProps; + feFlood: React.SVGProps; + feFuncA: React.SVGProps; + feFuncB: React.SVGProps; + feFuncG: React.SVGProps; + feFuncR: React.SVGProps; + feGaussianBlur: React.SVGProps; + feImage: React.SVGProps; + feMerge: React.SVGProps; + feMergeNode: React.SVGProps; + feMorphology: React.SVGProps; + feOffset: React.SVGProps; + fePointLight: React.SVGProps; + feSpecularLighting: React.SVGProps; + feSpotLight: React.SVGProps; + feTile: React.SVGProps; + feTurbulence: React.SVGProps; + filter: React.SVGProps; + foreignObject: React.SVGProps; + g: React.SVGProps; + image: React.SVGProps; + line: React.SVGLineElementAttributes; + linearGradient: React.SVGProps; + marker: React.SVGProps; + mask: React.SVGProps; + metadata: React.SVGProps; + mpath: React.SVGProps; + path: React.SVGProps; + pattern: React.SVGProps; + polygon: React.SVGProps; + polyline: React.SVGProps; + radialGradient: React.SVGProps; + rect: React.SVGProps; + set: React.SVGProps; + stop: React.SVGProps; + switch: React.SVGProps; + symbol: React.SVGProps; + text: React.SVGTextElementAttributes; + textPath: React.SVGProps; + tspan: React.SVGProps; + use: React.SVGProps; + view: React.SVGProps; + } + } +} + +type InexactPartial = { [K in keyof T]?: T[K] | undefined }; + +// Any prop that has a default prop becomes optional, but its type is unchanged +// Undeclared default props are augmented into the resulting allowable attributes +// If declared props have indexed properties, ignore default props entirely as keyof gets widened +// Wrap in an outer-level conditional type to allow distribution over props that are unions +type Defaultize = P extends any ? string extends keyof P ? P + : + & Pick> + & InexactPartial>> + & InexactPartial>> + : never; + +type ReactManagedAttributes = C extends { defaultProps: infer D } ? Defaultize + : P; diff --git a/node_modules/@types/react/ts5.0/jsx-dev-runtime.d.ts b/node_modules/@types/react/ts5.0/jsx-dev-runtime.d.ts new file mode 100644 index 00000000..87d1dfe3 --- /dev/null +++ b/node_modules/@types/react/ts5.0/jsx-dev-runtime.d.ts @@ -0,0 +1,44 @@ +import * as React from "./"; +export { Fragment } from "./"; + +export namespace JSX { + interface Element extends React.JSX.Element {} + interface ElementClass extends React.JSX.ElementClass {} + interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {} + interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {} + type LibraryManagedAttributes = React.JSX.LibraryManagedAttributes; + interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {} + interface IntrinsicClassAttributes extends React.JSX.IntrinsicClassAttributes {} + interface IntrinsicElements extends React.JSX.IntrinsicElements {} +} + +export interface JSXSource { + /** + * The source file where the element originates from. + */ + fileName?: string | undefined; + + /** + * The line number where the element was created. + */ + lineNumber?: number | undefined; + + /** + * The column number where the element was created. + */ + columnNumber?: number | undefined; +} + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsxDEV( + type: React.ElementType, + props: unknown, + key: React.Key | undefined, + isStatic: boolean, + source?: JSXSource, + self?: unknown, +): React.ReactElement; diff --git a/node_modules/@types/react/ts5.0/jsx-runtime.d.ts b/node_modules/@types/react/ts5.0/jsx-runtime.d.ts new file mode 100644 index 00000000..8cc3b974 --- /dev/null +++ b/node_modules/@types/react/ts5.0/jsx-runtime.d.ts @@ -0,0 +1,35 @@ +import * as React from "./"; +export { Fragment } from "./"; + +export namespace JSX { + interface Element extends React.JSX.Element {} + interface ElementClass extends React.JSX.ElementClass {} + interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {} + interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {} + type LibraryManagedAttributes = React.JSX.LibraryManagedAttributes; + interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {} + interface IntrinsicClassAttributes extends React.JSX.IntrinsicClassAttributes {} + interface IntrinsicElements extends React.JSX.IntrinsicElements {} +} + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsx( + type: React.ElementType, + props: unknown, + key?: React.Key, +): React.ReactElement; + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsxs( + type: React.ElementType, + props: unknown, + key?: React.Key, +): React.ReactElement; diff --git a/node_modules/@types/react/ts5.0/v18/global.d.ts b/node_modules/@types/react/ts5.0/v18/global.d.ts new file mode 100644 index 00000000..8911182a --- /dev/null +++ b/node_modules/@types/react/ts5.0/v18/global.d.ts @@ -0,0 +1,161 @@ +/* +React projects that don't include the DOM library need these interfaces to compile. +React Native applications use React, but there is no DOM available. The JavaScript runtime +is ES6/ES2015 only. These definitions allow such projects to compile with only `--lib ES6`. + +Warning: all of these interfaces are empty. If you want type definitions for various properties +(such as HTMLInputElement.prototype.value), you need to add `--lib DOM` (via command line or tsconfig.json). +*/ + +interface Event {} +interface AnimationEvent extends Event {} +interface ClipboardEvent extends Event {} +interface CompositionEvent extends Event {} +interface DragEvent extends Event {} +interface FocusEvent extends Event {} +interface InputEvent extends Event {} +interface KeyboardEvent extends Event {} +interface MouseEvent extends Event {} +interface TouchEvent extends Event {} +interface PointerEvent extends Event {} +interface ToggleEvent extends Event {} +interface TransitionEvent extends Event {} +interface UIEvent extends Event {} +interface WheelEvent extends Event {} + +interface EventTarget {} +interface Document {} +interface DataTransfer {} +interface StyleMedia {} + +interface Element {} +interface DocumentFragment {} + +interface HTMLElement extends Element {} +interface HTMLAnchorElement extends HTMLElement {} +interface HTMLAreaElement extends HTMLElement {} +interface HTMLAudioElement extends HTMLElement {} +interface HTMLBaseElement extends HTMLElement {} +interface HTMLBodyElement extends HTMLElement {} +interface HTMLBRElement extends HTMLElement {} +interface HTMLButtonElement extends HTMLElement {} +interface HTMLCanvasElement extends HTMLElement {} +interface HTMLDataElement extends HTMLElement {} +interface HTMLDataListElement extends HTMLElement {} +interface HTMLDetailsElement extends HTMLElement {} +interface HTMLDialogElement extends HTMLElement {} +interface HTMLDivElement extends HTMLElement {} +interface HTMLDListElement extends HTMLElement {} +interface HTMLEmbedElement extends HTMLElement {} +interface HTMLFieldSetElement extends HTMLElement {} +interface HTMLFormElement extends HTMLElement {} +interface HTMLHeadingElement extends HTMLElement {} +interface HTMLHeadElement extends HTMLElement {} +interface HTMLHRElement extends HTMLElement {} +interface HTMLHtmlElement extends HTMLElement {} +interface HTMLIFrameElement extends HTMLElement {} +interface HTMLImageElement extends HTMLElement {} +interface HTMLInputElement extends HTMLElement {} +interface HTMLModElement extends HTMLElement {} +interface HTMLLabelElement extends HTMLElement {} +interface HTMLLegendElement extends HTMLElement {} +interface HTMLLIElement extends HTMLElement {} +interface HTMLLinkElement extends HTMLElement {} +interface HTMLMapElement extends HTMLElement {} +interface HTMLMetaElement extends HTMLElement {} +interface HTMLMeterElement extends HTMLElement {} +interface HTMLObjectElement extends HTMLElement {} +interface HTMLOListElement extends HTMLElement {} +interface HTMLOptGroupElement extends HTMLElement {} +interface HTMLOptionElement extends HTMLElement {} +interface HTMLOutputElement extends HTMLElement {} +interface HTMLParagraphElement extends HTMLElement {} +interface HTMLParamElement extends HTMLElement {} +interface HTMLPreElement extends HTMLElement {} +interface HTMLProgressElement extends HTMLElement {} +interface HTMLQuoteElement extends HTMLElement {} +interface HTMLSlotElement extends HTMLElement {} +interface HTMLScriptElement extends HTMLElement {} +interface HTMLSelectElement extends HTMLElement {} +interface HTMLSourceElement extends HTMLElement {} +interface HTMLSpanElement extends HTMLElement {} +interface HTMLStyleElement extends HTMLElement {} +interface HTMLTableElement extends HTMLElement {} +interface HTMLTableColElement extends HTMLElement {} +interface HTMLTableDataCellElement extends HTMLElement {} +interface HTMLTableHeaderCellElement extends HTMLElement {} +interface HTMLTableRowElement extends HTMLElement {} +interface HTMLTableSectionElement extends HTMLElement {} +interface HTMLTemplateElement extends HTMLElement {} +interface HTMLTextAreaElement extends HTMLElement {} +interface HTMLTimeElement extends HTMLElement {} +interface HTMLTitleElement extends HTMLElement {} +interface HTMLTrackElement extends HTMLElement {} +interface HTMLUListElement extends HTMLElement {} +interface HTMLVideoElement extends HTMLElement {} +interface HTMLWebViewElement extends HTMLElement {} + +interface SVGElement extends Element {} +interface SVGSVGElement extends SVGElement {} +interface SVGCircleElement extends SVGElement {} +interface SVGClipPathElement extends SVGElement {} +interface SVGDefsElement extends SVGElement {} +interface SVGDescElement extends SVGElement {} +interface SVGEllipseElement extends SVGElement {} +interface SVGFEBlendElement extends SVGElement {} +interface SVGFEColorMatrixElement extends SVGElement {} +interface SVGFEComponentTransferElement extends SVGElement {} +interface SVGFECompositeElement extends SVGElement {} +interface SVGFEConvolveMatrixElement extends SVGElement {} +interface SVGFEDiffuseLightingElement extends SVGElement {} +interface SVGFEDisplacementMapElement extends SVGElement {} +interface SVGFEDistantLightElement extends SVGElement {} +interface SVGFEDropShadowElement extends SVGElement {} +interface SVGFEFloodElement extends SVGElement {} +interface SVGFEFuncAElement extends SVGElement {} +interface SVGFEFuncBElement extends SVGElement {} +interface SVGFEFuncGElement extends SVGElement {} +interface SVGFEFuncRElement extends SVGElement {} +interface SVGFEGaussianBlurElement extends SVGElement {} +interface SVGFEImageElement extends SVGElement {} +interface SVGFEMergeElement extends SVGElement {} +interface SVGFEMergeNodeElement extends SVGElement {} +interface SVGFEMorphologyElement extends SVGElement {} +interface SVGFEOffsetElement extends SVGElement {} +interface SVGFEPointLightElement extends SVGElement {} +interface SVGFESpecularLightingElement extends SVGElement {} +interface SVGFESpotLightElement extends SVGElement {} +interface SVGFETileElement extends SVGElement {} +interface SVGFETurbulenceElement extends SVGElement {} +interface SVGFilterElement extends SVGElement {} +interface SVGForeignObjectElement extends SVGElement {} +interface SVGGElement extends SVGElement {} +interface SVGImageElement extends SVGElement {} +interface SVGLineElement extends SVGElement {} +interface SVGLinearGradientElement extends SVGElement {} +interface SVGMarkerElement extends SVGElement {} +interface SVGMaskElement extends SVGElement {} +interface SVGMetadataElement extends SVGElement {} +interface SVGPathElement extends SVGElement {} +interface SVGPatternElement extends SVGElement {} +interface SVGPolygonElement extends SVGElement {} +interface SVGPolylineElement extends SVGElement {} +interface SVGRadialGradientElement extends SVGElement {} +interface SVGRectElement extends SVGElement {} +interface SVGSetElement extends SVGElement {} +interface SVGStopElement extends SVGElement {} +interface SVGSwitchElement extends SVGElement {} +interface SVGSymbolElement extends SVGElement {} +interface SVGTextElement extends SVGElement {} +interface SVGTextPathElement extends SVGElement {} +interface SVGTSpanElement extends SVGElement {} +interface SVGUseElement extends SVGElement {} +interface SVGViewElement extends SVGElement {} + +interface FormData {} +interface Text {} +interface TouchList {} +interface WebGLRenderingContext {} +interface WebGL2RenderingContext {} + +interface TrustedHTML {} diff --git a/node_modules/@types/react/ts5.0/v18/index.d.ts b/node_modules/@types/react/ts5.0/v18/index.d.ts new file mode 100644 index 00000000..59cc15c7 --- /dev/null +++ b/node_modules/@types/react/ts5.0/v18/index.d.ts @@ -0,0 +1,4550 @@ +// NOTE: Users of the `experimental` builds of React should add a reference +// to 'react/experimental' in their project. See experimental.d.ts's top comment +// for reference and documentation on how exactly to do it. + +/// + +import * as CSS from "csstype"; +import * as PropTypes from "prop-types"; + +type NativeAnimationEvent = AnimationEvent; +type NativeClipboardEvent = ClipboardEvent; +type NativeCompositionEvent = CompositionEvent; +type NativeDragEvent = DragEvent; +type NativeFocusEvent = FocusEvent; +type NativeInputEvent = InputEvent; +type NativeKeyboardEvent = KeyboardEvent; +type NativeMouseEvent = MouseEvent; +type NativeTouchEvent = TouchEvent; +type NativePointerEvent = PointerEvent; +type NativeTransitionEvent = TransitionEvent; +type NativeUIEvent = UIEvent; +type NativeWheelEvent = WheelEvent; + +/** + * Used to represent DOM API's where users can either pass + * true or false as a boolean or as its equivalent strings. + */ +type Booleanish = boolean | "true" | "false"; + +/** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin MDN} + */ +type CrossOrigin = "anonymous" | "use-credentials" | "" | undefined; + +declare const UNDEFINED_VOID_ONLY: unique symbol; + +/** + * The function returned from an effect passed to {@link React.useEffect useEffect}, + * which can be used to clean up the effect when the component unmounts. + * + * @see {@link https://react.dev/reference/react/useEffect React Docs} + */ +type Destructor = () => void | { [UNDEFINED_VOID_ONLY]: never }; +type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never }; + +// eslint-disable-next-line @definitelytyped/export-just-namespace +export = React; +export as namespace React; + +declare namespace React { + // + // React Elements + // ---------------------------------------------------------------------- + + /** + * Used to retrieve the possible components which accept a given set of props. + * + * Can be passed no type parameters to get a union of all possible components + * and tags. + * + * Is a superset of {@link ComponentType}. + * + * @template P The props to match against. If not passed, defaults to any. + * @template Tag An optional tag to match against. If not passed, attempts to match against all possible tags. + * + * @example + * + * ```tsx + * // All components and tags (img, embed etc.) + * // which accept `src` + * type SrcComponents = ElementType<{ src: any }>; + * ``` + * + * @example + * + * ```tsx + * // All components + * type AllComponents = ElementType; + * ``` + * + * @example + * + * ```tsx + * // All custom components which match `src`, and tags which + * // match `src`, narrowed down to just `audio` and `embed` + * type SrcComponents = ElementType<{ src: any }, 'audio' | 'embed'>; + * ``` + */ + type ElementType

= + | { [K in Tag]: P extends JSX.IntrinsicElements[K] ? K : never }[Tag] + | ComponentType

; + + /** + * Represents any user-defined component, either as a function or a class. + * + * Similar to {@link JSXElementConstructor}, but with extra properties like + * {@link FunctionComponent.defaultProps defaultProps } and + * {@link ComponentClass.contextTypes contextTypes}. + * + * @template P The props the component accepts. + * + * @see {@link ComponentClass} + * @see {@link FunctionComponent} + */ + type ComponentType

= ComponentClass

| FunctionComponent

; + + /** + * Represents any user-defined component, either as a function or a class. + * + * Similar to {@link ComponentType}, but without extra properties like + * {@link FunctionComponent.defaultProps defaultProps } and + * {@link ComponentClass.contextTypes contextTypes}. + * + * @template P The props the component accepts. + */ + type JSXElementConstructor

= + | (( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-stateless-function-components React Docs} + */ + deprecatedLegacyContext?: any, + ) => ReactNode) + | (new( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs} + */ + deprecatedLegacyContext?: any, + ) => Component); + + /** + * A readonly ref container where {@link current} cannot be mutated. + * + * Created by {@link createRef}, or {@link useRef} when passed `null`. + * + * @template T The type of the ref's value. + * + * @example + * + * ```tsx + * const ref = createRef(); + * + * ref.current = document.createElement('div'); // Error + * ``` + */ + interface RefObject { + /** + * The current value of the ref. + */ + readonly current: T | null; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES { + } + /** + * A callback fired whenever the ref's value changes. + * + * @template T The type of the ref's value. + * + * @see {@link https://react.dev/reference/react-dom/components/common#ref-callback React Docs} + * + * @example + * + * ```tsx + *

console.log(node)} /> + * ``` + */ + type RefCallback = { + bivarianceHack( + instance: T | null, + ): + | void + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES + ]; + }["bivarianceHack"]; + + /** + * A union type of all possible shapes for React refs. + * + * @see {@link RefCallback} + * @see {@link RefObject} + */ + + type Ref = RefCallback | RefObject | null; + /** + * A legacy implementation of refs where you can pass a string to a ref prop. + * + * @see {@link https://react.dev/reference/react/Component#refs React Docs} + * + * @example + * + * ```tsx + *
+ * ``` + */ + // TODO: Remove the string ref special case from `PropsWithRef` once we remove LegacyRef + type LegacyRef = string | Ref; + + /** + * Retrieves the type of the 'ref' prop for a given component type or tag name. + * + * @template C The component type. + * + * @example + * + * ```tsx + * type MyComponentRef = React.ElementRef; + * ``` + * + * @example + * + * ```tsx + * type DivRef = React.ElementRef<'div'>; + * ``` + */ + type ElementRef< + C extends + | ForwardRefExoticComponent + | { new(props: any): Component } + | ((props: any, deprecatedLegacyContext?: any) => ReactNode) + | keyof JSX.IntrinsicElements, + > = + // need to check first if `ref` is a valid prop for ts@3.0 + // otherwise it will infer `{}` instead of `never` + "ref" extends keyof ComponentPropsWithRef + ? NonNullable["ref"]> extends RefAttributes< + infer Instance + >["ref"] ? Instance + : never + : never; + + type ComponentState = any; + + /** + * A value which uniquely identifies a node among items in an array. + * + * @see {@link https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key React Docs} + */ + type Key = string | number | bigint; + + /** + * @internal The props any component can receive. + * You don't have to add this type. All components automatically accept these props. + * ```tsx + * const Component = () =>
; + * + * ``` + * + * WARNING: The implementation of a component will never have access to these attributes. + * The following example would be incorrect usage because {@link Component} would never have access to `key`: + * ```tsx + * const Component = (props: React.Attributes) => props.key; + * ``` + */ + interface Attributes { + key?: Key | null | undefined; + } + /** + * The props any component accepting refs can receive. + * Class components, built-in browser components (e.g. `div`) and forwardRef components can receive refs and automatically accept these props. + * ```tsx + * const Component = forwardRef(() =>
); + * console.log(current)} /> + * ``` + * + * You only need this type if you manually author the types of props that need to be compatible with legacy refs. + * ```tsx + * interface Props extends React.RefAttributes {} + * declare const Component: React.FunctionComponent; + * ``` + * + * Otherwise it's simpler to directly use {@link Ref} since you can safely use the + * props type to describe to props that a consumer can pass to the component + * as well as describing the props the implementation of a component "sees". + * {@link RefAttributes} is generally not safe to describe both consumer and seen props. + * + * ```tsx + * interface Props extends { + * ref?: React.Ref | undefined; + * } + * declare const Component: React.FunctionComponent; + * ``` + * + * WARNING: The implementation of a component will not have access to the same type in versions of React supporting string refs. + * The following example would be incorrect usage because {@link Component} would never have access to a `ref` with type `string` + * ```tsx + * const Component = (props: React.RefAttributes) => props.ref; + * ``` + */ + interface RefAttributes extends Attributes { + /** + * Allows getting a ref to the component instance. + * Once the component unmounts, React will set `ref.current` to `null` + * (or call the ref with `null` if you passed a callback ref). + * + * @see {@link https://react.dev/learn/referencing-values-with-refs#refs-and-the-dom React Docs} + */ + ref?: LegacyRef | undefined; + } + + /** + * Represents the built-in attributes available to class components. + */ + interface ClassAttributes extends RefAttributes { + } + + /** + * Represents a JSX element. + * + * Where {@link ReactNode} represents everything that can be rendered, `ReactElement` + * only represents JSX. + * + * @template P The type of the props object + * @template T The type of the component or tag + * + * @example + * + * ```tsx + * const element: ReactElement =
; + * ``` + */ + interface ReactElement< + P = any, + T extends string | JSXElementConstructor = string | JSXElementConstructor, + > { + type: T; + props: P; + key: string | null; + } + + /** + * @deprecated + */ + interface ReactComponentElement< + T extends keyof JSX.IntrinsicElements | JSXElementConstructor, + P = Pick, Exclude, "key" | "ref">>, + > extends ReactElement> {} + + interface FunctionComponentElement

extends ReactElement> { + ref?: ("ref" extends keyof P ? P extends { ref?: infer R | undefined } ? R : never : never) | undefined; + } + + type CElement> = ComponentElement; + interface ComponentElement> extends ReactElement> { + ref?: LegacyRef | undefined; + } + + /** + * @deprecated Use {@link ComponentElement} instead. + */ + type ClassicElement

= CElement>; + + // string fallback for custom web-components + interface DOMElement

| SVGAttributes, T extends Element> + extends ReactElement + { + ref: LegacyRef; + } + + // ReactHTML for ReactHTMLElement + interface ReactHTMLElement extends DetailedReactHTMLElement, T> {} + + interface DetailedReactHTMLElement

, T extends HTMLElement> extends DOMElement { + type: keyof ReactHTML; + } + + // ReactSVG for ReactSVGElement + interface ReactSVGElement extends DOMElement, SVGElement> { + type: keyof ReactSVG; + } + + interface ReactPortal extends ReactElement { + children: ReactNode; + } + + // + // Factories + // ---------------------------------------------------------------------- + + type Factory

= (props?: Attributes & P, ...children: ReactNode[]) => ReactElement

; + + /** + * @deprecated Please use `FunctionComponentFactory` + */ + type SFCFactory

= FunctionComponentFactory

; + + type FunctionComponentFactory

= ( + props?: Attributes & P, + ...children: ReactNode[] + ) => FunctionComponentElement

; + + type ComponentFactory> = ( + props?: ClassAttributes & P, + ...children: ReactNode[] + ) => CElement; + + type CFactory> = ComponentFactory; + type ClassicFactory

= CFactory>; + + type DOMFactory

, T extends Element> = ( + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ) => DOMElement; + + interface HTMLFactory extends DetailedHTMLFactory, T> {} + + interface DetailedHTMLFactory

, T extends HTMLElement> extends DOMFactory { + (props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement; + } + + interface SVGFactory extends DOMFactory, SVGElement> { + ( + props?: ClassAttributes & SVGAttributes | null, + ...children: ReactNode[] + ): ReactSVGElement; + } + + /** + * @deprecated - This type is not relevant when using React. Inline the type instead to make the intent clear. + */ + type ReactText = string | number; + /** + * @deprecated - This type is not relevant when using React. Inline the type instead to make the intent clear. + */ + type ReactChild = ReactElement | string | number; + + /** + * @deprecated Use either `ReactNode[]` if you need an array or `Iterable` if its passed to a host component. + */ + interface ReactNodeArray extends ReadonlyArray {} + /** + * WARNING: Not related to `React.Fragment`. + * @deprecated This type is not relevant when using React. Inline the type instead to make the intent clear. + */ + type ReactFragment = Iterable; + + /** + * Different release channels declare additional types of ReactNode this particular release channel accepts. + * App or library types should never augment this interface. + */ + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES {} + + /** + * Represents all of the things React can render. + * + * Where {@link ReactElement} only represents JSX, `ReactNode` represents everything that can be rendered. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/reactnode/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Typing children + * type Props = { children: ReactNode } + * + * const Component = ({ children }: Props) =>

{children}
+ * + * hello + * ``` + * + * @example + * + * ```tsx + * // Typing a custom element + * type Props = { customElement: ReactNode } + * + * const Component = ({ customElement }: Props) =>
{customElement}
+ * + * hello
} /> + * ``` + */ + // non-thenables need to be kept in sync with AwaitedReactNode + type ReactNode = + | ReactElement + | string + | number + | Iterable + | ReactPortal + | boolean + | null + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES + ]; + + // + // Top Level API + // ---------------------------------------------------------------------- + + // DOM Elements + /** @deprecated */ + function createFactory( + type: keyof ReactHTML, + ): HTMLFactory; + /** @deprecated */ + function createFactory( + type: keyof ReactSVG, + ): SVGFactory; + /** @deprecated */ + function createFactory

, T extends Element>( + type: string, + ): DOMFactory; + + // Custom components + /** @deprecated */ + function createFactory

(type: FunctionComponent

): FunctionComponentFactory

; + /** @deprecated */ + function createFactory, C extends ComponentClass

>( + type: ClassType, + ): CFactory; + /** @deprecated */ + function createFactory

(type: ComponentClass

): Factory

; + + // DOM Elements + // TODO: generalize this to everything in `keyof ReactHTML`, not just "input" + function createElement( + type: "input", + props?: InputHTMLAttributes & ClassAttributes | null, + ...children: ReactNode[] + ): DetailedReactHTMLElement, HTMLInputElement>; + function createElement

, T extends HTMLElement>( + type: keyof ReactHTML, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): DetailedReactHTMLElement; + function createElement

, T extends SVGElement>( + type: keyof ReactSVG, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): ReactSVGElement; + function createElement

, T extends Element>( + type: string, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): DOMElement; + + // Custom components + + function createElement

( + type: FunctionComponent

, + props?: Attributes & P | null, + ...children: ReactNode[] + ): FunctionComponentElement

; + function createElement

, C extends ComponentClass

>( + type: ClassType, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): CElement; + function createElement

( + type: FunctionComponent

| ComponentClass

| string, + props?: Attributes & P | null, + ...children: ReactNode[] + ): ReactElement

; + + // DOM Elements + // ReactHTMLElement + function cloneElement

, T extends HTMLElement>( + element: DetailedReactHTMLElement, + props?: P, + ...children: ReactNode[] + ): DetailedReactHTMLElement; + // ReactHTMLElement, less specific + function cloneElement

, T extends HTMLElement>( + element: ReactHTMLElement, + props?: P, + ...children: ReactNode[] + ): ReactHTMLElement; + // SVGElement + function cloneElement

, T extends SVGElement>( + element: ReactSVGElement, + props?: P, + ...children: ReactNode[] + ): ReactSVGElement; + // DOM Element (has to be the last, because type checking stops at first overload that fits) + function cloneElement

, T extends Element>( + element: DOMElement, + props?: DOMAttributes & P, + ...children: ReactNode[] + ): DOMElement; + + // Custom components + function cloneElement

( + element: FunctionComponentElement

, + props?: Partial

& Attributes, + ...children: ReactNode[] + ): FunctionComponentElement

; + function cloneElement>( + element: CElement, + props?: Partial

& ClassAttributes, + ...children: ReactNode[] + ): CElement; + function cloneElement

( + element: ReactElement

, + props?: Partial

& Attributes, + ...children: ReactNode[] + ): ReactElement

; + + /** + * Describes the props accepted by a Context {@link Provider}. + * + * @template T The type of the value the context provides. + */ + interface ProviderProps { + value: T; + children?: ReactNode | undefined; + } + + /** + * Describes the props accepted by a Context {@link Consumer}. + * + * @template T The type of the value the context provides. + */ + interface ConsumerProps { + children: (value: T) => ReactNode; + } + + /** + * An object masquerading as a component. These are created by functions + * like {@link forwardRef}, {@link memo}, and {@link createContext}. + * + * In order to make TypeScript work, we pretend that they are normal + * components. + * + * But they are, in fact, not callable - instead, they are objects which + * are treated specially by the renderer. + * + * @template P The props the component accepts. + */ + interface ExoticComponent

{ + (props: P): ReactNode; + readonly $$typeof: symbol; + } + + /** + * An {@link ExoticComponent} with a `displayName` property applied to it. + * + * @template P The props the component accepts. + */ + interface NamedExoticComponent

extends ExoticComponent

{ + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * An {@link ExoticComponent} with a `propTypes` property applied to it. + * + * @template P The props the component accepts. + */ + interface ProviderExoticComponent

extends ExoticComponent

{ + propTypes?: WeakValidationMap

| undefined; + } + + /** + * Used to retrieve the type of a context object from a {@link Context}. + * + * @template C The context object. + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const MyContext = createContext({ foo: 'bar' }); + * + * type ContextType = ContextType; + * // ContextType = { foo: string } + * ``` + */ + type ContextType> = C extends Context ? T : never; + + /** + * Wraps your components to specify the value of this context for all components inside. + * + * @see {@link https://react.dev/reference/react/createContext#provider React Docs} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * + * function App() { + * return ( + * + * + * + * ); + * } + * ``` + */ + type Provider = ProviderExoticComponent>; + + /** + * The old way to read context, before {@link useContext} existed. + * + * @see {@link https://react.dev/reference/react/createContext#consumer React Docs} + * + * @example + * + * ```tsx + * import { UserContext } from './user-context'; + * + * function Avatar() { + * return ( + * + * {user => {user.name}} + * + * ); + * } + * ``` + */ + type Consumer = ExoticComponent>; + + /** + * Context lets components pass information deep down without explicitly + * passing props. + * + * Created from {@link createContext} + * + * @see {@link https://react.dev/learn/passing-data-deeply-with-context React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * ``` + */ + interface Context { + Provider: Provider; + Consumer: Consumer; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * Lets you create a {@link Context} that components can provide or read. + * + * @param defaultValue The value you want the context to have when there is no matching + * {@link Provider} in the tree above the component reading the context. This is meant + * as a "last resort" fallback. + * + * @see {@link https://react.dev/reference/react/createContext#reference React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * ``` + */ + function createContext( + // If you thought this should be optional, see + // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106 + defaultValue: T, + ): Context; + + function isValidElement

(object: {} | null | undefined): object is ReactElement

; + + /** + * Maintainer's note: Sync with {@link ReactChildren} until {@link ReactChildren} is removed. + */ + const Children: { + map( + children: C | readonly C[], + fn: (child: C, index: number) => T, + ): C extends null | undefined ? C : Array>; + forEach(children: C | readonly C[], fn: (child: C, index: number) => void): void; + count(children: any): number; + only(children: C): C extends any[] ? never : C; + toArray(children: ReactNode | ReactNode[]): Array>; + }; + /** + * Lets you group elements without a wrapper node. + * + * @see {@link https://react.dev/reference/react/Fragment React Docs} + * + * @example + * + * ```tsx + * import { Fragment } from 'react'; + * + * + * Hello + * World + * + * ``` + * + * @example + * + * ```tsx + * // Using the <> shorthand syntax: + * + * <> + * Hello + * World + * + * ``` + */ + const Fragment: ExoticComponent<{ children?: ReactNode | undefined }>; + + /** + * Lets you find common bugs in your components early during development. + * + * @see {@link https://react.dev/reference/react/StrictMode React Docs} + * + * @example + * + * ```tsx + * import { StrictMode } from 'react'; + * + * + * + * + * ``` + */ + const StrictMode: ExoticComponent<{ children?: ReactNode | undefined }>; + + /** + * The props accepted by {@link Suspense}. + * + * @see {@link https://react.dev/reference/react/Suspense React Docs} + */ + interface SuspenseProps { + children?: ReactNode | undefined; + + /** A fallback react tree to show when a Suspense child (like React.lazy) suspends */ + fallback?: ReactNode; + + /** + * A name for this Suspense boundary for instrumentation purposes. + * The name will help identify this boundary in React DevTools. + */ + name?: string | undefined; + } + + /** + * Lets you display a fallback until its children have finished loading. + * + * @see {@link https://react.dev/reference/react/Suspense React Docs} + * + * @example + * + * ```tsx + * import { Suspense } from 'react'; + * + * }> + * + * + * ``` + */ + const Suspense: ExoticComponent; + const version: string; + + /** + * The callback passed to {@link ProfilerProps.onRender}. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + type ProfilerOnRenderCallback = ( + /** + * The string id prop of the {@link Profiler} tree that has just committed. This lets + * you identify which part of the tree was committed if you are using multiple + * profilers. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + id: string, + /** + * This lets you know whether the tree has just been mounted for the first time + * or re-rendered due to a change in props, state, or hooks. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + phase: "mount" | "update" | "nested-update", + /** + * The number of milliseconds spent rendering the {@link Profiler} and its descendants + * for the current update. This indicates how well the subtree makes use of + * memoization (e.g. {@link memo} and {@link useMemo}). Ideally this value should decrease + * significantly after the initial mount as many of the descendants will only need to + * re-render if their specific props change. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + actualDuration: number, + /** + * The number of milliseconds estimating how much time it would take to re-render the entire + * {@link Profiler} subtree without any optimizations. It is calculated by summing up the most + * recent render durations of each component in the tree. This value estimates a worst-case + * cost of rendering (e.g. the initial mount or a tree with no memoization). Compare + * {@link actualDuration} against it to see if memoization is working. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + baseDuration: number, + /** + * A numeric timestamp for when React began rendering the current update. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + startTime: number, + /** + * A numeric timestamp for when React committed the current update. This value is shared + * between all profilers in a commit, enabling them to be grouped if desirable. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + commitTime: number, + ) => void; + + /** + * The props accepted by {@link Profiler}. + * + * @see {@link https://react.dev/reference/react/Profiler React Docs} + */ + interface ProfilerProps { + children?: ReactNode | undefined; + id: string; + onRender: ProfilerOnRenderCallback; + } + + /** + * Lets you measure rendering performance of a React tree programmatically. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + * + * @example + * + * ```tsx + * + * + * + * ``` + */ + const Profiler: ExoticComponent; + + // + // Component API + // ---------------------------------------------------------------------- + + type ReactInstance = Component | Element; + + // Base component for plain JS classes + interface Component

extends ComponentLifecycle {} + class Component { + /** + * If set, `this.context` will be set at runtime to the current value of the given Context. + * + * @example + * + * ```ts + * type MyContext = number + * const Ctx = React.createContext(0) + * + * class Foo extends React.Component { + * static contextType = Ctx + * context!: React.ContextType + * render () { + * return <>My context's value: {this.context}; + * } + * } + * ``` + * + * @see {@link https://react.dev/reference/react/Component#static-contexttype} + */ + static contextType?: Context | undefined; + + /** + * If using the new style context, re-declare this in your class to be the + * `React.ContextType` of your `static contextType`. + * Should be used with type annotation or static contextType. + * + * @example + * ```ts + * static contextType = MyContext + * // For TS pre-3.7: + * context!: React.ContextType + * // For TS 3.7 and above: + * declare context: React.ContextType + * ``` + * + * @see {@link https://react.dev/reference/react/Component#context React Docs} + */ + context: unknown; + + constructor(props: P); + /** + * @deprecated + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html React Docs} + */ + constructor(props: P, context: any); + + // We MUST keep setState() as a unified signature because it allows proper checking of the method return type. + // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257 + // Also, the ` | S` allows intellisense to not be dumbisense + setState( + state: ((prevState: Readonly, props: Readonly

) => Pick | S | null) | (Pick | S | null), + callback?: () => void, + ): void; + + forceUpdate(callback?: () => void): void; + render(): ReactNode; + + readonly props: Readonly

; + state: Readonly; + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs Legacy React Docs} + */ + refs: { + [key: string]: ReactInstance; + }; + } + + class PureComponent

extends Component {} + + /** + * @deprecated Use `ClassicComponent` from `create-react-class` + * + * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs} + * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm} + */ + interface ClassicComponent

extends Component { + replaceState(nextState: S, callback?: () => void): void; + isMounted(): boolean; + getInitialState?(): S; + } + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + /** + * Represents the type of a function component. Can optionally + * receive a type argument that represents the props the component + * receives. + * + * @template P The props the component accepts. + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet} + * @alias for {@link FunctionComponent} + * + * @example + * + * ```tsx + * // With props: + * type Props = { name: string } + * + * const MyComponent: FC = (props) => { + * return

{props.name}
+ * } + * ``` + * + * @example + * + * ```tsx + * // Without props: + * const MyComponentWithoutProps: FC = () => { + * return
MyComponentWithoutProps
+ * } + * ``` + */ + type FC

= FunctionComponent

; + + /** + * Represents the type of a function component. Can optionally + * receive a type argument that represents the props the component + * accepts. + * + * @template P The props the component accepts. + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // With props: + * type Props = { name: string } + * + * const MyComponent: FunctionComponent = (props) => { + * return

{props.name}
+ * } + * ``` + * + * @example + * + * ```tsx + * // Without props: + * const MyComponentWithoutProps: FunctionComponent = () => { + * return
MyComponentWithoutProps
+ * } + * ``` + */ + interface FunctionComponent

{ + ( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs} + */ + deprecatedLegacyContext?: any, + ): ReactNode; + /** + * Used to declare the types of the props accepted by the + * component. These types will be checked during rendering + * and in development only. + * + * We recommend using TypeScript instead of checking prop + * types at runtime. + * + * @see {@link https://react.dev/reference/react/Component#static-proptypes React Docs} + */ + propTypes?: WeakValidationMap

| undefined; + /** + * @deprecated + * + * Lets you specify which legacy context is consumed by + * this component. + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html Legacy React Docs} + */ + contextTypes?: ValidationMap | undefined; + /** + * Used to define default values for the props accepted by + * the component. + * + * @see {@link https://react.dev/reference/react/Component#static-defaultprops React Docs} + * + * @example + * + * ```tsx + * type Props = { name?: string } + * + * const MyComponent: FC = (props) => { + * return

{props.name}
+ * } + * + * MyComponent.defaultProps = { + * name: 'John Doe' + * } + * ``` + * + * @deprecated Use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value|default values for destructuring assignments instead}. + */ + defaultProps?: Partial

| undefined; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + * + * @example + * + * ```tsx + * + * const MyComponent: FC = () => { + * return

Hello!
+ * } + * + * MyComponent.displayName = 'MyAwesomeComponent' + * ``` + */ + displayName?: string | undefined; + } + + /** + * @deprecated - Equivalent to {@link React.FunctionComponent}. + * + * @see {@link React.FunctionComponent} + * @alias {@link VoidFunctionComponent} + */ + type VFC

= VoidFunctionComponent

; + + /** + * @deprecated - Equivalent to {@link React.FunctionComponent}. + * + * @see {@link React.FunctionComponent} + */ + interface VoidFunctionComponent

{ + ( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs} + */ + deprecatedLegacyContext?: any, + ): ReactNode; + propTypes?: WeakValidationMap

| undefined; + contextTypes?: ValidationMap | undefined; + /** + * @deprecated Use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value|default values for destructuring assignments instead}. + */ + defaultProps?: Partial

| undefined; + displayName?: string | undefined; + } + + /** + * The type of the ref received by a {@link ForwardRefRenderFunction}. + * + * @see {@link ForwardRefRenderFunction} + */ + type ForwardedRef = ((instance: T | null) => void) | MutableRefObject | null; + + /** + * The type of the function passed to {@link forwardRef}. This is considered different + * to a normal {@link FunctionComponent} because it receives an additional argument, + * + * @param props Props passed to the component, if any. + * @param ref A ref forwarded to the component of type {@link ForwardedRef}. + * + * @template T The type of the forwarded ref. + * @template P The type of the props the component accepts. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet} + * @see {@link forwardRef} + */ + interface ForwardRefRenderFunction { + (props: P, ref: ForwardedRef): ReactNode; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * Will show `ForwardRef(${Component.displayName || Component.name})` + * in devtools by default, but can be given its own specific name. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + /** + * defaultProps are not supported on render functions passed to forwardRef. + * + * @see {@link https://github.com/microsoft/TypeScript/issues/36826 linked GitHub issue} for context + * @see {@link https://react.dev/reference/react/Component#static-defaultprops React Docs} + */ + defaultProps?: never | undefined; + /** + * propTypes are not supported on render functions passed to forwardRef. + * + * @see {@link https://github.com/microsoft/TypeScript/issues/36826 linked GitHub issue} for context + * @see {@link https://react.dev/reference/react/Component#static-proptypes React Docs} + */ + propTypes?: never | undefined; + } + + /** + * Represents a component class in React. + * + * @template P The props the component accepts. + * @template S The internal state of the component. + */ + interface ComponentClass

extends StaticLifecycle { + new( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs} + */ + deprecatedLegacyContext?: any, + ): Component; + /** + * Used to declare the types of the props accepted by the + * component. These types will be checked during rendering + * and in development only. + * + * We recommend using TypeScript instead of checking prop + * types at runtime. + * + * @see {@link https://react.dev/reference/react/Component#static-proptypes React Docs} + */ + propTypes?: WeakValidationMap

| undefined; + contextType?: Context | undefined; + /** + * @deprecated use {@link ComponentClass.contextType} instead + * + * Lets you specify which legacy context is consumed by + * this component. + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html Legacy React Docs} + */ + contextTypes?: ValidationMap | undefined; + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#how-to-use-context Legacy React Docs} + */ + childContextTypes?: ValidationMap | undefined; + /** + * Used to define default values for the props accepted by + * the component. + * + * @see {@link https://react.dev/reference/react/Component#static-defaultprops React Docs} + */ + defaultProps?: Partial

| undefined; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * @deprecated Use `ClassicComponentClass` from `create-react-class` + * + * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs} + * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm} + */ + interface ClassicComponentClass

extends ComponentClass

{ + new(props: P, deprecatedLegacyContext?: any): ClassicComponent; + getDefaultProps?(): P; + } + + /** + * Used in {@link createElement} and {@link createFactory} to represent + * a class. + * + * An intersection type is used to infer multiple type parameters from + * a single argument, which is useful for many top-level API defs. + * See {@link https://github.com/Microsoft/TypeScript/issues/7234 this GitHub issue} + * for more info. + */ + type ClassType, C extends ComponentClass

> = + & C + & (new(props: P, deprecatedLegacyContext?: any) => T); + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + // This should actually be something like `Lifecycle | DeprecatedLifecycle`, + // as React will _not_ call the deprecated lifecycle methods if any of the new lifecycle + // methods are present. + interface ComponentLifecycle extends NewLifecycle, DeprecatedLifecycle { + /** + * Called immediately after a component is mounted. Setting state here will trigger re-rendering. + */ + componentDidMount?(): void; + /** + * Called to determine whether the change in props and state should trigger a re-render. + * + * `Component` always returns true. + * `PureComponent` implements a shallow comparison on props and state and returns true if any + * props or states have changed. + * + * If false is returned, {@link Component.render}, `componentWillUpdate` + * and `componentDidUpdate` will not be called. + */ + shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; + /** + * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as + * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`. + */ + componentWillUnmount?(): void; + /** + * Catches exceptions generated in descendant components. Unhandled exceptions will cause + * the entire component tree to unmount. + */ + componentDidCatch?(error: Error, errorInfo: ErrorInfo): void; + } + + // Unfortunately, we have no way of declaring that the component constructor must implement this + interface StaticLifecycle { + getDerivedStateFromProps?: GetDerivedStateFromProps | undefined; + getDerivedStateFromError?: GetDerivedStateFromError | undefined; + } + + type GetDerivedStateFromProps = + /** + * Returns an update to a component's state based on its new props and old state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (nextProps: Readonly

, prevState: S) => Partial | null; + + type GetDerivedStateFromError = + /** + * This lifecycle is invoked after an error has been thrown by a descendant component. + * It receives the error that was thrown as a parameter and should return a value to update state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (error: any) => Partial | null; + + // This should be "infer SS" but can't use it yet + interface NewLifecycle { + /** + * Runs before React applies the result of {@link Component.render render} to the document, and + * returns an object to be given to {@link componentDidUpdate}. Useful for saving + * things such as scroll position before {@link Component.render render} causes changes to it. + * + * Note: the presence of this method prevents any of the deprecated + * lifecycle events from running. + */ + getSnapshotBeforeUpdate?(prevProps: Readonly

, prevState: Readonly): SS | null; + /** + * Called immediately after updating occurs. Not called for the initial render. + * + * The snapshot is only present if {@link getSnapshotBeforeUpdate} is present and returns non-null. + */ + componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, snapshot?: SS): void; + } + + interface DeprecatedLifecycle { + /** + * Called immediately before mounting occurs, and before {@link Component.render}. + * Avoid introducing any side-effects or subscriptions in this method. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillMount?(): void; + /** + * Called immediately before mounting occurs, and before {@link Component.render}. + * Avoid introducing any side-effects or subscriptions in this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillMount?(): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling {@link Component.setState} generally does not trigger this method. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling {@link Component.setState} generally does not trigger this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call {@link Component.setState} here. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call {@link Component.setState} here. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + } + + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/blog/2016/07/13/mixins-considered-harmful.html Mixins Considered Harmful} + */ + interface Mixin extends ComponentLifecycle { + mixins?: Array> | undefined; + statics?: { + [key: string]: any; + } | undefined; + + displayName?: string | undefined; + propTypes?: ValidationMap | undefined; + contextTypes?: ValidationMap | undefined; + childContextTypes?: ValidationMap | undefined; + + getDefaultProps?(): P; + getInitialState?(): S; + } + + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/blog/2016/07/13/mixins-considered-harmful.html Mixins Considered Harmful} + */ + interface ComponentSpec extends Mixin { + render(): ReactNode; + + [propertyName: string]: any; + } + + function createRef(): RefObject; + + /** + * The type of the component returned from {@link forwardRef}. + * + * @template P The props the component accepts, if any. + * + * @see {@link ExoticComponent} + */ + interface ForwardRefExoticComponent

extends NamedExoticComponent

{ + /** + * @deprecated Use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value|default values for destructuring assignments instead}. + */ + defaultProps?: Partial

| undefined; + propTypes?: WeakValidationMap

| undefined; + } + + /** + * Lets your component expose a DOM node to a parent component + * using a ref. + * + * @see {@link https://react.dev/reference/react/forwardRef React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet} + * + * @param render See the {@link ForwardRefRenderFunction}. + * + * @template T The type of the DOM node. + * @template P The props the component accepts, if any. + * + * @example + * + * ```tsx + * interface Props { + * children?: ReactNode; + * type: "submit" | "button"; + * } + * + * export const FancyButton = forwardRef((props, ref) => ( + * + * )); + * ``` + */ + function forwardRef( + render: ForwardRefRenderFunction>, + ): ForwardRefExoticComponent & RefAttributes>; + + /** + * Omits the 'ref' attribute from the given props object. + * + * @template P The props object type. + */ + type PropsWithoutRef

= + // Omit would not be sufficient for this. We'd like to avoid unnecessary mapping and need a distributive conditional to support unions. + // see: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types + // https://github.com/Microsoft/TypeScript/issues/28339 + P extends any ? ("ref" extends keyof P ? Omit : P) : P; + /** Ensures that the props do not include string ref, which cannot be forwarded */ + type PropsWithRef

= + // Note: String refs can be forwarded. We can't fix this bug without breaking a bunch of libraries now though. + // Just "P extends { ref?: infer R }" looks sufficient, but R will infer as {} if P is {}. + "ref" extends keyof P + ? P extends { ref?: infer R | undefined } + ? string extends R ? PropsWithoutRef

& { ref?: Exclude | undefined } + : P + : P + : P; + + type PropsWithChildren

= P & { children?: ReactNode | undefined }; + + /** + * Used to retrieve the props a component accepts. Can either be passed a string, + * indicating a DOM element (e.g. 'div', 'span', etc.) or the type of a React + * component. + * + * It's usually better to use {@link ComponentPropsWithRef} or {@link ComponentPropsWithoutRef} + * instead of this type, as they let you be explicit about whether or not to include + * the `ref` prop. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentProps<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>

; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentProps = React.ComponentProps; + * ``` + */ + type ComponentProps> = T extends + JSXElementConstructor ? P + : T extends keyof JSX.IntrinsicElements ? JSX.IntrinsicElements[T] + : {}; + + /** + * Used to retrieve the props a component accepts with its ref. Can either be + * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the + * type of a React component. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentPropsWithRef<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>
; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithRef = React.ComponentPropsWithRef; + * ``` + */ + type ComponentPropsWithRef = T extends (new(props: infer P) => Component) + ? PropsWithoutRef

& RefAttributes> + : PropsWithRef>; + /** + * Used to retrieve the props a custom component accepts with its ref. + * + * Unlike {@link ComponentPropsWithRef}, this only works with custom + * components, i.e. components you define yourself. This is to improve + * type-checking performance. + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>

; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithRef = React.CustomComponentPropsWithRef; + * ``` + */ + type CustomComponentPropsWithRef = T extends (new(props: infer P) => Component) + ? (PropsWithoutRef

& RefAttributes>) + : T extends ((props: infer P, legacyContext?: any) => ReactNode) ? PropsWithRef

+ : never; + + /** + * Used to retrieve the props a component accepts without its ref. Can either be + * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the + * type of a React component. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentPropsWithoutRef<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>

; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithoutRef = React.ComponentPropsWithoutRef; + * ``` + */ + type ComponentPropsWithoutRef = PropsWithoutRef>; + + type ComponentRef = T extends NamedExoticComponent< + ComponentPropsWithoutRef & RefAttributes + > ? Method + : ComponentPropsWithRef extends RefAttributes ? Method + : never; + + // will show `Memo(${Component.displayName || Component.name})` in devtools by default, + // but can be given its own specific name + type MemoExoticComponent> = NamedExoticComponent> & { + readonly type: T; + }; + + /** + * Lets you skip re-rendering a component when its props are unchanged. + * + * @see {@link https://react.dev/reference/react/memo React Docs} + * + * @param Component The component to memoize. + * @param propsAreEqual A function that will be used to determine if the props have changed. + * + * @example + * + * ```tsx + * import { memo } from 'react'; + * + * const SomeComponent = memo(function SomeComponent(props: { foo: string }) { + * // ... + * }); + * ``` + */ + function memo

( + Component: FunctionComponent

, + propsAreEqual?: (prevProps: Readonly

, nextProps: Readonly

) => boolean, + ): NamedExoticComponent

; + function memo>( + Component: T, + propsAreEqual?: (prevProps: Readonly>, nextProps: Readonly>) => boolean, + ): MemoExoticComponent; + + interface LazyExoticComponent> + extends ExoticComponent> + { + readonly _result: T; + } + + /** + * Lets you defer loading a component’s code until it is rendered for the first time. + * + * @see {@link https://react.dev/reference/react/lazy React Docs} + * + * @param load A function that returns a `Promise` or another thenable (a `Promise`-like object with a + * then method). React will not call `load` until the first time you attempt to render the returned + * component. After React first calls load, it will wait for it to resolve, and then render the + * resolved value’s `.default` as a React component. Both the returned `Promise` and the `Promise`’s + * resolved value will be cached, so React will not call load more than once. If the `Promise` rejects, + * React will throw the rejection reason for the nearest Error Boundary to handle. + * + * @example + * + * ```tsx + * import { lazy } from 'react'; + * + * const MarkdownPreview = lazy(() => import('./MarkdownPreview.js')); + * ``` + */ + function lazy>( + load: () => Promise<{ default: T }>, + ): LazyExoticComponent; + + // + // React Hooks + // ---------------------------------------------------------------------- + + /** + * The instruction passed to a {@link Dispatch} function in {@link useState} + * to tell React what the next value of the {@link useState} should be. + * + * Often found wrapped in {@link Dispatch}. + * + * @template S The type of the state. + * + * @example + * + * ```tsx + * // This return type correctly represents the type of + * // `setCount` in the example below. + * const useCustomState = (): Dispatch> => { + * const [count, setCount] = useState(0); + * + * return setCount; + * } + * ``` + */ + type SetStateAction = S | ((prevState: S) => S); + + /** + * A function that can be used to update the state of a {@link useState} + * or {@link useReducer} hook. + */ + type Dispatch = (value: A) => void; + /** + * A {@link Dispatch} function can sometimes be called without any arguments. + */ + type DispatchWithoutAction = () => void; + // Unlike redux, the actions _can_ be anything + type Reducer = (prevState: S, action: A) => S; + // If useReducer accepts a reducer without action, dispatch may be called without any parameters. + type ReducerWithoutAction = (prevState: S) => S; + // types used to try and prevent the compiler from reducing S + // to a supertype common with the second argument to useReducer() + type ReducerState> = R extends Reducer ? S : never; + type ReducerAction> = R extends Reducer ? A : never; + // The identity check is done with the SameValue algorithm (Object.is), which is stricter than === + type ReducerStateWithoutAction> = R extends ReducerWithoutAction ? S + : never; + type DependencyList = readonly unknown[]; + + // NOTE: callbacks are _only_ allowed to return either void, or a destructor. + type EffectCallback = () => void | Destructor; + + interface MutableRefObject { + current: T; + } + + // This will technically work if you give a Consumer or Provider but it's deprecated and warns + /** + * Accepts a context object (the value returned from `React.createContext`) and returns the current + * context value, as given by the nearest context provider for the given context. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useContext} + */ + function useContext(context: Context /*, (not public API) observedBits?: number|boolean */): T; + /** + * Returns a stateful value, and a function to update it. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useState} + */ + function useState(initialState: S | (() => S)): [S, Dispatch>]; + // convenience overload when first argument is omitted + /** + * Returns a stateful value, and a function to update it. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useState} + */ + function useState(): [S | undefined, Dispatch>]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + // overload where dispatch could accept 0 arguments. + function useReducer, I>( + reducer: R, + initializerArg: I, + initializer: (arg: I) => ReducerStateWithoutAction, + ): [ReducerStateWithoutAction, DispatchWithoutAction]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + // overload where dispatch could accept 0 arguments. + function useReducer>( + reducer: R, + initializerArg: ReducerStateWithoutAction, + initializer?: undefined, + ): [ReducerStateWithoutAction, DispatchWithoutAction]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + // overload where "I" may be a subset of ReducerState; used to provide autocompletion. + // If "I" matches ReducerState exactly then the last overload will allow initializer to be omitted. + // the last overload effectively behaves as if the identity function (x => x) is the initializer. + function useReducer, I>( + reducer: R, + initializerArg: I & ReducerState, + initializer: (arg: I & ReducerState) => ReducerState, + ): [ReducerState, Dispatch>]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + // overload for free "I"; all goes as long as initializer converts it into "ReducerState". + function useReducer, I>( + reducer: R, + initializerArg: I, + initializer: (arg: I) => ReducerState, + ): [ReducerState, Dispatch>]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + + // I'm not sure if I keep this 2-ary or if I make it (2,3)-ary; it's currently (2,3)-ary. + // The Flow types do have an overload for 3-ary invocation with undefined initializer. + + // NOTE: without the ReducerState indirection, TypeScript would reduce S to be the most common + // supertype between the reducer's return type and the initialState (or the initializer's return type), + // which would prevent autocompletion from ever working. + + // TODO: double-check if this weird overload logic is necessary. It is possible it's either a bug + // in older versions, or a regression in newer versions of the typescript completion service. + function useReducer>( + reducer: R, + initialState: ReducerState, + initializer?: undefined, + ): [ReducerState, Dispatch>]; + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T): MutableRefObject; + // convenience overload for refs given as a ref prop as they typically start with a null value + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * Usage note: if you need the result of useRef to be directly mutable, include `| null` in the type + * of the generic argument. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T | null): RefObject; + // convenience overload for potentially undefined initialValue / call with 0 arguments + // has a default to stop it from defaulting to {} instead + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(): MutableRefObject; + /** + * The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations. + * Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside + * `useLayoutEffect` will be flushed synchronously, before the browser has a chance to paint. + * + * Prefer the standard `useEffect` when possible to avoid blocking visual updates. + * + * If you’re migrating code from a class component, `useLayoutEffect` fires in the same phase as + * `componentDidMount` and `componentDidUpdate`. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useLayoutEffect} + */ + function useLayoutEffect(effect: EffectCallback, deps?: DependencyList): void; + /** + * Accepts a function that contains imperative, possibly effectful code. + * + * @param effect Imperative function that can return a cleanup function + * @param deps If present, effect will only activate if the values in the list change. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useEffect} + */ + function useEffect(effect: EffectCallback, deps?: DependencyList): void; + // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref + /** + * `useImperativeHandle` customizes the instance value that is exposed to parent components when using + * `ref`. As always, imperative code using refs should be avoided in most cases. + * + * `useImperativeHandle` should be used with `React.forwardRef`. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useImperativeHandle} + */ + function useImperativeHandle(ref: Ref | undefined, init: () => R, deps?: DependencyList): void; + // I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key + // useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y. + /** + * `useCallback` will return a memoized version of the callback that only changes if one of the `inputs` + * has changed. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useCallback} + */ + // A specific function type would not trigger implicit any. + // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/52873#issuecomment-845806435 for a comparison between `Function` and more specific types. + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + function useCallback(callback: T, deps: DependencyList): T; + /** + * `useMemo` will only recompute the memoized value when one of the `deps` has changed. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useMemo} + */ + // allow undefined, but don't make it optional as that is very likely a mistake + function useMemo(factory: () => T, deps: DependencyList): T; + /** + * `useDebugValue` can be used to display a label for custom hooks in React DevTools. + * + * NOTE: We don’t recommend adding debug values to every custom hook. + * It’s most valuable for custom hooks that are part of shared libraries. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useDebugValue} + */ + // the name of the custom hook is itself derived from the function name at runtime: + // it's just the function name without the "use" prefix. + function useDebugValue(value: T, format?: (value: T) => any): void; + + // must be synchronous + export type TransitionFunction = () => VoidOrUndefinedOnly; + // strange definition to allow vscode to show documentation on the invocation + export interface TransitionStartFunction { + /** + * State updates caused inside the callback are allowed to be deferred. + * + * **If some state update causes a component to suspend, that state update should be wrapped in a transition.** + * + * @param callback A _synchronous_ function which causes state updates that can be deferred. + */ + (callback: TransitionFunction): void; + } + + /** + * Returns a deferred version of the value that may “lag behind” it. + * + * This is commonly used to keep the interface responsive when you have something that renders immediately + * based on user input and something that needs to wait for a data fetch. + * + * A good example of this is a text input. + * + * @param value The value that is going to be deferred + * + * @see {@link https://react.dev/reference/react/useDeferredValue} + */ + export function useDeferredValue(value: T): T; + + /** + * Allows components to avoid undesirable loading states by waiting for content to load + * before transitioning to the next screen. It also allows components to defer slower, + * data fetching updates until subsequent renders so that more crucial updates can be + * rendered immediately. + * + * The `useTransition` hook returns two values in an array. + * + * The first is a boolean, React’s way of informing us whether we’re waiting for the transition to finish. + * The second is a function that takes a callback. We can use it to tell React which state we want to defer. + * + * **If some state update causes a component to suspend, that state update should be wrapped in a transition.** + * + * @see {@link https://react.dev/reference/react/useTransition} + */ + export function useTransition(): [boolean, TransitionStartFunction]; + + /** + * Similar to `useTransition` but allows uses where hooks are not available. + * + * @param callback A _synchronous_ function which causes state updates that can be deferred. + */ + export function startTransition(scope: TransitionFunction): void; + + /** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ + // While act does always return Thenable, if a void function is passed, we pretend the return value is also void to not trigger dangling Promise lint rules. + export function act(callback: () => VoidOrUndefinedOnly): void; + export function act(callback: () => T | Promise): Promise; + + export function useId(): string; + + /** + * @param effect Imperative function that can return a cleanup function + * @param deps If present, effect will only activate if the values in the list change. + * + * @see {@link https://github.com/facebook/react/pull/21913} + */ + export function useInsertionEffect(effect: EffectCallback, deps?: DependencyList): void; + + /** + * @param subscribe + * @param getSnapshot + * + * @see {@link https://github.com/reactwg/react-18/discussions/86} + */ + // keep in sync with `useSyncExternalStore` from `use-sync-external-store` + export function useSyncExternalStore( + subscribe: (onStoreChange: () => void) => () => void, + getSnapshot: () => Snapshot, + getServerSnapshot?: () => Snapshot, + ): Snapshot; + + // + // Event System + // ---------------------------------------------------------------------- + // TODO: change any to unknown when moving to TS v3 + interface BaseSyntheticEvent { + nativeEvent: E; + currentTarget: C; + target: T; + bubbles: boolean; + cancelable: boolean; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + preventDefault(): void; + isDefaultPrevented(): boolean; + stopPropagation(): void; + isPropagationStopped(): boolean; + persist(): void; + timeStamp: number; + type: string; + } + + /** + * currentTarget - a reference to the element on which the event listener is registered. + * + * target - a reference to the element from which the event was originally dispatched. + * This might be a child element to the element on which the event listener is registered. + * If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11508#issuecomment-256045682 + */ + interface SyntheticEvent extends BaseSyntheticEvent {} + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + } + + interface CompositionEvent extends SyntheticEvent { + data: string; + } + + interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + } + + interface PointerEvent extends MouseEvent { + pointerId: number; + pressure: number; + tangentialPressure: number; + tiltX: number; + tiltY: number; + twist: number; + width: number; + height: number; + pointerType: "mouse" | "pen" | "touch"; + isPrimary: boolean; + } + + interface FocusEvent extends SyntheticEvent { + relatedTarget: (EventTarget & RelatedTarget) | null; + target: EventTarget & Target; + } + + interface FormEvent extends SyntheticEvent { + } + + interface InvalidEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface ChangeEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface InputEvent extends SyntheticEvent { + data: string; + } + + export type ModifierKey = + | "Alt" + | "AltGraph" + | "CapsLock" + | "Control" + | "Fn" + | "FnLock" + | "Hyper" + | "Meta" + | "NumLock" + | "ScrollLock" + | "Shift" + | "Super" + | "Symbol" + | "SymbolLock"; + + interface KeyboardEvent extends UIEvent { + altKey: boolean; + /** @deprecated */ + charCode: number; + ctrlKey: boolean; + code: string; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + /** + * See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values + */ + key: string; + /** @deprecated */ + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + repeat: boolean; + shiftKey: boolean; + /** @deprecated */ + which: number; + } + + interface MouseEvent extends UIEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + metaKey: boolean; + movementX: number; + movementY: number; + pageX: number; + pageY: number; + relatedTarget: EventTarget | null; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends UIEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + metaKey: boolean; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + view: AbstractView; + } + + interface WheelEvent extends MouseEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + } + + interface AnimationEvent extends SyntheticEvent { + animationName: string; + elapsedTime: number; + pseudoElement: string; + } + + interface TransitionEvent extends SyntheticEvent { + elapsedTime: number; + propertyName: string; + pseudoElement: string; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + type EventHandler> = { bivarianceHack(event: E): void }["bivarianceHack"]; + + type ReactEventHandler = EventHandler>; + + type ClipboardEventHandler = EventHandler>; + type CompositionEventHandler = EventHandler>; + type DragEventHandler = EventHandler>; + type FocusEventHandler = EventHandler>; + type FormEventHandler = EventHandler>; + type ChangeEventHandler = EventHandler>; + type InputEventHandler = EventHandler>; + type KeyboardEventHandler = EventHandler>; + type MouseEventHandler = EventHandler>; + type TouchEventHandler = EventHandler>; + type PointerEventHandler = EventHandler>; + type UIEventHandler = EventHandler>; + type WheelEventHandler = EventHandler>; + type AnimationEventHandler = EventHandler>; + type TransitionEventHandler = EventHandler>; + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + interface HTMLProps extends AllHTMLAttributes, ClassAttributes { + } + + type DetailedHTMLProps, T> = ClassAttributes & E; + + interface SVGProps extends SVGAttributes, ClassAttributes { + } + + interface SVGLineElementAttributes extends SVGProps {} + interface SVGTextElementAttributes extends SVGProps {} + + interface DOMAttributes { + children?: ReactNode | undefined; + dangerouslySetInnerHTML?: { + // Should be InnerHTML['innerHTML']. + // But unfortunately we're mixing renderer-specific type declarations. + __html: string | TrustedHTML; + } | undefined; + + // Clipboard Events + onCopy?: ClipboardEventHandler | undefined; + onCopyCapture?: ClipboardEventHandler | undefined; + onCut?: ClipboardEventHandler | undefined; + onCutCapture?: ClipboardEventHandler | undefined; + onPaste?: ClipboardEventHandler | undefined; + onPasteCapture?: ClipboardEventHandler | undefined; + + // Composition Events + onCompositionEnd?: CompositionEventHandler | undefined; + onCompositionEndCapture?: CompositionEventHandler | undefined; + onCompositionStart?: CompositionEventHandler | undefined; + onCompositionStartCapture?: CompositionEventHandler | undefined; + onCompositionUpdate?: CompositionEventHandler | undefined; + onCompositionUpdateCapture?: CompositionEventHandler | undefined; + + // Focus Events + onFocus?: FocusEventHandler | undefined; + onFocusCapture?: FocusEventHandler | undefined; + onBlur?: FocusEventHandler | undefined; + onBlurCapture?: FocusEventHandler | undefined; + + // Form Events + onChange?: FormEventHandler | undefined; + onChangeCapture?: FormEventHandler | undefined; + onBeforeInput?: InputEventHandler | undefined; + onBeforeInputCapture?: FormEventHandler | undefined; + onInput?: FormEventHandler | undefined; + onInputCapture?: FormEventHandler | undefined; + onReset?: FormEventHandler | undefined; + onResetCapture?: FormEventHandler | undefined; + onSubmit?: FormEventHandler | undefined; + onSubmitCapture?: FormEventHandler | undefined; + onInvalid?: FormEventHandler | undefined; + onInvalidCapture?: FormEventHandler | undefined; + + // Image Events + onLoad?: ReactEventHandler | undefined; + onLoadCapture?: ReactEventHandler | undefined; + onError?: ReactEventHandler | undefined; // also a Media Event + onErrorCapture?: ReactEventHandler | undefined; // also a Media Event + + // Keyboard Events + onKeyDown?: KeyboardEventHandler | undefined; + onKeyDownCapture?: KeyboardEventHandler | undefined; + /** @deprecated Use `onKeyUp` or `onKeyDown` instead */ + onKeyPress?: KeyboardEventHandler | undefined; + /** @deprecated Use `onKeyUpCapture` or `onKeyDownCapture` instead */ + onKeyPressCapture?: KeyboardEventHandler | undefined; + onKeyUp?: KeyboardEventHandler | undefined; + onKeyUpCapture?: KeyboardEventHandler | undefined; + + // Media Events + onAbort?: ReactEventHandler | undefined; + onAbortCapture?: ReactEventHandler | undefined; + onCanPlay?: ReactEventHandler | undefined; + onCanPlayCapture?: ReactEventHandler | undefined; + onCanPlayThrough?: ReactEventHandler | undefined; + onCanPlayThroughCapture?: ReactEventHandler | undefined; + onDurationChange?: ReactEventHandler | undefined; + onDurationChangeCapture?: ReactEventHandler | undefined; + onEmptied?: ReactEventHandler | undefined; + onEmptiedCapture?: ReactEventHandler | undefined; + onEncrypted?: ReactEventHandler | undefined; + onEncryptedCapture?: ReactEventHandler | undefined; + onEnded?: ReactEventHandler | undefined; + onEndedCapture?: ReactEventHandler | undefined; + onLoadedData?: ReactEventHandler | undefined; + onLoadedDataCapture?: ReactEventHandler | undefined; + onLoadedMetadata?: ReactEventHandler | undefined; + onLoadedMetadataCapture?: ReactEventHandler | undefined; + onLoadStart?: ReactEventHandler | undefined; + onLoadStartCapture?: ReactEventHandler | undefined; + onPause?: ReactEventHandler | undefined; + onPauseCapture?: ReactEventHandler | undefined; + onPlay?: ReactEventHandler | undefined; + onPlayCapture?: ReactEventHandler | undefined; + onPlaying?: ReactEventHandler | undefined; + onPlayingCapture?: ReactEventHandler | undefined; + onProgress?: ReactEventHandler | undefined; + onProgressCapture?: ReactEventHandler | undefined; + onRateChange?: ReactEventHandler | undefined; + onRateChangeCapture?: ReactEventHandler | undefined; + onSeeked?: ReactEventHandler | undefined; + onSeekedCapture?: ReactEventHandler | undefined; + onSeeking?: ReactEventHandler | undefined; + onSeekingCapture?: ReactEventHandler | undefined; + onStalled?: ReactEventHandler | undefined; + onStalledCapture?: ReactEventHandler | undefined; + onSuspend?: ReactEventHandler | undefined; + onSuspendCapture?: ReactEventHandler | undefined; + onTimeUpdate?: ReactEventHandler | undefined; + onTimeUpdateCapture?: ReactEventHandler | undefined; + onVolumeChange?: ReactEventHandler | undefined; + onVolumeChangeCapture?: ReactEventHandler | undefined; + onWaiting?: ReactEventHandler | undefined; + onWaitingCapture?: ReactEventHandler | undefined; + + // MouseEvents + onAuxClick?: MouseEventHandler | undefined; + onAuxClickCapture?: MouseEventHandler | undefined; + onClick?: MouseEventHandler | undefined; + onClickCapture?: MouseEventHandler | undefined; + onContextMenu?: MouseEventHandler | undefined; + onContextMenuCapture?: MouseEventHandler | undefined; + onDoubleClick?: MouseEventHandler | undefined; + onDoubleClickCapture?: MouseEventHandler | undefined; + onDrag?: DragEventHandler | undefined; + onDragCapture?: DragEventHandler | undefined; + onDragEnd?: DragEventHandler | undefined; + onDragEndCapture?: DragEventHandler | undefined; + onDragEnter?: DragEventHandler | undefined; + onDragEnterCapture?: DragEventHandler | undefined; + onDragExit?: DragEventHandler | undefined; + onDragExitCapture?: DragEventHandler | undefined; + onDragLeave?: DragEventHandler | undefined; + onDragLeaveCapture?: DragEventHandler | undefined; + onDragOver?: DragEventHandler | undefined; + onDragOverCapture?: DragEventHandler | undefined; + onDragStart?: DragEventHandler | undefined; + onDragStartCapture?: DragEventHandler | undefined; + onDrop?: DragEventHandler | undefined; + onDropCapture?: DragEventHandler | undefined; + onMouseDown?: MouseEventHandler | undefined; + onMouseDownCapture?: MouseEventHandler | undefined; + onMouseEnter?: MouseEventHandler | undefined; + onMouseLeave?: MouseEventHandler | undefined; + onMouseMove?: MouseEventHandler | undefined; + onMouseMoveCapture?: MouseEventHandler | undefined; + onMouseOut?: MouseEventHandler | undefined; + onMouseOutCapture?: MouseEventHandler | undefined; + onMouseOver?: MouseEventHandler | undefined; + onMouseOverCapture?: MouseEventHandler | undefined; + onMouseUp?: MouseEventHandler | undefined; + onMouseUpCapture?: MouseEventHandler | undefined; + + // Selection Events + onSelect?: ReactEventHandler | undefined; + onSelectCapture?: ReactEventHandler | undefined; + + // Touch Events + onTouchCancel?: TouchEventHandler | undefined; + onTouchCancelCapture?: TouchEventHandler | undefined; + onTouchEnd?: TouchEventHandler | undefined; + onTouchEndCapture?: TouchEventHandler | undefined; + onTouchMove?: TouchEventHandler | undefined; + onTouchMoveCapture?: TouchEventHandler | undefined; + onTouchStart?: TouchEventHandler | undefined; + onTouchStartCapture?: TouchEventHandler | undefined; + + // Pointer Events + onPointerDown?: PointerEventHandler | undefined; + onPointerDownCapture?: PointerEventHandler | undefined; + onPointerMove?: PointerEventHandler | undefined; + onPointerMoveCapture?: PointerEventHandler | undefined; + onPointerUp?: PointerEventHandler | undefined; + onPointerUpCapture?: PointerEventHandler | undefined; + onPointerCancel?: PointerEventHandler | undefined; + onPointerCancelCapture?: PointerEventHandler | undefined; + onPointerEnter?: PointerEventHandler | undefined; + onPointerLeave?: PointerEventHandler | undefined; + onPointerOver?: PointerEventHandler | undefined; + onPointerOverCapture?: PointerEventHandler | undefined; + onPointerOut?: PointerEventHandler | undefined; + onPointerOutCapture?: PointerEventHandler | undefined; + onGotPointerCapture?: PointerEventHandler | undefined; + onGotPointerCaptureCapture?: PointerEventHandler | undefined; + onLostPointerCapture?: PointerEventHandler | undefined; + onLostPointerCaptureCapture?: PointerEventHandler | undefined; + + // UI Events + onScroll?: UIEventHandler | undefined; + onScrollCapture?: UIEventHandler | undefined; + + // Wheel Events + onWheel?: WheelEventHandler | undefined; + onWheelCapture?: WheelEventHandler | undefined; + + // Animation Events + onAnimationStart?: AnimationEventHandler | undefined; + onAnimationStartCapture?: AnimationEventHandler | undefined; + onAnimationEnd?: AnimationEventHandler | undefined; + onAnimationEndCapture?: AnimationEventHandler | undefined; + onAnimationIteration?: AnimationEventHandler | undefined; + onAnimationIterationCapture?: AnimationEventHandler | undefined; + + // Transition Events + onTransitionEnd?: TransitionEventHandler | undefined; + onTransitionEndCapture?: TransitionEventHandler | undefined; + } + + export interface CSSProperties extends CSS.Properties { + /** + * The index signature was removed to enable closed typing for style + * using CSSType. You're able to use type assertion or module augmentation + * to add properties or an index signature of your own. + * + * For examples and more information, visit: + * https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors + */ + } + + // All the WAI-ARIA 1.1 attributes from https://www.w3.org/TR/wai-aria-1.1/ + interface AriaAttributes { + /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */ + "aria-activedescendant"?: string | undefined; + /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */ + "aria-atomic"?: Booleanish | undefined; + /** + * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be + * presented if they are made. + */ + "aria-autocomplete"?: "none" | "inline" | "list" | "both" | undefined; + /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */ + /** + * Defines a string value that labels the current element, which is intended to be converted into Braille. + * @see aria-label. + */ + "aria-braillelabel"?: string | undefined; + /** + * Defines a human-readable, author-localized abbreviated description for the role of an element, which is intended to be converted into Braille. + * @see aria-roledescription. + */ + "aria-brailleroledescription"?: string | undefined; + "aria-busy"?: Booleanish | undefined; + /** + * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. + * @see aria-pressed @see aria-selected. + */ + "aria-checked"?: boolean | "false" | "mixed" | "true" | undefined; + /** + * Defines the total number of columns in a table, grid, or treegrid. + * @see aria-colindex. + */ + "aria-colcount"?: number | undefined; + /** + * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. + * @see aria-colcount @see aria-colspan. + */ + "aria-colindex"?: number | undefined; + /** + * Defines a human readable text alternative of aria-colindex. + * @see aria-rowindextext. + */ + "aria-colindextext"?: string | undefined; + /** + * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-colindex @see aria-rowspan. + */ + "aria-colspan"?: number | undefined; + /** + * Identifies the element (or elements) whose contents or presence are controlled by the current element. + * @see aria-owns. + */ + "aria-controls"?: string | undefined; + /** Indicates the element that represents the current item within a container or set of related elements. */ + "aria-current"?: boolean | "false" | "true" | "page" | "step" | "location" | "date" | "time" | undefined; + /** + * Identifies the element (or elements) that describes the object. + * @see aria-labelledby + */ + "aria-describedby"?: string | undefined; + /** + * Defines a string value that describes or annotates the current element. + * @see related aria-describedby. + */ + "aria-description"?: string | undefined; + /** + * Identifies the element that provides a detailed, extended description for the object. + * @see aria-describedby. + */ + "aria-details"?: string | undefined; + /** + * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. + * @see aria-hidden @see aria-readonly. + */ + "aria-disabled"?: Booleanish | undefined; + /** + * Indicates what functions can be performed when a dragged object is released on the drop target. + * @deprecated in ARIA 1.1 + */ + "aria-dropeffect"?: "none" | "copy" | "execute" | "link" | "move" | "popup" | undefined; + /** + * Identifies the element that provides an error message for the object. + * @see aria-invalid @see aria-describedby. + */ + "aria-errormessage"?: string | undefined; + /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */ + "aria-expanded"?: Booleanish | undefined; + /** + * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, + * allows assistive technology to override the general default of reading in document source order. + */ + "aria-flowto"?: string | undefined; + /** + * Indicates an element's "grabbed" state in a drag-and-drop operation. + * @deprecated in ARIA 1.1 + */ + "aria-grabbed"?: Booleanish | undefined; + /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */ + "aria-haspopup"?: boolean | "false" | "true" | "menu" | "listbox" | "tree" | "grid" | "dialog" | undefined; + /** + * Indicates whether the element is exposed to an accessibility API. + * @see aria-disabled. + */ + "aria-hidden"?: Booleanish | undefined; + /** + * Indicates the entered value does not conform to the format expected by the application. + * @see aria-errormessage. + */ + "aria-invalid"?: boolean | "false" | "true" | "grammar" | "spelling" | undefined; + /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */ + "aria-keyshortcuts"?: string | undefined; + /** + * Defines a string value that labels the current element. + * @see aria-labelledby. + */ + "aria-label"?: string | undefined; + /** + * Identifies the element (or elements) that labels the current element. + * @see aria-describedby. + */ + "aria-labelledby"?: string | undefined; + /** Defines the hierarchical level of an element within a structure. */ + "aria-level"?: number | undefined; + /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */ + "aria-live"?: "off" | "assertive" | "polite" | undefined; + /** Indicates whether an element is modal when displayed. */ + "aria-modal"?: Booleanish | undefined; + /** Indicates whether a text box accepts multiple lines of input or only a single line. */ + "aria-multiline"?: Booleanish | undefined; + /** Indicates that the user may select more than one item from the current selectable descendants. */ + "aria-multiselectable"?: Booleanish | undefined; + /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ + "aria-orientation"?: "horizontal" | "vertical" | undefined; + /** + * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship + * between DOM elements where the DOM hierarchy cannot be used to represent the relationship. + * @see aria-controls. + */ + "aria-owns"?: string | undefined; + /** + * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. + * A hint could be a sample value or a brief description of the expected format. + */ + "aria-placeholder"?: string | undefined; + /** + * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-setsize. + */ + "aria-posinset"?: number | undefined; + /** + * Indicates the current "pressed" state of toggle buttons. + * @see aria-checked @see aria-selected. + */ + "aria-pressed"?: boolean | "false" | "mixed" | "true" | undefined; + /** + * Indicates that the element is not editable, but is otherwise operable. + * @see aria-disabled. + */ + "aria-readonly"?: Booleanish | undefined; + /** + * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. + * @see aria-atomic. + */ + "aria-relevant"?: + | "additions" + | "additions removals" + | "additions text" + | "all" + | "removals" + | "removals additions" + | "removals text" + | "text" + | "text additions" + | "text removals" + | undefined; + /** Indicates that user input is required on the element before a form may be submitted. */ + "aria-required"?: Booleanish | undefined; + /** Defines a human-readable, author-localized description for the role of an element. */ + "aria-roledescription"?: string | undefined; + /** + * Defines the total number of rows in a table, grid, or treegrid. + * @see aria-rowindex. + */ + "aria-rowcount"?: number | undefined; + /** + * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. + * @see aria-rowcount @see aria-rowspan. + */ + "aria-rowindex"?: number | undefined; + /** + * Defines a human readable text alternative of aria-rowindex. + * @see aria-colindextext. + */ + "aria-rowindextext"?: string | undefined; + /** + * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-rowindex @see aria-colspan. + */ + "aria-rowspan"?: number | undefined; + /** + * Indicates the current "selected" state of various widgets. + * @see aria-checked @see aria-pressed. + */ + "aria-selected"?: Booleanish | undefined; + /** + * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-posinset. + */ + "aria-setsize"?: number | undefined; + /** Indicates if items in a table or grid are sorted in ascending or descending order. */ + "aria-sort"?: "none" | "ascending" | "descending" | "other" | undefined; + /** Defines the maximum allowed value for a range widget. */ + "aria-valuemax"?: number | undefined; + /** Defines the minimum allowed value for a range widget. */ + "aria-valuemin"?: number | undefined; + /** + * Defines the current value for a range widget. + * @see aria-valuetext. + */ + "aria-valuenow"?: number | undefined; + /** Defines the human readable text alternative of aria-valuenow for a range widget. */ + "aria-valuetext"?: string | undefined; + } + + // All the WAI-ARIA 1.1 role attribute values from https://www.w3.org/TR/wai-aria-1.1/#role_definitions + type AriaRole = + | "alert" + | "alertdialog" + | "application" + | "article" + | "banner" + | "button" + | "cell" + | "checkbox" + | "columnheader" + | "combobox" + | "complementary" + | "contentinfo" + | "definition" + | "dialog" + | "directory" + | "document" + | "feed" + | "figure" + | "form" + | "grid" + | "gridcell" + | "group" + | "heading" + | "img" + | "link" + | "list" + | "listbox" + | "listitem" + | "log" + | "main" + | "marquee" + | "math" + | "menu" + | "menubar" + | "menuitem" + | "menuitemcheckbox" + | "menuitemradio" + | "navigation" + | "none" + | "note" + | "option" + | "presentation" + | "progressbar" + | "radio" + | "radiogroup" + | "region" + | "row" + | "rowgroup" + | "rowheader" + | "scrollbar" + | "search" + | "searchbox" + | "separator" + | "slider" + | "spinbutton" + | "status" + | "switch" + | "tab" + | "table" + | "tablist" + | "tabpanel" + | "term" + | "textbox" + | "timer" + | "toolbar" + | "tooltip" + | "tree" + | "treegrid" + | "treeitem" + | (string & {}); + + interface HTMLAttributes extends AriaAttributes, DOMAttributes { + // React-specific Attributes + defaultChecked?: boolean | undefined; + defaultValue?: string | number | readonly string[] | undefined; + suppressContentEditableWarning?: boolean | undefined; + suppressHydrationWarning?: boolean | undefined; + + // Standard HTML Attributes + accessKey?: string | undefined; + autoCapitalize?: "off" | "none" | "on" | "sentences" | "words" | "characters" | undefined | (string & {}); + autoFocus?: boolean | undefined; + className?: string | undefined; + contentEditable?: Booleanish | "inherit" | "plaintext-only" | undefined; + contextMenu?: string | undefined; + dir?: string | undefined; + draggable?: Booleanish | undefined; + enterKeyHint?: "enter" | "done" | "go" | "next" | "previous" | "search" | "send" | undefined; + hidden?: boolean | undefined; + id?: string | undefined; + lang?: string | undefined; + nonce?: string | undefined; + slot?: string | undefined; + spellCheck?: Booleanish | undefined; + style?: CSSProperties | undefined; + tabIndex?: number | undefined; + title?: string | undefined; + translate?: "yes" | "no" | undefined; + + // Unknown + radioGroup?: string | undefined; // , + + // WAI-ARIA + role?: AriaRole | undefined; + + // RDFa Attributes + about?: string | undefined; + content?: string | undefined; + datatype?: string | undefined; + inlist?: any; + prefix?: string | undefined; + property?: string | undefined; + rel?: string | undefined; + resource?: string | undefined; + rev?: string | undefined; + typeof?: string | undefined; + vocab?: string | undefined; + + // Non-standard Attributes + autoCorrect?: string | undefined; + autoSave?: string | undefined; + color?: string | undefined; + itemProp?: string | undefined; + itemScope?: boolean | undefined; + itemType?: string | undefined; + itemID?: string | undefined; + itemRef?: string | undefined; + results?: number | undefined; + security?: string | undefined; + unselectable?: "on" | "off" | undefined; + + // Living Standard + /** + * Hints at the type of data that might be entered by the user while editing the element or its contents + * @see {@link https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute} + */ + inputMode?: "none" | "text" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined; + /** + * Specify that a standard HTML element should behave like a defined custom built-in element + * @see {@link https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is} + */ + is?: string | undefined; + } + + /** + * For internal usage only. + * Different release channels declare additional types of ReactNode this particular release channel accepts. + * App or library types should never augment this interface. + */ + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS {} + + interface AllHTMLAttributes extends HTMLAttributes { + // Standard HTML Attributes + accept?: string | undefined; + acceptCharset?: string | undefined; + action?: + | string + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + allowFullScreen?: boolean | undefined; + allowTransparency?: boolean | undefined; + alt?: string | undefined; + as?: string | undefined; + async?: boolean | undefined; + autoComplete?: string | undefined; + autoPlay?: boolean | undefined; + capture?: boolean | "user" | "environment" | undefined; + cellPadding?: number | string | undefined; + cellSpacing?: number | string | undefined; + charSet?: string | undefined; + challenge?: string | undefined; + checked?: boolean | undefined; + cite?: string | undefined; + classID?: string | undefined; + cols?: number | undefined; + colSpan?: number | undefined; + controls?: boolean | undefined; + coords?: string | undefined; + crossOrigin?: CrossOrigin; + data?: string | undefined; + dateTime?: string | undefined; + default?: boolean | undefined; + defer?: boolean | undefined; + disabled?: boolean | undefined; + download?: any; + encType?: string | undefined; + form?: string | undefined; + formAction?: + | string + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + frameBorder?: number | string | undefined; + headers?: string | undefined; + height?: number | string | undefined; + high?: number | undefined; + href?: string | undefined; + hrefLang?: string | undefined; + htmlFor?: string | undefined; + httpEquiv?: string | undefined; + integrity?: string | undefined; + keyParams?: string | undefined; + keyType?: string | undefined; + kind?: string | undefined; + label?: string | undefined; + list?: string | undefined; + loop?: boolean | undefined; + low?: number | undefined; + manifest?: string | undefined; + marginHeight?: number | undefined; + marginWidth?: number | undefined; + max?: number | string | undefined; + maxLength?: number | undefined; + media?: string | undefined; + mediaGroup?: string | undefined; + method?: string | undefined; + min?: number | string | undefined; + minLength?: number | undefined; + multiple?: boolean | undefined; + muted?: boolean | undefined; + name?: string | undefined; + noValidate?: boolean | undefined; + open?: boolean | undefined; + optimum?: number | undefined; + pattern?: string | undefined; + placeholder?: string | undefined; + playsInline?: boolean | undefined; + poster?: string | undefined; + preload?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + reversed?: boolean | undefined; + rows?: number | undefined; + rowSpan?: number | undefined; + sandbox?: string | undefined; + scope?: string | undefined; + scoped?: boolean | undefined; + scrolling?: string | undefined; + seamless?: boolean | undefined; + selected?: boolean | undefined; + shape?: string | undefined; + size?: number | undefined; + sizes?: string | undefined; + span?: number | undefined; + src?: string | undefined; + srcDoc?: string | undefined; + srcLang?: string | undefined; + srcSet?: string | undefined; + start?: number | undefined; + step?: number | string | undefined; + summary?: string | undefined; + target?: string | undefined; + type?: string | undefined; + useMap?: string | undefined; + value?: string | readonly string[] | number | undefined; + width?: number | string | undefined; + wmode?: string | undefined; + wrap?: string | undefined; + } + + type HTMLAttributeReferrerPolicy = + | "" + | "no-referrer" + | "no-referrer-when-downgrade" + | "origin" + | "origin-when-cross-origin" + | "same-origin" + | "strict-origin" + | "strict-origin-when-cross-origin" + | "unsafe-url"; + + type HTMLAttributeAnchorTarget = + | "_self" + | "_blank" + | "_parent" + | "_top" + | (string & {}); + + interface AnchorHTMLAttributes extends HTMLAttributes { + download?: any; + href?: string | undefined; + hrefLang?: string | undefined; + media?: string | undefined; + ping?: string | undefined; + target?: HTMLAttributeAnchorTarget | undefined; + type?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + } + + interface AudioHTMLAttributes extends MediaHTMLAttributes {} + + interface AreaHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + coords?: string | undefined; + download?: any; + href?: string | undefined; + hrefLang?: string | undefined; + media?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + shape?: string | undefined; + target?: string | undefined; + } + + interface BaseHTMLAttributes extends HTMLAttributes { + href?: string | undefined; + target?: string | undefined; + } + + interface BlockquoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + + interface ButtonHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + formAction?: + | string + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ] + | undefined; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + name?: string | undefined; + type?: "submit" | "reset" | "button" | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface CanvasHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + width?: number | string | undefined; + } + + interface ColHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + width?: number | string | undefined; + } + + interface ColgroupHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + } + + interface DataHTMLAttributes extends HTMLAttributes { + value?: string | readonly string[] | number | undefined; + } + + interface DetailsHTMLAttributes extends HTMLAttributes { + open?: boolean | undefined; + onToggle?: ReactEventHandler | undefined; + name?: string | undefined; + } + + interface DelHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + dateTime?: string | undefined; + } + + interface DialogHTMLAttributes extends HTMLAttributes { + onCancel?: ReactEventHandler | undefined; + onClose?: ReactEventHandler | undefined; + open?: boolean | undefined; + } + + interface EmbedHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + src?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + } + + interface FieldsetHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + name?: string | undefined; + } + + interface FormHTMLAttributes extends HTMLAttributes { + acceptCharset?: string | undefined; + action?: + | string + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + autoComplete?: string | undefined; + encType?: string | undefined; + method?: string | undefined; + name?: string | undefined; + noValidate?: boolean | undefined; + target?: string | undefined; + } + + interface HtmlHTMLAttributes extends HTMLAttributes { + manifest?: string | undefined; + } + + interface IframeHTMLAttributes extends HTMLAttributes { + allow?: string | undefined; + allowFullScreen?: boolean | undefined; + allowTransparency?: boolean | undefined; + /** @deprecated */ + frameBorder?: number | string | undefined; + height?: number | string | undefined; + loading?: "eager" | "lazy" | undefined; + /** @deprecated */ + marginHeight?: number | undefined; + /** @deprecated */ + marginWidth?: number | undefined; + name?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sandbox?: string | undefined; + /** @deprecated */ + scrolling?: string | undefined; + seamless?: boolean | undefined; + src?: string | undefined; + srcDoc?: string | undefined; + width?: number | string | undefined; + } + + interface ImgHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + crossOrigin?: CrossOrigin; + decoding?: "async" | "auto" | "sync" | undefined; + fetchPriority?: "high" | "low" | "auto"; + height?: number | string | undefined; + loading?: "eager" | "lazy" | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + src?: string | undefined; + srcSet?: string | undefined; + useMap?: string | undefined; + width?: number | string | undefined; + } + + interface InsHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + dateTime?: string | undefined; + } + + type HTMLInputTypeAttribute = + | "button" + | "checkbox" + | "color" + | "date" + | "datetime-local" + | "email" + | "file" + | "hidden" + | "image" + | "month" + | "number" + | "password" + | "radio" + | "range" + | "reset" + | "search" + | "submit" + | "tel" + | "text" + | "time" + | "url" + | "week" + | (string & {}); + + type AutoFillAddressKind = "billing" | "shipping"; + type AutoFillBase = "" | "off" | "on"; + type AutoFillContactField = + | "email" + | "tel" + | "tel-area-code" + | "tel-country-code" + | "tel-extension" + | "tel-local" + | "tel-local-prefix" + | "tel-local-suffix" + | "tel-national"; + type AutoFillContactKind = "home" | "mobile" | "work"; + type AutoFillCredentialField = "webauthn"; + type AutoFillNormalField = + | "additional-name" + | "address-level1" + | "address-level2" + | "address-level3" + | "address-level4" + | "address-line1" + | "address-line2" + | "address-line3" + | "bday-day" + | "bday-month" + | "bday-year" + | "cc-csc" + | "cc-exp" + | "cc-exp-month" + | "cc-exp-year" + | "cc-family-name" + | "cc-given-name" + | "cc-name" + | "cc-number" + | "cc-type" + | "country" + | "country-name" + | "current-password" + | "family-name" + | "given-name" + | "honorific-prefix" + | "honorific-suffix" + | "name" + | "new-password" + | "one-time-code" + | "organization" + | "postal-code" + | "street-address" + | "transaction-amount" + | "transaction-currency" + | "username"; + type OptionalPrefixToken = `${T} ` | ""; + type OptionalPostfixToken = ` ${T}` | ""; + type AutoFillField = AutoFillNormalField | `${OptionalPrefixToken}${AutoFillContactField}`; + type AutoFillSection = `section-${string}`; + type AutoFill = + | AutoFillBase + | `${OptionalPrefixToken}${OptionalPrefixToken< + AutoFillAddressKind + >}${AutoFillField}${OptionalPostfixToken}`; + type HTMLInputAutoCompleteAttribute = AutoFill | (string & {}); + + interface InputHTMLAttributes extends HTMLAttributes { + accept?: string | undefined; + alt?: string | undefined; + autoComplete?: HTMLInputAutoCompleteAttribute | undefined; + capture?: boolean | "user" | "environment" | undefined; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute + checked?: boolean | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + formAction?: + | string + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ] + | undefined; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + height?: number | string | undefined; + list?: string | undefined; + max?: number | string | undefined; + maxLength?: number | undefined; + min?: number | string | undefined; + minLength?: number | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + pattern?: string | undefined; + placeholder?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + size?: number | undefined; + src?: string | undefined; + step?: number | string | undefined; + type?: HTMLInputTypeAttribute | undefined; + value?: string | readonly string[] | number | undefined; + width?: number | string | undefined; + + onChange?: ChangeEventHandler | undefined; + } + + interface KeygenHTMLAttributes extends HTMLAttributes { + challenge?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + keyType?: string | undefined; + keyParams?: string | undefined; + name?: string | undefined; + } + + interface LabelHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + htmlFor?: string | undefined; + } + + interface LiHTMLAttributes extends HTMLAttributes { + value?: string | readonly string[] | number | undefined; + } + + interface LinkHTMLAttributes extends HTMLAttributes { + as?: string | undefined; + crossOrigin?: CrossOrigin; + fetchPriority?: "high" | "low" | "auto"; + href?: string | undefined; + hrefLang?: string | undefined; + integrity?: string | undefined; + media?: string | undefined; + imageSrcSet?: string | undefined; + imageSizes?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + type?: string | undefined; + charSet?: string | undefined; + } + + interface MapHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + + interface MenuHTMLAttributes extends HTMLAttributes { + type?: string | undefined; + } + + interface MediaHTMLAttributes extends HTMLAttributes { + autoPlay?: boolean | undefined; + controls?: boolean | undefined; + controlsList?: string | undefined; + crossOrigin?: CrossOrigin; + loop?: boolean | undefined; + mediaGroup?: string | undefined; + muted?: boolean | undefined; + playsInline?: boolean | undefined; + preload?: string | undefined; + src?: string | undefined; + } + + interface MetaHTMLAttributes extends HTMLAttributes { + charSet?: string | undefined; + content?: string | undefined; + httpEquiv?: string | undefined; + media?: string | undefined; + name?: string | undefined; + } + + interface MeterHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + high?: number | undefined; + low?: number | undefined; + max?: number | string | undefined; + min?: number | string | undefined; + optimum?: number | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface QuoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + + interface ObjectHTMLAttributes extends HTMLAttributes { + classID?: string | undefined; + data?: string | undefined; + form?: string | undefined; + height?: number | string | undefined; + name?: string | undefined; + type?: string | undefined; + useMap?: string | undefined; + width?: number | string | undefined; + wmode?: string | undefined; + } + + interface OlHTMLAttributes extends HTMLAttributes { + reversed?: boolean | undefined; + start?: number | undefined; + type?: "1" | "a" | "A" | "i" | "I" | undefined; + } + + interface OptgroupHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + } + + interface OptionHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + selected?: boolean | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface OutputHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + htmlFor?: string | undefined; + name?: string | undefined; + } + + interface ParamHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface ProgressHTMLAttributes extends HTMLAttributes { + max?: number | string | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface SlotHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + + interface ScriptHTMLAttributes extends HTMLAttributes { + async?: boolean | undefined; + /** @deprecated */ + charSet?: string | undefined; + crossOrigin?: CrossOrigin; + defer?: boolean | undefined; + integrity?: string | undefined; + noModule?: boolean | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + src?: string | undefined; + type?: string | undefined; + } + + interface SelectHTMLAttributes extends HTMLAttributes { + autoComplete?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + required?: boolean | undefined; + size?: number | undefined; + value?: string | readonly string[] | number | undefined; + onChange?: ChangeEventHandler | undefined; + } + + interface SourceHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + media?: string | undefined; + sizes?: string | undefined; + src?: string | undefined; + srcSet?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + } + + interface StyleHTMLAttributes extends HTMLAttributes { + media?: string | undefined; + scoped?: boolean | undefined; + type?: string | undefined; + } + + interface TableHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | undefined; + bgcolor?: string | undefined; + border?: number | undefined; + cellPadding?: number | string | undefined; + cellSpacing?: number | string | undefined; + frame?: boolean | undefined; + rules?: "none" | "groups" | "rows" | "columns" | "all" | undefined; + summary?: string | undefined; + width?: number | string | undefined; + } + + interface TextareaHTMLAttributes extends HTMLAttributes { + autoComplete?: string | undefined; + cols?: number | undefined; + dirName?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + maxLength?: number | undefined; + minLength?: number | undefined; + name?: string | undefined; + placeholder?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + rows?: number | undefined; + value?: string | readonly string[] | number | undefined; + wrap?: string | undefined; + + onChange?: ChangeEventHandler | undefined; + } + + interface TdHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | "justify" | "char" | undefined; + colSpan?: number | undefined; + headers?: string | undefined; + rowSpan?: number | undefined; + scope?: string | undefined; + abbr?: string | undefined; + height?: number | string | undefined; + width?: number | string | undefined; + valign?: "top" | "middle" | "bottom" | "baseline" | undefined; + } + + interface ThHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | "justify" | "char" | undefined; + colSpan?: number | undefined; + headers?: string | undefined; + rowSpan?: number | undefined; + scope?: string | undefined; + abbr?: string | undefined; + } + + interface TimeHTMLAttributes extends HTMLAttributes { + dateTime?: string | undefined; + } + + interface TrackHTMLAttributes extends HTMLAttributes { + default?: boolean | undefined; + kind?: string | undefined; + label?: string | undefined; + src?: string | undefined; + srcLang?: string | undefined; + } + + interface VideoHTMLAttributes extends MediaHTMLAttributes { + height?: number | string | undefined; + playsInline?: boolean | undefined; + poster?: string | undefined; + width?: number | string | undefined; + disablePictureInPicture?: boolean | undefined; + disableRemotePlayback?: boolean | undefined; + + onResize?: ReactEventHandler | undefined; + onResizeCapture?: ReactEventHandler | undefined; + } + + // this list is "complete" in that it contains every SVG attribute + // that React supports, but the types can be improved. + // Full list here: https://facebook.github.io/react/docs/dom-elements.html + // + // The three broad type categories are (in order of restrictiveness): + // - "number | string" + // - "string" + // - union of string literals + interface SVGAttributes extends AriaAttributes, DOMAttributes { + // React-specific Attributes + suppressHydrationWarning?: boolean | undefined; + + // Attributes which also defined in HTMLAttributes + // See comment in SVGDOMPropertyConfig.js + className?: string | undefined; + color?: string | undefined; + height?: number | string | undefined; + id?: string | undefined; + lang?: string | undefined; + max?: number | string | undefined; + media?: string | undefined; + method?: string | undefined; + min?: number | string | undefined; + name?: string | undefined; + style?: CSSProperties | undefined; + target?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + + // Other HTML properties supported by SVG elements in browsers + role?: AriaRole | undefined; + tabIndex?: number | undefined; + crossOrigin?: CrossOrigin; + + // SVG Specific attributes + accentHeight?: number | string | undefined; + accumulate?: "none" | "sum" | undefined; + additive?: "replace" | "sum" | undefined; + alignmentBaseline?: + | "auto" + | "baseline" + | "before-edge" + | "text-before-edge" + | "middle" + | "central" + | "after-edge" + | "text-after-edge" + | "ideographic" + | "alphabetic" + | "hanging" + | "mathematical" + | "inherit" + | undefined; + allowReorder?: "no" | "yes" | undefined; + alphabetic?: number | string | undefined; + amplitude?: number | string | undefined; + arabicForm?: "initial" | "medial" | "terminal" | "isolated" | undefined; + ascent?: number | string | undefined; + attributeName?: string | undefined; + attributeType?: string | undefined; + autoReverse?: Booleanish | undefined; + azimuth?: number | string | undefined; + baseFrequency?: number | string | undefined; + baselineShift?: number | string | undefined; + baseProfile?: number | string | undefined; + bbox?: number | string | undefined; + begin?: number | string | undefined; + bias?: number | string | undefined; + by?: number | string | undefined; + calcMode?: number | string | undefined; + capHeight?: number | string | undefined; + clip?: number | string | undefined; + clipPath?: string | undefined; + clipPathUnits?: number | string | undefined; + clipRule?: number | string | undefined; + colorInterpolation?: number | string | undefined; + colorInterpolationFilters?: "auto" | "sRGB" | "linearRGB" | "inherit" | undefined; + colorProfile?: number | string | undefined; + colorRendering?: number | string | undefined; + contentScriptType?: number | string | undefined; + contentStyleType?: number | string | undefined; + cursor?: number | string | undefined; + cx?: number | string | undefined; + cy?: number | string | undefined; + d?: string | undefined; + decelerate?: number | string | undefined; + descent?: number | string | undefined; + diffuseConstant?: number | string | undefined; + direction?: number | string | undefined; + display?: number | string | undefined; + divisor?: number | string | undefined; + dominantBaseline?: number | string | undefined; + dur?: number | string | undefined; + dx?: number | string | undefined; + dy?: number | string | undefined; + edgeMode?: number | string | undefined; + elevation?: number | string | undefined; + enableBackground?: number | string | undefined; + end?: number | string | undefined; + exponent?: number | string | undefined; + externalResourcesRequired?: Booleanish | undefined; + fill?: string | undefined; + fillOpacity?: number | string | undefined; + fillRule?: "nonzero" | "evenodd" | "inherit" | undefined; + filter?: string | undefined; + filterRes?: number | string | undefined; + filterUnits?: number | string | undefined; + floodColor?: number | string | undefined; + floodOpacity?: number | string | undefined; + focusable?: Booleanish | "auto" | undefined; + fontFamily?: string | undefined; + fontSize?: number | string | undefined; + fontSizeAdjust?: number | string | undefined; + fontStretch?: number | string | undefined; + fontStyle?: number | string | undefined; + fontVariant?: number | string | undefined; + fontWeight?: number | string | undefined; + format?: number | string | undefined; + fr?: number | string | undefined; + from?: number | string | undefined; + fx?: number | string | undefined; + fy?: number | string | undefined; + g1?: number | string | undefined; + g2?: number | string | undefined; + glyphName?: number | string | undefined; + glyphOrientationHorizontal?: number | string | undefined; + glyphOrientationVertical?: number | string | undefined; + glyphRef?: number | string | undefined; + gradientTransform?: string | undefined; + gradientUnits?: string | undefined; + hanging?: number | string | undefined; + horizAdvX?: number | string | undefined; + horizOriginX?: number | string | undefined; + href?: string | undefined; + ideographic?: number | string | undefined; + imageRendering?: number | string | undefined; + in2?: number | string | undefined; + in?: string | undefined; + intercept?: number | string | undefined; + k1?: number | string | undefined; + k2?: number | string | undefined; + k3?: number | string | undefined; + k4?: number | string | undefined; + k?: number | string | undefined; + kernelMatrix?: number | string | undefined; + kernelUnitLength?: number | string | undefined; + kerning?: number | string | undefined; + keyPoints?: number | string | undefined; + keySplines?: number | string | undefined; + keyTimes?: number | string | undefined; + lengthAdjust?: number | string | undefined; + letterSpacing?: number | string | undefined; + lightingColor?: number | string | undefined; + limitingConeAngle?: number | string | undefined; + local?: number | string | undefined; + markerEnd?: string | undefined; + markerHeight?: number | string | undefined; + markerMid?: string | undefined; + markerStart?: string | undefined; + markerUnits?: number | string | undefined; + markerWidth?: number | string | undefined; + mask?: string | undefined; + maskContentUnits?: number | string | undefined; + maskUnits?: number | string | undefined; + mathematical?: number | string | undefined; + mode?: number | string | undefined; + numOctaves?: number | string | undefined; + offset?: number | string | undefined; + opacity?: number | string | undefined; + operator?: number | string | undefined; + order?: number | string | undefined; + orient?: number | string | undefined; + orientation?: number | string | undefined; + origin?: number | string | undefined; + overflow?: number | string | undefined; + overlinePosition?: number | string | undefined; + overlineThickness?: number | string | undefined; + paintOrder?: number | string | undefined; + panose1?: number | string | undefined; + path?: string | undefined; + pathLength?: number | string | undefined; + patternContentUnits?: string | undefined; + patternTransform?: number | string | undefined; + patternUnits?: string | undefined; + pointerEvents?: number | string | undefined; + points?: string | undefined; + pointsAtX?: number | string | undefined; + pointsAtY?: number | string | undefined; + pointsAtZ?: number | string | undefined; + preserveAlpha?: Booleanish | undefined; + preserveAspectRatio?: string | undefined; + primitiveUnits?: number | string | undefined; + r?: number | string | undefined; + radius?: number | string | undefined; + refX?: number | string | undefined; + refY?: number | string | undefined; + renderingIntent?: number | string | undefined; + repeatCount?: number | string | undefined; + repeatDur?: number | string | undefined; + requiredExtensions?: number | string | undefined; + requiredFeatures?: number | string | undefined; + restart?: number | string | undefined; + result?: string | undefined; + rotate?: number | string | undefined; + rx?: number | string | undefined; + ry?: number | string | undefined; + scale?: number | string | undefined; + seed?: number | string | undefined; + shapeRendering?: number | string | undefined; + slope?: number | string | undefined; + spacing?: number | string | undefined; + specularConstant?: number | string | undefined; + specularExponent?: number | string | undefined; + speed?: number | string | undefined; + spreadMethod?: string | undefined; + startOffset?: number | string | undefined; + stdDeviation?: number | string | undefined; + stemh?: number | string | undefined; + stemv?: number | string | undefined; + stitchTiles?: number | string | undefined; + stopColor?: string | undefined; + stopOpacity?: number | string | undefined; + strikethroughPosition?: number | string | undefined; + strikethroughThickness?: number | string | undefined; + string?: number | string | undefined; + stroke?: string | undefined; + strokeDasharray?: string | number | undefined; + strokeDashoffset?: string | number | undefined; + strokeLinecap?: "butt" | "round" | "square" | "inherit" | undefined; + strokeLinejoin?: "miter" | "round" | "bevel" | "inherit" | undefined; + strokeMiterlimit?: number | string | undefined; + strokeOpacity?: number | string | undefined; + strokeWidth?: number | string | undefined; + surfaceScale?: number | string | undefined; + systemLanguage?: number | string | undefined; + tableValues?: number | string | undefined; + targetX?: number | string | undefined; + targetY?: number | string | undefined; + textAnchor?: string | undefined; + textDecoration?: number | string | undefined; + textLength?: number | string | undefined; + textRendering?: number | string | undefined; + to?: number | string | undefined; + transform?: string | undefined; + u1?: number | string | undefined; + u2?: number | string | undefined; + underlinePosition?: number | string | undefined; + underlineThickness?: number | string | undefined; + unicode?: number | string | undefined; + unicodeBidi?: number | string | undefined; + unicodeRange?: number | string | undefined; + unitsPerEm?: number | string | undefined; + vAlphabetic?: number | string | undefined; + values?: string | undefined; + vectorEffect?: number | string | undefined; + version?: string | undefined; + vertAdvY?: number | string | undefined; + vertOriginX?: number | string | undefined; + vertOriginY?: number | string | undefined; + vHanging?: number | string | undefined; + vIdeographic?: number | string | undefined; + viewBox?: string | undefined; + viewTarget?: number | string | undefined; + visibility?: number | string | undefined; + vMathematical?: number | string | undefined; + widths?: number | string | undefined; + wordSpacing?: number | string | undefined; + writingMode?: number | string | undefined; + x1?: number | string | undefined; + x2?: number | string | undefined; + x?: number | string | undefined; + xChannelSelector?: string | undefined; + xHeight?: number | string | undefined; + xlinkActuate?: string | undefined; + xlinkArcrole?: string | undefined; + xlinkHref?: string | undefined; + xlinkRole?: string | undefined; + xlinkShow?: string | undefined; + xlinkTitle?: string | undefined; + xlinkType?: string | undefined; + xmlBase?: string | undefined; + xmlLang?: string | undefined; + xmlns?: string | undefined; + xmlnsXlink?: string | undefined; + xmlSpace?: string | undefined; + y1?: number | string | undefined; + y2?: number | string | undefined; + y?: number | string | undefined; + yChannelSelector?: string | undefined; + z?: number | string | undefined; + zoomAndPan?: string | undefined; + } + + interface WebViewHTMLAttributes extends HTMLAttributes { + allowFullScreen?: boolean | undefined; + allowpopups?: boolean | undefined; + autosize?: boolean | undefined; + blinkfeatures?: string | undefined; + disableblinkfeatures?: string | undefined; + disableguestresize?: boolean | undefined; + disablewebsecurity?: boolean | undefined; + guestinstance?: string | undefined; + httpreferrer?: string | undefined; + nodeintegration?: boolean | undefined; + partition?: string | undefined; + plugins?: boolean | undefined; + preload?: string | undefined; + src?: string | undefined; + useragent?: string | undefined; + webpreferences?: string | undefined; + } + + // + // React.DOM + // ---------------------------------------------------------------------- + + interface ReactHTML { + a: DetailedHTMLFactory, HTMLAnchorElement>; + abbr: DetailedHTMLFactory, HTMLElement>; + address: DetailedHTMLFactory, HTMLElement>; + area: DetailedHTMLFactory, HTMLAreaElement>; + article: DetailedHTMLFactory, HTMLElement>; + aside: DetailedHTMLFactory, HTMLElement>; + audio: DetailedHTMLFactory, HTMLAudioElement>; + b: DetailedHTMLFactory, HTMLElement>; + base: DetailedHTMLFactory, HTMLBaseElement>; + bdi: DetailedHTMLFactory, HTMLElement>; + bdo: DetailedHTMLFactory, HTMLElement>; + big: DetailedHTMLFactory, HTMLElement>; + blockquote: DetailedHTMLFactory, HTMLQuoteElement>; + body: DetailedHTMLFactory, HTMLBodyElement>; + br: DetailedHTMLFactory, HTMLBRElement>; + button: DetailedHTMLFactory, HTMLButtonElement>; + canvas: DetailedHTMLFactory, HTMLCanvasElement>; + caption: DetailedHTMLFactory, HTMLElement>; + center: DetailedHTMLFactory, HTMLElement>; + cite: DetailedHTMLFactory, HTMLElement>; + code: DetailedHTMLFactory, HTMLElement>; + col: DetailedHTMLFactory, HTMLTableColElement>; + colgroup: DetailedHTMLFactory, HTMLTableColElement>; + data: DetailedHTMLFactory, HTMLDataElement>; + datalist: DetailedHTMLFactory, HTMLDataListElement>; + dd: DetailedHTMLFactory, HTMLElement>; + del: DetailedHTMLFactory, HTMLModElement>; + details: DetailedHTMLFactory, HTMLDetailsElement>; + dfn: DetailedHTMLFactory, HTMLElement>; + dialog: DetailedHTMLFactory, HTMLDialogElement>; + div: DetailedHTMLFactory, HTMLDivElement>; + dl: DetailedHTMLFactory, HTMLDListElement>; + dt: DetailedHTMLFactory, HTMLElement>; + em: DetailedHTMLFactory, HTMLElement>; + embed: DetailedHTMLFactory, HTMLEmbedElement>; + fieldset: DetailedHTMLFactory, HTMLFieldSetElement>; + figcaption: DetailedHTMLFactory, HTMLElement>; + figure: DetailedHTMLFactory, HTMLElement>; + footer: DetailedHTMLFactory, HTMLElement>; + form: DetailedHTMLFactory, HTMLFormElement>; + h1: DetailedHTMLFactory, HTMLHeadingElement>; + h2: DetailedHTMLFactory, HTMLHeadingElement>; + h3: DetailedHTMLFactory, HTMLHeadingElement>; + h4: DetailedHTMLFactory, HTMLHeadingElement>; + h5: DetailedHTMLFactory, HTMLHeadingElement>; + h6: DetailedHTMLFactory, HTMLHeadingElement>; + head: DetailedHTMLFactory, HTMLHeadElement>; + header: DetailedHTMLFactory, HTMLElement>; + hgroup: DetailedHTMLFactory, HTMLElement>; + hr: DetailedHTMLFactory, HTMLHRElement>; + html: DetailedHTMLFactory, HTMLHtmlElement>; + i: DetailedHTMLFactory, HTMLElement>; + iframe: DetailedHTMLFactory, HTMLIFrameElement>; + img: DetailedHTMLFactory, HTMLImageElement>; + input: DetailedHTMLFactory, HTMLInputElement>; + ins: DetailedHTMLFactory, HTMLModElement>; + kbd: DetailedHTMLFactory, HTMLElement>; + keygen: DetailedHTMLFactory, HTMLElement>; + label: DetailedHTMLFactory, HTMLLabelElement>; + legend: DetailedHTMLFactory, HTMLLegendElement>; + li: DetailedHTMLFactory, HTMLLIElement>; + link: DetailedHTMLFactory, HTMLLinkElement>; + main: DetailedHTMLFactory, HTMLElement>; + map: DetailedHTMLFactory, HTMLMapElement>; + mark: DetailedHTMLFactory, HTMLElement>; + menu: DetailedHTMLFactory, HTMLElement>; + menuitem: DetailedHTMLFactory, HTMLElement>; + meta: DetailedHTMLFactory, HTMLMetaElement>; + meter: DetailedHTMLFactory, HTMLMeterElement>; + nav: DetailedHTMLFactory, HTMLElement>; + noscript: DetailedHTMLFactory, HTMLElement>; + object: DetailedHTMLFactory, HTMLObjectElement>; + ol: DetailedHTMLFactory, HTMLOListElement>; + optgroup: DetailedHTMLFactory, HTMLOptGroupElement>; + option: DetailedHTMLFactory, HTMLOptionElement>; + output: DetailedHTMLFactory, HTMLOutputElement>; + p: DetailedHTMLFactory, HTMLParagraphElement>; + param: DetailedHTMLFactory, HTMLParamElement>; + picture: DetailedHTMLFactory, HTMLElement>; + pre: DetailedHTMLFactory, HTMLPreElement>; + progress: DetailedHTMLFactory, HTMLProgressElement>; + q: DetailedHTMLFactory, HTMLQuoteElement>; + rp: DetailedHTMLFactory, HTMLElement>; + rt: DetailedHTMLFactory, HTMLElement>; + ruby: DetailedHTMLFactory, HTMLElement>; + s: DetailedHTMLFactory, HTMLElement>; + samp: DetailedHTMLFactory, HTMLElement>; + search: DetailedHTMLFactory, HTMLElement>; + slot: DetailedHTMLFactory, HTMLSlotElement>; + script: DetailedHTMLFactory, HTMLScriptElement>; + section: DetailedHTMLFactory, HTMLElement>; + select: DetailedHTMLFactory, HTMLSelectElement>; + small: DetailedHTMLFactory, HTMLElement>; + source: DetailedHTMLFactory, HTMLSourceElement>; + span: DetailedHTMLFactory, HTMLSpanElement>; + strong: DetailedHTMLFactory, HTMLElement>; + style: DetailedHTMLFactory, HTMLStyleElement>; + sub: DetailedHTMLFactory, HTMLElement>; + summary: DetailedHTMLFactory, HTMLElement>; + sup: DetailedHTMLFactory, HTMLElement>; + table: DetailedHTMLFactory, HTMLTableElement>; + template: DetailedHTMLFactory, HTMLTemplateElement>; + tbody: DetailedHTMLFactory, HTMLTableSectionElement>; + td: DetailedHTMLFactory, HTMLTableDataCellElement>; + textarea: DetailedHTMLFactory, HTMLTextAreaElement>; + tfoot: DetailedHTMLFactory, HTMLTableSectionElement>; + th: DetailedHTMLFactory, HTMLTableHeaderCellElement>; + thead: DetailedHTMLFactory, HTMLTableSectionElement>; + time: DetailedHTMLFactory, HTMLTimeElement>; + title: DetailedHTMLFactory, HTMLTitleElement>; + tr: DetailedHTMLFactory, HTMLTableRowElement>; + track: DetailedHTMLFactory, HTMLTrackElement>; + u: DetailedHTMLFactory, HTMLElement>; + ul: DetailedHTMLFactory, HTMLUListElement>; + "var": DetailedHTMLFactory, HTMLElement>; + video: DetailedHTMLFactory, HTMLVideoElement>; + wbr: DetailedHTMLFactory, HTMLElement>; + webview: DetailedHTMLFactory, HTMLWebViewElement>; + } + + interface ReactSVG { + animate: SVGFactory; + circle: SVGFactory; + clipPath: SVGFactory; + defs: SVGFactory; + desc: SVGFactory; + ellipse: SVGFactory; + feBlend: SVGFactory; + feColorMatrix: SVGFactory; + feComponentTransfer: SVGFactory; + feComposite: SVGFactory; + feConvolveMatrix: SVGFactory; + feDiffuseLighting: SVGFactory; + feDisplacementMap: SVGFactory; + feDistantLight: SVGFactory; + feDropShadow: SVGFactory; + feFlood: SVGFactory; + feFuncA: SVGFactory; + feFuncB: SVGFactory; + feFuncG: SVGFactory; + feFuncR: SVGFactory; + feGaussianBlur: SVGFactory; + feImage: SVGFactory; + feMerge: SVGFactory; + feMergeNode: SVGFactory; + feMorphology: SVGFactory; + feOffset: SVGFactory; + fePointLight: SVGFactory; + feSpecularLighting: SVGFactory; + feSpotLight: SVGFactory; + feTile: SVGFactory; + feTurbulence: SVGFactory; + filter: SVGFactory; + foreignObject: SVGFactory; + g: SVGFactory; + image: SVGFactory; + line: SVGFactory; + linearGradient: SVGFactory; + marker: SVGFactory; + mask: SVGFactory; + metadata: SVGFactory; + path: SVGFactory; + pattern: SVGFactory; + polygon: SVGFactory; + polyline: SVGFactory; + radialGradient: SVGFactory; + rect: SVGFactory; + stop: SVGFactory; + svg: SVGFactory; + switch: SVGFactory; + symbol: SVGFactory; + text: SVGFactory; + textPath: SVGFactory; + tspan: SVGFactory; + use: SVGFactory; + view: SVGFactory; + } + + interface ReactDOM extends ReactHTML, ReactSVG {} + + // + // React.PropTypes + // ---------------------------------------------------------------------- + + /** + * @deprecated Use `Validator` from the ´prop-types` instead. + */ + type Validator = PropTypes.Validator; + + /** + * @deprecated Use `Requireable` from the ´prop-types` instead. + */ + type Requireable = PropTypes.Requireable; + + /** + * @deprecated Use `ValidationMap` from the ´prop-types` instead. + */ + type ValidationMap = PropTypes.ValidationMap; + + /** + * @deprecated Use `WeakValidationMap` from the ´prop-types` instead. + */ + type WeakValidationMap = { + [K in keyof T]?: null extends T[K] ? Validator + : undefined extends T[K] ? Validator + : Validator; + }; + + /** + * @deprecated Use `PropTypes.*` where `PropTypes` comes from `import * as PropTypes from 'prop-types'` instead. + */ + interface ReactPropTypes { + any: typeof PropTypes.any; + array: typeof PropTypes.array; + bool: typeof PropTypes.bool; + func: typeof PropTypes.func; + number: typeof PropTypes.number; + object: typeof PropTypes.object; + string: typeof PropTypes.string; + node: typeof PropTypes.node; + element: typeof PropTypes.element; + instanceOf: typeof PropTypes.instanceOf; + oneOf: typeof PropTypes.oneOf; + oneOfType: typeof PropTypes.oneOfType; + arrayOf: typeof PropTypes.arrayOf; + objectOf: typeof PropTypes.objectOf; + shape: typeof PropTypes.shape; + exact: typeof PropTypes.exact; + } + + // + // React.Children + // ---------------------------------------------------------------------- + + /** + * @deprecated - Use `typeof React.Children` instead. + */ + // Sync with type of `const Children`. + interface ReactChildren { + map( + children: C | readonly C[], + fn: (child: C, index: number) => T, + ): C extends null | undefined ? C : Array>; + forEach(children: C | readonly C[], fn: (child: C, index: number) => void): void; + count(children: any): number; + only(children: C): C extends any[] ? never : C; + toArray(children: ReactNode | ReactNode[]): Array>; + } + + // + // Browser Interfaces + // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts + // ---------------------------------------------------------------------- + + interface AbstractView { + styleMedia: StyleMedia; + document: Document; + } + + interface Touch { + identifier: number; + target: EventTarget; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + pageX: number; + pageY: number; + } + + interface TouchList { + [index: number]: Touch; + length: number; + item(index: number): Touch; + identifiedTouch(identifier: number): Touch; + } + + // + // Error Interfaces + // ---------------------------------------------------------------------- + interface ErrorInfo { + /** + * Captures which component contained the exception, and its ancestors. + */ + componentStack?: string | null; + digest?: string | null; + } + + // Keep in sync with JSX namespace in ./jsx-runtime.d.ts and ./jsx-dev-runtime.d.ts + namespace JSX { + type ElementType = GlobalJSXElementType; + interface Element extends GlobalJSXElement {} + interface ElementClass extends GlobalJSXElementClass {} + interface ElementAttributesProperty extends GlobalJSXElementAttributesProperty {} + interface ElementChildrenAttribute extends GlobalJSXElementChildrenAttribute {} + + type LibraryManagedAttributes = GlobalJSXLibraryManagedAttributes; + + interface IntrinsicAttributes extends GlobalJSXIntrinsicAttributes {} + interface IntrinsicClassAttributes extends GlobalJSXIntrinsicClassAttributes {} + interface IntrinsicElements extends GlobalJSXIntrinsicElements {} + } +} + +// naked 'any' type in a conditional type will short circuit and union both the then/else branches +// so boolean is only resolved for T = any +type IsExactlyAny = boolean extends (T extends never ? true : false) ? true : false; + +type ExactlyAnyPropertyKeys = { [K in keyof T]: IsExactlyAny extends true ? K : never }[keyof T]; +type NotExactlyAnyPropertyKeys = Exclude>; + +// Try to resolve ill-defined props like for JS users: props can be any, or sometimes objects with properties of type any +type MergePropTypes = + // Distribute over P in case it is a union type + P extends any + // If props is type any, use propTypes definitions + ? IsExactlyAny

extends true ? T + // If declared props have indexed properties, ignore inferred props entirely as keyof gets widened + : string extends keyof P ? P + // Prefer declared types which are not exactly any + : + & Pick> + // For props which are exactly any, use the type inferred from propTypes if present + & Pick>> + // Keep leftover props not specified in propTypes + & Pick> + : never; + +type InexactPartial = { [K in keyof T]?: T[K] | undefined }; + +// Any prop that has a default prop becomes optional, but its type is unchanged +// Undeclared default props are augmented into the resulting allowable attributes +// If declared props have indexed properties, ignore default props entirely as keyof gets widened +// Wrap in an outer-level conditional type to allow distribution over props that are unions +type Defaultize = P extends any ? string extends keyof P ? P + : + & Pick> + & InexactPartial>> + & InexactPartial>> + : never; + +type ReactManagedAttributes = C extends { propTypes: infer T; defaultProps: infer D } + ? Defaultize>, D> + : C extends { propTypes: infer T } ? MergePropTypes> + : C extends { defaultProps: infer D } ? Defaultize + : P; + +declare global { + /** + * @deprecated Use `React.JSX` instead of the global `JSX` namespace. + */ + namespace JSX { + // We don't just alias React.ElementType because React.ElementType + // historically does more than we need it to. + // E.g. it also contains .propTypes and so TS also verifies the declared + // props type does match the declared .propTypes. + // But if libraries declared their .propTypes but not props type, + // or they mismatch, you won't be able to use the class component + // as a JSX.ElementType. + // We could fix this everywhere but we're ultimately not interested in + // .propTypes assignability so we might as well drop it entirely here to + // reduce the work of the type-checker. + // TODO: Check impact of making React.ElementType

= React.JSXElementConstructor

+ type ElementType = string | React.JSXElementConstructor; + interface Element extends React.ReactElement {} + interface ElementClass extends React.Component { + render(): React.ReactNode; + } + interface ElementAttributesProperty { + props: {}; + } + interface ElementChildrenAttribute { + children: {}; + } + + // We can't recurse forever because `type` can't be self-referential; + // let's assume it's reasonable to do a single React.lazy() around a single React.memo() / vice-versa + type LibraryManagedAttributes = C extends + React.MemoExoticComponent | React.LazyExoticComponent + ? T extends React.MemoExoticComponent | React.LazyExoticComponent + ? ReactManagedAttributes + : ReactManagedAttributes + : ReactManagedAttributes; + + interface IntrinsicAttributes extends React.Attributes {} + interface IntrinsicClassAttributes extends React.ClassAttributes {} + + interface IntrinsicElements { + // HTML + a: React.DetailedHTMLProps, HTMLAnchorElement>; + abbr: React.DetailedHTMLProps, HTMLElement>; + address: React.DetailedHTMLProps, HTMLElement>; + area: React.DetailedHTMLProps, HTMLAreaElement>; + article: React.DetailedHTMLProps, HTMLElement>; + aside: React.DetailedHTMLProps, HTMLElement>; + audio: React.DetailedHTMLProps, HTMLAudioElement>; + b: React.DetailedHTMLProps, HTMLElement>; + base: React.DetailedHTMLProps, HTMLBaseElement>; + bdi: React.DetailedHTMLProps, HTMLElement>; + bdo: React.DetailedHTMLProps, HTMLElement>; + big: React.DetailedHTMLProps, HTMLElement>; + blockquote: React.DetailedHTMLProps, HTMLQuoteElement>; + body: React.DetailedHTMLProps, HTMLBodyElement>; + br: React.DetailedHTMLProps, HTMLBRElement>; + button: React.DetailedHTMLProps, HTMLButtonElement>; + canvas: React.DetailedHTMLProps, HTMLCanvasElement>; + caption: React.DetailedHTMLProps, HTMLElement>; + center: React.DetailedHTMLProps, HTMLElement>; + cite: React.DetailedHTMLProps, HTMLElement>; + code: React.DetailedHTMLProps, HTMLElement>; + col: React.DetailedHTMLProps, HTMLTableColElement>; + colgroup: React.DetailedHTMLProps, HTMLTableColElement>; + data: React.DetailedHTMLProps, HTMLDataElement>; + datalist: React.DetailedHTMLProps, HTMLDataListElement>; + dd: React.DetailedHTMLProps, HTMLElement>; + del: React.DetailedHTMLProps, HTMLModElement>; + details: React.DetailedHTMLProps, HTMLDetailsElement>; + dfn: React.DetailedHTMLProps, HTMLElement>; + dialog: React.DetailedHTMLProps, HTMLDialogElement>; + div: React.DetailedHTMLProps, HTMLDivElement>; + dl: React.DetailedHTMLProps, HTMLDListElement>; + dt: React.DetailedHTMLProps, HTMLElement>; + em: React.DetailedHTMLProps, HTMLElement>; + embed: React.DetailedHTMLProps, HTMLEmbedElement>; + fieldset: React.DetailedHTMLProps, HTMLFieldSetElement>; + figcaption: React.DetailedHTMLProps, HTMLElement>; + figure: React.DetailedHTMLProps, HTMLElement>; + footer: React.DetailedHTMLProps, HTMLElement>; + form: React.DetailedHTMLProps, HTMLFormElement>; + h1: React.DetailedHTMLProps, HTMLHeadingElement>; + h2: React.DetailedHTMLProps, HTMLHeadingElement>; + h3: React.DetailedHTMLProps, HTMLHeadingElement>; + h4: React.DetailedHTMLProps, HTMLHeadingElement>; + h5: React.DetailedHTMLProps, HTMLHeadingElement>; + h6: React.DetailedHTMLProps, HTMLHeadingElement>; + head: React.DetailedHTMLProps, HTMLHeadElement>; + header: React.DetailedHTMLProps, HTMLElement>; + hgroup: React.DetailedHTMLProps, HTMLElement>; + hr: React.DetailedHTMLProps, HTMLHRElement>; + html: React.DetailedHTMLProps, HTMLHtmlElement>; + i: React.DetailedHTMLProps, HTMLElement>; + iframe: React.DetailedHTMLProps, HTMLIFrameElement>; + img: React.DetailedHTMLProps, HTMLImageElement>; + input: React.DetailedHTMLProps, HTMLInputElement>; + ins: React.DetailedHTMLProps, HTMLModElement>; + kbd: React.DetailedHTMLProps, HTMLElement>; + keygen: React.DetailedHTMLProps, HTMLElement>; + label: React.DetailedHTMLProps, HTMLLabelElement>; + legend: React.DetailedHTMLProps, HTMLLegendElement>; + li: React.DetailedHTMLProps, HTMLLIElement>; + link: React.DetailedHTMLProps, HTMLLinkElement>; + main: React.DetailedHTMLProps, HTMLElement>; + map: React.DetailedHTMLProps, HTMLMapElement>; + mark: React.DetailedHTMLProps, HTMLElement>; + menu: React.DetailedHTMLProps, HTMLElement>; + menuitem: React.DetailedHTMLProps, HTMLElement>; + meta: React.DetailedHTMLProps, HTMLMetaElement>; + meter: React.DetailedHTMLProps, HTMLMeterElement>; + nav: React.DetailedHTMLProps, HTMLElement>; + noindex: React.DetailedHTMLProps, HTMLElement>; + noscript: React.DetailedHTMLProps, HTMLElement>; + object: React.DetailedHTMLProps, HTMLObjectElement>; + ol: React.DetailedHTMLProps, HTMLOListElement>; + optgroup: React.DetailedHTMLProps, HTMLOptGroupElement>; + option: React.DetailedHTMLProps, HTMLOptionElement>; + output: React.DetailedHTMLProps, HTMLOutputElement>; + p: React.DetailedHTMLProps, HTMLParagraphElement>; + param: React.DetailedHTMLProps, HTMLParamElement>; + picture: React.DetailedHTMLProps, HTMLElement>; + pre: React.DetailedHTMLProps, HTMLPreElement>; + progress: React.DetailedHTMLProps, HTMLProgressElement>; + q: React.DetailedHTMLProps, HTMLQuoteElement>; + rp: React.DetailedHTMLProps, HTMLElement>; + rt: React.DetailedHTMLProps, HTMLElement>; + ruby: React.DetailedHTMLProps, HTMLElement>; + s: React.DetailedHTMLProps, HTMLElement>; + samp: React.DetailedHTMLProps, HTMLElement>; + search: React.DetailedHTMLProps, HTMLElement>; + slot: React.DetailedHTMLProps, HTMLSlotElement>; + script: React.DetailedHTMLProps, HTMLScriptElement>; + section: React.DetailedHTMLProps, HTMLElement>; + select: React.DetailedHTMLProps, HTMLSelectElement>; + small: React.DetailedHTMLProps, HTMLElement>; + source: React.DetailedHTMLProps, HTMLSourceElement>; + span: React.DetailedHTMLProps, HTMLSpanElement>; + strong: React.DetailedHTMLProps, HTMLElement>; + style: React.DetailedHTMLProps, HTMLStyleElement>; + sub: React.DetailedHTMLProps, HTMLElement>; + summary: React.DetailedHTMLProps, HTMLElement>; + sup: React.DetailedHTMLProps, HTMLElement>; + table: React.DetailedHTMLProps, HTMLTableElement>; + template: React.DetailedHTMLProps, HTMLTemplateElement>; + tbody: React.DetailedHTMLProps, HTMLTableSectionElement>; + td: React.DetailedHTMLProps, HTMLTableDataCellElement>; + textarea: React.DetailedHTMLProps, HTMLTextAreaElement>; + tfoot: React.DetailedHTMLProps, HTMLTableSectionElement>; + th: React.DetailedHTMLProps, HTMLTableHeaderCellElement>; + thead: React.DetailedHTMLProps, HTMLTableSectionElement>; + time: React.DetailedHTMLProps, HTMLTimeElement>; + title: React.DetailedHTMLProps, HTMLTitleElement>; + tr: React.DetailedHTMLProps, HTMLTableRowElement>; + track: React.DetailedHTMLProps, HTMLTrackElement>; + u: React.DetailedHTMLProps, HTMLElement>; + ul: React.DetailedHTMLProps, HTMLUListElement>; + "var": React.DetailedHTMLProps, HTMLElement>; + video: React.DetailedHTMLProps, HTMLVideoElement>; + wbr: React.DetailedHTMLProps, HTMLElement>; + webview: React.DetailedHTMLProps, HTMLWebViewElement>; + + // SVG + svg: React.SVGProps; + + animate: React.SVGProps; // TODO: It is SVGAnimateElement but is not in TypeScript's lib.dom.d.ts for now. + animateMotion: React.SVGProps; + animateTransform: React.SVGProps; // TODO: It is SVGAnimateTransformElement but is not in TypeScript's lib.dom.d.ts for now. + circle: React.SVGProps; + clipPath: React.SVGProps; + defs: React.SVGProps; + desc: React.SVGProps; + ellipse: React.SVGProps; + feBlend: React.SVGProps; + feColorMatrix: React.SVGProps; + feComponentTransfer: React.SVGProps; + feComposite: React.SVGProps; + feConvolveMatrix: React.SVGProps; + feDiffuseLighting: React.SVGProps; + feDisplacementMap: React.SVGProps; + feDistantLight: React.SVGProps; + feDropShadow: React.SVGProps; + feFlood: React.SVGProps; + feFuncA: React.SVGProps; + feFuncB: React.SVGProps; + feFuncG: React.SVGProps; + feFuncR: React.SVGProps; + feGaussianBlur: React.SVGProps; + feImage: React.SVGProps; + feMerge: React.SVGProps; + feMergeNode: React.SVGProps; + feMorphology: React.SVGProps; + feOffset: React.SVGProps; + fePointLight: React.SVGProps; + feSpecularLighting: React.SVGProps; + feSpotLight: React.SVGProps; + feTile: React.SVGProps; + feTurbulence: React.SVGProps; + filter: React.SVGProps; + foreignObject: React.SVGProps; + g: React.SVGProps; + image: React.SVGProps; + line: React.SVGLineElementAttributes; + linearGradient: React.SVGProps; + marker: React.SVGProps; + mask: React.SVGProps; + metadata: React.SVGProps; + mpath: React.SVGProps; + path: React.SVGProps; + pattern: React.SVGProps; + polygon: React.SVGProps; + polyline: React.SVGProps; + radialGradient: React.SVGProps; + rect: React.SVGProps; + set: React.SVGProps; + stop: React.SVGProps; + switch: React.SVGProps; + symbol: React.SVGProps; + text: React.SVGTextElementAttributes; + textPath: React.SVGProps; + tspan: React.SVGProps; + use: React.SVGProps; + view: React.SVGProps; + } + } +} + +// React.JSX needs to point to global.JSX to keep global module augmentations intact. +// But we can't access global.JSX so we need to create these aliases instead. +// Once the global JSX namespace will be removed we replace React.JSX with the contents of global.JSX +type GlobalJSXElementType = JSX.ElementType; +interface GlobalJSXElement extends JSX.Element {} +interface GlobalJSXElementClass extends JSX.ElementClass {} +interface GlobalJSXElementAttributesProperty extends JSX.ElementAttributesProperty {} +interface GlobalJSXElementChildrenAttribute extends JSX.ElementChildrenAttribute {} + +type GlobalJSXLibraryManagedAttributes = JSX.LibraryManagedAttributes; + +interface GlobalJSXIntrinsicAttributes extends JSX.IntrinsicAttributes {} +interface GlobalJSXIntrinsicClassAttributes extends JSX.IntrinsicClassAttributes {} + +interface GlobalJSXIntrinsicElements extends JSX.IntrinsicElements {} diff --git a/node_modules/@types/react/ts5.0/v18/jsx-dev-runtime.d.ts b/node_modules/@types/react/ts5.0/v18/jsx-dev-runtime.d.ts new file mode 100644 index 00000000..d28644c6 --- /dev/null +++ b/node_modules/@types/react/ts5.0/v18/jsx-dev-runtime.d.ts @@ -0,0 +1,45 @@ +import * as React from "./"; +export { Fragment } from "./"; + +export namespace JSX { + type ElementType = React.JSX.ElementType; + interface Element extends React.JSX.Element {} + interface ElementClass extends React.JSX.ElementClass {} + interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {} + interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {} + type LibraryManagedAttributes = React.JSX.LibraryManagedAttributes; + interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {} + interface IntrinsicClassAttributes extends React.JSX.IntrinsicClassAttributes {} + interface IntrinsicElements extends React.JSX.IntrinsicElements {} +} + +export interface JSXSource { + /** + * The source file where the element originates from. + */ + fileName?: string | undefined; + + /** + * The line number where the element was created. + */ + lineNumber?: number | undefined; + + /** + * The column number where the element was created. + */ + columnNumber?: number | undefined; +} + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsxDEV( + type: React.ElementType, + props: unknown, + key: React.Key | undefined, + isStatic: boolean, + source?: JSXSource, + self?: unknown, +): React.ReactElement; diff --git a/node_modules/@types/react/ts5.0/v18/jsx-runtime.d.ts b/node_modules/@types/react/ts5.0/v18/jsx-runtime.d.ts new file mode 100644 index 00000000..e9fea27d --- /dev/null +++ b/node_modules/@types/react/ts5.0/v18/jsx-runtime.d.ts @@ -0,0 +1,36 @@ +import * as React from "./"; +export { Fragment } from "./"; + +export namespace JSX { + type ElementType = React.JSX.ElementType; + interface Element extends React.JSX.Element {} + interface ElementClass extends React.JSX.ElementClass {} + interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {} + interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {} + type LibraryManagedAttributes = React.JSX.LibraryManagedAttributes; + interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {} + interface IntrinsicClassAttributes extends React.JSX.IntrinsicClassAttributes {} + interface IntrinsicElements extends React.JSX.IntrinsicElements {} +} + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsx( + type: React.ElementType, + props: unknown, + key?: React.Key, +): React.ReactElement; + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsxs( + type: React.ElementType, + props: unknown, + key?: React.Key, +): React.ReactElement; diff --git a/node_modules/@types/react/ts5.0/v18/ts5.0/global.d.ts b/node_modules/@types/react/ts5.0/v18/ts5.0/global.d.ts new file mode 100644 index 00000000..8911182a --- /dev/null +++ b/node_modules/@types/react/ts5.0/v18/ts5.0/global.d.ts @@ -0,0 +1,161 @@ +/* +React projects that don't include the DOM library need these interfaces to compile. +React Native applications use React, but there is no DOM available. The JavaScript runtime +is ES6/ES2015 only. These definitions allow such projects to compile with only `--lib ES6`. + +Warning: all of these interfaces are empty. If you want type definitions for various properties +(such as HTMLInputElement.prototype.value), you need to add `--lib DOM` (via command line or tsconfig.json). +*/ + +interface Event {} +interface AnimationEvent extends Event {} +interface ClipboardEvent extends Event {} +interface CompositionEvent extends Event {} +interface DragEvent extends Event {} +interface FocusEvent extends Event {} +interface InputEvent extends Event {} +interface KeyboardEvent extends Event {} +interface MouseEvent extends Event {} +interface TouchEvent extends Event {} +interface PointerEvent extends Event {} +interface ToggleEvent extends Event {} +interface TransitionEvent extends Event {} +interface UIEvent extends Event {} +interface WheelEvent extends Event {} + +interface EventTarget {} +interface Document {} +interface DataTransfer {} +interface StyleMedia {} + +interface Element {} +interface DocumentFragment {} + +interface HTMLElement extends Element {} +interface HTMLAnchorElement extends HTMLElement {} +interface HTMLAreaElement extends HTMLElement {} +interface HTMLAudioElement extends HTMLElement {} +interface HTMLBaseElement extends HTMLElement {} +interface HTMLBodyElement extends HTMLElement {} +interface HTMLBRElement extends HTMLElement {} +interface HTMLButtonElement extends HTMLElement {} +interface HTMLCanvasElement extends HTMLElement {} +interface HTMLDataElement extends HTMLElement {} +interface HTMLDataListElement extends HTMLElement {} +interface HTMLDetailsElement extends HTMLElement {} +interface HTMLDialogElement extends HTMLElement {} +interface HTMLDivElement extends HTMLElement {} +interface HTMLDListElement extends HTMLElement {} +interface HTMLEmbedElement extends HTMLElement {} +interface HTMLFieldSetElement extends HTMLElement {} +interface HTMLFormElement extends HTMLElement {} +interface HTMLHeadingElement extends HTMLElement {} +interface HTMLHeadElement extends HTMLElement {} +interface HTMLHRElement extends HTMLElement {} +interface HTMLHtmlElement extends HTMLElement {} +interface HTMLIFrameElement extends HTMLElement {} +interface HTMLImageElement extends HTMLElement {} +interface HTMLInputElement extends HTMLElement {} +interface HTMLModElement extends HTMLElement {} +interface HTMLLabelElement extends HTMLElement {} +interface HTMLLegendElement extends HTMLElement {} +interface HTMLLIElement extends HTMLElement {} +interface HTMLLinkElement extends HTMLElement {} +interface HTMLMapElement extends HTMLElement {} +interface HTMLMetaElement extends HTMLElement {} +interface HTMLMeterElement extends HTMLElement {} +interface HTMLObjectElement extends HTMLElement {} +interface HTMLOListElement extends HTMLElement {} +interface HTMLOptGroupElement extends HTMLElement {} +interface HTMLOptionElement extends HTMLElement {} +interface HTMLOutputElement extends HTMLElement {} +interface HTMLParagraphElement extends HTMLElement {} +interface HTMLParamElement extends HTMLElement {} +interface HTMLPreElement extends HTMLElement {} +interface HTMLProgressElement extends HTMLElement {} +interface HTMLQuoteElement extends HTMLElement {} +interface HTMLSlotElement extends HTMLElement {} +interface HTMLScriptElement extends HTMLElement {} +interface HTMLSelectElement extends HTMLElement {} +interface HTMLSourceElement extends HTMLElement {} +interface HTMLSpanElement extends HTMLElement {} +interface HTMLStyleElement extends HTMLElement {} +interface HTMLTableElement extends HTMLElement {} +interface HTMLTableColElement extends HTMLElement {} +interface HTMLTableDataCellElement extends HTMLElement {} +interface HTMLTableHeaderCellElement extends HTMLElement {} +interface HTMLTableRowElement extends HTMLElement {} +interface HTMLTableSectionElement extends HTMLElement {} +interface HTMLTemplateElement extends HTMLElement {} +interface HTMLTextAreaElement extends HTMLElement {} +interface HTMLTimeElement extends HTMLElement {} +interface HTMLTitleElement extends HTMLElement {} +interface HTMLTrackElement extends HTMLElement {} +interface HTMLUListElement extends HTMLElement {} +interface HTMLVideoElement extends HTMLElement {} +interface HTMLWebViewElement extends HTMLElement {} + +interface SVGElement extends Element {} +interface SVGSVGElement extends SVGElement {} +interface SVGCircleElement extends SVGElement {} +interface SVGClipPathElement extends SVGElement {} +interface SVGDefsElement extends SVGElement {} +interface SVGDescElement extends SVGElement {} +interface SVGEllipseElement extends SVGElement {} +interface SVGFEBlendElement extends SVGElement {} +interface SVGFEColorMatrixElement extends SVGElement {} +interface SVGFEComponentTransferElement extends SVGElement {} +interface SVGFECompositeElement extends SVGElement {} +interface SVGFEConvolveMatrixElement extends SVGElement {} +interface SVGFEDiffuseLightingElement extends SVGElement {} +interface SVGFEDisplacementMapElement extends SVGElement {} +interface SVGFEDistantLightElement extends SVGElement {} +interface SVGFEDropShadowElement extends SVGElement {} +interface SVGFEFloodElement extends SVGElement {} +interface SVGFEFuncAElement extends SVGElement {} +interface SVGFEFuncBElement extends SVGElement {} +interface SVGFEFuncGElement extends SVGElement {} +interface SVGFEFuncRElement extends SVGElement {} +interface SVGFEGaussianBlurElement extends SVGElement {} +interface SVGFEImageElement extends SVGElement {} +interface SVGFEMergeElement extends SVGElement {} +interface SVGFEMergeNodeElement extends SVGElement {} +interface SVGFEMorphologyElement extends SVGElement {} +interface SVGFEOffsetElement extends SVGElement {} +interface SVGFEPointLightElement extends SVGElement {} +interface SVGFESpecularLightingElement extends SVGElement {} +interface SVGFESpotLightElement extends SVGElement {} +interface SVGFETileElement extends SVGElement {} +interface SVGFETurbulenceElement extends SVGElement {} +interface SVGFilterElement extends SVGElement {} +interface SVGForeignObjectElement extends SVGElement {} +interface SVGGElement extends SVGElement {} +interface SVGImageElement extends SVGElement {} +interface SVGLineElement extends SVGElement {} +interface SVGLinearGradientElement extends SVGElement {} +interface SVGMarkerElement extends SVGElement {} +interface SVGMaskElement extends SVGElement {} +interface SVGMetadataElement extends SVGElement {} +interface SVGPathElement extends SVGElement {} +interface SVGPatternElement extends SVGElement {} +interface SVGPolygonElement extends SVGElement {} +interface SVGPolylineElement extends SVGElement {} +interface SVGRadialGradientElement extends SVGElement {} +interface SVGRectElement extends SVGElement {} +interface SVGSetElement extends SVGElement {} +interface SVGStopElement extends SVGElement {} +interface SVGSwitchElement extends SVGElement {} +interface SVGSymbolElement extends SVGElement {} +interface SVGTextElement extends SVGElement {} +interface SVGTextPathElement extends SVGElement {} +interface SVGTSpanElement extends SVGElement {} +interface SVGUseElement extends SVGElement {} +interface SVGViewElement extends SVGElement {} + +interface FormData {} +interface Text {} +interface TouchList {} +interface WebGLRenderingContext {} +interface WebGL2RenderingContext {} + +interface TrustedHTML {} diff --git a/node_modules/@types/react/ts5.0/v18/ts5.0/index.d.ts b/node_modules/@types/react/ts5.0/v18/ts5.0/index.d.ts new file mode 100644 index 00000000..a558f371 --- /dev/null +++ b/node_modules/@types/react/ts5.0/v18/ts5.0/index.d.ts @@ -0,0 +1,4537 @@ +// NOTE: Users of the `experimental` builds of React should add a reference +// to 'react/experimental' in their project. See experimental.d.ts's top comment +// for reference and documentation on how exactly to do it. + +/// + +import * as CSS from "csstype"; +import * as PropTypes from "prop-types"; + +type NativeAnimationEvent = AnimationEvent; +type NativeClipboardEvent = ClipboardEvent; +type NativeCompositionEvent = CompositionEvent; +type NativeDragEvent = DragEvent; +type NativeFocusEvent = FocusEvent; +type NativeInputEvent = InputEvent; +type NativeKeyboardEvent = KeyboardEvent; +type NativeMouseEvent = MouseEvent; +type NativeTouchEvent = TouchEvent; +type NativePointerEvent = PointerEvent; +type NativeTransitionEvent = TransitionEvent; +type NativeUIEvent = UIEvent; +type NativeWheelEvent = WheelEvent; + +/** + * Used to represent DOM API's where users can either pass + * true or false as a boolean or as its equivalent strings. + */ +type Booleanish = boolean | "true" | "false"; + +/** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin MDN} + */ +type CrossOrigin = "anonymous" | "use-credentials" | "" | undefined; + +declare const UNDEFINED_VOID_ONLY: unique symbol; + +/** + * The function returned from an effect passed to {@link React.useEffect useEffect}, + * which can be used to clean up the effect when the component unmounts. + * + * @see {@link https://react.dev/reference/react/useEffect React Docs} + */ +type Destructor = () => void | { [UNDEFINED_VOID_ONLY]: never }; +type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never }; + +// eslint-disable-next-line @definitelytyped/export-just-namespace +export = React; +export as namespace React; + +declare namespace React { + // + // React Elements + // ---------------------------------------------------------------------- + + /** + * Used to retrieve the possible components which accept a given set of props. + * + * Can be passed no type parameters to get a union of all possible components + * and tags. + * + * Is a superset of {@link ComponentType}. + * + * @template P The props to match against. If not passed, defaults to any. + * @template Tag An optional tag to match against. If not passed, attempts to match against all possible tags. + * + * @example + * + * ```tsx + * // All components and tags (img, embed etc.) + * // which accept `src` + * type SrcComponents = ElementType<{ src: any }>; + * ``` + * + * @example + * + * ```tsx + * // All components + * type AllComponents = ElementType; + * ``` + * + * @example + * + * ```tsx + * // All custom components which match `src`, and tags which + * // match `src`, narrowed down to just `audio` and `embed` + * type SrcComponents = ElementType<{ src: any }, 'audio' | 'embed'>; + * ``` + */ + type ElementType

= + | { [K in Tag]: P extends JSX.IntrinsicElements[K] ? K : never }[Tag] + | ComponentType

; + + /** + * Represents any user-defined component, either as a function or a class. + * + * Similar to {@link JSXElementConstructor}, but with extra properties like + * {@link FunctionComponent.defaultProps defaultProps } and + * {@link ComponentClass.contextTypes contextTypes}. + * + * @template P The props the component accepts. + * + * @see {@link ComponentClass} + * @see {@link FunctionComponent} + */ + type ComponentType

= ComponentClass

| FunctionComponent

; + + /** + * Represents any user-defined component, either as a function or a class. + * + * Similar to {@link ComponentType}, but without extra properties like + * {@link FunctionComponent.defaultProps defaultProps } and + * {@link ComponentClass.contextTypes contextTypes}. + * + * @template P The props the component accepts. + */ + type JSXElementConstructor

= + | (( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-stateless-function-components React Docs} + */ + deprecatedLegacyContext?: any, + ) => ReactElement | null) + | (new( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs} + */ + deprecatedLegacyContext?: any, + ) => Component); + + /** + * A readonly ref container where {@link current} cannot be mutated. + * + * Created by {@link createRef}, or {@link useRef} when passed `null`. + * + * @template T The type of the ref's value. + * + * @example + * + * ```tsx + * const ref = createRef(); + * + * ref.current = document.createElement('div'); // Error + * ``` + */ + interface RefObject { + /** + * The current value of the ref. + */ + readonly current: T | null; + } + + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES { + } + /** + * A callback fired whenever the ref's value changes. + * + * @template T The type of the ref's value. + * + * @see {@link https://react.dev/reference/react-dom/components/common#ref-callback React Docs} + * + * @example + * + * ```tsx + *

console.log(node)} /> + * ``` + */ + type RefCallback = { + bivarianceHack( + instance: T | null, + ): + | void + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES + ]; + }["bivarianceHack"]; + + /** + * A union type of all possible shapes for React refs. + * + * @see {@link RefCallback} + * @see {@link RefObject} + */ + + type Ref = RefCallback | RefObject | null; + /** + * A legacy implementation of refs where you can pass a string to a ref prop. + * + * @see {@link https://react.dev/reference/react/Component#refs React Docs} + * + * @example + * + * ```tsx + *
+ * ``` + */ + // TODO: Remove the string ref special case from `PropsWithRef` once we remove LegacyRef + type LegacyRef = string | Ref; + + /** + * Retrieves the type of the 'ref' prop for a given component type or tag name. + * + * @template C The component type. + * + * @example + * + * ```tsx + * type MyComponentRef = React.ElementRef; + * ``` + * + * @example + * + * ```tsx + * type DivRef = React.ElementRef<'div'>; + * ``` + */ + type ElementRef< + C extends + | ForwardRefExoticComponent + | { new(props: any): Component } + | ((props: any, deprecatedLegacyContext?: any) => ReactElement | null) + | keyof JSX.IntrinsicElements, + > = + // need to check first if `ref` is a valid prop for ts@3.0 + // otherwise it will infer `{}` instead of `never` + "ref" extends keyof ComponentPropsWithRef + ? NonNullable["ref"]> extends RefAttributes< + infer Instance + >["ref"] ? Instance + : never + : never; + + type ComponentState = any; + + /** + * A value which uniquely identifies a node among items in an array. + * + * @see {@link https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key React Docs} + */ + type Key = string | number | bigint; + + /** + * @internal The props any component can receive. + * You don't have to add this type. All components automatically accept these props. + * ```tsx + * const Component = () =>
; + * + * ``` + * + * WARNING: The implementation of a component will never have access to these attributes. + * The following example would be incorrect usage because {@link Component} would never have access to `key`: + * ```tsx + * const Component = (props: React.Attributes) => props.key; + * ``` + */ + interface Attributes { + key?: Key | null | undefined; + } + /** + * The props any component accepting refs can receive. + * Class components, built-in browser components (e.g. `div`) and forwardRef components can receive refs and automatically accept these props. + * ```tsx + * const Component = forwardRef(() =>
); + * console.log(current)} /> + * ``` + * + * You only need this type if you manually author the types of props that need to be compatible with legacy refs. + * ```tsx + * interface Props extends React.RefAttributes {} + * declare const Component: React.FunctionComponent; + * ``` + * + * Otherwise it's simpler to directly use {@link Ref} since you can safely use the + * props type to describe to props that a consumer can pass to the component + * as well as describing the props the implementation of a component "sees". + * {@link RefAttributes} is generally not safe to describe both consumer and seen props. + * + * ```tsx + * interface Props extends { + * ref?: React.Ref | undefined; + * } + * declare const Component: React.FunctionComponent; + * ``` + * + * WARNING: The implementation of a component will not have access to the same type in versions of React supporting string refs. + * The following example would be incorrect usage because {@link Component} would never have access to a `ref` with type `string` + * ```tsx + * const Component = (props: React.RefAttributes) => props.ref; + * ``` + */ + interface RefAttributes extends Attributes { + /** + * Allows getting a ref to the component instance. + * Once the component unmounts, React will set `ref.current` to `null` + * (or call the ref with `null` if you passed a callback ref). + * + * @see {@link https://react.dev/learn/referencing-values-with-refs#refs-and-the-dom React Docs} + */ + ref?: LegacyRef | undefined; + } + + /** + * Represents the built-in attributes available to class components. + */ + interface ClassAttributes extends RefAttributes { + } + + /** + * Represents a JSX element. + * + * Where {@link ReactNode} represents everything that can be rendered, `ReactElement` + * only represents JSX. + * + * @template P The type of the props object + * @template T The type of the component or tag + * + * @example + * + * ```tsx + * const element: ReactElement =
; + * ``` + */ + interface ReactElement< + P = any, + T extends string | JSXElementConstructor = string | JSXElementConstructor, + > { + type: T; + props: P; + key: string | null; + } + + /** + * @deprecated + */ + interface ReactComponentElement< + T extends keyof JSX.IntrinsicElements | JSXElementConstructor, + P = Pick, Exclude, "key" | "ref">>, + > extends ReactElement> {} + + interface FunctionComponentElement

extends ReactElement> { + ref?: ("ref" extends keyof P ? P extends { ref?: infer R | undefined } ? R : never : never) | undefined; + } + + type CElement> = ComponentElement; + interface ComponentElement> extends ReactElement> { + ref?: LegacyRef | undefined; + } + + /** + * @deprecated Use {@link ComponentElement} instead. + */ + type ClassicElement

= CElement>; + + // string fallback for custom web-components + interface DOMElement

| SVGAttributes, T extends Element> + extends ReactElement + { + ref: LegacyRef; + } + + // ReactHTML for ReactHTMLElement + interface ReactHTMLElement extends DetailedReactHTMLElement, T> {} + + interface DetailedReactHTMLElement

, T extends HTMLElement> extends DOMElement { + type: keyof ReactHTML; + } + + // ReactSVG for ReactSVGElement + interface ReactSVGElement extends DOMElement, SVGElement> { + type: keyof ReactSVG; + } + + interface ReactPortal extends ReactElement { + children: ReactNode; + } + + // + // Factories + // ---------------------------------------------------------------------- + + type Factory

= (props?: Attributes & P, ...children: ReactNode[]) => ReactElement

; + + /** + * @deprecated Please use `FunctionComponentFactory` + */ + type SFCFactory

= FunctionComponentFactory

; + + type FunctionComponentFactory

= ( + props?: Attributes & P, + ...children: ReactNode[] + ) => FunctionComponentElement

; + + type ComponentFactory> = ( + props?: ClassAttributes & P, + ...children: ReactNode[] + ) => CElement; + + type CFactory> = ComponentFactory; + type ClassicFactory

= CFactory>; + + type DOMFactory

, T extends Element> = ( + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ) => DOMElement; + + interface HTMLFactory extends DetailedHTMLFactory, T> {} + + interface DetailedHTMLFactory

, T extends HTMLElement> extends DOMFactory { + (props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement; + } + + interface SVGFactory extends DOMFactory, SVGElement> { + ( + props?: ClassAttributes & SVGAttributes | null, + ...children: ReactNode[] + ): ReactSVGElement; + } + + /** + * @deprecated - This type is not relevant when using React. Inline the type instead to make the intent clear. + */ + type ReactText = string | number; + /** + * @deprecated - This type is not relevant when using React. Inline the type instead to make the intent clear. + */ + type ReactChild = ReactElement | string | number; + + /** + * @deprecated Use either `ReactNode[]` if you need an array or `Iterable` if its passed to a host component. + */ + interface ReactNodeArray extends ReadonlyArray {} + /** + * WARNING: Not related to `React.Fragment`. + * @deprecated This type is not relevant when using React. Inline the type instead to make the intent clear. + */ + type ReactFragment = Iterable; + + /** + * For internal usage only. + * Different release channels declare additional types of ReactNode this particular release channel accepts. + * App or library types should never augment this interface. + */ + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES {} + + /** + * Represents all of the things React can render. + * + * Where {@link ReactElement} only represents JSX, `ReactNode` represents everything that can be rendered. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/reactnode/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Typing children + * type Props = { children: ReactNode } + * + * const Component = ({ children }: Props) =>

{children}
+ * + * hello + * ``` + * + * @example + * + * ```tsx + * // Typing a custom element + * type Props = { customElement: ReactNode } + * + * const Component = ({ customElement }: Props) =>
{customElement}
+ * + * hello
} /> + * ``` + */ + // non-thenables need to be kept in sync with AwaitedReactNode + type ReactNode = + | ReactElement + | string + | number + | Iterable + | ReactPortal + | boolean + | null + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES + ]; + + // + // Top Level API + // ---------------------------------------------------------------------- + + // DOM Elements + /** @deprecated */ + function createFactory( + type: keyof ReactHTML, + ): HTMLFactory; + /** @deprecated */ + function createFactory( + type: keyof ReactSVG, + ): SVGFactory; + /** @deprecated */ + function createFactory

, T extends Element>( + type: string, + ): DOMFactory; + + // Custom components + /** @deprecated */ + function createFactory

(type: FunctionComponent

): FunctionComponentFactory

; + /** @deprecated */ + function createFactory, C extends ComponentClass

>( + type: ClassType, + ): CFactory; + /** @deprecated */ + function createFactory

(type: ComponentClass

): Factory

; + + // DOM Elements + // TODO: generalize this to everything in `keyof ReactHTML`, not just "input" + function createElement( + type: "input", + props?: InputHTMLAttributes & ClassAttributes | null, + ...children: ReactNode[] + ): DetailedReactHTMLElement, HTMLInputElement>; + function createElement

, T extends HTMLElement>( + type: keyof ReactHTML, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): DetailedReactHTMLElement; + function createElement

, T extends SVGElement>( + type: keyof ReactSVG, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): ReactSVGElement; + function createElement

, T extends Element>( + type: string, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): DOMElement; + + // Custom components + + function createElement

( + type: FunctionComponent

, + props?: Attributes & P | null, + ...children: ReactNode[] + ): FunctionComponentElement

; + function createElement

, C extends ComponentClass

>( + type: ClassType, + props?: ClassAttributes & P | null, + ...children: ReactNode[] + ): CElement; + function createElement

( + type: FunctionComponent

| ComponentClass

| string, + props?: Attributes & P | null, + ...children: ReactNode[] + ): ReactElement

; + + // DOM Elements + // ReactHTMLElement + function cloneElement

, T extends HTMLElement>( + element: DetailedReactHTMLElement, + props?: P, + ...children: ReactNode[] + ): DetailedReactHTMLElement; + // ReactHTMLElement, less specific + function cloneElement

, T extends HTMLElement>( + element: ReactHTMLElement, + props?: P, + ...children: ReactNode[] + ): ReactHTMLElement; + // SVGElement + function cloneElement

, T extends SVGElement>( + element: ReactSVGElement, + props?: P, + ...children: ReactNode[] + ): ReactSVGElement; + // DOM Element (has to be the last, because type checking stops at first overload that fits) + function cloneElement

, T extends Element>( + element: DOMElement, + props?: DOMAttributes & P, + ...children: ReactNode[] + ): DOMElement; + + // Custom components + function cloneElement

( + element: FunctionComponentElement

, + props?: Partial

& Attributes, + ...children: ReactNode[] + ): FunctionComponentElement

; + function cloneElement>( + element: CElement, + props?: Partial

& ClassAttributes, + ...children: ReactNode[] + ): CElement; + function cloneElement

( + element: ReactElement

, + props?: Partial

& Attributes, + ...children: ReactNode[] + ): ReactElement

; + + /** + * Describes the props accepted by a Context {@link Provider}. + * + * @template T The type of the value the context provides. + */ + interface ProviderProps { + value: T; + children?: ReactNode | undefined; + } + + /** + * Describes the props accepted by a Context {@link Consumer}. + * + * @template T The type of the value the context provides. + */ + interface ConsumerProps { + children: (value: T) => ReactNode; + } + + /** + * An object masquerading as a component. These are created by functions + * like {@link forwardRef}, {@link memo}, and {@link createContext}. + * + * In order to make TypeScript work, we pretend that they are normal + * components. + * + * But they are, in fact, not callable - instead, they are objects which + * are treated specially by the renderer. + * + * @template P The props the component accepts. + */ + interface ExoticComponent

{ + (props: P): ReactElement | null; + readonly $$typeof: symbol; + } + + /** + * An {@link ExoticComponent} with a `displayName` property applied to it. + * + * @template P The props the component accepts. + */ + interface NamedExoticComponent

extends ExoticComponent

{ + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * An {@link ExoticComponent} with a `propTypes` property applied to it. + * + * @template P The props the component accepts. + */ + interface ProviderExoticComponent

extends ExoticComponent

{ + propTypes?: WeakValidationMap

| undefined; + } + + /** + * Used to retrieve the type of a context object from a {@link Context}. + * + * @template C The context object. + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const MyContext = createContext({ foo: 'bar' }); + * + * type ContextType = ContextType; + * // ContextType = { foo: string } + * ``` + */ + type ContextType> = C extends Context ? T : never; + + /** + * Wraps your components to specify the value of this context for all components inside. + * + * @see {@link https://react.dev/reference/react/createContext#provider React Docs} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * + * function App() { + * return ( + * + * + * + * ); + * } + * ``` + */ + type Provider = ProviderExoticComponent>; + + /** + * The old way to read context, before {@link useContext} existed. + * + * @see {@link https://react.dev/reference/react/createContext#consumer React Docs} + * + * @example + * + * ```tsx + * import { UserContext } from './user-context'; + * + * function Avatar() { + * return ( + * + * {user => {user.name}} + * + * ); + * } + * ``` + */ + type Consumer = ExoticComponent>; + + /** + * Context lets components pass information deep down without explicitly + * passing props. + * + * Created from {@link createContext} + * + * @see {@link https://react.dev/learn/passing-data-deeply-with-context React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * ``` + */ + interface Context { + Provider: Provider; + Consumer: Consumer; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * Lets you create a {@link Context} that components can provide or read. + * + * @param defaultValue The value you want the context to have when there is no matching + * {@link Provider} in the tree above the component reading the context. This is meant + * as a "last resort" fallback. + * + * @see {@link https://react.dev/reference/react/createContext#reference React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * import { createContext } from 'react'; + * + * const ThemeContext = createContext('light'); + * ``` + */ + function createContext( + // If you thought this should be optional, see + // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106 + defaultValue: T, + ): Context; + + function isValidElement

(object: {} | null | undefined): object is ReactElement

; + + /** + * Maintainer's note: Sync with {@link ReactChildren} until {@link ReactChildren} is removed. + */ + const Children: { + map( + children: C | readonly C[], + fn: (child: C, index: number) => T, + ): C extends null | undefined ? C : Array>; + forEach(children: C | readonly C[], fn: (child: C, index: number) => void): void; + count(children: any): number; + only(children: C): C extends any[] ? never : C; + toArray(children: ReactNode | ReactNode[]): Array>; + }; + /** + * Lets you group elements without a wrapper node. + * + * @see {@link https://react.dev/reference/react/Fragment React Docs} + * + * @example + * + * ```tsx + * import { Fragment } from 'react'; + * + * + * Hello + * World + * + * ``` + * + * @example + * + * ```tsx + * // Using the <> shorthand syntax: + * + * <> + * Hello + * World + * + * ``` + */ + const Fragment: ExoticComponent<{ children?: ReactNode | undefined }>; + + /** + * Lets you find common bugs in your components early during development. + * + * @see {@link https://react.dev/reference/react/StrictMode React Docs} + * + * @example + * + * ```tsx + * import { StrictMode } from 'react'; + * + * + * + * + * ``` + */ + const StrictMode: ExoticComponent<{ children?: ReactNode | undefined }>; + + /** + * The props accepted by {@link Suspense}. + * + * @see {@link https://react.dev/reference/react/Suspense React Docs} + */ + interface SuspenseProps { + children?: ReactNode | undefined; + + /** A fallback react tree to show when a Suspense child (like React.lazy) suspends */ + fallback?: ReactNode; + + /** + * A name for this Suspense boundary for instrumentation purposes. + * The name will help identify this boundary in React DevTools. + */ + name?: string | undefined; + } + + /** + * Lets you display a fallback until its children have finished loading. + * + * @see {@link https://react.dev/reference/react/Suspense React Docs} + * + * @example + * + * ```tsx + * import { Suspense } from 'react'; + * + * }> + * + * + * ``` + */ + const Suspense: ExoticComponent; + const version: string; + + /** + * The callback passed to {@link ProfilerProps.onRender}. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + type ProfilerOnRenderCallback = ( + /** + * The string id prop of the {@link Profiler} tree that has just committed. This lets + * you identify which part of the tree was committed if you are using multiple + * profilers. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + id: string, + /** + * This lets you know whether the tree has just been mounted for the first time + * or re-rendered due to a change in props, state, or hooks. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + phase: "mount" | "update" | "nested-update", + /** + * The number of milliseconds spent rendering the {@link Profiler} and its descendants + * for the current update. This indicates how well the subtree makes use of + * memoization (e.g. {@link memo} and {@link useMemo}). Ideally this value should decrease + * significantly after the initial mount as many of the descendants will only need to + * re-render if their specific props change. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + actualDuration: number, + /** + * The number of milliseconds estimating how much time it would take to re-render the entire + * {@link Profiler} subtree without any optimizations. It is calculated by summing up the most + * recent render durations of each component in the tree. This value estimates a worst-case + * cost of rendering (e.g. the initial mount or a tree with no memoization). Compare + * {@link actualDuration} against it to see if memoization is working. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + baseDuration: number, + /** + * A numeric timestamp for when React began rendering the current update. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + startTime: number, + /** + * A numeric timestamp for when React committed the current update. This value is shared + * between all profilers in a commit, enabling them to be grouped if desirable. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + */ + commitTime: number, + ) => void; + + /** + * The props accepted by {@link Profiler}. + * + * @see {@link https://react.dev/reference/react/Profiler React Docs} + */ + interface ProfilerProps { + children?: ReactNode | undefined; + id: string; + onRender: ProfilerOnRenderCallback; + } + + /** + * Lets you measure rendering performance of a React tree programmatically. + * + * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs} + * + * @example + * + * ```tsx + * + * + * + * ``` + */ + const Profiler: ExoticComponent; + + // + // Component API + // ---------------------------------------------------------------------- + + type ReactInstance = Component | Element; + + // Base component for plain JS classes + interface Component

extends ComponentLifecycle {} + class Component { + /** + * If set, `this.context` will be set at runtime to the current value of the given Context. + * + * @example + * + * ```ts + * type MyContext = number + * const Ctx = React.createContext(0) + * + * class Foo extends React.Component { + * static contextType = Ctx + * context!: React.ContextType + * render () { + * return <>My context's value: {this.context}; + * } + * } + * ``` + * + * @see {@link https://react.dev/reference/react/Component#static-contexttype} + */ + static contextType?: Context | undefined; + + /** + * If using the new style context, re-declare this in your class to be the + * `React.ContextType` of your `static contextType`. + * Should be used with type annotation or static contextType. + * + * @example + * ```ts + * static contextType = MyContext + * // For TS pre-3.7: + * context!: React.ContextType + * // For TS 3.7 and above: + * declare context: React.ContextType + * ``` + * + * @see {@link https://react.dev/reference/react/Component#context React Docs} + */ + context: unknown; + + constructor(props: P); + /** + * @deprecated + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html React Docs} + */ + constructor(props: P, context: any); + + // We MUST keep setState() as a unified signature because it allows proper checking of the method return type. + // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257 + // Also, the ` | S` allows intellisense to not be dumbisense + setState( + state: ((prevState: Readonly, props: Readonly

) => Pick | S | null) | (Pick | S | null), + callback?: () => void, + ): void; + + forceUpdate(callback?: () => void): void; + render(): ReactNode; + + readonly props: Readonly

; + state: Readonly; + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs Legacy React Docs} + */ + refs: { + [key: string]: ReactInstance; + }; + } + + class PureComponent

extends Component {} + + /** + * @deprecated Use `ClassicComponent` from `create-react-class` + * + * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs} + * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm} + */ + interface ClassicComponent

extends Component { + replaceState(nextState: S, callback?: () => void): void; + isMounted(): boolean; + getInitialState?(): S; + } + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + /** + * Represents the type of a function component. Can optionally + * receive a type argument that represents the props the component + * receives. + * + * @template P The props the component accepts. + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet} + * @alias for {@link FunctionComponent} + * + * @example + * + * ```tsx + * // With props: + * type Props = { name: string } + * + * const MyComponent: FC = (props) => { + * return

{props.name}
+ * } + * ``` + * + * @example + * + * ```tsx + * // Without props: + * const MyComponentWithoutProps: FC = () => { + * return
MyComponentWithoutProps
+ * } + * ``` + */ + type FC

= FunctionComponent

; + + /** + * Represents the type of a function component. Can optionally + * receive a type argument that represents the props the component + * accepts. + * + * @template P The props the component accepts. + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // With props: + * type Props = { name: string } + * + * const MyComponent: FunctionComponent = (props) => { + * return

{props.name}
+ * } + * ``` + * + * @example + * + * ```tsx + * // Without props: + * const MyComponentWithoutProps: FunctionComponent = () => { + * return
MyComponentWithoutProps
+ * } + * ``` + */ + interface FunctionComponent

{ + ( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs} + */ + deprecatedLegacyContext?: any, + ): ReactElement | null; + /** + * Used to declare the types of the props accepted by the + * component. These types will be checked during rendering + * and in development only. + * + * We recommend using TypeScript instead of checking prop + * types at runtime. + * + * @see {@link https://react.dev/reference/react/Component#static-proptypes React Docs} + */ + propTypes?: WeakValidationMap

| undefined; + /** + * @deprecated + * + * Lets you specify which legacy context is consumed by + * this component. + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html Legacy React Docs} + */ + contextTypes?: ValidationMap | undefined; + /** + * Used to define default values for the props accepted by + * the component. + * + * @see {@link https://react.dev/reference/react/Component#static-defaultprops React Docs} + * + * @example + * + * ```tsx + * type Props = { name?: string } + * + * const MyComponent: FC = (props) => { + * return

{props.name}
+ * } + * + * MyComponent.defaultProps = { + * name: 'John Doe' + * } + * ``` + * + * @deprecated Use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value|default values for destructuring assignments instead}. + */ + defaultProps?: Partial

| undefined; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + * + * @example + * + * ```tsx + * + * const MyComponent: FC = () => { + * return

Hello!
+ * } + * + * MyComponent.displayName = 'MyAwesomeComponent' + * ``` + */ + displayName?: string | undefined; + } + + /** + * @deprecated - Equivalent to {@link React.FunctionComponent}. + * + * @see {@link React.FunctionComponent} + * @alias {@link VoidFunctionComponent} + */ + type VFC

= VoidFunctionComponent

; + + /** + * @deprecated - Equivalent to {@link React.FunctionComponent}. + * + * @see {@link React.FunctionComponent} + */ + interface VoidFunctionComponent

{ + ( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs} + */ + deprecatedLegacyContext?: any, + ): ReactElement | null; + propTypes?: WeakValidationMap

| undefined; + contextTypes?: ValidationMap | undefined; + /** + * @deprecated Use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value|default values for destructuring assignments instead}. + */ + defaultProps?: Partial

| undefined; + displayName?: string | undefined; + } + + /** + * The type of the ref received by a {@link ForwardRefRenderFunction}. + * + * @see {@link ForwardRefRenderFunction} + */ + type ForwardedRef = ((instance: T | null) => void) | MutableRefObject | null; + + /** + * The type of the function passed to {@link forwardRef}. This is considered different + * to a normal {@link FunctionComponent} because it receives an additional argument, + * + * @param props Props passed to the component, if any. + * @param ref A ref forwarded to the component of type {@link ForwardedRef}. + * + * @template T The type of the forwarded ref. + * @template P The type of the props the component accepts. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet} + * @see {@link forwardRef} + */ + interface ForwardRefRenderFunction { + (props: P, ref: ForwardedRef): ReactElement | null; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * Will show `ForwardRef(${Component.displayName || Component.name})` + * in devtools by default, but can be given its own specific name. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + /** + * defaultProps are not supported on render functions passed to forwardRef. + * + * @see {@link https://github.com/microsoft/TypeScript/issues/36826 linked GitHub issue} for context + * @see {@link https://react.dev/reference/react/Component#static-defaultprops React Docs} + */ + defaultProps?: never | undefined; + /** + * propTypes are not supported on render functions passed to forwardRef. + * + * @see {@link https://github.com/microsoft/TypeScript/issues/36826 linked GitHub issue} for context + * @see {@link https://react.dev/reference/react/Component#static-proptypes React Docs} + */ + propTypes?: never | undefined; + } + + /** + * Represents a component class in React. + * + * @template P The props the component accepts. + * @template S The internal state of the component. + */ + interface ComponentClass

extends StaticLifecycle { + new( + props: P, + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs} + */ + deprecatedLegacyContext?: any, + ): Component; + /** + * Used to declare the types of the props accepted by the + * component. These types will be checked during rendering + * and in development only. + * + * We recommend using TypeScript instead of checking prop + * types at runtime. + * + * @see {@link https://react.dev/reference/react/Component#static-proptypes React Docs} + */ + propTypes?: WeakValidationMap

| undefined; + contextType?: Context | undefined; + /** + * @deprecated use {@link ComponentClass.contextType} instead + * + * Lets you specify which legacy context is consumed by + * this component. + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html Legacy React Docs} + */ + contextTypes?: ValidationMap | undefined; + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#how-to-use-context Legacy React Docs} + */ + childContextTypes?: ValidationMap | undefined; + /** + * Used to define default values for the props accepted by + * the component. + * + * @see {@link https://react.dev/reference/react/Component#static-defaultprops React Docs} + */ + defaultProps?: Partial

| undefined; + /** + * Used in debugging messages. You might want to set it + * explicitly if you want to display a different name for + * debugging purposes. + * + * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs} + */ + displayName?: string | undefined; + } + + /** + * @deprecated Use `ClassicComponentClass` from `create-react-class` + * + * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs} + * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm} + */ + interface ClassicComponentClass

extends ComponentClass

{ + new(props: P, deprecatedLegacyContext?: any): ClassicComponent; + getDefaultProps?(): P; + } + + /** + * Used in {@link createElement} and {@link createFactory} to represent + * a class. + * + * An intersection type is used to infer multiple type parameters from + * a single argument, which is useful for many top-level API defs. + * See {@link https://github.com/Microsoft/TypeScript/issues/7234 this GitHub issue} + * for more info. + */ + type ClassType, C extends ComponentClass

> = + & C + & (new(props: P, deprecatedLegacyContext?: any) => T); + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + // This should actually be something like `Lifecycle | DeprecatedLifecycle`, + // as React will _not_ call the deprecated lifecycle methods if any of the new lifecycle + // methods are present. + interface ComponentLifecycle extends NewLifecycle, DeprecatedLifecycle { + /** + * Called immediately after a component is mounted. Setting state here will trigger re-rendering. + */ + componentDidMount?(): void; + /** + * Called to determine whether the change in props and state should trigger a re-render. + * + * `Component` always returns true. + * `PureComponent` implements a shallow comparison on props and state and returns true if any + * props or states have changed. + * + * If false is returned, {@link Component.render}, `componentWillUpdate` + * and `componentDidUpdate` will not be called. + */ + shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; + /** + * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as + * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`. + */ + componentWillUnmount?(): void; + /** + * Catches exceptions generated in descendant components. Unhandled exceptions will cause + * the entire component tree to unmount. + */ + componentDidCatch?(error: Error, errorInfo: ErrorInfo): void; + } + + // Unfortunately, we have no way of declaring that the component constructor must implement this + interface StaticLifecycle { + getDerivedStateFromProps?: GetDerivedStateFromProps | undefined; + getDerivedStateFromError?: GetDerivedStateFromError | undefined; + } + + type GetDerivedStateFromProps = + /** + * Returns an update to a component's state based on its new props and old state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (nextProps: Readonly

, prevState: S) => Partial | null; + + type GetDerivedStateFromError = + /** + * This lifecycle is invoked after an error has been thrown by a descendant component. + * It receives the error that was thrown as a parameter and should return a value to update state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (error: any) => Partial | null; + + // This should be "infer SS" but can't use it yet + interface NewLifecycle { + /** + * Runs before React applies the result of {@link Component.render render} to the document, and + * returns an object to be given to {@link componentDidUpdate}. Useful for saving + * things such as scroll position before {@link Component.render render} causes changes to it. + * + * Note: the presence of this method prevents any of the deprecated + * lifecycle events from running. + */ + getSnapshotBeforeUpdate?(prevProps: Readonly

, prevState: Readonly): SS | null; + /** + * Called immediately after updating occurs. Not called for the initial render. + * + * The snapshot is only present if {@link getSnapshotBeforeUpdate} is present and returns non-null. + */ + componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, snapshot?: SS): void; + } + + interface DeprecatedLifecycle { + /** + * Called immediately before mounting occurs, and before {@link Component.render}. + * Avoid introducing any side-effects or subscriptions in this method. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillMount?(): void; + /** + * Called immediately before mounting occurs, and before {@link Component.render}. + * Avoid introducing any side-effects or subscriptions in this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillMount?(): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling {@link Component.setState} generally does not trigger this method. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling {@link Component.setState} generally does not trigger this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call {@link Component.setState} here. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17 + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call {@link Component.setState} here. + * + * This method will not stop working in React 17. + * + * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate} + * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents + * this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update} + * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path} + */ + UNSAFE_componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + } + + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/blog/2016/07/13/mixins-considered-harmful.html Mixins Considered Harmful} + */ + interface Mixin extends ComponentLifecycle { + mixins?: Array> | undefined; + statics?: { + [key: string]: any; + } | undefined; + + displayName?: string | undefined; + propTypes?: ValidationMap | undefined; + contextTypes?: ValidationMap | undefined; + childContextTypes?: ValidationMap | undefined; + + getDefaultProps?(): P; + getInitialState?(): S; + } + + /** + * @deprecated + * + * @see {@link https://legacy.reactjs.org/blog/2016/07/13/mixins-considered-harmful.html Mixins Considered Harmful} + */ + interface ComponentSpec extends Mixin { + render(): ReactNode; + + [propertyName: string]: any; + } + + function createRef(): RefObject; + + /** + * The type of the component returned from {@link forwardRef}. + * + * @template P The props the component accepts, if any. + * + * @see {@link ExoticComponent} + */ + interface ForwardRefExoticComponent

extends NamedExoticComponent

{ + /** + * @deprecated Use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value|default values for destructuring assignments instead}. + */ + defaultProps?: Partial

| undefined; + propTypes?: WeakValidationMap

| undefined; + } + + /** + * Lets your component expose a DOM node to a parent component + * using a ref. + * + * @see {@link https://react.dev/reference/react/forwardRef React Docs} + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet} + * + * @param render See the {@link ForwardRefRenderFunction}. + * + * @template T The type of the DOM node. + * @template P The props the component accepts, if any. + * + * @example + * + * ```tsx + * interface Props { + * children?: ReactNode; + * type: "submit" | "button"; + * } + * + * export const FancyButton = forwardRef((props, ref) => ( + * + * )); + * ``` + */ + function forwardRef( + render: ForwardRefRenderFunction>, + ): ForwardRefExoticComponent & RefAttributes>; + + /** + * Omits the 'ref' attribute from the given props object. + * + * @template P The props object type. + */ + type PropsWithoutRef

= + // Omit would not be sufficient for this. We'd like to avoid unnecessary mapping and need a distributive conditional to support unions. + // see: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types + // https://github.com/Microsoft/TypeScript/issues/28339 + P extends any ? ("ref" extends keyof P ? Omit : P) : P; + /** Ensures that the props do not include string ref, which cannot be forwarded */ + type PropsWithRef

= + // Note: String refs can be forwarded. We can't fix this bug without breaking a bunch of libraries now though. + // Just "P extends { ref?: infer R }" looks sufficient, but R will infer as {} if P is {}. + "ref" extends keyof P + ? P extends { ref?: infer R | undefined } + ? string extends R ? PropsWithoutRef

& { ref?: Exclude | undefined } + : P + : P + : P; + + type PropsWithChildren

= P & { children?: ReactNode | undefined }; + + /** + * Used to retrieve the props a component accepts. Can either be passed a string, + * indicating a DOM element (e.g. 'div', 'span', etc.) or the type of a React + * component. + * + * It's usually better to use {@link ComponentPropsWithRef} or {@link ComponentPropsWithoutRef} + * instead of this type, as they let you be explicit about whether or not to include + * the `ref` prop. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentProps<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>

; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentProps = React.ComponentProps; + * ``` + */ + type ComponentProps> = T extends + JSXElementConstructor ? P + : T extends keyof JSX.IntrinsicElements ? JSX.IntrinsicElements[T] + : {}; + + /** + * Used to retrieve the props a component accepts with its ref. Can either be + * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the + * type of a React component. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentPropsWithRef<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>
; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithRef = React.ComponentPropsWithRef; + * ``` + */ + type ComponentPropsWithRef = T extends (new(props: infer P) => Component) + ? PropsWithoutRef

& RefAttributes> + : PropsWithRef>; + /** + * Used to retrieve the props a custom component accepts with its ref. + * + * Unlike {@link ComponentPropsWithRef}, this only works with custom + * components, i.e. components you define yourself. This is to improve + * type-checking performance. + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>

; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithRef = React.CustomComponentPropsWithRef; + * ``` + */ + type CustomComponentPropsWithRef = T extends (new(props: infer P) => Component) + ? (PropsWithoutRef

& RefAttributes>) + : T extends ((props: infer P, legacyContext?: any) => ReactNode) ? PropsWithRef

+ : never; + + /** + * Used to retrieve the props a component accepts without its ref. Can either be + * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the + * type of a React component. + * + * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet} + * + * @example + * + * ```tsx + * // Retrieves the props an 'input' element accepts + * type InputProps = React.ComponentPropsWithoutRef<'input'>; + * ``` + * + * @example + * + * ```tsx + * const MyComponent = (props: { foo: number, bar: string }) =>

; + * + * // Retrieves the props 'MyComponent' accepts + * type MyComponentPropsWithoutRef = React.ComponentPropsWithoutRef; + * ``` + */ + type ComponentPropsWithoutRef = PropsWithoutRef>; + + type ComponentRef = T extends NamedExoticComponent< + ComponentPropsWithoutRef & RefAttributes + > ? Method + : ComponentPropsWithRef extends RefAttributes ? Method + : never; + + // will show `Memo(${Component.displayName || Component.name})` in devtools by default, + // but can be given its own specific name + type MemoExoticComponent> = NamedExoticComponent> & { + readonly type: T; + }; + + /** + * Lets you skip re-rendering a component when its props are unchanged. + * + * @see {@link https://react.dev/reference/react/memo React Docs} + * + * @param Component The component to memoize. + * @param propsAreEqual A function that will be used to determine if the props have changed. + * + * @example + * + * ```tsx + * import { memo } from 'react'; + * + * const SomeComponent = memo(function SomeComponent(props: { foo: string }) { + * // ... + * }); + * ``` + */ + function memo

( + Component: FunctionComponent

, + propsAreEqual?: (prevProps: Readonly

, nextProps: Readonly

) => boolean, + ): NamedExoticComponent

; + function memo>( + Component: T, + propsAreEqual?: (prevProps: Readonly>, nextProps: Readonly>) => boolean, + ): MemoExoticComponent; + + interface LazyExoticComponent> + extends ExoticComponent> + { + readonly _result: T; + } + + /** + * Lets you defer loading a component’s code until it is rendered for the first time. + * + * @see {@link https://react.dev/reference/react/lazy React Docs} + * + * @param load A function that returns a `Promise` or another thenable (a `Promise`-like object with a + * then method). React will not call `load` until the first time you attempt to render the returned + * component. After React first calls load, it will wait for it to resolve, and then render the + * resolved value’s `.default` as a React component. Both the returned `Promise` and the `Promise`’s + * resolved value will be cached, so React will not call load more than once. If the `Promise` rejects, + * React will throw the rejection reason for the nearest Error Boundary to handle. + * + * @example + * + * ```tsx + * import { lazy } from 'react'; + * + * const MarkdownPreview = lazy(() => import('./MarkdownPreview.js')); + * ``` + */ + function lazy>( + load: () => Promise<{ default: T }>, + ): LazyExoticComponent; + + // + // React Hooks + // ---------------------------------------------------------------------- + + /** + * The instruction passed to a {@link Dispatch} function in {@link useState} + * to tell React what the next value of the {@link useState} should be. + * + * Often found wrapped in {@link Dispatch}. + * + * @template S The type of the state. + * + * @example + * + * ```tsx + * // This return type correctly represents the type of + * // `setCount` in the example below. + * const useCustomState = (): Dispatch> => { + * const [count, setCount] = useState(0); + * + * return setCount; + * } + * ``` + */ + type SetStateAction = S | ((prevState: S) => S); + + /** + * A function that can be used to update the state of a {@link useState} + * or {@link useReducer} hook. + */ + type Dispatch = (value: A) => void; + /** + * A {@link Dispatch} function can sometimes be called without any arguments. + */ + type DispatchWithoutAction = () => void; + // Unlike redux, the actions _can_ be anything + type Reducer = (prevState: S, action: A) => S; + // If useReducer accepts a reducer without action, dispatch may be called without any parameters. + type ReducerWithoutAction = (prevState: S) => S; + // types used to try and prevent the compiler from reducing S + // to a supertype common with the second argument to useReducer() + type ReducerState> = R extends Reducer ? S : never; + type ReducerAction> = R extends Reducer ? A : never; + // The identity check is done with the SameValue algorithm (Object.is), which is stricter than === + type ReducerStateWithoutAction> = R extends ReducerWithoutAction ? S + : never; + type DependencyList = readonly unknown[]; + + // NOTE: callbacks are _only_ allowed to return either void, or a destructor. + type EffectCallback = () => void | Destructor; + + interface MutableRefObject { + current: T; + } + + // This will technically work if you give a Consumer or Provider but it's deprecated and warns + /** + * Accepts a context object (the value returned from `React.createContext`) and returns the current + * context value, as given by the nearest context provider for the given context. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useContext} + */ + function useContext(context: Context /*, (not public API) observedBits?: number|boolean */): T; + /** + * Returns a stateful value, and a function to update it. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useState} + */ + function useState(initialState: S | (() => S)): [S, Dispatch>]; + // convenience overload when first argument is omitted + /** + * Returns a stateful value, and a function to update it. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useState} + */ + function useState(): [S | undefined, Dispatch>]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + // overload where dispatch could accept 0 arguments. + function useReducer, I>( + reducer: R, + initializerArg: I, + initializer: (arg: I) => ReducerStateWithoutAction, + ): [ReducerStateWithoutAction, DispatchWithoutAction]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + // overload where dispatch could accept 0 arguments. + function useReducer>( + reducer: R, + initializerArg: ReducerStateWithoutAction, + initializer?: undefined, + ): [ReducerStateWithoutAction, DispatchWithoutAction]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + // overload where "I" may be a subset of ReducerState; used to provide autocompletion. + // If "I" matches ReducerState exactly then the last overload will allow initializer to be omitted. + // the last overload effectively behaves as if the identity function (x => x) is the initializer. + function useReducer, I>( + reducer: R, + initializerArg: I & ReducerState, + initializer: (arg: I & ReducerState) => ReducerState, + ): [ReducerState, Dispatch>]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + // overload for free "I"; all goes as long as initializer converts it into "ReducerState". + function useReducer, I>( + reducer: R, + initializerArg: I, + initializer: (arg: I) => ReducerState, + ): [ReducerState, Dispatch>]; + /** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useReducer} + */ + + // I'm not sure if I keep this 2-ary or if I make it (2,3)-ary; it's currently (2,3)-ary. + // The Flow types do have an overload for 3-ary invocation with undefined initializer. + + // NOTE: without the ReducerState indirection, TypeScript would reduce S to be the most common + // supertype between the reducer's return type and the initialState (or the initializer's return type), + // which would prevent autocompletion from ever working. + + // TODO: double-check if this weird overload logic is necessary. It is possible it's either a bug + // in older versions, or a regression in newer versions of the typescript completion service. + function useReducer>( + reducer: R, + initialState: ReducerState, + initializer?: undefined, + ): [ReducerState, Dispatch>]; + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T): MutableRefObject; + // convenience overload for refs given as a ref prop as they typically start with a null value + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * Usage note: if you need the result of useRef to be directly mutable, include `| null` in the type + * of the generic argument. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(initialValue: T | null): RefObject; + // convenience overload for potentially undefined initialValue / call with 0 arguments + // has a default to stop it from defaulting to {} instead + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useRef} + */ + function useRef(): MutableRefObject; + /** + * The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations. + * Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside + * `useLayoutEffect` will be flushed synchronously, before the browser has a chance to paint. + * + * Prefer the standard `useEffect` when possible to avoid blocking visual updates. + * + * If you’re migrating code from a class component, `useLayoutEffect` fires in the same phase as + * `componentDidMount` and `componentDidUpdate`. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useLayoutEffect} + */ + function useLayoutEffect(effect: EffectCallback, deps?: DependencyList): void; + /** + * Accepts a function that contains imperative, possibly effectful code. + * + * @param effect Imperative function that can return a cleanup function + * @param deps If present, effect will only activate if the values in the list change. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useEffect} + */ + function useEffect(effect: EffectCallback, deps?: DependencyList): void; + // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref + /** + * `useImperativeHandle` customizes the instance value that is exposed to parent components when using + * `ref`. As always, imperative code using refs should be avoided in most cases. + * + * `useImperativeHandle` should be used with `React.forwardRef`. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useImperativeHandle} + */ + function useImperativeHandle(ref: Ref | undefined, init: () => R, deps?: DependencyList): void; + // I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key + // useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y. + /** + * `useCallback` will return a memoized version of the callback that only changes if one of the `inputs` + * has changed. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useCallback} + */ + // A specific function type would not trigger implicit any. + // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/52873#issuecomment-845806435 for a comparison between `Function` and more specific types. + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + function useCallback(callback: T, deps: DependencyList): T; + /** + * `useMemo` will only recompute the memoized value when one of the `deps` has changed. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useMemo} + */ + // allow undefined, but don't make it optional as that is very likely a mistake + function useMemo(factory: () => T, deps: DependencyList): T; + /** + * `useDebugValue` can be used to display a label for custom hooks in React DevTools. + * + * NOTE: We don’t recommend adding debug values to every custom hook. + * It’s most valuable for custom hooks that are part of shared libraries. + * + * @version 16.8.0 + * @see {@link https://react.dev/reference/react/useDebugValue} + */ + // the name of the custom hook is itself derived from the function name at runtime: + // it's just the function name without the "use" prefix. + function useDebugValue(value: T, format?: (value: T) => any): void; + + // must be synchronous + export type TransitionFunction = () => VoidOrUndefinedOnly; + // strange definition to allow vscode to show documentation on the invocation + export interface TransitionStartFunction { + /** + * State updates caused inside the callback are allowed to be deferred. + * + * **If some state update causes a component to suspend, that state update should be wrapped in a transition.** + * + * @param callback A _synchronous_ function which causes state updates that can be deferred. + */ + (callback: TransitionFunction): void; + } + + /** + * Returns a deferred version of the value that may “lag behind” it. + * + * This is commonly used to keep the interface responsive when you have something that renders immediately + * based on user input and something that needs to wait for a data fetch. + * + * A good example of this is a text input. + * + * @param value The value that is going to be deferred + * + * @see {@link https://react.dev/reference/react/useDeferredValue} + */ + export function useDeferredValue(value: T): T; + + /** + * Allows components to avoid undesirable loading states by waiting for content to load + * before transitioning to the next screen. It also allows components to defer slower, + * data fetching updates until subsequent renders so that more crucial updates can be + * rendered immediately. + * + * The `useTransition` hook returns two values in an array. + * + * The first is a boolean, React’s way of informing us whether we’re waiting for the transition to finish. + * The second is a function that takes a callback. We can use it to tell React which state we want to defer. + * + * **If some state update causes a component to suspend, that state update should be wrapped in a transition.** + * + * @see {@link https://react.dev/reference/react/useTransition} + */ + export function useTransition(): [boolean, TransitionStartFunction]; + + /** + * Similar to `useTransition` but allows uses where hooks are not available. + * + * @param callback A _synchronous_ function which causes state updates that can be deferred. + */ + export function startTransition(scope: TransitionFunction): void; + + /** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ + // While act does always return Thenable, if a void function is passed, we pretend the return value is also void to not trigger dangling Promise lint rules. + export function act(callback: () => VoidOrUndefinedOnly): void; + export function act(callback: () => T | Promise): Promise; + + export function useId(): string; + + /** + * @param effect Imperative function that can return a cleanup function + * @param deps If present, effect will only activate if the values in the list change. + * + * @see {@link https://github.com/facebook/react/pull/21913} + */ + export function useInsertionEffect(effect: EffectCallback, deps?: DependencyList): void; + + /** + * @param subscribe + * @param getSnapshot + * + * @see {@link https://github.com/reactwg/react-18/discussions/86} + */ + // keep in sync with `useSyncExternalStore` from `use-sync-external-store` + export function useSyncExternalStore( + subscribe: (onStoreChange: () => void) => () => void, + getSnapshot: () => Snapshot, + getServerSnapshot?: () => Snapshot, + ): Snapshot; + + // + // Event System + // ---------------------------------------------------------------------- + // TODO: change any to unknown when moving to TS v3 + interface BaseSyntheticEvent { + nativeEvent: E; + currentTarget: C; + target: T; + bubbles: boolean; + cancelable: boolean; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + preventDefault(): void; + isDefaultPrevented(): boolean; + stopPropagation(): void; + isPropagationStopped(): boolean; + persist(): void; + timeStamp: number; + type: string; + } + + /** + * currentTarget - a reference to the element on which the event listener is registered. + * + * target - a reference to the element from which the event was originally dispatched. + * This might be a child element to the element on which the event listener is registered. + * If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11508#issuecomment-256045682 + */ + interface SyntheticEvent extends BaseSyntheticEvent {} + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + } + + interface CompositionEvent extends SyntheticEvent { + data: string; + } + + interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + } + + interface PointerEvent extends MouseEvent { + pointerId: number; + pressure: number; + tangentialPressure: number; + tiltX: number; + tiltY: number; + twist: number; + width: number; + height: number; + pointerType: "mouse" | "pen" | "touch"; + isPrimary: boolean; + } + + interface FocusEvent extends SyntheticEvent { + relatedTarget: (EventTarget & RelatedTarget) | null; + target: EventTarget & Target; + } + + interface FormEvent extends SyntheticEvent { + } + + interface InvalidEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface ChangeEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface InputEvent extends SyntheticEvent { + data: string; + } + + export type ModifierKey = + | "Alt" + | "AltGraph" + | "CapsLock" + | "Control" + | "Fn" + | "FnLock" + | "Hyper" + | "Meta" + | "NumLock" + | "ScrollLock" + | "Shift" + | "Super" + | "Symbol" + | "SymbolLock"; + + interface KeyboardEvent extends UIEvent { + altKey: boolean; + /** @deprecated */ + charCode: number; + ctrlKey: boolean; + code: string; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + /** + * See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values + */ + key: string; + /** @deprecated */ + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + repeat: boolean; + shiftKey: boolean; + /** @deprecated */ + which: number; + } + + interface MouseEvent extends UIEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + metaKey: boolean; + movementX: number; + movementY: number; + pageX: number; + pageY: number; + relatedTarget: EventTarget | null; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends UIEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: ModifierKey): boolean; + metaKey: boolean; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + view: AbstractView; + } + + interface WheelEvent extends MouseEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + } + + interface AnimationEvent extends SyntheticEvent { + animationName: string; + elapsedTime: number; + pseudoElement: string; + } + + interface TransitionEvent extends SyntheticEvent { + elapsedTime: number; + propertyName: string; + pseudoElement: string; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + type EventHandler> = { bivarianceHack(event: E): void }["bivarianceHack"]; + + type ReactEventHandler = EventHandler>; + + type ClipboardEventHandler = EventHandler>; + type CompositionEventHandler = EventHandler>; + type DragEventHandler = EventHandler>; + type FocusEventHandler = EventHandler>; + type FormEventHandler = EventHandler>; + type ChangeEventHandler = EventHandler>; + type InputEventHandler = EventHandler>; + type KeyboardEventHandler = EventHandler>; + type MouseEventHandler = EventHandler>; + type TouchEventHandler = EventHandler>; + type PointerEventHandler = EventHandler>; + type UIEventHandler = EventHandler>; + type WheelEventHandler = EventHandler>; + type AnimationEventHandler = EventHandler>; + type TransitionEventHandler = EventHandler>; + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + interface HTMLProps extends AllHTMLAttributes, ClassAttributes { + } + + type DetailedHTMLProps, T> = ClassAttributes & E; + + interface SVGProps extends SVGAttributes, ClassAttributes { + } + + interface SVGLineElementAttributes extends SVGProps {} + interface SVGTextElementAttributes extends SVGProps {} + + interface DOMAttributes { + children?: ReactNode | undefined; + dangerouslySetInnerHTML?: { + // Should be InnerHTML['innerHTML']. + // But unfortunately we're mixing renderer-specific type declarations. + __html: string | TrustedHTML; + } | undefined; + + // Clipboard Events + onCopy?: ClipboardEventHandler | undefined; + onCopyCapture?: ClipboardEventHandler | undefined; + onCut?: ClipboardEventHandler | undefined; + onCutCapture?: ClipboardEventHandler | undefined; + onPaste?: ClipboardEventHandler | undefined; + onPasteCapture?: ClipboardEventHandler | undefined; + + // Composition Events + onCompositionEnd?: CompositionEventHandler | undefined; + onCompositionEndCapture?: CompositionEventHandler | undefined; + onCompositionStart?: CompositionEventHandler | undefined; + onCompositionStartCapture?: CompositionEventHandler | undefined; + onCompositionUpdate?: CompositionEventHandler | undefined; + onCompositionUpdateCapture?: CompositionEventHandler | undefined; + + // Focus Events + onFocus?: FocusEventHandler | undefined; + onFocusCapture?: FocusEventHandler | undefined; + onBlur?: FocusEventHandler | undefined; + onBlurCapture?: FocusEventHandler | undefined; + + // Form Events + onChange?: FormEventHandler | undefined; + onChangeCapture?: FormEventHandler | undefined; + onBeforeInput?: InputEventHandler | undefined; + onBeforeInputCapture?: FormEventHandler | undefined; + onInput?: FormEventHandler | undefined; + onInputCapture?: FormEventHandler | undefined; + onReset?: FormEventHandler | undefined; + onResetCapture?: FormEventHandler | undefined; + onSubmit?: FormEventHandler | undefined; + onSubmitCapture?: FormEventHandler | undefined; + onInvalid?: FormEventHandler | undefined; + onInvalidCapture?: FormEventHandler | undefined; + + // Image Events + onLoad?: ReactEventHandler | undefined; + onLoadCapture?: ReactEventHandler | undefined; + onError?: ReactEventHandler | undefined; // also a Media Event + onErrorCapture?: ReactEventHandler | undefined; // also a Media Event + + // Keyboard Events + onKeyDown?: KeyboardEventHandler | undefined; + onKeyDownCapture?: KeyboardEventHandler | undefined; + /** @deprecated Use `onKeyUp` or `onKeyDown` instead */ + onKeyPress?: KeyboardEventHandler | undefined; + /** @deprecated Use `onKeyUpCapture` or `onKeyDownCapture` instead */ + onKeyPressCapture?: KeyboardEventHandler | undefined; + onKeyUp?: KeyboardEventHandler | undefined; + onKeyUpCapture?: KeyboardEventHandler | undefined; + + // Media Events + onAbort?: ReactEventHandler | undefined; + onAbortCapture?: ReactEventHandler | undefined; + onCanPlay?: ReactEventHandler | undefined; + onCanPlayCapture?: ReactEventHandler | undefined; + onCanPlayThrough?: ReactEventHandler | undefined; + onCanPlayThroughCapture?: ReactEventHandler | undefined; + onDurationChange?: ReactEventHandler | undefined; + onDurationChangeCapture?: ReactEventHandler | undefined; + onEmptied?: ReactEventHandler | undefined; + onEmptiedCapture?: ReactEventHandler | undefined; + onEncrypted?: ReactEventHandler | undefined; + onEncryptedCapture?: ReactEventHandler | undefined; + onEnded?: ReactEventHandler | undefined; + onEndedCapture?: ReactEventHandler | undefined; + onLoadedData?: ReactEventHandler | undefined; + onLoadedDataCapture?: ReactEventHandler | undefined; + onLoadedMetadata?: ReactEventHandler | undefined; + onLoadedMetadataCapture?: ReactEventHandler | undefined; + onLoadStart?: ReactEventHandler | undefined; + onLoadStartCapture?: ReactEventHandler | undefined; + onPause?: ReactEventHandler | undefined; + onPauseCapture?: ReactEventHandler | undefined; + onPlay?: ReactEventHandler | undefined; + onPlayCapture?: ReactEventHandler | undefined; + onPlaying?: ReactEventHandler | undefined; + onPlayingCapture?: ReactEventHandler | undefined; + onProgress?: ReactEventHandler | undefined; + onProgressCapture?: ReactEventHandler | undefined; + onRateChange?: ReactEventHandler | undefined; + onRateChangeCapture?: ReactEventHandler | undefined; + onSeeked?: ReactEventHandler | undefined; + onSeekedCapture?: ReactEventHandler | undefined; + onSeeking?: ReactEventHandler | undefined; + onSeekingCapture?: ReactEventHandler | undefined; + onStalled?: ReactEventHandler | undefined; + onStalledCapture?: ReactEventHandler | undefined; + onSuspend?: ReactEventHandler | undefined; + onSuspendCapture?: ReactEventHandler | undefined; + onTimeUpdate?: ReactEventHandler | undefined; + onTimeUpdateCapture?: ReactEventHandler | undefined; + onVolumeChange?: ReactEventHandler | undefined; + onVolumeChangeCapture?: ReactEventHandler | undefined; + onWaiting?: ReactEventHandler | undefined; + onWaitingCapture?: ReactEventHandler | undefined; + + // MouseEvents + onAuxClick?: MouseEventHandler | undefined; + onAuxClickCapture?: MouseEventHandler | undefined; + onClick?: MouseEventHandler | undefined; + onClickCapture?: MouseEventHandler | undefined; + onContextMenu?: MouseEventHandler | undefined; + onContextMenuCapture?: MouseEventHandler | undefined; + onDoubleClick?: MouseEventHandler | undefined; + onDoubleClickCapture?: MouseEventHandler | undefined; + onDrag?: DragEventHandler | undefined; + onDragCapture?: DragEventHandler | undefined; + onDragEnd?: DragEventHandler | undefined; + onDragEndCapture?: DragEventHandler | undefined; + onDragEnter?: DragEventHandler | undefined; + onDragEnterCapture?: DragEventHandler | undefined; + onDragExit?: DragEventHandler | undefined; + onDragExitCapture?: DragEventHandler | undefined; + onDragLeave?: DragEventHandler | undefined; + onDragLeaveCapture?: DragEventHandler | undefined; + onDragOver?: DragEventHandler | undefined; + onDragOverCapture?: DragEventHandler | undefined; + onDragStart?: DragEventHandler | undefined; + onDragStartCapture?: DragEventHandler | undefined; + onDrop?: DragEventHandler | undefined; + onDropCapture?: DragEventHandler | undefined; + onMouseDown?: MouseEventHandler | undefined; + onMouseDownCapture?: MouseEventHandler | undefined; + onMouseEnter?: MouseEventHandler | undefined; + onMouseLeave?: MouseEventHandler | undefined; + onMouseMove?: MouseEventHandler | undefined; + onMouseMoveCapture?: MouseEventHandler | undefined; + onMouseOut?: MouseEventHandler | undefined; + onMouseOutCapture?: MouseEventHandler | undefined; + onMouseOver?: MouseEventHandler | undefined; + onMouseOverCapture?: MouseEventHandler | undefined; + onMouseUp?: MouseEventHandler | undefined; + onMouseUpCapture?: MouseEventHandler | undefined; + + // Selection Events + onSelect?: ReactEventHandler | undefined; + onSelectCapture?: ReactEventHandler | undefined; + + // Touch Events + onTouchCancel?: TouchEventHandler | undefined; + onTouchCancelCapture?: TouchEventHandler | undefined; + onTouchEnd?: TouchEventHandler | undefined; + onTouchEndCapture?: TouchEventHandler | undefined; + onTouchMove?: TouchEventHandler | undefined; + onTouchMoveCapture?: TouchEventHandler | undefined; + onTouchStart?: TouchEventHandler | undefined; + onTouchStartCapture?: TouchEventHandler | undefined; + + // Pointer Events + onPointerDown?: PointerEventHandler | undefined; + onPointerDownCapture?: PointerEventHandler | undefined; + onPointerMove?: PointerEventHandler | undefined; + onPointerMoveCapture?: PointerEventHandler | undefined; + onPointerUp?: PointerEventHandler | undefined; + onPointerUpCapture?: PointerEventHandler | undefined; + onPointerCancel?: PointerEventHandler | undefined; + onPointerCancelCapture?: PointerEventHandler | undefined; + onPointerEnter?: PointerEventHandler | undefined; + onPointerLeave?: PointerEventHandler | undefined; + onPointerOver?: PointerEventHandler | undefined; + onPointerOverCapture?: PointerEventHandler | undefined; + onPointerOut?: PointerEventHandler | undefined; + onPointerOutCapture?: PointerEventHandler | undefined; + onGotPointerCapture?: PointerEventHandler | undefined; + onGotPointerCaptureCapture?: PointerEventHandler | undefined; + onLostPointerCapture?: PointerEventHandler | undefined; + onLostPointerCaptureCapture?: PointerEventHandler | undefined; + + // UI Events + onScroll?: UIEventHandler | undefined; + onScrollCapture?: UIEventHandler | undefined; + + // Wheel Events + onWheel?: WheelEventHandler | undefined; + onWheelCapture?: WheelEventHandler | undefined; + + // Animation Events + onAnimationStart?: AnimationEventHandler | undefined; + onAnimationStartCapture?: AnimationEventHandler | undefined; + onAnimationEnd?: AnimationEventHandler | undefined; + onAnimationEndCapture?: AnimationEventHandler | undefined; + onAnimationIteration?: AnimationEventHandler | undefined; + onAnimationIterationCapture?: AnimationEventHandler | undefined; + + // Transition Events + onTransitionEnd?: TransitionEventHandler | undefined; + onTransitionEndCapture?: TransitionEventHandler | undefined; + } + + export interface CSSProperties extends CSS.Properties { + /** + * The index signature was removed to enable closed typing for style + * using CSSType. You're able to use type assertion or module augmentation + * to add properties or an index signature of your own. + * + * For examples and more information, visit: + * https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors + */ + } + + // All the WAI-ARIA 1.1 attributes from https://www.w3.org/TR/wai-aria-1.1/ + interface AriaAttributes { + /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */ + "aria-activedescendant"?: string | undefined; + /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */ + "aria-atomic"?: Booleanish | undefined; + /** + * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be + * presented if they are made. + */ + "aria-autocomplete"?: "none" | "inline" | "list" | "both" | undefined; + /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */ + /** + * Defines a string value that labels the current element, which is intended to be converted into Braille. + * @see aria-label. + */ + "aria-braillelabel"?: string | undefined; + /** + * Defines a human-readable, author-localized abbreviated description for the role of an element, which is intended to be converted into Braille. + * @see aria-roledescription. + */ + "aria-brailleroledescription"?: string | undefined; + "aria-busy"?: Booleanish | undefined; + /** + * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. + * @see aria-pressed @see aria-selected. + */ + "aria-checked"?: boolean | "false" | "mixed" | "true" | undefined; + /** + * Defines the total number of columns in a table, grid, or treegrid. + * @see aria-colindex. + */ + "aria-colcount"?: number | undefined; + /** + * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. + * @see aria-colcount @see aria-colspan. + */ + "aria-colindex"?: number | undefined; + /** + * Defines a human readable text alternative of aria-colindex. + * @see aria-rowindextext. + */ + "aria-colindextext"?: string | undefined; + /** + * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-colindex @see aria-rowspan. + */ + "aria-colspan"?: number | undefined; + /** + * Identifies the element (or elements) whose contents or presence are controlled by the current element. + * @see aria-owns. + */ + "aria-controls"?: string | undefined; + /** Indicates the element that represents the current item within a container or set of related elements. */ + "aria-current"?: boolean | "false" | "true" | "page" | "step" | "location" | "date" | "time" | undefined; + /** + * Identifies the element (or elements) that describes the object. + * @see aria-labelledby + */ + "aria-describedby"?: string | undefined; + /** + * Defines a string value that describes or annotates the current element. + * @see related aria-describedby. + */ + "aria-description"?: string | undefined; + /** + * Identifies the element that provides a detailed, extended description for the object. + * @see aria-describedby. + */ + "aria-details"?: string | undefined; + /** + * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. + * @see aria-hidden @see aria-readonly. + */ + "aria-disabled"?: Booleanish | undefined; + /** + * Indicates what functions can be performed when a dragged object is released on the drop target. + * @deprecated in ARIA 1.1 + */ + "aria-dropeffect"?: "none" | "copy" | "execute" | "link" | "move" | "popup" | undefined; + /** + * Identifies the element that provides an error message for the object. + * @see aria-invalid @see aria-describedby. + */ + "aria-errormessage"?: string | undefined; + /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */ + "aria-expanded"?: Booleanish | undefined; + /** + * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, + * allows assistive technology to override the general default of reading in document source order. + */ + "aria-flowto"?: string | undefined; + /** + * Indicates an element's "grabbed" state in a drag-and-drop operation. + * @deprecated in ARIA 1.1 + */ + "aria-grabbed"?: Booleanish | undefined; + /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */ + "aria-haspopup"?: boolean | "false" | "true" | "menu" | "listbox" | "tree" | "grid" | "dialog" | undefined; + /** + * Indicates whether the element is exposed to an accessibility API. + * @see aria-disabled. + */ + "aria-hidden"?: Booleanish | undefined; + /** + * Indicates the entered value does not conform to the format expected by the application. + * @see aria-errormessage. + */ + "aria-invalid"?: boolean | "false" | "true" | "grammar" | "spelling" | undefined; + /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */ + "aria-keyshortcuts"?: string | undefined; + /** + * Defines a string value that labels the current element. + * @see aria-labelledby. + */ + "aria-label"?: string | undefined; + /** + * Identifies the element (or elements) that labels the current element. + * @see aria-describedby. + */ + "aria-labelledby"?: string | undefined; + /** Defines the hierarchical level of an element within a structure. */ + "aria-level"?: number | undefined; + /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */ + "aria-live"?: "off" | "assertive" | "polite" | undefined; + /** Indicates whether an element is modal when displayed. */ + "aria-modal"?: Booleanish | undefined; + /** Indicates whether a text box accepts multiple lines of input or only a single line. */ + "aria-multiline"?: Booleanish | undefined; + /** Indicates that the user may select more than one item from the current selectable descendants. */ + "aria-multiselectable"?: Booleanish | undefined; + /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ + "aria-orientation"?: "horizontal" | "vertical" | undefined; + /** + * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship + * between DOM elements where the DOM hierarchy cannot be used to represent the relationship. + * @see aria-controls. + */ + "aria-owns"?: string | undefined; + /** + * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. + * A hint could be a sample value or a brief description of the expected format. + */ + "aria-placeholder"?: string | undefined; + /** + * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-setsize. + */ + "aria-posinset"?: number | undefined; + /** + * Indicates the current "pressed" state of toggle buttons. + * @see aria-checked @see aria-selected. + */ + "aria-pressed"?: boolean | "false" | "mixed" | "true" | undefined; + /** + * Indicates that the element is not editable, but is otherwise operable. + * @see aria-disabled. + */ + "aria-readonly"?: Booleanish | undefined; + /** + * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. + * @see aria-atomic. + */ + "aria-relevant"?: + | "additions" + | "additions removals" + | "additions text" + | "all" + | "removals" + | "removals additions" + | "removals text" + | "text" + | "text additions" + | "text removals" + | undefined; + /** Indicates that user input is required on the element before a form may be submitted. */ + "aria-required"?: Booleanish | undefined; + /** Defines a human-readable, author-localized description for the role of an element. */ + "aria-roledescription"?: string | undefined; + /** + * Defines the total number of rows in a table, grid, or treegrid. + * @see aria-rowindex. + */ + "aria-rowcount"?: number | undefined; + /** + * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. + * @see aria-rowcount @see aria-rowspan. + */ + "aria-rowindex"?: number | undefined; + /** + * Defines a human readable text alternative of aria-rowindex. + * @see aria-colindextext. + */ + "aria-rowindextext"?: string | undefined; + /** + * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. + * @see aria-rowindex @see aria-colspan. + */ + "aria-rowspan"?: number | undefined; + /** + * Indicates the current "selected" state of various widgets. + * @see aria-checked @see aria-pressed. + */ + "aria-selected"?: Booleanish | undefined; + /** + * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. + * @see aria-posinset. + */ + "aria-setsize"?: number | undefined; + /** Indicates if items in a table or grid are sorted in ascending or descending order. */ + "aria-sort"?: "none" | "ascending" | "descending" | "other" | undefined; + /** Defines the maximum allowed value for a range widget. */ + "aria-valuemax"?: number | undefined; + /** Defines the minimum allowed value for a range widget. */ + "aria-valuemin"?: number | undefined; + /** + * Defines the current value for a range widget. + * @see aria-valuetext. + */ + "aria-valuenow"?: number | undefined; + /** Defines the human readable text alternative of aria-valuenow for a range widget. */ + "aria-valuetext"?: string | undefined; + } + + // All the WAI-ARIA 1.1 role attribute values from https://www.w3.org/TR/wai-aria-1.1/#role_definitions + type AriaRole = + | "alert" + | "alertdialog" + | "application" + | "article" + | "banner" + | "button" + | "cell" + | "checkbox" + | "columnheader" + | "combobox" + | "complementary" + | "contentinfo" + | "definition" + | "dialog" + | "directory" + | "document" + | "feed" + | "figure" + | "form" + | "grid" + | "gridcell" + | "group" + | "heading" + | "img" + | "link" + | "list" + | "listbox" + | "listitem" + | "log" + | "main" + | "marquee" + | "math" + | "menu" + | "menubar" + | "menuitem" + | "menuitemcheckbox" + | "menuitemradio" + | "navigation" + | "none" + | "note" + | "option" + | "presentation" + | "progressbar" + | "radio" + | "radiogroup" + | "region" + | "row" + | "rowgroup" + | "rowheader" + | "scrollbar" + | "search" + | "searchbox" + | "separator" + | "slider" + | "spinbutton" + | "status" + | "switch" + | "tab" + | "table" + | "tablist" + | "tabpanel" + | "term" + | "textbox" + | "timer" + | "toolbar" + | "tooltip" + | "tree" + | "treegrid" + | "treeitem" + | (string & {}); + + interface HTMLAttributes extends AriaAttributes, DOMAttributes { + // React-specific Attributes + defaultChecked?: boolean | undefined; + defaultValue?: string | number | readonly string[] | undefined; + suppressContentEditableWarning?: boolean | undefined; + suppressHydrationWarning?: boolean | undefined; + + // Standard HTML Attributes + accessKey?: string | undefined; + autoCapitalize?: "off" | "none" | "on" | "sentences" | "words" | "characters" | undefined | (string & {}); + autoFocus?: boolean | undefined; + className?: string | undefined; + contentEditable?: Booleanish | "inherit" | "plaintext-only" | undefined; + contextMenu?: string | undefined; + dir?: string | undefined; + draggable?: Booleanish | undefined; + enterKeyHint?: "enter" | "done" | "go" | "next" | "previous" | "search" | "send" | undefined; + hidden?: boolean | undefined; + id?: string | undefined; + lang?: string | undefined; + nonce?: string | undefined; + slot?: string | undefined; + spellCheck?: Booleanish | undefined; + style?: CSSProperties | undefined; + tabIndex?: number | undefined; + title?: string | undefined; + translate?: "yes" | "no" | undefined; + + // Unknown + radioGroup?: string | undefined; // , + + // WAI-ARIA + role?: AriaRole | undefined; + + // RDFa Attributes + about?: string | undefined; + content?: string | undefined; + datatype?: string | undefined; + inlist?: any; + prefix?: string | undefined; + property?: string | undefined; + rel?: string | undefined; + resource?: string | undefined; + rev?: string | undefined; + typeof?: string | undefined; + vocab?: string | undefined; + + // Non-standard Attributes + autoCorrect?: string | undefined; + autoSave?: string | undefined; + color?: string | undefined; + itemProp?: string | undefined; + itemScope?: boolean | undefined; + itemType?: string | undefined; + itemID?: string | undefined; + itemRef?: string | undefined; + results?: number | undefined; + security?: string | undefined; + unselectable?: "on" | "off" | undefined; + + // Living Standard + /** + * Hints at the type of data that might be entered by the user while editing the element or its contents + * @see {@link https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute} + */ + inputMode?: "none" | "text" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined; + /** + * Specify that a standard HTML element should behave like a defined custom built-in element + * @see {@link https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is} + */ + is?: string | undefined; + } + + /** + * For internal usage only. + * Different release channels declare additional types of ReactNode this particular release channel accepts. + * App or library types should never augment this interface. + */ + interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS {} + + interface AllHTMLAttributes extends HTMLAttributes { + // Standard HTML Attributes + accept?: string | undefined; + acceptCharset?: string | undefined; + action?: + | string + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + allowFullScreen?: boolean | undefined; + allowTransparency?: boolean | undefined; + alt?: string | undefined; + as?: string | undefined; + async?: boolean | undefined; + autoComplete?: string | undefined; + autoPlay?: boolean | undefined; + capture?: boolean | "user" | "environment" | undefined; + cellPadding?: number | string | undefined; + cellSpacing?: number | string | undefined; + charSet?: string | undefined; + challenge?: string | undefined; + checked?: boolean | undefined; + cite?: string | undefined; + classID?: string | undefined; + cols?: number | undefined; + colSpan?: number | undefined; + controls?: boolean | undefined; + coords?: string | undefined; + crossOrigin?: CrossOrigin; + data?: string | undefined; + dateTime?: string | undefined; + default?: boolean | undefined; + defer?: boolean | undefined; + disabled?: boolean | undefined; + download?: any; + encType?: string | undefined; + form?: string | undefined; + formAction?: + | string + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + frameBorder?: number | string | undefined; + headers?: string | undefined; + height?: number | string | undefined; + high?: number | undefined; + href?: string | undefined; + hrefLang?: string | undefined; + htmlFor?: string | undefined; + httpEquiv?: string | undefined; + integrity?: string | undefined; + keyParams?: string | undefined; + keyType?: string | undefined; + kind?: string | undefined; + label?: string | undefined; + list?: string | undefined; + loop?: boolean | undefined; + low?: number | undefined; + manifest?: string | undefined; + marginHeight?: number | undefined; + marginWidth?: number | undefined; + max?: number | string | undefined; + maxLength?: number | undefined; + media?: string | undefined; + mediaGroup?: string | undefined; + method?: string | undefined; + min?: number | string | undefined; + minLength?: number | undefined; + multiple?: boolean | undefined; + muted?: boolean | undefined; + name?: string | undefined; + noValidate?: boolean | undefined; + open?: boolean | undefined; + optimum?: number | undefined; + pattern?: string | undefined; + placeholder?: string | undefined; + playsInline?: boolean | undefined; + poster?: string | undefined; + preload?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + reversed?: boolean | undefined; + rows?: number | undefined; + rowSpan?: number | undefined; + sandbox?: string | undefined; + scope?: string | undefined; + scoped?: boolean | undefined; + scrolling?: string | undefined; + seamless?: boolean | undefined; + selected?: boolean | undefined; + shape?: string | undefined; + size?: number | undefined; + sizes?: string | undefined; + span?: number | undefined; + src?: string | undefined; + srcDoc?: string | undefined; + srcLang?: string | undefined; + srcSet?: string | undefined; + start?: number | undefined; + step?: number | string | undefined; + summary?: string | undefined; + target?: string | undefined; + type?: string | undefined; + useMap?: string | undefined; + value?: string | readonly string[] | number | undefined; + width?: number | string | undefined; + wmode?: string | undefined; + wrap?: string | undefined; + } + + type HTMLAttributeReferrerPolicy = + | "" + | "no-referrer" + | "no-referrer-when-downgrade" + | "origin" + | "origin-when-cross-origin" + | "same-origin" + | "strict-origin" + | "strict-origin-when-cross-origin" + | "unsafe-url"; + + type HTMLAttributeAnchorTarget = + | "_self" + | "_blank" + | "_parent" + | "_top" + | (string & {}); + + interface AnchorHTMLAttributes extends HTMLAttributes { + download?: any; + href?: string | undefined; + hrefLang?: string | undefined; + media?: string | undefined; + ping?: string | undefined; + target?: HTMLAttributeAnchorTarget | undefined; + type?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + } + + interface AudioHTMLAttributes extends MediaHTMLAttributes {} + + interface AreaHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + coords?: string | undefined; + download?: any; + href?: string | undefined; + hrefLang?: string | undefined; + media?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + shape?: string | undefined; + target?: string | undefined; + } + + interface BaseHTMLAttributes extends HTMLAttributes { + href?: string | undefined; + target?: string | undefined; + } + + interface BlockquoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + + interface ButtonHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + formAction?: + | string + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ] + | undefined; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + name?: string | undefined; + type?: "submit" | "reset" | "button" | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface CanvasHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + width?: number | string | undefined; + } + + interface ColHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + width?: number | string | undefined; + } + + interface ColgroupHTMLAttributes extends HTMLAttributes { + span?: number | undefined; + } + + interface DataHTMLAttributes extends HTMLAttributes { + value?: string | readonly string[] | number | undefined; + } + + interface DetailsHTMLAttributes extends HTMLAttributes { + open?: boolean | undefined; + onToggle?: ReactEventHandler | undefined; + name?: string | undefined; + } + + interface DelHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + dateTime?: string | undefined; + } + + interface DialogHTMLAttributes extends HTMLAttributes { + onCancel?: ReactEventHandler | undefined; + onClose?: ReactEventHandler | undefined; + open?: boolean | undefined; + } + + interface EmbedHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + src?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + } + + interface FieldsetHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + form?: string | undefined; + name?: string | undefined; + } + + interface FormHTMLAttributes extends HTMLAttributes { + acceptCharset?: string | undefined; + action?: + | string + | undefined + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ]; + autoComplete?: string | undefined; + encType?: string | undefined; + method?: string | undefined; + name?: string | undefined; + noValidate?: boolean | undefined; + target?: string | undefined; + } + + interface HtmlHTMLAttributes extends HTMLAttributes { + manifest?: string | undefined; + } + + interface IframeHTMLAttributes extends HTMLAttributes { + allow?: string | undefined; + allowFullScreen?: boolean | undefined; + allowTransparency?: boolean | undefined; + /** @deprecated */ + frameBorder?: number | string | undefined; + height?: number | string | undefined; + loading?: "eager" | "lazy" | undefined; + /** @deprecated */ + marginHeight?: number | undefined; + /** @deprecated */ + marginWidth?: number | undefined; + name?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sandbox?: string | undefined; + /** @deprecated */ + scrolling?: string | undefined; + seamless?: boolean | undefined; + src?: string | undefined; + srcDoc?: string | undefined; + width?: number | string | undefined; + } + + interface ImgHTMLAttributes extends HTMLAttributes { + alt?: string | undefined; + crossOrigin?: CrossOrigin; + decoding?: "async" | "auto" | "sync" | undefined; + fetchPriority?: "high" | "low" | "auto"; + height?: number | string | undefined; + loading?: "eager" | "lazy" | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + src?: string | undefined; + srcSet?: string | undefined; + useMap?: string | undefined; + width?: number | string | undefined; + } + + interface InsHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + dateTime?: string | undefined; + } + + type HTMLInputTypeAttribute = + | "button" + | "checkbox" + | "color" + | "date" + | "datetime-local" + | "email" + | "file" + | "hidden" + | "image" + | "month" + | "number" + | "password" + | "radio" + | "range" + | "reset" + | "search" + | "submit" + | "tel" + | "text" + | "time" + | "url" + | "week" + | (string & {}); + + type AutoFillAddressKind = "billing" | "shipping"; + type AutoFillBase = "" | "off" | "on"; + type AutoFillContactField = + | "email" + | "tel" + | "tel-area-code" + | "tel-country-code" + | "tel-extension" + | "tel-local" + | "tel-local-prefix" + | "tel-local-suffix" + | "tel-national"; + type AutoFillContactKind = "home" | "mobile" | "work"; + type AutoFillCredentialField = "webauthn"; + type AutoFillNormalField = + | "additional-name" + | "address-level1" + | "address-level2" + | "address-level3" + | "address-level4" + | "address-line1" + | "address-line2" + | "address-line3" + | "bday-day" + | "bday-month" + | "bday-year" + | "cc-csc" + | "cc-exp" + | "cc-exp-month" + | "cc-exp-year" + | "cc-family-name" + | "cc-given-name" + | "cc-name" + | "cc-number" + | "cc-type" + | "country" + | "country-name" + | "current-password" + | "family-name" + | "given-name" + | "honorific-prefix" + | "honorific-suffix" + | "name" + | "new-password" + | "one-time-code" + | "organization" + | "postal-code" + | "street-address" + | "transaction-amount" + | "transaction-currency" + | "username"; + type OptionalPrefixToken = `${T} ` | ""; + type OptionalPostfixToken = ` ${T}` | ""; + type AutoFillField = AutoFillNormalField | `${OptionalPrefixToken}${AutoFillContactField}`; + type AutoFillSection = `section-${string}`; + type AutoFill = + | AutoFillBase + | `${OptionalPrefixToken}${OptionalPrefixToken< + AutoFillAddressKind + >}${AutoFillField}${OptionalPostfixToken}`; + type HTMLInputAutoCompleteAttribute = AutoFill | (string & {}); + + interface InputHTMLAttributes extends HTMLAttributes { + accept?: string | undefined; + alt?: string | undefined; + autoComplete?: HTMLInputAutoCompleteAttribute | undefined; + capture?: boolean | "user" | "environment" | undefined; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute + checked?: boolean | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + formAction?: + | string + | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[ + keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS + ] + | undefined; + formEncType?: string | undefined; + formMethod?: string | undefined; + formNoValidate?: boolean | undefined; + formTarget?: string | undefined; + height?: number | string | undefined; + list?: string | undefined; + max?: number | string | undefined; + maxLength?: number | undefined; + min?: number | string | undefined; + minLength?: number | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + pattern?: string | undefined; + placeholder?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + size?: number | undefined; + src?: string | undefined; + step?: number | string | undefined; + type?: HTMLInputTypeAttribute | undefined; + value?: string | readonly string[] | number | undefined; + width?: number | string | undefined; + + onChange?: ChangeEventHandler | undefined; + } + + interface KeygenHTMLAttributes extends HTMLAttributes { + challenge?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + keyType?: string | undefined; + keyParams?: string | undefined; + name?: string | undefined; + } + + interface LabelHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + htmlFor?: string | undefined; + } + + interface LiHTMLAttributes extends HTMLAttributes { + value?: string | readonly string[] | number | undefined; + } + + interface LinkHTMLAttributes extends HTMLAttributes { + as?: string | undefined; + crossOrigin?: CrossOrigin; + fetchPriority?: "high" | "low" | "auto"; + href?: string | undefined; + hrefLang?: string | undefined; + integrity?: string | undefined; + media?: string | undefined; + imageSrcSet?: string | undefined; + imageSizes?: string | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + sizes?: string | undefined; + type?: string | undefined; + charSet?: string | undefined; + } + + interface MapHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + + interface MenuHTMLAttributes extends HTMLAttributes { + type?: string | undefined; + } + + interface MediaHTMLAttributes extends HTMLAttributes { + autoPlay?: boolean | undefined; + controls?: boolean | undefined; + controlsList?: string | undefined; + crossOrigin?: CrossOrigin; + loop?: boolean | undefined; + mediaGroup?: string | undefined; + muted?: boolean | undefined; + playsInline?: boolean | undefined; + preload?: string | undefined; + src?: string | undefined; + } + + interface MetaHTMLAttributes extends HTMLAttributes { + charSet?: string | undefined; + content?: string | undefined; + httpEquiv?: string | undefined; + media?: string | undefined; + name?: string | undefined; + } + + interface MeterHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + high?: number | undefined; + low?: number | undefined; + max?: number | string | undefined; + min?: number | string | undefined; + optimum?: number | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface QuoteHTMLAttributes extends HTMLAttributes { + cite?: string | undefined; + } + + interface ObjectHTMLAttributes extends HTMLAttributes { + classID?: string | undefined; + data?: string | undefined; + form?: string | undefined; + height?: number | string | undefined; + name?: string | undefined; + type?: string | undefined; + useMap?: string | undefined; + width?: number | string | undefined; + wmode?: string | undefined; + } + + interface OlHTMLAttributes extends HTMLAttributes { + reversed?: boolean | undefined; + start?: number | undefined; + type?: "1" | "a" | "A" | "i" | "I" | undefined; + } + + interface OptgroupHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + } + + interface OptionHTMLAttributes extends HTMLAttributes { + disabled?: boolean | undefined; + label?: string | undefined; + selected?: boolean | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface OutputHTMLAttributes extends HTMLAttributes { + form?: string | undefined; + htmlFor?: string | undefined; + name?: string | undefined; + } + + interface ParamHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface ProgressHTMLAttributes extends HTMLAttributes { + max?: number | string | undefined; + value?: string | readonly string[] | number | undefined; + } + + interface SlotHTMLAttributes extends HTMLAttributes { + name?: string | undefined; + } + + interface ScriptHTMLAttributes extends HTMLAttributes { + async?: boolean | undefined; + /** @deprecated */ + charSet?: string | undefined; + crossOrigin?: CrossOrigin; + defer?: boolean | undefined; + integrity?: string | undefined; + noModule?: boolean | undefined; + referrerPolicy?: HTMLAttributeReferrerPolicy | undefined; + src?: string | undefined; + type?: string | undefined; + } + + interface SelectHTMLAttributes extends HTMLAttributes { + autoComplete?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + multiple?: boolean | undefined; + name?: string | undefined; + required?: boolean | undefined; + size?: number | undefined; + value?: string | readonly string[] | number | undefined; + onChange?: ChangeEventHandler | undefined; + } + + interface SourceHTMLAttributes extends HTMLAttributes { + height?: number | string | undefined; + media?: string | undefined; + sizes?: string | undefined; + src?: string | undefined; + srcSet?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + } + + interface StyleHTMLAttributes extends HTMLAttributes { + media?: string | undefined; + scoped?: boolean | undefined; + type?: string | undefined; + } + + interface TableHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | undefined; + bgcolor?: string | undefined; + border?: number | undefined; + cellPadding?: number | string | undefined; + cellSpacing?: number | string | undefined; + frame?: boolean | undefined; + rules?: "none" | "groups" | "rows" | "columns" | "all" | undefined; + summary?: string | undefined; + width?: number | string | undefined; + } + + interface TextareaHTMLAttributes extends HTMLAttributes { + autoComplete?: string | undefined; + cols?: number | undefined; + dirName?: string | undefined; + disabled?: boolean | undefined; + form?: string | undefined; + maxLength?: number | undefined; + minLength?: number | undefined; + name?: string | undefined; + placeholder?: string | undefined; + readOnly?: boolean | undefined; + required?: boolean | undefined; + rows?: number | undefined; + value?: string | readonly string[] | number | undefined; + wrap?: string | undefined; + + onChange?: ChangeEventHandler | undefined; + } + + interface TdHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | "justify" | "char" | undefined; + colSpan?: number | undefined; + headers?: string | undefined; + rowSpan?: number | undefined; + scope?: string | undefined; + abbr?: string | undefined; + height?: number | string | undefined; + width?: number | string | undefined; + valign?: "top" | "middle" | "bottom" | "baseline" | undefined; + } + + interface ThHTMLAttributes extends HTMLAttributes { + align?: "left" | "center" | "right" | "justify" | "char" | undefined; + colSpan?: number | undefined; + headers?: string | undefined; + rowSpan?: number | undefined; + scope?: string | undefined; + abbr?: string | undefined; + } + + interface TimeHTMLAttributes extends HTMLAttributes { + dateTime?: string | undefined; + } + + interface TrackHTMLAttributes extends HTMLAttributes { + default?: boolean | undefined; + kind?: string | undefined; + label?: string | undefined; + src?: string | undefined; + srcLang?: string | undefined; + } + + interface VideoHTMLAttributes extends MediaHTMLAttributes { + height?: number | string | undefined; + playsInline?: boolean | undefined; + poster?: string | undefined; + width?: number | string | undefined; + disablePictureInPicture?: boolean | undefined; + disableRemotePlayback?: boolean | undefined; + + onResize?: ReactEventHandler | undefined; + onResizeCapture?: ReactEventHandler | undefined; + } + + // this list is "complete" in that it contains every SVG attribute + // that React supports, but the types can be improved. + // Full list here: https://facebook.github.io/react/docs/dom-elements.html + // + // The three broad type categories are (in order of restrictiveness): + // - "number | string" + // - "string" + // - union of string literals + interface SVGAttributes extends AriaAttributes, DOMAttributes { + // React-specific Attributes + suppressHydrationWarning?: boolean | undefined; + + // Attributes which also defined in HTMLAttributes + // See comment in SVGDOMPropertyConfig.js + className?: string | undefined; + color?: string | undefined; + height?: number | string | undefined; + id?: string | undefined; + lang?: string | undefined; + max?: number | string | undefined; + media?: string | undefined; + method?: string | undefined; + min?: number | string | undefined; + name?: string | undefined; + style?: CSSProperties | undefined; + target?: string | undefined; + type?: string | undefined; + width?: number | string | undefined; + + // Other HTML properties supported by SVG elements in browsers + role?: AriaRole | undefined; + tabIndex?: number | undefined; + crossOrigin?: CrossOrigin; + + // SVG Specific attributes + accentHeight?: number | string | undefined; + accumulate?: "none" | "sum" | undefined; + additive?: "replace" | "sum" | undefined; + alignmentBaseline?: + | "auto" + | "baseline" + | "before-edge" + | "text-before-edge" + | "middle" + | "central" + | "after-edge" + | "text-after-edge" + | "ideographic" + | "alphabetic" + | "hanging" + | "mathematical" + | "inherit" + | undefined; + allowReorder?: "no" | "yes" | undefined; + alphabetic?: number | string | undefined; + amplitude?: number | string | undefined; + arabicForm?: "initial" | "medial" | "terminal" | "isolated" | undefined; + ascent?: number | string | undefined; + attributeName?: string | undefined; + attributeType?: string | undefined; + autoReverse?: Booleanish | undefined; + azimuth?: number | string | undefined; + baseFrequency?: number | string | undefined; + baselineShift?: number | string | undefined; + baseProfile?: number | string | undefined; + bbox?: number | string | undefined; + begin?: number | string | undefined; + bias?: number | string | undefined; + by?: number | string | undefined; + calcMode?: number | string | undefined; + capHeight?: number | string | undefined; + clip?: number | string | undefined; + clipPath?: string | undefined; + clipPathUnits?: number | string | undefined; + clipRule?: number | string | undefined; + colorInterpolation?: number | string | undefined; + colorInterpolationFilters?: "auto" | "sRGB" | "linearRGB" | "inherit" | undefined; + colorProfile?: number | string | undefined; + colorRendering?: number | string | undefined; + contentScriptType?: number | string | undefined; + contentStyleType?: number | string | undefined; + cursor?: number | string | undefined; + cx?: number | string | undefined; + cy?: number | string | undefined; + d?: string | undefined; + decelerate?: number | string | undefined; + descent?: number | string | undefined; + diffuseConstant?: number | string | undefined; + direction?: number | string | undefined; + display?: number | string | undefined; + divisor?: number | string | undefined; + dominantBaseline?: number | string | undefined; + dur?: number | string | undefined; + dx?: number | string | undefined; + dy?: number | string | undefined; + edgeMode?: number | string | undefined; + elevation?: number | string | undefined; + enableBackground?: number | string | undefined; + end?: number | string | undefined; + exponent?: number | string | undefined; + externalResourcesRequired?: Booleanish | undefined; + fill?: string | undefined; + fillOpacity?: number | string | undefined; + fillRule?: "nonzero" | "evenodd" | "inherit" | undefined; + filter?: string | undefined; + filterRes?: number | string | undefined; + filterUnits?: number | string | undefined; + floodColor?: number | string | undefined; + floodOpacity?: number | string | undefined; + focusable?: Booleanish | "auto" | undefined; + fontFamily?: string | undefined; + fontSize?: number | string | undefined; + fontSizeAdjust?: number | string | undefined; + fontStretch?: number | string | undefined; + fontStyle?: number | string | undefined; + fontVariant?: number | string | undefined; + fontWeight?: number | string | undefined; + format?: number | string | undefined; + fr?: number | string | undefined; + from?: number | string | undefined; + fx?: number | string | undefined; + fy?: number | string | undefined; + g1?: number | string | undefined; + g2?: number | string | undefined; + glyphName?: number | string | undefined; + glyphOrientationHorizontal?: number | string | undefined; + glyphOrientationVertical?: number | string | undefined; + glyphRef?: number | string | undefined; + gradientTransform?: string | undefined; + gradientUnits?: string | undefined; + hanging?: number | string | undefined; + horizAdvX?: number | string | undefined; + horizOriginX?: number | string | undefined; + href?: string | undefined; + ideographic?: number | string | undefined; + imageRendering?: number | string | undefined; + in2?: number | string | undefined; + in?: string | undefined; + intercept?: number | string | undefined; + k1?: number | string | undefined; + k2?: number | string | undefined; + k3?: number | string | undefined; + k4?: number | string | undefined; + k?: number | string | undefined; + kernelMatrix?: number | string | undefined; + kernelUnitLength?: number | string | undefined; + kerning?: number | string | undefined; + keyPoints?: number | string | undefined; + keySplines?: number | string | undefined; + keyTimes?: number | string | undefined; + lengthAdjust?: number | string | undefined; + letterSpacing?: number | string | undefined; + lightingColor?: number | string | undefined; + limitingConeAngle?: number | string | undefined; + local?: number | string | undefined; + markerEnd?: string | undefined; + markerHeight?: number | string | undefined; + markerMid?: string | undefined; + markerStart?: string | undefined; + markerUnits?: number | string | undefined; + markerWidth?: number | string | undefined; + mask?: string | undefined; + maskContentUnits?: number | string | undefined; + maskUnits?: number | string | undefined; + mathematical?: number | string | undefined; + mode?: number | string | undefined; + numOctaves?: number | string | undefined; + offset?: number | string | undefined; + opacity?: number | string | undefined; + operator?: number | string | undefined; + order?: number | string | undefined; + orient?: number | string | undefined; + orientation?: number | string | undefined; + origin?: number | string | undefined; + overflow?: number | string | undefined; + overlinePosition?: number | string | undefined; + overlineThickness?: number | string | undefined; + paintOrder?: number | string | undefined; + panose1?: number | string | undefined; + path?: string | undefined; + pathLength?: number | string | undefined; + patternContentUnits?: string | undefined; + patternTransform?: number | string | undefined; + patternUnits?: string | undefined; + pointerEvents?: number | string | undefined; + points?: string | undefined; + pointsAtX?: number | string | undefined; + pointsAtY?: number | string | undefined; + pointsAtZ?: number | string | undefined; + preserveAlpha?: Booleanish | undefined; + preserveAspectRatio?: string | undefined; + primitiveUnits?: number | string | undefined; + r?: number | string | undefined; + radius?: number | string | undefined; + refX?: number | string | undefined; + refY?: number | string | undefined; + renderingIntent?: number | string | undefined; + repeatCount?: number | string | undefined; + repeatDur?: number | string | undefined; + requiredExtensions?: number | string | undefined; + requiredFeatures?: number | string | undefined; + restart?: number | string | undefined; + result?: string | undefined; + rotate?: number | string | undefined; + rx?: number | string | undefined; + ry?: number | string | undefined; + scale?: number | string | undefined; + seed?: number | string | undefined; + shapeRendering?: number | string | undefined; + slope?: number | string | undefined; + spacing?: number | string | undefined; + specularConstant?: number | string | undefined; + specularExponent?: number | string | undefined; + speed?: number | string | undefined; + spreadMethod?: string | undefined; + startOffset?: number | string | undefined; + stdDeviation?: number | string | undefined; + stemh?: number | string | undefined; + stemv?: number | string | undefined; + stitchTiles?: number | string | undefined; + stopColor?: string | undefined; + stopOpacity?: number | string | undefined; + strikethroughPosition?: number | string | undefined; + strikethroughThickness?: number | string | undefined; + string?: number | string | undefined; + stroke?: string | undefined; + strokeDasharray?: string | number | undefined; + strokeDashoffset?: string | number | undefined; + strokeLinecap?: "butt" | "round" | "square" | "inherit" | undefined; + strokeLinejoin?: "miter" | "round" | "bevel" | "inherit" | undefined; + strokeMiterlimit?: number | string | undefined; + strokeOpacity?: number | string | undefined; + strokeWidth?: number | string | undefined; + surfaceScale?: number | string | undefined; + systemLanguage?: number | string | undefined; + tableValues?: number | string | undefined; + targetX?: number | string | undefined; + targetY?: number | string | undefined; + textAnchor?: string | undefined; + textDecoration?: number | string | undefined; + textLength?: number | string | undefined; + textRendering?: number | string | undefined; + to?: number | string | undefined; + transform?: string | undefined; + u1?: number | string | undefined; + u2?: number | string | undefined; + underlinePosition?: number | string | undefined; + underlineThickness?: number | string | undefined; + unicode?: number | string | undefined; + unicodeBidi?: number | string | undefined; + unicodeRange?: number | string | undefined; + unitsPerEm?: number | string | undefined; + vAlphabetic?: number | string | undefined; + values?: string | undefined; + vectorEffect?: number | string | undefined; + version?: string | undefined; + vertAdvY?: number | string | undefined; + vertOriginX?: number | string | undefined; + vertOriginY?: number | string | undefined; + vHanging?: number | string | undefined; + vIdeographic?: number | string | undefined; + viewBox?: string | undefined; + viewTarget?: number | string | undefined; + visibility?: number | string | undefined; + vMathematical?: number | string | undefined; + widths?: number | string | undefined; + wordSpacing?: number | string | undefined; + writingMode?: number | string | undefined; + x1?: number | string | undefined; + x2?: number | string | undefined; + x?: number | string | undefined; + xChannelSelector?: string | undefined; + xHeight?: number | string | undefined; + xlinkActuate?: string | undefined; + xlinkArcrole?: string | undefined; + xlinkHref?: string | undefined; + xlinkRole?: string | undefined; + xlinkShow?: string | undefined; + xlinkTitle?: string | undefined; + xlinkType?: string | undefined; + xmlBase?: string | undefined; + xmlLang?: string | undefined; + xmlns?: string | undefined; + xmlnsXlink?: string | undefined; + xmlSpace?: string | undefined; + y1?: number | string | undefined; + y2?: number | string | undefined; + y?: number | string | undefined; + yChannelSelector?: string | undefined; + z?: number | string | undefined; + zoomAndPan?: string | undefined; + } + + interface WebViewHTMLAttributes extends HTMLAttributes { + allowFullScreen?: boolean | undefined; + allowpopups?: boolean | undefined; + autosize?: boolean | undefined; + blinkfeatures?: string | undefined; + disableblinkfeatures?: string | undefined; + disableguestresize?: boolean | undefined; + disablewebsecurity?: boolean | undefined; + guestinstance?: string | undefined; + httpreferrer?: string | undefined; + nodeintegration?: boolean | undefined; + partition?: string | undefined; + plugins?: boolean | undefined; + preload?: string | undefined; + src?: string | undefined; + useragent?: string | undefined; + webpreferences?: string | undefined; + } + + // + // React.DOM + // ---------------------------------------------------------------------- + + interface ReactHTML { + a: DetailedHTMLFactory, HTMLAnchorElement>; + abbr: DetailedHTMLFactory, HTMLElement>; + address: DetailedHTMLFactory, HTMLElement>; + area: DetailedHTMLFactory, HTMLAreaElement>; + article: DetailedHTMLFactory, HTMLElement>; + aside: DetailedHTMLFactory, HTMLElement>; + audio: DetailedHTMLFactory, HTMLAudioElement>; + b: DetailedHTMLFactory, HTMLElement>; + base: DetailedHTMLFactory, HTMLBaseElement>; + bdi: DetailedHTMLFactory, HTMLElement>; + bdo: DetailedHTMLFactory, HTMLElement>; + big: DetailedHTMLFactory, HTMLElement>; + blockquote: DetailedHTMLFactory, HTMLQuoteElement>; + body: DetailedHTMLFactory, HTMLBodyElement>; + br: DetailedHTMLFactory, HTMLBRElement>; + button: DetailedHTMLFactory, HTMLButtonElement>; + canvas: DetailedHTMLFactory, HTMLCanvasElement>; + caption: DetailedHTMLFactory, HTMLElement>; + center: DetailedHTMLFactory, HTMLElement>; + cite: DetailedHTMLFactory, HTMLElement>; + code: DetailedHTMLFactory, HTMLElement>; + col: DetailedHTMLFactory, HTMLTableColElement>; + colgroup: DetailedHTMLFactory, HTMLTableColElement>; + data: DetailedHTMLFactory, HTMLDataElement>; + datalist: DetailedHTMLFactory, HTMLDataListElement>; + dd: DetailedHTMLFactory, HTMLElement>; + del: DetailedHTMLFactory, HTMLModElement>; + details: DetailedHTMLFactory, HTMLDetailsElement>; + dfn: DetailedHTMLFactory, HTMLElement>; + dialog: DetailedHTMLFactory, HTMLDialogElement>; + div: DetailedHTMLFactory, HTMLDivElement>; + dl: DetailedHTMLFactory, HTMLDListElement>; + dt: DetailedHTMLFactory, HTMLElement>; + em: DetailedHTMLFactory, HTMLElement>; + embed: DetailedHTMLFactory, HTMLEmbedElement>; + fieldset: DetailedHTMLFactory, HTMLFieldSetElement>; + figcaption: DetailedHTMLFactory, HTMLElement>; + figure: DetailedHTMLFactory, HTMLElement>; + footer: DetailedHTMLFactory, HTMLElement>; + form: DetailedHTMLFactory, HTMLFormElement>; + h1: DetailedHTMLFactory, HTMLHeadingElement>; + h2: DetailedHTMLFactory, HTMLHeadingElement>; + h3: DetailedHTMLFactory, HTMLHeadingElement>; + h4: DetailedHTMLFactory, HTMLHeadingElement>; + h5: DetailedHTMLFactory, HTMLHeadingElement>; + h6: DetailedHTMLFactory, HTMLHeadingElement>; + head: DetailedHTMLFactory, HTMLHeadElement>; + header: DetailedHTMLFactory, HTMLElement>; + hgroup: DetailedHTMLFactory, HTMLElement>; + hr: DetailedHTMLFactory, HTMLHRElement>; + html: DetailedHTMLFactory, HTMLHtmlElement>; + i: DetailedHTMLFactory, HTMLElement>; + iframe: DetailedHTMLFactory, HTMLIFrameElement>; + img: DetailedHTMLFactory, HTMLImageElement>; + input: DetailedHTMLFactory, HTMLInputElement>; + ins: DetailedHTMLFactory, HTMLModElement>; + kbd: DetailedHTMLFactory, HTMLElement>; + keygen: DetailedHTMLFactory, HTMLElement>; + label: DetailedHTMLFactory, HTMLLabelElement>; + legend: DetailedHTMLFactory, HTMLLegendElement>; + li: DetailedHTMLFactory, HTMLLIElement>; + link: DetailedHTMLFactory, HTMLLinkElement>; + main: DetailedHTMLFactory, HTMLElement>; + map: DetailedHTMLFactory, HTMLMapElement>; + mark: DetailedHTMLFactory, HTMLElement>; + menu: DetailedHTMLFactory, HTMLElement>; + menuitem: DetailedHTMLFactory, HTMLElement>; + meta: DetailedHTMLFactory, HTMLMetaElement>; + meter: DetailedHTMLFactory, HTMLMeterElement>; + nav: DetailedHTMLFactory, HTMLElement>; + noscript: DetailedHTMLFactory, HTMLElement>; + object: DetailedHTMLFactory, HTMLObjectElement>; + ol: DetailedHTMLFactory, HTMLOListElement>; + optgroup: DetailedHTMLFactory, HTMLOptGroupElement>; + option: DetailedHTMLFactory, HTMLOptionElement>; + output: DetailedHTMLFactory, HTMLOutputElement>; + p: DetailedHTMLFactory, HTMLParagraphElement>; + param: DetailedHTMLFactory, HTMLParamElement>; + picture: DetailedHTMLFactory, HTMLElement>; + pre: DetailedHTMLFactory, HTMLPreElement>; + progress: DetailedHTMLFactory, HTMLProgressElement>; + q: DetailedHTMLFactory, HTMLQuoteElement>; + rp: DetailedHTMLFactory, HTMLElement>; + rt: DetailedHTMLFactory, HTMLElement>; + ruby: DetailedHTMLFactory, HTMLElement>; + s: DetailedHTMLFactory, HTMLElement>; + samp: DetailedHTMLFactory, HTMLElement>; + search: DetailedHTMLFactory, HTMLElement>; + slot: DetailedHTMLFactory, HTMLSlotElement>; + script: DetailedHTMLFactory, HTMLScriptElement>; + section: DetailedHTMLFactory, HTMLElement>; + select: DetailedHTMLFactory, HTMLSelectElement>; + small: DetailedHTMLFactory, HTMLElement>; + source: DetailedHTMLFactory, HTMLSourceElement>; + span: DetailedHTMLFactory, HTMLSpanElement>; + strong: DetailedHTMLFactory, HTMLElement>; + style: DetailedHTMLFactory, HTMLStyleElement>; + sub: DetailedHTMLFactory, HTMLElement>; + summary: DetailedHTMLFactory, HTMLElement>; + sup: DetailedHTMLFactory, HTMLElement>; + table: DetailedHTMLFactory, HTMLTableElement>; + template: DetailedHTMLFactory, HTMLTemplateElement>; + tbody: DetailedHTMLFactory, HTMLTableSectionElement>; + td: DetailedHTMLFactory, HTMLTableDataCellElement>; + textarea: DetailedHTMLFactory, HTMLTextAreaElement>; + tfoot: DetailedHTMLFactory, HTMLTableSectionElement>; + th: DetailedHTMLFactory, HTMLTableHeaderCellElement>; + thead: DetailedHTMLFactory, HTMLTableSectionElement>; + time: DetailedHTMLFactory, HTMLTimeElement>; + title: DetailedHTMLFactory, HTMLTitleElement>; + tr: DetailedHTMLFactory, HTMLTableRowElement>; + track: DetailedHTMLFactory, HTMLTrackElement>; + u: DetailedHTMLFactory, HTMLElement>; + ul: DetailedHTMLFactory, HTMLUListElement>; + "var": DetailedHTMLFactory, HTMLElement>; + video: DetailedHTMLFactory, HTMLVideoElement>; + wbr: DetailedHTMLFactory, HTMLElement>; + webview: DetailedHTMLFactory, HTMLWebViewElement>; + } + + interface ReactSVG { + animate: SVGFactory; + circle: SVGFactory; + clipPath: SVGFactory; + defs: SVGFactory; + desc: SVGFactory; + ellipse: SVGFactory; + feBlend: SVGFactory; + feColorMatrix: SVGFactory; + feComponentTransfer: SVGFactory; + feComposite: SVGFactory; + feConvolveMatrix: SVGFactory; + feDiffuseLighting: SVGFactory; + feDisplacementMap: SVGFactory; + feDistantLight: SVGFactory; + feDropShadow: SVGFactory; + feFlood: SVGFactory; + feFuncA: SVGFactory; + feFuncB: SVGFactory; + feFuncG: SVGFactory; + feFuncR: SVGFactory; + feGaussianBlur: SVGFactory; + feImage: SVGFactory; + feMerge: SVGFactory; + feMergeNode: SVGFactory; + feMorphology: SVGFactory; + feOffset: SVGFactory; + fePointLight: SVGFactory; + feSpecularLighting: SVGFactory; + feSpotLight: SVGFactory; + feTile: SVGFactory; + feTurbulence: SVGFactory; + filter: SVGFactory; + foreignObject: SVGFactory; + g: SVGFactory; + image: SVGFactory; + line: SVGFactory; + linearGradient: SVGFactory; + marker: SVGFactory; + mask: SVGFactory; + metadata: SVGFactory; + path: SVGFactory; + pattern: SVGFactory; + polygon: SVGFactory; + polyline: SVGFactory; + radialGradient: SVGFactory; + rect: SVGFactory; + stop: SVGFactory; + svg: SVGFactory; + switch: SVGFactory; + symbol: SVGFactory; + text: SVGFactory; + textPath: SVGFactory; + tspan: SVGFactory; + use: SVGFactory; + view: SVGFactory; + } + + interface ReactDOM extends ReactHTML, ReactSVG {} + + // + // React.PropTypes + // ---------------------------------------------------------------------- + + /** + * @deprecated Use `Validator` from the ´prop-types` instead. + */ + type Validator = PropTypes.Validator; + + /** + * @deprecated Use `Requireable` from the ´prop-types` instead. + */ + type Requireable = PropTypes.Requireable; + + /** + * @deprecated Use `ValidationMap` from the ´prop-types` instead. + */ + type ValidationMap = PropTypes.ValidationMap; + + /** + * @deprecated Use `WeakValidationMap` from the ´prop-types` instead. + */ + type WeakValidationMap = { + [K in keyof T]?: null extends T[K] ? Validator + : undefined extends T[K] ? Validator + : Validator; + }; + + /** + * @deprecated Use `PropTypes.*` where `PropTypes` comes from `import * as PropTypes from 'prop-types'` instead. + */ + interface ReactPropTypes { + any: typeof PropTypes.any; + array: typeof PropTypes.array; + bool: typeof PropTypes.bool; + func: typeof PropTypes.func; + number: typeof PropTypes.number; + object: typeof PropTypes.object; + string: typeof PropTypes.string; + node: typeof PropTypes.node; + element: typeof PropTypes.element; + instanceOf: typeof PropTypes.instanceOf; + oneOf: typeof PropTypes.oneOf; + oneOfType: typeof PropTypes.oneOfType; + arrayOf: typeof PropTypes.arrayOf; + objectOf: typeof PropTypes.objectOf; + shape: typeof PropTypes.shape; + exact: typeof PropTypes.exact; + } + + // + // React.Children + // ---------------------------------------------------------------------- + + /** + * @deprecated - Use `typeof React.Children` instead. + */ + // Sync with type of `const Children`. + interface ReactChildren { + map( + children: C | readonly C[], + fn: (child: C, index: number) => T, + ): C extends null | undefined ? C : Array>; + forEach(children: C | readonly C[], fn: (child: C, index: number) => void): void; + count(children: any): number; + only(children: C): C extends any[] ? never : C; + toArray(children: ReactNode | ReactNode[]): Array>; + } + + // + // Browser Interfaces + // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts + // ---------------------------------------------------------------------- + + interface AbstractView { + styleMedia: StyleMedia; + document: Document; + } + + interface Touch { + identifier: number; + target: EventTarget; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + pageX: number; + pageY: number; + } + + interface TouchList { + [index: number]: Touch; + length: number; + item(index: number): Touch; + identifiedTouch(identifier: number): Touch; + } + + // + // Error Interfaces + // ---------------------------------------------------------------------- + interface ErrorInfo { + /** + * Captures which component contained the exception, and its ancestors. + */ + componentStack?: string | null; + digest?: string | null; + } + + // Keep in sync with JSX namespace in ./jsx-runtime.d.ts and ./jsx-dev-runtime.d.ts + namespace JSX { + interface Element extends GlobalJSXElement {} + interface ElementClass extends GlobalJSXElementClass {} + interface ElementAttributesProperty extends GlobalJSXElementAttributesProperty {} + interface ElementChildrenAttribute extends GlobalJSXElementChildrenAttribute {} + + type LibraryManagedAttributes = GlobalJSXLibraryManagedAttributes; + + interface IntrinsicAttributes extends GlobalJSXIntrinsicAttributes {} + interface IntrinsicClassAttributes extends GlobalJSXIntrinsicClassAttributes {} + interface IntrinsicElements extends GlobalJSXIntrinsicElements {} + } +} + +// naked 'any' type in a conditional type will short circuit and union both the then/else branches +// so boolean is only resolved for T = any +type IsExactlyAny = boolean extends (T extends never ? true : false) ? true : false; + +type ExactlyAnyPropertyKeys = { [K in keyof T]: IsExactlyAny extends true ? K : never }[keyof T]; +type NotExactlyAnyPropertyKeys = Exclude>; + +// Try to resolve ill-defined props like for JS users: props can be any, or sometimes objects with properties of type any +type MergePropTypes = + // Distribute over P in case it is a union type + P extends any + // If props is type any, use propTypes definitions + ? IsExactlyAny

extends true ? T + // If declared props have indexed properties, ignore inferred props entirely as keyof gets widened + : string extends keyof P ? P + // Prefer declared types which are not exactly any + : + & Pick> + // For props which are exactly any, use the type inferred from propTypes if present + & Pick>> + // Keep leftover props not specified in propTypes + & Pick> + : never; + +type InexactPartial = { [K in keyof T]?: T[K] | undefined }; + +// Any prop that has a default prop becomes optional, but its type is unchanged +// Undeclared default props are augmented into the resulting allowable attributes +// If declared props have indexed properties, ignore default props entirely as keyof gets widened +// Wrap in an outer-level conditional type to allow distribution over props that are unions +type Defaultize = P extends any ? string extends keyof P ? P + : + & Pick> + & InexactPartial>> + & InexactPartial>> + : never; + +type ReactManagedAttributes = C extends { propTypes: infer T; defaultProps: infer D } + ? Defaultize>, D> + : C extends { propTypes: infer T } ? MergePropTypes> + : C extends { defaultProps: infer D } ? Defaultize + : P; + +declare global { + /** + * @deprecated Use `React.JSX` instead of the global `JSX` namespace. + */ + namespace JSX { + interface Element extends React.ReactElement {} + interface ElementClass extends React.Component { + render(): React.ReactNode; + } + interface ElementAttributesProperty { + props: {}; + } + interface ElementChildrenAttribute { + children: {}; + } + + // We can't recurse forever because `type` can't be self-referential; + // let's assume it's reasonable to do a single React.lazy() around a single React.memo() / vice-versa + type LibraryManagedAttributes = C extends + React.MemoExoticComponent | React.LazyExoticComponent + ? T extends React.MemoExoticComponent | React.LazyExoticComponent + ? ReactManagedAttributes + : ReactManagedAttributes + : ReactManagedAttributes; + + interface IntrinsicAttributes extends React.Attributes {} + interface IntrinsicClassAttributes extends React.ClassAttributes {} + + interface IntrinsicElements { + // HTML + a: React.DetailedHTMLProps, HTMLAnchorElement>; + abbr: React.DetailedHTMLProps, HTMLElement>; + address: React.DetailedHTMLProps, HTMLElement>; + area: React.DetailedHTMLProps, HTMLAreaElement>; + article: React.DetailedHTMLProps, HTMLElement>; + aside: React.DetailedHTMLProps, HTMLElement>; + audio: React.DetailedHTMLProps, HTMLAudioElement>; + b: React.DetailedHTMLProps, HTMLElement>; + base: React.DetailedHTMLProps, HTMLBaseElement>; + bdi: React.DetailedHTMLProps, HTMLElement>; + bdo: React.DetailedHTMLProps, HTMLElement>; + big: React.DetailedHTMLProps, HTMLElement>; + blockquote: React.DetailedHTMLProps, HTMLQuoteElement>; + body: React.DetailedHTMLProps, HTMLBodyElement>; + br: React.DetailedHTMLProps, HTMLBRElement>; + button: React.DetailedHTMLProps, HTMLButtonElement>; + canvas: React.DetailedHTMLProps, HTMLCanvasElement>; + caption: React.DetailedHTMLProps, HTMLElement>; + center: React.DetailedHTMLProps, HTMLElement>; + cite: React.DetailedHTMLProps, HTMLElement>; + code: React.DetailedHTMLProps, HTMLElement>; + col: React.DetailedHTMLProps, HTMLTableColElement>; + colgroup: React.DetailedHTMLProps, HTMLTableColElement>; + data: React.DetailedHTMLProps, HTMLDataElement>; + datalist: React.DetailedHTMLProps, HTMLDataListElement>; + dd: React.DetailedHTMLProps, HTMLElement>; + del: React.DetailedHTMLProps, HTMLModElement>; + details: React.DetailedHTMLProps, HTMLDetailsElement>; + dfn: React.DetailedHTMLProps, HTMLElement>; + dialog: React.DetailedHTMLProps, HTMLDialogElement>; + div: React.DetailedHTMLProps, HTMLDivElement>; + dl: React.DetailedHTMLProps, HTMLDListElement>; + dt: React.DetailedHTMLProps, HTMLElement>; + em: React.DetailedHTMLProps, HTMLElement>; + embed: React.DetailedHTMLProps, HTMLEmbedElement>; + fieldset: React.DetailedHTMLProps, HTMLFieldSetElement>; + figcaption: React.DetailedHTMLProps, HTMLElement>; + figure: React.DetailedHTMLProps, HTMLElement>; + footer: React.DetailedHTMLProps, HTMLElement>; + form: React.DetailedHTMLProps, HTMLFormElement>; + h1: React.DetailedHTMLProps, HTMLHeadingElement>; + h2: React.DetailedHTMLProps, HTMLHeadingElement>; + h3: React.DetailedHTMLProps, HTMLHeadingElement>; + h4: React.DetailedHTMLProps, HTMLHeadingElement>; + h5: React.DetailedHTMLProps, HTMLHeadingElement>; + h6: React.DetailedHTMLProps, HTMLHeadingElement>; + head: React.DetailedHTMLProps, HTMLHeadElement>; + header: React.DetailedHTMLProps, HTMLElement>; + hgroup: React.DetailedHTMLProps, HTMLElement>; + hr: React.DetailedHTMLProps, HTMLHRElement>; + html: React.DetailedHTMLProps, HTMLHtmlElement>; + i: React.DetailedHTMLProps, HTMLElement>; + iframe: React.DetailedHTMLProps, HTMLIFrameElement>; + img: React.DetailedHTMLProps, HTMLImageElement>; + input: React.DetailedHTMLProps, HTMLInputElement>; + ins: React.DetailedHTMLProps, HTMLModElement>; + kbd: React.DetailedHTMLProps, HTMLElement>; + keygen: React.DetailedHTMLProps, HTMLElement>; + label: React.DetailedHTMLProps, HTMLLabelElement>; + legend: React.DetailedHTMLProps, HTMLLegendElement>; + li: React.DetailedHTMLProps, HTMLLIElement>; + link: React.DetailedHTMLProps, HTMLLinkElement>; + main: React.DetailedHTMLProps, HTMLElement>; + map: React.DetailedHTMLProps, HTMLMapElement>; + mark: React.DetailedHTMLProps, HTMLElement>; + menu: React.DetailedHTMLProps, HTMLElement>; + menuitem: React.DetailedHTMLProps, HTMLElement>; + meta: React.DetailedHTMLProps, HTMLMetaElement>; + meter: React.DetailedHTMLProps, HTMLMeterElement>; + nav: React.DetailedHTMLProps, HTMLElement>; + noindex: React.DetailedHTMLProps, HTMLElement>; + noscript: React.DetailedHTMLProps, HTMLElement>; + object: React.DetailedHTMLProps, HTMLObjectElement>; + ol: React.DetailedHTMLProps, HTMLOListElement>; + optgroup: React.DetailedHTMLProps, HTMLOptGroupElement>; + option: React.DetailedHTMLProps, HTMLOptionElement>; + output: React.DetailedHTMLProps, HTMLOutputElement>; + p: React.DetailedHTMLProps, HTMLParagraphElement>; + param: React.DetailedHTMLProps, HTMLParamElement>; + picture: React.DetailedHTMLProps, HTMLElement>; + pre: React.DetailedHTMLProps, HTMLPreElement>; + progress: React.DetailedHTMLProps, HTMLProgressElement>; + q: React.DetailedHTMLProps, HTMLQuoteElement>; + rp: React.DetailedHTMLProps, HTMLElement>; + rt: React.DetailedHTMLProps, HTMLElement>; + ruby: React.DetailedHTMLProps, HTMLElement>; + s: React.DetailedHTMLProps, HTMLElement>; + samp: React.DetailedHTMLProps, HTMLElement>; + search: React.DetailedHTMLProps, HTMLElement>; + slot: React.DetailedHTMLProps, HTMLSlotElement>; + script: React.DetailedHTMLProps, HTMLScriptElement>; + section: React.DetailedHTMLProps, HTMLElement>; + select: React.DetailedHTMLProps, HTMLSelectElement>; + small: React.DetailedHTMLProps, HTMLElement>; + source: React.DetailedHTMLProps, HTMLSourceElement>; + span: React.DetailedHTMLProps, HTMLSpanElement>; + strong: React.DetailedHTMLProps, HTMLElement>; + style: React.DetailedHTMLProps, HTMLStyleElement>; + sub: React.DetailedHTMLProps, HTMLElement>; + summary: React.DetailedHTMLProps, HTMLElement>; + sup: React.DetailedHTMLProps, HTMLElement>; + table: React.DetailedHTMLProps, HTMLTableElement>; + template: React.DetailedHTMLProps, HTMLTemplateElement>; + tbody: React.DetailedHTMLProps, HTMLTableSectionElement>; + td: React.DetailedHTMLProps, HTMLTableDataCellElement>; + textarea: React.DetailedHTMLProps, HTMLTextAreaElement>; + tfoot: React.DetailedHTMLProps, HTMLTableSectionElement>; + th: React.DetailedHTMLProps, HTMLTableHeaderCellElement>; + thead: React.DetailedHTMLProps, HTMLTableSectionElement>; + time: React.DetailedHTMLProps, HTMLTimeElement>; + title: React.DetailedHTMLProps, HTMLTitleElement>; + tr: React.DetailedHTMLProps, HTMLTableRowElement>; + track: React.DetailedHTMLProps, HTMLTrackElement>; + u: React.DetailedHTMLProps, HTMLElement>; + ul: React.DetailedHTMLProps, HTMLUListElement>; + "var": React.DetailedHTMLProps, HTMLElement>; + video: React.DetailedHTMLProps, HTMLVideoElement>; + wbr: React.DetailedHTMLProps, HTMLElement>; + webview: React.DetailedHTMLProps, HTMLWebViewElement>; + + // SVG + svg: React.SVGProps; + + animate: React.SVGProps; // TODO: It is SVGAnimateElement but is not in TypeScript's lib.dom.d.ts for now. + animateMotion: React.SVGProps; + animateTransform: React.SVGProps; // TODO: It is SVGAnimateTransformElement but is not in TypeScript's lib.dom.d.ts for now. + circle: React.SVGProps; + clipPath: React.SVGProps; + defs: React.SVGProps; + desc: React.SVGProps; + ellipse: React.SVGProps; + feBlend: React.SVGProps; + feColorMatrix: React.SVGProps; + feComponentTransfer: React.SVGProps; + feComposite: React.SVGProps; + feConvolveMatrix: React.SVGProps; + feDiffuseLighting: React.SVGProps; + feDisplacementMap: React.SVGProps; + feDistantLight: React.SVGProps; + feDropShadow: React.SVGProps; + feFlood: React.SVGProps; + feFuncA: React.SVGProps; + feFuncB: React.SVGProps; + feFuncG: React.SVGProps; + feFuncR: React.SVGProps; + feGaussianBlur: React.SVGProps; + feImage: React.SVGProps; + feMerge: React.SVGProps; + feMergeNode: React.SVGProps; + feMorphology: React.SVGProps; + feOffset: React.SVGProps; + fePointLight: React.SVGProps; + feSpecularLighting: React.SVGProps; + feSpotLight: React.SVGProps; + feTile: React.SVGProps; + feTurbulence: React.SVGProps; + filter: React.SVGProps; + foreignObject: React.SVGProps; + g: React.SVGProps; + image: React.SVGProps; + line: React.SVGLineElementAttributes; + linearGradient: React.SVGProps; + marker: React.SVGProps; + mask: React.SVGProps; + metadata: React.SVGProps; + mpath: React.SVGProps; + path: React.SVGProps; + pattern: React.SVGProps; + polygon: React.SVGProps; + polyline: React.SVGProps; + radialGradient: React.SVGProps; + rect: React.SVGProps; + set: React.SVGProps; + stop: React.SVGProps; + switch: React.SVGProps; + symbol: React.SVGProps; + text: React.SVGTextElementAttributes; + textPath: React.SVGProps; + tspan: React.SVGProps; + use: React.SVGProps; + view: React.SVGProps; + } + } +} + +// React.JSX needs to point to global.JSX to keep global module augmentations intact. +// But we can't access global.JSX so we need to create these aliases instead. +// Once the global JSX namespace will be removed we replace React.JSX with the contents of global.JSX +interface GlobalJSXElement extends JSX.Element {} +interface GlobalJSXElementClass extends JSX.ElementClass {} +interface GlobalJSXElementAttributesProperty extends JSX.ElementAttributesProperty {} +interface GlobalJSXElementChildrenAttribute extends JSX.ElementChildrenAttribute {} + +type GlobalJSXLibraryManagedAttributes = JSX.LibraryManagedAttributes; + +interface GlobalJSXIntrinsicAttributes extends JSX.IntrinsicAttributes {} +interface GlobalJSXIntrinsicClassAttributes extends JSX.IntrinsicClassAttributes {} + +interface GlobalJSXIntrinsicElements extends JSX.IntrinsicElements {} diff --git a/node_modules/@types/react/ts5.0/v18/ts5.0/jsx-dev-runtime.d.ts b/node_modules/@types/react/ts5.0/v18/ts5.0/jsx-dev-runtime.d.ts new file mode 100644 index 00000000..87d1dfe3 --- /dev/null +++ b/node_modules/@types/react/ts5.0/v18/ts5.0/jsx-dev-runtime.d.ts @@ -0,0 +1,44 @@ +import * as React from "./"; +export { Fragment } from "./"; + +export namespace JSX { + interface Element extends React.JSX.Element {} + interface ElementClass extends React.JSX.ElementClass {} + interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {} + interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {} + type LibraryManagedAttributes = React.JSX.LibraryManagedAttributes; + interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {} + interface IntrinsicClassAttributes extends React.JSX.IntrinsicClassAttributes {} + interface IntrinsicElements extends React.JSX.IntrinsicElements {} +} + +export interface JSXSource { + /** + * The source file where the element originates from. + */ + fileName?: string | undefined; + + /** + * The line number where the element was created. + */ + lineNumber?: number | undefined; + + /** + * The column number where the element was created. + */ + columnNumber?: number | undefined; +} + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsxDEV( + type: React.ElementType, + props: unknown, + key: React.Key | undefined, + isStatic: boolean, + source?: JSXSource, + self?: unknown, +): React.ReactElement; diff --git a/node_modules/@types/react/ts5.0/v18/ts5.0/jsx-runtime.d.ts b/node_modules/@types/react/ts5.0/v18/ts5.0/jsx-runtime.d.ts new file mode 100644 index 00000000..8cc3b974 --- /dev/null +++ b/node_modules/@types/react/ts5.0/v18/ts5.0/jsx-runtime.d.ts @@ -0,0 +1,35 @@ +import * as React from "./"; +export { Fragment } from "./"; + +export namespace JSX { + interface Element extends React.JSX.Element {} + interface ElementClass extends React.JSX.ElementClass {} + interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {} + interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {} + type LibraryManagedAttributes = React.JSX.LibraryManagedAttributes; + interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {} + interface IntrinsicClassAttributes extends React.JSX.IntrinsicClassAttributes {} + interface IntrinsicElements extends React.JSX.IntrinsicElements {} +} + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsx( + type: React.ElementType, + props: unknown, + key?: React.Key, +): React.ReactElement; + +/** + * Create a React element. + * + * You should not use this function directly. Use JSX and a transpiler instead. + */ +export function jsxs( + type: React.ElementType, + props: unknown, + key?: React.Key, +): React.ReactElement; diff --git a/node_modules/@typescript-eslint/eslint-plugin/LICENSE b/node_modules/@typescript-eslint/eslint-plugin/LICENSE new file mode 100644 index 00000000..a1164108 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/eslint-plugin/README.md b/node_modules/@typescript-eslint/eslint-plugin/README.md new file mode 100644 index 00000000..3f894c88 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/eslint-plugin` + +An ESLint plugin which provides lint rules for TypeScript codebases. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/eslint-plugin.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/eslint-plugin) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/eslint-plugin.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/eslint-plugin) + +👉 See **https://typescript-eslint.io/getting-started** for our Getting Started docs. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslint-recommended-raw.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslint-recommended-raw.d.ts new file mode 100644 index 00000000..7a1365df --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslint-recommended-raw.d.ts @@ -0,0 +1,11 @@ +/** + * This is a compatibility ruleset that: + * - disables rules from eslint:recommended which are already handled by TypeScript. + * - enables rules that make sense due to TS's typechecking / transpilation. + */ +declare const config: (style: "glob" | "minimatch") => { + files: string[]; + rules: Record; +}; +export = config; +//# sourceMappingURL=eslint-recommended-raw.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslint-recommended-raw.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslint-recommended-raw.d.ts.map new file mode 100644 index 00000000..ecb60d07 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslint-recommended-raw.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eslint-recommended-raw.d.ts","sourceRoot":"","sources":["../../src/configs/eslint-recommended-raw.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,QAAA,MAAM,MAAM,GACV,OAAO,MAAM,GAAG,WAAW,KAC1B;IACD,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,GAAG,KAAK,GAAG,MAAM,CAAC,CAAC;CAkChD,CAAC;AAEH,SAAS,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslint-recommended-raw.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslint-recommended-raw.js new file mode 100644 index 00000000..5c9b29a8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslint-recommended-raw.js @@ -0,0 +1,41 @@ +"use strict"; +// NOTE: this file is isolated to be shared across legacy and flat configs. +/** + * This is a compatibility ruleset that: + * - disables rules from eslint:recommended which are already handled by TypeScript. + * - enables rules that make sense due to TS's typechecking / transpilation. + */ +const config = (style) => ({ + files: style === 'glob' + ? // classic configs use glob syntax + ['*.ts', '*.tsx', '*.mts', '*.cts'] + : // flat configs use minimatch syntax + ['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts'], + rules: { + 'constructor-super': 'off', // ts(2335) & ts(2377) + 'getter-return': 'off', // ts(2378) + 'no-class-assign': 'off', // ts(2629) + 'no-const-assign': 'off', // ts(2588) + 'no-dupe-args': 'off', // ts(2300) + 'no-dupe-class-members': 'off', // ts(2393) & ts(2300) + 'no-dupe-keys': 'off', // ts(1117) + 'no-func-assign': 'off', // ts(2630) + 'no-import-assign': 'off', // ts(2632) & ts(2540) + // TODO - remove this once we no longer support ESLint v8 + 'no-new-native-nonconstructor': 'off', // ts(7009) + 'no-new-symbol': 'off', // ts(7009) + 'no-obj-calls': 'off', // ts(2349) + 'no-redeclare': 'off', // ts(2451) + 'no-setter-return': 'off', // ts(2408) + 'no-this-before-super': 'off', // ts(2376) & ts(17009) + 'no-undef': 'off', // ts(2304) & ts(2552) + 'no-unreachable': 'off', // ts(7027) + 'no-unsafe-negation': 'off', // ts(2365) & ts(2322) & ts(2358) + 'no-var': 'error', // ts transpiles let/const to var, so no need for vars any more + 'no-with': 'off', // ts(1101) & ts(2410) + 'prefer-const': 'error', // ts provides better types with const + 'prefer-rest-params': 'error', // ts provides better types with rest args over arguments + 'prefer-spread': 'error', // ts transpiles spread to apply, so no need for manual apply + }, +}); +module.exports = config; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts new file mode 100644 index 00000000..6b711357 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts @@ -0,0 +1,156 @@ +declare const _default: { + extends: string[]; + rules: { + '@typescript-eslint/adjacent-overload-signatures': "error"; + '@typescript-eslint/array-type': "error"; + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': "error"; + '@typescript-eslint/ban-tslint-comment': "error"; + '@typescript-eslint/class-literal-property-style': "error"; + 'class-methods-use-this': "off"; + '@typescript-eslint/class-methods-use-this': "error"; + '@typescript-eslint/consistent-generic-constructors': "error"; + '@typescript-eslint/consistent-indexed-object-style': "error"; + 'consistent-return': "off"; + '@typescript-eslint/consistent-return': "error"; + '@typescript-eslint/consistent-type-assertions': "error"; + '@typescript-eslint/consistent-type-definitions': "error"; + '@typescript-eslint/consistent-type-exports': "error"; + '@typescript-eslint/consistent-type-imports': "error"; + 'default-param-last': "off"; + '@typescript-eslint/default-param-last': "error"; + 'dot-notation': "off"; + '@typescript-eslint/dot-notation': "error"; + '@typescript-eslint/explicit-function-return-type': "error"; + '@typescript-eslint/explicit-member-accessibility': "error"; + '@typescript-eslint/explicit-module-boundary-types': "error"; + 'init-declarations': "off"; + '@typescript-eslint/init-declarations': "error"; + 'max-params': "off"; + '@typescript-eslint/max-params': "error"; + '@typescript-eslint/member-ordering': "error"; + '@typescript-eslint/method-signature-style': "error"; + '@typescript-eslint/naming-convention': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-confusing-non-null-assertion': "error"; + '@typescript-eslint/no-confusing-void-expression': "error"; + '@typescript-eslint/no-deprecated': "error"; + 'no-dupe-class-members': "off"; + '@typescript-eslint/no-dupe-class-members': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-dynamic-delete': "error"; + 'no-empty-function': "off"; + '@typescript-eslint/no-empty-function': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-extraneous-class': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-import-type-side-effects': "error"; + '@typescript-eslint/no-inferrable-types': "error"; + 'no-invalid-this': "off"; + '@typescript-eslint/no-invalid-this': "error"; + '@typescript-eslint/no-invalid-void-type': "error"; + 'no-loop-func': "off"; + '@typescript-eslint/no-loop-func': "error"; + 'no-magic-numbers': "off"; + '@typescript-eslint/no-magic-numbers': "error"; + '@typescript-eslint/no-meaningless-void-operator': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-misused-spread': "error"; + '@typescript-eslint/no-mixed-enums': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-non-null-assertion': "error"; + 'no-redeclare': "off"; + '@typescript-eslint/no-redeclare': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + 'no-restricted-imports': "off"; + '@typescript-eslint/no-restricted-imports': "error"; + '@typescript-eslint/no-restricted-types': "error"; + 'no-shadow': "off"; + '@typescript-eslint/no-shadow': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "error"; + '@typescript-eslint/no-unnecessary-condition': "error"; + '@typescript-eslint/no-unnecessary-parameter-property-assignment': "error"; + '@typescript-eslint/no-unnecessary-qualifier': "error"; + '@typescript-eslint/no-unnecessary-template-expression': "error"; + '@typescript-eslint/no-unnecessary-type-arguments': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unnecessary-type-conversion': "error"; + '@typescript-eslint/no-unnecessary-type-parameters': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-type-assertion': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + 'no-use-before-define': "off"; + '@typescript-eslint/no-use-before-define': "error"; + 'no-useless-constructor': "off"; + '@typescript-eslint/no-useless-constructor': "error"; + '@typescript-eslint/no-useless-empty-export': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + '@typescript-eslint/non-nullable-type-assertion-style': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/parameter-properties': "error"; + '@typescript-eslint/prefer-as-const': "error"; + 'prefer-destructuring': "off"; + '@typescript-eslint/prefer-destructuring': "error"; + '@typescript-eslint/prefer-enum-initializers': "error"; + '@typescript-eslint/prefer-find': "error"; + '@typescript-eslint/prefer-for-of': "error"; + '@typescript-eslint/prefer-function-type': "error"; + '@typescript-eslint/prefer-includes': "error"; + '@typescript-eslint/prefer-literal-enum-member': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + '@typescript-eslint/prefer-nullish-coalescing': "error"; + '@typescript-eslint/prefer-optional-chain': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + '@typescript-eslint/prefer-readonly': "error"; + '@typescript-eslint/prefer-readonly-parameter-types': "error"; + '@typescript-eslint/prefer-reduce-type-parameter': "error"; + '@typescript-eslint/prefer-regexp-exec': "error"; + '@typescript-eslint/prefer-return-this-type': "error"; + '@typescript-eslint/prefer-string-starts-ends-with': "error"; + '@typescript-eslint/promise-function-async': "error"; + '@typescript-eslint/related-getter-setter-pairs': "error"; + '@typescript-eslint/require-array-sort-compare': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + 'no-return-await': "off"; + '@typescript-eslint/return-await': "error"; + '@typescript-eslint/strict-boolean-expressions': "error"; + '@typescript-eslint/switch-exhaustiveness-check': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + '@typescript-eslint/unified-signatures': "error"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "error"; + }; +}; +export = _default; +//# sourceMappingURL=all.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts.map new file mode 100644 index 00000000..206cc3ff --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"all.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/all.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBAyJiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.js new file mode 100644 index 00000000..0cc3f7d0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.js @@ -0,0 +1,161 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + '@typescript-eslint/adjacent-overload-signatures': 'error', + '@typescript-eslint/array-type': 'error', + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/ban-ts-comment': 'error', + '@typescript-eslint/ban-tslint-comment': 'error', + '@typescript-eslint/class-literal-property-style': 'error', + 'class-methods-use-this': 'off', + '@typescript-eslint/class-methods-use-this': 'error', + '@typescript-eslint/consistent-generic-constructors': 'error', + '@typescript-eslint/consistent-indexed-object-style': 'error', + 'consistent-return': 'off', + '@typescript-eslint/consistent-return': 'error', + '@typescript-eslint/consistent-type-assertions': 'error', + '@typescript-eslint/consistent-type-definitions': 'error', + '@typescript-eslint/consistent-type-exports': 'error', + '@typescript-eslint/consistent-type-imports': 'error', + 'default-param-last': 'off', + '@typescript-eslint/default-param-last': 'error', + 'dot-notation': 'off', + '@typescript-eslint/dot-notation': 'error', + '@typescript-eslint/explicit-function-return-type': 'error', + '@typescript-eslint/explicit-member-accessibility': 'error', + '@typescript-eslint/explicit-module-boundary-types': 'error', + 'init-declarations': 'off', + '@typescript-eslint/init-declarations': 'error', + 'max-params': 'off', + '@typescript-eslint/max-params': 'error', + '@typescript-eslint/member-ordering': 'error', + '@typescript-eslint/method-signature-style': 'error', + '@typescript-eslint/naming-convention': 'error', + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-confusing-non-null-assertion': 'error', + '@typescript-eslint/no-confusing-void-expression': 'error', + '@typescript-eslint/no-deprecated': 'error', + 'no-dupe-class-members': 'off', + '@typescript-eslint/no-dupe-class-members': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-dynamic-delete': 'error', + 'no-empty-function': 'off', + '@typescript-eslint/no-empty-function': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-extraneous-class': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-import-type-side-effects': 'error', + '@typescript-eslint/no-inferrable-types': 'error', + 'no-invalid-this': 'off', + '@typescript-eslint/no-invalid-this': 'error', + '@typescript-eslint/no-invalid-void-type': 'error', + 'no-loop-func': 'off', + '@typescript-eslint/no-loop-func': 'error', + 'no-magic-numbers': 'off', + '@typescript-eslint/no-magic-numbers': 'error', + '@typescript-eslint/no-meaningless-void-operator': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-misused-spread': 'error', + '@typescript-eslint/no-mixed-enums': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-non-null-assertion': 'error', + 'no-redeclare': 'off', + '@typescript-eslint/no-redeclare': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-require-imports': 'error', + 'no-restricted-imports': 'off', + '@typescript-eslint/no-restricted-imports': 'error', + '@typescript-eslint/no-restricted-types': 'error', + 'no-shadow': 'off', + '@typescript-eslint/no-shadow': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', + '@typescript-eslint/no-unnecessary-condition': 'error', + '@typescript-eslint/no-unnecessary-parameter-property-assignment': 'error', + '@typescript-eslint/no-unnecessary-qualifier': 'error', + '@typescript-eslint/no-unnecessary-template-expression': 'error', + '@typescript-eslint/no-unnecessary-type-arguments': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unnecessary-type-conversion': 'error', + '@typescript-eslint/no-unnecessary-type-parameters': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-type-assertion': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + 'no-use-before-define': 'off', + '@typescript-eslint/no-use-before-define': 'error', + 'no-useless-constructor': 'off', + '@typescript-eslint/no-useless-constructor': 'error', + '@typescript-eslint/no-useless-empty-export': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + '@typescript-eslint/non-nullable-type-assertion-style': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + '@typescript-eslint/parameter-properties': 'error', + '@typescript-eslint/prefer-as-const': 'error', + 'prefer-destructuring': 'off', + '@typescript-eslint/prefer-destructuring': 'error', + '@typescript-eslint/prefer-enum-initializers': 'error', + '@typescript-eslint/prefer-find': 'error', + '@typescript-eslint/prefer-for-of': 'error', + '@typescript-eslint/prefer-function-type': 'error', + '@typescript-eslint/prefer-includes': 'error', + '@typescript-eslint/prefer-literal-enum-member': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + '@typescript-eslint/prefer-nullish-coalescing': 'error', + '@typescript-eslint/prefer-optional-chain': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + '@typescript-eslint/prefer-readonly': 'error', + '@typescript-eslint/prefer-readonly-parameter-types': 'error', + '@typescript-eslint/prefer-reduce-type-parameter': 'error', + '@typescript-eslint/prefer-regexp-exec': 'error', + '@typescript-eslint/prefer-return-this-type': 'error', + '@typescript-eslint/prefer-string-starts-ends-with': 'error', + '@typescript-eslint/promise-function-async': 'error', + '@typescript-eslint/related-getter-setter-pairs': 'error', + '@typescript-eslint/require-array-sort-compare': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': 'error', + '@typescript-eslint/restrict-template-expressions': 'error', + 'no-return-await': 'off', + '@typescript-eslint/return-await': 'error', + '@typescript-eslint/strict-boolean-expressions': 'error', + '@typescript-eslint/switch-exhaustiveness-check': 'error', + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/unbound-method': 'error', + '@typescript-eslint/unified-signatures': 'error', + '@typescript-eslint/use-unknown-in-catch-callback-variable': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/base.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/base.d.ts new file mode 100644 index 00000000..940ddeb7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/base.d.ts @@ -0,0 +1,9 @@ +declare const _default: { + parser: string; + parserOptions: { + sourceType: "module"; + }; + plugins: string[]; +}; +export = _default; +//# sourceMappingURL=base.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/base.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/base.d.ts.map new file mode 100644 index 00000000..9095b6fc --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/base.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/base.ts"],"names":[],"mappings":";;;;;;;AAEA,kBAIiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/base.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/base.js new file mode 100644 index 00000000..2852f3c7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/base.js @@ -0,0 +1,6 @@ +"use strict"; +module.exports = { + parser: '@typescript-eslint/parser', + parserOptions: { sourceType: 'module' }, + plugins: ['@typescript-eslint'], +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/disable-type-checked.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/disable-type-checked.d.ts new file mode 100644 index 00000000..d3d6687a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/disable-type-checked.d.ts @@ -0,0 +1,70 @@ +declare const _default: { + parserOptions: { + program: null; + project: false; + projectService: false; + }; + rules: { + '@typescript-eslint/await-thenable': "off"; + '@typescript-eslint/consistent-return': "off"; + '@typescript-eslint/consistent-type-exports': "off"; + '@typescript-eslint/dot-notation': "off"; + '@typescript-eslint/naming-convention': "off"; + '@typescript-eslint/no-array-delete': "off"; + '@typescript-eslint/no-base-to-string': "off"; + '@typescript-eslint/no-confusing-void-expression': "off"; + '@typescript-eslint/no-deprecated': "off"; + '@typescript-eslint/no-duplicate-type-constituents': "off"; + '@typescript-eslint/no-floating-promises': "off"; + '@typescript-eslint/no-for-in-array': "off"; + '@typescript-eslint/no-implied-eval': "off"; + '@typescript-eslint/no-meaningless-void-operator': "off"; + '@typescript-eslint/no-misused-promises': "off"; + '@typescript-eslint/no-misused-spread': "off"; + '@typescript-eslint/no-mixed-enums': "off"; + '@typescript-eslint/no-redundant-type-constituents': "off"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "off"; + '@typescript-eslint/no-unnecessary-condition': "off"; + '@typescript-eslint/no-unnecessary-qualifier': "off"; + '@typescript-eslint/no-unnecessary-template-expression': "off"; + '@typescript-eslint/no-unnecessary-type-arguments': "off"; + '@typescript-eslint/no-unnecessary-type-assertion': "off"; + '@typescript-eslint/no-unnecessary-type-conversion': "off"; + '@typescript-eslint/no-unnecessary-type-parameters': "off"; + '@typescript-eslint/no-unsafe-argument': "off"; + '@typescript-eslint/no-unsafe-assignment': "off"; + '@typescript-eslint/no-unsafe-call': "off"; + '@typescript-eslint/no-unsafe-enum-comparison': "off"; + '@typescript-eslint/no-unsafe-member-access': "off"; + '@typescript-eslint/no-unsafe-return': "off"; + '@typescript-eslint/no-unsafe-type-assertion': "off"; + '@typescript-eslint/no-unsafe-unary-minus': "off"; + '@typescript-eslint/non-nullable-type-assertion-style': "off"; + '@typescript-eslint/only-throw-error': "off"; + '@typescript-eslint/prefer-destructuring': "off"; + '@typescript-eslint/prefer-find': "off"; + '@typescript-eslint/prefer-includes': "off"; + '@typescript-eslint/prefer-nullish-coalescing': "off"; + '@typescript-eslint/prefer-optional-chain': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-readonly': "off"; + '@typescript-eslint/prefer-readonly-parameter-types': "off"; + '@typescript-eslint/prefer-reduce-type-parameter': "off"; + '@typescript-eslint/prefer-regexp-exec': "off"; + '@typescript-eslint/prefer-return-this-type': "off"; + '@typescript-eslint/prefer-string-starts-ends-with': "off"; + '@typescript-eslint/promise-function-async': "off"; + '@typescript-eslint/related-getter-setter-pairs': "off"; + '@typescript-eslint/require-array-sort-compare': "off"; + '@typescript-eslint/require-await': "off"; + '@typescript-eslint/restrict-plus-operands': "off"; + '@typescript-eslint/restrict-template-expressions': "off"; + '@typescript-eslint/return-await': "off"; + '@typescript-eslint/strict-boolean-expressions': "off"; + '@typescript-eslint/switch-exhaustiveness-check': "off"; + '@typescript-eslint/unbound-method': "off"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "off"; + }; +}; +export = _default; +//# sourceMappingURL=disable-type-checked.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/disable-type-checked.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/disable-type-checked.d.ts.map new file mode 100644 index 00000000..c3bd25ef --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/disable-type-checked.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"disable-type-checked.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/disable-type-checked.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBA+DiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/disable-type-checked.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/disable-type-checked.js new file mode 100644 index 00000000..c29be311 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/disable-type-checked.js @@ -0,0 +1,71 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + parserOptions: { program: null, project: false, projectService: false }, + rules: { + '@typescript-eslint/await-thenable': 'off', + '@typescript-eslint/consistent-return': 'off', + '@typescript-eslint/consistent-type-exports': 'off', + '@typescript-eslint/dot-notation': 'off', + '@typescript-eslint/naming-convention': 'off', + '@typescript-eslint/no-array-delete': 'off', + '@typescript-eslint/no-base-to-string': 'off', + '@typescript-eslint/no-confusing-void-expression': 'off', + '@typescript-eslint/no-deprecated': 'off', + '@typescript-eslint/no-duplicate-type-constituents': 'off', + '@typescript-eslint/no-floating-promises': 'off', + '@typescript-eslint/no-for-in-array': 'off', + '@typescript-eslint/no-implied-eval': 'off', + '@typescript-eslint/no-meaningless-void-operator': 'off', + '@typescript-eslint/no-misused-promises': 'off', + '@typescript-eslint/no-misused-spread': 'off', + '@typescript-eslint/no-mixed-enums': 'off', + '@typescript-eslint/no-redundant-type-constituents': 'off', + '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'off', + '@typescript-eslint/no-unnecessary-condition': 'off', + '@typescript-eslint/no-unnecessary-qualifier': 'off', + '@typescript-eslint/no-unnecessary-template-expression': 'off', + '@typescript-eslint/no-unnecessary-type-arguments': 'off', + '@typescript-eslint/no-unnecessary-type-assertion': 'off', + '@typescript-eslint/no-unnecessary-type-conversion': 'off', + '@typescript-eslint/no-unnecessary-type-parameters': 'off', + '@typescript-eslint/no-unsafe-argument': 'off', + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-unsafe-call': 'off', + '@typescript-eslint/no-unsafe-enum-comparison': 'off', + '@typescript-eslint/no-unsafe-member-access': 'off', + '@typescript-eslint/no-unsafe-return': 'off', + '@typescript-eslint/no-unsafe-type-assertion': 'off', + '@typescript-eslint/no-unsafe-unary-minus': 'off', + '@typescript-eslint/non-nullable-type-assertion-style': 'off', + '@typescript-eslint/only-throw-error': 'off', + '@typescript-eslint/prefer-destructuring': 'off', + '@typescript-eslint/prefer-find': 'off', + '@typescript-eslint/prefer-includes': 'off', + '@typescript-eslint/prefer-nullish-coalescing': 'off', + '@typescript-eslint/prefer-optional-chain': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-readonly': 'off', + '@typescript-eslint/prefer-readonly-parameter-types': 'off', + '@typescript-eslint/prefer-reduce-type-parameter': 'off', + '@typescript-eslint/prefer-regexp-exec': 'off', + '@typescript-eslint/prefer-return-this-type': 'off', + '@typescript-eslint/prefer-string-starts-ends-with': 'off', + '@typescript-eslint/promise-function-async': 'off', + '@typescript-eslint/related-getter-setter-pairs': 'off', + '@typescript-eslint/require-array-sort-compare': 'off', + '@typescript-eslint/require-await': 'off', + '@typescript-eslint/restrict-plus-operands': 'off', + '@typescript-eslint/restrict-template-expressions': 'off', + '@typescript-eslint/return-await': 'off', + '@typescript-eslint/strict-boolean-expressions': 'off', + '@typescript-eslint/switch-exhaustiveness-check': 'off', + '@typescript-eslint/unbound-method': 'off', + '@typescript-eslint/use-unknown-in-catch-callback-variable': 'off', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/eslint-recommended.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/eslint-recommended.d.ts new file mode 100644 index 00000000..ac81a10d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/eslint-recommended.d.ts @@ -0,0 +1,13 @@ +/** + * This is a compatibility ruleset that: + * - disables rules from eslint:recommended which are already handled by TypeScript. + * - enables rules that make sense due to TS's typechecking / transpilation. + */ +declare const _default: { + overrides: { + files: string[]; + rules: Record; + }[]; +}; +export = _default; +//# sourceMappingURL=eslint-recommended.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/eslint-recommended.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/eslint-recommended.d.ts.map new file mode 100644 index 00000000..9ee759af --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/eslint-recommended.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eslint-recommended.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/eslint-recommended.ts"],"names":[],"mappings":"AAAA;;;;GAIG;;;;;;;AAMH,kBAEiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/eslint-recommended.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/eslint-recommended.js new file mode 100644 index 00000000..dc3cb7b7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/eslint-recommended.js @@ -0,0 +1,13 @@ +"use strict"; +/** + * This is a compatibility ruleset that: + * - disables rules from eslint:recommended which are already handled by TypeScript. + * - enables rules that make sense due to TS's typechecking / transpilation. + */ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const eslint_recommended_raw_1 = __importDefault(require("../eslint-recommended-raw")); +module.exports = { + overrides: [(0, eslint_recommended_raw_1.default)('glob')], +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked-only.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked-only.d.ts new file mode 100644 index 00000000..063e3122 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked-only.d.ts @@ -0,0 +1,34 @@ +declare const _default: { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + '@typescript-eslint/unbound-method': "error"; + }; +}; +export = _default; +//# sourceMappingURL=recommended-type-checked-only.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked-only.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked-only.d.ts.map new file mode 100644 index 00000000..6b288fc6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked-only.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"recommended-type-checked-only.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/recommended-type-checked-only.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBA+BiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked-only.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked-only.js new file mode 100644 index 00000000..66866861 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked-only.js @@ -0,0 +1,39 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': 'error', + '@typescript-eslint/restrict-template-expressions': 'error', + '@typescript-eslint/unbound-method': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked.d.ts new file mode 100644 index 00000000..706fa1ca --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked.d.ts @@ -0,0 +1,57 @@ +declare const _default: { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + }; +}; +export = _default; +//# sourceMappingURL=recommended-type-checked.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked.d.ts.map new file mode 100644 index 00000000..3e476ff9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"recommended-type-checked.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/recommended-type-checked.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBAsDiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked.js new file mode 100644 index 00000000..b0b32363 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended-type-checked.js @@ -0,0 +1,62 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/ban-ts-comment': 'error', + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-require-imports': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + '@typescript-eslint/prefer-as-const': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': 'error', + '@typescript-eslint/restrict-template-expressions': 'error', + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/unbound-method': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended.d.ts new file mode 100644 index 00000000..f874e521 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended.d.ts @@ -0,0 +1,30 @@ +declare const _default: { + extends: string[]; + rules: { + '@typescript-eslint/ban-ts-comment': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + }; +}; +export = _default; +//# sourceMappingURL=recommended.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended.d.ts.map new file mode 100644 index 00000000..efde7db9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"recommended.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/recommended.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBA2BiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended.js new file mode 100644 index 00000000..19a45348 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/recommended.js @@ -0,0 +1,35 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + '@typescript-eslint/ban-ts-comment': 'error', + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-require-imports': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + '@typescript-eslint/prefer-as-const': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + '@typescript-eslint/triple-slash-reference': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked-only.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked-only.d.ts new file mode 100644 index 00000000..a8a79657 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked-only.d.ts @@ -0,0 +1,63 @@ +declare const _default: { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-confusing-void-expression': "error"; + '@typescript-eslint/no-deprecated': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-meaningless-void-operator': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-misused-spread': "error"; + '@typescript-eslint/no-mixed-enums': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "error"; + '@typescript-eslint/no-unnecessary-condition': "error"; + '@typescript-eslint/no-unnecessary-template-expression': "error"; + '@typescript-eslint/no-unnecessary-type-arguments': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-parameters': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + '@typescript-eslint/prefer-reduce-type-parameter': "error"; + '@typescript-eslint/prefer-return-this-type': "error"; + '@typescript-eslint/related-getter-setter-pairs': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNullish: boolean; + allowNumberAndString: boolean; + allowRegExp: boolean; + }]; + '@typescript-eslint/restrict-template-expressions': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNever: boolean; + allowNullish: boolean; + allowNumber: boolean; + allowRegExp: boolean; + }]; + 'no-return-await': "off"; + '@typescript-eslint/return-await': ["error", string]; + '@typescript-eslint/unbound-method': "error"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "error"; + }; +}; +export = _default; +//# sourceMappingURL=strict-type-checked-only.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked-only.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked-only.d.ts.map new file mode 100644 index 00000000..4993f405 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked-only.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"strict-type-checked-only.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/strict-type-checked-only.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBAqEiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked-only.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked-only.js new file mode 100644 index 00000000..3bbe728b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked-only.js @@ -0,0 +1,77 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-confusing-void-expression': 'error', + '@typescript-eslint/no-deprecated': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-meaningless-void-operator': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-misused-spread': 'error', + '@typescript-eslint/no-mixed-enums': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', + '@typescript-eslint/no-unnecessary-condition': 'error', + '@typescript-eslint/no-unnecessary-template-expression': 'error', + '@typescript-eslint/no-unnecessary-type-arguments': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unnecessary-type-parameters': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + '@typescript-eslint/prefer-reduce-type-parameter': 'error', + '@typescript-eslint/prefer-return-this-type': 'error', + '@typescript-eslint/related-getter-setter-pairs': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': [ + 'error', + { + allowAny: false, + allowBoolean: false, + allowNullish: false, + allowNumberAndString: false, + allowRegExp: false, + }, + ], + '@typescript-eslint/restrict-template-expressions': [ + 'error', + { + allowAny: false, + allowBoolean: false, + allowNever: false, + allowNullish: false, + allowNumber: false, + allowRegExp: false, + }, + ], + 'no-return-await': 'off', + '@typescript-eslint/return-await': [ + 'error', + 'error-handling-correctness-only', + ], + '@typescript-eslint/unbound-method': 'error', + '@typescript-eslint/use-unknown-in-catch-callback-variable': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked.d.ts new file mode 100644 index 00000000..105bfdbe --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked.d.ts @@ -0,0 +1,97 @@ +declare const _default: { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': ["error", { + minimumDescriptionLength: number; + }]; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-confusing-void-expression': "error"; + '@typescript-eslint/no-deprecated': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-dynamic-delete': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-extraneous-class': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-invalid-void-type': "error"; + '@typescript-eslint/no-meaningless-void-operator': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-misused-spread': "error"; + '@typescript-eslint/no-mixed-enums': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-non-null-assertion': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "error"; + '@typescript-eslint/no-unnecessary-condition': "error"; + '@typescript-eslint/no-unnecessary-template-expression': "error"; + '@typescript-eslint/no-unnecessary-type-arguments': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unnecessary-type-parameters': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + 'no-useless-constructor': "off"; + '@typescript-eslint/no-useless-constructor': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-literal-enum-member': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + '@typescript-eslint/prefer-reduce-type-parameter': "error"; + '@typescript-eslint/prefer-return-this-type': "error"; + '@typescript-eslint/related-getter-setter-pairs': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNullish: boolean; + allowNumberAndString: boolean; + allowRegExp: boolean; + }]; + '@typescript-eslint/restrict-template-expressions': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNever: boolean; + allowNullish: boolean; + allowNumber: boolean; + allowRegExp: boolean; + }]; + 'no-return-await': "off"; + '@typescript-eslint/return-await': ["error", string]; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + '@typescript-eslint/unified-signatures': "error"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "error"; + }; +}; +export = _default; +//# sourceMappingURL=strict-type-checked.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked.d.ts.map new file mode 100644 index 00000000..da722b14 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"strict-type-checked.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/strict-type-checked.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBAwGiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked.js new file mode 100644 index 00000000..88f71d2b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict-type-checked.js @@ -0,0 +1,112 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/ban-ts-comment': [ + 'error', + { minimumDescriptionLength: 10 }, + ], + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-confusing-void-expression': 'error', + '@typescript-eslint/no-deprecated': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-dynamic-delete': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-extraneous-class': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-invalid-void-type': 'error', + '@typescript-eslint/no-meaningless-void-operator': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-misused-spread': 'error', + '@typescript-eslint/no-mixed-enums': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-non-null-assertion': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-require-imports': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', + '@typescript-eslint/no-unnecessary-condition': 'error', + '@typescript-eslint/no-unnecessary-template-expression': 'error', + '@typescript-eslint/no-unnecessary-type-arguments': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unnecessary-type-parameters': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + 'no-useless-constructor': 'off', + '@typescript-eslint/no-useless-constructor': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + '@typescript-eslint/prefer-as-const': 'error', + '@typescript-eslint/prefer-literal-enum-member': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + '@typescript-eslint/prefer-reduce-type-parameter': 'error', + '@typescript-eslint/prefer-return-this-type': 'error', + '@typescript-eslint/related-getter-setter-pairs': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': [ + 'error', + { + allowAny: false, + allowBoolean: false, + allowNullish: false, + allowNumberAndString: false, + allowRegExp: false, + }, + ], + '@typescript-eslint/restrict-template-expressions': [ + 'error', + { + allowAny: false, + allowBoolean: false, + allowNever: false, + allowNullish: false, + allowNumber: false, + allowRegExp: false, + }, + ], + 'no-return-await': 'off', + '@typescript-eslint/return-await': [ + 'error', + 'error-handling-correctness-only', + ], + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/unbound-method': 'error', + '@typescript-eslint/unified-signatures': 'error', + '@typescript-eslint/use-unknown-in-catch-callback-variable': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict.d.ts new file mode 100644 index 00000000..59dd9234 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict.d.ts @@ -0,0 +1,41 @@ +declare const _default: { + extends: string[]; + rules: { + '@typescript-eslint/ban-ts-comment': ["error", { + minimumDescriptionLength: number; + }]; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-dynamic-delete': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-extraneous-class': "error"; + '@typescript-eslint/no-invalid-void-type': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-non-null-assertion': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + 'no-useless-constructor': "off"; + '@typescript-eslint/no-useless-constructor': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-literal-enum-member': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unified-signatures': "error"; + }; +}; +export = _default; +//# sourceMappingURL=strict.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict.d.ts.map new file mode 100644 index 00000000..f2711499 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"strict.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/strict.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBAuCiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict.js new file mode 100644 index 00000000..66fabc24 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/strict.js @@ -0,0 +1,47 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + '@typescript-eslint/ban-ts-comment': [ + 'error', + { minimumDescriptionLength: 10 }, + ], + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-dynamic-delete': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-extraneous-class': 'error', + '@typescript-eslint/no-invalid-void-type': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-non-null-assertion': 'error', + '@typescript-eslint/no-require-imports': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + 'no-useless-constructor': 'off', + '@typescript-eslint/no-useless-constructor': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + '@typescript-eslint/prefer-as-const': 'error', + '@typescript-eslint/prefer-literal-enum-member': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/unified-signatures': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked-only.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked-only.d.ts new file mode 100644 index 00000000..d9febd8d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked-only.d.ts @@ -0,0 +1,16 @@ +declare const _default: { + extends: string[]; + rules: { + 'dot-notation': "off"; + '@typescript-eslint/dot-notation': "error"; + '@typescript-eslint/non-nullable-type-assertion-style': "error"; + '@typescript-eslint/prefer-find': "error"; + '@typescript-eslint/prefer-includes': "error"; + '@typescript-eslint/prefer-nullish-coalescing': "error"; + '@typescript-eslint/prefer-optional-chain': "error"; + '@typescript-eslint/prefer-regexp-exec': "error"; + '@typescript-eslint/prefer-string-starts-ends-with': "error"; + }; +}; +export = _default; +//# sourceMappingURL=stylistic-type-checked-only.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked-only.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked-only.d.ts.map new file mode 100644 index 00000000..915c5af1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked-only.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stylistic-type-checked-only.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/stylistic-type-checked-only.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AASA,kBAaiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked-only.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked-only.js new file mode 100644 index 00000000..e9367461 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked-only.js @@ -0,0 +1,21 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + 'dot-notation': 'off', + '@typescript-eslint/dot-notation': 'error', + '@typescript-eslint/non-nullable-type-assertion-style': 'error', + '@typescript-eslint/prefer-find': 'error', + '@typescript-eslint/prefer-includes': 'error', + '@typescript-eslint/prefer-nullish-coalescing': 'error', + '@typescript-eslint/prefer-optional-chain': 'error', + '@typescript-eslint/prefer-regexp-exec': 'error', + '@typescript-eslint/prefer-string-starts-ends-with': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked.d.ts new file mode 100644 index 00000000..67cd6391 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked.d.ts @@ -0,0 +1,30 @@ +declare const _default: { + extends: string[]; + rules: { + '@typescript-eslint/adjacent-overload-signatures': "error"; + '@typescript-eslint/array-type': "error"; + '@typescript-eslint/ban-tslint-comment': "error"; + '@typescript-eslint/class-literal-property-style': "error"; + '@typescript-eslint/consistent-generic-constructors': "error"; + '@typescript-eslint/consistent-indexed-object-style': "error"; + '@typescript-eslint/consistent-type-assertions': "error"; + '@typescript-eslint/consistent-type-definitions': "error"; + 'dot-notation': "off"; + '@typescript-eslint/dot-notation': "error"; + '@typescript-eslint/no-confusing-non-null-assertion': "error"; + 'no-empty-function': "off"; + '@typescript-eslint/no-empty-function': "error"; + '@typescript-eslint/no-inferrable-types': "error"; + '@typescript-eslint/non-nullable-type-assertion-style': "error"; + '@typescript-eslint/prefer-find': "error"; + '@typescript-eslint/prefer-for-of': "error"; + '@typescript-eslint/prefer-function-type': "error"; + '@typescript-eslint/prefer-includes': "error"; + '@typescript-eslint/prefer-nullish-coalescing': "error"; + '@typescript-eslint/prefer-optional-chain': "error"; + '@typescript-eslint/prefer-regexp-exec': "error"; + '@typescript-eslint/prefer-string-starts-ends-with': "error"; + }; +}; +export = _default; +//# sourceMappingURL=stylistic-type-checked.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked.d.ts.map new file mode 100644 index 00000000..1c4f5f07 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stylistic-type-checked.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/stylistic-type-checked.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBA2BiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked.js new file mode 100644 index 00000000..f219ca19 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic-type-checked.js @@ -0,0 +1,35 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + '@typescript-eslint/adjacent-overload-signatures': 'error', + '@typescript-eslint/array-type': 'error', + '@typescript-eslint/ban-tslint-comment': 'error', + '@typescript-eslint/class-literal-property-style': 'error', + '@typescript-eslint/consistent-generic-constructors': 'error', + '@typescript-eslint/consistent-indexed-object-style': 'error', + '@typescript-eslint/consistent-type-assertions': 'error', + '@typescript-eslint/consistent-type-definitions': 'error', + 'dot-notation': 'off', + '@typescript-eslint/dot-notation': 'error', + '@typescript-eslint/no-confusing-non-null-assertion': 'error', + 'no-empty-function': 'off', + '@typescript-eslint/no-empty-function': 'error', + '@typescript-eslint/no-inferrable-types': 'error', + '@typescript-eslint/non-nullable-type-assertion-style': 'error', + '@typescript-eslint/prefer-find': 'error', + '@typescript-eslint/prefer-for-of': 'error', + '@typescript-eslint/prefer-function-type': 'error', + '@typescript-eslint/prefer-includes': 'error', + '@typescript-eslint/prefer-nullish-coalescing': 'error', + '@typescript-eslint/prefer-optional-chain': 'error', + '@typescript-eslint/prefer-regexp-exec': 'error', + '@typescript-eslint/prefer-string-starts-ends-with': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic.d.ts new file mode 100644 index 00000000..4d899e86 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic.d.ts @@ -0,0 +1,21 @@ +declare const _default: { + extends: string[]; + rules: { + '@typescript-eslint/adjacent-overload-signatures': "error"; + '@typescript-eslint/array-type': "error"; + '@typescript-eslint/ban-tslint-comment': "error"; + '@typescript-eslint/class-literal-property-style': "error"; + '@typescript-eslint/consistent-generic-constructors': "error"; + '@typescript-eslint/consistent-indexed-object-style': "error"; + '@typescript-eslint/consistent-type-assertions': "error"; + '@typescript-eslint/consistent-type-definitions': "error"; + '@typescript-eslint/no-confusing-non-null-assertion': "error"; + 'no-empty-function': "off"; + '@typescript-eslint/no-empty-function': "error"; + '@typescript-eslint/no-inferrable-types': "error"; + '@typescript-eslint/prefer-for-of': "error"; + '@typescript-eslint/prefer-function-type': "error"; + }; +}; +export = _default; +//# sourceMappingURL=stylistic.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic.d.ts.map new file mode 100644 index 00000000..849edf4a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stylistic.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/stylistic.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AASA,kBAkBiC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic.js new file mode 100644 index 00000000..bab17ef8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/stylistic.js @@ -0,0 +1,26 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +module.exports = { + extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'], + rules: { + '@typescript-eslint/adjacent-overload-signatures': 'error', + '@typescript-eslint/array-type': 'error', + '@typescript-eslint/ban-tslint-comment': 'error', + '@typescript-eslint/class-literal-property-style': 'error', + '@typescript-eslint/consistent-generic-constructors': 'error', + '@typescript-eslint/consistent-indexed-object-style': 'error', + '@typescript-eslint/consistent-type-assertions': 'error', + '@typescript-eslint/consistent-type-definitions': 'error', + '@typescript-eslint/no-confusing-non-null-assertion': 'error', + 'no-empty-function': 'off', + '@typescript-eslint/no-empty-function': 'error', + '@typescript-eslint/no-inferrable-types': 'error', + '@typescript-eslint/prefer-for-of': 'error', + '@typescript-eslint/prefer-function-type': 'error', + }, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.d.ts new file mode 100644 index 00000000..aa288395 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * Enables each the rules provided as a part of typescript-eslint. Note that many rules are not applicable in all codebases, or are meant to be configured. + * @see {@link https://typescript-eslint.io/users/configs#all} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=all.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.d.ts.map new file mode 100644 index 00000000..ceb96d08 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"all.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/all.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBAiKE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.js new file mode 100644 index 00000000..c1489295 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.js @@ -0,0 +1,175 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * Enables each the rules provided as a part of typescript-eslint. Note that many rules are not applicable in all codebases, or are meant to be configured. + * @see {@link https://typescript-eslint.io/users/configs#all} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/all', + rules: { + '@typescript-eslint/adjacent-overload-signatures': 'error', + '@typescript-eslint/array-type': 'error', + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/ban-ts-comment': 'error', + '@typescript-eslint/ban-tslint-comment': 'error', + '@typescript-eslint/class-literal-property-style': 'error', + 'class-methods-use-this': 'off', + '@typescript-eslint/class-methods-use-this': 'error', + '@typescript-eslint/consistent-generic-constructors': 'error', + '@typescript-eslint/consistent-indexed-object-style': 'error', + 'consistent-return': 'off', + '@typescript-eslint/consistent-return': 'error', + '@typescript-eslint/consistent-type-assertions': 'error', + '@typescript-eslint/consistent-type-definitions': 'error', + '@typescript-eslint/consistent-type-exports': 'error', + '@typescript-eslint/consistent-type-imports': 'error', + 'default-param-last': 'off', + '@typescript-eslint/default-param-last': 'error', + 'dot-notation': 'off', + '@typescript-eslint/dot-notation': 'error', + '@typescript-eslint/explicit-function-return-type': 'error', + '@typescript-eslint/explicit-member-accessibility': 'error', + '@typescript-eslint/explicit-module-boundary-types': 'error', + 'init-declarations': 'off', + '@typescript-eslint/init-declarations': 'error', + 'max-params': 'off', + '@typescript-eslint/max-params': 'error', + '@typescript-eslint/member-ordering': 'error', + '@typescript-eslint/method-signature-style': 'error', + '@typescript-eslint/naming-convention': 'error', + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-confusing-non-null-assertion': 'error', + '@typescript-eslint/no-confusing-void-expression': 'error', + '@typescript-eslint/no-deprecated': 'error', + 'no-dupe-class-members': 'off', + '@typescript-eslint/no-dupe-class-members': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-dynamic-delete': 'error', + 'no-empty-function': 'off', + '@typescript-eslint/no-empty-function': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-extraneous-class': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-import-type-side-effects': 'error', + '@typescript-eslint/no-inferrable-types': 'error', + 'no-invalid-this': 'off', + '@typescript-eslint/no-invalid-this': 'error', + '@typescript-eslint/no-invalid-void-type': 'error', + 'no-loop-func': 'off', + '@typescript-eslint/no-loop-func': 'error', + 'no-magic-numbers': 'off', + '@typescript-eslint/no-magic-numbers': 'error', + '@typescript-eslint/no-meaningless-void-operator': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-misused-spread': 'error', + '@typescript-eslint/no-mixed-enums': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-non-null-assertion': 'error', + 'no-redeclare': 'off', + '@typescript-eslint/no-redeclare': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-require-imports': 'error', + 'no-restricted-imports': 'off', + '@typescript-eslint/no-restricted-imports': 'error', + '@typescript-eslint/no-restricted-types': 'error', + 'no-shadow': 'off', + '@typescript-eslint/no-shadow': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', + '@typescript-eslint/no-unnecessary-condition': 'error', + '@typescript-eslint/no-unnecessary-parameter-property-assignment': 'error', + '@typescript-eslint/no-unnecessary-qualifier': 'error', + '@typescript-eslint/no-unnecessary-template-expression': 'error', + '@typescript-eslint/no-unnecessary-type-arguments': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unnecessary-type-conversion': 'error', + '@typescript-eslint/no-unnecessary-type-parameters': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-type-assertion': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + 'no-use-before-define': 'off', + '@typescript-eslint/no-use-before-define': 'error', + 'no-useless-constructor': 'off', + '@typescript-eslint/no-useless-constructor': 'error', + '@typescript-eslint/no-useless-empty-export': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + '@typescript-eslint/non-nullable-type-assertion-style': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + '@typescript-eslint/parameter-properties': 'error', + '@typescript-eslint/prefer-as-const': 'error', + 'prefer-destructuring': 'off', + '@typescript-eslint/prefer-destructuring': 'error', + '@typescript-eslint/prefer-enum-initializers': 'error', + '@typescript-eslint/prefer-find': 'error', + '@typescript-eslint/prefer-for-of': 'error', + '@typescript-eslint/prefer-function-type': 'error', + '@typescript-eslint/prefer-includes': 'error', + '@typescript-eslint/prefer-literal-enum-member': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + '@typescript-eslint/prefer-nullish-coalescing': 'error', + '@typescript-eslint/prefer-optional-chain': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + '@typescript-eslint/prefer-readonly': 'error', + '@typescript-eslint/prefer-readonly-parameter-types': 'error', + '@typescript-eslint/prefer-reduce-type-parameter': 'error', + '@typescript-eslint/prefer-regexp-exec': 'error', + '@typescript-eslint/prefer-return-this-type': 'error', + '@typescript-eslint/prefer-string-starts-ends-with': 'error', + '@typescript-eslint/promise-function-async': 'error', + '@typescript-eslint/related-getter-setter-pairs': 'error', + '@typescript-eslint/require-array-sort-compare': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': 'error', + '@typescript-eslint/restrict-template-expressions': 'error', + 'no-return-await': 'off', + '@typescript-eslint/return-await': 'error', + '@typescript-eslint/strict-boolean-expressions': 'error', + '@typescript-eslint/switch-exhaustiveness-check': 'error', + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/unbound-method': 'error', + '@typescript-eslint/unified-signatures': 'error', + '@typescript-eslint/use-unknown-in-catch-callback-variable': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/base.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/base.d.ts new file mode 100644 index 00000000..06628aaa --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/base.d.ts @@ -0,0 +1,9 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * A minimal ruleset that sets only the required parser and plugin options needed to run typescript-eslint. + * We don't recommend using this directly; instead, extend from an earlier recommended rule. + * @see {@link https://typescript-eslint.io/users/configs#base} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.Config; +export default _default; +//# sourceMappingURL=base.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/base.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/base.d.ts.map new file mode 100644 index 00000000..d1aa326b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/base.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/base.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAErE;;;;GAIG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,MAAM;AAHpB,wBAYG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/base.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/base.js new file mode 100644 index 00000000..b9e6cbde --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/base.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * A minimal ruleset that sets only the required parser and plugin options needed to run typescript-eslint. + * We don't recommend using this directly; instead, extend from an earlier recommended rule. + * @see {@link https://typescript-eslint.io/users/configs#base} + */ +exports.default = (plugin, parser) => ({ + name: 'typescript-eslint/base', + languageOptions: { + parser, + sourceType: 'module', + }, + plugins: { + '@typescript-eslint': plugin, + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/disable-type-checked.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/disable-type-checked.d.ts new file mode 100644 index 00000000..446a037d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/disable-type-checked.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * A utility ruleset that will disable type-aware linting and all type-aware rules available in our project. + * @see {@link https://typescript-eslint.io/users/configs#disable-type-checked} + */ +declare const _default: (_plugin: FlatConfig.Plugin, _parser: FlatConfig.Parser) => FlatConfig.Config; +export default _default; +//# sourceMappingURL=disable-type-checked.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/disable-type-checked.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/disable-type-checked.d.ts.map new file mode 100644 index 00000000..21bb687b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/disable-type-checked.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"disable-type-checked.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/disable-type-checked.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAErE;;;GAGG;yBAED,SAAS,UAAU,CAAC,MAAM,EAC1B,SAAS,UAAU,CAAC,MAAM,KACzB,UAAU,CAAC,MAAM;AAHpB,wBAqEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/disable-type-checked.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/disable-type-checked.js new file mode 100644 index 00000000..9e895812 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/disable-type-checked.js @@ -0,0 +1,79 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * A utility ruleset that will disable type-aware linting and all type-aware rules available in our project. + * @see {@link https://typescript-eslint.io/users/configs#disable-type-checked} + */ +exports.default = (_plugin, _parser) => ({ + name: 'typescript-eslint/disable-type-checked', + rules: { + '@typescript-eslint/await-thenable': 'off', + '@typescript-eslint/consistent-return': 'off', + '@typescript-eslint/consistent-type-exports': 'off', + '@typescript-eslint/dot-notation': 'off', + '@typescript-eslint/naming-convention': 'off', + '@typescript-eslint/no-array-delete': 'off', + '@typescript-eslint/no-base-to-string': 'off', + '@typescript-eslint/no-confusing-void-expression': 'off', + '@typescript-eslint/no-deprecated': 'off', + '@typescript-eslint/no-duplicate-type-constituents': 'off', + '@typescript-eslint/no-floating-promises': 'off', + '@typescript-eslint/no-for-in-array': 'off', + '@typescript-eslint/no-implied-eval': 'off', + '@typescript-eslint/no-meaningless-void-operator': 'off', + '@typescript-eslint/no-misused-promises': 'off', + '@typescript-eslint/no-misused-spread': 'off', + '@typescript-eslint/no-mixed-enums': 'off', + '@typescript-eslint/no-redundant-type-constituents': 'off', + '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'off', + '@typescript-eslint/no-unnecessary-condition': 'off', + '@typescript-eslint/no-unnecessary-qualifier': 'off', + '@typescript-eslint/no-unnecessary-template-expression': 'off', + '@typescript-eslint/no-unnecessary-type-arguments': 'off', + '@typescript-eslint/no-unnecessary-type-assertion': 'off', + '@typescript-eslint/no-unnecessary-type-conversion': 'off', + '@typescript-eslint/no-unnecessary-type-parameters': 'off', + '@typescript-eslint/no-unsafe-argument': 'off', + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-unsafe-call': 'off', + '@typescript-eslint/no-unsafe-enum-comparison': 'off', + '@typescript-eslint/no-unsafe-member-access': 'off', + '@typescript-eslint/no-unsafe-return': 'off', + '@typescript-eslint/no-unsafe-type-assertion': 'off', + '@typescript-eslint/no-unsafe-unary-minus': 'off', + '@typescript-eslint/non-nullable-type-assertion-style': 'off', + '@typescript-eslint/only-throw-error': 'off', + '@typescript-eslint/prefer-destructuring': 'off', + '@typescript-eslint/prefer-find': 'off', + '@typescript-eslint/prefer-includes': 'off', + '@typescript-eslint/prefer-nullish-coalescing': 'off', + '@typescript-eslint/prefer-optional-chain': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-readonly': 'off', + '@typescript-eslint/prefer-readonly-parameter-types': 'off', + '@typescript-eslint/prefer-reduce-type-parameter': 'off', + '@typescript-eslint/prefer-regexp-exec': 'off', + '@typescript-eslint/prefer-return-this-type': 'off', + '@typescript-eslint/prefer-string-starts-ends-with': 'off', + '@typescript-eslint/promise-function-async': 'off', + '@typescript-eslint/related-getter-setter-pairs': 'off', + '@typescript-eslint/require-array-sort-compare': 'off', + '@typescript-eslint/require-await': 'off', + '@typescript-eslint/restrict-plus-operands': 'off', + '@typescript-eslint/restrict-template-expressions': 'off', + '@typescript-eslint/return-await': 'off', + '@typescript-eslint/strict-boolean-expressions': 'off', + '@typescript-eslint/switch-exhaustiveness-check': 'off', + '@typescript-eslint/unbound-method': 'off', + '@typescript-eslint/use-unknown-in-catch-callback-variable': 'off', + }, + languageOptions: { + parserOptions: { program: null, project: false, projectService: false }, + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/eslint-recommended.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/eslint-recommended.d.ts new file mode 100644 index 00000000..f1d26320 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/eslint-recommended.d.ts @@ -0,0 +1,10 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * This is a compatibility ruleset that: + * - disables rules from eslint:recommended which are already handled by TypeScript. + * - enables rules that make sense due to TS's typechecking / transpilation. + * @see {@link https://typescript-eslint.io/users/configs/#eslint-recommended} + */ +declare const _default: (_plugin: FlatConfig.Plugin, _parser: FlatConfig.Parser) => FlatConfig.Config; +export default _default; +//# sourceMappingURL=eslint-recommended.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/eslint-recommended.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/eslint-recommended.d.ts.map new file mode 100644 index 00000000..d8ec4b1f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/eslint-recommended.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eslint-recommended.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/eslint-recommended.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAIrE;;;;;GAKG;yBAED,SAAS,UAAU,CAAC,MAAM,EAC1B,SAAS,UAAU,CAAC,MAAM,KACzB,UAAU,CAAC,MAAM;AAHpB,wBAMG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/eslint-recommended.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/eslint-recommended.js new file mode 100644 index 00000000..a1ad8490 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/eslint-recommended.js @@ -0,0 +1,16 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const eslint_recommended_raw_1 = __importDefault(require("../eslint-recommended-raw")); +/** + * This is a compatibility ruleset that: + * - disables rules from eslint:recommended which are already handled by TypeScript. + * - enables rules that make sense due to TS's typechecking / transpilation. + * @see {@link https://typescript-eslint.io/users/configs/#eslint-recommended} + */ +exports.default = (_plugin, _parser) => ({ + ...(0, eslint_recommended_raw_1.default)('minimatch'), + name: 'typescript-eslint/eslint-recommended', +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked-only.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked-only.d.ts new file mode 100644 index 00000000..154c5b96 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked-only.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * A version of `recommended` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked-only} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=recommended-type-checked-only.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked-only.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked-only.d.ts.map new file mode 100644 index 00000000..8f245a6c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked-only.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"recommended-type-checked-only.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/recommended-type-checked-only.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBAsCE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked-only.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked-only.js new file mode 100644 index 00000000..4e847b9a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked-only.js @@ -0,0 +1,53 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * A version of `recommended` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked-only} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/recommended-type-checked-only', + rules: { + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': 'error', + '@typescript-eslint/restrict-template-expressions': 'error', + '@typescript-eslint/unbound-method': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked.d.ts new file mode 100644 index 00000000..eff1bb91 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * Contains all of `recommended` along with additional recommended rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=recommended-type-checked.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked.d.ts.map new file mode 100644 index 00000000..17bb8b58 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"recommended-type-checked.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/recommended-type-checked.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBA6DE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked.js new file mode 100644 index 00000000..fee6ff7f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended-type-checked.js @@ -0,0 +1,76 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * Contains all of `recommended` along with additional recommended rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/recommended-type-checked', + rules: { + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/ban-ts-comment': 'error', + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-require-imports': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + '@typescript-eslint/prefer-as-const': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': 'error', + '@typescript-eslint/restrict-template-expressions': 'error', + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/unbound-method': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended.d.ts new file mode 100644 index 00000000..a4e4e4c1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * Recommended rules for code correctness that you can drop in without additional configuration. + * @see {@link https://typescript-eslint.io/users/configs#recommended} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=recommended.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended.d.ts.map new file mode 100644 index 00000000..261a6650 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"recommended.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/recommended.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBAkCE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended.js new file mode 100644 index 00000000..9977b3eb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/recommended.js @@ -0,0 +1,49 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * Recommended rules for code correctness that you can drop in without additional configuration. + * @see {@link https://typescript-eslint.io/users/configs#recommended} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/recommended', + rules: { + '@typescript-eslint/ban-ts-comment': 'error', + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-require-imports': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + '@typescript-eslint/prefer-as-const': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + '@typescript-eslint/triple-slash-reference': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked-only.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked-only.d.ts new file mode 100644 index 00000000..c23c69e6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked-only.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * A version of `strict` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked-only} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=strict-type-checked-only.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked-only.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked-only.d.ts.map new file mode 100644 index 00000000..e535aa1f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked-only.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"strict-type-checked-only.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/strict-type-checked-only.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBA4EE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked-only.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked-only.js new file mode 100644 index 00000000..89e8ff2b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked-only.js @@ -0,0 +1,91 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * A version of `strict` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked-only} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/strict-type-checked-only', + rules: { + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-confusing-void-expression': 'error', + '@typescript-eslint/no-deprecated': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-meaningless-void-operator': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-misused-spread': 'error', + '@typescript-eslint/no-mixed-enums': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', + '@typescript-eslint/no-unnecessary-condition': 'error', + '@typescript-eslint/no-unnecessary-template-expression': 'error', + '@typescript-eslint/no-unnecessary-type-arguments': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unnecessary-type-parameters': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + '@typescript-eslint/prefer-reduce-type-parameter': 'error', + '@typescript-eslint/prefer-return-this-type': 'error', + '@typescript-eslint/related-getter-setter-pairs': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': [ + 'error', + { + allowAny: false, + allowBoolean: false, + allowNullish: false, + allowNumberAndString: false, + allowRegExp: false, + }, + ], + '@typescript-eslint/restrict-template-expressions': [ + 'error', + { + allowAny: false, + allowBoolean: false, + allowNever: false, + allowNullish: false, + allowNumber: false, + allowRegExp: false, + }, + ], + 'no-return-await': 'off', + '@typescript-eslint/return-await': [ + 'error', + 'error-handling-correctness-only', + ], + '@typescript-eslint/unbound-method': 'error', + '@typescript-eslint/use-unknown-in-catch-callback-variable': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked.d.ts new file mode 100644 index 00000000..d40726dd --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * Contains all of `recommended`, `recommended-type-checked`, and `strict`, along with additional strict rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=strict-type-checked.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked.d.ts.map new file mode 100644 index 00000000..ee5a9c02 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"strict-type-checked.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/strict-type-checked.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBA+GE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked.js new file mode 100644 index 00000000..fdee6fcd --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict-type-checked.js @@ -0,0 +1,126 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * Contains all of `recommended`, `recommended-type-checked`, and `strict`, along with additional strict rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/strict-type-checked', + rules: { + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/ban-ts-comment': [ + 'error', + { minimumDescriptionLength: 10 }, + ], + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-array-delete': 'error', + '@typescript-eslint/no-base-to-string': 'error', + '@typescript-eslint/no-confusing-void-expression': 'error', + '@typescript-eslint/no-deprecated': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-duplicate-type-constituents': 'error', + '@typescript-eslint/no-dynamic-delete': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-extraneous-class': 'error', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + 'no-implied-eval': 'off', + '@typescript-eslint/no-implied-eval': 'error', + '@typescript-eslint/no-invalid-void-type': 'error', + '@typescript-eslint/no-meaningless-void-operator': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-misused-promises': 'error', + '@typescript-eslint/no-misused-spread': 'error', + '@typescript-eslint/no-mixed-enums': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-non-null-assertion': 'error', + '@typescript-eslint/no-redundant-type-constituents': 'error', + '@typescript-eslint/no-require-imports': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', + '@typescript-eslint/no-unnecessary-condition': 'error', + '@typescript-eslint/no-unnecessary-template-expression': 'error', + '@typescript-eslint/no-unnecessary-type-arguments': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unnecessary-type-parameters': 'error', + '@typescript-eslint/no-unsafe-argument': 'error', + '@typescript-eslint/no-unsafe-assignment': 'error', + '@typescript-eslint/no-unsafe-call': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-enum-comparison': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + '@typescript-eslint/no-unsafe-member-access': 'error', + '@typescript-eslint/no-unsafe-return': 'error', + '@typescript-eslint/no-unsafe-unary-minus': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + 'no-useless-constructor': 'off', + '@typescript-eslint/no-useless-constructor': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + 'no-throw-literal': 'off', + '@typescript-eslint/only-throw-error': 'error', + '@typescript-eslint/prefer-as-const': 'error', + '@typescript-eslint/prefer-literal-enum-member': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + 'prefer-promise-reject-errors': 'off', + '@typescript-eslint/prefer-promise-reject-errors': 'error', + '@typescript-eslint/prefer-reduce-type-parameter': 'error', + '@typescript-eslint/prefer-return-this-type': 'error', + '@typescript-eslint/related-getter-setter-pairs': 'error', + 'require-await': 'off', + '@typescript-eslint/require-await': 'error', + '@typescript-eslint/restrict-plus-operands': [ + 'error', + { + allowAny: false, + allowBoolean: false, + allowNullish: false, + allowNumberAndString: false, + allowRegExp: false, + }, + ], + '@typescript-eslint/restrict-template-expressions': [ + 'error', + { + allowAny: false, + allowBoolean: false, + allowNever: false, + allowNullish: false, + allowNumber: false, + allowRegExp: false, + }, + ], + 'no-return-await': 'off', + '@typescript-eslint/return-await': [ + 'error', + 'error-handling-correctness-only', + ], + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/unbound-method': 'error', + '@typescript-eslint/unified-signatures': 'error', + '@typescript-eslint/use-unknown-in-catch-callback-variable': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict.d.ts new file mode 100644 index 00000000..e4fc5d4e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * Contains all of `recommended`, as well as additional strict rules that can also catch bugs. + * @see {@link https://typescript-eslint.io/users/configs#strict} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=strict.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict.d.ts.map new file mode 100644 index 00000000..a400a4e7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"strict.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/strict.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBA8CE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict.js new file mode 100644 index 00000000..0f6ef3ab --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/strict.js @@ -0,0 +1,61 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * Contains all of `recommended`, as well as additional strict rules that can also catch bugs. + * @see {@link https://typescript-eslint.io/users/configs#strict} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/strict', + rules: { + '@typescript-eslint/ban-ts-comment': [ + 'error', + { minimumDescriptionLength: 10 }, + ], + 'no-array-constructor': 'off', + '@typescript-eslint/no-array-constructor': 'error', + '@typescript-eslint/no-duplicate-enum-values': 'error', + '@typescript-eslint/no-dynamic-delete': 'error', + '@typescript-eslint/no-empty-object-type': 'error', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-extra-non-null-assertion': 'error', + '@typescript-eslint/no-extraneous-class': 'error', + '@typescript-eslint/no-invalid-void-type': 'error', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-non-null-assertion': 'error', + '@typescript-eslint/no-require-imports': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-type-constraint': 'error', + '@typescript-eslint/no-unsafe-declaration-merging': 'error', + '@typescript-eslint/no-unsafe-function-type': 'error', + 'no-unused-expressions': 'off', + '@typescript-eslint/no-unused-expressions': 'error', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + 'no-useless-constructor': 'off', + '@typescript-eslint/no-useless-constructor': 'error', + '@typescript-eslint/no-wrapper-object-types': 'error', + '@typescript-eslint/prefer-as-const': 'error', + '@typescript-eslint/prefer-literal-enum-member': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/unified-signatures': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked-only.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked-only.d.ts new file mode 100644 index 00000000..220782c3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked-only.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * A version of `stylistic` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked-only} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=stylistic-type-checked-only.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked-only.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked-only.d.ts.map new file mode 100644 index 00000000..aabcf68b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked-only.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stylistic-type-checked-only.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/stylistic-type-checked-only.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBAoBE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked-only.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked-only.js new file mode 100644 index 00000000..a0c9d688 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked-only.js @@ -0,0 +1,35 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * A version of `stylistic` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked-only} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/stylistic-type-checked-only', + rules: { + 'dot-notation': 'off', + '@typescript-eslint/dot-notation': 'error', + '@typescript-eslint/non-nullable-type-assertion-style': 'error', + '@typescript-eslint/prefer-find': 'error', + '@typescript-eslint/prefer-includes': 'error', + '@typescript-eslint/prefer-nullish-coalescing': 'error', + '@typescript-eslint/prefer-optional-chain': 'error', + '@typescript-eslint/prefer-regexp-exec': 'error', + '@typescript-eslint/prefer-string-starts-ends-with': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked.d.ts new file mode 100644 index 00000000..0df5ad04 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * Contains all of `stylistic`, along with additional stylistic rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=stylistic-type-checked.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked.d.ts.map new file mode 100644 index 00000000..ce641a8a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stylistic-type-checked.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/stylistic-type-checked.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBAkCE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked.js new file mode 100644 index 00000000..86da57e8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic-type-checked.js @@ -0,0 +1,49 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * Contains all of `stylistic`, along with additional stylistic rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/stylistic-type-checked', + rules: { + '@typescript-eslint/adjacent-overload-signatures': 'error', + '@typescript-eslint/array-type': 'error', + '@typescript-eslint/ban-tslint-comment': 'error', + '@typescript-eslint/class-literal-property-style': 'error', + '@typescript-eslint/consistent-generic-constructors': 'error', + '@typescript-eslint/consistent-indexed-object-style': 'error', + '@typescript-eslint/consistent-type-assertions': 'error', + '@typescript-eslint/consistent-type-definitions': 'error', + 'dot-notation': 'off', + '@typescript-eslint/dot-notation': 'error', + '@typescript-eslint/no-confusing-non-null-assertion': 'error', + 'no-empty-function': 'off', + '@typescript-eslint/no-empty-function': 'error', + '@typescript-eslint/no-inferrable-types': 'error', + '@typescript-eslint/non-nullable-type-assertion-style': 'error', + '@typescript-eslint/prefer-find': 'error', + '@typescript-eslint/prefer-for-of': 'error', + '@typescript-eslint/prefer-function-type': 'error', + '@typescript-eslint/prefer-includes': 'error', + '@typescript-eslint/prefer-nullish-coalescing': 'error', + '@typescript-eslint/prefer-optional-chain': 'error', + '@typescript-eslint/prefer-regexp-exec': 'error', + '@typescript-eslint/prefer-string-starts-ends-with': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic.d.ts new file mode 100644 index 00000000..99730bf8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic.d.ts @@ -0,0 +1,8 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +/** + * Rules considered to be best practice for modern TypeScript codebases, but that do not impact program logic. + * @see {@link https://typescript-eslint.io/users/configs#stylistic} + */ +declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray; +export default _default; +//# sourceMappingURL=stylistic.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic.d.ts.map new file mode 100644 index 00000000..c6c532b2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stylistic.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/stylistic.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBAyBE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic.js b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic.js new file mode 100644 index 00000000..020fa87d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/stylistic.js @@ -0,0 +1,40 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// SEE https://typescript-eslint.io/users/configs +// +// For developers working in the typescript-eslint monorepo: +// You can regenerate it using `yarn generate:configs` +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const base_1 = __importDefault(require("./base")); +const eslint_recommended_1 = __importDefault(require("./eslint-recommended")); +/** + * Rules considered to be best practice for modern TypeScript codebases, but that do not impact program logic. + * @see {@link https://typescript-eslint.io/users/configs#stylistic} + */ +exports.default = (plugin, parser) => [ + (0, base_1.default)(plugin, parser), + (0, eslint_recommended_1.default)(plugin, parser), + { + name: 'typescript-eslint/stylistic', + rules: { + '@typescript-eslint/adjacent-overload-signatures': 'error', + '@typescript-eslint/array-type': 'error', + '@typescript-eslint/ban-tslint-comment': 'error', + '@typescript-eslint/class-literal-property-style': 'error', + '@typescript-eslint/consistent-generic-constructors': 'error', + '@typescript-eslint/consistent-indexed-object-style': 'error', + '@typescript-eslint/consistent-type-assertions': 'error', + '@typescript-eslint/consistent-type-definitions': 'error', + '@typescript-eslint/no-confusing-non-null-assertion': 'error', + 'no-empty-function': 'off', + '@typescript-eslint/no-empty-function': 'error', + '@typescript-eslint/no-inferrable-types': 'error', + '@typescript-eslint/prefer-for-of': 'error', + '@typescript-eslint/prefer-function-type': 'error', + }, + }, +]; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts new file mode 100644 index 00000000..341509cc --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts @@ -0,0 +1,843 @@ +declare const _default: { + configs: { + all: { + extends: string[]; + rules: { + '@typescript-eslint/adjacent-overload-signatures': "error"; + '@typescript-eslint/array-type': "error"; + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': "error"; + '@typescript-eslint/ban-tslint-comment': "error"; + '@typescript-eslint/class-literal-property-style': "error"; + 'class-methods-use-this': "off"; + '@typescript-eslint/class-methods-use-this': "error"; + '@typescript-eslint/consistent-generic-constructors': "error"; + '@typescript-eslint/consistent-indexed-object-style': "error"; + 'consistent-return': "off"; + '@typescript-eslint/consistent-return': "error"; + '@typescript-eslint/consistent-type-assertions': "error"; + '@typescript-eslint/consistent-type-definitions': "error"; + '@typescript-eslint/consistent-type-exports': "error"; + '@typescript-eslint/consistent-type-imports': "error"; + 'default-param-last': "off"; + '@typescript-eslint/default-param-last': "error"; + 'dot-notation': "off"; + '@typescript-eslint/dot-notation': "error"; + '@typescript-eslint/explicit-function-return-type': "error"; + '@typescript-eslint/explicit-member-accessibility': "error"; + '@typescript-eslint/explicit-module-boundary-types': "error"; + 'init-declarations': "off"; + '@typescript-eslint/init-declarations': "error"; + 'max-params': "off"; + '@typescript-eslint/max-params': "error"; + '@typescript-eslint/member-ordering': "error"; + '@typescript-eslint/method-signature-style': "error"; + '@typescript-eslint/naming-convention': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-confusing-non-null-assertion': "error"; + '@typescript-eslint/no-confusing-void-expression': "error"; + '@typescript-eslint/no-deprecated': "error"; + 'no-dupe-class-members': "off"; + '@typescript-eslint/no-dupe-class-members': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-dynamic-delete': "error"; + 'no-empty-function': "off"; + '@typescript-eslint/no-empty-function': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-extraneous-class': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-import-type-side-effects': "error"; + '@typescript-eslint/no-inferrable-types': "error"; + 'no-invalid-this': "off"; + '@typescript-eslint/no-invalid-this': "error"; + '@typescript-eslint/no-invalid-void-type': "error"; + 'no-loop-func': "off"; + '@typescript-eslint/no-loop-func': "error"; + 'no-magic-numbers': "off"; + '@typescript-eslint/no-magic-numbers': "error"; + '@typescript-eslint/no-meaningless-void-operator': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-misused-spread': "error"; + '@typescript-eslint/no-mixed-enums': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-non-null-assertion': "error"; + 'no-redeclare': "off"; + '@typescript-eslint/no-redeclare': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + 'no-restricted-imports': "off"; + '@typescript-eslint/no-restricted-imports': "error"; + '@typescript-eslint/no-restricted-types': "error"; + 'no-shadow': "off"; + '@typescript-eslint/no-shadow': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "error"; + '@typescript-eslint/no-unnecessary-condition': "error"; + '@typescript-eslint/no-unnecessary-parameter-property-assignment': "error"; + '@typescript-eslint/no-unnecessary-qualifier': "error"; + '@typescript-eslint/no-unnecessary-template-expression': "error"; + '@typescript-eslint/no-unnecessary-type-arguments': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unnecessary-type-conversion': "error"; + '@typescript-eslint/no-unnecessary-type-parameters': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-type-assertion': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + 'no-use-before-define': "off"; + '@typescript-eslint/no-use-before-define': "error"; + 'no-useless-constructor': "off"; + '@typescript-eslint/no-useless-constructor': "error"; + '@typescript-eslint/no-useless-empty-export': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + '@typescript-eslint/non-nullable-type-assertion-style': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/parameter-properties': "error"; + '@typescript-eslint/prefer-as-const': "error"; + 'prefer-destructuring': "off"; + '@typescript-eslint/prefer-destructuring': "error"; + '@typescript-eslint/prefer-enum-initializers': "error"; + '@typescript-eslint/prefer-find': "error"; + '@typescript-eslint/prefer-for-of': "error"; + '@typescript-eslint/prefer-function-type': "error"; + '@typescript-eslint/prefer-includes': "error"; + '@typescript-eslint/prefer-literal-enum-member': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + '@typescript-eslint/prefer-nullish-coalescing': "error"; + '@typescript-eslint/prefer-optional-chain': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + '@typescript-eslint/prefer-readonly': "error"; + '@typescript-eslint/prefer-readonly-parameter-types': "error"; + '@typescript-eslint/prefer-reduce-type-parameter': "error"; + '@typescript-eslint/prefer-regexp-exec': "error"; + '@typescript-eslint/prefer-return-this-type': "error"; + '@typescript-eslint/prefer-string-starts-ends-with': "error"; + '@typescript-eslint/promise-function-async': "error"; + '@typescript-eslint/related-getter-setter-pairs': "error"; + '@typescript-eslint/require-array-sort-compare': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + 'no-return-await': "off"; + '@typescript-eslint/return-await': "error"; + '@typescript-eslint/strict-boolean-expressions': "error"; + '@typescript-eslint/switch-exhaustiveness-check': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + '@typescript-eslint/unified-signatures': "error"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "error"; + }; + }; + base: { + parser: string; + parserOptions: { + sourceType: "module"; + }; + plugins: string[]; + }; + 'disable-type-checked': { + parserOptions: { + program: null; + project: false; + projectService: false; + }; + rules: { + '@typescript-eslint/await-thenable': "off"; + '@typescript-eslint/consistent-return': "off"; + '@typescript-eslint/consistent-type-exports': "off"; + '@typescript-eslint/dot-notation': "off"; + '@typescript-eslint/naming-convention': "off"; + '@typescript-eslint/no-array-delete': "off"; + '@typescript-eslint/no-base-to-string': "off"; + '@typescript-eslint/no-confusing-void-expression': "off"; + '@typescript-eslint/no-deprecated': "off"; + '@typescript-eslint/no-duplicate-type-constituents': "off"; + '@typescript-eslint/no-floating-promises': "off"; + '@typescript-eslint/no-for-in-array': "off"; + '@typescript-eslint/no-implied-eval': "off"; + '@typescript-eslint/no-meaningless-void-operator': "off"; + '@typescript-eslint/no-misused-promises': "off"; + '@typescript-eslint/no-misused-spread': "off"; + '@typescript-eslint/no-mixed-enums': "off"; + '@typescript-eslint/no-redundant-type-constituents': "off"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "off"; + '@typescript-eslint/no-unnecessary-condition': "off"; + '@typescript-eslint/no-unnecessary-qualifier': "off"; + '@typescript-eslint/no-unnecessary-template-expression': "off"; + '@typescript-eslint/no-unnecessary-type-arguments': "off"; + '@typescript-eslint/no-unnecessary-type-assertion': "off"; + '@typescript-eslint/no-unnecessary-type-conversion': "off"; + '@typescript-eslint/no-unnecessary-type-parameters': "off"; + '@typescript-eslint/no-unsafe-argument': "off"; + '@typescript-eslint/no-unsafe-assignment': "off"; + '@typescript-eslint/no-unsafe-call': "off"; + '@typescript-eslint/no-unsafe-enum-comparison': "off"; + '@typescript-eslint/no-unsafe-member-access': "off"; + '@typescript-eslint/no-unsafe-return': "off"; + '@typescript-eslint/no-unsafe-type-assertion': "off"; + '@typescript-eslint/no-unsafe-unary-minus': "off"; + '@typescript-eslint/non-nullable-type-assertion-style': "off"; + '@typescript-eslint/only-throw-error': "off"; + '@typescript-eslint/prefer-destructuring': "off"; + '@typescript-eslint/prefer-find': "off"; + '@typescript-eslint/prefer-includes': "off"; + '@typescript-eslint/prefer-nullish-coalescing': "off"; + '@typescript-eslint/prefer-optional-chain': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-readonly': "off"; + '@typescript-eslint/prefer-readonly-parameter-types': "off"; + '@typescript-eslint/prefer-reduce-type-parameter': "off"; + '@typescript-eslint/prefer-regexp-exec': "off"; + '@typescript-eslint/prefer-return-this-type': "off"; + '@typescript-eslint/prefer-string-starts-ends-with': "off"; + '@typescript-eslint/promise-function-async': "off"; + '@typescript-eslint/related-getter-setter-pairs': "off"; + '@typescript-eslint/require-array-sort-compare': "off"; + '@typescript-eslint/require-await': "off"; + '@typescript-eslint/restrict-plus-operands': "off"; + '@typescript-eslint/restrict-template-expressions': "off"; + '@typescript-eslint/return-await': "off"; + '@typescript-eslint/strict-boolean-expressions': "off"; + '@typescript-eslint/switch-exhaustiveness-check': "off"; + '@typescript-eslint/unbound-method': "off"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "off"; + }; + }; + 'eslint-recommended': { + overrides: { + files: string[]; + rules: Record; + }[]; + }; + recommended: { + extends: string[]; + rules: { + '@typescript-eslint/ban-ts-comment': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + }; + }; + 'recommended-requiring-type-checking': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + }; + }; + 'recommended-type-checked': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + }; + }; + 'recommended-type-checked-only': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + '@typescript-eslint/unbound-method': "error"; + }; + }; + strict: { + extends: string[]; + rules: { + '@typescript-eslint/ban-ts-comment': ["error", { + minimumDescriptionLength: number; + }]; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-dynamic-delete': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-extraneous-class': "error"; + '@typescript-eslint/no-invalid-void-type': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-non-null-assertion': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + 'no-useless-constructor': "off"; + '@typescript-eslint/no-useless-constructor': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-literal-enum-member': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unified-signatures': "error"; + }; + }; + 'strict-type-checked': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': ["error", { + minimumDescriptionLength: number; + }]; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-confusing-void-expression': "error"; + '@typescript-eslint/no-deprecated': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-dynamic-delete': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-extraneous-class': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-invalid-void-type': "error"; + '@typescript-eslint/no-meaningless-void-operator': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-misused-spread': "error"; + '@typescript-eslint/no-mixed-enums': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-non-null-assertion': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "error"; + '@typescript-eslint/no-unnecessary-condition': "error"; + '@typescript-eslint/no-unnecessary-template-expression': "error"; + '@typescript-eslint/no-unnecessary-type-arguments': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unnecessary-type-parameters': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + 'no-useless-constructor': "off"; + '@typescript-eslint/no-useless-constructor': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-literal-enum-member': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + '@typescript-eslint/prefer-reduce-type-parameter': "error"; + '@typescript-eslint/prefer-return-this-type': "error"; + '@typescript-eslint/related-getter-setter-pairs': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNullish: boolean; + allowNumberAndString: boolean; + allowRegExp: boolean; + }]; + '@typescript-eslint/restrict-template-expressions': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNever: boolean; + allowNullish: boolean; + allowNumber: boolean; + allowRegExp: boolean; + }]; + 'no-return-await': "off"; + '@typescript-eslint/return-await': ["error", string]; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + '@typescript-eslint/unified-signatures': "error"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "error"; + }; + }; + 'strict-type-checked-only': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-confusing-void-expression': "error"; + '@typescript-eslint/no-deprecated': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-meaningless-void-operator': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-misused-spread': "error"; + '@typescript-eslint/no-mixed-enums': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "error"; + '@typescript-eslint/no-unnecessary-condition': "error"; + '@typescript-eslint/no-unnecessary-template-expression': "error"; + '@typescript-eslint/no-unnecessary-type-arguments': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-parameters': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + '@typescript-eslint/prefer-reduce-type-parameter': "error"; + '@typescript-eslint/prefer-return-this-type': "error"; + '@typescript-eslint/related-getter-setter-pairs': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNullish: boolean; + allowNumberAndString: boolean; + allowRegExp: boolean; + }]; + '@typescript-eslint/restrict-template-expressions': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNever: boolean; + allowNullish: boolean; + allowNumber: boolean; + allowRegExp: boolean; + }]; + 'no-return-await': "off"; + '@typescript-eslint/return-await': ["error", string]; + '@typescript-eslint/unbound-method': "error"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "error"; + }; + }; + stylistic: { + extends: string[]; + rules: { + '@typescript-eslint/adjacent-overload-signatures': "error"; + '@typescript-eslint/array-type': "error"; + '@typescript-eslint/ban-tslint-comment': "error"; + '@typescript-eslint/class-literal-property-style': "error"; + '@typescript-eslint/consistent-generic-constructors': "error"; + '@typescript-eslint/consistent-indexed-object-style': "error"; + '@typescript-eslint/consistent-type-assertions': "error"; + '@typescript-eslint/consistent-type-definitions': "error"; + '@typescript-eslint/no-confusing-non-null-assertion': "error"; + 'no-empty-function': "off"; + '@typescript-eslint/no-empty-function': "error"; + '@typescript-eslint/no-inferrable-types': "error"; + '@typescript-eslint/prefer-for-of': "error"; + '@typescript-eslint/prefer-function-type': "error"; + }; + }; + 'stylistic-type-checked': { + extends: string[]; + rules: { + '@typescript-eslint/adjacent-overload-signatures': "error"; + '@typescript-eslint/array-type': "error"; + '@typescript-eslint/ban-tslint-comment': "error"; + '@typescript-eslint/class-literal-property-style': "error"; + '@typescript-eslint/consistent-generic-constructors': "error"; + '@typescript-eslint/consistent-indexed-object-style': "error"; + '@typescript-eslint/consistent-type-assertions': "error"; + '@typescript-eslint/consistent-type-definitions': "error"; + 'dot-notation': "off"; + '@typescript-eslint/dot-notation': "error"; + '@typescript-eslint/no-confusing-non-null-assertion': "error"; + 'no-empty-function': "off"; + '@typescript-eslint/no-empty-function': "error"; + '@typescript-eslint/no-inferrable-types': "error"; + '@typescript-eslint/non-nullable-type-assertion-style': "error"; + '@typescript-eslint/prefer-find': "error"; + '@typescript-eslint/prefer-for-of': "error"; + '@typescript-eslint/prefer-function-type': "error"; + '@typescript-eslint/prefer-includes': "error"; + '@typescript-eslint/prefer-nullish-coalescing': "error"; + '@typescript-eslint/prefer-optional-chain': "error"; + '@typescript-eslint/prefer-regexp-exec': "error"; + '@typescript-eslint/prefer-string-starts-ends-with': "error"; + }; + }; + 'stylistic-type-checked-only': { + extends: string[]; + rules: { + 'dot-notation': "off"; + '@typescript-eslint/dot-notation': "error"; + '@typescript-eslint/non-nullable-type-assertion-style': "error"; + '@typescript-eslint/prefer-find': "error"; + '@typescript-eslint/prefer-includes': "error"; + '@typescript-eslint/prefer-nullish-coalescing': "error"; + '@typescript-eslint/prefer-optional-chain': "error"; + '@typescript-eslint/prefer-regexp-exec': "error"; + '@typescript-eslint/prefer-string-starts-ends-with': "error"; + }; + }; + }; + meta: { + name: string; + version: string; + }; + rules: { + 'adjacent-overload-signatures': import("@typescript-eslint/utils/ts-eslint").RuleModule<"adjacentSignature", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'array-type': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'await-thenable': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'ban-ts-comment': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'ban-tslint-comment': import("@typescript-eslint/utils/ts-eslint").RuleModule<"commentDetected", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'class-literal-property-style': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'class-methods-use-this': import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingThis", import("./rules/class-methods-use-this").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'consistent-generic-constructors': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'consistent-indexed-object-style': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'consistent-return': import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingReturn" | "missingReturnValue" | "unexpectedReturnValue", [({ + treatUndefinedAsUnspecified?: boolean; + } | undefined)?], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'consistent-type-assertions': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'consistent-type-definitions': import("@typescript-eslint/utils/ts-eslint").RuleModule<"interfaceOverType" | "typeOverInterface", [string], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'consistent-type-exports': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'consistent-type-imports': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'default-param-last': import("@typescript-eslint/utils/ts-eslint").RuleModule<"shouldBeLast", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'dot-notation': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useBrackets" | "useDot", [{ + allowIndexSignaturePropertyAccess?: boolean; + allowKeywords?: boolean; + allowPattern?: string; + allowPrivateClassPropertyAccess?: boolean; + allowProtectedClassPropertyAccess?: boolean; + }], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'explicit-function-return-type': import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingReturnType", import("./rules/explicit-function-return-type").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'explicit-member-accessibility': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'explicit-module-boundary-types': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'init-declarations': import("@typescript-eslint/utils/ts-eslint").RuleModule<"initialized" | "notInitialized", ["always" | "never", ({ + ignoreForLoopInit?: boolean; + } | undefined)?], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'max-params': import("@typescript-eslint/utils/ts-eslint").RuleModule<"exceed", ({ + countVoidThis?: boolean; + max: number; + } | { + countVoidThis?: boolean; + maximum: number; + })[], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'member-ordering': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'method-signature-style': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'naming-convention': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-array-constructor': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useLiteral", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-array-delete': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-base-to-string': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-confusing-non-null-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-confusing-void-expression': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-deprecated': import("@typescript-eslint/utils/ts-eslint").RuleModule<"deprecated" | "deprecatedWithReason", [{ + allow?: import("@typescript-eslint/type-utils").TypeOrValueSpecifier[]; + }], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-dupe-class-members': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpected", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-duplicate-enum-values': import("@typescript-eslint/utils/ts-eslint").RuleModule<"duplicateValue", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-duplicate-type-constituents': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-dynamic-delete': import("@typescript-eslint/utils/ts-eslint").RuleModule<"dynamicDelete", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-empty-function': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpected", [{ + allow?: string[]; + }], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-empty-interface': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-empty-object-type': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-explicit-any': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-extra-non-null-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noExtraNonNullAssertion", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-extraneous-class': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-floating-promises': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-for-in-array': import("@typescript-eslint/utils/ts-eslint").RuleModule<"forInViolation", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-implied-eval': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noFunctionConstructor" | "noImpliedEvalError", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-import-type-side-effects': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useTopLevelQualifier", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-inferrable-types': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noInferrableType", import("./rules/no-inferrable-types").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-invalid-this': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpectedThis", [({ + capIsConstructor?: boolean; + } | undefined)?], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-invalid-void-type': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-loop-func': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeRefs", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-loss-of-precision': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noLossOfPrecision", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-magic-numbers': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noMagic", [{ + detectObjects?: boolean; + enforceConst?: boolean; + ignore?: (number | string)[]; + ignoreArrayIndexes?: boolean; + ignoreEnums?: boolean; + ignoreNumericLiteralTypes?: boolean; + ignoreReadonlyClassProperties?: boolean; + ignoreTypeIndexes?: boolean; + }], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-meaningless-void-operator': import("@typescript-eslint/utils/ts-eslint").RuleModule<"meaninglessVoidOperator" | "removeVoid", import("./rules/no-meaningless-void-operator").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-misused-new': import("@typescript-eslint/utils/ts-eslint").RuleModule<"errorMessageClass" | "errorMessageInterface", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-misused-promises': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-misused-spread': import("@typescript-eslint/utils/ts-eslint").RuleModule<"addAwait" | "noArraySpreadInObject" | "noClassDeclarationSpreadInObject" | "noClassInstanceSpreadInObject" | "noFunctionSpreadInObject" | "noIterableSpreadInObject" | "noMapSpreadInObject" | "noPromiseSpreadInObject" | "noStringSpread" | "replaceMapSpreadInObject", [{ + allow?: import("@typescript-eslint/type-utils").TypeOrValueSpecifier[]; + }], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-mixed-enums': import("@typescript-eslint/utils/ts-eslint").RuleModule<"mixed", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-namespace': import("@typescript-eslint/utils/ts-eslint").RuleModule<"moduleSyntaxIsPreferred", import("./rules/no-namespace").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-non-null-asserted-nullish-coalescing': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noNonNullAssertedNullishCoalescing" | "suggestRemovingNonNull", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-non-null-asserted-optional-chain': import("@typescript-eslint/utils/ts-eslint").RuleModule<"suggestRemovingNonNull" | "noNonNullOptionalChain", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-non-null-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-redeclare': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-redundant-type-constituents': import("@typescript-eslint/utils/ts-eslint").RuleModule<"overrides" | "errorTypeOverrides" | "literalOverridden" | "overridden" | "primitiveOverridden", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-require-imports': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noRequireImports", import("./rules/no-require-imports").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-restricted-imports': import("@typescript-eslint/utils/ts-eslint").RuleModule<"everything" | "everythingWithCustomMessage" | "importName" | "importNameWithCustomMessage" | "path" | "pathWithCustomMessage" | "patterns" | "patternWithCustomMessage", [import("eslint/lib/rules/no-restricted-imports").ObjectOfPathsAndPatterns] | import("eslint/lib/rules/no-restricted-imports").ArrayOfStringOrObject, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-restricted-types': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-shadow': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-this-alias': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-type-alias': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unnecessary-boolean-literal-compare': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unnecessary-condition': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unnecessary-parameter-property-assignment': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unnecessaryAssign", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-qualifier': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unnecessaryQualifier", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-template-expression': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noUnnecessaryTemplateExpression", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-type-arguments': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unnecessaryTypeParameter", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-type-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unnecessary-type-constraint': import("@typescript-eslint/utils/ts-eslint").RuleModule<"removeUnnecessaryConstraint" | "unnecessaryConstraint", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-type-conversion': import("@typescript-eslint/utils/ts-eslint").RuleModule<"suggestRemove" | "suggestSatisfies" | "unnecessaryTypeConversion", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-type-parameters': import("@typescript-eslint/utils/ts-eslint").RuleModule<"replaceUsagesWithConstraint" | "sole", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-argument': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unsafe-assignment': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeArraySpread" | "anyAssignment" | "anyAssignmentThis" | "unsafeArrayPattern" | "unsafeArrayPatternFromTuple" | "unsafeAssignment", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-call': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unsafe-declaration-merging': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeMerging", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-enum-comparison': import("@typescript-eslint/utils/ts-eslint").RuleModule<"mismatchedCase" | "mismatchedCondition" | "replaceValueWithEnum", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-function-type': import("@typescript-eslint/utils/ts-eslint").RuleModule<"bannedFunctionType", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-member-access': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeComputedMemberAccess" | "unsafeMemberExpression" | "unsafeThisMemberExpression", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-return': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeReturn" | "unsafeReturnAssignment" | "unsafeReturnThis", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-type-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeOfAnyTypeAssertion" | "unsafeToAnyTypeAssertion" | "unsafeToUnconstrainedTypeAssertion" | "unsafeTypeAssertion" | "unsafeTypeAssertionAssignableToConstraint", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-unary-minus': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unaryMinus", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unused-expressions': import("@typescript-eslint/utils/ts-eslint").RuleModule<"expected", [{ + allowShortCircuit?: boolean; + allowTaggedTemplates?: boolean; + allowTernary?: boolean; + }], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unused-vars': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-use-before-define': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noUseBeforeDefine", import("./rules/no-use-before-define").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-useless-constructor': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noUselessConstructor" | "removeConstructor", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-useless-empty-export': import("@typescript-eslint/utils/ts-eslint").RuleModule<"uselessExport", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-var-requires': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noVarReqs", import("./rules/no-var-requires").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-wrapper-object-types': import("@typescript-eslint/utils/ts-eslint").RuleModule<"bannedClassType", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'non-nullable-type-assertion-style': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferNonNullAssertion", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'only-throw-error': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'parameter-properties': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-as-const': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferConstAssertion" | "variableConstAssertion" | "variableSuggest", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-destructuring': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferDestructuring", import("./rules/prefer-destructuring").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-enum-initializers': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-find': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferFind" | "preferFindSuggestion", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-for-of': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferForOf", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-function-type': import("@typescript-eslint/utils/ts-eslint").RuleModule<"functionTypeOverCallableType" | "unexpectedThisOnFunctionOnlyInterface", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-includes': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferIncludes" | "preferStringIncludes", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-literal-enum-member': import("@typescript-eslint/utils/ts-eslint").RuleModule<"notLiteral" | "notLiteralOrBitwiseExpression", [{ + allowBitwiseExpressions: boolean; + }], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-namespace-keyword': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useNamespace", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-nullish-coalescing': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-optional-chain': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-promise-reject-errors': import("@typescript-eslint/utils/ts-eslint").RuleModule<"rejectAnError", import("./rules/prefer-promise-reject-errors").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-readonly': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferReadonly", import("./rules/prefer-readonly").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-readonly-parameter-types': import("@typescript-eslint/utils/ts-eslint").RuleModule<"shouldBeReadonly", import("./rules/prefer-readonly-parameter-types").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-reduce-type-parameter': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferTypeParameter", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-regexp-exec': import("@typescript-eslint/utils/ts-eslint").RuleModule<"regExpExecOverStringMatch", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-return-this-type': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useThisType", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-string-starts-ends-with': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-ts-expect-error': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferExpectErrorComment", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'promise-function-async': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'related-getter-setter-pairs': import("@typescript-eslint/utils/ts-eslint").RuleModule<"mismatch", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'require-array-sort-compare': import("@typescript-eslint/utils/ts-eslint").RuleModule<"requireCompare", import("./rules/require-array-sort-compare").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'require-await': import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingAwait" | "removeAsync", [], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'restrict-plus-operands': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'restrict-template-expressions': import("@typescript-eslint/utils/ts-eslint").RuleModule<"invalidType", import("./rules/restrict-template-expressions").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'return-await': import("@typescript-eslint/utils/ts-eslint").RuleModule<"disallowedPromiseAwait" | "disallowedPromiseAwaitSuggestion" | "nonPromiseAwait" | "requiredPromiseAwait" | "requiredPromiseAwaitSuggestion", [string], import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'sort-type-constituents': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'strict-boolean-expressions': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'switch-exhaustiveness-check': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'triple-slash-reference': import("@typescript-eslint/utils/ts-eslint").RuleModule<"tripleSlashReference", import("./rules/triple-slash-reference").Options, import("../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + typedef: import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'unbound-method': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'unified-signatures': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'use-unknown-in-catch-callback-variable': import("@typescript-eslint/utils/ts-eslint").RuleModule; + }; +}; +export = _default; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts.map new file mode 100644 index 00000000..a775874e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,kBAA0B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/index.js b/node_modules/@typescript-eslint/eslint-plugin/dist/index.js new file mode 100644 index 00000000..dd949b42 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/index.js @@ -0,0 +1,6 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const raw_plugin_1 = __importDefault(require("./raw-plugin")); +module.exports = raw_plugin_1.default.plugin; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts new file mode 100644 index 00000000..75c8c919 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts @@ -0,0 +1,867 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; +declare const _default: { + flatConfigs: { + 'flat/all': FlatConfig.ConfigArray; + 'flat/base': FlatConfig.Config; + 'flat/disable-type-checked': FlatConfig.Config; + 'flat/eslint-recommended': FlatConfig.Config; + 'flat/recommended': FlatConfig.ConfigArray; + 'flat/recommended-type-checked': FlatConfig.ConfigArray; + 'flat/recommended-type-checked-only': FlatConfig.ConfigArray; + 'flat/strict': FlatConfig.ConfigArray; + 'flat/strict-type-checked': FlatConfig.ConfigArray; + 'flat/strict-type-checked-only': FlatConfig.ConfigArray; + 'flat/stylistic': FlatConfig.ConfigArray; + 'flat/stylistic-type-checked': FlatConfig.ConfigArray; + 'flat/stylistic-type-checked-only': FlatConfig.ConfigArray; + }; + parser: { + meta?: { [K in keyof TSESLint.Parser.ParserMeta]?: TSESLint.Parser.ParserMeta[K] | undefined; }; + parseForESLint(text: string, options?: unknown): { [k in keyof TSESLint.Parser.ParseResult]: unknown; }; + }; + plugin: { + configs: { + all: { + extends: string[]; + rules: { + '@typescript-eslint/adjacent-overload-signatures': "error"; + '@typescript-eslint/array-type': "error"; + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': "error"; + '@typescript-eslint/ban-tslint-comment': "error"; + '@typescript-eslint/class-literal-property-style': "error"; + 'class-methods-use-this': "off"; + '@typescript-eslint/class-methods-use-this': "error"; + '@typescript-eslint/consistent-generic-constructors': "error"; + '@typescript-eslint/consistent-indexed-object-style': "error"; + 'consistent-return': "off"; + '@typescript-eslint/consistent-return': "error"; + '@typescript-eslint/consistent-type-assertions': "error"; + '@typescript-eslint/consistent-type-definitions': "error"; + '@typescript-eslint/consistent-type-exports': "error"; + '@typescript-eslint/consistent-type-imports': "error"; + 'default-param-last': "off"; + '@typescript-eslint/default-param-last': "error"; + 'dot-notation': "off"; + '@typescript-eslint/dot-notation': "error"; + '@typescript-eslint/explicit-function-return-type': "error"; + '@typescript-eslint/explicit-member-accessibility': "error"; + '@typescript-eslint/explicit-module-boundary-types': "error"; + 'init-declarations': "off"; + '@typescript-eslint/init-declarations': "error"; + 'max-params': "off"; + '@typescript-eslint/max-params': "error"; + '@typescript-eslint/member-ordering': "error"; + '@typescript-eslint/method-signature-style': "error"; + '@typescript-eslint/naming-convention': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-confusing-non-null-assertion': "error"; + '@typescript-eslint/no-confusing-void-expression': "error"; + '@typescript-eslint/no-deprecated': "error"; + 'no-dupe-class-members': "off"; + '@typescript-eslint/no-dupe-class-members': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-dynamic-delete': "error"; + 'no-empty-function': "off"; + '@typescript-eslint/no-empty-function': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-extraneous-class': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-import-type-side-effects': "error"; + '@typescript-eslint/no-inferrable-types': "error"; + 'no-invalid-this': "off"; + '@typescript-eslint/no-invalid-this': "error"; + '@typescript-eslint/no-invalid-void-type': "error"; + 'no-loop-func': "off"; + '@typescript-eslint/no-loop-func': "error"; + 'no-magic-numbers': "off"; + '@typescript-eslint/no-magic-numbers': "error"; + '@typescript-eslint/no-meaningless-void-operator': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-misused-spread': "error"; + '@typescript-eslint/no-mixed-enums': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-non-null-assertion': "error"; + 'no-redeclare': "off"; + '@typescript-eslint/no-redeclare': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + 'no-restricted-imports': "off"; + '@typescript-eslint/no-restricted-imports': "error"; + '@typescript-eslint/no-restricted-types': "error"; + 'no-shadow': "off"; + '@typescript-eslint/no-shadow': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "error"; + '@typescript-eslint/no-unnecessary-condition': "error"; + '@typescript-eslint/no-unnecessary-parameter-property-assignment': "error"; + '@typescript-eslint/no-unnecessary-qualifier': "error"; + '@typescript-eslint/no-unnecessary-template-expression': "error"; + '@typescript-eslint/no-unnecessary-type-arguments': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unnecessary-type-conversion': "error"; + '@typescript-eslint/no-unnecessary-type-parameters': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-type-assertion': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + 'no-use-before-define': "off"; + '@typescript-eslint/no-use-before-define': "error"; + 'no-useless-constructor': "off"; + '@typescript-eslint/no-useless-constructor': "error"; + '@typescript-eslint/no-useless-empty-export': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + '@typescript-eslint/non-nullable-type-assertion-style': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/parameter-properties': "error"; + '@typescript-eslint/prefer-as-const': "error"; + 'prefer-destructuring': "off"; + '@typescript-eslint/prefer-destructuring': "error"; + '@typescript-eslint/prefer-enum-initializers': "error"; + '@typescript-eslint/prefer-find': "error"; + '@typescript-eslint/prefer-for-of': "error"; + '@typescript-eslint/prefer-function-type': "error"; + '@typescript-eslint/prefer-includes': "error"; + '@typescript-eslint/prefer-literal-enum-member': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + '@typescript-eslint/prefer-nullish-coalescing': "error"; + '@typescript-eslint/prefer-optional-chain': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + '@typescript-eslint/prefer-readonly': "error"; + '@typescript-eslint/prefer-readonly-parameter-types': "error"; + '@typescript-eslint/prefer-reduce-type-parameter': "error"; + '@typescript-eslint/prefer-regexp-exec': "error"; + '@typescript-eslint/prefer-return-this-type': "error"; + '@typescript-eslint/prefer-string-starts-ends-with': "error"; + '@typescript-eslint/promise-function-async': "error"; + '@typescript-eslint/related-getter-setter-pairs': "error"; + '@typescript-eslint/require-array-sort-compare': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + 'no-return-await': "off"; + '@typescript-eslint/return-await': "error"; + '@typescript-eslint/strict-boolean-expressions': "error"; + '@typescript-eslint/switch-exhaustiveness-check': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + '@typescript-eslint/unified-signatures': "error"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "error"; + }; + }; + base: { + parser: string; + parserOptions: { + sourceType: "module"; + }; + plugins: string[]; + }; + 'disable-type-checked': { + parserOptions: { + program: null; + project: false; + projectService: false; + }; + rules: { + '@typescript-eslint/await-thenable': "off"; + '@typescript-eslint/consistent-return': "off"; + '@typescript-eslint/consistent-type-exports': "off"; + '@typescript-eslint/dot-notation': "off"; + '@typescript-eslint/naming-convention': "off"; + '@typescript-eslint/no-array-delete': "off"; + '@typescript-eslint/no-base-to-string': "off"; + '@typescript-eslint/no-confusing-void-expression': "off"; + '@typescript-eslint/no-deprecated': "off"; + '@typescript-eslint/no-duplicate-type-constituents': "off"; + '@typescript-eslint/no-floating-promises': "off"; + '@typescript-eslint/no-for-in-array': "off"; + '@typescript-eslint/no-implied-eval': "off"; + '@typescript-eslint/no-meaningless-void-operator': "off"; + '@typescript-eslint/no-misused-promises': "off"; + '@typescript-eslint/no-misused-spread': "off"; + '@typescript-eslint/no-mixed-enums': "off"; + '@typescript-eslint/no-redundant-type-constituents': "off"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "off"; + '@typescript-eslint/no-unnecessary-condition': "off"; + '@typescript-eslint/no-unnecessary-qualifier': "off"; + '@typescript-eslint/no-unnecessary-template-expression': "off"; + '@typescript-eslint/no-unnecessary-type-arguments': "off"; + '@typescript-eslint/no-unnecessary-type-assertion': "off"; + '@typescript-eslint/no-unnecessary-type-conversion': "off"; + '@typescript-eslint/no-unnecessary-type-parameters': "off"; + '@typescript-eslint/no-unsafe-argument': "off"; + '@typescript-eslint/no-unsafe-assignment': "off"; + '@typescript-eslint/no-unsafe-call': "off"; + '@typescript-eslint/no-unsafe-enum-comparison': "off"; + '@typescript-eslint/no-unsafe-member-access': "off"; + '@typescript-eslint/no-unsafe-return': "off"; + '@typescript-eslint/no-unsafe-type-assertion': "off"; + '@typescript-eslint/no-unsafe-unary-minus': "off"; + '@typescript-eslint/non-nullable-type-assertion-style': "off"; + '@typescript-eslint/only-throw-error': "off"; + '@typescript-eslint/prefer-destructuring': "off"; + '@typescript-eslint/prefer-find': "off"; + '@typescript-eslint/prefer-includes': "off"; + '@typescript-eslint/prefer-nullish-coalescing': "off"; + '@typescript-eslint/prefer-optional-chain': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-readonly': "off"; + '@typescript-eslint/prefer-readonly-parameter-types': "off"; + '@typescript-eslint/prefer-reduce-type-parameter': "off"; + '@typescript-eslint/prefer-regexp-exec': "off"; + '@typescript-eslint/prefer-return-this-type': "off"; + '@typescript-eslint/prefer-string-starts-ends-with': "off"; + '@typescript-eslint/promise-function-async': "off"; + '@typescript-eslint/related-getter-setter-pairs': "off"; + '@typescript-eslint/require-array-sort-compare': "off"; + '@typescript-eslint/require-await': "off"; + '@typescript-eslint/restrict-plus-operands': "off"; + '@typescript-eslint/restrict-template-expressions': "off"; + '@typescript-eslint/return-await': "off"; + '@typescript-eslint/strict-boolean-expressions': "off"; + '@typescript-eslint/switch-exhaustiveness-check': "off"; + '@typescript-eslint/unbound-method': "off"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "off"; + }; + }; + 'eslint-recommended': { + overrides: { + files: string[]; + rules: Record; + }[]; + }; + recommended: { + extends: string[]; + rules: { + '@typescript-eslint/ban-ts-comment': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + }; + }; + /** @deprecated - please use "recommended-type-checked" instead. */ + 'recommended-requiring-type-checking': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + }; + }; + 'recommended-type-checked': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': "error"; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + }; + }; + 'recommended-type-checked-only': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': "error"; + '@typescript-eslint/restrict-template-expressions': "error"; + '@typescript-eslint/unbound-method': "error"; + }; + }; + strict: { + extends: string[]; + rules: { + '@typescript-eslint/ban-ts-comment': ["error", { + minimumDescriptionLength: number; + }]; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-dynamic-delete': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-extraneous-class': "error"; + '@typescript-eslint/no-invalid-void-type': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-non-null-assertion': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + 'no-useless-constructor': "off"; + '@typescript-eslint/no-useless-constructor': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-literal-enum-member': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unified-signatures': "error"; + }; + }; + 'strict-type-checked': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/ban-ts-comment': ["error", { + minimumDescriptionLength: number; + }]; + 'no-array-constructor': "off"; + '@typescript-eslint/no-array-constructor': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-confusing-void-expression': "error"; + '@typescript-eslint/no-deprecated': "error"; + '@typescript-eslint/no-duplicate-enum-values': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-dynamic-delete': "error"; + '@typescript-eslint/no-empty-object-type': "error"; + '@typescript-eslint/no-explicit-any': "error"; + '@typescript-eslint/no-extra-non-null-assertion': "error"; + '@typescript-eslint/no-extraneous-class': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-invalid-void-type': "error"; + '@typescript-eslint/no-meaningless-void-operator': "error"; + '@typescript-eslint/no-misused-new': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-misused-spread': "error"; + '@typescript-eslint/no-mixed-enums': "error"; + '@typescript-eslint/no-namespace': "error"; + '@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error"; + '@typescript-eslint/no-non-null-asserted-optional-chain': "error"; + '@typescript-eslint/no-non-null-assertion': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-require-imports': "error"; + '@typescript-eslint/no-this-alias': "error"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "error"; + '@typescript-eslint/no-unnecessary-condition': "error"; + '@typescript-eslint/no-unnecessary-template-expression': "error"; + '@typescript-eslint/no-unnecessary-type-arguments': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-constraint': "error"; + '@typescript-eslint/no-unnecessary-type-parameters': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-declaration-merging': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-function-type': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-unused-expressions': "off"; + '@typescript-eslint/no-unused-expressions': "error"; + 'no-unused-vars': "off"; + '@typescript-eslint/no-unused-vars': "error"; + 'no-useless-constructor': "off"; + '@typescript-eslint/no-useless-constructor': "error"; + '@typescript-eslint/no-wrapper-object-types': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + '@typescript-eslint/prefer-as-const': "error"; + '@typescript-eslint/prefer-literal-enum-member': "error"; + '@typescript-eslint/prefer-namespace-keyword': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + '@typescript-eslint/prefer-reduce-type-parameter': "error"; + '@typescript-eslint/prefer-return-this-type': "error"; + '@typescript-eslint/related-getter-setter-pairs': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNullish: boolean; + allowNumberAndString: boolean; + allowRegExp: boolean; + }]; + '@typescript-eslint/restrict-template-expressions': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNever: boolean; + allowNullish: boolean; + allowNumber: boolean; + allowRegExp: boolean; + }]; + 'no-return-await': "off"; + '@typescript-eslint/return-await': ["error", string]; + '@typescript-eslint/triple-slash-reference': "error"; + '@typescript-eslint/unbound-method': "error"; + '@typescript-eslint/unified-signatures': "error"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "error"; + }; + }; + 'strict-type-checked-only': { + extends: string[]; + rules: { + '@typescript-eslint/await-thenable': "error"; + '@typescript-eslint/no-array-delete': "error"; + '@typescript-eslint/no-base-to-string': "error"; + '@typescript-eslint/no-confusing-void-expression': "error"; + '@typescript-eslint/no-deprecated': "error"; + '@typescript-eslint/no-duplicate-type-constituents': "error"; + '@typescript-eslint/no-floating-promises': "error"; + '@typescript-eslint/no-for-in-array': "error"; + 'no-implied-eval': "off"; + '@typescript-eslint/no-implied-eval': "error"; + '@typescript-eslint/no-meaningless-void-operator': "error"; + '@typescript-eslint/no-misused-promises': "error"; + '@typescript-eslint/no-misused-spread': "error"; + '@typescript-eslint/no-mixed-enums': "error"; + '@typescript-eslint/no-redundant-type-constituents': "error"; + '@typescript-eslint/no-unnecessary-boolean-literal-compare': "error"; + '@typescript-eslint/no-unnecessary-condition': "error"; + '@typescript-eslint/no-unnecessary-template-expression': "error"; + '@typescript-eslint/no-unnecessary-type-arguments': "error"; + '@typescript-eslint/no-unnecessary-type-assertion': "error"; + '@typescript-eslint/no-unnecessary-type-parameters': "error"; + '@typescript-eslint/no-unsafe-argument': "error"; + '@typescript-eslint/no-unsafe-assignment': "error"; + '@typescript-eslint/no-unsafe-call': "error"; + '@typescript-eslint/no-unsafe-enum-comparison': "error"; + '@typescript-eslint/no-unsafe-member-access': "error"; + '@typescript-eslint/no-unsafe-return': "error"; + '@typescript-eslint/no-unsafe-unary-minus': "error"; + 'no-throw-literal': "off"; + '@typescript-eslint/only-throw-error': "error"; + 'prefer-promise-reject-errors': "off"; + '@typescript-eslint/prefer-promise-reject-errors': "error"; + '@typescript-eslint/prefer-reduce-type-parameter': "error"; + '@typescript-eslint/prefer-return-this-type': "error"; + '@typescript-eslint/related-getter-setter-pairs': "error"; + 'require-await': "off"; + '@typescript-eslint/require-await': "error"; + '@typescript-eslint/restrict-plus-operands': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNullish: boolean; + allowNumberAndString: boolean; + allowRegExp: boolean; + }]; + '@typescript-eslint/restrict-template-expressions': ["error", { + allowAny: boolean; + allowBoolean: boolean; + allowNever: boolean; + allowNullish: boolean; + allowNumber: boolean; + allowRegExp: boolean; + }]; + 'no-return-await': "off"; + '@typescript-eslint/return-await': ["error", string]; + '@typescript-eslint/unbound-method': "error"; + '@typescript-eslint/use-unknown-in-catch-callback-variable': "error"; + }; + }; + stylistic: { + extends: string[]; + rules: { + '@typescript-eslint/adjacent-overload-signatures': "error"; + '@typescript-eslint/array-type': "error"; + '@typescript-eslint/ban-tslint-comment': "error"; + '@typescript-eslint/class-literal-property-style': "error"; + '@typescript-eslint/consistent-generic-constructors': "error"; + '@typescript-eslint/consistent-indexed-object-style': "error"; + '@typescript-eslint/consistent-type-assertions': "error"; + '@typescript-eslint/consistent-type-definitions': "error"; + '@typescript-eslint/no-confusing-non-null-assertion': "error"; + 'no-empty-function': "off"; + '@typescript-eslint/no-empty-function': "error"; + '@typescript-eslint/no-inferrable-types': "error"; + '@typescript-eslint/prefer-for-of': "error"; + '@typescript-eslint/prefer-function-type': "error"; + }; + }; + 'stylistic-type-checked': { + extends: string[]; + rules: { + '@typescript-eslint/adjacent-overload-signatures': "error"; + '@typescript-eslint/array-type': "error"; + '@typescript-eslint/ban-tslint-comment': "error"; + '@typescript-eslint/class-literal-property-style': "error"; + '@typescript-eslint/consistent-generic-constructors': "error"; + '@typescript-eslint/consistent-indexed-object-style': "error"; + '@typescript-eslint/consistent-type-assertions': "error"; + '@typescript-eslint/consistent-type-definitions': "error"; + 'dot-notation': "off"; + '@typescript-eslint/dot-notation': "error"; + '@typescript-eslint/no-confusing-non-null-assertion': "error"; + 'no-empty-function': "off"; + '@typescript-eslint/no-empty-function': "error"; + '@typescript-eslint/no-inferrable-types': "error"; + '@typescript-eslint/non-nullable-type-assertion-style': "error"; + '@typescript-eslint/prefer-find': "error"; + '@typescript-eslint/prefer-for-of': "error"; + '@typescript-eslint/prefer-function-type': "error"; + '@typescript-eslint/prefer-includes': "error"; + '@typescript-eslint/prefer-nullish-coalescing': "error"; + '@typescript-eslint/prefer-optional-chain': "error"; + '@typescript-eslint/prefer-regexp-exec': "error"; + '@typescript-eslint/prefer-string-starts-ends-with': "error"; + }; + }; + 'stylistic-type-checked-only': { + extends: string[]; + rules: { + 'dot-notation': "off"; + '@typescript-eslint/dot-notation': "error"; + '@typescript-eslint/non-nullable-type-assertion-style': "error"; + '@typescript-eslint/prefer-find': "error"; + '@typescript-eslint/prefer-includes': "error"; + '@typescript-eslint/prefer-nullish-coalescing': "error"; + '@typescript-eslint/prefer-optional-chain': "error"; + '@typescript-eslint/prefer-regexp-exec': "error"; + '@typescript-eslint/prefer-string-starts-ends-with': "error"; + }; + }; + }; + meta: { + name: string; + version: string; + }; + rules: { + 'adjacent-overload-signatures': TSESLint.RuleModule<"adjacentSignature", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'array-type': TSESLint.RuleModule; + 'await-thenable': TSESLint.RuleModule; + 'ban-ts-comment': TSESLint.RuleModule; + 'ban-tslint-comment': TSESLint.RuleModule<"commentDetected", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'class-literal-property-style': TSESLint.RuleModule; + 'class-methods-use-this': TSESLint.RuleModule<"missingThis", import("./rules/class-methods-use-this").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'consistent-generic-constructors': TSESLint.RuleModule; + 'consistent-indexed-object-style': TSESLint.RuleModule; + 'consistent-return': TSESLint.RuleModule<"missingReturn" | "missingReturnValue" | "unexpectedReturnValue", [({ + treatUndefinedAsUnspecified?: boolean; + } | undefined)?], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'consistent-type-assertions': TSESLint.RuleModule; + 'consistent-type-definitions': TSESLint.RuleModule<"interfaceOverType" | "typeOverInterface", [string], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'consistent-type-exports': TSESLint.RuleModule; + 'consistent-type-imports': TSESLint.RuleModule; + 'default-param-last': TSESLint.RuleModule<"shouldBeLast", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'dot-notation': TSESLint.RuleModule<"useBrackets" | "useDot", [{ + allowIndexSignaturePropertyAccess?: boolean; + allowKeywords?: boolean; + allowPattern?: string; + allowPrivateClassPropertyAccess?: boolean; + allowProtectedClassPropertyAccess?: boolean; + }], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'explicit-function-return-type': TSESLint.RuleModule<"missingReturnType", import("./rules/explicit-function-return-type").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'explicit-member-accessibility': TSESLint.RuleModule; + 'explicit-module-boundary-types': TSESLint.RuleModule; + 'init-declarations': TSESLint.RuleModule<"initialized" | "notInitialized", ["always" | "never", ({ + ignoreForLoopInit?: boolean; + } | undefined)?], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'max-params': TSESLint.RuleModule<"exceed", ({ + countVoidThis?: boolean; + max: number; + } | { + countVoidThis?: boolean; + maximum: number; + })[], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'member-ordering': TSESLint.RuleModule; + 'method-signature-style': TSESLint.RuleModule; + 'naming-convention': TSESLint.RuleModule; + 'no-array-constructor': TSESLint.RuleModule<"useLiteral", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-array-delete': TSESLint.RuleModule; + 'no-base-to-string': TSESLint.RuleModule; + 'no-confusing-non-null-assertion': TSESLint.RuleModule; + 'no-confusing-void-expression': TSESLint.RuleModule; + 'no-deprecated': TSESLint.RuleModule<"deprecated" | "deprecatedWithReason", [{ + allow?: import("@typescript-eslint/type-utils").TypeOrValueSpecifier[]; + }], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-dupe-class-members': TSESLint.RuleModule<"unexpected", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-duplicate-enum-values': TSESLint.RuleModule<"duplicateValue", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-duplicate-type-constituents': TSESLint.RuleModule; + 'no-dynamic-delete': TSESLint.RuleModule<"dynamicDelete", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-empty-function': TSESLint.RuleModule<"unexpected", [{ + allow?: string[]; + }], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-empty-interface': TSESLint.RuleModule; + 'no-empty-object-type': TSESLint.RuleModule; + 'no-explicit-any': TSESLint.RuleModule; + 'no-extra-non-null-assertion': TSESLint.RuleModule<"noExtraNonNullAssertion", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-extraneous-class': TSESLint.RuleModule; + 'no-floating-promises': TSESLint.RuleModule; + 'no-for-in-array': TSESLint.RuleModule<"forInViolation", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-implied-eval': TSESLint.RuleModule<"noFunctionConstructor" | "noImpliedEvalError", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-import-type-side-effects': TSESLint.RuleModule<"useTopLevelQualifier", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-inferrable-types': TSESLint.RuleModule<"noInferrableType", import("./rules/no-inferrable-types").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-invalid-this': TSESLint.RuleModule<"unexpectedThis", [({ + capIsConstructor?: boolean; + } | undefined)?], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-invalid-void-type': TSESLint.RuleModule; + 'no-loop-func': TSESLint.RuleModule<"unsafeRefs", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-loss-of-precision': TSESLint.RuleModule<"noLossOfPrecision", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-magic-numbers': TSESLint.RuleModule<"noMagic", [{ + detectObjects?: boolean; + enforceConst?: boolean; + ignore?: (number | string)[]; + ignoreArrayIndexes?: boolean; + ignoreEnums?: boolean; + ignoreNumericLiteralTypes?: boolean; + ignoreReadonlyClassProperties?: boolean; + ignoreTypeIndexes?: boolean; + }], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-meaningless-void-operator': TSESLint.RuleModule<"meaninglessVoidOperator" | "removeVoid", import("./rules/no-meaningless-void-operator").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-misused-new': TSESLint.RuleModule<"errorMessageClass" | "errorMessageInterface", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-misused-promises': TSESLint.RuleModule; + 'no-misused-spread': TSESLint.RuleModule<"addAwait" | "noArraySpreadInObject" | "noClassDeclarationSpreadInObject" | "noClassInstanceSpreadInObject" | "noFunctionSpreadInObject" | "noIterableSpreadInObject" | "noMapSpreadInObject" | "noPromiseSpreadInObject" | "noStringSpread" | "replaceMapSpreadInObject", [{ + allow?: import("@typescript-eslint/type-utils").TypeOrValueSpecifier[]; + }], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-mixed-enums': TSESLint.RuleModule<"mixed", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-namespace': TSESLint.RuleModule<"moduleSyntaxIsPreferred", import("./rules/no-namespace").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-non-null-asserted-nullish-coalescing': TSESLint.RuleModule<"noNonNullAssertedNullishCoalescing" | "suggestRemovingNonNull", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-non-null-asserted-optional-chain': TSESLint.RuleModule<"suggestRemovingNonNull" | "noNonNullOptionalChain", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-non-null-assertion': TSESLint.RuleModule; + 'no-redeclare': TSESLint.RuleModule; + 'no-redundant-type-constituents': TSESLint.RuleModule<"overrides" | "errorTypeOverrides" | "literalOverridden" | "overridden" | "primitiveOverridden", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-require-imports': TSESLint.RuleModule<"noRequireImports", import("./rules/no-require-imports").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-restricted-imports': TSESLint.RuleModule<"everything" | "everythingWithCustomMessage" | "importName" | "importNameWithCustomMessage" | "path" | "pathWithCustomMessage" | "patterns" | "patternWithCustomMessage", [import("eslint/lib/rules/no-restricted-imports").ObjectOfPathsAndPatterns] | import("eslint/lib/rules/no-restricted-imports").ArrayOfStringOrObject, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-restricted-types': TSESLint.RuleModule; + 'no-shadow': TSESLint.RuleModule; + 'no-this-alias': TSESLint.RuleModule; + 'no-type-alias': TSESLint.RuleModule; + 'no-unnecessary-boolean-literal-compare': TSESLint.RuleModule; + 'no-unnecessary-condition': TSESLint.RuleModule; + 'no-unnecessary-parameter-property-assignment': TSESLint.RuleModule<"unnecessaryAssign", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unnecessary-qualifier': TSESLint.RuleModule<"unnecessaryQualifier", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unnecessary-template-expression': TSESLint.RuleModule<"noUnnecessaryTemplateExpression", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unnecessary-type-arguments': TSESLint.RuleModule<"unnecessaryTypeParameter", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unnecessary-type-assertion': TSESLint.RuleModule; + 'no-unnecessary-type-constraint': TSESLint.RuleModule<"removeUnnecessaryConstraint" | "unnecessaryConstraint", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unnecessary-type-conversion': TSESLint.RuleModule<"suggestRemove" | "suggestSatisfies" | "unnecessaryTypeConversion", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unnecessary-type-parameters': TSESLint.RuleModule<"replaceUsagesWithConstraint" | "sole", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unsafe-argument': TSESLint.RuleModule; + 'no-unsafe-assignment': TSESLint.RuleModule<"unsafeArraySpread" | "anyAssignment" | "anyAssignmentThis" | "unsafeArrayPattern" | "unsafeArrayPatternFromTuple" | "unsafeAssignment", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unsafe-call': TSESLint.RuleModule; + 'no-unsafe-declaration-merging': TSESLint.RuleModule<"unsafeMerging", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unsafe-enum-comparison': TSESLint.RuleModule<"mismatchedCase" | "mismatchedCondition" | "replaceValueWithEnum", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unsafe-function-type': TSESLint.RuleModule<"bannedFunctionType", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unsafe-member-access': TSESLint.RuleModule<"unsafeComputedMemberAccess" | "unsafeMemberExpression" | "unsafeThisMemberExpression", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unsafe-return': TSESLint.RuleModule<"unsafeReturn" | "unsafeReturnAssignment" | "unsafeReturnThis", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unsafe-type-assertion': TSESLint.RuleModule<"unsafeOfAnyTypeAssertion" | "unsafeToAnyTypeAssertion" | "unsafeToUnconstrainedTypeAssertion" | "unsafeTypeAssertion" | "unsafeTypeAssertionAssignableToConstraint", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unsafe-unary-minus': TSESLint.RuleModule<"unaryMinus", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unused-expressions': TSESLint.RuleModule<"expected", [{ + allowShortCircuit?: boolean; + allowTaggedTemplates?: boolean; + allowTernary?: boolean; + }], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-unused-vars': TSESLint.RuleModule; + 'no-use-before-define': TSESLint.RuleModule<"noUseBeforeDefine", import("./rules/no-use-before-define").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-useless-constructor': TSESLint.RuleModule<"noUselessConstructor" | "removeConstructor", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-useless-empty-export': TSESLint.RuleModule<"uselessExport", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-var-requires': TSESLint.RuleModule<"noVarReqs", import("./rules/no-var-requires").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'no-wrapper-object-types': TSESLint.RuleModule<"bannedClassType", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'non-nullable-type-assertion-style': TSESLint.RuleModule<"preferNonNullAssertion", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'only-throw-error': TSESLint.RuleModule; + 'parameter-properties': TSESLint.RuleModule; + 'prefer-as-const': TSESLint.RuleModule<"preferConstAssertion" | "variableConstAssertion" | "variableSuggest", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-destructuring': TSESLint.RuleModule<"preferDestructuring", import("./rules/prefer-destructuring").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-enum-initializers': TSESLint.RuleModule; + 'prefer-find': TSESLint.RuleModule<"preferFind" | "preferFindSuggestion", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-for-of': TSESLint.RuleModule<"preferForOf", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-function-type': TSESLint.RuleModule<"functionTypeOverCallableType" | "unexpectedThisOnFunctionOnlyInterface", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-includes': TSESLint.RuleModule<"preferIncludes" | "preferStringIncludes", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-literal-enum-member': TSESLint.RuleModule<"notLiteral" | "notLiteralOrBitwiseExpression", [{ + allowBitwiseExpressions: boolean; + }], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-namespace-keyword': TSESLint.RuleModule<"useNamespace", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-nullish-coalescing': TSESLint.RuleModule; + 'prefer-optional-chain': TSESLint.RuleModule; + 'prefer-promise-reject-errors': TSESLint.RuleModule<"rejectAnError", import("./rules/prefer-promise-reject-errors").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-readonly': TSESLint.RuleModule<"preferReadonly", import("./rules/prefer-readonly").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-readonly-parameter-types': TSESLint.RuleModule<"shouldBeReadonly", import("./rules/prefer-readonly-parameter-types").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-reduce-type-parameter': TSESLint.RuleModule<"preferTypeParameter", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-regexp-exec': TSESLint.RuleModule<"regExpExecOverStringMatch", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-return-this-type': TSESLint.RuleModule<"useThisType", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'prefer-string-starts-ends-with': TSESLint.RuleModule; + 'prefer-ts-expect-error': TSESLint.RuleModule<"preferExpectErrorComment", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'promise-function-async': TSESLint.RuleModule; + 'related-getter-setter-pairs': TSESLint.RuleModule<"mismatch", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'require-array-sort-compare': TSESLint.RuleModule<"requireCompare", import("./rules/require-array-sort-compare").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'require-await': TSESLint.RuleModule<"missingAwait" | "removeAsync", [], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'restrict-plus-operands': TSESLint.RuleModule; + 'restrict-template-expressions': TSESLint.RuleModule<"invalidType", import("./rules/restrict-template-expressions").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'return-await': TSESLint.RuleModule<"disallowedPromiseAwait" | "disallowedPromiseAwaitSuggestion" | "nonPromiseAwait" | "requiredPromiseAwait" | "requiredPromiseAwaitSuggestion", [string], import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + 'sort-type-constituents': TSESLint.RuleModule; + 'strict-boolean-expressions': TSESLint.RuleModule; + 'switch-exhaustiveness-check': TSESLint.RuleModule; + 'triple-slash-reference': TSESLint.RuleModule<"tripleSlashReference", import("./rules/triple-slash-reference").Options, import("../rules").ESLintPluginDocs, TSESLint.RuleListener>; + typedef: TSESLint.RuleModule; + 'unbound-method': TSESLint.RuleModule; + 'unified-signatures': TSESLint.RuleModule; + 'use-unknown-in-catch-callback-variable': TSESLint.RuleModule; + }; + }; +}; +export = _default; +//# sourceMappingURL=raw-plugin.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts.map new file mode 100644 index 00000000..15f90d97 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"raw-plugin.d.ts","sourceRoot":"","sources":["../src/raw-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,EAAE,UAAU,EAAU,MAAM,oCAAoC,CAAC;;;;;;;;;;;;;;;;;;wDAetD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAqCpB,mEAAmE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDvE,kBAIE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.js b/node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.js new file mode 100644 index 00000000..5c98d309 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.js @@ -0,0 +1,121 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const parserBase = __importStar(require("@typescript-eslint/parser")); +const all_1 = __importDefault(require("./configs/eslintrc/all")); +const base_1 = __importDefault(require("./configs/eslintrc/base")); +const disable_type_checked_1 = __importDefault(require("./configs/eslintrc/disable-type-checked")); +const eslint_recommended_1 = __importDefault(require("./configs/eslintrc/eslint-recommended")); +const recommended_1 = __importDefault(require("./configs/eslintrc/recommended")); +const recommended_type_checked_1 = __importDefault(require("./configs/eslintrc/recommended-type-checked")); +const recommended_type_checked_only_1 = __importDefault(require("./configs/eslintrc/recommended-type-checked-only")); +const strict_1 = __importDefault(require("./configs/eslintrc/strict")); +const strict_type_checked_1 = __importDefault(require("./configs/eslintrc/strict-type-checked")); +const strict_type_checked_only_1 = __importDefault(require("./configs/eslintrc/strict-type-checked-only")); +const stylistic_1 = __importDefault(require("./configs/eslintrc/stylistic")); +const stylistic_type_checked_1 = __importDefault(require("./configs/eslintrc/stylistic-type-checked")); +const stylistic_type_checked_only_1 = __importDefault(require("./configs/eslintrc/stylistic-type-checked-only")); +const all_2 = __importDefault(require("./configs/flat/all")); +const base_2 = __importDefault(require("./configs/flat/base")); +const disable_type_checked_2 = __importDefault(require("./configs/flat/disable-type-checked")); +const eslint_recommended_2 = __importDefault(require("./configs/flat/eslint-recommended")); +const recommended_2 = __importDefault(require("./configs/flat/recommended")); +const recommended_type_checked_2 = __importDefault(require("./configs/flat/recommended-type-checked")); +const recommended_type_checked_only_2 = __importDefault(require("./configs/flat/recommended-type-checked-only")); +const strict_2 = __importDefault(require("./configs/flat/strict")); +const strict_type_checked_2 = __importDefault(require("./configs/flat/strict-type-checked")); +const strict_type_checked_only_2 = __importDefault(require("./configs/flat/strict-type-checked-only")); +const stylistic_2 = __importDefault(require("./configs/flat/stylistic")); +const stylistic_type_checked_2 = __importDefault(require("./configs/flat/stylistic-type-checked")); +const stylistic_type_checked_only_2 = __importDefault(require("./configs/flat/stylistic-type-checked-only")); +const rules_1 = __importDefault(require("./rules")); +const parser = { + meta: parserBase.meta, + parseForESLint: parserBase.parseForESLint, +}; +// note - cannot migrate this to an import statement because it will make TSC copy the package.json to the dist folder +const { name, version } = require('../package.json'); +const plugin = { + // not fully initialized yet. + // See https://eslint.org/docs/latest/extend/plugins#configs-in-plugins + configs: { + all: all_1.default, + base: base_1.default, + 'disable-type-checked': disable_type_checked_1.default, + 'eslint-recommended': eslint_recommended_1.default, + recommended: recommended_1.default, + /** @deprecated - please use "recommended-type-checked" instead. */ + 'recommended-requiring-type-checking': recommended_type_checked_1.default, + 'recommended-type-checked': recommended_type_checked_1.default, + 'recommended-type-checked-only': recommended_type_checked_only_1.default, + strict: strict_1.default, + 'strict-type-checked': strict_type_checked_1.default, + 'strict-type-checked-only': strict_type_checked_only_1.default, + stylistic: stylistic_1.default, + 'stylistic-type-checked': stylistic_type_checked_1.default, + 'stylistic-type-checked-only': stylistic_type_checked_only_1.default, + }, + meta: { + name, + version, + }, + rules: rules_1.default, +}; +// @ts-expect-error -- upstream type incompatibility stuff +const flatPlugin = plugin; +// included due to https://github.com/eslint/eslint/issues/19513 +const flatConfigs = { + 'flat/all': (0, all_2.default)(flatPlugin, parser), + 'flat/base': (0, base_2.default)(flatPlugin, parser), + 'flat/disable-type-checked': (0, disable_type_checked_2.default)(flatPlugin, parser), + 'flat/eslint-recommended': (0, eslint_recommended_2.default)(flatPlugin, parser), + 'flat/recommended': (0, recommended_2.default)(flatPlugin, parser), + 'flat/recommended-type-checked': (0, recommended_type_checked_2.default)(flatPlugin, parser), + 'flat/recommended-type-checked-only': (0, recommended_type_checked_only_2.default)(flatPlugin, parser), + 'flat/strict': (0, strict_2.default)(flatPlugin, parser), + 'flat/strict-type-checked': (0, strict_type_checked_2.default)(flatPlugin, parser), + 'flat/strict-type-checked-only': (0, strict_type_checked_only_2.default)(flatPlugin, parser), + 'flat/stylistic': (0, stylistic_2.default)(flatPlugin, parser), + 'flat/stylistic-type-checked': (0, stylistic_type_checked_2.default)(flatPlugin, parser), + 'flat/stylistic-type-checked-only': (0, stylistic_type_checked_only_2.default)(flatPlugin, parser), +}; +Object.assign(plugin.configs, flatConfigs); +module.exports = { + flatConfigs, + parser, + plugin, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.d.ts new file mode 100644 index 00000000..2dc3e38b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"adjacentSignature", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=adjacent-overload-signatures.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.d.ts.map new file mode 100644 index 00000000..a346ff8c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"adjacent-overload-signatures.d.ts","sourceRoot":"","sources":["../../src/rules/adjacent-overload-signatures.ts"],"names":[],"mappings":";AAuBA,wBA8IG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.js new file mode 100644 index 00000000..cf11132e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.js @@ -0,0 +1,124 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'adjacent-overload-signatures', + meta: { + type: 'suggestion', + docs: { + description: 'Require that function overload signatures be consecutive', + recommended: 'stylistic', + }, + messages: { + adjacentSignature: 'All {{name}} signatures should be adjacent.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + /** + * Gets the name and attribute of the member being processed. + * @param member the member being processed. + * @returns the name and attribute of the member or null if it's a member not relevant to the rule. + */ + function getMemberMethod(member) { + switch (member.type) { + case utils_1.AST_NODE_TYPES.ExportDefaultDeclaration: + case utils_1.AST_NODE_TYPES.ExportNamedDeclaration: { + // export statements (e.g. export { a };) + // have no declarations, so ignore them + if (!member.declaration) { + return null; + } + return getMemberMethod(member.declaration); + } + case utils_1.AST_NODE_TYPES.TSDeclareFunction: + case utils_1.AST_NODE_TYPES.FunctionDeclaration: { + const name = member.id?.name ?? null; + if (name == null) { + return null; + } + return { + name, + type: util_1.MemberNameType.Normal, + callSignature: false, + }; + } + case utils_1.AST_NODE_TYPES.TSMethodSignature: + case utils_1.AST_NODE_TYPES.MethodDefinition: + return { + ...(0, util_1.getNameFromMember)(member, context.sourceCode), + callSignature: false, + static: member.static, + }; + case utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration: + return { + name: 'call', + type: util_1.MemberNameType.Normal, + callSignature: true, + }; + case utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration: + return { + name: 'new', + type: util_1.MemberNameType.Normal, + callSignature: false, + }; + } + return null; + } + function isSameMethod(method1, method2) { + return (!!method2 && + method1.name === method2.name && + method1.static === method2.static && + method1.callSignature === method2.callSignature && + method1.type === method2.type); + } + function getMembers(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.ClassBody: + case utils_1.AST_NODE_TYPES.Program: + case utils_1.AST_NODE_TYPES.TSModuleBlock: + case utils_1.AST_NODE_TYPES.TSInterfaceBody: + case utils_1.AST_NODE_TYPES.BlockStatement: + return node.body; + case utils_1.AST_NODE_TYPES.TSTypeLiteral: + return node.members; + } + } + function checkBodyForOverloadMethods(node) { + const members = getMembers(node); + let lastMethod = null; + const seenMethods = []; + members.forEach(member => { + const method = getMemberMethod(member); + if (method == null) { + lastMethod = null; + return; + } + const index = seenMethods.findIndex(seenMethod => isSameMethod(method, seenMethod)); + if (index > -1 && !isSameMethod(method, lastMethod)) { + context.report({ + node: member, + messageId: 'adjacentSignature', + data: { + name: `${method.static ? 'static ' : ''}${method.name}`, + }, + }); + } + else if (index === -1) { + seenMethods.push(method); + } + lastMethod = method; + }); + } + return { + BlockStatement: checkBodyForOverloadMethods, + ClassBody: checkBodyForOverloadMethods, + Program: checkBodyForOverloadMethods, + TSInterfaceBody: checkBodyForOverloadMethods, + TSModuleBlock: checkBodyForOverloadMethods, + TSTypeLiteral: checkBodyForOverloadMethods, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/array-type.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/array-type.d.ts new file mode 100644 index 00000000..dead5b9b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/array-type.d.ts @@ -0,0 +1,11 @@ +export type OptionString = 'array' | 'array-simple' | 'generic'; +export type Options = [ + { + default: OptionString; + readonly?: OptionString; + } +]; +export type MessageIds = 'errorStringArray' | 'errorStringArrayReadonly' | 'errorStringArraySimple' | 'errorStringArraySimpleReadonly' | 'errorStringGeneric' | 'errorStringGenericSimple'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=array-type.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/array-type.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/array-type.d.ts.map new file mode 100644 index 00000000..d027d020 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/array-type.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"array-type.d.ts","sourceRoot":"","sources":["../../src/rules/array-type.ts"],"names":[],"mappings":"AA2EA,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,cAAc,GAAG,SAAS,CAAC;AAChE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,OAAO,EAAE,YAAY,CAAC;QACtB,QAAQ,CAAC,EAAE,YAAY,CAAC;KACzB;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAClB,kBAAkB,GAClB,0BAA0B,GAC1B,wBAAwB,GACxB,gCAAgC,GAChC,oBAAoB,GACpB,0BAA0B,CAAC;;AAE/B,wBAgNG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/array-type.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/array-type.js new file mode 100644 index 00000000..b8235d0a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/array-type.js @@ -0,0 +1,232 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +/** + * Check whatever node can be considered as simple + * @param node the node to be evaluated. + */ +function isSimpleType(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.Identifier: + case utils_1.AST_NODE_TYPES.TSAnyKeyword: + case utils_1.AST_NODE_TYPES.TSBooleanKeyword: + case utils_1.AST_NODE_TYPES.TSNeverKeyword: + case utils_1.AST_NODE_TYPES.TSNumberKeyword: + case utils_1.AST_NODE_TYPES.TSBigIntKeyword: + case utils_1.AST_NODE_TYPES.TSObjectKeyword: + case utils_1.AST_NODE_TYPES.TSStringKeyword: + case utils_1.AST_NODE_TYPES.TSSymbolKeyword: + case utils_1.AST_NODE_TYPES.TSUnknownKeyword: + case utils_1.AST_NODE_TYPES.TSVoidKeyword: + case utils_1.AST_NODE_TYPES.TSNullKeyword: + case utils_1.AST_NODE_TYPES.TSArrayType: + case utils_1.AST_NODE_TYPES.TSUndefinedKeyword: + case utils_1.AST_NODE_TYPES.TSThisType: + case utils_1.AST_NODE_TYPES.TSQualifiedName: + return true; + case utils_1.AST_NODE_TYPES.TSTypeReference: + if (node.typeName.type === utils_1.AST_NODE_TYPES.Identifier && + node.typeName.name === 'Array') { + if (!node.typeArguments) { + return true; + } + if (node.typeArguments.params.length === 1) { + return isSimpleType(node.typeArguments.params[0]); + } + } + else { + if (node.typeArguments) { + return false; + } + return isSimpleType(node.typeName); + } + return false; + default: + return false; + } +} +/** + * Check if node needs parentheses + * @param node the node to be evaluated. + */ +function typeNeedsParentheses(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSTypeReference: + return typeNeedsParentheses(node.typeName); + case utils_1.AST_NODE_TYPES.TSUnionType: + case utils_1.AST_NODE_TYPES.TSFunctionType: + case utils_1.AST_NODE_TYPES.TSIntersectionType: + case utils_1.AST_NODE_TYPES.TSTypeOperator: + case utils_1.AST_NODE_TYPES.TSInferType: + case utils_1.AST_NODE_TYPES.TSConstructorType: + case utils_1.AST_NODE_TYPES.TSConditionalType: + return true; + case utils_1.AST_NODE_TYPES.Identifier: + return node.name === 'ReadonlyArray'; + default: + return false; + } +} +exports.default = (0, util_1.createRule)({ + name: 'array-type', + meta: { + type: 'suggestion', + docs: { + description: 'Require consistently using either `T[]` or `Array` for arrays', + recommended: 'stylistic', + }, + fixable: 'code', + messages: { + errorStringArray: "Array type using '{{className}}<{{type}}>' is forbidden. Use '{{readonlyPrefix}}{{type}}[]' instead.", + errorStringArrayReadonly: "Array type using '{{className}}<{{type}}>' is forbidden. Use '{{readonlyPrefix}}{{type}}' instead.", + errorStringArraySimple: "Array type using '{{className}}<{{type}}>' is forbidden for simple types. Use '{{readonlyPrefix}}{{type}}[]' instead.", + errorStringArraySimpleReadonly: "Array type using '{{className}}<{{type}}>' is forbidden for simple types. Use '{{readonlyPrefix}}{{type}}' instead.", + errorStringGeneric: "Array type using '{{readonlyPrefix}}{{type}}[]' is forbidden. Use '{{className}}<{{type}}>' instead.", + errorStringGenericSimple: "Array type using '{{readonlyPrefix}}{{type}}[]' is forbidden for non-simple types. Use '{{className}}<{{type}}>' instead.", + }, + schema: [ + { + type: 'object', + $defs: { + arrayOption: { + type: 'string', + enum: ['array', 'generic', 'array-simple'], + }, + }, + additionalProperties: false, + properties: { + default: { + $ref: '#/items/0/$defs/arrayOption', + description: 'The array type expected for mutable cases.', + }, + readonly: { + $ref: '#/items/0/$defs/arrayOption', + description: 'The array type expected for readonly cases. If omitted, the value for `default` will be used.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + default: 'array', + }, + ], + create(context, [options]) { + const defaultOption = options.default; + const readonlyOption = options.readonly ?? defaultOption; + /** + * @param node the node to be evaluated. + */ + function getMessageType(node) { + if (isSimpleType(node)) { + return context.sourceCode.getText(node); + } + return 'T'; + } + return { + TSArrayType(node) { + const isReadonly = node.parent.type === utils_1.AST_NODE_TYPES.TSTypeOperator && + node.parent.operator === 'readonly'; + const currentOption = isReadonly ? readonlyOption : defaultOption; + if (currentOption === 'array' || + (currentOption === 'array-simple' && isSimpleType(node.elementType))) { + return; + } + const messageId = currentOption === 'generic' + ? 'errorStringGeneric' + : 'errorStringGenericSimple'; + const errorNode = isReadonly ? node.parent : node; + context.report({ + node: errorNode, + messageId, + data: { + type: getMessageType(node.elementType), + className: isReadonly ? 'ReadonlyArray' : 'Array', + readonlyPrefix: isReadonly ? 'readonly ' : '', + }, + fix(fixer) { + const typeNode = node.elementType; + const arrayType = isReadonly ? 'ReadonlyArray' : 'Array'; + return [ + fixer.replaceTextRange([errorNode.range[0], typeNode.range[0]], `${arrayType}<`), + fixer.replaceTextRange([typeNode.range[1], errorNode.range[1]], '>'), + ]; + }, + }); + }, + TSTypeReference(node) { + if (node.typeName.type !== utils_1.AST_NODE_TYPES.Identifier || + !(node.typeName.name === 'Array' || + node.typeName.name === 'ReadonlyArray' || + node.typeName.name === 'Readonly') || + (node.typeName.name === 'Readonly' && + node.typeArguments?.params[0].type !== utils_1.AST_NODE_TYPES.TSArrayType)) { + return; + } + const isReadonlyWithGenericArrayType = node.typeName.name === 'Readonly' && + node.typeArguments?.params[0].type === utils_1.AST_NODE_TYPES.TSArrayType; + const isReadonlyArrayType = node.typeName.name === 'ReadonlyArray' || + isReadonlyWithGenericArrayType; + const currentOption = isReadonlyArrayType + ? readonlyOption + : defaultOption; + if (currentOption === 'generic') { + return; + } + const readonlyPrefix = isReadonlyArrayType ? 'readonly ' : ''; + const typeParams = node.typeArguments?.params; + const messageId = currentOption === 'array' + ? isReadonlyWithGenericArrayType + ? 'errorStringArrayReadonly' + : 'errorStringArray' + : isReadonlyArrayType && node.typeName.name !== 'ReadonlyArray' + ? 'errorStringArraySimpleReadonly' + : 'errorStringArraySimple'; + if (!typeParams || typeParams.length === 0) { + // Create an 'any' array + context.report({ + node, + messageId, + data: { + type: 'any', + className: isReadonlyArrayType ? 'ReadonlyArray' : 'Array', + readonlyPrefix, + }, + fix(fixer) { + return fixer.replaceText(node, `${readonlyPrefix}any[]`); + }, + }); + return; + } + if (typeParams.length !== 1 || + (currentOption === 'array-simple' && !isSimpleType(typeParams[0]))) { + return; + } + const type = typeParams[0]; + const typeParens = typeNeedsParentheses(type); + const parentParens = readonlyPrefix && + node.parent.type === utils_1.AST_NODE_TYPES.TSArrayType && + !(0, util_1.isParenthesized)(node.parent.elementType, context.sourceCode); + const start = `${parentParens ? '(' : ''}${readonlyPrefix}${typeParens ? '(' : ''}`; + const end = `${typeParens ? ')' : ''}${isReadonlyWithGenericArrayType ? '' : `[]`}${parentParens ? ')' : ''}`; + context.report({ + node, + messageId, + data: { + type: getMessageType(type), + className: isReadonlyArrayType ? node.typeName.name : 'Array', + readonlyPrefix, + }, + fix(fixer) { + return [ + fixer.replaceTextRange([node.range[0], type.range[0]], start), + fixer.replaceTextRange([type.range[1], node.range[1]], end), + ]; + }, + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/await-thenable.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/await-thenable.d.ts new file mode 100644 index 00000000..a0ae98bd --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/await-thenable.d.ts @@ -0,0 +1,5 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageId = 'await' | 'awaitUsingOfNonAsyncDisposable' | 'convertToOrdinaryFor' | 'forAwaitOfNonAsyncIterable' | 'removeAwait'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=await-thenable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/await-thenable.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/await-thenable.d.ts.map new file mode 100644 index 00000000..b36c8756 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/await-thenable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"await-thenable.d.ts","sourceRoot":"","sources":["../../src/rules/await-thenable.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAiBnE,MAAM,MAAM,SAAS,GACjB,OAAO,GACP,gCAAgC,GAChC,sBAAsB,GACtB,4BAA4B,GAC5B,aAAa,CAAC;;AAElB,wBAyJG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/await-thenable.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/await-thenable.js new file mode 100644 index 00000000..3c57ee06 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/await-thenable.js @@ -0,0 +1,146 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +const getForStatementHeadLoc_1 = require("../util/getForStatementHeadLoc"); +exports.default = (0, util_1.createRule)({ + name: 'await-thenable', + meta: { + type: 'problem', + docs: { + description: 'Disallow awaiting a value that is not a Thenable', + recommended: 'recommended', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + await: 'Unexpected `await` of a non-Promise (non-"Thenable") value.', + awaitUsingOfNonAsyncDisposable: 'Unexpected `await using` of a value that is not async disposable.', + convertToOrdinaryFor: 'Convert to an ordinary `for...of` loop.', + forAwaitOfNonAsyncIterable: 'Unexpected `for await...of` of a value that is not async iterable.', + removeAwait: 'Remove unnecessary `await`.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + return { + AwaitExpression(node) { + const awaitArgumentEsNode = node.argument; + const awaitArgumentType = services.getTypeAtLocation(awaitArgumentEsNode); + const awaitArgumentTsNode = services.esTreeNodeToTSNodeMap.get(awaitArgumentEsNode); + const certainty = (0, util_1.needsToBeAwaited)(checker, awaitArgumentTsNode, awaitArgumentType); + if (certainty === util_1.Awaitable.Never) { + context.report({ + node, + messageId: 'await', + suggest: [ + { + messageId: 'removeAwait', + fix(fixer) { + const awaitKeyword = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node, util_1.isAwaitKeyword), util_1.NullThrowsReasons.MissingToken('await', 'await expression')); + return fixer.remove(awaitKeyword); + }, + }, + ], + }); + } + }, + 'ForOfStatement[await=true]'(node) { + const type = services.getTypeAtLocation(node.right); + if ((0, util_1.isTypeAnyType)(type)) { + return; + } + const hasAsyncIteratorSymbol = tsutils + .unionConstituents(type) + .some(typePart => tsutils.getWellKnownSymbolPropertyOfType(typePart, 'asyncIterator', checker) != null); + if (!hasAsyncIteratorSymbol) { + context.report({ + loc: (0, getForStatementHeadLoc_1.getForStatementHeadLoc)(context.sourceCode, node), + messageId: 'forAwaitOfNonAsyncIterable', + suggest: [ + // Note that this suggestion causes broken code for sync iterables + // of promises, since the loop variable is not awaited. + { + messageId: 'convertToOrdinaryFor', + fix(fixer) { + const awaitToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node, util_1.isAwaitKeyword), util_1.NullThrowsReasons.MissingToken('await', 'for await loop')); + return fixer.remove(awaitToken); + }, + }, + ], + }); + } + }, + 'VariableDeclaration[kind="await using"]'(node) { + for (const declarator of node.declarations) { + const init = declarator.init; + if (init == null) { + continue; + } + const type = services.getTypeAtLocation(init); + if ((0, util_1.isTypeAnyType)(type)) { + continue; + } + const hasAsyncDisposeSymbol = tsutils + .unionConstituents(type) + .some(typePart => tsutils.getWellKnownSymbolPropertyOfType(typePart, 'asyncDispose', checker) != null); + if (!hasAsyncDisposeSymbol) { + context.report({ + node: init, + messageId: 'awaitUsingOfNonAsyncDisposable', + // let the user figure out what to do if there's + // await using a = b, c = d, e = f; + // it's rare and not worth the complexity to handle. + ...(0, util_1.getFixOrSuggest)({ + fixOrSuggest: node.declarations.length === 1 ? 'suggest' : 'none', + suggestion: { + messageId: 'removeAwait', + fix(fixer) { + const awaitToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node, util_1.isAwaitKeyword), util_1.NullThrowsReasons.MissingToken('await', 'await using')); + return fixer.remove(awaitToken); + }, + }, + }), + }); + } + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-ts-comment.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-ts-comment.d.ts new file mode 100644 index 00000000..9b08ec76 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-ts-comment.d.ts @@ -0,0 +1,16 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type DirectiveConfig = boolean | 'allow-with-description' | { + descriptionFormat: string; +}; +export interface OptionsShape { + minimumDescriptionLength?: number; + 'ts-check'?: DirectiveConfig; + 'ts-expect-error'?: DirectiveConfig; + 'ts-ignore'?: DirectiveConfig; + 'ts-nocheck'?: DirectiveConfig; +} +export type Options = [OptionsShape]; +export type MessageIds = 'replaceTsIgnoreWithTsExpectError' | 'tsDirectiveComment' | 'tsDirectiveCommentDescriptionNotMatchPattern' | 'tsDirectiveCommentRequiresDescription' | 'tsIgnoreInsteadOfExpectError'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=ban-ts-comment.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-ts-comment.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-ts-comment.d.ts.map new file mode 100644 index 00000000..a58a433e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-ts-comment.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ban-ts-comment.d.ts","sourceRoot":"","sources":["../../src/rules/ban-ts-comment.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAQnE,MAAM,MAAM,eAAe,GACvB,OAAO,GACP,wBAAwB,GACxB;IAAE,iBAAiB,EAAE,MAAM,CAAA;CAAE,CAAC;AAElC,MAAM,WAAW,YAAY;IAC3B,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,UAAU,CAAC,EAAE,eAAe,CAAC;IAC7B,iBAAiB,CAAC,EAAE,eAAe,CAAC;IACpC,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,YAAY,CAAC,EAAE,eAAe,CAAC;CAChC;AAED,MAAM,MAAM,OAAO,GAAG,CAAC,YAAY,CAAC,CAAC;AAErC,MAAM,MAAM,UAAU,GAClB,kCAAkC,GAClC,oBAAoB,GACpB,8CAA8C,GAC9C,uCAAuC,GACvC,8BAA8B,CAAC;;AAOnC,wBA8OG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-ts-comment.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-ts-comment.js new file mode 100644 index 00000000..766495a6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-ts-comment.js @@ -0,0 +1,184 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const defaultMinimumDescriptionLength = 3; +exports.default = (0, util_1.createRule)({ + name: 'ban-ts-comment', + meta: { + type: 'problem', + docs: { + description: 'Disallow `@ts-` comments or require descriptions after directives', + recommended: { + recommended: true, + strict: [{ minimumDescriptionLength: 10 }], + }, + }, + hasSuggestions: true, + messages: { + replaceTsIgnoreWithTsExpectError: 'Replace "@ts-ignore" with "@ts-expect-error".', + tsDirectiveComment: 'Do not use "@ts-{{directive}}" because it alters compilation errors.', + tsDirectiveCommentDescriptionNotMatchPattern: 'The description for the "@ts-{{directive}}" directive must match the {{format}} format.', + tsDirectiveCommentRequiresDescription: 'Include a description after the "@ts-{{directive}}" directive to explain why the @ts-{{directive}} is necessary. The description must be {{minimumDescriptionLength}} characters or longer.', + tsIgnoreInsteadOfExpectError: 'Use "@ts-expect-error" instead of "@ts-ignore", as "@ts-ignore" will do nothing if the following line is error-free.', + }, + schema: [ + { + type: 'object', + $defs: { + directiveConfigSchema: { + oneOf: [ + { + type: 'boolean', + default: true, + }, + { + type: 'string', + enum: ['allow-with-description'], + }, + { + type: 'object', + additionalProperties: false, + properties: { + descriptionFormat: { type: 'string' }, + }, + }, + ], + }, + }, + additionalProperties: false, + properties: { + minimumDescriptionLength: { + type: 'number', + default: defaultMinimumDescriptionLength, + description: 'A minimum character length for descriptions when `allow-with-description` is enabled.', + }, + 'ts-check': { $ref: '#/items/0/$defs/directiveConfigSchema' }, + 'ts-expect-error': { $ref: '#/items/0/$defs/directiveConfigSchema' }, + 'ts-ignore': { $ref: '#/items/0/$defs/directiveConfigSchema' }, + 'ts-nocheck': { $ref: '#/items/0/$defs/directiveConfigSchema' }, + }, + }, + ], + }, + defaultOptions: [ + { + minimumDescriptionLength: defaultMinimumDescriptionLength, + 'ts-check': false, + 'ts-expect-error': 'allow-with-description', + 'ts-ignore': true, + 'ts-nocheck': true, + }, + ], + create(context, [options]) { + // https://github.com/microsoft/TypeScript/blob/6f1ad5ad8bec5671f7e951a3524b62d82ec4be68/src/compiler/parser.ts#L10591 + const singleLinePragmaRegEx = /^\/\/\/?\s*@ts-(?check|nocheck)(?.*)$/; + /* + The regex used are taken from the ones used in the official TypeScript repo - + https://github.com/microsoft/TypeScript/blob/6f1ad5ad8bec5671f7e951a3524b62d82ec4be68/src/compiler/scanner.ts#L340-L348 + */ + const commentDirectiveRegExSingleLine = /^\/*\s*@ts-(?expect-error|ignore)(?.*)/; + const commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@ts-(?expect-error|ignore)(?.*)/; + const descriptionFormats = new Map(); + for (const directive of [ + 'ts-expect-error', + 'ts-ignore', + 'ts-nocheck', + 'ts-check', + ]) { + const option = options[directive]; + if (typeof option === 'object' && option.descriptionFormat) { + descriptionFormats.set(directive, new RegExp(option.descriptionFormat)); + } + } + function execDirectiveRegEx(regex, str) { + const match = regex.exec(str); + if (!match) { + return null; + } + const { description, directive } = (0, util_1.nullThrows)(match.groups, 'RegExp should contain groups'); + return { + description: (0, util_1.nullThrows)(description, 'RegExp should contain "description" group'), + directive: (0, util_1.nullThrows)(directive, 'RegExp should contain "directive" group'), + }; + } + function findDirectiveInComment(comment) { + if (comment.type === utils_1.AST_TOKEN_TYPES.Line) { + const matchedPragma = execDirectiveRegEx(singleLinePragmaRegEx, `//${comment.value}`); + if (matchedPragma) { + return matchedPragma; + } + return execDirectiveRegEx(commentDirectiveRegExSingleLine, comment.value); + } + const commentLines = comment.value.split('\n'); + return execDirectiveRegEx(commentDirectiveRegExMultiLine, commentLines[commentLines.length - 1]); + } + return { + Program(node) { + const firstStatement = node.body.at(0); + const comments = context.sourceCode.getAllComments(); + comments.forEach(comment => { + const match = findDirectiveInComment(comment); + if (!match) { + return; + } + const { description, directive } = match; + if (directive === 'nocheck' && + firstStatement && + firstStatement.loc.start.line <= comment.loc.start.line) { + return; + } + const fullDirective = `ts-${directive}`; + const option = options[fullDirective]; + if (option === true) { + if (directive === 'ignore') { + // Special case to suggest @ts-expect-error instead of @ts-ignore + context.report({ + node: comment, + messageId: 'tsIgnoreInsteadOfExpectError', + suggest: [ + { + messageId: 'replaceTsIgnoreWithTsExpectError', + fix(fixer) { + const commentText = comment.value.replace(/@ts-ignore/, '@ts-expect-error'); + return fixer.replaceText(comment, comment.type === utils_1.AST_TOKEN_TYPES.Line + ? `//${commentText}` + : `/*${commentText}*/`); + }, + }, + ], + }); + } + else { + context.report({ + node: comment, + messageId: 'tsDirectiveComment', + data: { directive }, + }); + } + } + if (option === 'allow-with-description' || + (typeof option === 'object' && option.descriptionFormat)) { + const { minimumDescriptionLength } = options; + const format = descriptionFormats.get(fullDirective); + if ((0, util_1.getStringLength)(description.trim()) < + (0, util_1.nullThrows)(minimumDescriptionLength, 'Expected minimumDescriptionLength to be set')) { + context.report({ + node: comment, + messageId: 'tsDirectiveCommentRequiresDescription', + data: { directive, minimumDescriptionLength }, + }); + } + else if (format && !format.test(description)) { + context.report({ + node: comment, + messageId: 'tsDirectiveCommentDescriptionNotMatchPattern', + data: { directive, format: format.source }, + }); + } + } + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-tslint-comment.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-tslint-comment.d.ts new file mode 100644 index 00000000..e011000d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-tslint-comment.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"commentDetected", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=ban-tslint-comment.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-tslint-comment.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-tslint-comment.d.ts.map new file mode 100644 index 00000000..133fd582 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-tslint-comment.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ban-tslint-comment.d.ts","sourceRoot":"","sources":["../../src/rules/ban-tslint-comment.ts"],"names":[],"mappings":";AAiBA,wBA0CG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-tslint-comment.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-tslint-comment.js new file mode 100644 index 00000000..db4c4e7b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/ban-tslint-comment.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +// tslint regex +// https://github.com/palantir/tslint/blob/95d9d958833fd9dc0002d18cbe34db20d0fbf437/src/enableDisableRules.ts#L32 +const ENABLE_DISABLE_REGEX = /^\s*tslint:(enable|disable)(?:-(line|next-line))?(:|\s|$)/; +const toText = (text, type) => type === utils_1.AST_TOKEN_TYPES.Line + ? ['//', text.trim()].join(' ') + : ['/*', text.trim(), '*/'].join(' '); +exports.default = (0, util_1.createRule)({ + name: 'ban-tslint-comment', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow `// tslint:` comments', + recommended: 'stylistic', + }, + fixable: 'code', + messages: { + commentDetected: 'tslint comment detected: "{{ text }}"', + }, + schema: [], + }, + defaultOptions: [], + create: context => { + return { + Program() { + const comments = context.sourceCode.getAllComments(); + comments.forEach(c => { + if (ENABLE_DISABLE_REGEX.test(c.value)) { + context.report({ + node: c, + messageId: 'commentDetected', + data: { text: toText(c.value, c.type) }, + fix(fixer) { + const rangeStart = context.sourceCode.getIndexFromLoc({ + column: c.loc.start.column > 0 ? c.loc.start.column - 1 : 0, + line: c.loc.start.line, + }); + const rangeEnd = context.sourceCode.getIndexFromLoc({ + column: c.loc.end.column, + line: c.loc.end.line, + }); + return fixer.removeRange([rangeStart, rangeEnd + 1]); + }, + }); + } + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-literal-property-style.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-literal-property-style.d.ts new file mode 100644 index 00000000..31a9c7a1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-literal-property-style.d.ts @@ -0,0 +1,6 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = ['fields' | 'getters']; +export type MessageIds = 'preferFieldStyle' | 'preferFieldStyleSuggestion' | 'preferGetterStyle' | 'preferGetterStyleSuggestion'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=class-literal-property-style.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-literal-property-style.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-literal-property-style.d.ts.map new file mode 100644 index 00000000..44f13618 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-literal-property-style.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"class-literal-property-style.d.ts","sourceRoot":"","sources":["../../src/rules/class-literal-property-style.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAanE,MAAM,MAAM,OAAO,GAAG,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAC;AAC7C,MAAM,MAAM,UAAU,GAClB,kBAAkB,GAClB,4BAA4B,GAC5B,mBAAmB,GACnB,6BAA6B,CAAC;;AAsClC,wBAoLG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-literal-property-style.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-literal-property-style.js new file mode 100644 index 00000000..ba357984 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-literal-property-style.js @@ -0,0 +1,160 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const printNodeModifiers = (node, final) => `${node.accessibility ?? ''}${node.static ? ' static' : ''} ${final} `.trimStart(); +const isSupportedLiteral = (node) => { + switch (node.type) { + case utils_1.AST_NODE_TYPES.Literal: + return true; + case utils_1.AST_NODE_TYPES.TaggedTemplateExpression: + return node.quasi.quasis.length === 1; + case utils_1.AST_NODE_TYPES.TemplateLiteral: + return node.quasis.length === 1; + default: + return false; + } +}; +exports.default = (0, util_1.createRule)({ + name: 'class-literal-property-style', + meta: { + type: 'problem', + docs: { + description: 'Enforce that literals on classes are exposed in a consistent style', + recommended: 'stylistic', + }, + hasSuggestions: true, + messages: { + preferFieldStyle: 'Literals should be exposed using readonly fields.', + preferFieldStyleSuggestion: 'Replace the literals with readonly fields.', + preferGetterStyle: 'Literals should be exposed using getters.', + preferGetterStyleSuggestion: 'Replace the literals with getters.', + }, + schema: [ + { + type: 'string', + description: 'Which literal class member syntax to prefer.', + enum: ['fields', 'getters'], + }, + ], + }, + defaultOptions: ['fields'], + create(context, [style]) { + const propertiesInfoStack = []; + function enterClassBody() { + propertiesInfoStack.push({ + excludeSet: new Set(), + properties: [], + }); + } + function exitClassBody() { + const { excludeSet, properties } = (0, util_1.nullThrows)(propertiesInfoStack.pop(), 'Stack should exist on class exit'); + properties.forEach(node => { + const { value } = node; + if (!value || !isSupportedLiteral(value)) { + return; + } + const name = (0, util_1.getStaticMemberAccessValue)(node, context); + if (name && excludeSet.has(name)) { + return; + } + context.report({ + node: node.key, + messageId: 'preferGetterStyle', + suggest: [ + { + messageId: 'preferGetterStyleSuggestion', + fix(fixer) { + const name = context.sourceCode.getText(node.key); + let text = ''; + text += printNodeModifiers(node, 'get'); + text += node.computed ? `[${name}]` : name; + text += `() { return ${context.sourceCode.getText(value)}; }`; + return fixer.replaceText(node, text); + }, + }, + ], + }); + }); + } + function excludeAssignedProperty(node) { + if ((0, util_1.isAssignee)(node)) { + const { excludeSet } = propertiesInfoStack[propertiesInfoStack.length - 1]; + const name = (0, util_1.getStaticMemberAccessValue)(node, context); + if (name) { + excludeSet.add(name); + } + } + } + return { + ...(style === 'fields' && { + MethodDefinition(node) { + if (node.kind !== 'get' || + node.override || + !node.value.body || + node.value.body.body.length === 0) { + return; + } + const [statement] = node.value.body.body; + if (statement.type !== utils_1.AST_NODE_TYPES.ReturnStatement) { + return; + } + const { argument } = statement; + if (!argument || !isSupportedLiteral(argument)) { + return; + } + const name = (0, util_1.getStaticMemberAccessValue)(node, context); + const hasDuplicateKeySetter = name && + node.parent.body.some(element => { + return (element.type === utils_1.AST_NODE_TYPES.MethodDefinition && + element.kind === 'set' && + (0, util_1.isStaticMemberAccessOfValue)(element, context, name)); + }); + if (hasDuplicateKeySetter) { + return; + } + context.report({ + node: node.key, + messageId: 'preferFieldStyle', + suggest: [ + { + messageId: 'preferFieldStyleSuggestion', + fix(fixer) { + const name = context.sourceCode.getText(node.key); + let text = ''; + text += printNodeModifiers(node, 'readonly'); + text += node.computed ? `[${name}]` : name; + text += ` = ${context.sourceCode.getText(argument)};`; + return fixer.replaceText(node, text); + }, + }, + ], + }); + }, + }), + ...(style === 'getters' && { + ClassBody: enterClassBody, + 'ClassBody:exit': exitClassBody, + 'MethodDefinition[kind="constructor"] ThisExpression'(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.MemberExpression) { + let parent = node.parent; + while (!(0, util_1.isFunction)(parent)) { + parent = parent.parent; + } + if (parent.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition && + parent.parent.kind === 'constructor') { + excludeAssignedProperty(node.parent); + } + } + }, + PropertyDefinition(node) { + if (!node.readonly || node.declare || node.override) { + return; + } + const { properties } = propertiesInfoStack[propertiesInfoStack.length - 1]; + properties.push(node); + }, + }), + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-methods-use-this.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-methods-use-this.d.ts new file mode 100644 index 00000000..ecfd01f3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-methods-use-this.d.ts @@ -0,0 +1,12 @@ +export type Options = [ + { + enforceForClassFields?: boolean; + exceptMethods?: string[]; + ignoreClassesThatImplementAnInterface?: boolean | 'public-fields'; + ignoreOverrideMethods?: boolean; + } +]; +export type MessageIds = 'missingThis'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingThis", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=class-methods-use-this.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-methods-use-this.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-methods-use-this.d.ts.map new file mode 100644 index 00000000..34009978 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-methods-use-this.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"class-methods-use-this.d.ts","sourceRoot":"","sources":["../../src/rules/class-methods-use-this.ts"],"names":[],"mappings":"AAWA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,qBAAqB,CAAC,EAAE,OAAO,CAAC;QAChC,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;QACzB,qCAAqC,CAAC,EAAE,OAAO,GAAG,eAAe,CAAC;QAClE,qBAAqB,CAAC,EAAE,OAAO,CAAC;KACjC;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,aAAa,CAAC;;AAEvC,wBAkSG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-methods-use-this.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-methods-use-this.js new file mode 100644 index 00000000..15734bb4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/class-methods-use-this.js @@ -0,0 +1,220 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'class-methods-use-this', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce that class methods utilize `this`', + extendsBaseRule: true, + requiresTypeChecking: false, + }, + messages: { + missingThis: "Expected 'this' to be used by class {{name}}.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + enforceForClassFields: { + type: 'boolean', + default: true, + description: 'Enforces that functions used as instance field initializers utilize `this`.', + }, + exceptMethods: { + type: 'array', + description: 'Allows specified method names to be ignored with this rule.', + items: { + type: 'string', + }, + }, + ignoreClassesThatImplementAnInterface: { + description: 'Whether to ignore class members that are defined within a class that `implements` a type.', + oneOf: [ + { + type: 'boolean', + description: 'Ignore all classes that implement an interface', + }, + { + type: 'string', + description: 'Ignore only the public fields of classes that implement an interface', + enum: ['public-fields'], + }, + ], + }, + ignoreOverrideMethods: { + type: 'boolean', + description: 'Whether to ignore members marked with the `override` modifier.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + enforceForClassFields: true, + exceptMethods: [], + ignoreClassesThatImplementAnInterface: false, + ignoreOverrideMethods: false, + }, + ], + create(context, [{ enforceForClassFields, exceptMethods: exceptMethodsRaw, ignoreClassesThatImplementAnInterface, ignoreOverrideMethods, },]) { + const exceptMethods = new Set(exceptMethodsRaw); + let stack; + function pushContext(member) { + if (member?.parent.type === utils_1.AST_NODE_TYPES.ClassBody) { + stack = { + class: member.parent.parent, + member, + parent: stack, + usesThis: false, + }; + } + else { + stack = { + class: null, + member: null, + parent: stack, + usesThis: false, + }; + } + } + function enterFunction(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition || + node.parent.type === utils_1.AST_NODE_TYPES.PropertyDefinition || + node.parent.type === utils_1.AST_NODE_TYPES.AccessorProperty) { + pushContext(node.parent); + } + else { + pushContext(); + } + } + /** + * Pop `this` used flag from the stack. + */ + function popContext() { + const oldStack = stack; + stack = stack?.parent; + return oldStack; + } + function isPublicField(accessibility) { + if (!accessibility || accessibility === 'public') { + return true; + } + return false; + } + /** + * Check if the node is an instance method not excluded by config + */ + function isIncludedInstanceMethod(node) { + if (node.static || + (node.type === utils_1.AST_NODE_TYPES.MethodDefinition && + node.kind === 'constructor') || + ((node.type === utils_1.AST_NODE_TYPES.PropertyDefinition || + node.type === utils_1.AST_NODE_TYPES.AccessorProperty) && + !enforceForClassFields)) { + return false; + } + if (node.computed || exceptMethods.size === 0) { + return true; + } + const hashIfNeeded = node.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier ? '#' : ''; + const name = (0, util_1.getStaticMemberAccessValue)(node, context); + return (typeof name !== 'string' || !exceptMethods.has(hashIfNeeded + name)); + } + /** + * Checks if we are leaving a function that is a method, and reports if 'this' has not been used. + * Static methods and the constructor are exempt. + * Then pops the context off the stack. + */ + function exitFunction(node) { + const stackContext = popContext(); + if (stackContext?.member == null || + stackContext.usesThis || + (ignoreOverrideMethods && stackContext.member.override) || + (ignoreClassesThatImplementAnInterface === true && + stackContext.class.implements.length > 0) || + (ignoreClassesThatImplementAnInterface === 'public-fields' && + stackContext.class.implements.length > 0 && + isPublicField(stackContext.member.accessibility))) { + return; + } + if (isIncludedInstanceMethod(stackContext.member)) { + context.report({ + loc: (0, util_1.getFunctionHeadLoc)(node, context.sourceCode), + node, + messageId: 'missingThis', + data: { + name: (0, util_1.getFunctionNameWithKind)(node), + }, + }); + } + } + return { + // function declarations have their own `this` context + FunctionDeclaration() { + pushContext(); + }, + 'FunctionDeclaration:exit'() { + popContext(); + }, + FunctionExpression(node) { + enterFunction(node); + }, + 'FunctionExpression:exit'(node) { + exitFunction(node); + }, + ...(enforceForClassFields + ? { + 'AccessorProperty > ArrowFunctionExpression.value'(node) { + enterFunction(node); + }, + 'AccessorProperty > ArrowFunctionExpression.value:exit'(node) { + exitFunction(node); + }, + 'PropertyDefinition > ArrowFunctionExpression.value'(node) { + enterFunction(node); + }, + 'PropertyDefinition > ArrowFunctionExpression.value:exit'(node) { + exitFunction(node); + }, + } + : {}), + /* + * Class field value are implicit functions. + */ + 'AccessorProperty:exit'() { + popContext(); + }, + 'AccessorProperty > *.key:exit'() { + pushContext(); + }, + 'PropertyDefinition:exit'() { + popContext(); + }, + 'PropertyDefinition > *.key:exit'() { + pushContext(); + }, + /* + * Class static blocks are implicit functions. They aren't required to use `this`, + * but we have to push context so that it captures any use of `this` in the static block + * separately from enclosing contexts, because static blocks have their own `this` and it + * shouldn't count as used `this` in enclosing contexts. + */ + StaticBlock() { + pushContext(); + }, + 'StaticBlock:exit'() { + popContext(); + }, + 'ThisExpression, Super'() { + if (stack) { + stack.usesThis = true; + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-generic-constructors.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-generic-constructors.d.ts new file mode 100644 index 00000000..fbd58d99 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-generic-constructors.d.ts @@ -0,0 +1,5 @@ +export type MessageIds = 'preferConstructor' | 'preferTypeAnnotation'; +export type Options = ['constructor' | 'type-annotation']; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=consistent-generic-constructors.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-generic-constructors.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-generic-constructors.d.ts.map new file mode 100644 index 00000000..094963c4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-generic-constructors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"consistent-generic-constructors.d.ts","sourceRoot":"","sources":["../../src/rules/consistent-generic-constructors.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,UAAU,GAAG,mBAAmB,GAAG,sBAAsB,CAAC;AACtE,MAAM,MAAM,OAAO,GAAG,CAAC,aAAa,GAAG,iBAAiB,CAAC,CAAC;;AAE1D,wBAqJG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-generic-constructors.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-generic-constructors.js new file mode 100644 index 00000000..6c2548e9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-generic-constructors.js @@ -0,0 +1,110 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'consistent-generic-constructors', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce specifying generic type arguments on type annotation or constructor name of a constructor call', + recommended: 'stylistic', + }, + fixable: 'code', + messages: { + preferConstructor: 'The generic type arguments should be specified as part of the constructor type arguments.', + preferTypeAnnotation: 'The generic type arguments should be specified as part of the type annotation.', + }, + schema: [ + { + type: 'string', + description: 'Which constructor call syntax to prefer.', + enum: ['type-annotation', 'constructor'], + }, + ], + }, + defaultOptions: ['constructor'], + create(context, [mode]) { + return { + 'VariableDeclarator,PropertyDefinition,AccessorProperty,:matches(FunctionDeclaration,FunctionExpression) > AssignmentPattern'(node) { + function getLHSRHS() { + switch (node.type) { + case utils_1.AST_NODE_TYPES.VariableDeclarator: + return [node.id, node.init]; + case utils_1.AST_NODE_TYPES.PropertyDefinition: + case utils_1.AST_NODE_TYPES.AccessorProperty: + return [node, node.value]; + case utils_1.AST_NODE_TYPES.AssignmentPattern: + return [node.left, node.right]; + default: + throw new Error(`Unhandled node type: ${node.type}`); + } + } + const [lhsName, rhs] = getLHSRHS(); + const lhs = lhsName.typeAnnotation?.typeAnnotation; + if (!rhs || + rhs.type !== utils_1.AST_NODE_TYPES.NewExpression || + rhs.callee.type !== utils_1.AST_NODE_TYPES.Identifier) { + return; + } + if (lhs && + (lhs.type !== utils_1.AST_NODE_TYPES.TSTypeReference || + lhs.typeName.type !== utils_1.AST_NODE_TYPES.Identifier || + lhs.typeName.name !== rhs.callee.name)) { + return; + } + if (mode === 'type-annotation') { + if (!lhs && rhs.typeArguments) { + const { callee, typeArguments } = rhs; + const typeAnnotation = context.sourceCode.getText(callee) + + context.sourceCode.getText(typeArguments); + context.report({ + node, + messageId: 'preferTypeAnnotation', + fix(fixer) { + function getIDToAttachAnnotation() { + if (node.type !== utils_1.AST_NODE_TYPES.PropertyDefinition && + node.type !== utils_1.AST_NODE_TYPES.AccessorProperty) { + return lhsName; + } + if (!node.computed) { + return node.key; + } + // If the property's computed, we have to attach the + // annotation after the square bracket, not the enclosed expression + return (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.key), util_1.NullThrowsReasons.MissingToken(']', 'key')); + } + return [ + fixer.remove(typeArguments), + fixer.insertTextAfter(getIDToAttachAnnotation(), `: ${typeAnnotation}`), + ]; + }, + }); + } + return; + } + if (lhs?.typeArguments && !rhs.typeArguments) { + const hasParens = context.sourceCode.getTokenAfter(rhs.callee)?.value === '('; + const extraComments = new Set(context.sourceCode.getCommentsInside(lhs.parent)); + context.sourceCode + .getCommentsInside(lhs.typeArguments) + .forEach(c => extraComments.delete(c)); + context.report({ + node, + messageId: 'preferConstructor', + *fix(fixer) { + yield fixer.remove(lhs.parent); + for (const comment of extraComments) { + yield fixer.insertTextAfter(rhs.callee, context.sourceCode.getText(comment)); + } + yield fixer.insertTextAfter(rhs.callee, context.sourceCode.getText(lhs.typeArguments)); + if (!hasParens) { + yield fixer.insertTextAfter(rhs.callee, '()'); + } + }, + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-indexed-object-style.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-indexed-object-style.d.ts new file mode 100644 index 00000000..5b8cfc7a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-indexed-object-style.d.ts @@ -0,0 +1,6 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageIds = 'preferIndexSignature' | 'preferIndexSignatureSuggestion' | 'preferRecord'; +export type Options = ['index-signature' | 'record']; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=consistent-indexed-object-style.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-indexed-object-style.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-indexed-object-style.d.ts.map new file mode 100644 index 00000000..0e1ba66c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-indexed-object-style.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"consistent-indexed-object-style.d.ts","sourceRoot":"","sources":["../../src/rules/consistent-indexed-object-style.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAanE,MAAM,MAAM,UAAU,GAClB,sBAAsB,GACtB,gCAAgC,GAChC,cAAc,CAAC;AACnB,MAAM,MAAM,OAAO,GAAG,CAAC,iBAAiB,GAAG,QAAQ,CAAC,CAAC;;AAErD,wBA2OG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-indexed-object-style.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-indexed-object-style.js new file mode 100644 index 00000000..5c8c030e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-indexed-object-style.js @@ -0,0 +1,255 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'consistent-indexed-object-style', + meta: { + type: 'suggestion', + docs: { + description: 'Require or disallow the `Record` type', + recommended: 'stylistic', + }, + fixable: 'code', + // eslint-disable-next-line eslint-plugin/require-meta-has-suggestions -- suggestions are exposed through a helper. + hasSuggestions: true, + messages: { + preferIndexSignature: 'An index signature is preferred over a record.', + preferIndexSignatureSuggestion: 'Change into an index signature instead of a record.', + preferRecord: 'A record is preferred over an index signature.', + }, + schema: [ + { + type: 'string', + description: 'Which indexed object syntax to prefer.', + enum: ['record', 'index-signature'], + }, + ], + }, + defaultOptions: ['record'], + create(context, [mode]) { + function checkMembers(members, node, parentId, prefix, postfix, safeFix = true) { + if (members.length !== 1) { + return; + } + const [member] = members; + if (member.type !== utils_1.AST_NODE_TYPES.TSIndexSignature) { + return; + } + const parameter = member.parameters.at(0); + if (parameter?.type !== utils_1.AST_NODE_TYPES.Identifier) { + return; + } + const keyType = parameter.typeAnnotation; + if (!keyType) { + return; + } + const valueType = member.typeAnnotation; + if (!valueType) { + return; + } + if (parentId) { + const scope = context.sourceCode.getScope(parentId); + const superVar = utils_1.ASTUtils.findVariable(scope, parentId.name); + if (superVar && + isDeeplyReferencingType(node, superVar, new Set([parentId]))) { + return; + } + } + context.report({ + node, + messageId: 'preferRecord', + fix: safeFix + ? (fixer) => { + const key = context.sourceCode.getText(keyType.typeAnnotation); + const value = context.sourceCode.getText(valueType.typeAnnotation); + const record = member.readonly + ? `Readonly>` + : `Record<${key}, ${value}>`; + return fixer.replaceText(node, `${prefix}${record}${postfix}`); + } + : null, + }); + } + return { + ...(mode === 'index-signature' && { + TSTypeReference(node) { + const typeName = node.typeName; + if (typeName.type !== utils_1.AST_NODE_TYPES.Identifier) { + return; + } + if (typeName.name !== 'Record') { + return; + } + const params = node.typeArguments?.params; + if (params?.length !== 2) { + return; + } + const indexParam = params[0]; + const shouldFix = indexParam.type === utils_1.AST_NODE_TYPES.TSStringKeyword || + indexParam.type === utils_1.AST_NODE_TYPES.TSNumberKeyword || + indexParam.type === utils_1.AST_NODE_TYPES.TSSymbolKeyword; + context.report({ + node, + messageId: 'preferIndexSignature', + ...(0, util_1.getFixOrSuggest)({ + fixOrSuggest: shouldFix ? 'fix' : 'suggest', + suggestion: { + messageId: 'preferIndexSignatureSuggestion', + fix: fixer => { + const key = context.sourceCode.getText(params[0]); + const type = context.sourceCode.getText(params[1]); + return fixer.replaceText(node, `{ [key: ${key}]: ${type} }`); + }, + }, + }), + }); + }, + }), + ...(mode === 'record' && { + TSInterfaceDeclaration(node) { + let genericTypes = ''; + if (node.typeParameters?.params.length) { + genericTypes = `<${node.typeParameters.params + .map(p => context.sourceCode.getText(p)) + .join(', ')}>`; + } + checkMembers(node.body.body, node, node.id, `type ${node.id.name}${genericTypes} = `, ';', !node.extends.length); + }, + TSMappedType(node) { + const key = node.key; + const scope = context.sourceCode.getScope(key); + const scopeManagerKey = (0, util_1.nullThrows)(scope.variables.find(value => value.name === key.name && value.isTypeVariable), 'key type parameter must be a defined type variable in its scope'); + // If the key is used to compute the value, we can't convert to a Record. + if (scopeManagerKey.references.some(reference => reference.isTypeReference)) { + return; + } + const constraint = node.constraint; + if (constraint.type === utils_1.AST_NODE_TYPES.TSTypeOperator && + constraint.operator === 'keyof' && + !(0, util_1.isParenthesized)(constraint, context.sourceCode)) { + // This is a weird special case, since modifiers are preserved by + // the mapped type, but not by the Record type. So this type is not, + // in general, equivalent to a Record type. + return; + } + // If the mapped type is circular, we can't convert it to a Record. + const parentId = findParentDeclaration(node)?.id; + if (parentId) { + const scope = context.sourceCode.getScope(key); + const superVar = utils_1.ASTUtils.findVariable(scope, parentId.name); + if (superVar) { + const isCircular = isDeeplyReferencingType(node.parent, superVar, new Set([parentId])); + if (isCircular) { + return; + } + } + } + // There's no builtin Mutable type, so we can't autofix it really. + const canFix = node.readonly !== '-'; + context.report({ + node, + messageId: 'preferRecord', + ...(canFix && { + fix: (fixer) => { + const keyType = context.sourceCode.getText(constraint); + const valueType = node.typeAnnotation + ? context.sourceCode.getText(node.typeAnnotation) + : 'any'; + let recordText = `Record<${keyType}, ${valueType}>`; + if (node.optional === '+' || node.optional === true) { + recordText = `Partial<${recordText}>`; + } + else if (node.optional === '-') { + recordText = `Required<${recordText}>`; + } + if (node.readonly === '+' || node.readonly === true) { + recordText = `Readonly<${recordText}>`; + } + return fixer.replaceText(node, recordText); + }, + }), + }); + }, + TSTypeLiteral(node) { + const parent = findParentDeclaration(node); + checkMembers(node.members, node, parent?.id, '', ''); + }, + }), + }; + }, +}); +function findParentDeclaration(node) { + if (node.parent && node.parent.type !== utils_1.AST_NODE_TYPES.TSTypeAnnotation) { + if (node.parent.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration) { + return node.parent; + } + return findParentDeclaration(node.parent); + } + return undefined; +} +function isDeeplyReferencingType(node, superVar, visited) { + if (visited.has(node)) { + // something on the chain is circular but it's not the reference being checked + return false; + } + visited.add(node); + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSTypeLiteral: + return node.members.some(member => isDeeplyReferencingType(member, superVar, visited)); + case utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration: + return isDeeplyReferencingType(node.typeAnnotation, superVar, visited); + case utils_1.AST_NODE_TYPES.TSIndexedAccessType: + return [node.indexType, node.objectType].some(type => isDeeplyReferencingType(type, superVar, visited)); + case utils_1.AST_NODE_TYPES.TSMappedType: + if (node.typeAnnotation) { + return isDeeplyReferencingType(node.typeAnnotation, superVar, visited); + } + break; + case utils_1.AST_NODE_TYPES.TSConditionalType: + return [ + node.checkType, + node.extendsType, + node.falseType, + node.trueType, + ].some(type => isDeeplyReferencingType(type, superVar, visited)); + case utils_1.AST_NODE_TYPES.TSUnionType: + case utils_1.AST_NODE_TYPES.TSIntersectionType: + return node.types.some(type => isDeeplyReferencingType(type, superVar, visited)); + case utils_1.AST_NODE_TYPES.TSInterfaceDeclaration: + return node.body.body.some(type => isDeeplyReferencingType(type, superVar, visited)); + case utils_1.AST_NODE_TYPES.TSTypeAnnotation: + return isDeeplyReferencingType(node.typeAnnotation, superVar, visited); + case utils_1.AST_NODE_TYPES.TSIndexSignature: { + if (node.typeAnnotation) { + return isDeeplyReferencingType(node.typeAnnotation, superVar, visited); + } + break; + } + case utils_1.AST_NODE_TYPES.TSTypeParameterInstantiation: { + return node.params.some(param => isDeeplyReferencingType(param, superVar, visited)); + } + case utils_1.AST_NODE_TYPES.TSTypeReference: { + if (isDeeplyReferencingType(node.typeName, superVar, visited)) { + return true; + } + if (node.typeArguments && + isDeeplyReferencingType(node.typeArguments, superVar, visited)) { + return true; + } + break; + } + case utils_1.AST_NODE_TYPES.Identifier: { + // check if the identifier is a reference of the type being checked + if (superVar.references.some(ref => (0, util_1.isNodeEqual)(ref.identifier, node))) { + return true; + } + // otherwise, follow its definition(s) + const refVar = utils_1.ASTUtils.findVariable(superVar.scope, node.name); + if (refVar) { + return refVar.defs.some(def => isDeeplyReferencingType(def.node, superVar, visited)); + } + } + } + return false; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-return.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-return.d.ts new file mode 100644 index 00000000..f0804782 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-return.d.ts @@ -0,0 +1,17 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingReturn" | "missingReturnValue" | "unexpectedReturnValue", [({ + treatUndefinedAsUnspecified?: boolean; +} | undefined)?], unknown, { + 'ArrowFunctionExpression:exit'(node: TSESTree.ArrowFunctionExpression): void; + 'FunctionDeclaration:exit'(node: TSESTree.FunctionDeclaration): void; + 'FunctionExpression:exit'(node: TSESTree.FunctionExpression): void; + ReturnStatement(node: TSESTree.ReturnStatement): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingReturn" | "missingReturnValue" | "unexpectedReturnValue", [({ + treatUndefinedAsUnspecified?: boolean; +} | undefined)?], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=consistent-return.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-return.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-return.d.ts.map new file mode 100644 index 00000000..2b666ac2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-return.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"consistent-return.d.ts","sourceRoot":"","sources":["../../src/rules/consistent-return.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAKzD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;;;yCAoFkB,SAC1B,uBAAiB;qCAEf,SAAS,mBAAmB;oCAEZ,SAAU,kBACvB;0BACH,SAAG,eACT;EA5FqD,CAAC;AAExD,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;;;AAQtE,wBA2GG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-return.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-return.js new file mode 100644 index 00000000..73fa4249 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-return.js @@ -0,0 +1,135 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('consistent-return'); +const defaultOptions = [{ treatUndefinedAsUnspecified: false }]; +exports.default = (0, util_1.createRule)({ + name: 'consistent-return', + meta: { + type: 'suggestion', + defaultOptions, + docs: { + description: 'Require `return` statements to either always or never specify values', + extendsBaseRule: true, + requiresTypeChecking: true, + }, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: baseRule.meta.schema, + }, + defaultOptions, + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const rules = baseRule.create(context); + const functions = []; + const treatUndefinedAsUnspecified = options?.treatUndefinedAsUnspecified === true; + function enterFunction(node) { + functions.push(node); + } + function exitFunction() { + functions.pop(); + } + function getCurrentFunction() { + return functions[functions.length - 1] ?? null; + } + function isPromiseVoid(node, type) { + if (tsutils.isThenableType(checker, node, type) && + tsutils.isTypeReference(type)) { + const awaitedType = type.typeArguments?.[0]; + if (awaitedType) { + if ((0, util_1.isTypeFlagSet)(awaitedType, ts.TypeFlags.Void)) { + return true; + } + return isPromiseVoid(node, awaitedType); + } + } + return false; + } + function isReturnVoidOrThenableVoid(node) { + const functionType = services.getTypeAtLocation(node); + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + const callSignatures = functionType.getCallSignatures(); + return callSignatures.some(signature => { + const returnType = signature.getReturnType(); + if (node.async) { + return isPromiseVoid(tsNode, returnType); + } + return (0, util_1.isTypeFlagSet)(returnType, ts.TypeFlags.Void); + }); + } + return { + ...rules, + ArrowFunctionExpression: enterFunction, + 'ArrowFunctionExpression:exit'(node) { + exitFunction(); + rules['ArrowFunctionExpression:exit'](node); + }, + FunctionDeclaration: enterFunction, + 'FunctionDeclaration:exit'(node) { + exitFunction(); + rules['FunctionDeclaration:exit'](node); + }, + FunctionExpression: enterFunction, + 'FunctionExpression:exit'(node) { + exitFunction(); + rules['FunctionExpression:exit'](node); + }, + ReturnStatement(node) { + const functionNode = getCurrentFunction(); + if (!node.argument && + functionNode && + isReturnVoidOrThenableVoid(functionNode)) { + return; + } + if (treatUndefinedAsUnspecified && node.argument) { + const returnValueType = services.getTypeAtLocation(node.argument); + if (returnValueType.flags === ts.TypeFlags.Undefined) { + rules.ReturnStatement({ + ...node, + argument: null, + }); + return; + } + } + rules.ReturnStatement(node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-assertions.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-assertions.d.ts new file mode 100644 index 00000000..be5d644e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-assertions.d.ts @@ -0,0 +1,13 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageIds = 'angle-bracket' | 'as' | 'never' | 'replaceArrayTypeAssertionWithAnnotation' | 'replaceArrayTypeAssertionWithSatisfies' | 'replaceObjectTypeAssertionWithAnnotation' | 'replaceObjectTypeAssertionWithSatisfies' | 'unexpectedArrayTypeAssertion' | 'unexpectedObjectTypeAssertion'; +type OptUnion = { + assertionStyle: 'angle-bracket' | 'as'; + objectLiteralTypeAssertions?: 'allow' | 'allow-as-parameter' | 'never'; + arrayLiteralTypeAssertions?: 'allow' | 'allow-as-parameter' | 'never'; +} | { + assertionStyle: 'never'; +}; +export type Options = readonly [OptUnion]; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=consistent-type-assertions.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-assertions.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-assertions.d.ts.map new file mode 100644 index 00000000..baf24016 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-assertions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"consistent-type-assertions.d.ts","sourceRoot":"","sources":["../../src/rules/consistent-type-assertions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAgBnE,MAAM,MAAM,UAAU,GAClB,eAAe,GACf,IAAI,GACJ,OAAO,GACP,yCAAyC,GACzC,wCAAwC,GACxC,0CAA0C,GAC1C,yCAAyC,GACzC,8BAA8B,GAC9B,+BAA+B,CAAC;AACpC,KAAK,QAAQ,GACT;IACE,cAAc,EAAE,eAAe,GAAG,IAAI,CAAC;IACvC,2BAA2B,CAAC,EAAE,OAAO,GAAG,oBAAoB,GAAG,OAAO,CAAC;IACvE,0BAA0B,CAAC,EAAE,OAAO,GAAG,oBAAoB,GAAG,OAAO,CAAC;CACvE,GACD;IACE,cAAc,EAAE,OAAO,CAAC;CACzB,CAAC;AACN,MAAM,MAAM,OAAO,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;;AAM1C,wBA2TG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-assertions.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-assertions.js new file mode 100644 index 00000000..fb941d40 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-assertions.js @@ -0,0 +1,256 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const getWrappedCode_1 = require("../util/getWrappedCode"); +exports.default = (0, util_1.createRule)({ + name: 'consistent-type-assertions', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce consistent usage of type assertions', + recommended: 'stylistic', + }, + fixable: 'code', + hasSuggestions: true, + messages: { + 'angle-bracket': "Use '<{{cast}}>' instead of 'as {{cast}}'.", + as: "Use 'as {{cast}}' instead of '<{{cast}}>'.", + never: 'Do not use any type assertions.', + replaceArrayTypeAssertionWithAnnotation: 'Use const x: {{cast}} = [ ... ] instead.', + replaceArrayTypeAssertionWithSatisfies: 'Use const x = [ ... ] satisfies {{cast}} instead.', + replaceObjectTypeAssertionWithAnnotation: 'Use const x: {{cast}} = { ... } instead.', + replaceObjectTypeAssertionWithSatisfies: 'Use const x = { ... } satisfies {{cast}} instead.', + unexpectedArrayTypeAssertion: 'Always prefer const x: T[] = [ ... ].', + unexpectedObjectTypeAssertion: 'Always prefer const x: T = { ... }.', + }, + schema: [ + { + oneOf: [ + { + type: 'object', + additionalProperties: false, + properties: { + assertionStyle: { + type: 'string', + description: 'The expected assertion style to enforce.', + enum: ['never'], + }, + }, + required: ['assertionStyle'], + }, + { + type: 'object', + additionalProperties: false, + properties: { + arrayLiteralTypeAssertions: { + type: 'string', + description: 'Whether to always prefer type declarations for array literals used as variable initializers, rather than type assertions.', + enum: ['allow', 'allow-as-parameter', 'never'], + }, + assertionStyle: { + type: 'string', + description: 'The expected assertion style to enforce.', + enum: ['as', 'angle-bracket'], + }, + objectLiteralTypeAssertions: { + type: 'string', + description: 'Whether to always prefer type declarations for object literals used as variable initializers, rather than type assertions.', + enum: ['allow', 'allow-as-parameter', 'never'], + }, + }, + }, + ], + }, + ], + }, + defaultOptions: [ + { + arrayLiteralTypeAssertions: 'allow', + assertionStyle: 'as', + objectLiteralTypeAssertions: 'allow', + }, + ], + create(context, [options]) { + function isConst(node) { + if (node.type !== utils_1.AST_NODE_TYPES.TSTypeReference) { + return false; + } + return (node.typeName.type === utils_1.AST_NODE_TYPES.Identifier && + node.typeName.name === 'const'); + } + function reportIncorrectAssertionType(node) { + const messageId = options.assertionStyle; + // If this node is `as const`, then don't report an error. + if (isConst(node.typeAnnotation) && messageId === 'never') { + return; + } + context.report({ + node, + messageId, + data: messageId !== 'never' + ? { cast: context.sourceCode.getText(node.typeAnnotation) } + : {}, + fix: messageId === 'as' + ? (fixer) => { + // lazily access parserServices to avoid crashing on non TS files (#9860) + const tsNode = (0, util_1.getParserServices)(context, true).esTreeNodeToTSNodeMap.get(node); + const expressionCode = context.sourceCode.getText(node.expression); + const typeAnnotationCode = context.sourceCode.getText(node.typeAnnotation); + const asPrecedence = (0, util_1.getOperatorPrecedence)(ts.SyntaxKind.AsExpression, ts.SyntaxKind.Unknown); + const parentPrecedence = (0, util_1.getOperatorPrecedence)(tsNode.parent.kind, ts.isBinaryExpression(tsNode.parent) + ? tsNode.parent.operatorToken.kind + : ts.SyntaxKind.Unknown, ts.isNewExpression(tsNode.parent) + ? tsNode.parent.arguments != null && + tsNode.parent.arguments.length > 0 + : undefined); + const expressionPrecedence = (0, util_1.getOperatorPrecedenceForNode)(node.expression); + const expressionCodeWrapped = (0, getWrappedCode_1.getWrappedCode)(expressionCode, expressionPrecedence, asPrecedence); + const text = `${expressionCodeWrapped} as ${typeAnnotationCode}`; + return fixer.replaceText(node, (0, util_1.isParenthesized)(node, context.sourceCode) + ? text + : (0, getWrappedCode_1.getWrappedCode)(text, asPrecedence, parentPrecedence)); + } + : undefined, + }); + } + function checkType(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSAnyKeyword: + case utils_1.AST_NODE_TYPES.TSUnknownKeyword: + return false; + case utils_1.AST_NODE_TYPES.TSTypeReference: + return ( + // Ignore `as const` and `` + !isConst(node) || + // Allow qualified names which have dots between identifiers, `Foo.Bar` + node.typeName.type === utils_1.AST_NODE_TYPES.TSQualifiedName); + default: + return true; + } + } + function getSuggestions(node, annotationMessageId, satisfiesMessageId) { + const suggestions = []; + if (node.parent.type === utils_1.AST_NODE_TYPES.VariableDeclarator && + !node.parent.id.typeAnnotation) { + const { parent } = node; + suggestions.push({ + messageId: annotationMessageId, + data: { cast: context.sourceCode.getText(node.typeAnnotation) }, + fix: fixer => [ + fixer.insertTextAfter(parent.id, `: ${context.sourceCode.getText(node.typeAnnotation)}`), + fixer.replaceText(node, (0, util_1.getTextWithParentheses)(context.sourceCode, node.expression)), + ], + }); + } + suggestions.push({ + messageId: satisfiesMessageId, + data: { cast: context.sourceCode.getText(node.typeAnnotation) }, + fix: fixer => [ + fixer.replaceText(node, (0, util_1.getTextWithParentheses)(context.sourceCode, node.expression)), + fixer.insertTextAfter(node, ` satisfies ${context.sourceCode.getText(node.typeAnnotation)}`), + ], + }); + return suggestions; + } + function isAsParameter(node) { + return (node.parent.type === utils_1.AST_NODE_TYPES.NewExpression || + node.parent.type === utils_1.AST_NODE_TYPES.CallExpression || + node.parent.type === utils_1.AST_NODE_TYPES.ThrowStatement || + node.parent.type === utils_1.AST_NODE_TYPES.AssignmentPattern || + node.parent.type === utils_1.AST_NODE_TYPES.JSXExpressionContainer || + (node.parent.type === utils_1.AST_NODE_TYPES.TemplateLiteral && + node.parent.parent.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression)); + } + function checkExpressionForObjectAssertion(node) { + if (options.assertionStyle === 'never' || + options.objectLiteralTypeAssertions === 'allow' || + node.expression.type !== utils_1.AST_NODE_TYPES.ObjectExpression) { + return; + } + if (options.objectLiteralTypeAssertions === 'allow-as-parameter' && + isAsParameter(node)) { + return; + } + if (checkType(node.typeAnnotation)) { + const suggest = getSuggestions(node, 'replaceObjectTypeAssertionWithAnnotation', 'replaceObjectTypeAssertionWithSatisfies'); + context.report({ + node, + messageId: 'unexpectedObjectTypeAssertion', + suggest, + }); + } + } + function checkExpressionForArrayAssertion(node) { + if (options.assertionStyle === 'never' || + options.arrayLiteralTypeAssertions === 'allow' || + node.expression.type !== utils_1.AST_NODE_TYPES.ArrayExpression) { + return; + } + if (options.arrayLiteralTypeAssertions === 'allow-as-parameter' && + isAsParameter(node)) { + return; + } + if (checkType(node.typeAnnotation)) { + const suggest = getSuggestions(node, 'replaceArrayTypeAssertionWithAnnotation', 'replaceArrayTypeAssertionWithSatisfies'); + context.report({ + node, + messageId: 'unexpectedArrayTypeAssertion', + suggest, + }); + } + } + return { + TSAsExpression(node) { + if (options.assertionStyle !== 'as') { + reportIncorrectAssertionType(node); + return; + } + checkExpressionForObjectAssertion(node); + checkExpressionForArrayAssertion(node); + }, + TSTypeAssertion(node) { + if (options.assertionStyle !== 'angle-bracket') { + reportIncorrectAssertionType(node); + return; + } + checkExpressionForObjectAssertion(node); + checkExpressionForArrayAssertion(node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-definitions.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-definitions.d.ts new file mode 100644 index 00000000..398c48f6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-definitions.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"interfaceOverType" | "typeOverInterface", [string], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=consistent-type-definitions.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-definitions.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-definitions.d.ts.map new file mode 100644 index 00000000..cc490c4d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-definitions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"consistent-type-definitions.d.ts","sourceRoot":"","sources":["../../src/rules/consistent-type-definitions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAMnE,wBAkJG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-definitions.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-definitions.js new file mode 100644 index 00000000..3669ecb4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-definitions.js @@ -0,0 +1,100 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'consistent-type-definitions', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce type definitions to consistently use either `interface` or `type`', + recommended: 'stylistic', + }, + fixable: 'code', + messages: { + interfaceOverType: 'Use an `interface` instead of a `type`.', + typeOverInterface: 'Use a `type` instead of an `interface`.', + }, + schema: [ + { + type: 'string', + description: 'Which type definition syntax to prefer.', + enum: ['interface', 'type'], + }, + ], + }, + defaultOptions: ['interface'], + create(context, [option]) { + /** + * Iterates from the highest parent to the currently traversed node + * to determine whether any node in tree is globally declared module declaration + */ + function isCurrentlyTraversedNodeWithinModuleDeclaration(node) { + return context.sourceCode + .getAncestors(node) + .some(node => node.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration && + node.declare && + node.kind === 'global'); + } + return { + ...(option === 'interface' && { + "TSTypeAliasDeclaration[typeAnnotation.type='TSTypeLiteral']"(node) { + context.report({ + node: node.id, + messageId: 'interfaceOverType', + fix(fixer) { + const typeToken = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(node.id, token => token.value === 'type'), util_1.NullThrowsReasons.MissingToken('type keyword', 'type alias')); + const equalsToken = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(node.typeAnnotation, token => token.value === '='), util_1.NullThrowsReasons.MissingToken('=', 'type alias')); + const beforeEqualsToken = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(equalsToken, { + includeComments: true, + }), util_1.NullThrowsReasons.MissingToken('before =', 'type alias')); + return [ + // replace 'type' with 'interface'. + fixer.replaceText(typeToken, 'interface'), + // delete from the = to the { of the type, and put a space to be pretty. + fixer.replaceTextRange([beforeEqualsToken.range[1], node.typeAnnotation.range[0]], ' '), + // remove from the closing } through the end of the statement. + fixer.removeRange([ + node.typeAnnotation.range[1], + node.range[1], + ]), + ]; + }, + }); + }, + }), + ...(option === 'type' && { + TSInterfaceDeclaration(node) { + const fix = isCurrentlyTraversedNodeWithinModuleDeclaration(node) + ? null + : (fixer) => { + const typeNode = node.typeParameters ?? node.id; + const fixes = []; + const firstToken = context.sourceCode.getTokenBefore(node.id); + if (firstToken) { + fixes.push(fixer.replaceText(firstToken, 'type')); + fixes.push(fixer.replaceTextRange([typeNode.range[1], node.body.range[0]], ' = ')); + } + node.extends.forEach(heritage => { + const typeIdentifier = context.sourceCode.getText(heritage); + fixes.push(fixer.insertTextAfter(node.body, ` & ${typeIdentifier}`)); + }); + if (node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration) { + fixes.push(fixer.removeRange([node.parent.range[0], node.range[0]]), fixer.insertTextAfter(node.body, `\nexport default ${node.id.name}`)); + } + return fixes; + }; + context.report({ + node: node.id, + messageId: 'typeOverInterface', + /** + * remove automatically fix when the interface is within a declare global + * @see {@link https://github.com/typescript-eslint/typescript-eslint/issues/2707} + */ + fix, + }); + }, + }), + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.d.ts new file mode 100644 index 00000000..20f2fa63 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.d.ts @@ -0,0 +1,10 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = [ + { + fixMixedExportsWithInlineTypeSpecifier: boolean; + } +]; +export type MessageIds = 'multipleExportsAreTypes' | 'singleExportIsType' | 'typeOverValue'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=consistent-type-exports.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.d.ts.map new file mode 100644 index 00000000..208ebc31 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"consistent-type-exports.d.ts","sourceRoot":"","sources":["../../src/rules/consistent-type-exports.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAgBnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,sCAAsC,EAAE,OAAO,CAAC;KACjD;CACF,CAAC;AAgBF,MAAM,MAAM,UAAU,GAClB,yBAAyB,GACzB,oBAAoB,GACpB,eAAe,CAAC;;AAEpB,wBA8RG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.js new file mode 100644 index 00000000..cfb7c0e1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.js @@ -0,0 +1,333 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'consistent-type-exports', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce consistent usage of type exports', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + multipleExportsAreTypes: 'Type exports {{exportNames}} are not values and should be exported using `export type`.', + singleExportIsType: 'Type export {{exportNames}} is not a value and should be exported using `export type`.', + typeOverValue: 'All exports in the declaration are only used as types. Use `export type`.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + fixMixedExportsWithInlineTypeSpecifier: { + type: 'boolean', + description: 'Whether the rule will autofix "mixed" export cases using TS inline type specifiers.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + fixMixedExportsWithInlineTypeSpecifier: false, + }, + ], + create(context, [{ fixMixedExportsWithInlineTypeSpecifier }]) { + const sourceExportsMap = {}; + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + /** + * Helper for identifying if a symbol resolves to a + * JavaScript value or a TypeScript type. + * + * @returns True/false if is a type or not, or undefined if the specifier + * can't be resolved. + */ + function isSymbolTypeBased(symbol) { + if (!symbol) { + return undefined; + } + const aliasedSymbol = tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias) + ? checker.getAliasedSymbol(symbol) + : symbol; + if (checker.isUnknownSymbol(aliasedSymbol)) { + return undefined; + } + return !(aliasedSymbol.flags & ts.SymbolFlags.Value); + } + return { + ExportAllDeclaration(node) { + if (node.exportKind === 'type') { + return; + } + const sourceModule = ts.resolveModuleName(node.source.value, context.filename, services.program.getCompilerOptions(), ts.sys); + if (sourceModule.resolvedModule == null) { + return; + } + const sourceFile = services.program.getSourceFile(sourceModule.resolvedModule.resolvedFileName); + if (sourceFile == null) { + return; + } + const sourceFileSymbol = checker.getSymbolAtLocation(sourceFile); + if (sourceFileSymbol == null) { + return; + } + const sourceFileType = checker.getTypeOfSymbol(sourceFileSymbol); + // Module can explicitly export types or values, and it's not difficult + // to distinguish one from the other, since we can get the flags of + // the exported symbols or check if symbol export declaration has + // the "type" keyword in it. + // + // Things get a lot more complicated when we're dealing with + // export * from './module-with-type-only-exports' + // export type * from './module-with-type-and-value-exports' + // + // TS checker has an internal function getExportsOfModuleWorker that + // recursively visits all module exports, including "export *". It then + // puts type-only-star-exported symbols into the typeOnlyExportStarMap + // property of sourceFile's SymbolLinks. Since symbol links aren't + // exposed outside the checker, we cannot access it directly. + // + // Therefore, to filter out value properties, we use the following hack: + // checker.getPropertiesOfType returns all exports that were originally + // values, but checker.getPropertyOfType returns undefined for + // properties that are mentioned in the typeOnlyExportStarMap. + const isThereAnyExportedValue = checker + .getPropertiesOfType(sourceFileType) + .some(propertyTypeSymbol => checker.getPropertyOfType(sourceFileType, propertyTypeSymbol.escapedName.toString()) != null); + if (isThereAnyExportedValue) { + return; + } + context.report({ + node, + messageId: 'typeOverValue', + fix(fixer) { + const asteriskToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && + token.value === '*'), util_1.NullThrowsReasons.MissingToken('asterisk', 'export all declaration')); + return fixer.insertTextBefore(asteriskToken, 'type '); + }, + }); + }, + ExportNamedDeclaration(node) { + // Coerce the source into a string for use as a lookup entry. + const source = getSourceFromExport(node) ?? 'undefined'; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + const sourceExports = (sourceExportsMap[source] ||= { + reportValueExports: [], + source, + typeOnlyNamedExport: null, + valueOnlyNamedExport: null, + }); + // Cache the first encountered exports for the package. We will need to come + // back to these later when fixing the problems. + if (node.exportKind === 'type') { + // The export is a type export + sourceExports.typeOnlyNamedExport ??= node; + } + else { + // The export is a value export + sourceExports.valueOnlyNamedExport ??= node; + } + // Next for the current export, we will separate type/value specifiers. + const typeBasedSpecifiers = []; + const inlineTypeSpecifiers = []; + const valueSpecifiers = []; + // Note: it is valid to export values as types. We will avoid reporting errors + // when this is encountered. + if (node.exportKind !== 'type') { + for (const specifier of node.specifiers) { + if (specifier.exportKind === 'type') { + inlineTypeSpecifiers.push(specifier); + continue; + } + const isTypeBased = isSymbolTypeBased(services.getSymbolAtLocation(specifier.exported)); + if (isTypeBased === true) { + typeBasedSpecifiers.push(specifier); + } + else if (isTypeBased === false) { + // When isTypeBased is undefined, we should avoid reporting them. + valueSpecifiers.push(specifier); + } + } + } + if ((node.exportKind === 'value' && typeBasedSpecifiers.length) || + (node.exportKind === 'type' && valueSpecifiers.length)) { + sourceExports.reportValueExports.push({ + node, + inlineTypeSpecifiers, + typeBasedSpecifiers, + valueSpecifiers, + }); + } + }, + 'Program:exit'() { + for (const sourceExports of Object.values(sourceExportsMap)) { + // If this export has no issues, move on. + if (sourceExports.reportValueExports.length === 0) { + continue; + } + for (const report of sourceExports.reportValueExports) { + if (report.valueSpecifiers.length === 0) { + // Export is all type-only with no type specifiers; convert the entire export to `export type`. + context.report({ + node: report.node, + messageId: 'typeOverValue', + *fix(fixer) { + yield* fixExportInsertType(fixer, context.sourceCode, report.node); + }, + }); + continue; + } + // We have both type and value violations. + const allExportNames = report.typeBasedSpecifiers.map(specifier => specifier.local.type === utils_1.AST_NODE_TYPES.Identifier + ? specifier.local.name + : specifier.local.value); + if (allExportNames.length === 1) { + const exportNames = allExportNames[0]; + context.report({ + node: report.node, + messageId: 'singleExportIsType', + data: { exportNames }, + *fix(fixer) { + if (fixMixedExportsWithInlineTypeSpecifier) { + yield* fixAddTypeSpecifierToNamedExports(fixer, report); + } + else { + yield* fixSeparateNamedExports(fixer, context.sourceCode, report); + } + }, + }); + } + else { + const exportNames = (0, util_1.formatWordList)(allExportNames); + context.report({ + node: report.node, + messageId: 'multipleExportsAreTypes', + data: { exportNames }, + *fix(fixer) { + if (fixMixedExportsWithInlineTypeSpecifier) { + yield* fixAddTypeSpecifierToNamedExports(fixer, report); + } + else { + yield* fixSeparateNamedExports(fixer, context.sourceCode, report); + } + }, + }); + } + } + } + }, + }; + }, +}); +/** + * Inserts "type" into an export. + * + * Example: + * + * export type { Foo } from 'foo'; + * ^^^^ + */ +function* fixExportInsertType(fixer, sourceCode, node) { + const exportToken = (0, util_1.nullThrows)(sourceCode.getFirstToken(node), util_1.NullThrowsReasons.MissingToken('export', node.type)); + yield fixer.insertTextAfter(exportToken, ' type'); + for (const specifier of node.specifiers) { + if (specifier.exportKind === 'type') { + const kindToken = (0, util_1.nullThrows)(sourceCode.getFirstToken(specifier), util_1.NullThrowsReasons.MissingToken('export', specifier.type)); + const firstTokenAfter = (0, util_1.nullThrows)(sourceCode.getTokenAfter(kindToken, { + includeComments: true, + }), 'Missing token following the export kind.'); + yield fixer.removeRange([kindToken.range[0], firstTokenAfter.range[0]]); + } + } +} +/** + * Separates the exports which mismatch the kind of export the given + * node represents. For example, a type export's named specifiers which + * represent values will be inserted in a separate `export` statement. + */ +function* fixSeparateNamedExports(fixer, sourceCode, report) { + const { node, inlineTypeSpecifiers, typeBasedSpecifiers, valueSpecifiers } = report; + const typeSpecifiers = [...typeBasedSpecifiers, ...inlineTypeSpecifiers]; + const source = getSourceFromExport(node); + const specifierNames = typeSpecifiers.map(getSpecifierText).join(', '); + const exportToken = (0, util_1.nullThrows)(sourceCode.getFirstToken(node), util_1.NullThrowsReasons.MissingToken('export', node.type)); + // Filter the bad exports from the current line. + const filteredSpecifierNames = valueSpecifiers + .map(getSpecifierText) + .join(', '); + const openToken = (0, util_1.nullThrows)(sourceCode.getFirstToken(node, util_1.isOpeningBraceToken), util_1.NullThrowsReasons.MissingToken('{', node.type)); + const closeToken = (0, util_1.nullThrows)(sourceCode.getLastToken(node, util_1.isClosingBraceToken), util_1.NullThrowsReasons.MissingToken('}', node.type)); + // Remove exports from the current line which we're going to re-insert. + yield fixer.replaceTextRange([openToken.range[1], closeToken.range[0]], ` ${filteredSpecifierNames} `); + // Insert the bad exports into a new export line above. + yield fixer.insertTextBefore(exportToken, `export type { ${specifierNames} }${source ? ` from '${source}'` : ''};\n`); +} +function* fixAddTypeSpecifierToNamedExports(fixer, report) { + if (report.node.exportKind === 'type') { + return; + } + for (const specifier of report.typeBasedSpecifiers) { + yield fixer.insertTextBefore(specifier, 'type '); + } +} +/** + * Returns the source of the export, or undefined if the named export has no source. + */ +function getSourceFromExport(node) { + if (node.source?.type === utils_1.AST_NODE_TYPES.Literal && + typeof node.source.value === 'string') { + return node.source.value; + } + return undefined; +} +/** + * Returns the specifier text for the export. If it is aliased, we take care to return + * the proper formatting. + */ +function getSpecifierText(specifier) { + const exportedName = specifier.exported.type === utils_1.AST_NODE_TYPES.Literal + ? specifier.exported.raw + : specifier.exported.name; + const localName = specifier.local.type === utils_1.AST_NODE_TYPES.Literal + ? specifier.local.raw + : specifier.local.name; + return `${localName}${exportedName !== localName ? ` as ${exportedName}` : ''}`; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-imports.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-imports.d.ts new file mode 100644 index 00000000..128fe41e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-imports.d.ts @@ -0,0 +1,14 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +type Prefer = 'no-type-imports' | 'type-imports'; +type FixStyle = 'inline-type-imports' | 'separate-type-imports'; +export type Options = [ + { + disallowTypeAnnotations?: boolean; + fixStyle?: FixStyle; + prefer?: Prefer; + } +]; +export type MessageIds = 'avoidImportType' | 'noImportTypeAnnotations' | 'someImportsAreOnlyTypes' | 'typeOverValue'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=consistent-type-imports.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-imports.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-imports.d.ts.map new file mode 100644 index 00000000..096131ae --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-imports.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"consistent-type-imports.d.ts","sourceRoot":"","sources":["../../src/rules/consistent-type-imports.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAkBnE,KAAK,MAAM,GAAG,iBAAiB,GAAG,cAAc,CAAC;AACjD,KAAK,QAAQ,GAAG,qBAAqB,GAAG,uBAAuB,CAAC;AAEhE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,uBAAuB,CAAC,EAAE,OAAO,CAAC;QAClC,QAAQ,CAAC,EAAE,QAAQ,CAAC;QACpB,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB;CACF,CAAC;AAoBF,MAAM,MAAM,UAAU,GAClB,iBAAiB,GACjB,yBAAyB,GACzB,yBAAyB,GACzB,eAAe,CAAC;;AACpB,wBAw4BG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-imports.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-imports.js new file mode 100644 index 00000000..6ff20155 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-imports.js @@ -0,0 +1,608 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'consistent-type-imports', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce consistent usage of type imports', + }, + fixable: 'code', + messages: { + avoidImportType: 'Use an `import` instead of an `import type`.', + noImportTypeAnnotations: '`import()` type annotations are forbidden.', + someImportsAreOnlyTypes: 'Imports {{typeImports}} are only used as type.', + typeOverValue: 'All imports in the declaration are only used as types. Use `import type`.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + disallowTypeAnnotations: { + type: 'boolean', + description: 'Whether to disallow type imports in type annotations (`import()`).', + }, + fixStyle: { + type: 'string', + description: 'The expected type modifier to be added when an import is detected as used only in the type position.', + enum: ['separate-type-imports', 'inline-type-imports'], + }, + prefer: { + type: 'string', + description: 'The expected import kind for type-only imports.', + enum: ['type-imports', 'no-type-imports'], + }, + }, + }, + ], + }, + defaultOptions: [ + { + disallowTypeAnnotations: true, + fixStyle: 'separate-type-imports', + prefer: 'type-imports', + }, + ], + create(context, [option]) { + const prefer = option.prefer ?? 'type-imports'; + const disallowTypeAnnotations = option.disallowTypeAnnotations !== false; + const selectors = {}; + if (disallowTypeAnnotations) { + selectors.TSImportType = (node) => { + context.report({ + node, + messageId: 'noImportTypeAnnotations', + }); + }; + } + if (prefer === 'no-type-imports') { + return { + ...selectors, + 'ImportDeclaration[importKind = "type"]'(node) { + context.report({ + node, + messageId: 'avoidImportType', + fix(fixer) { + return fixRemoveTypeSpecifierFromImportDeclaration(fixer, node); + }, + }); + }, + 'ImportSpecifier[importKind = "type"]'(node) { + context.report({ + node, + messageId: 'avoidImportType', + fix(fixer) { + return fixRemoveTypeSpecifierFromImportSpecifier(fixer, node); + }, + }); + }, + }; + } + // prefer type imports + const fixStyle = option.fixStyle ?? 'separate-type-imports'; + let hasDecoratorMetadata = false; + const sourceImportsMap = {}; + const emitDecoratorMetadata = (0, util_1.getParserServices)(context, true).emitDecoratorMetadata ?? false; + const experimentalDecorators = (0, util_1.getParserServices)(context, true).experimentalDecorators ?? false; + if (experimentalDecorators && emitDecoratorMetadata) { + selectors.Decorator = () => { + hasDecoratorMetadata = true; + }; + } + return { + ...selectors, + ImportDeclaration(node) { + const source = node.source.value; + // sourceImports is the object containing all the specifics for a particular import source, type or value + sourceImportsMap[source] ??= { + reportValueImports: [], // if there is a mismatch where type importKind but value specifiers + source, + typeOnlyNamedImport: null, // if only type imports + valueImport: null, // if only value imports + valueOnlyNamedImport: null, // if only value imports with named specifiers + }; + const sourceImports = sourceImportsMap[source]; + if (node.importKind === 'type') { + if (!sourceImports.typeOnlyNamedImport && + node.specifiers.every(specifier => specifier.type === utils_1.AST_NODE_TYPES.ImportSpecifier)) { + // definitely import type { TypeX } + sourceImports.typeOnlyNamedImport = node; + } + } + else if (!sourceImports.valueOnlyNamedImport && + node.specifiers.length && + node.specifiers.every(specifier => specifier.type === utils_1.AST_NODE_TYPES.ImportSpecifier)) { + sourceImports.valueOnlyNamedImport = node; + sourceImports.valueImport = node; + } + else if (!sourceImports.valueImport && + node.specifiers.some(specifier => specifier.type === utils_1.AST_NODE_TYPES.ImportDefaultSpecifier)) { + sourceImports.valueImport = node; + } + const typeSpecifiers = []; + const inlineTypeSpecifiers = []; + const valueSpecifiers = []; + const unusedSpecifiers = []; + for (const specifier of node.specifiers) { + if (specifier.type === utils_1.AST_NODE_TYPES.ImportSpecifier && + specifier.importKind === 'type') { + inlineTypeSpecifiers.push(specifier); + continue; + } + const [variable] = context.sourceCode.getDeclaredVariables(specifier); + if (variable.references.length === 0) { + unusedSpecifiers.push(specifier); + } + else { + const onlyHasTypeReferences = variable.references.every(ref => { + /** + * keep origin import kind when export + * export { Type } + * export default Type; + * export = Type; + */ + if ((ref.identifier.parent.type === + utils_1.AST_NODE_TYPES.ExportSpecifier || + ref.identifier.parent.type === + utils_1.AST_NODE_TYPES.ExportDefaultDeclaration || + ref.identifier.parent.type === + utils_1.AST_NODE_TYPES.TSExportAssignment) && + ref.isValueReference && + ref.isTypeReference) { + return node.importKind === 'type'; + } + if (ref.isValueReference) { + let parent = ref.identifier.parent; + let child = ref.identifier; + while (parent) { + switch (parent.type) { + // CASE 1: + // `type T = typeof foo` will create a value reference because "foo" must be a value type + // however this value reference is safe to use with type-only imports + case utils_1.AST_NODE_TYPES.TSTypeQuery: + return true; + case utils_1.AST_NODE_TYPES.TSQualifiedName: + // TSTypeQuery must have a TSESTree.EntityName as its child, so we can filter here and break early + if (parent.left !== child) { + return false; + } + child = parent; + parent = parent.parent; + continue; + // END CASE 1 + ////////////// + // CASE 2: + // `type T = { [foo]: string }` will create a value reference because "foo" must be a value type + // however this value reference is safe to use with type-only imports. + // Also this is represented as a non-type AST - hence it uses MemberExpression + case utils_1.AST_NODE_TYPES.TSPropertySignature: + return parent.key === child; + case utils_1.AST_NODE_TYPES.MemberExpression: + if (parent.object !== child) { + return false; + } + child = parent; + parent = parent.parent; + continue; + // END CASE 2 + default: + return false; + } + } + } + return ref.isTypeReference; + }); + if (onlyHasTypeReferences) { + typeSpecifiers.push(specifier); + } + else { + valueSpecifiers.push(specifier); + } + } + } + if (node.importKind === 'value' && typeSpecifiers.length) { + sourceImports.reportValueImports.push({ + node, + inlineTypeSpecifiers, + typeSpecifiers, + unusedSpecifiers, + valueSpecifiers, + }); + } + }, + 'Program:exit'() { + if (hasDecoratorMetadata) { + // Experimental decorator metadata is bowl of poop that cannot be + // supported based on pure syntactic analysis. + // + // So we can do one of two things: + // 1) add type-information to the rule in a breaking change and + // prevent users from using it so that we can fully support this + // case. + // 2) make the rule ignore all imports that are used in a file that + // might have decorator metadata. + // + // (1) is has huge impact and prevents the rule from being used by 99% + // of users Frankly - it's a straight-up bad option. So instead we + // choose with option (2) and just avoid reporting on any imports in a + // file with both emitDecoratorMetadata AND decorators + // + // For more context see the discussion in this issue and its linked + // issues: + // https://github.com/typescript-eslint/typescript-eslint/issues/5468 + // + // + // NOTE - in TS 5.0 `experimentalDecorators` became the legacy option, + // replaced with un-flagged, stable decorators and thus the type-aware + // emitDecoratorMetadata implementation also became legacy. in TS 5.2 + // support for the new, stable decorator metadata proposal was added - + // however this proposal does not include type information + // + // + // PHEW. So TL;DR what does all this mean? + // - if you use experimentalDecorators:true, + // emitDecoratorMetadata:true, and have a decorator in the file - + // the rule will do nothing in the file out of an abundance of + // caution. + // - else the rule will work as normal. + return; + } + for (const sourceImports of Object.values(sourceImportsMap)) { + if (sourceImports.reportValueImports.length === 0) { + // nothing to fix. value specifiers and type specifiers are correctly written + continue; + } + for (const report of sourceImports.reportValueImports) { + if (report.valueSpecifiers.length === 0 && + report.unusedSpecifiers.length === 0 && + report.node.importKind !== 'type') { + /** + * checks if import has type assertions + * @example + * ```ts + * import * as type from 'mod' assert \{ type: 'json' \}; + * ``` + * https://github.com/typescript-eslint/typescript-eslint/issues/7527 + */ + if (report.node.attributes.length === 0) { + context.report({ + node: report.node, + messageId: 'typeOverValue', + *fix(fixer) { + yield* fixToTypeImportDeclaration(fixer, report, sourceImports); + }, + }); + } + } + else { + // we have a mixed type/value import or just value imports, so we need to split them out into multiple imports if separate-type-imports is configured + const importNames = report.typeSpecifiers.map(specifier => `"${specifier.local.name}"`); + const message = (() => { + const typeImports = (0, util_1.formatWordList)(importNames); + if (importNames.length === 1) { + return { + messageId: 'someImportsAreOnlyTypes', + data: { + typeImports, + }, + }; + } + return { + messageId: 'someImportsAreOnlyTypes', + data: { + typeImports, + }, + }; + })(); + context.report({ + node: report.node, + ...message, + *fix(fixer) { + // take all the typeSpecifiers and put them on a new line + yield* fixToTypeImportDeclaration(fixer, report, sourceImports); + }, + }); + } + } + } + }, + }; + function classifySpecifier(node) { + const defaultSpecifier = node.specifiers[0].type === utils_1.AST_NODE_TYPES.ImportDefaultSpecifier + ? node.specifiers[0] + : null; + const namespaceSpecifier = node.specifiers.find((specifier) => specifier.type === utils_1.AST_NODE_TYPES.ImportNamespaceSpecifier) ?? null; + const namedSpecifiers = node.specifiers.filter((specifier) => specifier.type === utils_1.AST_NODE_TYPES.ImportSpecifier); + return { + defaultSpecifier, + namedSpecifiers, + namespaceSpecifier, + }; + } + /** + * Returns information for fixing named specifiers, type or value + */ + function getFixesNamedSpecifiers(fixer, node, subsetNamedSpecifiers, allNamedSpecifiers) { + if (allNamedSpecifiers.length === 0) { + return { + removeTypeNamedSpecifiers: [], + typeNamedSpecifiersText: '', + }; + } + const typeNamedSpecifiersTexts = []; + const removeTypeNamedSpecifiers = []; + if (subsetNamedSpecifiers.length === allNamedSpecifiers.length) { + // import Foo, {Type1, Type2} from 'foo' + // import DefType, {Type1, Type2} from 'foo' + const openingBraceToken = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(subsetNamedSpecifiers[0], util_1.isOpeningBraceToken), util_1.NullThrowsReasons.MissingToken('{', node.type)); + const commaToken = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(openingBraceToken, util_1.isCommaToken), util_1.NullThrowsReasons.MissingToken(',', node.type)); + const closingBraceToken = (0, util_1.nullThrows)(context.sourceCode.getFirstTokenBetween(openingBraceToken, node.source, util_1.isClosingBraceToken), util_1.NullThrowsReasons.MissingToken('}', node.type)); + // import DefType, {...} from 'foo' + // ^^^^^^^ remove + removeTypeNamedSpecifiers.push(fixer.removeRange([commaToken.range[0], closingBraceToken.range[1]])); + typeNamedSpecifiersTexts.push(context.sourceCode.text.slice(openingBraceToken.range[1], closingBraceToken.range[0])); + } + else { + const namedSpecifierGroups = []; + let group = []; + for (const namedSpecifier of allNamedSpecifiers) { + if (subsetNamedSpecifiers.includes(namedSpecifier)) { + group.push(namedSpecifier); + } + else if (group.length) { + namedSpecifierGroups.push(group); + group = []; + } + } + if (group.length) { + namedSpecifierGroups.push(group); + } + for (const namedSpecifiers of namedSpecifierGroups) { + const { removeRange, textRange } = getNamedSpecifierRanges(namedSpecifiers, allNamedSpecifiers); + removeTypeNamedSpecifiers.push(fixer.removeRange(removeRange)); + typeNamedSpecifiersTexts.push(context.sourceCode.text.slice(...textRange)); + } + } + return { + removeTypeNamedSpecifiers, + typeNamedSpecifiersText: typeNamedSpecifiersTexts.join(','), + }; + } + /** + * Returns ranges for fixing named specifier. + */ + function getNamedSpecifierRanges(namedSpecifierGroup, allNamedSpecifiers) { + const first = namedSpecifierGroup[0]; + const last = namedSpecifierGroup[namedSpecifierGroup.length - 1]; + const removeRange = [first.range[0], last.range[1]]; + const textRange = [...removeRange]; + const before = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(first), util_1.NullThrowsReasons.MissingToken('token', 'first specifier')); + textRange[0] = before.range[1]; + if ((0, util_1.isCommaToken)(before)) { + removeRange[0] = before.range[0]; + } + else { + removeRange[0] = before.range[1]; + } + const isFirst = allNamedSpecifiers[0] === first; + const isLast = allNamedSpecifiers[allNamedSpecifiers.length - 1] === last; + const after = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(last), util_1.NullThrowsReasons.MissingToken('token', 'last specifier')); + textRange[1] = after.range[0]; + if ((isFirst || isLast) && (0, util_1.isCommaToken)(after)) { + removeRange[1] = after.range[1]; + } + return { + removeRange, + textRange, + }; + } + /** + * insert specifiers to named import node. + * e.g. + * import type { Already, Type1, Type2 } from 'foo' + * ^^^^^^^^^^^^^ insert + */ + function fixInsertNamedSpecifiersInNamedSpecifierList(fixer, target, insertText) { + const closingBraceToken = (0, util_1.nullThrows)(context.sourceCode.getFirstTokenBetween((0, util_1.nullThrows)(context.sourceCode.getFirstToken(target), util_1.NullThrowsReasons.MissingToken('token before', 'import')), target.source, util_1.isClosingBraceToken), util_1.NullThrowsReasons.MissingToken('}', target.type)); + const before = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(closingBraceToken), util_1.NullThrowsReasons.MissingToken('token before', 'closing brace')); + if (!(0, util_1.isCommaToken)(before) && !(0, util_1.isOpeningBraceToken)(before)) { + insertText = `,${insertText}`; + } + return fixer.insertTextBefore(closingBraceToken, insertText); + } + /** + * insert type keyword to named import node. + * e.g. + * import ADefault, { Already, type Type1, type Type2 } from 'foo' + * ^^^^ insert + */ + function* fixInsertTypeKeywordInNamedSpecifierList(fixer, typeSpecifiers) { + for (const spec of typeSpecifiers) { + const insertText = context.sourceCode.text.slice(...spec.range); + yield fixer.replaceTextRange(spec.range, `type ${insertText}`); + } + } + function* fixInlineTypeImportDeclaration(fixer, report, sourceImports) { + const { node } = report; + // For a value import, will only add an inline type to named specifiers + const { namedSpecifiers } = classifySpecifier(node); + const typeNamedSpecifiers = namedSpecifiers.filter(specifier => report.typeSpecifiers.includes(specifier)); + if (sourceImports.valueImport) { + // add import named type specifiers to its value import + // import ValueA, { type A } + // ^^^^ insert + const { namedSpecifiers: valueImportNamedSpecifiers } = classifySpecifier(sourceImports.valueImport); + if (sourceImports.valueOnlyNamedImport || + valueImportNamedSpecifiers.length) { + yield* fixInsertTypeKeywordInNamedSpecifierList(fixer, typeNamedSpecifiers); + } + } + } + function* fixToTypeImportDeclaration(fixer, report, sourceImports) { + const { node } = report; + const { defaultSpecifier, namedSpecifiers, namespaceSpecifier } = classifySpecifier(node); + if (namespaceSpecifier && !defaultSpecifier) { + // import * as types from 'foo' + // checks for presence of import assertions + if (node.attributes.length === 0) { + yield* fixInsertTypeSpecifierForImportDeclaration(fixer, node, false); + } + return; + } + if (defaultSpecifier) { + if (report.typeSpecifiers.includes(defaultSpecifier) && + namedSpecifiers.length === 0 && + !namespaceSpecifier) { + // import Type from 'foo' + yield* fixInsertTypeSpecifierForImportDeclaration(fixer, node, true); + return; + } + if (fixStyle === 'inline-type-imports' && + !report.typeSpecifiers.includes(defaultSpecifier) && + namedSpecifiers.length > 0 && + !namespaceSpecifier) { + // if there is a default specifier but it isn't a type specifier, then just add the inline type modifier to the named specifiers + // import AValue, {BValue, Type1, Type2} from 'foo' + yield* fixInlineTypeImportDeclaration(fixer, report, sourceImports); + return; + } + } + else if (!namespaceSpecifier) { + if (fixStyle === 'inline-type-imports' && + namedSpecifiers.some(specifier => report.typeSpecifiers.includes(specifier))) { + // import {AValue, Type1, Type2} from 'foo' + yield* fixInlineTypeImportDeclaration(fixer, report, sourceImports); + return; + } + if (namedSpecifiers.every(specifier => report.typeSpecifiers.includes(specifier))) { + // import {Type1, Type2} from 'foo' + yield* fixInsertTypeSpecifierForImportDeclaration(fixer, node, false); + return; + } + } + const typeNamedSpecifiers = namedSpecifiers.filter(specifier => report.typeSpecifiers.includes(specifier)); + const fixesNamedSpecifiers = getFixesNamedSpecifiers(fixer, node, typeNamedSpecifiers, namedSpecifiers); + const afterFixes = []; + if (typeNamedSpecifiers.length) { + if (sourceImports.typeOnlyNamedImport) { + const insertTypeNamedSpecifiers = fixInsertNamedSpecifiersInNamedSpecifierList(fixer, sourceImports.typeOnlyNamedImport, fixesNamedSpecifiers.typeNamedSpecifiersText); + if (sourceImports.typeOnlyNamedImport.range[1] <= node.range[0]) { + yield insertTypeNamedSpecifiers; + } + else { + afterFixes.push(insertTypeNamedSpecifiers); + } + } + else { + // The import is both default and named. Insert named on new line because can't mix default type import and named type imports + // eslint-disable-next-line no-lonely-if + if (fixStyle === 'inline-type-imports') { + yield fixer.insertTextBefore(node, `import {${typeNamedSpecifiers + .map(spec => { + const insertText = context.sourceCode.text.slice(...spec.range); + return `type ${insertText}`; + }) + .join(', ')}} from ${context.sourceCode.getText(node.source)};\n`); + } + else { + yield fixer.insertTextBefore(node, `import type {${fixesNamedSpecifiers.typeNamedSpecifiersText}} from ${context.sourceCode.getText(node.source)};\n`); + } + } + } + const fixesRemoveTypeNamespaceSpecifier = []; + if (namespaceSpecifier && + report.typeSpecifiers.includes(namespaceSpecifier)) { + // import Foo, * as Type from 'foo' + // import DefType, * as Type from 'foo' + // import DefType, * as Type from 'foo' + const commaToken = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(namespaceSpecifier, util_1.isCommaToken), util_1.NullThrowsReasons.MissingToken(',', node.type)); + // import Def, * as Ns from 'foo' + // ^^^^^^^^^ remove + fixesRemoveTypeNamespaceSpecifier.push(fixer.removeRange([commaToken.range[0], namespaceSpecifier.range[1]])); + // import type * as Ns from 'foo' + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ insert + yield fixer.insertTextBefore(node, `import type ${context.sourceCode.getText(namespaceSpecifier)} from ${context.sourceCode.getText(node.source)};\n`); + } + if (defaultSpecifier && + report.typeSpecifiers.includes(defaultSpecifier)) { + if (report.typeSpecifiers.length === node.specifiers.length) { + const importToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node, util_1.isImportKeyword), util_1.NullThrowsReasons.MissingToken('import', node.type)); + // import type Type from 'foo' + // ^^^^ insert + yield fixer.insertTextAfter(importToken, ' type'); + } + else { + const commaToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(defaultSpecifier, util_1.isCommaToken), util_1.NullThrowsReasons.MissingToken(',', defaultSpecifier.type)); + // import Type , {...} from 'foo' + // ^^^^^ pick + const defaultText = context.sourceCode.text + .slice(defaultSpecifier.range[0], commaToken.range[0]) + .trim(); + yield fixer.insertTextBefore(node, `import type ${defaultText} from ${context.sourceCode.getText(node.source)};\n`); + const afterToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(commaToken, { + includeComments: true, + }), util_1.NullThrowsReasons.MissingToken('any token', node.type)); + // import Type , {...} from 'foo' + // ^^^^^^^ remove + yield fixer.removeRange([ + defaultSpecifier.range[0], + afterToken.range[0], + ]); + } + } + yield* fixesNamedSpecifiers.removeTypeNamedSpecifiers; + yield* fixesRemoveTypeNamespaceSpecifier; + yield* afterFixes; + } + function* fixInsertTypeSpecifierForImportDeclaration(fixer, node, isDefaultImport) { + // import type Foo from 'foo' + // ^^^^^ insert + const importToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node, util_1.isImportKeyword), util_1.NullThrowsReasons.MissingToken('import', node.type)); + yield fixer.insertTextAfter(importToken, ' type'); + if (isDefaultImport) { + // Has default import + const openingBraceToken = context.sourceCode.getFirstTokenBetween(importToken, node.source, util_1.isOpeningBraceToken); + if (openingBraceToken) { + // Only braces. e.g. import Foo, {} from 'foo' + const commaToken = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(openingBraceToken, util_1.isCommaToken), util_1.NullThrowsReasons.MissingToken(',', node.type)); + const closingBraceToken = (0, util_1.nullThrows)(context.sourceCode.getFirstTokenBetween(openingBraceToken, node.source, util_1.isClosingBraceToken), util_1.NullThrowsReasons.MissingToken('}', node.type)); + // import type Foo, {} from 'foo' + // ^^ remove + yield fixer.removeRange([ + commaToken.range[0], + closingBraceToken.range[1], + ]); + const specifiersText = context.sourceCode.text.slice(commaToken.range[1], closingBraceToken.range[1]); + if (node.specifiers.length > 1) { + yield fixer.insertTextAfter(node, `\nimport type${specifiersText} from ${context.sourceCode.getText(node.source)};`); + } + } + } + // make sure we don't do anything like `import type {type T} from 'foo';` + for (const specifier of node.specifiers) { + if (specifier.type === utils_1.AST_NODE_TYPES.ImportSpecifier && + specifier.importKind === 'type') { + yield* fixRemoveTypeSpecifierFromImportSpecifier(fixer, specifier); + } + } + } + function* fixRemoveTypeSpecifierFromImportDeclaration(fixer, node) { + // import type Foo from 'foo' + // ^^^^ remove + const importToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node, util_1.isImportKeyword), util_1.NullThrowsReasons.MissingToken('import', node.type)); + const typeToken = (0, util_1.nullThrows)(context.sourceCode.getFirstTokenBetween(importToken, node.specifiers[0]?.local ?? node.source, util_1.isTypeKeyword), util_1.NullThrowsReasons.MissingToken('type', node.type)); + const afterToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(typeToken, { includeComments: true }), util_1.NullThrowsReasons.MissingToken('any token', node.type)); + yield fixer.removeRange([typeToken.range[0], afterToken.range[0]]); + } + function* fixRemoveTypeSpecifierFromImportSpecifier(fixer, node) { + // import { type Foo } from 'foo' + // ^^^^ remove + const typeToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node, util_1.isTypeKeyword), util_1.NullThrowsReasons.MissingToken('type', node.type)); + const afterToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(typeToken, { includeComments: true }), util_1.NullThrowsReasons.MissingToken('any token', node.type)); + yield fixer.removeRange([typeToken.range[0], afterToken.range[0]]); + } + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/default-param-last.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/default-param-last.d.ts new file mode 100644 index 00000000..73159afe --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/default-param-last.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"shouldBeLast", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=default-param-last.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/default-param-last.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/default-param-last.d.ts.map new file mode 100644 index 00000000..bfa4bf4b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/default-param-last.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"default-param-last.d.ts","sourceRoot":"","sources":["../../src/rules/default-param-last.ts"],"names":[],"mappings":";AAMA,wBA+EG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/default-param-last.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/default-param-last.js new file mode 100644 index 00000000..15f6971e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/default-param-last.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'default-param-last', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce default parameters to be last', + extendsBaseRule: true, + }, + messages: { + shouldBeLast: 'Default parameters should be last.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + /** + * checks if node is optional parameter + * @param node the node to be evaluated + * @private + */ + function isOptionalParam(node) { + return ((node.type === utils_1.AST_NODE_TYPES.ArrayPattern || + node.type === utils_1.AST_NODE_TYPES.AssignmentPattern || + node.type === utils_1.AST_NODE_TYPES.Identifier || + node.type === utils_1.AST_NODE_TYPES.ObjectPattern || + node.type === utils_1.AST_NODE_TYPES.RestElement) && + node.optional); + } + /** + * checks if node is plain parameter + * @param node the node to be evaluated + * @private + */ + function isPlainParam(node) { + return !(node.type === utils_1.AST_NODE_TYPES.AssignmentPattern || + node.type === utils_1.AST_NODE_TYPES.RestElement || + isOptionalParam(node)); + } + function checkDefaultParamLast(node) { + let hasSeenPlainParam = false; + for (let i = node.params.length - 1; i >= 0; i--) { + const current = node.params[i]; + const param = current.type === utils_1.AST_NODE_TYPES.TSParameterProperty + ? current.parameter + : current; + if (isPlainParam(param)) { + hasSeenPlainParam = true; + continue; + } + if (hasSeenPlainParam && + (isOptionalParam(param) || + param.type === utils_1.AST_NODE_TYPES.AssignmentPattern)) { + context.report({ node: current, messageId: 'shouldBeLast' }); + } + } + } + return { + ArrowFunctionExpression: checkDefaultParamLast, + FunctionDeclaration: checkDefaultParamLast, + FunctionExpression: checkDefaultParamLast, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/dot-notation.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/dot-notation.d.ts new file mode 100644 index 00000000..fd9b94af --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/dot-notation.d.ts @@ -0,0 +1,22 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"useBrackets" | "useDot", [{ + allowIndexSignaturePropertyAccess?: boolean; + allowKeywords?: boolean; + allowPattern?: string; + allowPrivateClassPropertyAccess?: boolean; + allowProtectedClassPropertyAccess?: boolean; +}], unknown, { + MemberExpression(node: TSESTree.MemberExpression): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"useBrackets" | "useDot", [{ + allowIndexSignaturePropertyAccess?: boolean; + allowKeywords?: boolean; + allowPattern?: string; + allowPrivateClassPropertyAccess?: boolean; + allowProtectedClassPropertyAccess?: boolean; +}], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=dot-notation.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/dot-notation.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/dot-notation.d.ts.map new file mode 100644 index 00000000..566c7953 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/dot-notation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dot-notation.d.ts","sourceRoot":"","sources":["../../src/rules/dot-notation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAMzD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;;;;;;;2BAoI4gP,SAAU,gBAAgB;EApIlgP,CAAC;AAEnD,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;;;;;;;AAYtE,wBAoHG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/dot-notation.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/dot-notation.js new file mode 100644 index 00000000..a9dcbdac --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/dot-notation.js @@ -0,0 +1,143 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('dot-notation'); +const defaultOptions = [ + { + allowIndexSignaturePropertyAccess: false, + allowKeywords: true, + allowPattern: '', + allowPrivateClassPropertyAccess: false, + allowProtectedClassPropertyAccess: false, + }, +]; +exports.default = (0, util_1.createRule)({ + name: 'dot-notation', + meta: { + type: 'suggestion', + defaultOptions, + docs: { + description: 'Enforce dot notation whenever possible', + extendsBaseRule: true, + recommended: 'stylistic', + requiresTypeChecking: true, + }, + fixable: baseRule.meta.fixable, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowIndexSignaturePropertyAccess: { + type: 'boolean', + default: false, + description: 'Whether to allow accessing properties matching an index signature with array notation.', + }, + allowKeywords: { + type: 'boolean', + default: true, + description: 'Whether to allow keywords such as ["class"]`.', + }, + allowPattern: { + type: 'string', + default: '', + description: 'Regular expression of names to allow.', + }, + allowPrivateClassPropertyAccess: { + type: 'boolean', + default: false, + description: 'Whether to allow accessing class members marked as `private` with array notation.', + }, + allowProtectedClassPropertyAccess: { + type: 'boolean', + default: false, + description: 'Whether to allow accessing class members marked as `protected` with array notation.', + }, + }, + }, + ], + }, + defaultOptions, + create(context, [options]) { + const rules = baseRule.create(context); + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const allowPrivateClassPropertyAccess = options.allowPrivateClassPropertyAccess; + const allowProtectedClassPropertyAccess = options.allowProtectedClassPropertyAccess; + const allowIndexSignaturePropertyAccess = (options.allowIndexSignaturePropertyAccess ?? false) || + tsutils.isCompilerOptionEnabled(services.program.getCompilerOptions(), 'noPropertyAccessFromIndexSignature'); + return { + MemberExpression(node) { + if ((allowPrivateClassPropertyAccess || + allowProtectedClassPropertyAccess || + allowIndexSignaturePropertyAccess) && + node.computed) { + // for perf reasons - only fetch symbols if we have to + const propertySymbol = services.getSymbolAtLocation(node.property) ?? + services + .getTypeAtLocation(node.object) + .getNonNullableType() + .getProperties() + .find(propertySymbol => node.property.type === utils_1.AST_NODE_TYPES.Literal && + propertySymbol.escapedName === node.property.value); + const modifierKind = (0, util_1.getModifiers)(propertySymbol?.getDeclarations()?.[0])?.[0].kind; + if ((allowPrivateClassPropertyAccess && + modifierKind === ts.SyntaxKind.PrivateKeyword) || + (allowProtectedClassPropertyAccess && + modifierKind === ts.SyntaxKind.ProtectedKeyword)) { + return; + } + if (propertySymbol == null && allowIndexSignaturePropertyAccess) { + const objectType = services + .getTypeAtLocation(node.object) + .getNonNullableType(); + const indexInfos = checker.getIndexInfosOfType(objectType); + if (indexInfos.some(info => info.keyType.flags & ts.TypeFlags.StringLike)) { + return; + } + } + } + rules.MemberExpression(node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/enum-utils/shared.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/enum-utils/shared.d.ts new file mode 100644 index 00000000..c9138e49 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/enum-utils/shared.d.ts @@ -0,0 +1,37 @@ +import * as ts from 'typescript'; +/** + * Retrieve only the Enum literals from a type. for example: + * - 123 --> [] + * - {} --> [] + * - Fruit.Apple --> [Fruit.Apple] + * - Fruit.Apple | Vegetable.Lettuce --> [Fruit.Apple, Vegetable.Lettuce] + * - Fruit.Apple | Vegetable.Lettuce | 123 --> [Fruit.Apple, Vegetable.Lettuce] + * - T extends Fruit --> [Fruit] + */ +export declare function getEnumLiterals(type: ts.Type): ts.LiteralType[]; +/** + * A type can have 0 or more enum types. For example: + * - 123 --> [] + * - {} --> [] + * - Fruit.Apple --> [Fruit] + * - Fruit.Apple | Vegetable.Lettuce --> [Fruit, Vegetable] + * - Fruit.Apple | Vegetable.Lettuce | 123 --> [Fruit, Vegetable] + * - T extends Fruit --> [Fruit] + */ +export declare function getEnumTypes(typeChecker: ts.TypeChecker, type: ts.Type): ts.Type[]; +/** + * Returns the enum key that matches the given literal node, or null if none + * match. For example: + * ```ts + * enum Fruit { + * Apple = 'apple', + * Banana = 'banana', + * } + * + * getEnumKeyForLiteral([Fruit.Apple, Fruit.Banana], 'apple') --> 'Fruit.Apple' + * getEnumKeyForLiteral([Fruit.Apple, Fruit.Banana], 'banana') --> 'Fruit.Banana' + * getEnumKeyForLiteral([Fruit.Apple, Fruit.Banana], 'cherry') --> null + * ``` + */ +export declare function getEnumKeyForLiteral(enumLiterals: ts.LiteralType[], literal: unknown): string | null; +//# sourceMappingURL=shared.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/enum-utils/shared.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/enum-utils/shared.d.ts.map new file mode 100644 index 00000000..708c30b1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/enum-utils/shared.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../../src/rules/enum-utils/shared.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAwBjC;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC,WAAW,EAAE,CAM/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAC1B,WAAW,EAAE,EAAE,CAAC,WAAW,EAC3B,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,EAAE,CAAC,IAAI,EAAE,CAEX;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,oBAAoB,CAClC,YAAY,EAAE,EAAE,CAAC,WAAW,EAAE,EAC9B,OAAO,EAAE,OAAO,GACf,MAAM,GAAG,IAAI,CA+Bf"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/enum-utils/shared.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/enum-utils/shared.js new file mode 100644 index 00000000..c8ea8d28 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/enum-utils/shared.js @@ -0,0 +1,121 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getEnumLiterals = getEnumLiterals; +exports.getEnumTypes = getEnumTypes; +exports.getEnumKeyForLiteral = getEnumKeyForLiteral; +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../../util"); +/* + * If passed an enum member, returns the type of the parent. Otherwise, + * returns itself. + * + * For example: + * - `Fruit` --> `Fruit` + * - `Fruit.Apple` --> `Fruit` + */ +function getBaseEnumType(typeChecker, type) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const symbol = type.getSymbol(); + if (!tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.EnumMember)) { + return type; + } + return typeChecker.getTypeAtLocation(symbol.valueDeclaration.parent); +} +/** + * Retrieve only the Enum literals from a type. for example: + * - 123 --> [] + * - {} --> [] + * - Fruit.Apple --> [Fruit.Apple] + * - Fruit.Apple | Vegetable.Lettuce --> [Fruit.Apple, Vegetable.Lettuce] + * - Fruit.Apple | Vegetable.Lettuce | 123 --> [Fruit.Apple, Vegetable.Lettuce] + * - T extends Fruit --> [Fruit] + */ +function getEnumLiterals(type) { + return tsutils + .unionConstituents(type) + .filter((subType) => (0, util_1.isTypeFlagSet)(subType, ts.TypeFlags.EnumLiteral)); +} +/** + * A type can have 0 or more enum types. For example: + * - 123 --> [] + * - {} --> [] + * - Fruit.Apple --> [Fruit] + * - Fruit.Apple | Vegetable.Lettuce --> [Fruit, Vegetable] + * - Fruit.Apple | Vegetable.Lettuce | 123 --> [Fruit, Vegetable] + * - T extends Fruit --> [Fruit] + */ +function getEnumTypes(typeChecker, type) { + return getEnumLiterals(type).map(type => getBaseEnumType(typeChecker, type)); +} +/** + * Returns the enum key that matches the given literal node, or null if none + * match. For example: + * ```ts + * enum Fruit { + * Apple = 'apple', + * Banana = 'banana', + * } + * + * getEnumKeyForLiteral([Fruit.Apple, Fruit.Banana], 'apple') --> 'Fruit.Apple' + * getEnumKeyForLiteral([Fruit.Apple, Fruit.Banana], 'banana') --> 'Fruit.Banana' + * getEnumKeyForLiteral([Fruit.Apple, Fruit.Banana], 'cherry') --> null + * ``` + */ +function getEnumKeyForLiteral(enumLiterals, literal) { + for (const enumLiteral of enumLiterals) { + if (enumLiteral.value === literal) { + const { symbol } = enumLiteral; + const memberDeclaration = symbol.valueDeclaration; + const enumDeclaration = memberDeclaration.parent; + const memberNameIdentifier = memberDeclaration.name; + const enumName = enumDeclaration.name.text; + switch (memberNameIdentifier.kind) { + case ts.SyntaxKind.Identifier: + return `${enumName}.${memberNameIdentifier.text}`; + case ts.SyntaxKind.StringLiteral: { + const memberName = memberNameIdentifier.text.replaceAll("'", "\\'"); + return `${enumName}['${memberName}']`; + } + case ts.SyntaxKind.ComputedPropertyName: + return `${enumName}[${memberNameIdentifier.expression.getText()}]`; + default: + break; + } + } + } + return null; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-function-return-type.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-function-return-type.d.ts new file mode 100644 index 00000000..6ec20c0b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-function-return-type.d.ts @@ -0,0 +1,16 @@ +export type Options = [ + { + allowConciseArrowFunctionExpressionsStartingWithVoid?: boolean; + allowDirectConstAssertionInArrowFunctions?: boolean; + allowedNames?: string[]; + allowExpressions?: boolean; + allowFunctionsWithoutTypeParameters?: boolean; + allowHigherOrderFunctions?: boolean; + allowIIFEs?: boolean; + allowTypedFunctionExpressions?: boolean; + } +]; +export type MessageIds = 'missingReturnType'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingReturnType", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=explicit-function-return-type.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-function-return-type.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-function-return-type.d.ts.map new file mode 100644 index 00000000..253270ff --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-function-return-type.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"explicit-function-return-type.d.ts","sourceRoot":"","sources":["../../src/rules/explicit-function-return-type.ts"],"names":[],"mappings":"AAaA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,oDAAoD,CAAC,EAAE,OAAO,CAAC;QAC/D,yCAAyC,CAAC,EAAE,OAAO,CAAC;QACpD,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;QACxB,gBAAgB,CAAC,EAAE,OAAO,CAAC;QAC3B,mCAAmC,CAAC,EAAE,OAAO,CAAC;QAC9C,yBAAyB,CAAC,EAAE,OAAO,CAAC;QACpC,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,6BAA6B,CAAC,EAAE,OAAO,CAAC;KACzC;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,mBAAmB,CAAC;;AAO7C,wBAiOG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-function-return-type.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-function-return-type.js new file mode 100644 index 00000000..ae6089e1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-function-return-type.js @@ -0,0 +1,179 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const explicitReturnTypeUtils_1 = require("../util/explicitReturnTypeUtils"); +exports.default = (0, util_1.createRule)({ + name: 'explicit-function-return-type', + meta: { + type: 'problem', + docs: { + description: 'Require explicit return types on functions and class methods', + }, + messages: { + missingReturnType: 'Missing return type on function.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowConciseArrowFunctionExpressionsStartingWithVoid: { + type: 'boolean', + description: 'Whether to allow arrow functions that start with the `void` keyword.', + }, + allowDirectConstAssertionInArrowFunctions: { + type: 'boolean', + description: 'Whether to ignore arrow functions immediately returning a `as const` value.', + }, + allowedNames: { + type: 'array', + description: 'An array of function/method names that will not have their arguments or return values checked.', + items: { + type: 'string', + }, + }, + allowExpressions: { + type: 'boolean', + description: 'Whether to ignore function expressions (functions which are not part of a declaration).', + }, + allowFunctionsWithoutTypeParameters: { + type: 'boolean', + description: "Whether to ignore functions that don't have generic type parameters.", + }, + allowHigherOrderFunctions: { + type: 'boolean', + description: 'Whether to ignore functions immediately returning another function expression.', + }, + allowIIFEs: { + type: 'boolean', + description: 'Whether to ignore immediately invoked function expressions (IIFEs).', + }, + allowTypedFunctionExpressions: { + type: 'boolean', + description: 'Whether to ignore type annotations on the variable of function expressions.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowConciseArrowFunctionExpressionsStartingWithVoid: false, + allowDirectConstAssertionInArrowFunctions: true, + allowedNames: [], + allowExpressions: false, + allowFunctionsWithoutTypeParameters: false, + allowHigherOrderFunctions: true, + allowIIFEs: false, + allowTypedFunctionExpressions: true, + }, + ], + create(context, [options]) { + const functionInfoStack = []; + function enterFunction(node) { + functionInfoStack.push({ + node, + returns: [], + }); + } + function popFunctionInfo(exitNodeType) { + return (0, util_1.nullThrows)(functionInfoStack.pop(), `Stack should exist on ${exitNodeType} exit`); + } + function isAllowedFunction(node) { + if (options.allowFunctionsWithoutTypeParameters && !node.typeParameters) { + return true; + } + if (options.allowIIFEs && isIIFE(node)) { + return true; + } + if (!options.allowedNames?.length) { + return false; + } + if (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression || + node.type === utils_1.AST_NODE_TYPES.FunctionExpression) { + const parent = node.parent; + let funcName; + if (node.id?.name) { + funcName = node.id.name; + } + else { + switch (parent.type) { + case utils_1.AST_NODE_TYPES.VariableDeclarator: { + if (parent.id.type === utils_1.AST_NODE_TYPES.Identifier) { + funcName = parent.id.name; + } + break; + } + case utils_1.AST_NODE_TYPES.MethodDefinition: + case utils_1.AST_NODE_TYPES.PropertyDefinition: + case utils_1.AST_NODE_TYPES.Property: { + if (parent.key.type === utils_1.AST_NODE_TYPES.Identifier && + !parent.computed) { + funcName = parent.key.name; + } + break; + } + } + } + if (!!funcName && options.allowedNames.includes(funcName)) { + return true; + } + } + if (node.type === utils_1.AST_NODE_TYPES.FunctionDeclaration && + node.id && + options.allowedNames.includes(node.id.name)) { + return true; + } + return false; + } + function isIIFE(node) { + return node.parent.type === utils_1.AST_NODE_TYPES.CallExpression; + } + function exitFunctionExpression(node) { + const info = popFunctionInfo('function expression'); + if (options.allowConciseArrowFunctionExpressionsStartingWithVoid && + node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + node.expression && + node.body.type === utils_1.AST_NODE_TYPES.UnaryExpression && + node.body.operator === 'void') { + return; + } + if (isAllowedFunction(node)) { + return; + } + if (options.allowTypedFunctionExpressions && + ((0, explicitReturnTypeUtils_1.isValidFunctionExpressionReturnType)(node, options) || + (0, explicitReturnTypeUtils_1.ancestorHasReturnType)(node))) { + return; + } + (0, explicitReturnTypeUtils_1.checkFunctionReturnType)(info, options, context.sourceCode, loc => context.report({ + loc, + node, + messageId: 'missingReturnType', + })); + } + return { + 'ArrowFunctionExpression, FunctionExpression, FunctionDeclaration': enterFunction, + 'ArrowFunctionExpression:exit': exitFunctionExpression, + 'FunctionDeclaration:exit'(node) { + const info = popFunctionInfo('function declaration'); + if (isAllowedFunction(node)) { + return; + } + if (options.allowTypedFunctionExpressions && node.returnType) { + return; + } + (0, explicitReturnTypeUtils_1.checkFunctionReturnType)(info, options, context.sourceCode, loc => context.report({ + loc, + node, + messageId: 'missingReturnType', + })); + }, + 'FunctionExpression:exit': exitFunctionExpression, + ReturnStatement(node) { + functionInfoStack.at(-1)?.returns.push(node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-member-accessibility.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-member-accessibility.d.ts new file mode 100644 index 00000000..a5352698 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-member-accessibility.d.ts @@ -0,0 +1,18 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +type AccessibilityLevel = 'explicit' | 'no-public' | 'off'; +export interface Config { + accessibility?: AccessibilityLevel; + ignoredMethodNames?: string[]; + overrides?: { + accessors?: AccessibilityLevel; + constructors?: AccessibilityLevel; + methods?: AccessibilityLevel; + parameterProperties?: AccessibilityLevel; + properties?: AccessibilityLevel; + }; +} +export type Options = [Config]; +export type MessageIds = 'addExplicitAccessibility' | 'missingAccessibility' | 'unwantedPublicAccessibility'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=explicit-member-accessibility.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-member-accessibility.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-member-accessibility.d.ts.map new file mode 100644 index 00000000..5e9ddfca --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-member-accessibility.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"explicit-member-accessibility.d.ts","sourceRoot":"","sources":["../../src/rules/explicit-member-accessibility.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAgBnE,KAAK,kBAAkB,GACnB,UAAU,GACV,WAAW,GACX,KAAK,CAAC;AAEV,MAAM,WAAW,MAAM;IACrB,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9B,SAAS,CAAC,EAAE;QACV,SAAS,CAAC,EAAE,kBAAkB,CAAC;QAC/B,YAAY,CAAC,EAAE,kBAAkB,CAAC;QAClC,OAAO,CAAC,EAAE,kBAAkB,CAAC;QAC7B,mBAAmB,CAAC,EAAE,kBAAkB,CAAC;QACzC,UAAU,CAAC,EAAE,kBAAkB,CAAC;KACjC,CAAC;CACH;AAED,MAAM,MAAM,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC;AAE/B,MAAM,MAAM,UAAU,GAClB,0BAA0B,GAC1B,sBAAsB,GACtB,6BAA6B,CAAC;;AAElC,wBA0WG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-member-accessibility.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-member-accessibility.js new file mode 100644 index 00000000..772dba01 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-member-accessibility.js @@ -0,0 +1,292 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getMemberHeadLoc_1 = require("../util/getMemberHeadLoc"); +const rangeToLoc_1 = require("../util/rangeToLoc"); +exports.default = (0, util_1.createRule)({ + name: 'explicit-member-accessibility', + meta: { + type: 'problem', + docs: { + description: 'Require explicit accessibility modifiers on class properties and methods', + // too opinionated to be recommended + }, + fixable: 'code', + hasSuggestions: true, + messages: { + addExplicitAccessibility: "Add '{{ type }}' accessibility modifier", + missingAccessibility: 'Missing accessibility modifier on {{type}} {{name}}.', + unwantedPublicAccessibility: 'Public accessibility modifier on {{type}} {{name}}.', + }, + schema: [ + { + type: 'object', + $defs: { + accessibilityLevel: { + oneOf: [ + { + type: 'string', + description: 'Always require an accessor.', + enum: ['explicit'], + }, + { + type: 'string', + description: 'Require an accessor except when public.', + enum: ['no-public'], + }, + { + type: 'string', + description: 'Never check whether there is an accessor.', + enum: ['off'], + }, + ], + }, + }, + additionalProperties: false, + properties: { + accessibility: { + $ref: '#/items/0/$defs/accessibilityLevel', + description: 'Which accessibility modifier is required to exist or not exist.', + }, + ignoredMethodNames: { + type: 'array', + description: 'Specific method names that may be ignored.', + items: { + type: 'string', + }, + }, + overrides: { + type: 'object', + additionalProperties: false, + description: 'Changes to required accessibility modifiers for specific kinds of class members.', + properties: { + accessors: { $ref: '#/items/0/$defs/accessibilityLevel' }, + constructors: { $ref: '#/items/0/$defs/accessibilityLevel' }, + methods: { $ref: '#/items/0/$defs/accessibilityLevel' }, + parameterProperties: { + $ref: '#/items/0/$defs/accessibilityLevel', + }, + properties: { $ref: '#/items/0/$defs/accessibilityLevel' }, + }, + }, + }, + }, + ], + }, + defaultOptions: [{ accessibility: 'explicit' }], + create(context, [option]) { + const baseCheck = option.accessibility ?? 'explicit'; + const overrides = option.overrides ?? {}; + const ctorCheck = overrides.constructors ?? baseCheck; + const accessorCheck = overrides.accessors ?? baseCheck; + const methodCheck = overrides.methods ?? baseCheck; + const propCheck = overrides.properties ?? baseCheck; + const paramPropCheck = overrides.parameterProperties ?? baseCheck; + const ignoredMethodNames = new Set(option.ignoredMethodNames ?? []); + /** + * Checks if a method declaration has an accessibility modifier. + * @param methodDefinition The node representing a MethodDefinition. + */ + function checkMethodAccessibilityModifier(methodDefinition) { + if (methodDefinition.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) { + return; + } + let nodeType = 'method definition'; + let check = baseCheck; + switch (methodDefinition.kind) { + case 'method': + check = methodCheck; + break; + case 'constructor': + check = ctorCheck; + break; + case 'get': + case 'set': + check = accessorCheck; + nodeType = `${methodDefinition.kind} property accessor`; + break; + } + const { name: methodName } = (0, util_1.getNameFromMember)(methodDefinition, context.sourceCode); + if (check === 'off' || ignoredMethodNames.has(methodName)) { + return; + } + if (check === 'no-public' && + methodDefinition.accessibility === 'public') { + const publicKeyword = findPublicKeyword(methodDefinition); + context.report({ + loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, publicKeyword.range), + messageId: 'unwantedPublicAccessibility', + data: { + name: methodName, + type: nodeType, + }, + fix: fixer => fixer.removeRange(publicKeyword.rangeToRemove), + }); + } + else if (check === 'explicit' && !methodDefinition.accessibility) { + context.report({ + loc: (0, getMemberHeadLoc_1.getMemberHeadLoc)(context.sourceCode, methodDefinition), + messageId: 'missingAccessibility', + data: { + name: methodName, + type: nodeType, + }, + suggest: getMissingAccessibilitySuggestions(methodDefinition), + }); + } + } + /** + * Returns an object containing a range that corresponds to the "public" + * keyword for a node, and the range that would need to be removed to + * remove the "public" keyword (including associated whitespace). + */ + function findPublicKeyword(node) { + const tokens = context.sourceCode.getTokens(node); + let rangeToRemove; + let keywordRange; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (token.type === utils_1.AST_TOKEN_TYPES.Keyword && + token.value === 'public') { + keywordRange = structuredClone(token.range); + const commensAfterPublicKeyword = context.sourceCode.getCommentsAfter(token); + if (commensAfterPublicKeyword.length) { + // public /* Hi there! */ static foo() + // ^^^^^^^ + rangeToRemove = [ + token.range[0], + commensAfterPublicKeyword[0].range[0], + ]; + break; + } + else { + // public static foo() + // ^^^^^^^ + rangeToRemove = [token.range[0], tokens[i + 1].range[0]]; + break; + } + } + } + return { range: keywordRange, rangeToRemove }; + } + /** + * Creates a fixer that adds an accessibility modifier keyword + */ + function getMissingAccessibilitySuggestions(node) { + function fix(accessibility, fixer) { + if (node.decorators.length) { + const lastDecorator = node.decorators[node.decorators.length - 1]; + const nextToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(lastDecorator), util_1.NullThrowsReasons.MissingToken('token', 'last decorator')); + return fixer.insertTextBefore(nextToken, `${accessibility} `); + } + return fixer.insertTextBefore(node, `${accessibility} `); + } + return [ + { + messageId: 'addExplicitAccessibility', + data: { type: 'public' }, + fix: fixer => fix('public', fixer), + }, + { + messageId: 'addExplicitAccessibility', + data: { type: 'private' }, + fix: fixer => fix('private', fixer), + }, + { + messageId: 'addExplicitAccessibility', + data: { type: 'protected' }, + fix: fixer => fix('protected', fixer), + }, + ]; + } + /** + * Checks if property has an accessibility modifier. + * @param propertyDefinition The node representing a PropertyDefinition. + */ + function checkPropertyAccessibilityModifier(propertyDefinition) { + if (propertyDefinition.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) { + return; + } + const nodeType = 'class property'; + const { name: propertyName } = (0, util_1.getNameFromMember)(propertyDefinition, context.sourceCode); + if (propCheck === 'no-public' && + propertyDefinition.accessibility === 'public') { + const publicKeywordRange = findPublicKeyword(propertyDefinition); + context.report({ + loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, publicKeywordRange.range), + messageId: 'unwantedPublicAccessibility', + data: { + name: propertyName, + type: nodeType, + }, + fix: fixer => fixer.removeRange(publicKeywordRange.rangeToRemove), + }); + } + else if (propCheck === 'explicit' && + !propertyDefinition.accessibility) { + context.report({ + loc: (0, getMemberHeadLoc_1.getMemberHeadLoc)(context.sourceCode, propertyDefinition), + messageId: 'missingAccessibility', + data: { + name: propertyName, + type: nodeType, + }, + suggest: getMissingAccessibilitySuggestions(propertyDefinition), + }); + } + } + /** + * Checks that the parameter property has the desired accessibility modifiers set. + * @param node The node representing a Parameter Property + */ + function checkParameterPropertyAccessibilityModifier(node) { + const nodeType = 'parameter property'; + // HAS to be an identifier or assignment or TSC will throw + if (node.parameter.type !== utils_1.AST_NODE_TYPES.Identifier && + node.parameter.type !== utils_1.AST_NODE_TYPES.AssignmentPattern) { + return; + } + const nodeName = node.parameter.type === utils_1.AST_NODE_TYPES.Identifier + ? node.parameter.name + : // has to be an Identifier or TSC will throw an error + node.parameter.left.name; + switch (paramPropCheck) { + case 'explicit': { + if (!node.accessibility) { + context.report({ + loc: (0, getMemberHeadLoc_1.getParameterPropertyHeadLoc)(context.sourceCode, node, nodeName), + messageId: 'missingAccessibility', + data: { + name: nodeName, + type: nodeType, + }, + suggest: getMissingAccessibilitySuggestions(node), + }); + } + break; + } + case 'no-public': { + if (node.accessibility === 'public' && node.readonly) { + const publicKeyword = findPublicKeyword(node); + context.report({ + loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, publicKeyword.range), + messageId: 'unwantedPublicAccessibility', + data: { + name: nodeName, + type: nodeType, + }, + fix: fixer => fixer.removeRange(publicKeyword.rangeToRemove), + }); + } + break; + } + } + } + return { + 'MethodDefinition, TSAbstractMethodDefinition': checkMethodAccessibilityModifier, + 'PropertyDefinition, TSAbstractPropertyDefinition, AccessorProperty, TSAbstractAccessorProperty': checkPropertyAccessibilityModifier, + TSParameterProperty: checkParameterPropertyAccessibilityModifier, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-module-boundary-types.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-module-boundary-types.d.ts new file mode 100644 index 00000000..de6a2a50 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-module-boundary-types.d.ts @@ -0,0 +1,14 @@ +export type Options = [ + { + allowArgumentsExplicitlyTypedAsAny?: boolean; + allowDirectConstAssertionInArrowFunctions?: boolean; + allowedNames?: string[]; + allowHigherOrderFunctions?: boolean; + allowTypedFunctionExpressions?: boolean; + allowOverloadFunctions?: boolean; + } +]; +export type MessageIds = 'anyTypedArg' | 'anyTypedArgUnnamed' | 'missingArgType' | 'missingArgTypeUnnamed' | 'missingReturnType'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=explicit-module-boundary-types.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-module-boundary-types.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-module-boundary-types.d.ts.map new file mode 100644 index 00000000..bcf25523 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-module-boundary-types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"explicit-module-boundary-types.d.ts","sourceRoot":"","sources":["../../src/rules/explicit-module-boundary-types.ts"],"names":[],"mappings":"AAyBA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,kCAAkC,CAAC,EAAE,OAAO,CAAC;QAC7C,yCAAyC,CAAC,EAAE,OAAO,CAAC;QACpD,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;QACxB,yBAAyB,CAAC,EAAE,OAAO,CAAC;QACpC,6BAA6B,CAAC,EAAE,OAAO,CAAC;QACxC,sBAAsB,CAAC,EAAE,OAAO,CAAC;KAClC;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAClB,aAAa,GACb,oBAAoB,GACpB,gBAAgB,GAChB,uBAAuB,GACvB,mBAAmB,CAAC;;AAExB,wBAweG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-module-boundary-types.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-module-boundary-types.js new file mode 100644 index 00000000..eebf8350 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/explicit-module-boundary-types.js @@ -0,0 +1,386 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const explicitReturnTypeUtils_1 = require("../util/explicitReturnTypeUtils"); +exports.default = (0, util_1.createRule)({ + name: 'explicit-module-boundary-types', + meta: { + type: 'problem', + docs: { + description: "Require explicit return and argument types on exported functions' and classes' public class methods", + }, + messages: { + anyTypedArg: "Argument '{{name}}' should be typed with a non-any type.", + anyTypedArgUnnamed: '{{type}} argument should be typed with a non-any type.', + missingArgType: "Argument '{{name}}' should be typed.", + missingArgTypeUnnamed: '{{type}} argument should be typed.', + missingReturnType: 'Missing return type on function.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowArgumentsExplicitlyTypedAsAny: { + type: 'boolean', + description: 'Whether to ignore arguments that are explicitly typed as `any`.', + }, + allowDirectConstAssertionInArrowFunctions: { + type: 'boolean', + description: [ + 'Whether to ignore return type annotations on body-less arrow functions that return an `as const` type assertion.', + 'You must still type the parameters of the function.', + ].join('\n'), + }, + allowedNames: { + type: 'array', + description: 'An array of function/method names that will not have their arguments or return values checked.', + items: { + type: 'string', + }, + }, + allowHigherOrderFunctions: { + type: 'boolean', + description: [ + 'Whether to ignore return type annotations on functions immediately returning another function expression.', + 'You must still type the parameters of the function.', + ].join('\n'), + }, + allowOverloadFunctions: { + type: 'boolean', + description: 'Whether to ignore return type annotations on functions with overload signatures.', + }, + allowTypedFunctionExpressions: { + type: 'boolean', + description: 'Whether to ignore type annotations on the variable of a function expression.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowArgumentsExplicitlyTypedAsAny: false, + allowDirectConstAssertionInArrowFunctions: true, + allowedNames: [], + allowHigherOrderFunctions: true, + allowOverloadFunctions: false, + allowTypedFunctionExpressions: true, + }, + ], + create(context, [options]) { + // tracks all of the functions we've already checked + const checkedFunctions = new Set(); + const functionStack = []; + const functionReturnsMap = new Map(); + // all nodes visited, avoids infinite recursion for cyclic references + // (such as class member referring to itself) + const alreadyVisited = new Set(); + function getReturnsInFunction(node) { + return functionReturnsMap.get(node) ?? []; + } + function enterFunction(node) { + functionStack.push(node); + functionReturnsMap.set(node, []); + } + function exitFunction() { + functionStack.pop(); + } + /* + # How the rule works: + + As the rule traverses the AST, it immediately checks every single function that it finds is exported. + "exported" means that it is either directly exported, or that its name is exported. + + It also collects a list of every single function it finds on the way, but does not check them. + After it's finished traversing the AST, it then iterates through the list of found functions, and checks to see if + any of them are part of a higher-order function + */ + return { + 'ArrowFunctionExpression, FunctionDeclaration, FunctionExpression': enterFunction, + 'ArrowFunctionExpression:exit': exitFunction, + 'ExportDefaultDeclaration:exit'(node) { + checkNode(node.declaration); + }, + 'ExportNamedDeclaration:not([source]):exit'(node) { + if (node.declaration) { + checkNode(node.declaration); + } + else { + for (const specifier of node.specifiers) { + followReference(specifier.local); + } + } + }, + 'FunctionDeclaration:exit': exitFunction, + 'FunctionExpression:exit': exitFunction, + 'Program:exit'() { + for (const [node, returns] of functionReturnsMap) { + if (isExportedHigherOrderFunction({ node, returns })) { + checkNode(node); + } + } + }, + ReturnStatement(node) { + const current = functionStack[functionStack.length - 1]; + functionReturnsMap.get(current)?.push(node); + }, + 'TSExportAssignment:exit'(node) { + checkNode(node.expression); + }, + }; + function checkParameters(node) { + function checkParameter(param) { + function report(namedMessageId, unnamedMessageId) { + if (param.type === utils_1.AST_NODE_TYPES.Identifier) { + context.report({ + node: param, + messageId: namedMessageId, + data: { name: param.name }, + }); + } + else if (param.type === utils_1.AST_NODE_TYPES.ArrayPattern) { + context.report({ + node: param, + messageId: unnamedMessageId, + data: { type: 'Array pattern' }, + }); + } + else if (param.type === utils_1.AST_NODE_TYPES.ObjectPattern) { + context.report({ + node: param, + messageId: unnamedMessageId, + data: { type: 'Object pattern' }, + }); + } + else if (param.type === utils_1.AST_NODE_TYPES.RestElement) { + if (param.argument.type === utils_1.AST_NODE_TYPES.Identifier) { + context.report({ + node: param, + messageId: namedMessageId, + data: { name: param.argument.name }, + }); + } + else { + context.report({ + node: param, + messageId: unnamedMessageId, + data: { type: 'Rest' }, + }); + } + } + } + switch (param.type) { + case utils_1.AST_NODE_TYPES.ArrayPattern: + case utils_1.AST_NODE_TYPES.Identifier: + case utils_1.AST_NODE_TYPES.ObjectPattern: + case utils_1.AST_NODE_TYPES.RestElement: + if (!param.typeAnnotation) { + report('missingArgType', 'missingArgTypeUnnamed'); + } + else if (options.allowArgumentsExplicitlyTypedAsAny !== true && + param.typeAnnotation.typeAnnotation.type === + utils_1.AST_NODE_TYPES.TSAnyKeyword) { + report('anyTypedArg', 'anyTypedArgUnnamed'); + } + return; + case utils_1.AST_NODE_TYPES.TSParameterProperty: + return checkParameter(param.parameter); + case utils_1.AST_NODE_TYPES.AssignmentPattern: // ignored as it has a type via its assignment + return; + } + } + for (const arg of node.params) { + checkParameter(arg); + } + } + /** + * Checks if a function name is allowed and should not be checked. + */ + function isAllowedName(node) { + if (!node || !options.allowedNames || options.allowedNames.length === 0) { + return false; + } + if (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator || + node.type === utils_1.AST_NODE_TYPES.FunctionDeclaration) { + return (node.id?.type === utils_1.AST_NODE_TYPES.Identifier && + options.allowedNames.includes(node.id.name)); + } + if (node.type === utils_1.AST_NODE_TYPES.MethodDefinition || + node.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition || + (node.type === utils_1.AST_NODE_TYPES.Property && node.method) || + node.type === utils_1.AST_NODE_TYPES.PropertyDefinition || + node.type === utils_1.AST_NODE_TYPES.AccessorProperty) { + return (0, util_1.isStaticMemberAccessOfValue)(node, context, ...options.allowedNames); + } + return false; + } + function isExportedHigherOrderFunction({ node, }) { + let current = node.parent; + while (current) { + if (current.type === utils_1.AST_NODE_TYPES.ReturnStatement) { + // the parent of a return will always be a block statement, so we can skip over it + current = current.parent.parent; + continue; + } + if (!(0, util_1.isFunction)(current)) { + return false; + } + const returns = getReturnsInFunction(current); + if (!(0, explicitReturnTypeUtils_1.doesImmediatelyReturnFunctionExpression)({ node: current, returns })) { + return false; + } + if (checkedFunctions.has(current)) { + return true; + } + current = current.parent; + } + return false; + } + function followReference(node) { + const scope = context.sourceCode.getScope(node); + const variable = scope.set.get(node.name); + /* istanbul ignore if */ if (!variable) { + return; + } + // check all of the definitions + for (const definition of variable.defs) { + // cases we don't care about in this rule + if ([ + scope_manager_1.DefinitionType.CatchClause, + scope_manager_1.DefinitionType.ImplicitGlobalVariable, + scope_manager_1.DefinitionType.ImportBinding, + scope_manager_1.DefinitionType.Parameter, + ].includes(definition.type)) { + continue; + } + checkNode(definition.node); + } + // follow references to find writes to the variable + for (const reference of variable.references) { + if ( + // we don't want to check the initialization ref, as this is handled by the declaration check + !reference.init && + reference.writeExpr) { + checkNode(reference.writeExpr); + } + } + } + function checkNode(node) { + if (node == null || alreadyVisited.has(node)) { + return; + } + alreadyVisited.add(node); + switch (node.type) { + case utils_1.AST_NODE_TYPES.ArrowFunctionExpression: + case utils_1.AST_NODE_TYPES.FunctionExpression: { + const returns = getReturnsInFunction(node); + return checkFunctionExpression({ node, returns }); + } + case utils_1.AST_NODE_TYPES.ArrayExpression: + for (const element of node.elements) { + checkNode(element); + } + return; + case utils_1.AST_NODE_TYPES.PropertyDefinition: + case utils_1.AST_NODE_TYPES.AccessorProperty: + case utils_1.AST_NODE_TYPES.MethodDefinition: + case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition: + if (node.accessibility === 'private' || + node.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) { + return; + } + return checkNode(node.value); + case utils_1.AST_NODE_TYPES.ClassDeclaration: + case utils_1.AST_NODE_TYPES.ClassExpression: + for (const element of node.body.body) { + checkNode(element); + } + return; + case utils_1.AST_NODE_TYPES.FunctionDeclaration: { + const returns = getReturnsInFunction(node); + return checkFunction({ node, returns }); + } + case utils_1.AST_NODE_TYPES.Identifier: + return followReference(node); + case utils_1.AST_NODE_TYPES.ObjectExpression: + for (const property of node.properties) { + checkNode(property); + } + return; + case utils_1.AST_NODE_TYPES.Property: + return checkNode(node.value); + case utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression: + return checkEmptyBodyFunctionExpression(node); + case utils_1.AST_NODE_TYPES.VariableDeclaration: + for (const declaration of node.declarations) { + checkNode(declaration); + } + return; + case utils_1.AST_NODE_TYPES.VariableDeclarator: + return checkNode(node.init); + } + } + function checkEmptyBodyFunctionExpression(node) { + const isConstructor = node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition && + node.parent.kind === 'constructor'; + const isSetAccessor = (node.parent.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition || + node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition) && + node.parent.kind === 'set'; + if (!isConstructor && !isSetAccessor && !node.returnType) { + context.report({ + node, + messageId: 'missingReturnType', + }); + } + checkParameters(node); + } + function checkFunctionExpression({ node, returns, }) { + if (checkedFunctions.has(node)) { + return; + } + checkedFunctions.add(node); + if (isAllowedName(node.parent) || + (0, explicitReturnTypeUtils_1.isTypedFunctionExpression)(node, options) || + (0, explicitReturnTypeUtils_1.ancestorHasReturnType)(node)) { + return; + } + if (options.allowOverloadFunctions && + node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition && + (0, util_1.hasOverloadSignatures)(node.parent, context)) { + return; + } + (0, explicitReturnTypeUtils_1.checkFunctionExpressionReturnType)({ node, returns }, options, context.sourceCode, loc => { + context.report({ + loc, + node, + messageId: 'missingReturnType', + }); + }); + checkParameters(node); + } + function checkFunction({ node, returns, }) { + if (checkedFunctions.has(node)) { + return; + } + checkedFunctions.add(node); + if (isAllowedName(node) || (0, explicitReturnTypeUtils_1.ancestorHasReturnType)(node)) { + return; + } + if (options.allowOverloadFunctions && + (0, util_1.hasOverloadSignatures)(node, context)) { + return; + } + (0, explicitReturnTypeUtils_1.checkFunctionReturnType)({ node, returns }, options, context.sourceCode, loc => { + context.report({ + loc, + node, + messageId: 'missingReturnType', + }); + }); + checkParameters(node); + } + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.d.ts new file mode 100644 index 00000000..c19a484f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.d.ts @@ -0,0 +1,174 @@ +declare const rules: { + 'adjacent-overload-signatures': import("@typescript-eslint/utils/ts-eslint").RuleModule<"adjacentSignature", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'array-type': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'await-thenable': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'ban-ts-comment': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'ban-tslint-comment': import("@typescript-eslint/utils/ts-eslint").RuleModule<"commentDetected", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'class-literal-property-style': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'class-methods-use-this': import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingThis", import("./class-methods-use-this").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'consistent-generic-constructors': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'consistent-indexed-object-style': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'consistent-return': import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingReturn" | "missingReturnValue" | "unexpectedReturnValue", [({ + treatUndefinedAsUnspecified?: boolean; + } | undefined)?], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'consistent-type-assertions': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'consistent-type-definitions': import("@typescript-eslint/utils/ts-eslint").RuleModule<"interfaceOverType" | "typeOverInterface", [string], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'consistent-type-exports': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'consistent-type-imports': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'default-param-last': import("@typescript-eslint/utils/ts-eslint").RuleModule<"shouldBeLast", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'dot-notation': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useBrackets" | "useDot", [{ + allowIndexSignaturePropertyAccess?: boolean; + allowKeywords?: boolean; + allowPattern?: string; + allowPrivateClassPropertyAccess?: boolean; + allowProtectedClassPropertyAccess?: boolean; + }], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'explicit-function-return-type': import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingReturnType", import("./explicit-function-return-type").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'explicit-member-accessibility': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'explicit-module-boundary-types': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'init-declarations': import("@typescript-eslint/utils/ts-eslint").RuleModule<"initialized" | "notInitialized", ["always" | "never", ({ + ignoreForLoopInit?: boolean; + } | undefined)?], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'max-params': import("@typescript-eslint/utils/ts-eslint").RuleModule<"exceed", ({ + countVoidThis?: boolean; + max: number; + } | { + countVoidThis?: boolean; + maximum: number; + })[], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'member-ordering': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'method-signature-style': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'naming-convention': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-array-constructor': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useLiteral", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-array-delete': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-base-to-string': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-confusing-non-null-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-confusing-void-expression': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-deprecated': import("@typescript-eslint/utils/ts-eslint").RuleModule<"deprecated" | "deprecatedWithReason", [{ + allow?: import("@typescript-eslint/type-utils").TypeOrValueSpecifier[]; + }], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-dupe-class-members': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpected", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-duplicate-enum-values': import("@typescript-eslint/utils/ts-eslint").RuleModule<"duplicateValue", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-duplicate-type-constituents': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-dynamic-delete': import("@typescript-eslint/utils/ts-eslint").RuleModule<"dynamicDelete", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-empty-function': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpected", [{ + allow?: string[]; + }], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-empty-interface': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-empty-object-type': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-explicit-any': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-extra-non-null-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noExtraNonNullAssertion", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-extraneous-class': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-floating-promises': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-for-in-array': import("@typescript-eslint/utils/ts-eslint").RuleModule<"forInViolation", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-implied-eval': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noFunctionConstructor" | "noImpliedEvalError", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-import-type-side-effects': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useTopLevelQualifier", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-inferrable-types': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noInferrableType", import("./no-inferrable-types").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-invalid-this': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpectedThis", [({ + capIsConstructor?: boolean; + } | undefined)?], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-invalid-void-type': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-loop-func': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeRefs", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-loss-of-precision': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noLossOfPrecision", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-magic-numbers': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noMagic", [{ + detectObjects?: boolean; + enforceConst?: boolean; + ignore?: (number | string)[]; + ignoreArrayIndexes?: boolean; + ignoreEnums?: boolean; + ignoreNumericLiteralTypes?: boolean; + ignoreReadonlyClassProperties?: boolean; + ignoreTypeIndexes?: boolean; + }], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-meaningless-void-operator': import("@typescript-eslint/utils/ts-eslint").RuleModule<"meaninglessVoidOperator" | "removeVoid", import("./no-meaningless-void-operator").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-misused-new': import("@typescript-eslint/utils/ts-eslint").RuleModule<"errorMessageClass" | "errorMessageInterface", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-misused-promises': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-misused-spread': import("@typescript-eslint/utils/ts-eslint").RuleModule<"addAwait" | "noArraySpreadInObject" | "noClassDeclarationSpreadInObject" | "noClassInstanceSpreadInObject" | "noFunctionSpreadInObject" | "noIterableSpreadInObject" | "noMapSpreadInObject" | "noPromiseSpreadInObject" | "noStringSpread" | "replaceMapSpreadInObject", [{ + allow?: import("@typescript-eslint/type-utils").TypeOrValueSpecifier[]; + }], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-mixed-enums': import("@typescript-eslint/utils/ts-eslint").RuleModule<"mixed", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-namespace': import("@typescript-eslint/utils/ts-eslint").RuleModule<"moduleSyntaxIsPreferred", import("./no-namespace").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-non-null-asserted-nullish-coalescing': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noNonNullAssertedNullishCoalescing" | "suggestRemovingNonNull", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-non-null-asserted-optional-chain': import("@typescript-eslint/utils/ts-eslint").RuleModule<"suggestRemovingNonNull" | "noNonNullOptionalChain", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-non-null-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-redeclare': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-redundant-type-constituents': import("@typescript-eslint/utils/ts-eslint").RuleModule<"overrides" | "errorTypeOverrides" | "literalOverridden" | "overridden" | "primitiveOverridden", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-require-imports': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noRequireImports", import("./no-require-imports").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-restricted-imports': import("@typescript-eslint/utils/ts-eslint").RuleModule<"everything" | "everythingWithCustomMessage" | "importName" | "importNameWithCustomMessage" | "path" | "pathWithCustomMessage" | "patterns" | "patternWithCustomMessage", [import("eslint/lib/rules/no-restricted-imports").ObjectOfPathsAndPatterns] | import("eslint/lib/rules/no-restricted-imports").ArrayOfStringOrObject, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-restricted-types': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-shadow': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-this-alias': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-type-alias': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unnecessary-boolean-literal-compare': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unnecessary-condition': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unnecessary-parameter-property-assignment': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unnecessaryAssign", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-qualifier': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unnecessaryQualifier", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-template-expression': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noUnnecessaryTemplateExpression", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-type-arguments': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unnecessaryTypeParameter", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-type-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unnecessary-type-constraint': import("@typescript-eslint/utils/ts-eslint").RuleModule<"removeUnnecessaryConstraint" | "unnecessaryConstraint", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-type-conversion': import("@typescript-eslint/utils/ts-eslint").RuleModule<"suggestRemove" | "suggestSatisfies" | "unnecessaryTypeConversion", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unnecessary-type-parameters': import("@typescript-eslint/utils/ts-eslint").RuleModule<"replaceUsagesWithConstraint" | "sole", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-argument': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unsafe-assignment': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeArraySpread" | "anyAssignment" | "anyAssignmentThis" | "unsafeArrayPattern" | "unsafeArrayPatternFromTuple" | "unsafeAssignment", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-call': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-unsafe-declaration-merging': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeMerging", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-enum-comparison': import("@typescript-eslint/utils/ts-eslint").RuleModule<"mismatchedCase" | "mismatchedCondition" | "replaceValueWithEnum", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-function-type': import("@typescript-eslint/utils/ts-eslint").RuleModule<"bannedFunctionType", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-member-access': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeComputedMemberAccess" | "unsafeMemberExpression" | "unsafeThisMemberExpression", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-return': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeReturn" | "unsafeReturnAssignment" | "unsafeReturnThis", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-type-assertion': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeOfAnyTypeAssertion" | "unsafeToAnyTypeAssertion" | "unsafeToUnconstrainedTypeAssertion" | "unsafeTypeAssertion" | "unsafeTypeAssertionAssignableToConstraint", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unsafe-unary-minus': import("@typescript-eslint/utils/ts-eslint").RuleModule<"unaryMinus", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unused-expressions': import("@typescript-eslint/utils/ts-eslint").RuleModule<"expected", [{ + allowShortCircuit?: boolean; + allowTaggedTemplates?: boolean; + allowTernary?: boolean; + }], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-unused-vars': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'no-use-before-define': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noUseBeforeDefine", import("./no-use-before-define").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-useless-constructor': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noUselessConstructor" | "removeConstructor", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-useless-empty-export': import("@typescript-eslint/utils/ts-eslint").RuleModule<"uselessExport", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-var-requires': import("@typescript-eslint/utils/ts-eslint").RuleModule<"noVarReqs", import("./no-var-requires").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'no-wrapper-object-types': import("@typescript-eslint/utils/ts-eslint").RuleModule<"bannedClassType", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'non-nullable-type-assertion-style': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferNonNullAssertion", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'only-throw-error': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'parameter-properties': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-as-const': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferConstAssertion" | "variableConstAssertion" | "variableSuggest", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-destructuring': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferDestructuring", import("./prefer-destructuring").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-enum-initializers': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-find': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferFind" | "preferFindSuggestion", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-for-of': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferForOf", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-function-type': import("@typescript-eslint/utils/ts-eslint").RuleModule<"functionTypeOverCallableType" | "unexpectedThisOnFunctionOnlyInterface", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-includes': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferIncludes" | "preferStringIncludes", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-literal-enum-member': import("@typescript-eslint/utils/ts-eslint").RuleModule<"notLiteral" | "notLiteralOrBitwiseExpression", [{ + allowBitwiseExpressions: boolean; + }], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-namespace-keyword': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useNamespace", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-nullish-coalescing': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-optional-chain': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-promise-reject-errors': import("@typescript-eslint/utils/ts-eslint").RuleModule<"rejectAnError", import("./prefer-promise-reject-errors").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-readonly': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferReadonly", import("./prefer-readonly").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-readonly-parameter-types': import("@typescript-eslint/utils/ts-eslint").RuleModule<"shouldBeReadonly", import("./prefer-readonly-parameter-types").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-reduce-type-parameter': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferTypeParameter", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-regexp-exec': import("@typescript-eslint/utils/ts-eslint").RuleModule<"regExpExecOverStringMatch", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-return-this-type': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useThisType", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'prefer-string-starts-ends-with': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'prefer-ts-expect-error': import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferExpectErrorComment", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'promise-function-async': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'related-getter-setter-pairs': import("@typescript-eslint/utils/ts-eslint").RuleModule<"mismatch", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'require-array-sort-compare': import("@typescript-eslint/utils/ts-eslint").RuleModule<"requireCompare", import("./require-array-sort-compare").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'require-await': import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingAwait" | "removeAsync", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'restrict-plus-operands': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'restrict-template-expressions': import("@typescript-eslint/utils/ts-eslint").RuleModule<"invalidType", import("./restrict-template-expressions").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'return-await': import("@typescript-eslint/utils/ts-eslint").RuleModule<"disallowedPromiseAwait" | "disallowedPromiseAwaitSuggestion" | "nonPromiseAwait" | "requiredPromiseAwait" | "requiredPromiseAwaitSuggestion", [string], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + 'sort-type-constituents': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'strict-boolean-expressions': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'switch-exhaustiveness-check': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'triple-slash-reference': import("@typescript-eslint/utils/ts-eslint").RuleModule<"tripleSlashReference", import("./triple-slash-reference").Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; + typedef: import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'unbound-method': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'unified-signatures': import("@typescript-eslint/utils/ts-eslint").RuleModule; + 'use-unknown-in-catch-callback-variable': import("@typescript-eslint/utils/ts-eslint").RuleModule; +}; +export = rules; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.d.ts.map new file mode 100644 index 00000000..ac5f8a28 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/rules/index.ts"],"names":[],"mappings":"AAsIA,QAAA,MAAM,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqImB,CAAC;AAE/B,SAAS,KAAK,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.js new file mode 100644 index 00000000..022bf35a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.js @@ -0,0 +1,269 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const adjacent_overload_signatures_1 = __importDefault(require("./adjacent-overload-signatures")); +const array_type_1 = __importDefault(require("./array-type")); +const await_thenable_1 = __importDefault(require("./await-thenable")); +const ban_ts_comment_1 = __importDefault(require("./ban-ts-comment")); +const ban_tslint_comment_1 = __importDefault(require("./ban-tslint-comment")); +const class_literal_property_style_1 = __importDefault(require("./class-literal-property-style")); +const class_methods_use_this_1 = __importDefault(require("./class-methods-use-this")); +const consistent_generic_constructors_1 = __importDefault(require("./consistent-generic-constructors")); +const consistent_indexed_object_style_1 = __importDefault(require("./consistent-indexed-object-style")); +const consistent_return_1 = __importDefault(require("./consistent-return")); +const consistent_type_assertions_1 = __importDefault(require("./consistent-type-assertions")); +const consistent_type_definitions_1 = __importDefault(require("./consistent-type-definitions")); +const consistent_type_exports_1 = __importDefault(require("./consistent-type-exports")); +const consistent_type_imports_1 = __importDefault(require("./consistent-type-imports")); +const default_param_last_1 = __importDefault(require("./default-param-last")); +const dot_notation_1 = __importDefault(require("./dot-notation")); +const explicit_function_return_type_1 = __importDefault(require("./explicit-function-return-type")); +const explicit_member_accessibility_1 = __importDefault(require("./explicit-member-accessibility")); +const explicit_module_boundary_types_1 = __importDefault(require("./explicit-module-boundary-types")); +const init_declarations_1 = __importDefault(require("./init-declarations")); +const max_params_1 = __importDefault(require("./max-params")); +const member_ordering_1 = __importDefault(require("./member-ordering")); +const method_signature_style_1 = __importDefault(require("./method-signature-style")); +const naming_convention_1 = __importDefault(require("./naming-convention")); +const no_array_constructor_1 = __importDefault(require("./no-array-constructor")); +const no_array_delete_1 = __importDefault(require("./no-array-delete")); +const no_base_to_string_1 = __importDefault(require("./no-base-to-string")); +const no_confusing_non_null_assertion_1 = __importDefault(require("./no-confusing-non-null-assertion")); +const no_confusing_void_expression_1 = __importDefault(require("./no-confusing-void-expression")); +const no_deprecated_1 = __importDefault(require("./no-deprecated")); +const no_dupe_class_members_1 = __importDefault(require("./no-dupe-class-members")); +const no_duplicate_enum_values_1 = __importDefault(require("./no-duplicate-enum-values")); +const no_duplicate_type_constituents_1 = __importDefault(require("./no-duplicate-type-constituents")); +const no_dynamic_delete_1 = __importDefault(require("./no-dynamic-delete")); +const no_empty_function_1 = __importDefault(require("./no-empty-function")); +const no_empty_interface_1 = __importDefault(require("./no-empty-interface")); +const no_empty_object_type_1 = __importDefault(require("./no-empty-object-type")); +const no_explicit_any_1 = __importDefault(require("./no-explicit-any")); +const no_extra_non_null_assertion_1 = __importDefault(require("./no-extra-non-null-assertion")); +const no_extraneous_class_1 = __importDefault(require("./no-extraneous-class")); +const no_floating_promises_1 = __importDefault(require("./no-floating-promises")); +const no_for_in_array_1 = __importDefault(require("./no-for-in-array")); +const no_implied_eval_1 = __importDefault(require("./no-implied-eval")); +const no_import_type_side_effects_1 = __importDefault(require("./no-import-type-side-effects")); +const no_inferrable_types_1 = __importDefault(require("./no-inferrable-types")); +const no_invalid_this_1 = __importDefault(require("./no-invalid-this")); +const no_invalid_void_type_1 = __importDefault(require("./no-invalid-void-type")); +const no_loop_func_1 = __importDefault(require("./no-loop-func")); +const no_loss_of_precision_1 = __importDefault(require("./no-loss-of-precision")); +const no_magic_numbers_1 = __importDefault(require("./no-magic-numbers")); +const no_meaningless_void_operator_1 = __importDefault(require("./no-meaningless-void-operator")); +const no_misused_new_1 = __importDefault(require("./no-misused-new")); +const no_misused_promises_1 = __importDefault(require("./no-misused-promises")); +const no_misused_spread_1 = __importDefault(require("./no-misused-spread")); +const no_mixed_enums_1 = __importDefault(require("./no-mixed-enums")); +const no_namespace_1 = __importDefault(require("./no-namespace")); +const no_non_null_asserted_nullish_coalescing_1 = __importDefault(require("./no-non-null-asserted-nullish-coalescing")); +const no_non_null_asserted_optional_chain_1 = __importDefault(require("./no-non-null-asserted-optional-chain")); +const no_non_null_assertion_1 = __importDefault(require("./no-non-null-assertion")); +const no_redeclare_1 = __importDefault(require("./no-redeclare")); +const no_redundant_type_constituents_1 = __importDefault(require("./no-redundant-type-constituents")); +const no_require_imports_1 = __importDefault(require("./no-require-imports")); +const no_restricted_imports_1 = __importDefault(require("./no-restricted-imports")); +const no_restricted_types_1 = __importDefault(require("./no-restricted-types")); +const no_shadow_1 = __importDefault(require("./no-shadow")); +const no_this_alias_1 = __importDefault(require("./no-this-alias")); +const no_type_alias_1 = __importDefault(require("./no-type-alias")); +const no_unnecessary_boolean_literal_compare_1 = __importDefault(require("./no-unnecessary-boolean-literal-compare")); +const no_unnecessary_condition_1 = __importDefault(require("./no-unnecessary-condition")); +const no_unnecessary_parameter_property_assignment_1 = __importDefault(require("./no-unnecessary-parameter-property-assignment")); +const no_unnecessary_qualifier_1 = __importDefault(require("./no-unnecessary-qualifier")); +const no_unnecessary_template_expression_1 = __importDefault(require("./no-unnecessary-template-expression")); +const no_unnecessary_type_arguments_1 = __importDefault(require("./no-unnecessary-type-arguments")); +const no_unnecessary_type_assertion_1 = __importDefault(require("./no-unnecessary-type-assertion")); +const no_unnecessary_type_constraint_1 = __importDefault(require("./no-unnecessary-type-constraint")); +const no_unnecessary_type_conversion_1 = __importDefault(require("./no-unnecessary-type-conversion")); +const no_unnecessary_type_parameters_1 = __importDefault(require("./no-unnecessary-type-parameters")); +const no_unsafe_argument_1 = __importDefault(require("./no-unsafe-argument")); +const no_unsafe_assignment_1 = __importDefault(require("./no-unsafe-assignment")); +const no_unsafe_call_1 = __importDefault(require("./no-unsafe-call")); +const no_unsafe_declaration_merging_1 = __importDefault(require("./no-unsafe-declaration-merging")); +const no_unsafe_enum_comparison_1 = __importDefault(require("./no-unsafe-enum-comparison")); +const no_unsafe_function_type_1 = __importDefault(require("./no-unsafe-function-type")); +const no_unsafe_member_access_1 = __importDefault(require("./no-unsafe-member-access")); +const no_unsafe_return_1 = __importDefault(require("./no-unsafe-return")); +const no_unsafe_type_assertion_1 = __importDefault(require("./no-unsafe-type-assertion")); +const no_unsafe_unary_minus_1 = __importDefault(require("./no-unsafe-unary-minus")); +const no_unused_expressions_1 = __importDefault(require("./no-unused-expressions")); +const no_unused_vars_1 = __importDefault(require("./no-unused-vars")); +const no_use_before_define_1 = __importDefault(require("./no-use-before-define")); +const no_useless_constructor_1 = __importDefault(require("./no-useless-constructor")); +const no_useless_empty_export_1 = __importDefault(require("./no-useless-empty-export")); +const no_var_requires_1 = __importDefault(require("./no-var-requires")); +const no_wrapper_object_types_1 = __importDefault(require("./no-wrapper-object-types")); +const non_nullable_type_assertion_style_1 = __importDefault(require("./non-nullable-type-assertion-style")); +const only_throw_error_1 = __importDefault(require("./only-throw-error")); +const parameter_properties_1 = __importDefault(require("./parameter-properties")); +const prefer_as_const_1 = __importDefault(require("./prefer-as-const")); +const prefer_destructuring_1 = __importDefault(require("./prefer-destructuring")); +const prefer_enum_initializers_1 = __importDefault(require("./prefer-enum-initializers")); +const prefer_find_1 = __importDefault(require("./prefer-find")); +const prefer_for_of_1 = __importDefault(require("./prefer-for-of")); +const prefer_function_type_1 = __importDefault(require("./prefer-function-type")); +const prefer_includes_1 = __importDefault(require("./prefer-includes")); +const prefer_literal_enum_member_1 = __importDefault(require("./prefer-literal-enum-member")); +const prefer_namespace_keyword_1 = __importDefault(require("./prefer-namespace-keyword")); +const prefer_nullish_coalescing_1 = __importDefault(require("./prefer-nullish-coalescing")); +const prefer_optional_chain_1 = __importDefault(require("./prefer-optional-chain")); +const prefer_promise_reject_errors_1 = __importDefault(require("./prefer-promise-reject-errors")); +const prefer_readonly_1 = __importDefault(require("./prefer-readonly")); +const prefer_readonly_parameter_types_1 = __importDefault(require("./prefer-readonly-parameter-types")); +const prefer_reduce_type_parameter_1 = __importDefault(require("./prefer-reduce-type-parameter")); +const prefer_regexp_exec_1 = __importDefault(require("./prefer-regexp-exec")); +const prefer_return_this_type_1 = __importDefault(require("./prefer-return-this-type")); +const prefer_string_starts_ends_with_1 = __importDefault(require("./prefer-string-starts-ends-with")); +const prefer_ts_expect_error_1 = __importDefault(require("./prefer-ts-expect-error")); +const promise_function_async_1 = __importDefault(require("./promise-function-async")); +const related_getter_setter_pairs_1 = __importDefault(require("./related-getter-setter-pairs")); +const require_array_sort_compare_1 = __importDefault(require("./require-array-sort-compare")); +const require_await_1 = __importDefault(require("./require-await")); +const restrict_plus_operands_1 = __importDefault(require("./restrict-plus-operands")); +const restrict_template_expressions_1 = __importDefault(require("./restrict-template-expressions")); +const return_await_1 = __importDefault(require("./return-await")); +const sort_type_constituents_1 = __importDefault(require("./sort-type-constituents")); +const strict_boolean_expressions_1 = __importDefault(require("./strict-boolean-expressions")); +const switch_exhaustiveness_check_1 = __importDefault(require("./switch-exhaustiveness-check")); +const triple_slash_reference_1 = __importDefault(require("./triple-slash-reference")); +const typedef_1 = __importDefault(require("./typedef")); +const unbound_method_1 = __importDefault(require("./unbound-method")); +const unified_signatures_1 = __importDefault(require("./unified-signatures")); +const use_unknown_in_catch_callback_variable_1 = __importDefault(require("./use-unknown-in-catch-callback-variable")); +const rules = { + 'adjacent-overload-signatures': adjacent_overload_signatures_1.default, + 'array-type': array_type_1.default, + 'await-thenable': await_thenable_1.default, + 'ban-ts-comment': ban_ts_comment_1.default, + 'ban-tslint-comment': ban_tslint_comment_1.default, + 'class-literal-property-style': class_literal_property_style_1.default, + 'class-methods-use-this': class_methods_use_this_1.default, + 'consistent-generic-constructors': consistent_generic_constructors_1.default, + 'consistent-indexed-object-style': consistent_indexed_object_style_1.default, + 'consistent-return': consistent_return_1.default, + 'consistent-type-assertions': consistent_type_assertions_1.default, + 'consistent-type-definitions': consistent_type_definitions_1.default, + 'consistent-type-exports': consistent_type_exports_1.default, + 'consistent-type-imports': consistent_type_imports_1.default, + 'default-param-last': default_param_last_1.default, + 'dot-notation': dot_notation_1.default, + 'explicit-function-return-type': explicit_function_return_type_1.default, + 'explicit-member-accessibility': explicit_member_accessibility_1.default, + 'explicit-module-boundary-types': explicit_module_boundary_types_1.default, + 'init-declarations': init_declarations_1.default, + 'max-params': max_params_1.default, + 'member-ordering': member_ordering_1.default, + 'method-signature-style': method_signature_style_1.default, + 'naming-convention': naming_convention_1.default, + 'no-array-constructor': no_array_constructor_1.default, + 'no-array-delete': no_array_delete_1.default, + 'no-base-to-string': no_base_to_string_1.default, + 'no-confusing-non-null-assertion': no_confusing_non_null_assertion_1.default, + 'no-confusing-void-expression': no_confusing_void_expression_1.default, + 'no-deprecated': no_deprecated_1.default, + 'no-dupe-class-members': no_dupe_class_members_1.default, + 'no-duplicate-enum-values': no_duplicate_enum_values_1.default, + 'no-duplicate-type-constituents': no_duplicate_type_constituents_1.default, + 'no-dynamic-delete': no_dynamic_delete_1.default, + 'no-empty-function': no_empty_function_1.default, + 'no-empty-interface': no_empty_interface_1.default, + 'no-empty-object-type': no_empty_object_type_1.default, + 'no-explicit-any': no_explicit_any_1.default, + 'no-extra-non-null-assertion': no_extra_non_null_assertion_1.default, + 'no-extraneous-class': no_extraneous_class_1.default, + 'no-floating-promises': no_floating_promises_1.default, + 'no-for-in-array': no_for_in_array_1.default, + 'no-implied-eval': no_implied_eval_1.default, + 'no-import-type-side-effects': no_import_type_side_effects_1.default, + 'no-inferrable-types': no_inferrable_types_1.default, + 'no-invalid-this': no_invalid_this_1.default, + 'no-invalid-void-type': no_invalid_void_type_1.default, + 'no-loop-func': no_loop_func_1.default, + 'no-loss-of-precision': no_loss_of_precision_1.default, + 'no-magic-numbers': no_magic_numbers_1.default, + 'no-meaningless-void-operator': no_meaningless_void_operator_1.default, + 'no-misused-new': no_misused_new_1.default, + 'no-misused-promises': no_misused_promises_1.default, + 'no-misused-spread': no_misused_spread_1.default, + 'no-mixed-enums': no_mixed_enums_1.default, + 'no-namespace': no_namespace_1.default, + 'no-non-null-asserted-nullish-coalescing': no_non_null_asserted_nullish_coalescing_1.default, + 'no-non-null-asserted-optional-chain': no_non_null_asserted_optional_chain_1.default, + 'no-non-null-assertion': no_non_null_assertion_1.default, + 'no-redeclare': no_redeclare_1.default, + 'no-redundant-type-constituents': no_redundant_type_constituents_1.default, + 'no-require-imports': no_require_imports_1.default, + 'no-restricted-imports': no_restricted_imports_1.default, + 'no-restricted-types': no_restricted_types_1.default, + 'no-shadow': no_shadow_1.default, + 'no-this-alias': no_this_alias_1.default, + 'no-type-alias': no_type_alias_1.default, + 'no-unnecessary-boolean-literal-compare': no_unnecessary_boolean_literal_compare_1.default, + 'no-unnecessary-condition': no_unnecessary_condition_1.default, + 'no-unnecessary-parameter-property-assignment': no_unnecessary_parameter_property_assignment_1.default, + 'no-unnecessary-qualifier': no_unnecessary_qualifier_1.default, + 'no-unnecessary-template-expression': no_unnecessary_template_expression_1.default, + 'no-unnecessary-type-arguments': no_unnecessary_type_arguments_1.default, + 'no-unnecessary-type-assertion': no_unnecessary_type_assertion_1.default, + 'no-unnecessary-type-constraint': no_unnecessary_type_constraint_1.default, + 'no-unnecessary-type-conversion': no_unnecessary_type_conversion_1.default, + 'no-unnecessary-type-parameters': no_unnecessary_type_parameters_1.default, + 'no-unsafe-argument': no_unsafe_argument_1.default, + 'no-unsafe-assignment': no_unsafe_assignment_1.default, + 'no-unsafe-call': no_unsafe_call_1.default, + 'no-unsafe-declaration-merging': no_unsafe_declaration_merging_1.default, + 'no-unsafe-enum-comparison': no_unsafe_enum_comparison_1.default, + 'no-unsafe-function-type': no_unsafe_function_type_1.default, + 'no-unsafe-member-access': no_unsafe_member_access_1.default, + 'no-unsafe-return': no_unsafe_return_1.default, + 'no-unsafe-type-assertion': no_unsafe_type_assertion_1.default, + 'no-unsafe-unary-minus': no_unsafe_unary_minus_1.default, + 'no-unused-expressions': no_unused_expressions_1.default, + 'no-unused-vars': no_unused_vars_1.default, + 'no-use-before-define': no_use_before_define_1.default, + 'no-useless-constructor': no_useless_constructor_1.default, + 'no-useless-empty-export': no_useless_empty_export_1.default, + 'no-var-requires': no_var_requires_1.default, + 'no-wrapper-object-types': no_wrapper_object_types_1.default, + 'non-nullable-type-assertion-style': non_nullable_type_assertion_style_1.default, + 'only-throw-error': only_throw_error_1.default, + 'parameter-properties': parameter_properties_1.default, + 'prefer-as-const': prefer_as_const_1.default, + 'prefer-destructuring': prefer_destructuring_1.default, + 'prefer-enum-initializers': prefer_enum_initializers_1.default, + 'prefer-find': prefer_find_1.default, + 'prefer-for-of': prefer_for_of_1.default, + 'prefer-function-type': prefer_function_type_1.default, + 'prefer-includes': prefer_includes_1.default, + 'prefer-literal-enum-member': prefer_literal_enum_member_1.default, + 'prefer-namespace-keyword': prefer_namespace_keyword_1.default, + 'prefer-nullish-coalescing': prefer_nullish_coalescing_1.default, + 'prefer-optional-chain': prefer_optional_chain_1.default, + 'prefer-promise-reject-errors': prefer_promise_reject_errors_1.default, + 'prefer-readonly': prefer_readonly_1.default, + 'prefer-readonly-parameter-types': prefer_readonly_parameter_types_1.default, + 'prefer-reduce-type-parameter': prefer_reduce_type_parameter_1.default, + 'prefer-regexp-exec': prefer_regexp_exec_1.default, + 'prefer-return-this-type': prefer_return_this_type_1.default, + 'prefer-string-starts-ends-with': prefer_string_starts_ends_with_1.default, + 'prefer-ts-expect-error': prefer_ts_expect_error_1.default, + 'promise-function-async': promise_function_async_1.default, + 'related-getter-setter-pairs': related_getter_setter_pairs_1.default, + 'require-array-sort-compare': require_array_sort_compare_1.default, + 'require-await': require_await_1.default, + 'restrict-plus-operands': restrict_plus_operands_1.default, + 'restrict-template-expressions': restrict_template_expressions_1.default, + 'return-await': return_await_1.default, + 'sort-type-constituents': sort_type_constituents_1.default, + 'strict-boolean-expressions': strict_boolean_expressions_1.default, + 'switch-exhaustiveness-check': switch_exhaustiveness_check_1.default, + 'triple-slash-reference': triple_slash_reference_1.default, + typedef: typedef_1.default, + 'unbound-method': unbound_method_1.default, + 'unified-signatures': unified_signatures_1.default, + 'use-unknown-in-catch-callback-variable': use_unknown_in_catch_callback_variable_1.default, +}; +module.exports = rules; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/init-declarations.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/init-declarations.d.ts new file mode 100644 index 00000000..067e4eb5 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/init-declarations.d.ts @@ -0,0 +1,14 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"initialized" | "notInitialized", ["always" | "never", ({ + ignoreForLoopInit?: boolean; +} | undefined)?], unknown, { + 'VariableDeclaration:exit'(node: TSESTree.VariableDeclaration): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"initialized" | "notInitialized", ["always" | "never", ({ + ignoreForLoopInit?: boolean; +} | undefined)?], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=init-declarations.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/init-declarations.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/init-declarations.d.ts.map new file mode 100644 index 00000000..ff920cf3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/init-declarations.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"init-declarations.d.ts","sourceRoot":"","sources":["../../src/rules/init-declarations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;;;qCA6H2lO,SAAU,mBAAmB;EA7H/kO,CAAC;AAExD,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;;;AAEtE,wBAgGG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/init-declarations.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/init-declarations.js new file mode 100644 index 00000000..4523a3d1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/init-declarations.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('init-declarations'); +exports.default = (0, util_1.createRule)({ + name: 'init-declarations', + meta: { + type: 'suggestion', + // defaultOptions, -- base rule does not use defaultOptions + docs: { + description: 'Require or disallow initialization in variable declarations', + extendsBaseRule: true, + }, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: baseRule.meta.schema, + }, + defaultOptions: ['always'], + create(context, [mode]) { + // Make a custom context to adjust the loc of reports where the base + // rule's behavior is a bit too aggressive with TS-specific syntax (namely, + // type annotations). + function getBaseContextOverride() { + const reportOverride = descriptor => { + if ('node' in descriptor && descriptor.loc == null) { + const { node, ...rest } = descriptor; + // We only want to special case the report loc when reporting on + // variables declarations that are not initialized. Declarations that + // _are_ initialized get reported by the base rule due to a setting to + // prohibit initializing variables entirely, in which case underlining + // the whole node including the type annotation and initializer is + // appropriate. + if (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator && + node.init == null) { + context.report({ + ...rest, + loc: getReportLoc(node), + }); + return; + } + } + context.report(descriptor); + }; + // `return { ...context, report: reportOverride }` isn't safe because the + // `context` object has some getters that need to be preserved. + // + // `return new Proxy(context, ...)` doesn't work because `context` has + // non-configurable properties that throw when constructing a Proxy. + // + // So, we'll just use Proxy on a dummy object and use the `get` trap to + // proxy `context`'s properties. + return new Proxy({}, { + get: (target, prop, receiver) => prop === 'report' + ? reportOverride + : Reflect.get(context, prop, receiver), + }); + } + const rules = baseRule.create(getBaseContextOverride()); + return { + 'VariableDeclaration:exit'(node) { + if (mode === 'always') { + if (node.declare) { + return; + } + if (isAncestorNamespaceDeclared(node)) { + return; + } + } + rules['VariableDeclaration:exit'](node); + }, + }; + function isAncestorNamespaceDeclared(node) { + let ancestor = node.parent; + while (ancestor) { + if (ancestor.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration && + ancestor.declare) { + return true; + } + ancestor = ancestor.parent; + } + return false; + } + }, +}); +/** + * When reporting an uninitialized variable declarator, get the loc excluding + * the type annotation. + */ +function getReportLoc(node) { + const start = structuredClone(node.loc.start); + const end = { + line: node.loc.start.line, + // `if (id.type === AST_NODE_TYPES.Identifier)` is a condition for + // reporting in the base rule (as opposed to things like destructuring + // assignment), so the type assertion should always be valid. + column: node.loc.start.column + node.id.name.length, + }; + return { + start, + end, + }; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/max-params.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/max-params.d.ts new file mode 100644 index 00000000..fd98273b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/max-params.d.ts @@ -0,0 +1,24 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"exceed", ({ + countVoidThis?: boolean; + max: number; +} | { + countVoidThis?: boolean; + maximum: number; +})[], unknown, { + ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression): void; + FunctionDeclaration(node: TSESTree.FunctionDeclaration | TSESTree.TSDeclareFunction | TSESTree.TSFunctionType): void; + FunctionExpression(node: TSESTree.FunctionExpression): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"exceed", ({ + countVoidThis?: boolean; + max: number; +} | { + countVoidThis?: boolean; + maximum: number; +})[], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=max-params.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/max-params.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/max-params.d.ts.map new file mode 100644 index 00000000..fdce4d96 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/max-params.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"max-params.d.ts","sourceRoot":"","sources":["../../src/rules/max-params.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAcjB,QAAA,MAAM,QAAQ;;;;;;;kCAqFqgC,SAAU,uBAAuB;8BAA6D,SAAU,mBAAmB,GAAY,SAAU,iBAAiB,GAAY,SAAU,cAAc;6BAA+C,SAAU,kBAAkB;EArFpvC,CAAC;AAEjD,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;;;;;;;AAEtE,wBA+EG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/max-params.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/max-params.js new file mode 100644 index 00000000..418ebc17 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/max-params.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('max-params'); +exports.default = (0, util_1.createRule)({ + name: 'max-params', + meta: { + type: 'suggestion', + // defaultOptions, -- base rule does not use defaultOptions + docs: { + description: 'Enforce a maximum number of parameters in function definitions', + extendsBaseRule: true, + }, + messages: baseRule.meta.messages, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + countVoidThis: { + type: 'boolean', + description: 'Whether to count a `this` declaration when the type is `void`.', + }, + max: { + type: 'integer', + description: 'A maximum number of parameters in function definitions.', + minimum: 0, + }, + maximum: { + type: 'integer', + description: '(deprecated) A maximum number of parameters in function definitions.', + minimum: 0, + }, + }, + }, + ], + }, + defaultOptions: [{ countVoidThis: false, max: 3 }], + create(context, [{ countVoidThis }]) { + const baseRules = baseRule.create(context); + if (countVoidThis === true) { + return baseRules; + } + const removeVoidThisParam = (node) => { + if (node.params.length === 0 || + node.params[0].type !== utils_1.AST_NODE_TYPES.Identifier || + node.params[0].name !== 'this' || + node.params[0].typeAnnotation?.typeAnnotation.type !== + utils_1.AST_NODE_TYPES.TSVoidKeyword) { + return node; + } + return { + ...node, + params: node.params.slice(1), + }; + }; + const wrapListener = (listener) => { + return (node) => { + listener(removeVoidThisParam(node)); + }; + }; + return { + ArrowFunctionExpression: wrapListener(baseRules.ArrowFunctionExpression), + FunctionDeclaration: wrapListener(baseRules.FunctionDeclaration), + FunctionExpression: wrapListener(baseRules.FunctionExpression), + TSDeclareFunction: wrapListener(baseRules.FunctionDeclaration), + TSFunctionType: wrapListener(baseRules.FunctionDeclaration), + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/member-ordering.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/member-ordering.d.ts new file mode 100644 index 00000000..462adaf0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/member-ordering.d.ts @@ -0,0 +1,32 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +export type MessageIds = 'incorrectGroupOrder' | 'incorrectOrder' | 'incorrectRequiredMembersOrder'; +type ReadonlyType = 'readonly-field' | 'readonly-signature'; +type MemberKind = 'accessor' | 'call-signature' | 'constructor' | 'field' | 'get' | 'method' | 'set' | 'signature' | 'static-initialization' | ReadonlyType; +type DecoratedMemberKind = 'accessor' | 'field' | 'get' | 'method' | 'set' | Exclude; +type NonCallableMemberKind = Exclude; +type MemberScope = 'abstract' | 'instance' | 'static'; +type Accessibility = '#private' | TSESTree.Accessibility; +type BaseMemberType = `${Accessibility}-${Exclude}` | `${Accessibility}-${MemberScope}-${NonCallableMemberKind}` | `${Accessibility}-decorated-${DecoratedMemberKind}` | `${MemberScope}-${NonCallableMemberKind}` | `decorated-${DecoratedMemberKind}` | MemberKind; +type MemberType = BaseMemberType | BaseMemberType[]; +type AlphabeticalOrder = 'alphabetically' | 'alphabetically-case-insensitive' | 'natural' | 'natural-case-insensitive'; +type Order = 'as-written' | AlphabeticalOrder; +interface SortedOrderConfig { + memberTypes?: 'never' | MemberType[]; + optionalityOrder?: OptionalityOrder; + order?: Order; +} +type OrderConfig = 'never' | MemberType[] | SortedOrderConfig; +type OptionalityOrder = 'optional-first' | 'required-first'; +export type Options = [ + { + classes?: OrderConfig; + classExpressions?: OrderConfig; + default?: OrderConfig; + interfaces?: OrderConfig; + typeLiterals?: OrderConfig; + } +]; +export declare const defaultOrder: MemberType[]; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=member-ordering.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/member-ordering.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/member-ordering.d.ts.map new file mode 100644 index 00000000..4d67d19e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/member-ordering.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"member-ordering.d.ts","sourceRoot":"","sources":["../../src/rules/member-ordering.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAc,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAY/E,MAAM,MAAM,UAAU,GAClB,qBAAqB,GACrB,gBAAgB,GAChB,+BAA+B,CAAC;AAEpC,KAAK,YAAY,GAAG,gBAAgB,GAAG,oBAAoB,CAAC;AAE5D,KAAK,UAAU,GACX,UAAU,GACV,gBAAgB,GAChB,aAAa,GACb,OAAO,GACP,KAAK,GACL,QAAQ,GACR,KAAK,GACL,WAAW,GACX,uBAAuB,GACvB,YAAY,CAAC;AAEjB,KAAK,mBAAmB,GACpB,UAAU,GACV,OAAO,GACP,KAAK,GACL,QAAQ,GACR,KAAK,GACL,OAAO,CAAC,YAAY,EAAE,oBAAoB,CAAC,CAAC;AAEhD,KAAK,qBAAqB,GAAG,OAAO,CAClC,UAAU,EACV,aAAa,GAAG,oBAAoB,GAAG,WAAW,CACnD,CAAC;AAEF,KAAK,WAAW,GAAG,UAAU,GAAG,UAAU,GAAG,QAAQ,CAAC;AAEtD,KAAK,aAAa,GAAG,UAAU,GAAG,QAAQ,CAAC,aAAa,CAAC;AAEzD,KAAK,cAAc,GACf,GAAG,aAAa,IAAI,OAAO,CACzB,UAAU,EACV,oBAAoB,GAAG,WAAW,GAAG,uBAAuB,CAC7D,EAAE,GACH,GAAG,aAAa,IAAI,WAAW,IAAI,qBAAqB,EAAE,GAC1D,GAAG,aAAa,cAAc,mBAAmB,EAAE,GACnD,GAAG,WAAW,IAAI,qBAAqB,EAAE,GACzC,aAAa,mBAAmB,EAAE,GAClC,UAAU,CAAC;AAEf,KAAK,UAAU,GAAG,cAAc,GAAG,cAAc,EAAE,CAAC;AAEpD,KAAK,iBAAiB,GAClB,gBAAgB,GAChB,iCAAiC,GACjC,SAAS,GACT,0BAA0B,CAAC;AAE/B,KAAK,KAAK,GAAG,YAAY,GAAG,iBAAiB,CAAC;AAE9C,UAAU,iBAAiB;IACzB,WAAW,CAAC,EAAE,OAAO,GAAG,UAAU,EAAE,CAAC;IACrC,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;IACpC,KAAK,CAAC,EAAE,KAAK,CAAC;CACf;AAED,KAAK,WAAW,GAAG,OAAO,GAAG,UAAU,EAAE,GAAG,iBAAiB,CAAC;AAG9D,KAAK,gBAAgB,GAAG,gBAAgB,GAAG,gBAAgB,CAAC;AAE5D,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,OAAO,CAAC,EAAE,WAAW,CAAC;QACtB,gBAAgB,CAAC,EAAE,WAAW,CAAC;QAC/B,OAAO,CAAC,EAAE,WAAW,CAAC;QACtB,UAAU,CAAC,EAAE,WAAW,CAAC;QACzB,YAAY,CAAC,EAAE,WAAW,CAAC;KAC5B;CACF,CAAC;AAwCF,eAAO,MAAM,YAAY,EAAE,UAAU,EAyKpC,CAAC;;AAwaF,wBA2YG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/member-ordering.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/member-ordering.js new file mode 100644 index 00000000..fdaa8317 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/member-ordering.js @@ -0,0 +1,827 @@ +"use strict"; +// This rule was feature-frozen before we enabled no-property-in-node. +/* eslint-disable eslint-plugin/no-property-in-node */ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultOrder = void 0; +const utils_1 = require("@typescript-eslint/utils"); +const natural_compare_1 = __importDefault(require("natural-compare")); +const util_1 = require("../util"); +const neverConfig = { + type: 'string', + enum: ['never'], +}; +const arrayConfig = (memberTypes) => ({ + type: 'array', + items: { + oneOf: [ + { + $ref: memberTypes, + }, + { + type: 'array', + items: { + $ref: memberTypes, + }, + }, + ], + }, +}); +const objectConfig = (memberTypes) => ({ + type: 'object', + additionalProperties: false, + properties: { + memberTypes: { + oneOf: [arrayConfig(memberTypes), neverConfig], + }, + optionalityOrder: { + $ref: '#/items/0/$defs/optionalityOrderOptions', + }, + order: { + $ref: '#/items/0/$defs/orderOptions', + }, + }, +}); +exports.defaultOrder = [ + // Index signature + 'signature', + 'call-signature', + // Fields + 'public-static-field', + 'protected-static-field', + 'private-static-field', + '#private-static-field', + 'public-decorated-field', + 'protected-decorated-field', + 'private-decorated-field', + 'public-instance-field', + 'protected-instance-field', + 'private-instance-field', + '#private-instance-field', + 'public-abstract-field', + 'protected-abstract-field', + 'public-field', + 'protected-field', + 'private-field', + '#private-field', + 'static-field', + 'instance-field', + 'abstract-field', + 'decorated-field', + 'field', + // Static initialization + 'static-initialization', + // Constructors + 'public-constructor', + 'protected-constructor', + 'private-constructor', + 'constructor', + // Accessors + 'public-static-accessor', + 'protected-static-accessor', + 'private-static-accessor', + '#private-static-accessor', + 'public-decorated-accessor', + 'protected-decorated-accessor', + 'private-decorated-accessor', + 'public-instance-accessor', + 'protected-instance-accessor', + 'private-instance-accessor', + '#private-instance-accessor', + 'public-abstract-accessor', + 'protected-abstract-accessor', + 'public-accessor', + 'protected-accessor', + 'private-accessor', + '#private-accessor', + 'static-accessor', + 'instance-accessor', + 'abstract-accessor', + 'decorated-accessor', + 'accessor', + // Getters + 'public-static-get', + 'protected-static-get', + 'private-static-get', + '#private-static-get', + 'public-decorated-get', + 'protected-decorated-get', + 'private-decorated-get', + 'public-instance-get', + 'protected-instance-get', + 'private-instance-get', + '#private-instance-get', + 'public-abstract-get', + 'protected-abstract-get', + 'public-get', + 'protected-get', + 'private-get', + '#private-get', + 'static-get', + 'instance-get', + 'abstract-get', + 'decorated-get', + 'get', + // Setters + 'public-static-set', + 'protected-static-set', + 'private-static-set', + '#private-static-set', + 'public-decorated-set', + 'protected-decorated-set', + 'private-decorated-set', + 'public-instance-set', + 'protected-instance-set', + 'private-instance-set', + '#private-instance-set', + 'public-abstract-set', + 'protected-abstract-set', + 'public-set', + 'protected-set', + 'private-set', + '#private-set', + 'static-set', + 'instance-set', + 'abstract-set', + 'decorated-set', + 'set', + // Methods + 'public-static-method', + 'protected-static-method', + 'private-static-method', + '#private-static-method', + 'public-decorated-method', + 'protected-decorated-method', + 'private-decorated-method', + 'public-instance-method', + 'protected-instance-method', + 'private-instance-method', + '#private-instance-method', + 'public-abstract-method', + 'protected-abstract-method', + 'public-method', + 'protected-method', + 'private-method', + '#private-method', + 'static-method', + 'instance-method', + 'abstract-method', + 'decorated-method', + 'method', +]; +const allMemberTypes = [ + ...new Set([ + 'readonly-signature', + 'signature', + 'readonly-field', + 'field', + 'method', + 'call-signature', + 'constructor', + 'accessor', + 'get', + 'set', + 'static-initialization', + ].flatMap(type => [ + type, + ...['public', 'protected', 'private', '#private'] + .flatMap(accessibility => [ + type !== 'readonly-signature' && + type !== 'signature' && + type !== 'static-initialization' && + type !== 'call-signature' && + !(type === 'constructor' && accessibility === '#private') + ? `${accessibility}-${type}` // e.g. `public-field` + : [], + // Only class instance fields, methods, accessors, get and set can have decorators attached to them + accessibility !== '#private' && + (type === 'readonly-field' || + type === 'field' || + type === 'method' || + type === 'accessor' || + type === 'get' || + type === 'set') + ? [`${accessibility}-decorated-${type}`, `decorated-${type}`] + : [], + type !== 'constructor' && + type !== 'readonly-signature' && + type !== 'signature' && + type !== 'call-signature' + ? [ + 'static', + 'instance', + // There is no `static-constructor` or `instance-constructor` or `abstract-constructor` + ...(accessibility === '#private' || + accessibility === 'private' + ? [] + : ['abstract']), + ].flatMap(scope => [ + `${scope}-${type}`, + `${accessibility}-${scope}-${type}`, + ]) + : [], + ]) + .flat(), + ])), +]; +const functionExpressions = [ + utils_1.AST_NODE_TYPES.FunctionExpression, + utils_1.AST_NODE_TYPES.ArrowFunctionExpression, +]; +/** + * Gets the node type. + * + * @param node the node to be evaluated. + */ +function getNodeType(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition: + case utils_1.AST_NODE_TYPES.MethodDefinition: + case utils_1.AST_NODE_TYPES.TSMethodSignature: + return node.kind; + case utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration: + return 'call-signature'; + case utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration: + return 'constructor'; + case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition: + case utils_1.AST_NODE_TYPES.TSPropertySignature: + return node.readonly ? 'readonly-field' : 'field'; + case utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty: + case utils_1.AST_NODE_TYPES.AccessorProperty: + return 'accessor'; + case utils_1.AST_NODE_TYPES.PropertyDefinition: + return node.value && functionExpressions.includes(node.value.type) + ? 'method' + : node.readonly + ? 'readonly-field' + : 'field'; + case utils_1.AST_NODE_TYPES.TSIndexSignature: + return node.readonly ? 'readonly-signature' : 'signature'; + case utils_1.AST_NODE_TYPES.StaticBlock: + return 'static-initialization'; + default: + return null; + } +} +/** + * Gets the raw string value of a member's name + */ +function getMemberRawName(member, sourceCode) { + const { name, type } = (0, util_1.getNameFromMember)(member, sourceCode); + if (type === util_1.MemberNameType.Quoted) { + return name.slice(1, -1); + } + if (type === util_1.MemberNameType.Private) { + return name.slice(1); + } + return name; +} +/** + * Gets the member name based on the member type. + * + * @param node the node to be evaluated. + */ +function getMemberName(node, sourceCode) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSPropertySignature: + case utils_1.AST_NODE_TYPES.TSMethodSignature: + case utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty: + case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition: + case utils_1.AST_NODE_TYPES.AccessorProperty: + case utils_1.AST_NODE_TYPES.PropertyDefinition: + return getMemberRawName(node, sourceCode); + case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition: + case utils_1.AST_NODE_TYPES.MethodDefinition: + return node.kind === 'constructor' + ? 'constructor' + : getMemberRawName(node, sourceCode); + case utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration: + return 'new'; + case utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration: + return 'call'; + case utils_1.AST_NODE_TYPES.TSIndexSignature: + return (0, util_1.getNameFromIndexSignature)(node); + case utils_1.AST_NODE_TYPES.StaticBlock: + return 'static block'; + default: + return null; + } +} +/** + * Returns true if the member is optional based on the member type. + * + * @param node the node to be evaluated. + * + * @returns Whether the member is optional, or false if it cannot be optional at all. + */ +function isMemberOptional(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSPropertySignature: + case utils_1.AST_NODE_TYPES.TSMethodSignature: + case utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty: + case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition: + case utils_1.AST_NODE_TYPES.AccessorProperty: + case utils_1.AST_NODE_TYPES.PropertyDefinition: + case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition: + case utils_1.AST_NODE_TYPES.MethodDefinition: + return node.optional; + } + return false; +} +/** + * Gets the calculated rank using the provided method definition. + * The algorithm is as follows: + * - Get the rank based on the accessibility-scope-type name, e.g. public-instance-field + * - If there is no order for accessibility-scope-type, then strip out the accessibility. + * - If there is no order for scope-type, then strip out the scope. + * - If there is no order for type, then return -1 + * @param memberGroups the valid names to be validated. + * @param orderConfig the current order to be validated. + * + * @return Index of the matching member type in the order configuration. + */ +function getRankOrder(memberGroups, orderConfig) { + let rank = -1; + const stack = [...memberGroups]; // Get a copy of the member groups + while (stack.length > 0 && rank === -1) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const memberGroup = stack.shift(); + rank = orderConfig.findIndex(memberType => Array.isArray(memberType) + ? memberType.includes(memberGroup) + : memberType === memberGroup); + } + return rank; +} +function getAccessibility(node) { + if ('accessibility' in node && node.accessibility) { + return node.accessibility; + } + if ('key' in node && node.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) { + return '#private'; + } + return 'public'; +} +/** + * Gets the rank of the node given the order. + * @param node the node to be evaluated. + * @param orderConfig the current order to be validated. + * @param supportsModifiers a flag indicating whether the type supports modifiers (scope or accessibility) or not. + */ +function getRank(node, orderConfig, supportsModifiers) { + const type = getNodeType(node); + if (node.type === utils_1.AST_NODE_TYPES.MethodDefinition && + node.value.type === utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression) { + return -1; + } + if (type == null) { + // shouldn't happen but just in case, put it on the end + return orderConfig.length - 1; + } + const abstract = node.type === utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty || + node.type === utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition || + node.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition; + const scope = 'static' in node && node.static + ? 'static' + : abstract + ? 'abstract' + : 'instance'; + const accessibility = getAccessibility(node); + // Collect all existing member groups that apply to this node... + // (e.g. 'public-instance-field', 'instance-field', 'public-field', 'constructor' etc.) + const memberGroups = []; + if (supportsModifiers) { + const decorated = 'decorators' in node && node.decorators.length > 0; + if (decorated && + (type === 'readonly-field' || + type === 'field' || + type === 'method' || + type === 'accessor' || + type === 'get' || + type === 'set')) { + memberGroups.push(`${accessibility}-decorated-${type}`); + memberGroups.push(`decorated-${type}`); + if (type === 'readonly-field') { + memberGroups.push(`${accessibility}-decorated-field`); + memberGroups.push(`decorated-field`); + } + } + if (type !== 'readonly-signature' && + type !== 'signature' && + type !== 'static-initialization') { + if (type !== 'constructor') { + // Constructors have no scope + memberGroups.push(`${accessibility}-${scope}-${type}`); + memberGroups.push(`${scope}-${type}`); + if (type === 'readonly-field') { + memberGroups.push(`${accessibility}-${scope}-field`); + memberGroups.push(`${scope}-field`); + } + } + memberGroups.push(`${accessibility}-${type}`); + if (type === 'readonly-field') { + memberGroups.push(`${accessibility}-field`); + } + } + } + memberGroups.push(type); + if (type === 'readonly-signature') { + memberGroups.push('signature'); + } + else if (type === 'readonly-field') { + memberGroups.push('field'); + } + // ...then get the rank order for those member groups based on the node + return getRankOrder(memberGroups, orderConfig); +} +/** + * Groups members into arrays of consecutive members with the same rank. + * If, for example, the memberSet parameter looks like the following... + * @example + * ``` + * interface Foo { + * [a: string]: number; + * + * a: x; + * B: x; + * c: x; + * + * c(): void; + * B(): void; + * a(): void; + * + * (): Baz; + * + * new (): Bar; + * } + * ``` + * ...the resulting array will look like: [[a, B, c], [c, B, a]]. + * @param memberSet The members to be grouped. + * @param memberType The configured order of member types. + * @param supportsModifiers It'll get passed to getRank(). + * @returns The array of groups of members. + */ +function groupMembersByType(members, memberTypes, supportsModifiers) { + const groupedMembers = []; + const memberRanks = members.map(member => getRank(member, memberTypes, supportsModifiers)); + let previousRank = undefined; + members.forEach((member, index) => { + if (index === members.length - 1) { + return; + } + const rankOfCurrentMember = memberRanks[index]; + const rankOfNextMember = memberRanks[index + 1]; + if (rankOfCurrentMember === previousRank) { + groupedMembers.at(-1)?.push(member); + } + else if (rankOfCurrentMember === rankOfNextMember) { + groupedMembers.push([member]); + previousRank = rankOfCurrentMember; + } + }); + return groupedMembers; +} +/** + * Gets the lowest possible rank(s) higher than target. + * e.g. given the following order: + * ... + * public-static-method + * protected-static-method + * private-static-method + * public-instance-method + * protected-instance-method + * private-instance-method + * ... + * and considering that a public-instance-method has already been declared, so ranks contains + * public-instance-method, then the lowest possible rank for public-static-method is + * public-instance-method. + * If a lowest possible rank is a member group, a comma separated list of ranks is returned. + * @param ranks the existing ranks in the object. + * @param target the minimum target rank to filter on. + * @param order the current order to be validated. + * @returns the name(s) of the lowest possible rank without dashes (-). + */ +function getLowestRank(ranks, target, order) { + let lowest = ranks[ranks.length - 1]; + ranks.forEach(rank => { + if (rank > target) { + lowest = Math.min(lowest, rank); + } + }); + const lowestRank = order[lowest]; + const lowestRanks = Array.isArray(lowestRank) ? lowestRank : [lowestRank]; + return lowestRanks.map(rank => rank.replaceAll('-', ' ')).join(', '); +} +exports.default = (0, util_1.createRule)({ + name: 'member-ordering', + meta: { + type: 'suggestion', + docs: { + description: 'Require a consistent member declaration order', + }, + messages: { + incorrectGroupOrder: 'Member {{name}} should be declared before all {{rank}} definitions.', + incorrectOrder: 'Member {{member}} should be declared before member {{beforeMember}}.', + incorrectRequiredMembersOrder: `Member {{member}} should be declared after all {{optionalOrRequired}} members.`, + }, + schema: [ + { + type: 'object', + $defs: { + allItems: { + type: 'string', + enum: allMemberTypes, + }, + optionalityOrderOptions: { + type: 'string', + enum: ['optional-first', 'required-first'], + }, + orderOptions: { + type: 'string', + enum: [ + 'alphabetically', + 'alphabetically-case-insensitive', + 'as-written', + 'natural', + 'natural-case-insensitive', + ], + }, + typeItems: { + type: 'string', + enum: [ + 'readonly-signature', + 'signature', + 'readonly-field', + 'field', + 'method', + 'constructor', + ], + }, + // ajv is order-dependent; these configs must come last + baseConfig: { + oneOf: [ + neverConfig, + arrayConfig('#/items/0/$defs/allItems'), + objectConfig('#/items/0/$defs/allItems'), + ], + }, + typesConfig: { + oneOf: [ + neverConfig, + arrayConfig('#/items/0/$defs/typeItems'), + objectConfig('#/items/0/$defs/typeItems'), + ], + }, + }, + additionalProperties: false, + properties: { + classes: { + $ref: '#/items/0/$defs/baseConfig', + }, + classExpressions: { + $ref: '#/items/0/$defs/baseConfig', + }, + default: { + $ref: '#/items/0/$defs/baseConfig', + }, + interfaces: { + $ref: '#/items/0/$defs/typesConfig', + }, + typeLiterals: { + $ref: '#/items/0/$defs/typesConfig', + }, + }, + }, + ], + }, + defaultOptions: [ + { + default: { + memberTypes: exports.defaultOrder, + }, + }, + ], + create(context, [options]) { + /** + * Checks if the member groups are correctly sorted. + * + * @param members Members to be validated. + * @param groupOrder Group order to be validated. + * @param supportsModifiers A flag indicating whether the type supports modifiers (scope or accessibility) or not. + * + * @return Array of member groups or null if one of the groups is not correctly sorted. + */ + function checkGroupSort(members, groupOrder, supportsModifiers) { + const previousRanks = []; + const memberGroups = []; + let isCorrectlySorted = true; + // Find first member which isn't correctly sorted + for (const member of members) { + const rank = getRank(member, groupOrder, supportsModifiers); + const name = getMemberName(member, context.sourceCode); + const rankLastMember = previousRanks[previousRanks.length - 1]; + if (rank === -1) { + continue; + } + // Works for 1st item because x < undefined === false for any x (typeof string) + if (rank < rankLastMember) { + context.report({ + node: member, + messageId: 'incorrectGroupOrder', + data: { + name, + rank: getLowestRank(previousRanks, rank, groupOrder), + }, + }); + isCorrectlySorted = false; + } + else if (rank === rankLastMember) { + // Same member group --> Push to existing member group array + memberGroups[memberGroups.length - 1].push(member); + } + else { + // New member group --> Create new member group array + previousRanks.push(rank); + memberGroups.push([member]); + } + } + return isCorrectlySorted ? memberGroups : null; + } + /** + * Checks if the members are alphabetically sorted. + * + * @param members Members to be validated. + * @param order What order the members should be sorted in. + * + * @return True if all members are correctly sorted. + */ + function checkAlphaSort(members, order) { + let previousName = ''; + let isCorrectlySorted = true; + // Find first member which isn't correctly sorted + members.forEach(member => { + const name = getMemberName(member, context.sourceCode); + // Note: Not all members have names + if (name) { + if (naturalOutOfOrder(name, previousName, order)) { + context.report({ + node: member, + messageId: 'incorrectOrder', + data: { + beforeMember: previousName, + member: name, + }, + }); + isCorrectlySorted = false; + } + previousName = name; + } + }); + return isCorrectlySorted; + } + function naturalOutOfOrder(name, previousName, order) { + if (name === previousName) { + return false; + } + switch (order) { + case 'alphabetically': + return name < previousName; + case 'alphabetically-case-insensitive': + return name.toLowerCase() < previousName.toLowerCase(); + case 'natural': + return (0, natural_compare_1.default)(name, previousName) !== 1; + case 'natural-case-insensitive': + return ((0, natural_compare_1.default)(name.toLowerCase(), previousName.toLowerCase()) !== 1); + } + } + /** + * Checks if the order of optional and required members is correct based + * on the given 'required' parameter. + * + * @param members Members to be validated. + * @param optionalityOrder Where to place optional members, if not intermixed. + * + * @return True if all required and optional members are correctly sorted. + */ + function checkRequiredOrder(members, optionalityOrder) { + const switchIndex = members.findIndex((member, i) => i && isMemberOptional(member) !== isMemberOptional(members[i - 1])); + const report = (member) => context.report({ + loc: member.loc, + messageId: 'incorrectRequiredMembersOrder', + data: { + member: getMemberName(member, context.sourceCode), + optionalOrRequired: optionalityOrder === 'required-first' ? 'required' : 'optional', + }, + }); + // if the optionality of the first item is correct (based on optionalityOrder) + // then the first 0 inclusive to switchIndex exclusive members all + // have the correct optionality + if (isMemberOptional(members[0]) !== + (optionalityOrder === 'optional-first')) { + report(members[0]); + return false; + } + for (let i = switchIndex + 1; i < members.length; i++) { + if (isMemberOptional(members[i]) !== + isMemberOptional(members[switchIndex])) { + report(members[switchIndex]); + return false; + } + } + return true; + } + /** + * Validates if all members are correctly sorted. + * + * @param members Members to be validated. + * @param orderConfig Order config to be validated. + * @param supportsModifiers A flag indicating whether the type supports modifiers (scope or accessibility) or not. + */ + function validateMembersOrder(members, orderConfig, supportsModifiers) { + if (orderConfig === 'never') { + return; + } + // Standardize config + let order; + let memberTypes; + let optionalityOrder; + /** + * It runs an alphabetic sort on the groups of the members of the class in the source code. + * @param memberSet The members in the class of the source code on which the grouping operation will be performed. + */ + const checkAlphaSortForAllMembers = (memberSet) => { + const hasAlphaSort = !!(order && order !== 'as-written'); + if (hasAlphaSort && Array.isArray(memberTypes)) { + groupMembersByType(memberSet, memberTypes, supportsModifiers).forEach(members => { + checkAlphaSort(members, order); + }); + } + }; + // returns true if everything is good and false if an error was reported + const checkOrder = (memberSet) => { + const hasAlphaSort = !!(order && order !== 'as-written'); + // Check order + if (Array.isArray(memberTypes)) { + const grouped = checkGroupSort(memberSet, memberTypes, supportsModifiers); + if (grouped == null) { + checkAlphaSortForAllMembers(members); + return false; + } + if (hasAlphaSort) { + grouped.map(groupMember => checkAlphaSort(groupMember, order)); + } + } + else if (hasAlphaSort) { + return checkAlphaSort(memberSet, order); + } + return false; + }; + if (Array.isArray(orderConfig)) { + memberTypes = orderConfig; + } + else { + order = orderConfig.order; + memberTypes = orderConfig.memberTypes; + optionalityOrder = orderConfig.optionalityOrder; + } + if (!optionalityOrder) { + checkOrder(members); + return; + } + const switchIndex = members.findIndex((member, i) => i && isMemberOptional(member) !== isMemberOptional(members[i - 1])); + if (switchIndex !== -1) { + if (!checkRequiredOrder(members, optionalityOrder)) { + return; + } + checkOrder(members.slice(0, switchIndex)); + checkOrder(members.slice(switchIndex)); + } + else { + checkOrder(members); + } + } + // https://github.com/typescript-eslint/typescript-eslint/issues/5439 + /* eslint-disable @typescript-eslint/no-non-null-assertion */ + return { + ClassDeclaration(node) { + validateMembersOrder(node.body.body, options.classes ?? options.default, true); + }, + 'ClassDeclaration, FunctionDeclaration'(node) { + if ('superClass' in node) { + // ... + } + }, + ClassExpression(node) { + validateMembersOrder(node.body.body, options.classExpressions ?? options.default, true); + }, + TSInterfaceDeclaration(node) { + validateMembersOrder(node.body.body, options.interfaces ?? options.default, false); + }, + TSTypeLiteral(node) { + validateMembersOrder(node.members, options.typeLiterals ?? options.default, false); + }, + }; + /* eslint-enable @typescript-eslint/no-non-null-assertion */ + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/method-signature-style.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/method-signature-style.d.ts new file mode 100644 index 00000000..2f0d43d4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/method-signature-style.d.ts @@ -0,0 +1,5 @@ +export type Options = [('method' | 'property')?]; +export type MessageIds = 'errorMethod' | 'errorProperty'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=method-signature-style.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/method-signature-style.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/method-signature-style.d.ts.map new file mode 100644 index 00000000..bcd1ad01 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/method-signature-style.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"method-signature-style.d.ts","sourceRoot":"","sources":["../../src/rules/method-signature-style.ts"],"names":[],"mappings":"AAaA,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,QAAQ,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;AACjD,MAAM,MAAM,UAAU,GAAG,aAAa,GAAG,eAAe,CAAC;;AAEzD,wBAmOG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/method-signature-style.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/method-signature-style.js new file mode 100644 index 00000000..741e3ec1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/method-signature-style.js @@ -0,0 +1,176 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'method-signature-style', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce using a particular method signature syntax', + }, + fixable: 'code', + messages: { + errorMethod: 'Shorthand method signature is forbidden. Use a function property instead.', + errorProperty: 'Function property signature is forbidden. Use a method shorthand instead.', + }, + schema: [ + { + type: 'string', + enum: ['property', 'method'], + }, + ], + }, + defaultOptions: ['property'], + create(context, [mode]) { + function getMethodKey(node) { + let key = context.sourceCode.getText(node.key); + if (node.computed) { + key = `[${key}]`; + } + if (node.optional) { + key = `${key}?`; + } + if (node.readonly) { + key = `readonly ${key}`; + } + return key; + } + function getMethodParams(node) { + let params = '()'; + if (node.params.length > 0) { + const openingParen = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(node.params[0], util_1.isOpeningParenToken), 'Missing opening paren before first parameter'); + const closingParen = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.params[node.params.length - 1], util_1.isClosingParenToken), 'Missing closing paren after last parameter'); + params = context.sourceCode.text.substring(openingParen.range[0], closingParen.range[1]); + } + if (node.typeParameters != null) { + const typeParams = context.sourceCode.getText(node.typeParameters); + params = `${typeParams}${params}`; + } + return params; + } + function getMethodReturnType(node) { + return node.returnType == null + ? // if the method has no return type, it implicitly has an `any` return type + // we just make it explicit here so we can do the fix + 'any' + : context.sourceCode.getText(node.returnType.typeAnnotation); + } + function getDelimiter(node) { + const lastToken = context.sourceCode.getLastToken(node); + if (lastToken && + ((0, util_1.isSemicolonToken)(lastToken) || (0, util_1.isCommaToken)(lastToken))) { + return lastToken.value; + } + return ''; + } + function isNodeParentModuleDeclaration(node) { + if (!node.parent) { + return false; + } + if (node.parent.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration) { + return true; + } + if (node.parent.type === utils_1.AST_NODE_TYPES.Program) { + return false; + } + return isNodeParentModuleDeclaration(node.parent); + } + return { + ...(mode === 'property' && { + TSMethodSignature(methodNode) { + if (methodNode.kind !== 'method') { + return; + } + const parent = methodNode.parent; + const members = parent.type === utils_1.AST_NODE_TYPES.TSInterfaceBody + ? parent.body + : parent.members; + const duplicatedKeyMethodNodes = members.filter((element) => element.type === utils_1.AST_NODE_TYPES.TSMethodSignature && + element !== methodNode && + getMethodKey(element) === getMethodKey(methodNode)); + const isParentModule = isNodeParentModuleDeclaration(methodNode); + if (duplicatedKeyMethodNodes.length > 0) { + if (isParentModule) { + context.report({ + node: methodNode, + messageId: 'errorMethod', + }); + } + else { + context.report({ + node: methodNode, + messageId: 'errorMethod', + *fix(fixer) { + const methodNodes = [ + methodNode, + ...duplicatedKeyMethodNodes, + ].sort((a, b) => (a.range[0] < b.range[0] ? -1 : 1)); + const typeString = methodNodes + .map(node => { + const params = getMethodParams(node); + const returnType = getMethodReturnType(node); + return `(${params} => ${returnType})`; + }) + .join(' & '); + const key = getMethodKey(methodNode); + const delimiter = getDelimiter(methodNode); + yield fixer.replaceText(methodNode, `${key}: ${typeString}${delimiter}`); + for (const node of duplicatedKeyMethodNodes) { + const lastToken = context.sourceCode.getLastToken(node); + if (lastToken) { + const nextToken = context.sourceCode.getTokenAfter(lastToken); + if (nextToken) { + yield fixer.remove(node); + yield fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], ''); + } + } + } + }, + }); + } + return; + } + if (isParentModule) { + context.report({ + node: methodNode, + messageId: 'errorMethod', + }); + } + else { + context.report({ + node: methodNode, + messageId: 'errorMethod', + fix: fixer => { + const key = getMethodKey(methodNode); + const params = getMethodParams(methodNode); + const returnType = getMethodReturnType(methodNode); + const delimiter = getDelimiter(methodNode); + return fixer.replaceText(methodNode, `${key}: ${params} => ${returnType}${delimiter}`); + }, + }); + } + }, + }), + ...(mode === 'method' && { + TSPropertySignature(propertyNode) { + const typeNode = propertyNode.typeAnnotation?.typeAnnotation; + if (typeNode?.type !== utils_1.AST_NODE_TYPES.TSFunctionType) { + return; + } + context.report({ + node: propertyNode, + messageId: 'errorProperty', + fix: fixer => { + const key = getMethodKey(propertyNode); + const params = getMethodParams(typeNode); + const returnType = getMethodReturnType(typeNode); + const delimiter = getDelimiter(propertyNode); + return fixer.replaceText(propertyNode, `${key}${params}: ${returnType}${delimiter}`); + }, + }); + }, + }), + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/enums.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/enums.d.ts new file mode 100644 index 00000000..dbb729d1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/enums.d.ts @@ -0,0 +1,80 @@ +export declare enum PredefinedFormats { + camelCase = 1, + strictCamelCase = 2, + PascalCase = 3, + StrictPascalCase = 4, + snake_case = 5, + UPPER_CASE = 6 +} +export type PredefinedFormatsString = keyof typeof PredefinedFormats; +export declare enum UnderscoreOptions { + forbid = 1, + allow = 2, + require = 3, + requireDouble = 4, + allowDouble = 5, + allowSingleOrDouble = 6 +} +export type UnderscoreOptionsString = keyof typeof UnderscoreOptions; +export declare enum Selectors { + variable = 1, + function = 2, + parameter = 4, + parameterProperty = 8, + classicAccessor = 16, + enumMember = 32, + classMethod = 64, + objectLiteralMethod = 128, + typeMethod = 256, + classProperty = 512, + objectLiteralProperty = 1024, + typeProperty = 2048, + autoAccessor = 4096, + class = 8192, + interface = 16384, + typeAlias = 32768, + enum = 65536, + typeParameter = 131072, + import = 262144 +} +export type SelectorsString = keyof typeof Selectors; +export declare enum MetaSelectors { + default = -1, + variableLike = 7, + memberLike = 8184, + typeLike = 253952, + method = 448, + property = 3584, + accessor = 4112 +} +export type MetaSelectorsString = keyof typeof MetaSelectors; +export type IndividualAndMetaSelectorsString = MetaSelectorsString | SelectorsString; +export declare enum Modifiers { + const = 1, + readonly = 2, + static = 4, + public = 8, + protected = 16, + private = 32, + '#private' = 64, + abstract = 128, + destructured = 256, + global = 512, + exported = 1024, + unused = 2048, + requiresQuotes = 4096, + override = 8192, + async = 16384, + default = 32768, + namespace = 65536 +} +export type ModifiersString = keyof typeof Modifiers; +export declare enum TypeModifiers { + boolean = 131072, + string = 262144, + number = 524288, + function = 1048576, + array = 2097152 +} +export type TypeModifiersString = keyof typeof TypeModifiers; +//# sourceMappingURL=enums.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/enums.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/enums.d.ts.map new file mode 100644 index 00000000..7f6a5629 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/enums.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"enums.d.ts","sourceRoot":"","sources":["../../../src/rules/naming-convention-utils/enums.ts"],"names":[],"mappings":"AAAA,oBAAY,iBAAiB;IAC3B,SAAS,IAAI;IACb,eAAe,IAAA;IACf,UAAU,IAAA;IACV,gBAAgB,IAAA;IAChB,UAAU,IAA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AEhB,cAAc,OAAU;IAExB,QAAQ,OAAU;IAElB,KAAK,QAAU;IAEf,OAAO,QAAU;IAEjB,SAAS,QAAU;CAGpB;AACD,MAAM,MAAM,eAAe,GAAG,MAAM,OAAO,SAAS,CAAC;AAErD,oBAAY,aAAa;IACvB,OAAO,SAAU;IACjB,MAAM,SAAU;IAChB,MAAM,SAAU;IAChB,QAAQ,UAAU;IAClB,KAAK,UAAU;CAChB;AACD,MAAM,MAAM,mBAAmB,GAAG,MAAM,OAAO,aAAa,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/enums.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/enums.js new file mode 100644 index 00000000..56966533 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/enums.js @@ -0,0 +1,102 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeModifiers = exports.Modifiers = exports.MetaSelectors = exports.Selectors = exports.UnderscoreOptions = exports.PredefinedFormats = void 0; +var PredefinedFormats; +(function (PredefinedFormats) { + PredefinedFormats[PredefinedFormats["camelCase"] = 1] = "camelCase"; + PredefinedFormats[PredefinedFormats["strictCamelCase"] = 2] = "strictCamelCase"; + PredefinedFormats[PredefinedFormats["PascalCase"] = 3] = "PascalCase"; + PredefinedFormats[PredefinedFormats["StrictPascalCase"] = 4] = "StrictPascalCase"; + PredefinedFormats[PredefinedFormats["snake_case"] = 5] = "snake_case"; + PredefinedFormats[PredefinedFormats["UPPER_CASE"] = 6] = "UPPER_CASE"; +})(PredefinedFormats || (exports.PredefinedFormats = PredefinedFormats = {})); +var UnderscoreOptions; +(function (UnderscoreOptions) { + UnderscoreOptions[UnderscoreOptions["forbid"] = 1] = "forbid"; + UnderscoreOptions[UnderscoreOptions["allow"] = 2] = "allow"; + UnderscoreOptions[UnderscoreOptions["require"] = 3] = "require"; + // special cases as it's common practice to use double underscore + UnderscoreOptions[UnderscoreOptions["requireDouble"] = 4] = "requireDouble"; + UnderscoreOptions[UnderscoreOptions["allowDouble"] = 5] = "allowDouble"; + UnderscoreOptions[UnderscoreOptions["allowSingleOrDouble"] = 6] = "allowSingleOrDouble"; +})(UnderscoreOptions || (exports.UnderscoreOptions = UnderscoreOptions = {})); +var Selectors; +(function (Selectors) { + // variableLike + Selectors[Selectors["variable"] = 1] = "variable"; + Selectors[Selectors["function"] = 2] = "function"; + Selectors[Selectors["parameter"] = 4] = "parameter"; + // memberLike + Selectors[Selectors["parameterProperty"] = 8] = "parameterProperty"; + Selectors[Selectors["classicAccessor"] = 16] = "classicAccessor"; + Selectors[Selectors["enumMember"] = 32] = "enumMember"; + Selectors[Selectors["classMethod"] = 64] = "classMethod"; + Selectors[Selectors["objectLiteralMethod"] = 128] = "objectLiteralMethod"; + Selectors[Selectors["typeMethod"] = 256] = "typeMethod"; + Selectors[Selectors["classProperty"] = 512] = "classProperty"; + Selectors[Selectors["objectLiteralProperty"] = 1024] = "objectLiteralProperty"; + Selectors[Selectors["typeProperty"] = 2048] = "typeProperty"; + Selectors[Selectors["autoAccessor"] = 4096] = "autoAccessor"; + // typeLike + Selectors[Selectors["class"] = 8192] = "class"; + Selectors[Selectors["interface"] = 16384] = "interface"; + Selectors[Selectors["typeAlias"] = 32768] = "typeAlias"; + Selectors[Selectors["enum"] = 65536] = "enum"; + Selectors[Selectors["typeParameter"] = 131072] = "typeParameter"; + // other + Selectors[Selectors["import"] = 262144] = "import"; +})(Selectors || (exports.Selectors = Selectors = {})); +var MetaSelectors; +(function (MetaSelectors) { + /* eslint-disable @typescript-eslint/prefer-literal-enum-member */ + MetaSelectors[MetaSelectors["default"] = -1] = "default"; + MetaSelectors[MetaSelectors["variableLike"] = 7] = "variableLike"; + MetaSelectors[MetaSelectors["memberLike"] = 8184] = "memberLike"; + MetaSelectors[MetaSelectors["typeLike"] = 253952] = "typeLike"; + MetaSelectors[MetaSelectors["method"] = 448] = "method"; + MetaSelectors[MetaSelectors["property"] = 3584] = "property"; + MetaSelectors[MetaSelectors["accessor"] = 4112] = "accessor"; + /* eslint-enable @typescript-eslint/prefer-literal-enum-member */ +})(MetaSelectors || (exports.MetaSelectors = MetaSelectors = {})); +var Modifiers; +(function (Modifiers) { + // const variable + Modifiers[Modifiers["const"] = 1] = "const"; + // readonly members + Modifiers[Modifiers["readonly"] = 2] = "readonly"; + // static members + Modifiers[Modifiers["static"] = 4] = "static"; + // member accessibility + Modifiers[Modifiers["public"] = 8] = "public"; + Modifiers[Modifiers["protected"] = 16] = "protected"; + Modifiers[Modifiers["private"] = 32] = "private"; + Modifiers[Modifiers["#private"] = 64] = "#private"; + Modifiers[Modifiers["abstract"] = 128] = "abstract"; + // destructured variable + Modifiers[Modifiers["destructured"] = 256] = "destructured"; + // variables declared in the top-level scope + Modifiers[Modifiers["global"] = 512] = "global"; + // things that are exported + Modifiers[Modifiers["exported"] = 1024] = "exported"; + // things that are unused + Modifiers[Modifiers["unused"] = 2048] = "unused"; + // properties that require quoting + Modifiers[Modifiers["requiresQuotes"] = 4096] = "requiresQuotes"; + // class members that are overridden + Modifiers[Modifiers["override"] = 8192] = "override"; + // class methods, object function properties, or functions that are async via the `async` keyword + Modifiers[Modifiers["async"] = 16384] = "async"; + // default imports + Modifiers[Modifiers["default"] = 32768] = "default"; + // namespace imports + Modifiers[Modifiers["namespace"] = 65536] = "namespace"; + // make sure TypeModifiers starts at Modifiers + 1 or else sorting won't work +})(Modifiers || (exports.Modifiers = Modifiers = {})); +var TypeModifiers; +(function (TypeModifiers) { + TypeModifiers[TypeModifiers["boolean"] = 131072] = "boolean"; + TypeModifiers[TypeModifiers["string"] = 262144] = "string"; + TypeModifiers[TypeModifiers["number"] = 524288] = "number"; + TypeModifiers[TypeModifiers["function"] = 1048576] = "function"; + TypeModifiers[TypeModifiers["array"] = 2097152] = "array"; +})(TypeModifiers || (exports.TypeModifiers = TypeModifiers = {})); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/format.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/format.d.ts new file mode 100644 index 00000000..8284d0bb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/format.d.ts @@ -0,0 +1,3 @@ +import { PredefinedFormats } from './enums'; +export declare const PredefinedFormatToCheckFunction: Readonly boolean>>; +//# sourceMappingURL=format.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/format.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/format.d.ts.map new file mode 100644 index 00000000..1919b9e2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/format.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../../src/rules/naming-convention-utils/format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAkG5C,eAAO,MAAM,+BAA+B,EAAE,QAAQ,CACpD,MAAM,CAAC,iBAAiB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,CAQrD,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/format.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/format.js new file mode 100644 index 00000000..e2a6eec3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/format.js @@ -0,0 +1,89 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PredefinedFormatToCheckFunction = void 0; +const enums_1 = require("./enums"); +/* +These format functions are taken from `tslint-consistent-codestyle/naming-convention`: +https://github.com/ajafff/tslint-consistent-codestyle/blob/ab156cc8881bcc401236d999f4ce034b59039e81/rules/namingConventionRule.ts#L603-L645 + +The license for the code can be viewed here: +https://github.com/ajafff/tslint-consistent-codestyle/blob/ab156cc8881bcc401236d999f4ce034b59039e81/LICENSE +*/ +/* +Why not regex here? Because it's actually really, really difficult to create a regex to handle +all of the unicode cases, and we have many non-english users that use non-english characters. +https://gist.github.com/mathiasbynens/6334847 +*/ +function isPascalCase(name) { + return (name.length === 0 || + (name[0] === name[0].toUpperCase() && !name.includes('_'))); +} +function isStrictPascalCase(name) { + return (name.length === 0 || + (name[0] === name[0].toUpperCase() && hasStrictCamelHumps(name, true))); +} +function isCamelCase(name) { + return (name.length === 0 || + (name[0] === name[0].toLowerCase() && !name.includes('_'))); +} +function isStrictCamelCase(name) { + return (name.length === 0 || + (name[0] === name[0].toLowerCase() && hasStrictCamelHumps(name, false))); +} +function hasStrictCamelHumps(name, isUpper) { + function isUppercaseChar(char) { + return char === char.toUpperCase() && char !== char.toLowerCase(); + } + if (name.startsWith('_')) { + return false; + } + for (let i = 1; i < name.length; ++i) { + if (name[i] === '_') { + return false; + } + if (isUpper === isUppercaseChar(name[i])) { + if (isUpper) { + return false; + } + } + else { + isUpper = !isUpper; + } + } + return true; +} +function isSnakeCase(name) { + return (name.length === 0 || + (name === name.toLowerCase() && validateUnderscores(name))); +} +function isUpperCase(name) { + return (name.length === 0 || + (name === name.toUpperCase() && validateUnderscores(name))); +} +/** Check for leading trailing and adjacent underscores */ +function validateUnderscores(name) { + if (name.startsWith('_')) { + return false; + } + let wasUnderscore = false; + for (let i = 1; i < name.length; ++i) { + if (name[i] === '_') { + if (wasUnderscore) { + return false; + } + wasUnderscore = true; + } + else { + wasUnderscore = false; + } + } + return !wasUnderscore; +} +exports.PredefinedFormatToCheckFunction = { + [enums_1.PredefinedFormats.camelCase]: isCamelCase, + [enums_1.PredefinedFormats.PascalCase]: isPascalCase, + [enums_1.PredefinedFormats.snake_case]: isSnakeCase, + [enums_1.PredefinedFormats.strictCamelCase]: isStrictCamelCase, + [enums_1.PredefinedFormats.StrictPascalCase]: isStrictPascalCase, + [enums_1.PredefinedFormats.UPPER_CASE]: isUpperCase, +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/index.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/index.d.ts new file mode 100644 index 00000000..d2f6feef --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/index.d.ts @@ -0,0 +1,7 @@ +export { Modifiers } from './enums'; +export type { PredefinedFormatsString } from './enums'; +export { parseOptions } from './parse-options'; +export { SCHEMA } from './schema'; +export { selectorTypeToMessageString } from './shared'; +export type { Context, Selector, ValidatorFunction } from './types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/index.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/index.d.ts.map new file mode 100644 index 00000000..f8900c92 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/rules/naming-convention-utils/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,YAAY,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AACvD,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/index.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/index.js new file mode 100644 index 00000000..0db6e930 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/index.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.selectorTypeToMessageString = exports.SCHEMA = exports.parseOptions = exports.Modifiers = void 0; +var enums_1 = require("./enums"); +Object.defineProperty(exports, "Modifiers", { enumerable: true, get: function () { return enums_1.Modifiers; } }); +var parse_options_1 = require("./parse-options"); +Object.defineProperty(exports, "parseOptions", { enumerable: true, get: function () { return parse_options_1.parseOptions; } }); +var schema_1 = require("./schema"); +Object.defineProperty(exports, "SCHEMA", { enumerable: true, get: function () { return schema_1.SCHEMA; } }); +var shared_1 = require("./shared"); +Object.defineProperty(exports, "selectorTypeToMessageString", { enumerable: true, get: function () { return shared_1.selectorTypeToMessageString; } }); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/parse-options.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/parse-options.d.ts new file mode 100644 index 00000000..d1a018a1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/parse-options.d.ts @@ -0,0 +1,3 @@ +import type { Context, ParsedOptions } from './types'; +export declare function parseOptions(context: Context): ParsedOptions; +//# sourceMappingURL=parse-options.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/parse-options.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/parse-options.d.ts.map new file mode 100644 index 00000000..b24b230e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/parse-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-options.d.ts","sourceRoot":"","sources":["../../../src/rules/naming-convention-utils/parse-options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EAEP,aAAa,EAEd,MAAM,SAAS,CAAC;AA6EjB,wBAAgB,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,aAAa,CAS5D"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/parse-options.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/parse-options.js new file mode 100644 index 00000000..eff503ff --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/parse-options.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseOptions = parseOptions; +const util_1 = require("../../util"); +const enums_1 = require("./enums"); +const shared_1 = require("./shared"); +const validator_1 = require("./validator"); +function normalizeOption(option) { + let weight = 0; + option.modifiers?.forEach(mod => { + weight |= enums_1.Modifiers[mod]; + }); + option.types?.forEach(mod => { + weight |= enums_1.TypeModifiers[mod]; + }); + // give selectors with a filter the _highest_ priority + if (option.filter) { + weight |= 1 << 30; + } + const normalizedOption = { + // format options + custom: option.custom + ? { + match: option.custom.match, + regex: new RegExp(option.custom.regex, 'u'), + } + : null, + filter: option.filter != null + ? typeof option.filter === 'string' + ? { + match: true, + regex: new RegExp(option.filter, 'u'), + } + : { + match: option.filter.match, + regex: new RegExp(option.filter.regex, 'u'), + } + : null, + format: option.format ? option.format.map(f => enums_1.PredefinedFormats[f]) : null, + leadingUnderscore: option.leadingUnderscore != null + ? enums_1.UnderscoreOptions[option.leadingUnderscore] + : null, + modifiers: option.modifiers?.map(m => enums_1.Modifiers[m]) ?? null, + prefix: option.prefix && option.prefix.length > 0 ? option.prefix : null, + suffix: option.suffix && option.suffix.length > 0 ? option.suffix : null, + trailingUnderscore: option.trailingUnderscore != null + ? enums_1.UnderscoreOptions[option.trailingUnderscore] + : null, + types: option.types?.map(m => enums_1.TypeModifiers[m]) ?? null, + // calculated ordering weight based on modifiers + modifierWeight: weight, + }; + const selectors = Array.isArray(option.selector) + ? option.selector + : [option.selector]; + return selectors.map(selector => ({ + selector: (0, shared_1.isMetaSelector)(selector) + ? enums_1.MetaSelectors[selector] + : enums_1.Selectors[selector], + ...normalizedOption, + })); +} +function parseOptions(context) { + const normalizedOptions = context.options.flatMap(normalizeOption); + return Object.fromEntries((0, util_1.getEnumNames)(enums_1.Selectors).map(k => [ + k, + (0, validator_1.createValidator)(k, context, normalizedOptions), + ])); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/schema.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/schema.d.ts new file mode 100644 index 00000000..81390cb1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/schema.d.ts @@ -0,0 +1,3 @@ +import type { JSONSchema } from '@typescript-eslint/utils'; +export declare const SCHEMA: JSONSchema.JSONSchema4; +//# sourceMappingURL=schema.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/schema.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/schema.d.ts.map new file mode 100644 index 00000000..6363d485 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/schema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../src/rules/naming-convention-utils/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AA2L3D,eAAO,MAAM,MAAM,EAAE,UAAU,CAAC,WA+I/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/schema.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/schema.js new file mode 100644 index 00000000..719777d3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/schema.js @@ -0,0 +1,305 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SCHEMA = void 0; +const util_1 = require("../../util"); +const enums_1 = require("./enums"); +const $DEFS = { + // enums + predefinedFormats: { + enum: (0, util_1.getEnumNames)(enums_1.PredefinedFormats), + type: 'string', + }, + typeModifiers: { + enum: (0, util_1.getEnumNames)(enums_1.TypeModifiers), + type: 'string', + }, + underscoreOptions: { + enum: (0, util_1.getEnumNames)(enums_1.UnderscoreOptions), + type: 'string', + }, + // repeated types + formatOptionsConfig: { + oneOf: [ + { + additionalItems: false, + items: { + $ref: '#/$defs/predefinedFormats', + }, + type: 'array', + }, + { + type: 'null', + }, + ], + }, + matchRegexConfig: { + additionalProperties: false, + properties: { + match: { type: 'boolean' }, + regex: { type: 'string' }, + }, + required: ['match', 'regex'], + type: 'object', + }, + prefixSuffixConfig: { + additionalItems: false, + items: { + minLength: 1, + type: 'string', + }, + type: 'array', + }, +}; +const UNDERSCORE_SCHEMA = { + $ref: '#/$defs/underscoreOptions', +}; +const PREFIX_SUFFIX_SCHEMA = { + $ref: '#/$defs/prefixSuffixConfig', +}; +const MATCH_REGEX_SCHEMA = { + $ref: '#/$defs/matchRegexConfig', +}; +const FORMAT_OPTIONS_PROPERTIES = { + custom: MATCH_REGEX_SCHEMA, + failureMessage: { + type: 'string', + }, + format: { + $ref: '#/$defs/formatOptionsConfig', + }, + leadingUnderscore: UNDERSCORE_SCHEMA, + prefix: PREFIX_SUFFIX_SCHEMA, + suffix: PREFIX_SUFFIX_SCHEMA, + trailingUnderscore: UNDERSCORE_SCHEMA, +}; +function selectorSchema(selectorString, allowType, modifiers) { + const selector = { + filter: { + oneOf: [ + { + minLength: 1, + type: 'string', + }, + MATCH_REGEX_SCHEMA, + ], + }, + selector: { + enum: [selectorString], + type: 'string', + }, + }; + if (modifiers && modifiers.length > 0) { + selector.modifiers = { + additionalItems: false, + items: { + enum: modifiers, + type: 'string', + }, + type: 'array', + }; + } + if (allowType) { + selector.types = { + additionalItems: false, + items: { + $ref: '#/$defs/typeModifiers', + }, + type: 'array', + }; + } + return [ + { + additionalProperties: false, + description: `Selector '${selectorString}'`, + properties: { + ...FORMAT_OPTIONS_PROPERTIES, + ...selector, + }, + required: ['selector', 'format'], + type: 'object', + }, + ]; +} +function selectorsSchema() { + return { + additionalProperties: false, + description: 'Multiple selectors in one config', + properties: { + ...FORMAT_OPTIONS_PROPERTIES, + filter: { + oneOf: [ + { + minLength: 1, + type: 'string', + }, + MATCH_REGEX_SCHEMA, + ], + }, + modifiers: { + additionalItems: false, + items: { + enum: (0, util_1.getEnumNames)(enums_1.Modifiers), + type: 'string', + }, + type: 'array', + }, + selector: { + additionalItems: false, + items: { + enum: [...(0, util_1.getEnumNames)(enums_1.MetaSelectors), ...(0, util_1.getEnumNames)(enums_1.Selectors)], + type: 'string', + }, + type: 'array', + }, + types: { + additionalItems: false, + items: { + $ref: '#/$defs/typeModifiers', + }, + type: 'array', + }, + }, + required: ['selector', 'format'], + type: 'object', + }; +} +exports.SCHEMA = { + $defs: $DEFS, + additionalItems: false, + items: { + oneOf: [ + selectorsSchema(), + ...selectorSchema('default', false, (0, util_1.getEnumNames)(enums_1.Modifiers)), + ...selectorSchema('variableLike', false, ['unused', 'async']), + ...selectorSchema('variable', true, [ + 'const', + 'destructured', + 'exported', + 'global', + 'unused', + 'async', + ]), + ...selectorSchema('function', false, [ + 'exported', + 'global', + 'unused', + 'async', + ]), + ...selectorSchema('parameter', true, ['destructured', 'unused']), + ...selectorSchema('memberLike', false, [ + 'abstract', + 'private', + '#private', + 'protected', + 'public', + 'readonly', + 'requiresQuotes', + 'static', + 'override', + 'async', + ]), + ...selectorSchema('classProperty', true, [ + 'abstract', + 'private', + '#private', + 'protected', + 'public', + 'readonly', + 'requiresQuotes', + 'static', + 'override', + ]), + ...selectorSchema('objectLiteralProperty', true, [ + 'public', + 'requiresQuotes', + ]), + ...selectorSchema('typeProperty', true, [ + 'public', + 'readonly', + 'requiresQuotes', + ]), + ...selectorSchema('parameterProperty', true, [ + 'private', + 'protected', + 'public', + 'readonly', + ]), + ...selectorSchema('property', true, [ + 'abstract', + 'private', + '#private', + 'protected', + 'public', + 'readonly', + 'requiresQuotes', + 'static', + 'override', + 'async', + ]), + ...selectorSchema('classMethod', false, [ + 'abstract', + 'private', + '#private', + 'protected', + 'public', + 'requiresQuotes', + 'static', + 'override', + 'async', + ]), + ...selectorSchema('objectLiteralMethod', false, [ + 'public', + 'requiresQuotes', + 'async', + ]), + ...selectorSchema('typeMethod', false, ['public', 'requiresQuotes']), + ...selectorSchema('method', false, [ + 'abstract', + 'private', + '#private', + 'protected', + 'public', + 'requiresQuotes', + 'static', + 'override', + 'async', + ]), + ...selectorSchema('classicAccessor', true, [ + 'abstract', + 'private', + 'protected', + 'public', + 'requiresQuotes', + 'static', + 'override', + ]), + ...selectorSchema('autoAccessor', true, [ + 'abstract', + 'private', + 'protected', + 'public', + 'requiresQuotes', + 'static', + 'override', + ]), + ...selectorSchema('accessor', true, [ + 'abstract', + 'private', + 'protected', + 'public', + 'requiresQuotes', + 'static', + 'override', + ]), + ...selectorSchema('enumMember', false, ['requiresQuotes']), + ...selectorSchema('typeLike', false, ['abstract', 'exported', 'unused']), + ...selectorSchema('class', false, ['abstract', 'exported', 'unused']), + ...selectorSchema('interface', false, ['exported', 'unused']), + ...selectorSchema('typeAlias', false, ['exported', 'unused']), + ...selectorSchema('enum', false, ['exported', 'unused']), + ...selectorSchema('typeParameter', false, ['unused']), + ...selectorSchema('import', false, ['default', 'namespace']), + ], + }, + type: 'array', +}; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/shared.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/shared.d.ts new file mode 100644 index 00000000..39e483cc --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/shared.d.ts @@ -0,0 +1,6 @@ +import type { IndividualAndMetaSelectorsString, MetaSelectorsString, Selectors, SelectorsString } from './enums'; +import { MetaSelectors } from './enums'; +export declare function selectorTypeToMessageString(selectorType: SelectorsString): string; +export declare function isMetaSelector(selector: IndividualAndMetaSelectorsString | MetaSelectors | Selectors): selector is MetaSelectorsString; +export declare function isMethodOrPropertySelector(selector: IndividualAndMetaSelectorsString | MetaSelectors | Selectors): boolean; +//# sourceMappingURL=shared.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/shared.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/shared.d.ts.map new file mode 100644 index 00000000..bf963cd0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/shared.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../../src/rules/naming-convention-utils/shared.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gCAAgC,EAChC,mBAAmB,EACnB,SAAS,EACT,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAExC,wBAAgB,2BAA2B,CACzC,YAAY,EAAE,eAAe,GAC5B,MAAM,CAGR;AAED,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,gCAAgC,GAAG,aAAa,GAAG,SAAS,GACrE,QAAQ,IAAI,mBAAmB,CAEjC;AAED,wBAAgB,0BAA0B,CACxC,QAAQ,EAAE,gCAAgC,GAAG,aAAa,GAAG,SAAS,GACrE,OAAO,CAIT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/shared.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/shared.js new file mode 100644 index 00000000..654cb252 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/shared.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.selectorTypeToMessageString = selectorTypeToMessageString; +exports.isMetaSelector = isMetaSelector; +exports.isMethodOrPropertySelector = isMethodOrPropertySelector; +const enums_1 = require("./enums"); +function selectorTypeToMessageString(selectorType) { + const notCamelCase = selectorType.replaceAll(/([A-Z])/g, ' $1'); + return notCamelCase.charAt(0).toUpperCase() + notCamelCase.slice(1); +} +function isMetaSelector(selector) { + return selector in enums_1.MetaSelectors; +} +function isMethodOrPropertySelector(selector) { + return (selector === enums_1.MetaSelectors.method || selector === enums_1.MetaSelectors.property); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/types.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/types.d.ts new file mode 100644 index 00000000..8008417a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/types.d.ts @@ -0,0 +1,40 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +import type { MessageIds, Options } from '../naming-convention'; +import type { IndividualAndMetaSelectorsString, MetaSelectors, Modifiers, ModifiersString, PredefinedFormats, PredefinedFormatsString, Selectors, SelectorsString, TypeModifiers, TypeModifiersString, UnderscoreOptions, UnderscoreOptionsString } from './enums'; +export interface MatchRegex { + match: boolean; + regex: string; +} +export interface Selector { + custom?: MatchRegex; + filter?: string | MatchRegex; + format: PredefinedFormatsString[] | null; + leadingUnderscore?: UnderscoreOptionsString; + modifiers?: ModifiersString[]; + prefix?: string[]; + selector: IndividualAndMetaSelectorsString | IndividualAndMetaSelectorsString[]; + suffix?: string[]; + trailingUnderscore?: UnderscoreOptionsString; + types?: TypeModifiersString[]; +} +export interface NormalizedMatchRegex { + match: boolean; + regex: RegExp; +} +export interface NormalizedSelector { + custom: NormalizedMatchRegex | null; + filter: NormalizedMatchRegex | null; + format: PredefinedFormats[] | null; + leadingUnderscore: UnderscoreOptions | null; + modifiers: Modifiers[] | null; + modifierWeight: number; + prefix: string[] | null; + selector: MetaSelectors | Selectors; + suffix: string[] | null; + trailingUnderscore: UnderscoreOptions | null; + types: TypeModifiers[] | null; +} +export type ValidatorFunction = (node: TSESTree.Identifier | TSESTree.Literal | TSESTree.PrivateIdentifier, modifiers?: Set) => void; +export type ParsedOptions = Record; +export type Context = Readonly>; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/types.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/types.d.ts.map new file mode 100644 index 00000000..1c006167 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/rules/naming-convention-utils/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,KAAK,EACV,gCAAgC,EAChC,aAAa,EACb,SAAS,EACT,eAAe,EACf,iBAAiB,EACjB,uBAAuB,EACvB,SAAS,EACT,eAAe,EACf,aAAa,EACb,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,EACxB,MAAM,SAAS,CAAC;AAEjB,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,QAAQ;IACvB,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;IAE7B,MAAM,EAAE,uBAAuB,EAAE,GAAG,IAAI,CAAC;IACzC,iBAAiB,CAAC,EAAE,uBAAuB,CAAC;IAC5C,SAAS,CAAC,EAAE,eAAe,EAAE,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAElB,QAAQ,EACJ,gCAAgC,GAChC,gCAAgC,EAAE,CAAC;IACvC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,kBAAkB,CAAC,EAAE,uBAAuB,CAAC;IAC7C,KAAK,CAAC,EAAE,mBAAmB,EAAE,CAAC;CAC/B;AAED,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,oBAAoB,GAAG,IAAI,CAAC;IACpC,MAAM,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAEpC,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;IACnC,iBAAiB,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAC5C,SAAS,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IAE9B,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAExB,QAAQ,EAAE,aAAa,GAAG,SAAS,CAAC;IACpC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACxB,kBAAkB,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAC7C,KAAK,EAAE,aAAa,EAAE,GAAG,IAAI,CAAC;CAC/B;AAED,MAAM,MAAM,iBAAiB,GAAG,CAC9B,IAAI,EAAE,QAAQ,CAAC,UAAU,GAAG,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC,iBAAiB,EACzE,SAAS,CAAC,EAAE,GAAG,CAAC,SAAS,CAAC,KACvB,IAAI,CAAC;AACV,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,eAAe,EAAE,iBAAiB,CAAC,CAAC;AACvE,MAAM,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/types.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/types.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/validator.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/validator.d.ts new file mode 100644 index 00000000..21de505b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/validator.d.ts @@ -0,0 +1,5 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { SelectorsString } from './enums'; +import type { Context, NormalizedSelector } from './types'; +export declare function createValidator(type: SelectorsString, context: Context, allConfigs: NormalizedSelector[]): (node: TSESTree.Identifier | TSESTree.Literal | TSESTree.PrivateIdentifier) => void; +//# sourceMappingURL=validator.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/validator.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/validator.d.ts.map new file mode 100644 index 00000000..302b1b27 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/validator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"validator.d.ts","sourceRoot":"","sources":["../../../src/rules/naming-convention-utils/validator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAKzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAkB3D,wBAAgB,eAAe,CAC7B,IAAI,EAAE,eAAe,EACrB,OAAO,EAAE,OAAO,EAChB,UAAU,EAAE,kBAAkB,EAAE,GAC/B,CACD,IAAI,EAAE,QAAQ,CAAC,UAAU,GAAG,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC,iBAAiB,KACtE,IAAI,CAgYR"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/validator.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/validator.js new file mode 100644 index 00000000..64dfc623 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention-utils/validator.js @@ -0,0 +1,349 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createValidator = createValidator; +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../../util"); +const enums_1 = require("./enums"); +const format_1 = require("./format"); +const shared_1 = require("./shared"); +function createValidator(type, context, allConfigs) { + // make sure the "highest priority" configs are checked first + const selectorType = enums_1.Selectors[type]; + const configs = allConfigs + // gather all of the applicable selectors + .filter(c => (c.selector & selectorType) !== 0 || + c.selector === enums_1.MetaSelectors.default) + .sort((a, b) => { + if (a.selector === b.selector) { + // in the event of the same selector, order by modifier weight + // sort descending - the type modifiers are "more important" + return b.modifierWeight - a.modifierWeight; + } + const aIsMeta = (0, shared_1.isMetaSelector)(a.selector); + const bIsMeta = (0, shared_1.isMetaSelector)(b.selector); + // non-meta selectors should go ahead of meta selectors + if (aIsMeta && !bIsMeta) { + return 1; + } + if (!aIsMeta && bIsMeta) { + return -1; + } + const aIsMethodOrProperty = (0, shared_1.isMethodOrPropertySelector)(a.selector); + const bIsMethodOrProperty = (0, shared_1.isMethodOrPropertySelector)(b.selector); + // for backward compatibility, method and property have higher precedence than other meta selectors + if (aIsMethodOrProperty && !bIsMethodOrProperty) { + return -1; + } + if (!aIsMethodOrProperty && bIsMethodOrProperty) { + return 1; + } + // both aren't meta selectors + // sort descending - the meta selectors are "least important" + return b.selector - a.selector; + }); + return (node, modifiers = new Set()) => { + const originalName = node.type === utils_1.AST_NODE_TYPES.Identifier || + node.type === utils_1.AST_NODE_TYPES.PrivateIdentifier + ? node.name + : `${node.value}`; + // return will break the loop and stop checking configs + // it is only used when the name is known to have failed or succeeded a config. + for (const config of configs) { + if (config.filter?.regex.test(originalName) !== config.filter?.match) { + // name does not match the filter + continue; + } + if (config.modifiers?.some(modifier => !modifiers.has(modifier))) { + // does not have the required modifiers + continue; + } + if (!isCorrectType(node, config, context, selectorType)) { + // is not the correct type + continue; + } + let name = originalName; + name = validateUnderscore('leading', config, name, node, originalName); + if (name == null) { + // fail + return; + } + name = validateUnderscore('trailing', config, name, node, originalName); + if (name == null) { + // fail + return; + } + name = validateAffix('prefix', config, name, node, originalName); + if (name == null) { + // fail + return; + } + name = validateAffix('suffix', config, name, node, originalName); + if (name == null) { + // fail + return; + } + if (!validateCustom(config, name, node, originalName)) { + // fail + return; + } + if (!validatePredefinedFormat(config, name, node, originalName, modifiers)) { + // fail + return; + } + // it's valid for this config, so we don't need to check any more configs + return; + } + }; + // centralizes the logic for formatting the report data + function formatReportData({ affixes, count, custom, formats, originalName, position, processedName, }) { + return { + affixes: affixes?.join(', '), + count, + formats: formats?.map(f => enums_1.PredefinedFormats[f]).join(', '), + name: originalName, + position, + processedName, + regex: custom?.regex.toString(), + regexMatch: custom?.match === true + ? 'match' + : custom?.match === false + ? 'not match' + : null, + type: (0, shared_1.selectorTypeToMessageString)(type), + }; + } + /** + * @returns the name with the underscore removed, if it is valid according to the specified underscore option, null otherwise + */ + function validateUnderscore(position, config, name, node, originalName) { + const option = position === 'leading' + ? config.leadingUnderscore + : config.trailingUnderscore; + if (!option) { + return name; + } + const hasSingleUnderscore = position === 'leading' + ? () => name.startsWith('_') + : () => name.endsWith('_'); + const trimSingleUnderscore = position === 'leading' + ? () => name.slice(1) + : () => name.slice(0, -1); + const hasDoubleUnderscore = position === 'leading' + ? () => name.startsWith('__') + : () => name.endsWith('__'); + const trimDoubleUnderscore = position === 'leading' + ? () => name.slice(2) + : () => name.slice(0, -2); + switch (option) { + // ALLOW - no conditions as the user doesn't care if it's there or not + case enums_1.UnderscoreOptions.allow: { + if (hasSingleUnderscore()) { + return trimSingleUnderscore(); + } + return name; + } + case enums_1.UnderscoreOptions.allowDouble: { + if (hasDoubleUnderscore()) { + return trimDoubleUnderscore(); + } + return name; + } + case enums_1.UnderscoreOptions.allowSingleOrDouble: { + if (hasDoubleUnderscore()) { + return trimDoubleUnderscore(); + } + if (hasSingleUnderscore()) { + return trimSingleUnderscore(); + } + return name; + } + // FORBID + case enums_1.UnderscoreOptions.forbid: { + if (hasSingleUnderscore()) { + context.report({ + data: formatReportData({ + count: 'one', + originalName, + position, + }), + messageId: 'unexpectedUnderscore', + node, + }); + return null; + } + return name; + } + // REQUIRE + case enums_1.UnderscoreOptions.require: { + if (!hasSingleUnderscore()) { + context.report({ + data: formatReportData({ + count: 'one', + originalName, + position, + }), + messageId: 'missingUnderscore', + node, + }); + return null; + } + return trimSingleUnderscore(); + } + case enums_1.UnderscoreOptions.requireDouble: { + if (!hasDoubleUnderscore()) { + context.report({ + data: formatReportData({ + count: 'two', + originalName, + position, + }), + messageId: 'missingUnderscore', + node, + }); + return null; + } + return trimDoubleUnderscore(); + } + } + } + /** + * @returns the name with the affix removed, if it is valid according to the specified affix option, null otherwise + */ + function validateAffix(position, config, name, node, originalName) { + const affixes = config[position]; + if (!affixes || affixes.length === 0) { + return name; + } + for (const affix of affixes) { + const hasAffix = position === 'prefix' ? name.startsWith(affix) : name.endsWith(affix); + const trimAffix = position === 'prefix' + ? () => name.slice(affix.length) + : () => name.slice(0, -affix.length); + if (hasAffix) { + // matches, so trim it and return + return trimAffix(); + } + } + context.report({ + data: formatReportData({ + affixes, + originalName, + position, + }), + messageId: 'missingAffix', + node, + }); + return null; + } + /** + * @returns true if the name is valid according to the `regex` option, false otherwise + */ + function validateCustom(config, name, node, originalName) { + const custom = config.custom; + if (!custom) { + return true; + } + const result = custom.regex.test(name); + if (custom.match && result) { + return true; + } + if (!custom.match && !result) { + return true; + } + context.report({ + data: formatReportData({ + custom, + originalName, + }), + messageId: 'satisfyCustom', + node, + }); + return false; + } + /** + * @returns true if the name is valid according to the `format` option, false otherwise + */ + function validatePredefinedFormat(config, name, node, originalName, modifiers) { + const formats = config.format; + if (!formats?.length) { + return true; + } + if (!modifiers.has(enums_1.Modifiers.requiresQuotes)) { + for (const format of formats) { + const checker = format_1.PredefinedFormatToCheckFunction[format]; + if (checker(name)) { + return true; + } + } + } + context.report({ + data: formatReportData({ + formats, + originalName, + processedName: name, + }), + messageId: originalName === name + ? 'doesNotMatchFormat' + : 'doesNotMatchFormatTrimmed', + node, + }); + return false; + } +} +const SelectorsAllowedToHaveTypes = enums_1.Selectors.variable | + enums_1.Selectors.parameter | + enums_1.Selectors.classProperty | + enums_1.Selectors.objectLiteralProperty | + enums_1.Selectors.typeProperty | + enums_1.Selectors.parameterProperty | + enums_1.Selectors.classicAccessor; +function isCorrectType(node, config, context, selector) { + if (config.types == null) { + return true; + } + if ((SelectorsAllowedToHaveTypes & selector) === 0) { + return true; + } + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const type = services + .getTypeAtLocation(node) + // remove null and undefined from the type, as we don't care about it here + .getNonNullableType(); + for (const allowedType of config.types) { + switch (allowedType) { + case enums_1.TypeModifiers.array: + if (isAllTypesMatch(type, t => checker.isArrayType(t) || checker.isTupleType(t))) { + return true; + } + break; + case enums_1.TypeModifiers.function: + if (isAllTypesMatch(type, t => t.getCallSignatures().length > 0)) { + return true; + } + break; + case enums_1.TypeModifiers.boolean: + case enums_1.TypeModifiers.number: + case enums_1.TypeModifiers.string: { + const typeString = checker.typeToString( + // this will resolve things like true => boolean, 'a' => string and 1 => number + checker.getWidenedType(checker.getBaseTypeOfLiteralType(type))); + const allowedTypeString = enums_1.TypeModifiers[allowedType]; + if (typeString === allowedTypeString) { + return true; + } + break; + } + } + } + return false; +} +/** + * @returns `true` if the type (or all union types) in the given type return true for the callback + */ +function isAllTypesMatch(type, cb) { + if (type.isUnion()) { + return type.types.every(t => cb(t)); + } + return cb(type); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention.d.ts new file mode 100644 index 00000000..26d98ddf --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention.d.ts @@ -0,0 +1,7 @@ +import { TSESLint } from '@typescript-eslint/utils'; +import type { Selector } from './naming-convention-utils'; +export type MessageIds = 'doesNotMatchFormat' | 'doesNotMatchFormatTrimmed' | 'missingAffix' | 'missingUnderscore' | 'satisfyCustom' | 'unexpectedUnderscore'; +export type Options = Selector[]; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=naming-convention.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention.d.ts.map new file mode 100644 index 00000000..868be6b6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"naming-convention.d.ts","sourceRoot":"","sources":["../../src/rules/naming-convention.ts"],"names":[],"mappings":"AAOA,OAAO,EAAkB,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEpE,OAAO,KAAK,EAEV,QAAQ,EAET,MAAM,2BAA2B,CAAC;AAUnC,MAAM,MAAM,UAAU,GAClB,oBAAoB,GACpB,2BAA2B,GAC3B,cAAc,GACd,mBAAmB,GACnB,eAAe,GACf,sBAAsB,CAAC;AAK3B,MAAM,MAAM,OAAO,GAAG,QAAQ,EAAE,CAAC;;AA8BjC,wBAspBG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention.js new file mode 100644 index 00000000..c7b14c95 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/naming-convention.js @@ -0,0 +1,504 @@ +"use strict"; +// This rule was feature-frozen before we enabled no-property-in-node. +/* eslint-disable eslint-plugin/no-property-in-node */ +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const naming_convention_utils_1 = require("./naming-convention-utils"); +// This essentially mirrors ESLint's `camelcase` rule +// note that that rule ignores leading and trailing underscores and only checks those in the middle of a variable name +const defaultCamelCaseAllTheThingsConfig = [ + { + format: ['camelCase'], + leadingUnderscore: 'allow', + selector: 'default', + trailingUnderscore: 'allow', + }, + { + format: ['camelCase', 'PascalCase'], + selector: 'import', + }, + { + format: ['camelCase', 'UPPER_CASE'], + leadingUnderscore: 'allow', + selector: 'variable', + trailingUnderscore: 'allow', + }, + { + format: ['PascalCase'], + selector: 'typeLike', + }, +]; +exports.default = (0, util_1.createRule)({ + name: 'naming-convention', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce naming conventions for everything across a codebase', + // technically only requires type checking if the user uses "type" modifiers + requiresTypeChecking: true, + }, + messages: { + doesNotMatchFormat: '{{type}} name `{{name}}` must match one of the following formats: {{formats}}', + doesNotMatchFormatTrimmed: '{{type}} name `{{name}}` trimmed as `{{processedName}}` must match one of the following formats: {{formats}}', + missingAffix: '{{type}} name `{{name}}` must have one of the following {{position}}es: {{affixes}}', + missingUnderscore: '{{type}} name `{{name}}` must have {{count}} {{position}} underscore(s).', + satisfyCustom: '{{type}} name `{{name}}` must {{regexMatch}} the RegExp: {{regex}}', + unexpectedUnderscore: '{{type}} name `{{name}}` must not have a {{position}} underscore.', + }, + schema: naming_convention_utils_1.SCHEMA, + }, + defaultOptions: defaultCamelCaseAllTheThingsConfig, + create(contextWithoutDefaults) { + const context = contextWithoutDefaults.options.length > 0 + ? contextWithoutDefaults + : // only apply the defaults when the user provides no config + Object.setPrototypeOf({ + options: defaultCamelCaseAllTheThingsConfig, + }, contextWithoutDefaults); + const validators = (0, naming_convention_utils_1.parseOptions)(context); + const compilerOptions = (0, util_1.getParserServices)(context, true).program?.getCompilerOptions() ?? {}; + function handleMember(validator, node, modifiers) { + const key = node.key; + if (requiresQuoting(key, compilerOptions.target)) { + modifiers.add(naming_convention_utils_1.Modifiers.requiresQuotes); + } + validator(key, modifiers); + } + function getMemberModifiers(node) { + const modifiers = new Set(); + if ('key' in node && node.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) { + modifiers.add(naming_convention_utils_1.Modifiers['#private']); + } + else if (node.accessibility) { + modifiers.add(naming_convention_utils_1.Modifiers[node.accessibility]); + } + else { + modifiers.add(naming_convention_utils_1.Modifiers.public); + } + if (node.static) { + modifiers.add(naming_convention_utils_1.Modifiers.static); + } + if ('readonly' in node && node.readonly) { + modifiers.add(naming_convention_utils_1.Modifiers.readonly); + } + if ('override' in node && node.override) { + modifiers.add(naming_convention_utils_1.Modifiers.override); + } + if (node.type === utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition || + node.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition || + node.type === utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty) { + modifiers.add(naming_convention_utils_1.Modifiers.abstract); + } + return modifiers; + } + const { unusedVariables } = (0, util_1.collectVariables)(context); + function isUnused(name, initialScope) { + let variable = null; + let scope = initialScope; + while (scope) { + variable = scope.set.get(name) ?? null; + if (variable) { + break; + } + scope = scope.upper; + } + if (!variable) { + return false; + } + return unusedVariables.has(variable); + } + function isDestructured(id) { + return ( + // `const { x }` + // does not match `const { x: y }` + (id.parent.type === utils_1.AST_NODE_TYPES.Property && id.parent.shorthand) || + // `const { x = 2 }` + // does not match const `{ x: y = 2 }` + (id.parent.type === utils_1.AST_NODE_TYPES.AssignmentPattern && + id.parent.parent.type === utils_1.AST_NODE_TYPES.Property && + id.parent.parent.shorthand)); + } + function isAsyncMemberOrProperty(propertyOrMemberNode) { + return Boolean('value' in propertyOrMemberNode && + propertyOrMemberNode.value && + 'async' in propertyOrMemberNode.value && + propertyOrMemberNode.value.async); + } + function isAsyncVariableIdentifier(id) { + return Boolean(('async' in id.parent && id.parent.async) || + ('init' in id.parent && + id.parent.init && + 'async' in id.parent.init && + id.parent.init.async)); + } + const selectors = { + // #region import + 'FunctionDeclaration, TSDeclareFunction, FunctionExpression': { + handler: (node, validator) => { + if (node.id == null) { + return; + } + const modifiers = new Set(); + // functions create their own nested scope + const scope = context.sourceCode.getScope(node).upper; + if (isGlobal(scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.global); + } + if (isExported(node, node.id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.exported); + } + if (isUnused(node.id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.unused); + } + if (node.async) { + modifiers.add(naming_convention_utils_1.Modifiers.async); + } + validator(node.id, modifiers); + }, + validator: validators.function, + }, + // #endregion + // #region variable + 'ImportDefaultSpecifier, ImportNamespaceSpecifier, ImportSpecifier': { + handler: (node, validator) => { + const modifiers = new Set(); + switch (node.type) { + case utils_1.AST_NODE_TYPES.ImportDefaultSpecifier: + modifiers.add(naming_convention_utils_1.Modifiers.default); + break; + case utils_1.AST_NODE_TYPES.ImportNamespaceSpecifier: + modifiers.add(naming_convention_utils_1.Modifiers.namespace); + break; + case utils_1.AST_NODE_TYPES.ImportSpecifier: + // Handle `import { default as Foo }` + if (node.imported.type === utils_1.AST_NODE_TYPES.Identifier && + node.imported.name !== 'default') { + return; + } + modifiers.add(naming_convention_utils_1.Modifiers.default); + break; + } + validator(node.local, modifiers); + }, + validator: validators.import, + }, + // #endregion + // #region function + VariableDeclarator: { + handler: (node, validator) => { + const identifiers = getIdentifiersFromPattern(node.id); + const baseModifiers = new Set(); + const parent = node.parent; + if (parent.kind === 'const') { + baseModifiers.add(naming_convention_utils_1.Modifiers.const); + } + if (isGlobal(context.sourceCode.getScope(node))) { + baseModifiers.add(naming_convention_utils_1.Modifiers.global); + } + identifiers.forEach(id => { + const modifiers = new Set(baseModifiers); + if (isDestructured(id)) { + modifiers.add(naming_convention_utils_1.Modifiers.destructured); + } + const scope = context.sourceCode.getScope(id); + if (isExported(parent, id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.exported); + } + if (isUnused(id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.unused); + } + if (isAsyncVariableIdentifier(id)) { + modifiers.add(naming_convention_utils_1.Modifiers.async); + } + validator(id, modifiers); + }); + }, + validator: validators.variable, + }, + // #endregion function + // #region parameter + ':matches(PropertyDefinition, TSAbstractPropertyDefinition)[computed = false][value.type != "ArrowFunctionExpression"][value.type != "FunctionExpression"][value.type != "TSEmptyBodyFunctionExpression"]': { + handler: (node, validator) => { + const modifiers = getMemberModifiers(node); + handleMember(validator, node, modifiers); + }, + validator: validators.classProperty, + }, + // #endregion parameter + // #region parameterProperty + ':not(ObjectPattern) > Property[computed = false][kind = "init"][value.type != "ArrowFunctionExpression"][value.type != "FunctionExpression"][value.type != "TSEmptyBodyFunctionExpression"]': { + handler: (node, validator) => { + const modifiers = new Set([naming_convention_utils_1.Modifiers.public]); + handleMember(validator, node, modifiers); + }, + validator: validators.objectLiteralProperty, + }, + // #endregion parameterProperty + // #region property + [[ + ':matches(PropertyDefinition, TSAbstractPropertyDefinition)[computed = false][value.type = "ArrowFunctionExpression"]', + ':matches(PropertyDefinition, TSAbstractPropertyDefinition)[computed = false][value.type = "FunctionExpression"]', + ':matches(PropertyDefinition, TSAbstractPropertyDefinition)[computed = false][value.type = "TSEmptyBodyFunctionExpression"]', + ':matches(MethodDefinition, TSAbstractMethodDefinition)[computed = false][kind = "method"]', + ].join(', ')]: { + handler: (node, validator) => { + const modifiers = getMemberModifiers(node); + if (isAsyncMemberOrProperty(node)) { + modifiers.add(naming_convention_utils_1.Modifiers.async); + } + handleMember(validator, node, modifiers); + }, + validator: validators.classMethod, + }, + [[ + 'MethodDefinition[computed = false]:matches([kind = "get"], [kind = "set"])', + 'TSAbstractMethodDefinition[computed = false]:matches([kind="get"], [kind="set"])', + ].join(', ')]: { + handler: (node, validator) => { + const modifiers = getMemberModifiers(node); + handleMember(validator, node, modifiers); + }, + validator: validators.classicAccessor, + }, + [[ + 'Property[computed = false][kind = "init"][value.type = "ArrowFunctionExpression"]', + 'Property[computed = false][kind = "init"][value.type = "FunctionExpression"]', + 'Property[computed = false][kind = "init"][value.type = "TSEmptyBodyFunctionExpression"]', + ].join(', ')]: { + handler: (node, validator) => { + const modifiers = new Set([naming_convention_utils_1.Modifiers.public]); + if (isAsyncMemberOrProperty(node)) { + modifiers.add(naming_convention_utils_1.Modifiers.async); + } + handleMember(validator, node, modifiers); + }, + validator: validators.objectLiteralMethod, + }, + // #endregion property + // #region method + [[ + 'TSMethodSignature[computed = false]', + 'TSPropertySignature[computed = false][typeAnnotation.typeAnnotation.type = "TSFunctionType"]', + ].join(', ')]: { + handler: (node, validator) => { + const modifiers = new Set([naming_convention_utils_1.Modifiers.public]); + handleMember(validator, node, modifiers); + }, + validator: validators.typeMethod, + }, + [[ + utils_1.AST_NODE_TYPES.AccessorProperty, + utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty, + ].join(', ')]: { + handler: (node, validator) => { + const modifiers = getMemberModifiers(node); + handleMember(validator, node, modifiers); + }, + validator: validators.autoAccessor, + }, + 'FunctionDeclaration, TSDeclareFunction, TSEmptyBodyFunctionExpression, FunctionExpression, ArrowFunctionExpression': { + handler: (node, validator) => { + node.params.forEach(param => { + if (param.type === utils_1.AST_NODE_TYPES.TSParameterProperty) { + return; + } + const identifiers = getIdentifiersFromPattern(param); + identifiers.forEach(i => { + const modifiers = new Set(); + if (isDestructured(i)) { + modifiers.add(naming_convention_utils_1.Modifiers.destructured); + } + if (isUnused(i.name, context.sourceCode.getScope(i))) { + modifiers.add(naming_convention_utils_1.Modifiers.unused); + } + validator(i, modifiers); + }); + }); + }, + validator: validators.parameter, + }, + // #endregion method + // #region accessor + 'Property[computed = false]:matches([kind = "get"], [kind = "set"])': { + handler: (node, validator) => { + const modifiers = new Set([naming_convention_utils_1.Modifiers.public]); + handleMember(validator, node, modifiers); + }, + validator: validators.classicAccessor, + }, + TSParameterProperty: { + handler: (node, validator) => { + const modifiers = getMemberModifiers(node); + const identifiers = getIdentifiersFromPattern(node.parameter); + identifiers.forEach(i => { + validator(i, modifiers); + }); + }, + validator: validators.parameterProperty, + }, + // #endregion accessor + // #region autoAccessor + 'TSPropertySignature[computed = false][typeAnnotation.typeAnnotation.type != "TSFunctionType"]': { + handler: (node, validator) => { + const modifiers = new Set([naming_convention_utils_1.Modifiers.public]); + if (node.readonly) { + modifiers.add(naming_convention_utils_1.Modifiers.readonly); + } + handleMember(validator, node, modifiers); + }, + validator: validators.typeProperty, + }, + // #endregion autoAccessor + // #region enumMember + // computed is optional, so can't do [computed = false] + 'ClassDeclaration, ClassExpression': { + handler: (node, validator) => { + const id = node.id; + if (id == null) { + return; + } + const modifiers = new Set(); + // classes create their own nested scope + const scope = context.sourceCode.getScope(node).upper; + if (node.abstract) { + modifiers.add(naming_convention_utils_1.Modifiers.abstract); + } + if (isExported(node, id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.exported); + } + if (isUnused(id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.unused); + } + validator(id, modifiers); + }, + validator: validators.class, + }, + // #endregion enumMember + // #region class + TSEnumDeclaration: { + handler: (node, validator) => { + const modifiers = new Set(); + // enums create their own nested scope + const scope = context.sourceCode.getScope(node).upper; + if (isExported(node, node.id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.exported); + } + if (isUnused(node.id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.unused); + } + validator(node.id, modifiers); + }, + validator: validators.enum, + }, + // #endregion class + // #region interface + 'TSEnumMember[computed != true]': { + handler: (node, validator) => { + const id = node.id; + const modifiers = new Set(); + if (requiresQuoting(id, compilerOptions.target)) { + modifiers.add(naming_convention_utils_1.Modifiers.requiresQuotes); + } + validator(id, modifiers); + }, + validator: validators.enumMember, + }, + // #endregion interface + // #region typeAlias + TSInterfaceDeclaration: { + handler: (node, validator) => { + const modifiers = new Set(); + const scope = context.sourceCode.getScope(node); + if (isExported(node, node.id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.exported); + } + if (isUnused(node.id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.unused); + } + validator(node.id, modifiers); + }, + validator: validators.interface, + }, + // #endregion typeAlias + // #region enum + TSTypeAliasDeclaration: { + handler: (node, validator) => { + const modifiers = new Set(); + const scope = context.sourceCode.getScope(node); + if (isExported(node, node.id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.exported); + } + if (isUnused(node.id.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.unused); + } + validator(node.id, modifiers); + }, + validator: validators.typeAlias, + }, + // #endregion enum + // #region typeParameter + 'TSTypeParameterDeclaration > TSTypeParameter': { + handler: (node, validator) => { + const modifiers = new Set(); + const scope = context.sourceCode.getScope(node); + if (isUnused(node.name.name, scope)) { + modifiers.add(naming_convention_utils_1.Modifiers.unused); + } + validator(node.name, modifiers); + }, + validator: validators.typeParameter, + }, + // #endregion typeParameter + }; + return Object.fromEntries(Object.entries(selectors).map(([selector, { handler, validator }]) => { + return [ + selector, + (node) => { + handler(node, validator); + }, + ]; + })); + }, +}); +function getIdentifiersFromPattern(pattern) { + const identifiers = []; + const visitor = new scope_manager_1.PatternVisitor({}, pattern, id => identifiers.push(id)); + visitor.visit(pattern); + return identifiers; +} +function isExported(node, name, scope) { + if (node?.parent?.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration || + node?.parent?.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration) { + return true; + } + if (scope == null) { + return false; + } + const variable = scope.set.get(name); + if (variable) { + for (const ref of variable.references) { + const refParent = ref.identifier.parent; + if (refParent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration || + refParent.type === utils_1.AST_NODE_TYPES.ExportSpecifier) { + return true; + } + } + } + return false; +} +function isGlobal(scope) { + if (scope == null) { + return false; + } + return (scope.type === utils_1.TSESLint.Scope.ScopeType.global || + scope.type === utils_1.TSESLint.Scope.ScopeType.module); +} +function requiresQuoting(node, target) { + const name = node.type === utils_1.AST_NODE_TYPES.Identifier || + node.type === utils_1.AST_NODE_TYPES.PrivateIdentifier + ? node.name + : `${node.value}`; + return (0, util_1.requiresQuoting)(name, target); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-constructor.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-constructor.d.ts new file mode 100644 index 00000000..3d107296 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-constructor.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"useLiteral", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-array-constructor.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-constructor.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-constructor.d.ts.map new file mode 100644 index 00000000..b4536d71 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-constructor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-array-constructor.d.ts","sourceRoot":"","sources":["../../src/rules/no-array-constructor.ts"],"names":[],"mappings":";AAUA,wBAsEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-constructor.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-constructor.js new file mode 100644 index 00000000..2db78538 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-constructor.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const ast_utils_1 = require("@typescript-eslint/utils/ast-utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-array-constructor', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow generic `Array` constructors', + extendsBaseRule: true, + recommended: 'recommended', + }, + fixable: 'code', + messages: { + useLiteral: 'The array literal notation [] is preferable.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const sourceCode = context.sourceCode; + function getArgumentsText(node) { + const lastToken = sourceCode.getLastToken(node); + if (lastToken == null || !(0, ast_utils_1.isClosingParenToken)(lastToken)) { + return ''; + } + let firstToken = node.callee; + do { + firstToken = sourceCode.getTokenAfter(firstToken); + if (!firstToken || firstToken === lastToken) { + return ''; + } + } while (!(0, ast_utils_1.isOpeningParenToken)(firstToken)); + return sourceCode.text.slice(firstToken.range[1], lastToken.range[0]); + } + /** + * Disallow construction of dense arrays using the Array constructor + * @param node node to evaluate + */ + function check(node) { + if (node.arguments.length !== 1 && + node.callee.type === utils_1.AST_NODE_TYPES.Identifier && + node.callee.name === 'Array' && + !node.typeArguments) { + context.report({ + node, + messageId: 'useLiteral', + fix(fixer) { + const argsText = getArgumentsText(node); + return fixer.replaceText(node, `[${argsText}]`); + }, + }); + } + } + return { + CallExpression: check, + NewExpression: check, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-delete.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-delete.d.ts new file mode 100644 index 00000000..c3d3c804 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-delete.d.ts @@ -0,0 +1,5 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageId = 'noArrayDelete' | 'useSplice'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-array-delete.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-delete.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-delete.d.ts.map new file mode 100644 index 00000000..bfbd39ab --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-delete.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-array-delete.d.ts","sourceRoot":"","sources":["../../src/rules/no-array-delete.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAWnE,MAAM,MAAM,SAAS,GAAG,eAAe,GAAG,WAAW,CAAC;;AAEtD,wBAiGG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-delete.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-delete.js new file mode 100644 index 00000000..cff2cdba --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-array-delete.js @@ -0,0 +1,80 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-array-delete', + meta: { + type: 'problem', + docs: { + description: 'Disallow using the `delete` operator on array values', + recommended: 'recommended', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + noArrayDelete: 'Using the `delete` operator with an array expression is unsafe.', + useSplice: 'Use `array.splice()` instead.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function isUnderlyingTypeArray(type) { + const predicate = (t) => checker.isArrayType(t) || checker.isTupleType(t); + if (type.isUnion()) { + return type.types.every(predicate); + } + if (type.isIntersection()) { + return type.types.some(predicate); + } + return predicate(type); + } + return { + 'UnaryExpression[operator="delete"]'(node) { + const { argument } = node; + if (argument.type !== utils_1.AST_NODE_TYPES.MemberExpression) { + return; + } + const type = (0, util_1.getConstrainedTypeAtLocation)(services, argument.object); + if (!isUnderlyingTypeArray(type)) { + return; + } + context.report({ + node, + messageId: 'noArrayDelete', + suggest: [ + { + messageId: 'useSplice', + fix(fixer) { + const { object, property } = argument; + const shouldHaveParentheses = property.type === utils_1.AST_NODE_TYPES.SequenceExpression; + const nodeMap = services.esTreeNodeToTSNodeMap; + const target = nodeMap.get(object).getText(); + const rawKey = nodeMap.get(property).getText(); + const key = shouldHaveParentheses ? `(${rawKey})` : rawKey; + let suggestion = `${target}.splice(${key}, 1)`; + const comments = context.sourceCode.getCommentsInside(node); + if (comments.length > 0) { + const indentationCount = node.loc.start.column; + const indentation = ' '.repeat(indentationCount); + const commentsText = comments + .map(comment => { + return comment.type === utils_1.AST_TOKEN_TYPES.Line + ? `//${comment.value}` + : `/*${comment.value}*/`; + }) + .join(`\n${indentation}`); + suggestion = `${commentsText}\n${indentation}${suggestion}`; + } + return fixer.replaceText(node, suggestion); + }, + }, + ], + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-base-to-string.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-base-to-string.d.ts new file mode 100644 index 00000000..1b09044f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-base-to-string.d.ts @@ -0,0 +1,9 @@ +export type Options = [ + { + ignoredTypeNames?: string[]; + } +]; +export type MessageIds = 'baseArrayJoin' | 'baseToString'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-base-to-string.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-base-to-string.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-base-to-string.d.ts.map new file mode 100644 index 00000000..3abddfbf --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-base-to-string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-base-to-string.d.ts","sourceRoot":"","sources":["../../src/rules/no-base-to-string.ts"],"names":[],"mappings":"AAoBA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;KAC7B;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,eAAe,GAAG,cAAc,CAAC;;AAE1D,wBAwTG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-base-to-string.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-base-to-string.js new file mode 100644 index 00000000..4e80892a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-base-to-string.js @@ -0,0 +1,266 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +var Usefulness; +(function (Usefulness) { + Usefulness["Always"] = "always"; + Usefulness["Never"] = "will"; + Usefulness["Sometimes"] = "may"; +})(Usefulness || (Usefulness = {})); +exports.default = (0, util_1.createRule)({ + name: 'no-base-to-string', + meta: { + type: 'suggestion', + docs: { + description: 'Require `.toString()` and `.toLocaleString()` to only be called on objects which provide useful information when stringified', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + baseArrayJoin: "Using `join()` for {{name}} {{certainty}} use Object's default stringification format ('[object Object]') when stringified.", + baseToString: "'{{name}}' {{certainty}} use Object's default stringification format ('[object Object]') when stringified.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + ignoredTypeNames: { + type: 'array', + description: 'Stringified regular expressions of type names to ignore.', + items: { + type: 'string', + }, + }, + }, + }, + ], + }, + defaultOptions: [ + { + ignoredTypeNames: ['Error', 'RegExp', 'URL', 'URLSearchParams'], + }, + ], + create(context, [option]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const ignoredTypeNames = option.ignoredTypeNames ?? []; + function checkExpression(node, type) { + if (node.type === utils_1.AST_NODE_TYPES.Literal) { + return; + } + const certainty = collectToStringCertainty(type ?? services.getTypeAtLocation(node), new Set()); + if (certainty === Usefulness.Always) { + return; + } + context.report({ + node, + messageId: 'baseToString', + data: { + name: context.sourceCode.getText(node), + certainty, + }, + }); + } + function checkExpressionForArrayJoin(node, type) { + const certainty = collectJoinCertainty(type, new Set()); + if (certainty === Usefulness.Always) { + return; + } + context.report({ + node, + messageId: 'baseArrayJoin', + data: { + name: context.sourceCode.getText(node), + certainty, + }, + }); + } + function collectUnionTypeCertainty(type, collectSubTypeCertainty) { + const certainties = type.types.map(t => collectSubTypeCertainty(t)); + if (certainties.every(certainty => certainty === Usefulness.Never)) { + return Usefulness.Never; + } + if (certainties.every(certainty => certainty === Usefulness.Always)) { + return Usefulness.Always; + } + return Usefulness.Sometimes; + } + function collectIntersectionTypeCertainty(type, collectSubTypeCertainty) { + for (const subType of type.types) { + const subtypeUsefulness = collectSubTypeCertainty(subType); + if (subtypeUsefulness === Usefulness.Always) { + return Usefulness.Always; + } + } + return Usefulness.Never; + } + function collectTupleCertainty(type, visited) { + const typeArgs = checker.getTypeArguments(type); + const certainties = typeArgs.map(t => collectToStringCertainty(t, visited)); + if (certainties.some(certainty => certainty === Usefulness.Never)) { + return Usefulness.Never; + } + if (certainties.some(certainty => certainty === Usefulness.Sometimes)) { + return Usefulness.Sometimes; + } + return Usefulness.Always; + } + function collectArrayCertainty(type, visited) { + const elemType = (0, util_1.nullThrows)(type.getNumberIndexType(), 'array should have number index type'); + return collectToStringCertainty(elemType, visited); + } + function collectJoinCertainty(type, visited) { + if (tsutils.isUnionType(type)) { + return collectUnionTypeCertainty(type, t => collectJoinCertainty(t, visited)); + } + if (tsutils.isIntersectionType(type)) { + return collectIntersectionTypeCertainty(type, t => collectJoinCertainty(t, visited)); + } + if (checker.isTupleType(type)) { + return collectTupleCertainty(type, visited); + } + if (checker.isArrayType(type)) { + return collectArrayCertainty(type, visited); + } + return Usefulness.Always; + } + function collectToStringCertainty(type, visited) { + if (visited.has(type)) { + // don't report if this is a self referencing array or tuple type + return Usefulness.Always; + } + if (tsutils.isTypeParameter(type)) { + const constraint = type.getConstraint(); + if (constraint) { + return collectToStringCertainty(constraint, visited); + } + // unconstrained generic means `unknown` + return Usefulness.Always; + } + // the Boolean type definition missing toString() + if (type.flags & ts.TypeFlags.Boolean || + type.flags & ts.TypeFlags.BooleanLiteral) { + return Usefulness.Always; + } + if (ignoredTypeNames.includes((0, util_1.getTypeName)(checker, type))) { + return Usefulness.Always; + } + if (type.isIntersection()) { + return collectIntersectionTypeCertainty(type, t => collectToStringCertainty(t, visited)); + } + if (type.isUnion()) { + return collectUnionTypeCertainty(type, t => collectToStringCertainty(t, visited)); + } + if (checker.isTupleType(type)) { + return collectTupleCertainty(type, new Set([...visited, type])); + } + if (checker.isArrayType(type)) { + return collectArrayCertainty(type, new Set([...visited, type])); + } + const toString = checker.getPropertyOfType(type, 'toString') ?? + checker.getPropertyOfType(type, 'toLocaleString'); + if (!toString) { + // e.g. any/unknown + return Usefulness.Always; + } + const declarations = toString.getDeclarations(); + if (declarations == null || declarations.length !== 1) { + // If there are multiple declarations, at least one of them must not be + // the default object toString. + // + // This may only matter for older versions of TS + // see https://github.com/typescript-eslint/typescript-eslint/issues/8585 + return Usefulness.Always; + } + const declaration = declarations[0]; + const isBaseToString = ts.isInterfaceDeclaration(declaration.parent) && + declaration.parent.name.text === 'Object'; + return isBaseToString ? Usefulness.Never : Usefulness.Always; + } + function isBuiltInStringCall(node) { + if (node.callee.type === utils_1.AST_NODE_TYPES.Identifier && + // eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum + node.callee.name === 'String' && + node.arguments[0]) { + const scope = context.sourceCode.getScope(node); + // eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum + const variable = scope.set.get('String'); + return !variable?.defs.length; + } + return false; + } + return { + 'AssignmentExpression[operator = "+="], BinaryExpression[operator = "+"]'(node) { + const leftType = services.getTypeAtLocation(node.left); + const rightType = services.getTypeAtLocation(node.right); + if ((0, util_1.getTypeName)(checker, leftType) === 'string') { + checkExpression(node.right, rightType); + } + else if ((0, util_1.getTypeName)(checker, rightType) === 'string' && + node.left.type !== utils_1.AST_NODE_TYPES.PrivateIdentifier) { + checkExpression(node.left, leftType); + } + }, + CallExpression(node) { + if (isBuiltInStringCall(node) && + node.arguments[0].type !== utils_1.AST_NODE_TYPES.SpreadElement) { + checkExpression(node.arguments[0]); + } + }, + 'CallExpression > MemberExpression.callee > Identifier[name = "join"].property'(node) { + const memberExpr = node.parent; + const type = (0, util_1.getConstrainedTypeAtLocation)(services, memberExpr.object); + checkExpressionForArrayJoin(memberExpr.object, type); + }, + 'CallExpression > MemberExpression.callee > Identifier[name = /^(toLocaleString|toString)$/].property'(node) { + const memberExpr = node.parent; + checkExpression(memberExpr.object); + }, + TemplateLiteral(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression) { + return; + } + for (const expression of node.expressions) { + checkExpression(expression); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-non-null-assertion.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-non-null-assertion.d.ts new file mode 100644 index 00000000..b7428645 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-non-null-assertion.d.ts @@ -0,0 +1,5 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageId = 'confusingAssign' | 'confusingEqual' | 'confusingOperator' | 'notNeedInAssign' | 'notNeedInEqualTest' | 'notNeedInOperator' | 'wrapUpLeft'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-confusing-non-null-assertion.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-non-null-assertion.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-non-null-assertion.d.ts.map new file mode 100644 index 00000000..33422144 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-non-null-assertion.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-confusing-non-null-assertion.d.ts","sourceRoot":"","sources":["../../src/rules/no-confusing-non-null-assertion.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAUnE,MAAM,MAAM,SAAS,GACjB,iBAAiB,GACjB,gBAAgB,GAChB,mBAAmB,GACnB,iBAAiB,GACjB,oBAAoB,GACpB,mBAAmB,GACnB,YAAY,CAAC;;AAgBjB,wBA8IG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-non-null-assertion.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-non-null-assertion.js new file mode 100644 index 00000000..73319b9a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-non-null-assertion.js @@ -0,0 +1,142 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const confusingOperators = new Set([ + '=', + '==', + '===', + 'in', + 'instanceof', +]); +function isConfusingOperator(operator) { + return confusingOperators.has(operator); +} +exports.default = (0, util_1.createRule)({ + name: 'no-confusing-non-null-assertion', + meta: { + type: 'problem', + docs: { + description: 'Disallow non-null assertion in locations that may be confusing', + recommended: 'stylistic', + }, + hasSuggestions: true, + messages: { + confusingAssign: 'Confusing combination of non-null assertion and assignment like `a! = b`, which looks very similar to `a != b`.', + confusingEqual: 'Confusing combination of non-null assertion and equality test like `a! == b`, which looks very similar to `a !== b`.', + confusingOperator: 'Confusing combination of non-null assertion and `{{operator}}` operator like `a! {{operator}} b`, which might be misinterpreted as `!(a {{operator}} b)`.', + notNeedInAssign: 'Remove unnecessary non-null assertion (!) in assignment left-hand side.', + notNeedInEqualTest: 'Remove unnecessary non-null assertion (!) in equality test.', + notNeedInOperator: 'Remove possibly unnecessary non-null assertion (!) in the left operand of the `{{operator}}` operator.', + wrapUpLeft: 'Wrap the left-hand side in parentheses to avoid confusion with "{{operator}}" operator.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function confusingOperatorToMessageData(operator) { + switch (operator) { + case '=': + return { + messageId: 'confusingAssign', + }; + case '==': + case '===': + return { + messageId: 'confusingEqual', + }; + case 'in': + case 'instanceof': + return { + messageId: 'confusingOperator', + data: { operator }, + }; + // istanbul ignore next + default: + operator; + throw new Error(`Unexpected operator ${operator}`); + } + } + return { + 'BinaryExpression, AssignmentExpression'(node) { + const operator = node.operator; + if (isConfusingOperator(operator)) { + // Look for a non-null assertion as the last token on the left hand side. + // That way, we catch things like `1 + two! === 3`, even though the left + // hand side isn't a non-null assertion AST node. + const leftHandFinalToken = context.sourceCode.getLastToken(node.left); + const tokenAfterLeft = context.sourceCode.getTokenAfter(node.left); + if (leftHandFinalToken?.type === utils_1.AST_TOKEN_TYPES.Punctuator && + leftHandFinalToken.value === '!' && + tokenAfterLeft?.value !== ')') { + if (node.left.type === utils_1.AST_NODE_TYPES.TSNonNullExpression) { + let suggestions; + switch (operator) { + case '=': + suggestions = [ + { + messageId: 'notNeedInAssign', + fix: (fixer) => fixer.remove(leftHandFinalToken), + }, + ]; + break; + case '==': + case '===': + suggestions = [ + { + messageId: 'notNeedInEqualTest', + fix: (fixer) => fixer.remove(leftHandFinalToken), + }, + ]; + break; + case 'in': + case 'instanceof': + suggestions = [ + { + messageId: 'notNeedInOperator', + data: { operator }, + fix: (fixer) => fixer.remove(leftHandFinalToken), + }, + { + messageId: 'wrapUpLeft', + data: { operator }, + fix: wrapUpLeftFixer(node), + }, + ]; + break; + // istanbul ignore next + default: + operator; + return; + } + context.report({ + node, + ...confusingOperatorToMessageData(operator), + suggest: suggestions, + }); + } + else { + context.report({ + node, + ...confusingOperatorToMessageData(operator), + suggest: [ + { + messageId: 'wrapUpLeft', + data: { operator }, + fix: wrapUpLeftFixer(node), + }, + ], + }); + } + } + } + }, + }; + }, +}); +function wrapUpLeftFixer(node) { + return (fixer) => [ + fixer.insertTextBefore(node.left, '('), + fixer.insertTextAfter(node.left, ')'), + ]; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-void-expression.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-void-expression.d.ts new file mode 100644 index 00000000..f42d150e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-void-expression.d.ts @@ -0,0 +1,12 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = [ + { + ignoreArrowShorthand?: boolean; + ignoreVoidOperator?: boolean; + ignoreVoidReturningFunctions?: boolean; + } +]; +export type MessageId = 'invalidVoidExpr' | 'invalidVoidExprArrow' | 'invalidVoidExprArrowWrapVoid' | 'invalidVoidExprReturn' | 'invalidVoidExprReturnLast' | 'invalidVoidExprReturnWrapVoid' | 'invalidVoidExprWrapVoid' | 'voidExprWrapVoid'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-confusing-void-expression.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-void-expression.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-void-expression.d.ts.map new file mode 100644 index 00000000..54d6b2ca --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-void-expression.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-confusing-void-expression.d.ts","sourceRoot":"","sources":["../../src/rules/no-confusing-void-expression.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAoBnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,oBAAoB,CAAC,EAAE,OAAO,CAAC;QAC/B,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,4BAA4B,CAAC,EAAE,OAAO,CAAC;KACxC;CACF,CAAC;AAEF,MAAM,MAAM,SAAS,GACjB,iBAAiB,GACjB,sBAAsB,GACtB,8BAA8B,GAC9B,uBAAuB,GACvB,2BAA2B,GAC3B,+BAA+B,GAC/B,yBAAyB,GACzB,kBAAkB,CAAC;;AAEvB,wBAobG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-void-expression.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-void-expression.js new file mode 100644 index 00000000..4376150a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-confusing-void-expression.js @@ -0,0 +1,359 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const getParentFunctionNode_1 = require("../util/getParentFunctionNode"); +exports.default = (0, util_1.createRule)({ + name: 'no-confusing-void-expression', + meta: { + type: 'problem', + docs: { + description: 'Require expressions of type void to appear in statement position', + recommended: 'strict', + requiresTypeChecking: true, + }, + fixable: 'code', + hasSuggestions: true, + messages: { + invalidVoidExpr: 'Placing a void expression inside another expression is forbidden. ' + + 'Move it to its own statement instead.', + invalidVoidExprArrow: 'Returning a void expression from an arrow function shorthand is forbidden. ' + + 'Please add braces to the arrow function.', + invalidVoidExprArrowWrapVoid: 'Void expressions returned from an arrow function shorthand ' + + 'must be marked explicitly with the `void` operator.', + invalidVoidExprReturn: 'Returning a void expression from a function is forbidden. ' + + 'Please move it before the `return` statement.', + invalidVoidExprReturnLast: 'Returning a void expression from a function is forbidden. ' + + 'Please remove the `return` statement.', + invalidVoidExprReturnWrapVoid: 'Void expressions returned from a function ' + + 'must be marked explicitly with the `void` operator.', + invalidVoidExprWrapVoid: 'Void expressions used inside another expression ' + + 'must be moved to its own statement ' + + 'or marked explicitly with the `void` operator.', + voidExprWrapVoid: 'Mark with an explicit `void` operator.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + ignoreArrowShorthand: { + type: 'boolean', + description: 'Whether to ignore "shorthand" `() =>` arrow functions: those without `{ ... }` braces.', + }, + ignoreVoidOperator: { + type: 'boolean', + description: 'Whether to ignore returns that start with the `void` operator.', + }, + ignoreVoidReturningFunctions: { + type: 'boolean', + description: 'Whether to ignore returns from functions with explicit `void` return types and functions with contextual `void` return types.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + ignoreArrowShorthand: false, + ignoreVoidOperator: false, + ignoreVoidReturningFunctions: false, + }, + ], + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + return { + 'AwaitExpression, CallExpression, TaggedTemplateExpression'(node) { + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node); + if (!tsutils.isTypeFlagSet(type, ts.TypeFlags.VoidLike)) { + // not a void expression + return; + } + const invalidAncestor = findInvalidAncestor(node); + if (invalidAncestor == null) { + // void expression is in valid position + return; + } + const wrapVoidFix = (fixer) => { + const nodeText = context.sourceCode.getText(node); + const newNodeText = `void ${nodeText}`; + return fixer.replaceText(node, newNodeText); + }; + if (invalidAncestor.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression) { + // handle arrow function shorthand + if (options.ignoreVoidReturningFunctions) { + const returnsVoid = isVoidReturningFunctionNode(invalidAncestor); + if (returnsVoid) { + return; + } + } + if (options.ignoreVoidOperator) { + // handle wrapping with `void` + return context.report({ + node, + messageId: 'invalidVoidExprArrowWrapVoid', + fix: wrapVoidFix, + }); + } + // handle wrapping with braces + const arrowFunction = invalidAncestor; + return context.report({ + node, + messageId: 'invalidVoidExprArrow', + fix(fixer) { + if (!canFix(arrowFunction)) { + return null; + } + const arrowBody = arrowFunction.body; + const arrowBodyText = context.sourceCode.getText(arrowBody); + const newArrowBodyText = `{ ${arrowBodyText}; }`; + if ((0, util_1.isParenthesized)(arrowBody, context.sourceCode)) { + const bodyOpeningParen = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(arrowBody, util_1.isOpeningParenToken), util_1.NullThrowsReasons.MissingToken('opening parenthesis', 'arrow body')); + const bodyClosingParen = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(arrowBody, util_1.isClosingParenToken), util_1.NullThrowsReasons.MissingToken('closing parenthesis', 'arrow body')); + return fixer.replaceTextRange([bodyOpeningParen.range[0], bodyClosingParen.range[1]], newArrowBodyText); + } + return fixer.replaceText(arrowBody, newArrowBodyText); + }, + }); + } + if (invalidAncestor.type === utils_1.AST_NODE_TYPES.ReturnStatement) { + // handle return statement + if (options.ignoreVoidReturningFunctions) { + const functionNode = (0, getParentFunctionNode_1.getParentFunctionNode)(invalidAncestor); + if (functionNode) { + const returnsVoid = isVoidReturningFunctionNode(functionNode); + if (returnsVoid) { + return; + } + } + } + if (options.ignoreVoidOperator) { + // handle wrapping with `void` + return context.report({ + node, + messageId: 'invalidVoidExprReturnWrapVoid', + fix: wrapVoidFix, + }); + } + if (isFinalReturn(invalidAncestor)) { + // remove the `return` keyword + return context.report({ + node, + messageId: 'invalidVoidExprReturnLast', + fix(fixer) { + if (!canFix(invalidAncestor)) { + return null; + } + const returnValue = invalidAncestor.argument; + const returnValueText = context.sourceCode.getText(returnValue); + let newReturnStmtText = `${returnValueText};`; + if (isPreventingASI(returnValue)) { + // put a semicolon at the beginning of the line + newReturnStmtText = `;${newReturnStmtText}`; + } + return fixer.replaceText(invalidAncestor, newReturnStmtText); + }, + }); + } + // move before the `return` keyword + return context.report({ + node, + messageId: 'invalidVoidExprReturn', + fix(fixer) { + const returnValue = invalidAncestor.argument; + const returnValueText = context.sourceCode.getText(returnValue); + let newReturnStmtText = `${returnValueText}; return;`; + if (isPreventingASI(returnValue)) { + // put a semicolon at the beginning of the line + newReturnStmtText = `;${newReturnStmtText}`; + } + if (invalidAncestor.parent.type !== utils_1.AST_NODE_TYPES.BlockStatement) { + // e.g. `if (cond) return console.error();` + // add braces if not inside a block + newReturnStmtText = `{ ${newReturnStmtText} }`; + } + return fixer.replaceText(invalidAncestor, newReturnStmtText); + }, + }); + } + // handle generic case + if (options.ignoreVoidOperator) { + // this would be reported by this rule btw. such irony + return context.report({ + node, + messageId: 'invalidVoidExprWrapVoid', + suggest: [{ messageId: 'voidExprWrapVoid', fix: wrapVoidFix }], + }); + } + context.report({ + node, + messageId: 'invalidVoidExpr', + }); + }, + }; + /** + * Inspects the void expression's ancestors and finds closest invalid one. + * By default anything other than an ExpressionStatement is invalid. + * Parent expressions which can be used for their short-circuiting behavior + * are ignored and their parents are checked instead. + * @param node The void expression node to check. + * @returns Invalid ancestor node if it was found. `null` otherwise. + */ + function findInvalidAncestor(node) { + const parent = (0, util_1.nullThrows)(node.parent, util_1.NullThrowsReasons.MissingParent); + if (parent.type === utils_1.AST_NODE_TYPES.SequenceExpression && + node !== parent.expressions[parent.expressions.length - 1]) { + return null; + } + if (parent.type === utils_1.AST_NODE_TYPES.ExpressionStatement) { + // e.g. `{ console.log("foo"); }` + // this is always valid + return null; + } + if (parent.type === utils_1.AST_NODE_TYPES.LogicalExpression && + parent.right === node) { + // e.g. `x && console.log(x)` + // this is valid only if the next ancestor is valid + return findInvalidAncestor(parent); + } + if (parent.type === utils_1.AST_NODE_TYPES.ConditionalExpression && + (parent.consequent === node || parent.alternate === node)) { + // e.g. `cond ? console.log(true) : console.log(false)` + // this is valid only if the next ancestor is valid + return findInvalidAncestor(parent); + } + if (parent.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + // e.g. `() => console.log("foo")` + // this is valid with an appropriate option + options.ignoreArrowShorthand) { + return null; + } + if (parent.type === utils_1.AST_NODE_TYPES.UnaryExpression && + parent.operator === 'void' && + // e.g. `void console.log("foo")` + // this is valid with an appropriate option + options.ignoreVoidOperator) { + return null; + } + if (parent.type === utils_1.AST_NODE_TYPES.ChainExpression) { + // e.g. `console?.log('foo')` + return findInvalidAncestor(parent); + } + // Any other parent is invalid. + // We can assume a return statement will have an argument. + return parent; + } + /** Checks whether the return statement is the last statement in a function body. */ + function isFinalReturn(node) { + // the parent must be a block + const block = (0, util_1.nullThrows)(node.parent, util_1.NullThrowsReasons.MissingParent); + if (block.type !== utils_1.AST_NODE_TYPES.BlockStatement) { + // e.g. `if (cond) return;` (not in a block) + return false; + } + // the block's parent must be a function + const blockParent = (0, util_1.nullThrows)(block.parent, util_1.NullThrowsReasons.MissingParent); + if (![ + utils_1.AST_NODE_TYPES.ArrowFunctionExpression, + utils_1.AST_NODE_TYPES.FunctionDeclaration, + utils_1.AST_NODE_TYPES.FunctionExpression, + ].includes(blockParent.type)) { + // e.g. `if (cond) { return; }` + // not in a top-level function block + return false; + } + // must be the last child of the block + if (block.body.indexOf(node) < block.body.length - 1) { + // not the last statement in the block + return false; + } + return true; + } + /** + * Checks whether the given node, if placed on its own line, + * would prevent automatic semicolon insertion on the line before. + * + * This happens if the line begins with `(`, `[` or `` ` `` + */ + function isPreventingASI(node) { + const startToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node), util_1.NullThrowsReasons.MissingToken('first token', node.type)); + return ['(', '[', '`'].includes(startToken.value); + } + function canFix(node) { + const targetNode = node.type === utils_1.AST_NODE_TYPES.ReturnStatement + ? node.argument + : node.body; + const type = (0, util_1.getConstrainedTypeAtLocation)(services, targetNode); + return tsutils.isTypeFlagSet(type, ts.TypeFlags.VoidLike); + } + function isFunctionReturnTypeIncludesVoid(functionType) { + const callSignatures = tsutils.getCallSignaturesOfType(functionType); + return callSignatures.some(signature => { + const returnType = signature.getReturnType(); + return tsutils + .unionConstituents(returnType) + .some(tsutils.isIntrinsicVoidType); + }); + } + function isVoidReturningFunctionNode(functionNode) { + // Game plan: + // - If the function node has a type annotation, check if it includes `void`. + // - If it does then the function is safe to return `void` expressions in. + // - Otherwise, check if the function is a function-expression or an arrow-function. + // - If it is, get its contextual type and bail if we cannot. + // - Return based on whether the contextual type includes `void` or not + const functionTSNode = services.esTreeNodeToTSNodeMap.get(functionNode); + if (functionTSNode.type) { + const returnType = checker.getTypeFromTypeNode(functionTSNode.type); + return tsutils + .unionConstituents(returnType) + .some(tsutils.isIntrinsicVoidType); + } + if (ts.isExpression(functionTSNode)) { + const functionType = checker.getContextualType(functionTSNode); + if (functionType) { + return tsutils + .unionConstituents(functionType) + .some(isFunctionReturnTypeIncludesVoid); + } + } + return false; + } + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-deprecated.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-deprecated.d.ts new file mode 100644 index 00000000..1da7b62d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-deprecated.d.ts @@ -0,0 +1,10 @@ +import type { TypeOrValueSpecifier } from '../util'; +type MessageIds = 'deprecated' | 'deprecatedWithReason'; +type Options = [ + { + allow?: TypeOrValueSpecifier[]; + } +]; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-deprecated.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-deprecated.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-deprecated.d.ts.map new file mode 100644 index 00000000..b8a976ae --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-deprecated.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-deprecated.d.ts","sourceRoot":"","sources":["../../src/rules/no-deprecated.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAgBpD,KAAK,UAAU,GAAG,YAAY,GAAG,sBAAsB,CAAC;AAExD,KAAK,OAAO,GAAG;IACb;QACE,KAAK,CAAC,EAAE,oBAAoB,EAAE,CAAC;KAChC;CACF,CAAC;;AAEF,wBAmaG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-deprecated.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-deprecated.js new file mode 100644 index 00000000..80f8f645 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-deprecated.js @@ -0,0 +1,374 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-deprecated', + meta: { + type: 'problem', + docs: { + description: 'Disallow using code marked as `@deprecated`', + recommended: 'strict', + requiresTypeChecking: true, + }, + messages: { + deprecated: `\`{{name}}\` is deprecated.`, + deprecatedWithReason: `\`{{name}}\` is deprecated. {{reason}}`, + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allow: { + ...util_1.typeOrValueSpecifiersSchema, + description: 'Type specifiers that can be allowed.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allow: [], + }, + ], + create(context, [options]) { + const { jsDocParsingMode } = context.parserOptions; + const allow = options.allow; + if (jsDocParsingMode === 'none' || jsDocParsingMode === 'type-info') { + throw new Error(`Cannot be used with jsDocParsingMode: '${jsDocParsingMode}'.`); + } + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + // Deprecated jsdoc tags can be added on some symbol alias, e.g. + // + // export { /** @deprecated */ foo } + // + // When we import foo, its symbol is an alias of the exported foo (the one + // with the deprecated tag), which is itself an alias of the original foo. + // Therefore, we carefully go through the chain of aliases and check each + // immediate alias for deprecated tags + function searchForDeprecationInAliasesChain(symbol, checkDeprecationsOfAliasedSymbol) { + if (!symbol || !tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias)) { + return checkDeprecationsOfAliasedSymbol + ? getJsDocDeprecation(symbol) + : undefined; + } + const targetSymbol = checker.getAliasedSymbol(symbol); + while (tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias)) { + const reason = getJsDocDeprecation(symbol); + if (reason != null) { + return reason; + } + const immediateAliasedSymbol = symbol.getDeclarations() && checker.getImmediateAliasedSymbol(symbol); + if (!immediateAliasedSymbol) { + break; + } + symbol = immediateAliasedSymbol; + if (checkDeprecationsOfAliasedSymbol && symbol === targetSymbol) { + return getJsDocDeprecation(symbol); + } + } + return undefined; + } + function isDeclaration(node) { + const { parent } = node; + switch (parent.type) { + case utils_1.AST_NODE_TYPES.ArrayPattern: + return parent.elements.includes(node); + case utils_1.AST_NODE_TYPES.ClassExpression: + case utils_1.AST_NODE_TYPES.ClassDeclaration: + case utils_1.AST_NODE_TYPES.VariableDeclarator: + case utils_1.AST_NODE_TYPES.TSEnumMember: + return parent.id === node; + case utils_1.AST_NODE_TYPES.MethodDefinition: + case utils_1.AST_NODE_TYPES.PropertyDefinition: + case utils_1.AST_NODE_TYPES.AccessorProperty: + return parent.key === node; + case utils_1.AST_NODE_TYPES.Property: + // foo in "const { foo } = bar" will be processed twice, as parent.key + // and parent.value. The second is treated as a declaration. + if (parent.shorthand && parent.value === node) { + return parent.parent.type === utils_1.AST_NODE_TYPES.ObjectPattern; + } + if (parent.value === node) { + return false; + } + return parent.parent.type === utils_1.AST_NODE_TYPES.ObjectExpression; + case utils_1.AST_NODE_TYPES.AssignmentPattern: + // foo in "const { foo = "" } = bar" will be processed twice, as parent.parent.key + // and parent.left. The second is treated as a declaration. + return parent.left === node; + case utils_1.AST_NODE_TYPES.ArrowFunctionExpression: + case utils_1.AST_NODE_TYPES.FunctionDeclaration: + case utils_1.AST_NODE_TYPES.FunctionExpression: + case utils_1.AST_NODE_TYPES.TSDeclareFunction: + case utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression: + case utils_1.AST_NODE_TYPES.TSEnumDeclaration: + case utils_1.AST_NODE_TYPES.TSInterfaceDeclaration: + case utils_1.AST_NODE_TYPES.TSMethodSignature: + case utils_1.AST_NODE_TYPES.TSModuleDeclaration: + case utils_1.AST_NODE_TYPES.TSParameterProperty: + case utils_1.AST_NODE_TYPES.TSPropertySignature: + case utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration: + case utils_1.AST_NODE_TYPES.TSTypeParameter: + return true; + default: + return false; + } + } + function isInsideExportOrImport(node) { + let current = node; + while (true) { + switch (current.type) { + case utils_1.AST_NODE_TYPES.ExportAllDeclaration: + case utils_1.AST_NODE_TYPES.ExportNamedDeclaration: + case utils_1.AST_NODE_TYPES.ImportDeclaration: + return true; + case utils_1.AST_NODE_TYPES.ArrowFunctionExpression: + case utils_1.AST_NODE_TYPES.BlockStatement: + case utils_1.AST_NODE_TYPES.ClassDeclaration: + case utils_1.AST_NODE_TYPES.TSInterfaceDeclaration: + case utils_1.AST_NODE_TYPES.FunctionDeclaration: + case utils_1.AST_NODE_TYPES.FunctionExpression: + case utils_1.AST_NODE_TYPES.Program: + case utils_1.AST_NODE_TYPES.TSUnionType: + case utils_1.AST_NODE_TYPES.VariableDeclarator: + return false; + default: + current = current.parent; + } + } + } + function getJsDocDeprecation(symbol) { + let jsDocTags; + try { + jsDocTags = symbol?.getJsDocTags(checker); + } + catch { + // workaround for https://github.com/microsoft/TypeScript/issues/60024 + return; + } + const tag = jsDocTags?.find(tag => tag.name === 'deprecated'); + if (!tag) { + return undefined; + } + const displayParts = tag.text; + return displayParts ? ts.displayPartsToString(displayParts) : ''; + } + function isNodeCalleeOfParent(node) { + switch (node.parent?.type) { + case utils_1.AST_NODE_TYPES.NewExpression: + case utils_1.AST_NODE_TYPES.CallExpression: + return node.parent.callee === node; + case utils_1.AST_NODE_TYPES.TaggedTemplateExpression: + return node.parent.tag === node; + case utils_1.AST_NODE_TYPES.JSXOpeningElement: + return node.parent.name === node; + default: + return false; + } + } + function getCallLikeNode(node) { + let callee = node; + while (callee.parent?.type === utils_1.AST_NODE_TYPES.MemberExpression && + callee.parent.property === callee) { + callee = callee.parent; + } + return isNodeCalleeOfParent(callee) ? callee : undefined; + } + function getCallLikeDeprecation(node) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node.parent); + // If the node is a direct function call, we look for its signature. + const signature = (0, util_1.nullThrows)(checker.getResolvedSignature(tsNode), 'Expected call like node to have signature'); + const symbol = services.getSymbolAtLocation(node); + const aliasedSymbol = symbol != null && tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias) + ? checker.getAliasedSymbol(symbol) + : symbol; + const symbolDeclarationKind = aliasedSymbol?.declarations?.[0].kind; + // Properties with function-like types have "deprecated" jsdoc + // on their symbols, not on their signatures: + // + // interface Props { + // /** @deprecated */ + // property: () => 'foo' + // ^symbol^ ^signature^ + // } + if (symbolDeclarationKind !== ts.SyntaxKind.MethodDeclaration && + symbolDeclarationKind !== ts.SyntaxKind.FunctionDeclaration && + symbolDeclarationKind !== ts.SyntaxKind.MethodSignature) { + return (searchForDeprecationInAliasesChain(symbol, true) ?? + getJsDocDeprecation(signature) ?? + getJsDocDeprecation(aliasedSymbol)); + } + return (searchForDeprecationInAliasesChain(symbol, + // Here we're working with a function declaration or method. + // Both can have 1 or more overloads, each overload creates one + // ts.Declaration which is placed in symbol.declarations. + // + // Imagine the following code: + // + // function foo(): void + // /** @deprecated Some Reason */ + // function foo(arg: string): void + // function foo(arg?: string): void {} + // + // foo() // <- foo is our symbol + // + // If we call getJsDocDeprecation(checker.getAliasedSymbol(symbol)), + // we get 'Some Reason', but after all, we are calling foo with + // a signature that is not deprecated! + // It works this way because symbol.getJsDocTags returns tags from + // all symbol declarations combined into one array. And AFAIK there is + // no publicly exported TS function that can tell us if a particular + // declaration is deprecated or not. + // + // So, in case of function and method declarations, we don't check original + // aliased symbol, but rely on the getJsDocDeprecation(signature) call below. + false) ?? getJsDocDeprecation(signature)); + } + function getJSXAttributeDeprecation(openingElement, propertyName) { + const tsNode = services.esTreeNodeToTSNodeMap.get(openingElement.name); + const contextualType = (0, util_1.nullThrows)(checker.getContextualType(tsNode), 'Expected JSX opening element name to have contextualType'); + const symbol = contextualType.getProperty(propertyName); + return getJsDocDeprecation(symbol); + } + function getDeprecationReason(node) { + const callLikeNode = getCallLikeNode(node); + if (callLikeNode) { + return getCallLikeDeprecation(callLikeNode); + } + if (node.parent.type === utils_1.AST_NODE_TYPES.JSXAttribute && + node.type !== utils_1.AST_NODE_TYPES.Super) { + return getJSXAttributeDeprecation(node.parent.parent, node.name); + } + if (node.parent.type === utils_1.AST_NODE_TYPES.Property && + node.type !== utils_1.AST_NODE_TYPES.Super) { + const property = services + .getTypeAtLocation(node.parent.parent) + .getProperty(node.name); + const propertySymbol = services.getSymbolAtLocation(node); + const valueSymbol = checker.getShorthandAssignmentValueSymbol(propertySymbol?.valueDeclaration); + return (searchForDeprecationInAliasesChain(propertySymbol, true) ?? + getJsDocDeprecation(property) ?? + getJsDocDeprecation(propertySymbol) ?? + getJsDocDeprecation(valueSymbol)); + } + return searchForDeprecationInAliasesChain(services.getSymbolAtLocation(node), true); + } + function checkIdentifier(node) { + if (isDeclaration(node) || isInsideExportOrImport(node)) { + return; + } + const reason = getDeprecationReason(node); + if (reason == null) { + return; + } + const type = services.getTypeAtLocation(node); + if ((0, util_1.typeMatchesSomeSpecifier)(type, allow, services.program)) { + return; + } + const name = getReportedNodeName(node); + context.report({ + ...(reason + ? { + messageId: 'deprecatedWithReason', + data: { name, reason }, + } + : { + messageId: 'deprecated', + data: { name }, + }), + node, + }); + } + function checkMemberExpression(node) { + if (!node.computed) { + return; + } + const propertyType = services.getTypeAtLocation(node.property); + if (propertyType.isLiteral()) { + const objectType = services.getTypeAtLocation(node.object); + const propertyName = propertyType.isStringLiteral() + ? propertyType.value + : String(propertyType.value); + const property = objectType.getProperty(propertyName); + const reason = getJsDocDeprecation(property); + if (reason == null) { + return; + } + if ((0, util_1.typeMatchesSomeSpecifier)(objectType, allow, services.program)) { + return; + } + context.report({ + ...(reason + ? { + messageId: 'deprecatedWithReason', + data: { name: propertyName, reason }, + } + : { + messageId: 'deprecated', + data: { name: propertyName }, + }), + node: node.property, + }); + } + } + return { + Identifier: checkIdentifier, + JSXIdentifier(node) { + if (node.parent.type !== utils_1.AST_NODE_TYPES.JSXClosingElement) { + checkIdentifier(node); + } + }, + MemberExpression: checkMemberExpression, + PrivateIdentifier: checkIdentifier, + Super: checkIdentifier, + }; + }, +}); +function getReportedNodeName(node) { + if (node.type === utils_1.AST_NODE_TYPES.Super) { + return 'super'; + } + if (node.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) { + return `#${node.name}`; + } + return node.name; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dupe-class-members.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dupe-class-members.d.ts new file mode 100644 index 00000000..10b90409 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dupe-class-members.d.ts @@ -0,0 +1,13 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpected", [], unknown, { + 'ClassBody:exit'(): void; + 'MethodDefinition, PropertyDefinition'(node: TSESTree.MethodDefinition | TSESTree.PropertyDefinition): void; + ClassBody(): void; + Program(): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpected", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-dupe-class-members.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dupe-class-members.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dupe-class-members.d.ts.map new file mode 100644 index 00000000..17070394 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dupe-class-members.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-dupe-class-members.d.ts","sourceRoot":"","sources":["../../src/rules/no-dupe-class-members.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;;iDAiDw+F,SAAU,gBAAgB,GAAE,SAAU,kBAAkB;;;EAjDn/F,CAAC;AAE5D,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;AAEtE,wBA2CG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dupe-class-members.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dupe-class-members.js new file mode 100644 index 00000000..b5468dad --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dupe-class-members.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-dupe-class-members'); +exports.default = (0, util_1.createRule)({ + name: 'no-dupe-class-members', + meta: { + type: 'problem', + // defaultOptions, -- base rule does not use defaultOptions + docs: { + description: 'Disallow duplicate class members', + extendsBaseRule: true, + }, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: baseRule.meta.schema, + }, + defaultOptions: [], + create(context) { + const rules = baseRule.create(context); + function wrapMemberDefinitionListener(coreListener) { + return (node) => { + if (node.computed) { + return; + } + if (node.value && + node.value.type === utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression) { + return; + } + return coreListener(node); + }; + } + return { + ...rules, + 'MethodDefinition, PropertyDefinition': wrapMemberDefinitionListener(rules['MethodDefinition, PropertyDefinition']), + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-enum-values.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-enum-values.d.ts new file mode 100644 index 00000000..9711323c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-enum-values.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"duplicateValue", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-duplicate-enum-values.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-enum-values.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-enum-values.d.ts.map new file mode 100644 index 00000000..980a1477 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-enum-values.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-duplicate-enum-values.d.ts","sourceRoot":"","sources":["../../src/rules/no-duplicate-enum-values.ts"],"names":[],"mappings":";AAMA,wBAgFG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-enum-values.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-enum-values.js new file mode 100644 index 00000000..5a74957d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-enum-values.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-duplicate-enum-values', + meta: { + type: 'problem', + docs: { + description: 'Disallow duplicate enum member values', + recommended: 'recommended', + }, + hasSuggestions: false, + messages: { + duplicateValue: 'Duplicate enum member value {{value}}.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function isStringLiteral(node) { + return (node.type === utils_1.AST_NODE_TYPES.Literal && typeof node.value === 'string'); + } + function isNumberLiteral(node) { + return (node.type === utils_1.AST_NODE_TYPES.Literal && typeof node.value === 'number'); + } + function isStaticTemplateLiteral(node) { + return (node.type === utils_1.AST_NODE_TYPES.TemplateLiteral && + node.expressions.length === 0 && + node.quasis.length === 1); + } + return { + TSEnumDeclaration(node) { + const enumMembers = node.body.members; + const seenValues = new Set(); + enumMembers.forEach(member => { + if (member.initializer == null) { + return; + } + let value; + if (isStringLiteral(member.initializer)) { + value = member.initializer.value; + } + else if (isNumberLiteral(member.initializer)) { + value = member.initializer.value; + } + else if (isStaticTemplateLiteral(member.initializer)) { + value = member.initializer.quasis[0].value.cooked; + } + if (value == null) { + return; + } + if (seenValues.has(value)) { + context.report({ + node: member, + messageId: 'duplicateValue', + data: { + value, + }, + }); + } + else { + seenValues.add(value); + } + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-type-constituents.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-type-constituents.d.ts new file mode 100644 index 00000000..1cdce8a8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-type-constituents.d.ts @@ -0,0 +1,10 @@ +export type Options = [ + { + ignoreIntersections?: boolean; + ignoreUnions?: boolean; + } +]; +export type MessageIds = 'duplicate' | 'unnecessary'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-duplicate-type-constituents.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-type-constituents.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-type-constituents.d.ts.map new file mode 100644 index 00000000..4984743f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-type-constituents.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-duplicate-type-constituents.d.ts","sourceRoot":"","sources":["../../src/rules/no-duplicate-type-constituents.ts"],"names":[],"mappings":"AAeA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,mBAAmB,CAAC,EAAE,OAAO,CAAC;QAC9B,YAAY,CAAC,EAAE,OAAO,CAAC;KACxB;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG,aAAa,CAAC;;AAwDrD,wBA4NG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-type-constituents.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-type-constituents.js new file mode 100644 index 00000000..acb785c1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-duplicate-type-constituents.js @@ -0,0 +1,219 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const astIgnoreKeys = new Set(['loc', 'parent', 'range']); +const isSameAstNode = (actualNode, expectedNode) => { + if (actualNode === expectedNode) { + return true; + } + if (actualNode && + expectedNode && + typeof actualNode === 'object' && + typeof expectedNode === 'object') { + if (Array.isArray(actualNode) && Array.isArray(expectedNode)) { + if (actualNode.length !== expectedNode.length) { + return false; + } + return !actualNode.some((nodeEle, index) => !isSameAstNode(nodeEle, expectedNode[index])); + } + const actualNodeKeys = Object.keys(actualNode).filter(key => !astIgnoreKeys.has(key)); + const expectedNodeKeys = Object.keys(expectedNode).filter(key => !astIgnoreKeys.has(key)); + if (actualNodeKeys.length !== expectedNodeKeys.length) { + return false; + } + if (actualNodeKeys.some(actualNodeKey => !Object.hasOwn(expectedNode, actualNodeKey))) { + return false; + } + if (actualNodeKeys.some(actualNodeKey => !isSameAstNode(actualNode[actualNodeKey], expectedNode[actualNodeKey]))) { + return false; + } + return true; + } + return false; +}; +exports.default = (0, util_1.createRule)({ + name: 'no-duplicate-type-constituents', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow duplicate constituents of union or intersection types', + recommended: 'recommended', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + duplicate: '{{type}} type constituent is duplicated with {{previous}}.', + unnecessary: 'Explicit undefined is unnecessary on an optional parameter.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + ignoreIntersections: { + type: 'boolean', + description: 'Whether to ignore `&` intersections.', + }, + ignoreUnions: { + type: 'boolean', + description: 'Whether to ignore `|` unions.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + ignoreIntersections: false, + ignoreUnions: false, + }, + ], + create(context, [{ ignoreIntersections, ignoreUnions }]) { + const parserServices = (0, util_1.getParserServices)(context); + const { sourceCode } = context; + function report(messageId, constituentNode, data) { + const getUnionOrIntersectionToken = (where, at) => sourceCode[`getTokens${where}`](constituentNode, { + filter: token => ['&', '|'].includes(token.value) && + constituentNode.parent.range[0] <= token.range[0] && + token.range[1] <= constituentNode.parent.range[1], + }).at(at); + const beforeUnionOrIntersectionToken = getUnionOrIntersectionToken('Before', -1); + let afterUnionOrIntersectionToken; + let bracketBeforeTokens; + let bracketAfterTokens; + if (beforeUnionOrIntersectionToken) { + bracketBeforeTokens = sourceCode.getTokensBetween(beforeUnionOrIntersectionToken, constituentNode); + bracketAfterTokens = sourceCode.getTokensAfter(constituentNode, { + count: bracketBeforeTokens.length, + }); + } + else { + afterUnionOrIntersectionToken = (0, util_1.nullThrows)(getUnionOrIntersectionToken('After', 0), util_1.NullThrowsReasons.MissingToken('union or intersection token', 'duplicate type constituent')); + bracketAfterTokens = sourceCode.getTokensBetween(constituentNode, afterUnionOrIntersectionToken); + bracketBeforeTokens = sourceCode.getTokensBefore(constituentNode, { + count: bracketAfterTokens.length, + }); + } + context.report({ + loc: { + start: constituentNode.loc.start, + end: (bracketAfterTokens.at(-1) ?? constituentNode).loc.end, + }, + node: constituentNode, + messageId, + data, + fix: fixer => [ + beforeUnionOrIntersectionToken, + ...bracketBeforeTokens, + constituentNode, + ...bracketAfterTokens, + afterUnionOrIntersectionToken, + ].flatMap(token => (token ? fixer.remove(token) : [])), + }); + } + function checkDuplicateRecursively(unionOrIntersection, constituentNode, uniqueConstituents, cachedTypeMap, forEachNodeType) { + const type = parserServices.getTypeAtLocation(constituentNode); + if (tsutils.isIntrinsicErrorType(type)) { + return; + } + const duplicatedPrevious = uniqueConstituents.find(ele => isSameAstNode(ele, constituentNode)) ?? + cachedTypeMap.get(type); + if (duplicatedPrevious) { + report('duplicate', constituentNode, { + type: unionOrIntersection, + previous: sourceCode.getText(duplicatedPrevious), + }); + return; + } + forEachNodeType?.(type, constituentNode); + cachedTypeMap.set(type, constituentNode); + uniqueConstituents.push(constituentNode); + if ((unionOrIntersection === 'Union' && + constituentNode.type === utils_1.AST_NODE_TYPES.TSUnionType) || + (unionOrIntersection === 'Intersection' && + constituentNode.type === utils_1.AST_NODE_TYPES.TSIntersectionType)) { + for (const constituent of constituentNode.types) { + checkDuplicateRecursively(unionOrIntersection, constituent, uniqueConstituents, cachedTypeMap, forEachNodeType); + } + } + } + function checkDuplicate(node, forEachNodeType) { + const cachedTypeMap = new Map(); + const uniqueConstituents = []; + const unionOrIntersection = node.type === utils_1.AST_NODE_TYPES.TSIntersectionType + ? 'Intersection' + : 'Union'; + for (const type of node.types) { + checkDuplicateRecursively(unionOrIntersection, type, uniqueConstituents, cachedTypeMap, forEachNodeType); + } + } + return { + ...(!ignoreIntersections && { + TSIntersectionType(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.TSIntersectionType) { + return; + } + checkDuplicate(node); + }, + }), + ...(!ignoreUnions && { + TSUnionType: (node) => { + if (node.parent.type === utils_1.AST_NODE_TYPES.TSUnionType) { + return; + } + checkDuplicate(node, (constituentNodeType, constituentNode) => { + const maybeTypeAnnotation = node.parent; + if (maybeTypeAnnotation.type === utils_1.AST_NODE_TYPES.TSTypeAnnotation) { + const maybeIdentifier = maybeTypeAnnotation.parent; + if (maybeIdentifier.type === utils_1.AST_NODE_TYPES.Identifier && + maybeIdentifier.optional) { + const maybeFunction = maybeIdentifier.parent; + if ((0, util_1.isFunctionOrFunctionType)(maybeFunction) && + maybeFunction.params.includes(maybeIdentifier) && + tsutils.isTypeFlagSet(constituentNodeType, ts.TypeFlags.Undefined)) { + report('unnecessary', constituentNode); + } + } + } + }); + }, + }), + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dynamic-delete.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dynamic-delete.d.ts new file mode 100644 index 00000000..7eda3a9d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dynamic-delete.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"dynamicDelete", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-dynamic-delete.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dynamic-delete.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dynamic-delete.d.ts.map new file mode 100644 index 00000000..1cf85857 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dynamic-delete.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-dynamic-delete.d.ts","sourceRoot":"","sources":["../../src/rules/no-dynamic-delete.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAMnE,wBAwEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dynamic-delete.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dynamic-delete.js new file mode 100644 index 00000000..0937e40c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-dynamic-delete.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-dynamic-delete', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow using the `delete` operator on computed key expressions', + recommended: 'strict', + }, + fixable: 'code', + messages: { + dynamicDelete: 'Do not delete dynamically computed property keys.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function createFixer(member) { + if (member.property.type === utils_1.AST_NODE_TYPES.Literal && + typeof member.property.value === 'string') { + return createPropertyReplacement(member.property, `.${member.property.value}`); + } + return undefined; + } + return { + 'UnaryExpression[operator=delete]'(node) { + if (node.argument.type !== utils_1.AST_NODE_TYPES.MemberExpression || + !node.argument.computed || + isAcceptableIndexExpression(node.argument.property)) { + return; + } + context.report({ + node: node.argument.property, + messageId: 'dynamicDelete', + fix: createFixer(node.argument), + }); + }, + }; + function createPropertyReplacement(property, replacement) { + return (fixer) => fixer.replaceTextRange(getTokenRange(property), replacement); + } + function getTokenRange(property) { + return [ + (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(property), util_1.NullThrowsReasons.MissingToken('token before', 'property')).range[0], + (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(property), util_1.NullThrowsReasons.MissingToken('token after', 'property')).range[1], + ]; + } + }, +}); +function isAcceptableIndexExpression(property) { + return ((property.type === utils_1.AST_NODE_TYPES.Literal && + ['number', 'string'].includes(typeof property.value)) || + (property.type === utils_1.AST_NODE_TYPES.UnaryExpression && + property.operator === '-' && + property.argument.type === utils_1.AST_NODE_TYPES.Literal && + typeof property.argument.value === 'number')); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-function.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-function.d.ts new file mode 100644 index 00000000..64381042 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-function.d.ts @@ -0,0 +1,15 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpected", [{ + allow?: string[]; +}], unknown, { + FunctionDeclaration(node: TSESTree.FunctionDeclaration): void; + FunctionExpression(node: TSESTree.FunctionExpression): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpected", [{ + allow?: string[]; +}], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-empty-function.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-function.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-function.d.ts.map new file mode 100644 index 00000000..b31be935 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-function.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-empty-function.d.ts","sourceRoot":"","sources":["../../src/rules/no-empty-function.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAKzD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;;;8BA2K4S,SAAU,mBAAmB;6BAAuC,SAAU,kBAAkB;EA3KnW,CAAC;AAExD,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;;;AA0CtE,wBA6HG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-function.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-function.js new file mode 100644 index 00000000..f4449fc4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-function.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-empty-function'); +const defaultOptions = [ + { + allow: [], + }, +]; +const schema = (0, util_1.deepMerge)( +// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- https://github.com/microsoft/TypeScript/issues/17002 +Array.isArray(baseRule.meta.schema) + ? baseRule.meta.schema[0] + : baseRule.meta.schema, { + properties: { + allow: { + description: 'Locations and kinds of functions that are allowed to be empty.', + items: { + type: 'string', + enum: [ + 'functions', + 'arrowFunctions', + 'generatorFunctions', + 'methods', + 'generatorMethods', + 'getters', + 'setters', + 'constructors', + 'private-constructors', + 'protected-constructors', + 'asyncFunctions', + 'asyncMethods', + 'decoratedFunctions', + 'overrideMethods', + ], + }, + }, + }, +}); +exports.default = (0, util_1.createRule)({ + name: 'no-empty-function', + meta: { + type: 'suggestion', + defaultOptions, + docs: { + description: 'Disallow empty functions', + extendsBaseRule: true, + recommended: 'stylistic', + }, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: [schema], + }, + defaultOptions, + create(context, [{ allow = [] }]) { + const rules = baseRule.create(context); + const isAllowedProtectedConstructors = allow.includes('protected-constructors'); + const isAllowedPrivateConstructors = allow.includes('private-constructors'); + const isAllowedDecoratedFunctions = allow.includes('decoratedFunctions'); + const isAllowedOverrideMethods = allow.includes('overrideMethods'); + /** + * Check if the method body is empty + * @param node the node to be validated + * @returns true if the body is empty + * @private + */ + function isBodyEmpty(node) { + return node.body.body.length === 0; + } + /** + * Check if method has parameter properties + * @param node the node to be validated + * @returns true if the body has parameter properties + * @private + */ + function hasParameterProperties(node) { + return node.params.some(param => param.type === utils_1.AST_NODE_TYPES.TSParameterProperty); + } + /** + * @param node the node to be validated + * @returns true if the constructor is allowed to be empty + * @private + */ + function isAllowedEmptyConstructor(node) { + const parent = node.parent; + if (isBodyEmpty(node) && + parent.type === utils_1.AST_NODE_TYPES.MethodDefinition && + parent.kind === 'constructor') { + const { accessibility } = parent; + return ( + // allow protected constructors + (accessibility === 'protected' && isAllowedProtectedConstructors) || + // allow private constructors + (accessibility === 'private' && isAllowedPrivateConstructors) || + // allow constructors which have parameter properties + hasParameterProperties(node)); + } + return false; + } + /** + * @param node the node to be validated + * @returns true if a function has decorators + * @private + */ + function isAllowedEmptyDecoratedFunctions(node) { + if (isAllowedDecoratedFunctions && isBodyEmpty(node)) { + const decorators = node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition + ? node.parent.decorators + : undefined; + return !!decorators && !!decorators.length; + } + return false; + } + function isAllowedEmptyOverrideMethod(node) { + return (isAllowedOverrideMethods && + isBodyEmpty(node) && + node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition && + node.parent.override); + } + return { + ...rules, + FunctionExpression(node) { + if (isAllowedEmptyConstructor(node) || + isAllowedEmptyDecoratedFunctions(node) || + isAllowedEmptyOverrideMethod(node)) { + return; + } + rules.FunctionExpression(node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-interface.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-interface.d.ts new file mode 100644 index 00000000..e2e7922c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-interface.d.ts @@ -0,0 +1,10 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = [ + { + allowSingleExtends?: boolean; + } +]; +export type MessageIds = 'noEmpty' | 'noEmptyWithSuper'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-empty-interface.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-interface.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-interface.d.ts.map new file mode 100644 index 00000000..bbb1af24 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-interface.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-empty-interface.d.ts","sourceRoot":"","sources":["../../src/rules/no-empty-interface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAOzD,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,kBAAkB,CAAC;;AAExD,wBAkHG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-interface.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-interface.js new file mode 100644 index 00000000..18f6e96d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-interface.js @@ -0,0 +1,102 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-empty-interface', + meta: { + type: 'suggestion', + deprecated: { + deprecatedSince: '8.0.0', + replacedBy: [ + { + rule: { + name: '@typescript-eslint/no-empty-object-type', + url: 'https://typescript-eslint.io/rules/no-empty-object-type', + }, + }, + ], + url: 'https://github.com/typescript-eslint/typescript-eslint/pull/8977', + }, + docs: { + description: 'Disallow the declaration of empty interfaces', + }, + fixable: 'code', + hasSuggestions: true, + messages: { + noEmpty: 'An empty interface is equivalent to `{}`.', + noEmptyWithSuper: 'An interface declaring no members is equivalent to its supertype.', + }, + replacedBy: ['@typescript-eslint/no-empty-object-type'], + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowSingleExtends: { + type: 'boolean', + description: 'Whether to allow empty interfaces that extend a single other interface.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowSingleExtends: false, + }, + ], + create(context, [{ allowSingleExtends }]) { + return { + TSInterfaceDeclaration(node) { + if (node.body.body.length !== 0) { + // interface contains members --> Nothing to report + return; + } + const extend = node.extends; + if (extend.length === 0) { + context.report({ + node: node.id, + messageId: 'noEmpty', + }); + } + else if (extend.length === 1 && + // interface extends exactly 1 interface --> Report depending on rule setting + !allowSingleExtends) { + const fix = (fixer) => { + let typeParam = ''; + if (node.typeParameters) { + typeParam = context.sourceCode.getText(node.typeParameters); + } + return fixer.replaceText(node, `type ${context.sourceCode.getText(node.id)}${typeParam} = ${context.sourceCode.getText(extend[0])}`); + }; + const scope = context.sourceCode.getScope(node); + const mergedWithClassDeclaration = scope.set + .get(node.id.name) + ?.defs.some(def => def.node.type === utils_1.AST_NODE_TYPES.ClassDeclaration); + const isInAmbientDeclaration = (0, util_1.isDefinitionFile)(context.filename) && + scope.type === scope_manager_1.ScopeType.tsModule && + scope.block.declare; + const useAutoFix = !(isInAmbientDeclaration || mergedWithClassDeclaration); + context.report({ + node: node.id, + messageId: 'noEmptyWithSuper', + ...(useAutoFix + ? { fix } + : !mergedWithClassDeclaration + ? { + suggest: [ + { + messageId: 'noEmptyWithSuper', + fix, + }, + ], + } + : null), + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-object-type.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-object-type.d.ts new file mode 100644 index 00000000..3a5f1d77 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-object-type.d.ts @@ -0,0 +1,14 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type AllowInterfaces = 'always' | 'never' | 'with-single-extends'; +export type AllowObjectTypes = 'always' | 'never'; +export type Options = [ + { + allowInterfaces?: AllowInterfaces; + allowObjectTypes?: AllowObjectTypes; + allowWithName?: string; + } +]; +export type MessageIds = 'noEmptyInterface' | 'noEmptyInterfaceWithSuper' | 'noEmptyObject' | 'replaceEmptyInterface' | 'replaceEmptyInterfaceWithSuper' | 'replaceEmptyObjectType'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-empty-object-type.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-object-type.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-object-type.d.ts.map new file mode 100644 index 00000000..3ffe6c4d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-object-type.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-empty-object-type.d.ts","sourceRoot":"","sources":["../../src/rules/no-empty-object-type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAMzD,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,OAAO,GAAG,qBAAqB,CAAC;AAEzE,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElD,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,eAAe,CAAC,EAAE,eAAe,CAAC;QAClC,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;QACpC,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAClB,kBAAkB,GAClB,2BAA2B,GAC3B,eAAe,GACf,uBAAuB,GACvB,gCAAgC,GAChC,wBAAwB,CAAC;;AAU7B,wBA6JG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-object-type.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-object-type.js new file mode 100644 index 00000000..89beddf9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-empty-object-type.js @@ -0,0 +1,143 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const noEmptyMessage = (emptyType) => [ + `${emptyType} allows any non-nullish value, including literals like \`0\` and \`""\`.`, + "- If that's what you want, disable this lint rule with an inline comment or configure the '{{ option }}' rule option.", + '- If you want a type meaning "any object", you probably want `object` instead.', + '- If you want a type meaning "any value", you probably want `unknown` instead.', +].join('\n'); +exports.default = (0, util_1.createRule)({ + name: 'no-empty-object-type', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow accidentally using the "empty object" type', + recommended: 'recommended', + }, + hasSuggestions: true, + messages: { + noEmptyInterface: noEmptyMessage('An empty interface declaration'), + noEmptyInterfaceWithSuper: 'An interface declaring no members is equivalent to its supertype.', + noEmptyObject: noEmptyMessage('The `{}` ("empty object") type'), + replaceEmptyInterface: 'Replace empty interface with `{{replacement}}`.', + replaceEmptyInterfaceWithSuper: 'Replace empty interface with a type alias.', + replaceEmptyObjectType: 'Replace `{}` with `{{replacement}}`.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowInterfaces: { + type: 'string', + description: 'Whether to allow empty interfaces.', + enum: ['always', 'never', 'with-single-extends'], + }, + allowObjectTypes: { + type: 'string', + description: 'Whether to allow empty object type literals.', + enum: ['always', 'never'], + }, + allowWithName: { + type: 'string', + description: 'A stringified regular expression to allow interfaces and object type aliases with the configured name.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowInterfaces: 'never', + allowObjectTypes: 'never', + }, + ], + create(context, [{ allowInterfaces, allowObjectTypes, allowWithName }]) { + const allowWithNameTester = allowWithName + ? new RegExp(allowWithName, 'u') + : undefined; + return { + ...(allowInterfaces !== 'always' && { + TSInterfaceDeclaration(node) { + if (allowWithNameTester?.test(node.id.name)) { + return; + } + const extend = node.extends; + if (node.body.body.length !== 0 || + (extend.length === 1 && + allowInterfaces === 'with-single-extends') || + extend.length > 1) { + return; + } + const scope = context.sourceCode.getScope(node); + const mergedWithClassDeclaration = scope.set + .get(node.id.name) + ?.defs.some(def => def.node.type === utils_1.AST_NODE_TYPES.ClassDeclaration); + if (extend.length === 0) { + context.report({ + node: node.id, + messageId: 'noEmptyInterface', + data: { option: 'allowInterfaces' }, + ...(!mergedWithClassDeclaration && { + suggest: ['object', 'unknown'].map(replacement => ({ + messageId: 'replaceEmptyInterface', + data: { replacement }, + fix(fixer) { + const id = context.sourceCode.getText(node.id); + const typeParam = node.typeParameters + ? context.sourceCode.getText(node.typeParameters) + : ''; + return fixer.replaceText(node, `type ${id}${typeParam} = ${replacement}`); + }, + })), + }), + }); + return; + } + context.report({ + node: node.id, + messageId: 'noEmptyInterfaceWithSuper', + ...(!mergedWithClassDeclaration && { + suggest: [ + { + messageId: 'replaceEmptyInterfaceWithSuper', + fix(fixer) { + const extended = context.sourceCode.getText(extend[0]); + const id = context.sourceCode.getText(node.id); + const typeParam = node.typeParameters + ? context.sourceCode.getText(node.typeParameters) + : ''; + return fixer.replaceText(node, `type ${id}${typeParam} = ${extended}`); + }, + }, + ], + }), + }); + }, + }), + ...(allowObjectTypes !== 'always' && { + TSTypeLiteral(node) { + if (node.members.length || + node.parent.type === utils_1.AST_NODE_TYPES.TSIntersectionType || + (allowWithNameTester && + node.parent.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration && + allowWithNameTester.test(node.parent.id.name))) { + return; + } + context.report({ + node, + messageId: 'noEmptyObject', + data: { option: 'allowObjectTypes' }, + suggest: ['object', 'unknown'].map(replacement => ({ + messageId: 'replaceEmptyObjectType', + data: { replacement }, + fix: (fixer) => fixer.replaceText(node, replacement), + })), + }); + }, + }), + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-explicit-any.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-explicit-any.d.ts new file mode 100644 index 00000000..a8e0afba --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-explicit-any.d.ts @@ -0,0 +1,11 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = [ + { + fixToUnknown?: boolean; + ignoreRestArgs?: boolean; + } +]; +export type MessageIds = 'suggestNever' | 'suggestPropertyKey' | 'suggestUnknown' | 'unexpectedAny'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-explicit-any.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-explicit-any.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-explicit-any.d.ts.map new file mode 100644 index 00000000..963732bd --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-explicit-any.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-explicit-any.d.ts","sourceRoot":"","sources":["../../src/rules/no-explicit-any.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAMnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,cAAc,CAAC,EAAE,OAAO,CAAC;KAC1B;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAClB,cAAc,GACd,oBAAoB,GACpB,gBAAgB,GAChB,eAAe,CAAC;;AAEpB,wBAuOG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-explicit-any.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-explicit-any.js new file mode 100644 index 00000000..0f47d12c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-explicit-any.js @@ -0,0 +1,197 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-explicit-any', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow the `any` type', + recommended: 'recommended', + }, + fixable: 'code', + hasSuggestions: true, + messages: { + suggestNever: "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of.", + suggestPropertyKey: 'Use `PropertyKey` instead, this is more explicit than `keyof any`.', + suggestUnknown: 'Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct.', + unexpectedAny: 'Unexpected any. Specify a different type.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + fixToUnknown: { + type: 'boolean', + description: 'Whether to enable auto-fixing in which the `any` type is converted to the `unknown` type.', + }, + ignoreRestArgs: { + type: 'boolean', + description: 'Whether to ignore rest parameter arrays.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + fixToUnknown: false, + ignoreRestArgs: false, + }, + ], + create(context, [{ fixToUnknown, ignoreRestArgs }]) { + /** + * Checks if the node is an arrow function, function/constructor declaration or function expression + * @param node the node to be validated. + * @returns true if the node is any kind of function declaration or expression + * @private + */ + function isNodeValidFunction(node) { + return [ + utils_1.AST_NODE_TYPES.ArrowFunctionExpression, // const x = (...args: any[]) => {}; + utils_1.AST_NODE_TYPES.FunctionDeclaration, // function f(...args: any[]) {} + utils_1.AST_NODE_TYPES.FunctionExpression, // const x = function(...args: any[]) {}; + utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration, // type T = {(...args: any[]): unknown}; + utils_1.AST_NODE_TYPES.TSConstructorType, // type T = new (...args: any[]) => unknown + utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration, // type T = {new (...args: any[]): unknown}; + utils_1.AST_NODE_TYPES.TSDeclareFunction, // declare function _8(...args: any[]): unknown; + utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression, // declare class A { f(...args: any[]): unknown; } + utils_1.AST_NODE_TYPES.TSFunctionType, // type T = (...args: any[]) => unknown; + utils_1.AST_NODE_TYPES.TSMethodSignature, // type T = {f(...args: any[]): unknown}; + ].includes(node.type); + } + /** + * Checks if the node is a rest element child node of a function + * @param node the node to be validated. + * @returns true if the node is a rest element child node of a function + * @private + */ + function isNodeRestElementInFunction(node) { + return (node.type === utils_1.AST_NODE_TYPES.RestElement && + isNodeValidFunction(node.parent)); + } + /** + * Checks if the node is a TSTypeOperator node with a readonly operator + * @param node the node to be validated. + * @returns true if the node is a TSTypeOperator node with a readonly operator + * @private + */ + function isNodeReadonlyTSTypeOperator(node) { + return (node.type === utils_1.AST_NODE_TYPES.TSTypeOperator && + node.operator === 'readonly'); + } + /** + * Checks if the node is a TSTypeReference node with an Array identifier + * @param node the node to be validated. + * @returns true if the node is a TSTypeReference node with an Array identifier + * @private + */ + function isNodeValidArrayTSTypeReference(node) { + return (node.type === utils_1.AST_NODE_TYPES.TSTypeReference && + node.typeName.type === utils_1.AST_NODE_TYPES.Identifier && + ['Array', 'ReadonlyArray'].includes(node.typeName.name)); + } + /** + * Checks if the node is a valid TSTypeOperator or TSTypeReference node + * @param node the node to be validated. + * @returns true if the node is a valid TSTypeOperator or TSTypeReference node + * @private + */ + function isNodeValidTSType(node) { + return (isNodeReadonlyTSTypeOperator(node) || + isNodeValidArrayTSTypeReference(node)); + } + /** + * Checks if the great grand-parent node is a RestElement node in a function + * @param node the node to be validated. + * @returns true if the great grand-parent node is a RestElement node in a function + * @private + */ + function isGreatGrandparentRestElement(node) { + return (node.parent?.parent?.parent != null && + isNodeRestElementInFunction(node.parent.parent.parent)); + } + /** + * Checks if the great great grand-parent node is a valid RestElement node in a function + * @param node the node to be validated. + * @returns true if the great great grand-parent node is a valid RestElement node in a function + * @private + */ + function isGreatGreatGrandparentRestElement(node) { + return (node.parent?.parent?.parent?.parent != null && + isNodeValidTSType(node.parent.parent) && + isNodeRestElementInFunction(node.parent.parent.parent.parent)); + } + /** + * Checks if the great grand-parent or the great great grand-parent node is a RestElement node + * @param node the node to be validated. + * @returns true if the great grand-parent or the great great grand-parent node is a RestElement node + * @private + */ + function isNodeDescendantOfRestElementInFunction(node) { + return (isGreatGrandparentRestElement(node) || + isGreatGreatGrandparentRestElement(node)); + } + /** + * Checks if the node is within a keyof any expression + * @param node the node to be validated. + * @returns true if the node is within a keyof any expression, false otherwise + * @private + */ + function isNodeWithinKeyofAny(node) { + return (node.parent.type === utils_1.AST_NODE_TYPES.TSTypeOperator && + node.parent.operator === 'keyof'); + } + /** + * Creates a fixer that replaces a keyof any with PropertyKey + * @param node the node to be fixed. + * @returns a function that will fix the node. + * @private + */ + function createPropertyKeyFixer(node) { + return (fixer) => { + return fixer.replaceText(node.parent, 'PropertyKey'); + }; + } + return { + TSAnyKeyword(node) { + const isKeyofAny = isNodeWithinKeyofAny(node); + if (ignoreRestArgs && isNodeDescendantOfRestElementInFunction(node)) { + return; + } + const fixOrSuggest = { + fix: null, + suggest: isKeyofAny + ? [ + { + messageId: 'suggestPropertyKey', + fix: createPropertyKeyFixer(node), + }, + ] + : [ + { + messageId: 'suggestUnknown', + fix: fixer => fixer.replaceText(node, 'unknown'), + }, + { + messageId: 'suggestNever', + fix: fixer => fixer.replaceText(node, 'never'), + }, + ], + }; + if (fixToUnknown) { + fixOrSuggest.fix = isKeyofAny + ? createPropertyKeyFixer(node) + : fixer => fixer.replaceText(node, 'unknown'); + } + context.report({ + node, + messageId: 'unexpectedAny', + ...fixOrSuggest, + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extra-non-null-assertion.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extra-non-null-assertion.d.ts new file mode 100644 index 00000000..05920008 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extra-non-null-assertion.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noExtraNonNullAssertion", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-extra-non-null-assertion.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extra-non-null-assertion.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extra-non-null-assertion.d.ts.map new file mode 100644 index 00000000..c23c3839 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extra-non-null-assertion.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-extra-non-null-assertion.d.ts","sourceRoot":"","sources":["../../src/rules/no-extra-non-null-assertion.ts"],"names":[],"mappings":";AAIA,wBAoCG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extra-non-null-assertion.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extra-non-null-assertion.js new file mode 100644 index 00000000..e91afd76 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extra-non-null-assertion.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-extra-non-null-assertion', + meta: { + type: 'problem', + docs: { + description: 'Disallow extra non-null assertions', + recommended: 'recommended', + }, + fixable: 'code', + messages: { + noExtraNonNullAssertion: 'Forbidden extra non-null assertion.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function checkExtraNonNullAssertion(node) { + context.report({ + node, + messageId: 'noExtraNonNullAssertion', + fix(fixer) { + return fixer.removeRange([node.range[1] - 1, node.range[1]]); + }, + }); + } + return { + 'CallExpression[optional = true] > TSNonNullExpression.callee': checkExtraNonNullAssertion, + 'MemberExpression[optional = true] > TSNonNullExpression.object': checkExtraNonNullAssertion, + 'TSNonNullExpression > TSNonNullExpression': checkExtraNonNullAssertion, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extraneous-class.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extraneous-class.d.ts new file mode 100644 index 00000000..98aa0c93 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extraneous-class.d.ts @@ -0,0 +1,12 @@ +export type Options = [ + { + allowConstructorOnly?: boolean; + allowEmpty?: boolean; + allowStaticOnly?: boolean; + allowWithDecorator?: boolean; + } +]; +export type MessageIds = 'empty' | 'onlyConstructor' | 'onlyStatic'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-extraneous-class.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extraneous-class.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extraneous-class.d.ts.map new file mode 100644 index 00000000..3f835c40 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extraneous-class.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-extraneous-class.d.ts","sourceRoot":"","sources":["../../src/rules/no-extraneous-class.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,oBAAoB,CAAC,EAAE,OAAO,CAAC;QAC/B,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,eAAe,CAAC,EAAE,OAAO,CAAC;QAC1B,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,iBAAiB,GAAG,YAAY,CAAC;;AAEpE,wBA8IG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extraneous-class.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extraneous-class.js new file mode 100644 index 00000000..3e052449 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-extraneous-class.js @@ -0,0 +1,120 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-extraneous-class', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow classes used as namespaces', + recommended: 'strict', + }, + messages: { + empty: 'Unexpected empty class.', + onlyConstructor: 'Unexpected class with only a constructor.', + onlyStatic: 'Unexpected class with only static properties.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowConstructorOnly: { + type: 'boolean', + description: 'Whether to allow extraneous classes that contain only a constructor.', + }, + allowEmpty: { + type: 'boolean', + description: 'Whether to allow extraneous classes that have no body (i.e. are empty).', + }, + allowStaticOnly: { + type: 'boolean', + description: 'Whether to allow extraneous classes that only contain static members.', + }, + allowWithDecorator: { + type: 'boolean', + description: 'Whether to allow extraneous classes that include a decorator.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowConstructorOnly: false, + allowEmpty: false, + allowStaticOnly: false, + allowWithDecorator: false, + }, + ], + create(context, [{ allowConstructorOnly, allowEmpty, allowStaticOnly, allowWithDecorator }]) { + const isAllowWithDecorator = (node) => { + return !!(allowWithDecorator && + node?.decorators && + node.decorators.length !== 0); + }; + return { + ClassBody(node) { + const parent = node.parent; + if (parent.superClass || isAllowWithDecorator(parent)) { + return; + } + const reportNode = parent.type === utils_1.AST_NODE_TYPES.ClassDeclaration && parent.id + ? parent.id + : parent; + if (node.body.length === 0) { + if (allowEmpty) { + return; + } + context.report({ + node: reportNode, + messageId: 'empty', + }); + return; + } + let onlyStatic = true; + let onlyConstructor = true; + for (const prop of node.body) { + if (prop.type === utils_1.AST_NODE_TYPES.MethodDefinition && + prop.kind === 'constructor') { + if (prop.value.params.some(param => param.type === utils_1.AST_NODE_TYPES.TSParameterProperty)) { + onlyConstructor = false; + onlyStatic = false; + } + } + else { + onlyConstructor = false; + if (((prop.type === utils_1.AST_NODE_TYPES.PropertyDefinition || + prop.type === utils_1.AST_NODE_TYPES.MethodDefinition || + prop.type === utils_1.AST_NODE_TYPES.AccessorProperty) && + !prop.static) || + prop.type === utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition || + prop.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition || // `static abstract` methods and properties are currently not supported. See: https://github.com/microsoft/TypeScript/issues/34516 + prop.type === utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty) { + onlyStatic = false; + } + } + if (!(onlyStatic || onlyConstructor)) { + break; + } + } + if (onlyConstructor) { + if (!allowConstructorOnly) { + context.report({ + node: reportNode, + messageId: 'onlyConstructor', + }); + } + return; + } + if (onlyStatic && !allowStaticOnly) { + context.report({ + node: reportNode, + messageId: 'onlyStatic', + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-floating-promises.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-floating-promises.d.ts new file mode 100644 index 00000000..6c8a4625 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-floating-promises.d.ts @@ -0,0 +1,15 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +import type { TypeOrValueSpecifier } from '../util'; +export type Options = [ + { + allowForKnownSafeCalls?: TypeOrValueSpecifier[]; + allowForKnownSafePromises?: TypeOrValueSpecifier[]; + checkThenables?: boolean; + ignoreIIFE?: boolean; + ignoreVoid?: boolean; + } +]; +export type MessageId = 'floating' | 'floatingFixAwait' | 'floatingFixVoid' | 'floatingPromiseArray' | 'floatingPromiseArrayVoid' | 'floatingUselessRejectionHandler' | 'floatingUselessRejectionHandlerVoid' | 'floatingVoid'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-floating-promises.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-floating-promises.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-floating-promises.d.ts.map new file mode 100644 index 00000000..99c304b4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-floating-promises.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-floating-promises.d.ts","sourceRoot":"","sources":["../../src/rules/no-floating-promises.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAMnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAmBpD,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,sBAAsB,CAAC,EAAE,oBAAoB,EAAE,CAAC;QAChD,yBAAyB,CAAC,EAAE,oBAAoB,EAAE,CAAC;QACnD,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,UAAU,CAAC,EAAE,OAAO,CAAC;KACtB;CACF,CAAC;AAEF,MAAM,MAAM,SAAS,GACjB,UAAU,GACV,kBAAkB,GAClB,iBAAiB,GACjB,sBAAsB,GACtB,0BAA0B,GAC1B,iCAAiC,GACjC,qCAAqC,GACrC,cAAc,CAAC;;AAmBnB,wBAqZG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-floating-promises.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-floating-promises.js new file mode 100644 index 00000000..b02de12c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-floating-promises.js @@ -0,0 +1,369 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const promiseUtils_1 = require("../util/promiseUtils"); +const messageBase = 'Promises must be awaited, end with a call to .catch, or end with a call to .then with a rejection handler.'; +const messageBaseVoid = 'Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler' + + ' or be explicitly marked as ignored with the `void` operator.'; +const messageRejectionHandler = 'A rejection handler that is not a function will be ignored.'; +const messagePromiseArray = "An array of Promises may be unintentional. Consider handling the promises' fulfillment or rejection with Promise.all or similar."; +const messagePromiseArrayVoid = "An array of Promises may be unintentional. Consider handling the promises' fulfillment or rejection with Promise.all or similar," + + ' or explicitly marking the expression as ignored with the `void` operator.'; +exports.default = (0, util_1.createRule)({ + name: 'no-floating-promises', + meta: { + type: 'problem', + docs: { + description: 'Require Promise-like statements to be handled appropriately', + recommended: 'recommended', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + floating: messageBase, + floatingFixAwait: 'Add await operator.', + floatingFixVoid: 'Add void operator to ignore.', + floatingPromiseArray: messagePromiseArray, + floatingPromiseArrayVoid: messagePromiseArrayVoid, + floatingUselessRejectionHandler: `${messageBase} ${messageRejectionHandler}`, + floatingUselessRejectionHandlerVoid: `${messageBaseVoid} ${messageRejectionHandler}`, + floatingVoid: messageBaseVoid, + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowForKnownSafeCalls: { + ...util_1.readonlynessOptionsSchema.properties.allow, + description: 'Type specifiers of functions whose calls are safe to float.', + }, + allowForKnownSafePromises: { + ...util_1.readonlynessOptionsSchema.properties.allow, + description: 'Type specifiers that are known to be safe to float.', + }, + checkThenables: { + type: 'boolean', + description: 'Whether to check all "Thenable"s, not just the built-in Promise type.', + }, + ignoreIIFE: { + type: 'boolean', + description: 'Whether to ignore async IIFEs (Immediately Invoked Function Expressions).', + }, + ignoreVoid: { + type: 'boolean', + description: 'Whether to ignore `void` expressions.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowForKnownSafeCalls: util_1.readonlynessOptionsDefaults.allow, + allowForKnownSafePromises: util_1.readonlynessOptionsDefaults.allow, + checkThenables: false, + ignoreIIFE: false, + ignoreVoid: true, + }, + ], + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const { checkThenables } = options; + // TODO: #5439 + /* eslint-disable @typescript-eslint/no-non-null-assertion */ + const allowForKnownSafePromises = options.allowForKnownSafePromises; + const allowForKnownSafeCalls = options.allowForKnownSafeCalls; + /* eslint-enable @typescript-eslint/no-non-null-assertion */ + return { + ExpressionStatement(node) { + if (options.ignoreIIFE && isAsyncIife(node)) { + return; + } + const expression = (0, util_1.skipChainExpression)(node.expression); + if (isKnownSafePromiseReturn(expression)) { + return; + } + const { isUnhandled, nonFunctionHandler, promiseArray } = isUnhandledPromise(checker, expression); + if (isUnhandled) { + if (promiseArray) { + context.report({ + node, + messageId: options.ignoreVoid + ? 'floatingPromiseArrayVoid' + : 'floatingPromiseArray', + }); + } + else if (options.ignoreVoid) { + context.report({ + node, + messageId: nonFunctionHandler + ? 'floatingUselessRejectionHandlerVoid' + : 'floatingVoid', + suggest: [ + { + messageId: 'floatingFixVoid', + fix(fixer) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node.expression); + if (isHigherPrecedenceThanUnary(tsNode)) { + return fixer.insertTextBefore(node, 'void '); + } + return [ + fixer.insertTextBefore(node, 'void ('), + fixer.insertTextAfterRange([expression.range[1], expression.range[1]], ')'), + ]; + }, + }, + { + messageId: 'floatingFixAwait', + fix: (fixer) => addAwait(fixer, expression, node), + }, + ], + }); + } + else { + context.report({ + node, + messageId: nonFunctionHandler + ? 'floatingUselessRejectionHandler' + : 'floating', + suggest: [ + { + messageId: 'floatingFixAwait', + fix: (fixer) => addAwait(fixer, expression, node), + }, + ], + }); + } + } + }, + }; + function addAwait(fixer, expression, node) { + if (expression.type === utils_1.AST_NODE_TYPES.UnaryExpression && + expression.operator === 'void') { + return fixer.replaceTextRange([expression.range[0], expression.range[0] + 4], 'await'); + } + const tsNode = services.esTreeNodeToTSNodeMap.get(node.expression); + if (isHigherPrecedenceThanUnary(tsNode)) { + return fixer.insertTextBefore(node, 'await '); + } + return [ + fixer.insertTextBefore(node, 'await ('), + fixer.insertTextAfterRange([expression.range[1], expression.range[1]], ')'), + ]; + } + function isKnownSafePromiseReturn(node) { + if (node.type !== utils_1.AST_NODE_TYPES.CallExpression) { + return false; + } + const type = services.getTypeAtLocation(node.callee); + return (0, util_1.typeMatchesSomeSpecifier)(type, allowForKnownSafeCalls, services.program); + } + function isHigherPrecedenceThanUnary(node) { + const operator = ts.isBinaryExpression(node) + ? node.operatorToken.kind + : ts.SyntaxKind.Unknown; + const nodePrecedence = (0, util_1.getOperatorPrecedence)(node.kind, operator); + return nodePrecedence > util_1.OperatorPrecedence.Unary; + } + function isAsyncIife(node) { + if (node.expression.type !== utils_1.AST_NODE_TYPES.CallExpression) { + return false; + } + return (node.expression.callee.type === + utils_1.AST_NODE_TYPES.ArrowFunctionExpression || + node.expression.callee.type === utils_1.AST_NODE_TYPES.FunctionExpression); + } + function isValidRejectionHandler(rejectionHandler) { + return (services.program + .getTypeChecker() + .getTypeAtLocation(services.esTreeNodeToTSNodeMap.get(rejectionHandler)) + .getCallSignatures().length > 0); + } + function isUnhandledPromise(checker, node) { + if (node.type === utils_1.AST_NODE_TYPES.AssignmentExpression) { + return { isUnhandled: false }; + } + // First, check expressions whose resulting types may not be promise-like + if (node.type === utils_1.AST_NODE_TYPES.SequenceExpression) { + // Any child in a comma expression could return a potentially unhandled + // promise, so we check them all regardless of whether the final returned + // value is promise-like. + return (node.expressions + .map(item => isUnhandledPromise(checker, item)) + .find(result => result.isUnhandled) ?? { isUnhandled: false }); + } + if (!options.ignoreVoid && + node.type === utils_1.AST_NODE_TYPES.UnaryExpression && + node.operator === 'void') { + // Similarly, a `void` expression always returns undefined, so we need to + // see what's inside it without checking the type of the overall expression. + return isUnhandledPromise(checker, node.argument); + } + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + // Check the type. At this point it can't be unhandled if it isn't a promise + // or array thereof. + if (isPromiseArray(tsNode)) { + return { isUnhandled: true, promiseArray: true }; + } + // await expression addresses promises, but not promise arrays. + if (node.type === utils_1.AST_NODE_TYPES.AwaitExpression) { + // you would think this wouldn't be strictly necessary, since we're + // anyway checking the type of the expression, but, unfortunately TS + // reports the result of `await (promise as Promise & number)` + // as `Promise & number` instead of `number`. + return { isUnhandled: false }; + } + if (!isPromiseLike(tsNode)) { + return { isUnhandled: false }; + } + if (node.type === utils_1.AST_NODE_TYPES.CallExpression) { + // If the outer expression is a call, a `.catch()` or `.then()` with + // rejection handler handles the promise. + const promiseHandlingMethodCall = (0, promiseUtils_1.parseCatchCall)(node, context) ?? (0, promiseUtils_1.parseThenCall)(node, context); + if (promiseHandlingMethodCall != null) { + const onRejected = promiseHandlingMethodCall.onRejected; + if (onRejected != null) { + if (isValidRejectionHandler(onRejected)) { + return { isUnhandled: false }; + } + return { isUnhandled: true, nonFunctionHandler: true }; + } + return { isUnhandled: true }; + } + const promiseFinallyCall = (0, promiseUtils_1.parseFinallyCall)(node, context); + if (promiseFinallyCall != null) { + return isUnhandledPromise(checker, promiseFinallyCall.object); + } + // All other cases are unhandled. + return { isUnhandled: true }; + } + if (node.type === utils_1.AST_NODE_TYPES.ConditionalExpression) { + // We must be getting the promise-like value from one of the branches of the + // ternary. Check them directly. + const alternateResult = isUnhandledPromise(checker, node.alternate); + if (alternateResult.isUnhandled) { + return alternateResult; + } + return isUnhandledPromise(checker, node.consequent); + } + if (node.type === utils_1.AST_NODE_TYPES.LogicalExpression) { + const leftResult = isUnhandledPromise(checker, node.left); + if (leftResult.isUnhandled) { + return leftResult; + } + return isUnhandledPromise(checker, node.right); + } + // Anything else is unhandled. + return { isUnhandled: true }; + } + function isPromiseArray(node) { + const type = checker.getTypeAtLocation(node); + for (const ty of tsutils + .unionConstituents(type) + .map(t => checker.getApparentType(t))) { + if (checker.isArrayType(ty)) { + const arrayType = checker.getTypeArguments(ty)[0]; + if (isPromiseLike(node, arrayType)) { + return true; + } + } + if (checker.isTupleType(ty)) { + for (const tupleElementType of checker.getTypeArguments(ty)) { + if (isPromiseLike(node, tupleElementType)) { + return true; + } + } + } + } + return false; + } + function isPromiseLike(node, type) { + type ??= checker.getTypeAtLocation(node); + // The highest priority is to allow anything allowlisted + if ((0, util_1.typeMatchesSomeSpecifier)(type, allowForKnownSafePromises, services.program)) { + return false; + } + // Otherwise, we always consider the built-in Promise to be Promise-like... + const typeParts = tsutils.unionConstituents(checker.getApparentType(type)); + if (typeParts.some(typePart => (0, util_1.isBuiltinSymbolLike)(services.program, typePart, 'Promise'))) { + return true; + } + // ...and only check all Thenables if explicitly told to + if (!checkThenables) { + return false; + } + // Modified from tsutils.isThenable() to only consider thenables which can be + // rejected/caught via a second parameter. Original source (MIT licensed): + // + // https://github.com/ajafff/tsutils/blob/49d0d31050b44b81e918eae4fbaf1dfe7b7286af/util/type.ts#L95-L125 + for (const ty of typeParts) { + const then = ty.getProperty('then'); + if (then == null) { + continue; + } + const thenType = checker.getTypeOfSymbolAtLocation(then, node); + if (hasMatchingSignature(thenType, signature => signature.parameters.length >= 2 && + isFunctionParam(checker, signature.parameters[0], node) && + isFunctionParam(checker, signature.parameters[1], node))) { + return true; + } + } + return false; + } + }, +}); +function hasMatchingSignature(type, matcher) { + for (const t of tsutils.unionConstituents(type)) { + if (t.getCallSignatures().some(matcher)) { + return true; + } + } + return false; +} +function isFunctionParam(checker, param, node) { + const type = checker.getApparentType(checker.getTypeOfSymbolAtLocation(param, node)); + for (const t of tsutils.unionConstituents(type)) { + if (t.getCallSignatures().length !== 0) { + return true; + } + } + return false; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-for-in-array.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-for-in-array.d.ts new file mode 100644 index 00000000..1ad72d62 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-for-in-array.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"forInViolation", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-for-in-array.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-for-in-array.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-for-in-array.d.ts.map new file mode 100644 index 00000000..7e2f9550 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-for-in-array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-for-in-array.d.ts","sourceRoot":"","sources":["../../src/rules/no-for-in-array.ts"],"names":[],"mappings":";AAUA,wBAiCG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-for-in-array.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-for-in-array.js new file mode 100644 index 00000000..95f3e8b7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-for-in-array.js @@ -0,0 +1,86 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const getForStatementHeadLoc_1 = require("../util/getForStatementHeadLoc"); +exports.default = (0, util_1.createRule)({ + name: 'no-for-in-array', + meta: { + type: 'problem', + docs: { + description: 'Disallow iterating over an array with a for-in loop', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + forInViolation: 'For-in loops over arrays skips holes, returns indices as strings, and may visit the prototype chain or other enumerable properties. Use a more robust iteration method such as for-of or array.forEach instead.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + return { + ForInStatement(node) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node.right); + if (isArrayLike(checker, type)) { + context.report({ + loc: (0, getForStatementHeadLoc_1.getForStatementHeadLoc)(context.sourceCode, node), + messageId: 'forInViolation', + }); + } + }, + }; + }, +}); +function isArrayLike(checker, type) { + return isTypeRecurser(type, t => t.getNumberIndexType() != null && hasArrayishLength(checker, t)); +} +function hasArrayishLength(checker, type) { + const lengthProperty = type.getProperty('length'); + if (lengthProperty == null) { + return false; + } + return tsutils.isTypeFlagSet(checker.getTypeOfSymbol(lengthProperty), ts.TypeFlags.NumberLike); +} +function isTypeRecurser(type, predicate) { + if (type.isUnionOrIntersection()) { + return type.types.some(t => isTypeRecurser(t, predicate)); + } + return predicate(type); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.d.ts new file mode 100644 index 00000000..94f1ffbe --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noFunctionConstructor" | "noImpliedEvalError", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-implied-eval.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.d.ts.map new file mode 100644 index 00000000..319aedf4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-implied-eval.d.ts","sourceRoot":"","sources":["../../src/rules/no-implied-eval.ts"],"names":[],"mappings":";AAsBA,wBA6IG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.js new file mode 100644 index 00000000..52c745ed --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.js @@ -0,0 +1,152 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const FUNCTION_CONSTRUCTOR = 'Function'; +const GLOBAL_CANDIDATES = new Set(['global', 'globalThis', 'window']); +const EVAL_LIKE_FUNCTIONS = new Set([ + 'execScript', + 'setImmediate', + 'setInterval', + 'setTimeout', +]); +exports.default = (0, util_1.createRule)({ + name: 'no-implied-eval', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow the use of `eval()`-like functions', + extendsBaseRule: true, + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + noFunctionConstructor: 'Implied eval. Do not use the Function constructor to create functions.', + noImpliedEvalError: 'Implied eval. Consider passing a function.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function getCalleeName(node) { + if (node.type === utils_1.AST_NODE_TYPES.Identifier) { + return node.name; + } + if (node.type === utils_1.AST_NODE_TYPES.MemberExpression && + node.object.type === utils_1.AST_NODE_TYPES.Identifier && + GLOBAL_CANDIDATES.has(node.object.name)) { + if (node.property.type === utils_1.AST_NODE_TYPES.Identifier) { + return node.property.name; + } + if (node.property.type === utils_1.AST_NODE_TYPES.Literal && + typeof node.property.value === 'string') { + return node.property.value; + } + } + return null; + } + function isFunctionType(node) { + const type = services.getTypeAtLocation(node); + const symbol = type.getSymbol(); + if (symbol && + tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Function | ts.SymbolFlags.Method)) { + return true; + } + if ((0, util_1.isBuiltinSymbolLike)(services.program, type, FUNCTION_CONSTRUCTOR)) { + return true; + } + const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call); + return signatures.length > 0; + } + function isBind(node) { + return node.type === utils_1.AST_NODE_TYPES.MemberExpression + ? isBind(node.property) + : node.type === utils_1.AST_NODE_TYPES.Identifier && node.name === 'bind'; + } + function isFunction(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.ArrowFunctionExpression: + case utils_1.AST_NODE_TYPES.FunctionDeclaration: + case utils_1.AST_NODE_TYPES.FunctionExpression: + return true; + case utils_1.AST_NODE_TYPES.Literal: + case utils_1.AST_NODE_TYPES.TemplateLiteral: + return false; + case utils_1.AST_NODE_TYPES.CallExpression: + return isBind(node.callee) || isFunctionType(node); + default: + return isFunctionType(node); + } + } + function checkImpliedEval(node) { + const calleeName = getCalleeName(node.callee); + if (calleeName == null) { + return; + } + if (calleeName === FUNCTION_CONSTRUCTOR) { + const type = services.getTypeAtLocation(node.callee); + const symbol = type.getSymbol(); + if (symbol) { + if ((0, util_1.isBuiltinSymbolLike)(services.program, type, 'FunctionConstructor')) { + context.report({ node, messageId: 'noFunctionConstructor' }); + return; + } + } + else { + context.report({ node, messageId: 'noFunctionConstructor' }); + return; + } + } + if (node.arguments.length === 0) { + return; + } + const [handler] = node.arguments; + if (EVAL_LIKE_FUNCTIONS.has(calleeName) && + !isFunction(handler) && + (0, util_1.isReferenceToGlobalFunction)(calleeName, node, context.sourceCode)) { + context.report({ node: handler, messageId: 'noImpliedEvalError' }); + } + } + return { + CallExpression: checkImpliedEval, + NewExpression: checkImpliedEval, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-import-type-side-effects.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-import-type-side-effects.d.ts new file mode 100644 index 00000000..d04e2828 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-import-type-side-effects.d.ts @@ -0,0 +1,6 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = []; +export type MessageIds = 'useTopLevelQualifier'; +declare const _default: TSESLint.RuleModule<"useTopLevelQualifier", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-import-type-side-effects.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-import-type-side-effects.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-import-type-side-effects.d.ts.map new file mode 100644 index 00000000..467025d8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-import-type-side-effects.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-import-type-side-effects.d.ts","sourceRoot":"","sources":["../../src/rules/no-import-type-side-effects.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAYnE,MAAM,MAAM,OAAO,GAAG,EAAE,CAAC;AACzB,MAAM,MAAM,UAAU,GAAG,sBAAsB,CAAC;;AAEhD,wBAqEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-import-type-side-effects.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-import-type-side-effects.js new file mode 100644 index 00000000..e4e09b7f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-import-type-side-effects.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-import-type-side-effects', + meta: { + type: 'problem', + docs: { + description: 'Enforce the use of top-level import type qualifier when an import only has specifiers with inline type qualifiers', + }, + fixable: 'code', + messages: { + useTopLevelQualifier: 'TypeScript will only remove the inline type specifiers which will leave behind a side effect import at runtime. Convert this to a top-level type qualifier to properly remove the entire import.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + return { + 'ImportDeclaration[importKind!="type"]'(node) { + if (node.specifiers.length === 0) { + return; + } + const specifiers = []; + for (const specifier of node.specifiers) { + if (specifier.type !== utils_1.AST_NODE_TYPES.ImportSpecifier || + specifier.importKind !== 'type') { + return; + } + specifiers.push(specifier); + } + context.report({ + node, + messageId: 'useTopLevelQualifier', + fix(fixer) { + const fixes = []; + for (const specifier of specifiers) { + const qualifier = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(specifier, util_1.isTypeKeyword), util_1.NullThrowsReasons.MissingToken('type keyword', 'import specifier')); + fixes.push(fixer.removeRange([ + qualifier.range[0], + specifier.imported.range[0], + ])); + } + const importKeyword = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node, util_1.isImportKeyword), util_1.NullThrowsReasons.MissingToken('import keyword', 'import')); + fixes.push(fixer.insertTextAfter(importKeyword, ' type')); + return fixes; + }, + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-inferrable-types.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-inferrable-types.d.ts new file mode 100644 index 00000000..93a048e1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-inferrable-types.d.ts @@ -0,0 +1,10 @@ +export type Options = [ + { + ignoreParameters?: boolean; + ignoreProperties?: boolean; + } +]; +export type MessageIds = 'noInferrableType'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noInferrableType", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-inferrable-types.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-inferrable-types.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-inferrable-types.d.ts.map new file mode 100644 index 00000000..5c08dd2a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-inferrable-types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-inferrable-types.d.ts","sourceRoot":"","sources":["../../src/rules/no-inferrable-types.ts"],"names":[],"mappings":"AAYA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,gBAAgB,CAAC,EAAE,OAAO,CAAC;QAC3B,gBAAgB,CAAC,EAAE,OAAO,CAAC;KAC5B;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,kBAAkB,CAAC;;AAE5C,wBAgRG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-inferrable-types.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-inferrable-types.js new file mode 100644 index 00000000..622ac2db --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-inferrable-types.js @@ -0,0 +1,182 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-inferrable-types', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow explicit type declarations for variables or parameters initialized to a number, string, or boolean', + recommended: 'stylistic', + }, + fixable: 'code', + messages: { + noInferrableType: 'Type {{type}} trivially inferred from a {{type}} literal, remove type annotation.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + ignoreParameters: { + type: 'boolean', + description: 'Whether to ignore function parameters.', + }, + ignoreProperties: { + type: 'boolean', + description: 'Whether to ignore class properties.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + ignoreParameters: false, + ignoreProperties: false, + }, + ], + create(context, [{ ignoreParameters, ignoreProperties }]) { + function isFunctionCall(init, callName) { + const node = (0, util_1.skipChainExpression)(init); + return (node.type === utils_1.AST_NODE_TYPES.CallExpression && + node.callee.type === utils_1.AST_NODE_TYPES.Identifier && + node.callee.name === callName); + } + function isLiteral(init, typeName) { + return (init.type === utils_1.AST_NODE_TYPES.Literal && typeof init.value === typeName); + } + function isIdentifier(init, ...names) { + return (init.type === utils_1.AST_NODE_TYPES.Identifier && names.includes(init.name)); + } + function hasUnaryPrefix(init, ...operators) { + return (init.type === utils_1.AST_NODE_TYPES.UnaryExpression && + operators.includes(init.operator)); + } + const keywordMap = { + [utils_1.AST_NODE_TYPES.TSBigIntKeyword]: 'bigint', + [utils_1.AST_NODE_TYPES.TSBooleanKeyword]: 'boolean', + [utils_1.AST_NODE_TYPES.TSNullKeyword]: 'null', + [utils_1.AST_NODE_TYPES.TSNumberKeyword]: 'number', + [utils_1.AST_NODE_TYPES.TSStringKeyword]: 'string', + [utils_1.AST_NODE_TYPES.TSSymbolKeyword]: 'symbol', + [utils_1.AST_NODE_TYPES.TSUndefinedKeyword]: 'undefined', + }; + /** + * Returns whether a node has an inferrable value or not + */ + function isInferrable(annotation, init) { + switch (annotation.type) { + case utils_1.AST_NODE_TYPES.TSBigIntKeyword: { + // note that bigint cannot have + prefixed to it + const unwrappedInit = hasUnaryPrefix(init, '-') + ? init.argument + : init; + return (isFunctionCall(unwrappedInit, 'BigInt') || + unwrappedInit.type === utils_1.AST_NODE_TYPES.Literal); + } + case utils_1.AST_NODE_TYPES.TSBooleanKeyword: + return (hasUnaryPrefix(init, '!') || + isFunctionCall(init, 'Boolean') || + isLiteral(init, 'boolean')); + case utils_1.AST_NODE_TYPES.TSNumberKeyword: { + const unwrappedInit = hasUnaryPrefix(init, '+', '-') + ? init.argument + : init; + return (isIdentifier(unwrappedInit, 'Infinity', 'NaN') || + isFunctionCall(unwrappedInit, 'Number') || + isLiteral(unwrappedInit, 'number')); + } + case utils_1.AST_NODE_TYPES.TSNullKeyword: + return init.type === utils_1.AST_NODE_TYPES.Literal && init.value == null; + case utils_1.AST_NODE_TYPES.TSStringKeyword: + return (isFunctionCall(init, 'String') || + isLiteral(init, 'string') || + init.type === utils_1.AST_NODE_TYPES.TemplateLiteral); + case utils_1.AST_NODE_TYPES.TSSymbolKeyword: + return isFunctionCall(init, 'Symbol'); + case utils_1.AST_NODE_TYPES.TSTypeReference: { + if (annotation.typeName.type === utils_1.AST_NODE_TYPES.Identifier && + annotation.typeName.name === 'RegExp') { + const isRegExpLiteral = init.type === utils_1.AST_NODE_TYPES.Literal && + init.value instanceof RegExp; + const isRegExpNewCall = init.type === utils_1.AST_NODE_TYPES.NewExpression && + init.callee.type === utils_1.AST_NODE_TYPES.Identifier && + init.callee.name === 'RegExp'; + const isRegExpCall = isFunctionCall(init, 'RegExp'); + return isRegExpLiteral || isRegExpCall || isRegExpNewCall; + } + return false; + } + case utils_1.AST_NODE_TYPES.TSUndefinedKeyword: + return (hasUnaryPrefix(init, 'void') || isIdentifier(init, 'undefined')); + } + return false; + } + /** + * Reports an inferrable type declaration, if any + */ + function reportInferrableType(node, typeNode, initNode) { + if (!typeNode || !initNode) { + return; + } + if (!isInferrable(typeNode.typeAnnotation, initNode)) { + return; + } + const type = typeNode.typeAnnotation.type === utils_1.AST_NODE_TYPES.TSTypeReference + ? // TODO - if we add more references + 'RegExp' + : keywordMap[typeNode.typeAnnotation.type]; + context.report({ + node, + messageId: 'noInferrableType', + data: { + type, + }, + *fix(fixer) { + if ((node.type === utils_1.AST_NODE_TYPES.AssignmentPattern && + node.left.optional) || + (node.type === utils_1.AST_NODE_TYPES.PropertyDefinition && node.definite)) { + yield fixer.remove((0, util_1.nullThrows)(context.sourceCode.getTokenBefore(typeNode), util_1.NullThrowsReasons.MissingToken('token before', 'type node'))); + } + yield fixer.remove(typeNode); + }, + }); + } + function inferrableVariableVisitor(node) { + reportInferrableType(node, node.id.typeAnnotation, node.init); + } + function inferrableParameterVisitor(node) { + if (ignoreParameters) { + return; + } + node.params.forEach(param => { + if (param.type === utils_1.AST_NODE_TYPES.TSParameterProperty) { + param = param.parameter; + } + if (param.type === utils_1.AST_NODE_TYPES.AssignmentPattern) { + reportInferrableType(param, param.left.typeAnnotation, param.right); + } + }); + } + function inferrablePropertyVisitor(node) { + // We ignore `readonly` because of Microsoft/TypeScript#14416 + // Essentially a readonly property without a type + // will result in its value being the type, leading to + // compile errors if the type is stripped. + if (ignoreProperties || node.readonly || node.optional) { + return; + } + reportInferrableType(node, node.typeAnnotation, node.value); + } + return { + AccessorProperty: inferrablePropertyVisitor, + ArrowFunctionExpression: inferrableParameterVisitor, + FunctionDeclaration: inferrableParameterVisitor, + FunctionExpression: inferrableParameterVisitor, + PropertyDefinition: inferrablePropertyVisitor, + VariableDeclarator: inferrableVariableVisitor, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-this.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-this.d.ts new file mode 100644 index 00000000..9709160c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-this.d.ts @@ -0,0 +1,14 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpectedThis", [({ + capIsConstructor?: boolean; +} | undefined)?], unknown, { + ThisExpression(node: TSESTree.ThisExpression): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unexpectedThis", [({ + capIsConstructor?: boolean; +} | undefined)?], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-invalid-this.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-this.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-this.d.ts.map new file mode 100644 index 00000000..846c882a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-this.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-invalid-this.d.ts","sourceRoot":"","sources":["../../src/rules/no-invalid-this.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;;;yBA0Fu1R,SAAU,cAAc;EA1Fx0R,CAAC;AAEtD,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;;;AAItE,wBAkFG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-this.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-this.js new file mode 100644 index 00000000..a3d80e7b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-this.js @@ -0,0 +1,75 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-invalid-this'); +const defaultOptions = [{ capIsConstructor: true }]; +exports.default = (0, util_1.createRule)({ + name: 'no-invalid-this', + meta: { + type: 'suggestion', + defaultOptions, + docs: { + description: 'Disallow `this` keywords outside of classes or class-like objects', + extendsBaseRule: true, + }, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: baseRule.meta.schema, + }, + defaultOptions, + create(context) { + const rules = baseRule.create(context); + /** + * Since function definitions can be nested we use a stack storing if "this" is valid in the current context. + * + * Example: + * + * function a(this: number) { // valid "this" + * function b() { + * console.log(this); // invalid "this" + * } + * } + * + * When parsing the function declaration of "a" the stack will be: [true] + * When parsing the function declaration of "b" the stack will be: [true, false] + */ + const thisIsValidStack = []; + return { + ...rules, + AccessorProperty() { + thisIsValidStack.push(true); + }, + 'AccessorProperty:exit'() { + thisIsValidStack.pop(); + }, + FunctionDeclaration(node) { + thisIsValidStack.push(node.params.some(param => param.type === utils_1.AST_NODE_TYPES.Identifier && param.name === 'this')); + }, + 'FunctionDeclaration:exit'() { + thisIsValidStack.pop(); + }, + FunctionExpression(node) { + thisIsValidStack.push(node.params.some(param => param.type === utils_1.AST_NODE_TYPES.Identifier && param.name === 'this')); + }, + 'FunctionExpression:exit'() { + thisIsValidStack.pop(); + }, + PropertyDefinition() { + thisIsValidStack.push(true); + }, + 'PropertyDefinition:exit'() { + thisIsValidStack.pop(); + }, + ThisExpression(node) { + const thisIsValidHere = thisIsValidStack[thisIsValidStack.length - 1]; + if (thisIsValidHere) { + return; + } + // baseRule's work + rules.ThisExpression(node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-void-type.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-void-type.d.ts new file mode 100644 index 00000000..dcfd4f49 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-void-type.d.ts @@ -0,0 +1,8 @@ +export interface Options { + allowAsThisParameter?: boolean; + allowInGenericTypeArguments?: boolean | [string, ...string[]]; +} +export type MessageIds = 'invalidVoidForGeneric' | 'invalidVoidNotReturn' | 'invalidVoidNotReturnOrGeneric' | 'invalidVoidNotReturnOrThisParam' | 'invalidVoidNotReturnOrThisParamOrGeneric' | 'invalidVoidUnionConstituent'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-invalid-void-type.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-void-type.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-void-type.d.ts.map new file mode 100644 index 00000000..151bafc7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-void-type.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-invalid-void-type.d.ts","sourceRoot":"","sources":["../../src/rules/no-invalid-void-type.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,OAAO;IACtB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,2BAA2B,CAAC,EAAE,OAAO,GAAG,CAAC,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;CAC/D;AAED,MAAM,MAAM,UAAU,GAClB,uBAAuB,GACvB,sBAAsB,GACtB,+BAA+B,GAC/B,iCAAiC,GACjC,0CAA0C,GAC1C,6BAA6B,CAAC;;AAElC,wBA2OG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-void-type.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-void-type.js new file mode 100644 index 00000000..ba54c514 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-invalid-void-type.js @@ -0,0 +1,210 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-invalid-void-type', + meta: { + type: 'problem', + docs: { + description: 'Disallow `void` type outside of generic or return types', + recommended: 'strict', + }, + messages: { + invalidVoidForGeneric: '{{ generic }} may not have void as a type argument.', + invalidVoidNotReturn: 'void is only valid as a return type.', + invalidVoidNotReturnOrGeneric: 'void is only valid as a return type or generic type argument.', + invalidVoidNotReturnOrThisParam: 'void is only valid as return type or type of `this` parameter.', + invalidVoidNotReturnOrThisParamOrGeneric: 'void is only valid as a return type or generic type argument or the type of a `this` parameter.', + invalidVoidUnionConstituent: 'void is not valid as a constituent in a union type', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowAsThisParameter: { + type: 'boolean', + description: 'Whether a `this` parameter of a function may be `void`.', + }, + allowInGenericTypeArguments: { + description: 'Whether `void` can be used as a valid value for generic type parameters.', + oneOf: [ + { + type: 'boolean', + description: 'Whether `void` can be used as a valid value for all generic type parameters.', + }, + { + type: 'array', + description: 'Allowlist of types that may accept `void` as a generic type parameter.', + items: { type: 'string' }, + minItems: 1, + }, + ], + }, + }, + }, + ], + }, + defaultOptions: [ + { allowAsThisParameter: false, allowInGenericTypeArguments: true }, + ], + create(context, [{ allowAsThisParameter, allowInGenericTypeArguments }]) { + const validParents = [ + utils_1.AST_NODE_TYPES.TSTypeAnnotation, // + ]; + const invalidGrandParents = [ + utils_1.AST_NODE_TYPES.TSPropertySignature, + utils_1.AST_NODE_TYPES.CallExpression, + utils_1.AST_NODE_TYPES.PropertyDefinition, + utils_1.AST_NODE_TYPES.AccessorProperty, + utils_1.AST_NODE_TYPES.Identifier, + ]; + const validUnionMembers = [ + utils_1.AST_NODE_TYPES.TSVoidKeyword, + utils_1.AST_NODE_TYPES.TSNeverKeyword, + ]; + if (allowInGenericTypeArguments === true) { + validParents.push(utils_1.AST_NODE_TYPES.TSTypeParameterInstantiation); + } + /** + * @brief check if the given void keyword is used as a valid generic type + * + * reports if the type parametrized by void is not in the allowlist, or + * allowInGenericTypeArguments is false. + * no-op if the given void keyword is not used as generic type + */ + function checkGenericTypeArgument(node) { + // only matches T<..., void, ...> + // extra check for precaution + /* istanbul ignore next */ + if (node.parent.type !== utils_1.AST_NODE_TYPES.TSTypeParameterInstantiation || + node.parent.parent.type !== utils_1.AST_NODE_TYPES.TSTypeReference) { + return; + } + // check allowlist + if (Array.isArray(allowInGenericTypeArguments)) { + const fullyQualifiedName = context.sourceCode + .getText(node.parent.parent.typeName) + .replaceAll(' ', ''); + if (!allowInGenericTypeArguments + .map(s => s.replaceAll(' ', '')) + .includes(fullyQualifiedName)) { + context.report({ + node, + messageId: 'invalidVoidForGeneric', + data: { generic: fullyQualifiedName }, + }); + } + return; + } + if (!allowInGenericTypeArguments) { + context.report({ + node, + messageId: allowAsThisParameter + ? 'invalidVoidNotReturnOrThisParam' + : 'invalidVoidNotReturn', + }); + } + } + /** + * @brief checks if the generic type parameter defaults to void + */ + function checkDefaultVoid(node, parentNode) { + if (parentNode.default !== node) { + context.report({ + node, + messageId: getNotReturnOrGenericMessageId(node), + }); + } + } + /** + * @brief checks that a union containing void is valid + * @return true if every member of the union is specified as a valid type in + * validUnionMembers, or is a valid generic type parametrized by void + */ + function isValidUnionType(node) { + return node.types.every(member => validUnionMembers.includes(member.type) || + // allows any T<..., void, ...> here, checked by checkGenericTypeArgument + (member.type === utils_1.AST_NODE_TYPES.TSTypeReference && + member.typeArguments?.type === + utils_1.AST_NODE_TYPES.TSTypeParameterInstantiation && + member.typeArguments.params + .map(param => param.type) + .includes(utils_1.AST_NODE_TYPES.TSVoidKeyword))); + } + return { + TSVoidKeyword(node) { + // checks T<..., void, ...> against specification of allowInGenericArguments option + if (node.parent.type === utils_1.AST_NODE_TYPES.TSTypeParameterInstantiation && + node.parent.parent.type === utils_1.AST_NODE_TYPES.TSTypeReference) { + checkGenericTypeArgument(node); + return; + } + // allow if allowInGenericTypeArguments is specified, and report if the generic type parameter extends void + if (allowInGenericTypeArguments && + node.parent.type === utils_1.AST_NODE_TYPES.TSTypeParameter && + node.parent.default?.type === utils_1.AST_NODE_TYPES.TSVoidKeyword) { + checkDefaultVoid(node, node.parent); + return; + } + // union w/ void must contain types from validUnionMembers, or a valid generic void type + if (node.parent.type === utils_1.AST_NODE_TYPES.TSUnionType && + isValidUnionType(node.parent)) { + return; + } + // using `void` as part of the return type of function overloading implementation + if (node.parent.type === utils_1.AST_NODE_TYPES.TSUnionType) { + const declaringFunction = getParentFunctionDeclarationNode(node.parent); + if (declaringFunction && + (0, util_1.hasOverloadSignatures)(declaringFunction, context)) { + return; + } + } + // this parameter is ok to be void. + if (allowAsThisParameter && + node.parent.type === utils_1.AST_NODE_TYPES.TSTypeAnnotation && + node.parent.parent.type === utils_1.AST_NODE_TYPES.Identifier && + node.parent.parent.name === 'this') { + return; + } + // default cases + if (validParents.includes(node.parent.type) && + // https://github.com/typescript-eslint/typescript-eslint/issues/6225 + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + !invalidGrandParents.includes(node.parent.parent.type)) { + return; + } + context.report({ + node, + messageId: allowInGenericTypeArguments && allowAsThisParameter + ? 'invalidVoidNotReturnOrThisParamOrGeneric' + : allowInGenericTypeArguments + ? getNotReturnOrGenericMessageId(node) + : allowAsThisParameter + ? 'invalidVoidNotReturnOrThisParam' + : 'invalidVoidNotReturn', + }); + }, + }; + }, +}); +function getNotReturnOrGenericMessageId(node) { + return node.parent.type === utils_1.AST_NODE_TYPES.TSUnionType + ? 'invalidVoidUnionConstituent' + : 'invalidVoidNotReturnOrGeneric'; +} +function getParentFunctionDeclarationNode(node) { + let current = node.parent; + while (current) { + if (current.type === utils_1.AST_NODE_TYPES.FunctionDeclaration) { + return current; + } + if (current.type === utils_1.AST_NODE_TYPES.MethodDefinition && + current.value.body != null) { + return current; + } + current = current.parent; + } + return null; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loop-func.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loop-func.d.ts new file mode 100644 index 00000000..60594eb3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loop-func.d.ts @@ -0,0 +1,12 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: TSESLint.RuleModule<"unsafeRefs", [], unknown, { + ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression): void; + FunctionDeclaration(node: TSESTree.FunctionDeclaration): void; + FunctionExpression(node: TSESTree.FunctionExpression): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: TSESLint.RuleModule<"unsafeRefs", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-loop-func.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loop-func.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loop-func.d.ts.map new file mode 100644 index 00000000..da1160e4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loop-func.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-loop-func.d.ts","sourceRoot":"","sources":["../../src/rules/no-loop-func.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAInE,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;kCAgMoB,SAC1B,uBAAgB;8BACC,SAAU,mBAElC;6BAAuC,SAAU,kBAEnC;EAtMmC,CAAC;AAEnD,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;AAEtE,wBA0OG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loop-func.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loop-func.js new file mode 100644 index 00000000..29b85796 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loop-func.js @@ -0,0 +1,187 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-loop-func'); +exports.default = (0, util_1.createRule)({ + name: 'no-loop-func', + meta: { + type: 'suggestion', + // defaultOptions, -- base rule does not use defaultOptions + docs: { + description: 'Disallow function declarations that contain unsafe references inside loop statements', + extendsBaseRule: true, + }, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: [], + }, + defaultOptions: [], + create(context) { + const SKIPPED_IIFE_NODES = new Set(); + /** + * Gets the containing loop node of a specified node. + * + * We don't need to check nested functions, so this ignores those. + * `Scope.through` contains references of nested functions. + * + * @param node An AST node to get. + * @returns The containing loop node of the specified node, or `null`. + */ + function getContainingLoopNode(node) { + for (let currentNode = node; currentNode.parent; currentNode = currentNode.parent) { + const parent = currentNode.parent; + switch (parent.type) { + case utils_1.AST_NODE_TYPES.WhileStatement: + case utils_1.AST_NODE_TYPES.DoWhileStatement: + return parent; + case utils_1.AST_NODE_TYPES.ForStatement: + // `init` is outside of the loop. + if (parent.init !== currentNode) { + return parent; + } + break; + case utils_1.AST_NODE_TYPES.ForInStatement: + case utils_1.AST_NODE_TYPES.ForOfStatement: + // `right` is outside of the loop. + if (parent.right !== currentNode) { + return parent; + } + break; + case utils_1.AST_NODE_TYPES.ArrowFunctionExpression: + case utils_1.AST_NODE_TYPES.FunctionExpression: + case utils_1.AST_NODE_TYPES.FunctionDeclaration: + // We don't need to check nested functions. + // We need to check nested functions only in case of IIFE. + if (SKIPPED_IIFE_NODES.has(parent)) { + break; + } + return null; + default: + break; + } + } + return null; + } + /** + * Gets the containing loop node of a given node. + * If the loop was nested, this returns the most outer loop. + * @param node A node to get. This is a loop node. + * @param excludedNode A node that the result node should not include. + * @returns The most outer loop node. + */ + function getTopLoopNode(node, excludedNode) { + const border = excludedNode ? excludedNode.range[1] : 0; + let retv = node; + let containingLoopNode = node; + while (containingLoopNode && containingLoopNode.range[0] >= border) { + retv = containingLoopNode; + containingLoopNode = getContainingLoopNode(containingLoopNode); + } + return retv; + } + /** + * Checks whether a given reference which refers to an upper scope's variable is + * safe or not. + * @param loopNode A containing loop node. + * @param reference A reference to check. + * @returns `true` if the reference is safe or not. + */ + function isSafe(loopNode, reference) { + const variable = reference.resolved; + const definition = variable?.defs[0]; + const declaration = definition?.parent; + const kind = declaration?.type === utils_1.AST_NODE_TYPES.VariableDeclaration + ? declaration.kind + : ''; + // type references are all safe + // this only really matters for global types that haven't been configured + if (reference.isTypeReference) { + return true; + } + // Variables which are declared by `const` is safe. + if (kind === 'const') { + return true; + } + /* + * Variables which are declared by `let` in the loop is safe. + * It's a different instance from the next loop step's. + */ + if (kind === 'let' && + declaration && + declaration.range[0] > loopNode.range[0] && + declaration.range[1] < loopNode.range[1]) { + return true; + } + /* + * WriteReferences which exist after this border are unsafe because those + * can modify the variable. + */ + const border = getTopLoopNode(loopNode, kind === 'let' ? declaration : null).range[0]; + /** + * Checks whether a given reference is safe or not. + * The reference is every reference of the upper scope's variable we are + * looking now. + * + * It's safe if the reference matches one of the following condition. + * - is readonly. + * - doesn't exist inside a local function and after the border. + * + * @param upperRef A reference to check. + * @returns `true` if the reference is safe. + */ + function isSafeReference(upperRef) { + const id = upperRef.identifier; + return (!upperRef.isWrite() || + (variable?.scope.variableScope === upperRef.from.variableScope && + id.range[0] < border)); + } + return variable?.references.every(isSafeReference) ?? false; + } + /** + * Reports functions which match the following condition: + * - has a loop node in ancestors. + * - has any references which refers to an unsafe variable. + * + * @param node The AST node to check. + */ + function checkForLoops(node) { + const loopNode = getContainingLoopNode(node); + if (!loopNode) { + return; + } + const references = context.sourceCode.getScope(node).through; + if (!(node.async || node.generator) && isIIFE(node)) { + const isFunctionExpression = node.type === utils_1.AST_NODE_TYPES.FunctionExpression; + // Check if the function is referenced elsewhere in the code + const isFunctionReferenced = isFunctionExpression && node.id + ? references.some(r => r.identifier.name === node.id?.name) + : false; + if (!isFunctionReferenced) { + SKIPPED_IIFE_NODES.add(node); + return; + } + } + const unsafeRefs = references + .filter(r => r.resolved && !isSafe(loopNode, r)) + .map(r => r.identifier.name); + if (unsafeRefs.length > 0) { + context.report({ + node, + messageId: 'unsafeRefs', + data: { varNames: `'${unsafeRefs.join("', '")}'` }, + }); + } + } + return { + ArrowFunctionExpression: checkForLoops, + FunctionDeclaration: checkForLoops, + FunctionExpression: checkForLoops, + }; + }, +}); +function isIIFE(node) { + return (node.parent.type === utils_1.AST_NODE_TYPES.CallExpression && + node.parent.callee === node); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loss-of-precision.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loss-of-precision.d.ts new file mode 100644 index 00000000..8f882ab7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loss-of-precision.d.ts @@ -0,0 +1,8 @@ +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +import { getESLintCoreRule } from '../util/getESLintCoreRule'; +declare const baseRule: ReturnType; +export type Options = InferOptionsTypeFromRule>; +export type MessageIds = InferMessageIdsTypeFromRule>; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noLossOfPrecision", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-loss-of-precision.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loss-of-precision.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loss-of-precision.d.ts.map new file mode 100644 index 00000000..d501d2e7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loss-of-precision.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-loss-of-precision.d.ts","sourceRoot":"","sources":["../../src/rules/no-loss-of-precision.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAGjB,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAE9D,QAAA,MAAM,QAAQ,EAAE,UAAU,CAAC,OAAO,iBAAiB,CAElD,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,WAAW,CAAC,OAAO,QAAQ,CAAC,CAAC,CAAC;AAC7E,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAClD,WAAW,CAAC,OAAO,QAAQ,CAAC,CAC7B,CAAC;;AAEF,wBA6BG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loss-of-precision.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loss-of-precision.js new file mode 100644 index 00000000..0c2b6a7b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-loss-of-precision.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-loss-of-precision'); +exports.default = (0, util_1.createRule)({ + name: 'no-loss-of-precision', + meta: { + type: 'problem', + // defaultOptions, -- base rule does not use defaultOptions + deprecated: { + deprecatedSince: '8.0.0', + replacedBy: [ + { + rule: { + name: 'no-loss-of-precision', + url: 'https://eslint.org/docs/latest/rules/no-loss-of-precision', + }, + }, + ], + url: 'https://github.com/typescript-eslint/typescript-eslint/pull/8832', + }, + docs: { + description: 'Disallow literal numbers that lose precision', + extendsBaseRule: true, + }, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: [], + }, + defaultOptions: [], + create(context) { + return baseRule.create(context); + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-magic-numbers.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-magic-numbers.d.ts new file mode 100644 index 00000000..540eaaf7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-magic-numbers.d.ts @@ -0,0 +1,28 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noMagic", [{ + detectObjects?: boolean; + enforceConst?: boolean; + ignore?: (number | string)[]; + ignoreArrayIndexes?: boolean; + ignoreEnums?: boolean; + ignoreNumericLiteralTypes?: boolean; + ignoreReadonlyClassProperties?: boolean; + ignoreTypeIndexes?: boolean; +}], unknown, { + Literal(node: TSESTree.Literal): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noMagic", [{ + detectObjects?: boolean; + enforceConst?: boolean; + ignore?: (number | string)[]; + ignoreArrayIndexes?: boolean; + ignoreEnums?: boolean; + ignoreNumericLiteralTypes?: boolean; + ignoreReadonlyClassProperties?: boolean; + ignoreTypeIndexes?: boolean; +}], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-magic-numbers.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-magic-numbers.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-magic-numbers.d.ts.map new file mode 100644 index 00000000..f9b0625b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-magic-numbers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-magic-numbers.d.ts","sourceRoot":"","sources":["../../src/rules/no-magic-numbers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAKzD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;;;;;;;;;;kBA+MQ,SAAU,OAAO;EA/Me,CAAC;AAEvD,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;;;;;;;;;;AA+BtE,wBA+FG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-magic-numbers.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-magic-numbers.js new file mode 100644 index 00000000..911ab469 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-magic-numbers.js @@ -0,0 +1,247 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-magic-numbers'); +// Extend base schema with additional property to ignore TS numeric literal types +const schema = (0, util_1.deepMerge)( +// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- https://github.com/microsoft/TypeScript/issues/17002 +Array.isArray(baseRule.meta.schema) + ? baseRule.meta.schema[0] + : baseRule.meta.schema, { + properties: { + ignoreEnums: { + type: 'boolean', + description: 'Whether enums used in TypeScript are considered okay.', + }, + ignoreNumericLiteralTypes: { + type: 'boolean', + description: 'Whether numbers used in TypeScript numeric literal types are considered okay.', + }, + ignoreReadonlyClassProperties: { + type: 'boolean', + description: 'Whether `readonly` class properties are considered okay.', + }, + ignoreTypeIndexes: { + type: 'boolean', + description: 'Whether numbers used to index types are okay.', + }, + }, +}); +exports.default = (0, util_1.createRule)({ + name: 'no-magic-numbers', + meta: { + type: 'suggestion', + // defaultOptions, -- base rule does not use defaultOptions + docs: { + description: 'Disallow magic numbers', + extendsBaseRule: true, + }, + messages: baseRule.meta.messages, + schema: [schema], + }, + defaultOptions: [ + { + detectObjects: false, + enforceConst: false, + ignore: [], + ignoreArrayIndexes: false, + ignoreEnums: false, + ignoreNumericLiteralTypes: false, + ignoreReadonlyClassProperties: false, + ignoreTypeIndexes: false, + }, + ], + create(context, [options]) { + const rules = baseRule.create(context); + const ignored = new Set((options.ignore ?? []).map(normalizeIgnoreValue)); + return { + Literal(node) { + // If it’s not a numeric literal we’re not interested + if (typeof node.value !== 'number' && typeof node.value !== 'bigint') { + return; + } + // This will be `true` if we’re configured to ignore this case (eg. it’s + // an enum and `ignoreEnums` is `true`). It will be `false` if we’re not + // configured to ignore this case. It will remain `undefined` if this is + // not one of our exception cases, and we’ll fall back to the base rule. + let isAllowed; + // Check if the node is ignored + if (ignored.has(normalizeLiteralValue(node, node.value))) { + isAllowed = true; + } + // Check if the node is a TypeScript enum declaration + else if (isParentTSEnumDeclaration(node)) { + isAllowed = options.ignoreEnums === true; + } + // Check TypeScript specific nodes for Numeric Literal + else if (isTSNumericLiteralType(node)) { + isAllowed = options.ignoreNumericLiteralTypes === true; + } + // Check if the node is a type index + else if (isAncestorTSIndexedAccessType(node)) { + isAllowed = options.ignoreTypeIndexes === true; + } + // Check if the node is a readonly class property + else if (isParentTSReadonlyPropertyDefinition(node)) { + isAllowed = options.ignoreReadonlyClassProperties === true; + } + // If we’ve hit a case where the ignore option is true we can return now + if (isAllowed === true) { + return; + } + // If the ignore option is *not* set we can report it now + if (isAllowed === false) { + let fullNumberNode = node; + let raw = node.raw; + if (node.parent.type === utils_1.AST_NODE_TYPES.UnaryExpression && + // the base rule only shows the operator for negative numbers + // https://github.com/eslint/eslint/blob/9dfc8501fb1956c90dc11e6377b4cb38a6bea65d/lib/rules/no-magic-numbers.js#L126 + node.parent.operator === '-') { + fullNumberNode = node.parent; + raw = `${node.parent.operator}${node.raw}`; + } + context.report({ + node: fullNumberNode, + messageId: 'noMagic', + data: { raw }, + }); + return; + } + // Let the base rule deal with the rest + rules.Literal(node); + }, + }; + }, +}); +/** + * Convert the value to bigint if it's a string. Otherwise, return the value as-is. + * @param value The value to normalize. + * @returns The normalized value. + */ +function normalizeIgnoreValue(value) { + if (typeof value === 'string') { + return BigInt(value.slice(0, -1)); + } + return value; +} +/** + * Converts the node to its numeric value, handling prefixed numbers (-1 / +1) + * @param node the node to normalize. + * @param value the node's value. + */ +function normalizeLiteralValue(node, value) { + if (node.parent.type === utils_1.AST_NODE_TYPES.UnaryExpression && + ['-', '+'].includes(node.parent.operator) && + node.parent.operator === '-') { + return -value; + } + return value; +} +/** + * Gets the true parent of the literal, handling prefixed numbers (-1 / +1) + */ +function getLiteralParent(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.UnaryExpression && + ['-', '+'].includes(node.parent.operator)) { + return node.parent.parent; + } + return node.parent; +} +/** + * Checks if the node grandparent is a Typescript type alias declaration + * @param node the node to be validated. + * @returns true if the node grandparent is a Typescript type alias declaration + * @private + */ +function isGrandparentTSTypeAliasDeclaration(node) { + return node.parent?.parent?.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration; +} +/** + * Checks if the node grandparent is a Typescript union type and its parent is a type alias declaration + * @param node the node to be validated. + * @returns true if the node grandparent is a Typescript union type and its parent is a type alias declaration + * @private + */ +function isGrandparentTSUnionType(node) { + if (node.parent?.parent?.type === utils_1.AST_NODE_TYPES.TSUnionType) { + return isGrandparentTSTypeAliasDeclaration(node.parent); + } + return false; +} +/** + * Checks if the node parent is a Typescript enum member + * @param node the node to be validated. + * @returns true if the node parent is a Typescript enum member + * @private + */ +function isParentTSEnumDeclaration(node) { + const parent = getLiteralParent(node); + return parent?.type === utils_1.AST_NODE_TYPES.TSEnumMember; +} +/** + * Checks if the node parent is a Typescript literal type + * @param node the node to be validated. + * @returns true if the node parent is a Typescript literal type + * @private + */ +function isParentTSLiteralType(node) { + return node.parent?.type === utils_1.AST_NODE_TYPES.TSLiteralType; +} +/** + * Checks if the node is a valid TypeScript numeric literal type. + * @param node the node to be validated. + * @returns true if the node is a TypeScript numeric literal type. + * @private + */ +function isTSNumericLiteralType(node) { + // For negative numbers, use the parent node + if (node.parent?.type === utils_1.AST_NODE_TYPES.UnaryExpression && + node.parent.operator === '-') { + node = node.parent; + } + // If the parent node is not a TSLiteralType, early return + if (!isParentTSLiteralType(node)) { + return false; + } + // If the grandparent is a TSTypeAliasDeclaration, ignore + if (isGrandparentTSTypeAliasDeclaration(node)) { + return true; + } + // If the grandparent is a TSUnionType and it's parent is a TSTypeAliasDeclaration, ignore + if (isGrandparentTSUnionType(node)) { + return true; + } + return false; +} +/** + * Checks if the node parent is a readonly class property + * @param node the node to be validated. + * @returns true if the node parent is a readonly class property + * @private + */ +function isParentTSReadonlyPropertyDefinition(node) { + const parent = getLiteralParent(node); + if (parent?.type === utils_1.AST_NODE_TYPES.PropertyDefinition && parent.readonly) { + return true; + } + return false; +} +/** + * Checks if the node is part of a type indexed access (eg. Foo[4]) + * @param node the node to be validated. + * @returns true if the node is part of an indexed access + * @private + */ +function isAncestorTSIndexedAccessType(node) { + // Handle unary expressions (eg. -4) + let ancestor = getLiteralParent(node); + // Go up another level while we’re part of a type union (eg. 1 | 2) or + // intersection (eg. 1 & 2) + while (ancestor?.parent?.type === utils_1.AST_NODE_TYPES.TSUnionType || + ancestor?.parent?.type === utils_1.AST_NODE_TYPES.TSIntersectionType) { + ancestor = ancestor.parent; + } + return ancestor?.parent?.type === utils_1.AST_NODE_TYPES.TSIndexedAccessType; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-meaningless-void-operator.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-meaningless-void-operator.d.ts new file mode 100644 index 00000000..d2d8c70b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-meaningless-void-operator.d.ts @@ -0,0 +1,9 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = [ + { + checkNever: boolean; + } +]; +declare const _default: TSESLint.RuleModule<"meaninglessVoidOperator" | "removeVoid", Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-meaningless-void-operator.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-meaningless-void-operator.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-meaningless-void-operator.d.ts.map new file mode 100644 index 00000000..e84ccff2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-meaningless-void-operator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-meaningless-void-operator.d.ts","sourceRoot":"","sources":["../../src/rules/no-meaningless-void-operator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAQnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,UAAU,EAAE,OAAO,CAAC;KACrB;CACF,CAAC;;AAEF,wBA8EG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-meaningless-void-operator.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-meaningless-void-operator.js new file mode 100644 index 00000000..f019f246 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-meaningless-void-operator.js @@ -0,0 +1,104 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-meaningless-void-operator', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow the `void` operator except when used to discard a value', + recommended: 'strict', + requiresTypeChecking: true, + }, + fixable: 'code', + hasSuggestions: true, + messages: { + meaninglessVoidOperator: "void operator shouldn't be used on {{type}}; it should convey that a return value is being ignored", + removeVoid: "Remove 'void'", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + checkNever: { + type: 'boolean', + default: false, + description: 'Whether to suggest removing `void` when the argument has type `never`.', + }, + }, + }, + ], + }, + defaultOptions: [{ checkNever: false }], + create(context, [{ checkNever }]) { + const services = utils_1.ESLintUtils.getParserServices(context); + const checker = services.program.getTypeChecker(); + return { + 'UnaryExpression[operator="void"]'(node) { + const fix = (fixer) => { + return fixer.removeRange([ + context.sourceCode.getTokens(node)[0].range[0], + context.sourceCode.getTokens(node)[1].range[0], + ]); + }; + const argType = services.getTypeAtLocation(node.argument); + const unionParts = tsutils.unionConstituents(argType); + if (unionParts.every(part => part.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined))) { + context.report({ + node, + messageId: 'meaninglessVoidOperator', + data: { type: checker.typeToString(argType) }, + fix, + }); + } + else if (checkNever && + unionParts.every(part => part.flags & + (ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Never))) { + context.report({ + node, + messageId: 'meaninglessVoidOperator', + data: { type: checker.typeToString(argType) }, + suggest: [{ messageId: 'removeVoid', fix }], + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-new.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-new.d.ts new file mode 100644 index 00000000..8a069a9b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-new.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"errorMessageClass" | "errorMessageInterface", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-misused-new.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-new.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-new.d.ts.map new file mode 100644 index 00000000..e60e9b14 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-new.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-misused-new.d.ts","sourceRoot":"","sources":["../../src/rules/no-misused-new.ts"],"names":[],"mappings":";AAMA,wBA2GG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-new.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-new.js new file mode 100644 index 00000000..2cbc6117 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-new.js @@ -0,0 +1,81 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-misused-new', + meta: { + type: 'problem', + docs: { + description: 'Enforce valid definition of `new` and `constructor`', + recommended: 'recommended', + }, + messages: { + errorMessageClass: 'Class cannot have method named `new`.', + errorMessageInterface: 'Interfaces cannot be constructed, only classes.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + /** + * @param node type to be inspected. + * @returns name of simple type or null + */ + function getTypeReferenceName(node) { + if (node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSTypeAnnotation: + return getTypeReferenceName(node.typeAnnotation); + case utils_1.AST_NODE_TYPES.TSTypeReference: + return getTypeReferenceName(node.typeName); + case utils_1.AST_NODE_TYPES.Identifier: + return node.name; + default: + break; + } + } + return null; + } + /** + * @param parent parent node. + * @param returnType type to be compared + */ + function isMatchingParentType(parent, returnType) { + if (parent && + (parent.type === utils_1.AST_NODE_TYPES.ClassDeclaration || + parent.type === utils_1.AST_NODE_TYPES.ClassExpression || + parent.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration) && + parent.id) { + return getTypeReferenceName(returnType) === parent.id.name; + } + return false; + } + return { + "ClassBody > MethodDefinition[key.name='new']"(node) { + if (node.value.type === utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression && + isMatchingParentType(node.parent.parent, node.value.returnType)) { + context.report({ + node, + messageId: 'errorMessageClass', + }); + } + }, + 'TSInterfaceBody > TSConstructSignatureDeclaration'(node) { + if (isMatchingParentType(node.parent.parent, node.returnType)) { + // constructor + context.report({ + node, + messageId: 'errorMessageInterface', + }); + } + }, + "TSMethodSignature[key.name='constructor']"(node) { + context.report({ + node, + messageId: 'errorMessageInterface', + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-promises.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-promises.d.ts new file mode 100644 index 00000000..b0629859 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-promises.d.ts @@ -0,0 +1,20 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = [ + { + checksConditionals?: boolean; + checksSpreads?: boolean; + checksVoidReturn?: boolean | ChecksVoidReturnOptions; + } +]; +export interface ChecksVoidReturnOptions { + arguments?: boolean; + attributes?: boolean; + inheritedMethods?: boolean; + properties?: boolean; + returns?: boolean; + variables?: boolean; +} +export type MessageId = 'conditional' | 'predicate' | 'spread' | 'voidReturnArgument' | 'voidReturnAttribute' | 'voidReturnInheritedMethod' | 'voidReturnProperty' | 'voidReturnReturnValue' | 'voidReturnVariable'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-misused-promises.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-promises.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-promises.d.ts.map new file mode 100644 index 00000000..12626e19 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-promises.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-misused-promises.d.ts","sourceRoot":"","sources":["../../src/rules/no-misused-promises.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAiBnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,aAAa,CAAC,EAAE,OAAO,CAAC;QACxB,gBAAgB,CAAC,EAAE,OAAO,GAAG,uBAAuB,CAAC;KACtD;CACF,CAAC;AAEF,MAAM,WAAW,uBAAuB;IACtC,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,MAAM,SAAS,GACjB,aAAa,GACb,WAAW,GACX,QAAQ,GACR,oBAAoB,GACpB,qBAAqB,GACrB,2BAA2B,GAC3B,oBAAoB,GACpB,uBAAuB,GACvB,oBAAoB,CAAC;;AAgCzB,wBAgmBG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-promises.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-promises.js new file mode 100644 index 00000000..e358b1a2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-promises.js @@ -0,0 +1,753 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +function parseChecksVoidReturn(checksVoidReturn) { + switch (checksVoidReturn) { + case false: + return false; + case true: + case undefined: + return { + arguments: true, + attributes: true, + inheritedMethods: true, + properties: true, + returns: true, + variables: true, + }; + default: + return { + arguments: checksVoidReturn.arguments ?? true, + attributes: checksVoidReturn.attributes ?? true, + inheritedMethods: checksVoidReturn.inheritedMethods ?? true, + properties: checksVoidReturn.properties ?? true, + returns: checksVoidReturn.returns ?? true, + variables: checksVoidReturn.variables ?? true, + }; + } +} +exports.default = (0, util_1.createRule)({ + name: 'no-misused-promises', + meta: { + type: 'problem', + docs: { + description: 'Disallow Promises in places not designed to handle them', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + conditional: 'Expected non-Promise value in a boolean conditional.', + predicate: 'Expected a non-Promise value to be returned.', + spread: 'Expected a non-Promise value to be spreaded in an object.', + voidReturnArgument: 'Promise returned in function argument where a void return was expected.', + voidReturnAttribute: 'Promise-returning function provided to attribute where a void return was expected.', + voidReturnInheritedMethod: "Promise-returning method provided where a void return was expected by extended/implemented type '{{ heritageTypeName }}'.", + voidReturnProperty: 'Promise-returning function provided to property where a void return was expected.', + voidReturnReturnValue: 'Promise-returning function provided to return value where a void return was expected.', + voidReturnVariable: 'Promise-returning function provided to variable where a void return was expected.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + checksConditionals: { + type: 'boolean', + description: 'Whether to warn when a Promise is provided to conditional statements.', + }, + checksSpreads: { + type: 'boolean', + description: 'Whether to warn when `...` spreading a `Promise`.', + }, + checksVoidReturn: { + description: 'Whether to warn when a Promise is returned from a function typed as returning `void`.', + oneOf: [ + { + type: 'boolean', + description: 'Whether to disable checking all asynchronous functions.', + }, + { + type: 'object', + additionalProperties: false, + description: 'Which forms of functions may have checking disabled.', + properties: { + arguments: { + type: 'boolean', + description: 'Disables checking an asynchronous function passed as argument where the parameter type expects a function that returns `void`.', + }, + attributes: { + type: 'boolean', + description: 'Disables checking an asynchronous function passed as a JSX attribute expected to be a function that returns `void`.', + }, + inheritedMethods: { + type: 'boolean', + description: 'Disables checking an asynchronous method in a type that extends or implements another type expecting that method to return `void`.', + }, + properties: { + type: 'boolean', + description: 'Disables checking an asynchronous function passed as an object property expected to be a function that returns `void`.', + }, + returns: { + type: 'boolean', + description: 'Disables checking an asynchronous function returned in a function whose return type is a function that returns `void`.', + }, + variables: { + type: 'boolean', + description: 'Disables checking an asynchronous function used as a variable whose return type is a function that returns `void`.', + }, + }, + }, + ], + }, + }, + }, + ], + }, + defaultOptions: [ + { + checksConditionals: true, + checksSpreads: true, + checksVoidReturn: true, + }, + ], + create(context, [{ checksConditionals, checksSpreads, checksVoidReturn }]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const checkedNodes = new Set(); + const conditionalChecks = { + 'CallExpression > MemberExpression': checkArrayPredicates, + ConditionalExpression: checkTestConditional, + DoWhileStatement: checkTestConditional, + ForStatement: checkTestConditional, + IfStatement: checkTestConditional, + LogicalExpression: checkConditional, + 'UnaryExpression[operator="!"]'(node) { + checkConditional(node.argument, true); + }, + WhileStatement: checkTestConditional, + }; + checksVoidReturn = parseChecksVoidReturn(checksVoidReturn); + const voidReturnChecks = checksVoidReturn + ? { + ...(checksVoidReturn.arguments && { + CallExpression: checkArguments, + NewExpression: checkArguments, + }), + ...(checksVoidReturn.attributes && { + JSXAttribute: checkJSXAttribute, + }), + ...(checksVoidReturn.inheritedMethods && { + ClassDeclaration: checkClassLikeOrInterfaceNode, + ClassExpression: checkClassLikeOrInterfaceNode, + TSInterfaceDeclaration: checkClassLikeOrInterfaceNode, + }), + ...(checksVoidReturn.properties && { + Property: checkProperty, + }), + ...(checksVoidReturn.returns && { + ReturnStatement: checkReturnStatement, + }), + ...(checksVoidReturn.variables && { + AssignmentExpression: checkAssignment, + VariableDeclarator: checkVariableDeclaration, + }), + } + : {}; + const spreadChecks = { + SpreadElement: checkSpread, + }; + /** + * A syntactic check to see if an annotated type is maybe a function type. + * This is a perf optimization to help avoid requesting types where possible + */ + function isPossiblyFunctionType(node) { + switch (node.typeAnnotation.type) { + case utils_1.AST_NODE_TYPES.TSConditionalType: + case utils_1.AST_NODE_TYPES.TSConstructorType: + case utils_1.AST_NODE_TYPES.TSFunctionType: + case utils_1.AST_NODE_TYPES.TSImportType: + case utils_1.AST_NODE_TYPES.TSIndexedAccessType: + case utils_1.AST_NODE_TYPES.TSInferType: + case utils_1.AST_NODE_TYPES.TSIntersectionType: + case utils_1.AST_NODE_TYPES.TSQualifiedName: + case utils_1.AST_NODE_TYPES.TSThisType: + case utils_1.AST_NODE_TYPES.TSTypeOperator: + case utils_1.AST_NODE_TYPES.TSTypeQuery: + case utils_1.AST_NODE_TYPES.TSTypeReference: + case utils_1.AST_NODE_TYPES.TSUnionType: + return true; + case utils_1.AST_NODE_TYPES.TSTypeLiteral: + return node.typeAnnotation.members.some(member => member.type === utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration || + member.type === utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration); + case utils_1.AST_NODE_TYPES.TSAbstractKeyword: + case utils_1.AST_NODE_TYPES.TSAnyKeyword: + case utils_1.AST_NODE_TYPES.TSArrayType: + case utils_1.AST_NODE_TYPES.TSAsyncKeyword: + case utils_1.AST_NODE_TYPES.TSBigIntKeyword: + case utils_1.AST_NODE_TYPES.TSBooleanKeyword: + case utils_1.AST_NODE_TYPES.TSDeclareKeyword: + case utils_1.AST_NODE_TYPES.TSExportKeyword: + case utils_1.AST_NODE_TYPES.TSIntrinsicKeyword: + case utils_1.AST_NODE_TYPES.TSLiteralType: + case utils_1.AST_NODE_TYPES.TSMappedType: + case utils_1.AST_NODE_TYPES.TSNamedTupleMember: + case utils_1.AST_NODE_TYPES.TSNeverKeyword: + case utils_1.AST_NODE_TYPES.TSNullKeyword: + case utils_1.AST_NODE_TYPES.TSNumberKeyword: + case utils_1.AST_NODE_TYPES.TSObjectKeyword: + case utils_1.AST_NODE_TYPES.TSOptionalType: + case utils_1.AST_NODE_TYPES.TSPrivateKeyword: + case utils_1.AST_NODE_TYPES.TSProtectedKeyword: + case utils_1.AST_NODE_TYPES.TSPublicKeyword: + case utils_1.AST_NODE_TYPES.TSReadonlyKeyword: + case utils_1.AST_NODE_TYPES.TSRestType: + case utils_1.AST_NODE_TYPES.TSStaticKeyword: + case utils_1.AST_NODE_TYPES.TSStringKeyword: + case utils_1.AST_NODE_TYPES.TSSymbolKeyword: + case utils_1.AST_NODE_TYPES.TSTemplateLiteralType: + case utils_1.AST_NODE_TYPES.TSTupleType: + case utils_1.AST_NODE_TYPES.TSTypePredicate: + case utils_1.AST_NODE_TYPES.TSUndefinedKeyword: + case utils_1.AST_NODE_TYPES.TSUnknownKeyword: + case utils_1.AST_NODE_TYPES.TSVoidKeyword: + return false; + } + } + function checkTestConditional(node) { + if (node.test) { + checkConditional(node.test, true); + } + } + /** + * This function analyzes the type of a node and checks if it is a Promise in a boolean conditional. + * It uses recursion when checking nested logical operators. + * @param node The AST node to check. + * @param isTestExpr Whether the node is a descendant of a test expression. + */ + function checkConditional(node, isTestExpr = false) { + // prevent checking the same node multiple times + if (checkedNodes.has(node)) { + return; + } + checkedNodes.add(node); + if (node.type === utils_1.AST_NODE_TYPES.LogicalExpression) { + // ignore the left operand for nullish coalescing expressions not in a context of a test expression + if (node.operator !== '??' || isTestExpr) { + checkConditional(node.left, isTestExpr); + } + // we ignore the right operand when not in a context of a test expression + if (isTestExpr) { + checkConditional(node.right, isTestExpr); + } + return; + } + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + if (isAlwaysThenable(checker, tsNode)) { + context.report({ + node, + messageId: 'conditional', + }); + } + } + function checkArrayPredicates(node) { + const parent = node.parent; + if (parent.type === utils_1.AST_NODE_TYPES.CallExpression) { + const callback = parent.arguments.at(0); + if (callback && + (0, util_1.isArrayMethodCallWithPredicate)(context, services, parent)) { + const type = services.esTreeNodeToTSNodeMap.get(callback); + if (returnsThenable(checker, type)) { + context.report({ + node: callback, + messageId: 'predicate', + }); + } + } + } + } + function checkArguments(node) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + const voidArgs = voidFunctionArguments(checker, tsNode); + if (voidArgs.size === 0) { + return; + } + for (const [index, argument] of node.arguments.entries()) { + if (!voidArgs.has(index)) { + continue; + } + const tsNode = services.esTreeNodeToTSNodeMap.get(argument); + if (returnsThenable(checker, tsNode)) { + context.report({ + node: argument, + messageId: 'voidReturnArgument', + }); + } + } + } + function checkAssignment(node) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + const varType = services.getTypeAtLocation(node.left); + if (!isVoidReturningFunctionType(checker, tsNode.left, varType)) { + return; + } + if (returnsThenable(checker, tsNode.right)) { + context.report({ + node: node.right, + messageId: 'voidReturnVariable', + }); + } + } + function checkVariableDeclaration(node) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + if (tsNode.initializer == null || + node.init == null || + node.id.typeAnnotation == null) { + return; + } + // syntactically ignore some known-good cases to avoid touching type info + if (!isPossiblyFunctionType(node.id.typeAnnotation)) { + return; + } + const varType = services.getTypeAtLocation(node.id); + if (!isVoidReturningFunctionType(checker, tsNode.initializer, varType)) { + return; + } + if (returnsThenable(checker, tsNode.initializer)) { + context.report({ + node: node.init, + messageId: 'voidReturnVariable', + }); + } + } + function checkProperty(node) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + if (ts.isPropertyAssignment(tsNode)) { + const contextualType = checker.getContextualType(tsNode.initializer); + if (contextualType != null && + isVoidReturningFunctionType(checker, tsNode.initializer, contextualType) && + returnsThenable(checker, tsNode.initializer)) { + if ((0, util_1.isFunction)(node.value)) { + const functionNode = node.value; + if (functionNode.returnType) { + context.report({ + node: functionNode.returnType.typeAnnotation, + messageId: 'voidReturnProperty', + }); + } + else { + context.report({ + loc: (0, util_1.getFunctionHeadLoc)(functionNode, context.sourceCode), + messageId: 'voidReturnProperty', + }); + } + } + else { + context.report({ + node: node.value, + messageId: 'voidReturnProperty', + }); + } + } + } + else if (ts.isShorthandPropertyAssignment(tsNode)) { + const contextualType = checker.getContextualType(tsNode.name); + if (contextualType != null && + isVoidReturningFunctionType(checker, tsNode.name, contextualType) && + returnsThenable(checker, tsNode.name)) { + context.report({ + node: node.value, + messageId: 'voidReturnProperty', + }); + } + } + else if (ts.isMethodDeclaration(tsNode)) { + if (ts.isComputedPropertyName(tsNode.name)) { + return; + } + const obj = tsNode.parent; + // Below condition isn't satisfied unless something goes wrong, + // but is needed for type checking. + // 'node' does not include class method declaration so 'obj' is + // always an object literal expression, but after converting 'node' + // to TypeScript AST, its type includes MethodDeclaration which + // does include the case of class method declaration. + if (!ts.isObjectLiteralExpression(obj)) { + return; + } + if (!returnsThenable(checker, tsNode)) { + return; + } + const objType = checker.getContextualType(obj); + if (objType == null) { + return; + } + const propertySymbol = checker.getPropertyOfType(objType, tsNode.name.text); + if (propertySymbol == null) { + return; + } + const contextualType = checker.getTypeOfSymbolAtLocation(propertySymbol, tsNode.name); + if (isVoidReturningFunctionType(checker, tsNode.name, contextualType)) { + const functionNode = node.value; + if (functionNode.returnType) { + context.report({ + node: functionNode.returnType.typeAnnotation, + messageId: 'voidReturnProperty', + }); + } + else { + context.report({ + loc: (0, util_1.getFunctionHeadLoc)(functionNode, context.sourceCode), + messageId: 'voidReturnProperty', + }); + } + } + return; + } + } + function checkReturnStatement(node) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + if (tsNode.expression == null || node.argument == null) { + return; + } + // syntactically ignore some known-good cases to avoid touching type info + const functionNode = (() => { + let current = node.parent; + while (current && !(0, util_1.isFunction)(current)) { + current = current.parent; + } + return (0, util_1.nullThrows)(current, util_1.NullThrowsReasons.MissingParent); + })(); + if (functionNode.returnType && + !isPossiblyFunctionType(functionNode.returnType)) { + return; + } + const contextualType = checker.getContextualType(tsNode.expression); + if (contextualType != null && + isVoidReturningFunctionType(checker, tsNode.expression, contextualType) && + returnsThenable(checker, tsNode.expression)) { + context.report({ + node: node.argument, + messageId: 'voidReturnReturnValue', + }); + } + } + function checkClassLikeOrInterfaceNode(node) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + const heritageTypes = getHeritageTypes(checker, tsNode); + if (!heritageTypes?.length) { + return; + } + for (const nodeMember of tsNode.members) { + const memberName = nodeMember.name?.getText(); + if (memberName == null) { + // Call/construct/index signatures don't have names. TS allows call signatures to mismatch, + // and construct signatures can't be async. + // TODO - Once we're able to use `checker.isTypeAssignableTo` (v8), we can check an index + // signature here against its compatible index signatures in `heritageTypes` + continue; + } + if (!returnsThenable(checker, nodeMember)) { + continue; + } + const node = services.tsNodeToESTreeNodeMap.get(nodeMember); + if (isStaticMember(node)) { + continue; + } + for (const heritageType of heritageTypes) { + checkHeritageTypeForMemberReturningVoid(nodeMember, heritageType, memberName); + } + } + } + /** + * Checks `heritageType` for a member named `memberName` that returns void; reports the + * 'voidReturnInheritedMethod' message if found. + * @param nodeMember Node member that returns a Promise + * @param heritageType Heritage type to check against + * @param memberName Name of the member to check for + */ + function checkHeritageTypeForMemberReturningVoid(nodeMember, heritageType, memberName) { + const heritageMember = getMemberIfExists(heritageType, memberName); + if (heritageMember == null) { + return; + } + const memberType = checker.getTypeOfSymbolAtLocation(heritageMember, nodeMember); + if (!isVoidReturningFunctionType(checker, nodeMember, memberType)) { + return; + } + context.report({ + node: services.tsNodeToESTreeNodeMap.get(nodeMember), + messageId: 'voidReturnInheritedMethod', + data: { heritageTypeName: checker.typeToString(heritageType) }, + }); + } + function checkJSXAttribute(node) { + if (node.value == null || + node.value.type !== utils_1.AST_NODE_TYPES.JSXExpressionContainer) { + return; + } + const expressionContainer = services.esTreeNodeToTSNodeMap.get(node.value); + const expression = services.esTreeNodeToTSNodeMap.get(node.value.expression); + const contextualType = checker.getContextualType(expressionContainer); + if (contextualType != null && + isVoidReturningFunctionType(checker, expressionContainer, contextualType) && + returnsThenable(checker, expression)) { + context.report({ + node: node.value, + messageId: 'voidReturnAttribute', + }); + } + } + function checkSpread(node) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + if (isSometimesThenable(checker, tsNode.expression)) { + context.report({ + node: node.argument, + messageId: 'spread', + }); + } + } + return { + ...(checksConditionals ? conditionalChecks : {}), + ...(checksVoidReturn ? voidReturnChecks : {}), + ...(checksSpreads ? spreadChecks : {}), + }; + }, +}); +function isSometimesThenable(checker, node) { + const type = checker.getTypeAtLocation(node); + for (const subType of tsutils.unionConstituents(checker.getApparentType(type))) { + if (tsutils.isThenableType(checker, node, subType)) { + return true; + } + } + return false; +} +// Variation on the thenable check which requires all forms of the type (read: +// alternates in a union) to be thenable. Otherwise, you might be trying to +// check if something is defined or undefined and get caught because one of the +// branches is thenable. +function isAlwaysThenable(checker, node) { + const type = checker.getTypeAtLocation(node); + for (const subType of tsutils.unionConstituents(checker.getApparentType(type))) { + const thenProp = subType.getProperty('then'); + // If one of the alternates has no then property, it is not thenable in all + // cases. + if (thenProp == null) { + return false; + } + // We walk through each variation of the then property. Since we know it + // exists at this point, we just need at least one of the alternates to + // be of the right form to consider it thenable. + const thenType = checker.getTypeOfSymbolAtLocation(thenProp, node); + let hasThenableSignature = false; + for (const subType of tsutils.unionConstituents(thenType)) { + for (const signature of subType.getCallSignatures()) { + if (signature.parameters.length !== 0 && + isFunctionParam(checker, signature.parameters[0], node)) { + hasThenableSignature = true; + break; + } + } + // We only need to find one variant of the then property that has a + // function signature for it to be thenable. + if (hasThenableSignature) { + break; + } + } + // If no flavors of the then property are thenable, we don't consider the + // overall type to be thenable + if (!hasThenableSignature) { + return false; + } + } + // If all variants are considered thenable (i.e. haven't returned false), we + // consider the overall type thenable + return true; +} +function isFunctionParam(checker, param, node) { + const type = checker.getApparentType(checker.getTypeOfSymbolAtLocation(param, node)); + for (const subType of tsutils.unionConstituents(type)) { + if (subType.getCallSignatures().length !== 0) { + return true; + } + } + return false; +} +function checkThenableOrVoidArgument(checker, node, type, index, thenableReturnIndices, voidReturnIndices) { + if (isThenableReturningFunctionType(checker, node.expression, type)) { + thenableReturnIndices.add(index); + } + else if (isVoidReturningFunctionType(checker, node.expression, type) && + // If a certain argument accepts both thenable and void returns, + // a promise-returning function is valid + !thenableReturnIndices.has(index)) { + voidReturnIndices.add(index); + } + const contextualType = checker.getContextualTypeForArgumentAtIndex(node, index); + if (contextualType !== type) { + checkThenableOrVoidArgument(checker, node, contextualType, index, thenableReturnIndices, voidReturnIndices); + } +} +// Get the positions of arguments which are void functions (and not also +// thenable functions). These are the candidates for the void-return check at +// the current call site. +// If the function parameters end with a 'rest' parameter, then we consider +// the array type parameter (e.g. '...args:Array') when determining +// if trailing arguments are candidates. +function voidFunctionArguments(checker, node) { + // 'new' can be used without any arguments, as in 'let b = new Object;' + // In this case, there are no argument positions to check, so return early. + if (!node.arguments) { + return new Set(); + } + const thenableReturnIndices = new Set(); + const voidReturnIndices = new Set(); + const type = checker.getTypeAtLocation(node.expression); + // We can't use checker.getResolvedSignature because it prefers an early '() => void' over a later '() => Promise' + // See https://github.com/microsoft/TypeScript/issues/48077 + for (const subType of tsutils.unionConstituents(type)) { + // Standard function calls and `new` have two different types of signatures + const signatures = ts.isCallExpression(node) + ? subType.getCallSignatures() + : subType.getConstructSignatures(); + for (const signature of signatures) { + for (const [index, parameter] of signature.parameters.entries()) { + const decl = parameter.valueDeclaration; + let type = checker.getTypeOfSymbolAtLocation(parameter, node.expression); + // If this is a array 'rest' parameter, check all of the argument indices + // from the current argument to the end. + if (decl && (0, util_1.isRestParameterDeclaration)(decl)) { + if (checker.isArrayType(type)) { + // Unwrap 'Array' to 'MaybeVoidFunction', + // so that we'll handle it in the same way as a non-rest + // 'param: MaybeVoidFunction' + type = checker.getTypeArguments(type)[0]; + for (let i = index; i < node.arguments.length; i++) { + checkThenableOrVoidArgument(checker, node, type, i, thenableReturnIndices, voidReturnIndices); + } + } + else if (checker.isTupleType(type)) { + // Check each type in the tuple - for example, [boolean, () => void] would + // add the index of the second tuple parameter to 'voidReturnIndices' + const typeArgs = checker.getTypeArguments(type); + for (let i = index; i < node.arguments.length && i - index < typeArgs.length; i++) { + checkThenableOrVoidArgument(checker, node, typeArgs[i - index], i, thenableReturnIndices, voidReturnIndices); + } + } + } + else { + checkThenableOrVoidArgument(checker, node, type, index, thenableReturnIndices, voidReturnIndices); + } + } + } + } + for (const index of thenableReturnIndices) { + voidReturnIndices.delete(index); + } + return voidReturnIndices; +} +/** + * @returns Whether any call signature of the type has a thenable return type. + */ +function anySignatureIsThenableType(checker, node, type) { + for (const signature of type.getCallSignatures()) { + const returnType = signature.getReturnType(); + if (tsutils.isThenableType(checker, node, returnType)) { + return true; + } + } + return false; +} +/** + * @returns Whether type is a thenable-returning function. + */ +function isThenableReturningFunctionType(checker, node, type) { + for (const subType of tsutils.unionConstituents(type)) { + if (anySignatureIsThenableType(checker, node, subType)) { + return true; + } + } + return false; +} +/** + * @returns Whether type is a void-returning function. + */ +function isVoidReturningFunctionType(checker, node, type) { + let hadVoidReturn = false; + for (const subType of tsutils.unionConstituents(type)) { + for (const signature of subType.getCallSignatures()) { + const returnType = signature.getReturnType(); + // If a certain positional argument accepts both thenable and void returns, + // a promise-returning function is valid + if (tsutils.isThenableType(checker, node, returnType)) { + return false; + } + hadVoidReturn ||= tsutils.isTypeFlagSet(returnType, ts.TypeFlags.Void); + } + } + return hadVoidReturn; +} +/** + * @returns Whether expression is a function that returns a thenable. + */ +function returnsThenable(checker, node) { + const type = checker.getApparentType(checker.getTypeAtLocation(node)); + return tsutils + .unionConstituents(type) + .some(t => anySignatureIsThenableType(checker, node, t)); +} +function getHeritageTypes(checker, tsNode) { + return tsNode.heritageClauses + ?.flatMap(clause => clause.types) + .map(typeExpression => checker.getTypeAtLocation(typeExpression)); +} +/** + * @returns The member with the given name in `type`, if it exists. + */ +function getMemberIfExists(type, memberName) { + const escapedMemberName = ts.escapeLeadingUnderscores(memberName); + const symbolMemberMatch = type.getSymbol()?.members?.get(escapedMemberName); + return (symbolMemberMatch ?? tsutils.getPropertyOfType(type, escapedMemberName)); +} +function isStaticMember(node) { + return ((node.type === utils_1.AST_NODE_TYPES.MethodDefinition || + node.type === utils_1.AST_NODE_TYPES.PropertyDefinition || + node.type === utils_1.AST_NODE_TYPES.AccessorProperty) && + node.static); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-spread.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-spread.d.ts new file mode 100644 index 00000000..f3583383 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-spread.d.ts @@ -0,0 +1,11 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +import type { TypeOrValueSpecifier } from '../util'; +type Options = [ + { + allow?: TypeOrValueSpecifier[]; + } +]; +type MessageIds = 'addAwait' | 'noArraySpreadInObject' | 'noClassDeclarationSpreadInObject' | 'noClassInstanceSpreadInObject' | 'noFunctionSpreadInObject' | 'noIterableSpreadInObject' | 'noMapSpreadInObject' | 'noPromiseSpreadInObject' | 'noStringSpread' | 'replaceMapSpreadInObject'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-misused-spread.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-spread.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-spread.d.ts.map new file mode 100644 index 00000000..f930c590 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-spread.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-misused-spread.d.ts","sourceRoot":"","sources":["../../src/rules/no-misused-spread.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAMnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAepD,KAAK,OAAO,GAAG;IACb;QACE,KAAK,CAAC,EAAE,oBAAoB,EAAE,CAAC;KAChC;CACF,CAAC;AAEF,KAAK,UAAU,GACX,UAAU,GACV,uBAAuB,GACvB,kCAAkC,GAClC,+BAA+B,GAC/B,0BAA0B,GAC1B,0BAA0B,GAC1B,qBAAqB,GACrB,yBAAyB,GACzB,gBAAgB,GAChB,0BAA0B,CAAC;;AAE/B,wBA2NG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-spread.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-spread.js new file mode 100644 index 00000000..001bfc76 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-misused-spread.js @@ -0,0 +1,260 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-misused-spread', + meta: { + type: 'problem', + docs: { + description: 'Disallow using the spread operator when it might cause unexpected behavior', + recommended: 'strict', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + addAwait: 'Add await operator.', + noArraySpreadInObject: 'Using the spread operator on an array in an object will result in a list of indices.', + noClassDeclarationSpreadInObject: 'Using the spread operator on class declarations will spread only their static properties, and will lose their class prototype.', + noClassInstanceSpreadInObject: 'Using the spread operator on class instances will lose their class prototype.', + noFunctionSpreadInObject: 'Using the spread operator on a function without additional properties can cause unexpected behavior. Did you forget to call the function?', + noIterableSpreadInObject: 'Using the spread operator on an Iterable in an object can cause unexpected behavior.', + noMapSpreadInObject: 'Using the spread operator on a Map in an object will result in an empty object. Did you mean to use `Object.fromEntries(map)` instead?', + noPromiseSpreadInObject: 'Using the spread operator on Promise in an object can cause unexpected behavior. Did you forget to await the promise?', + noStringSpread: [ + 'Using the spread operator on a string can mishandle special characters, as can `.split("")`.', + '- `...` produces Unicode code points, which will decompose complex emojis into individual emojis', + '- .split("") produces UTF-16 code units, which breaks rich characters in many languages', + 'Consider using `Intl.Segmenter` for locale-aware string decomposition.', + "Otherwise, if you don't need to preserve emojis or other non-Ascii characters, disable this lint rule on this line or configure the 'allow' rule option.", + ].join('\n'), + replaceMapSpreadInObject: 'Replace map spread in object with `Object.fromEntries()`', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allow: { + ...util_1.readonlynessOptionsSchema.properties.allow, + description: 'An array of type specifiers that are known to be safe to spread.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allow: [], + }, + ], + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function checkArrayOrCallSpread(node) { + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node.argument); + if (!(0, util_1.typeMatchesSomeSpecifier)(type, options.allow, services.program) && + isString(type)) { + context.report({ + node, + messageId: 'noStringSpread', + }); + } + } + function getMapSpreadSuggestions(node, type) { + const types = tsutils.unionConstituents(type); + if (types.some(t => !isMap(services.program, t))) { + return null; + } + if (node.parent.type === utils_1.AST_NODE_TYPES.ObjectExpression && + node.parent.properties.length === 1) { + return [ + { + messageId: 'replaceMapSpreadInObject', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node.argument, + sourceCode: context.sourceCode, + wrap: code => `Object.fromEntries(${code})`, + }), + }, + ]; + } + return [ + { + messageId: 'replaceMapSpreadInObject', + fix: (0, util_1.getWrappingFixer)({ + node: node.argument, + sourceCode: context.sourceCode, + wrap: code => `Object.fromEntries(${code})`, + }), + }, + ]; + } + function getPromiseSpreadSuggestions(node) { + const isHighPrecendence = (0, util_1.isHigherPrecedenceThanAwait)(services.esTreeNodeToTSNodeMap.get(node)); + return [ + { + messageId: 'addAwait', + fix: fixer => isHighPrecendence + ? fixer.insertTextBefore(node, 'await ') + : [ + fixer.insertTextBefore(node, 'await ('), + fixer.insertTextAfter(node, ')'), + ], + }, + ]; + } + function checkObjectSpread(node) { + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node.argument); + if ((0, util_1.typeMatchesSomeSpecifier)(type, options.allow, services.program)) { + return; + } + if (isPromise(services.program, type)) { + context.report({ + node, + messageId: 'noPromiseSpreadInObject', + suggest: getPromiseSpreadSuggestions(node.argument), + }); + return; + } + if (isFunctionWithoutProps(type)) { + context.report({ + node, + messageId: 'noFunctionSpreadInObject', + }); + return; + } + if (isMap(services.program, type)) { + context.report({ + node, + messageId: 'noMapSpreadInObject', + suggest: getMapSpreadSuggestions(node, type), + }); + return; + } + if (isArray(checker, type)) { + context.report({ + node, + messageId: 'noArraySpreadInObject', + }); + return; + } + if (isIterable(type, checker) && + // Don't report when the type is string, since TS will flag it already + !isString(type)) { + context.report({ + node, + messageId: 'noIterableSpreadInObject', + }); + return; + } + if (isClassInstance(checker, type)) { + context.report({ + node, + messageId: 'noClassInstanceSpreadInObject', + }); + return; + } + if (isClassDeclaration(type)) { + context.report({ + node, + messageId: 'noClassDeclarationSpreadInObject', + }); + } + } + return { + 'ArrayExpression > SpreadElement': checkArrayOrCallSpread, + 'CallExpression > SpreadElement': checkArrayOrCallSpread, + JSXSpreadAttribute: checkObjectSpread, + 'ObjectExpression > SpreadElement': checkObjectSpread, + }; + }, +}); +function isIterable(type, checker) { + return tsutils + .typeConstituents(type) + .some(t => !!tsutils.getWellKnownSymbolPropertyOfType(t, 'iterator', checker)); +} +function isArray(checker, type) { + return isTypeRecurser(type, t => checker.isArrayType(t) || checker.isTupleType(t)); +} +function isString(type) { + return isTypeRecurser(type, t => (0, util_1.isTypeFlagSet)(t, ts.TypeFlags.StringLike)); +} +function isFunctionWithoutProps(type) { + return isTypeRecurser(type, t => t.getCallSignatures().length > 0 && t.getProperties().length === 0); +} +function isPromise(program, type) { + return isTypeRecurser(type, t => (0, util_1.isPromiseLike)(program, t)); +} +function isClassInstance(checker, type) { + return isTypeRecurser(type, t => { + // If the type itself has a construct signature, it's a class(-like) + if (t.getConstructSignatures().length) { + return false; + } + const symbol = t.getSymbol(); + // If the type's symbol has a construct signature, the type is an instance + return !!symbol + ?.getDeclarations() + ?.some(declaration => checker + .getTypeOfSymbolAtLocation(symbol, declaration) + .getConstructSignatures().length); + }); +} +function isClassDeclaration(type) { + return isTypeRecurser(type, t => { + if (tsutils.isObjectType(t) && + tsutils.isObjectFlagSet(t, ts.ObjectFlags.InstantiationExpressionType)) { + return true; + } + const kind = t.getSymbol()?.valueDeclaration?.kind; + return (kind === ts.SyntaxKind.ClassDeclaration || + kind === ts.SyntaxKind.ClassExpression); + }); +} +function isMap(program, type) { + return isTypeRecurser(type, t => (0, util_1.isBuiltinSymbolLike)(program, t, ['Map', 'ReadonlyMap', 'WeakMap'])); +} +function isTypeRecurser(type, predicate) { + if (type.isUnionOrIntersection()) { + return type.types.some(t => isTypeRecurser(t, predicate)); + } + return predicate(type); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-mixed-enums.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-mixed-enums.d.ts new file mode 100644 index 00000000..67263fce --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-mixed-enums.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"mixed", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-mixed-enums.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-mixed-enums.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-mixed-enums.d.ts.map new file mode 100644 index 00000000..6b1c35a7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-mixed-enums.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-mixed-enums.d.ts","sourceRoot":"","sources":["../../src/rules/no-mixed-enums.ts"],"names":[],"mappings":";AAgBA,wBA4MG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-mixed-enums.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-mixed-enums.js new file mode 100644 index 00000000..91e064a8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-mixed-enums.js @@ -0,0 +1,200 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +var AllowedType; +(function (AllowedType) { + AllowedType[AllowedType["Number"] = 0] = "Number"; + AllowedType[AllowedType["String"] = 1] = "String"; + AllowedType[AllowedType["Unknown"] = 2] = "Unknown"; +})(AllowedType || (AllowedType = {})); +exports.default = (0, util_1.createRule)({ + name: 'no-mixed-enums', + meta: { + type: 'problem', + docs: { + description: 'Disallow enums from having both number and string members', + recommended: 'strict', + requiresTypeChecking: true, + }, + messages: { + mixed: `Mixing number and string enums can be confusing.`, + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const parserServices = (0, util_1.getParserServices)(context); + const typeChecker = parserServices.program.getTypeChecker(); + function collectNodeDefinitions(node) { + const { name } = node.id; + const found = { + imports: [], + previousSibling: undefined, + }; + let scope = context.sourceCode.getScope(node); + for (const definition of scope.upper?.set.get(name)?.defs ?? []) { + if (definition.node.type === utils_1.AST_NODE_TYPES.TSEnumDeclaration && + definition.node.range[0] < node.range[0] && + definition.node.body.members.length > 0) { + found.previousSibling = definition.node; + break; + } + } + while (scope) { + scope.set.get(name)?.defs.forEach(definition => { + if (definition.type === scope_manager_1.DefinitionType.ImportBinding) { + found.imports.push(definition.node); + } + }); + scope = scope.upper; + } + return found; + } + function getAllowedTypeForNode(node) { + return tsutils.isTypeFlagSet(typeChecker.getTypeAtLocation(node), ts.TypeFlags.StringLike) + ? AllowedType.String + : AllowedType.Number; + } + function getTypeFromImported(imported) { + const type = typeChecker.getTypeAtLocation(parserServices.esTreeNodeToTSNodeMap.get(imported)); + const valueDeclaration = type.getSymbol()?.valueDeclaration; + if (!valueDeclaration || + !ts.isEnumDeclaration(valueDeclaration) || + valueDeclaration.members.length === 0) { + return undefined; + } + return getAllowedTypeForNode(valueDeclaration.members[0]); + } + function getMemberType(member) { + if (!member.initializer) { + return AllowedType.Number; + } + switch (member.initializer.type) { + case utils_1.AST_NODE_TYPES.Literal: + switch (typeof member.initializer.value) { + case 'number': + return AllowedType.Number; + case 'string': + return AllowedType.String; + default: + return AllowedType.Unknown; + } + case utils_1.AST_NODE_TYPES.TemplateLiteral: + return AllowedType.String; + default: + return getAllowedTypeForNode(parserServices.esTreeNodeToTSNodeMap.get(member.initializer)); + } + } + function getDesiredTypeForDefinition(node) { + const { imports, previousSibling } = collectNodeDefinitions(node); + // Case: Merged ambiently via module augmentation + // import { MyEnum } from 'other-module'; + // declare module 'other-module' { + // enum MyEnum { A } + // } + for (const imported of imports) { + const typeFromImported = getTypeFromImported(imported); + if (typeFromImported != null) { + return typeFromImported; + } + } + // Case: Multiple enum declarations in the same file + // enum MyEnum { A } + // enum MyEnum { B } + if (previousSibling) { + return getMemberType(previousSibling.body.members[0]); + } + // Case: Namespace declaration merging + // namespace MyNamespace { + // export enum MyEnum { A } + // } + // namespace MyNamespace { + // export enum MyEnum { B } + // } + if (node.parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration && + node.parent.parent.type === utils_1.AST_NODE_TYPES.TSModuleBlock) { + // https://github.com/typescript-eslint/typescript-eslint/issues/8352 + // TODO: We don't need to dip into the TypeScript type checker here! + // Merged namespaces must all exist in the same file. + // We could instead compare this file's nodes to find the merges. + const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node.id); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const declarations = typeChecker + .getSymbolAtLocation(tsNode) + .getDeclarations(); + const [{ initializer }] = declarations[0] + .members; + return initializer && + tsutils.isTypeFlagSet(typeChecker.getTypeAtLocation(initializer), ts.TypeFlags.StringLike) + ? AllowedType.String + : AllowedType.Number; + } + // Finally, we default to the type of the first enum member + return getMemberType(node.body.members[0]); + } + return { + TSEnumDeclaration(node) { + if (!node.body.members.length) { + return; + } + let desiredType = getDesiredTypeForDefinition(node); + if (desiredType === ts.TypeFlags.Unknown) { + return; + } + for (const member of node.body.members) { + const currentType = getMemberType(member); + if (currentType === AllowedType.Unknown) { + return; + } + if (currentType === AllowedType.Number) { + desiredType ??= currentType; + } + if (currentType !== desiredType) { + context.report({ + node: member.initializer ?? member, + messageId: 'mixed', + }); + return; + } + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-namespace.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-namespace.d.ts new file mode 100644 index 00000000..2e5273c3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-namespace.d.ts @@ -0,0 +1,10 @@ +export type Options = [ + { + allowDeclarations?: boolean; + allowDefinitionFiles?: boolean; + } +]; +export type MessageIds = 'moduleSyntaxIsPreferred'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"moduleSyntaxIsPreferred", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-namespace.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-namespace.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-namespace.d.ts.map new file mode 100644 index 00000000..7a680749 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-namespace.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-namespace.d.ts","sourceRoot":"","sources":["../../src/rules/no-namespace.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,iBAAiB,CAAC,EAAE,OAAO,CAAC;QAC5B,oBAAoB,CAAC,EAAE,OAAO,CAAC;KAChC;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,yBAAyB,CAAC;;AAEnD,wBAiEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-namespace.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-namespace.js new file mode 100644 index 00000000..c0035138 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-namespace.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-namespace', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow TypeScript namespaces', + recommended: 'recommended', + }, + messages: { + moduleSyntaxIsPreferred: 'ES2015 module syntax is preferred over namespaces.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowDeclarations: { + type: 'boolean', + description: 'Whether to allow `declare` with custom TypeScript namespaces.', + }, + allowDefinitionFiles: { + type: 'boolean', + description: 'Whether to allow `declare` with custom TypeScript namespaces inside definition files.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowDeclarations: false, + allowDefinitionFiles: true, + }, + ], + create(context, [{ allowDeclarations, allowDefinitionFiles }]) { + function isDeclaration(node) { + if (node.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration && node.declare) { + return true; + } + return node.parent != null && isDeclaration(node.parent); + } + return { + "TSModuleDeclaration[global!=true][id.type!='Literal']"(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration || + (allowDefinitionFiles && (0, util_1.isDefinitionFile)(context.filename)) || + (allowDeclarations && isDeclaration(node))) { + return; + } + context.report({ + node, + messageId: 'moduleSyntaxIsPreferred', + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-nullish-coalescing.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-nullish-coalescing.d.ts new file mode 100644 index 00000000..9e56ccb8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-nullish-coalescing.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"noNonNullAssertedNullishCoalescing" | "suggestRemovingNonNull", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-non-null-asserted-nullish-coalescing.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-nullish-coalescing.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-nullish-coalescing.d.ts.map new file mode 100644 index 00000000..301e9f9f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-nullish-coalescing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-non-null-asserted-nullish-coalescing.d.ts","sourceRoot":"","sources":["../../src/rules/no-non-null-asserted-nullish-coalescing.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;;AA+BzD,wBAmEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-nullish-coalescing.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-nullish-coalescing.js new file mode 100644 index 00000000..c37f52fd --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-nullish-coalescing.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +function hasAssignmentBeforeNode(variable, node) { + return (variable.references.some(ref => ref.isWrite() && ref.identifier.range[1] < node.range[1]) || + variable.defs.some(def => isDefinitionWithAssignment(def) && def.node.range[1] < node.range[1])); +} +function isDefinitionWithAssignment(definition) { + if (definition.type !== scope_manager_1.DefinitionType.Variable) { + return false; + } + const variableDeclarator = definition.node; + return variableDeclarator.definite || variableDeclarator.init != null; +} +exports.default = (0, util_1.createRule)({ + name: 'no-non-null-asserted-nullish-coalescing', + meta: { + type: 'problem', + docs: { + description: 'Disallow non-null assertions in the left operand of a nullish coalescing operator', + recommended: 'strict', + }, + hasSuggestions: true, + messages: { + noNonNullAssertedNullishCoalescing: 'The nullish coalescing operator is designed to handle undefined and null - using a non-null assertion is not needed.', + suggestRemovingNonNull: 'Remove the non-null assertion.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + return { + 'LogicalExpression[operator = "??"] > TSNonNullExpression.left'(node) { + if (node.expression.type === utils_1.TSESTree.AST_NODE_TYPES.Identifier) { + const scope = context.sourceCode.getScope(node); + const identifier = node.expression; + const variable = utils_1.ASTUtils.findVariable(scope, identifier.name); + if (variable && !hasAssignmentBeforeNode(variable, node)) { + return; + } + } + context.report({ + node, + messageId: 'noNonNullAssertedNullishCoalescing', + /* + Use a suggestion instead of a fixer, because this can break type checks. + The resulting type of the nullish coalesce is only influenced by the right operand if the left operand can be `null` or `undefined`. + After removing the non-null assertion the type of the left operand might contain `null` or `undefined` and then the type of the right operand + might change the resulting type of the nullish coalesce. + See the following example: + + function test(x?: string): string { + const bar = x! ?? false; // type analysis reports `bar` has type `string` + // x ?? false; // type analysis reports `bar` has type `string | false` + return bar; + } + */ + suggest: [ + { + messageId: 'suggestRemovingNonNull', + fix(fixer) { + const exclamationMark = (0, util_1.nullThrows)(context.sourceCode.getLastToken(node, utils_1.ASTUtils.isNonNullAssertionPunctuator), util_1.NullThrowsReasons.MissingToken('!', 'Non-null Assertion')); + return fixer.remove(exclamationMark); + }, + }, + ], + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-optional-chain.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-optional-chain.d.ts new file mode 100644 index 00000000..44138c68 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-optional-chain.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"suggestRemovingNonNull" | "noNonNullOptionalChain", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-non-null-asserted-optional-chain.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-optional-chain.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-optional-chain.d.ts.map new file mode 100644 index 00000000..cc8343c1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-optional-chain.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-non-null-asserted-optional-chain.d.ts","sourceRoot":"","sources":["../../src/rules/no-non-null-asserted-optional-chain.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAInE,wBAoEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-optional-chain.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-optional-chain.js new file mode 100644 index 00000000..58e41c15 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-asserted-optional-chain.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-non-null-asserted-optional-chain', + meta: { + type: 'problem', + docs: { + description: 'Disallow non-null assertions after an optional chain expression', + recommended: 'recommended', + }, + hasSuggestions: true, + messages: { + noNonNullOptionalChain: 'Optional chain expressions can return undefined by design - using a non-null assertion is unsafe and wrong.', + suggestRemovingNonNull: 'You should remove the non-null assertion.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + return { + // non-nulling a wrapped chain will scrub all nulls introduced by the chain + // (x?.y)! + // (x?.())! + 'TSNonNullExpression > ChainExpression'(node) { + // selector guarantees this assertion + const parent = node.parent; + context.report({ + node, + messageId: 'noNonNullOptionalChain', + // use a suggestion instead of a fixer, because this can obviously break type checks + suggest: [ + { + messageId: 'suggestRemovingNonNull', + fix(fixer) { + return fixer.removeRange([ + parent.range[1] - 1, + parent.range[1], + ]); + }, + }, + ], + }); + }, + // non-nulling at the end of a chain will scrub all nulls introduced by the chain + // x?.y! + // x?.()! + 'ChainExpression > TSNonNullExpression'(node) { + context.report({ + node, + messageId: 'noNonNullOptionalChain', + // use a suggestion instead of a fixer, because this can obviously break type checks + suggest: [ + { + messageId: 'suggestRemovingNonNull', + fix(fixer) { + return fixer.removeRange([node.range[1] - 1, node.range[1]]); + }, + }, + ], + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-assertion.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-assertion.d.ts new file mode 100644 index 00000000..6652a477 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-assertion.d.ts @@ -0,0 +1,5 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageIds = 'noNonNull' | 'suggestOptionalChain'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-non-null-assertion.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-assertion.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-assertion.d.ts.map new file mode 100644 index 00000000..a5668711 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-assertion.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-non-null-assertion.d.ts","sourceRoot":"","sources":["../../src/rules/no-non-null-assertion.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAWzD,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG,sBAAsB,CAAC;;AAE9D,wBAuGG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-assertion.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-assertion.js new file mode 100644 index 00000000..02c9fcb8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-non-null-assertion.js @@ -0,0 +1,92 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-non-null-assertion', + meta: { + type: 'problem', + docs: { + description: 'Disallow non-null assertions using the `!` postfix operator', + recommended: 'strict', + }, + hasSuggestions: true, + messages: { + noNonNull: 'Forbidden non-null assertion.', + suggestOptionalChain: 'Consider using the optional chain operator `?.` instead. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + return { + TSNonNullExpression(node) { + const suggest = []; + // it always exists in non-null assertion + const nonNullOperator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.expression, util_1.isNonNullAssertionPunctuator), util_1.NullThrowsReasons.MissingToken('!', 'expression')); + function replaceTokenWithOptional() { + return fixer => fixer.replaceText(nonNullOperator, '?.'); + } + function removeToken() { + return fixer => fixer.remove(nonNullOperator); + } + if (node.parent.type === utils_1.AST_NODE_TYPES.MemberExpression && + node.parent.object === node) { + if (!node.parent.optional) { + if (node.parent.computed) { + // it is x![y]?.z + suggest.push({ + messageId: 'suggestOptionalChain', + fix: replaceTokenWithOptional(), + }); + } + else { + // it is x!.y?.z + suggest.push({ + messageId: 'suggestOptionalChain', + fix(fixer) { + // x!.y?.z + // ^ punctuator + const punctuator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(nonNullOperator), util_1.NullThrowsReasons.MissingToken('.', '!')); + return [ + fixer.remove(nonNullOperator), + fixer.insertTextBefore(punctuator, '?'), + ]; + }, + }); + } + } + else { + // it is x!?.[y].z or x!?.y.z + suggest.push({ + messageId: 'suggestOptionalChain', + fix: removeToken(), + }); + } + } + else if (node.parent.type === utils_1.AST_NODE_TYPES.CallExpression && + node.parent.callee === node) { + if (!node.parent.optional) { + // it is x.y?.z!() + suggest.push({ + messageId: 'suggestOptionalChain', + fix: replaceTokenWithOptional(), + }); + } + else { + // it is x.y.z!?.() + suggest.push({ + messageId: 'suggestOptionalChain', + fix: removeToken(), + }); + } + } + context.report({ + node, + messageId: 'noNonNull', + suggest, + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redeclare.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redeclare.d.ts new file mode 100644 index 00000000..55060e4d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redeclare.d.ts @@ -0,0 +1,11 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageIds = 'redeclared' | 'redeclaredAsBuiltin' | 'redeclaredBySyntax'; +export type Options = [ + { + builtinGlobals?: boolean; + ignoreDeclarationMerge?: boolean; + } +]; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-redeclare.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redeclare.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redeclare.d.ts.map new file mode 100644 index 00000000..b9b802da --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redeclare.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-redeclare.d.ts","sourceRoot":"","sources":["../../src/rules/no-redeclare.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAOnE,MAAM,MAAM,UAAU,GAClB,YAAY,GACZ,qBAAqB,GACrB,oBAAoB,CAAC;AACzB,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,sBAAsB,CAAC,EAAE,OAAO,CAAC;KAClC;CACF,CAAC;;AAEF,wBAyQG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redeclare.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redeclare.js new file mode 100644 index 00000000..cf453c97 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redeclare.js @@ -0,0 +1,200 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-redeclare', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow variable redeclaration', + extendsBaseRule: true, + }, + messages: { + redeclared: "'{{id}}' is already defined.", + redeclaredAsBuiltin: "'{{id}}' is already defined as a built-in global variable.", + redeclaredBySyntax: "'{{id}}' is already defined by a variable declaration.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + builtinGlobals: { + type: 'boolean', + description: 'Whether to report shadowing of built-in global variables.', + }, + ignoreDeclarationMerge: { + type: 'boolean', + description: 'Whether to ignore declaration merges between certain TypeScript declaration types.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + builtinGlobals: true, + ignoreDeclarationMerge: true, + }, + ], + create(context, [options]) { + const CLASS_DECLARATION_MERGE_NODES = new Set([ + utils_1.AST_NODE_TYPES.ClassDeclaration, + utils_1.AST_NODE_TYPES.TSInterfaceDeclaration, + utils_1.AST_NODE_TYPES.TSModuleDeclaration, + ]); + const FUNCTION_DECLARATION_MERGE_NODES = new Set([ + utils_1.AST_NODE_TYPES.FunctionDeclaration, + utils_1.AST_NODE_TYPES.TSModuleDeclaration, + ]); + const ENUM_DECLARATION_MERGE_NODES = new Set([ + utils_1.AST_NODE_TYPES.TSEnumDeclaration, + utils_1.AST_NODE_TYPES.TSModuleDeclaration, + ]); + function* iterateDeclarations(variable) { + if (options.builtinGlobals && + 'eslintImplicitGlobalSetting' in variable && + (variable.eslintImplicitGlobalSetting === 'readonly' || + variable.eslintImplicitGlobalSetting === 'writable')) { + yield { type: 'builtin' }; + } + if ('eslintExplicitGlobalComments' in variable && + variable.eslintExplicitGlobalComments) { + for (const comment of variable.eslintExplicitGlobalComments) { + yield { + loc: (0, util_1.getNameLocationInGlobalDirectiveComment)(context.sourceCode, comment, variable.name), + node: comment, + type: 'comment', + }; + } + } + const identifiers = variable.identifiers + .map(id => ({ + identifier: id, + parent: id.parent, + })) + // ignore function declarations because TS will treat them as an overload + .filter(({ parent }) => parent.type !== utils_1.AST_NODE_TYPES.TSDeclareFunction); + if (options.ignoreDeclarationMerge && identifiers.length > 1) { + if ( + // interfaces merging + identifiers.every(({ parent }) => parent.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration)) { + return; + } + if ( + // namespace/module merging + identifiers.every(({ parent }) => parent.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration)) { + return; + } + if ( + // class + interface/namespace merging + identifiers.every(({ parent }) => CLASS_DECLARATION_MERGE_NODES.has(parent.type))) { + const classDecls = identifiers.filter(({ parent }) => parent.type === utils_1.AST_NODE_TYPES.ClassDeclaration); + if (classDecls.length === 1) { + // safe declaration merging + return; + } + // there's more than one class declaration, which needs to be reported + for (const { identifier } of classDecls) { + yield { loc: identifier.loc, node: identifier, type: 'syntax' }; + } + return; + } + if ( + // class + interface/namespace merging + identifiers.every(({ parent }) => FUNCTION_DECLARATION_MERGE_NODES.has(parent.type))) { + const functionDecls = identifiers.filter(({ parent }) => parent.type === utils_1.AST_NODE_TYPES.FunctionDeclaration); + if (functionDecls.length === 1) { + // safe declaration merging + return; + } + // there's more than one function declaration, which needs to be reported + for (const { identifier } of functionDecls) { + yield { loc: identifier.loc, node: identifier, type: 'syntax' }; + } + return; + } + if ( + // enum + namespace merging + identifiers.every(({ parent }) => ENUM_DECLARATION_MERGE_NODES.has(parent.type))) { + const enumDecls = identifiers.filter(({ parent }) => parent.type === utils_1.AST_NODE_TYPES.TSEnumDeclaration); + if (enumDecls.length === 1) { + // safe declaration merging + return; + } + // there's more than one enum declaration, which needs to be reported + for (const { identifier } of enumDecls) { + yield { loc: identifier.loc, node: identifier, type: 'syntax' }; + } + return; + } + } + for (const { identifier } of identifiers) { + yield { loc: identifier.loc, node: identifier, type: 'syntax' }; + } + } + function findVariablesInScope(scope) { + for (const variable of scope.variables) { + const [declaration, ...extraDeclarations] = iterateDeclarations(variable); + if (extraDeclarations.length === 0) { + continue; + } + /* + * If the type of a declaration is different from the type of + * the first declaration, it shows the location of the first + * declaration. + */ + const detailMessageId = declaration.type === 'builtin' + ? 'redeclaredAsBuiltin' + : 'redeclaredBySyntax'; + const data = { id: variable.name }; + // Report extra declarations. + for (const { loc, node, type } of extraDeclarations) { + const messageId = type === declaration.type ? 'redeclared' : detailMessageId; + if (node) { + context.report({ loc, node, messageId, data }); + } + else if (loc) { + context.report({ loc, messageId, data }); + } + } + } + } + /** + * Find variables in the current scope. + */ + function checkForBlock(node) { + const scope = context.sourceCode.getScope(node); + /* + * In ES5, some node type such as `BlockStatement` doesn't have that scope. + * `scope.block` is a different node in such a case. + */ + if (scope.block === node) { + findVariablesInScope(scope); + } + } + return { + ArrowFunctionExpression: checkForBlock, + BlockStatement: checkForBlock, + ForInStatement: checkForBlock, + ForOfStatement: checkForBlock, + ForStatement: checkForBlock, + FunctionDeclaration: checkForBlock, + FunctionExpression: checkForBlock, + Program(node) { + const scope = context.sourceCode.getScope(node); + findVariablesInScope(scope); + // Node.js or ES modules has a special scope. + if (scope.type === scope_manager_1.ScopeType.global && + scope.childScopes[0] && + // The special scope's block is the Program node. + scope.block === scope.childScopes[0].block) { + findVariablesInScope(scope.childScopes[0]); + } + }, + SwitchStatement: checkForBlock, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redundant-type-constituents.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redundant-type-constituents.d.ts new file mode 100644 index 00000000..74d21fab --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redundant-type-constituents.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"overrides" | "errorTypeOverrides" | "literalOverridden" | "overridden" | "primitiveOverridden", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-redundant-type-constituents.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redundant-type-constituents.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redundant-type-constituents.d.ts.map new file mode 100644 index 00000000..97a7cb5e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redundant-type-constituents.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-redundant-type-constituents.d.ts","sourceRoot":"","sources":["../../src/rules/no-redundant-type-constituents.ts"],"names":[],"mappings":";AAgMA,wBAqVG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redundant-type-constituents.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redundant-type-constituents.js new file mode 100644 index 00000000..8e14210d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-redundant-type-constituents.js @@ -0,0 +1,431 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const literalToPrimitiveTypeFlags = { + [ts.TypeFlags.BigIntLiteral]: ts.TypeFlags.BigInt, + [ts.TypeFlags.BooleanLiteral]: ts.TypeFlags.Boolean, + [ts.TypeFlags.NumberLiteral]: ts.TypeFlags.Number, + [ts.TypeFlags.StringLiteral]: ts.TypeFlags.String, + [ts.TypeFlags.TemplateLiteral]: ts.TypeFlags.String, +}; +const literalTypeFlags = [ + ts.TypeFlags.BigIntLiteral, + ts.TypeFlags.BooleanLiteral, + ts.TypeFlags.NumberLiteral, + ts.TypeFlags.StringLiteral, + ts.TypeFlags.TemplateLiteral, +]; +const primitiveTypeFlags = [ + ts.TypeFlags.BigInt, + ts.TypeFlags.Boolean, + ts.TypeFlags.Number, + ts.TypeFlags.String, +]; +const primitiveTypeFlagNames = { + [ts.TypeFlags.BigInt]: 'bigint', + [ts.TypeFlags.Boolean]: 'boolean', + [ts.TypeFlags.Number]: 'number', + [ts.TypeFlags.String]: 'string', +}; +const primitiveTypeFlagTypes = { + bigint: ts.TypeFlags.BigIntLiteral, + boolean: ts.TypeFlags.BooleanLiteral, + number: ts.TypeFlags.NumberLiteral, + string: ts.TypeFlags.StringLiteral, +}; +const keywordNodeTypesToTsTypes = new Map([ + [utils_1.TSESTree.AST_NODE_TYPES.TSAnyKeyword, ts.TypeFlags.Any], + [utils_1.TSESTree.AST_NODE_TYPES.TSBigIntKeyword, ts.TypeFlags.BigInt], + [utils_1.TSESTree.AST_NODE_TYPES.TSBooleanKeyword, ts.TypeFlags.Boolean], + [utils_1.TSESTree.AST_NODE_TYPES.TSNeverKeyword, ts.TypeFlags.Never], + [utils_1.TSESTree.AST_NODE_TYPES.TSNumberKeyword, ts.TypeFlags.Number], + [utils_1.TSESTree.AST_NODE_TYPES.TSStringKeyword, ts.TypeFlags.String], + [utils_1.TSESTree.AST_NODE_TYPES.TSUnknownKeyword, ts.TypeFlags.Unknown], +]); +function addToMapGroup(map, key, value) { + const existing = map.get(key); + if (existing) { + existing.push(value); + } + else { + map.set(key, [value]); + } +} +function describeLiteralType(type) { + if (type.isStringLiteral()) { + return JSON.stringify(type.value); + } + if ((0, util_1.isTypeBigIntLiteralType)(type)) { + return `${type.value.negative ? '-' : ''}${type.value.base10Value}n`; + } + if (type.isLiteral()) { + // eslint-disable-next-line @typescript-eslint/no-base-to-string + return type.value.toString(); + } + if (tsutils.isIntrinsicErrorType(type) && type.aliasSymbol) { + return type.aliasSymbol.escapedName.toString(); + } + if ((0, util_1.isTypeAnyType)(type)) { + return 'any'; + } + if ((0, util_1.isTypeNeverType)(type)) { + return 'never'; + } + if ((0, util_1.isTypeUnknownType)(type)) { + return 'unknown'; + } + if ((0, util_1.isTypeTemplateLiteralType)(type)) { + return 'template literal type'; + } + if ((0, util_1.isTypeBigIntLiteralType)(type)) { + return `${type.value.negative ? '-' : ''}${type.value.base10Value}n`; + } + if (tsutils.isTrueLiteralType(type)) { + return 'true'; + } + if (tsutils.isFalseLiteralType(type)) { + return 'false'; + } + return 'literal type'; +} +function describeLiteralTypeNode(typeNode) { + switch (typeNode.type) { + case utils_1.AST_NODE_TYPES.TSAnyKeyword: + return 'any'; + case utils_1.AST_NODE_TYPES.TSBooleanKeyword: + return 'boolean'; + case utils_1.AST_NODE_TYPES.TSNeverKeyword: + return 'never'; + case utils_1.AST_NODE_TYPES.TSNumberKeyword: + return 'number'; + case utils_1.AST_NODE_TYPES.TSStringKeyword: + return 'string'; + case utils_1.AST_NODE_TYPES.TSUnknownKeyword: + return 'unknown'; + case utils_1.AST_NODE_TYPES.TSLiteralType: + switch (typeNode.literal.type) { + case utils_1.TSESTree.AST_NODE_TYPES.Literal: + switch (typeof typeNode.literal.value) { + case 'bigint': + return `${typeNode.literal.value < 0 ? '-' : ''}${typeNode.literal.value}n`; + case 'string': + return JSON.stringify(typeNode.literal.value); + default: + return `${typeNode.literal.value}`; + } + case utils_1.TSESTree.AST_NODE_TYPES.TemplateLiteral: + return 'template literal type'; + } + } + return 'literal type'; +} +function isNodeInsideReturnType(node) { + return (node.parent.type === utils_1.AST_NODE_TYPES.TSTypeAnnotation && + (0, util_1.isFunctionOrFunctionType)(node.parent.parent)); +} +/** + * @remarks TypeScript stores boolean types as the union false | true, always. + */ +function unionTypePartsUnlessBoolean(type) { + return type.isUnion() && + type.types.length === 2 && + tsutils.isFalseLiteralType(type.types[0]) && + tsutils.isTrueLiteralType(type.types[1]) + ? [type] + : tsutils.unionConstituents(type); +} +exports.default = (0, util_1.createRule)({ + name: 'no-redundant-type-constituents', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow members of unions and intersections that do nothing or override type information', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + errorTypeOverrides: `'{{typeName}}' is an 'error' type that acts as 'any' and overrides all other types in this {{container}} type.`, + literalOverridden: `{{literal}} is overridden by {{primitive}} in this union type.`, + overridden: `'{{typeName}}' is overridden by other types in this {{container}} type.`, + overrides: `'{{typeName}}' overrides all other types in this {{container}} type.`, + primitiveOverridden: `{{primitive}} is overridden by the {{literal}} in this intersection type.`, + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const typesCache = new Map(); + function getTypeNodeTypePartFlags(typeNode) { + const keywordTypeFlags = keywordNodeTypesToTsTypes.get(typeNode.type); + if (keywordTypeFlags) { + return [ + { + typeFlags: keywordTypeFlags, + typeName: describeLiteralTypeNode(typeNode), + }, + ]; + } + if (typeNode.type === utils_1.AST_NODE_TYPES.TSLiteralType && + typeNode.literal.type === utils_1.AST_NODE_TYPES.Literal) { + return [ + { + typeFlags: primitiveTypeFlagTypes[typeof typeNode.literal + .value], + typeName: describeLiteralTypeNode(typeNode), + }, + ]; + } + if (typeNode.type === utils_1.AST_NODE_TYPES.TSUnionType) { + return typeNode.types.flatMap(getTypeNodeTypePartFlags); + } + const nodeType = services.getTypeAtLocation(typeNode); + const typeParts = unionTypePartsUnlessBoolean(nodeType); + return typeParts.map(typePart => ({ + typeFlags: typePart.flags, + typeName: describeLiteralType(typePart), + })); + } + function getTypeNodeTypePartFlagsCached(typeNode) { + const existing = typesCache.get(typeNode); + if (existing) { + return existing; + } + const created = getTypeNodeTypePartFlags(typeNode); + typesCache.set(typeNode, created); + return created; + } + return { + 'TSIntersectionType:exit'(node) { + const seenLiteralTypes = new Map(); + const seenPrimitiveTypes = new Map(); + const seenUnionTypes = new Map(); + function checkIntersectionBottomAndTopTypes({ typeFlags, typeName }, typeNode) { + for (const [messageId, checkFlag] of [ + ['overrides', ts.TypeFlags.Any], + ['overrides', ts.TypeFlags.Never], + ['overridden', ts.TypeFlags.Unknown], + ]) { + if (typeFlags === checkFlag) { + context.report({ + node: typeNode, + messageId: typeFlags === ts.TypeFlags.Any && typeName !== 'any' + ? 'errorTypeOverrides' + : messageId, + data: { + container: 'intersection', + typeName, + }, + }); + return true; + } + } + return false; + } + for (const typeNode of node.types) { + const typePartFlags = getTypeNodeTypePartFlagsCached(typeNode); + for (const typePart of typePartFlags) { + if (checkIntersectionBottomAndTopTypes(typePart, typeNode)) { + continue; + } + for (const literalTypeFlag of literalTypeFlags) { + if (typePart.typeFlags === literalTypeFlag) { + addToMapGroup(seenLiteralTypes, literalToPrimitiveTypeFlags[literalTypeFlag], typePart.typeName); + break; + } + } + for (const primitiveTypeFlag of primitiveTypeFlags) { + if (typePart.typeFlags === primitiveTypeFlag) { + addToMapGroup(seenPrimitiveTypes, primitiveTypeFlag, typeNode); + } + } + } + // if any typeNode is TSTypeReference and typePartFlags have more than 1 element, than the referenced type is definitely a union. + if (typePartFlags.length >= 2) { + seenUnionTypes.set(typeNode, typePartFlags); + } + } + /** + * @example + * ```ts + * type F = "a"|2|"b"; + * type I = F & string; + * ``` + * This function checks if all the union members of `F` are assignable to the other member of `I`. If every member is assignable, then its reported else not. + */ + const checkIfUnionsAreAssignable = () => { + for (const [typeRef, typeValues] of seenUnionTypes) { + let primitive = undefined; + for (const { typeFlags } of typeValues) { + if (seenPrimitiveTypes.has(literalToPrimitiveTypeFlags[typeFlags])) { + primitive = + literalToPrimitiveTypeFlags[typeFlags]; + } + else { + primitive = undefined; + break; + } + } + if (Number.isInteger(primitive)) { + context.report({ + node: typeRef, + messageId: 'primitiveOverridden', + data: { + literal: typeValues.map(name => name.typeName).join(' | '), + primitive: primitiveTypeFlagNames[primitive], + }, + }); + } + } + }; + if (seenUnionTypes.size > 0) { + checkIfUnionsAreAssignable(); + return; + } + // For each primitive type of all the seen primitive types, + // if there was a literal type seen that overrides it, + // report each of the primitive type's type nodes + for (const [primitiveTypeFlag, typeNodes] of seenPrimitiveTypes) { + const matchedLiteralTypes = seenLiteralTypes.get(primitiveTypeFlag); + if (matchedLiteralTypes) { + for (const typeNode of typeNodes) { + context.report({ + node: typeNode, + messageId: 'primitiveOverridden', + data: { + literal: matchedLiteralTypes.join(' | '), + primitive: primitiveTypeFlagNames[primitiveTypeFlag], + }, + }); + } + } + } + }, + 'TSUnionType:exit'(node) { + const seenLiteralTypes = new Map(); + const seenPrimitiveTypes = new Set(); + function checkUnionBottomAndTopTypes({ typeFlags, typeName }, typeNode) { + for (const checkFlag of [ + ts.TypeFlags.Any, + ts.TypeFlags.Unknown, + ]) { + if (typeFlags === checkFlag) { + context.report({ + node: typeNode, + messageId: typeFlags === ts.TypeFlags.Any && typeName !== 'any' + ? 'errorTypeOverrides' + : 'overrides', + data: { + container: 'union', + typeName, + }, + }); + return true; + } + } + if (typeFlags === ts.TypeFlags.Never && + !isNodeInsideReturnType(node)) { + context.report({ + node: typeNode, + messageId: 'overridden', + data: { + container: 'union', + typeName: 'never', + }, + }); + return true; + } + return false; + } + for (const typeNode of node.types) { + const typePartFlags = getTypeNodeTypePartFlagsCached(typeNode); + for (const typePart of typePartFlags) { + if (checkUnionBottomAndTopTypes(typePart, typeNode)) { + continue; + } + for (const literalTypeFlag of literalTypeFlags) { + if (typePart.typeFlags === literalTypeFlag) { + addToMapGroup(seenLiteralTypes, literalToPrimitiveTypeFlags[literalTypeFlag], { + literalValue: typePart.typeName, + typeNode, + }); + break; + } + } + for (const primitiveTypeFlag of primitiveTypeFlags) { + if ((typePart.typeFlags & primitiveTypeFlag) !== 0) { + seenPrimitiveTypes.add(primitiveTypeFlag); + } + } + } + } + const overriddenTypeNodes = new Map(); + // For each primitive type of all the seen literal types, + // if there was a primitive type seen that overrides it, + // upsert the literal text and primitive type under the backing type node + for (const [primitiveTypeFlag, typeNodesWithText] of seenLiteralTypes) { + if (seenPrimitiveTypes.has(primitiveTypeFlag)) { + for (const { literalValue, typeNode } of typeNodesWithText) { + addToMapGroup(overriddenTypeNodes, typeNode, { + literalValue, + primitiveTypeFlag, + }); + } + } + } + // For each type node that had at least one overridden literal, + // group those literals by their primitive type, + // then report each primitive type with all its literals + for (const [typeNode, typeFlagsWithText] of overriddenTypeNodes) { + const grouped = (0, util_1.arrayGroupByToMap)(typeFlagsWithText, pair => pair.primitiveTypeFlag); + for (const [primitiveTypeFlag, pairs] of grouped) { + context.report({ + node: typeNode, + messageId: 'literalOverridden', + data: { + literal: pairs.map(pair => pair.literalValue).join(' | '), + primitive: primitiveTypeFlagNames[primitiveTypeFlag], + }, + }); + } + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-require-imports.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-require-imports.d.ts new file mode 100644 index 00000000..eb0a0a66 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-require-imports.d.ts @@ -0,0 +1,10 @@ +export type Options = [ + { + allow?: string[]; + allowAsImport?: boolean; + } +]; +export type MessageIds = 'noRequireImports'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noRequireImports", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-require-imports.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-require-imports.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-require-imports.d.ts.map new file mode 100644 index 00000000..80bb4fbe --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-require-imports.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-require-imports.d.ts","sourceRoot":"","sources":["../../src/rules/no-require-imports.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;QACjB,aAAa,CAAC,EAAE,OAAO,CAAC;KACzB;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,kBAAkB,CAAC;;AAE5C,wBAyFG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-require-imports.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-require-imports.js new file mode 100644 index 00000000..a3bc4840 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-require-imports.js @@ -0,0 +1,115 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util = __importStar(require("../util")); +exports.default = util.createRule({ + name: 'no-require-imports', + meta: { + type: 'problem', + docs: { + description: 'Disallow invocation of `require()`', + recommended: 'recommended', + }, + messages: { + noRequireImports: 'A `require()` style import is forbidden.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allow: { + type: 'array', + description: 'Patterns of import paths to allow requiring from.', + items: { type: 'string' }, + }, + allowAsImport: { + type: 'boolean', + description: 'Allows `require` statements in import declarations.', + }, + }, + }, + ], + }, + defaultOptions: [{ allow: [], allowAsImport: false }], + create(context, options) { + const allowAsImport = options[0].allowAsImport; + const allowPatterns = options[0].allow?.map(pattern => new RegExp(pattern, 'u')); + function isImportPathAllowed(importPath) { + return allowPatterns?.some(pattern => importPath.match(pattern)); + } + function isStringOrTemplateLiteral(node) { + return ((node.type === utils_1.AST_NODE_TYPES.Literal && + typeof node.value === 'string') || + node.type === utils_1.AST_NODE_TYPES.TemplateLiteral); + } + return { + 'CallExpression[callee.name="require"]'(node) { + if (node.arguments[0] && isStringOrTemplateLiteral(node.arguments[0])) { + const argValue = util.getStaticStringValue(node.arguments[0]); + if (typeof argValue === 'string' && isImportPathAllowed(argValue)) { + return; + } + } + const variable = utils_1.ASTUtils.findVariable(context.sourceCode.getScope(node), 'require'); + // ignore non-global require usage as it's something user-land custom instead + // of the commonjs standard + if (!variable?.identifiers.length) { + context.report({ + node, + messageId: 'noRequireImports', + }); + } + }, + TSExternalModuleReference(node) { + if (isStringOrTemplateLiteral(node.expression)) { + const argValue = util.getStaticStringValue(node.expression); + if (typeof argValue === 'string' && isImportPathAllowed(argValue)) { + return; + } + } + if (allowAsImport && + node.parent.type === utils_1.AST_NODE_TYPES.TSImportEqualsDeclaration) { + return; + } + context.report({ + node, + messageId: 'noRequireImports', + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-imports.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-imports.d.ts new file mode 100644 index 00000000..fa7007fe --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-imports.d.ts @@ -0,0 +1,8 @@ +import type { ArrayOfStringOrObject, RuleListener } from 'eslint/lib/rules/no-restricted-imports'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"everything" | "everythingWithCustomMessage" | "importName" | "importNameWithCustomMessage" | "path" | "pathWithCustomMessage" | "patterns" | "patternWithCustomMessage", [import("eslint/lib/rules/no-restricted-imports").ObjectOfPathsAndPatterns] | ArrayOfStringOrObject, unknown, RuleListener>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"everything" | "everythingWithCustomMessage" | "importName" | "importNameWithCustomMessage" | "path" | "pathWithCustomMessage" | "patterns" | "patternWithCustomMessage", [import("eslint/lib/rules/no-restricted-imports").ObjectOfPathsAndPatterns] | ArrayOfStringOrObject, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-restricted-imports.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-imports.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-imports.d.ts.map new file mode 100644 index 00000000..6f9a2945 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-imports.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-restricted-imports.d.ts","sourceRoot":"","sources":["../../src/rules/no-restricted-imports.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,qBAAqB,EAErB,YAAY,EACb,MAAM,wCAAwC,CAAC;AAMhD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ,+VAA6C,CAAC;AAE5D,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;AA4MtE,wBAkJG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-imports.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-imports.js new file mode 100644 index 00000000..83755e3d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-imports.js @@ -0,0 +1,243 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const ignore_1 = __importDefault(require("ignore")); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-restricted-imports'); +// In some versions of eslint, the base rule has a completely incompatible schema +// This helper function is to safely try to get parts of the schema. If it's not +// possible, we'll fallback to less strict checks. +const tryAccess = (getter, fallback) => { + try { + return getter(); + } + catch { + return fallback; + } +}; +const baseSchema = baseRule.meta.schema; +const allowTypeImportsOptionSchema = { + allowTypeImports: { + type: 'boolean', + description: 'Whether to allow type-only imports for a path.', + }, +}; +const arrayOfStringsOrObjects = { + type: 'array', + items: { + anyOf: [ + { type: 'string' }, + { + type: 'object', + additionalProperties: false, + properties: { + ...tryAccess(() => baseSchema.anyOf[1].items[0].properties.paths.items.anyOf[1] + .properties, undefined), + ...allowTypeImportsOptionSchema, + }, + required: tryAccess(() => baseSchema.anyOf[1].items[0].properties.paths.items.anyOf[1] + .required, undefined), + }, + ], + }, + uniqueItems: true, +}; +const arrayOfStringsOrObjectPatterns = { + anyOf: [ + { + type: 'array', + items: { + type: 'string', + }, + uniqueItems: true, + }, + { + type: 'array', + items: { + type: 'object', + additionalProperties: false, + properties: { + ...tryAccess(() => baseSchema.anyOf[1].items[0].properties.patterns.anyOf[1].items + .properties, undefined), + ...allowTypeImportsOptionSchema, + }, + required: tryAccess(() => baseSchema.anyOf[1].items[0].properties.patterns.anyOf[1].items + .required, []), + }, + uniqueItems: true, + }, + ], +}; +const schema = { + anyOf: [ + arrayOfStringsOrObjects, + { + type: 'array', + additionalItems: false, + items: [ + { + type: 'object', + additionalProperties: false, + properties: { + paths: arrayOfStringsOrObjects, + patterns: arrayOfStringsOrObjectPatterns, + }, + }, + ], + }, + ], +}; +function isObjectOfPaths(obj) { + return !!obj && Object.hasOwn(obj, 'paths'); +} +function isObjectOfPatterns(obj) { + return !!obj && Object.hasOwn(obj, 'patterns'); +} +function isOptionsArrayOfStringOrObject(options) { + if (isObjectOfPaths(options[0])) { + return false; + } + if (isObjectOfPatterns(options[0])) { + return false; + } + return true; +} +function getRestrictedPaths(options) { + if (isOptionsArrayOfStringOrObject(options)) { + return options; + } + if (isObjectOfPaths(options[0])) { + return options[0].paths; + } + return []; +} +function getRestrictedPatterns(options) { + if (isObjectOfPatterns(options[0])) { + return options[0].patterns; + } + return []; +} +function shouldCreateRule(baseRules, options) { + if (Object.keys(baseRules).length === 0 || options.length === 0) { + return false; + } + if (!isOptionsArrayOfStringOrObject(options)) { + return !!(options[0].paths?.length || options[0].patterns?.length); + } + return true; +} +exports.default = (0, util_1.createRule)({ + name: 'no-restricted-imports', + meta: { + type: 'suggestion', + // defaultOptions, -- base rule does not use defaultOptions + docs: { + description: 'Disallow specified modules when loaded by `import`', + extendsBaseRule: true, + }, + fixable: baseRule.meta.fixable, + messages: baseRule.meta.messages, + schema, + }, + defaultOptions: [], + create(context) { + const rules = baseRule.create(context); + const { options } = context; + if (!shouldCreateRule(rules, options)) { + return {}; + } + const restrictedPaths = getRestrictedPaths(options); + const allowedTypeImportPathNameSet = new Set(); + for (const restrictedPath of restrictedPaths) { + if (typeof restrictedPath === 'object' && + restrictedPath.allowTypeImports) { + allowedTypeImportPathNameSet.add(restrictedPath.name); + } + } + function isAllowedTypeImportPath(importSource) { + return allowedTypeImportPathNameSet.has(importSource); + } + const restrictedPatterns = getRestrictedPatterns(options); + const allowedImportTypeMatchers = []; + const allowedImportTypeRegexMatchers = []; + for (const restrictedPattern of restrictedPatterns) { + if (typeof restrictedPattern === 'object' && + restrictedPattern.allowTypeImports) { + // Following how ignore is configured in the base rule + if (restrictedPattern.group) { + allowedImportTypeMatchers.push((0, ignore_1.default)({ + allowRelativePaths: true, + ignoreCase: !restrictedPattern.caseSensitive, + }).add(restrictedPattern.group)); + } + if (restrictedPattern.regex) { + allowedImportTypeRegexMatchers.push(new RegExp(restrictedPattern.regex, restrictedPattern.caseSensitive ? 'u' : 'iu')); + } + } + } + function isAllowedTypeImportPattern(importSource) { + return ( + // As long as there's one matching pattern that allows type import + allowedImportTypeMatchers.some(matcher => matcher.ignores(importSource)) || + allowedImportTypeRegexMatchers.some(regex => regex.test(importSource))); + } + function checkImportNode(node) { + if (node.importKind === 'type' || + (node.specifiers.length > 0 && + node.specifiers.every(specifier => specifier.type === utils_1.AST_NODE_TYPES.ImportSpecifier && + specifier.importKind === 'type'))) { + const importSource = node.source.value.trim(); + if (!isAllowedTypeImportPath(importSource) && + !isAllowedTypeImportPattern(importSource)) { + return rules.ImportDeclaration(node); + } + } + else { + return rules.ImportDeclaration(node); + } + } + return { + ExportAllDeclaration: rules.ExportAllDeclaration, + 'ExportNamedDeclaration[source]'(node) { + if (node.exportKind === 'type' || + (node.specifiers.length > 0 && + node.specifiers.every(specifier => specifier.exportKind === 'type'))) { + const importSource = node.source.value.trim(); + if (!isAllowedTypeImportPath(importSource) && + !isAllowedTypeImportPattern(importSource)) { + return rules.ExportNamedDeclaration(node); + } + } + else { + return rules.ExportNamedDeclaration(node); + } + }, + ImportDeclaration: checkImportNode, + TSImportEqualsDeclaration(node) { + if (node.moduleReference.type === utils_1.AST_NODE_TYPES.TSExternalModuleReference) { + const synthesizedImport = { + ...node, + type: utils_1.AST_NODE_TYPES.ImportDeclaration, + assertions: [], + attributes: [], + source: node.moduleReference.expression, + specifiers: [ + { + ...node.id, + type: utils_1.AST_NODE_TYPES.ImportDefaultSpecifier, + local: node.id, + // @ts-expect-error -- parent types are incompatible but it's fine for the purposes of this extension + parent: node.id.parent, + }, + ], + }; + return checkImportNode(synthesizedImport); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-types.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-types.d.ts new file mode 100644 index 00000000..3b11c5fa --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-types.d.ts @@ -0,0 +1,15 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +type Types = Record; +export type Options = [ + { + types?: Types; + } +]; +export type MessageIds = 'bannedTypeMessage' | 'bannedTypeReplacement'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-restricted-types.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-types.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-types.d.ts.map new file mode 100644 index 00000000..7a0f8242 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-restricted-types.d.ts","sourceRoot":"","sources":["../../src/rules/no-restricted-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAMnE,KAAK,KAAK,GAAG,MAAM,CACjB,MAAM,EACJ,OAAO,GACP,MAAM,GACN;IACE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7B,GACD,IAAI,CACP,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,KAAK,CAAC,EAAE,KAAK,CAAC;KACf;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,mBAAmB,GAAG,uBAAuB,CAAC;;AA6CvE,wBAyJG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-types.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-types.js new file mode 100644 index 00000000..fa3204cb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-restricted-types.js @@ -0,0 +1,165 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +function removeSpaces(str) { + return str.replaceAll(/\s/g, ''); +} +function stringifyNode(node, sourceCode) { + return removeSpaces(sourceCode.getText(node)); +} +function getCustomMessage(bannedType) { + if (!bannedType || bannedType === true) { + return ''; + } + if (typeof bannedType === 'string') { + return ` ${bannedType}`; + } + if (bannedType.message) { + return ` ${bannedType.message}`; + } + return ''; +} +const TYPE_KEYWORDS = { + bigint: utils_1.AST_NODE_TYPES.TSBigIntKeyword, + boolean: utils_1.AST_NODE_TYPES.TSBooleanKeyword, + never: utils_1.AST_NODE_TYPES.TSNeverKeyword, + null: utils_1.AST_NODE_TYPES.TSNullKeyword, + number: utils_1.AST_NODE_TYPES.TSNumberKeyword, + object: utils_1.AST_NODE_TYPES.TSObjectKeyword, + string: utils_1.AST_NODE_TYPES.TSStringKeyword, + symbol: utils_1.AST_NODE_TYPES.TSSymbolKeyword, + undefined: utils_1.AST_NODE_TYPES.TSUndefinedKeyword, + unknown: utils_1.AST_NODE_TYPES.TSUnknownKeyword, + void: utils_1.AST_NODE_TYPES.TSVoidKeyword, +}; +exports.default = (0, util_1.createRule)({ + name: 'no-restricted-types', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow certain types', + }, + fixable: 'code', + hasSuggestions: true, + messages: { + bannedTypeMessage: "Don't use `{{name}}` as a type.{{customMessage}}", + bannedTypeReplacement: 'Replace `{{name}}` with `{{replacement}}`.', + }, + schema: [ + { + type: 'object', + $defs: { + banConfig: { + oneOf: [ + { + type: 'boolean', + description: 'Bans the type with the default message.', + enum: [true], + }, + { + type: 'string', + description: 'Bans the type with a custom message.', + }, + { + type: 'object', + additionalProperties: false, + description: 'Bans a type.', + properties: { + fixWith: { + type: 'string', + description: 'Type to autofix replace with. Note that autofixers can be applied automatically - so you need to be careful with this option.', + }, + message: { + type: 'string', + description: 'Custom error message.', + }, + suggest: { + type: 'array', + description: 'Types to suggest replacing with.', + items: { type: 'string' }, + }, + }, + }, + ], + }, + }, + additionalProperties: false, + properties: { + types: { + type: 'object', + additionalProperties: { + $ref: '#/items/0/$defs/banConfig', + }, + description: 'An object whose keys are the types you want to ban, and the values are error messages.', + }, + }, + }, + ], + }, + defaultOptions: [{}], + create(context, [{ types = {} }]) { + const bannedTypes = new Map(Object.entries(types).map(([type, data]) => [removeSpaces(type), data])); + function checkBannedTypes(typeNode, name = stringifyNode(typeNode, context.sourceCode)) { + const bannedType = bannedTypes.get(name); + if (bannedType == null || bannedType === false) { + return; + } + const customMessage = getCustomMessage(bannedType); + const fixWith = bannedType && typeof bannedType === 'object' && bannedType.fixWith; + const suggest = bannedType && typeof bannedType === 'object' + ? bannedType.suggest + : undefined; + context.report({ + node: typeNode, + messageId: 'bannedTypeMessage', + data: { + name, + customMessage, + }, + fix: fixWith + ? (fixer) => fixer.replaceText(typeNode, fixWith) + : null, + suggest: suggest?.map(replacement => ({ + messageId: 'bannedTypeReplacement', + data: { + name, + replacement, + }, + fix: (fixer) => fixer.replaceText(typeNode, replacement), + })), + }); + } + const keywordSelectors = (0, util_1.objectReduceKey)(TYPE_KEYWORDS, (acc, keyword) => { + if (bannedTypes.has(keyword)) { + acc[TYPE_KEYWORDS[keyword]] = (node) => checkBannedTypes(node, keyword); + } + return acc; + }, {}); + return { + ...keywordSelectors, + TSClassImplements(node) { + checkBannedTypes(node); + }, + TSInterfaceHeritage(node) { + checkBannedTypes(node); + }, + TSTupleType(node) { + if (!node.elementTypes.length) { + checkBannedTypes(node); + } + }, + TSTypeLiteral(node) { + if (!node.members.length) { + checkBannedTypes(node); + } + }, + TSTypeReference(node) { + checkBannedTypes(node.typeName); + if (node.typeArguments) { + checkBannedTypes(node); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-shadow.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-shadow.d.ts new file mode 100644 index 00000000..c46c9b6c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-shadow.d.ts @@ -0,0 +1,15 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageIds = 'noShadow' | 'noShadowGlobal'; +export type Options = [ + { + allow?: string[]; + builtinGlobals?: boolean; + hoist?: 'all' | 'functions' | 'functions-and-types' | 'never' | 'types'; + ignoreFunctionTypeParameterNameValueShadow?: boolean; + ignoreOnInitialization?: boolean; + ignoreTypeValueShadow?: boolean; + } +]; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-shadow.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-shadow.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-shadow.d.ts.map new file mode 100644 index 00000000..7749277a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-shadow.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-shadow.d.ts","sourceRoot":"","sources":["../../src/rules/no-shadow.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAQnE,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,gBAAgB,CAAC;AACvD,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;QACjB,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,KAAK,CAAC,EAAE,KAAK,GAAG,WAAW,GAAG,qBAAqB,GAAG,OAAO,GAAG,OAAO,CAAC;QACxE,0CAA0C,CAAC,EAAE,OAAO,CAAC;QACrD,sBAAsB,CAAC,EAAE,OAAO,CAAC;QACjC,qBAAqB,CAAC,EAAE,OAAO,CAAC;KACjC;CACF,CAAC;;AAmBF,wBAgqBG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-shadow.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-shadow.js new file mode 100644 index 00000000..3769ed8c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-shadow.js @@ -0,0 +1,521 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const isTypeImport_1 = require("../util/isTypeImport"); +const allowedFunctionVariableDefTypes = new Set([ + utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration, + utils_1.AST_NODE_TYPES.TSFunctionType, + utils_1.AST_NODE_TYPES.TSMethodSignature, + utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression, + utils_1.AST_NODE_TYPES.TSDeclareFunction, + utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration, + utils_1.AST_NODE_TYPES.TSConstructorType, +]); +const functionsHoistedNodes = new Set([utils_1.AST_NODE_TYPES.FunctionDeclaration]); +const typesHoistedNodes = new Set([ + utils_1.AST_NODE_TYPES.TSInterfaceDeclaration, + utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration, +]); +exports.default = (0, util_1.createRule)({ + name: 'no-shadow', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow variable declarations from shadowing variables declared in the outer scope', + extendsBaseRule: true, + }, + messages: { + noShadow: "'{{name}}' is already declared in the upper scope on line {{shadowedLine}} column {{shadowedColumn}}.", + noShadowGlobal: "'{{name}}' is already a global variable.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allow: { + type: 'array', + description: 'Identifier names for which shadowing is allowed.', + items: { + type: 'string', + }, + }, + builtinGlobals: { + type: 'boolean', + description: 'Whether to report shadowing of built-in global variables.', + }, + hoist: { + type: 'string', + description: 'Whether to report shadowing before outer functions or variables are defined.', + enum: ['all', 'functions', 'functions-and-types', 'never', 'types'], + }, + ignoreFunctionTypeParameterNameValueShadow: { + type: 'boolean', + description: 'Whether to ignore function parameters named the same as a variable.', + }, + ignoreOnInitialization: { + type: 'boolean', + description: 'Whether to ignore the variable initializers when the shadowed variable is presumably still unitialized.', + }, + ignoreTypeValueShadow: { + type: 'boolean', + description: 'Whether to ignore types named the same as a variable.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allow: [], + builtinGlobals: false, + hoist: 'functions-and-types', + ignoreFunctionTypeParameterNameValueShadow: true, + ignoreOnInitialization: false, + ignoreTypeValueShadow: true, + }, + ], + create(context, [options]) { + /** + * Check if a scope is a TypeScript module augmenting the global namespace. + */ + function isGlobalAugmentation(scope) { + return ((scope.type === scope_manager_1.ScopeType.tsModule && scope.block.kind === 'global') || + (!!scope.upper && isGlobalAugmentation(scope.upper))); + } + /** + * Check if variable is a `this` parameter. + */ + function isThisParam(variable) { + return (variable.defs[0].type === scope_manager_1.DefinitionType.Parameter && + variable.name === 'this'); + } + function isTypeValueShadow(variable, shadowed) { + if (options.ignoreTypeValueShadow !== true) { + return false; + } + if (!('isValueVariable' in variable)) { + // this shouldn't happen... + return false; + } + const firstDefinition = shadowed.defs.at(0); + const isShadowedValue = !('isValueVariable' in shadowed) || + !firstDefinition || + (!(0, isTypeImport_1.isTypeImport)(firstDefinition) && shadowed.isValueVariable); + return variable.isValueVariable !== isShadowedValue; + } + function isFunctionTypeParameterNameValueShadow(variable, shadowed) { + if (options.ignoreFunctionTypeParameterNameValueShadow !== true) { + return false; + } + if (!('isValueVariable' in variable)) { + // this shouldn't happen... + return false; + } + const isShadowedValue = 'isValueVariable' in shadowed ? shadowed.isValueVariable : true; + if (!isShadowedValue) { + return false; + } + return variable.defs.every(def => allowedFunctionVariableDefTypes.has(def.node.type)); + } + function isGenericOfStaticMethod(variable) { + if (!('isTypeVariable' in variable)) { + // this shouldn't happen... + return false; + } + if (!variable.isTypeVariable) { + return false; + } + if (variable.identifiers.length === 0) { + return false; + } + const typeParameter = variable.identifiers[0].parent; + if (typeParameter.type !== utils_1.AST_NODE_TYPES.TSTypeParameter) { + return false; + } + const typeParameterDecl = typeParameter.parent; + if (typeParameterDecl.type !== utils_1.AST_NODE_TYPES.TSTypeParameterDeclaration) { + return false; + } + const functionExpr = typeParameterDecl.parent; + if (functionExpr.type !== utils_1.AST_NODE_TYPES.FunctionExpression && + functionExpr.type !== utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression) { + return false; + } + const methodDefinition = functionExpr.parent; + if (methodDefinition.type !== utils_1.AST_NODE_TYPES.MethodDefinition) { + return false; + } + return methodDefinition.static; + } + function isGenericOfClass(variable) { + if (!('isTypeVariable' in variable)) { + // this shouldn't happen... + return false; + } + if (!variable.isTypeVariable) { + return false; + } + if (variable.identifiers.length === 0) { + return false; + } + const typeParameter = variable.identifiers[0].parent; + if (typeParameter.type !== utils_1.AST_NODE_TYPES.TSTypeParameter) { + return false; + } + const typeParameterDecl = typeParameter.parent; + if (typeParameterDecl.type !== utils_1.AST_NODE_TYPES.TSTypeParameterDeclaration) { + return false; + } + const classDecl = typeParameterDecl.parent; + return (classDecl.type === utils_1.AST_NODE_TYPES.ClassDeclaration || + classDecl.type === utils_1.AST_NODE_TYPES.ClassExpression); + } + function isGenericOfAStaticMethodShadow(variable, shadowed) { + return isGenericOfStaticMethod(variable) && isGenericOfClass(shadowed); + } + function isImportDeclaration(definition) { + return definition.type === utils_1.AST_NODE_TYPES.ImportDeclaration; + } + function isExternalModuleDeclarationWithName(scope, name) { + return (scope.type === scope_manager_1.ScopeType.tsModule && + scope.block.id.type === utils_1.AST_NODE_TYPES.Literal && + scope.block.id.value === name); + } + function isExternalDeclarationMerging(scope, variable, shadowed) { + const [firstDefinition] = shadowed.defs; + const [secondDefinition] = variable.defs; + return ((0, isTypeImport_1.isTypeImport)(firstDefinition) && + isImportDeclaration(firstDefinition.parent) && + isExternalModuleDeclarationWithName(scope, firstDefinition.parent.source.value) && + (secondDefinition.node.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration || + secondDefinition.node.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration)); + } + /** + * Check if variable name is allowed. + * @param variable The variable to check. + * @returns Whether or not the variable name is allowed. + */ + function isAllowed(variable) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return options.allow.includes(variable.name); + } + /** + * Checks if a variable of the class name in the class scope of ClassDeclaration. + * + * ClassDeclaration creates two variables of its name into its outer scope and its class scope. + * So we should ignore the variable in the class scope. + * @param variable The variable to check. + * @returns Whether or not the variable of the class name in the class scope of ClassDeclaration. + */ + function isDuplicatedClassNameVariable(variable) { + const block = variable.scope.block; + return (block.type === utils_1.AST_NODE_TYPES.ClassDeclaration && + block.id === variable.identifiers[0]); + } + /** + * Checks if a variable of the class name in the class scope of TSEnumDeclaration. + * + * TSEnumDeclaration creates two variables of its name into its outer scope and its class scope. + * So we should ignore the variable in the class scope. + * @param variable The variable to check. + * @returns Whether or not the variable of the class name in the class scope of TSEnumDeclaration. + */ + function isDuplicatedEnumNameVariable(variable) { + const block = variable.scope.block; + return (block.type === utils_1.AST_NODE_TYPES.TSEnumDeclaration && + block.id === variable.identifiers[0]); + } + /** + * Checks whether or not a given location is inside of the range of a given node. + * @param node An node to check. + * @param location A location to check. + * @returns `true` if the location is inside of the range of the node. + */ + function isInRange(node, location) { + return node && node.range[0] <= location && location <= node.range[1]; + } + /** + * Searches from the current node through its ancestry to find a matching node. + * @param node a node to get. + * @param match a callback that checks whether or not the node verifies its condition or not. + * @returns the matching node. + */ + function findSelfOrAncestor(node, match) { + let currentNode = node; + while (currentNode && !match(currentNode)) { + currentNode = currentNode.parent; + } + return currentNode; + } + /** + * Finds function's outer scope. + * @param scope Function's own scope. + * @returns Function's outer scope. + */ + function getOuterScope(scope) { + const upper = scope.upper; + if (upper?.type === scope_manager_1.ScopeType.functionExpressionName) { + return upper.upper; + } + return upper; + } + /** + * Checks if a variable and a shadowedVariable have the same init pattern ancestor. + * @param variable a variable to check. + * @param shadowedVariable a shadowedVariable to check. + * @returns Whether or not the variable and the shadowedVariable have the same init pattern ancestor. + */ + function isInitPatternNode(variable, shadowedVariable) { + const outerDef = shadowedVariable.defs.at(0); + if (!outerDef) { + return false; + } + const { variableScope } = variable.scope; + if (!((variableScope.block.type === + utils_1.AST_NODE_TYPES.ArrowFunctionExpression || + variableScope.block.type === utils_1.AST_NODE_TYPES.FunctionExpression) && + getOuterScope(variableScope) === shadowedVariable.scope)) { + return false; + } + const fun = variableScope.block; + const { parent } = fun; + const callExpression = findSelfOrAncestor(parent, node => node.type === utils_1.AST_NODE_TYPES.CallExpression); + if (!callExpression) { + return false; + } + let node = outerDef.name; + const location = callExpression.range[1]; + while (node) { + if (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator) { + if (isInRange(node.init, location)) { + return true; + } + if ((node.parent.parent.type === utils_1.AST_NODE_TYPES.ForInStatement || + node.parent.parent.type === utils_1.AST_NODE_TYPES.ForOfStatement) && + isInRange(node.parent.parent.right, location)) { + return true; + } + break; + } + else if (node.type === utils_1.AST_NODE_TYPES.AssignmentPattern) { + if (isInRange(node.right, location)) { + return true; + } + } + else if ([ + utils_1.AST_NODE_TYPES.ArrowFunctionExpression, + utils_1.AST_NODE_TYPES.CatchClause, + utils_1.AST_NODE_TYPES.ClassDeclaration, + utils_1.AST_NODE_TYPES.ClassExpression, + utils_1.AST_NODE_TYPES.ExportNamedDeclaration, + utils_1.AST_NODE_TYPES.FunctionDeclaration, + utils_1.AST_NODE_TYPES.FunctionExpression, + utils_1.AST_NODE_TYPES.ImportDeclaration, + ].includes(node.type)) { + break; + } + node = node.parent; + } + return false; + } + /** + * Checks if a variable is inside the initializer of scopeVar. + * + * To avoid reporting at declarations such as `var a = function a() {};`. + * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`. + * @param variable The variable to check. + * @param scopeVar The scope variable to look for. + * @returns Whether or not the variable is inside initializer of scopeVar. + */ + function isOnInitializer(variable, scopeVar) { + const outerScope = scopeVar.scope; + const outerDef = scopeVar.defs.at(0); + const outer = outerDef?.parent?.range; + const innerScope = variable.scope; + const innerDef = variable.defs.at(0); + const inner = innerDef?.name.range; + return !!(outer && + inner && + outer[0] < inner[0] && + inner[1] < outer[1] && + ((innerDef.type === scope_manager_1.DefinitionType.FunctionName && + innerDef.node.type === utils_1.AST_NODE_TYPES.FunctionExpression) || + innerDef.node.type === utils_1.AST_NODE_TYPES.ClassExpression) && + outerScope === innerScope.upper); + } + /** + * Get a range of a variable's identifier node. + * @param variable The variable to get. + * @returns The range of the variable's identifier node. + */ + function getNameRange(variable) { + const def = variable.defs.at(0); + return def?.name.range; + } + /** + * Checks if a variable is in TDZ of scopeVar. + * @param variable The variable to check. + * @param scopeVar The variable of TDZ. + * @returns Whether or not the variable is in TDZ of scopeVar. + */ + function isInTdz(variable, scopeVar) { + const outerDef = scopeVar.defs.at(0); + const inner = getNameRange(variable); + const outer = getNameRange(scopeVar); + if (!inner || !outer || inner[1] >= outer[0]) { + return false; + } + if (!outerDef) { + return true; + } + if (options.hoist === 'functions') { + return !functionsHoistedNodes.has(outerDef.node.type); + } + if (options.hoist === 'types') { + return !typesHoistedNodes.has(outerDef.node.type); + } + if (options.hoist === 'functions-and-types') { + return (!functionsHoistedNodes.has(outerDef.node.type) && + !typesHoistedNodes.has(outerDef.node.type)); + } + return true; + } + /** + * Get declared line and column of a variable. + * @param variable The variable to get. + * @returns The declared line and column of the variable. + */ + function getDeclaredLocation(variable) { + const identifier = variable.identifiers.at(0); + if (identifier) { + return { + column: identifier.loc.start.column + 1, + global: false, + line: identifier.loc.start.line, + }; + } + return { + global: true, + }; + } + /** + * Checks if the initialization of a variable has the declare modifier in a + * definition file. + */ + function isDeclareInDTSFile(variable) { + const fileName = context.filename; + if (!(0, util_1.isDefinitionFile)(fileName)) { + return false; + } + return variable.defs.some(def => { + return ((def.type === scope_manager_1.DefinitionType.Variable && def.parent.declare) || + (def.type === scope_manager_1.DefinitionType.ClassName && def.node.declare) || + (def.type === scope_manager_1.DefinitionType.TSEnumName && def.node.declare) || + (def.type === scope_manager_1.DefinitionType.TSModuleName && def.node.declare)); + }); + } + /** + * Checks the current context for shadowed variables. + * @param scope Fixme + */ + function checkForShadows(scope) { + // ignore global augmentation + if (isGlobalAugmentation(scope)) { + return; + } + const variables = scope.variables; + for (const variable of variables) { + // ignore "arguments" + if (variable.identifiers.length === 0) { + continue; + } + // this params are pseudo-params that cannot be shadowed + if (isThisParam(variable)) { + continue; + } + // ignore variables of a class name in the class scope of ClassDeclaration + if (isDuplicatedClassNameVariable(variable)) { + continue; + } + // ignore variables of a class name in the class scope of ClassDeclaration + if (isDuplicatedEnumNameVariable(variable)) { + continue; + } + // ignore configured allowed names + if (isAllowed(variable)) { + continue; + } + // ignore variables with the declare keyword in .d.ts files + if (isDeclareInDTSFile(variable)) { + continue; + } + // Gets shadowed variable. + const shadowed = scope.upper + ? utils_1.ASTUtils.findVariable(scope.upper, variable.name) + : null; + if (!shadowed) { + continue; + } + // ignore type value variable shadowing if configured + if (isTypeValueShadow(variable, shadowed)) { + continue; + } + // ignore function type parameter name shadowing if configured + if (isFunctionTypeParameterNameValueShadow(variable, shadowed)) { + continue; + } + // ignore static class method generic shadowing class generic + // this is impossible for the scope analyser to understand + // so we have to handle this manually in this rule + if (isGenericOfAStaticMethodShadow(variable, shadowed)) { + continue; + } + if (isExternalDeclarationMerging(scope, variable, shadowed)) { + continue; + } + const isESLintGlobal = 'writeable' in shadowed; + if ((shadowed.identifiers.length > 0 || + (options.builtinGlobals && isESLintGlobal)) && + !isOnInitializer(variable, shadowed) && + !(options.ignoreOnInitialization && + isInitPatternNode(variable, shadowed)) && + !(options.hoist !== 'all' && isInTdz(variable, shadowed))) { + const location = getDeclaredLocation(shadowed); + context.report({ + node: variable.identifiers[0], + ...(location.global + ? { + messageId: 'noShadowGlobal', + data: { + name: variable.name, + }, + } + : { + messageId: 'noShadow', + data: { + name: variable.name, + shadowedColumn: location.column, + shadowedLine: location.line, + }, + }), + }); + } + } + } + return { + 'Program:exit'(node) { + const globalScope = context.sourceCode.getScope(node); + const stack = [...globalScope.childScopes]; + while (stack.length) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const scope = stack.pop(); + stack.push(...scope.childScopes); + checkForShadows(scope); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-this-alias.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-this-alias.d.ts new file mode 100644 index 00000000..fa3dfe1a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-this-alias.d.ts @@ -0,0 +1,10 @@ +export type Options = [ + { + allowDestructuring?: boolean; + allowedNames?: string[]; + } +]; +export type MessageIds = 'thisAssignment' | 'thisDestructure'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-this-alias.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-this-alias.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-this-alias.d.ts.map new file mode 100644 index 00000000..41e7fbc9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-this-alias.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-this-alias.d.ts","sourceRoot":"","sources":["../../src/rules/no-this-alias.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;KACzB;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,gBAAgB,GAAG,iBAAiB,CAAC;;AAE9D,wBAsEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-this-alias.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-this-alias.js new file mode 100644 index 00000000..f63fa3c6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-this-alias.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-this-alias', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow aliasing `this`', + recommended: 'recommended', + }, + messages: { + thisAssignment: "Unexpected aliasing of 'this' to local variable.", + thisDestructure: "Unexpected aliasing of members of 'this' to local variables.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowDestructuring: { + type: 'boolean', + description: 'Whether to ignore destructurings, such as `const { props, state } = this`.', + }, + allowedNames: { + type: 'array', + description: 'Names to ignore, such as ["self"] for `const self = this;`.', + items: { + type: 'string', + }, + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowDestructuring: true, + allowedNames: [], + }, + ], + create(context, [{ allowDestructuring, allowedNames }]) { + return { + "VariableDeclarator[init.type='ThisExpression'], AssignmentExpression[right.type='ThisExpression']"(node) { + const id = node.type === utils_1.AST_NODE_TYPES.VariableDeclarator ? node.id : node.left; + if (allowDestructuring && id.type !== utils_1.AST_NODE_TYPES.Identifier) { + return; + } + const hasAllowedName = id.type === utils_1.AST_NODE_TYPES.Identifier + ? // https://github.com/typescript-eslint/typescript-eslint/issues/5439 + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + allowedNames.includes(id.name) + : false; + if (!hasAllowedName) { + context.report({ + node: id, + messageId: id.type === utils_1.AST_NODE_TYPES.Identifier + ? 'thisAssignment' + : 'thisDestructure', + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-type-alias.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-type-alias.d.ts new file mode 100644 index 00000000..8a855c13 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-type-alias.d.ts @@ -0,0 +1,17 @@ +type Values = 'always' | 'in-intersections' | 'in-unions' | 'in-unions-and-intersections' | 'never'; +export type Options = [ + { + allowAliases?: Values; + allowCallbacks?: 'always' | 'never'; + allowConditionalTypes?: 'always' | 'never'; + allowConstructors?: 'always' | 'never'; + allowGenerics?: 'always' | 'never'; + allowLiterals?: Values; + allowMappedTypes?: Values; + allowTupleTypes?: Values; + } +]; +export type MessageIds = 'noCompositionAlias' | 'noTypeAlias'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-type-alias.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-type-alias.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-type-alias.d.ts.map new file mode 100644 index 00000000..9e313de4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-type-alias.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-type-alias.d.ts","sourceRoot":"","sources":["../../src/rules/no-type-alias.ts"],"names":[],"mappings":"AAMA,KAAK,MAAM,GACP,QAAQ,GACR,kBAAkB,GAClB,WAAW,GACX,6BAA6B,GAC7B,OAAO,CAAC;AAEZ,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,cAAc,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;QACpC,qBAAqB,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;QAC3C,iBAAiB,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;QACvC,aAAa,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;QACnC,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,eAAe,CAAC,EAAE,MAAM,CAAC;KAC1B;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,oBAAoB,GAAG,aAAa,CAAC;;AAU9D,wBAmUG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-type-alias.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-type-alias.js new file mode 100644 index 00000000..dd1cdbe7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-type-alias.js @@ -0,0 +1,269 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-type-alias', + meta: { + type: 'suggestion', + deprecated: { + deprecatedSince: '6.0.0', + replacedBy: [ + { + rule: { + name: '@typescript-eslint/consistent-type-definitions', + url: 'https://typescript-eslint.io/rules/consistent-type-definitions', + }, + }, + ], + url: 'https://github.com/typescript-eslint/typescript-eslint/pull/6229', + }, + docs: { + description: 'Disallow type aliases', + // too opinionated to be recommended + }, + messages: { + noCompositionAlias: '{{typeName}} in {{compositionType}} types are not allowed.', + noTypeAlias: 'Type {{alias}} are not allowed.', + }, + schema: [ + { + type: 'object', + $defs: { + expandedOptions: { + type: 'string', + enum: [ + 'always', + 'never', + 'in-unions', + 'in-intersections', + 'in-unions-and-intersections', + ], + }, + simpleOptions: { + type: 'string', + enum: ['always', 'never'], + }, + }, + additionalProperties: false, + properties: { + allowAliases: { + $ref: '#/items/0/$defs/expandedOptions', + description: 'Whether to allow direct one-to-one type aliases.', + }, + allowCallbacks: { + $ref: '#/items/0/$defs/simpleOptions', + description: 'Whether to allow type aliases for callbacks.', + }, + allowConditionalTypes: { + $ref: '#/items/0/$defs/simpleOptions', + description: 'Whether to allow type aliases for conditional types.', + }, + allowConstructors: { + $ref: '#/items/0/$defs/simpleOptions', + description: 'Whether to allow type aliases with constructors.', + }, + allowGenerics: { + $ref: '#/items/0/$defs/simpleOptions', + description: 'Whether to allow type aliases with generic types.', + }, + allowLiterals: { + $ref: '#/items/0/$defs/expandedOptions', + description: 'Whether to allow type aliases with object literal types.', + }, + allowMappedTypes: { + $ref: '#/items/0/$defs/expandedOptions', + description: 'Whether to allow type aliases with mapped types.', + }, + allowTupleTypes: { + $ref: '#/items/0/$defs/expandedOptions', + description: 'Whether to allow type aliases with tuple types.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowAliases: 'never', + allowCallbacks: 'never', + allowConditionalTypes: 'never', + allowConstructors: 'never', + allowGenerics: 'never', + allowLiterals: 'never', + allowMappedTypes: 'never', + allowTupleTypes: 'never', + }, + ], + create(context, [{ allowAliases, allowCallbacks, allowConditionalTypes, allowConstructors, allowGenerics, allowLiterals, allowMappedTypes, allowTupleTypes, },]) { + const unions = ['always', 'in-unions', 'in-unions-and-intersections']; + const intersections = [ + 'always', + 'in-intersections', + 'in-unions-and-intersections', + ]; + const compositions = [ + 'in-unions', + 'in-intersections', + 'in-unions-and-intersections', + ]; + const aliasTypes = new Set([ + utils_1.AST_NODE_TYPES.TSArrayType, + utils_1.AST_NODE_TYPES.TSImportType, + utils_1.AST_NODE_TYPES.TSIndexedAccessType, + utils_1.AST_NODE_TYPES.TSLiteralType, + utils_1.AST_NODE_TYPES.TSTemplateLiteralType, + utils_1.AST_NODE_TYPES.TSTypeQuery, + utils_1.AST_NODE_TYPES.TSTypeReference, + ]); + /** + * Determines if the composition type is supported by the allowed flags. + * @param isTopLevel a flag indicating this is the top level node. + * @param compositionType the composition type (either TSUnionType or TSIntersectionType) + * @param allowed the currently allowed flags. + */ + function isSupportedComposition(isTopLevel, compositionType, allowed) { + return (!compositions.includes(allowed) || + (!isTopLevel && + ((compositionType === utils_1.AST_NODE_TYPES.TSUnionType && + unions.includes(allowed)) || + (compositionType === utils_1.AST_NODE_TYPES.TSIntersectionType && + intersections.includes(allowed))))); + } + /** + * Gets the message to be displayed based on the node type and whether the node is a top level declaration. + * @param node the location + * @param compositionType the type of composition this alias is part of (undefined if not + * part of a composition) + * @param isRoot a flag indicating we are dealing with the top level declaration. + * @param type the kind of type alias being validated. + */ + function reportError(node, compositionType, isRoot, type) { + if (isRoot) { + return context.report({ + node, + messageId: 'noTypeAlias', + data: { + alias: type.toLowerCase(), + }, + }); + } + return context.report({ + node, + messageId: 'noCompositionAlias', + data: { + compositionType: compositionType === utils_1.AST_NODE_TYPES.TSUnionType + ? 'union' + : 'intersection', + typeName: type, + }, + }); + } + const isValidTupleType = (type) => { + if (type.node.type === utils_1.AST_NODE_TYPES.TSTupleType) { + return true; + } + if (type.node.type === utils_1.AST_NODE_TYPES.TSTypeOperator && + ['keyof', 'readonly'].includes(type.node.operator) && + type.node.typeAnnotation && + type.node.typeAnnotation.type === utils_1.AST_NODE_TYPES.TSTupleType) { + return true; + } + return false; + }; + const isValidGeneric = (type) => { + return (type.node.type === utils_1.AST_NODE_TYPES.TSTypeReference && + type.node.typeArguments != null); + }; + const checkAndReport = (optionValue, isTopLevel, type, label) => { + if (optionValue === 'never' || + !isSupportedComposition(isTopLevel, type.compositionType, optionValue)) { + reportError(type.node, type.compositionType, isTopLevel, label); + } + }; + /** + * Validates the node looking for aliases, callbacks and literals. + * @param type the type of composition this alias is part of (null if not + * part of a composition) + * @param isTopLevel a flag indicating this is the top level node. + */ + function validateTypeAliases(type, isTopLevel = false) { + // https://github.com/typescript-eslint/typescript-eslint/issues/5439 + /* eslint-disable @typescript-eslint/no-non-null-assertion */ + if (type.node.type === utils_1.AST_NODE_TYPES.TSFunctionType) { + // callback + if (allowCallbacks === 'never') { + reportError(type.node, type.compositionType, isTopLevel, 'Callbacks'); + } + } + else if (type.node.type === utils_1.AST_NODE_TYPES.TSConditionalType) { + // conditional type + if (allowConditionalTypes === 'never') { + reportError(type.node, type.compositionType, isTopLevel, 'Conditional types'); + } + } + else if (type.node.type === utils_1.AST_NODE_TYPES.TSConstructorType) { + if (allowConstructors === 'never') { + reportError(type.node, type.compositionType, isTopLevel, 'Constructors'); + } + } + else if (type.node.type === utils_1.AST_NODE_TYPES.TSTypeLiteral) { + // literal object type + checkAndReport(allowLiterals, isTopLevel, type, 'Literals'); + } + else if (type.node.type === utils_1.AST_NODE_TYPES.TSMappedType) { + // mapped type + checkAndReport(allowMappedTypes, isTopLevel, type, 'Mapped types'); + } + else if (isValidTupleType(type)) { + // tuple types + checkAndReport(allowTupleTypes, isTopLevel, type, 'Tuple Types'); + } + else if (isValidGeneric(type)) { + if (allowGenerics === 'never') { + reportError(type.node, type.compositionType, isTopLevel, 'Generics'); + } + } + else if (type.node.type.endsWith(utils_1.AST_TOKEN_TYPES.Keyword) || + aliasTypes.has(type.node.type) || + (type.node.type === utils_1.AST_NODE_TYPES.TSTypeOperator && + (type.node.operator === 'keyof' || + (type.node.operator === 'readonly' && + type.node.typeAnnotation && + aliasTypes.has(type.node.typeAnnotation.type))))) { + // alias / keyword + checkAndReport(allowAliases, isTopLevel, type, 'Aliases'); + } + else { + // unhandled type - shouldn't happen + reportError(type.node, type.compositionType, isTopLevel, 'Unhandled'); + } + /* eslint-enable @typescript-eslint/no-non-null-assertion */ + } + /** + * Flatten the given type into an array of its dependencies + */ + function getTypes(node, compositionType = null) { + if (node.type === utils_1.AST_NODE_TYPES.TSUnionType || + node.type === utils_1.AST_NODE_TYPES.TSIntersectionType) { + return node.types.flatMap(type => getTypes(type, node.type)); + } + return [{ node, compositionType }]; + } + return { + TSTypeAliasDeclaration(node) { + const types = getTypes(node.typeAnnotation); + if (types.length === 1) { + // is a top level type annotation + validateTypeAliases(types[0], true); + } + else { + // is a composition type + types.forEach(type => { + validateTypeAliases(type); + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-boolean-literal-compare.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-boolean-literal-compare.d.ts new file mode 100644 index 00000000..66c6610b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-boolean-literal-compare.d.ts @@ -0,0 +1,11 @@ +export type MessageIds = 'comparingNullableToFalse' | 'comparingNullableToTrueDirect' | 'comparingNullableToTrueNegated' | 'direct' | 'negated' | 'noStrictNullCheck'; +export type Options = [ + { + allowComparingNullableBooleansToFalse?: boolean; + allowComparingNullableBooleansToTrue?: boolean; + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean; + } +]; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-unnecessary-boolean-literal-compare.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-boolean-literal-compare.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-boolean-literal-compare.d.ts.map new file mode 100644 index 00000000..7544513d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-boolean-literal-compare.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-boolean-literal-compare.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-boolean-literal-compare.ts"],"names":[],"mappings":"AAaA,MAAM,MAAM,UAAU,GAClB,0BAA0B,GAC1B,+BAA+B,GAC/B,gCAAgC,GAChC,QAAQ,GACR,SAAS,GACT,mBAAmB,CAAC;AAExB,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,qCAAqC,CAAC,EAAE,OAAO,CAAC;QAChD,oCAAoC,CAAC,EAAE,OAAO,CAAC;QAC/C,sDAAsD,CAAC,EAAE,OAAO,CAAC;KAClE;CACF,CAAC;;AAYF,wBAkRG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-boolean-literal-compare.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-boolean-literal-compare.js new file mode 100644 index 00000000..f2db70ac --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-boolean-literal-compare.js @@ -0,0 +1,263 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unnecessary-boolean-literal-compare', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow unnecessary equality comparisons against boolean literals', + recommended: 'strict', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + comparingNullableToFalse: 'This expression unnecessarily compares a nullable boolean value to false instead of using the ?? operator to provide a default.', + comparingNullableToTrueDirect: 'This expression unnecessarily compares a nullable boolean value to true instead of using it directly.', + comparingNullableToTrueNegated: 'This expression unnecessarily compares a nullable boolean value to true instead of negating it.', + direct: 'This expression unnecessarily compares a boolean value to a boolean instead of using it directly.', + negated: 'This expression unnecessarily compares a boolean value to a boolean instead of negating it.', + noStrictNullCheck: 'This rule requires the `strictNullChecks` compiler option to be turned on to function correctly.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowComparingNullableBooleansToFalse: { + type: 'boolean', + description: 'Whether to allow comparisons between nullable boolean variables and `false`.', + }, + allowComparingNullableBooleansToTrue: { + type: 'boolean', + description: 'Whether to allow comparisons between nullable boolean variables and `true`.', + }, + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: { + type: 'boolean', + description: 'Unless this is set to `true`, the rule will error on every file whose `tsconfig.json` does _not_ have the `strictNullChecks` compiler option (or `strict`) set to `true`.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowComparingNullableBooleansToFalse: true, + allowComparingNullableBooleansToTrue: true, + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false, + }, + ], + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const compilerOptions = services.program.getCompilerOptions(); + const isStrictNullChecks = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks'); + if (!isStrictNullChecks && + options.allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing !== true) { + context.report({ + loc: { + start: { column: 0, line: 0 }, + end: { column: 0, line: 0 }, + }, + messageId: 'noStrictNullCheck', + }); + } + function getBooleanComparison(node) { + const comparison = deconstructComparison(node); + if (!comparison) { + return undefined; + } + const { constraintType, isTypeParameter } = (0, util_1.getConstraintInfo)(checker, services.getTypeAtLocation(comparison.expression)); + if (isTypeParameter && constraintType == null) { + return undefined; + } + if (isBooleanType(constraintType)) { + return { + ...comparison, + expressionIsNullableBoolean: false, + }; + } + if (isNullableBoolean(constraintType)) { + return { + ...comparison, + expressionIsNullableBoolean: true, + }; + } + return undefined; + } + function isBooleanType(expressionType) { + return tsutils.isTypeFlagSet(expressionType, ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral); + } + /** + * checks if the expressionType is a union that + * 1) contains at least one nullish type (null or undefined) + * 2) contains at least once boolean type (true or false or boolean) + * 3) does not contain any types besides nullish and boolean types + */ + function isNullableBoolean(expressionType) { + if (!expressionType.isUnion()) { + return false; + } + const { types } = expressionType; + const nonNullishTypes = types.filter(type => !tsutils.isTypeFlagSet(type, ts.TypeFlags.Undefined | ts.TypeFlags.Null)); + const hasNonNullishType = nonNullishTypes.length > 0; + if (!hasNonNullishType) { + return false; + } + const hasNullableType = nonNullishTypes.length < types.length; + if (!hasNullableType) { + return false; + } + const allNonNullishTypesAreBoolean = nonNullishTypes.every(isBooleanType); + if (!allNonNullishTypesAreBoolean) { + return false; + } + return true; + } + function deconstructComparison(node) { + const comparisonType = getEqualsKind(node.operator); + if (!comparisonType) { + return undefined; + } + for (const [against, expression] of [ + [node.right, node.left], + [node.left, node.right], + ]) { + if (against.type !== utils_1.AST_NODE_TYPES.Literal || + typeof against.value !== 'boolean') { + continue; + } + const { value: literalBooleanInComparison } = against; + const negated = !comparisonType.isPositive; + return { + expression, + literalBooleanInComparison, + negated, + }; + } + return undefined; + } + function nodeIsUnaryNegation(node) { + return (node.type === utils_1.AST_NODE_TYPES.UnaryExpression && + node.prefix && + node.operator === '!'); + } + return { + BinaryExpression(node) { + const comparison = getBooleanComparison(node); + if (comparison == null) { + return; + } + if (comparison.expressionIsNullableBoolean) { + if (comparison.literalBooleanInComparison && + options.allowComparingNullableBooleansToTrue) { + return; + } + if (!comparison.literalBooleanInComparison && + options.allowComparingNullableBooleansToFalse) { + return; + } + } + context.report({ + node, + messageId: comparison.expressionIsNullableBoolean + ? comparison.literalBooleanInComparison + ? comparison.negated + ? 'comparingNullableToTrueNegated' + : 'comparingNullableToTrueDirect' + : 'comparingNullableToFalse' + : comparison.negated + ? 'negated' + : 'direct', + *fix(fixer) { + // 1. isUnaryNegation - parent negation + // 2. literalBooleanInComparison - is compared to literal boolean + // 3. negated - is expression negated + const isUnaryNegation = nodeIsUnaryNegation(node.parent); + const shouldNegate = comparison.negated !== comparison.literalBooleanInComparison; + const mutatedNode = isUnaryNegation ? node.parent : node; + yield fixer.replaceText(mutatedNode, context.sourceCode.getText(comparison.expression)); + // if `isUnaryNegation === literalBooleanInComparison === !negated` is true - negate the expression + if (shouldNegate === isUnaryNegation) { + yield fixer.insertTextBefore(mutatedNode, '!'); + // if the expression `exp` is not a strong precedence node, wrap it in parentheses + if (!(0, util_1.isStrongPrecedenceNode)(comparison.expression)) { + yield fixer.insertTextBefore(mutatedNode, '('); + yield fixer.insertTextAfter(mutatedNode, ')'); + } + } + // if the expression `exp` is nullable, and we're not comparing to `true`, insert `?? true` + if (comparison.expressionIsNullableBoolean && + !comparison.literalBooleanInComparison) { + // provide the default `true` + yield fixer.insertTextBefore(mutatedNode, '('); + yield fixer.insertTextAfter(mutatedNode, ' ?? true)'); + } + }, + }); + }, + }; + }, +}); +function getEqualsKind(operator) { + switch (operator) { + case '!=': + return { + isPositive: false, + isStrict: false, + }; + case '!==': + return { + isPositive: false, + isStrict: true, + }; + case '==': + return { + isPositive: true, + isStrict: false, + }; + case '===': + return { + isPositive: true, + isStrict: true, + }; + default: + return undefined; + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-condition.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-condition.d.ts new file mode 100644 index 00000000..8fc8ae36 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-condition.d.ts @@ -0,0 +1,13 @@ +type LegacyAllowConstantLoopConditions = boolean; +type AllowConstantLoopConditions = 'always' | 'never' | 'only-allowed-literals'; +export type Options = [ + { + allowConstantLoopConditions?: AllowConstantLoopConditions | LegacyAllowConstantLoopConditions; + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean; + checkTypePredicates?: boolean; + } +]; +export type MessageId = 'alwaysFalsy' | 'alwaysFalsyFunc' | 'alwaysNullish' | 'alwaysTruthy' | 'alwaysTruthyFunc' | 'comparisonBetweenLiteralTypes' | 'never' | 'neverNullish' | 'neverOptionalChain' | 'noOverlapBooleanExpression' | 'noStrictNullCheck' | 'suggestRemoveOptionalChain' | 'typeGuardAlreadyIsType'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-unnecessary-condition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-condition.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-condition.d.ts.map new file mode 100644 index 00000000..4e68b814 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-condition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-condition.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-condition.ts"],"names":[],"mappings":"AAyHA,KAAK,iCAAiC,GAAG,OAAO,CAAC;AAEjD,KAAK,2BAA2B,GAAG,QAAQ,GAAG,OAAO,GAAG,uBAAuB,CAAC;AAShF,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,2BAA2B,CAAC,EACxB,2BAA2B,GAC3B,iCAAiC,CAAC;QACtC,sDAAsD,CAAC,EAAE,OAAO,CAAC;QACjE,mBAAmB,CAAC,EAAE,OAAO,CAAC;KAC/B;CACF,CAAC;AAEF,MAAM,MAAM,SAAS,GACjB,aAAa,GACb,iBAAiB,GACjB,eAAe,GACf,cAAc,GACd,kBAAkB,GAClB,+BAA+B,GAC/B,OAAO,GACP,cAAc,GACd,oBAAoB,GACpB,4BAA4B,GAC5B,mBAAmB,GACnB,4BAA4B,GAC5B,wBAAwB,CAAC;;AAE7B,wBA0wBG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-condition.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-condition.js new file mode 100644 index 00000000..2cf902d2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-condition.js @@ -0,0 +1,676 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const assertionFunctionUtils_1 = require("../util/assertionFunctionUtils"); +// #region +const nullishFlag = ts.TypeFlags.Undefined | ts.TypeFlags.Null; +function isNullishType(type) { + return tsutils.isTypeFlagSet(type, nullishFlag); +} +function isAlwaysNullish(type) { + return tsutils.unionConstituents(type).every(isNullishType); +} +/** + * Note that this differs from {@link isNullableType} in that it doesn't consider + * `any` or `unknown` to be nullable. + */ +function isPossiblyNullish(type) { + return tsutils.unionConstituents(type).some(isNullishType); +} +function toStaticValue(type) { + // type.isLiteral() only covers numbers/bigints and strings, hence the rest of the branches. + if (tsutils.isBooleanLiteralType(type)) { + return { value: tsutils.isTrueLiteralType(type) }; + } + if (type.flags === ts.TypeFlags.Undefined) { + return { value: undefined }; + } + if (type.flags === ts.TypeFlags.Null) { + return { value: null }; + } + if (type.isLiteral()) { + return { value: (0, util_1.getValueOfLiteralType)(type) }; + } + return undefined; +} +const BOOL_OPERATORS = new Set([ + '<', + '>', + '<=', + '>=', + '==', + '===', + '!=', + '!==', +]); +function isBoolOperator(operator) { + return BOOL_OPERATORS.has(operator); +} +function booleanComparison(left, operator, right) { + switch (operator) { + case '!=': + // eslint-disable-next-line eqeqeq -- intentionally comparing with loose equality + return left != right; + case '!==': + return left !== right; + case '<': + // @ts-expect-error: we don't care if the comparison seems unintentional. + return left < right; + case '<=': + // @ts-expect-error: we don't care if the comparison seems unintentional. + return left <= right; + case '==': + // eslint-disable-next-line eqeqeq -- intentionally comparing with loose equality + return left == right; + case '===': + return left === right; + case '>': + // @ts-expect-error: we don't care if the comparison seems unintentional. + return left > right; + case '>=': + // @ts-expect-error: we don't care if the comparison seems unintentional. + return left >= right; + } +} +const constantLoopConditionsAllowedLiterals = new Set([ + true, + false, + 1, + 0, +]); +exports.default = (0, util_1.createRule)({ + name: 'no-unnecessary-condition', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow conditionals where the type is always truthy or always falsy', + recommended: 'strict', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + alwaysFalsy: 'Unnecessary conditional, value is always falsy.', + alwaysFalsyFunc: 'This callback should return a conditional, but return is always falsy.', + alwaysNullish: 'Unnecessary conditional, left-hand side of `??` operator is always `null` or `undefined`.', + alwaysTruthy: 'Unnecessary conditional, value is always truthy.', + alwaysTruthyFunc: 'This callback should return a conditional, but return is always truthy.', + comparisonBetweenLiteralTypes: 'Unnecessary conditional, comparison is always {{trueOrFalse}}, since `{{left}} {{operator}} {{right}}` is {{trueOrFalse}}.', + never: 'Unnecessary conditional, value is `never`.', + neverNullish: 'Unnecessary conditional, expected left-hand side of `??` operator to be possibly null or undefined.', + neverOptionalChain: 'Unnecessary optional chain on a non-nullish value.', + noOverlapBooleanExpression: 'Unnecessary conditional, the types have no overlap.', + noStrictNullCheck: 'This rule requires the `strictNullChecks` compiler option to be turned on to function correctly.', + suggestRemoveOptionalChain: 'Remove unnecessary optional chain', + typeGuardAlreadyIsType: 'Unnecessary conditional, expression already has the type being checked by the {{typeGuardOrAssertionFunction}}.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowConstantLoopConditions: { + description: 'Whether to ignore constant loop conditions, such as `while (true)`.', + oneOf: [ + { + type: 'boolean', + }, + { + type: 'string', + enum: ['always', 'never', 'only-allowed-literals'], + }, + ], + }, + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: { + type: 'boolean', + description: 'Whether to not error when running with a tsconfig that has strictNullChecks turned.', + }, + checkTypePredicates: { + type: 'boolean', + description: 'Whether to check the asserted argument of a type predicate function for unnecessary conditions', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowConstantLoopConditions: 'never', + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false, + checkTypePredicates: false, + }, + ], + create(context, [{ allowConstantLoopConditions, allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing, checkTypePredicates, },]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const compilerOptions = services.program.getCompilerOptions(); + const isStrictNullChecks = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks'); + const isNoUncheckedIndexedAccess = tsutils.isCompilerOptionEnabled(compilerOptions, 'noUncheckedIndexedAccess'); + const allowConstantLoopConditionsOption = normalizeAllowConstantLoopConditions( + // https://github.com/typescript-eslint/typescript-eslint/issues/5439 + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + allowConstantLoopConditions); + if (!isStrictNullChecks && + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing !== true) { + context.report({ + loc: { + start: { column: 0, line: 0 }, + end: { column: 0, line: 0 }, + }, + messageId: 'noStrictNullCheck', + }); + } + function nodeIsArrayType(node) { + const nodeType = (0, util_1.getConstrainedTypeAtLocation)(services, node); + return tsutils + .unionConstituents(nodeType) + .some(part => checker.isArrayType(part)); + } + function nodeIsTupleType(node) { + const nodeType = (0, util_1.getConstrainedTypeAtLocation)(services, node); + return tsutils + .unionConstituents(nodeType) + .some(part => checker.isTupleType(part)); + } + function isArrayIndexExpression(node) { + return ( + // Is an index signature + node.type === utils_1.AST_NODE_TYPES.MemberExpression && + node.computed && + // ...into an array type + (nodeIsArrayType(node.object) || + // ... or a tuple type + (nodeIsTupleType(node.object) && + // Exception: literal index into a tuple - will have a sound type + node.property.type !== utils_1.AST_NODE_TYPES.Literal))); + } + // Conditional is always necessary if it involves: + // `any` or `unknown` or a naked type variable + function isConditionalAlwaysNecessary(type) { + return tsutils + .unionConstituents(type) + .some(part => (0, util_1.isTypeAnyType)(part) || + (0, util_1.isTypeUnknownType)(part) || + (0, util_1.isTypeFlagSet)(part, ts.TypeFlags.TypeVariable)); + } + function isNullableMemberExpression(node) { + const objectType = services.getTypeAtLocation(node.object); + if (node.computed) { + const propertyType = services.getTypeAtLocation(node.property); + return isNullablePropertyType(objectType, propertyType); + } + const property = node.property; + // Get the actual property name, to account for private properties (this.#prop). + const propertyName = context.sourceCode.getText(property); + const propertyType = objectType + .getProperties() + .find(prop => prop.name === propertyName); + if (propertyType && + tsutils.isSymbolFlagSet(propertyType, ts.SymbolFlags.Optional)) { + return true; + } + return false; + } + /** + * Checks if a conditional node is necessary: + * if the type of the node is always true or always false, it's not necessary. + */ + function checkNode(expression, isUnaryNotArgument = false, node = expression) { + // Check if the node is Unary Negation expression and handle it + if (expression.type === utils_1.AST_NODE_TYPES.UnaryExpression && + expression.operator === '!') { + return checkNode(expression.argument, !isUnaryNotArgument, node); + } + // Since typescript array index signature types don't represent the + // possibility of out-of-bounds access, if we're indexing into an array + // just skip the check, to avoid false positives + if (!isNoUncheckedIndexedAccess && isArrayIndexExpression(expression)) { + return; + } + // When checking logical expressions, only check the right side + // as the left side has been checked by checkLogicalExpressionForUnnecessaryConditionals + // + // Unless the node is nullish coalescing, as it's common to use patterns like `nullBool ?? true` to to strict + // boolean checks if we inspect the right here, it'll usually be a constant condition on purpose. + // In this case it's better to inspect the type of the expression as a whole. + if (expression.type === utils_1.AST_NODE_TYPES.LogicalExpression && + expression.operator !== '??') { + return checkNode(expression.right); + } + const type = (0, util_1.getConstrainedTypeAtLocation)(services, expression); + if (isConditionalAlwaysNecessary(type)) { + return; + } + let messageId = null; + if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Never)) { + messageId = 'never'; + } + else if (!(0, util_1.isPossiblyTruthy)(type)) { + messageId = !isUnaryNotArgument ? 'alwaysFalsy' : 'alwaysTruthy'; + } + else if (!(0, util_1.isPossiblyFalsy)(type)) { + messageId = !isUnaryNotArgument ? 'alwaysTruthy' : 'alwaysFalsy'; + } + if (messageId) { + context.report({ node, messageId }); + } + } + function checkNodeForNullish(node) { + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node); + // Conditional is always necessary if it involves `any`, `unknown` or a naked type parameter + if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Any | + ts.TypeFlags.Unknown | + ts.TypeFlags.TypeParameter | + ts.TypeFlags.TypeVariable)) { + return; + } + let messageId = null; + if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Never)) { + messageId = 'never'; + } + else if (!isPossiblyNullish(type) && + !(node.type === utils_1.AST_NODE_TYPES.MemberExpression && + isNullableMemberExpression(node))) { + // Since typescript array index signature types don't represent the + // possibility of out-of-bounds access, if we're indexing into an array + // just skip the check, to avoid false positives + if (isNoUncheckedIndexedAccess || + (!isArrayIndexExpression(node) && + !(node.type === utils_1.AST_NODE_TYPES.ChainExpression && + node.expression.type !== utils_1.AST_NODE_TYPES.TSNonNullExpression && + optionChainContainsOptionArrayIndex(node.expression)))) { + messageId = 'neverNullish'; + } + } + else if (isAlwaysNullish(type)) { + messageId = 'alwaysNullish'; + } + if (messageId) { + context.report({ node, messageId }); + } + } + /** + * Checks that a binary expression is necessarily conditional, reports otherwise. + * If both sides of the binary expression are literal values, it's not a necessary condition. + * + * NOTE: It's also unnecessary if the types that don't overlap at all + * but that case is handled by the Typescript compiler itself. + * Known exceptions: + * - https://github.com/microsoft/TypeScript/issues/32627 + * - https://github.com/microsoft/TypeScript/issues/37160 (handled) + */ + function checkIfBoolExpressionIsNecessaryConditional(node, left, right, operator) { + const leftType = (0, util_1.getConstrainedTypeAtLocation)(services, left); + const rightType = (0, util_1.getConstrainedTypeAtLocation)(services, right); + const leftStaticValue = toStaticValue(leftType); + const rightStaticValue = toStaticValue(rightType); + if (leftStaticValue != null && rightStaticValue != null) { + const conditionIsTrue = booleanComparison(leftStaticValue.value, operator, rightStaticValue.value); + context.report({ + node, + messageId: 'comparisonBetweenLiteralTypes', + data: { + left: checker.typeToString(leftType), + operator, + right: checker.typeToString(rightType), + trueOrFalse: conditionIsTrue ? 'true' : 'false', + }, + }); + return; + } + // Workaround for https://github.com/microsoft/TypeScript/issues/37160 + if (isStrictNullChecks) { + const UNDEFINED = ts.TypeFlags.Undefined; + const NULL = ts.TypeFlags.Null; + const VOID = ts.TypeFlags.Void; + const isComparable = (type, flag) => { + // Allow comparison to `any`, `unknown` or a naked type parameter. + flag |= + ts.TypeFlags.Any | + ts.TypeFlags.Unknown | + ts.TypeFlags.TypeParameter | + ts.TypeFlags.TypeVariable; + // Allow loose comparison to nullish values. + if (operator === '==' || operator === '!=') { + flag |= NULL | UNDEFINED | VOID; + } + return (0, util_1.isTypeFlagSet)(type, flag); + }; + if ((leftType.flags === UNDEFINED && + !isComparable(rightType, UNDEFINED | VOID)) || + (rightType.flags === UNDEFINED && + !isComparable(leftType, UNDEFINED | VOID)) || + (leftType.flags === NULL && !isComparable(rightType, NULL)) || + (rightType.flags === NULL && !isComparable(leftType, NULL))) { + context.report({ node, messageId: 'noOverlapBooleanExpression' }); + return; + } + } + } + /** + * Checks that a logical expression contains a boolean, reports otherwise. + */ + function checkLogicalExpressionForUnnecessaryConditionals(node) { + if (node.operator === '??') { + checkNodeForNullish(node.left); + return; + } + // Only checks the left side, since the right side might not be "conditional" at all. + // The right side will be checked if the LogicalExpression is used in a conditional context + checkNode(node.left); + } + function checkIfWhileLoopIsNecessaryConditional(node) { + if (allowConstantLoopConditionsOption === 'only-allowed-literals' && + node.test.type === utils_1.AST_NODE_TYPES.Literal && + constantLoopConditionsAllowedLiterals.has(node.test.value)) { + return; + } + checkIfLoopIsNecessaryConditional(node); + } + /** + * Checks that a testable expression of a loop is necessarily conditional, reports otherwise. + */ + function checkIfLoopIsNecessaryConditional(node) { + if (node.test == null) { + // e.g. `for(;;)` + return; + } + if (allowConstantLoopConditionsOption === 'always' && + tsutils.isTrueLiteralType((0, util_1.getConstrainedTypeAtLocation)(services, node.test))) { + return; + } + checkNode(node.test); + } + function checkCallExpression(node) { + if (checkTypePredicates) { + const truthinessAssertedArgument = (0, assertionFunctionUtils_1.findTruthinessAssertedArgument)(services, node); + if (truthinessAssertedArgument != null) { + checkNode(truthinessAssertedArgument); + } + const typeGuardAssertedArgument = (0, assertionFunctionUtils_1.findTypeGuardAssertedArgument)(services, node); + if (typeGuardAssertedArgument != null) { + const typeOfArgument = (0, util_1.getConstrainedTypeAtLocation)(services, typeGuardAssertedArgument.argument); + if (typeOfArgument === typeGuardAssertedArgument.type) { + context.report({ + node: typeGuardAssertedArgument.argument, + messageId: 'typeGuardAlreadyIsType', + data: { + typeGuardOrAssertionFunction: typeGuardAssertedArgument.asserts + ? 'assertion function' + : 'type guard', + }, + }); + } + } + } + // If this is something like arr.filter(x => /*condition*/), check `condition` + if ((0, util_1.isArrayMethodCallWithPredicate)(context, services, node) && + node.arguments.length) { + const callback = node.arguments[0]; + // Inline defined functions + if (callback.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression || + callback.type === utils_1.AST_NODE_TYPES.FunctionExpression) { + // Two special cases, where we can directly check the node that's returned: + // () => something + if (callback.body.type !== utils_1.AST_NODE_TYPES.BlockStatement) { + return checkNode(callback.body); + } + // () => { return something; } + const callbackBody = callback.body.body; + if (callbackBody.length === 1 && + callbackBody[0].type === utils_1.AST_NODE_TYPES.ReturnStatement && + callbackBody[0].argument) { + return checkNode(callbackBody[0].argument); + } + // Potential enhancement: could use code-path analysis to check + // any function with a single return statement + // (Value to complexity ratio is dubious however) + } + // Otherwise just do type analysis on the function as a whole. + const returnTypes = tsutils + .getCallSignaturesOfType((0, util_1.getConstrainedTypeAtLocation)(services, callback)) + .map(sig => sig.getReturnType()); + if (returnTypes.length === 0) { + // Not a callable function, e.g. `any` + return; + } + let hasFalsyReturnTypes = false; + let hasTruthyReturnTypes = false; + for (const type of returnTypes) { + const { constraintType } = (0, util_1.getConstraintInfo)(checker, type); + // Predicate is always necessary if it involves `any` or `unknown` + if (!constraintType || + (0, util_1.isTypeAnyType)(constraintType) || + (0, util_1.isTypeUnknownType)(constraintType)) { + return; + } + if ((0, util_1.isPossiblyFalsy)(constraintType)) { + hasFalsyReturnTypes = true; + } + if ((0, util_1.isPossiblyTruthy)(constraintType)) { + hasTruthyReturnTypes = true; + } + // bail early if both a possibly-truthy and a possibly-falsy have been detected + if (hasFalsyReturnTypes && hasTruthyReturnTypes) { + return; + } + } + if (!hasFalsyReturnTypes) { + return context.report({ + node: callback, + messageId: 'alwaysTruthyFunc', + }); + } + if (!hasTruthyReturnTypes) { + return context.report({ + node: callback, + messageId: 'alwaysFalsyFunc', + }); + } + } + } + // Recursively searches an optional chain for an array index expression + // Has to search the entire chain, because an array index will "infect" the rest of the types + // Example: + // ``` + // [{x: {y: "z"} }][n] // type is {x: {y: "z"}} + // ?.x // type is {y: "z"} + // ?.y // This access is considered "unnecessary" according to the types + // ``` + function optionChainContainsOptionArrayIndex(node) { + const lhsNode = node.type === utils_1.AST_NODE_TYPES.CallExpression ? node.callee : node.object; + if (node.optional && isArrayIndexExpression(lhsNode)) { + return true; + } + if (lhsNode.type === utils_1.AST_NODE_TYPES.MemberExpression || + lhsNode.type === utils_1.AST_NODE_TYPES.CallExpression) { + return optionChainContainsOptionArrayIndex(lhsNode); + } + return false; + } + function isNullablePropertyType(objType, propertyType) { + if (propertyType.isUnion()) { + return propertyType.types.some(type => isNullablePropertyType(objType, type)); + } + if (propertyType.isNumberLiteral() || propertyType.isStringLiteral()) { + const propType = (0, util_1.getTypeOfPropertyOfName)(checker, objType, propertyType.value.toString()); + if (propType) { + return (0, util_1.isNullableType)(propType); + } + } + const typeName = (0, util_1.getTypeName)(checker, propertyType); + return checker + .getIndexInfosOfType(objType) + .some(info => (0, util_1.getTypeName)(checker, info.keyType) === typeName); + } + // Checks whether a member expression is nullable or not regardless of it's previous node. + // Example: + // ``` + // // 'bar' is nullable if 'foo' is null. + // // but this function checks regardless of 'foo' type, so returns 'true'. + // declare const foo: { bar : { baz: string } } | null + // foo?.bar; + // ``` + function isMemberExpressionNullableOriginFromObject(node) { + const prevType = (0, util_1.getConstrainedTypeAtLocation)(services, node.object); + const property = node.property; + if (prevType.isUnion() && (0, util_1.isIdentifier)(property)) { + const isOwnNullable = prevType.types.some(type => { + if (node.computed) { + const propertyType = (0, util_1.getConstrainedTypeAtLocation)(services, node.property); + return isNullablePropertyType(type, propertyType); + } + const propType = (0, util_1.getTypeOfPropertyOfName)(checker, type, property.name); + if (propType) { + return (0, util_1.isNullableType)(propType); + } + const indexInfo = checker.getIndexInfosOfType(type); + return indexInfo.some(info => { + const isStringTypeName = (0, util_1.getTypeName)(checker, info.keyType) === 'string'; + return (isStringTypeName && + (isNoUncheckedIndexedAccess || (0, util_1.isNullableType)(info.type))); + }); + }); + return !isOwnNullable && (0, util_1.isNullableType)(prevType); + } + return false; + } + function isCallExpressionNullableOriginFromCallee(node) { + const prevType = (0, util_1.getConstrainedTypeAtLocation)(services, node.callee); + if (prevType.isUnion()) { + const isOwnNullable = prevType.types.some(type => { + const signatures = type.getCallSignatures(); + return signatures.some(sig => (0, util_1.isNullableType)(sig.getReturnType())); + }); + return !isOwnNullable && (0, util_1.isNullableType)(prevType); + } + return false; + } + function isOptionableExpression(node) { + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node); + const isOwnNullable = node.type === utils_1.AST_NODE_TYPES.MemberExpression + ? !isMemberExpressionNullableOriginFromObject(node) + : node.type === utils_1.AST_NODE_TYPES.CallExpression + ? !isCallExpressionNullableOriginFromCallee(node) + : true; + return (isConditionalAlwaysNecessary(type) || + (isOwnNullable && (0, util_1.isNullableType)(type))); + } + function checkOptionalChain(node, beforeOperator, fix) { + // We only care if this step in the chain is optional. If just descend + // from an optional chain, then that's fine. + if (!node.optional) { + return; + } + // Since typescript array index signature types don't represent the + // possibility of out-of-bounds access, if we're indexing into an array + // just skip the check, to avoid false positives + if (!isNoUncheckedIndexedAccess && + optionChainContainsOptionArrayIndex(node)) { + return; + } + const nodeToCheck = node.type === utils_1.AST_NODE_TYPES.CallExpression ? node.callee : node.object; + if (isOptionableExpression(nodeToCheck)) { + return; + } + const questionDotOperator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(beforeOperator, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && token.value === '?.'), util_1.NullThrowsReasons.MissingToken('operator', node.type)); + context.report({ + loc: questionDotOperator.loc, + node, + messageId: 'neverOptionalChain', + suggest: [ + { + messageId: 'suggestRemoveOptionalChain', + fix(fixer) { + return fixer.replaceText(questionDotOperator, fix); + }, + }, + ], + }); + } + function checkOptionalMemberExpression(node) { + checkOptionalChain(node, node.object, node.computed ? '' : '.'); + } + function checkOptionalCallExpression(node) { + checkOptionalChain(node, node.callee, ''); + } + function checkAssignmentExpression(node) { + // Similar to checkLogicalExpressionForUnnecessaryConditionals, since + // a ||= b is equivalent to a || (a = b) + if (['&&=', '||='].includes(node.operator)) { + checkNode(node.left); + } + else if (node.operator === '??=') { + checkNodeForNullish(node.left); + } + } + return { + AssignmentExpression: checkAssignmentExpression, + BinaryExpression(node) { + const { operator } = node; + if (isBoolOperator(operator)) { + checkIfBoolExpressionIsNecessaryConditional(node, node.left, node.right, operator); + } + }, + CallExpression: checkCallExpression, + 'CallExpression[optional = true]': checkOptionalCallExpression, + ConditionalExpression: (node) => checkNode(node.test), + DoWhileStatement: checkIfLoopIsNecessaryConditional, + ForStatement: checkIfLoopIsNecessaryConditional, + IfStatement: (node) => checkNode(node.test), + LogicalExpression: checkLogicalExpressionForUnnecessaryConditionals, + 'MemberExpression[optional = true]': checkOptionalMemberExpression, + SwitchCase({ parent, test }) { + // only check `case ...:`, not `default:` + if (test) { + checkIfBoolExpressionIsNecessaryConditional(test, parent.discriminant, test, '==='); + } + }, + WhileStatement: checkIfWhileLoopIsNecessaryConditional, + }; + }, +}); +function normalizeAllowConstantLoopConditions(allowConstantLoopConditions) { + if (allowConstantLoopConditions === true) { + return 'always'; + } + if (allowConstantLoopConditions === false) { + return 'never'; + } + return allowConstantLoopConditions; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-parameter-property-assignment.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-parameter-property-assignment.d.ts new file mode 100644 index 00000000..77c9e607 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-parameter-property-assignment.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unnecessaryAssign", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unnecessary-parameter-property-assignment.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-parameter-property-assignment.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-parameter-property-assignment.d.ts.map new file mode 100644 index 00000000..27dc2f25 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-parameter-property-assignment.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-parameter-property-assignment.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-parameter-property-assignment.ts"],"names":[],"mappings":";AASA,wBA8NG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-parameter-property-assignment.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-parameter-property-assignment.js new file mode 100644 index 00000000..c62b9eac --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-parameter-property-assignment.js @@ -0,0 +1,149 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const UNNECESSARY_OPERATORS = new Set(['??=', '&&=', '=', '||=']); +exports.default = (0, util_1.createRule)({ + name: 'no-unnecessary-parameter-property-assignment', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow unnecessary assignment of constructor property parameter', + }, + messages: { + unnecessaryAssign: 'This assignment is unnecessary since it is already assigned by a parameter property.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const reportInfoStack = []; + function isThisMemberExpression(node) { + return (node.type === utils_1.AST_NODE_TYPES.MemberExpression && + node.object.type === utils_1.AST_NODE_TYPES.ThisExpression); + } + function getPropertyName(node) { + if (!isThisMemberExpression(node)) { + return null; + } + if (node.property.type === utils_1.AST_NODE_TYPES.Identifier) { + return node.property.name; + } + if (node.computed) { + return (0, util_1.getStaticStringValue)(node.property); + } + return null; + } + function findParentFunction(node) { + if (!node || + node.type === utils_1.AST_NODE_TYPES.FunctionDeclaration || + node.type === utils_1.AST_NODE_TYPES.FunctionExpression || + node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression) { + return node; + } + return findParentFunction(node.parent); + } + function findParentPropertyDefinition(node) { + if (!node || node.type === utils_1.AST_NODE_TYPES.PropertyDefinition) { + return node; + } + return findParentPropertyDefinition(node.parent); + } + function isConstructorFunctionExpression(node) { + return (node?.type === utils_1.AST_NODE_TYPES.FunctionExpression && + utils_1.ASTUtils.isConstructor(node.parent)); + } + function isReferenceFromParameter(node) { + const scope = context.sourceCode.getScope(node); + const rightRef = scope.references.find(ref => ref.identifier.name === node.name); + return rightRef?.resolved?.defs.at(0)?.type === scope_manager_1.DefinitionType.Parameter; + } + function isParameterPropertyWithName(node, name) { + return (node.type === utils_1.AST_NODE_TYPES.TSParameterProperty && + ((node.parameter.type === utils_1.AST_NODE_TYPES.Identifier && // constructor (public foo) {} + node.parameter.name === name) || + (node.parameter.type === utils_1.AST_NODE_TYPES.AssignmentPattern && // constructor (public foo = 1) {} + node.parameter.left.type === utils_1.AST_NODE_TYPES.Identifier && + node.parameter.left.name === name))); + } + function getIdentifier(node) { + if (node.type === utils_1.AST_NODE_TYPES.Identifier) { + return node; + } + if (node.type === utils_1.AST_NODE_TYPES.TSAsExpression || + node.type === utils_1.AST_NODE_TYPES.TSNonNullExpression) { + return getIdentifier(node.expression); + } + return null; + } + function isArrowIIFE(node) { + return (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + node.parent.type === utils_1.AST_NODE_TYPES.CallExpression); + } + return { + ClassBody() { + reportInfoStack.push({ + assignedBeforeConstructor: new Set(), + assignedBeforeUnnecessary: new Set(), + unnecessaryAssignments: [], + }); + }, + 'ClassBody:exit'() { + const { assignedBeforeConstructor, unnecessaryAssignments } = (0, util_1.nullThrows)(reportInfoStack.pop(), 'The top stack should exist'); + unnecessaryAssignments.forEach(({ name, node }) => { + if (assignedBeforeConstructor.has(name)) { + return; + } + context.report({ + node, + messageId: 'unnecessaryAssign', + }); + }); + }, + "MethodDefinition[kind='constructor'] > FunctionExpression AssignmentExpression"(node) { + const leftName = getPropertyName(node.left); + if (!leftName) { + return; + } + let functionNode = findParentFunction(node); + if (functionNode && isArrowIIFE(functionNode)) { + functionNode = findParentFunction(functionNode.parent); + } + if (!isConstructorFunctionExpression(functionNode)) { + return; + } + const { assignedBeforeUnnecessary, unnecessaryAssignments } = (0, util_1.nullThrows)(reportInfoStack.at(reportInfoStack.length - 1), 'The top of stack should exist'); + if (!UNNECESSARY_OPERATORS.has(node.operator)) { + assignedBeforeUnnecessary.add(leftName); + return; + } + const rightId = getIdentifier(node.right); + if (leftName !== rightId?.name || !isReferenceFromParameter(rightId)) { + return; + } + const hasParameterProperty = functionNode.params.some(param => isParameterPropertyWithName(param, rightId.name)); + if (hasParameterProperty && !assignedBeforeUnnecessary.has(leftName)) { + unnecessaryAssignments.push({ + name: leftName, + node, + }); + } + }, + 'PropertyDefinition AssignmentExpression'(node) { + const name = getPropertyName(node.left); + if (!name) { + return; + } + const functionNode = findParentFunction(node); + if (functionNode && + !(isArrowIIFE(functionNode) && + findParentPropertyDefinition(node)?.value === functionNode.parent)) { + return; + } + const { assignedBeforeConstructor } = (0, util_1.nullThrows)(reportInfoStack.at(-1), 'The top stack should exist'); + assignedBeforeConstructor.add(name); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-qualifier.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-qualifier.d.ts new file mode 100644 index 00000000..2324ac00 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-qualifier.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unnecessaryQualifier", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unnecessary-qualifier.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-qualifier.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-qualifier.d.ts.map new file mode 100644 index 00000000..359a0b36 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-qualifier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-qualifier.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-qualifier.ts"],"names":[],"mappings":";AAQA,wBAuLG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-qualifier.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-qualifier.js new file mode 100644 index 00000000..bd0d2fbd --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-qualifier.js @@ -0,0 +1,156 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unnecessary-qualifier', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow unnecessary namespace qualifiers', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + unnecessaryQualifier: "Qualifier is unnecessary since '{{ name }}' is in scope.", + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const namespacesInScope = []; + let currentFailedNamespaceExpression = null; + const services = (0, util_1.getParserServices)(context); + const esTreeNodeToTSNodeMap = services.esTreeNodeToTSNodeMap; + const checker = services.program.getTypeChecker(); + function tryGetAliasedSymbol(symbol, checker) { + return tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias) + ? checker.getAliasedSymbol(symbol) + : null; + } + function symbolIsNamespaceInScope(symbol) { + const symbolDeclarations = symbol.getDeclarations() ?? []; + if (symbolDeclarations.some(decl => namespacesInScope.some(ns => ns === decl))) { + return true; + } + const alias = tryGetAliasedSymbol(symbol, checker); + return alias != null && symbolIsNamespaceInScope(alias); + } + function getSymbolInScope(node, flags, name) { + const scope = checker.getSymbolsInScope(node, flags); + return scope.find(scopeSymbol => scopeSymbol.name === name); + } + function symbolsAreEqual(accessed, inScope) { + return accessed === checker.getExportSymbolOfSymbol(inScope); + } + function qualifierIsUnnecessary(qualifier, name) { + const namespaceSymbol = services.getSymbolAtLocation(qualifier); + if (namespaceSymbol == null || + !symbolIsNamespaceInScope(namespaceSymbol)) { + return false; + } + const accessedSymbol = services.getSymbolAtLocation(name); + if (accessedSymbol == null) { + return false; + } + // If the symbol in scope is different, the qualifier is necessary. + const tsQualifier = esTreeNodeToTSNodeMap.get(qualifier); + const fromScope = getSymbolInScope(tsQualifier, accessedSymbol.flags, context.sourceCode.getText(name)); + return !!fromScope && symbolsAreEqual(accessedSymbol, fromScope); + } + function visitNamespaceAccess(node, qualifier, name) { + // Only look for nested qualifier errors if we didn't already fail on the outer qualifier. + if (!currentFailedNamespaceExpression && + qualifierIsUnnecessary(qualifier, name)) { + currentFailedNamespaceExpression = node; + context.report({ + node: qualifier, + messageId: 'unnecessaryQualifier', + data: { + name: context.sourceCode.getText(name), + }, + fix(fixer) { + return fixer.removeRange([qualifier.range[0], name.range[0]]); + }, + }); + } + } + function enterDeclaration(node) { + namespacesInScope.push(esTreeNodeToTSNodeMap.get(node)); + } + function exitDeclaration() { + namespacesInScope.pop(); + } + function resetCurrentNamespaceExpression(node) { + if (node === currentFailedNamespaceExpression) { + currentFailedNamespaceExpression = null; + } + } + function isPropertyAccessExpression(node) { + return node.type === utils_1.AST_NODE_TYPES.MemberExpression && !node.computed; + } + function isEntityNameExpression(node) { + return (node.type === utils_1.AST_NODE_TYPES.Identifier || + (isPropertyAccessExpression(node) && + isEntityNameExpression(node.object))); + } + return { + 'ExportNamedDeclaration[declaration.type="TSEnumDeclaration"]': enterDeclaration, + 'ExportNamedDeclaration[declaration.type="TSEnumDeclaration"]:exit': exitDeclaration, + 'ExportNamedDeclaration[declaration.type="TSModuleDeclaration"]': enterDeclaration, + 'ExportNamedDeclaration[declaration.type="TSModuleDeclaration"]:exit': exitDeclaration, + 'MemberExpression:exit': resetCurrentNamespaceExpression, + 'MemberExpression[computed=false]'(node) { + const property = node.property; + if (isEntityNameExpression(node.object)) { + visitNamespaceAccess(node, node.object, property); + } + }, + TSEnumDeclaration: enterDeclaration, + 'TSEnumDeclaration:exit': exitDeclaration, + 'TSModuleDeclaration:exit': exitDeclaration, + 'TSModuleDeclaration > TSModuleBlock'(node) { + enterDeclaration(node.parent); + }, + TSQualifiedName(node) { + visitNamespaceAccess(node, node.left, node.right); + }, + 'TSQualifiedName:exit': resetCurrentNamespaceExpression, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-template-expression.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-template-expression.d.ts new file mode 100644 index 00000000..d3544c44 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-template-expression.d.ts @@ -0,0 +1,5 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageId = 'noUnnecessaryTemplateExpression'; +declare const _default: TSESLint.RuleModule<"noUnnecessaryTemplateExpression", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-unnecessary-template-expression.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-template-expression.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-template-expression.d.ts.map new file mode 100644 index 00000000..30b61596 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-template-expression.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-template-expression.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-template-expression.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAmBzD,MAAM,MAAM,SAAS,GAAG,iCAAiC,CAAC;;AAqB1D,wBAgbG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-template-expression.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-template-expression.js new file mode 100644 index 00000000..5eab7345 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-template-expression.js @@ -0,0 +1,361 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const rangeToLoc_1 = require("../util/rangeToLoc"); +const evenNumOfBackslashesRegExp = /(? { + const symbol = t.getSymbol(); + return !!(symbol?.valueDeclaration && ts.isEnumMember(symbol.valueDeclaration)); + }); + } + const isLiteral = (0, util_1.isNodeOfType)(utils_1.TSESTree.AST_NODE_TYPES.Literal); + function isTemplateLiteral(node) { + return node.type === utils_1.AST_NODE_TYPES.TemplateLiteral; + } + function isInfinityIdentifier(node) { + return (node.type === utils_1.AST_NODE_TYPES.Identifier && node.name === 'Infinity'); + } + function isNaNIdentifier(node) { + return node.type === utils_1.AST_NODE_TYPES.Identifier && node.name === 'NaN'; + } + function isFixableIdentifier(node) { + return ((0, util_1.isUndefinedIdentifier)(node) || + isInfinityIdentifier(node) || + isNaNIdentifier(node)); + } + function hasCommentsBetweenQuasi(startQuasi, endQuasi) { + const startToken = (0, util_1.nullThrows)(context.sourceCode.getTokenByRangeStart(startQuasi.range[0]), util_1.NullThrowsReasons.MissingToken('`${', 'opening template literal')); + const endToken = (0, util_1.nullThrows)(context.sourceCode.getTokenByRangeStart(endQuasi.range[0]), util_1.NullThrowsReasons.MissingToken('}', 'closing template literal')); + return context.sourceCode.commentsExistBetween(startToken, endToken); + } + function isTrivialInterpolation(node) { + return (node.quasis.length === 2 && + node.quasis[0].value.raw === '' && + node.quasis[1].value.raw === ''); + } + function getInterpolations(node) { + if (node.type === utils_1.AST_NODE_TYPES.TemplateLiteral) { + return node.expressions; + } + return node.types; + } + function getInterpolationInfos(node) { + return getInterpolations(node).map((interpolation, index) => ({ + interpolation, + nextQuasi: node.quasis[index + 1], + prevQuasi: node.quasis[index], + })); + } + function getLiteral(node) { + const maybeLiteral = node.type === utils_1.AST_NODE_TYPES.TSLiteralType ? node.literal : node; + return isLiteral(maybeLiteral) ? maybeLiteral : null; + } + function getTemplateLiteral(node) { + const maybeTemplateLiteral = node.type === utils_1.AST_NODE_TYPES.TSLiteralType ? node.literal : node; + return isTemplateLiteral(maybeTemplateLiteral) + ? maybeTemplateLiteral + : null; + } + function reportSingleInterpolation(node) { + const interpolations = getInterpolations(node); + context.report({ + loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, [ + interpolations[0].range[0] - 2, + interpolations[0].range[1] + 1, + ]), + messageId: 'noUnnecessaryTemplateExpression', + fix(fixer) { + const wrappingCode = (0, util_1.getMovedNodeCode)({ + destinationNode: node, + nodeToMove: interpolations[0], + sourceCode: context.sourceCode, + }); + return fixer.replaceText(node, wrappingCode); + }, + }); + } + function isUnncessaryValueInterpolation({ interpolation, nextQuasi, prevQuasi, }) { + if (hasCommentsBetweenQuasi(prevQuasi, nextQuasi)) { + return false; + } + if (isFixableIdentifier(interpolation)) { + return true; + } + if (isLiteral(interpolation)) { + // allow trailing whitespace literal + if (startsWithNewLine(nextQuasi.value.raw)) { + return !(typeof interpolation.value === 'string' && + isWhitespace(interpolation.value)); + } + return true; + } + if (isTemplateLiteral(interpolation)) { + // allow trailing whitespace literal + if (startsWithNewLine(nextQuasi.value.raw)) { + return !(interpolation.quasis.length === 1 && + isWhitespace(interpolation.quasis[0].value.raw)); + } + return true; + } + return false; + } + function isUnncessaryTypeInterpolation({ interpolation, nextQuasi, prevQuasi, }) { + if (hasCommentsBetweenQuasi(prevQuasi, nextQuasi)) { + return false; + } + const literal = getLiteral(interpolation); + if (literal) { + // allow trailing whitespace literal + if (startsWithNewLine(nextQuasi.value.raw)) { + return !(typeof literal.value === 'string' && isWhitespace(literal.value)); + } + return true; + } + if (interpolation.type === utils_1.AST_NODE_TYPES.TSNullKeyword || + interpolation.type === utils_1.AST_NODE_TYPES.TSUndefinedKeyword) { + return true; + } + const templateLiteral = getTemplateLiteral(interpolation); + if (templateLiteral) { + // allow trailing whitespace literal + if (startsWithNewLine(nextQuasi.value.raw)) { + return !(templateLiteral.quasis.length === 1 && + isWhitespace(templateLiteral.quasis[0].value.raw)); + } + return true; + } + return false; + } + function getReportDescriptors(infos) { + let nextCharacterIsOpeningCurlyBrace = false; + const reportDescriptors = []; + const reversedInfos = [...infos].reverse(); + for (const { interpolation, nextQuasi, prevQuasi } of reversedInfos) { + const fixers = []; + if (nextQuasi.value.raw !== '') { + nextCharacterIsOpeningCurlyBrace = + nextQuasi.value.raw.startsWith('{'); + } + const literal = getLiteral(interpolation); + const templateLiteral = getTemplateLiteral(interpolation); + if (literal) { + let escapedValue = (typeof literal.value === 'string' + ? // The value is already a string, so we're removing quotes: + // "'va`lue'" -> "va`lue" + literal.raw.slice(1, -1) + : // The value may be one of number | bigint | boolean | RegExp | null. + // In regular expressions, we escape every backslash + String(literal.value).replaceAll('\\', '\\\\')) + // The string or RegExp may contain ` or ${. + // We want both of these to be escaped in the final template expression. + // + // A pair of backslashes means "escaped backslash", so backslashes + // from this pair won't escape ` or ${. Therefore, to escape these + // sequences in the resulting template expression, we need to escape + // all sequences that are preceded by an even number of backslashes. + // + // This RegExp does the following transformations: + // \` -> \` + // \\` -> \\\` + // \${ -> \${ + // \\${ -> \\\${ + .replaceAll(new RegExp(`${evenNumOfBackslashesRegExp.source}(\`|\\\${)`, 'g'), '\\$1'); + // `...${'...$'}{...` + // ^^^^ + if (nextCharacterIsOpeningCurlyBrace && + endsWithUnescapedDollarSign(escapedValue)) { + escapedValue = escapedValue.replaceAll(/\$$/g, '\\$'); + } + if (escapedValue.length !== 0) { + nextCharacterIsOpeningCurlyBrace = escapedValue.startsWith('{'); + } + fixers.push(fixer => [fixer.replaceText(literal, escapedValue)]); + } + else if (templateLiteral) { + // Since we iterate from the last expression to the first, + // a subsequent expression can tell the current expression + // that it starts with {. + // + // `... ${`... $`}${'{...'} ...` + // ^ ^ subsequent expression starts with { + // current expression ends with a dollar sign, + // so '$' + '{' === '${' (bad news for us). + // Let's escape the dollar sign at the end. + if (nextCharacterIsOpeningCurlyBrace && + endsWithUnescapedDollarSign(templateLiteral.quasis[templateLiteral.quasis.length - 1].value + .raw)) { + fixers.push(fixer => [ + fixer.replaceTextRange([templateLiteral.range[1] - 2, templateLiteral.range[1] - 2], '\\'), + ]); + } + if (templateLiteral.quasis.length === 1 && + templateLiteral.quasis[0].value.raw.length !== 0) { + nextCharacterIsOpeningCurlyBrace = + templateLiteral.quasis[0].value.raw.startsWith('{'); + } + // Remove the beginning and trailing backtick characters. + fixers.push(fixer => [ + fixer.removeRange([ + templateLiteral.range[0], + templateLiteral.range[0] + 1, + ]), + fixer.removeRange([ + templateLiteral.range[1] - 1, + templateLiteral.range[1], + ]), + ]); + } + else { + nextCharacterIsOpeningCurlyBrace = false; + } + // `... $${'{...'} ...` + // ^^^^^ + if (nextCharacterIsOpeningCurlyBrace && + endsWithUnescapedDollarSign(prevQuasi.value.raw)) { + fixers.push(fixer => [ + fixer.replaceTextRange([prevQuasi.range[1] - 3, prevQuasi.range[1] - 2], '\\$'), + ]); + } + const warnLocStart = prevQuasi.range[1] - 2; + const warnLocEnd = nextQuasi.range[0] + 1; + reportDescriptors.push({ + loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, [warnLocStart, warnLocEnd]), + messageId: 'noUnnecessaryTemplateExpression', + fix(fixer) { + return [ + // Remove the quasis' parts that are related to the current expression. + fixer.removeRange([warnLocStart, interpolation.range[0]]), + fixer.removeRange([interpolation.range[1], warnLocEnd]), + ...fixers.flatMap(cb => cb(fixer)), + ]; + }, + }); + } + return reportDescriptors; + } + return { + TemplateLiteral(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression) { + return; + } + if (isTrivialInterpolation(node) && + !hasCommentsBetweenQuasi(node.quasis[0], node.quasis[1])) { + const { constraintType } = (0, util_1.getConstraintInfo)(checker, services.getTypeAtLocation(node.expressions[0])); + if (constraintType && isUnderlyingTypeString(constraintType)) { + reportSingleInterpolation(node); + return; + } + } + const infos = getInterpolationInfos(node).filter(isUnncessaryValueInterpolation); + for (const reportDescriptor of getReportDescriptors(infos)) { + context.report(reportDescriptor); + } + }, + TSTemplateLiteralType(node) { + if (isTrivialInterpolation(node) && + !hasCommentsBetweenQuasi(node.quasis[0], node.quasis[1])) { + const { constraintType, isTypeParameter } = (0, util_1.getConstraintInfo)(checker, services.getTypeAtLocation(node.types[0])); + if (constraintType && + !isTypeParameter && + isUnderlyingTypeString(constraintType) && + !isEnumMemberType(constraintType)) { + reportSingleInterpolation(node); + return; + } + } + const infos = getInterpolationInfos(node).filter(isUnncessaryTypeInterpolation); + for (const reportDescriptor of getReportDescriptors(infos)) { + context.report(reportDescriptor); + } + }, + }; + }, +}); +function isWhitespace(x) { + // allow empty string too since we went to allow + // ` ${''} + // `; + // + // in addition to + // `${' '} + // `; + // + return /^\s*$/.test(x); +} +function startsWithNewLine(x) { + return x.startsWith('\n') || x.startsWith('\r\n'); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-arguments.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-arguments.d.ts new file mode 100644 index 00000000..2b90b53b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-arguments.d.ts @@ -0,0 +1,4 @@ +export type MessageIds = 'unnecessaryTypeParameter'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unnecessaryTypeParameter", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unnecessary-type-arguments.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-arguments.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-arguments.d.ts.map new file mode 100644 index 00000000..3aea5c11 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-arguments.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-type-arguments.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-type-arguments.ts"],"names":[],"mappings":"AAwBA,MAAM,MAAM,UAAU,GAAG,0BAA0B,CAAC;;AAEpD,wBAoGG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-arguments.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-arguments.js new file mode 100644 index 00000000..bfbebf30 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-arguments.js @@ -0,0 +1,197 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unnecessary-type-arguments', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow type arguments that are equal to the default', + recommended: 'strict', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + unnecessaryTypeParameter: 'This is the default value for this type parameter, so it can be omitted.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function getTypeForComparison(type) { + if ((0, util_1.isTypeReferenceType)(type)) { + return { + type: type.target, + typeArguments: checker.getTypeArguments(type), + }; + } + return { + type, + typeArguments: [], + }; + } + function checkTSArgsAndParameters(esParameters, typeParameters) { + // Just check the last one. Must specify previous type parameters if the last one is specified. + const i = esParameters.params.length - 1; + const arg = esParameters.params[i]; + const param = typeParameters.at(i); + if (!param?.default) { + return; + } + // TODO: would like checker.areTypesEquivalent. https://github.com/Microsoft/TypeScript/issues/13502 + const defaultType = checker.getTypeAtLocation(param.default); + const argType = services.getTypeAtLocation(arg); + // this check should handle some of the most simple cases of like strings, numbers, etc + if (defaultType !== argType) { + // For more complex types (like aliases to generic object types) - TS won't always create a + // global shared type object for the type - so we need to resort to manually comparing the + // reference type and the passed type arguments. + // Also - in case there are aliases - we need to resolve them before we do checks + const defaultTypeResolved = getTypeForComparison(defaultType); + const argTypeResolved = getTypeForComparison(argType); + if ( + // ensure the resolved type AND all the parameters are the same + defaultTypeResolved.type !== argTypeResolved.type || + defaultTypeResolved.typeArguments.length !== + argTypeResolved.typeArguments.length || + defaultTypeResolved.typeArguments.some((t, i) => t !== argTypeResolved.typeArguments[i])) { + return; + } + } + context.report({ + node: arg, + messageId: 'unnecessaryTypeParameter', + fix: fixer => fixer.removeRange(i === 0 + ? esParameters.range + : [esParameters.params[i - 1].range[1], arg.range[1]]), + }); + } + return { + TSTypeParameterInstantiation(node) { + const expression = services.esTreeNodeToTSNodeMap.get(node); + const typeParameters = getTypeParametersFromNode(node, expression, checker); + if (typeParameters) { + checkTSArgsAndParameters(node, typeParameters); + } + }, + }; + }, +}); +function getTypeParametersFromNode(node, tsNode, checker) { + if (ts.isExpressionWithTypeArguments(tsNode)) { + return getTypeParametersFromType(node, tsNode.expression, checker); + } + if (ts.isTypeReferenceNode(tsNode)) { + return getTypeParametersFromType(node, tsNode.typeName, checker); + } + if (ts.isCallExpression(tsNode) || + ts.isNewExpression(tsNode) || + ts.isTaggedTemplateExpression(tsNode) || + ts.isJsxOpeningElement(tsNode) || + ts.isJsxSelfClosingElement(tsNode)) { + return getTypeParametersFromCall(node, tsNode, checker); + } + return undefined; +} +function getTypeParametersFromType(node, type, checker) { + const symAtLocation = checker.getSymbolAtLocation(type); + if (!symAtLocation) { + return undefined; + } + const sym = getAliasedSymbol(symAtLocation, checker); + const declarations = sym.getDeclarations(); + if (!declarations) { + return undefined; + } + const sortedDeclaraions = sortDeclarationsByTypeValueContext(node, declarations); + return (0, util_1.findFirstResult)(sortedDeclaraions, decl => { + if (ts.isTypeAliasDeclaration(decl) || + ts.isInterfaceDeclaration(decl) || + ts.isClassLike(decl)) { + return decl.typeParameters; + } + if (ts.isVariableDeclaration(decl)) { + return getConstructSignatureDeclaration(symAtLocation, checker) + ?.typeParameters; + } + return undefined; + }); +} +function getTypeParametersFromCall(node, tsNode, checker) { + const sig = checker.getResolvedSignature(tsNode); + const sigDecl = sig?.getDeclaration(); + if (!sigDecl) { + return ts.isNewExpression(tsNode) + ? getTypeParametersFromType(node, tsNode.expression, checker) + : undefined; + } + return sigDecl.typeParameters; +} +function getAliasedSymbol(symbol, checker) { + return tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias) + ? checker.getAliasedSymbol(symbol) + : symbol; +} +function isInTypeContext(node) { + return (node.parent.type === utils_1.AST_NODE_TYPES.TSInterfaceHeritage || + node.parent.type === utils_1.AST_NODE_TYPES.TSTypeReference || + node.parent.type === utils_1.AST_NODE_TYPES.TSClassImplements); +} +function isTypeContextDeclaration(decl) { + return ts.isTypeAliasDeclaration(decl) || ts.isInterfaceDeclaration(decl); +} +function typeFirstCompare(declA, declB) { + const aIsType = isTypeContextDeclaration(declA); + const bIsType = isTypeContextDeclaration(declB); + return Number(bIsType) - Number(aIsType); +} +function sortDeclarationsByTypeValueContext(node, declarations) { + const sorted = [...declarations].sort(typeFirstCompare); + if (isInTypeContext(node)) { + return sorted; + } + return sorted.reverse(); +} +function getConstructSignatureDeclaration(symbol, checker) { + const type = checker.getTypeOfSymbol(symbol); + const sig = type.getConstructSignatures(); + return sig.at(0)?.getDeclaration(); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-assertion.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-assertion.d.ts new file mode 100644 index 00000000..31e7d089 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-assertion.d.ts @@ -0,0 +1,10 @@ +export type Options = [ + { + checkLiteralConstAssertions?: boolean; + typesToIgnore?: string[]; + } +]; +export type MessageIds = 'contextuallyUnnecessary' | 'unnecessaryAssertion'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-unnecessary-type-assertion.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-assertion.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-assertion.d.ts.map new file mode 100644 index 00000000..c2d14283 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-assertion.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-type-assertion.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-type-assertion.ts"],"names":[],"mappings":"AAqBA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,2BAA2B,CAAC,EAAE,OAAO,CAAC;QACtC,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;KAC1B;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,yBAAyB,GAAG,sBAAsB,CAAC;;AAE5E,wBA4YG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-assertion.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-assertion.js new file mode 100644 index 00000000..f2713a2a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-assertion.js @@ -0,0 +1,312 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unnecessary-type-assertion', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow type assertions that do not change the type of an expression', + recommended: 'recommended', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + contextuallyUnnecessary: 'This assertion is unnecessary since the receiver accepts the original type of the expression.', + unnecessaryAssertion: 'This assertion is unnecessary since it does not change the type of the expression.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + checkLiteralConstAssertions: { + type: 'boolean', + description: 'Whether to check literal const assertions.', + }, + typesToIgnore: { + type: 'array', + description: 'A list of type names to ignore.', + items: { + type: 'string', + }, + }, + }, + }, + ], + }, + defaultOptions: [{}], + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const compilerOptions = services.program.getCompilerOptions(); + /** + * Returns true if there's a chance the variable has been used before a value has been assigned to it + */ + function isPossiblyUsedBeforeAssigned(node) { + const declaration = (0, util_1.getDeclaration)(services, node); + if (!declaration) { + // don't know what the declaration is for some reason, so just assume the worst + return true; + } + if ( + // non-strict mode doesn't care about used before assigned errors + tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks') && + // ignore class properties as they are compile time guarded + // also ignore function arguments as they can't be used before defined + ts.isVariableDeclaration(declaration)) { + // For var declarations, we need to check whether the node + // is actually in a descendant of its declaration or not. If not, + // it may be used before defined. + // eg + // if (Math.random() < 0.5) { + // var x: number = 2; + // } else { + // x!.toFixed(); + // } + if (ts.isVariableDeclarationList(declaration.parent) && + // var + declaration.parent.flags === ts.NodeFlags.None && + // If they are not in the same file it will not exist. + // This situation must not occur using before defined. + services.tsNodeToESTreeNodeMap.has(declaration)) { + const declaratorNode = services.tsNodeToESTreeNodeMap.get(declaration); + const scope = context.sourceCode.getScope(node); + const declaratorScope = context.sourceCode.getScope(declaratorNode); + let parentScope = declaratorScope; + while ((parentScope = parentScope.upper)) { + if (parentScope === scope) { + return true; + } + } + } + if ( + // is it `const x!: number` + declaration.initializer == null && + declaration.exclamationToken == null && + declaration.type != null) { + // check if the defined variable type has changed since assignment + const declarationType = checker.getTypeFromTypeNode(declaration.type); + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node); + if (declarationType === type && + // `declare`s are never narrowed, so never skip them + !(ts.isVariableDeclarationList(declaration.parent) && + ts.isVariableStatement(declaration.parent.parent) && + tsutils.includesModifier((0, util_1.getModifiers)(declaration.parent.parent), ts.SyntaxKind.DeclareKeyword))) { + // possibly used before assigned, so just skip it + // better to false negative and skip it, than false positive and fix to compile erroring code + // + // no better way to figure this out right now + // https://github.com/Microsoft/TypeScript/issues/31124 + return true; + } + } + } + return false; + } + function isConstAssertion(node) { + return (node.type === utils_1.AST_NODE_TYPES.TSTypeReference && + node.typeName.type === utils_1.AST_NODE_TYPES.Identifier && + node.typeName.name === 'const'); + } + function isTemplateLiteralWithExpressions(expression) { + return (expression.type === utils_1.AST_NODE_TYPES.TemplateLiteral && + expression.expressions.length !== 0); + } + function isImplicitlyNarrowedLiteralDeclaration({ expression, parent, }) { + /** + * Even on `const` variable declarations, template literals with expressions can sometimes be widened without a type assertion. + * @see https://github.com/typescript-eslint/typescript-eslint/issues/8737 + */ + if (isTemplateLiteralWithExpressions(expression)) { + return false; + } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const maybeDeclarationNode = parent.parent; + return ((maybeDeclarationNode.type === utils_1.AST_NODE_TYPES.VariableDeclaration && + maybeDeclarationNode.kind === 'const') || + (parent.type === utils_1.AST_NODE_TYPES.PropertyDefinition && parent.readonly)); + } + function isTypeUnchanged(uncast, cast) { + if (uncast === cast) { + return true; + } + if ((0, util_1.isTypeFlagSet)(uncast, ts.TypeFlags.Undefined) && + (0, util_1.isTypeFlagSet)(cast, ts.TypeFlags.Undefined) && + tsutils.isCompilerOptionEnabled(compilerOptions, 'exactOptionalPropertyTypes')) { + const uncastParts = tsutils + .unionConstituents(uncast) + .filter(part => !(0, util_1.isTypeFlagSet)(part, ts.TypeFlags.Undefined)); + const castParts = tsutils + .unionConstituents(cast) + .filter(part => !(0, util_1.isTypeFlagSet)(part, ts.TypeFlags.Undefined)); + if (uncastParts.length !== castParts.length) { + return false; + } + const uncastPartsSet = new Set(uncastParts); + return castParts.every(part => uncastPartsSet.has(part)); + } + return false; + } + function isTypeLiteral(type) { + return type.isLiteral() || tsutils.isBooleanLiteralType(type); + } + return { + 'TSAsExpression, TSTypeAssertion'(node) { + if (options.typesToIgnore?.includes(context.sourceCode.getText(node.typeAnnotation))) { + return; + } + const castType = services.getTypeAtLocation(node); + const castTypeIsLiteral = isTypeLiteral(castType); + const typeAnnotationIsConstAssertion = isConstAssertion(node.typeAnnotation); + if (!options.checkLiteralConstAssertions && + castTypeIsLiteral && + typeAnnotationIsConstAssertion) { + return; + } + const uncastType = services.getTypeAtLocation(node.expression); + const typeIsUnchanged = isTypeUnchanged(uncastType, castType); + const wouldSameTypeBeInferred = castTypeIsLiteral + ? isImplicitlyNarrowedLiteralDeclaration(node) + : !typeAnnotationIsConstAssertion; + if (typeIsUnchanged && wouldSameTypeBeInferred) { + context.report({ + node, + messageId: 'unnecessaryAssertion', + fix(fixer) { + if (node.type === utils_1.AST_NODE_TYPES.TSTypeAssertion) { + const openingAngleBracket = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(node.typeAnnotation, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && + token.value === '<'), util_1.NullThrowsReasons.MissingToken('<', 'type annotation')); + const closingAngleBracket = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.typeAnnotation, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && + token.value === '>'), util_1.NullThrowsReasons.MissingToken('>', 'type annotation')); + // < ( number ) > ( 3 + 5 ) + // ^---remove---^ + return fixer.removeRange([ + openingAngleBracket.range[0], + closingAngleBracket.range[1], + ]); + } + // `as` is always present in TSAsExpression + const asToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.expression, token => token.type === utils_1.AST_TOKEN_TYPES.Identifier && + token.value === 'as'), util_1.NullThrowsReasons.MissingToken('>', 'type annotation')); + const tokenBeforeAs = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(asToken, { + includeComments: true, + }), util_1.NullThrowsReasons.MissingToken('comment', 'as')); + // ( 3 + 5 ) as number + // ^--remove--^ + return fixer.removeRange([tokenBeforeAs.range[1], node.range[1]]); + }, + }); + } + // TODO - add contextually unnecessary check for this + }, + TSNonNullExpression(node) { + const removeExclamationFix = fixer => { + const exclamationToken = (0, util_1.nullThrows)(context.sourceCode.getLastToken(node, token => token.value === '!'), util_1.NullThrowsReasons.MissingToken('exclamation mark', 'non-null assertion')); + return fixer.removeRange(exclamationToken.range); + }; + if (node.parent.type === utils_1.AST_NODE_TYPES.AssignmentExpression && + node.parent.operator === '=') { + if (node.parent.left === node) { + context.report({ + node, + messageId: 'contextuallyUnnecessary', + fix: removeExclamationFix, + }); + } + // for all other = assignments we ignore non-null checks + // this is because non-null assertions can change the type-flow of the code + // so whilst they might be unnecessary for the assignment - they are necessary + // for following code + return; + } + const originalNode = services.esTreeNodeToTSNodeMap.get(node); + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node.expression); + if (!(0, util_1.isNullableType)(type)) { + if (node.expression.type === utils_1.AST_NODE_TYPES.Identifier && + isPossiblyUsedBeforeAssigned(node.expression)) { + return; + } + context.report({ + node, + messageId: 'unnecessaryAssertion', + fix: removeExclamationFix, + }); + } + else { + // we know it's a nullable type + // so figure out if the variable is used in a place that accepts nullable types + const contextualType = (0, util_1.getContextualType)(checker, originalNode); + if (contextualType) { + if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Unknown) && + !(0, util_1.isTypeFlagSet)(contextualType, ts.TypeFlags.Unknown)) { + return; + } + // in strict mode you can't assign null to undefined, so we have to make sure that + // the two types share a nullable type + const typeIncludesUndefined = (0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Undefined); + const typeIncludesNull = (0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Null); + const typeIncludesVoid = (0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Void); + const contextualTypeIncludesUndefined = (0, util_1.isTypeFlagSet)(contextualType, ts.TypeFlags.Undefined); + const contextualTypeIncludesNull = (0, util_1.isTypeFlagSet)(contextualType, ts.TypeFlags.Null); + const contextualTypeIncludesVoid = (0, util_1.isTypeFlagSet)(contextualType, ts.TypeFlags.Void); + // make sure that the parent accepts the same types + // i.e. assigning `string | null | undefined` to `string | undefined` is invalid + const isValidUndefined = typeIncludesUndefined + ? contextualTypeIncludesUndefined + : true; + const isValidNull = typeIncludesNull + ? contextualTypeIncludesNull + : true; + const isValidVoid = typeIncludesVoid + ? contextualTypeIncludesVoid + : true; + if (isValidUndefined && isValidNull && isValidVoid) { + context.report({ + node, + messageId: 'contextuallyUnnecessary', + fix: removeExclamationFix, + }); + } + } + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-constraint.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-constraint.d.ts new file mode 100644 index 00000000..5816f954 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-constraint.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"removeUnnecessaryConstraint" | "unnecessaryConstraint", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-unnecessary-type-constraint.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-constraint.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-constraint.d.ts.map new file mode 100644 index 00000000..85d6598f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-constraint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-type-constraint.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-type-constraint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAenE,wBAsGG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-constraint.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-constraint.js new file mode 100644 index 00000000..adb49eee --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-constraint.js @@ -0,0 +1,119 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const node_path_1 = require("node:path"); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unnecessary-type-constraint', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow unnecessary constraints on generic types', + recommended: 'recommended', + }, + hasSuggestions: true, + messages: { + removeUnnecessaryConstraint: 'Remove the unnecessary `{{constraint}}` constraint.', + unnecessaryConstraint: 'Constraining the generic type `{{name}}` to `{{constraint}}` does nothing and is unnecessary.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + // In theory, we could use the type checker for more advanced constraint types... + // ...but in practice, these types are rare, and likely not worth requiring type info. + // https://github.com/typescript-eslint/typescript-eslint/pull/2516#discussion_r495731858 + const unnecessaryConstraints = new Map([ + [utils_1.AST_NODE_TYPES.TSAnyKeyword, 'any'], + [utils_1.AST_NODE_TYPES.TSUnknownKeyword, 'unknown'], + ]); + function checkRequiresGenericDeclarationDisambiguation(filename) { + const pathExt = (0, node_path_1.extname)(filename).toLocaleLowerCase(); + switch (pathExt) { + case ts.Extension.Cts: + case ts.Extension.Mts: + case ts.Extension.Tsx: + return true; + default: + return false; + } + } + const requiresGenericDeclarationDisambiguation = checkRequiresGenericDeclarationDisambiguation(context.filename); + const checkNode = (node, inArrowFunction) => { + const constraint = unnecessaryConstraints.get(node.constraint.type); + function shouldAddTrailingComma() { + if (!inArrowFunction || !requiresGenericDeclarationDisambiguation) { + return false; + } + // Only () => {} would need trailing comma + return (node.parent.params.length === + 1 && + context.sourceCode.getTokensAfter(node)[0].value !== ',' && + !node.default); + } + if (constraint) { + context.report({ + node, + messageId: 'unnecessaryConstraint', + data: { + name: node.name.name, + constraint, + }, + suggest: [ + { + messageId: 'removeUnnecessaryConstraint', + data: { + constraint, + }, + fix(fixer) { + return fixer.replaceTextRange([node.name.range[1], node.constraint.range[1]], shouldAddTrailingComma() ? ',' : ''); + }, + }, + ], + }); + } + }; + return { + ':not(ArrowFunctionExpression) > TSTypeParameterDeclaration > TSTypeParameter[constraint]'(node) { + checkNode(node, false); + }, + 'ArrowFunctionExpression > TSTypeParameterDeclaration > TSTypeParameter[constraint]'(node) { + checkNode(node, true); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-conversion.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-conversion.d.ts new file mode 100644 index 00000000..bd426d3f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-conversion.d.ts @@ -0,0 +1,4 @@ +type MessageIds = 'suggestRemove' | 'suggestSatisfies' | 'unnecessaryTypeConversion'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-unnecessary-type-conversion.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-conversion.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-conversion.d.ts.map new file mode 100644 index 00000000..752cb2b7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-conversion.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-type-conversion.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-type-conversion.ts"],"names":[],"mappings":"AAgBA,KAAK,UAAU,GACX,eAAe,GACf,kBAAkB,GAClB,2BAA2B,CAAC;;AAEhC,wBAqVG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-conversion.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-conversion.js new file mode 100644 index 00000000..ac2a7ecb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-conversion.js @@ -0,0 +1,306 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unnecessary-type-conversion', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow conversion idioms when they do not change the type or value of the expression', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + suggestRemove: 'Remove the type conversion.', + suggestSatisfies: 'Instead, assert that the value satisfies the {{type}} type.', + unnecessaryTypeConversion: '{{violation}} does not change the type or value of the {{type}}.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function doesUnderlyingTypeMatchFlag(type, typeFlag) { + return tsutils + .unionConstituents(type) + .every(t => (0, util_1.isTypeFlagSet)(t, typeFlag)); + } + const services = (0, util_1.getParserServices)(context); + function handleUnaryOperator(node, typeFlag, typeString, violation, isDoubleOperator) { + const outerNode = isDoubleOperator ? node.parent : node; + const type = services.getTypeAtLocation(node.argument); + if (doesUnderlyingTypeMatchFlag(type, typeFlag)) { + const wrappingFixerParams = { + node: outerNode, + innerNode: [node.argument], + sourceCode: context.sourceCode, + }; + context.report({ + loc: { + start: outerNode.loc.start, + end: { + column: node.loc.start.column + 1, + line: node.loc.start.line, + }, + }, + messageId: 'unnecessaryTypeConversion', + data: { type: typeString, violation }, + suggest: [ + { + messageId: 'suggestRemove', + fix: (0, util_1.getWrappingFixer)(wrappingFixerParams), + }, + { + messageId: 'suggestSatisfies', + data: { type: typeString }, + fix: (0, util_1.getWrappingFixer)({ + ...wrappingFixerParams, + wrap: expr => `${expr} satisfies ${typeString}`, + }), + }, + ], + }); + } + } + return { + 'AssignmentExpression[operator = "+="]'(node) { + if (node.right.type === utils_1.AST_NODE_TYPES.Literal && + node.right.value === '' && + doesUnderlyingTypeMatchFlag(services.getTypeAtLocation(node.left), ts.TypeFlags.StringLike)) { + const wrappingFixerParams = { + node, + innerNode: [node.left], + sourceCode: context.sourceCode, + }; + context.report({ + node, + messageId: 'unnecessaryTypeConversion', + data: { + type: 'string', + violation: "Concatenating a string with ''", + }, + suggest: [ + { + messageId: 'suggestRemove', + fix: node.parent.type === utils_1.AST_NODE_TYPES.ExpressionStatement + ? (fixer) => [ + fixer.removeRange([ + node.parent.range[0], + node.parent.range[1], + ]), + ] + : (0, util_1.getWrappingFixer)(wrappingFixerParams), + }, + { + messageId: 'suggestSatisfies', + data: { type: 'string' }, + fix: (0, util_1.getWrappingFixer)({ + ...wrappingFixerParams, + wrap: expr => `${expr} satisfies string`, + }), + }, + ], + }); + } + }, + 'BinaryExpression[operator = "+"]'(node) { + if (node.right.type === utils_1.AST_NODE_TYPES.Literal && + node.right.value === '' && + doesUnderlyingTypeMatchFlag(services.getTypeAtLocation(node.left), ts.TypeFlags.StringLike)) { + const wrappingFixerParams = { + node, + innerNode: [node.left], + sourceCode: context.sourceCode, + }; + context.report({ + loc: { + start: node.left.loc.end, + end: node.loc.end, + }, + messageId: 'unnecessaryTypeConversion', + data: { + type: 'string', + violation: "Concatenating a string with ''", + }, + suggest: [ + { + messageId: 'suggestRemove', + fix: (0, util_1.getWrappingFixer)(wrappingFixerParams), + }, + { + messageId: 'suggestSatisfies', + data: { type: 'string' }, + fix: (0, util_1.getWrappingFixer)({ + ...wrappingFixerParams, + wrap: expr => `${expr} satisfies string`, + }), + }, + ], + }); + } + else if (node.left.type === utils_1.AST_NODE_TYPES.Literal && + node.left.value === '' && + doesUnderlyingTypeMatchFlag(services.getTypeAtLocation(node.right), ts.TypeFlags.StringLike)) { + const wrappingFixerParams = { + node, + innerNode: [node.right], + sourceCode: context.sourceCode, + }; + context.report({ + loc: { + start: node.loc.start, + end: node.right.loc.start, + }, + messageId: 'unnecessaryTypeConversion', + data: { + type: 'string', + violation: "Concatenating '' with a string", + }, + suggest: [ + { + messageId: 'suggestRemove', + fix: (0, util_1.getWrappingFixer)(wrappingFixerParams), + }, + { + messageId: 'suggestSatisfies', + data: { type: 'string' }, + fix: (0, util_1.getWrappingFixer)({ + ...wrappingFixerParams, + wrap: expr => `${expr} satisfies string`, + }), + }, + ], + }); + } + }, + CallExpression(node) { + const nodeCallee = node.callee; + const builtInTypeFlags = { + BigInt: ts.TypeFlags.BigIntLike, + Boolean: ts.TypeFlags.BooleanLike, + Number: ts.TypeFlags.NumberLike, + String: ts.TypeFlags.StringLike, + }; + if (nodeCallee.type !== utils_1.AST_NODE_TYPES.Identifier || + !(nodeCallee.name in builtInTypeFlags)) { + return; + } + const typeFlag = builtInTypeFlags[nodeCallee.name]; + const scope = context.sourceCode.getScope(node); + const variable = scope.set.get(nodeCallee.name); + if (!!variable?.defs.length || + !doesUnderlyingTypeMatchFlag((0, util_1.getConstrainedTypeAtLocation)(services, node.arguments[0]), typeFlag)) { + return; + } + const wrappingFixerParams = { + node, + innerNode: [node.arguments[0]], + sourceCode: context.sourceCode, + }; + const typeString = nodeCallee.name.toLowerCase(); + context.report({ + node: nodeCallee, + messageId: 'unnecessaryTypeConversion', + data: { + type: nodeCallee.name.toLowerCase(), + violation: `Passing a ${typeString} to ${nodeCallee.name}()`, + }, + suggest: [ + { + messageId: 'suggestRemove', + fix: (0, util_1.getWrappingFixer)(wrappingFixerParams), + }, + { + messageId: 'suggestSatisfies', + data: { type: typeString }, + fix: (0, util_1.getWrappingFixer)({ + ...wrappingFixerParams, + wrap: expr => `${expr} satisfies ${typeString}`, + }), + }, + ], + }); + }, + 'CallExpression > MemberExpression.callee > Identifier[name = "toString"].property'(node) { + const memberExpr = node.parent; + const type = (0, util_1.getConstrainedTypeAtLocation)(services, memberExpr.object); + if (doesUnderlyingTypeMatchFlag(type, ts.TypeFlags.StringLike)) { + const wrappingFixerParams = { + node: memberExpr.parent, + innerNode: [memberExpr.object], + sourceCode: context.sourceCode, + }; + context.report({ + loc: { + start: memberExpr.property.loc.start, + end: memberExpr.parent.loc.end, + }, + messageId: 'unnecessaryTypeConversion', + data: { + type: 'string', + violation: "Calling a string's .toString() method", + }, + suggest: [ + { + messageId: 'suggestRemove', + fix: (0, util_1.getWrappingFixer)(wrappingFixerParams), + }, + { + messageId: 'suggestSatisfies', + data: { type: 'string' }, + fix: (0, util_1.getWrappingFixer)({ + ...wrappingFixerParams, + wrap: expr => `${expr} satisfies string`, + }), + }, + ], + }); + } + }, + 'UnaryExpression[operator = "!"] > UnaryExpression[operator = "!"]'(node) { + handleUnaryOperator(node, ts.TypeFlags.BooleanLike, 'boolean', 'Using !! on a boolean', true); + }, + 'UnaryExpression[operator = "+"]'(node) { + handleUnaryOperator(node, ts.TypeFlags.NumberLike, 'number', 'Using the unary + operator on a number', false); + }, + 'UnaryExpression[operator = "~"] > UnaryExpression[operator = "~"]'(node) { + handleUnaryOperator(node, ts.TypeFlags.NumberLike, 'number', 'Using ~~ on a number', true); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-parameters.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-parameters.d.ts new file mode 100644 index 00000000..39d11e91 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-parameters.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"replaceUsagesWithConstraint" | "sole", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-unnecessary-type-parameters.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-parameters.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-parameters.d.ts.map new file mode 100644 index 00000000..4cbe9e57 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-parameters.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unnecessary-type-parameters.d.ts","sourceRoot":"","sources":["../../src/rules/no-unnecessary-type-parameters.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAqBnE,wBA0MG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-parameters.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-parameters.js new file mode 100644 index 00000000..8ef5eae6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unnecessary-type-parameters.js @@ -0,0 +1,422 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unnecessary-type-parameters', + meta: { + type: 'problem', + docs: { + description: "Disallow type parameters that aren't used multiple times", + recommended: 'strict', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + replaceUsagesWithConstraint: 'Replace all usages of type parameter with its constraint.', + sole: 'Type parameter {{name}} is {{uses}} in the {{descriptor}} signature.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const parserServices = (0, util_1.getParserServices)(context); + function checkNode(node, descriptor) { + const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node); + const checker = parserServices.program.getTypeChecker(); + let counts; + // Get the scope in which the type parameters are declared. + const scope = context.sourceCode.getScope(node); + for (const typeParameter of tsNode.typeParameters) { + const esTypeParameter = parserServices.tsNodeToESTreeNodeMap.get(typeParameter); + const smTypeParameterVariable = (0, util_1.nullThrows)((() => { + const variable = scope.set.get(esTypeParameter.name.name); + return variable?.isTypeVariable ? variable : undefined; + })(), "Type parameter should be present in scope's variables."); + // Quick path: if the type parameter is used multiple times in the AST, + // we don't need to dip into types to know it's repeated. + if (isTypeParameterRepeatedInAST(esTypeParameter, smTypeParameterVariable.references, node.body?.range[0] ?? node.returnType?.range[1])) { + continue; + } + // For any inferred types, we have to dip into type checking. + counts ??= countTypeParameterUsage(checker, tsNode); + const identifierCounts = counts.get(typeParameter.name); + if (!identifierCounts || identifierCounts > 2) { + continue; + } + context.report({ + node: esTypeParameter, + messageId: 'sole', + data: { + name: typeParameter.name.text, + descriptor, + uses: identifierCounts === 1 ? 'never used' : 'used only once', + }, + suggest: [ + { + messageId: 'replaceUsagesWithConstraint', + *fix(fixer) { + // Replace all the usages of the type parameter with the constraint... + const constraint = esTypeParameter.constraint; + // special case - a constraint of 'any' actually acts like 'unknown' + const constraintText = constraint != null && + constraint.type !== utils_1.AST_NODE_TYPES.TSAnyKeyword + ? context.sourceCode.getText(constraint) + : 'unknown'; + for (const reference of smTypeParameterVariable.references) { + if (reference.isTypeReference) { + const referenceNode = reference.identifier; + const isComplexType = constraint?.type === utils_1.AST_NODE_TYPES.TSUnionType || + constraint?.type === utils_1.AST_NODE_TYPES.TSIntersectionType || + constraint?.type === utils_1.AST_NODE_TYPES.TSConditionalType; + const hasMatchingAncestorType = [ + utils_1.AST_NODE_TYPES.TSArrayType, + utils_1.AST_NODE_TYPES.TSIndexedAccessType, + utils_1.AST_NODE_TYPES.TSIntersectionType, + utils_1.AST_NODE_TYPES.TSUnionType, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + ].some(type => referenceNode.parent.parent.type === type); + if (isComplexType && hasMatchingAncestorType) { + const fixResult = (0, util_1.getWrappingFixer)({ + node: referenceNode, + innerNode: constraint, + sourceCode: context.sourceCode, + wrap: constraintNode => constraintNode, + })(fixer); + yield fixResult; + } + else { + yield fixer.replaceText(referenceNode, constraintText); + } + } + } + // ...and remove the type parameter itself from the declaration. + const typeParamsNode = (0, util_1.nullThrows)(node.typeParameters, 'node should have type parameters'); + // We are assuming at this point that the reported type parameter + // is present in the inspected node's type parameters. + if (typeParamsNode.params.length === 1) { + // Remove the whole generic syntax if we're removing the only type parameter in the list. + yield fixer.remove(typeParamsNode); + } + else { + const index = typeParamsNode.params.indexOf(esTypeParameter); + if (index === 0) { + const commaAfter = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(esTypeParameter, token => token.value === ','), util_1.NullThrowsReasons.MissingToken('comma', 'type parameter list')); + const tokenAfterComma = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(commaAfter, { + includeComments: true, + }), util_1.NullThrowsReasons.MissingToken('token', 'type parameter list')); + yield fixer.removeRange([ + esTypeParameter.range[0], + tokenAfterComma.range[0], + ]); + } + else { + const commaBefore = (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(esTypeParameter, token => token.value === ','), util_1.NullThrowsReasons.MissingToken('comma', 'type parameter list')); + yield fixer.removeRange([ + commaBefore.range[0], + esTypeParameter.range[1], + ]); + } + } + }, + }, + ], + }); + } + } + return { + [[ + 'ArrowFunctionExpression[typeParameters]', + 'FunctionDeclaration[typeParameters]', + 'FunctionExpression[typeParameters]', + 'TSCallSignatureDeclaration[typeParameters]', + 'TSConstructorType[typeParameters]', + 'TSDeclareFunction[typeParameters]', + 'TSEmptyBodyFunctionExpression[typeParameters]', + 'TSFunctionType[typeParameters]', + 'TSMethodSignature[typeParameters]', + ].join(', ')](node) { + checkNode(node, 'function'); + }, + [[ + 'ClassDeclaration[typeParameters]', + 'ClassExpression[typeParameters]', + ].join(', ')](node) { + checkNode(node, 'class'); + }, + }; + }, +}); +function isTypeParameterRepeatedInAST(node, references, startOfBody = Infinity) { + let total = 0; + for (const reference of references) { + // References inside the type parameter's definition don't count... + if (reference.identifier.range[0] < node.range[1] && + reference.identifier.range[1] > node.range[0]) { + continue; + } + // ...nor references that are outside the declaring signature. + if (reference.identifier.range[0] > startOfBody) { + continue; + } + // Neither do references that aren't to the same type parameter, + // namely value-land (non-type) identifiers of the type parameter's type, + // and references to different type parameters or values. + if (!reference.isTypeReference || + reference.identifier.name !== node.name.name) { + continue; + } + // If the type parameter is being used as a type argument, then we + // know the type parameter is being reused and can't be reported. + if (reference.identifier.parent.type === utils_1.AST_NODE_TYPES.TSTypeReference) { + const grandparent = skipConstituentsUpward(reference.identifier.parent.parent); + if (grandparent.type === utils_1.AST_NODE_TYPES.TSTypeParameterInstantiation && + grandparent.params.includes(reference.identifier.parent) && + // Array and ReadonlyArray must be handled carefully + // let's defer the check to the type-aware phase + !(grandparent.parent.type === utils_1.AST_NODE_TYPES.TSTypeReference && + grandparent.parent.typeName.type === utils_1.AST_NODE_TYPES.Identifier && + ['Array', 'ReadonlyArray'].includes(grandparent.parent.typeName.name))) { + return true; + } + } + total += 1; + if (total >= 2) { + return true; + } + } + return false; +} +function skipConstituentsUpward(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSIntersectionType: + case utils_1.AST_NODE_TYPES.TSUnionType: + return skipConstituentsUpward(node.parent); + default: + return node; + } +} +/** + * Count uses of type parameters in inferred return types. + * We need to resolve and analyze the inferred return type of a function + * to see whether it contains additional references to the type parameters. + * For classes, we need to do this for all their methods. + */ +function countTypeParameterUsage(checker, node) { + const counts = new Map(); + if (ts.isClassLike(node)) { + for (const typeParameter of node.typeParameters) { + collectTypeParameterUsageCounts(checker, typeParameter, counts, true); + } + for (const member of node.members) { + collectTypeParameterUsageCounts(checker, member, counts, true); + } + } + else { + collectTypeParameterUsageCounts(checker, node, counts, false); + } + return counts; +} +/** + * Populates {@link foundIdentifierUsages} by the number of times each type parameter + * appears in the given type by checking its uses through its type references. + * This is essentially a limited subset of the scope manager, but for types. + */ +function collectTypeParameterUsageCounts(checker, node, foundIdentifierUsages, fromClass) { + const visitedSymbolLists = new Set(); + const type = checker.getTypeAtLocation(node); + const typeUsages = new Map(); + const visitedConstraints = new Set(); + let functionLikeType = false; + let visitedDefault = false; + if (ts.isCallSignatureDeclaration(node) || + ts.isConstructorDeclaration(node)) { + functionLikeType = true; + visitSignature(checker.getSignatureFromDeclaration(node)); + } + if (!functionLikeType) { + visitType(type, false); + } + function visitType(type, assumeMultipleUses, isReturnType = false) { + // Seeing the same type > (threshold=3 ** 2) times indicates a likely + // recursive type, like `type T = { [P in keyof T]: T }`. + // If it's not recursive, then heck, we've seen it enough times that any + // referenced types have been counted enough to qualify as used. + if (!type || incrementTypeUsages(type) > 9) { + return; + } + if (tsutils.isTypeParameter(type)) { + const declaration = type.getSymbol()?.getDeclarations()?.[0]; + if (declaration) { + incrementIdentifierCount(declaration.name, assumeMultipleUses); + // Visiting the type of a constrained type parameter will recurse into + // the constraint. We avoid infinite loops by visiting each only once. + if (declaration.constraint && + !visitedConstraints.has(declaration.constraint)) { + visitedConstraints.add(declaration.constraint); + visitType(checker.getTypeAtLocation(declaration.constraint), false); + } + if (declaration.default && !visitedDefault) { + visitedDefault = true; + visitType(checker.getTypeAtLocation(declaration.default), false); + } + } + } + // Catch-all: generic type references like `Exclude` + else if (type.aliasTypeArguments) { + // We don't descend into the definition of the type alias, so we don't + // know whether it's used multiple times. It's safest to assume it is. + visitTypesList(type.aliasTypeArguments, true); + } + // Intersections and unions like `0 | 1` + else if (tsutils.isUnionOrIntersectionType(type)) { + visitTypesList(type.types, assumeMultipleUses); + } + // Index access types like `T[K]` + else if (tsutils.isIndexedAccessType(type)) { + visitType(type.objectType, assumeMultipleUses); + visitType(type.indexType, assumeMultipleUses); + } + // Tuple types like `[K, V]` + // Generic type references like `Map` + else if (tsutils.isTypeReference(type)) { + for (const typeArgument of type.typeArguments ?? []) { + // currently, if we are in a "class context", everything is accepted + let thisAssumeMultipleUses = fromClass || assumeMultipleUses; + // special cases - readonly arrays/tuples are considered only to use the + // type parameter once. Mutable arrays/tuples are considered to use the + // type parameter multiple times if and only if they are returned. + // other kind of type references always count as multiple uses + thisAssumeMultipleUses ||= tsutils.isTupleType(type.target) + ? isReturnType && !type.target.readonly + : checker.isArrayType(type.target) + ? isReturnType && + type.symbol?.getName() === 'Array' + : true; + visitType(typeArgument, thisAssumeMultipleUses, isReturnType); + } + } + // Template literals like `a${T}b` + else if (tsutils.isTemplateLiteralType(type)) { + for (const subType of type.types) { + visitType(subType, assumeMultipleUses); + } + } + // Conditional types like `T extends string ? T : never` + else if (tsutils.isConditionalType(type)) { + visitType(type.checkType, assumeMultipleUses); + visitType(type.extendsType, assumeMultipleUses); + } + // Catch-all: inferred object types like `{ K: V }`. + // These catch-alls should be _after_ more specific checks like + // `isTypeReference` to avoid descending into all the properties of a + // generic interface/class, e.g. `Map`. + else if (tsutils.isObjectType(type)) { + const properties = type.getProperties(); + visitSymbolsListOnce(properties, false); + if (isMappedType(type)) { + visitType(type.typeParameter, false); + if (properties.length === 0) { + // TS treats mapped types like `{[k in "a"]: T}` like `{a: T}`. + // They have properties, so we need to avoid double-counting. + visitType(type.templateType ?? type.constraintType, false); + } + } + visitType(type.getNumberIndexType(), true); + visitType(type.getStringIndexType(), true); + type.getCallSignatures().forEach(signature => { + functionLikeType = true; + visitSignature(signature); + }); + type.getConstructSignatures().forEach(signature => { + functionLikeType = true; + visitSignature(signature); + }); + } + // Catch-all: operator types like `keyof T` + else if (isOperatorType(type)) { + visitType(type.type, assumeMultipleUses); + } + } + function incrementIdentifierCount(id, assumeMultipleUses) { + const identifierCount = foundIdentifierUsages.get(id) ?? 0; + const value = assumeMultipleUses ? 2 : 1; + foundIdentifierUsages.set(id, identifierCount + value); + } + function incrementTypeUsages(type) { + const count = (typeUsages.get(type) ?? 0) + 1; + typeUsages.set(type, count); + return count; + } + function visitSignature(signature) { + if (!signature) { + return; + } + if (signature.thisParameter) { + visitType(checker.getTypeOfSymbol(signature.thisParameter), false); + } + for (const parameter of signature.parameters) { + visitType(checker.getTypeOfSymbol(parameter), false); + } + for (const typeParameter of signature.getTypeParameters() ?? []) { + visitType(typeParameter, false); + } + visitType(checker.getTypePredicateOfSignature(signature)?.type ?? + signature.getReturnType(), false, true); + } + function visitSymbolsListOnce(symbols, assumeMultipleUses) { + if (visitedSymbolLists.has(symbols)) { + return; + } + visitedSymbolLists.add(symbols); + for (const symbol of symbols) { + visitType(checker.getTypeOfSymbol(symbol), assumeMultipleUses); + } + } + function visitTypesList(types, assumeMultipleUses) { + for (const type of types) { + visitType(type, assumeMultipleUses); + } + } +} +function isMappedType(type) { + return 'typeParameter' in type; +} +function isOperatorType(type) { + return 'type' in type && !!type.type; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-argument.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-argument.d.ts new file mode 100644 index 00000000..2535f14b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-argument.d.ts @@ -0,0 +1,4 @@ +export type MessageIds = 'unsafeArgument' | 'unsafeArraySpread' | 'unsafeSpread' | 'unsafeTupleSpread'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-unsafe-argument.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-argument.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-argument.d.ts.map new file mode 100644 index 00000000..51978689 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-argument.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-argument.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-argument.ts"],"names":[],"mappings":"AAgBA,MAAM,MAAM,UAAU,GAClB,gBAAgB,GAChB,mBAAmB,GACnB,cAAc,GACd,mBAAmB,CAAC;;AA2HxB,wBAuLG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-argument.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-argument.js new file mode 100644 index 00000000..0ac4090c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-argument.js @@ -0,0 +1,272 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +var RestTypeKind; +(function (RestTypeKind) { + RestTypeKind[RestTypeKind["Array"] = 0] = "Array"; + RestTypeKind[RestTypeKind["Tuple"] = 1] = "Tuple"; + RestTypeKind[RestTypeKind["Other"] = 2] = "Other"; +})(RestTypeKind || (RestTypeKind = {})); +class FunctionSignature { + paramTypes; + restType; + hasConsumedArguments = false; + parameterTypeIndex = 0; + constructor(paramTypes, restType) { + this.paramTypes = paramTypes; + this.restType = restType; + } + static create(checker, tsNode) { + const signature = checker.getResolvedSignature(tsNode); + if (!signature) { + return null; + } + const paramTypes = []; + let restType = null; + const parameters = signature.getParameters(); + for (let i = 0; i < parameters.length; i += 1) { + const param = parameters[i]; + const type = checker.getTypeOfSymbolAtLocation(param, tsNode); + const decl = param.getDeclarations()?.[0]; + if (decl && (0, util_1.isRestParameterDeclaration)(decl)) { + // is a rest param + if (checker.isArrayType(type)) { + restType = { + type: checker.getTypeArguments(type)[0], + index: i, + kind: RestTypeKind.Array, + }; + } + else if (checker.isTupleType(type)) { + restType = { + index: i, + kind: RestTypeKind.Tuple, + typeArguments: checker.getTypeArguments(type), + }; + } + else { + restType = { + type, + index: i, + kind: RestTypeKind.Other, + }; + } + break; + } + paramTypes.push(type); + } + return new this(paramTypes, restType); + } + consumeRemainingArguments() { + this.hasConsumedArguments = true; + } + getNextParameterType() { + const index = this.parameterTypeIndex; + this.parameterTypeIndex += 1; + if (index >= this.paramTypes.length || this.hasConsumedArguments) { + if (this.restType == null) { + return null; + } + switch (this.restType.kind) { + case RestTypeKind.Tuple: { + const typeArguments = this.restType.typeArguments; + if (this.hasConsumedArguments) { + // all types consumed by a rest - just assume it's the last type + // there is one edge case where this is wrong, but we ignore it because + // it's rare and really complicated to handle + // eg: function foo(...a: [number, ...string[], number]) + return typeArguments[typeArguments.length - 1]; + } + const typeIndex = index - this.restType.index; + if (typeIndex >= typeArguments.length) { + return typeArguments[typeArguments.length - 1]; + } + return typeArguments[typeIndex]; + } + case RestTypeKind.Array: + case RestTypeKind.Other: + return this.restType.type; + } + } + return this.paramTypes[index]; + } +} +exports.default = (0, util_1.createRule)({ + name: 'no-unsafe-argument', + meta: { + type: 'problem', + docs: { + description: 'Disallow calling a function with a value with type `any`', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + unsafeArgument: 'Unsafe argument of type {{sender}} assigned to a parameter of type {{receiver}}.', + unsafeArraySpread: 'Unsafe spread of an {{sender}} array type.', + unsafeSpread: 'Unsafe spread of an {{sender}} type.', + unsafeTupleSpread: 'Unsafe spread of a tuple type. The argument is {{sender}} and is assigned to a parameter of type {{receiver}}.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function describeType(type) { + if (tsutils.isIntrinsicErrorType(type)) { + return 'error typed'; + } + return `\`${checker.typeToString(type)}\``; + } + function describeTypeForSpread(type) { + if (checker.isArrayType(type) && + tsutils.isIntrinsicErrorType(checker.getTypeArguments(type)[0])) { + return 'error'; + } + return describeType(type); + } + function describeTypeForTuple(type) { + if (tsutils.isIntrinsicErrorType(type)) { + return 'error typed'; + } + return `of type \`${checker.typeToString(type)}\``; + } + function checkUnsafeArguments(args, callee, node) { + if (args.length === 0) { + return; + } + // ignore any-typed calls as these are caught by no-unsafe-call + if ((0, util_1.isTypeAnyType)(services.getTypeAtLocation(callee))) { + return; + } + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + const signature = (0, util_1.nullThrows)(FunctionSignature.create(checker, tsNode), 'Expected to a signature resolved'); + if (node.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression) { + // Consumes the first parameter (TemplateStringsArray) of the function called with TaggedTemplateExpression. + signature.getNextParameterType(); + } + for (const argument of args) { + switch (argument.type) { + // spreads consume + case utils_1.AST_NODE_TYPES.SpreadElement: { + const spreadArgType = services.getTypeAtLocation(argument.argument); + if ((0, util_1.isTypeAnyType)(spreadArgType)) { + // foo(...any) + context.report({ + node: argument, + messageId: 'unsafeSpread', + data: { sender: describeType(spreadArgType) }, + }); + } + else if ((0, util_1.isTypeAnyArrayType)(spreadArgType, checker)) { + // foo(...any[]) + // TODO - we could break down the spread and compare the array type against each argument + context.report({ + node: argument, + messageId: 'unsafeArraySpread', + data: { sender: describeTypeForSpread(spreadArgType) }, + }); + } + else if (checker.isTupleType(spreadArgType)) { + // foo(...[tuple1, tuple2]) + const spreadTypeArguments = checker.getTypeArguments(spreadArgType); + for (const tupleType of spreadTypeArguments) { + const parameterType = signature.getNextParameterType(); + if (parameterType == null) { + continue; + } + const result = (0, util_1.isUnsafeAssignment)(tupleType, parameterType, checker, + // we can't pass the individual tuple members in here as this will most likely be a spread variable + // not a spread array + null); + if (result) { + context.report({ + node: argument, + messageId: 'unsafeTupleSpread', + data: { + receiver: describeType(parameterType), + sender: describeTypeForTuple(tupleType), + }, + }); + } + } + if (spreadArgType.target.combinedFlags & ts.ElementFlags.Variable) { + // the last element was a rest - so all remaining defined arguments can be considered "consumed" + // all remaining arguments should be compared against the rest type (if one exists) + signature.consumeRemainingArguments(); + } + } + else { + // something that's iterable + // handling this will be pretty complex - so we ignore it for now + // TODO - handle generic iterable case + } + break; + } + default: { + const parameterType = signature.getNextParameterType(); + if (parameterType == null) { + continue; + } + const argumentType = services.getTypeAtLocation(argument); + const result = (0, util_1.isUnsafeAssignment)(argumentType, parameterType, checker, argument); + if (result) { + context.report({ + node: argument, + messageId: 'unsafeArgument', + data: { + receiver: describeType(parameterType), + sender: describeType(argumentType), + }, + }); + } + } + } + } + } + return { + 'CallExpression, NewExpression'(node) { + checkUnsafeArguments(node.arguments, node.callee, node); + }, + TaggedTemplateExpression(node) { + checkUnsafeArguments(node.quasi.expressions, node.tag, node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-assignment.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-assignment.d.ts new file mode 100644 index 00000000..b93ea5e6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-assignment.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeArraySpread" | "anyAssignment" | "anyAssignmentThis" | "unsafeArrayPattern" | "unsafeArrayPatternFromTuple" | "unsafeAssignment", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unsafe-assignment.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-assignment.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-assignment.d.ts.map new file mode 100644 index 00000000..818e5325 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-assignment.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-assignment.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-assignment.ts"],"names":[],"mappings":";AA6BA,wBA4ZG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-assignment.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-assignment.js new file mode 100644 index 00000000..6ec98589 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-assignment.js @@ -0,0 +1,320 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +var ComparisonType; +(function (ComparisonType) { + /** Do no assignment comparison */ + ComparisonType[ComparisonType["None"] = 0] = "None"; + /** Use the receiver's type for comparison */ + ComparisonType[ComparisonType["Basic"] = 1] = "Basic"; + /** Use the sender's contextual type for comparison */ + ComparisonType[ComparisonType["Contextual"] = 2] = "Contextual"; +})(ComparisonType || (ComparisonType = {})); +exports.default = (0, util_1.createRule)({ + name: 'no-unsafe-assignment', + meta: { + type: 'problem', + docs: { + description: 'Disallow assigning a value with type `any` to variables and properties', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + anyAssignment: 'Unsafe assignment of an {{sender}} value.', + anyAssignmentThis: [ + 'Unsafe assignment of an {{sender}} value. `this` is typed as `any`.', + 'You can try to fix this by turning on the `noImplicitThis` compiler option, or adding a `this` parameter to the function.', + ].join('\n'), + unsafeArrayPattern: 'Unsafe array destructuring of an {{sender}} array value.', + unsafeArrayPatternFromTuple: 'Unsafe array destructuring of a tuple element with an {{sender}} value.', + unsafeArraySpread: 'Unsafe spread of an {{sender}} value in an array.', + unsafeAssignment: 'Unsafe assignment of type {{sender}} to a variable of type {{receiver}}.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const compilerOptions = services.program.getCompilerOptions(); + const isNoImplicitThis = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'noImplicitThis'); + // returns true if the assignment reported + function checkArrayDestructureHelper(receiverNode, senderNode) { + if (receiverNode.type !== utils_1.AST_NODE_TYPES.ArrayPattern) { + return false; + } + const senderTsNode = services.esTreeNodeToTSNodeMap.get(senderNode); + const senderType = services.getTypeAtLocation(senderNode); + return checkArrayDestructure(receiverNode, senderType, senderTsNode); + } + // returns true if the assignment reported + function checkArrayDestructure(receiverNode, senderType, senderNode) { + // any array + // const [x] = ([] as any[]); + if ((0, util_1.isTypeAnyArrayType)(senderType, checker)) { + context.report({ + node: receiverNode, + messageId: 'unsafeArrayPattern', + data: createData(senderType), + }); + return false; + } + if (!checker.isTupleType(senderType)) { + return true; + } + const tupleElements = checker.getTypeArguments(senderType); + // tuple with any + // const [x] = [1 as any]; + let didReport = false; + for (let receiverIndex = 0; receiverIndex < receiverNode.elements.length; receiverIndex += 1) { + const receiverElement = receiverNode.elements[receiverIndex]; + if (!receiverElement) { + continue; + } + if (receiverElement.type === utils_1.AST_NODE_TYPES.RestElement) { + // don't handle rests as they're not a 1:1 assignment + continue; + } + const senderType = tupleElements[receiverIndex]; + if (!senderType) { + continue; + } + // check for the any type first so we can handle [[[x]]] = [any] + if ((0, util_1.isTypeAnyType)(senderType)) { + context.report({ + node: receiverElement, + messageId: 'unsafeArrayPatternFromTuple', + data: createData(senderType), + }); + // we want to report on every invalid element in the tuple + didReport = true; + } + else if (receiverElement.type === utils_1.AST_NODE_TYPES.ArrayPattern) { + didReport = checkArrayDestructure(receiverElement, senderType, senderNode); + } + else if (receiverElement.type === utils_1.AST_NODE_TYPES.ObjectPattern) { + didReport = checkObjectDestructure(receiverElement, senderType, senderNode); + } + } + return didReport; + } + // returns true if the assignment reported + function checkObjectDestructureHelper(receiverNode, senderNode) { + if (receiverNode.type !== utils_1.AST_NODE_TYPES.ObjectPattern) { + return false; + } + const senderTsNode = services.esTreeNodeToTSNodeMap.get(senderNode); + const senderType = services.getTypeAtLocation(senderNode); + return checkObjectDestructure(receiverNode, senderType, senderTsNode); + } + // returns true if the assignment reported + function checkObjectDestructure(receiverNode, senderType, senderNode) { + const properties = new Map(senderType + .getProperties() + .map(property => [ + property.getName(), + checker.getTypeOfSymbolAtLocation(property, senderNode), + ])); + let didReport = false; + for (const receiverProperty of receiverNode.properties) { + if (receiverProperty.type === utils_1.AST_NODE_TYPES.RestElement) { + // don't bother checking rest + continue; + } + let key; + if (!receiverProperty.computed) { + key = + receiverProperty.key.type === utils_1.AST_NODE_TYPES.Identifier + ? receiverProperty.key.name + : String(receiverProperty.key.value); + } + else if (receiverProperty.key.type === utils_1.AST_NODE_TYPES.Literal) { + key = String(receiverProperty.key.value); + } + else if (receiverProperty.key.type === utils_1.AST_NODE_TYPES.TemplateLiteral && + receiverProperty.key.quasis.length === 1) { + key = receiverProperty.key.quasis[0].value.cooked; + } + else { + // can't figure out the name, so skip it + continue; + } + const senderType = properties.get(key); + if (!senderType) { + continue; + } + // check for the any type first so we can handle {x: {y: z}} = {x: any} + if ((0, util_1.isTypeAnyType)(senderType)) { + context.report({ + node: receiverProperty.value, + messageId: 'unsafeArrayPatternFromTuple', + data: createData(senderType), + }); + didReport = true; + } + else if (receiverProperty.value.type === utils_1.AST_NODE_TYPES.ArrayPattern) { + didReport = checkArrayDestructure(receiverProperty.value, senderType, senderNode); + } + else if (receiverProperty.value.type === utils_1.AST_NODE_TYPES.ObjectPattern) { + didReport = checkObjectDestructure(receiverProperty.value, senderType, senderNode); + } + } + return didReport; + } + // returns true if the assignment reported + function checkAssignment(receiverNode, senderNode, reportingNode, comparisonType) { + const receiverTsNode = services.esTreeNodeToTSNodeMap.get(receiverNode); + const receiverType = comparisonType === ComparisonType.Contextual + ? ((0, util_1.getContextualType)(checker, receiverTsNode) ?? + services.getTypeAtLocation(receiverNode)) + : services.getTypeAtLocation(receiverNode); + const senderType = services.getTypeAtLocation(senderNode); + if ((0, util_1.isTypeAnyType)(senderType)) { + // handle cases when we assign any ==> unknown. + if ((0, util_1.isTypeUnknownType)(receiverType)) { + return false; + } + let messageId = 'anyAssignment'; + if (!isNoImplicitThis) { + // `var foo = this` + const thisExpression = (0, util_1.getThisExpression)(senderNode); + if (thisExpression && + (0, util_1.isTypeAnyType)((0, util_1.getConstrainedTypeAtLocation)(services, thisExpression))) { + messageId = 'anyAssignmentThis'; + } + } + context.report({ + node: reportingNode, + messageId, + data: createData(senderType), + }); + return true; + } + if (comparisonType === ComparisonType.None) { + return false; + } + const result = (0, util_1.isUnsafeAssignment)(senderType, receiverType, checker, senderNode); + if (!result) { + return false; + } + const { receiver, sender } = result; + context.report({ + node: reportingNode, + messageId: 'unsafeAssignment', + data: createData(sender, receiver), + }); + return true; + } + function getComparisonType(typeAnnotation) { + return typeAnnotation + ? // if there's a type annotation, we can do a comparison + ComparisonType.Basic + : // no type annotation means the variable's type will just be inferred, thus equal + ComparisonType.None; + } + function createData(senderType, receiverType) { + if (receiverType) { + return { + receiver: `\`${checker.typeToString(receiverType)}\``, + sender: `\`${checker.typeToString(senderType)}\``, + }; + } + return { + sender: tsutils.isIntrinsicErrorType(senderType) + ? 'error typed' + : '`any`', + }; + } + return { + 'AccessorProperty[value != null]'(node) { + checkAssignment(node.key, node.value, node, getComparisonType(node.typeAnnotation)); + }, + 'AssignmentExpression[operator = "="], AssignmentPattern'(node) { + let didReport = checkAssignment(node.left, node.right, node, + // the variable already has some form of a type to compare against + ComparisonType.Basic); + if (!didReport) { + didReport = checkArrayDestructureHelper(node.left, node.right); + } + if (!didReport) { + checkObjectDestructureHelper(node.left, node.right); + } + }, + 'PropertyDefinition[value != null]'(node) { + checkAssignment(node.key, node.value, node, getComparisonType(node.typeAnnotation)); + }, + 'VariableDeclarator[init != null]'(node) { + const init = (0, util_1.nullThrows)(node.init, util_1.NullThrowsReasons.MissingToken(node.type, 'init')); + let didReport = checkAssignment(node.id, init, node, getComparisonType(node.id.typeAnnotation)); + if (!didReport) { + didReport = checkArrayDestructureHelper(node.id, init); + } + if (!didReport) { + checkObjectDestructureHelper(node.id, init); + } + }, + // object pattern props are checked via assignments + ':not(ObjectPattern) > Property'(node) { + if (node.value.type === utils_1.AST_NODE_TYPES.AssignmentPattern || + node.value.type === utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression) { + // handled by other selector + return; + } + checkAssignment(node.key, node.value, node, ComparisonType.Contextual); + }, + 'ArrayExpression > SpreadElement'(node) { + const restType = services.getTypeAtLocation(node.argument); + if ((0, util_1.isTypeAnyType)(restType) || (0, util_1.isTypeAnyArrayType)(restType, checker)) { + context.report({ + node, + messageId: 'unsafeArraySpread', + data: createData(restType), + }); + } + }, + 'JSXAttribute[value != null]'(node) { + const value = (0, util_1.nullThrows)(node.value, util_1.NullThrowsReasons.MissingToken(node.type, 'value')); + if (value.type !== utils_1.AST_NODE_TYPES.JSXExpressionContainer || + value.expression.type === utils_1.AST_NODE_TYPES.JSXEmptyExpression) { + return; + } + checkAssignment(node.name, value.expression, value.expression, ComparisonType.Contextual); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-call.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-call.d.ts new file mode 100644 index 00000000..e78db264 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-call.d.ts @@ -0,0 +1,4 @@ +export type MessageIds = 'unsafeCall' | 'unsafeCallThis' | 'unsafeNew' | 'unsafeTemplateTag'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=no-unsafe-call.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-call.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-call.d.ts.map new file mode 100644 index 00000000..916aba4c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-call.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-call.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-call.ts"],"names":[],"mappings":"AAaA,MAAM,MAAM,UAAU,GAClB,YAAY,GACZ,gBAAgB,GAChB,WAAW,GACX,mBAAmB,CAAC;;AAExB,wBAuHG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-call.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-call.js new file mode 100644 index 00000000..8aa687e4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-call.js @@ -0,0 +1,131 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unsafe-call', + meta: { + type: 'problem', + docs: { + description: 'Disallow calling a value with type `any`', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + unsafeCall: 'Unsafe call of a(n) {{type}} typed value.', + unsafeCallThis: [ + 'Unsafe call of a(n) {{type}} typed value. `this` is typed as {{type}}.', + 'You can try to fix this by turning on the `noImplicitThis` compiler option, or adding a `this` parameter to the function.', + ].join('\n'), + unsafeNew: 'Unsafe construction of a(n) {{type}} typed value.', + unsafeTemplateTag: 'Unsafe use of a(n) {{type}} typed template tag.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const compilerOptions = services.program.getCompilerOptions(); + const isNoImplicitThis = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'noImplicitThis'); + function checkCall(node, reportingNode, messageId) { + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node); + if ((0, util_1.isTypeAnyType)(type)) { + if (!isNoImplicitThis) { + // `this()` or `this.foo()` or `this.foo[bar]()` + const thisExpression = (0, util_1.getThisExpression)(node); + if (thisExpression && + (0, util_1.isTypeAnyType)((0, util_1.getConstrainedTypeAtLocation)(services, thisExpression))) { + messageId = 'unsafeCallThis'; + } + } + const isErrorType = tsutils.isIntrinsicErrorType(type); + context.report({ + node: reportingNode, + messageId, + data: { + type: isErrorType ? '`error` type' : '`any`', + }, + }); + return; + } + if ((0, util_1.isBuiltinSymbolLike)(services.program, type, 'Function')) { + // this also matches subtypes of `Function`, like `interface Foo extends Function {}`. + // + // For weird TS reasons that I don't understand, these are + // + // safe to construct if: + // - they have at least one call signature _that is not void-returning_, + // - OR they have at least one construct signature. + // + // safe to call (including as template) if: + // - they have at least one call signature + // - OR they have at least one construct signature. + const constructSignatures = type.getConstructSignatures(); + if (constructSignatures.length > 0) { + return; + } + const callSignatures = type.getCallSignatures(); + if (messageId === 'unsafeNew') { + if (callSignatures.some(signature => !tsutils.isIntrinsicVoidType(signature.getReturnType()))) { + return; + } + } + else if (callSignatures.length > 0) { + return; + } + context.report({ + node: reportingNode, + messageId, + data: { + type: '`Function`', + }, + }); + return; + } + } + return { + 'CallExpression > *.callee'(node) { + checkCall(node, node, 'unsafeCall'); + }, + NewExpression(node) { + checkCall(node.callee, node, 'unsafeNew'); + }, + 'TaggedTemplateExpression > *.tag'(node) { + checkCall(node, node, 'unsafeTemplateTag'); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-declaration-merging.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-declaration-merging.d.ts new file mode 100644 index 00000000..476c64a3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-declaration-merging.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeMerging", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unsafe-declaration-merging.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-declaration-merging.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-declaration-merging.d.ts.map new file mode 100644 index 00000000..236ef9d6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-declaration-merging.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-declaration-merging.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-declaration-merging.ts"],"names":[],"mappings":";AAOA,wBAkEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-declaration-merging.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-declaration-merging.js new file mode 100644 index 00000000..8d54322f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-declaration-merging.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unsafe-declaration-merging', + meta: { + type: 'problem', + docs: { + description: 'Disallow unsafe declaration merging', + recommended: 'recommended', + requiresTypeChecking: false, + }, + messages: { + unsafeMerging: 'Unsafe declaration merging between classes and interfaces.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function checkUnsafeDeclaration(scope, node, unsafeKind) { + const variable = scope.set.get(node.name); + if (!variable) { + return; + } + const defs = variable.defs; + if (defs.length <= 1) { + return; + } + if (defs.some(def => def.node.type === unsafeKind)) { + context.report({ + node, + messageId: 'unsafeMerging', + }); + } + } + return { + ClassDeclaration(node) { + if (node.id) { + // by default eslint returns the inner class scope for the ClassDeclaration node + // but we want the outer scope within which merged variables will sit + const currentScope = context.sourceCode.getScope(node).upper; + if (currentScope == null) { + return; + } + checkUnsafeDeclaration(currentScope, node.id, utils_1.AST_NODE_TYPES.TSInterfaceDeclaration); + } + }, + TSInterfaceDeclaration(node) { + checkUnsafeDeclaration(context.sourceCode.getScope(node), node.id, utils_1.AST_NODE_TYPES.ClassDeclaration); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-enum-comparison.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-enum-comparison.d.ts new file mode 100644 index 00000000..642696e5 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-enum-comparison.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"mismatchedCase" | "mismatchedCondition" | "replaceValueWithEnum", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-unsafe-enum-comparison.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-enum-comparison.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-enum-comparison.d.ts.map new file mode 100644 index 00000000..66a1d3f1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-enum-comparison.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-enum-comparison.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-enum-comparison.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAyDnE,wBAsJG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-enum-comparison.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-enum-comparison.js new file mode 100644 index 00000000..d2a7d1f4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-enum-comparison.js @@ -0,0 +1,190 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const shared_1 = require("./enum-utils/shared"); +/** + * @returns Whether the right type is an unsafe comparison against any left type. + */ +function typeViolates(leftTypeParts, rightType) { + const leftEnumValueTypes = new Set(leftTypeParts.map(getEnumValueType)); + return ((leftEnumValueTypes.has(ts.TypeFlags.Number) && isNumberLike(rightType)) || + (leftEnumValueTypes.has(ts.TypeFlags.String) && isStringLike(rightType))); +} +function isNumberLike(type) { + const typeParts = tsutils.intersectionConstituents(type); + return typeParts.some(typePart => { + return tsutils.isTypeFlagSet(typePart, ts.TypeFlags.Number | ts.TypeFlags.NumberLike); + }); +} +function isStringLike(type) { + const typeParts = tsutils.intersectionConstituents(type); + return typeParts.some(typePart => { + return tsutils.isTypeFlagSet(typePart, ts.TypeFlags.String | ts.TypeFlags.StringLike); + }); +} +/** + * @returns What type a type's enum value is (number or string), if either. + */ +function getEnumValueType(type) { + return tsutils.isTypeFlagSet(type, ts.TypeFlags.EnumLike) + ? tsutils.isTypeFlagSet(type, ts.TypeFlags.NumberLiteral) + ? ts.TypeFlags.Number + : ts.TypeFlags.String + : undefined; +} +exports.default = (0, util_1.createRule)({ + name: 'no-unsafe-enum-comparison', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow comparing an enum value with a non-enum value', + recommended: 'recommended', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + mismatchedCase: 'The case statement does not have a shared enum type with the switch predicate.', + mismatchedCondition: 'The two values in this comparison do not have a shared enum type.', + replaceValueWithEnum: 'Replace with an enum value comparison.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const parserServices = (0, util_1.getParserServices)(context); + const typeChecker = parserServices.program.getTypeChecker(); + function isMismatchedComparison(leftType, rightType) { + // Allow comparisons that don't have anything to do with enums: + // + // ```ts + // 1 === 2; + // ``` + const leftEnumTypes = (0, shared_1.getEnumTypes)(typeChecker, leftType); + const rightEnumTypes = new Set((0, shared_1.getEnumTypes)(typeChecker, rightType)); + if (leftEnumTypes.length === 0 && rightEnumTypes.size === 0) { + return false; + } + // Allow comparisons that share an enum type: + // + // ```ts + // Fruit.Apple === Fruit.Banana; + // ``` + for (const leftEnumType of leftEnumTypes) { + if (rightEnumTypes.has(leftEnumType)) { + return false; + } + } + // We need to split the type into the union type parts in order to find + // valid enum comparisons like: + // + // ```ts + // declare const something: Fruit | Vegetable; + // something === Fruit.Apple; + // ``` + const leftTypeParts = tsutils.unionConstituents(leftType); + const rightTypeParts = tsutils.unionConstituents(rightType); + // If a type exists in both sides, we consider this comparison safe: + // + // ```ts + // declare const fruit: Fruit.Apple | 0; + // fruit === 0; + // ``` + for (const leftTypePart of leftTypeParts) { + if (rightTypeParts.includes(leftTypePart)) { + return false; + } + } + return (typeViolates(leftTypeParts, rightType) || + typeViolates(rightTypeParts, leftType)); + } + return { + 'BinaryExpression[operator=/^[<>!=]?={0,2}$/]'(node) { + const leftType = parserServices.getTypeAtLocation(node.left); + const rightType = parserServices.getTypeAtLocation(node.right); + if (isMismatchedComparison(leftType, rightType)) { + context.report({ + node, + messageId: 'mismatchedCondition', + suggest: [ + { + messageId: 'replaceValueWithEnum', + fix(fixer) { + // Replace the right side with an enum key if possible: + // + // ```ts + // Fruit.Apple === 'apple'; // Fruit.Apple === Fruit.Apple + // ``` + const leftEnumKey = (0, shared_1.getEnumKeyForLiteral)((0, shared_1.getEnumLiterals)(leftType), (0, util_1.getStaticValue)(node.right)?.value); + if (leftEnumKey) { + return fixer.replaceText(node.right, leftEnumKey); + } + // Replace the left side with an enum key if possible: + // + // ```ts + // declare const fruit: Fruit; + // 'apple' === Fruit.Apple; // Fruit.Apple === Fruit.Apple + // ``` + const rightEnumKey = (0, shared_1.getEnumKeyForLiteral)((0, shared_1.getEnumLiterals)(rightType), (0, util_1.getStaticValue)(node.left)?.value); + if (rightEnumKey) { + return fixer.replaceText(node.left, rightEnumKey); + } + return null; + }, + }, + ], + }); + } + }, + SwitchCase(node) { + // Ignore `default` cases. + if (node.test == null) { + return; + } + const { parent } = node; + const leftType = parserServices.getTypeAtLocation(parent.discriminant); + const rightType = parserServices.getTypeAtLocation(node.test); + if (isMismatchedComparison(leftType, rightType)) { + context.report({ + node, + messageId: 'mismatchedCase', + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-function-type.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-function-type.d.ts new file mode 100644 index 00000000..8c636f58 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-function-type.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"bannedFunctionType", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unsafe-function-type.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-function-type.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-function-type.d.ts.map new file mode 100644 index 00000000..383a6554 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-function-type.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-function-type.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-function-type.ts"],"names":[],"mappings":";AAMA,wBA2CG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-function-type.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-function-type.js new file mode 100644 index 00000000..c749232c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-function-type.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unsafe-function-type', + meta: { + type: 'problem', + docs: { + description: 'Disallow using the unsafe built-in Function type', + recommended: 'recommended', + }, + messages: { + bannedFunctionType: [ + 'The `Function` type accepts any function-like value.', + 'Prefer explicitly defining any function parameters and return type.', + ].join('\n'), + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function checkBannedTypes(node) { + if (node.type === utils_1.AST_NODE_TYPES.Identifier && + node.name === 'Function' && + (0, util_1.isReferenceToGlobalFunction)('Function', node, context.sourceCode)) { + context.report({ + node, + messageId: 'bannedFunctionType', + }); + } + } + return { + TSClassImplements(node) { + checkBannedTypes(node.expression); + }, + TSInterfaceHeritage(node) { + checkBannedTypes(node.expression); + }, + TSTypeReference(node) { + checkBannedTypes(node.typeName); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-member-access.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-member-access.d.ts new file mode 100644 index 00000000..e0025cec --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-member-access.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeComputedMemberAccess" | "unsafeMemberExpression" | "unsafeThisMemberExpression", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unsafe-member-access.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-member-access.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-member-access.d.ts.map new file mode 100644 index 00000000..08d7d67d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-member-access.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-member-access.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-member-access.ts"],"names":[],"mappings":";AAwBA,wBAwHG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-member-access.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-member-access.js new file mode 100644 index 00000000..3d9c6194 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-member-access.js @@ -0,0 +1,141 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +var State; +(function (State) { + State[State["Unsafe"] = 1] = "Unsafe"; + State[State["Safe"] = 2] = "Safe"; +})(State || (State = {})); +function createDataType(type) { + const isErrorType = tsutils.isIntrinsicErrorType(type); + return isErrorType ? '`error` typed' : '`any`'; +} +exports.default = (0, util_1.createRule)({ + name: 'no-unsafe-member-access', + meta: { + type: 'problem', + docs: { + description: 'Disallow member access on a value with type `any`', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + unsafeComputedMemberAccess: 'Computed name {{property}} resolves to an {{type}} value.', + unsafeMemberExpression: 'Unsafe member access {{property}} on an {{type}} value.', + unsafeThisMemberExpression: [ + 'Unsafe member access {{property}} on an `any` value. `this` is typed as `any`.', + 'You can try to fix this by turning on the `noImplicitThis` compiler option, or adding a `this` parameter to the function.', + ].join('\n'), + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const compilerOptions = services.program.getCompilerOptions(); + const isNoImplicitThis = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'noImplicitThis'); + const stateCache = new Map(); + function checkMemberExpression(node) { + const cachedState = stateCache.get(node); + if (cachedState) { + return cachedState; + } + if (node.object.type === utils_1.AST_NODE_TYPES.MemberExpression) { + const objectState = checkMemberExpression(node.object); + if (objectState === State.Unsafe) { + // if the object is unsafe, we know this will be unsafe as well + // we don't need to report, as we have already reported on the inner member expr + stateCache.set(node, objectState); + return objectState; + } + } + const type = services.getTypeAtLocation(node.object); + const state = (0, util_1.isTypeAnyType)(type) ? State.Unsafe : State.Safe; + stateCache.set(node, state); + if (state === State.Unsafe) { + const propertyName = context.sourceCode.getText(node.property); + let messageId = 'unsafeMemberExpression'; + if (!isNoImplicitThis) { + // `this.foo` or `this.foo[bar]` + const thisExpression = (0, util_1.getThisExpression)(node); + if (thisExpression && + (0, util_1.isTypeAnyType)((0, util_1.getConstrainedTypeAtLocation)(services, thisExpression))) { + messageId = 'unsafeThisMemberExpression'; + } + } + context.report({ + node: node.property, + messageId, + data: { + type: createDataType(type), + property: node.computed ? `[${propertyName}]` : `.${propertyName}`, + }, + }); + } + return state; + } + return { + // ignore MemberExpressions with ancestors of type `TSClassImplements` or `TSInterfaceHeritage` + 'MemberExpression:not(TSClassImplements MemberExpression, TSInterfaceHeritage MemberExpression)': checkMemberExpression, + 'MemberExpression[computed = true] > *.property'(node) { + if ( + // x[1] + node.type === utils_1.AST_NODE_TYPES.Literal || + // x[1++] x[++x] etc + // FUN FACT - **all** update expressions return type number, regardless of the argument's type, + // because JS engines return NaN if there the argument is not a number. + node.type === utils_1.AST_NODE_TYPES.UpdateExpression) { + // perf optimizations - literals can obviously never be `any` + return; + } + const type = services.getTypeAtLocation(node); + if ((0, util_1.isTypeAnyType)(type)) { + const propertyName = context.sourceCode.getText(node); + context.report({ + node, + messageId: 'unsafeComputedMemberAccess', + data: { + type: createDataType(type), + property: `[${propertyName}]`, + }, + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-return.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-return.d.ts new file mode 100644 index 00000000..2fc225aa --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-return.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeReturn" | "unsafeReturnAssignment" | "unsafeReturnThis", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unsafe-return.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-return.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-return.d.ts.map new file mode 100644 index 00000000..22741674 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-return.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-return.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-return.ts"],"names":[],"mappings":";AAqBA,wBAsMG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-return.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-return.js new file mode 100644 index 00000000..e466b945 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-return.js @@ -0,0 +1,183 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const getParentFunctionNode_1 = require("../util/getParentFunctionNode"); +exports.default = (0, util_1.createRule)({ + name: 'no-unsafe-return', + meta: { + type: 'problem', + docs: { + description: 'Disallow returning a value with type `any` from a function', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + unsafeReturn: 'Unsafe return of a value of type {{type}}.', + unsafeReturnAssignment: 'Unsafe return of type `{{sender}}` from function with return type `{{receiver}}`.', + unsafeReturnThis: [ + 'Unsafe return of a value of type `{{type}}`. `this` is typed as `any`.', + 'You can try to fix this by turning on the `noImplicitThis` compiler option, or adding a `this` parameter to the function.', + ].join('\n'), + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const compilerOptions = services.program.getCompilerOptions(); + const isNoImplicitThis = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'noImplicitThis'); + function checkReturn(returnNode, reportingNode = returnNode) { + const tsNode = services.esTreeNodeToTSNodeMap.get(returnNode); + const type = checker.getTypeAtLocation(tsNode); + const anyType = (0, util_1.discriminateAnyType)(type, checker, services.program, tsNode); + const functionNode = (0, getParentFunctionNode_1.getParentFunctionNode)(returnNode); + /* istanbul ignore if */ if (!functionNode) { + return; + } + // function has an explicit return type, so ensure it's a safe return + const returnNodeType = (0, util_1.getConstrainedTypeAtLocation)(services, returnNode); + const functionTSNode = services.esTreeNodeToTSNodeMap.get(functionNode); + // function expressions will not have their return type modified based on receiver typing + // so we have to use the contextual typing in these cases, i.e. + // const foo1: () => Set = () => new Set(); + // the return type of the arrow function is Set even though the variable is typed as Set + let functionType = ts.isFunctionExpression(functionTSNode) || + ts.isArrowFunction(functionTSNode) + ? (0, util_1.getContextualType)(checker, functionTSNode) + : services.getTypeAtLocation(functionNode); + functionType ??= services.getTypeAtLocation(functionNode); + const callSignatures = tsutils.getCallSignaturesOfType(functionType); + // If there is an explicit type annotation *and* that type matches the actual + // function return type, we shouldn't complain (it's intentional, even if unsafe) + if (functionTSNode.type) { + for (const signature of callSignatures) { + const signatureReturnType = signature.getReturnType(); + if (returnNodeType === signatureReturnType || + (0, util_1.isTypeFlagSet)(signatureReturnType, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { + return; + } + if (functionNode.async) { + const awaitedSignatureReturnType = checker.getAwaitedType(signatureReturnType); + const awaitedReturnNodeType = checker.getAwaitedType(returnNodeType); + if (awaitedReturnNodeType === awaitedSignatureReturnType || + (awaitedSignatureReturnType && + (0, util_1.isTypeFlagSet)(awaitedSignatureReturnType, ts.TypeFlags.Any | ts.TypeFlags.Unknown))) { + return; + } + } + } + } + if (anyType !== util_1.AnyType.Safe) { + // Allow cases when the declared return type of the function is either unknown or unknown[] + // and the function is returning any or any[]. + for (const signature of callSignatures) { + const functionReturnType = signature.getReturnType(); + if (anyType === util_1.AnyType.Any && + (0, util_1.isTypeUnknownType)(functionReturnType)) { + return; + } + if (anyType === util_1.AnyType.AnyArray && + (0, util_1.isTypeUnknownArrayType)(functionReturnType, checker)) { + return; + } + const awaitedType = checker.getAwaitedType(functionReturnType); + if (awaitedType && + anyType === util_1.AnyType.PromiseAny && + (0, util_1.isTypeUnknownType)(awaitedType)) { + return; + } + } + if (anyType === util_1.AnyType.PromiseAny && !functionNode.async) { + return; + } + let messageId = 'unsafeReturn'; + const isErrorType = tsutils.isIntrinsicErrorType(returnNodeType); + if (!isNoImplicitThis) { + // `return this` + const thisExpression = (0, util_1.getThisExpression)(returnNode); + if (thisExpression && + (0, util_1.isTypeAnyType)((0, util_1.getConstrainedTypeAtLocation)(services, thisExpression))) { + messageId = 'unsafeReturnThis'; + } + } + // If the function return type was not unknown/unknown[], mark usage as unsafeReturn. + return context.report({ + node: reportingNode, + messageId, + data: { + type: isErrorType + ? 'error' + : anyType === util_1.AnyType.Any + ? '`any`' + : anyType === util_1.AnyType.PromiseAny + ? '`Promise`' + : '`any[]`', + }, + }); + } + const signature = functionType.getCallSignatures().at(0); + if (signature) { + const functionReturnType = signature.getReturnType(); + const result = (0, util_1.isUnsafeAssignment)(returnNodeType, functionReturnType, checker, returnNode); + if (!result) { + return; + } + const { receiver, sender } = result; + return context.report({ + node: reportingNode, + messageId: 'unsafeReturnAssignment', + data: { + receiver: checker.typeToString(receiver), + sender: checker.typeToString(sender), + }, + }); + } + } + return { + 'ArrowFunctionExpression > :not(BlockStatement).body': checkReturn, + ReturnStatement(node) { + const argument = node.argument; + if (!argument) { + return; + } + checkReturn(argument, node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-type-assertion.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-type-assertion.d.ts new file mode 100644 index 00000000..5b80769d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-type-assertion.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unsafeOfAnyTypeAssertion" | "unsafeToAnyTypeAssertion" | "unsafeToUnconstrainedTypeAssertion" | "unsafeTypeAssertion" | "unsafeTypeAssertionAssignableToConstraint", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unsafe-type-assertion.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-type-assertion.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-type-assertion.d.ts.map new file mode 100644 index 00000000..c4bf50ac --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-type-assertion.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-type-assertion.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-type-assertion.ts"],"names":[],"mappings":";AAaA,wBAqKG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-type-assertion.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-type-assertion.js new file mode 100644 index 00000000..9e3a2c8f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-type-assertion.js @@ -0,0 +1,158 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-unsafe-type-assertion', + meta: { + type: 'problem', + docs: { + description: 'Disallow type assertions that narrow a type', + requiresTypeChecking: true, + }, + messages: { + unsafeOfAnyTypeAssertion: 'Unsafe assertion from {{type}} detected: consider using type guards or a safer assertion.', + unsafeToAnyTypeAssertion: 'Unsafe assertion to {{type}} detected: consider using a more specific type to ensure safety.', + unsafeToUnconstrainedTypeAssertion: "Unsafe type assertion: '{{type}}' could be instantiated with an arbitrary type which could be unrelated to the original type.", + unsafeTypeAssertion: "Unsafe type assertion: type '{{type}}' is more narrow than the original type.", + unsafeTypeAssertionAssignableToConstraint: "Unsafe type assertion: the original type is assignable to the constraint of type '{{type}}', but '{{type}}' could be instantiated with a different subtype of its constraint.", + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function getAnyTypeName(type) { + return tsutils.isIntrinsicErrorType(type) ? 'error typed' : '`any`'; + } + function isObjectLiteralType(type) { + return (tsutils.isObjectType(type) && + tsutils.isObjectFlagSet(type, ts.ObjectFlags.ObjectLiteral)); + } + function checkExpression(node) { + const expressionType = services.getTypeAtLocation(node.expression); + const assertedType = services.getTypeAtLocation(node.typeAnnotation); + if (expressionType === assertedType) { + return; + } + // handle cases when asserting unknown ==> any. + if ((0, util_1.isTypeAnyType)(assertedType) && (0, util_1.isTypeUnknownType)(expressionType)) { + context.report({ + node, + messageId: 'unsafeToAnyTypeAssertion', + data: { + type: '`any`', + }, + }); + return; + } + const unsafeExpressionAny = (0, util_1.isUnsafeAssignment)(expressionType, assertedType, checker, node.expression); + if (unsafeExpressionAny) { + context.report({ + node, + messageId: 'unsafeOfAnyTypeAssertion', + data: { + type: getAnyTypeName(unsafeExpressionAny.sender), + }, + }); + return; + } + const unsafeAssertedAny = (0, util_1.isUnsafeAssignment)(assertedType, expressionType, checker, node.typeAnnotation); + if (unsafeAssertedAny) { + context.report({ + node, + messageId: 'unsafeToAnyTypeAssertion', + data: { + type: getAnyTypeName(unsafeAssertedAny.sender), + }, + }); + return; + } + // Use the widened type in case of an object literal so `isTypeAssignableTo()` + // won't fail on excess property check. + const expressionWidenedType = isObjectLiteralType(expressionType) + ? checker.getWidenedType(expressionType) + : expressionType; + const isAssertionSafe = checker.isTypeAssignableTo(expressionWidenedType, assertedType); + if (isAssertionSafe) { + return; + } + // Produce a more specific error message when targeting a type parameter + if (tsutils.isTypeParameter(assertedType)) { + const assertedTypeConstraint = checker.getBaseConstraintOfType(assertedType); + if (!assertedTypeConstraint) { + // asserting to an unconstrained type parameter is unsafe + context.report({ + node, + messageId: 'unsafeToUnconstrainedTypeAssertion', + data: { + type: checker.typeToString(assertedType), + }, + }); + return; + } + // special case message if the original type is assignable to the + // constraint of the target type parameter + const isAssignableToConstraint = checker.isTypeAssignableTo(expressionWidenedType, assertedTypeConstraint); + if (isAssignableToConstraint) { + context.report({ + node, + messageId: 'unsafeTypeAssertionAssignableToConstraint', + data: { + type: checker.typeToString(assertedType), + }, + }); + return; + } + } + // General error message + context.report({ + node, + messageId: 'unsafeTypeAssertion', + data: { + type: checker.typeToString(assertedType), + }, + }); + } + return { + 'TSAsExpression, TSTypeAssertion'(node) { + checkExpression(node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-unary-minus.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-unary-minus.d.ts new file mode 100644 index 00000000..cd8d540f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-unary-minus.d.ts @@ -0,0 +1,5 @@ +export type Options = []; +export type MessageIds = 'unaryMinus'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unaryMinus", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unsafe-unary-minus.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-unary-minus.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-unary-minus.d.ts.map new file mode 100644 index 00000000..1c60cb52 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-unary-minus.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unsafe-unary-minus.d.ts","sourceRoot":"","sources":["../../src/rules/no-unsafe-unary-minus.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,OAAO,GAAG,EAAE,CAAC;AACzB,MAAM,MAAM,UAAU,GAAG,YAAY,CAAC;;AAEtC,wBAmDG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-unary-minus.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-unary-minus.js new file mode 100644 index 00000000..749f4b01 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unsafe-unary-minus.js @@ -0,0 +1,78 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util = __importStar(require("../util")); +exports.default = util.createRule({ + name: 'no-unsafe-unary-minus', + meta: { + type: 'problem', + docs: { + description: 'Require unary negation to take a number', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + unaryMinus: 'Argument of unary negation should be assignable to number | bigint but is {{type}} instead.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + return { + UnaryExpression(node) { + if (node.operator !== '-') { + return; + } + const services = util.getParserServices(context); + const argType = util.getConstrainedTypeAtLocation(services, node.argument); + const checker = services.program.getTypeChecker(); + if (tsutils + .unionConstituents(argType) + .some(type => !tsutils.isTypeFlagSet(type, ts.TypeFlags.Any | + ts.TypeFlags.Never | + ts.TypeFlags.BigIntLike | + ts.TypeFlags.NumberLike))) { + context.report({ + node, + messageId: 'unaryMinus', + data: { type: checker.typeToString(argType) }, + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-expressions.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-expressions.d.ts new file mode 100644 index 00000000..480c0752 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-expressions.d.ts @@ -0,0 +1,18 @@ +import { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"expected", [{ + allowShortCircuit?: boolean; + allowTaggedTemplates?: boolean; + allowTernary?: boolean; +}], unknown, { + ExpressionStatement(node: TSESTree.ExpressionStatement): void; +}>; +export type MessageIds = InferMessageIdsTypeFromRule; +export type Options = InferOptionsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"expected", [{ + allowShortCircuit?: boolean; + allowTaggedTemplates?: boolean; + allowTernary?: boolean; +}], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-unused-expressions.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-expressions.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-expressions.d.ts.map new file mode 100644 index 00000000..5a4fa673 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-expressions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unused-expressions.d.ts","sourceRoot":"","sources":["../../src/rules/no-unused-expressions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEpE,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;;;;;8BA2EwrO,SAAU,mBAAmB;EA3ExqO,CAAC;AAE5D,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;AACtE,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;;;;;;AAUhE,wBA6DG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-expressions.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-expressions.js new file mode 100644 index 00000000..c8118c51 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-expressions.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-unused-expressions'); +const defaultOptions = [ + { + allowShortCircuit: false, + allowTaggedTemplates: false, + allowTernary: false, + }, +]; +exports.default = (0, util_1.createRule)({ + name: 'no-unused-expressions', + meta: { + type: 'suggestion', + defaultOptions, + docs: { + description: 'Disallow unused expressions', + extendsBaseRule: true, + recommended: 'recommended', + }, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: baseRule.meta.schema, + }, + defaultOptions, + create(context, [{ allowShortCircuit = false, allowTernary = false }]) { + const rules = baseRule.create(context); + function isValidExpression(node) { + if (allowShortCircuit && node.type === utils_1.AST_NODE_TYPES.LogicalExpression) { + return isValidExpression(node.right); + } + if (allowTernary && node.type === utils_1.AST_NODE_TYPES.ConditionalExpression) { + return (isValidExpression(node.alternate) && + isValidExpression(node.consequent)); + } + return ((node.type === utils_1.AST_NODE_TYPES.ChainExpression && + node.expression.type === utils_1.AST_NODE_TYPES.CallExpression) || + node.type === utils_1.AST_NODE_TYPES.ImportExpression); + } + return { + ExpressionStatement(node) { + if (node.directive || isValidExpression(node.expression)) { + return; + } + const expressionType = node.expression.type; + if (expressionType === + utils_1.TSESTree.AST_NODE_TYPES.TSInstantiationExpression || + expressionType === utils_1.TSESTree.AST_NODE_TYPES.TSAsExpression || + expressionType === utils_1.TSESTree.AST_NODE_TYPES.TSNonNullExpression || + expressionType === utils_1.TSESTree.AST_NODE_TYPES.TSTypeAssertion) { + rules.ExpressionStatement({ + ...node, + expression: node.expression.expression, + }); + return; + } + rules.ExpressionStatement(node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-vars.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-vars.d.ts new file mode 100644 index 00000000..d00939c4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-vars.d.ts @@ -0,0 +1,19 @@ +import { TSESLint } from '@typescript-eslint/utils'; +export type MessageIds = 'unusedVar' | 'usedIgnoredVar' | 'usedOnlyAsType'; +export type Options = [ + 'all' | 'local' | { + args?: 'after-used' | 'all' | 'none'; + argsIgnorePattern?: string; + caughtErrors?: 'all' | 'none'; + caughtErrorsIgnorePattern?: string; + destructuredArrayIgnorePattern?: string; + ignoreClassWithStaticInitBlock?: boolean; + ignoreRestSiblings?: boolean; + reportUsedIgnorePattern?: boolean; + vars?: 'all' | 'local'; + varsIgnorePattern?: string; + } +]; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=no-unused-vars.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-vars.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-vars.d.ts.map new file mode 100644 index 00000000..4783a260 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-vars.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-unused-vars.d.ts","sourceRoot":"","sources":["../../src/rules/no-unused-vars.ts"],"names":[],"mappings":"AAUA,OAAO,EAAkB,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAepE,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG,gBAAgB,GAAG,gBAAgB,CAAC;AAC3E,MAAM,MAAM,OAAO,GAAG;IAClB,KAAK,GACL,OAAO,GACP;QACE,IAAI,CAAC,EAAE,YAAY,GAAG,KAAK,GAAG,MAAM,CAAC;QACrC,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,YAAY,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;QAC9B,yBAAyB,CAAC,EAAE,MAAM,CAAC;QACnC,8BAA8B,CAAC,EAAE,MAAM,CAAC;QACxC,8BAA8B,CAAC,EAAE,OAAO,CAAC;QACzC,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,uBAAuB,CAAC,EAAE,OAAO,CAAC;QAClC,IAAI,CAAC,EAAE,KAAK,GAAG,OAAO,CAAC;QACvB,iBAAiB,CAAC,EAAE,MAAM,CAAC;KAC5B;CACJ,CAAC;;AA0BF,wBAuuBG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-vars.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-vars.js new file mode 100644 index 00000000..5de48883 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-unused-vars.js @@ -0,0 +1,668 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const referenceContainsTypeQuery_1 = require("../util/referenceContainsTypeQuery"); +exports.default = (0, util_1.createRule)({ + name: 'no-unused-vars', + meta: { + type: 'problem', + docs: { + description: 'Disallow unused variables', + extendsBaseRule: true, + recommended: 'recommended', + }, + messages: { + unusedVar: "'{{varName}}' is {{action}} but never used{{additional}}.", + usedIgnoredVar: "'{{varName}}' is marked as ignored but is used{{additional}}.", + usedOnlyAsType: "'{{varName}}' is {{action}} but only used as a type{{additional}}.", + }, + schema: [ + { + oneOf: [ + { + type: 'string', + enum: ['all', 'local'], + }, + { + type: 'object', + additionalProperties: false, + properties: { + args: { + type: 'string', + description: 'Whether to check all, some, or no arguments.', + enum: ['all', 'after-used', 'none'], + }, + argsIgnorePattern: { + type: 'string', + description: 'Regular expressions of argument names to not check for usage.', + }, + caughtErrors: { + type: 'string', + description: 'Whether to check catch block arguments.', + enum: ['all', 'none'], + }, + caughtErrorsIgnorePattern: { + type: 'string', + description: 'Regular expressions of catch block argument names to not check for usage.', + }, + destructuredArrayIgnorePattern: { + type: 'string', + description: 'Regular expressions of destructured array variable names to not check for usage.', + }, + ignoreClassWithStaticInitBlock: { + type: 'boolean', + description: 'Whether to ignore classes with at least one static initialization block.', + }, + ignoreRestSiblings: { + type: 'boolean', + description: 'Whether to ignore sibling properties in `...` destructurings.', + }, + reportUsedIgnorePattern: { + type: 'boolean', + description: 'Whether to report variables that match any of the valid ignore pattern options if they have been used.', + }, + vars: { + type: 'string', + description: 'Whether to check all variables or only locally-declared variables.', + enum: ['all', 'local'], + }, + varsIgnorePattern: { + type: 'string', + description: 'Regular expressions of variable names to not check for usage.', + }, + }, + }, + ], + }, + ], + }, + defaultOptions: [{}], + create(context, [firstOption]) { + const MODULE_DECL_CACHE = new Map(); + const options = (() => { + const options = { + args: 'after-used', + caughtErrors: 'all', + ignoreClassWithStaticInitBlock: false, + ignoreRestSiblings: false, + reportUsedIgnorePattern: false, + vars: 'all', + }; + if (typeof firstOption === 'string') { + options.vars = firstOption; + } + else { + options.vars = firstOption.vars ?? options.vars; + options.args = firstOption.args ?? options.args; + options.ignoreRestSiblings = + firstOption.ignoreRestSiblings ?? options.ignoreRestSiblings; + options.caughtErrors = firstOption.caughtErrors ?? options.caughtErrors; + options.ignoreClassWithStaticInitBlock = + firstOption.ignoreClassWithStaticInitBlock ?? + options.ignoreClassWithStaticInitBlock; + options.reportUsedIgnorePattern = + firstOption.reportUsedIgnorePattern ?? + options.reportUsedIgnorePattern; + if (firstOption.varsIgnorePattern) { + options.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern, 'u'); + } + if (firstOption.argsIgnorePattern) { + options.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern, 'u'); + } + if (firstOption.caughtErrorsIgnorePattern) { + options.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern, 'u'); + } + if (firstOption.destructuredArrayIgnorePattern) { + options.destructuredArrayIgnorePattern = new RegExp(firstOption.destructuredArrayIgnorePattern, 'u'); + } + } + return options; + })(); + /** + * Determines what variable type a def is. + * @param def the declaration to check + * @returns a simple name for the types of variables that this rule supports + */ + function defToVariableType(def) { + /* + * This `destructuredArrayIgnorePattern` error report works differently from the catch + * clause and parameter error reports. _Both_ the `varsIgnorePattern` and the + * `destructuredArrayIgnorePattern` will be checked for array destructuring. However, + * for the purposes of the report, the currently defined behavior is to only inform the + * user of the `destructuredArrayIgnorePattern` if it's present (regardless of the fact + * that the `varsIgnorePattern` would also apply). If it's not present, the user will be + * informed of the `varsIgnorePattern`, assuming that's present. + */ + if (options.destructuredArrayIgnorePattern && + def.name.parent.type === utils_1.AST_NODE_TYPES.ArrayPattern) { + return 'array-destructure'; + } + switch (def.type) { + case scope_manager_1.DefinitionType.CatchClause: + return 'catch-clause'; + case scope_manager_1.DefinitionType.Parameter: + return 'parameter'; + default: + return 'variable'; + } + } + /** + * Gets a given variable's description and configured ignore pattern + * based on the provided variableType + * @param variableType a simple name for the types of variables that this rule supports + * @returns the given variable's description and + * ignore pattern + */ + function getVariableDescription(variableType) { + switch (variableType) { + case 'array-destructure': + return { + pattern: options.destructuredArrayIgnorePattern?.toString(), + variableDescription: 'elements of array destructuring', + }; + case 'catch-clause': + return { + pattern: options.caughtErrorsIgnorePattern?.toString(), + variableDescription: 'caught errors', + }; + case 'parameter': + return { + pattern: options.argsIgnorePattern?.toString(), + variableDescription: 'args', + }; + case 'variable': + return { + pattern: options.varsIgnorePattern?.toString(), + variableDescription: 'vars', + }; + } + } + /** + * Generates the message data about the variable being defined and unused, + * including the ignore pattern if configured. + * @param unusedVar eslint-scope variable object. + * @returns The message data to be used with this unused variable. + */ + function getDefinedMessageData(unusedVar) { + const def = unusedVar.defs.at(0); + let additionalMessageData = ''; + if (def) { + const { pattern, variableDescription } = getVariableDescription(defToVariableType(def)); + if (pattern && variableDescription) { + additionalMessageData = `. Allowed unused ${variableDescription} must match ${pattern}`; + } + } + return { + action: 'defined', + additional: additionalMessageData, + varName: unusedVar.name, + }; + } + /** + * Generate the warning message about the variable being + * assigned and unused, including the ignore pattern if configured. + * @param unusedVar eslint-scope variable object. + * @returns The message data to be used with this unused variable. + */ + function getAssignedMessageData(unusedVar) { + const def = unusedVar.defs.at(0); + let additionalMessageData = ''; + if (def) { + const { pattern, variableDescription } = getVariableDescription(defToVariableType(def)); + if (pattern && variableDescription) { + additionalMessageData = `. Allowed unused ${variableDescription} must match ${pattern}`; + } + } + return { + action: 'assigned a value', + additional: additionalMessageData, + varName: unusedVar.name, + }; + } + /** + * Generate the warning message about a variable being used even though + * it is marked as being ignored. + * @param variable eslint-scope variable object + * @param variableType a simple name for the types of variables that this rule supports + * @returns The message data to be used with this used ignored variable. + */ + function getUsedIgnoredMessageData(variable, variableType) { + const { pattern, variableDescription } = getVariableDescription(variableType); + let additionalMessageData = ''; + if (pattern && variableDescription) { + additionalMessageData = `. Used ${variableDescription} must not match ${pattern}`; + } + return { + additional: additionalMessageData, + varName: variable.name, + }; + } + function collectUnusedVariables() { + /** + * Checks whether a node is a sibling of the rest property or not. + * @param node a node to check + * @returns True if the node is a sibling of the rest property, otherwise false. + */ + function hasRestSibling(node) { + return (node.type === utils_1.AST_NODE_TYPES.Property && + node.parent.type === utils_1.AST_NODE_TYPES.ObjectPattern && + node.parent.properties[node.parent.properties.length - 1].type === + utils_1.AST_NODE_TYPES.RestElement); + } + /** + * Determines if a variable has a sibling rest property + * @param variable eslint-scope variable object. + * @returns True if the variable is exported, false if not. + */ + function hasRestSpreadSibling(variable) { + if (options.ignoreRestSiblings) { + const hasRestSiblingDefinition = variable.defs.some(def => hasRestSibling(def.name.parent)); + const hasRestSiblingReference = variable.references.some(ref => hasRestSibling(ref.identifier.parent)); + return hasRestSiblingDefinition || hasRestSiblingReference; + } + return false; + } + /** + * Checks whether the given variable is after the last used parameter. + * @param variable The variable to check. + * @returns `true` if the variable is defined after the last used parameter. + */ + function isAfterLastUsedArg(variable) { + const def = variable.defs[0]; + const params = context.sourceCode.getDeclaredVariables(def.node); + const posteriorParams = params.slice(params.indexOf(variable) + 1); + // If any used parameters occur after this parameter, do not report. + return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed); + } + const analysisResults = (0, util_1.collectVariables)(context); + const variables = [ + ...Array.from(analysisResults.unusedVariables, variable => ({ + used: false, + variable, + })), + ...Array.from(analysisResults.usedVariables, variable => ({ + used: true, + variable, + })), + ]; + const unusedVariablesReturn = []; + for (const { used, variable } of variables) { + // explicit global variables don't have definitions. + if (variable.defs.length === 0) { + if (!used) { + unusedVariablesReturn.push(variable); + } + continue; + } + const def = variable.defs[0]; + if (variable.scope.type === utils_1.TSESLint.Scope.ScopeType.global && + options.vars === 'local') { + // skip variables in the global scope if configured to + continue; + } + const refUsedInArrayPatterns = variable.references.some(ref => ref.identifier.parent.type === utils_1.AST_NODE_TYPES.ArrayPattern); + // skip elements of array destructuring patterns + if ((def.name.parent.type === utils_1.AST_NODE_TYPES.ArrayPattern || + refUsedInArrayPatterns) && + def.name.type === utils_1.AST_NODE_TYPES.Identifier && + options.destructuredArrayIgnorePattern?.test(def.name.name)) { + if (options.reportUsedIgnorePattern && used) { + context.report({ + node: def.name, + messageId: 'usedIgnoredVar', + data: getUsedIgnoredMessageData(variable, 'array-destructure'), + }); + } + continue; + } + if (def.type === utils_1.TSESLint.Scope.DefinitionType.ClassName) { + const hasStaticBlock = def.node.body.body.some(node => node.type === utils_1.AST_NODE_TYPES.StaticBlock); + if (options.ignoreClassWithStaticInitBlock && hasStaticBlock) { + continue; + } + } + // skip catch variables + if (def.type === utils_1.TSESLint.Scope.DefinitionType.CatchClause) { + if (options.caughtErrors === 'none') { + continue; + } + // skip ignored parameters + if (def.name.type === utils_1.AST_NODE_TYPES.Identifier && + options.caughtErrorsIgnorePattern?.test(def.name.name)) { + if (options.reportUsedIgnorePattern && used) { + context.report({ + node: def.name, + messageId: 'usedIgnoredVar', + data: getUsedIgnoredMessageData(variable, 'catch-clause'), + }); + } + continue; + } + } + else if (def.type === utils_1.TSESLint.Scope.DefinitionType.Parameter) { + // if "args" option is "none", skip any parameter + if (options.args === 'none') { + continue; + } + // skip ignored parameters + if (def.name.type === utils_1.AST_NODE_TYPES.Identifier && + options.argsIgnorePattern?.test(def.name.name)) { + if (options.reportUsedIgnorePattern && used) { + context.report({ + node: def.name, + messageId: 'usedIgnoredVar', + data: getUsedIgnoredMessageData(variable, 'parameter'), + }); + } + continue; + } + // if "args" option is "after-used", skip used variables + if (options.args === 'after-used' && + (0, util_1.isFunction)(def.name.parent) && + !isAfterLastUsedArg(variable)) { + continue; + } + } + // skip ignored variables + else if (def.name.type === utils_1.AST_NODE_TYPES.Identifier && + options.varsIgnorePattern?.test(def.name.name)) { + if (options.reportUsedIgnorePattern && + used && + /* enum members are always marked as 'used' by `collectVariables`, but in reality they may be used or + unused. either way, don't complain about their naming. */ + def.type !== utils_1.TSESLint.Scope.DefinitionType.TSEnumMember) { + context.report({ + node: def.name, + messageId: 'usedIgnoredVar', + data: getUsedIgnoredMessageData(variable, 'variable'), + }); + } + continue; + } + if (hasRestSpreadSibling(variable)) { + continue; + } + // in case another rule has run and used the collectUnusedVariables, + // we want to ensure our selectors that marked variables as used are respected + if (variable.eslintUsed) { + continue; + } + if (!used) { + unusedVariablesReturn.push(variable); + } + } + return unusedVariablesReturn; + } + return { + // top-level declaration file handling + [ambientDeclarationSelector(utils_1.AST_NODE_TYPES.Program)](node) { + if (!(0, util_1.isDefinitionFile)(context.filename)) { + return; + } + const moduleDecl = (0, util_1.nullThrows)(node.parent, util_1.NullThrowsReasons.MissingParent); + if (checkForOverridingExportStatements(moduleDecl)) { + return; + } + markDeclarationChildAsUsed(node); + }, + // children of a namespace that is a child of a declared namespace are auto-exported + [ambientDeclarationSelector('TSModuleDeclaration[declare = true] > TSModuleBlock TSModuleDeclaration > TSModuleBlock')](node) { + const moduleDecl = (0, util_1.nullThrows)(node.parent.parent, util_1.NullThrowsReasons.MissingParent); + if (checkForOverridingExportStatements(moduleDecl)) { + return; + } + markDeclarationChildAsUsed(node); + }, + // declared namespace handling + [ambientDeclarationSelector('TSModuleDeclaration[declare = true] > TSModuleBlock')](node) { + const moduleDecl = (0, util_1.nullThrows)(node.parent.parent, util_1.NullThrowsReasons.MissingParent); + if (checkForOverridingExportStatements(moduleDecl)) { + return; + } + markDeclarationChildAsUsed(node); + }, + // namespace handling in definition files + [ambientDeclarationSelector('TSModuleDeclaration > TSModuleBlock')](node) { + if (!(0, util_1.isDefinitionFile)(context.filename)) { + return; + } + const moduleDecl = (0, util_1.nullThrows)(node.parent.parent, util_1.NullThrowsReasons.MissingParent); + if (checkForOverridingExportStatements(moduleDecl)) { + return; + } + markDeclarationChildAsUsed(node); + }, + // collect + 'Program:exit'(programNode) { + const unusedVars = collectUnusedVariables(); + for (const unusedVar of unusedVars) { + // Report the first declaration. + if (unusedVar.defs.length > 0) { + const usedOnlyAsType = unusedVar.references.some(ref => (0, referenceContainsTypeQuery_1.referenceContainsTypeQuery)(ref.identifier)); + const isImportUsedOnlyAsType = usedOnlyAsType && + unusedVar.defs.some(def => def.type === scope_manager_1.DefinitionType.ImportBinding); + if (isImportUsedOnlyAsType) { + continue; + } + const writeReferences = unusedVar.references.filter(ref => ref.isWrite() && + ref.from.variableScope === unusedVar.scope.variableScope); + const id = writeReferences.length + ? writeReferences[writeReferences.length - 1].identifier + : unusedVar.identifiers[0]; + const messageId = usedOnlyAsType ? 'usedOnlyAsType' : 'unusedVar'; + const { start } = id.loc; + const idLength = id.name.length; + const loc = { + start, + end: { + column: start.column + idLength, + line: start.line, + }, + }; + context.report({ + loc, + messageId, + data: unusedVar.references.some(ref => ref.isWrite()) + ? getAssignedMessageData(unusedVar) + : getDefinedMessageData(unusedVar), + }); + // If there are no regular declaration, report the first `/*globals*/` comment directive. + } + else if ('eslintExplicitGlobalComments' in unusedVar && + unusedVar.eslintExplicitGlobalComments) { + const directiveComment = unusedVar.eslintExplicitGlobalComments[0]; + context.report({ + loc: (0, util_1.getNameLocationInGlobalDirectiveComment)(context.sourceCode, directiveComment, unusedVar.name), + node: programNode, + messageId: 'unusedVar', + data: getDefinedMessageData(unusedVar), + }); + } + } + }, + }; + function checkForOverridingExportStatements(node) { + const cached = MODULE_DECL_CACHE.get(node); + if (cached != null) { + return cached; + } + const body = getStatementsOfNode(node); + if (hasOverridingExportStatement(body)) { + MODULE_DECL_CACHE.set(node, true); + return true; + } + MODULE_DECL_CACHE.set(node, false); + return false; + } + function ambientDeclarationSelector(parent) { + return [ + // Types are ambiently exported + `${parent} > :matches(${[ + utils_1.AST_NODE_TYPES.TSInterfaceDeclaration, + utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration, + ].join(', ')})`, + // Value things are ambiently exported if they are "declare"d + `${parent} > :matches(${[ + utils_1.AST_NODE_TYPES.ClassDeclaration, + utils_1.AST_NODE_TYPES.TSDeclareFunction, + utils_1.AST_NODE_TYPES.TSEnumDeclaration, + utils_1.AST_NODE_TYPES.TSModuleDeclaration, + utils_1.AST_NODE_TYPES.VariableDeclaration, + ].join(', ')})`, + ].join(', '); + } + function markDeclarationChildAsUsed(node) { + const identifiers = []; + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSInterfaceDeclaration: + case utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration: + case utils_1.AST_NODE_TYPES.ClassDeclaration: + case utils_1.AST_NODE_TYPES.FunctionDeclaration: + case utils_1.AST_NODE_TYPES.TSDeclareFunction: + case utils_1.AST_NODE_TYPES.TSEnumDeclaration: + case utils_1.AST_NODE_TYPES.TSModuleDeclaration: + if (node.id?.type === utils_1.AST_NODE_TYPES.Identifier) { + identifiers.push(node.id); + } + break; + case utils_1.AST_NODE_TYPES.VariableDeclaration: + for (const declaration of node.declarations) { + visitPattern(declaration, pattern => { + identifiers.push(pattern); + }); + } + break; + } + let scope = context.sourceCode.getScope(node); + const shouldUseUpperScope = [ + utils_1.AST_NODE_TYPES.TSDeclareFunction, + utils_1.AST_NODE_TYPES.TSModuleDeclaration, + ].includes(node.type); + if (scope.variableScope !== scope) { + scope = scope.variableScope; + } + else if (shouldUseUpperScope && scope.upper) { + scope = scope.upper; + } + for (const id of identifiers) { + const superVar = scope.set.get(id.name); + if (superVar) { + superVar.eslintUsed = true; + } + } + } + function visitPattern(node, cb) { + const visitor = new scope_manager_1.PatternVisitor({}, node, cb); + visitor.visit(node); + } + }, +}); +function hasOverridingExportStatement(body) { + for (const statement of body) { + if ((statement.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration && + statement.declaration == null) || + statement.type === utils_1.AST_NODE_TYPES.ExportAllDeclaration || + statement.type === utils_1.AST_NODE_TYPES.TSExportAssignment) { + return true; + } + if (statement.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration && + statement.declaration.type === utils_1.AST_NODE_TYPES.Identifier) { + return true; + } + } + return false; +} +function getStatementsOfNode(block) { + if (block.type === utils_1.AST_NODE_TYPES.Program) { + return block.body; + } + return block.body.body; +} +/* + +###### TODO ###### + +Edge cases that aren't currently handled due to laziness and them being super edgy edge cases + + +--- function params referenced in typeof type refs in the function declaration --- +--- NOTE - TS gets these cases wrong + +function _foo( + arg: number // arg should be unused +): typeof arg { + return 1 as any; +} + +function _bar( + arg: number, // arg should be unused + _arg2: typeof arg, +) {} + + +--- function names referenced in typeof type refs in the function declaration --- +--- NOTE - TS gets these cases right + +function foo( // foo should be unused +): typeof foo { + return 1 as any; +} + +function bar( // bar should be unused + _arg: typeof bar +) {} + + +--- if an interface is merged into a namespace --- +--- NOTE - TS gets these cases wrong + +namespace Test { + interface Foo { // Foo should be unused here + a: string; + } + export namespace Foo { + export type T = 'b'; + } +} +type T = Test.Foo; // Error: Namespace 'Test' has no exported member 'Foo'. + + +namespace Test { + export interface Foo { + a: string; + } + namespace Foo { // Foo should be unused here + export type T = 'b'; + } +} +type T = Test.Foo.T; // Error: Namespace 'Test' has no exported member 'Foo'. + +--- + +These cases are mishandled because the base rule assumes that each variable has one def, but type-value shadowing +creates a variable with two defs + +--- type-only or value-only references to type/value shadowed variables --- +--- NOTE - TS gets these cases wrong + +type T = 1; +const T = 2; // this T should be unused + +type U = T; // this U should be unused +const U = 3; + +const _V = U; + + +--- partially exported type/value shadowed variables --- +--- NOTE - TS gets these cases wrong + +export interface Foo {} +const Foo = 1; // this Foo should be unused + +interface Bar {} // this Bar should be unused +export const Bar = 1; + +*/ diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.d.ts new file mode 100644 index 00000000..7ef7fba3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.d.ts @@ -0,0 +1,15 @@ +import { TSESLint } from '@typescript-eslint/utils'; +export interface Config { + allowNamedExports?: boolean; + classes?: boolean; + enums?: boolean; + functions?: boolean; + ignoreTypeReferences?: boolean; + typedefs?: boolean; + variables?: boolean; +} +export type Options = ['nofunc' | Config]; +export type MessageIds = 'noUseBeforeDefine'; +declare const _default: TSESLint.RuleModule<"noUseBeforeDefine", Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-use-before-define.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.d.ts.map new file mode 100644 index 00000000..e146883f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-use-before-define.d.ts","sourceRoot":"","sources":["../../src/rules/no-use-before-define.ts"],"names":[],"mappings":"AAGA,OAAO,EAAkB,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AA0MpE,MAAM,WAAW,MAAM;IACrB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AACD,MAAM,MAAM,OAAO,GAAG,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAC;AAC1C,MAAM,MAAM,UAAU,GAAG,mBAAmB,CAAC;;AAE7C,wBA+KG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.js new file mode 100644 index 00000000..3c033093 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.js @@ -0,0 +1,302 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const referenceContainsTypeQuery_1 = require("../util/referenceContainsTypeQuery"); +const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/; +/** + * Parses a given value as options. + */ +function parseOptions(options) { + let functions = true; + let classes = true; + let enums = true; + let variables = true; + let typedefs = true; + let ignoreTypeReferences = true; + let allowNamedExports = false; + if (typeof options === 'string') { + functions = options !== 'nofunc'; + } + else if (typeof options === 'object' && options != null) { + functions = options.functions !== false; + classes = options.classes !== false; + enums = options.enums !== false; + variables = options.variables !== false; + typedefs = options.typedefs !== false; + ignoreTypeReferences = options.ignoreTypeReferences !== false; + allowNamedExports = options.allowNamedExports !== false; + } + return { + allowNamedExports, + classes, + enums, + functions, + ignoreTypeReferences, + typedefs, + variables, + }; +} +/** + * Checks whether or not a given variable is a function declaration. + */ +function isFunction(variable) { + return variable.defs[0].type === scope_manager_1.DefinitionType.FunctionName; +} +/** + * Checks whether or not a given variable is a type declaration. + */ +function isTypedef(variable) { + return variable.defs[0].type === scope_manager_1.DefinitionType.Type; +} +/** + * Checks whether or not a given variable is a enum declaration. + */ +function isOuterEnum(variable, reference) { + return (variable.defs[0].type === scope_manager_1.DefinitionType.TSEnumName && + variable.scope.variableScope !== reference.from.variableScope); +} +/** + * Checks whether or not a given variable is a class declaration in an upper function scope. + */ +function isOuterClass(variable, reference) { + return (variable.defs[0].type === scope_manager_1.DefinitionType.ClassName && + variable.scope.variableScope !== reference.from.variableScope); +} +/** + * Checks whether or not a given variable is a variable declaration in an upper function scope. + */ +function isOuterVariable(variable, reference) { + return (variable.defs[0].type === scope_manager_1.DefinitionType.Variable && + variable.scope.variableScope !== reference.from.variableScope); +} +/** + * Checks whether or not a given reference is a export reference. + */ +function isNamedExports(reference) { + const { identifier } = reference; + return (identifier.parent.type === utils_1.AST_NODE_TYPES.ExportSpecifier && + identifier.parent.local === identifier); +} +/** + * Checks whether or not a given reference is a type reference. + */ +function isTypeReference(reference) { + return (reference.isTypeReference || + (0, referenceContainsTypeQuery_1.referenceContainsTypeQuery)(reference.identifier)); +} +/** + * Checks whether or not a given location is inside of the range of a given node. + */ +function isInRange(node, location) { + return !!node && node.range[0] <= location && location <= node.range[1]; +} +/** + * Decorators are transpiled such that the decorator is placed after the class declaration + * So it is considered safe + */ +function isClassRefInClassDecorator(variable, reference) { + if (variable.defs[0].type !== scope_manager_1.DefinitionType.ClassName || + variable.defs[0].node.decorators.length === 0) { + return false; + } + for (const deco of variable.defs[0].node.decorators) { + if (reference.identifier.range[0] >= deco.range[0] && + reference.identifier.range[1] <= deco.range[1]) { + return true; + } + } + return false; +} +/** + * Checks whether or not a given reference is inside of the initializers of a given variable. + * + * @returns `true` in the following cases: + * - var a = a + * - var [a = a] = list + * - var {a = a} = obj + * - for (var a in a) {} + * - for (var a of a) {} + */ +function isInInitializer(variable, reference) { + if (variable.scope !== reference.from) { + return false; + } + let node = variable.identifiers[0].parent; + const location = reference.identifier.range[1]; + while (node) { + if (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator) { + if (isInRange(node.init, location)) { + return true; + } + if ((node.parent.parent.type === utils_1.AST_NODE_TYPES.ForInStatement || + node.parent.parent.type === utils_1.AST_NODE_TYPES.ForOfStatement) && + isInRange(node.parent.parent.right, location)) { + return true; + } + break; + } + else if (node.type === utils_1.AST_NODE_TYPES.AssignmentPattern) { + if (isInRange(node.right, location)) { + return true; + } + } + else if (SENTINEL_TYPE.test(node.type)) { + break; + } + node = node.parent; + } + return false; +} +exports.default = (0, util_1.createRule)({ + name: 'no-use-before-define', + meta: { + type: 'problem', + docs: { + description: 'Disallow the use of variables before they are defined', + extendsBaseRule: true, + }, + messages: { + noUseBeforeDefine: "'{{name}}' was used before it was defined.", + }, + schema: [ + { + oneOf: [ + { + type: 'string', + enum: ['nofunc'], + }, + { + type: 'object', + additionalProperties: false, + properties: { + allowNamedExports: { + type: 'boolean', + description: 'Whether to ignore named exports.', + }, + classes: { + type: 'boolean', + description: 'Whether to ignore references to class declarations.', + }, + enums: { + type: 'boolean', + description: 'Whether to check references to enums.', + }, + functions: { + type: 'boolean', + description: 'Whether to ignore references to function declarations.', + }, + ignoreTypeReferences: { + type: 'boolean', + description: 'Whether to ignore type references, such as in type annotations and assertions.', + }, + typedefs: { + type: 'boolean', + description: 'Whether to check references to types.', + }, + variables: { + type: 'boolean', + description: 'Whether to ignore references to variables.', + }, + }, + }, + ], + }, + ], + }, + defaultOptions: [ + { + allowNamedExports: false, + classes: true, + enums: true, + functions: true, + ignoreTypeReferences: true, + typedefs: true, + variables: true, + }, + ], + create(context, optionsWithDefault) { + const options = parseOptions(optionsWithDefault[0]); + /** + * Determines whether a given use-before-define case should be reported according to the options. + * @param variable The variable that gets used before being defined + * @param reference The reference to the variable + */ + function isForbidden(variable, reference) { + if (options.ignoreTypeReferences && isTypeReference(reference)) { + return false; + } + if (isFunction(variable)) { + return options.functions; + } + if (isOuterClass(variable, reference)) { + return options.classes; + } + if (isOuterVariable(variable, reference)) { + return options.variables; + } + if (isOuterEnum(variable, reference)) { + return options.enums; + } + if (isTypedef(variable)) { + return options.typedefs; + } + return true; + } + function isDefinedBeforeUse(variable, reference) { + return (variable.identifiers[0].range[1] <= reference.identifier.range[1] && + !(reference.isValueReference && isInInitializer(variable, reference))); + } + /** + * Finds and validates all variables in a given scope. + */ + function findVariablesInScope(scope) { + scope.references.forEach(reference => { + const variable = reference.resolved; + function report() { + context.report({ + node: reference.identifier, + messageId: 'noUseBeforeDefine', + data: { + name: reference.identifier.name, + }, + }); + } + // Skips when the reference is: + // - initializations. + // - referring to an undefined variable. + // - referring to a global environment variable (there're no identifiers). + // - located preceded by the variable (except in initializers). + // - allowed by options. + if (reference.init) { + return; + } + if (!options.allowNamedExports && isNamedExports(reference)) { + if (!variable || !isDefinedBeforeUse(variable, reference)) { + report(); + } + return; + } + if (!variable) { + return; + } + if (variable.identifiers.length === 0 || + isDefinedBeforeUse(variable, reference) || + !isForbidden(variable, reference) || + isClassRefInClassDecorator(variable, reference) || + reference.from.type === utils_1.TSESLint.Scope.ScopeType.functionType) { + return; + } + // Reports. + report(); + }); + scope.childScopes.forEach(findVariablesInScope); + } + return { + Program(node) { + findVariablesInScope(context.sourceCode.getScope(node)); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-constructor.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-constructor.d.ts new file mode 100644 index 00000000..d281074c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-constructor.d.ts @@ -0,0 +1,10 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noUselessConstructor" | "removeConstructor", [], unknown, { + MethodDefinition(node: TSESTree.MethodDefinition): void; +}>; +export type Options = InferOptionsTypeFromRule; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noUselessConstructor" | "removeConstructor", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-useless-constructor.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-constructor.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-constructor.d.ts.map new file mode 100644 index 00000000..3812148e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-constructor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-useless-constructor.d.ts","sourceRoot":"","sources":["../../src/rules/no-useless-constructor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;2BA+Dm+R,SAAU,gBAAgB;EA/D/8R,CAAC;AAE7D,MAAM,MAAM,OAAO,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAChE,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;AA8BtE,wBA6BG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-constructor.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-constructor.js new file mode 100644 index 00000000..6bdee67b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-constructor.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-useless-constructor'); +/** + * Check if method with accessibility is not useless + */ +function checkAccessibility(node) { + switch (node.accessibility) { + case 'protected': + case 'private': + return false; + case 'public': + if (node.parent.parent.superClass) { + return false; + } + break; + } + return true; +} +/** + * Check if method is not useless due to typescript parameter properties and decorators + */ +function checkParams(node) { + return !node.value.params.some(param => param.type === utils_1.AST_NODE_TYPES.TSParameterProperty || + param.decorators.length); +} +exports.default = (0, util_1.createRule)({ + name: 'no-useless-constructor', + meta: { + type: 'problem', + // defaultOptions, -- base rule does not use defaultOptions + docs: { + description: 'Disallow unnecessary constructors', + extendsBaseRule: true, + recommended: 'strict', + }, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema: baseRule.meta.schema, + }, + defaultOptions: [], + create(context) { + const rules = baseRule.create(context); + return { + MethodDefinition(node) { + if (node.value.type === utils_1.AST_NODE_TYPES.FunctionExpression && + checkAccessibility(node) && + checkParams(node)) { + rules.MethodDefinition(node); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-empty-export.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-empty-export.d.ts new file mode 100644 index 00000000..bd2c10ad --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-empty-export.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"uselessExport", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-useless-empty-export.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-empty-export.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-empty-export.d.ts.map new file mode 100644 index 00000000..962c9839 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-empty-export.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-useless-empty-export.d.ts","sourceRoot":"","sources":["../../src/rules/no-useless-empty-export.ts"],"names":[],"mappings":";AA0BA,wBAyDG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-empty-export.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-empty-export.js new file mode 100644 index 00000000..804dfa39 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-useless-empty-export.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +function isEmptyExport(node) { + return (node.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration && + node.specifiers.length === 0 && + !node.declaration); +} +const exportOrImportNodeTypes = new Set([ + utils_1.AST_NODE_TYPES.ExportAllDeclaration, + utils_1.AST_NODE_TYPES.ExportDefaultDeclaration, + utils_1.AST_NODE_TYPES.ExportNamedDeclaration, + utils_1.AST_NODE_TYPES.ExportSpecifier, + utils_1.AST_NODE_TYPES.ImportDeclaration, + utils_1.AST_NODE_TYPES.TSExportAssignment, + utils_1.AST_NODE_TYPES.TSImportEqualsDeclaration, +]); +exports.default = (0, util_1.createRule)({ + name: 'no-useless-empty-export', + meta: { + type: 'suggestion', + docs: { + description: "Disallow empty exports that don't change anything in a module file", + }, + fixable: 'code', + hasSuggestions: false, + messages: { + uselessExport: 'Empty export does nothing and can be removed.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + // In a definition file, export {} is necessary to make the module properly + // encapsulated, even when there are other exports + // https://github.com/typescript-eslint/typescript-eslint/issues/4975 + if ((0, util_1.isDefinitionFile)(context.filename)) { + return {}; + } + function checkNode(node) { + if (!Array.isArray(node.body)) { + return; + } + const emptyExports = []; + let foundOtherExport = false; + for (const statement of node.body) { + if (isEmptyExport(statement)) { + emptyExports.push(statement); + } + else if (exportOrImportNodeTypes.has(statement.type)) { + foundOtherExport = true; + } + } + if (foundOtherExport) { + for (const emptyExport of emptyExports) { + context.report({ + node: emptyExport, + messageId: 'uselessExport', + fix: fixer => fixer.remove(emptyExport), + }); + } + } + } + return { + Program: checkNode, + TSModuleDeclaration: checkNode, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-var-requires.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-var-requires.d.ts new file mode 100644 index 00000000..6ddfaa32 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-var-requires.d.ts @@ -0,0 +1,9 @@ +export type Options = [ + { + allow: string[]; + } +]; +export type MessageIds = 'noVarReqs'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"noVarReqs", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=no-var-requires.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-var-requires.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-var-requires.d.ts.map new file mode 100644 index 00000000..39ba18ca --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-var-requires.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-var-requires.d.ts","sourceRoot":"","sources":["../../src/rules/no-var-requires.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,KAAK,EAAE,MAAM,EAAE,CAAC;KACjB;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,WAAW,CAAC;;AAErC,wBA8FG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-var-requires.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-var-requires.js new file mode 100644 index 00000000..a6d79359 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-var-requires.js @@ -0,0 +1,83 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'no-var-requires', + meta: { + type: 'problem', + deprecated: { + deprecatedSince: '8.0.0', + replacedBy: [ + { + rule: { + name: '@typescript-eslint/no-require-imports', + url: 'https://typescript-eslint.io/rules/no-require-imports', + }, + }, + ], + url: 'https://github.com/typescript-eslint/typescript-eslint/pull/8334', + }, + docs: { + description: 'Disallow `require` statements except in import statements', + }, + messages: { + noVarReqs: 'Require statement not part of import statement.', + }, + replacedBy: ['@typescript-eslint/no-require-imports'], + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allow: { + type: 'array', + description: 'Patterns of import paths to allow requiring from.', + items: { type: 'string' }, + }, + }, + }, + ], + }, + defaultOptions: [{ allow: [] }], + create(context, options) { + const allowPatterns = options[0].allow.map(pattern => new RegExp(pattern, 'u')); + function isImportPathAllowed(importPath) { + return allowPatterns.some(pattern => importPath.match(pattern)); + } + function isStringOrTemplateLiteral(node) { + return ((node.type === utils_1.AST_NODE_TYPES.Literal && + typeof node.value === 'string') || + node.type === utils_1.AST_NODE_TYPES.TemplateLiteral); + } + return { + 'CallExpression[callee.name="require"]'(node) { + if (node.arguments[0] && isStringOrTemplateLiteral(node.arguments[0])) { + const argValue = (0, util_1.getStaticStringValue)(node.arguments[0]); + if (typeof argValue === 'string' && isImportPathAllowed(argValue)) { + return; + } + } + const parent = node.parent.type === utils_1.AST_NODE_TYPES.ChainExpression + ? node.parent.parent + : node.parent; + if ([ + utils_1.AST_NODE_TYPES.CallExpression, + utils_1.AST_NODE_TYPES.MemberExpression, + utils_1.AST_NODE_TYPES.NewExpression, + utils_1.AST_NODE_TYPES.TSAsExpression, + utils_1.AST_NODE_TYPES.TSTypeAssertion, + utils_1.AST_NODE_TYPES.VariableDeclarator, + ].includes(parent.type)) { + const variable = utils_1.ASTUtils.findVariable(context.sourceCode.getScope(node), 'require'); + if (!variable?.identifiers.length) { + context.report({ + node, + messageId: 'noVarReqs', + }); + } + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-wrapper-object-types.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-wrapper-object-types.d.ts new file mode 100644 index 00000000..9906e106 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-wrapper-object-types.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"bannedClassType", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=no-wrapper-object-types.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-wrapper-object-types.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-wrapper-object-types.d.ts.map new file mode 100644 index 00000000..2030181e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-wrapper-object-types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"no-wrapper-object-types.d.ts","sourceRoot":"","sources":["../../src/rules/no-wrapper-object-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAiBnE,wBAsDG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-wrapper-object-types.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-wrapper-object-types.js new file mode 100644 index 00000000..11c35090 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-wrapper-object-types.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const classNames = new Set([ + 'BigInt', + // eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum + 'Boolean', + 'Number', + 'Object', + // eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum + 'String', + 'Symbol', +]); +exports.default = (0, util_1.createRule)({ + name: 'no-wrapper-object-types', + meta: { + type: 'problem', + docs: { + description: 'Disallow using confusing built-in primitive class wrappers', + recommended: 'recommended', + }, + fixable: 'code', + messages: { + bannedClassType: 'Prefer using the primitive `{{preferred}}` as a type name, rather than the upper-cased `{{typeName}}`.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function checkBannedTypes(node, includeFix) { + const typeName = node.type === utils_1.AST_NODE_TYPES.Identifier && node.name; + if (!typeName || + !classNames.has(typeName) || + !(0, util_1.isReferenceToGlobalFunction)(typeName, node, context.sourceCode)) { + return; + } + const preferred = typeName.toLowerCase(); + context.report({ + node, + messageId: 'bannedClassType', + data: { preferred, typeName }, + fix: includeFix + ? (fixer) => fixer.replaceText(node, preferred) + : undefined, + }); + } + return { + TSClassImplements(node) { + checkBannedTypes(node.expression, false); + }, + TSInterfaceHeritage(node) { + checkBannedTypes(node.expression, false); + }, + TSTypeReference(node) { + checkBannedTypes(node.typeName, true); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/non-nullable-type-assertion-style.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/non-nullable-type-assertion-style.d.ts new file mode 100644 index 00000000..08c64c22 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/non-nullable-type-assertion-style.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferNonNullAssertion", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=non-nullable-type-assertion-style.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/non-nullable-type-assertion-style.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/non-nullable-type-assertion-style.d.ts.map new file mode 100644 index 00000000..1c54ce94 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/non-nullable-type-assertion-style.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"non-nullable-type-assertion-style.d.ts","sourceRoot":"","sources":["../../src/rules/non-nullable-type-assertion-style.ts"],"names":[],"mappings":";AAaA,wBAwIG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/non-nullable-type-assertion-style.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/non-nullable-type-assertion-style.js new file mode 100644 index 00000000..19952886 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/non-nullable-type-assertion-style.js @@ -0,0 +1,132 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'non-nullable-type-assertion-style', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce non-null assertions over explicit type assertions', + recommended: 'stylistic', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + preferNonNullAssertion: 'Use a ! assertion to more succinctly remove null and undefined from the type.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const getTypesIfNotLoose = (node) => { + const type = services.getTypeAtLocation(node); + if (tsutils.isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { + return undefined; + } + return tsutils.unionConstituents(type); + }; + const couldBeNullish = (type) => { + if (type.flags & ts.TypeFlags.TypeParameter) { + const constraint = type.getConstraint(); + return constraint == null || couldBeNullish(constraint); + } + if (tsutils.isUnionType(type)) { + for (const part of type.types) { + if (couldBeNullish(part)) { + return true; + } + } + return false; + } + return (type.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) !== 0; + }; + const sameTypeWithoutNullish = (assertedTypes, originalTypes) => { + const nonNullishOriginalTypes = originalTypes.filter(type => (type.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) === 0); + if (nonNullishOriginalTypes.length === originalTypes.length) { + return false; + } + for (const assertedType of assertedTypes) { + if (couldBeNullish(assertedType) || + !nonNullishOriginalTypes.includes(assertedType)) { + return false; + } + } + for (const originalType of nonNullishOriginalTypes) { + if (!assertedTypes.includes(originalType)) { + return false; + } + } + return true; + }; + const isConstAssertion = (node) => { + return (node.typeAnnotation.type === utils_1.AST_NODE_TYPES.TSTypeReference && + node.typeAnnotation.typeName.type === utils_1.AST_NODE_TYPES.Identifier && + node.typeAnnotation.typeName.name === 'const'); + }; + return { + 'TSAsExpression, TSTypeAssertion'(node) { + if (isConstAssertion(node)) { + return; + } + const originalTypes = getTypesIfNotLoose(node.expression); + if (!originalTypes) { + return; + } + const assertedTypes = getTypesIfNotLoose(node.typeAnnotation); + if (!assertedTypes) { + return; + } + if (sameTypeWithoutNullish(assertedTypes, originalTypes)) { + const expressionSourceCode = context.sourceCode.getText(node.expression); + const higherPrecedenceThanUnary = (0, util_1.getOperatorPrecedence)(services.esTreeNodeToTSNodeMap.get(node.expression).kind, ts.SyntaxKind.Unknown) > util_1.OperatorPrecedence.Unary; + context.report({ + node, + messageId: 'preferNonNullAssertion', + fix(fixer) { + return fixer.replaceText(node, higherPrecedenceThanUnary + ? `${expressionSourceCode}!` + : `(${expressionSourceCode})!`); + }, + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/only-throw-error.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/only-throw-error.d.ts new file mode 100644 index 00000000..bbf95201 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/only-throw-error.d.ts @@ -0,0 +1,13 @@ +import type { TypeOrValueSpecifier } from '../util'; +export type MessageIds = 'object' | 'undef'; +export type Options = [ + { + allow?: TypeOrValueSpecifier[]; + allowRethrowing?: boolean; + allowThrowingAny?: boolean; + allowThrowingUnknown?: boolean; + } +]; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=only-throw-error.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/only-throw-error.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/only-throw-error.d.ts.map new file mode 100644 index 00000000..67ee3eb8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/only-throw-error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"only-throw-error.d.ts","sourceRoot":"","sources":["../../src/rules/only-throw-error.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAepD,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,OAAO,CAAC;AAE5C,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,KAAK,CAAC,EAAE,oBAAoB,EAAE,CAAC;QAC/B,eAAe,CAAC,EAAE,OAAO,CAAC;QAC1B,gBAAgB,CAAC,EAAE,OAAO,CAAC;QAC3B,oBAAoB,CAAC,EAAE,OAAO,CAAC;KAChC;CACF,CAAC;;AAEF,wBA4JG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/only-throw-error.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/only-throw-error.js new file mode 100644 index 00000000..21196857 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/only-throw-error.js @@ -0,0 +1,161 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const ts_api_utils_1 = require("ts-api-utils"); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const promiseUtils_1 = require("../util/promiseUtils"); +exports.default = (0, util_1.createRule)({ + name: 'only-throw-error', + meta: { + type: 'problem', + docs: { + description: 'Disallow throwing non-`Error` values as exceptions', + extendsBaseRule: 'no-throw-literal', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + object: 'Expected an error object to be thrown.', + undef: 'Do not throw undefined.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allow: { + ...util_1.typeOrValueSpecifiersSchema, + description: 'Type specifiers that can be thrown.', + }, + allowRethrowing: { + type: 'boolean', + description: 'Whether to allow rethrowing caught values that are not `Error` objects.', + }, + allowThrowingAny: { + type: 'boolean', + description: 'Whether to always allow throwing values typed as `any`.', + }, + allowThrowingUnknown: { + type: 'boolean', + description: 'Whether to always allow throwing values typed as `unknown`.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allow: [], + allowRethrowing: true, + allowThrowingAny: true, + allowThrowingUnknown: true, + }, + ], + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + const allow = options.allow; + function isRethrownError(node) { + if (node.type !== utils_1.AST_NODE_TYPES.Identifier) { + return false; + } + const scope = context.sourceCode.getScope(node); + const smVariable = (0, util_1.nullThrows)((0, util_1.findVariable)(scope, node), `Variable ${node.name} should exist in scope manager`); + const variableDefinitions = smVariable.defs.filter(def => def.isVariableDefinition); + if (variableDefinitions.length !== 1) { + return false; + } + const def = smVariable.defs[0]; + // try { /* ... */ } catch (x) { throw x; } + if (def.node.type === utils_1.AST_NODE_TYPES.CatchClause) { + return true; + } + // promise.catch(x => { throw x; }) + // promise.then(onFulfilled, x => { throw x; }) + if (def.node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + def.node.params.length >= 1 && + def.node.params[0] === def.name && + def.node.parent.type === utils_1.AST_NODE_TYPES.CallExpression) { + const callExpression = def.node.parent; + const parsedPromiseHandlingCall = (0, promiseUtils_1.parseCatchCall)(callExpression, context) ?? + (0, promiseUtils_1.parseThenCall)(callExpression, context); + if (parsedPromiseHandlingCall != null) { + const { object, onRejected } = parsedPromiseHandlingCall; + if (onRejected === def.node) { + const tsObjectNode = services.esTreeNodeToTSNodeMap.get(object); + // make sure we're actually dealing with a promise + if ((0, ts_api_utils_1.isThenableType)(services.program.getTypeChecker(), tsObjectNode)) { + return true; + } + } + } + } + return false; + } + function checkThrowArgument(node) { + if (node.type === utils_1.AST_NODE_TYPES.AwaitExpression || + node.type === utils_1.AST_NODE_TYPES.YieldExpression) { + return; + } + if (options.allowRethrowing && isRethrownError(node)) { + return; + } + const type = services.getTypeAtLocation(node); + if ((0, util_1.typeMatchesSomeSpecifier)(type, allow, services.program)) { + return; + } + if (type.flags & ts.TypeFlags.Undefined) { + context.report({ node, messageId: 'undef' }); + return; + } + if (options.allowThrowingAny && (0, util_1.isTypeAnyType)(type)) { + return; + } + if (options.allowThrowingUnknown && (0, util_1.isTypeUnknownType)(type)) { + return; + } + if ((0, util_1.isErrorLike)(services.program, type)) { + return; + } + context.report({ node, messageId: 'object' }); + } + return { + ThrowStatement(node) { + checkThrowArgument(node.argument); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/parameter-properties.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/parameter-properties.d.ts new file mode 100644 index 00000000..17a90395 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/parameter-properties.d.ts @@ -0,0 +1,12 @@ +type Modifier = 'private' | 'private readonly' | 'protected' | 'protected readonly' | 'public' | 'public readonly' | 'readonly'; +type Prefer = 'class-property' | 'parameter-property'; +export type Options = [ + { + allow?: Modifier[]; + prefer?: Prefer; + } +]; +export type MessageIds = 'preferClassProperty' | 'preferParameterProperty'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=parameter-properties.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/parameter-properties.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/parameter-properties.d.ts.map new file mode 100644 index 00000000..b64050b7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/parameter-properties.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parameter-properties.d.ts","sourceRoot":"","sources":["../../src/rules/parameter-properties.ts"],"names":[],"mappings":"AAMA,KAAK,QAAQ,GACT,SAAS,GACT,kBAAkB,GAClB,WAAW,GACX,oBAAoB,GACpB,QAAQ,GACR,iBAAiB,GACjB,UAAU,CAAC;AAEf,KAAK,MAAM,GAAG,gBAAgB,GAAG,oBAAoB,CAAC;AAEtD,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC;QACnB,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,qBAAqB,GAAG,yBAAyB,CAAC;;AAE3E,wBAiOG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/parameter-properties.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/parameter-properties.js new file mode 100644 index 00000000..95a5e12d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/parameter-properties.js @@ -0,0 +1,170 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'parameter-properties', + meta: { + type: 'problem', + docs: { + description: 'Require or disallow parameter properties in class constructors', + }, + messages: { + preferClassProperty: 'Property {{parameter}} should be declared as a class property.', + preferParameterProperty: 'Property {{parameter}} should be declared as a parameter property.', + }, + schema: [ + { + type: 'object', + $defs: { + modifier: { + type: 'string', + enum: [ + 'readonly', + 'private', + 'protected', + 'public', + 'private readonly', + 'protected readonly', + 'public readonly', + ], + }, + }, + additionalProperties: false, + properties: { + allow: { + type: 'array', + description: 'Whether to allow certain kinds of properties to be ignored.', + items: { + $ref: '#/items/0/$defs/modifier', + }, + }, + prefer: { + type: 'string', + description: 'Whether to prefer class properties or parameter properties.', + enum: ['class-property', 'parameter-property'], + }, + }, + }, + ], + }, + defaultOptions: [ + { + allow: [], + prefer: 'class-property', + }, + ], + create(context, [{ allow = [], prefer = 'class-property' }]) { + /** + * Gets the modifiers of `node`. + * @param node the node to be inspected. + */ + function getModifiers(node) { + const modifiers = []; + if (node.accessibility) { + modifiers.push(node.accessibility); + } + if (node.readonly) { + modifiers.push('readonly'); + } + return modifiers.filter(Boolean).join(' '); + } + if (prefer === 'class-property') { + return { + TSParameterProperty(node) { + const modifiers = getModifiers(node); + if (!allow.includes(modifiers)) { + // HAS to be an identifier or assignment or TSC will throw + if (node.parameter.type !== utils_1.AST_NODE_TYPES.Identifier && + node.parameter.type !== utils_1.AST_NODE_TYPES.AssignmentPattern) { + return; + } + const name = node.parameter.type === utils_1.AST_NODE_TYPES.Identifier + ? node.parameter.name + : // has to be an Identifier or TSC will throw an error + node.parameter.left.name; + context.report({ + node, + messageId: 'preferClassProperty', + data: { + parameter: name, + }, + }); + } + }, + }; + } + const propertyNodesByNameStack = []; + function getNodesByName(name) { + const propertyNodesByName = propertyNodesByNameStack[propertyNodesByNameStack.length - 1]; + const existing = propertyNodesByName.get(name); + if (existing) { + return existing; + } + const created = {}; + propertyNodesByName.set(name, created); + return created; + } + function typeAnnotationsMatch(classProperty, constructorParameter) { + if (!classProperty.typeAnnotation || + !constructorParameter.typeAnnotation) { + return (classProperty.typeAnnotation === constructorParameter.typeAnnotation); + } + return (context.sourceCode.getText(classProperty.typeAnnotation) === + context.sourceCode.getText(constructorParameter.typeAnnotation)); + } + return { + ':matches(ClassDeclaration, ClassExpression):exit'() { + const propertyNodesByName = (0, util_1.nullThrows)(propertyNodesByNameStack.pop(), 'Stack should exist on class exit'); + for (const [name, nodes] of propertyNodesByName) { + if (nodes.classProperty && + nodes.constructorAssignment && + nodes.constructorParameter && + typeAnnotationsMatch(nodes.classProperty, nodes.constructorParameter)) { + context.report({ + node: nodes.classProperty, + messageId: 'preferParameterProperty', + data: { + parameter: name, + }, + }); + } + } + }, + ClassBody(node) { + for (const element of node.body) { + if (element.type === utils_1.AST_NODE_TYPES.PropertyDefinition && + element.key.type === utils_1.AST_NODE_TYPES.Identifier && + !element.value && + !allow.includes(getModifiers(element))) { + getNodesByName(element.key.name).classProperty = element; + } + } + }, + 'ClassDeclaration, ClassExpression'() { + propertyNodesByNameStack.push(new Map()); + }, + 'MethodDefinition[kind="constructor"]'(node) { + for (const parameter of node.value.params) { + if (parameter.type === utils_1.AST_NODE_TYPES.Identifier) { + getNodesByName(parameter.name).constructorParameter = parameter; + } + } + for (const statement of node.value.body?.body ?? []) { + if (statement.type !== utils_1.AST_NODE_TYPES.ExpressionStatement || + statement.expression.type !== utils_1.AST_NODE_TYPES.AssignmentExpression || + statement.expression.left.type !== + utils_1.AST_NODE_TYPES.MemberExpression || + statement.expression.left.object.type !== + utils_1.AST_NODE_TYPES.ThisExpression || + statement.expression.left.property.type !== + utils_1.AST_NODE_TYPES.Identifier || + statement.expression.right.type !== utils_1.AST_NODE_TYPES.Identifier) { + break; + } + getNodesByName(statement.expression.right.name).constructorAssignment = statement.expression; + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-as-const.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-as-const.d.ts new file mode 100644 index 00000000..28c5601e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-as-const.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"preferConstAssertion" | "variableConstAssertion" | "variableSuggest", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=prefer-as-const.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-as-const.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-as-const.d.ts.map new file mode 100644 index 00000000..1dc9166c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-as-const.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-as-const.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-as-const.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAMnE,wBA2EG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-as-const.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-as-const.js new file mode 100644 index 00000000..9e7ef2fc --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-as-const.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-as-const', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce the use of `as const` over literal type', + recommended: 'recommended', + }, + fixable: 'code', + hasSuggestions: true, + messages: { + preferConstAssertion: 'Expected a `const` instead of a literal type assertion.', + variableConstAssertion: 'Expected a `const` assertion instead of a literal type annotation.', + variableSuggest: 'You should use `as const` instead of type annotation.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function compareTypes(valueNode, typeNode, canFix) { + if (valueNode.type === utils_1.AST_NODE_TYPES.Literal && + typeNode.type === utils_1.AST_NODE_TYPES.TSLiteralType && + typeNode.literal.type === utils_1.AST_NODE_TYPES.Literal && + valueNode.raw === typeNode.literal.raw) { + if (canFix) { + context.report({ + node: typeNode, + messageId: 'preferConstAssertion', + fix: fixer => fixer.replaceText(typeNode, 'const'), + }); + } + else { + context.report({ + node: typeNode, + messageId: 'variableConstAssertion', + suggest: [ + { + messageId: 'variableSuggest', + fix: (fixer) => [ + fixer.remove(typeNode.parent), + fixer.insertTextAfter(valueNode, ' as const'), + ], + }, + ], + }); + } + } + } + return { + PropertyDefinition(node) { + if (node.value && node.typeAnnotation) { + compareTypes(node.value, node.typeAnnotation.typeAnnotation, false); + } + }, + TSAsExpression(node) { + compareTypes(node.expression, node.typeAnnotation, true); + }, + TSTypeAssertion(node) { + compareTypes(node.expression, node.typeAnnotation, true); + }, + VariableDeclarator(node) { + if (node.init && node.id.typeAnnotation) { + compareTypes(node.init, node.id.typeAnnotation.typeAnnotation, false); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.d.ts new file mode 100644 index 00000000..08bf3a6c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.d.ts @@ -0,0 +1,18 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util'; +declare const baseRule: TSESLint.RuleModule<"preferDestructuring", [import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig | { + AssignmentExpression?: import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig; + VariableDeclarator?: import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig; +}, (import("eslint/lib/rules/prefer-destructuring").Option1 | undefined)?], unknown, { + AssignmentExpression(node: TSESTree.AssignmentExpression): void; + VariableDeclarator(node: TSESTree.VariableDeclarator): void; +}>; +type BaseOptions = InferOptionsTypeFromRule; +type EnforcementOptions = { + enforceForDeclarationWithTypeAnnotation?: boolean; +} & BaseOptions[1]; +export type Options = [BaseOptions[0], EnforcementOptions]; +export type MessageIds = InferMessageIdsTypeFromRule; +declare const _default: TSESLint.RuleModule<"preferDestructuring", Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=prefer-destructuring.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.d.ts.map new file mode 100644 index 00000000..b2f7a8c7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-destructuring.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-destructuring.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAOnE,OAAO,KAAK,EACV,2BAA2B,EAC3B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAKjB,QAAA,MAAM,QAAQ;;;;+BAuOktN,SAAU,oBAAoB;6BAAuC,SAAU,kBAAkB;EAvOvwN,CAAC;AAE3D,KAAK,WAAW,GAAG,wBAAwB,CAAC,OAAO,QAAQ,CAAC,CAAC;AAC7D,KAAK,kBAAkB,GAAG;IACxB,uCAAuC,CAAC,EAAE,OAAO,CAAC;CACnD,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;AACnB,MAAM,MAAM,OAAO,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,kBAAkB,CAAC,CAAC;AAE3D,MAAM,MAAM,UAAU,GAAG,2BAA2B,CAAC,OAAO,QAAQ,CAAC,CAAC;;AA8CtE,wBAuHG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.js new file mode 100644 index 00000000..76b414e3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.js @@ -0,0 +1,214 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +const getESLintCoreRule_1 = require("../util/getESLintCoreRule"); +const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('prefer-destructuring'); +const destructuringTypeConfig = { + type: 'object', + additionalProperties: false, + properties: { + array: { + type: 'boolean', + }, + object: { + type: 'boolean', + }, + }, +}; +const schema = [ + { + oneOf: [ + { + type: 'object', + additionalProperties: false, + properties: { + AssignmentExpression: destructuringTypeConfig, + VariableDeclarator: destructuringTypeConfig, + }, + }, + destructuringTypeConfig, + ], + }, + { + type: 'object', + properties: { + enforceForDeclarationWithTypeAnnotation: { + type: 'boolean', + description: 'Whether to enforce destructuring on variable declarations with type annotations.', + }, + enforceForRenamedProperties: { + type: 'boolean', + description: 'Whether to enforce destructuring that use a different variable name than the property name.', + }, + }, + }, +]; +exports.default = (0, util_1.createRule)({ + name: 'prefer-destructuring', + meta: { + type: 'suggestion', + // defaultOptions, -- base rule does not use defaultOptions + docs: { + description: 'Require destructuring from arrays and/or objects', + extendsBaseRule: true, + requiresTypeChecking: true, + }, + fixable: baseRule.meta.fixable, + hasSuggestions: baseRule.meta.hasSuggestions, + messages: baseRule.meta.messages, + schema, + }, + defaultOptions: [ + { + AssignmentExpression: { + array: true, + object: true, + }, + VariableDeclarator: { + array: true, + object: true, + }, + }, + {}, + ], + create(context, [enabledTypes, options]) { + const { enforceForDeclarationWithTypeAnnotation = false, enforceForRenamedProperties = false, } = options; + const { esTreeNodeToTSNodeMap, program } = (0, util_1.getParserServices)(context); + const typeChecker = program.getTypeChecker(); + const baseRules = baseRule.create(context); + let baseRulesWithoutFixCache = null; + return { + AssignmentExpression(node) { + if (node.operator !== '=') { + return; + } + performCheck(node.left, node.right, node); + }, + VariableDeclarator(node) { + performCheck(node.id, node.init, node); + }, + }; + function performCheck(leftNode, rightNode, reportNode) { + const rules = leftNode.type === utils_1.AST_NODE_TYPES.Identifier && + leftNode.typeAnnotation == null + ? baseRules + : baseRulesWithoutFix(); + if ((leftNode.type === utils_1.AST_NODE_TYPES.ArrayPattern || + leftNode.type === utils_1.AST_NODE_TYPES.Identifier || + leftNode.type === utils_1.AST_NODE_TYPES.ObjectPattern) && + leftNode.typeAnnotation != null && + !enforceForDeclarationWithTypeAnnotation) { + return; + } + if (rightNode != null && + isArrayLiteralIntegerIndexAccess(rightNode) && + rightNode.object.type !== utils_1.AST_NODE_TYPES.Super) { + const tsObj = esTreeNodeToTSNodeMap.get(rightNode.object); + const objType = typeChecker.getTypeAtLocation(tsObj); + if (!isTypeAnyOrIterableType(objType, typeChecker)) { + if (!enforceForRenamedProperties || + !getNormalizedEnabledType(reportNode.type, 'object')) { + return; + } + context.report({ + node: reportNode, + messageId: 'preferDestructuring', + data: { type: 'object' }, + }); + return; + } + } + if (reportNode.type === utils_1.AST_NODE_TYPES.AssignmentExpression) { + rules.AssignmentExpression(reportNode); + } + else { + rules.VariableDeclarator(reportNode); + } + } + function getNormalizedEnabledType(nodeType, destructuringType) { + if ('object' in enabledTypes || 'array' in enabledTypes) { + return enabledTypes[destructuringType]; + } + return enabledTypes[nodeType][destructuringType]; + } + function baseRulesWithoutFix() { + baseRulesWithoutFixCache ??= baseRule.create(noFixContext(context)); + return baseRulesWithoutFixCache; + } + }, +}); +function noFixContext(context) { + const customContext = { + report: (descriptor) => { + context.report({ + ...descriptor, + fix: undefined, + }); + }, + }; + // we can't directly proxy `context` because its `report` property is non-configurable + // and non-writable. So we proxy `customContext` and redirect all + // property access to the original context except for `report` + return new Proxy(customContext, { + get(target, path, receiver) { + if (path !== 'report') { + return Reflect.get(context, path, receiver); + } + return Reflect.get(target, path, receiver); + }, + }); +} +function isTypeAnyOrIterableType(type, typeChecker) { + if ((0, util_1.isTypeAnyType)(type)) { + return true; + } + if (!type.isUnion()) { + const iterator = tsutils.getWellKnownSymbolPropertyOfType(type, 'iterator', typeChecker); + return iterator != null; + } + return type.types.every(t => isTypeAnyOrIterableType(t, typeChecker)); +} +function isArrayLiteralIntegerIndexAccess(node) { + if (node.type !== utils_1.AST_NODE_TYPES.MemberExpression) { + return false; + } + if (node.property.type !== utils_1.AST_NODE_TYPES.Literal) { + return false; + } + return Number.isInteger(node.property.value); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-enum-initializers.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-enum-initializers.d.ts new file mode 100644 index 00000000..7a2ac587 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-enum-initializers.d.ts @@ -0,0 +1,5 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageIds = 'defineInitializer' | 'defineInitializerSuggestion'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=prefer-enum-initializers.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-enum-initializers.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-enum-initializers.d.ts.map new file mode 100644 index 00000000..4265619a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-enum-initializers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-enum-initializers.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-enum-initializers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAInE,MAAM,MAAM,UAAU,GAAG,mBAAmB,GAAG,6BAA6B,CAAC;;AAE7E,wBA+DG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-enum-initializers.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-enum-initializers.js new file mode 100644 index 00000000..d9549e65 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-enum-initializers.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-enum-initializers', + meta: { + type: 'suggestion', + docs: { + description: 'Require each enum member value to be explicitly initialized', + }, + hasSuggestions: true, + messages: { + defineInitializer: "The value of the member '{{ name }}' should be explicitly defined.", + defineInitializerSuggestion: 'Can be fixed to {{ name }} = {{ suggested }}', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function TSEnumDeclaration(node) { + const { members } = node.body; + members.forEach((member, index) => { + if (member.initializer == null) { + const name = context.sourceCode.getText(member); + context.report({ + node: member, + messageId: 'defineInitializer', + data: { + name, + }, + suggest: [ + { + messageId: 'defineInitializerSuggestion', + data: { name, suggested: index }, + fix: (fixer) => { + return fixer.replaceText(member, `${name} = ${index}`); + }, + }, + { + messageId: 'defineInitializerSuggestion', + data: { name, suggested: index + 1 }, + fix: (fixer) => { + return fixer.replaceText(member, `${name} = ${index + 1}`); + }, + }, + { + messageId: 'defineInitializerSuggestion', + data: { name, suggested: `'${name}'` }, + fix: (fixer) => { + return fixer.replaceText(member, `${name} = '${name}'`); + }, + }, + ], + }); + } + }); + } + return { + TSEnumDeclaration, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-find.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-find.d.ts new file mode 100644 index 00000000..5d8b6d4b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-find.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"preferFind" | "preferFindSuggestion", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=prefer-find.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-find.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-find.d.ts.map new file mode 100644 index 00000000..c37430a4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-find.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-find.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-find.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAiBnE,wBA2SG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-find.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-find.js new file mode 100644 index 00000000..fc23349e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-find.js @@ -0,0 +1,247 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-find', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result', + recommended: 'stylistic', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + preferFind: 'Prefer .find(...) instead of .filter(...)[0].', + preferFindSuggestion: 'Use .find(...) instead of .filter(...)[0].', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const globalScope = context.sourceCode.getScope(context.sourceCode.ast); + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function parseArrayFilterExpressions(expression) { + const node = (0, util_1.skipChainExpression)(expression); + if (node.type === utils_1.AST_NODE_TYPES.SequenceExpression) { + // Only the last expression in (a, b, [1, 2, 3].filter(condition))[0] matters + const lastExpression = (0, util_1.nullThrows)(node.expressions.at(-1), 'Expected to have more than zero expressions in a sequence expression'); + return parseArrayFilterExpressions(lastExpression); + } + // This is the only reason we're returning a list rather than a single value. + if (node.type === utils_1.AST_NODE_TYPES.ConditionalExpression) { + // Both branches of the ternary _must_ return results. + const consequentResult = parseArrayFilterExpressions(node.consequent); + if (consequentResult.length === 0) { + return []; + } + const alternateResult = parseArrayFilterExpressions(node.alternate); + if (alternateResult.length === 0) { + return []; + } + // Accumulate the results from both sides and pass up the chain. + return [...consequentResult, ...alternateResult]; + } + // Check if it looks like <>(...), but not <>?.(...) + if (node.type === utils_1.AST_NODE_TYPES.CallExpression && !node.optional) { + const callee = node.callee; + // Check if it looks like <>.filter(...) or <>['filter'](...), + // or the optional chaining variants. + if (callee.type === utils_1.AST_NODE_TYPES.MemberExpression) { + const isBracketSyntaxForFilter = callee.computed; + if ((0, util_1.isStaticMemberAccessOfValue)(callee, context, 'filter')) { + const filterNode = callee.property; + const filteredObjectType = (0, util_1.getConstrainedTypeAtLocation)(services, callee.object); + // As long as the object is a (possibly nullable) array, + // this is an Array.prototype.filter expression. + if (isArrayish(filteredObjectType)) { + return [ + { + filterNode, + isBracketSyntaxForFilter, + }, + ]; + } + } + } + } + // not a filter expression. + return []; + } + /** + * Tells whether the type is a possibly nullable array/tuple or union thereof. + */ + function isArrayish(type) { + let isAtLeastOneArrayishComponent = false; + for (const unionPart of tsutils.unionConstituents(type)) { + if (tsutils.isIntrinsicNullType(unionPart) || + tsutils.isIntrinsicUndefinedType(unionPart)) { + continue; + } + // apparently checker.isArrayType(T[] & S[]) => false. + // so we need to check the intersection parts individually. + const isArrayOrIntersectionThereof = tsutils + .intersectionConstituents(unionPart) + .every(intersectionPart => checker.isArrayType(intersectionPart) || + checker.isTupleType(intersectionPart)); + if (!isArrayOrIntersectionThereof) { + // There is a non-array, non-nullish type component, + // so it's not an array. + return false; + } + isAtLeastOneArrayishComponent = true; + } + return isAtLeastOneArrayishComponent; + } + function getObjectIfArrayAtZeroExpression(node) { + // .at() should take exactly one argument. + if (node.arguments.length !== 1) { + return undefined; + } + const callee = node.callee; + if (callee.type === utils_1.AST_NODE_TYPES.MemberExpression && + !callee.optional && + (0, util_1.isStaticMemberAccessOfValue)(callee, context, 'at')) { + const atArgument = (0, util_1.getStaticValue)(node.arguments[0], globalScope); + if (atArgument != null && isTreatedAsZeroByArrayAt(atArgument.value)) { + return callee.object; + } + } + return undefined; + } + /** + * Implements the algorithm for array indexing by `.at()` method. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at#parameters + */ + function isTreatedAsZeroByArrayAt(value) { + // This would cause the number constructor coercion to throw. Other static + // values are safe. + if (typeof value === 'symbol') { + return false; + } + const asNumber = Number(value); + if (isNaN(asNumber)) { + return true; + } + return Math.trunc(asNumber) === 0; + } + function isMemberAccessOfZero(node) { + const property = (0, util_1.getStaticValue)(node.property, globalScope); + // Check if it looks like <>[0] or <>['0'], but not <>?.[0] + return (!node.optional && + property != null && + isTreatedAsZeroByMemberAccess(property.value)); + } + /** + * Implements the algorithm for array indexing by member operator. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_indices + */ + function isTreatedAsZeroByMemberAccess(value) { + return String(value) === '0'; + } + function generateFixToRemoveArrayElementAccess(fixer, arrayNode, wholeExpressionBeingFlagged) { + const tokenToStartDeletingFrom = (0, util_1.nullThrows)( + // The next `.` or `[` is what we're looking for. + // think of (...).at(0) or (...)[0] or even (...)["at"](0). + context.sourceCode.getTokenAfter(arrayNode, token => token.value === '.' || token.value === '['), 'Expected to find a member access token!'); + return fixer.removeRange([ + tokenToStartDeletingFrom.range[0], + wholeExpressionBeingFlagged.range[1], + ]); + } + function generateFixToReplaceFilterWithFind(fixer, filterExpression) { + return fixer.replaceText(filterExpression.filterNode, filterExpression.isBracketSyntaxForFilter ? '"find"' : 'find'); + } + return { + // This query will be used to find things like `filteredResults.at(0)`. + CallExpression(node) { + const object = getObjectIfArrayAtZeroExpression(node); + if (object) { + const filterExpressions = parseArrayFilterExpressions(object); + if (filterExpressions.length !== 0) { + context.report({ + node, + messageId: 'preferFind', + suggest: [ + { + messageId: 'preferFindSuggestion', + fix: (fixer) => { + return [ + ...filterExpressions.map(filterExpression => generateFixToReplaceFilterWithFind(fixer, filterExpression)), + // Get rid of the .at(0) or ['at'](0). + generateFixToRemoveArrayElementAccess(fixer, object, node), + ]; + }, + }, + ], + }); + } + } + }, + // This query will be used to find things like `filteredResults[0]`. + // + // Note: we're always looking for array member access to be "computed", + // i.e. `filteredResults[0]`, since `filteredResults.0` isn't a thing. + 'MemberExpression[computed=true]'(node) { + if (isMemberAccessOfZero(node)) { + const object = node.object; + const filterExpressions = parseArrayFilterExpressions(object); + if (filterExpressions.length !== 0) { + context.report({ + node, + messageId: 'preferFind', + suggest: [ + { + messageId: 'preferFindSuggestion', + fix: (fixer) => { + return [ + ...filterExpressions.map(filterExpression => generateFixToReplaceFilterWithFind(fixer, filterExpression)), + // Get rid of the [0]. + generateFixToRemoveArrayElementAccess(fixer, object, node), + ]; + }, + }, + ], + }); + } + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-for-of.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-for-of.d.ts new file mode 100644 index 00000000..2fedea5d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-for-of.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"preferForOf", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=prefer-for-of.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-for-of.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-for-of.d.ts.map new file mode 100644 index 00000000..f2186164 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-for-of.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-for-of.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-for-of.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAMnE,wBAgKG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-for-of.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-for-of.js new file mode 100644 index 00000000..e77461a7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-for-of.js @@ -0,0 +1,115 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-for-of', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce the use of `for-of` loop over the standard `for` loop where possible', + recommended: 'stylistic', + }, + messages: { + preferForOf: 'Expected a `for-of` loop instead of a `for` loop with this simple iteration.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + function isSingleVariableDeclaration(node) { + return (node?.type === utils_1.AST_NODE_TYPES.VariableDeclaration && + node.kind !== 'const' && + node.declarations.length === 1); + } + function isLiteral(node, value) { + return node.type === utils_1.AST_NODE_TYPES.Literal && node.value === value; + } + function isZeroInitialized(node) { + return node.init != null && isLiteral(node.init, 0); + } + function isMatchingIdentifier(node, name) { + return node.type === utils_1.AST_NODE_TYPES.Identifier && node.name === name; + } + function isLessThanLengthExpression(node, name) { + if (node?.type === utils_1.AST_NODE_TYPES.BinaryExpression && + node.operator === '<' && + isMatchingIdentifier(node.left, name) && + node.right.type === utils_1.AST_NODE_TYPES.MemberExpression && + isMatchingIdentifier(node.right.property, 'length')) { + return node.right.object; + } + return null; + } + function isIncrement(node, name) { + if (!node) { + return false; + } + switch (node.type) { + case utils_1.AST_NODE_TYPES.UpdateExpression: + // x++ or ++x + return (node.operator === '++' && isMatchingIdentifier(node.argument, name)); + case utils_1.AST_NODE_TYPES.AssignmentExpression: + if (isMatchingIdentifier(node.left, name)) { + if (node.operator === '+=') { + // x += 1 + return isLiteral(node.right, 1); + } + if (node.operator === '=') { + // x = x + 1 or x = 1 + x + const expr = node.right; + return (expr.type === utils_1.AST_NODE_TYPES.BinaryExpression && + expr.operator === '+' && + ((isMatchingIdentifier(expr.left, name) && + isLiteral(expr.right, 1)) || + (isLiteral(expr.left, 1) && + isMatchingIdentifier(expr.right, name)))); + } + } + } + return false; + } + function contains(outer, inner) { + return (outer.range[0] <= inner.range[0] && outer.range[1] >= inner.range[1]); + } + function isIndexOnlyUsedWithArray(body, indexVar, arrayExpression) { + const arrayText = context.sourceCode.getText(arrayExpression); + return indexVar.references.every(reference => { + const id = reference.identifier; + const node = id.parent; + return (!contains(body, id) || + (node.type === utils_1.AST_NODE_TYPES.MemberExpression && + node.object.type !== utils_1.AST_NODE_TYPES.ThisExpression && + node.property === id && + context.sourceCode.getText(node.object) === arrayText && + !(0, util_1.isAssignee)(node))); + }); + } + return { + 'ForStatement:exit'(node) { + if (!isSingleVariableDeclaration(node.init)) { + return; + } + const declarator = node.init.declarations[0]; + if (!declarator || + !isZeroInitialized(declarator) || + declarator.id.type !== utils_1.AST_NODE_TYPES.Identifier) { + return; + } + const indexName = declarator.id.name; + const arrayExpression = isLessThanLengthExpression(node.test, indexName); + if (!arrayExpression) { + return; + } + const [indexVar] = context.sourceCode.getDeclaredVariables(node.init); + if (isIncrement(node.update, indexName) && + isIndexOnlyUsedWithArray(node.body, indexVar, arrayExpression)) { + context.report({ + node, + messageId: 'preferForOf', + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-function-type.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-function-type.d.ts new file mode 100644 index 00000000..23fdaa60 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-function-type.d.ts @@ -0,0 +1,8 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export declare const phrases: { + readonly TSInterfaceDeclaration: "Interface"; + readonly TSTypeLiteral: "Type literal"; +}; +declare const _default: TSESLint.RuleModule<"functionTypeOverCallableType" | "unexpectedThisOnFunctionOnlyInterface", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=prefer-function-type.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-function-type.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-function-type.d.ts.map new file mode 100644 index 00000000..ebe19604 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-function-type.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-function-type.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-function-type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAMnE,eAAO,MAAM,OAAO;;;CAGV,CAAC;;AAEX,wBAsNG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-function-type.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-function-type.js new file mode 100644 index 00000000..b9337347 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-function-type.js @@ -0,0 +1,186 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.phrases = void 0; +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.phrases = { + [utils_1.AST_NODE_TYPES.TSInterfaceDeclaration]: 'Interface', + [utils_1.AST_NODE_TYPES.TSTypeLiteral]: 'Type literal', +}; +exports.default = (0, util_1.createRule)({ + name: 'prefer-function-type', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce using function types instead of interfaces with call signatures', + recommended: 'stylistic', + }, + fixable: 'code', + messages: { + functionTypeOverCallableType: '{{ literalOrInterface }} only has a call signature, you should use a function type instead.', + unexpectedThisOnFunctionOnlyInterface: "`this` refers to the function type '{{ interfaceName }}', did you intend to use a generic `this` parameter like `(this: Self, ...) => Self` instead?", + }, + schema: [], + }, + defaultOptions: [], + create(context) { + /** + * Checks if there the interface has exactly one supertype that isn't named 'Function' + * @param node The node being checked + */ + function hasOneSupertype(node) { + if (node.extends.length === 0) { + return false; + } + if (node.extends.length !== 1) { + return true; + } + const expr = node.extends[0].expression; + return (expr.type !== utils_1.AST_NODE_TYPES.Identifier || expr.name !== 'Function'); + } + /** + * @param parent The parent of the call signature causing the diagnostic + */ + function shouldWrapSuggestion(parent) { + if (!parent) { + return false; + } + switch (parent.type) { + case utils_1.AST_NODE_TYPES.TSUnionType: + case utils_1.AST_NODE_TYPES.TSIntersectionType: + case utils_1.AST_NODE_TYPES.TSArrayType: + return true; + default: + return false; + } + } + /** + * @param member The TypeElement being checked + * @param node The parent of member being checked + */ + function checkMember(member, node, tsThisTypes = null) { + if ((member.type === utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration || + member.type === utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration) && + member.returnType != null) { + if (tsThisTypes?.length && + node.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration) { + // the message can be confusing if we don't point directly to the `this` node instead of the whole member + // and in favour of generating at most one error we'll only report the first occurrence of `this` if there are multiple + context.report({ + node: tsThisTypes[0], + messageId: 'unexpectedThisOnFunctionOnlyInterface', + data: { + interfaceName: node.id.name, + }, + }); + return; + } + const fixable = node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration; + const fix = fixable + ? null + : (fixer) => { + const fixes = []; + const start = member.range[0]; + // https://github.com/microsoft/TypeScript/pull/56908 + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const colonPos = member.returnType.range[0] - start; + const text = context.sourceCode + .getText() + .slice(start, member.range[1]); + const comments = [ + ...context.sourceCode.getCommentsBefore(member), + ...context.sourceCode.getCommentsAfter(member), + ]; + let suggestion = `${text.slice(0, colonPos)} =>${text.slice(colonPos + 1)}`; + const lastChar = suggestion.endsWith(';') ? ';' : ''; + if (lastChar) { + suggestion = suggestion.slice(0, -1); + } + if (shouldWrapSuggestion(node.parent)) { + suggestion = `(${suggestion})`; + } + if (node.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration) { + if (node.typeParameters != null) { + suggestion = `type ${context.sourceCode + .getText() + .slice(node.id.range[0], node.typeParameters.range[1])} = ${suggestion}${lastChar}`; + } + else { + suggestion = `type ${node.id.name} = ${suggestion}${lastChar}`; + } + } + const isParentExported = node.parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration; + if (node.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration && + isParentExported) { + const commentsText = comments + .map(({ type, value }) => type === utils_1.AST_TOKEN_TYPES.Line + ? `//${value}\n` + : `/*${value}*/\n`) + .join(''); + // comments should move before export and not between export and interface declaration + fixes.push(fixer.insertTextBefore(node.parent, commentsText)); + } + else { + comments.forEach(comment => { + let commentText = comment.type === utils_1.AST_TOKEN_TYPES.Line + ? `//${comment.value}` + : `/*${comment.value}*/`; + const isCommentOnTheSameLine = comment.loc.start.line === member.loc.start.line; + if (!isCommentOnTheSameLine) { + commentText += '\n'; + } + else { + commentText += ' '; + } + suggestion = commentText + suggestion; + }); + } + const fixStart = node.range[0]; + fixes.push(fixer.replaceTextRange([fixStart, node.range[1]], suggestion)); + return fixes; + }; + context.report({ + node: member, + messageId: 'functionTypeOverCallableType', + data: { + literalOrInterface: exports.phrases[node.type], + }, + fix, + }); + } + } + let tsThisTypes = null; + let literalNesting = 0; + return { + TSInterfaceDeclaration() { + // when entering an interface reset the count of `this`s to empty. + tsThisTypes = []; + }, + 'TSInterfaceDeclaration:exit'(node) { + if (!hasOneSupertype(node) && node.body.body.length === 1) { + checkMember(node.body.body[0], node, tsThisTypes); + } + // on exit check member and reset the array to nothing. + tsThisTypes = null; + }, + 'TSInterfaceDeclaration TSThisType'(node) { + // inside an interface keep track of all ThisType references. + // unless it's inside a nested type literal in which case it's invalid code anyway + // we don't want to incorrectly say "it refers to name" while typescript says it's completely invalid. + if (literalNesting === 0 && tsThisTypes != null) { + tsThisTypes.push(node); + } + }, + // keep track of nested literals to avoid complaining about invalid `this` uses + 'TSInterfaceDeclaration TSTypeLiteral'() { + literalNesting += 1; + }, + 'TSInterfaceDeclaration TSTypeLiteral:exit'() { + literalNesting -= 1; + }, + 'TSTypeLiteral[members.length = 1]'(node) { + checkMember(node.members[0], node); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-includes.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-includes.d.ts new file mode 100644 index 00000000..201e2fe7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-includes.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"preferIncludes" | "preferStringIncludes", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=prefer-includes.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-includes.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-includes.d.ts.map new file mode 100644 index 00000000..000e3a22 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-includes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-includes.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-includes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAcnE,wBAkQG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-includes.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-includes.js new file mode 100644 index 00000000..171dac6b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-includes.js @@ -0,0 +1,242 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const regexpp_1 = require("@eslint-community/regexpp"); +const utils_1 = require("@typescript-eslint/utils"); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-includes', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce `includes` method over `indexOf` method', + recommended: 'stylistic', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + preferIncludes: "Use 'includes()' method instead.", + preferStringIncludes: 'Use `String#includes()` method with a string instead.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const globalScope = context.sourceCode.getScope(context.sourceCode.ast); + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function isNumber(node, value) { + const evaluated = (0, util_1.getStaticValue)(node, globalScope); + return evaluated != null && evaluated.value === value; + } + function isPositiveCheck(node) { + switch (node.operator) { + case '!==': + case '!=': + case '>': + return isNumber(node.right, -1); + case '>=': + return isNumber(node.right, 0); + default: + return false; + } + } + function isNegativeCheck(node) { + switch (node.operator) { + case '===': + case '==': + case '<=': + return isNumber(node.right, -1); + case '<': + return isNumber(node.right, 0); + default: + return false; + } + } + function hasSameParameters(nodeA, nodeB) { + if (!ts.isFunctionLike(nodeA) || !ts.isFunctionLike(nodeB)) { + return false; + } + const paramsA = nodeA.parameters; + const paramsB = nodeB.parameters; + if (paramsA.length !== paramsB.length) { + return false; + } + for (let i = 0; i < paramsA.length; ++i) { + const paramA = paramsA[i]; + const paramB = paramsB[i]; + // Check name, type, and question token once. + if (paramA.getText() !== paramB.getText()) { + return false; + } + } + return true; + } + /** + * Parse a given node if it's a `RegExp` instance. + * @param node The node to parse. + */ + function parseRegExp(node) { + const evaluated = (0, util_1.getStaticValue)(node, globalScope); + if (evaluated == null || !(evaluated.value instanceof RegExp)) { + return null; + } + const { flags, pattern } = (0, regexpp_1.parseRegExpLiteral)(evaluated.value); + if (pattern.alternatives.length !== 1 || + flags.ignoreCase || + flags.global) { + return null; + } + // Check if it can determine a unique string. + const chars = pattern.alternatives[0].elements; + if (!chars.every(c => c.type === 'Character')) { + return null; + } + // To string. + return String.fromCodePoint(...chars.map(c => c.value)); + } + function escapeString(str) { + const EscapeMap = { + '\0': '\\0', + '\t': '\\t', + '\n': '\\n', + '\v': '\\v', + '\f': '\\f', + '\r': '\\r', + "'": "\\'", + '\\': '\\\\', + // "\b" cause unexpected replacements + // '\b': '\\b', + }; + const replaceRegex = new RegExp(Object.values(EscapeMap).join('|'), 'g'); + return str.replaceAll(replaceRegex, char => EscapeMap[char]); + } + function checkArrayIndexOf(node, allowFixing) { + if (!(0, util_1.isStaticMemberAccessOfValue)(node, context, 'indexOf')) { + return; + } + // Check if the comparison is equivalent to `includes()`. + const callNode = node.parent; + const compareNode = (callNode.parent.type === utils_1.AST_NODE_TYPES.ChainExpression + ? callNode.parent.parent + : callNode.parent); + const negative = isNegativeCheck(compareNode); + if (!negative && !isPositiveCheck(compareNode)) { + return; + } + // Get the symbol of `indexOf` method. + const indexofMethodDeclarations = services + .getSymbolAtLocation(node.property) + ?.getDeclarations(); + if (indexofMethodDeclarations == null || + indexofMethodDeclarations.length === 0) { + return; + } + // Check if every declaration of `indexOf` method has `includes` method + // and the two methods have the same parameters. + for (const instanceofMethodDecl of indexofMethodDeclarations) { + const typeDecl = instanceofMethodDecl.parent; + const type = checker.getTypeAtLocation(typeDecl); + const includesMethodDecl = type + .getProperty('includes') + ?.getDeclarations(); + if (!includesMethodDecl?.some(includesMethodDecl => hasSameParameters(includesMethodDecl, instanceofMethodDecl))) { + return; + } + } + // Report it. + context.report({ + node: compareNode, + messageId: 'preferIncludes', + ...(allowFixing && { + *fix(fixer) { + if (negative) { + yield fixer.insertTextBefore(callNode, '!'); + } + yield fixer.replaceText(node.property, 'includes'); + yield fixer.removeRange([callNode.range[1], compareNode.range[1]]); + }, + }), + }); + } + return { + // a.indexOf(b) !== 1 + 'BinaryExpression > CallExpression.left > MemberExpression'(node) { + checkArrayIndexOf(node, /* allowFixing */ true); + }, + // a?.indexOf(b) !== 1 + 'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression'(node) { + checkArrayIndexOf(node, /* allowFixing */ false); + }, + // /bar/.test(foo) + 'CallExpression[arguments.length=1] > MemberExpression.callee[property.name="test"][computed=false]'(node) { + const callNode = node.parent; + const text = parseRegExp(node.object); + if (text == null) { + return; + } + //check the argument type of test methods + const argument = callNode.arguments[0]; + const type = (0, util_1.getConstrainedTypeAtLocation)(services, argument); + const includesMethodDecl = type + .getProperty('includes') + ?.getDeclarations(); + if (includesMethodDecl == null) { + return; + } + context.report({ + node: callNode, + messageId: 'preferStringIncludes', + *fix(fixer) { + const argNode = callNode.arguments[0]; + const needsParen = argNode.type !== utils_1.AST_NODE_TYPES.Literal && + argNode.type !== utils_1.AST_NODE_TYPES.TemplateLiteral && + argNode.type !== utils_1.AST_NODE_TYPES.Identifier && + argNode.type !== utils_1.AST_NODE_TYPES.MemberExpression && + argNode.type !== utils_1.AST_NODE_TYPES.CallExpression; + yield fixer.removeRange([callNode.range[0], argNode.range[0]]); + yield fixer.removeRange([argNode.range[1], callNode.range[1]]); + if (needsParen) { + yield fixer.insertTextBefore(argNode, '('); + yield fixer.insertTextAfter(argNode, ')'); + } + yield fixer.insertTextAfter(argNode, `${node.optional ? '?.' : '.'}includes('${escapeString(text)}')`); + }, + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-literal-enum-member.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-literal-enum-member.d.ts new file mode 100644 index 00000000..4ebd5ad5 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-literal-enum-member.d.ts @@ -0,0 +1,5 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"notLiteral" | "notLiteralOrBitwiseExpression", [{ + allowBitwiseExpressions: boolean; +}], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=prefer-literal-enum-member.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-literal-enum-member.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-literal-enum-member.d.ts.map new file mode 100644 index 00000000..c7e341c9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-literal-enum-member.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-literal-enum-member.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-literal-enum-member.ts"],"names":[],"mappings":";;;AAMA,wBAmJG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-literal-enum-member.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-literal-enum-member.js new file mode 100644 index 00000000..168fdcd7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-literal-enum-member.js @@ -0,0 +1,116 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-literal-enum-member', + meta: { + type: 'suggestion', + docs: { + description: 'Require all enum members to be literal values', + recommended: 'strict', + requiresTypeChecking: false, + }, + messages: { + notLiteral: `Explicit enum value must only be a literal value (string or number).`, + notLiteralOrBitwiseExpression: `Explicit enum value must only be a literal value (string or number) or a bitwise expression.`, + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowBitwiseExpressions: { + type: 'boolean', + description: 'Whether to allow using bitwise expressions in enum initializers.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowBitwiseExpressions: false, + }, + ], + create(context, [{ allowBitwiseExpressions }]) { + function isIdentifierWithName(node, name) { + return node.type === utils_1.AST_NODE_TYPES.Identifier && node.name === name; + } + function hasEnumMember(decl, name) { + return decl.body.members.some(member => isIdentifierWithName(member.id, name) || + (member.id.type === utils_1.AST_NODE_TYPES.Literal && + (0, util_1.getStaticStringValue)(member.id) === name)); + } + function isSelfEnumMember(decl, node) { + if (node.type === utils_1.AST_NODE_TYPES.Identifier) { + return hasEnumMember(decl, node.name); + } + if (node.type === utils_1.AST_NODE_TYPES.MemberExpression && + isIdentifierWithName(node.object, decl.id.name)) { + if (node.property.type === utils_1.AST_NODE_TYPES.Identifier) { + return hasEnumMember(decl, node.property.name); + } + if (node.computed) { + const propertyName = (0, util_1.getStaticStringValue)(node.property); + if (propertyName) { + return hasEnumMember(decl, propertyName); + } + } + } + return false; + } + return { + TSEnumMember(node) { + // If there is no initializer, then this node is just the name of the member, so ignore. + if (node.initializer == null) { + return; + } + const declaration = node.parent.parent; + function isAllowedInitializerExpressionRecursive(node, partOfBitwiseComputation) { + // You can only refer to an enum member if it's part of a bitwise computation. + // so C = B isn't allowed (special case), but C = A | B is. + if (partOfBitwiseComputation && isSelfEnumMember(declaration, node)) { + return true; + } + switch (node.type) { + // any old literal + case utils_1.AST_NODE_TYPES.Literal: + return true; + // TemplateLiteral without expressions + case utils_1.AST_NODE_TYPES.TemplateLiteral: + return node.expressions.length === 0; + case utils_1.AST_NODE_TYPES.UnaryExpression: + // +123, -123, etc. + if (['-', '+'].includes(node.operator)) { + return isAllowedInitializerExpressionRecursive(node.argument, partOfBitwiseComputation); + } + if (allowBitwiseExpressions) { + return (node.operator === '~' && + isAllowedInitializerExpressionRecursive(node.argument, true)); + } + return false; + case utils_1.AST_NODE_TYPES.BinaryExpression: + if (allowBitwiseExpressions) { + return (['&', '^', '<<', '>>', '>>>', '|'].includes(node.operator) && + isAllowedInitializerExpressionRecursive(node.left, true) && + isAllowedInitializerExpressionRecursive(node.right, true)); + } + return false; + default: + return false; + } + } + if (isAllowedInitializerExpressionRecursive(node.initializer, false)) { + return; + } + context.report({ + node: node.id, + messageId: allowBitwiseExpressions + ? 'notLiteralOrBitwiseExpression' + : 'notLiteral', + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-namespace-keyword.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-namespace-keyword.d.ts new file mode 100644 index 00000000..8fab3389 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-namespace-keyword.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"useNamespace", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=prefer-namespace-keyword.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-namespace-keyword.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-namespace-keyword.d.ts.map new file mode 100644 index 00000000..208d0565 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-namespace-keyword.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-namespace-keyword.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-namespace-keyword.ts"],"names":[],"mappings":";AAIA,wBA2CG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-namespace-keyword.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-namespace-keyword.js new file mode 100644 index 00000000..f606def3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-namespace-keyword.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-namespace-keyword', + meta: { + type: 'suggestion', + docs: { + description: 'Require using `namespace` keyword over `module` keyword to declare custom TypeScript modules', + recommended: 'recommended', + }, + fixable: 'code', + messages: { + useNamespace: "Use 'namespace' instead of 'module' to declare custom TypeScript modules.", + }, + schema: [], + }, + defaultOptions: [], + create(context) { + return { + TSModuleDeclaration(node) { + // Do nothing if the name is a string. + if (node.id.type === utils_1.AST_NODE_TYPES.Literal) { + return; + } + // Get tokens of the declaration header. + const moduleType = context.sourceCode.getTokenBefore(node.id); + if (moduleType && + moduleType.type === utils_1.AST_TOKEN_TYPES.Identifier && + moduleType.value === 'module') { + context.report({ + node, + messageId: 'useNamespace', + fix(fixer) { + return fixer.replaceText(moduleType, 'namespace'); + }, + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-nullish-coalescing.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-nullish-coalescing.d.ts new file mode 100644 index 00000000..27ec6831 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-nullish-coalescing.d.ts @@ -0,0 +1,21 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = [ + { + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean; + ignoreBooleanCoercion?: boolean; + ignoreConditionalTests?: boolean; + ignoreIfStatements?: boolean; + ignoreMixedLogicalExpressions?: boolean; + ignorePrimitives?: true | { + bigint?: boolean; + boolean?: boolean; + number?: boolean; + string?: boolean; + }; + ignoreTernaryTests?: boolean; + } +]; +export type MessageIds = 'noStrictNullCheck' | 'preferNullishOverAssignment' | 'preferNullishOverOr' | 'preferNullishOverTernary' | 'suggestNullish'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=prefer-nullish-coalescing.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-nullish-coalescing.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-nullish-coalescing.d.ts.map new file mode 100644 index 00000000..9fbf097e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-nullish-coalescing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-nullish-coalescing.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-nullish-coalescing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAyCnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,sDAAsD,CAAC,EAAE,OAAO,CAAC;QACjE,qBAAqB,CAAC,EAAE,OAAO,CAAC;QAChC,sBAAsB,CAAC,EAAE,OAAO,CAAC;QACjC,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,6BAA6B,CAAC,EAAE,OAAO,CAAC;QACxC,gBAAgB,CAAC,EACb,IAAI,GACJ;YACE,MAAM,CAAC,EAAE,OAAO,CAAC;YACjB,OAAO,CAAC,EAAE,OAAO,CAAC;YAClB,MAAM,CAAC,EAAE,OAAO,CAAC;YACjB,MAAM,CAAC,EAAE,OAAO,CAAC;SAClB,CAAC;QACN,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAClB,mBAAmB,GACnB,6BAA6B,GAC7B,qBAAqB,GACrB,0BAA0B,GAC1B,gBAAgB,CAAC;;AAErB,wBA+kBG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-nullish-coalescing.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-nullish-coalescing.js new file mode 100644 index 00000000..5e781ebb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-nullish-coalescing.js @@ -0,0 +1,645 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const getWrappedCode_1 = require("../util/getWrappedCode"); +const isMemberAccessLike = (0, util_1.isNodeOfTypes)([ + utils_1.AST_NODE_TYPES.ChainExpression, + utils_1.AST_NODE_TYPES.Identifier, + utils_1.AST_NODE_TYPES.MemberExpression, +]); +const isNullLiteralOrUndefinedIdentifier = (node) => (0, util_1.isNullLiteral)(node) || (0, util_1.isUndefinedIdentifier)(node); +const isNodeNullishComparison = (node) => isNullLiteralOrUndefinedIdentifier(node.left) && + isNullLiteralOrUndefinedIdentifier(node.right); +exports.default = (0, util_1.createRule)({ + name: 'prefer-nullish-coalescing', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce using the nullish coalescing operator instead of logical assignments or chaining', + recommended: 'stylistic', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + noStrictNullCheck: 'This rule requires the `strictNullChecks` compiler option to be turned on to function correctly.', + preferNullishOverAssignment: 'Prefer using nullish coalescing operator (`??{{ equals }}`) instead of an assignment expression, as it is simpler to read.', + preferNullishOverOr: 'Prefer using nullish coalescing operator (`??{{ equals }}`) instead of a logical {{ description }} (`||{{ equals }}`), as it is a safer operator.', + preferNullishOverTernary: 'Prefer using nullish coalescing operator (`??{{ equals }}`) instead of a ternary expression, as it is simpler to read.', + suggestNullish: 'Fix to nullish coalescing operator (`??{{ equals }}`).', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: { + type: 'boolean', + description: 'Unless this is set to `true`, the rule will error on every file whose `tsconfig.json` does _not_ have the `strictNullChecks` compiler option (or `strict`) set to `true`.', + }, + ignoreBooleanCoercion: { + type: 'boolean', + description: 'Whether to ignore arguments to the `Boolean` constructor', + }, + ignoreConditionalTests: { + type: 'boolean', + description: 'Whether to ignore cases that are located within a conditional test.', + }, + ignoreIfStatements: { + type: 'boolean', + description: 'Whether to ignore any if statements that could be simplified by using the nullish coalescing operator.', + }, + ignoreMixedLogicalExpressions: { + type: 'boolean', + description: 'Whether to ignore any logical or expressions that are part of a mixed logical expression (with `&&`).', + }, + ignorePrimitives: { + description: 'Whether to ignore all (`true`) or some (an object with properties) primitive types.', + oneOf: [ + { + type: 'object', + description: 'Which primitives types may be ignored.', + properties: { + bigint: { + type: 'boolean', + description: 'Ignore bigint primitive types.', + }, + boolean: { + type: 'boolean', + description: 'Ignore boolean primitive types.', + }, + number: { + type: 'boolean', + description: 'Ignore number primitive types.', + }, + string: { + type: 'boolean', + description: 'Ignore string primitive types.', + }, + }, + }, + { + type: 'boolean', + description: 'Ignore all primitive types.', + enum: [true], + }, + ], + }, + ignoreTernaryTests: { + type: 'boolean', + description: 'Whether to ignore any ternary expressions that could be simplified by using the nullish coalescing operator.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false, + ignoreBooleanCoercion: false, + ignoreConditionalTests: true, + ignoreIfStatements: false, + ignoreMixedLogicalExpressions: false, + ignorePrimitives: { + bigint: false, + boolean: false, + number: false, + string: false, + }, + ignoreTernaryTests: false, + }, + ], + create(context, [{ allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing, ignoreBooleanCoercion, ignoreConditionalTests, ignoreIfStatements, ignoreMixedLogicalExpressions, ignorePrimitives, ignoreTernaryTests, },]) { + const parserServices = (0, util_1.getParserServices)(context); + const compilerOptions = parserServices.program.getCompilerOptions(); + const isStrictNullChecks = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks'); + if (!isStrictNullChecks && + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing !== true) { + context.report({ + loc: { + start: { column: 0, line: 0 }, + end: { column: 0, line: 0 }, + }, + messageId: 'noStrictNullCheck', + }); + } + /** + * Checks whether a type tested for truthiness is eligible for conversion to + * a nullishness check, taking into account the rule's configuration. + */ + function isTypeEligibleForPreferNullish(type) { + if (!(0, util_1.isNullableType)(type)) { + return false; + } + const ignorableFlags = [ + /* eslint-disable @typescript-eslint/no-non-null-assertion */ + (ignorePrimitives === true || ignorePrimitives.bigint) && + ts.TypeFlags.BigIntLike, + (ignorePrimitives === true || ignorePrimitives.boolean) && + ts.TypeFlags.BooleanLike, + (ignorePrimitives === true || ignorePrimitives.number) && + ts.TypeFlags.NumberLike, + (ignorePrimitives === true || ignorePrimitives.string) && + ts.TypeFlags.StringLike, + /* eslint-enable @typescript-eslint/no-non-null-assertion */ + ] + .filter((flag) => typeof flag === 'number') + .reduce((previous, flag) => previous | flag, 0); + if (ignorableFlags === 0) { + // any types are eligible for conversion. + return true; + } + // if the type is `any` or `unknown` we can't make any assumptions + // about the value, so it could be any primitive, even though the flags + // won't be set. + // + // technically, this is true of `void` as well, however, it's a TS error + // to test `void` for truthiness, so we don't need to bother checking for + // it in valid code. + if (tsutils.isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { + return false; + } + if (tsutils + .typeConstituents(type) + .some(t => tsutils + .intersectionConstituents(t) + .some(t => tsutils.isTypeFlagSet(t, ignorableFlags)))) { + return false; + } + return true; + } + /** + * Determines whether a control flow construct that uses the truthiness of + * a test expression is eligible for conversion to the nullish coalescing + * operator, taking into account (both dependent on the rule's configuration): + * 1. Whether the construct is in a permitted syntactic context + * 2. Whether the type of the test expression is deemed eligible for + * conversion + * + * @param node The overall node to be converted (e.g. `a || b` or `a ? a : b`) + * @param testNode The node being tested (i.e. `a`) + */ + function isTruthinessCheckEligibleForPreferNullish({ node, testNode, }) { + const testType = parserServices.getTypeAtLocation(testNode); + if (!isTypeEligibleForPreferNullish(testType)) { + return false; + } + if (ignoreConditionalTests === true && isConditionalTest(node)) { + return false; + } + if (ignoreBooleanCoercion === true && + isBooleanConstructorContext(node, context)) { + return false; + } + return true; + } + function checkAndFixWithPreferNullishOverOr(node, description, equals) { + if (!isTruthinessCheckEligibleForPreferNullish({ + node, + testNode: node.left, + })) { + return; + } + if (ignoreMixedLogicalExpressions === true && + isMixedLogicalExpression(node)) { + return; + } + const barBarOperator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.left, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && + token.value === node.operator), util_1.NullThrowsReasons.MissingToken('operator', node.type)); + function* fix(fixer) { + if ((0, util_1.isLogicalOrOperator)(node.parent)) { + // '&&' and '??' operations cannot be mixed without parentheses (e.g. a && b ?? c) + if (node.left.type === utils_1.AST_NODE_TYPES.LogicalExpression && + !(0, util_1.isLogicalOrOperator)(node.left.left)) { + yield fixer.insertTextBefore(node.left.right, '('); + } + else { + yield fixer.insertTextBefore(node.left, '('); + } + yield fixer.insertTextAfter(node.right, ')'); + } + yield fixer.replaceText(barBarOperator, node.operator.replace('||', '??')); + } + context.report({ + node: barBarOperator, + messageId: 'preferNullishOverOr', + data: { description, equals }, + suggest: [ + { + messageId: 'suggestNullish', + data: { equals }, + fix, + }, + ], + }); + } + function getNullishCoalescingParams(node, nonNullishNode, nodesInsideTestExpression, operator) { + let nullishCoalescingLeftNode; + let hasTruthinessCheck = false; + let hasNullCheckWithoutTruthinessCheck = false; + let hasUndefinedCheckWithoutTruthinessCheck = false; + if (!nodesInsideTestExpression.length) { + hasTruthinessCheck = true; + nullishCoalescingLeftNode = + node.test.type === utils_1.AST_NODE_TYPES.UnaryExpression + ? node.test.argument + : node.test; + if (!areNodesSimilarMemberAccess(nullishCoalescingLeftNode, nonNullishNode)) { + return { isFixable: false }; + } + } + else { + // we check that the test only contains null, undefined and the identifier + for (const testNode of nodesInsideTestExpression) { + if ((0, util_1.isNullLiteral)(testNode)) { + hasNullCheckWithoutTruthinessCheck = true; + } + else if ((0, util_1.isUndefinedIdentifier)(testNode)) { + hasUndefinedCheckWithoutTruthinessCheck = true; + } + else if (areNodesSimilarMemberAccess(testNode, nonNullishNode)) { + // Only consider the first expression in a multi-part nullish check, + // as subsequent expressions might not require all the optional chaining operators. + // For example: a?.b?.c !== undefined && a.b.c !== null ? a.b.c : 'foo'; + // This works because `node.test` is always evaluated first in the loop + // and has the same or more necessary optional chaining operators + // than `node.alternate` or `node.consequent`. + nullishCoalescingLeftNode ??= testNode; + } + else { + return { isFixable: false }; + } + } + } + if (!nullishCoalescingLeftNode) { + return { isFixable: false }; + } + const isFixable = (() => { + if (hasTruthinessCheck) { + return isTruthinessCheckEligibleForPreferNullish({ + node, + testNode: nullishCoalescingLeftNode, + }); + } + // it is fixable if we check for both null and undefined, or not if neither + if (hasUndefinedCheckWithoutTruthinessCheck === + hasNullCheckWithoutTruthinessCheck) { + return hasUndefinedCheckWithoutTruthinessCheck; + } + // it is fixable if we loosely check for either null or undefined + if (['==', '!='].includes(operator)) { + return true; + } + const type = parserServices.getTypeAtLocation(nullishCoalescingLeftNode); + const flags = (0, util_1.getTypeFlags)(type); + if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { + return false; + } + const hasNullType = (flags & ts.TypeFlags.Null) !== 0; + // it is fixable if we check for undefined and the type is not nullable + if (hasUndefinedCheckWithoutTruthinessCheck && !hasNullType) { + return true; + } + const hasUndefinedType = (flags & ts.TypeFlags.Undefined) !== 0; + // it is fixable if we check for null and the type can't be undefined + return hasNullCheckWithoutTruthinessCheck && !hasUndefinedType; + })(); + return isFixable + ? { isFixable: true, nullishCoalescingLeftNode } + : { isFixable: false }; + } + return { + 'AssignmentExpression[operator = "||="]'(node) { + checkAndFixWithPreferNullishOverOr(node, 'assignment', '='); + }, + ConditionalExpression(node) { + if (ignoreTernaryTests) { + return; + } + const { nodesInsideTestExpression, operator } = getOperatorAndNodesInsideTestExpression(node); + if (operator == null) { + return; + } + const { nonNullishBranch, nullishBranch } = getBranchNodes(node, operator); + const nullishCoalescingParams = getNullishCoalescingParams(node, nonNullishBranch, nodesInsideTestExpression, operator); + if (nullishCoalescingParams.isFixable) { + context.report({ + node, + messageId: 'preferNullishOverTernary', + // TODO: also account for = in the ternary clause + data: { equals: '' }, + suggest: [ + { + messageId: 'suggestNullish', + data: { equals: '' }, + fix(fixer) { + const nullishBranchText = (0, util_1.getTextWithParentheses)(context.sourceCode, nullishBranch); + const rightOperandReplacement = (0, util_1.isParenthesized)(nullishBranch, context.sourceCode) + ? nullishBranchText + : (0, getWrappedCode_1.getWrappedCode)(nullishBranchText, (0, util_1.getOperatorPrecedenceForNode)(nullishBranch), util_1.OperatorPrecedence.Coalesce); + return fixer.replaceText(node, `${(0, util_1.getTextWithParentheses)(context.sourceCode, nullishCoalescingParams.nullishCoalescingLeftNode)} ?? ${rightOperandReplacement}`); + }, + }, + ], + }); + } + }, + IfStatement(node) { + if (ignoreIfStatements || node.alternate != null) { + return; + } + let assignmentExpression; + if (node.consequent.type === utils_1.AST_NODE_TYPES.BlockStatement && + node.consequent.body.length === 1 && + node.consequent.body[0].type === utils_1.AST_NODE_TYPES.ExpressionStatement) { + assignmentExpression = node.consequent.body[0].expression; + } + else if (node.consequent.type === utils_1.AST_NODE_TYPES.ExpressionStatement) { + assignmentExpression = node.consequent.expression; + } + if (!assignmentExpression || + assignmentExpression.type !== utils_1.AST_NODE_TYPES.AssignmentExpression || + !isMemberAccessLike(assignmentExpression.left)) { + return; + } + const nullishCoalescingLeftNode = assignmentExpression.left; + const nullishCoalescingRightNode = assignmentExpression.right; + const { nodesInsideTestExpression, operator } = getOperatorAndNodesInsideTestExpression(node); + if (operator == null || !['!', '==', '==='].includes(operator)) { + return; + } + const nullishCoalescingParams = getNullishCoalescingParams(node, nullishCoalescingLeftNode, nodesInsideTestExpression, operator); + if (nullishCoalescingParams.isFixable) { + // Handle comments + const isConsequentNodeBlockStatement = node.consequent.type === utils_1.AST_NODE_TYPES.BlockStatement; + const commentsBefore = formatComments(context.sourceCode.getCommentsBefore(assignmentExpression), isConsequentNodeBlockStatement ? '\n' : ' '); + const commentsAfter = isConsequentNodeBlockStatement + ? formatComments(context.sourceCode.getCommentsAfter(assignmentExpression.parent), '\n') + : ''; + context.report({ + node, + messageId: 'preferNullishOverAssignment', + data: { equals: '=' }, + suggest: [ + { + messageId: 'suggestNullish', + data: { equals: '=' }, + fix(fixer) { + const fixes = []; + if (commentsBefore) { + fixes.push(fixer.insertTextBefore(node, commentsBefore)); + } + fixes.push(fixer.replaceText(node, `${(0, util_1.getTextWithParentheses)(context.sourceCode, nullishCoalescingLeftNode)} ??= ${(0, util_1.getTextWithParentheses)(context.sourceCode, nullishCoalescingRightNode)};`)); + if (commentsAfter) { + fixes.push(fixer.insertTextAfter(node, ` ${commentsAfter.slice(0, -1)}`)); + } + return fixes; + }, + }, + ], + }); + } + }, + 'LogicalExpression[operator = "||"]'(node) { + checkAndFixWithPreferNullishOverOr(node, 'or', ''); + }, + }; + }, +}); +function isConditionalTest(node) { + const parent = node.parent; + if (parent == null) { + return false; + } + if (parent.type === utils_1.AST_NODE_TYPES.LogicalExpression) { + return isConditionalTest(parent); + } + if (parent.type === utils_1.AST_NODE_TYPES.ConditionalExpression && + (parent.consequent === node || parent.alternate === node)) { + return isConditionalTest(parent); + } + if (parent.type === utils_1.AST_NODE_TYPES.SequenceExpression && + parent.expressions.at(-1) === node) { + return isConditionalTest(parent); + } + if (parent.type === utils_1.AST_NODE_TYPES.UnaryExpression && + parent.operator === '!') { + return isConditionalTest(parent); + } + if ((parent.type === utils_1.AST_NODE_TYPES.ConditionalExpression || + parent.type === utils_1.AST_NODE_TYPES.DoWhileStatement || + parent.type === utils_1.AST_NODE_TYPES.IfStatement || + parent.type === utils_1.AST_NODE_TYPES.ForStatement || + parent.type === utils_1.AST_NODE_TYPES.WhileStatement) && + parent.test === node) { + return true; + } + return false; +} +function isBooleanConstructorContext(node, context) { + const parent = node.parent; + if (parent == null) { + return false; + } + if (parent.type === utils_1.AST_NODE_TYPES.LogicalExpression) { + return isBooleanConstructorContext(parent, context); + } + if (parent.type === utils_1.AST_NODE_TYPES.ConditionalExpression && + (parent.consequent === node || parent.alternate === node)) { + return isBooleanConstructorContext(parent, context); + } + if (parent.type === utils_1.AST_NODE_TYPES.SequenceExpression && + parent.expressions.at(-1) === node) { + return isBooleanConstructorContext(parent, context); + } + return isBuiltInBooleanCall(parent, context); +} +function isBuiltInBooleanCall(node, context) { + if (node.type === utils_1.AST_NODE_TYPES.CallExpression && + node.callee.type === utils_1.AST_NODE_TYPES.Identifier && + // eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum + node.callee.name === 'Boolean' && + node.arguments[0]) { + const scope = context.sourceCode.getScope(node); + const variable = scope.set.get(utils_1.AST_TOKEN_TYPES.Boolean); + return variable == null || variable.defs.length === 0; + } + return false; +} +function isMixedLogicalExpression(node) { + const seen = new Set(); + const queue = [node.parent, node.left, node.right]; + for (const current of queue) { + if (seen.has(current)) { + continue; + } + seen.add(current); + if (current.type === utils_1.AST_NODE_TYPES.LogicalExpression) { + if (current.operator === '&&') { + return true; + } + if (['||', '||='].includes(current.operator)) { + // check the pieces of the node to catch cases like `a || b || c && d` + queue.push(current.parent, current.left, current.right); + } + } + } + return false; +} +/** + * Checks if two TSESTree nodes have the same member access sequence, + * regardless of optional chaining differences. + * + * Note: This does not imply that the nodes are runtime-equivalent. + * + * Example: `a.b.c`, `a?.b.c`, `a.b?.c`, `(a?.b).c`, `(a.b)?.c` are considered similar. + * + * @param a First TSESTree node. + * @param b Second TSESTree node. + * @returns `true` if the nodes access members in the same order; otherwise, `false`. + */ +function areNodesSimilarMemberAccess(a, b) { + if (a.type === utils_1.AST_NODE_TYPES.MemberExpression && + b.type === utils_1.AST_NODE_TYPES.MemberExpression) { + if (!areNodesSimilarMemberAccess(a.object, b.object)) { + return false; + } + if (a.computed === b.computed) { + return (0, util_1.isNodeEqual)(a.property, b.property); + } + if (a.property.type === utils_1.AST_NODE_TYPES.Literal && + b.property.type === utils_1.AST_NODE_TYPES.Identifier) { + return a.property.value === b.property.name; + } + if (a.property.type === utils_1.AST_NODE_TYPES.Identifier && + b.property.type === utils_1.AST_NODE_TYPES.Literal) { + return a.property.name === b.property.value; + } + return false; + } + if (a.type === utils_1.AST_NODE_TYPES.ChainExpression || + b.type === utils_1.AST_NODE_TYPES.ChainExpression) { + return areNodesSimilarMemberAccess((0, util_1.skipChainExpression)(a), (0, util_1.skipChainExpression)(b)); + } + return (0, util_1.isNodeEqual)(a, b); +} +/** + * Returns the branch nodes of a conditional expression: + * - the "nonNullish branch" is the branch when test node is not nullish + * - the "nullish branch" is the branch when test node is nullish + */ +function getBranchNodes(node, operator) { + if (['', '!=', '!=='].includes(operator)) { + return { nonNullishBranch: node.consequent, nullishBranch: node.alternate }; + } + return { nonNullishBranch: node.alternate, nullishBranch: node.consequent }; +} +function getOperatorAndNodesInsideTestExpression(node) { + let operator = null; + let nodesInsideTestExpression = []; + if (isMemberAccessLike(node.test) || + node.test.type === utils_1.AST_NODE_TYPES.UnaryExpression) { + operator = getNonBinaryNodeOperator(node.test); + } + else if (node.test.type === utils_1.AST_NODE_TYPES.BinaryExpression) { + nodesInsideTestExpression = [node.test.left, node.test.right]; + if (node.test.operator === '==' || + node.test.operator === '!=' || + node.test.operator === '===' || + node.test.operator === '!==') { + operator = node.test.operator; + } + } + else if (node.test.type === utils_1.AST_NODE_TYPES.LogicalExpression && + node.test.left.type === utils_1.AST_NODE_TYPES.BinaryExpression && + node.test.right.type === utils_1.AST_NODE_TYPES.BinaryExpression) { + if (isNodeNullishComparison(node.test.left) || + isNodeNullishComparison(node.test.right)) { + return { nodesInsideTestExpression, operator }; + } + nodesInsideTestExpression = [ + node.test.left.left, + node.test.left.right, + node.test.right.left, + node.test.right.right, + ]; + if (['||', '||='].includes(node.test.operator)) { + if (node.test.left.operator === '===' && + node.test.right.operator === '===') { + operator = '==='; + } + else if (((node.test.left.operator === '===' || + node.test.right.operator === '===') && + (node.test.left.operator === '==' || + node.test.right.operator === '==')) || + (node.test.left.operator === '==' && node.test.right.operator === '==')) { + operator = '=='; + } + } + else if (node.test.operator === '&&') { + if (node.test.left.operator === '!==' && + node.test.right.operator === '!==') { + operator = '!=='; + } + else if (((node.test.left.operator === '!==' || + node.test.right.operator === '!==') && + (node.test.left.operator === '!=' || + node.test.right.operator === '!=')) || + (node.test.left.operator === '!=' && node.test.right.operator === '!=')) { + operator = '!='; + } + } + } + return { nodesInsideTestExpression, operator }; +} +function getNonBinaryNodeOperator(node) { + if (node.type !== utils_1.AST_NODE_TYPES.UnaryExpression) { + return ''; + } + if (isMemberAccessLike(node.argument) && node.operator === '!') { + return '!'; + } + return null; +} +function formatComments(comments, separator) { + return comments + .map(({ type, value }) => type === utils_1.AST_TOKEN_TYPES.Line + ? `//${value}${separator}` + : `/*${value}*/${separator}`) + .join(''); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.d.ts new file mode 100644 index 00000000..0f7bc8fc --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.d.ts @@ -0,0 +1,12 @@ +export type PreferOptionalChainMessageIds = 'optionalChainSuggest' | 'preferOptionalChain'; +export interface PreferOptionalChainOptions { + allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing?: boolean; + checkAny?: boolean; + checkBigInt?: boolean; + checkBoolean?: boolean; + checkNumber?: boolean; + checkString?: boolean; + checkUnknown?: boolean; + requireNullish?: boolean; +} +//# sourceMappingURL=PreferOptionalChainOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.d.ts.map new file mode 100644 index 00000000..d6b67a6c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PreferOptionalChainOptions.d.ts","sourceRoot":"","sources":["../../../src/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,6BAA6B,GACrC,sBAAsB,GACtB,qBAAqB,CAAC;AAE1B,MAAM,WAAW,0BAA0B;IACzC,kEAAkE,CAAC,EAAE,OAAO,CAAC;IAC7E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/PreferOptionalChainOptions.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/analyzeChain.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/analyzeChain.d.ts new file mode 100644 index 00000000..18c310ad --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/analyzeChain.d.ts @@ -0,0 +1,8 @@ +import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/utils'; +import type { RuleContext } from '@typescript-eslint/utils/ts-eslint'; +import type { ValidOperand } from './gatherLogicalOperands'; +import type { PreferOptionalChainMessageIds, PreferOptionalChainOptions } from './PreferOptionalChainOptions'; +export declare function analyzeChain(context: RuleContext, parserServices: ParserServicesWithTypeInformation, options: PreferOptionalChainOptions, node: TSESTree.Node, operator: TSESTree.LogicalExpression['operator'], chain: ValidOperand[]): void; +//# sourceMappingURL=analyzeChain.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/analyzeChain.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/analyzeChain.d.ts.map new file mode 100644 index 00000000..af7eb19a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/analyzeChain.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"analyzeChain.d.ts","sourceRoot":"","sources":["../../../src/rules/prefer-optional-chain-utils/analyzeChain.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EACjC,QAAQ,EACT,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAGV,WAAW,EAEZ,MAAM,oCAAoC,CAAC;AAM5C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,KAAK,EACV,6BAA6B,EAC7B,0BAA0B,EAC3B,MAAM,8BAA8B,CAAC;AA8etC,wBAAgB,YAAY,CAC1B,OAAO,EAAE,WAAW,CAClB,6BAA6B,EAC7B;IAAC,0BAA0B;CAAC,CAC7B,EACD,cAAc,EAAE,iCAAiC,EACjD,OAAO,EAAE,0BAA0B,EACnC,IAAI,EAAE,QAAQ,CAAC,IAAI,EACnB,QAAQ,EAAE,QAAQ,CAAC,iBAAiB,CAAC,UAAU,CAAC,EAChD,KAAK,EAAE,YAAY,EAAE,GACpB,IAAI,CA0GN"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/analyzeChain.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/analyzeChain.js new file mode 100644 index 00000000..fa38bb3f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/analyzeChain.js @@ -0,0 +1,467 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.analyzeChain = analyzeChain; +const utils_1 = require("@typescript-eslint/utils"); +const ts_api_utils_1 = require("ts-api-utils"); +const ts = __importStar(require("typescript")); +const util_1 = require("../../util"); +const checkNullishAndReport_1 = require("./checkNullishAndReport"); +const compareNodes_1 = require("./compareNodes"); +const gatherLogicalOperands_1 = require("./gatherLogicalOperands"); +function includesType(parserServices, node, typeFlagIn) { + const typeFlag = typeFlagIn | ts.TypeFlags.Any | ts.TypeFlags.Unknown; + const types = (0, ts_api_utils_1.unionConstituents)(parserServices.getTypeAtLocation(node)); + for (const type of types) { + if ((0, util_1.isTypeFlagSet)(type, typeFlag)) { + return true; + } + } + return false; +} +const analyzeAndChainOperand = (parserServices, operand, index, chain) => { + switch (operand.comparisonType) { + case gatherLogicalOperands_1.NullishComparisonType.Boolean: { + const nextOperand = chain.at(index + 1); + if (nextOperand?.comparisonType === + gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualNull && + operand.comparedName.type === utils_1.AST_NODE_TYPES.Identifier) { + return null; + } + return [operand]; + } + case gatherLogicalOperands_1.NullishComparisonType.NotEqualNullOrUndefined: + return [operand]; + case gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualNull: { + // handle `x !== null && x !== undefined` + const nextOperand = chain.at(index + 1); + if (nextOperand?.comparisonType === + gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualUndefined && + (0, compareNodes_1.compareNodes)(operand.comparedName, nextOperand.comparedName) === + compareNodes_1.NodeComparisonResult.Equal) { + return [operand, nextOperand]; + } + if (includesType(parserServices, operand.comparedName, ts.TypeFlags.Undefined)) { + // we know the next operand is not an `undefined` check and that this + // operand includes `undefined` - which means that making this an + // optional chain would change the runtime behavior of the expression + return null; + } + return [operand]; + } + case gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualUndefined: { + // handle `x !== undefined && x !== null` + const nextOperand = chain.at(index + 1); + if (nextOperand?.comparisonType === + gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualNull && + (0, compareNodes_1.compareNodes)(operand.comparedName, nextOperand.comparedName) === + compareNodes_1.NodeComparisonResult.Equal) { + return [operand, nextOperand]; + } + if (includesType(parserServices, operand.comparedName, ts.TypeFlags.Null)) { + // we know the next operand is not a `null` check and that this + // operand includes `null` - which means that making this an + // optional chain would change the runtime behavior of the expression + return null; + } + return [operand]; + } + default: + return null; + } +}; +const analyzeOrChainOperand = (parserServices, operand, index, chain) => { + switch (operand.comparisonType) { + case gatherLogicalOperands_1.NullishComparisonType.NotBoolean: + case gatherLogicalOperands_1.NullishComparisonType.EqualNullOrUndefined: + return [operand]; + case gatherLogicalOperands_1.NullishComparisonType.StrictEqualNull: { + // handle `x === null || x === undefined` + const nextOperand = chain.at(index + 1); + if (nextOperand?.comparisonType === + gatherLogicalOperands_1.NullishComparisonType.StrictEqualUndefined && + (0, compareNodes_1.compareNodes)(operand.comparedName, nextOperand.comparedName) === + compareNodes_1.NodeComparisonResult.Equal) { + return [operand, nextOperand]; + } + if (includesType(parserServices, operand.comparedName, ts.TypeFlags.Undefined)) { + // we know the next operand is not an `undefined` check and that this + // operand includes `undefined` - which means that making this an + // optional chain would change the runtime behavior of the expression + return null; + } + return [operand]; + } + case gatherLogicalOperands_1.NullishComparisonType.StrictEqualUndefined: { + // handle `x === undefined || x === null` + const nextOperand = chain.at(index + 1); + if (nextOperand?.comparisonType === gatherLogicalOperands_1.NullishComparisonType.StrictEqualNull && + (0, compareNodes_1.compareNodes)(operand.comparedName, nextOperand.comparedName) === + compareNodes_1.NodeComparisonResult.Equal) { + return [operand, nextOperand]; + } + if (includesType(parserServices, operand.comparedName, ts.TypeFlags.Null)) { + // we know the next operand is not a `null` check and that this + // operand includes `null` - which means that making this an + // optional chain would change the runtime behavior of the expression + return null; + } + return [operand]; + } + default: + return null; + } +}; +/** + * Returns the range that needs to be reported from the chain. + * @param chain The chain of logical expressions. + * @param boundary The boundary range that the range to report cannot fall outside. + * @param sourceCode The source code to get tokens. + * @returns The range to report. + */ +function getReportRange(chain, boundary, sourceCode) { + const leftNode = chain[0].node; + const rightNode = chain[chain.length - 1].node; + let leftMost = (0, util_1.nullThrows)(sourceCode.getFirstToken(leftNode), util_1.NullThrowsReasons.MissingToken('any token', leftNode.type)); + let rightMost = (0, util_1.nullThrows)(sourceCode.getLastToken(rightNode), util_1.NullThrowsReasons.MissingToken('any token', rightNode.type)); + while (leftMost.range[0] > boundary[0]) { + const token = sourceCode.getTokenBefore(leftMost); + if (!token || !(0, util_1.isOpeningParenToken)(token) || token.range[0] < boundary[0]) { + break; + } + leftMost = token; + } + while (rightMost.range[1] < boundary[1]) { + const token = sourceCode.getTokenAfter(rightMost); + if (!token || !(0, util_1.isClosingParenToken)(token) || token.range[1] > boundary[1]) { + break; + } + rightMost = token; + } + return [leftMost.range[0], rightMost.range[1]]; +} +function getReportDescriptor(sourceCode, parserServices, node, operator, options, chain) { + const lastOperand = chain[chain.length - 1]; + let useSuggestionFixer; + if (options.allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing === + true) { + // user has opted-in to the unsafe behavior + useSuggestionFixer = false; + } + // optional chain specifically will union `undefined` into the final type + // so we need to make sure that there is at least one operand that includes + // `undefined`, or else we're going to change the final type - which is + // unsafe and might cause downstream type errors. + else if (lastOperand.comparisonType === gatherLogicalOperands_1.NullishComparisonType.EqualNullOrUndefined || + lastOperand.comparisonType === + gatherLogicalOperands_1.NullishComparisonType.NotEqualNullOrUndefined || + lastOperand.comparisonType === gatherLogicalOperands_1.NullishComparisonType.StrictEqualUndefined || + lastOperand.comparisonType === + gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualUndefined || + (operator === '||' && + lastOperand.comparisonType === gatherLogicalOperands_1.NullishComparisonType.NotBoolean)) { + // we know the last operand is an equality check - so the change in types + // DOES NOT matter and will not change the runtime result or cause a type + // check error + useSuggestionFixer = false; + } + else { + useSuggestionFixer = true; + for (const operand of chain) { + if (includesType(parserServices, operand.node, ts.TypeFlags.Undefined)) { + useSuggestionFixer = false; + break; + } + } + // TODO - we could further reduce the false-positive rate of this check by + // checking for cases where the change in types don't matter like + // the test location of an if/while/etc statement. + // but it's quite complex to do this without false-negatives, so + // for now we'll just be over-eager with our matching. + // + // it's MUCH better to false-positive here and only provide a + // suggestion fixer, rather than false-negative and autofix to + // broken code. + } + // In its most naive form we could just slap `?.` for every single part of the + // chain. However this would be undesirable because it'd create unnecessary + // conditions in the user's code where there were none before - and it would + // cause errors with rules like our `no-unnecessary-condition`. + // + // Instead we want to include the minimum number of `?.` required to correctly + // unify the code into a single chain. Naively you might think that we can + // just take the final operand add `?.` after the locations from the previous + // operands - however this won't be correct either because earlier operands + // can include a necessary `?.` that's not needed or included in a later + // operand. + // + // So instead what we need to do is to start at the first operand and + // iteratively diff it against the next operand, and add the difference to the + // first operand. + // + // eg + // `foo && foo.bar && foo.bar.baz?.bam && foo.bar.baz.bam()` + // 1) `foo` + // 2) diff(`foo`, `foo.bar`) = `.bar` + // 3) result = `foo?.bar` + // 4) diff(`foo.bar`, `foo.bar.baz?.bam`) = `.baz?.bam` + // 5) result = `foo?.bar?.baz?.bam` + // 6) diff(`foo.bar.baz?.bam`, `foo.bar.baz.bam()`) = `()` + // 7) result = `foo?.bar?.baz?.bam?.()` + const parts = []; + for (const current of chain) { + const nextOperand = flattenChainExpression(sourceCode, current.comparedName); + const diff = nextOperand.slice(parts.length); + if (diff.length > 0) { + if (parts.length > 0) { + // we need to make the first operand of the diff optional so it matches the + // logic before merging + // foo.bar && foo.bar.baz + // diff = .baz + // result = foo.bar?.baz + diff[0].optional = true; + } + parts.push(...diff); + } + } + let newCode = parts + .map(part => { + let str = ''; + if (part.optional) { + str += '?.'; + } + else { + if (part.nonNull) { + str += '!'; + } + if (part.requiresDot) { + str += '.'; + } + } + if (part.precedence !== util_1.OperatorPrecedence.Invalid && + part.precedence < util_1.OperatorPrecedence.Member) { + str += `(${part.text})`; + } + else { + str += part.text; + } + return str; + }) + .join(''); + if (lastOperand.node.type === utils_1.AST_NODE_TYPES.BinaryExpression) { + // retain the ending comparison for cases like + // x && x.a != null + // x && typeof x.a !== 'undefined' + const operator = lastOperand.node.operator; + const { left, right } = (() => { + if (lastOperand.isYoda) { + const unaryOperator = lastOperand.node.right.type === utils_1.AST_NODE_TYPES.UnaryExpression + ? `${lastOperand.node.right.operator} ` + : ''; + return { + left: sourceCode.getText(lastOperand.node.left), + right: unaryOperator + newCode, + }; + } + const unaryOperator = lastOperand.node.left.type === utils_1.AST_NODE_TYPES.UnaryExpression + ? `${lastOperand.node.left.operator} ` + : ''; + return { + left: unaryOperator + newCode, + right: sourceCode.getText(lastOperand.node.right), + }; + })(); + newCode = `${left} ${operator} ${right}`; + } + else if (lastOperand.comparisonType === gatherLogicalOperands_1.NullishComparisonType.NotBoolean) { + newCode = `!${newCode}`; + } + const reportRange = getReportRange(chain, node.range, sourceCode); + const fix = fixer => fixer.replaceTextRange(reportRange, newCode); + return { + loc: { + end: sourceCode.getLocFromIndex(reportRange[1]), + start: sourceCode.getLocFromIndex(reportRange[0]), + }, + messageId: 'preferOptionalChain', + ...(0, util_1.getFixOrSuggest)({ + fixOrSuggest: useSuggestionFixer ? 'suggest' : 'fix', + suggestion: { + fix, + messageId: 'optionalChainSuggest', + }, + }), + }; + function flattenChainExpression(sourceCode, node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.ChainExpression: + return flattenChainExpression(sourceCode, node.expression); + case utils_1.AST_NODE_TYPES.CallExpression: { + const argumentsText = (() => { + const closingParenToken = (0, util_1.nullThrows)(sourceCode.getLastToken(node), util_1.NullThrowsReasons.MissingToken('closing parenthesis', node.type)); + const openingParenToken = (0, util_1.nullThrows)(sourceCode.getFirstTokenBetween(node.typeArguments ?? node.callee, closingParenToken, util_1.isOpeningParenToken), util_1.NullThrowsReasons.MissingToken('opening parenthesis', node.type)); + return sourceCode.text.substring(openingParenToken.range[0], closingParenToken.range[1]); + })(); + const typeArgumentsText = (() => { + if (node.typeArguments == null) { + return ''; + } + return sourceCode.getText(node.typeArguments); + })(); + return [ + ...flattenChainExpression(sourceCode, node.callee), + { + nonNull: false, + optional: node.optional, + // no precedence for this + precedence: util_1.OperatorPrecedence.Invalid, + requiresDot: false, + text: typeArgumentsText + argumentsText, + }, + ]; + } + case utils_1.AST_NODE_TYPES.MemberExpression: { + const propertyText = sourceCode.getText(node.property); + return [ + ...flattenChainExpression(sourceCode, node.object), + { + nonNull: node.object.type === utils_1.AST_NODE_TYPES.TSNonNullExpression, + optional: node.optional, + precedence: node.computed + ? // computed is already wrapped in [] so no need to wrap in () as well + util_1.OperatorPrecedence.Invalid + : (0, util_1.getOperatorPrecedenceForNode)(node.property), + requiresDot: !node.computed, + text: node.computed ? `[${propertyText}]` : propertyText, + }, + ]; + } + case utils_1.AST_NODE_TYPES.TSNonNullExpression: + return flattenChainExpression(sourceCode, node.expression); + default: + return [ + { + nonNull: false, + optional: false, + precedence: (0, util_1.getOperatorPrecedenceForNode)(node), + requiresDot: false, + text: sourceCode.getText(node), + }, + ]; + } + } +} +function analyzeChain(context, parserServices, options, node, operator, chain) { + // need at least 2 operands in a chain for it to be a chain + if (chain.length <= 1 || + /* istanbul ignore next -- previous checks make this unreachable, but keep it for exhaustiveness check */ + operator === '??') { + return; + } + const analyzeOperand = (() => { + switch (operator) { + case '&&': + return analyzeAndChainOperand; + case '||': + return analyzeOrChainOperand; + } + })(); + // Things like x !== null && x !== undefined have two nodes, but they are + // one logical unit here, so we'll allow them to be grouped. + let subChain = []; + const maybeReportThenReset = (newChainSeed) => { + if (subChain.length > 1) { + const subChainFlat = subChain.flat(); + (0, checkNullishAndReport_1.checkNullishAndReport)(context, parserServices, options, subChainFlat.slice(0, -1).map(({ node }) => node), getReportDescriptor(context.sourceCode, parserServices, node, operator, options, subChainFlat)); + } + // we've reached the end of a chain of logical expressions + // i.e. the current operand doesn't belong to the previous chain. + // + // we don't want to throw away the current operand otherwise we will skip it + // and that can cause us to miss chains. So instead we seed the new chain + // with the current operand + // + // eg this means we can catch cases like: + // unrelated != null && foo != null && foo.bar != null; + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ first "chain" + // ^^^^^^^^^^^ newChainSeed + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ second chain + subChain = newChainSeed ? [newChainSeed] : []; + }; + for (let i = 0; i < chain.length; i += 1) { + const lastOperand = subChain.flat().at(-1); + const operand = chain[i]; + const validatedOperands = analyzeOperand(parserServices, operand, i, chain); + if (!validatedOperands) { + // TODO - #7170 + // check if the name is a superset/equal - if it is, then it likely + // intended to be part of the chain and something we should include in the + // report, eg + // foo == null || foo.bar; + // ^^^^^^^^^^^ valid OR chain + // ^^^^^^^ invalid OR chain logical, but still part of + // the chain for combination purposes + maybeReportThenReset(); + continue; + } + // in case multiple operands were consumed - make sure to correctly increment the index + i += validatedOperands.length - 1; + const currentOperand = validatedOperands[0]; + if (lastOperand) { + const comparisonResult = (0, compareNodes_1.compareNodes)(lastOperand.comparedName, + // purposely inspect and push the last operand because the prior operands don't matter + // this also means we won't false-positive in cases like + // foo !== null && foo !== undefined + validatedOperands[validatedOperands.length - 1].comparedName); + if (comparisonResult === compareNodes_1.NodeComparisonResult.Subset) { + // the operands are comparable, so we can continue searching + subChain.push(currentOperand); + } + else if (comparisonResult === compareNodes_1.NodeComparisonResult.Invalid) { + maybeReportThenReset(validatedOperands); + } + else { + // purposely don't push this case because the node is a no-op and if + // we consider it then we might report on things like + // foo && foo + } + } + else { + subChain.push(currentOperand); + } + } + // check the leftovers + maybeReportThenReset(); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/checkNullishAndReport.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/checkNullishAndReport.d.ts new file mode 100644 index 00000000..3232fa5e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/checkNullishAndReport.d.ts @@ -0,0 +1,7 @@ +import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/utils'; +import type { ReportDescriptor, RuleContext } from '@typescript-eslint/utils/ts-eslint'; +import type { PreferOptionalChainMessageIds, PreferOptionalChainOptions } from './PreferOptionalChainOptions'; +export declare function checkNullishAndReport(context: RuleContext, parserServices: ParserServicesWithTypeInformation, { requireNullish }: PreferOptionalChainOptions, maybeNullishNodes: TSESTree.Expression[], descriptor: ReportDescriptor): void; +//# sourceMappingURL=checkNullishAndReport.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/checkNullishAndReport.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/checkNullishAndReport.d.ts.map new file mode 100644 index 00000000..d827b57c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/checkNullishAndReport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"checkNullishAndReport.d.ts","sourceRoot":"","sources":["../../../src/rules/prefer-optional-chain-utils/checkNullishAndReport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EACjC,QAAQ,EACT,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EACV,gBAAgB,EAChB,WAAW,EACZ,MAAM,oCAAoC,CAAC;AAM5C,OAAO,KAAK,EACV,6BAA6B,EAC7B,0BAA0B,EAC3B,MAAM,8BAA8B,CAAC;AAEtC,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,CAClB,6BAA6B,EAC7B;IAAC,0BAA0B;CAAC,CAC7B,EACD,cAAc,EAAE,iCAAiC,EACjD,EAAE,cAAc,EAAE,EAAE,0BAA0B,EAC9C,iBAAiB,EAAE,QAAQ,CAAC,UAAU,EAAE,EACxC,UAAU,EAAE,gBAAgB,CAAC,6BAA6B,CAAC,GAC1D,IAAI,CAWN"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/checkNullishAndReport.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/checkNullishAndReport.js new file mode 100644 index 00000000..55724e06 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/checkNullishAndReport.js @@ -0,0 +1,45 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkNullishAndReport = checkNullishAndReport; +const type_utils_1 = require("@typescript-eslint/type-utils"); +const ts_api_utils_1 = require("ts-api-utils"); +const ts = __importStar(require("typescript")); +function checkNullishAndReport(context, parserServices, { requireNullish }, maybeNullishNodes, descriptor) { + if (!requireNullish || + maybeNullishNodes.some(node => (0, ts_api_utils_1.unionConstituents)(parserServices.getTypeAtLocation(node)).some(t => (0, type_utils_1.isTypeFlagSet)(t, ts.TypeFlags.Null | ts.TypeFlags.Undefined)))) { + context.report(descriptor); + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/compareNodes.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/compareNodes.d.ts new file mode 100644 index 00000000..9e960872 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/compareNodes.d.ts @@ -0,0 +1,16 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +export declare const enum NodeComparisonResult { + /** the two nodes are comparably the same */ + Equal = "Equal", + /** the left node is a subset of the right node */ + Subset = "Subset", + /** the left node is not the same or is a superset of the right node */ + Invalid = "Invalid" +} +type CompareNodesArgument = TSESTree.Node | null | undefined; +/** + * Compares two nodes' ASTs to determine if the A is equal to or a subset of B + */ +export declare function compareNodes(nodeA: CompareNodesArgument, nodeB: CompareNodesArgument): NodeComparisonResult; +export {}; +//# sourceMappingURL=compareNodes.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/compareNodes.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/compareNodes.d.ts.map new file mode 100644 index 00000000..a1717dba --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/compareNodes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"compareNodes.d.ts","sourceRoot":"","sources":["../../../src/rules/prefer-optional-chain-utils/compareNodes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAKzD,0BAAkB,oBAAoB;IACpC,4CAA4C;IAC5C,KAAK,UAAU;IACf,kDAAkD;IAClD,MAAM,WAAW;IACjB,uEAAuE;IACvE,OAAO,YAAY;CACpB;AA8GD,KAAK,oBAAoB,GAAG,QAAQ,CAAC,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;AAuQ7D;;GAEG;AACH,wBAAgB,YAAY,CAC1B,KAAK,EAAE,oBAAoB,EAC3B,KAAK,EAAE,oBAAoB,GAC1B,oBAAoB,CAqBtB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/compareNodes.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/compareNodes.js new file mode 100644 index 00000000..8ac09efa --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/compareNodes.js @@ -0,0 +1,326 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NodeComparisonResult = void 0; +exports.compareNodes = compareNodes; +const utils_1 = require("@typescript-eslint/utils"); +const visitor_keys_1 = require("@typescript-eslint/visitor-keys"); +var NodeComparisonResult; +(function (NodeComparisonResult) { + /** the two nodes are comparably the same */ + NodeComparisonResult["Equal"] = "Equal"; + /** the left node is a subset of the right node */ + NodeComparisonResult["Subset"] = "Subset"; + /** the left node is not the same or is a superset of the right node */ + NodeComparisonResult["Invalid"] = "Invalid"; +})(NodeComparisonResult || (exports.NodeComparisonResult = NodeComparisonResult = {})); +function compareArrays(arrayA, arrayB) { + if (arrayA.length !== arrayB.length) { + return NodeComparisonResult.Invalid; + } + const result = arrayA.every((elA, idx) => { + const elB = arrayB[idx]; + if (elA == null || elB == null) { + return elA === elB; + } + return compareUnknownValues(elA, elB) === NodeComparisonResult.Equal; + }); + if (result) { + return NodeComparisonResult.Equal; + } + return NodeComparisonResult.Invalid; +} +function isValidNode(x) { + return (typeof x === 'object' && + x != null && + 'type' in x && + typeof x.type === 'string'); +} +function isValidChainExpressionToLookThrough(node) { + return (!(node.parent?.type === utils_1.AST_NODE_TYPES.MemberExpression && + node.parent.object === node) && + !(node.parent?.type === utils_1.AST_NODE_TYPES.CallExpression && + node.parent.callee === node) && + node.type === utils_1.AST_NODE_TYPES.ChainExpression); +} +function compareUnknownValues(valueA, valueB) { + /* istanbul ignore if -- not possible for us to test this - it's just a sanity safeguard */ + if (valueA == null || valueB == null) { + if (valueA !== valueB) { + return NodeComparisonResult.Invalid; + } + return NodeComparisonResult.Equal; + } + /* istanbul ignore if -- not possible for us to test this - it's just a sanity safeguard */ + if (!isValidNode(valueA) || !isValidNode(valueB)) { + return NodeComparisonResult.Invalid; + } + return compareNodes(valueA, valueB); +} +function compareByVisiting(nodeA, nodeB) { + const currentVisitorKeys = visitor_keys_1.visitorKeys[nodeA.type]; + /* istanbul ignore if -- not possible for us to test this - it's just a sanity safeguard */ + if (currentVisitorKeys == null) { + // we don't know how to visit this node, so assume it's invalid to avoid false-positives / broken fixers + return NodeComparisonResult.Invalid; + } + if (currentVisitorKeys.length === 0) { + // assume nodes with no keys are constant things like keywords + return NodeComparisonResult.Equal; + } + for (const key of currentVisitorKeys) { + // @ts-expect-error - dynamic access but it's safe + const nodeAChildOrChildren = nodeA[key]; + // @ts-expect-error - dynamic access but it's safe + const nodeBChildOrChildren = nodeB[key]; + if (Array.isArray(nodeAChildOrChildren)) { + const arrayA = nodeAChildOrChildren; + const arrayB = nodeBChildOrChildren; + const result = compareArrays(arrayA, arrayB); + if (result !== NodeComparisonResult.Equal) { + return NodeComparisonResult.Invalid; + } + // fallthrough to the next key as the key was "equal" + } + else { + const result = compareUnknownValues(nodeAChildOrChildren, nodeBChildOrChildren); + if (result !== NodeComparisonResult.Equal) { + return NodeComparisonResult.Invalid; + } + // fallthrough to the next key as the key was "equal" + } + } + return NodeComparisonResult.Equal; +} +function compareNodesUncached(nodeA, nodeB) { + if (nodeA.type !== nodeB.type) { + // special cases where nodes are allowed to be non-equal + // look through a chain expression node at the top-level because it only + // exists to delimit the end of an optional chain + // + // a?.b && a.b.c + // ^^^^ ChainExpression, MemberExpression + // ^^^^^ MemberExpression + // + // except for in this class of cases + // (a?.b).c && a.b.c + // because the parentheses have runtime meaning (sad face) + if (isValidChainExpressionToLookThrough(nodeA)) { + return compareNodes(nodeA.expression, nodeB); + } + if (isValidChainExpressionToLookThrough(nodeB)) { + return compareNodes(nodeA, nodeB.expression); + } + // look through the type-only non-null assertion because its existence could + // possibly be replaced by an optional chain instead + // + // a.b! && a.b.c + // ^^^^ TSNonNullExpression + if (nodeA.type === utils_1.AST_NODE_TYPES.TSNonNullExpression) { + return compareNodes(nodeA.expression, nodeB); + } + if (nodeB.type === utils_1.AST_NODE_TYPES.TSNonNullExpression) { + return compareNodes(nodeA, nodeB.expression); + } + // special case for subset optional chains where the node types don't match, + // but we want to try comparing by discarding the "extra" code + // + // a && a.b + // ^ compare this + // a && a() + // ^ compare this + // a.b && a.b() + // ^^^ compare this + // a() && a().b + // ^^^ compare this + // import.meta && import.meta.b + // ^^^^^^^^^^^ compare this + if (nodeA.type === utils_1.AST_NODE_TYPES.CallExpression || + nodeA.type === utils_1.AST_NODE_TYPES.Identifier || + nodeA.type === utils_1.AST_NODE_TYPES.MemberExpression || + nodeA.type === utils_1.AST_NODE_TYPES.MetaProperty) { + switch (nodeB.type) { + case utils_1.AST_NODE_TYPES.MemberExpression: + if (nodeB.property.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) { + // Private identifiers in optional chaining is not currently allowed + // TODO - handle this once TS supports it (https://github.com/microsoft/TypeScript/issues/42734) + return NodeComparisonResult.Invalid; + } + if (compareNodes(nodeA, nodeB.object) !== NodeComparisonResult.Invalid) { + return NodeComparisonResult.Subset; + } + return NodeComparisonResult.Invalid; + case utils_1.AST_NODE_TYPES.CallExpression: + if (compareNodes(nodeA, nodeB.callee) !== NodeComparisonResult.Invalid) { + return NodeComparisonResult.Subset; + } + return NodeComparisonResult.Invalid; + default: + return NodeComparisonResult.Invalid; + } + } + return NodeComparisonResult.Invalid; + } + switch (nodeA.type) { + // these expressions create a new instance each time - so it makes no sense to compare the chain + case utils_1.AST_NODE_TYPES.ArrayExpression: + case utils_1.AST_NODE_TYPES.ArrowFunctionExpression: + case utils_1.AST_NODE_TYPES.ClassExpression: + case utils_1.AST_NODE_TYPES.FunctionExpression: + case utils_1.AST_NODE_TYPES.JSXElement: + case utils_1.AST_NODE_TYPES.JSXFragment: + case utils_1.AST_NODE_TYPES.NewExpression: + case utils_1.AST_NODE_TYPES.ObjectExpression: + return NodeComparisonResult.Invalid; + // chaining from assignments could change the value irrevocably - so it makes no sense to compare the chain + case utils_1.AST_NODE_TYPES.AssignmentExpression: + return NodeComparisonResult.Invalid; + case utils_1.AST_NODE_TYPES.CallExpression: { + const nodeBCall = nodeB; + // check for cases like + // foo() && foo()(bar) + // ^^^^^ nodeA + // ^^^^^^^^^^ nodeB + // we don't want to check the arguments in this case + const aSubsetOfB = compareNodes(nodeA, nodeBCall.callee); + if (aSubsetOfB !== NodeComparisonResult.Invalid) { + return NodeComparisonResult.Subset; + } + const calleeCompare = compareNodes(nodeA.callee, nodeBCall.callee); + if (calleeCompare !== NodeComparisonResult.Equal) { + return NodeComparisonResult.Invalid; + } + // NOTE - we purposely ignore optional flag because for our purposes + // foo?.bar() && foo.bar?.()?.baz + // or + // foo.bar() && foo?.bar?.()?.baz + // are going to be exactly the same + const argumentCompare = compareArrays(nodeA.arguments, nodeBCall.arguments); + if (argumentCompare !== NodeComparisonResult.Equal) { + return NodeComparisonResult.Invalid; + } + const typeParamCompare = compareNodes(nodeA.typeArguments, nodeBCall.typeArguments); + if (typeParamCompare === NodeComparisonResult.Equal) { + return NodeComparisonResult.Equal; + } + return NodeComparisonResult.Invalid; + } + case utils_1.AST_NODE_TYPES.ChainExpression: + // special case handling for ChainExpression because it's allowed to be a subset + return compareNodes(nodeA, nodeB.expression); + case utils_1.AST_NODE_TYPES.Identifier: + case utils_1.AST_NODE_TYPES.PrivateIdentifier: + if (nodeA.name === nodeB.name) { + return NodeComparisonResult.Equal; + } + return NodeComparisonResult.Invalid; + case utils_1.AST_NODE_TYPES.Literal: { + const nodeBLiteral = nodeB; + if (nodeA.raw === nodeBLiteral.raw && + nodeA.value === nodeBLiteral.value) { + return NodeComparisonResult.Equal; + } + return NodeComparisonResult.Invalid; + } + case utils_1.AST_NODE_TYPES.MemberExpression: { + const nodeBMember = nodeB; + if (nodeBMember.property.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) { + // Private identifiers in optional chaining is not currently allowed + // TODO - handle this once TS supports it (https://github.com/microsoft/TypeScript/issues/42734) + return NodeComparisonResult.Invalid; + } + // check for cases like + // foo.bar && foo.bar.baz + // ^^^^^^^ nodeA + // ^^^^^^^^^^^ nodeB + // result === Equal + // + // foo.bar && foo.bar.baz.bam + // ^^^^^^^ nodeA + // ^^^^^^^^^^^^^^^ nodeB + // result === Subset + // + // we don't want to check the property in this case + const aSubsetOfB = compareNodes(nodeA, nodeBMember.object); + if (aSubsetOfB !== NodeComparisonResult.Invalid) { + return NodeComparisonResult.Subset; + } + if (nodeA.computed !== nodeBMember.computed) { + return NodeComparisonResult.Invalid; + } + // NOTE - we purposely ignore optional flag because for our purposes + // foo?.bar && foo.bar?.baz + // or + // foo.bar && foo?.bar?.baz + // are going to be exactly the same + const objectCompare = compareNodes(nodeA.object, nodeBMember.object); + if (objectCompare !== NodeComparisonResult.Equal) { + return NodeComparisonResult.Invalid; + } + return compareNodes(nodeA.property, nodeBMember.property); + } + case utils_1.AST_NODE_TYPES.TSTemplateLiteralType: + case utils_1.AST_NODE_TYPES.TemplateLiteral: { + const nodeBTemplate = nodeB; + const areQuasisEqual = nodeA.quasis.length === nodeBTemplate.quasis.length && + nodeA.quasis.every((elA, idx) => { + const elB = nodeBTemplate.quasis[idx]; + return elA.value.cooked === elB.value.cooked; + }); + if (!areQuasisEqual) { + return NodeComparisonResult.Invalid; + } + return NodeComparisonResult.Equal; + } + case utils_1.AST_NODE_TYPES.TemplateElement: { + const nodeBElement = nodeB; + if (nodeA.value.cooked === nodeBElement.value.cooked) { + return NodeComparisonResult.Equal; + } + return NodeComparisonResult.Invalid; + } + // these aren't actually valid expressions. + // https://github.com/typescript-eslint/typescript-eslint/blob/20d7caee35ab84ae6381fdf04338c9e2b9e2bc48/packages/ast-spec/src/unions/Expression.ts#L37-L43 + case utils_1.AST_NODE_TYPES.ArrayPattern: + case utils_1.AST_NODE_TYPES.ObjectPattern: + /* istanbul ignore next */ + return NodeComparisonResult.Invalid; + // update expression returns a number and also changes the value each time - so it makes no sense to compare the chain + case utils_1.AST_NODE_TYPES.UpdateExpression: + return NodeComparisonResult.Invalid; + // yield returns the value passed to the `next` function, so it may not be the same each time - so it makes no sense to compare the chain + case utils_1.AST_NODE_TYPES.YieldExpression: + return NodeComparisonResult.Invalid; + // general-case automatic handling of nodes to save us implementing every + // single case by hand. This just iterates the visitor keys to recursively + // check the children. + // + // Any specific logic cases or short-circuits should be listed as separate + // cases so that they don't fall into this generic handling + default: + return compareByVisiting(nodeA, nodeB); + } +} +const COMPARE_NODES_CACHE = new WeakMap(); +/** + * Compares two nodes' ASTs to determine if the A is equal to or a subset of B + */ +function compareNodes(nodeA, nodeB) { + if (nodeA == null || nodeB == null) { + if (nodeA !== nodeB) { + return NodeComparisonResult.Invalid; + } + return NodeComparisonResult.Equal; + } + const cached = COMPARE_NODES_CACHE.get(nodeA)?.get(nodeB); + if (cached) { + return cached; + } + const result = compareNodesUncached(nodeA, nodeB); + let mapA = COMPARE_NODES_CACHE.get(nodeA); + if (mapA == null) { + mapA = new WeakMap(); + COMPARE_NODES_CACHE.set(nodeA, mapA); + } + mapA.set(nodeB, result); + return result; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/gatherLogicalOperands.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/gatherLogicalOperands.d.ts new file mode 100644 index 00000000..74652ede --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/gatherLogicalOperands.d.ts @@ -0,0 +1,42 @@ +import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/utils'; +import type { SourceCode } from '@typescript-eslint/utils/ts-eslint'; +import type { PreferOptionalChainOptions } from './PreferOptionalChainOptions'; +export declare const enum OperandValidity { + Valid = "Valid", + Invalid = "Invalid" +} +export declare const enum NullishComparisonType { + /** `x != null`, `x != undefined` */ + NotEqualNullOrUndefined = "NotEqualNullOrUndefined", + /** `x == null`, `x == undefined` */ + EqualNullOrUndefined = "EqualNullOrUndefined", + /** `x !== null` */ + NotStrictEqualNull = "NotStrictEqualNull", + /** `x === null` */ + StrictEqualNull = "StrictEqualNull", + /** `x !== undefined`, `typeof x !== 'undefined'` */ + NotStrictEqualUndefined = "NotStrictEqualUndefined", + /** `x === undefined`, `typeof x === 'undefined'` */ + StrictEqualUndefined = "StrictEqualUndefined", + /** `!x` */ + NotBoolean = "NotBoolean", + /** `x` */ + Boolean = "Boolean" +} +export interface ValidOperand { + comparedName: TSESTree.Node; + comparisonType: NullishComparisonType; + isYoda: boolean; + node: TSESTree.Expression; + type: OperandValidity.Valid; +} +export interface InvalidOperand { + type: OperandValidity.Invalid; +} +type Operand = InvalidOperand | ValidOperand; +export declare function gatherLogicalOperands(node: TSESTree.LogicalExpression, parserServices: ParserServicesWithTypeInformation, sourceCode: Readonly, options: PreferOptionalChainOptions): { + newlySeenLogicals: Set; + operands: Operand[]; +}; +export {}; +//# sourceMappingURL=gatherLogicalOperands.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/gatherLogicalOperands.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/gatherLogicalOperands.d.ts.map new file mode 100644 index 00000000..bba5ee6a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/gatherLogicalOperands.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"gatherLogicalOperands.d.ts","sourceRoot":"","sources":["../../../src/rules/prefer-optional-chain-utils/gatherLogicalOperands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EACjC,QAAQ,EACT,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAYrE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAS/E,0BAAkB,eAAe;IAC/B,KAAK,UAAU;IACf,OAAO,YAAY;CACpB;AACD,0BAAkB,qBAAqB;IACrC,oCAAoC;IACpC,uBAAuB,4BAA4B;IACnD,oCAAoC;IACpC,oBAAoB,yBAAyB;IAE7C,mBAAmB;IACnB,kBAAkB,uBAAuB;IACzC,mBAAmB;IACnB,eAAe,oBAAoB;IAEnC,oDAAoD;IACpD,uBAAuB,4BAA4B;IACnD,oDAAoD;IACpD,oBAAoB,yBAAyB;IAE7C,WAAW;IACX,UAAU,eAAe;IACzB,UAAU;IACV,OAAO,YAAY;CACpB;AACD,MAAM,WAAW,YAAY;IAC3B,YAAY,EAAE,QAAQ,CAAC,IAAI,CAAC;IAC5B,cAAc,EAAE,qBAAqB,CAAC;IACtC,MAAM,EAAE,OAAO,CAAC;IAChB,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC;IAC1B,IAAI,EAAE,eAAe,CAAC,KAAK,CAAC;CAC7B;AACD,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,eAAe,CAAC,OAAO,CAAC;CAC/B;AACD,KAAK,OAAO,GAAG,cAAc,GAAG,YAAY,CAAC;AAwD7C,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,QAAQ,CAAC,iBAAiB,EAChC,cAAc,EAAE,iCAAiC,EACjD,UAAU,EAAE,QAAQ,CAAC,UAAU,CAAC,EAChC,OAAO,EAAE,0BAA0B,GAClC;IACD,iBAAiB,EAAE,GAAG,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC;IACnD,QAAQ,EAAE,OAAO,EAAE,CAAC;CACrB,CA0PA"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/gatherLogicalOperands.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/gatherLogicalOperands.js new file mode 100644 index 00000000..d4595624 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain-utils/gatherLogicalOperands.js @@ -0,0 +1,319 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NullishComparisonType = exports.OperandValidity = void 0; +exports.gatherLogicalOperands = gatherLogicalOperands; +const utils_1 = require("@typescript-eslint/utils"); +const ts_api_utils_1 = require("ts-api-utils"); +const ts = __importStar(require("typescript")); +const util_1 = require("../../util"); +var ComparisonValueType; +(function (ComparisonValueType) { + ComparisonValueType["Null"] = "Null"; + ComparisonValueType["Undefined"] = "Undefined"; + ComparisonValueType["UndefinedStringLiteral"] = "UndefinedStringLiteral"; +})(ComparisonValueType || (ComparisonValueType = {})); +var OperandValidity; +(function (OperandValidity) { + OperandValidity["Valid"] = "Valid"; + OperandValidity["Invalid"] = "Invalid"; +})(OperandValidity || (exports.OperandValidity = OperandValidity = {})); +var NullishComparisonType; +(function (NullishComparisonType) { + /** `x != null`, `x != undefined` */ + NullishComparisonType["NotEqualNullOrUndefined"] = "NotEqualNullOrUndefined"; + /** `x == null`, `x == undefined` */ + NullishComparisonType["EqualNullOrUndefined"] = "EqualNullOrUndefined"; + /** `x !== null` */ + NullishComparisonType["NotStrictEqualNull"] = "NotStrictEqualNull"; + /** `x === null` */ + NullishComparisonType["StrictEqualNull"] = "StrictEqualNull"; + /** `x !== undefined`, `typeof x !== 'undefined'` */ + NullishComparisonType["NotStrictEqualUndefined"] = "NotStrictEqualUndefined"; + /** `x === undefined`, `typeof x === 'undefined'` */ + NullishComparisonType["StrictEqualUndefined"] = "StrictEqualUndefined"; + /** `!x` */ + NullishComparisonType["NotBoolean"] = "NotBoolean"; + /** `x` */ + NullishComparisonType["Boolean"] = "Boolean"; +})(NullishComparisonType || (exports.NullishComparisonType = NullishComparisonType = {})); +const NULLISH_FLAGS = ts.TypeFlags.Null | ts.TypeFlags.Undefined; +function isValidFalseBooleanCheckType(node, disallowFalseyLiteral, parserServices, options) { + const type = parserServices.getTypeAtLocation(node); + const types = (0, ts_api_utils_1.unionConstituents)(type); + if (disallowFalseyLiteral && + /* + ``` + declare const x: false | {a: string}; + x && x.a; + !x || x.a; + ``` + + We don't want to consider these two cases because the boolean expression + narrows out the non-nullish falsy cases - so converting the chain to `x?.a` + would introduce a build error + */ (types.some(t => (0, ts_api_utils_1.isBooleanLiteralType)(t) && t.intrinsicName === 'false') || + types.some(t => (0, ts_api_utils_1.isStringLiteralType)(t) && t.value === '') || + types.some(t => (0, ts_api_utils_1.isNumberLiteralType)(t) && t.value === 0) || + types.some(t => (0, ts_api_utils_1.isBigIntLiteralType)(t) && t.value.base10Value === '0'))) { + return false; + } + let allowedFlags = NULLISH_FLAGS | ts.TypeFlags.Object; + if (options.checkAny === true) { + allowedFlags |= ts.TypeFlags.Any; + } + if (options.checkUnknown === true) { + allowedFlags |= ts.TypeFlags.Unknown; + } + if (options.checkString === true) { + allowedFlags |= ts.TypeFlags.StringLike; + } + if (options.checkNumber === true) { + allowedFlags |= ts.TypeFlags.NumberLike; + } + if (options.checkBoolean === true) { + allowedFlags |= ts.TypeFlags.BooleanLike; + } + if (options.checkBigInt === true) { + allowedFlags |= ts.TypeFlags.BigIntLike; + } + return types.every(t => (0, util_1.isTypeFlagSet)(t, allowedFlags)); +} +function gatherLogicalOperands(node, parserServices, sourceCode, options) { + const result = []; + const { newlySeenLogicals, operands } = flattenLogicalOperands(node); + for (const operand of operands) { + const areMoreOperands = operand !== operands.at(-1); + switch (operand.type) { + case utils_1.AST_NODE_TYPES.BinaryExpression: { + // check for "yoda" style logical: null != x + const { comparedExpression, comparedValue, isYoda } = (() => { + // non-yoda checks are by far the most common, so check for them first + const comparedValueRight = getComparisonValueType(operand.right); + if (comparedValueRight) { + return { + comparedExpression: operand.left, + comparedValue: comparedValueRight, + isYoda: false, + }; + } + return { + comparedExpression: operand.right, + comparedValue: getComparisonValueType(operand.left), + isYoda: true, + }; + })(); + if (comparedValue === ComparisonValueType.UndefinedStringLiteral) { + if (comparedExpression.type === utils_1.AST_NODE_TYPES.UnaryExpression && + comparedExpression.operator === 'typeof') { + const argument = comparedExpression.argument; + if (argument.type === utils_1.AST_NODE_TYPES.Identifier && + // typeof window === 'undefined' + (0, util_1.isReferenceToGlobalFunction)(argument.name, argument, sourceCode)) { + result.push({ type: OperandValidity.Invalid }); + continue; + } + // typeof x.y === 'undefined' + result.push({ + comparedName: comparedExpression.argument, + comparisonType: operand.operator.startsWith('!') + ? NullishComparisonType.NotStrictEqualUndefined + : NullishComparisonType.StrictEqualUndefined, + isYoda, + node: operand, + type: OperandValidity.Valid, + }); + continue; + } + // y === 'undefined' + result.push({ type: OperandValidity.Invalid }); + continue; + } + switch (operand.operator) { + case '!=': + case '==': + if (comparedValue === ComparisonValueType.Null || + comparedValue === ComparisonValueType.Undefined) { + // x == null, x == undefined + result.push({ + comparedName: comparedExpression, + comparisonType: operand.operator.startsWith('!') + ? NullishComparisonType.NotEqualNullOrUndefined + : NullishComparisonType.EqualNullOrUndefined, + isYoda, + node: operand, + type: OperandValidity.Valid, + }); + continue; + } + // x == something :( + result.push({ type: OperandValidity.Invalid }); + continue; + case '!==': + case '===': { + const comparedName = comparedExpression; + switch (comparedValue) { + case ComparisonValueType.Null: + result.push({ + comparedName, + comparisonType: operand.operator.startsWith('!') + ? NullishComparisonType.NotStrictEqualNull + : NullishComparisonType.StrictEqualNull, + isYoda, + node: operand, + type: OperandValidity.Valid, + }); + continue; + case ComparisonValueType.Undefined: + result.push({ + comparedName, + comparisonType: operand.operator.startsWith('!') + ? NullishComparisonType.NotStrictEqualUndefined + : NullishComparisonType.StrictEqualUndefined, + isYoda, + node: operand, + type: OperandValidity.Valid, + }); + continue; + default: + // x === something :( + result.push({ type: OperandValidity.Invalid }); + continue; + } + } + } + result.push({ type: OperandValidity.Invalid }); + continue; + } + case utils_1.AST_NODE_TYPES.UnaryExpression: + if (operand.operator === '!' && + isValidFalseBooleanCheckType(operand.argument, areMoreOperands && node.operator === '||', parserServices, options)) { + result.push({ + comparedName: operand.argument, + comparisonType: NullishComparisonType.NotBoolean, + isYoda: false, + node: operand, + type: OperandValidity.Valid, + }); + continue; + } + result.push({ type: OperandValidity.Invalid }); + continue; + case utils_1.AST_NODE_TYPES.LogicalExpression: + // explicitly ignore the mixed logical expression cases + result.push({ type: OperandValidity.Invalid }); + continue; + default: + if (isValidFalseBooleanCheckType(operand, areMoreOperands && node.operator === '&&', parserServices, options)) { + result.push({ + comparedName: operand, + comparisonType: NullishComparisonType.Boolean, + isYoda: false, + node: operand, + type: OperandValidity.Valid, + }); + } + else { + result.push({ type: OperandValidity.Invalid }); + } + continue; + } + } + return { + newlySeenLogicals, + operands: result, + }; + /* + The AST is always constructed such the first element is always the deepest element. + I.e. for this code: `foo && foo.bar && foo.bar.baz && foo.bar.baz.buzz` + The AST will look like this: + { + left: { + left: { + left: foo + right: foo.bar + } + right: foo.bar.baz + } + right: foo.bar.baz.buzz + } + + So given any logical expression, we can perform a depth-first traversal to get + the operands in order. + + Note that this function purposely does not inspect mixed logical expressions + like `foo || foo.bar && foo.bar.baz` - separate selector + */ + function flattenLogicalOperands(node) { + const operands = []; + const newlySeenLogicals = new Set([node]); + const stack = [node.right, node.left]; + let current; + while ((current = stack.pop())) { + if (current.type === utils_1.AST_NODE_TYPES.LogicalExpression && + current.operator === node.operator) { + newlySeenLogicals.add(current); + stack.push(current.right); + stack.push(current.left); + } + else { + operands.push(current); + } + } + return { + newlySeenLogicals, + operands, + }; + } + function getComparisonValueType(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.Literal: + // eslint-disable-next-line eqeqeq, @typescript-eslint/internal/eqeq-nullish -- intentional exact comparison against null + if (node.value === null && node.raw === 'null') { + return ComparisonValueType.Null; + } + if (node.value === 'undefined') { + return ComparisonValueType.UndefinedStringLiteral; + } + return null; + case utils_1.AST_NODE_TYPES.Identifier: + if (node.name === 'undefined') { + return ComparisonValueType.Undefined; + } + return null; + } + return null; + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain.d.ts new file mode 100644 index 00000000..775556c4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain.d.ts @@ -0,0 +1,4 @@ +import type { PreferOptionalChainMessageIds, PreferOptionalChainOptions } from './prefer-optional-chain-utils/PreferOptionalChainOptions'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=prefer-optional-chain.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain.d.ts.map new file mode 100644 index 00000000..8fa9e94a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-optional-chain.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-optional-chain.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,6BAA6B,EAC7B,0BAA0B,EAC3B,MAAM,0DAA0D,CAAC;;AAelE,wBAkMG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain.js new file mode 100644 index 00000000..13c9c481 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-optional-chain.js @@ -0,0 +1,146 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const analyzeChain_1 = require("./prefer-optional-chain-utils/analyzeChain"); +const checkNullishAndReport_1 = require("./prefer-optional-chain-utils/checkNullishAndReport"); +const gatherLogicalOperands_1 = require("./prefer-optional-chain-utils/gatherLogicalOperands"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-optional-chain', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce using concise optional chain expressions instead of chained logical ands, negated logical ors, or empty objects', + recommended: 'stylistic', + requiresTypeChecking: true, + }, + fixable: 'code', + hasSuggestions: true, + messages: { + optionalChainSuggest: 'Change to an optional chain.', + preferOptionalChain: "Prefer using an optional chain expression instead, as it's more concise and easier to read.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing: { + type: 'boolean', + description: 'Allow autofixers that will change the return type of the expression. This option is considered unsafe as it may break the build.', + }, + checkAny: { + type: 'boolean', + description: 'Check operands that are typed as `any` when inspecting "loose boolean" operands.', + }, + checkBigInt: { + type: 'boolean', + description: 'Check operands that are typed as `bigint` when inspecting "loose boolean" operands.', + }, + checkBoolean: { + type: 'boolean', + description: 'Check operands that are typed as `boolean` when inspecting "loose boolean" operands.', + }, + checkNumber: { + type: 'boolean', + description: 'Check operands that are typed as `number` when inspecting "loose boolean" operands.', + }, + checkString: { + type: 'boolean', + description: 'Check operands that are typed as `string` when inspecting "loose boolean" operands.', + }, + checkUnknown: { + type: 'boolean', + description: 'Check operands that are typed as `unknown` when inspecting "loose boolean" operands.', + }, + requireNullish: { + type: 'boolean', + description: 'Skip operands that are not typed with `null` and/or `undefined` when inspecting "loose boolean" operands.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing: false, + checkAny: true, + checkBigInt: true, + checkBoolean: true, + checkNumber: true, + checkString: true, + checkUnknown: true, + requireNullish: false, + }, + ], + create(context, [options]) { + const parserServices = (0, util_1.getParserServices)(context); + const seenLogicals = new Set(); + return { + 'LogicalExpression[operator!="??"]'(node) { + if (seenLogicals.has(node)) { + return; + } + const { newlySeenLogicals, operands } = (0, gatherLogicalOperands_1.gatherLogicalOperands)(node, parserServices, context.sourceCode, options); + for (const logical of newlySeenLogicals) { + seenLogicals.add(logical); + } + let currentChain = []; + for (const operand of operands) { + if (operand.type === gatherLogicalOperands_1.OperandValidity.Invalid) { + (0, analyzeChain_1.analyzeChain)(context, parserServices, options, node, node.operator, currentChain); + currentChain = []; + } + else { + currentChain.push(operand); + } + } + // make sure to check whatever's left + if (currentChain.length > 0) { + (0, analyzeChain_1.analyzeChain)(context, parserServices, options, node, node.operator, currentChain); + } + }, + // specific handling for `(foo ?? {}).bar` / `(foo || {}).bar` + 'LogicalExpression[operator="||"], LogicalExpression[operator="??"]'(node) { + const leftNode = node.left; + const rightNode = node.right; + const parentNode = node.parent; + const isRightNodeAnEmptyObjectLiteral = rightNode.type === utils_1.AST_NODE_TYPES.ObjectExpression && + rightNode.properties.length === 0; + if (!isRightNodeAnEmptyObjectLiteral || + parentNode.type !== utils_1.AST_NODE_TYPES.MemberExpression || + parentNode.optional) { + return; + } + seenLogicals.add(node); + function isLeftSideLowerPrecedence() { + const logicalTsNode = parserServices.esTreeNodeToTSNodeMap.get(node); + const leftTsNode = parserServices.esTreeNodeToTSNodeMap.get(leftNode); + const leftPrecedence = (0, util_1.getOperatorPrecedence)(leftTsNode.kind, logicalTsNode.operatorToken.kind); + return leftPrecedence < util_1.OperatorPrecedence.LeftHandSide; + } + (0, checkNullishAndReport_1.checkNullishAndReport)(context, parserServices, options, [leftNode], { + node: parentNode, + messageId: 'preferOptionalChain', + suggest: [ + { + messageId: 'optionalChainSuggest', + fix: (fixer) => { + const leftNodeText = context.sourceCode.getText(leftNode); + // Any node that is made of an operator with higher or equal precedence, + const maybeWrappedLeftNode = isLeftSideLowerPrecedence() + ? `(${leftNodeText})` + : leftNodeText; + const propertyToBeOptionalText = context.sourceCode.getText(parentNode.property); + const maybeWrappedProperty = parentNode.computed + ? `[${propertyToBeOptionalText}]` + : propertyToBeOptionalText; + return fixer.replaceTextRange(parentNode.range, `${maybeWrappedLeftNode}?.${maybeWrappedProperty}`); + }, + }, + ], + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-promise-reject-errors.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-promise-reject-errors.d.ts new file mode 100644 index 00000000..c6a1244a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-promise-reject-errors.d.ts @@ -0,0 +1,11 @@ +export type MessageIds = 'rejectAnError'; +export type Options = [ + { + allowEmptyReject?: boolean; + allowThrowingAny?: boolean; + allowThrowingUnknown?: boolean; + } +]; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"rejectAnError", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=prefer-promise-reject-errors.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-promise-reject-errors.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-promise-reject-errors.d.ts.map new file mode 100644 index 00000000..57e38abf --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-promise-reject-errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-promise-reject-errors.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-promise-reject-errors.ts"],"names":[],"mappings":"AAmBA,MAAM,MAAM,UAAU,GAAG,eAAe,CAAC;AAEzC,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,gBAAgB,CAAC,EAAE,OAAO,CAAC;QAC3B,gBAAgB,CAAC,EAAE,OAAO,CAAC;QAC3B,oBAAoB,CAAC,EAAE,OAAO,CAAC;KAChC;CACF,CAAC;;AAEF,wBA4IG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-promise-reject-errors.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-promise-reject-errors.js new file mode 100644 index 00000000..bc97e1c3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-promise-reject-errors.js @@ -0,0 +1,116 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-promise-reject-errors', + meta: { + type: 'suggestion', + docs: { + description: 'Require using Error objects as Promise rejection reasons', + extendsBaseRule: true, + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + rejectAnError: 'Expected the Promise rejection reason to be an Error.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowEmptyReject: { + type: 'boolean', + description: 'Whether to allow calls to `Promise.reject()` with no arguments.', + }, + allowThrowingAny: { + type: 'boolean', + description: 'Whether to always allow throwing values typed as `any`.', + }, + allowThrowingUnknown: { + type: 'boolean', + description: 'Whether to always allow throwing values typed as `unknown`.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowEmptyReject: false, + allowThrowingAny: false, + allowThrowingUnknown: false, + }, + ], + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + function checkRejectCall(callExpression) { + const argument = callExpression.arguments.at(0); + if (argument) { + const type = services.getTypeAtLocation(argument); + if (options.allowThrowingAny && (0, util_1.isTypeAnyType)(type)) { + return; + } + if (options.allowThrowingUnknown && (0, util_1.isTypeUnknownType)(type)) { + return; + } + if ((0, util_1.isErrorLike)(services.program, type) || + (0, util_1.isReadonlyErrorLike)(services.program, type)) { + return; + } + } + else if (options.allowEmptyReject) { + return; + } + context.report({ + node: callExpression, + messageId: 'rejectAnError', + }); + } + function typeAtLocationIsLikePromise(node) { + const type = services.getTypeAtLocation(node); + return ((0, util_1.isPromiseConstructorLike)(services.program, type) || + (0, util_1.isPromiseLike)(services.program, type)); + } + return { + CallExpression(node) { + const callee = (0, util_1.skipChainExpression)(node.callee); + if (callee.type !== utils_1.AST_NODE_TYPES.MemberExpression) { + return; + } + if (!(0, util_1.isStaticMemberAccessOfValue)(callee, context, 'reject') || + !typeAtLocationIsLikePromise(callee.object)) { + return; + } + checkRejectCall(node); + }, + NewExpression(node) { + const callee = (0, util_1.skipChainExpression)(node.callee); + if (!(0, util_1.isPromiseConstructorLike)(services.program, services.getTypeAtLocation(callee))) { + return; + } + const executor = node.arguments.at(0); + if (!executor || !(0, util_1.isFunction)(executor)) { + return; + } + const rejectParamNode = executor.params.at(1); + if (!rejectParamNode || !(0, util_1.isIdentifier)(rejectParamNode)) { + return; + } + // reject param is always present in variables declared by executor + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const rejectVariable = context.sourceCode + .getDeclaredVariables(executor) + .find(variable => variable.identifiers.includes(rejectParamNode)); + rejectVariable.references.forEach(ref => { + if (ref.identifier.parent.type !== utils_1.AST_NODE_TYPES.CallExpression || + ref.identifier !== ref.identifier.parent.callee) { + return; + } + checkRejectCall(ref.identifier.parent); + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly-parameter-types.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly-parameter-types.d.ts new file mode 100644 index 00000000..95d7f43d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly-parameter-types.d.ts @@ -0,0 +1,13 @@ +import type { TypeOrValueSpecifier } from '../util'; +export type Options = [ + { + allow?: TypeOrValueSpecifier[]; + checkParameterProperties?: boolean; + ignoreInferredTypes?: boolean; + treatMethodsAsReadonly?: boolean; + } +]; +export type MessageIds = 'shouldBeReadonly'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"shouldBeReadonly", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=prefer-readonly-parameter-types.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly-parameter-types.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly-parameter-types.d.ts.map new file mode 100644 index 00000000..b668036c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly-parameter-types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-readonly-parameter-types.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-readonly-parameter-types.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAUpD,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,KAAK,CAAC,EAAE,oBAAoB,EAAE,CAAC;QAC/B,wBAAwB,CAAC,EAAE,OAAO,CAAC;QACnC,mBAAmB,CAAC,EAAE,OAAO,CAAC;QAC9B,sBAAsB,CAAC,EAAE,OAAO,CAAC;KAClC;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,kBAAkB,CAAC;;AAE5C,wBAqHG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly-parameter-types.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly-parameter-types.js new file mode 100644 index 00000000..63cc636a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly-parameter-types.js @@ -0,0 +1,89 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-readonly-parameter-types', + meta: { + type: 'suggestion', + docs: { + description: 'Require function parameters to be typed as `readonly` to prevent accidental mutation of inputs', + requiresTypeChecking: true, + }, + messages: { + shouldBeReadonly: 'Parameter should be a read only type.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allow: { + ...util_1.readonlynessOptionsSchema.properties.allow, + description: 'An array of type specifiers to ignore.', + }, + checkParameterProperties: { + type: 'boolean', + description: 'Whether to check class parameter properties.', + }, + ignoreInferredTypes: { + type: 'boolean', + description: "Whether to ignore parameters which don't explicitly specify a type.", + }, + treatMethodsAsReadonly: { + ...util_1.readonlynessOptionsSchema.properties.treatMethodsAsReadonly, + description: 'Whether to treat all mutable methods as though they are readonly.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allow: util_1.readonlynessOptionsDefaults.allow, + checkParameterProperties: true, + ignoreInferredTypes: false, + treatMethodsAsReadonly: util_1.readonlynessOptionsDefaults.treatMethodsAsReadonly, + }, + ], + create(context, [{ allow, checkParameterProperties, ignoreInferredTypes, treatMethodsAsReadonly, },]) { + const services = (0, util_1.getParserServices)(context); + return { + [[ + utils_1.AST_NODE_TYPES.ArrowFunctionExpression, + utils_1.AST_NODE_TYPES.FunctionDeclaration, + utils_1.AST_NODE_TYPES.FunctionExpression, + utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration, + utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration, + utils_1.AST_NODE_TYPES.TSDeclareFunction, + utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression, + utils_1.AST_NODE_TYPES.TSFunctionType, + utils_1.AST_NODE_TYPES.TSMethodSignature, + ].join(', ')](node) { + for (const param of node.params) { + if (!checkParameterProperties && + param.type === utils_1.AST_NODE_TYPES.TSParameterProperty) { + continue; + } + const actualParam = param.type === utils_1.AST_NODE_TYPES.TSParameterProperty + ? param.parameter + : param; + if (ignoreInferredTypes && actualParam.typeAnnotation == null) { + continue; + } + const type = services.getTypeAtLocation(actualParam); + const isReadOnly = (0, util_1.isTypeReadonly)(services.program, type, { + allow, + treatMethodsAsReadonly: !!treatMethodsAsReadonly, + }); + if (!isReadOnly) { + context.report({ + node: actualParam, + messageId: 'shouldBeReadonly', + }); + } + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly.d.ts new file mode 100644 index 00000000..ec8efef2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly.d.ts @@ -0,0 +1,9 @@ +export type MessageIds = 'preferReadonly'; +export type Options = [ + { + onlyInlineLambdas?: boolean; + } +]; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferReadonly", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=prefer-readonly.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly.d.ts.map new file mode 100644 index 00000000..9788f7dc --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-readonly.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-readonly.ts"],"names":[],"mappings":"AAiBA,MAAM,MAAM,UAAU,GAAG,gBAAgB,CAAC;AAC1C,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,iBAAiB,CAAC,EAAE,OAAO,CAAC;KAC7B;CACF,CAAC;;AASF,wBAgUG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly.js new file mode 100644 index 00000000..d92c6b70 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-readonly.js @@ -0,0 +1,392 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const getMemberHeadLoc_1 = require("../util/getMemberHeadLoc"); +const functionScopeBoundaries = [ + utils_1.AST_NODE_TYPES.ArrowFunctionExpression, + utils_1.AST_NODE_TYPES.FunctionDeclaration, + utils_1.AST_NODE_TYPES.FunctionExpression, + utils_1.AST_NODE_TYPES.MethodDefinition, +].join(', '); +exports.default = (0, util_1.createRule)({ + name: 'prefer-readonly', + meta: { + type: 'suggestion', + docs: { + description: "Require private members to be marked as `readonly` if they're never modified outside of the constructor", + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + preferReadonly: "Member '{{name}}' is never reassigned; mark it as `readonly`.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + onlyInlineLambdas: { + type: 'boolean', + description: 'Whether to restrict checking only to members immediately assigned a lambda value.', + }, + }, + }, + ], + }, + defaultOptions: [{ onlyInlineLambdas: false }], + create(context, [{ onlyInlineLambdas }]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const classScopeStack = []; + function handlePropertyAccessExpression(node, parent, classScope) { + if (ts.isBinaryExpression(parent)) { + handleParentBinaryExpression(node, parent, classScope); + return; + } + if (ts.isDeleteExpression(parent) || isDestructuringAssignment(node)) { + classScope.addVariableModification(node); + return; + } + if (ts.isPostfixUnaryExpression(parent) || + ts.isPrefixUnaryExpression(parent)) { + handleParentPostfixOrPrefixUnaryExpression(parent, classScope); + } + } + function handleParentBinaryExpression(node, parent, classScope) { + if (parent.left === node && + tsutils.isAssignmentKind(parent.operatorToken.kind)) { + classScope.addVariableModification(node); + } + } + function handleParentPostfixOrPrefixUnaryExpression(node, classScope) { + if (node.operator === ts.SyntaxKind.PlusPlusToken || + node.operator === ts.SyntaxKind.MinusMinusToken) { + classScope.addVariableModification(node.operand); + } + } + function isDestructuringAssignment(node) { + let current = node.parent; + while (current) { + const parent = current.parent; + if (ts.isObjectLiteralExpression(parent) || + ts.isArrayLiteralExpression(parent) || + ts.isSpreadAssignment(parent) || + (ts.isSpreadElement(parent) && + ts.isArrayLiteralExpression(parent.parent))) { + current = parent; + } + else if (ts.isBinaryExpression(parent) && + !ts.isPropertyAccessExpression(current)) { + return (parent.left === current && + parent.operatorToken.kind === ts.SyntaxKind.EqualsToken); + } + else { + break; + } + } + return false; + } + function isFunctionScopeBoundaryInStack(node) { + if (classScopeStack.length === 0) { + return false; + } + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + if (ts.isConstructorDeclaration(tsNode)) { + return false; + } + return tsutils.isFunctionScopeBoundary(tsNode); + } + function getEsNodesFromViolatingNode(violatingNode) { + return { + esNode: services.tsNodeToESTreeNodeMap.get(violatingNode), + nameNode: services.tsNodeToESTreeNodeMap.get(violatingNode.name), + }; + } + function getTypeAnnotationForViolatingNode(node, type, initializerType) { + const annotation = checker.typeToString(type); + // verify the about-to-be-added type annotation is in-scope + if (tsutils.isTypeFlagSet(initializerType, ts.TypeFlags.EnumLiteral)) { + const scope = context.sourceCode.getScope(node); + const variable = utils_1.ASTUtils.findVariable(scope, annotation); + if (variable == null) { + return null; + } + const definition = variable.defs.find(def => def.isTypeDefinition); + if (definition == null) { + return null; + } + const definitionType = services.getTypeAtLocation(definition.node); + if (definitionType !== type) { + return null; + } + } + return annotation; + } + return { + [`${functionScopeBoundaries}:exit`](node) { + if (utils_1.ASTUtils.isConstructor(node)) { + classScopeStack[classScopeStack.length - 1].exitConstructor(); + } + else if (isFunctionScopeBoundaryInStack(node)) { + classScopeStack[classScopeStack.length - 1].exitNonConstructor(); + } + }, + 'ClassDeclaration, ClassExpression'(node) { + classScopeStack.push(new ClassScope(checker, services.esTreeNodeToTSNodeMap.get(node), onlyInlineLambdas)); + }, + 'ClassDeclaration, ClassExpression:exit'() { + const finalizedClassScope = (0, util_1.nullThrows)(classScopeStack.pop(), 'Stack should exist on class exit'); + for (const violatingNode of finalizedClassScope.finalizeUnmodifiedPrivateNonReadonlys()) { + const { esNode, nameNode } = getEsNodesFromViolatingNode(violatingNode); + const reportNodeOrLoc = (() => { + switch (esNode.type) { + case utils_1.AST_NODE_TYPES.MethodDefinition: + case utils_1.AST_NODE_TYPES.PropertyDefinition: + case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition: + return { loc: (0, getMemberHeadLoc_1.getMemberHeadLoc)(context.sourceCode, esNode) }; + case utils_1.AST_NODE_TYPES.TSParameterProperty: + return { + loc: (0, getMemberHeadLoc_1.getParameterPropertyHeadLoc)(context.sourceCode, esNode, nameNode.name), + }; + default: + return { node: esNode }; + } + })(); + const typeAnnotation = (() => { + if (esNode.type !== utils_1.AST_NODE_TYPES.PropertyDefinition) { + return null; + } + if (esNode.typeAnnotation || !esNode.value) { + return null; + } + if (nameNode.type !== utils_1.AST_NODE_TYPES.Identifier) { + return null; + } + const hasConstructorModifications = finalizedClassScope.memberHasConstructorModifications(nameNode.name); + if (!hasConstructorModifications) { + return null; + } + const violatingType = services.getTypeAtLocation(esNode); + const initializerType = services.getTypeAtLocation(esNode.value); + // if the RHS is a literal, its type would be narrowed, while the + // type of the initializer (which isn't `readonly`) would be the + // widened type + if (initializerType === violatingType) { + return null; + } + if (!tsutils.isLiteralType(initializerType)) { + return null; + } + return getTypeAnnotationForViolatingNode(esNode, violatingType, initializerType); + })(); + context.report({ + ...reportNodeOrLoc, + messageId: 'preferReadonly', + data: { + name: context.sourceCode.getText(nameNode), + }, + *fix(fixer) { + yield fixer.insertTextBefore(nameNode, 'readonly '); + if (typeAnnotation) { + yield fixer.insertTextAfter(nameNode, `: ${typeAnnotation}`); + } + }, + }); + } + }, + [functionScopeBoundaries](node) { + if (utils_1.ASTUtils.isConstructor(node)) { + classScopeStack[classScopeStack.length - 1].enterConstructor(services.esTreeNodeToTSNodeMap.get(node)); + } + else if (isFunctionScopeBoundaryInStack(node)) { + classScopeStack[classScopeStack.length - 1].enterNonConstructor(); + } + }, + MemberExpression(node) { + if (classScopeStack.length !== 0 && !node.computed) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + handlePropertyAccessExpression(tsNode, tsNode.parent, classScopeStack[classScopeStack.length - 1]); + } + }, + }; + }, +}); +const OUTSIDE_CONSTRUCTOR = -1; +const DIRECTLY_INSIDE_CONSTRUCTOR = 0; +var TypeToClassRelation; +(function (TypeToClassRelation) { + TypeToClassRelation[TypeToClassRelation["ClassAndInstance"] = 0] = "ClassAndInstance"; + TypeToClassRelation[TypeToClassRelation["Class"] = 1] = "Class"; + TypeToClassRelation[TypeToClassRelation["Instance"] = 2] = "Instance"; + TypeToClassRelation[TypeToClassRelation["None"] = 3] = "None"; +})(TypeToClassRelation || (TypeToClassRelation = {})); +class ClassScope { + checker; + onlyInlineLambdas; + classType; + constructorScopeDepth = OUTSIDE_CONSTRUCTOR; + memberVariableModifications = new Set(); + memberVariableWithConstructorModifications = new Set(); + privateModifiableMembers = new Map(); + privateModifiableStatics = new Map(); + staticVariableModifications = new Set(); + constructor(checker, classNode, onlyInlineLambdas) { + this.checker = checker; + this.onlyInlineLambdas = onlyInlineLambdas; + const classType = checker.getTypeAtLocation(classNode); + if (tsutils.isIntersectionType(classType)) { + this.classType = classType.types[0]; + } + else { + this.classType = classType; + } + for (const member of classNode.members) { + if (ts.isPropertyDeclaration(member)) { + this.addDeclaredVariable(member); + } + } + } + addDeclaredVariable(node) { + if (!(tsutils.isModifierFlagSet(node, ts.ModifierFlags.Private) || + node.name.kind === ts.SyntaxKind.PrivateIdentifier) || + tsutils.isModifierFlagSet(node, ts.ModifierFlags.Accessor | ts.ModifierFlags.Readonly) || + ts.isComputedPropertyName(node.name)) { + return; + } + if (this.onlyInlineLambdas && + node.initializer != null && + !ts.isArrowFunction(node.initializer)) { + return; + } + (tsutils.isModifierFlagSet(node, ts.ModifierFlags.Static) + ? this.privateModifiableStatics + : this.privateModifiableMembers).set(node.name.getText(), node); + } + addVariableModification(node) { + const modifierType = this.checker.getTypeAtLocation(node.expression); + const relationOfModifierTypeToClass = this.getTypeToClassRelation(modifierType); + if (relationOfModifierTypeToClass === TypeToClassRelation.Instance && + this.constructorScopeDepth === DIRECTLY_INSIDE_CONSTRUCTOR) { + this.memberVariableWithConstructorModifications.add(node.name.text); + return; + } + if (relationOfModifierTypeToClass === TypeToClassRelation.Instance || + relationOfModifierTypeToClass === TypeToClassRelation.ClassAndInstance) { + this.memberVariableModifications.add(node.name.text); + } + if (relationOfModifierTypeToClass === TypeToClassRelation.Class || + relationOfModifierTypeToClass === TypeToClassRelation.ClassAndInstance) { + this.staticVariableModifications.add(node.name.text); + } + } + enterConstructor(node) { + this.constructorScopeDepth = DIRECTLY_INSIDE_CONSTRUCTOR; + for (const parameter of node.parameters) { + if (tsutils.isModifierFlagSet(parameter, ts.ModifierFlags.Private)) { + this.addDeclaredVariable(parameter); + } + } + } + enterNonConstructor() { + if (this.constructorScopeDepth !== OUTSIDE_CONSTRUCTOR) { + this.constructorScopeDepth += 1; + } + } + exitConstructor() { + this.constructorScopeDepth = OUTSIDE_CONSTRUCTOR; + } + exitNonConstructor() { + if (this.constructorScopeDepth !== OUTSIDE_CONSTRUCTOR) { + this.constructorScopeDepth -= 1; + } + } + finalizeUnmodifiedPrivateNonReadonlys() { + this.memberVariableModifications.forEach(variableName => { + this.privateModifiableMembers.delete(variableName); + }); + this.staticVariableModifications.forEach(variableName => { + this.privateModifiableStatics.delete(variableName); + }); + return [ + ...this.privateModifiableMembers.values(), + ...this.privateModifiableStatics.values(), + ]; + } + getTypeToClassRelation(type) { + if (type.isIntersection()) { + let result = TypeToClassRelation.None; + for (const subType of type.types) { + const subTypeResult = this.getTypeToClassRelation(subType); + switch (subTypeResult) { + case TypeToClassRelation.Class: + if (result === TypeToClassRelation.Instance) { + return TypeToClassRelation.ClassAndInstance; + } + result = TypeToClassRelation.Class; + break; + case TypeToClassRelation.Instance: + if (result === TypeToClassRelation.Class) { + return TypeToClassRelation.ClassAndInstance; + } + result = TypeToClassRelation.Instance; + break; + } + } + return result; + } + if (type.isUnion()) { + // any union of class/instance and something else will prevent access to + // private members, so we assume that union consists only of classes + // or class instances, because otherwise tsc will report an error + return this.getTypeToClassRelation(type.types[0]); + } + if (!type.getSymbol() || !(0, util_1.typeIsOrHasBaseType)(type, this.classType)) { + return TypeToClassRelation.None; + } + const typeIsClass = tsutils.isObjectType(type) && + tsutils.isObjectFlagSet(type, ts.ObjectFlags.Anonymous); + if (typeIsClass) { + return TypeToClassRelation.Class; + } + return TypeToClassRelation.Instance; + } + memberHasConstructorModifications(name) { + return this.memberVariableWithConstructorModifications.has(name); + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-reduce-type-parameter.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-reduce-type-parameter.d.ts new file mode 100644 index 00000000..55b81ca0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-reduce-type-parameter.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferTypeParameter", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=prefer-reduce-type-parameter.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-reduce-type-parameter.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-reduce-type-parameter.d.ts.map new file mode 100644 index 00000000..a28bfe21 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-reduce-type-parameter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-reduce-type-parameter.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-reduce-type-parameter.ts"],"names":[],"mappings":";AAiBA,wBA6GG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-reduce-type-parameter.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-reduce-type-parameter.js new file mode 100644 index 00000000..ec6f6a79 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-reduce-type-parameter.js @@ -0,0 +1,114 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-reduce-type-parameter', + meta: { + type: 'problem', + docs: { + description: 'Enforce using type parameter when calling `Array#reduce` instead of using a type assertion', + recommended: 'strict', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + preferTypeParameter: 'Unnecessary assertion: Array#reduce accepts a type parameter for the default value.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function isArrayType(type) { + return tsutils + .unionConstituents(type) + .every(unionPart => tsutils + .intersectionConstituents(unionPart) + .every(t => checker.isArrayType(t) || checker.isTupleType(t))); + } + return { + 'CallExpression > MemberExpression.callee'(callee) { + if (!(0, util_1.isStaticMemberAccessOfValue)(callee, context, 'reduce')) { + return; + } + const [, secondArg] = callee.parent.arguments; + if (callee.parent.arguments.length < 2) { + return; + } + if ((0, util_1.isTypeAssertion)(secondArg)) { + const initializerType = services.getTypeAtLocation(secondArg.expression); + const assertedType = services.getTypeAtLocation(secondArg.typeAnnotation); + const isAssertionNecessary = !checker.isTypeAssignableTo(initializerType, assertedType); + // don't report this if the resulting fix will be a type error + if (isAssertionNecessary) { + return; + } + } + else { + return; + } + // Get the symbol of the `reduce` method. + const calleeObjType = (0, util_1.getConstrainedTypeAtLocation)(services, callee.object); + // Check the owner type of the `reduce` method. + if (isArrayType(calleeObjType)) { + context.report({ + node: secondArg, + messageId: 'preferTypeParameter', + fix: fixer => { + const fixes = [ + fixer.removeRange([ + secondArg.range[0], + secondArg.expression.range[0], + ]), + fixer.removeRange([ + secondArg.expression.range[1], + secondArg.range[1], + ]), + ]; + if (!callee.parent.typeArguments) { + fixes.push(fixer.insertTextAfter(callee, `<${context.sourceCode.getText(secondArg.typeAnnotation)}>`)); + } + return fixes; + }, + }); + return; + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-regexp-exec.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-regexp-exec.d.ts new file mode 100644 index 00000000..e4be5a6b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-regexp-exec.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"regExpExecOverStringMatch", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=prefer-regexp-exec.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-regexp-exec.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-regexp-exec.d.ts.map new file mode 100644 index 00000000..9aecc391 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-regexp-exec.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-regexp-exec.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-regexp-exec.ts"],"names":[],"mappings":";AAsBA,wBAkKG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-regexp-exec.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-regexp-exec.js new file mode 100644 index 00000000..22c662e3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-regexp-exec.js @@ -0,0 +1,178 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +var ArgumentType; +(function (ArgumentType) { + ArgumentType[ArgumentType["Other"] = 0] = "Other"; + ArgumentType[ArgumentType["String"] = 1] = "String"; + ArgumentType[ArgumentType["RegExp"] = 2] = "RegExp"; + ArgumentType[ArgumentType["Both"] = 3] = "Both"; +})(ArgumentType || (ArgumentType = {})); +exports.default = (0, util_1.createRule)({ + name: 'prefer-regexp-exec', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce `RegExp#exec` over `String#match` if no global flag is provided', + recommended: 'stylistic', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + regExpExecOverStringMatch: 'Use the `RegExp#exec()` method instead.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const globalScope = context.sourceCode.getScope(context.sourceCode.ast); + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + /** + * Check if a given node type is a string. + * @param type The node type to check. + */ + function isStringType(type) { + return (0, util_1.getTypeName)(checker, type) === 'string'; + } + /** + * Check if a given node type is a RegExp. + * @param type The node type to check. + */ + function isRegExpType(type) { + return (0, util_1.getTypeName)(checker, type) === 'RegExp'; + } + function collectArgumentTypes(types) { + let result = ArgumentType.Other; + for (const type of types) { + if (isRegExpType(type)) { + result |= ArgumentType.RegExp; + } + else if (isStringType(type)) { + result |= ArgumentType.String; + } + } + return result; + } + /** + * Returns true if and only if we have syntactic proof that the /g flag is + * absent. Returns false in all other cases (i.e. it still might or might + * not contain the global flag). + */ + function definitelyDoesNotContainGlobalFlag(node) { + if ((node.type === utils_1.AST_NODE_TYPES.CallExpression || + node.type === utils_1.AST_NODE_TYPES.NewExpression) && + node.callee.type === utils_1.AST_NODE_TYPES.Identifier && + node.callee.name === 'RegExp') { + const flags = node.arguments.at(1); + return !(flags?.type === utils_1.AST_NODE_TYPES.Literal && + typeof flags.value === 'string' && + flags.value.includes('g')); + } + return false; + } + return { + 'CallExpression[arguments.length=1] > MemberExpression'(memberNode) { + if (!(0, util_1.isStaticMemberAccessOfValue)(memberNode, context, 'match')) { + return; + } + const objectNode = memberNode.object; + const callNode = memberNode.parent; + const [argumentNode] = callNode.arguments; + const argumentValue = (0, util_1.getStaticValue)(argumentNode, globalScope); + if (!isStringType(services.getTypeAtLocation(objectNode))) { + return; + } + // Don't report regular expressions with global flag. + if ((!argumentValue && + !definitelyDoesNotContainGlobalFlag(argumentNode)) || + (argumentValue && + argumentValue.value instanceof RegExp && + argumentValue.value.flags.includes('g'))) { + return; + } + if (argumentNode.type === utils_1.AST_NODE_TYPES.Literal && + typeof argumentNode.value === 'string') { + let regExp; + try { + regExp = RegExp(argumentNode.value); + } + catch { + return; + } + return context.report({ + node: memberNode.property, + messageId: 'regExpExecOverStringMatch', + fix: (0, util_1.getWrappingFixer)({ + node: callNode, + innerNode: [objectNode], + sourceCode: context.sourceCode, + wrap: objectCode => `${regExp.toString()}.exec(${objectCode})`, + }), + }); + } + const argumentType = services.getTypeAtLocation(argumentNode); + const argumentTypes = collectArgumentTypes(tsutils.unionConstituents(argumentType)); + switch (argumentTypes) { + case ArgumentType.RegExp: + return context.report({ + node: memberNode.property, + messageId: 'regExpExecOverStringMatch', + fix: (0, util_1.getWrappingFixer)({ + node: callNode, + innerNode: [objectNode, argumentNode], + sourceCode: context.sourceCode, + wrap: (objectCode, argumentCode) => `${argumentCode}.exec(${objectCode})`, + }), + }); + case ArgumentType.String: + return context.report({ + node: memberNode.property, + messageId: 'regExpExecOverStringMatch', + fix: (0, util_1.getWrappingFixer)({ + node: callNode, + innerNode: [objectNode, argumentNode], + sourceCode: context.sourceCode, + wrap: (objectCode, argumentCode) => `RegExp(${argumentCode}).exec(${objectCode})`, + }), + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-return-this-type.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-return-this-type.d.ts new file mode 100644 index 00000000..170f3550 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-return-this-type.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"useThisType", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=prefer-return-this-type.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-return-this-type.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-return-this-type.d.ts.map new file mode 100644 index 00000000..fa491db2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-return-this-type.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-return-this-type.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-return-this-type.ts"],"names":[],"mappings":";AAeA,wBA8JG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-return-this-type.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-return-this-type.js new file mode 100644 index 00000000..2b7a5b1d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-return-this-type.js @@ -0,0 +1,148 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-return-this-type', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce that `this` is used when only `this` type is returned', + recommended: 'strict', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + useThisType: 'Use `this` type instead.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function tryGetNameInType(name, typeNode) { + if (typeNode.type === utils_1.AST_NODE_TYPES.TSTypeReference && + typeNode.typeName.type === utils_1.AST_NODE_TYPES.Identifier && + typeNode.typeName.name === name) { + return typeNode; + } + if (typeNode.type === utils_1.AST_NODE_TYPES.TSUnionType) { + for (const type of typeNode.types) { + const found = tryGetNameInType(name, type); + if (found) { + return found; + } + } + } + return undefined; + } + function isThisSpecifiedInParameters(originalFunc) { + const firstArg = originalFunc.params.at(0); + return (firstArg?.type === utils_1.AST_NODE_TYPES.Identifier && firstArg.name === 'this'); + } + function isFunctionReturningThis(originalFunc, originalClass) { + if (isThisSpecifiedInParameters(originalFunc)) { + return false; + } + const func = services.esTreeNodeToTSNodeMap.get(originalFunc); + if (!func.body) { + return false; + } + const classType = services.getTypeAtLocation(originalClass); + if (func.body.kind !== ts.SyntaxKind.Block) { + const type = checker.getTypeAtLocation(func.body); + return classType.thisType === type; + } + let hasReturnThis = false; + let hasReturnClassType = false; + (0, util_1.forEachReturnStatement)(func.body, stmt => { + const expr = stmt.expression; + if (!expr) { + return; + } + // fast check + if (expr.kind === ts.SyntaxKind.ThisKeyword) { + hasReturnThis = true; + return; + } + const type = checker.getTypeAtLocation(expr); + if (classType === type) { + hasReturnClassType = true; + return true; + } + if (classType.thisType === type) { + hasReturnThis = true; + return; + } + return; + }); + return !hasReturnClassType && hasReturnThis; + } + function checkFunction(originalFunc, originalClass) { + const className = originalClass.id?.name; + if (!className || !originalFunc.returnType) { + return; + } + const node = tryGetNameInType(className, originalFunc.returnType.typeAnnotation); + if (!node) { + return; + } + if (isFunctionReturningThis(originalFunc, originalClass)) { + context.report({ + node, + messageId: 'useThisType', + fix: fixer => fixer.replaceText(node, 'this'), + }); + } + } + function checkProperty(node) { + if (!(node.value?.type === utils_1.AST_NODE_TYPES.FunctionExpression || + node.value?.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression)) { + return; + } + checkFunction(node.value, node.parent.parent); + } + return { + 'ClassBody > AccessorProperty': checkProperty, + 'ClassBody > MethodDefinition'(node) { + checkFunction(node.value, node.parent.parent); + }, + 'ClassBody > PropertyDefinition': checkProperty, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-string-starts-ends-with.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-string-starts-ends-with.d.ts new file mode 100644 index 00000000..cf65f94c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-string-starts-ends-with.d.ts @@ -0,0 +1,11 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +type AllowedSingleElementEquality = 'always' | 'never'; +export type Options = [ + { + allowSingleElementEquality?: AllowedSingleElementEquality; + } +]; +export type MessageIds = 'preferEndsWith' | 'preferStartsWith'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=prefer-string-starts-ends-with.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-string-starts-ends-with.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-string-starts-ends-with.d.ts.map new file mode 100644 index 00000000..225269b3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-string-starts-ends-with.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-string-starts-ends-with.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-string-starts-ends-with.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAqBnE,KAAK,4BAA4B,GAAG,QAAQ,GAAG,OAAO,CAAC;AAEvD,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,0BAA0B,CAAC,EAAE,4BAA4B,CAAC;KAC3D;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,gBAAgB,GAAG,kBAAkB,CAAC;;AAE/D,wBAkrBG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-string-starts-ends-with.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-string-starts-ends-with.js new file mode 100644 index 00000000..b921a320 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-string-starts-ends-with.js @@ -0,0 +1,512 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const regexpp_1 = require("@eslint-community/regexpp"); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +const EQ_OPERATORS = /^[=!]=/; +const regexpp = new regexpp_1.RegExpParser(); +exports.default = (0, util_1.createRule)({ + name: 'prefer-string-starts-ends-with', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce using `String#startsWith` and `String#endsWith` over other equivalent methods of checking substrings', + recommended: 'stylistic', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + preferEndsWith: "Use the 'String#endsWith' method instead.", + preferStartsWith: "Use 'String#startsWith' method instead.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowSingleElementEquality: { + type: 'string', + description: 'Whether to allow equality checks against the first or last element of a string.', + enum: ['always', 'never'], + }, + }, + }, + ], + }, + defaultOptions: [{ allowSingleElementEquality: 'never' }], + create(context, [{ allowSingleElementEquality }]) { + const globalScope = context.sourceCode.getScope(context.sourceCode.ast); + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + /** + * Check if a given node is a string. + * @param node The node to check. + */ + function isStringType(node) { + const objectType = services.getTypeAtLocation(node); + return (0, util_1.getTypeName)(checker, objectType) === 'string'; + } + /** + * Check if a given node is a `Literal` node that is null. + * @param node The node to check. + */ + function isNull(node) { + const evaluated = (0, util_1.getStaticValue)(node, globalScope); + return evaluated != null && evaluated.value == null; + } + /** + * Check if a given node is a `Literal` node that is a given value. + * @param node The node to check. + * @param value The expected value of the `Literal` node. + */ + function isNumber(node, value) { + const evaluated = (0, util_1.getStaticValue)(node, globalScope); + return evaluated != null && evaluated.value === value; + } + /** + * Check if a given node is a `Literal` node that is a character. + * @param node The node to check. + */ + function isCharacter(node) { + const evaluated = (0, util_1.getStaticValue)(node, globalScope); + return (evaluated != null && + typeof evaluated.value === 'string' && + // checks if the string is a character long + evaluated.value[0] === evaluated.value); + } + /** + * Check if a given node is `==`, `===`, `!=`, or `!==`. + * @param node The node to check. + */ + function isEqualityComparison(node) { + return (node.type === utils_1.AST_NODE_TYPES.BinaryExpression && + EQ_OPERATORS.test(node.operator)); + } + /** + * Check if two given nodes are the same meaning. + * @param node1 A node to compare. + * @param node2 Another node to compare. + */ + function isSameTokens(node1, node2) { + const tokens1 = context.sourceCode.getTokens(node1); + const tokens2 = context.sourceCode.getTokens(node2); + if (tokens1.length !== tokens2.length) { + return false; + } + for (let i = 0; i < tokens1.length; ++i) { + const token1 = tokens1[i]; + const token2 = tokens2[i]; + if (token1.type !== token2.type || token1.value !== token2.value) { + return false; + } + } + return true; + } + /** + * Check if a given node is the expression of the length of a string. + * + * - If `length` property access of `expectedObjectNode`, it's `true`. + * E.g., `foo` → `foo.length` / `"foo"` → `"foo".length` + * - If `expectedObjectNode` is a string literal, `node` can be a number. + * E.g., `"foo"` → `3` + * + * @param node The node to check. + * @param expectedObjectNode The node which is expected as the receiver of `length` property. + */ + function isLengthExpression(node, expectedObjectNode) { + if (node.type === utils_1.AST_NODE_TYPES.MemberExpression) { + return ((0, util_1.getPropertyName)(node, globalScope) === 'length' && + isSameTokens(node.object, expectedObjectNode)); + } + const evaluatedLength = (0, util_1.getStaticValue)(node, globalScope); + const evaluatedString = (0, util_1.getStaticValue)(expectedObjectNode, globalScope); + return (evaluatedLength != null && + evaluatedString != null && + typeof evaluatedLength.value === 'number' && + typeof evaluatedString.value === 'string' && + evaluatedLength.value === evaluatedString.value.length); + } + /** + * Returns true if `node` is `-substring.length` or + * `parentString.length - substring.length` + */ + function isLengthAheadOfEnd(node, substring, parentString) { + return ((node.type === utils_1.AST_NODE_TYPES.UnaryExpression && + node.operator === '-' && + isLengthExpression(node.argument, substring)) || + (node.type === utils_1.AST_NODE_TYPES.BinaryExpression && + node.operator === '-' && + isLengthExpression(node.left, parentString) && + isLengthExpression(node.right, substring))); + } + /** + * Check if a given node is the expression of the last index. + * + * E.g. `foo.length - 1` + * + * @param node The node to check. + * @param expectedObjectNode The node which is expected as the receiver of `length` property. + */ + function isLastIndexExpression(node, expectedObjectNode) { + return (node.type === utils_1.AST_NODE_TYPES.BinaryExpression && + node.operator === '-' && + isLengthExpression(node.left, expectedObjectNode) && + isNumber(node.right, 1)); + } + /** + * Get the range of the property of a given `MemberExpression` node. + * + * - `obj[foo]` → the range of `[foo]` + * - `obf.foo` → the range of `.foo` + * - `(obj).foo` → the range of `.foo` + * + * @param node The member expression node to get. + */ + function getPropertyRange(node) { + const dotOrOpenBracket = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.object, util_1.isNotClosingParenToken), util_1.NullThrowsReasons.MissingToken('closing parenthesis', 'member')); + return [dotOrOpenBracket.range[0], node.range[1]]; + } + /** + * Parse a given `RegExp` pattern to that string if it's a static string. + * @param pattern The RegExp pattern text to parse. + * @param unicode Whether the RegExp is unicode. + */ + function parseRegExpText(pattern, unicode) { + // Parse it. + const ast = regexpp.parsePattern(pattern, undefined, undefined, { + unicode, + }); + if (ast.alternatives.length !== 1) { + return null; + } + // Drop `^`/`$` assertion. + const chars = ast.alternatives[0].elements; + const first = chars[0]; + if (first.type === 'Assertion' && first.kind === 'start') { + chars.shift(); + } + else { + chars.pop(); + } + // Check if it can determine a unique string. + if (!chars.every(c => c.type === 'Character')) { + return null; + } + // To string. + return String.fromCodePoint(...chars.map(c => c.value)); + } + /** + * Parse a given node if it's a `RegExp` instance. + * @param node The node to parse. + */ + function parseRegExp(node) { + const evaluated = (0, util_1.getStaticValue)(node, globalScope); + if (evaluated == null || !(evaluated.value instanceof RegExp)) { + return null; + } + const { flags, source } = evaluated.value; + const isStartsWith = source.startsWith('^'); + const isEndsWith = source.endsWith('$'); + if (isStartsWith === isEndsWith || + flags.includes('i') || + flags.includes('m')) { + return null; + } + const text = parseRegExpText(source, flags.includes('u')); + if (text == null) { + return null; + } + return { isEndsWith, isStartsWith, text }; + } + function getLeftNode(init) { + const node = (0, util_1.skipChainExpression)(init); + const leftNode = node.type === utils_1.AST_NODE_TYPES.CallExpression ? node.callee : node; + if (leftNode.type !== utils_1.AST_NODE_TYPES.MemberExpression) { + throw new Error(`Expected a MemberExpression, got ${leftNode.type}`); + } + return leftNode; + } + /** + * Fix code with using the right operand as the search string. + * For example: `foo.slice(0, 3) === 'bar'` → `foo.startsWith('bar')` + * @param fixer The rule fixer. + * @param node The node which was reported. + * @param kind The kind of the report. + * @param isNegative The flag to fix to negative condition. + */ + function* fixWithRightOperand(fixer, node, kind, isNegative, isOptional) { + // left is CallExpression or MemberExpression. + const leftNode = getLeftNode(node.left); + const propertyRange = getPropertyRange(leftNode); + if (isNegative) { + yield fixer.insertTextBefore(node, '!'); + } + yield fixer.replaceTextRange([propertyRange[0], node.right.range[0]], `${isOptional ? '?.' : '.'}${kind}sWith(`); + yield fixer.replaceTextRange([node.right.range[1], node.range[1]], ')'); + } + /** + * Fix code with using the first argument as the search string. + * For example: `foo.indexOf('bar') === 0` → `foo.startsWith('bar')` + * @param fixer The rule fixer. + * @param node The node which was reported. + * @param kind The kind of the report. + * @param negative The flag to fix to negative condition. + */ + function* fixWithArgument(fixer, node, callNode, calleeNode, kind, negative, isOptional) { + if (negative) { + yield fixer.insertTextBefore(node, '!'); + } + yield fixer.replaceTextRange(getPropertyRange(calleeNode), `${isOptional ? '?.' : '.'}${kind}sWith`); + yield fixer.removeRange([callNode.range[1], node.range[1]]); + } + function getParent(node) { + return (0, util_1.nullThrows)(node.parent?.type === utils_1.AST_NODE_TYPES.ChainExpression + ? node.parent.parent + : node.parent, util_1.NullThrowsReasons.MissingParent); + } + return { + // foo[0] === "a" + // foo.charAt(0) === "a" + // foo[foo.length - 1] === "a" + // foo.charAt(foo.length - 1) === "a" + [[ + 'BinaryExpression > MemberExpression.left[computed=true]', + 'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="charAt"][computed=false]', + 'BinaryExpression > ChainExpression.left > MemberExpression[computed=true]', + 'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="charAt"][computed=false]', + ].join(', ')](node) { + let parentNode = getParent(node); + let indexNode = null; + if (parentNode.type === utils_1.AST_NODE_TYPES.CallExpression) { + if (parentNode.arguments.length === 1) { + indexNode = parentNode.arguments[0]; + } + parentNode = getParent(parentNode); + } + else { + indexNode = node.property; + } + if (indexNode == null || + !isEqualityComparison(parentNode) || + !isStringType(node.object)) { + return; + } + const isEndsWith = isLastIndexExpression(indexNode, node.object); + if (allowSingleElementEquality === 'always' && isEndsWith) { + return; + } + const isStartsWith = !isEndsWith && isNumber(indexNode, 0); + if ((allowSingleElementEquality === 'always' && isStartsWith) || + (!isStartsWith && !isEndsWith)) { + return; + } + const eqNode = parentNode; + context.report({ + node: parentNode, + messageId: isStartsWith ? 'preferStartsWith' : 'preferEndsWith', + fix(fixer) { + // Don't fix if it can change the behavior. + if (!isCharacter(eqNode.right)) { + return null; + } + return fixWithRightOperand(fixer, eqNode, isStartsWith ? 'start' : 'end', eqNode.operator.startsWith('!'), node.optional); + }, + }); + }, + // foo.indexOf('bar') === 0 + [[ + 'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="indexOf"][computed=false]', + 'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="indexOf"][computed=false]', + ].join(', ')](node) { + const callNode = getParent(node); + const parentNode = getParent(callNode); + if (callNode.arguments.length !== 1 || + !isEqualityComparison(parentNode) || + !isNumber(parentNode.right, 0) || + !isStringType(node.object)) { + return; + } + context.report({ + node: parentNode, + messageId: 'preferStartsWith', + fix(fixer) { + return fixWithArgument(fixer, parentNode, callNode, node, 'start', parentNode.operator.startsWith('!'), node.optional); + }, + }); + }, + // foo.lastIndexOf('bar') === foo.length - 3 + // foo.lastIndexOf(bar) === foo.length - bar.length + [[ + 'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="lastIndexOf"][computed=false]', + 'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="lastIndexOf"][computed=false]', + ].join(', ')](node) { + const callNode = getParent(node); + const parentNode = getParent(callNode); + if (callNode.arguments.length !== 1 || + !isEqualityComparison(parentNode) || + parentNode.right.type !== utils_1.AST_NODE_TYPES.BinaryExpression || + parentNode.right.operator !== '-' || + !isLengthExpression(parentNode.right.left, node.object) || + !isLengthExpression(parentNode.right.right, callNode.arguments[0]) || + !isStringType(node.object)) { + return; + } + context.report({ + node: parentNode, + messageId: 'preferEndsWith', + fix(fixer) { + return fixWithArgument(fixer, parentNode, callNode, node, 'end', parentNode.operator.startsWith('!'), node.optional); + }, + }); + }, + // foo.match(/^bar/) === null + // foo.match(/bar$/) === null + [[ + 'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="match"][computed=false]', + 'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="match"][computed=false]', + ].join(', ')](node) { + const callNode = getParent(node); + const parentNode = getParent(callNode); + if (!isNull(parentNode.right) || !isStringType(node.object)) { + return; + } + const parsed = callNode.arguments.length === 1 + ? parseRegExp(callNode.arguments[0]) + : null; + if (parsed == null) { + return; + } + const { isStartsWith, text } = parsed; + context.report({ + node: callNode, + messageId: isStartsWith ? 'preferStartsWith' : 'preferEndsWith', + *fix(fixer) { + if (!parentNode.operator.startsWith('!')) { + yield fixer.insertTextBefore(parentNode, '!'); + } + yield fixer.replaceTextRange(getPropertyRange(node), `${node.optional ? '?.' : '.'}${isStartsWith ? 'start' : 'end'}sWith`); + yield fixer.replaceText(callNode.arguments[0], JSON.stringify(text)); + yield fixer.removeRange([callNode.range[1], parentNode.range[1]]); + }, + }); + }, + // foo.slice(0, 3) === 'bar' + // foo.slice(-3) === 'bar' + // foo.slice(-3, foo.length) === 'bar' + // foo.substring(0, 3) === 'bar' + // foo.substring(foo.length - 3) === 'bar' + // foo.substring(foo.length - 3, foo.length) === 'bar' + [[ + 'BinaryExpression > CallExpression.left > MemberExpression', + 'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression', + ].join(', ')](node) { + if (!(0, util_1.isStaticMemberAccessOfValue)(node, context, 'slice', 'substring')) { + return; + } + const callNode = getParent(node); + const parentNode = getParent(callNode); + if (!isEqualityComparison(parentNode) || !isStringType(node.object)) { + return; + } + let isEndsWith = false; + let isStartsWith = false; + if (callNode.arguments.length === 1) { + if ( + // foo.slice(-bar.length) === bar + // foo.slice(foo.length - bar.length) === bar + isLengthAheadOfEnd(callNode.arguments[0], parentNode.right, node.object)) { + isEndsWith = true; + } + } + else if (callNode.arguments.length === 2) { + if ( + // foo.slice(0, bar.length) === bar + isNumber(callNode.arguments[0], 0) && + isLengthExpression(callNode.arguments[1], parentNode.right)) { + isStartsWith = true; + } + else if ( + // foo.slice(foo.length - bar.length, foo.length) === bar + // foo.slice(foo.length - bar.length, 0) === bar + // foo.slice(-bar.length, foo.length) === bar + // foo.slice(-bar.length, 0) === bar + (isLengthExpression(callNode.arguments[1], node.object) || + isNumber(callNode.arguments[1], 0)) && + isLengthAheadOfEnd(callNode.arguments[0], parentNode.right, node.object)) { + isEndsWith = true; + } + } + if (!isStartsWith && !isEndsWith) { + return; + } + const eqNode = parentNode; + const negativeIndexSupported = node.property.name === 'slice'; + context.report({ + node: parentNode, + messageId: isStartsWith ? 'preferStartsWith' : 'preferEndsWith', + fix(fixer) { + // Don't fix if it can change the behavior. + if (eqNode.operator.length === 2 && + (eqNode.right.type !== utils_1.AST_NODE_TYPES.Literal || + typeof eqNode.right.value !== 'string')) { + return null; + } + // code being checked is likely mistake: + // unequal length of strings being checked for equality + // or reliant on behavior of substring (negative indices interpreted as 0) + if (isStartsWith) { + if (!isLengthExpression(callNode.arguments[1], eqNode.right)) { + return null; + } + } + else { + const posNode = callNode.arguments[0]; + const posNodeIsAbsolutelyValid = (posNode.type === utils_1.AST_NODE_TYPES.BinaryExpression && + posNode.operator === '-' && + isLengthExpression(posNode.left, node.object) && + isLengthExpression(posNode.right, eqNode.right)) || + (negativeIndexSupported && + posNode.type === utils_1.AST_NODE_TYPES.UnaryExpression && + posNode.operator === '-' && + isLengthExpression(posNode.argument, eqNode.right)); + if (!posNodeIsAbsolutelyValid) { + return null; + } + } + return fixWithRightOperand(fixer, parentNode, isStartsWith ? 'start' : 'end', parentNode.operator.startsWith('!'), node.optional); + }, + }); + }, + // /^bar/.test(foo) + // /bar$/.test(foo) + 'CallExpression > MemberExpression.callee[property.name="test"][computed=false]'(node) { + const callNode = getParent(node); + const parsed = callNode.arguments.length === 1 ? parseRegExp(node.object) : null; + if (parsed == null) { + return; + } + const { isStartsWith, text } = parsed; + const messageId = isStartsWith ? 'preferStartsWith' : 'preferEndsWith'; + const methodName = isStartsWith ? 'startsWith' : 'endsWith'; + context.report({ + node: callNode, + messageId, + *fix(fixer) { + const argNode = callNode.arguments[0]; + const needsParen = argNode.type !== utils_1.AST_NODE_TYPES.Literal && + argNode.type !== utils_1.AST_NODE_TYPES.TemplateLiteral && + argNode.type !== utils_1.AST_NODE_TYPES.Identifier && + argNode.type !== utils_1.AST_NODE_TYPES.MemberExpression && + argNode.type !== utils_1.AST_NODE_TYPES.CallExpression; + yield fixer.removeRange([callNode.range[0], argNode.range[0]]); + if (needsParen) { + yield fixer.insertTextBefore(argNode, '('); + yield fixer.insertTextAfter(argNode, ')'); + } + yield fixer.insertTextAfter(argNode, `${node.optional ? '?.' : '.'}${methodName}(${JSON.stringify(text)}`); + }, + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-ts-expect-error.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-ts-expect-error.d.ts new file mode 100644 index 00000000..476d23e3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-ts-expect-error.d.ts @@ -0,0 +1,4 @@ +export type MessageIds = 'preferExpectErrorComment'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferExpectErrorComment", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=prefer-ts-expect-error.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-ts-expect-error.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-ts-expect-error.d.ts.map new file mode 100644 index 00000000..bf41bb37 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-ts-expect-error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prefer-ts-expect-error.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-ts-expect-error.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,UAAU,GAAG,0BAA0B,CAAC;;AAEpD,wBAqFG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-ts-expect-error.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-ts-expect-error.js new file mode 100644 index 00000000..e2db83bd --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-ts-expect-error.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'prefer-ts-expect-error', + meta: { + type: 'problem', + deprecated: { + deprecatedSince: '7.11.0', + replacedBy: [ + { + rule: { + name: '@typescript-eslint/ban-ts-comment', + url: 'https://typescript-eslint.io/rules/ban-ts-comment', + }, + }, + ], + url: 'https://github.com/typescript-eslint/typescript-eslint/pull/9081', + }, + docs: { + description: 'Enforce using `@ts-expect-error` over `@ts-ignore`', + }, + fixable: 'code', + messages: { + preferExpectErrorComment: 'Use "@ts-expect-error" to ensure an error is actually being suppressed.', + }, + replacedBy: ['@typescript-eslint/ban-ts-comment'], + schema: [], + }, + defaultOptions: [], + create(context) { + const tsIgnoreRegExpSingleLine = /^\s*\/?\s*@ts-ignore/; + const tsIgnoreRegExpMultiLine = /^\s*(?:\/|\*)*\s*@ts-ignore/; + function isLineComment(comment) { + return comment.type === utils_1.AST_TOKEN_TYPES.Line; + } + function getLastCommentLine(comment) { + if (isLineComment(comment)) { + return comment.value; + } + // For multiline comments - we look at only the last line. + const commentlines = comment.value.split('\n'); + return commentlines[commentlines.length - 1]; + } + function isValidTsIgnorePresent(comment) { + const line = getLastCommentLine(comment); + return isLineComment(comment) + ? tsIgnoreRegExpSingleLine.test(line) + : tsIgnoreRegExpMultiLine.test(line); + } + return { + Program() { + const comments = context.sourceCode.getAllComments(); + comments.forEach(comment => { + if (isValidTsIgnorePresent(comment)) { + const lineCommentRuleFixer = (fixer) => fixer.replaceText(comment, `//${comment.value.replace('@ts-ignore', '@ts-expect-error')}`); + const blockCommentRuleFixer = (fixer) => fixer.replaceText(comment, `/*${comment.value.replace('@ts-ignore', '@ts-expect-error')}*/`); + context.report({ + node: comment, + messageId: 'preferExpectErrorComment', + fix: isLineComment(comment) + ? lineCommentRuleFixer + : blockCommentRuleFixer, + }); + } + }); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/promise-function-async.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/promise-function-async.d.ts new file mode 100644 index 00000000..82e23683 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/promise-function-async.d.ts @@ -0,0 +1,14 @@ +export type Options = [ + { + allowAny?: boolean; + allowedPromiseNames?: string[]; + checkArrowFunctions?: boolean; + checkFunctionDeclarations?: boolean; + checkFunctionExpressions?: boolean; + checkMethodDeclarations?: boolean; + } +]; +export type MessageIds = 'missingAsync' | 'missingAsyncHybridReturn'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=promise-function-async.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/promise-function-async.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/promise-function-async.d.ts.map new file mode 100644 index 00000000..0497291e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/promise-function-async.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"promise-function-async.d.ts","sourceRoot":"","sources":["../../src/rules/promise-function-async.ts"],"names":[],"mappings":"AAeA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;QAC/B,mBAAmB,CAAC,EAAE,OAAO,CAAC;QAC9B,yBAAyB,CAAC,EAAE,OAAO,CAAC;QACpC,wBAAwB,CAAC,EAAE,OAAO,CAAC;QACnC,uBAAuB,CAAC,EAAE,OAAO,CAAC;KACnC;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,cAAc,GAAG,0BAA0B,CAAC;;AAErE,wBAyPG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/promise-function-async.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/promise-function-async.js new file mode 100644 index 00000000..dd3c7980 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/promise-function-async.js @@ -0,0 +1,202 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'promise-function-async', + meta: { + type: 'suggestion', + docs: { + description: 'Require any function or method that returns a Promise to be marked async', + requiresTypeChecking: true, + }, + fixable: 'code', + messages: { + missingAsync: 'Functions that return promises must be async.', + missingAsyncHybridReturn: 'Functions that return promises must be async. Consider adding an explicit return type annotation if the function is intended to return a union of promise and non-promise types.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowAny: { + type: 'boolean', + description: 'Whether to consider `any` and `unknown` to be Promises.', + }, + allowedPromiseNames: { + type: 'array', + description: 'Any extra names of classes or interfaces to be considered Promises.', + items: { + type: 'string', + }, + }, + checkArrowFunctions: { + type: 'boolean', + description: 'Whether to check arrow functions.', + }, + checkFunctionDeclarations: { + type: 'boolean', + description: 'Whether to check standalone function declarations.', + }, + checkFunctionExpressions: { + type: 'boolean', + description: 'Whether to check inline function expressions', + }, + checkMethodDeclarations: { + type: 'boolean', + description: 'Whether to check methods on classes and object literals.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowAny: true, + allowedPromiseNames: [], + checkArrowFunctions: true, + checkFunctionDeclarations: true, + checkFunctionExpressions: true, + checkMethodDeclarations: true, + }, + ], + create(context, [{ allowAny, allowedPromiseNames, checkArrowFunctions, checkFunctionDeclarations, checkFunctionExpressions, checkMethodDeclarations, },]) { + const allAllowedPromiseNames = new Set([ + 'Promise', + // https://github.com/typescript-eslint/typescript-eslint/issues/5439 + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + ...allowedPromiseNames, + ]); + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + function validateNode(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition) { + // Abstract method can't be async + return; + } + if ((node.parent.type === utils_1.AST_NODE_TYPES.Property || + node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition) && + (node.parent.kind === 'get' || node.parent.kind === 'set')) { + // Getters and setters can't be async + return; + } + const signatures = services.getTypeAtLocation(node).getCallSignatures(); + if (!signatures.length) { + return; + } + const returnTypes = signatures.map(signature => checker.getReturnTypeOfSignature(signature)); + if (!allowAny && + returnTypes.some(type => (0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown))) { + // Report without auto fixer because the return type is unknown + return context.report({ + loc: (0, util_1.getFunctionHeadLoc)(node, context.sourceCode), + node, + messageId: 'missingAsync', + }); + } + if ( + // require all potential return types to be promise/any/unknown + returnTypes.every(type => (0, util_1.containsAllTypesByName)(type, true, allAllowedPromiseNames, + // If no return type is explicitly set, we check if any parts of the return type match a Promise (instead of requiring all to match). + node.returnType == null))) { + const isHybridReturnType = returnTypes.some(type => type.isUnion() && + !type.types.every(part => (0, util_1.containsAllTypesByName)(part, true, allAllowedPromiseNames))); + context.report({ + loc: (0, util_1.getFunctionHeadLoc)(node, context.sourceCode), + node, + messageId: isHybridReturnType + ? 'missingAsyncHybridReturn' + : 'missingAsync', + fix: fixer => { + if (node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition || + (node.parent.type === utils_1.AST_NODE_TYPES.Property && + node.parent.method)) { + // this function is a class method or object function property shorthand + const method = node.parent; + // the token to put `async` before + let keyToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(method), util_1.NullThrowsReasons.MissingToken('key token', 'method')); + // if there are decorators then skip past them + if (method.type === utils_1.AST_NODE_TYPES.MethodDefinition && + method.decorators.length) { + const lastDecorator = method.decorators[method.decorators.length - 1]; + keyToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(lastDecorator), util_1.NullThrowsReasons.MissingToken('key token', 'last decorator')); + } + // if current token is a keyword like `static` or `public` then skip it + while (keyToken.type === utils_1.AST_TOKEN_TYPES.Keyword && + keyToken.range[0] < method.key.range[0]) { + keyToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(keyToken), util_1.NullThrowsReasons.MissingToken('token', 'keyword')); + } + // check if there is a space between key and previous token + const insertSpace = !context.sourceCode.isSpaceBetween((0, util_1.nullThrows)(context.sourceCode.getTokenBefore(keyToken), util_1.NullThrowsReasons.MissingToken('token', 'keyword')), keyToken); + let code = 'async '; + if (insertSpace) { + code = ` ${code}`; + } + return fixer.insertTextBefore(keyToken, code); + } + return fixer.insertTextBefore(node, 'async '); + }, + }); + } + } + return { + ...(checkArrowFunctions && { + 'ArrowFunctionExpression[async = false]'(node) { + validateNode(node); + }, + }), + ...(checkFunctionDeclarations && { + 'FunctionDeclaration[async = false]'(node) { + validateNode(node); + }, + }), + 'FunctionExpression[async = false]'(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition && + node.parent.kind === 'method') { + if (checkMethodDeclarations) { + validateNode(node); + } + return; + } + if (checkFunctionExpressions) { + validateNode(node); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/related-getter-setter-pairs.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/related-getter-setter-pairs.d.ts new file mode 100644 index 00000000..1870ce76 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/related-getter-setter-pairs.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"mismatch", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=related-getter-setter-pairs.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/related-getter-setter-pairs.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/related-getter-setter-pairs.d.ts.map new file mode 100644 index 00000000..ff801246 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/related-getter-setter-pairs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"related-getter-setter-pairs.d.ts","sourceRoot":"","sources":["../../src/rules/related-getter-setter-pairs.ts"],"names":[],"mappings":";AAwBA,wBAoFG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/related-getter-setter-pairs.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/related-getter-setter-pairs.js new file mode 100644 index 00000000..b0328ce1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/related-getter-setter-pairs.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'related-getter-setter-pairs', + meta: { + type: 'problem', + docs: { + description: 'Enforce that `get()` types should be assignable to their equivalent `set()` type', + recommended: 'strict', + requiresTypeChecking: true, + }, + messages: { + mismatch: '`get()` type should be assignable to its equivalent `set()` type.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const methodPairsStack = []; + function addPropertyNode(member, inner, kind) { + const methodPairs = methodPairsStack[methodPairsStack.length - 1]; + const { name } = (0, util_1.getNameFromMember)(member, context.sourceCode); + methodPairs.set(name, { + ...methodPairs.get(name), + [kind]: inner, + }); + } + return { + ':matches(ClassBody, TSInterfaceBody, TSTypeLiteral):exit'() { + const methodPairs = methodPairsStack[methodPairsStack.length - 1]; + for (const pair of methodPairs.values()) { + if (!pair.get || !pair.set) { + continue; + } + const getter = pair.get; + const getType = services.getTypeAtLocation(getter); + const setType = services.getTypeAtLocation(pair.set.params[0]); + if (!checker.isTypeAssignableTo(getType, setType)) { + context.report({ + node: getter.returnType.typeAnnotation, + messageId: 'mismatch', + }); + } + } + methodPairsStack.pop(); + }, + ':matches(MethodDefinition, TSMethodSignature)[kind=get]'(node) { + const getter = getMethodFromNode(node); + if (getter.returnType) { + addPropertyNode(node, getter, 'get'); + } + }, + ':matches(MethodDefinition, TSMethodSignature)[kind=set]'(node) { + const setter = getMethodFromNode(node); + if (setter.params.length === 1) { + addPropertyNode(node, setter, 'set'); + } + }, + 'ClassBody, TSInterfaceBody, TSTypeLiteral'() { + methodPairsStack.push(new Map()); + }, + }; + }, +}); +function getMethodFromNode(node) { + return node.type === utils_1.AST_NODE_TYPES.TSMethodSignature ? node : node.value; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-array-sort-compare.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-array-sort-compare.d.ts new file mode 100644 index 00000000..38ade8de --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-array-sort-compare.d.ts @@ -0,0 +1,9 @@ +export type Options = [ + { + ignoreStringArrays?: boolean; + } +]; +export type MessageIds = 'requireCompare'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"requireCompare", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=require-array-sort-compare.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-array-sort-compare.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-array-sort-compare.d.ts.map new file mode 100644 index 00000000..c8c8342f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-array-sort-compare.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"require-array-sort-compare.d.ts","sourceRoot":"","sources":["../../src/rules/require-array-sort-compare.ts"],"names":[],"mappings":"AAWA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,gBAAgB,CAAC;;AAE1C,wBAyEG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-array-sort-compare.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-array-sort-compare.js new file mode 100644 index 00000000..eff6280b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-array-sort-compare.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'require-array-sort-compare', + meta: { + type: 'problem', + docs: { + description: 'Require `Array#sort` and `Array#toSorted` calls to always provide a `compareFunction`', + requiresTypeChecking: true, + }, + messages: { + requireCompare: "Require 'compare' argument.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + ignoreStringArrays: { + type: 'boolean', + description: 'Whether to ignore arrays in which all elements are strings.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + ignoreStringArrays: true, + }, + ], + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + /** + * Check if a given node is an array which all elements are string. + */ + function isStringArrayNode(node) { + const type = services.getTypeAtLocation(node); + if (checker.isArrayType(type) || checker.isTupleType(type)) { + const typeArgs = checker.getTypeArguments(type); + return typeArgs.every(arg => (0, util_1.getTypeName)(checker, arg) === 'string'); + } + return false; + } + function checkSortArgument(callee) { + if (!(0, util_1.isStaticMemberAccessOfValue)(callee, context, 'sort', 'toSorted')) { + return; + } + const calleeObjType = (0, util_1.getConstrainedTypeAtLocation)(services, callee.object); + if (options.ignoreStringArrays && isStringArrayNode(callee.object)) { + return; + } + if ((0, util_1.isTypeArrayTypeOrUnionOfArrayTypes)(calleeObjType, checker)) { + context.report({ node: callee.parent, messageId: 'requireCompare' }); + } + } + return { + 'CallExpression[arguments.length=0] > MemberExpression': checkSortArgument, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-await.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-await.d.ts new file mode 100644 index 00000000..a1a19a13 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-await.d.ts @@ -0,0 +1,3 @@ +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingAwait" | "removeAsync", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=require-await.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-await.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-await.d.ts.map new file mode 100644 index 00000000..5bf61da3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-await.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"require-await.d.ts","sourceRoot":"","sources":["../../src/rules/require-await.ts"],"names":[],"mappings":";AA8BA,wBAuRG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-await.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-await.js new file mode 100644 index 00000000..afc5dffe --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/require-await.js @@ -0,0 +1,263 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'require-await', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow async functions which do not return promises and have no `await` expression', + extendsBaseRule: true, + recommended: 'recommended', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + missingAwait: "{{name}} has no 'await' expression.", + removeAsync: "Remove 'async'.", + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + let scopeInfo = null; + /** + * Push the scope info object to the stack. + */ + function enterFunction(node) { + scopeInfo = { + hasAsync: node.async, + hasAwait: false, + isAsyncYield: false, + isGen: node.generator || false, + upper: scopeInfo, + }; + } + /** + * Pop the top scope info object from the stack. + * Also, it reports the function if needed. + */ + function exitFunction(node) { + /* istanbul ignore if */ if (!scopeInfo) { + // this shouldn't ever happen, as we have to exit a function after we enter it + return; + } + if (node.async && + !scopeInfo.hasAwait && + !isEmptyFunction(node) && + !(scopeInfo.isGen && scopeInfo.isAsyncYield)) { + // If the function belongs to a method definition or + // property, then the function's range may not include the + // `async` keyword and we should look at the parent instead. + const nodeWithAsyncKeyword = (node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition && + node.parent.value === node) || + (node.parent.type === utils_1.AST_NODE_TYPES.Property && + node.parent.method && + node.parent.value === node) + ? node.parent + : node; + const asyncToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(nodeWithAsyncKeyword, token => token.value === 'async'), 'The node is an async function, so it must have an "async" token.'); + const asyncRange = [ + asyncToken.range[0], + (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(asyncToken, { + includeComments: true, + }), 'There will always be a token after the "async" keyword.').range[0], + ]; + // Removing the `async` keyword can cause parsing errors if the + // current statement is relying on automatic semicolon insertion. + // If ASI is currently being used, then we should replace the + // `async` keyword with a semicolon. + const nextToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(asyncToken), 'There will always be a token after the "async" keyword.'); + const addSemiColon = nextToken.type === utils_1.AST_TOKEN_TYPES.Punctuator && + (nextToken.value === '[' || nextToken.value === '(') && + (nodeWithAsyncKeyword.type === utils_1.AST_NODE_TYPES.MethodDefinition || + (0, util_1.isStartOfExpressionStatement)(nodeWithAsyncKeyword)) && + (0, util_1.needsPrecedingSemicolon)(context.sourceCode, nodeWithAsyncKeyword); + const changes = [ + { range: asyncRange, replacement: addSemiColon ? ';' : undefined }, + ]; + // If there's a return type annotation and it's a + // `Promise`, we can also change the return type + // annotation to just `T` as part of the suggestion. + // Alternatively, if the function is a generator and + // the return type annotation is `AsyncGenerator`, + // then we can change it to `Generator`. + if (node.returnType?.typeAnnotation.type === + utils_1.AST_NODE_TYPES.TSTypeReference) { + if (scopeInfo.isGen) { + if (hasTypeName(node.returnType.typeAnnotation, 'AsyncGenerator')) { + changes.push({ + range: node.returnType.typeAnnotation.typeName.range, + replacement: 'Generator', + }); + } + } + else if (hasTypeName(node.returnType.typeAnnotation, 'Promise') && + node.returnType.typeAnnotation.typeArguments != null) { + const openAngle = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node.returnType.typeAnnotation, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && + token.value === '<'), 'There are type arguments, so the angle bracket will exist.'); + const closeAngle = (0, util_1.nullThrows)(context.sourceCode.getLastToken(node.returnType.typeAnnotation, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && + token.value === '>'), 'There are type arguments, so the angle bracket will exist.'); + changes.push( + // Remove the closing angled bracket. + { range: closeAngle.range, replacement: undefined }, + // Remove the "Promise" identifier + // and the opening angled bracket. + { + range: [ + node.returnType.typeAnnotation.typeName.range[0], + openAngle.range[1], + ], + replacement: undefined, + }); + } + } + context.report({ + loc: (0, util_1.getFunctionHeadLoc)(node, context.sourceCode), + node, + messageId: 'missingAwait', + data: { + name: (0, util_1.upperCaseFirst)((0, util_1.getFunctionNameWithKind)(node)), + }, + suggest: [ + { + messageId: 'removeAsync', + fix: (fixer) => changes.map(change => change.replacement != null + ? fixer.replaceTextRange(change.range, change.replacement) + : fixer.removeRange(change.range)), + }, + ], + }); + } + scopeInfo = scopeInfo.upper; + } + /** + * Checks if the node returns a thenable type + */ + function isThenableType(node) { + const type = checker.getTypeAtLocation(node); + return tsutils.isThenableType(checker, node, type); + } + /** + * Marks the current scope as having an await + */ + function markAsHasAwait() { + if (!scopeInfo) { + return; + } + scopeInfo.hasAwait = true; + } + /** + * Mark `scopeInfo.isAsyncYield` to `true` if it + * 1) delegates async generator function + * or + * 2) yields thenable type + */ + function visitYieldExpression(node) { + if (!scopeInfo?.isGen || !node.argument) { + return; + } + if (node.argument.type === utils_1.AST_NODE_TYPES.Literal) { + // ignoring this as for literals we don't need to check the definition + // eg : async function* run() { yield* 1 } + return; + } + if (!node.delegate) { + if (isThenableType(services.esTreeNodeToTSNodeMap.get(node.argument))) { + scopeInfo.isAsyncYield = true; + } + return; + } + const type = services.getTypeAtLocation(node.argument); + const typesToCheck = expandUnionOrIntersectionType(type); + for (const type of typesToCheck) { + const asyncIterator = tsutils.getWellKnownSymbolPropertyOfType(type, 'asyncIterator', checker); + if (asyncIterator != null) { + scopeInfo.isAsyncYield = true; + break; + } + } + } + return { + ArrowFunctionExpression: enterFunction, + 'ArrowFunctionExpression:exit': exitFunction, + AwaitExpression: markAsHasAwait, + 'ForOfStatement[await = true]': markAsHasAwait, + FunctionDeclaration: enterFunction, + 'FunctionDeclaration:exit': exitFunction, + FunctionExpression: enterFunction, + 'FunctionExpression:exit': exitFunction, + 'VariableDeclaration[kind = "await using"]': markAsHasAwait, + YieldExpression: visitYieldExpression, + // check body-less async arrow function. + // ignore `async () => await foo` because it's obviously correct + 'ArrowFunctionExpression[async = true] > :not(BlockStatement, AwaitExpression)'(node) { + const expression = services.esTreeNodeToTSNodeMap.get(node); + if (isThenableType(expression)) { + markAsHasAwait(); + } + }, + ReturnStatement(node) { + // short circuit early to avoid unnecessary type checks + if (!scopeInfo || scopeInfo.hasAwait || !scopeInfo.hasAsync) { + return; + } + const { expression } = services.esTreeNodeToTSNodeMap.get(node); + if (expression && isThenableType(expression)) { + markAsHasAwait(); + } + }, + }; + }, +}); +function isEmptyFunction(node) { + return (node.body.type === utils_1.AST_NODE_TYPES.BlockStatement && + node.body.body.length === 0); +} +function expandUnionOrIntersectionType(type) { + if (type.isUnionOrIntersection()) { + return type.types.flatMap(expandUnionOrIntersectionType); + } + return [type]; +} +function hasTypeName(typeReference, typeName) { + return (typeReference.typeName.type === utils_1.AST_NODE_TYPES.Identifier && + typeReference.typeName.name === typeName); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-plus-operands.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-plus-operands.d.ts new file mode 100644 index 00000000..25eee616 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-plus-operands.d.ts @@ -0,0 +1,14 @@ +export type Options = [ + { + allowAny?: boolean; + allowBoolean?: boolean; + allowNullish?: boolean; + allowNumberAndString?: boolean; + allowRegExp?: boolean; + skipCompoundAssignments?: boolean; + } +]; +export type MessageIds = 'bigintAndNumber' | 'invalid' | 'mismatched'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=restrict-plus-operands.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-plus-operands.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-plus-operands.d.ts.map new file mode 100644 index 00000000..a65b537c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-plus-operands.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"restrict-plus-operands.d.ts","sourceRoot":"","sources":["../../src/rules/restrict-plus-operands.ts"],"names":[],"mappings":"AAcA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,oBAAoB,CAAC,EAAE,OAAO,CAAC;QAC/B,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,uBAAuB,CAAC,EAAE,OAAO,CAAC;KACnC;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,iBAAiB,GAAG,SAAS,GAAG,YAAY,CAAC;;AAEtE,wBA0OG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-plus-operands.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-plus-operands.js new file mode 100644 index 00000000..8b05a736 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-plus-operands.js @@ -0,0 +1,231 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'restrict-plus-operands', + meta: { + type: 'problem', + docs: { + description: 'Require both operands of addition to be the same type and be `bigint`, `number`, or `string`', + recommended: { + recommended: true, + strict: [ + { + allowAny: false, + allowBoolean: false, + allowNullish: false, + allowNumberAndString: false, + allowRegExp: false, + }, + ], + }, + requiresTypeChecking: true, + }, + messages: { + bigintAndNumber: "Numeric '+' operations must either be both bigints or both numbers. Got `{{left}}` + `{{right}}`.", + invalid: "Invalid operand for a '+' operation. Operands must each be a number or {{stringLike}}. Got `{{type}}`.", + mismatched: "Operands of '+' operations must be a number or {{stringLike}}. Got `{{left}}` + `{{right}}`.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowAny: { + type: 'boolean', + description: 'Whether to allow `any` typed values.', + }, + allowBoolean: { + type: 'boolean', + description: 'Whether to allow `boolean` typed values.', + }, + allowNullish: { + type: 'boolean', + description: 'Whether to allow potentially `null` or `undefined` typed values.', + }, + allowNumberAndString: { + type: 'boolean', + description: 'Whether to allow `bigint`/`number` typed values and `string` typed values to be added together.', + }, + allowRegExp: { + type: 'boolean', + description: 'Whether to allow `regexp` typed values.', + }, + skipCompoundAssignments: { + type: 'boolean', + description: 'Whether to skip compound assignments such as `+=`.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowAny: true, + allowBoolean: true, + allowNullish: true, + allowNumberAndString: true, + allowRegExp: true, + skipCompoundAssignments: false, + }, + ], + create(context, [{ allowAny, allowBoolean, allowNullish, allowNumberAndString, allowRegExp, skipCompoundAssignments, },]) { + const services = (0, util_1.getParserServices)(context); + const typeChecker = services.program.getTypeChecker(); + const stringLikes = [ + allowAny && '`any`', + allowBoolean && '`boolean`', + allowNullish && '`null`', + allowRegExp && '`RegExp`', + allowNullish && '`undefined`', + ].filter((value) => typeof value === 'string'); + const stringLike = stringLikes.length + ? stringLikes.length === 1 + ? `string, allowing a string + ${stringLikes[0]}` + : `string, allowing a string + any of: ${stringLikes.join(', ')}` + : 'string'; + function getTypeConstrained(node) { + return typeChecker.getBaseTypeOfLiteralType((0, util_1.getConstrainedTypeAtLocation)(services, node)); + } + function checkPlusOperands(node) { + const leftType = getTypeConstrained(node.left); + const rightType = getTypeConstrained(node.right); + if (leftType === rightType && + tsutils.isTypeFlagSet(leftType, ts.TypeFlags.BigIntLike | + ts.TypeFlags.NumberLike | + ts.TypeFlags.StringLike)) { + return; + } + let hadIndividualComplaint = false; + for (const [baseNode, baseType, otherType] of [ + [node.left, leftType, rightType], + [node.right, rightType, leftType], + ]) { + if (isTypeFlagSetInUnion(baseType, ts.TypeFlags.ESSymbolLike | + ts.TypeFlags.Never | + ts.TypeFlags.Unknown) || + (!allowAny && isTypeFlagSetInUnion(baseType, ts.TypeFlags.Any)) || + (!allowBoolean && + isTypeFlagSetInUnion(baseType, ts.TypeFlags.BooleanLike)) || + (!allowNullish && + (0, util_1.isTypeFlagSet)(baseType, ts.TypeFlags.Null | ts.TypeFlags.Undefined))) { + context.report({ + node: baseNode, + messageId: 'invalid', + data: { + type: typeChecker.typeToString(baseType), + stringLike, + }, + }); + hadIndividualComplaint = true; + continue; + } + // RegExps also contain ts.TypeFlags.Any & ts.TypeFlags.Object + for (const subBaseType of tsutils.unionConstituents(baseType)) { + const typeName = (0, util_1.getTypeName)(typeChecker, subBaseType); + if (typeName === 'RegExp' + ? !allowRegExp || + tsutils.isTypeFlagSet(otherType, ts.TypeFlags.NumberLike) + : (!allowAny && (0, util_1.isTypeAnyType)(subBaseType)) || + isDeeplyObjectType(subBaseType)) { + context.report({ + node: baseNode, + messageId: 'invalid', + data: { + type: typeChecker.typeToString(subBaseType), + stringLike, + }, + }); + hadIndividualComplaint = true; + continue; + } + } + } + if (hadIndividualComplaint) { + return; + } + for (const [baseType, otherType] of [ + [leftType, rightType], + [rightType, leftType], + ]) { + if (!allowNumberAndString && + isTypeFlagSetInUnion(baseType, ts.TypeFlags.StringLike) && + isTypeFlagSetInUnion(otherType, ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike)) { + return context.report({ + node, + messageId: 'mismatched', + data: { + left: typeChecker.typeToString(leftType), + right: typeChecker.typeToString(rightType), + stringLike, + }, + }); + } + if (isTypeFlagSetInUnion(baseType, ts.TypeFlags.NumberLike) && + isTypeFlagSetInUnion(otherType, ts.TypeFlags.BigIntLike)) { + return context.report({ + node, + messageId: 'bigintAndNumber', + data: { + left: typeChecker.typeToString(leftType), + right: typeChecker.typeToString(rightType), + }, + }); + } + } + } + return { + "BinaryExpression[operator='+']": checkPlusOperands, + ...(!skipCompoundAssignments && { + "AssignmentExpression[operator='+=']"(node) { + checkPlusOperands(node); + }, + }), + }; + }, +}); +function isDeeplyObjectType(type) { + return type.isIntersection() + ? tsutils.intersectionConstituents(type).every(tsutils.isObjectType) + : tsutils.unionConstituents(type).every(tsutils.isObjectType); +} +function isTypeFlagSetInUnion(type, flag) { + return tsutils + .unionConstituents(type) + .some(subType => tsutils.isTypeFlagSet(subType, flag)); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-template-expressions.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-template-expressions.d.ts new file mode 100644 index 00000000..935de1ec --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-template-expressions.d.ts @@ -0,0 +1,18 @@ +import type { Type, TypeChecker } from 'typescript'; +import type { TypeOrValueSpecifier } from '../util'; +import { isTypeAnyType, isTypeNeverType } from '../util'; +type OptionTester = (type: Type, checker: TypeChecker, recursivelyCheckType: (type: Type) => boolean) => boolean; +declare const optionTesters: { + type: "Array" | "RegExp" | "Boolean" | "Number" | "Any" | "Nullish" | "Never"; + option: "allowAny" | "allowBoolean" | "allowNullish" | "allowRegExp" | "allowNever" | "allowNumber" | "allowArray"; + tester: typeof isTypeAnyType | typeof isTypeNeverType | OptionTester | ((type: Type, checker: TypeChecker, recursivelyCheckType: (type: Type) => boolean) => boolean) | ((type: Type, checker: TypeChecker) => boolean); +}[]; +export type Options = [ + { + allow?: TypeOrValueSpecifier[]; + } & Partial> +]; +export type MessageId = 'invalidType'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"invalidType", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=restrict-template-expressions.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-template-expressions.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-template-expressions.d.ts.map new file mode 100644 index 00000000..e72ec9b3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-template-expressions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"restrict-template-expressions.d.ts","sourceRoot":"","sources":["../../src/rules/restrict-template-expressions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AASpD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,OAAO,EAKL,aAAa,EAEb,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB,KAAK,YAAY,GAAG,CAClB,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,WAAW,EACpB,oBAAoB,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,KAC1C,OAAO,CAAC;AAOb,QAAA,MAAM,aAAa;;;4IARY,IAAI,KAAK,OAAO,KAaF,OAAO,2CAW7B,OAAO;GAQ3B,CAAC;AAEJ,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,KAAK,CAAC,EAAE,oBAAoB,EAAE,CAAC;KAChC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC;CACvE,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG,aAAa,CAAC;;AAEtC,wBA2GG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-template-expressions.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-template-expressions.js new file mode 100644 index 00000000..b514423c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/restrict-template-expressions.js @@ -0,0 +1,119 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const type_utils_1 = require("@typescript-eslint/type-utils"); +const utils_1 = require("@typescript-eslint/utils"); +const typescript_1 = require("typescript"); +const util_1 = require("../util"); +const testTypeFlag = (flagsToCheck) => type => (0, util_1.isTypeFlagSet)(type, flagsToCheck); +const optionTesters = [ + ['Any', util_1.isTypeAnyType], + [ + 'Array', + (type, checker, recursivelyCheckType) => (checker.isArrayType(type) || checker.isTupleType(type)) && + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + recursivelyCheckType(type.getNumberIndexType()), + ], + // eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum + ['Boolean', testTypeFlag(typescript_1.TypeFlags.BooleanLike)], + ['Nullish', testTypeFlag(typescript_1.TypeFlags.Null | typescript_1.TypeFlags.Undefined)], + ['Number', testTypeFlag(typescript_1.TypeFlags.NumberLike | typescript_1.TypeFlags.BigIntLike)], + [ + 'RegExp', + (type, checker) => (0, util_1.getTypeName)(checker, type) === 'RegExp', + ], + ['Never', util_1.isTypeNeverType], +].map(([type, tester]) => ({ + type, + option: `allow${type}`, + tester, +})); +exports.default = (0, util_1.createRule)({ + name: 'restrict-template-expressions', + meta: { + type: 'problem', + docs: { + description: 'Enforce template literal expressions to be of `string` type', + recommended: { + recommended: true, + strict: [ + { + allowAny: false, + allowBoolean: false, + allowNever: false, + allowNullish: false, + allowNumber: false, + allowRegExp: false, + }, + ], + }, + requiresTypeChecking: true, + }, + messages: { + invalidType: 'Invalid type "{{type}}" of template literal expression.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + ...Object.fromEntries(optionTesters.map(({ type, option }) => [ + option, + { + type: 'boolean', + description: `Whether to allow \`${type.toLowerCase()}\` typed values in template expressions.`, + }, + ])), + allow: { + description: `Types to allow in template expressions.`, + ...type_utils_1.typeOrValueSpecifiersSchema, + }, + }, + }, + ], + }, + defaultOptions: [ + { + allow: [{ name: ['Error', 'URL', 'URLSearchParams'], from: 'lib' }], + allowAny: true, + allowBoolean: true, + allowNullish: true, + allowNumber: true, + allowRegExp: true, + }, + ], + create(context, [{ allow, ...options }]) { + const services = (0, util_1.getParserServices)(context); + const { program } = services; + const checker = program.getTypeChecker(); + const enabledOptionTesters = optionTesters.filter(({ option }) => options[option]); + return { + TemplateLiteral(node) { + // don't check tagged template literals + if (node.parent.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression) { + return; + } + for (const expression of node.expressions) { + const expressionType = (0, util_1.getConstrainedTypeAtLocation)(services, expression); + if (!recursivelyCheckType(expressionType)) { + context.report({ + node: expression, + messageId: 'invalidType', + data: { type: checker.typeToString(expressionType) }, + }); + } + } + }, + }; + function recursivelyCheckType(innerType) { + if (innerType.isUnion()) { + return innerType.types.every(recursivelyCheckType); + } + if (innerType.isIntersection()) { + return innerType.types.some(recursivelyCheckType); + } + return ((0, util_1.isTypeFlagSet)(innerType, typescript_1.TypeFlags.StringLike) || + (0, type_utils_1.typeMatchesSomeSpecifier)(innerType, allow, program) || + enabledOptionTesters.some(({ tester }) => tester(innerType, checker, recursivelyCheckType))); + } + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/return-await.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/return-await.d.ts new file mode 100644 index 00000000..4b9a3c7f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/return-await.d.ts @@ -0,0 +1,4 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule<"disallowedPromiseAwait" | "disallowedPromiseAwaitSuggestion" | "nonPromiseAwait" | "requiredPromiseAwait" | "requiredPromiseAwaitSuggestion", [string], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener>; +export default _default; +//# sourceMappingURL=return-await.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/return-await.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/return-await.d.ts.map new file mode 100644 index 00000000..42247338 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/return-await.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"return-await.d.ts","sourceRoot":"","sources":["../../src/rules/return-await.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;;AAiCnE,wBAuXG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/return-await.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/return-await.js new file mode 100644 index 00000000..b3340253 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/return-await.js @@ -0,0 +1,363 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'return-await', + meta: { + type: 'problem', + docs: { + description: 'Enforce consistent awaiting of returned promises', + recommended: { + strict: ['error-handling-correctness-only'], + }, + requiresTypeChecking: true, + }, + fixable: 'code', + // eslint-disable-next-line eslint-plugin/require-meta-has-suggestions -- suggestions are exposed through a helper. + hasSuggestions: true, + messages: { + disallowedPromiseAwait: 'Returning an awaited promise is not allowed in this context.', + disallowedPromiseAwaitSuggestion: 'Remove `await` before the expression. Use caution as this may impact control flow.', + nonPromiseAwait: 'Returning an awaited value that is not a promise is not allowed.', + requiredPromiseAwait: 'Returning an awaited promise is required in this context.', + requiredPromiseAwaitSuggestion: 'Add `await` before the expression. Use caution as this may impact control flow.', + }, + schema: [ + { + type: 'string', + oneOf: [ + { + type: 'string', + description: 'Requires that all returned promises be awaited.', + enum: ['always'], + }, + { + type: 'string', + description: 'In error-handling contexts, the rule enforces that returned promises must be awaited. In ordinary contexts, the rule does not enforce any particular behavior around whether returned promises are awaited.', + enum: ['error-handling-correctness-only'], + }, + { + type: 'string', + description: 'In error-handling contexts, the rule enforces that returned promises must be awaited. In ordinary contexts, the rule enforces that returned promises _must not_ be awaited.', + enum: ['in-try-catch'], + }, + { + type: 'string', + description: 'Disallows awaiting any returned promises.', + enum: ['never'], + }, + ], + }, + ], + }, + defaultOptions: ['in-try-catch'], + create(context, [option]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const scopeInfoStack = []; + function enterFunction(node) { + scopeInfoStack.push({ + hasAsync: node.async, + owningFunc: node, + }); + } + function exitFunction() { + scopeInfoStack.pop(); + } + function affectsExplicitResourceManagement(node) { + // just need to determine if there is a `using` declaration in scope. + let scope = context.sourceCode.getScope(node); + const functionScope = scope.variableScope; + while (true) { + for (const variable of scope.variables) { + if (variable.defs.length !== 1) { + // This can't be the case for `using` or `await using` since it's + // an error to redeclare those more than once in the same scope, + // unlike, say, `var` declarations. + continue; + } + const declaration = variable.defs[0]; + const declaratorNode = declaration.node; + const declarationNode = declaratorNode.parent; + // if it's a using/await using declaration, and it comes _before_ the + // node we're checking, it affects control flow for that node. + if (['await using', 'using'].includes(declarationNode.kind) && + declaratorNode.range[1] < node.range[0]) { + return true; + } + } + if (scope === functionScope) { + // We've checked all the relevant scopes + break; + } + // This should always exist, since the rule should only be checking + // contexts in which `return` statements are legal, which should always + // be inside a function. + scope = (0, util_1.nullThrows)(scope.upper, 'Expected parent scope to exist. return-await should only operate on return statements within functions'); + } + return false; + } + /** + * Tests whether a node is inside of an explicit error handling context + * (try/catch/finally) in a way that throwing an exception will have an + * impact on the program's control flow. + */ + function affectsExplicitErrorHandling(node) { + // If an error-handling block is followed by another error-handling block, + // control flow is affected by whether promises in it are awaited or not. + // Otherwise, we need to check recursively for nested try statements until + // we get to the top level of a function or the program. If by then, + // there's no offending error-handling blocks, it doesn't affect control + // flow. + const tryAncestorResult = findContainingTryStatement(node); + if (tryAncestorResult == null) { + return false; + } + const { block, tryStatement } = tryAncestorResult; + switch (block) { + case 'catch': + // Exceptions thrown in catch blocks followed by a finally block affect + // control flow. + if (tryStatement.finallyBlock != null) { + return true; + } + // Otherwise recurse. + return affectsExplicitErrorHandling(tryStatement); + case 'finally': + return affectsExplicitErrorHandling(tryStatement); + case 'try': + // Try blocks are always followed by either a catch or finally, + // so exceptions thrown here always affect control flow. + return true; + default: { + const __never = block; + throw new Error(`Unexpected block type: ${String(__never)}`); + } + } + } + /** + * A try _statement_ is the whole thing that encompasses try block, + * catch clause, and finally block. This function finds the nearest + * enclosing try statement (if present) for a given node, and reports which + * part of the try statement the node is in. + */ + function findContainingTryStatement(node) { + let child = node; + let ancestor = node.parent; + while (ancestor && !ts.isFunctionLike(ancestor)) { + if (ts.isTryStatement(ancestor)) { + let block; + if (child === ancestor.tryBlock) { + block = 'try'; + } + else if (child === ancestor.catchClause) { + block = 'catch'; + } + else if (child === ancestor.finallyBlock) { + block = 'finally'; + } + return { + block: (0, util_1.nullThrows)(block, 'Child of a try statement must be a try block, catch clause, or finally block'), + tryStatement: ancestor, + }; + } + child = ancestor; + ancestor = ancestor.parent; + } + return undefined; + } + function removeAwait(fixer, node) { + // Should always be an await node; but let's be safe. + /* istanbul ignore if */ if (!(0, util_1.isAwaitExpression)(node)) { + return null; + } + const awaitToken = context.sourceCode.getFirstToken(node, util_1.isAwaitKeyword); + // Should always be the case; but let's be safe. + /* istanbul ignore if */ if (!awaitToken) { + return null; + } + const startAt = awaitToken.range[0]; + let endAt = awaitToken.range[1]; + // Also remove any extraneous whitespace after `await`, if there is any. + const nextToken = context.sourceCode.getTokenAfter(awaitToken, { + includeComments: true, + }); + if (nextToken) { + endAt = nextToken.range[0]; + } + return fixer.removeRange([startAt, endAt]); + } + function insertAwait(fixer, node, isHighPrecendence) { + if (isHighPrecendence) { + return fixer.insertTextBefore(node, 'await '); + } + return [ + fixer.insertTextBefore(node, 'await ('), + fixer.insertTextAfter(node, ')'), + ]; + } + function test(node, expression) { + let child; + const isAwait = ts.isAwaitExpression(expression); + if (isAwait) { + child = expression.getChildAt(1); + } + else { + child = expression; + } + const type = checker.getTypeAtLocation(child); + const certainty = (0, util_1.needsToBeAwaited)(checker, expression, type); + // handle awaited _non_thenables + if (certainty !== util_1.Awaitable.Always) { + if (isAwait) { + if (certainty === util_1.Awaitable.May) { + return; + } + context.report({ + node, + messageId: 'nonPromiseAwait', + fix: fixer => removeAwait(fixer, node), + }); + } + return; + } + // At this point it's definitely a thenable. + const affectsErrorHandling = affectsExplicitErrorHandling(expression) || + affectsExplicitResourceManagement(node); + const useAutoFix = !affectsErrorHandling; + const ruleConfiguration = getConfiguration(option); + const shouldAwaitInCurrentContext = affectsErrorHandling + ? ruleConfiguration.errorHandlingContext + : ruleConfiguration.ordinaryContext; + switch (shouldAwaitInCurrentContext) { + case 'await': + if (!isAwait) { + context.report({ + node, + messageId: 'requiredPromiseAwait', + ...(0, util_1.getFixOrSuggest)({ + fixOrSuggest: useAutoFix ? 'fix' : 'suggest', + suggestion: { + messageId: 'requiredPromiseAwaitSuggestion', + fix: fixer => insertAwait(fixer, node, (0, util_1.isHigherPrecedenceThanAwait)(expression)), + }, + }), + }); + } + break; + case "don't-care": + break; + case 'no-await': + if (isAwait) { + context.report({ + node, + messageId: 'disallowedPromiseAwait', + ...(0, util_1.getFixOrSuggest)({ + fixOrSuggest: useAutoFix ? 'fix' : 'suggest', + suggestion: { + messageId: 'disallowedPromiseAwaitSuggestion', + fix: fixer => removeAwait(fixer, node), + }, + }), + }); + } + break; + } + } + function findPossiblyReturnedNodes(node) { + if (node.type === utils_1.AST_NODE_TYPES.ConditionalExpression) { + return [ + ...findPossiblyReturnedNodes(node.alternate), + ...findPossiblyReturnedNodes(node.consequent), + ]; + } + return [node]; + } + return { + ArrowFunctionExpression: enterFunction, + 'ArrowFunctionExpression:exit': exitFunction, + FunctionDeclaration: enterFunction, + 'FunctionDeclaration:exit': exitFunction, + FunctionExpression: enterFunction, + 'FunctionExpression:exit': exitFunction, + // executes after less specific handler, so exitFunction is called + 'ArrowFunctionExpression[async = true]:exit'(node) { + if (node.body.type !== utils_1.AST_NODE_TYPES.BlockStatement) { + findPossiblyReturnedNodes(node.body).forEach(node => { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + test(node, tsNode); + }); + } + }, + ReturnStatement(node) { + const scopeInfo = scopeInfoStack.at(-1); + if (!scopeInfo?.hasAsync || !node.argument) { + return; + } + findPossiblyReturnedNodes(node.argument).forEach(node => { + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + test(node, tsNode); + }); + }, + }; + }, +}); +function getConfiguration(option) { + switch (option) { + case 'always': + return { + errorHandlingContext: 'await', + ordinaryContext: 'await', + }; + case 'error-handling-correctness-only': + return { + errorHandlingContext: 'await', + ordinaryContext: "don't-care", + }; + case 'in-try-catch': + return { + errorHandlingContext: 'await', + ordinaryContext: 'no-await', + }; + case 'never': + return { + errorHandlingContext: 'no-await', + ordinaryContext: 'no-await', + }; + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/sort-type-constituents.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/sort-type-constituents.d.ts new file mode 100644 index 00000000..fa9964cb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/sort-type-constituents.d.ts @@ -0,0 +1,13 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = [ + { + caseSensitive?: boolean; + checkIntersections?: boolean; + checkUnions?: boolean; + groupOrder?: string[]; + } +]; +export type MessageIds = 'notSorted' | 'notSortedNamed' | 'suggestFix'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=sort-type-constituents.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/sort-type-constituents.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/sort-type-constituents.d.ts.map new file mode 100644 index 00000000..118a378d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/sort-type-constituents.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort-type-constituents.d.ts","sourceRoot":"","sources":["../../src/rules/sort-type-constituents.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AA6GnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,aAAa,CAAC,EAAE,OAAO,CAAC;QACxB,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;KACvB;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG,gBAAgB,GAAG,YAAY,CAAC;;AAEvE,wBA0MG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/sort-type-constituents.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/sort-type-constituents.js new file mode 100644 index 00000000..c4a51cce --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/sort-type-constituents.js @@ -0,0 +1,272 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +var Group; +(function (Group) { + Group["conditional"] = "conditional"; + Group["function"] = "function"; + Group["import"] = "import"; + Group["intersection"] = "intersection"; + Group["keyword"] = "keyword"; + Group["nullish"] = "nullish"; + Group["literal"] = "literal"; + Group["named"] = "named"; + Group["object"] = "object"; + Group["operator"] = "operator"; + Group["tuple"] = "tuple"; + Group["union"] = "union"; +})(Group || (Group = {})); +function getGroup(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSConditionalType: + return Group.conditional; + case utils_1.AST_NODE_TYPES.TSConstructorType: + case utils_1.AST_NODE_TYPES.TSFunctionType: + return Group.function; + case utils_1.AST_NODE_TYPES.TSImportType: + return Group.import; + case utils_1.AST_NODE_TYPES.TSIntersectionType: + return Group.intersection; + case utils_1.AST_NODE_TYPES.TSAnyKeyword: + case utils_1.AST_NODE_TYPES.TSBigIntKeyword: + case utils_1.AST_NODE_TYPES.TSBooleanKeyword: + case utils_1.AST_NODE_TYPES.TSNeverKeyword: + case utils_1.AST_NODE_TYPES.TSNumberKeyword: + case utils_1.AST_NODE_TYPES.TSObjectKeyword: + case utils_1.AST_NODE_TYPES.TSStringKeyword: + case utils_1.AST_NODE_TYPES.TSSymbolKeyword: + case utils_1.AST_NODE_TYPES.TSThisType: + case utils_1.AST_NODE_TYPES.TSUnknownKeyword: + case utils_1.AST_NODE_TYPES.TSIntrinsicKeyword: + return Group.keyword; + case utils_1.AST_NODE_TYPES.TSNullKeyword: + case utils_1.AST_NODE_TYPES.TSUndefinedKeyword: + case utils_1.AST_NODE_TYPES.TSVoidKeyword: + return Group.nullish; + case utils_1.AST_NODE_TYPES.TSLiteralType: + case utils_1.AST_NODE_TYPES.TSTemplateLiteralType: + return Group.literal; + case utils_1.AST_NODE_TYPES.TSArrayType: + case utils_1.AST_NODE_TYPES.TSIndexedAccessType: + case utils_1.AST_NODE_TYPES.TSInferType: + case utils_1.AST_NODE_TYPES.TSTypeReference: + case utils_1.AST_NODE_TYPES.TSQualifiedName: + return Group.named; + case utils_1.AST_NODE_TYPES.TSMappedType: + case utils_1.AST_NODE_TYPES.TSTypeLiteral: + return Group.object; + case utils_1.AST_NODE_TYPES.TSTypeOperator: + case utils_1.AST_NODE_TYPES.TSTypeQuery: + return Group.operator; + case utils_1.AST_NODE_TYPES.TSTupleType: + return Group.tuple; + case utils_1.AST_NODE_TYPES.TSUnionType: + return Group.union; + // These types should never occur as part of a union/intersection + case utils_1.AST_NODE_TYPES.TSAbstractKeyword: + case utils_1.AST_NODE_TYPES.TSAsyncKeyword: + case utils_1.AST_NODE_TYPES.TSDeclareKeyword: + case utils_1.AST_NODE_TYPES.TSExportKeyword: + case utils_1.AST_NODE_TYPES.TSNamedTupleMember: + case utils_1.AST_NODE_TYPES.TSOptionalType: + case utils_1.AST_NODE_TYPES.TSPrivateKeyword: + case utils_1.AST_NODE_TYPES.TSProtectedKeyword: + case utils_1.AST_NODE_TYPES.TSPublicKeyword: + case utils_1.AST_NODE_TYPES.TSReadonlyKeyword: + case utils_1.AST_NODE_TYPES.TSRestType: + case utils_1.AST_NODE_TYPES.TSStaticKeyword: + case utils_1.AST_NODE_TYPES.TSTypePredicate: + /* istanbul ignore next */ + throw new Error(`Unexpected Type ${node.type}`); + } +} +function caseSensitiveSort(a, b) { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; +} +exports.default = (0, util_1.createRule)({ + name: 'sort-type-constituents', + meta: { + type: 'suggestion', + deprecated: { + deprecatedSince: '7.13.0', + replacedBy: [ + { + plugin: { + name: 'eslint-plugin-perfectionist', + url: 'https://perfectionist.dev', + }, + rule: { + name: 'perfectionist/sort-intersection-types', + url: 'https://perfectionist.dev/rules/sort-intersection-types', + }, + }, + { + plugin: { + name: 'eslint-plugin-perfectionist', + url: 'https://perfectionist.dev', + }, + rule: { + name: 'perfectionist/sort-union-types', + url: 'https://perfectionist.dev/rules/sort-union-types', + }, + }, + ], + url: 'https://github.com/typescript-eslint/typescript-eslint/pull/9253', + }, + docs: { + description: 'Enforce constituents of a type union/intersection to be sorted alphabetically', + }, + fixable: 'code', + hasSuggestions: true, + messages: { + notSorted: '{{type}} type constituents must be sorted.', + notSortedNamed: '{{type}} type {{name}} constituents must be sorted.', + suggestFix: 'Sort constituents of type (removes all comments).', + }, + replacedBy: [ + 'perfectionist/sort-intersection-types', + 'perfectionist/sort-union-types', + ], + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + caseSensitive: { + type: 'boolean', + description: 'Whether to sort using case sensitive string comparisons.', + }, + checkIntersections: { + type: 'boolean', + description: 'Whether to check intersection types (`&`).', + }, + checkUnions: { + type: 'boolean', + description: 'Whether to check union types (`|`).', + }, + groupOrder: { + type: 'array', + description: 'Ordering of the groups.', + items: { + type: 'string', + enum: (0, util_1.getEnumNames)(Group), + }, + }, + }, + }, + ], + }, + defaultOptions: [ + { + caseSensitive: false, + checkIntersections: true, + checkUnions: true, + groupOrder: [ + Group.named, + Group.keyword, + Group.operator, + Group.literal, + Group.function, + Group.import, + Group.conditional, + Group.object, + Group.tuple, + Group.intersection, + Group.union, + Group.nullish, + ], + }, + ], + create(context, [{ caseSensitive, checkIntersections, checkUnions, groupOrder }]) { + const collator = new Intl.Collator('en', { + numeric: true, + sensitivity: 'base', + }); + function checkSorting(node) { + const sourceOrder = node.types.map(type => { + const group = groupOrder?.indexOf(getGroup(type)) ?? -1; + return { + node: type, + group: group === -1 ? Number.MAX_SAFE_INTEGER : group, + text: context.sourceCode.getText(type), + }; + }); + const expectedOrder = [...sourceOrder].sort((a, b) => { + if (a.group !== b.group) { + return a.group - b.group; + } + if (caseSensitive) { + return caseSensitiveSort(a.text, b.text); + } + return (collator.compare(a.text, b.text) || + (a.text < b.text ? -1 : a.text > b.text ? 1 : 0)); + }); + const hasComments = node.types.some(type => { + const count = context.sourceCode.getCommentsBefore(type).length + + context.sourceCode.getCommentsAfter(type).length; + return count > 0; + }); + for (let i = 0; i < expectedOrder.length; i += 1) { + if (expectedOrder[i].node !== sourceOrder[i].node) { + let messageId = 'notSorted'; + const data = { + name: '', + type: node.type === utils_1.AST_NODE_TYPES.TSIntersectionType + ? 'Intersection' + : 'Union', + }; + if (node.parent.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration) { + messageId = 'notSortedNamed'; + data.name = node.parent.id.name; + } + const fix = fixer => { + const sorted = expectedOrder + .map(t => (0, util_1.typeNodeRequiresParentheses)(t.node, t.text) || + (node.type === utils_1.AST_NODE_TYPES.TSIntersectionType && + t.node.type === utils_1.AST_NODE_TYPES.TSUnionType) + ? `(${t.text})` + : t.text) + .join(node.type === utils_1.AST_NODE_TYPES.TSIntersectionType ? ' & ' : ' | '); + return fixer.replaceText(node, sorted); + }; + return context.report({ + node, + messageId, + data, + // don't autofix if any of the types have leading/trailing comments + // the logic for preserving them correctly is a pain - we may implement this later + ...(hasComments + ? { + suggest: [ + { + messageId: 'suggestFix', + fix, + }, + ], + } + : { fix }), + }); + } + } + } + return { + ...(checkIntersections && { + TSIntersectionType(node) { + checkSorting(node); + }, + }), + ...(checkUnions && { + TSUnionType(node) { + checkSorting(node); + }, + }), + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/strict-boolean-expressions.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/strict-boolean-expressions.d.ts new file mode 100644 index 00000000..64dcfe77 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/strict-boolean-expressions.d.ts @@ -0,0 +1,18 @@ +export type Options = [ + { + allowAny?: boolean; + allowNullableBoolean?: boolean; + allowNullableEnum?: boolean; + allowNullableNumber?: boolean; + allowNullableObject?: boolean; + allowNullableString?: boolean; + allowNumber?: boolean; + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean; + allowString?: boolean; + } +]; +type ConditionErrorMessageId = 'conditionErrorAny' | 'conditionErrorNullableBoolean' | 'conditionErrorNullableEnum' | 'conditionErrorNullableNumber' | 'conditionErrorNullableObject' | 'conditionErrorNullableString' | 'conditionErrorNullish' | 'conditionErrorNumber' | 'conditionErrorObject' | 'conditionErrorOther' | 'conditionErrorString'; +export type MessageId = 'conditionFixCastBoolean' | 'conditionFixCompareArrayLengthNonzero' | 'conditionFixCompareArrayLengthZero' | 'conditionFixCompareEmptyString' | 'conditionFixCompareFalse' | 'conditionFixCompareNaN' | 'conditionFixCompareNullish' | 'conditionFixCompareStringLength' | 'conditionFixCompareTrue' | 'conditionFixCompareZero' | 'conditionFixDefaultEmptyString' | 'conditionFixDefaultFalse' | 'conditionFixDefaultZero' | 'explicitBooleanReturnType' | 'noStrictNullCheck' | 'predicateCannotBeAsync' | ConditionErrorMessageId; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=strict-boolean-expressions.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/strict-boolean-expressions.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/strict-boolean-expressions.d.ts.map new file mode 100644 index 00000000..080330eb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/strict-boolean-expressions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"strict-boolean-expressions.d.ts","sourceRoot":"","sources":["../../src/rules/strict-boolean-expressions.ts"],"names":[],"mappings":"AAsBA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;QAC/B,iBAAiB,CAAC,EAAE,OAAO,CAAC;QAC5B,mBAAmB,CAAC,EAAE,OAAO,CAAC;QAC9B,mBAAmB,CAAC,EAAE,OAAO,CAAC;QAC9B,mBAAmB,CAAC,EAAE,OAAO,CAAC;QAC9B,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,sDAAsD,CAAC,EAAE,OAAO,CAAC;QACjE,WAAW,CAAC,EAAE,OAAO,CAAC;KACvB;CACF,CAAC;AAEF,KAAK,uBAAuB,GACxB,mBAAmB,GACnB,+BAA+B,GAC/B,4BAA4B,GAC5B,8BAA8B,GAC9B,8BAA8B,GAC9B,8BAA8B,GAC9B,uBAAuB,GACvB,sBAAsB,GACtB,sBAAsB,GACtB,qBAAqB,GACrB,sBAAsB,CAAC;AAE3B,MAAM,MAAM,SAAS,GACjB,yBAAyB,GACzB,uCAAuC,GACvC,oCAAoC,GACpC,gCAAgC,GAChC,0BAA0B,GAC1B,wBAAwB,GACxB,4BAA4B,GAC5B,iCAAiC,GACjC,yBAAyB,GACzB,yBAAyB,GACzB,gCAAgC,GAChC,0BAA0B,GAC1B,yBAAyB,GACzB,2BAA2B,GAC3B,mBAAmB,GACnB,wBAAwB,GACxB,uBAAuB,CAAC;;AAE5B,wBAq/BG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/strict-boolean-expressions.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/strict-boolean-expressions.js new file mode 100644 index 00000000..14074655 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/strict-boolean-expressions.js @@ -0,0 +1,882 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const assertionFunctionUtils_1 = require("../util/assertionFunctionUtils"); +exports.default = (0, util_1.createRule)({ + name: 'strict-boolean-expressions', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow certain types in boolean expressions', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + conditionErrorAny: 'Unexpected any value in {{context}}. ' + + 'An explicit comparison or type conversion is required.', + conditionErrorNullableBoolean: 'Unexpected nullable boolean value in {{context}}. ' + + 'Please handle the nullish case explicitly.', + conditionErrorNullableEnum: 'Unexpected nullable enum value in {{context}}. ' + + 'Please handle the nullish/zero/NaN cases explicitly.', + conditionErrorNullableNumber: 'Unexpected nullable number value in {{context}}. ' + + 'Please handle the nullish/zero/NaN cases explicitly.', + conditionErrorNullableObject: 'Unexpected nullable object value in {{context}}. ' + + 'An explicit null check is required.', + conditionErrorNullableString: 'Unexpected nullable string value in {{context}}. ' + + 'Please handle the nullish/empty cases explicitly.', + conditionErrorNullish: 'Unexpected nullish value in conditional. ' + + 'The condition is always false.', + conditionErrorNumber: 'Unexpected number value in {{context}}. ' + + 'An explicit zero/NaN check is required.', + conditionErrorObject: 'Unexpected object value in {{context}}. ' + + 'The condition is always true.', + conditionErrorOther: 'Unexpected value in conditional. ' + + 'A boolean expression is required.', + conditionErrorString: 'Unexpected string value in {{context}}. ' + + 'An explicit empty string check is required.', + conditionFixCastBoolean: 'Explicitly convert value to a boolean (`Boolean(value)`)', + conditionFixCompareArrayLengthNonzero: "Change condition to check array's length (`value.length > 0`)", + conditionFixCompareArrayLengthZero: "Change condition to check array's length (`value.length === 0`)", + conditionFixCompareEmptyString: 'Change condition to check for empty string (`value !== ""`)', + conditionFixCompareFalse: 'Change condition to check if false (`value === false`)', + conditionFixCompareNaN: 'Change condition to check for NaN (`!Number.isNaN(value)`)', + conditionFixCompareNullish: 'Change condition to check for null/undefined (`value != null`)', + conditionFixCompareStringLength: "Change condition to check string's length (`value.length !== 0`)", + conditionFixCompareTrue: 'Change condition to check if true (`value === true`)', + conditionFixCompareZero: 'Change condition to check for 0 (`value !== 0`)', + conditionFixDefaultEmptyString: 'Explicitly treat nullish value the same as an empty string (`value ?? ""`)', + conditionFixDefaultFalse: 'Explicitly treat nullish value the same as false (`value ?? false`)', + conditionFixDefaultZero: 'Explicitly treat nullish value the same as 0 (`value ?? 0`)', + explicitBooleanReturnType: 'Add an explicit `boolean` return type annotation.', + noStrictNullCheck: 'This rule requires the `strictNullChecks` compiler option to be turned on to function correctly.', + predicateCannotBeAsync: "Predicate function should not be 'async'; expected a boolean return type.", + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowAny: { + type: 'boolean', + description: 'Whether to allow `any`s in a boolean context.', + }, + allowNullableBoolean: { + type: 'boolean', + description: 'Whether to allow nullable `boolean`s in a boolean context.', + }, + allowNullableEnum: { + type: 'boolean', + description: 'Whether to allow nullable `enum`s in a boolean context.', + }, + allowNullableNumber: { + type: 'boolean', + description: 'Whether to allow nullable `number`s in a boolean context.', + }, + allowNullableObject: { + type: 'boolean', + description: 'Whether to allow nullable `object`s, `symbol`s, and functions in a boolean context.', + }, + allowNullableString: { + type: 'boolean', + description: 'Whether to allow nullable `string`s in a boolean context.', + }, + allowNumber: { + type: 'boolean', + description: 'Whether to allow `number`s in a boolean context.', + }, + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: { + type: 'boolean', + description: 'Unless this is set to `true`, the rule will error on every file whose `tsconfig.json` does _not_ have the `strictNullChecks` compiler option (or `strict`) set to `true`.', + }, + allowString: { + type: 'boolean', + description: 'Whether to allow `string`s in a boolean context.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowAny: false, + allowNullableBoolean: false, + allowNullableEnum: false, + allowNullableNumber: false, + allowNullableObject: true, + allowNullableString: false, + allowNumber: true, + allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false, + allowString: true, + }, + ], + create(context, [options]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const compilerOptions = services.program.getCompilerOptions(); + const isStrictNullChecks = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks'); + if (!isStrictNullChecks && + options.allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing !== true) { + context.report({ + loc: { + start: { column: 0, line: 0 }, + end: { column: 0, line: 0 }, + }, + messageId: 'noStrictNullCheck', + }); + } + const traversedNodes = new Set(); + return { + CallExpression: traverseCallExpression, + ConditionalExpression: traverseTestExpression, + DoWhileStatement: traverseTestExpression, + ForStatement: traverseTestExpression, + IfStatement: traverseTestExpression, + 'LogicalExpression[operator!="??"]': traverseLogicalExpression, + 'UnaryExpression[operator="!"]': traverseUnaryLogicalExpression, + WhileStatement: traverseTestExpression, + }; + /** + * Inspects condition of a test expression. (`if`, `while`, `for`, etc.) + */ + function traverseTestExpression(node) { + if (node.test == null) { + return; + } + traverseNode(node.test, true); + } + /** + * Inspects the argument of a unary logical expression (`!`). + */ + function traverseUnaryLogicalExpression(node) { + traverseNode(node.argument, true); + } + /** + * Inspects the arguments of a logical expression (`&&`, `||`). + * + * If the logical expression is a descendant of a test expression, + * the `isCondition` flag should be set to true. + * Otherwise, if the logical expression is there on it's own, + * it's used for control flow and is not a condition itself. + */ + function traverseLogicalExpression(node, isCondition = false) { + // left argument is always treated as a condition + traverseNode(node.left, true); + // if the logical expression is used for control flow, + // then its right argument is used for its side effects only + traverseNode(node.right, isCondition); + } + function traverseCallExpression(node) { + const assertedArgument = (0, assertionFunctionUtils_1.findTruthinessAssertedArgument)(services, node); + if (assertedArgument != null) { + traverseNode(assertedArgument, true); + } + if ((0, util_1.isArrayMethodCallWithPredicate)(context, services, node)) { + const predicate = node.arguments.at(0); + if (predicate) { + checkArrayMethodCallPredicate(predicate); + } + } + } + /** + * Dedicated function to check array method predicate calls. Reports predicate + * arguments that don't return a boolean value. + */ + function checkArrayMethodCallPredicate(predicateNode) { + const isFunctionExpression = utils_1.ASTUtils.isFunction(predicateNode); + // custom message for accidental `async` function expressions + if (isFunctionExpression && predicateNode.async) { + return context.report({ + node: predicateNode, + messageId: 'predicateCannotBeAsync', + }); + } + const returnTypes = services + .getTypeAtLocation(predicateNode) + .getCallSignatures() + .map(signature => { + const type = signature.getReturnType(); + if (tsutils.isTypeParameter(type)) { + return checker.getBaseConstraintOfType(type) ?? type; + } + return type; + }); + const flattenTypes = [ + ...new Set(returnTypes.flatMap(type => tsutils.unionConstituents(type))), + ]; + const types = inspectVariantTypes(flattenTypes); + const reportType = determineReportType(types); + if (reportType == null) { + return; + } + const suggestions = []; + if (isFunctionExpression && + predicateNode.body.type !== utils_1.AST_NODE_TYPES.BlockStatement) { + suggestions.push(...getSuggestionsForConditionError(predicateNode.body, reportType)); + } + if (isFunctionExpression && !predicateNode.returnType) { + suggestions.push({ + messageId: 'explicitBooleanReturnType', + fix: fixer => { + if (predicateNode.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + (0, util_1.isParenlessArrowFunction)(predicateNode, context.sourceCode)) { + return [ + fixer.insertTextBefore(predicateNode.params[0], '('), + fixer.insertTextAfter(predicateNode.params[0], '): boolean'), + ]; + } + if (predicateNode.params.length === 0) { + const closingBracket = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(predicateNode, token => token.value === ')'), 'function expression has to have a closing parenthesis.'); + return fixer.insertTextAfter(closingBracket, ': boolean'); + } + const lastClosingParenthesis = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(predicateNode.params[predicateNode.params.length - 1], token => token.value === ')'), 'function expression has to have a closing parenthesis.'); + return fixer.insertTextAfter(lastClosingParenthesis, ': boolean'); + }, + }); + } + return context.report({ + node: predicateNode, + messageId: reportType, + data: { + context: 'array predicate return type', + }, + suggest: suggestions, + }); + } + /** + * Inspects any node. + * + * If it's a logical expression then it recursively traverses its arguments. + * If it's any other kind of node then it's type is finally checked against the rule, + * unless `isCondition` flag is set to false, in which case + * it's assumed to be used for side effects only and is skipped. + */ + function traverseNode(node, isCondition) { + // prevent checking the same node multiple times + if (traversedNodes.has(node)) { + return; + } + traversedNodes.add(node); + // for logical operator, we check its operands + if (node.type === utils_1.AST_NODE_TYPES.LogicalExpression && + node.operator !== '??') { + traverseLogicalExpression(node, isCondition); + return; + } + // skip if node is not a condition + if (!isCondition) { + return; + } + checkNode(node); + } + function determineReportType(types) { + const is = (...wantedTypes) => types.size === wantedTypes.length && + wantedTypes.every(type => types.has(type)); + // boolean + if (is('boolean') || is('truthy boolean')) { + // boolean is always ok + return undefined; + } + // never + if (is('never')) { + // never is always okay + return undefined; + } + // nullish + if (is('nullish')) { + // condition is always false + return 'conditionErrorNullish'; + } + // Known edge case: boolean `true` and nullish values are always valid boolean expressions + if (is('nullish', 'truthy boolean')) { + return; + } + // nullable boolean + if (is('nullish', 'boolean')) { + return !options.allowNullableBoolean + ? 'conditionErrorNullableBoolean' + : undefined; + } + // Known edge case: truthy primitives and nullish values are always valid boolean expressions + if ((options.allowNumber && is('nullish', 'truthy number')) || + (options.allowString && is('nullish', 'truthy string'))) { + return; + } + // string + if (is('string') || is('truthy string')) { + return !options.allowString ? 'conditionErrorString' : undefined; + } + // nullable string + if (is('nullish', 'string')) { + return !options.allowNullableString + ? 'conditionErrorNullableString' + : undefined; + } + // number + if (is('number') || is('truthy number')) { + return !options.allowNumber ? 'conditionErrorNumber' : undefined; + } + // nullable number + if (is('nullish', 'number')) { + return !options.allowNullableNumber + ? 'conditionErrorNullableNumber' + : undefined; + } + // object + if (is('object')) { + return 'conditionErrorObject'; + } + // nullable object + if (is('nullish', 'object')) { + return !options.allowNullableObject + ? 'conditionErrorNullableObject' + : undefined; + } + // nullable enum + if (is('nullish', 'number', 'enum') || + is('nullish', 'string', 'enum') || + is('nullish', 'truthy number', 'enum') || + is('nullish', 'truthy string', 'enum') || + // mixed enums + is('nullish', 'truthy number', 'truthy string', 'enum') || + is('nullish', 'truthy number', 'string', 'enum') || + is('nullish', 'truthy string', 'number', 'enum') || + is('nullish', 'number', 'string', 'enum')) { + return !options.allowNullableEnum + ? 'conditionErrorNullableEnum' + : undefined; + } + // any + if (is('any')) { + return !options.allowAny ? 'conditionErrorAny' : undefined; + } + return 'conditionErrorOther'; + } + function getSuggestionsForConditionError(node, conditionError) { + switch (conditionError) { + case 'conditionErrorAny': + return [ + { + messageId: 'conditionFixCastBoolean', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `Boolean(${code})`, + }), + }, + ]; + case 'conditionErrorNullableBoolean': + if (isLogicalNegationExpression(node.parent)) { + // if (!nullableBoolean) + return [ + { + messageId: 'conditionFixDefaultFalse', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} ?? false`, + }), + }, + { + messageId: 'conditionFixCompareFalse', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `${code} === false`, + }), + }, + ]; + } + // if (nullableBoolean) + return [ + { + messageId: 'conditionFixDefaultFalse', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} ?? false`, + }), + }, + { + messageId: 'conditionFixCompareTrue', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} === true`, + }), + }, + ]; + case 'conditionErrorNullableEnum': + if (isLogicalNegationExpression(node.parent)) { + return [ + { + messageId: 'conditionFixCompareNullish', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `${code} == null`, + }), + }, + ]; + } + return [ + { + messageId: 'conditionFixCompareNullish', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} != null`, + }), + }, + ]; + case 'conditionErrorNullableNumber': + if (isLogicalNegationExpression(node.parent)) { + // if (!nullableNumber) + return [ + { + messageId: 'conditionFixCompareNullish', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `${code} == null`, + }), + }, + { + messageId: 'conditionFixDefaultZero', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} ?? 0`, + }), + }, + { + messageId: 'conditionFixCastBoolean', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `!Boolean(${code})`, + }), + }, + ]; + } + // if (nullableNumber) + return [ + { + messageId: 'conditionFixCompareNullish', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} != null`, + }), + }, + { + messageId: 'conditionFixDefaultZero', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} ?? 0`, + }), + }, + { + messageId: 'conditionFixCastBoolean', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `Boolean(${code})`, + }), + }, + ]; + case 'conditionErrorNullableObject': + if (isLogicalNegationExpression(node.parent)) { + // if (!nullableObject) + return [ + { + messageId: 'conditionFixCompareNullish', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `${code} == null`, + }), + }, + ]; + } + // if (nullableObject) + return [ + { + messageId: 'conditionFixCompareNullish', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} != null`, + }), + }, + ]; + case 'conditionErrorNullableString': + if (isLogicalNegationExpression(node.parent)) { + // if (!nullableString) + return [ + { + messageId: 'conditionFixCompareNullish', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `${code} == null`, + }), + }, + { + messageId: 'conditionFixDefaultEmptyString', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} ?? ""`, + }), + }, + { + messageId: 'conditionFixCastBoolean', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `!Boolean(${code})`, + }), + }, + ]; + } + // if (nullableString) + return [ + { + messageId: 'conditionFixCompareNullish', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} != null`, + }), + }, + { + messageId: 'conditionFixDefaultEmptyString', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} ?? ""`, + }), + }, + { + messageId: 'conditionFixCastBoolean', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `Boolean(${code})`, + }), + }, + ]; + case 'conditionErrorNumber': + if (isArrayLengthExpression(node, checker, services)) { + if (isLogicalNegationExpression(node.parent)) { + // if (!array.length) + return [ + { + messageId: 'conditionFixCompareArrayLengthZero', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `${code} === 0`, + }), + }, + ]; + } + // if (array.length) + return [ + { + messageId: 'conditionFixCompareArrayLengthNonzero', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} > 0`, + }), + }, + ]; + } + if (isLogicalNegationExpression(node.parent)) { + // if (!number) + return [ + { + messageId: 'conditionFixCompareZero', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + // TODO: we have to compare to 0n if the type is bigint + wrap: code => `${code} === 0`, + }), + }, + { + // TODO: don't suggest this for bigint because it can't be NaN + messageId: 'conditionFixCompareNaN', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `Number.isNaN(${code})`, + }), + }, + { + messageId: 'conditionFixCastBoolean', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `!Boolean(${code})`, + }), + }, + ]; + } + // if (number) + return [ + { + messageId: 'conditionFixCompareZero', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} !== 0`, + }), + }, + { + messageId: 'conditionFixCompareNaN', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `!Number.isNaN(${code})`, + }), + }, + { + messageId: 'conditionFixCastBoolean', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `Boolean(${code})`, + }), + }, + ]; + case 'conditionErrorString': + if (isLogicalNegationExpression(node.parent)) { + // if (!string) + return [ + { + messageId: 'conditionFixCompareStringLength', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `${code}.length === 0`, + }), + }, + { + messageId: 'conditionFixCompareEmptyString', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `${code} === ""`, + }), + }, + { + messageId: 'conditionFixCastBoolean', + fix: (0, util_1.getWrappingFixer)({ + node: node.parent, + innerNode: node, + sourceCode: context.sourceCode, + wrap: code => `!Boolean(${code})`, + }), + }, + ]; + } + // if (string) + return [ + { + messageId: 'conditionFixCompareStringLength', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code}.length > 0`, + }), + }, + { + messageId: 'conditionFixCompareEmptyString', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `${code} !== ""`, + }), + }, + { + messageId: 'conditionFixCastBoolean', + fix: (0, util_1.getWrappingFixer)({ + node, + sourceCode: context.sourceCode, + wrap: code => `Boolean(${code})`, + }), + }, + ]; + case 'conditionErrorObject': + case 'conditionErrorNullish': + case 'conditionErrorOther': + return []; + default: + conditionError; + throw new Error('Unreachable'); + } + } + /** + * This function does the actual type check on a node. + * It analyzes the type of a node and checks if it is allowed in a boolean context. + */ + function checkNode(node) { + const type = (0, util_1.getConstrainedTypeAtLocation)(services, node); + const types = inspectVariantTypes(tsutils.unionConstituents(type)); + const reportType = determineReportType(types); + if (reportType != null) { + context.report({ + node, + messageId: reportType, + data: { + context: 'conditional', + }, + suggest: getSuggestionsForConditionError(node, reportType), + }); + } + } + /** + * Check union variants for the types we care about + */ + function inspectVariantTypes(types) { + const variantTypes = new Set(); + if (types.some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.VoidLike))) { + variantTypes.add('nullish'); + } + const booleans = types.filter(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.BooleanLike)); + // If incoming type is either "true" or "false", there will be one type + // object with intrinsicName set accordingly + // If incoming type is boolean, there will be two type objects with + // intrinsicName set "true" and "false" each because of ts-api-utils.unionConstituents() + if (booleans.length === 1) { + variantTypes.add(tsutils.isTrueLiteralType(booleans[0]) ? 'truthy boolean' : 'boolean'); + } + else if (booleans.length === 2) { + variantTypes.add('boolean'); + } + const strings = types.filter(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.StringLike)); + if (strings.length) { + if (strings.every(type => type.isStringLiteral() && type.value !== '')) { + variantTypes.add('truthy string'); + } + else { + variantTypes.add('string'); + } + } + const numbers = types.filter(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike)); + if (numbers.length) { + if (numbers.every(type => type.isNumberLiteral() && type.value !== 0)) { + variantTypes.add('truthy number'); + } + else { + variantTypes.add('number'); + } + } + if (types.some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.EnumLike))) { + variantTypes.add('enum'); + } + if (types.some(type => !tsutils.isTypeFlagSet(type, ts.TypeFlags.Null | + ts.TypeFlags.Undefined | + ts.TypeFlags.VoidLike | + ts.TypeFlags.BooleanLike | + ts.TypeFlags.StringLike | + ts.TypeFlags.NumberLike | + ts.TypeFlags.BigIntLike | + ts.TypeFlags.TypeParameter | + ts.TypeFlags.Any | + ts.TypeFlags.Unknown | + ts.TypeFlags.Never))) { + variantTypes.add(types.some(isBrandedBoolean) ? 'boolean' : 'object'); + } + if (types.some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.TypeParameter | + ts.TypeFlags.Any | + ts.TypeFlags.Unknown))) { + variantTypes.add('any'); + } + if (types.some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.Never))) { + variantTypes.add('never'); + } + return variantTypes; + } + }, +}); +function isLogicalNegationExpression(node) { + return node.type === utils_1.AST_NODE_TYPES.UnaryExpression && node.operator === '!'; +} +function isArrayLengthExpression(node, typeChecker, services) { + if (node.type !== utils_1.AST_NODE_TYPES.MemberExpression) { + return false; + } + if (node.computed) { + return false; + } + if (node.property.name !== 'length') { + return false; + } + const objectType = (0, util_1.getConstrainedTypeAtLocation)(services, node.object); + return (0, util_1.isTypeArrayTypeOrUnionOfArrayTypes)(objectType, typeChecker); +} +/** + * Verify is the type is a branded boolean (e.g. `type Foo = boolean & { __brand: 'Foo' }`) + * + * @param type The type checked + */ +function isBrandedBoolean(type) { + return (type.isIntersection() && + type.types.some(childType => isBooleanType(childType))); +} +function isBooleanType(expressionType) { + return tsutils.isTypeFlagSet(expressionType, ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/switch-exhaustiveness-check.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/switch-exhaustiveness-check.d.ts new file mode 100644 index 00000000..89d9f32b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/switch-exhaustiveness-check.d.ts @@ -0,0 +1,32 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type Options = [ + { + /** + * If `true`, allow `default` cases on switch statements with exhaustive + * cases. + * + * @default true + */ + allowDefaultCaseForExhaustiveSwitch?: boolean; + /** + * If `true`, require a `default` clause for switches on non-union types. + * + * @default false + */ + requireDefaultForNonUnion?: boolean; + /** + * Regular expression for a comment that can indicate an intentionally omitted default case. + */ + defaultCaseCommentPattern?: string; + /** + * If `true`, the `default` clause is used to determine whether the switch statement is exhaustive for union types. + * + * @default false + */ + considerDefaultExhaustiveForUnions?: boolean; + } +]; +export type MessageIds = 'addMissingCases' | 'dangerousDefaultCase' | 'switchIsNotExhaustive'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=switch-exhaustiveness-check.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/switch-exhaustiveness-check.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/switch-exhaustiveness-check.d.ts.map new file mode 100644 index 00000000..e0ce6f1c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/switch-exhaustiveness-check.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"switch-exhaustiveness-check.d.ts","sourceRoot":"","sources":["../../src/rules/switch-exhaustiveness-check.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAyBnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE;;;;;WAKG;QACH,mCAAmC,CAAC,EAAE,OAAO,CAAC;QAE9C;;;;WAIG;QACH,yBAAyB,CAAC,EAAE,OAAO,CAAC;QAEpC;;WAEG;QACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;QAEnC;;;;WAIG;QACH,kCAAkC,CAAC,EAAE,OAAO,CAAC;KAC9C;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAClB,iBAAiB,GACjB,sBAAsB,GACtB,uBAAuB,CAAC;;AAE5B,wBA+VG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/switch-exhaustiveness-check.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/switch-exhaustiveness-check.js new file mode 100644 index 00000000..cce57df8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/switch-exhaustiveness-check.js @@ -0,0 +1,291 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +const DEFAULT_COMMENT_PATTERN = /^no default$/iu; +exports.default = (0, util_1.createRule)({ + name: 'switch-exhaustiveness-check', + meta: { + type: 'suggestion', + docs: { + description: 'Require switch-case statements to be exhaustive', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + addMissingCases: 'Add branches for missing cases.', + dangerousDefaultCase: 'The switch statement is exhaustive, so the default case is unnecessary.', + switchIsNotExhaustive: 'Switch is not exhaustive. Cases not matched: {{missingBranches}}', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + allowDefaultCaseForExhaustiveSwitch: { + type: 'boolean', + description: `If 'true', allow 'default' cases on switch statements with exhaustive cases.`, + }, + considerDefaultExhaustiveForUnions: { + type: 'boolean', + description: `If 'true', the 'default' clause is used to determine whether the switch statement is exhaustive for union type`, + }, + defaultCaseCommentPattern: { + type: 'string', + description: `Regular expression for a comment that can indicate an intentionally omitted default case.`, + }, + requireDefaultForNonUnion: { + type: 'boolean', + description: `If 'true', require a 'default' clause for switches on non-union types.`, + }, + }, + }, + ], + }, + defaultOptions: [ + { + allowDefaultCaseForExhaustiveSwitch: true, + considerDefaultExhaustiveForUnions: false, + requireDefaultForNonUnion: false, + }, + ], + create(context, [{ allowDefaultCaseForExhaustiveSwitch, considerDefaultExhaustiveForUnions, defaultCaseCommentPattern, requireDefaultForNonUnion, },]) { + const services = (0, util_1.getParserServices)(context); + const checker = services.program.getTypeChecker(); + const compilerOptions = services.program.getCompilerOptions(); + const commentRegExp = defaultCaseCommentPattern != null + ? new RegExp(defaultCaseCommentPattern, 'u') + : DEFAULT_COMMENT_PATTERN; + function getCommentDefaultCase(node) { + const lastCase = node.cases.at(-1); + const commentsAfterLastCase = lastCase + ? context.sourceCode.getCommentsAfter(lastCase) + : []; + const defaultCaseComment = commentsAfterLastCase.at(-1); + if (commentRegExp.test(defaultCaseComment?.value.trim() || '')) { + return defaultCaseComment; + } + return; + } + function typeToString(type) { + return checker.typeToString(type, undefined, ts.TypeFormatFlags.AllowUniqueESSymbolType | + ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope | + ts.TypeFormatFlags.UseFullyQualifiedType); + } + function getSwitchMetadata(node) { + const defaultCase = node.cases.find(switchCase => switchCase.test == null); + const discriminantType = (0, util_1.getConstrainedTypeAtLocation)(services, node.discriminant); + const symbolName = discriminantType.getSymbol()?.escapedName; + const containsNonLiteralType = doesTypeContainNonLiteralType(discriminantType); + const caseTypes = new Set(); + for (const switchCase of node.cases) { + // If the `test` property of the switch case is `null`, then we are on a + // `default` case. + if (switchCase.test == null) { + continue; + } + const caseType = (0, util_1.getConstrainedTypeAtLocation)(services, switchCase.test); + caseTypes.add(caseType); + } + const missingLiteralBranchTypes = []; + for (const unionPart of tsutils.unionConstituents(discriminantType)) { + for (const intersectionPart of tsutils.intersectionConstituents(unionPart)) { + if (caseTypes.has(intersectionPart) || + !isTypeLiteralLikeType(intersectionPart)) { + continue; + } + // "missing", "optional" and "undefined" types are different runtime objects, + // but all of them have TypeFlags.Undefined type flag + if ([...caseTypes].some(tsutils.isIntrinsicUndefinedType) && + tsutils.isIntrinsicUndefinedType(intersectionPart)) { + continue; + } + missingLiteralBranchTypes.push(intersectionPart); + } + } + return { + containsNonLiteralType, + defaultCase: defaultCase ?? getCommentDefaultCase(node), + missingLiteralBranchTypes, + symbolName, + }; + } + function checkSwitchExhaustive(node, switchMetadata) { + const { defaultCase, missingLiteralBranchTypes, symbolName } = switchMetadata; + // If considerDefaultExhaustiveForUnions is enabled, the presence of a default case + // always makes the switch exhaustive. + if (considerDefaultExhaustiveForUnions && defaultCase != null) { + return; + } + if (missingLiteralBranchTypes.length > 0) { + context.report({ + node: node.discriminant, + messageId: 'switchIsNotExhaustive', + data: { + missingBranches: missingLiteralBranchTypes + .map(missingType => tsutils.isTypeFlagSet(missingType, ts.TypeFlags.ESSymbolLike) + ? `typeof ${missingType.getSymbol()?.escapedName}` + : typeToString(missingType)) + .join(' | '), + }, + suggest: [ + { + messageId: 'addMissingCases', + fix(fixer) { + return fixSwitch(fixer, node, missingLiteralBranchTypes, defaultCase, symbolName?.toString()); + }, + }, + ], + }); + } + } + function fixSwitch(fixer, node, missingBranchTypes, // null means default branch + defaultCase, symbolName) { + const lastCase = node.cases.length > 0 ? node.cases[node.cases.length - 1] : null; + const caseIndent = lastCase + ? ' '.repeat(lastCase.loc.start.column) + : // If there are no cases, use indentation of the switch statement and + // leave it to the user to format it correctly. + ' '.repeat(node.loc.start.column); + const missingCases = []; + for (const missingBranchType of missingBranchTypes) { + if (missingBranchType == null) { + missingCases.push(`default: { throw new Error('default case') }`); + continue; + } + const missingBranchName = missingBranchType.getSymbol()?.escapedName; + let caseTest = tsutils.isTypeFlagSet(missingBranchType, ts.TypeFlags.ESSymbolLike) + ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + missingBranchName + : typeToString(missingBranchType); + if (symbolName && + (missingBranchName || missingBranchName === '') && + (0, util_1.requiresQuoting)(missingBranchName.toString(), compilerOptions.target)) { + const escapedBranchName = missingBranchName + .replaceAll("'", "\\'") + .replaceAll('\n', '\\n') + .replaceAll('\r', '\\r'); + caseTest = `${symbolName}['${escapedBranchName}']`; + } + missingCases.push(`case ${caseTest}: { throw new Error('Not implemented yet: ${caseTest + .replaceAll('\\', '\\\\') + .replaceAll("'", "\\'")} case') }`); + } + const fixString = missingCases + .map(code => `${caseIndent}${code}`) + .join('\n'); + if (lastCase) { + if (defaultCase) { + const beforeFixString = missingCases + .map(code => `${code}\n${caseIndent}`) + .join(''); + return fixer.insertTextBefore(defaultCase, beforeFixString); + } + return fixer.insertTextAfter(lastCase, `\n${fixString}`); + } + // There were no existing cases. + const openingBrace = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.discriminant, util_1.isOpeningBraceToken), util_1.NullThrowsReasons.MissingToken('{', 'discriminant')); + const closingBrace = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.discriminant, util_1.isClosingBraceToken), util_1.NullThrowsReasons.MissingToken('}', 'discriminant')); + return fixer.replaceTextRange([openingBrace.range[0], closingBrace.range[1]], ['{', fixString, `${caseIndent}}`].join('\n')); + } + function checkSwitchUnnecessaryDefaultCase(switchMetadata) { + if (allowDefaultCaseForExhaustiveSwitch) { + return; + } + const { containsNonLiteralType, defaultCase, missingLiteralBranchTypes } = switchMetadata; + if (missingLiteralBranchTypes.length === 0 && + defaultCase != null && + !containsNonLiteralType) { + context.report({ + node: defaultCase, + messageId: 'dangerousDefaultCase', + }); + } + } + function checkSwitchNoUnionDefaultCase(node, switchMetadata) { + if (!requireDefaultForNonUnion) { + return; + } + const { containsNonLiteralType, defaultCase } = switchMetadata; + if (containsNonLiteralType && defaultCase == null) { + context.report({ + node: node.discriminant, + messageId: 'switchIsNotExhaustive', + data: { missingBranches: 'default' }, + suggest: [ + { + messageId: 'addMissingCases', + fix(fixer) { + return fixSwitch(fixer, node, [null], defaultCase); + }, + }, + ], + }); + } + } + return { + SwitchStatement(node) { + const switchMetadata = getSwitchMetadata(node); + checkSwitchExhaustive(node, switchMetadata); + checkSwitchUnnecessaryDefaultCase(switchMetadata); + checkSwitchNoUnionDefaultCase(node, switchMetadata); + }, + }; + }, +}); +function isTypeLiteralLikeType(type) { + return tsutils.isTypeFlagSet(type, ts.TypeFlags.Literal | + ts.TypeFlags.Undefined | + ts.TypeFlags.Null | + ts.TypeFlags.UniqueESSymbol); +} +/** + * For example: + * + * - `"foo" | "bar"` is a type with all literal types. + * - `"foo" | number` is a type that contains non-literal types. + * - `"foo" & { bar: 1 }` is a type that contains non-literal types. + * + * Default cases are never superfluous in switches with non-literal types. + */ +function doesTypeContainNonLiteralType(type) { + return tsutils + .unionConstituents(type) + .some(type => tsutils + .intersectionConstituents(type) + .every(subType => !isTypeLiteralLikeType(subType))); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/triple-slash-reference.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/triple-slash-reference.d.ts new file mode 100644 index 00000000..74601006 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/triple-slash-reference.d.ts @@ -0,0 +1,11 @@ +export type Options = [ + { + lib?: 'always' | 'never'; + path?: 'always' | 'never'; + types?: 'always' | 'never' | 'prefer-import'; + } +]; +export type MessageIds = 'tripleSlashReference'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"tripleSlashReference", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>; +export default _default; +//# sourceMappingURL=triple-slash-reference.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/triple-slash-reference.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/triple-slash-reference.d.ts.map new file mode 100644 index 00000000..29be62d0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/triple-slash-reference.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"triple-slash-reference.d.ts","sourceRoot":"","sources":["../../src/rules/triple-slash-reference.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,GAAG,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;QACzB,IAAI,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;QAC1B,KAAK,CAAC,EAAE,QAAQ,GAAG,OAAO,GAAG,eAAe,CAAC;KAC9C;CACF,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,sBAAsB,CAAC;;AAEhD,wBA0HG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/triple-slash-reference.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/triple-slash-reference.js new file mode 100644 index 00000000..edc8d3f0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/triple-slash-reference.js @@ -0,0 +1,110 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'triple-slash-reference', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow certain triple slash directives in favor of ES6-style import declarations', + recommended: 'recommended', + }, + messages: { + tripleSlashReference: 'Do not use a triple slash reference for {{module}}, use `import` style instead.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + lib: { + type: 'string', + description: 'What to enforce for `/// ` references.', + enum: ['always', 'never'], + }, + path: { + type: 'string', + description: 'What to enforce for `/// ` references.', + enum: ['always', 'never'], + }, + types: { + type: 'string', + description: 'What to enforce for `/// ` references.', + enum: ['always', 'never', 'prefer-import'], + }, + }, + }, + ], + }, + defaultOptions: [ + { + lib: 'always', + path: 'never', + types: 'prefer-import', + }, + ], + create(context, [{ lib, path, types }]) { + let programNode; + const references = []; + function hasMatchingReference(source) { + references.forEach(reference => { + if (reference.importName === source.value) { + context.report({ + node: reference.comment, + messageId: 'tripleSlashReference', + data: { + module: reference.importName, + }, + }); + } + }); + } + return { + ImportDeclaration(node) { + if (programNode) { + hasMatchingReference(node.source); + } + }, + Program(node) { + if (lib === 'always' && path === 'always' && types === 'always') { + return; + } + programNode = node; + const referenceRegExp = /^\/\s* { + if (comment.type !== utils_1.AST_TOKEN_TYPES.Line) { + return; + } + const referenceResult = referenceRegExp.exec(comment.value); + if (referenceResult) { + if ((referenceResult[1] === 'types' && types === 'never') || + (referenceResult[1] === 'path' && path === 'never') || + (referenceResult[1] === 'lib' && lib === 'never')) { + context.report({ + node: comment, + messageId: 'tripleSlashReference', + data: { + module: referenceResult[2], + }, + }); + return; + } + if (referenceResult[1] === 'types' && types === 'prefer-import') { + references.push({ comment, importName: referenceResult[2] }); + } + } + }); + }, + TSImportEqualsDeclaration(node) { + if (programNode) { + const reference = node.moduleReference; + if (reference.type === utils_1.AST_NODE_TYPES.TSExternalModuleReference) { + hasMatchingReference(reference.expression); + } + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.d.ts new file mode 100644 index 00000000..9b313681 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.d.ts @@ -0,0 +1,15 @@ +export declare const enum OptionKeys { + ArrayDestructuring = "arrayDestructuring", + ArrowParameter = "arrowParameter", + MemberVariableDeclaration = "memberVariableDeclaration", + ObjectDestructuring = "objectDestructuring", + Parameter = "parameter", + PropertyDeclaration = "propertyDeclaration", + VariableDeclaration = "variableDeclaration", + VariableDeclarationIgnoreFunction = "variableDeclarationIgnoreFunction" +} +export type Options = [Partial>]; +export type MessageIds = 'expectedTypedef' | 'expectedTypedefNamed'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=typedef.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.d.ts.map new file mode 100644 index 00000000..9585d8ec --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"typedef.d.ts","sourceRoot":"","sources":["../../src/rules/typedef.ts"],"names":[],"mappings":"AAMA,0BAAkB,UAAU;IAC1B,kBAAkB,uBAAuB;IACzC,cAAc,mBAAmB;IACjC,yBAAyB,8BAA8B;IACvD,mBAAmB,wBAAwB;IAC3C,SAAS,cAAc;IACvB,mBAAmB,wBAAwB;IAC3C,mBAAmB,wBAAwB;IAC3C,iCAAiC,sCAAsC;CACxE;AAED,MAAM,MAAM,OAAO,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;AAE7D,MAAM,MAAM,UAAU,GAAG,iBAAiB,GAAG,sBAAsB,CAAC;;AAEpE,wBAqSG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.js new file mode 100644 index 00000000..1e9b27b9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.js @@ -0,0 +1,239 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OptionKeys = void 0; +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +var OptionKeys; +(function (OptionKeys) { + OptionKeys["ArrayDestructuring"] = "arrayDestructuring"; + OptionKeys["ArrowParameter"] = "arrowParameter"; + OptionKeys["MemberVariableDeclaration"] = "memberVariableDeclaration"; + OptionKeys["ObjectDestructuring"] = "objectDestructuring"; + OptionKeys["Parameter"] = "parameter"; + OptionKeys["PropertyDeclaration"] = "propertyDeclaration"; + OptionKeys["VariableDeclaration"] = "variableDeclaration"; + OptionKeys["VariableDeclarationIgnoreFunction"] = "variableDeclarationIgnoreFunction"; +})(OptionKeys || (exports.OptionKeys = OptionKeys = {})); +exports.default = (0, util_1.createRule)({ + name: 'typedef', + meta: { + type: 'suggestion', + deprecated: { + deprecatedSince: '8.33.0', + message: 'This is an old rule that is no longer recommended for use.', + }, + docs: { + description: 'Require type annotations in certain places', + }, + messages: { + expectedTypedef: 'Expected a type annotation.', + expectedTypedefNamed: 'Expected {{name}} to have a type annotation.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + [OptionKeys.ArrayDestructuring]: { + type: 'boolean', + description: 'Whether to enforce type annotations on variables declared using array destructuring.', + }, + [OptionKeys.ArrowParameter]: { + type: 'boolean', + description: 'Whether to enforce type annotations for parameters of arrow functions.', + }, + [OptionKeys.MemberVariableDeclaration]: { + type: 'boolean', + description: 'Whether to enforce type annotations on member variables of classes.', + }, + [OptionKeys.ObjectDestructuring]: { + type: 'boolean', + description: 'Whether to enforce type annotations on variables declared using object destructuring.', + }, + [OptionKeys.Parameter]: { + type: 'boolean', + description: 'Whether to enforce type annotations for parameters of functions and methods.', + }, + [OptionKeys.PropertyDeclaration]: { + type: 'boolean', + description: 'Whether to enforce type annotations for properties of interfaces and types.', + }, + [OptionKeys.VariableDeclaration]: { + type: 'boolean', + description: 'Whether to enforce type annotations for variable declarations, excluding array and object destructuring.', + }, + [OptionKeys.VariableDeclarationIgnoreFunction]: { + type: 'boolean', + description: 'Whether to ignore variable declarations for non-arrow and arrow functions.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + [OptionKeys.ArrayDestructuring]: false, + [OptionKeys.ArrowParameter]: false, + [OptionKeys.MemberVariableDeclaration]: false, + [OptionKeys.ObjectDestructuring]: false, + [OptionKeys.Parameter]: false, + [OptionKeys.PropertyDeclaration]: false, + [OptionKeys.VariableDeclaration]: false, + [OptionKeys.VariableDeclarationIgnoreFunction]: false, + }, + ], + create(context, [{ arrayDestructuring, arrowParameter, memberVariableDeclaration, objectDestructuring, parameter, propertyDeclaration, variableDeclaration, variableDeclarationIgnoreFunction, },]) { + function report(location, name) { + context.report({ + node: location, + messageId: name ? 'expectedTypedefNamed' : 'expectedTypedef', + data: { name }, + }); + } + function getNodeName(node) { + return node.type === utils_1.AST_NODE_TYPES.Identifier ? node.name : undefined; + } + function isForOfStatementContext(node) { + let current = node.parent; + while (current) { + switch (current.type) { + case utils_1.AST_NODE_TYPES.VariableDeclarator: + case utils_1.AST_NODE_TYPES.VariableDeclaration: + case utils_1.AST_NODE_TYPES.ObjectPattern: + case utils_1.AST_NODE_TYPES.ArrayPattern: + case utils_1.AST_NODE_TYPES.Property: + current = current.parent; + break; + case utils_1.AST_NODE_TYPES.ForOfStatement: + return true; + default: + current = undefined; + } + } + return false; + } + function checkParameters(params) { + for (const param of params) { + let annotationNode; + switch (param.type) { + case utils_1.AST_NODE_TYPES.AssignmentPattern: + annotationNode = param.left; + break; + case utils_1.AST_NODE_TYPES.TSParameterProperty: + annotationNode = param.parameter; + // Check TS parameter property with default value like `constructor(private param: string = 'something') {}` + if (annotationNode.type === utils_1.AST_NODE_TYPES.AssignmentPattern) { + annotationNode = annotationNode.left; + } + break; + default: + annotationNode = param; + break; + } + if (!annotationNode.typeAnnotation) { + report(param, getNodeName(param)); + } + } + } + function isVariableDeclarationIgnoreFunction(node) { + return (variableDeclarationIgnoreFunction === true && + (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression || + node.type === utils_1.AST_NODE_TYPES.FunctionExpression)); + } + function isAncestorHasTypeAnnotation(node) { + let ancestor = node.parent; + while (ancestor) { + if ((ancestor.type === utils_1.AST_NODE_TYPES.ObjectPattern || + ancestor.type === utils_1.AST_NODE_TYPES.ArrayPattern) && + ancestor.typeAnnotation) { + return true; + } + ancestor = ancestor.parent; + } + return false; + } + return { + ...(arrayDestructuring && { + ArrayPattern(node) { + if (node.parent.type === utils_1.AST_NODE_TYPES.RestElement && + node.parent.typeAnnotation) { + return; + } + if (!node.typeAnnotation && + !isForOfStatementContext(node) && + !isAncestorHasTypeAnnotation(node) && + node.parent.type !== utils_1.AST_NODE_TYPES.AssignmentExpression) { + report(node); + } + }, + }), + ...(arrowParameter && { + ArrowFunctionExpression(node) { + checkParameters(node.params); + }, + }), + ...(memberVariableDeclaration && { + PropertyDefinition(node) { + if (!(node.value && isVariableDeclarationIgnoreFunction(node.value)) && + !node.typeAnnotation) { + report(node, node.key.type === utils_1.AST_NODE_TYPES.Identifier + ? node.key.name + : undefined); + } + }, + }), + ...(parameter && { + 'FunctionDeclaration, FunctionExpression'(node) { + checkParameters(node.params); + }, + }), + ...(objectDestructuring && { + ObjectPattern(node) { + if (!node.typeAnnotation && + !isForOfStatementContext(node) && + !isAncestorHasTypeAnnotation(node)) { + report(node); + } + }, + }), + ...(propertyDeclaration && { + 'TSIndexSignature, TSPropertySignature'(node) { + if (!node.typeAnnotation) { + report(node, node.type === utils_1.AST_NODE_TYPES.TSPropertySignature + ? getNodeName(node.key) + : undefined); + } + }, + }), + VariableDeclarator(node) { + if (!variableDeclaration || + node.id.typeAnnotation || + (node.id.type === utils_1.AST_NODE_TYPES.ArrayPattern && + !arrayDestructuring) || + (node.id.type === utils_1.AST_NODE_TYPES.ObjectPattern && + !objectDestructuring) || + (node.init && isVariableDeclarationIgnoreFunction(node.init))) { + return; + } + let current = node.parent; + while (current) { + switch (current.type) { + case utils_1.AST_NODE_TYPES.VariableDeclaration: + // Keep looking upwards + current = current.parent; + break; + case utils_1.AST_NODE_TYPES.ForOfStatement: + case utils_1.AST_NODE_TYPES.ForInStatement: + // Stop traversing and don't report an error + return; + default: + // Stop traversing + current = undefined; + break; + } + } + report(node, getNodeName(node.id)); + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unbound-method.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unbound-method.d.ts new file mode 100644 index 00000000..92a5eb49 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unbound-method.d.ts @@ -0,0 +1,8 @@ +interface Config { + ignoreStatic: boolean; +} +export type Options = [Config]; +export type MessageIds = 'unbound' | 'unboundWithoutThisAnnotation'; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=unbound-method.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unbound-method.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unbound-method.d.ts.map new file mode 100644 index 00000000..af2e60cf --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unbound-method.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"unbound-method.d.ts","sourceRoot":"","sources":["../../src/rules/unbound-method.ts"],"names":[],"mappings":"AAkBA,UAAU,MAAM;IACd,YAAY,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,MAAM,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC;AAE/B,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,8BAA8B,CAAC;;AAiFpE,wBA4KG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unbound-method.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unbound-method.js new file mode 100644 index 00000000..39ac5353 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unbound-method.js @@ -0,0 +1,331 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const util_1 = require("../util"); +/** + * Static methods on these globals are either not `this`-aware or supported being + * called without `this`. + * + * - `Promise` is not in the list because it supports subclassing by using `this` + * - `Array` is in the list because although it supports subclassing, the `this` + * value defaults to `Array` when unbound + * + * This is now a language-design invariant: static methods are never `this`-aware + * because TC39 wants to make `array.map(Class.method)` work! + */ +const SUPPORTED_GLOBALS = [ + 'Number', + 'Object', + 'String', // eslint-disable-line @typescript-eslint/internal/prefer-ast-types-enum + 'RegExp', + 'Symbol', + 'Array', + 'Proxy', + 'Date', + 'Atomics', + 'Reflect', + 'console', + 'Math', + 'JSON', + 'Intl', +]; +const nativelyBoundMembers = new Set(SUPPORTED_GLOBALS.flatMap(namespace => { + if (!(namespace in global)) { + // node.js might not have namespaces like Intl depending on compilation options + // https://nodejs.org/api/intl.html#intl_options_for_building_node_js + return []; + } + const object = global[namespace]; + return Object.getOwnPropertyNames(object) + .filter(name => !name.startsWith('_') && + typeof object[name] === 'function') + .map(name => `${namespace}.${name}`); +})); +const SUPPORTED_GLOBAL_TYPES = [ + 'NumberConstructor', + 'ObjectConstructor', + 'StringConstructor', + 'SymbolConstructor', + 'ArrayConstructor', + 'Array', + 'ProxyConstructor', + 'Console', + 'DateConstructor', + 'Atomics', + 'Math', + 'JSON', +]; +const isNotImported = (symbol, currentSourceFile) => { + const { valueDeclaration } = symbol; + if (!valueDeclaration) { + // working around https://github.com/microsoft/TypeScript/issues/31294 + return false; + } + return (!!currentSourceFile && + currentSourceFile !== valueDeclaration.getSourceFile()); +}; +const BASE_MESSAGE = 'Avoid referencing unbound methods which may cause unintentional scoping of `this`.'; +exports.default = (0, util_1.createRule)({ + name: 'unbound-method', + meta: { + type: 'problem', + docs: { + description: 'Enforce unbound methods are called with their expected scope', + recommended: 'recommended', + requiresTypeChecking: true, + }, + messages: { + unbound: BASE_MESSAGE, + unboundWithoutThisAnnotation: `${BASE_MESSAGE}\nIf your function does not access \`this\`, you can annotate it with \`this: void\`, or consider using an arrow function instead.`, + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + ignoreStatic: { + type: 'boolean', + description: 'Whether to skip checking whether `static` methods are correctly bound.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + ignoreStatic: false, + }, + ], + create(context, [{ ignoreStatic }]) { + const services = (0, util_1.getParserServices)(context); + const currentSourceFile = services.program.getSourceFile(context.filename); + function checkIfMethodAndReport(node, symbol) { + if (!symbol) { + return false; + } + const { dangerous, firstParamIsThis } = checkIfMethod(symbol, ignoreStatic); + if (dangerous) { + context.report({ + node, + messageId: firstParamIsThis === false + ? 'unboundWithoutThisAnnotation' + : 'unbound', + }); + return true; + } + return false; + } + function isNativelyBound(object, property) { + // We can't rely entirely on the type-level checks made at the end of this + // function, because sometimes type declarations don't come from the + // default library, but come from, for example, "@types/node". And we can't + // tell if a method is unbound just by looking at its signature declared in + // the interface. + // + // See related discussion https://github.com/typescript-eslint/typescript-eslint/pull/8952#discussion_r1576543310 + if (object.type === utils_1.AST_NODE_TYPES.Identifier && + property.type === utils_1.AST_NODE_TYPES.Identifier) { + const objectSymbol = services.getSymbolAtLocation(object); + const notImported = objectSymbol != null && + isNotImported(objectSymbol, currentSourceFile); + if (notImported && + nativelyBoundMembers.has(`${object.name}.${property.name}`)) { + return true; + } + } + // if `${object.name}.${property.name}` doesn't match any of + // the nativelyBoundMembers, then we fallback to type-level checks + return ((0, util_1.isBuiltinSymbolLike)(services.program, services.getTypeAtLocation(object), SUPPORTED_GLOBAL_TYPES) && + (0, util_1.isSymbolFromDefaultLibrary)(services.program, services.getTypeAtLocation(property).getSymbol())); + } + return { + MemberExpression(node) { + if (isSafeUse(node) || isNativelyBound(node.object, node.property)) { + return; + } + checkIfMethodAndReport(node, services.getSymbolAtLocation(node)); + }, + ObjectPattern(node) { + if (isNodeInsideTypeDeclaration(node)) { + return; + } + let initNode = null; + if (node.parent.type === utils_1.AST_NODE_TYPES.VariableDeclarator) { + initNode = node.parent.init; + } + else if (node.parent.type === utils_1.AST_NODE_TYPES.AssignmentPattern || + node.parent.type === utils_1.AST_NODE_TYPES.AssignmentExpression) { + initNode = node.parent.right; + } + for (const property of node.properties) { + if (property.type !== utils_1.AST_NODE_TYPES.Property || + property.key.type !== utils_1.AST_NODE_TYPES.Identifier) { + continue; + } + if (initNode) { + if (!isNativelyBound(initNode, property.key)) { + const reported = checkIfMethodAndReport(property.key, services + .getTypeAtLocation(initNode) + .getProperty(property.key.name)); + if (reported) { + continue; + } + // In assignment patterns, we should also check the type of + // Foo's nativelyBound method because initNode might be used as + // default value: + // function ({ nativelyBound }: Foo = NativeObject) {} + } + else if (node.parent.type !== utils_1.AST_NODE_TYPES.AssignmentPattern) { + continue; + } + } + for (const intersectionPart of tsutils + .unionConstituents(services.getTypeAtLocation(node)) + .flatMap(unionPart => tsutils.intersectionConstituents(unionPart))) { + const reported = checkIfMethodAndReport(property.key, intersectionPart.getProperty(property.key.name)); + if (reported) { + break; + } + } + } + }, + }; + }, +}); +function isNodeInsideTypeDeclaration(node) { + let parent = node; + while ((parent = parent.parent)) { + if ((parent.type === utils_1.AST_NODE_TYPES.ClassDeclaration && parent.declare) || + parent.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition || + parent.type === utils_1.AST_NODE_TYPES.TSDeclareFunction || + parent.type === utils_1.AST_NODE_TYPES.TSFunctionType || + parent.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration || + parent.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration || + (parent.type === utils_1.AST_NODE_TYPES.VariableDeclaration && parent.declare)) { + return true; + } + } + return false; +} +function checkIfMethod(symbol, ignoreStatic) { + const { valueDeclaration } = symbol; + if (!valueDeclaration) { + // working around https://github.com/microsoft/TypeScript/issues/31294 + return { dangerous: false }; + } + switch (valueDeclaration.kind) { + case ts.SyntaxKind.PropertyDeclaration: + return { + dangerous: valueDeclaration.initializer?.kind === + ts.SyntaxKind.FunctionExpression, + }; + case ts.SyntaxKind.PropertyAssignment: { + const assignee = valueDeclaration.initializer; + if (assignee.kind !== ts.SyntaxKind.FunctionExpression) { + return { + dangerous: false, + }; + } + return checkMethod(assignee, ignoreStatic); + } + case ts.SyntaxKind.MethodDeclaration: + case ts.SyntaxKind.MethodSignature: { + return checkMethod(valueDeclaration, ignoreStatic); + } + } + return { dangerous: false }; +} +function checkMethod(valueDeclaration, ignoreStatic) { + const firstParam = valueDeclaration.parameters.at(0); + const firstParamIsThis = firstParam?.name.kind === ts.SyntaxKind.Identifier && + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison + firstParam.name.escapedText === 'this'; + const thisArgIsVoid = firstParamIsThis && firstParam.type?.kind === ts.SyntaxKind.VoidKeyword; + return { + dangerous: !thisArgIsVoid && + !(ignoreStatic && + tsutils.includesModifier((0, util_1.getModifiers)(valueDeclaration), ts.SyntaxKind.StaticKeyword)), + firstParamIsThis, + }; +} +function isSafeUse(node) { + const parent = node.parent; + switch (parent?.type) { + case utils_1.AST_NODE_TYPES.IfStatement: + case utils_1.AST_NODE_TYPES.ForStatement: + case utils_1.AST_NODE_TYPES.MemberExpression: + case utils_1.AST_NODE_TYPES.SwitchStatement: + case utils_1.AST_NODE_TYPES.UpdateExpression: + case utils_1.AST_NODE_TYPES.WhileStatement: + return true; + case utils_1.AST_NODE_TYPES.CallExpression: + return parent.callee === node; + case utils_1.AST_NODE_TYPES.ConditionalExpression: + return parent.test === node; + case utils_1.AST_NODE_TYPES.TaggedTemplateExpression: + return parent.tag === node; + case utils_1.AST_NODE_TYPES.UnaryExpression: + // the first case is safe for obvious + // reasons. The second one is also fine + // since we're returning something falsy + return ['!', 'delete', 'typeof', 'void'].includes(parent.operator); + case utils_1.AST_NODE_TYPES.BinaryExpression: + return ['!=', '!==', '==', '===', 'instanceof'].includes(parent.operator); + case utils_1.AST_NODE_TYPES.AssignmentExpression: + return (parent.operator === '=' && + (node === parent.left || + (node.type === utils_1.AST_NODE_TYPES.MemberExpression && + node.object.type === utils_1.AST_NODE_TYPES.Super && + parent.left.type === utils_1.AST_NODE_TYPES.MemberExpression && + parent.left.object.type === utils_1.AST_NODE_TYPES.ThisExpression))); + case utils_1.AST_NODE_TYPES.ChainExpression: + case utils_1.AST_NODE_TYPES.TSNonNullExpression: + case utils_1.AST_NODE_TYPES.TSAsExpression: + case utils_1.AST_NODE_TYPES.TSTypeAssertion: + return isSafeUse(parent); + case utils_1.AST_NODE_TYPES.LogicalExpression: + if (parent.operator === '&&' && parent.left === node) { + // this is safe, as && will return the left if and only if it's falsy + return true; + } + // in all other cases, it's likely the logical expression will return the method ref + // so make sure the parent is a safe usage + return isSafeUse(parent); + } + return false; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unified-signatures.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unified-signatures.d.ts new file mode 100644 index 00000000..91949f36 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unified-signatures.d.ts @@ -0,0 +1,10 @@ +export type MessageIds = 'omittingRestParameter' | 'omittingSingleParameter' | 'singleParameterDifference'; +export type Options = [ + { + ignoreDifferentlyNamedParameters?: boolean; + ignoreOverloadsWithDifferentJSDoc?: boolean; + } +]; +declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule; +export default _default; +//# sourceMappingURL=unified-signatures.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unified-signatures.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unified-signatures.d.ts.map new file mode 100644 index 00000000..a671247f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unified-signatures.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"unified-signatures.d.ts","sourceRoot":"","sources":["../../src/rules/unified-signatures.ts"],"names":[],"mappings":"AAuDA,MAAM,MAAM,UAAU,GAClB,uBAAuB,GACvB,yBAAyB,GACzB,2BAA2B,CAAC;AAEhC,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,gCAAgC,CAAC,EAAE,OAAO,CAAC;QAC3C,iCAAiC,CAAC,EAAE,OAAO,CAAC;KAC7C;CACF,CAAC;;AAEF,wBA8kBG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unified-signatures.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unified-signatures.js new file mode 100644 index 00000000..37a1e612 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/unified-signatures.js @@ -0,0 +1,462 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const util_1 = require("../util"); +exports.default = (0, util_1.createRule)({ + name: 'unified-signatures', + meta: { + type: 'suggestion', + docs: { + description: 'Disallow two overloads that could be unified into one with a union or an optional/rest parameter', + // too opinionated to be recommended + recommended: 'strict', + }, + messages: { + omittingRestParameter: '{{failureStringStart}} with a rest parameter.', + omittingSingleParameter: '{{failureStringStart}} with an optional parameter.', + singleParameterDifference: '{{failureStringStart}} taking `{{type1}} | {{type2}}`.', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + ignoreDifferentlyNamedParameters: { + type: 'boolean', + description: 'Whether two parameters with different names at the same index should be considered different even if their types are the same.', + }, + ignoreOverloadsWithDifferentJSDoc: { + type: 'boolean', + description: 'Whether two overloads with different JSDoc comments should be considered different even if their parameter and return types are the same.', + }, + }, + }, + ], + }, + defaultOptions: [ + { + ignoreDifferentlyNamedParameters: false, + ignoreOverloadsWithDifferentJSDoc: false, + }, + ], + create(context, [{ ignoreDifferentlyNamedParameters, ignoreOverloadsWithDifferentJSDoc }]) { + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + function failureStringStart(otherLine) { + // For only 2 overloads we don't need to specify which is the other one. + const overloads = otherLine == null + ? 'These overloads' + : `This overload and the one on line ${otherLine}`; + return `${overloads} can be combined into one signature`; + } + function addFailures(failures) { + for (const failure of failures) { + const { only2, unify } = failure; + switch (unify.kind) { + case 'single-parameter-difference': { + const { p0, p1 } = unify; + const lineOfOtherOverload = only2 ? undefined : p0.loc.start.line; + const typeAnnotation0 = isTSParameterProperty(p0) + ? p0.parameter.typeAnnotation + : p0.typeAnnotation; + const typeAnnotation1 = isTSParameterProperty(p1) + ? p1.parameter.typeAnnotation + : p1.typeAnnotation; + context.report({ + loc: p1.loc, + node: p1, + messageId: 'singleParameterDifference', + data: { + failureStringStart: failureStringStart(lineOfOtherOverload), + type1: context.sourceCode.getText(typeAnnotation0?.typeAnnotation), + type2: context.sourceCode.getText(typeAnnotation1?.typeAnnotation), + }, + }); + break; + } + case 'extra-parameter': { + const { extraParameter, otherSignature } = unify; + const lineOfOtherOverload = only2 + ? undefined + : otherSignature.loc.start.line; + context.report({ + loc: extraParameter.loc, + node: extraParameter, + messageId: extraParameter.type === utils_1.AST_NODE_TYPES.RestElement + ? 'omittingRestParameter' + : 'omittingSingleParameter', + data: { + failureStringStart: failureStringStart(lineOfOtherOverload), + }, + }); + } + } + } + } + function checkOverloads(signatures, typeParameters) { + const result = []; + const isTypeParameter = getIsTypeParameter(typeParameters); + for (const overloads of signatures) { + forEachPair(overloads, (a, b) => { + const signature0 = a.value ?? a; + const signature1 = b.value ?? b; + const unify = compareSignatures(signature0, signature1, isTypeParameter); + if (unify != null) { + result.push({ only2: overloads.length === 2, unify }); + } + }); + } + return result; + } + function compareSignatures(a, b, isTypeParameter) { + if (!signaturesCanBeUnified(a, b, isTypeParameter)) { + return undefined; + } + return a.params.length === b.params.length + ? signaturesDifferBySingleParameter(a.params, b.params) + : signaturesDifferByOptionalOrRestParameter(a, b); + } + function signaturesCanBeUnified(a, b, isTypeParameter) { + // Must return the same type. + const aTypeParams = a.typeParameters != null ? a.typeParameters.params : undefined; + const bTypeParams = b.typeParameters != null ? b.typeParameters.params : undefined; + if (ignoreDifferentlyNamedParameters) { + const commonParamsLength = Math.min(a.params.length, b.params.length); + for (let i = 0; i < commonParamsLength; i += 1) { + if (a.params[i].type === b.params[i].type && + getStaticParameterName(a.params[i]) !== + getStaticParameterName(b.params[i])) { + return false; + } + } + } + if (ignoreOverloadsWithDifferentJSDoc) { + const aComment = getBlockCommentForNode(getExportingNode(a) ?? a); + const bComment = getBlockCommentForNode(getExportingNode(b) ?? b); + if (aComment?.value !== bComment?.value) { + return false; + } + } + return (typesAreEqual(a.returnType, b.returnType) && + // Must take the same type parameters. + // If one uses a type parameter (from outside) and the other doesn't, they shouldn't be joined. + (0, util_1.arraysAreEqual)(aTypeParams, bTypeParams, typeParametersAreEqual) && + signatureUsesTypeParameter(a, isTypeParameter) === + signatureUsesTypeParameter(b, isTypeParameter)); + } + /** Detect `a(x: number, y: number, z: number)` and `a(x: number, y: string, z: number)`. */ + function signaturesDifferBySingleParameter(types1, types2) { + const firstParam1 = types1[0]; + const firstParam2 = types2[0]; + // exempt signatures with `this: void` from the rule + if (isThisVoidParam(firstParam1) || isThisVoidParam(firstParam2)) { + return undefined; + } + const index = getIndexOfFirstDifference(types1, types2, parametersAreEqual); + if (index == null) { + return undefined; + } + // If remaining arrays are equal, the signatures differ by just one parameter type + if (!(0, util_1.arraysAreEqual)(types1.slice(index + 1), types2.slice(index + 1), parametersAreEqual)) { + return undefined; + } + const a = types1[index]; + const b = types2[index]; + // Can unify `a?: string` and `b?: number`. Can't unify `...args: string[]` and `...args: number[]`. + // See https://github.com/Microsoft/TypeScript/issues/5077 + return parametersHaveEqualSigils(a, b) && + a.type !== utils_1.AST_NODE_TYPES.RestElement + ? { kind: 'single-parameter-difference', p0: a, p1: b } + : undefined; + } + function isThisParam(param) { + return (param != null && + param.type === utils_1.AST_NODE_TYPES.Identifier && + param.name === 'this'); + } + function isThisVoidParam(param) { + return (isThisParam(param) && + param.typeAnnotation?.typeAnnotation.type === + utils_1.AST_NODE_TYPES.TSVoidKeyword); + } + /** + * Detect `a(): void` and `a(x: number): void`. + * Returns the parameter declaration (`x: number` in this example) that should be optional/rest, and overload it's a part of. + */ + function signaturesDifferByOptionalOrRestParameter(a, b) { + const sig1 = a.params; + const sig2 = b.params; + const minLength = Math.min(sig1.length, sig2.length); + const longer = sig1.length < sig2.length ? sig2 : sig1; + const shorter = sig1.length < sig2.length ? sig1 : sig2; + const shorterSig = sig1.length < sig2.length ? a : b; + const firstParam1 = sig1.at(0); + const firstParam2 = sig2.at(0); + // If one signature has explicit this type and another doesn't, they can't + // be unified. + if (isThisParam(firstParam1) !== isThisParam(firstParam2)) { + return undefined; + } + // exempt signatures with `this: void` from the rule + if (isThisVoidParam(firstParam1) || isThisVoidParam(firstParam2)) { + return undefined; + } + // If one is has 2+ parameters more than the other, they must all be optional/rest. + // Differ by optional parameters: f() and f(x), f() and f(x, ?y, ...z) + // Not allowed: f() and f(x, y) + for (let i = minLength + 1; i < longer.length; i++) { + if (!parameterMayBeMissing(longer[i])) { + return undefined; + } + } + for (let i = 0; i < minLength; i++) { + const sig1i = sig1[i]; + const sig2i = sig2[i]; + const typeAnnotation1 = isTSParameterProperty(sig1i) + ? sig1i.parameter.typeAnnotation + : sig1i.typeAnnotation; + const typeAnnotation2 = isTSParameterProperty(sig2i) + ? sig2i.parameter.typeAnnotation + : sig2i.typeAnnotation; + if (!typesAreEqual(typeAnnotation1, typeAnnotation2)) { + return undefined; + } + } + if (minLength > 0 && + shorter[minLength - 1].type === utils_1.AST_NODE_TYPES.RestElement) { + return undefined; + } + return { + extraParameter: longer[longer.length - 1], + kind: 'extra-parameter', + otherSignature: shorterSig, + }; + } + /** Given type parameters, returns a function to test whether a type is one of those parameters. */ + function getIsTypeParameter(typeParameters) { + if (typeParameters == null) { + return (() => false); + } + const set = new Set(); + for (const t of typeParameters.params) { + set.add(t.name.name); + } + return (typeName => set.has(typeName)); + } + /** True if any of the outer type parameters are used in a signature. */ + function signatureUsesTypeParameter(sig, isTypeParameter) { + return sig.params.some((p) => typeContainsTypeParameter(isTSParameterProperty(p) + ? p.parameter.typeAnnotation + : p.typeAnnotation)); + function typeContainsTypeParameter(type) { + if (!type) { + return false; + } + if (type.type === utils_1.AST_NODE_TYPES.TSTypeReference) { + const typeName = type.typeName; + if (isIdentifier(typeName) && isTypeParameter(typeName.name)) { + return true; + } + } + return typeContainsTypeParameter(type.typeAnnotation ?? + type.elementType); + } + } + function isTSParameterProperty(node) { + return node.type === utils_1.AST_NODE_TYPES.TSParameterProperty; + } + function parametersAreEqual(a, b) { + const typeAnnotationA = isTSParameterProperty(a) + ? a.parameter.typeAnnotation + : a.typeAnnotation; + const typeAnnotationB = isTSParameterProperty(b) + ? b.parameter.typeAnnotation + : b.typeAnnotation; + return (parametersHaveEqualSigils(a, b) && + typesAreEqual(typeAnnotationA, typeAnnotationB)); + } + /** True for optional/rest parameters. */ + function parameterMayBeMissing(p) { + const optional = isTSParameterProperty(p) + ? p.parameter.optional + : p.optional; + return p.type === utils_1.AST_NODE_TYPES.RestElement || optional; + } + /** False if one is optional and the other isn't, or one is a rest parameter and the other isn't. */ + function parametersHaveEqualSigils(a, b) { + const optionalA = isTSParameterProperty(a) + ? a.parameter.optional + : a.optional; + const optionalB = isTSParameterProperty(b) + ? b.parameter.optional + : b.optional; + return ((a.type === utils_1.AST_NODE_TYPES.RestElement) === + (b.type === utils_1.AST_NODE_TYPES.RestElement) && optionalA === optionalB); + } + function typeParametersAreEqual(a, b) { + return (a.name.name === b.name.name && + constraintsAreEqual(a.constraint, b.constraint)); + } + function typesAreEqual(a, b) { + return (a === b || + (a != null && + b != null && + context.sourceCode.getText(a.typeAnnotation) === + context.sourceCode.getText(b.typeAnnotation))); + } + function constraintsAreEqual(a, b) { + return a === b || (a != null && b != null && a.type === b.type); + } + /* Returns the first index where `a` and `b` differ. */ + function getIndexOfFirstDifference(a, b, equal) { + for (let i = 0; i < a.length && i < b.length; i++) { + if (!equal(a[i], b[i])) { + return i; + } + } + return undefined; + } + /** Calls `action` for every pair of values in `values`. */ + function forEachPair(values, action) { + for (let i = 0; i < values.length; i++) { + for (let j = i + 1; j < values.length; j++) { + action(values[i], values[j]); + } + } + } + const scopes = []; + let currentScope = { + overloads: new Map(), + }; + function createScope(parent, typeParameters) { + if (currentScope) { + scopes.push(currentScope); + } + currentScope = { + overloads: new Map(), + parent, + typeParameters, + }; + } + function checkScope() { + const scope = (0, util_1.nullThrows)(currentScope, 'checkScope() called without a current scope'); + const failures = checkOverloads([...scope.overloads.values()], scope.typeParameters); + addFailures(failures); + currentScope = scopes.pop(); + } + /** + * @returns the first valid JSDoc comment annotating `node` + */ + function getBlockCommentForNode(node) { + return context.sourceCode + .getCommentsBefore(node) + .reverse() + .find(comment => comment.type === utils_1.AST_TOKEN_TYPES.Block); + } + function addOverload(signature, key, containingNode) { + key ??= getOverloadKey(signature); + if (currentScope && + (containingNode ?? signature).parent === currentScope.parent) { + const overloads = currentScope.overloads.get(key); + if (overloads != null) { + overloads.push(signature); + } + else { + currentScope.overloads.set(key, [signature]); + } + } + } + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + return { + ClassDeclaration(node) { + createScope(node.body, node.typeParameters); + }, + Program: createScope, + TSInterfaceDeclaration(node) { + createScope(node.body, node.typeParameters); + }, + TSModuleBlock: createScope, + TSTypeLiteral: createScope, + // collect overloads + MethodDefinition(node) { + if (!node.value.body && !isGetterOrSetter(node)) { + addOverload(node); + } + }, + TSAbstractMethodDefinition(node) { + if (!node.value.body && !isGetterOrSetter(node)) { + addOverload(node); + } + }, + TSCallSignatureDeclaration: addOverload, + TSConstructSignatureDeclaration: addOverload, + TSDeclareFunction(node) { + const exportingNode = getExportingNode(node); + addOverload(node, node.id?.name ?? exportingNode?.type, exportingNode); + }, + TSMethodSignature(node) { + if (!isGetterOrSetter(node)) { + addOverload(node); + } + }, + // validate scopes + 'ClassDeclaration:exit': checkScope, + 'Program:exit': checkScope, + 'TSInterfaceDeclaration:exit': checkScope, + 'TSModuleBlock:exit': checkScope, + 'TSTypeLiteral:exit': checkScope, + }; + }, +}); +function getExportingNode(node) { + return node.parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration || + node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration + ? node.parent + : undefined; +} +function getOverloadKey(node) { + const info = getOverloadInfo(node); + return ((node.computed ? '0' : '1') + + (node.static ? '0' : '1') + + info); +} +function getOverloadInfo(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration: + return 'constructor'; + case utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration: + return '()'; + default: { + const { key } = node; + if (isPrivateIdentifier(key)) { + return `private_identifier_${key.name}`; + } + if (isIdentifier(key)) { + return `identifier_${key.name}`; + } + return key.raw; + } + } +} +function getStaticParameterName(param) { + switch (param.type) { + case utils_1.AST_NODE_TYPES.Identifier: + return param.name; + case utils_1.AST_NODE_TYPES.RestElement: + return getStaticParameterName(param.argument); + default: + return undefined; + } +} +function isIdentifier(node) { + return node.type === utils_1.AST_NODE_TYPES.Identifier; +} +function isPrivateIdentifier(node) { + return node.type === utils_1.AST_NODE_TYPES.PrivateIdentifier; +} +function isGetterOrSetter(node) { + return node.kind === 'get' || node.kind === 'set'; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/use-unknown-in-catch-callback-variable.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/use-unknown-in-catch-callback-variable.d.ts new file mode 100644 index 00000000..603a6388 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/use-unknown-in-catch-callback-variable.d.ts @@ -0,0 +1,5 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type MessageIds = 'addUnknownRestTypeAnnotationSuggestion' | 'addUnknownTypeAnnotationSuggestion' | 'useUnknown' | 'useUnknownArrayDestructuringPattern' | 'useUnknownObjectDestructuringPattern' | 'wrongRestTypeAnnotationSuggestion' | 'wrongTypeAnnotationSuggestion'; +declare const _default: TSESLint.RuleModule; +export default _default; +//# sourceMappingURL=use-unknown-in-catch-callback-variable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/use-unknown-in-catch-callback-variable.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/use-unknown-in-catch-callback-variable.d.ts.map new file mode 100644 index 00000000..e30bcbe8 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/use-unknown-in-catch-callback-variable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"use-unknown-in-catch-callback-variable.d.ts","sourceRoot":"","sources":["../../src/rules/use-unknown-in-catch-callback-variable.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAgBnE,MAAM,MAAM,UAAU,GAClB,wCAAwC,GACxC,oCAAoC,GACpC,YAAY,GACZ,qCAAqC,GACrC,sCAAsC,GACtC,mCAAmC,GACnC,+BAA+B,CAAC;;AAKpC,wBAkSG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/rules/use-unknown-in-catch-callback-variable.js b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/use-unknown-in-catch-callback-variable.js new file mode 100644 index 00000000..2f60e8fd --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/rules/use-unknown-in-catch-callback-variable.js @@ -0,0 +1,261 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const util_1 = require("../util"); +const useUnknownMessageBase = 'Prefer the safe `: unknown` for a `{{method}}`{{append}} callback variable.'; +exports.default = (0, util_1.createRule)({ + name: 'use-unknown-in-catch-callback-variable', + meta: { + type: 'suggestion', + docs: { + description: 'Enforce typing arguments in Promise rejection callbacks as `unknown`', + recommended: 'strict', + requiresTypeChecking: true, + }, + hasSuggestions: true, + messages: { + addUnknownRestTypeAnnotationSuggestion: 'Add an explicit `: [unknown]` type annotation to the rejection callback rest variable.', + addUnknownTypeAnnotationSuggestion: 'Add an explicit `: unknown` type annotation to the rejection callback variable.', + useUnknown: useUnknownMessageBase, + useUnknownArrayDestructuringPattern: `${useUnknownMessageBase} The thrown error may not be iterable.`, + useUnknownObjectDestructuringPattern: `${useUnknownMessageBase} The thrown error may be nullable, or may not have the expected shape.`, + wrongRestTypeAnnotationSuggestion: 'Change existing type annotation to `: [unknown]`.', + wrongTypeAnnotationSuggestion: 'Change existing type annotation to `: unknown`.', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const { esTreeNodeToTSNodeMap, program } = (0, util_1.getParserServices)(context); + const checker = program.getTypeChecker(); + function isFlaggableHandlerType(type) { + for (const unionPart of tsutils.unionConstituents(type)) { + const callSignatures = tsutils.getCallSignaturesOfType(unionPart); + if (callSignatures.length === 0) { + // Ignore any non-function components to the type. Those are not this rule's problem. + continue; + } + for (const callSignature of callSignatures) { + const firstParam = callSignature.parameters.at(0); + if (!firstParam) { + // it's not an issue if there's no catch variable at all. + continue; + } + let firstParamType = checker.getTypeOfSymbol(firstParam); + const decl = firstParam.valueDeclaration; + if (decl != null && (0, util_1.isRestParameterDeclaration)(decl)) { + if (checker.isArrayType(firstParamType)) { + firstParamType = checker.getTypeArguments(firstParamType)[0]; + } + else if (checker.isTupleType(firstParamType)) { + firstParamType = checker.getTypeArguments(firstParamType)[0]; + } + else { + // a rest arg that's not an array or tuple should definitely be flagged. + return true; + } + } + if (!tsutils.isIntrinsicUnknownType(firstParamType)) { + return true; + } + } + } + return false; + } + function collectFlaggedNodes(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.LogicalExpression: + return [ + ...collectFlaggedNodes(node.left), + ...collectFlaggedNodes(node.right), + ]; + case utils_1.AST_NODE_TYPES.SequenceExpression: + return collectFlaggedNodes((0, util_1.nullThrows)(node.expressions.at(-1), 'sequence expression must have multiple expressions')); + case utils_1.AST_NODE_TYPES.ConditionalExpression: + return [ + ...collectFlaggedNodes(node.consequent), + ...collectFlaggedNodes(node.alternate), + ]; + case utils_1.AST_NODE_TYPES.ArrowFunctionExpression: + case utils_1.AST_NODE_TYPES.FunctionExpression: + { + const argument = esTreeNodeToTSNodeMap.get(node); + const typeOfArgument = checker.getTypeAtLocation(argument); + if (isFlaggableHandlerType(typeOfArgument)) { + return [node]; + } + } + break; + default: + break; + } + return []; + } + /** + * Analyzes the syntax of the catch argument and makes a best effort to pinpoint + * why it's reporting, and to come up with a suggested fix if possible. + * + * This function is explicitly operating under the assumption that the + * rule _is reporting_, so it is not guaranteed to be sound to call otherwise. + */ + function refineReportIfPossible(argument) { + const catchVariableOuterWithIncorrectTypes = (0, util_1.nullThrows)(argument.params.at(0), 'There should have been at least one parameter for the rule to have flagged.'); + // Function expressions can't have parameter properties; those only exist in constructors. + const catchVariableOuter = catchVariableOuterWithIncorrectTypes; + const catchVariableInner = catchVariableOuter.type === utils_1.AST_NODE_TYPES.AssignmentPattern + ? catchVariableOuter.left + : catchVariableOuter; + switch (catchVariableInner.type) { + case utils_1.AST_NODE_TYPES.Identifier: { + const catchVariableTypeAnnotation = catchVariableInner.typeAnnotation; + if (catchVariableTypeAnnotation == null) { + return { + node: catchVariableOuter, + suggest: [ + { + messageId: 'addUnknownTypeAnnotationSuggestion', + fix: (fixer) => { + if (argument.type === + utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + (0, util_1.isParenlessArrowFunction)(argument, context.sourceCode)) { + return [ + fixer.insertTextBefore(catchVariableInner, '('), + fixer.insertTextAfter(catchVariableInner, ': unknown)'), + ]; + } + return [ + fixer.insertTextAfter(catchVariableInner, ': unknown'), + ]; + }, + }, + ], + }; + } + return { + node: catchVariableOuter, + suggest: [ + { + messageId: 'wrongTypeAnnotationSuggestion', + fix: (fixer) => fixer.replaceText(catchVariableTypeAnnotation, ': unknown'), + }, + ], + }; + } + case utils_1.AST_NODE_TYPES.ArrayPattern: { + return { + node: catchVariableOuter, + messageId: 'useUnknownArrayDestructuringPattern', + }; + } + case utils_1.AST_NODE_TYPES.ObjectPattern: { + return { + node: catchVariableOuter, + messageId: 'useUnknownObjectDestructuringPattern', + }; + } + case utils_1.AST_NODE_TYPES.RestElement: { + const catchVariableTypeAnnotation = catchVariableInner.typeAnnotation; + if (catchVariableTypeAnnotation == null) { + return { + node: catchVariableOuter, + suggest: [ + { + messageId: 'addUnknownRestTypeAnnotationSuggestion', + fix: (fixer) => fixer.insertTextAfter(catchVariableInner, ': [unknown]'), + }, + ], + }; + } + return { + node: catchVariableOuter, + suggest: [ + { + messageId: 'wrongRestTypeAnnotationSuggestion', + fix: (fixer) => fixer.replaceText(catchVariableTypeAnnotation, ': [unknown]'), + }, + ], + }; + } + } + } + return { + CallExpression({ arguments: args, callee }) { + if (callee.type !== utils_1.AST_NODE_TYPES.MemberExpression) { + return; + } + const staticMemberAccessKey = (0, util_1.getStaticMemberAccessValue)(callee, context); + if (!staticMemberAccessKey) { + return; + } + const promiseMethodInfo = [ + { append: '', argIndexToCheck: 0, method: 'catch' }, + { append: ' rejection', argIndexToCheck: 1, method: 'then' }, + ].find(({ method }) => staticMemberAccessKey === method); + if (!promiseMethodInfo) { + return; + } + // Need to be enough args to check + const { argIndexToCheck, ...data } = promiseMethodInfo; + if (args.length < argIndexToCheck + 1) { + return; + } + // Argument to check, and all arguments before it, must be "ordinary" arguments (i.e. no spread arguments) + // promise.catch(f), promise.catch(() => {}), promise.catch(, <>) + const argsToCheck = args.slice(0, argIndexToCheck + 1); + if (argsToCheck.some(({ type }) => type === utils_1.AST_NODE_TYPES.SpreadElement)) { + return; + } + if (!tsutils.isThenableType(checker, esTreeNodeToTSNodeMap.get(callee), checker.getTypeAtLocation(esTreeNodeToTSNodeMap.get(callee.object)))) { + return; + } + // the `some` check above has already excluded `SpreadElement`, so we are safe to assert the same + const argToCheck = argsToCheck[argIndexToCheck]; + for (const node of collectFlaggedNodes(argToCheck)) { + // We are now guaranteed to report, but we have a bit of work to do + // to determine exactly where, and whether we can fix it. + const overrides = refineReportIfPossible(node); + context.report({ + node, + messageId: 'useUnknown', + data, + ...overrides, + }); + } + }, + }; + }, +}); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/assertionFunctionUtils.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/assertionFunctionUtils.d.ts new file mode 100644 index 00000000..65d6fe75 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/assertionFunctionUtils.d.ts @@ -0,0 +1,17 @@ +import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/utils'; +import * as ts from 'typescript'; +/** + * Inspect a call expression to see if it's a call to an assertion function. + * If it is, return the node of the argument that is asserted. + */ +export declare function findTruthinessAssertedArgument(services: ParserServicesWithTypeInformation, node: TSESTree.CallExpression): TSESTree.Expression | undefined; +/** + * Inspect a call expression to see if it's a call to an assertion function. + * If it is, return the node of the argument that is asserted and other useful info. + */ +export declare function findTypeGuardAssertedArgument(services: ParserServicesWithTypeInformation, node: TSESTree.CallExpression): { + argument: TSESTree.Expression; + asserts: boolean; + type: ts.Type; +} | undefined; +//# sourceMappingURL=assertionFunctionUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/assertionFunctionUtils.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/assertionFunctionUtils.d.ts.map new file mode 100644 index 00000000..38be7f58 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/assertionFunctionUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"assertionFunctionUtils.d.ts","sourceRoot":"","sources":["../../src/util/assertionFunctionUtils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EACjC,QAAQ,EACT,MAAM,0BAA0B,CAAC;AAGlC,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC;;;GAGG;AACH,wBAAgB,8BAA8B,CAC5C,QAAQ,EAAE,iCAAiC,EAC3C,IAAI,EAAE,QAAQ,CAAC,cAAc,GAC5B,QAAQ,CAAC,UAAU,GAAG,SAAS,CAsCjC;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,QAAQ,EAAE,iCAAiC,EAC3C,IAAI,EAAE,QAAQ,CAAC,cAAc,GAE3B;IACE,QAAQ,EAAE,QAAQ,CAAC,UAAU,CAAC;IAC9B,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC;CACf,GACD,SAAS,CAmDZ"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/assertionFunctionUtils.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/assertionFunctionUtils.js new file mode 100644 index 00000000..63f9a7e0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/assertionFunctionUtils.js @@ -0,0 +1,118 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.findTruthinessAssertedArgument = findTruthinessAssertedArgument; +exports.findTypeGuardAssertedArgument = findTypeGuardAssertedArgument; +const utils_1 = require("@typescript-eslint/utils"); +const ts = __importStar(require("typescript")); +/** + * Inspect a call expression to see if it's a call to an assertion function. + * If it is, return the node of the argument that is asserted. + */ +function findTruthinessAssertedArgument(services, node) { + // If the call looks like `assert(expr1, expr2, ...c, d, e, f)`, then we can + // only care if `expr1` or `expr2` is asserted, since anything that happens + // within or after a spread argument is out of scope to reason about. + const checkableArguments = []; + for (const argument of node.arguments) { + if (argument.type === utils_1.AST_NODE_TYPES.SpreadElement) { + break; + } + checkableArguments.push(argument); + } + // nothing to do + if (checkableArguments.length === 0) { + return undefined; + } + const checker = services.program.getTypeChecker(); + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + const signature = checker.getResolvedSignature(tsNode); + if (signature == null) { + return undefined; + } + const firstTypePredicateResult = checker.getTypePredicateOfSignature(signature); + if (firstTypePredicateResult == null) { + return undefined; + } + const { kind, parameterIndex, type } = firstTypePredicateResult; + if (!(kind === ts.TypePredicateKind.AssertsIdentifier && type == null)) { + return undefined; + } + return checkableArguments.at(parameterIndex); +} +/** + * Inspect a call expression to see if it's a call to an assertion function. + * If it is, return the node of the argument that is asserted and other useful info. + */ +function findTypeGuardAssertedArgument(services, node) { + // If the call looks like `assert(expr1, expr2, ...c, d, e, f)`, then we can + // only care if `expr1` or `expr2` is asserted, since anything that happens + // within or after a spread argument is out of scope to reason about. + const checkableArguments = []; + for (const argument of node.arguments) { + if (argument.type === utils_1.AST_NODE_TYPES.SpreadElement) { + break; + } + checkableArguments.push(argument); + } + // nothing to do + if (checkableArguments.length === 0) { + return undefined; + } + const checker = services.program.getTypeChecker(); + const tsNode = services.esTreeNodeToTSNodeMap.get(node); + const callSignature = checker.getResolvedSignature(tsNode); + if (callSignature == null) { + return undefined; + } + const typePredicateInfo = checker.getTypePredicateOfSignature(callSignature); + if (typePredicateInfo == null) { + return undefined; + } + const { kind, parameterIndex, type } = typePredicateInfo; + if (!((kind === ts.TypePredicateKind.AssertsIdentifier || + kind === ts.TypePredicateKind.Identifier) && + type != null)) { + return undefined; + } + if (parameterIndex >= checkableArguments.length) { + return undefined; + } + return { + argument: checkableArguments[parameterIndex], + asserts: kind === ts.TypePredicateKind.AssertsIdentifier, + type, + }; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.d.ts new file mode 100644 index 00000000..0f26d070 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.d.ts @@ -0,0 +1,13 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +import * as ts from 'typescript'; +export * from '@typescript-eslint/utils/ast-utils'; +/** + * Get the `loc` object of a given name in a `/*globals` comment directive. + * @param sourceCode The source code to convert index to loc. + * @param comment The `/*globals` comment directive which include the name. + * @param name The name to find. + * @returns The `loc` object. + */ +export declare function getNameLocationInGlobalDirectiveComment(sourceCode: TSESLint.SourceCode, comment: TSESTree.Comment, name: string): TSESTree.SourceLocation; +export declare function forEachReturnStatement(body: ts.Block, visitor: (stmt: ts.ReturnStatement) => T): T | undefined; +//# sourceMappingURL=astUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.d.ts.map new file mode 100644 index 00000000..92f12fe3 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"astUtils.d.ts","sourceRoot":"","sources":["../../src/util/astUtils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAKjC,cAAc,oCAAoC,CAAC;AAKnD;;;;;;GAMG;AACH,wBAAgB,uCAAuC,CACrD,UAAU,EAAE,QAAQ,CAAC,UAAU,EAC/B,OAAO,EAAE,QAAQ,CAAC,OAAO,EACzB,IAAI,EAAE,MAAM,GACX,QAAQ,CAAC,cAAc,CAsBzB;AAKD,wBAAgB,sBAAsB,CAAC,CAAC,EACtC,IAAI,EAAE,EAAE,CAAC,KAAK,EACd,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,eAAe,KAAK,CAAC,GACvC,CAAC,GAAG,SAAS,CA2Bf"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.js new file mode 100644 index 00000000..c001d42d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.js @@ -0,0 +1,97 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getNameLocationInGlobalDirectiveComment = getNameLocationInGlobalDirectiveComment; +exports.forEachReturnStatement = forEachReturnStatement; +const ts = __importStar(require("typescript")); +const escapeRegExp_1 = require("./escapeRegExp"); +// deeply re-export, for convenience +__exportStar(require("@typescript-eslint/utils/ast-utils"), exports); +// The following is copied from `eslint`'s source code since it doesn't exist in eslint@5. +// https://github.com/eslint/eslint/blob/145aec1ab9052fbca96a44d04927c595951b1536/lib/rules/utils/ast-utils.js#L1751-L1779 +// Could be export { getNameLocationInGlobalDirectiveComment } from 'eslint/lib/rules/utils/ast-utils' +/** + * Get the `loc` object of a given name in a `/*globals` comment directive. + * @param sourceCode The source code to convert index to loc. + * @param comment The `/*globals` comment directive which include the name. + * @param name The name to find. + * @returns The `loc` object. + */ +function getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) { + const namePattern = new RegExp(`[\\s,]${(0, escapeRegExp_1.escapeRegExp)(name)}(?:$|[\\s,:])`, 'gu'); + // To ignore the first text "global". + namePattern.lastIndex = comment.value.indexOf('global') + 6; + // Search a given variable name. + const match = namePattern.exec(comment.value); + // Convert the index to loc. + const start = sourceCode.getLocFromIndex(comment.range[0] + '/*'.length + (match ? match.index + 1 : 0)); + const end = { + column: start.column + (match ? name.length : 1), + line: start.line, + }; + return { end, start }; +} +// Copied from typescript https://github.com/microsoft/TypeScript/blob/42b0e3c4630c129ca39ce0df9fff5f0d1b4dd348/src/compiler/utilities.ts#L1335 +// Warning: This has the same semantics as the forEach family of functions, +// in that traversal terminates in the event that 'visitor' supplies a truthy value. +function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case ts.SyntaxKind.ReturnStatement: + return visitor(node); + case ts.SyntaxKind.CaseBlock: + case ts.SyntaxKind.Block: + case ts.SyntaxKind.IfStatement: + case ts.SyntaxKind.DoStatement: + case ts.SyntaxKind.WhileStatement: + case ts.SyntaxKind.ForStatement: + case ts.SyntaxKind.ForInStatement: + case ts.SyntaxKind.ForOfStatement: + case ts.SyntaxKind.WithStatement: + case ts.SyntaxKind.SwitchStatement: + case ts.SyntaxKind.CaseClause: + case ts.SyntaxKind.DefaultClause: + case ts.SyntaxKind.LabeledStatement: + case ts.SyntaxKind.TryStatement: + case ts.SyntaxKind.CatchClause: + return ts.forEachChild(node, traverse); + } + return undefined; + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/collectUnusedVariables.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/collectUnusedVariables.d.ts new file mode 100644 index 00000000..2ae2312a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/collectUnusedVariables.d.ts @@ -0,0 +1,16 @@ +import type { ScopeVariable } from '@typescript-eslint/scope-manager'; +import { TSESLint } from '@typescript-eslint/utils'; +interface VariableAnalysis { + readonly unusedVariables: ReadonlySet; + readonly usedVariables: ReadonlySet; +} +/** + * Collects the set of unused variables for a given context. + * + * Due to complexity, this does not take into consideration: + * - variables within declaration files + * - variables within ambient module declarations + */ +export declare function collectVariables(context: Readonly>): VariableAnalysis; +export {}; +//# sourceMappingURL=collectUnusedVariables.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/collectUnusedVariables.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/collectUnusedVariables.d.ts.map new file mode 100644 index 00000000..e619ae43 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/collectUnusedVariables.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"collectUnusedVariables.d.ts","sourceRoot":"","sources":["../../src/util/collectUnusedVariables.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,aAAa,EACd,MAAM,kCAAkC,CAAC;AAQ1C,OAAO,EAIL,QAAQ,EACT,MAAM,0BAA0B,CAAC;AAKlC,UAAU,gBAAgB;IACxB,QAAQ,CAAC,eAAe,EAAE,WAAW,CAAC,aAAa,CAAC,CAAC;IACrD,QAAQ,CAAC,aAAa,EAAE,WAAW,CAAC,aAAa,CAAC,CAAC;CACpD;AAmxBD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,SAAS,MAAM,EACzB,OAAO,SAAS,SAAS,OAAO,EAAE,EAElC,OAAO,EAAE,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,GAC3D,gBAAgB,CAQlB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/collectUnusedVariables.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/collectUnusedVariables.js new file mode 100644 index 00000000..848eba66 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/collectUnusedVariables.js @@ -0,0 +1,604 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.collectVariables = collectVariables; +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +const isTypeImport_1 = require("./isTypeImport"); +const referenceContainsTypeQuery_1 = require("./referenceContainsTypeQuery"); +/** + * This class leverages an AST visitor to mark variables as used via the + * `eslintUsed` property. + */ +class UnusedVarsVisitor extends scope_manager_1.Visitor { + /** + * We keep a weak cache so that multiple rules can share the calculation + */ + static RESULTS_CACHE = new WeakMap(); + ClassDeclaration = this.visitClass; + ClassExpression = this.visitClass; + ForInStatement = this.visitForInForOf; + ForOfStatement = this.visitForInForOf; + //#region HELPERS + FunctionDeclaration = this.visitFunction; + FunctionExpression = this.visitFunction; + MethodDefinition = this.visitSetter; + Property = this.visitSetter; + TSCallSignatureDeclaration = this.visitFunctionTypeSignature; + TSConstructorType = this.visitFunctionTypeSignature; + TSConstructSignatureDeclaration = this.visitFunctionTypeSignature; + TSDeclareFunction = this.visitFunctionTypeSignature; + TSEmptyBodyFunctionExpression = this.visitFunctionTypeSignature; + //#endregion HELPERS + //#region VISITORS + // NOTE - This is a simple visitor - meaning it does not support selectors + TSFunctionType = this.visitFunctionTypeSignature; + TSMethodSignature = this.visitFunctionTypeSignature; + #scopeManager; + constructor(scopeManager) { + super({ + visitChildrenEvenIfSelectorExists: true, + }); + this.#scopeManager = scopeManager; + } + static collectUnusedVariables(program, scopeManager) { + const cached = this.RESULTS_CACHE.get(program); + if (cached) { + return cached; + } + const visitor = new this(scopeManager); + visitor.visit(program); + const unusedVars = visitor.collectUnusedVariables(visitor.getScope(program)); + this.RESULTS_CACHE.set(program, unusedVars); + return unusedVars; + } + Identifier(node) { + const scope = this.getScope(node); + if (scope.type === utils_1.TSESLint.Scope.ScopeType.function && + node.name === 'this' && + // this parameters should always be considered used as they're pseudo-parameters + 'params' in scope.block && + scope.block.params.includes(node)) { + this.markVariableAsUsed(node); + } + } + TSEnumDeclaration(node) { + // enum members create variables because they can be referenced within the enum, + // but they obviously aren't unused variables for the purposes of this rule. + const scope = this.getScope(node); + for (const variable of scope.variables) { + this.markVariableAsUsed(variable); + } + } + TSMappedType(node) { + // mapped types create a variable for their type name, but it's not necessary to reference it, + // so we shouldn't consider it as unused for the purpose of this rule. + this.markVariableAsUsed(node.key); + } + TSModuleDeclaration(node) { + // -- global augmentation can be in any file, and they do not need exports + if (node.kind === 'global') { + this.markVariableAsUsed('global', node.parent); + } + } + TSParameterProperty(node) { + let identifier = null; + switch (node.parameter.type) { + case utils_1.AST_NODE_TYPES.AssignmentPattern: + if (node.parameter.left.type === utils_1.AST_NODE_TYPES.Identifier) { + identifier = node.parameter.left; + } + break; + case utils_1.AST_NODE_TYPES.Identifier: + identifier = node.parameter; + break; + } + if (identifier) { + this.markVariableAsUsed(identifier); + } + } + collectUnusedVariables(scope, variables = { + unusedVariables: new Set(), + usedVariables: new Set(), + }) { + if ( + // skip function expression names + // this scope is created just to house the variable that allows a function + // expression to self-reference if it has a name defined + !scope.functionExpressionScope) { + for (const variable of scope.variables) { + // cases that we don't want to treat as used or unused + if ( + // implicit lib variables (from @typescript-eslint/scope-manager) + // these aren't variables that should be checked ever + variable instanceof scope_manager_1.ImplicitLibVariable) { + continue; + } + if ( + // variables marked with markVariableAsUsed() + variable.eslintUsed || + // basic exported variables + isExported(variable) || + // variables implicitly exported via a merged declaration + isMergableExported(variable) || + // used variables + isUsedVariable(variable)) { + variables.usedVariables.add(variable); + } + else { + variables.unusedVariables.add(variable); + } + } + } + for (const childScope of scope.childScopes) { + this.collectUnusedVariables(childScope, variables); + } + return variables; + } + getScope(currentNode) { + // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope. + const inner = currentNode.type !== utils_1.AST_NODE_TYPES.Program; + let node = currentNode; + while (node) { + const scope = this.#scopeManager.acquire(node, inner); + if (scope) { + if (scope.type === scope_manager_1.ScopeType.functionExpressionName) { + return scope.childScopes[0]; + } + return scope; + } + node = node.parent; + } + return this.#scopeManager.scopes[0]; + } + markVariableAsUsed(variableOrIdentifierOrName, parent) { + if (typeof variableOrIdentifierOrName !== 'string' && + !('type' in variableOrIdentifierOrName)) { + variableOrIdentifierOrName.eslintUsed = true; + return; + } + let name; + let node; + if (typeof variableOrIdentifierOrName === 'string') { + name = variableOrIdentifierOrName; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + node = parent; + } + else { + name = variableOrIdentifierOrName.name; + node = variableOrIdentifierOrName; + } + let currentScope = this.getScope(node); + while (currentScope) { + const variable = currentScope.variables.find(scopeVar => scopeVar.name === name); + if (variable) { + variable.eslintUsed = true; + return; + } + currentScope = currentScope.upper; + } + } + visitClass(node) { + // skip a variable of class itself name in the class scope + const scope = this.getScope(node); + for (const variable of scope.variables) { + if (variable.identifiers[0] === scope.block.id) { + this.markVariableAsUsed(variable); + return; + } + } + } + visitForInForOf(node) { + /** + * (Brad Zacher): I hate that this has to exist. + * But it is required for compat with the base ESLint rule. + * + * In 2015, ESLint decided to add an exception for these two specific cases + * ``` + * for (var key in object) return; + * + * var key; + * for (key in object) return; + * ``` + * + * I disagree with it, but what are you going to do... + * + * https://github.com/eslint/eslint/issues/2342 + */ + let idOrVariable; + if (node.left.type === utils_1.AST_NODE_TYPES.VariableDeclaration) { + const variable = this.#scopeManager.getDeclaredVariables(node.left).at(0); + if (!variable) { + return; + } + idOrVariable = variable; + } + if (node.left.type === utils_1.AST_NODE_TYPES.Identifier) { + idOrVariable = node.left; + } + if (idOrVariable == null) { + return; + } + let body = node.body; + if (node.body.type === utils_1.AST_NODE_TYPES.BlockStatement) { + if (node.body.body.length !== 1) { + return; + } + body = node.body.body[0]; + } + if (body.type !== utils_1.AST_NODE_TYPES.ReturnStatement) { + return; + } + this.markVariableAsUsed(idOrVariable); + } + visitFunction(node) { + const scope = this.getScope(node); + // skip implicit "arguments" variable + const variable = scope.set.get('arguments'); + if (variable?.defs.length === 0) { + this.markVariableAsUsed(variable); + } + } + visitFunctionTypeSignature(node) { + // function type signature params create variables because they can be referenced within the signature, + // but they obviously aren't unused variables for the purposes of this rule. + for (const param of node.params) { + this.visitPattern(param, name => { + this.markVariableAsUsed(name); + }); + } + } + visitSetter(node) { + if (node.kind === 'set') { + // ignore setter parameters because they're syntactically required to exist + for (const param of node.value.params) { + this.visitPattern(param, id => { + this.markVariableAsUsed(id); + }); + } + } + } +} +//#region private helpers +/** + * Checks the position of given nodes. + * @param inner A node which is expected as inside. + * @param outer A node which is expected as outside. + * @returns `true` if the `inner` node exists in the `outer` node. + */ +function isInside(inner, outer) { + return inner.range[0] >= outer.range[0] && inner.range[1] <= outer.range[1]; +} +/** + * Determine if an identifier is referencing an enclosing name. + * This only applies to declarations that create their own scope (modules, functions, classes) + * @param ref The reference to check. + * @param nodes The candidate function nodes. + * @returns True if it's a self-reference, false if not. + */ +function isSelfReference(ref, nodes) { + let scope = ref.from; + while (scope) { + if (nodes.has(scope.block)) { + return true; + } + scope = scope.upper; + } + return false; +} +const MERGABLE_TYPES = new Set([ + utils_1.AST_NODE_TYPES.ClassDeclaration, + utils_1.AST_NODE_TYPES.FunctionDeclaration, + utils_1.AST_NODE_TYPES.TSInterfaceDeclaration, + utils_1.AST_NODE_TYPES.TSModuleDeclaration, + utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration, +]); +/** + * Determine if the variable is directly exported + * @param variable the variable to check + */ +function isMergableExported(variable) { + // If all of the merged things are of the same type, TS will error if not all of them are exported - so we only need to find one + for (const def of variable.defs) { + // parameters can never be exported. + // their `node` prop points to the function decl, which can be exported + // so we need to special case them + if (def.type === utils_1.TSESLint.Scope.DefinitionType.Parameter) { + continue; + } + if ((MERGABLE_TYPES.has(def.node.type) && + def.node.parent?.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration) || + def.node.parent?.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration) { + return true; + } + } + return false; +} +/** + * Determines if a given variable is being exported from a module. + * @param variable eslint-scope variable object. + * @returns True if the variable is exported, false if not. + */ +function isExported(variable) { + return variable.defs.some(definition => { + let node = definition.node; + if (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + node = node.parent; + } + else if (definition.type === utils_1.TSESLint.Scope.DefinitionType.Parameter) { + return false; + } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return node.parent.type.startsWith('Export'); + }); +} +const LOGICAL_ASSIGNMENT_OPERATORS = new Set(['??=', '&&=', '||=']); +/** + * Determines if the variable is used. + * @param variable The variable to check. + * @returns True if the variable is used + */ +function isUsedVariable(variable) { + /** + * Gets a list of function definitions for a specified variable. + * @param variable eslint-scope variable object. + * @returns Function nodes. + */ + function getFunctionDefinitions(variable) { + const functionDefinitions = new Set(); + variable.defs.forEach(def => { + // FunctionDeclarations + if (def.type === utils_1.TSESLint.Scope.DefinitionType.FunctionName) { + functionDefinitions.add(def.node); + } + // FunctionExpressions + if (def.type === utils_1.TSESLint.Scope.DefinitionType.Variable && + (def.node.init?.type === utils_1.AST_NODE_TYPES.FunctionExpression || + def.node.init?.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression)) { + functionDefinitions.add(def.node.init); + } + }); + return functionDefinitions; + } + function getTypeDeclarations(variable) { + const nodes = new Set(); + variable.defs.forEach(def => { + if (def.node.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration || + def.node.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration) { + nodes.add(def.node); + } + }); + return nodes; + } + function getModuleDeclarations(variable) { + const nodes = new Set(); + variable.defs.forEach(def => { + if (def.node.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration) { + nodes.add(def.node); + } + }); + return nodes; + } + function getEnumDeclarations(variable) { + const nodes = new Set(); + variable.defs.forEach(def => { + if (def.node.type === utils_1.AST_NODE_TYPES.TSEnumDeclaration) { + nodes.add(def.node); + } + }); + return nodes; + } + /** + * Checks if the ref is contained within one of the given nodes + */ + function isInsideOneOf(ref, nodes) { + for (const node of nodes) { + if (isInside(ref.identifier, node)) { + return true; + } + } + return false; + } + /** + * Checks whether a given node is unused expression or not. + * @param node The node itself + * @returns The node is an unused expression. + */ + function isUnusedExpression(node) { + const parent = node.parent; + if (parent.type === utils_1.AST_NODE_TYPES.ExpressionStatement) { + return true; + } + if (parent.type === utils_1.AST_NODE_TYPES.SequenceExpression) { + const isLastExpression = parent.expressions[parent.expressions.length - 1] === node; + if (!isLastExpression) { + return true; + } + return isUnusedExpression(parent); + } + return false; + } + /** + * If a given reference is left-hand side of an assignment, this gets + * the right-hand side node of the assignment. + * + * In the following cases, this returns null. + * + * - The reference is not the LHS of an assignment expression. + * - The reference is inside of a loop. + * - The reference is inside of a function scope which is different from + * the declaration. + * @param ref A reference to check. + * @param prevRhsNode The previous RHS node. + * @returns The RHS node or null. + */ + function getRhsNode(ref, prevRhsNode) { + /** + * Checks whether the given node is in a loop or not. + * @param node The node to check. + * @returns `true` if the node is in a loop. + */ + function isInLoop(node) { + let currentNode = node; + while (currentNode) { + if (utils_1.ASTUtils.isFunction(currentNode)) { + break; + } + if (utils_1.ASTUtils.isLoop(currentNode)) { + return true; + } + currentNode = currentNode.parent; + } + return false; + } + const id = ref.identifier; + const parent = id.parent; + const refScope = ref.from.variableScope; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const varScope = ref.resolved.scope.variableScope; + const canBeUsedLater = refScope !== varScope || isInLoop(id); + /* + * Inherits the previous node if this reference is in the node. + * This is for `a = a + a`-like code. + */ + if (prevRhsNode && isInside(id, prevRhsNode)) { + return prevRhsNode; + } + if (parent.type === utils_1.AST_NODE_TYPES.AssignmentExpression && + isUnusedExpression(parent) && + id === parent.left && + !canBeUsedLater) { + return parent.right; + } + return null; + } + /** + * Checks whether a given reference is a read to update itself or not. + * @param ref A reference to check. + * @param rhsNode The RHS node of the previous assignment. + * @returns The reference is a read to update itself. + */ + function isReadForItself(ref, rhsNode) { + /** + * Checks whether a given Identifier node exists inside of a function node which can be used later. + * + * "can be used later" means: + * - the function is assigned to a variable. + * - the function is bound to a property and the object can be used later. + * - the function is bound as an argument of a function call. + * + * If a reference exists in a function which can be used later, the reference is read when the function is called. + * @param id An Identifier node to check. + * @param rhsNode The RHS node of the previous assignment. + * @returns `true` if the `id` node exists inside of a function node which can be used later. + */ + function isInsideOfStorableFunction(id, rhsNode) { + /** + * Finds a function node from ancestors of a node. + * @param node A start node to find. + * @returns A found function node. + */ + function getUpperFunction(node) { + let currentNode = node; + while (currentNode) { + if (utils_1.ASTUtils.isFunction(currentNode)) { + return currentNode; + } + currentNode = currentNode.parent; + } + return null; + } + /** + * Checks whether a given function node is stored to somewhere or not. + * If the function node is stored, the function can be used later. + * @param funcNode A function node to check. + * @param rhsNode The RHS node of the previous assignment. + * @returns `true` if under the following conditions: + * - the funcNode is assigned to a variable. + * - the funcNode is bound as an argument of a function call. + * - the function is bound to a property and the object satisfies above conditions. + */ + function isStorableFunction(funcNode, rhsNode) { + let node = funcNode; + let parent = funcNode.parent; + while (parent && isInside(parent, rhsNode)) { + switch (parent.type) { + case utils_1.AST_NODE_TYPES.SequenceExpression: + if (parent.expressions[parent.expressions.length - 1] !== node) { + return false; + } + break; + case utils_1.AST_NODE_TYPES.CallExpression: + case utils_1.AST_NODE_TYPES.NewExpression: + return parent.callee !== node; + case utils_1.AST_NODE_TYPES.AssignmentExpression: + case utils_1.AST_NODE_TYPES.TaggedTemplateExpression: + case utils_1.AST_NODE_TYPES.YieldExpression: + return true; + default: + if (parent.type.endsWith('Statement') || + parent.type.endsWith('Declaration')) { + /* + * If it encountered statements, this is a complex pattern. + * Since analyzing complex patterns is hard, this returns `true` to avoid false positive. + */ + return true; + } + } + node = parent; + parent = parent.parent; + } + return false; + } + const funcNode = getUpperFunction(id); + return (!!funcNode && + isInside(funcNode, rhsNode) && + isStorableFunction(funcNode, rhsNode)); + } + const id = ref.identifier; + const parent = id.parent; + return (ref.isRead() && // in RHS of an assignment for itself. e.g. `a = a + 1` + // self update. e.g. `a += 1`, `a++` + ((parent.type === utils_1.AST_NODE_TYPES.AssignmentExpression && + !LOGICAL_ASSIGNMENT_OPERATORS.has(parent.operator) && + isUnusedExpression(parent) && + parent.left === id) || + (parent.type === utils_1.AST_NODE_TYPES.UpdateExpression && + isUnusedExpression(parent)) || + (!!rhsNode && + isInside(id, rhsNode) && + !isInsideOfStorableFunction(id, rhsNode)))); + } + const functionNodes = getFunctionDefinitions(variable); + const isFunctionDefinition = functionNodes.size > 0; + const typeDeclNodes = getTypeDeclarations(variable); + const isTypeDecl = typeDeclNodes.size > 0; + const moduleDeclNodes = getModuleDeclarations(variable); + const isModuleDecl = moduleDeclNodes.size > 0; + const enumDeclNodes = getEnumDeclarations(variable); + const isEnumDecl = enumDeclNodes.size > 0; + const isImportedAsType = variable.defs.every(isTypeImport_1.isTypeImport); + let rhsNode = null; + return variable.references.some(ref => { + const forItself = isReadForItself(ref, rhsNode); + rhsNode = getRhsNode(ref, rhsNode); + return (ref.isRead() && + !forItself && + !(!isImportedAsType && (0, referenceContainsTypeQuery_1.referenceContainsTypeQuery)(ref.identifier)) && + !(isFunctionDefinition && isSelfReference(ref, functionNodes)) && + !(isTypeDecl && isInsideOneOf(ref, typeDeclNodes)) && + !(isModuleDecl && isSelfReference(ref, moduleDeclNodes)) && + !(isEnumDecl && isSelfReference(ref, enumDeclNodes))); + }); +} +//#endregion private helpers +/** + * Collects the set of unused variables for a given context. + * + * Due to complexity, this does not take into consideration: + * - variables within declaration files + * - variables within ambient module declarations + */ +function collectVariables(context) { + return UnusedVarsVisitor.collectUnusedVariables(context.sourceCode.ast, utils_1.ESLintUtils.nullThrows(context.sourceCode.scopeManager, 'Missing required scope manager')); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/createRule.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/createRule.d.ts new file mode 100644 index 00000000..67d10451 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/createRule.d.ts @@ -0,0 +1,4 @@ +import { ESLintUtils } from '@typescript-eslint/utils'; +import type { ESLintPluginDocs } from '../../rules'; +export declare const createRule: ({ meta, name, ...rule }: Readonly>) => ESLintUtils.RuleModule; +//# sourceMappingURL=createRule.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/createRule.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/createRule.d.ts.map new file mode 100644 index 00000000..662680c6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/createRule.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"createRule.d.ts","sourceRoot":"","sources":["../../src/util/createRule.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEpD,eAAO,MAAM,UAAU,uQAEtB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/createRule.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/createRule.js new file mode 100644 index 00000000..2ae6aec2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/createRule.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createRule = void 0; +const utils_1 = require("@typescript-eslint/utils"); +exports.createRule = utils_1.ESLintUtils.RuleCreator(name => `https://typescript-eslint.io/rules/${name}`); diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/escapeRegExp.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/escapeRegExp.d.ts new file mode 100644 index 00000000..8e53ee73 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/escapeRegExp.d.ts @@ -0,0 +1,2 @@ +export declare function escapeRegExp(string?: string): string; +//# sourceMappingURL=escapeRegExp.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/escapeRegExp.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/escapeRegExp.d.ts.map new file mode 100644 index 00000000..4b2b6c11 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/escapeRegExp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"escapeRegExp.d.ts","sourceRoot":"","sources":["../../src/util/escapeRegExp.ts"],"names":[],"mappings":"AAOA,wBAAgB,YAAY,CAAC,MAAM,SAAK,GAAG,MAAM,CAIhD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/escapeRegExp.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/escapeRegExp.js new file mode 100644 index 00000000..02d2ab68 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/escapeRegExp.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.escapeRegExp = escapeRegExp; +/** + * Lodash + * Released under MIT license + */ +const reRegExpChar = /[\\^$.*+?()[\]{}|]/g; +const reHasRegExpChar = RegExp(reRegExpChar.source); +function escapeRegExp(string = '') { + return string && reHasRegExpChar.test(string) + ? string.replaceAll(reRegExpChar, '\\$&') + : string; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/explicitReturnTypeUtils.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/explicitReturnTypeUtils.d.ts new file mode 100644 index 00000000..887f2bec --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/explicitReturnTypeUtils.d.ts @@ -0,0 +1,48 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +export type FunctionExpression = TSESTree.ArrowFunctionExpression | TSESTree.FunctionExpression; +export type FunctionNode = FunctionExpression | TSESTree.FunctionDeclaration; +export interface FunctionInfo { + node: T; + returns: TSESTree.ReturnStatement[]; +} +/** + * Checks if a function belongs to: + * ``` + * () => () => ... + * () => function () { ... } + * () => { return () => ... } + * () => { return function () { ... } } + * function fn() { return () => ... } + * function fn() { return function() { ... } } + * ``` + */ +export declare function doesImmediatelyReturnFunctionExpression({ node, returns, }: FunctionInfo): boolean; +interface Options { + allowDirectConstAssertionInArrowFunctions?: boolean; + allowExpressions?: boolean; + allowHigherOrderFunctions?: boolean; + allowTypedFunctionExpressions?: boolean; +} +/** + * True when the provided function expression is typed. + */ +export declare function isTypedFunctionExpression(node: FunctionExpression, options: Options): boolean; +/** + * Check whether the function expression return type is either typed or valid + * with the provided options. + */ +export declare function isValidFunctionExpressionReturnType(node: FunctionExpression, options: Options): boolean; +/** + * Checks if a function declaration/expression has a return type. + */ +export declare function checkFunctionReturnType({ node, returns }: FunctionInfo, options: Options, sourceCode: TSESLint.SourceCode, report: (loc: TSESTree.SourceLocation) => void): void; +/** + * Checks if a function declaration/expression has a return type. + */ +export declare function checkFunctionExpressionReturnType(info: FunctionInfo, options: Options, sourceCode: TSESLint.SourceCode, report: (loc: TSESTree.SourceLocation) => void): void; +/** + * Check whether any ancestor of the provided function has a valid return type. + */ +export declare function ancestorHasReturnType(node: FunctionNode): boolean; +export {}; +//# sourceMappingURL=explicitReturnTypeUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/explicitReturnTypeUtils.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/explicitReturnTypeUtils.d.ts.map new file mode 100644 index 00000000..8ddbacdb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/explicitReturnTypeUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"explicitReturnTypeUtils.d.ts","sourceRoot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E,YAAY,CAAC,kBAAkB,CAAC,EACtC,OAAO,EAAE,OAAO,EAChB,UAAU,EAAE,QAAQ,CAAC,UAAU,EAC/B,MAAM,EAAE,CAAC,GAAG,EAAE,QAAQ,CAAC,cAAc,KAAK,IAAI,GAC7C,IAAI,CAMN;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAyCjE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/explicitReturnTypeUtils.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/explicitReturnTypeUtils.js new file mode 100644 index 00000000..d574aca4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/explicitReturnTypeUtils.js @@ -0,0 +1,240 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.doesImmediatelyReturnFunctionExpression = doesImmediatelyReturnFunctionExpression; +exports.isTypedFunctionExpression = isTypedFunctionExpression; +exports.isValidFunctionExpressionReturnType = isValidFunctionExpressionReturnType; +exports.checkFunctionReturnType = checkFunctionReturnType; +exports.checkFunctionExpressionReturnType = checkFunctionExpressionReturnType; +exports.ancestorHasReturnType = ancestorHasReturnType; +const utils_1 = require("@typescript-eslint/utils"); +const astUtils_1 = require("./astUtils"); +const getFunctionHeadLoc_1 = require("./getFunctionHeadLoc"); +/** + * Checks if a node is a variable declarator with a type annotation. + * ``` + * const x: Foo = ... + * ``` + */ +function isVariableDeclaratorWithTypeAnnotation(node) { + return (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator && !!node.id.typeAnnotation); +} +/** + * Checks if a node is a class property with a type annotation. + * ``` + * public x: Foo = ... + * ``` + */ +function isPropertyDefinitionWithTypeAnnotation(node) { + return (node.type === utils_1.AST_NODE_TYPES.PropertyDefinition && !!node.typeAnnotation); +} +/** + * Checks if a node belongs to: + * ``` + * foo(() => 1) + * ``` + */ +function isFunctionArgument(parent, callee) { + return (parent.type === utils_1.AST_NODE_TYPES.CallExpression && + // make sure this isn't an IIFE + parent.callee !== callee); +} +/** + * Checks if a node is type-constrained in JSX + * ``` + * {}} /> + * {() => {}} + * + * ``` + */ +function isTypedJSX(node) { + return (node.type === utils_1.AST_NODE_TYPES.JSXExpressionContainer || + node.type === utils_1.AST_NODE_TYPES.JSXSpreadAttribute); +} +function isTypedParent(parent, callee) { + return ((0, astUtils_1.isTypeAssertion)(parent) || + isVariableDeclaratorWithTypeAnnotation(parent) || + isDefaultFunctionParameterWithTypeAnnotation(parent) || + isPropertyDefinitionWithTypeAnnotation(parent) || + isFunctionArgument(parent, callee) || + isTypedJSX(parent)); +} +function isDefaultFunctionParameterWithTypeAnnotation(node) { + return (node.type === utils_1.AST_NODE_TYPES.AssignmentPattern && + node.left.typeAnnotation != null); +} +/** + * Checks if a node belongs to: + * ``` + * new Foo(() => {}) + * ^^^^^^^^ + * ``` + */ +function isConstructorArgument(node) { + return node.type === utils_1.AST_NODE_TYPES.NewExpression; +} +/** + * Checks if a node is a property or a nested property of a typed object: + * ``` + * const x: Foo = { prop: () => {} } + * const x = { prop: () => {} } as Foo + * const x = { prop: () => {} } + * const x: Foo = { bar: { prop: () => {} } } + * ``` + */ +function isPropertyOfObjectWithType(property) { + if (!property || property.type !== utils_1.AST_NODE_TYPES.Property) { + return false; + } + const objectExpr = property.parent; + if (objectExpr.type !== utils_1.AST_NODE_TYPES.ObjectExpression) { + return false; + } + const parent = objectExpr.parent; + return isTypedParent(parent) || isPropertyOfObjectWithType(parent); +} +/** + * Checks if a function belongs to: + * ``` + * () => () => ... + * () => function () { ... } + * () => { return () => ... } + * () => { return function () { ... } } + * function fn() { return () => ... } + * function fn() { return function() { ... } } + * ``` + */ +function doesImmediatelyReturnFunctionExpression({ node, returns, }) { + if (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + utils_1.ASTUtils.isFunction(node.body)) { + return true; + } + if (returns.length === 0) { + return false; + } + return returns.every(node => node.argument && utils_1.ASTUtils.isFunction(node.argument)); +} +/** + * Checks if a function belongs to: + * ``` + * ({ action: 'xxx' } as const) + * ``` + */ +function isConstAssertion(node) { + if ((0, astUtils_1.isTypeAssertion)(node)) { + const { typeAnnotation } = node; + if (typeAnnotation.type === utils_1.AST_NODE_TYPES.TSTypeReference) { + const { typeName } = typeAnnotation; + if (typeName.type === utils_1.AST_NODE_TYPES.Identifier && + typeName.name === 'const') { + return true; + } + } + } + return false; +} +/** + * True when the provided function expression is typed. + */ +function isTypedFunctionExpression(node, options) { + const parent = utils_1.ESLintUtils.nullThrows(node.parent, utils_1.ESLintUtils.NullThrowsReasons.MissingParent); + if (!options.allowTypedFunctionExpressions) { + return false; + } + return (isTypedParent(parent, node) || + isPropertyOfObjectWithType(parent) || + isConstructorArgument(parent)); +} +/** + * Check whether the function expression return type is either typed or valid + * with the provided options. + */ +function isValidFunctionExpressionReturnType(node, options) { + if (isTypedFunctionExpression(node, options)) { + return true; + } + const parent = utils_1.ESLintUtils.nullThrows(node.parent, utils_1.ESLintUtils.NullThrowsReasons.MissingParent); + if (options.allowExpressions && + parent.type !== utils_1.AST_NODE_TYPES.VariableDeclarator && + parent.type !== utils_1.AST_NODE_TYPES.MethodDefinition && + parent.type !== utils_1.AST_NODE_TYPES.ExportDefaultDeclaration && + parent.type !== utils_1.AST_NODE_TYPES.PropertyDefinition) { + return true; + } + // https://github.com/typescript-eslint/typescript-eslint/issues/653 + if (!options.allowDirectConstAssertionInArrowFunctions || + node.type !== utils_1.AST_NODE_TYPES.ArrowFunctionExpression) { + return false; + } + let body = node.body; + while (body.type === utils_1.AST_NODE_TYPES.TSSatisfiesExpression) { + body = body.expression; + } + return isConstAssertion(body); +} +/** + * Check that the function expression or declaration is valid. + */ +function isValidFunctionReturnType({ node, returns }, options) { + if (options.allowHigherOrderFunctions && + doesImmediatelyReturnFunctionExpression({ node, returns })) { + return true; + } + return (node.returnType != null || + (0, astUtils_1.isConstructor)(node.parent) || + (0, astUtils_1.isSetter)(node.parent)); +} +/** + * Checks if a function declaration/expression has a return type. + */ +function checkFunctionReturnType({ node, returns }, options, sourceCode, report) { + if (isValidFunctionReturnType({ node, returns }, options)) { + return; + } + report((0, getFunctionHeadLoc_1.getFunctionHeadLoc)(node, sourceCode)); +} +/** + * Checks if a function declaration/expression has a return type. + */ +function checkFunctionExpressionReturnType(info, options, sourceCode, report) { + if (isValidFunctionExpressionReturnType(info.node, options)) { + return; + } + checkFunctionReturnType(info, options, sourceCode, report); +} +/** + * Check whether any ancestor of the provided function has a valid return type. + */ +function ancestorHasReturnType(node) { + let ancestor = node.parent; + if (ancestor.type === utils_1.AST_NODE_TYPES.Property) { + ancestor = ancestor.value; + } + // if the ancestor is not a return, then this function was not returned at all, so we can exit early + const isReturnStatement = ancestor.type === utils_1.AST_NODE_TYPES.ReturnStatement; + const isBodylessArrow = ancestor.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + ancestor.body.type !== utils_1.AST_NODE_TYPES.BlockStatement; + if (!isReturnStatement && !isBodylessArrow) { + return false; + } + while (ancestor) { + switch (ancestor.type) { + case utils_1.AST_NODE_TYPES.ArrowFunctionExpression: + case utils_1.AST_NODE_TYPES.FunctionExpression: + case utils_1.AST_NODE_TYPES.FunctionDeclaration: + if (ancestor.returnType) { + return true; + } + break; + // const x: Foo = () => {}; + // Assume that a typed variable types the function expression + case utils_1.AST_NODE_TYPES.VariableDeclarator: + return !!ancestor.id.typeAnnotation; + case utils_1.AST_NODE_TYPES.PropertyDefinition: + return !!ancestor.typeAnnotation; + case utils_1.AST_NODE_TYPES.ExpressionStatement: + return false; + } + ancestor = ancestor.parent; + } + return false; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getConstraintInfo.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getConstraintInfo.d.ts new file mode 100644 index 00000000..2c259c48 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getConstraintInfo.d.ts @@ -0,0 +1,36 @@ +import type * as ts from 'typescript'; +export interface ConstraintTypeInfoUnconstrained { + constraintType: undefined; + isTypeParameter: true; +} +export interface ConstraintTypeInfoConstrained { + constraintType: ts.Type; + isTypeParameter: true; +} +export interface ConstraintTypeInfoNonGeneric { + constraintType: ts.Type; + isTypeParameter: false; +} +export type ConstraintTypeInfo = ConstraintTypeInfoConstrained | ConstraintTypeInfoNonGeneric | ConstraintTypeInfoUnconstrained; +/** + * Returns whether the type is a generic and what its constraint is. + * + * If the type is not a generic, `isTypeParameter` will be `false`, and + * `constraintType` will be the same as the input type. + * + * If the type is a generic, and it is constrained, `isTypeParameter` will be + * `true`, and `constraintType` will be the constraint type. + * + * If the type is a generic, but it is not constrained, `constraintType` will be + * `undefined` (rather than an `unknown` type), due to https://github.com/microsoft/TypeScript/issues/60475 + * + * Successor to {@link getConstrainedTypeAtLocation} due to https://github.com/typescript-eslint/typescript-eslint/issues/10438 + * + * This is considered internal since it is unstable for now and may have breaking changes at any time. + * Use at your own risk. + * + * @internal + * + */ +export declare function getConstraintInfo(checker: ts.TypeChecker, type: ts.Type): ConstraintTypeInfo; +//# sourceMappingURL=getConstraintInfo.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getConstraintInfo.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getConstraintInfo.d.ts.map new file mode 100644 index 00000000..9cf19979 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getConstraintInfo.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getConstraintInfo.d.ts","sourceRoot":"","sources":["../../src/util/getConstraintInfo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAItC,MAAM,WAAW,+BAA+B;IAC9C,cAAc,EAAE,SAAS,CAAC;IAC1B,eAAe,EAAE,IAAI,CAAC;CACvB;AAED,MAAM,WAAW,6BAA6B;IAC5C,cAAc,EAAE,EAAE,CAAC,IAAI,CAAC;IACxB,eAAe,EAAE,IAAI,CAAC;CACvB;AAED,MAAM,WAAW,4BAA4B;IAC3C,cAAc,EAAE,EAAE,CAAC,IAAI,CAAC;IACxB,eAAe,EAAE,KAAK,CAAC;CACxB;AAED,MAAM,MAAM,kBAAkB,GAC1B,6BAA6B,GAC7B,4BAA4B,GAC5B,+BAA+B,CAAC;AAEpC;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,EAAE,CAAC,WAAW,EACvB,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,kBAAkB,CAYpB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getConstraintInfo.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getConstraintInfo.js new file mode 100644 index 00000000..76f20963 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getConstraintInfo.js @@ -0,0 +1,70 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getConstraintInfo = getConstraintInfo; +const tsutils = __importStar(require("ts-api-utils")); +/** + * Returns whether the type is a generic and what its constraint is. + * + * If the type is not a generic, `isTypeParameter` will be `false`, and + * `constraintType` will be the same as the input type. + * + * If the type is a generic, and it is constrained, `isTypeParameter` will be + * `true`, and `constraintType` will be the constraint type. + * + * If the type is a generic, but it is not constrained, `constraintType` will be + * `undefined` (rather than an `unknown` type), due to https://github.com/microsoft/TypeScript/issues/60475 + * + * Successor to {@link getConstrainedTypeAtLocation} due to https://github.com/typescript-eslint/typescript-eslint/issues/10438 + * + * This is considered internal since it is unstable for now and may have breaking changes at any time. + * Use at your own risk. + * + * @internal + * + */ +function getConstraintInfo(checker, type) { + if (tsutils.isTypeParameter(type)) { + const constraintType = checker.getBaseConstraintOfType(type); + return { + constraintType, + isTypeParameter: true, + }; + } + return { + constraintType: type, + isTypeParameter: false, + }; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getESLintCoreRule.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getESLintCoreRule.d.ts new file mode 100644 index 00000000..5e853087 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getESLintCoreRule.d.ts @@ -0,0 +1,28 @@ +interface RuleMap { + 'arrow-parens': typeof import('eslint/lib/rules/arrow-parens'); + 'consistent-return': typeof import('eslint/lib/rules/consistent-return'); + 'dot-notation': typeof import('eslint/lib/rules/dot-notation'); + 'init-declarations': typeof import('eslint/lib/rules/init-declarations'); + 'max-params': typeof import('eslint/lib/rules/max-params'); + 'no-dupe-args': typeof import('eslint/lib/rules/no-dupe-args'); + 'no-dupe-class-members': typeof import('eslint/lib/rules/no-dupe-class-members'); + 'no-empty-function': typeof import('eslint/lib/rules/no-empty-function'); + 'no-implicit-globals': typeof import('eslint/lib/rules/no-implicit-globals'); + 'no-invalid-this': typeof import('eslint/lib/rules/no-invalid-this'); + 'no-loop-func': typeof import('eslint/lib/rules/no-loop-func'); + 'no-loss-of-precision': typeof import('eslint/lib/rules/no-loss-of-precision'); + 'no-magic-numbers': typeof import('eslint/lib/rules/no-magic-numbers'); + 'no-restricted-globals': typeof import('eslint/lib/rules/no-restricted-globals'); + 'no-restricted-imports': typeof import('eslint/lib/rules/no-restricted-imports'); + 'no-undef': typeof import('eslint/lib/rules/no-undef'); + 'no-unused-expressions': typeof import('eslint/lib/rules/no-unused-expressions'); + 'no-useless-constructor': typeof import('eslint/lib/rules/no-useless-constructor'); + 'prefer-const': typeof import('eslint/lib/rules/prefer-const'); + 'prefer-destructuring': typeof import('eslint/lib/rules/prefer-destructuring'); + strict: typeof import('eslint/lib/rules/strict'); +} +type RuleId = keyof RuleMap; +export declare const getESLintCoreRule: (ruleId: R) => RuleMap[R]; +export declare function maybeGetESLintCoreRule(ruleId: R): RuleMap[R] | null; +export {}; +//# sourceMappingURL=getESLintCoreRule.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getESLintCoreRule.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getESLintCoreRule.d.ts.map new file mode 100644 index 00000000..03b625d2 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getESLintCoreRule.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getESLintCoreRule.d.ts","sourceRoot":"","sources":["../../src/util/getESLintCoreRule.ts"],"names":[],"mappings":"AAGA,UAAU,OAAO;IAEf,cAAc,EAAE,cAAc,+BAA+B,CAAC,CAAC;IAC/D,mBAAmB,EAAE,cAAc,oCAAoC,CAAC,CAAC;IACzE,cAAc,EAAE,cAAc,+BAA+B,CAAC,CAAC;IAC/D,mBAAmB,EAAE,cAAc,oCAAoC,CAAC,CAAC;IACzE,YAAY,EAAE,cAAc,6BAA6B,CAAC,CAAC;IAC3D,cAAc,EAAE,cAAc,+BAA+B,CAAC,CAAC;IAC/D,uBAAuB,EAAE,cAAc,wCAAwC,CAAC,CAAC;IACjF,mBAAmB,EAAE,cAAc,oCAAoC,CAAC,CAAC;IACzE,qBAAqB,EAAE,cAAc,sCAAsC,CAAC,CAAC;IAC7E,iBAAiB,EAAE,cAAc,kCAAkC,CAAC,CAAC;IACrE,cAAc,EAAE,cAAc,+BAA+B,CAAC,CAAC;IAC/D,sBAAsB,EAAE,cAAc,uCAAuC,CAAC,CAAC;IAC/E,kBAAkB,EAAE,cAAc,mCAAmC,CAAC,CAAC;IACvE,uBAAuB,EAAE,cAAc,wCAAwC,CAAC,CAAC;IACjF,uBAAuB,EAAE,cAAc,wCAAwC,CAAC,CAAC;IACjF,UAAU,EAAE,cAAc,2BAA2B,CAAC,CAAC;IACvD,uBAAuB,EAAE,cAAc,wCAAwC,CAAC,CAAC;IACjF,wBAAwB,EAAE,cAAc,yCAAyC,CAAC,CAAC;IACnF,cAAc,EAAE,cAAc,+BAA+B,CAAC,CAAC;IAC/D,sBAAsB,EAAE,cAAc,uCAAuC,CAAC,CAAC;IAC/E,MAAM,EAAE,cAAc,yBAAyB,CAAC,CAAC;CAElD;AAED,KAAK,MAAM,GAAG,MAAM,OAAO,CAAC;AAE5B,eAAO,MAAM,iBAAiB,GAAI,CAAC,SAAS,MAAM,EAAE,QAAQ,CAAC,KAAG,OAAO,CAAC,CAAC,CAItE,CAAC;AAEJ,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,MAAM,EACrD,MAAM,EAAE,CAAC,GACR,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAMnB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getESLintCoreRule.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getESLintCoreRule.js new file mode 100644 index 00000000..6bb8fa47 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getESLintCoreRule.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getESLintCoreRule = void 0; +exports.maybeGetESLintCoreRule = maybeGetESLintCoreRule; +const utils_1 = require("@typescript-eslint/utils"); +const use_at_your_own_risk_1 = require("eslint/use-at-your-own-risk"); +const getESLintCoreRule = (ruleId) => utils_1.ESLintUtils.nullThrows(use_at_your_own_risk_1.builtinRules.get(ruleId), `ESLint's core rule '${ruleId}' not found.`); +exports.getESLintCoreRule = getESLintCoreRule; +function maybeGetESLintCoreRule(ruleId) { + try { + return (0, exports.getESLintCoreRule)(ruleId); + } + catch { + return null; + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFixOrSuggest.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFixOrSuggest.d.ts new file mode 100644 index 00000000..08889278 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFixOrSuggest.d.ts @@ -0,0 +1,10 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export declare function getFixOrSuggest({ fixOrSuggest, suggestion, }: { + fixOrSuggest: 'fix' | 'none' | 'suggest'; + suggestion: TSESLint.SuggestionReportDescriptor; +}): { + fix: TSESLint.ReportFixFunction; +} | { + suggest: TSESLint.SuggestionReportDescriptor[]; +} | undefined; +//# sourceMappingURL=getFixOrSuggest.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFixOrSuggest.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFixOrSuggest.d.ts.map new file mode 100644 index 00000000..44a7071b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFixOrSuggest.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getFixOrSuggest.d.ts","sourceRoot":"","sources":["../../src/util/getFixOrSuggest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,wBAAgB,eAAe,CAAC,SAAS,SAAS,MAAM,EAAE,EACxD,YAAY,EACZ,UAAU,GACX,EAAE;IACD,YAAY,EAAE,KAAK,GAAG,MAAM,GAAG,SAAS,CAAC;IACzC,UAAU,EAAE,QAAQ,CAAC,0BAA0B,CAAC,SAAS,CAAC,CAAC;CAC5D,GACG;IAAE,GAAG,EAAE,QAAQ,CAAC,iBAAiB,CAAA;CAAE,GACnC;IAAE,OAAO,EAAE,QAAQ,CAAC,0BAA0B,CAAC,SAAS,CAAC,EAAE,CAAA;CAAE,GAC7D,SAAS,CASZ"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFixOrSuggest.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFixOrSuggest.js new file mode 100644 index 00000000..d665b96a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFixOrSuggest.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getFixOrSuggest = getFixOrSuggest; +function getFixOrSuggest({ fixOrSuggest, suggestion, }) { + switch (fixOrSuggest) { + case 'fix': + return { fix: suggestion.fix }; + case 'none': + return undefined; + case 'suggest': + return { suggest: [suggestion] }; + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getForStatementHeadLoc.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getForStatementHeadLoc.d.ts new file mode 100644 index 00000000..7ffff343 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getForStatementHeadLoc.d.ts @@ -0,0 +1,18 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +/** + * Gets the location of the head of the given for statement variant for reporting. + * + * - `for (const foo in bar) expressionOrBlock` + * ^^^^^^^^^^^^^^^^^^^^^^ + * + * - `for (const foo of bar) expressionOrBlock` + * ^^^^^^^^^^^^^^^^^^^^^^ + * + * - `for await (const foo of bar) expressionOrBlock` + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * + * - `for (let i = 0; i < 10; i++) expressionOrBlock` + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + */ +export declare function getForStatementHeadLoc(sourceCode: TSESLint.SourceCode, node: TSESTree.ForInStatement | TSESTree.ForOfStatement | TSESTree.ForStatement): TSESTree.SourceLocation; +//# sourceMappingURL=getForStatementHeadLoc.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getForStatementHeadLoc.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getForStatementHeadLoc.d.ts.map new file mode 100644 index 00000000..7707abc0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getForStatementHeadLoc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getForStatementHeadLoc.d.ts","sourceRoot":"","sources":["../../src/util/getForStatementHeadLoc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAInE;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,sBAAsB,CACpC,UAAU,EAAE,QAAQ,CAAC,UAAU,EAC/B,IAAI,EACA,QAAQ,CAAC,cAAc,GACvB,QAAQ,CAAC,cAAc,GACvB,QAAQ,CAAC,YAAY,GACxB,QAAQ,CAAC,cAAc,CASzB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getForStatementHeadLoc.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getForStatementHeadLoc.js new file mode 100644 index 00000000..aa6c0daf --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getForStatementHeadLoc.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getForStatementHeadLoc = getForStatementHeadLoc; +const eslint_utils_1 = require("@typescript-eslint/utils/eslint-utils"); +/** + * Gets the location of the head of the given for statement variant for reporting. + * + * - `for (const foo in bar) expressionOrBlock` + * ^^^^^^^^^^^^^^^^^^^^^^ + * + * - `for (const foo of bar) expressionOrBlock` + * ^^^^^^^^^^^^^^^^^^^^^^ + * + * - `for await (const foo of bar) expressionOrBlock` + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * + * - `for (let i = 0; i < 10; i++) expressionOrBlock` + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + */ +function getForStatementHeadLoc(sourceCode, node) { + const closingParens = (0, eslint_utils_1.nullThrows)(sourceCode.getTokenBefore(node.body, token => token.value === ')'), 'for statement must have a closing parenthesis.'); + return { + end: structuredClone(closingParens.loc.end), + start: structuredClone(node.loc.start), + }; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFunctionHeadLoc.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFunctionHeadLoc.d.ts new file mode 100644 index 00000000..4c498aec --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFunctionHeadLoc.d.ts @@ -0,0 +1,102 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +type FunctionNode = TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression; +/** + * Gets the location of the given function node for reporting. + * + * - `function foo() {}` + * ^^^^^^^^^^^^ + * - `(function foo() {})` + * ^^^^^^^^^^^^ + * - `(function() {})` + * ^^^^^^^^ + * - `function* foo() {}` + * ^^^^^^^^^^^^^ + * - `(function* foo() {})` + * ^^^^^^^^^^^^^ + * - `(function*() {})` + * ^^^^^^^^^ + * - `() => {}` + * ^^ + * - `async () => {}` + * ^^ + * - `({ foo: function foo() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ foo: function() {} })` + * ^^^^^^^^^^^^^ + * - `({ ['foo']: function() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function() {} })` + * ^^^^^^^^^^^^^^^ + * - `({ foo() {} })` + * ^^^ + * - `({ foo: function* foo() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ foo: function*() {} })` + * ^^^^^^^^^^^^^^ + * - `({ ['foo']: function*() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function*() {} })` + * ^^^^^^^^^^^^^^^^ + * - `({ *foo() {} })` + * ^^^^ + * - `({ foo: async function foo() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ foo: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^ + * - `({ ['foo']: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `({ async foo() {} })` + * ^^^^^^^^^ + * - `({ get foo() {} })` + * ^^^^^^^ + * - `({ set foo(a) {} })` + * ^^^^^^^ + * - `class A { constructor() {} }` + * ^^^^^^^^^^^ + * - `class A { foo() {} }` + * ^^^ + * - `class A { *foo() {} }` + * ^^^^ + * - `class A { async foo() {} }` + * ^^^^^^^^^ + * - `class A { ['foo']() {} }` + * ^^^^^^^ + * - `class A { *['foo']() {} }` + * ^^^^^^^^ + * - `class A { async ['foo']() {} }` + * ^^^^^^^^^^^^^ + * - `class A { [foo]() {} }` + * ^^^^^ + * - `class A { *[foo]() {} }` + * ^^^^^^ + * - `class A { async [foo]() {} }` + * ^^^^^^^^^^^ + * - `class A { get foo() {} }` + * ^^^^^^^ + * - `class A { set foo(a) {} }` + * ^^^^^^^ + * - `class A { static foo() {} }` + * ^^^^^^^^^^ + * - `class A { static *foo() {} }` + * ^^^^^^^^^^^ + * - `class A { static async foo() {} }` + * ^^^^^^^^^^^^^^^^ + * - `class A { static get foo() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static set foo(a) {} }` + * ^^^^^^^^^^^^^^ + * - `class A { foo = function() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static foo = function() {} }` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `class A { foo = (a, b) => {} }` + * ^^^^^^ + * @param node The function node to get. + * @param sourceCode The source code object to get tokens. + * @returns The location of the function node for reporting. + */ +export declare function getFunctionHeadLoc(node: FunctionNode, sourceCode: TSESLint.SourceCode): TSESTree.SourceLocation; +export {}; +//# sourceMappingURL=getFunctionHeadLoc.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFunctionHeadLoc.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFunctionHeadLoc.d.ts.map new file mode 100644 index 00000000..e2220282 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFunctionHeadLoc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getFunctionHeadLoc.d.ts","sourceRoot":"","sources":["../../src/util/getFunctionHeadLoc.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAMnE,KAAK,YAAY,GACb,QAAQ,CAAC,uBAAuB,GAChC,QAAQ,CAAC,mBAAmB,GAC5B,QAAQ,CAAC,kBAAkB,CAAC;AA2ChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgGG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,YAAY,EAClB,UAAU,EAAE,QAAQ,CAAC,UAAU,GAC9B,QAAQ,CAAC,cAAc,CAiDzB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFunctionHeadLoc.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFunctionHeadLoc.js new file mode 100644 index 00000000..15d2b073 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getFunctionHeadLoc.js @@ -0,0 +1,161 @@ +"use strict"; +// adapted from https://github.com/eslint/eslint/blob/5bdaae205c3a0089ea338b382df59e21d5b06436/lib/rules/utils/ast-utils.js#L1668-L1787 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getFunctionHeadLoc = getFunctionHeadLoc; +const utils_1 = require("@typescript-eslint/utils"); +const astUtils_1 = require("./astUtils"); +/** + * Gets the `(` token of the given function node. + * @param node The function node to get. + * @param sourceCode The source code object to get tokens. + * @returns `(` token. + */ +function getOpeningParenOfParams(node, sourceCode) { + // If the node is an arrow function and doesn't have parens, this returns the identifier of the first param. + if (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + node.params.length === 1) { + const argToken = utils_1.ESLintUtils.nullThrows(sourceCode.getFirstToken(node.params[0]), utils_1.ESLintUtils.NullThrowsReasons.MissingToken('parameter', 'arrow function')); + const maybeParenToken = sourceCode.getTokenBefore(argToken); + return maybeParenToken && (0, astUtils_1.isOpeningParenToken)(maybeParenToken) + ? maybeParenToken + : argToken; + } + // Otherwise, returns paren. + return node.id != null + ? utils_1.ESLintUtils.nullThrows(sourceCode.getTokenAfter(node.id, astUtils_1.isOpeningParenToken), utils_1.ESLintUtils.NullThrowsReasons.MissingToken('id', 'function')) + : utils_1.ESLintUtils.nullThrows(sourceCode.getFirstToken(node, astUtils_1.isOpeningParenToken), utils_1.ESLintUtils.NullThrowsReasons.MissingToken('opening parenthesis', 'function')); +} +/** + * Gets the location of the given function node for reporting. + * + * - `function foo() {}` + * ^^^^^^^^^^^^ + * - `(function foo() {})` + * ^^^^^^^^^^^^ + * - `(function() {})` + * ^^^^^^^^ + * - `function* foo() {}` + * ^^^^^^^^^^^^^ + * - `(function* foo() {})` + * ^^^^^^^^^^^^^ + * - `(function*() {})` + * ^^^^^^^^^ + * - `() => {}` + * ^^ + * - `async () => {}` + * ^^ + * - `({ foo: function foo() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ foo: function() {} })` + * ^^^^^^^^^^^^^ + * - `({ ['foo']: function() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function() {} })` + * ^^^^^^^^^^^^^^^ + * - `({ foo() {} })` + * ^^^ + * - `({ foo: function* foo() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ foo: function*() {} })` + * ^^^^^^^^^^^^^^ + * - `({ ['foo']: function*() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function*() {} })` + * ^^^^^^^^^^^^^^^^ + * - `({ *foo() {} })` + * ^^^^ + * - `({ foo: async function foo() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ foo: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^ + * - `({ ['foo']: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `({ async foo() {} })` + * ^^^^^^^^^ + * - `({ get foo() {} })` + * ^^^^^^^ + * - `({ set foo(a) {} })` + * ^^^^^^^ + * - `class A { constructor() {} }` + * ^^^^^^^^^^^ + * - `class A { foo() {} }` + * ^^^ + * - `class A { *foo() {} }` + * ^^^^ + * - `class A { async foo() {} }` + * ^^^^^^^^^ + * - `class A { ['foo']() {} }` + * ^^^^^^^ + * - `class A { *['foo']() {} }` + * ^^^^^^^^ + * - `class A { async ['foo']() {} }` + * ^^^^^^^^^^^^^ + * - `class A { [foo]() {} }` + * ^^^^^ + * - `class A { *[foo]() {} }` + * ^^^^^^ + * - `class A { async [foo]() {} }` + * ^^^^^^^^^^^ + * - `class A { get foo() {} }` + * ^^^^^^^ + * - `class A { set foo(a) {} }` + * ^^^^^^^ + * - `class A { static foo() {} }` + * ^^^^^^^^^^ + * - `class A { static *foo() {} }` + * ^^^^^^^^^^^ + * - `class A { static async foo() {} }` + * ^^^^^^^^^^^^^^^^ + * - `class A { static get foo() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static set foo(a) {} }` + * ^^^^^^^^^^^^^^ + * - `class A { foo = function() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static foo = function() {} }` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `class A { foo = (a, b) => {} }` + * ^^^^^^ + * @param node The function node to get. + * @param sourceCode The source code object to get tokens. + * @returns The location of the function node for reporting. + */ +function getFunctionHeadLoc(node, sourceCode) { + const parent = node.parent; + let start = null; + let end = null; + if (parent.type === utils_1.AST_NODE_TYPES.MethodDefinition || + parent.type === utils_1.AST_NODE_TYPES.PropertyDefinition) { + // the decorator's range is included within the member + // however it's usually irrelevant to the member itself - so we don't want + // to highlight it ever. + if (parent.decorators.length > 0) { + const lastDecorator = parent.decorators[parent.decorators.length - 1]; + const firstTokenAfterDecorator = utils_1.ESLintUtils.nullThrows(sourceCode.getTokenAfter(lastDecorator), utils_1.ESLintUtils.NullThrowsReasons.MissingToken('modifier or member name', 'class member')); + start = firstTokenAfterDecorator.loc.start; + } + else { + start = parent.loc.start; + } + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + else if (parent.type === utils_1.AST_NODE_TYPES.Property) { + start = parent.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + else if (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression) { + const arrowToken = utils_1.ESLintUtils.nullThrows(sourceCode.getTokenBefore(node.body, astUtils_1.isArrowToken), utils_1.ESLintUtils.NullThrowsReasons.MissingToken('arrow token', 'arrow function')); + start = arrowToken.loc.start; + end = arrowToken.loc.end; + } + else { + start = node.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + return { + end: { ...end }, + start: { ...start }, + }; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getMemberHeadLoc.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getMemberHeadLoc.d.ts new file mode 100644 index 00000000..acdc4c6d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getMemberHeadLoc.d.ts @@ -0,0 +1,37 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +/** + * Generates report loc suitable for reporting on how a class member is + * declared, rather than how it's implemented. + * + * ```ts + * class A { + * abstract method(): void; + * ~~~~~~~~~~~~~~~ + * + * concreteMethod(): void { + * ~~~~~~~~~~~~~~ + * // code + * } + * + * abstract private property?: string; + * ~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * @decorator override concreteProperty = 'value'; + * ~~~~~~~~~~~~~~~~~~~~~~~~~ + * } + * ``` + */ +export declare function getMemberHeadLoc(sourceCode: Readonly, node: TSESTree.AccessorProperty | TSESTree.MethodDefinition | TSESTree.PropertyDefinition | TSESTree.TSAbstractAccessorProperty | TSESTree.TSAbstractMethodDefinition | TSESTree.TSAbstractPropertyDefinition): TSESTree.SourceLocation; +/** + * Generates report loc suitable for reporting on how a parameter property is + * declared. + * + * ```ts + * class A { + * constructor(private property: string = 'value') { + * ~~~~~~~~~~~~~~~~ + * } + * ``` + */ +export declare function getParameterPropertyHeadLoc(sourceCode: Readonly, node: TSESTree.TSParameterProperty, nodeName: string): TSESTree.SourceLocation; +//# sourceMappingURL=getMemberHeadLoc.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getMemberHeadLoc.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getMemberHeadLoc.d.ts.map new file mode 100644 index 00000000..d13b3794 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getMemberHeadLoc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getMemberHeadLoc.d.ts","sourceRoot":"","sources":["../../src/util/getMemberHeadLoc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAOnE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,EAAE,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,EACzC,IAAI,EACA,QAAQ,CAAC,gBAAgB,GACzB,QAAQ,CAAC,gBAAgB,GACzB,QAAQ,CAAC,kBAAkB,GAC3B,QAAQ,CAAC,0BAA0B,GACnC,QAAQ,CAAC,0BAA0B,GACnC,QAAQ,CAAC,4BAA4B,GACxC,QAAQ,CAAC,cAAc,CA8BzB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,2BAA2B,CACzC,UAAU,EAAE,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,EACzC,IAAI,EAAE,QAAQ,CAAC,mBAAmB,EAClC,QAAQ,EAAE,MAAM,GACf,QAAQ,CAAC,cAAc,CAyBzB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getMemberHeadLoc.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getMemberHeadLoc.js new file mode 100644 index 00000000..8b0f1776 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getMemberHeadLoc.js @@ -0,0 +1,79 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMemberHeadLoc = getMemberHeadLoc; +exports.getParameterPropertyHeadLoc = getParameterPropertyHeadLoc; +const eslint_utils_1 = require("@typescript-eslint/utils/eslint-utils"); +/** + * Generates report loc suitable for reporting on how a class member is + * declared, rather than how it's implemented. + * + * ```ts + * class A { + * abstract method(): void; + * ~~~~~~~~~~~~~~~ + * + * concreteMethod(): void { + * ~~~~~~~~~~~~~~ + * // code + * } + * + * abstract private property?: string; + * ~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * @decorator override concreteProperty = 'value'; + * ~~~~~~~~~~~~~~~~~~~~~~~~~ + * } + * ``` + */ +function getMemberHeadLoc(sourceCode, node) { + let start; + if (node.decorators.length === 0) { + start = node.loc.start; + } + else { + const lastDecorator = node.decorators[node.decorators.length - 1]; + const nextToken = (0, eslint_utils_1.nullThrows)(sourceCode.getTokenAfter(lastDecorator), eslint_utils_1.NullThrowsReasons.MissingToken('token', 'last decorator')); + start = nextToken.loc.start; + } + let end; + if (!node.computed) { + end = node.key.loc.end; + } + else { + const closingBracket = (0, eslint_utils_1.nullThrows)(sourceCode.getTokenAfter(node.key, token => token.value === ']'), eslint_utils_1.NullThrowsReasons.MissingToken(']', node.type)); + end = closingBracket.loc.end; + } + return { + end: structuredClone(end), + start: structuredClone(start), + }; +} +/** + * Generates report loc suitable for reporting on how a parameter property is + * declared. + * + * ```ts + * class A { + * constructor(private property: string = 'value') { + * ~~~~~~~~~~~~~~~~ + * } + * ``` + */ +function getParameterPropertyHeadLoc(sourceCode, node, nodeName) { + // Parameter properties have a weirdly different AST structure + // than other class members. + let start; + if (node.decorators.length === 0) { + start = structuredClone(node.loc.start); + } + else { + const lastDecorator = node.decorators[node.decorators.length - 1]; + const nextToken = (0, eslint_utils_1.nullThrows)(sourceCode.getTokenAfter(lastDecorator), eslint_utils_1.NullThrowsReasons.MissingToken('token', 'last decorator')); + start = structuredClone(nextToken.loc.start); + } + const end = sourceCode.getLocFromIndex(node.parameter.range[0] + nodeName.length); + return { + end, + start, + }; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getOperatorPrecedence.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getOperatorPrecedence.d.ts new file mode 100644 index 00000000..ca048414 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getOperatorPrecedence.d.ts @@ -0,0 +1,36 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import { SyntaxKind } from 'typescript'; +import type { ValueOf } from './types'; +export declare enum OperatorPrecedence { + Comma = 0, + Spread = 1, + Yield = 2, + Assignment = 3, + Conditional = 4, + Coalesce = 4,// NOTE: This is wrong + LogicalOR = 5, + LogicalAND = 6, + BitwiseOR = 7, + BitwiseXOR = 8, + BitwiseAND = 9, + Equality = 10, + Relational = 11, + Shift = 12, + Additive = 13, + Multiplicative = 14, + Exponentiation = 15, + Unary = 16, + Update = 17, + LeftHandSide = 18, + Member = 19, + Primary = 20, + Highest = 20, + Lowest = 0, + Invalid = -1 +} +export declare function getOperatorPrecedenceForNode(node: TSESTree.Node): OperatorPrecedence; +type TSESTreeOperatorKind = ValueOf | ValueOf; +export declare function getOperatorPrecedence(nodeKind: SyntaxKind, operatorKind: SyntaxKind, hasArguments?: boolean): OperatorPrecedence; +export declare function getBinaryOperatorPrecedence(kind: SyntaxKind | TSESTreeOperatorKind): OperatorPrecedence; +export {}; +//# sourceMappingURL=getOperatorPrecedence.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getOperatorPrecedence.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getOperatorPrecedence.d.ts.map new file mode 100644 index 00000000..10330839 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getOperatorPrecedence.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getOperatorPrecedence.d.ts","sourceRoot":"","sources":["../../src/util/getOperatorPrecedence.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAGzD,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAEvC,oBAAY,kBAAkB;IAI5B,KAAK,IAAA;IAKL,MAAM,IAAA;IAkBN,KAAK,IAAA;IAML,UAAU,IAAA;IAWV,WAAW,IAAA;IAOX,QAAQ,IAAc,CAAE,sBAAsB;IAK9C,SAAS,IAAA;IAKT,UAAU,IAAA;IAKV,SAAS,IAAA;IAKT,UAAU,IAAA;IAKV,UAAU,IAAA;IAQV,QAAQ,KAAA;IAWR,UAAU,KAAA;IAOV,KAAK,KAAA;IAML,QAAQ,KAAA;IAMR,cAAc,KAAA;IAKd,cAAc,KAAA;IAed,KAAK,KAAA;IAML,MAAM,KAAA;IAQN,YAAY,KAAA;IAkBZ,MAAM,KAAA;IAiBN,OAAO,KAAA;IAEP,OAAO,KAAU;IACjB,MAAM,IAAQ;IAGd,OAAO,KAAK;CACb;AAED,wBAAgB,4BAA4B,CAC1C,IAAI,EAAE,QAAQ,CAAC,IAAI,GAClB,kBAAkB,CA8FpB;AAED,KAAK,oBAAoB,GACrB,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAC,GACtC,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;AAE5C,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,UAAU,EACpB,YAAY,EAAE,UAAU,EACxB,YAAY,CAAC,EAAE,OAAO,GACrB,kBAAkB,CAqGpB;AAED,wBAAgB,2BAA2B,CACzC,IAAI,EAAE,UAAU,GAAG,oBAAoB,GACtC,kBAAkB,CAkFpB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getOperatorPrecedence.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getOperatorPrecedence.js new file mode 100644 index 00000000..13e1e03a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getOperatorPrecedence.js @@ -0,0 +1,417 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OperatorPrecedence = void 0; +exports.getOperatorPrecedenceForNode = getOperatorPrecedenceForNode; +exports.getOperatorPrecedence = getOperatorPrecedence; +exports.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; +const utils_1 = require("@typescript-eslint/utils"); +const typescript_1 = require("typescript"); +var OperatorPrecedence; +(function (OperatorPrecedence) { + // Expression: + // AssignmentExpression + // Expression `,` AssignmentExpression + OperatorPrecedence[OperatorPrecedence["Comma"] = 0] = "Comma"; + // NOTE: `Spread` is higher than `Comma` due to how it is parsed in |ElementList| + // SpreadElement: + // `...` AssignmentExpression + OperatorPrecedence[OperatorPrecedence["Spread"] = 1] = "Spread"; + // AssignmentExpression: + // ConditionalExpression + // YieldExpression + // ArrowFunction + // AsyncArrowFunction + // LeftHandSideExpression `=` AssignmentExpression + // LeftHandSideExpression AssignmentOperator AssignmentExpression + // + // NOTE: AssignmentExpression is broken down into several precedences due to the requirements + // of the parenthesize rules. + // AssignmentExpression: YieldExpression + // YieldExpression: + // `yield` + // `yield` AssignmentExpression + // `yield` `*` AssignmentExpression + OperatorPrecedence[OperatorPrecedence["Yield"] = 2] = "Yield"; + // AssignmentExpression: LeftHandSideExpression `=` AssignmentExpression + // AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression + // AssignmentOperator: one of + // `*=` `/=` `%=` `+=` `-=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` `**=` + OperatorPrecedence[OperatorPrecedence["Assignment"] = 3] = "Assignment"; + // NOTE: `Conditional` is considered higher than `Assignment` here, but in reality they have + // the same precedence. + // AssignmentExpression: ConditionalExpression + // ConditionalExpression: + // ShortCircuitExpression + // ShortCircuitExpression `?` AssignmentExpression `:` AssignmentExpression + // ShortCircuitExpression: + // LogicalORExpression + // CoalesceExpression + OperatorPrecedence[OperatorPrecedence["Conditional"] = 4] = "Conditional"; + // CoalesceExpression: + // CoalesceExpressionHead `??` BitwiseORExpression + // CoalesceExpressionHead: + // CoalesceExpression + // BitwiseORExpression + OperatorPrecedence[OperatorPrecedence["Coalesce"] = 4] = "Coalesce"; + // LogicalORExpression: + // LogicalANDExpression + // LogicalORExpression `||` LogicalANDExpression + OperatorPrecedence[OperatorPrecedence["LogicalOR"] = 5] = "LogicalOR"; + // LogicalANDExpression: + // BitwiseORExpression + // LogicalANDExpression `&&` BitwiseORExpression + OperatorPrecedence[OperatorPrecedence["LogicalAND"] = 6] = "LogicalAND"; + // BitwiseORExpression: + // BitwiseXORExpression + // BitwiseORExpression `^` BitwiseXORExpression + OperatorPrecedence[OperatorPrecedence["BitwiseOR"] = 7] = "BitwiseOR"; + // BitwiseXORExpression: + // BitwiseANDExpression + // BitwiseXORExpression `^` BitwiseANDExpression + OperatorPrecedence[OperatorPrecedence["BitwiseXOR"] = 8] = "BitwiseXOR"; + // BitwiseANDExpression: + // EqualityExpression + // BitwiseANDExpression `^` EqualityExpression + OperatorPrecedence[OperatorPrecedence["BitwiseAND"] = 9] = "BitwiseAND"; + // EqualityExpression: + // RelationalExpression + // EqualityExpression `==` RelationalExpression + // EqualityExpression `!=` RelationalExpression + // EqualityExpression `===` RelationalExpression + // EqualityExpression `!==` RelationalExpression + OperatorPrecedence[OperatorPrecedence["Equality"] = 10] = "Equality"; + // RelationalExpression: + // ShiftExpression + // RelationalExpression `<` ShiftExpression + // RelationalExpression `>` ShiftExpression + // RelationalExpression `<=` ShiftExpression + // RelationalExpression `>=` ShiftExpression + // RelationalExpression `instanceof` ShiftExpression + // RelationalExpression `in` ShiftExpression + // [+TypeScript] RelationalExpression `as` Type + OperatorPrecedence[OperatorPrecedence["Relational"] = 11] = "Relational"; + // ShiftExpression: + // AdditiveExpression + // ShiftExpression `<<` AdditiveExpression + // ShiftExpression `>>` AdditiveExpression + // ShiftExpression `>>>` AdditiveExpression + OperatorPrecedence[OperatorPrecedence["Shift"] = 12] = "Shift"; + // AdditiveExpression: + // MultiplicativeExpression + // AdditiveExpression `+` MultiplicativeExpression + // AdditiveExpression `-` MultiplicativeExpression + OperatorPrecedence[OperatorPrecedence["Additive"] = 13] = "Additive"; + // MultiplicativeExpression: + // ExponentiationExpression + // MultiplicativeExpression MultiplicativeOperator ExponentiationExpression + // MultiplicativeOperator: one of `*`, `/`, `%` + OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 14] = "Multiplicative"; + // ExponentiationExpression: + // UnaryExpression + // UpdateExpression `**` ExponentiationExpression + OperatorPrecedence[OperatorPrecedence["Exponentiation"] = 15] = "Exponentiation"; + // UnaryExpression: + // UpdateExpression + // `delete` UnaryExpression + // `void` UnaryExpression + // `typeof` UnaryExpression + // `+` UnaryExpression + // `-` UnaryExpression + // `~` UnaryExpression + // `!` UnaryExpression + // AwaitExpression + // UpdateExpression: // TODO: Do we need to investigate the precedence here? + // `++` UnaryExpression + // `--` UnaryExpression + OperatorPrecedence[OperatorPrecedence["Unary"] = 16] = "Unary"; + // UpdateExpression: + // LeftHandSideExpression + // LeftHandSideExpression `++` + // LeftHandSideExpression `--` + OperatorPrecedence[OperatorPrecedence["Update"] = 17] = "Update"; + // LeftHandSideExpression: + // NewExpression + // CallExpression + // NewExpression: + // MemberExpression + // `new` NewExpression + OperatorPrecedence[OperatorPrecedence["LeftHandSide"] = 18] = "LeftHandSide"; + // CallExpression: + // CoverCallExpressionAndAsyncArrowHead + // SuperCall + // ImportCall + // CallExpression Arguments + // CallExpression `[` Expression `]` + // CallExpression `.` IdentifierName + // CallExpression TemplateLiteral + // MemberExpression: + // PrimaryExpression + // MemberExpression `[` Expression `]` + // MemberExpression `.` IdentifierName + // MemberExpression TemplateLiteral + // SuperProperty + // MetaProperty + // `new` MemberExpression Arguments + OperatorPrecedence[OperatorPrecedence["Member"] = 19] = "Member"; + // TODO: JSXElement? + // PrimaryExpression: + // `this` + // IdentifierReference + // Literal + // ArrayLiteral + // ObjectLiteral + // FunctionExpression + // ClassExpression + // GeneratorExpression + // AsyncFunctionExpression + // AsyncGeneratorExpression + // RegularExpressionLiteral + // TemplateLiteral + // CoverParenthesizedExpressionAndArrowParameterList + OperatorPrecedence[OperatorPrecedence["Primary"] = 20] = "Primary"; + OperatorPrecedence[OperatorPrecedence["Highest"] = 20] = "Highest"; + OperatorPrecedence[OperatorPrecedence["Lowest"] = 0] = "Lowest"; + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + OperatorPrecedence[OperatorPrecedence["Invalid"] = -1] = "Invalid"; +})(OperatorPrecedence || (exports.OperatorPrecedence = OperatorPrecedence = {})); +function getOperatorPrecedenceForNode(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.SpreadElement: + case utils_1.AST_NODE_TYPES.RestElement: + return OperatorPrecedence.Spread; + case utils_1.AST_NODE_TYPES.YieldExpression: + case utils_1.AST_NODE_TYPES.ArrowFunctionExpression: + return OperatorPrecedence.Yield; + case utils_1.AST_NODE_TYPES.ConditionalExpression: + return OperatorPrecedence.Conditional; + case utils_1.AST_NODE_TYPES.SequenceExpression: + return OperatorPrecedence.Comma; + case utils_1.AST_NODE_TYPES.AssignmentExpression: + case utils_1.AST_NODE_TYPES.BinaryExpression: + case utils_1.AST_NODE_TYPES.LogicalExpression: + switch (node.operator) { + case '==': + case '+=': + case '-=': + case '**=': + case '*=': + case '/=': + case '%=': + case '<<=': + case '>>=': + case '>>>=': + case '&=': + case '^=': + case '|=': + case '||=': + case '&&=': + case '??=': + return OperatorPrecedence.Assignment; + default: + return getBinaryOperatorPrecedence(node.operator); + } + case utils_1.AST_NODE_TYPES.TSTypeAssertion: + case utils_1.AST_NODE_TYPES.TSNonNullExpression: + case utils_1.AST_NODE_TYPES.UnaryExpression: + case utils_1.AST_NODE_TYPES.AwaitExpression: + return OperatorPrecedence.Unary; + case utils_1.AST_NODE_TYPES.UpdateExpression: + // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? + if (node.prefix) { + return OperatorPrecedence.Unary; + } + return OperatorPrecedence.Update; + case utils_1.AST_NODE_TYPES.ChainExpression: + return getOperatorPrecedenceForNode(node.expression); + case utils_1.AST_NODE_TYPES.CallExpression: + return OperatorPrecedence.LeftHandSide; + case utils_1.AST_NODE_TYPES.NewExpression: + return node.arguments.length > 0 + ? OperatorPrecedence.Member + : OperatorPrecedence.LeftHandSide; + case utils_1.AST_NODE_TYPES.TaggedTemplateExpression: + case utils_1.AST_NODE_TYPES.MemberExpression: + case utils_1.AST_NODE_TYPES.MetaProperty: + return OperatorPrecedence.Member; + case utils_1.AST_NODE_TYPES.TSAsExpression: + return OperatorPrecedence.Relational; + case utils_1.AST_NODE_TYPES.ThisExpression: + case utils_1.AST_NODE_TYPES.Super: + case utils_1.AST_NODE_TYPES.Identifier: + case utils_1.AST_NODE_TYPES.PrivateIdentifier: + case utils_1.AST_NODE_TYPES.Literal: + case utils_1.AST_NODE_TYPES.ArrayExpression: + case utils_1.AST_NODE_TYPES.ObjectExpression: + case utils_1.AST_NODE_TYPES.FunctionExpression: + case utils_1.AST_NODE_TYPES.ClassExpression: + case utils_1.AST_NODE_TYPES.TemplateLiteral: + case utils_1.AST_NODE_TYPES.JSXElement: + case utils_1.AST_NODE_TYPES.JSXFragment: + // we don't have nodes for these cases + // case SyntaxKind.ParenthesizedExpression: + // case SyntaxKind.OmittedExpression: + return OperatorPrecedence.Primary; + default: + return OperatorPrecedence.Invalid; + } +} +function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + // A list of comma-separated expressions. This node is only created by transformations. + case typescript_1.SyntaxKind.CommaListExpression: + return OperatorPrecedence.Comma; + case typescript_1.SyntaxKind.SpreadElement: + return OperatorPrecedence.Spread; + case typescript_1.SyntaxKind.YieldExpression: + return OperatorPrecedence.Yield; + case typescript_1.SyntaxKind.ConditionalExpression: + return OperatorPrecedence.Conditional; + case typescript_1.SyntaxKind.BinaryExpression: + switch (operatorKind) { + case typescript_1.SyntaxKind.AmpersandAmpersandEqualsToken: + case typescript_1.SyntaxKind.AmpersandEqualsToken: + case typescript_1.SyntaxKind.AsteriskAsteriskEqualsToken: + case typescript_1.SyntaxKind.AsteriskEqualsToken: + case typescript_1.SyntaxKind.BarBarEqualsToken: + case typescript_1.SyntaxKind.BarEqualsToken: + case typescript_1.SyntaxKind.CaretEqualsToken: + case typescript_1.SyntaxKind.EqualsToken: + case typescript_1.SyntaxKind.GreaterThanGreaterThanEqualsToken: + case typescript_1.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: + case typescript_1.SyntaxKind.LessThanLessThanEqualsToken: + case typescript_1.SyntaxKind.MinusEqualsToken: + case typescript_1.SyntaxKind.PercentEqualsToken: + case typescript_1.SyntaxKind.PlusEqualsToken: + case typescript_1.SyntaxKind.QuestionQuestionEqualsToken: + case typescript_1.SyntaxKind.SlashEqualsToken: + return OperatorPrecedence.Assignment; + case typescript_1.SyntaxKind.CommaToken: + return OperatorPrecedence.Comma; + default: + return getBinaryOperatorPrecedence(operatorKind); + } + // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? + case typescript_1.SyntaxKind.TypeAssertionExpression: + case typescript_1.SyntaxKind.NonNullExpression: + case typescript_1.SyntaxKind.PrefixUnaryExpression: + case typescript_1.SyntaxKind.TypeOfExpression: + case typescript_1.SyntaxKind.VoidExpression: + case typescript_1.SyntaxKind.DeleteExpression: + case typescript_1.SyntaxKind.AwaitExpression: + return OperatorPrecedence.Unary; + case typescript_1.SyntaxKind.PostfixUnaryExpression: + return OperatorPrecedence.Update; + case typescript_1.SyntaxKind.CallExpression: + return OperatorPrecedence.LeftHandSide; + case typescript_1.SyntaxKind.NewExpression: + return hasArguments + ? OperatorPrecedence.Member + : OperatorPrecedence.LeftHandSide; + case typescript_1.SyntaxKind.TaggedTemplateExpression: + case typescript_1.SyntaxKind.PropertyAccessExpression: + case typescript_1.SyntaxKind.ElementAccessExpression: + case typescript_1.SyntaxKind.MetaProperty: + return OperatorPrecedence.Member; + case typescript_1.SyntaxKind.AsExpression: + case typescript_1.SyntaxKind.SatisfiesExpression: + return OperatorPrecedence.Relational; + case typescript_1.SyntaxKind.ThisKeyword: + case typescript_1.SyntaxKind.SuperKeyword: + case typescript_1.SyntaxKind.Identifier: + case typescript_1.SyntaxKind.PrivateIdentifier: + case typescript_1.SyntaxKind.NullKeyword: + case typescript_1.SyntaxKind.TrueKeyword: + case typescript_1.SyntaxKind.FalseKeyword: + case typescript_1.SyntaxKind.NumericLiteral: + case typescript_1.SyntaxKind.BigIntLiteral: + case typescript_1.SyntaxKind.StringLiteral: + case typescript_1.SyntaxKind.ArrayLiteralExpression: + case typescript_1.SyntaxKind.ObjectLiteralExpression: + case typescript_1.SyntaxKind.FunctionExpression: + case typescript_1.SyntaxKind.ArrowFunction: + case typescript_1.SyntaxKind.ClassExpression: + case typescript_1.SyntaxKind.RegularExpressionLiteral: + case typescript_1.SyntaxKind.NoSubstitutionTemplateLiteral: + case typescript_1.SyntaxKind.TemplateExpression: + case typescript_1.SyntaxKind.ParenthesizedExpression: + case typescript_1.SyntaxKind.OmittedExpression: + case typescript_1.SyntaxKind.JsxElement: + case typescript_1.SyntaxKind.JsxSelfClosingElement: + case typescript_1.SyntaxKind.JsxFragment: + return OperatorPrecedence.Primary; + default: + return OperatorPrecedence.Invalid; + } +} +function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case '-': + case '+': + case typescript_1.SyntaxKind.MinusToken: + case typescript_1.SyntaxKind.PlusToken: + return OperatorPrecedence.Additive; + case '!=': + case '!==': + case '==': + case '===': + case typescript_1.SyntaxKind.EqualsEqualsEqualsToken: + case typescript_1.SyntaxKind.EqualsEqualsToken: + case typescript_1.SyntaxKind.ExclamationEqualsEqualsToken: + case typescript_1.SyntaxKind.ExclamationEqualsToken: + return OperatorPrecedence.Equality; + case '??': + case typescript_1.SyntaxKind.QuestionQuestionToken: + return OperatorPrecedence.Coalesce; + case '*': + case '/': + case '%': + case typescript_1.SyntaxKind.AsteriskToken: + case typescript_1.SyntaxKind.PercentToken: + case typescript_1.SyntaxKind.SlashToken: + return OperatorPrecedence.Multiplicative; + case '**': + case typescript_1.SyntaxKind.AsteriskAsteriskToken: + return OperatorPrecedence.Exponentiation; + case '&': + case typescript_1.SyntaxKind.AmpersandToken: + return OperatorPrecedence.BitwiseAND; + case '&&': + case typescript_1.SyntaxKind.AmpersandAmpersandToken: + return OperatorPrecedence.LogicalAND; + case '^': + case typescript_1.SyntaxKind.CaretToken: + return OperatorPrecedence.BitwiseXOR; + case '<': + case '<=': + case '>': + case '>=': + case 'in': + case 'instanceof': + case typescript_1.SyntaxKind.AsKeyword: + case typescript_1.SyntaxKind.GreaterThanEqualsToken: + case typescript_1.SyntaxKind.GreaterThanToken: + case typescript_1.SyntaxKind.InKeyword: + case typescript_1.SyntaxKind.InstanceOfKeyword: + case typescript_1.SyntaxKind.LessThanEqualsToken: + case typescript_1.SyntaxKind.LessThanToken: + // case 'as': -- we don't have a token for this + return OperatorPrecedence.Relational; + case '<<': + case '>>': + case '>>>': + case typescript_1.SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + case typescript_1.SyntaxKind.GreaterThanGreaterThanToken: + case typescript_1.SyntaxKind.LessThanLessThanToken: + return OperatorPrecedence.Shift; + case '|': + case typescript_1.SyntaxKind.BarToken: + return OperatorPrecedence.BitwiseOR; + case '||': + case typescript_1.SyntaxKind.BarBarToken: + return OperatorPrecedence.LogicalOR; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getParentFunctionNode.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getParentFunctionNode.d.ts new file mode 100644 index 00000000..ae5713b4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getParentFunctionNode.d.ts @@ -0,0 +1,3 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +export declare function getParentFunctionNode(node: TSESTree.Node): TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | null; +//# sourceMappingURL=getParentFunctionNode.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getParentFunctionNode.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getParentFunctionNode.d.ts.map new file mode 100644 index 00000000..4c8c2361 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getParentFunctionNode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getParentFunctionNode.d.ts","sourceRoot":"","sources":["../../src/util/getParentFunctionNode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,QAAQ,CAAC,IAAI,GAEjB,QAAQ,CAAC,uBAAuB,GAChC,QAAQ,CAAC,mBAAmB,GAC5B,QAAQ,CAAC,kBAAkB,GAC3B,IAAI,CAiBP"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getParentFunctionNode.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getParentFunctionNode.js new file mode 100644 index 00000000..fba2413c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getParentFunctionNode.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getParentFunctionNode = getParentFunctionNode; +const utils_1 = require("@typescript-eslint/utils"); +function getParentFunctionNode(node) { + let current = node.parent; + while (current) { + if (current.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression || + current.type === utils_1.AST_NODE_TYPES.FunctionDeclaration || + current.type === utils_1.AST_NODE_TYPES.FunctionExpression) { + return current; + } + current = current.parent; + } + // this shouldn't happen in correct code, but someone may attempt to parse bad code + // the parser won't error, so we shouldn't throw here + /* istanbul ignore next */ return null; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStaticStringValue.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStaticStringValue.d.ts new file mode 100644 index 00000000..660ac246 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStaticStringValue.d.ts @@ -0,0 +1,12 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +/** + * Returns the result of the string conversion applied to the evaluated value of the given expression node, + * if it can be determined statically. + * + * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only. + * In all other cases, this function returns `null`. + * @param node Expression node. + * @returns String value if it can be determined. Otherwise, `null`. + */ +export declare function getStaticStringValue(node: TSESTree.Node): string | null; +//# sourceMappingURL=getStaticStringValue.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStaticStringValue.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStaticStringValue.d.ts.map new file mode 100644 index 00000000..bc45f3d5 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStaticStringValue.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getStaticStringValue.d.ts","sourceRoot":"","sources":["../../src/util/getStaticStringValue.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAMzD;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,GAAG,MAAM,GAAG,IAAI,CAgCvE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStaticStringValue.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStaticStringValue.js new file mode 100644 index 00000000..e7ecd11d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStaticStringValue.js @@ -0,0 +1,44 @@ +"use strict"; +// adapted from https://github.com/eslint/eslint/blob/5bdaae205c3a0089ea338b382df59e21d5b06436/lib/rules/utils/ast-utils.js#L191-L230 +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getStaticStringValue = getStaticStringValue; +const utils_1 = require("@typescript-eslint/utils"); +const isNullLiteral_1 = require("./isNullLiteral"); +/** + * Returns the result of the string conversion applied to the evaluated value of the given expression node, + * if it can be determined statically. + * + * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only. + * In all other cases, this function returns `null`. + * @param node Expression node. + * @returns String value if it can be determined. Otherwise, `null`. + */ +function getStaticStringValue(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.Literal: + // eslint-disable-next-line eqeqeq, @typescript-eslint/internal/eqeq-nullish -- intentional strict comparison for literal value + if (node.value === null) { + if ((0, isNullLiteral_1.isNullLiteral)(node)) { + return String(node.value); // "null" + } + if ('regex' in node) { + return `/${node.regex.pattern}/${node.regex.flags}`; + } + if ('bigint' in node) { + return node.bigint; + } + // Otherwise, this is an unknown literal. The function will return null. + } + else { + return String(node.value); + } + break; + case utils_1.AST_NODE_TYPES.TemplateLiteral: + if (node.expressions.length === 0 && node.quasis.length === 1) { + return node.quasis[0].value.cooked; + } + break; + // no default + } + return null; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStringLength.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStringLength.d.ts new file mode 100644 index 00000000..5f7ed590 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStringLength.d.ts @@ -0,0 +1,2 @@ +export declare function getStringLength(value: string): number; +//# sourceMappingURL=getStringLength.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStringLength.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStringLength.d.ts.map new file mode 100644 index 00000000..fc912d93 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStringLength.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getStringLength.d.ts","sourceRoot":"","sources":["../../src/util/getStringLength.ts"],"names":[],"mappings":"AAQA,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAQrD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStringLength.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStringLength.js new file mode 100644 index 00000000..c65dc7e9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getStringLength.js @@ -0,0 +1,18 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getStringLength = getStringLength; +const graphemer_1 = __importDefault(require("graphemer")); +let splitter; +function isASCII(value) { + return /^[\u0020-\u007f]*$/u.test(value); +} +function getStringLength(value) { + if (isASCII(value)) { + return value.length; + } + splitter ??= new graphemer_1.default(); + return splitter.countGraphemes(value); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getTextWithParentheses.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getTextWithParentheses.d.ts new file mode 100644 index 00000000..f8e2d1bf --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getTextWithParentheses.d.ts @@ -0,0 +1,4 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { SourceCode } from '@typescript-eslint/utils/ts-eslint'; +export declare function getTextWithParentheses(sourceCode: Readonly, node: TSESTree.Node): string; +//# sourceMappingURL=getTextWithParentheses.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getTextWithParentheses.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getTextWithParentheses.d.ts.map new file mode 100644 index 00000000..caab081a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getTextWithParentheses.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getTextWithParentheses.d.ts","sourceRoot":"","sources":["../../src/util/getTextWithParentheses.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAUrE,wBAAgB,sBAAsB,CACpC,UAAU,EAAE,QAAQ,CAAC,UAAU,CAAC,EAChC,IAAI,EAAE,QAAQ,CAAC,IAAI,GAClB,MAAM,CAoBR"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getTextWithParentheses.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getTextWithParentheses.js new file mode 100644 index 00000000..bcdd7d02 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getTextWithParentheses.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getTextWithParentheses = getTextWithParentheses; +const _1 = require("."); +function getTextWithParentheses(sourceCode, node) { + // Capture parentheses before and after the node + let beforeCount = 0; + let afterCount = 0; + if ((0, _1.isParenthesized)(node, sourceCode)) { + const bodyOpeningParen = (0, _1.nullThrows)(sourceCode.getTokenBefore(node, _1.isOpeningParenToken), _1.NullThrowsReasons.MissingToken('(', 'node')); + const bodyClosingParen = (0, _1.nullThrows)(sourceCode.getTokenAfter(node, _1.isClosingParenToken), _1.NullThrowsReasons.MissingToken(')', 'node')); + beforeCount = node.range[0] - bodyOpeningParen.range[0]; + afterCount = bodyClosingParen.range[1] - node.range[1]; + } + return sourceCode.getText(node, beforeCount, afterCount); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getThisExpression.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getThisExpression.d.ts new file mode 100644 index 00000000..9e41c9d6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getThisExpression.d.ts @@ -0,0 +1,3 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +export declare function getThisExpression(node: TSESTree.Node): TSESTree.ThisExpression | undefined; +//# sourceMappingURL=getThisExpression.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getThisExpression.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getThisExpression.d.ts.map new file mode 100644 index 00000000..668b172f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getThisExpression.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getThisExpression.d.ts","sourceRoot":"","sources":["../../src/util/getThisExpression.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,QAAQ,CAAC,IAAI,GAClB,QAAQ,CAAC,cAAc,GAAG,SAAS,CAgBrC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getThisExpression.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getThisExpression.js new file mode 100644 index 00000000..c0beac14 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getThisExpression.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getThisExpression = getThisExpression; +const utils_1 = require("@typescript-eslint/utils"); +function getThisExpression(node) { + while (true) { + if (node.type === utils_1.AST_NODE_TYPES.CallExpression) { + node = node.callee; + } + else if (node.type === utils_1.AST_NODE_TYPES.ThisExpression) { + return node; + } + else if (node.type === utils_1.AST_NODE_TYPES.MemberExpression) { + node = node.object; + } + else if (node.type === utils_1.AST_NODE_TYPES.ChainExpression) { + node = node.expression; + } + else { + break; + } + } + return; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getValueOfLiteralType.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getValueOfLiteralType.d.ts new file mode 100644 index 00000000..d42b56a0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getValueOfLiteralType.d.ts @@ -0,0 +1,3 @@ +import type * as ts from 'typescript'; +export declare const getValueOfLiteralType: (type: ts.LiteralType) => bigint | number | string; +//# sourceMappingURL=getValueOfLiteralType.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getValueOfLiteralType.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getValueOfLiteralType.d.ts.map new file mode 100644 index 00000000..b7aca83d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getValueOfLiteralType.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getValueOfLiteralType.d.ts","sourceRoot":"","sources":["../../src/util/getValueOfLiteralType.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAYtC,eAAO,MAAM,qBAAqB,GAChC,MAAM,EAAE,CAAC,WAAW,KACnB,MAAM,GAAG,MAAM,GAAG,MAKpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getValueOfLiteralType.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getValueOfLiteralType.js new file mode 100644 index 00000000..7d5889b9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getValueOfLiteralType.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getValueOfLiteralType = void 0; +const valueIsPseudoBigInt = (value) => { + return typeof value === 'object'; +}; +const pseudoBigIntToBigInt = (value) => { + return BigInt((value.negative ? '-' : '') + value.base10Value); +}; +const getValueOfLiteralType = (type) => { + if (valueIsPseudoBigInt(type.value)) { + return pseudoBigIntToBigInt(type.value); + } + return type.value; +}; +exports.getValueOfLiteralType = getValueOfLiteralType; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappedCode.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappedCode.d.ts new file mode 100644 index 00000000..9c2363b4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappedCode.d.ts @@ -0,0 +1,3 @@ +import type { OperatorPrecedence } from './getOperatorPrecedence'; +export declare function getWrappedCode(text: string, nodePrecedence: OperatorPrecedence, parentPrecedence: OperatorPrecedence): string; +//# sourceMappingURL=getWrappedCode.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappedCode.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappedCode.d.ts.map new file mode 100644 index 00000000..65ccee02 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappedCode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getWrappedCode.d.ts","sourceRoot":"","sources":["../../src/util/getWrappedCode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAElE,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,kBAAkB,EAClC,gBAAgB,EAAE,kBAAkB,GACnC,MAAM,CAER"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappedCode.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappedCode.js new file mode 100644 index 00000000..e098b8c9 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappedCode.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getWrappedCode = getWrappedCode; +function getWrappedCode(text, nodePrecedence, parentPrecedence) { + return nodePrecedence > parentPrecedence ? text : `(${text})`; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappingFixer.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappingFixer.d.ts new file mode 100644 index 00000000..329f5a98 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappingFixer.d.ts @@ -0,0 +1,43 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +interface WrappingFixerParams { + /** + * Descendant of `node` we want to preserve. + * Use this to replace some code with another. + * By default it's the node we are modifying (so nothing is removed). + * You can pass multiple nodes as an array. + */ + innerNode?: TSESTree.Node | TSESTree.Node[]; + /** The node we want to modify. */ + node: TSESTree.Node; + /** Source code. */ + sourceCode: Readonly; + /** + * The function which gets the code of the `innerNode` and returns some code around it. + * Receives multiple arguments if there are multiple innerNodes. + * E.g. ``code => `${code} != null` `` + */ + wrap?: (...code: string[]) => string; +} +/** + * Wraps node with some code. Adds parentheses as necessary. + * @returns Fixer which adds the specified code and parens if necessary. + */ +export declare function getWrappingFixer(params: WrappingFixerParams): (fixer: TSESLint.RuleFixer) => TSESLint.RuleFix; +/** + * If the node to be moved and the destination node require parentheses, include parentheses in the node to be moved. + * @param sourceCode Source code of current file + * @param nodeToMove Nodes that need to be moved + * @param destinationNode Final destination node with nodeToMove + * @returns If parentheses are required, code for the nodeToMove node is returned with parentheses at both ends of the code. + */ +export declare function getMovedNodeCode(params: { + destinationNode: TSESTree.Node; + nodeToMove: TSESTree.Node; + sourceCode: Readonly; +}): string; +/** + * Check if a node will always have the same precedence if its parent changes. + */ +export declare function isStrongPrecedenceNode(innerNode: TSESTree.Node): boolean; +export {}; +//# sourceMappingURL=getWrappingFixer.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappingFixer.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappingFixer.d.ts.map new file mode 100644 index 00000000..efa5adcd --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappingFixer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getWrappingFixer.d.ts","sourceRoot":"","sources":["../../src/util/getWrappingFixer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAQnE,UAAU,mBAAmB;IAC3B;;;;;OAKG;IACH,SAAS,CAAC,EAAE,QAAQ,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC5C,kCAAkC;IAClC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC;IACpB,mBAAmB;IACnB,UAAU,EAAE,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IAC1C;;;;OAIG;IACH,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,KAAK,MAAM,CAAC;CACtC;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,mBAAmB,GAC1B,CAAC,KAAK,EAAE,QAAQ,CAAC,SAAS,KAAK,QAAQ,CAAC,OAAO,CA+CjD;AACD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE;IACvC,eAAe,EAAE,QAAQ,CAAC,IAAI,CAAC;IAC/B,UAAU,EAAE,QAAQ,CAAC,IAAI,CAAC;IAC1B,UAAU,EAAE,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;CAC3C,GAAG,MAAM,CAeT;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,QAAQ,CAAC,IAAI,GAAG,OAAO,CAcxE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappingFixer.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappingFixer.js new file mode 100644 index 00000000..68b2c768 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/getWrappingFixer.js @@ -0,0 +1,184 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getWrappingFixer = getWrappingFixer; +exports.getMovedNodeCode = getMovedNodeCode; +exports.isStrongPrecedenceNode = isStrongPrecedenceNode; +const utils_1 = require("@typescript-eslint/utils"); +/** + * Wraps node with some code. Adds parentheses as necessary. + * @returns Fixer which adds the specified code and parens if necessary. + */ +function getWrappingFixer(params) { + const { node, innerNode = node, sourceCode, wrap } = params; + const innerNodes = Array.isArray(innerNode) ? innerNode : [innerNode]; + return (fixer) => { + const innerCodes = innerNodes.map(innerNode => { + let code = sourceCode.getText(innerNode); + /** + * Wrap our node in parens to prevent the following cases: + * - It has a weaker precedence than the code we are wrapping it in + * - It's gotten mistaken as block statement instead of object expression + */ + if (!isStrongPrecedenceNode(innerNode) || + isObjectExpressionInOneLineReturn(node, innerNode)) { + code = `(${code})`; + } + return code; + }); + if (!wrap) { + return fixer.replaceText(node, innerCodes.join('')); + } + // do the wrapping + let code = wrap(...innerCodes); + // check the outer expression's precedence + if (isWeakPrecedenceParent(node) && + // we wrapped the node in some expression which very likely has a different precedence than original wrapped node + // let's wrap the whole expression in parens just in case + !utils_1.ASTUtils.isParenthesized(node, sourceCode)) { + code = `(${code})`; + } + // check if we need to insert semicolon + if (/^[`([]/.test(code) && isMissingSemicolonBefore(node, sourceCode)) { + code = `;${code}`; + } + return fixer.replaceText(node, code); + }; +} +/** + * If the node to be moved and the destination node require parentheses, include parentheses in the node to be moved. + * @param sourceCode Source code of current file + * @param nodeToMove Nodes that need to be moved + * @param destinationNode Final destination node with nodeToMove + * @returns If parentheses are required, code for the nodeToMove node is returned with parentheses at both ends of the code. + */ +function getMovedNodeCode(params) { + const { destinationNode, nodeToMove: existingNode, sourceCode } = params; + const code = sourceCode.getText(existingNode); + if (isStrongPrecedenceNode(existingNode)) { + // Moved node never needs parens + return code; + } + if (!isWeakPrecedenceParent(destinationNode)) { + // Destination would never needs parens, regardless what node moves there + return code; + } + // Parens may be necessary + return `(${code})`; +} +/** + * Check if a node will always have the same precedence if its parent changes. + */ +function isStrongPrecedenceNode(innerNode) { + return (innerNode.type === utils_1.AST_NODE_TYPES.Literal || + innerNode.type === utils_1.AST_NODE_TYPES.Identifier || + innerNode.type === utils_1.AST_NODE_TYPES.TSTypeReference || + innerNode.type === utils_1.AST_NODE_TYPES.TSTypeOperator || + innerNode.type === utils_1.AST_NODE_TYPES.ArrayExpression || + innerNode.type === utils_1.AST_NODE_TYPES.ObjectExpression || + innerNode.type === utils_1.AST_NODE_TYPES.MemberExpression || + innerNode.type === utils_1.AST_NODE_TYPES.CallExpression || + innerNode.type === utils_1.AST_NODE_TYPES.NewExpression || + innerNode.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression || + innerNode.type === utils_1.AST_NODE_TYPES.TSInstantiationExpression); +} +/** + * Check if a node's parent could have different precedence if the node changes. + */ +function isWeakPrecedenceParent(node) { + const parent = node.parent; + if (!parent) { + return false; + } + if (parent.type === utils_1.AST_NODE_TYPES.UpdateExpression || + parent.type === utils_1.AST_NODE_TYPES.UnaryExpression || + parent.type === utils_1.AST_NODE_TYPES.BinaryExpression || + parent.type === utils_1.AST_NODE_TYPES.LogicalExpression || + parent.type === utils_1.AST_NODE_TYPES.ConditionalExpression || + parent.type === utils_1.AST_NODE_TYPES.AwaitExpression) { + return true; + } + if (parent.type === utils_1.AST_NODE_TYPES.MemberExpression && + parent.object === node) { + return true; + } + if ((parent.type === utils_1.AST_NODE_TYPES.CallExpression || + parent.type === utils_1.AST_NODE_TYPES.NewExpression) && + parent.callee === node) { + return true; + } + if (parent.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression && + parent.tag === node) { + return true; + } + return false; +} +/** + * Returns true if a node is at the beginning of expression statement and the statement above doesn't end with semicolon. + * Doesn't check if the node begins with `(`, `[` or `` ` ``. + */ +function isMissingSemicolonBefore(node, sourceCode) { + for (;;) { + // https://github.com/typescript-eslint/typescript-eslint/issues/6225 + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const parent = node.parent; + if (parent.type === utils_1.AST_NODE_TYPES.ExpressionStatement) { + const block = parent.parent; + if (block.type === utils_1.AST_NODE_TYPES.Program || + block.type === utils_1.AST_NODE_TYPES.BlockStatement) { + // parent is an expression statement in a block + const statementIndex = block.body.indexOf(parent); + const previousStatement = block.body[statementIndex - 1]; + if (statementIndex > 0 && + utils_1.ESLintUtils.nullThrows(sourceCode.getLastToken(previousStatement), 'Mismatched semicolon and block').value !== ';') { + return true; + } + } + } + if (!isLeftHandSide(node)) { + return false; + } + node = parent; + } +} +/** + * Checks if a node is LHS of an operator. + */ +function isLeftHandSide(node) { + // https://github.com/typescript-eslint/typescript-eslint/issues/6225 + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const parent = node.parent; + // a++ + if (parent.type === utils_1.AST_NODE_TYPES.UpdateExpression) { + return true; + } + // a + b + if ((parent.type === utils_1.AST_NODE_TYPES.BinaryExpression || + parent.type === utils_1.AST_NODE_TYPES.LogicalExpression || + parent.type === utils_1.AST_NODE_TYPES.AssignmentExpression) && + node === parent.left) { + return true; + } + // a ? b : c + if (parent.type === utils_1.AST_NODE_TYPES.ConditionalExpression && + node === parent.test) { + return true; + } + // a(b) + if (parent.type === utils_1.AST_NODE_TYPES.CallExpression && node === parent.callee) { + return true; + } + // a`b` + if (parent.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression && + node === parent.tag) { + return true; + } + return false; +} +/** + * Checks if a node's parent is arrow function expression and a inner node is object expression + */ +function isObjectExpressionInOneLineReturn(node, innerNode) { + return (node.parent?.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression && + node.parent.body === node && + innerNode.type === utils_1.AST_NODE_TYPES.ObjectExpression); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/hasOverloadSignatures.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/hasOverloadSignatures.d.ts new file mode 100644 index 00000000..9122264f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/hasOverloadSignatures.d.ts @@ -0,0 +1,7 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { RuleContext } from '@typescript-eslint/utils/ts-eslint'; +/** + * @return `true` if the function or method node has overload signatures. + */ +export declare function hasOverloadSignatures(node: TSESTree.FunctionDeclaration | TSESTree.MethodDefinition, context: RuleContext): boolean; +//# sourceMappingURL=hasOverloadSignatures.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/hasOverloadSignatures.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/hasOverloadSignatures.d.ts.map new file mode 100644 index 00000000..64bbe504 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/hasOverloadSignatures.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hasOverloadSignatures.d.ts","sourceRoot":"","sources":["../../src/util/hasOverloadSignatures.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAC;AAMtE;;GAEG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,QAAQ,CAAC,mBAAmB,GAAG,QAAQ,CAAC,gBAAgB,EAC9D,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,GACtC,OAAO,CAqCT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/hasOverloadSignatures.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/hasOverloadSignatures.js new file mode 100644 index 00000000..02117662 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/hasOverloadSignatures.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasOverloadSignatures = hasOverloadSignatures; +const utils_1 = require("@typescript-eslint/utils"); +const misc_1 = require("./misc"); +/** + * @return `true` if the function or method node has overload signatures. + */ +function hasOverloadSignatures(node, context) { + // `export default function () {}` + if (node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration) { + return node.parent.parent.body.some(member => { + return (member.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration && + member.declaration.type === utils_1.AST_NODE_TYPES.TSDeclareFunction); + }); + } + // `export function f() {}` + if (node.parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration) { + return node.parent.parent.body.some(member => { + return (member.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration && + member.declaration?.type === utils_1.AST_NODE_TYPES.TSDeclareFunction && + getFunctionDeclarationName(member.declaration, context) === + getFunctionDeclarationName(node, context)); + }); + } + // either: + // - `function f() {}` + // - `class T { foo() {} }` + const nodeKey = getFunctionDeclarationName(node, context); + return node.parent.body.some(member => { + return ((member.type === utils_1.AST_NODE_TYPES.TSDeclareFunction || + (member.type === utils_1.AST_NODE_TYPES.MethodDefinition && + member.value.body == null)) && + nodeKey === getFunctionDeclarationName(member, context)); + }); +} +function getFunctionDeclarationName(node, context) { + if (node.type === utils_1.AST_NODE_TYPES.FunctionDeclaration || + node.type === utils_1.AST_NODE_TYPES.TSDeclareFunction) { + // For a `FunctionDeclaration` or `TSDeclareFunction` this may be `null` if + // and only if the parent is an `ExportDefaultDeclaration`. + // + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return node.id.name; + } + return (0, misc_1.getStaticMemberAccessValue)(node, context); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.d.ts new file mode 100644 index 00000000..0babc392 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.d.ts @@ -0,0 +1,38 @@ +import { ESLintUtils } from '@typescript-eslint/utils'; +export * from './astUtils'; +export * from './collectUnusedVariables'; +export * from './createRule'; +export * from './getFixOrSuggest'; +export * from './getFunctionHeadLoc'; +export * from './getOperatorPrecedence'; +export * from './getStaticStringValue'; +export * from './getStringLength'; +export * from './getTextWithParentheses'; +export * from './getThisExpression'; +export * from './getWrappingFixer'; +export * from './hasOverloadSignatures'; +export * from './isArrayMethodCallWithPredicate'; +export * from './isAssignee'; +export * from './isNodeEqual'; +export * from './isNullLiteral'; +export * from './isStartOfExpressionStatement'; +export * from './isUndefinedIdentifier'; +export * from './misc'; +export * from './needsPrecedingSemiColon'; +export * from './objectIterators'; +export * from './needsToBeAwaited'; +export * from './scopeUtils'; +export * from './types'; +export * from './getConstraintInfo'; +export * from './getValueOfLiteralType'; +export * from './isHigherPrecedenceThanAwait'; +export * from './skipChainExpression'; +export * from './truthinessUtils'; +export * from '@typescript-eslint/type-utils'; +export declare const applyDefault: typeof ESLintUtils.applyDefault, deepMerge: typeof ESLintUtils.deepMerge, getParserServices: typeof ESLintUtils.getParserServices, isObjectNotArray: typeof ESLintUtils.isObjectNotArray, nullThrows: typeof ESLintUtils.nullThrows, NullThrowsReasons: { + readonly MissingParent: "Expected node to have a parent."; + readonly MissingToken: (token: string, thing: string) => string; +}; +export type InferMessageIdsTypeFromRule = ESLintUtils.InferMessageIdsTypeFromRule; +export type InferOptionsTypeFromRule = ESLintUtils.InferOptionsTypeFromRule; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.d.ts.map new file mode 100644 index 00000000..6807f6d1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/util/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC;AACzC,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,0BAA0B,CAAC;AACzC,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kCAAkC,CAAC;AACjD,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,yBAAyB,CAAC;AACxC,cAAc,QAAQ,CAAC;AACvB,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAGlC,cAAc,+BAA+B,CAAC;AAE9C,eAAO,MACL,YAAY,mCACZ,SAAS,gCACT,iBAAiB,wCACjB,gBAAgB,uCAChB,UAAU,iCACV,iBAAiB;;;CACJ,CAAC;AAChB,MAAM,MAAM,2BAA2B,CAAC,CAAC,IACvC,WAAW,CAAC,2BAA2B,CAAC,CAAC,CAAC,CAAC;AAC7C,MAAM,MAAM,wBAAwB,CAAC,CAAC,IACpC,WAAW,CAAC,wBAAwB,CAAC,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.js new file mode 100644 index 00000000..a852e9b4 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.js @@ -0,0 +1,50 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NullThrowsReasons = exports.nullThrows = exports.isObjectNotArray = exports.getParserServices = exports.deepMerge = exports.applyDefault = void 0; +const utils_1 = require("@typescript-eslint/utils"); +__exportStar(require("./astUtils"), exports); +__exportStar(require("./collectUnusedVariables"), exports); +__exportStar(require("./createRule"), exports); +__exportStar(require("./getFixOrSuggest"), exports); +__exportStar(require("./getFunctionHeadLoc"), exports); +__exportStar(require("./getOperatorPrecedence"), exports); +__exportStar(require("./getStaticStringValue"), exports); +__exportStar(require("./getStringLength"), exports); +__exportStar(require("./getTextWithParentheses"), exports); +__exportStar(require("./getThisExpression"), exports); +__exportStar(require("./getWrappingFixer"), exports); +__exportStar(require("./hasOverloadSignatures"), exports); +__exportStar(require("./isArrayMethodCallWithPredicate"), exports); +__exportStar(require("./isAssignee"), exports); +__exportStar(require("./isNodeEqual"), exports); +__exportStar(require("./isNullLiteral"), exports); +__exportStar(require("./isStartOfExpressionStatement"), exports); +__exportStar(require("./isUndefinedIdentifier"), exports); +__exportStar(require("./misc"), exports); +__exportStar(require("./needsPrecedingSemiColon"), exports); +__exportStar(require("./objectIterators"), exports); +__exportStar(require("./needsToBeAwaited"), exports); +__exportStar(require("./scopeUtils"), exports); +__exportStar(require("./types"), exports); +__exportStar(require("./getConstraintInfo"), exports); +__exportStar(require("./getValueOfLiteralType"), exports); +__exportStar(require("./isHigherPrecedenceThanAwait"), exports); +__exportStar(require("./skipChainExpression"), exports); +__exportStar(require("./truthinessUtils"), exports); +// this is done for convenience - saves migrating all of the old rules +__exportStar(require("@typescript-eslint/type-utils"), exports); +exports.applyDefault = utils_1.ESLintUtils.applyDefault, exports.deepMerge = utils_1.ESLintUtils.deepMerge, exports.getParserServices = utils_1.ESLintUtils.getParserServices, exports.isObjectNotArray = utils_1.ESLintUtils.isObjectNotArray, exports.nullThrows = utils_1.ESLintUtils.nullThrows, exports.NullThrowsReasons = utils_1.ESLintUtils.NullThrowsReasons; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isArrayMethodCallWithPredicate.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isArrayMethodCallWithPredicate.d.ts new file mode 100644 index 00000000..74c60d65 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isArrayMethodCallWithPredicate.d.ts @@ -0,0 +1,4 @@ +import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/utils'; +import type { RuleContext } from '@typescript-eslint/utils/ts-eslint'; +export declare function isArrayMethodCallWithPredicate(context: RuleContext, services: ParserServicesWithTypeInformation, node: TSESTree.CallExpression): boolean; +//# sourceMappingURL=isArrayMethodCallWithPredicate.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isArrayMethodCallWithPredicate.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isArrayMethodCallWithPredicate.d.ts.map new file mode 100644 index 00000000..29f33b28 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isArrayMethodCallWithPredicate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isArrayMethodCallWithPredicate.d.ts","sourceRoot":"","sources":["../../src/util/isArrayMethodCallWithPredicate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EACjC,QAAQ,EACT,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAC;AAkBtE,wBAAgB,8BAA8B,CAC5C,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,EACvC,QAAQ,EAAE,iCAAiC,EAC3C,IAAI,EAAE,QAAQ,CAAC,cAAc,GAC5B,OAAO,CAiBT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isArrayMethodCallWithPredicate.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isArrayMethodCallWithPredicate.js new file mode 100644 index 00000000..12d7f96d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isArrayMethodCallWithPredicate.js @@ -0,0 +1,64 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isArrayMethodCallWithPredicate = isArrayMethodCallWithPredicate; +const type_utils_1 = require("@typescript-eslint/type-utils"); +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const misc_1 = require("./misc"); +const ARRAY_PREDICATE_FUNCTIONS = new Set([ + 'every', + 'filter', + 'find', + 'findIndex', + 'findLast', + 'findLastIndex', + 'some', +]); +function isArrayMethodCallWithPredicate(context, services, node) { + if (node.callee.type !== utils_1.AST_NODE_TYPES.MemberExpression) { + return false; + } + const staticAccessValue = (0, misc_1.getStaticMemberAccessValue)(node.callee, context); + if (!ARRAY_PREDICATE_FUNCTIONS.has(staticAccessValue)) { + return false; + } + const checker = services.program.getTypeChecker(); + const type = (0, type_utils_1.getConstrainedTypeAtLocation)(services, node.callee.object); + return tsutils + .unionConstituents(type) + .flatMap(part => tsutils.intersectionConstituents(part)) + .some(t => checker.isArrayType(t) || checker.isTupleType(t)); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isAssignee.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isAssignee.d.ts new file mode 100644 index 00000000..9aa685bf --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isAssignee.d.ts @@ -0,0 +1,3 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +export declare function isAssignee(node: TSESTree.Node): boolean; +//# sourceMappingURL=isAssignee.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isAssignee.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isAssignee.d.ts.map new file mode 100644 index 00000000..43ac24cf --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isAssignee.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isAssignee.d.ts","sourceRoot":"","sources":["../../src/util/isAssignee.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,wBAAgB,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,GAAG,OAAO,CA+DvD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isAssignee.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isAssignee.js new file mode 100644 index 00000000..8707f7bf --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isAssignee.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAssignee = isAssignee; +const utils_1 = require("@typescript-eslint/utils"); +function isAssignee(node) { + const parent = node.parent; + if (!parent) { + return false; + } + // a[i] = 1, a[i] += 1, etc. + if (parent.type === utils_1.AST_NODE_TYPES.AssignmentExpression && + parent.left === node) { + return true; + } + // delete a[i] + if (parent.type === utils_1.AST_NODE_TYPES.UnaryExpression && + parent.operator === 'delete' && + parent.argument === node) { + return true; + } + // a[i]++, --a[i], etc. + if (parent.type === utils_1.AST_NODE_TYPES.UpdateExpression && + parent.argument === node) { + return true; + } + // [a[i]] = [0] + if (parent.type === utils_1.AST_NODE_TYPES.ArrayPattern) { + return true; + } + // [...a[i]] = [0] + if (parent.type === utils_1.AST_NODE_TYPES.RestElement) { + return true; + } + // ({ foo: a[i] }) = { foo: 0 } + if (parent.type === utils_1.AST_NODE_TYPES.Property && + parent.value === node && + parent.parent.type === utils_1.AST_NODE_TYPES.ObjectExpression && + isAssignee(parent.parent)) { + return true; + } + // (a[i] as number)++, [...a[i]!] = [0], etc. + if ((parent.type === utils_1.AST_NODE_TYPES.TSNonNullExpression || + parent.type === utils_1.AST_NODE_TYPES.TSAsExpression || + parent.type === utils_1.AST_NODE_TYPES.TSTypeAssertion || + parent.type === utils_1.AST_NODE_TYPES.TSSatisfiesExpression) && + isAssignee(parent)) { + return true; + } + return false; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isHigherPrecedenceThanAwait.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isHigherPrecedenceThanAwait.d.ts new file mode 100644 index 00000000..61c46ef1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isHigherPrecedenceThanAwait.d.ts @@ -0,0 +1,3 @@ +import * as ts from 'typescript'; +export declare function isHigherPrecedenceThanAwait(tsNode: ts.Node): boolean; +//# sourceMappingURL=isHigherPrecedenceThanAwait.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isHigherPrecedenceThanAwait.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isHigherPrecedenceThanAwait.d.ts.map new file mode 100644 index 00000000..4b9cd5c1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isHigherPrecedenceThanAwait.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isHigherPrecedenceThanAwait.d.ts","sourceRoot":"","sources":["../../src/util/isHigherPrecedenceThanAwait.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAIjC,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAUpE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isHigherPrecedenceThanAwait.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isHigherPrecedenceThanAwait.js new file mode 100644 index 00000000..a2e7dc40 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isHigherPrecedenceThanAwait.js @@ -0,0 +1,46 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isHigherPrecedenceThanAwait = isHigherPrecedenceThanAwait; +const ts = __importStar(require("typescript")); +const getOperatorPrecedence_1 = require("./getOperatorPrecedence"); +function isHigherPrecedenceThanAwait(tsNode) { + const operator = ts.isBinaryExpression(tsNode) + ? tsNode.operatorToken.kind + : ts.SyntaxKind.Unknown; + const nodePrecedence = (0, getOperatorPrecedence_1.getOperatorPrecedence)(tsNode.kind, operator); + const awaitPrecedence = (0, getOperatorPrecedence_1.getOperatorPrecedence)(ts.SyntaxKind.AwaitExpression, ts.SyntaxKind.Unknown); + return nodePrecedence > awaitPrecedence; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNodeEqual.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNodeEqual.d.ts new file mode 100644 index 00000000..6102c38b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNodeEqual.d.ts @@ -0,0 +1,3 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +export declare function isNodeEqual(a: TSESTree.Node, b: TSESTree.Node): boolean; +//# sourceMappingURL=isNodeEqual.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNodeEqual.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNodeEqual.d.ts.map new file mode 100644 index 00000000..d6ace843 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNodeEqual.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isNodeEqual.d.ts","sourceRoot":"","sources":["../../src/util/isNodeEqual.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,wBAAgB,WAAW,CAAC,CAAC,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,EAAE,QAAQ,CAAC,IAAI,GAAG,OAAO,CA4BvE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNodeEqual.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNodeEqual.js new file mode 100644 index 00000000..3f980242 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNodeEqual.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isNodeEqual = isNodeEqual; +const utils_1 = require("@typescript-eslint/utils"); +function isNodeEqual(a, b) { + if (a.type !== b.type) { + return false; + } + if (a.type === utils_1.AST_NODE_TYPES.ThisExpression && + b.type === utils_1.AST_NODE_TYPES.ThisExpression) { + return true; + } + if (a.type === utils_1.AST_NODE_TYPES.Literal && b.type === utils_1.AST_NODE_TYPES.Literal) { + return a.value === b.value; + } + if (a.type === utils_1.AST_NODE_TYPES.Identifier && + b.type === utils_1.AST_NODE_TYPES.Identifier) { + return a.name === b.name; + } + if (a.type === utils_1.AST_NODE_TYPES.MemberExpression && + b.type === utils_1.AST_NODE_TYPES.MemberExpression) { + return (isNodeEqual(a.property, b.property) && isNodeEqual(a.object, b.object)); + } + return false; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNullLiteral.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNullLiteral.d.ts new file mode 100644 index 00000000..6221bfdb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNullLiteral.d.ts @@ -0,0 +1,3 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +export declare function isNullLiteral(i: TSESTree.Node): i is TSESTree.NullLiteral; +//# sourceMappingURL=isNullLiteral.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNullLiteral.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNullLiteral.d.ts.map new file mode 100644 index 00000000..3eac91ac --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNullLiteral.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isNullLiteral.d.ts","sourceRoot":"","sources":["../../src/util/isNullLiteral.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,wBAAgB,aAAa,CAAC,CAAC,EAAE,QAAQ,CAAC,IAAI,GAAG,CAAC,IAAI,QAAQ,CAAC,WAAW,CAEzE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNullLiteral.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNullLiteral.js new file mode 100644 index 00000000..e9a7921c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isNullLiteral.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isNullLiteral = isNullLiteral; +const utils_1 = require("@typescript-eslint/utils"); +function isNullLiteral(i) { + return i.type === utils_1.AST_NODE_TYPES.Literal && i.value == null; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isStartOfExpressionStatement.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isStartOfExpressionStatement.d.ts new file mode 100644 index 00000000..9996f712 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isStartOfExpressionStatement.d.ts @@ -0,0 +1,8 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +/** + * Tests if a node appears at the beginning of an ancestor ExpressionStatement node. + * @param node The node to check. + * @returns Whether the node appears at the beginning of an ancestor ExpressionStatement node. + */ +export declare function isStartOfExpressionStatement(node: TSESTree.Node): boolean; +//# sourceMappingURL=isStartOfExpressionStatement.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isStartOfExpressionStatement.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isStartOfExpressionStatement.d.ts.map new file mode 100644 index 00000000..95eb210a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isStartOfExpressionStatement.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isStartOfExpressionStatement.d.ts","sourceRoot":"","sources":["../../src/util/isStartOfExpressionStatement.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAOzD;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,GAAG,OAAO,CAUzE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isStartOfExpressionStatement.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isStartOfExpressionStatement.js new file mode 100644 index 00000000..cdaf7e59 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isStartOfExpressionStatement.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isStartOfExpressionStatement = isStartOfExpressionStatement; +const utils_1 = require("@typescript-eslint/utils"); +// The following is copied from `eslint`'s source code. +// https://github.com/eslint/eslint/blob/3a4eaf921543b1cd5d1df4ea9dec02fab396af2a/lib/rules/utils/ast-utils.js#L1026-L1041 +// Could be export { isStartOfExpressionStatement } from 'eslint/lib/rules/utils/ast-utils' +/** + * Tests if a node appears at the beginning of an ancestor ExpressionStatement node. + * @param node The node to check. + * @returns Whether the node appears at the beginning of an ancestor ExpressionStatement node. + */ +function isStartOfExpressionStatement(node) { + const start = node.range[0]; + let ancestor = node; + while ((ancestor = ancestor.parent) && ancestor.range[0] === start) { + if (ancestor.type === utils_1.AST_NODE_TYPES.ExpressionStatement) { + return true; + } + } + return false; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isTypeImport.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isTypeImport.d.ts new file mode 100644 index 00000000..541ad9b6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isTypeImport.d.ts @@ -0,0 +1,13 @@ +import type { Definition, ImportBindingDefinition } from '@typescript-eslint/scope-manager'; +/** + * Determine whether a variable definition is a type import. e.g.: + * + * ```ts + * import type { Foo } from 'foo'; + * import { type Bar } from 'bar'; + * ``` + * + * @param definition - The variable definition to check. + */ +export declare function isTypeImport(definition?: Definition): definition is ImportBindingDefinition; +//# sourceMappingURL=isTypeImport.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isTypeImport.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isTypeImport.d.ts.map new file mode 100644 index 00000000..59e50e48 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isTypeImport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isTypeImport.d.ts","sourceRoot":"","sources":["../../src/util/isTypeImport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EACV,uBAAuB,EACxB,MAAM,kCAAkC,CAAC;AAK1C;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC1B,UAAU,CAAC,EAAE,UAAU,GACtB,UAAU,IAAI,uBAAuB,CAOvC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isTypeImport.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isTypeImport.js new file mode 100644 index 00000000..1baae10b --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isTypeImport.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isTypeImport = isTypeImport; +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const utils_1 = require("@typescript-eslint/utils"); +/** + * Determine whether a variable definition is a type import. e.g.: + * + * ```ts + * import type { Foo } from 'foo'; + * import { type Bar } from 'bar'; + * ``` + * + * @param definition - The variable definition to check. + */ +function isTypeImport(definition) { + return (definition?.type === scope_manager_1.DefinitionType.ImportBinding && + (definition.parent.importKind === 'type' || + (definition.node.type === utils_1.AST_NODE_TYPES.ImportSpecifier && + definition.node.importKind === 'type'))); +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isUndefinedIdentifier.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isUndefinedIdentifier.d.ts new file mode 100644 index 00000000..db9e81d0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isUndefinedIdentifier.d.ts @@ -0,0 +1,3 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +export declare function isUndefinedIdentifier(i: TSESTree.Node): boolean; +//# sourceMappingURL=isUndefinedIdentifier.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isUndefinedIdentifier.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isUndefinedIdentifier.d.ts.map new file mode 100644 index 00000000..28d6b9f6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isUndefinedIdentifier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isUndefinedIdentifier.d.ts","sourceRoot":"","sources":["../../src/util/isUndefinedIdentifier.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,wBAAgB,qBAAqB,CAAC,CAAC,EAAE,QAAQ,CAAC,IAAI,GAAG,OAAO,CAE/D"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/isUndefinedIdentifier.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isUndefinedIdentifier.js new file mode 100644 index 00000000..e43bf372 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/isUndefinedIdentifier.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isUndefinedIdentifier = isUndefinedIdentifier; +const utils_1 = require("@typescript-eslint/utils"); +function isUndefinedIdentifier(i) { + return i.type === utils_1.AST_NODE_TYPES.Identifier && i.name === 'undefined'; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/misc.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/misc.d.ts new file mode 100644 index 00000000..28abc7ea --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/misc.d.ts @@ -0,0 +1,116 @@ +/** + * @fileoverview Really small utility functions that didn't deserve their own files + */ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +import type { RuleContext } from '@typescript-eslint/utils/ts-eslint'; +import * as ts from 'typescript'; +/** + * Check if the context file name is *.d.ts or *.d.tsx + */ +export declare function isDefinitionFile(fileName: string): boolean; +/** + * Upper cases the first character or the string + */ +export declare function upperCaseFirst(str: string): string; +export declare function arrayGroupByToMap(array: T[], getKey: (item: T) => Key): Map; +/** Return true if both parameters are equal. */ +export type Equal = (a: T, b: T) => boolean; +export declare function arraysAreEqual(a: T[] | undefined, b: T[] | undefined, eq: (a: T, b: T) => boolean): boolean; +/** Returns the first non-`undefined` result. */ +export declare function findFirstResult(inputs: T[], getResult: (t: T) => U | undefined): U | undefined; +/** + * Gets a string representation of the name of the index signature. + */ +export declare function getNameFromIndexSignature(node: TSESTree.TSIndexSignature): string; +export declare enum MemberNameType { + Private = 1, + Quoted = 2, + Normal = 3, + Expression = 4 +} +/** + * Gets a string name representation of the name of the given MethodDefinition + * or PropertyDefinition node, with handling for computed property names. + */ +export declare function getNameFromMember(member: TSESTree.AccessorProperty | TSESTree.MethodDefinition | TSESTree.Property | TSESTree.PropertyDefinition | TSESTree.TSAbstractAccessorProperty | TSESTree.TSAbstractMethodDefinition | TSESTree.TSAbstractPropertyDefinition | TSESTree.TSMethodSignature | TSESTree.TSPropertySignature, sourceCode: TSESLint.SourceCode): { + name: string; + type: MemberNameType; +}; +export type ExcludeKeys, Keys extends keyof Obj> = { + [k in Exclude]: Obj[k]; +}; +export type RequireKeys, Keys extends keyof Obj> = { + [k in Keys]-?: Exclude; +} & ExcludeKeys; +export declare function getEnumNames(myEnum: Record): T[]; +/** + * Given an array of words, returns an English-friendly concatenation, separated with commas, with + * the `and` clause inserted before the last item. + * + * Example: ['foo', 'bar', 'baz' ] returns the string "foo, bar, and baz". + */ +export declare function formatWordList(words: string[]): string; +/** + * Iterates the array in reverse and returns the index of the first element it + * finds which passes the predicate function. + * + * @returns Returns the index of the element if it finds it or -1 otherwise. + */ +export declare function findLastIndex(members: T[], predicate: (member: T) => boolean | null | undefined): number; +export declare function typeNodeRequiresParentheses(node: TSESTree.TypeNode, text: string): boolean; +export declare function isRestParameterDeclaration(decl: ts.Declaration): boolean; +export declare function isParenlessArrowFunction(node: TSESTree.ArrowFunctionExpression, sourceCode: TSESLint.SourceCode): boolean; +export type NodeWithKey = TSESTree.AccessorProperty | TSESTree.MemberExpression | TSESTree.MethodDefinition | TSESTree.Property | TSESTree.PropertyDefinition | TSESTree.TSAbstractMethodDefinition | TSESTree.TSAbstractPropertyDefinition; +/** + * Gets a member being accessed or declared if its value can be determined statically, and + * resolves it to the string or symbol value that will be used as the actual member + * access key at runtime. Otherwise, returns `undefined`. + * + * ```ts + * x.member // returns 'member' + * ^^^^^^^^ + * + * x?.member // returns 'member' (optional chaining is treated the same) + * ^^^^^^^^^ + * + * x['value'] // returns 'value' + * ^^^^^^^^^^ + * + * x[Math.random()] // returns undefined (not a static value) + * ^^^^^^^^^^^^^^^^ + * + * arr[0] // returns '0' (NOT 0) + * ^^^^^^ + * + * arr[0n] // returns '0' (NOT 0n) + * ^^^^^^^ + * + * const s = Symbol.for('symbolName') + * x[s] // returns `Symbol.for('symbolName')` (since it's a static/global symbol) + * ^^^^ + * + * const us = Symbol('symbolName') + * x[us] // returns undefined (since it's a unique symbol, so not statically analyzable) + * ^^^^^ + * + * var object = { + * 1234: '4567', // returns '1234' (NOT 1234) + * ^^^^^^^^^^^^ + * method() { } // returns 'method' + * ^^^^^^^^^^^^ + * } + * + * class WithMembers { + * foo: string // returns 'foo' + * ^^^^^^^^^^^ + * } + * ``` + */ +export declare function getStaticMemberAccessValue(node: NodeWithKey, { sourceCode }: RuleContext): string | symbol | undefined; +/** + * Answers whether the member expression looks like + * `x.value`, `x['value']`, + * or even `const v = 'value'; x[v]` (or optional variants thereof). + */ +export declare const isStaticMemberAccessOfValue: (memberExpression: NodeWithKey, context: RuleContext, ...values: (string | symbol)[]) => boolean; +//# sourceMappingURL=misc.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/misc.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/misc.d.ts.map new file mode 100644 index 00000000..22e0024c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/misc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"misc.d.ts","sourceRoot":"","sources":["../../src/util/misc.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAC;AAItE,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AASjC;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAS1D;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,GAAG,SAAS,MAAM,GAAG,MAAM,EAC9D,KAAK,EAAE,CAAC,EAAE,EACV,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,GAAG,GACvB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,QAAQ,CAAC,kBAAkB,GAC3B,QAAQ,CAAC,0BAA0B,GACnC,QAAQ,CAAC,4BAA4B,CAAC;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,wBAAgB,0BAA0B,CACxC,IAAI,EAAE,WAAW,EACjB,EAAE,UAAU,EAAE,EAAE,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,GAC7C,MAAM,GAAG,MAAM,GAAG,SAAS,CAiB7B;AAED;;;;GAIG;AACH,eAAO,MAAM,2BAA2B,GACtC,kBAAkB,WAAW,EAC7B,SAAS,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,EACvC,GAAG,QAAQ,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,KAC7B,OAGA,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/misc.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/misc.js new file mode 100644 index 00000000..6d5a6303 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/misc.js @@ -0,0 +1,273 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isStaticMemberAccessOfValue = exports.MemberNameType = void 0; +exports.isDefinitionFile = isDefinitionFile; +exports.upperCaseFirst = upperCaseFirst; +exports.arrayGroupByToMap = arrayGroupByToMap; +exports.arraysAreEqual = arraysAreEqual; +exports.findFirstResult = findFirstResult; +exports.getNameFromIndexSignature = getNameFromIndexSignature; +exports.getNameFromMember = getNameFromMember; +exports.getEnumNames = getEnumNames; +exports.formatWordList = formatWordList; +exports.findLastIndex = findLastIndex; +exports.typeNodeRequiresParentheses = typeNodeRequiresParentheses; +exports.isRestParameterDeclaration = isRestParameterDeclaration; +exports.isParenlessArrowFunction = isParenlessArrowFunction; +exports.getStaticMemberAccessValue = getStaticMemberAccessValue; +const type_utils_1 = require("@typescript-eslint/type-utils"); +const utils_1 = require("@typescript-eslint/utils"); +const ts = __importStar(require("typescript")); +const astUtils_1 = require("./astUtils"); +const DEFINITION_EXTENSIONS = [ + ts.Extension.Dts, + ts.Extension.Dcts, + ts.Extension.Dmts, +]; +/** + * Check if the context file name is *.d.ts or *.d.tsx + */ +function isDefinitionFile(fileName) { + const lowerFileName = fileName.toLowerCase(); + for (const definitionExt of DEFINITION_EXTENSIONS) { + if (lowerFileName.endsWith(definitionExt)) { + return true; + } + } + return /\.d\.(ts|cts|mts|.*\.ts)$/.test(lowerFileName); +} +/** + * Upper cases the first character or the string + */ +function upperCaseFirst(str) { + return str[0].toUpperCase() + str.slice(1); +} +function arrayGroupByToMap(array, getKey) { + const groups = new Map(); + for (const item of array) { + const key = getKey(item); + const existing = groups.get(key); + if (existing) { + existing.push(item); + } + else { + groups.set(key, [item]); + } + } + return groups; +} +function arraysAreEqual(a, b, eq) { + return (a === b || + (a != null && + b != null && + a.length === b.length && + a.every((x, idx) => eq(x, b[idx])))); +} +/** Returns the first non-`undefined` result. */ +function findFirstResult(inputs, getResult) { + for (const element of inputs) { + const result = getResult(element); + // eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish + if (result !== undefined) { + return result; + } + } + return undefined; +} +/** + * Gets a string representation of the name of the index signature. + */ +function getNameFromIndexSignature(node) { + const propName = node.parameters.find((parameter) => parameter.type === utils_1.AST_NODE_TYPES.Identifier); + return propName ? propName.name : '(index signature)'; +} +var MemberNameType; +(function (MemberNameType) { + MemberNameType[MemberNameType["Private"] = 1] = "Private"; + MemberNameType[MemberNameType["Quoted"] = 2] = "Quoted"; + MemberNameType[MemberNameType["Normal"] = 3] = "Normal"; + MemberNameType[MemberNameType["Expression"] = 4] = "Expression"; +})(MemberNameType || (exports.MemberNameType = MemberNameType = {})); +/** + * Gets a string name representation of the name of the given MethodDefinition + * or PropertyDefinition node, with handling for computed property names. + */ +function getNameFromMember(member, sourceCode) { + if (member.key.type === utils_1.AST_NODE_TYPES.Identifier) { + return { + name: member.key.name, + type: MemberNameType.Normal, + }; + } + if (member.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) { + return { + name: `#${member.key.name}`, + type: MemberNameType.Private, + }; + } + if (member.key.type === utils_1.AST_NODE_TYPES.Literal) { + const name = `${member.key.value}`; + if ((0, type_utils_1.requiresQuoting)(name)) { + return { + name: `"${name}"`, + type: MemberNameType.Quoted, + }; + } + return { + name, + type: MemberNameType.Normal, + }; + } + return { + name: sourceCode.text.slice(...member.key.range), + type: MemberNameType.Expression, + }; +} +function getEnumNames(myEnum) { + return Object.keys(myEnum).filter(x => isNaN(Number(x))); +} +/** + * Given an array of words, returns an English-friendly concatenation, separated with commas, with + * the `and` clause inserted before the last item. + * + * Example: ['foo', 'bar', 'baz' ] returns the string "foo, bar, and baz". + */ +function formatWordList(words) { + if (!words.length) { + return ''; + } + if (words.length === 1) { + return words[0]; + } + return [words.slice(0, -1).join(', '), words.slice(-1)[0]].join(' and '); +} +/** + * Iterates the array in reverse and returns the index of the first element it + * finds which passes the predicate function. + * + * @returns Returns the index of the element if it finds it or -1 otherwise. + */ +function findLastIndex(members, predicate) { + let idx = members.length - 1; + while (idx >= 0) { + const valid = predicate(members[idx]); + if (valid) { + return idx; + } + idx--; + } + return -1; +} +function typeNodeRequiresParentheses(node, text) { + return (node.type === utils_1.AST_NODE_TYPES.TSFunctionType || + node.type === utils_1.AST_NODE_TYPES.TSConstructorType || + node.type === utils_1.AST_NODE_TYPES.TSConditionalType || + (node.type === utils_1.AST_NODE_TYPES.TSUnionType && text.startsWith('|')) || + (node.type === utils_1.AST_NODE_TYPES.TSIntersectionType && text.startsWith('&'))); +} +function isRestParameterDeclaration(decl) { + return ts.isParameter(decl) && decl.dotDotDotToken != null; +} +function isParenlessArrowFunction(node, sourceCode) { + return (node.params.length === 1 && !(0, astUtils_1.isParenthesized)(node.params[0], sourceCode)); +} +/** + * Gets a member being accessed or declared if its value can be determined statically, and + * resolves it to the string or symbol value that will be used as the actual member + * access key at runtime. Otherwise, returns `undefined`. + * + * ```ts + * x.member // returns 'member' + * ^^^^^^^^ + * + * x?.member // returns 'member' (optional chaining is treated the same) + * ^^^^^^^^^ + * + * x['value'] // returns 'value' + * ^^^^^^^^^^ + * + * x[Math.random()] // returns undefined (not a static value) + * ^^^^^^^^^^^^^^^^ + * + * arr[0] // returns '0' (NOT 0) + * ^^^^^^ + * + * arr[0n] // returns '0' (NOT 0n) + * ^^^^^^^ + * + * const s = Symbol.for('symbolName') + * x[s] // returns `Symbol.for('symbolName')` (since it's a static/global symbol) + * ^^^^ + * + * const us = Symbol('symbolName') + * x[us] // returns undefined (since it's a unique symbol, so not statically analyzable) + * ^^^^^ + * + * var object = { + * 1234: '4567', // returns '1234' (NOT 1234) + * ^^^^^^^^^^^^ + * method() { } // returns 'method' + * ^^^^^^^^^^^^ + * } + * + * class WithMembers { + * foo: string // returns 'foo' + * ^^^^^^^^^^^ + * } + * ``` + */ +function getStaticMemberAccessValue(node, { sourceCode }) { + const key = node.type === utils_1.AST_NODE_TYPES.MemberExpression ? node.property : node.key; + const { type } = key; + if (!node.computed && + (type === utils_1.AST_NODE_TYPES.Identifier || + type === utils_1.AST_NODE_TYPES.PrivateIdentifier)) { + return key.name; + } + const result = (0, astUtils_1.getStaticValue)(key, sourceCode.getScope(node)); + if (!result) { + return undefined; + } + const { value } = result; + return typeof value === 'symbol' ? value : String(value); +} +/** + * Answers whether the member expression looks like + * `x.value`, `x['value']`, + * or even `const v = 'value'; x[v]` (or optional variants thereof). + */ +const isStaticMemberAccessOfValue = (memberExpression, context, ...values) => values.includes(getStaticMemberAccessValue(memberExpression, context)); +exports.isStaticMemberAccessOfValue = isStaticMemberAccessOfValue; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsPrecedingSemiColon.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsPrecedingSemiColon.d.ts new file mode 100644 index 00000000..876d75cc --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsPrecedingSemiColon.d.ts @@ -0,0 +1,12 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { SourceCode } from '@typescript-eslint/utils/ts-eslint'; +/** + * Determines whether an opening parenthesis `(`, bracket `[` or backtick ``` ` ``` needs to be preceded by a semicolon. + * This opening parenthesis or bracket should be at the start of an `ExpressionStatement`, a `MethodDefinition` or at + * the start of the body of an `ArrowFunctionExpression`. + * @param sourceCode The source code object. + * @param node A node at the position where an opening parenthesis or bracket will be inserted. + * @returns Whether a semicolon is required before the opening parenthesis or bracket. + */ +export declare function needsPrecedingSemicolon(sourceCode: SourceCode, node: TSESTree.Node): boolean; +//# sourceMappingURL=needsPrecedingSemiColon.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsPrecedingSemiColon.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsPrecedingSemiColon.d.ts.map new file mode 100644 index 00000000..06cedab0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsPrecedingSemiColon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"needsPrecedingSemiColon.d.ts","sourceRoot":"","sources":["../../src/util/needsPrecedingSemiColon.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AA6DrE;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CACrC,UAAU,EAAE,UAAU,EACtB,IAAI,EAAE,QAAQ,CAAC,IAAI,GAClB,OAAO,CAoDT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsPrecedingSemiColon.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsPrecedingSemiColon.js new file mode 100644 index 00000000..91760aea --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsPrecedingSemiColon.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.needsPrecedingSemicolon = needsPrecedingSemicolon; +const utils_1 = require("@typescript-eslint/utils"); +const ast_utils_1 = require("@typescript-eslint/utils/ast-utils"); +// The following is adapted from `eslint`'s source code. +// https://github.com/eslint/eslint/blob/3a4eaf921543b1cd5d1df4ea9dec02fab396af2a/lib/rules/utils/ast-utils.js#L1043-L1132 +// Could be export { isStartOfExpressionStatement } from 'eslint/lib/rules/utils/ast-utils' +const BREAK_OR_CONTINUE = new Set([ + utils_1.AST_NODE_TYPES.BreakStatement, + utils_1.AST_NODE_TYPES.ContinueStatement, +]); +// Declaration types that must contain a string Literal node at the end. +const DECLARATIONS = new Set([ + utils_1.AST_NODE_TYPES.ExportAllDeclaration, + utils_1.AST_NODE_TYPES.ExportNamedDeclaration, + utils_1.AST_NODE_TYPES.ImportDeclaration, +]); +const IDENTIFIER_OR_KEYWORD = new Set([ + utils_1.AST_NODE_TYPES.Identifier, + utils_1.AST_TOKEN_TYPES.Keyword, +]); +// Keywords that can immediately precede an ExpressionStatement node, mapped to the their node types. +const NODE_TYPES_BY_KEYWORD = { + __proto__: null, + break: utils_1.AST_NODE_TYPES.BreakStatement, + continue: utils_1.AST_NODE_TYPES.ContinueStatement, + debugger: utils_1.AST_NODE_TYPES.DebuggerStatement, + do: utils_1.AST_NODE_TYPES.DoWhileStatement, + else: utils_1.AST_NODE_TYPES.IfStatement, + return: utils_1.AST_NODE_TYPES.ReturnStatement, + yield: utils_1.AST_NODE_TYPES.YieldExpression, +}; +/* + * Before an opening parenthesis, postfix `++` and `--` always trigger ASI; + * the tokens `:`, `;`, `{` and `=>` don't expect a semicolon, as that would count as an empty statement. + */ +const PUNCTUATORS = new Set(['--', ';', ':', '{', '++', '=>']); +/* + * Statements that can contain an `ExpressionStatement` after a closing parenthesis. + * DoWhileStatement is an exception in that it always triggers ASI after the closing parenthesis. + */ +const STATEMENTS = new Set([ + utils_1.AST_NODE_TYPES.DoWhileStatement, + utils_1.AST_NODE_TYPES.ForInStatement, + utils_1.AST_NODE_TYPES.ForOfStatement, + utils_1.AST_NODE_TYPES.ForStatement, + utils_1.AST_NODE_TYPES.IfStatement, + utils_1.AST_NODE_TYPES.WhileStatement, + utils_1.AST_NODE_TYPES.WithStatement, +]); +/** + * Determines whether an opening parenthesis `(`, bracket `[` or backtick ``` ` ``` needs to be preceded by a semicolon. + * This opening parenthesis or bracket should be at the start of an `ExpressionStatement`, a `MethodDefinition` or at + * the start of the body of an `ArrowFunctionExpression`. + * @param sourceCode The source code object. + * @param node A node at the position where an opening parenthesis or bracket will be inserted. + * @returns Whether a semicolon is required before the opening parenthesis or bracket. + */ +function needsPrecedingSemicolon(sourceCode, node) { + const prevToken = sourceCode.getTokenBefore(node); + if (!prevToken || + (prevToken.type === utils_1.AST_TOKEN_TYPES.Punctuator && + PUNCTUATORS.has(prevToken.value))) { + return false; + } + const prevNode = sourceCode.getNodeByRangeIndex(prevToken.range[0]); + if (!prevNode) { + return false; + } + if ((0, ast_utils_1.isClosingParenToken)(prevToken)) { + return !STATEMENTS.has(prevNode.type); + } + if ((0, ast_utils_1.isClosingBraceToken)(prevToken)) { + return ((prevNode.type === utils_1.AST_NODE_TYPES.BlockStatement && + prevNode.parent.type === utils_1.AST_NODE_TYPES.FunctionExpression && + prevNode.parent.parent.type !== utils_1.AST_NODE_TYPES.MethodDefinition) || + (prevNode.type === utils_1.AST_NODE_TYPES.ClassBody && + prevNode.parent.type === utils_1.AST_NODE_TYPES.ClassExpression) || + prevNode.type === utils_1.AST_NODE_TYPES.ObjectExpression); + } + if (!prevNode.parent) { + return false; + } + if (IDENTIFIER_OR_KEYWORD.has(prevToken.type)) { + if (BREAK_OR_CONTINUE.has(prevNode.parent.type)) { + return false; + } + const keyword = prevToken.value; + const nodeType = NODE_TYPES_BY_KEYWORD[keyword]; + return prevNode.type !== nodeType; + } + if (prevToken.type === utils_1.AST_TOKEN_TYPES.String) { + return !DECLARATIONS.has(prevNode.parent.type); + } + return true; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsToBeAwaited.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsToBeAwaited.d.ts new file mode 100644 index 00000000..d7e0a758 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsToBeAwaited.d.ts @@ -0,0 +1,8 @@ +import type * as ts from 'typescript'; +export declare enum Awaitable { + Always = 0, + Never = 1, + May = 2 +} +export declare function needsToBeAwaited(checker: ts.TypeChecker, node: ts.Node, type: ts.Type): Awaitable; +//# sourceMappingURL=needsToBeAwaited.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsToBeAwaited.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsToBeAwaited.d.ts.map new file mode 100644 index 00000000..d41b43b7 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsToBeAwaited.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"needsToBeAwaited.d.ts","sourceRoot":"","sources":["../../src/util/needsToBeAwaited.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAUtC,oBAAY,SAAS;IACnB,MAAM,IAAA;IACN,KAAK,IAAA;IACL,GAAG,IAAA;CACJ;AAED,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,EAAE,CAAC,WAAW,EACvB,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,SAAS,CAoBX"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsToBeAwaited.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsToBeAwaited.js new file mode 100644 index 00000000..7cd63a2d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/needsToBeAwaited.js @@ -0,0 +1,63 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Awaitable = void 0; +exports.needsToBeAwaited = needsToBeAwaited; +const type_utils_1 = require("@typescript-eslint/type-utils"); +const tsutils = __importStar(require("ts-api-utils")); +const getConstraintInfo_1 = require("./getConstraintInfo"); +var Awaitable; +(function (Awaitable) { + Awaitable[Awaitable["Always"] = 0] = "Always"; + Awaitable[Awaitable["Never"] = 1] = "Never"; + Awaitable[Awaitable["May"] = 2] = "May"; +})(Awaitable || (exports.Awaitable = Awaitable = {})); +function needsToBeAwaited(checker, node, type) { + const { constraintType, isTypeParameter } = (0, getConstraintInfo_1.getConstraintInfo)(checker, type); + // unconstrained generic types should be treated as unknown + if (isTypeParameter && constraintType == null) { + return Awaitable.May; + } + // `any` and `unknown` types may need to be awaited + if ((0, type_utils_1.isTypeAnyType)(constraintType) || (0, type_utils_1.isTypeUnknownType)(constraintType)) { + return Awaitable.May; + } + // 'thenable' values should always be be awaited + if (tsutils.isThenableType(checker, node, constraintType)) { + return Awaitable.Always; + } + // anything else should not be awaited + return Awaitable.Never; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/objectIterators.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/objectIterators.d.ts new file mode 100644 index 00000000..044ec82c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/objectIterators.d.ts @@ -0,0 +1,4 @@ +export declare function objectForEachKey>(obj: T, callback: (key: keyof T) => void): void; +export declare function objectMapKey, Return>(obj: T, callback: (key: keyof T) => Return): Return[]; +export declare function objectReduceKey, Accumulator>(obj: T, callback: (acc: Accumulator, key: keyof T) => Accumulator, initial: Accumulator): Accumulator; +//# sourceMappingURL=objectIterators.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/objectIterators.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/objectIterators.d.ts.map new file mode 100644 index 00000000..d1413645 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/objectIterators.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"objectIterators.d.ts","sourceRoot":"","sources":["../../src/util/objectIterators.ts"],"names":[],"mappings":"AAAA,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChE,GAAG,EAAE,CAAC,EACN,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,IAAI,GAC/B,IAAI,CAKN;AAED,wBAAgB,YAAY,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EACpE,GAAG,EAAE,CAAC,EACN,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,MAAM,GACjC,MAAM,EAAE,CAMV;AAED,wBAAgB,eAAe,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAC5E,GAAG,EAAE,CAAC,EACN,QAAQ,EAAE,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,CAAC,KAAK,WAAW,EACzD,OAAO,EAAE,WAAW,GACnB,WAAW,CAMb"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/objectIterators.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/objectIterators.js new file mode 100644 index 00000000..80651afe --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/objectIterators.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.objectForEachKey = objectForEachKey; +exports.objectMapKey = objectMapKey; +exports.objectReduceKey = objectReduceKey; +function objectForEachKey(obj, callback) { + const keys = Object.keys(obj); + for (const key of keys) { + callback(key); + } +} +function objectMapKey(obj, callback) { + const values = []; + objectForEachKey(obj, key => { + values.push(callback(key)); + }); + return values; +} +function objectReduceKey(obj, callback, initial) { + let accumulator = initial; + objectForEachKey(obj, key => { + accumulator = callback(accumulator, key); + }); + return accumulator; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/promiseUtils.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/promiseUtils.d.ts new file mode 100644 index 00000000..6f5ee506 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/promiseUtils.d.ts @@ -0,0 +1,28 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { RuleContext } from '@typescript-eslint/utils/ts-eslint'; +/** + * Parses a syntactically possible `Promise.then()` call. Does not check the + * type of the callee. + */ +export declare function parseThenCall(node: TSESTree.CallExpression, context: RuleContext): { + onFulfilled?: TSESTree.Expression | undefined; + onRejected?: TSESTree.Expression | undefined; + object: TSESTree.Expression; +} | undefined; +/** + * Parses a syntactically possible `Promise.catch()` call. Does not check the + * type of the callee. + */ +export declare function parseCatchCall(node: TSESTree.CallExpression, context: RuleContext): { + onRejected?: TSESTree.Expression | undefined; + object: TSESTree.Expression; +} | undefined; +/** + * Parses a syntactically possible `Promise.finally()` call. Does not check the + * type of the callee. + */ +export declare function parseFinallyCall(node: TSESTree.CallExpression, context: RuleContext): { + object: TSESTree.Expression; + onFinally?: TSESTree.Expression | undefined; +} | undefined; +//# sourceMappingURL=promiseUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/promiseUtils.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/promiseUtils.d.ts.map new file mode 100644 index 00000000..a534c7c0 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/promiseUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"promiseUtils.d.ts","sourceRoot":"","sources":["../../src/util/promiseUtils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAC;AAMtE;;;GAGG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,QAAQ,CAAC,cAAc,EAC7B,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,GAErC;IACE,WAAW,CAAC,EAAE,QAAQ,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9C,UAAU,CAAC,EAAE,QAAQ,CAAC,UAAU,GAAG,SAAS,CAAC;IAC7C,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC;CAC7B,GACD,SAAS,CAqCZ;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,QAAQ,CAAC,cAAc,EAC7B,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,GAErC;IACE,UAAU,CAAC,EAAE,QAAQ,CAAC,UAAU,GAAG,SAAS,CAAC;IAC7C,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC;CAC7B,GACD,SAAS,CAuBZ;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,QAAQ,CAAC,cAAc,EAC7B,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,GAErC;IACE,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC;IAC5B,SAAS,CAAC,EAAE,QAAQ,CAAC,UAAU,GAAG,SAAS,CAAC;CAC7C,GACD,SAAS,CAsBZ"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/promiseUtils.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/promiseUtils.js new file mode 100644 index 00000000..4a2df50d --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/promiseUtils.js @@ -0,0 +1,98 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseThenCall = parseThenCall; +exports.parseCatchCall = parseCatchCall; +exports.parseFinallyCall = parseFinallyCall; +const utils_1 = require("@typescript-eslint/utils"); +const misc_1 = require("./misc"); +/** + * Parses a syntactically possible `Promise.then()` call. Does not check the + * type of the callee. + */ +function parseThenCall(node, context) { + if (node.callee.type === utils_1.AST_NODE_TYPES.MemberExpression) { + const methodName = (0, misc_1.getStaticMemberAccessValue)(node.callee, context); + if (methodName === 'then') { + if (node.arguments.length >= 1) { + if (node.arguments[0].type === utils_1.AST_NODE_TYPES.SpreadElement) { + return { + object: node.callee.object, + }; + } + if (node.arguments.length >= 2) { + if (node.arguments[1].type === utils_1.AST_NODE_TYPES.SpreadElement) { + return { + object: node.callee.object, + onFulfilled: node.arguments[0], + }; + } + return { + object: node.callee.object, + onFulfilled: node.arguments[0], + onRejected: node.arguments[1], + }; + } + return { + object: node.callee.object, + onFulfilled: node.arguments[0], + }; + } + return { + object: node.callee.object, + }; + } + } + return undefined; +} +/** + * Parses a syntactically possible `Promise.catch()` call. Does not check the + * type of the callee. + */ +function parseCatchCall(node, context) { + if (node.callee.type === utils_1.AST_NODE_TYPES.MemberExpression) { + const methodName = (0, misc_1.getStaticMemberAccessValue)(node.callee, context); + if (methodName === 'catch') { + if (node.arguments.length >= 1) { + if (node.arguments[0].type === utils_1.AST_NODE_TYPES.SpreadElement) { + return { + object: node.callee.object, + }; + } + return { + object: node.callee.object, + onRejected: node.arguments[0], + }; + } + return { + object: node.callee.object, + }; + } + } + return undefined; +} +/** + * Parses a syntactically possible `Promise.finally()` call. Does not check the + * type of the callee. + */ +function parseFinallyCall(node, context) { + if (node.callee.type === utils_1.AST_NODE_TYPES.MemberExpression) { + const methodName = (0, misc_1.getStaticMemberAccessValue)(node.callee, context); + if (methodName === 'finally') { + if (node.arguments.length >= 1) { + if (node.arguments[0].type === utils_1.AST_NODE_TYPES.SpreadElement) { + return { + object: node.callee.object, + }; + } + return { + object: node.callee.object, + onFinally: node.arguments[0], + }; + } + return { + object: node.callee.object, + }; + } + } + return undefined; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/rangeToLoc.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/rangeToLoc.d.ts new file mode 100644 index 00000000..9d8cf85a --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/rangeToLoc.d.ts @@ -0,0 +1,3 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +export declare function rangeToLoc(sourceCode: TSESLint.SourceCode, range: TSESLint.AST.Range): TSESTree.SourceLocation; +//# sourceMappingURL=rangeToLoc.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/rangeToLoc.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/rangeToLoc.d.ts.map new file mode 100644 index 00000000..202619b5 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/rangeToLoc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rangeToLoc.d.ts","sourceRoot":"","sources":["../../src/util/rangeToLoc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEnE,wBAAgB,UAAU,CACxB,UAAU,EAAE,QAAQ,CAAC,UAAU,EAC/B,KAAK,EAAE,QAAQ,CAAC,GAAG,CAAC,KAAK,GACxB,QAAQ,CAAC,cAAc,CAKzB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/rangeToLoc.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/rangeToLoc.js new file mode 100644 index 00000000..2fb8cbae --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/rangeToLoc.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rangeToLoc = rangeToLoc; +function rangeToLoc(sourceCode, range) { + return { + end: sourceCode.getLocFromIndex(range[1]), + start: sourceCode.getLocFromIndex(range[0]), + }; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/referenceContainsTypeQuery.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/referenceContainsTypeQuery.d.ts new file mode 100644 index 00000000..5c981308 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/referenceContainsTypeQuery.d.ts @@ -0,0 +1,6 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +/** + * Recursively checks whether a given reference has a type query declaration among its parents + */ +export declare function referenceContainsTypeQuery(node: TSESTree.Node): boolean; +//# sourceMappingURL=referenceContainsTypeQuery.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/referenceContainsTypeQuery.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/referenceContainsTypeQuery.d.ts.map new file mode 100644 index 00000000..862d9a34 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/referenceContainsTypeQuery.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"referenceContainsTypeQuery.d.ts","sourceRoot":"","sources":["../../src/util/referenceContainsTypeQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,GAAG,OAAO,CAavE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/referenceContainsTypeQuery.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/referenceContainsTypeQuery.js new file mode 100644 index 00000000..45bc86ef --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/referenceContainsTypeQuery.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.referenceContainsTypeQuery = referenceContainsTypeQuery; +const utils_1 = require("@typescript-eslint/utils"); +/** + * Recursively checks whether a given reference has a type query declaration among its parents + */ +function referenceContainsTypeQuery(node) { + switch (node.type) { + case utils_1.AST_NODE_TYPES.TSTypeQuery: + return true; + case utils_1.AST_NODE_TYPES.TSQualifiedName: + case utils_1.AST_NODE_TYPES.Identifier: + return referenceContainsTypeQuery(node.parent); + default: + // if we find a different node, there's no chance that we're in a TSTypeQuery + return false; + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/scopeUtils.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/scopeUtils.d.ts new file mode 100644 index 00000000..ba4c6471 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/scopeUtils.d.ts @@ -0,0 +1,4 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type { SourceCode } from '@typescript-eslint/utils/ts-eslint'; +export declare function isReferenceToGlobalFunction(calleeName: string, node: TSESTree.Node, sourceCode: SourceCode): boolean; +//# sourceMappingURL=scopeUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/scopeUtils.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/scopeUtils.d.ts.map new file mode 100644 index 00000000..e1d99991 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/scopeUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopeUtils.d.ts","sourceRoot":"","sources":["../../src/util/scopeUtils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAErE,wBAAgB,2BAA2B,CACzC,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,QAAQ,CAAC,IAAI,EACnB,UAAU,EAAE,UAAU,GACrB,OAAO,CAOT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/scopeUtils.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/scopeUtils.js new file mode 100644 index 00000000..21445521 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/scopeUtils.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isReferenceToGlobalFunction = isReferenceToGlobalFunction; +function isReferenceToGlobalFunction(calleeName, node, sourceCode) { + const ref = sourceCode + .getScope(node) + .references.find(ref => ref.identifier.name === calleeName); + // ensure it's the "global" version + return !ref?.resolved?.defs.length; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/skipChainExpression.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/skipChainExpression.d.ts new file mode 100644 index 00000000..ea376eda --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/skipChainExpression.d.ts @@ -0,0 +1,3 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +export declare function skipChainExpression(node: T): T | TSESTree.ChainElement; +//# sourceMappingURL=skipChainExpression.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/skipChainExpression.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/skipChainExpression.d.ts.map new file mode 100644 index 00000000..3f2399db --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/skipChainExpression.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"skipChainExpression.d.ts","sourceRoot":"","sources":["../../src/util/skipChainExpression.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,QAAQ,CAAC,IAAI,EACzD,IAAI,EAAE,CAAC,GACN,CAAC,GAAG,QAAQ,CAAC,YAAY,CAE3B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/skipChainExpression.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/skipChainExpression.js new file mode 100644 index 00000000..8f041cfb --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/skipChainExpression.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.skipChainExpression = skipChainExpression; +const utils_1 = require("@typescript-eslint/utils"); +function skipChainExpression(node) { + return node.type === utils_1.AST_NODE_TYPES.ChainExpression ? node.expression : node; +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/truthinessUtils.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/truthinessUtils.d.ts new file mode 100644 index 00000000..4316b13c --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/truthinessUtils.d.ts @@ -0,0 +1,4 @@ +import * as ts from 'typescript'; +export declare const isPossiblyFalsy: (type: ts.Type) => boolean; +export declare const isPossiblyTruthy: (type: ts.Type) => boolean; +//# sourceMappingURL=truthinessUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/truthinessUtils.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/truthinessUtils.d.ts.map new file mode 100644 index 00000000..6eb9d824 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/truthinessUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"truthinessUtils.d.ts","sourceRoot":"","sources":["../../src/util/truthinessUtils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AASjC,eAAO,MAAM,eAAe,GAAI,MAAM,EAAE,CAAC,IAAI,KAAG,OAS0B,CAAC;AAE3E,eAAO,MAAM,gBAAgB,GAAI,MAAM,EAAE,CAAC,IAAI,KAAG,OAQ5C,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/truthinessUtils.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/truthinessUtils.js new file mode 100644 index 00000000..2ef0dc40 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/truthinessUtils.js @@ -0,0 +1,60 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isPossiblyTruthy = exports.isPossiblyFalsy = void 0; +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const getValueOfLiteralType_1 = require("./getValueOfLiteralType"); +// Truthiness utilities +const isTruthyLiteral = (type) => tsutils.isTrueLiteralType(type) || + (type.isLiteral() && !!(0, getValueOfLiteralType_1.getValueOfLiteralType)(type)); +const isPossiblyFalsy = (type) => tsutils + .unionConstituents(type) + // Intersections like `string & {}` can also be possibly falsy, + // requiring us to look into the intersection. + .flatMap(type => tsutils.intersectionConstituents(type)) + // PossiblyFalsy flag includes literal values, so exclude ones that + // are definitely truthy + .filter(t => !isTruthyLiteral(t)) + .some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.PossiblyFalsy)); +exports.isPossiblyFalsy = isPossiblyFalsy; +const isPossiblyTruthy = (type) => tsutils + .unionConstituents(type) + .map(type => tsutils.intersectionConstituents(type)) + .some(intersectionParts => +// It is possible to define intersections that are always falsy, +// like `"" & { __brand: string }`. +intersectionParts.every(type => !tsutils.isFalsyType(type))); +exports.isPossiblyTruthy = isPossiblyTruthy; diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/types.d.ts b/node_modules/@typescript-eslint/eslint-plugin/dist/util/types.d.ts new file mode 100644 index 00000000..9d8bf4ea --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/types.d.ts @@ -0,0 +1,3 @@ +export type MakeRequired = Omit & Required>>; +export type ValueOf = T[keyof T]; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/types.d.ts.map b/node_modules/@typescript-eslint/eslint-plugin/dist/util/types.d.ts.map new file mode 100644 index 00000000..dfbe8d1e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/util/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,CAAC,IAAI,EAAE,GAAG,SAAS,MAAM,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,GACtE,QAAQ,CAAC,MAAM,CAAC,GAAG,EAAE,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AAEhD,MAAM,MAAM,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/dist/util/types.js b/node_modules/@typescript-eslint/eslint-plugin/dist/util/types.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/dist/util/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/eslint-plugin/index.d.ts b/node_modules/@typescript-eslint/eslint-plugin/index.d.ts new file mode 100644 index 00000000..756a025e --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/index.d.ts @@ -0,0 +1,13 @@ +import type { + ClassicConfig, + FlatConfig, +} from '@typescript-eslint/utils/ts-eslint'; + +import type rules from './rules'; + +declare const cjsExport: { + configs: Record; + meta: FlatConfig.PluginMeta; + rules: typeof rules; +}; +export = cjsExport; diff --git a/node_modules/@typescript-eslint/eslint-plugin/package.json b/node_modules/@typescript-eslint/eslint-plugin/package.json new file mode 100644 index 00000000..0e0f237f --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/package.json @@ -0,0 +1,121 @@ +{ + "name": "@typescript-eslint/eslint-plugin", + "version": "8.34.0", + "description": "TypeScript plugin for ESLint", + "files": [ + "dist", + "!*.tsbuildinfo", + "index.d.ts", + "raw-plugin.d.ts", + "rules.d.ts", + "package.json", + "./README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json", + "./use-at-your-own-risk/rules": { + "types": "./rules.d.ts", + "default": "./dist/rules/index.js" + }, + "./use-at-your-own-risk/raw-plugin": { + "types": "./raw-plugin.d.ts", + "default": "./dist/raw-plugin.js" + } + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/eslint-plugin" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/eslint-plugin", + "license": "MIT", + "keywords": [ + "eslint", + "eslintplugin", + "eslint-plugin", + "typescript" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "format": "yarn run -T format", + "generate-breaking-changes": "yarn run -BT nx generate-breaking-changes", + "generate-configs": "yarn run -T generate-configs", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "dependencies": { + "@eslint-community/regexpp": "^4.10.0", + "@typescript-eslint/scope-manager": "8.34.0", + "@typescript-eslint/type-utils": "8.34.0", + "@typescript-eslint/utils": "8.34.0", + "@typescript-eslint/visitor-keys": "8.34.0", + "graphemer": "^1.4.0", + "ignore": "^7.0.0", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.1.0" + }, + "devDependencies": { + "@types/mdast": "^4.0.3", + "@types/natural-compare": "*", + "@typescript-eslint/rule-schema-to-typescript-types": "8.34.0", + "@typescript-eslint/rule-tester": "8.34.0", + "@vitest/coverage-v8": "^3.1.3", + "ajv": "^6.12.6", + "cross-fetch": "*", + "eslint": "*", + "json-schema": "*", + "markdown-table": "^3.0.3", + "marked": "^15.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-mdx": "^3.0.0", + "micromark-extension-mdxjs": "^3.0.0", + "prettier": "^3.5.3", + "rimraf": "*", + "title-case": "^4.0.0", + "tsx": "*", + "typescript": "*", + "unist-util-visit": "^5.0.0", + "vitest": "^3.1.3" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.34.0", + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "eslint-plugin", + "includedScripts": [ + "clean" + ], + "targets": { + "generate-breaking-changes": { + "command": "tsx tools/generate-breaking-changes.mts", + "options": { + "cwd": "{projectRoot}" + }, + "dependsOn": [ + "type-utils:build" + ] + } + } + } +} diff --git a/node_modules/@typescript-eslint/eslint-plugin/raw-plugin.d.ts b/node_modules/@typescript-eslint/eslint-plugin/raw-plugin.d.ts new file mode 100644 index 00000000..25a093ab --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/raw-plugin.d.ts @@ -0,0 +1,25 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; + +import type plugin from './index'; + +declare const cjsExport: { + flatConfigs: { + 'flat/all': FlatConfig.ConfigArray; + 'flat/base': FlatConfig.Config; + 'flat/disable-type-checked': FlatConfig.Config; + 'flat/eslint-recommended': FlatConfig.Config; + 'flat/recommended': FlatConfig.ConfigArray; + 'flat/recommended-type-checked': FlatConfig.ConfigArray; + 'flat/recommended-type-checked-only': FlatConfig.ConfigArray; + 'flat/strict': FlatConfig.ConfigArray; + 'flat/strict-type-checked': FlatConfig.ConfigArray; + 'flat/strict-type-checked-only': FlatConfig.ConfigArray; + 'flat/stylistic': FlatConfig.ConfigArray; + 'flat/stylistic-type-checked': FlatConfig.ConfigArray; + 'flat/stylistic-type-checked-only': FlatConfig.ConfigArray; + }; + parser: FlatConfig.Parser; + plugin: typeof plugin; +}; + +export = cjsExport; diff --git a/node_modules/@typescript-eslint/eslint-plugin/rules.d.ts b/node_modules/@typescript-eslint/eslint-plugin/rules.d.ts new file mode 100644 index 00000000..db19c5d6 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/rules.d.ts @@ -0,0 +1,87 @@ +/* +We purposely don't generate types for our plugin because TL;DR: +1) there's no real reason that anyone should do a typed import of our rules, +2) it would require us to change our code so there aren't as many inferred types + +This type declaration exists as a hacky way to add a type to the export for our +internal packages that require it. + +*** Long reason *** + +When you turn on declaration files, TS requires all types to be "fully resolvable" +without changes to the code. +All of our lint rules `export default createRule(...)`, which means they all +implicitly reference the `TSESLint.Rule` type for the export. + +TS wants to transpile each rule file to this `.d.ts` file: + +```ts +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule; +export default _default; +``` + +Because we don't import `TSESLint` in most files, it means that TS would have to +insert a new import during the declaration emit to make this work. +However TS wants to avoid adding new imports to the file because a new module +could have type side-effects (like global augmentation) which could cause weird +type side-effects in the decl file that wouldn't exist in source TS file. + +So TS errors on most of our rules with the following error: +``` +The inferred type of 'default' cannot be named without a reference to +'../../../../node_modules/@typescript-eslint/utils/src/ts-eslint/Rule'. +This is likely not portable. A type annotation is necessary. ts(2742) +``` +*/ +/* eslint-disable no-restricted-syntax */ + +import type { + RuleModuleWithMetaDocs, + RuleRecommendation, + RuleRecommendationAcrossConfigs, +} from '@typescript-eslint/utils/ts-eslint'; + +interface ESLintPluginDocs { + /** + * Does the rule extend (or is it based off of) an ESLint code rule? + * Alternately accepts the name of the base rule, in case the rule has been renamed. + * This is only used for documentation purposes. + */ + extendsBaseRule?: boolean | string; + + /** + * If a string config name, which starting config this rule is enabled in. + * If an object, which settings it has enabled in each of those configs. + */ + recommended?: RuleRecommendation | RuleRecommendationAcrossConfigs; + + /** + * Does the rule require us to create a full TypeScript Program in order for it + * to type-check code. This is only used for documentation purposes. + */ + requiresTypeChecking?: boolean; +} + +type ESLintPluginRuleModule = RuleModuleWithMetaDocs< + string, + readonly unknown[], + ESLintPluginDocs +>; + +type TypeScriptESLintRules = Record< + string, + RuleModuleWithMetaDocs +>; + +declare const rules: TypeScriptESLintRules; + +declare namespace rules { + export type { + ESLintPluginDocs, + ESLintPluginRuleModule, + TypeScriptESLintRules, + }; +} + +export = rules; diff --git a/node_modules/@typescript-eslint/parser/LICENSE b/node_modules/@typescript-eslint/parser/LICENSE new file mode 100644 index 00000000..a1164108 --- /dev/null +++ b/node_modules/@typescript-eslint/parser/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/parser/README.md b/node_modules/@typescript-eslint/parser/README.md new file mode 100644 index 00000000..56ee655a --- /dev/null +++ b/node_modules/@typescript-eslint/parser/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/parser` + +> An ESLint parser which leverages TypeScript ESTree to allow for ESLint to lint TypeScript source code. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/parser.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/parser) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/parser.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/parser) + +👉 See **https://typescript-eslint.io/packages/parser** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/parser/dist/index.d.ts b/node_modules/@typescript-eslint/parser/dist/index.d.ts new file mode 100644 index 00000000..938e645c --- /dev/null +++ b/node_modules/@typescript-eslint/parser/dist/index.d.ts @@ -0,0 +1,8 @@ +export { parse, parseForESLint, type ParserOptions } from './parser'; +export { clearCaches, createProgram, type ParserServices, type ParserServicesWithoutTypeInformation, type ParserServicesWithTypeInformation, withoutProjectParserOptions, } from '@typescript-eslint/typescript-estree'; +export declare const version: string; +export declare const meta: { + name: string; + version: string; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/parser/dist/index.d.ts.map b/node_modules/@typescript-eslint/parser/dist/index.d.ts.map new file mode 100644 index 00000000..124854e3 --- /dev/null +++ b/node_modules/@typescript-eslint/parser/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,KAAK,aAAa,EAAE,MAAM,UAAU,CAAC;AACrE,OAAO,EACL,WAAW,EACX,aAAa,EACb,KAAK,cAAc,EACnB,KAAK,oCAAoC,EACzC,KAAK,iCAAiC,EACtC,2BAA2B,GAC5B,MAAM,sCAAsC,CAAC;AAI9C,eAAO,MAAM,OAAO,EAAE,MAA2C,CAAC;AAElE,eAAO,MAAM,IAAI;;;CAGhB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/parser/dist/index.js b/node_modules/@typescript-eslint/parser/dist/index.js new file mode 100644 index 00000000..47ea577f --- /dev/null +++ b/node_modules/@typescript-eslint/parser/dist/index.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.meta = exports.version = exports.withoutProjectParserOptions = exports.createProgram = exports.clearCaches = exports.parseForESLint = exports.parse = void 0; +var parser_1 = require("./parser"); +Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parser_1.parse; } }); +Object.defineProperty(exports, "parseForESLint", { enumerable: true, get: function () { return parser_1.parseForESLint; } }); +var typescript_estree_1 = require("@typescript-eslint/typescript-estree"); +Object.defineProperty(exports, "clearCaches", { enumerable: true, get: function () { return typescript_estree_1.clearCaches; } }); +Object.defineProperty(exports, "createProgram", { enumerable: true, get: function () { return typescript_estree_1.createProgram; } }); +Object.defineProperty(exports, "withoutProjectParserOptions", { enumerable: true, get: function () { return typescript_estree_1.withoutProjectParserOptions; } }); +// note - cannot migrate this to an import statement because it will make TSC copy the package.json to the dist folder +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access +exports.version = require('../package.json').version; +exports.meta = { + name: 'typescript-eslint/parser', + version: exports.version, +}; diff --git a/node_modules/@typescript-eslint/parser/dist/parser.d.ts b/node_modules/@typescript-eslint/parser/dist/parser.d.ts new file mode 100644 index 00000000..fb3182b1 --- /dev/null +++ b/node_modules/@typescript-eslint/parser/dist/parser.d.ts @@ -0,0 +1,23 @@ +import type { ScopeManager } from '@typescript-eslint/scope-manager'; +import type { ParserOptions, TSESTree } from '@typescript-eslint/types'; +import type { AST, ParserServices } from '@typescript-eslint/typescript-estree'; +import type { VisitorKeys } from '@typescript-eslint/visitor-keys'; +import type * as ts from 'typescript'; +interface ESLintProgram extends AST<{ + comment: true; + tokens: true; +}> { + comments: TSESTree.Comment[]; + range: [number, number]; + tokens: TSESTree.Token[]; +} +interface ParseForESLintResult { + ast: ESLintProgram; + scopeManager: ScopeManager; + services: ParserServices; + visitorKeys: VisitorKeys; +} +export declare function parse(code: string | ts.SourceFile, options?: ParserOptions): ParseForESLintResult['ast']; +export declare function parseForESLint(code: string | ts.SourceFile, parserOptions?: ParserOptions | null): ParseForESLintResult; +export type { ParserOptions } from '@typescript-eslint/types'; +//# sourceMappingURL=parser.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/parser/dist/parser.d.ts.map b/node_modules/@typescript-eslint/parser/dist/parser.d.ts.map new file mode 100644 index 00000000..34bc99e2 --- /dev/null +++ b/node_modules/@typescript-eslint/parser/dist/parser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../src/parser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,YAAY,EACb,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EAAO,aAAa,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAC7E,OAAO,KAAK,EACV,GAAG,EACH,cAAc,EAEf,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAUtC,UAAU,aAAc,SAAQ,GAAG,CAAC;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,IAAI,CAAA;CAAE,CAAC;IAClE,QAAQ,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC7B,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxB,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC;CAC1B;AAED,UAAU,oBAAoB;IAC5B,GAAG,EAAE,aAAa,CAAC;IACnB,YAAY,EAAE,YAAY,CAAC;IAC3B,QAAQ,EAAE,cAAc,CAAC;IACzB,WAAW,EAAE,WAAW,CAAC;CAC1B;AAkDD,wBAAgB,KAAK,CACnB,IAAI,EAAE,MAAM,GAAG,EAAE,CAAC,UAAU,EAC5B,OAAO,CAAC,EAAE,aAAa,GACtB,oBAAoB,CAAC,KAAK,CAAC,CAE7B;AAED,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,GAAG,EAAE,CAAC,UAAU,EAC5B,aAAa,CAAC,EAAE,aAAa,GAAG,IAAI,GACnC,oBAAoB,CAiGtB;AAED,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/parser/dist/parser.js b/node_modules/@typescript-eslint/parser/dist/parser.js new file mode 100644 index 00000000..c61beece --- /dev/null +++ b/node_modules/@typescript-eslint/parser/dist/parser.js @@ -0,0 +1,139 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parse = parse; +exports.parseForESLint = parseForESLint; +const scope_manager_1 = require("@typescript-eslint/scope-manager"); +const typescript_estree_1 = require("@typescript-eslint/typescript-estree"); +const visitor_keys_1 = require("@typescript-eslint/visitor-keys"); +const debug_1 = __importDefault(require("debug")); +const typescript_1 = require("typescript"); +const log = (0, debug_1.default)('typescript-eslint:parser:parser'); +function validateBoolean(value, fallback = false) { + if (typeof value !== 'boolean') { + return fallback; + } + return value; +} +const LIB_FILENAME_REGEX = /lib\.(.+)\.d\.[cm]?ts$/; +function getLib(compilerOptions) { + if (compilerOptions.lib) { + return compilerOptions.lib + .map(lib => LIB_FILENAME_REGEX.exec(lib.toLowerCase())?.[1]) + .filter((lib) => !!lib); + } + const target = compilerOptions.target ?? typescript_1.ScriptTarget.ES5; + // https://github.com/microsoft/TypeScript/blob/ae582a22ee1bb052e19b7c1bc4cac60509b574e0/src/compiler/utilitiesPublic.ts#L13-L36 + switch (target) { + case typescript_1.ScriptTarget.ES2015: + return ['es6']; + case typescript_1.ScriptTarget.ES2016: + return ['es2016.full']; + case typescript_1.ScriptTarget.ES2017: + return ['es2017.full']; + case typescript_1.ScriptTarget.ES2018: + return ['es2018.full']; + case typescript_1.ScriptTarget.ES2019: + return ['es2019.full']; + case typescript_1.ScriptTarget.ES2020: + return ['es2020.full']; + case typescript_1.ScriptTarget.ES2021: + return ['es2021.full']; + case typescript_1.ScriptTarget.ES2022: + return ['es2022.full']; + case typescript_1.ScriptTarget.ES2023: + return ['es2023.full']; + case typescript_1.ScriptTarget.ES2024: + return ['es2024.full']; + case typescript_1.ScriptTarget.ESNext: + return ['esnext.full']; + default: + return ['lib']; + } +} +function parse(code, options) { + return parseForESLint(code, options).ast; +} +function parseForESLint(code, parserOptions) { + if (!parserOptions || typeof parserOptions !== 'object') { + parserOptions = {}; + } + else { + parserOptions = { ...parserOptions }; + } + // https://eslint.org/docs/user-guide/configuring#specifying-parser-options + // if sourceType is not provided by default eslint expect that it will be set to "script" + if (parserOptions.sourceType !== 'module' && + parserOptions.sourceType !== 'script') { + parserOptions.sourceType = 'script'; + } + if (typeof parserOptions.ecmaFeatures !== 'object') { + parserOptions.ecmaFeatures = {}; + } + /** + * Allow the user to suppress the warning from typescript-estree if they are using an unsupported + * version of TypeScript + */ + const warnOnUnsupportedTypeScriptVersion = validateBoolean(parserOptions.warnOnUnsupportedTypeScriptVersion, true); + const tsestreeOptions = { + jsx: validateBoolean(parserOptions.ecmaFeatures.jsx), + ...(!warnOnUnsupportedTypeScriptVersion && { loggerFn: false }), + ...parserOptions, + // Override errorOnTypeScriptSyntacticAndSemanticIssues and set it to false to prevent use from user config + // https://github.com/typescript-eslint/typescript-eslint/issues/8681#issuecomment-2000411834 + errorOnTypeScriptSyntacticAndSemanticIssues: false, + // comment, loc, range, and tokens should always be set for ESLint usage + // https://github.com/typescript-eslint/typescript-eslint/issues/8347 + comment: true, + loc: true, + range: true, + tokens: true, + }; + const analyzeOptions = { + globalReturn: parserOptions.ecmaFeatures.globalReturn, + jsxFragmentName: parserOptions.jsxFragmentName, + jsxPragma: parserOptions.jsxPragma, + lib: parserOptions.lib, + sourceType: parserOptions.sourceType, + }; + const { ast, services } = (0, typescript_estree_1.parseAndGenerateServices)(code, tsestreeOptions); + ast.sourceType = parserOptions.sourceType; + if (services.program) { + // automatically apply the options configured for the program + const compilerOptions = services.program.getCompilerOptions(); + if (analyzeOptions.lib == null) { + analyzeOptions.lib = getLib(compilerOptions); + log('Resolved libs from program: %o', analyzeOptions.lib); + } + if ( + // eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish + analyzeOptions.jsxPragma === undefined && + compilerOptions.jsxFactory != null) { + // in case the user has specified something like "preact.h" + const factory = compilerOptions.jsxFactory.split('.')[0].trim(); + analyzeOptions.jsxPragma = factory; + log('Resolved jsxPragma from program: %s', analyzeOptions.jsxPragma); + } + if ( + // eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish + analyzeOptions.jsxFragmentName === undefined && + compilerOptions.jsxFragmentFactory != null) { + // in case the user has specified something like "preact.Fragment" + const fragFactory = compilerOptions.jsxFragmentFactory + .split('.')[0] + .trim(); + analyzeOptions.jsxFragmentName = fragFactory; + log('Resolved jsxFragmentName from program: %s', analyzeOptions.jsxFragmentName); + } + } + const scopeManager = (0, scope_manager_1.analyze)(ast, analyzeOptions); + // if not defined - override from the parserOptions + services.emitDecoratorMetadata ??= + parserOptions.emitDecoratorMetadata === true; + services.experimentalDecorators ??= + parserOptions.experimentalDecorators === true; + services.isolatedDeclarations ??= parserOptions.isolatedDeclarations === true; + return { ast, scopeManager, services, visitorKeys: visitor_keys_1.visitorKeys }; +} diff --git a/node_modules/@typescript-eslint/parser/package.json b/node_modules/@typescript-eslint/parser/package.json new file mode 100644 index 00000000..774cd569 --- /dev/null +++ b/node_modules/@typescript-eslint/parser/package.json @@ -0,0 +1,78 @@ +{ + "name": "@typescript-eslint/parser", + "version": "8.34.0", + "description": "An ESLint custom parser which leverages TypeScript ESTree", + "files": [ + "dist", + "!*.tsbuildinfo", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/parser" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/parser", + "license": "MIT", + "keywords": [ + "ast", + "ecmascript", + "javascript", + "typescript", + "parser", + "syntax", + "eslint" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "format": "yarn run -T format", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + }, + "dependencies": { + "@typescript-eslint/scope-manager": "8.34.0", + "@typescript-eslint/types": "8.34.0", + "@typescript-eslint/typescript-estree": "8.34.0", + "@typescript-eslint/visitor-keys": "8.34.0", + "debug": "^4.3.4" + }, + "devDependencies": { + "@vitest/coverage-v8": "^3.1.3", + "glob": "*", + "rimraf": "*", + "typescript": "*", + "vitest": "^3.1.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "parser", + "includedScripts": [ + "clean" + ] + } +} diff --git a/node_modules/@typescript-eslint/project-service/LICENSE b/node_modules/@typescript-eslint/project-service/LICENSE new file mode 100644 index 00000000..310a18f8 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/project-service/README.md b/node_modules/@typescript-eslint/project-service/README.md new file mode 100644 index 00000000..cf1a6716 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/project-service` + +> Standalone TypeScript project service wrapper for linting. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/project-service.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/project-service) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/project-service.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/project-service) + +A standalone export of the "Project Service" that powers typed linting for typescript-eslint. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/project-service/dist/createProjectService.d.ts b/node_modules/@typescript-eslint/project-service/dist/createProjectService.d.ts new file mode 100644 index 00000000..1a1b46cc --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/dist/createProjectService.d.ts @@ -0,0 +1,60 @@ +import type { ProjectServiceOptions } from '@typescript-eslint/types'; +import type * as ts from 'typescript/lib/tsserverlibrary'; +/** + * Shortcut type to refer to TypeScript's server ProjectService. + */ +export type TypeScriptProjectService = ts.server.ProjectService; +/** + * A created Project Service instance, as well as metadata on its creation. + */ +export interface ProjectServiceAndMetadata { + /** + * Files allowed to be loaded from the default project, if any were specified. + */ + allowDefaultProject: string[] | undefined; + /** + * The performance.now() timestamp of the last reload of the project service. + */ + lastReloadTimestamp: number; + /** + * The maximum number of files that can be matched by the default project. + */ + maximumDefaultProjectFileMatchCount: number; + /** + * The created TypeScript Project Service instance. + */ + service: TypeScriptProjectService; +} +/** + * Settings to create a new Project Service instance with {@link createProjectService}. + */ +export interface CreateProjectServiceSettings { + /** + * Granular options to configure the project service. + */ + options?: ProjectServiceOptions; + /** + * How aggressively (and slowly) to parse JSDoc comments. + */ + jsDocParsingMode?: ts.JSDocParsingMode; + /** + * Root directory for the tsconfig.json file, if not the current directory. + */ + tsconfigRootDir?: string; +} +/** + * Creates a new Project Service instance, as well as metadata on its creation. + * @param settings Settings to create a new Project Service instance. + * @returns A new Project Service instance, as well as metadata on its creation. + * @example + * ```ts + * import { createProjectService } from '@typescript-eslint/project-service'; + * + * const { service } = createProjectService(); + * + * service.openClientFile('index.ts'); + * ``` + */ +export declare function createProjectService({ jsDocParsingMode, options: optionsRaw, tsconfigRootDir, }?: CreateProjectServiceSettings): ProjectServiceAndMetadata; +export { type ProjectServiceOptions } from '@typescript-eslint/types'; +//# sourceMappingURL=createProjectService.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/project-service/dist/createProjectService.d.ts.map b/node_modules/@typescript-eslint/project-service/dist/createProjectService.d.ts.map new file mode 100644 index 00000000..612c908f --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/dist/createProjectService.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"createProjectService.d.ts","sourceRoot":"","sources":["../src/createProjectService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACtE,OAAO,KAAK,KAAK,EAAE,MAAM,gCAAgC,CAAC;AA4B1D;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC;AAEhE;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,mBAAmB,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;IAE1C;;OAEG;IACH,mBAAmB,EAAE,MAAM,CAAC;IAE5B;;OAEG;IACH,mCAAmC,EAAE,MAAM,CAAC;IAE5C;;OAEG;IACH,OAAO,EAAE,wBAAwB,CAAC;CACnC;AAED;;GAEG;AACH,MAAM,WAAW,4BAA4B;IAC3C;;OAEG;IACH,OAAO,CAAC,EAAE,qBAAqB,CAAC;IAEhC;;OAEG;IACH,gBAAgB,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC;IAEvC;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,gBAAgB,EAChB,OAAO,EAAE,UAAe,EACxB,eAAe,GAChB,GAAE,4BAAiC,GAAG,yBAAyB,CA0H/D;AAED,OAAO,EAAE,KAAK,qBAAqB,EAAE,MAAM,0BAA0B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/project-service/dist/createProjectService.js b/node_modules/@typescript-eslint/project-service/dist/createProjectService.js new file mode 100644 index 00000000..43ddcebe --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/dist/createProjectService.js @@ -0,0 +1,137 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createProjectService = createProjectService; +const debug_1 = __importDefault(require("debug")); +const getParsedConfigFileFromTSServer_js_1 = require("./getParsedConfigFileFromTSServer.js"); +const DEFAULT_PROJECT_MATCHED_FILES_THRESHOLD = 8; +const log = (0, debug_1.default)('typescript-eslint:project-service:createProjectService'); +const logTsserverErr = (0, debug_1.default)('typescript-eslint:project-service:tsserver:err'); +const logTsserverInfo = (0, debug_1.default)('typescript-eslint:project-service:tsserver:info'); +const logTsserverPerf = (0, debug_1.default)('typescript-eslint:project-service:tsserver:perf'); +const logTsserverEvent = (0, debug_1.default)('typescript-eslint:project-service:tsserver:event'); +// For TypeScript APIs that expect a function to be passed in +// eslint-disable-next-line @typescript-eslint/no-empty-function +const doNothing = () => { }; +const createStubFileWatcher = () => ({ + close: doNothing, +}); +/** + * Creates a new Project Service instance, as well as metadata on its creation. + * @param settings Settings to create a new Project Service instance. + * @returns A new Project Service instance, as well as metadata on its creation. + * @example + * ```ts + * import { createProjectService } from '@typescript-eslint/project-service'; + * + * const { service } = createProjectService(); + * + * service.openClientFile('index.ts'); + * ``` + */ +function createProjectService({ jsDocParsingMode, options: optionsRaw = {}, tsconfigRootDir, } = {}) { + const options = { + defaultProject: 'tsconfig.json', + ...optionsRaw, + }; + // We import this lazily to avoid its cost for users who don't use the service + // TODO: Once we drop support for TS<5.3 we can import from "typescript" directly + // eslint-disable-next-line @typescript-eslint/no-require-imports + const tsserver = require('typescript/lib/tsserverlibrary'); + // TODO: see getWatchProgramsForProjects + // We don't watch the disk, we just refer to these when ESLint calls us + // there's a whole separate update pass in maybeInvalidateProgram at the bottom of getWatchProgramsForProjects + // (this "goes nuclear on TypeScript") + const system = { + ...tsserver.sys, + clearImmediate, + clearTimeout, + setImmediate, + setTimeout, + watchDirectory: createStubFileWatcher, + watchFile: createStubFileWatcher, + // We stop loading any TypeScript plugins by default, to prevent them from attaching disk watchers + // See https://github.com/typescript-eslint/typescript-eslint/issues/9905 + ...(!options.loadTypeScriptPlugins && { + require: () => ({ + error: { + message: 'TypeScript plugins are not required when using parserOptions.projectService.', + }, + module: undefined, + }), + }), + }; + const logger = { + close: doNothing, + endGroup: doNothing, + getLogFileName: () => undefined, + // The debug library doesn't use levels without creating a namespace for each. + // Log levels are not passed to the writer so we wouldn't be able to forward + // to a respective namespace. Supporting would require an additional flag for + // granular control. Defaulting to all levels for now. + hasLevel: () => true, + info(s) { + this.msg(s, tsserver.server.Msg.Info); + }, + loggingEnabled: () => + // if none of the debug namespaces are enabled, then don't enable logging in tsserver + logTsserverInfo.enabled || + logTsserverErr.enabled || + logTsserverPerf.enabled, + msg: (s, type) => { + switch (type) { + case tsserver.server.Msg.Err: + logTsserverErr(s); + break; + case tsserver.server.Msg.Perf: + logTsserverPerf(s); + break; + default: + logTsserverInfo(s); + } + }, + perftrc(s) { + this.msg(s, tsserver.server.Msg.Perf); + }, + startGroup: doNothing, + }; + log('Creating Project Service with: %o', options); + const service = new tsserver.server.ProjectService({ + cancellationToken: { isCancellationRequested: () => false }, + eventHandler: logTsserverEvent.enabled + ? (e) => { + logTsserverEvent(e); + } + : undefined, + host: system, + jsDocParsingMode, + logger, + session: undefined, + useInferredProjectPerProjectRoot: false, + useSingleInferredProject: false, + }); + service.setHostConfiguration({ + preferences: { + includePackageJsonAutoImports: 'off', + }, + }); + log('Enabling default project: %s', options.defaultProject); + const configFile = (0, getParsedConfigFileFromTSServer_js_1.getParsedConfigFileFromTSServer)(tsserver, options.defaultProject, !!optionsRaw.defaultProject, tsconfigRootDir); + if (configFile) { + service.setCompilerOptionsForInferredProjects( + // NOTE: The inferred projects API is not intended for source files when a tsconfig + // exists. There is no API that generates an InferredProjectCompilerOptions suggesting + // it is meant for hard coded options passed in. Hard asserting as a work around. + // See https://github.com/microsoft/TypeScript/blob/27bcd4cb5a98bce46c9cdd749752703ead021a4b/src/server/protocol.ts#L1904 + configFile.options); + } + return { + allowDefaultProject: options.allowDefaultProject, + lastReloadTimestamp: performance.now(), + maximumDefaultProjectFileMatchCount: options.maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING ?? + DEFAULT_PROJECT_MATCHED_FILES_THRESHOLD, + service, + }; +} diff --git a/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.d.ts b/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.d.ts new file mode 100644 index 00000000..4ddeb945 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.d.ts @@ -0,0 +1,3 @@ +import type * as ts from 'typescript/lib/tsserverlibrary'; +export declare function getParsedConfigFileFromTSServer(tsserver: typeof ts, defaultProject: string, throwOnFailure: boolean, tsconfigRootDir?: string): ts.ParsedCommandLine | undefined; +//# sourceMappingURL=getParsedConfigFileFromTSServer.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.d.ts.map b/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.d.ts.map new file mode 100644 index 00000000..6aab4b26 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getParsedConfigFileFromTSServer.d.ts","sourceRoot":"","sources":["../src/getParsedConfigFileFromTSServer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,gCAAgC,CAAC;AAI1D,wBAAgB,+BAA+B,CAC7C,QAAQ,EAAE,OAAO,EAAE,EACnB,cAAc,EAAE,MAAM,EACtB,cAAc,EAAE,OAAO,EACvB,eAAe,CAAC,EAAE,MAAM,GACvB,EAAE,CAAC,iBAAiB,GAAG,SAAS,CAYlC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.js b/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.js new file mode 100644 index 00000000..d4451fb5 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/dist/getParsedConfigFileFromTSServer.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getParsedConfigFileFromTSServer = getParsedConfigFileFromTSServer; +const tsconfig_utils_1 = require("@typescript-eslint/tsconfig-utils"); +function getParsedConfigFileFromTSServer(tsserver, defaultProject, throwOnFailure, tsconfigRootDir) { + try { + return (0, tsconfig_utils_1.getParsedConfigFile)(tsserver, defaultProject, tsconfigRootDir); + } + catch (error) { + if (throwOnFailure) { + throw new Error(`Could not read Project Service default project '${defaultProject}': ${error.message}`); + } + } + return undefined; +} diff --git a/node_modules/@typescript-eslint/project-service/dist/index.d.ts b/node_modules/@typescript-eslint/project-service/dist/index.d.ts new file mode 100644 index 00000000..e4f22447 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/dist/index.d.ts @@ -0,0 +1,2 @@ +export * from './createProjectService'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/project-service/dist/index.d.ts.map b/node_modules/@typescript-eslint/project-service/dist/index.d.ts.map new file mode 100644 index 00000000..1d973921 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/project-service/dist/index.js b/node_modules/@typescript-eslint/project-service/dist/index.js new file mode 100644 index 00000000..f574a9b9 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/dist/index.js @@ -0,0 +1,17 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./createProjectService"), exports); diff --git a/node_modules/@typescript-eslint/project-service/package.json b/node_modules/@typescript-eslint/project-service/package.json new file mode 100644 index 00000000..d5c25f23 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/package.json @@ -0,0 +1,69 @@ +{ + "name": "@typescript-eslint/project-service", + "version": "8.34.0", + "description": "Standalone TypeScript project service wrapper for linting.", + "files": [ + "dist", + "!*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/project-service" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "format": "yarn run -T format", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + }, + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.34.0", + "@typescript-eslint/types": "^8.34.0", + "debug": "^4.3.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "publishConfig": { + "access": "public" + }, + "nx": { + "name": "project-service", + "includedScripts": [ + "clean" + ] + } +} diff --git a/node_modules/@typescript-eslint/scope-manager/LICENSE b/node_modules/@typescript-eslint/scope-manager/LICENSE new file mode 100644 index 00000000..a1164108 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/scope-manager/README.md b/node_modules/@typescript-eslint/scope-manager/README.md new file mode 100644 index 00000000..b730e9d8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/README.md @@ -0,0 +1,10 @@ +# `@typescript-eslint/scope-manager` + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/scope-manager.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/scope-manager) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/scope-manager.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/scope-manager) + +👉 See **https://typescript-eslint.io/packages/scope-manager** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/scope-manager/dist/ID.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/ID.d.ts new file mode 100644 index 00000000..3a3f5e08 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/ID.d.ts @@ -0,0 +1,3 @@ +export declare function createIdGenerator(): () => number; +export declare function resetIds(): void; +//# sourceMappingURL=ID.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/ID.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/ID.d.ts.map new file mode 100644 index 00000000..62f8e821 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/ID.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ID.d.ts","sourceRoot":"","sources":["../src/ID.ts"],"names":[],"mappings":"AAGA,wBAAgB,iBAAiB,IAAI,MAAM,MAAM,CAUhD;AAED,wBAAgB,QAAQ,IAAI,IAAI,CAE/B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/ID.js b/node_modules/@typescript-eslint/scope-manager/dist/ID.js new file mode 100644 index 00000000..587fa917 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/ID.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createIdGenerator = createIdGenerator; +exports.resetIds = resetIds; +const ID_CACHE = new Map(); +let NEXT_KEY = 0; +function createIdGenerator() { + const key = (NEXT_KEY += 1); + ID_CACHE.set(key, 0); + return () => { + const current = ID_CACHE.get(key) ?? 0; + const next = current + 1; + ID_CACHE.set(key, next); + return next; + }; +} +function resetIds() { + ID_CACHE.clear(); +} diff --git a/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.d.ts new file mode 100644 index 00000000..c7fc54a0 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.d.ts @@ -0,0 +1,72 @@ +import type { SourceType, TSESTree } from '@typescript-eslint/types'; +import type { Scope } from './scope'; +import type { Variable } from './variable'; +import { BlockScope, CatchScope, ClassScope, ConditionalTypeScope, ForScope, FunctionExpressionNameScope, FunctionScope, FunctionTypeScope, GlobalScope, MappedTypeScope, ModuleScope, SwitchScope, TSEnumScope, TSModuleScope, TypeScope, WithScope } from './scope'; +import { ClassFieldInitializerScope } from './scope/ClassFieldInitializerScope'; +import { ClassStaticBlockScope } from './scope/ClassStaticBlockScope'; +interface ScopeManagerOptions { + globalReturn?: boolean; + impliedStrict?: boolean; + sourceType?: SourceType; +} +/** + * @see https://eslint.org/docs/latest/developer-guide/scope-manager-interface#scopemanager-interface + */ +export declare class ScopeManager { + #private; + currentScope: Scope | null; + readonly declaredVariables: WeakMap; + /** + * The root scope + */ + globalScope: GlobalScope | null; + readonly nodeToScope: WeakMap; + /** + * All scopes + * @public + */ + readonly scopes: Scope[]; + constructor(options: ScopeManagerOptions); + isES6(): boolean; + isGlobalReturn(): boolean; + isImpliedStrict(): boolean; + isModule(): boolean; + isStrictModeSupported(): boolean; + get variables(): Variable[]; + /** + * Get the variables that a given AST node defines. The gotten variables' `def[].node`/`def[].parent` property is the node. + * If the node does not define any variable, this returns an empty array. + * @param node An AST node to get their variables. + */ + getDeclaredVariables(node: TSESTree.Node): Variable[]; + /** + * Get the scope of a given AST node. The gotten scope's `block` property is the node. + * This method never returns `function-expression-name` scope. If the node does not have their scope, this returns `null`. + * + * @param node An AST node to get their scope. + * @param inner If the node has multiple scopes, this returns the outermost scope normally. + * If `inner` is `true` then this returns the innermost scope. + */ + acquire(node: TSESTree.Node, inner?: boolean): Scope | null; + nestBlockScope(node: BlockScope['block']): BlockScope; + nestCatchScope(node: CatchScope['block']): CatchScope; + nestClassFieldInitializerScope(node: ClassFieldInitializerScope['block']): ClassFieldInitializerScope; + nestClassScope(node: ClassScope['block']): ClassScope; + nestClassStaticBlockScope(node: ClassStaticBlockScope['block']): ClassStaticBlockScope; + nestConditionalTypeScope(node: ConditionalTypeScope['block']): ConditionalTypeScope; + nestForScope(node: ForScope['block']): ForScope; + nestFunctionExpressionNameScope(node: FunctionExpressionNameScope['block']): FunctionExpressionNameScope; + nestFunctionScope(node: FunctionScope['block'], isMethodDefinition: boolean): FunctionScope; + nestFunctionTypeScope(node: FunctionTypeScope['block']): FunctionTypeScope; + nestGlobalScope(node: GlobalScope['block']): GlobalScope; + nestMappedTypeScope(node: MappedTypeScope['block']): MappedTypeScope; + nestModuleScope(node: ModuleScope['block']): ModuleScope; + nestSwitchScope(node: SwitchScope['block']): SwitchScope; + nestTSEnumScope(node: TSEnumScope['block']): TSEnumScope; + nestTSModuleScope(node: TSModuleScope['block']): TSModuleScope; + nestTypeScope(node: TypeScope['block']): TypeScope; + nestWithScope(node: WithScope['block']): WithScope; + protected nestScope(scope: T): T; +} +export {}; +//# sourceMappingURL=ScopeManager.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.d.ts.map new file mode 100644 index 00000000..f543d9d3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ScopeManager.d.ts","sourceRoot":"","sources":["../src/ScopeManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAErE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAG3C,OAAO,EACL,UAAU,EACV,UAAU,EACV,UAAU,EACV,oBAAoB,EACpB,QAAQ,EACR,2BAA2B,EAC3B,aAAa,EACb,iBAAi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AE,KAAK,EAAE,CAAC,GAAG,CAAC;CASlD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.js b/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.js new file mode 100644 index 00000000..f78b682a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/ScopeManager.js @@ -0,0 +1,181 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ScopeManager = void 0; +const assert_1 = require("./assert"); +const scope_1 = require("./scope"); +const ClassFieldInitializerScope_1 = require("./scope/ClassFieldInitializerScope"); +const ClassStaticBlockScope_1 = require("./scope/ClassStaticBlockScope"); +/** + * @see https://eslint.org/docs/latest/developer-guide/scope-manager-interface#scopemanager-interface + */ +class ScopeManager { + #options; + currentScope; + declaredVariables; + /** + * The root scope + */ + globalScope; + nodeToScope; + /** + * All scopes + * @public + */ + scopes; + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.nodeToScope = new WeakMap(); + this.currentScope = null; + this.#options = options; + this.declaredVariables = new WeakMap(); + } + isES6() { + return true; + } + isGlobalReturn() { + return this.#options.globalReturn === true; + } + isImpliedStrict() { + return this.#options.impliedStrict === true; + } + isModule() { + return this.#options.sourceType === 'module'; + } + isStrictModeSupported() { + return true; + } + get variables() { + const variables = new Set(); + function recurse(scope) { + scope.variables.forEach(v => variables.add(v)); + scope.childScopes.forEach(recurse); + } + this.scopes.forEach(recurse); + return [...variables].sort((a, b) => a.$id - b.$id); + } + /** + * Get the variables that a given AST node defines. The gotten variables' `def[].node`/`def[].parent` property is the node. + * If the node does not define any variable, this returns an empty array. + * @param node An AST node to get their variables. + */ + getDeclaredVariables(node) { + return this.declaredVariables.get(node) ?? []; + } + /** + * Get the scope of a given AST node. The gotten scope's `block` property is the node. + * This method never returns `function-expression-name` scope. If the node does not have their scope, this returns `null`. + * + * @param node An AST node to get their scope. + * @param inner If the node has multiple scopes, this returns the outermost scope normally. + * If `inner` is `true` then this returns the innermost scope. + */ + acquire(node, inner = false) { + function predicate(testScope) { + if (testScope.type === scope_1.ScopeType.function && + testScope.functionExpressionScope) { + return false; + } + return true; + } + const scopes = this.nodeToScope.get(node); + if (!scopes || scopes.length === 0) { + return null; + } + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } + if (inner) { + for (let i = scopes.length - 1; i >= 0; --i) { + const scope = scopes[i]; + if (predicate(scope)) { + return scope; + } + } + return null; + } + return scopes.find(predicate) ?? null; + } + nestBlockScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.BlockScope(this, this.currentScope, node)); + } + nestCatchScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.CatchScope(this, this.currentScope, node)); + } + nestClassFieldInitializerScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new ClassFieldInitializerScope_1.ClassFieldInitializerScope(this, this.currentScope, node)); + } + nestClassScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.ClassScope(this, this.currentScope, node)); + } + nestClassStaticBlockScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new ClassStaticBlockScope_1.ClassStaticBlockScope(this, this.currentScope, node)); + } + nestConditionalTypeScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.ConditionalTypeScope(this, this.currentScope, node)); + } + nestForScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.ForScope(this, this.currentScope, node)); + } + nestFunctionExpressionNameScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.FunctionExpressionNameScope(this, this.currentScope, node)); + } + nestFunctionScope(node, isMethodDefinition) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.FunctionScope(this, this.currentScope, node, isMethodDefinition)); + } + nestFunctionTypeScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.FunctionTypeScope(this, this.currentScope, node)); + } + nestGlobalScope(node) { + return this.nestScope(new scope_1.GlobalScope(this, node)); + } + nestMappedTypeScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.MappedTypeScope(this, this.currentScope, node)); + } + nestModuleScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.ModuleScope(this, this.currentScope, node)); + } + nestSwitchScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.SwitchScope(this, this.currentScope, node)); + } + nestTSEnumScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.TSEnumScope(this, this.currentScope, node)); + } + nestTSModuleScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.TSModuleScope(this, this.currentScope, node)); + } + nestTypeScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.TypeScope(this, this.currentScope, node)); + } + nestWithScope(node) { + (0, assert_1.assert)(this.currentScope); + return this.nestScope(new scope_1.WithScope(this, this.currentScope, node)); + } + nestScope(scope) { + if (scope instanceof scope_1.GlobalScope) { + (0, assert_1.assert)(this.currentScope == null); + this.globalScope = scope; + } + this.currentScope = scope; + return scope; + } +} +exports.ScopeManager = ScopeManager; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/analyze.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/analyze.d.ts new file mode 100644 index 00000000..907e2392 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/analyze.d.ts @@ -0,0 +1,54 @@ +import type { Lib, SourceType, TSESTree } from '@typescript-eslint/types'; +import type { ReferencerOptions } from './referencer'; +import { ScopeManager } from './ScopeManager'; +export interface AnalyzeOptions { + /** + * Known visitor keys. + */ + childVisitorKeys?: ReferencerOptions['childVisitorKeys']; + /** + * Whether the whole script is executed under node.js environment. + * When enabled, the scope manager adds a function scope immediately following the global scope. + * Defaults to `false`. + */ + globalReturn?: boolean; + /** + * Implied strict mode. + * Defaults to `false`. + */ + impliedStrict?: boolean; + /** + * The identifier that's used for JSX Element creation (after transpilation). + * This should not be a member expression - just the root identifier (i.e. use "React" instead of "React.createElement"). + * Defaults to `"React"`. + */ + jsxPragma?: string | null; + /** + * The identifier that's used for JSX fragment elements (after transpilation). + * If `null`, assumes transpilation will always use a member on `jsxFactory` (i.e. React.Fragment). + * This should not be a member expression - just the root identifier (i.e. use "h" instead of "h.Fragment"). + * Defaults to `null`. + */ + jsxFragmentName?: string | null; + /** + * The lib used by the project. + * This automatically defines a type variable for any types provided by the configured TS libs. + * Defaults to ['esnext']. + * + * https://www.typescriptlang.org/tsconfig#lib + */ + lib?: Lib[]; + /** + * The source type of the script. + */ + sourceType?: SourceType; + /** + * @deprecated This option never did what it was intended for and will be removed in a future major release. + */ + emitDecoratorMetadata?: boolean; +} +/** + * Takes an AST and returns the analyzed scopes. + */ +export declare function analyze(tree: TSESTree.Node, providedOptions?: AnalyzeOptions): ScopeManager; +//# sourceMappingURL=analyze.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/analyze.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/analyze.d.ts.map new file mode 100644 index 00000000..73c73817 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/analyze.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAI1E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAGtD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAM9C,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,gBAAgB,CAAC,EAAE,iBAAiB,CAAC,kBAAkB,CAAC,CAAC;IAEzD;;;;OAIG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IAExB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1B;;;;;OAKG;IACH,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAEhC;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC;IAEZ;;OAEG;IACH,UAAU,CAAC,EAAE,UAAU,CAAC;IAGxB;;OAEG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC;AAaD;;GAEG;AACH,wBAAgB,OAAO,CACrB,IAAI,EAAE,QAAQ,CAAC,IAAI,EACnB,eAAe,CAAC,EAAE,cAAc,GAC/B,YAAY,CA4Bd"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/analyze.js b/node_modules/@typescript-eslint/scope-manager/dist/analyze.js new file mode 100644 index 00000000..dfedd03c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/analyze.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.analyze = analyze; +const visitor_keys_1 = require("@typescript-eslint/visitor-keys"); +const referencer_1 = require("./referencer"); +const ScopeManager_1 = require("./ScopeManager"); +const DEFAULT_OPTIONS = { + childVisitorKeys: visitor_keys_1.visitorKeys, + emitDecoratorMetadata: false, + globalReturn: false, + impliedStrict: false, + jsxFragmentName: null, + jsxPragma: 'React', + lib: ['es2018'], + sourceType: 'script', +}; +/** + * Takes an AST and returns the analyzed scopes. + */ +function analyze(tree, providedOptions) { + const options = { + childVisitorKeys: providedOptions?.childVisitorKeys ?? DEFAULT_OPTIONS.childVisitorKeys, + emitDecoratorMetadata: false, + globalReturn: providedOptions?.globalReturn ?? DEFAULT_OPTIONS.globalReturn, + impliedStrict: providedOptions?.impliedStrict ?? DEFAULT_OPTIONS.impliedStrict, + jsxFragmentName: providedOptions?.jsxFragmentName ?? DEFAULT_OPTIONS.jsxFragmentName, + jsxPragma: + // eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish + providedOptions?.jsxPragma === undefined + ? DEFAULT_OPTIONS.jsxPragma + : providedOptions.jsxPragma, + lib: providedOptions?.lib ?? ['esnext'], + sourceType: providedOptions?.sourceType ?? DEFAULT_OPTIONS.sourceType, + }; + // ensure the option is lower cased + options.lib = options.lib.map(l => l.toLowerCase()); + const scopeManager = new ScopeManager_1.ScopeManager(options); + const referencer = new referencer_1.Referencer(options, scopeManager); + referencer.visit(tree); + return scopeManager; +} diff --git a/node_modules/@typescript-eslint/scope-manager/dist/assert.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/assert.d.ts new file mode 100644 index 00000000..a9a0993a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/assert.d.ts @@ -0,0 +1,2 @@ +export declare function assert(value: unknown, message?: string): asserts value; +//# sourceMappingURL=assert.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/assert.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/assert.d.ts.map new file mode 100644 index 00000000..137bbfaf --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/assert.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"assert.d.ts","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":"AACA,wBAAgB,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAItE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/assert.js b/node_modules/@typescript-eslint/scope-manager/dist/assert.js new file mode 100644 index 00000000..24c3c196 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/assert.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assert = assert; +// the base assert module doesn't use ts assertion syntax +function assert(value, message) { + if (value == null) { + throw new Error(message); + } +} diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.d.ts new file mode 100644 index 00000000..63179a90 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class CatchClauseDefinition extends DefinitionBase { + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + constructor(name: TSESTree.BindingName, node: CatchClauseDefinition['node']); +} +//# sourceMappingURL=CatchClauseDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.d.ts.map new file mode 100644 index 00000000..86b2a6fb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"CatchClauseDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/CatchClauseDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,qBAAsB,SAAQ,cAAc,CACvD,cAAc,CAAC,WAAW,EAC1B,QAAQ,CAAC,WAAW,EACpB,IAAI,EACJ,QAAQ,CAAC,WAAW,CACrB;IACC,SAAgB,gBAAgB,SAAS;IACzC,SAAgB,oBAAoB,QAAQ;gBAEhC,IAAI,EAAE,QAAQ,CAAC,WAAW,EAAE,IAAI,EAAE,qBAAqB,CAAC,MAAM,CAAC;CAG5E"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.js new file mode 100644 index 00000000..a1816c5f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/CatchClauseDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CatchClauseDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class CatchClauseDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = false; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.CatchClause, name, node, null); + } +} +exports.CatchClauseDefinition = CatchClauseDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.d.ts new file mode 100644 index 00000000..3444c9c1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class ClassNameDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: ClassNameDefinition['node']); +} +//# sourceMappingURL=ClassNameDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.d.ts.map new file mode 100644 index 00000000..20a02501 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ClassNameDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/ClassNameDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,mBAAoB,SAAQ,cAAc,CACrD,cAAc,CAAC,SAAS,EACxB,QAAQ,CAAC,gBAAgB,GAAG,QAAQ,CAAC,eAAe,EACpD,IAAI,EACJ,QAAQ,CAAC,UAAU,CACpB;IACC,SAAgB,gBAAgB,QAAQ;IACxC,SAAgB,oBAAoB,QAAQ;gBAEhC,IAAI,EAAE,QAAQ,CAAC,UAAU,EAAE,IAAI,EAAE,mBAAmB,CAAC,MAAM,CAAC;CAGzE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.js new file mode 100644 index 00000000..55e6cc5e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ClassNameDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClassNameDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class ClassNameDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.ClassName, name, node, null); + } +} +exports.ClassNameDefinition = ClassNameDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.d.ts new file mode 100644 index 00000000..82dcbc7d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.d.ts @@ -0,0 +1,13 @@ +import type { CatchClauseDefinition } from './CatchClauseDefinition'; +import type { ClassNameDefinition } from './ClassNameDefinition'; +import type { FunctionNameDefinition } from './FunctionNameDefinition'; +import type { ImplicitGlobalVariableDefinition } from './ImplicitGlobalVariableDefinition'; +import type { ImportBindingDefinition } from './ImportBindingDefinition'; +import type { ParameterDefinition } from './ParameterDefinition'; +import type { TSEnumMemberDefinition } from './TSEnumMemberDefinition'; +import type { TSEnumNameDefinition } from './TSEnumNameDefinition'; +import type { TSModuleNameDefinition } from './TSModuleNameDefinition'; +import type { TypeDefinition } from './TypeDefinition'; +import type { VariableDefinition } from './VariableDefinition'; +export type Definition = CatchClauseDefinition | ClassNameDefinition | FunctionNameDefinition | ImplicitGlobalVariableDefinition | ImportBindingDefinition | ParameterDefinition | TSEnumMemberDefinition | TSEnumNameDefinition | TSModuleNameDefinition | TypeDefinition | VariableDefinition; +//# sourceMappingURL=Definition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.d.ts.map new file mode 100644 index 00000000..5b1588ee --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Definition.d.ts","sourceRoot":"","sources":["../../src/definition/Definition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,oCAAoC,CAAC;AAC3F,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE/D,MAAM,MAAM,UAAU,GAClB,qBAAqB,GACrB,mBAAmB,GACnB,sBAAsB,GACtB,gCAAgC,GAChC,uBAAuB,GACvB,mBAAmB,GACnB,sBAAsB,GACtB,oBAAoB,GACpB,sBAAsB,GACtB,cAAc,GACd,kBAAkB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/Definition.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.d.ts new file mode 100644 index 00000000..9cddc0de --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.d.ts @@ -0,0 +1,34 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { DefinitionType } from './DefinitionType'; +export declare abstract class DefinitionBase { + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + readonly $id: number; + readonly type: Type; + /** + * The `Identifier` node of this definition + * @public + */ + readonly name: Name; + /** + * The enclosing node of the name. + * @public + */ + readonly node: Node; + /** + * the enclosing statement node of the identifier. + * @public + */ + readonly parent: Parent; + constructor(type: Type, name: Name, node: Node, parent: Parent); + /** + * `true` if the variable is valid in a type context, false otherwise + */ + abstract readonly isTypeDefinition: boolean; + /** + * `true` if the variable is valid in a value context, false otherwise + */ + abstract readonly isVariableDefinition: boolean; +} +//# sourceMappingURL=DefinitionBase.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.d.ts.map new file mode 100644 index 00000000..ee26ef44 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"DefinitionBase.d.ts","sourceRoot":"","sources":["../../src/definition/DefinitionBase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAMvD,8BAAsB,cAAc,CAClC,IAAI,SAAS,cAAc,EAC3B,IAAI,SAAS,QAAQ,CAAC,IAAI,EAC1B,MAAM,SAAS,QAAQ,CAAC,IAAI,GAAG,IAAI,EACnC,IAAI,SAAS,QAAQ,CAAC,IAAI;IAE1B;;OAEG;IACH,SAAgB,GAAG,EAAE,MAAM,CAAe;IAE1C,SAAgB,IAAI,EAAE,IAAI,CAAC;IAE3B;;;OAGG;IACH,SAAgB,IAAI,EAAE,IAAI,CAAC;IAE3B;;;OAGG;IACH,SAAgB,IAAI,EAAE,IAAI,CAAC;IAE3B;;;OAGG;IACH,SAAgB,MAAM,EAAE,MAAM,CAAC;gBAEnB,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM;IAO9D;;OAEG;IACH,kBAAyB,gBAAgB,EAAE,OAAO,CAAC;IAEnD;;OAEG;IACH,kBAAyB,oBAAoB,EAAE,OAAO,CAAC;CACxD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.js new file mode 100644 index 00000000..3327b11b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionBase.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefinitionBase = void 0; +const ID_1 = require("../ID"); +const generator = (0, ID_1.createIdGenerator)(); +class DefinitionBase { + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + $id = generator(); + type; + /** + * The `Identifier` node of this definition + * @public + */ + name; + /** + * The enclosing node of the name. + * @public + */ + node; + /** + * the enclosing statement node of the identifier. + * @public + */ + parent; + constructor(type, name, node, parent) { + this.type = type; + this.name = name; + this.node = node; + this.parent = parent; + } +} +exports.DefinitionBase = DefinitionBase; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.d.ts new file mode 100644 index 00000000..67a4bf24 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.d.ts @@ -0,0 +1,14 @@ +export declare enum DefinitionType { + CatchClause = "CatchClause", + ClassName = "ClassName", + FunctionName = "FunctionName", + ImplicitGlobalVariable = "ImplicitGlobalVariable", + ImportBinding = "ImportBinding", + Parameter = "Parameter", + TSEnumName = "TSEnumName", + TSEnumMember = "TSEnumMemberName", + TSModuleName = "TSModuleName", + Type = "Type", + Variable = "Variable" +} +//# sourceMappingURL=DefinitionType.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.d.ts.map new file mode 100644 index 00000000..62946242 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"DefinitionType.d.ts","sourceRoot":"","sources":["../../src/definition/DefinitionType.ts"],"names":[],"mappings":"AAAA,oBAAY,cAAc;IACxB,WAAW,gBAAgB;IAC3B,SAAS,cAAc;IACvB,YAAY,iBAAiB;IAC7B,sBAAsB,2BAA2B;IACjD,aAAa,kBAAkB;IAC/B,SAAS,cAAc;IACvB,UAAU,eAAe;IACzB,YAAY,qBAAqB;IACjC,YAAY,iBAAiB;IAC7B,IAAI,SAAS;IACb,QAAQ,aAAa;CACtB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.js new file mode 100644 index 00000000..1ac31940 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/DefinitionType.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefinitionType = void 0; +var DefinitionType; +(function (DefinitionType) { + DefinitionType["CatchClause"] = "CatchClause"; + DefinitionType["ClassName"] = "ClassName"; + DefinitionType["FunctionName"] = "FunctionName"; + DefinitionType["ImplicitGlobalVariable"] = "ImplicitGlobalVariable"; + DefinitionType["ImportBinding"] = "ImportBinding"; + DefinitionType["Parameter"] = "Parameter"; + DefinitionType["TSEnumName"] = "TSEnumName"; + DefinitionType["TSEnumMember"] = "TSEnumMemberName"; + DefinitionType["TSModuleName"] = "TSModuleName"; + DefinitionType["Type"] = "Type"; + DefinitionType["Variable"] = "Variable"; +})(DefinitionType || (exports.DefinitionType = DefinitionType = {})); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.d.ts new file mode 100644 index 00000000..0de0535a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class FunctionNameDefinition extends DefinitionBase { + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: FunctionNameDefinition['node']); +} +//# sourceMappingURL=FunctionNameDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.d.ts.map new file mode 100644 index 00000000..17faaaa4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionNameDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/FunctionNameDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,sBAAuB,SAAQ,cAAc,CACxD,cAAc,CAAC,YAAY,EACzB,QAAQ,CAAC,mBAAmB,GAC5B,QAAQ,CAAC,kBAAkB,GAC3B,QAAQ,CAAC,iBAAiB,GAC1B,QAAQ,CAAC,6BAA6B,EACxC,IAAI,EACJ,QAAQ,CAAC,UAAU,CACpB;IACC,SAAgB,gBAAgB,SAAS;IACzC,SAAgB,oBAAoB,QAAQ;gBAEhC,IAAI,EAAE,QAAQ,CAAC,UAAU,EAAE,IAAI,EAAE,sBAAsB,CAAC,MAAM,CAAC;CAG5E"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.js new file mode 100644 index 00000000..ed7998d5 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/FunctionNameDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionNameDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class FunctionNameDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = false; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.FunctionName, name, node, null); + } +} +exports.FunctionNameDefinition = FunctionNameDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.d.ts new file mode 100644 index 00000000..18411a4c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class ImplicitGlobalVariableDefinition extends DefinitionBase { + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + constructor(name: TSESTree.BindingName, node: ImplicitGlobalVariableDefinition['node']); +} +//# sourceMappingURL=ImplicitGlobalVariableDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.d.ts.map new file mode 100644 index 00000000..c17e8486 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ImplicitGlobalVariableDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/ImplicitGlobalVariableDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,gCAAiC,SAAQ,cAAc,CAClE,cAAc,CAAC,sBAAsB,EACrC,QAAQ,CAAC,IAAI,EACb,IAAI,EACJ,QAAQ,CAAC,WAAW,CACrB;IACC,SAAgB,gBAAgB,SAAS;IACzC,SAAgB,oBAAoB,QAAQ;gBAG1C,IAAI,EAAE,QAAQ,CAAC,WAAW,EAC1B,IAAI,EAAE,gCAAgC,CAAC,MAAM,CAAC;CAIjD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.js new file mode 100644 index 00000000..f48182db --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImplicitGlobalVariableDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ImplicitGlobalVariableDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class ImplicitGlobalVariableDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = false; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.ImplicitGlobalVariable, name, node, null); + } +} +exports.ImplicitGlobalVariableDefinition = ImplicitGlobalVariableDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.d.ts new file mode 100644 index 00000000..56dc95ed --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.d.ts @@ -0,0 +1,10 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class ImportBindingDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: TSESTree.TSImportEqualsDeclaration, decl: TSESTree.TSImportEqualsDeclaration); + constructor(name: TSESTree.Identifier, node: Exclude, decl: TSESTree.ImportDeclaration); +} +//# sourceMappingURL=ImportBindingDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.d.ts.map new file mode 100644 index 00000000..25ac83b4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ImportBindingDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/ImportBindingDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,uBAAwB,SAAQ,cAAc,CACzD,cAAc,CAAC,aAAa,EAC1B,QAAQ,CAAC,sBAAsB,GAC/B,QAAQ,CAAC,wBAAwB,GACjC,QAAQ,CAAC,eAAe,GACxB,QAAQ,CAAC,yBAAyB,EACpC,QAAQ,CAAC,iBAAiB,GAAG,QAAQ,CAAC,yBAAyB,EAC/D,QAAQ,CAAC,UAAU,CACpB;IACC,SAAgB,gBAAgB,QAAQ;IACxC,SAAgB,oBAAoB,QAAQ;gBAG1C,IAAI,EAAE,QAAQ,CAAC,UAAU,EACzB,IAAI,EAAE,QAAQ,CAAC,yBAAyB,EACxC,IAAI,EAAE,QAAQ,CAAC,yBAAyB;gBAGxC,IAAI,EAAE,QAAQ,CAAC,UAAU,EACzB,IAAI,EAAE,OAAO,CACX,uBAAuB,CAAC,MAAM,CAAC,EAC/B,QAAQ,CAAC,yBAAyB,CACnC,EACD,IAAI,EAAE,QAAQ,CAAC,iBAAiB;CASnC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.js new file mode 100644 index 00000000..e5407f31 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ImportBindingDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ImportBindingDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class ImportBindingDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node, decl) { + super(DefinitionType_1.DefinitionType.ImportBinding, name, node, decl); + } +} +exports.ImportBindingDefinition = ImportBindingDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.d.ts new file mode 100644 index 00000000..3d6e4592 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.d.ts @@ -0,0 +1,13 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class ParameterDefinition extends DefinitionBase { + /** + * Whether the parameter definition is a part of a rest parameter. + */ + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + readonly rest: boolean; + constructor(name: TSESTree.BindingName, node: ParameterDefinition['node'], rest: boolean); +} +//# sourceMappingURL=ParameterDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.d.ts.map new file mode 100644 index 00000000..bcdbf7bf --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ParameterDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/ParameterDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,mBAAoB,SAAQ,cAAc,CACrD,cAAc,CAAC,SAAS,EACtB,QAAQ,CAAC,uBAAuB,GAChC,QAAQ,CAAC,mBAAmB,GAC5B,QAAQ,CAAC,kBAAkB,GAC3B,QAAQ,CAAC,0BAA0B,GACnC,QAAQ,CAAC,iBAAiB,GAC1B,QAAQ,CAAC,+BAA+B,GACxC,QAAQ,CAAC,iBAAiB,GAC1B,QAAQ,CAAC,6BAA6B,GACtC,QAAQ,CAAC,cAAc,GACvB,QAAQ,CAAC,iBAAiB,EAC5B,IAAI,EACJ,QAAQ,CAAC,WAAW,CACrB;IACC;;OAEG;IACH,SAAgB,gBAAgB,SAAS;IACzC,SAAgB,oBAAoB,QAAQ;IAC5C,SAAgB,IAAI,EAAE,OAAO,CAAC;gBAG5B,IAAI,EAAE,QAAQ,CAAC,WAAW,EAC1B,IAAI,EAAE,mBAAmB,CAAC,MAAM,CAAC,EACjC,IAAI,EAAE,OAAO;CAKhB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.js new file mode 100644 index 00000000..81a48951 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/ParameterDefinition.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ParameterDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class ParameterDefinition extends DefinitionBase_1.DefinitionBase { + /** + * Whether the parameter definition is a part of a rest parameter. + */ + isTypeDefinition = false; + isVariableDefinition = true; + rest; + constructor(name, node, rest) { + super(DefinitionType_1.DefinitionType.Parameter, name, node, null); + this.rest = rest; + } +} +exports.ParameterDefinition = ParameterDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.d.ts new file mode 100644 index 00000000..b1009bd8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class TSEnumMemberDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier | TSESTree.StringLiteral, node: TSEnumMemberDefinition['node']); +} +//# sourceMappingURL=TSEnumMemberDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.d.ts.map new file mode 100644 index 00000000..86e58b80 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TSEnumMemberDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/TSEnumMemberDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,sBAAuB,SAAQ,cAAc,CACxD,cAAc,CAAC,YAAY,EAC3B,QAAQ,CAAC,YAAY,EACrB,IAAI,EACJ,QAAQ,CAAC,UAAU,GAAG,QAAQ,CAAC,aAAa,CAC7C;IACC,SAAgB,gBAAgB,QAAQ;IACxC,SAAgB,oBAAoB,QAAQ;gBAG1C,IAAI,EAAE,QAAQ,CAAC,UAAU,GAAG,QAAQ,CAAC,aAAa,EAClD,IAAI,EAAE,sBAAsB,CAAC,MAAM,CAAC;CAIvC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.js new file mode 100644 index 00000000..c6da1904 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumMemberDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSEnumMemberDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class TSEnumMemberDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.TSEnumMember, name, node, null); + } +} +exports.TSEnumMemberDefinition = TSEnumMemberDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.d.ts new file mode 100644 index 00000000..2e3617b7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class TSEnumNameDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: TSEnumNameDefinition['node']); +} +//# sourceMappingURL=TSEnumNameDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.d.ts.map new file mode 100644 index 00000000..2687ea2f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TSEnumNameDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/TSEnumNameDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,oBAAqB,SAAQ,cAAc,CACtD,cAAc,CAAC,UAAU,EACzB,QAAQ,CAAC,iBAAiB,EAC1B,IAAI,EACJ,QAAQ,CAAC,UAAU,CACpB;IACC,SAAgB,gBAAgB,QAAQ;IACxC,SAAgB,oBAAoB,QAAQ;gBAEhC,IAAI,EAAE,QAAQ,CAAC,UAAU,EAAE,IAAI,EAAE,oBAAoB,CAAC,MAAM,CAAC;CAG1E"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.js new file mode 100644 index 00000000..d5453d26 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSEnumNameDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSEnumNameDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class TSEnumNameDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.TSEnumName, name, node, null); + } +} +exports.TSEnumNameDefinition = TSEnumNameDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.d.ts new file mode 100644 index 00000000..750249a7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class TSModuleNameDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: TSModuleNameDefinition['node']); +} +//# sourceMappingURL=TSModuleNameDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.d.ts.map new file mode 100644 index 00000000..da414877 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TSModuleNameDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/TSModuleNameDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,sBAAuB,SAAQ,cAAc,CACxD,cAAc,CAAC,YAAY,EAC3B,QAAQ,CAAC,mBAAmB,EAC5B,IAAI,EACJ,QAAQ,CAAC,UAAU,CACpB;IACC,SAAgB,gBAAgB,QAAQ;IACxC,SAAgB,oBAAoB,QAAQ;gBAEhC,IAAI,EAAE,QAAQ,CAAC,UAAU,EAAE,IAAI,EAAE,sBAAsB,CAAC,MAAM,CAAC;CAG5E"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.js new file mode 100644 index 00000000..93fb8470 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TSModuleNameDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSModuleNameDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class TSModuleNameDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = true; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.TSModuleName, name, node, null); + } +} +exports.TSModuleNameDefinition = TSModuleNameDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.d.ts new file mode 100644 index 00000000..67d1085f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class TypeDefinition extends DefinitionBase { + readonly isTypeDefinition = true; + readonly isVariableDefinition = false; + constructor(name: TSESTree.Identifier, node: TypeDefinition['node']); +} +//# sourceMappingURL=TypeDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.d.ts.map new file mode 100644 index 00000000..d7803866 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TypeDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/TypeDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,cAAe,SAAQ,cAAc,CAChD,cAAc,CAAC,IAAI,EACjB,QAAQ,CAAC,sBAAsB,GAC/B,QAAQ,CAAC,YAAY,GACrB,QAAQ,CAAC,sBAAsB,GAC/B,QAAQ,CAAC,eAAe,EAC1B,IAAI,EACJ,QAAQ,CAAC,UAAU,CACpB;IACC,SAAgB,gBAAgB,QAAQ;IACxC,SAAgB,oBAAoB,SAAS;gBAEjC,IAAI,EAAE,QAAQ,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,MAAM,CAAC;CAGpE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.js new file mode 100644 index 00000000..2966fde9 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/TypeDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class TypeDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = true; + isVariableDefinition = false; + constructor(name, node) { + super(DefinitionType_1.DefinitionType.Type, name, node, null); + } +} +exports.TypeDefinition = TypeDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts new file mode 100644 index 00000000..200b9158 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { DefinitionBase } from './DefinitionBase'; +import { DefinitionType } from './DefinitionType'; +export declare class VariableDefinition extends DefinitionBase { + readonly isTypeDefinition = false; + readonly isVariableDefinition = true; + constructor(name: TSESTree.Identifier, node: VariableDefinition['node'], decl: TSESTree.VariableDeclaration); +} +//# sourceMappingURL=VariableDefinition.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts.map new file mode 100644 index 00000000..7957c3fb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"VariableDefinition.d.ts","sourceRoot":"","sources":["../../src/definition/VariableDefinition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,kBAAmB,SAAQ,cAAc,CACpD,cAAc,CAAC,QAAQ,EACvB,QAAQ,CAAC,kBAAkB,EAC3B,QAAQ,CAAC,mBAAmB,EAC5B,QAAQ,CAAC,UAAU,CACpB;IACC,SAAgB,gBAAgB,SAAS;IACzC,SAAgB,oBAAoB,QAAQ;gBAG1C,IAAI,EAAE,QAAQ,CAAC,UAAU,EACzB,IAAI,EAAE,kBAAkB,CAAC,MAAM,CAAC,EAChC,IAAI,EAAE,QAAQ,CAAC,mBAAmB;CAIrC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.js new file mode 100644 index 00000000..fc30f838 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VariableDefinition = void 0; +const DefinitionBase_1 = require("./DefinitionBase"); +const DefinitionType_1 = require("./DefinitionType"); +class VariableDefinition extends DefinitionBase_1.DefinitionBase { + isTypeDefinition = false; + isVariableDefinition = true; + constructor(name, node, decl) { + super(DefinitionType_1.DefinitionType.Variable, name, node, decl); + } +} +exports.VariableDefinition = VariableDefinition; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/index.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/definition/index.d.ts new file mode 100644 index 00000000..2be95a12 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/index.d.ts @@ -0,0 +1,14 @@ +export * from './CatchClauseDefinition'; +export * from './ClassNameDefinition'; +export * from './Definition'; +export * from './DefinitionType'; +export * from './FunctionNameDefinition'; +export * from './ImplicitGlobalVariableDefinition'; +export * from './ImportBindingDefinition'; +export * from './ParameterDefinition'; +export * from './TSEnumMemberDefinition'; +export * from './TSEnumNameDefinition'; +export * from './TSModuleNameDefinition'; +export * from './TypeDefinition'; +export * from './VariableDefinition'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/index.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/definition/index.d.ts.map new file mode 100644 index 00000000..dfd43be8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/definition/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,0BAA0B,CAAC;AACzC,cAAc,oCAAoC,CAAC;AACnD,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,0BAA0B,CAAC;AACzC,cAAc,wBAAwB,CAAC;AACvC,cAAc,0BAA0B,CAAC;AACzC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/definition/index.js b/node_modules/@typescript-eslint/scope-manager/dist/definition/index.js new file mode 100644 index 00000000..67fad66b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/definition/index.js @@ -0,0 +1,29 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./CatchClauseDefinition"), exports); +__exportStar(require("./ClassNameDefinition"), exports); +__exportStar(require("./Definition"), exports); +__exportStar(require("./DefinitionType"), exports); +__exportStar(require("./FunctionNameDefinition"), exports); +__exportStar(require("./ImplicitGlobalVariableDefinition"), exports); +__exportStar(require("./ImportBindingDefinition"), exports); +__exportStar(require("./ParameterDefinition"), exports); +__exportStar(require("./TSEnumMemberDefinition"), exports); +__exportStar(require("./TSEnumNameDefinition"), exports); +__exportStar(require("./TSModuleNameDefinition"), exports); +__exportStar(require("./TypeDefinition"), exports); +__exportStar(require("./VariableDefinition"), exports); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/index.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/index.d.ts new file mode 100644 index 00000000..435c05cc --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/index.d.ts @@ -0,0 +1,9 @@ +export { analyze, type AnalyzeOptions } from './analyze'; +export * from './definition'; +export { PatternVisitor, type PatternVisitorCallback, type PatternVisitorOptions, } from './referencer/PatternVisitor'; +export { Reference } from './referencer/Reference'; +export { Visitor } from './referencer/Visitor'; +export * from './scope'; +export { ScopeManager } from './ScopeManager'; +export * from './variable'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/index.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/index.d.ts.map new file mode 100644 index 00000000..dd3d5544 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AACzD,cAAc,cAAc,CAAC;AAC7B,OAAO,EACL,cAAc,EACd,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,GAC3B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC/C,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,cAAc,YAAY,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/index.js b/node_modules/@typescript-eslint/scope-manager/dist/index.js new file mode 100644 index 00000000..3ecc7a33 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/index.js @@ -0,0 +1,30 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ScopeManager = exports.Visitor = exports.Reference = exports.PatternVisitor = exports.analyze = void 0; +var analyze_1 = require("./analyze"); +Object.defineProperty(exports, "analyze", { enumerable: true, get: function () { return analyze_1.analyze; } }); +__exportStar(require("./definition"), exports); +var PatternVisitor_1 = require("./referencer/PatternVisitor"); +Object.defineProperty(exports, "PatternVisitor", { enumerable: true, get: function () { return PatternVisitor_1.PatternVisitor; } }); +var Reference_1 = require("./referencer/Reference"); +Object.defineProperty(exports, "Reference", { enumerable: true, get: function () { return Reference_1.Reference; } }); +var Visitor_1 = require("./referencer/Visitor"); +Object.defineProperty(exports, "Visitor", { enumerable: true, get: function () { return Visitor_1.Visitor; } }); +__exportStar(require("./scope"), exports); +var ScopeManager_1 = require("./ScopeManager"); +Object.defineProperty(exports, "ScopeManager", { enumerable: true, get: function () { return ScopeManager_1.ScopeManager; } }); +__exportStar(require("./variable"), exports); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.d.ts new file mode 100644 index 00000000..6b2fddaa --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.d.ts @@ -0,0 +1,16 @@ +export declare const TYPE: Readonly<{ + eslintImplicitGlobalSetting: "readonly"; + isTypeVariable: true; + isValueVariable: false; +}>; +export declare const VALUE: Readonly<{ + eslintImplicitGlobalSetting: "readonly"; + isTypeVariable: false; + isValueVariable: true; +}>; +export declare const TYPE_VALUE: Readonly<{ + eslintImplicitGlobalSetting: "readonly"; + isTypeVariable: true; + isValueVariable: true; +}>; +//# sourceMappingURL=base-config.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.d.ts.map new file mode 100644 index 00000000..632981a2 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"base-config.d.ts","sourceRoot":"","sources":["../../src/lib/base-config.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,IAAI;;;;EAIf,CAAC;AACH,eAAO,MAAM,KAAK;;;;EAIhB,CAAC;AACH,eAAO,MAAM,UAAU;;;;EAIrB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.js new file mode 100644 index 00000000..52febf4e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/base-config.js @@ -0,0 +1,22 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TYPE_VALUE = exports.VALUE = exports.TYPE = void 0; +exports.TYPE = Object.freeze({ + eslintImplicitGlobalSetting: 'readonly', + isTypeVariable: true, + isValueVariable: false, +}); +exports.VALUE = Object.freeze({ + eslintImplicitGlobalSetting: 'readonly', + isTypeVariable: false, + isValueVariable: true, +}); +exports.TYPE_VALUE = Object.freeze({ + eslintImplicitGlobalSetting: 'readonly', + isTypeVariable: true, + isValueVariable: true, +}); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.d.ts new file mode 100644 index 00000000..5b5ee98f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const decorators: LibDefinition; +//# sourceMappingURL=decorators.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.d.ts.map new file mode 100644 index 00000000..7135f0ae --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../../src/lib/decorators.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,UAAU,EAAE,aAgBxB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.js new file mode 100644 index 00000000..4b8c452b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.js @@ -0,0 +1,25 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decorators = void 0; +const base_config_1 = require("./base-config"); +exports.decorators = { + libs: [], + variables: [ + ['ClassMemberDecoratorContext', base_config_1.TYPE], + ['DecoratorContext', base_config_1.TYPE], + ['DecoratorMetadataObject', base_config_1.TYPE], + ['DecoratorMetadata', base_config_1.TYPE], + ['ClassDecoratorContext', base_config_1.TYPE], + ['ClassMethodDecoratorContext', base_config_1.TYPE], + ['ClassGetterDecoratorContext', base_config_1.TYPE], + ['ClassSetterDecoratorContext', base_config_1.TYPE], + ['ClassAccessorDecoratorContext', base_config_1.TYPE], + ['ClassAccessorDecoratorTarget', base_config_1.TYPE], + ['ClassAccessorDecoratorResult', base_config_1.TYPE], + ['ClassFieldDecoratorContext', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.d.ts new file mode 100644 index 00000000..7db863ea --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const decorators_legacy: LibDefinition; +//# sourceMappingURL=decorators.legacy.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.d.ts.map new file mode 100644 index 00000000..3da556ae --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decorators.legacy.d.ts","sourceRoot":"","sources":["../../src/lib/decorators.legacy.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,iBAAiB,EAAE,aAQ/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.js new file mode 100644 index 00000000..c6c196d6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/decorators.legacy.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decorators_legacy = void 0; +const base_config_1 = require("./base-config"); +exports.decorators_legacy = { + libs: [], + variables: [ + ['ClassDecorator', base_config_1.TYPE], + ['PropertyDecorator', base_config_1.TYPE], + ['MethodDecorator', base_config_1.TYPE], + ['ParameterDecorator', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.d.ts new file mode 100644 index 00000000..b4a0f0a1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const dom_asynciterable: LibDefinition; +//# sourceMappingURL=dom.asynciterable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.d.ts.map new file mode 100644 index 00000000..2af9e908 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dom.asynciterable.d.ts","sourceRoot":"","sources":["../../src/lib/dom.asynciterable.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,iBAAiB,EAAE,aAQ/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.js new file mode 100644 index 00000000..29fb89d0 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.asynciterable.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dom_asynciterable = void 0; +const base_config_1 = require("./base-config"); +exports.dom_asynciterable = { + libs: [], + variables: [ + ['FileSystemDirectoryHandleAsyncIterator', base_config_1.TYPE], + ['FileSystemDirectoryHandle', base_config_1.TYPE], + ['ReadableStreamAsyncIterator', base_config_1.TYPE], + ['ReadableStream', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.d.ts new file mode 100644 index 00000000..19864cec --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const dom: LibDefinition; +//# sourceMappingURL=dom.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.d.ts.map new file mode 100644 index 00000000..9d459fe1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dom.d.ts","sourceRoot":"","sources":["../../src/lib/dom.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,GAAG,EAAE,aAy+CjB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.d.ts new file mode 100644 index 00000000..b9cd1137 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const dom_iterable: LibDefinition; +//# sourceMappingURL=dom.iterable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.d.ts.map new file mode 100644 index 00000000..47fdbd4d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dom.iterable.d.ts","sourceRoot":"","sources":["../../src/lib/dom.iterable.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,YAAY,EAAE,aA8E1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.js new file mode 100644 index 00000000..2f8b9d62 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.iterable.js @@ -0,0 +1,87 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dom_iterable = void 0; +const base_config_1 = require("./base-config"); +exports.dom_iterable = { + libs: [], + variables: [ + ['AudioParam', base_config_1.TYPE], + ['AudioParamMap', base_config_1.TYPE], + ['BaseAudioContext', base_config_1.TYPE], + ['CSSKeyframesRule', base_config_1.TYPE], + ['CSSNumericArray', base_config_1.TYPE], + ['CSSRuleList', base_config_1.TYPE], + ['CSSStyleDeclaration', base_config_1.TYPE], + ['CSSTransformValue', base_config_1.TYPE], + ['CSSUnparsedValue', base_config_1.TYPE], + ['Cache', base_config_1.TYPE], + ['CanvasPath', base_config_1.TYPE], + ['CanvasPathDrawingStyles', base_config_1.TYPE], + ['CustomStateSet', base_config_1.TYPE], + ['DOMRectList', base_config_1.TYPE], + ['DOMStringList', base_config_1.TYPE], + ['DOMTokenList', base_config_1.TYPE], + ['DataTransferItemList', base_config_1.TYPE], + ['EventCounts', base_config_1.TYPE], + ['FileList', base_config_1.TYPE], + ['FontFaceSet', base_config_1.TYPE], + ['FormDataIterator', base_config_1.TYPE], + ['FormData', base_config_1.TYPE], + ['HTMLAllCollection', base_config_1.TYPE], + ['HTMLCollectionBase', base_config_1.TYPE], + ['HTMLCollectionOf', base_config_1.TYPE], + ['HTMLFormElement', base_config_1.TYPE], + ['HTMLSelectElement', base_config_1.TYPE], + ['HeadersIterator', base_config_1.TYPE], + ['Headers', base_config_1.TYPE], + ['Highlight', base_config_1.TYPE], + ['HighlightRegistry', base_config_1.TYPE], + ['IDBDatabase', base_config_1.TYPE], + ['IDBObjectStore', base_config_1.TYPE], + ['ImageTrackList', base_config_1.TYPE], + ['MIDIInputMap', base_config_1.TYPE], + ['MIDIOutput', base_config_1.TYPE], + ['MIDIOutputMap', base_config_1.TYPE], + ['MediaKeyStatusMapIterator', base_config_1.TYPE], + ['MediaKeyStatusMap', base_config_1.TYPE], + ['MediaList', base_config_1.TYPE], + ['MessageEvent', base_config_1.TYPE], + ['MimeTypeArray', base_config_1.TYPE], + ['NamedNodeMap', base_config_1.TYPE], + ['Navigator', base_config_1.TYPE], + ['NodeList', base_config_1.TYPE], + ['NodeListOf', base_config_1.TYPE], + ['Plugin', base_config_1.TYPE], + ['PluginArray', base_config_1.TYPE], + ['RTCRtpTransceiver', base_config_1.TYPE], + ['RTCStatsReport', base_config_1.TYPE], + ['SVGLengthList', base_config_1.TYPE], + ['SVGNumberList', base_config_1.TYPE], + ['SVGPointList', base_config_1.TYPE], + ['SVGStringList', base_config_1.TYPE], + ['SVGTransformList', base_config_1.TYPE], + ['SourceBufferList', base_config_1.TYPE], + ['SpeechRecognitionResult', base_config_1.TYPE], + ['SpeechRecognitionResultList', base_config_1.TYPE], + ['StylePropertyMapReadOnlyIterator', base_config_1.TYPE], + ['StylePropertyMapReadOnly', base_config_1.TYPE], + ['StyleSheetList', base_config_1.TYPE], + ['SubtleCrypto', base_config_1.TYPE], + ['TextTrackCueList', base_config_1.TYPE], + ['TextTrackList', base_config_1.TYPE], + ['TouchList', base_config_1.TYPE], + ['URLSearchParamsIterator', base_config_1.TYPE], + ['URLSearchParams', base_config_1.TYPE], + ['ViewTransitionTypeSet', base_config_1.TYPE], + ['WEBGL_draw_buffers', base_config_1.TYPE], + ['WEBGL_multi_draw', base_config_1.TYPE], + ['WebGL2RenderingContextBase', base_config_1.TYPE], + ['WebGL2RenderingContextOverloads', base_config_1.TYPE], + ['WebGLRenderingContextBase', base_config_1.TYPE], + ['WebGLRenderingContextOverloads', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.js new file mode 100644 index 00000000..0997d6aa --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/dom.js @@ -0,0 +1,1522 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dom = void 0; +const base_config_1 = require("./base-config"); +exports.dom = { + libs: [], + variables: [ + ['AddEventListenerOptions', base_config_1.TYPE], + ['AddressErrors', base_config_1.TYPE], + ['AesCbcParams', base_config_1.TYPE], + ['AesCtrParams', base_config_1.TYPE], + ['AesDerivedKeyParams', base_config_1.TYPE], + ['AesGcmParams', base_config_1.TYPE], + ['AesKeyAlgorithm', base_config_1.TYPE], + ['AesKeyGenParams', base_config_1.TYPE], + ['Algorithm', base_config_1.TYPE], + ['AnalyserOptions', base_config_1.TYPE], + ['AnimationEventInit', base_config_1.TYPE], + ['AnimationPlaybackEventInit', base_config_1.TYPE], + ['AssignedNodesOptions', base_config_1.TYPE], + ['AudioBufferOptions', base_config_1.TYPE], + ['AudioBufferSourceOptions', base_config_1.TYPE], + ['AudioConfiguration', base_config_1.TYPE], + ['AudioContextOptions', base_config_1.TYPE], + ['AudioDataCopyToOptions', base_config_1.TYPE], + ['AudioDataInit', base_config_1.TYPE], + ['AudioDecoderConfig', base_config_1.TYPE], + ['AudioDecoderInit', base_config_1.TYPE], + ['AudioDecoderSupport', base_config_1.TYPE], + ['AudioEncoderConfig', base_config_1.TYPE], + ['AudioEncoderInit', base_config_1.TYPE], + ['AudioEncoderSupport', base_config_1.TYPE], + ['AudioNodeOptions', base_config_1.TYPE], + ['AudioProcessingEventInit', base_config_1.TYPE], + ['AudioTimestamp', base_config_1.TYPE], + ['AudioWorkletNodeOptions', base_config_1.TYPE], + ['AuthenticationExtensionsClientInputs', base_config_1.TYPE], + ['AuthenticationExtensionsClientInputsJSON', base_config_1.TYPE], + ['AuthenticationExtensionsClientOutputs', base_config_1.TYPE], + ['AuthenticationExtensionsPRFInputs', base_config_1.TYPE], + ['AuthenticationExtensionsPRFOutputs', base_config_1.TYPE], + ['AuthenticationExtensionsPRFValues', base_config_1.TYPE], + ['AuthenticatorSelectionCriteria', base_config_1.TYPE], + ['AvcEncoderConfig', base_config_1.TYPE], + ['BiquadFilterOptions', base_config_1.TYPE], + ['BlobEventInit', base_config_1.TYPE], + ['BlobPropertyBag', base_config_1.TYPE], + ['CSSMatrixComponentOptions', base_config_1.TYPE], + ['CSSNumericType', base_config_1.TYPE], + ['CSSStyleSheetInit', base_config_1.TYPE], + ['CacheQueryOptions', base_config_1.TYPE], + ['CanvasRenderingContext2DSettings', base_config_1.TYPE], + ['CaretPositionFromPointOptions', base_config_1.TYPE], + ['ChannelMergerOptions', base_config_1.TYPE], + ['ChannelSplitterOptions', base_config_1.TYPE], + ['CheckVisibilityOptions', base_config_1.TYPE], + ['ClientQueryOptions', base_config_1.TYPE], + ['ClipboardEventInit', base_config_1.TYPE], + ['ClipboardItemOptions', base_config_1.TYPE], + ['CloseEventInit', base_config_1.TYPE], + ['CompositionEventInit', base_config_1.TYPE], + ['ComputedEffectTiming', base_config_1.TYPE], + ['ComputedKeyframe', base_config_1.TYPE], + ['ConstantSourceOptions', base_config_1.TYPE], + ['ConstrainBooleanParameters', base_config_1.TYPE], + ['ConstrainDOMStringParameters', base_config_1.TYPE], + ['ConstrainDoubleRange', base_config_1.TYPE], + ['ConstrainULongRange', base_config_1.TYPE], + ['ContentVisibilityAutoStateChangeEventInit', base_config_1.TYPE], + ['ConvolverOptions', base_config_1.TYPE], + ['CredentialCreationOptions', base_config_1.TYPE], + ['CredentialPropertiesOutput', base_config_1.TYPE], + ['CredentialRequestOptions', base_config_1.TYPE], + ['CryptoKeyPair', base_config_1.TYPE], + ['CustomEventInit', base_config_1.TYPE], + ['DOMMatrix2DInit', base_config_1.TYPE], + ['DOMMatrixInit', base_config_1.TYPE], + ['DOMPointInit', base_config_1.TYPE], + ['DOMQuadInit', base_config_1.TYPE], + ['DOMRectInit', base_config_1.TYPE], + ['DelayOptions', base_config_1.TYPE], + ['DeviceMotionEventAccelerationInit', base_config_1.TYPE], + ['DeviceMotionEventInit', base_config_1.TYPE], + ['DeviceMotionEventRotationRateInit', base_config_1.TYPE], + ['DeviceOrientationEventInit', base_config_1.TYPE], + ['DisplayMediaStreamOptions', base_config_1.TYPE], + ['DocumentTimelineOptions', base_config_1.TYPE], + ['DoubleRange', base_config_1.TYPE], + ['DragEventInit', base_config_1.TYPE], + ['DynamicsCompressorOptions', base_config_1.TYPE], + ['EcKeyAlgorithm', base_config_1.TYPE], + ['EcKeyGenParams', base_config_1.TYPE], + ['EcKeyImportParams', base_config_1.TYPE], + ['EcdhKeyDeriveParams', base_config_1.TYPE], + ['EcdsaParams', base_config_1.TYPE], + ['EffectTiming', base_config_1.TYPE], + ['ElementCreationOptions', base_config_1.TYPE], + ['ElementDefinitionOptions', base_config_1.TYPE], + ['EncodedAudioChunkInit', base_config_1.TYPE], + ['EncodedAudioChunkMetadata', base_config_1.TYPE], + ['EncodedVideoChunkInit', base_config_1.TYPE], + ['EncodedVideoChunkMetadata', base_config_1.TYPE], + ['ErrorEventInit', base_config_1.TYPE], + ['EventInit', base_config_1.TYPE], + ['EventListenerOptions', base_config_1.TYPE], + ['EventModifierInit', base_config_1.TYPE], + ['EventSourceInit', base_config_1.TYPE], + ['FilePropertyBag', base_config_1.TYPE], + ['FileSystemCreateWritableOptions', base_config_1.TYPE], + ['FileSystemFlags', base_config_1.TYPE], + ['FileSystemGetDirectoryOptions', base_config_1.TYPE], + ['FileSystemGetFileOptions', base_config_1.TYPE], + ['FileSystemRemoveOptions', base_config_1.TYPE], + ['FocusEventInit', base_config_1.TYPE], + ['FocusOptions', base_config_1.TYPE], + ['FontFaceDescriptors', base_config_1.TYPE], + ['FontFaceSetLoadEventInit', base_config_1.TYPE], + ['FormDataEventInit', base_config_1.TYPE], + ['FullscreenOptions', base_config_1.TYPE], + ['GainOptions', base_config_1.TYPE], + ['GamepadEffectParameters', base_config_1.TYPE], + ['GamepadEventInit', base_config_1.TYPE], + ['GetAnimationsOptions', base_config_1.TYPE], + ['GetHTMLOptions', base_config_1.TYPE], + ['GetNotificationOptions', base_config_1.TYPE], + ['GetRootNodeOptions', base_config_1.TYPE], + ['HashChangeEventInit', base_config_1.TYPE], + ['HkdfParams', base_config_1.TYPE], + ['HmacImportParams', base_config_1.TYPE], + ['HmacKeyAlgorithm', base_config_1.TYPE], + ['HmacKeyGenParams', base_config_1.TYPE], + ['IDBDatabaseInfo', base_config_1.TYPE], + ['IDBIndexParameters', base_config_1.TYPE], + ['IDBObjectStoreParameters', base_config_1.TYPE], + ['IDBTransactionOptions', base_config_1.TYPE], + ['IDBVersionChangeEventInit', base_config_1.TYPE], + ['IIRFilterOptions', base_config_1.TYPE], + ['IdleRequestOptions', base_config_1.TYPE], + ['ImageBitmapOptions', base_config_1.TYPE], + ['ImageBitmapRenderingContextSettings', base_config_1.TYPE], + ['ImageDataSettings', base_config_1.TYPE], + ['ImageDecodeOptions', base_config_1.TYPE], + ['ImageDecodeResult', base_config_1.TYPE], + ['ImageDecoderInit', base_config_1.TYPE], + ['ImageEncodeOptions', base_config_1.TYPE], + ['InputEventInit', base_config_1.TYPE], + ['IntersectionObserverInit', base_config_1.TYPE], + ['JsonWebKey', base_config_1.TYPE], + ['KeyAlgorithm', base_config_1.TYPE], + ['KeyboardEventInit', base_config_1.TYPE], + ['Keyframe', base_config_1.TYPE], + ['KeyframeAnimationOptions', base_config_1.TYPE], + ['KeyframeEffectOptions', base_config_1.TYPE], + ['LockInfo', base_config_1.TYPE], + ['LockManagerSnapshot', base_config_1.TYPE], + ['LockOptions', base_config_1.TYPE], + ['MIDIConnectionEventInit', base_config_1.TYPE], + ['MIDIMessageEventInit', base_config_1.TYPE], + ['MIDIOptions', base_config_1.TYPE], + ['MediaCapabilitiesDecodingInfo', base_config_1.TYPE], + ['MediaCapabilitiesEncodingInfo', base_config_1.TYPE], + ['MediaCapabilitiesInfo', base_config_1.TYPE], + ['MediaConfiguration', base_config_1.TYPE], + ['MediaDecodingConfiguration', base_config_1.TYPE], + ['MediaElementAudioSourceOptions', base_config_1.TYPE], + ['MediaEncodingConfiguration', base_config_1.TYPE], + ['MediaEncryptedEventInit', base_config_1.TYPE], + ['MediaImage', base_config_1.TYPE], + ['MediaKeyMessageEventInit', base_config_1.TYPE], + ['MediaKeySystemConfiguration', base_config_1.TYPE], + ['MediaKeySystemMediaCapability', base_config_1.TYPE], + ['MediaKeysPolicy', base_config_1.TYPE], + ['MediaMetadataInit', base_config_1.TYPE], + ['MediaPositionState', base_config_1.TYPE], + ['MediaQueryListEventInit', base_config_1.TYPE], + ['MediaRecorderOptions', base_config_1.TYPE], + ['MediaSessionActionDetails', base_config_1.TYPE], + ['MediaStreamAudioSourceOptions', base_config_1.TYPE], + ['MediaStreamConstraints', base_config_1.TYPE], + ['MediaStreamTrackEventInit', base_config_1.TYPE], + ['MediaTrackCapabilities', base_config_1.TYPE], + ['MediaTrackConstraintSet', base_config_1.TYPE], + ['MediaTrackConstraints', base_config_1.TYPE], + ['MediaTrackSettings', base_config_1.TYPE], + ['MediaTrackSupportedConstraints', base_config_1.TYPE], + ['MessageEventInit', base_config_1.TYPE], + ['MouseEventInit', base_config_1.TYPE], + ['MultiCacheQueryOptions', base_config_1.TYPE], + ['MutationObserverInit', base_config_1.TYPE], + ['NavigationPreloadState', base_config_1.TYPE], + ['NotificationOptions', base_config_1.TYPE], + ['OfflineAudioCompletionEventInit', base_config_1.TYPE], + ['OfflineAudioContextOptions', base_config_1.TYPE], + ['OptionalEffectTiming', base_config_1.TYPE], + ['OpusEncoderConfig', base_config_1.TYPE], + ['OscillatorOptions', base_config_1.TYPE], + ['PageRevealEventInit', base_config_1.TYPE], + ['PageSwapEventInit', base_config_1.TYPE], + ['PageTransitionEventInit', base_config_1.TYPE], + ['PannerOptions', base_config_1.TYPE], + ['PayerErrors', base_config_1.TYPE], + ['PaymentCurrencyAmount', base_config_1.TYPE], + ['PaymentDetailsBase', base_config_1.TYPE], + ['PaymentDetailsInit', base_config_1.TYPE], + ['PaymentDetailsModifier', base_config_1.TYPE], + ['PaymentDetailsUpdate', base_config_1.TYPE], + ['PaymentItem', base_config_1.TYPE], + ['PaymentMethodChangeEventInit', base_config_1.TYPE], + ['PaymentMethodData', base_config_1.TYPE], + ['PaymentOptions', base_config_1.TYPE], + ['PaymentRequestUpdateEventInit', base_config_1.TYPE], + ['PaymentShippingOption', base_config_1.TYPE], + ['PaymentValidationErrors', base_config_1.TYPE], + ['Pbkdf2Params', base_config_1.TYPE], + ['PerformanceMarkOptions', base_config_1.TYPE], + ['PerformanceMeasureOptions', base_config_1.TYPE], + ['PerformanceObserverInit', base_config_1.TYPE], + ['PeriodicWaveConstraints', base_config_1.TYPE], + ['PeriodicWaveOptions', base_config_1.TYPE], + ['PermissionDescriptor', base_config_1.TYPE], + ['PictureInPictureEventInit', base_config_1.TYPE], + ['PlaneLayout', base_config_1.TYPE], + ['PointerEventInit', base_config_1.TYPE], + ['PointerLockOptions', base_config_1.TYPE], + ['PopStateEventInit', base_config_1.TYPE], + ['PositionOptions', base_config_1.TYPE], + ['ProgressEventInit', base_config_1.TYPE], + ['PromiseRejectionEventInit', base_config_1.TYPE], + ['PropertyDefinition', base_config_1.TYPE], + ['PropertyIndexedKeyframes', base_config_1.TYPE], + ['PublicKeyCredentialCreationOptions', base_config_1.TYPE], + ['PublicKeyCredentialCreationOptionsJSON', base_config_1.TYPE], + ['PublicKeyCredentialDescriptor', base_config_1.TYPE], + ['PublicKeyCredentialDescriptorJSON', base_config_1.TYPE], + ['PublicKeyCredentialEntity', base_config_1.TYPE], + ['PublicKeyCredentialParameters', base_config_1.TYPE], + ['PublicKeyCredentialRequestOptions', base_config_1.TYPE], + ['PublicKeyCredentialRequestOptionsJSON', base_config_1.TYPE], + ['PublicKeyCredentialRpEntity', base_config_1.TYPE], + ['PublicKeyCredentialUserEntity', base_config_1.TYPE], + ['PublicKeyCredentialUserEntityJSON', base_config_1.TYPE], + ['PushSubscriptionJSON', base_config_1.TYPE], + ['PushSubscriptionOptionsInit', base_config_1.TYPE], + ['QueuingStrategy', base_config_1.TYPE], + ['QueuingStrategyInit', base_config_1.TYPE], + ['RTCAnswerOptions', base_config_1.TYPE], + ['RTCCertificateExpiration', base_config_1.TYPE], + ['RTCConfiguration', base_config_1.TYPE], + ['RTCDTMFToneChangeEventInit', base_config_1.TYPE], + ['RTCDataChannelEventInit', base_config_1.TYPE], + ['RTCDataChannelInit', base_config_1.TYPE], + ['RTCDtlsFingerprint', base_config_1.TYPE], + ['RTCEncodedAudioFrameMetadata', base_config_1.TYPE], + ['RTCEncodedVideoFrameMetadata', base_config_1.TYPE], + ['RTCErrorEventInit', base_config_1.TYPE], + ['RTCErrorInit', base_config_1.TYPE], + ['RTCIceCandidateInit', base_config_1.TYPE], + ['RTCIceCandidatePairStats', base_config_1.TYPE], + ['RTCIceServer', base_config_1.TYPE], + ['RTCInboundRtpStreamStats', base_config_1.TYPE], + ['RTCLocalSessionDescriptionInit', base_config_1.TYPE], + ['RTCOfferAnswerOptions', base_config_1.TYPE], + ['RTCOfferOptions', base_config_1.TYPE], + ['RTCOutboundRtpStreamStats', base_config_1.TYPE], + ['RTCPeerConnectionIceErrorEventInit', base_config_1.TYPE], + ['RTCPeerConnectionIceEventInit', base_config_1.TYPE], + ['RTCReceivedRtpStreamStats', base_config_1.TYPE], + ['RTCRtcpParameters', base_config_1.TYPE], + ['RTCRtpCapabilities', base_config_1.TYPE], + ['RTCRtpCodec', base_config_1.TYPE], + ['RTCRtpCodecParameters', base_config_1.TYPE], + ['RTCRtpCodingParameters', base_config_1.TYPE], + ['RTCRtpContributingSource', base_config_1.TYPE], + ['RTCRtpEncodingParameters', base_config_1.TYPE], + ['RTCRtpHeaderExtensionCapability', base_config_1.TYPE], + ['RTCRtpHeaderExtensionParameters', base_config_1.TYPE], + ['RTCRtpParameters', base_config_1.TYPE], + ['RTCRtpReceiveParameters', base_config_1.TYPE], + ['RTCRtpSendParameters', base_config_1.TYPE], + ['RTCRtpStreamStats', base_config_1.TYPE], + ['RTCRtpSynchronizationSource', base_config_1.TYPE], + ['RTCRtpTransceiverInit', base_config_1.TYPE], + ['RTCSentRtpStreamStats', base_config_1.TYPE], + ['RTCSessionDescriptionInit', base_config_1.TYPE], + ['RTCSetParameterOptions', base_config_1.TYPE], + ['RTCStats', base_config_1.TYPE], + ['RTCTrackEventInit', base_config_1.TYPE], + ['RTCTransportStats', base_config_1.TYPE], + ['ReadableStreamGetReaderOptions', base_config_1.TYPE], + ['ReadableStreamIteratorOptions', base_config_1.TYPE], + ['ReadableStreamReadDoneResult', base_config_1.TYPE], + ['ReadableStreamReadValueResult', base_config_1.TYPE], + ['ReadableWritablePair', base_config_1.TYPE], + ['RegistrationOptions', base_config_1.TYPE], + ['ReportingObserverOptions', base_config_1.TYPE], + ['RequestInit', base_config_1.TYPE], + ['ResizeObserverOptions', base_config_1.TYPE], + ['ResponseInit', base_config_1.TYPE], + ['RsaHashedImportParams', base_config_1.TYPE], + ['RsaHashedKeyAlgorithm', base_config_1.TYPE], + ['RsaHashedKeyGenParams', base_config_1.TYPE], + ['RsaKeyAlgorithm', base_config_1.TYPE], + ['RsaKeyGenParams', base_config_1.TYPE], + ['RsaOaepParams', base_config_1.TYPE], + ['RsaOtherPrimesInfo', base_config_1.TYPE], + ['RsaPssParams', base_config_1.TYPE], + ['SVGBoundingBoxOptions', base_config_1.TYPE], + ['ScrollIntoViewOptions', base_config_1.TYPE], + ['ScrollOptions', base_config_1.TYPE], + ['ScrollToOptions', base_config_1.TYPE], + ['SecurityPolicyViolationEventInit', base_config_1.TYPE], + ['ShadowRootInit', base_config_1.TYPE], + ['ShareData', base_config_1.TYPE], + ['SpeechSynthesisErrorEventInit', base_config_1.TYPE], + ['SpeechSynthesisEventInit', base_config_1.TYPE], + ['StaticRangeInit', base_config_1.TYPE], + ['StereoPannerOptions', base_config_1.TYPE], + ['StorageEstimate', base_config_1.TYPE], + ['StorageEventInit', base_config_1.TYPE], + ['StreamPipeOptions', base_config_1.TYPE], + ['StructuredSerializeOptions', base_config_1.TYPE], + ['SubmitEventInit', base_config_1.TYPE], + ['TextDecodeOptions', base_config_1.TYPE], + ['TextDecoderOptions', base_config_1.TYPE], + ['TextEncoderEncodeIntoResult', base_config_1.TYPE], + ['ToggleEventInit', base_config_1.TYPE], + ['TouchEventInit', base_config_1.TYPE], + ['TouchInit', base_config_1.TYPE], + ['TrackEventInit', base_config_1.TYPE], + ['Transformer', base_config_1.TYPE], + ['TransitionEventInit', base_config_1.TYPE], + ['UIEventInit', base_config_1.TYPE], + ['ULongRange', base_config_1.TYPE], + ['UnderlyingByteSource', base_config_1.TYPE], + ['UnderlyingDefaultSource', base_config_1.TYPE], + ['UnderlyingSink', base_config_1.TYPE], + ['UnderlyingSource', base_config_1.TYPE], + ['ValidityStateFlags', base_config_1.TYPE], + ['VideoColorSpaceInit', base_config_1.TYPE], + ['VideoConfiguration', base_config_1.TYPE], + ['VideoDecoderConfig', base_config_1.TYPE], + ['VideoDecoderInit', base_config_1.TYPE], + ['VideoDecoderSupport', base_config_1.TYPE], + ['VideoEncoderConfig', base_config_1.TYPE], + ['VideoEncoderEncodeOptions', base_config_1.TYPE], + ['VideoEncoderEncodeOptionsForAvc', base_config_1.TYPE], + ['VideoEncoderInit', base_config_1.TYPE], + ['VideoEncoderSupport', base_config_1.TYPE], + ['VideoFrameBufferInit', base_config_1.TYPE], + ['VideoFrameCallbackMetadata', base_config_1.TYPE], + ['VideoFrameCopyToOptions', base_config_1.TYPE], + ['VideoFrameInit', base_config_1.TYPE], + ['WaveShaperOptions', base_config_1.TYPE], + ['WebGLContextAttributes', base_config_1.TYPE], + ['WebGLContextEventInit', base_config_1.TYPE], + ['WebTransportCloseInfo', base_config_1.TYPE], + ['WebTransportErrorOptions', base_config_1.TYPE], + ['WebTransportHash', base_config_1.TYPE], + ['WebTransportOptions', base_config_1.TYPE], + ['WebTransportSendStreamOptions', base_config_1.TYPE], + ['WheelEventInit', base_config_1.TYPE], + ['WindowPostMessageOptions', base_config_1.TYPE], + ['WorkerOptions', base_config_1.TYPE], + ['WorkletOptions', base_config_1.TYPE], + ['WriteParams', base_config_1.TYPE], + ['NodeFilter', base_config_1.TYPE_VALUE], + ['XPathNSResolver', base_config_1.TYPE], + ['ANGLE_instanced_arrays', base_config_1.TYPE], + ['ARIAMixin', base_config_1.TYPE], + ['AbortController', base_config_1.TYPE_VALUE], + ['AbortSignalEventMap', base_config_1.TYPE], + ['AbortSignal', base_config_1.TYPE_VALUE], + ['AbstractRange', base_config_1.TYPE_VALUE], + ['AbstractWorkerEventMap', base_config_1.TYPE], + ['AbstractWorker', base_config_1.TYPE], + ['AnalyserNode', base_config_1.TYPE_VALUE], + ['Animatable', base_config_1.TYPE], + ['AnimationEventMap', base_config_1.TYPE], + ['Animation', base_config_1.TYPE_VALUE], + ['AnimationEffect', base_config_1.TYPE_VALUE], + ['AnimationEvent', base_config_1.TYPE_VALUE], + ['AnimationFrameProvider', base_config_1.TYPE], + ['AnimationPlaybackEvent', base_config_1.TYPE_VALUE], + ['AnimationTimeline', base_config_1.TYPE_VALUE], + ['Attr', base_config_1.TYPE_VALUE], + ['AudioBuffer', base_config_1.TYPE_VALUE], + ['AudioBufferSourceNode', base_config_1.TYPE_VALUE], + ['AudioContext', base_config_1.TYPE_VALUE], + ['AudioData', base_config_1.TYPE_VALUE], + ['AudioDecoderEventMap', base_config_1.TYPE], + ['AudioDecoder', base_config_1.TYPE_VALUE], + ['AudioDestinationNode', base_config_1.TYPE_VALUE], + ['AudioEncoderEventMap', base_config_1.TYPE], + ['AudioEncoder', base_config_1.TYPE_VALUE], + ['AudioListener', base_config_1.TYPE_VALUE], + ['AudioNode', base_config_1.TYPE_VALUE], + ['AudioParam', base_config_1.TYPE_VALUE], + ['AudioParamMap', base_config_1.TYPE_VALUE], + ['AudioProcessingEvent', base_config_1.TYPE_VALUE], + ['AudioScheduledSourceNodeEventMap', base_config_1.TYPE], + ['AudioScheduledSourceNode', base_config_1.TYPE_VALUE], + ['AudioWorklet', base_config_1.TYPE_VALUE], + ['AudioWorkletNodeEventMap', base_config_1.TYPE], + ['AudioWorkletNode', base_config_1.TYPE_VALUE], + ['AuthenticatorAssertionResponse', base_config_1.TYPE_VALUE], + ['AuthenticatorAttestationResponse', base_config_1.TYPE_VALUE], + ['AuthenticatorResponse', base_config_1.TYPE_VALUE], + ['BarProp', base_config_1.TYPE_VALUE], + ['BaseAudioContextEventMap', base_config_1.TYPE], + ['BaseAudioContext', base_config_1.TYPE_VALUE], + ['BeforeUnloadEvent', base_config_1.TYPE_VALUE], + ['BiquadFilterNode', base_config_1.TYPE_VALUE], + ['Blob', base_config_1.TYPE_VALUE], + ['BlobEvent', base_config_1.TYPE_VALUE], + ['Body', base_config_1.TYPE], + ['BroadcastChannelEventMap', base_config_1.TYPE], + ['BroadcastChannel', base_config_1.TYPE_VALUE], + ['ByteLengthQueuingStrategy', base_config_1.TYPE_VALUE], + ['CDATASection', base_config_1.TYPE_VALUE], + ['CSSAnimation', base_config_1.TYPE_VALUE], + ['CSSConditionRule', base_config_1.TYPE_VALUE], + ['CSSContainerRule', base_config_1.TYPE_VALUE], + ['CSSCounterStyleRule', base_config_1.TYPE_VALUE], + ['CSSFontFaceRule', base_config_1.TYPE_VALUE], + ['CSSFontFeatureValuesRule', base_config_1.TYPE_VALUE], + ['CSSFontPaletteValuesRule', base_config_1.TYPE_VALUE], + ['CSSGroupingRule', base_config_1.TYPE_VALUE], + ['CSSImageValue', base_config_1.TYPE_VALUE], + ['CSSImportRule', base_config_1.TYPE_VALUE], + ['CSSKeyframeRule', base_config_1.TYPE_VALUE], + ['CSSKeyframesRule', base_config_1.TYPE_VALUE], + ['CSSKeywordValue', base_config_1.TYPE_VALUE], + ['CSSLayerBlockRule', base_config_1.TYPE_VALUE], + ['CSSLayerStatementRule', base_config_1.TYPE_VALUE], + ['CSSMathClamp', base_config_1.TYPE_VALUE], + ['CSSMathInvert', base_config_1.TYPE_VALUE], + ['CSSMathMax', base_config_1.TYPE_VALUE], + ['CSSMathMin', base_config_1.TYPE_VALUE], + ['CSSMathNegate', base_config_1.TYPE_VALUE], + ['CSSMathProduct', base_config_1.TYPE_VALUE], + ['CSSMathSum', base_config_1.TYPE_VALUE], + ['CSSMathValue', base_config_1.TYPE_VALUE], + ['CSSMatrixComponent', base_config_1.TYPE_VALUE], + ['CSSMediaRule', base_config_1.TYPE_VALUE], + ['CSSNamespaceRule', base_config_1.TYPE_VALUE], + ['CSSNestedDeclarations', base_config_1.TYPE_VALUE], + ['CSSNumericArray', base_config_1.TYPE_VALUE], + ['CSSNumericValue', base_config_1.TYPE_VALUE], + ['CSSPageRule', base_config_1.TYPE_VALUE], + ['CSSPerspective', base_config_1.TYPE_VALUE], + ['CSSPropertyRule', base_config_1.TYPE_VALUE], + ['CSSRotate', base_config_1.TYPE_VALUE], + ['CSSRule', base_config_1.TYPE_VALUE], + ['CSSRuleList', base_config_1.TYPE_VALUE], + ['CSSScale', base_config_1.TYPE_VALUE], + ['CSSScopeRule', base_config_1.TYPE_VALUE], + ['CSSSkew', base_config_1.TYPE_VALUE], + ['CSSSkewX', base_config_1.TYPE_VALUE], + ['CSSSkewY', base_config_1.TYPE_VALUE], + ['CSSStartingStyleRule', base_config_1.TYPE_VALUE], + ['CSSStyleDeclaration', base_config_1.TYPE_VALUE], + ['CSSStyleRule', base_config_1.TYPE_VALUE], + ['CSSStyleSheet', base_config_1.TYPE_VALUE], + ['CSSStyleValue', base_config_1.TYPE_VALUE], + ['CSSSupportsRule', base_config_1.TYPE_VALUE], + ['CSSTransformComponent', base_config_1.TYPE_VALUE], + ['CSSTransformValue', base_config_1.TYPE_VALUE], + ['CSSTransition', base_config_1.TYPE_VALUE], + ['CSSTranslate', base_config_1.TYPE_VALUE], + ['CSSUnitValue', base_config_1.TYPE_VALUE], + ['CSSUnparsedValue', base_config_1.TYPE_VALUE], + ['CSSVariableReferenceValue', base_config_1.TYPE_VALUE], + ['CSSViewTransitionRule', base_config_1.TYPE_VALUE], + ['Cache', base_config_1.TYPE_VALUE], + ['CacheStorage', base_config_1.TYPE_VALUE], + ['CanvasCaptureMediaStreamTrack', base_config_1.TYPE_VALUE], + ['CanvasCompositing', base_config_1.TYPE], + ['CanvasDrawImage', base_config_1.TYPE], + ['CanvasDrawPath', base_config_1.TYPE], + ['CanvasFillStrokeStyles', base_config_1.TYPE], + ['CanvasFilters', base_config_1.TYPE], + ['CanvasGradient', base_config_1.TYPE_VALUE], + ['CanvasImageData', base_config_1.TYPE], + ['CanvasImageSmoothing', base_config_1.TYPE], + ['CanvasPath', base_config_1.TYPE], + ['CanvasPathDrawingStyles', base_config_1.TYPE], + ['CanvasPattern', base_config_1.TYPE_VALUE], + ['CanvasRect', base_config_1.TYPE], + ['CanvasRenderingContext2D', base_config_1.TYPE_VALUE], + ['CanvasSettings', base_config_1.TYPE], + ['CanvasShadowStyles', base_config_1.TYPE], + ['CanvasState', base_config_1.TYPE], + ['CanvasText', base_config_1.TYPE], + ['CanvasTextDrawingStyles', base_config_1.TYPE], + ['CanvasTransform', base_config_1.TYPE], + ['CanvasUserInterface', base_config_1.TYPE], + ['CaretPosition', base_config_1.TYPE_VALUE], + ['ChannelMergerNode', base_config_1.TYPE_VALUE], + ['ChannelSplitterNode', base_config_1.TYPE_VALUE], + ['CharacterData', base_config_1.TYPE_VALUE], + ['ChildNode', base_config_1.TYPE], + ['ClientRect', base_config_1.TYPE], + ['Clipboard', base_config_1.TYPE_VALUE], + ['ClipboardEvent', base_config_1.TYPE_VALUE], + ['ClipboardItem', base_config_1.TYPE_VALUE], + ['CloseEvent', base_config_1.TYPE_VALUE], + ['Comment', base_config_1.TYPE_VALUE], + ['CompositionEvent', base_config_1.TYPE_VALUE], + ['CompressionStream', base_config_1.TYPE_VALUE], + ['ConstantSourceNode', base_config_1.TYPE_VALUE], + ['ContentVisibilityAutoStateChangeEvent', base_config_1.TYPE_VALUE], + ['ConvolverNode', base_config_1.TYPE_VALUE], + ['CountQueuingStrategy', base_config_1.TYPE_VALUE], + ['Credential', base_config_1.TYPE_VALUE], + ['CredentialsContainer', base_config_1.TYPE_VALUE], + ['Crypto', base_config_1.TYPE_VALUE], + ['CryptoKey', base_config_1.TYPE_VALUE], + ['CustomElementRegistry', base_config_1.TYPE_VALUE], + ['CustomEvent', base_config_1.TYPE_VALUE], + ['CustomStateSet', base_config_1.TYPE_VALUE], + ['DOMException', base_config_1.TYPE_VALUE], + ['DOMImplementation', base_config_1.TYPE_VALUE], + ['DOMMatrix', base_config_1.TYPE_VALUE], + ['SVGMatrix', base_config_1.TYPE_VALUE], + ['WebKitCSSMatrix', base_config_1.TYPE_VALUE], + ['DOMMatrixReadOnly', base_config_1.TYPE_VALUE], + ['DOMParser', base_config_1.TYPE_VALUE], + ['DOMPoint', base_config_1.TYPE_VALUE], + ['SVGPoint', base_config_1.TYPE_VALUE], + ['DOMPointReadOnly', base_config_1.TYPE_VALUE], + ['DOMQuad', base_config_1.TYPE_VALUE], + ['DOMRect', base_config_1.TYPE_VALUE], + ['SVGRect', base_config_1.TYPE_VALUE], + ['DOMRectList', base_config_1.TYPE_VALUE], + ['DOMRectReadOnly', base_config_1.TYPE_VALUE], + ['DOMStringList', base_config_1.TYPE_VALUE], + ['DOMStringMap', base_config_1.TYPE_VALUE], + ['DOMTokenList', base_config_1.TYPE_VALUE], + ['DataTransfer', base_config_1.TYPE_VALUE], + ['DataTransferItem', base_config_1.TYPE_VALUE], + ['DataTransferItemList', base_config_1.TYPE_VALUE], + ['DecompressionStream', base_config_1.TYPE_VALUE], + ['DelayNode', base_config_1.TYPE_VALUE], + ['DeviceMotionEvent', base_config_1.TYPE_VALUE], + ['DeviceMotionEventAcceleration', base_config_1.TYPE], + ['DeviceMotionEventRotationRate', base_config_1.TYPE], + ['DeviceOrientationEvent', base_config_1.TYPE_VALUE], + ['DocumentEventMap', base_config_1.TYPE], + ['Document', base_config_1.TYPE_VALUE], + ['DocumentFragment', base_config_1.TYPE_VALUE], + ['DocumentOrShadowRoot', base_config_1.TYPE], + ['DocumentTimeline', base_config_1.TYPE_VALUE], + ['DocumentType', base_config_1.TYPE_VALUE], + ['DragEvent', base_config_1.TYPE_VALUE], + ['DynamicsCompressorNode', base_config_1.TYPE_VALUE], + ['EXT_blend_minmax', base_config_1.TYPE], + ['EXT_color_buffer_float', base_config_1.TYPE], + ['EXT_color_buffer_half_float', base_config_1.TYPE], + ['EXT_float_blend', base_config_1.TYPE], + ['EXT_frag_depth', base_config_1.TYPE], + ['EXT_sRGB', base_config_1.TYPE], + ['EXT_shader_texture_lod', base_config_1.TYPE], + ['EXT_texture_compression_bptc', base_config_1.TYPE], + ['EXT_texture_compression_rgtc', base_config_1.TYPE], + ['EXT_texture_filter_anisotropic', base_config_1.TYPE], + ['EXT_texture_norm16', base_config_1.TYPE], + ['ElementEventMap', base_config_1.TYPE], + ['Element', base_config_1.TYPE_VALUE], + ['ElementCSSInlineStyle', base_config_1.TYPE], + ['ElementContentEditable', base_config_1.TYPE], + ['ElementInternals', base_config_1.TYPE_VALUE], + ['EncodedAudioChunk', base_config_1.TYPE_VALUE], + ['EncodedVideoChunk', base_config_1.TYPE_VALUE], + ['ErrorEvent', base_config_1.TYPE_VALUE], + ['Event', base_config_1.TYPE_VALUE], + ['EventCounts', base_config_1.TYPE_VALUE], + ['EventListener', base_config_1.TYPE], + ['EventListenerObject', base_config_1.TYPE], + ['EventSourceEventMap', base_config_1.TYPE], + ['EventSource', base_config_1.TYPE_VALUE], + ['EventTarget', base_config_1.TYPE_VALUE], + ['External', base_config_1.TYPE_VALUE], + ['File', base_config_1.TYPE_VALUE], + ['FileList', base_config_1.TYPE_VALUE], + ['FileReaderEventMap', base_config_1.TYPE], + ['FileReader', base_config_1.TYPE_VALUE], + ['FileSystem', base_config_1.TYPE_VALUE], + ['FileSystemDirectoryEntry', base_config_1.TYPE_VALUE], + ['FileSystemDirectoryHandle', base_config_1.TYPE_VALUE], + ['FileSystemDirectoryReader', base_config_1.TYPE_VALUE], + ['FileSystemEntry', base_config_1.TYPE_VALUE], + ['FileSystemFileEntry', base_config_1.TYPE_VALUE], + ['FileSystemFileHandle', base_config_1.TYPE_VALUE], + ['FileSystemHandle', base_config_1.TYPE_VALUE], + ['FileSystemWritableFileStream', base_config_1.TYPE_VALUE], + ['FocusEvent', base_config_1.TYPE_VALUE], + ['FontFace', base_config_1.TYPE_VALUE], + ['FontFaceSetEventMap', base_config_1.TYPE], + ['FontFaceSet', base_config_1.TYPE_VALUE], + ['FontFaceSetLoadEvent', base_config_1.TYPE_VALUE], + ['FontFaceSource', base_config_1.TYPE], + ['FormData', base_config_1.TYPE_VALUE], + ['FormDataEvent', base_config_1.TYPE_VALUE], + ['FragmentDirective', base_config_1.TYPE_VALUE], + ['GPUError', base_config_1.TYPE], + ['GainNode', base_config_1.TYPE_VALUE], + ['Gamepad', base_config_1.TYPE_VALUE], + ['GamepadButton', base_config_1.TYPE_VALUE], + ['GamepadEvent', base_config_1.TYPE_VALUE], + ['GamepadHapticActuator', base_config_1.TYPE_VALUE], + ['GenericTransformStream', base_config_1.TYPE], + ['Geolocation', base_config_1.TYPE_VALUE], + ['GeolocationCoordinates', base_config_1.TYPE_VALUE], + ['GeolocationPosition', base_config_1.TYPE_VALUE], + ['GeolocationPositionError', base_config_1.TYPE_VALUE], + ['GlobalEventHandlersEventMap', base_config_1.TYPE], + ['GlobalEventHandlers', base_config_1.TYPE], + ['HTMLAllCollection', base_config_1.TYPE_VALUE], + ['HTMLAnchorElement', base_config_1.TYPE_VALUE], + ['HTMLAreaElement', base_config_1.TYPE_VALUE], + ['HTMLAudioElement', base_config_1.TYPE_VALUE], + ['HTMLBRElement', base_config_1.TYPE_VALUE], + ['HTMLBaseElement', base_config_1.TYPE_VALUE], + ['HTMLBodyElementEventMap', base_config_1.TYPE], + ['HTMLBodyElement', base_config_1.TYPE_VALUE], + ['HTMLButtonElement', base_config_1.TYPE_VALUE], + ['HTMLCanvasElement', base_config_1.TYPE_VALUE], + ['HTMLCollectionBase', base_config_1.TYPE], + ['HTMLCollection', base_config_1.TYPE_VALUE], + ['HTMLCollectionOf', base_config_1.TYPE], + ['HTMLDListElement', base_config_1.TYPE_VALUE], + ['HTMLDataElement', base_config_1.TYPE_VALUE], + ['HTMLDataListElement', base_config_1.TYPE_VALUE], + ['HTMLDetailsElement', base_config_1.TYPE_VALUE], + ['HTMLDialogElement', base_config_1.TYPE_VALUE], + ['HTMLDirectoryElement', base_config_1.TYPE_VALUE], + ['HTMLDivElement', base_config_1.TYPE_VALUE], + ['HTMLDocument', base_config_1.TYPE_VALUE], + ['HTMLElementEventMap', base_config_1.TYPE], + ['HTMLElement', base_config_1.TYPE_VALUE], + ['HTMLEmbedElement', base_config_1.TYPE_VALUE], + ['HTMLFieldSetElement', base_config_1.TYPE_VALUE], + ['HTMLFontElement', base_config_1.TYPE_VALUE], + ['HTMLFormControlsCollection', base_config_1.TYPE_VALUE], + ['HTMLFormElement', base_config_1.TYPE_VALUE], + ['HTMLFrameElement', base_config_1.TYPE_VALUE], + ['HTMLFrameSetElementEventMap', base_config_1.TYPE], + ['HTMLFrameSetElement', base_config_1.TYPE_VALUE], + ['HTMLHRElement', base_config_1.TYPE_VALUE], + ['HTMLHeadElement', base_config_1.TYPE_VALUE], + ['HTMLHeadingElement', base_config_1.TYPE_VALUE], + ['HTMLHtmlElement', base_config_1.TYPE_VALUE], + ['HTMLHyperlinkElementUtils', base_config_1.TYPE], + ['HTMLIFrameElement', base_config_1.TYPE_VALUE], + ['HTMLImageElement', base_config_1.TYPE_VALUE], + ['HTMLInputElement', base_config_1.TYPE_VALUE], + ['HTMLLIElement', base_config_1.TYPE_VALUE], + ['HTMLLabelElement', base_config_1.TYPE_VALUE], + ['HTMLLegendElement', base_config_1.TYPE_VALUE], + ['HTMLLinkElement', base_config_1.TYPE_VALUE], + ['HTMLMapElement', base_config_1.TYPE_VALUE], + ['HTMLMarqueeElement', base_config_1.TYPE_VALUE], + ['HTMLMediaElementEventMap', base_config_1.TYPE], + ['HTMLMediaElement', base_config_1.TYPE_VALUE], + ['HTMLMenuElement', base_config_1.TYPE_VALUE], + ['HTMLMetaElement', base_config_1.TYPE_VALUE], + ['HTMLMeterElement', base_config_1.TYPE_VALUE], + ['HTMLModElement', base_config_1.TYPE_VALUE], + ['HTMLOListElement', base_config_1.TYPE_VALUE], + ['HTMLObjectElement', base_config_1.TYPE_VALUE], + ['HTMLOptGroupElement', base_config_1.TYPE_VALUE], + ['HTMLOptionElement', base_config_1.TYPE_VALUE], + ['HTMLOptionsCollection', base_config_1.TYPE_VALUE], + ['HTMLOrSVGElement', base_config_1.TYPE], + ['HTMLOutputElement', base_config_1.TYPE_VALUE], + ['HTMLParagraphElement', base_config_1.TYPE_VALUE], + ['HTMLParamElement', base_config_1.TYPE_VALUE], + ['HTMLPictureElement', base_config_1.TYPE_VALUE], + ['HTMLPreElement', base_config_1.TYPE_VALUE], + ['HTMLProgressElement', base_config_1.TYPE_VALUE], + ['HTMLQuoteElement', base_config_1.TYPE_VALUE], + ['HTMLScriptElement', base_config_1.TYPE_VALUE], + ['HTMLSelectElement', base_config_1.TYPE_VALUE], + ['HTMLSlotElement', base_config_1.TYPE_VALUE], + ['HTMLSourceElement', base_config_1.TYPE_VALUE], + ['HTMLSpanElement', base_config_1.TYPE_VALUE], + ['HTMLStyleElement', base_config_1.TYPE_VALUE], + ['HTMLTableCaptionElement', base_config_1.TYPE_VALUE], + ['HTMLTableCellElement', base_config_1.TYPE_VALUE], + ['HTMLTableColElement', base_config_1.TYPE_VALUE], + ['HTMLTableDataCellElement', base_config_1.TYPE], + ['HTMLTableElement', base_config_1.TYPE_VALUE], + ['HTMLTableHeaderCellElement', base_config_1.TYPE], + ['HTMLTableRowElement', base_config_1.TYPE_VALUE], + ['HTMLTableSectionElement', base_config_1.TYPE_VALUE], + ['HTMLTemplateElement', base_config_1.TYPE_VALUE], + ['HTMLTextAreaElement', base_config_1.TYPE_VALUE], + ['HTMLTimeElement', base_config_1.TYPE_VALUE], + ['HTMLTitleElement', base_config_1.TYPE_VALUE], + ['HTMLTrackElement', base_config_1.TYPE_VALUE], + ['HTMLUListElement', base_config_1.TYPE_VALUE], + ['HTMLUnknownElement', base_config_1.TYPE_VALUE], + ['HTMLVideoElementEventMap', base_config_1.TYPE], + ['HTMLVideoElement', base_config_1.TYPE_VALUE], + ['HashChangeEvent', base_config_1.TYPE_VALUE], + ['Headers', base_config_1.TYPE_VALUE], + ['Highlight', base_config_1.TYPE_VALUE], + ['HighlightRegistry', base_config_1.TYPE_VALUE], + ['History', base_config_1.TYPE_VALUE], + ['IDBCursor', base_config_1.TYPE_VALUE], + ['IDBCursorWithValue', base_config_1.TYPE_VALUE], + ['IDBDatabaseEventMap', base_config_1.TYPE], + ['IDBDatabase', base_config_1.TYPE_VALUE], + ['IDBFactory', base_config_1.TYPE_VALUE], + ['IDBIndex', base_config_1.TYPE_VALUE], + ['IDBKeyRange', base_config_1.TYPE_VALUE], + ['IDBObjectStore', base_config_1.TYPE_VALUE], + ['IDBOpenDBRequestEventMap', base_config_1.TYPE], + ['IDBOpenDBRequest', base_config_1.TYPE_VALUE], + ['IDBRequestEventMap', base_config_1.TYPE], + ['IDBRequest', base_config_1.TYPE_VALUE], + ['IDBTransactionEventMap', base_config_1.TYPE], + ['IDBTransaction', base_config_1.TYPE_VALUE], + ['IDBVersionChangeEvent', base_config_1.TYPE_VALUE], + ['IIRFilterNode', base_config_1.TYPE_VALUE], + ['IdleDeadline', base_config_1.TYPE_VALUE], + ['ImageBitmap', base_config_1.TYPE_VALUE], + ['ImageBitmapRenderingContext', base_config_1.TYPE_VALUE], + ['ImageData', base_config_1.TYPE_VALUE], + ['ImageDecoder', base_config_1.TYPE_VALUE], + ['ImageTrack', base_config_1.TYPE_VALUE], + ['ImageTrackList', base_config_1.TYPE_VALUE], + ['ImportMeta', base_config_1.TYPE], + ['InputDeviceInfo', base_config_1.TYPE_VALUE], + ['InputEvent', base_config_1.TYPE_VALUE], + ['IntersectionObserver', base_config_1.TYPE_VALUE], + ['IntersectionObserverEntry', base_config_1.TYPE_VALUE], + ['KHR_parallel_shader_compile', base_config_1.TYPE], + ['KeyboardEvent', base_config_1.TYPE_VALUE], + ['KeyframeEffect', base_config_1.TYPE_VALUE], + ['LargestContentfulPaint', base_config_1.TYPE_VALUE], + ['LinkStyle', base_config_1.TYPE], + ['Location', base_config_1.TYPE_VALUE], + ['Lock', base_config_1.TYPE_VALUE], + ['LockManager', base_config_1.TYPE_VALUE], + ['MIDIAccessEventMap', base_config_1.TYPE], + ['MIDIAccess', base_config_1.TYPE_VALUE], + ['MIDIConnectionEvent', base_config_1.TYPE_VALUE], + ['MIDIInputEventMap', base_config_1.TYPE], + ['MIDIInput', base_config_1.TYPE_VALUE], + ['MIDIInputMap', base_config_1.TYPE_VALUE], + ['MIDIMessageEvent', base_config_1.TYPE_VALUE], + ['MIDIOutput', base_config_1.TYPE_VALUE], + ['MIDIOutputMap', base_config_1.TYPE_VALUE], + ['MIDIPortEventMap', base_config_1.TYPE], + ['MIDIPort', base_config_1.TYPE_VALUE], + ['MathMLElementEventMap', base_config_1.TYPE], + ['MathMLElement', base_config_1.TYPE_VALUE], + ['MediaCapabilities', base_config_1.TYPE_VALUE], + ['MediaDeviceInfo', base_config_1.TYPE_VALUE], + ['MediaDevicesEventMap', base_config_1.TYPE], + ['MediaDevices', base_config_1.TYPE_VALUE], + ['MediaElementAudioSourceNode', base_config_1.TYPE_VALUE], + ['MediaEncryptedEvent', base_config_1.TYPE_VALUE], + ['MediaError', base_config_1.TYPE_VALUE], + ['MediaKeyMessageEvent', base_config_1.TYPE_VALUE], + ['MediaKeySessionEventMap', base_config_1.TYPE], + ['MediaKeySession', base_config_1.TYPE_VALUE], + ['MediaKeyStatusMap', base_config_1.TYPE_VALUE], + ['MediaKeySystemAccess', base_config_1.TYPE_VALUE], + ['MediaKeys', base_config_1.TYPE_VALUE], + ['MediaList', base_config_1.TYPE_VALUE], + ['MediaMetadata', base_config_1.TYPE_VALUE], + ['MediaQueryListEventMap', base_config_1.TYPE], + ['MediaQueryList', base_config_1.TYPE_VALUE], + ['MediaQueryListEvent', base_config_1.TYPE_VALUE], + ['MediaRecorderEventMap', base_config_1.TYPE], + ['MediaRecorder', base_config_1.TYPE_VALUE], + ['MediaSession', base_config_1.TYPE_VALUE], + ['MediaSourceEventMap', base_config_1.TYPE], + ['MediaSource', base_config_1.TYPE_VALUE], + ['MediaSourceHandle', base_config_1.TYPE_VALUE], + ['MediaStreamEventMap', base_config_1.TYPE], + ['MediaStream', base_config_1.TYPE_VALUE], + ['MediaStreamAudioDestinationNode', base_config_1.TYPE_VALUE], + ['MediaStreamAudioSourceNode', base_config_1.TYPE_VALUE], + ['MediaStreamTrackEventMap', base_config_1.TYPE], + ['MediaStreamTrack', base_config_1.TYPE_VALUE], + ['MediaStreamTrackEvent', base_config_1.TYPE_VALUE], + ['MessageChannel', base_config_1.TYPE_VALUE], + ['MessageEvent', base_config_1.TYPE_VALUE], + ['MessageEventTargetEventMap', base_config_1.TYPE], + ['MessageEventTarget', base_config_1.TYPE], + ['MessagePortEventMap', base_config_1.TYPE], + ['MessagePort', base_config_1.TYPE_VALUE], + ['MimeType', base_config_1.TYPE_VALUE], + ['MimeTypeArray', base_config_1.TYPE_VALUE], + ['MouseEvent', base_config_1.TYPE_VALUE], + ['MutationObserver', base_config_1.TYPE_VALUE], + ['MutationRecord', base_config_1.TYPE_VALUE], + ['NamedNodeMap', base_config_1.TYPE_VALUE], + ['NavigationActivation', base_config_1.TYPE_VALUE], + ['NavigationHistoryEntryEventMap', base_config_1.TYPE], + ['NavigationHistoryEntry', base_config_1.TYPE_VALUE], + ['NavigationPreloadManager', base_config_1.TYPE_VALUE], + ['Navigator', base_config_1.TYPE_VALUE], + ['NavigatorAutomationInformation', base_config_1.TYPE], + ['NavigatorBadge', base_config_1.TYPE], + ['NavigatorConcurrentHardware', base_config_1.TYPE], + ['NavigatorContentUtils', base_config_1.TYPE], + ['NavigatorCookies', base_config_1.TYPE], + ['NavigatorID', base_config_1.TYPE], + ['NavigatorLanguage', base_config_1.TYPE], + ['NavigatorLocks', base_config_1.TYPE], + ['NavigatorOnLine', base_config_1.TYPE], + ['NavigatorPlugins', base_config_1.TYPE], + ['NavigatorStorage', base_config_1.TYPE], + ['Node', base_config_1.TYPE_VALUE], + ['NodeIterator', base_config_1.TYPE_VALUE], + ['NodeList', base_config_1.TYPE_VALUE], + ['NodeListOf', base_config_1.TYPE], + ['NonDocumentTypeChildNode', base_config_1.TYPE], + ['NonElementParentNode', base_config_1.TYPE], + ['NotificationEventMap', base_config_1.TYPE], + ['Notification', base_config_1.TYPE_VALUE], + ['OES_draw_buffers_indexed', base_config_1.TYPE], + ['OES_element_index_uint', base_config_1.TYPE], + ['OES_fbo_render_mipmap', base_config_1.TYPE], + ['OES_standard_derivatives', base_config_1.TYPE], + ['OES_texture_float', base_config_1.TYPE], + ['OES_texture_float_linear', base_config_1.TYPE], + ['OES_texture_half_float', base_config_1.TYPE], + ['OES_texture_half_float_linear', base_config_1.TYPE], + ['OES_vertex_array_object', base_config_1.TYPE], + ['OVR_multiview2', base_config_1.TYPE], + ['OfflineAudioCompletionEvent', base_config_1.TYPE_VALUE], + ['OfflineAudioContextEventMap', base_config_1.TYPE], + ['OfflineAudioContext', base_config_1.TYPE_VALUE], + ['OffscreenCanvasEventMap', base_config_1.TYPE], + ['OffscreenCanvas', base_config_1.TYPE_VALUE], + ['OffscreenCanvasRenderingContext2D', base_config_1.TYPE_VALUE], + ['OscillatorNode', base_config_1.TYPE_VALUE], + ['OverconstrainedError', base_config_1.TYPE_VALUE], + ['PageRevealEvent', base_config_1.TYPE_VALUE], + ['PageSwapEvent', base_config_1.TYPE_VALUE], + ['PageTransitionEvent', base_config_1.TYPE_VALUE], + ['PannerNode', base_config_1.TYPE_VALUE], + ['ParentNode', base_config_1.TYPE], + ['Path2D', base_config_1.TYPE_VALUE], + ['PaymentAddress', base_config_1.TYPE_VALUE], + ['PaymentMethodChangeEvent', base_config_1.TYPE_VALUE], + ['PaymentRequestEventMap', base_config_1.TYPE], + ['PaymentRequest', base_config_1.TYPE_VALUE], + ['PaymentRequestUpdateEvent', base_config_1.TYPE_VALUE], + ['PaymentResponseEventMap', base_config_1.TYPE], + ['PaymentResponse', base_config_1.TYPE_VALUE], + ['PerformanceEventMap', base_config_1.TYPE], + ['Performance', base_config_1.TYPE_VALUE], + ['PerformanceEntry', base_config_1.TYPE_VALUE], + ['PerformanceEventTiming', base_config_1.TYPE_VALUE], + ['PerformanceMark', base_config_1.TYPE_VALUE], + ['PerformanceMeasure', base_config_1.TYPE_VALUE], + ['PerformanceNavigation', base_config_1.TYPE_VALUE], + ['PerformanceNavigationTiming', base_config_1.TYPE_VALUE], + ['PerformanceObserver', base_config_1.TYPE_VALUE], + ['PerformanceObserverEntryList', base_config_1.TYPE_VALUE], + ['PerformancePaintTiming', base_config_1.TYPE_VALUE], + ['PerformanceResourceTiming', base_config_1.TYPE_VALUE], + ['PerformanceServerTiming', base_config_1.TYPE_VALUE], + ['PerformanceTiming', base_config_1.TYPE_VALUE], + ['PeriodicWave', base_config_1.TYPE_VALUE], + ['PermissionStatusEventMap', base_config_1.TYPE], + ['PermissionStatus', base_config_1.TYPE_VALUE], + ['Permissions', base_config_1.TYPE_VALUE], + ['PictureInPictureEvent', base_config_1.TYPE_VALUE], + ['PictureInPictureWindowEventMap', base_config_1.TYPE], + ['PictureInPictureWindow', base_config_1.TYPE_VALUE], + ['Plugin', base_config_1.TYPE_VALUE], + ['PluginArray', base_config_1.TYPE_VALUE], + ['PointerEvent', base_config_1.TYPE_VALUE], + ['PopStateEvent', base_config_1.TYPE_VALUE], + ['PopoverInvokerElement', base_config_1.TYPE], + ['ProcessingInstruction', base_config_1.TYPE_VALUE], + ['ProgressEvent', base_config_1.TYPE_VALUE], + ['PromiseRejectionEvent', base_config_1.TYPE_VALUE], + ['PublicKeyCredential', base_config_1.TYPE_VALUE], + ['PushManager', base_config_1.TYPE_VALUE], + ['PushSubscription', base_config_1.TYPE_VALUE], + ['PushSubscriptionOptions', base_config_1.TYPE_VALUE], + ['RTCCertificate', base_config_1.TYPE_VALUE], + ['RTCDTMFSenderEventMap', base_config_1.TYPE], + ['RTCDTMFSender', base_config_1.TYPE_VALUE], + ['RTCDTMFToneChangeEvent', base_config_1.TYPE_VALUE], + ['RTCDataChannelEventMap', base_config_1.TYPE], + ['RTCDataChannel', base_config_1.TYPE_VALUE], + ['RTCDataChannelEvent', base_config_1.TYPE_VALUE], + ['RTCDtlsTransportEventMap', base_config_1.TYPE], + ['RTCDtlsTransport', base_config_1.TYPE_VALUE], + ['RTCEncodedAudioFrame', base_config_1.TYPE_VALUE], + ['RTCEncodedVideoFrame', base_config_1.TYPE_VALUE], + ['RTCError', base_config_1.TYPE_VALUE], + ['RTCErrorEvent', base_config_1.TYPE_VALUE], + ['RTCIceCandidate', base_config_1.TYPE_VALUE], + ['RTCIceCandidatePair', base_config_1.TYPE], + ['RTCIceTransportEventMap', base_config_1.TYPE], + ['RTCIceTransport', base_config_1.TYPE_VALUE], + ['RTCPeerConnectionEventMap', base_config_1.TYPE], + ['RTCPeerConnection', base_config_1.TYPE_VALUE], + ['RTCPeerConnectionIceErrorEvent', base_config_1.TYPE_VALUE], + ['RTCPeerConnectionIceEvent', base_config_1.TYPE_VALUE], + ['RTCRtpReceiver', base_config_1.TYPE_VALUE], + ['RTCRtpScriptTransform', base_config_1.TYPE_VALUE], + ['RTCRtpSender', base_config_1.TYPE_VALUE], + ['RTCRtpTransceiver', base_config_1.TYPE_VALUE], + ['RTCSctpTransportEventMap', base_config_1.TYPE], + ['RTCSctpTransport', base_config_1.TYPE_VALUE], + ['RTCSessionDescription', base_config_1.TYPE_VALUE], + ['RTCStatsReport', base_config_1.TYPE_VALUE], + ['RTCTrackEvent', base_config_1.TYPE_VALUE], + ['RadioNodeList', base_config_1.TYPE_VALUE], + ['Range', base_config_1.TYPE_VALUE], + ['ReadableByteStreamController', base_config_1.TYPE_VALUE], + ['ReadableStream', base_config_1.TYPE_VALUE], + ['ReadableStreamBYOBReader', base_config_1.TYPE_VALUE], + ['ReadableStreamBYOBRequest', base_config_1.TYPE_VALUE], + ['ReadableStreamDefaultController', base_config_1.TYPE_VALUE], + ['ReadableStreamDefaultReader', base_config_1.TYPE_VALUE], + ['ReadableStreamGenericReader', base_config_1.TYPE], + ['RemotePlaybackEventMap', base_config_1.TYPE], + ['RemotePlayback', base_config_1.TYPE_VALUE], + ['Report', base_config_1.TYPE_VALUE], + ['ReportBody', base_config_1.TYPE_VALUE], + ['ReportingObserver', base_config_1.TYPE_VALUE], + ['Request', base_config_1.TYPE_VALUE], + ['ResizeObserver', base_config_1.TYPE_VALUE], + ['ResizeObserverEntry', base_config_1.TYPE_VALUE], + ['ResizeObserverSize', base_config_1.TYPE_VALUE], + ['Response', base_config_1.TYPE_VALUE], + ['SVGAElement', base_config_1.TYPE_VALUE], + ['SVGAngle', base_config_1.TYPE_VALUE], + ['SVGAnimateElement', base_config_1.TYPE_VALUE], + ['SVGAnimateMotionElement', base_config_1.TYPE_VALUE], + ['SVGAnimateTransformElement', base_config_1.TYPE_VALUE], + ['SVGAnimatedAngle', base_config_1.TYPE_VALUE], + ['SVGAnimatedBoolean', base_config_1.TYPE_VALUE], + ['SVGAnimatedEnumeration', base_config_1.TYPE_VALUE], + ['SVGAnimatedInteger', base_config_1.TYPE_VALUE], + ['SVGAnimatedLength', base_config_1.TYPE_VALUE], + ['SVGAnimatedLengthList', base_config_1.TYPE_VALUE], + ['SVGAnimatedNumber', base_config_1.TYPE_VALUE], + ['SVGAnimatedNumberList', base_config_1.TYPE_VALUE], + ['SVGAnimatedPoints', base_config_1.TYPE], + ['SVGAnimatedPreserveAspectRatio', base_config_1.TYPE_VALUE], + ['SVGAnimatedRect', base_config_1.TYPE_VALUE], + ['SVGAnimatedString', base_config_1.TYPE_VALUE], + ['SVGAnimatedTransformList', base_config_1.TYPE_VALUE], + ['SVGAnimationElement', base_config_1.TYPE_VALUE], + ['SVGCircleElement', base_config_1.TYPE_VALUE], + ['SVGClipPathElement', base_config_1.TYPE_VALUE], + ['SVGComponentTransferFunctionElement', base_config_1.TYPE_VALUE], + ['SVGDefsElement', base_config_1.TYPE_VALUE], + ['SVGDescElement', base_config_1.TYPE_VALUE], + ['SVGElementEventMap', base_config_1.TYPE], + ['SVGElement', base_config_1.TYPE_VALUE], + ['SVGEllipseElement', base_config_1.TYPE_VALUE], + ['SVGFEBlendElement', base_config_1.TYPE_VALUE], + ['SVGFEColorMatrixElement', base_config_1.TYPE_VALUE], + ['SVGFEComponentTransferElement', base_config_1.TYPE_VALUE], + ['SVGFECompositeElement', base_config_1.TYPE_VALUE], + ['SVGFEConvolveMatrixElement', base_config_1.TYPE_VALUE], + ['SVGFEDiffuseLightingElement', base_config_1.TYPE_VALUE], + ['SVGFEDisplacementMapElement', base_config_1.TYPE_VALUE], + ['SVGFEDistantLightElement', base_config_1.TYPE_VALUE], + ['SVGFEDropShadowElement', base_config_1.TYPE_VALUE], + ['SVGFEFloodElement', base_config_1.TYPE_VALUE], + ['SVGFEFuncAElement', base_config_1.TYPE_VALUE], + ['SVGFEFuncBElement', base_config_1.TYPE_VALUE], + ['SVGFEFuncGElement', base_config_1.TYPE_VALUE], + ['SVGFEFuncRElement', base_config_1.TYPE_VALUE], + ['SVGFEGaussianBlurElement', base_config_1.TYPE_VALUE], + ['SVGFEImageElement', base_config_1.TYPE_VALUE], + ['SVGFEMergeElement', base_config_1.TYPE_VALUE], + ['SVGFEMergeNodeElement', base_config_1.TYPE_VALUE], + ['SVGFEMorphologyElement', base_config_1.TYPE_VALUE], + ['SVGFEOffsetElement', base_config_1.TYPE_VALUE], + ['SVGFEPointLightElement', base_config_1.TYPE_VALUE], + ['SVGFESpecularLightingElement', base_config_1.TYPE_VALUE], + ['SVGFESpotLightElement', base_config_1.TYPE_VALUE], + ['SVGFETileElement', base_config_1.TYPE_VALUE], + ['SVGFETurbulenceElement', base_config_1.TYPE_VALUE], + ['SVGFilterElement', base_config_1.TYPE_VALUE], + ['SVGFilterPrimitiveStandardAttributes', base_config_1.TYPE], + ['SVGFitToViewBox', base_config_1.TYPE], + ['SVGForeignObjectElement', base_config_1.TYPE_VALUE], + ['SVGGElement', base_config_1.TYPE_VALUE], + ['SVGGeometryElement', base_config_1.TYPE_VALUE], + ['SVGGradientElement', base_config_1.TYPE_VALUE], + ['SVGGraphicsElement', base_config_1.TYPE_VALUE], + ['SVGImageElement', base_config_1.TYPE_VALUE], + ['SVGLength', base_config_1.TYPE_VALUE], + ['SVGLengthList', base_config_1.TYPE_VALUE], + ['SVGLineElement', base_config_1.TYPE_VALUE], + ['SVGLinearGradientElement', base_config_1.TYPE_VALUE], + ['SVGMPathElement', base_config_1.TYPE_VALUE], + ['SVGMarkerElement', base_config_1.TYPE_VALUE], + ['SVGMaskElement', base_config_1.TYPE_VALUE], + ['SVGMetadataElement', base_config_1.TYPE_VALUE], + ['SVGNumber', base_config_1.TYPE_VALUE], + ['SVGNumberList', base_config_1.TYPE_VALUE], + ['SVGPathElement', base_config_1.TYPE_VALUE], + ['SVGPatternElement', base_config_1.TYPE_VALUE], + ['SVGPointList', base_config_1.TYPE_VALUE], + ['SVGPolygonElement', base_config_1.TYPE_VALUE], + ['SVGPolylineElement', base_config_1.TYPE_VALUE], + ['SVGPreserveAspectRatio', base_config_1.TYPE_VALUE], + ['SVGRadialGradientElement', base_config_1.TYPE_VALUE], + ['SVGRectElement', base_config_1.TYPE_VALUE], + ['SVGSVGElementEventMap', base_config_1.TYPE], + ['SVGSVGElement', base_config_1.TYPE_VALUE], + ['SVGScriptElement', base_config_1.TYPE_VALUE], + ['SVGSetElement', base_config_1.TYPE_VALUE], + ['SVGStopElement', base_config_1.TYPE_VALUE], + ['SVGStringList', base_config_1.TYPE_VALUE], + ['SVGStyleElement', base_config_1.TYPE_VALUE], + ['SVGSwitchElement', base_config_1.TYPE_VALUE], + ['SVGSymbolElement', base_config_1.TYPE_VALUE], + ['SVGTSpanElement', base_config_1.TYPE_VALUE], + ['SVGTests', base_config_1.TYPE], + ['SVGTextContentElement', base_config_1.TYPE_VALUE], + ['SVGTextElement', base_config_1.TYPE_VALUE], + ['SVGTextPathElement', base_config_1.TYPE_VALUE], + ['SVGTextPositioningElement', base_config_1.TYPE_VALUE], + ['SVGTitleElement', base_config_1.TYPE_VALUE], + ['SVGTransform', base_config_1.TYPE_VALUE], + ['SVGTransformList', base_config_1.TYPE_VALUE], + ['SVGURIReference', base_config_1.TYPE], + ['SVGUnitTypes', base_config_1.TYPE_VALUE], + ['SVGUseElement', base_config_1.TYPE_VALUE], + ['SVGViewElement', base_config_1.TYPE_VALUE], + ['Screen', base_config_1.TYPE_VALUE], + ['ScreenOrientationEventMap', base_config_1.TYPE], + ['ScreenOrientation', base_config_1.TYPE_VALUE], + ['ScriptProcessorNodeEventMap', base_config_1.TYPE], + ['ScriptProcessorNode', base_config_1.TYPE_VALUE], + ['SecurityPolicyViolationEvent', base_config_1.TYPE_VALUE], + ['Selection', base_config_1.TYPE_VALUE], + ['ServiceWorkerEventMap', base_config_1.TYPE], + ['ServiceWorker', base_config_1.TYPE_VALUE], + ['ServiceWorkerContainerEventMap', base_config_1.TYPE], + ['ServiceWorkerContainer', base_config_1.TYPE_VALUE], + ['ServiceWorkerRegistrationEventMap', base_config_1.TYPE], + ['ServiceWorkerRegistration', base_config_1.TYPE_VALUE], + ['ShadowRootEventMap', base_config_1.TYPE], + ['ShadowRoot', base_config_1.TYPE_VALUE], + ['SharedWorker', base_config_1.TYPE_VALUE], + ['Slottable', base_config_1.TYPE], + ['SourceBufferEventMap', base_config_1.TYPE], + ['SourceBuffer', base_config_1.TYPE_VALUE], + ['SourceBufferListEventMap', base_config_1.TYPE], + ['SourceBufferList', base_config_1.TYPE_VALUE], + ['SpeechRecognitionAlternative', base_config_1.TYPE_VALUE], + ['SpeechRecognitionResult', base_config_1.TYPE_VALUE], + ['SpeechRecognitionResultList', base_config_1.TYPE_VALUE], + ['SpeechSynthesisEventMap', base_config_1.TYPE], + ['SpeechSynthesis', base_config_1.TYPE_VALUE], + ['SpeechSynthesisErrorEvent', base_config_1.TYPE_VALUE], + ['SpeechSynthesisEvent', base_config_1.TYPE_VALUE], + ['SpeechSynthesisUtteranceEventMap', base_config_1.TYPE], + ['SpeechSynthesisUtterance', base_config_1.TYPE_VALUE], + ['SpeechSynthesisVoice', base_config_1.TYPE_VALUE], + ['StaticRange', base_config_1.TYPE_VALUE], + ['StereoPannerNode', base_config_1.TYPE_VALUE], + ['Storage', base_config_1.TYPE_VALUE], + ['StorageEvent', base_config_1.TYPE_VALUE], + ['StorageManager', base_config_1.TYPE_VALUE], + ['StyleMedia', base_config_1.TYPE], + ['StylePropertyMap', base_config_1.TYPE_VALUE], + ['StylePropertyMapReadOnly', base_config_1.TYPE_VALUE], + ['StyleSheet', base_config_1.TYPE_VALUE], + ['StyleSheetList', base_config_1.TYPE_VALUE], + ['SubmitEvent', base_config_1.TYPE_VALUE], + ['SubtleCrypto', base_config_1.TYPE_VALUE], + ['Text', base_config_1.TYPE_VALUE], + ['TextDecoder', base_config_1.TYPE_VALUE], + ['TextDecoderCommon', base_config_1.TYPE], + ['TextDecoderStream', base_config_1.TYPE_VALUE], + ['TextEncoder', base_config_1.TYPE_VALUE], + ['TextEncoderCommon', base_config_1.TYPE], + ['TextEncoderStream', base_config_1.TYPE_VALUE], + ['TextEvent', base_config_1.TYPE_VALUE], + ['TextMetrics', base_config_1.TYPE_VALUE], + ['TextTrackEventMap', base_config_1.TYPE], + ['TextTrack', base_config_1.TYPE_VALUE], + ['TextTrackCueEventMap', base_config_1.TYPE], + ['TextTrackCue', base_config_1.TYPE_VALUE], + ['TextTrackCueList', base_config_1.TYPE_VALUE], + ['TextTrackListEventMap', base_config_1.TYPE], + ['TextTrackList', base_config_1.TYPE_VALUE], + ['TimeRanges', base_config_1.TYPE_VALUE], + ['ToggleEvent', base_config_1.TYPE_VALUE], + ['Touch', base_config_1.TYPE_VALUE], + ['TouchEvent', base_config_1.TYPE_VALUE], + ['TouchList', base_config_1.TYPE_VALUE], + ['TrackEvent', base_config_1.TYPE_VALUE], + ['TransformStream', base_config_1.TYPE_VALUE], + ['TransformStreamDefaultController', base_config_1.TYPE_VALUE], + ['TransitionEvent', base_config_1.TYPE_VALUE], + ['TreeWalker', base_config_1.TYPE_VALUE], + ['UIEvent', base_config_1.TYPE_VALUE], + ['URL', base_config_1.TYPE_VALUE], + ['webkitURL', base_config_1.TYPE_VALUE], + ['URLSearchParams', base_config_1.TYPE_VALUE], + ['UserActivation', base_config_1.TYPE_VALUE], + ['VTTCue', base_config_1.TYPE_VALUE], + ['VTTRegion', base_config_1.TYPE_VALUE], + ['ValidityState', base_config_1.TYPE_VALUE], + ['VideoColorSpace', base_config_1.TYPE_VALUE], + ['VideoDecoderEventMap', base_config_1.TYPE], + ['VideoDecoder', base_config_1.TYPE_VALUE], + ['VideoEncoderEventMap', base_config_1.TYPE], + ['VideoEncoder', base_config_1.TYPE_VALUE], + ['VideoFrame', base_config_1.TYPE_VALUE], + ['VideoPlaybackQuality', base_config_1.TYPE_VALUE], + ['ViewTransition', base_config_1.TYPE_VALUE], + ['ViewTransitionTypeSet', base_config_1.TYPE_VALUE], + ['VisualViewportEventMap', base_config_1.TYPE], + ['VisualViewport', base_config_1.TYPE_VALUE], + ['WEBGL_color_buffer_float', base_config_1.TYPE], + ['WEBGL_compressed_texture_astc', base_config_1.TYPE], + ['WEBGL_compressed_texture_etc', base_config_1.TYPE], + ['WEBGL_compressed_texture_etc1', base_config_1.TYPE], + ['WEBGL_compressed_texture_pvrtc', base_config_1.TYPE], + ['WEBGL_compressed_texture_s3tc', base_config_1.TYPE], + ['WEBGL_compressed_texture_s3tc_srgb', base_config_1.TYPE], + ['WEBGL_debug_renderer_info', base_config_1.TYPE], + ['WEBGL_debug_shaders', base_config_1.TYPE], + ['WEBGL_depth_texture', base_config_1.TYPE], + ['WEBGL_draw_buffers', base_config_1.TYPE], + ['WEBGL_lose_context', base_config_1.TYPE], + ['WEBGL_multi_draw', base_config_1.TYPE], + ['WakeLock', base_config_1.TYPE_VALUE], + ['WakeLockSentinelEventMap', base_config_1.TYPE], + ['WakeLockSentinel', base_config_1.TYPE_VALUE], + ['WaveShaperNode', base_config_1.TYPE_VALUE], + ['WebGL2RenderingContext', base_config_1.TYPE_VALUE], + ['WebGL2RenderingContextBase', base_config_1.TYPE], + ['WebGL2RenderingContextOverloads', base_config_1.TYPE], + ['WebGLActiveInfo', base_config_1.TYPE_VALUE], + ['WebGLBuffer', base_config_1.TYPE_VALUE], + ['WebGLContextEvent', base_config_1.TYPE_VALUE], + ['WebGLFramebuffer', base_config_1.TYPE_VALUE], + ['WebGLProgram', base_config_1.TYPE_VALUE], + ['WebGLQuery', base_config_1.TYPE_VALUE], + ['WebGLRenderbuffer', base_config_1.TYPE_VALUE], + ['WebGLRenderingContext', base_config_1.TYPE_VALUE], + ['WebGLRenderingContextBase', base_config_1.TYPE], + ['WebGLRenderingContextOverloads', base_config_1.TYPE], + ['WebGLSampler', base_config_1.TYPE_VALUE], + ['WebGLShader', base_config_1.TYPE_VALUE], + ['WebGLShaderPrecisionFormat', base_config_1.TYPE_VALUE], + ['WebGLSync', base_config_1.TYPE_VALUE], + ['WebGLTexture', base_config_1.TYPE_VALUE], + ['WebGLTransformFeedback', base_config_1.TYPE_VALUE], + ['WebGLUniformLocation', base_config_1.TYPE_VALUE], + ['WebGLVertexArrayObject', base_config_1.TYPE_VALUE], + ['WebGLVertexArrayObjectOES', base_config_1.TYPE], + ['WebSocketEventMap', base_config_1.TYPE], + ['WebSocket', base_config_1.TYPE_VALUE], + ['WebTransport', base_config_1.TYPE_VALUE], + ['WebTransportBidirectionalStream', base_config_1.TYPE_VALUE], + ['WebTransportDatagramDuplexStream', base_config_1.TYPE_VALUE], + ['WebTransportError', base_config_1.TYPE_VALUE], + ['WheelEvent', base_config_1.TYPE_VALUE], + ['WindowEventMap', base_config_1.TYPE], + ['Window', base_config_1.TYPE_VALUE], + ['WindowEventHandlersEventMap', base_config_1.TYPE], + ['WindowEventHandlers', base_config_1.TYPE], + ['WindowLocalStorage', base_config_1.TYPE], + ['WindowOrWorkerGlobalScope', base_config_1.TYPE], + ['WindowSessionStorage', base_config_1.TYPE], + ['WorkerEventMap', base_config_1.TYPE], + ['Worker', base_config_1.TYPE_VALUE], + ['Worklet', base_config_1.TYPE_VALUE], + ['WritableStream', base_config_1.TYPE_VALUE], + ['WritableStreamDefaultController', base_config_1.TYPE_VALUE], + ['WritableStreamDefaultWriter', base_config_1.TYPE_VALUE], + ['XMLDocument', base_config_1.TYPE_VALUE], + ['XMLHttpRequestEventMap', base_config_1.TYPE], + ['XMLHttpRequest', base_config_1.TYPE_VALUE], + ['XMLHttpRequestEventTargetEventMap', base_config_1.TYPE], + ['XMLHttpRequestEventTarget', base_config_1.TYPE_VALUE], + ['XMLHttpRequestUpload', base_config_1.TYPE_VALUE], + ['XMLSerializer', base_config_1.TYPE_VALUE], + ['XPathEvaluator', base_config_1.TYPE_VALUE], + ['XPathEvaluatorBase', base_config_1.TYPE], + ['XPathExpression', base_config_1.TYPE_VALUE], + ['XPathResult', base_config_1.TYPE_VALUE], + ['XSLTProcessor', base_config_1.TYPE_VALUE], + ['Console', base_config_1.TYPE], + ['CSS', base_config_1.TYPE_VALUE], + ['WebAssembly', base_config_1.TYPE_VALUE], + ['AudioDataOutputCallback', base_config_1.TYPE], + ['BlobCallback', base_config_1.TYPE], + ['CustomElementConstructor', base_config_1.TYPE], + ['DecodeErrorCallback', base_config_1.TYPE], + ['DecodeSuccessCallback', base_config_1.TYPE], + ['EncodedAudioChunkOutputCallback', base_config_1.TYPE], + ['EncodedVideoChunkOutputCallback', base_config_1.TYPE], + ['ErrorCallback', base_config_1.TYPE], + ['FileCallback', base_config_1.TYPE], + ['FileSystemEntriesCallback', base_config_1.TYPE], + ['FileSystemEntryCallback', base_config_1.TYPE], + ['FrameRequestCallback', base_config_1.TYPE], + ['FunctionStringCallback', base_config_1.TYPE], + ['IdleRequestCallback', base_config_1.TYPE], + ['IntersectionObserverCallback', base_config_1.TYPE], + ['LockGrantedCallback', base_config_1.TYPE], + ['MediaSessionActionHandler', base_config_1.TYPE], + ['MutationCallback', base_config_1.TYPE], + ['NotificationPermissionCallback', base_config_1.TYPE], + ['OnBeforeUnloadEventHandlerNonNull', base_config_1.TYPE], + ['OnErrorEventHandlerNonNull', base_config_1.TYPE], + ['PerformanceObserverCallback', base_config_1.TYPE], + ['PositionCallback', base_config_1.TYPE], + ['PositionErrorCallback', base_config_1.TYPE], + ['QueuingStrategySize', base_config_1.TYPE], + ['RTCPeerConnectionErrorCallback', base_config_1.TYPE], + ['RTCSessionDescriptionCallback', base_config_1.TYPE], + ['RemotePlaybackAvailabilityCallback', base_config_1.TYPE], + ['ReportingObserverCallback', base_config_1.TYPE], + ['ResizeObserverCallback', base_config_1.TYPE], + ['TransformerFlushCallback', base_config_1.TYPE], + ['TransformerStartCallback', base_config_1.TYPE], + ['TransformerTransformCallback', base_config_1.TYPE], + ['UnderlyingSinkAbortCallback', base_config_1.TYPE], + ['UnderlyingSinkCloseCallback', base_config_1.TYPE], + ['UnderlyingSinkStartCallback', base_config_1.TYPE], + ['UnderlyingSinkWriteCallback', base_config_1.TYPE], + ['UnderlyingSourceCancelCallback', base_config_1.TYPE], + ['UnderlyingSourcePullCallback', base_config_1.TYPE], + ['UnderlyingSourceStartCallback', base_config_1.TYPE], + ['VideoFrameOutputCallback', base_config_1.TYPE], + ['VideoFrameRequestCallback', base_config_1.TYPE], + ['ViewTransitionUpdateCallback', base_config_1.TYPE], + ['VoidFunction', base_config_1.TYPE], + ['WebCodecsErrorCallback', base_config_1.TYPE], + ['HTMLElementTagNameMap', base_config_1.TYPE], + ['HTMLElementDeprecatedTagNameMap', base_config_1.TYPE], + ['SVGElementTagNameMap', base_config_1.TYPE], + ['MathMLElementTagNameMap', base_config_1.TYPE], + ['ElementTagNameMap', base_config_1.TYPE], + ['AlgorithmIdentifier', base_config_1.TYPE], + ['AllowSharedBufferSource', base_config_1.TYPE], + ['AutoFill', base_config_1.TYPE], + ['AutoFillField', base_config_1.TYPE], + ['AutoFillSection', base_config_1.TYPE], + ['Base64URLString', base_config_1.TYPE], + ['BigInteger', base_config_1.TYPE], + ['BlobPart', base_config_1.TYPE], + ['BodyInit', base_config_1.TYPE], + ['BufferSource', base_config_1.TYPE], + ['COSEAlgorithmIdentifier', base_config_1.TYPE], + ['CSSKeywordish', base_config_1.TYPE], + ['CSSNumberish', base_config_1.TYPE], + ['CSSPerspectiveValue', base_config_1.TYPE], + ['CSSUnparsedSegment', base_config_1.TYPE], + ['CanvasImageSource', base_config_1.TYPE], + ['ClipboardItemData', base_config_1.TYPE], + ['ClipboardItems', base_config_1.TYPE], + ['ConstrainBoolean', base_config_1.TYPE], + ['ConstrainDOMString', base_config_1.TYPE], + ['ConstrainDouble', base_config_1.TYPE], + ['ConstrainULong', base_config_1.TYPE], + ['DOMHighResTimeStamp', base_config_1.TYPE], + ['EpochTimeStamp', base_config_1.TYPE], + ['EventListenerOrEventListenerObject', base_config_1.TYPE], + ['FileSystemWriteChunkType', base_config_1.TYPE], + ['Float32List', base_config_1.TYPE], + ['FormDataEntryValue', base_config_1.TYPE], + ['GLbitfield', base_config_1.TYPE], + ['GLboolean', base_config_1.TYPE], + ['GLclampf', base_config_1.TYPE], + ['GLenum', base_config_1.TYPE], + ['GLfloat', base_config_1.TYPE], + ['GLint', base_config_1.TYPE], + ['GLint64', base_config_1.TYPE], + ['GLintptr', base_config_1.TYPE], + ['GLsizei', base_config_1.TYPE], + ['GLsizeiptr', base_config_1.TYPE], + ['GLuint', base_config_1.TYPE], + ['GLuint64', base_config_1.TYPE], + ['HTMLOrSVGImageElement', base_config_1.TYPE], + ['HTMLOrSVGScriptElement', base_config_1.TYPE], + ['HashAlgorithmIdentifier', base_config_1.TYPE], + ['HeadersInit', base_config_1.TYPE], + ['IDBValidKey', base_config_1.TYPE], + ['ImageBitmapSource', base_config_1.TYPE], + ['ImageBufferSource', base_config_1.TYPE], + ['Int32List', base_config_1.TYPE], + ['LineAndPositionSetting', base_config_1.TYPE], + ['MediaProvider', base_config_1.TYPE], + ['MessageEventSource', base_config_1.TYPE], + ['MutationRecordType', base_config_1.TYPE], + ['NamedCurve', base_config_1.TYPE], + ['OffscreenRenderingContext', base_config_1.TYPE], + ['OnBeforeUnloadEventHandler', base_config_1.TYPE], + ['OnErrorEventHandler', base_config_1.TYPE], + ['OptionalPostfixToken', base_config_1.TYPE], + ['OptionalPrefixToken', base_config_1.TYPE], + ['PerformanceEntryList', base_config_1.TYPE], + ['PublicKeyCredentialClientCapabilities', base_config_1.TYPE], + ['PublicKeyCredentialJSON', base_config_1.TYPE], + ['RTCRtpTransform', base_config_1.TYPE], + ['ReadableStreamController', base_config_1.TYPE], + ['ReadableStreamReadResult', base_config_1.TYPE], + ['ReadableStreamReader', base_config_1.TYPE], + ['RenderingContext', base_config_1.TYPE], + ['ReportList', base_config_1.TYPE], + ['RequestInfo', base_config_1.TYPE], + ['TexImageSource', base_config_1.TYPE], + ['TimerHandler', base_config_1.TYPE], + ['Transferable', base_config_1.TYPE], + ['Uint32List', base_config_1.TYPE], + ['VibratePattern', base_config_1.TYPE], + ['WindowProxy', base_config_1.TYPE], + ['XMLHttpRequestBodyInit', base_config_1.TYPE], + ['AlignSetting', base_config_1.TYPE], + ['AlphaOption', base_config_1.TYPE], + ['AnimationPlayState', base_config_1.TYPE], + ['AnimationReplaceState', base_config_1.TYPE], + ['AppendMode', base_config_1.TYPE], + ['AttestationConveyancePreference', base_config_1.TYPE], + ['AudioContextLatencyCategory', base_config_1.TYPE], + ['AudioContextState', base_config_1.TYPE], + ['AudioSampleFormat', base_config_1.TYPE], + ['AuthenticatorAttachment', base_config_1.TYPE], + ['AuthenticatorTransport', base_config_1.TYPE], + ['AutoFillAddressKind', base_config_1.TYPE], + ['AutoFillBase', base_config_1.TYPE], + ['AutoFillContactField', base_config_1.TYPE], + ['AutoFillContactKind', base_config_1.TYPE], + ['AutoFillCredentialField', base_config_1.TYPE], + ['AutoFillNormalField', base_config_1.TYPE], + ['AutoKeyword', base_config_1.TYPE], + ['AutomationRate', base_config_1.TYPE], + ['AvcBitstreamFormat', base_config_1.TYPE], + ['BinaryType', base_config_1.TYPE], + ['BiquadFilterType', base_config_1.TYPE], + ['BitrateMode', base_config_1.TYPE], + ['CSSMathOperator', base_config_1.TYPE], + ['CSSNumericBaseType', base_config_1.TYPE], + ['CanPlayTypeResult', base_config_1.TYPE], + ['CanvasDirection', base_config_1.TYPE], + ['CanvasFillRule', base_config_1.TYPE], + ['CanvasFontKerning', base_config_1.TYPE], + ['CanvasFontStretch', base_config_1.TYPE], + ['CanvasFontVariantCaps', base_config_1.TYPE], + ['CanvasLineCap', base_config_1.TYPE], + ['CanvasLineJoin', base_config_1.TYPE], + ['CanvasTextAlign', base_config_1.TYPE], + ['CanvasTextBaseline', base_config_1.TYPE], + ['CanvasTextRendering', base_config_1.TYPE], + ['ChannelCountMode', base_config_1.TYPE], + ['ChannelInterpretation', base_config_1.TYPE], + ['ClientTypes', base_config_1.TYPE], + ['CodecState', base_config_1.TYPE], + ['ColorGamut', base_config_1.TYPE], + ['ColorSpaceConversion', base_config_1.TYPE], + ['CompositeOperation', base_config_1.TYPE], + ['CompositeOperationOrAuto', base_config_1.TYPE], + ['CompressionFormat', base_config_1.TYPE], + ['CredentialMediationRequirement', base_config_1.TYPE], + ['DOMParserSupportedType', base_config_1.TYPE], + ['DirectionSetting', base_config_1.TYPE], + ['DisplayCaptureSurfaceType', base_config_1.TYPE], + ['DistanceModelType', base_config_1.TYPE], + ['DocumentReadyState', base_config_1.TYPE], + ['DocumentVisibilityState', base_config_1.TYPE], + ['EncodedAudioChunkType', base_config_1.TYPE], + ['EncodedVideoChunkType', base_config_1.TYPE], + ['EndOfStreamError', base_config_1.TYPE], + ['EndingType', base_config_1.TYPE], + ['FileSystemHandleKind', base_config_1.TYPE], + ['FillMode', base_config_1.TYPE], + ['FontDisplay', base_config_1.TYPE], + ['FontFaceLoadStatus', base_config_1.TYPE], + ['FontFaceSetLoadStatus', base_config_1.TYPE], + ['FullscreenNavigationUI', base_config_1.TYPE], + ['GamepadHapticEffectType', base_config_1.TYPE], + ['GamepadHapticsResult', base_config_1.TYPE], + ['GamepadMappingType', base_config_1.TYPE], + ['GlobalCompositeOperation', base_config_1.TYPE], + ['HardwareAcceleration', base_config_1.TYPE], + ['HdrMetadataType', base_config_1.TYPE], + ['HighlightType', base_config_1.TYPE], + ['IDBCursorDirection', base_config_1.TYPE], + ['IDBRequestReadyState', base_config_1.TYPE], + ['IDBTransactionDurability', base_config_1.TYPE], + ['IDBTransactionMode', base_config_1.TYPE], + ['ImageOrientation', base_config_1.TYPE], + ['ImageSmoothingQuality', base_config_1.TYPE], + ['InsertPosition', base_config_1.TYPE], + ['IterationCompositeOperation', base_config_1.TYPE], + ['KeyFormat', base_config_1.TYPE], + ['KeyType', base_config_1.TYPE], + ['KeyUsage', base_config_1.TYPE], + ['LatencyMode', base_config_1.TYPE], + ['LineAlignSetting', base_config_1.TYPE], + ['LockMode', base_config_1.TYPE], + ['MIDIPortConnectionState', base_config_1.TYPE], + ['MIDIPortDeviceState', base_config_1.TYPE], + ['MIDIPortType', base_config_1.TYPE], + ['MediaDecodingType', base_config_1.TYPE], + ['MediaDeviceKind', base_config_1.TYPE], + ['MediaEncodingType', base_config_1.TYPE], + ['MediaKeyMessageType', base_config_1.TYPE], + ['MediaKeySessionClosedReason', base_config_1.TYPE], + ['MediaKeySessionType', base_config_1.TYPE], + ['MediaKeyStatus', base_config_1.TYPE], + ['MediaKeysRequirement', base_config_1.TYPE], + ['MediaSessionAction', base_config_1.TYPE], + ['MediaSessionPlaybackState', base_config_1.TYPE], + ['MediaStreamTrackState', base_config_1.TYPE], + ['NavigationTimingType', base_config_1.TYPE], + ['NavigationType', base_config_1.TYPE], + ['NotificationDirection', base_config_1.TYPE], + ['NotificationPermission', base_config_1.TYPE], + ['OffscreenRenderingContextId', base_config_1.TYPE], + ['OpusBitstreamFormat', base_config_1.TYPE], + ['OrientationType', base_config_1.TYPE], + ['OscillatorType', base_config_1.TYPE], + ['OverSampleType', base_config_1.TYPE], + ['PanningModelType', base_config_1.TYPE], + ['PaymentComplete', base_config_1.TYPE], + ['PaymentShippingType', base_config_1.TYPE], + ['PermissionName', base_config_1.TYPE], + ['PermissionState', base_config_1.TYPE], + ['PlaybackDirection', base_config_1.TYPE], + ['PositionAlignSetting', base_config_1.TYPE], + ['PredefinedColorSpace', base_config_1.TYPE], + ['PremultiplyAlpha', base_config_1.TYPE], + ['PresentationStyle', base_config_1.TYPE], + ['PublicKeyCredentialType', base_config_1.TYPE], + ['PushEncryptionKeyName', base_config_1.TYPE], + ['RTCBundlePolicy', base_config_1.TYPE], + ['RTCDataChannelState', base_config_1.TYPE], + ['RTCDegradationPreference', base_config_1.TYPE], + ['RTCDtlsRole', base_config_1.TYPE], + ['RTCDtlsTransportState', base_config_1.TYPE], + ['RTCEncodedVideoFrameType', base_config_1.TYPE], + ['RTCErrorDetailType', base_config_1.TYPE], + ['RTCIceCandidateType', base_config_1.TYPE], + ['RTCIceComponent', base_config_1.TYPE], + ['RTCIceConnectionState', base_config_1.TYPE], + ['RTCIceGathererState', base_config_1.TYPE], + ['RTCIceGatheringState', base_config_1.TYPE], + ['RTCIceProtocol', base_config_1.TYPE], + ['RTCIceRole', base_config_1.TYPE], + ['RTCIceTcpCandidateType', base_config_1.TYPE], + ['RTCIceTransportPolicy', base_config_1.TYPE], + ['RTCIceTransportState', base_config_1.TYPE], + ['RTCPeerConnectionState', base_config_1.TYPE], + ['RTCPriorityType', base_config_1.TYPE], + ['RTCQualityLimitationReason', base_config_1.TYPE], + ['RTCRtcpMuxPolicy', base_config_1.TYPE], + ['RTCRtpTransceiverDirection', base_config_1.TYPE], + ['RTCSctpTransportState', base_config_1.TYPE], + ['RTCSdpType', base_config_1.TYPE], + ['RTCSignalingState', base_config_1.TYPE], + ['RTCStatsIceCandidatePairState', base_config_1.TYPE], + ['RTCStatsType', base_config_1.TYPE], + ['ReadableStreamReaderMode', base_config_1.TYPE], + ['ReadableStreamType', base_config_1.TYPE], + ['ReadyState', base_config_1.TYPE], + ['RecordingState', base_config_1.TYPE], + ['ReferrerPolicy', base_config_1.TYPE], + ['RemotePlaybackState', base_config_1.TYPE], + ['RequestCache', base_config_1.TYPE], + ['RequestCredentials', base_config_1.TYPE], + ['RequestDestination', base_config_1.TYPE], + ['RequestMode', base_config_1.TYPE], + ['RequestPriority', base_config_1.TYPE], + ['RequestRedirect', base_config_1.TYPE], + ['ResidentKeyRequirement', base_config_1.TYPE], + ['ResizeObserverBoxOptions', base_config_1.TYPE], + ['ResizeQuality', base_config_1.TYPE], + ['ResponseType', base_config_1.TYPE], + ['ScrollBehavior', base_config_1.TYPE], + ['ScrollLogicalPosition', base_config_1.TYPE], + ['ScrollRestoration', base_config_1.TYPE], + ['ScrollSetting', base_config_1.TYPE], + ['SecurityPolicyViolationEventDisposition', base_config_1.TYPE], + ['SelectionMode', base_config_1.TYPE], + ['ServiceWorkerState', base_config_1.TYPE], + ['ServiceWorkerUpdateViaCache', base_config_1.TYPE], + ['ShadowRootMode', base_config_1.TYPE], + ['SlotAssignmentMode', base_config_1.TYPE], + ['SpeechSynthesisErrorCode', base_config_1.TYPE], + ['TextTrackKind', base_config_1.TYPE], + ['TextTrackMode', base_config_1.TYPE], + ['TouchType', base_config_1.TYPE], + ['TransferFunction', base_config_1.TYPE], + ['UserVerificationRequirement', base_config_1.TYPE], + ['VideoColorPrimaries', base_config_1.TYPE], + ['VideoEncoderBitrateMode', base_config_1.TYPE], + ['VideoFacingModeEnum', base_config_1.TYPE], + ['VideoMatrixCoefficients', base_config_1.TYPE], + ['VideoPixelFormat', base_config_1.TYPE], + ['VideoTransferCharacteristics', base_config_1.TYPE], + ['WakeLockType', base_config_1.TYPE], + ['WebGLPowerPreference', base_config_1.TYPE], + ['WebTransportCongestionControl', base_config_1.TYPE], + ['WebTransportErrorSource', base_config_1.TYPE], + ['WorkerType', base_config_1.TYPE], + ['WriteCommandType', base_config_1.TYPE], + ['XMLHttpRequestResponseType', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.d.ts new file mode 100644 index 00000000..5c54284e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_collection: LibDefinition; +//# sourceMappingURL=es2015.collection.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.d.ts.map new file mode 100644 index 00000000..db37fad8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.collection.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.collection.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,iBAAiB,EAAE,aAc/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.js new file mode 100644 index 00000000..30f3035b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.collection.js @@ -0,0 +1,23 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_collection = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_collection = { + libs: [], + variables: [ + ['Map', base_config_1.TYPE_VALUE], + ['MapConstructor', base_config_1.TYPE], + ['ReadonlyMap', base_config_1.TYPE], + ['WeakMap', base_config_1.TYPE_VALUE], + ['WeakMapConstructor', base_config_1.TYPE], + ['Set', base_config_1.TYPE_VALUE], + ['SetConstructor', base_config_1.TYPE], + ['ReadonlySet', base_config_1.TYPE], + ['WeakSet', base_config_1.TYPE_VALUE], + ['WeakSetConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.d.ts new file mode 100644 index 00000000..c246e029 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_core: LibDefinition; +//# sourceMappingURL=es2015.core.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.d.ts.map new file mode 100644 index 00000000..7eaa1080 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.core.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.core.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAyBzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.js new file mode 100644 index 00000000..f8c2a08a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.core.js @@ -0,0 +1,34 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_core = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_core = { + libs: [], + variables: [ + ['Array', base_config_1.TYPE], + ['ArrayConstructor', base_config_1.TYPE], + ['DateConstructor', base_config_1.TYPE], + ['Function', base_config_1.TYPE], + ['Math', base_config_1.TYPE], + ['NumberConstructor', base_config_1.TYPE], + ['ObjectConstructor', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['RegExp', base_config_1.TYPE], + ['RegExpConstructor', base_config_1.TYPE], + ['String', base_config_1.TYPE], + ['StringConstructor', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.d.ts new file mode 100644 index 00000000..972d4198 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015: LibDefinition; +//# sourceMappingURL=es2015.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.d.ts.map new file mode 100644 index 00000000..81ef182f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAajD,eAAO,MAAM,MAAM,EAAE,aAcpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.d.ts new file mode 100644 index 00000000..e652ea0b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_generator: LibDefinition; +//# sourceMappingURL=es2015.generator.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.d.ts.map new file mode 100644 index 00000000..d22be27d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.generator.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.generator.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,gBAAgB,EAAE,aAO9B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.js new file mode 100644 index 00000000..0b51a856 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.generator.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_generator = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +exports.es2015_generator = { + libs: [es2015_iterable_1.es2015_iterable], + variables: [ + ['Generator', base_config_1.TYPE], + ['GeneratorFunction', base_config_1.TYPE], + ['GeneratorFunctionConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.d.ts new file mode 100644 index 00000000..5a32cbbd --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_iterable: LibDefinition; +//# sourceMappingURL=es2015.iterable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.d.ts.map new file mode 100644 index 00000000..bb7bc33b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.iterable.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.iterable.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,eAAe,EAAE,aAoD7B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.js new file mode 100644 index 00000000..d91a0a7d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.iterable.js @@ -0,0 +1,62 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_iterable = void 0; +const base_config_1 = require("./base-config"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.es2015_iterable = { + libs: [es2015_symbol_1.es2015_symbol], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['IteratorYieldResult', base_config_1.TYPE], + ['IteratorReturnResult', base_config_1.TYPE], + ['IteratorResult', base_config_1.TYPE], + ['Iterator', base_config_1.TYPE], + ['Iterable', base_config_1.TYPE], + ['IterableIterator', base_config_1.TYPE], + ['IteratorObject', base_config_1.TYPE], + ['BuiltinIteratorReturn', base_config_1.TYPE], + ['ArrayIterator', base_config_1.TYPE], + ['Array', base_config_1.TYPE], + ['ArrayConstructor', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['IArguments', base_config_1.TYPE], + ['MapIterator', base_config_1.TYPE], + ['Map', base_config_1.TYPE], + ['ReadonlyMap', base_config_1.TYPE], + ['MapConstructor', base_config_1.TYPE], + ['WeakMap', base_config_1.TYPE], + ['WeakMapConstructor', base_config_1.TYPE], + ['SetIterator', base_config_1.TYPE], + ['Set', base_config_1.TYPE], + ['ReadonlySet', base_config_1.TYPE], + ['SetConstructor', base_config_1.TYPE], + ['WeakSet', base_config_1.TYPE], + ['WeakSetConstructor', base_config_1.TYPE], + ['Promise', base_config_1.TYPE], + ['PromiseConstructor', base_config_1.TYPE], + ['StringIterator', base_config_1.TYPE], + ['String', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Int8ArrayConstructor', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ArrayConstructor', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Uint8ClampedArrayConstructor', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Int16ArrayConstructor', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Uint16ArrayConstructor', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Int32ArrayConstructor', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Uint32ArrayConstructor', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float32ArrayConstructor', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ['Float64ArrayConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.js new file mode 100644 index 00000000..44ab404a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.js @@ -0,0 +1,32 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015 = void 0; +const es5_1 = require("./es5"); +const es2015_collection_1 = require("./es2015.collection"); +const es2015_core_1 = require("./es2015.core"); +const es2015_generator_1 = require("./es2015.generator"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_promise_1 = require("./es2015.promise"); +const es2015_proxy_1 = require("./es2015.proxy"); +const es2015_reflect_1 = require("./es2015.reflect"); +const es2015_symbol_1 = require("./es2015.symbol"); +const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown"); +exports.es2015 = { + libs: [ + es5_1.es5, + es2015_core_1.es2015_core, + es2015_collection_1.es2015_collection, + es2015_iterable_1.es2015_iterable, + es2015_generator_1.es2015_generator, + es2015_promise_1.es2015_promise, + es2015_proxy_1.es2015_proxy, + es2015_reflect_1.es2015_reflect, + es2015_symbol_1.es2015_symbol, + es2015_symbol_wellknown_1.es2015_symbol_wellknown, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.d.ts new file mode 100644 index 00000000..068e487a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_promise: LibDefinition; +//# sourceMappingURL=es2015.promise.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.d.ts.map new file mode 100644 index 00000000..1eb7cf9e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.promise.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.promise.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,cAAc,EAAE,aAG5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.js new file mode 100644 index 00000000..aca59619 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.promise.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_promise = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_promise = { + libs: [], + variables: [['PromiseConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.d.ts new file mode 100644 index 00000000..a676c812 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_proxy: LibDefinition; +//# sourceMappingURL=es2015.proxy.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.d.ts.map new file mode 100644 index 00000000..088e9680 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.proxy.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.proxy.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,YAAY,EAAE,aAM1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.js new file mode 100644 index 00000000..2ce5022e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.proxy.js @@ -0,0 +1,15 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_proxy = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_proxy = { + libs: [], + variables: [ + ['ProxyHandler', base_config_1.TYPE], + ['ProxyConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.d.ts new file mode 100644 index 00000000..13343fdd --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_reflect: LibDefinition; +//# sourceMappingURL=es2015.reflect.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.d.ts.map new file mode 100644 index 00000000..2aafc04d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.reflect.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.reflect.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,cAAc,EAAE,aAG5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.js new file mode 100644 index 00000000..0e29c2e4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.reflect.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_reflect = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_reflect = { + libs: [], + variables: [['Reflect', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.d.ts new file mode 100644 index 00000000..090c9ff2 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_symbol: LibDefinition; +//# sourceMappingURL=es2015.symbol.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.d.ts.map new file mode 100644 index 00000000..b202a755 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.symbol.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.symbol.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.js new file mode 100644 index 00000000..2baaf5ab --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_symbol = void 0; +const base_config_1 = require("./base-config"); +exports.es2015_symbol = { + libs: [], + variables: [['SymbolConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.d.ts new file mode 100644 index 00000000..7b7459b1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2015_symbol_wellknown: LibDefinition; +//# sourceMappingURL=es2015.symbol.wellknown.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.d.ts.map new file mode 100644 index 00000000..277f7546 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2015.symbol.wellknown.d.ts","sourceRoot":"","sources":["../../src/lib/es2015.symbol.wellknown.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,uBAAuB,EAAE,aAqCrC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.js new file mode 100644 index 00000000..fc5dadd7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2015.symbol.wellknown.js @@ -0,0 +1,47 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2015_symbol_wellknown = void 0; +const base_config_1 = require("./base-config"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.es2015_symbol_wellknown = { + libs: [es2015_symbol_1.es2015_symbol], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['Symbol', base_config_1.TYPE], + ['Array', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['Date', base_config_1.TYPE], + ['Map', base_config_1.TYPE], + ['WeakMap', base_config_1.TYPE], + ['Set', base_config_1.TYPE], + ['WeakSet', base_config_1.TYPE], + ['JSON', base_config_1.TYPE], + ['Function', base_config_1.TYPE], + ['GeneratorFunction', base_config_1.TYPE], + ['Math', base_config_1.TYPE], + ['Promise', base_config_1.TYPE], + ['PromiseConstructor', base_config_1.TYPE], + ['RegExp', base_config_1.TYPE], + ['RegExpConstructor', base_config_1.TYPE], + ['String', base_config_1.TYPE], + ['ArrayBuffer', base_config_1.TYPE], + ['DataView', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ['ArrayConstructor', base_config_1.TYPE], + ['MapConstructor', base_config_1.TYPE], + ['SetConstructor', base_config_1.TYPE], + ['ArrayBufferConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.d.ts new file mode 100644 index 00000000..33764ac0 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2016_array_include: LibDefinition; +//# sourceMappingURL=es2016.array.include.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.d.ts.map new file mode 100644 index 00000000..83a55721 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2016.array.include.d.ts","sourceRoot":"","sources":["../../src/lib/es2016.array.include.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,oBAAoB,EAAE,aAelC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.js new file mode 100644 index 00000000..baab2d1b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.array.include.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2016_array_include = void 0; +const base_config_1 = require("./base-config"); +exports.es2016_array_include = { + libs: [], + variables: [ + ['Array', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.d.ts new file mode 100644 index 00000000..3c1dbffe --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2016: LibDefinition; +//# sourceMappingURL=es2016.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.d.ts.map new file mode 100644 index 00000000..d5ec029b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2016.d.ts","sourceRoot":"","sources":["../../src/lib/es2016.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,eAAO,MAAM,MAAM,EAAE,aAGpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.d.ts new file mode 100644 index 00000000..45ec7bbc --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2016_full: LibDefinition; +//# sourceMappingURL=es2016.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.d.ts.map new file mode 100644 index 00000000..49a637e5 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2016.full.d.ts","sourceRoot":"","sources":["../../src/lib/es2016.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAQjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.js new file mode 100644 index 00000000..029ae1c3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.full.js @@ -0,0 +1,16 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2016_full = void 0; +const dom_1 = require("./dom"); +const dom_iterable_1 = require("./dom.iterable"); +const es2016_1 = require("./es2016"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2016_full = { + libs: [es2016_1.es2016, dom_1.dom, webworker_importscripts_1.webworker_importscripts, scripthost_1.scripthost, dom_iterable_1.dom_iterable], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.d.ts new file mode 100644 index 00000000..5dd851ac --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2016_intl: LibDefinition; +//# sourceMappingURL=es2016.intl.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.d.ts.map new file mode 100644 index 00000000..0a6ae8fe --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2016.intl.d.ts","sourceRoot":"","sources":["../../src/lib/es2016.intl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.js new file mode 100644 index 00000000..e32da505 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2016_intl = void 0; +const base_config_1 = require("./base-config"); +exports.es2016_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.js new file mode 100644 index 00000000..b98f66db --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2016.js @@ -0,0 +1,14 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2016 = void 0; +const es2015_1 = require("./es2015"); +const es2016_array_include_1 = require("./es2016.array.include"); +const es2016_intl_1 = require("./es2016.intl"); +exports.es2016 = { + libs: [es2015_1.es2015, es2016_array_include_1.es2016_array_include, es2016_intl_1.es2016_intl], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.d.ts new file mode 100644 index 00000000..19f8e7ce --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_arraybuffer: LibDefinition; +//# sourceMappingURL=es2017.arraybuffer.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.d.ts.map new file mode 100644 index 00000000..b1ec8088 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2017.arraybuffer.d.ts","sourceRoot":"","sources":["../../src/lib/es2017.arraybuffer.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,kBAAkB,EAAE,aAGhC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.js new file mode 100644 index 00000000..8f96439a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.arraybuffer.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_arraybuffer = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_arraybuffer = { + libs: [], + variables: [['ArrayBufferConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.d.ts new file mode 100644 index 00000000..223471fd --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017: LibDefinition; +//# sourceMappingURL=es2017.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.d.ts.map new file mode 100644 index 00000000..62cc070c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2017.d.ts","sourceRoot":"","sources":["../../src/lib/es2017.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAWjD,eAAO,MAAM,MAAM,EAAE,aAYpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.d.ts new file mode 100644 index 00000000..3274ee12 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_date: LibDefinition; +//# sourceMappingURL=es2017.date.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.d.ts.map new file mode 100644 index 00000000..c37dfb1f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2017.date.d.ts","sourceRoot":"","sources":["../../src/lib/es2017.date.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.js new file mode 100644 index 00000000..5e54f22f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.date.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_date = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_date = { + libs: [], + variables: [['DateConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.d.ts new file mode 100644 index 00000000..d926cc7d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_full: LibDefinition; +//# sourceMappingURL=es2017.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.d.ts.map new file mode 100644 index 00000000..e4742156 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2017.full.d.ts","sourceRoot":"","sources":["../../src/lib/es2017.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAQjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.js new file mode 100644 index 00000000..12a1568e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.full.js @@ -0,0 +1,16 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_full = void 0; +const dom_1 = require("./dom"); +const dom_iterable_1 = require("./dom.iterable"); +const es2017_1 = require("./es2017"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2017_full = { + libs: [es2017_1.es2017, dom_1.dom, webworker_importscripts_1.webworker_importscripts, scripthost_1.scripthost, dom_iterable_1.dom_iterable], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.d.ts new file mode 100644 index 00000000..7123ef6f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_intl: LibDefinition; +//# sourceMappingURL=es2017.intl.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.d.ts.map new file mode 100644 index 00000000..4898b0c1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2017.intl.d.ts","sourceRoot":"","sources":["../../src/lib/es2017.intl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.js new file mode 100644 index 00000000..4b9ba6a7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_intl = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.js new file mode 100644 index 00000000..bef7d0c7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.js @@ -0,0 +1,28 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017 = void 0; +const es2016_1 = require("./es2016"); +const es2017_arraybuffer_1 = require("./es2017.arraybuffer"); +const es2017_date_1 = require("./es2017.date"); +const es2017_intl_1 = require("./es2017.intl"); +const es2017_object_1 = require("./es2017.object"); +const es2017_sharedmemory_1 = require("./es2017.sharedmemory"); +const es2017_string_1 = require("./es2017.string"); +const es2017_typedarrays_1 = require("./es2017.typedarrays"); +exports.es2017 = { + libs: [ + es2016_1.es2016, + es2017_arraybuffer_1.es2017_arraybuffer, + es2017_date_1.es2017_date, + es2017_intl_1.es2017_intl, + es2017_object_1.es2017_object, + es2017_sharedmemory_1.es2017_sharedmemory, + es2017_string_1.es2017_string, + es2017_typedarrays_1.es2017_typedarrays, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.d.ts new file mode 100644 index 00000000..342c5856 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_object: LibDefinition; +//# sourceMappingURL=es2017.object.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.d.ts.map new file mode 100644 index 00000000..b18737de --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2017.object.d.ts","sourceRoot":"","sources":["../../src/lib/es2017.object.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.js new file mode 100644 index 00000000..85c7b95b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.object.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_object = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_object = { + libs: [], + variables: [['ObjectConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.d.ts new file mode 100644 index 00000000..d158e6d4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_sharedmemory: LibDefinition; +//# sourceMappingURL=es2017.sharedmemory.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.d.ts.map new file mode 100644 index 00000000..271fdbf3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2017.sharedmemory.d.ts","sourceRoot":"","sources":["../../src/lib/es2017.sharedmemory.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,eAAO,MAAM,mBAAmB,EAAE,aAQjC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.js new file mode 100644 index 00000000..66d08440 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.sharedmemory.js @@ -0,0 +1,19 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_sharedmemory = void 0; +const base_config_1 = require("./base-config"); +const es2015_symbol_1 = require("./es2015.symbol"); +const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown"); +exports.es2017_sharedmemory = { + libs: [es2015_symbol_1.es2015_symbol, es2015_symbol_wellknown_1.es2015_symbol_wellknown], + variables: [ + ['SharedArrayBuffer', base_config_1.TYPE_VALUE], + ['SharedArrayBufferConstructor', base_config_1.TYPE], + ['ArrayBufferTypes', base_config_1.TYPE], + ['Atomics', base_config_1.TYPE_VALUE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.d.ts new file mode 100644 index 00000000..9171867e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_string: LibDefinition; +//# sourceMappingURL=es2017.string.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.d.ts.map new file mode 100644 index 00000000..0d175b0b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2017.string.d.ts","sourceRoot":"","sources":["../../src/lib/es2017.string.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.js new file mode 100644 index 00000000..30939851 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.string.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_string = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_string = { + libs: [], + variables: [['String', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.d.ts new file mode 100644 index 00000000..c13588b2 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2017_typedarrays: LibDefinition; +//# sourceMappingURL=es2017.typedarrays.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.d.ts.map new file mode 100644 index 00000000..9eee679b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2017.typedarrays.d.ts","sourceRoot":"","sources":["../../src/lib/es2017.typedarrays.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,kBAAkB,EAAE,aAahC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.js new file mode 100644 index 00000000..986aed96 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2017.typedarrays.js @@ -0,0 +1,22 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2017_typedarrays = void 0; +const base_config_1 = require("./base-config"); +exports.es2017_typedarrays = { + libs: [], + variables: [ + ['Int8ArrayConstructor', base_config_1.TYPE], + ['Uint8ArrayConstructor', base_config_1.TYPE], + ['Uint8ClampedArrayConstructor', base_config_1.TYPE], + ['Int16ArrayConstructor', base_config_1.TYPE], + ['Uint16ArrayConstructor', base_config_1.TYPE], + ['Int32ArrayConstructor', base_config_1.TYPE], + ['Uint32ArrayConstructor', base_config_1.TYPE], + ['Float32ArrayConstructor', base_config_1.TYPE], + ['Float64ArrayConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.d.ts new file mode 100644 index 00000000..3818eb08 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018_asyncgenerator: LibDefinition; +//# sourceMappingURL=es2018.asyncgenerator.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.d.ts.map new file mode 100644 index 00000000..d49718bf --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2018.asyncgenerator.d.ts","sourceRoot":"","sources":["../../src/lib/es2018.asyncgenerator.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,qBAAqB,EAAE,aAOnC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.js new file mode 100644 index 00000000..653f3733 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asyncgenerator.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2018_asyncgenerator = void 0; +const base_config_1 = require("./base-config"); +const es2018_asynciterable_1 = require("./es2018.asynciterable"); +exports.es2018_asyncgenerator = { + libs: [es2018_asynciterable_1.es2018_asynciterable], + variables: [ + ['AsyncGenerator', base_config_1.TYPE], + ['AsyncGeneratorFunction', base_config_1.TYPE], + ['AsyncGeneratorFunctionConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.d.ts new file mode 100644 index 00000000..0fbf6b8c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018_asynciterable: LibDefinition; +//# sourceMappingURL=es2018.asynciterable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.d.ts.map new file mode 100644 index 00000000..5924c703 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2018.asynciterable.d.ts","sourceRoot":"","sources":["../../src/lib/es2018.asynciterable.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,eAAO,MAAM,oBAAoB,EAAE,aASlC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.js new file mode 100644 index 00000000..028f65ca --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.asynciterable.js @@ -0,0 +1,20 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2018_asynciterable = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.es2018_asynciterable = { + libs: [es2015_symbol_1.es2015_symbol, es2015_iterable_1.es2015_iterable], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['AsyncIterator', base_config_1.TYPE], + ['AsyncIterable', base_config_1.TYPE], + ['AsyncIterableIterator', base_config_1.TYPE], + ['AsyncIteratorObject', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.d.ts new file mode 100644 index 00000000..e33ea9a7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018: LibDefinition; +//# sourceMappingURL=es2018.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.d.ts.map new file mode 100644 index 00000000..765264dc --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2018.d.ts","sourceRoot":"","sources":["../../src/lib/es2018.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,MAAM,EAAE,aAUpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.d.ts new file mode 100644 index 00000000..402d09dd --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018_full: LibDefinition; +//# sourceMappingURL=es2018.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.d.ts.map new file mode 100644 index 00000000..06e8c0f6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2018.full.d.ts","sourceRoot":"","sources":["../../src/lib/es2018.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,WAAW,EAAE,aAUzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.js new file mode 100644 index 00000000..51466f55 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.full.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2018_full = void 0; +const dom_1 = require("./dom"); +const dom_asynciterable_1 = require("./dom.asynciterable"); +const dom_iterable_1 = require("./dom.iterable"); +const es2018_1 = require("./es2018"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2018_full = { + libs: [ + es2018_1.es2018, + dom_1.dom, + webworker_importscripts_1.webworker_importscripts, + scripthost_1.scripthost, + dom_iterable_1.dom_iterable, + dom_asynciterable_1.dom_asynciterable, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.intl.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.intl.d.ts new file mode 100644 index 00000000..41528e3e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.intl.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018_intl: LibDefinition; +//# sourceMappingURL=es2018.intl.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.intl.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.intl.d.ts.map new file mode 100644 index 00000000..73b8c8bd --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.intl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2018.intl.d.ts","sourceRoot":"","sources":["../../src/lib/es2018.intl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.intl.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.intl.js new file mode 100644 index 00000000..f5a83a96 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2018_intl = void 0; +const base_config_1 = require("./base-config"); +exports.es2018_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.js new file mode 100644 index 00000000..d618693d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2018 = void 0; +const es2017_1 = require("./es2017"); +const es2018_asyncgenerator_1 = require("./es2018.asyncgenerator"); +const es2018_asynciterable_1 = require("./es2018.asynciterable"); +const es2018_intl_1 = require("./es2018.intl"); +const es2018_promise_1 = require("./es2018.promise"); +const es2018_regexp_1 = require("./es2018.regexp"); +exports.es2018 = { + libs: [ + es2017_1.es2017, + es2018_asynciterable_1.es2018_asynciterable, + es2018_asyncgenerator_1.es2018_asyncgenerator, + es2018_promise_1.es2018_promise, + es2018_regexp_1.es2018_regexp, + es2018_intl_1.es2018_intl, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.promise.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.promise.d.ts new file mode 100644 index 00000000..fe5e0e86 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.promise.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018_promise: LibDefinition; +//# sourceMappingURL=es2018.promise.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.promise.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.promise.d.ts.map new file mode 100644 index 00000000..ecfcc36e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2018.promise.d.ts","sourceRoot":"","sources":["../../src/lib/es2018.promise.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,cAAc,EAAE,aAG5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.promise.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.promise.js new file mode 100644 index 00000000..d4bafd7c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.promise.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2018_promise = void 0; +const base_config_1 = require("./base-config"); +exports.es2018_promise = { + libs: [], + variables: [['Promise', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.regexp.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.regexp.d.ts new file mode 100644 index 00000000..ddc6a5bb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.regexp.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2018_regexp: LibDefinition; +//# sourceMappingURL=es2018.regexp.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.regexp.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.regexp.d.ts.map new file mode 100644 index 00000000..978490d6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.regexp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2018.regexp.d.ts","sourceRoot":"","sources":["../../src/lib/es2018.regexp.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAO3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.regexp.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.regexp.js new file mode 100644 index 00000000..3de3e33d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2018.regexp.js @@ -0,0 +1,16 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2018_regexp = void 0; +const base_config_1 = require("./base-config"); +exports.es2018_regexp = { + libs: [], + variables: [ + ['RegExpMatchArray', base_config_1.TYPE], + ['RegExpExecArray', base_config_1.TYPE], + ['RegExp', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.array.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.array.d.ts new file mode 100644 index 00000000..472ea9a6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.array.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2019_array: LibDefinition; +//# sourceMappingURL=es2019.array.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.array.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.array.d.ts.map new file mode 100644 index 00000000..876a8eba --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2019.array.d.ts","sourceRoot":"","sources":["../../src/lib/es2019.array.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,YAAY,EAAE,aAO1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.array.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.array.js new file mode 100644 index 00000000..8b314e60 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.array.js @@ -0,0 +1,16 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2019_array = void 0; +const base_config_1 = require("./base-config"); +exports.es2019_array = { + libs: [], + variables: [ + ['FlatArray', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['Array', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.d.ts new file mode 100644 index 00000000..0d1ec218 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2019: LibDefinition; +//# sourceMappingURL=es2019.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.d.ts.map new file mode 100644 index 00000000..0337d9bb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2019.d.ts","sourceRoot":"","sources":["../../src/lib/es2019.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,MAAM,EAAE,aAUpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.full.d.ts new file mode 100644 index 00000000..35fd9394 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2019_full: LibDefinition; +//# sourceMappingURL=es2019.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.full.d.ts.map new file mode 100644 index 00000000..accff5ae --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2019.full.d.ts","sourceRoot":"","sources":["../../src/lib/es2019.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,WAAW,EAAE,aAUzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.full.js new file mode 100644 index 00000000..e9d25030 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.full.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2019_full = void 0; +const dom_1 = require("./dom"); +const dom_asynciterable_1 = require("./dom.asynciterable"); +const dom_iterable_1 = require("./dom.iterable"); +const es2019_1 = require("./es2019"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2019_full = { + libs: [ + es2019_1.es2019, + dom_1.dom, + webworker_importscripts_1.webworker_importscripts, + scripthost_1.scripthost, + dom_iterable_1.dom_iterable, + dom_asynciterable_1.dom_asynciterable, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.intl.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.intl.d.ts new file mode 100644 index 00000000..2d8c374a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.intl.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2019_intl: LibDefinition; +//# sourceMappingURL=es2019.intl.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.intl.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.intl.d.ts.map new file mode 100644 index 00000000..f83ecbfb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.intl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2019.intl.d.ts","sourceRoot":"","sources":["../../src/lib/es2019.intl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.intl.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.intl.js new file mode 100644 index 00000000..01c94691 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2019_intl = void 0; +const base_config_1 = require("./base-config"); +exports.es2019_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.js new file mode 100644 index 00000000..de5c6a2f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2019 = void 0; +const es2018_1 = require("./es2018"); +const es2019_array_1 = require("./es2019.array"); +const es2019_intl_1 = require("./es2019.intl"); +const es2019_object_1 = require("./es2019.object"); +const es2019_string_1 = require("./es2019.string"); +const es2019_symbol_1 = require("./es2019.symbol"); +exports.es2019 = { + libs: [ + es2018_1.es2018, + es2019_array_1.es2019_array, + es2019_object_1.es2019_object, + es2019_string_1.es2019_string, + es2019_symbol_1.es2019_symbol, + es2019_intl_1.es2019_intl, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.object.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.object.d.ts new file mode 100644 index 00000000..7f2934ae --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.object.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2019_object: LibDefinition; +//# sourceMappingURL=es2019.object.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.object.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.object.d.ts.map new file mode 100644 index 00000000..ba581cfc --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2019.object.d.ts","sourceRoot":"","sources":["../../src/lib/es2019.object.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.object.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.object.js new file mode 100644 index 00000000..2d197bb8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.object.js @@ -0,0 +1,13 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2019_object = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +exports.es2019_object = { + libs: [es2015_iterable_1.es2015_iterable], + variables: [['ObjectConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.string.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.string.d.ts new file mode 100644 index 00000000..06eb0d53 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.string.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2019_string: LibDefinition; +//# sourceMappingURL=es2019.string.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.string.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.string.d.ts.map new file mode 100644 index 00000000..0abb46a3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2019.string.d.ts","sourceRoot":"","sources":["../../src/lib/es2019.string.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.string.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.string.js new file mode 100644 index 00000000..b311a5b4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.string.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2019_string = void 0; +const base_config_1 = require("./base-config"); +exports.es2019_string = { + libs: [], + variables: [['String', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.symbol.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.symbol.d.ts new file mode 100644 index 00000000..8b97e469 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.symbol.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2019_symbol: LibDefinition; +//# sourceMappingURL=es2019.symbol.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.symbol.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.symbol.d.ts.map new file mode 100644 index 00000000..dd77e9f5 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.symbol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2019.symbol.d.ts","sourceRoot":"","sources":["../../src/lib/es2019.symbol.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.symbol.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.symbol.js new file mode 100644 index 00000000..af24022c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2019.symbol.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2019_symbol = void 0; +const base_config_1 = require("./base-config"); +exports.es2019_symbol = { + libs: [], + variables: [['Symbol', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.bigint.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.bigint.d.ts new file mode 100644 index 00000000..a29cab30 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.bigint.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020_bigint: LibDefinition; +//# sourceMappingURL=es2020.bigint.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.bigint.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.bigint.d.ts.map new file mode 100644 index 00000000..188837f3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.bigint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.bigint.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.bigint.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,aAAa,EAAE,aAa3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.bigint.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.bigint.js new file mode 100644 index 00000000..8956da3d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.bigint.js @@ -0,0 +1,23 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020_bigint = void 0; +const base_config_1 = require("./base-config"); +const es2020_intl_1 = require("./es2020.intl"); +exports.es2020_bigint = { + libs: [es2020_intl_1.es2020_intl], + variables: [ + ['BigIntToLocaleStringOptions', base_config_1.TYPE], + ['BigInt', base_config_1.TYPE_VALUE], + ['BigIntConstructor', base_config_1.TYPE], + ['BigInt64Array', base_config_1.TYPE_VALUE], + ['BigInt64ArrayConstructor', base_config_1.TYPE], + ['BigUint64Array', base_config_1.TYPE_VALUE], + ['BigUint64ArrayConstructor', base_config_1.TYPE], + ['DataView', base_config_1.TYPE], + ['Intl', base_config_1.TYPE_VALUE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.d.ts new file mode 100644 index 00000000..64176b88 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020: LibDefinition; +//# sourceMappingURL=es2020.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.d.ts.map new file mode 100644 index 00000000..dc85ad49 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAYjD,eAAO,MAAM,MAAM,EAAE,aAapB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.date.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.date.d.ts new file mode 100644 index 00000000..9a5b53ac --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.date.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020_date: LibDefinition; +//# sourceMappingURL=es2020.date.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.date.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.date.d.ts.map new file mode 100644 index 00000000..03be4760 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.date.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.date.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.date.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.date.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.date.js new file mode 100644 index 00000000..adcad452 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.date.js @@ -0,0 +1,13 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020_date = void 0; +const base_config_1 = require("./base-config"); +const es2020_intl_1 = require("./es2020.intl"); +exports.es2020_date = { + libs: [es2020_intl_1.es2020_intl], + variables: [['Date', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.full.d.ts new file mode 100644 index 00000000..fbc478ca --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020_full: LibDefinition; +//# sourceMappingURL=es2020.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.full.d.ts.map new file mode 100644 index 00000000..3e634397 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.full.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,WAAW,EAAE,aAUzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.full.js new file mode 100644 index 00000000..200fedf5 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.full.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020_full = void 0; +const dom_1 = require("./dom"); +const dom_asynciterable_1 = require("./dom.asynciterable"); +const dom_iterable_1 = require("./dom.iterable"); +const es2020_1 = require("./es2020"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2020_full = { + libs: [ + es2020_1.es2020, + dom_1.dom, + webworker_importscripts_1.webworker_importscripts, + scripthost_1.scripthost, + dom_iterable_1.dom_iterable, + dom_asynciterable_1.dom_asynciterable, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.intl.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.intl.d.ts new file mode 100644 index 00000000..c84bc476 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.intl.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020_intl: LibDefinition; +//# sourceMappingURL=es2020.intl.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.intl.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.intl.d.ts.map new file mode 100644 index 00000000..49e71a87 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.intl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.intl.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.intl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.intl.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.intl.js new file mode 100644 index 00000000..36a0f079 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.intl.js @@ -0,0 +1,13 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020_intl = void 0; +const base_config_1 = require("./base-config"); +const es2018_intl_1 = require("./es2018.intl"); +exports.es2020_intl = { + libs: [es2018_intl_1.es2018_intl], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.js new file mode 100644 index 00000000..99976671 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.js @@ -0,0 +1,30 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020 = void 0; +const es2019_1 = require("./es2019"); +const es2020_bigint_1 = require("./es2020.bigint"); +const es2020_date_1 = require("./es2020.date"); +const es2020_intl_1 = require("./es2020.intl"); +const es2020_number_1 = require("./es2020.number"); +const es2020_promise_1 = require("./es2020.promise"); +const es2020_sharedmemory_1 = require("./es2020.sharedmemory"); +const es2020_string_1 = require("./es2020.string"); +const es2020_symbol_wellknown_1 = require("./es2020.symbol.wellknown"); +exports.es2020 = { + libs: [ + es2019_1.es2019, + es2020_bigint_1.es2020_bigint, + es2020_date_1.es2020_date, + es2020_number_1.es2020_number, + es2020_promise_1.es2020_promise, + es2020_sharedmemory_1.es2020_sharedmemory, + es2020_string_1.es2020_string, + es2020_symbol_wellknown_1.es2020_symbol_wellknown, + es2020_intl_1.es2020_intl, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.number.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.number.d.ts new file mode 100644 index 00000000..cd570115 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.number.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020_number: LibDefinition; +//# sourceMappingURL=es2020.number.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.number.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.number.d.ts.map new file mode 100644 index 00000000..ab03a3f8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.number.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.number.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.number.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.number.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.number.js new file mode 100644 index 00000000..bafbf935 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.number.js @@ -0,0 +1,13 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020_number = void 0; +const base_config_1 = require("./base-config"); +const es2020_intl_1 = require("./es2020.intl"); +exports.es2020_number = { + libs: [es2020_intl_1.es2020_intl], + variables: [['Number', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.promise.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.promise.d.ts new file mode 100644 index 00000000..89497502 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.promise.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020_promise: LibDefinition; +//# sourceMappingURL=es2020.promise.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.promise.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.promise.d.ts.map new file mode 100644 index 00000000..c0d5b545 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.promise.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.promise.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,cAAc,EAAE,aAQ5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.promise.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.promise.js new file mode 100644 index 00000000..0640cef3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.promise.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020_promise = void 0; +const base_config_1 = require("./base-config"); +exports.es2020_promise = { + libs: [], + variables: [ + ['PromiseFulfilledResult', base_config_1.TYPE], + ['PromiseRejectedResult', base_config_1.TYPE], + ['PromiseSettledResult', base_config_1.TYPE], + ['PromiseConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.sharedmemory.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.sharedmemory.d.ts new file mode 100644 index 00000000..1b4d58de --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.sharedmemory.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020_sharedmemory: LibDefinition; +//# sourceMappingURL=es2020.sharedmemory.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.sharedmemory.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.sharedmemory.d.ts.map new file mode 100644 index 00000000..a7acf316 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.sharedmemory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.sharedmemory.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.sharedmemory.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,mBAAmB,EAAE,aAGjC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.sharedmemory.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.sharedmemory.js new file mode 100644 index 00000000..d9455474 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.sharedmemory.js @@ -0,0 +1,13 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020_sharedmemory = void 0; +const base_config_1 = require("./base-config"); +const es2020_bigint_1 = require("./es2020.bigint"); +exports.es2020_sharedmemory = { + libs: [es2020_bigint_1.es2020_bigint], + variables: [['Atomics', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.string.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.string.d.ts new file mode 100644 index 00000000..1f7fa0c6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.string.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020_string: LibDefinition; +//# sourceMappingURL=es2020.string.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.string.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.string.d.ts.map new file mode 100644 index 00000000..53fcbe96 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.string.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.string.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAOjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.string.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.string.js new file mode 100644 index 00000000..78390dae --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.string.js @@ -0,0 +1,15 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020_string = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2020_intl_1 = require("./es2020.intl"); +const es2020_symbol_wellknown_1 = require("./es2020.symbol.wellknown"); +exports.es2020_string = { + libs: [es2015_iterable_1.es2015_iterable, es2020_intl_1.es2020_intl, es2020_symbol_wellknown_1.es2020_symbol_wellknown], + variables: [['String', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.symbol.wellknown.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.symbol.wellknown.d.ts new file mode 100644 index 00000000..665469cb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.symbol.wellknown.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2020_symbol_wellknown: LibDefinition; +//# sourceMappingURL=es2020.symbol.wellknown.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.symbol.wellknown.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.symbol.wellknown.d.ts.map new file mode 100644 index 00000000..430d5d06 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.symbol.wellknown.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2020.symbol.wellknown.d.ts","sourceRoot":"","sources":["../../src/lib/es2020.symbol.wellknown.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,eAAO,MAAM,uBAAuB,EAAE,aAOrC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.symbol.wellknown.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.symbol.wellknown.js new file mode 100644 index 00000000..23374c4c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2020.symbol.wellknown.js @@ -0,0 +1,18 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2020_symbol_wellknown = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.es2020_symbol_wellknown = { + libs: [es2015_iterable_1.es2015_iterable, es2015_symbol_1.es2015_symbol], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['RegExpStringIterator', base_config_1.TYPE], + ['RegExp', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.d.ts new file mode 100644 index 00000000..a86d6174 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2021: LibDefinition; +//# sourceMappingURL=es2021.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.d.ts.map new file mode 100644 index 00000000..b362a0f7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2021.d.ts","sourceRoot":"","sources":["../../src/lib/es2021.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAQjD,eAAO,MAAM,MAAM,EAAE,aAGpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.full.d.ts new file mode 100644 index 00000000..c3c7602f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2021_full: LibDefinition; +//# sourceMappingURL=es2021.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.full.d.ts.map new file mode 100644 index 00000000..913239e7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2021.full.d.ts","sourceRoot":"","sources":["../../src/lib/es2021.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,WAAW,EAAE,aAUzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.full.js new file mode 100644 index 00000000..09d9eada --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.full.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2021_full = void 0; +const dom_1 = require("./dom"); +const dom_asynciterable_1 = require("./dom.asynciterable"); +const dom_iterable_1 = require("./dom.iterable"); +const es2021_1 = require("./es2021"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2021_full = { + libs: [ + es2021_1.es2021, + dom_1.dom, + webworker_importscripts_1.webworker_importscripts, + scripthost_1.scripthost, + dom_iterable_1.dom_iterable, + dom_asynciterable_1.dom_asynciterable, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.intl.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.intl.d.ts new file mode 100644 index 00000000..8e3a1bc1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.intl.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2021_intl: LibDefinition; +//# sourceMappingURL=es2021.intl.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.intl.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.intl.d.ts.map new file mode 100644 index 00000000..9a95e0f5 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.intl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2021.intl.d.ts","sourceRoot":"","sources":["../../src/lib/es2021.intl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.intl.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.intl.js new file mode 100644 index 00000000..e4f17846 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2021_intl = void 0; +const base_config_1 = require("./base-config"); +exports.es2021_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.js new file mode 100644 index 00000000..a62791f4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.js @@ -0,0 +1,16 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2021 = void 0; +const es2020_1 = require("./es2020"); +const es2021_intl_1 = require("./es2021.intl"); +const es2021_promise_1 = require("./es2021.promise"); +const es2021_string_1 = require("./es2021.string"); +const es2021_weakref_1 = require("./es2021.weakref"); +exports.es2021 = { + libs: [es2020_1.es2020, es2021_promise_1.es2021_promise, es2021_string_1.es2021_string, es2021_weakref_1.es2021_weakref, es2021_intl_1.es2021_intl], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.promise.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.promise.d.ts new file mode 100644 index 00000000..03f0452b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.promise.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2021_promise: LibDefinition; +//# sourceMappingURL=es2021.promise.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.promise.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.promise.d.ts.map new file mode 100644 index 00000000..4c4bdaac --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2021.promise.d.ts","sourceRoot":"","sources":["../../src/lib/es2021.promise.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,cAAc,EAAE,aAO5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.promise.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.promise.js new file mode 100644 index 00000000..515cebc2 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.promise.js @@ -0,0 +1,16 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2021_promise = void 0; +const base_config_1 = require("./base-config"); +exports.es2021_promise = { + libs: [], + variables: [ + ['AggregateError', base_config_1.TYPE_VALUE], + ['AggregateErrorConstructor', base_config_1.TYPE], + ['PromiseConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.string.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.string.d.ts new file mode 100644 index 00000000..9056865d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.string.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2021_string: LibDefinition; +//# sourceMappingURL=es2021.string.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.string.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.string.d.ts.map new file mode 100644 index 00000000..f2afcab0 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2021.string.d.ts","sourceRoot":"","sources":["../../src/lib/es2021.string.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.string.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.string.js new file mode 100644 index 00000000..54dd1318 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.string.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2021_string = void 0; +const base_config_1 = require("./base-config"); +exports.es2021_string = { + libs: [], + variables: [['String', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.weakref.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.weakref.d.ts new file mode 100644 index 00000000..e54c83cd --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.weakref.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2021_weakref: LibDefinition; +//# sourceMappingURL=es2021.weakref.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.weakref.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.weakref.d.ts.map new file mode 100644 index 00000000..98aee9b8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.weakref.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2021.weakref.d.ts","sourceRoot":"","sources":["../../src/lib/es2021.weakref.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,cAAc,EAAE,aAQ5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.weakref.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.weakref.js new file mode 100644 index 00000000..5e85a24c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2021.weakref.js @@ -0,0 +1,18 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2021_weakref = void 0; +const base_config_1 = require("./base-config"); +const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown"); +exports.es2021_weakref = { + libs: [es2015_symbol_wellknown_1.es2015_symbol_wellknown], + variables: [ + ['WeakRef', base_config_1.TYPE_VALUE], + ['WeakRefConstructor', base_config_1.TYPE], + ['FinalizationRegistry', base_config_1.TYPE_VALUE], + ['FinalizationRegistryConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.array.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.array.d.ts new file mode 100644 index 00000000..5f99f51d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.array.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2022_array: LibDefinition; +//# sourceMappingURL=es2022.array.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.array.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.array.d.ts.map new file mode 100644 index 00000000..5d96a1f4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2022.array.d.ts","sourceRoot":"","sources":["../../src/lib/es2022.array.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,YAAY,EAAE,aAiB1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.array.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.array.js new file mode 100644 index 00000000..f66580d9 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.array.js @@ -0,0 +1,26 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2022_array = void 0; +const base_config_1 = require("./base-config"); +exports.es2022_array = { + libs: [], + variables: [ + ['Array', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ['BigInt64Array', base_config_1.TYPE], + ['BigUint64Array', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.d.ts new file mode 100644 index 00000000..1100d514 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2022: LibDefinition; +//# sourceMappingURL=es2022.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.d.ts.map new file mode 100644 index 00000000..5db589f3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2022.d.ts","sourceRoot":"","sources":["../../src/lib/es2022.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAUjD,eAAO,MAAM,MAAM,EAAE,aAWpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.error.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.error.d.ts new file mode 100644 index 00000000..c7a5d21e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.error.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2022_error: LibDefinition; +//# sourceMappingURL=es2022.error.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.error.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.error.d.ts.map new file mode 100644 index 00000000..5d290532 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2022.error.d.ts","sourceRoot":"","sources":["../../src/lib/es2022.error.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,YAAY,EAAE,aAc1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.error.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.error.js new file mode 100644 index 00000000..a880a6e0 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.error.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2022_error = void 0; +const base_config_1 = require("./base-config"); +const es2021_promise_1 = require("./es2021.promise"); +exports.es2022_error = { + libs: [es2021_promise_1.es2021_promise], + variables: [ + ['ErrorOptions', base_config_1.TYPE], + ['Error', base_config_1.TYPE], + ['ErrorConstructor', base_config_1.TYPE], + ['EvalErrorConstructor', base_config_1.TYPE], + ['RangeErrorConstructor', base_config_1.TYPE], + ['ReferenceErrorConstructor', base_config_1.TYPE], + ['SyntaxErrorConstructor', base_config_1.TYPE], + ['TypeErrorConstructor', base_config_1.TYPE], + ['URIErrorConstructor', base_config_1.TYPE], + ['AggregateErrorConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.full.d.ts new file mode 100644 index 00000000..8543df3f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2022_full: LibDefinition; +//# sourceMappingURL=es2022.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.full.d.ts.map new file mode 100644 index 00000000..bfd70a03 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2022.full.d.ts","sourceRoot":"","sources":["../../src/lib/es2022.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,WAAW,EAAE,aAUzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.full.js new file mode 100644 index 00000000..378631b3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.full.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2022_full = void 0; +const dom_1 = require("./dom"); +const dom_asynciterable_1 = require("./dom.asynciterable"); +const dom_iterable_1 = require("./dom.iterable"); +const es2022_1 = require("./es2022"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2022_full = { + libs: [ + es2022_1.es2022, + dom_1.dom, + webworker_importscripts_1.webworker_importscripts, + scripthost_1.scripthost, + dom_iterable_1.dom_iterable, + dom_asynciterable_1.dom_asynciterable, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.intl.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.intl.d.ts new file mode 100644 index 00000000..f5640484 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.intl.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2022_intl: LibDefinition; +//# sourceMappingURL=es2022.intl.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.intl.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.intl.d.ts.map new file mode 100644 index 00000000..40c294c4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.intl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2022.intl.d.ts","sourceRoot":"","sources":["../../src/lib/es2022.intl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.intl.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.intl.js new file mode 100644 index 00000000..afe167df --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2022_intl = void 0; +const base_config_1 = require("./base-config"); +exports.es2022_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.js new file mode 100644 index 00000000..382f73da --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.js @@ -0,0 +1,26 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2022 = void 0; +const es2021_1 = require("./es2021"); +const es2022_array_1 = require("./es2022.array"); +const es2022_error_1 = require("./es2022.error"); +const es2022_intl_1 = require("./es2022.intl"); +const es2022_object_1 = require("./es2022.object"); +const es2022_regexp_1 = require("./es2022.regexp"); +const es2022_string_1 = require("./es2022.string"); +exports.es2022 = { + libs: [ + es2021_1.es2021, + es2022_array_1.es2022_array, + es2022_error_1.es2022_error, + es2022_intl_1.es2022_intl, + es2022_object_1.es2022_object, + es2022_regexp_1.es2022_regexp, + es2022_string_1.es2022_string, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.object.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.object.d.ts new file mode 100644 index 00000000..b5d327f7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.object.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2022_object: LibDefinition; +//# sourceMappingURL=es2022.object.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.object.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.object.d.ts.map new file mode 100644 index 00000000..e6d4b076 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2022.object.d.ts","sourceRoot":"","sources":["../../src/lib/es2022.object.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.object.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.object.js new file mode 100644 index 00000000..81699acd --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.object.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2022_object = void 0; +const base_config_1 = require("./base-config"); +exports.es2022_object = { + libs: [], + variables: [['ObjectConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.regexp.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.regexp.d.ts new file mode 100644 index 00000000..5c087d77 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.regexp.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2022_regexp: LibDefinition; +//# sourceMappingURL=es2022.regexp.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.regexp.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.regexp.d.ts.map new file mode 100644 index 00000000..d4ecb5b1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.regexp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2022.regexp.d.ts","sourceRoot":"","sources":["../../src/lib/es2022.regexp.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAQ3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.regexp.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.regexp.js new file mode 100644 index 00000000..ab785107 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.regexp.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2022_regexp = void 0; +const base_config_1 = require("./base-config"); +exports.es2022_regexp = { + libs: [], + variables: [ + ['RegExpMatchArray', base_config_1.TYPE], + ['RegExpExecArray', base_config_1.TYPE], + ['RegExpIndicesArray', base_config_1.TYPE], + ['RegExp', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.string.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.string.d.ts new file mode 100644 index 00000000..df11189a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.string.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2022_string: LibDefinition; +//# sourceMappingURL=es2022.string.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.string.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.string.d.ts.map new file mode 100644 index 00000000..c6b022e0 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2022.string.d.ts","sourceRoot":"","sources":["../../src/lib/es2022.string.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.string.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.string.js new file mode 100644 index 00000000..500dd504 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2022.string.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2022_string = void 0; +const base_config_1 = require("./base-config"); +exports.es2022_string = { + libs: [], + variables: [['String', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.array.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.array.d.ts new file mode 100644 index 00000000..77149050 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.array.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2023_array: LibDefinition; +//# sourceMappingURL=es2023.array.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.array.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.array.d.ts.map new file mode 100644 index 00000000..19221cff --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2023.array.d.ts","sourceRoot":"","sources":["../../src/lib/es2023.array.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,YAAY,EAAE,aAiB1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.array.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.array.js new file mode 100644 index 00000000..5b9a19bb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.array.js @@ -0,0 +1,26 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2023_array = void 0; +const base_config_1 = require("./base-config"); +exports.es2023_array = { + libs: [], + variables: [ + ['Array', base_config_1.TYPE], + ['ReadonlyArray', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE], + ['BigInt64Array', base_config_1.TYPE], + ['BigUint64Array', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.collection.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.collection.d.ts new file mode 100644 index 00000000..4d134a7d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.collection.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2023_collection: LibDefinition; +//# sourceMappingURL=es2023.collection.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.collection.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.collection.d.ts.map new file mode 100644 index 00000000..5e70e10a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.collection.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2023.collection.d.ts","sourceRoot":"","sources":["../../src/lib/es2023.collection.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,iBAAiB,EAAE,aAG/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.collection.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.collection.js new file mode 100644 index 00000000..b6ef0b3e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.collection.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2023_collection = void 0; +const base_config_1 = require("./base-config"); +exports.es2023_collection = { + libs: [], + variables: [['WeakKeyTypes', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.d.ts new file mode 100644 index 00000000..cf3f2ec0 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2023: LibDefinition; +//# sourceMappingURL=es2023.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.d.ts.map new file mode 100644 index 00000000..479c56a8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2023.d.ts","sourceRoot":"","sources":["../../src/lib/es2023.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAOjD,eAAO,MAAM,MAAM,EAAE,aAGpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.full.d.ts new file mode 100644 index 00000000..0773c475 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2023_full: LibDefinition; +//# sourceMappingURL=es2023.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.full.d.ts.map new file mode 100644 index 00000000..bee49415 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2023.full.d.ts","sourceRoot":"","sources":["../../src/lib/es2023.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,WAAW,EAAE,aAUzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.full.js new file mode 100644 index 00000000..88dbbe24 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.full.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2023_full = void 0; +const dom_1 = require("./dom"); +const dom_asynciterable_1 = require("./dom.asynciterable"); +const dom_iterable_1 = require("./dom.iterable"); +const es2023_1 = require("./es2023"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2023_full = { + libs: [ + es2023_1.es2023, + dom_1.dom, + webworker_importscripts_1.webworker_importscripts, + scripthost_1.scripthost, + dom_iterable_1.dom_iterable, + dom_asynciterable_1.dom_asynciterable, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.intl.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.intl.d.ts new file mode 100644 index 00000000..5043caab --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.intl.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2023_intl: LibDefinition; +//# sourceMappingURL=es2023.intl.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.intl.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.intl.d.ts.map new file mode 100644 index 00000000..cde05d8f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.intl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2023.intl.d.ts","sourceRoot":"","sources":["../../src/lib/es2023.intl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.intl.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.intl.js new file mode 100644 index 00000000..d67b5658 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2023_intl = void 0; +const base_config_1 = require("./base-config"); +exports.es2023_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.js new file mode 100644 index 00000000..7369e245 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2023.js @@ -0,0 +1,15 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2023 = void 0; +const es2022_1 = require("./es2022"); +const es2023_array_1 = require("./es2023.array"); +const es2023_collection_1 = require("./es2023.collection"); +const es2023_intl_1 = require("./es2023.intl"); +exports.es2023 = { + libs: [es2022_1.es2022, es2023_array_1.es2023_array, es2023_collection_1.es2023_collection, es2023_intl_1.es2023_intl], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.arraybuffer.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.arraybuffer.d.ts new file mode 100644 index 00000000..360470a7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.arraybuffer.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2024_arraybuffer: LibDefinition; +//# sourceMappingURL=es2024.arraybuffer.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.arraybuffer.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.arraybuffer.d.ts.map new file mode 100644 index 00000000..2cbdb61f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.arraybuffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2024.arraybuffer.d.ts","sourceRoot":"","sources":["../../src/lib/es2024.arraybuffer.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,kBAAkB,EAAE,aAMhC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.arraybuffer.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.arraybuffer.js new file mode 100644 index 00000000..c11b4860 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.arraybuffer.js @@ -0,0 +1,15 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2024_arraybuffer = void 0; +const base_config_1 = require("./base-config"); +exports.es2024_arraybuffer = { + libs: [], + variables: [ + ['ArrayBuffer', base_config_1.TYPE], + ['ArrayBufferConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.collection.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.collection.d.ts new file mode 100644 index 00000000..06327e4c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.collection.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2024_collection: LibDefinition; +//# sourceMappingURL=es2024.collection.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.collection.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.collection.d.ts.map new file mode 100644 index 00000000..ba7fcbcd --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.collection.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2024.collection.d.ts","sourceRoot":"","sources":["../../src/lib/es2024.collection.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,iBAAiB,EAAE,aAG/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.collection.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.collection.js new file mode 100644 index 00000000..e0c7b688 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.collection.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2024_collection = void 0; +const base_config_1 = require("./base-config"); +exports.es2024_collection = { + libs: [], + variables: [['MapConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.d.ts new file mode 100644 index 00000000..31a789d8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2024: LibDefinition; +//# sourceMappingURL=es2024.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.d.ts.map new file mode 100644 index 00000000..5b26f105 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2024.d.ts","sourceRoot":"","sources":["../../src/lib/es2024.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAWjD,eAAO,MAAM,MAAM,EAAE,aAYpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.full.d.ts new file mode 100644 index 00000000..9fc04e0a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2024_full: LibDefinition; +//# sourceMappingURL=es2024.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.full.d.ts.map new file mode 100644 index 00000000..bd384ba9 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2024.full.d.ts","sourceRoot":"","sources":["../../src/lib/es2024.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,WAAW,EAAE,aAUzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.full.js new file mode 100644 index 00000000..5f31eef6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.full.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2024_full = void 0; +const dom_1 = require("./dom"); +const dom_asynciterable_1 = require("./dom.asynciterable"); +const dom_iterable_1 = require("./dom.iterable"); +const es2024_1 = require("./es2024"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.es2024_full = { + libs: [ + es2024_1.es2024, + dom_1.dom, + webworker_importscripts_1.webworker_importscripts, + scripthost_1.scripthost, + dom_iterable_1.dom_iterable, + dom_asynciterable_1.dom_asynciterable, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.js new file mode 100644 index 00000000..fddb8773 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.js @@ -0,0 +1,28 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2024 = void 0; +const es2023_1 = require("./es2023"); +const es2024_arraybuffer_1 = require("./es2024.arraybuffer"); +const es2024_collection_1 = require("./es2024.collection"); +const es2024_object_1 = require("./es2024.object"); +const es2024_promise_1 = require("./es2024.promise"); +const es2024_regexp_1 = require("./es2024.regexp"); +const es2024_sharedmemory_1 = require("./es2024.sharedmemory"); +const es2024_string_1 = require("./es2024.string"); +exports.es2024 = { + libs: [ + es2023_1.es2023, + es2024_arraybuffer_1.es2024_arraybuffer, + es2024_collection_1.es2024_collection, + es2024_object_1.es2024_object, + es2024_promise_1.es2024_promise, + es2024_regexp_1.es2024_regexp, + es2024_sharedmemory_1.es2024_sharedmemory, + es2024_string_1.es2024_string, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.object.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.object.d.ts new file mode 100644 index 00000000..e969c646 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.object.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2024_object: LibDefinition; +//# sourceMappingURL=es2024.object.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.object.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.object.d.ts.map new file mode 100644 index 00000000..6278015b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2024.object.d.ts","sourceRoot":"","sources":["../../src/lib/es2024.object.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.object.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.object.js new file mode 100644 index 00000000..e733f70f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.object.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2024_object = void 0; +const base_config_1 = require("./base-config"); +exports.es2024_object = { + libs: [], + variables: [['ObjectConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.promise.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.promise.d.ts new file mode 100644 index 00000000..59514f1f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.promise.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2024_promise: LibDefinition; +//# sourceMappingURL=es2024.promise.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.promise.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.promise.d.ts.map new file mode 100644 index 00000000..d8b453b1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2024.promise.d.ts","sourceRoot":"","sources":["../../src/lib/es2024.promise.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,cAAc,EAAE,aAM5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.promise.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.promise.js new file mode 100644 index 00000000..4501e655 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.promise.js @@ -0,0 +1,15 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2024_promise = void 0; +const base_config_1 = require("./base-config"); +exports.es2024_promise = { + libs: [], + variables: [ + ['PromiseWithResolvers', base_config_1.TYPE], + ['PromiseConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.regexp.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.regexp.d.ts new file mode 100644 index 00000000..03238e39 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.regexp.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2024_regexp: LibDefinition; +//# sourceMappingURL=es2024.regexp.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.regexp.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.regexp.d.ts.map new file mode 100644 index 00000000..276591d6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.regexp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2024.regexp.d.ts","sourceRoot":"","sources":["../../src/lib/es2024.regexp.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.regexp.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.regexp.js new file mode 100644 index 00000000..a2da5ada --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.regexp.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2024_regexp = void 0; +const base_config_1 = require("./base-config"); +exports.es2024_regexp = { + libs: [], + variables: [['RegExp', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.sharedmemory.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.sharedmemory.d.ts new file mode 100644 index 00000000..c2940434 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.sharedmemory.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2024_sharedmemory: LibDefinition; +//# sourceMappingURL=es2024.sharedmemory.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.sharedmemory.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.sharedmemory.d.ts.map new file mode 100644 index 00000000..7b9b7339 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.sharedmemory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2024.sharedmemory.d.ts","sourceRoot":"","sources":["../../src/lib/es2024.sharedmemory.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,mBAAmB,EAAE,aAOjC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.sharedmemory.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.sharedmemory.js new file mode 100644 index 00000000..2ed579bb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.sharedmemory.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2024_sharedmemory = void 0; +const base_config_1 = require("./base-config"); +const es2020_bigint_1 = require("./es2020.bigint"); +exports.es2024_sharedmemory = { + libs: [es2020_bigint_1.es2020_bigint], + variables: [ + ['Atomics', base_config_1.TYPE], + ['SharedArrayBuffer', base_config_1.TYPE], + ['SharedArrayBufferConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.string.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.string.d.ts new file mode 100644 index 00000000..39fdc579 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.string.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es2024_string: LibDefinition; +//# sourceMappingURL=es2024.string.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.string.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.string.d.ts.map new file mode 100644 index 00000000..3ccec645 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es2024.string.d.ts","sourceRoot":"","sources":["../../src/lib/es2024.string.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.string.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.string.js new file mode 100644 index 00000000..fcf00291 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es2024.string.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es2024_string = void 0; +const base_config_1 = require("./base-config"); +exports.es2024_string = { + libs: [], + variables: [['String', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es5.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es5.d.ts new file mode 100644 index 00000000..e8e80654 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es5.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es5: LibDefinition; +//# sourceMappingURL=es5.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es5.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es5.d.ts.map new file mode 100644 index 00000000..3d4af9ec --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es5.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es5.d.ts","sourceRoot":"","sources":["../../src/lib/es5.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,eAAO,MAAM,GAAG,EAAE,aA2GjB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es5.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es5.js new file mode 100644 index 00000000..69ffa453 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es5.js @@ -0,0 +1,118 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es5 = void 0; +const base_config_1 = require("./base-config"); +const decorators_1 = require("./decorators"); +const decorators_legacy_1 = require("./decorators.legacy"); +exports.es5 = { + libs: [decorators_1.decorators, decorators_legacy_1.decorators_legacy], + variables: [ + ['Symbol', base_config_1.TYPE], + ['PropertyKey', base_config_1.TYPE], + ['PropertyDescriptor', base_config_1.TYPE], + ['PropertyDescriptorMap', base_config_1.TYPE], + ['Object', base_config_1.TYPE_VALUE], + ['ObjectConstructor', base_config_1.TYPE], + ['Function', base_config_1.TYPE_VALUE], + ['FunctionConstructor', base_config_1.TYPE], + ['ThisParameterType', base_config_1.TYPE], + ['OmitThisParameter', base_config_1.TYPE], + ['CallableFunction', base_config_1.TYPE], + ['NewableFunction', base_config_1.TYPE], + ['IArguments', base_config_1.TYPE], + ['String', base_config_1.TYPE_VALUE], + ['StringConstructor', base_config_1.TYPE], + ['Boolean', base_config_1.TYPE_VALUE], + ['BooleanConstructor', base_config_1.TYPE], + ['Number', base_config_1.TYPE_VALUE], + ['NumberConstructor', base_config_1.TYPE], + ['TemplateStringsArray', base_config_1.TYPE], + ['ImportMeta', base_config_1.TYPE], + ['ImportCallOptions', base_config_1.TYPE], + ['ImportAssertions', base_config_1.TYPE], + ['ImportAttributes', base_config_1.TYPE], + ['Math', base_config_1.TYPE_VALUE], + ['Date', base_config_1.TYPE_VALUE], + ['DateConstructor', base_config_1.TYPE], + ['RegExpMatchArray', base_config_1.TYPE], + ['RegExpExecArray', base_config_1.TYPE], + ['RegExp', base_config_1.TYPE_VALUE], + ['RegExpConstructor', base_config_1.TYPE], + ['Error', base_config_1.TYPE_VALUE], + ['ErrorConstructor', base_config_1.TYPE], + ['EvalError', base_config_1.TYPE_VALUE], + ['EvalErrorConstructor', base_config_1.TYPE], + ['RangeError', base_config_1.TYPE_VALUE], + ['RangeErrorConstructor', base_config_1.TYPE], + ['ReferenceError', base_config_1.TYPE_VALUE], + ['ReferenceErrorConstructor', base_config_1.TYPE], + ['SyntaxError', base_config_1.TYPE_VALUE], + ['SyntaxErrorConstructor', base_config_1.TYPE], + ['TypeError', base_config_1.TYPE_VALUE], + ['TypeErrorConstructor', base_config_1.TYPE], + ['URIError', base_config_1.TYPE_VALUE], + ['URIErrorConstructor', base_config_1.TYPE], + ['JSON', base_config_1.TYPE_VALUE], + ['ReadonlyArray', base_config_1.TYPE], + ['ConcatArray', base_config_1.TYPE], + ['Array', base_config_1.TYPE_VALUE], + ['ArrayConstructor', base_config_1.TYPE], + ['TypedPropertyDescriptor', base_config_1.TYPE], + ['PromiseConstructorLike', base_config_1.TYPE], + ['PromiseLike', base_config_1.TYPE], + ['Promise', base_config_1.TYPE], + ['Awaited', base_config_1.TYPE], + ['ArrayLike', base_config_1.TYPE], + ['Partial', base_config_1.TYPE], + ['Required', base_config_1.TYPE], + ['Readonly', base_config_1.TYPE], + ['Pick', base_config_1.TYPE], + ['Record', base_config_1.TYPE], + ['Exclude', base_config_1.TYPE], + ['Extract', base_config_1.TYPE], + ['Omit', base_config_1.TYPE], + ['NonNullable', base_config_1.TYPE], + ['Parameters', base_config_1.TYPE], + ['ConstructorParameters', base_config_1.TYPE], + ['ReturnType', base_config_1.TYPE], + ['InstanceType', base_config_1.TYPE], + ['Uppercase', base_config_1.TYPE], + ['Lowercase', base_config_1.TYPE], + ['Capitalize', base_config_1.TYPE], + ['Uncapitalize', base_config_1.TYPE], + ['NoInfer', base_config_1.TYPE], + ['ThisType', base_config_1.TYPE], + ['WeakKeyTypes', base_config_1.TYPE], + ['WeakKey', base_config_1.TYPE], + ['ArrayBuffer', base_config_1.TYPE_VALUE], + ['ArrayBufferTypes', base_config_1.TYPE], + ['ArrayBufferLike', base_config_1.TYPE], + ['ArrayBufferConstructor', base_config_1.TYPE], + ['ArrayBufferView', base_config_1.TYPE], + ['DataView', base_config_1.TYPE_VALUE], + ['DataViewConstructor', base_config_1.TYPE], + ['Int8Array', base_config_1.TYPE_VALUE], + ['Int8ArrayConstructor', base_config_1.TYPE], + ['Uint8Array', base_config_1.TYPE_VALUE], + ['Uint8ArrayConstructor', base_config_1.TYPE], + ['Uint8ClampedArray', base_config_1.TYPE_VALUE], + ['Uint8ClampedArrayConstructor', base_config_1.TYPE], + ['Int16Array', base_config_1.TYPE_VALUE], + ['Int16ArrayConstructor', base_config_1.TYPE], + ['Uint16Array', base_config_1.TYPE_VALUE], + ['Uint16ArrayConstructor', base_config_1.TYPE], + ['Int32Array', base_config_1.TYPE_VALUE], + ['Int32ArrayConstructor', base_config_1.TYPE], + ['Uint32Array', base_config_1.TYPE_VALUE], + ['Uint32ArrayConstructor', base_config_1.TYPE], + ['Float32Array', base_config_1.TYPE_VALUE], + ['Float32ArrayConstructor', base_config_1.TYPE], + ['Float64Array', base_config_1.TYPE_VALUE], + ['Float64ArrayConstructor', base_config_1.TYPE], + ['Intl', base_config_1.TYPE_VALUE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es6.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es6.d.ts new file mode 100644 index 00000000..2b6e55b3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es6.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es6: LibDefinition; +//# sourceMappingURL=es6.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es6.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es6.d.ts.map new file mode 100644 index 00000000..c79acded --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es6.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es6.d.ts","sourceRoot":"","sources":["../../src/lib/es6.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAajD,eAAO,MAAM,GAAG,EAAE,aAcjB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es6.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es6.js new file mode 100644 index 00000000..1d5f05ec --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es6.js @@ -0,0 +1,32 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es6 = void 0; +const es5_1 = require("./es5"); +const es2015_collection_1 = require("./es2015.collection"); +const es2015_core_1 = require("./es2015.core"); +const es2015_generator_1 = require("./es2015.generator"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_promise_1 = require("./es2015.promise"); +const es2015_proxy_1 = require("./es2015.proxy"); +const es2015_reflect_1 = require("./es2015.reflect"); +const es2015_symbol_1 = require("./es2015.symbol"); +const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown"); +exports.es6 = { + libs: [ + es5_1.es5, + es2015_core_1.es2015_core, + es2015_collection_1.es2015_collection, + es2015_iterable_1.es2015_iterable, + es2015_generator_1.es2015_generator, + es2015_promise_1.es2015_promise, + es2015_proxy_1.es2015_proxy, + es2015_reflect_1.es2015_reflect, + es2015_symbol_1.es2015_symbol, + es2015_symbol_wellknown_1.es2015_symbol_wellknown, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es7.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/es7.d.ts new file mode 100644 index 00000000..6bdf62d4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es7.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const es7: LibDefinition; +//# sourceMappingURL=es7.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es7.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/es7.d.ts.map new file mode 100644 index 00000000..9709d248 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es7.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"es7.d.ts","sourceRoot":"","sources":["../../src/lib/es7.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,eAAO,MAAM,GAAG,EAAE,aAGjB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/es7.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/es7.js new file mode 100644 index 00000000..7b23ee3a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/es7.js @@ -0,0 +1,14 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.es7 = void 0; +const es2015_1 = require("./es2015"); +const es2016_array_include_1 = require("./es2016.array.include"); +const es2016_intl_1 = require("./es2016.intl"); +exports.es7 = { + libs: [es2015_1.es2015, es2016_array_include_1.es2016_array_include, es2016_intl_1.es2016_intl], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.array.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.array.d.ts new file mode 100644 index 00000000..3ad552de --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.array.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_array: LibDefinition; +//# sourceMappingURL=esnext.array.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.array.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.array.d.ts.map new file mode 100644 index 00000000..1f6b0308 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.array.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.array.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,YAAY,EAAE,aAG1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.array.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.array.js new file mode 100644 index 00000000..d94bd46a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.array.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_array = void 0; +const base_config_1 = require("./base-config"); +exports.esnext_array = { + libs: [], + variables: [['ArrayConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.asynciterable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.asynciterable.d.ts new file mode 100644 index 00000000..4487e733 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.asynciterable.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_asynciterable: LibDefinition; +//# sourceMappingURL=esnext.asynciterable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.asynciterable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.asynciterable.d.ts.map new file mode 100644 index 00000000..2b1525a4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.asynciterable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.asynciterable.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.asynciterable.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,eAAO,MAAM,oBAAoB,EAAE,aASlC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.asynciterable.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.asynciterable.js new file mode 100644 index 00000000..08501d91 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.asynciterable.js @@ -0,0 +1,20 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_asynciterable = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.esnext_asynciterable = { + libs: [es2015_symbol_1.es2015_symbol, es2015_iterable_1.es2015_iterable], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['AsyncIterator', base_config_1.TYPE], + ['AsyncIterable', base_config_1.TYPE], + ['AsyncIterableIterator', base_config_1.TYPE], + ['AsyncIteratorObject', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.bigint.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.bigint.d.ts new file mode 100644 index 00000000..1cd0091c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.bigint.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_bigint: LibDefinition; +//# sourceMappingURL=esnext.bigint.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.bigint.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.bigint.d.ts.map new file mode 100644 index 00000000..9f7bcf42 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.bigint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.bigint.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.bigint.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,aAAa,EAAE,aAa3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.bigint.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.bigint.js new file mode 100644 index 00000000..986f9af5 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.bigint.js @@ -0,0 +1,23 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_bigint = void 0; +const base_config_1 = require("./base-config"); +const es2020_intl_1 = require("./es2020.intl"); +exports.esnext_bigint = { + libs: [es2020_intl_1.es2020_intl], + variables: [ + ['BigIntToLocaleStringOptions', base_config_1.TYPE], + ['BigInt', base_config_1.TYPE_VALUE], + ['BigIntConstructor', base_config_1.TYPE], + ['BigInt64Array', base_config_1.TYPE_VALUE], + ['BigInt64ArrayConstructor', base_config_1.TYPE], + ['BigUint64Array', base_config_1.TYPE_VALUE], + ['BigUint64ArrayConstructor', base_config_1.TYPE], + ['DataView', base_config_1.TYPE], + ['Intl', base_config_1.TYPE_VALUE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.collection.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.collection.d.ts new file mode 100644 index 00000000..2b058029 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.collection.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_collection: LibDefinition; +//# sourceMappingURL=esnext.collection.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.collection.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.collection.d.ts.map new file mode 100644 index 00000000..8a1fc1d0 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.collection.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.collection.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.collection.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,iBAAiB,EAAE,aAO/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.collection.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.collection.js new file mode 100644 index 00000000..aff3926f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.collection.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_collection = void 0; +const base_config_1 = require("./base-config"); +const es2024_collection_1 = require("./es2024.collection"); +exports.esnext_collection = { + libs: [es2024_collection_1.es2024_collection], + variables: [ + ['ReadonlySetLike', base_config_1.TYPE], + ['Set', base_config_1.TYPE], + ['ReadonlySet', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.d.ts new file mode 100644 index 00000000..e282b093 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext: LibDefinition; +//# sourceMappingURL=esnext.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.d.ts.map new file mode 100644 index 00000000..ae5bda4e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAYjD,eAAO,MAAM,MAAM,EAAE,aAapB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.decorators.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.decorators.d.ts new file mode 100644 index 00000000..8d1f7ef2 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.decorators.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_decorators: LibDefinition; +//# sourceMappingURL=esnext.decorators.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.decorators.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.decorators.d.ts.map new file mode 100644 index 00000000..f25bd5fa --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.decorators.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.decorators.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.decorators.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,eAAO,MAAM,iBAAiB,EAAE,aAM/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.decorators.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.decorators.js new file mode 100644 index 00000000..4ab33380 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.decorators.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_decorators = void 0; +const base_config_1 = require("./base-config"); +const decorators_1 = require("./decorators"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.esnext_decorators = { + libs: [es2015_symbol_1.es2015_symbol, decorators_1.decorators], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['Function', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.disposable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.disposable.d.ts new file mode 100644 index 00000000..a38fb0e4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.disposable.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_disposable: LibDefinition; +//# sourceMappingURL=esnext.disposable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.disposable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.disposable.d.ts.map new file mode 100644 index 00000000..934eb73a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.disposable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.disposable.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.disposable.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAOjD,eAAO,MAAM,iBAAiB,EAAE,aAe/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.disposable.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.disposable.js new file mode 100644 index 00000000..476c4970 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.disposable.js @@ -0,0 +1,27 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_disposable = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_symbol_1 = require("./es2015.symbol"); +const es2018_asynciterable_1 = require("./es2018.asynciterable"); +exports.esnext_disposable = { + libs: [es2015_symbol_1.es2015_symbol, es2015_iterable_1.es2015_iterable, es2018_asynciterable_1.es2018_asynciterable], + variables: [ + ['SymbolConstructor', base_config_1.TYPE], + ['Disposable', base_config_1.TYPE], + ['AsyncDisposable', base_config_1.TYPE], + ['SuppressedError', base_config_1.TYPE_VALUE], + ['SuppressedErrorConstructor', base_config_1.TYPE], + ['DisposableStack', base_config_1.TYPE_VALUE], + ['DisposableStackConstructor', base_config_1.TYPE], + ['AsyncDisposableStack', base_config_1.TYPE_VALUE], + ['AsyncDisposableStackConstructor', base_config_1.TYPE], + ['IteratorObject', base_config_1.TYPE], + ['AsyncIteratorObject', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.float16.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.float16.d.ts new file mode 100644 index 00000000..fa318057 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.float16.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_float16: LibDefinition; +//# sourceMappingURL=esnext.float16.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.float16.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.float16.d.ts.map new file mode 100644 index 00000000..ca478537 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.float16.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.float16.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.float16.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,eAAO,MAAM,cAAc,EAAE,aAQ5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.float16.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.float16.js new file mode 100644 index 00000000..ca945414 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.float16.js @@ -0,0 +1,19 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_float16 = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_symbol_1 = require("./es2015.symbol"); +exports.esnext_float16 = { + libs: [es2015_symbol_1.es2015_symbol, es2015_iterable_1.es2015_iterable], + variables: [ + ['Float16Array', base_config_1.TYPE_VALUE], + ['Float16ArrayConstructor', base_config_1.TYPE], + ['Math', base_config_1.TYPE], + ['DataView', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.full.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.full.d.ts new file mode 100644 index 00000000..5fda61e1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.full.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_full: LibDefinition; +//# sourceMappingURL=esnext.full.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.full.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.full.d.ts.map new file mode 100644 index 00000000..7f82e61d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.full.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.full.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.full.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD,eAAO,MAAM,WAAW,EAAE,aAUzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.full.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.full.js new file mode 100644 index 00000000..86500031 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.full.js @@ -0,0 +1,24 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_full = void 0; +const dom_1 = require("./dom"); +const dom_asynciterable_1 = require("./dom.asynciterable"); +const dom_iterable_1 = require("./dom.iterable"); +const esnext_1 = require("./esnext"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.esnext_full = { + libs: [ + esnext_1.esnext, + dom_1.dom, + webworker_importscripts_1.webworker_importscripts, + scripthost_1.scripthost, + dom_iterable_1.dom_iterable, + dom_asynciterable_1.dom_asynciterable, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.intl.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.intl.d.ts new file mode 100644 index 00000000..cb3b6544 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.intl.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_intl: LibDefinition; +//# sourceMappingURL=esnext.intl.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.intl.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.intl.d.ts.map new file mode 100644 index 00000000..26ec82c3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.intl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.intl.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.intl.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,WAAW,EAAE,aAGzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.intl.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.intl.js new file mode 100644 index 00000000..cda8263d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.intl.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_intl = void 0; +const base_config_1 = require("./base-config"); +exports.esnext_intl = { + libs: [], + variables: [['Intl', base_config_1.TYPE_VALUE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.iterator.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.iterator.d.ts new file mode 100644 index 00000000..2f866da6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.iterator.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_iterator: LibDefinition; +//# sourceMappingURL=esnext.iterator.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.iterator.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.iterator.d.ts.map new file mode 100644 index 00000000..f67e4ed1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.iterator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.iterator.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.iterator.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,eAAe,EAAE,aAM7B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.iterator.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.iterator.js new file mode 100644 index 00000000..b4d4f553 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.iterator.js @@ -0,0 +1,16 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_iterator = void 0; +const base_config_1 = require("./base-config"); +const es2015_iterable_1 = require("./es2015.iterable"); +exports.esnext_iterator = { + libs: [es2015_iterable_1.es2015_iterable], + variables: [ + ['Iterator', base_config_1.TYPE_VALUE], + ['IteratorObjectConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.js new file mode 100644 index 00000000..474f0897 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.js @@ -0,0 +1,30 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext = void 0; +const es2024_1 = require("./es2024"); +const esnext_array_1 = require("./esnext.array"); +const esnext_collection_1 = require("./esnext.collection"); +const esnext_decorators_1 = require("./esnext.decorators"); +const esnext_disposable_1 = require("./esnext.disposable"); +const esnext_float16_1 = require("./esnext.float16"); +const esnext_intl_1 = require("./esnext.intl"); +const esnext_iterator_1 = require("./esnext.iterator"); +const esnext_promise_1 = require("./esnext.promise"); +exports.esnext = { + libs: [ + es2024_1.es2024, + esnext_intl_1.esnext_intl, + esnext_decorators_1.esnext_decorators, + esnext_disposable_1.esnext_disposable, + esnext_collection_1.esnext_collection, + esnext_array_1.esnext_array, + esnext_iterator_1.esnext_iterator, + esnext_promise_1.esnext_promise, + esnext_float16_1.esnext_float16, + ], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.object.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.object.d.ts new file mode 100644 index 00000000..7b9c1694 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.object.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_object: LibDefinition; +//# sourceMappingURL=esnext.object.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.object.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.object.d.ts.map new file mode 100644 index 00000000..159e8c54 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.object.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.object.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.object.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.object.js new file mode 100644 index 00000000..4e222d90 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.object.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_object = void 0; +const base_config_1 = require("./base-config"); +exports.esnext_object = { + libs: [], + variables: [['ObjectConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.promise.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.promise.d.ts new file mode 100644 index 00000000..cd0a52c7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.promise.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_promise: LibDefinition; +//# sourceMappingURL=esnext.promise.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.promise.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.promise.d.ts.map new file mode 100644 index 00000000..a10b4369 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.promise.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.promise.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,cAAc,EAAE,aAG5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.promise.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.promise.js new file mode 100644 index 00000000..1f325c97 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.promise.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_promise = void 0; +const base_config_1 = require("./base-config"); +exports.esnext_promise = { + libs: [], + variables: [['PromiseConstructor', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.regexp.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.regexp.d.ts new file mode 100644 index 00000000..e251d77d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.regexp.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_regexp: LibDefinition; +//# sourceMappingURL=esnext.regexp.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.regexp.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.regexp.d.ts.map new file mode 100644 index 00000000..a76a4019 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.regexp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.regexp.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.regexp.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.regexp.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.regexp.js new file mode 100644 index 00000000..53d0b171 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.regexp.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_regexp = void 0; +const base_config_1 = require("./base-config"); +exports.esnext_regexp = { + libs: [], + variables: [['RegExp', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.string.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.string.d.ts new file mode 100644 index 00000000..7f3daca7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.string.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_string: LibDefinition; +//# sourceMappingURL=esnext.string.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.string.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.string.d.ts.map new file mode 100644 index 00000000..79d57dab --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.string.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.string.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.string.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.string.js new file mode 100644 index 00000000..1999ac13 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.string.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_string = void 0; +const base_config_1 = require("./base-config"); +exports.esnext_string = { + libs: [], + variables: [['String', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.symbol.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.symbol.d.ts new file mode 100644 index 00000000..96b623ef --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.symbol.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_symbol: LibDefinition; +//# sourceMappingURL=esnext.symbol.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.symbol.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.symbol.d.ts.map new file mode 100644 index 00000000..83fec728 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.symbol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.symbol.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.symbol.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.symbol.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.symbol.js new file mode 100644 index 00000000..a7935f56 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.symbol.js @@ -0,0 +1,12 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_symbol = void 0; +const base_config_1 = require("./base-config"); +exports.esnext_symbol = { + libs: [], + variables: [['Symbol', base_config_1.TYPE]], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.weakref.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.weakref.d.ts new file mode 100644 index 00000000..cde8fb5d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.weakref.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const esnext_weakref: LibDefinition; +//# sourceMappingURL=esnext.weakref.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.weakref.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.weakref.d.ts.map new file mode 100644 index 00000000..865c3b87 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.weakref.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"esnext.weakref.d.ts","sourceRoot":"","sources":["../../src/lib/esnext.weakref.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjD,eAAO,MAAM,cAAc,EAAE,aAQ5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.weakref.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.weakref.js new file mode 100644 index 00000000..f2f4a9eb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/esnext.weakref.js @@ -0,0 +1,18 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.esnext_weakref = void 0; +const base_config_1 = require("./base-config"); +const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown"); +exports.esnext_weakref = { + libs: [es2015_symbol_wellknown_1.es2015_symbol_wellknown], + variables: [ + ['WeakRef', base_config_1.TYPE_VALUE], + ['WeakRefConstructor', base_config_1.TYPE], + ['FinalizationRegistry', base_config_1.TYPE_VALUE], + ['FinalizationRegistryConstructor', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/index.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/index.d.ts new file mode 100644 index 00000000..0a992d89 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/index.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const lib: ReadonlyMap; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/index.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/index.d.ts.map new file mode 100644 index 00000000..487056c2 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AA6GjD,eAAO,MAAM,GAAG,EAAE,WAAW,CAAC,MAAM,EAAE,aAAa,CA8GjD,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/index.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/index.js new file mode 100644 index 00000000..bda08893 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/index.js @@ -0,0 +1,221 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.lib = void 0; +const decorators_1 = require("./decorators"); +const decorators_legacy_1 = require("./decorators.legacy"); +const dom_1 = require("./dom"); +const dom_asynciterable_1 = require("./dom.asynciterable"); +const dom_iterable_1 = require("./dom.iterable"); +const es5_1 = require("./es5"); +const es6_1 = require("./es6"); +const es7_1 = require("./es7"); +const es2015_1 = require("./es2015"); +const es2015_collection_1 = require("./es2015.collection"); +const es2015_core_1 = require("./es2015.core"); +const es2015_generator_1 = require("./es2015.generator"); +const es2015_iterable_1 = require("./es2015.iterable"); +const es2015_promise_1 = require("./es2015.promise"); +const es2015_proxy_1 = require("./es2015.proxy"); +const es2015_reflect_1 = require("./es2015.reflect"); +const es2015_symbol_1 = require("./es2015.symbol"); +const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown"); +const es2016_1 = require("./es2016"); +const es2016_array_include_1 = require("./es2016.array.include"); +const es2016_full_1 = require("./es2016.full"); +const es2016_intl_1 = require("./es2016.intl"); +const es2017_1 = require("./es2017"); +const es2017_arraybuffer_1 = require("./es2017.arraybuffer"); +const es2017_date_1 = require("./es2017.date"); +const es2017_full_1 = require("./es2017.full"); +const es2017_intl_1 = require("./es2017.intl"); +const es2017_object_1 = require("./es2017.object"); +const es2017_sharedmemory_1 = require("./es2017.sharedmemory"); +const es2017_string_1 = require("./es2017.string"); +const es2017_typedarrays_1 = require("./es2017.typedarrays"); +const es2018_1 = require("./es2018"); +const es2018_asyncgenerator_1 = require("./es2018.asyncgenerator"); +const es2018_asynciterable_1 = require("./es2018.asynciterable"); +const es2018_full_1 = require("./es2018.full"); +const es2018_intl_1 = require("./es2018.intl"); +const es2018_promise_1 = require("./es2018.promise"); +const es2018_regexp_1 = require("./es2018.regexp"); +const es2019_1 = require("./es2019"); +const es2019_array_1 = require("./es2019.array"); +const es2019_full_1 = require("./es2019.full"); +const es2019_intl_1 = require("./es2019.intl"); +const es2019_object_1 = require("./es2019.object"); +const es2019_string_1 = require("./es2019.string"); +const es2019_symbol_1 = require("./es2019.symbol"); +const es2020_1 = require("./es2020"); +const es2020_bigint_1 = require("./es2020.bigint"); +const es2020_date_1 = require("./es2020.date"); +const es2020_full_1 = require("./es2020.full"); +const es2020_intl_1 = require("./es2020.intl"); +const es2020_number_1 = require("./es2020.number"); +const es2020_promise_1 = require("./es2020.promise"); +const es2020_sharedmemory_1 = require("./es2020.sharedmemory"); +const es2020_string_1 = require("./es2020.string"); +const es2020_symbol_wellknown_1 = require("./es2020.symbol.wellknown"); +const es2021_1 = require("./es2021"); +const es2021_full_1 = require("./es2021.full"); +const es2021_intl_1 = require("./es2021.intl"); +const es2021_promise_1 = require("./es2021.promise"); +const es2021_string_1 = require("./es2021.string"); +const es2021_weakref_1 = require("./es2021.weakref"); +const es2022_1 = require("./es2022"); +const es2022_array_1 = require("./es2022.array"); +const es2022_error_1 = require("./es2022.error"); +const es2022_full_1 = require("./es2022.full"); +const es2022_intl_1 = require("./es2022.intl"); +const es2022_object_1 = require("./es2022.object"); +const es2022_regexp_1 = require("./es2022.regexp"); +const es2022_string_1 = require("./es2022.string"); +const es2023_1 = require("./es2023"); +const es2023_array_1 = require("./es2023.array"); +const es2023_collection_1 = require("./es2023.collection"); +const es2023_full_1 = require("./es2023.full"); +const es2023_intl_1 = require("./es2023.intl"); +const es2024_1 = require("./es2024"); +const es2024_arraybuffer_1 = require("./es2024.arraybuffer"); +const es2024_collection_1 = require("./es2024.collection"); +const es2024_full_1 = require("./es2024.full"); +const es2024_object_1 = require("./es2024.object"); +const es2024_promise_1 = require("./es2024.promise"); +const es2024_regexp_1 = require("./es2024.regexp"); +const es2024_sharedmemory_1 = require("./es2024.sharedmemory"); +const es2024_string_1 = require("./es2024.string"); +const esnext_1 = require("./esnext"); +const esnext_array_1 = require("./esnext.array"); +const esnext_asynciterable_1 = require("./esnext.asynciterable"); +const esnext_bigint_1 = require("./esnext.bigint"); +const esnext_collection_1 = require("./esnext.collection"); +const esnext_decorators_1 = require("./esnext.decorators"); +const esnext_disposable_1 = require("./esnext.disposable"); +const esnext_float16_1 = require("./esnext.float16"); +const esnext_full_1 = require("./esnext.full"); +const esnext_intl_1 = require("./esnext.intl"); +const esnext_iterator_1 = require("./esnext.iterator"); +const esnext_object_1 = require("./esnext.object"); +const esnext_promise_1 = require("./esnext.promise"); +const esnext_regexp_1 = require("./esnext.regexp"); +const esnext_string_1 = require("./esnext.string"); +const esnext_symbol_1 = require("./esnext.symbol"); +const esnext_weakref_1 = require("./esnext.weakref"); +const lib_1 = require("./lib"); +const scripthost_1 = require("./scripthost"); +const webworker_1 = require("./webworker"); +const webworker_asynciterable_1 = require("./webworker.asynciterable"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +const webworker_iterable_1 = require("./webworker.iterable"); +exports.lib = new Map([ + ['es5', es5_1.es5], + ['es6', es6_1.es6], + ['es2015', es2015_1.es2015], + ['es7', es7_1.es7], + ['es2016', es2016_1.es2016], + ['es2017', es2017_1.es2017], + ['es2018', es2018_1.es2018], + ['es2019', es2019_1.es2019], + ['es2020', es2020_1.es2020], + ['es2021', es2021_1.es2021], + ['es2022', es2022_1.es2022], + ['es2023', es2023_1.es2023], + ['es2024', es2024_1.es2024], + ['esnext', esnext_1.esnext], + ['dom', dom_1.dom], + ['dom.iterable', dom_iterable_1.dom_iterable], + ['dom.asynciterable', dom_asynciterable_1.dom_asynciterable], + ['webworker', webworker_1.webworker], + ['webworker.importscripts', webworker_importscripts_1.webworker_importscripts], + ['webworker.iterable', webworker_iterable_1.webworker_iterable], + ['webworker.asynciterable', webworker_asynciterable_1.webworker_asynciterable], + ['scripthost', scripthost_1.scripthost], + ['es2015.core', es2015_core_1.es2015_core], + ['es2015.collection', es2015_collection_1.es2015_collection], + ['es2015.generator', es2015_generator_1.es2015_generator], + ['es2015.iterable', es2015_iterable_1.es2015_iterable], + ['es2015.promise', es2015_promise_1.es2015_promise], + ['es2015.proxy', es2015_proxy_1.es2015_proxy], + ['es2015.reflect', es2015_reflect_1.es2015_reflect], + ['es2015.symbol', es2015_symbol_1.es2015_symbol], + ['es2015.symbol.wellknown', es2015_symbol_wellknown_1.es2015_symbol_wellknown], + ['es2016.array.include', es2016_array_include_1.es2016_array_include], + ['es2016.intl', es2016_intl_1.es2016_intl], + ['es2017.arraybuffer', es2017_arraybuffer_1.es2017_arraybuffer], + ['es2017.date', es2017_date_1.es2017_date], + ['es2017.object', es2017_object_1.es2017_object], + ['es2017.sharedmemory', es2017_sharedmemory_1.es2017_sharedmemory], + ['es2017.string', es2017_string_1.es2017_string], + ['es2017.intl', es2017_intl_1.es2017_intl], + ['es2017.typedarrays', es2017_typedarrays_1.es2017_typedarrays], + ['es2018.asyncgenerator', es2018_asyncgenerator_1.es2018_asyncgenerator], + ['es2018.asynciterable', es2018_asynciterable_1.es2018_asynciterable], + ['es2018.intl', es2018_intl_1.es2018_intl], + ['es2018.promise', es2018_promise_1.es2018_promise], + ['es2018.regexp', es2018_regexp_1.es2018_regexp], + ['es2019.array', es2019_array_1.es2019_array], + ['es2019.object', es2019_object_1.es2019_object], + ['es2019.string', es2019_string_1.es2019_string], + ['es2019.symbol', es2019_symbol_1.es2019_symbol], + ['es2019.intl', es2019_intl_1.es2019_intl], + ['es2020.bigint', es2020_bigint_1.es2020_bigint], + ['es2020.date', es2020_date_1.es2020_date], + ['es2020.promise', es2020_promise_1.es2020_promise], + ['es2020.sharedmemory', es2020_sharedmemory_1.es2020_sharedmemory], + ['es2020.string', es2020_string_1.es2020_string], + ['es2020.symbol.wellknown', es2020_symbol_wellknown_1.es2020_symbol_wellknown], + ['es2020.intl', es2020_intl_1.es2020_intl], + ['es2020.number', es2020_number_1.es2020_number], + ['es2021.promise', es2021_promise_1.es2021_promise], + ['es2021.string', es2021_string_1.es2021_string], + ['es2021.weakref', es2021_weakref_1.es2021_weakref], + ['es2021.intl', es2021_intl_1.es2021_intl], + ['es2022.array', es2022_array_1.es2022_array], + ['es2022.error', es2022_error_1.es2022_error], + ['es2022.intl', es2022_intl_1.es2022_intl], + ['es2022.object', es2022_object_1.es2022_object], + ['es2022.string', es2022_string_1.es2022_string], + ['es2022.regexp', es2022_regexp_1.es2022_regexp], + ['es2023.array', es2023_array_1.es2023_array], + ['es2023.collection', es2023_collection_1.es2023_collection], + ['es2023.intl', es2023_intl_1.es2023_intl], + ['es2024.arraybuffer', es2024_arraybuffer_1.es2024_arraybuffer], + ['es2024.collection', es2024_collection_1.es2024_collection], + ['es2024.object', es2024_object_1.es2024_object], + ['es2024.promise', es2024_promise_1.es2024_promise], + ['es2024.regexp', es2024_regexp_1.es2024_regexp], + ['es2024.sharedmemory', es2024_sharedmemory_1.es2024_sharedmemory], + ['es2024.string', es2024_string_1.es2024_string], + ['esnext.array', esnext_array_1.esnext_array], + ['esnext.collection', esnext_collection_1.esnext_collection], + ['esnext.symbol', esnext_symbol_1.esnext_symbol], + ['esnext.asynciterable', esnext_asynciterable_1.esnext_asynciterable], + ['esnext.intl', esnext_intl_1.esnext_intl], + ['esnext.disposable', esnext_disposable_1.esnext_disposable], + ['esnext.bigint', esnext_bigint_1.esnext_bigint], + ['esnext.string', esnext_string_1.esnext_string], + ['esnext.promise', esnext_promise_1.esnext_promise], + ['esnext.weakref', esnext_weakref_1.esnext_weakref], + ['esnext.decorators', esnext_decorators_1.esnext_decorators], + ['esnext.object', esnext_object_1.esnext_object], + ['esnext.regexp', esnext_regexp_1.esnext_regexp], + ['esnext.iterator', esnext_iterator_1.esnext_iterator], + ['esnext.float16', esnext_float16_1.esnext_float16], + ['decorators', decorators_1.decorators], + ['decorators.legacy', decorators_legacy_1.decorators_legacy], + ['es2016.full', es2016_full_1.es2016_full], + ['es2017.full', es2017_full_1.es2017_full], + ['es2018.full', es2018_full_1.es2018_full], + ['es2019.full', es2019_full_1.es2019_full], + ['es2020.full', es2020_full_1.es2020_full], + ['es2021.full', es2021_full_1.es2021_full], + ['es2022.full', es2022_full_1.es2022_full], + ['es2023.full', es2023_full_1.es2023_full], + ['es2024.full', es2024_full_1.es2024_full], + ['esnext.full', esnext_full_1.esnext_full], + ['lib', lib_1.lib], +]); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/lib.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/lib.d.ts new file mode 100644 index 00000000..51f0739a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/lib.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const lib: LibDefinition; +//# sourceMappingURL=lib.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/lib.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/lib.d.ts.map new file mode 100644 index 00000000..1c9f86fe --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/lib.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../../src/lib/lib.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAOjD,eAAO,MAAM,GAAG,EAAE,aAGjB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/lib.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/lib.js new file mode 100644 index 00000000..0866092d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/lib.js @@ -0,0 +1,15 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.lib = void 0; +const dom_1 = require("./dom"); +const es5_1 = require("./es5"); +const scripthost_1 = require("./scripthost"); +const webworker_importscripts_1 = require("./webworker.importscripts"); +exports.lib = { + libs: [es5_1.es5, dom_1.dom, webworker_importscripts_1.webworker_importscripts, scripthost_1.scripthost], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/scripthost.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/scripthost.d.ts new file mode 100644 index 00000000..e04f9a79 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/scripthost.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const scripthost: LibDefinition; +//# sourceMappingURL=scripthost.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/scripthost.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/scripthost.d.ts.map new file mode 100644 index 00000000..3c979b1a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/scripthost.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scripthost.d.ts","sourceRoot":"","sources":["../../src/lib/scripthost.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,UAAU,EAAE,aAiBxB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/scripthost.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/scripthost.js new file mode 100644 index 00000000..45607511 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/scripthost.js @@ -0,0 +1,26 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scripthost = void 0; +const base_config_1 = require("./base-config"); +exports.scripthost = { + libs: [], + variables: [ + ['ActiveXObject', base_config_1.TYPE_VALUE], + ['ITextWriter', base_config_1.TYPE], + ['TextStreamBase', base_config_1.TYPE], + ['TextStreamWriter', base_config_1.TYPE], + ['TextStreamReader', base_config_1.TYPE], + ['SafeArray', base_config_1.TYPE_VALUE], + ['Enumerator', base_config_1.TYPE_VALUE], + ['EnumeratorConstructor', base_config_1.TYPE], + ['VBArray', base_config_1.TYPE_VALUE], + ['VBArrayConstructor', base_config_1.TYPE], + ['VarDate', base_config_1.TYPE_VALUE], + ['DateConstructor', base_config_1.TYPE], + ['Date', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.asynciterable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.asynciterable.d.ts new file mode 100644 index 00000000..473d2560 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.asynciterable.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const webworker_asynciterable: LibDefinition; +//# sourceMappingURL=webworker.asynciterable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.asynciterable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.asynciterable.d.ts.map new file mode 100644 index 00000000..83f16631 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.asynciterable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webworker.asynciterable.d.ts","sourceRoot":"","sources":["../../src/lib/webworker.asynciterable.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,uBAAuB,EAAE,aAQrC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.asynciterable.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.asynciterable.js new file mode 100644 index 00000000..55c93711 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.asynciterable.js @@ -0,0 +1,17 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.webworker_asynciterable = void 0; +const base_config_1 = require("./base-config"); +exports.webworker_asynciterable = { + libs: [], + variables: [ + ['FileSystemDirectoryHandleAsyncIterator', base_config_1.TYPE], + ['FileSystemDirectoryHandle', base_config_1.TYPE], + ['ReadableStreamAsyncIterator', base_config_1.TYPE], + ['ReadableStream', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.d.ts new file mode 100644 index 00000000..000c7844 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const webworker: LibDefinition; +//# sourceMappingURL=webworker.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.d.ts.map new file mode 100644 index 00000000..9772b42f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webworker.d.ts","sourceRoot":"","sources":["../../src/lib/webworker.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,SAAS,EAAE,aA+mBvB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.importscripts.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.importscripts.d.ts new file mode 100644 index 00000000..18b6bb8e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.importscripts.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const webworker_importscripts: LibDefinition; +//# sourceMappingURL=webworker.importscripts.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.importscripts.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.importscripts.d.ts.map new file mode 100644 index 00000000..ee4dbe0a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.importscripts.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webworker.importscripts.d.ts","sourceRoot":"","sources":["../../src/lib/webworker.importscripts.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,eAAO,MAAM,uBAAuB,EAAE,aAGrC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.importscripts.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.importscripts.js new file mode 100644 index 00000000..b2d350c3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.importscripts.js @@ -0,0 +1,11 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.webworker_importscripts = void 0; +exports.webworker_importscripts = { + libs: [], + variables: [], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.iterable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.iterable.d.ts new file mode 100644 index 00000000..90db596a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.iterable.d.ts @@ -0,0 +1,3 @@ +import type { LibDefinition } from '../variable'; +export declare const webworker_iterable: LibDefinition; +//# sourceMappingURL=webworker.iterable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.iterable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.iterable.d.ts.map new file mode 100644 index 00000000..191307ad --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.iterable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webworker.iterable.d.ts","sourceRoot":"","sources":["../../src/lib/webworker.iterable.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAIjD,eAAO,MAAM,kBAAkB,EAAE,aAgChC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.iterable.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.iterable.js new file mode 100644 index 00000000..1ba4cc75 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.iterable.js @@ -0,0 +1,41 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.webworker_iterable = void 0; +const base_config_1 = require("./base-config"); +exports.webworker_iterable = { + libs: [], + variables: [ + ['CSSNumericArray', base_config_1.TYPE], + ['CSSTransformValue', base_config_1.TYPE], + ['CSSUnparsedValue', base_config_1.TYPE], + ['Cache', base_config_1.TYPE], + ['CanvasPath', base_config_1.TYPE], + ['CanvasPathDrawingStyles', base_config_1.TYPE], + ['DOMStringList', base_config_1.TYPE], + ['FileList', base_config_1.TYPE], + ['FontFaceSet', base_config_1.TYPE], + ['FormDataIterator', base_config_1.TYPE], + ['FormData', base_config_1.TYPE], + ['HeadersIterator', base_config_1.TYPE], + ['Headers', base_config_1.TYPE], + ['IDBDatabase', base_config_1.TYPE], + ['IDBObjectStore', base_config_1.TYPE], + ['ImageTrackList', base_config_1.TYPE], + ['MessageEvent', base_config_1.TYPE], + ['StylePropertyMapReadOnlyIterator', base_config_1.TYPE], + ['StylePropertyMapReadOnly', base_config_1.TYPE], + ['SubtleCrypto', base_config_1.TYPE], + ['URLSearchParamsIterator', base_config_1.TYPE], + ['URLSearchParams', base_config_1.TYPE], + ['WEBGL_draw_buffers', base_config_1.TYPE], + ['WEBGL_multi_draw', base_config_1.TYPE], + ['WebGL2RenderingContextBase', base_config_1.TYPE], + ['WebGL2RenderingContextOverloads', base_config_1.TYPE], + ['WebGLRenderingContextBase', base_config_1.TYPE], + ['WebGLRenderingContextOverloads', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.js b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.js new file mode 100644 index 00000000..babe6e7f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/lib/webworker.js @@ -0,0 +1,632 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); +exports.webworker = void 0; +const base_config_1 = require("./base-config"); +exports.webworker = { + libs: [], + variables: [ + ['AddEventListenerOptions', base_config_1.TYPE], + ['AesCbcParams', base_config_1.TYPE], + ['AesCtrParams', base_config_1.TYPE], + ['AesDerivedKeyParams', base_config_1.TYPE], + ['AesGcmParams', base_config_1.TYPE], + ['AesKeyAlgorithm', base_config_1.TYPE], + ['AesKeyGenParams', base_config_1.TYPE], + ['Algorithm', base_config_1.TYPE], + ['AudioConfiguration', base_config_1.TYPE], + ['AudioDataCopyToOptions', base_config_1.TYPE], + ['AudioDataInit', base_config_1.TYPE], + ['AudioDecoderConfig', base_config_1.TYPE], + ['AudioDecoderInit', base_config_1.TYPE], + ['AudioDecoderSupport', base_config_1.TYPE], + ['AudioEncoderConfig', base_config_1.TYPE], + ['AudioEncoderInit', base_config_1.TYPE], + ['AudioEncoderSupport', base_config_1.TYPE], + ['AvcEncoderConfig', base_config_1.TYPE], + ['BlobPropertyBag', base_config_1.TYPE], + ['CSSMatrixComponentOptions', base_config_1.TYPE], + ['CSSNumericType', base_config_1.TYPE], + ['CacheQueryOptions', base_config_1.TYPE], + ['ClientQueryOptions', base_config_1.TYPE], + ['CloseEventInit', base_config_1.TYPE], + ['CryptoKeyPair', base_config_1.TYPE], + ['CustomEventInit', base_config_1.TYPE], + ['DOMMatrix2DInit', base_config_1.TYPE], + ['DOMMatrixInit', base_config_1.TYPE], + ['DOMPointInit', base_config_1.TYPE], + ['DOMQuadInit', base_config_1.TYPE], + ['DOMRectInit', base_config_1.TYPE], + ['EcKeyGenParams', base_config_1.TYPE], + ['EcKeyImportParams', base_config_1.TYPE], + ['EcdhKeyDeriveParams', base_config_1.TYPE], + ['EcdsaParams', base_config_1.TYPE], + ['EncodedAudioChunkInit', base_config_1.TYPE], + ['EncodedAudioChunkMetadata', base_config_1.TYPE], + ['EncodedVideoChunkInit', base_config_1.TYPE], + ['EncodedVideoChunkMetadata', base_config_1.TYPE], + ['ErrorEventInit', base_config_1.TYPE], + ['EventInit', base_config_1.TYPE], + ['EventListenerOptions', base_config_1.TYPE], + ['EventSourceInit', base_config_1.TYPE], + ['ExtendableEventInit', base_config_1.TYPE], + ['ExtendableMessageEventInit', base_config_1.TYPE], + ['FetchEventInit', base_config_1.TYPE], + ['FilePropertyBag', base_config_1.TYPE], + ['FileSystemCreateWritableOptions', base_config_1.TYPE], + ['FileSystemGetDirectoryOptions', base_config_1.TYPE], + ['FileSystemGetFileOptions', base_config_1.TYPE], + ['FileSystemReadWriteOptions', base_config_1.TYPE], + ['FileSystemRemoveOptions', base_config_1.TYPE], + ['FontFaceDescriptors', base_config_1.TYPE], + ['FontFaceSetLoadEventInit', base_config_1.TYPE], + ['GetNotificationOptions', base_config_1.TYPE], + ['HkdfParams', base_config_1.TYPE], + ['HmacImportParams', base_config_1.TYPE], + ['HmacKeyGenParams', base_config_1.TYPE], + ['IDBDatabaseInfo', base_config_1.TYPE], + ['IDBIndexParameters', base_config_1.TYPE], + ['IDBObjectStoreParameters', base_config_1.TYPE], + ['IDBTransactionOptions', base_config_1.TYPE], + ['IDBVersionChangeEventInit', base_config_1.TYPE], + ['ImageBitmapOptions', base_config_1.TYPE], + ['ImageBitmapRenderingContextSettings', base_config_1.TYPE], + ['ImageDataSettings', base_config_1.TYPE], + ['ImageDecodeOptions', base_config_1.TYPE], + ['ImageDecodeResult', base_config_1.TYPE], + ['ImageDecoderInit', base_config_1.TYPE], + ['ImageEncodeOptions', base_config_1.TYPE], + ['JsonWebKey', base_config_1.TYPE], + ['KeyAlgorithm', base_config_1.TYPE], + ['LockInfo', base_config_1.TYPE], + ['LockManagerSnapshot', base_config_1.TYPE], + ['LockOptions', base_config_1.TYPE], + ['MediaCapabilitiesDecodingInfo', base_config_1.TYPE], + ['MediaCapabilitiesEncodingInfo', base_config_1.TYPE], + ['MediaCapabilitiesInfo', base_config_1.TYPE], + ['MediaConfiguration', base_config_1.TYPE], + ['MediaDecodingConfiguration', base_config_1.TYPE], + ['MediaEncodingConfiguration', base_config_1.TYPE], + ['MediaStreamTrackProcessorInit', base_config_1.TYPE], + ['MessageEventInit', base_config_1.TYPE], + ['MultiCacheQueryOptions', base_config_1.TYPE], + ['NavigationPreloadState', base_config_1.TYPE], + ['NotificationEventInit', base_config_1.TYPE], + ['NotificationOptions', base_config_1.TYPE], + ['OpusEncoderConfig', base_config_1.TYPE], + ['Pbkdf2Params', base_config_1.TYPE], + ['PerformanceMarkOptions', base_config_1.TYPE], + ['PerformanceMeasureOptions', base_config_1.TYPE], + ['PerformanceObserverInit', base_config_1.TYPE], + ['PermissionDescriptor', base_config_1.TYPE], + ['PlaneLayout', base_config_1.TYPE], + ['ProgressEventInit', base_config_1.TYPE], + ['PromiseRejectionEventInit', base_config_1.TYPE], + ['PushEventInit', base_config_1.TYPE], + ['PushSubscriptionJSON', base_config_1.TYPE], + ['PushSubscriptionOptionsInit', base_config_1.TYPE], + ['QueuingStrategy', base_config_1.TYPE], + ['QueuingStrategyInit', base_config_1.TYPE], + ['RTCEncodedAudioFrameMetadata', base_config_1.TYPE], + ['RTCEncodedVideoFrameMetadata', base_config_1.TYPE], + ['ReadableStreamGetReaderOptions', base_config_1.TYPE], + ['ReadableStreamIteratorOptions', base_config_1.TYPE], + ['ReadableStreamReadDoneResult', base_config_1.TYPE], + ['ReadableStreamReadValueResult', base_config_1.TYPE], + ['ReadableWritablePair', base_config_1.TYPE], + ['RegistrationOptions', base_config_1.TYPE], + ['ReportingObserverOptions', base_config_1.TYPE], + ['RequestInit', base_config_1.TYPE], + ['ResponseInit', base_config_1.TYPE], + ['RsaHashedImportParams', base_config_1.TYPE], + ['RsaHashedKeyGenParams', base_config_1.TYPE], + ['RsaKeyGenParams', base_config_1.TYPE], + ['RsaOaepParams', base_config_1.TYPE], + ['RsaOtherPrimesInfo', base_config_1.TYPE], + ['RsaPssParams', base_config_1.TYPE], + ['SecurityPolicyViolationEventInit', base_config_1.TYPE], + ['StorageEstimate', base_config_1.TYPE], + ['StreamPipeOptions', base_config_1.TYPE], + ['StructuredSerializeOptions', base_config_1.TYPE], + ['TextDecodeOptions', base_config_1.TYPE], + ['TextDecoderOptions', base_config_1.TYPE], + ['TextEncoderEncodeIntoResult', base_config_1.TYPE], + ['Transformer', base_config_1.TYPE], + ['UnderlyingByteSource', base_config_1.TYPE], + ['UnderlyingDefaultSource', base_config_1.TYPE], + ['UnderlyingSink', base_config_1.TYPE], + ['UnderlyingSource', base_config_1.TYPE], + ['VideoColorSpaceInit', base_config_1.TYPE], + ['VideoConfiguration', base_config_1.TYPE], + ['VideoDecoderConfig', base_config_1.TYPE], + ['VideoDecoderInit', base_config_1.TYPE], + ['VideoDecoderSupport', base_config_1.TYPE], + ['VideoEncoderConfig', base_config_1.TYPE], + ['VideoEncoderEncodeOptions', base_config_1.TYPE], + ['VideoEncoderEncodeOptionsForAvc', base_config_1.TYPE], + ['VideoEncoderInit', base_config_1.TYPE], + ['VideoEncoderSupport', base_config_1.TYPE], + ['VideoFrameBufferInit', base_config_1.TYPE], + ['VideoFrameCopyToOptions', base_config_1.TYPE], + ['VideoFrameInit', base_config_1.TYPE], + ['WebGLContextAttributes', base_config_1.TYPE], + ['WebGLContextEventInit', base_config_1.TYPE], + ['WebTransportCloseInfo', base_config_1.TYPE], + ['WebTransportErrorOptions', base_config_1.TYPE], + ['WebTransportHash', base_config_1.TYPE], + ['WebTransportOptions', base_config_1.TYPE], + ['WebTransportSendStreamOptions', base_config_1.TYPE], + ['WorkerOptions', base_config_1.TYPE], + ['WriteParams', base_config_1.TYPE], + ['ANGLE_instanced_arrays', base_config_1.TYPE], + ['AbortController', base_config_1.TYPE_VALUE], + ['AbortSignalEventMap', base_config_1.TYPE], + ['AbortSignal', base_config_1.TYPE_VALUE], + ['AbstractWorkerEventMap', base_config_1.TYPE], + ['AbstractWorker', base_config_1.TYPE], + ['AnimationFrameProvider', base_config_1.TYPE], + ['AudioData', base_config_1.TYPE_VALUE], + ['AudioDecoderEventMap', base_config_1.TYPE], + ['AudioDecoder', base_config_1.TYPE_VALUE], + ['AudioEncoderEventMap', base_config_1.TYPE], + ['AudioEncoder', base_config_1.TYPE_VALUE], + ['Blob', base_config_1.TYPE_VALUE], + ['Body', base_config_1.TYPE], + ['BroadcastChannelEventMap', base_config_1.TYPE], + ['BroadcastChannel', base_config_1.TYPE_VALUE], + ['ByteLengthQueuingStrategy', base_config_1.TYPE_VALUE], + ['CSSImageValue', base_config_1.TYPE_VALUE], + ['CSSKeywordValue', base_config_1.TYPE_VALUE], + ['CSSMathClamp', base_config_1.TYPE_VALUE], + ['CSSMathInvert', base_config_1.TYPE_VALUE], + ['CSSMathMax', base_config_1.TYPE_VALUE], + ['CSSMathMin', base_config_1.TYPE_VALUE], + ['CSSMathNegate', base_config_1.TYPE_VALUE], + ['CSSMathProduct', base_config_1.TYPE_VALUE], + ['CSSMathSum', base_config_1.TYPE_VALUE], + ['CSSMathValue', base_config_1.TYPE_VALUE], + ['CSSMatrixComponent', base_config_1.TYPE_VALUE], + ['CSSNumericArray', base_config_1.TYPE_VALUE], + ['CSSNumericValue', base_config_1.TYPE_VALUE], + ['CSSPerspective', base_config_1.TYPE_VALUE], + ['CSSRotate', base_config_1.TYPE_VALUE], + ['CSSScale', base_config_1.TYPE_VALUE], + ['CSSSkew', base_config_1.TYPE_VALUE], + ['CSSSkewX', base_config_1.TYPE_VALUE], + ['CSSSkewY', base_config_1.TYPE_VALUE], + ['CSSStyleValue', base_config_1.TYPE_VALUE], + ['CSSTransformComponent', base_config_1.TYPE_VALUE], + ['CSSTransformValue', base_config_1.TYPE_VALUE], + ['CSSTranslate', base_config_1.TYPE_VALUE], + ['CSSUnitValue', base_config_1.TYPE_VALUE], + ['CSSUnparsedValue', base_config_1.TYPE_VALUE], + ['CSSVariableReferenceValue', base_config_1.TYPE_VALUE], + ['Cache', base_config_1.TYPE_VALUE], + ['CacheStorage', base_config_1.TYPE_VALUE], + ['CanvasCompositing', base_config_1.TYPE], + ['CanvasDrawImage', base_config_1.TYPE], + ['CanvasDrawPath', base_config_1.TYPE], + ['CanvasFillStrokeStyles', base_config_1.TYPE], + ['CanvasFilters', base_config_1.TYPE], + ['CanvasGradient', base_config_1.TYPE_VALUE], + ['CanvasImageData', base_config_1.TYPE], + ['CanvasImageSmoothing', base_config_1.TYPE], + ['CanvasPath', base_config_1.TYPE], + ['CanvasPathDrawingStyles', base_config_1.TYPE], + ['CanvasPattern', base_config_1.TYPE_VALUE], + ['CanvasRect', base_config_1.TYPE], + ['CanvasShadowStyles', base_config_1.TYPE], + ['CanvasState', base_config_1.TYPE], + ['CanvasText', base_config_1.TYPE], + ['CanvasTextDrawingStyles', base_config_1.TYPE], + ['CanvasTransform', base_config_1.TYPE], + ['Client', base_config_1.TYPE_VALUE], + ['Clients', base_config_1.TYPE_VALUE], + ['CloseEvent', base_config_1.TYPE_VALUE], + ['CompressionStream', base_config_1.TYPE_VALUE], + ['CountQueuingStrategy', base_config_1.TYPE_VALUE], + ['Crypto', base_config_1.TYPE_VALUE], + ['CryptoKey', base_config_1.TYPE_VALUE], + ['CustomEvent', base_config_1.TYPE_VALUE], + ['DOMException', base_config_1.TYPE_VALUE], + ['DOMMatrix', base_config_1.TYPE_VALUE], + ['DOMMatrixReadOnly', base_config_1.TYPE_VALUE], + ['DOMPoint', base_config_1.TYPE_VALUE], + ['DOMPointReadOnly', base_config_1.TYPE_VALUE], + ['DOMQuad', base_config_1.TYPE_VALUE], + ['DOMRect', base_config_1.TYPE_VALUE], + ['DOMRectReadOnly', base_config_1.TYPE_VALUE], + ['DOMStringList', base_config_1.TYPE_VALUE], + ['DecompressionStream', base_config_1.TYPE_VALUE], + ['DedicatedWorkerGlobalScopeEventMap', base_config_1.TYPE], + ['DedicatedWorkerGlobalScope', base_config_1.TYPE_VALUE], + ['EXT_blend_minmax', base_config_1.TYPE], + ['EXT_color_buffer_float', base_config_1.TYPE], + ['EXT_color_buffer_half_float', base_config_1.TYPE], + ['EXT_float_blend', base_config_1.TYPE], + ['EXT_frag_depth', base_config_1.TYPE], + ['EXT_sRGB', base_config_1.TYPE], + ['EXT_shader_texture_lod', base_config_1.TYPE], + ['EXT_texture_compression_bptc', base_config_1.TYPE], + ['EXT_texture_compression_rgtc', base_config_1.TYPE], + ['EXT_texture_filter_anisotropic', base_config_1.TYPE], + ['EXT_texture_norm16', base_config_1.TYPE], + ['EncodedAudioChunk', base_config_1.TYPE_VALUE], + ['EncodedVideoChunk', base_config_1.TYPE_VALUE], + ['ErrorEvent', base_config_1.TYPE_VALUE], + ['Event', base_config_1.TYPE_VALUE], + ['EventListener', base_config_1.TYPE], + ['EventListenerObject', base_config_1.TYPE], + ['EventSourceEventMap', base_config_1.TYPE], + ['EventSource', base_config_1.TYPE_VALUE], + ['EventTarget', base_config_1.TYPE_VALUE], + ['ExtendableEvent', base_config_1.TYPE_VALUE], + ['ExtendableMessageEvent', base_config_1.TYPE_VALUE], + ['FetchEvent', base_config_1.TYPE_VALUE], + ['File', base_config_1.TYPE_VALUE], + ['FileList', base_config_1.TYPE_VALUE], + ['FileReaderEventMap', base_config_1.TYPE], + ['FileReader', base_config_1.TYPE_VALUE], + ['FileReaderSync', base_config_1.TYPE_VALUE], + ['FileSystemDirectoryHandle', base_config_1.TYPE_VALUE], + ['FileSystemFileHandle', base_config_1.TYPE_VALUE], + ['FileSystemHandle', base_config_1.TYPE_VALUE], + ['FileSystemSyncAccessHandle', base_config_1.TYPE_VALUE], + ['FileSystemWritableFileStream', base_config_1.TYPE_VALUE], + ['FontFace', base_config_1.TYPE_VALUE], + ['FontFaceSetEventMap', base_config_1.TYPE], + ['FontFaceSet', base_config_1.TYPE_VALUE], + ['FontFaceSetLoadEvent', base_config_1.TYPE_VALUE], + ['FontFaceSource', base_config_1.TYPE], + ['FormData', base_config_1.TYPE_VALUE], + ['GPUError', base_config_1.TYPE], + ['GenericTransformStream', base_config_1.TYPE], + ['Headers', base_config_1.TYPE_VALUE], + ['IDBCursor', base_config_1.TYPE_VALUE], + ['IDBCursorWithValue', base_config_1.TYPE_VALUE], + ['IDBDatabaseEventMap', base_config_1.TYPE], + ['IDBDatabase', base_config_1.TYPE_VALUE], + ['IDBFactory', base_config_1.TYPE_VALUE], + ['IDBIndex', base_config_1.TYPE_VALUE], + ['IDBKeyRange', base_config_1.TYPE_VALUE], + ['IDBObjectStore', base_config_1.TYPE_VALUE], + ['IDBOpenDBRequestEventMap', base_config_1.TYPE], + ['IDBOpenDBRequest', base_config_1.TYPE_VALUE], + ['IDBRequestEventMap', base_config_1.TYPE], + ['IDBRequest', base_config_1.TYPE_VALUE], + ['IDBTransactionEventMap', base_config_1.TYPE], + ['IDBTransaction', base_config_1.TYPE_VALUE], + ['IDBVersionChangeEvent', base_config_1.TYPE_VALUE], + ['ImageBitmap', base_config_1.TYPE_VALUE], + ['ImageBitmapRenderingContext', base_config_1.TYPE_VALUE], + ['ImageData', base_config_1.TYPE_VALUE], + ['ImageDecoder', base_config_1.TYPE_VALUE], + ['ImageTrack', base_config_1.TYPE_VALUE], + ['ImageTrackList', base_config_1.TYPE_VALUE], + ['ImportMeta', base_config_1.TYPE], + ['KHR_parallel_shader_compile', base_config_1.TYPE], + ['Lock', base_config_1.TYPE_VALUE], + ['LockManager', base_config_1.TYPE_VALUE], + ['MediaCapabilities', base_config_1.TYPE_VALUE], + ['MediaSourceHandle', base_config_1.TYPE_VALUE], + ['MediaStreamTrackProcessor', base_config_1.TYPE_VALUE], + ['MessageChannel', base_config_1.TYPE_VALUE], + ['MessageEvent', base_config_1.TYPE_VALUE], + ['MessageEventTargetEventMap', base_config_1.TYPE], + ['MessageEventTarget', base_config_1.TYPE], + ['MessagePortEventMap', base_config_1.TYPE], + ['MessagePort', base_config_1.TYPE_VALUE], + ['NavigationPreloadManager', base_config_1.TYPE_VALUE], + ['NavigatorBadge', base_config_1.TYPE], + ['NavigatorConcurrentHardware', base_config_1.TYPE], + ['NavigatorID', base_config_1.TYPE], + ['NavigatorLanguage', base_config_1.TYPE], + ['NavigatorLocks', base_config_1.TYPE], + ['NavigatorOnLine', base_config_1.TYPE], + ['NavigatorStorage', base_config_1.TYPE], + ['NotificationEventMap', base_config_1.TYPE], + ['Notification', base_config_1.TYPE_VALUE], + ['NotificationEvent', base_config_1.TYPE_VALUE], + ['OES_draw_buffers_indexed', base_config_1.TYPE], + ['OES_element_index_uint', base_config_1.TYPE], + ['OES_fbo_render_mipmap', base_config_1.TYPE], + ['OES_standard_derivatives', base_config_1.TYPE], + ['OES_texture_float', base_config_1.TYPE], + ['OES_texture_float_linear', base_config_1.TYPE], + ['OES_texture_half_float', base_config_1.TYPE], + ['OES_texture_half_float_linear', base_config_1.TYPE], + ['OES_vertex_array_object', base_config_1.TYPE], + ['OVR_multiview2', base_config_1.TYPE], + ['OffscreenCanvasEventMap', base_config_1.TYPE], + ['OffscreenCanvas', base_config_1.TYPE_VALUE], + ['OffscreenCanvasRenderingContext2D', base_config_1.TYPE_VALUE], + ['Path2D', base_config_1.TYPE_VALUE], + ['PerformanceEventMap', base_config_1.TYPE], + ['Performance', base_config_1.TYPE_VALUE], + ['PerformanceEntry', base_config_1.TYPE_VALUE], + ['PerformanceMark', base_config_1.TYPE_VALUE], + ['PerformanceMeasure', base_config_1.TYPE_VALUE], + ['PerformanceObserver', base_config_1.TYPE_VALUE], + ['PerformanceObserverEntryList', base_config_1.TYPE_VALUE], + ['PerformanceResourceTiming', base_config_1.TYPE_VALUE], + ['PerformanceServerTiming', base_config_1.TYPE_VALUE], + ['PermissionStatusEventMap', base_config_1.TYPE], + ['PermissionStatus', base_config_1.TYPE_VALUE], + ['Permissions', base_config_1.TYPE_VALUE], + ['ProgressEvent', base_config_1.TYPE_VALUE], + ['PromiseRejectionEvent', base_config_1.TYPE_VALUE], + ['PushEvent', base_config_1.TYPE_VALUE], + ['PushManager', base_config_1.TYPE_VALUE], + ['PushMessageData', base_config_1.TYPE_VALUE], + ['PushSubscription', base_config_1.TYPE_VALUE], + ['PushSubscriptionOptions', base_config_1.TYPE_VALUE], + ['RTCDataChannelEventMap', base_config_1.TYPE], + ['RTCDataChannel', base_config_1.TYPE_VALUE], + ['RTCEncodedAudioFrame', base_config_1.TYPE_VALUE], + ['RTCEncodedVideoFrame', base_config_1.TYPE_VALUE], + ['RTCRtpScriptTransformer', base_config_1.TYPE_VALUE], + ['RTCTransformEvent', base_config_1.TYPE_VALUE], + ['ReadableByteStreamController', base_config_1.TYPE_VALUE], + ['ReadableStream', base_config_1.TYPE_VALUE], + ['ReadableStreamBYOBReader', base_config_1.TYPE_VALUE], + ['ReadableStreamBYOBRequest', base_config_1.TYPE_VALUE], + ['ReadableStreamDefaultController', base_config_1.TYPE_VALUE], + ['ReadableStreamDefaultReader', base_config_1.TYPE_VALUE], + ['ReadableStreamGenericReader', base_config_1.TYPE], + ['Report', base_config_1.TYPE_VALUE], + ['ReportBody', base_config_1.TYPE_VALUE], + ['ReportingObserver', base_config_1.TYPE_VALUE], + ['Request', base_config_1.TYPE_VALUE], + ['Response', base_config_1.TYPE_VALUE], + ['SecurityPolicyViolationEvent', base_config_1.TYPE_VALUE], + ['ServiceWorkerEventMap', base_config_1.TYPE], + ['ServiceWorker', base_config_1.TYPE_VALUE], + ['ServiceWorkerContainerEventMap', base_config_1.TYPE], + ['ServiceWorkerContainer', base_config_1.TYPE_VALUE], + ['ServiceWorkerGlobalScopeEventMap', base_config_1.TYPE], + ['ServiceWorkerGlobalScope', base_config_1.TYPE_VALUE], + ['ServiceWorkerRegistrationEventMap', base_config_1.TYPE], + ['ServiceWorkerRegistration', base_config_1.TYPE_VALUE], + ['SharedWorkerGlobalScopeEventMap', base_config_1.TYPE], + ['SharedWorkerGlobalScope', base_config_1.TYPE_VALUE], + ['StorageManager', base_config_1.TYPE_VALUE], + ['StylePropertyMapReadOnly', base_config_1.TYPE_VALUE], + ['SubtleCrypto', base_config_1.TYPE_VALUE], + ['TextDecoder', base_config_1.TYPE_VALUE], + ['TextDecoderCommon', base_config_1.TYPE], + ['TextDecoderStream', base_config_1.TYPE_VALUE], + ['TextEncoder', base_config_1.TYPE_VALUE], + ['TextEncoderCommon', base_config_1.TYPE], + ['TextEncoderStream', base_config_1.TYPE_VALUE], + ['TextMetrics', base_config_1.TYPE_VALUE], + ['TransformStream', base_config_1.TYPE_VALUE], + ['TransformStreamDefaultController', base_config_1.TYPE_VALUE], + ['URL', base_config_1.TYPE_VALUE], + ['URLSearchParams', base_config_1.TYPE_VALUE], + ['VideoColorSpace', base_config_1.TYPE_VALUE], + ['VideoDecoderEventMap', base_config_1.TYPE], + ['VideoDecoder', base_config_1.TYPE_VALUE], + ['VideoEncoderEventMap', base_config_1.TYPE], + ['VideoEncoder', base_config_1.TYPE_VALUE], + ['VideoFrame', base_config_1.TYPE_VALUE], + ['WEBGL_color_buffer_float', base_config_1.TYPE], + ['WEBGL_compressed_texture_astc', base_config_1.TYPE], + ['WEBGL_compressed_texture_etc', base_config_1.TYPE], + ['WEBGL_compressed_texture_etc1', base_config_1.TYPE], + ['WEBGL_compressed_texture_pvrtc', base_config_1.TYPE], + ['WEBGL_compressed_texture_s3tc', base_config_1.TYPE], + ['WEBGL_compressed_texture_s3tc_srgb', base_config_1.TYPE], + ['WEBGL_debug_renderer_info', base_config_1.TYPE], + ['WEBGL_debug_shaders', base_config_1.TYPE], + ['WEBGL_depth_texture', base_config_1.TYPE], + ['WEBGL_draw_buffers', base_config_1.TYPE], + ['WEBGL_lose_context', base_config_1.TYPE], + ['WEBGL_multi_draw', base_config_1.TYPE], + ['WebGL2RenderingContext', base_config_1.TYPE_VALUE], + ['WebGL2RenderingContextBase', base_config_1.TYPE], + ['WebGL2RenderingContextOverloads', base_config_1.TYPE], + ['WebGLActiveInfo', base_config_1.TYPE_VALUE], + ['WebGLBuffer', base_config_1.TYPE_VALUE], + ['WebGLContextEvent', base_config_1.TYPE_VALUE], + ['WebGLFramebuffer', base_config_1.TYPE_VALUE], + ['WebGLProgram', base_config_1.TYPE_VALUE], + ['WebGLQuery', base_config_1.TYPE_VALUE], + ['WebGLRenderbuffer', base_config_1.TYPE_VALUE], + ['WebGLRenderingContext', base_config_1.TYPE_VALUE], + ['WebGLRenderingContextBase', base_config_1.TYPE], + ['WebGLRenderingContextOverloads', base_config_1.TYPE], + ['WebGLSampler', base_config_1.TYPE_VALUE], + ['WebGLShader', base_config_1.TYPE_VALUE], + ['WebGLShaderPrecisionFormat', base_config_1.TYPE_VALUE], + ['WebGLSync', base_config_1.TYPE_VALUE], + ['WebGLTexture', base_config_1.TYPE_VALUE], + ['WebGLTransformFeedback', base_config_1.TYPE_VALUE], + ['WebGLUniformLocation', base_config_1.TYPE_VALUE], + ['WebGLVertexArrayObject', base_config_1.TYPE_VALUE], + ['WebGLVertexArrayObjectOES', base_config_1.TYPE], + ['WebSocketEventMap', base_config_1.TYPE], + ['WebSocket', base_config_1.TYPE_VALUE], + ['WebTransport', base_config_1.TYPE_VALUE], + ['WebTransportBidirectionalStream', base_config_1.TYPE_VALUE], + ['WebTransportDatagramDuplexStream', base_config_1.TYPE_VALUE], + ['WebTransportError', base_config_1.TYPE_VALUE], + ['WindowClient', base_config_1.TYPE_VALUE], + ['WindowOrWorkerGlobalScope', base_config_1.TYPE], + ['WorkerEventMap', base_config_1.TYPE], + ['Worker', base_config_1.TYPE_VALUE], + ['WorkerGlobalScopeEventMap', base_config_1.TYPE], + ['WorkerGlobalScope', base_config_1.TYPE_VALUE], + ['WorkerLocation', base_config_1.TYPE_VALUE], + ['WorkerNavigator', base_config_1.TYPE_VALUE], + ['WritableStream', base_config_1.TYPE_VALUE], + ['WritableStreamDefaultController', base_config_1.TYPE_VALUE], + ['WritableStreamDefaultWriter', base_config_1.TYPE_VALUE], + ['XMLHttpRequestEventMap', base_config_1.TYPE], + ['XMLHttpRequest', base_config_1.TYPE_VALUE], + ['XMLHttpRequestEventTargetEventMap', base_config_1.TYPE], + ['XMLHttpRequestEventTarget', base_config_1.TYPE_VALUE], + ['XMLHttpRequestUpload', base_config_1.TYPE_VALUE], + ['Console', base_config_1.TYPE], + ['WebAssembly', base_config_1.TYPE_VALUE], + ['AudioDataOutputCallback', base_config_1.TYPE], + ['EncodedAudioChunkOutputCallback', base_config_1.TYPE], + ['EncodedVideoChunkOutputCallback', base_config_1.TYPE], + ['FrameRequestCallback', base_config_1.TYPE], + ['LockGrantedCallback', base_config_1.TYPE], + ['OnErrorEventHandlerNonNull', base_config_1.TYPE], + ['PerformanceObserverCallback', base_config_1.TYPE], + ['QueuingStrategySize', base_config_1.TYPE], + ['ReportingObserverCallback', base_config_1.TYPE], + ['TransformerFlushCallback', base_config_1.TYPE], + ['TransformerStartCallback', base_config_1.TYPE], + ['TransformerTransformCallback', base_config_1.TYPE], + ['UnderlyingSinkAbortCallback', base_config_1.TYPE], + ['UnderlyingSinkCloseCallback', base_config_1.TYPE], + ['UnderlyingSinkStartCallback', base_config_1.TYPE], + ['UnderlyingSinkWriteCallback', base_config_1.TYPE], + ['UnderlyingSourceCancelCallback', base_config_1.TYPE], + ['UnderlyingSourcePullCallback', base_config_1.TYPE], + ['UnderlyingSourceStartCallback', base_config_1.TYPE], + ['VideoFrameOutputCallback', base_config_1.TYPE], + ['VoidFunction', base_config_1.TYPE], + ['WebCodecsErrorCallback', base_config_1.TYPE], + ['AlgorithmIdentifier', base_config_1.TYPE], + ['AllowSharedBufferSource', base_config_1.TYPE], + ['BigInteger', base_config_1.TYPE], + ['BlobPart', base_config_1.TYPE], + ['BodyInit', base_config_1.TYPE], + ['BufferSource', base_config_1.TYPE], + ['CSSKeywordish', base_config_1.TYPE], + ['CSSNumberish', base_config_1.TYPE], + ['CSSPerspectiveValue', base_config_1.TYPE], + ['CSSUnparsedSegment', base_config_1.TYPE], + ['CanvasImageSource', base_config_1.TYPE], + ['DOMHighResTimeStamp', base_config_1.TYPE], + ['EpochTimeStamp', base_config_1.TYPE], + ['EventListenerOrEventListenerObject', base_config_1.TYPE], + ['FileSystemWriteChunkType', base_config_1.TYPE], + ['Float32List', base_config_1.TYPE], + ['FormDataEntryValue', base_config_1.TYPE], + ['GLbitfield', base_config_1.TYPE], + ['GLboolean', base_config_1.TYPE], + ['GLclampf', base_config_1.TYPE], + ['GLenum', base_config_1.TYPE], + ['GLfloat', base_config_1.TYPE], + ['GLint', base_config_1.TYPE], + ['GLint64', base_config_1.TYPE], + ['GLintptr', base_config_1.TYPE], + ['GLsizei', base_config_1.TYPE], + ['GLsizeiptr', base_config_1.TYPE], + ['GLuint', base_config_1.TYPE], + ['GLuint64', base_config_1.TYPE], + ['HashAlgorithmIdentifier', base_config_1.TYPE], + ['HeadersInit', base_config_1.TYPE], + ['IDBValidKey', base_config_1.TYPE], + ['ImageBitmapSource', base_config_1.TYPE], + ['ImageBufferSource', base_config_1.TYPE], + ['Int32List', base_config_1.TYPE], + ['MessageEventSource', base_config_1.TYPE], + ['NamedCurve', base_config_1.TYPE], + ['OffscreenRenderingContext', base_config_1.TYPE], + ['OnErrorEventHandler', base_config_1.TYPE], + ['PerformanceEntryList', base_config_1.TYPE], + ['PushMessageDataInit', base_config_1.TYPE], + ['ReadableStreamController', base_config_1.TYPE], + ['ReadableStreamReadResult', base_config_1.TYPE], + ['ReadableStreamReader', base_config_1.TYPE], + ['ReportList', base_config_1.TYPE], + ['RequestInfo', base_config_1.TYPE], + ['TexImageSource', base_config_1.TYPE], + ['TimerHandler', base_config_1.TYPE], + ['Transferable', base_config_1.TYPE], + ['Uint32List', base_config_1.TYPE], + ['XMLHttpRequestBodyInit', base_config_1.TYPE], + ['AlphaOption', base_config_1.TYPE], + ['AudioSampleFormat', base_config_1.TYPE], + ['AvcBitstreamFormat', base_config_1.TYPE], + ['BinaryType', base_config_1.TYPE], + ['BitrateMode', base_config_1.TYPE], + ['CSSMathOperator', base_config_1.TYPE], + ['CSSNumericBaseType', base_config_1.TYPE], + ['CanvasDirection', base_config_1.TYPE], + ['CanvasFillRule', base_config_1.TYPE], + ['CanvasFontKerning', base_config_1.TYPE], + ['CanvasFontStretch', base_config_1.TYPE], + ['CanvasFontVariantCaps', base_config_1.TYPE], + ['CanvasLineCap', base_config_1.TYPE], + ['CanvasLineJoin', base_config_1.TYPE], + ['CanvasTextAlign', base_config_1.TYPE], + ['CanvasTextBaseline', base_config_1.TYPE], + ['CanvasTextRendering', base_config_1.TYPE], + ['ClientTypes', base_config_1.TYPE], + ['CodecState', base_config_1.TYPE], + ['ColorGamut', base_config_1.TYPE], + ['ColorSpaceConversion', base_config_1.TYPE], + ['CompressionFormat', base_config_1.TYPE], + ['DocumentVisibilityState', base_config_1.TYPE], + ['EncodedAudioChunkType', base_config_1.TYPE], + ['EncodedVideoChunkType', base_config_1.TYPE], + ['EndingType', base_config_1.TYPE], + ['FileSystemHandleKind', base_config_1.TYPE], + ['FontDisplay', base_config_1.TYPE], + ['FontFaceLoadStatus', base_config_1.TYPE], + ['FontFaceSetLoadStatus', base_config_1.TYPE], + ['FrameType', base_config_1.TYPE], + ['GlobalCompositeOperation', base_config_1.TYPE], + ['HardwareAcceleration', base_config_1.TYPE], + ['HdrMetadataType', base_config_1.TYPE], + ['IDBCursorDirection', base_config_1.TYPE], + ['IDBRequestReadyState', base_config_1.TYPE], + ['IDBTransactionDurability', base_config_1.TYPE], + ['IDBTransactionMode', base_config_1.TYPE], + ['ImageOrientation', base_config_1.TYPE], + ['ImageSmoothingQuality', base_config_1.TYPE], + ['KeyFormat', base_config_1.TYPE], + ['KeyType', base_config_1.TYPE], + ['KeyUsage', base_config_1.TYPE], + ['LatencyMode', base_config_1.TYPE], + ['LockMode', base_config_1.TYPE], + ['MediaDecodingType', base_config_1.TYPE], + ['MediaEncodingType', base_config_1.TYPE], + ['NotificationDirection', base_config_1.TYPE], + ['NotificationPermission', base_config_1.TYPE], + ['OffscreenRenderingContextId', base_config_1.TYPE], + ['OpusBitstreamFormat', base_config_1.TYPE], + ['PermissionName', base_config_1.TYPE], + ['PermissionState', base_config_1.TYPE], + ['PredefinedColorSpace', base_config_1.TYPE], + ['PremultiplyAlpha', base_config_1.TYPE], + ['PushEncryptionKeyName', base_config_1.TYPE], + ['RTCDataChannelState', base_config_1.TYPE], + ['RTCEncodedVideoFrameType', base_config_1.TYPE], + ['ReadableStreamReaderMode', base_config_1.TYPE], + ['ReadableStreamType', base_config_1.TYPE], + ['ReferrerPolicy', base_config_1.TYPE], + ['RequestCache', base_config_1.TYPE], + ['RequestCredentials', base_config_1.TYPE], + ['RequestDestination', base_config_1.TYPE], + ['RequestMode', base_config_1.TYPE], + ['RequestPriority', base_config_1.TYPE], + ['RequestRedirect', base_config_1.TYPE], + ['ResizeQuality', base_config_1.TYPE], + ['ResponseType', base_config_1.TYPE], + ['SecurityPolicyViolationEventDisposition', base_config_1.TYPE], + ['ServiceWorkerState', base_config_1.TYPE], + ['ServiceWorkerUpdateViaCache', base_config_1.TYPE], + ['TransferFunction', base_config_1.TYPE], + ['VideoColorPrimaries', base_config_1.TYPE], + ['VideoEncoderBitrateMode', base_config_1.TYPE], + ['VideoMatrixCoefficients', base_config_1.TYPE], + ['VideoPixelFormat', base_config_1.TYPE], + ['VideoTransferCharacteristics', base_config_1.TYPE], + ['WebGLPowerPreference', base_config_1.TYPE], + ['WebTransportCongestionControl', base_config_1.TYPE], + ['WebTransportErrorSource', base_config_1.TYPE], + ['WorkerType', base_config_1.TYPE], + ['WriteCommandType', base_config_1.TYPE], + ['XMLHttpRequestResponseType', base_config_1.TYPE], + ], +}; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.d.ts new file mode 100644 index 00000000..fdaa70dc --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.d.ts @@ -0,0 +1,28 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { Referencer } from './Referencer'; +import { Visitor } from './Visitor'; +export declare class ClassVisitor extends Visitor { + #private; + constructor(referencer: Referencer, node: TSESTree.ClassDeclaration | TSESTree.ClassExpression); + static visit(referencer: Referencer, node: TSESTree.ClassDeclaration | TSESTree.ClassExpression): void; + visit(node: TSESTree.Node | null | undefined): void; + protected visitClass(node: TSESTree.ClassDeclaration | TSESTree.ClassExpression): void; + protected visitFunctionParameterTypeAnnotation(node: TSESTree.Parameter): void; + protected visitMethod(node: TSESTree.MethodDefinition): void; + protected visitMethodFunction(node: TSESTree.FunctionExpression, methodNode: TSESTree.MethodDefinition): void; + protected visitPropertyBase(node: TSESTree.AccessorProperty | TSESTree.PropertyDefinition | TSESTree.TSAbstractAccessorProperty | TSESTree.TSAbstractMethodDefinition | TSESTree.TSAbstractPropertyDefinition): void; + protected visitPropertyDefinition(node: TSESTree.AccessorProperty | TSESTree.PropertyDefinition | TSESTree.TSAbstractAccessorProperty | TSESTree.TSAbstractPropertyDefinition): void; + protected visitType(node: TSESTree.Node | null | undefined): void; + protected AccessorProperty(node: TSESTree.AccessorProperty): void; + protected ClassBody(node: TSESTree.ClassBody): void; + protected Identifier(node: TSESTree.Identifier): void; + protected MethodDefinition(node: TSESTree.MethodDefinition): void; + protected PrivateIdentifier(): void; + protected PropertyDefinition(node: TSESTree.PropertyDefinition): void; + protected StaticBlock(node: TSESTree.StaticBlock): void; + protected TSAbstractAccessorProperty(node: TSESTree.TSAbstractAccessorProperty): void; + protected TSAbstractMethodDefinition(node: TSESTree.TSAbstractMethodDefinition): void; + protected TSAbstractPropertyDefinition(node: TSESTree.TSAbstractPropertyDefinition): void; + protected TSIndexSignature(node: TSESTree.TSIndexSignature): void; +} +//# sourceMappingURL=ClassVisitor.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.d.ts.map new file mode 100644 index 00000000..576fe00b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ClassVisitor.d.ts","sourceRoot":"","sources":["../../src/referencer/ClassVisitor.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B,GACxC,IAAI;IAWP,SAAS,CAAC,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI;IAWjE,SAAS,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,gBAAgB,GAAG,IAAI;IAIjE,SAAS,CAAC,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,SAAS,GAAG,IAAI;IAMnD,SAAS,CAAC,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI;IAIrD,SAAS,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,gBAAgB,GAAG,IAAI;IAIjE,SAAS,CAAC,iBAAiB,IAAI,IAAI;IAInC,SAAS,CAAC,kBAAkB,CAAC,IAAI,EAAE,QAAQ,CAAC,kBAAkB,GAAG,IAAI;IAIrE,SAAS,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,WAAW,GAAG,IAAI;IAQvD,SAAS,CAAC,0BAA0B,CAClC,IAAI,EAAE,QAAQ,CAAC,0BAA0B,GACxC,IAAI;IAIP,SAAS,CAAC,0BAA0B,CAClC,IAAI,EAAE,QAAQ,CAAC,0BAA0B,GACxC,IAAI;IAIP,SAAS,CAAC,4BAA4B,CACpC,IAAI,EAAE,QAAQ,CAAC,4BAA4B,GAC1C,IAAI;IAIP,SAAS,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,gBAAgB,GAAG,IAAI;CAGlE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.js new file mode 100644 index 00000000..c5c90cc7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.js @@ -0,0 +1,267 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClassVisitor = void 0; +const types_1 = require("@typescript-eslint/types"); +const definition_1 = require("../definition"); +const TypeVisitor_1 = require("./TypeVisitor"); +const Visitor_1 = require("./Visitor"); +class ClassVisitor extends Visitor_1.Visitor { + #classNode; + #referencer; + constructor(referencer, node) { + super(referencer); + this.#referencer = referencer; + this.#classNode = node; + } + static visit(referencer, node) { + const classVisitor = new ClassVisitor(referencer, node); + classVisitor.visitClass(node); + } + visit(node) { + // make sure we only handle the nodes we are designed to handle + if (node && node.type in this) { + super.visit(node); + } + else { + this.#referencer.visit(node); + } + } + /////////////////// + // Visit helpers // + /////////////////// + visitClass(node) { + if (node.type === types_1.AST_NODE_TYPES.ClassDeclaration && node.id) { + this.#referencer + .currentScope() + .defineIdentifier(node.id, new definition_1.ClassNameDefinition(node.id, node)); + } + node.decorators.forEach(d => this.#referencer.visit(d)); + this.#referencer.scopeManager.nestClassScope(node); + if (node.id) { + // define the class name again inside the new scope + // references to the class should not resolve directly to the parent class + this.#referencer + .currentScope() + .defineIdentifier(node.id, new definition_1.ClassNameDefinition(node.id, node)); + } + this.#referencer.visit(node.superClass); + // visit the type param declarations + this.visitType(node.typeParameters); + // then the usages + this.visitType(node.superTypeArguments); + node.implements.forEach(imp => this.visitType(imp)); + this.visit(node.body); + this.#referencer.close(node); + } + visitFunctionParameterTypeAnnotation(node) { + switch (node.type) { + case types_1.AST_NODE_TYPES.AssignmentPattern: + this.visitType(node.left.typeAnnotation); + break; + case types_1.AST_NODE_TYPES.TSParameterProperty: + this.visitFunctionParameterTypeAnnotation(node.parameter); + break; + default: + this.visitType(node.typeAnnotation); + } + } + visitMethod(node) { + if (node.computed) { + this.#referencer.visit(node.key); + } + if (node.value.type === types_1.AST_NODE_TYPES.FunctionExpression) { + this.visitMethodFunction(node.value, node); + } + else { + this.#referencer.visit(node.value); + } + node.decorators.forEach(d => this.#referencer.visit(d)); + } + visitMethodFunction(node, methodNode) { + if (node.id) { + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + this.#referencer.scopeManager.nestFunctionExpressionNameScope(node); + } + node.params.forEach(param => { + param.decorators.forEach(d => this.visit(d)); + }); + // Consider this function is in the MethodDefinition. + this.#referencer.scopeManager.nestFunctionScope(node, true); + /** + * class A { + * @meta // <--- check this + * foo(a: Type) {} + * + * @meta // <--- check this + * foo(): Type {} + * } + */ + let withMethodDecorators = !!methodNode.decorators.length; + /** + * class A { + * foo( + * @meta // <--- check this + * a: Type + * ) {} + * + * set foo( + * @meta // <--- EXCEPT this. TS do nothing for this + * a: Type + * ) {} + * } + */ + withMethodDecorators ||= + methodNode.kind !== 'set' && + node.params.some(param => param.decorators.length); + if (!withMethodDecorators && methodNode.kind === 'set') { + const keyName = getLiteralMethodKeyName(methodNode); + /** + * class A { + * @meta // <--- check this + * get a() {} + * set ['a'](v: Type) {} + * } + */ + if (keyName != null && + this.#classNode.body.body.find((node) => node !== methodNode && + node.type === types_1.AST_NODE_TYPES.MethodDefinition && + // Node must both be static or not + node.static === methodNode.static && + getLiteralMethodKeyName(node) === keyName)?.decorators.length) { + withMethodDecorators = true; + } + } + /** + * @meta // <--- check this + * class A { + * constructor(a: Type) {} + * } + */ + if (!withMethodDecorators && + methodNode.kind === 'constructor' && + this.#classNode.decorators.length) { + withMethodDecorators = true; + } + // Process parameter declarations. + for (const param of node.params) { + this.visitPattern(param, (pattern, info) => { + this.#referencer + .currentScope() + .defineIdentifier(pattern, new definition_1.ParameterDefinition(pattern, node, info.rest)); + this.#referencer.referencingDefaultValue(pattern, info.assignments, null, true); + }, { processRightHandNodes: true }); + this.visitFunctionParameterTypeAnnotation(param); + } + this.visitType(node.returnType); + this.visitType(node.typeParameters); + this.#referencer.visitChildren(node.body); + this.#referencer.close(node); + } + visitPropertyBase(node) { + if (node.computed) { + this.#referencer.visit(node.key); + } + if (node.value) { + if (node.type === types_1.AST_NODE_TYPES.PropertyDefinition || + node.type === types_1.AST_NODE_TYPES.AccessorProperty) { + this.#referencer.scopeManager.nestClassFieldInitializerScope(node.value); + } + this.#referencer.visit(node.value); + if (node.type === types_1.AST_NODE_TYPES.PropertyDefinition || + node.type === types_1.AST_NODE_TYPES.AccessorProperty) { + this.#referencer.close(node.value); + } + } + node.decorators.forEach(d => this.#referencer.visit(d)); + } + visitPropertyDefinition(node) { + this.visitPropertyBase(node); + /** + * class A { + * @meta // <--- check this + * foo: Type; + * } + */ + this.visitType(node.typeAnnotation); + } + visitType(node) { + if (!node) { + return; + } + TypeVisitor_1.TypeVisitor.visit(this.#referencer, node); + } + ///////////////////// + // Visit selectors // + ///////////////////// + AccessorProperty(node) { + this.visitPropertyDefinition(node); + } + ClassBody(node) { + // this is here on purpose so that this visitor explicitly declares visitors + // for all nodes it cares about (see the instance visit method above) + this.visitChildren(node); + } + Identifier(node) { + this.#referencer.visit(node); + } + MethodDefinition(node) { + this.visitMethod(node); + } + PrivateIdentifier() { + // intentionally skip + } + PropertyDefinition(node) { + this.visitPropertyDefinition(node); + } + StaticBlock(node) { + this.#referencer.scopeManager.nestClassStaticBlockScope(node); + node.body.forEach(b => this.visit(b)); + this.#referencer.close(node); + } + TSAbstractAccessorProperty(node) { + this.visitPropertyDefinition(node); + } + TSAbstractMethodDefinition(node) { + this.visitPropertyBase(node); + } + TSAbstractPropertyDefinition(node) { + this.visitPropertyDefinition(node); + } + TSIndexSignature(node) { + this.visitType(node); + } +} +exports.ClassVisitor = ClassVisitor; +/** + * Only if key is one of [identifier, string, number], ts will combine metadata of accessors . + * class A { + * get a() {} + * set ['a'](v: Type) {} + * + * get [1]() {} + * set [1](v: Type) {} + * + * // Following won't be combined + * get [key]() {} + * set [key](v: Type) {} + * + * get [true]() {} + * set [true](v: Type) {} + * + * get ['a'+'b']() {} + * set ['a'+'b']() {} + * } + */ +function getLiteralMethodKeyName(node) { + if (node.computed && node.key.type === types_1.AST_NODE_TYPES.Literal) { + if (typeof node.key.value === 'string' || + typeof node.key.value === 'number') { + return node.key.value; + } + } + else if (!node.computed && node.key.type === types_1.AST_NODE_TYPES.Identifier) { + return node.key.name; + } + return null; +} diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/ExportVisitor.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ExportVisitor.d.ts new file mode 100644 index 00000000..99f600d7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ExportVisitor.d.ts @@ -0,0 +1,14 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { Referencer } from './Referencer'; +import { Visitor } from './Visitor'; +export type ExportNode = TSESTree.ExportAllDeclaration | TSESTree.ExportDefaultDeclaration | TSESTree.ExportNamedDeclaration; +export declare class ExportVisitor extends Visitor { + #private; + constructor(node: ExportNode, referencer: Referencer); + static visit(referencer: Referencer, node: ExportNode): void; + protected ExportDefaultDeclaration(node: TSESTree.ExportDefaultDeclaration): void; + protected ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration): void; + protected ExportSpecifier(node: TSESTree.ExportSpecifier): void; + protected Identifier(node: TSESTree.Identifier): void; +} +//# sourceMappingURL=ExportVisitor.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/ExportVisitor.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ExportVisitor.d.ts.map new file mode 100644 index 00000000..7fac17ef --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ExportVisitor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ExportVisitor.d.ts","sourceRoot":"","sources":["../../src/referencer/ExportVisitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,MAAM,MAAM,UAAU,GAClB,QAAQ,CAAC,oBAAoB,GAC7B,QAAQ,CAAC,wBAAwB,GACjC,QAAQ,CAAC,sBAAsB,CAAC;AAEpC,qBAAa,aAAc,SAAQ,OAAO;;gBAI5B,IAAI,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAMpD,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,GAAG,IAAI;IAK5D,SAAS,CAAC,wBAAwB,CAChC,IAAI,EAAE,QAAQ,CAAC,wBAAwB,GACtC,IAAI;IAaP,SAAS,CAAC,sBAAsB,CAC9B,IAAI,EAAE,QAAQ,CAAC,sBAAsB,GACpC,IAAI;IAgBP,SAAS,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,eAAe,GAAG,IAAI;IAgB/D,SAAS,CAAC,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI;CAStD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/ExportVisitor.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ExportVisitor.js new file mode 100644 index 00000000..3e089e6b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ExportVisitor.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExportVisitor = void 0; +const types_1 = require("@typescript-eslint/types"); +const Visitor_1 = require("./Visitor"); +class ExportVisitor extends Visitor_1.Visitor { + #exportNode; + #referencer; + constructor(node, referencer) { + super(referencer); + this.#exportNode = node; + this.#referencer = referencer; + } + static visit(referencer, node) { + const exportReferencer = new ExportVisitor(node, referencer); + exportReferencer.visit(node); + } + ExportDefaultDeclaration(node) { + if (node.declaration.type === types_1.AST_NODE_TYPES.Identifier) { + // export default A; + // this could be a type or a variable + this.visit(node.declaration); + } + else { + // export const a = 1; + // export something(); + // etc + // these not included in the scope of this visitor as they are all guaranteed to be values or declare variables + } + } + ExportNamedDeclaration(node) { + if (node.source) { + // export ... from 'foo'; + // these are external identifiers so there shouldn't be references or defs + return; + } + if (!node.declaration) { + // export { x }; + this.visitChildren(node); + } + else { + // export const x = 1; + // this is not included in the scope of this visitor as it creates a variable + } + } + ExportSpecifier(node) { + if (node.exportKind === 'type' && + node.local.type === types_1.AST_NODE_TYPES.Identifier) { + // export { type T }; + // type exports can only reference types + // + // we can't let this fall through to the Identifier selector because the exportKind is on this node + // and we don't have access to the `.parent` during scope analysis + this.#referencer.currentScope().referenceType(node.local); + } + else { + this.visit(node.local); + } + } + Identifier(node) { + if (this.#exportNode.exportKind === 'type') { + // export type { T }; + // type exports can only reference types + this.#referencer.currentScope().referenceType(node); + } + else { + this.#referencer.currentScope().referenceDualValueType(node); + } + } +} +exports.ExportVisitor = ExportVisitor; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/ImportVisitor.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ImportVisitor.d.ts new file mode 100644 index 00000000..4768b550 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ImportVisitor.d.ts @@ -0,0 +1,13 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { Referencer } from './Referencer'; +import { Visitor } from './Visitor'; +export declare class ImportVisitor extends Visitor { + #private; + constructor(declaration: TSESTree.ImportDeclaration, referencer: Referencer); + static visit(referencer: Referencer, declaration: TSESTree.ImportDeclaration): void; + protected ImportDefaultSpecifier(node: TSESTree.ImportDefaultSpecifier): void; + protected ImportNamespaceSpecifier(node: TSESTree.ImportNamespaceSpecifier): void; + protected ImportSpecifier(node: TSESTree.ImportSpecifier): void; + protected visitImport(id: TSESTree.Identifier, specifier: TSESTree.ImportDefaultSpecifier | TSESTree.ImportNamespaceSpecifier | TSESTree.ImportSpecifier): void; +} +//# sourceMappingURL=ImportVisitor.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/ImportVisitor.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ImportVisitor.d.ts.map new file mode 100644 index 00000000..44ec7b54 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ImportVisitor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ImportVisitor.d.ts","sourceRoot":"","sources":["../../src/referencer/ImportVisitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG/C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,qBAAa,aAAc,SAAQ,OAAO;;gBAI5B,WAAW,EAAE,QAAQ,CAAC,iBAAiB,EAAE,UAAU,EAAE,UAAU;IAM3E,MAAM,CAAC,KAAK,CACV,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,QAAQ,CAAC,iBAAiB,GACtC,IAAI;IAKP,SAAS,CAAC,sBAAsB,CAC9B,IAAI,EAAE,QAAQ,CAAC,sBAAsB,GACpC,IAAI;IAKP,SAAS,CAAC,wBAAwB,CAChC,IAAI,EAAE,QAAQ,CAAC,wBAAwB,GACtC,IAAI;IAKP,SAAS,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,eAAe,GAAG,IAAI;IAK/D,SAAS,CAAC,WAAW,CACnB,EAAE,EAAE,QAAQ,CAAC,UAAU,EACvB,SAAS,EACL,QAAQ,CAAC,sBAAsB,GAC/B,QAAQ,CAAC,wBAAwB,GACjC,QAAQ,CAAC,eAAe,GAC3B,IAAI;CAQR"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/ImportVisitor.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ImportVisitor.js new file mode 100644 index 00000000..67a00f36 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/ImportVisitor.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ImportVisitor = void 0; +const definition_1 = require("../definition"); +const Visitor_1 = require("./Visitor"); +class ImportVisitor extends Visitor_1.Visitor { + #declaration; + #referencer; + constructor(declaration, referencer) { + super(referencer); + this.#declaration = declaration; + this.#referencer = referencer; + } + static visit(referencer, declaration) { + const importReferencer = new ImportVisitor(declaration, referencer); + importReferencer.visit(declaration); + } + ImportDefaultSpecifier(node) { + const local = node.local; + this.visitImport(local, node); + } + ImportNamespaceSpecifier(node) { + const local = node.local; + this.visitImport(local, node); + } + ImportSpecifier(node) { + const local = node.local; + this.visitImport(local, node); + } + visitImport(id, specifier) { + this.#referencer + .currentScope() + .defineIdentifier(id, new definition_1.ImportBindingDefinition(id, specifier, this.#declaration)); + } +} +exports.ImportVisitor = ImportVisitor; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/PatternVisitor.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/PatternVisitor.d.ts new file mode 100644 index 00000000..6a0a4eb3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/PatternVisitor.d.ts @@ -0,0 +1,28 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { VisitorOptions } from './VisitorBase'; +import { VisitorBase } from './VisitorBase'; +export type PatternVisitorCallback = (pattern: TSESTree.Identifier, info: { + assignments: (TSESTree.AssignmentExpression | TSESTree.AssignmentPattern)[]; + rest: boolean; + topLevel: boolean; +}) => void; +export type PatternVisitorOptions = VisitorOptions; +export declare class PatternVisitor extends VisitorBase { + #private; + readonly rightHandNodes: TSESTree.Node[]; + constructor(options: PatternVisitorOptions, rootPattern: TSESTree.Node, callback: PatternVisitorCallback); + static isPattern(node: TSESTree.Node): node is TSESTree.ArrayPattern | TSESTree.AssignmentPattern | TSESTree.Identifier | TSESTree.ObjectPattern | TSESTree.RestElement | TSESTree.SpreadElement; + protected ArrayExpression(node: TSESTree.ArrayExpression): void; + protected ArrayPattern(pattern: TSESTree.ArrayPattern): void; + protected AssignmentExpression(node: TSESTree.AssignmentExpression): void; + protected AssignmentPattern(pattern: TSESTree.AssignmentPattern): void; + protected CallExpression(node: TSESTree.CallExpression): void; + protected Decorator(): void; + protected Identifier(pattern: TSESTree.Identifier): void; + protected MemberExpression(node: TSESTree.MemberExpression): void; + protected Property(property: TSESTree.Property): void; + protected RestElement(pattern: TSESTree.RestElement): void; + protected SpreadElement(node: TSESTree.SpreadElement): void; + protected TSTypeAnnotation(): void; +} +//# sourceMappingURL=PatternVisitor.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/PatternVisitor.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/PatternVisitor.d.ts.map new file mode 100644 index 00000000..2d0fb568 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/PatternVisitor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PatternVisitor.d.ts","sourceRoot":"","sources":["../../src/referencer/PatternVisitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,MAAM,MAAM,sBAAsB,GAAG,CACnC,OAAO,EAAE,QAAQ,CAAC,UAAU,EAC5B,IAAI,EAAE;IACJ,WAAW,EAAE,CAAC,QAAQ,CAAC,oBAAoB,GAAG,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC;IAC5E,IAAI,EAAE,OAAO,CAAC;IACd,QAAQ,EAAE,OAAO,CAAC;CACnB,KACE,IAAI,CAAC;AAEV,MAAM,MAAM,qBAAqB,GAAG,cAAc,CAAC;AACnD,qBAAa,cAAe,SAAQ,WAAW;;IAS7C,SAAgB,cAAc,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAM;gBAGnD,OAAO,EAAE,qBAAqB,EAC9B,WAAW,EAAE,QAAQ,CAAC,IAAI,EAC1B,QAAQ,EAAE,sBAAsB;WAOpB,SAAS,CACrB,IAAI,EAAE,QAAQ,CAAC,IAAI,GAClB,IAAI,IACH,QAAQ,CAAC,YAAY,GACrB,QAAQ,CAAC,iBAAiB,GAC1B,QAAQ,CAAC,UAAU,GACnB,QAAQ,CAAC,aAAa,GACtB,QAAQ,CAAC,WAAW,GACpB,QAAQ,CAAC,aAAa;IAa1B,SAAS,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,eAAe,GAAG,IAAI;IAI/D,SAAS,CAAC,YAAY,CAAC,OAAO,EAAE,QAAQ,CAAC,YAAY,GAAG,IAAI;IAM5D,SAAS,CAAC,oBAAoB,CAAC,IAAI,EAAE,QAAQ,CAAC,oBAAoB,GAAG,IAAI;IAOzE,SAAS,CAAC,iBAAiB,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,GAAG,IAAI;IAOtE,SAAS,CAAC,cAAc,CAAC,IAAI,EAAE,QAAQ,CAAC,cAAc,GAAG,IAAI;IAQ7D,SAAS,CAAC,SAAS,IAAI,IAAI;IAI3B,SAAS,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI;IAUxD,SAAS,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,gBAAgB,GAAG,IAAI;IAUjE,SAAS,CAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,GAAG,IAAI;IAYrD,SAAS,CAAC,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC,WAAW,GAAG,IAAI;IAM1D,SAAS,CAAC,aAAa,CAAC,IAAI,EAAE,QAAQ,CAAC,aAAa,GAAG,IAAI;IAI3D,SAAS,CAAC,gBAAgB,IAAI,IAAI;CAGnC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/PatternVisitor.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/PatternVisitor.js new file mode 100644 index 00000000..c7cab649 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/PatternVisitor.js @@ -0,0 +1,94 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PatternVisitor = void 0; +const types_1 = require("@typescript-eslint/types"); +const VisitorBase_1 = require("./VisitorBase"); +class PatternVisitor extends VisitorBase_1.VisitorBase { + #assignments = []; + #callback; + #restElements = []; + #rootPattern; + rightHandNodes = []; + constructor(options, rootPattern, callback) { + super(options); + this.#rootPattern = rootPattern; + this.#callback = callback; + } + static isPattern(node) { + const nodeType = node.type; + return (nodeType === types_1.AST_NODE_TYPES.Identifier || + nodeType === types_1.AST_NODE_TYPES.ObjectPattern || + nodeType === types_1.AST_NODE_TYPES.ArrayPattern || + nodeType === types_1.AST_NODE_TYPES.SpreadElement || + nodeType === types_1.AST_NODE_TYPES.RestElement || + nodeType === types_1.AST_NODE_TYPES.AssignmentPattern); + } + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } + ArrayPattern(pattern) { + for (const element of pattern.elements) { + this.visit(element); + } + } + AssignmentExpression(node) { + this.#assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.#assignments.pop(); + } + AssignmentPattern(pattern) { + this.#assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.#assignments.pop(); + } + CallExpression(node) { + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } + Decorator() { + // don't visit any decorators when exploring a pattern + } + Identifier(pattern) { + const lastRestElement = this.#restElements.at(-1); + this.#callback(pattern, { + assignments: this.#assignments, + rest: lastRestElement?.argument === pattern, + topLevel: pattern === this.#rootPattern, + }); + } + MemberExpression(node) { + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } + Property(property) { + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); + } + RestElement(pattern) { + this.#restElements.push(pattern); + this.visit(pattern.argument); + this.#restElements.pop(); + } + SpreadElement(node) { + this.visit(node.argument); + } + TSTypeAnnotation() { + // we don't want to visit types + } +} +exports.PatternVisitor = PatternVisitor; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/Reference.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Reference.d.ts new file mode 100644 index 00000000..97cacb40 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Reference.d.ts @@ -0,0 +1,88 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { Scope } from '../scope'; +import type { Variable } from '../variable'; +export declare enum ReferenceFlag { + Read = 1, + Write = 2, + ReadWrite = 3 +} +export interface ReferenceImplicitGlobal { + node: TSESTree.Node; + pattern: TSESTree.BindingName; + ref?: Reference; +} +export declare enum ReferenceTypeFlag { + Value = 1, + Type = 2 +} +/** + * A Reference represents a single occurrence of an identifier in code. + */ +export declare class Reference { + #private; + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + readonly $id: number; + /** + * Reference to the enclosing Scope. + * @public + */ + readonly from: Scope; + /** + * Identifier syntax node. + * @public + */ + readonly identifier: TSESTree.Identifier | TSESTree.JSXIdentifier; + /** + * `true` if this writing reference is a variable initializer or a default value. + * @public + */ + readonly init?: boolean; + readonly maybeImplicitGlobal?: ReferenceImplicitGlobal | null; + /** + * The {@link Variable} object that this reference refers to. If such variable was not defined, this is `null`. + * @public + */ + resolved: Variable | null; + /** + * If reference is writeable, this is the node being written to it. + * @public + */ + readonly writeExpr?: TSESTree.Node | null; + constructor(identifier: TSESTree.Identifier | TSESTree.JSXIdentifier, scope: Scope, flag: ReferenceFlag, writeExpr?: TSESTree.Node | null, maybeImplicitGlobal?: ReferenceImplicitGlobal | null, init?: boolean, referenceType?: ReferenceTypeFlag); + /** + * True if this reference can reference types + */ + get isTypeReference(): boolean; + /** + * True if this reference can reference values + */ + get isValueReference(): boolean; + /** + * Whether the reference is writeable. + * @public + */ + isWrite(): boolean; + /** + * Whether the reference is readable. + * @public + */ + isRead(): boolean; + /** + * Whether the reference is read-only. + * @public + */ + isReadOnly(): boolean; + /** + * Whether the reference is write-only. + * @public + */ + isWriteOnly(): boolean; + /** + * Whether the reference is read-write. + * @public + */ + isReadWrite(): boolean; +} +//# sourceMappingURL=Reference.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/Reference.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Reference.d.ts.map new file mode 100644 index 00000000..e8239bd9 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Reference.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Reference.d.ts","sourceRoot":"","sources":["../../src/referencer/Reference.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAI5C,oBAAY,aAAa;IACvB,IAAI,IAAM;IACV,KAAK,IAAM;IACX,SAAS,IAAM;CAChB;AAED,MAAM,WAAW,uBAAuB;IACtC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC;IACpB,OAAO,EAAE,QAAQ,CAAC,WAAW,CAAC;IAC9B,GAAG,CAAC,EAAE,SAAS,CAAC;CACjB;AAID,oBAAY,iBAAiB;IAC3B,KAAK,IAAM;IACX,IAAI,IAAM;CACX;AAED;;GAEG;AACH,qBAAa,SAAS;;IACpB;;OAEG;IACH,SAAgB,GAAG,EAAE,MAAM,CAAe;IAO1C;;;OAGG;IACH,SAAgB,IAAI,EAAE,KAAK,CAAC;IAE5B;;;OAGG;IACH,SAAgB,UAAU,EAAE,QAAQ,CAAC,UAAU,GAAG,QAAQ,CAAC,aAAa,CAAC;IAEzE;;;OAGG;IACH,SAAgB,IAAI,CAAC,EAAE,OAAO,CAAC;IAE/B,SAAgB,mBAAmB,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAErE;;;OAGG;IACI,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAEjC;;;OAGG;IACH,SAAgB,SAAS,CAAC,EAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC;gBAQ/C,UAAU,EAAE,QAAQ,CAAC,UAAU,GAAG,QAAQ,CAAC,aAAa,EACxD,KAAK,EAAE,KAAK,EACZ,IAAI,EAAE,aAAa,EACnB,SAAS,CAAC,EAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,EAChC,mBAAmB,CAAC,EAAE,uBAAuB,GAAG,IAAI,EACpD,IAAI,CAAC,EAAE,OAAO,EACd,aAAa,oBAA0B;IAgBzC;;OAEG;IACH,IAAW,eAAe,IAAI,OAAO,CAEpC;IAED;;OAEG;IACH,IAAW,gBAAgB,IAAI,OAAO,CAErC;IAED;;;OAGG;IACI,OAAO,IAAI,OAAO;IAIzB;;;OAGG;IACI,MAAM,IAAI,OAAO;IAIxB;;;OAGG;IACI,UAAU,IAAI,OAAO;IAI5B;;;OAGG;IACI,WAAW,IAAI,OAAO;IAI7B;;;OAGG;IACI,WAAW,IAAI,OAAO;CAG9B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/Reference.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Reference.js new file mode 100644 index 00000000..49ceac7f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Reference.js @@ -0,0 +1,119 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Reference = exports.ReferenceTypeFlag = exports.ReferenceFlag = void 0; +const ID_1 = require("../ID"); +var ReferenceFlag; +(function (ReferenceFlag) { + ReferenceFlag[ReferenceFlag["Read"] = 1] = "Read"; + ReferenceFlag[ReferenceFlag["Write"] = 2] = "Write"; + ReferenceFlag[ReferenceFlag["ReadWrite"] = 3] = "ReadWrite"; +})(ReferenceFlag || (exports.ReferenceFlag = ReferenceFlag = {})); +const generator = (0, ID_1.createIdGenerator)(); +var ReferenceTypeFlag; +(function (ReferenceTypeFlag) { + ReferenceTypeFlag[ReferenceTypeFlag["Value"] = 1] = "Value"; + ReferenceTypeFlag[ReferenceTypeFlag["Type"] = 2] = "Type"; +})(ReferenceTypeFlag || (exports.ReferenceTypeFlag = ReferenceTypeFlag = {})); +/** + * A Reference represents a single occurrence of an identifier in code. + */ +class Reference { + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + $id = generator(); + /** + * The read-write mode of the reference. + */ + #flag; + /** + * Reference to the enclosing Scope. + * @public + */ + from; + /** + * Identifier syntax node. + * @public + */ + identifier; + /** + * `true` if this writing reference is a variable initializer or a default value. + * @public + */ + init; + maybeImplicitGlobal; + /** + * The {@link Variable} object that this reference refers to. If such variable was not defined, this is `null`. + * @public + */ + resolved; + /** + * If reference is writeable, this is the node being written to it. + * @public + */ + writeExpr; + /** + * In some cases, a reference may be a type, value or both a type and value reference. + */ + #referenceType; + constructor(identifier, scope, flag, writeExpr, maybeImplicitGlobal, init, referenceType = ReferenceTypeFlag.Value) { + this.identifier = identifier; + this.from = scope; + this.resolved = null; + this.#flag = flag; + if (this.isWrite()) { + this.writeExpr = writeExpr; + this.init = init; + } + this.maybeImplicitGlobal = maybeImplicitGlobal; + this.#referenceType = referenceType; + } + /** + * True if this reference can reference types + */ + get isTypeReference() { + return (this.#referenceType & ReferenceTypeFlag.Type) !== 0; + } + /** + * True if this reference can reference values + */ + get isValueReference() { + return (this.#referenceType & ReferenceTypeFlag.Value) !== 0; + } + /** + * Whether the reference is writeable. + * @public + */ + isWrite() { + return !!(this.#flag & ReferenceFlag.Write); + } + /** + * Whether the reference is readable. + * @public + */ + isRead() { + return !!(this.#flag & ReferenceFlag.Read); + } + /** + * Whether the reference is read-only. + * @public + */ + isReadOnly() { + return this.#flag === ReferenceFlag.Read; + } + /** + * Whether the reference is write-only. + * @public + */ + isWriteOnly() { + return this.#flag === ReferenceFlag.Write; + } + /** + * Whether the reference is read-write. + * @public + */ + isReadWrite() { + return this.#flag === ReferenceFlag.ReadWrite; + } +} +exports.Reference = Reference; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.d.ts new file mode 100644 index 00000000..2703d423 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.d.ts @@ -0,0 +1,87 @@ +import type { Lib, TSESTree } from '@typescript-eslint/types'; +import type { Scope } from '../scope'; +import type { ScopeManager } from '../ScopeManager'; +import type { ReferenceImplicitGlobal } from './Reference'; +import type { VisitorOptions } from './Visitor'; +import { Visitor } from './Visitor'; +export interface ReferencerOptions extends VisitorOptions { + jsxFragmentName: string | null; + jsxPragma: string | null; + lib: Lib[]; +} +export declare class Referencer extends Visitor { + #private; + readonly scopeManager: ScopeManager; + constructor(options: ReferencerOptions, scopeManager: ScopeManager); + private populateGlobalsFromLib; + close(node: TSESTree.Node): void; + currentScope(): Scope; + currentScope(throwOnNull: true): Scope | null; + referencingDefaultValue(pattern: TSESTree.Identifier, assignments: (TSESTree.AssignmentExpression | TSESTree.AssignmentPattern)[], maybeImplicitGlobal: ReferenceImplicitGlobal | null, init: boolean): void; + /** + * Searches for a variable named "name" in the upper scopes and adds a pseudo-reference from itself to itself + */ + private referenceInSomeUpperScope; + private referenceJsxFragment; + private referenceJsxPragma; + protected visitClass(node: TSESTree.ClassDeclaration | TSESTree.ClassExpression): void; + protected visitForIn(node: TSESTree.ForInStatement | TSESTree.ForOfStatement): void; + protected visitFunction(node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.TSDeclareFunction | TSESTree.TSEmptyBodyFunctionExpression): void; + protected visitFunctionParameterTypeAnnotation(node: TSESTree.Parameter): void; + protected visitJSXElement(node: TSESTree.JSXClosingElement | TSESTree.JSXOpeningElement): void; + protected visitProperty(node: TSESTree.Property): void; + protected visitType(node: TSESTree.Node | null | undefined): void; + protected visitTypeAssertion(node: TSESTree.TSAsExpression | TSESTree.TSSatisfiesExpression | TSESTree.TSTypeAssertion): void; + protected ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression): void; + protected AssignmentExpression(node: TSESTree.AssignmentExpression): void; + protected BlockStatement(node: TSESTree.BlockStatement): void; + protected BreakStatement(): void; + protected CallExpression(node: TSESTree.CallExpression): void; + protected CatchClause(node: TSESTree.CatchClause): void; + protected ClassDeclaration(node: TSESTree.ClassDeclaration): void; + protected ClassExpression(node: TSESTree.ClassExpression): void; + protected ContinueStatement(): void; + protected ExportAllDeclaration(): void; + protected ExportDefaultDeclaration(node: TSESTree.ExportDefaultDeclaration): void; + protected ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration): void; + protected ForInStatement(node: TSESTree.ForInStatement): void; + protected ForOfStatement(node: TSESTree.ForOfStatement): void; + protected ForStatement(node: TSESTree.ForStatement): void; + protected FunctionDeclaration(node: TSESTree.FunctionDeclaration): void; + protected FunctionExpression(node: TSESTree.FunctionExpression): void; + protected Identifier(node: TSESTree.Identifier): void; + protected ImportAttribute(): void; + protected ImportDeclaration(node: TSESTree.ImportDeclaration): void; + protected JSXAttribute(node: TSESTree.JSXAttribute): void; + protected JSXClosingElement(node: TSESTree.JSXClosingElement): void; + protected JSXFragment(node: TSESTree.JSXFragment): void; + protected JSXIdentifier(node: TSESTree.JSXIdentifier): void; + protected JSXMemberExpression(node: TSESTree.JSXMemberExpression): void; + protected JSXOpeningElement(node: TSESTree.JSXOpeningElement): void; + protected LabeledStatement(node: TSESTree.LabeledStatement): void; + protected MemberExpression(node: TSESTree.MemberExpression): void; + protected MetaProperty(): void; + protected NewExpression(node: TSESTree.NewExpression): void; + protected PrivateIdentifier(): void; + protected Program(node: TSESTree.Program): void; + protected Property(node: TSESTree.Property): void; + protected SwitchStatement(node: TSESTree.SwitchStatement): void; + protected TaggedTemplateExpression(node: TSESTree.TaggedTemplateExpression): void; + protected TSAsExpression(node: TSESTree.TSAsExpression): void; + protected TSDeclareFunction(node: TSESTree.TSDeclareFunction): void; + protected TSEmptyBodyFunctionExpression(node: TSESTree.TSEmptyBodyFunctionExpression): void; + protected TSEnumDeclaration(node: TSESTree.TSEnumDeclaration): void; + protected TSExportAssignment(node: TSESTree.TSExportAssignment): void; + protected TSImportEqualsDeclaration(node: TSESTree.TSImportEqualsDeclaration): void; + protected TSInstantiationExpression(node: TSESTree.TSInstantiationExpression): void; + protected TSInterfaceDeclaration(node: TSESTree.TSInterfaceDeclaration): void; + protected TSModuleDeclaration(node: TSESTree.TSModuleDeclaration): void; + protected TSSatisfiesExpression(node: TSESTree.TSSatisfiesExpression): void; + protected TSTypeAliasDeclaration(node: TSESTree.TSTypeAliasDeclaration): void; + protected TSTypeAssertion(node: TSESTree.TSTypeAssertion): void; + protected UpdateExpression(node: TSESTree.UpdateExpression): void; + protected VariableDeclaration(node: TSESTree.VariableDeclaration): void; + protected WithStatement(node: TSESTree.WithStatement): void; + private visitExpressionTarget; +} +//# sourceMappingURL=Referencer.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.d.ts.map new file mode 100644 index 00000000..6512a6b8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Referencer.d.ts","sourceRoot":"","sources":["../../src/referencer/Referencer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAI9D,OAAO,KAAK,EAAe,KAAK,EAAE,MAAM,UAAU,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,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AE,QAAQ,CAAC,qBAAqB,GAAG,IAAI;IAI3E,SAAS,CAAC,sBAAsB,CAC9B,IAAI,EAAE,QAAQ,CAAC,sBAAsB,GACpC,IAAI;IAIP,SAAS,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,eAAe,GAAG,IAAI;IAI/D,SAAS,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,gBAAgB,GAAG,IAAI;IAgBjE,SAAS,CAAC,mBAAmB,CAAC,IAAI,EAAE,QAAQ,CAAC,mBAAmB,GAAG,IAAI;IAoCvE,SAAS,CAAC,aAAa,CAAC,IAAI,EAAE,QAAQ,CAAC,aAAa,GAAG,IAAI;IAW3D,OAAO,CAAC,qBAAqB;CAc9B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.js new file mode 100644 index 00000000..0d4f62f2 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.js @@ -0,0 +1,552 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Referencer = void 0; +const types_1 = require("@typescript-eslint/types"); +const assert_1 = require("../assert"); +const definition_1 = require("../definition"); +const lib_1 = require("../lib"); +const ClassVisitor_1 = require("./ClassVisitor"); +const ExportVisitor_1 = require("./ExportVisitor"); +const ImportVisitor_1 = require("./ImportVisitor"); +const PatternVisitor_1 = require("./PatternVisitor"); +const Reference_1 = require("./Reference"); +const TypeVisitor_1 = require("./TypeVisitor"); +const Visitor_1 = require("./Visitor"); +// Referencing variables and creating bindings. +class Referencer extends Visitor_1.Visitor { + #hasReferencedJsxFactory = false; + #hasReferencedJsxFragmentFactory = false; + #jsxFragmentName; + #jsxPragma; + #lib; + scopeManager; + constructor(options, scopeManager) { + super(options); + this.scopeManager = scopeManager; + this.#jsxPragma = options.jsxPragma; + this.#jsxFragmentName = options.jsxFragmentName; + this.#lib = options.lib; + } + populateGlobalsFromLib(globalScope) { + const flattenedLibs = new Set(); + for (const lib of this.#lib) { + const definition = lib_1.lib.get(lib); + if (!definition) { + throw new Error(`Invalid value for lib provided: ${lib}`); + } + flattenedLibs.add(definition); + } + // Flatten and deduplicate the set of included libs + for (const lib of flattenedLibs) { + // By adding the dependencies to the set as we iterate it, + // they get iterated only if they are new + for (const referencedLib of lib.libs) { + flattenedLibs.add(referencedLib); + } + // This loop is guaranteed to see each included lib exactly once + for (const [name, variable] of lib.variables) { + globalScope.defineImplicitVariable(name, variable); + } + } + // for const assertions (`{} as const` / `{}`) + globalScope.defineImplicitVariable('const', { + eslintImplicitGlobalSetting: 'readonly', + isTypeVariable: true, + isValueVariable: false, + }); + } + close(node) { + while (this.currentScope(true) && node === this.currentScope().block) { + this.scopeManager.currentScope = this.currentScope().close(this.scopeManager); + } + } + currentScope(dontThrowOnNull) { + if (!dontThrowOnNull) { + (0, assert_1.assert)(this.scopeManager.currentScope, 'aaa'); + } + return this.scopeManager.currentScope; + } + referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + assignments.forEach(assignment => { + this.currentScope().referenceValue(pattern, Reference_1.ReferenceFlag.Write, assignment.right, maybeImplicitGlobal, init); + }); + } + /** + * Searches for a variable named "name" in the upper scopes and adds a pseudo-reference from itself to itself + */ + referenceInSomeUpperScope(name) { + let scope = this.scopeManager.currentScope; + while (scope) { + const variable = scope.set.get(name); + if (!variable) { + scope = scope.upper; + continue; + } + scope.referenceValue(variable.identifiers[0]); + return true; + } + return false; + } + referenceJsxFragment() { + if (this.#jsxFragmentName == null || + this.#hasReferencedJsxFragmentFactory) { + return; + } + this.#hasReferencedJsxFragmentFactory = this.referenceInSomeUpperScope(this.#jsxFragmentName); + } + referenceJsxPragma() { + if (this.#jsxPragma == null || this.#hasReferencedJsxFactory) { + return; + } + this.#hasReferencedJsxFactory = this.referenceInSomeUpperScope(this.#jsxPragma); + } + /////////////////// + // Visit helpers // + /////////////////// + visitClass(node) { + ClassVisitor_1.ClassVisitor.visit(this, node); + } + visitForIn(node) { + if (node.left.type === types_1.AST_NODE_TYPES.VariableDeclaration && + node.left.kind !== 'var') { + this.scopeManager.nestForScope(node); + } + if (node.left.type === types_1.AST_NODE_TYPES.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, pattern => { + this.currentScope().referenceValue(pattern, Reference_1.ReferenceFlag.Write, node.right, null, true); + }); + } + else { + this.visitPattern(node.left, (pattern, info) => { + const maybeImplicitGlobal = !this.currentScope().isStrict + ? { + node, + pattern, + } + : null; + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().referenceValue(pattern, Reference_1.ReferenceFlag.Write, node.right, maybeImplicitGlobal, false); + }, { processRightHandNodes: true }); + } + this.visit(node.right); + this.visit(node.body); + this.close(node); + } + visitFunction(node) { + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. + if (node.type === types_1.AST_NODE_TYPES.FunctionExpression) { + if (node.id) { + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + this.scopeManager.nestFunctionExpressionNameScope(node); + } + } + else if (node.id) { + // id is defined in upper scope + this.currentScope().defineIdentifier(node.id, new definition_1.FunctionNameDefinition(node.id, node)); + } + // Consider this function is in the MethodDefinition. + this.scopeManager.nestFunctionScope(node, false); + // Process parameter declarations. + for (const param of node.params) { + this.visitPattern(param, (pattern, info) => { + this.currentScope().defineIdentifier(pattern, new definition_1.ParameterDefinition(pattern, node, info.rest)); + this.referencingDefaultValue(pattern, info.assignments, null, true); + }, { processRightHandNodes: true }); + this.visitFunctionParameterTypeAnnotation(param); + param.decorators.forEach(d => this.visit(d)); + } + this.visitType(node.returnType); + this.visitType(node.typeParameters); + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === types_1.AST_NODE_TYPES.BlockStatement) { + this.visitChildren(node.body); + } + else { + this.visit(node.body); + } + } + this.close(node); + } + visitFunctionParameterTypeAnnotation(node) { + switch (node.type) { + case types_1.AST_NODE_TYPES.AssignmentPattern: + this.visitType(node.left.typeAnnotation); + break; + case types_1.AST_NODE_TYPES.TSParameterProperty: + this.visitFunctionParameterTypeAnnotation(node.parameter); + break; + default: + this.visitType(node.typeAnnotation); + break; + } + } + visitJSXElement(node) { + if (node.name.type === types_1.AST_NODE_TYPES.JSXIdentifier) { + if (node.name.name[0].toUpperCase() === node.name.name[0] || + node.name.name === 'this') { + // lower cased component names are always treated as "intrinsic" names, and are converted to a string, + // not a variable by JSX transforms: + //

=> React.createElement("div", null) + // the only case we want to visit a lower-cased component has its name as "this", + this.visit(node.name); + } + } + else { + this.visit(node.name); + } + } + visitProperty(node) { + if (node.computed) { + this.visit(node.key); + } + this.visit(node.value); + } + visitType(node) { + if (!node) { + return; + } + TypeVisitor_1.TypeVisitor.visit(this, node); + } + visitTypeAssertion(node) { + this.visit(node.expression); + this.visitType(node.typeAnnotation); + } + ///////////////////// + // Visit selectors // + ///////////////////// + ArrowFunctionExpression(node) { + this.visitFunction(node); + } + AssignmentExpression(node) { + const left = this.visitExpressionTarget(node.left); + if (PatternVisitor_1.PatternVisitor.isPattern(left)) { + if (node.operator === '=') { + this.visitPattern(left, (pattern, info) => { + const maybeImplicitGlobal = !this.currentScope().isStrict + ? { + node, + pattern, + } + : null; + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().referenceValue(pattern, Reference_1.ReferenceFlag.Write, node.right, maybeImplicitGlobal, false); + }, { processRightHandNodes: true }); + } + else if (left.type === types_1.AST_NODE_TYPES.Identifier) { + this.currentScope().referenceValue(left, Reference_1.ReferenceFlag.ReadWrite, node.right); + } + } + else { + this.visit(left); + } + this.visit(node.right); + } + BlockStatement(node) { + this.scopeManager.nestBlockScope(node); + this.visitChildren(node); + this.close(node); + } + BreakStatement() { + // don't reference the break statement's label + } + CallExpression(node) { + this.visitChildren(node, ['typeArguments']); + this.visitType(node.typeArguments); + } + CatchClause(node) { + this.scopeManager.nestCatchScope(node); + if (node.param) { + const param = node.param; + this.visitPattern(param, (pattern, info) => { + this.currentScope().defineIdentifier(pattern, new definition_1.CatchClauseDefinition(param, node)); + this.referencingDefaultValue(pattern, info.assignments, null, true); + }, { processRightHandNodes: true }); + } + this.visit(node.body); + this.close(node); + } + ClassDeclaration(node) { + this.visitClass(node); + } + ClassExpression(node) { + this.visitClass(node); + } + ContinueStatement() { + // don't reference the continue statement's label + } + ExportAllDeclaration() { + // this defines no local variables + } + ExportDefaultDeclaration(node) { + if (node.declaration.type === types_1.AST_NODE_TYPES.Identifier) { + ExportVisitor_1.ExportVisitor.visit(this, node); + } + else { + this.visit(node.declaration); + } + } + ExportNamedDeclaration(node) { + if (node.declaration) { + this.visit(node.declaration); + } + else { + ExportVisitor_1.ExportVisitor.visit(this, node); + } + } + ForInStatement(node) { + this.visitForIn(node); + } + ForOfStatement(node) { + this.visitForIn(node); + } + ForStatement(node) { + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates per iteration environment. However, this is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && + node.init.type === types_1.AST_NODE_TYPES.VariableDeclaration && + node.init.kind !== 'var') { + this.scopeManager.nestForScope(node); + } + this.visitChildren(node); + this.close(node); + } + FunctionDeclaration(node) { + this.visitFunction(node); + } + FunctionExpression(node) { + this.visitFunction(node); + } + Identifier(node) { + this.currentScope().referenceValue(node); + this.visitType(node.typeAnnotation); + } + ImportAttribute() { + // import assertions are module metadata and thus have no variables to reference + } + ImportDeclaration(node) { + (0, assert_1.assert)(this.scopeManager.isModule(), 'ImportDeclaration should appear when the mode is ES6 and in the module context.'); + ImportVisitor_1.ImportVisitor.visit(this, node); + } + JSXAttribute(node) { + this.visit(node.value); + } + JSXClosingElement(node) { + this.visitJSXElement(node); + } + JSXFragment(node) { + this.referenceJsxPragma(); + this.referenceJsxFragment(); + this.visitChildren(node); + } + JSXIdentifier(node) { + this.currentScope().referenceValue(node); + } + JSXMemberExpression(node) { + if (node.object.type !== types_1.AST_NODE_TYPES.JSXIdentifier || + node.object.name !== 'this') { + this.visit(node.object); + } + // we don't ever reference the property as it's always going to be a property on the thing + } + JSXOpeningElement(node) { + this.referenceJsxPragma(); + this.visitJSXElement(node); + this.visitType(node.typeArguments); + for (const attr of node.attributes) { + this.visit(attr); + } + } + LabeledStatement(node) { + this.visit(node.body); + } + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + MetaProperty() { + // meta properties all builtin globals + } + NewExpression(node) { + this.visitChildren(node, ['typeArguments']); + this.visitType(node.typeArguments); + } + PrivateIdentifier() { + // private identifiers are members on classes and thus have no variables to reference + } + Program(node) { + const globalScope = this.scopeManager.nestGlobalScope(node); + this.populateGlobalsFromLib(globalScope); + if (this.scopeManager.isGlobalReturn()) { + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.nestFunctionScope(node, false); + } + if (this.scopeManager.isModule()) { + this.scopeManager.nestModuleScope(node); + } + if (this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; + } + this.visitChildren(node); + this.close(node); + } + Property(node) { + this.visitProperty(node); + } + SwitchStatement(node) { + this.visit(node.discriminant); + this.scopeManager.nestSwitchScope(node); + for (const switchCase of node.cases) { + this.visit(switchCase); + } + this.close(node); + } + TaggedTemplateExpression(node) { + this.visit(node.tag); + this.visit(node.quasi); + this.visitType(node.typeArguments); + } + TSAsExpression(node) { + this.visitTypeAssertion(node); + } + TSDeclareFunction(node) { + this.visitFunction(node); + } + TSEmptyBodyFunctionExpression(node) { + this.visitFunction(node); + } + TSEnumDeclaration(node) { + this.currentScope().defineIdentifier(node.id, new definition_1.TSEnumNameDefinition(node.id, node)); + // enum members can be referenced within the enum body + this.scopeManager.nestTSEnumScope(node); + for (const member of node.body.members) { + // TS resolves literal named members to be actual names + // enum Foo { + // 'a' = 1, + // b = a, // this references the 'a' member + // } + if (member.id.type === types_1.AST_NODE_TYPES.Literal && + typeof member.id.value === 'string') { + const name = member.id; + this.currentScope().defineLiteralIdentifier(name, new definition_1.TSEnumMemberDefinition(name, member)); + } + else if (!member.computed && + member.id.type === types_1.AST_NODE_TYPES.Identifier) { + this.currentScope().defineIdentifier(member.id, new definition_1.TSEnumMemberDefinition(member.id, member)); + } + this.visit(member.initializer); + } + this.close(node); + } + TSExportAssignment(node) { + if (node.expression.type === types_1.AST_NODE_TYPES.Identifier) { + // this is a special case - you can `export = T` where `T` is a type OR a + // value however `T[U]` is illegal when `T` is a type and `T.U` is illegal + // when `T.U` is a type + // i.e. if the expression is JUST an Identifier - it could be either ref + // kind; otherwise the standard rules apply + this.currentScope().referenceDualValueType(node.expression); + } + else { + this.visit(node.expression); + } + } + TSImportEqualsDeclaration(node) { + this.currentScope().defineIdentifier(node.id, new definition_1.ImportBindingDefinition(node.id, node, node)); + if (node.moduleReference.type === types_1.AST_NODE_TYPES.TSQualifiedName) { + let moduleIdentifier = node.moduleReference.left; + while (moduleIdentifier.type === types_1.AST_NODE_TYPES.TSQualifiedName) { + moduleIdentifier = moduleIdentifier.left; + } + this.visit(moduleIdentifier); + } + else { + this.visit(node.moduleReference); + } + } + TSInstantiationExpression(node) { + this.visitChildren(node, ['typeArguments']); + this.visitType(node.typeArguments); + } + TSInterfaceDeclaration(node) { + this.visitType(node); + } + TSModuleDeclaration(node) { + if (node.id.type === types_1.AST_NODE_TYPES.Identifier && node.kind !== 'global') { + this.currentScope().defineIdentifier(node.id, new definition_1.TSModuleNameDefinition(node.id, node)); + } + this.scopeManager.nestTSModuleScope(node); + this.visit(node.body); + this.close(node); + } + TSSatisfiesExpression(node) { + this.visitTypeAssertion(node); + } + TSTypeAliasDeclaration(node) { + this.visitType(node); + } + TSTypeAssertion(node) { + this.visitTypeAssertion(node); + } + UpdateExpression(node) { + const argument = this.visitExpressionTarget(node.argument); + if (PatternVisitor_1.PatternVisitor.isPattern(argument)) { + this.visitPattern(argument, pattern => { + this.currentScope().referenceValue(pattern, Reference_1.ReferenceFlag.ReadWrite, null); + }); + } + else { + this.visitChildren(node); + } + } + VariableDeclaration(node) { + const variableTargetScope = node.kind === 'var' + ? this.currentScope().variableScope + : this.currentScope(); + for (const decl of node.declarations) { + const init = decl.init; + this.visitPattern(decl.id, (pattern, info) => { + variableTargetScope.defineIdentifier(pattern, new definition_1.VariableDefinition(pattern, decl, node)); + this.referencingDefaultValue(pattern, info.assignments, null, true); + if (init) { + this.currentScope().referenceValue(pattern, Reference_1.ReferenceFlag.Write, init, null, true); + } + }, { processRightHandNodes: true }); + this.visit(decl.init); + this.visitType(decl.id.typeAnnotation); + } + } + WithStatement(node) { + this.visit(node.object); + // Then nest scope for WithStatement. + this.scopeManager.nestWithScope(node); + this.visit(node.body); + this.close(node); + } + visitExpressionTarget(left) { + switch (left.type) { + case types_1.AST_NODE_TYPES.TSAsExpression: + case types_1.AST_NODE_TYPES.TSTypeAssertion: + // explicitly visit the type annotation + this.visitType(left.typeAnnotation); + // intentional fallthrough + case types_1.AST_NODE_TYPES.TSNonNullExpression: + // unwrap the expression + left = left.expression; + } + return left; + } +} +exports.Referencer = Referencer; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/TypeVisitor.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/TypeVisitor.d.ts new file mode 100644 index 00000000..ee0e8c16 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/TypeVisitor.d.ts @@ -0,0 +1,32 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { Referencer } from './Referencer'; +import { Visitor } from './Visitor'; +export declare class TypeVisitor extends Visitor { + #private; + constructor(referencer: Referencer); + static visit(referencer: Referencer, node: TSESTree.Node): void; + protected visitFunctionType(node: TSESTree.TSCallSignatureDeclaration | TSESTree.TSConstructorType | TSESTree.TSConstructSignatureDeclaration | TSESTree.TSFunctionType | TSESTree.TSMethodSignature): void; + protected visitPropertyKey(node: TSESTree.TSMethodSignature | TSESTree.TSPropertySignature): void; + protected Identifier(node: TSESTree.Identifier): void; + protected MemberExpression(node: TSESTree.MemberExpression): void; + protected TSCallSignatureDeclaration(node: TSESTree.TSCallSignatureDeclaration): void; + protected TSConditionalType(node: TSESTree.TSConditionalType): void; + protected TSConstructorType(node: TSESTree.TSConstructorType): void; + protected TSConstructSignatureDeclaration(node: TSESTree.TSConstructSignatureDeclaration): void; + protected TSFunctionType(node: TSESTree.TSFunctionType): void; + protected TSImportType(node: TSESTree.TSImportType): void; + protected TSIndexSignature(node: TSESTree.TSIndexSignature): void; + protected TSInferType(node: TSESTree.TSInferType): void; + protected TSInterfaceDeclaration(node: TSESTree.TSInterfaceDeclaration): void; + protected TSMappedType(node: TSESTree.TSMappedType): void; + protected TSMethodSignature(node: TSESTree.TSMethodSignature): void; + protected TSNamedTupleMember(node: TSESTree.TSNamedTupleMember): void; + protected TSPropertySignature(node: TSESTree.TSPropertySignature): void; + protected TSQualifiedName(node: TSESTree.TSQualifiedName): void; + protected TSTypeAliasDeclaration(node: TSESTree.TSTypeAliasDeclaration): void; + protected TSTypeParameter(node: TSESTree.TSTypeParameter): void; + protected TSTypePredicate(node: TSESTree.TSTypePredicate): void; + protected TSTypeAnnotation(node: TSESTree.TSTypeAnnotation): void; + protected TSTypeQuery(node: TSESTree.TSTypeQuery): void; +} +//# sourceMappingURL=TypeVisitor.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/TypeVisitor.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/TypeVisitor.d.ts.map new file mode 100644 index 00000000..ae68524e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/TypeVisitor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TypeVisitor.d.ts","sourceRoot":"","sources":["../../src/referencer/TypeVisitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,E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AAC,IAAI,EAAE,QAAQ,CAAC,gBAAgB,GAAG,IAAI;IASjE,SAAS,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,WAAW,GAAG,IAAI;IAwCvD,SAAS,CAAC,sBAAsB,CAC9B,IAAI,EAAE,QAAQ,CAAC,sBAAsB,GACpC,IAAI;IAmBP,SAAS,CAAC,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,YAAY,GAAG,IAAI;IAYzD,SAAS,CAAC,iBAAiB,CAAC,IAAI,EAAE,QAAQ,CAAC,iBAAiB,GAAG,IAAI;IAKnE,SAAS,CAAC,kBAAkB,CAAC,IAAI,EAAE,QAAQ,CAAC,kBAAkB,GAAG,IAAI;IAKrE,SAAS,CAAC,mBAAmB,CAAC,IAAI,EAAE,QAAQ,CAAC,mBAAmB,GAAG,IAAI;IAKvE,SAAS,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,eAAe,GAAG,IAAI;IAK/D,SAAS,CAAC,sBAAsB,CAC9B,IAAI,EAAE,QAAQ,CAAC,sBAAsB,GACpC,IAAI;IAkBP,SAAS,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,eAAe,GAAG,IAAI;IAS/D,SAAS,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,eAAe,GAAG,IAAI;IAQ/D,SAAS,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,gBAAgB,GAAG,IAAI;IAKjE,SAAS,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,WAAW,GAAG,IAAI;CAwBxD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/TypeVisitor.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/TypeVisitor.js new file mode 100644 index 00000000..2509a4a9 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/TypeVisitor.js @@ -0,0 +1,221 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeVisitor = void 0; +const types_1 = require("@typescript-eslint/types"); +const definition_1 = require("../definition"); +const scope_1 = require("../scope"); +const Visitor_1 = require("./Visitor"); +class TypeVisitor extends Visitor_1.Visitor { + #referencer; + constructor(referencer) { + super(referencer); + this.#referencer = referencer; + } + static visit(referencer, node) { + const typeReferencer = new TypeVisitor(referencer); + typeReferencer.visit(node); + } + /////////////////// + // Visit helpers // + /////////////////// + visitFunctionType(node) { + // arguments and type parameters can only be referenced from within the function + this.#referencer.scopeManager.nestFunctionTypeScope(node); + this.visit(node.typeParameters); + for (const param of node.params) { + let didVisitAnnotation = false; + this.visitPattern(param, (pattern, info) => { + // a parameter name creates a value type variable which can be referenced later via typeof arg + this.#referencer + .currentScope() + .defineIdentifier(pattern, new definition_1.ParameterDefinition(pattern, node, info.rest)); + if (pattern.typeAnnotation) { + this.visit(pattern.typeAnnotation); + didVisitAnnotation = true; + } + }); + // there are a few special cases where the type annotation is owned by the parameter, not the pattern + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!didVisitAnnotation && 'typeAnnotation' in param) { + this.visit(param.typeAnnotation); + } + } + this.visit(node.returnType); + this.#referencer.close(node); + } + visitPropertyKey(node) { + if (!node.computed) { + return; + } + // computed members are treated as value references, and TS expects they have a literal type + this.#referencer.visit(node.key); + } + ///////////////////// + // Visit selectors // + ///////////////////// + Identifier(node) { + this.#referencer.currentScope().referenceType(node); + } + MemberExpression(node) { + this.visit(node.object); + // don't visit the property + } + TSCallSignatureDeclaration(node) { + this.visitFunctionType(node); + } + TSConditionalType(node) { + // conditional types can define inferred type parameters + // which are only accessible from inside the conditional parameter + this.#referencer.scopeManager.nestConditionalTypeScope(node); + // type parameters inferred in the condition clause are not accessible within the false branch + this.visitChildren(node, ['falseType']); + this.#referencer.close(node); + this.visit(node.falseType); + } + TSConstructorType(node) { + this.visitFunctionType(node); + } + TSConstructSignatureDeclaration(node) { + this.visitFunctionType(node); + } + TSFunctionType(node) { + this.visitFunctionType(node); + } + TSImportType(node) { + // the TS parser allows any type to be the parameter, but it's a syntax error - so we can ignore it + this.visit(node.typeArguments); + // the qualifier is just part of a standard EntityName, so it should not be visited + } + TSIndexSignature(node) { + for (const param of node.parameters) { + if (param.type === types_1.AST_NODE_TYPES.Identifier) { + this.visit(param.typeAnnotation); + } + } + this.visit(node.typeAnnotation); + } + TSInferType(node) { + const typeParameter = node.typeParameter; + let scope = this.#referencer.currentScope(); + /* + In cases where there is a sub-type scope created within a conditional type, then the generic should be defined in the + conditional type's scope, not the child type scope. + If we define it within the child type's scope then it won't be able to be referenced outside the child type + */ + if (scope.type === scope_1.ScopeType.functionType || + scope.type === scope_1.ScopeType.mappedType) { + // search up the scope tree to figure out if we're in a nested type scope + let currentScope = scope.upper; + while (currentScope) { + if (currentScope.type === scope_1.ScopeType.functionType || + currentScope.type === scope_1.ScopeType.mappedType) { + // ensure valid type parents only + currentScope = currentScope.upper; + continue; + } + if (currentScope.type === scope_1.ScopeType.conditionalType) { + scope = currentScope; + break; + } + break; + } + } + scope.defineIdentifier(typeParameter.name, new definition_1.TypeDefinition(typeParameter.name, typeParameter)); + this.visit(typeParameter.constraint); + } + TSInterfaceDeclaration(node) { + this.#referencer + .currentScope() + .defineIdentifier(node.id, new definition_1.TypeDefinition(node.id, node)); + if (node.typeParameters) { + // type parameters cannot be referenced from outside their current scope + this.#referencer.scopeManager.nestTypeScope(node); + this.visit(node.typeParameters); + } + node.extends.forEach(this.visit, this); + this.visit(node.body); + if (node.typeParameters) { + this.#referencer.close(node); + } + } + TSMappedType(node) { + // mapped types key can only be referenced within their return value + this.#referencer.scopeManager.nestMappedTypeScope(node); + this.#referencer + .currentScope() + .defineIdentifier(node.key, new definition_1.TypeDefinition(node.key, node)); + this.visit(node.constraint); + this.visit(node.nameType); + this.visit(node.typeAnnotation); + this.#referencer.close(node); + } + TSMethodSignature(node) { + this.visitPropertyKey(node); + this.visitFunctionType(node); + } + TSNamedTupleMember(node) { + this.visit(node.elementType); + // we don't visit the label as the label only exists for the purposes of documentation + } + TSPropertySignature(node) { + this.visitPropertyKey(node); + this.visit(node.typeAnnotation); + } + TSQualifiedName(node) { + this.visit(node.left); + // we don't visit the right as it a name on the thing, not a name to reference + } + TSTypeAliasDeclaration(node) { + this.#referencer + .currentScope() + .defineIdentifier(node.id, new definition_1.TypeDefinition(node.id, node)); + if (node.typeParameters) { + // type parameters cannot be referenced from outside their current scope + this.#referencer.scopeManager.nestTypeScope(node); + this.visit(node.typeParameters); + } + this.visit(node.typeAnnotation); + if (node.typeParameters) { + this.#referencer.close(node); + } + } + TSTypeParameter(node) { + this.#referencer + .currentScope() + .defineIdentifier(node.name, new definition_1.TypeDefinition(node.name, node)); + this.visit(node.constraint); + this.visit(node.default); + } + TSTypePredicate(node) { + if (node.parameterName.type !== types_1.AST_NODE_TYPES.TSThisType) { + this.#referencer.currentScope().referenceValue(node.parameterName); + } + this.visit(node.typeAnnotation); + } + // a type query `typeof foo` is a special case that references a _non-type_ variable, + TSTypeAnnotation(node) { + // check + this.visitChildren(node); + } + TSTypeQuery(node) { + let entityName; + if (node.exprName.type === types_1.AST_NODE_TYPES.TSQualifiedName) { + let iter = node.exprName; + while (iter.left.type === types_1.AST_NODE_TYPES.TSQualifiedName) { + iter = iter.left; + } + entityName = iter.left; + } + else { + entityName = node.exprName; + if (node.exprName.type === types_1.AST_NODE_TYPES.TSImportType) { + this.visit(node.exprName); + } + } + if (entityName.type === types_1.AST_NODE_TYPES.Identifier) { + this.#referencer.currentScope().referenceValue(entityName); + } + this.visit(node.typeArguments); + } +} +exports.TypeVisitor = TypeVisitor; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/Visitor.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Visitor.d.ts new file mode 100644 index 00000000..cd15f880 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Visitor.d.ts @@ -0,0 +1,14 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { PatternVisitorCallback, PatternVisitorOptions } from './PatternVisitor'; +import type { VisitorOptions } from './VisitorBase'; +import { VisitorBase } from './VisitorBase'; +interface VisitPatternOptions extends PatternVisitorOptions { + processRightHandNodes?: boolean; +} +export declare class Visitor extends VisitorBase { + #private; + constructor(optionsOrVisitor: Visitor | VisitorOptions); + protected visitPattern(node: TSESTree.Node, callback: PatternVisitorCallback, options?: VisitPatternOptions): void; +} +export { VisitorBase, type VisitorOptions } from './VisitorBase'; +//# sourceMappingURL=Visitor.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/Visitor.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Visitor.d.ts.map new file mode 100644 index 00000000..83830e0a --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Visitor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Visitor.d.ts","sourceRoot":"","sources":["../../src/referencer/Visitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EACV,sBAAsB,EACtB,qBAAqB,EACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAGpD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,UAAU,mBAAoB,SAAQ,qBAAqB;IACzD,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC;AACD,qBAAa,OAAQ,SAAQ,WAAW;;gBAE1B,gBAAgB,EAAE,OAAO,GAAG,cAAc;IAatD,SAAS,CAAC,YAAY,CACpB,IAAI,EAAE,QAAQ,CAAC,IAAI,EACnB,QAAQ,EAAE,sBAAsB,EAChC,OAAO,GAAE,mBAAsD,GAC9D,IAAI;CAWR;AAED,OAAO,EAAE,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/Visitor.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Visitor.js new file mode 100644 index 00000000..9752defa --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/Visitor.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VisitorBase = exports.Visitor = void 0; +const PatternVisitor_1 = require("./PatternVisitor"); +const VisitorBase_1 = require("./VisitorBase"); +class Visitor extends VisitorBase_1.VisitorBase { + #options; + constructor(optionsOrVisitor) { + super(optionsOrVisitor instanceof Visitor + ? optionsOrVisitor.#options + : optionsOrVisitor); + this.#options = + optionsOrVisitor instanceof Visitor + ? optionsOrVisitor.#options + : optionsOrVisitor; + } + visitPattern(node, callback, options = { processRightHandNodes: false }) { + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + const visitor = new PatternVisitor_1.PatternVisitor(this.#options, node, callback); + visitor.visit(node); + // Process the right hand nodes recursively. + if (options.processRightHandNodes) { + visitor.rightHandNodes.forEach(this.visit, this); + } + } +} +exports.Visitor = Visitor; +var VisitorBase_2 = require("./VisitorBase"); +Object.defineProperty(exports, "VisitorBase", { enumerable: true, get: function () { return VisitorBase_2.VisitorBase; } }); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/VisitorBase.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/VisitorBase.d.ts new file mode 100644 index 00000000..6c550158 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/VisitorBase.d.ts @@ -0,0 +1,22 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { VisitorKeys } from '@typescript-eslint/visitor-keys'; +export interface VisitorOptions { + childVisitorKeys?: VisitorKeys | null; + visitChildrenEvenIfSelectorExists?: boolean; +} +export declare abstract class VisitorBase { + #private; + constructor(options: VisitorOptions); + /** + * Default method for visiting children. + * @param node the node whose children should be visited + * @param excludeArr a list of keys to not visit + */ + visitChildren(node: T | null | undefined, excludeArr?: (keyof T)[]): void; + /** + * Dispatching node. + */ + visit(node: TSESTree.Node | null | undefined): void; +} +export type { VisitorKeys } from '@typescript-eslint/visitor-keys'; +//# sourceMappingURL=VisitorBase.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/VisitorBase.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/VisitorBase.d.ts.map new file mode 100644 index 00000000..da51b6f9 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/VisitorBase.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"VisitorBase.d.ts","sourceRoot":"","sources":["../../src/referencer/VisitorBase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkB,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAInE,MAAM,WAAW,cAAc;IAC7B,gBAAgB,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC;IACtC,iCAAiC,CAAC,EAAE,OAAO,CAAC;CAC7C;AAaD,8BAAsB,WAAW;;gBAGnB,OAAO,EAAE,cAAc;IAMnC;;;;OAIG;IACH,aAAa,CAAC,CAAC,SAAS,QAAQ,CAAC,IAAI,EACnC,IAAI,EAAE,CAAC,GAAG,IAAI,GAAG,SAAS,EAC1B,UAAU,GAAE,CAAC,MAAM,CAAC,CAAC,EAAO,GAC3B,IAAI;IA6BP;;OAEG;IACH,KAAK,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI;CAepD;AAED,YAAY,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/VisitorBase.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/VisitorBase.js new file mode 100644 index 00000000..b7725653 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/VisitorBase.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VisitorBase = void 0; +const visitor_keys_1 = require("@typescript-eslint/visitor-keys"); +function isObject(obj) { + return typeof obj === 'object' && obj != null; +} +function isNode(node) { + return isObject(node) && typeof node.type === 'string'; +} +class VisitorBase { + #childVisitorKeys; + #visitChildrenEvenIfSelectorExists; + constructor(options) { + this.#childVisitorKeys = options.childVisitorKeys ?? visitor_keys_1.visitorKeys; + this.#visitChildrenEvenIfSelectorExists = + options.visitChildrenEvenIfSelectorExists ?? false; + } + /** + * Default method for visiting children. + * @param node the node whose children should be visited + * @param excludeArr a list of keys to not visit + */ + visitChildren(node, excludeArr = []) { + if (node?.type == null) { + return; + } + const exclude = new Set([...excludeArr, 'parent']); + const children = this.#childVisitorKeys[node.type] ?? Object.keys(node); + for (const key of children) { + if (exclude.has(key)) { + continue; + } + const child = node[key]; + if (!child) { + continue; + } + if (Array.isArray(child)) { + for (const subChild of child) { + if (isNode(subChild)) { + this.visit(subChild); + } + } + } + else if (isNode(child)) { + this.visit(child); + } + } + } + /** + * Dispatching node. + */ + visit(node) { + if (node?.type == null) { + return; + } + const visitor = this[node.type]; + if (visitor) { + visitor.call(this, node); + if (!this.#visitChildrenEvenIfSelectorExists) { + return; + } + } + this.visitChildren(node); + } +} +exports.VisitorBase = VisitorBase; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/index.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/referencer/index.d.ts new file mode 100644 index 00000000..7f232ed4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/index.d.ts @@ -0,0 +1,2 @@ +export { Referencer, type ReferencerOptions } from './Referencer'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/index.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/referencer/index.d.ts.map new file mode 100644 index 00000000..36b3e570 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/referencer/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/referencer/index.js b/node_modules/@typescript-eslint/scope-manager/dist/referencer/index.js new file mode 100644 index 00000000..0f94d64e --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/referencer/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Referencer = void 0; +var Referencer_1 = require("./Referencer"); +Object.defineProperty(exports, "Referencer", { enumerable: true, get: function () { return Referencer_1.Referencer; } }); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/BlockScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/BlockScope.d.ts new file mode 100644 index 00000000..22ac51ed --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/BlockScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class BlockScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: BlockScope['upper'], block: BlockScope['block']); +} +//# sourceMappingURL=BlockScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/BlockScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/BlockScope.d.ts.map new file mode 100644 index 00000000..591ab324 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/BlockScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"BlockScope.d.ts","sourceRoot":"","sources":["../../src/scope/BlockScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,UAAW,SAAQ,SAAS,CACvC,SAAS,CAAC,KAAK,EACf,QAAQ,CAAC,cAAc,EACvB,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,UAAU,CAAC,OAAO,CAAC,EAC/B,KAAK,EAAE,UAAU,CAAC,OAAO,CAAC;CAI7B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/BlockScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/BlockScope.js new file mode 100644 index 00000000..9ead6115 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/BlockScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BlockScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class BlockScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.block, upperScope, block, false); + } +} +exports.BlockScope = BlockScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/CatchScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/CatchScope.d.ts new file mode 100644 index 00000000..5d4474f4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/CatchScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class CatchScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: CatchScope['upper'], block: CatchScope['block']); +} +//# sourceMappingURL=CatchScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/CatchScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/CatchScope.d.ts.map new file mode 100644 index 00000000..87c09cf7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/CatchScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"CatchScope.d.ts","sourceRoot":"","sources":["../../src/scope/CatchScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,UAAW,SAAQ,SAAS,CACvC,SAAS,CAAC,KAAK,EACf,QAAQ,CAAC,WAAW,EACpB,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,UAAU,CAAC,OAAO,CAAC,EAC/B,KAAK,EAAE,UAAU,CAAC,OAAO,CAAC;CAI7B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/CatchScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/CatchScope.js new file mode 100644 index 00000000..613ffb9b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/CatchScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CatchScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class CatchScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.catch, upperScope, block, false); + } +} +exports.CatchScope = CatchScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassFieldInitializerScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassFieldInitializerScope.d.ts new file mode 100644 index 00000000..e8341f11 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassFieldInitializerScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class ClassFieldInitializerScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: ClassFieldInitializerScope['upper'], block: ClassFieldInitializerScope['block']); +} +//# sourceMappingURL=ClassFieldInitializerScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassFieldInitializerScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassFieldInitializerScope.d.ts.map new file mode 100644 index 00000000..821c2e87 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassFieldInitializerScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ClassFieldInitializerScope.d.ts","sourceRoot":"","sources":["../../src/scope/ClassFieldInitializerScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,0BAA2B,SAAQ,SAAS,CACvD,SAAS,CAAC,qBAAqB,EAE/B,QAAQ,CAAC,UAAU,EACnB,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,0BAA0B,CAAC,OAAO,CAAC,EAC/C,KAAK,EAAE,0BAA0B,CAAC,OAAO,CAAC;CAU7C"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassFieldInitializerScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassFieldInitializerScope.js new file mode 100644 index 00000000..c4693743 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassFieldInitializerScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClassFieldInitializerScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class ClassFieldInitializerScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.classFieldInitializer, upperScope, block, false); + } +} +exports.ClassFieldInitializerScope = ClassFieldInitializerScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassScope.d.ts new file mode 100644 index 00000000..2b054b9c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class ClassScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: ClassScope['upper'], block: ClassScope['block']); +} +//# sourceMappingURL=ClassScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassScope.d.ts.map new file mode 100644 index 00000000..94a4ddfc --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ClassScope.d.ts","sourceRoot":"","sources":["../../src/scope/ClassScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,UAAW,SAAQ,SAAS,CACvC,SAAS,CAAC,KAAK,EACf,QAAQ,CAAC,gBAAgB,GAAG,QAAQ,CAAC,eAAe,EACpD,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,UAAU,CAAC,OAAO,CAAC,EAC/B,KAAK,EAAE,UAAU,CAAC,OAAO,CAAC;CAI7B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassScope.js new file mode 100644 index 00000000..187c9732 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClassScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class ClassScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.class, upperScope, block, false); + } +} +exports.ClassScope = ClassScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassStaticBlockScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassStaticBlockScope.d.ts new file mode 100644 index 00000000..bc9f5916 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassStaticBlockScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class ClassStaticBlockScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: ClassStaticBlockScope['upper'], block: ClassStaticBlockScope['block']); +} +//# sourceMappingURL=ClassStaticBlockScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassStaticBlockScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassStaticBlockScope.d.ts.map new file mode 100644 index 00000000..948e0886 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassStaticBlockScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ClassStaticBlockScope.d.ts","sourceRoot":"","sources":["../../src/scope/ClassStaticBlockScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,qBAAsB,SAAQ,SAAS,CAClD,SAAS,CAAC,gBAAgB,EAC1B,QAAQ,CAAC,WAAW,EACpB,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,qBAAqB,CAAC,OAAO,CAAC,EAC1C,KAAK,EAAE,qBAAqB,CAAC,OAAO,CAAC;CAIxC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassStaticBlockScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassStaticBlockScope.js new file mode 100644 index 00000000..77d700ec --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ClassStaticBlockScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClassStaticBlockScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class ClassStaticBlockScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.classStaticBlock, upperScope, block, false); + } +} +exports.ClassStaticBlockScope = ClassStaticBlockScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ConditionalTypeScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/ConditionalTypeScope.d.ts new file mode 100644 index 00000000..06f13d10 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ConditionalTypeScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class ConditionalTypeScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: ConditionalTypeScope['upper'], block: ConditionalTypeScope['block']); +} +//# sourceMappingURL=ConditionalTypeScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ConditionalTypeScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/ConditionalTypeScope.d.ts.map new file mode 100644 index 00000000..7c287437 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ConditionalTypeScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ConditionalTypeScope.d.ts","sourceRoot":"","sources":["../../src/scope/ConditionalTypeScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,oBAAqB,SAAQ,SAAS,CACjD,SAAS,CAAC,eAAe,EACzB,QAAQ,CAAC,iBAAiB,EAC1B,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,oBAAoB,CAAC,OAAO,CAAC,EACzC,KAAK,EAAE,oBAAoB,CAAC,OAAO,CAAC;CAIvC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ConditionalTypeScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/ConditionalTypeScope.js new file mode 100644 index 00000000..e1d7e5f1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ConditionalTypeScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConditionalTypeScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class ConditionalTypeScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.conditionalType, upperScope, block, false); + } +} +exports.ConditionalTypeScope = ConditionalTypeScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ForScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/ForScope.d.ts new file mode 100644 index 00000000..bc73314d --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ForScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class ForScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: ForScope['upper'], block: ForScope['block']); +} +//# sourceMappingURL=ForScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ForScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/ForScope.d.ts.map new file mode 100644 index 00000000..c551db14 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ForScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ForScope.d.ts","sourceRoot":"","sources":["../../src/scope/ForScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,QAAS,SAAQ,SAAS,CACrC,SAAS,CAAC,GAAG,EACb,QAAQ,CAAC,cAAc,GAAG,QAAQ,CAAC,cAAc,GAAG,QAAQ,CAAC,YAAY,EACzE,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,QAAQ,CAAC,OAAO,CAAC,EAC7B,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC;CAI3B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ForScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/ForScope.js new file mode 100644 index 00000000..dc3d7d55 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ForScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ForScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class ForScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.for, upperScope, block, false); + } +} +exports.ForScope = ForScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionExpressionNameScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionExpressionNameScope.d.ts new file mode 100644 index 00000000..2c2b9725 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionExpressionNameScope.d.ts @@ -0,0 +1,10 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class FunctionExpressionNameScope extends ScopeBase { + readonly functionExpressionScope: true; + constructor(scopeManager: ScopeManager, upperScope: FunctionExpressionNameScope['upper'], block: FunctionExpressionNameScope['block']); +} +//# sourceMappingURL=FunctionExpressionNameScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionExpressionNameScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionExpressionNameScope.d.ts.map new file mode 100644 index 00000000..de03bbfc --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionExpressionNameScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionExpressionNameScope.d.ts","sourceRoot":"","sources":["../../src/scope/FunctionExpressionNameScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAGrC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,2BAA4B,SAAQ,SAAS,CACxD,SAAS,CAAC,sBAAsB,EAChC,QAAQ,CAAC,kBAAkB,EAC3B,KAAK,CACN;IACC,SAAyB,uBAAuB,EAAE,IAAI,CAAC;gBAGrD,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,2BAA2B,CAAC,OAAO,CAAC,EAChD,KAAK,EAAE,2BAA2B,CAAC,OAAO,CAAC;CAiB9C"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionExpressionNameScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionExpressionNameScope.js new file mode 100644 index 00000000..3afd1bd6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionExpressionNameScope.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionExpressionNameScope = void 0; +const definition_1 = require("../definition"); +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class FunctionExpressionNameScope extends ScopeBase_1.ScopeBase { + functionExpressionScope; + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.functionExpressionName, upperScope, block, false); + if (block.id) { + this.defineIdentifier(block.id, new definition_1.FunctionNameDefinition(block.id, block)); + } + this.functionExpressionScope = true; + } +} +exports.FunctionExpressionNameScope = FunctionExpressionNameScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionScope.d.ts new file mode 100644 index 00000000..75678103 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionScope.d.ts @@ -0,0 +1,12 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { Reference } from '../referencer/Reference'; +import type { ScopeManager } from '../ScopeManager'; +import type { Variable } from '../variable'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class FunctionScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: FunctionScope['upper'], block: FunctionScope['block'], isMethodDefinition: boolean); + protected isValidResolution(ref: Reference, variable: Variable): boolean; +} +//# sourceMappingURL=FunctionScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionScope.d.ts.map new file mode 100644 index 00000000..3c06de57 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionScope.d.ts","sourceRoot":"","sources":["../../src/scope/FunctionScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,aAAc,SAAQ,SAAS,CAC1C,SAAS,CAAC,QAAQ,EAChB,QAAQ,CAAC,uBAAuB,GAChC,QAAQ,CAAC,mBAAmB,GAC5B,QAAQ,CAAC,kBAAkB,GAC3B,QAAQ,CAAC,OAAO,GAChB,QAAQ,CAAC,iBAAiB,GAC1B,QAAQ,CAAC,6BAA6B,EACxC,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,aAAa,CAAC,OAAO,CAAC,EAClC,KAAK,EAAE,aAAa,CAAC,OAAO,CAAC,EAC7B,kBAAkB,EAAE,OAAO;cAuBV,iBAAiB,CAClC,GAAG,EAAE,SAAS,EACd,QAAQ,EAAE,QAAQ,GACjB,OAAO;CAiBX"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionScope.js new file mode 100644 index 00000000..f5eb4d90 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionScope.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionScope = void 0; +const types_1 = require("@typescript-eslint/types"); +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class FunctionScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, ScopeType_1.ScopeType.function, upperScope, block, isMethodDefinition); + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== types_1.AST_NODE_TYPES.ArrowFunctionExpression) { + this.defineVariable('arguments', this.set, this.variables, null, null); + } + } + // References in default parameters isn't resolved to variables which are in their function body. + // const x = 1 + // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. + // const x = 2 + // console.log(a) + // } + isValidResolution(ref, variable) { + // If `options.globalReturn` is true, `this.block` becomes a Program node. + if (this.block.type === types_1.AST_NODE_TYPES.Program) { + return true; + } + const bodyStart = this.block.body?.range[0] ?? -1; + // It's invalid resolution in the following case: + return !((variable.scope === this && + ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. + variable.defs.every(d => d.name.range[0] >= bodyStart)) // the variable is in the body. + ); + } +} +exports.FunctionScope = FunctionScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionTypeScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionTypeScope.d.ts new file mode 100644 index 00000000..71788445 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionTypeScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class FunctionTypeScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: FunctionTypeScope['upper'], block: FunctionTypeScope['block']); +} +//# sourceMappingURL=FunctionTypeScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionTypeScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionTypeScope.d.ts.map new file mode 100644 index 00000000..072a4d30 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionTypeScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionTypeScope.d.ts","sourceRoot":"","sources":["../../src/scope/FunctionTypeScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,iBAAkB,SAAQ,SAAS,CAC9C,SAAS,CAAC,YAAY,EACpB,QAAQ,CAAC,0BAA0B,GACnC,QAAQ,CAAC,iBAAiB,GAC1B,QAAQ,CAAC,+BAA+B,GACxC,QAAQ,CAAC,cAAc,GACvB,QAAQ,CAAC,iBAAiB,EAC5B,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,iBAAiB,CAAC,OAAO,CAAC,EACtC,KAAK,EAAE,iBAAiB,CAAC,OAAO,CAAC;CAIpC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionTypeScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionTypeScope.js new file mode 100644 index 00000000..9b3e5bf3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/FunctionTypeScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionTypeScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class FunctionTypeScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.functionType, upperScope, block, false); + } +} +exports.FunctionTypeScope = FunctionTypeScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/GlobalScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/GlobalScope.d.ts new file mode 100644 index 00000000..e3208ab7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/GlobalScope.d.ts @@ -0,0 +1,17 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { ImplicitLibVariableOptions } from '../variable'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class GlobalScope extends ScopeBase { + private readonly implicit; + constructor(scopeManager: ScopeManager, block: GlobalScope['block']); + close(scopeManager: ScopeManager): Scope | null; + defineImplicitVariable(name: string, options: ImplicitLibVariableOptions): void; +} +//# sourceMappingURL=GlobalScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/GlobalScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/GlobalScope.d.ts.map new file mode 100644 index 00000000..7265bfbf --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/GlobalScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GlobalScope.d.ts","sourceRoot":"","sources":["../../src/scope/GlobalScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAKzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,0BAA0B,EAAY,MAAM,aAAa,CAAC;AACxE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAKrC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,WAAY,SAAQ,SAAS,CACxC,SAAS,CAAC,MAAM,EAChB,QAAQ,CAAC,OAAO;AAChB;;GAEG;AACH,IAAI,CACL;IAEC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAQvB;gBAEU,YAAY,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC;IASnD,KAAK,CAAC,YAAY,EAAE,YAAY,GAAG,KAAK,GAAG,IAAI;IAwBxD,sBAAsB,CAC3B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,0BAA0B,GAClC,IAAI;CASR"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/GlobalScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/GlobalScope.js new file mode 100644 index 00000000..42df3776 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/GlobalScope.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GlobalScope = void 0; +const types_1 = require("@typescript-eslint/types"); +const assert_1 = require("../assert"); +const ImplicitGlobalVariableDefinition_1 = require("../definition/ImplicitGlobalVariableDefinition"); +const variable_1 = require("../variable"); +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class GlobalScope extends ScopeBase_1.ScopeBase { + // note this is accessed in used in the legacy eslint-scope tests, so it can't be true private + implicit; + constructor(scopeManager, block) { + super(scopeManager, ScopeType_1.ScopeType.global, null, block, false); + this.implicit = { + leftToBeResolved: [], + set: new Map(), + variables: [], + }; + } + close(scopeManager) { + (0, assert_1.assert)(this.leftToResolve); + for (const ref of this.leftToResolve) { + if (ref.maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + // create an implicit global variable from assignment expression + const info = ref.maybeImplicitGlobal; + const node = info.pattern; + if (node.type === types_1.AST_NODE_TYPES.Identifier) { + this.defineVariable(node.name, this.implicit.set, this.implicit.variables, node, new ImplicitGlobalVariableDefinition_1.ImplicitGlobalVariableDefinition(info.pattern, info.node)); + } + } + } + this.implicit.leftToBeResolved = this.leftToResolve; + return super.close(scopeManager); + } + defineImplicitVariable(name, options) { + this.defineVariable(new variable_1.ImplicitLibVariable(this, name, options), this.set, this.variables, null, null); + } +} +exports.GlobalScope = GlobalScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/MappedTypeScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/MappedTypeScope.d.ts new file mode 100644 index 00000000..bd709054 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/MappedTypeScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class MappedTypeScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: MappedTypeScope['upper'], block: MappedTypeScope['block']); +} +//# sourceMappingURL=MappedTypeScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/MappedTypeScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/MappedTypeScope.d.ts.map new file mode 100644 index 00000000..1e146e3b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/MappedTypeScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MappedTypeScope.d.ts","sourceRoot":"","sources":["../../src/scope/MappedTypeScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,eAAgB,SAAQ,SAAS,CAC5C,SAAS,CAAC,UAAU,EACpB,QAAQ,CAAC,YAAY,EACrB,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,eAAe,CAAC,OAAO,CAAC,EACpC,KAAK,EAAE,eAAe,CAAC,OAAO,CAAC;CAIlC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/MappedTypeScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/MappedTypeScope.js new file mode 100644 index 00000000..bbe7bd2c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/MappedTypeScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MappedTypeScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class MappedTypeScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.mappedType, upperScope, block, false); + } +} +exports.MappedTypeScope = MappedTypeScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ModuleScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/ModuleScope.d.ts new file mode 100644 index 00000000..d80d5860 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ModuleScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class ModuleScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: ModuleScope['upper'], block: ModuleScope['block']); +} +//# sourceMappingURL=ModuleScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ModuleScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/ModuleScope.d.ts.map new file mode 100644 index 00000000..39572ce3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ModuleScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ModuleScope.d.ts","sourceRoot":"","sources":["../../src/scope/ModuleScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,WAAY,SAAQ,SAAS,CACxC,SAAS,CAAC,MAAM,EAChB,QAAQ,CAAC,OAAO,EAChB,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,EAChC,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC;CAI9B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ModuleScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/ModuleScope.js new file mode 100644 index 00000000..3180a569 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ModuleScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ModuleScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class ModuleScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.module, upperScope, block, false); + } +} +exports.ModuleScope = ModuleScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/Scope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/Scope.d.ts new file mode 100644 index 00000000..b67b14a7 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/Scope.d.ts @@ -0,0 +1,20 @@ +import type { BlockScope } from './BlockScope'; +import type { CatchScope } from './CatchScope'; +import type { ClassFieldInitializerScope } from './ClassFieldInitializerScope'; +import type { ClassScope } from './ClassScope'; +import type { ClassStaticBlockScope } from './ClassStaticBlockScope'; +import type { ConditionalTypeScope } from './ConditionalTypeScope'; +import type { ForScope } from './ForScope'; +import type { FunctionExpressionNameScope } from './FunctionExpressionNameScope'; +import type { FunctionScope } from './FunctionScope'; +import type { FunctionTypeScope } from './FunctionTypeScope'; +import type { GlobalScope } from './GlobalScope'; +import type { MappedTypeScope } from './MappedTypeScope'; +import type { ModuleScope } from './ModuleScope'; +import type { SwitchScope } from './SwitchScope'; +import type { TSEnumScope } from './TSEnumScope'; +import type { TSModuleScope } from './TSModuleScope'; +import type { TypeScope } from './TypeScope'; +import type { WithScope } from './WithScope'; +export type Scope = BlockScope | CatchScope | ClassFieldInitializerScope | ClassScope | ClassStaticBlockScope | ConditionalTypeScope | ForScope | FunctionExpressionNameScope | FunctionScope | FunctionTypeScope | GlobalScope | MappedTypeScope | ModuleScope | SwitchScope | TSEnumScope | TSModuleScope | TypeScope | WithScope; +//# sourceMappingURL=Scope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/Scope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/Scope.d.ts.map new file mode 100644 index 00000000..d7cda278 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/Scope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Scope.d.ts","sourceRoot":"","sources":["../../src/scope/Scope.ts"],"names":[],"mappings":"AAAA,OAAO,KAA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ACT,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/Scope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/Scope.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/Scope.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeBase.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeBase.d.ts new file mode 100644 index 00000000..a243c79b --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeBase.d.ts @@ -0,0 +1,98 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { Definition } from '../definition'; +import type { ReferenceImplicitGlobal } from '../referencer/Reference'; +import type { ScopeManager } from '../ScopeManager'; +import type { FunctionScope } from './FunctionScope'; +import type { GlobalScope } from './GlobalScope'; +import type { ModuleScope } from './ModuleScope'; +import type { Scope } from './Scope'; +import type { TSModuleScope } from './TSModuleScope'; +import { Reference, ReferenceFlag } from '../referencer/Reference'; +import { Variable } from '../variable'; +import { ScopeType } from './ScopeType'; +type VariableScope = FunctionScope | GlobalScope | ModuleScope | TSModuleScope; +export declare abstract class ScopeBase { + #private; + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + readonly $id: number; + /** + * The AST node which created this scope. + * @public + */ + readonly block: Block; + /** + * The array of child scopes. This does not include grandchild scopes. + * @public + */ + readonly childScopes: Scope[]; + /** + * Whether this scope is created by a FunctionExpression. + * @public + */ + readonly functionExpressionScope: boolean; + /** + * Whether 'use strict' is in effect in this scope. + * @public + */ + isStrict: boolean; + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + */ + protected leftToResolve: Reference[] | null; + /** + * Any variable {@link Reference} found in this scope. + * This includes occurrences of local variables as well as variables from parent scopes (including the global scope). + * For local variables this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the formal parameter in the parameter list. + * @public + */ + readonly references: Reference[]; + /** + * The map from variable names to variable objects. + * @public + */ + readonly set: Map; + /** + * The {@link Reference}s that are not resolved with this scope. + * @public + */ + readonly through: Reference[]; + readonly type: Type; + /** + * Reference to the parent {@link Scope}. + * @public + */ + readonly upper: Upper; + /** + * The scoped {@link Variable}s of this scope. + * In the case of a 'function' scope this includes the automatic argument `arguments` as its first element, as well + * as all further formal arguments. + * This does not include variables which are defined in child scopes. + * @public + */ + readonly variables: Variable[]; + readonly variableScope: VariableScope; + constructor(scopeManager: ScopeManager, type: Type, upperScope: Upper, block: Block, isMethodDefinition: boolean); + private isVariableScope; + private shouldStaticallyCloseForGlobal; + close(scopeManager: ScopeManager): Scope | null; + shouldStaticallyClose(): boolean; + /** + * To override by function scopes. + * References in default parameters isn't resolved to variables which are in their function body. + */ + protected defineVariable(nameOrVariable: string | Variable, set: Map, variables: Variable[], node: TSESTree.Identifier | null, def: Definition | null): void; + protected delegateToUpperScope(ref: Reference): void; + protected isValidResolution(_ref: Reference, _variable: Variable): boolean; + private addDeclaredVariablesOfNode; + defineIdentifier(node: TSESTree.Identifier, def: Definition): void; + defineLiteralIdentifier(node: TSESTree.StringLiteral, def: Definition): void; + referenceDualValueType(node: TSESTree.Identifier): void; + referenceType(node: TSESTree.Identifier): void; + referenceValue(node: TSESTree.Identifier | TSESTree.JSXIdentifier, assign?: ReferenceFlag, writeExpr?: TSESTree.Expression | null, maybeImplicitGlobal?: ReferenceImplicitGlobal | null, init?: boolean): void; +} +export {}; +//# sourceMappingURL=ScopeBase.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeBase.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeBase.d.ts.map new file mode 100644 index 00000000..b693f2de --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeBase.d.ts.map @@ -0,0 +1 @@ +{"version":3,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aAAa,EAC5B,GAAG,EAAE,UAAU,GACd,IAAI;IAIA,sBAAsB,CAAC,IAAI,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI;IAevD,aAAa,CAAC,IAAI,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI;IAe9C,cAAc,CACnB,IAAI,EAAE,QAAQ,CAAC,UAAU,GAAG,QAAQ,CAAC,aAAa,EAClD,MAAM,GAAE,aAAkC,EAC1C,SAAS,CAAC,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI,EACtC,mBAAmB,CAAC,EAAE,uBAAuB,GAAG,IAAI,EACpD,IAAI,UAAQ,GACX,IAAI;CAcR"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeBase.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeBase.js new file mode 100644 index 00000000..5e07a7c3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeBase.js @@ -0,0 +1,360 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ScopeBase = void 0; +const types_1 = require("@typescript-eslint/types"); +const assert_1 = require("../assert"); +const definition_1 = require("../definition"); +const ID_1 = require("../ID"); +const Reference_1 = require("../referencer/Reference"); +const variable_1 = require("../variable"); +const ScopeType_1 = require("./ScopeType"); +/** + * Test if scope is strict + */ +function isStrictScope(scope, block, isMethodDefinition) { + let body; + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper?.isStrict) { + return true; + } + if (isMethodDefinition) { + return true; + } + if (scope.type === ScopeType_1.ScopeType.class || + scope.type === ScopeType_1.ScopeType.conditionalType || + scope.type === ScopeType_1.ScopeType.functionType || + scope.type === ScopeType_1.ScopeType.mappedType || + scope.type === ScopeType_1.ScopeType.module || + scope.type === ScopeType_1.ScopeType.tsEnum || + scope.type === ScopeType_1.ScopeType.tsModule || + scope.type === ScopeType_1.ScopeType.type) { + return true; + } + if (scope.type === ScopeType_1.ScopeType.block || scope.type === ScopeType_1.ScopeType.switch) { + return false; + } + if (scope.type === ScopeType_1.ScopeType.function) { + const functionBody = block; + switch (functionBody.type) { + case types_1.AST_NODE_TYPES.ArrowFunctionExpression: + if (functionBody.body.type !== types_1.AST_NODE_TYPES.BlockStatement) { + return false; + } + body = functionBody.body; + break; + case types_1.AST_NODE_TYPES.Program: + body = functionBody; + break; + default: + body = functionBody.body; + } + if (!body) { + return false; + } + } + else if (scope.type === ScopeType_1.ScopeType.global) { + body = block; + } + else { + return false; + } + // Search 'use strict' directive. + for (const stmt of body.body) { + if (stmt.type !== types_1.AST_NODE_TYPES.ExpressionStatement) { + break; + } + if (stmt.directive === 'use strict') { + return true; + } + const expr = stmt.expression; + if (expr.type !== types_1.AST_NODE_TYPES.Literal) { + break; + } + if (expr.raw === '"use strict"' || expr.raw === "'use strict'") { + return true; + } + if (expr.value === 'use strict') { + return true; + } + } + return false; +} +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); + const scopes = scopeManager.nodeToScope.get(scope.block); + if (scopes) { + scopes.push(scope); + } + else { + scopeManager.nodeToScope.set(scope.block, [scope]); + } +} +const generator = (0, ID_1.createIdGenerator)(); +const VARIABLE_SCOPE_TYPES = new Set([ + ScopeType_1.ScopeType.classFieldInitializer, + ScopeType_1.ScopeType.classStaticBlock, + ScopeType_1.ScopeType.function, + ScopeType_1.ScopeType.global, + ScopeType_1.ScopeType.module, + ScopeType_1.ScopeType.tsModule, +]); +class ScopeBase { + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + $id = generator(); + /** + * The AST node which created this scope. + * @public + */ + block; + /** + * The array of child scopes. This does not include grandchild scopes. + * @public + */ + childScopes = []; + /** + * A map of the variables for each node in this scope. + * This is map is a pointer to the one in the parent ScopeManager instance + */ + #declaredVariables; + /** + * Generally, through the lexical scoping of JS you can always know which variable an identifier in the source code + * refers to. There are a few exceptions to this rule. With `global` and `with` scopes you can only decide at runtime + * which variable a reference refers to. + * All those scopes are considered "dynamic". + */ + #dynamic; + /** + * Whether this scope is created by a FunctionExpression. + * @public + */ + functionExpressionScope = false; + /** + * Whether 'use strict' is in effect in this scope. + * @public + */ + isStrict; + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + */ + leftToResolve = []; + /** + * Any variable {@link Reference} found in this scope. + * This includes occurrences of local variables as well as variables from parent scopes (including the global scope). + * For local variables this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the formal parameter in the parameter list. + * @public + */ + references = []; + /** + * The map from variable names to variable objects. + * @public + */ + set = new Map(); + /** + * The {@link Reference}s that are not resolved with this scope. + * @public + */ + through = []; + type; + /** + * Reference to the parent {@link Scope}. + * @public + */ + upper; + /** + * The scoped {@link Variable}s of this scope. + * In the case of a 'function' scope this includes the automatic argument `arguments` as its first element, as well + * as all further formal arguments. + * This does not include variables which are defined in child scopes. + * @public + */ + variables = []; + /** + * For scopes that can contain variable declarations, this is a self-reference. + * For other scope types this is the *variableScope* value of the parent scope. + * @public + */ + #dynamicCloseRef = (ref) => { + // notify all names are through to global + let current = this; + do { + /* eslint-disable @typescript-eslint/no-non-null-assertion */ + current.through.push(ref); + current = current.upper; + /* eslint-enable @typescript-eslint/no-non-null-assertion */ + } while (current); + }; + #globalCloseRef = (ref, scopeManager) => { + // let/const/class declarations should be resolved statically. + // others should be resolved dynamically. + if (this.shouldStaticallyCloseForGlobal(ref, scopeManager)) { + this.#staticCloseRef(ref); + } + else { + this.#dynamicCloseRef(ref); + } + }; + #staticCloseRef = (ref) => { + const resolve = () => { + const name = ref.identifier.name; + const variable = this.set.get(name); + if (!variable) { + return false; + } + if (!this.isValidResolution(ref, variable)) { + return false; + } + // make sure we don't match a type reference to a value variable + const isValidTypeReference = ref.isTypeReference && variable.isTypeVariable; + const isValidValueReference = ref.isValueReference && variable.isValueVariable; + if (!isValidTypeReference && !isValidValueReference) { + return false; + } + variable.references.push(ref); + ref.resolved = variable; + return true; + }; + if (!resolve()) { + this.delegateToUpperScope(ref); + } + }; + variableScope; + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + const upperScopeAsScopeBase = upperScope; + this.type = type; + this.#dynamic = + this.type === ScopeType_1.ScopeType.global || this.type === ScopeType_1.ScopeType.with; + this.block = block; + this.variableScope = this.isVariableScope() + ? this + : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + upperScopeAsScopeBase.variableScope; + this.upper = upperScope; + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = isStrictScope(this, block, isMethodDefinition); + // this is guaranteed to be correct at runtime + upperScopeAsScopeBase?.childScopes.push(this); + this.#declaredVariables = scopeManager.declaredVariables; + registerScope(scopeManager, this); + } + isVariableScope() { + return VARIABLE_SCOPE_TYPES.has(this.type); + } + shouldStaticallyCloseForGlobal(ref, scopeManager) { + // On global scope, let/const/class declarations should be resolved statically. + const name = ref.identifier.name; + const variable = this.set.get(name); + if (!variable) { + return false; + } + // variable exists on the scope + // in module mode, we can statically resolve everything, regardless of its decl type + if (scopeManager.isModule()) { + return true; + } + // in script mode, only certain cases should be statically resolved + // Example: + // a `var` decl is ignored by the runtime if it clashes with a global name + // this means that we should not resolve the reference to the variable + const defs = variable.defs; + return (defs.length > 0 && + defs.every(def => { + if (def.type === definition_1.DefinitionType.Variable && def.parent.kind === 'var') { + return false; + } + return true; + })); + } + close(scopeManager) { + let closeRef; + if (this.shouldStaticallyClose()) { + closeRef = this.#staticCloseRef; + } + else if (this.type !== 'global') { + closeRef = this.#dynamicCloseRef; + } + else { + closeRef = this.#globalCloseRef; + } + // Try Resolving all references in this scope. + (0, assert_1.assert)(this.leftToResolve); + this.leftToResolve.forEach(ref => closeRef(ref, scopeManager)); + this.leftToResolve = null; + return this.upper; + } + shouldStaticallyClose() { + return !this.#dynamic; + } + /** + * To override by function scopes. + * References in default parameters isn't resolved to variables which are in their function body. + */ + defineVariable(nameOrVariable, set, variables, node, def) { + const name = typeof nameOrVariable === 'string' ? nameOrVariable : nameOrVariable.name; + let variable = set.get(name); + if (!variable) { + variable = + typeof nameOrVariable === 'string' + ? new variable_1.Variable(name, this) + : nameOrVariable; + set.set(name, variable); + variables.push(variable); + } + if (def) { + variable.defs.push(def); + this.addDeclaredVariablesOfNode(variable, def.node); + this.addDeclaredVariablesOfNode(variable, def.parent); + } + if (node) { + variable.identifiers.push(node); + } + } + delegateToUpperScope(ref) { + this.upper?.leftToResolve?.push(ref); + this.through.push(ref); + } + isValidResolution(_ref, _variable) { + return true; + } + addDeclaredVariablesOfNode(variable, node) { + if (node == null) { + return; + } + let variables = this.#declaredVariables.get(node); + if (variables == null) { + variables = []; + this.#declaredVariables.set(node, variables); + } + if (!variables.includes(variable)) { + variables.push(variable); + } + } + defineIdentifier(node, def) { + this.defineVariable(node.name, this.set, this.variables, node, def); + } + defineLiteralIdentifier(node, def) { + this.defineVariable(node.value, this.set, this.variables, null, def); + } + referenceDualValueType(node) { + const ref = new Reference_1.Reference(node, this, Reference_1.ReferenceFlag.Read, null, null, false, Reference_1.ReferenceTypeFlag.Type | Reference_1.ReferenceTypeFlag.Value); + this.references.push(ref); + this.leftToResolve?.push(ref); + } + referenceType(node) { + const ref = new Reference_1.Reference(node, this, Reference_1.ReferenceFlag.Read, null, null, false, Reference_1.ReferenceTypeFlag.Type); + this.references.push(ref); + this.leftToResolve?.push(ref); + } + referenceValue(node, assign = Reference_1.ReferenceFlag.Read, writeExpr, maybeImplicitGlobal, init = false) { + const ref = new Reference_1.Reference(node, this, assign, writeExpr, maybeImplicitGlobal, init, Reference_1.ReferenceTypeFlag.Value); + this.references.push(ref); + this.leftToResolve?.push(ref); + } +} +exports.ScopeBase = ScopeBase; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeType.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeType.d.ts new file mode 100644 index 00000000..a67c73d8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeType.d.ts @@ -0,0 +1,21 @@ +export declare enum ScopeType { + block = "block", + catch = "catch", + class = "class", + classFieldInitializer = "class-field-initializer", + classStaticBlock = "class-static-block", + conditionalType = "conditionalType", + for = "for", + function = "function", + functionExpressionName = "function-expression-name", + functionType = "functionType", + global = "global", + mappedType = "mappedType", + module = "module", + switch = "switch", + tsEnum = "tsEnum", + tsModule = "tsModule", + type = "type", + with = "with" +} +//# sourceMappingURL=ScopeType.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeType.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeType.d.ts.map new file mode 100644 index 00000000..6181f2d2 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeType.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ScopeType.d.ts","sourceRoot":"","sources":["../../src/scope/ScopeType.ts"],"names":[],"mappings":"AAAA,oBAAY,SAAS;IACnB,KAAK,UAAU;IACf,KAAK,UAAU;IACf,KAAK,UAAU;IACf,qBAAqB,4BAA4B;IACjD,gBAAgB,uBAAuB;IACvC,eAAe,oBAAoB;IACnC,GAAG,QAAQ;IACX,QAAQ,aAAa;IACrB,sBAAsB,6BAA6B;IACnD,YAAY,iBAAiB;IAC7B,MAAM,WAAW;IACjB,UAAU,eAAe;IACzB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,QAAQ,aAAa;IACrB,IAAI,SAAS;IACb,IAAI,SAAS;CACd"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeType.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeType.js new file mode 100644 index 00000000..a0279738 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/ScopeType.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ScopeType = void 0; +var ScopeType; +(function (ScopeType) { + ScopeType["block"] = "block"; + ScopeType["catch"] = "catch"; + ScopeType["class"] = "class"; + ScopeType["classFieldInitializer"] = "class-field-initializer"; + ScopeType["classStaticBlock"] = "class-static-block"; + ScopeType["conditionalType"] = "conditionalType"; + ScopeType["for"] = "for"; + ScopeType["function"] = "function"; + ScopeType["functionExpressionName"] = "function-expression-name"; + ScopeType["functionType"] = "functionType"; + ScopeType["global"] = "global"; + ScopeType["mappedType"] = "mappedType"; + ScopeType["module"] = "module"; + ScopeType["switch"] = "switch"; + ScopeType["tsEnum"] = "tsEnum"; + ScopeType["tsModule"] = "tsModule"; + ScopeType["type"] = "type"; + ScopeType["with"] = "with"; +})(ScopeType || (exports.ScopeType = ScopeType = {})); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/SwitchScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/SwitchScope.d.ts new file mode 100644 index 00000000..85b5d2ef --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/SwitchScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class SwitchScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: SwitchScope['upper'], block: SwitchScope['block']); +} +//# sourceMappingURL=SwitchScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/SwitchScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/SwitchScope.d.ts.map new file mode 100644 index 00000000..035d6aee --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/SwitchScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SwitchScope.d.ts","sourceRoot":"","sources":["../../src/scope/SwitchScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,WAAY,SAAQ,SAAS,CACxC,SAAS,CAAC,MAAM,EAChB,QAAQ,CAAC,eAAe,EACxB,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,EAChC,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC;CAI9B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/SwitchScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/SwitchScope.js new file mode 100644 index 00000000..c894a033 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/SwitchScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SwitchScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class SwitchScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.switch, upperScope, block, false); + } +} +exports.SwitchScope = SwitchScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/TSEnumScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSEnumScope.d.ts new file mode 100644 index 00000000..026aeedc --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSEnumScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class TSEnumScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: TSEnumScope['upper'], block: TSEnumScope['block']); +} +//# sourceMappingURL=TSEnumScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/TSEnumScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSEnumScope.d.ts.map new file mode 100644 index 00000000..dac52dce --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSEnumScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TSEnumScope.d.ts","sourceRoot":"","sources":["../../src/scope/TSEnumScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,WAAY,SAAQ,SAAS,CACxC,SAAS,CAAC,MAAM,EAChB,QAAQ,CAAC,iBAAiB,EAC1B,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,EAChC,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC;CAI9B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/TSEnumScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSEnumScope.js new file mode 100644 index 00000000..417bdde9 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSEnumScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSEnumScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class TSEnumScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.tsEnum, upperScope, block, false); + } +} +exports.TSEnumScope = TSEnumScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/TSModuleScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSModuleScope.d.ts new file mode 100644 index 00000000..76c49e39 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSModuleScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class TSModuleScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: TSModuleScope['upper'], block: TSModuleScope['block']); +} +//# sourceMappingURL=TSModuleScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/TSModuleScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSModuleScope.d.ts.map new file mode 100644 index 00000000..beda3923 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSModuleScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TSModuleScope.d.ts","sourceRoot":"","sources":["../../src/scope/TSModuleScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,aAAc,SAAQ,SAAS,CAC1C,SAAS,CAAC,QAAQ,EAClB,QAAQ,CAAC,mBAAmB,EAC5B,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,aAAa,CAAC,OAAO,CAAC,EAClC,KAAK,EAAE,aAAa,CAAC,OAAO,CAAC;CAIhC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/TSModuleScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSModuleScope.js new file mode 100644 index 00000000..04d97746 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/TSModuleScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSModuleScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class TSModuleScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.tsModule, upperScope, block, false); + } +} +exports.TSModuleScope = TSModuleScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/TypeScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/TypeScope.d.ts new file mode 100644 index 00000000..25163260 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/TypeScope.d.ts @@ -0,0 +1,9 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class TypeScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: TypeScope['upper'], block: TypeScope['block']); +} +//# sourceMappingURL=TypeScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/TypeScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/TypeScope.d.ts.map new file mode 100644 index 00000000..838d8732 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/TypeScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TypeScope.d.ts","sourceRoot":"","sources":["../../src/scope/TypeScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,SAAU,SAAQ,SAAS,CACtC,SAAS,CAAC,IAAI,EACd,QAAQ,CAAC,sBAAsB,GAAG,QAAQ,CAAC,sBAAsB,EACjE,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,SAAS,CAAC,OAAO,CAAC,EAC9B,KAAK,EAAE,SAAS,CAAC,OAAO,CAAC;CAI5B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/TypeScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/TypeScope.js new file mode 100644 index 00000000..c62ad968 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/TypeScope.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypeScope = void 0; +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class TypeScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.type, upperScope, block, false); + } +} +exports.TypeScope = TypeScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/WithScope.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/WithScope.d.ts new file mode 100644 index 00000000..3743b5d6 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/WithScope.d.ts @@ -0,0 +1,10 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { ScopeManager } from '../ScopeManager'; +import type { Scope } from './Scope'; +import { ScopeBase } from './ScopeBase'; +import { ScopeType } from './ScopeType'; +export declare class WithScope extends ScopeBase { + constructor(scopeManager: ScopeManager, upperScope: WithScope['upper'], block: WithScope['block']); + close(scopeManager: ScopeManager): Scope | null; +} +//# sourceMappingURL=WithScope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/WithScope.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/WithScope.d.ts.map new file mode 100644 index 00000000..b6dab38f --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/WithScope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WithScope.d.ts","sourceRoot":"","sources":["../../src/scope/WithScope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAGrC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,qBAAa,SAAU,SAAQ,SAAS,CACtC,SAAS,CAAC,IAAI,EACd,QAAQ,CAAC,aAAa,EACtB,KAAK,CACN;gBAEG,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,SAAS,CAAC,OAAO,CAAC,EAC9B,KAAK,EAAE,SAAS,CAAC,OAAO,CAAC;IAKX,KAAK,CAAC,YAAY,EAAE,YAAY,GAAG,KAAK,GAAG,IAAI;CAShE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/WithScope.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/WithScope.js new file mode 100644 index 00000000..9ec3a47c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/WithScope.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WithScope = void 0; +const assert_1 = require("../assert"); +const ScopeBase_1 = require("./ScopeBase"); +const ScopeType_1 = require("./ScopeType"); +class WithScope extends ScopeBase_1.ScopeBase { + constructor(scopeManager, upperScope, block) { + super(scopeManager, ScopeType_1.ScopeType.with, upperScope, block, false); + } + close(scopeManager) { + if (this.shouldStaticallyClose()) { + return super.close(scopeManager); + } + (0, assert_1.assert)(this.leftToResolve); + this.leftToResolve.forEach(ref => this.delegateToUpperScope(ref)); + this.leftToResolve = null; + return this.upper; + } +} +exports.WithScope = WithScope; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/index.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/scope/index.d.ts new file mode 100644 index 00000000..7bf60717 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/index.d.ts @@ -0,0 +1,20 @@ +export * from './BlockScope'; +export * from './CatchScope'; +export * from './ClassFieldInitializerScope'; +export * from './ClassScope'; +export * from './ConditionalTypeScope'; +export * from './ForScope'; +export * from './FunctionExpressionNameScope'; +export * from './FunctionScope'; +export * from './FunctionTypeScope'; +export * from './GlobalScope'; +export * from './MappedTypeScope'; +export * from './ModuleScope'; +export * from './Scope'; +export * from './ScopeType'; +export * from './SwitchScope'; +export * from './TSEnumScope'; +export * from './TSModuleScope'; +export * from './TypeScope'; +export * from './WithScope'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/index.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/scope/index.d.ts.map new file mode 100644 index 00000000..43f10ba3 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scope/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC;AAC7B,cAAc,8BAA8B,CAAC;AAC7C,cAAc,cAAc,CAAC;AAC7B,cAAc,wBAAwB,CAAC;AACvC,cAAc,YAAY,CAAC;AAC3B,cAAc,+BAA+B,CAAC;AAC9C,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,eAAe,CAAC;AAC9B,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAC9B,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/scope/index.js b/node_modules/@typescript-eslint/scope-manager/dist/scope/index.js new file mode 100644 index 00000000..d2e73d83 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/scope/index.js @@ -0,0 +1,35 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./BlockScope"), exports); +__exportStar(require("./CatchScope"), exports); +__exportStar(require("./ClassFieldInitializerScope"), exports); +__exportStar(require("./ClassScope"), exports); +__exportStar(require("./ConditionalTypeScope"), exports); +__exportStar(require("./ForScope"), exports); +__exportStar(require("./FunctionExpressionNameScope"), exports); +__exportStar(require("./FunctionScope"), exports); +__exportStar(require("./FunctionTypeScope"), exports); +__exportStar(require("./GlobalScope"), exports); +__exportStar(require("./MappedTypeScope"), exports); +__exportStar(require("./ModuleScope"), exports); +__exportStar(require("./Scope"), exports); +__exportStar(require("./ScopeType"), exports); +__exportStar(require("./SwitchScope"), exports); +__exportStar(require("./TSEnumScope"), exports); +__exportStar(require("./TSModuleScope"), exports); +__exportStar(require("./TypeScope"), exports); +__exportStar(require("./WithScope"), exports); diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/ESLintScopeVariable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/variable/ESLintScopeVariable.d.ts new file mode 100644 index 00000000..5d230e23 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/ESLintScopeVariable.d.ts @@ -0,0 +1,33 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import { VariableBase } from './VariableBase'; +/** + * ESLint defines global variables using the eslint-scope Variable class + * This is declared here for consumers to use + */ +export declare class ESLintScopeVariable extends VariableBase { + /** + * Written to by ESLint. + * If this key exists, this variable is a global variable added by ESLint. + * If this is `true`, this variable can be assigned arbitrary values. + * If this is `false`, this variable is readonly. + */ + writeable?: boolean; + /** + * Written to by ESLint. + * This property is undefined if there are no globals comment directives. + * The array of globals comment directives which defined this global variable in the source code file. + */ + eslintExplicitGlobal?: boolean; + /** + * Written to by ESLint. + * The configured value in config files. This can be different from `variable.writeable` if there are globals comment directives. + */ + eslintImplicitGlobalSetting?: 'readonly' | 'writable'; + /** + * Written to by ESLint. + * If this key exists, it is a global variable added by ESLint. + * If `true`, this global variable was defined by a globals comment directive in the source code file. + */ + eslintExplicitGlobalComments?: TSESTree.Comment[]; +} +//# sourceMappingURL=ESLintScopeVariable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/ESLintScopeVariable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/variable/ESLintScopeVariable.d.ts.map new file mode 100644 index 00000000..0890facb --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/ESLintScopeVariable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ESLintScopeVariable.d.ts","sourceRoot":"","sources":["../../src/variable/ESLintScopeVariable.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,YAAY;IACnD;;;;;OAKG;IACI,SAAS,CAAC,EAAE,OAAO,CAAC;IAE3B;;;;OAIG;IACI,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAEtC;;;OAGG;IACI,2BAA2B,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAE7D;;;;OAIG;IACI,4BAA4B,CAAC,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;CAC1D"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/ESLintScopeVariable.js b/node_modules/@typescript-eslint/scope-manager/dist/variable/ESLintScopeVariable.js new file mode 100644 index 00000000..4450dad2 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/ESLintScopeVariable.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ESLintScopeVariable = void 0; +const VariableBase_1 = require("./VariableBase"); +/** + * ESLint defines global variables using the eslint-scope Variable class + * This is declared here for consumers to use + */ +class ESLintScopeVariable extends VariableBase_1.VariableBase { + /** + * Written to by ESLint. + * If this key exists, this variable is a global variable added by ESLint. + * If this is `true`, this variable can be assigned arbitrary values. + * If this is `false`, this variable is readonly. + */ + writeable; // note that this isn't a typo - ESlint uses this spelling here + /** + * Written to by ESLint. + * This property is undefined if there are no globals comment directives. + * The array of globals comment directives which defined this global variable in the source code file. + */ + eslintExplicitGlobal; + /** + * Written to by ESLint. + * The configured value in config files. This can be different from `variable.writeable` if there are globals comment directives. + */ + eslintImplicitGlobalSetting; + /** + * Written to by ESLint. + * If this key exists, it is a global variable added by ESLint. + * If `true`, this global variable was defined by a globals comment directive in the source code file. + */ + eslintExplicitGlobalComments; +} +exports.ESLintScopeVariable = ESLintScopeVariable; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/ImplicitLibVariable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/variable/ImplicitLibVariable.d.ts new file mode 100644 index 00000000..2fed9b96 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/ImplicitLibVariable.d.ts @@ -0,0 +1,28 @@ +import type { Scope } from '../scope'; +import type { Variable } from './Variable'; +import { ESLintScopeVariable } from './ESLintScopeVariable'; +export interface ImplicitLibVariableOptions { + readonly eslintImplicitGlobalSetting?: ESLintScopeVariable['eslintImplicitGlobalSetting']; + readonly isTypeVariable?: boolean; + readonly isValueVariable?: boolean; + readonly writeable?: boolean; +} +export interface LibDefinition { + libs: readonly LibDefinition[]; + variables: readonly [string, ImplicitLibVariableOptions][]; +} +/** + * An variable implicitly defined by the TS Lib + */ +export declare class ImplicitLibVariable extends ESLintScopeVariable implements Variable { + /** + * `true` if the variable is valid in a type context, false otherwise + */ + readonly isTypeVariable: boolean; + /** + * `true` if the variable is valid in a value context, false otherwise + */ + readonly isValueVariable: boolean; + constructor(scope: Scope, name: string, { eslintImplicitGlobalSetting, isTypeVariable, isValueVariable, writeable, }: ImplicitLibVariableOptions); +} +//# sourceMappingURL=ImplicitLibVariable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/ImplicitLibVariable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/variable/ImplicitLibVariable.d.ts.map new file mode 100644 index 00000000..322f6756 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/ImplicitLibVariable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ImplicitLibVariable.d.ts","sourceRoot":"","sources":["../../src/variable/ImplicitLibVariable.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,2BAA2B,CAAC,EAAE,mBAAmB,CAAC,6BAA6B,CAAC,CAAC;IAC1F,QAAQ,CAAC,cAAc,CAAC,EAAE,OAAO,CAAC;IAClC,QAAQ,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IACnC,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,SAAS,aAAa,EAAE,CAAC;IAC/B,SAAS,EAAE,SAAS,CAAC,MAAM,EAAE,0BAA0B,CAAC,EAAE,CAAC;CAC5D;AAED;;GAEG;AACH,qBAAa,mBACX,SAAQ,mBACR,YAAW,QAAQ;IAEnB;;OAEG;IACH,SAAgB,cAAc,EAAE,OAAO,CAAC;IAExC;;OAEG;IACH,SAAgB,eAAe,EAAE,OAAO,CAAC;gBAGvC,KAAK,EAAE,KAAK,EACZ,IAAI,EAAE,MAAM,EACZ,EACE,2BAA2B,EAC3B,cAAc,EACd,eAAe,EACf,SAAS,GACV,EAAE,0BAA0B;CAShC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/ImplicitLibVariable.js b/node_modules/@typescript-eslint/scope-manager/dist/variable/ImplicitLibVariable.js new file mode 100644 index 00000000..b896c1e4 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/ImplicitLibVariable.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ImplicitLibVariable = void 0; +const ESLintScopeVariable_1 = require("./ESLintScopeVariable"); +/** + * An variable implicitly defined by the TS Lib + */ +class ImplicitLibVariable extends ESLintScopeVariable_1.ESLintScopeVariable { + /** + * `true` if the variable is valid in a type context, false otherwise + */ + isTypeVariable; + /** + * `true` if the variable is valid in a value context, false otherwise + */ + isValueVariable; + constructor(scope, name, { eslintImplicitGlobalSetting, isTypeVariable, isValueVariable, writeable, }) { + super(name, scope); + this.isTypeVariable = isTypeVariable ?? false; + this.isValueVariable = isValueVariable ?? false; + this.writeable = writeable ?? false; + this.eslintImplicitGlobalSetting = + eslintImplicitGlobalSetting ?? 'readonly'; + } +} +exports.ImplicitLibVariable = ImplicitLibVariable; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.d.ts new file mode 100644 index 00000000..64d46253 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.d.ts @@ -0,0 +1,17 @@ +import { VariableBase } from './VariableBase'; +/** + * A Variable represents a locally scoped identifier. These include arguments to functions. + */ +export declare class Variable extends VariableBase { + /** + * `true` if the variable is valid in a type context, false otherwise + * @public + */ + get isTypeVariable(): boolean; + /** + * `true` if the variable is valid in a value context, false otherwise + * @public + */ + get isValueVariable(): boolean; +} +//# sourceMappingURL=Variable.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.d.ts.map new file mode 100644 index 00000000..9263ad44 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Variable.d.ts","sourceRoot":"","sources":["../../src/variable/Variable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;GAEG;AACH,qBAAa,QAAS,SAAQ,YAAY;IACxC;;;OAGG;IACH,IAAW,cAAc,IAAI,OAAO,CAOnC;IAED;;;OAGG;IACH,IAAW,eAAe,IAAI,OAAO,CAOpC;CACF"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.js b/node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.js new file mode 100644 index 00000000..3623de9c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Variable = void 0; +const VariableBase_1 = require("./VariableBase"); +/** + * A Variable represents a locally scoped identifier. These include arguments to functions. + */ +class Variable extends VariableBase_1.VariableBase { + /** + * `true` if the variable is valid in a type context, false otherwise + * @public + */ + get isTypeVariable() { + if (this.defs.length === 0) { + // we don't statically know whether this is a type or a value + return true; + } + return this.defs.some(def => def.isTypeDefinition); + } + /** + * `true` if the variable is valid in a value context, false otherwise + * @public + */ + get isValueVariable() { + if (this.defs.length === 0) { + // we don't statically know whether this is a type or a value + return true; + } + return this.defs.some(def => def.isVariableDefinition); + } +} +exports.Variable = Variable; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/VariableBase.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/variable/VariableBase.d.ts new file mode 100644 index 00000000..0efe6e4c --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/VariableBase.d.ts @@ -0,0 +1,43 @@ +import type { TSESTree } from '@typescript-eslint/types'; +import type { Definition } from '../definition'; +import type { Reference } from '../referencer/Reference'; +import type { Scope } from '../scope'; +export declare class VariableBase { + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + readonly $id: number; + /** + * The array of the definitions of this variable. + * @public + */ + readonly defs: Definition[]; + /** + * True if the variable is considered used for the purposes of `no-unused-vars`, false otherwise. + * @public + */ + eslintUsed: boolean; + /** + * The array of `Identifier` nodes which define this variable. + * If this variable is redeclared, this array includes two or more nodes. + * @public + */ + readonly identifiers: TSESTree.Identifier[]; + /** + * The variable name, as given in the source code. + * @public + */ + readonly name: string; + /** + * List of {@link Reference} of this variable (excluding parameter entries) in its defining scope and all nested scopes. + * For defining occurrences only see {@link Variable#defs}. + * @public + */ + readonly references: Reference[]; + /** + * Reference to the enclosing Scope. + */ + readonly scope: Scope; + constructor(name: string, scope: Scope); +} +//# sourceMappingURL=VariableBase.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/VariableBase.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/variable/VariableBase.d.ts.map new file mode 100644 index 00000000..182e3983 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/VariableBase.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"VariableBase.d.ts","sourceRoot":"","sources":["../../src/variable/VariableBase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAMtC,qBAAa,YAAY;IACvB;;OAEG;IACH,SAAgB,GAAG,EAAE,MAAM,CAAe;IAE1C;;;OAGG;IACH,SAAgB,IAAI,EAAE,UAAU,EAAE,CAAM;IACxC;;;OAGG;IACI,UAAU,UAAS;IAC1B;;;;OAIG;IACH,SAAgB,WAAW,EAAE,QAAQ,CAAC,UAAU,EAAE,CAAM;IACxD;;;OAGG;IACH,SAAgB,IAAI,EAAE,MAAM,CAAC;IAC7B;;;;OAIG;IACH,SAAgB,UAAU,EAAE,SAAS,EAAE,CAAM;IAC7C;;OAEG;IACH,SAAgB,KAAK,EAAE,KAAK,CAAC;gBAEjB,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK;CAIvC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/VariableBase.js b/node_modules/@typescript-eslint/scope-manager/dist/variable/VariableBase.js new file mode 100644 index 00000000..8a81b341 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/VariableBase.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VariableBase = void 0; +const ID_1 = require("../ID"); +const generator = (0, ID_1.createIdGenerator)(); +class VariableBase { + /** + * A unique ID for this instance - primarily used to help debugging and testing + */ + $id = generator(); + /** + * The array of the definitions of this variable. + * @public + */ + defs = []; + /** + * True if the variable is considered used for the purposes of `no-unused-vars`, false otherwise. + * @public + */ + eslintUsed = false; + /** + * The array of `Identifier` nodes which define this variable. + * If this variable is redeclared, this array includes two or more nodes. + * @public + */ + identifiers = []; + /** + * The variable name, as given in the source code. + * @public + */ + name; + /** + * List of {@link Reference} of this variable (excluding parameter entries) in its defining scope and all nested scopes. + * For defining occurrences only see {@link Variable#defs}. + * @public + */ + references = []; + /** + * Reference to the enclosing Scope. + */ + scope; + constructor(name, scope) { + this.name = name; + this.scope = scope; + } +} +exports.VariableBase = VariableBase; diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/index.d.ts b/node_modules/@typescript-eslint/scope-manager/dist/variable/index.d.ts new file mode 100644 index 00000000..33c861e1 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/index.d.ts @@ -0,0 +1,7 @@ +import type { ESLintScopeVariable } from './ESLintScopeVariable'; +import type { Variable } from './Variable'; +export { ESLintScopeVariable } from './ESLintScopeVariable'; +export { ImplicitLibVariable, type ImplicitLibVariableOptions, type LibDefinition, } from './ImplicitLibVariable'; +export { Variable } from './Variable'; +export type ScopeVariable = ESLintScopeVariable | Variable; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/index.d.ts.map b/node_modules/@typescript-eslint/scope-manager/dist/variable/index.d.ts.map new file mode 100644 index 00000000..46c7ba66 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/variable/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EACL,mBAAmB,EACnB,KAAK,0BAA0B,EAC/B,KAAK,aAAa,GACnB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,mBAAmB,GAAG,QAAQ,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/dist/variable/index.js b/node_modules/@typescript-eslint/scope-manager/dist/variable/index.js new file mode 100644 index 00000000..a194a417 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/dist/variable/index.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Variable = exports.ImplicitLibVariable = exports.ESLintScopeVariable = void 0; +var ESLintScopeVariable_1 = require("./ESLintScopeVariable"); +Object.defineProperty(exports, "ESLintScopeVariable", { enumerable: true, get: function () { return ESLintScopeVariable_1.ESLintScopeVariable; } }); +var ImplicitLibVariable_1 = require("./ImplicitLibVariable"); +Object.defineProperty(exports, "ImplicitLibVariable", { enumerable: true, get: function () { return ImplicitLibVariable_1.ImplicitLibVariable; } }); +var Variable_1 = require("./Variable"); +Object.defineProperty(exports, "Variable", { enumerable: true, get: function () { return Variable_1.Variable; } }); diff --git a/node_modules/@typescript-eslint/scope-manager/package.json b/node_modules/@typescript-eslint/scope-manager/package.json new file mode 100644 index 00000000..62865506 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/package.json @@ -0,0 +1,74 @@ +{ + "name": "@typescript-eslint/scope-manager", + "version": "8.34.0", + "description": "TypeScript scope analyser for ESLint", + "files": [ + "dist", + "!*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/scope-manager" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/scope-manager", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "clean-fixtures": "rimraf -g \"./src/**/fixtures/**/snapshots\"", + "format": "yarn run -T format", + "generate-lib": "yarn run -BT nx generate-lib repo", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "dependencies": { + "@typescript-eslint/types": "8.34.0", + "@typescript-eslint/visitor-keys": "8.34.0" + }, + "devDependencies": { + "@typescript-eslint/typescript-estree": "8.34.0", + "@vitest/coverage-v8": "^3.1.3", + "@vitest/pretty-format": "^3.1.3", + "glob": "*", + "rimraf": "*", + "typescript": "*", + "vitest": "^3.1.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "scope-manager", + "includedScripts": [ + "clean", + "clean-fixtures" + ] + } +} diff --git a/node_modules/@typescript-eslint/tsconfig-utils/LICENSE b/node_modules/@typescript-eslint/tsconfig-utils/LICENSE new file mode 100644 index 00000000..310a18f8 --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/tsconfig-utils/README.md b/node_modules/@typescript-eslint/tsconfig-utils/README.md new file mode 100644 index 00000000..075c3fbb --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/tsconfig-utils` + +> Utilities for collecting TSConfigs for linting scenarios. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/tsconfig-utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/tsconfig-utils) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/tsconfig-utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/tsconfig-utils) + +The utilities in this package are separated from `@typescript-eslint/utils` so that they do not have a dependency on `eslint` or `@typescript-eslint/typescript-estree`. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/tsconfig-utils/dist/compilerOptions.d.ts b/node_modules/@typescript-eslint/tsconfig-utils/dist/compilerOptions.d.ts new file mode 100644 index 00000000..61a748db --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/dist/compilerOptions.d.ts @@ -0,0 +1,9 @@ +/** + * Compiler options required to avoid critical functionality issues + */ +export declare const CORE_COMPILER_OPTIONS: { + noEmit: true; + noUnusedLocals: true; + noUnusedParameters: true; +}; +//# sourceMappingURL=compilerOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/tsconfig-utils/dist/compilerOptions.d.ts.map b/node_modules/@typescript-eslint/tsconfig-utils/dist/compilerOptions.d.ts.map new file mode 100644 index 00000000..4ae07a78 --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/dist/compilerOptions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"compilerOptions.d.ts","sourceRoot":"","sources":["../src/compilerOptions.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,qBAAqB;;;;CAOJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/tsconfig-utils/dist/compilerOptions.js b/node_modules/@typescript-eslint/tsconfig-utils/dist/compilerOptions.js new file mode 100644 index 00000000..06265dd5 --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/dist/compilerOptions.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CORE_COMPILER_OPTIONS = void 0; +/** + * Compiler options required to avoid critical functionality issues + */ +exports.CORE_COMPILER_OPTIONS = { + // Required to avoid parse from causing emit to occur + noEmit: true, + // Flags required to make no-unused-vars work + noUnusedLocals: true, + noUnusedParameters: true, +}; diff --git a/node_modules/@typescript-eslint/tsconfig-utils/dist/getParsedConfigFile.d.ts b/node_modules/@typescript-eslint/tsconfig-utils/dist/getParsedConfigFile.d.ts new file mode 100644 index 00000000..c8c5817a --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/dist/getParsedConfigFile.d.ts @@ -0,0 +1,9 @@ +import type * as ts from 'typescript/lib/tsserverlibrary'; +/** + * Parses a TSConfig file using the same logic as tsserver. + * + * @param configFile the path to the tsconfig.json file, relative to `projectDirectory` + * @param projectDirectory the project directory to use as the CWD, defaults to `process.cwd()` + */ +export declare function getParsedConfigFile(tsserver: typeof ts, configFile: string, projectDirectory?: string): ts.ParsedCommandLine; +//# sourceMappingURL=getParsedConfigFile.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/tsconfig-utils/dist/getParsedConfigFile.d.ts.map b/node_modules/@typescript-eslint/tsconfig-utils/dist/getParsedConfigFile.d.ts.map new file mode 100644 index 00000000..160615bb --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/dist/getParsedConfigFile.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getParsedConfigFile.d.ts","sourceRoot":"","sources":["../src/getParsedConfigFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,gCAAgC,CAAC;AAO1D;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,OAAO,EAAE,EACnB,UAAU,EAAE,MAAM,EAClB,gBAAgB,CAAC,EAAE,MAAM,GACxB,EAAE,CAAC,iBAAiB,CA6CtB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/tsconfig-utils/dist/getParsedConfigFile.js b/node_modules/@typescript-eslint/tsconfig-utils/dist/getParsedConfigFile.js new file mode 100644 index 00000000..68b3cbf7 --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/dist/getParsedConfigFile.js @@ -0,0 +1,76 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getParsedConfigFile = getParsedConfigFile; +const fs = __importStar(require("node:fs")); +const path = __importStar(require("node:path")); +const compilerOptions_1 = require("./compilerOptions"); +/** + * Parses a TSConfig file using the same logic as tsserver. + * + * @param configFile the path to the tsconfig.json file, relative to `projectDirectory` + * @param projectDirectory the project directory to use as the CWD, defaults to `process.cwd()` + */ +function getParsedConfigFile(tsserver, configFile, projectDirectory) { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/internal/eqeq-nullish + if (tsserver.sys === undefined) { + throw new Error('`getParsedConfigFile` is only supported in a Node-like environment.'); + } + const parsed = tsserver.getParsedCommandLineOfConfigFile(configFile, compilerOptions_1.CORE_COMPILER_OPTIONS, { + fileExists: fs.existsSync, + getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: diag => { + throw new Error(formatDiagnostics([diag])); // ensures that `parsed` is defined. + }, + readDirectory: tsserver.sys.readDirectory, + readFile: file => fs.readFileSync(path.isAbsolute(file) ? file : path.join(getCurrentDirectory(), file), 'utf-8'), + useCaseSensitiveFileNames: tsserver.sys.useCaseSensitiveFileNames, + }); + if (parsed?.errors.length) { + throw new Error(formatDiagnostics(parsed.errors)); + } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return parsed; + function getCurrentDirectory() { + return projectDirectory ? path.resolve(projectDirectory) : process.cwd(); + } + function formatDiagnostics(diagnostics) { + return tsserver.formatDiagnostics(diagnostics, { + getCanonicalFileName: f => f, + getCurrentDirectory, + getNewLine: () => '\n', + }); + } +} diff --git a/node_modules/@typescript-eslint/tsconfig-utils/dist/index.d.ts b/node_modules/@typescript-eslint/tsconfig-utils/dist/index.d.ts new file mode 100644 index 00000000..928fe5a1 --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/dist/index.d.ts @@ -0,0 +1,3 @@ +export * from './compilerOptions'; +export * from './getParsedConfigFile'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/tsconfig-utils/dist/index.d.ts.map b/node_modules/@typescript-eslint/tsconfig-utils/dist/index.d.ts.map new file mode 100644 index 00000000..903a2e2a --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/tsconfig-utils/dist/index.js b/node_modules/@typescript-eslint/tsconfig-utils/dist/index.js new file mode 100644 index 00000000..fdc529fe --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/dist/index.js @@ -0,0 +1,18 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./compilerOptions"), exports); +__exportStar(require("./getParsedConfigFile"), exports); diff --git a/node_modules/@typescript-eslint/tsconfig-utils/package.json b/node_modules/@typescript-eslint/tsconfig-utils/package.json new file mode 100644 index 00000000..97f071a8 --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/package.json @@ -0,0 +1,63 @@ +{ + "name": "@typescript-eslint/tsconfig-utils", + "version": "8.34.0", + "description": "Utilities for collecting TSConfigs for linting scenarios.", + "files": [ + "dist", + "!*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/tsconfig-utils" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "format": "yarn run -T format", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "publishConfig": { + "access": "public" + }, + "nx": { + "name": "tsconfig-utils", + "includedScripts": [ + "clean" + ] + } +} diff --git a/node_modules/@typescript-eslint/type-utils/LICENSE b/node_modules/@typescript-eslint/type-utils/LICENSE new file mode 100644 index 00000000..dabd464a --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/type-utils/README.md b/node_modules/@typescript-eslint/type-utils/README.md new file mode 100644 index 00000000..c5d32797 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/type-utils` + +> Type utilities for working with TypeScript within ESLint rules. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) + +The utilities in this package are separated from `@typescript-eslint/utils` so that that package does not require a dependency on `typescript`. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/type-utils/dist/TypeOrValueSpecifier.d.ts b/node_modules/@typescript-eslint/type-utils/dist/TypeOrValueSpecifier.d.ts new file mode 100644 index 00000000..9cd34dde --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/TypeOrValueSpecifier.d.ts @@ -0,0 +1,130 @@ +import type * as ts from 'typescript'; +/** + * Describes specific types or values declared in local files. + * See [TypeOrValueSpecifier > FileSpecifier](/packages/type-utils/type-or-value-specifier#filespecifier). + */ +export interface FileSpecifier { + from: 'file'; + /** + * Type or value name(s) to match on. + */ + name: string | string[]; + /** + * A specific file the types or values must be declared in. + */ + path?: string; +} +/** + * Describes specific types or values declared in TypeScript's built-in lib definitions. + * See [TypeOrValueSpecifier > LibSpecifier](/packages/type-utils/type-or-value-specifier#libspecifier). + */ +export interface LibSpecifier { + from: 'lib'; + /** + * Type or value name(s) to match on. + */ + name: string | string[]; +} +/** + * Describes specific types or values imported from packages. + * See [TypeOrValueSpecifier > PackageSpecifier](/packages/type-utils/type-or-value-specifier#packagespecifier). + */ +export interface PackageSpecifier { + from: 'package'; + /** + * Type or value name(s) to match on. + */ + name: string | string[]; + /** + * Package name the type or value must be declared in. + */ + package: string; +} +/** + * A centralized format for rule options to describe specific _types_ and/or _values_. + * See [TypeOrValueSpecifier](/packages/type-utils/type-or-value-specifier). + */ +export type TypeOrValueSpecifier = string | FileSpecifier | LibSpecifier | PackageSpecifier; +export declare const typeOrValueSpecifiersSchema: { + readonly items: { + readonly oneOf: [{ + readonly type: "string"; + }, { + readonly additionalProperties: false; + readonly properties: { + readonly from: { + readonly enum: ["file"]; + readonly type: "string"; + }; + readonly name: { + readonly oneOf: [{ + readonly type: "string"; + }, { + readonly items: { + readonly type: "string"; + }; + readonly minItems: 1; + readonly type: "array"; + readonly uniqueItems: true; + }]; + }; + readonly path: { + readonly type: "string"; + }; + }; + readonly required: ["from", "name"]; + readonly type: "object"; + }, { + readonly additionalProperties: false; + readonly properties: { + readonly from: { + readonly enum: ["lib"]; + readonly type: "string"; + }; + readonly name: { + readonly oneOf: [{ + readonly type: "string"; + }, { + readonly items: { + readonly type: "string"; + }; + readonly minItems: 1; + readonly type: "array"; + readonly uniqueItems: true; + }]; + }; + }; + readonly required: ["from", "name"]; + readonly type: "object"; + }, { + readonly additionalProperties: false; + readonly properties: { + readonly from: { + readonly enum: ["package"]; + readonly type: "string"; + }; + readonly name: { + readonly oneOf: [{ + readonly type: "string"; + }, { + readonly items: { + readonly type: "string"; + }; + readonly minItems: 1; + readonly type: "array"; + readonly uniqueItems: true; + }]; + }; + readonly package: { + readonly type: "string"; + }; + }; + readonly required: ["from", "name", "package"]; + readonly type: "object"; + }]; + }; + readonly type: "array"; +}; +export declare function typeMatchesSpecifier(type: ts.Type, specifier: TypeOrValueSpecifier, program: ts.Program): boolean; +export declare const typeMatchesSomeSpecifier: (type: ts.Type, specifiers: TypeOrValueSpecifier[] | undefined, program: ts.Program) => boolean; +//# sourceMappingURL=TypeOrValueSpecifier.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/TypeOrValueSpecifier.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/TypeOrValueSpecifier.d.ts.map new file mode 100644 index 00000000..2be10844 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/TypeOrValueSpecifier.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"TypeOrValueSpecifier.d.ts","sourceRoot":"","sources":["../src/TypeOrValueSpecifier.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAStC;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAExB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,KAAK,CAAC;IAEZ;;OAEG;IACH,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CACzB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,SAAS,CAAC;IAEhB;;OAEG;IACH,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAExB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,MAAM,oBAAoB,GAC5B,MAAM,GACN,aAAa,GACb,YAAY,GACZ,gBAAgB,CAAC;AAErB,eAAO,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6FR,CAAC;AAEjC,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,SAAS,EAAE,oBAAoB,EAC/B,OAAO,EAAE,EAAE,CAAC,OAAO,GAClB,OAAO,CA6CT;AAED,eAAO,MAAM,wBAAwB,GACnC,MAAM,EAAE,CAAC,IAAI,EACb,YAAY,oBAAoB,EAAE,YAAK,EACvC,SAAS,EAAE,CAAC,OAAO,KAClB,OAC2E,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/TypeOrValueSpecifier.js b/node_modules/@typescript-eslint/type-utils/dist/TypeOrValueSpecifier.js new file mode 100644 index 00000000..16977d99 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/TypeOrValueSpecifier.js @@ -0,0 +1,172 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.typeMatchesSomeSpecifier = exports.typeOrValueSpecifiersSchema = void 0; +exports.typeMatchesSpecifier = typeMatchesSpecifier; +const tsutils = __importStar(require("ts-api-utils")); +const specifierNameMatches_1 = require("./typeOrValueSpecifiers/specifierNameMatches"); +const typeDeclaredInFile_1 = require("./typeOrValueSpecifiers/typeDeclaredInFile"); +const typeDeclaredInLib_1 = require("./typeOrValueSpecifiers/typeDeclaredInLib"); +const typeDeclaredInPackageDeclarationFile_1 = require("./typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile"); +exports.typeOrValueSpecifiersSchema = { + items: { + oneOf: [ + { + type: 'string', + }, + { + additionalProperties: false, + properties: { + from: { + enum: ['file'], + type: 'string', + }, + name: { + oneOf: [ + { + type: 'string', + }, + { + items: { + type: 'string', + }, + minItems: 1, + type: 'array', + uniqueItems: true, + }, + ], + }, + path: { + type: 'string', + }, + }, + required: ['from', 'name'], + type: 'object', + }, + { + additionalProperties: false, + properties: { + from: { + enum: ['lib'], + type: 'string', + }, + name: { + oneOf: [ + { + type: 'string', + }, + { + items: { + type: 'string', + }, + minItems: 1, + type: 'array', + uniqueItems: true, + }, + ], + }, + }, + required: ['from', 'name'], + type: 'object', + }, + { + additionalProperties: false, + properties: { + from: { + enum: ['package'], + type: 'string', + }, + name: { + oneOf: [ + { + type: 'string', + }, + { + items: { + type: 'string', + }, + minItems: 1, + type: 'array', + uniqueItems: true, + }, + ], + }, + package: { + type: 'string', + }, + }, + required: ['from', 'name', 'package'], + type: 'object', + }, + ], + }, + type: 'array', +}; +function typeMatchesSpecifier(type, specifier, program) { + const wholeTypeMatches = (() => { + if (tsutils.isIntrinsicErrorType(type)) { + return false; + } + if (typeof specifier === 'string') { + return (0, specifierNameMatches_1.specifierNameMatches)(type, specifier); + } + if (!(0, specifierNameMatches_1.specifierNameMatches)(type, specifier.name)) { + return false; + } + const symbol = type.getSymbol() ?? type.aliasSymbol; + const declarations = symbol?.getDeclarations() ?? []; + const declarationFiles = declarations.map(declaration => declaration.getSourceFile()); + switch (specifier.from) { + case 'file': + return (0, typeDeclaredInFile_1.typeDeclaredInFile)(specifier.path, declarationFiles, program); + case 'lib': + return (0, typeDeclaredInLib_1.typeDeclaredInLib)(declarationFiles, program); + case 'package': + return (0, typeDeclaredInPackageDeclarationFile_1.typeDeclaredInPackageDeclarationFile)(specifier.package, declarations, declarationFiles, program); + } + })(); + if (wholeTypeMatches) { + return true; + } + if (tsutils.isIntersectionType(type) && + tsutils + .intersectionConstituents(type) + .some(part => typeMatchesSpecifier(part, specifier, program))) { + return true; + } + return false; +} +const typeMatchesSomeSpecifier = (type, specifiers = [], program) => specifiers.some(specifier => typeMatchesSpecifier(type, specifier, program)); +exports.typeMatchesSomeSpecifier = typeMatchesSomeSpecifier; diff --git a/node_modules/@typescript-eslint/type-utils/dist/builtinSymbolLikes.d.ts b/node_modules/@typescript-eslint/type-utils/dist/builtinSymbolLikes.d.ts new file mode 100644 index 00000000..4f398405 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/builtinSymbolLikes.d.ts @@ -0,0 +1,54 @@ +import * as ts from 'typescript'; +/** + * @example + * ```ts + * class DerivedClass extends Promise {} + * DerivedClass.reject + * // ^ PromiseLike + * ``` + */ +export declare function isPromiseLike(program: ts.Program, type: ts.Type): boolean; +/** + * @example + * ```ts + * const value = Promise + * value.reject + * // ^ PromiseConstructorLike + * ``` + */ +export declare function isPromiseConstructorLike(program: ts.Program, type: ts.Type): boolean; +/** + * @example + * ```ts + * class Foo extends Error {} + * new Foo() + * // ^ ErrorLike + * ``` + */ +export declare function isErrorLike(program: ts.Program, type: ts.Type): boolean; +/** + * @example + * ```ts + * type T = Readonly + * // ^ ReadonlyErrorLike + * ``` + */ +export declare function isReadonlyErrorLike(program: ts.Program, type: ts.Type): boolean; +/** + * @example + * ```ts + * type T = Readonly<{ foo: 'bar' }> + * // ^ ReadonlyTypeLike + * ``` + */ +export declare function isReadonlyTypeLike(program: ts.Program, type: ts.Type, predicate?: (subType: { + aliasSymbol: ts.Symbol; + aliasTypeArguments: readonly ts.Type[]; +} & ts.Type) => boolean): boolean; +export declare function isBuiltinTypeAliasLike(program: ts.Program, type: ts.Type, predicate: (subType: { + aliasSymbol: ts.Symbol; + aliasTypeArguments: readonly ts.Type[]; +} & ts.Type) => boolean): boolean; +export declare function isBuiltinSymbolLike(program: ts.Program, type: ts.Type, symbolName: string | string[]): boolean; +export declare function isBuiltinSymbolLikeRecurser(program: ts.Program, type: ts.Type, predicate: (subType: ts.Type) => boolean | null): boolean; +//# sourceMappingURL=builtinSymbolLikes.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/builtinSymbolLikes.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/builtinSymbolLikes.d.ts.map new file mode 100644 index 00000000..f47f7d34 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/builtinSymbolLikes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"builtinSymbolLikes.d.ts","sourceRoot":"","sources":["../src/builtinSymbolLikes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAIjC;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAEzE;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,OAAO,CAET;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAEvE;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,OAAO,CAQT;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,SAAS,CAAC,EAAE,CACV,OAAO,EAAE;IACP,WAAW,EAAE,EAAE,CAAC,MAAM,CAAC;IACvB,kBAAkB,EAAE,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC;CACxC,GAAG,EAAE,CAAC,IAAI,KACR,OAAO,GACX,OAAO,CAMT;AACD,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,SAAS,EAAE,CACT,OAAO,EAAE;IACP,WAAW,EAAE,EAAE,CAAC,MAAM,CAAC;IACvB,kBAAkB,EAAE,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC;CACxC,GAAG,EAAE,CAAC,IAAI,KACR,OAAO,GACX,OAAO,CAsBT;AAED,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,GAC5B,OAAO,CAoBT;AAED,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,KAAK,OAAO,GAAG,IAAI,GAC9C,OAAO,CAuCT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/builtinSymbolLikes.js b/node_modules/@typescript-eslint/type-utils/dist/builtinSymbolLikes.js new file mode 100644 index 00000000..3d1002f4 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/builtinSymbolLikes.js @@ -0,0 +1,164 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isPromiseLike = isPromiseLike; +exports.isPromiseConstructorLike = isPromiseConstructorLike; +exports.isErrorLike = isErrorLike; +exports.isReadonlyErrorLike = isReadonlyErrorLike; +exports.isReadonlyTypeLike = isReadonlyTypeLike; +exports.isBuiltinTypeAliasLike = isBuiltinTypeAliasLike; +exports.isBuiltinSymbolLike = isBuiltinSymbolLike; +exports.isBuiltinSymbolLikeRecurser = isBuiltinSymbolLikeRecurser; +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const isSymbolFromDefaultLibrary_1 = require("./isSymbolFromDefaultLibrary"); +/** + * @example + * ```ts + * class DerivedClass extends Promise {} + * DerivedClass.reject + * // ^ PromiseLike + * ``` + */ +function isPromiseLike(program, type) { + return isBuiltinSymbolLike(program, type, 'Promise'); +} +/** + * @example + * ```ts + * const value = Promise + * value.reject + * // ^ PromiseConstructorLike + * ``` + */ +function isPromiseConstructorLike(program, type) { + return isBuiltinSymbolLike(program, type, 'PromiseConstructor'); +} +/** + * @example + * ```ts + * class Foo extends Error {} + * new Foo() + * // ^ ErrorLike + * ``` + */ +function isErrorLike(program, type) { + return isBuiltinSymbolLike(program, type, 'Error'); +} +/** + * @example + * ```ts + * type T = Readonly + * // ^ ReadonlyErrorLike + * ``` + */ +function isReadonlyErrorLike(program, type) { + return isReadonlyTypeLike(program, type, subtype => { + const [typeArgument] = subtype.aliasTypeArguments; + return (isErrorLike(program, typeArgument) || + isReadonlyErrorLike(program, typeArgument)); + }); +} +/** + * @example + * ```ts + * type T = Readonly<{ foo: 'bar' }> + * // ^ ReadonlyTypeLike + * ``` + */ +function isReadonlyTypeLike(program, type, predicate) { + return isBuiltinTypeAliasLike(program, type, subtype => { + return (subtype.aliasSymbol.getName() === 'Readonly' && !!predicate?.(subtype)); + }); +} +function isBuiltinTypeAliasLike(program, type, predicate) { + return isBuiltinSymbolLikeRecurser(program, type, subtype => { + const { aliasSymbol, aliasTypeArguments } = subtype; + if (!aliasSymbol || !aliasTypeArguments) { + return false; + } + if ((0, isSymbolFromDefaultLibrary_1.isSymbolFromDefaultLibrary)(program, aliasSymbol) && + predicate(subtype)) { + return true; + } + return null; + }); +} +function isBuiltinSymbolLike(program, type, symbolName) { + return isBuiltinSymbolLikeRecurser(program, type, subType => { + const symbol = subType.getSymbol(); + if (!symbol) { + return false; + } + const actualSymbolName = symbol.getName(); + if ((Array.isArray(symbolName) + ? symbolName.some(name => actualSymbolName === name) + : actualSymbolName === symbolName) && + (0, isSymbolFromDefaultLibrary_1.isSymbolFromDefaultLibrary)(program, symbol)) { + return true; + } + return null; + }); +} +function isBuiltinSymbolLikeRecurser(program, type, predicate) { + if (type.isIntersection()) { + return type.types.some(t => isBuiltinSymbolLikeRecurser(program, t, predicate)); + } + if (type.isUnion()) { + return type.types.every(t => isBuiltinSymbolLikeRecurser(program, t, predicate)); + } + if (tsutils.isTypeParameter(type)) { + const t = type.getConstraint(); + if (t) { + return isBuiltinSymbolLikeRecurser(program, t, predicate); + } + return false; + } + const predicateResult = predicate(type); + if (typeof predicateResult === 'boolean') { + return predicateResult; + } + const symbol = type.getSymbol(); + if (symbol && + symbol.flags & (ts.SymbolFlags.Class | ts.SymbolFlags.Interface)) { + const checker = program.getTypeChecker(); + for (const baseType of checker.getBaseTypes(type)) { + if (isBuiltinSymbolLikeRecurser(program, baseType, predicate)) { + return true; + } + } + } + return false; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/containsAllTypesByName.d.ts b/node_modules/@typescript-eslint/type-utils/dist/containsAllTypesByName.d.ts new file mode 100644 index 00000000..d40e2047 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/containsAllTypesByName.d.ts @@ -0,0 +1,10 @@ +import * as ts from 'typescript'; +/** + * @param type Type being checked by name. + * @param allowAny Whether to consider `any` and `unknown` to match. + * @param allowedNames Symbol names checking on the type. + * @param matchAnyInstead Whether to instead just check if any parts match, rather than all parts. + * @returns Whether the type is, extends, or contains the allowed names (or all matches the allowed names, if mustMatchAll is true). + */ +export declare function containsAllTypesByName(type: ts.Type, allowAny: boolean, allowedNames: Set, matchAnyInstead?: boolean): boolean; +//# sourceMappingURL=containsAllTypesByName.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/containsAllTypesByName.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/containsAllTypesByName.d.ts.map new file mode 100644 index 00000000..d043e638 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/containsAllTypesByName.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"containsAllTypesByName.d.ts","sourceRoot":"","sources":["../src/containsAllTypesByName.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAIjC;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,QAAQ,EAAE,OAAO,EACjB,YAAY,EAAE,GAAG,CAAC,MAAM,CAAC,EACzB,eAAe,UAAQ,GACtB,OAAO,CA+BT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/containsAllTypesByName.js b/node_modules/@typescript-eslint/type-utils/dist/containsAllTypesByName.js new file mode 100644 index 00000000..33079704 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/containsAllTypesByName.js @@ -0,0 +1,69 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.containsAllTypesByName = containsAllTypesByName; +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const typeFlagUtils_1 = require("./typeFlagUtils"); +/** + * @param type Type being checked by name. + * @param allowAny Whether to consider `any` and `unknown` to match. + * @param allowedNames Symbol names checking on the type. + * @param matchAnyInstead Whether to instead just check if any parts match, rather than all parts. + * @returns Whether the type is, extends, or contains the allowed names (or all matches the allowed names, if mustMatchAll is true). + */ +function containsAllTypesByName(type, allowAny, allowedNames, matchAnyInstead = false) { + if ((0, typeFlagUtils_1.isTypeFlagSet)(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { + return !allowAny; + } + if (tsutils.isTypeReference(type)) { + type = type.target; + } + const symbol = type.getSymbol(); + if (symbol && allowedNames.has(symbol.name)) { + return true; + } + const predicate = (t) => containsAllTypesByName(t, allowAny, allowedNames, matchAnyInstead); + if (tsutils.isUnionOrIntersectionType(type)) { + return matchAnyInstead + ? type.types.some(predicate) + : type.types.every(predicate); + } + const bases = type.getBaseTypes(); + return (bases != null && + (matchAnyInstead + ? bases.some(predicate) + : bases.length > 0 && bases.every(predicate))); +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/discriminateAnyType.d.ts b/node_modules/@typescript-eslint/type-utils/dist/discriminateAnyType.d.ts new file mode 100644 index 00000000..af332ac8 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/discriminateAnyType.d.ts @@ -0,0 +1,13 @@ +import type * as ts from 'typescript'; +export declare enum AnyType { + Any = 0, + PromiseAny = 1, + AnyArray = 2, + Safe = 3 +} +/** + * @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, `AnyType.PromiseAny` if the type is `Promise`, + * otherwise it returns `AnyType.Safe`. + */ +export declare function discriminateAnyType(type: ts.Type, checker: ts.TypeChecker, program: ts.Program, tsNode: ts.Node): AnyType; +//# sourceMappingURL=discriminateAnyType.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/discriminateAnyType.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/discriminateAnyType.d.ts.map new file mode 100644 index 00000000..92d83713 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/discriminateAnyType.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"discriminateAnyType.d.ts","sourceRoot":"","sources":["../src/discriminateAnyType.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAMtC,oBAAY,OAAO;IACjB,GAAG,IAAA;IACH,UAAU,IAAA;IACV,QAAQ,IAAA;IACR,IAAI,IAAA;CACL;AACD;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,EAAE,EAAE,CAAC,WAAW,EACvB,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,MAAM,EAAE,EAAE,CAAC,IAAI,GACd,OAAO,CAET"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/discriminateAnyType.js b/node_modules/@typescript-eslint/type-utils/dist/discriminateAnyType.js new file mode 100644 index 00000000..6183386d --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/discriminateAnyType.js @@ -0,0 +1,77 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AnyType = void 0; +exports.discriminateAnyType = discriminateAnyType; +const tsutils = __importStar(require("ts-api-utils")); +const predicates_1 = require("./predicates"); +var AnyType; +(function (AnyType) { + AnyType[AnyType["Any"] = 0] = "Any"; + AnyType[AnyType["PromiseAny"] = 1] = "PromiseAny"; + AnyType[AnyType["AnyArray"] = 2] = "AnyArray"; + AnyType[AnyType["Safe"] = 3] = "Safe"; +})(AnyType || (exports.AnyType = AnyType = {})); +/** + * @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, `AnyType.PromiseAny` if the type is `Promise`, + * otherwise it returns `AnyType.Safe`. + */ +function discriminateAnyType(type, checker, program, tsNode) { + return discriminateAnyTypeWorker(type, checker, program, tsNode, new Set()); +} +function discriminateAnyTypeWorker(type, checker, program, tsNode, visited) { + if (visited.has(type)) { + return AnyType.Safe; + } + visited.add(type); + if ((0, predicates_1.isTypeAnyType)(type)) { + return AnyType.Any; + } + if ((0, predicates_1.isTypeAnyArrayType)(type, checker)) { + return AnyType.AnyArray; + } + for (const part of tsutils.typeConstituents(type)) { + if (tsutils.isThenableType(checker, tsNode, part)) { + const awaitedType = checker.getAwaitedType(part); + if (awaitedType) { + const awaitedAnyType = discriminateAnyTypeWorker(awaitedType, checker, program, tsNode, visited); + if (awaitedAnyType === AnyType.Any) { + return AnyType.PromiseAny; + } + } + } + } + return AnyType.Safe; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/getConstrainedTypeAtLocation.d.ts b/node_modules/@typescript-eslint/type-utils/dist/getConstrainedTypeAtLocation.d.ts new file mode 100644 index 00000000..54c27170 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getConstrainedTypeAtLocation.d.ts @@ -0,0 +1,13 @@ +import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/typescript-estree'; +import type * as ts from 'typescript'; +/** + * Resolves the given node's type. Will return the type's generic constraint, if it has one. + * + * Warning - if the type is generic and does _not_ have a constraint, the type will be + * returned as-is, rather than returning an `unknown` type. This can be checked + * for by checking for the type flag ts.TypeFlags.TypeParameter. + * + * @see https://github.com/typescript-eslint/typescript-eslint/issues/10438 + */ +export declare function getConstrainedTypeAtLocation(services: ParserServicesWithTypeInformation, node: TSESTree.Node): ts.Type; +//# sourceMappingURL=getConstrainedTypeAtLocation.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getConstrainedTypeAtLocation.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/getConstrainedTypeAtLocation.d.ts.map new file mode 100644 index 00000000..6248b21b --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getConstrainedTypeAtLocation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getConstrainedTypeAtLocation.d.ts","sourceRoot":"","sources":["../src/getConstrainedTypeAtLocation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EACjC,QAAQ,EACT,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC;;;;;;;;GAQG;AACH,wBAAgB,4BAA4B,CAC1C,QAAQ,EAAE,iCAAiC,EAC3C,IAAI,EAAE,QAAQ,CAAC,IAAI,GAClB,EAAE,CAAC,IAAI,CAOT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getConstrainedTypeAtLocation.js b/node_modules/@typescript-eslint/type-utils/dist/getConstrainedTypeAtLocation.js new file mode 100644 index 00000000..05af126d --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getConstrainedTypeAtLocation.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getConstrainedTypeAtLocation = getConstrainedTypeAtLocation; +/** + * Resolves the given node's type. Will return the type's generic constraint, if it has one. + * + * Warning - if the type is generic and does _not_ have a constraint, the type will be + * returned as-is, rather than returning an `unknown` type. This can be checked + * for by checking for the type flag ts.TypeFlags.TypeParameter. + * + * @see https://github.com/typescript-eslint/typescript-eslint/issues/10438 + */ +function getConstrainedTypeAtLocation(services, node) { + const nodeType = services.getTypeAtLocation(node); + const constrained = services.program + .getTypeChecker() + .getBaseConstraintOfType(nodeType); + return constrained ?? nodeType; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/getContextualType.d.ts b/node_modules/@typescript-eslint/type-utils/dist/getContextualType.d.ts new file mode 100644 index 00000000..cfd2c83a --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getContextualType.d.ts @@ -0,0 +1,8 @@ +import * as ts from 'typescript'; +/** + * Returns the contextual type of a given node. + * Contextual type is the type of the target the node is going into. + * i.e. the type of a called function's parameter, or the defined type of a variable declaration + */ +export declare function getContextualType(checker: ts.TypeChecker, node: ts.Expression): ts.Type | undefined; +//# sourceMappingURL=getContextualType.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getContextualType.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/getContextualType.d.ts.map new file mode 100644 index 00000000..4f66d460 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getContextualType.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getContextualType.d.ts","sourceRoot":"","sources":["../src/getContextualType.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC;;;;GAIG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,EAAE,CAAC,WAAW,EACvB,IAAI,EAAE,EAAE,CAAC,UAAU,GAClB,EAAE,CAAC,IAAI,GAAG,SAAS,CAwCrB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getContextualType.js b/node_modules/@typescript-eslint/type-utils/dist/getContextualType.js new file mode 100644 index 00000000..b67ef76d --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getContextualType.js @@ -0,0 +1,76 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getContextualType = getContextualType; +const ts = __importStar(require("typescript")); +/** + * Returns the contextual type of a given node. + * Contextual type is the type of the target the node is going into. + * i.e. the type of a called function's parameter, or the defined type of a variable declaration + */ +function getContextualType(checker, node) { + const parent = node.parent; + if (ts.isCallExpression(parent) || ts.isNewExpression(parent)) { + if (node === parent.expression) { + // is the callee, so has no contextual type + return; + } + } + else if (ts.isVariableDeclaration(parent) || + ts.isPropertyDeclaration(parent) || + ts.isParameter(parent)) { + return parent.type ? checker.getTypeFromTypeNode(parent.type) : undefined; + } + else if (ts.isJsxExpression(parent)) { + return checker.getContextualType(parent); + } + else if (ts.isIdentifier(node) && + (ts.isPropertyAssignment(parent) || + ts.isShorthandPropertyAssignment(parent))) { + return checker.getContextualType(node); + } + else if (ts.isBinaryExpression(parent) && + parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && + parent.right === node) { + // is RHS of assignment + return checker.getTypeAtLocation(parent.left); + } + else if (![ts.SyntaxKind.JsxExpression, ts.SyntaxKind.TemplateSpan].includes(parent.kind)) { + // parent is not something we know we can get the contextual type of + return; + } + // TODO - support return statement checking + return checker.getContextualType(node); +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/getDeclaration.d.ts b/node_modules/@typescript-eslint/type-utils/dist/getDeclaration.d.ts new file mode 100644 index 00000000..072056b3 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getDeclaration.d.ts @@ -0,0 +1,7 @@ +import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/typescript-estree'; +import type * as ts from 'typescript'; +/** + * Gets the declaration for the given variable + */ +export declare function getDeclaration(services: ParserServicesWithTypeInformation, node: TSESTree.Node): ts.Declaration | null; +//# sourceMappingURL=getDeclaration.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getDeclaration.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/getDeclaration.d.ts.map new file mode 100644 index 00000000..369214d8 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getDeclaration.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getDeclaration.d.ts","sourceRoot":"","sources":["../src/getDeclaration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EACjC,QAAQ,EACT,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC;;GAEG;AACH,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,iCAAiC,EAC3C,IAAI,EAAE,QAAQ,CAAC,IAAI,GAClB,EAAE,CAAC,WAAW,GAAG,IAAI,CAOvB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getDeclaration.js b/node_modules/@typescript-eslint/type-utils/dist/getDeclaration.js new file mode 100644 index 00000000..eba593d6 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getDeclaration.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDeclaration = getDeclaration; +/** + * Gets the declaration for the given variable + */ +function getDeclaration(services, node) { + const symbol = services.getSymbolAtLocation(node); + if (!symbol) { + return null; + } + const declarations = symbol.getDeclarations(); + return declarations?.[0] ?? null; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/getSourceFileOfNode.d.ts b/node_modules/@typescript-eslint/type-utils/dist/getSourceFileOfNode.d.ts new file mode 100644 index 00000000..7274e7b1 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getSourceFileOfNode.d.ts @@ -0,0 +1,7 @@ +import * as ts from 'typescript'; +/** + * @deprecated + * Gets the source file for a given node + */ +export declare function getSourceFileOfNode(node: ts.Node): ts.SourceFile; +//# sourceMappingURL=getSourceFileOfNode.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getSourceFileOfNode.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/getSourceFileOfNode.d.ts.map new file mode 100644 index 00000000..2558b1ea --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getSourceFileOfNode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getSourceFileOfNode.d.ts","sourceRoot":"","sources":["../src/getSourceFileOfNode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC,UAAU,CAKhE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getSourceFileOfNode.js b/node_modules/@typescript-eslint/type-utils/dist/getSourceFileOfNode.js new file mode 100644 index 00000000..3842a6ba --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getSourceFileOfNode.js @@ -0,0 +1,47 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSourceFileOfNode = getSourceFileOfNode; +const ts = __importStar(require("typescript")); +/** + * @deprecated + * Gets the source file for a given node + */ +function getSourceFileOfNode(node) { + while (node.kind !== ts.SyntaxKind.SourceFile) { + node = node.parent; + } + return node; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/getTypeName.d.ts b/node_modules/@typescript-eslint/type-utils/dist/getTypeName.d.ts new file mode 100644 index 00000000..0d7b92ae --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getTypeName.d.ts @@ -0,0 +1,8 @@ +import * as ts from 'typescript'; +/** + * Get the type name of a given type. + * @param typeChecker The context sensitive TypeScript TypeChecker. + * @param type The type to get the name of. + */ +export declare function getTypeName(typeChecker: ts.TypeChecker, type: ts.Type): string; +//# sourceMappingURL=getTypeName.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getTypeName.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/getTypeName.d.ts.map new file mode 100644 index 00000000..a598b0fe --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getTypeName.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getTypeName.d.ts","sourceRoot":"","sources":["../src/getTypeName.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,WAAW,EAAE,EAAE,CAAC,WAAW,EAC3B,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,MAAM,CAqDR"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/getTypeName.js b/node_modules/@typescript-eslint/type-utils/dist/getTypeName.js new file mode 100644 index 00000000..e78114f3 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/getTypeName.js @@ -0,0 +1,83 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getTypeName = getTypeName; +const ts = __importStar(require("typescript")); +/** + * Get the type name of a given type. + * @param typeChecker The context sensitive TypeScript TypeChecker. + * @param type The type to get the name of. + */ +function getTypeName(typeChecker, type) { + // It handles `string` and string literal types as string. + if ((type.flags & ts.TypeFlags.StringLike) !== 0) { + return 'string'; + } + // If the type is a type parameter which extends primitive string types, + // but it was not recognized as a string like. So check the constraint + // type of the type parameter. + if ((type.flags & ts.TypeFlags.TypeParameter) !== 0) { + // `type.getConstraint()` method doesn't return the constraint type of + // the type parameter for some reason. So this gets the constraint type + // via AST. + const symbol = type.getSymbol(); + const decls = symbol?.getDeclarations(); + const typeParamDecl = decls?.[0]; + if (typeParamDecl != null && + ts.isTypeParameterDeclaration(typeParamDecl) && + typeParamDecl.constraint != null) { + return getTypeName(typeChecker, typeChecker.getTypeFromTypeNode(typeParamDecl.constraint)); + } + } + // If the type is a union and all types in the union are string like, + // return `string`. For example: + // - `"a" | "b"` is string. + // - `string | string[]` is not string. + if (type.isUnion() && + type.types + .map(value => getTypeName(typeChecker, value)) + .every(t => t === 'string')) { + return 'string'; + } + // If the type is an intersection and a type in the intersection is string + // like, return `string`. For example: `string & {__htmlEscaped: void}` + if (type.isIntersection() && + type.types + .map(value => getTypeName(typeChecker, value)) + .some(t => t === 'string')) { + return 'string'; + } + return typeChecker.typeToString(type); +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/index.d.ts b/node_modules/@typescript-eslint/type-utils/dist/index.d.ts new file mode 100644 index 00000000..3fd97197 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/index.d.ts @@ -0,0 +1,18 @@ +export * from './builtinSymbolLikes'; +export * from './containsAllTypesByName'; +export * from './getConstrainedTypeAtLocation'; +export * from './getContextualType'; +export * from './getDeclaration'; +export * from './getSourceFileOfNode'; +export * from './getTypeName'; +export * from './isSymbolFromDefaultLibrary'; +export * from './isTypeReadonly'; +export * from './isUnsafeAssignment'; +export * from './predicates'; +export * from './propertyTypes'; +export * from './requiresQuoting'; +export * from './typeFlagUtils'; +export * from './TypeOrValueSpecifier'; +export * from './discriminateAnyType'; +export { getDecorators, getModifiers, typescriptVersionIsAtLeast, } from '@typescript-eslint/typescript-estree'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/index.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/index.d.ts.map new file mode 100644 index 00000000..98c6a176 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,eAAe,CAAC;AAC9B,cAAc,8BAA8B,CAAC;AAC7C,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,OAAO,EACL,aAAa,EACb,YAAY,EACZ,0BAA0B,GAC3B,MAAM,sCAAsC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/index.js b/node_modules/@typescript-eslint/type-utils/dist/index.js new file mode 100644 index 00000000..d98ca97d --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/index.js @@ -0,0 +1,37 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.typescriptVersionIsAtLeast = exports.getModifiers = exports.getDecorators = void 0; +__exportStar(require("./builtinSymbolLikes"), exports); +__exportStar(require("./containsAllTypesByName"), exports); +__exportStar(require("./getConstrainedTypeAtLocation"), exports); +__exportStar(require("./getContextualType"), exports); +__exportStar(require("./getDeclaration"), exports); +__exportStar(require("./getSourceFileOfNode"), exports); +__exportStar(require("./getTypeName"), exports); +__exportStar(require("./isSymbolFromDefaultLibrary"), exports); +__exportStar(require("./isTypeReadonly"), exports); +__exportStar(require("./isUnsafeAssignment"), exports); +__exportStar(require("./predicates"), exports); +__exportStar(require("./propertyTypes"), exports); +__exportStar(require("./requiresQuoting"), exports); +__exportStar(require("./typeFlagUtils"), exports); +__exportStar(require("./TypeOrValueSpecifier"), exports); +__exportStar(require("./discriminateAnyType"), exports); +var typescript_estree_1 = require("@typescript-eslint/typescript-estree"); +Object.defineProperty(exports, "getDecorators", { enumerable: true, get: function () { return typescript_estree_1.getDecorators; } }); +Object.defineProperty(exports, "getModifiers", { enumerable: true, get: function () { return typescript_estree_1.getModifiers; } }); +Object.defineProperty(exports, "typescriptVersionIsAtLeast", { enumerable: true, get: function () { return typescript_estree_1.typescriptVersionIsAtLeast; } }); diff --git a/node_modules/@typescript-eslint/type-utils/dist/isSymbolFromDefaultLibrary.d.ts b/node_modules/@typescript-eslint/type-utils/dist/isSymbolFromDefaultLibrary.d.ts new file mode 100644 index 00000000..e620443e --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/isSymbolFromDefaultLibrary.d.ts @@ -0,0 +1,3 @@ +import type * as ts from 'typescript'; +export declare function isSymbolFromDefaultLibrary(program: ts.Program, symbol: ts.Symbol | undefined): boolean; +//# sourceMappingURL=isSymbolFromDefaultLibrary.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/isSymbolFromDefaultLibrary.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/isSymbolFromDefaultLibrary.d.ts.map new file mode 100644 index 00000000..9e4009e3 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/isSymbolFromDefaultLibrary.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isSymbolFromDefaultLibrary.d.ts","sourceRoot":"","sources":["../src/isSymbolFromDefaultLibrary.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,MAAM,EAAE,EAAE,CAAC,MAAM,GAAG,SAAS,GAC5B,OAAO,CAcT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/isSymbolFromDefaultLibrary.js b/node_modules/@typescript-eslint/type-utils/dist/isSymbolFromDefaultLibrary.js new file mode 100644 index 00000000..4eba2152 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/isSymbolFromDefaultLibrary.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isSymbolFromDefaultLibrary = isSymbolFromDefaultLibrary; +function isSymbolFromDefaultLibrary(program, symbol) { + if (!symbol) { + return false; + } + const declarations = symbol.getDeclarations() ?? []; + for (const declaration of declarations) { + const sourceFile = declaration.getSourceFile(); + if (program.isSourceFileDefaultLibrary(sourceFile)) { + return true; + } + } + return false; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/isTypeReadonly.d.ts b/node_modules/@typescript-eslint/type-utils/dist/isTypeReadonly.d.ts new file mode 100644 index 00000000..182042be --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/isTypeReadonly.d.ts @@ -0,0 +1,101 @@ +import * as ts from 'typescript'; +import type { TypeOrValueSpecifier } from './TypeOrValueSpecifier'; +export interface ReadonlynessOptions { + readonly allow?: TypeOrValueSpecifier[]; + readonly treatMethodsAsReadonly?: boolean; +} +export declare const readonlynessOptionsSchema: { + additionalProperties: false; + properties: { + allow: { + readonly items: { + readonly oneOf: [{ + readonly type: "string"; + }, { + readonly additionalProperties: false; + readonly properties: { + readonly from: { + readonly enum: ["file"]; + readonly type: "string"; + }; + readonly name: { + readonly oneOf: [{ + readonly type: "string"; + }, { + readonly items: { + readonly type: "string"; + }; + readonly minItems: 1; + readonly type: "array"; + readonly uniqueItems: true; + }]; + }; + readonly path: { + readonly type: "string"; + }; + }; + readonly required: ["from", "name"]; + readonly type: "object"; + }, { + readonly additionalProperties: false; + readonly properties: { + readonly from: { + readonly enum: ["lib"]; + readonly type: "string"; + }; + readonly name: { + readonly oneOf: [{ + readonly type: "string"; + }, { + readonly items: { + readonly type: "string"; + }; + readonly minItems: 1; + readonly type: "array"; + readonly uniqueItems: true; + }]; + }; + }; + readonly required: ["from", "name"]; + readonly type: "object"; + }, { + readonly additionalProperties: false; + readonly properties: { + readonly from: { + readonly enum: ["package"]; + readonly type: "string"; + }; + readonly name: { + readonly oneOf: [{ + readonly type: "string"; + }, { + readonly items: { + readonly type: "string"; + }; + readonly minItems: 1; + readonly type: "array"; + readonly uniqueItems: true; + }]; + }; + readonly package: { + readonly type: "string"; + }; + }; + readonly required: ["from", "name", "package"]; + readonly type: "object"; + }]; + }; + readonly type: "array"; + }; + treatMethodsAsReadonly: { + type: "boolean"; + }; + }; + type: "object"; +}; +export declare const readonlynessOptionsDefaults: ReadonlynessOptions; +/** + * Checks if the given type is readonly + */ +export declare function isTypeReadonly(program: ts.Program, type: ts.Type, options?: ReadonlynessOptions): boolean; +//# sourceMappingURL=isTypeReadonly.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/isTypeReadonly.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/isTypeReadonly.d.ts.map new file mode 100644 index 00000000..e2749b0a --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/isTypeReadonly.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isTypeReadonly.d.ts","sourceRoot":"","sources":["../src/isTypeReadonly.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAiBnE,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,KAAK,CAAC,EAAE,oBAAoB,EAAE,CAAC;IACxC,QAAQ,CAAC,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAC3C;AAED,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CASf,CAAC;AAExB,eAAO,MAAM,2BAA2B,EAAE,mBAGzC,CAAC;AAgSF;;GAEG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,GAAE,mBAAiD,GACzD,OAAO,CAKT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/isTypeReadonly.js b/node_modules/@typescript-eslint/type-utils/dist/isTypeReadonly.js new file mode 100644 index 00000000..1957b7d4 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/isTypeReadonly.js @@ -0,0 +1,241 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readonlynessOptionsDefaults = exports.readonlynessOptionsSchema = void 0; +exports.isTypeReadonly = isTypeReadonly; +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const propertyTypes_1 = require("./propertyTypes"); +const TypeOrValueSpecifier_1 = require("./TypeOrValueSpecifier"); +var Readonlyness; +(function (Readonlyness) { + /** the type cannot be handled by the function */ + Readonlyness[Readonlyness["UnknownType"] = 1] = "UnknownType"; + /** the type is mutable */ + Readonlyness[Readonlyness["Mutable"] = 2] = "Mutable"; + /** the type is readonly */ + Readonlyness[Readonlyness["Readonly"] = 3] = "Readonly"; +})(Readonlyness || (Readonlyness = {})); +exports.readonlynessOptionsSchema = { + additionalProperties: false, + properties: { + allow: TypeOrValueSpecifier_1.typeOrValueSpecifiersSchema, + treatMethodsAsReadonly: { + type: 'boolean', + }, + }, + type: 'object', +}; +exports.readonlynessOptionsDefaults = { + allow: [], + treatMethodsAsReadonly: false, +}; +function hasSymbol(node) { + return Object.hasOwn(node, 'symbol'); +} +function isTypeReadonlyArrayOrTuple(program, type, options, seenTypes) { + const checker = program.getTypeChecker(); + function checkTypeArguments(arrayType) { + const typeArguments = checker.getTypeArguments(arrayType); + // this shouldn't happen in reality as: + // - tuples require at least 1 type argument + // - ReadonlyArray requires at least 1 type argument + /* istanbul ignore if */ if (typeArguments.length === 0) { + return Readonlyness.Readonly; + } + // validate the element types are also readonly + if (typeArguments.some(typeArg => isTypeReadonlyRecurser(program, typeArg, options, seenTypes) === + Readonlyness.Mutable)) { + return Readonlyness.Mutable; + } + return Readonlyness.Readonly; + } + if (checker.isArrayType(type)) { + const symbol = utils_1.ESLintUtils.nullThrows(type.getSymbol(), utils_1.ESLintUtils.NullThrowsReasons.MissingToken('symbol', 'array type')); + const escapedName = symbol.getEscapedName(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison + if (escapedName === 'Array') { + return Readonlyness.Mutable; + } + return checkTypeArguments(type); + } + if (checker.isTupleType(type)) { + if (!type.target.readonly) { + return Readonlyness.Mutable; + } + return checkTypeArguments(type); + } + return Readonlyness.UnknownType; +} +function isTypeReadonlyObject(program, type, options, seenTypes) { + const checker = program.getTypeChecker(); + function checkIndexSignature(kind) { + const indexInfo = checker.getIndexInfoOfType(type, kind); + if (indexInfo) { + if (!indexInfo.isReadonly) { + return Readonlyness.Mutable; + } + if (indexInfo.type === type || seenTypes.has(indexInfo.type)) { + return Readonlyness.Readonly; + } + return isTypeReadonlyRecurser(program, indexInfo.type, options, seenTypes); + } + return Readonlyness.UnknownType; + } + const properties = type.getProperties(); + if (properties.length) { + // ensure the properties are marked as readonly + for (const property of properties) { + if (options.treatMethodsAsReadonly) { + if (property.valueDeclaration != null && + hasSymbol(property.valueDeclaration) && + tsutils.isSymbolFlagSet(property.valueDeclaration.symbol, ts.SymbolFlags.Method)) { + continue; + } + const declarations = property.getDeclarations(); + const lastDeclaration = declarations != null && declarations.length > 0 + ? declarations[declarations.length - 1] + : undefined; + if (lastDeclaration != null && + hasSymbol(lastDeclaration) && + tsutils.isSymbolFlagSet(lastDeclaration.symbol, ts.SymbolFlags.Method)) { + continue; + } + } + if (tsutils.isPropertyReadonlyInType(type, property.getEscapedName(), checker)) { + continue; + } + const name = ts.getNameOfDeclaration(property.valueDeclaration); + if (name && ts.isPrivateIdentifier(name)) { + continue; + } + return Readonlyness.Mutable; + } + // all properties were readonly + // now ensure that all of the values are readonly also. + // do this after checking property readonly-ness as a perf optimization, + // as we might be able to bail out early due to a mutable property before + // doing this deep, potentially expensive check. + for (const property of properties) { + const propertyType = utils_1.ESLintUtils.nullThrows((0, propertyTypes_1.getTypeOfPropertyOfType)(checker, type, property), utils_1.ESLintUtils.NullThrowsReasons.MissingToken(`property "${property.name}"`, 'type')); + // handle recursive types. + // we only need this simple check, because a mutable recursive type will break via the above prop readonly check + if (seenTypes.has(propertyType)) { + continue; + } + if (isTypeReadonlyRecurser(program, propertyType, options, seenTypes) === + Readonlyness.Mutable) { + return Readonlyness.Mutable; + } + } + } + const isStringIndexSigReadonly = checkIndexSignature(ts.IndexKind.String); + if (isStringIndexSigReadonly === Readonlyness.Mutable) { + return isStringIndexSigReadonly; + } + const isNumberIndexSigReadonly = checkIndexSignature(ts.IndexKind.Number); + if (isNumberIndexSigReadonly === Readonlyness.Mutable) { + return isNumberIndexSigReadonly; + } + return Readonlyness.Readonly; +} +// a helper function to ensure the seenTypes map is always passed down, except by the external caller +function isTypeReadonlyRecurser(program, type, options, seenTypes) { + const checker = program.getTypeChecker(); + seenTypes.add(type); + if ((0, TypeOrValueSpecifier_1.typeMatchesSomeSpecifier)(type, options.allow, program)) { + return Readonlyness.Readonly; + } + if (tsutils.isUnionType(type)) { + // all types in the union must be readonly + const result = tsutils + .unionConstituents(type) + .every(t => seenTypes.has(t) || + isTypeReadonlyRecurser(program, t, options, seenTypes) === + Readonlyness.Readonly); + const readonlyness = result ? Readonlyness.Readonly : Readonlyness.Mutable; + return readonlyness; + } + if (tsutils.isIntersectionType(type)) { + // Special case for handling arrays/tuples (as readonly arrays/tuples always have mutable methods). + if (type.types.some(t => checker.isArrayType(t) || checker.isTupleType(t))) { + const allReadonlyParts = type.types.every(t => seenTypes.has(t) || + isTypeReadonlyRecurser(program, t, options, seenTypes) === + Readonlyness.Readonly); + return allReadonlyParts ? Readonlyness.Readonly : Readonlyness.Mutable; + } + // Normal case. + const isReadonlyObject = isTypeReadonlyObject(program, type, options, seenTypes); + if (isReadonlyObject !== Readonlyness.UnknownType) { + return isReadonlyObject; + } + } + if (tsutils.isConditionalType(type)) { + const result = [type.root.node.trueType, type.root.node.falseType] + .map(checker.getTypeFromTypeNode) + .every(t => seenTypes.has(t) || + isTypeReadonlyRecurser(program, t, options, seenTypes) === + Readonlyness.Readonly); + const readonlyness = result ? Readonlyness.Readonly : Readonlyness.Mutable; + return readonlyness; + } + // all non-object, non-intersection types are readonly. + // this should only be primitive types + if (!tsutils.isObjectType(type)) { + return Readonlyness.Readonly; + } + // pure function types are readonly + if (type.getCallSignatures().length > 0 && + type.getProperties().length === 0) { + return Readonlyness.Readonly; + } + const isReadonlyArray = isTypeReadonlyArrayOrTuple(program, type, options, seenTypes); + if (isReadonlyArray !== Readonlyness.UnknownType) { + return isReadonlyArray; + } + const isReadonlyObject = isTypeReadonlyObject(program, type, options, seenTypes); + /* istanbul ignore else */ if (isReadonlyObject !== Readonlyness.UnknownType) { + return isReadonlyObject; + } + throw new Error('Unhandled type'); +} +/** + * Checks if the given type is readonly + */ +function isTypeReadonly(program, type, options = exports.readonlynessOptionsDefaults) { + return (isTypeReadonlyRecurser(program, type, options, new Set()) === + Readonlyness.Readonly); +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/isUnsafeAssignment.d.ts b/node_modules/@typescript-eslint/type-utils/dist/isUnsafeAssignment.d.ts new file mode 100644 index 00000000..97b9c3e1 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/isUnsafeAssignment.d.ts @@ -0,0 +1,17 @@ +import type { TSESTree } from '@typescript-eslint/utils'; +import type * as ts from 'typescript'; +/** + * Does a simple check to see if there is an any being assigned to a non-any type. + * + * This also checks generic positions to ensure there's no unsafe sub-assignments. + * Note: in the case of generic positions, it makes the assumption that the two types are the same. + * + * @example See tests for examples + * + * @returns false if it's safe, or an object with the two types if it's unsafe + */ +export declare function isUnsafeAssignment(type: ts.Type, receiver: ts.Type, checker: ts.TypeChecker, senderNode: TSESTree.Node | null): false | { + receiver: ts.Type; + sender: ts.Type; +}; +//# sourceMappingURL=isUnsafeAssignment.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/isUnsafeAssignment.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/isUnsafeAssignment.d.ts.map new file mode 100644 index 00000000..6d2fd1fb --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/isUnsafeAssignment.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isUnsafeAssignment.d.ts","sourceRoot":"","sources":["../src/isUnsafeAssignment.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAOtC;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,QAAQ,EAAE,EAAE,CAAC,IAAI,EACjB,OAAO,EAAE,EAAE,CAAC,WAAW,EACvB,UAAU,EAAE,QAAQ,CAAC,IAAI,GAAG,IAAI,GAC/B,KAAK,GAAG;IAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC;IAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAA;CAAE,CAQhD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/isUnsafeAssignment.js b/node_modules/@typescript-eslint/type-utils/dist/isUnsafeAssignment.js new file mode 100644 index 00000000..2fde82e6 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/isUnsafeAssignment.js @@ -0,0 +1,114 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isUnsafeAssignment = isUnsafeAssignment; +const utils_1 = require("@typescript-eslint/utils"); +const tsutils = __importStar(require("ts-api-utils")); +const predicates_1 = require("./predicates"); +/** + * Does a simple check to see if there is an any being assigned to a non-any type. + * + * This also checks generic positions to ensure there's no unsafe sub-assignments. + * Note: in the case of generic positions, it makes the assumption that the two types are the same. + * + * @example See tests for examples + * + * @returns false if it's safe, or an object with the two types if it's unsafe + */ +function isUnsafeAssignment(type, receiver, checker, senderNode) { + return isUnsafeAssignmentWorker(type, receiver, checker, senderNode, new Map()); +} +function isUnsafeAssignmentWorker(type, receiver, checker, senderNode, visited) { + if ((0, predicates_1.isTypeAnyType)(type)) { + // Allow assignment of any ==> unknown. + if ((0, predicates_1.isTypeUnknownType)(receiver)) { + return false; + } + if (!(0, predicates_1.isTypeAnyType)(receiver)) { + return { receiver, sender: type }; + } + } + const typeAlreadyVisited = visited.get(type); + if (typeAlreadyVisited) { + if (typeAlreadyVisited.has(receiver)) { + return false; + } + typeAlreadyVisited.add(receiver); + } + else { + visited.set(type, new Set([receiver])); + } + if (tsutils.isTypeReference(type) && tsutils.isTypeReference(receiver)) { + // TODO - figure out how to handle cases like this, + // where the types are assignable, but not the same type + /* + function foo(): ReadonlySet { return new Set(); } + + // and + + type Test = { prop: T } + type Test2 = { prop: string } + declare const a: Test; + const b: Test2 = a; + */ + if (type.target !== receiver.target) { + // if the type references are different, assume safe, as we won't know how to compare the two types + // the generic positions might not be equivalent for both types + return false; + } + if (senderNode?.type === utils_1.AST_NODE_TYPES.NewExpression && + senderNode.callee.type === utils_1.AST_NODE_TYPES.Identifier && + senderNode.callee.name === 'Map' && + senderNode.arguments.length === 0 && + senderNode.typeArguments == null) { + // special case to handle `new Map()` + // unfortunately Map's default empty constructor is typed to return `Map` :( + // https://github.com/typescript-eslint/typescript-eslint/issues/2109#issuecomment-634144396 + return false; + } + const typeArguments = type.typeArguments ?? []; + const receiverTypeArguments = receiver.typeArguments ?? []; + for (let i = 0; i < typeArguments.length; i += 1) { + const arg = typeArguments[i]; + const receiverArg = receiverTypeArguments[i]; + const unsafe = isUnsafeAssignmentWorker(arg, receiverArg, checker, senderNode, visited); + if (unsafe) { + return { receiver, sender: type }; + } + } + return false; + } + return false; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/predicates.d.ts b/node_modules/@typescript-eslint/type-utils/dist/predicates.d.ts new file mode 100644 index 00000000..09222929 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/predicates.d.ts @@ -0,0 +1,38 @@ +import * as ts from 'typescript'; +/** + * Checks if the given type is (or accepts) nullable + */ +export declare function isNullableType(type: ts.Type): boolean; +/** + * Checks if the given type is either an array type, + * or a union made up solely of array types. + */ +export declare function isTypeArrayTypeOrUnionOfArrayTypes(type: ts.Type, checker: ts.TypeChecker): boolean; +/** + * @returns true if the type is `never` + */ +export declare function isTypeNeverType(type: ts.Type): boolean; +/** + * @returns true if the type is `unknown` + */ +export declare function isTypeUnknownType(type: ts.Type): boolean; +export declare function isTypeReferenceType(type: ts.Type): type is ts.TypeReference; +/** + * @returns true if the type is `any` + */ +export declare function isTypeAnyType(type: ts.Type): boolean; +/** + * @returns true if the type is `any[]` + */ +export declare function isTypeAnyArrayType(type: ts.Type, checker: ts.TypeChecker): boolean; +/** + * @returns true if the type is `unknown[]` + */ +export declare function isTypeUnknownArrayType(type: ts.Type, checker: ts.TypeChecker): boolean; +/** + * @returns Whether a type is an instance of the parent type, including for the parent's base types. + */ +export declare function typeIsOrHasBaseType(type: ts.Type, parentType: ts.Type): boolean; +export declare function isTypeBigIntLiteralType(type: ts.Type): type is ts.BigIntLiteralType; +export declare function isTypeTemplateLiteralType(type: ts.Type): type is ts.TemplateLiteralType; +//# sourceMappingURL=predicates.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/predicates.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/predicates.d.ts.map new file mode 100644 index 00000000..53441204 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/predicates.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"predicates.d.ts","sourceRoot":"","sources":["../src/predicates.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAMjC;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CASrD;AAED;;;GAGG;AACH,wBAAgB,kCAAkC,CAChD,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,EAAE,EAAE,CAAC,WAAW,GACtB,OAAO,CAQT;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAEtD;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAExD;AAYD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,aAAa,CAM3E;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAQpD;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,EAAE,EAAE,CAAC,WAAW,GACtB,OAAO,CAKT;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,EAAE,EAAE,CAAC,WAAW,GACtB,OAAO,CAKT;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,UAAU,EAAE,EAAE,CAAC,IAAI,GAClB,OAAO,CAqBT;AAED,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,IAAI,IAAI,EAAE,CAAC,iBAAiB,CAE9B;AAED,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,IAAI,IAAI,EAAE,CAAC,mBAAmB,CAEhC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/predicates.js b/node_modules/@typescript-eslint/type-utils/dist/predicates.js new file mode 100644 index 00000000..85b46a62 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/predicates.js @@ -0,0 +1,157 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isNullableType = isNullableType; +exports.isTypeArrayTypeOrUnionOfArrayTypes = isTypeArrayTypeOrUnionOfArrayTypes; +exports.isTypeNeverType = isTypeNeverType; +exports.isTypeUnknownType = isTypeUnknownType; +exports.isTypeReferenceType = isTypeReferenceType; +exports.isTypeAnyType = isTypeAnyType; +exports.isTypeAnyArrayType = isTypeAnyArrayType; +exports.isTypeUnknownArrayType = isTypeUnknownArrayType; +exports.typeIsOrHasBaseType = typeIsOrHasBaseType; +exports.isTypeBigIntLiteralType = isTypeBigIntLiteralType; +exports.isTypeTemplateLiteralType = isTypeTemplateLiteralType; +const debug_1 = __importDefault(require("debug")); +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const typeFlagUtils_1 = require("./typeFlagUtils"); +const log = (0, debug_1.default)('typescript-eslint:type-utils:predicates'); +/** + * Checks if the given type is (or accepts) nullable + */ +function isNullableType(type) { + return (0, typeFlagUtils_1.isTypeFlagSet)(type, ts.TypeFlags.Any | + ts.TypeFlags.Unknown | + ts.TypeFlags.Null | + ts.TypeFlags.Undefined | + ts.TypeFlags.Void); +} +/** + * Checks if the given type is either an array type, + * or a union made up solely of array types. + */ +function isTypeArrayTypeOrUnionOfArrayTypes(type, checker) { + for (const t of tsutils.unionConstituents(type)) { + if (!checker.isArrayType(t)) { + return false; + } + } + return true; +} +/** + * @returns true if the type is `never` + */ +function isTypeNeverType(type) { + return (0, typeFlagUtils_1.isTypeFlagSet)(type, ts.TypeFlags.Never); +} +/** + * @returns true if the type is `unknown` + */ +function isTypeUnknownType(type) { + return (0, typeFlagUtils_1.isTypeFlagSet)(type, ts.TypeFlags.Unknown); +} +// https://github.com/microsoft/TypeScript/blob/42aa18bf442c4df147e30deaf27261a41cbdc617/src/compiler/types.ts#L5157 +const Nullable = ts.TypeFlags.Undefined | ts.TypeFlags.Null; +// https://github.com/microsoft/TypeScript/blob/42aa18bf442c4df147e30deaf27261a41cbdc617/src/compiler/types.ts#L5187 +const ObjectFlagsType = ts.TypeFlags.Any | + Nullable | + ts.TypeFlags.Never | + ts.TypeFlags.Object | + ts.TypeFlags.Union | + ts.TypeFlags.Intersection; +function isTypeReferenceType(type) { + if ((type.flags & ObjectFlagsType) === 0) { + return false; + } + const objectTypeFlags = type.objectFlags; + return (objectTypeFlags & ts.ObjectFlags.Reference) !== 0; +} +/** + * @returns true if the type is `any` + */ +function isTypeAnyType(type) { + if ((0, typeFlagUtils_1.isTypeFlagSet)(type, ts.TypeFlags.Any)) { + if (type.intrinsicName === 'error') { + log('Found an "error" any type'); + } + return true; + } + return false; +} +/** + * @returns true if the type is `any[]` + */ +function isTypeAnyArrayType(type, checker) { + return (checker.isArrayType(type) && + isTypeAnyType(checker.getTypeArguments(type)[0])); +} +/** + * @returns true if the type is `unknown[]` + */ +function isTypeUnknownArrayType(type, checker) { + return (checker.isArrayType(type) && + isTypeUnknownType(checker.getTypeArguments(type)[0])); +} +/** + * @returns Whether a type is an instance of the parent type, including for the parent's base types. + */ +function typeIsOrHasBaseType(type, parentType) { + const parentSymbol = parentType.getSymbol(); + if (!type.getSymbol() || !parentSymbol) { + return false; + } + const typeAndBaseTypes = [type]; + const ancestorTypes = type.getBaseTypes(); + if (ancestorTypes) { + typeAndBaseTypes.push(...ancestorTypes); + } + for (const baseType of typeAndBaseTypes) { + const baseSymbol = baseType.getSymbol(); + if (baseSymbol && baseSymbol.name === parentSymbol.name) { + return true; + } + } + return false; +} +function isTypeBigIntLiteralType(type) { + return (0, typeFlagUtils_1.isTypeFlagSet)(type, ts.TypeFlags.BigIntLiteral); +} +function isTypeTemplateLiteralType(type) { + return (0, typeFlagUtils_1.isTypeFlagSet)(type, ts.TypeFlags.TemplateLiteral); +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/propertyTypes.d.ts b/node_modules/@typescript-eslint/type-utils/dist/propertyTypes.d.ts new file mode 100644 index 00000000..068d208e --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/propertyTypes.d.ts @@ -0,0 +1,4 @@ +import type * as ts from 'typescript'; +export declare function getTypeOfPropertyOfName(checker: ts.TypeChecker, type: ts.Type, name: string, escapedName?: ts.__String): ts.Type | undefined; +export declare function getTypeOfPropertyOfType(checker: ts.TypeChecker, type: ts.Type, property: ts.Symbol): ts.Type | undefined; +//# sourceMappingURL=propertyTypes.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/propertyTypes.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/propertyTypes.d.ts.map new file mode 100644 index 00000000..214952c1 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/propertyTypes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"propertyTypes.d.ts","sourceRoot":"","sources":["../src/propertyTypes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,EAAE,CAAC,WAAW,EACvB,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,IAAI,EAAE,MAAM,EACZ,WAAW,CAAC,EAAE,EAAE,CAAC,QAAQ,GACxB,EAAE,CAAC,IAAI,GAAG,SAAS,CAerB;AAED,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,EAAE,CAAC,WAAW,EACvB,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,QAAQ,EAAE,EAAE,CAAC,MAAM,GAClB,EAAE,CAAC,IAAI,GAAG,SAAS,CAOrB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/propertyTypes.js b/node_modules/@typescript-eslint/type-utils/dist/propertyTypes.js new file mode 100644 index 00000000..d2c95a69 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/propertyTypes.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getTypeOfPropertyOfName = getTypeOfPropertyOfName; +exports.getTypeOfPropertyOfType = getTypeOfPropertyOfType; +function getTypeOfPropertyOfName(checker, type, name, escapedName) { + // Most names are directly usable in the checker and aren't different from escaped names + if (!escapedName || !isSymbol(escapedName)) { + return checker.getTypeOfPropertyOfType(type, name); + } + // Symbolic names may differ in their escaped name compared to their human-readable name + // https://github.com/typescript-eslint/typescript-eslint/issues/2143 + const escapedProperty = type + .getProperties() + .find(property => property.escapedName === escapedName); + return escapedProperty + ? checker.getDeclaredTypeOfSymbol(escapedProperty) + : undefined; +} +function getTypeOfPropertyOfType(checker, type, property) { + return getTypeOfPropertyOfName(checker, type, property.getName(), property.getEscapedName()); +} +// Symbolic names need to be specially handled because TS api is not sufficient for these cases. +// Source based on: +// https://github.com/microsoft/TypeScript/blob/0043abe982aae0d35f8df59f9715be6ada758ff7/src/compiler/utilities.ts#L3388-L3402 +function isSymbol(escapedName) { + return isKnownSymbol(escapedName) || isPrivateIdentifierSymbol(escapedName); +} +// case for escapedName: "__@foo@10", name: "__@foo@10" +function isKnownSymbol(escapedName) { + return escapedName.startsWith('__@'); +} +// case for escapedName: "__#1@#foo", name: "#foo" +function isPrivateIdentifierSymbol(escapedName) { + return escapedName.startsWith('__#'); +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/requiresQuoting.d.ts b/node_modules/@typescript-eslint/type-utils/dist/requiresQuoting.d.ts new file mode 100644 index 00000000..c2fd035f --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/requiresQuoting.d.ts @@ -0,0 +1,4 @@ +import * as ts from 'typescript'; +/*** Indicates whether identifiers require the use of quotation marks when accessing property definitions and dot notation. */ +export declare function requiresQuoting(name: string, target?: ts.ScriptTarget): boolean; +//# sourceMappingURL=requiresQuoting.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/requiresQuoting.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/requiresQuoting.d.ts.map new file mode 100644 index 00000000..faa85ea8 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/requiresQuoting.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"requiresQuoting.d.ts","sourceRoot":"","sources":["../src/requiresQuoting.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AACjC,8HAA8H;AAC9H,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,EACZ,MAAM,GAAE,EAAE,CAAC,YAAqC,GAC/C,OAAO,CAgBT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/requiresQuoting.js b/node_modules/@typescript-eslint/type-utils/dist/requiresQuoting.js new file mode 100644 index 00000000..1f2b379b --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/requiresQuoting.js @@ -0,0 +1,52 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.requiresQuoting = requiresQuoting; +const ts = __importStar(require("typescript")); +/*** Indicates whether identifiers require the use of quotation marks when accessing property definitions and dot notation. */ +function requiresQuoting(name, target = ts.ScriptTarget.ESNext) { + if (name.length === 0) { + return true; + } + if (!ts.isIdentifierStart(name.charCodeAt(0), target)) { + return true; + } + for (let i = 1; i < name.length; i += 1) { + if (!ts.isIdentifierPart(name.charCodeAt(i), target)) { + return true; + } + } + return false; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeFlagUtils.d.ts b/node_modules/@typescript-eslint/type-utils/dist/typeFlagUtils.d.ts new file mode 100644 index 00000000..b2e4757f --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeFlagUtils.d.ts @@ -0,0 +1,18 @@ +import * as ts from 'typescript'; +/** + * Gets all of the type flags in a type, iterating through unions automatically. + */ +export declare function getTypeFlags(type: ts.Type): ts.TypeFlags; +/** + * @param flagsToCheck The composition of one or more `ts.TypeFlags`. + * @param isReceiver Whether the type is a receiving type (e.g. the type of a + * called function's parameter). + * @remarks + * Note that if the type is a union, this function will decompose it into the + * parts and get the flags of every union constituent. If this is not desired, + * use the `isTypeFlag` function from tsutils. + */ +export declare function isTypeFlagSet(type: ts.Type, flagsToCheck: ts.TypeFlags, +/** @deprecated This params is not used and will be removed in the future.*/ +isReceiver?: boolean): boolean; +//# sourceMappingURL=typeFlagUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeFlagUtils.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/typeFlagUtils.d.ts.map new file mode 100644 index 00000000..44c0c484 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeFlagUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"typeFlagUtils.d.ts","sourceRoot":"","sources":["../src/typeFlagUtils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAIjC;;GAEG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC,SAAS,CAOxD;AAED;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,YAAY,EAAE,EAAE,CAAC,SAAS;AAC1B,4EAA4E;AAC5E,UAAU,CAAC,EAAE,OAAO,GACnB,OAAO,CAST"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeFlagUtils.js b/node_modules/@typescript-eslint/type-utils/dist/typeFlagUtils.js new file mode 100644 index 00000000..63102096 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeFlagUtils.js @@ -0,0 +1,70 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getTypeFlags = getTypeFlags; +exports.isTypeFlagSet = isTypeFlagSet; +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const ANY_OR_UNKNOWN = ts.TypeFlags.Any | ts.TypeFlags.Unknown; +/** + * Gets all of the type flags in a type, iterating through unions automatically. + */ +function getTypeFlags(type) { + // @ts-expect-error Since typescript 5.0, this is invalid, but uses 0 as the default value of TypeFlags. + let flags = 0; + for (const t of tsutils.unionConstituents(type)) { + flags |= t.flags; + } + return flags; +} +/** + * @param flagsToCheck The composition of one or more `ts.TypeFlags`. + * @param isReceiver Whether the type is a receiving type (e.g. the type of a + * called function's parameter). + * @remarks + * Note that if the type is a union, this function will decompose it into the + * parts and get the flags of every union constituent. If this is not desired, + * use the `isTypeFlag` function from tsutils. + */ +function isTypeFlagSet(type, flagsToCheck, +/** @deprecated This params is not used and will be removed in the future.*/ +isReceiver) { + const flags = getTypeFlags(type); + // eslint-disable-next-line @typescript-eslint/no-deprecated -- not used + if (isReceiver && flags & ANY_OR_UNKNOWN) { + return true; + } + return (flags & flagsToCheck) !== 0; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/specifierNameMatches.d.ts b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/specifierNameMatches.d.ts new file mode 100644 index 00000000..66eefe47 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/specifierNameMatches.d.ts @@ -0,0 +1,3 @@ +import type * as ts from 'typescript'; +export declare function specifierNameMatches(type: ts.Type, names: string | string[]): boolean; +//# sourceMappingURL=specifierNameMatches.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/specifierNameMatches.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/specifierNameMatches.d.ts.map new file mode 100644 index 00000000..271cfb7a --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/specifierNameMatches.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"specifierNameMatches.d.ts","sourceRoot":"","sources":["../../src/typeOrValueSpecifiers/specifierNameMatches.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GACvB,OAAO,CAeT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/specifierNameMatches.js b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/specifierNameMatches.js new file mode 100644 index 00000000..ac91b763 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/specifierNameMatches.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.specifierNameMatches = specifierNameMatches; +function specifierNameMatches(type, names) { + if (typeof names === 'string') { + names = [names]; + } + const symbol = type.aliasSymbol ?? type.getSymbol(); + const candidateNames = symbol + ? [symbol.escapedName, type.intrinsicName] + : [type.intrinsicName]; + if (names.some(item => candidateNames.includes(item))) { + return true; + } + return false; +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInFile.d.ts b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInFile.d.ts new file mode 100644 index 00000000..26166c7f --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInFile.d.ts @@ -0,0 +1,3 @@ +import type * as ts from 'typescript'; +export declare function typeDeclaredInFile(relativePath: string | undefined, declarationFiles: ts.SourceFile[], program: ts.Program): boolean; +//# sourceMappingURL=typeDeclaredInFile.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInFile.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInFile.d.ts.map new file mode 100644 index 00000000..3e278d80 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInFile.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"typeDeclaredInFile.d.ts","sourceRoot":"","sources":["../../src/typeOrValueSpecifiers/typeDeclaredInFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAKtC,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,gBAAgB,EAAE,EAAE,CAAC,UAAU,EAAE,EACjC,OAAO,EAAE,EAAE,CAAC,OAAO,GAClB,OAAO,CAaT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInFile.js b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInFile.js new file mode 100644 index 00000000..95306494 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInFile.js @@ -0,0 +1,16 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.typeDeclaredInFile = typeDeclaredInFile; +const typescript_estree_1 = require("@typescript-eslint/typescript-estree"); +const node_path_1 = __importDefault(require("node:path")); +function typeDeclaredInFile(relativePath, declarationFiles, program) { + if (relativePath == null) { + const cwd = (0, typescript_estree_1.getCanonicalFileName)(program.getCurrentDirectory()); + return declarationFiles.some(declaration => (0, typescript_estree_1.getCanonicalFileName)(declaration.fileName).startsWith(cwd)); + } + const absolutePath = (0, typescript_estree_1.getCanonicalFileName)(node_path_1.default.join(program.getCurrentDirectory(), relativePath)); + return declarationFiles.some(declaration => (0, typescript_estree_1.getCanonicalFileName)(declaration.fileName) === absolutePath); +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInLib.d.ts b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInLib.d.ts new file mode 100644 index 00000000..ed49ac54 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInLib.d.ts @@ -0,0 +1,3 @@ +import type * as ts from 'typescript'; +export declare function typeDeclaredInLib(declarationFiles: ts.SourceFile[], program: ts.Program): boolean; +//# sourceMappingURL=typeDeclaredInLib.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInLib.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInLib.d.ts.map new file mode 100644 index 00000000..09f2826d --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInLib.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"typeDeclaredInLib.d.ts","sourceRoot":"","sources":["../../src/typeOrValueSpecifiers/typeDeclaredInLib.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC,wBAAgB,iBAAiB,CAC/B,gBAAgB,EAAE,EAAE,CAAC,UAAU,EAAE,EACjC,OAAO,EAAE,EAAE,CAAC,OAAO,GAClB,OAAO,CAUT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInLib.js b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInLib.js new file mode 100644 index 00000000..e25031a1 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInLib.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.typeDeclaredInLib = typeDeclaredInLib; +function typeDeclaredInLib(declarationFiles, program) { + // Assertion: The type is not an error type. + // Intrinsic type (i.e. string, number, boolean, etc) - Treat it as if it's from lib. + if (declarationFiles.length === 0) { + return true; + } + return declarationFiles.some(declaration => program.isSourceFileDefaultLibrary(declaration)); +} diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.d.ts b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.d.ts new file mode 100644 index 00000000..9e19df40 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.d.ts @@ -0,0 +1,3 @@ +import * as ts from 'typescript'; +export declare function typeDeclaredInPackageDeclarationFile(packageName: string, declarations: ts.Node[], declarationFiles: ts.SourceFile[], program: ts.Program): boolean; +//# sourceMappingURL=typeDeclaredInPackageDeclarationFile.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.d.ts.map b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.d.ts.map new file mode 100644 index 00000000..1e797bd0 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"typeDeclaredInPackageDeclarationFile.d.ts","sourceRoot":"","sources":["../../src/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AA8CjC,wBAAgB,oCAAoC,CAClD,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,EAAE,CAAC,IAAI,EAAE,EACvB,gBAAgB,EAAE,EAAE,CAAC,UAAU,EAAE,EACjC,OAAO,EAAE,EAAE,CAAC,OAAO,GAClB,OAAO,CAKT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.js b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.js new file mode 100644 index 00000000..b4feebf1 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/dist/typeOrValueSpecifiers/typeDeclaredInPackageDeclarationFile.js @@ -0,0 +1,67 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.typeDeclaredInPackageDeclarationFile = typeDeclaredInPackageDeclarationFile; +const ts = __importStar(require("typescript")); +function findParentModuleDeclaration(node) { + switch (node.kind) { + case ts.SyntaxKind.ModuleDeclaration: + return ts.isStringLiteral(node.name) + ? node + : undefined; + case ts.SyntaxKind.SourceFile: + return undefined; + default: + return findParentModuleDeclaration(node.parent); + } +} +function typeDeclaredInDeclareModule(packageName, declarations) { + return declarations.some(declaration => findParentModuleDeclaration(declaration)?.name.text === packageName); +} +function typeDeclaredInDeclarationFile(packageName, declarationFiles, program) { + // Handle scoped packages: if the name starts with @, remove it and replace / with __ + const typesPackageName = packageName.replace(/^@([^/]+)\//, '$1__'); + const matcher = new RegExp(`${packageName}|${typesPackageName}`); + return declarationFiles.some(declaration => { + const packageIdName = program.sourceFileToPackageName.get(declaration.path); + return (packageIdName != null && + matcher.test(packageIdName) && + program.isSourceFileFromExternalLibrary(declaration)); + }); +} +function typeDeclaredInPackageDeclarationFile(packageName, declarations, declarationFiles, program) { + return (typeDeclaredInDeclareModule(packageName, declarations) || + typeDeclaredInDeclarationFile(packageName, declarationFiles, program)); +} diff --git a/node_modules/@typescript-eslint/type-utils/package.json b/node_modules/@typescript-eslint/type-utils/package.json new file mode 100644 index 00000000..9f3b152e --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/package.json @@ -0,0 +1,76 @@ +{ + "name": "@typescript-eslint/type-utils", + "version": "8.34.0", + "description": "Type utilities for working with TypeScript + ESLint together", + "files": [ + "dist", + "!*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/type-utils" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "format": "yarn run -T format", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "dependencies": { + "@typescript-eslint/typescript-estree": "8.34.0", + "@typescript-eslint/utils": "8.34.0", + "debug": "^4.3.4", + "ts-api-utils": "^2.1.0" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + }, + "devDependencies": { + "@typescript-eslint/parser": "8.34.0", + "@vitest/coverage-v8": "^3.1.3", + "ajv": "^6.12.6", + "eslint": "*", + "rimraf": "*", + "typescript": "*", + "vitest": "^3.1.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "type-utils", + "includedScripts": [ + "clean" + ] + } +} diff --git a/node_modules/@typescript-eslint/types/LICENSE b/node_modules/@typescript-eslint/types/LICENSE new file mode 100644 index 00000000..a1164108 --- /dev/null +++ b/node_modules/@typescript-eslint/types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/types/README.md b/node_modules/@typescript-eslint/types/README.md new file mode 100644 index 00000000..7a3008bb --- /dev/null +++ b/node_modules/@typescript-eslint/types/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/types` + +> Types for the TypeScript-ESTree AST spec + +This package exists to help us reduce cycles and provide lighter-weight packages at runtime. + +## ✋ Internal Package + +This is an _internal package_ to the [typescript-eslint monorepo](https://github.com/typescript-eslint/typescript-eslint). +You likely don't want to use it directly. + +👉 See **https://typescript-eslint.io** for docs on typescript-eslint. diff --git a/node_modules/@typescript-eslint/types/dist/generated/ast-spec.d.ts b/node_modules/@typescript-eslint/types/dist/generated/ast-spec.d.ts new file mode 100644 index 00000000..43f077cb --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/generated/ast-spec.d.ts @@ -0,0 +1,2164 @@ +/********************************************** + * DO NOT MODIFY THIS FILE MANUALLY * + * * + * THIS FILE HAS BEEN COPIED FROM ast-spec. * + * ANY CHANGES WILL BE LOST ON THE NEXT BUILD * + * * + * MAKE CHANGES TO ast-spec AND THEN RUN * + * yarn build * + **********************************************/ +import type { SyntaxKind } from 'typescript'; +export declare type Accessibility = 'private' | 'protected' | 'public'; +export declare type AccessorProperty = AccessorPropertyComputedName | AccessorPropertyNonComputedName; +export declare interface AccessorPropertyComputedName extends PropertyDefinitionComputedNameBase { + type: AST_NODE_TYPES.AccessorProperty; +} +export declare interface AccessorPropertyNonComputedName extends PropertyDefinitionNonComputedNameBase { + type: AST_NODE_TYPES.AccessorProperty; +} +export declare interface ArrayExpression extends BaseNode { + type: AST_NODE_TYPES.ArrayExpression; + /** + * an element will be `null` in the case of a sparse array: `[1, ,3]` + */ + elements: (Expression | SpreadElement | null)[]; +} +export declare interface ArrayPattern extends BaseNode { + type: AST_NODE_TYPES.ArrayPattern; + decorators: Decorator[]; + elements: (DestructuringPattern | null)[]; + optional: boolean; + typeAnnotation: TSTypeAnnotation | undefined; +} +export declare interface ArrowFunctionExpression extends BaseNode { + type: AST_NODE_TYPES.ArrowFunctionExpression; + async: boolean; + body: BlockStatement | Expression; + expression: boolean; + generator: boolean; + id: null; + params: Parameter[]; + returnType: TSTypeAnnotation | undefined; + typeParameters: TSTypeParameterDeclaration | undefined; +} +export declare interface AssignmentExpression extends BaseNode { + type: AST_NODE_TYPES.AssignmentExpression; + left: Expression; + operator: ValueOf; + right: Expression; +} +export declare interface AssignmentOperatorToText { + [SyntaxKind.AmpersandAmpersandEqualsToken]: '&&='; + [SyntaxKind.AmpersandEqualsToken]: '&='; + [SyntaxKind.AsteriskAsteriskEqualsToken]: '**='; + [SyntaxKind.AsteriskEqualsToken]: '*='; + [SyntaxKind.BarBarEqualsToken]: '||='; + [SyntaxKind.BarEqualsToken]: '|='; + [SyntaxKind.CaretEqualsToken]: '^='; + [SyntaxKind.EqualsToken]: '='; + [SyntaxKind.GreaterThanGreaterThanEqualsToken]: '>>='; + [SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken]: '>>>='; + [SyntaxKind.LessThanLessThanEqualsToken]: '<<='; + [SyntaxKind.MinusEqualsToken]: '-='; + [SyntaxKind.PercentEqualsToken]: '%='; + [SyntaxKind.PlusEqualsToken]: '+='; + [SyntaxKind.QuestionQuestionEqualsToken]: '??='; + [SyntaxKind.SlashEqualsToken]: '/='; +} +export declare interface AssignmentPattern extends BaseNode { + type: AST_NODE_TYPES.AssignmentPattern; + decorators: Decorator[]; + left: BindingName; + optional: boolean; + right: Expression; + typeAnnotation: TSTypeAnnotation | undefined; +} +export declare enum AST_NODE_TYPES { + AccessorProperty = "AccessorProperty", + ArrayExpression = "ArrayExpression", + ArrayPattern = "ArrayPattern", + ArrowFunctionExpression = "ArrowFunctionExpression", + AssignmentExpression = "AssignmentExpression", + AssignmentPattern = "AssignmentPattern", + AwaitExpression = "AwaitExpression", + BinaryExpression = "BinaryExpression", + BlockStatement = "BlockStatement", + BreakStatement = "BreakStatement", + CallExpression = "CallExpression", + CatchClause = "CatchClause", + ChainExpression = "ChainExpression", + ClassBody = "ClassBody", + ClassDeclaration = "ClassDeclaration", + ClassExpression = "ClassExpression", + ConditionalExpression = "ConditionalExpression", + ContinueStatement = "ContinueStatement", + DebuggerStatement = "DebuggerStatement", + Decorator = "Decorator", + DoWhileStatement = "DoWhileStatement", + EmptyStatement = "EmptyStatement", + ExportAllDeclaration = "ExportAllDeclaration", + ExportDefaultDeclaration = "ExportDefaultDeclaration", + ExportNamedDeclaration = "ExportNamedDeclaration", + ExportSpecifier = "ExportSpecifier", + ExpressionStatement = "ExpressionStatement", + ForInStatement = "ForInStatement", + ForOfStatement = "ForOfStatement", + ForStatement = "ForStatement", + FunctionDeclaration = "FunctionDeclaration", + FunctionExpression = "FunctionExpression", + Identifier = "Identifier", + IfStatement = "IfStatement", + ImportAttribute = "ImportAttribute", + ImportDeclaration = "ImportDeclaration", + ImportDefaultSpecifier = "ImportDefaultSpecifier", + ImportExpression = "ImportExpression", + ImportNamespaceSpecifier = "ImportNamespaceSpecifier", + ImportSpecifier = "ImportSpecifier", + JSXAttribute = "JSXAttribute", + JSXClosingElement = "JSXClosingElement", + JSXClosingFragment = "JSXClosingFragment", + JSXElement = "JSXElement", + JSXEmptyExpression = "JSXEmptyExpression", + JSXExpressionContainer = "JSXExpressionContainer", + JSXFragment = "JSXFragment", + JSXIdentifier = "JSXIdentifier", + JSXMemberExpression = "JSXMemberExpression", + JSXNamespacedName = "JSXNamespacedName", + JSXOpeningElement = "JSXOpeningElement", + JSXOpeningFragment = "JSXOpeningFragment", + JSXSpreadAttribute = "JSXSpreadAttribute", + JSXSpreadChild = "JSXSpreadChild", + JSXText = "JSXText", + LabeledStatement = "LabeledStatement", + Literal = "Literal", + LogicalExpression = "LogicalExpression", + MemberExpression = "MemberExpression", + MetaProperty = "MetaProperty", + MethodDefinition = "MethodDefinition", + NewExpression = "NewExpression", + ObjectExpression = "ObjectExpression", + ObjectPattern = "ObjectPattern", + PrivateIdentifier = "PrivateIdentifier", + Program = "Program", + Property = "Property", + PropertyDefinition = "PropertyDefinition", + RestElement = "RestElement", + ReturnStatement = "ReturnStatement", + SequenceExpression = "SequenceExpression", + SpreadElement = "SpreadElement", + StaticBlock = "StaticBlock", + Super = "Super", + SwitchCase = "SwitchCase", + SwitchStatement = "SwitchStatement", + TaggedTemplateExpression = "TaggedTemplateExpression", + TemplateElement = "TemplateElement", + TemplateLiteral = "TemplateLiteral", + ThisExpression = "ThisExpression", + ThrowStatement = "ThrowStatement", + TryStatement = "TryStatement", + UnaryExpression = "UnaryExpression", + UpdateExpression = "UpdateExpression", + VariableDeclaration = "VariableDeclaration", + VariableDeclarator = "VariableDeclarator", + WhileStatement = "WhileStatement", + WithStatement = "WithStatement", + YieldExpression = "YieldExpression", + TSAbstractAccessorProperty = "TSAbstractAccessorProperty", + TSAbstractKeyword = "TSAbstractKeyword", + TSAbstractMethodDefinition = "TSAbstractMethodDefinition", + TSAbstractPropertyDefinition = "TSAbstractPropertyDefinition", + TSAnyKeyword = "TSAnyKeyword", + TSArrayType = "TSArrayType", + TSAsExpression = "TSAsExpression", + TSAsyncKeyword = "TSAsyncKeyword", + TSBigIntKeyword = "TSBigIntKeyword", + TSBooleanKeyword = "TSBooleanKeyword", + TSCallSignatureDeclaration = "TSCallSignatureDeclaration", + TSClassImplements = "TSClassImplements", + TSConditionalType = "TSConditionalType", + TSConstructorType = "TSConstructorType", + TSConstructSignatureDeclaration = "TSConstructSignatureDeclaration", + TSDeclareFunction = "TSDeclareFunction", + TSDeclareKeyword = "TSDeclareKeyword", + TSEmptyBodyFunctionExpression = "TSEmptyBodyFunctionExpression", + TSEnumBody = "TSEnumBody", + TSEnumDeclaration = "TSEnumDeclaration", + TSEnumMember = "TSEnumMember", + TSExportAssignment = "TSExportAssignment", + TSExportKeyword = "TSExportKeyword", + TSExternalModuleReference = "TSExternalModuleReference", + TSFunctionType = "TSFunctionType", + TSImportEqualsDeclaration = "TSImportEqualsDeclaration", + TSImportType = "TSImportType", + TSIndexedAccessType = "TSIndexedAccessType", + TSIndexSignature = "TSIndexSignature", + TSInferType = "TSInferType", + TSInstantiationExpression = "TSInstantiationExpression", + TSInterfaceBody = "TSInterfaceBody", + TSInterfaceDeclaration = "TSInterfaceDeclaration", + TSInterfaceHeritage = "TSInterfaceHeritage", + TSIntersectionType = "TSIntersectionType", + TSIntrinsicKeyword = "TSIntrinsicKeyword", + TSLiteralType = "TSLiteralType", + TSMappedType = "TSMappedType", + TSMethodSignature = "TSMethodSignature", + TSModuleBlock = "TSModuleBlock", + TSModuleDeclaration = "TSModuleDeclaration", + TSNamedTupleMember = "TSNamedTupleMember", + TSNamespaceExportDeclaration = "TSNamespaceExportDeclaration", + TSNeverKeyword = "TSNeverKeyword", + TSNonNullExpression = "TSNonNullExpression", + TSNullKeyword = "TSNullKeyword", + TSNumberKeyword = "TSNumberKeyword", + TSObjectKeyword = "TSObjectKeyword", + TSOptionalType = "TSOptionalType", + TSParameterProperty = "TSParameterProperty", + TSPrivateKeyword = "TSPrivateKeyword", + TSPropertySignature = "TSPropertySignature", + TSProtectedKeyword = "TSProtectedKeyword", + TSPublicKeyword = "TSPublicKeyword", + TSQualifiedName = "TSQualifiedName", + TSReadonlyKeyword = "TSReadonlyKeyword", + TSRestType = "TSRestType", + TSSatisfiesExpression = "TSSatisfiesExpression", + TSStaticKeyword = "TSStaticKeyword", + TSStringKeyword = "TSStringKeyword", + TSSymbolKeyword = "TSSymbolKeyword", + TSTemplateLiteralType = "TSTemplateLiteralType", + TSThisType = "TSThisType", + TSTupleType = "TSTupleType", + TSTypeAliasDeclaration = "TSTypeAliasDeclaration", + TSTypeAnnotation = "TSTypeAnnotation", + TSTypeAssertion = "TSTypeAssertion", + TSTypeLiteral = "TSTypeLiteral", + TSTypeOperator = "TSTypeOperator", + TSTypeParameter = "TSTypeParameter", + TSTypeParameterDeclaration = "TSTypeParameterDeclaration", + TSTypeParameterInstantiation = "TSTypeParameterInstantiation", + TSTypePredicate = "TSTypePredicate", + TSTypeQuery = "TSTypeQuery", + TSTypeReference = "TSTypeReference", + TSUndefinedKeyword = "TSUndefinedKeyword", + TSUnionType = "TSUnionType", + TSUnknownKeyword = "TSUnknownKeyword", + TSVoidKeyword = "TSVoidKeyword" +} +export declare enum AST_TOKEN_TYPES { + Boolean = "Boolean", + Identifier = "Identifier", + JSXIdentifier = "JSXIdentifier", + PrivateIdentifier = "PrivateIdentifier", + JSXText = "JSXText", + Keyword = "Keyword", + Null = "Null", + Numeric = "Numeric", + Punctuator = "Punctuator", + RegularExpression = "RegularExpression", + String = "String", + Template = "Template", + Block = "Block", + Line = "Line" +} +export declare interface AwaitExpression extends BaseNode { + type: AST_NODE_TYPES.AwaitExpression; + argument: Expression; +} +export declare interface BaseNode extends NodeOrTokenData { + type: AST_NODE_TYPES; +} +declare interface BaseToken extends NodeOrTokenData { + type: AST_TOKEN_TYPES; + value: string; +} +export declare interface BigIntLiteral extends LiteralBase { + bigint: string; + value: bigint | null; +} +export declare interface BinaryExpression extends BaseNode { + type: AST_NODE_TYPES.BinaryExpression; + left: Expression | PrivateIdentifier; + operator: ValueOf; + right: Expression; +} +export declare interface BinaryOperatorToText { + [SyntaxKind.AmpersandAmpersandToken]: '&&'; + [SyntaxKind.AmpersandToken]: '&'; + [SyntaxKind.AsteriskAsteriskToken]: '**'; + [SyntaxKind.AsteriskToken]: '*'; + [SyntaxKind.BarBarToken]: '||'; + [SyntaxKind.BarToken]: '|'; + [SyntaxKind.CaretToken]: '^'; + [SyntaxKind.EqualsEqualsEqualsToken]: '==='; + [SyntaxKind.EqualsEqualsToken]: '=='; + [SyntaxKind.ExclamationEqualsEqualsToken]: '!=='; + [SyntaxKind.ExclamationEqualsToken]: '!='; + [SyntaxKind.GreaterThanEqualsToken]: '>='; + [SyntaxKind.GreaterThanGreaterThanGreaterThanToken]: '>>>'; + [SyntaxKind.GreaterThanGreaterThanToken]: '>>'; + [SyntaxKind.GreaterThanToken]: '>'; + [SyntaxKind.InKeyword]: 'in'; + [SyntaxKind.InstanceOfKeyword]: 'instanceof'; + [SyntaxKind.LessThanEqualsToken]: '<='; + [SyntaxKind.LessThanLessThanToken]: '<<'; + [SyntaxKind.LessThanToken]: '<'; + [SyntaxKind.MinusToken]: '-'; + [SyntaxKind.PercentToken]: '%'; + [SyntaxKind.PlusToken]: '+'; + [SyntaxKind.SlashToken]: '/'; +} +export declare type BindingName = BindingPattern | Identifier; +export declare type BindingPattern = ArrayPattern | ObjectPattern; +export declare interface BlockComment extends BaseToken { + type: AST_TOKEN_TYPES.Block; +} +export declare interface BlockStatement extends BaseNode { + type: AST_NODE_TYPES.BlockStatement; + body: Statement[]; +} +export declare interface BooleanLiteral extends LiteralBase { + raw: 'false' | 'true'; + value: boolean; +} +export declare interface BooleanToken extends BaseToken { + type: AST_TOKEN_TYPES.Boolean; +} +export declare interface BreakStatement extends BaseNode { + type: AST_NODE_TYPES.BreakStatement; + label: Identifier | null; +} +export declare interface CallExpression extends BaseNode { + type: AST_NODE_TYPES.CallExpression; + arguments: CallExpressionArgument[]; + callee: Expression; + optional: boolean; + typeArguments: TSTypeParameterInstantiation | undefined; +} +export declare type CallExpressionArgument = Expression | SpreadElement; +export declare interface CatchClause extends BaseNode { + type: AST_NODE_TYPES.CatchClause; + body: BlockStatement; + param: BindingName | null; +} +export declare type ChainElement = CallExpression | MemberExpression | TSNonNullExpression; +export declare interface ChainExpression extends BaseNode { + type: AST_NODE_TYPES.ChainExpression; + expression: ChainElement; +} +declare interface ClassBase extends BaseNode { + /** + * Whether the class is an abstract class. + * @example + * ```ts + * abstract class Foo {} + * ``` + */ + abstract: boolean; + /** + * The class body. + */ + body: ClassBody; + /** + * Whether the class has been `declare`d: + * @example + * ```ts + * declare class Foo {} + * ``` + */ + declare: boolean; + /** + * The decorators declared for the class. + * @example + * ```ts + * @deco + * class Foo {} + * ``` + */ + decorators: Decorator[]; + /** + * The class's name. + * - For a `ClassExpression` this may be `null` if the name is omitted. + * - For a `ClassDeclaration` this may be `null` if and only if the parent is + * an `ExportDefaultDeclaration`. + */ + id: Identifier | null; + /** + * The implemented interfaces for the class. + */ + implements: TSClassImplements[]; + /** + * The super class this class extends. + */ + superClass: LeftHandSideExpression | null; + /** + * The generic type parameters passed to the superClass. + */ + superTypeArguments: TSTypeParameterInstantiation | undefined; + /** + * The generic type parameters declared for the class. + */ + typeParameters: TSTypeParameterDeclaration | undefined; +} +export declare interface ClassBody extends BaseNode { + type: AST_NODE_TYPES.ClassBody; + body: ClassElement[]; +} +export declare type ClassDeclaration = ClassDeclarationWithName | ClassDeclarationWithOptionalName; +declare interface ClassDeclarationBase extends ClassBase { + type: AST_NODE_TYPES.ClassDeclaration; +} +/** + * A normal class declaration: + * ``` + * class A {} + * ``` + */ +export declare interface ClassDeclarationWithName extends ClassDeclarationBase { + id: Identifier; +} +/** + * Default-exported class declarations have optional names: + * ``` + * export default class {} + * ``` + */ +export declare interface ClassDeclarationWithOptionalName extends ClassDeclarationBase { + id: Identifier | null; +} +export declare type ClassElement = AccessorProperty | MethodDefinition | PropertyDefinition | StaticBlock | TSAbstractAccessorProperty | TSAbstractMethodDefinition | TSAbstractPropertyDefinition | TSIndexSignature; +export declare interface ClassExpression extends ClassBase { + type: AST_NODE_TYPES.ClassExpression; + abstract: false; + declare: false; +} +declare interface ClassMethodDefinitionNonComputedNameBase extends MethodDefinitionBase { + computed: false; + key: ClassPropertyNameNonComputed; +} +declare interface ClassPropertyDefinitionNonComputedNameBase extends PropertyDefinitionBase { + computed: false; + key: ClassPropertyNameNonComputed; +} +export declare type ClassPropertyNameNonComputed = PrivateIdentifier | PropertyNameNonComputed; +export declare type Comment = BlockComment | LineComment; +export declare interface ConditionalExpression extends BaseNode { + type: AST_NODE_TYPES.ConditionalExpression; + alternate: Expression; + consequent: Expression; + test: Expression; +} +export declare interface ConstDeclaration extends LetOrConstOrVarDeclarationBase { + /** + * In a `declare const` declaration, the declarators may have initializers, but + * not definite assignment assertions. Each declarator cannot have both an + * initializer and a type annotation. + * + * Even if the declaration has no `declare`, it may still be ambient and have + * no initializer. + */ + declarations: VariableDeclaratorMaybeInit[]; + kind: 'const'; +} +export declare interface ContinueStatement extends BaseNode { + type: AST_NODE_TYPES.ContinueStatement; + label: Identifier | null; +} +export declare interface DebuggerStatement extends BaseNode { + type: AST_NODE_TYPES.DebuggerStatement; +} +/** + * @deprecated + * Note that this is neither up to date nor fully correct. + */ +export declare type DeclarationStatement = ClassDeclaration | ClassExpression | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | FunctionDeclaration | TSDeclareFunction | TSEnumDeclaration | TSImportEqualsDeclaration | TSInterfaceDeclaration | TSModuleDeclaration | TSNamespaceExportDeclaration | TSTypeAliasDeclaration; +export declare interface Decorator extends BaseNode { + type: AST_NODE_TYPES.Decorator; + expression: LeftHandSideExpression; +} +export declare type DefaultExportDeclarations = ClassDeclarationWithOptionalName | Expression | FunctionDeclarationWithName | FunctionDeclarationWithOptionalName | TSDeclareFunction | TSEnumDeclaration | TSInterfaceDeclaration | TSModuleDeclaration | TSTypeAliasDeclaration | VariableDeclaration; +export declare type DestructuringPattern = ArrayPattern | AssignmentPattern | Identifier | MemberExpression | ObjectPattern | RestElement; +export declare interface DoWhileStatement extends BaseNode { + type: AST_NODE_TYPES.DoWhileStatement; + body: Statement; + test: Expression; +} +export declare interface EmptyStatement extends BaseNode { + type: AST_NODE_TYPES.EmptyStatement; +} +export declare type EntityName = Identifier | ThisExpression | TSQualifiedName; +export declare interface ExportAllDeclaration extends BaseNode { + type: AST_NODE_TYPES.ExportAllDeclaration; + /** + * The assertions declared for the export. + * @example + * ```ts + * export * from 'mod' assert \{ type: 'json' \}; + * ``` + * @deprecated Replaced with {@link `attributes`}. + */ + assertions: ImportAttribute[]; + /** + * The attributes declared for the export. + * @example + * ```ts + * export * from 'mod' with \{ type: 'json' \}; + * ``` + */ + attributes: ImportAttribute[]; + /** + * The name for the exported items (`as X`). `null` if no name is assigned. + */ + exported: Identifier | null; + /** + * The kind of the export. + */ + exportKind: ExportKind; + /** + * The source module being exported from. + */ + source: StringLiteral; +} +declare type ExportAndImportKind = 'type' | 'value'; +export declare type ExportDeclaration = DefaultExportDeclarations | NamedExportDeclarations; +export declare interface ExportDefaultDeclaration extends BaseNode { + type: AST_NODE_TYPES.ExportDefaultDeclaration; + /** + * The declaration being exported. + */ + declaration: DefaultExportDeclarations; + /** + * The kind of the export. Always `value` for default exports. + */ + exportKind: 'value'; +} +declare type ExportKind = ExportAndImportKind; +export declare type ExportNamedDeclaration = ExportNamedDeclarationWithoutSourceWithMultiple | ExportNamedDeclarationWithoutSourceWithSingle | ExportNamedDeclarationWithSource; +declare interface ExportNamedDeclarationBase extends BaseNode { + type: AST_NODE_TYPES.ExportNamedDeclaration; + /** + * The assertions declared for the export. + * @example + * ```ts + * export { foo } from 'mod' assert \{ type: 'json' \}; + * ``` + * This will be an empty array if `source` is `null` + * @deprecated Replaced with {@link `attributes`}. + */ + assertions: ImportAttribute[]; + /** + * The attributes declared for the export. + * @example + * ```ts + * export { foo } from 'mod' with \{ type: 'json' \}; + * ``` + * This will be an empty array if `source` is `null` + */ + attributes: ImportAttribute[]; + /** + * The exported declaration. + * @example + * ```ts + * export const x = 1; + * ``` + * This will be `null` if `source` is not `null`, or if there are `specifiers` + */ + declaration: NamedExportDeclarations | null; + /** + * The kind of the export. + */ + exportKind: ExportKind; + /** + * The source module being exported from. + */ + source: StringLiteral | null; + /** + * The specifiers being exported. + * @example + * ```ts + * export { a, b }; + * ``` + * This will be an empty array if `declaration` is not `null` + */ + specifiers: ExportSpecifier[]; +} +export declare type ExportNamedDeclarationWithoutSource = ExportNamedDeclarationWithoutSourceWithMultiple | ExportNamedDeclarationWithoutSourceWithSingle; +/** + * Exporting names from the current module. + * ``` + * export {}; + * export { a, b }; + * ``` + */ +export declare interface ExportNamedDeclarationWithoutSourceWithMultiple extends ExportNamedDeclarationBase { + /** + * This will always be an empty array. + * @deprecated Replaced with {@link `attributes`}. + */ + assertions: ImportAttribute[]; + /** + * This will always be an empty array. + */ + attributes: ImportAttribute[]; + declaration: null; + source: null; + specifiers: ExportSpecifierWithIdentifierLocal[]; +} +/** + * Exporting a single named declaration. + * ``` + * export const x = 1; + * ``` + */ +export declare interface ExportNamedDeclarationWithoutSourceWithSingle extends ExportNamedDeclarationBase { + /** + * This will always be an empty array. + * @deprecated Replaced with {@link `attributes`}. + */ + assertions: ImportAttribute[]; + /** + * This will always be an empty array. + */ + attributes: ImportAttribute[]; + declaration: NamedExportDeclarations; + source: null; + /** + * This will always be an empty array. + */ + specifiers: ExportSpecifierWithIdentifierLocal[]; +} +/** + * Export names from another module. + * ``` + * export { a, b } from 'mod'; + * ``` + */ +export declare interface ExportNamedDeclarationWithSource extends ExportNamedDeclarationBase { + declaration: null; + source: StringLiteral; +} +export declare type ExportSpecifier = ExportSpecifierWithIdentifierLocal | ExportSpecifierWithStringOrLiteralLocal; +declare interface ExportSpecifierBase extends BaseNode { + type: AST_NODE_TYPES.ExportSpecifier; + exported: Identifier | StringLiteral; + exportKind: ExportKind; + local: Identifier | StringLiteral; +} +export declare interface ExportSpecifierWithIdentifierLocal extends ExportSpecifierBase { + local: Identifier; +} +export declare interface ExportSpecifierWithStringOrLiteralLocal extends ExportSpecifierBase { + local: Identifier | StringLiteral; +} +export declare type Expression = ArrayExpression | ArrayPattern | ArrowFunctionExpression | AssignmentExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ConditionalExpression | FunctionExpression | Identifier | ImportExpression | JSXElement | JSXFragment | LiteralExpression | LogicalExpression | MemberExpression | MetaProperty | NewExpression | ObjectExpression | ObjectPattern | SequenceExpression | Super | TaggedTemplateExpression | TemplateLiteral | ThisExpression | TSAsExpression | TSInstantiationExpression | TSNonNullExpression | TSSatisfiesExpression | TSTypeAssertion | UnaryExpression | UpdateExpression | YieldExpression; +export declare interface ExpressionStatement extends BaseNode { + type: AST_NODE_TYPES.ExpressionStatement; + directive: string | undefined; + expression: Expression; +} +export declare type ForInitialiser = Expression | LetOrConstOrVarDeclaration; +export declare interface ForInStatement extends BaseNode { + type: AST_NODE_TYPES.ForInStatement; + body: Statement; + left: ForInitialiser; + right: Expression; +} +declare type ForOfInitialiser = Expression | LetOrConstOrVarDeclaration | UsingInForOfDeclaration; +export declare interface ForOfStatement extends BaseNode { + type: AST_NODE_TYPES.ForOfStatement; + await: boolean; + body: Statement; + left: ForOfInitialiser; + right: Expression; +} +export declare interface ForStatement extends BaseNode { + type: AST_NODE_TYPES.ForStatement; + body: Statement; + init: Expression | ForInitialiser | null; + test: Expression | null; + update: Expression | null; +} +declare interface FunctionBase extends BaseNode { + /** + * Whether the function is async: + * ``` + * async function foo() {} + * const x = async function () {} + * const x = async () => {} + * ``` + */ + async: boolean; + /** + * The body of the function. + * - For an `ArrowFunctionExpression` this may be an `Expression` or `BlockStatement`. + * - For a `FunctionDeclaration` or `FunctionExpression` this is always a `BlockStatement`. + * - For a `TSDeclareFunction` this is always `undefined`. + * - For a `TSEmptyBodyFunctionExpression` this is always `null`. + */ + body: BlockStatement | Expression | null | undefined; + /** + * This is only `true` if and only if the node is a `TSDeclareFunction` and it has `declare`: + * ``` + * declare function foo() {} + * ``` + */ + declare: boolean; + /** + * This is only ever `true` if and only the node is an `ArrowFunctionExpression` and the body + * is an expression: + * ``` + * (() => 1) + * ``` + */ + expression: boolean; + /** + * Whether the function is a generator function: + * ``` + * function *foo() {} + * const x = function *() {} + * ``` + * This is always `false` for arrow functions as they cannot be generators. + */ + generator: boolean; + /** + * The function's name. + * - For an `ArrowFunctionExpression` this is always `null`. + * - For a `FunctionExpression` this may be `null` if the name is omitted. + * - For a `FunctionDeclaration` or `TSDeclareFunction` this may be `null` if + * and only if the parent is an `ExportDefaultDeclaration`. + */ + id: Identifier | null; + /** + * The list of parameters declared for the function. + */ + params: Parameter[]; + /** + * The return type annotation for the function. + */ + returnType: TSTypeAnnotation | undefined; + /** + * The generic type parameter declaration for the function. + */ + typeParameters: TSTypeParameterDeclaration | undefined; +} +export declare type FunctionDeclaration = FunctionDeclarationWithName | FunctionDeclarationWithOptionalName; +declare interface FunctionDeclarationBase extends FunctionBase { + type: AST_NODE_TYPES.FunctionDeclaration; + body: BlockStatement; + declare: false; + expression: false; +} +/** + * A normal function declaration: + * ``` + * function f() {} + * ``` + */ +export declare interface FunctionDeclarationWithName extends FunctionDeclarationBase { + id: Identifier; +} +/** + * Default-exported function declarations have optional names: + * ``` + * export default function () {} + * ``` + */ +export declare interface FunctionDeclarationWithOptionalName extends FunctionDeclarationBase { + id: Identifier | null; +} +export declare interface FunctionExpression extends FunctionBase { + type: AST_NODE_TYPES.FunctionExpression; + body: BlockStatement; + expression: false; +} +export declare type FunctionLike = ArrowFunctionExpression | FunctionDeclaration | FunctionExpression | TSDeclareFunction | TSEmptyBodyFunctionExpression; +export declare interface Identifier extends BaseNode { + type: AST_NODE_TYPES.Identifier; + decorators: Decorator[]; + name: string; + optional: boolean; + typeAnnotation: TSTypeAnnotation | undefined; +} +export declare interface IdentifierToken extends BaseToken { + type: AST_TOKEN_TYPES.Identifier; +} +export declare interface IfStatement extends BaseNode { + type: AST_NODE_TYPES.IfStatement; + alternate: Statement | null; + consequent: Statement; + test: Expression; +} +export declare interface ImportAttribute extends BaseNode { + type: AST_NODE_TYPES.ImportAttribute; + key: Identifier | Literal; + value: Literal; +} +export declare type ImportClause = ImportDefaultSpecifier | ImportNamespaceSpecifier | ImportSpecifier; +export declare interface ImportDeclaration extends BaseNode { + type: AST_NODE_TYPES.ImportDeclaration; + /** + * The assertions declared for the export. + * @example + * ```ts + * import * from 'mod' assert \{ type: 'json' \}; + * ``` + * @deprecated Replaced with {@link `attributes`}. + */ + assertions: ImportAttribute[]; + /** + * The attributes declared for the export. + * @example + * ```ts + * import * from 'mod' with \{ type: 'json' \}; + * ``` + */ + attributes: ImportAttribute[]; + /** + * The kind of the import. + */ + importKind: ImportKind; + /** + * The source module being imported from. + */ + source: StringLiteral; + /** + * The specifiers being imported. + * If this is an empty array then either there are no specifiers: + * ``` + * import {} from 'mod'; + * ``` + * Or it is a side-effect import: + * ``` + * import 'mod'; + * ``` + */ + specifiers: ImportClause[]; +} +export declare interface ImportDefaultSpecifier extends BaseNode { + type: AST_NODE_TYPES.ImportDefaultSpecifier; + local: Identifier; +} +export declare interface ImportExpression extends BaseNode { + type: AST_NODE_TYPES.ImportExpression; + /** + * The attributes declared for the dynamic import. + * @example + * ```ts + * import('mod', \{ assert: \{ type: 'json' \} \}); + * ``` + * @deprecated Replaced with {@link `options`}. + */ + attributes: Expression | null; + /** + * The options bag declared for the dynamic import. + * @example + * ```ts + * import('mod', \{ assert: \{ type: 'json' \} \}); + * ``` + */ + options: Expression | null; + source: Expression; +} +declare type ImportKind = ExportAndImportKind; +export declare interface ImportNamespaceSpecifier extends BaseNode { + type: AST_NODE_TYPES.ImportNamespaceSpecifier; + local: Identifier; +} +export declare interface ImportSpecifier extends BaseNode { + type: AST_NODE_TYPES.ImportSpecifier; + imported: Identifier | StringLiteral; + importKind: ImportKind; + local: Identifier; +} +export declare type IterationStatement = DoWhileStatement | ForInStatement | ForOfStatement | ForStatement | WhileStatement; +export declare interface JSXAttribute extends BaseNode { + type: AST_NODE_TYPES.JSXAttribute; + name: JSXIdentifier | JSXNamespacedName; + value: JSXElement | JSXExpression | Literal | null; +} +export declare type JSXChild = JSXElement | JSXExpression | JSXFragment | JSXText; +export declare interface JSXClosingElement extends BaseNode { + type: AST_NODE_TYPES.JSXClosingElement; + name: JSXTagNameExpression; +} +export declare interface JSXClosingFragment extends BaseNode { + type: AST_NODE_TYPES.JSXClosingFragment; +} +export declare interface JSXElement extends BaseNode { + type: AST_NODE_TYPES.JSXElement; + children: JSXChild[]; + closingElement: JSXClosingElement | null; + openingElement: JSXOpeningElement; +} +export declare interface JSXEmptyExpression extends BaseNode { + type: AST_NODE_TYPES.JSXEmptyExpression; +} +export declare type JSXExpression = JSXExpressionContainer | JSXSpreadChild; +export declare interface JSXExpressionContainer extends BaseNode { + type: AST_NODE_TYPES.JSXExpressionContainer; + expression: Expression | JSXEmptyExpression; +} +export declare interface JSXFragment extends BaseNode { + type: AST_NODE_TYPES.JSXFragment; + children: JSXChild[]; + closingFragment: JSXClosingFragment; + openingFragment: JSXOpeningFragment; +} +export declare interface JSXIdentifier extends BaseNode { + type: AST_NODE_TYPES.JSXIdentifier; + name: string; +} +export declare interface JSXIdentifierToken extends BaseToken { + type: AST_TOKEN_TYPES.JSXIdentifier; +} +export declare interface JSXMemberExpression extends BaseNode { + type: AST_NODE_TYPES.JSXMemberExpression; + object: JSXTagNameExpression; + property: JSXIdentifier; +} +export declare interface JSXNamespacedName extends BaseNode { + type: AST_NODE_TYPES.JSXNamespacedName; + name: JSXIdentifier; + namespace: JSXIdentifier; +} +export declare interface JSXOpeningElement extends BaseNode { + type: AST_NODE_TYPES.JSXOpeningElement; + attributes: (JSXAttribute | JSXSpreadAttribute)[]; + name: JSXTagNameExpression; + selfClosing: boolean; + typeArguments: TSTypeParameterInstantiation | undefined; +} +export declare interface JSXOpeningFragment extends BaseNode { + type: AST_NODE_TYPES.JSXOpeningFragment; +} +export declare interface JSXSpreadAttribute extends BaseNode { + type: AST_NODE_TYPES.JSXSpreadAttribute; + argument: Expression; +} +export declare interface JSXSpreadChild extends BaseNode { + type: AST_NODE_TYPES.JSXSpreadChild; + expression: Expression | JSXEmptyExpression; +} +export declare type JSXTagNameExpression = JSXIdentifier | JSXMemberExpression | JSXNamespacedName; +export declare interface JSXText extends BaseNode { + type: AST_NODE_TYPES.JSXText; + raw: string; + value: string; +} +export declare interface JSXTextToken extends BaseToken { + type: AST_TOKEN_TYPES.JSXText; +} +export declare interface KeywordToken extends BaseToken { + type: AST_TOKEN_TYPES.Keyword; +} +export declare interface LabeledStatement extends BaseNode { + type: AST_NODE_TYPES.LabeledStatement; + body: Statement; + label: Identifier; +} +export declare type LeftHandSideExpression = ArrayExpression | ArrayPattern | ArrowFunctionExpression | CallExpression | ClassExpression | FunctionExpression | Identifier | JSXElement | JSXFragment | LiteralExpression | MemberExpression | MetaProperty | ObjectExpression | ObjectPattern | SequenceExpression | Super | TaggedTemplateExpression | ThisExpression | TSAsExpression | TSNonNullExpression | TSTypeAssertion; +export declare type LetOrConstOrVarDeclaration = ConstDeclaration | LetOrVarDeclaredDeclaration | LetOrVarNonDeclaredDeclaration; +declare interface LetOrConstOrVarDeclarationBase extends BaseNode { + type: AST_NODE_TYPES.VariableDeclaration; + /** + * The variables declared by this declaration. + * Always non-empty. + * @example + * ```ts + * let x; + * let y, z; + * ``` + */ + declarations: LetOrConstOrVarDeclarator[]; + /** + * Whether the declaration is `declare`d + * @example + * ```ts + * declare const x = 1; + * ``` + */ + declare: boolean; + /** + * The keyword used to declare the variable(s) + * @example + * ```ts + * const x = 1; + * let y = 2; + * var z = 3; + * ``` + */ + kind: 'const' | 'let' | 'var'; +} +export declare type LetOrConstOrVarDeclarator = VariableDeclaratorDefiniteAssignment | VariableDeclaratorMaybeInit | VariableDeclaratorNoInit; +export declare interface LetOrVarDeclaredDeclaration extends LetOrConstOrVarDeclarationBase { + /** + * In a `declare let` declaration, the declarators must not have definite assignment + * assertions or initializers. + * + * @example + * ```ts + * using x = 1; + * using y =1, z = 2; + * ``` + */ + declarations: VariableDeclaratorNoInit[]; + declare: true; + kind: 'let' | 'var'; +} +export declare interface LetOrVarNonDeclaredDeclaration extends LetOrConstOrVarDeclarationBase { + /** + * In a `let`/`var` declaration, the declarators may have definite assignment + * assertions or initializers, but not both. + */ + declarations: (VariableDeclaratorDefiniteAssignment | VariableDeclaratorMaybeInit)[]; + declare: false; + kind: 'let' | 'var'; +} +export declare interface LineComment extends BaseToken { + type: AST_TOKEN_TYPES.Line; +} +export declare type Literal = BigIntLiteral | BooleanLiteral | NullLiteral | NumberLiteral | RegExpLiteral | StringLiteral; +declare interface LiteralBase extends BaseNode { + type: AST_NODE_TYPES.Literal; + raw: string; + value: bigint | boolean | number | string | RegExp | null; +} +export declare type LiteralExpression = Literal | TemplateLiteral; +export declare interface LogicalExpression extends BaseNode { + type: AST_NODE_TYPES.LogicalExpression; + left: Expression; + operator: '&&' | '??' | '||'; + right: Expression; +} +export declare type MemberExpression = MemberExpressionComputedName | MemberExpressionNonComputedName; +declare interface MemberExpressionBase extends BaseNode { + computed: boolean; + object: Expression; + optional: boolean; + property: Expression | Identifier | PrivateIdentifier; +} +export declare interface MemberExpressionComputedName extends MemberExpressionBase { + type: AST_NODE_TYPES.MemberExpression; + computed: true; + property: Expression; +} +export declare interface MemberExpressionNonComputedName extends MemberExpressionBase { + type: AST_NODE_TYPES.MemberExpression; + computed: false; + property: Identifier | PrivateIdentifier; +} +export declare interface MetaProperty extends BaseNode { + type: AST_NODE_TYPES.MetaProperty; + meta: Identifier; + property: Identifier; +} +export declare type MethodDefinition = MethodDefinitionComputedName | MethodDefinitionNonComputedName; +/** this should not be directly used - instead use MethodDefinitionComputedNameBase or MethodDefinitionNonComputedNameBase */ +declare interface MethodDefinitionBase extends BaseNode { + accessibility: Accessibility | undefined; + computed: boolean; + decorators: Decorator[]; + key: PropertyName; + kind: 'constructor' | 'get' | 'method' | 'set'; + optional: boolean; + override: boolean; + static: boolean; + value: FunctionExpression | TSEmptyBodyFunctionExpression; +} +export declare interface MethodDefinitionComputedName extends MethodDefinitionComputedNameBase { + type: AST_NODE_TYPES.MethodDefinition; +} +declare interface MethodDefinitionComputedNameBase extends MethodDefinitionBase { + computed: true; + key: PropertyNameComputed; +} +export declare interface MethodDefinitionNonComputedName extends ClassMethodDefinitionNonComputedNameBase { + type: AST_NODE_TYPES.MethodDefinition; +} +declare interface MethodDefinitionNonComputedNameBase extends MethodDefinitionBase { + computed: false; + key: PropertyNameNonComputed; +} +export declare type NamedExportDeclarations = ClassDeclarationWithName | ClassDeclarationWithOptionalName | FunctionDeclarationWithName | FunctionDeclarationWithOptionalName | TSDeclareFunction | TSEnumDeclaration | TSImportEqualsDeclaration | TSInterfaceDeclaration | TSModuleDeclaration | TSTypeAliasDeclaration | VariableDeclaration; +export declare interface NewExpression extends BaseNode { + type: AST_NODE_TYPES.NewExpression; + arguments: CallExpressionArgument[]; + callee: Expression; + typeArguments: TSTypeParameterInstantiation | undefined; +} +export declare type Node = AccessorProperty | ArrayExpression | ArrayPattern | ArrowFunctionExpression | AssignmentExpression | AssignmentPattern | AwaitExpression | BinaryExpression | BlockStatement | BreakStatement | CallExpression | CatchClause | ChainExpression | ClassBody | ClassDeclaration | ClassExpression | ConditionalExpression | ContinueStatement | DebuggerStatement | Decorator | DoWhileStatement | EmptyStatement | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ExportSpecifier | ExpressionStatement | ForInStatement | ForOfStatement | ForStatement | FunctionDeclaration | FunctionExpression | Identifier | IfStatement | ImportAttribute | ImportDeclaration | ImportDefaultSpecifier | ImportExpression | ImportNamespaceSpecifier | ImportSpecifier | JSXAttribute | JSXClosingElement | JSXClosingFragment | JSXElement | JSXEmptyExpression | JSXExpressionContainer | JSXFragment | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXOpeningFragment | JSXSpreadAttribute | JSXSpreadChild | JSXText | LabeledStatement | Literal | LogicalExpression | MemberExpression | MetaProperty | MethodDefinition | NewExpression | ObjectExpression | ObjectPattern | PrivateIdentifier | Program | Property | PropertyDefinition | RestElement | ReturnStatement | SequenceExpression | SpreadElement | StaticBlock | Super | SwitchCase | SwitchStatement | TaggedTemplateExpression | TemplateElement | TemplateLiteral | ThisExpression | ThrowStatement | TryStatement | TSAbstractAccessorProperty | TSAbstractKeyword | TSAbstractMethodDefinition | TSAbstractPropertyDefinition | TSAnyKeyword | TSArrayType | TSAsExpression | TSAsyncKeyword | TSBigIntKeyword | TSBooleanKeyword | TSCallSignatureDeclaration | TSClassImplements | TSConditionalType | TSConstructorType | TSConstructSignatureDeclaration | TSDeclareFunction | TSDeclareKeyword | TSEmptyBodyFunctionExpression | TSEnumBody | TSEnumDeclaration | TSEnumMember | TSExportAssignment | TSExportKeyword | TSExternalModuleReference | TSFunctionType | TSImportEqualsDeclaration | TSImportType | TSIndexedAccessType | TSIndexSignature | TSInferType | TSInstantiationExpression | TSInterfaceBody | TSInterfaceDeclaration | TSInterfaceHeritage | TSIntersectionType | TSIntrinsicKeyword | TSLiteralType | TSMappedType | TSMethodSignature | TSModuleBlock | TSModuleDeclaration | TSNamedTupleMember | TSNamespaceExportDeclaration | TSNeverKeyword | TSNonNullExpression | TSNullKeyword | TSNumberKeyword | TSObjectKeyword | TSOptionalType | TSParameterProperty | TSPrivateKeyword | TSPropertySignature | TSProtectedKeyword | TSPublicKeyword | TSQualifiedName | TSReadonlyKeyword | TSRestType | TSSatisfiesExpression | TSStaticKeyword | TSStringKeyword | TSSymbolKeyword | TSTemplateLiteralType | TSThisType | TSTupleType | TSTypeAliasDeclaration | TSTypeAnnotation | TSTypeAssertion | TSTypeLiteral | TSTypeOperator | TSTypeParameter | TSTypeParameterDeclaration | TSTypeParameterInstantiation | TSTypePredicate | TSTypeQuery | TSTypeReference | TSUndefinedKeyword | TSUnionType | TSUnknownKeyword | TSVoidKeyword | UnaryExpression | UpdateExpression | VariableDeclaration | VariableDeclarator | WhileStatement | WithStatement | YieldExpression; +export declare interface NodeOrTokenData { + type: string; + /** + * The source location information of the node. + * + * The loc property is defined as nullable by ESTree, but ESLint requires this property. + */ + loc: SourceLocation; + range: Range; +} +export declare interface NullLiteral extends LiteralBase { + raw: 'null'; + value: null; +} +export declare interface NullToken extends BaseToken { + type: AST_TOKEN_TYPES.Null; +} +export declare interface NumberLiteral extends LiteralBase { + value: number; +} +export declare interface NumericToken extends BaseToken { + type: AST_TOKEN_TYPES.Numeric; +} +export declare interface ObjectExpression extends BaseNode { + type: AST_NODE_TYPES.ObjectExpression; + properties: ObjectLiteralElement[]; +} +export declare type ObjectLiteralElement = Property | SpreadElement; +export declare type ObjectLiteralElementLike = ObjectLiteralElement; +export declare interface ObjectPattern extends BaseNode { + type: AST_NODE_TYPES.ObjectPattern; + decorators: Decorator[]; + optional: boolean; + properties: (Property | RestElement)[]; + typeAnnotation: TSTypeAnnotation | undefined; +} +export declare type OptionalRangeAndLoc = { + loc?: SourceLocation; + range?: Range; +} & Pick>; +export declare type Parameter = ArrayPattern | AssignmentPattern | Identifier | ObjectPattern | RestElement | TSParameterProperty; +export declare interface Position { + /** + * Column number on the line (0-indexed) + */ + column: number; + /** + * Line number (1-indexed) + */ + line: number; +} +export declare type PrimaryExpression = ArrayExpression | ArrayPattern | ClassExpression | FunctionExpression | Identifier | JSXElement | JSXFragment | JSXOpeningElement | LiteralExpression | MetaProperty | ObjectExpression | ObjectPattern | Super | TemplateLiteral | ThisExpression | TSNullKeyword; +export declare interface PrivateIdentifier extends BaseNode { + type: AST_NODE_TYPES.PrivateIdentifier; + name: string; +} +export declare interface PrivateIdentifierToken extends BaseToken { + type: AST_TOKEN_TYPES.PrivateIdentifier; +} +export declare interface Program extends NodeOrTokenData { + type: AST_NODE_TYPES.Program; + body: ProgramStatement[]; + comments: Comment[] | undefined; + sourceType: 'module' | 'script'; + tokens: Token[] | undefined; +} +export declare type ProgramStatement = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | Statement | TSImportEqualsDeclaration | TSNamespaceExportDeclaration; +export declare type Property = PropertyComputedName | PropertyNonComputedName; +declare interface PropertyBase extends BaseNode { + type: AST_NODE_TYPES.Property; + computed: boolean; + key: PropertyName; + kind: 'get' | 'init' | 'set'; + method: boolean; + optional: boolean; + shorthand: boolean; + value: AssignmentPattern | BindingName | Expression | TSEmptyBodyFunctionExpression; +} +export declare interface PropertyComputedName extends PropertyBase { + computed: true; + key: PropertyNameComputed; +} +export declare type PropertyDefinition = PropertyDefinitionComputedName | PropertyDefinitionNonComputedName; +declare interface PropertyDefinitionBase extends BaseNode { + accessibility: Accessibility | undefined; + computed: boolean; + declare: boolean; + decorators: Decorator[]; + definite: boolean; + key: PropertyName; + optional: boolean; + override: boolean; + readonly: boolean; + static: boolean; + typeAnnotation: TSTypeAnnotation | undefined; + value: Expression | null; +} +export declare interface PropertyDefinitionComputedName extends PropertyDefinitionComputedNameBase { + type: AST_NODE_TYPES.PropertyDefinition; +} +declare interface PropertyDefinitionComputedNameBase extends PropertyDefinitionBase { + computed: true; + key: PropertyNameComputed; +} +export declare interface PropertyDefinitionNonComputedName extends ClassPropertyDefinitionNonComputedNameBase { + type: AST_NODE_TYPES.PropertyDefinition; +} +declare interface PropertyDefinitionNonComputedNameBase extends PropertyDefinitionBase { + computed: false; + key: PropertyNameNonComputed; +} +export declare type PropertyName = ClassPropertyNameNonComputed | PropertyNameComputed | PropertyNameNonComputed; +export declare type PropertyNameComputed = Expression; +export declare type PropertyNameNonComputed = Identifier | NumberLiteral | StringLiteral; +export declare interface PropertyNonComputedName extends PropertyBase { + computed: false; + key: PropertyNameNonComputed; +} +export declare interface PunctuatorToken extends BaseToken { + type: AST_TOKEN_TYPES.Punctuator; + value: ValueOf; +} +export declare interface PunctuatorTokenToText extends AssignmentOperatorToText { + [SyntaxKind.AmpersandAmpersandToken]: '&&'; + [SyntaxKind.AmpersandToken]: '&'; + [SyntaxKind.AsteriskAsteriskToken]: '**'; + [SyntaxKind.AsteriskToken]: '*'; + [SyntaxKind.AtToken]: '@'; + [SyntaxKind.BacktickToken]: '`'; + [SyntaxKind.BarBarToken]: '||'; + [SyntaxKind.BarToken]: '|'; + [SyntaxKind.CaretToken]: '^'; + [SyntaxKind.CloseBraceToken]: '}'; + [SyntaxKind.CloseBracketToken]: ']'; + [SyntaxKind.CloseParenToken]: ')'; + [SyntaxKind.ColonToken]: ':'; + [SyntaxKind.CommaToken]: ','; + [SyntaxKind.DotDotDotToken]: '...'; + [SyntaxKind.DotToken]: '.'; + [SyntaxKind.EqualsEqualsEqualsToken]: '==='; + [SyntaxKind.EqualsEqualsToken]: '=='; + [SyntaxKind.EqualsGreaterThanToken]: '=>'; + [SyntaxKind.ExclamationEqualsEqualsToken]: '!=='; + [SyntaxKind.ExclamationEqualsToken]: '!='; + [SyntaxKind.ExclamationToken]: '!'; + [SyntaxKind.GreaterThanEqualsToken]: '>='; + [SyntaxKind.GreaterThanGreaterThanGreaterThanToken]: '>>>'; + [SyntaxKind.GreaterThanGreaterThanToken]: '>>'; + [SyntaxKind.GreaterThanToken]: '>'; + [SyntaxKind.HashToken]: '#'; + [SyntaxKind.LessThanEqualsToken]: '<='; + [SyntaxKind.LessThanLessThanToken]: '<<'; + [SyntaxKind.LessThanSlashToken]: '`) is different from no declaration. + */ + typeParameters: TSTypeParameterDeclaration | undefined; +} +export declare interface TSInterfaceHeritage extends TSHeritageBase { + type: AST_NODE_TYPES.TSInterfaceHeritage; +} +export declare interface TSIntersectionType extends BaseNode { + type: AST_NODE_TYPES.TSIntersectionType; + types: TypeNode[]; +} +export declare interface TSIntrinsicKeyword extends BaseNode { + type: AST_NODE_TYPES.TSIntrinsicKeyword; +} +export declare interface TSLiteralType extends BaseNode { + type: AST_NODE_TYPES.TSLiteralType; + literal: LiteralExpression | UnaryExpression | UpdateExpression; +} +export declare interface TSMappedType extends BaseNode { + type: AST_NODE_TYPES.TSMappedType; + constraint: TypeNode; + key: Identifier; + nameType: TypeNode | null; + optional: boolean | '+' | '-' | undefined; + readonly: boolean | '+' | '-' | undefined; + typeAnnotation: TypeNode | undefined; + /** @deprecated Use {@link `constraint`} and {@link `key`} instead. */ + typeParameter: TSTypeParameter; +} +export declare type TSMethodSignature = TSMethodSignatureComputedName | TSMethodSignatureNonComputedName; +declare interface TSMethodSignatureBase extends BaseNode { + type: AST_NODE_TYPES.TSMethodSignature; + accessibility: Accessibility | undefined; + computed: boolean; + key: PropertyName; + kind: 'get' | 'method' | 'set'; + optional: boolean; + params: Parameter[]; + readonly: boolean; + returnType: TSTypeAnnotation | undefined; + static: boolean; + typeParameters: TSTypeParameterDeclaration | undefined; +} +export declare interface TSMethodSignatureComputedName extends TSMethodSignatureBase { + computed: true; + key: PropertyNameComputed; +} +export declare interface TSMethodSignatureNonComputedName extends TSMethodSignatureBase { + computed: false; + key: PropertyNameNonComputed; +} +export declare interface TSModuleBlock extends BaseNode { + type: AST_NODE_TYPES.TSModuleBlock; + body: ProgramStatement[]; +} +export declare type TSModuleDeclaration = TSModuleDeclarationGlobal | TSModuleDeclarationModule | TSModuleDeclarationNamespace; +declare interface TSModuleDeclarationBase extends BaseNode { + type: AST_NODE_TYPES.TSModuleDeclaration; + /** + * The body of the module. + * This can only be `undefined` for the code `declare module 'mod';` + */ + body?: TSModuleBlock; + /** + * Whether the module is `declare`d + * @example + * ```ts + * declare namespace F {} + * ``` + */ + declare: boolean; + /** + * Whether this is a global declaration + * @example + * ```ts + * declare global {} + * ``` + * + * @deprecated Use {@link kind} instead + */ + global: boolean; + /** + * The name of the module + * ``` + * namespace A {} + * namespace A.B.C {} + * module 'a' {} + * ``` + */ + id: Identifier | Literal | TSQualifiedName; + /** + * The keyword used to define this module declaration + * @example + * ```ts + * namespace Foo {} + * ^^^^^^^^^ + * + * module 'foo' {} + * ^^^^^^ + * + * global {} + * ^^^^^^ + * ``` + */ + kind: TSModuleDeclarationKind; +} +export declare interface TSModuleDeclarationGlobal extends TSModuleDeclarationBase { + body: TSModuleBlock; + /** + * This will always be an Identifier with name `global` + */ + id: Identifier; + kind: 'global'; +} +export declare type TSModuleDeclarationKind = 'global' | 'module' | 'namespace'; +export declare type TSModuleDeclarationModule = TSModuleDeclarationModuleWithIdentifierId | TSModuleDeclarationModuleWithStringId; +declare interface TSModuleDeclarationModuleBase extends TSModuleDeclarationBase { + kind: 'module'; +} +/** + * The legacy module declaration, replaced with namespace declarations. + * ``` + * module A {} + * ``` + */ +export declare interface TSModuleDeclarationModuleWithIdentifierId extends TSModuleDeclarationModuleBase { + body: TSModuleBlock; + id: Identifier; + kind: 'module'; +} +export declare type TSModuleDeclarationModuleWithStringId = TSModuleDeclarationModuleWithStringIdDeclared | TSModuleDeclarationModuleWithStringIdNotDeclared; +/** + * A string module declaration that is declared: + * ``` + * declare module 'foo' {} + * declare module 'foo'; + * ``` + */ +export declare interface TSModuleDeclarationModuleWithStringIdDeclared extends TSModuleDeclarationModuleBase { + body?: TSModuleBlock; + declare: true; + id: StringLiteral; + kind: 'module'; +} +/** + * A string module declaration that is not declared: + * ``` + * module 'foo' {} + * ``` + */ +export declare interface TSModuleDeclarationModuleWithStringIdNotDeclared extends TSModuleDeclarationModuleBase { + body: TSModuleBlock; + declare: false; + id: StringLiteral; + kind: 'module'; +} +export declare interface TSModuleDeclarationNamespace extends TSModuleDeclarationBase { + body: TSModuleBlock; + id: Identifier | TSQualifiedName; + kind: 'namespace'; +} +export declare interface TSNamedTupleMember extends BaseNode { + type: AST_NODE_TYPES.TSNamedTupleMember; + elementType: TypeNode; + label: Identifier; + optional: boolean; +} +/** + * For the following declaration: + * ``` + * export as namespace X; + * ``` + */ +export declare interface TSNamespaceExportDeclaration extends BaseNode { + type: AST_NODE_TYPES.TSNamespaceExportDeclaration; + /** + * The name of the global variable that's exported as namespace + */ + id: Identifier; +} +export declare interface TSNeverKeyword extends BaseNode { + type: AST_NODE_TYPES.TSNeverKeyword; +} +export declare interface TSNonNullExpression extends BaseNode { + type: AST_NODE_TYPES.TSNonNullExpression; + expression: Expression; +} +export declare interface TSNullKeyword extends BaseNode { + type: AST_NODE_TYPES.TSNullKeyword; +} +export declare interface TSNumberKeyword extends BaseNode { + type: AST_NODE_TYPES.TSNumberKeyword; +} +export declare interface TSObjectKeyword extends BaseNode { + type: AST_NODE_TYPES.TSObjectKeyword; +} +export declare interface TSOptionalType extends BaseNode { + type: AST_NODE_TYPES.TSOptionalType; + typeAnnotation: TypeNode; +} +export declare interface TSParameterProperty extends BaseNode { + type: AST_NODE_TYPES.TSParameterProperty; + accessibility: Accessibility | undefined; + decorators: Decorator[]; + override: boolean; + parameter: AssignmentPattern | BindingName | RestElement; + readonly: boolean; + static: boolean; +} +export declare interface TSPrivateKeyword extends BaseNode { + type: AST_NODE_TYPES.TSPrivateKeyword; +} +export declare type TSPropertySignature = TSPropertySignatureComputedName | TSPropertySignatureNonComputedName; +declare interface TSPropertySignatureBase extends BaseNode { + type: AST_NODE_TYPES.TSPropertySignature; + accessibility: Accessibility | undefined; + computed: boolean; + key: PropertyName; + optional: boolean; + readonly: boolean; + static: boolean; + typeAnnotation: TSTypeAnnotation | undefined; +} +export declare interface TSPropertySignatureComputedName extends TSPropertySignatureBase { + computed: true; + key: PropertyNameComputed; +} +export declare interface TSPropertySignatureNonComputedName extends TSPropertySignatureBase { + computed: false; + key: PropertyNameNonComputed; +} +export declare interface TSProtectedKeyword extends BaseNode { + type: AST_NODE_TYPES.TSProtectedKeyword; +} +export declare interface TSPublicKeyword extends BaseNode { + type: AST_NODE_TYPES.TSPublicKeyword; +} +export declare interface TSQualifiedName extends BaseNode { + type: AST_NODE_TYPES.TSQualifiedName; + left: EntityName; + right: Identifier; +} +export declare interface TSReadonlyKeyword extends BaseNode { + type: AST_NODE_TYPES.TSReadonlyKeyword; +} +export declare interface TSRestType extends BaseNode { + type: AST_NODE_TYPES.TSRestType; + typeAnnotation: TypeNode; +} +export declare interface TSSatisfiesExpression extends BaseNode { + type: AST_NODE_TYPES.TSSatisfiesExpression; + expression: Expression; + typeAnnotation: TypeNode; +} +export declare interface TSStaticKeyword extends BaseNode { + type: AST_NODE_TYPES.TSStaticKeyword; +} +export declare interface TSStringKeyword extends BaseNode { + type: AST_NODE_TYPES.TSStringKeyword; +} +export declare interface TSSymbolKeyword extends BaseNode { + type: AST_NODE_TYPES.TSSymbolKeyword; +} +export declare interface TSTemplateLiteralType extends BaseNode { + type: AST_NODE_TYPES.TSTemplateLiteralType; + quasis: TemplateElement[]; + types: TypeNode[]; +} +export declare interface TSThisType extends BaseNode { + type: AST_NODE_TYPES.TSThisType; +} +export declare interface TSTupleType extends BaseNode { + type: AST_NODE_TYPES.TSTupleType; + elementTypes: TypeNode[]; +} +export declare interface TSTypeAliasDeclaration extends BaseNode { + type: AST_NODE_TYPES.TSTypeAliasDeclaration; + /** + * Whether the type was `declare`d. + * @example + * ```ts + * declare type T = 1; + * ``` + */ + declare: boolean; + /** + * The name of the type. + */ + id: Identifier; + /** + * The "value" (type) of the declaration + */ + typeAnnotation: TypeNode; + /** + * The generic type parameters declared for the type. Empty declaration + * (`<>`) is different from no declaration. + */ + typeParameters: TSTypeParameterDeclaration | undefined; +} +export declare interface TSTypeAnnotation extends BaseNode { + type: AST_NODE_TYPES.TSTypeAnnotation; + typeAnnotation: TypeNode; +} +export declare interface TSTypeAssertion extends BaseNode { + type: AST_NODE_TYPES.TSTypeAssertion; + expression: Expression; + typeAnnotation: TypeNode; +} +export declare interface TSTypeLiteral extends BaseNode { + type: AST_NODE_TYPES.TSTypeLiteral; + members: TypeElement[]; +} +export declare interface TSTypeOperator extends BaseNode { + type: AST_NODE_TYPES.TSTypeOperator; + operator: 'keyof' | 'readonly' | 'unique'; + typeAnnotation: TypeNode | undefined; +} +export declare interface TSTypeParameter extends BaseNode { + type: AST_NODE_TYPES.TSTypeParameter; + const: boolean; + constraint: TypeNode | undefined; + default: TypeNode | undefined; + in: boolean; + name: Identifier; + out: boolean; +} +export declare interface TSTypeParameterDeclaration extends BaseNode { + type: AST_NODE_TYPES.TSTypeParameterDeclaration; + params: TSTypeParameter[]; +} +export declare interface TSTypeParameterInstantiation extends BaseNode { + type: AST_NODE_TYPES.TSTypeParameterInstantiation; + params: TypeNode[]; +} +export declare interface TSTypePredicate extends BaseNode { + type: AST_NODE_TYPES.TSTypePredicate; + asserts: boolean; + parameterName: Identifier | TSThisType; + typeAnnotation: TSTypeAnnotation | null; +} +export declare interface TSTypeQuery extends BaseNode { + type: AST_NODE_TYPES.TSTypeQuery; + exprName: EntityName | TSImportType; + typeArguments: TSTypeParameterInstantiation | undefined; +} +export declare interface TSTypeReference extends BaseNode { + type: AST_NODE_TYPES.TSTypeReference; + typeArguments: TSTypeParameterInstantiation | undefined; + typeName: EntityName; +} +export declare type TSUnaryExpression = AwaitExpression | LeftHandSideExpression | UnaryExpression | UpdateExpression; +export declare interface TSUndefinedKeyword extends BaseNode { + type: AST_NODE_TYPES.TSUndefinedKeyword; +} +export declare interface TSUnionType extends BaseNode { + type: AST_NODE_TYPES.TSUnionType; + types: TypeNode[]; +} +export declare interface TSUnknownKeyword extends BaseNode { + type: AST_NODE_TYPES.TSUnknownKeyword; +} +export declare interface TSVoidKeyword extends BaseNode { + type: AST_NODE_TYPES.TSVoidKeyword; +} +export declare type TypeElement = TSCallSignatureDeclaration | TSConstructSignatureDeclaration | TSIndexSignature | TSMethodSignature | TSPropertySignature; +export declare type TypeNode = TSAbstractKeyword | TSAnyKeyword | TSArrayType | TSAsyncKeyword | TSBigIntKeyword | TSBooleanKeyword | TSConditionalType | TSConstructorType | TSDeclareKeyword | TSExportKeyword | TSFunctionType | TSImportType | TSIndexedAccessType | TSInferType | TSIntersectionType | TSIntrinsicKeyword | TSLiteralType | TSMappedType | TSNamedTupleMember | TSNeverKeyword | TSNullKeyword | TSNumberKeyword | TSObjectKeyword | TSOptionalType | TSPrivateKeyword | TSProtectedKeyword | TSPublicKeyword | TSQualifiedName | TSReadonlyKeyword | TSRestType | TSStaticKeyword | TSStringKeyword | TSSymbolKeyword | TSTemplateLiteralType | TSThisType | TSTupleType | TSTypeLiteral | TSTypeOperator | TSTypePredicate | TSTypeQuery | TSTypeReference | TSUndefinedKeyword | TSUnionType | TSUnknownKeyword | TSVoidKeyword; +export declare interface UnaryExpression extends UnaryExpressionBase { + type: AST_NODE_TYPES.UnaryExpression; + operator: '!' | '+' | '-' | 'delete' | 'typeof' | 'void' | '~'; +} +declare interface UnaryExpressionBase extends BaseNode { + argument: Expression; + operator: string; + prefix: boolean; +} +export declare interface UpdateExpression extends UnaryExpressionBase { + type: AST_NODE_TYPES.UpdateExpression; + operator: '++' | '--'; +} +export declare type UsingDeclaration = UsingInForOfDeclaration | UsingInNormalContextDeclaration; +declare interface UsingDeclarationBase extends BaseNode { + type: AST_NODE_TYPES.VariableDeclaration; + /** + * This value will always be `false` + * because 'declare' modifier cannot appear on a 'using' declaration. + */ + declare: false; + /** + * The keyword used to declare the variable(s) + * @example + * ```ts + * using x = 1; + * await using y = 2; + * ``` + */ + kind: 'await using' | 'using'; +} +export declare type UsingDeclarator = UsingInForOfDeclarator | UsingInNormalContextDeclarator; +export declare interface UsingInForOfDeclaration extends UsingDeclarationBase { + /** + * The variables declared by this declaration. + * Always has exactly one element. + * @example + * ```ts + * for (using x of y) {} + * ``` + */ + declarations: [UsingInForOfDeclarator]; +} +export declare interface UsingInForOfDeclarator extends VariableDeclaratorBase { + definite: false; + id: Identifier; + init: null; +} +export declare interface UsingInNormalContextDeclaration extends UsingDeclarationBase { + /** + * The variables declared by this declaration. + * Always non-empty. + * @example + * ```ts + * using x = 1; + * using y = 1, z = 2; + * ``` + */ + declarations: UsingInNormalContextDeclarator[]; +} +export declare interface UsingInNormalContextDeclarator extends VariableDeclaratorBase { + definite: false; + id: Identifier; + init: Expression; +} +declare type ValueOf = T[keyof T]; +export declare type VariableDeclaration = LetOrConstOrVarDeclaration | UsingDeclaration; +export declare type VariableDeclarator = LetOrConstOrVarDeclarator | UsingDeclarator; +declare interface VariableDeclaratorBase extends BaseNode { + type: AST_NODE_TYPES.VariableDeclarator; + /** + * Whether there's definite assignment assertion (`let x!: number`). + * If `true`, then: `id` must be an identifier with a type annotation, + * `init` must be `null`, and the declarator must be a `var`/`let` declarator. + */ + definite: boolean; + /** + * The name(s) of the variable(s). + */ + id: BindingName; + /** + * The initializer expression of the variable. Must be present for `const` unless + * in a `declare const`. + */ + init: Expression | null; +} +export declare interface VariableDeclaratorDefiniteAssignment extends VariableDeclaratorBase { + definite: true; + /** + * The name of the variable. Must have a type annotation. + */ + id: Identifier; + init: null; +} +export declare interface VariableDeclaratorMaybeInit extends VariableDeclaratorBase { + definite: false; +} +export declare interface VariableDeclaratorNoInit extends VariableDeclaratorBase { + definite: false; + init: null; +} +export declare interface WhileStatement extends BaseNode { + type: AST_NODE_TYPES.WhileStatement; + body: Statement; + test: Expression; +} +export declare interface WithStatement extends BaseNode { + type: AST_NODE_TYPES.WithStatement; + body: Statement; + object: Expression; +} +export declare interface YieldExpression extends BaseNode { + type: AST_NODE_TYPES.YieldExpression; + argument: Expression | null; + delegate: boolean; +} +export {}; +//# sourceMappingURL=ast-spec.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/generated/ast-spec.d.ts.map b/node_modules/@typescript-eslint/types/dist/generated/ast-spec.d.ts.map new file mode 100644 index 00000000..d42e25c2 --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/generated/ast-spec.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ast-spec.d.ts","sourceRoot":"","sources":["../../src/generated/ast-spec.ts"],"names":[],"mappings":"AAAA;;;;;;;;gDAQgD;AAEhD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,MAAM,CAAC,OAAO,MAAM,aAAa,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,CAAC;AAEvE,MAAM,CAAC,OAAO,MAAM,gBAAgB,GAChC,4BAA4B,GAC5B,+BAA+B,CAAC;AAEpC,MAAM,CAAC,OAAO,WAAW,4BACvB,SAAQ,kCAAkC;IAC1C,IAAI,EAAE,cAAc,CAAC,gBAAgB,CAAC;CACvC;AAED,MAAM,CAAC,OAAO,WAAW,+BACvB,SAAQ,qCAAqC;IAC7C,IAAI,EAAE,cAAc,CAAC,gBAAgB,CAAC;CACvC;AAED,MAAM,CAAC,OAAO,WAAW,eAAgB,SAAQ,QAAQ;IACvD,IAAI,EAAE,cAAc,CAAC,eAAe,CAAC;IACrC;;OAEG;IACH,QAAQ,EAAE,CAAC,UAAU,GAAG,aAAa,GAAG,IAAI,CAAC,EAAE,CAAC;CACjD;AAED,MAAM,CAAC,OAAO,WAAW,YAAa,SAAQ,QAAQ;IACpD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AQ;IACvD,IAAI,EAAE,cAAc,CAAC,eAAe,CAAC;IACrC,QAAQ,EAAE,UAAU,GAAG,IAAI,CAAC;IAC5B,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/generated/ast-spec.js b/node_modules/@typescript-eslint/types/dist/generated/ast-spec.js new file mode 100644 index 00000000..bb040d3a --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/generated/ast-spec.js @@ -0,0 +1,200 @@ +"use strict"; +/********************************************** + * DO NOT MODIFY THIS FILE MANUALLY * + * * + * THIS FILE HAS BEEN COPIED FROM ast-spec. * + * ANY CHANGES WILL BE LOST ON THE NEXT BUILD * + * * + * MAKE CHANGES TO ast-spec AND THEN RUN * + * yarn build * + **********************************************/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AST_TOKEN_TYPES = exports.AST_NODE_TYPES = void 0; +var AST_NODE_TYPES; +(function (AST_NODE_TYPES) { + AST_NODE_TYPES["AccessorProperty"] = "AccessorProperty"; + AST_NODE_TYPES["ArrayExpression"] = "ArrayExpression"; + AST_NODE_TYPES["ArrayPattern"] = "ArrayPattern"; + AST_NODE_TYPES["ArrowFunctionExpression"] = "ArrowFunctionExpression"; + AST_NODE_TYPES["AssignmentExpression"] = "AssignmentExpression"; + AST_NODE_TYPES["AssignmentPattern"] = "AssignmentPattern"; + AST_NODE_TYPES["AwaitExpression"] = "AwaitExpression"; + AST_NODE_TYPES["BinaryExpression"] = "BinaryExpression"; + AST_NODE_TYPES["BlockStatement"] = "BlockStatement"; + AST_NODE_TYPES["BreakStatement"] = "BreakStatement"; + AST_NODE_TYPES["CallExpression"] = "CallExpression"; + AST_NODE_TYPES["CatchClause"] = "CatchClause"; + AST_NODE_TYPES["ChainExpression"] = "ChainExpression"; + AST_NODE_TYPES["ClassBody"] = "ClassBody"; + AST_NODE_TYPES["ClassDeclaration"] = "ClassDeclaration"; + AST_NODE_TYPES["ClassExpression"] = "ClassExpression"; + AST_NODE_TYPES["ConditionalExpression"] = "ConditionalExpression"; + AST_NODE_TYPES["ContinueStatement"] = "ContinueStatement"; + AST_NODE_TYPES["DebuggerStatement"] = "DebuggerStatement"; + AST_NODE_TYPES["Decorator"] = "Decorator"; + AST_NODE_TYPES["DoWhileStatement"] = "DoWhileStatement"; + AST_NODE_TYPES["EmptyStatement"] = "EmptyStatement"; + AST_NODE_TYPES["ExportAllDeclaration"] = "ExportAllDeclaration"; + AST_NODE_TYPES["ExportDefaultDeclaration"] = "ExportDefaultDeclaration"; + AST_NODE_TYPES["ExportNamedDeclaration"] = "ExportNamedDeclaration"; + AST_NODE_TYPES["ExportSpecifier"] = "ExportSpecifier"; + AST_NODE_TYPES["ExpressionStatement"] = "ExpressionStatement"; + AST_NODE_TYPES["ForInStatement"] = "ForInStatement"; + AST_NODE_TYPES["ForOfStatement"] = "ForOfStatement"; + AST_NODE_TYPES["ForStatement"] = "ForStatement"; + AST_NODE_TYPES["FunctionDeclaration"] = "FunctionDeclaration"; + AST_NODE_TYPES["FunctionExpression"] = "FunctionExpression"; + AST_NODE_TYPES["Identifier"] = "Identifier"; + AST_NODE_TYPES["IfStatement"] = "IfStatement"; + AST_NODE_TYPES["ImportAttribute"] = "ImportAttribute"; + AST_NODE_TYPES["ImportDeclaration"] = "ImportDeclaration"; + AST_NODE_TYPES["ImportDefaultSpecifier"] = "ImportDefaultSpecifier"; + AST_NODE_TYPES["ImportExpression"] = "ImportExpression"; + AST_NODE_TYPES["ImportNamespaceSpecifier"] = "ImportNamespaceSpecifier"; + AST_NODE_TYPES["ImportSpecifier"] = "ImportSpecifier"; + AST_NODE_TYPES["JSXAttribute"] = "JSXAttribute"; + AST_NODE_TYPES["JSXClosingElement"] = "JSXClosingElement"; + AST_NODE_TYPES["JSXClosingFragment"] = "JSXClosingFragment"; + AST_NODE_TYPES["JSXElement"] = "JSXElement"; + AST_NODE_TYPES["JSXEmptyExpression"] = "JSXEmptyExpression"; + AST_NODE_TYPES["JSXExpressionContainer"] = "JSXExpressionContainer"; + AST_NODE_TYPES["JSXFragment"] = "JSXFragment"; + AST_NODE_TYPES["JSXIdentifier"] = "JSXIdentifier"; + AST_NODE_TYPES["JSXMemberExpression"] = "JSXMemberExpression"; + AST_NODE_TYPES["JSXNamespacedName"] = "JSXNamespacedName"; + AST_NODE_TYPES["JSXOpeningElement"] = "JSXOpeningElement"; + AST_NODE_TYPES["JSXOpeningFragment"] = "JSXOpeningFragment"; + AST_NODE_TYPES["JSXSpreadAttribute"] = "JSXSpreadAttribute"; + AST_NODE_TYPES["JSXSpreadChild"] = "JSXSpreadChild"; + AST_NODE_TYPES["JSXText"] = "JSXText"; + AST_NODE_TYPES["LabeledStatement"] = "LabeledStatement"; + AST_NODE_TYPES["Literal"] = "Literal"; + AST_NODE_TYPES["LogicalExpression"] = "LogicalExpression"; + AST_NODE_TYPES["MemberExpression"] = "MemberExpression"; + AST_NODE_TYPES["MetaProperty"] = "MetaProperty"; + AST_NODE_TYPES["MethodDefinition"] = "MethodDefinition"; + AST_NODE_TYPES["NewExpression"] = "NewExpression"; + AST_NODE_TYPES["ObjectExpression"] = "ObjectExpression"; + AST_NODE_TYPES["ObjectPattern"] = "ObjectPattern"; + AST_NODE_TYPES["PrivateIdentifier"] = "PrivateIdentifier"; + AST_NODE_TYPES["Program"] = "Program"; + AST_NODE_TYPES["Property"] = "Property"; + AST_NODE_TYPES["PropertyDefinition"] = "PropertyDefinition"; + AST_NODE_TYPES["RestElement"] = "RestElement"; + AST_NODE_TYPES["ReturnStatement"] = "ReturnStatement"; + AST_NODE_TYPES["SequenceExpression"] = "SequenceExpression"; + AST_NODE_TYPES["SpreadElement"] = "SpreadElement"; + AST_NODE_TYPES["StaticBlock"] = "StaticBlock"; + AST_NODE_TYPES["Super"] = "Super"; + AST_NODE_TYPES["SwitchCase"] = "SwitchCase"; + AST_NODE_TYPES["SwitchStatement"] = "SwitchStatement"; + AST_NODE_TYPES["TaggedTemplateExpression"] = "TaggedTemplateExpression"; + AST_NODE_TYPES["TemplateElement"] = "TemplateElement"; + AST_NODE_TYPES["TemplateLiteral"] = "TemplateLiteral"; + AST_NODE_TYPES["ThisExpression"] = "ThisExpression"; + AST_NODE_TYPES["ThrowStatement"] = "ThrowStatement"; + AST_NODE_TYPES["TryStatement"] = "TryStatement"; + AST_NODE_TYPES["UnaryExpression"] = "UnaryExpression"; + AST_NODE_TYPES["UpdateExpression"] = "UpdateExpression"; + AST_NODE_TYPES["VariableDeclaration"] = "VariableDeclaration"; + AST_NODE_TYPES["VariableDeclarator"] = "VariableDeclarator"; + AST_NODE_TYPES["WhileStatement"] = "WhileStatement"; + AST_NODE_TYPES["WithStatement"] = "WithStatement"; + AST_NODE_TYPES["YieldExpression"] = "YieldExpression"; + AST_NODE_TYPES["TSAbstractAccessorProperty"] = "TSAbstractAccessorProperty"; + AST_NODE_TYPES["TSAbstractKeyword"] = "TSAbstractKeyword"; + AST_NODE_TYPES["TSAbstractMethodDefinition"] = "TSAbstractMethodDefinition"; + AST_NODE_TYPES["TSAbstractPropertyDefinition"] = "TSAbstractPropertyDefinition"; + AST_NODE_TYPES["TSAnyKeyword"] = "TSAnyKeyword"; + AST_NODE_TYPES["TSArrayType"] = "TSArrayType"; + AST_NODE_TYPES["TSAsExpression"] = "TSAsExpression"; + AST_NODE_TYPES["TSAsyncKeyword"] = "TSAsyncKeyword"; + AST_NODE_TYPES["TSBigIntKeyword"] = "TSBigIntKeyword"; + AST_NODE_TYPES["TSBooleanKeyword"] = "TSBooleanKeyword"; + AST_NODE_TYPES["TSCallSignatureDeclaration"] = "TSCallSignatureDeclaration"; + AST_NODE_TYPES["TSClassImplements"] = "TSClassImplements"; + AST_NODE_TYPES["TSConditionalType"] = "TSConditionalType"; + AST_NODE_TYPES["TSConstructorType"] = "TSConstructorType"; + AST_NODE_TYPES["TSConstructSignatureDeclaration"] = "TSConstructSignatureDeclaration"; + AST_NODE_TYPES["TSDeclareFunction"] = "TSDeclareFunction"; + AST_NODE_TYPES["TSDeclareKeyword"] = "TSDeclareKeyword"; + AST_NODE_TYPES["TSEmptyBodyFunctionExpression"] = "TSEmptyBodyFunctionExpression"; + AST_NODE_TYPES["TSEnumBody"] = "TSEnumBody"; + AST_NODE_TYPES["TSEnumDeclaration"] = "TSEnumDeclaration"; + AST_NODE_TYPES["TSEnumMember"] = "TSEnumMember"; + AST_NODE_TYPES["TSExportAssignment"] = "TSExportAssignment"; + AST_NODE_TYPES["TSExportKeyword"] = "TSExportKeyword"; + AST_NODE_TYPES["TSExternalModuleReference"] = "TSExternalModuleReference"; + AST_NODE_TYPES["TSFunctionType"] = "TSFunctionType"; + AST_NODE_TYPES["TSImportEqualsDeclaration"] = "TSImportEqualsDeclaration"; + AST_NODE_TYPES["TSImportType"] = "TSImportType"; + AST_NODE_TYPES["TSIndexedAccessType"] = "TSIndexedAccessType"; + AST_NODE_TYPES["TSIndexSignature"] = "TSIndexSignature"; + AST_NODE_TYPES["TSInferType"] = "TSInferType"; + AST_NODE_TYPES["TSInstantiationExpression"] = "TSInstantiationExpression"; + AST_NODE_TYPES["TSInterfaceBody"] = "TSInterfaceBody"; + AST_NODE_TYPES["TSInterfaceDeclaration"] = "TSInterfaceDeclaration"; + AST_NODE_TYPES["TSInterfaceHeritage"] = "TSInterfaceHeritage"; + AST_NODE_TYPES["TSIntersectionType"] = "TSIntersectionType"; + AST_NODE_TYPES["TSIntrinsicKeyword"] = "TSIntrinsicKeyword"; + AST_NODE_TYPES["TSLiteralType"] = "TSLiteralType"; + AST_NODE_TYPES["TSMappedType"] = "TSMappedType"; + AST_NODE_TYPES["TSMethodSignature"] = "TSMethodSignature"; + AST_NODE_TYPES["TSModuleBlock"] = "TSModuleBlock"; + AST_NODE_TYPES["TSModuleDeclaration"] = "TSModuleDeclaration"; + AST_NODE_TYPES["TSNamedTupleMember"] = "TSNamedTupleMember"; + AST_NODE_TYPES["TSNamespaceExportDeclaration"] = "TSNamespaceExportDeclaration"; + AST_NODE_TYPES["TSNeverKeyword"] = "TSNeverKeyword"; + AST_NODE_TYPES["TSNonNullExpression"] = "TSNonNullExpression"; + AST_NODE_TYPES["TSNullKeyword"] = "TSNullKeyword"; + AST_NODE_TYPES["TSNumberKeyword"] = "TSNumberKeyword"; + AST_NODE_TYPES["TSObjectKeyword"] = "TSObjectKeyword"; + AST_NODE_TYPES["TSOptionalType"] = "TSOptionalType"; + AST_NODE_TYPES["TSParameterProperty"] = "TSParameterProperty"; + AST_NODE_TYPES["TSPrivateKeyword"] = "TSPrivateKeyword"; + AST_NODE_TYPES["TSPropertySignature"] = "TSPropertySignature"; + AST_NODE_TYPES["TSProtectedKeyword"] = "TSProtectedKeyword"; + AST_NODE_TYPES["TSPublicKeyword"] = "TSPublicKeyword"; + AST_NODE_TYPES["TSQualifiedName"] = "TSQualifiedName"; + AST_NODE_TYPES["TSReadonlyKeyword"] = "TSReadonlyKeyword"; + AST_NODE_TYPES["TSRestType"] = "TSRestType"; + AST_NODE_TYPES["TSSatisfiesExpression"] = "TSSatisfiesExpression"; + AST_NODE_TYPES["TSStaticKeyword"] = "TSStaticKeyword"; + AST_NODE_TYPES["TSStringKeyword"] = "TSStringKeyword"; + AST_NODE_TYPES["TSSymbolKeyword"] = "TSSymbolKeyword"; + AST_NODE_TYPES["TSTemplateLiteralType"] = "TSTemplateLiteralType"; + AST_NODE_TYPES["TSThisType"] = "TSThisType"; + AST_NODE_TYPES["TSTupleType"] = "TSTupleType"; + AST_NODE_TYPES["TSTypeAliasDeclaration"] = "TSTypeAliasDeclaration"; + AST_NODE_TYPES["TSTypeAnnotation"] = "TSTypeAnnotation"; + AST_NODE_TYPES["TSTypeAssertion"] = "TSTypeAssertion"; + AST_NODE_TYPES["TSTypeLiteral"] = "TSTypeLiteral"; + AST_NODE_TYPES["TSTypeOperator"] = "TSTypeOperator"; + AST_NODE_TYPES["TSTypeParameter"] = "TSTypeParameter"; + AST_NODE_TYPES["TSTypeParameterDeclaration"] = "TSTypeParameterDeclaration"; + AST_NODE_TYPES["TSTypeParameterInstantiation"] = "TSTypeParameterInstantiation"; + AST_NODE_TYPES["TSTypePredicate"] = "TSTypePredicate"; + AST_NODE_TYPES["TSTypeQuery"] = "TSTypeQuery"; + AST_NODE_TYPES["TSTypeReference"] = "TSTypeReference"; + AST_NODE_TYPES["TSUndefinedKeyword"] = "TSUndefinedKeyword"; + AST_NODE_TYPES["TSUnionType"] = "TSUnionType"; + AST_NODE_TYPES["TSUnknownKeyword"] = "TSUnknownKeyword"; + AST_NODE_TYPES["TSVoidKeyword"] = "TSVoidKeyword"; +})(AST_NODE_TYPES || (exports.AST_NODE_TYPES = AST_NODE_TYPES = {})); +var AST_TOKEN_TYPES; +(function (AST_TOKEN_TYPES) { + AST_TOKEN_TYPES["Boolean"] = "Boolean"; + AST_TOKEN_TYPES["Identifier"] = "Identifier"; + AST_TOKEN_TYPES["JSXIdentifier"] = "JSXIdentifier"; + AST_TOKEN_TYPES["PrivateIdentifier"] = "PrivateIdentifier"; + AST_TOKEN_TYPES["JSXText"] = "JSXText"; + AST_TOKEN_TYPES["Keyword"] = "Keyword"; + AST_TOKEN_TYPES["Null"] = "Null"; + AST_TOKEN_TYPES["Numeric"] = "Numeric"; + AST_TOKEN_TYPES["Punctuator"] = "Punctuator"; + AST_TOKEN_TYPES["RegularExpression"] = "RegularExpression"; + AST_TOKEN_TYPES["String"] = "String"; + AST_TOKEN_TYPES["Template"] = "Template"; + AST_TOKEN_TYPES["Block"] = "Block"; + AST_TOKEN_TYPES["Line"] = "Line"; +})(AST_TOKEN_TYPES || (exports.AST_TOKEN_TYPES = AST_TOKEN_TYPES = {})); diff --git a/node_modules/@typescript-eslint/types/dist/index.d.ts b/node_modules/@typescript-eslint/types/dist/index.d.ts new file mode 100644 index 00000000..3d39147f --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/index.d.ts @@ -0,0 +1,5 @@ +export { AST_NODE_TYPES, AST_TOKEN_TYPES } from './generated/ast-spec'; +export * from './lib'; +export * from './parser-options'; +export * from './ts-estree'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/index.d.ts.map b/node_modules/@typescript-eslint/types/dist/index.d.ts.map new file mode 100644 index 00000000..6a86c537 --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvE,cAAc,OAAO,CAAC;AACtB,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/index.js b/node_modules/@typescript-eslint/types/dist/index.js new file mode 100644 index 00000000..837a2321 --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/index.js @@ -0,0 +1,23 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AST_TOKEN_TYPES = exports.AST_NODE_TYPES = void 0; +var ast_spec_1 = require("./generated/ast-spec"); +Object.defineProperty(exports, "AST_NODE_TYPES", { enumerable: true, get: function () { return ast_spec_1.AST_NODE_TYPES; } }); +Object.defineProperty(exports, "AST_TOKEN_TYPES", { enumerable: true, get: function () { return ast_spec_1.AST_TOKEN_TYPES; } }); +__exportStar(require("./lib"), exports); +__exportStar(require("./parser-options"), exports); +__exportStar(require("./ts-estree"), exports); diff --git a/node_modules/@typescript-eslint/types/dist/lib.d.ts b/node_modules/@typescript-eslint/types/dist/lib.d.ts new file mode 100644 index 00000000..90b63d56 --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/lib.d.ts @@ -0,0 +1,2 @@ +export type Lib = 'decorators' | 'decorators.legacy' | 'dom' | 'dom.asynciterable' | 'dom.iterable' | 'es5' | 'es6' | 'es7' | 'es2015' | 'es2015.collection' | 'es2015.core' | 'es2015.generator' | 'es2015.iterable' | 'es2015.promise' | 'es2015.proxy' | 'es2015.reflect' | 'es2015.symbol' | 'es2015.symbol.wellknown' | 'es2016' | 'es2016.array.include' | 'es2016.full' | 'es2016.intl' | 'es2017' | 'es2017.arraybuffer' | 'es2017.date' | 'es2017.full' | 'es2017.intl' | 'es2017.object' | 'es2017.sharedmemory' | 'es2017.string' | 'es2017.typedarrays' | 'es2018' | 'es2018.asyncgenerator' | 'es2018.asynciterable' | 'es2018.full' | 'es2018.intl' | 'es2018.promise' | 'es2018.regexp' | 'es2019' | 'es2019.array' | 'es2019.full' | 'es2019.intl' | 'es2019.object' | 'es2019.string' | 'es2019.symbol' | 'es2020' | 'es2020.bigint' | 'es2020.date' | 'es2020.full' | 'es2020.intl' | 'es2020.number' | 'es2020.promise' | 'es2020.sharedmemory' | 'es2020.string' | 'es2020.symbol.wellknown' | 'es2021' | 'es2021.full' | 'es2021.intl' | 'es2021.promise' | 'es2021.string' | 'es2021.weakref' | 'es2022' | 'es2022.array' | 'es2022.error' | 'es2022.full' | 'es2022.intl' | 'es2022.object' | 'es2022.regexp' | 'es2022.string' | 'es2023' | 'es2023.array' | 'es2023.collection' | 'es2023.full' | 'es2023.intl' | 'es2024' | 'es2024.arraybuffer' | 'es2024.collection' | 'es2024.full' | 'es2024.object' | 'es2024.promise' | 'es2024.regexp' | 'es2024.sharedmemory' | 'es2024.string' | 'esnext' | 'esnext.array' | 'esnext.asynciterable' | 'esnext.bigint' | 'esnext.collection' | 'esnext.decorators' | 'esnext.disposable' | 'esnext.float16' | 'esnext.full' | 'esnext.intl' | 'esnext.iterator' | 'esnext.object' | 'esnext.promise' | 'esnext.regexp' | 'esnext.string' | 'esnext.symbol' | 'esnext.weakref' | 'lib' | 'scripthost' | 'webworker' | 'webworker.asynciterable' | 'webworker.importscripts' | 'webworker.iterable'; +//# sourceMappingURL=lib.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/lib.d.ts.map b/node_modules/@typescript-eslint/types/dist/lib.d.ts.map new file mode 100644 index 00000000..4f09ac45 --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/lib.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../src/lib.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,GAAG,GACX,YAAY,GACZ,mBAAmB,GACnB,KAAK,GACL,mBAAmB,GACnB,cAAc,GACd,KAAK,GACL,KAAK,GACL,KAAK,GACL,QAAQ,GACR,mBAAmB,GACnB,aAAa,GACb,kBAAkB,GAClB,iBAAiB,GACjB,gBAAgB,GAChB,cAAc,GACd,gBAAgB,GAChB,eAAe,GACf,yBAAyB,GACzB,QAAQ,GACR,sBAAsB,GACtB,aAAa,GACb,aAAa,GACb,QAAQ,GACR,oBAAoB,GACpB,aAAa,GACb,aAAa,GACb,aAAa,GACb,eAAe,GACf,qBAAqB,GACrB,eAAe,GACf,oBAAoB,GACpB,QAAQ,GACR,uBAAuB,GACvB,sBAAsB,GACtB,aAAa,GACb,aAAa,GACb,gBAAgB,GAChB,eAAe,GACf,QAAQ,GACR,cAAc,GACd,aAAa,GACb,aAAa,GACb,eAAe,GACf,eAAe,GACf,eAAe,GACf,QAAQ,GACR,eAAe,GACf,aAAa,GACb,aAAa,GACb,aAAa,GACb,eAAe,GACf,gBAAgB,GAChB,qBAAqB,GACrB,eAAe,GACf,yBAAyB,GACzB,QAAQ,GACR,aAAa,GACb,aAAa,GACb,gBAAgB,GAChB,eAAe,GACf,gBAAgB,GAChB,QAAQ,GACR,cAAc,GACd,cAAc,GACd,aAAa,GACb,aAAa,GACb,eAAe,GACf,eAAe,GACf,eAAe,GACf,QAAQ,GACR,cAAc,GACd,mBAAmB,GACnB,aAAa,GACb,aAAa,GACb,QAAQ,GACR,oBAAoB,GACpB,mBAAmB,GACnB,aAAa,GACb,eAAe,GACf,gBAAgB,GAChB,eAAe,GACf,qBAAqB,GACrB,eAAe,GACf,QAAQ,GACR,cAAc,GACd,sBAAsB,GACtB,eAAe,GACf,mBAAmB,GACnB,mBAAmB,GACnB,mBAAmB,GACnB,gBAAgB,GAChB,aAAa,GACb,aAAa,GACb,iBAAiB,GACjB,eAAe,GACf,gBAAgB,GAChB,eAAe,GACf,eAAe,GACf,eAAe,GACf,gBAAgB,GAChB,KAAK,GACL,YAAY,GACZ,WAAW,GACX,yBAAyB,GACzB,yBAAyB,GACzB,oBAAoB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/lib.js b/node_modules/@typescript-eslint/types/dist/lib.js new file mode 100644 index 00000000..fa29352b --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/lib.js @@ -0,0 +1,6 @@ +"use strict"; +// THIS CODE WAS AUTOMATICALLY GENERATED +// DO NOT EDIT THIS CODE BY HAND +// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE: +// npx nx generate-lib repo +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/types/dist/parser-options.d.ts b/node_modules/@typescript-eslint/types/dist/parser-options.d.ts new file mode 100644 index 00000000..5923587f --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/parser-options.d.ts @@ -0,0 +1,69 @@ +import type { Program } from 'typescript'; +import type { Lib } from './lib'; +export type DebugLevel = boolean | ('eslint' | 'typescript' | 'typescript-eslint')[]; +export type CacheDurationSeconds = number | 'Infinity'; +export type EcmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | 'latest' | undefined; +export type SourceTypeClassic = 'module' | 'script'; +export type SourceType = 'commonjs' | SourceTypeClassic; +export type JSDocParsingMode = 'all' | 'none' | 'type-info'; +/** + * Granular options to configure the project service. + */ +export interface ProjectServiceOptions { + /** + * Globs of files to allow running with the default project compiler options + * despite not being matched by the project service. + */ + allowDefaultProject?: string[]; + /** + * Path to a TSConfig to use instead of TypeScript's default project configuration. + * @default 'tsconfig.json' + */ + defaultProject?: string; + /** + * Whether to allow TypeScript plugins as configured in the TSConfig. + */ + loadTypeScriptPlugins?: boolean; + /** + * The maximum number of files {@link allowDefaultProject} may match. + * Each file match slows down linting, so if you do need to use this, please + * file an informative issue on typescript-eslint explaining why - so we can + * help you avoid using it! + * @default 8 + */ + maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING?: number; +} +export interface ParserOptions { + [additionalProperties: string]: unknown; + cacheLifetime?: { + glob?: CacheDurationSeconds; + }; + debugLevel?: DebugLevel; + ecmaFeatures?: { + [key: string]: unknown; + globalReturn?: boolean | undefined; + jsx?: boolean | undefined; + } | undefined; + ecmaVersion?: EcmaVersion; + emitDecoratorMetadata?: boolean; + errorOnTypeScriptSyntacticAndSemanticIssues?: boolean; + errorOnUnknownASTType?: boolean; + experimentalDecorators?: boolean; + extraFileExtensions?: string[]; + filePath?: string; + isolatedDeclarations?: boolean; + jsDocParsingMode?: JSDocParsingMode; + jsxFragmentName?: string | null; + jsxPragma?: string | null; + lib?: Lib[]; + programs?: Program[] | null; + project?: boolean | string | string[] | null; + projectFolderIgnoreList?: string[]; + projectService?: boolean | ProjectServiceOptions; + range?: boolean; + sourceType?: SourceType | undefined; + tokens?: boolean; + tsconfigRootDir?: string; + warnOnUnsupportedTypeScriptVersion?: boolean; +} +//# sourceMappingURL=parser-options.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/parser-options.d.ts.map b/node_modules/@typescript-eslint/types/dist/parser-options.d.ts.map new file mode 100644 index 00000000..6c0fff12 --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/parser-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parser-options.d.ts","sourceRoot":"","sources":["../src/parser-options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAEjC,MAAM,MAAM,UAAU,GAClB,OAAO,GACP,CAAC,QAAQ,GAAG,YAAY,GAAG,mBAAmB,CAAC,EAAE,CAAC;AACtD,MAAM,MAAM,oBAAoB,GAAG,MAAM,GAAG,UAAU,CAAC;AAEvD,MAAM,MAAM,WAAW,GACnB,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,GACD,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,EAAE,GACF,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,QAAQ,GACR,SAAS,CAAC;AAEd,MAAM,MAAM,iBAAiB,GAAG,QAAQ,GAAG,QAAQ,CAAC;AACpD,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,iBAAiB,CAAC;AAExD,MAAM,MAAM,gBAAgB,GAAG,KAAK,GAAG,MAAM,GAAG,WAAW,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;IAE/B;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB;;OAEG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAEhC;;;;;;OAMG;IACH,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C,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB,kCAAkC,CAAC,EAAE,OAAO,CAAC;CAC9C"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/parser-options.js b/node_modules/@typescript-eslint/types/dist/parser-options.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/parser-options.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/types/dist/ts-estree.d.ts b/node_modules/@typescript-eslint/types/dist/ts-estree.d.ts new file mode 100644 index 00000000..49753fa5 --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/ts-estree.d.ts @@ -0,0 +1,191 @@ +import type * as TSESTree from './generated/ast-spec'; +declare module './generated/ast-spec' { + interface BaseNode { + parent: TSESTree.Node; + } + interface Program { + /** + * @remarks This never-used property exists only as a convenience for code that tries to access node parents repeatedly. + */ + parent?: never; + } + interface AccessorPropertyComputedName { + parent: TSESTree.ClassBody; + } + interface AccessorPropertyNonComputedName { + parent: TSESTree.ClassBody; + } + interface TSAbstractAccessorPropertyComputedName { + parent: TSESTree.ClassBody; + } + interface TSAbstractAccessorPropertyNonComputedName { + parent: TSESTree.ClassBody; + } + interface VariableDeclaratorDefiniteAssignment { + parent: TSESTree.VariableDeclaration; + } + interface VariableDeclaratorMaybeInit { + parent: TSESTree.VariableDeclaration; + } + interface VariableDeclaratorNoInit { + parent: TSESTree.VariableDeclaration; + } + interface UsingInForOfDeclarator { + parent: TSESTree.VariableDeclaration; + } + interface UsingInNormalContextDeclarator { + parent: TSESTree.VariableDeclaration; + } + interface CatchClause { + parent: TSESTree.TryStatement; + } + interface ClassBody { + parent: TSESTree.ClassDeclaration | TSESTree.ClassExpression; + } + interface ImportAttribute { + parent: TSESTree.ExportAllDeclaration | TSESTree.ExportNamedDeclaration | TSESTree.ImportDeclaration | TSESTree.TSImportType; + } + interface ImportDefaultSpecifier { + parent: TSESTree.ImportDeclaration; + } + interface ImportNamespaceSpecifier { + parent: TSESTree.ImportDeclaration; + } + interface ImportSpecifier { + parent: TSESTree.ExportAllDeclaration | TSESTree.ExportNamedDeclaration | TSESTree.ImportDeclaration; + } + interface ExportDefaultDeclaration { + parent: TSESTree.BlockStatement | TSESTree.Program | TSESTree.TSModuleBlock; + } + interface ExportNamedDeclarationWithoutSourceWithMultiple { + parent: TSESTree.BlockStatement | TSESTree.Program | TSESTree.TSModuleBlock; + } + interface ExportNamedDeclarationWithoutSourceWithSingle { + parent: TSESTree.BlockStatement | TSESTree.Program | TSESTree.TSModuleBlock; + } + interface ExportNamedDeclarationWithSource { + parent: TSESTree.BlockStatement | TSESTree.Program | TSESTree.TSModuleBlock; + } + interface FunctionDeclarationWithName { + parent: TSESTree.BlockStatement | TSESTree.ExportDefaultDeclaration | TSESTree.ExportNamedDeclaration | TSESTree.Program; + } + interface FunctionDeclarationWithOptionalName { + parent: TSESTree.ExportDefaultDeclaration; + } + interface JSXAttribute { + parent: TSESTree.JSXOpeningElement; + } + interface JSXClosingElement { + parent: TSESTree.JSXElement; + } + interface JSXClosingFragment { + parent: TSESTree.JSXFragment; + } + interface JSXOpeningElement { + parent: TSESTree.JSXElement; + } + interface JSXOpeningFragment { + parent: TSESTree.JSXFragment; + } + interface JSXSpreadAttribute { + parent: TSESTree.JSXOpeningElement; + } + interface MethodDefinitionComputedName { + parent: TSESTree.ClassBody; + } + interface MethodDefinitionNonComputedName { + parent: TSESTree.ClassBody; + } + interface TSAbstractMethodDefinitionComputedName { + parent: TSESTree.ClassBody; + } + interface TSAbstractMethodDefinitionNonComputedName { + parent: TSESTree.ClassBody; + } + interface PropertyComputedName { + parent: TSESTree.ObjectExpression | TSESTree.ObjectPattern; + } + interface PropertyNonComputedName { + parent: TSESTree.ObjectExpression | TSESTree.ObjectPattern; + } + interface PropertyDefinitionComputedName { + parent: TSESTree.ClassBody; + } + interface PropertyDefinitionNonComputedName { + parent: TSESTree.ClassBody; + } + interface TSAbstractPropertyDefinitionComputedName { + parent: TSESTree.ClassBody; + } + interface TSAbstractPropertyDefinitionNonComputedName { + parent: TSESTree.ClassBody; + } + interface SpreadElement { + parent: TSESTree.ArrayExpression | TSESTree.CallExpression | TSESTree.NewExpression | TSESTree.ObjectExpression; + } + interface StaticBlock { + parent: TSESTree.ClassBody; + } + interface SwitchCase { + parent: TSESTree.SwitchStatement; + } + interface TemplateElement { + parent: TSESTree.TemplateLiteral | TSESTree.TSTemplateLiteralType; + } + interface TSCallSignatureDeclaration { + parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral; + } + interface TSConstructSignatureDeclaration { + parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral; + } + interface TSClassImplements { + parent: TSESTree.ClassDeclaration | TSESTree.ClassExpression; + } + interface TSEnumBody { + parent: TSESTree.TSEnumDeclaration; + } + interface TSEnumMemberComputedName { + parent: TSESTree.TSEnumBody; + } + interface TSEnumMemberNonComputedName { + parent: TSESTree.TSEnumBody; + } + interface TSIndexSignature { + parent: TSESTree.ClassBody | TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral; + } + interface TSInterfaceBody { + parent: TSESTree.TSInterfaceDeclaration; + } + interface TSInterfaceHeritage { + parent: TSESTree.TSInterfaceBody; + } + interface TSMethodSignatureComputedName { + parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral; + } + interface TSMethodSignatureNonComputedName { + parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral; + } + interface TSModuleBlock { + parent: TSESTree.TSModuleDeclaration; + } + interface TSParameterProperty { + parent: TSESTree.FunctionLike; + } + interface TSPropertySignatureComputedName { + parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral; + } + interface TSPropertySignatureNonComputedName { + parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral; + } + interface TSTypeParameter { + parent: TSESTree.TSInferType | TSESTree.TSMappedType | TSESTree.TSTypeParameterDeclaration; + } + interface ExportSpecifierWithIdentifierLocal { + parent: TSESTree.ExportNamedDeclaration; + } + interface ExportSpecifierWithStringOrLiteralLocal { + parent: TSESTree.ExportNamedDeclaration; + } +} +export * as TSESTree from './generated/ast-spec'; +//# sourceMappingURL=ts-estree.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/ts-estree.d.ts.map b/node_modules/@typescript-eslint/types/dist/ts-estree.d.ts.map new file mode 100644 index 00000000..2f9f374d --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/ts-estree.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ts-estree.d.ts","sourceRoot":"","sources":["../src/ts-estree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,QAAQ,MAAM,sBAAsB,CAAC;AAGtD,OAAO,QAAQ,sBAAsB,CAAC;IACpC,UAAU,QAAQ;QAChB,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC;KACvB;IAED,UAAU,OAAO;QACf;;WAEG;QACH,MAAM,CAAC,EAAE,KAAK,CAAC;KAChB;IAED,UAAU,4BAA4B;QACpC,MAAM,EAAE,QAAQ,CAAC,SAAS,CAAC;KAC5B;IACD,UAAU,+BAA+B;QACvC,MAAM,EAAE,QAAQ,CAAC,SAAS,CAAC;KAC5B;IACD,UAAU,sCAAsC;QAC9C,MAAM,EAAE,QAAQ,CAAC,SAAS,CAAC;KAC5B;IACD,UAAU,yCAAyC;QACjD,MAAM,EAAE,QAAQ,CAAC,SAAS,CAAC;KAC5B;IAED,UAAU,oCAAoC;QAC5C,MAAM,EAAE,QAAQ,CAAC,mBAAmB,CAAC;KACtC;IACD,UAAU,2BAA2B;QACnC,MAAM,EAAE,QAAQ,CAAC,mBAAmB,CAAC;KACtC;IACD,UAAU,wBAAwB;QAChC,MAAM,EAAE,QAAQ,CAAC,mBAAmB,CAAC;KACtC;IACD,UAAU,sBAAsB;QAC9B,MAAM,EAAE,QAAQ,CAAC,mBAAmB,CAAC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AAM,EAAE,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC,aAAa,CAAC;KAC3D;IACD,UAAU,gCAAgC;QACxC,MAAM,EAAE,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC,aAAa,CAAC;KAC3D;IAED,UAAU,aAAa;QACrB,MAAM,EAAE,QAAQ,CAAC,mBAAmB,CAAC;KACtC;IAED,UAAU,mBAAmB;QAC3B,MAAM,EAAE,QAAQ,CAAC,YAAY,CAAC;KAC/B;IAED,UAAU,+BAA+B;QACvC,MAAM,EAAE,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC,aAAa,CAAC;KAC3D;IACD,UAAU,kCAAkC;QAC1C,MAAM,EAAE,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC,aAAa,CAAC;KAC3D;IAED,UAAU,eAAe;QACvB,MAAM,EACF,QAAQ,CAAC,WAAW,GACpB,QAAQ,CAAC,YAAY,GACrB,QAAQ,CAAC,0BAA0B,CAAC;KACzC;IAED,UAAU,kCAAkC;QAC1C,MAAM,EAAE,QAAQ,CAAC,sBAAsB,CAAC;KACzC;IACD,UAAU,uCAAuC;QAC/C,MAAM,EAAE,QAAQ,CAAC,sBAAsB,CAAC;KACzC;CACF;AAED,OAAO,KAAK,QAAQ,MAAM,sBAAsB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/dist/ts-estree.js b/node_modules/@typescript-eslint/types/dist/ts-estree.js new file mode 100644 index 00000000..004be3cd --- /dev/null +++ b/node_modules/@typescript-eslint/types/dist/ts-estree.js @@ -0,0 +1,37 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSESTree = void 0; +exports.TSESTree = __importStar(require("./generated/ast-spec")); diff --git a/node_modules/@typescript-eslint/types/package.json b/node_modules/@typescript-eslint/types/package.json new file mode 100644 index 00000000..6761a72c --- /dev/null +++ b/node_modules/@typescript-eslint/types/package.json @@ -0,0 +1,87 @@ +{ + "name": "@typescript-eslint/types", + "version": "8.34.0", + "description": "Types for the TypeScript-ESTree AST spec", + "files": [ + "dist", + "!*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/types" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ src/generated/ coverage/", + "copy-ast-spec": "tsx ./tools/copy-ast-spec.mts", + "format": "yarn run -T format", + "generate-lib": "yarn run -BT nx run scope-manager:generate-lib", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "devDependencies": { + "@vitest/coverage-v8": "^3.1.3", + "rimraf": "*", + "tsx": "*", + "typescript": "*", + "vitest": "^3.1.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "types", + "includedScripts": [ + "clean" + ], + "targets": { + "build": { + "dependsOn": [ + "copy-ast-spec" + ] + }, + "copy-ast-spec": { + "command": "tsx ./tools/copy-ast-spec.mts", + "options": { + "cwd": "{projectRoot}" + }, + "dependsOn": [ + "ast-spec:build" + ], + "outputs": [ + "{projectRoot}/src/generated" + ], + "cache": true + } + } + } +} diff --git a/node_modules/@typescript-eslint/typescript-estree/LICENSE b/node_modules/@typescript-eslint/typescript-estree/LICENSE new file mode 100644 index 00000000..a1164108 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/typescript-estree/README.md b/node_modules/@typescript-eslint/typescript-estree/README.md new file mode 100644 index 00000000..c98838da --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/README.md @@ -0,0 +1,14 @@ +# `@typescript-eslint/typescript-estree` + +> A parser that produces an ESTree-compatible AST for TypeScript code. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/typescript-estree.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/typescript-estree.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) + +## Contributing + +👉 See **https://typescript-eslint.io/packages/typescript-estree** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.d.ts new file mode 100644 index 00000000..684f35a8 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.d.ts @@ -0,0 +1,9 @@ +import type { SourceFile } from 'typescript'; +import type { ASTMaps } from './convert'; +import type { ParseSettings } from './parseSettings'; +import type { TSESTree } from './ts-estree'; +export declare function astConverter(ast: SourceFile, parseSettings: ParseSettings, shouldPreserveNodeMaps: boolean): { + astMaps: ASTMaps; + estree: TSESTree.Program; +}; +//# sourceMappingURL=ast-converter.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.d.ts.map new file mode 100644 index 00000000..8da91fde --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ast-converter.d.ts","sourceRoot":"","sources":["../src/ast-converter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAO5C,wBAAgB,YAAY,CAC1B,GAAG,EAAE,UAAU,EACf,aAAa,EAAE,aAAa,EAC5B,sBAAsB,EAAE,OAAO,GAC9B;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAA;CAAE,CA4DhD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.js b/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.js new file mode 100644 index 00000000..4e65f88b --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.astConverter = astConverter; +const convert_1 = require("./convert"); +const convert_comments_1 = require("./convert-comments"); +const node_utils_1 = require("./node-utils"); +const simple_traverse_1 = require("./simple-traverse"); +function astConverter(ast, parseSettings, shouldPreserveNodeMaps) { + /** + * The TypeScript compiler produced fundamental parse errors when parsing the + * source. + */ + const { parseDiagnostics } = ast; + if (parseDiagnostics.length) { + throw (0, convert_1.convertError)(parseDiagnostics[0]); + } + /** + * Recursively convert the TypeScript AST into an ESTree-compatible AST + */ + const instance = new convert_1.Converter(ast, { + allowInvalidAST: parseSettings.allowInvalidAST, + errorOnUnknownASTType: parseSettings.errorOnUnknownASTType, + shouldPreserveNodeMaps, + suppressDeprecatedPropertyWarnings: parseSettings.suppressDeprecatedPropertyWarnings, + }); + const estree = instance.convertProgram(); + /** + * Optionally remove range and loc if specified + */ + if (!parseSettings.range || !parseSettings.loc) { + (0, simple_traverse_1.simpleTraverse)(estree, { + enter: node => { + if (!parseSettings.range) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment -- TS 4.0 made this an error because the types aren't optional + // @ts-expect-error + delete node.range; + } + if (!parseSettings.loc) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment -- TS 4.0 made this an error because the types aren't optional + // @ts-expect-error + delete node.loc; + } + }, + }); + } + /** + * Optionally convert and include all tokens in the AST + */ + if (parseSettings.tokens) { + estree.tokens = (0, node_utils_1.convertTokens)(ast); + } + /** + * Optionally convert and include all comments in the AST + */ + if (parseSettings.comment) { + estree.comments = (0, convert_comments_1.convertComments)(ast, parseSettings.codeFullText); + } + const astMaps = instance.getASTMaps(); + return { astMaps, estree }; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/clear-caches.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/clear-caches.d.ts new file mode 100644 index 00000000..18457024 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/clear-caches.d.ts @@ -0,0 +1,10 @@ +/** + * Clears all of the internal caches. + * Generally you shouldn't need or want to use this. + * Examples of intended uses: + * - In tests to reset parser state to keep tests isolated. + * - In custom lint tooling that iteratively lints one project at a time to prevent OOMs. + */ +export declare function clearCaches(): void; +export declare const clearProgramCache: typeof clearCaches; +//# sourceMappingURL=clear-caches.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/clear-caches.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/clear-caches.d.ts.map new file mode 100644 index 00000000..eeec191b --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/clear-caches.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clear-caches.d.ts","sourceRoot":"","sources":["../src/clear-caches.ts"],"names":[],"mappings":"AAWA;;;;;;GAMG;AACH,wBAAgB,WAAW,IAAI,IAAI,CAOlC;AAGD,eAAO,MAAM,iBAAiB,oBAAc,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/clear-caches.js b/node_modules/@typescript-eslint/typescript-estree/dist/clear-caches.js new file mode 100644 index 00000000..f86643ba --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/clear-caches.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.clearProgramCache = void 0; +exports.clearCaches = clearCaches; +const getWatchProgramsForProjects_1 = require("./create-program/getWatchProgramsForProjects"); +const parser_1 = require("./parser"); +const createParseSettings_1 = require("./parseSettings/createParseSettings"); +const resolveProjectList_1 = require("./parseSettings/resolveProjectList"); +/** + * Clears all of the internal caches. + * Generally you shouldn't need or want to use this. + * Examples of intended uses: + * - In tests to reset parser state to keep tests isolated. + * - In custom lint tooling that iteratively lints one project at a time to prevent OOMs. + */ +function clearCaches() { + (0, parser_1.clearDefaultProjectMatchedFiles)(); + (0, parser_1.clearProgramCache)(); + (0, getWatchProgramsForProjects_1.clearWatchCaches)(); + (0, createParseSettings_1.clearTSConfigMatchCache)(); + (0, createParseSettings_1.clearTSServerProjectService)(); + (0, resolveProjectList_1.clearGlobCache)(); +} +// TODO - delete this in next major +exports.clearProgramCache = clearCaches; diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/convert-comments.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/convert-comments.d.ts new file mode 100644 index 00000000..bdf93691 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/convert-comments.d.ts @@ -0,0 +1,11 @@ +import * as ts from 'typescript'; +import type { TSESTree } from './ts-estree'; +/** + * Convert all comments for the given AST. + * @param ast the AST object + * @param code the TypeScript code + * @returns the converted ESTreeComment + * @private + */ +export declare function convertComments(ast: ts.SourceFile, code: string): TSESTree.Comment[]; +//# sourceMappingURL=convert-comments.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/convert-comments.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/convert-comments.d.ts.map new file mode 100644 index 00000000..4ac22871 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/convert-comments.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"convert-comments.d.ts","sourceRoot":"","sources":["../src/convert-comments.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAK5C;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,GAAG,EAAE,EAAE,CAAC,UAAU,EAClB,IAAI,EAAE,MAAM,GACX,QAAQ,CAAC,OAAO,EAAE,CAgCpB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/convert-comments.js b/node_modules/@typescript-eslint/typescript-estree/dist/convert-comments.js new file mode 100644 index 00000000..b277f010 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/convert-comments.js @@ -0,0 +1,71 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertComments = convertComments; +const tsutils = __importStar(require("ts-api-utils")); +const ts = __importStar(require("typescript")); +const node_utils_1 = require("./node-utils"); +const ts_estree_1 = require("./ts-estree"); +/** + * Convert all comments for the given AST. + * @param ast the AST object + * @param code the TypeScript code + * @returns the converted ESTreeComment + * @private + */ +function convertComments(ast, code) { + const comments = []; + tsutils.forEachComment(ast, (_, comment) => { + const type = comment.kind === ts.SyntaxKind.SingleLineCommentTrivia + ? ts_estree_1.AST_TOKEN_TYPES.Line + : ts_estree_1.AST_TOKEN_TYPES.Block; + const range = [comment.pos, comment.end]; + const loc = (0, node_utils_1.getLocFor)(range, ast); + // both comments start with 2 characters - /* or // + const textStart = range[0] + 2; + const textEnd = comment.kind === ts.SyntaxKind.SingleLineCommentTrivia + ? // single line comments end at the end + range[1] - textStart + : // multiline comments end 2 characters early + range[1] - textStart - 2; + comments.push({ + type, + loc, + range, + value: code.slice(textStart, textStart + textEnd), + }); + }, ast); + return comments; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/convert.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/convert.d.ts new file mode 100644 index 00000000..eec3ee4c --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/convert.d.ts @@ -0,0 +1,137 @@ +import * as ts from 'typescript'; +import type { TSError } from './node-utils'; +import type { ParserWeakMap, ParserWeakMapESTreeToTSNode } from './parser-options'; +import type { SemanticOrSyntacticError } from './semantic-or-syntactic-errors'; +import type { TSESTree, TSNode } from './ts-estree'; +export interface ConverterOptions { + allowInvalidAST?: boolean; + errorOnUnknownASTType?: boolean; + shouldPreserveNodeMaps?: boolean; + suppressDeprecatedPropertyWarnings?: boolean; +} +/** + * Extends and formats a given error object + * @param error the error object + * @returns converted error object + */ +export declare function convertError(error: SemanticOrSyntacticError | ts.DiagnosticWithLocation): TSError; +export interface ASTMaps { + esTreeNodeToTSNodeMap: ParserWeakMapESTreeToTSNode; + tsNodeToESTreeNodeMap: ParserWeakMap; +} +export declare class Converter { + #private; + private allowPattern; + private readonly ast; + private readonly esTreeNodeToTSNodeMap; + private readonly options; + private readonly tsNodeToESTreeNodeMap; + /** + * Converts a TypeScript node into an ESTree node + * @param ast the full TypeScript AST + * @param options additional options for the conversion + * @returns the converted ESTreeNode + */ + constructor(ast: ts.SourceFile, options?: ConverterOptions); + private assertModuleSpecifier; + private convertBindingNameWithTypeAnnotation; + /** + * Coverts body Nodes and add a directive field to StringLiterals + * @param nodes of ts.Node + * @param parent parentNode + * @returns Array of body statements + */ + private convertBodyExpressions; + private convertChainExpression; + /** + * Converts a TypeScript node into an ESTree node. + * @param child the child ts.Node + * @param parent parentNode + * @returns the converted ESTree node + */ + private convertChild; + /** + * Converts a TypeScript node into an ESTree node. + * @param child the child ts.Node + * @param parent parentNode + * @returns the converted ESTree node + */ + private convertPattern; + /** + * Converts a child into a type annotation. This creates an intermediary + * TypeAnnotation node to match what Flow does. + * @param child The TypeScript AST node to convert. + * @param parent parentNode + * @returns The type annotation node. + */ + private convertTypeAnnotation; + /** + * Converts a ts.Node's typeArguments to TSTypeParameterInstantiation node + * @param typeArguments ts.NodeArray typeArguments + * @param node parent used to create this node + * @returns TypeParameterInstantiation node + */ + private convertTypeArgumentsToTypeParameterInstantiation; + /** + * Converts a ts.Node's typeParameters to TSTypeParameterDeclaration node + * @param typeParameters ts.Node typeParameters + * @returns TypeParameterDeclaration node + */ + private convertTSTypeParametersToTypeParametersDeclaration; + /** + * Converts an array of ts.Node parameters into an array of ESTreeNode params + * @param parameters An array of ts.Node params to be converted + * @returns an array of converted ESTreeNode params + */ + private convertParameters; + /** + * Converts a TypeScript node into an ESTree node. + * @param node the child ts.Node + * @param parent parentNode + * @param allowPattern flag to determine if patterns are allowed + * @returns the converted ESTree node + */ + private converter; + private convertImportAttributes; + private convertJSXIdentifier; + private convertJSXNamespaceOrIdentifier; + /** + * Converts a TypeScript JSX node.tagName into an ESTree node.name + * @param node the tagName object from a JSX ts.Node + * @returns the converted ESTree name object + */ + private convertJSXTagName; + private convertMethodSignature; + /** + * Uses the provided range location to adjust the location data of the given Node + * @param result The node that will have its location data mutated + * @param childRange The child node range used to expand location + */ + private fixParentLocation; + /** + * Converts a TypeScript node into an ESTree node. + * The core of the conversion logic: + * Identify and convert each relevant TypeScript SyntaxKind + * @returns the converted ESTree node + */ + private convertNode; + private createNode; + convertProgram(): TSESTree.Program; + /** + * For nodes that are copied directly from the TypeScript AST into + * ESTree mostly as-is. The only difference is the addition of a type + * property instead of a kind property. Recursively copies all children. + */ + private deeplyCopy; + /** + * Fixes the exports of the given ts.Node + * @returns the ESTreeNode with fixed exports + */ + private fixExports; + getASTMaps(): ASTMaps; + /** + * Register specific TypeScript node into map with first ESTree node provided + */ + private registerTSNodeInNodeMap; +} +//# sourceMappingURL=convert.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/convert.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/convert.d.ts.map new file mode 100644 index 00000000..2c981720 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/convert.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"convert.d.ts","sourceRoot":"","sources":["../src/convert.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,KAAK,EACV,aAAa,EACb,2BAA2B,EAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,KAAK,EAAE,QAAQ,EAAoB,MAAM,EAAE,MAAM,aAAa,CAAC;AAmCtE,MAAM,WAAW,gBAAgB;IAC/B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,sBAAsB,CAAC,EAAE,OAAO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H,OAAO,CAAC,iBAAiB;IAczB;;;;;OAKG;IACH,OAAO,CAAC,WAAW;IA+iFnB,OAAO,CAAC,UAAU;IAclB,cAAc,IAAI,QAAQ,CAAC,OAAO;IAIlC;;;;OAIG;IACH,OAAO,CAAC,UAAU;IA0FlB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAgFlB,UAAU,IAAI,OAAO;IAOrB;;OAEG;IACH,OAAO,CAAC,uBAAuB;CAYhC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/convert.js b/node_modules/@typescript-eslint/typescript-estree/dist/convert.js new file mode 100644 index 00000000..119781bf --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/convert.js @@ -0,0 +1,2746 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Converter = void 0; +exports.convertError = convertError; +// There's lots of funny stuff due to the typing of ts.Node +/* eslint-disable @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access */ +const ts = __importStar(require("typescript")); +const getModifiers_1 = require("./getModifiers"); +const node_utils_1 = require("./node-utils"); +const ts_estree_1 = require("./ts-estree"); +const SyntaxKind = ts.SyntaxKind; +/** + * Extends and formats a given error object + * @param error the error object + * @returns converted error object + */ +function convertError(error) { + return (0, node_utils_1.createError)(('message' in error && error.message) || error.messageText, error.file, error.start); +} +function isPropertyAccessEntityNameExpression(node) { + return (ts.isPropertyAccessExpression(node) && + ts.isIdentifier(node.name) && + isEntityNameExpression(node.expression)); +} +function isEntityNameExpression(node) { + return (node.kind === SyntaxKind.Identifier || + isPropertyAccessEntityNameExpression(node)); +} +class Converter { + allowPattern = false; + ast; + esTreeNodeToTSNodeMap = new WeakMap(); + options; + tsNodeToESTreeNodeMap = new WeakMap(); + /** + * Converts a TypeScript node into an ESTree node + * @param ast the full TypeScript AST + * @param options additional options for the conversion + * @returns the converted ESTreeNode + */ + constructor(ast, options) { + this.ast = ast; + this.options = { ...options }; + } + #checkForStatementDeclaration(initializer, kind) { + const loop = kind === ts.SyntaxKind.ForInStatement ? 'for...in' : 'for...of'; + if (ts.isVariableDeclarationList(initializer)) { + if (initializer.declarations.length !== 1) { + this.#throwError(initializer, `Only a single variable declaration is allowed in a '${loop}' statement.`); + } + const declaration = initializer.declarations[0]; + if (declaration.initializer) { + this.#throwError(declaration, `The variable declaration of a '${loop}' statement cannot have an initializer.`); + } + else if (declaration.type) { + this.#throwError(declaration, `The variable declaration of a '${loop}' statement cannot have a type annotation.`); + } + if (kind === ts.SyntaxKind.ForInStatement && + initializer.flags & ts.NodeFlags.Using) { + this.#throwError(initializer, "The left-hand side of a 'for...in' statement cannot be a 'using' declaration."); + } + } + else if (!(0, node_utils_1.isValidAssignmentTarget)(initializer) && + initializer.kind !== ts.SyntaxKind.ObjectLiteralExpression && + initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) { + this.#throwError(initializer, `The left-hand side of a '${loop}' statement must be a variable or a property access.`); + } + } + #checkModifiers(node) { + if (this.options.allowInvalidAST) { + return; + } + // typescript<5.0.0 + if ((0, node_utils_1.nodeHasIllegalDecorators)(node)) { + this.#throwError(node.illegalDecorators[0], 'Decorators are not valid here.'); + } + for (const decorator of (0, getModifiers_1.getDecorators)(node, + /* includeIllegalDecorators */ true) ?? []) { + // `checkGrammarModifiers` function in typescript + if (!(0, node_utils_1.nodeCanBeDecorated)(node)) { + if (ts.isMethodDeclaration(node) && !(0, node_utils_1.nodeIsPresent)(node.body)) { + this.#throwError(decorator, 'A decorator can only decorate a method implementation, not an overload.'); + } + else { + this.#throwError(decorator, 'Decorators are not valid here.'); + } + } + } + for (const modifier of (0, getModifiers_1.getModifiers)(node, + /* includeIllegalModifiers */ true) ?? []) { + if (modifier.kind !== SyntaxKind.ReadonlyKeyword) { + if (node.kind === SyntaxKind.PropertySignature || + node.kind === SyntaxKind.MethodSignature) { + this.#throwError(modifier, `'${ts.tokenToString(modifier.kind)}' modifier cannot appear on a type member`); + } + if (node.kind === SyntaxKind.IndexSignature && + (modifier.kind !== SyntaxKind.StaticKeyword || + !ts.isClassLike(node.parent))) { + this.#throwError(modifier, `'${ts.tokenToString(modifier.kind)}' modifier cannot appear on an index signature`); + } + } + if (modifier.kind !== SyntaxKind.InKeyword && + modifier.kind !== SyntaxKind.OutKeyword && + modifier.kind !== SyntaxKind.ConstKeyword && + node.kind === SyntaxKind.TypeParameter) { + this.#throwError(modifier, `'${ts.tokenToString(modifier.kind)}' modifier cannot appear on a type parameter`); + } + if ((modifier.kind === SyntaxKind.InKeyword || + modifier.kind === SyntaxKind.OutKeyword) && + (node.kind !== SyntaxKind.TypeParameter || + !(ts.isInterfaceDeclaration(node.parent) || + ts.isClassLike(node.parent) || + ts.isTypeAliasDeclaration(node.parent)))) { + this.#throwError(modifier, `'${ts.tokenToString(modifier.kind)}' modifier can only appear on a type parameter of a class, interface or type alias`); + } + if (modifier.kind === SyntaxKind.ReadonlyKeyword && + node.kind !== SyntaxKind.PropertyDeclaration && + node.kind !== SyntaxKind.PropertySignature && + node.kind !== SyntaxKind.IndexSignature && + node.kind !== SyntaxKind.Parameter) { + this.#throwError(modifier, "'readonly' modifier can only appear on a property declaration or index signature."); + } + if (modifier.kind === SyntaxKind.DeclareKeyword && + ts.isClassLike(node.parent) && + !ts.isPropertyDeclaration(node)) { + this.#throwError(modifier, `'${ts.tokenToString(modifier.kind)}' modifier cannot appear on class elements of this kind.`); + } + if (modifier.kind === SyntaxKind.DeclareKeyword && + ts.isVariableStatement(node)) { + const declarationKind = (0, node_utils_1.getDeclarationKind)(node.declarationList); + if (declarationKind === 'using' || declarationKind === 'await using') { + this.#throwError(modifier, `'declare' modifier cannot appear on a '${declarationKind}' declaration.`); + } + } + if (modifier.kind === SyntaxKind.AbstractKeyword && + node.kind !== SyntaxKind.ClassDeclaration && + node.kind !== SyntaxKind.ConstructorType && + node.kind !== SyntaxKind.MethodDeclaration && + node.kind !== SyntaxKind.PropertyDeclaration && + node.kind !== SyntaxKind.GetAccessor && + node.kind !== SyntaxKind.SetAccessor) { + this.#throwError(modifier, `'${ts.tokenToString(modifier.kind)}' modifier can only appear on a class, method, or property declaration.`); + } + if ((modifier.kind === SyntaxKind.StaticKeyword || + modifier.kind === SyntaxKind.PublicKeyword || + modifier.kind === SyntaxKind.ProtectedKeyword || + modifier.kind === SyntaxKind.PrivateKeyword) && + (node.parent.kind === SyntaxKind.ModuleBlock || + node.parent.kind === SyntaxKind.SourceFile)) { + this.#throwError(modifier, `'${ts.tokenToString(modifier.kind)}' modifier cannot appear on a module or namespace element.`); + } + if (modifier.kind === SyntaxKind.AccessorKeyword && + node.kind !== SyntaxKind.PropertyDeclaration) { + this.#throwError(modifier, "'accessor' modifier can only appear on a property declaration."); + } + // `checkGrammarAsyncModifier` function in `typescript` + if (modifier.kind === SyntaxKind.AsyncKeyword && + node.kind !== SyntaxKind.MethodDeclaration && + node.kind !== SyntaxKind.FunctionDeclaration && + node.kind !== SyntaxKind.FunctionExpression && + node.kind !== SyntaxKind.ArrowFunction) { + this.#throwError(modifier, "'async' modifier cannot be used here."); + } + // `checkGrammarModifiers` function in `typescript` + if (node.kind === SyntaxKind.Parameter && + (modifier.kind === SyntaxKind.StaticKeyword || + modifier.kind === SyntaxKind.ExportKeyword || + modifier.kind === SyntaxKind.DeclareKeyword || + modifier.kind === SyntaxKind.AsyncKeyword)) { + this.#throwError(modifier, `'${ts.tokenToString(modifier.kind)}' modifier cannot appear on a parameter.`); + } + // `checkGrammarModifiers` function in `typescript` + if (modifier.kind === SyntaxKind.PublicKeyword || + modifier.kind === SyntaxKind.ProtectedKeyword || + modifier.kind === SyntaxKind.PrivateKeyword) { + for (const anotherModifier of (0, getModifiers_1.getModifiers)(node) ?? []) { + if (anotherModifier !== modifier && + (anotherModifier.kind === SyntaxKind.PublicKeyword || + anotherModifier.kind === SyntaxKind.ProtectedKeyword || + anotherModifier.kind === SyntaxKind.PrivateKeyword)) { + this.#throwError(anotherModifier, `Accessibility modifier already seen.`); + } + } + } + // `checkParameter` function in `typescript` + if (node.kind === SyntaxKind.Parameter && + // In `typescript` package, it's `ts.hasSyntacticModifier(node, ts.ModifierFlags.ParameterPropertyModifier)` + // https://github.com/typescript-eslint/typescript-eslint/pull/6615#discussion_r1136489935 + (modifier.kind === SyntaxKind.PublicKeyword || + modifier.kind === SyntaxKind.PrivateKeyword || + modifier.kind === SyntaxKind.ProtectedKeyword || + modifier.kind === SyntaxKind.ReadonlyKeyword || + modifier.kind === SyntaxKind.OverrideKeyword)) { + const func = (0, node_utils_1.getContainingFunction)(node); + if (!(func.kind === SyntaxKind.Constructor && (0, node_utils_1.nodeIsPresent)(func.body))) { + this.#throwError(modifier, 'A parameter property is only allowed in a constructor implementation.'); + } + } + } + } + #throwError(node, message) { + let start; + let end; + if (typeof node === 'number') { + start = end = node; + } + else { + start = node.getStart(this.ast); + end = node.getEnd(); + } + throw (0, node_utils_1.createError)(message, this.ast, start, end); + } + #throwUnlessAllowInvalidAST(node, message) { + if (!this.options.allowInvalidAST) { + this.#throwError(node, message); + } + } + /** + * Creates a getter for a property under aliasKey that returns the value under + * valueKey. If suppressDeprecatedPropertyWarnings is not enabled, the + * getter also console warns about the deprecation. + * + * @see https://github.com/typescript-eslint/typescript-eslint/issues/6469 + */ + #withDeprecatedAliasGetter(node, aliasKey, valueKey, suppressWarnings = false) { + let warned = suppressWarnings; + Object.defineProperty(node, aliasKey, { + configurable: true, + get: this.options.suppressDeprecatedPropertyWarnings + ? () => node[valueKey] + : () => { + if (!warned) { + process.emitWarning(`The '${aliasKey}' property is deprecated on ${node.type} nodes. Use '${valueKey}' instead. See https://typescript-eslint.io/troubleshooting/faqs/general#the-key-property-is-deprecated-on-type-nodes-use-key-instead-warnings.`, 'DeprecationWarning'); + warned = true; + } + return node[valueKey]; + }, + set(value) { + Object.defineProperty(node, aliasKey, { + enumerable: true, + value, + writable: true, + }); + }, + }); + return node; + } + #withDeprecatedGetter(node, deprecatedKey, preferredKey, value) { + let warned = false; + Object.defineProperty(node, deprecatedKey, { + configurable: true, + get: this.options.suppressDeprecatedPropertyWarnings + ? () => value + : () => { + if (!warned) { + process.emitWarning(`The '${deprecatedKey}' property is deprecated on ${node.type} nodes. Use ${preferredKey} instead. See https://typescript-eslint.io/troubleshooting/faqs/general#the-key-property-is-deprecated-on-type-nodes-use-key-instead-warnings.`, 'DeprecationWarning'); + warned = true; + } + return value; + }, + set(value) { + Object.defineProperty(node, deprecatedKey, { + enumerable: true, + value, + writable: true, + }); + }, + }); + return node; + } + assertModuleSpecifier(node, allowNull) { + if (!allowNull && node.moduleSpecifier == null) { + this.#throwUnlessAllowInvalidAST(node, 'Module specifier must be a string literal.'); + } + if (node.moduleSpecifier && + node.moduleSpecifier?.kind !== SyntaxKind.StringLiteral) { + this.#throwUnlessAllowInvalidAST(node.moduleSpecifier, 'Module specifier must be a string literal.'); + } + } + convertBindingNameWithTypeAnnotation(name, tsType, parent) { + const id = this.convertPattern(name); + if (tsType) { + id.typeAnnotation = this.convertTypeAnnotation(tsType, parent); + this.fixParentLocation(id, id.typeAnnotation.range); + } + return id; + } + /** + * Coverts body Nodes and add a directive field to StringLiterals + * @param nodes of ts.Node + * @param parent parentNode + * @returns Array of body statements + */ + convertBodyExpressions(nodes, parent) { + let allowDirectives = (0, node_utils_1.canContainDirective)(parent); + return (nodes + .map(statement => { + const child = this.convertChild(statement); + if (allowDirectives) { + if (child?.expression && + ts.isExpressionStatement(statement) && + ts.isStringLiteral(statement.expression)) { + const raw = child.expression.raw; + child.directive = raw.slice(1, -1); + return child; // child can be null, but it's filtered below + } + allowDirectives = false; + } + return child; // child can be null, but it's filtered below + }) + // filter out unknown nodes for now + .filter(statement => statement)); + } + convertChainExpression(node, tsNode) { + const { child, isOptional } = (() => { + if (node.type === ts_estree_1.AST_NODE_TYPES.MemberExpression) { + return { child: node.object, isOptional: node.optional }; + } + if (node.type === ts_estree_1.AST_NODE_TYPES.CallExpression) { + return { child: node.callee, isOptional: node.optional }; + } + return { child: node.expression, isOptional: false }; + })(); + const isChildUnwrappable = (0, node_utils_1.isChildUnwrappableOptionalChain)(tsNode, child); + if (!isChildUnwrappable && !isOptional) { + return node; + } + if (isChildUnwrappable && (0, node_utils_1.isChainExpression)(child)) { + // unwrap the chain expression child + const newChild = child.expression; + if (node.type === ts_estree_1.AST_NODE_TYPES.MemberExpression) { + node.object = newChild; + } + else if (node.type === ts_estree_1.AST_NODE_TYPES.CallExpression) { + node.callee = newChild; + } + else { + node.expression = newChild; + } + } + return this.createNode(tsNode, { + type: ts_estree_1.AST_NODE_TYPES.ChainExpression, + expression: node, + }); + } + /** + * Converts a TypeScript node into an ESTree node. + * @param child the child ts.Node + * @param parent parentNode + * @returns the converted ESTree node + */ + convertChild(child, parent) { + return this.converter(child, parent, false); + } + /** + * Converts a TypeScript node into an ESTree node. + * @param child the child ts.Node + * @param parent parentNode + * @returns the converted ESTree node + */ + convertPattern(child, parent) { + return this.converter(child, parent, true); + } + /** + * Converts a child into a type annotation. This creates an intermediary + * TypeAnnotation node to match what Flow does. + * @param child The TypeScript AST node to convert. + * @param parent parentNode + * @returns The type annotation node. + */ + convertTypeAnnotation(child, parent) { + // in FunctionType and ConstructorType typeAnnotation has 2 characters `=>` and in other places is just colon + const offset = parent?.kind === SyntaxKind.FunctionType || + parent?.kind === SyntaxKind.ConstructorType + ? 2 + : 1; + const annotationStartCol = child.getFullStart() - offset; + const range = [annotationStartCol, child.end]; + const loc = (0, node_utils_1.getLocFor)(range, this.ast); + return { + type: ts_estree_1.AST_NODE_TYPES.TSTypeAnnotation, + loc, + range, + typeAnnotation: this.convertChild(child), + }; + } + /** + * Converts a ts.Node's typeArguments to TSTypeParameterInstantiation node + * @param typeArguments ts.NodeArray typeArguments + * @param node parent used to create this node + * @returns TypeParameterInstantiation node + */ + convertTypeArgumentsToTypeParameterInstantiation(typeArguments, node) { + const greaterThanToken = (0, node_utils_1.findNextToken)(typeArguments, this.ast, this.ast); + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypeParameterInstantiation, + range: [typeArguments.pos - 1, greaterThanToken.end], + params: typeArguments.map(typeArgument => this.convertChild(typeArgument)), + }); + } + /** + * Converts a ts.Node's typeParameters to TSTypeParameterDeclaration node + * @param typeParameters ts.Node typeParameters + * @returns TypeParameterDeclaration node + */ + convertTSTypeParametersToTypeParametersDeclaration(typeParameters) { + const greaterThanToken = (0, node_utils_1.findNextToken)(typeParameters, this.ast, this.ast); + const range = [ + typeParameters.pos - 1, + greaterThanToken.end, + ]; + return { + type: ts_estree_1.AST_NODE_TYPES.TSTypeParameterDeclaration, + loc: (0, node_utils_1.getLocFor)(range, this.ast), + range, + params: typeParameters.map(typeParameter => this.convertChild(typeParameter)), + }; + } + /** + * Converts an array of ts.Node parameters into an array of ESTreeNode params + * @param parameters An array of ts.Node params to be converted + * @returns an array of converted ESTreeNode params + */ + convertParameters(parameters) { + if (!parameters?.length) { + return []; + } + return parameters.map(param => { + const convertedParam = this.convertChild(param); + convertedParam.decorators = + (0, getModifiers_1.getDecorators)(param)?.map(el => this.convertChild(el)) ?? []; + return convertedParam; + }); + } + /** + * Converts a TypeScript node into an ESTree node. + * @param node the child ts.Node + * @param parent parentNode + * @param allowPattern flag to determine if patterns are allowed + * @returns the converted ESTree node + */ + converter(node, parent, allowPattern) { + /** + * Exit early for null and undefined + */ + if (!node) { + return null; + } + this.#checkModifiers(node); + const pattern = this.allowPattern; + if (allowPattern != null) { + this.allowPattern = allowPattern; + } + const result = this.convertNode(node, (parent ?? node.parent)); + this.registerTSNodeInNodeMap(node, result); + this.allowPattern = pattern; + return result; + } + convertImportAttributes(node) { + return node == null + ? [] + : node.elements.map(element => this.convertChild(element)); + } + convertJSXIdentifier(node) { + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXIdentifier, + name: node.getText(), + }); + this.registerTSNodeInNodeMap(node, result); + return result; + } + convertJSXNamespaceOrIdentifier(node) { + // TypeScript@5.1 added in ts.JsxNamespacedName directly + // We prefer using that if it's relevant for this node type + if (node.kind === ts.SyntaxKind.JsxNamespacedName) { + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXNamespacedName, + name: this.createNode(node.name, { + type: ts_estree_1.AST_NODE_TYPES.JSXIdentifier, + name: node.name.text, + }), + namespace: this.createNode(node.namespace, { + type: ts_estree_1.AST_NODE_TYPES.JSXIdentifier, + name: node.namespace.text, + }), + }); + this.registerTSNodeInNodeMap(node, result); + return result; + } + // TypeScript@<5.1 has to manually parse the JSX attributes + const text = node.getText(); + const colonIndex = text.indexOf(':'); + // this is intentional we can ignore conversion if `:` is in first character + if (colonIndex > 0) { + const range = (0, node_utils_1.getRange)(node, this.ast); + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXNamespacedName, + range, + name: this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXIdentifier, + range: [range[0] + colonIndex + 1, range[1]], + name: text.slice(colonIndex + 1), + }), + namespace: this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXIdentifier, + range: [range[0], range[0] + colonIndex], + name: text.slice(0, colonIndex), + }), + }); + this.registerTSNodeInNodeMap(node, result); + return result; + } + return this.convertJSXIdentifier(node); + } + /** + * Converts a TypeScript JSX node.tagName into an ESTree node.name + * @param node the tagName object from a JSX ts.Node + * @returns the converted ESTree name object + */ + convertJSXTagName(node, parent) { + let result; + switch (node.kind) { + case SyntaxKind.PropertyAccessExpression: + if (node.name.kind === SyntaxKind.PrivateIdentifier) { + // This is one of the few times where TS explicitly errors, and doesn't even gracefully handle the syntax. + // So we shouldn't ever get into this state to begin with. + this.#throwError(node.name, 'Non-private identifier expected.'); + } + result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXMemberExpression, + object: this.convertJSXTagName(node.expression, parent), + property: this.convertJSXIdentifier(node.name), + }); + break; + case SyntaxKind.ThisKeyword: + case SyntaxKind.Identifier: + default: + return this.convertJSXNamespaceOrIdentifier(node); + } + this.registerTSNodeInNodeMap(node, result); + return result; + } + convertMethodSignature(node) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSMethodSignature, + accessibility: (0, node_utils_1.getTSNodeAccessibility)(node), + computed: (0, node_utils_1.isComputedProperty)(node.name), + key: this.convertChild(node.name), + kind: (() => { + switch (node.kind) { + case SyntaxKind.GetAccessor: + return 'get'; + case SyntaxKind.SetAccessor: + return 'set'; + case SyntaxKind.MethodSignature: + return 'method'; + } + })(), + optional: (0, node_utils_1.isOptional)(node), + params: this.convertParameters(node.parameters), + readonly: (0, node_utils_1.hasModifier)(SyntaxKind.ReadonlyKeyword, node), + returnType: node.type && this.convertTypeAnnotation(node.type, node), + static: (0, node_utils_1.hasModifier)(SyntaxKind.StaticKeyword, node), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + } + /** + * Uses the provided range location to adjust the location data of the given Node + * @param result The node that will have its location data mutated + * @param childRange The child node range used to expand location + */ + fixParentLocation(result, childRange) { + if (childRange[0] < result.range[0]) { + result.range[0] = childRange[0]; + result.loc.start = (0, node_utils_1.getLineAndCharacterFor)(result.range[0], this.ast); + } + if (childRange[1] > result.range[1]) { + result.range[1] = childRange[1]; + result.loc.end = (0, node_utils_1.getLineAndCharacterFor)(result.range[1], this.ast); + } + } + /** + * Converts a TypeScript node into an ESTree node. + * The core of the conversion logic: + * Identify and convert each relevant TypeScript SyntaxKind + * @returns the converted ESTree node + */ + convertNode(node, parent) { + switch (node.kind) { + case SyntaxKind.SourceFile: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Program, + range: [node.getStart(this.ast), node.endOfFileToken.end], + body: this.convertBodyExpressions(node.statements, node), + comments: undefined, + sourceType: node.externalModuleIndicator ? 'module' : 'script', + tokens: undefined, + }); + } + case SyntaxKind.Block: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.BlockStatement, + body: this.convertBodyExpressions(node.statements, node), + }); + } + case SyntaxKind.Identifier: { + if ((0, node_utils_1.isThisInTypeQuery)(node)) { + // special case for `typeof this.foo` - TS emits an Identifier for `this` + // but we want to treat it as a ThisExpression for consistency + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ThisExpression, + }); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Identifier, + decorators: [], + name: node.text, + optional: false, + typeAnnotation: undefined, + }); + } + case SyntaxKind.PrivateIdentifier: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.PrivateIdentifier, + // typescript includes the `#` in the text + name: node.text.slice(1), + }); + } + case SyntaxKind.WithStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.WithStatement, + body: this.convertChild(node.statement), + object: this.convertChild(node.expression), + }); + // Control Flow + case SyntaxKind.ReturnStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ReturnStatement, + argument: this.convertChild(node.expression), + }); + case SyntaxKind.LabeledStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.LabeledStatement, + body: this.convertChild(node.statement), + label: this.convertChild(node.label), + }); + case SyntaxKind.ContinueStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ContinueStatement, + label: this.convertChild(node.label), + }); + case SyntaxKind.BreakStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.BreakStatement, + label: this.convertChild(node.label), + }); + // Choice + case SyntaxKind.IfStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.IfStatement, + alternate: this.convertChild(node.elseStatement), + consequent: this.convertChild(node.thenStatement), + test: this.convertChild(node.expression), + }); + case SyntaxKind.SwitchStatement: + if (node.caseBlock.clauses.filter(switchCase => switchCase.kind === SyntaxKind.DefaultClause).length > 1) { + this.#throwError(node, "A 'default' clause cannot appear more than once in a 'switch' statement."); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.SwitchStatement, + cases: node.caseBlock.clauses.map(el => this.convertChild(el)), + discriminant: this.convertChild(node.expression), + }); + case SyntaxKind.CaseClause: + case SyntaxKind.DefaultClause: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.SwitchCase, + // expression is present in case only + consequent: node.statements.map(el => this.convertChild(el)), + test: node.kind === SyntaxKind.CaseClause + ? this.convertChild(node.expression) + : null, + }); + // Exceptions + case SyntaxKind.ThrowStatement: + if (node.expression.end === node.expression.pos) { + this.#throwUnlessAllowInvalidAST(node, 'A throw statement must throw an expression.'); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ThrowStatement, + argument: this.convertChild(node.expression), + }); + case SyntaxKind.TryStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TryStatement, + block: this.convertChild(node.tryBlock), + finalizer: this.convertChild(node.finallyBlock), + handler: this.convertChild(node.catchClause), + }); + case SyntaxKind.CatchClause: + if (node.variableDeclaration?.initializer) { + this.#throwError(node.variableDeclaration.initializer, 'Catch clause variable cannot have an initializer.'); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.CatchClause, + body: this.convertChild(node.block), + param: node.variableDeclaration + ? this.convertBindingNameWithTypeAnnotation(node.variableDeclaration.name, node.variableDeclaration.type) + : null, + }); + // Loops + case SyntaxKind.WhileStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.WhileStatement, + body: this.convertChild(node.statement), + test: this.convertChild(node.expression), + }); + /** + * Unlike other parsers, TypeScript calls a "DoWhileStatement" + * a "DoStatement" + */ + case SyntaxKind.DoStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.DoWhileStatement, + body: this.convertChild(node.statement), + test: this.convertChild(node.expression), + }); + case SyntaxKind.ForStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ForStatement, + body: this.convertChild(node.statement), + init: this.convertChild(node.initializer), + test: this.convertChild(node.condition), + update: this.convertChild(node.incrementor), + }); + case SyntaxKind.ForInStatement: + this.#checkForStatementDeclaration(node.initializer, node.kind); + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ForInStatement, + body: this.convertChild(node.statement), + left: this.convertPattern(node.initializer), + right: this.convertChild(node.expression), + }); + case SyntaxKind.ForOfStatement: { + this.#checkForStatementDeclaration(node.initializer, node.kind); + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ForOfStatement, + await: Boolean(node.awaitModifier && + node.awaitModifier.kind === SyntaxKind.AwaitKeyword), + body: this.convertChild(node.statement), + left: this.convertPattern(node.initializer), + right: this.convertChild(node.expression), + }); + } + // Declarations + case SyntaxKind.FunctionDeclaration: { + const isDeclare = (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node); + const isAsync = (0, node_utils_1.hasModifier)(SyntaxKind.AsyncKeyword, node); + const isGenerator = !!node.asteriskToken; + if (isDeclare) { + if (node.body) { + this.#throwError(node, 'An implementation cannot be declared in ambient contexts.'); + } + else if (isAsync) { + this.#throwError(node, "'async' modifier cannot be used in an ambient context."); + } + else if (isGenerator) { + this.#throwError(node, 'Generators are not allowed in an ambient context.'); + } + } + else if (!node.body && isGenerator) { + this.#throwError(node, 'A function signature cannot be declared as a generator.'); + } + const result = this.createNode(node, { + // declare implies no body due to the invariant above + type: !node.body + ? ts_estree_1.AST_NODE_TYPES.TSDeclareFunction + : ts_estree_1.AST_NODE_TYPES.FunctionDeclaration, + async: isAsync, + body: this.convertChild(node.body) || undefined, + declare: isDeclare, + expression: false, + generator: isGenerator, + id: this.convertChild(node.name), + params: this.convertParameters(node.parameters), + returnType: node.type && this.convertTypeAnnotation(node.type, node), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + return this.fixExports(node, result); + } + case SyntaxKind.VariableDeclaration: { + const definite = !!node.exclamationToken; + const init = this.convertChild(node.initializer); + const id = this.convertBindingNameWithTypeAnnotation(node.name, node.type, node); + if (definite) { + if (init) { + this.#throwError(node, 'Declarations with initializers cannot also have definite assignment assertions.'); + } + else if (id.type !== ts_estree_1.AST_NODE_TYPES.Identifier || + !id.typeAnnotation) { + this.#throwError(node, 'Declarations with definite assignment assertions must also have type annotations.'); + } + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.VariableDeclarator, + definite, + id, + init, + }); + } + case SyntaxKind.VariableStatement: { + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.VariableDeclaration, + declarations: node.declarationList.declarations.map(el => this.convertChild(el)), + declare: (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node), + kind: (0, node_utils_1.getDeclarationKind)(node.declarationList), + }); + if (!result.declarations.length) { + this.#throwUnlessAllowInvalidAST(node, 'A variable declaration list must have at least one variable declarator.'); + } + if (result.kind === 'using' || result.kind === 'await using') { + node.declarationList.declarations.forEach((declaration, i) => { + if (result.declarations[i].init == null) { + this.#throwError(declaration, `'${result.kind}' declarations must be initialized.`); + } + if (result.declarations[i].id.type !== ts_estree_1.AST_NODE_TYPES.Identifier) { + this.#throwError(declaration.name, `'${result.kind}' declarations may not have binding patterns.`); + } + }); + } + // Definite assignment only allowed for non-declare let and var + if (result.declare || + ['await using', 'const', 'using'].includes(result.kind)) { + node.declarationList.declarations.forEach((declaration, i) => { + if (result.declarations[i].definite) { + this.#throwError(declaration, `A definite assignment assertion '!' is not permitted in this context.`); + } + }); + } + if (result.declare) { + node.declarationList.declarations.forEach((declaration, i) => { + if (result.declarations[i].init && + (['let', 'var'].includes(result.kind) || + result.declarations[i].id.typeAnnotation)) { + this.#throwError(declaration, `Initializers are not permitted in ambient contexts.`); + } + }); + // Theoretically, only certain initializers are allowed for declare const, + // (TS1254: A 'const' initializer in an ambient context must be a string + // or numeric literal or literal enum reference.) but we just allow + // all expressions + } + // Note! No-declare does not mean the variable is not ambient, because + // it can be further nested in other declare contexts. Therefore we cannot + // check for const initializers. + /** + * Semantically, decorators are not allowed on variable declarations, + * Pre 4.8 TS would include them in the AST, so we did as well. + * However as of 4.8 TS no longer includes it (as it is, well, invalid). + * + * So for consistency across versions, we no longer include it either. + */ + return this.fixExports(node, result); + } + // mostly for for-of, for-in + case SyntaxKind.VariableDeclarationList: { + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.VariableDeclaration, + declarations: node.declarations.map(el => this.convertChild(el)), + declare: false, + kind: (0, node_utils_1.getDeclarationKind)(node), + }); + if (result.kind === 'using' || result.kind === 'await using') { + node.declarations.forEach((declaration, i) => { + if (result.declarations[i].init != null) { + this.#throwError(declaration, `'${result.kind}' declarations may not be initialized in for statement.`); + } + if (result.declarations[i].id.type !== ts_estree_1.AST_NODE_TYPES.Identifier) { + this.#throwError(declaration.name, `'${result.kind}' declarations may not have binding patterns.`); + } + }); + } + return result; + } + // Expressions + case SyntaxKind.ExpressionStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ExpressionStatement, + directive: undefined, + expression: this.convertChild(node.expression), + }); + case SyntaxKind.ThisKeyword: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ThisExpression, + }); + case SyntaxKind.ArrayLiteralExpression: { + // TypeScript uses ArrayLiteralExpression in destructuring assignment, too + if (this.allowPattern) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ArrayPattern, + decorators: [], + elements: node.elements.map(el => this.convertPattern(el)), + optional: false, + typeAnnotation: undefined, + }); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ArrayExpression, + elements: node.elements.map(el => this.convertChild(el)), + }); + } + case SyntaxKind.ObjectLiteralExpression: { + // TypeScript uses ObjectLiteralExpression in destructuring assignment, too + if (this.allowPattern) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ObjectPattern, + decorators: [], + optional: false, + properties: node.properties.map(el => this.convertPattern(el)), + typeAnnotation: undefined, + }); + } + const properties = []; + for (const property of node.properties) { + if ((property.kind === SyntaxKind.GetAccessor || + property.kind === SyntaxKind.SetAccessor || + property.kind === SyntaxKind.MethodDeclaration) && + !property.body) { + this.#throwUnlessAllowInvalidAST(property.end - 1, "'{' expected."); + } + properties.push(this.convertChild(property)); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ObjectExpression, + properties, + }); + } + case SyntaxKind.PropertyAssignment: { + // eslint-disable-next-line @typescript-eslint/no-deprecated + const { exclamationToken, questionToken } = node; + if (questionToken) { + this.#throwError(questionToken, 'A property assignment cannot have a question token.'); + } + if (exclamationToken) { + this.#throwError(exclamationToken, 'A property assignment cannot have an exclamation token.'); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Property, + computed: (0, node_utils_1.isComputedProperty)(node.name), + key: this.convertChild(node.name), + kind: 'init', + method: false, + optional: false, + shorthand: false, + value: this.converter(node.initializer, node, this.allowPattern), + }); + } + case SyntaxKind.ShorthandPropertyAssignment: { + // eslint-disable-next-line @typescript-eslint/no-deprecated + const { exclamationToken, modifiers, questionToken } = node; + if (modifiers) { + this.#throwError(modifiers[0], 'A shorthand property assignment cannot have modifiers.'); + } + if (questionToken) { + this.#throwError(questionToken, 'A shorthand property assignment cannot have a question token.'); + } + if (exclamationToken) { + this.#throwError(exclamationToken, 'A shorthand property assignment cannot have an exclamation token.'); + } + if (node.objectAssignmentInitializer) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Property, + computed: false, + key: this.convertChild(node.name), + kind: 'init', + method: false, + optional: false, + shorthand: true, + value: this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.AssignmentPattern, + decorators: [], + left: this.convertPattern(node.name), + optional: false, + right: this.convertChild(node.objectAssignmentInitializer), + typeAnnotation: undefined, + }), + }); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Property, + computed: false, + key: this.convertChild(node.name), + kind: 'init', + method: false, + optional: false, + shorthand: true, + value: this.convertChild(node.name), + }); + } + case SyntaxKind.ComputedPropertyName: + return this.convertChild(node.expression); + case SyntaxKind.PropertyDeclaration: { + const isAbstract = (0, node_utils_1.hasModifier)(SyntaxKind.AbstractKeyword, node); + if (isAbstract && node.initializer) { + this.#throwError(node.initializer, `Abstract property cannot have an initializer.`); + } + const isAccessor = (0, node_utils_1.hasModifier)(SyntaxKind.AccessorKeyword, node); + const type = (() => { + if (isAccessor) { + if (isAbstract) { + return ts_estree_1.AST_NODE_TYPES.TSAbstractAccessorProperty; + } + return ts_estree_1.AST_NODE_TYPES.AccessorProperty; + } + if (isAbstract) { + return ts_estree_1.AST_NODE_TYPES.TSAbstractPropertyDefinition; + } + return ts_estree_1.AST_NODE_TYPES.PropertyDefinition; + })(); + const key = this.convertChild(node.name); + return this.createNode(node, { + type, + accessibility: (0, node_utils_1.getTSNodeAccessibility)(node), + computed: (0, node_utils_1.isComputedProperty)(node.name), + declare: (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node), + decorators: (0, getModifiers_1.getDecorators)(node)?.map(el => this.convertChild(el)) ?? [], + definite: !!node.exclamationToken, + key, + optional: (key.type === ts_estree_1.AST_NODE_TYPES.Literal || + node.name.kind === SyntaxKind.Identifier || + node.name.kind === SyntaxKind.ComputedPropertyName || + node.name.kind === SyntaxKind.PrivateIdentifier) && + !!node.questionToken, + override: (0, node_utils_1.hasModifier)(SyntaxKind.OverrideKeyword, node), + readonly: (0, node_utils_1.hasModifier)(SyntaxKind.ReadonlyKeyword, node), + static: (0, node_utils_1.hasModifier)(SyntaxKind.StaticKeyword, node), + typeAnnotation: node.type && this.convertTypeAnnotation(node.type, node), + value: isAbstract ? null : this.convertChild(node.initializer), + }); + } + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: { + if (node.parent.kind === SyntaxKind.InterfaceDeclaration || + node.parent.kind === SyntaxKind.TypeLiteral) { + return this.convertMethodSignature(node); + } + } + // otherwise, it is a non-type accessor - intentional fallthrough + case SyntaxKind.MethodDeclaration: { + const method = this.createNode(node, { + type: !node.body + ? ts_estree_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression + : ts_estree_1.AST_NODE_TYPES.FunctionExpression, + range: [node.parameters.pos - 1, node.end], + async: (0, node_utils_1.hasModifier)(SyntaxKind.AsyncKeyword, node), + body: this.convertChild(node.body), + declare: false, + expression: false, // ESTreeNode as ESTreeNode here + generator: !!node.asteriskToken, + id: null, + params: [], + returnType: node.type && this.convertTypeAnnotation(node.type, node), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + if (method.typeParameters) { + this.fixParentLocation(method, method.typeParameters.range); + } + let result; + if (parent.kind === SyntaxKind.ObjectLiteralExpression) { + method.params = node.parameters.map(el => this.convertChild(el)); + result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Property, + computed: (0, node_utils_1.isComputedProperty)(node.name), + key: this.convertChild(node.name), + kind: 'init', + method: node.kind === SyntaxKind.MethodDeclaration, + optional: !!node.questionToken, + shorthand: false, + value: method, + }); + } + else { + // class + /** + * Unlike in object literal methods, class method params can have decorators + */ + method.params = this.convertParameters(node.parameters); + /** + * TypeScript class methods can be defined as "abstract" + */ + const methodDefinitionType = (0, node_utils_1.hasModifier)(SyntaxKind.AbstractKeyword, node) + ? ts_estree_1.AST_NODE_TYPES.TSAbstractMethodDefinition + : ts_estree_1.AST_NODE_TYPES.MethodDefinition; + result = this.createNode(node, { + type: methodDefinitionType, + accessibility: (0, node_utils_1.getTSNodeAccessibility)(node), + computed: (0, node_utils_1.isComputedProperty)(node.name), + decorators: (0, getModifiers_1.getDecorators)(node)?.map(el => this.convertChild(el)) ?? [], + key: this.convertChild(node.name), + kind: 'method', + optional: !!node.questionToken, + override: (0, node_utils_1.hasModifier)(SyntaxKind.OverrideKeyword, node), + static: (0, node_utils_1.hasModifier)(SyntaxKind.StaticKeyword, node), + value: method, + }); + } + if (node.kind === SyntaxKind.GetAccessor) { + result.kind = 'get'; + } + else if (node.kind === SyntaxKind.SetAccessor) { + result.kind = 'set'; + } + else if (!result.static && + node.name.kind === SyntaxKind.StringLiteral && + node.name.text === 'constructor' && + result.type !== ts_estree_1.AST_NODE_TYPES.Property) { + result.kind = 'constructor'; + } + return result; + } + // TypeScript uses this even for static methods named "constructor" + case SyntaxKind.Constructor: { + const lastModifier = (0, node_utils_1.getLastModifier)(node); + const constructorToken = (lastModifier && (0, node_utils_1.findNextToken)(lastModifier, node, this.ast)) ?? + node.getFirstToken(); + const constructor = this.createNode(node, { + type: !node.body + ? ts_estree_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression + : ts_estree_1.AST_NODE_TYPES.FunctionExpression, + range: [node.parameters.pos - 1, node.end], + async: false, + body: this.convertChild(node.body), + declare: false, + expression: false, // is not present in ESTreeNode + generator: false, + id: null, + params: this.convertParameters(node.parameters), + returnType: node.type && this.convertTypeAnnotation(node.type, node), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + if (constructor.typeParameters) { + this.fixParentLocation(constructor, constructor.typeParameters.range); + } + const constructorKey = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Identifier, + range: [constructorToken.getStart(this.ast), constructorToken.end], + decorators: [], + name: 'constructor', + optional: false, + typeAnnotation: undefined, + }); + const isStatic = (0, node_utils_1.hasModifier)(SyntaxKind.StaticKeyword, node); + return this.createNode(node, { + type: (0, node_utils_1.hasModifier)(SyntaxKind.AbstractKeyword, node) + ? ts_estree_1.AST_NODE_TYPES.TSAbstractMethodDefinition + : ts_estree_1.AST_NODE_TYPES.MethodDefinition, + accessibility: (0, node_utils_1.getTSNodeAccessibility)(node), + computed: false, + decorators: [], + key: constructorKey, + kind: isStatic ? 'method' : 'constructor', + optional: false, + override: false, + static: isStatic, + value: constructor, + }); + } + case SyntaxKind.FunctionExpression: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.FunctionExpression, + async: (0, node_utils_1.hasModifier)(SyntaxKind.AsyncKeyword, node), + body: this.convertChild(node.body), + declare: false, + expression: false, + generator: !!node.asteriskToken, + id: this.convertChild(node.name), + params: this.convertParameters(node.parameters), + returnType: node.type && this.convertTypeAnnotation(node.type, node), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + } + case SyntaxKind.SuperKeyword: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Super, + }); + case SyntaxKind.ArrayBindingPattern: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ArrayPattern, + decorators: [], + elements: node.elements.map(el => this.convertPattern(el)), + optional: false, + typeAnnotation: undefined, + }); + // occurs with missing array elements like [,] + case SyntaxKind.OmittedExpression: + return null; + case SyntaxKind.ObjectBindingPattern: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ObjectPattern, + decorators: [], + optional: false, + properties: node.elements.map(el => this.convertPattern(el)), + typeAnnotation: undefined, + }); + case SyntaxKind.BindingElement: { + if (parent.kind === SyntaxKind.ArrayBindingPattern) { + const arrayItem = this.convertChild(node.name, parent); + if (node.initializer) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.AssignmentPattern, + decorators: [], + left: arrayItem, + optional: false, + right: this.convertChild(node.initializer), + typeAnnotation: undefined, + }); + } + if (node.dotDotDotToken) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.RestElement, + argument: arrayItem, + decorators: [], + optional: false, + typeAnnotation: undefined, + value: undefined, + }); + } + return arrayItem; + } + let result; + if (node.dotDotDotToken) { + result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.RestElement, + argument: this.convertChild(node.propertyName ?? node.name), + decorators: [], + optional: false, + typeAnnotation: undefined, + value: undefined, + }); + } + else { + result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Property, + computed: Boolean(node.propertyName && + node.propertyName.kind === SyntaxKind.ComputedPropertyName), + key: this.convertChild(node.propertyName ?? node.name), + kind: 'init', + method: false, + optional: false, + shorthand: !node.propertyName, + value: this.convertChild(node.name), + }); + } + if (node.initializer) { + result.value = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.AssignmentPattern, + range: [node.name.getStart(this.ast), node.initializer.end], + decorators: [], + left: this.convertChild(node.name), + optional: false, + right: this.convertChild(node.initializer), + typeAnnotation: undefined, + }); + } + return result; + } + case SyntaxKind.ArrowFunction: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ArrowFunctionExpression, + async: (0, node_utils_1.hasModifier)(SyntaxKind.AsyncKeyword, node), + body: this.convertChild(node.body), + expression: node.body.kind !== SyntaxKind.Block, + generator: false, + id: null, + params: this.convertParameters(node.parameters), + returnType: node.type && this.convertTypeAnnotation(node.type, node), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + } + case SyntaxKind.YieldExpression: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.YieldExpression, + argument: this.convertChild(node.expression), + delegate: !!node.asteriskToken, + }); + case SyntaxKind.AwaitExpression: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.AwaitExpression, + argument: this.convertChild(node.expression), + }); + // Template Literals + case SyntaxKind.NoSubstitutionTemplateLiteral: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TemplateLiteral, + expressions: [], + quasis: [ + this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TemplateElement, + tail: true, + value: { + cooked: node.text, + raw: this.ast.text.slice(node.getStart(this.ast) + 1, node.end - 1), + }, + }), + ], + }); + case SyntaxKind.TemplateExpression: { + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TemplateLiteral, + expressions: [], + quasis: [this.convertChild(node.head)], + }); + node.templateSpans.forEach(templateSpan => { + result.expressions.push(this.convertChild(templateSpan.expression)); + result.quasis.push(this.convertChild(templateSpan.literal)); + }); + return result; + } + case SyntaxKind.TaggedTemplateExpression: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TaggedTemplateExpression, + quasi: this.convertChild(node.template), + tag: this.convertChild(node.tag), + typeArguments: node.typeArguments && + this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node), + }); + case SyntaxKind.TemplateHead: + case SyntaxKind.TemplateMiddle: + case SyntaxKind.TemplateTail: { + const tail = node.kind === SyntaxKind.TemplateTail; + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TemplateElement, + tail, + value: { + cooked: node.text, + raw: this.ast.text.slice(node.getStart(this.ast) + 1, node.end - (tail ? 1 : 2)), + }, + }); + } + // Patterns + case SyntaxKind.SpreadAssignment: + case SyntaxKind.SpreadElement: { + if (this.allowPattern) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.RestElement, + argument: this.convertPattern(node.expression), + decorators: [], + optional: false, + typeAnnotation: undefined, + value: undefined, + }); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.SpreadElement, + argument: this.convertChild(node.expression), + }); + } + case SyntaxKind.Parameter: { + let parameter; + let result; + if (node.dotDotDotToken) { + parameter = result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.RestElement, + argument: this.convertChild(node.name), + decorators: [], + optional: false, + typeAnnotation: undefined, + value: undefined, + }); + } + else if (node.initializer) { + parameter = this.convertChild(node.name); + result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.AssignmentPattern, + range: [node.name.getStart(this.ast), node.initializer.end], + decorators: [], + left: parameter, + optional: false, + right: this.convertChild(node.initializer), + typeAnnotation: undefined, + }); + const modifiers = (0, getModifiers_1.getModifiers)(node); + if (modifiers) { + // AssignmentPattern should not contain modifiers in range + result.range[0] = parameter.range[0]; + result.loc = (0, node_utils_1.getLocFor)(result.range, this.ast); + } + } + else { + parameter = result = this.convertChild(node.name, parent); + } + if (node.type) { + parameter.typeAnnotation = this.convertTypeAnnotation(node.type, node); + this.fixParentLocation(parameter, parameter.typeAnnotation.range); + } + if (node.questionToken) { + if (node.questionToken.end > parameter.range[1]) { + parameter.range[1] = node.questionToken.end; + parameter.loc.end = (0, node_utils_1.getLineAndCharacterFor)(parameter.range[1], this.ast); + } + parameter.optional = true; + } + const modifiers = (0, getModifiers_1.getModifiers)(node); + if (modifiers) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSParameterProperty, + accessibility: (0, node_utils_1.getTSNodeAccessibility)(node), + decorators: [], + override: (0, node_utils_1.hasModifier)(SyntaxKind.OverrideKeyword, node), + parameter: result, + readonly: (0, node_utils_1.hasModifier)(SyntaxKind.ReadonlyKeyword, node), + static: (0, node_utils_1.hasModifier)(SyntaxKind.StaticKeyword, node), + }); + } + return result; + } + // Classes + case SyntaxKind.ClassDeclaration: + if (!node.name && + (!(0, node_utils_1.hasModifier)(ts.SyntaxKind.ExportKeyword, node) || + !(0, node_utils_1.hasModifier)(ts.SyntaxKind.DefaultKeyword, node))) { + this.#throwUnlessAllowInvalidAST(node, "A class declaration without the 'default' modifier must have a name."); + } + /* intentional fallthrough */ + case SyntaxKind.ClassExpression: { + const heritageClauses = node.heritageClauses ?? []; + const classNodeType = node.kind === SyntaxKind.ClassDeclaration + ? ts_estree_1.AST_NODE_TYPES.ClassDeclaration + : ts_estree_1.AST_NODE_TYPES.ClassExpression; + let extendsClause; + let implementsClause; + for (const heritageClause of heritageClauses) { + const { token, types } = heritageClause; + if (types.length === 0) { + this.#throwUnlessAllowInvalidAST(heritageClause, `'${ts.tokenToString(token)}' list cannot be empty.`); + } + if (token === SyntaxKind.ExtendsKeyword) { + if (extendsClause) { + this.#throwUnlessAllowInvalidAST(heritageClause, "'extends' clause already seen."); + } + if (implementsClause) { + this.#throwUnlessAllowInvalidAST(heritageClause, "'extends' clause must precede 'implements' clause."); + } + if (types.length > 1) { + this.#throwUnlessAllowInvalidAST(types[1], 'Classes can only extend a single class.'); + } + extendsClause ??= heritageClause; + } + else if (token === SyntaxKind.ImplementsKeyword) { + if (implementsClause) { + this.#throwUnlessAllowInvalidAST(heritageClause, "'implements' clause already seen."); + } + implementsClause ??= heritageClause; + } + } + const result = this.createNode(node, { + type: classNodeType, + abstract: (0, node_utils_1.hasModifier)(SyntaxKind.AbstractKeyword, node), + body: this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ClassBody, + range: [node.members.pos - 1, node.end], + body: node.members + .filter(node_utils_1.isESTreeClassMember) + .map(el => this.convertChild(el)), + }), + declare: (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node), + decorators: (0, getModifiers_1.getDecorators)(node)?.map(el => this.convertChild(el)) ?? [], + id: this.convertChild(node.name), + implements: implementsClause?.types.map(el => this.convertChild(el)) ?? [], + superClass: extendsClause?.types[0] + ? this.convertChild(extendsClause.types[0].expression) + : null, + superTypeArguments: undefined, + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + if (extendsClause?.types[0]?.typeArguments) { + result.superTypeArguments = + this.convertTypeArgumentsToTypeParameterInstantiation(extendsClause.types[0].typeArguments, extendsClause.types[0]); + } + return this.fixExports(node, result); + } + // Modules + case SyntaxKind.ModuleBlock: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSModuleBlock, + body: this.convertBodyExpressions(node.statements, node), + }); + case SyntaxKind.ImportDeclaration: { + this.assertModuleSpecifier(node, false); + const result = this.createNode(node, this.#withDeprecatedAliasGetter({ + type: ts_estree_1.AST_NODE_TYPES.ImportDeclaration, + attributes: this.convertImportAttributes( + // eslint-disable-next-line @typescript-eslint/no-deprecated + node.attributes ?? node.assertClause), + importKind: 'value', + source: this.convertChild(node.moduleSpecifier), + specifiers: [], + }, 'assertions', 'attributes', true)); + if (node.importClause) { + if (node.importClause.isTypeOnly) { + result.importKind = 'type'; + } + if (node.importClause.name) { + result.specifiers.push(this.convertChild(node.importClause)); + } + if (node.importClause.namedBindings) { + switch (node.importClause.namedBindings.kind) { + case SyntaxKind.NamespaceImport: + result.specifiers.push(this.convertChild(node.importClause.namedBindings)); + break; + case SyntaxKind.NamedImports: + result.specifiers.push(...node.importClause.namedBindings.elements.map(el => this.convertChild(el))); + break; + } + } + } + return result; + } + case SyntaxKind.NamespaceImport: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ImportNamespaceSpecifier, + local: this.convertChild(node.name), + }); + case SyntaxKind.ImportSpecifier: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ImportSpecifier, + imported: this.convertChild(node.propertyName ?? node.name), + importKind: node.isTypeOnly ? 'type' : 'value', + local: this.convertChild(node.name), + }); + case SyntaxKind.ImportClause: { + const local = this.convertChild(node.name); + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ImportDefaultSpecifier, + range: local.range, + local, + }); + } + case SyntaxKind.ExportDeclaration: { + if (node.exportClause?.kind === SyntaxKind.NamedExports) { + this.assertModuleSpecifier(node, true); + return this.createNode(node, this.#withDeprecatedAliasGetter({ + type: ts_estree_1.AST_NODE_TYPES.ExportNamedDeclaration, + attributes: this.convertImportAttributes( + // eslint-disable-next-line @typescript-eslint/no-deprecated + node.attributes ?? node.assertClause), + declaration: null, + exportKind: node.isTypeOnly ? 'type' : 'value', + source: this.convertChild(node.moduleSpecifier), + specifiers: node.exportClause.elements.map(el => this.convertChild(el, node)), + }, 'assertions', 'attributes', true)); + } + this.assertModuleSpecifier(node, false); + return this.createNode(node, this.#withDeprecatedAliasGetter({ + type: ts_estree_1.AST_NODE_TYPES.ExportAllDeclaration, + attributes: this.convertImportAttributes( + // eslint-disable-next-line @typescript-eslint/no-deprecated + node.attributes ?? node.assertClause), + exported: node.exportClause?.kind === SyntaxKind.NamespaceExport + ? this.convertChild(node.exportClause.name) + : null, + exportKind: node.isTypeOnly ? 'type' : 'value', + source: this.convertChild(node.moduleSpecifier), + }, 'assertions', 'attributes', true)); + } + case SyntaxKind.ExportSpecifier: { + const local = node.propertyName ?? node.name; + if (local.kind === SyntaxKind.StringLiteral && + parent.kind === SyntaxKind.ExportDeclaration && + parent.moduleSpecifier?.kind !== SyntaxKind.StringLiteral) { + this.#throwError(local, 'A string literal cannot be used as a local exported binding without `from`.'); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ExportSpecifier, + exported: this.convertChild(node.name), + exportKind: node.isTypeOnly ? 'type' : 'value', + local: this.convertChild(local), + }); + } + case SyntaxKind.ExportAssignment: + if (node.isExportEquals) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSExportAssignment, + expression: this.convertChild(node.expression), + }); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ExportDefaultDeclaration, + declaration: this.convertChild(node.expression), + exportKind: 'value', + }); + // Unary Operations + case SyntaxKind.PrefixUnaryExpression: + case SyntaxKind.PostfixUnaryExpression: { + const operator = (0, node_utils_1.getTextForTokenKind)(node.operator); + /** + * ESTree uses UpdateExpression for ++/-- + */ + if (operator === '++' || operator === '--') { + if (!(0, node_utils_1.isValidAssignmentTarget)(node.operand)) { + this.#throwUnlessAllowInvalidAST(node.operand, 'Invalid left-hand side expression in unary operation'); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.UpdateExpression, + argument: this.convertChild(node.operand), + operator, + prefix: node.kind === SyntaxKind.PrefixUnaryExpression, + }); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.UnaryExpression, + argument: this.convertChild(node.operand), + operator, + prefix: node.kind === SyntaxKind.PrefixUnaryExpression, + }); + } + case SyntaxKind.DeleteExpression: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.UnaryExpression, + argument: this.convertChild(node.expression), + operator: 'delete', + prefix: true, + }); + case SyntaxKind.VoidExpression: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.UnaryExpression, + argument: this.convertChild(node.expression), + operator: 'void', + prefix: true, + }); + case SyntaxKind.TypeOfExpression: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.UnaryExpression, + argument: this.convertChild(node.expression), + operator: 'typeof', + prefix: true, + }); + case SyntaxKind.TypeOperator: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypeOperator, + operator: (0, node_utils_1.getTextForTokenKind)(node.operator), + typeAnnotation: this.convertChild(node.type), + }); + // Binary Operations + case SyntaxKind.BinaryExpression: { + // TypeScript uses BinaryExpression for sequences as well + if ((0, node_utils_1.isComma)(node.operatorToken)) { + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.SequenceExpression, + expressions: [], + }); + const left = this.convertChild(node.left); + if (left.type === ts_estree_1.AST_NODE_TYPES.SequenceExpression && + node.left.kind !== SyntaxKind.ParenthesizedExpression) { + result.expressions.push(...left.expressions); + } + else { + result.expressions.push(left); + } + result.expressions.push(this.convertChild(node.right)); + return result; + } + const expressionType = (0, node_utils_1.getBinaryExpressionType)(node.operatorToken); + if (this.allowPattern && + expressionType.type === ts_estree_1.AST_NODE_TYPES.AssignmentExpression) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.AssignmentPattern, + decorators: [], + left: this.convertPattern(node.left, node), + optional: false, + right: this.convertChild(node.right), + typeAnnotation: undefined, + }); + } + return this.createNode(node, { + ...expressionType, + left: this.converter(node.left, node, expressionType.type === ts_estree_1.AST_NODE_TYPES.AssignmentExpression), + right: this.convertChild(node.right), + }); + } + case SyntaxKind.PropertyAccessExpression: { + const object = this.convertChild(node.expression); + const property = this.convertChild(node.name); + const computed = false; + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.MemberExpression, + computed, + object, + optional: node.questionDotToken != null, + property, + }); + return this.convertChainExpression(result, node); + } + case SyntaxKind.ElementAccessExpression: { + const object = this.convertChild(node.expression); + const property = this.convertChild(node.argumentExpression); + const computed = true; + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.MemberExpression, + computed, + object, + optional: node.questionDotToken != null, + property, + }); + return this.convertChainExpression(result, node); + } + case SyntaxKind.CallExpression: { + if (node.expression.kind === SyntaxKind.ImportKeyword) { + if (node.arguments.length !== 1 && node.arguments.length !== 2) { + this.#throwUnlessAllowInvalidAST(node.arguments[2] ?? node, 'Dynamic import requires exactly one or two arguments.'); + } + return this.createNode(node, this.#withDeprecatedAliasGetter({ + type: ts_estree_1.AST_NODE_TYPES.ImportExpression, + options: node.arguments[1] + ? this.convertChild(node.arguments[1]) + : null, + source: this.convertChild(node.arguments[0]), + }, 'attributes', 'options', true)); + } + const callee = this.convertChild(node.expression); + const args = node.arguments.map(el => this.convertChild(el)); + const typeArguments = node.typeArguments && + this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node); + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.CallExpression, + arguments: args, + callee, + optional: node.questionDotToken != null, + typeArguments, + }); + return this.convertChainExpression(result, node); + } + case SyntaxKind.NewExpression: { + const typeArguments = node.typeArguments && + this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node); + // NOTE - NewExpression cannot have an optional chain in it + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.NewExpression, + arguments: node.arguments + ? node.arguments.map(el => this.convertChild(el)) + : [], + callee: this.convertChild(node.expression), + typeArguments, + }); + } + case SyntaxKind.ConditionalExpression: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ConditionalExpression, + alternate: this.convertChild(node.whenFalse), + consequent: this.convertChild(node.whenTrue), + test: this.convertChild(node.condition), + }); + case SyntaxKind.MetaProperty: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.MetaProperty, + meta: this.createNode( + // TODO: do we really want to convert it to Token? + node.getFirstToken(), { + type: ts_estree_1.AST_NODE_TYPES.Identifier, + decorators: [], + name: (0, node_utils_1.getTextForTokenKind)(node.keywordToken), + optional: false, + typeAnnotation: undefined, + }), + property: this.convertChild(node.name), + }); + } + case SyntaxKind.Decorator: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Decorator, + expression: this.convertChild(node.expression), + }); + } + // Literals + case SyntaxKind.StringLiteral: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Literal, + raw: node.getText(), + value: parent.kind === SyntaxKind.JsxAttribute + ? (0, node_utils_1.unescapeStringLiteralText)(node.text) + : node.text, + }); + } + case SyntaxKind.NumericLiteral: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Literal, + raw: node.getText(), + value: Number(node.text), + }); + } + case SyntaxKind.BigIntLiteral: { + const range = (0, node_utils_1.getRange)(node, this.ast); + const rawValue = this.ast.text.slice(range[0], range[1]); + const bigint = rawValue + // remove suffix `n` + .slice(0, -1) + // `BigInt` doesn't accept numeric separator + // and `bigint` property should not include numeric separator + .replaceAll('_', ''); + const value = typeof BigInt !== 'undefined' ? BigInt(bigint) : null; + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Literal, + range, + bigint: value == null ? bigint : String(value), + raw: rawValue, + value, + }); + } + case SyntaxKind.RegularExpressionLiteral: { + const pattern = node.text.slice(1, node.text.lastIndexOf('/')); + const flags = node.text.slice(node.text.lastIndexOf('/') + 1); + let regex = null; + try { + regex = new RegExp(pattern, flags); + } + catch { + // Intentionally blank, so regex stays null + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Literal, + raw: node.text, + regex: { + flags, + pattern, + }, + value: regex, + }); + } + case SyntaxKind.TrueKeyword: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Literal, + raw: 'true', + value: true, + }); + case SyntaxKind.FalseKeyword: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Literal, + raw: 'false', + value: false, + }); + case SyntaxKind.NullKeyword: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Literal, + raw: 'null', + value: null, + }); + } + case SyntaxKind.EmptyStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.EmptyStatement, + }); + case SyntaxKind.DebuggerStatement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.DebuggerStatement, + }); + // JSX + case SyntaxKind.JsxElement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXElement, + children: node.children.map(el => this.convertChild(el)), + closingElement: this.convertChild(node.closingElement), + openingElement: this.convertChild(node.openingElement), + }); + case SyntaxKind.JsxFragment: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXFragment, + children: node.children.map(el => this.convertChild(el)), + closingFragment: this.convertChild(node.closingFragment), + openingFragment: this.convertChild(node.openingFragment), + }); + case SyntaxKind.JsxSelfClosingElement: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXElement, + /** + * Convert SyntaxKind.JsxSelfClosingElement to SyntaxKind.JsxOpeningElement, + * TypeScript does not seem to have the idea of openingElement when tag is self-closing + */ + children: [], + closingElement: null, + openingElement: this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXOpeningElement, + range: (0, node_utils_1.getRange)(node, this.ast), + attributes: node.attributes.properties.map(el => this.convertChild(el)), + name: this.convertJSXTagName(node.tagName, node), + selfClosing: true, + typeArguments: node.typeArguments + ? this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node) + : undefined, + }), + }); + } + case SyntaxKind.JsxOpeningElement: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXOpeningElement, + attributes: node.attributes.properties.map(el => this.convertChild(el)), + name: this.convertJSXTagName(node.tagName, node), + selfClosing: false, + typeArguments: node.typeArguments && + this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node), + }); + } + case SyntaxKind.JsxClosingElement: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXClosingElement, + name: this.convertJSXTagName(node.tagName, node), + }); + case SyntaxKind.JsxOpeningFragment: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXOpeningFragment, + }); + case SyntaxKind.JsxClosingFragment: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXClosingFragment, + }); + case SyntaxKind.JsxExpression: { + const expression = node.expression + ? this.convertChild(node.expression) + : this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXEmptyExpression, + range: [node.getStart(this.ast) + 1, node.getEnd() - 1], + }); + if (node.dotDotDotToken) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXSpreadChild, + expression, + }); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXExpressionContainer, + expression, + }); + } + case SyntaxKind.JsxAttribute: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXAttribute, + name: this.convertJSXNamespaceOrIdentifier(node.name), + value: this.convertChild(node.initializer), + }); + } + case SyntaxKind.JsxText: { + const start = node.getFullStart(); + const end = node.getEnd(); + const text = this.ast.text.slice(start, end); + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXText, + range: [start, end], + raw: text, + value: (0, node_utils_1.unescapeStringLiteralText)(text), + }); + } + case SyntaxKind.JsxSpreadAttribute: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.JSXSpreadAttribute, + argument: this.convertChild(node.expression), + }); + case SyntaxKind.QualifiedName: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSQualifiedName, + left: this.convertChild(node.left), + right: this.convertChild(node.right), + }); + } + // TypeScript specific + case SyntaxKind.TypeReference: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypeReference, + typeArguments: node.typeArguments && + this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node), + typeName: this.convertChild(node.typeName), + }); + case SyntaxKind.TypeParameter: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypeParameter, + const: (0, node_utils_1.hasModifier)(SyntaxKind.ConstKeyword, node), + constraint: node.constraint && this.convertChild(node.constraint), + default: node.default ? this.convertChild(node.default) : undefined, + in: (0, node_utils_1.hasModifier)(SyntaxKind.InKeyword, node), + name: this.convertChild(node.name), + out: (0, node_utils_1.hasModifier)(SyntaxKind.OutKeyword, node), + }); + } + case SyntaxKind.ThisType: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSThisType, + }); + case SyntaxKind.AnyKeyword: + case SyntaxKind.BigIntKeyword: + case SyntaxKind.BooleanKeyword: + case SyntaxKind.NeverKeyword: + case SyntaxKind.NumberKeyword: + case SyntaxKind.ObjectKeyword: + case SyntaxKind.StringKeyword: + case SyntaxKind.SymbolKeyword: + case SyntaxKind.UnknownKeyword: + case SyntaxKind.VoidKeyword: + case SyntaxKind.UndefinedKeyword: + case SyntaxKind.IntrinsicKeyword: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES[`TS${SyntaxKind[node.kind]}`], + }); + } + case SyntaxKind.NonNullExpression: { + const nnExpr = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSNonNullExpression, + expression: this.convertChild(node.expression), + }); + return this.convertChainExpression(nnExpr, node); + } + case SyntaxKind.TypeLiteral: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypeLiteral, + members: node.members.map(el => this.convertChild(el)), + }); + } + case SyntaxKind.ArrayType: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSArrayType, + elementType: this.convertChild(node.elementType), + }); + } + case SyntaxKind.IndexedAccessType: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSIndexedAccessType, + indexType: this.convertChild(node.indexType), + objectType: this.convertChild(node.objectType), + }); + } + case SyntaxKind.ConditionalType: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSConditionalType, + checkType: this.convertChild(node.checkType), + extendsType: this.convertChild(node.extendsType), + falseType: this.convertChild(node.falseType), + trueType: this.convertChild(node.trueType), + }); + } + case SyntaxKind.TypeQuery: + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypeQuery, + exprName: this.convertChild(node.exprName), + typeArguments: node.typeArguments && + this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node), + }); + case SyntaxKind.MappedType: { + if (node.members && node.members.length > 0) { + this.#throwUnlessAllowInvalidAST(node.members[0], 'A mapped type may not declare properties or methods.'); + } + return this.createNode(node, this.#withDeprecatedGetter({ + type: ts_estree_1.AST_NODE_TYPES.TSMappedType, + constraint: this.convertChild(node.typeParameter.constraint), + key: this.convertChild(node.typeParameter.name), + nameType: this.convertChild(node.nameType) ?? null, + optional: node.questionToken + ? node.questionToken.kind === SyntaxKind.QuestionToken || + (0, node_utils_1.getTextForTokenKind)(node.questionToken.kind) + : false, + readonly: node.readonlyToken + ? node.readonlyToken.kind === SyntaxKind.ReadonlyKeyword || + (0, node_utils_1.getTextForTokenKind)(node.readonlyToken.kind) + : undefined, + typeAnnotation: node.type && this.convertChild(node.type), + }, 'typeParameter', "'constraint' and 'key'", this.convertChild(node.typeParameter))); + } + case SyntaxKind.ParenthesizedExpression: + return this.convertChild(node.expression, parent); + case SyntaxKind.TypeAliasDeclaration: { + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypeAliasDeclaration, + declare: (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node), + id: this.convertChild(node.name), + typeAnnotation: this.convertChild(node.type), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + return this.fixExports(node, result); + } + case SyntaxKind.MethodSignature: { + return this.convertMethodSignature(node); + } + case SyntaxKind.PropertySignature: { + // eslint-disable-next-line @typescript-eslint/no-deprecated + const { initializer } = node; + if (initializer) { + this.#throwError(initializer, 'A property signature cannot have an initializer.'); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSPropertySignature, + accessibility: (0, node_utils_1.getTSNodeAccessibility)(node), + computed: (0, node_utils_1.isComputedProperty)(node.name), + key: this.convertChild(node.name), + optional: (0, node_utils_1.isOptional)(node), + readonly: (0, node_utils_1.hasModifier)(SyntaxKind.ReadonlyKeyword, node), + static: (0, node_utils_1.hasModifier)(SyntaxKind.StaticKeyword, node), + typeAnnotation: node.type && this.convertTypeAnnotation(node.type, node), + }); + } + case SyntaxKind.IndexSignature: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSIndexSignature, + accessibility: (0, node_utils_1.getTSNodeAccessibility)(node), + parameters: node.parameters.map(el => this.convertChild(el)), + readonly: (0, node_utils_1.hasModifier)(SyntaxKind.ReadonlyKeyword, node), + static: (0, node_utils_1.hasModifier)(SyntaxKind.StaticKeyword, node), + typeAnnotation: node.type && this.convertTypeAnnotation(node.type, node), + }); + } + case SyntaxKind.ConstructorType: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSConstructorType, + abstract: (0, node_utils_1.hasModifier)(SyntaxKind.AbstractKeyword, node), + params: this.convertParameters(node.parameters), + returnType: node.type && this.convertTypeAnnotation(node.type, node), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + } + case SyntaxKind.FunctionType: { + // eslint-disable-next-line @typescript-eslint/no-deprecated + const { modifiers } = node; + if (modifiers) { + this.#throwError(modifiers[0], 'A function type cannot have modifiers.'); + } + } + // intentional fallthrough + case SyntaxKind.ConstructSignature: + case SyntaxKind.CallSignature: { + const type = node.kind === SyntaxKind.ConstructSignature + ? ts_estree_1.AST_NODE_TYPES.TSConstructSignatureDeclaration + : node.kind === SyntaxKind.CallSignature + ? ts_estree_1.AST_NODE_TYPES.TSCallSignatureDeclaration + : ts_estree_1.AST_NODE_TYPES.TSFunctionType; + return this.createNode(node, { + type, + params: this.convertParameters(node.parameters), + returnType: node.type && this.convertTypeAnnotation(node.type, node), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + } + case SyntaxKind.ExpressionWithTypeArguments: { + const parentKind = parent.kind; + const type = parentKind === SyntaxKind.InterfaceDeclaration + ? ts_estree_1.AST_NODE_TYPES.TSInterfaceHeritage + : parentKind === SyntaxKind.HeritageClause + ? ts_estree_1.AST_NODE_TYPES.TSClassImplements + : ts_estree_1.AST_NODE_TYPES.TSInstantiationExpression; + return this.createNode(node, { + type, + expression: this.convertChild(node.expression), + typeArguments: node.typeArguments && + this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node), + }); + } + case SyntaxKind.InterfaceDeclaration: { + const interfaceHeritageClauses = node.heritageClauses ?? []; + const interfaceExtends = []; + let seenExtendsClause = false; + for (const heritageClause of interfaceHeritageClauses) { + if (heritageClause.token !== SyntaxKind.ExtendsKeyword) { + this.#throwError(heritageClause, heritageClause.token === SyntaxKind.ImplementsKeyword + ? "Interface declaration cannot have 'implements' clause." + : 'Unexpected token.'); + } + if (seenExtendsClause) { + this.#throwError(heritageClause, "'extends' clause already seen."); + } + seenExtendsClause = true; + for (const heritageType of heritageClause.types) { + if (!isEntityNameExpression(heritageType.expression) || + ts.isOptionalChain(heritageType.expression)) { + this.#throwError(heritageType, 'Interface declaration can only extend an identifier/qualified name with optional type arguments.'); + } + interfaceExtends.push(this.convertChild(heritageType, node)); + } + } + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSInterfaceDeclaration, + body: this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSInterfaceBody, + range: [node.members.pos - 1, node.end], + body: node.members.map(member => this.convertChild(member)), + }), + declare: (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node), + extends: interfaceExtends, + id: this.convertChild(node.name), + typeParameters: node.typeParameters && + this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters), + }); + return this.fixExports(node, result); + } + case SyntaxKind.TypePredicate: { + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypePredicate, + asserts: node.assertsModifier != null, + parameterName: this.convertChild(node.parameterName), + typeAnnotation: null, + }); + /** + * Specific fix for type-guard location data + */ + if (node.type) { + result.typeAnnotation = this.convertTypeAnnotation(node.type, node); + result.typeAnnotation.loc = result.typeAnnotation.typeAnnotation.loc; + result.typeAnnotation.range = + result.typeAnnotation.typeAnnotation.range; + } + return result; + } + case SyntaxKind.ImportType: { + const range = (0, node_utils_1.getRange)(node, this.ast); + if (node.isTypeOf) { + const token = (0, node_utils_1.findNextToken)(node.getFirstToken(), node, this.ast); + range[0] = token.getStart(this.ast); + } + let options = null; + if (node.attributes) { + const value = this.createNode(node.attributes, { + type: ts_estree_1.AST_NODE_TYPES.ObjectExpression, + properties: node.attributes.elements.map(importAttribute => this.createNode(importAttribute, { + type: ts_estree_1.AST_NODE_TYPES.Property, + computed: false, + key: this.convertChild(importAttribute.name), + kind: 'init', + method: false, + optional: false, + shorthand: false, + value: this.convertChild(importAttribute.value), + })), + }); + const commaToken = (0, node_utils_1.findNextToken)(node.argument, node, this.ast); + const openBraceToken = (0, node_utils_1.findNextToken)(commaToken, node, this.ast); + const closeBraceToken = (0, node_utils_1.findNextToken)(node.attributes, node, this.ast); + const withOrAssertToken = (0, node_utils_1.findNextToken)(openBraceToken, node, this.ast); + const withOrAssertTokenRange = (0, node_utils_1.getRange)(withOrAssertToken, this.ast); + const withOrAssertName = withOrAssertToken.kind === ts.SyntaxKind.AssertKeyword + ? 'assert' + : 'with'; + options = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ObjectExpression, + range: [openBraceToken.getStart(this.ast), closeBraceToken.end], + properties: [ + this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Property, + range: [withOrAssertTokenRange[0], node.attributes.end], + computed: false, + key: this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.Identifier, + range: withOrAssertTokenRange, + decorators: [], + name: withOrAssertName, + optional: false, + typeAnnotation: undefined, + }), + kind: 'init', + method: false, + optional: false, + shorthand: false, + value, + }), + ], + }); + } + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSImportType, + range, + argument: this.convertChild(node.argument), + options, + qualifier: this.convertChild(node.qualifier), + typeArguments: node.typeArguments + ? this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node) + : null, + }); + if (node.isTypeOf) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypeQuery, + exprName: result, + typeArguments: undefined, + }); + } + return result; + } + case SyntaxKind.EnumDeclaration: { + const members = node.members.map(el => this.convertChild(el)); + const result = this.createNode(node, this.#withDeprecatedGetter({ + type: ts_estree_1.AST_NODE_TYPES.TSEnumDeclaration, + body: this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSEnumBody, + range: [node.members.pos - 1, node.end], + members, + }), + const: (0, node_utils_1.hasModifier)(SyntaxKind.ConstKeyword, node), + declare: (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node), + id: this.convertChild(node.name), + }, 'members', `'body.members'`, node.members.map(el => this.convertChild(el)))); + return this.fixExports(node, result); + } + case SyntaxKind.EnumMember: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSEnumMember, + computed: node.name.kind === ts.SyntaxKind.ComputedPropertyName, + id: this.convertChild(node.name), + initializer: node.initializer && this.convertChild(node.initializer), + }); + } + case SyntaxKind.ModuleDeclaration: { + let isDeclare = (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node); + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSModuleDeclaration, + ...(() => { + // the constraints checked by this function are syntactically enforced by TS + // the checks mostly exist for type's sake + if (node.flags & ts.NodeFlags.GlobalAugmentation) { + const id = this.convertChild(node.name); + const body = this.convertChild(node.body); + if (body == null || + body.type === ts_estree_1.AST_NODE_TYPES.TSModuleDeclaration) { + this.#throwUnlessAllowInvalidAST(node.body ?? node, 'Expected a valid module body'); + } + if (id.type !== ts_estree_1.AST_NODE_TYPES.Identifier) { + this.#throwUnlessAllowInvalidAST(node.name, 'global module augmentation must have an Identifier id'); + } + return { + body: body, + declare: false, + global: false, + id, + kind: 'global', + }; + } + if (ts.isStringLiteral(node.name)) { + const body = this.convertChild(node.body); + return { + kind: 'module', + ...(body != null ? { body } : {}), + declare: false, + global: false, + id: this.convertChild(node.name), + }; + } + // Nested module declarations are stored in TypeScript as nested tree nodes. + // We "unravel" them here by making our own nested TSQualifiedName, + // with the innermost node's body as the actual node body. + if (node.body == null) { + this.#throwUnlessAllowInvalidAST(node, 'Expected a module body'); + } + if (node.name.kind !== ts.SyntaxKind.Identifier) { + this.#throwUnlessAllowInvalidAST(node.name, '`namespace`s must have an Identifier id'); + } + let name = this.createNode(node.name, { + type: ts_estree_1.AST_NODE_TYPES.Identifier, + range: [node.name.getStart(this.ast), node.name.getEnd()], + decorators: [], + name: node.name.text, + optional: false, + typeAnnotation: undefined, + }); + while (node.body && + ts.isModuleDeclaration(node.body) && + node.body.name) { + node = node.body; + isDeclare ||= (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node); + const nextName = node.name; + const right = this.createNode(nextName, { + type: ts_estree_1.AST_NODE_TYPES.Identifier, + range: [nextName.getStart(this.ast), nextName.getEnd()], + decorators: [], + name: nextName.text, + optional: false, + typeAnnotation: undefined, + }); + name = this.createNode(nextName, { + type: ts_estree_1.AST_NODE_TYPES.TSQualifiedName, + range: [name.range[0], right.range[1]], + left: name, + right, + }); + } + return { + body: this.convertChild(node.body), + declare: false, + global: false, + id: name, + kind: node.flags & ts.NodeFlags.Namespace ? 'namespace' : 'module', + }; + })(), + }); + result.declare = isDeclare; + if (node.flags & ts.NodeFlags.GlobalAugmentation) { + // eslint-disable-next-line @typescript-eslint/no-deprecated + result.global = true; + } + return this.fixExports(node, result); + } + // TypeScript specific types + case SyntaxKind.ParenthesizedType: { + return this.convertChild(node.type); + } + case SyntaxKind.UnionType: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSUnionType, + types: node.types.map(el => this.convertChild(el)), + }); + } + case SyntaxKind.IntersectionType: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSIntersectionType, + types: node.types.map(el => this.convertChild(el)), + }); + } + case SyntaxKind.AsExpression: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSAsExpression, + expression: this.convertChild(node.expression), + typeAnnotation: this.convertChild(node.type), + }); + } + case SyntaxKind.InferType: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSInferType, + typeParameter: this.convertChild(node.typeParameter), + }); + } + case SyntaxKind.LiteralType: { + if (node.literal.kind === SyntaxKind.NullKeyword) { + // 4.0 started nesting null types inside a LiteralType node + // but our AST is designed around the old way of null being a keyword + return this.createNode(node.literal, { + type: ts_estree_1.AST_NODE_TYPES.TSNullKeyword, + }); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSLiteralType, + literal: this.convertChild(node.literal), + }); + } + case SyntaxKind.TypeAssertionExpression: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTypeAssertion, + expression: this.convertChild(node.expression), + typeAnnotation: this.convertChild(node.type), + }); + } + case SyntaxKind.ImportEqualsDeclaration: { + return this.fixExports(node, this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSImportEqualsDeclaration, + id: this.convertChild(node.name), + importKind: node.isTypeOnly ? 'type' : 'value', + moduleReference: this.convertChild(node.moduleReference), + })); + } + case SyntaxKind.ExternalModuleReference: { + if (node.expression.kind !== SyntaxKind.StringLiteral) { + this.#throwError(node.expression, 'String literal expected.'); + } + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSExternalModuleReference, + expression: this.convertChild(node.expression), + }); + } + case SyntaxKind.NamespaceExportDeclaration: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSNamespaceExportDeclaration, + id: this.convertChild(node.name), + }); + } + case SyntaxKind.AbstractKeyword: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSAbstractKeyword, + }); + } + // Tuple + case SyntaxKind.TupleType: { + const elementTypes = node.elements.map(el => this.convertChild(el)); + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTupleType, + elementTypes, + }); + } + case SyntaxKind.NamedTupleMember: { + const member = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSNamedTupleMember, + elementType: this.convertChild(node.type, node), + label: this.convertChild(node.name, node), + optional: node.questionToken != null, + }); + if (node.dotDotDotToken) { + // adjust the start to account for the "..." + member.range[0] = member.label.range[0]; + member.loc.start = member.label.loc.start; + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSRestType, + typeAnnotation: member, + }); + } + return member; + } + case SyntaxKind.OptionalType: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSOptionalType, + typeAnnotation: this.convertChild(node.type), + }); + } + case SyntaxKind.RestType: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSRestType, + typeAnnotation: this.convertChild(node.type), + }); + } + // Template Literal Types + case SyntaxKind.TemplateLiteralType: { + const result = this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSTemplateLiteralType, + quasis: [this.convertChild(node.head)], + types: [], + }); + node.templateSpans.forEach(templateSpan => { + result.types.push(this.convertChild(templateSpan.type)); + result.quasis.push(this.convertChild(templateSpan.literal)); + }); + return result; + } + case SyntaxKind.ClassStaticBlockDeclaration: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.StaticBlock, + body: this.convertBodyExpressions(node.body.statements, node), + }); + } + // eslint-disable-next-line @typescript-eslint/no-deprecated + case SyntaxKind.AssertEntry: + case SyntaxKind.ImportAttribute: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ImportAttribute, + key: this.convertChild(node.name), + value: this.convertChild(node.value), + }); + } + case SyntaxKind.SatisfiesExpression: { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.TSSatisfiesExpression, + expression: this.convertChild(node.expression), + typeAnnotation: this.convertChild(node.type), + }); + } + default: + return this.deeplyCopy(node); + } + } + createNode(node, data) { + const result = data; + result.range ??= (0, node_utils_1.getRange)(node, this.ast); + result.loc ??= (0, node_utils_1.getLocFor)(result.range, this.ast); + if (result && this.options.shouldPreserveNodeMaps) { + this.esTreeNodeToTSNodeMap.set(result, node); + } + return result; + } + convertProgram() { + return this.converter(this.ast); + } + /** + * For nodes that are copied directly from the TypeScript AST into + * ESTree mostly as-is. The only difference is the addition of a type + * property instead of a kind property. Recursively copies all children. + */ + deeplyCopy(node) { + if (node.kind === ts.SyntaxKind.JSDocFunctionType) { + this.#throwError(node, 'JSDoc types can only be used inside documentation comments.'); + } + const customType = `TS${SyntaxKind[node.kind]}`; + /** + * If the "errorOnUnknownASTType" option is set to true, throw an error, + * otherwise fallback to just including the unknown type as-is. + */ + if (this.options.errorOnUnknownASTType && !ts_estree_1.AST_NODE_TYPES[customType]) { + throw new Error(`Unknown AST_NODE_TYPE: "${customType}"`); + } + const result = this.createNode(node, { + type: customType, + }); + if ('type' in node) { + result.typeAnnotation = + node.type && 'kind' in node.type && ts.isTypeNode(node.type) + ? this.convertTypeAnnotation(node.type, node) + : null; + } + if ('typeArguments' in node) { + result.typeArguments = + node.typeArguments && 'pos' in node.typeArguments + ? this.convertTypeArgumentsToTypeParameterInstantiation(node.typeArguments, node) + : null; + } + if ('typeParameters' in node) { + result.typeParameters = + node.typeParameters && 'pos' in node.typeParameters + ? this.convertTSTypeParametersToTypeParametersDeclaration(node.typeParameters) + : null; + } + const decorators = (0, getModifiers_1.getDecorators)(node); + if (decorators?.length) { + result.decorators = decorators.map(el => this.convertChild(el)); + } + // keys we never want to clone from the base typescript node as they + // introduce garbage into our AST + const KEYS_TO_NOT_COPY = new Set([ + '_children', + 'decorators', + 'end', + 'flags', + 'heritageClauses', + 'illegalDecorators', + 'jsDoc', + 'kind', + 'locals', + 'localSymbol', + 'modifierFlagsCache', + 'modifiers', + 'nextContainer', + 'parent', + 'pos', + 'symbol', + 'transformFlags', + 'type', + 'typeArguments', + 'typeParameters', + ]); + Object.entries(node) + .filter(([key]) => !KEYS_TO_NOT_COPY.has(key)) + .forEach(([key, value]) => { + if (Array.isArray(value)) { + result[key] = value.map(el => this.convertChild(el)); + } + else if (value && typeof value === 'object' && value.kind) { + // need to check node[key].kind to ensure we don't try to convert a symbol + result[key] = this.convertChild(value); + } + else { + result[key] = value; + } + }); + return result; + } + /** + * Fixes the exports of the given ts.Node + * @returns the ESTreeNode with fixed exports + */ + fixExports(node, result) { + const isNamespaceNode = ts.isModuleDeclaration(node) && !ts.isStringLiteral(node.name); + const modifiers = isNamespaceNode + ? (0, node_utils_1.getNamespaceModifiers)(node) + : (0, getModifiers_1.getModifiers)(node); + if (modifiers?.[0].kind === SyntaxKind.ExportKeyword) { + /** + * Make sure that original node is registered instead of export + */ + this.registerTSNodeInNodeMap(node, result); + const exportKeyword = modifiers[0]; + const nextModifier = modifiers[1]; + const declarationIsDefault = nextModifier?.kind === SyntaxKind.DefaultKeyword; + const varToken = declarationIsDefault + ? (0, node_utils_1.findNextToken)(nextModifier, this.ast, this.ast) + : (0, node_utils_1.findNextToken)(exportKeyword, this.ast, this.ast); + result.range[0] = varToken.getStart(this.ast); + result.loc = (0, node_utils_1.getLocFor)(result.range, this.ast); + if (declarationIsDefault) { + return this.createNode(node, { + type: ts_estree_1.AST_NODE_TYPES.ExportDefaultDeclaration, + range: [exportKeyword.getStart(this.ast), result.range[1]], + declaration: result, + exportKind: 'value', + }); + } + const isType = result.type === ts_estree_1.AST_NODE_TYPES.TSInterfaceDeclaration || + result.type === ts_estree_1.AST_NODE_TYPES.TSTypeAliasDeclaration; + const isDeclare = 'declare' in result && result.declare; + return this.createNode(node, + // @ts-expect-error - TODO, narrow the types here + this.#withDeprecatedAliasGetter({ + type: ts_estree_1.AST_NODE_TYPES.ExportNamedDeclaration, + range: [exportKeyword.getStart(this.ast), result.range[1]], + attributes: [], + declaration: result, + exportKind: isType || isDeclare ? 'type' : 'value', + source: null, + specifiers: [], + }, 'assertions', 'attributes', true)); + } + return result; + } + getASTMaps() { + return { + esTreeNodeToTSNodeMap: this.esTreeNodeToTSNodeMap, + tsNodeToESTreeNodeMap: this.tsNodeToESTreeNodeMap, + }; + } + /** + * Register specific TypeScript node into map with first ESTree node provided + */ + registerTSNodeInNodeMap(node, result) { + if (result && + this.options.shouldPreserveNodeMaps && + !this.tsNodeToESTreeNodeMap.has(node)) { + this.tsNodeToESTreeNodeMap.set(node, result); + } + } +} +exports.Converter = Converter; diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/WatchCompilerHostOfConfigFile.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/WatchCompilerHostOfConfigFile.d.ts new file mode 100644 index 00000000..6e371059 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/WatchCompilerHostOfConfigFile.d.ts @@ -0,0 +1,13 @@ +import type * as ts from 'typescript'; +interface DirectoryStructureHost { + readDirectory?(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; +} +interface CachedDirectoryStructureHost extends DirectoryStructureHost { + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; +} +export interface WatchCompilerHostOfConfigFile extends ts.WatchCompilerHostOfConfigFile { + extraFileExtensions?: readonly ts.FileExtensionInfo[]; + onCachedDirectoryStructureHostCreate(host: CachedDirectoryStructureHost): void; +} +export {}; +//# sourceMappingURL=WatchCompilerHostOfConfigFile.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/WatchCompilerHostOfConfigFile.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/WatchCompilerHostOfConfigFile.d.ts.map new file mode 100644 index 00000000..41de9ea5 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/WatchCompilerHostOfConfigFile.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"WatchCompilerHostOfConfigFile.d.ts","sourceRoot":"","sources":["../../src/create-program/WatchCompilerHostOfConfigFile.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAGtC,UAAU,sBAAsB;IAC9B,aAAa,CAAC,CACZ,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,EAC9B,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,EAC3B,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,EAC3B,KAAK,CAAC,EAAE,MAAM,GACb,MAAM,EAAE,CAAC;CACb;AAGD,UAAU,4BAA6B,SAAQ,sBAAsB;IACnE,aAAa,CACX,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,EAC9B,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,EAC3B,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,EAC3B,KAAK,CAAC,EAAE,MAAM,GACb,MAAM,EAAE,CAAC;CACb;AAGD,MAAM,WAAW,6BAA6B,CAAC,CAAC,SAAS,EAAE,CAAC,cAAc,CACxE,SAAQ,EAAE,CAAC,6BAA6B,CAAC,CAAC,CAAC;IAC3C,mBAAmB,CAAC,EAAE,SAAS,EAAE,CAAC,iBAAiB,EAAE,CAAC;IACtD,oCAAoC,CAClC,IAAI,EAAE,4BAA4B,GACjC,IAAI,CAAC;CACT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/WatchCompilerHostOfConfigFile.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/WatchCompilerHostOfConfigFile.js new file mode 100644 index 00000000..3cbc8982 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/WatchCompilerHostOfConfigFile.js @@ -0,0 +1,5 @@ +"use strict"; +// These types are internal to TS. +// They have been trimmed down to only include the relevant bits +// We use some special internal TS apis to help us do our parsing flexibly +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createIsolatedProgram.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createIsolatedProgram.d.ts new file mode 100644 index 00000000..425fd1c5 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createIsolatedProgram.d.ts @@ -0,0 +1,7 @@ +import type { ParseSettings } from '../parseSettings'; +import type { ASTAndDefiniteProgram } from './shared'; +/** + * @returns Returns a new source file and program corresponding to the linted code + */ +export declare function createIsolatedProgram(parseSettings: ParseSettings): ASTAndDefiniteProgram; +//# sourceMappingURL=createIsolatedProgram.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createIsolatedProgram.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createIsolatedProgram.d.ts.map new file mode 100644 index 00000000..a642dd6c --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createIsolatedProgram.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"createIsolatedProgram.d.ts","sourceRoot":"","sources":["../../src/create-program/createIsolatedProgram.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAStD;;GAEG;AACH,wBAAgB,qBAAqB,CACnC,aAAa,EAAE,aAAa,GAC3B,qBAAqB,CAoEvB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createIsolatedProgram.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createIsolatedProgram.js new file mode 100644 index 00000000..85fb0b02 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createIsolatedProgram.js @@ -0,0 +1,96 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createIsolatedProgram = createIsolatedProgram; +const debug_1 = __importDefault(require("debug")); +const ts = __importStar(require("typescript")); +const getScriptKind_1 = require("./getScriptKind"); +const shared_1 = require("./shared"); +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:create-program:createIsolatedProgram'); +/** + * @returns Returns a new source file and program corresponding to the linted code + */ +function createIsolatedProgram(parseSettings) { + log('Getting isolated program in %s mode for: %s', parseSettings.jsx ? 'TSX' : 'TS', parseSettings.filePath); + const compilerHost = { + fileExists() { + return true; + }, + getCanonicalFileName() { + return parseSettings.filePath; + }, + getCurrentDirectory() { + return ''; + }, + getDefaultLibFileName() { + return 'lib.d.ts'; + }, + getDirectories() { + return []; + }, + // TODO: Support Windows CRLF + getNewLine() { + return '\n'; + }, + getSourceFile(filename) { + return ts.createSourceFile(filename, parseSettings.codeFullText, ts.ScriptTarget.Latest, + /* setParentNodes */ true, (0, getScriptKind_1.getScriptKind)(parseSettings.filePath, parseSettings.jsx)); + }, + readFile() { + return undefined; + }, + useCaseSensitiveFileNames() { + return true; + }, + writeFile() { + return null; + }, + }; + const program = ts.createProgram([parseSettings.filePath], { + jsDocParsingMode: parseSettings.jsDocParsingMode, + jsx: parseSettings.jsx ? ts.JsxEmit.Preserve : undefined, + noResolve: true, + target: ts.ScriptTarget.Latest, + ...(0, shared_1.createDefaultCompilerOptionsFromExtra)(parseSettings), + }, compilerHost); + const ast = program.getSourceFile(parseSettings.filePath); + if (!ast) { + throw new Error('Expected an ast to be returned for the single-file isolated program.'); + } + return { ast, program }; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgram.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgram.d.ts new file mode 100644 index 00000000..3e5f70aa --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgram.d.ts @@ -0,0 +1,9 @@ +import type * as ts from 'typescript'; +import type { ParseSettings } from '../parseSettings'; +import type { ASTAndDefiniteProgram } from './shared'; +/** + * @param parseSettings Internal settings for parsing the file + * @returns If found, the source file corresponding to the code and the containing program + */ +export declare function createProjectProgram(parseSettings: ParseSettings, programsForProjects: readonly ts.Program[]): ASTAndDefiniteProgram; +//# sourceMappingURL=createProjectProgram.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgram.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgram.d.ts.map new file mode 100644 index 00000000..3d03fa59 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgram.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"createProjectProgram.d.ts","sourceRoot":"","sources":["../../src/create-program/createProjectProgram.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAItC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAUtD;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,aAAa,EAAE,aAAa,EAC5B,mBAAmB,EAAE,SAAS,EAAE,CAAC,OAAO,EAAE,GACzC,qBAAqB,CAcvB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgram.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgram.js new file mode 100644 index 00000000..584e98b4 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgram.js @@ -0,0 +1,23 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createProjectProgram = createProjectProgram; +const debug_1 = __importDefault(require("debug")); +const node_utils_1 = require("../node-utils"); +const createProjectProgramError_1 = require("./createProjectProgramError"); +const shared_1 = require("./shared"); +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:create-program:createProjectProgram'); +/** + * @param parseSettings Internal settings for parsing the file + * @returns If found, the source file corresponding to the code and the containing program + */ +function createProjectProgram(parseSettings, programsForProjects) { + log('Creating project program for: %s', parseSettings.filePath); + const astAndProgram = (0, node_utils_1.firstDefined)(programsForProjects, currentProgram => (0, shared_1.getAstFromProgram)(currentProgram, parseSettings.filePath)); + if (!astAndProgram) { + throw new Error((0, createProjectProgramError_1.createProjectProgramError)(parseSettings, programsForProjects).join('\n')); + } + return astAndProgram; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgramError.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgramError.d.ts new file mode 100644 index 00000000..18dc8c07 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgramError.d.ts @@ -0,0 +1,4 @@ +import type * as ts from 'typescript'; +import type { ParseSettings } from '../parseSettings'; +export declare function createProjectProgramError(parseSettings: ParseSettings, programsForProjects: readonly ts.Program[]): string[]; +//# sourceMappingURL=createProjectProgramError.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgramError.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgramError.d.ts.map new file mode 100644 index 00000000..104141e9 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgramError.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"createProjectProgramError.d.ts","sourceRoot":"","sources":["../../src/create-program/createProjectProgramError.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAItC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAKtD,wBAAgB,yBAAyB,CACvC,aAAa,EAAE,aAAa,EAC5B,mBAAmB,EAAE,SAAS,EAAE,CAAC,OAAO,EAAE,GACzC,MAAM,EAAE,CAUV"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgramError.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgramError.js new file mode 100644 index 00000000..f8e60990 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createProjectProgramError.js @@ -0,0 +1,74 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createProjectProgramError = createProjectProgramError; +const node_path_1 = __importDefault(require("node:path")); +const describeFilePath_1 = require("./describeFilePath"); +const shared_1 = require("./shared"); +function createProjectProgramError(parseSettings, programsForProjects) { + const describedFilePath = (0, describeFilePath_1.describeFilePath)(parseSettings.filePath, parseSettings.tsconfigRootDir); + return [ + getErrorStart(describedFilePath, parseSettings), + ...getErrorDetails(describedFilePath, parseSettings, programsForProjects), + ]; +} +function getErrorStart(describedFilePath, parseSettings) { + const relativeProjects = [...parseSettings.projects.values()].map(projectFile => (0, describeFilePath_1.describeFilePath)(projectFile, parseSettings.tsconfigRootDir)); + const describedPrograms = relativeProjects.length === 1 + ? ` ${relativeProjects[0]}` + : `\n${relativeProjects.map(project => `- ${project}`).join('\n')}`; + return `ESLint was configured to run on \`${describedFilePath}\` using \`parserOptions.project\`:${describedPrograms}`; +} +function getErrorDetails(describedFilePath, parseSettings, programsForProjects) { + if (programsForProjects.length === 1 && + programsForProjects[0].getProjectReferences()?.length) { + return [ + `That TSConfig uses project "references" and doesn't include \`${describedFilePath}\` directly, which is not supported by \`parserOptions.project\`.`, + `Either:`, + `- Switch to \`parserOptions.projectService\``, + `- Use an ESLint-specific TSConfig`, + `See the typescript-eslint docs for more info: https://typescript-eslint.io/troubleshooting/typed-linting#are-typescript-project-references-supported`, + ]; + } + const { extraFileExtensions } = parseSettings; + const details = []; + for (const extraExtension of extraFileExtensions) { + if (!extraExtension.startsWith('.')) { + details.push(`Found unexpected extension \`${extraExtension}\` specified with the \`parserOptions.extraFileExtensions\` option. Did you mean \`.${extraExtension}\`?`); + } + if (shared_1.DEFAULT_EXTRA_FILE_EXTENSIONS.has(extraExtension)) { + details.push(`You unnecessarily included the extension \`${extraExtension}\` with the \`parserOptions.extraFileExtensions\` option. This extension is already handled by the parser by default.`); + } + } + const fileExtension = node_path_1.default.extname(parseSettings.filePath); + if (!shared_1.DEFAULT_EXTRA_FILE_EXTENSIONS.has(fileExtension)) { + const nonStandardExt = `The extension for the file (\`${fileExtension}\`) is non-standard`; + if (extraFileExtensions.length > 0) { + if (!extraFileExtensions.includes(fileExtension)) { + return [ + ...details, + `${nonStandardExt}. It should be added to your existing \`parserOptions.extraFileExtensions\`.`, + ]; + } + } + else { + return [ + ...details, + `${nonStandardExt}. You should add \`parserOptions.extraFileExtensions\` to your config.`, + ]; + } + } + const [describedInclusions, describedSpecifiers] = parseSettings.projects.size === 1 + ? ['that TSConfig does not', 'that TSConfig'] + : ['none of those TSConfigs', 'one of those TSConfigs']; + return [ + ...details, + `However, ${describedInclusions} include this file. Either:`, + `- Change ESLint's list of included files to not include this file`, + `- Change ${describedSpecifiers} to include this file`, + `- Create a new TSConfig that includes this file and include it in your parserOptions.project`, + `See the typescript-eslint docs for more info: https://typescript-eslint.io/troubleshooting/typed-linting#i-get-errors-telling-me-eslint-was-configured-to-run--however-that-tsconfig-does-not--none-of-those-tsconfigs-include-this-file`, + ]; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createSourceFile.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createSourceFile.d.ts new file mode 100644 index 00000000..858038d5 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createSourceFile.d.ts @@ -0,0 +1,6 @@ +import * as ts from 'typescript'; +import type { ParseSettings } from '../parseSettings'; +import type { ASTAndNoProgram } from './shared'; +export declare function createSourceFile(parseSettings: ParseSettings): ts.SourceFile; +export declare function createNoProgram(parseSettings: ParseSettings): ASTAndNoProgram; +//# sourceMappingURL=createSourceFile.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createSourceFile.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createSourceFile.d.ts.map new file mode 100644 index 00000000..781e0867 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createSourceFile.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"createSourceFile.d.ts","sourceRoot":"","sources":["../../src/create-program/createSourceFile.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAShD,wBAAgB,gBAAgB,CAAC,aAAa,EAAE,aAAa,GAAG,EAAE,CAAC,UAAU,CAoB5E;AAED,wBAAgB,eAAe,CAAC,aAAa,EAAE,aAAa,GAAG,eAAe,CAK7E"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createSourceFile.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createSourceFile.js new file mode 100644 index 00000000..2ec86469 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/createSourceFile.js @@ -0,0 +1,62 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createSourceFile = createSourceFile; +exports.createNoProgram = createNoProgram; +const debug_1 = __importDefault(require("debug")); +const ts = __importStar(require("typescript")); +const source_files_1 = require("../source-files"); +const getScriptKind_1 = require("./getScriptKind"); +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:create-program:createSourceFile'); +function createSourceFile(parseSettings) { + log('Getting AST without type information in %s mode for: %s', parseSettings.jsx ? 'TSX' : 'TS', parseSettings.filePath); + return (0, source_files_1.isSourceFile)(parseSettings.code) + ? parseSettings.code + : ts.createSourceFile(parseSettings.filePath, parseSettings.codeFullText, { + jsDocParsingMode: parseSettings.jsDocParsingMode, + languageVersion: ts.ScriptTarget.Latest, + setExternalModuleIndicator: parseSettings.setExternalModuleIndicator, + }, + /* setParentNodes */ true, (0, getScriptKind_1.getScriptKind)(parseSettings.filePath, parseSettings.jsx)); +} +function createNoProgram(parseSettings) { + return { + ast: createSourceFile(parseSettings), + program: null, + }; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/describeFilePath.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/describeFilePath.d.ts new file mode 100644 index 00000000..d46f86aa --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/describeFilePath.d.ts @@ -0,0 +1,2 @@ +export declare function describeFilePath(filePath: string, tsconfigRootDir: string): string; +//# sourceMappingURL=describeFilePath.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/describeFilePath.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/describeFilePath.d.ts.map new file mode 100644 index 00000000..6d049bed --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/describeFilePath.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"describeFilePath.d.ts","sourceRoot":"","sources":["../../src/create-program/describeFilePath.ts"],"names":[],"mappings":"AAEA,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,MAAM,EAChB,eAAe,EAAE,MAAM,GACtB,MAAM,CAyBR"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/describeFilePath.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/describeFilePath.js new file mode 100644 index 00000000..f84ab502 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/describeFilePath.js @@ -0,0 +1,30 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.describeFilePath = describeFilePath; +const node_path_1 = __importDefault(require("node:path")); +function describeFilePath(filePath, tsconfigRootDir) { + // If the TSConfig root dir is a parent of the filePath, use + // `` as a prefix for the path. + const relative = node_path_1.default.relative(tsconfigRootDir, filePath); + if (relative && !relative.startsWith('..') && !node_path_1.default.isAbsolute(relative)) { + return `/${relative}`; + } + // Root-like Mac/Linux (~/*, ~*) or Windows (C:/*, /) paths that aren't + // relative to the TSConfig root dir should be fully described. + // This avoids strings like /../../../../repo/file.ts. + // https://github.com/typescript-eslint/typescript-eslint/issues/6289 + if (/^[(\w+:)\\/~]/.test(filePath)) { + return filePath; + } + // Similarly, if the relative path would contain a lot of ../.., then + // ignore it and print the file path directly. + if (/\.\.[/\\]\.\./.test(relative)) { + return filePath; + } + // Lastly, since we've eliminated all special cases, we know the cleanest + // path to print is probably the prefixed relative one. + return `/${relative}`; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.d.ts new file mode 100644 index 00000000..0142b474 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.d.ts @@ -0,0 +1,4 @@ +import * as ts from 'typescript'; +export declare function getScriptKind(filePath: string, jsx: boolean): ts.ScriptKind; +export declare function getLanguageVariant(scriptKind: ts.ScriptKind): ts.LanguageVariant; +//# sourceMappingURL=getScriptKind.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.d.ts.map new file mode 100644 index 00000000..787037cf --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getScriptKind.d.ts","sourceRoot":"","sources":["../../src/create-program/getScriptKind.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,EAAE,CAAC,UAAU,CA8B3E;AAED,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,EAAE,CAAC,UAAU,GACxB,EAAE,CAAC,eAAe,CAYpB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.js new file mode 100644 index 00000000..6c948b5b --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.js @@ -0,0 +1,80 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getScriptKind = getScriptKind; +exports.getLanguageVariant = getLanguageVariant; +const node_path_1 = __importDefault(require("node:path")); +const ts = __importStar(require("typescript")); +function getScriptKind(filePath, jsx) { + const extension = node_path_1.default.extname(filePath).toLowerCase(); + // note - we only respect the user's jsx setting for unknown extensions + // this is so that we always match TS's internal script kind logic, preventing + // weird errors due to a mismatch. + // https://github.com/microsoft/TypeScript/blob/da00ba67ed1182ad334f7c713b8254fba174aeba/src/compiler/utilities.ts#L6948-L6968 + switch (extension) { + case ts.Extension.Cjs: + case ts.Extension.Js: + case ts.Extension.Mjs: + return ts.ScriptKind.JS; + case ts.Extension.Cts: + case ts.Extension.Mts: + case ts.Extension.Ts: + return ts.ScriptKind.TS; + case ts.Extension.Json: + return ts.ScriptKind.JSON; + case ts.Extension.Jsx: + return ts.ScriptKind.JSX; + case ts.Extension.Tsx: + return ts.ScriptKind.TSX; + default: + // unknown extension, force typescript to ignore the file extension, and respect the user's setting + return jsx ? ts.ScriptKind.TSX : ts.ScriptKind.TS; + } +} +function getLanguageVariant(scriptKind) { + // https://github.com/microsoft/TypeScript/blob/d6e483b8dabd8fd37c00954c3f2184bb7f1eb90c/src/compiler/utilities.ts#L6281-L6285 + switch (scriptKind) { + case ts.ScriptKind.JS: + case ts.ScriptKind.JSON: + case ts.ScriptKind.JSX: + case ts.ScriptKind.TSX: + return ts.LanguageVariant.JSX; + default: + return ts.LanguageVariant.Standard; + } +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getWatchProgramsForProjects.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getWatchProgramsForProjects.d.ts new file mode 100644 index 00000000..f79e898f --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getWatchProgramsForProjects.d.ts @@ -0,0 +1,14 @@ +import * as ts from 'typescript'; +import type { ParseSettings } from '../parseSettings'; +/** + * Clear all of the parser caches. + * This should only be used in testing to ensure the parser is clean between tests. + */ +export declare function clearWatchCaches(): void; +/** + * Calculate project environments using options provided by consumer and paths from config + * @param parseSettings Internal settings for parsing the file + * @returns The programs corresponding to the supplied tsconfig paths + */ +export declare function getWatchProgramsForProjects(parseSettings: ParseSettings): ts.Program[]; +//# sourceMappingURL=getWatchProgramsForProjects.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getWatchProgramsForProjects.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getWatchProgramsForProjects.d.ts.map new file mode 100644 index 00000000..a3eae899 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getWatchProgramsForProjects.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getWatchProgramsForProjects.d.ts","sourceRoot":"","sources":["../../src/create-program/getWatchProgramsForProjects.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAiDtD;;;GAGG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAOvC;AA4DD;;;;GAIG;AACH,wBAAgB,2BAA2B,CACzC,aAAa,EAAE,aAAa,GAC3B,EAAE,CAAC,OAAO,EAAE,CA8Gd"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getWatchProgramsForProjects.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getWatchProgramsForProjects.js new file mode 100644 index 00000000..1979990e --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/getWatchProgramsForProjects.js @@ -0,0 +1,380 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.clearWatchCaches = clearWatchCaches; +exports.getWatchProgramsForProjects = getWatchProgramsForProjects; +const debug_1 = __importDefault(require("debug")); +const node_fs_1 = __importDefault(require("node:fs")); +const ts = __importStar(require("typescript")); +const source_files_1 = require("../source-files"); +const shared_1 = require("./shared"); +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:create-program:getWatchProgramsForProjects'); +/** + * Maps tsconfig paths to their corresponding file contents and resulting watches + */ +const knownWatchProgramMap = new Map(); +/** + * Maps file/folder paths to their set of corresponding watch callbacks + * There may be more than one per file/folder if a file/folder is shared between projects + */ +const fileWatchCallbackTrackingMap = new Map(); +const folderWatchCallbackTrackingMap = new Map(); +/** + * Stores the list of known files for each program + */ +const programFileListCache = new Map(); +/** + * Caches the last modified time of the tsconfig files + */ +const tsconfigLastModifiedTimestampCache = new Map(); +const parsedFilesSeenHash = new Map(); +/** + * Clear all of the parser caches. + * This should only be used in testing to ensure the parser is clean between tests. + */ +function clearWatchCaches() { + knownWatchProgramMap.clear(); + fileWatchCallbackTrackingMap.clear(); + folderWatchCallbackTrackingMap.clear(); + parsedFilesSeenHash.clear(); + programFileListCache.clear(); + tsconfigLastModifiedTimestampCache.clear(); +} +function saveWatchCallback(trackingMap) { + return (fileName, callback) => { + const normalizedFileName = (0, shared_1.getCanonicalFileName)(fileName); + const watchers = (() => { + let watchers = trackingMap.get(normalizedFileName); + if (!watchers) { + watchers = new Set(); + trackingMap.set(normalizedFileName, watchers); + } + return watchers; + })(); + watchers.add(callback); + return { + close: () => { + watchers.delete(callback); + }, + }; + }; +} +/** + * Holds information about the file currently being linted + */ +const currentLintOperationState = { + code: '', + filePath: '', +}; +/** + * Appropriately report issues found when reading a config file + * @param diagnostic The diagnostic raised when creating a program + */ +function diagnosticReporter(diagnostic) { + throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine)); +} +function updateCachedFileList(tsconfigPath, program) { + const fileList = new Set(program.getRootFileNames().map(f => (0, shared_1.getCanonicalFileName)(f))); + programFileListCache.set(tsconfigPath, fileList); + return fileList; +} +/** + * Calculate project environments using options provided by consumer and paths from config + * @param parseSettings Internal settings for parsing the file + * @returns The programs corresponding to the supplied tsconfig paths + */ +function getWatchProgramsForProjects(parseSettings) { + const filePath = (0, shared_1.getCanonicalFileName)(parseSettings.filePath); + const results = []; + // preserve reference to code and file being linted + currentLintOperationState.code = parseSettings.code; + currentLintOperationState.filePath = filePath; + // Update file version if necessary + const fileWatchCallbacks = fileWatchCallbackTrackingMap.get(filePath); + const codeHash = (0, shared_1.createHash)((0, source_files_1.getCodeText)(parseSettings.code)); + if (parsedFilesSeenHash.get(filePath) !== codeHash && + fileWatchCallbacks && + fileWatchCallbacks.size > 0) { + fileWatchCallbacks.forEach(cb => cb(filePath, ts.FileWatcherEventKind.Changed)); + } + const currentProjectsFromSettings = new Map(parseSettings.projects); + /* + * before we go into the process of attempting to find and update every program + * see if we know of a program that contains this file + */ + for (const [tsconfigPath, existingWatch] of knownWatchProgramMap.entries()) { + if (!currentProjectsFromSettings.has(tsconfigPath)) { + // the current parser run doesn't specify this tsconfig in parserOptions.project + // so we don't want to consider it for caching purposes. + // + // if we did consider it we might return a program for a project + // that wasn't specified in the current parser run (which is obv bad!). + continue; + } + let fileList = programFileListCache.get(tsconfigPath); + let updatedProgram = null; + if (!fileList) { + updatedProgram = existingWatch.getProgram().getProgram(); + fileList = updateCachedFileList(tsconfigPath, updatedProgram); + } + if (fileList.has(filePath)) { + log('Found existing program for file. %s', filePath); + updatedProgram ??= existingWatch.getProgram().getProgram(); + // sets parent pointers in source files + updatedProgram.getTypeChecker(); + return [updatedProgram]; + } + } + log('File did not belong to any existing programs, moving to create/update. %s', filePath); + /* + * We don't know of a program that contains the file, this means that either: + * - the required program hasn't been created yet, or + * - the file is new/renamed, and the program hasn't been updated. + */ + for (const tsconfigPath of parseSettings.projects) { + const existingWatch = knownWatchProgramMap.get(tsconfigPath[0]); + if (existingWatch) { + const updatedProgram = maybeInvalidateProgram(existingWatch, filePath, tsconfigPath[0]); + if (!updatedProgram) { + continue; + } + // sets parent pointers in source files + updatedProgram.getTypeChecker(); + // cache and check the file list + const fileList = updateCachedFileList(tsconfigPath[0], updatedProgram); + if (fileList.has(filePath)) { + log('Found updated program for file. %s', filePath); + // we can return early because we know this program contains the file + return [updatedProgram]; + } + results.push(updatedProgram); + continue; + } + const programWatch = createWatchProgram(tsconfigPath[1], parseSettings); + knownWatchProgramMap.set(tsconfigPath[0], programWatch); + const program = programWatch.getProgram().getProgram(); + // sets parent pointers in source files + program.getTypeChecker(); + // cache and check the file list + const fileList = updateCachedFileList(tsconfigPath[0], program); + if (fileList.has(filePath)) { + log('Found program for file. %s', filePath); + // we can return early because we know this program contains the file + return [program]; + } + results.push(program); + } + return results; +} +function createWatchProgram(tsconfigPath, parseSettings) { + log('Creating watch program for %s.', tsconfigPath); + // create compiler host + const watchCompilerHost = ts.createWatchCompilerHost(tsconfigPath, (0, shared_1.createDefaultCompilerOptionsFromExtra)(parseSettings), ts.sys, ts.createAbstractBuilder, diagnosticReporter, + // TODO: file issue on TypeScript to suggest making optional? + // eslint-disable-next-line @typescript-eslint/no-empty-function + /*reportWatchStatus*/ () => { }); + watchCompilerHost.jsDocParsingMode = parseSettings.jsDocParsingMode; + // ensure readFile reads the code being linted instead of the copy on disk + const oldReadFile = watchCompilerHost.readFile; + watchCompilerHost.readFile = (filePathIn, encoding) => { + const filePath = (0, shared_1.getCanonicalFileName)(filePathIn); + const fileContent = filePath === currentLintOperationState.filePath + ? (0, source_files_1.getCodeText)(currentLintOperationState.code) + : oldReadFile(filePath, encoding); + if (fileContent != null) { + parsedFilesSeenHash.set(filePath, (0, shared_1.createHash)(fileContent)); + } + return fileContent; + }; + // ensure process reports error on failure instead of exiting process immediately + watchCompilerHost.onUnRecoverableConfigFileDiagnostic = diagnosticReporter; + // ensure process doesn't emit programs + watchCompilerHost.afterProgramCreate = (program) => { + // report error if there are any errors in the config file + const configFileDiagnostics = program + .getConfigFileParsingDiagnostics() + .filter(diag => diag.category === ts.DiagnosticCategory.Error && diag.code !== 18003); + if (configFileDiagnostics.length > 0) { + diagnosticReporter(configFileDiagnostics[0]); + } + }; + /* + * From the CLI, the file watchers won't matter, as the files will be parsed once and then forgotten. + * When running from an IDE, these watchers will let us tell typescript about changes. + * + * ESLint IDE plugins will send us unfinished file content as the user types (before it's saved to disk). + * We use the file watchers to tell typescript about this latest file content. + * + * When files are created (or renamed), we won't know about them because we have no filesystem watchers attached. + * We use the folder watchers to tell typescript it needs to go and find new files in the project folders. + */ + watchCompilerHost.watchFile = saveWatchCallback(fileWatchCallbackTrackingMap); + watchCompilerHost.watchDirectory = saveWatchCallback(folderWatchCallbackTrackingMap); + // allow files with custom extensions to be included in program (uses internal ts api) + const oldOnDirectoryStructureHostCreate = watchCompilerHost.onCachedDirectoryStructureHostCreate; + watchCompilerHost.onCachedDirectoryStructureHostCreate = (host) => { + const oldReadDirectory = host.readDirectory; + host.readDirectory = (path, extensions, exclude, include, depth) => oldReadDirectory(path, !extensions + ? undefined + : [...extensions, ...parseSettings.extraFileExtensions], exclude, include, depth); + oldOnDirectoryStructureHostCreate(host); + }; + // This works only on 3.9 + watchCompilerHost.extraFileExtensions = parseSettings.extraFileExtensions.map(extension => ({ + extension, + isMixedContent: true, + scriptKind: ts.ScriptKind.Deferred, + })); + watchCompilerHost.trace = log; + // Since we don't want to asynchronously update program we want to disable timeout methods + // So any changes in the program will be delayed and updated when getProgram is called on watch + watchCompilerHost.setTimeout = undefined; + watchCompilerHost.clearTimeout = undefined; + return ts.createWatchProgram(watchCompilerHost); +} +function hasTSConfigChanged(tsconfigPath) { + const stat = node_fs_1.default.statSync(tsconfigPath); + const lastModifiedAt = stat.mtimeMs; + const cachedLastModifiedAt = tsconfigLastModifiedTimestampCache.get(tsconfigPath); + tsconfigLastModifiedTimestampCache.set(tsconfigPath, lastModifiedAt); + if (cachedLastModifiedAt == null) { + return false; + } + return Math.abs(cachedLastModifiedAt - lastModifiedAt) > Number.EPSILON; +} +function maybeInvalidateProgram(existingWatch, filePath, tsconfigPath) { + /* + * By calling watchProgram.getProgram(), it will trigger a resync of the program based on + * whatever new file content we've given it from our input. + */ + let updatedProgram = existingWatch.getProgram().getProgram(); + // In case this change causes problems in larger real world codebases + // Provide an escape hatch so people don't _have_ to revert to an older version + if (process.env.TSESTREE_NO_INVALIDATION === 'true') { + return updatedProgram; + } + if (hasTSConfigChanged(tsconfigPath)) { + /* + * If the stat of the tsconfig has changed, that could mean the include/exclude/files lists has changed + * We need to make sure typescript knows this so it can update appropriately + */ + log('tsconfig has changed - triggering program update. %s', tsconfigPath); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + fileWatchCallbackTrackingMap + .get(tsconfigPath) + .forEach(cb => cb(tsconfigPath, ts.FileWatcherEventKind.Changed)); + // tsconfig change means that the file list more than likely changed, so clear the cache + programFileListCache.delete(tsconfigPath); + } + let sourceFile = updatedProgram.getSourceFile(filePath); + if (sourceFile) { + return updatedProgram; + } + /* + * Missing source file means our program's folder structure might be out of date. + * So we need to tell typescript it needs to update the correct folder. + */ + log('File was not found in program - triggering folder update. %s', filePath); + // Find the correct directory callback by climbing the folder tree + const currentDir = (0, shared_1.canonicalDirname)(filePath); + let current = null; + let next = currentDir; + let hasCallback = false; + while (current !== next) { + current = next; + const folderWatchCallbacks = folderWatchCallbackTrackingMap.get(current); + if (folderWatchCallbacks) { + for (const cb of folderWatchCallbacks) { + if (currentDir !== current) { + cb(currentDir, ts.FileWatcherEventKind.Changed); + } + cb(current, ts.FileWatcherEventKind.Changed); + } + hasCallback = true; + } + next = (0, shared_1.canonicalDirname)(current); + } + if (!hasCallback) { + /* + * No callback means the paths don't matchup - so no point returning any program + * this will signal to the caller to skip this program + */ + log('No callback found for file, not part of this program. %s', filePath); + return null; + } + // directory update means that the file list more than likely changed, so clear the cache + programFileListCache.delete(tsconfigPath); + // force the immediate resync + updatedProgram = existingWatch.getProgram().getProgram(); + sourceFile = updatedProgram.getSourceFile(filePath); + if (sourceFile) { + return updatedProgram; + } + /* + * At this point we're in one of two states: + * - The file isn't supposed to be in this program due to exclusions + * - The file is new, and was renamed from an old, included filename + * + * For the latter case, we need to tell typescript that the old filename is now deleted + */ + log('File was still not found in program after directory update - checking file deletions. %s', filePath); + const rootFilenames = updatedProgram.getRootFileNames(); + // use find because we only need to "delete" one file to cause typescript to do a full resync + const deletedFile = rootFilenames.find(file => !node_fs_1.default.existsSync(file)); + if (!deletedFile) { + // There are no deleted files, so it must be the former case of the file not belonging to this program + return null; + } + const fileWatchCallbacks = fileWatchCallbackTrackingMap.get((0, shared_1.getCanonicalFileName)(deletedFile)); + if (!fileWatchCallbacks) { + // shouldn't happen, but just in case + log('Could not find watch callbacks for root file. %s', deletedFile); + return updatedProgram; + } + log('Marking file as deleted. %s', deletedFile); + fileWatchCallbacks.forEach(cb => cb(deletedFile, ts.FileWatcherEventKind.Deleted)); + // deleted files means that the file list _has_ changed, so clear the cache + programFileListCache.delete(tsconfigPath); + updatedProgram = existingWatch.getProgram().getProgram(); + sourceFile = updatedProgram.getSourceFile(filePath); + if (sourceFile) { + return updatedProgram; + } + log('File was still not found in program after deletion check, assuming it is not part of this program. %s', filePath); + return null; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/shared.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/shared.d.ts new file mode 100644 index 00000000..e48057e0 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/shared.d.ts @@ -0,0 +1,28 @@ +import type { Program } from 'typescript'; +import * as ts from 'typescript'; +import type { ParseSettings } from '../parseSettings'; +export interface ASTAndNoProgram { + ast: ts.SourceFile; + program: null; +} +export interface ASTAndDefiniteProgram { + ast: ts.SourceFile; + program: ts.Program; +} +export type ASTAndProgram = ASTAndDefiniteProgram | ASTAndNoProgram; +export declare const DEFAULT_EXTRA_FILE_EXTENSIONS: Set; +export declare function createDefaultCompilerOptionsFromExtra(parseSettings: ParseSettings): ts.CompilerOptions; +export type CanonicalPath = { + __brand: unknown; +} & string; +export declare function getCanonicalFileName(filePath: string): CanonicalPath; +export declare function ensureAbsolutePath(p: string, tsconfigRootDir: string): string; +export declare function canonicalDirname(p: CanonicalPath): CanonicalPath; +export declare function getAstFromProgram(currentProgram: Program, filePath: string): ASTAndDefiniteProgram | undefined; +/** + * Hash content for compare content. + * @param content hashed contend + * @returns hashed result + */ +export declare function createHash(content: string): string; +//# sourceMappingURL=shared.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/shared.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/shared.d.ts.map new file mode 100644 index 00000000..5e631057 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/shared.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/create-program/shared.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAI1C,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC;IACnB,OAAO,EAAE,IAAI,CAAC;CACf;AACD,MAAM,WAAW,qBAAqB;IACpC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC;IACnB,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC;CACrB;AACD,MAAM,MAAM,aAAa,GAAG,qBAAqB,GAAG,eAAe,CAAC;AAYpE,eAAO,MAAM,6BAA6B,aASxC,CAAC;AAEH,wBAAgB,qCAAqC,CACnD,aAAa,EAAE,aAAa,GAC3B,EAAE,CAAC,eAAe,CASpB;AAGD,MAAM,MAAM,aAAa,GAAG;IAAE,OAAO,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,CAAC;AAU1D,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,aAAa,CAMpE;AAED,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,MAAM,CAI7E;AAED,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,aAAa,GAAG,aAAa,CAEhE;AAmBD,wBAAgB,iBAAiB,CAC/B,cAAc,EAAE,OAAO,EACvB,QAAQ,EAAE,MAAM,GACf,qBAAqB,GAAG,SAAS,CAWnC;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAOlD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/shared.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/shared.js new file mode 100644 index 00000000..6b4b122c --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/shared.js @@ -0,0 +1,132 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_EXTRA_FILE_EXTENSIONS = void 0; +exports.createDefaultCompilerOptionsFromExtra = createDefaultCompilerOptionsFromExtra; +exports.getCanonicalFileName = getCanonicalFileName; +exports.ensureAbsolutePath = ensureAbsolutePath; +exports.canonicalDirname = canonicalDirname; +exports.getAstFromProgram = getAstFromProgram; +exports.createHash = createHash; +const tsconfig_utils_1 = require("@typescript-eslint/tsconfig-utils"); +const node_path_1 = __importDefault(require("node:path")); +const ts = __importStar(require("typescript")); +/** + * Default compiler options for program generation + */ +const DEFAULT_COMPILER_OPTIONS = { + ...tsconfig_utils_1.CORE_COMPILER_OPTIONS, + allowJs: true, + allowNonTsExtensions: true, + checkJs: true, +}; +exports.DEFAULT_EXTRA_FILE_EXTENSIONS = new Set([ + ts.Extension.Cjs, + ts.Extension.Cts, + ts.Extension.Js, + ts.Extension.Jsx, + ts.Extension.Mjs, + ts.Extension.Mts, + ts.Extension.Ts, + ts.Extension.Tsx, +]); +function createDefaultCompilerOptionsFromExtra(parseSettings) { + if (parseSettings.debugLevel.has('typescript')) { + return { + ...DEFAULT_COMPILER_OPTIONS, + extendedDiagnostics: true, + }; + } + return DEFAULT_COMPILER_OPTIONS; +} +// typescript doesn't provide a ts.sys implementation for browser environments +const useCaseSensitiveFileNames = +// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/internal/eqeq-nullish +ts.sys !== undefined ? ts.sys.useCaseSensitiveFileNames : true; +const correctPathCasing = useCaseSensitiveFileNames + ? (filePath) => filePath + : (filePath) => filePath.toLowerCase(); +function getCanonicalFileName(filePath) { + let normalized = node_path_1.default.normalize(filePath); + if (normalized.endsWith(node_path_1.default.sep)) { + normalized = normalized.slice(0, -1); + } + return correctPathCasing(normalized); +} +function ensureAbsolutePath(p, tsconfigRootDir) { + return node_path_1.default.isAbsolute(p) + ? p + : node_path_1.default.join(tsconfigRootDir || process.cwd(), p); +} +function canonicalDirname(p) { + return node_path_1.default.dirname(p); +} +const DEFINITION_EXTENSIONS = [ + ts.Extension.Dts, + ts.Extension.Dcts, + ts.Extension.Dmts, +]; +function getExtension(fileName) { + if (!fileName) { + return null; + } + return (DEFINITION_EXTENSIONS.find(definitionExt => fileName.endsWith(definitionExt)) ?? node_path_1.default.extname(fileName)); +} +function getAstFromProgram(currentProgram, filePath) { + const ast = currentProgram.getSourceFile(filePath); + // working around https://github.com/typescript-eslint/typescript-eslint/issues/1573 + const expectedExt = getExtension(filePath); + const returnedExt = getExtension(ast?.fileName); + if (expectedExt !== returnedExt) { + return undefined; + } + return ast && { ast, program: currentProgram }; +} +/** + * Hash content for compare content. + * @param content hashed contend + * @returns hashed result + */ +function createHash(content) { + // No ts.sys in browser environments. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (ts.sys?.createHash) { + return ts.sys.createHash(content); + } + return content; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/useProvidedPrograms.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/useProvidedPrograms.d.ts new file mode 100644 index 00000000..e8eb86ae --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/useProvidedPrograms.d.ts @@ -0,0 +1,12 @@ +import * as ts from 'typescript'; +import type { ParseSettings } from '../parseSettings'; +import type { ASTAndDefiniteProgram } from './shared'; +export declare function useProvidedPrograms(programInstances: Iterable, parseSettings: ParseSettings): ASTAndDefiniteProgram | undefined; +/** + * Utility offered by parser to help consumers construct their own program instance. + * + * @param configFile the path to the tsconfig.json file, relative to `projectDirectory` + * @param projectDirectory the project directory to use as the CWD, defaults to `process.cwd()` + */ +export declare function createProgramFromConfigFile(configFile: string, projectDirectory?: string): ts.Program; +//# sourceMappingURL=useProvidedPrograms.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/useProvidedPrograms.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/useProvidedPrograms.d.ts.map new file mode 100644 index 00000000..fac88ec3 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/useProvidedPrograms.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"useProvidedPrograms.d.ts","sourceRoot":"","sources":["../../src/create-program/useProvidedPrograms.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAQtD,wBAAgB,mBAAmB,CACjC,gBAAgB,EAAE,QAAQ,CAAC,EAAE,CAAC,OAAO,CAAC,EACtC,aAAa,EAAE,aAAa,GAC3B,qBAAqB,GAAG,SAAS,CAoCnC;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CACzC,UAAU,EAAE,MAAM,EAClB,gBAAgB,CAAC,EAAE,MAAM,GACxB,EAAE,CAAC,OAAO,CAIZ"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/useProvidedPrograms.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/useProvidedPrograms.js new file mode 100644 index 00000000..7369ed9e --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/useProvidedPrograms.js @@ -0,0 +1,81 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useProvidedPrograms = useProvidedPrograms; +exports.createProgramFromConfigFile = createProgramFromConfigFile; +const tsconfig_utils_1 = require("@typescript-eslint/tsconfig-utils"); +const debug_1 = __importDefault(require("debug")); +const path = __importStar(require("node:path")); +const ts = __importStar(require("typescript")); +const shared_1 = require("./shared"); +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:create-program:useProvidedPrograms'); +function useProvidedPrograms(programInstances, parseSettings) { + log('Retrieving ast for %s from provided program instance(s)', parseSettings.filePath); + let astAndProgram; + for (const programInstance of programInstances) { + astAndProgram = (0, shared_1.getAstFromProgram)(programInstance, parseSettings.filePath); + // Stop at the first applicable program instance + if (astAndProgram) { + break; + } + } + if (astAndProgram) { + astAndProgram.program.getTypeChecker(); // ensure parent pointers are set in source files + return astAndProgram; + } + const relativeFilePath = path.relative(parseSettings.tsconfigRootDir, parseSettings.filePath); + const [typeSource, typeSources] = parseSettings.projects.size > 0 + ? ['project', 'project(s)'] + : ['programs', 'program instance(s)']; + const errorLines = [ + `"parserOptions.${typeSource}" has been provided for @typescript-eslint/parser.`, + `The file was not found in any of the provided ${typeSources}: ${relativeFilePath}`, + ]; + throw new Error(errorLines.join('\n')); +} +/** + * Utility offered by parser to help consumers construct their own program instance. + * + * @param configFile the path to the tsconfig.json file, relative to `projectDirectory` + * @param projectDirectory the project directory to use as the CWD, defaults to `process.cwd()` + */ +function createProgramFromConfigFile(configFile, projectDirectory) { + const parsed = (0, tsconfig_utils_1.getParsedConfigFile)(ts, configFile, projectDirectory); + const host = ts.createCompilerHost(parsed.options, true); + return ts.createProgram(parsed.fileNames, parsed.options, host); +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/validateDefaultProjectForFilesGlob.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/validateDefaultProjectForFilesGlob.d.ts new file mode 100644 index 00000000..cd36c54f --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/validateDefaultProjectForFilesGlob.d.ts @@ -0,0 +1,3 @@ +export declare const DEFAULT_PROJECT_FILES_ERROR_EXPLANATION = "\n\nHaving many files run with the default project is known to cause performance issues and slow down linting.\n\nSee https://typescript-eslint.io/troubleshooting/typed-linting#allowdefaultproject-glob-too-wide\n"; +export declare function validateDefaultProjectForFilesGlob(allowDefaultProject: string[] | undefined): void; +//# sourceMappingURL=validateDefaultProjectForFilesGlob.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/validateDefaultProjectForFilesGlob.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/validateDefaultProjectForFilesGlob.d.ts.map new file mode 100644 index 00000000..18df39ca --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/validateDefaultProjectForFilesGlob.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"validateDefaultProjectForFilesGlob.d.ts","sourceRoot":"","sources":["../../src/create-program/validateDefaultProjectForFilesGlob.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,uCAAuC,yNAKnD,CAAC;AAEF,wBAAgB,kCAAkC,CAChD,mBAAmB,EAAE,MAAM,EAAE,GAAG,SAAS,GACxC,IAAI,CAiBN"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/create-program/validateDefaultProjectForFilesGlob.js b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/validateDefaultProjectForFilesGlob.js new file mode 100644 index 00000000..1a7fab73 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/create-program/validateDefaultProjectForFilesGlob.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION = void 0; +exports.validateDefaultProjectForFilesGlob = validateDefaultProjectForFilesGlob; +exports.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION = ` + +Having many files run with the default project is known to cause performance issues and slow down linting. + +See https://typescript-eslint.io/troubleshooting/typed-linting#allowdefaultproject-glob-too-wide +`; +function validateDefaultProjectForFilesGlob(allowDefaultProject) { + if (!allowDefaultProject?.length) { + return; + } + for (const glob of allowDefaultProject) { + if (glob === '*') { + throw new Error(`allowDefaultProject contains the overly wide '*'.${exports.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION}`); + } + if (glob.includes('**')) { + throw new Error(`allowDefaultProject glob '${glob}' contains a disallowed '**'.${exports.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION}`); + } + } +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/createParserServices.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/createParserServices.d.ts new file mode 100644 index 00000000..28b98fe8 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/createParserServices.d.ts @@ -0,0 +1,5 @@ +import type * as ts from 'typescript'; +import type { ASTMaps } from './convert'; +import type { ParserServices } from './parser-options'; +export declare function createParserServices(astMaps: ASTMaps, program: ts.Program | null): ParserServices; +//# sourceMappingURL=createParserServices.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/createParserServices.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/createParserServices.d.ts.map new file mode 100644 index 00000000..2cdc2b58 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/createParserServices.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"createParserServices.d.ts","sourceRoot":"","sources":["../src/createParserServices.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,EAAE,CAAC,OAAO,GAAG,IAAI,GACzB,cAAc,CA6BhB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/createParserServices.js b/node_modules/@typescript-eslint/typescript-estree/dist/createParserServices.js new file mode 100644 index 00000000..cdaa6936 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/createParserServices.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createParserServices = createParserServices; +function createParserServices(astMaps, program) { + if (!program) { + return { + emitDecoratorMetadata: undefined, + experimentalDecorators: undefined, + isolatedDeclarations: undefined, + program, + // we always return the node maps because + // (a) they don't require type info and + // (b) they can be useful when using some of TS's internal non-type-aware AST utils + ...astMaps, + }; + } + const checker = program.getTypeChecker(); + const compilerOptions = program.getCompilerOptions(); + return { + program, + // not set in the config is the same as off + emitDecoratorMetadata: compilerOptions.emitDecoratorMetadata ?? false, + experimentalDecorators: compilerOptions.experimentalDecorators ?? false, + isolatedDeclarations: compilerOptions.isolatedDeclarations ?? false, + ...astMaps, + getSymbolAtLocation: node => checker.getSymbolAtLocation(astMaps.esTreeNodeToTSNodeMap.get(node)), + getTypeAtLocation: node => checker.getTypeAtLocation(astMaps.esTreeNodeToTSNodeMap.get(node)), + }; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/getModifiers.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/getModifiers.d.ts new file mode 100644 index 00000000..c312b154 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/getModifiers.d.ts @@ -0,0 +1,4 @@ +import * as ts from 'typescript'; +export declare function getModifiers(node: ts.Node | null | undefined, includeIllegalModifiers?: boolean): ts.Modifier[] | undefined; +export declare function getDecorators(node: ts.Node | null | undefined, includeIllegalDecorators?: boolean): ts.Decorator[] | undefined; +//# sourceMappingURL=getModifiers.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/getModifiers.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/getModifiers.d.ts.map new file mode 100644 index 00000000..a67408e6 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/getModifiers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getModifiers.d.ts","sourceRoot":"","sources":["../src/getModifiers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAMjC,wBAAgB,YAAY,CAC1B,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,IAAI,GAAG,SAAS,EAChC,uBAAuB,UAAQ,GAC9B,EAAE,CAAC,QAAQ,EAAE,GAAG,SAAS,CAsB3B;AAED,wBAAgB,aAAa,CAC3B,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,IAAI,GAAG,SAAS,EAChC,wBAAwB,UAAQ,GAC/B,EAAE,CAAC,SAAS,EAAE,GAAG,SAAS,CAoB5B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/getModifiers.js b/node_modules/@typescript-eslint/typescript-estree/dist/getModifiers.js new file mode 100644 index 00000000..4c164059 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/getModifiers.js @@ -0,0 +1,74 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getModifiers = getModifiers; +exports.getDecorators = getDecorators; +const ts = __importStar(require("typescript")); +const version_check_1 = require("./version-check"); +const isAtLeast48 = version_check_1.typescriptVersionIsAtLeast['4.8']; +function getModifiers(node, includeIllegalModifiers = false) { + if (node == null) { + return undefined; + } + if (isAtLeast48) { + // eslint-disable-next-line @typescript-eslint/no-deprecated -- this is safe as it's guarded + if (includeIllegalModifiers || ts.canHaveModifiers(node)) { + // eslint-disable-next-line @typescript-eslint/no-deprecated -- this is safe as it's guarded + const modifiers = ts.getModifiers(node); + return modifiers ? [...modifiers] : undefined; + } + return undefined; + } + return ( + // @ts-expect-error intentional fallback for older TS versions + node.modifiers?.filter((m) => !ts.isDecorator(m))); +} +function getDecorators(node, includeIllegalDecorators = false) { + if (node == null) { + return undefined; + } + if (isAtLeast48) { + // eslint-disable-next-line @typescript-eslint/no-deprecated -- this is safe as it's guarded + if (includeIllegalDecorators || ts.canHaveDecorators(node)) { + // eslint-disable-next-line @typescript-eslint/no-deprecated -- this is safe as it's guarded + const decorators = ts.getDecorators(node); + return decorators ? [...decorators] : undefined; + } + return undefined; + } + return ( + // @ts-expect-error intentional fallback for older TS versions + node.decorators?.filter(ts.isDecorator)); +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/index.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/index.d.ts new file mode 100644 index 00000000..5abd5434 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/index.d.ts @@ -0,0 +1,14 @@ +export * from './clear-caches'; +export * from './create-program/getScriptKind'; +export { getCanonicalFileName } from './create-program/shared'; +export { createProgramFromConfigFile as createProgram } from './create-program/useProvidedPrograms'; +export * from './getModifiers'; +export { TSError } from './node-utils'; +export { type AST, parse, parseAndGenerateServices, type ParseAndGenerateServicesResult, } from './parser'; +export type { ParserServices, ParserServicesWithoutTypeInformation, ParserServicesWithTypeInformation, TSESTreeOptions, } from './parser-options'; +export { simpleTraverse } from './simple-traverse'; +export * from './ts-estree'; +export { typescriptVersionIsAtLeast } from './version-check'; +export { version } from './version'; +export { withoutProjectParserOptions } from './withoutProjectParserOptions'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/index.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/index.d.ts.map new file mode 100644 index 00000000..e3be7bee --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gCAAgC,CAAC;AAC/C,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,EAAE,2BAA2B,IAAI,aAAa,EAAE,MAAM,sCAAsC,CAAC;AACpG,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EACL,KAAK,GAAG,EACR,KAAK,EACL,wBAAwB,EACxB,KAAK,8BAA8B,GACpC,MAAM,UAAU,CAAC;AAClB,YAAY,EACV,cAAc,EACd,oCAAoC,EACpC,iCAAiC,EACjC,eAAe,GAChB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/index.js b/node_modules/@typescript-eslint/typescript-estree/dist/index.js new file mode 100644 index 00000000..1f86bf3d --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/index.js @@ -0,0 +1,38 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.withoutProjectParserOptions = exports.version = exports.typescriptVersionIsAtLeast = exports.simpleTraverse = exports.parseAndGenerateServices = exports.parse = exports.TSError = exports.createProgram = exports.getCanonicalFileName = void 0; +__exportStar(require("./clear-caches"), exports); +__exportStar(require("./create-program/getScriptKind"), exports); +var shared_1 = require("./create-program/shared"); +Object.defineProperty(exports, "getCanonicalFileName", { enumerable: true, get: function () { return shared_1.getCanonicalFileName; } }); +var useProvidedPrograms_1 = require("./create-program/useProvidedPrograms"); +Object.defineProperty(exports, "createProgram", { enumerable: true, get: function () { return useProvidedPrograms_1.createProgramFromConfigFile; } }); +__exportStar(require("./getModifiers"), exports); +var node_utils_1 = require("./node-utils"); +Object.defineProperty(exports, "TSError", { enumerable: true, get: function () { return node_utils_1.TSError; } }); +var parser_1 = require("./parser"); +Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parser_1.parse; } }); +Object.defineProperty(exports, "parseAndGenerateServices", { enumerable: true, get: function () { return parser_1.parseAndGenerateServices; } }); +var simple_traverse_1 = require("./simple-traverse"); +Object.defineProperty(exports, "simpleTraverse", { enumerable: true, get: function () { return simple_traverse_1.simpleTraverse; } }); +__exportStar(require("./ts-estree"), exports); +var version_check_1 = require("./version-check"); +Object.defineProperty(exports, "typescriptVersionIsAtLeast", { enumerable: true, get: function () { return version_check_1.typescriptVersionIsAtLeast; } }); +var version_1 = require("./version"); +Object.defineProperty(exports, "version", { enumerable: true, get: function () { return version_1.version; } }); +var withoutProjectParserOptions_1 = require("./withoutProjectParserOptions"); +Object.defineProperty(exports, "withoutProjectParserOptions", { enumerable: true, get: function () { return withoutProjectParserOptions_1.withoutProjectParserOptions; } }); diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/jsx/xhtml-entities.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/jsx/xhtml-entities.d.ts new file mode 100644 index 00000000..7953cc6f --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/jsx/xhtml-entities.d.ts @@ -0,0 +1,2 @@ +export declare const xhtmlEntities: Record; +//# sourceMappingURL=xhtml-entities.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/jsx/xhtml-entities.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/jsx/xhtml-entities.d.ts.map new file mode 100644 index 00000000..ce45e83d --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/jsx/xhtml-entities.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"xhtml-entities.d.ts","sourceRoot":"","sources":["../../src/jsx/xhtml-entities.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CA8PhD,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/jsx/xhtml-entities.js b/node_modules/@typescript-eslint/typescript-estree/dist/jsx/xhtml-entities.js new file mode 100644 index 00000000..8fc299b2 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/jsx/xhtml-entities.js @@ -0,0 +1,258 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.xhtmlEntities = void 0; +exports.xhtmlEntities = { + Aacute: '\u00C1', + aacute: '\u00E1', + Acirc: '\u00C2', + acirc: '\u00E2', + acute: '\u00B4', + AElig: '\u00C6', + aelig: '\u00E6', + Agrave: '\u00C0', + agrave: '\u00E0', + alefsym: '\u2135', + Alpha: '\u0391', + alpha: '\u03B1', + amp: '&', + and: '\u2227', + ang: '\u2220', + apos: '\u0027', + Aring: '\u00C5', + aring: '\u00E5', + asymp: '\u2248', + Atilde: '\u00C3', + atilde: '\u00E3', + Auml: '\u00C4', + auml: '\u00E4', + bdquo: '\u201E', + Beta: '\u0392', + beta: '\u03B2', + brvbar: '\u00A6', + bull: '\u2022', + cap: '\u2229', + Ccedil: '\u00C7', + ccedil: '\u00E7', + cedil: '\u00B8', + cent: '\u00A2', + Chi: '\u03A7', + chi: '\u03C7', + circ: '\u02C6', + clubs: '\u2663', + cong: '\u2245', + copy: '\u00A9', + crarr: '\u21B5', + cup: '\u222A', + curren: '\u00A4', + dagger: '\u2020', + Dagger: '\u2021', + darr: '\u2193', + dArr: '\u21D3', + deg: '\u00B0', + Delta: '\u0394', + delta: '\u03B4', + diams: '\u2666', + divide: '\u00F7', + Eacute: '\u00C9', + eacute: '\u00E9', + Ecirc: '\u00CA', + ecirc: '\u00EA', + Egrave: '\u00C8', + egrave: '\u00E8', + empty: '\u2205', + emsp: '\u2003', + ensp: '\u2002', + Epsilon: '\u0395', + epsilon: '\u03B5', + equiv: '\u2261', + Eta: '\u0397', + eta: '\u03B7', + ETH: '\u00D0', + eth: '\u00F0', + Euml: '\u00CB', + euml: '\u00EB', + euro: '\u20AC', + exist: '\u2203', + fnof: '\u0192', + forall: '\u2200', + frac12: '\u00BD', + frac14: '\u00BC', + frac34: '\u00BE', + frasl: '\u2044', + Gamma: '\u0393', + gamma: '\u03B3', + ge: '\u2265', + gt: '>', + harr: '\u2194', + hArr: '\u21D4', + hearts: '\u2665', + hellip: '\u2026', + Iacute: '\u00CD', + iacute: '\u00ED', + Icirc: '\u00CE', + icirc: '\u00EE', + iexcl: '\u00A1', + Igrave: '\u00CC', + igrave: '\u00EC', + image: '\u2111', + infin: '\u221E', + int: '\u222B', + Iota: '\u0399', + iota: '\u03B9', + iquest: '\u00BF', + isin: '\u2208', + Iuml: '\u00CF', + iuml: '\u00EF', + Kappa: '\u039A', + kappa: '\u03BA', + Lambda: '\u039B', + lambda: '\u03BB', + lang: '\u2329', + laquo: '\u00AB', + larr: '\u2190', + lArr: '\u21D0', + lceil: '\u2308', + ldquo: '\u201C', + le: '\u2264', + lfloor: '\u230A', + lowast: '\u2217', + loz: '\u25CA', + lrm: '\u200E', + lsaquo: '\u2039', + lsquo: '\u2018', + lt: '<', + macr: '\u00AF', + mdash: '\u2014', + micro: '\u00B5', + middot: '\u00B7', + minus: '\u2212', + Mu: '\u039C', + mu: '\u03BC', + nabla: '\u2207', + nbsp: '\u00A0', + ndash: '\u2013', + ne: '\u2260', + ni: '\u220B', + not: '\u00AC', + notin: '\u2209', + nsub: '\u2284', + Ntilde: '\u00D1', + ntilde: '\u00F1', + Nu: '\u039D', + nu: '\u03BD', + Oacute: '\u00D3', + oacute: '\u00F3', + Ocirc: '\u00D4', + ocirc: '\u00F4', + OElig: '\u0152', + oelig: '\u0153', + Ograve: '\u00D2', + ograve: '\u00F2', + oline: '\u203E', + Omega: '\u03A9', + omega: '\u03C9', + Omicron: '\u039F', + omicron: '\u03BF', + oplus: '\u2295', + or: '\u2228', + ordf: '\u00AA', + ordm: '\u00BA', + Oslash: '\u00D8', + oslash: '\u00F8', + Otilde: '\u00D5', + otilde: '\u00F5', + otimes: '\u2297', + Ouml: '\u00D6', + ouml: '\u00F6', + para: '\u00B6', + part: '\u2202', + permil: '\u2030', + perp: '\u22A5', + Phi: '\u03A6', + phi: '\u03C6', + Pi: '\u03A0', + pi: '\u03C0', + piv: '\u03D6', + plusmn: '\u00B1', + pound: '\u00A3', + prime: '\u2032', + Prime: '\u2033', + prod: '\u220F', + prop: '\u221D', + Psi: '\u03A8', + psi: '\u03C8', + quot: '\u0022', + radic: '\u221A', + rang: '\u232A', + raquo: '\u00BB', + rarr: '\u2192', + rArr: '\u21D2', + rceil: '\u2309', + rdquo: '\u201D', + real: '\u211C', + reg: '\u00AE', + rfloor: '\u230B', + Rho: '\u03A1', + rho: '\u03C1', + rlm: '\u200F', + rsaquo: '\u203A', + rsquo: '\u2019', + sbquo: '\u201A', + Scaron: '\u0160', + scaron: '\u0161', + sdot: '\u22C5', + sect: '\u00A7', + shy: '\u00AD', + Sigma: '\u03A3', + sigma: '\u03C3', + sigmaf: '\u03C2', + sim: '\u223C', + spades: '\u2660', + sub: '\u2282', + sube: '\u2286', + sum: '\u2211', + sup: '\u2283', + sup1: '\u00B9', + sup2: '\u00B2', + sup3: '\u00B3', + supe: '\u2287', + szlig: '\u00DF', + Tau: '\u03A4', + tau: '\u03C4', + there4: '\u2234', + Theta: '\u0398', + theta: '\u03B8', + thetasym: '\u03D1', + thinsp: '\u2009', + THORN: '\u00DE', + thorn: '\u00FE', + tilde: '\u02DC', + times: '\u00D7', + trade: '\u2122', + Uacute: '\u00DA', + uacute: '\u00FA', + uarr: '\u2191', + uArr: '\u21D1', + Ucirc: '\u00DB', + ucirc: '\u00FB', + Ugrave: '\u00D9', + ugrave: '\u00F9', + uml: '\u00A8', + upsih: '\u03D2', + Upsilon: '\u03A5', + upsilon: '\u03C5', + Uuml: '\u00DC', + uuml: '\u00FC', + weierp: '\u2118', + Xi: '\u039E', + xi: '\u03BE', + Yacute: '\u00DD', + yacute: '\u00FD', + yen: '\u00A5', + yuml: '\u00FF', + Yuml: '\u0178', + Zeta: '\u0396', + zeta: '\u03B6', + zwj: '\u200D', + zwnj: '\u200C', +}; diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.d.ts new file mode 100644 index 00000000..8dcbed5b --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.d.ts @@ -0,0 +1,192 @@ +import * as ts from 'typescript'; +import type { TSESTree, TSNode } from './ts-estree'; +import { AST_NODE_TYPES, AST_TOKEN_TYPES } from './ts-estree'; +declare const SyntaxKind: typeof ts.SyntaxKind; +type LogicalOperatorKind = ts.SyntaxKind.AmpersandAmpersandToken | ts.SyntaxKind.BarBarToken | ts.SyntaxKind.QuestionQuestionToken; +interface TokenToText extends TSESTree.PunctuatorTokenToText, TSESTree.BinaryOperatorToText { + [SyntaxKind.ImportKeyword]: 'import'; + [SyntaxKind.KeyOfKeyword]: 'keyof'; + [SyntaxKind.NewKeyword]: 'new'; + [SyntaxKind.ReadonlyKeyword]: 'readonly'; + [SyntaxKind.UniqueKeyword]: 'unique'; +} +type AssignmentOperatorKind = keyof TSESTree.AssignmentOperatorToText; +type BinaryOperatorKind = keyof TSESTree.BinaryOperatorToText; +type DeclarationKind = TSESTree.VariableDeclaration['kind']; +/** + * Returns true if the given ts.Token is a logical operator + */ +export declare function isLogicalOperator(operator: ts.BinaryOperatorToken): operator is ts.Token; +export declare function isESTreeBinaryOperator(operator: ts.BinaryOperatorToken): operator is ts.Token; +type TokenForTokenKind = T extends keyof TokenToText ? TokenToText[T] : string | undefined; +/** + * Returns the string form of the given TSToken SyntaxKind + */ +export declare function getTextForTokenKind(kind: T): TokenForTokenKind; +/** + * Returns true if the given ts.Node is a valid ESTree class member + */ +export declare function isESTreeClassMember(node: ts.Node): boolean; +/** + * Checks if a ts.Node has a modifier + */ +export declare function hasModifier(modifierKind: ts.KeywordSyntaxKind, node: ts.Node): boolean; +/** + * Get last last modifier in ast + * @returns returns last modifier if present or null + */ +export declare function getLastModifier(node: ts.Node): ts.Modifier | null; +/** + * Returns true if the given ts.Token is a comma + */ +export declare function isComma(token: ts.Node): token is ts.Token; +/** + * Returns true if the given ts.Node is a comment + */ +export declare function isComment(node: ts.Node): boolean; +/** + * Returns the binary expression type of the given ts.Token + */ +export declare function getBinaryExpressionType(operator: ts.BinaryOperatorToken): { + operator: TokenForTokenKind; + type: AST_NODE_TYPES.AssignmentExpression; +} | { + operator: TokenForTokenKind; + type: AST_NODE_TYPES.BinaryExpression; +} | { + operator: TokenForTokenKind; + type: AST_NODE_TYPES.LogicalExpression; +}; +/** + * Returns line and column data for the given positions + */ +export declare function getLineAndCharacterFor(pos: number, ast: ts.SourceFile): TSESTree.Position; +/** + * Returns line and column data for the given start and end positions, + * for the given AST + */ +export declare function getLocFor(range: TSESTree.Range, ast: ts.SourceFile): TSESTree.SourceLocation; +/** + * Check whatever node can contain directive + */ +export declare function canContainDirective(node: ts.Block | ts.ClassStaticBlockDeclaration | ts.ModuleBlock | ts.SourceFile): boolean; +/** + * Returns range for the given ts.Node + */ +export declare function getRange(node: Pick, ast: ts.SourceFile): [number, number]; +/** + * Returns true if a given ts.Node is a JSX token + */ +export declare function isJSXToken(node: ts.Node): boolean; +/** + * Returns the declaration kind of the given ts.Node + */ +export declare function getDeclarationKind(node: ts.VariableDeclarationList): DeclarationKind; +/** + * Gets a ts.Node's accessibility level + */ +export declare function getTSNodeAccessibility(node: ts.Node): 'private' | 'protected' | 'public' | undefined; +/** + * Finds the next token based on the previous one and its parent + * Had to copy this from TS instead of using TS's version because theirs doesn't pass the ast to getChildren + */ +export declare function findNextToken(previousToken: ts.TextRange, parent: ts.Node, ast: ts.SourceFile): ts.Node | undefined; +/** + * Find the first matching ancestor based on the given predicate function. + * @param node The current ts.Node + * @param predicate The predicate function to apply to each checked ancestor + * @returns a matching parent ts.Node + */ +export declare function findFirstMatchingAncestor(node: ts.Node, predicate: (node: ts.Node) => boolean): ts.Node | undefined; +/** + * Returns true if a given ts.Node has a JSX token within its hierarchy + */ +export declare function hasJSXAncestor(node: ts.Node): boolean; +/** + * Unescape the text content of string literals, e.g. & -> & + * @param text The escaped string literal text. + * @returns The unescaped string literal text. + */ +export declare function unescapeStringLiteralText(text: string): string; +/** + * Returns true if a given ts.Node is a computed property + */ +export declare function isComputedProperty(node: ts.Node): node is ts.ComputedPropertyName; +/** + * Returns true if a given ts.Node is optional (has QuestionToken) + * @param node ts.Node to be checked + */ +export declare function isOptional(node: { + questionToken?: ts.QuestionToken; +}): boolean; +/** + * Returns true if the node is an optional chain node + */ +export declare function isChainExpression(node: TSESTree.Node): node is TSESTree.ChainExpression; +/** + * Returns true of the child of property access expression is an optional chain + */ +export declare function isChildUnwrappableOptionalChain(node: ts.CallExpression | ts.ElementAccessExpression | ts.NonNullExpression | ts.PropertyAccessExpression, child: TSESTree.Node): boolean; +/** + * Returns the type of a given ts.Token + */ +export declare function getTokenType(token: ts.Identifier | ts.Token): Exclude; +/** + * Extends and formats a given ts.Token, for a given AST + */ +export declare function convertToken(token: ts.Token, ast: ts.SourceFile): TSESTree.Token; +/** + * Converts all tokens for the given AST + * @param ast the AST object + * @returns the converted Tokens + */ +export declare function convertTokens(ast: ts.SourceFile): TSESTree.Token[]; +export declare class TSError extends Error { + readonly fileName: string; + readonly location: { + end: { + column: number; + line: number; + offset: number; + }; + start: { + column: number; + line: number; + offset: number; + }; + }; + constructor(message: string, fileName: string, location: { + end: { + column: number; + line: number; + offset: number; + }; + start: { + column: number; + line: number; + offset: number; + }; + }); + get index(): number; + get lineNumber(): number; + get column(): number; +} +export declare function createError(message: string, ast: ts.SourceFile, startIndex: number, endIndex?: number): TSError; +export declare function nodeHasIllegalDecorators(node: ts.Node): node is { + illegalDecorators: ts.Node[]; +} & ts.Node; +export declare function nodeHasTokens(n: ts.Node, ast: ts.SourceFile): boolean; +/** + * Like `forEach`, but suitable for use with numbers and strings (which may be falsy). + */ +export declare function firstDefined(array: readonly T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined; +export declare function identifierIsThisKeyword(id: ts.Identifier): boolean; +export declare function isThisIdentifier(node: ts.Node | undefined): node is ts.Identifier; +export declare function isThisInTypeQuery(node: ts.Node): boolean; +export declare function nodeIsPresent(node: ts.Node | undefined): node is ts.Node; +export declare function getContainingFunction(node: ts.Node): ts.SignatureDeclaration | undefined; +export declare function nodeCanBeDecorated(node: TSNode): boolean; +export declare function isValidAssignmentTarget(node: ts.Node): boolean; +export declare function getNamespaceModifiers(node: ts.ModuleDeclaration): ts.Modifier[] | undefined; +export {}; +//# sourceMappingURL=node-utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.d.ts.map new file mode 100644 index 00000000..5ab4c563 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"node-utils.d.ts","sourceRoot":"","sources":["../src/node-utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAIpD,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAK9D,QAAA,MAAM,UAAU,sBAAgB,CAAC;AAEjC,KAAK,mBAAmB,GACpB,EAAE,CAAC,UAAU,CAAC,uBAAuB,GACrC,EAAE,CAAC,UAAU,CAAC,WAAW,GACzB,EAAE,CAAC,UAAU,CAAC,qBAAqB,CAAC;AAOxC,UAAU,WACR,SAAQ,QAAQ,CAAC,qBAAqB,EACpC,QAAQ,CAAC,oBAAoB;IAC/B,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC;IACrC,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;IACnC,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,KAAK,CAAC;IAC/B,CAAC,UAAU,CAAC,eAAe,CAAC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S,CAErC;AA4BD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAuDxD;AAED,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CA6B9D;AAED,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,EAAE,CAAC,iBAAiB,GACzB,EAAE,CAAC,QAAQ,EAAE,GAAG,SAAS,CAgB3B"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.js b/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.js new file mode 100644 index 00000000..df5a7eed --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.js @@ -0,0 +1,754 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSError = void 0; +exports.isLogicalOperator = isLogicalOperator; +exports.isESTreeBinaryOperator = isESTreeBinaryOperator; +exports.getTextForTokenKind = getTextForTokenKind; +exports.isESTreeClassMember = isESTreeClassMember; +exports.hasModifier = hasModifier; +exports.getLastModifier = getLastModifier; +exports.isComma = isComma; +exports.isComment = isComment; +exports.getBinaryExpressionType = getBinaryExpressionType; +exports.getLineAndCharacterFor = getLineAndCharacterFor; +exports.getLocFor = getLocFor; +exports.canContainDirective = canContainDirective; +exports.getRange = getRange; +exports.isJSXToken = isJSXToken; +exports.getDeclarationKind = getDeclarationKind; +exports.getTSNodeAccessibility = getTSNodeAccessibility; +exports.findNextToken = findNextToken; +exports.findFirstMatchingAncestor = findFirstMatchingAncestor; +exports.hasJSXAncestor = hasJSXAncestor; +exports.unescapeStringLiteralText = unescapeStringLiteralText; +exports.isComputedProperty = isComputedProperty; +exports.isOptional = isOptional; +exports.isChainExpression = isChainExpression; +exports.isChildUnwrappableOptionalChain = isChildUnwrappableOptionalChain; +exports.getTokenType = getTokenType; +exports.convertToken = convertToken; +exports.convertTokens = convertTokens; +exports.createError = createError; +exports.nodeHasIllegalDecorators = nodeHasIllegalDecorators; +exports.nodeHasTokens = nodeHasTokens; +exports.firstDefined = firstDefined; +exports.identifierIsThisKeyword = identifierIsThisKeyword; +exports.isThisIdentifier = isThisIdentifier; +exports.isThisInTypeQuery = isThisInTypeQuery; +exports.nodeIsPresent = nodeIsPresent; +exports.getContainingFunction = getContainingFunction; +exports.nodeCanBeDecorated = nodeCanBeDecorated; +exports.isValidAssignmentTarget = isValidAssignmentTarget; +exports.getNamespaceModifiers = getNamespaceModifiers; +const ts = __importStar(require("typescript")); +const getModifiers_1 = require("./getModifiers"); +const xhtml_entities_1 = require("./jsx/xhtml-entities"); +const ts_estree_1 = require("./ts-estree"); +const version_check_1 = require("./version-check"); +const isAtLeast50 = version_check_1.typescriptVersionIsAtLeast['5.0']; +const SyntaxKind = ts.SyntaxKind; +const LOGICAL_OPERATORS = new Set([ + SyntaxKind.AmpersandAmpersandToken, + SyntaxKind.BarBarToken, + SyntaxKind.QuestionQuestionToken, +]); +const ASSIGNMENT_OPERATORS = new Set([ + ts.SyntaxKind.AmpersandAmpersandEqualsToken, + ts.SyntaxKind.AmpersandEqualsToken, + ts.SyntaxKind.AsteriskAsteriskEqualsToken, + ts.SyntaxKind.AsteriskEqualsToken, + ts.SyntaxKind.BarBarEqualsToken, + ts.SyntaxKind.BarEqualsToken, + ts.SyntaxKind.CaretEqualsToken, + ts.SyntaxKind.EqualsToken, + ts.SyntaxKind.GreaterThanGreaterThanEqualsToken, + ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken, + ts.SyntaxKind.LessThanLessThanEqualsToken, + ts.SyntaxKind.MinusEqualsToken, + ts.SyntaxKind.PercentEqualsToken, + ts.SyntaxKind.PlusEqualsToken, + ts.SyntaxKind.QuestionQuestionEqualsToken, + ts.SyntaxKind.SlashEqualsToken, +]); +const BINARY_OPERATORS = new Set([ + SyntaxKind.AmpersandAmpersandToken, + SyntaxKind.AmpersandToken, + SyntaxKind.AsteriskAsteriskToken, + SyntaxKind.AsteriskToken, + SyntaxKind.BarBarToken, + SyntaxKind.BarToken, + SyntaxKind.CaretToken, + SyntaxKind.EqualsEqualsEqualsToken, + SyntaxKind.EqualsEqualsToken, + SyntaxKind.ExclamationEqualsEqualsToken, + SyntaxKind.ExclamationEqualsToken, + SyntaxKind.GreaterThanEqualsToken, + SyntaxKind.GreaterThanGreaterThanGreaterThanToken, + SyntaxKind.GreaterThanGreaterThanToken, + SyntaxKind.GreaterThanToken, + SyntaxKind.InKeyword, + SyntaxKind.InstanceOfKeyword, + SyntaxKind.LessThanEqualsToken, + SyntaxKind.LessThanLessThanToken, + SyntaxKind.LessThanToken, + SyntaxKind.MinusToken, + SyntaxKind.PercentToken, + SyntaxKind.PlusToken, + SyntaxKind.SlashToken, +]); +/** + * Returns true if the given ts.Token is the assignment operator + */ +function isAssignmentOperator(operator) { + return ASSIGNMENT_OPERATORS.has(operator.kind); +} +/** + * Returns true if the given ts.Token is a logical operator + */ +function isLogicalOperator(operator) { + return LOGICAL_OPERATORS.has(operator.kind); +} +function isESTreeBinaryOperator(operator) { + return BINARY_OPERATORS.has(operator.kind); +} +/** + * Returns the string form of the given TSToken SyntaxKind + */ +function getTextForTokenKind(kind) { + return ts.tokenToString(kind); +} +/** + * Returns true if the given ts.Node is a valid ESTree class member + */ +function isESTreeClassMember(node) { + return node.kind !== SyntaxKind.SemicolonClassElement; +} +/** + * Checks if a ts.Node has a modifier + */ +function hasModifier(modifierKind, node) { + const modifiers = (0, getModifiers_1.getModifiers)(node); + return modifiers?.some(modifier => modifier.kind === modifierKind) === true; +} +/** + * Get last last modifier in ast + * @returns returns last modifier if present or null + */ +function getLastModifier(node) { + const modifiers = (0, getModifiers_1.getModifiers)(node); + if (modifiers == null) { + return null; + } + return modifiers[modifiers.length - 1] ?? null; +} +/** + * Returns true if the given ts.Token is a comma + */ +function isComma(token) { + return token.kind === SyntaxKind.CommaToken; +} +/** + * Returns true if the given ts.Node is a comment + */ +function isComment(node) { + return (node.kind === SyntaxKind.SingleLineCommentTrivia || + node.kind === SyntaxKind.MultiLineCommentTrivia); +} +/** + * Returns true if the given ts.Node is a JSDoc comment + */ +function isJSDocComment(node) { + // eslint-disable-next-line @typescript-eslint/no-deprecated -- SyntaxKind.JSDoc was only added in TS4.7 so we can't use it yet + return node.kind === SyntaxKind.JSDocComment; +} +/** + * Returns the binary expression type of the given ts.Token + */ +function getBinaryExpressionType(operator) { + if (isAssignmentOperator(operator)) { + return { + type: ts_estree_1.AST_NODE_TYPES.AssignmentExpression, + operator: getTextForTokenKind(operator.kind), + }; + } + if (isLogicalOperator(operator)) { + return { + type: ts_estree_1.AST_NODE_TYPES.LogicalExpression, + operator: getTextForTokenKind(operator.kind), + }; + } + if (isESTreeBinaryOperator(operator)) { + return { + type: ts_estree_1.AST_NODE_TYPES.BinaryExpression, + operator: getTextForTokenKind(operator.kind), + }; + } + throw new Error(`Unexpected binary operator ${ts.tokenToString(operator.kind)}`); +} +/** + * Returns line and column data for the given positions + */ +function getLineAndCharacterFor(pos, ast) { + const loc = ast.getLineAndCharacterOfPosition(pos); + return { + column: loc.character, + line: loc.line + 1, + }; +} +/** + * Returns line and column data for the given start and end positions, + * for the given AST + */ +function getLocFor(range, ast) { + const [start, end] = range.map(pos => getLineAndCharacterFor(pos, ast)); + return { end, start }; +} +/** + * Check whatever node can contain directive + */ +function canContainDirective(node) { + if (node.kind === ts.SyntaxKind.Block) { + switch (node.parent.kind) { + case ts.SyntaxKind.Constructor: + case ts.SyntaxKind.GetAccessor: + case ts.SyntaxKind.SetAccessor: + case ts.SyntaxKind.ArrowFunction: + case ts.SyntaxKind.FunctionExpression: + case ts.SyntaxKind.FunctionDeclaration: + case ts.SyntaxKind.MethodDeclaration: + return true; + default: + return false; + } + } + return true; +} +/** + * Returns range for the given ts.Node + */ +function getRange(node, ast) { + return [node.getStart(ast), node.getEnd()]; +} +/** + * Returns true if a given ts.Node is a token + */ +function isToken(node) { + return (node.kind >= SyntaxKind.FirstToken && node.kind <= SyntaxKind.LastToken); +} +/** + * Returns true if a given ts.Node is a JSX token + */ +function isJSXToken(node) { + return (node.kind >= SyntaxKind.JsxElement && node.kind <= SyntaxKind.JsxAttribute); +} +/** + * Returns the declaration kind of the given ts.Node + */ +function getDeclarationKind(node) { + if (node.flags & ts.NodeFlags.Let) { + return 'let'; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison + if ((node.flags & ts.NodeFlags.AwaitUsing) === ts.NodeFlags.AwaitUsing) { + return 'await using'; + } + if (node.flags & ts.NodeFlags.Const) { + return 'const'; + } + if (node.flags & ts.NodeFlags.Using) { + return 'using'; + } + return 'var'; +} +/** + * Gets a ts.Node's accessibility level + */ +function getTSNodeAccessibility(node) { + const modifiers = (0, getModifiers_1.getModifiers)(node); + if (modifiers == null) { + return undefined; + } + for (const modifier of modifiers) { + switch (modifier.kind) { + case SyntaxKind.PublicKeyword: + return 'public'; + case SyntaxKind.ProtectedKeyword: + return 'protected'; + case SyntaxKind.PrivateKeyword: + return 'private'; + default: + break; + } + } + return undefined; +} +/** + * Finds the next token based on the previous one and its parent + * Had to copy this from TS instead of using TS's version because theirs doesn't pass the ast to getChildren + */ +function findNextToken(previousToken, parent, ast) { + return find(parent); + function find(n) { + if (ts.isToken(n) && n.pos === previousToken.end) { + // this is token that starts at the end of previous token - return it + return n; + } + return firstDefined(n.getChildren(ast), (child) => { + const shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + child.pos === previousToken.end; + return shouldDiveInChildNode && nodeHasTokens(child, ast) + ? find(child) + : undefined; + }); + } +} +/** + * Find the first matching ancestor based on the given predicate function. + * @param node The current ts.Node + * @param predicate The predicate function to apply to each checked ancestor + * @returns a matching parent ts.Node + */ +function findFirstMatchingAncestor(node, predicate) { + let current = node; + while (current) { + if (predicate(current)) { + return current; + } + current = current.parent; + } + return undefined; +} +/** + * Returns true if a given ts.Node has a JSX token within its hierarchy + */ +function hasJSXAncestor(node) { + return !!findFirstMatchingAncestor(node, isJSXToken); +} +/** + * Unescape the text content of string literals, e.g. & -> & + * @param text The escaped string literal text. + * @returns The unescaped string literal text. + */ +function unescapeStringLiteralText(text) { + return text.replaceAll(/&(?:#\d+|#x[\da-fA-F]+|[0-9a-zA-Z]+);/g, entity => { + const item = entity.slice(1, -1); + if (item[0] === '#') { + const codePoint = item[1] === 'x' + ? parseInt(item.slice(2), 16) + : parseInt(item.slice(1), 10); + return codePoint > 0x10ffff // RangeError: Invalid code point + ? entity + : String.fromCodePoint(codePoint); + } + return xhtml_entities_1.xhtmlEntities[item] || entity; + }); +} +/** + * Returns true if a given ts.Node is a computed property + */ +function isComputedProperty(node) { + return node.kind === SyntaxKind.ComputedPropertyName; +} +/** + * Returns true if a given ts.Node is optional (has QuestionToken) + * @param node ts.Node to be checked + */ +function isOptional(node) { + return !!node.questionToken; +} +/** + * Returns true if the node is an optional chain node + */ +function isChainExpression(node) { + return node.type === ts_estree_1.AST_NODE_TYPES.ChainExpression; +} +/** + * Returns true of the child of property access expression is an optional chain + */ +function isChildUnwrappableOptionalChain(node, child) { + return (isChainExpression(child) && + // (x?.y).z is semantically different, and as such .z is no longer optional + node.expression.kind !== ts.SyntaxKind.ParenthesizedExpression); +} +/** + * Returns the type of a given ts.Token + */ +function getTokenType(token) { + if (token.kind === SyntaxKind.NullKeyword) { + return ts_estree_1.AST_TOKEN_TYPES.Null; + } + let keywordKind; + if (isAtLeast50 && token.kind === SyntaxKind.Identifier) { + keywordKind = ts.identifierToKeywordKind(token); + } + else if ('originalKeywordKind' in token) { + // @ts-expect-error -- intentional fallback for older TS versions <=4.9 + keywordKind = token.originalKeywordKind; + } + if (keywordKind) { + if (keywordKind === SyntaxKind.NullKeyword) { + return ts_estree_1.AST_TOKEN_TYPES.Null; + } + if (keywordKind >= SyntaxKind.FirstFutureReservedWord && + keywordKind <= SyntaxKind.LastKeyword) { + return ts_estree_1.AST_TOKEN_TYPES.Identifier; + } + return ts_estree_1.AST_TOKEN_TYPES.Keyword; + } + if (token.kind >= SyntaxKind.FirstKeyword && + token.kind <= SyntaxKind.LastFutureReservedWord) { + if (token.kind === SyntaxKind.FalseKeyword || + token.kind === SyntaxKind.TrueKeyword) { + return ts_estree_1.AST_TOKEN_TYPES.Boolean; + } + return ts_estree_1.AST_TOKEN_TYPES.Keyword; + } + if (token.kind >= SyntaxKind.FirstPunctuation && + token.kind <= SyntaxKind.LastPunctuation) { + return ts_estree_1.AST_TOKEN_TYPES.Punctuator; + } + if (token.kind >= SyntaxKind.NoSubstitutionTemplateLiteral && + token.kind <= SyntaxKind.TemplateTail) { + return ts_estree_1.AST_TOKEN_TYPES.Template; + } + switch (token.kind) { + case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: + return ts_estree_1.AST_TOKEN_TYPES.Numeric; + case SyntaxKind.PrivateIdentifier: + return ts_estree_1.AST_TOKEN_TYPES.PrivateIdentifier; + case SyntaxKind.JsxText: + return ts_estree_1.AST_TOKEN_TYPES.JSXText; + case SyntaxKind.StringLiteral: + // A TypeScript-StringLiteral token with a TypeScript-JsxAttribute or TypeScript-JsxElement parent, + // must actually be an ESTree-JSXText token + if (token.parent.kind === SyntaxKind.JsxAttribute || + token.parent.kind === SyntaxKind.JsxElement) { + return ts_estree_1.AST_TOKEN_TYPES.JSXText; + } + return ts_estree_1.AST_TOKEN_TYPES.String; + case SyntaxKind.RegularExpressionLiteral: + return ts_estree_1.AST_TOKEN_TYPES.RegularExpression; + case SyntaxKind.Identifier: + case SyntaxKind.ConstructorKeyword: + case SyntaxKind.GetKeyword: + case SyntaxKind.SetKeyword: + // intentional fallthrough + default: + } + // Some JSX tokens have to be determined based on their parent + if (token.kind === SyntaxKind.Identifier) { + if (isJSXToken(token.parent)) { + return ts_estree_1.AST_TOKEN_TYPES.JSXIdentifier; + } + if (token.parent.kind === SyntaxKind.PropertyAccessExpression && + hasJSXAncestor(token)) { + return ts_estree_1.AST_TOKEN_TYPES.JSXIdentifier; + } + } + return ts_estree_1.AST_TOKEN_TYPES.Identifier; +} +/** + * Extends and formats a given ts.Token, for a given AST + */ +function convertToken(token, ast) { + const start = token.kind === SyntaxKind.JsxText + ? token.getFullStart() + : token.getStart(ast); + const end = token.getEnd(); + const value = ast.text.slice(start, end); + const tokenType = getTokenType(token); + const range = [start, end]; + const loc = getLocFor(range, ast); + if (tokenType === ts_estree_1.AST_TOKEN_TYPES.RegularExpression) { + return { + type: tokenType, + loc, + range, + regex: { + flags: value.slice(value.lastIndexOf('/') + 1), + pattern: value.slice(1, value.lastIndexOf('/')), + }, + value, + }; + } + if (tokenType === ts_estree_1.AST_TOKEN_TYPES.PrivateIdentifier) { + return { + type: tokenType, + loc, + range, + value: value.slice(1), + }; + } + // @ts-expect-error TS is complaining about `value` not being the correct + // type but it is + return { + type: tokenType, + loc, + range, + value, + }; +} +/** + * Converts all tokens for the given AST + * @param ast the AST object + * @returns the converted Tokens + */ +function convertTokens(ast) { + const result = []; + /** + * @param node the ts.Node + */ + function walk(node) { + // TypeScript generates tokens for types in JSDoc blocks. Comment tokens + // and their children should not be walked or added to the resulting tokens list. + if (isComment(node) || isJSDocComment(node)) { + return; + } + if (isToken(node) && node.kind !== SyntaxKind.EndOfFileToken) { + result.push(convertToken(node, ast)); + } + else { + node.getChildren(ast).forEach(walk); + } + } + walk(ast); + return result; +} +class TSError extends Error { + fileName; + location; + constructor(message, fileName, location) { + super(message); + this.fileName = fileName; + this.location = location; + Object.defineProperty(this, 'name', { + configurable: true, + enumerable: false, + value: new.target.name, + }); + } + // For old version of ESLint https://github.com/typescript-eslint/typescript-eslint/pull/6556#discussion_r1123237311 + get index() { + return this.location.start.offset; + } + // https://github.com/eslint/eslint/blob/b09a512107249a4eb19ef5a37b0bd672266eafdb/lib/linter/linter.js#L853 + get lineNumber() { + return this.location.start.line; + } + // https://github.com/eslint/eslint/blob/b09a512107249a4eb19ef5a37b0bd672266eafdb/lib/linter/linter.js#L854 + get column() { + return this.location.start.column; + } +} +exports.TSError = TSError; +function createError(message, ast, startIndex, endIndex = startIndex) { + const [start, end] = [startIndex, endIndex].map(offset => { + const { character: column, line } = ast.getLineAndCharacterOfPosition(offset); + return { column, line: line + 1, offset }; + }); + return new TSError(message, ast.fileName, { end, start }); +} +function nodeHasIllegalDecorators(node) { + return !!('illegalDecorators' in node && + node.illegalDecorators?.length); +} +function nodeHasTokens(n, ast) { + // If we have a token or node that has a non-zero width, it must have tokens. + // Note: getWidth() does not take trivia into account. + return n.kind === SyntaxKind.EndOfFileToken + ? !!n.jsDoc + : n.getWidth(ast) !== 0; +} +/** + * Like `forEach`, but suitable for use with numbers and strings (which may be falsy). + */ +function firstDefined(array, callback) { + // eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish + if (array === undefined) { + return undefined; + } + for (let i = 0; i < array.length; i++) { + const result = callback(array[i], i); + // eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish + if (result !== undefined) { + return result; + } + } + return undefined; +} +function identifierIsThisKeyword(id) { + return ((isAtLeast50 + ? ts.identifierToKeywordKind(id) + : // @ts-expect-error -- intentional fallback for older TS versions <=4.9 + id.originalKeywordKind) === SyntaxKind.ThisKeyword); +} +function isThisIdentifier(node) { + return (!!node && + node.kind === SyntaxKind.Identifier && + identifierIsThisKeyword(node)); +} +function isThisInTypeQuery(node) { + if (!isThisIdentifier(node)) { + return false; + } + while (ts.isQualifiedName(node.parent) && node.parent.left === node) { + node = node.parent; + } + return node.parent.kind === SyntaxKind.TypeQuery; +} +// `ts.nodeIsMissing` +function nodeIsMissing(node) { + if (node == null) { + return true; + } + return (node.pos === node.end && + node.pos >= 0 && + node.kind !== SyntaxKind.EndOfFileToken); +} +// `ts.nodeIsPresent` +function nodeIsPresent(node) { + return !nodeIsMissing(node); +} +// `ts.getContainingFunction` +function getContainingFunction(node) { + return ts.findAncestor(node.parent, ts.isFunctionLike); +} +// `ts.hasAbstractModifier` +function hasAbstractModifier(node) { + return hasModifier(SyntaxKind.AbstractKeyword, node); +} +// `ts.getThisParameter` +function getThisParameter(signature) { + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { + const thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + return null; +} +// `ts.parameterIsThisKeyword` +function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); +} +// Rewrite version of `ts.nodeCanBeDecorated` +// Returns `true` for both `useLegacyDecorators: true` and `useLegacyDecorators: false` +function nodeCanBeDecorated(node) { + switch (node.kind) { + case SyntaxKind.ClassDeclaration: + return true; + case SyntaxKind.ClassExpression: + // `ts.nodeCanBeDecorated` returns `false` if `useLegacyDecorators: true` + return true; + case SyntaxKind.PropertyDeclaration: { + const { parent } = node; + // `ts.nodeCanBeDecorated` uses this if `useLegacyDecorators: true` + if (ts.isClassDeclaration(parent)) { + return true; + } + // `ts.nodeCanBeDecorated` uses this if `useLegacyDecorators: false` + if (ts.isClassLike(parent) && !hasAbstractModifier(node)) { + return true; + } + return false; + } + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.MethodDeclaration: { + const { parent } = node; + // In `ts.nodeCanBeDecorated` + // when `useLegacyDecorators: true` uses `ts.isClassDeclaration` + // when `useLegacyDecorators: true` uses `ts.isClassLike` + return (Boolean(node.body) && + (ts.isClassDeclaration(parent) || ts.isClassLike(parent))); + } + case SyntaxKind.Parameter: { + // `ts.nodeCanBeDecorated` returns `false` if `useLegacyDecorators: false` + const { parent } = node; + const grandparent = parent.parent; + return (Boolean(parent) && + 'body' in parent && + Boolean(parent.body) && + (parent.kind === SyntaxKind.Constructor || + parent.kind === SyntaxKind.MethodDeclaration || + parent.kind === SyntaxKind.SetAccessor) && + getThisParameter(parent) !== node && + Boolean(grandparent) && + grandparent.kind === SyntaxKind.ClassDeclaration); + } + } + return false; +} +function isValidAssignmentTarget(node) { + switch (node.kind) { + case SyntaxKind.Identifier: + return true; + case SyntaxKind.PropertyAccessExpression: + case SyntaxKind.ElementAccessExpression: + if (node.flags & ts.NodeFlags.OptionalChain) { + return false; + } + return true; + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.TypeAssertionExpression: + case SyntaxKind.AsExpression: + case SyntaxKind.SatisfiesExpression: + case SyntaxKind.ExpressionWithTypeArguments: + case SyntaxKind.NonNullExpression: + return isValidAssignmentTarget(node.expression); + default: + return false; + } +} +function getNamespaceModifiers(node) { + // For following nested namespaces, use modifiers given to the topmost namespace + // export declare namespace foo.bar.baz {} + let modifiers = (0, getModifiers_1.getModifiers)(node); + let moduleDeclaration = node; + while ((!modifiers || modifiers.length === 0) && + ts.isModuleDeclaration(moduleDeclaration.parent)) { + const parentModifiers = (0, getModifiers_1.getModifiers)(moduleDeclaration.parent); + if (parentModifiers?.length) { + modifiers = parentModifiers; + } + moduleDeclaration = moduleDeclaration.parent; + } + return modifiers; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.d.ts new file mode 100644 index 00000000..6de22f10 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.d.ts @@ -0,0 +1,17 @@ +import type { CacheDurationSeconds } from '@typescript-eslint/types'; +export declare const DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS = 30; +export interface CacheLike { + get(key: Key): Value | undefined; + set(key: Key, value: Value): this; +} +/** + * A map with key-level expiration. + */ +export declare class ExpiringCache implements CacheLike { + #private; + constructor(cacheDurationSeconds: CacheDurationSeconds); + clear(): void; + get(key: Key): Value | undefined; + set(key: Key, value: Value): this; +} +//# sourceMappingURL=ExpiringCache.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.d.ts.map new file mode 100644 index 00000000..25de4e08 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ExpiringCache.d.ts","sourceRoot":"","sources":["../../src/parseSettings/ExpiringCache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAErE,eAAO,MAAM,uCAAuC,KAAK,CAAC;AAG1D,MAAM,WAAW,SAAS,CAAC,GAAG,EAAE,KAAK;IACnC,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,KAAK,GAAG,SAAS,CAAC;IACjC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;CACnC;AAED;;GAEG;AACH,qBAAa,aAAa,CAAC,GAAG,EAAE,KAAK,CAAE,YAAW,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC;;gBAWzD,oBAAoB,EAAE,oBAAoB;IAItD,KAAK,IAAI,IAAI;IAIb,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,KAAK,GAAG,SAAS;IAmBhC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI;CAWlC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.js b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.js new file mode 100644 index 00000000..0571828a --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExpiringCache = exports.DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS = void 0; +exports.DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS = 30; +const ZERO_HR_TIME = [0, 0]; +/** + * A map with key-level expiration. + */ +class ExpiringCache { + #cacheDurationSeconds; + #map = new Map(); + constructor(cacheDurationSeconds) { + this.#cacheDurationSeconds = cacheDurationSeconds; + } + clear() { + this.#map.clear(); + } + get(key) { + const entry = this.#map.get(key); + if (entry?.value != null) { + if (this.#cacheDurationSeconds === 'Infinity') { + return entry.value; + } + const ageSeconds = process.hrtime(entry.lastSeen)[0]; + if (ageSeconds < this.#cacheDurationSeconds) { + // cache hit woo! + return entry.value; + } + // key has expired - clean it up to free up memory + this.#map.delete(key); + } + // no hit :'( + return undefined; + } + set(key, value) { + this.#map.set(key, { + lastSeen: this.#cacheDurationSeconds === 'Infinity' + ? // no need to waste time calculating the hrtime in infinity mode as there's no expiry + ZERO_HR_TIME + : process.hrtime(), + value, + }); + return this; + } +} +exports.ExpiringCache = ExpiringCache; diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.d.ts new file mode 100644 index 00000000..73af7479 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.d.ts @@ -0,0 +1,7 @@ +import * as ts from 'typescript'; +import type { TSESTreeOptions } from '../parser-options'; +import type { MutableParseSettings } from './index'; +export declare function createParseSettings(code: string | ts.SourceFile, tsestreeOptions?: Partial): MutableParseSettings; +export declare function clearTSConfigMatchCache(): void; +export declare function clearTSServerProjectService(): void; +//# sourceMappingURL=createParseSettings.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.d.ts.map new file mode 100644 index 00000000..004bf79a --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"createParseSettings.d.ts","sourceRoot":"","sources":["../../src/parseSettings/createParseSettings.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAiCpD,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,GAAG,EAAE,CAAC,UAAU,EAC5B,eAAe,GAAE,OAAO,CAAC,eAAe,CAAM,GAC7C,oBAAoB,CAwJtB;AAED,wBAAgB,uBAAuB,IAAI,IAAI,CAE9C;AAED,wBAAgB,2BAA2B,IAAI,IAAI,CAElD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.js b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.js new file mode 100644 index 00000000..bb234fcb --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.js @@ -0,0 +1,224 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createParseSettings = createParseSettings; +exports.clearTSConfigMatchCache = clearTSConfigMatchCache; +exports.clearTSServerProjectService = clearTSServerProjectService; +const project_service_1 = require("@typescript-eslint/project-service"); +const debug_1 = __importDefault(require("debug")); +const node_path_1 = __importDefault(require("node:path")); +const ts = __importStar(require("typescript")); +const shared_1 = require("../create-program/shared"); +const validateDefaultProjectForFilesGlob_1 = require("../create-program/validateDefaultProjectForFilesGlob"); +const source_files_1 = require("../source-files"); +const ExpiringCache_1 = require("./ExpiringCache"); +const getProjectConfigFiles_1 = require("./getProjectConfigFiles"); +const inferSingleRun_1 = require("./inferSingleRun"); +const resolveProjectList_1 = require("./resolveProjectList"); +const warnAboutTSVersion_1 = require("./warnAboutTSVersion"); +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:parseSettings:createParseSettings'); +let TSCONFIG_MATCH_CACHE; +let TSSERVER_PROJECT_SERVICE = null; +// NOTE - we intentionally use "unnecessary" `?.` here because in TS<5.3 this enum doesn't exist +// This object exists so we can centralize these for tracking and so we don't proliferate these across the file +// https://github.com/microsoft/TypeScript/issues/56579 +/* eslint-disable @typescript-eslint/no-unnecessary-condition */ +const JSDocParsingMode = { + ParseAll: ts.JSDocParsingMode?.ParseAll, + ParseForTypeErrors: ts.JSDocParsingMode?.ParseForTypeErrors, + ParseForTypeInfo: ts.JSDocParsingMode?.ParseForTypeInfo, + ParseNone: ts.JSDocParsingMode?.ParseNone, +}; +/* eslint-enable @typescript-eslint/no-unnecessary-condition */ +function createParseSettings(code, tsestreeOptions = {}) { + const codeFullText = enforceCodeString(code); + const singleRun = (0, inferSingleRun_1.inferSingleRun)(tsestreeOptions); + const tsconfigRootDir = typeof tsestreeOptions.tsconfigRootDir === 'string' + ? tsestreeOptions.tsconfigRootDir + : process.cwd(); + const passedLoggerFn = typeof tsestreeOptions.loggerFn === 'function'; + const filePath = (0, shared_1.ensureAbsolutePath)(typeof tsestreeOptions.filePath === 'string' && + tsestreeOptions.filePath !== '' + ? tsestreeOptions.filePath + : getFileName(tsestreeOptions.jsx), tsconfigRootDir); + const extension = node_path_1.default.extname(filePath).toLowerCase(); + const jsDocParsingMode = (() => { + switch (tsestreeOptions.jsDocParsingMode) { + case 'all': + return JSDocParsingMode.ParseAll; + case 'none': + return JSDocParsingMode.ParseNone; + case 'type-info': + return JSDocParsingMode.ParseForTypeInfo; + default: + return JSDocParsingMode.ParseAll; + } + })(); + const parseSettings = { + loc: tsestreeOptions.loc === true, + range: tsestreeOptions.range === true, + allowInvalidAST: tsestreeOptions.allowInvalidAST === true, + code, + codeFullText, + comment: tsestreeOptions.comment === true, + comments: [], + debugLevel: tsestreeOptions.debugLevel === true + ? new Set(['typescript-eslint']) + : Array.isArray(tsestreeOptions.debugLevel) + ? new Set(tsestreeOptions.debugLevel) + : new Set(), + errorOnTypeScriptSyntacticAndSemanticIssues: false, + errorOnUnknownASTType: tsestreeOptions.errorOnUnknownASTType === true, + extraFileExtensions: Array.isArray(tsestreeOptions.extraFileExtensions) && + tsestreeOptions.extraFileExtensions.every(ext => typeof ext === 'string') + ? tsestreeOptions.extraFileExtensions + : [], + filePath, + jsDocParsingMode, + jsx: tsestreeOptions.jsx === true, + log: typeof tsestreeOptions.loggerFn === 'function' + ? tsestreeOptions.loggerFn + : tsestreeOptions.loggerFn === false + ? () => { } // eslint-disable-line @typescript-eslint/no-empty-function + : console.log, // eslint-disable-line no-console + preserveNodeMaps: tsestreeOptions.preserveNodeMaps !== false, + programs: Array.isArray(tsestreeOptions.programs) + ? tsestreeOptions.programs + : null, + projects: new Map(), + projectService: tsestreeOptions.projectService || + (tsestreeOptions.project && + tsestreeOptions.projectService !== false && + process.env.TYPESCRIPT_ESLINT_PROJECT_SERVICE === 'true') + ? populateProjectService(tsestreeOptions.projectService, { + jsDocParsingMode, + tsconfigRootDir, + }) + : undefined, + setExternalModuleIndicator: tsestreeOptions.sourceType === 'module' || + (tsestreeOptions.sourceType == null && extension === ts.Extension.Mjs) || + (tsestreeOptions.sourceType == null && extension === ts.Extension.Mts) + ? (file) => { + file.externalModuleIndicator = true; + } + : undefined, + singleRun, + suppressDeprecatedPropertyWarnings: tsestreeOptions.suppressDeprecatedPropertyWarnings ?? + process.env.NODE_ENV !== 'test', + tokens: tsestreeOptions.tokens === true ? [] : null, + tsconfigMatchCache: (TSCONFIG_MATCH_CACHE ??= new ExpiringCache_1.ExpiringCache(singleRun + ? 'Infinity' + : (tsestreeOptions.cacheLifetime?.glob ?? + ExpiringCache_1.DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS))), + tsconfigRootDir, + }; + // debug doesn't support multiple `enable` calls, so have to do it all at once + if (parseSettings.debugLevel.size > 0) { + const namespaces = []; + if (parseSettings.debugLevel.has('typescript-eslint')) { + namespaces.push('typescript-eslint:*'); + } + if (parseSettings.debugLevel.has('eslint') || + // make sure we don't turn off the eslint debug if it was enabled via --debug + debug_1.default.enabled('eslint:*,-eslint:code-path')) { + // https://github.com/eslint/eslint/blob/9dfc8501fb1956c90dc11e6377b4cb38a6bea65d/bin/eslint.js#L25 + namespaces.push('eslint:*,-eslint:code-path'); + } + debug_1.default.enable(namespaces.join(',')); + } + if (Array.isArray(tsestreeOptions.programs)) { + if (!tsestreeOptions.programs.length) { + throw new Error(`You have set parserOptions.programs to an empty array. This will cause all files to not be found in existing programs. Either provide one or more existing TypeScript Program instances in the array, or remove the parserOptions.programs setting.`); + } + log('parserOptions.programs was provided, so parserOptions.project will be ignored.'); + } + // Providing a program or project service overrides project resolution + if (!parseSettings.programs && !parseSettings.projectService) { + parseSettings.projects = (0, resolveProjectList_1.resolveProjectList)({ + cacheLifetime: tsestreeOptions.cacheLifetime, + project: (0, getProjectConfigFiles_1.getProjectConfigFiles)(parseSettings, tsestreeOptions.project), + projectFolderIgnoreList: tsestreeOptions.projectFolderIgnoreList, + singleRun: parseSettings.singleRun, + tsconfigRootDir, + }); + } + // No type-aware linting which means that cross-file (or even same-file) JSDoc is useless + // So in this specific case we default to 'none' if no value was provided + if (tsestreeOptions.jsDocParsingMode == null && + parseSettings.projects.size === 0 && + parseSettings.programs == null && + parseSettings.projectService == null) { + parseSettings.jsDocParsingMode = JSDocParsingMode.ParseNone; + } + (0, warnAboutTSVersion_1.warnAboutTSVersion)(parseSettings, passedLoggerFn); + return parseSettings; +} +function clearTSConfigMatchCache() { + TSCONFIG_MATCH_CACHE?.clear(); +} +function clearTSServerProjectService() { + TSSERVER_PROJECT_SERVICE = null; +} +/** + * Ensures source code is a string. + */ +function enforceCodeString(code) { + return (0, source_files_1.isSourceFile)(code) + ? code.getFullText(code) + : typeof code === 'string' + ? code + : String(code); +} +/** + * Compute the filename based on the parser options. + * + * Even if jsx option is set in typescript compiler, filename still has to + * contain .tsx file extension. + */ +function getFileName(jsx) { + return jsx ? 'estree.tsx' : 'estree.ts'; +} +function populateProjectService(optionsRaw, settings) { + const options = typeof optionsRaw === 'object' ? optionsRaw : {}; + (0, validateDefaultProjectForFilesGlob_1.validateDefaultProjectForFilesGlob)(options.allowDefaultProject); + TSSERVER_PROJECT_SERVICE ??= (0, project_service_1.createProjectService)({ + options, + ...settings, + }); + return TSSERVER_PROJECT_SERVICE; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.d.ts new file mode 100644 index 00000000..76103cf8 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.d.ts @@ -0,0 +1,13 @@ +import type { TSESTreeOptions } from '../parser-options'; +import type { ParseSettings } from './index'; +/** + * Checks for a matching TSConfig to a file including its parent directories, + * permanently caching results under each directory it checks. + * + * @remarks + * We don't (yet!) have a way to attach file watchers on disk, but still need to + * cache file checks for rapid subsequent calls to fs.existsSync. See discussion + * in https://github.com/typescript-eslint/typescript-eslint/issues/101. + */ +export declare function getProjectConfigFiles(parseSettings: Pick, project: TSESTreeOptions['project']): string[] | null; +//# sourceMappingURL=getProjectConfigFiles.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.d.ts.map new file mode 100644 index 00000000..be48dc3b --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getProjectConfigFiles.d.ts","sourceRoot":"","sources":["../../src/parseSettings/getProjectConfigFiles.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAM7C;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,aAAa,EAAE,IAAI,CACjB,aAAa,EACb,UAAU,GAAG,oBAAoB,GAAG,iBAAiB,CACtD,EACD,OAAO,EAAE,eAAe,CAAC,SAAS,CAAC,GAClC,MAAM,EAAE,GAAG,IAAI,CAuCjB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.js b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.js new file mode 100644 index 00000000..f487c737 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.js @@ -0,0 +1,82 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getProjectConfigFiles = getProjectConfigFiles; +const debug_1 = __importDefault(require("debug")); +const fs = __importStar(require("node:fs")); +const path = __importStar(require("node:path")); +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:parseSettings:getProjectConfigFiles'); +/** + * Checks for a matching TSConfig to a file including its parent directories, + * permanently caching results under each directory it checks. + * + * @remarks + * We don't (yet!) have a way to attach file watchers on disk, but still need to + * cache file checks for rapid subsequent calls to fs.existsSync. See discussion + * in https://github.com/typescript-eslint/typescript-eslint/issues/101. + */ +function getProjectConfigFiles(parseSettings, project) { + if (project !== true) { + if (project == null || project === false) { + return null; + } + if (Array.isArray(project)) { + return project; + } + return [project]; + } + log('Looking for tsconfig.json at or above file: %s', parseSettings.filePath); + let directory = path.dirname(parseSettings.filePath); + const checkedDirectories = [directory]; + do { + log('Checking tsconfig.json path: %s', directory); + const tsconfigPath = path.join(directory, 'tsconfig.json'); + const cached = parseSettings.tsconfigMatchCache.get(directory) ?? + (fs.existsSync(tsconfigPath) && tsconfigPath); + if (cached) { + for (const directory of checkedDirectories) { + parseSettings.tsconfigMatchCache.set(directory, cached); + } + return [cached]; + } + directory = path.dirname(directory); + checkedDirectories.push(directory); + } while (directory.length > 1 && + directory.length >= parseSettings.tsconfigRootDir.length); + throw new Error(`project was set to \`true\` but couldn't find any tsconfig.json relative to '${parseSettings.filePath}' within '${parseSettings.tsconfigRootDir}'.`); +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/index.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/index.d.ts new file mode 100644 index 00000000..eb6b8d73 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/index.d.ts @@ -0,0 +1,127 @@ +import type { ProjectServiceAndMetadata } from '@typescript-eslint/project-service'; +import type * as ts from 'typescript'; +import type { CanonicalPath } from '../create-program/shared'; +import type { TSESTree } from '../ts-estree'; +import type { CacheLike } from './ExpiringCache'; +type DebugModule = 'eslint' | 'typescript' | 'typescript-eslint'; +declare module 'typescript' { + enum JSDocParsingMode { + } +} +declare module 'typescript/lib/tsserverlibrary' { + enum JSDocParsingMode { + } +} +/** + * Internal settings used by the parser to run on a file. + */ +export interface MutableParseSettings { + /** + * Prevents the parser from throwing an error if it receives an invalid AST from TypeScript. + */ + allowInvalidAST: boolean; + /** + * Code of the file being parsed, or raw source file containing it. + */ + code: string | ts.SourceFile; + /** + * Full text of the file being parsed. + */ + codeFullText: string; + /** + * Whether the `comment` parse option is enabled. + */ + comment: boolean; + /** + * If the `comment` parse option is enabled, retrieved comments. + */ + comments: TSESTree.Comment[]; + /** + * Which debug areas should be logged. + */ + debugLevel: Set; + /** + * Whether to error if TypeScript reports a semantic or syntactic error diagnostic. + */ + errorOnTypeScriptSyntacticAndSemanticIssues: boolean; + /** + * Whether to error if an unknown AST node type is encountered. + */ + errorOnUnknownASTType: boolean; + /** + * Any non-standard file extensions which will be parsed. + */ + extraFileExtensions: string[]; + /** + * Path of the file being parsed. + */ + filePath: string; + /** + * Sets the external module indicator on the source file. + * Used by Typescript to determine if a sourceFile is an external module. + * + * needed to always parsing `mjs`/`mts` files as ESM + */ + setExternalModuleIndicator?: (file: ts.SourceFile) => void; + /** + * JSDoc parsing style to pass through to TypeScript + */ + jsDocParsingMode: ts.JSDocParsingMode; + /** + * Whether parsing of JSX is enabled. + * + * @remarks The applicable file extension is still required. + */ + jsx: boolean; + /** + * Whether to add `loc` information to each node. + */ + loc: boolean; + /** + * Log function, if not `console.log`. + */ + log: (message: string) => void; + /** + * Whether two-way AST node maps are preserved during the AST conversion process. + */ + preserveNodeMaps?: boolean; + /** + * One or more instances of TypeScript Program objects to be used for type information. + */ + programs: Iterable | null; + /** + * Normalized paths to provided project paths. + */ + projects: ReadonlyMap; + /** + * TypeScript server to power program creation. + */ + projectService: ProjectServiceAndMetadata | undefined; + /** + * Whether to add the `range` property to AST nodes. + */ + range: boolean; + /** + * Whether this is part of a single run, rather than a long-running process. + */ + singleRun: boolean; + /** + * Whether deprecated AST properties should skip calling console.warn on accesses. + */ + suppressDeprecatedPropertyWarnings: boolean; + /** + * If the `tokens` parse option is enabled, retrieved tokens. + */ + tokens: TSESTree.Token[] | null; + /** + * Caches searches for TSConfigs from project directories. + */ + tsconfigMatchCache: CacheLike; + /** + * The absolute path to the root directory for all provided `project`s. + */ + tsconfigRootDir: string; +} +export type ParseSettings = Readonly; +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/index.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/index.d.ts.map new file mode 100644 index 00000000..b4b871fd --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/parseSettings/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AACpF,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,KAAK,WAAW,GAAG,QAAQ,GAAG,YAAY,GAAG,mBAAmB,CAAC;AAGjE,OAAO,QAAQ,YAAY,CAAC;IAE1B,KAAK,gBAAgB;KAAG;CACzB;AAED,OAAO,QAAQ,gCAAgC,CAAC;IAE9C,KAAK,gBAAgB;KAAG;CACzB;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,eAAe,EAAE,OAAO,CAAC;IAEzB;;OAEG;IACH,IAAI,EAAE,MAAM,GAAG,EAAE,CAAC,UAAU,CAAC;IAE7B;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB;;OAEG;IACH,QAAQ,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;IAE7B;;OAEG;IACH,UAAU,EAAE,GAAG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escript-estree/dist/parseSettings/index.js b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/index.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.d.ts new file mode 100644 index 00000000..1b28697f --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.d.ts @@ -0,0 +1,15 @@ +import type { TSESTreeOptions } from '../parser-options'; +/** + * ESLint (and therefore typescript-eslint) is used in both "single run"/one-time contexts, + * such as an ESLint CLI invocation, and long-running sessions (such as continuous feedback + * on a file in an IDE). + * + * When typescript-eslint handles TypeScript Program management behind the scenes, this distinction + * is important because there is significant overhead to managing the so called Watch Programs + * needed for the long-running use-case. We therefore use the following logic to figure out which + * of these contexts applies to the current execution. + * + * @returns Whether this is part of a single run, rather than a long-running process. + */ +export declare function inferSingleRun(options: TSESTreeOptions | undefined): boolean; +//# sourceMappingURL=inferSingleRun.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.d.ts.map new file mode 100644 index 00000000..0c3f82e8 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inferSingleRun.d.ts","sourceRoot":"","sources":["../../src/parseSettings/inferSingleRun.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEzD;;;;;;;;;;;GAWG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,eAAe,GAAG,SAAS,GAAG,OAAO,CAsD5E"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.js b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.js new file mode 100644 index 00000000..52c4af2f --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.js @@ -0,0 +1,65 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.inferSingleRun = inferSingleRun; +const node_path_1 = __importDefault(require("node:path")); +/** + * ESLint (and therefore typescript-eslint) is used in both "single run"/one-time contexts, + * such as an ESLint CLI invocation, and long-running sessions (such as continuous feedback + * on a file in an IDE). + * + * When typescript-eslint handles TypeScript Program management behind the scenes, this distinction + * is important because there is significant overhead to managing the so called Watch Programs + * needed for the long-running use-case. We therefore use the following logic to figure out which + * of these contexts applies to the current execution. + * + * @returns Whether this is part of a single run, rather than a long-running process. + */ +function inferSingleRun(options) { + // https://github.com/typescript-eslint/typescript-eslint/issues/9504 + // There's no support (yet?) for extraFileExtensions in single-run hosts. + // Only watch program hosts and project service can support that. + if (options?.extraFileExtensions?.length) { + return false; + } + if ( + // single-run implies type-aware linting - no projects means we can't be in single-run mode + options?.project == null || + // programs passed via options means the user should be managing the programs, so we shouldn't + // be creating our own single-run programs accidentally + options.programs != null) { + return false; + } + // Allow users to explicitly inform us of their intent to perform a single run (or not) with TSESTREE_SINGLE_RUN + if (process.env.TSESTREE_SINGLE_RUN === 'false') { + return false; + } + if (process.env.TSESTREE_SINGLE_RUN === 'true') { + return true; + } + // Ideally, we'd like to try to auto-detect CI or CLI usage that lets us infer a single CLI run. + if (!options.disallowAutomaticSingleRunInference) { + const possibleEslintBinPaths = [ + 'node_modules/.bin/eslint', // npm or yarn repo + 'node_modules/eslint/bin/eslint.js', // pnpm repo + ]; + if ( + // Default to single runs for CI processes. CI=true is set by most CI providers by default. + process.env.CI === 'true' || + // This will be true for invocations such as `npx eslint ...` and `./node_modules/.bin/eslint ...` + possibleEslintBinPaths.some(binPath => process.argv.length > 1 && + process.argv[1].endsWith(node_path_1.default.normalize(binPath)))) { + return !process.argv.includes('--fix'); + } + } + /** + * We default to assuming that this run could be part of a long-running session (e.g. in an IDE) + * and watch programs will therefore be required. + * + * Unless we can reliably infer otherwise, we default to assuming that this run could be part + * of a long-running session (e.g. in an IDE) and watch programs will therefore be required + */ + return false; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/resolveProjectList.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/resolveProjectList.d.ts new file mode 100644 index 00000000..4067aec9 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/resolveProjectList.d.ts @@ -0,0 +1,19 @@ +import type { CanonicalPath } from '../create-program/shared'; +import type { TSESTreeOptions } from '../parser-options'; +export declare function clearGlobCache(): void; +/** + * Normalizes, sanitizes, resolves and filters the provided project paths + */ +export declare function resolveProjectList(options: Readonly<{ + cacheLifetime?: TSESTreeOptions['cacheLifetime']; + project: string[] | null; + projectFolderIgnoreList: TSESTreeOptions['projectFolderIgnoreList']; + singleRun: boolean; + tsconfigRootDir: string; +}>): ReadonlyMap; +/** + * Exported for testing purposes only + * @internal + */ +export declare function clearGlobResolutionCache(): void; +//# sourceMappingURL=resolveProjectList.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/resolveProjectList.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/resolveProjectList.d.ts.map new file mode 100644 index 00000000..ac7258ed --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/resolveProjectList.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"resolveProjectList.d.ts","sourceRoot":"","sources":["../../src/parseSettings/resolveProjectList.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAqBzD,wBAAgB,cAAc,IAAI,IAAI,CAErC;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,QAAQ,CAAC;IAChB,aAAa,CAAC,EAAE,eAAe,CAAC,eAAe,CAAC,CAAC;IACjD,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACzB,uBAAuB,EAAE,eAAe,CAAC,yBAAyB,CAAC,CAAC;IACpE,SAAS,EAAE,OAAO,CAAC;IACnB,eAAe,EAAE,MAAM,CAAC;CACzB,CAAC,GACD,WAAW,CAAC,aAAa,EAAE,MAAM,CAAC,CAgFpC;AAuBD;;;GAGG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAG/C"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/resolveProjectList.js b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/resolveProjectList.js new file mode 100644 index 00000000..92f822a7 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/resolveProjectList.js @@ -0,0 +1,99 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.clearGlobCache = clearGlobCache; +exports.resolveProjectList = resolveProjectList; +exports.clearGlobResolutionCache = clearGlobResolutionCache; +const debug_1 = __importDefault(require("debug")); +const fast_glob_1 = require("fast-glob"); +const is_glob_1 = __importDefault(require("is-glob")); +const shared_1 = require("../create-program/shared"); +const ExpiringCache_1 = require("./ExpiringCache"); +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:parseSettings:resolveProjectList'); +let RESOLUTION_CACHE = null; +function clearGlobCache() { + RESOLUTION_CACHE?.clear(); +} +/** + * Normalizes, sanitizes, resolves and filters the provided project paths + */ +function resolveProjectList(options) { + const sanitizedProjects = []; + // Normalize and sanitize the project paths + if (options.project != null) { + for (const project of options.project) { + if (typeof project === 'string') { + sanitizedProjects.push(project); + } + } + } + if (sanitizedProjects.length === 0) { + return new Map(); + } + const projectFolderIgnoreList = (options.projectFolderIgnoreList ?? ['**/node_modules/**']) + .filter(folder => typeof folder === 'string') + // prefix with a ! for not match glob + .map(folder => (folder.startsWith('!') ? folder : `!${folder}`)); + const cacheKey = getHash({ + project: sanitizedProjects, + projectFolderIgnoreList, + tsconfigRootDir: options.tsconfigRootDir, + }); + if (RESOLUTION_CACHE == null) { + // note - we initialize the global cache based on the first config we encounter. + // this does mean that you can't have multiple lifetimes set per folder + // I doubt that anyone will really bother reconfiguring this, let alone + // try to do complicated setups, so we'll deal with this later if ever. + RESOLUTION_CACHE = new ExpiringCache_1.ExpiringCache(options.singleRun + ? 'Infinity' + : (options.cacheLifetime?.glob ?? + ExpiringCache_1.DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS)); + } + else { + const cached = RESOLUTION_CACHE.get(cacheKey); + if (cached) { + return cached; + } + } + // Transform glob patterns into paths + const nonGlobProjects = sanitizedProjects.filter(project => !(0, is_glob_1.default)(project)); + const globProjects = sanitizedProjects.filter(project => (0, is_glob_1.default)(project)); + let globProjectPaths = []; + if (globProjects.length > 0) { + // Although fast-glob supports multiple patterns, fast-glob returns arbitrary order of results + // to improve performance. To ensure the order is correct, we need to call fast-glob for each pattern + // separately and then concatenate the results in patterns' order. + globProjectPaths = globProjects.flatMap(pattern => (0, fast_glob_1.sync)(pattern, { + cwd: options.tsconfigRootDir, + ignore: projectFolderIgnoreList, + })); + } + const uniqueCanonicalProjectPaths = new Map([...nonGlobProjects, ...globProjectPaths].map(project => [ + (0, shared_1.getCanonicalFileName)((0, shared_1.ensureAbsolutePath)(project, options.tsconfigRootDir)), + (0, shared_1.ensureAbsolutePath)(project, options.tsconfigRootDir), + ])); + log('parserOptions.project (excluding ignored) matched projects: %s', uniqueCanonicalProjectPaths); + RESOLUTION_CACHE.set(cacheKey, uniqueCanonicalProjectPaths); + return uniqueCanonicalProjectPaths; +} +function getHash({ project, projectFolderIgnoreList, tsconfigRootDir, }) { + // create a stable representation of the config + const hashObject = { + tsconfigRootDir, + // the project order does matter and can impact the resolved globs + project, + // the ignore order won't doesn't ever matter + projectFolderIgnoreList: [...projectFolderIgnoreList].sort(), + }; + return (0, shared_1.createHash)(JSON.stringify(hashObject)); +} +/** + * Exported for testing purposes only + * @internal + */ +function clearGlobResolutionCache() { + RESOLUTION_CACHE?.clear(); + RESOLUTION_CACHE = null; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.d.ts new file mode 100644 index 00000000..88cc46d9 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.d.ts @@ -0,0 +1,7 @@ +import type { ParseSettings } from './index'; +/** + * This needs to be kept in sync with package.json in the typescript-eslint monorepo + */ +export declare const SUPPORTED_TYPESCRIPT_VERSIONS = ">=4.8.4 <5.9.0"; +export declare function warnAboutTSVersion(parseSettings: ParseSettings, passedLoggerFn: boolean): void; +//# sourceMappingURL=warnAboutTSVersion.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.d.ts.map new file mode 100644 index 00000000..c629dd6a --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"warnAboutTSVersion.d.ts","sourceRoot":"","sources":["../../src/parseSettings/warnAboutTSVersion.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAI7C;;GAEG;AACH,eAAO,MAAM,6BAA6B,mBAAmB,CAAC;AAe9D,wBAAgB,kBAAkB,CAChC,aAAa,EAAE,aAAa,EAC5B,cAAc,EAAE,OAAO,GACtB,IAAI,CA8BN"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.js b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.js new file mode 100644 index 00000000..d867b74a --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.js @@ -0,0 +1,81 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SUPPORTED_TYPESCRIPT_VERSIONS = void 0; +exports.warnAboutTSVersion = warnAboutTSVersion; +const semver_1 = __importDefault(require("semver")); +const ts = __importStar(require("typescript")); +const version_1 = require("../version"); +/** + * This needs to be kept in sync with package.json in the typescript-eslint monorepo + */ +exports.SUPPORTED_TYPESCRIPT_VERSIONS = '>=4.8.4 <5.9.0'; +/* + * The semver package will ignore prerelease ranges, and we don't want to explicitly document every one + * List them all separately here, so we can automatically create the full string + */ +const SUPPORTED_PRERELEASE_RANGES = []; +const ACTIVE_TYPESCRIPT_VERSION = ts.version; +const isRunningSupportedTypeScriptVersion = semver_1.default.satisfies(ACTIVE_TYPESCRIPT_VERSION, [exports.SUPPORTED_TYPESCRIPT_VERSIONS, ...SUPPORTED_PRERELEASE_RANGES].join(' || ')); +let warnedAboutTSVersion = false; +function warnAboutTSVersion(parseSettings, passedLoggerFn) { + if (isRunningSupportedTypeScriptVersion || warnedAboutTSVersion) { + return; + } + if (passedLoggerFn || + // See https://github.com/typescript-eslint/typescript-eslint/issues/7896 + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (typeof process === 'undefined' ? false : process.stdout?.isTTY)) { + const border = '============='; + const versionWarning = [ + border, + '\n', + 'WARNING: You are currently running a version of TypeScript which is not officially supported by @typescript-eslint/typescript-estree.', + '\n', + `* @typescript-eslint/typescript-estree version: ${version_1.version}`, + `* Supported TypeScript versions: ${exports.SUPPORTED_TYPESCRIPT_VERSIONS}`, + `* Your TypeScript version: ${ACTIVE_TYPESCRIPT_VERSION}`, + '\n', + 'Please only submit bug reports when using the officially supported version.', + '\n', + border, + ].join('\n'); + parseSettings.log(versionWarning); + } + warnedAboutTSVersion = true; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parser-options.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/parser-options.d.ts new file mode 100644 index 00000000..2eeb9d1a --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parser-options.d.ts @@ -0,0 +1,207 @@ +import type { CacheDurationSeconds, DebugLevel, JSDocParsingMode, ProjectServiceOptions, SourceType } from '@typescript-eslint/types'; +import type * as ts from 'typescript'; +import type { TSESTree, TSESTreeToTSNode, TSNode, TSToken } from './ts-estree'; +interface ParseOptions { + /** + * Specify the `sourceType`. + * For more details, see https://github.com/typescript-eslint/typescript-eslint/pull/9121 + */ + sourceType?: SourceType; + /** + * Prevents the parser from throwing an error if it receives an invalid AST from TypeScript. + * This case only usually occurs when attempting to lint invalid code. + */ + allowInvalidAST?: boolean; + /** + * create a top-level comments array containing all comments + */ + comment?: boolean; + /** + * An array of modules to turn explicit debugging on for. + * - 'typescript-eslint' is the same as setting the env var `DEBUG=typescript-eslint:*` + * - 'eslint' is the same as setting the env var `DEBUG=eslint:*` + * - 'typescript' is the same as setting `extendedDiagnostics: true` in your tsconfig compilerOptions + * + * For convenience, also supports a boolean: + * - true === ['typescript-eslint'] + * - false === [] + */ + debugLevel?: DebugLevel; + /** + * Cause the parser to error if it encounters an unknown AST node type (useful for testing). + * This case only usually occurs when TypeScript releases new features. + */ + errorOnUnknownASTType?: boolean; + /** + * Absolute (or relative to `cwd`) path to the file being parsed. + */ + filePath?: string; + /** + * If you are using TypeScript version >=5.3 then this option can be used as a performance optimization. + * + * The valid values for this rule are: + * - `'all'` - parse all JSDoc comments, always. + * - `'none'` - parse no JSDoc comments, ever. + * - `'type-info'` - parse just JSDoc comments that are required to provide correct type-info. TS will always parse JSDoc in non-TS files, but never in TS files. + * + * If you do not rely on JSDoc tags from the TypeScript AST, then you can safely set this to `'none'` to improve performance. + */ + jsDocParsingMode?: JSDocParsingMode; + /** + * Enable parsing of JSX. + * For more details, see https://www.typescriptlang.org/docs/handbook/jsx.html + * + * NOTE: this setting does not effect known file types (.js, .cjs, .mjs, .jsx, .ts, .mts, .cts, .tsx, .json) because the + * TypeScript compiler has its own internal handling for known file extensions. + * + * For the exact behavior, see https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/parser#parseroptionsecmafeaturesjsx + */ + jsx?: boolean; + /** + * Controls whether the `loc` information to each node. + * The `loc` property is an object which contains the exact line/column the node starts/ends on. + * This is similar to the `range` property, except it is line/column relative. + */ + loc?: boolean; + loggerFn?: ((message: string) => void) | false; + /** + * Controls whether the `range` property is included on AST nodes. + * The `range` property is a [number, number] which indicates the start/end index of the node in the file contents. + * This is similar to the `loc` property, except this is the absolute index. + */ + range?: boolean; + /** + * Set to true to create a top-level array containing all tokens from the file. + */ + tokens?: boolean; + /** + * Whether deprecated AST properties should skip calling console.warn on accesses. + */ + suppressDeprecatedPropertyWarnings?: boolean; +} +interface ParseAndGenerateServicesOptions extends ParseOptions { + /** + * Granular control of the expiry lifetime of our internal caches. + * You can specify the number of seconds as an integer number, or the string + * 'Infinity' if you never want the cache to expire. + * + * By default cache entries will be evicted after 30 seconds, or will persist + * indefinitely if `disallowAutomaticSingleRunInference = false` AND the parser + * infers that it is a single run. + */ + cacheLifetime?: { + /** + * Glob resolution for `parserOptions.project` values. + */ + glob?: CacheDurationSeconds; + }; + /** + * ESLint (and therefore typescript-eslint) is used in both "single run"/one-time contexts, + * such as an ESLint CLI invocation, and long-running sessions (such as continuous feedback + * on a file in an IDE). + * + * When typescript-eslint handles TypeScript Program management behind the scenes, this distinction + * is important because there is significant overhead to managing the so called Watch Programs + * needed for the long-running use-case. + * + * By default, we will use common heuristics to infer whether ESLint is being + * used as part of a single run. This option disables those heuristics, and + * therefore the performance optimizations gained by them. + * + * In other words, typescript-eslint is faster by default, and this option + * disables an automatic performance optimization. + * + * This setting's default value can be specified by setting a `TSESTREE_SINGLE_RUN` + * environment variable to `"false"` or `"true"`. + * Otherwise, the default value is `false`. + */ + disallowAutomaticSingleRunInference?: boolean; + /** + * Causes the parser to error if the TypeScript compiler returns any unexpected syntax/semantic errors. + */ + errorOnTypeScriptSyntacticAndSemanticIssues?: boolean; + /** + * When `project` is provided, this controls the non-standard file extensions which will be parsed. + * It accepts an array of file extensions, each preceded by a `.`. + * + * NOTE: When used with {@link projectService}, full project reloads may occur. + */ + extraFileExtensions?: string[]; + /** + * Absolute (or relative to `tsconfigRootDir`) path to the file being parsed. + * When `project` is provided, this is required, as it is used to fetch the file from the TypeScript compiler's cache. + */ + filePath?: string; + /** + * Allows the user to control whether or not two-way AST node maps are preserved + * during the AST conversion process. + * + * By default: the AST node maps are NOT preserved, unless `project` has been specified, + * in which case the maps are made available on the returned `parserServices`. + * + * NOTE: If `preserveNodeMaps` is explicitly set by the user, it will be respected, + * regardless of whether or not `project` is in use. + */ + preserveNodeMaps?: boolean; + /** + * Absolute (or relative to `tsconfigRootDir`) paths to the tsconfig(s), + * or `true` to find the nearest tsconfig.json to the file. + * If this is provided, type information will be returned. + * + * If set to `false`, `null` or `undefined` type information will not be returned. + * + * Note that {@link projectService} is now preferred. + */ + project?: boolean | string | string[] | null; + /** + * If you provide a glob (or globs) to the project option, you can use this option to ignore certain folders from + * being matched by the globs. + * This accepts an array of globs to ignore. + * + * By default, this is set to ["**\/node_modules/**"] + */ + projectFolderIgnoreList?: string[]; + /** + * Whether to create a shared TypeScript project service to power program creation. + */ + projectService?: boolean | ProjectServiceOptions; + /** + * The absolute path to the root directory for all provided `project`s. + */ + tsconfigRootDir?: string; + /** + * An array of one or more instances of TypeScript Program objects to be used for type information. + * This overrides any program or programs that would have been computed from the `project` option. + * All linted files must be part of the provided program(s). + */ + programs?: ts.Program[] | null; +} +export type TSESTreeOptions = ParseAndGenerateServicesOptions; +export interface ParserWeakMap { + get(key: Key): Value; + has(key: unknown): boolean; +} +export interface ParserWeakMapESTreeToTSNode { + get(key: KeyBase): TSESTreeToTSNode; + has(key: unknown): boolean; +} +export interface ParserServicesBase { + emitDecoratorMetadata: boolean | undefined; + experimentalDecorators: boolean | undefined; + isolatedDeclarations: boolean | undefined; +} +export interface ParserServicesNodeMaps { + esTreeNodeToTSNodeMap: ParserWeakMapESTreeToTSNode; + tsNodeToESTreeNodeMap: ParserWeakMap; +} +export interface ParserServicesWithTypeInformation extends ParserServicesNodeMaps, ParserServicesBase { + getSymbolAtLocation: (node: TSESTree.Node) => ts.Symbol | undefined; + getTypeAtLocation: (node: TSESTree.Node) => ts.Type; + program: ts.Program; +} +export interface ParserServicesWithoutTypeInformation extends ParserServicesNodeMaps, ParserServicesBase { + program: null; +} +export type ParserServices = ParserServicesWithoutTypeInformation | ParserServicesWithTypeInformation; +export {}; +//# sourceMappingURL=parser-options.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parser-options.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/parser-options.d.ts.map new file mode 100644 index 00000000..bfa1b4ae --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parser-options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parser-options.d.ts","sourceRoot":"","sources":["../src/parser-options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EACpB,UAAU,EACV,gBAAgB,EAChB,qBAAqB,EACrB,UAAU,EACX,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAM/E,UAAU,YAAY;IACpB;;;OAGG;IACH,UAAU,CAAC,EAAE,UAAU,CAAC;IAExB;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;;;;;;;;OASG;IACH,UAAU,CAAC,EAAE,UAAU,CAAC;IAExB;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAEhC;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;IAEpC;;;;;;;;OAQG;IACH,GAAG,CAAC,EAAE,OAAO,CAAC;IAEd;;;;OAIG;IACH,GAAG,CAAC,EAAE,OAAO,CAAC;IAOd,QAAQ,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,KAAK,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AAG,SAAS,QAAQ,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI;IAEzC,GAAG,CAAC,OAAO,SAAS,GAAG,EAAE,GAAG,EAAE,OAAO,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAClE,GAAG,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC;CAC5B;AAED,MAAM,WAAW,kBAAkB;IACjC,qBAAqB,EAAE,OAAO,GAAG,SAAS,CAAC;IAC3C,sBAAsB,EAAE,OAAO,GAAG,SAAS,CAAC;IAC5C,oBAAoB,EAAE,OAAO,GAAG,SAAS,CAAC;CAC3C;AACD,MAAM,WAAW,sBAAsB;IACrC,qBAAqB,EAAE,2BAA2B,CAAC;IACnD,qBAAqB,EAAE,aAAa,CAAC,MAAM,GAAG,OAAO,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;CACvE;AACD,MAAM,WAAW,iCACf,SAAQ,sBAAsB,EAC5B,kBAAkB;IACpB,mBAAmB,EAAE,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,KAAK,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC;IACpE,iBAAiB,EAAE,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,KAAK,EAAE,CAAC,IAAI,CAAC;IACpD,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC;CACrB;AACD,MAAM,WAAW,oCACf,SAAQ,sBAAsB,EAC5B,kBAAkB;IACpB,OAAO,EAAE,IAAI,CAAC;CACf;AACD,MAAM,MAAM,cAAc,GACtB,oCAAoC,GACpC,iCAAiC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parser-options.js b/node_modules/@typescript-eslint/typescript-estree/dist/parser-options.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parser-options.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parser.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/parser.d.ts new file mode 100644 index 00000000..a2c01042 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parser.d.ts @@ -0,0 +1,18 @@ +import type * as ts from 'typescript'; +import type { ParserServices, TSESTreeOptions } from './parser-options'; +import type { TSESTree } from './ts-estree'; +export declare function clearProgramCache(): void; +export declare function clearDefaultProjectMatchedFiles(): void; +export type AST = (T['comment'] extends true ? { + comments: TSESTree.Comment[]; +} : {}) & (T['tokens'] extends true ? { + tokens: TSESTree.Token[]; +} : {}) & TSESTree.Program; +export interface ParseAndGenerateServicesResult { + ast: AST; + services: ParserServices; +} +export declare function parse(code: string, options?: T): AST; +export declare function clearParseAndGenerateServicesCalls(): void; +export declare function parseAndGenerateServices(code: string | ts.SourceFile, tsestreeOptions: T): ParseAndGenerateServicesResult; +//# sourceMappingURL=parser.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parser.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/parser.d.ts.map new file mode 100644 index 00000000..7e286db1 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../src/parser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAKtC,OAAO,KAAK,EACV,cAAc,EAEd,eAAe,EAChB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AA4B5C,wBAAgB,iBAAiB,IAAI,IAAI,CAExC;AAGD,wBAAgB,+BAA+B,IAAI,IAAI,CAEtD;AA8CD,MAAM,MAAM,GAAG,CAAC,CAAC,SAAS,eAAe,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,IAAI,GACnE;IAAE,QAAQ,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAA;CAAE,GAChC,EAAE,CAAC,GACL,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,IAAI,GAAG;IAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAA;CAAE,GAAG,EAAE,CAAC,GAC9D,QAAQ,CAAC,OAAO,CAAC;AAGnB,MAAM,WAAW,8BAA8B,CAAC,CAAC,SAAS,eAAe;IACvE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IACZ,QAAQ,EAAE,cAAc,CAAC;CAC1B;AAMD,wBAAgB,KAAK,CAAC,CAAC,SAAS,eAAe,GAAG,eAAe,EAC/D,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,CAAC,GACV,GAAG,CAAC,CAAC,CAAC,CAGR;AA4CD,wBAAgB,kCAAkC,IAAI,IAAI,CAEzD;AAED,wBAAgB,wBAAwB,CACtC,CAAC,SAAS,eAAe,GAAG,eAAe,EAE3C,IAAI,EAAE,MAAM,GAAG,EAAE,CAAC,UAAU,EAC5B,eAAe,EAAE,CAAC,GACjB,8BAA8B,CAAC,CAAC,CAAC,CA+GnC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/parser.js b/node_modules/@typescript-eslint/typescript-estree/dist/parser.js new file mode 100644 index 00000000..8fb3aa2f --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/parser.js @@ -0,0 +1,180 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.clearProgramCache = clearProgramCache; +exports.clearDefaultProjectMatchedFiles = clearDefaultProjectMatchedFiles; +exports.parse = parse; +exports.clearParseAndGenerateServicesCalls = clearParseAndGenerateServicesCalls; +exports.parseAndGenerateServices = parseAndGenerateServices; +const debug_1 = __importDefault(require("debug")); +const ast_converter_1 = require("./ast-converter"); +const convert_1 = require("./convert"); +const createIsolatedProgram_1 = require("./create-program/createIsolatedProgram"); +const createProjectProgram_1 = require("./create-program/createProjectProgram"); +const createSourceFile_1 = require("./create-program/createSourceFile"); +const getWatchProgramsForProjects_1 = require("./create-program/getWatchProgramsForProjects"); +const useProvidedPrograms_1 = require("./create-program/useProvidedPrograms"); +const createParserServices_1 = require("./createParserServices"); +const createParseSettings_1 = require("./parseSettings/createParseSettings"); +const semantic_or_syntactic_errors_1 = require("./semantic-or-syntactic-errors"); +const useProgramFromProjectService_1 = require("./useProgramFromProjectService"); +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:parser'); +/** + * Cache existing programs for the single run use-case. + * + * clearProgramCache() is only intended to be used in testing to ensure the parser is clean between tests. + */ +const existingPrograms = new Map(); +function clearProgramCache() { + existingPrograms.clear(); +} +const defaultProjectMatchedFiles = new Set(); +function clearDefaultProjectMatchedFiles() { + defaultProjectMatchedFiles.clear(); +} +/** + * @param parseSettings Internal settings for parsing the file + * @param hasFullTypeInformation True if the program should be attempted to be calculated from provided tsconfig files + * @returns Returns a source file and program corresponding to the linted code + */ +function getProgramAndAST(parseSettings, hasFullTypeInformation) { + if (parseSettings.projectService) { + const fromProjectService = (0, useProgramFromProjectService_1.useProgramFromProjectService)(parseSettings.projectService, parseSettings, hasFullTypeInformation, defaultProjectMatchedFiles); + if (fromProjectService) { + return fromProjectService; + } + } + if (parseSettings.programs) { + const fromProvidedPrograms = (0, useProvidedPrograms_1.useProvidedPrograms)(parseSettings.programs, parseSettings); + if (fromProvidedPrograms) { + return fromProvidedPrograms; + } + } + // no need to waste time creating a program as the caller didn't want parser services + // so we can save time and just create a lonesome source file + if (!hasFullTypeInformation) { + return (0, createSourceFile_1.createNoProgram)(parseSettings); + } + return (0, createProjectProgram_1.createProjectProgram)(parseSettings, (0, getWatchProgramsForProjects_1.getWatchProgramsForProjects)(parseSettings)); +} +function parse(code, options) { + const { ast } = parseWithNodeMapsInternal(code, options, false); + return ast; +} +function parseWithNodeMapsInternal(code, options, shouldPreserveNodeMaps) { + /** + * Reset the parse configuration + */ + const parseSettings = (0, createParseSettings_1.createParseSettings)(code, options); + /** + * Ensure users do not attempt to use parse() when they need parseAndGenerateServices() + */ + if (options?.errorOnTypeScriptSyntacticAndSemanticIssues) { + throw new Error(`"errorOnTypeScriptSyntacticAndSemanticIssues" is only supported for parseAndGenerateServices()`); + } + /** + * Create a ts.SourceFile directly, no ts.Program is needed for a simple parse + */ + const ast = (0, createSourceFile_1.createSourceFile)(parseSettings); + /** + * Convert the TypeScript AST to an ESTree-compatible one + */ + const { astMaps, estree } = (0, ast_converter_1.astConverter)(ast, parseSettings, shouldPreserveNodeMaps); + return { + ast: estree, + esTreeNodeToTSNodeMap: astMaps.esTreeNodeToTSNodeMap, + tsNodeToESTreeNodeMap: astMaps.tsNodeToESTreeNodeMap, + }; +} +let parseAndGenerateServicesCalls = {}; +// Privately exported utility intended for use in typescript-eslint unit tests only +function clearParseAndGenerateServicesCalls() { + parseAndGenerateServicesCalls = {}; +} +function parseAndGenerateServices(code, tsestreeOptions) { + /** + * Reset the parse configuration + */ + const parseSettings = (0, createParseSettings_1.createParseSettings)(code, tsestreeOptions); + /** + * If this is a single run in which the user has not provided any existing programs but there + * are programs which need to be created from the provided "project" option, + * create an Iterable which will lazily create the programs as needed by the iteration logic + */ + if (parseSettings.singleRun && + !parseSettings.programs && + parseSettings.projects.size > 0) { + parseSettings.programs = { + *[Symbol.iterator]() { + for (const configFile of parseSettings.projects) { + const existingProgram = existingPrograms.get(configFile[0]); + if (existingProgram) { + yield existingProgram; + } + else { + log('Detected single-run/CLI usage, creating Program once ahead of time for project: %s', configFile); + const newProgram = (0, useProvidedPrograms_1.createProgramFromConfigFile)(configFile[1]); + existingPrograms.set(configFile[0], newProgram); + yield newProgram; + } + } + }, + }; + } + const hasFullTypeInformation = parseSettings.programs != null || + parseSettings.projects.size > 0 || + !!parseSettings.projectService; + if (typeof tsestreeOptions.errorOnTypeScriptSyntacticAndSemanticIssues === + 'boolean' && + tsestreeOptions.errorOnTypeScriptSyntacticAndSemanticIssues) { + parseSettings.errorOnTypeScriptSyntacticAndSemanticIssues = true; + } + if (parseSettings.errorOnTypeScriptSyntacticAndSemanticIssues && + !hasFullTypeInformation) { + throw new Error('Cannot calculate TypeScript semantic issues without a valid project.'); + } + /** + * If we are in singleRun mode but the parseAndGenerateServices() function has been called more than once for the current file, + * it must mean that we are in the middle of an ESLint automated fix cycle (in which parsing can be performed up to an additional + * 10 times in order to apply all possible fixes for the file). + * + * In this scenario we cannot rely upon the singleRun AOT compiled programs because the SourceFiles will not contain the source + * with the latest fixes applied. Therefore we fallback to creating the quickest possible isolated program from the updated source. + */ + if (parseSettings.singleRun && tsestreeOptions.filePath) { + parseAndGenerateServicesCalls[tsestreeOptions.filePath] = + (parseAndGenerateServicesCalls[tsestreeOptions.filePath] || 0) + 1; + } + const { ast, program } = parseSettings.singleRun && + tsestreeOptions.filePath && + parseAndGenerateServicesCalls[tsestreeOptions.filePath] > 1 + ? (0, createIsolatedProgram_1.createIsolatedProgram)(parseSettings) + : getProgramAndAST(parseSettings, hasFullTypeInformation); + /** + * Convert the TypeScript AST to an ESTree-compatible one, and optionally preserve + * mappings between converted and original AST nodes + */ + const shouldPreserveNodeMaps = typeof parseSettings.preserveNodeMaps === 'boolean' + ? parseSettings.preserveNodeMaps + : true; + const { astMaps, estree } = (0, ast_converter_1.astConverter)(ast, parseSettings, shouldPreserveNodeMaps); + /** + * Even if TypeScript parsed the source code ok, and we had no problems converting the AST, + * there may be other syntactic or semantic issues in the code that we can optionally report on. + */ + if (program && parseSettings.errorOnTypeScriptSyntacticAndSemanticIssues) { + const error = (0, semantic_or_syntactic_errors_1.getFirstSemanticOrSyntacticError)(program, ast); + if (error) { + throw (0, convert_1.convertError)(error); + } + } + /** + * Return the converted AST and additional parser services + */ + return { + ast: estree, + services: (0, createParserServices_1.createParserServices)(astMaps, program), + }; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/semantic-or-syntactic-errors.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/semantic-or-syntactic-errors.d.ts new file mode 100644 index 00000000..bd35968c --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/semantic-or-syntactic-errors.d.ts @@ -0,0 +1,13 @@ +import type { Diagnostic, Program, SourceFile } from 'typescript'; +export interface SemanticOrSyntacticError extends Diagnostic { + message: string; +} +/** + * By default, diagnostics from the TypeScript compiler contain all errors - regardless of whether + * they are related to generic ECMAScript standards, or TypeScript-specific constructs. + * + * Therefore, we filter out all diagnostics, except for the ones we explicitly want to consider when + * the user opts in to throwing errors on semantic issues. + */ +export declare function getFirstSemanticOrSyntacticError(program: Program, ast: SourceFile): SemanticOrSyntacticError | undefined; +//# sourceMappingURL=semantic-or-syntactic-errors.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/semantic-or-syntactic-errors.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/semantic-or-syntactic-errors.d.ts.map new file mode 100644 index 00000000..63d13a71 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/semantic-or-syntactic-errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"semantic-or-syntactic-errors.d.ts","sourceRoot":"","sources":["../src/semantic-or-syntactic-errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EAEV,OAAO,EACP,UAAU,EACX,MAAM,YAAY,CAAC;AAIpB,MAAM,WAAW,wBAAyB,SAAQ,UAAU;IAC1D,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,UAAU,GACd,wBAAwB,GAAG,SAAS,CAmCtC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/semantic-or-syntactic-errors.js b/node_modules/@typescript-eslint/typescript-estree/dist/semantic-or-syntactic-errors.js new file mode 100644 index 00000000..5e77d97c --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/semantic-or-syntactic-errors.js @@ -0,0 +1,94 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getFirstSemanticOrSyntacticError = getFirstSemanticOrSyntacticError; +const typescript_1 = require("typescript"); +/** + * By default, diagnostics from the TypeScript compiler contain all errors - regardless of whether + * they are related to generic ECMAScript standards, or TypeScript-specific constructs. + * + * Therefore, we filter out all diagnostics, except for the ones we explicitly want to consider when + * the user opts in to throwing errors on semantic issues. + */ +function getFirstSemanticOrSyntacticError(program, ast) { + try { + const supportedSyntacticDiagnostics = allowlistSupportedDiagnostics(program.getSyntacticDiagnostics(ast)); + if (supportedSyntacticDiagnostics.length > 0) { + return convertDiagnosticToSemanticOrSyntacticError(supportedSyntacticDiagnostics[0]); + } + const supportedSemanticDiagnostics = allowlistSupportedDiagnostics(program.getSemanticDiagnostics(ast)); + if (supportedSemanticDiagnostics.length > 0) { + return convertDiagnosticToSemanticOrSyntacticError(supportedSemanticDiagnostics[0]); + } + return undefined; + } + catch (e) { + /** + * TypeScript compiler has certain Debug.fail() statements in, which will cause the diagnostics + * retrieval above to throw. + * + * E.g. from ast-alignment-tests + * "Debug Failure. Shouldn't ever directly check a JsxOpeningElement" + * + * For our current use-cases this is undesired behavior, so we just suppress it + * and log a warning. + */ + /* istanbul ignore next */ + console.warn(`Warning From TSC: "${e.message}`); // eslint-disable-line no-console + /* istanbul ignore next */ + return undefined; + } +} +function allowlistSupportedDiagnostics(diagnostics) { + return diagnostics.filter(diagnostic => { + switch (diagnostic.code) { + case 1013: // "A rest parameter or binding pattern may not have a trailing comma." + case 1014: // "A rest parameter must be last in a parameter list." + case 1044: // "'{0}' modifier cannot appear on a module or namespace element." + case 1045: // "A '{0}' modifier cannot be used with an interface declaration." + case 1048: // "A rest parameter cannot have an initializer." + case 1049: // "A 'set' accessor must have exactly one parameter." + case 1070: // "'{0}' modifier cannot appear on a type member." + case 1071: // "'{0}' modifier cannot appear on an index signature." + case 1085: // "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'." + case 1090: // "'{0}' modifier cannot appear on a parameter." + case 1096: // "An index signature must have exactly one parameter." + case 1097: // "'{0}' list cannot be empty." + case 1098: // "Type parameter list cannot be empty." + case 1099: // "Type argument list cannot be empty." + case 1117: // "An object literal cannot have multiple properties with the same name in strict mode." + case 1121: // "Octal literals are not allowed in strict mode." + case 1123: // "Variable declaration list cannot be empty." + case 1141: // "String literal expected." + case 1162: // "An object member cannot be declared optional." + case 1164: // "Computed property names are not allowed in enums." + case 1172: // "'extends' clause already seen." + case 1173: // "'extends' clause must precede 'implements' clause." + case 1175: // "'implements' clause already seen." + case 1176: // "Interface declaration cannot have 'implements' clause." + case 1190: // "The variable declaration of a 'for...of' statement cannot have an initializer." + case 1196: // "Catch clause variable type annotation must be 'any' or 'unknown' if specified." + case 1200: // "Line terminator not permitted before arrow." + case 1206: // "Decorators are not valid here." + case 1211: // "A class declaration without the 'default' modifier must have a name." + case 1242: // "'abstract' modifier can only appear on a class, method, or property declaration." + case 1246: // "An interface property cannot have an initializer." + case 1255: // "A definite assignment assertion '!' is not permitted in this context." + case 1308: // "'await' expression is only allowed within an async function." + case 2364: // "The left-hand side of an assignment expression must be a variable or a property access." + case 2369: // "A parameter property is only allowed in a constructor implementation." + case 2452: // "An enum member cannot have a numeric name." + case 2462: // "A rest element must be last in a destructuring pattern." + case 8017: // "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." + case 17012: // "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?" + case 17013: // "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor." + return true; + } + return false; + }); +} +function convertDiagnosticToSemanticOrSyntacticError(diagnostic) { + return { + ...diagnostic, + message: (0, typescript_1.flattenDiagnosticMessageText)(diagnostic.messageText, typescript_1.sys.newLine), + }; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/simple-traverse.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/simple-traverse.d.ts new file mode 100644 index 00000000..9b6b4c67 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/simple-traverse.d.ts @@ -0,0 +1,12 @@ +import type { VisitorKeys } from '@typescript-eslint/visitor-keys'; +import type { TSESTree } from './ts-estree'; +type SimpleTraverseOptions = Readonly<{ + enter: (node: TSESTree.Node, parent: TSESTree.Node | undefined) => void; + visitorKeys?: Readonly; +} | { + visitorKeys?: Readonly; + visitors: Record void>; +}>; +export declare function simpleTraverse(startingNode: TSESTree.Node, options: SimpleTraverseOptions, setParentPointers?: boolean): void; +export {}; +//# sourceMappingURL=simple-traverse.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/simple-traverse.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/simple-traverse.d.ts.map new file mode 100644 index 00000000..9abec97f --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/simple-traverse.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simple-traverse.d.ts","sourceRoot":"","sources":["../src/simple-traverse.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAInE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAmB5C,KAAK,qBAAqB,GAAG,QAAQ,CACjC;IACE,KAAK,EAAE,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,IAAI,GAAG,SAAS,KAAK,IAAI,CAAC;IACxE,WAAW,CAAC,EAAE,QAAQ,CAAC,WAAW,CAAC,CAAC;CACrC,GACD;IACE,WAAW,CAAC,EAAE,QAAQ,CAAC,WAAW,CAAC,CAAC;IACpC,QAAQ,EAAE,MAAM,CACd,MAAM,EACN,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,IAAI,GAAG,SAAS,KAAK,IAAI,CACjE,CAAC;CACH,CACJ,CAAC;AAiDF,wBAAgB,cAAc,CAC5B,YAAY,EAAE,QAAQ,CAAC,IAAI,EAC3B,OAAO,EAAE,qBAAqB,EAC9B,iBAAiB,UAAQ,GACxB,IAAI,CAKN"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/simple-traverse.js b/node_modules/@typescript-eslint/typescript-estree/dist/simple-traverse.js new file mode 100644 index 00000000..6960df2a --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/simple-traverse.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.simpleTraverse = simpleTraverse; +const visitor_keys_1 = require("@typescript-eslint/visitor-keys"); +function isValidNode(x) { + return (typeof x === 'object' && + x != null && + 'type' in x && + typeof x.type === 'string'); +} +function getVisitorKeysForNode(allVisitorKeys, node) { + const keys = allVisitorKeys[node.type]; + return (keys ?? []); +} +class SimpleTraverser { + allVisitorKeys = visitor_keys_1.visitorKeys; + selectors; + setParentPointers; + constructor(selectors, setParentPointers = false) { + this.selectors = selectors; + this.setParentPointers = setParentPointers; + if (selectors.visitorKeys) { + this.allVisitorKeys = selectors.visitorKeys; + } + } + traverse(node, parent) { + if (!isValidNode(node)) { + return; + } + if (this.setParentPointers) { + node.parent = parent; + } + if ('enter' in this.selectors) { + this.selectors.enter(node, parent); + } + else if (node.type in this.selectors.visitors) { + this.selectors.visitors[node.type](node, parent); + } + const keys = getVisitorKeysForNode(this.allVisitorKeys, node); + if (keys.length < 1) { + return; + } + for (const key of keys) { + const childOrChildren = node[key]; + if (Array.isArray(childOrChildren)) { + for (const child of childOrChildren) { + this.traverse(child, node); + } + } + else { + this.traverse(childOrChildren, node); + } + } + } +} +function simpleTraverse(startingNode, options, setParentPointers = false) { + new SimpleTraverser(options, setParentPointers).traverse(startingNode, undefined); +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/source-files.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/source-files.d.ts new file mode 100644 index 00000000..756b7815 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/source-files.d.ts @@ -0,0 +1,4 @@ +import * as ts from 'typescript'; +export declare function isSourceFile(code: unknown): code is ts.SourceFile; +export declare function getCodeText(code: string | ts.SourceFile): string; +//# sourceMappingURL=source-files.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/source-files.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/source-files.d.ts.map new file mode 100644 index 00000000..68685a97 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/source-files.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"source-files.d.ts","sourceRoot":"","sources":["../src/source-files.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAEjC,wBAAgB,YAAY,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,EAAE,CAAC,UAAU,CAUjE;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,EAAE,CAAC,UAAU,GAAG,MAAM,CAEhE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/source-files.js b/node_modules/@typescript-eslint/typescript-estree/dist/source-files.js new file mode 100644 index 00000000..51151c0e --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/source-files.js @@ -0,0 +1,49 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isSourceFile = isSourceFile; +exports.getCodeText = getCodeText; +const ts = __importStar(require("typescript")); +function isSourceFile(code) { + if (typeof code !== 'object' || code == null) { + return false; + } + const maybeSourceFile = code; + return (maybeSourceFile.kind === ts.SyntaxKind.SourceFile && + typeof maybeSourceFile.getFullText === 'function'); +} +function getCodeText(code) { + return isSourceFile(code) ? code.getFullText(code) : code; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/estree-to-ts-node-types.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/estree-to-ts-node-types.d.ts new file mode 100644 index 00000000..63ea30eb --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/estree-to-ts-node-types.d.ts @@ -0,0 +1,179 @@ +import type { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/types'; +import type * as ts from 'typescript'; +import type { TSNode } from './ts-nodes'; +export interface EstreeToTsNodeTypes { + [AST_NODE_TYPES.AccessorProperty]: ts.PropertyDeclaration; + [AST_NODE_TYPES.ArrayExpression]: ts.ArrayLiteralExpression; + [AST_NODE_TYPES.ArrayPattern]: ts.ArrayBindingPattern | ts.ArrayLiteralExpression; + [AST_NODE_TYPES.ArrowFunctionExpression]: ts.ArrowFunction; + [AST_NODE_TYPES.AssignmentExpression]: ts.BinaryExpression; + [AST_NODE_TYPES.AssignmentPattern]: ts.BinaryExpression | ts.BindingElement | ts.ParameterDeclaration | ts.ShorthandPropertyAssignment; + [AST_NODE_TYPES.AwaitExpression]: ts.AwaitExpression; + [AST_NODE_TYPES.BinaryExpression]: ts.BinaryExpression; + [AST_NODE_TYPES.BlockStatement]: ts.Block; + [AST_NODE_TYPES.BreakStatement]: ts.BreakStatement; + [AST_NODE_TYPES.CallExpression]: ts.CallExpression; + [AST_NODE_TYPES.CatchClause]: ts.CatchClause; + [AST_NODE_TYPES.ChainExpression]: ts.CallExpression | ts.ElementAccessExpression | ts.NonNullExpression | ts.PropertyAccessExpression; + [AST_NODE_TYPES.ClassBody]: ts.ClassDeclaration | ts.ClassExpression; + [AST_NODE_TYPES.ClassDeclaration]: ts.ClassDeclaration; + [AST_NODE_TYPES.ClassExpression]: ts.ClassExpression; + [AST_NODE_TYPES.ConditionalExpression]: ts.ConditionalExpression; + [AST_NODE_TYPES.ContinueStatement]: ts.ContinueStatement; + [AST_NODE_TYPES.DebuggerStatement]: ts.DebuggerStatement; + [AST_NODE_TYPES.Decorator]: ts.Decorator; + [AST_NODE_TYPES.DoWhileStatement]: ts.DoStatement; + [AST_NODE_TYPES.EmptyStatement]: ts.EmptyStatement; + [AST_NODE_TYPES.ExportAllDeclaration]: ts.ExportDeclaration; + [AST_NODE_TYPES.ExportDefaultDeclaration]: ts.ClassDeclaration | ts.ClassExpression | ts.EnumDeclaration | ts.ExportAssignment | ts.FunctionDeclaration | ts.InterfaceDeclaration | ts.ModuleDeclaration | ts.TypeAliasDeclaration | ts.VariableStatement; + [AST_NODE_TYPES.ExportNamedDeclaration]: ts.ClassDeclaration | ts.ClassExpression | ts.EnumDeclaration | ts.ExportDeclaration | ts.FunctionDeclaration | ts.ImportEqualsDeclaration | ts.InterfaceDeclaration | ts.ModuleDeclaration | ts.TypeAliasDeclaration | ts.VariableStatement; + [AST_NODE_TYPES.ExportSpecifier]: ts.ExportSpecifier; + [AST_NODE_TYPES.ExpressionStatement]: ts.ExpressionStatement; + [AST_NODE_TYPES.ForInStatement]: ts.ForInStatement; + [AST_NODE_TYPES.ForOfStatement]: ts.ForOfStatement; + [AST_NODE_TYPES.ForStatement]: ts.ForStatement; + [AST_NODE_TYPES.FunctionDeclaration]: ts.FunctionDeclaration; + [AST_NODE_TYPES.FunctionExpression]: ts.ConstructorDeclaration | ts.FunctionExpression | ts.GetAccessorDeclaration | ts.MethodDeclaration | ts.SetAccessorDeclaration; + [AST_NODE_TYPES.Identifier]: ts.ConstructorDeclaration | ts.Identifier | ts.Token; + [AST_NODE_TYPES.IfStatement]: ts.IfStatement; + [AST_NODE_TYPES.PrivateIdentifier]: ts.PrivateIdentifier; + [AST_NODE_TYPES.PropertyDefinition]: ts.PropertyDeclaration; + [AST_NODE_TYPES.ImportAttribute]: 'ImportAttribute' extends keyof typeof ts ? ts.ImportAttribute : ts.AssertEntry; + [AST_NODE_TYPES.ImportDeclaration]: ts.ImportDeclaration; + [AST_NODE_TYPES.ImportDefaultSpecifier]: ts.ImportClause; + [AST_NODE_TYPES.ImportExpression]: ts.CallExpression; + [AST_NODE_TYPES.ImportNamespaceSpecifier]: ts.NamespaceImport; + [AST_NODE_TYPES.ImportSpecifier]: ts.ImportSpecifier; + [AST_NODE_TYPES.JSXAttribute]: ts.JsxAttribute; + [AST_NODE_TYPES.JSXClosingElement]: ts.JsxClosingElement; + [AST_NODE_TYPES.JSXClosingFragment]: ts.JsxClosingFragment; + [AST_NODE_TYPES.JSXElement]: ts.JsxElement | ts.JsxSelfClosingElement; + [AST_NODE_TYPES.JSXEmptyExpression]: ts.JsxExpression; + [AST_NODE_TYPES.JSXExpressionContainer]: ts.JsxExpression; + [AST_NODE_TYPES.JSXFragment]: ts.JsxFragment; + [AST_NODE_TYPES.JSXIdentifier]: ts.Identifier | ts.ThisExpression; + [AST_NODE_TYPES.JSXMemberExpression]: ts.PropertyAccessExpression; + [AST_NODE_TYPES.JSXNamespacedName]: ts.JsxNamespacedName; + [AST_NODE_TYPES.JSXOpeningElement]: ts.JsxOpeningElement | ts.JsxSelfClosingElement; + [AST_NODE_TYPES.JSXOpeningFragment]: ts.JsxOpeningFragment; + [AST_NODE_TYPES.JSXSpreadAttribute]: ts.JsxSpreadAttribute; + [AST_NODE_TYPES.JSXSpreadChild]: ts.JsxExpression; + [AST_NODE_TYPES.JSXText]: ts.JsxText; + [AST_NODE_TYPES.LabeledStatement]: ts.LabeledStatement; + [AST_NODE_TYPES.Literal]: ts.BigIntLiteral | ts.BooleanLiteral | ts.NullLiteral | ts.NumericLiteral | ts.RegularExpressionLiteral | ts.StringLiteral; + [AST_NODE_TYPES.LogicalExpression]: ts.BinaryExpression; + [AST_NODE_TYPES.MemberExpression]: ts.ElementAccessExpression | ts.PropertyAccessExpression; + [AST_NODE_TYPES.MetaProperty]: ts.MetaProperty; + [AST_NODE_TYPES.MethodDefinition]: ts.ConstructorDeclaration | ts.GetAccessorDeclaration | ts.MethodDeclaration | ts.SetAccessorDeclaration; + [AST_NODE_TYPES.NewExpression]: ts.NewExpression; + [AST_NODE_TYPES.ObjectExpression]: ts.ObjectLiteralExpression; + [AST_NODE_TYPES.ObjectPattern]: ts.ObjectBindingPattern | ts.ObjectLiteralExpression; + [AST_NODE_TYPES.Program]: ts.SourceFile; + [AST_NODE_TYPES.Property]: ts.BindingElement | ts.GetAccessorDeclaration | ts.MethodDeclaration | ts.PropertyAssignment | ts.SetAccessorDeclaration | ts.ShorthandPropertyAssignment; + [AST_NODE_TYPES.RestElement]: ts.BindingElement | ts.ParameterDeclaration | ts.SpreadAssignment | ts.SpreadElement; + [AST_NODE_TYPES.ReturnStatement]: ts.ReturnStatement; + [AST_NODE_TYPES.SequenceExpression]: ts.BinaryExpression; + [AST_NODE_TYPES.SpreadElement]: ts.SpreadAssignment | ts.SpreadElement; + [AST_NODE_TYPES.StaticBlock]: ts.ClassStaticBlockDeclaration; + [AST_NODE_TYPES.Super]: ts.SuperExpression; + [AST_NODE_TYPES.SwitchCase]: ts.CaseClause | ts.DefaultClause; + [AST_NODE_TYPES.SwitchStatement]: ts.SwitchStatement; + [AST_NODE_TYPES.TaggedTemplateExpression]: ts.TaggedTemplateExpression; + [AST_NODE_TYPES.TemplateElement]: ts.NoSubstitutionTemplateLiteral | ts.TemplateHead | ts.TemplateMiddle | ts.TemplateTail; + [AST_NODE_TYPES.TemplateLiteral]: ts.NoSubstitutionTemplateLiteral | ts.TemplateExpression; + [AST_NODE_TYPES.ThisExpression]: ts.Identifier | ts.KeywordTypeNode | ts.ThisExpression; + [AST_NODE_TYPES.ThrowStatement]: ts.ThrowStatement; + [AST_NODE_TYPES.TryStatement]: ts.TryStatement; + [AST_NODE_TYPES.TSAbstractAccessorProperty]: ts.PropertyDeclaration; + [AST_NODE_TYPES.TSAbstractMethodDefinition]: ts.ConstructorDeclaration | ts.GetAccessorDeclaration | ts.MethodDeclaration | ts.SetAccessorDeclaration; + [AST_NODE_TYPES.TSAbstractPropertyDefinition]: ts.PropertyDeclaration; + [AST_NODE_TYPES.TSArrayType]: ts.ArrayTypeNode; + [AST_NODE_TYPES.TSAsExpression]: ts.AsExpression; + [AST_NODE_TYPES.TSCallSignatureDeclaration]: ts.CallSignatureDeclaration; + [AST_NODE_TYPES.TSClassImplements]: ts.ExpressionWithTypeArguments; + [AST_NODE_TYPES.TSConditionalType]: ts.ConditionalTypeNode; + [AST_NODE_TYPES.TSConstructorType]: ts.ConstructorTypeNode; + [AST_NODE_TYPES.TSConstructSignatureDeclaration]: ts.ConstructSignatureDeclaration; + [AST_NODE_TYPES.TSDeclareFunction]: ts.FunctionDeclaration; + [AST_NODE_TYPES.TSEnumBody]: ts.EnumDeclaration; + [AST_NODE_TYPES.TSEnumDeclaration]: ts.EnumDeclaration; + [AST_NODE_TYPES.TSEnumMember]: ts.EnumMember; + [AST_NODE_TYPES.TSExportAssignment]: ts.ExportAssignment; + [AST_NODE_TYPES.TSExternalModuleReference]: ts.ExternalModuleReference; + [AST_NODE_TYPES.TSFunctionType]: ts.FunctionTypeNode; + [AST_NODE_TYPES.TSImportEqualsDeclaration]: ts.ImportEqualsDeclaration; + [AST_NODE_TYPES.TSImportType]: ts.ImportTypeNode; + [AST_NODE_TYPES.TSIndexedAccessType]: ts.IndexedAccessTypeNode; + [AST_NODE_TYPES.TSIndexSignature]: ts.IndexSignatureDeclaration; + [AST_NODE_TYPES.TSInferType]: ts.InferTypeNode; + [AST_NODE_TYPES.TSInstantiationExpression]: ts.ExpressionWithTypeArguments; + [AST_NODE_TYPES.TSInterfaceBody]: ts.InterfaceDeclaration; + [AST_NODE_TYPES.TSInterfaceDeclaration]: ts.InterfaceDeclaration; + [AST_NODE_TYPES.TSInterfaceHeritage]: ts.ExpressionWithTypeArguments; + [AST_NODE_TYPES.TSIntersectionType]: ts.IntersectionTypeNode; + [AST_NODE_TYPES.TSLiteralType]: ts.LiteralTypeNode; + [AST_NODE_TYPES.TSMappedType]: ts.MappedTypeNode; + [AST_NODE_TYPES.TSMethodSignature]: ts.GetAccessorDeclaration | ts.MethodSignature | ts.SetAccessorDeclaration; + [AST_NODE_TYPES.TSModuleBlock]: ts.ModuleBlock; + [AST_NODE_TYPES.TSModuleDeclaration]: ts.ModuleDeclaration; + [AST_NODE_TYPES.TSNamedTupleMember]: ts.NamedTupleMember; + [AST_NODE_TYPES.TSNamespaceExportDeclaration]: ts.NamespaceExportDeclaration; + [AST_NODE_TYPES.TSNonNullExpression]: ts.NonNullExpression; + [AST_NODE_TYPES.TSOptionalType]: ts.OptionalTypeNode; + [AST_NODE_TYPES.TSParameterProperty]: ts.ParameterDeclaration; + [AST_NODE_TYPES.TSPropertySignature]: ts.PropertySignature; + [AST_NODE_TYPES.TSQualifiedName]: ts.Identifier | ts.QualifiedName; + [AST_NODE_TYPES.TSRestType]: ts.NamedTupleMember | ts.RestTypeNode; + [AST_NODE_TYPES.TSSatisfiesExpression]: ts.SatisfiesExpression; + [AST_NODE_TYPES.TSTemplateLiteralType]: ts.TemplateLiteralTypeNode; + [AST_NODE_TYPES.TSThisType]: ts.ThisTypeNode; + [AST_NODE_TYPES.TSTupleType]: ts.TupleTypeNode; + [AST_NODE_TYPES.TSTypeAliasDeclaration]: ts.TypeAliasDeclaration; + [AST_NODE_TYPES.TSTypeAnnotation]: undefined; + [AST_NODE_TYPES.TSTypeAssertion]: ts.TypeAssertion; + [AST_NODE_TYPES.TSTypeLiteral]: ts.TypeLiteralNode; + [AST_NODE_TYPES.TSTypeOperator]: ts.TypeOperatorNode; + [AST_NODE_TYPES.TSTypeParameter]: ts.TypeParameterDeclaration; + [AST_NODE_TYPES.TSTypeParameterDeclaration]: undefined; + [AST_NODE_TYPES.TSTypeParameterInstantiation]: ts.CallExpression | ts.ExpressionWithTypeArguments | ts.ImportTypeNode | ts.JsxOpeningElement | ts.JsxSelfClosingElement | ts.NewExpression | ts.TaggedTemplateExpression | ts.TypeQueryNode | ts.TypeReferenceNode; + [AST_NODE_TYPES.TSTypePredicate]: ts.TypePredicateNode; + [AST_NODE_TYPES.TSTypeQuery]: ts.ImportTypeNode | ts.TypeQueryNode; + [AST_NODE_TYPES.TSTypeReference]: ts.TypeReferenceNode; + [AST_NODE_TYPES.TSUnionType]: ts.UnionTypeNode; + [AST_NODE_TYPES.UnaryExpression]: ts.DeleteExpression | ts.PostfixUnaryExpression | ts.PrefixUnaryExpression | ts.TypeOfExpression | ts.VoidExpression; + [AST_NODE_TYPES.UpdateExpression]: ts.PostfixUnaryExpression | ts.PrefixUnaryExpression; + [AST_NODE_TYPES.VariableDeclaration]: ts.VariableDeclarationList | ts.VariableStatement; + [AST_NODE_TYPES.VariableDeclarator]: ts.VariableDeclaration; + [AST_NODE_TYPES.WhileStatement]: ts.WhileStatement; + [AST_NODE_TYPES.WithStatement]: ts.WithStatement; + [AST_NODE_TYPES.YieldExpression]: ts.YieldExpression; + [AST_NODE_TYPES.TSEmptyBodyFunctionExpression]: ts.ConstructorDeclaration | ts.FunctionExpression | ts.GetAccessorDeclaration | ts.MethodDeclaration | ts.SetAccessorDeclaration; + [AST_NODE_TYPES.TSAbstractKeyword]: ts.Token; + [AST_NODE_TYPES.TSAnyKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSBigIntKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSBooleanKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSIntrinsicKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSNeverKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSNullKeyword]: ts.KeywordTypeNode | ts.NullLiteral; + [AST_NODE_TYPES.TSNumberKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSObjectKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSStringKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSSymbolKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSUndefinedKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSUnknownKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSVoidKeyword]: ts.KeywordTypeNode; + [AST_NODE_TYPES.TSAsyncKeyword]: ts.Token; + [AST_NODE_TYPES.TSDeclareKeyword]: ts.Token; + [AST_NODE_TYPES.TSExportKeyword]: ts.Token; + [AST_NODE_TYPES.TSPrivateKeyword]: ts.Token; + [AST_NODE_TYPES.TSProtectedKeyword]: ts.Token; + [AST_NODE_TYPES.TSPublicKeyword]: ts.Token; + [AST_NODE_TYPES.TSReadonlyKeyword]: ts.Token; + [AST_NODE_TYPES.TSStaticKeyword]: ts.Token; +} +/** + * Maps TSESTree AST Node type to the expected TypeScript AST Node type(s). + * This mapping is based on the internal logic of the parser. + */ +export type TSESTreeToTSNode = Extract | TSNode, EstreeToTsNodeTypes[T['type']]>; +//# sourceMappingURL=estree-to-ts-node-types.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/estree-to-ts-node-types.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/estree-to-ts-node-types.d.ts.map new file mode 100644 index 00000000..9f13f56a --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/estree-to-ts-node-types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"estree-to-ts-node-types.d.ts","sourceRoot":"","sources":["../../src/ts-estree/estree-to-ts-node-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzE,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAEtC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC,MAAM,WAAW,mBAAmB;IAClC,CAAC,cAAc,CAAC,gBAAgB,CAAC,EAAE,EAAE,CAAC,mBAAmB,CAAC;IAC1D,CAAC,cAAc,CAAC,eAAe,CAAC,EAAE,EAAE,CAAC,sBAAsB,CAAC;IAC5D,CAAC,cAAc,CAAC,YAAY,CAAC,EACzB,EAAE,CAAC,mBAAmB,GACtB,EAAE,CAAC,sBAAsB,CAAC;IAC9B,CAAC,cAAc,CAAC,uBAAuB,CAAC,EAAE,EAAE,CAAC,aAAa,CAAC;IAC3D,CAAC,cAAc,CAAC,oBAAoB,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC;IAC3D,CAAC,cAAc,CAAC,iBAAiB,CAAC,EAC9B,EAAE,CAAC,gBAAgB,GACnB,EAAE,CAAC,cAAc,GACjB,EAAE,CAAC,oBAAoB,GACvB,EAAE,CAAC,2BAA2B,CAAC;IACnC,CAAC,cAAc,CAAC,eAAe,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC;IACrD,CAAC,cAAc,CAAC,gBAAgB,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC;IACvD,CAAC,cAAc,CAAC,cAAc,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC;IAC1C,CAAC,cAAc,CAAC,cAAc,CAAC,EAAE,EAAE,CAAC,cAAc,CAAC;IACnD,CAAC,cAAc,CAAC,cAAc,CAAC,EAAE,EAAE,CAAC,cAAc,CAAC;IACnD,CAAC,cAAc,CAAC,W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AI,IAAI,OAAO,CAC7E,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,UAAU,CAAC,aAAa,GAAG,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,GAAG,MAAM,EAEzE,mBAAmB,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAC/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/estree-to-ts-node-types.js b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/estree-to-ts-node-types.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/estree-to-ts-node-types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/index.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/index.d.ts new file mode 100644 index 00000000..11458c20 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/index.d.ts @@ -0,0 +1,4 @@ +export * from './estree-to-ts-node-types'; +export * from './ts-nodes'; +export { AST_NODE_TYPES, AST_TOKEN_TYPES, TSESTree, } from '@typescript-eslint/types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/index.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/index.d.ts.map new file mode 100644 index 00000000..8b223729 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ts-estree/index.ts"],"names":[],"mappings":"AACA,cAAc,2BAA2B,CAAC;AAC1C,cAAc,YAAY,CAAC;AAC3B,OAAO,EACL,cAAc,EACd,eAAe,EACf,QAAQ,GACT,MAAM,0BAA0B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/index.js b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/index.js new file mode 100644 index 00000000..2782aae0 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/index.js @@ -0,0 +1,24 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSESTree = exports.AST_TOKEN_TYPES = exports.AST_NODE_TYPES = void 0; +// for simplicity and backwards-compatibility +__exportStar(require("./estree-to-ts-node-types"), exports); +__exportStar(require("./ts-nodes"), exports); +var types_1 = require("@typescript-eslint/types"); +Object.defineProperty(exports, "AST_NODE_TYPES", { enumerable: true, get: function () { return types_1.AST_NODE_TYPES; } }); +Object.defineProperty(exports, "AST_TOKEN_TYPES", { enumerable: true, get: function () { return types_1.AST_TOKEN_TYPES; } }); +Object.defineProperty(exports, "TSESTree", { enumerable: true, get: function () { return types_1.TSESTree; } }); diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/ts-nodes.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/ts-nodes.d.ts new file mode 100644 index 00000000..fe674a96 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/ts-nodes.d.ts @@ -0,0 +1,18 @@ +import type * as ts from 'typescript'; +declare module 'typescript' { + interface AssertClause extends ts.ImportAttributes { + } + interface AssertEntry extends ts.ImportAttribute { + } + interface SatisfiesExpression extends ts.Node { + } + interface JsxNamespacedName extends ts.Node { + } + interface ImportAttribute extends ts.Node { + } + interface ImportAttributes extends ts.Node { + } +} +export type TSToken = ts.Token; +export type TSNode = ts.ArrayBindingPattern | ts.ArrayLiteralExpression | ts.ArrayTypeNode | ts.ArrowFunction | ts.AsExpression | ts.AssertClause | ts.AssertEntry | ts.AwaitExpression | ts.BigIntLiteral | ts.BinaryExpression | ts.BindingElement | ts.Block | ts.BooleanLiteral | ts.BreakStatement | ts.Bundle | ts.CallExpression | ts.CallSignatureDeclaration | ts.CaseBlock | ts.CaseClause | ts.CatchClause | ts.ClassDeclaration | ts.ClassExpression | ts.ClassStaticBlockDeclaration | ts.CommaListExpression | ts.ComputedPropertyName | ts.ConditionalExpression | ts.ConditionalTypeNode | ts.ConstructorDeclaration | ts.ConstructorTypeNode | ts.ConstructSignatureDeclaration | ts.ContinueStatement | ts.DebuggerStatement | ts.Decorator | ts.DefaultClause | ts.DeleteExpression | ts.DoStatement | ts.ElementAccessExpression | ts.EmptyStatement | ts.EnumDeclaration | ts.EnumMember | ts.ExportAssignment | ts.ExportDeclaration | ts.ExportSpecifier | ts.ExpressionStatement | ts.ExpressionWithTypeArguments | ts.ExternalModuleReference | ts.ForInStatement | ts.ForOfStatement | ts.ForStatement | ts.FunctionDeclaration | ts.FunctionExpression | ts.FunctionTypeNode | ts.GetAccessorDeclaration | ts.HeritageClause | ts.Identifier | ts.IfStatement | ts.ImportAttribute | ts.ImportAttributes | ts.ImportClause | ts.ImportDeclaration | ts.ImportEqualsDeclaration | ts.ImportExpression | ts.ImportSpecifier | ts.ImportTypeNode | ts.IndexedAccessTypeNode | ts.IndexSignatureDeclaration | ts.InferTypeNode | ts.InterfaceDeclaration | ts.IntersectionTypeNode | ts.JSDoc | ts.JSDocAllType | ts.JSDocAugmentsTag | ts.JSDocAuthorTag | ts.JSDocCallbackTag | ts.JSDocClassTag | ts.JSDocEnumTag | ts.JSDocFunctionType | ts.JSDocNonNullableType | ts.JSDocNullableType | ts.JSDocOptionalType | ts.JSDocParameterTag | ts.JSDocPropertyTag | ts.JSDocReturnTag | ts.JSDocSignature | ts.JSDocTemplateTag | ts.JSDocThisTag | ts.JSDocTypedefTag | ts.JSDocTypeExpression | ts.JSDocTypeLiteral | ts.JSDocTypeTag | ts.JSDocUnknownTag | ts.JSDocUnknownType | ts.JSDocVariadicType | ts.JsonMinusNumericLiteral | ts.JsxAttribute | ts.JsxClosingElement | ts.JsxClosingFragment | ts.JsxElement | ts.JsxExpression | ts.JsxFragment | ts.JsxNamespacedName | ts.JsxOpeningElement | ts.JsxOpeningFragment | ts.JsxSelfClosingElement | ts.JsxSpreadAttribute | ts.JsxText | ts.KeywordTypeNode | ts.LabeledStatement | ts.LiteralTypeNode | ts.MappedTypeNode | ts.MetaProperty | ts.MethodDeclaration | ts.MethodSignature | ts.MissingDeclaration | ts.Modifier | ts.ModuleBlock | ts.ModuleDeclaration | ts.NamedExports | ts.NamedImports | ts.NamedTupleMember | ts.NamespaceExportDeclaration | ts.NamespaceImport | ts.NewExpression | ts.NonNullExpression | ts.NoSubstitutionTemplateLiteral | ts.NotEmittedStatement | ts.NullLiteral | ts.NumericLiteral | ts.ObjectBindingPattern | ts.ObjectLiteralExpression | ts.OmittedExpression | ts.OptionalTypeNode | ts.ParameterDeclaration | ts.ParenthesizedExpression | ts.ParenthesizedTypeNode | ts.PartiallyEmittedExpression | ts.PostfixUnaryExpression | ts.PrefixUnaryExpression | ts.PrivateIdentifier | ts.PropertyAccessExpression | ts.PropertyAssignment | ts.PropertyDeclaration | ts.PropertySignature | ts.QualifiedName | ts.RegularExpressionLiteral | ts.RestTypeNode | ts.ReturnStatement | ts.SatisfiesExpression | ts.SemicolonClassElement | ts.SetAccessorDeclaration | ts.ShorthandPropertyAssignment | ts.SourceFile | ts.SpreadAssignment | ts.SpreadElement | ts.StringLiteral | ts.SuperExpression | ts.SwitchStatement | ts.SyntheticExpression | ts.TaggedTemplateExpression | ts.TemplateExpression | ts.TemplateHead | ts.TemplateLiteralTypeNode | ts.TemplateMiddle | ts.TemplateSpan | ts.TemplateTail | ts.ThisExpression | ts.ThisTypeNode | ts.ThrowStatement | ts.TryStatement | ts.TupleTypeNode | ts.TypeAliasDeclaration | ts.TypeAssertion | ts.TypeLiteralNode | ts.TypeOfExpression | ts.TypeOperatorNode | ts.TypeParameterDeclaration | ts.TypePredicateNode | ts.TypeQueryNode | ts.TypeReferenceNode | ts.UnionTypeNode | ts.VariableDeclaration | ts.VariableDeclarationList | ts.VariableStatement | ts.VoidExpression | ts.WhileStatement | ts.WithStatement | ts.YieldExpression; +//# sourceMappingURL=ts-nodes.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/ts-nodes.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/ts-nodes.d.ts.map new file mode 100644 index 00000000..e676701a --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/ts-nodes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ts-nodes.d.ts","sourceRoot":"","sources":["../../src/ts-estree/ts-nodes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAKtC,OAAO,QAAQ,YAAY,CAAC;IAE1B,UAAiB,YAAa,SAAQ,EAAE,CAAC,gBAAgB;KAAG;IAC5D,UAAiB,WAAY,SAAQ,EAAE,CAAC,eAAe;KAAG;IAE1D,UAAiB,mBAAoB,SAAQ,EAAE,CAAC,IAAI;KAAG;IAEvD,UAAiB,iBAAkB,SAAQ,EAAE,CAAC,IAAI;KAAG;IAErD,UAAiB,eAAgB,SAAQ,EAAE,CAAC,IAAI;KAAG;IACnD,UAAiB,gBAAiB,SAAQ,EAAE,CAAC,IAAI;KAAG;CACrD;AAGD,MAAM,MAAM,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC;AAE9C,MAAM,MAAM,MAAM,G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AAE,CAAC,eAAe,GAClB,EAAE,CAAC,mBAAmB,GACtB,EAAE,CAAC,qBAAqB,GACxB,EAAE,CAAC,sBAAsB,GAEzB,EAAE,CAAC,2BAA2B,GAC9B,EAAE,CAAC,UAAU,GACb,EAAE,CAAC,gBAAgB,GACnB,EAAE,CAAC,aAAa,GAChB,EAAE,CAAC,aAAa,GAChB,EAAE,CAAC,eAAe,GAClB,EAAE,CAAC,eAAe,GAClB,EAAE,CAAC,mBAAmB,GACtB,EAAE,CAAC,wBAAwB,GAC3B,EAAE,CAAC,kBAAkB,GACrB,EAAE,CAAC,YAAY,GACf,EAAE,CAAC,uBAAuB,GAC1B,EAAE,CAAC,cAAc,GAGjB,EAAE,CAAC,YAAY,GACf,EAAE,CAAC,YAAY,GACf,EAAE,CAAC,cAAc,GACjB,EAAE,CAAC,YAAY,GACf,EAAE,CAAC,cAAc,GACjB,EAAE,CAAC,YAAY,GACf,EAAE,CAAC,aAAa,GAChB,EAAE,CAAC,oBAAoB,GACvB,EAAE,CAAC,aAAa,GAChB,EAAE,CAAC,eAAe,GAClB,EAAE,CAAC,gBAAgB,GACnB,EAAE,CAAC,gBAAgB,GACnB,EAAE,CAAC,wBAAwB,GAC3B,EAAE,CAAC,iBAAiB,GACpB,EAAE,CAAC,aAAa,GAChB,EAAE,CAAC,iBAAiB,GACpB,EAAE,CAAC,aAAa,GAChB,EAAE,CAAC,mBAAmB,GACtB,EAAE,CAAC,uBAAuB,GAC1B,EAAE,CAAC,iBAAiB,GACpB,EAAE,CAAC,cAAc,GACjB,EAAE,CAAC,cAAc,GACjB,EAAE,CAAC,aAAa,GAChB,EAAE,CAAC,eAAe,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/ts-nodes.js b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/ts-nodes.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/ts-estree/ts-nodes.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/use-at-your-own-risk.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/use-at-your-own-risk.d.ts new file mode 100644 index 00000000..3d8aceee --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/use-at-your-own-risk.d.ts @@ -0,0 +1,7 @@ +export * from './ast-converter'; +export * from './create-program/getScriptKind'; +export type { ParseSettings } from './parseSettings'; +export * from './getModifiers'; +export { typescriptVersionIsAtLeast } from './version-check'; +export { getCanonicalFileName } from './create-program/shared'; +//# sourceMappingURL=use-at-your-own-risk.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/use-at-your-own-risk.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/use-at-your-own-risk.d.ts.map new file mode 100644 index 00000000..0cfba63b --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/use-at-your-own-risk.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"use-at-your-own-risk.d.ts","sourceRoot":"","sources":["../src/use-at-your-own-risk.ts"],"names":[],"mappings":"AACA,cAAc,iBAAiB,CAAC;AAChC,cAAc,gCAAgC,CAAC;AAC/C,YAAY,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGrD,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAG7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/use-at-your-own-risk.js b/node_modules/@typescript-eslint/typescript-estree/dist/use-at-your-own-risk.js new file mode 100644 index 00000000..2be33cd5 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/use-at-your-own-risk.js @@ -0,0 +1,27 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getCanonicalFileName = exports.typescriptVersionIsAtLeast = void 0; +// required by website +__exportStar(require("./ast-converter"), exports); +__exportStar(require("./create-program/getScriptKind"), exports); +// required by packages/utils/src/ts-estree.ts +__exportStar(require("./getModifiers"), exports); +var version_check_1 = require("./version-check"); +Object.defineProperty(exports, "typescriptVersionIsAtLeast", { enumerable: true, get: function () { return version_check_1.typescriptVersionIsAtLeast; } }); +// required by packages/type-utils +var shared_1 = require("./create-program/shared"); +Object.defineProperty(exports, "getCanonicalFileName", { enumerable: true, get: function () { return shared_1.getCanonicalFileName; } }); diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/useProgramFromProjectService.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/useProgramFromProjectService.d.ts new file mode 100644 index 00000000..cc917876 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/useProgramFromProjectService.d.ts @@ -0,0 +1,7 @@ +import type { ProjectServiceAndMetadata as ProjectServiceAndMetadata } from '@typescript-eslint/project-service'; +import type { ASTAndDefiniteProgram, ASTAndNoProgram, ASTAndProgram } from './create-program/shared'; +import type { MutableParseSettings } from './parseSettings'; +export declare function useProgramFromProjectService(serviceAndSettings: ProjectServiceAndMetadata, parseSettings: Readonly, hasFullTypeInformation: boolean, defaultProjectMatchedFiles: Set): ASTAndProgram | undefined; +export declare function useProgramFromProjectService(serviceAndSettings: ProjectServiceAndMetadata, parseSettings: Readonly, hasFullTypeInformation: true, defaultProjectMatchedFiles: Set): ASTAndDefiniteProgram | undefined; +export declare function useProgramFromProjectService(serviceAndSettings: ProjectServiceAndMetadata, parseSettings: Readonly, hasFullTypeInformation: false, defaultProjectMatchedFiles: Set): ASTAndNoProgram | undefined; +//# sourceMappingURL=useProgramFromProjectService.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/useProgramFromProjectService.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/useProgramFromProjectService.d.ts.map new file mode 100644 index 00000000..2a5a0222 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/useProgramFromProjectService.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"useProgramFromProjectService.d.ts","sourceRoot":"","sources":["../src/useProgramFromProjectService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,IAAI,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAQjH,OAAO,KAAK,EACV,qBAAqB,EACrB,eAAe,EACf,aAAa,EACd,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AA4M5D,wBAAgB,4BAA4B,CAC1C,kBAAkB,EAAE,yBAAyB,EAC7C,aAAa,EAAE,QAAQ,CAAC,oBAAoB,CAAC,EAC7C,sBAAsB,EAAE,OAAO,EAC/B,0BAA0B,EAAE,GAAG,CAAC,MAAM,CAAC,GACtC,aAAa,GAAG,SAAS,CAAC;AAC7B,wBAAgB,4BAA4B,CAC1C,kBAAkB,EAAE,yBAAyB,EAC7C,aAAa,EAAE,QAAQ,CAAC,oBAAoB,CAAC,EAC7C,sBAAsB,EAAE,IAAI,EAC5B,0BAA0B,EAAE,GAAG,CAAC,MAAM,CAAC,GACtC,qBAAqB,GAAG,SAAS,CAAC;AACrC,wBAAgB,4BAA4B,CAC1C,kBAAkB,EAAE,yBAAyB,EAC7C,aAAa,EAAE,QAAQ,CAAC,oBAAoB,CAAC,EAC7C,sBAAsB,EAAE,KAAK,EAC7B,0BAA0B,EAAE,GAAG,CAAC,MAAM,CAAC,GACtC,eAAe,GAAG,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/useProgramFromProjectService.js b/node_modules/@typescript-eslint/typescript-estree/dist/useProgramFromProjectService.js new file mode 100644 index 00000000..982fdee5 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/useProgramFromProjectService.js @@ -0,0 +1,196 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useProgramFromProjectService = useProgramFromProjectService; +const debug_1 = __importDefault(require("debug")); +const minimatch_1 = require("minimatch"); +const node_path_1 = __importDefault(require("node:path")); +const node_util_1 = __importDefault(require("node:util")); +const ts = __importStar(require("typescript")); +const createProjectProgram_1 = require("./create-program/createProjectProgram"); +const createSourceFile_1 = require("./create-program/createSourceFile"); +const shared_1 = require("./create-program/shared"); +const validateDefaultProjectForFilesGlob_1 = require("./create-program/validateDefaultProjectForFilesGlob"); +const RELOAD_THROTTLE_MS = 250; +const log = (0, debug_1.default)('typescript-eslint:typescript-estree:useProgramFromProjectService'); +const serviceFileExtensions = new WeakMap(); +const updateExtraFileExtensions = (service, extraFileExtensions) => { + const currentServiceFileExtensions = serviceFileExtensions.get(service) ?? []; + if (!node_util_1.default.isDeepStrictEqual(currentServiceFileExtensions, extraFileExtensions)) { + log('Updating extra file extensions: before=%s: after=%s', currentServiceFileExtensions, extraFileExtensions); + service.setHostConfiguration({ + extraFileExtensions: extraFileExtensions.map(extension => ({ + extension, + isMixedContent: false, + scriptKind: ts.ScriptKind.Deferred, + })), + }); + serviceFileExtensions.set(service, extraFileExtensions); + log('Extra file extensions updated: %o', extraFileExtensions); + } +}; +function openClientFileFromProjectService(defaultProjectMatchedFiles, isDefaultProjectAllowed, filePathAbsolute, parseSettings, serviceAndSettings) { + const opened = openClientFileAndMaybeReload(); + log('Result from attempting to open client file: %o', opened); + log('Default project allowed path: %s, based on config file: %s', isDefaultProjectAllowed, opened.configFileName); + if (opened.configFileName) { + if (isDefaultProjectAllowed) { + throw new Error(`${parseSettings.filePath} was included by allowDefaultProject but also was found in the project service. Consider removing it from allowDefaultProject.`); + } + } + else { + const wasNotFound = `${parseSettings.filePath} was not found by the project service`; + const fileExtension = node_path_1.default.extname(parseSettings.filePath); + const extraFileExtensions = parseSettings.extraFileExtensions; + if (!shared_1.DEFAULT_EXTRA_FILE_EXTENSIONS.has(fileExtension) && + !extraFileExtensions.includes(fileExtension)) { + const nonStandardExt = `${wasNotFound} because the extension for the file (\`${fileExtension}\`) is non-standard`; + if (extraFileExtensions.length > 0) { + throw new Error(`${nonStandardExt}. It should be added to your existing \`parserOptions.extraFileExtensions\`.`); + } + else { + throw new Error(`${nonStandardExt}. You should add \`parserOptions.extraFileExtensions\` to your config.`); + } + } + if (!isDefaultProjectAllowed) { + throw new Error(`${wasNotFound}. Consider either including it in the tsconfig.json or including it in allowDefaultProject.`); + } + } + // No a configFileName indicates this file wasn't included in a TSConfig. + // That means it must get its type information from the default project. + if (!opened.configFileName) { + defaultProjectMatchedFiles.add(filePathAbsolute); + if (defaultProjectMatchedFiles.size > + serviceAndSettings.maximumDefaultProjectFileMatchCount) { + const filePrintLimit = 20; + const filesToPrint = [...defaultProjectMatchedFiles].slice(0, filePrintLimit); + const truncatedFileCount = defaultProjectMatchedFiles.size - filesToPrint.length; + throw new Error(`Too many files (>${serviceAndSettings.maximumDefaultProjectFileMatchCount}) have matched the default project.${validateDefaultProjectForFilesGlob_1.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION} +Matching files: +${filesToPrint.map(file => `- ${file}`).join('\n')} +${truncatedFileCount ? `...and ${truncatedFileCount} more files\n` : ''} +If you absolutely need more files included, set parserOptions.projectService.maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING to a larger value. +`); + } + } + return opened; + function openClientFile() { + return serviceAndSettings.service.openClientFile(filePathAbsolute, parseSettings.codeFullText, + /* scriptKind */ undefined, parseSettings.tsconfigRootDir); + } + function openClientFileAndMaybeReload() { + log('Opening project service client file at path: %s', filePathAbsolute); + let opened = openClientFile(); + // If no project included the file and we're not in single-run mode, + // we might be running in an editor with outdated file info. + // We can try refreshing the project service - debounced for performance. + if (!opened.configFileErrors && + !opened.configFileName && + !parseSettings.singleRun && + !isDefaultProjectAllowed && + performance.now() - serviceAndSettings.lastReloadTimestamp > + RELOAD_THROTTLE_MS) { + log('No config file found; reloading project service and retrying.'); + serviceAndSettings.service.reloadProjects(); + opened = openClientFile(); + serviceAndSettings.lastReloadTimestamp = performance.now(); + } + return opened; + } +} +function createNoProgramWithProjectService(filePathAbsolute, parseSettings, service) { + log('No project service information available. Creating no program.'); + // If the project service knows about this file, this informs if of changes. + // Doing so ensures that: + // - if the file is not part of a project, we don't waste time creating a program (fast non-type-aware linting) + // - otherwise, we refresh the file in the project service (moderately fast, since the project is already loaded) + if (service.getScriptInfo(filePathAbsolute)) { + log('Script info available. Opening client file in project service.'); + service.openClientFile(filePathAbsolute, parseSettings.codeFullText, + /* scriptKind */ undefined, parseSettings.tsconfigRootDir); + } + return (0, createSourceFile_1.createNoProgram)(parseSettings); +} +function retrieveASTAndProgramFor(filePathAbsolute, parseSettings, serviceAndSettings) { + log('Retrieving script info and then program for: %s', filePathAbsolute); + const scriptInfo = serviceAndSettings.service.getScriptInfo(filePathAbsolute); + /* eslint-disable @typescript-eslint/no-non-null-assertion */ + const program = serviceAndSettings.service + .getDefaultProjectForFile(scriptInfo.fileName, true) + .getLanguageService(/*ensureSynchronized*/ true) + .getProgram(); + /* eslint-enable @typescript-eslint/no-non-null-assertion */ + if (!program) { + log('Could not find project service program for: %s', filePathAbsolute); + return undefined; + } + log('Found project service program for: %s', filePathAbsolute); + return (0, createProjectProgram_1.createProjectProgram)(parseSettings, [program]); +} +function useProgramFromProjectService(serviceAndSettings, parseSettings, hasFullTypeInformation, defaultProjectMatchedFiles) { + // NOTE: triggers a full project reload when changes are detected + updateExtraFileExtensions(serviceAndSettings.service, parseSettings.extraFileExtensions); + // We don't canonicalize the filename because it caused a performance regression. + // See https://github.com/typescript-eslint/typescript-eslint/issues/8519 + const filePathAbsolute = absolutify(parseSettings.filePath, serviceAndSettings); + log('Opening project service file for: %s at absolute path %s', parseSettings.filePath, filePathAbsolute); + const filePathRelative = node_path_1.default.relative(parseSettings.tsconfigRootDir, filePathAbsolute); + const isDefaultProjectAllowed = filePathMatchedBy(filePathRelative, serviceAndSettings.allowDefaultProject); + // Type-aware linting is disabled for this file. + // However, type-aware lint rules might still rely on its contents. + if (!hasFullTypeInformation && !isDefaultProjectAllowed) { + return createNoProgramWithProjectService(filePathAbsolute, parseSettings, serviceAndSettings.service); + } + // If type info was requested, we attempt to open it in the project service. + // By now, the file is known to be one of: + // - in the project service (valid configuration) + // - allowlisted in the default project (valid configuration) + // - neither, which openClientFileFromProjectService will throw an error for + const opened = hasFullTypeInformation && + openClientFileFromProjectService(defaultProjectMatchedFiles, isDefaultProjectAllowed, filePathAbsolute, parseSettings, serviceAndSettings); + log('Opened project service file: %o', opened); + return retrieveASTAndProgramFor(filePathAbsolute, parseSettings, serviceAndSettings); +} +function absolutify(filePath, serviceAndSettings) { + return node_path_1.default.isAbsolute(filePath) + ? filePath + : node_path_1.default.join(serviceAndSettings.service.host.getCurrentDirectory(), filePath); +} +function filePathMatchedBy(filePath, allowDefaultProject) { + return !!allowDefaultProject?.some(pattern => (0, minimatch_1.minimatch)(filePath, pattern)); +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/version-check.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/version-check.d.ts new file mode 100644 index 00000000..bffa079e --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/version-check.d.ts @@ -0,0 +1,5 @@ +declare const versions: readonly ["4.7", "4.8", "4.9", "5.0", "5.1", "5.2", "5.3", "5.4"]; +type Versions = typeof versions extends ArrayLike ? U : never; +export declare const typescriptVersionIsAtLeast: Record; +export {}; +//# sourceMappingURL=version-check.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/version-check.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/version-check.d.ts.map new file mode 100644 index 00000000..602feb17 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/version-check.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version-check.d.ts","sourceRoot":"","sources":["../src/version-check.ts"],"names":[],"mappings":"AAaA,QAAA,MAAM,QAAQ,mEASJ,CAAC;AACX,KAAK,QAAQ,GAAG,OAAO,QAAQ,SAAS,SAAS,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAEvE,eAAO,MAAM,0BAA0B,EAAS,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/version-check.js b/node_modules/@typescript-eslint/typescript-estree/dist/version-check.js new file mode 100644 index 00000000..81a2c894 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/version-check.js @@ -0,0 +1,57 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.typescriptVersionIsAtLeast = void 0; +const semver = __importStar(require("semver")); +const ts = __importStar(require("typescript")); +function semverCheck(version) { + return semver.satisfies(ts.version, `>= ${version}.0 || >= ${version}.1-rc || >= ${version}.0-beta`, { + includePrerelease: true, + }); +} +const versions = [ + '4.7', + '4.8', + '4.9', + '5.0', + '5.1', + '5.2', + '5.3', + '5.4', +]; +exports.typescriptVersionIsAtLeast = {}; +for (const version of versions) { + exports.typescriptVersionIsAtLeast[version] = semverCheck(version); +} diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/version.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/version.d.ts new file mode 100644 index 00000000..d3518070 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/version.d.ts @@ -0,0 +1,2 @@ +export declare const version: string; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/version.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/version.d.ts.map new file mode 100644 index 00000000..70ffa1c8 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,EAAE,MAA2C,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/version.js b/node_modules/@typescript-eslint/typescript-estree/dist/version.js new file mode 100644 index 00000000..b303ecb1 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/version.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +// note - cannot migrate this to an import statement because it will make TSC copy the package.json to the dist folder +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access +exports.version = require('../package.json').version; diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/withoutProjectParserOptions.d.ts b/node_modules/@typescript-eslint/typescript-estree/dist/withoutProjectParserOptions.d.ts new file mode 100644 index 00000000..7d2882be --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/withoutProjectParserOptions.d.ts @@ -0,0 +1,10 @@ +/** + * Removes options that prompt the parser to parse the project with type + * information. In other words, you can use this if you are invoking the parser + * directly, to ensure that one file will be parsed in isolation, which is much, + * much faster. + * + * @see https://github.com/typescript-eslint/typescript-eslint/issues/8428 + */ +export declare function withoutProjectParserOptions(opts: Options): Omit; +//# sourceMappingURL=withoutProjectParserOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/withoutProjectParserOptions.d.ts.map b/node_modules/@typescript-eslint/typescript-estree/dist/withoutProjectParserOptions.d.ts.map new file mode 100644 index 00000000..9d9db9e1 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/withoutProjectParserOptions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"withoutProjectParserOptions.d.ts","sourceRoot":"","sources":["../src/withoutProjectParserOptions.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CAAC,OAAO,SAAS,MAAM,EAChE,IAAI,EAAE,OAAO,GACZ,IAAI,CACL,OAAO,EACP,gCAAgC,GAAG,SAAS,GAAG,gBAAgB,CAChE,CAMA"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/dist/withoutProjectParserOptions.js b/node_modules/@typescript-eslint/typescript-estree/dist/withoutProjectParserOptions.js new file mode 100644 index 00000000..365ba9b2 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/dist/withoutProjectParserOptions.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.withoutProjectParserOptions = withoutProjectParserOptions; +/** + * Removes options that prompt the parser to parse the project with type + * information. In other words, you can use this if you are invoking the parser + * directly, to ensure that one file will be parsed in isolation, which is much, + * much faster. + * + * @see https://github.com/typescript-eslint/typescript-eslint/issues/8428 + */ +function withoutProjectParserOptions(opts) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars -- The variables are meant to be omitted + const { EXPERIMENTAL_useProjectService, project, projectService, ...rest } = opts; + return rest; +} diff --git a/node_modules/@typescript-eslint/typescript-estree/package.json b/node_modules/@typescript-eslint/typescript-estree/package.json new file mode 100644 index 00000000..0d624efc --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/package.json @@ -0,0 +1,88 @@ +{ + "name": "@typescript-eslint/typescript-estree", + "version": "8.34.0", + "description": "A parser that converts TypeScript source code into an ESTree compatible form", + "files": [ + "dist", + "!*.tsbuildinfo", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json", + "./use-at-your-own-risk": { + "types": "./dist/use-at-your-own-risk.d.ts", + "default": "./dist/use-at-your-own-risk.js" + } + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/typescript-estree" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/typescript-estree", + "license": "MIT", + "keywords": [ + "ast", + "estree", + "ecmascript", + "javascript", + "typescript", + "parser", + "syntax" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "format": "yarn run -T format", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "dependencies": { + "@typescript-eslint/project-service": "8.34.0", + "@typescript-eslint/tsconfig-utils": "8.34.0", + "@typescript-eslint/types": "8.34.0", + "@typescript-eslint/visitor-keys": "8.34.0", + "debug": "^4.3.4", + "fast-glob": "^3.3.2", + "is-glob": "^4.0.3", + "minimatch": "^9.0.4", + "semver": "^7.6.0", + "ts-api-utils": "^2.1.0" + }, + "devDependencies": { + "@types/is-glob": "^4.0.4", + "@vitest/coverage-v8": "^3.1.3", + "glob": "*", + "rimraf": "*", + "typescript": "*", + "vitest": "^3.1.3" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "typescript-estree", + "includedScripts": [ + "clean" + ] + } +} diff --git a/node_modules/@typescript-eslint/utils/LICENSE b/node_modules/@typescript-eslint/utils/LICENSE new file mode 100644 index 00000000..a1164108 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/utils/README.md b/node_modules/@typescript-eslint/utils/README.md new file mode 100644 index 00000000..7ba75009 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/utils` + +> Utilities for working with TypeScript + ESLint together. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) + +👉 See **https://typescript-eslint.io/packages/utils** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/PatternMatcher.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/PatternMatcher.d.ts new file mode 100644 index 00000000..3c54b1d1 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/PatternMatcher.d.ts @@ -0,0 +1,48 @@ +interface PatternMatcher { + /** + * Replace all matched parts by a given replacer. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#matcher-symbol-replace} + * @example + * const { PatternMatcher } = require("eslint-utils") + * const matcher = new PatternMatcher(/\\p{Script=Greek}/g) + * + * module.exports = { + * meta: {}, + * create(context) { + * return { + * "Literal[regex]"(node) { + * const replacedPattern = node.regex.pattern.replace( + * matcher, + * "[\\u0370-\\u0373\\u0375-\\u0377\\u037A-\\u037D\\u037F\\u0384\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03E1\\u03F0-\\u03FF\\u1D26-\\u1D2A\\u1D5D-\\u1D61\\u1D66-\\u1D6A\\u1DBF\\u1F00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FC4\\u1FC6-\\u1FD3\\u1FD6-\\u1FDB\\u1FDD-\\u1FEF\\u1FF2-\\u1FF4\\u1FF6-\\u1FFE\\u2126\\uAB65]|\\uD800[\\uDD40-\\uDD8E\\uDDA0]|\\uD834[\\uDE00-\\uDE45]" + * ) + * }, + * } + * }, + * } + */ + [Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string; + /** + * Iterate all matched parts in a given string. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#matcher-execall} + */ + execAll(str: string): IterableIterator; + /** + * Check whether this pattern matches a given string or not. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#matcher-test} + */ + test(str: string): boolean; +} +/** + * The class to find a pattern in strings as handling escape sequences. + * It ignores the found pattern if it's escaped with `\`. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#patternmatcher-class} + */ +export declare const PatternMatcher: new (pattern: RegExp, options?: { + escaped?: boolean; +}) => PatternMatcher; +export {}; +//# sourceMappingURL=PatternMatcher.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/PatternMatcher.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/PatternMatcher.d.ts.map new file mode 100644 index 00000000..b7278866 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/PatternMatcher.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PatternMatcher.d.ts","sourceRoot":"","sources":["../../../src/ast-utils/eslint-utils/PatternMatcher.ts"],"names":[],"mappings":"AAEA,UAAU,cAAc;IACtB;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,CAAC,MAAM,CAAC,OAAO,CAAC,CACd,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,KAAK,MAAM,CAAC,GACjD,MAAM,CAAC;IAEV;;;;OAIG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,CAAC,eAAe,CAAC,CAAC;IAExD;;;;OAIG;IACH,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CAC5B;AAED;;;;;GAKG;AACH,eAAO,MAAM,cAAc,EAAiC,KAC1D,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,KAC5B,cAAc,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/PatternMatcher.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/PatternMatcher.js new file mode 100644 index 00000000..a31b5f5a --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/PatternMatcher.js @@ -0,0 +1,44 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PatternMatcher = void 0; +const eslintUtils = __importStar(require("@eslint-community/eslint-utils")); +/** + * The class to find a pattern in strings as handling escape sequences. + * It ignores the found pattern if it's escaped with `\`. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#patternmatcher-class} + */ +exports.PatternMatcher = eslintUtils.PatternMatcher; diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/ReferenceTracker.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/ReferenceTracker.d.ts new file mode 100644 index 00000000..7046d3c4 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/ReferenceTracker.d.ts @@ -0,0 +1,76 @@ +import type * as TSESLint from '../../ts-eslint'; +import type { TSESTree } from '../../ts-estree'; +declare const ReferenceTrackerREAD: unique symbol; +declare const ReferenceTrackerCALL: unique symbol; +declare const ReferenceTrackerCONSTRUCT: unique symbol; +declare const ReferenceTrackerESM: unique symbol; +interface ReferenceTracker { + /** + * Iterate the references that the given `traceMap` determined. + * This method starts to search from `require()` expression. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#tracker-iteratecjsreferences} + */ + iterateCjsReferences(traceMap: ReferenceTracker.TraceMap): IterableIterator>; + /** + * Iterate the references that the given `traceMap` determined. + * This method starts to search from `import`/`export` declarations. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#tracker-iterateesmreferences} + */ + iterateEsmReferences(traceMap: ReferenceTracker.TraceMap): IterableIterator>; + /** + * Iterate the references that the given `traceMap` determined. + * This method starts to search from global variables. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#tracker-iterateglobalreferences} + */ + iterateGlobalReferences(traceMap: ReferenceTracker.TraceMap): IterableIterator>; +} +interface ReferenceTrackerStatic { + readonly CALL: typeof ReferenceTrackerCALL; + readonly CONSTRUCT: typeof ReferenceTrackerCONSTRUCT; + readonly ESM: typeof ReferenceTrackerESM; + new (globalScope: TSESLint.Scope.Scope, options?: { + /** + * The name list of Global Object. Optional. Default is `["global", "globalThis", "self", "window"]`. + */ + globalObjectNames?: readonly string[]; + /** + * The mode which determines how the `tracker.iterateEsmReferences()` method scans CommonJS modules. + * If this is `"strict"`, the method binds CommonJS modules to the default export. Otherwise, the method binds + * CommonJS modules to both the default export and named exports. Optional. Default is `"strict"`. + */ + mode?: 'legacy' | 'strict'; + }): ReferenceTracker; + readonly READ: typeof ReferenceTrackerREAD; +} +declare namespace ReferenceTracker { + type READ = ReferenceTrackerStatic['READ']; + type CALL = ReferenceTrackerStatic['CALL']; + type CONSTRUCT = ReferenceTrackerStatic['CONSTRUCT']; + type ESM = ReferenceTrackerStatic['ESM']; + type ReferenceType = CALL | CONSTRUCT | READ; + type TraceMap = Record>; + interface TraceMapElement { + [key: string]: TraceMapElement; + [ReferenceTrackerCALL]?: T; + [ReferenceTrackerCONSTRUCT]?: T; + [ReferenceTrackerESM]?: true; + [ReferenceTrackerREAD]?: T; + } + interface FoundReference { + info: T; + node: TSESTree.Node; + path: readonly string[]; + type: ReferenceType; + } +} +/** + * The tracker for references. This provides reference tracking for global variables, CommonJS modules, and ES modules. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class} + */ +export declare const ReferenceTracker: ReferenceTrackerStatic; +export {}; +//# sourceMappingURL=ReferenceTracker.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/ReferenceTracker.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/ReferenceTracker.d.ts.map new file mode 100644 index 00000000..20bac390 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/ReferenceTracker.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ReferenceTracker.d.ts","sourceRoot":"","sources":["../../../src/ast-utils/eslint-utils/ReferenceTracker.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD,QAAA,MAAM,oBAAoB,EAAE,OAAO,MAA0C,CAAC;AAC9E,QAAA,MAAM,oBAAoB,EAAE,OAAO,MAA0C,CAAC;AAC9E,QAAA,MAAM,yBAAyB,EAAE,OAAO,MACA,CAAC;AACzC,QAAA,MAAM,mBAAmB,EAAE,OAAO,MAAyC,CAAC;AAE5E,UAAU,gBAAgB;IACxB;;;;;OAKG;IACH,oBAAoB,CAAC,CAAC,EACpB,QAAQ,EAAE,gBAAgB,CA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;IAEpD,KAAY,QAAQ,CAAC,CAAC,GAAG,GAAG,IAAI,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;IACnE,UAAiB,eAAe,CAAC,CAAC;QAChC,CAAC,GAAG,EAAE,MAAM,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;QAClC,CAAC,oBAAoB,CAAC,CAAC,EAAE,CAAC,CAAC;QAC3B,CAAC,yBAAyB,CAAC,CAAC,EAAE,CAAC,CAAC;QAChC,CAAC,mBAAmB,CAAC,CAAC,EAAE,IAAI,CAAC;QAC7B,CAAC,oBAAoB,CAAC,CAAC,EAAE,CAAC,CAAC;KAC5B;IAED,UAAiB,cAAc,CAAC,CAAC,GAAG,GAAG;QACrC,IAAI,EAAE,CAAC,CAAC;QACR,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC;QACpB,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;QACxB,IAAI,EAAE,aAAa,CAAC;KACrB;CACF;AAED;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,EACK,sBAAsB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/ReferenceTracker.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/ReferenceTracker.js new file mode 100644 index 00000000..43c127df --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/ReferenceTracker.js @@ -0,0 +1,48 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReferenceTracker = void 0; +/* eslint-disable @typescript-eslint/no-namespace */ +const eslintUtils = __importStar(require("@eslint-community/eslint-utils")); +const ReferenceTrackerREAD = eslintUtils.ReferenceTracker.READ; +const ReferenceTrackerCALL = eslintUtils.ReferenceTracker.CALL; +const ReferenceTrackerCONSTRUCT = eslintUtils.ReferenceTracker.CONSTRUCT; +const ReferenceTrackerESM = eslintUtils.ReferenceTracker.ESM; +/** + * The tracker for references. This provides reference tracking for global variables, CommonJS modules, and ES modules. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class} + */ +exports.ReferenceTracker = eslintUtils.ReferenceTracker; diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/astUtilities.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/astUtilities.d.ts new file mode 100644 index 00000000..79bc7275 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/astUtilities.d.ts @@ -0,0 +1,84 @@ +import type * as TSESLint from '../../ts-eslint'; +import type { TSESTree } from '../../ts-estree'; +/** + * Get the proper location of a given function node to report. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getfunctionheadlocation} + */ +export declare const getFunctionHeadLocation: (node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression, sourceCode: TSESLint.SourceCode) => TSESTree.SourceLocation; +/** + * Get the name and kind of a given function node. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getfunctionnamewithkind} + */ +export declare const getFunctionNameWithKind: (node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression, sourceCode?: TSESLint.SourceCode) => string; +/** + * Get the property name of a given property node. + * If the node is a computed property, this tries to compute the property name by the getStringIfConstant function. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getpropertyname} + * @returns The property name of the node. If the property name is not constant then it returns `null`. + */ +export declare const getPropertyName: (node: TSESTree.MemberExpression | TSESTree.MethodDefinition | TSESTree.Property | TSESTree.PropertyDefinition, initialScope?: TSESLint.Scope.Scope) => string | null; +/** + * Get the value of a given node if it can decide the value statically. + * If the 2nd parameter `initialScope` was given, this function tries to resolve identifier references which are in the + * given node as much as possible. In the resolving way, it does on the assumption that built-in global objects have + * not been modified. + * For example, it considers `Symbol.iterator`, `Symbol.for('k')`, ` String.raw``hello`` `, and `Object.freeze({a: 1}).a` as static, but `Symbol('k')` is not static. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstaticvalue} + * @returns The `{ value: any }` shaped object. The `value` property is the static value. If it couldn't compute the + * static value of the node, it returns `null`. + */ +export declare const getStaticValue: (node: TSESTree.Node, initialScope?: TSESLint.Scope.Scope) => { + value: unknown; +} | null; +/** + * Get the string value of a given node. + * This function is a tiny wrapper of the getStaticValue function. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstringifconstant} + */ +export declare const getStringIfConstant: (node: TSESTree.Node, initialScope?: TSESLint.Scope.Scope) => string | null; +/** + * Check whether a given node has any side effect or not. + * The side effect means that it may modify a certain variable or object member. This function considers the node which + * contains the following types as the node which has side effects: + * - `AssignmentExpression` + * - `AwaitExpression` + * - `CallExpression` + * - `ImportExpression` + * - `NewExpression` + * - `UnaryExpression([operator = "delete"])` + * - `UpdateExpression` + * - `YieldExpression` + * - When `options.considerGetters` is `true`: + * - `MemberExpression` + * - When `options.considerImplicitTypeConversion` is `true`: + * - `BinaryExpression([operator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in"])` + * - `MemberExpression([computed = true])` + * - `MethodDefinition([computed = true])` + * - `Property([computed = true])` + * - `UnaryExpression([operator = "-" | "+" | "!" | "~"])` + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#hassideeffect} + */ +export declare const hasSideEffect: (node: TSESTree.Node, sourceCode: TSESLint.SourceCode, options?: { + considerGetters?: boolean; + considerImplicitTypeConversion?: boolean; +}) => boolean; +export declare const isParenthesized: { + (times: number, node: TSESTree.Node, sourceCode: TSESLint.SourceCode): boolean; + /** + * Check whether a given node is parenthesized or not. + * This function detects it correctly even if it's parenthesized by specific syntax. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#isparenthesized} + * @returns `true` if the node is parenthesized. + * If `times` was given, it returns `true` only if the node is parenthesized the `times` times. + * For example, `isParenthesized(2, node, sourceCode)` returns true for `((foo))`, but not for `(foo)`. + */ + (node: TSESTree.Node, sourceCode: TSESLint.SourceCode): boolean; +}; +//# sourceMappingURL=astUtilities.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/astUtilities.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/astUtilities.d.ts.map new file mode 100644 index 00000000..fd71e3b4 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/astUtilities.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"astUtilities.d.ts","sourceRoot":"","sources":["../../../src/ast-utils/eslint-utils/astUtilities.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AACjD,OAAO,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AE,QAAQ,CAAC,UAAU,EAC/B,OAAO,CAAC,EAAE;IACR,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,8BAA8B,CAAC,EAAE,OAAO,CAAC;CAC1C,KACE,OAAO,CAAC;AAEb,eAAO,MAAM,eAAe,EAAkC;IAC5D,CACE,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,QAAQ,CAAC,IAAI,EACnB,UAAU,EAAE,QAAQ,CAAC,UAAU,GAC9B,OAAO,CAAC;IAEX;;;;;;;;OAQG;IACH,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,CAAC,UAAU,GAAG,OAAO,CAAC;CACjE,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/astUtilities.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/astUtilities.js new file mode 100644 index 00000000..29a03697 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/astUtilities.js @@ -0,0 +1,101 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isParenthesized = exports.hasSideEffect = exports.getStringIfConstant = exports.getStaticValue = exports.getPropertyName = exports.getFunctionNameWithKind = exports.getFunctionHeadLocation = void 0; +const eslintUtils = __importStar(require("@eslint-community/eslint-utils")); +/** + * Get the proper location of a given function node to report. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getfunctionheadlocation} + */ +exports.getFunctionHeadLocation = eslintUtils.getFunctionHeadLocation; +/** + * Get the name and kind of a given function node. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getfunctionnamewithkind} + */ +exports.getFunctionNameWithKind = eslintUtils.getFunctionNameWithKind; +/** + * Get the property name of a given property node. + * If the node is a computed property, this tries to compute the property name by the getStringIfConstant function. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getpropertyname} + * @returns The property name of the node. If the property name is not constant then it returns `null`. + */ +exports.getPropertyName = eslintUtils.getPropertyName; +/** + * Get the value of a given node if it can decide the value statically. + * If the 2nd parameter `initialScope` was given, this function tries to resolve identifier references which are in the + * given node as much as possible. In the resolving way, it does on the assumption that built-in global objects have + * not been modified. + * For example, it considers `Symbol.iterator`, `Symbol.for('k')`, ` String.raw``hello`` `, and `Object.freeze({a: 1}).a` as static, but `Symbol('k')` is not static. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstaticvalue} + * @returns The `{ value: any }` shaped object. The `value` property is the static value. If it couldn't compute the + * static value of the node, it returns `null`. + */ +exports.getStaticValue = eslintUtils.getStaticValue; +/** + * Get the string value of a given node. + * This function is a tiny wrapper of the getStaticValue function. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstringifconstant} + */ +exports.getStringIfConstant = eslintUtils.getStringIfConstant; +/** + * Check whether a given node has any side effect or not. + * The side effect means that it may modify a certain variable or object member. This function considers the node which + * contains the following types as the node which has side effects: + * - `AssignmentExpression` + * - `AwaitExpression` + * - `CallExpression` + * - `ImportExpression` + * - `NewExpression` + * - `UnaryExpression([operator = "delete"])` + * - `UpdateExpression` + * - `YieldExpression` + * - When `options.considerGetters` is `true`: + * - `MemberExpression` + * - When `options.considerImplicitTypeConversion` is `true`: + * - `BinaryExpression([operator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in"])` + * - `MemberExpression([computed = true])` + * - `MethodDefinition([computed = true])` + * - `Property([computed = true])` + * - `UnaryExpression([operator = "-" | "+" | "!" | "~"])` + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#hassideeffect} + */ +exports.hasSideEffect = eslintUtils.hasSideEffect; +exports.isParenthesized = eslintUtils.isParenthesized; diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/index.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/index.d.ts new file mode 100644 index 00000000..3ec74aa2 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/index.d.ts @@ -0,0 +1,6 @@ +export * from './astUtilities'; +export * from './PatternMatcher'; +export * from './predicates'; +export * from './ReferenceTracker'; +export * from './scopeAnalysis'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/index.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/index.d.ts.map new file mode 100644 index 00000000..e6a66720 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/ast-utils/eslint-utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/index.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/index.js new file mode 100644 index 00000000..d2e9a645 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/index.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./astUtilities"), exports); +__exportStar(require("./PatternMatcher"), exports); +__exportStar(require("./predicates"), exports); +__exportStar(require("./ReferenceTracker"), exports); +__exportStar(require("./scopeAnalysis"), exports); diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/predicates.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/predicates.d.ts new file mode 100644 index 00000000..45887691 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/predicates.d.ts @@ -0,0 +1,32 @@ +import type { TSESTree } from '../../ts-estree'; +type IsSpecificTokenFunction = (token: TSESTree.Token) => token is SpecificToken; +type IsNotSpecificTokenFunction = (token: TSESTree.Token) => token is Exclude; +type PunctuatorTokenWithValue = { + value: Value; +} & TSESTree.PunctuatorToken; +type IsPunctuatorTokenWithValueFunction = IsSpecificTokenFunction>; +type IsNotPunctuatorTokenWithValueFunction = IsNotSpecificTokenFunction>; +export declare const isArrowToken: IsPunctuatorTokenWithValueFunction<"=>">; +export declare const isNotArrowToken: IsNotPunctuatorTokenWithValueFunction<"=>">; +export declare const isClosingBraceToken: IsPunctuatorTokenWithValueFunction<"}">; +export declare const isNotClosingBraceToken: IsNotPunctuatorTokenWithValueFunction<"}">; +export declare const isClosingBracketToken: IsPunctuatorTokenWithValueFunction<"]">; +export declare const isNotClosingBracketToken: IsNotPunctuatorTokenWithValueFunction<"]">; +export declare const isClosingParenToken: IsPunctuatorTokenWithValueFunction<")">; +export declare const isNotClosingParenToken: IsNotPunctuatorTokenWithValueFunction<")">; +export declare const isColonToken: IsPunctuatorTokenWithValueFunction<":">; +export declare const isNotColonToken: IsNotPunctuatorTokenWithValueFunction<":">; +export declare const isCommaToken: IsPunctuatorTokenWithValueFunction<",">; +export declare const isNotCommaToken: IsNotPunctuatorTokenWithValueFunction<",">; +export declare const isCommentToken: IsSpecificTokenFunction; +export declare const isNotCommentToken: IsNotSpecificTokenFunction; +export declare const isOpeningBraceToken: IsPunctuatorTokenWithValueFunction<"{">; +export declare const isNotOpeningBraceToken: IsNotPunctuatorTokenWithValueFunction<"{">; +export declare const isOpeningBracketToken: IsPunctuatorTokenWithValueFunction<"[">; +export declare const isNotOpeningBracketToken: IsNotPunctuatorTokenWithValueFunction<"[">; +export declare const isOpeningParenToken: IsPunctuatorTokenWithValueFunction<"(">; +export declare const isNotOpeningParenToken: IsNotPunctuatorTokenWithValueFunction<"(">; +export declare const isSemicolonToken: IsPunctuatorTokenWithValueFunction<";">; +export declare const isNotSemicolonToken: IsNotPunctuatorTokenWithValueFunction<";">; +export {}; +//# sourceMappingURL=predicates.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/predicates.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/predicates.d.ts.map new file mode 100644 index 00000000..b02b4933 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/predicates.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"predicates.d.ts","sourceRoot":"","sources":["../../../src/ast-utils/eslint-utils/predicates.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD,KAAK,uBAAuB,CAAC,aAAa,SAAS,QAAQ,CAAC,KAAK,IAAI,CACnE,KAAK,EAAE,QAAQ,CAAC,KAAK,KAClB,KAAK,IAAI,aAAa,CAAC;AAE5B,KAAK,0BAA0B,CAAC,aAAa,SAAS,QAAQ,CAAC,KAAK,IAAI,CACtE,KAAK,EAAE,QAAQ,CAAC,KAAK,KAClB,KAAK,IAAI,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;AAErD,KAAK,wBAAwB,CAAC,KAAK,SAAS,MAAM,IAAI;IACpD,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,QAAQ,CAAC,eAAe,CAAC;AAC7B,KAAK,kCAAkC,CAAC,KAAK,SAAS,MAAM,IAC1D,uBAAuB,CAAC,wBAAwB,CAAC,KAAK,CAAC,CAAC,CAAC;AAC3D,KAAK,qCAAqC,CAAC,KAAK,SAAS,MAAM,IAC7D,0BAA0B,CAAC,wBAAwB,CAAC,KAAK,CAAC,CAAC,CAAC;AAE9D,eAAO,MAAM,YAAY,EACK,kCAAkC,CAAC,IAAI,CAAC,CAAC;AACvE,eAAO,MAAM,eAAe,EACK,qCAAqC,CAAC,IAAI,CAAC,CAAC;AAE7E,eAAO,MAAM,mBAAmB,EACK,kCAAkC,CAAC,GAAG,CAAC,CAAC;AAC7E,eAAO,MAAM,sBAAsB,EACK,qCAAqC,CAAC,GAAG,CAAC,CAAC;AAEnF,eAAO,MAAM,qBAAqB,EACK,kCAAkC,CAAC,GAAG,CAAC,CAAC;AAC/E,eAAO,MAAM,wBAAwB,EACK,qCAAqC,CAAC,GAAG,CAAC,CAAC;AAErF,eAAO,MAAM,mBAAmB,EACK,kCAAkC,CAAC,GAAG,CAAC,CAAC;AAC7E,eAAO,MAAM,sBAAsB,EACK,qCAAqC,CAAC,GAAG,CAAC,CAAC;AAEnF,eAAO,MAAM,YAAY,EACK,kCAAkC,CAAC,GAAG,CAAC,CAAC;AACtE,eAAO,MAAM,eAAe,EACK,qCAAqC,CAAC,GAAG,CAAC,CAAC;AAE5E,eAAO,MAAM,YAAY,EACK,kCAAkC,CAAC,GAAG,CAAC,CAAC;AACtE,eAAO,MAAM,eAAe,EACK,qCAAqC,CAAC,GAAG,CAAC,CAAC;AAE5E,eAAO,MAAM,cAAc,EACK,uBAAuB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAC1E,eAAO,MAAM,iBAAiB,EACK,0BAA0B,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAEhF,eAAO,MAAM,mBAAmB,EACK,kCAAkC,CAAC,GAAG,CAAC,CAAC;AAC7E,eAAO,MAAM,sBAAsB,EACK,qCAAqC,CAAC,GAAG,CAAC,CAAC;AAEnF,eAAO,MAAM,qBAAqB,EACK,kCAAkC,CAAC,GAAG,CAAC,CAAC;AAC/E,eAAO,MAAM,wBAAwB,EACK,qCAAqC,CAAC,GAAG,CAAC,CAAC;AAErF,eAAO,MAAM,mBAAmB,EACK,kCAAkC,CAAC,GAAG,CAAC,CAAC;AAC7E,eAAO,MAAM,sBAAsB,EACK,qCAAqC,CAAC,GAAG,CAAC,CAAC;AAEnF,eAAO,MAAM,gBAAgB,EACK,kCAAkC,CAAC,GAAG,CAAC,CAAC;AAC1E,eAAO,MAAM,mBAAmB,EACK,qCAAqC,CAAC,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/predicates.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/predicates.js new file mode 100644 index 00000000..6ca12796 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/predicates.js @@ -0,0 +1,59 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isNotSemicolonToken = exports.isSemicolonToken = exports.isNotOpeningParenToken = exports.isOpeningParenToken = exports.isNotOpeningBracketToken = exports.isOpeningBracketToken = exports.isNotOpeningBraceToken = exports.isOpeningBraceToken = exports.isNotCommentToken = exports.isCommentToken = exports.isNotCommaToken = exports.isCommaToken = exports.isNotColonToken = exports.isColonToken = exports.isNotClosingParenToken = exports.isClosingParenToken = exports.isNotClosingBracketToken = exports.isClosingBracketToken = exports.isNotClosingBraceToken = exports.isClosingBraceToken = exports.isNotArrowToken = exports.isArrowToken = void 0; +const eslintUtils = __importStar(require("@eslint-community/eslint-utils")); +exports.isArrowToken = eslintUtils.isArrowToken; +exports.isNotArrowToken = eslintUtils.isNotArrowToken; +exports.isClosingBraceToken = eslintUtils.isClosingBraceToken; +exports.isNotClosingBraceToken = eslintUtils.isNotClosingBraceToken; +exports.isClosingBracketToken = eslintUtils.isClosingBracketToken; +exports.isNotClosingBracketToken = eslintUtils.isNotClosingBracketToken; +exports.isClosingParenToken = eslintUtils.isClosingParenToken; +exports.isNotClosingParenToken = eslintUtils.isNotClosingParenToken; +exports.isColonToken = eslintUtils.isColonToken; +exports.isNotColonToken = eslintUtils.isNotColonToken; +exports.isCommaToken = eslintUtils.isCommaToken; +exports.isNotCommaToken = eslintUtils.isNotCommaToken; +exports.isCommentToken = eslintUtils.isCommentToken; +exports.isNotCommentToken = eslintUtils.isNotCommentToken; +exports.isOpeningBraceToken = eslintUtils.isOpeningBraceToken; +exports.isNotOpeningBraceToken = eslintUtils.isNotOpeningBraceToken; +exports.isOpeningBracketToken = eslintUtils.isOpeningBracketToken; +exports.isNotOpeningBracketToken = eslintUtils.isNotOpeningBracketToken; +exports.isOpeningParenToken = eslintUtils.isOpeningParenToken; +exports.isNotOpeningParenToken = eslintUtils.isNotOpeningParenToken; +exports.isSemicolonToken = eslintUtils.isSemicolonToken; +exports.isNotSemicolonToken = eslintUtils.isNotSemicolonToken; diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/scopeAnalysis.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/scopeAnalysis.d.ts new file mode 100644 index 00000000..60855acd --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/scopeAnalysis.d.ts @@ -0,0 +1,17 @@ +import type * as TSESLint from '../../ts-eslint'; +import type { TSESTree } from '../../ts-estree'; +/** + * Get the variable of a given name. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#findvariable} + */ +export declare const findVariable: (initialScope: TSESLint.Scope.Scope, nameOrNode: string | TSESTree.Identifier) => TSESLint.Scope.Variable | null; +/** + * Get the innermost scope which contains a given node. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#getinnermostscope} + * @returns The innermost scope which contains the given node. + * If such scope doesn't exist then it returns the 1st argument `initialScope`. + */ +export declare const getInnermostScope: (initialScope: TSESLint.Scope.Scope, node: TSESTree.Node) => TSESLint.Scope.Scope; +//# sourceMappingURL=scopeAnalysis.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/scopeAnalysis.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/scopeAnalysis.d.ts.map new file mode 100644 index 00000000..40acf046 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/scopeAnalysis.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopeAnalysis.d.ts","sourceRoot":"","sources":["../../../src/ast-utils/eslint-utils/scopeAnalysis.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD;;;;GAIG;AACH,eAAO,MAAM,YAAY,EAA+B,CACtD,YAAY,EAAE,QAAQ,CAAC,KAAK,CAAC,KAAK,EAClC,UAAU,EAAE,MAAM,GAAG,QAAQ,CAAC,UAAU,KACrC,QAAQ,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;AAEpC;;;;;;GAMG;AACH,eAAO,MAAM,iBAAiB,EAAoC,CAChE,YAAY,EAAE,QAAQ,CAAC,KAAK,CAAC,KAAK,EAClC,IAAI,EAAE,QAAQ,CAAC,IAAI,KAChB,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/scopeAnalysis.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/scopeAnalysis.js new file mode 100644 index 00000000..5bc874e5 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/eslint-utils/scopeAnalysis.js @@ -0,0 +1,51 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getInnermostScope = exports.findVariable = void 0; +const eslintUtils = __importStar(require("@eslint-community/eslint-utils")); +/** + * Get the variable of a given name. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#findvariable} + */ +exports.findVariable = eslintUtils.findVariable; +/** + * Get the innermost scope which contains a given node. + * + * @see {@link https://eslint-community.github.io/eslint-utils/api/scope-utils.html#getinnermostscope} + * @returns The innermost scope which contains the given node. + * If such scope doesn't exist then it returns the 1st argument `initialScope`. + */ +exports.getInnermostScope = eslintUtils.getInnermostScope; diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/helpers.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/helpers.d.ts new file mode 100644 index 00000000..3b390058 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/helpers.d.ts @@ -0,0 +1,19 @@ +import type { AST_NODE_TYPES, AST_TOKEN_TYPES, TSESTree } from '../ts-estree'; +export declare const isNodeOfType: (nodeType: NodeType) => (node: TSESTree.Node | null | undefined) => node is Extract; +export declare const isNodeOfTypes: (nodeTypes: NodeTypes) => (node: TSESTree.Node | null | undefined) => node is Extract; +export declare const isNodeOfTypeWithConditions: , Conditions extends Partial>(nodeType: NodeType, conditions: Conditions) => ((node: TSESTree.Node | null | undefined) => node is Conditions & ExtractedNode); +export declare const isTokenOfTypeWithConditions: , Conditions extends Partial<{ + type: TokenType; +} & TSESTree.Token>>(tokenType: TokenType, conditions: Conditions) => ((token: TSESTree.Token | null | undefined) => token is Conditions & ExtractedToken); +export declare const isNotTokenOfTypeWithConditions: , Conditions extends Partial>(tokenType: TokenType, conditions: Conditions) => ((token: TSESTree.Token | null | undefined) => token is Exclude); +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/helpers.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/helpers.d.ts.map new file mode 100644 index 00000000..f9dd8794 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/ast-utils/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAO9E,eAAO,MAAM,YAAY,GACtB,QAAQ,SAAS,cAAc,EAAE,UAAU,QAAQ,MAElD,MAAM,QAAQ,CAAC,IAAI,GAAG,IAAI,GAAG,SAAS,KACrC,IAAI,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,CAC3B,CAAC;AAE5B,eAAO,MAAM,aAAa,GACvB,SAAS,SAAS,SAAS,cAA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AC,KAAK,GAAG,IAAI,GAAG,SAAS,KACrC,KAAK,IAAI,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,UAAU,GAAG,cAAc,CAAC,CAEN,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/helpers.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/helpers.js new file mode 100644 index 00000000..d1d7a8c8 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/helpers.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isNotTokenOfTypeWithConditions = exports.isTokenOfTypeWithConditions = exports.isNodeOfTypeWithConditions = exports.isNodeOfTypes = exports.isNodeOfType = void 0; +const isNodeOfType = (nodeType) => (node) => node?.type === nodeType; +exports.isNodeOfType = isNodeOfType; +const isNodeOfTypes = (nodeTypes) => (node) => !!node && nodeTypes.includes(node.type); +exports.isNodeOfTypes = isNodeOfTypes; +const isNodeOfTypeWithConditions = (nodeType, conditions) => { + const entries = Object.entries(conditions); + return (node) => node?.type === nodeType && + entries.every(([key, value]) => node[key] === value); +}; +exports.isNodeOfTypeWithConditions = isNodeOfTypeWithConditions; +const isTokenOfTypeWithConditions = (tokenType, conditions) => { + const entries = Object.entries(conditions); + return (token) => token?.type === tokenType && + entries.every(([key, value]) => token[key] === value); +}; +exports.isTokenOfTypeWithConditions = isTokenOfTypeWithConditions; +const isNotTokenOfTypeWithConditions = (tokenType, conditions) => (token) => !(0, exports.isTokenOfTypeWithConditions)(tokenType, conditions)(token); +exports.isNotTokenOfTypeWithConditions = isNotTokenOfTypeWithConditions; diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/index.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/index.d.ts new file mode 100644 index 00000000..714b9952 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/index.d.ts @@ -0,0 +1,5 @@ +export * from './eslint-utils'; +export * from './helpers'; +export * from './misc'; +export * from './predicates'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/index.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/index.d.ts.map new file mode 100644 index 00000000..c6f5e7f6 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ast-utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,QAAQ,CAAC;AACvB,cAAc,cAAc,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/index.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/index.js new file mode 100644 index 00000000..5442939b --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/index.js @@ -0,0 +1,20 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./eslint-utils"), exports); +__exportStar(require("./helpers"), exports); +__exportStar(require("./misc"), exports); +__exportStar(require("./predicates"), exports); diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/misc.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/misc.d.ts new file mode 100644 index 00000000..336eda61 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/misc.d.ts @@ -0,0 +1,7 @@ +import type { TSESTree } from '../ts-estree'; +export declare const LINEBREAK_MATCHER: RegExp; +/** + * Determines whether two adjacent tokens are on the same line + */ +export declare function isTokenOnSameLine(left: TSESTree.Node | TSESTree.Token, right: TSESTree.Node | TSESTree.Token): boolean; +//# sourceMappingURL=misc.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/misc.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/misc.d.ts.map new file mode 100644 index 00000000..ffd34d5c --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/misc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"misc.d.ts","sourceRoot":"","sources":["../../src/ast-utils/misc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAE7C,eAAO,MAAM,iBAAiB,QAA4B,CAAC;AAE3D;;GAEG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,QAAQ,CAAC,IAAI,GAAG,QAAQ,CAAC,KAAK,EACpC,KAAK,EAAE,QAAQ,CAAC,IAAI,GAAG,QAAQ,CAAC,KAAK,GACpC,OAAO,CAET"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/misc.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/misc.js new file mode 100644 index 00000000..58b8223f --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/misc.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LINEBREAK_MATCHER = void 0; +exports.isTokenOnSameLine = isTokenOnSameLine; +exports.LINEBREAK_MATCHER = /\r\n|[\r\n\u2028\u2029]/; +/** + * Determines whether two adjacent tokens are on the same line + */ +function isTokenOnSameLine(left, right) { + return left.loc.end.line === right.loc.start.line; +} diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/predicates.d.ts b/node_modules/@typescript-eslint/utils/dist/ast-utils/predicates.d.ts new file mode 100644 index 00000000..d762a4d9 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/predicates.d.ts @@ -0,0 +1,69 @@ +import type { TSESTree } from '../ts-estree'; +export declare const isOptionalChainPunctuator: (token: TSESTree.Token | null | undefined) => token is { + value: "?."; +} & TSESTree.PunctuatorToken; +export declare const isNotOptionalChainPunctuator: (token: TSESTree.Token | null | undefined) => token is TSESTree.BooleanToken | TSESTree.BlockComment | TSESTree.LineComment | TSESTree.IdentifierToken | TSESTree.JSXIdentifierToken | TSESTree.JSXTextToken | TSESTree.KeywordToken | TSESTree.NullToken | TSESTree.NumericToken | TSESTree.PrivateIdentifierToken | TSESTree.PunctuatorToken | TSESTree.RegularExpressionToken | TSESTree.StringToken | TSESTree.TemplateToken; +export declare const isNonNullAssertionPunctuator: (token: TSESTree.Token | null | undefined) => token is { + value: "!"; +} & TSESTree.PunctuatorToken; +export declare const isNotNonNullAssertionPunctuator: (token: TSESTree.Token | null | undefined) => token is TSESTree.BooleanToken | TSESTree.BlockComment | TSESTree.LineComment | TSESTree.IdentifierToken | TSESTree.JSXIdentifierToken | TSESTree.JSXTextToken | TSESTree.KeywordToken | TSESTree.NullToken | TSESTree.NumericToken | TSESTree.PrivateIdentifierToken | TSESTree.PunctuatorToken | TSESTree.RegularExpressionToken | TSESTree.StringToken | TSESTree.TemplateToken; +/** + * Returns true if and only if the node represents: foo?.() or foo.bar?.() + */ +export declare const isOptionalCallExpression: (node: TSESTree.Node | null | undefined) => node is { + optional: boolean; +} & TSESTree.CallExpression; +/** + * Returns true if and only if the node represents logical OR + */ +export declare const isLogicalOrOperator: (node: TSESTree.Node | null | undefined) => node is Partial & TSESTree.LogicalExpression; +/** + * Checks if a node is a type assertion: + * ``` + * x as foo + * x + * ``` + */ +export declare const isTypeAssertion: (node: TSESTree.Node | null | undefined) => node is TSESTree.TSAsExpression | TSESTree.TSTypeAssertion; +export declare const isVariableDeclarator: (node: TSESTree.Node | null | undefined) => node is TSESTree.VariableDeclaratorDefiniteAssignment | TSESTree.VariableDeclaratorMaybeInit | TSESTree.VariableDeclaratorNoInit | TSESTree.UsingInForOfDeclarator | TSESTree.UsingInNormalContextDeclarator; +export declare const isFunction: (node: TSESTree.Node | null | undefined) => node is TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclarationWithName | TSESTree.FunctionDeclarationWithOptionalName | TSESTree.FunctionExpression; +export declare const isFunctionType: (node: TSESTree.Node | null | undefined) => node is TSESTree.TSCallSignatureDeclaration | TSESTree.TSConstructorType | TSESTree.TSConstructSignatureDeclaration | TSESTree.TSDeclareFunctionNoDeclare | TSESTree.TSDeclareFunctionWithDeclare | TSESTree.TSEmptyBodyFunctionExpression | TSESTree.TSFunctionType | TSESTree.TSMethodSignatureComputedName | TSESTree.TSMethodSignatureNonComputedName; +export declare const isFunctionOrFunctionType: (node: TSESTree.Node | null | undefined) => node is TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclarationWithName | TSESTree.FunctionDeclarationWithOptionalName | TSESTree.FunctionExpression | TSESTree.TSCallSignatureDeclaration | TSESTree.TSConstructorType | TSESTree.TSConstructSignatureDeclaration | TSESTree.TSDeclareFunctionNoDeclare | TSESTree.TSDeclareFunctionWithDeclare | TSESTree.TSEmptyBodyFunctionExpression | TSESTree.TSFunctionType | TSESTree.TSMethodSignatureComputedName | TSESTree.TSMethodSignatureNonComputedName; +export declare const isTSFunctionType: (node: TSESTree.Node | null | undefined) => node is TSESTree.TSFunctionType; +export declare const isTSConstructorType: (node: TSESTree.Node | null | undefined) => node is TSESTree.TSConstructorType; +export declare const isClassOrTypeElement: (node: TSESTree.Node | null | undefined) => node is TSESTree.FunctionExpression | TSESTree.MethodDefinitionComputedName | TSESTree.MethodDefinitionNonComputedName | TSESTree.PropertyDefinitionComputedName | TSESTree.PropertyDefinitionNonComputedName | TSESTree.TSAbstractMethodDefinitionComputedName | TSESTree.TSAbstractMethodDefinitionNonComputedName | TSESTree.TSAbstractPropertyDefinitionComputedName | TSESTree.TSAbstractPropertyDefinitionNonComputedName | TSESTree.TSCallSignatureDeclaration | TSESTree.TSConstructSignatureDeclaration | TSESTree.TSEmptyBodyFunctionExpression | TSESTree.TSIndexSignature | TSESTree.TSMethodSignatureComputedName | TSESTree.TSMethodSignatureNonComputedName | TSESTree.TSPropertySignatureComputedName | TSESTree.TSPropertySignatureNonComputedName; +/** + * Checks if a node is a constructor method. + */ +export declare const isConstructor: (node: TSESTree.Node | null | undefined) => node is Partial & (TSESTree.MethodDefinitionComputedName | TSESTree.MethodDefinitionNonComputedName); +/** + * Checks if a node is a setter method. + */ +export declare function isSetter(node: TSESTree.Node | undefined): node is { + kind: 'set'; +} & (TSESTree.MethodDefinition | TSESTree.Property); +export declare const isIdentifier: (node: TSESTree.Node | null | undefined) => node is TSESTree.Identifier; +/** + * Checks if a node represents an `await …` expression. + */ +export declare const isAwaitExpression: (node: TSESTree.Node | null | undefined) => node is TSESTree.AwaitExpression; +/** + * Checks if a possible token is the `await` keyword. + */ +export declare const isAwaitKeyword: (token: TSESTree.Token | null | undefined) => token is { + value: "await"; +} & TSESTree.IdentifierToken; +/** + * Checks if a possible token is the `type` keyword. + */ +export declare const isTypeKeyword: (token: TSESTree.Token | null | undefined) => token is { + value: "type"; +} & TSESTree.IdentifierToken; +/** + * Checks if a possible token is the `import` keyword. + */ +export declare const isImportKeyword: (token: TSESTree.Token | null | undefined) => token is { + value: "import"; +} & TSESTree.KeywordToken; +export declare const isLoop: (node: TSESTree.Node | null | undefined) => node is TSESTree.DoWhileStatement | TSESTree.ForInStatement | TSESTree.ForOfStatement | TSESTree.ForStatement | TSESTree.WhileStatement; +//# sourceMappingURL=predicates.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/predicates.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ast-utils/predicates.d.ts.map new file mode 100644 index 00000000..4a296a63 --- /dev/null +++ b/node_modules/@typescript-e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,GAAG,SAAS,GAC9B,IAAI,IAAI;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,GAAG,CAAC,QAAQ,CAAC,gBAAgB,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAO3E;AAED,eAAO,MAAM,YAAY,SAzHf,SAAU,IAAI,mDAyH2C,CAAC;AAEpE;;GAEG;AACH,eAAO,MAAM,iBAAiB,SA9HpB,SAAU,IAAI,wDA8HqD,CAAC;AAE9E;;GAEG;AACH,eAAO,MAAM,cAAc,UAvEd,SAAW,KACxB;;4BAyEC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,aAAa,UA/Eb,SAAW,KACxB;;4BAiFC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,eAAe,UAvFf,SAAW,KACxB;;yBAyFC,CAAC;AAEF,eAAO,MAAM,MAAM,SA/IgD,SAC/D,IAAI,+JAoJG,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ast-utils/predicates.js b/node_modules/@typescript-eslint/utils/dist/ast-utils/predicates.js new file mode 100644 index 00000000..7b867603 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ast-utils/predicates.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isLoop = exports.isImportKeyword = exports.isTypeKeyword = exports.isAwaitKeyword = exports.isAwaitExpression = exports.isIdentifier = exports.isConstructor = exports.isClassOrTypeElement = exports.isTSConstructorType = exports.isTSFunctionType = exports.isFunctionOrFunctionType = exports.isFunctionType = exports.isFunction = exports.isVariableDeclarator = exports.isTypeAssertion = exports.isLogicalOrOperator = exports.isOptionalCallExpression = exports.isNotNonNullAssertionPunctuator = exports.isNonNullAssertionPunctuator = exports.isNotOptionalChainPunctuator = exports.isOptionalChainPunctuator = void 0; +exports.isSetter = isSetter; +const ts_estree_1 = require("../ts-estree"); +const helpers_1 = require("./helpers"); +exports.isOptionalChainPunctuator = (0, helpers_1.isTokenOfTypeWithConditions)(ts_estree_1.AST_TOKEN_TYPES.Punctuator, { value: '?.' }); +exports.isNotOptionalChainPunctuator = (0, helpers_1.isNotTokenOfTypeWithConditions)(ts_estree_1.AST_TOKEN_TYPES.Punctuator, { value: '?.' }); +exports.isNonNullAssertionPunctuator = (0, helpers_1.isTokenOfTypeWithConditions)(ts_estree_1.AST_TOKEN_TYPES.Punctuator, { value: '!' }); +exports.isNotNonNullAssertionPunctuator = (0, helpers_1.isNotTokenOfTypeWithConditions)(ts_estree_1.AST_TOKEN_TYPES.Punctuator, { value: '!' }); +/** + * Returns true if and only if the node represents: foo?.() or foo.bar?.() + */ +exports.isOptionalCallExpression = (0, helpers_1.isNodeOfTypeWithConditions)(ts_estree_1.AST_NODE_TYPES.CallExpression, +// this flag means the call expression itself is option +// i.e. it is foo.bar?.() and not foo?.bar() +{ optional: true }); +/** + * Returns true if and only if the node represents logical OR + */ +exports.isLogicalOrOperator = (0, helpers_1.isNodeOfTypeWithConditions)(ts_estree_1.AST_NODE_TYPES.LogicalExpression, { operator: '||' }); +/** + * Checks if a node is a type assertion: + * ``` + * x as foo + * x + * ``` + */ +exports.isTypeAssertion = (0, helpers_1.isNodeOfTypes)([ + ts_estree_1.AST_NODE_TYPES.TSAsExpression, + ts_estree_1.AST_NODE_TYPES.TSTypeAssertion, +]); +exports.isVariableDeclarator = (0, helpers_1.isNodeOfType)(ts_estree_1.AST_NODE_TYPES.VariableDeclarator); +const functionTypes = [ + ts_estree_1.AST_NODE_TYPES.ArrowFunctionExpression, + ts_estree_1.AST_NODE_TYPES.FunctionDeclaration, + ts_estree_1.AST_NODE_TYPES.FunctionExpression, +]; +exports.isFunction = (0, helpers_1.isNodeOfTypes)(functionTypes); +const functionTypeTypes = [ + ts_estree_1.AST_NODE_TYPES.TSCallSignatureDeclaration, + ts_estree_1.AST_NODE_TYPES.TSConstructorType, + ts_estree_1.AST_NODE_TYPES.TSConstructSignatureDeclaration, + ts_estree_1.AST_NODE_TYPES.TSDeclareFunction, + ts_estree_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression, + ts_estree_1.AST_NODE_TYPES.TSFunctionType, + ts_estree_1.AST_NODE_TYPES.TSMethodSignature, +]; +exports.isFunctionType = (0, helpers_1.isNodeOfTypes)(functionTypeTypes); +exports.isFunctionOrFunctionType = (0, helpers_1.isNodeOfTypes)([ + ...functionTypes, + ...functionTypeTypes, +]); +exports.isTSFunctionType = (0, helpers_1.isNodeOfType)(ts_estree_1.AST_NODE_TYPES.TSFunctionType); +exports.isTSConstructorType = (0, helpers_1.isNodeOfType)(ts_estree_1.AST_NODE_TYPES.TSConstructorType); +exports.isClassOrTypeElement = (0, helpers_1.isNodeOfTypes)([ + // ClassElement + ts_estree_1.AST_NODE_TYPES.PropertyDefinition, + ts_estree_1.AST_NODE_TYPES.FunctionExpression, + ts_estree_1.AST_NODE_TYPES.MethodDefinition, + ts_estree_1.AST_NODE_TYPES.TSAbstractPropertyDefinition, + ts_estree_1.AST_NODE_TYPES.TSAbstractMethodDefinition, + ts_estree_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression, + ts_estree_1.AST_NODE_TYPES.TSIndexSignature, + // TypeElement + ts_estree_1.AST_NODE_TYPES.TSCallSignatureDeclaration, + ts_estree_1.AST_NODE_TYPES.TSConstructSignatureDeclaration, + // AST_NODE_TYPES.TSIndexSignature, + ts_estree_1.AST_NODE_TYPES.TSMethodSignature, + ts_estree_1.AST_NODE_TYPES.TSPropertySignature, +]); +/** + * Checks if a node is a constructor method. + */ +exports.isConstructor = (0, helpers_1.isNodeOfTypeWithConditions)(ts_estree_1.AST_NODE_TYPES.MethodDefinition, { kind: 'constructor' }); +/** + * Checks if a node is a setter method. + */ +function isSetter(node) { + return (!!node && + (node.type === ts_estree_1.AST_NODE_TYPES.MethodDefinition || + node.type === ts_estree_1.AST_NODE_TYPES.Property) && + node.kind === 'set'); +} +exports.isIdentifier = (0, helpers_1.isNodeOfType)(ts_estree_1.AST_NODE_TYPES.Identifier); +/** + * Checks if a node represents an `await …` expression. + */ +exports.isAwaitExpression = (0, helpers_1.isNodeOfType)(ts_estree_1.AST_NODE_TYPES.AwaitExpression); +/** + * Checks if a possible token is the `await` keyword. + */ +exports.isAwaitKeyword = (0, helpers_1.isTokenOfTypeWithConditions)(ts_estree_1.AST_TOKEN_TYPES.Identifier, { value: 'await' }); +/** + * Checks if a possible token is the `type` keyword. + */ +exports.isTypeKeyword = (0, helpers_1.isTokenOfTypeWithConditions)(ts_estree_1.AST_TOKEN_TYPES.Identifier, { value: 'type' }); +/** + * Checks if a possible token is the `import` keyword. + */ +exports.isImportKeyword = (0, helpers_1.isTokenOfTypeWithConditions)(ts_estree_1.AST_TOKEN_TYPES.Keyword, { value: 'import' }); +exports.isLoop = (0, helpers_1.isNodeOfTypes)([ + ts_estree_1.AST_NODE_TYPES.DoWhileStatement, + ts_estree_1.AST_NODE_TYPES.ForStatement, + ts_estree_1.AST_NODE_TYPES.ForInStatement, + ts_estree_1.AST_NODE_TYPES.ForOfStatement, + ts_estree_1.AST_NODE_TYPES.WhileStatement, +]); diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/InferTypesFromRule.d.ts b/node_modules/@typescript-eslint/utils/dist/eslint-utils/InferTypesFromRule.d.ts new file mode 100644 index 00000000..b3abc64b --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/InferTypesFromRule.d.ts @@ -0,0 +1,10 @@ +import type { RuleCreateFunction, RuleModule } from '../ts-eslint'; +/** + * Uses type inference to fetch the Options type from the given RuleModule + */ +export type InferOptionsTypeFromRule = T extends RuleModule ? Options : T extends RuleCreateFunction ? Options : unknown; +/** + * Uses type inference to fetch the MessageIds type from the given RuleModule + */ +export type InferMessageIdsTypeFromRule = T extends RuleModule ? MessageIds : T extends RuleCreateFunction ? MessageIds : unknown; +//# sourceMappingURL=InferTypesFromRule.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/InferTypesFromRule.d.ts.map b/node_modules/@typescript-eslint/utils/dist/eslint-utils/InferTypesFromRule.d.ts.map new file mode 100644 index 00000000..925db43d --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/InferTypesFromRule.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InferTypesFromRule.d.ts","sourceRoot":"","sources":["../../src/eslint-utils/InferTypesFromRule.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAEnE;;GAEG;AACH,MAAM,MAAM,wBAAwB,CAAC,CAAC,IACpC,CAAC,SAAS,UAAU,CAAC,MAAM,WAAW,EAAE,MAAM,OAAO,CAAC,GAClD,OAAO,GACP,CAAC,SAAS,kBAAkB,CAAC,MAAM,WAAW,EAAE,MAAM,OAAO,CAAC,GAC5D,OAAO,GACP,OAAO,CAAC;AAEhB;;GAEG;AACH,MAAM,MAAM,2BAA2B,CAAC,CAAC,IACvC,CAAC,SAAS,UAAU,CAAC,MAAM,UAAU,EAAE,MAAM,SAAS,CAAC,GACnD,UAAU,GACV,CAAC,SAAS,kBAAkB,CAAC,MAAM,UAAU,EAAE,MAAM,SAAS,CAAC,GAC7D,UAAU,GACV,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/InferTypesFromRule.js b/node_modules/@typescript-eslint/utils/dist/eslint-utils/InferTypesFromRule.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/InferTypesFromRule.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.d.ts b/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.d.ts new file mode 100644 index 00000000..573efc7f --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.d.ts @@ -0,0 +1,28 @@ +import type { RuleContext, RuleListener, RuleMetaData, RuleMetaDataDocs, RuleModule } from '../ts-eslint/Rule'; +export type NamedCreateRuleMetaDocs = Omit; +export type NamedCreateRuleMeta = { + docs: PluginDocs & RuleMetaDataDocs; +} & Omit, 'docs'>; +export interface RuleCreateAndOptions { + create: (context: Readonly>, optionsWithDefault: Readonly) => RuleListener; + defaultOptions: Readonly; +} +export interface RuleWithMeta extends RuleCreateAndOptions { + meta: RuleMetaData; +} +export interface RuleWithMetaAndName extends RuleCreateAndOptions { + meta: NamedCreateRuleMeta; + name: string; +} +/** + * Creates reusable function to create rules with default options and docs URLs. + * + * @param urlCreator Creates a documentation URL for a given rule name. + * @returns Function to create a rule with the docs URL format. + */ +export declare function RuleCreator(urlCreator: (ruleName: string) => string): ({ meta, name, ...rule }: Readonly>) => RuleModule; +export declare namespace RuleCreator { + var withoutDocs: (args: Readonly>) => RuleModule; +} +export { type RuleListener, type RuleModule } from '../ts-eslint/Rule'; +//# sourceMappingURL=RuleCreator.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.d.ts.map b/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.d.ts.map new file mode 100644 index 00000000..69c927cf --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RuleCreator.d.ts","sourceRoot":"","sources":["../../src/eslint-utils/RuleCreator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACX,MAAM,mBAAmB,CAAC;AAK3B,MAAM,MAAM,uBAAuB,GAAG,IAAI,CAAC,gBAAgB,EAAE,KAAK,CAAC,CAAC;AAEpE,MAAM,MAAM,mBAAmB,CAC7B,UAAU,SAAS,MAAM,EACzB,UAAU,GAAG,OAAO,EACpB,OAAO,SAAS,SAAS,OAAO,EAAE,GAAG,EAAE,IACrC;IACF,IAAI,E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E,UAAU,CAAC,CAYhD;yBA1Be,WAAW;sBA0DzB,OAAO,SAAS,SAAS,OAAO,EAAE,EAClC,UAAU,SAAS,MAAM,QAEnB,QAAQ,CAAC,YAAY,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC,KAChD,UAAU,CAAC,UAAU,EAAE,OAAO,CAAC;;AAIlC,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.js b/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.js new file mode 100644 index 00000000..b4903e86 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RuleCreator = RuleCreator; +const applyDefault_1 = require("./applyDefault"); +/** + * Creates reusable function to create rules with default options and docs URLs. + * + * @param urlCreator Creates a documentation URL for a given rule name. + * @returns Function to create a rule with the docs URL format. + */ +function RuleCreator(urlCreator) { + // This function will get much easier to call when this is merged https://github.com/Microsoft/TypeScript/pull/26349 + // TODO - when the above PR lands; add type checking for the context.report `data` property + return function createNamedRule({ meta, name, ...rule }) { + return createRule({ + meta: { + ...meta, + docs: { + ...meta.docs, + url: urlCreator(name), + }, + }, + ...rule, + }); + }; +} +function createRule({ create, defaultOptions, meta, }) { + return { + create(context) { + const optionsWithDefault = (0, applyDefault_1.applyDefault)(defaultOptions, context.options); + return create(context, optionsWithDefault); + }, + defaultOptions, + meta, + }; +} +/** + * Creates a well-typed TSESLint custom ESLint rule without a docs URL. + * + * @returns Well-typed TSESLint custom ESLint rule. + * @remarks It is generally better to provide a docs URL function to RuleCreator. + */ +RuleCreator.withoutDocs = function withoutDocs(args) { + return createRule(args); +}; diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/applyDefault.d.ts b/node_modules/@typescript-eslint/utils/dist/eslint-utils/applyDefault.d.ts new file mode 100644 index 00000000..b0552c61 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/applyDefault.d.ts @@ -0,0 +1,9 @@ +/** + * Pure function - doesn't mutate either parameter! + * Uses the default options and overrides with the options provided by the user + * @param defaultOptions the defaults + * @param userOptions the user opts + * @returns the options with defaults + */ +export declare function applyDefault(defaultOptions: Readonly, userOptions: Readonly | null): Default; +//# sourceMappingURL=applyDefault.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/applyDefault.d.ts.map b/node_modules/@typescript-eslint/utils/dist/eslint-utils/applyDefault.d.ts.map new file mode 100644 index 00000000..eac05699 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/applyDefault.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"applyDefault.d.ts","sourceRoot":"","sources":["../../src/eslint-utils/applyDefault.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC1B,IAAI,SAAS,SAAS,OAAO,EAAE,EAC/B,OAAO,SAAS,IAAI,EAEpB,cAAc,EAAE,QAAQ,CAAC,OAAO,CAAC,EACjC,WAAW,EAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,IAAI,GACjC,OAAO,CAwBT"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/applyDefault.js b/node_modules/@typescript-eslint/utils/dist/eslint-utils/applyDefault.js new file mode 100644 index 00000000..7f1b395f --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/applyDefault.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.applyDefault = applyDefault; +const deepMerge_1 = require("./deepMerge"); +/** + * Pure function - doesn't mutate either parameter! + * Uses the default options and overrides with the options provided by the user + * @param defaultOptions the defaults + * @param userOptions the user opts + * @returns the options with defaults + */ +function applyDefault(defaultOptions, userOptions) { + // clone defaults + const options = structuredClone(defaultOptions); + if (userOptions == null) { + return options; + } + // For avoiding the type error + // `This expression is not callable. Type 'unknown' has no call signatures.ts(2349)` + options.forEach((opt, i) => { + // eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish + if (userOptions[i] !== undefined) { + const userOpt = userOptions[i]; + if ((0, deepMerge_1.isObjectNotArray)(userOpt) && (0, deepMerge_1.isObjectNotArray)(opt)) { + options[i] = (0, deepMerge_1.deepMerge)(opt, userOpt); + } + else { + options[i] = userOpt; + } + } + }); + return options; +} diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/deepMerge.d.ts b/node_modules/@typescript-eslint/utils/dist/eslint-utils/deepMerge.d.ts new file mode 100644 index 00000000..d83acf10 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/deepMerge.d.ts @@ -0,0 +1,15 @@ +export type ObjectLike = Record; +/** + * Check if the variable contains an object strictly rejecting arrays + * @returns `true` if obj is an object + */ +export declare function isObjectNotArray(obj: unknown): obj is ObjectLike; +/** + * Pure function - doesn't mutate either parameter! + * Merges two objects together deeply, overwriting the properties in first with the properties in second + * @param first The first object + * @param second The second object + * @returns a new object + */ +export declare function deepMerge(first?: ObjectLike, second?: ObjectLike): Record; +//# sourceMappingURL=deepMerge.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/deepMerge.d.ts.map b/node_modules/@typescript-eslint/utils/dist/eslint-utils/deepMerge.d.ts.map new file mode 100644 index 00000000..70f6e57b --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/deepMerge.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"deepMerge.d.ts","sourceRoot":"","sources":["../../src/eslint-utils/deepMerge.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,UAAU,CAAC,CAAC,GAAG,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AAExD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,UAAU,CAEhE;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CACvB,KAAK,GAAE,UAAe,EACtB,MAAM,GAAE,UAAe,GACtB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CA4BzB"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/deepMerge.js b/node_modules/@typescript-eslint/utils/dist/eslint-utils/deepMerge.js new file mode 100644 index 00000000..81017121 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/deepMerge.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isObjectNotArray = isObjectNotArray; +exports.deepMerge = deepMerge; +/** + * Check if the variable contains an object strictly rejecting arrays + * @returns `true` if obj is an object + */ +function isObjectNotArray(obj) { + return typeof obj === 'object' && obj != null && !Array.isArray(obj); +} +/** + * Pure function - doesn't mutate either parameter! + * Merges two objects together deeply, overwriting the properties in first with the properties in second + * @param first The first object + * @param second The second object + * @returns a new object + */ +function deepMerge(first = {}, second = {}) { + // get the unique set of keys across both objects + const keys = new Set([...Object.keys(first), ...Object.keys(second)]); + return Object.fromEntries([...keys].map(key => { + const firstHasKey = key in first; + const secondHasKey = key in second; + const firstValue = first[key]; + const secondValue = second[key]; + let value; + if (firstHasKey && secondHasKey) { + if (isObjectNotArray(firstValue) && isObjectNotArray(secondValue)) { + // object type + value = deepMerge(firstValue, secondValue); + } + else { + // value type + value = secondValue; + } + } + else if (firstHasKey) { + value = firstValue; + } + else { + value = secondValue; + } + return [key, value]; + })); +} diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.d.ts b/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.d.ts new file mode 100644 index 00000000..2f0a2f8f --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.d.ts @@ -0,0 +1,23 @@ +import type * as TSESLint from '../ts-eslint'; +import type { ParserServices, ParserServicesWithTypeInformation } from '../ts-estree'; +/** + * Try to retrieve type-aware parser service from context. + * This **_will_** throw if it is not available. + */ +export declare function getParserServices(context: Readonly>): ParserServicesWithTypeInformation; +/** + * Try to retrieve type-aware parser service from context. + * This **_will_** throw if it is not available. + */ +export declare function getParserServices(context: Readonly>, allowWithoutFullTypeInformation: false): ParserServicesWithTypeInformation; +/** + * Try to retrieve type-aware parser service from context. + * This **_will not_** throw if it is not available. + */ +export declare function getParserServices(context: Readonly>, allowWithoutFullTypeInformation: true): ParserServices; +/** + * Try to retrieve type-aware parser service from context. + * This may or may not throw if it is not available, depending on if `allowWithoutFullTypeInformation` is `true` + */ +export declare function getParserServices(context: Readonly>, allowWithoutFullTypeInformation: boolean): ParserServices; +//# sourceMappingURL=getParserServices.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.d.ts.map b/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.d.ts.map new file mode 100644 index 00000000..b2068056 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"getParserServices.d.ts","sourceRoot":"","sources":["../../src/eslint-utils/getParserServices.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,QAAQ,MAAM,cAAc,CAAC;AAC9C,OAAO,KAAK,EACV,cAAc,EACd,iCAAiC,EAClC,MAAM,cAAc,CAAC;AAWtB;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,SAAS,MAAM,EACzB,OAAO,SAAS,SAAS,OAAO,EAAE,EAElC,OAAO,EAAE,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,GAC3D,iCAAiC,CAAC;AACrC;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,SAAS,MAAM,EACzB,OAAO,SAAS,SAAS,OAAO,EAAE,EAElC,OAAO,EAAE,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,EAC5D,+BAA+B,EAAE,KAAK,GACrC,iCAAiC,CAAC;AACrC;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,SAAS,MAAM,EACzB,OAAO,SAAS,SAAS,OAAO,EAAE,EAElC,OAAO,EAAE,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,EAC5D,+BAA+B,EAAE,IAAI,GACpC,cAAc,CAAC;AAClB;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,SAAS,MAAM,EACzB,OAAO,SAAS,SAAS,OAAO,EAAE,EAElC,OAAO,EAAE,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,EAC5D,+BAA+B,EAAE,OAAO,GACvC,cAAc,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.js b/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.js new file mode 100644 index 00000000..bd0f76b6 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getParserServices = getParserServices; +const parserSeemsToBeTSESLint_1 = require("./parserSeemsToBeTSESLint"); +const ERROR_MESSAGE_REQUIRES_PARSER_SERVICES = "You have used a rule which requires type information, but don't have parserOptions set to generate type information for this file. See https://typescript-eslint.io/getting-started/typed-linting for enabling linting with type information."; +const ERROR_MESSAGE_UNKNOWN_PARSER = 'Note: detected a parser other than @typescript-eslint/parser. Make sure the parser is configured to forward "parserOptions.project" to @typescript-eslint/parser.'; +function getParserServices(context, allowWithoutFullTypeInformation = false) { + const parser = context.parserPath || context.languageOptions.parser?.meta?.name; + // This check is unnecessary if the user is using the latest version of our parser. + // + // However the world isn't perfect: + // - Users often use old parser versions. + // Old versions of the parser would not return any parserServices unless parserOptions.project was set. + // - Users sometimes use parsers that aren't @typescript-eslint/parser + // Other parsers won't return the parser services we expect (if they return any at all). + // + // This check allows us to handle bad user setups whilst providing a nice user-facing + // error message explaining the problem. + if (context.sourceCode.parserServices?.esTreeNodeToTSNodeMap == null || + context.sourceCode.parserServices.tsNodeToESTreeNodeMap == null) { + throwError(parser); + } + // if a rule requires full type information, then hard fail if it doesn't exist + // this forces the user to supply parserOptions.project + if (context.sourceCode.parserServices.program == null && + !allowWithoutFullTypeInformation) { + throwError(parser); + } + return context.sourceCode.parserServices; +} +/* eslint-enable @typescript-eslint/unified-signatures */ +function throwError(parser) { + const messages = [ + ERROR_MESSAGE_REQUIRES_PARSER_SERVICES, + `Parser: ${parser || '(unknown)'}`, + !(0, parserSeemsToBeTSESLint_1.parserSeemsToBeTSESLint)(parser) && ERROR_MESSAGE_UNKNOWN_PARSER, + ].filter(Boolean); + throw new Error(messages.join('\n')); +} diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/index.d.ts b/node_modules/@typescript-eslint/utils/dist/eslint-utils/index.d.ts new file mode 100644 index 00000000..95b326ec --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/index.d.ts @@ -0,0 +1,7 @@ +export * from './applyDefault'; +export * from './deepMerge'; +export * from './getParserServices'; +export * from './InferTypesFromRule'; +export * from './nullThrows'; +export * from './RuleCreator'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/index.d.ts.map b/node_modules/@typescript-eslint/utils/dist/eslint-utils/index.d.ts.map new file mode 100644 index 00000000..d5c13312 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/eslint-utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,sBAAsB,CAAC;AACrC,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/index.js b/node_modules/@typescript-eslint/utils/dist/eslint-utils/index.js new file mode 100644 index 00000000..c07bc84f --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/index.js @@ -0,0 +1,22 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./applyDefault"), exports); +__exportStar(require("./deepMerge"), exports); +__exportStar(require("./getParserServices"), exports); +__exportStar(require("./InferTypesFromRule"), exports); +__exportStar(require("./nullThrows"), exports); +__exportStar(require("./RuleCreator"), exports); diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/nullThrows.d.ts b/node_modules/@typescript-eslint/utils/dist/eslint-utils/nullThrows.d.ts new file mode 100644 index 00000000..ec9b9b74 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/nullThrows.d.ts @@ -0,0 +1,13 @@ +/** + * A set of common reasons for calling nullThrows + */ +export declare const NullThrowsReasons: { + readonly MissingParent: "Expected node to have a parent."; + readonly MissingToken: (token: string, thing: string) => string; +}; +/** + * Assert that a value must not be null or undefined. + * This is a nice explicit alternative to the non-null assertion operator. + */ +export declare function nullThrows(value: T, message: string): NonNullable; +//# sourceMappingURL=nullThrows.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/nullThrows.d.ts.map b/node_modules/@typescript-eslint/utils/dist/eslint-utils/nullThrows.d.ts.map new file mode 100644 index 00000000..0da9e62d --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/nullThrows.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"nullThrows.d.ts","sourceRoot":"","sources":["../../src/eslint-utils/nullThrows.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,iBAAiB;;mCAEN,MAAM,SAAS,MAAM;CAEnC,CAAC;AAEX;;;GAGG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,CAMvE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/nullThrows.js b/node_modules/@typescript-eslint/utils/dist/eslint-utils/nullThrows.js new file mode 100644 index 00000000..89e93828 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/nullThrows.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NullThrowsReasons = void 0; +exports.nullThrows = nullThrows; +/** + * A set of common reasons for calling nullThrows + */ +exports.NullThrowsReasons = { + MissingParent: 'Expected node to have a parent.', + MissingToken: (token, thing) => `Expected to find a ${token} for the ${thing}.`, +}; +/** + * Assert that a value must not be null or undefined. + * This is a nice explicit alternative to the non-null assertion operator. + */ +function nullThrows(value, message) { + if (value == null) { + throw new Error(`Non-null Assertion Failed: ${message}`); + } + return value; +} diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/parserSeemsToBeTSESLint.d.ts b/node_modules/@typescript-eslint/utils/dist/eslint-utils/parserSeemsToBeTSESLint.d.ts new file mode 100644 index 00000000..ba5bebe6 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/parserSeemsToBeTSESLint.d.ts @@ -0,0 +1,2 @@ +export declare function parserSeemsToBeTSESLint(parser: string | undefined): boolean; +//# sourceMappingURL=parserSeemsToBeTSESLint.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/parserSeemsToBeTSESLint.d.ts.map b/node_modules/@typescript-eslint/utils/dist/eslint-utils/parserSeemsToBeTSESLint.d.ts.map new file mode 100644 index 00000000..57c62220 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/parserSeemsToBeTSESLint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parserSeemsToBeTSESLint.d.ts","sourceRoot":"","sources":["../../src/eslint-utils/parserSeemsToBeTSESLint.ts"],"names":[],"mappings":"AAAA,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAE3E"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/eslint-utils/parserSeemsToBeTSESLint.js b/node_modules/@typescript-eslint/utils/dist/eslint-utils/parserSeemsToBeTSESLint.js new file mode 100644 index 00000000..c976b6c0 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/eslint-utils/parserSeemsToBeTSESLint.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parserSeemsToBeTSESLint = parserSeemsToBeTSESLint; +function parserSeemsToBeTSESLint(parser) { + return !!parser && /(?:typescript-eslint|\.\.)[\w/\\]*parser/.test(parser); +} diff --git a/node_modules/@typescript-eslint/utils/dist/index.d.ts b/node_modules/@typescript-eslint/utils/dist/index.d.ts new file mode 100644 index 00000000..fbc8815b --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/index.d.ts @@ -0,0 +1,7 @@ +export * as ASTUtils from './ast-utils'; +export * as ESLintUtils from './eslint-utils'; +export * as JSONSchema from './json-schema'; +export * as TSESLint from './ts-eslint'; +export * from './ts-estree'; +export * as TSUtils from './ts-utils'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/index.d.ts.map b/node_modules/@typescript-eslint/utils/dist/index.d.ts.map new file mode 100644 index 00000000..107a73c0 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,QAAQ,MAAM,aAAa,CAAC;AAExC,OAAO,KAAK,WAAW,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,UAAU,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,QAAQ,MAAM,aAAa,CAAC;AACxC,cAAc,aAAa,CAAC;AAC5B,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/index.js b/node_modules/@typescript-eslint/utils/dist/index.js new file mode 100644 index 00000000..8008ec2f --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/index.js @@ -0,0 +1,45 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSUtils = exports.TSESLint = exports.JSONSchema = exports.ESLintUtils = exports.ASTUtils = void 0; +exports.ASTUtils = __importStar(require("./ast-utils")); +exports.ESLintUtils = __importStar(require("./eslint-utils")); +exports.JSONSchema = __importStar(require("./json-schema")); +exports.TSESLint = __importStar(require("./ts-eslint")); +__exportStar(require("./ts-estree"), exports); +exports.TSUtils = __importStar(require("./ts-utils")); diff --git a/node_modules/@typescript-eslint/utils/dist/json-schema.d.ts b/node_modules/@typescript-eslint/utils/dist/json-schema.d.ts new file mode 100644 index 00000000..51303201 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/json-schema.d.ts @@ -0,0 +1,388 @@ +/** + * This is a fork of https://github.com/DefinitelyTyped/DefinitelyTyped/blob/13f63c2eb8d7479caf01ab8d72f9e3683368a8f5/types/json-schema/index.d.ts + * We intentionally fork this because: + * - ESLint ***ONLY*** supports JSONSchema v4 + * - We want to provide stricter types + */ +/** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 + */ +export type JSONSchema4TypeName = 'any' | 'array' | 'boolean' | 'integer' | 'null' | 'number' | 'object' | 'string'; +/** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-3.5 + */ +export type JSONSchema4Type = boolean | number | string | null; +export type JSONSchema4TypeExtended = JSONSchema4Array | JSONSchema4Object | JSONSchema4Type; +export interface JSONSchema4Object { + [key: string]: JSONSchema4TypeExtended; +} +export interface JSONSchema4Array extends Array { +} +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-04/schema#' + * - 'http://json-schema.org/draft-04/hyper-schema#' + * - 'http://json-schema.org/draft-03/schema#' + * - 'http://json-schema.org/draft-03/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema4Version = string; +/** + * JSON Schema V4 + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04 + */ +export type JSONSchema4 = JSONSchema4AllOfSchema | JSONSchema4AnyOfSchema | JSONSchema4AnySchema | JSONSchema4ArraySchema | JSONSchema4BooleanSchema | JSONSchema4MultiSchema | JSONSchema4NullSchema | JSONSchema4NumberSchema | JSONSchema4ObjectSchema | JSONSchema4OneOfSchema | JSONSchema4RefSchema | JSONSchema4StringSchema; +interface JSONSchema4Base { + /** + * Reusable definitions that can be referenced via `$ref` + */ + $defs?: Record | undefined; + /** + * Path to a schema defined in `definitions`/`$defs` that will form the base + * for this schema. + * + * If you are defining an "array" schema (`schema: [ ... ]`) for your rule + * then you should prefix this with `items/0` so that the validator can find + * your definitions. + * + * eg: `'#/items/0/definitions/myDef'` + * + * Otherwise if you are defining an "object" schema (`schema: { ... }`) for + * your rule you can directly reference your definitions + * + * eg: `'#/definitions/myDef'` + */ + $ref?: string | undefined; + $schema?: JSONSchema4Version | undefined; + /** + * (AND) Must be valid against all of the sub-schemas + */ + allOf?: JSONSchema4[] | undefined; + /** + * (OR) Must be valid against any of the sub-schemas + */ + anyOf?: JSONSchema4[] | undefined; + /** + * The default value for the item if not present + */ + default?: JSONSchema4TypeExtended | undefined; + /** + * Reusable definitions that can be referenced via `$ref` + */ + definitions?: Record | undefined; + /** + * This attribute is a string that provides a full description of the of + * purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.22 + */ + description?: string | undefined; + /** + * The value of this property MUST be another schema which will provide + * a base schema which the current schema will inherit from. The + * inheritance rules are such that any instance that is valid according + * to the current schema MUST be valid according to the referenced + * schema. This MAY also be an array, in which case, the instance MUST + * be valid for all the schemas in the array. A schema that extends + * another schema MAY define additional attributes, constrain existing + * attributes, or add other constraints. + * + * Conceptually, the behavior of extends can be seen as validating an + * instance against all constraints in the extending schema as well as + * the extended schema(s). + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.26 + */ + extends?: string | string[] | undefined; + id?: string | undefined; + /** + * (NOT) Must not be valid against the given schema + */ + not?: JSONSchema4 | undefined; + /** + * (XOR) Must be valid against exactly one of the sub-schemas + */ + oneOf?: JSONSchema4[] | undefined; + /** + * This attribute indicates if the instance must have a value, and not + * be undefined. This is false by default, making the instance + * optional. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.7 + */ + required?: boolean | string[] | undefined; + /** + * This attribute is a string that provides a short description of the + * instance property. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.21 + */ + title?: string | undefined; + /** + * A single type, or a union of simple types + */ + type?: JSONSchema4TypeName | JSONSchema4TypeName[] | undefined; +} +export interface JSONSchema4RefSchema extends JSONSchema4Base { + $ref: string; + type?: undefined; +} +export interface JSONSchema4AllOfSchema extends JSONSchema4Base { + allOf: JSONSchema4[]; + type?: undefined; +} +export interface JSONSchema4AnyOfSchema extends JSONSchema4Base { + anyOf: JSONSchema4[]; + type?: undefined; +} +export interface JSONSchema4OneOfSchema extends JSONSchema4Base { + oneOf: JSONSchema4[]; + type?: undefined; +} +export interface JSONSchema4MultiSchema extends Omit, Omit, Omit, Omit, Omit, Omit, Omit { + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19 + */ + enum?: JSONSchema4Type[]; + type: JSONSchema4TypeName[]; +} +/** + * @see https://json-schema.org/understanding-json-schema/reference/object.html + */ +export interface JSONSchema4ObjectSchema extends JSONSchema4Base { + /** + * This attribute defines a schema for all properties that are not + * explicitly defined in an object type definition. If specified, the + * value MUST be a schema or a boolean. If false is provided, no + * additional properties are allowed beyond the properties defined in + * the schema. The default value is an empty schema which allows any + * value for additional properties. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.4 + */ + additionalProperties?: boolean | JSONSchema4 | undefined; + /** + * The `dependencies` keyword conditionally applies a sub-schema when a given + * property is present. This schema is applied in the same way `allOf` applies + * schemas. Nothing is merged or extended. Both schemas apply independently. + */ + dependencies?: Record | undefined; + /** + * The maximum number of properties allowed for record-style schemas + */ + maxProperties?: number | undefined; + /** + * The minimum number of properties required for record-style schemas + */ + minProperties?: number | undefined; + /** + * This attribute is an object that defines the schema for a set of + * property names of an object instance. The name of each property of + * this attribute's object is a regular expression pattern in the ECMA + * 262/Perl 5 format, while the value is a schema. If the pattern + * matches the name of a property on the instance object, the value of + * the instance's property MUST be valid against the pattern name's + * schema value. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.3 + */ + patternProperties?: Record | undefined; + /** + * This attribute is an object with property definitions that define the + * valid values of instance object property values. When the instance + * value is an object, the property values of the instance object MUST + * conform to the property definitions in this object. In this object, + * each property definition's value MUST be a schema, and the property's + * name MUST be the name of the instance property that it defines. The + * instance property value MUST be valid according to the schema from + * the property definition. Properties are considered unordered, the + * order of the instance properties MAY be in any order. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.2 + */ + properties?: Record | undefined; + type: 'object'; +} +/** + * @see https://json-schema.org/understanding-json-schema/reference/array.html + */ +export interface JSONSchema4ArraySchema extends JSONSchema4Base { + /** + * May only be defined when "items" is defined, and is a tuple of JSONSchemas. + * + * This provides a definition for additional items in an array instance + * when tuple definitions of the items is provided. This can be false + * to indicate additional items in the array are not allowed, or it can + * be a schema that defines the schema of the additional items. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.6 + */ + additionalItems?: boolean | JSONSchema4 | undefined; + /** + * This attribute defines the allowed items in an instance array, and + * MUST be a schema or an array of schemas. The default value is an + * empty schema which allows any value for items in the instance array. + * + * When this attribute value is a schema and the instance value is an + * array, then all the items in the array MUST be valid according to the + * schema. + * + * When this attribute value is an array of schemas and the instance + * value is an array, each position in the instance array MUST conform + * to the schema in the corresponding position for this array. This + * called tuple typing. When tuple typing is used, additional items are + * allowed, disallowed, or constrained by the "additionalItems" + * (Section 5.6) attribute using the same rules as + * "additionalProperties" (Section 5.4) for objects. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.5 + */ + items?: JSONSchema4 | JSONSchema4[] | undefined; + /** + * Defines the maximum length of an array + */ + maxItems?: number | undefined; + /** + * Defines the minimum length of an array + */ + minItems?: number | undefined; + type: 'array'; + /** + * Enforces that all items in the array are unique + */ + uniqueItems?: boolean | undefined; +} +/** + * @see https://json-schema.org/understanding-json-schema/reference/string.html + */ +export interface JSONSchema4StringSchema extends JSONSchema4Base { + enum?: string[] | undefined; + /** + * The `format` keyword allows for basic semantic identification of certain + * kinds of string values that are commonly used. + * + * For example, because JSON doesn’t have a “DateTime” type, dates need to be + * encoded as strings. `format` allows the schema author to indicate that the + * string value should be interpreted as a date. + * + * ajv v6 provides a few built-in formats - all other strings will cause AJV + * to throw during schema compilation + */ + format?: 'date' | 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'json-pointer' | 'json-pointer-uri-fragment' | 'regex' | 'relative-json-pointer' | 'time' | 'uri' | 'uri-reference' | 'uri-template' | 'url' | 'uuid' | undefined; + /** + * The maximum allowed length for the string + */ + maxLength?: number | undefined; + /** + * The minimum allowed length for the string + */ + minLength?: number | undefined; + /** + * The `pattern` keyword is used to restrict a string to a particular regular + * expression. The regular expression syntax is the one defined in JavaScript + * (ECMA 262 specifically) with Unicode support. + * + * When defining the regular expressions, it’s important to note that the + * string is considered valid if the expression matches anywhere within the + * string. For example, the regular expression "p" will match any string with + * a p in it, such as "apple" not just a string that is simply "p". Therefore, + * it is usually less confusing, as a matter of course, to surround the + * regular expression in ^...$, for example, "^p$", unless there is a good + * reason not to do so. + */ + pattern?: string | undefined; + type: 'string'; +} +/** + * @see https://json-schema.org/understanding-json-schema/reference/numeric.html + */ +export interface JSONSchema4NumberSchema extends JSONSchema4Base { + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19 + */ + enum?: number[] | undefined; + /** + * The exclusive minimum allowed value for the number + * - `true` = `x < maximum` + * - `false` = `x <= maximum` + * + * Default is `false` + */ + exclusiveMaximum?: boolean | undefined; + /** + * Indicates whether or not `minimum` is the inclusive or exclusive minimum + * - `true` = `x > minimum` + * - `false` = `x ≥ minimum` + * + * Default is `false` + */ + exclusiveMinimum?: boolean | undefined; + /** + * The maximum allowed value for the number + */ + maximum?: number | undefined; + /** + * The minimum allowed value for the number + */ + minimum?: number | undefined; + /** + * Numbers can be restricted to a multiple of a given number, using the + * `multipleOf` keyword. It may be set to any positive number. + */ + multipleOf?: number | undefined; + type: 'integer' | 'number'; +} +/** + * @see https://json-schema.org/understanding-json-schema/reference/boolean.html + */ +export interface JSONSchema4BooleanSchema extends JSONSchema4Base { + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19 + */ + enum?: boolean[] | undefined; + type: 'boolean'; +} +/** + * @see https://json-schema.org/understanding-json-schema/reference/null.html + */ +export interface JSONSchema4NullSchema extends JSONSchema4Base { + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19 + */ + enum?: null[] | undefined; + type: 'null'; +} +export interface JSONSchema4AnySchema extends JSONSchema4Base { + type: 'any'; +} +export {}; +//# sourceMappingURL=json-schema.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/json-schema.d.ts.map b/node_modules/@typescript-eslint/utils/dist/json-schema.d.ts.map new file mode 100644 index 00000000..7e85351c --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/json-schema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"json-schema.d.ts","sourceRoot":"","sources":["../src/json-schema.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAC3B,KAAK,GACL,OAAO,GACP,SAAS,GACT,SAAS,GACT,MAAM,GACN,QAAQ,GACR,QAAQ,GACR,QAAQ,CAAC;AAEb;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;AAE/D,MAAM,MAAM,uBAAuB,GAC/B,gBAAgB,GAChB,iBAAiB,GACjB,eAAe,CAAC;AAEpB,MAAM,WAAW,iBAAiB;IAChC,CAAC,GAAG,EAAE,MAAM,GAAG,uBAAuB,CAAC;CACxC;AAKD,MAAM,WAAW,gBAAiB,SAAQ,KAAK,CAAC,uBAAuB,CAAC;CAAG;AAE3E;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAExC;;;GAGG;AACH,MAAM,MAAM,WAAW,GACnB,sBAAsB,GACtB,sBAAsB,GACtB,oBAAoB,GACpB,sBAAsB,GACtB,wBAAwB,GACxB,sBAAsB,GACtB,qBAAqB,GACrB,uBAAuB,GACvB,uBAAuB,GACvB,sBAAsB,GACtB,oBAAoB,GACpB,uBAAuB,CAAC;AAE5B,UAAU,eAAe;IACvB;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GAAG,SAA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D;;;;;;;;OAQG;IACH,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;IAE5B;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAEvC;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAEvC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE7B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE7B;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAEhC,IAAI,EAAE,SAAS,GAAG,QAAQ,CAAC;CAC5B;AAED;;GAEG;AACH,MAAM,WAAW,wBAAyB,SAAQ,eAAe;IAC/D;;;;;;;;OAQG;IACH,IAAI,CAAC,EAAE,OAAO,EAAE,GAAG,SAAS,CAAC;IAE7B,IAAI,EAAE,SAAS,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,qBAAsB,SAAQ,eAAe;IAC5D;;;;;;;;OAQG;IACH,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,SAAS,CAAC;IAE1B,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,oBAAqB,SAAQ,eAAe;IAC3D,IAAI,EAAE,KAAK,CAAC;CACb"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/json-schema.js b/node_modules/@typescript-eslint/utils/dist/json-schema.js new file mode 100644 index 00000000..2a79849e --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/json-schema.js @@ -0,0 +1,8 @@ +"use strict"; +/** + * This is a fork of https://github.com/DefinitelyTyped/DefinitelyTyped/blob/13f63c2eb8d7479caf01ab8d72f9e3683368a8f5/types/json-schema/index.d.ts + * We intentionally fork this because: + * - ESLint ***ONLY*** supports JSONSchema v4 + * - We want to provide stricter types + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/AST.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/AST.d.ts new file mode 100644 index 00000000..3b56109d --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/AST.d.ts @@ -0,0 +1,9 @@ +import type { AST_TOKEN_TYPES, TSESTree } from '../ts-estree'; +declare namespace AST { + type TokenType = AST_TOKEN_TYPES; + type Token = TSESTree.Token; + type SourceLocation = TSESTree.SourceLocation; + type Range = TSESTree.Range; +} +export type { AST }; +//# sourceMappingURL=AST.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/AST.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/AST.d.ts.map new file mode 100644 index 00000000..d62fd00f --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/AST.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AST.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/AST.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAE9D,kBAAU,GAAG,CAAC;IACZ,KAAY,SAAS,GAAG,eAAe,CAAC;IAExC,KAAY,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;IAEnC,KAAY,cAAc,GAAG,QAAQ,CAAC,cAAc,CAAC;IAErD,KAAY,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC;CACpC;AAED,YAAY,EAAE,GAAG,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/AST.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/AST.js new file mode 100644 index 00000000..d89703d6 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/AST.js @@ -0,0 +1,3 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-namespace, no-restricted-syntax */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Config.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Config.d.ts new file mode 100644 index 00000000..8ee36302 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Config.d.ts @@ -0,0 +1,277 @@ +import type { Parser as ParserType } from './Parser'; +import type * as ParserOptionsTypes from './ParserOptions'; +import type { Processor as ProcessorType } from './Processor'; +import type { LooseRuleDefinition, SharedConfigurationSettings } from './Rule'; +/** @internal */ +export declare namespace SharedConfig { + type Severity = 0 | 1 | 2; + type SeverityString = 'error' | 'off' | 'warn'; + type RuleLevel = Severity | SeverityString; + type RuleLevelAndOptions = [RuleLevel, ...unknown[]]; + type RuleEntry = RuleLevel | RuleLevelAndOptions; + type RulesRecord = Partial>; + type GlobalVariableOptionBase = 'off' | /** @deprecated use `'readonly'` */ 'readable' | 'readonly' | 'writable' | /** @deprecated use `'writable'` */ 'writeable'; + type GlobalVariableOptionBoolean = /** @deprecated use `'readonly'` */ false | /** @deprecated use `'writable'` */ true; + type GlobalVariableOption = GlobalVariableOptionBase | GlobalVariableOptionBoolean; + interface GlobalsConfig { + [name: string]: GlobalVariableOption; + } + interface EnvironmentConfig { + [name: string]: boolean; + } + type ParserOptions = ParserOptionsTypes.ParserOptions; + interface PluginMeta { + /** + * The meta.name property should match the npm package name for your plugin. + */ + name: string; + /** + * The meta.version property should match the npm package version for your plugin. + */ + version: string; + } +} +export declare namespace ClassicConfig { + export type EnvironmentConfig = SharedConfig.EnvironmentConfig; + export type GlobalsConfig = SharedConfig.GlobalsConfig; + export type GlobalVariableOption = SharedConfig.GlobalVariableOption; + export type GlobalVariableOptionBase = SharedConfig.GlobalVariableOptionBase; + export type ParserOptions = SharedConfig.ParserOptions; + export type RuleEntry = SharedConfig.RuleEntry; + export type RuleLevel = SharedConfig.RuleLevel; + export type RuleLevelAndOptions = SharedConfig.RuleLevelAndOptions; + export type RulesRecord = SharedConfig.RulesRecord; + export type Severity = SharedConfig.Severity; + export type SeverityString = SharedConfig.SeverityString; + interface BaseConfig { + $schema?: string; + /** + * The environment settings. + */ + env?: EnvironmentConfig; + /** + * The path to other config files or the package name of shareable configs. + */ + extends?: string | string[]; + /** + * The global variable settings. + */ + globals?: GlobalsConfig; + /** + * The flag that disables comment directives. + */ + noInlineConfig?: boolean; + /** + * The override settings per kind of files. + */ + overrides?: ConfigOverride[]; + /** + * The path to a parser or the package name of a parser. + */ + parser?: string | null; + /** + * The parser options. + */ + parserOptions?: ParserOptions; + /** + * The plugin specifiers. + */ + plugins?: string[]; + /** + * The processor specifier. + */ + processor?: string; + /** + * The flag to report unused `eslint-disable` comments. + */ + reportUnusedDisableDirectives?: boolean; + /** + * The rule settings. + */ + rules?: RulesRecord; + /** + * The shared settings. + */ + settings?: SharedConfigurationSettings; + } + export interface ConfigOverride extends BaseConfig { + excludedFiles?: string | string[]; + files: string | string[]; + } + export interface Config extends BaseConfig { + /** + * The glob patterns that ignore to lint. + */ + ignorePatterns?: string | string[]; + /** + * The root flag. + */ + root?: boolean; + } + export {}; +} +export declare namespace FlatConfig { + type EcmaVersion = ParserOptionsTypes.EcmaVersion; + type GlobalsConfig = SharedConfig.GlobalsConfig; + type Parser = ParserType.LooseParserModule; + type ParserOptions = SharedConfig.ParserOptions; + type PluginMeta = SharedConfig.PluginMeta; + type Processor = ProcessorType.LooseProcessorModule; + type RuleEntry = SharedConfig.RuleEntry; + type RuleLevel = SharedConfig.RuleLevel; + type RuleLevelAndOptions = SharedConfig.RuleLevelAndOptions; + type Rules = SharedConfig.RulesRecord; + type Settings = SharedConfigurationSettings; + type Severity = SharedConfig.Severity; + type SeverityString = SharedConfig.SeverityString; + type SourceType = 'commonjs' | ParserOptionsTypes.SourceType; + interface SharedConfigs { + [key: string]: Config | ConfigArray; + } + interface Plugin { + /** + * Shared configurations bundled with the plugin. + * Users will reference these directly in their config (i.e. `plugin.configs.recommended`). + */ + configs?: SharedConfigs; + /** + * Metadata about your plugin for easier debugging and more effective caching of plugins. + */ + meta?: { + [K in keyof PluginMeta]?: PluginMeta[K] | undefined; + }; + /** + * The definition of plugin processors. + * Users can stringly reference the processor using the key in their config (i.e., `"pluginName/processorName"`). + */ + processors?: Partial> | undefined; + /** + * The definition of plugin rules. + * The key must be the name of the rule that users will use + * Users can stringly reference the rule using the key they registered the plugin under combined with the rule name. + * i.e. for the user config `plugins: { foo: pluginReference }` - the reference would be `"foo/ruleName"`. + */ + rules?: Record | undefined; + } + interface Plugins { + /** + * We intentionally omit the `configs` key from this object because it avoids + * type conflicts with old plugins that haven't updated their configs to flat configs yet. + * It's valid to reference these old plugins because ESLint won't access the + * `.config` property of a plugin when evaluating a flat config. + */ + [pluginAlias: string]: Omit; + } + interface LinterOptions { + /** + * A Boolean value indicating if inline configuration is allowed. + */ + noInlineConfig?: boolean; + /** + * A severity string indicating if and how unused disable and enable + * directives should be tracked and reported. For legacy compatibility, `true` + * is equivalent to `"warn"` and `false` is equivalent to `"off"`. + * @default "off" + */ + reportUnusedDisableDirectives?: boolean | SharedConfig.Severity | SharedConfig.SeverityString; + /** + * A severity string indicating if and how unused inline directives + * should be tracked and reported. + * + * since ESLint 9.19.0 + * @default "off" + */ + reportUnusedInlineConfigs?: SharedConfig.Severity | SharedConfig.SeverityString; + } + interface LanguageOptions { + /** + * The version of ECMAScript to support. + * May be any year (i.e., `2022`) or version (i.e., `5`). + * Set to `"latest"` for the most recent supported version. + * @default "latest" + */ + ecmaVersion?: EcmaVersion | undefined; + /** + * An object specifying additional objects that should be added to the global scope during linting. + */ + globals?: GlobalsConfig | undefined; + /** + * An object containing a `parse()` method or a `parseForESLint()` method. + * @default + * ``` + * // https://github.com/eslint/espree + * require('espree') + * ``` + */ + parser?: Parser | undefined; + /** + * An object specifying additional options that are passed directly to the parser. + * The available options are parser-dependent. + */ + parserOptions?: ParserOptions | undefined; + /** + * The type of JavaScript source code. + * Possible values are `"script"` for traditional script files, `"module"` for ECMAScript modules (ESM), and `"commonjs"` for CommonJS files. + * @default + * ``` + * // for `.js` and `.mjs` files + * "module" + * // for `.cjs` files + * "commonjs" + * ``` + */ + sourceType?: SourceType | undefined; + } + interface Config { + /** + * An array of glob patterns indicating the files that the configuration object should apply to. + * If not specified, the configuration object applies to all files matched by any other configuration object. + */ + files?: (string | string[])[]; + /** + * An array of glob patterns indicating the files that the configuration object should not apply to. + * If not specified, the configuration object applies to all files matched by files. + */ + ignores?: string[]; + /** + * Language specifier in the form `namespace/language-name` where `namespace` is a plugin name set in the `plugins` field. + */ + language?: string; + /** + * An object containing settings related to how JavaScript is configured for linting. + */ + languageOptions?: LanguageOptions; + /** + * An object containing settings related to the linting process. + */ + linterOptions?: LinterOptions; + /** + * An string to identify the configuration object. Used in error messages and inspection tools. + */ + name?: string; + /** + * An object containing a name-value mapping of plugin names to plugin objects. + * When `files` is specified, these plugins are only available to the matching files. + */ + plugins?: Plugins; + /** + * Either an object containing `preprocess()` and `postprocess()` methods or + * a string indicating the name of a processor inside of a plugin + * (i.e., `"pluginName/processorName"`). + */ + processor?: string | Processor; + /** + * An object containing the configured rules. + * When `files` or `ignores` are specified, these rule configurations are only available to the matching files. + */ + rules?: Rules; + /** + * An object containing name-value pairs of information that should be available to all rules. + */ + settings?: Settings; + } + type ConfigArray = Config[]; + type ConfigPromise = Promise; + type ConfigFile = ConfigArray | ConfigPromise; +} +//# sourceMappingURL=Config.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Config.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Config.d.ts.map new file mode 100644 index 00000000..375230b4 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Config.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/Config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,UAAU,CAAC;AACrD,OAAO,KAAK,KAAK,kBAAkB,MAAM,iBAAi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ACH,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB;;WAEG;QACH,eAAe,CAAC,EAAE,eAAe,CAAC;QAClC;;WAEG;QACH,aAAa,CAAC,EAAE,aAAa,CAAC;QAC9B;;WAEG;QACH,IAAI,CAAC,EAAE,MAAM,CAAC;QACd;;;WAGG;QACH,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB;;;;WAIG;QACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QAC/B;;;WAGG;QACH,KAAK,CAAC,EAAE,KAAK,CAAC;QACd;;WAEG;QACH,QAAQ,CAAC,EAAE,QAAQ,CAAC;KACrB;IACD,KAAY,WAAW,GAAG,MAAM,EAAE,CAAC;IACnC,KAAY,aAAa,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IACjD,KAAY,UAAU,GAAG,WAAW,GAAG,aAAa,CAAC;CACtD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Config.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Config.js new file mode 100644 index 00000000..8e47a1b2 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Config.js @@ -0,0 +1,3 @@ +"use strict"; +/* eslint-disable @typescript-eslint/consistent-indexed-object-style, @typescript-eslint/no-namespace */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/ESLint.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ESLint.d.ts new file mode 100644 index 00000000..7c171a3e --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ESLint.d.ts @@ -0,0 +1,8 @@ +export { FlatESLint } from './eslint/FlatESLint'; +export { FlatESLint as ESLint } from './eslint/FlatESLint'; +export { +/** + * @deprecated - use ESLint instead + */ +LegacyESLint, } from './eslint/LegacyESLint'; +//# sourceMappingURL=ESLint.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/ESLint.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ESLint.d.ts.map new file mode 100644 index 00000000..097c99f4 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ESLint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ESLint.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/ESLint.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,UAAU,IAAI,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO;AAEL;;GAEG;AACH,YAAY,GACb,MAAM,uBAAuB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/ESLint.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ESLint.js new file mode 100644 index 00000000..566f6908 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ESLint.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LegacyESLint = exports.ESLint = exports.FlatESLint = void 0; +var FlatESLint_1 = require("./eslint/FlatESLint"); +Object.defineProperty(exports, "FlatESLint", { enumerable: true, get: function () { return FlatESLint_1.FlatESLint; } }); +var FlatESLint_2 = require("./eslint/FlatESLint"); +Object.defineProperty(exports, "ESLint", { enumerable: true, get: function () { return FlatESLint_2.FlatESLint; } }); +var LegacyESLint_1 = require("./eslint/LegacyESLint"); +// TODO(eslint@v10) - remove this in the next major +/** + * @deprecated - use ESLint instead + */ +Object.defineProperty(exports, "LegacyESLint", { enumerable: true, get: function () { return LegacyESLint_1.LegacyESLint; } }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Linter.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Linter.d.ts new file mode 100644 index 00000000..7f8b2a76 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Linter.d.ts @@ -0,0 +1,253 @@ +import type { ClassicConfig, FlatConfig, SharedConfig } from './Config'; +import type { Parser } from './Parser'; +import type { Processor as ProcessorType } from './Processor'; +import type { AnyRuleCreateFunction, AnyRuleModule, RuleCreateFunction, RuleFix, RuleModule } from './Rule'; +import type { SourceCode } from './SourceCode'; +export type MinimalRuleModule = Partial, 'create'>> & Pick, 'create'>; +declare class LinterBase { + /** + * The version from package.json. + */ + readonly version: string; + /** + * Initialize the Linter. + * @param config the config object + */ + constructor(config?: Linter.LinterOptions); + /** + * Define a new parser module + * @param parserId Name of the parser + * @param parserModule The parser object + */ + defineParser(parserId: string, parserModule: Parser.LooseParserModule): void; + /** + * Defines a new linting rule. + * @param ruleId A unique rule identifier + * @param ruleModule Function from context to object mapping AST node types to event handlers + */ + defineRule(ruleId: string, ruleModule: MinimalRuleModule | RuleCreateFunction): void; + /** + * Defines many new linting rules. + * @param rulesToDefine map from unique rule identifier to rule + */ + defineRules(rulesToDefine: Record | RuleCreateFunction>): void; + /** + * Gets an object with all loaded rules. + * @returns All loaded rules + */ + getRules(): Map>; + /** + * Gets the `SourceCode` object representing the parsed source. + * @returns The `SourceCode` object. + */ + getSourceCode(): SourceCode; + /** + * Verifies the text against the rules specified by the second argument. + * @param textOrSourceCode The text to parse or a SourceCode object. + * @param config An ESLintConfig instance to configure everything. + * @param filenameOrOptions The optional filename of the file being checked. + * If this is not set, the filename will default to '' in the rule context. + * If this is an object, then it has "filename", "allowInlineConfig", and some properties. + * @returns The results as an array of messages or an empty array if no messages. + */ + verify(textOrSourceCode: string | SourceCode, config: Linter.ConfigType, filenameOrOptions?: string | Linter.VerifyOptions): Linter.LintMessage[]; + /** + * The version from package.json. + */ + static readonly version: string; + /** + * Performs multiple autofix passes over the text until as many fixes as possible have been applied. + * @param code The source text to apply fixes to. + * @param config The ESLint config object to use. + * @param options The ESLint options object to use. + * @returns The result of the fix operation as returned from the SourceCodeFixer. + */ + verifyAndFix(code: string, config: Linter.ConfigType, options: Linter.FixOptions): Linter.FixReport; +} +declare namespace Linter { + interface LinterOptions { + /** + * Which config format to use. + * @default 'flat' + */ + configType?: ConfigTypeSpecifier; + /** + * path to a directory that should be considered as the current working directory. + */ + cwd?: string; + } + type ConfigTypeSpecifier = 'eslintrc' | 'flat'; + type EnvironmentConfig = SharedConfig.EnvironmentConfig; + type GlobalsConfig = SharedConfig.GlobalsConfig; + type GlobalVariableOption = SharedConfig.GlobalVariableOption; + type GlobalVariableOptionBase = SharedConfig.GlobalVariableOptionBase; + type ParserOptions = SharedConfig.ParserOptions; + type PluginMeta = SharedConfig.PluginMeta; + type RuleEntry = SharedConfig.RuleEntry; + type RuleLevel = SharedConfig.RuleLevel; + type RuleLevelAndOptions = SharedConfig.RuleLevelAndOptions; + type RulesRecord = SharedConfig.RulesRecord; + type Severity = SharedConfig.Severity; + type SeverityString = SharedConfig.SeverityString; + /** @deprecated use {@link Linter.ConfigType} instead */ + type Config = ClassicConfig.Config; + type ConfigType = ClassicConfig.Config | FlatConfig.Config | FlatConfig.ConfigArray; + /** @deprecated use {@link ClassicConfig.ConfigOverride} instead */ + type ConfigOverride = ClassicConfig.ConfigOverride; + interface VerifyOptions { + /** + * Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied. + * Useful if you want to validate JS without comments overriding rules. + */ + allowInlineConfig?: boolean; + /** + * if `true` then the linter doesn't make `fix` properties into the lint result. + */ + disableFixes?: boolean; + /** + * the filename of the source code. + */ + filename?: string; + /** + * the predicate function that selects adopt code blocks. + */ + filterCodeBlock?: (filename: string, text: string) => boolean; + /** + * postprocessor for report messages. + * If provided, this should accept an array of the message lists + * for each code block returned from the preprocessor, apply a mapping to + * the messages as appropriate, and return a one-dimensional array of + * messages. + */ + postprocess?: ProcessorType.PostProcess; + /** + * preprocessor for source text. + * If provided, this should accept a string of source text, and return an array of code blocks to lint. + */ + preprocess?: ProcessorType.PreProcess; + /** + * Adds reported errors for unused `eslint-disable` directives. + */ + reportUnusedDisableDirectives?: boolean | SeverityString; + } + interface FixOptions extends VerifyOptions { + /** + * Determines whether fixes should be applied. + */ + fix?: boolean; + } + interface LintSuggestion { + desc: string; + fix: RuleFix; + messageId?: string; + } + interface LintMessage { + /** + * The 1-based column number. + */ + column: number; + /** + * The 1-based column number of the end location. + */ + endColumn?: number; + /** + * The 1-based line number of the end location. + */ + endLine?: number; + /** + * If `true` then this is a fatal error. + */ + fatal?: true; + /** + * Information for autofix. + */ + fix?: RuleFix; + /** + * The 1-based line number. + */ + line: number; + /** + * The error message. + */ + message: string; + messageId?: string; + nodeType: string; + /** + * The ID of the rule which makes this message. + */ + ruleId: string | null; + /** + * The severity of this message. + */ + severity: Severity; + source: string | null; + /** + * Information for suggestions + */ + suggestions?: LintSuggestion[]; + } + interface FixReport { + /** + * True, if the code was fixed + */ + fixed: boolean; + /** + * Collection of all messages for the given code + */ + messages: LintMessage[]; + /** + * Fixed code text (might be the same as input if no fixes were applied). + */ + output: string; + } + /** @deprecated use {@link Parser.ParserModule} */ + type ParserModule = Parser.LooseParserModule; + /** @deprecated use {@link Parser.ParseResult} */ + type ESLintParseResult = Parser.ParseResult; + /** @deprecated use {@link ProcessorType.ProcessorModule} */ + type Processor = ProcessorType.ProcessorModule; + interface Environment { + /** + * The definition of global variables. + */ + globals?: GlobalsConfig; + /** + * The parser options that will be enabled under this environment. + */ + parserOptions?: ParserOptions; + } + type LegacyPluginRules = Record; + type PluginRules = Record; + interface Plugin { + /** + * The definition of plugin configs. + */ + configs?: Record; + /** + * The definition of plugin environments. + */ + environments?: Record; + /** + * Metadata about your plugin for easier debugging and more effective caching of plugins. + */ + meta?: PluginMeta; + /** + * The definition of plugin processors. + */ + processors?: Record; + /** + * The definition of plugin rules. + */ + rules?: LegacyPluginRules; + } +} +declare const Linter_base: typeof LinterBase; +/** + * The Linter object does the actual evaluation of the JavaScript code. It doesn't do any filesystem operations, it + * simply parses and reports on the code. In particular, the Linter object does not process configuration objects + * or files. + */ +declare class Linter extends Linter_base { +} +export { Linter }; +//# sourceMappingURL=Linter.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Linter.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Linter.d.ts.map new file mode 100644 index 00000000..c515393e --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Linter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Linter.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/Linter.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,KAAK,EAAE,SAAS,IAAI,aAAa,EAAE,MAAM,aAAa,CAAC;AAC9D,OAAO,KAAK,EACV,qBAAqB,EACrB,aAAa,EACb,kBAAkB,EAClB,OAAO,EACP,UAAU,EACX,MAAM,QAAQ,CAAC;AAChB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,MAAM,iBAAiB,CAC3B,UAAU,SAAS,MAAM,GAAG,MAAM,EAClC,OAAO,SAAS,SAAS,OAAO,EAAE,GAAG,EAAE,IACrC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,GAC1D,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAGlD,OAAO,OAAO,UAAU;IACtB;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAEzB;;;OAGG;gBACS,MAAM,CAAC,EAAE,MAAM,CAAC,aAAa;IAEzC;;;;OAIG;IACH,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,CAAC,iBAAiB,GAAG,IAAI;IAE5E;;;;OAIG;IACH,UAAU,CAAC,UAAU,SAAS,MAAM,EAAE,OAAO,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C;KAC/B;IAGD,KAAY,iBAAiB,GAAG,MAAM,CACpC,MAAM,EACN,qBAAqB,GAAG,aAAa,CACtC,CAAC;IACF,KAAY,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAExD,UAAiB,MAAM;QACrB;;WAEG;QACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;QAC/C;;WAEG;QACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;QAC3C;;WAEG;QACH,IAAI,CAAC,EAAE,UAAU,CAAC;QAClB;;WAEG;QACH,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,eAAe,CAAC,CAAC;QAC3D;;WAEG;QACH,KAAK,CAAC,EAAE,iBAAiB,CAAC;KAC3B;CACF;2BAOqC,OAAO,UAAU;AALvD;;;;GAIG;AACH,cAAM,MAAO,SAAQ,WAAmC;CAAG;AAE3D,OAAO,EAAE,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Linter.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Linter.js new file mode 100644 index 00000000..7fe7076e --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Linter.js @@ -0,0 +1,13 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-namespace, no-restricted-syntax */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Linter = void 0; +const eslint_1 = require("eslint"); +/** + * The Linter object does the actual evaluation of the JavaScript code. It doesn't do any filesystem operations, it + * simply parses and reports on the code. In particular, the Linter object does not process configuration objects + * or files. + */ +class Linter extends eslint_1.Linter { +} +exports.Linter = Linter; diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Parser.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Parser.d.ts new file mode 100644 index 00000000..84f52c92 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Parser.d.ts @@ -0,0 +1,95 @@ +import type { ParserServices, TSESTree } from '../ts-estree'; +import type { ParserOptions } from './ParserOptions'; +import type { Scope } from './Scope'; +export declare namespace Parser { + interface ParserMeta { + /** + * The unique name of the parser. + */ + name: string; + /** + * The a string identifying the version of the parser. + */ + version?: string; + } + /** + * A loose definition of the ParserModule type for use with configs + * This type intended to relax validation of configs so that parsers that have + * different AST types or scope managers can still be passed to configs + * + * @see {@link LooseRuleDefinition}, {@link LooseProcessorModule} + */ + type LooseParserModule = { + /** + * Information about the parser to uniquely identify it when serializing. + */ + meta?: { + [K in keyof ParserMeta]?: ParserMeta[K] | undefined; + }; + /** + * Parses the given text into an AST + */ + parseForESLint(text: string, options?: unknown): { + [k in keyof ParseResult]: unknown; + }; + } | { + /** + * Information about the parser to uniquely identify it when serializing. + */ + meta?: { + [K in keyof ParserMeta]?: ParserMeta[K] | undefined; + }; + /** + * Parses the given text into an ESTree AST + */ + parse(text: string, options?: unknown): unknown; + }; + type ParserModule = { + /** + * Information about the parser to uniquely identify it when serializing. + */ + meta?: ParserMeta; + /** + * Parses the given text into an AST + */ + parseForESLint(text: string, options?: ParserOptions): ParseResult; + } | { + /** + * Information about the parser to uniquely identify it when serializing. + */ + meta?: ParserMeta; + /** + * Parses the given text into an ESTree AST + */ + parse(text: string, options?: ParserOptions): TSESTree.Program; + }; + interface ParseResult { + /** + * The ESTree AST + */ + ast: TSESTree.Program; + /** + * A `ScopeManager` object. + * Custom parsers can use customized scope analysis for experimental/enhancement syntaxes. + * The default is the `ScopeManager` object which is created by `eslint-scope`. + */ + scopeManager?: Scope.ScopeManager; + /** + * Any parser-dependent services (such as type checkers for nodes). + * The value of the services property is available to rules as `context.sourceCode.parserServices`. + * The default is an empty object. + */ + services?: ParserServices; + /** + * An object to customize AST traversal. + * The keys of the object are the type of AST nodes. + * Each value is an array of the property names which should be traversed. + * The default is `KEYS` of `eslint-visitor-keys`. + */ + visitorKeys?: VisitorKeys; + } + interface VisitorKeys { + [nodeType: string]: readonly string[]; + } +} +//# sourceMappingURL=Parser.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Parser.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Parser.d.ts.map new file mode 100644 index 00000000..bb356585 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Parser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Parser.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/Parser.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,yBAAiB,MAAM,CAAC;IACtB,UAAiB,UAAU;QACzB;;WAEG;QACH,IAAI,EAAE,MAAM,CAAC;QACb;;WAEG;QACH,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB;IAED;;;;;;OAMG;IACH,KAAY,iBAAiB,GACzB;QACE;;WAEG;QACH,IAAI,CAAC,EAAE;aAAG,CAAC,IAAI,MAAM,UAAU,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,SAAS;SAAE,CAAC;QAC/D;;WAEG;QACH,cAAc,CACZ,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,OAAO,GAChB;aAEA,CAAC,IAAI,MAAM,WAAW,GAAG,OAAO;SAClC,CAAC;KACH,GACD;QACE;;WAEG;QACH,IAAI,CAAC,EAAE;aAAG,CAAC,IAAI,MAAM,UAAU,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,SAAS;SAAE,CAAC;QAC/D;;WAEG;QACH,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC;KACjD,CAAC;IAEN,KAAY,YAAY,GACpB;QACE;;WAEG;QACH,IAAI,CAAC,EAAE,UAAU,CAAC;QAClB;;WAEG;QACH,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,WAAW,CAAC;KACpE,GACD;QACE;;WAEG;QACH,IAAI,CAAC,EAAE,UAAU,CAAC;QAClB;;WAEG;QACH,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,QAAQ,CAAC,OAAO,CAAC;KAChE,CAAC;IAEN,UAAiB,WAAW;QAC1B;;WAEG;QACH,GAAG,EAAE,QAAQ,CAAC,OAAO,CAAC;QACtB;;;;WAIG;QACH,YAAY,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC;QAClC;;;;WAIG;QACH,QAAQ,CAAC,EAAE,cAAc,CAAC;QAC1B;;;;;WAKG;QACH,WAAW,CAAC,EAAE,WAAW,CAAC;KAC3B;IAGD,UAAiB,WAAW;QAC1B,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;KACvC;CACF"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Parser.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Parser.js new file mode 100644 index 00000000..0d0ae6b0 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Parser.js @@ -0,0 +1,3 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-namespace */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/ParserOptions.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ParserOptions.d.ts new file mode 100644 index 00000000..62d627d3 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ParserOptions.d.ts @@ -0,0 +1,2 @@ +export type { DebugLevel, EcmaVersion, ParserOptions, SourceType, } from '@typescript-eslint/types'; +//# sourceMappingURL=ParserOptions.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/ParserOptions.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ParserOptions.d.ts.map new file mode 100644 index 00000000..9c8b324a --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ParserOptions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ParserOptions.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/ParserOptions.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,UAAU,EACV,WAAW,EACX,aAAa,EACb,UAAU,GACX,MAAM,0BAA0B,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/ParserOptions.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ParserOptions.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/ParserOptions.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Processor.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Processor.d.ts new file mode 100644 index 00000000..0f212816 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Processor.d.ts @@ -0,0 +1,64 @@ +import type { Linter } from './Linter'; +export declare namespace Processor { + interface ProcessorMeta { + /** + * The unique name of the processor. + */ + name: string; + /** + * The a string identifying the version of the processor. + */ + version?: string; + } + type PreProcess = (text: string, filename: string) => (string | { + filename: string; + text: string; + })[]; + type PostProcess = (messagesList: Linter.LintMessage[][], filename: string) => Linter.LintMessage[]; + interface ProcessorModule { + /** + * Information about the processor to uniquely identify it when serializing. + */ + meta?: ProcessorMeta; + /** + * The function to merge messages. + */ + postprocess?: PostProcess; + /** + * The function to extract code blocks. + */ + preprocess?: PreProcess; + /** + * If `true` then it means the processor supports autofix. + */ + supportsAutofix?: boolean; + } + /** + * A loose definition of the ParserModule type for use with configs + * This type intended to relax validation of configs so that parsers that have + * different AST types or scope managers can still be passed to configs + * + * @see {@link LooseRuleDefinition}, {@link LooseParserModule} + */ + interface LooseProcessorModule { + /** + * Information about the processor to uniquely identify it when serializing. + */ + meta?: { + [K in keyof ProcessorMeta]?: ProcessorMeta[K] | undefined; + }; + /** + * The function to merge messages. + */ + postprocess?: (messagesList: any, filename: string) => any; + /** + * The function to extract code blocks. + */ + preprocess?: (text: string, filename: string) => any; + /** + * If `true` then it means the processor supports autofix. + */ + supportsAutofix?: boolean | undefined; + } +} +//# sourceMappingURL=Processor.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Processor.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Processor.d.ts.map new file mode 100644 index 00000000..3e4ccd17 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Processor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Processor.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/Processor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAEvC,yBAAiB,SAAS,CAAC;IACzB,UAAiB,aAAa;QAC5B;;WAEG;QACH,IAAI,EAAE,MAAM,CAAC;QACb;;WAEG;QACH,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB;IAED,KAAY,UAAU,GAAG,CACvB,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,KACb,CAAC,MAAM,GAAG;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,EAAE,CAAC;IAErD,KAAY,WAAW,GAAG,CACxB,YAAY,EAAE,MAAM,CAAC,WAAW,EAAE,EAAE,EACpC,QAAQ,EAAE,MAAM,KACb,MAAM,CAAC,WAAW,EAAE,CAAC;IAE1B,UAAiB,eAAe;QAC9B;;WAEG;QACH,IAAI,CAAC,EAAE,aAAa,CAAC;QAErB;;WAEG;QACH,WAAW,CAAC,EAAE,WAAW,CAAC;QAE1B;;WAEG;QACH,UAAU,CAAC,EAAE,UAAU,CAAC;QAExB;;WAEG;QACH,eAAe,CAAC,EAAE,OAAO,CAAC;KAC3B;IAED;;;;;;OAMG;IACH,UAAiB,oBAAoB;QACnC;;WAEG;QACH,IAAI,CAAC,EAAE;aAAG,CAAC,IAAI,MAAM,aAAa,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,SAAS;SAAE,CAAC;QAErE;;WAEG;QAMH,WAAW,CAAC,EAAE,CAAC,YAAY,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,KAAK,GAAG,CAAC;QAE3D;;WAEG;QAMH,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,GAAG,CAAC;QAErD;;WAEG;QACH,eAAe,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;KACvC;CACF"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Processor.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Processor.js new file mode 100644 index 00000000..0d0ae6b0 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Processor.js @@ -0,0 +1,3 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-namespace */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Rule.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Rule.d.ts new file mode 100644 index 00000000..df752102 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Rule.d.ts @@ -0,0 +1,602 @@ +import type { JSONSchema4 } from '../json-schema'; +import type { ParserServices, TSESTree } from '../ts-estree'; +import type { AST } from './AST'; +import type { FlatConfig } from './Config'; +import type { Linter } from './Linter'; +import type { Scope } from './Scope'; +import type { SourceCode } from './SourceCode'; +export type RuleRecommendation = 'recommended' | 'strict' | 'stylistic'; +export interface RuleRecommendationAcrossConfigs { + recommended?: true; + strict: Partial; +} +export interface RuleMetaDataDocs { + /** + * Concise description of the rule. + */ + description: string; + /** + * The URL of the rule's docs. + */ + url?: string; +} +export interface ExternalSpecifier { + /** + * Name of the referenced plugin / rule. + */ + name?: string; + /** + * URL pointing to documentation for the plugin / rule. + */ + url?: string; +} +export interface ReplacedByInfo { + /** + * General message presented to the user, e.g. how to replace the rule + */ + message?: string; + /** + * URL to more information about this replacement in general + */ + url?: string; + /** + * Name should be "eslint" if the replacement is an ESLint core rule. Omit + * the property if the replacement is in the same plugin. + */ + plugin?: ExternalSpecifier; + /** + * Name and documentation of the replacement rule + */ + rule?: ExternalSpecifier; +} +export interface DeprecatedInfo { + /** + * General message presented to the user, e.g. for the key rule why the rule + * is deprecated or for info how to replace the rule. + */ + message?: string; + /** + * URL to more information about this deprecation in general. + */ + url?: string; + /** + * An empty array explicitly states that there is no replacement. + */ + replacedBy?: ReplacedByInfo[]; + /** + * The package version since when the rule is deprecated (should use full + * semver without a leading "v"). + */ + deprecatedSince?: string; + /** + * The estimated version when the rule is removed (probably the next major + * version). null means the rule is "frozen" (will be available but will not + * be changed). + */ + availableUntil?: string | null; +} +export interface RuleMetaData { + /** + * True if the rule is deprecated, false otherwise + */ + deprecated?: boolean | DeprecatedInfo; + /** + * Documentation for the rule + */ + docs?: PluginDocs & RuleMetaDataDocs; + /** + * The fixer category. Omit if there is no fixer + */ + fixable?: 'code' | 'whitespace'; + /** + * Specifies whether rules can return suggestions. Omit if there is no suggestions + */ + hasSuggestions?: boolean; + /** + * A map of messages which the rule can report. + * The key is the messageId, and the string is the parameterised error string. + * See: https://eslint.org/docs/developer-guide/working-with-rules#messageids + */ + messages: Record; + /** + * The name of the rule this rule was replaced by, if it was deprecated. + * + * @deprecated since eslint 9.21.0, in favor of `RuleMetaData#deprecated.replacedBy` + */ + replacedBy?: readonly string[]; + /** + * The options schema. Supply an empty array if there are no options. + */ + schema: JSONSchema4 | readonly JSONSchema4[]; + /** + * The type of rule. + * - `"problem"` means the rule is identifying code that either will cause an error or may cause a confusing behavior. Developers should consider this a high priority to resolve. + * - `"suggestion"` means the rule is identifying something that could be done in a better way but no errors will occur if the code isn’t changed. + * - `"layout"` means the rule cares primarily about whitespace, semicolons, commas, and parentheses, all the parts of the program that determine how the code looks rather than how it executes. These rules work on parts of the code that aren’t specified in the AST. + */ + type: 'layout' | 'problem' | 'suggestion'; + /** + * Specifies default options for the rule. If present, any user-provided options in their config will be merged on top of them recursively. + * This merging will be applied directly to `context.options`. + * If you want backwards-compatible support for earlier ESLint version; consider using the top-level `defaultOptions` instead. + * + * since ESLint 9.15.0 + */ + defaultOptions?: Options; +} +export interface RuleMetaDataWithDocs extends RuleMetaData { + /** + * Documentation for the rule + */ + docs: PluginDocs & RuleMetaDataDocs; +} +export interface RuleFix { + range: Readonly; + text: string; +} +export interface RuleFixer { + insertTextAfter(nodeOrToken: TSESTree.Node | TSESTree.Token, text: string): RuleFix; + insertTextAfterRange(range: Readonly, text: string): RuleFix; + insertTextBefore(nodeOrToken: TSESTree.Node | TSESTree.Token, text: string): RuleFix; + insertTextBeforeRange(range: Readonly, text: string): RuleFix; + remove(nodeOrToken: TSESTree.Node | TSESTree.Token): RuleFix; + removeRange(range: Readonly): RuleFix; + replaceText(nodeOrToken: TSESTree.Node | TSESTree.Token, text: string): RuleFix; + replaceTextRange(range: Readonly, text: string): RuleFix; +} +export interface SuggestionReportDescriptor extends Omit, 'fix'> { + readonly fix: ReportFixFunction; +} +export type ReportFixFunction = (fixer: RuleFixer) => IterableIterator | readonly RuleFix[] | RuleFix | null; +export type ReportSuggestionArray = SuggestionReportDescriptor[]; +export type ReportDescriptorMessageData = Readonly>; +interface ReportDescriptorBase { + /** + * The parameters for the message string associated with `messageId`. + */ + readonly data?: ReportDescriptorMessageData; + /** + * The fixer function. + */ + readonly fix?: ReportFixFunction | null; + /** + * The messageId which is being reported. + */ + readonly messageId: MessageIds; +} +interface ReportDescriptorWithSuggestion extends ReportDescriptorBase { + /** + * 6.7's Suggestions API + */ + readonly suggest?: Readonly> | null; +} +interface ReportDescriptorNodeOptionalLoc { + /** + * An override of the location of the report + */ + readonly loc?: Readonly | Readonly; + /** + * The Node or AST Token which the report is being attached to + */ + readonly node: TSESTree.Node | TSESTree.Token; +} +interface ReportDescriptorLocOnly { + /** + * An override of the location of the report + */ + loc: Readonly | Readonly; +} +export type ReportDescriptor = (ReportDescriptorLocOnly | ReportDescriptorNodeOptionalLoc) & ReportDescriptorWithSuggestion; +/** + * Plugins can add their settings using declaration + * merging against this interface. + */ +export interface SharedConfigurationSettings { + [name: string]: unknown; +} +export interface RuleContext { + /** + * The rule ID. + */ + id: string; + /** + * The language options configured for this run + */ + languageOptions: FlatConfig.LanguageOptions; + /** + * An array of the configured options for this rule. + * This array does not include the rule severity. + */ + options: Options; + /** + * The parser options configured for this run + */ + parserOptions: Linter.ParserOptions; + /** + * The name of the parser from configuration, if in eslintrc (legacy) config. + */ + parserPath: string | undefined; + /** + * An object containing parser-provided services for rules + * + * @deprecated in favor of `SourceCode#parserServices` + */ + parserServices?: ParserServices; + /** + * The shared settings from configuration. + * We do not have any shared settings in this plugin. + */ + settings: SharedConfigurationSettings; + /** + * Returns an array of the ancestors of the currently-traversed node, starting at + * the root of the AST and continuing through the direct parent of the current node. + * This array does not include the currently-traversed node itself. + * + * @deprecated in favor of `SourceCode#getAncestors` + */ + getAncestors(): TSESTree.Node[]; + /** + * Returns a list of variables declared by the given node. + * This information can be used to track references to variables. + * + * @deprecated in favor of `SourceCode#getDeclaredVariables` + */ + getDeclaredVariables(node: TSESTree.Node): readonly Scope.Variable[]; + /** + * Returns the current working directory passed to Linter. + * It is a path to a directory that should be considered as the current working directory. + * @deprecated in favor of `RuleContext#cwd` + */ + getCwd(): string; + /** + * The current working directory passed to Linter. + * It is a path to a directory that should be considered as the current working directory. + */ + cwd: string; + /** + * Returns the filename associated with the source. + * + * @deprecated in favor of `RuleContext#filename` + */ + getFilename(): string; + /** + * The filename associated with the source. + */ + filename: string; + /** + * Returns the full path of the file on disk without any code block information (unlike `getFilename()`). + * @deprecated in favor of `RuleContext#physicalFilename` + */ + getPhysicalFilename(): string; + /** + * The full path of the file on disk without any code block information (unlike `filename`). + */ + physicalFilename: string; + /** + * Returns the scope of the currently-traversed node. + * This information can be used track references to variables. + * + * @deprecated in favor of `SourceCode#getScope` + */ + getScope(): Scope.Scope; + /** + * Returns a SourceCode object that you can use to work with the source that + * was passed to ESLint. + * + * @deprecated in favor of `RuleContext#sourceCode` + */ + getSourceCode(): Readonly; + /** + * A SourceCode object that you can use to work with the source that + * was passed to ESLint. + */ + sourceCode: Readonly; + /** + * Marks a variable with the given name in the current scope as used. + * This affects the no-unused-vars rule. + * + * @deprecated in favor of `SourceCode#markVariableAsUsed` + */ + markVariableAsUsed(name: string): boolean; + /** + * Reports a problem in the code. + */ + report(descriptor: ReportDescriptor): void; +} +/** + * Part of the code path analysis feature of ESLint: + * https://eslint.org/docs/latest/extend/code-path-analysis + * + * These are used in the `onCodePath*` methods. (Note that the `node` parameter + * of these methods is intentionally omitted.) + * + * @see https://github.com/typescript-eslint/typescript-eslint/issues/6993 + */ +export interface CodePath { + /** Code paths of functions this code path contains. */ + childCodePaths: CodePath[]; + /** + * Segments of the current traversal position. + * + * @deprecated + */ + currentSegments: CodePathSegment[]; + /** The final segments which includes both returned and thrown. */ + finalSegments: CodePathSegment[]; + /** + * A unique string. Respective rules can use `id` to save additional + * information for each code path. + */ + id: string; + initialSegment: CodePathSegment; + /** The final segments which includes only returned. */ + returnedSegments: CodePathSegment[]; + /** The final segments which includes only thrown. */ + thrownSegments: CodePathSegment[]; + /** The code path of the upper function/global scope. */ + upper: CodePath | null; +} +/** + * Part of the code path analysis feature of ESLint: + * https://eslint.org/docs/latest/extend/code-path-analysis + * + * These are used in the `onCodePath*` methods. (Note that the `node` parameter + * of these methods is intentionally omitted.) + * + * @see https://github.com/typescript-eslint/typescript-eslint/issues/6993 + */ +export interface CodePathSegment { + /** + * A unique string. Respective rules can use `id` to save additional + * information for each segment. + */ + id: string; + /** + * The next segments. If forking, there are two or more. If final, there is + * nothing. + */ + nextSegments: CodePathSegment[]; + /** + * The previous segments. If merging, there are two or more. If initial, there + * is nothing. + */ + prevSegments: CodePathSegment[]; + /** + * A flag which shows whether it is reachable. This becomes `false` when + * preceded by `return`, `throw`, `break`, or `continue`. + */ + reachable: boolean; +} +/** + * Part of the code path analysis feature of ESLint: + * https://eslint.org/docs/latest/extend/code-path-analysis + * + * This type is unused in the `typescript-eslint` codebase since putting it on + * the `nodeSelector` for `RuleListener` would break the existing definition. + * However, it is exported here for the purposes of manual type-assertion. + * + * @see https://github.com/typescript-eslint/typescript-eslint/issues/6993 + */ +export type CodePathFunction = ((codePath: CodePath, node: TSESTree.Node) => void) | ((fromSegment: CodePathSegment, toSegment: CodePathSegment, node: TSESTree.Node) => void) | ((segment: CodePathSegment, node: TSESTree.Node) => void); +export type RuleFunction = (node: T) => void; +interface RuleListenerBaseSelectors { + AccessorProperty?: RuleFunction; + ArrayExpression?: RuleFunction; + ArrayPattern?: RuleFunction; + ArrowFunctionExpression?: RuleFunction; + AssignmentExpression?: RuleFunction; + AssignmentPattern?: RuleFunction; + AwaitExpression?: RuleFunction; + BinaryExpression?: RuleFunction; + BlockStatement?: RuleFunction; + BreakStatement?: RuleFunction; + CallExpression?: RuleFunction; + CatchClause?: RuleFunction; + ChainExpression?: RuleFunction; + ClassBody?: RuleFunction; + ClassDeclaration?: RuleFunction; + ClassExpression?: RuleFunction; + ConditionalExpression?: RuleFunction; + ContinueStatement?: RuleFunction; + DebuggerStatement?: RuleFunction; + Decorator?: RuleFunction; + DoWhileStatement?: RuleFunction; + EmptyStatement?: RuleFunction; + ExportAllDeclaration?: RuleFunction; + ExportDefaultDeclaration?: RuleFunction; + ExportNamedDeclaration?: RuleFunction; + ExportSpecifier?: RuleFunction; + ExpressionStatement?: RuleFunction; + ForInStatement?: RuleFunction; + ForOfStatement?: RuleFunction; + ForStatement?: RuleFunction; + FunctionDeclaration?: RuleFunction; + FunctionExpression?: RuleFunction; + Identifier?: RuleFunction; + IfStatement?: RuleFunction; + ImportAttribute?: RuleFunction; + ImportDeclaration?: RuleFunction; + ImportDefaultSpecifier?: RuleFunction; + ImportExpression?: RuleFunction; + ImportNamespaceSpecifier?: RuleFunction; + ImportSpecifier?: RuleFunction; + JSXAttribute?: RuleFunction; + JSXClosingElement?: RuleFunction; + JSXClosingFragment?: RuleFunction; + JSXElement?: RuleFunction; + JSXEmptyExpression?: RuleFunction; + JSXExpressionContainer?: RuleFunction; + JSXFragment?: RuleFunction; + JSXIdentifier?: RuleFunction; + JSXMemberExpression?: RuleFunction; + JSXNamespacedName?: RuleFunction; + JSXOpeningElement?: RuleFunction; + JSXOpeningFragment?: RuleFunction; + JSXSpreadAttribute?: RuleFunction; + JSXSpreadChild?: RuleFunction; + JSXText?: RuleFunction; + LabeledStatement?: RuleFunction; + Literal?: RuleFunction; + LogicalExpression?: RuleFunction; + MemberExpression?: RuleFunction; + MetaProperty?: RuleFunction; + MethodDefinition?: RuleFunction; + NewExpression?: RuleFunction; + ObjectExpression?: RuleFunction; + ObjectPattern?: RuleFunction; + PrivateIdentifier?: RuleFunction; + Program?: RuleFunction; + Property?: RuleFunction; + PropertyDefinition?: RuleFunction; + RestElement?: RuleFunction; + ReturnStatement?: RuleFunction; + SequenceExpression?: RuleFunction; + SpreadElement?: RuleFunction; + StaticBlock?: RuleFunction; + Super?: RuleFunction; + SwitchCase?: RuleFunction; + SwitchStatement?: RuleFunction; + TaggedTemplateExpression?: RuleFunction; + TemplateElement?: RuleFunction; + TemplateLiteral?: RuleFunction; + ThisExpression?: RuleFunction; + ThrowStatement?: RuleFunction; + TryStatement?: RuleFunction; + TSAbstractAccessorProperty?: RuleFunction; + TSAbstractKeyword?: RuleFunction; + TSAbstractMethodDefinition?: RuleFunction; + TSAbstractPropertyDefinition?: RuleFunction; + TSAnyKeyword?: RuleFunction; + TSArrayType?: RuleFunction; + TSAsExpression?: RuleFunction; + TSAsyncKeyword?: RuleFunction; + TSBigIntKeyword?: RuleFunction; + TSBooleanKeyword?: RuleFunction; + TSCallSignatureDeclaration?: RuleFunction; + TSClassImplements?: RuleFunction; + TSConditionalType?: RuleFunction; + TSConstructorType?: RuleFunction; + TSConstructSignatureDeclaration?: RuleFunction; + TSDeclareFunction?: RuleFunction; + TSDeclareKeyword?: RuleFunction; + TSEmptyBodyFunctionExpression?: RuleFunction; + TSEnumBody?: RuleFunction; + TSEnumDeclaration?: RuleFunction; + TSEnumMember?: RuleFunction; + TSExportAssignment?: RuleFunction; + TSExportKeyword?: RuleFunction; + TSExternalModuleReference?: RuleFunction; + TSFunctionType?: RuleFunction; + TSImportEqualsDeclaration?: RuleFunction; + TSImportType?: RuleFunction; + TSIndexedAccessType?: RuleFunction; + TSIndexSignature?: RuleFunction; + TSInferType?: RuleFunction; + TSInstantiationExpression?: RuleFunction; + TSInterfaceBody?: RuleFunction; + TSInterfaceDeclaration?: RuleFunction; + TSInterfaceHeritage?: RuleFunction; + TSIntersectionType?: RuleFunction; + TSIntrinsicKeyword?: RuleFunction; + TSLiteralType?: RuleFunction; + TSMappedType?: RuleFunction; + TSMethodSignature?: RuleFunction; + TSModuleBlock?: RuleFunction; + TSModuleDeclaration?: RuleFunction; + TSNamedTupleMember?: RuleFunction; + TSNamespaceExportDeclaration?: RuleFunction; + TSNeverKeyword?: RuleFunction; + TSNonNullExpression?: RuleFunction; + TSNullKeyword?: RuleFunction; + TSNumberKeyword?: RuleFunction; + TSObjectKeyword?: RuleFunction; + TSOptionalType?: RuleFunction; + TSParameterProperty?: RuleFunction; + TSPrivateKeyword?: RuleFunction; + TSPropertySignature?: RuleFunction; + TSProtectedKeyword?: RuleFunction; + TSPublicKeyword?: RuleFunction; + TSQualifiedName?: RuleFunction; + TSReadonlyKeyword?: RuleFunction; + TSRestType?: RuleFunction; + TSSatisfiesExpression?: RuleFunction; + TSStaticKeyword?: RuleFunction; + TSStringKeyword?: RuleFunction; + TSSymbolKeyword?: RuleFunction; + TSTemplateLiteralType?: RuleFunction; + TSThisType?: RuleFunction; + TSTupleType?: RuleFunction; + TSTypeAliasDeclaration?: RuleFunction; + TSTypeAnnotation?: RuleFunction; + TSTypeAssertion?: RuleFunction; + TSTypeLiteral?: RuleFunction; + TSTypeOperator?: RuleFunction; + TSTypeParameter?: RuleFunction; + TSTypeParameterDeclaration?: RuleFunction; + TSTypeParameterInstantiation?: RuleFunction; + TSTypePredicate?: RuleFunction; + TSTypeQuery?: RuleFunction; + TSTypeReference?: RuleFunction; + TSUndefinedKeyword?: RuleFunction; + TSUnionType?: RuleFunction; + TSUnknownKeyword?: RuleFunction; + TSVoidKeyword?: RuleFunction; + UnaryExpression?: RuleFunction; + UpdateExpression?: RuleFunction; + VariableDeclaration?: RuleFunction; + VariableDeclarator?: RuleFunction; + WhileStatement?: RuleFunction; + WithStatement?: RuleFunction; + YieldExpression?: RuleFunction; +} +type RuleListenerExitSelectors = { + [K in keyof RuleListenerBaseSelectors as `${K}:exit`]: RuleListenerBaseSelectors[K]; +}; +type RuleListenerCatchAllBaseCase = Record; +export interface RuleListenerExtension { +} +export type RuleListener = RuleListenerBaseSelectors & RuleListenerCatchAllBaseCase & RuleListenerExitSelectors; +export interface RuleModule { + /** + * Function which returns an object with methods that ESLint calls to “visit” + * nodes while traversing the abstract syntax tree. + */ + create(context: Readonly>): ExtendedRuleListener; + /** + * Default options the rule will be run with + */ + defaultOptions: Options; + /** + * Metadata about the rule + */ + meta: RuleMetaData; +} +export type AnyRuleModule = RuleModule; +export interface RuleModuleWithMetaDocs extends RuleModule { + /** + * Metadata about the rule + */ + meta: RuleMetaDataWithDocs; +} +export type AnyRuleModuleWithMetaDocs = RuleModuleWithMetaDocs; +/** + * A loose definition of the RuleModule type for use with configs. This type is + * intended to relax validation of types so that we can have basic validation + * without being overly strict about nitty gritty details matching. + * + * For example the plugin might be declared using an old version of our types or + * they might use the DefinitelyTyped eslint types. Ultimately we don't need + * super strict validation in a config - a loose shape match is "good enough" to + * help validate the config is correct. + * + * @see {@link LooseParserModule}, {@link LooseProcessorModule} + */ +export type LooseRuleDefinition = LooseRuleCreateFunction | { + create: LooseRuleCreateFunction; + meta?: object | undefined; +}; +export type LooseRuleCreateFunction = (context: any) => Record; +export type RuleCreateFunction = (context: Readonly>) => RuleListener; +export type AnyRuleCreateFunction = RuleCreateFunction; +export {}; +//# sourceMappingURL=Rule.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Rule.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Rule.d.ts.map new file mode 100644 index 00000000..7e5593ba --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Rule.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Rule.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/Rule.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AACjC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,MAAM,kBAAkB,GAAG,aAAa,GAAG,QAAQ,GAAG,WAAW,CAAC;AAExE,MAAM,WAAW,+BAA+B,CAC9C,OAAO,SAAS,SAAS,OAAO,EAAE;IAElC,WAAW,CAAC,EAAE,IAAI,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,C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G,sBAAsB,CAC5D,MAAM,EACN,OAAO,EAAE,CACV,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,mBAAmB,GAE3B,uBAAuB,GACvB;IACE,MAAM,EAAE,uBAAuB,CAAC;IAChC,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC3B,CAAC;AAMN,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,EAAE,GAAG,KAAK,MAAM,CAC5D,MAAM,EAON,QAAQ,GAAG,SAAS,CACrB,CAAC;AAEF,MAAM,MAAM,kBAAkB,CAC5B,UAAU,SAAS,MAAM,GAAG,KAAK,EACjC,OAAO,SAAS,SAAS,OAAO,EAAE,GAAG,OAAO,EAAE,IAC5C,CAAC,OAAO,EAAE,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,KAAK,YAAY,CAAC;AAC1E,MAAM,MAAM,qBAAqB,GAAG,kBAAkB,CACpD,MAAM,EACN,SAAS,OAAO,EAAE,CACnB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Rule.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Rule.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Rule.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/RuleTester.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/RuleTester.d.ts new file mode 100644 index 00000000..b7cb4ece --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/RuleTester.d.ts @@ -0,0 +1,184 @@ +import type { AST_NODE_TYPES, AST_TOKEN_TYPES } from '../ts-estree'; +import type { ClassicConfig } from './Config'; +import type { Linter } from './Linter'; +import type { ParserOptions } from './ParserOptions'; +import type { ReportDescriptorMessageData, RuleCreateFunction, RuleModule, SharedConfigurationSettings } from './Rule'; +/** + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +export interface ValidTestCase { + /** + * Code for the test case. + */ + readonly code: string; + /** + * Environments for the test case. + */ + readonly env?: Readonly; + /** + * The fake filename for the test case. Useful for rules that make assertion about filenames. + */ + readonly filename?: string; + /** + * The additional global variables. + */ + readonly globals?: Readonly; + /** + * Name for the test case. + */ + readonly name?: string; + /** + * Run this case exclusively for debugging in supported test frameworks. + */ + readonly only?: boolean; + /** + * Options for the test case. + */ + readonly options?: Readonly; + /** + * The absolute path for the parser. + */ + readonly parser?: string; + /** + * Options for the parser. + */ + readonly parserOptions?: Readonly; + /** + * Settings for the test case. + */ + readonly settings?: Readonly; +} +/** + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +export interface SuggestionOutput { + /** + * The data used to fill the message template. + */ + readonly data?: ReportDescriptorMessageData; + /** + * Reported message ID. + */ + readonly messageId: MessageIds; + /** + * NOTE: Suggestions will be applied as a stand-alone change, without triggering multi-pass fixes. + * Each individual error has its own suggestion, so you have to show the correct, _isolated_ output for each suggestion. + */ + readonly output: string; +} +/** + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +export interface InvalidTestCase extends ValidTestCase { + /** + * Expected errors. + */ + readonly errors: readonly TestCaseError[]; + /** + * The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested. + */ + readonly output?: string | string[] | null; +} +/** + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +export interface TestCaseError { + /** + * The 1-based column number of the reported start location. + */ + readonly column?: number; + /** + * The data used to fill the message template. + */ + readonly data?: ReportDescriptorMessageData; + /** + * The 1-based column number of the reported end location. + */ + readonly endColumn?: number; + /** + * The 1-based line number of the reported end location. + */ + readonly endLine?: number; + /** + * The 1-based line number of the reported start location. + */ + readonly line?: number; + /** + * Reported message ID. + */ + readonly messageId: MessageIds; + /** + * Reported suggestions. + */ + readonly suggestions?: readonly SuggestionOutput[] | null; + /** + * The type of the reported AST node. + */ + readonly type?: AST_NODE_TYPES | AST_TOKEN_TYPES; +} +/** + * @param text a string describing the rule + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +export type RuleTesterTestFrameworkFunction = (text: string, callback: () => void) => void; +/** + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +export interface RunTests { + readonly invalid: readonly InvalidTestCase[]; + readonly valid: readonly (string | ValidTestCase)[]; +} +/** + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +export interface RuleTesterConfig extends ClassicConfig.Config { + readonly parser: string; + readonly parserOptions?: Readonly; +} +/** + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +declare class RuleTesterBase { + /** + * Creates a new instance of RuleTester. + * @param testerConfig extra configuration for the tester + */ + constructor(testerConfig?: RuleTesterConfig); + /** + * Adds a new rule test to execute. + * @param ruleName The name of the rule to run. + * @param rule The rule to test. + * @param tests The collection of tests to run. + */ + run(ruleName: string, rule: RuleModule, tests: RunTests): void; + /** + * If you supply a value to this property, the rule tester will call this instead of using the version defined on + * the global namespace. + */ + static get describe(): RuleTesterTestFrameworkFunction; + static set describe(value: RuleTesterTestFrameworkFunction | undefined); + /** + * If you supply a value to this property, the rule tester will call this instead of using the version defined on + * the global namespace. + */ + static get it(): RuleTesterTestFrameworkFunction; + static set it(value: RuleTesterTestFrameworkFunction | undefined); + /** + * If you supply a value to this property, the rule tester will call this instead of using the version defined on + * the global namespace. + */ + static get itOnly(): RuleTesterTestFrameworkFunction; + static set itOnly(value: RuleTesterTestFrameworkFunction | undefined); + /** + * Define a rule for one particular run of tests. + */ + defineRule(name: string, rule: RuleCreateFunction | RuleModule): void; +} +declare const RuleTester_base: typeof RuleTesterBase; +/** + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +export declare class RuleTester extends RuleTester_base { +} +export {}; +//# sourceMappingURL=RuleTester.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/RuleTester.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/RuleTester.d.ts.map new file mode 100644 index 00000000..39d7239d --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/RuleTester.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RuleTester.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/RuleTester.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAC9C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EACV,2BAA2B,EAC3B,kBAAkB,EAClB,UAAU,EACV,2BAA2B,EAC5B,MAAM,QAAQ,CAAC;AAEhB;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,OAAO,SAAS,SAAS,OAAO,EAAE;IAC/D;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;IAClD;;OAEG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B;;OAEG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAClD;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;IACrC;;OAEG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;OAEG;IACH,QAAQ,CAAC,aAAa,CAAC,EAA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,EAAE;IAElE;;;OAGG;IACH,MAAM,KAAK,MAAM,IAAI,+BAA+B,CAAC;IACrD,MAAM,KAAK,MAAM,CAAC,KAAK,EAAE,+BAA+B,GAAG,SAAS,EAAE;IAEtE;;OAEG;IACH,UAAU,CAAC,UAAU,SAAS,MAAM,EAAE,OAAO,SAAS,SAAS,OAAO,EAAE,EACtE,IAAI,EAAE,MAAM,EACZ,IAAI,EACA,kBAAkB,CAAC,UAAU,EAAE,OAAO,CAAC,GACvC,UAAU,CAAC,UAAU,EAAE,OAAO,CAAC,GAClC,IAAI;CACR;+BAKoD,OAAO,cAAc;AAH1E;;GAEG;AACH,qBAAa,UAAW,SAAQ,eAA2C;CAAG"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/RuleTester.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/RuleTester.js new file mode 100644 index 00000000..4ae6f2fc --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/RuleTester.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RuleTester = void 0; +/* eslint-disable @typescript-eslint/no-deprecated */ +const eslint_1 = require("eslint"); +/** + * @deprecated Use `@typescript-eslint/rule-tester` instead. + */ +class RuleTester extends eslint_1.RuleTester { +} +exports.RuleTester = RuleTester; diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Scope.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Scope.d.ts new file mode 100644 index 00000000..35be2a9a --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Scope.d.ts @@ -0,0 +1,43 @@ +import * as scopeManager from '@typescript-eslint/scope-manager'; +export declare namespace Scope { + type ScopeManager = scopeManager.ScopeManager; + type Reference = scopeManager.Reference; + type Variable = scopeManager.ScopeVariable; + type Scope = scopeManager.Scope; + const ScopeType: typeof scopeManager.ScopeType; + type DefinitionType = scopeManager.Definition; + type Definition = scopeManager.Definition; + const DefinitionType: typeof scopeManager.DefinitionType; + namespace Definitions { + type CatchClauseDefinition = scopeManager.CatchClauseDefinition; + type ClassNameDefinition = scopeManager.ClassNameDefinition; + type FunctionNameDefinition = scopeManager.FunctionNameDefinition; + type ImplicitGlobalVariableDefinition = scopeManager.ImplicitGlobalVariableDefinition; + type ImportBindingDefinition = scopeManager.ImportBindingDefinition; + type ParameterDefinition = scopeManager.ParameterDefinition; + type TSEnumMemberDefinition = scopeManager.TSEnumMemberDefinition; + type TSEnumNameDefinition = scopeManager.TSEnumNameDefinition; + type TSModuleNameDefinition = scopeManager.TSModuleNameDefinition; + type TypeDefinition = scopeManager.TypeDefinition; + type VariableDefinition = scopeManager.VariableDefinition; + } + namespace Scopes { + type BlockScope = scopeManager.BlockScope; + type CatchScope = scopeManager.CatchScope; + type ClassScope = scopeManager.ClassScope; + type ConditionalTypeScope = scopeManager.ConditionalTypeScope; + type ForScope = scopeManager.ForScope; + type FunctionExpressionNameScope = scopeManager.FunctionExpressionNameScope; + type FunctionScope = scopeManager.FunctionScope; + type FunctionTypeScope = scopeManager.FunctionTypeScope; + type GlobalScope = scopeManager.GlobalScope; + type MappedTypeScope = scopeManager.MappedTypeScope; + type ModuleScope = scopeManager.ModuleScope; + type SwitchScope = scopeManager.SwitchScope; + type TSEnumScope = scopeManager.TSEnumScope; + type TSModuleScope = scopeManager.TSModuleScope; + type TypeScope = scopeManager.TypeScope; + type WithScope = scopeManager.WithScope; + } +} +//# sourceMappingURL=Scope.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Scope.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Scope.d.ts.map new file mode 100644 index 00000000..1bc3d623 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Scope.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Scope.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/Scope.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,YA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BAAoB,CAAC;QACrE,KAAY,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC;QAC7C,KAAY,2BAA2B,GACrC,YAAY,CAAC,2BAA2B,CAAC;QAC3C,KAAY,aAAa,GAAG,YAAY,CAAC,aAAa,CAAC;QACvD,KAAY,iBAAiB,GAAG,YAAY,CAAC,iBAAiB,CAAC;QAC/D,KAAY,WAAW,GAAG,YAAY,CAAC,WAAW,CAAC;QACnD,KAAY,eAAe,GAAG,YAAY,CAAC,eAAe,CAAC;QAC3D,KAAY,WAAW,GAAG,YAAY,CAAC,WAAW,CAAC;QACnD,KAAY,WAAW,GAAG,YAAY,CAAC,WAAW,CAAC;QACnD,KAAY,WAAW,GAAG,YAAY,CAAC,WAAW,CAAC;QACnD,KAAY,aAAa,GAAG,YAAY,CAAC,aAAa,CAAC;QACvD,KAAY,SAAS,GAAG,YAAY,CAAC,SAAS,CAAC;QAC/C,KAAY,SAAS,GAAG,YAAY,CAAC,SAAS,CAAC;KAChD;CACF"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/Scope.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Scope.js new file mode 100644 index 00000000..f87449c5 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/Scope.js @@ -0,0 +1,43 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-namespace */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Scope = void 0; +const scopeManager = __importStar(require("@typescript-eslint/scope-manager")); +var Scope; +(function (Scope) { + Scope.ScopeType = scopeManager.ScopeType; + Scope.DefinitionType = scopeManager.DefinitionType; +})(Scope || (exports.Scope = Scope = {})); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/SourceCode.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/SourceCode.d.ts new file mode 100644 index 00000000..fc2bc221 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/SourceCode.d.ts @@ -0,0 +1,355 @@ +import type { ParserServices, TSESTree } from '../ts-estree'; +import type { Parser } from './Parser'; +import type { Scope } from './Scope'; +declare class TokenStore { + /** + * Checks whether any comments exist or not between the given 2 nodes. + * @param left The node to check. + * @param right The node to check. + * @returns `true` if one or more comments exist. + */ + commentsExistBetween(left: TSESTree.Node | TSESTree.Token, right: TSESTree.Node | TSESTree.Token): boolean; + /** + * Gets all comment tokens directly after the given node or token. + * @param nodeOrToken The AST node or token to check for adjacent comment tokens. + * @returns An array of comments in occurrence order. + */ + getCommentsAfter(nodeOrToken: TSESTree.Node | TSESTree.Token): TSESTree.Comment[]; + /** + * Gets all comment tokens directly before the given node or token. + * @param nodeOrToken The AST node or token to check for adjacent comment tokens. + * @returns An array of comments in occurrence order. + */ + getCommentsBefore(nodeOrToken: TSESTree.Node | TSESTree.Token): TSESTree.Comment[]; + /** + * Gets all comment tokens inside the given node. + * @param node The AST node to get the comments for. + * @returns An array of comments in occurrence order. + */ + getCommentsInside(node: TSESTree.Node): TSESTree.Comment[]; + /** + * Gets the first token of the given node. + * @param node The AST node. + * @param options The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. + * @returns An object representing the token. + */ + getFirstToken(node: TSESTree.Node, options?: T): SourceCode.ReturnTypeFromOptions | null; + /** + * Gets the first token between two non-overlapping nodes. + * @param left Node before the desired token range. + * @param right Node after the desired token range. + * @param options The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. + * @returns An object representing the token. + */ + getFirstTokenBetween(left: TSESTree.Node | TSESTree.Token, right: TSESTree.Node | TSESTree.Token, options?: T): SourceCode.ReturnTypeFromOptions | null; + /** + * Gets the first `count` tokens of the given node. + * @param node The AST node. + * @param options The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + */ + getFirstTokens(node: TSESTree.Node, options?: T): SourceCode.ReturnTypeFromOptions[]; + /** + * Gets the first `count` tokens between two non-overlapping nodes. + * @param left Node before the desired token range. + * @param right Node after the desired token range. + * @param options The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + * @returns Tokens between left and right. + */ + getFirstTokensBetween(left: TSESTree.Node | TSESTree.Token, right: TSESTree.Node | TSESTree.Token, options?: T): SourceCode.ReturnTypeFromOptions[]; + /** + * Gets the last token of the given node. + * @param node The AST node. + * @param options The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. + * @returns An object representing the token. + */ + getLastToken(node: TSESTree.Node, options?: T): SourceCode.ReturnTypeFromOptions | null; + /** + * Gets the last token between two non-overlapping nodes. + * @param left Node before the desired token range. + * @param right Node after the desired token range. + * @param options The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. + * @returns An object representing the token. + */ + getLastTokenBetween(left: TSESTree.Node | TSESTree.Token, right: TSESTree.Node | TSESTree.Token, options?: T): SourceCode.ReturnTypeFromOptions | null; + /** + * Gets the last `count` tokens of the given node. + * @param node The AST node. + * @param options The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + */ + getLastTokens(node: TSESTree.Node, options?: T): SourceCode.ReturnTypeFromOptions[]; + /** + * Gets the last `count` tokens between two non-overlapping nodes. + * @param left Node before the desired token range. + * @param right Node after the desired token range. + * @param options The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + * @returns Tokens between left and right. + */ + getLastTokensBetween(left: TSESTree.Node | TSESTree.Token, right: TSESTree.Node | TSESTree.Token, options?: T): SourceCode.ReturnTypeFromOptions[]; + /** + * Gets the token that follows a given node or token. + * @param node The AST node or token. + * @param options The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. + * @returns An object representing the token. + */ + getTokenAfter(node: TSESTree.Node | TSESTree.Token, options?: T): SourceCode.ReturnTypeFromOptions | null; + /** + * Gets the token that precedes a given node or token. + * @param node The AST node or token. + * @param options The option object + * @returns An object representing the token. + */ + getTokenBefore(node: TSESTree.Node | TSESTree.Token, options?: T): SourceCode.ReturnTypeFromOptions | null; + /** + * Gets the token starting at the specified index. + * @param offset Index of the start of the token's range. + * @param options The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. + * @returns The token starting at index, or null if no such token. + */ + getTokenByRangeStart(offset: number, options?: T): SourceCode.ReturnTypeFromOptions | null; + /** + * Gets all tokens that are related to the given node. + * @param node The AST node. + * @param beforeCount The number of tokens before the node to retrieve. + * @param afterCount The number of tokens after the node to retrieve. + * @returns Array of objects representing tokens. + */ + getTokens(node: TSESTree.Node, beforeCount?: number, afterCount?: number): TSESTree.Token[]; + /** + * Gets all tokens that are related to the given node. + * @param node The AST node. + * @param options The option object. If this is a function then it's `options.filter`. + * @returns Array of objects representing tokens. + */ + getTokens(node: TSESTree.Node, options: T): SourceCode.ReturnTypeFromOptions[]; + /** + * Gets the `count` tokens that follows a given node or token. + * @param node The AST node. + * @param options The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + */ + getTokensAfter(node: TSESTree.Node | TSESTree.Token, options?: number | T): SourceCode.ReturnTypeFromOptions[]; + /** + * Gets the `count` tokens that precedes a given node or token. + * @param node The AST node. + * @param options The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + */ + getTokensBefore(node: TSESTree.Node | TSESTree.Token, options?: number | T): SourceCode.ReturnTypeFromOptions[]; + /** + * Gets all of the tokens between two non-overlapping nodes. + * @param left Node before the desired token range. + * @param right Node after the desired token range. + * @param options The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + * @returns Tokens between left and right. + */ + getTokensBetween(left: TSESTree.Node | TSESTree.Token, right: TSESTree.Node | TSESTree.Token, options?: number | T): SourceCode.ReturnTypeFromOptions[]; +} +declare class SourceCodeBase extends TokenStore { + /** + * Represents parsed source code. + * @param ast The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. + */ + constructor(text: string, ast: SourceCode.Program); + /** + * Represents parsed source code. + * @param config The config object. + */ + constructor(config: SourceCode.SourceCodeConfig); + /** + * The parsed AST for the source code. + */ + ast: SourceCode.Program; + applyInlineConfig(): void; + applyLanguageOptions(): void; + finalize(): void; + /** + * Retrieves an array containing all comments in the source code. + * @returns An array of comment nodes. + */ + getAllComments(): TSESTree.Comment[]; + /** + * Converts a (line, column) pair into a range index. + * @param location A line/column location + * @returns The range index of the location in the file. + */ + getIndexFromLoc(location: TSESTree.Position): number; + /** + * Gets the entire source text split into an array of lines. + * @returns The source text as an array of lines. + */ + getLines(): string[]; + /** + * Converts a source text index into a (line, column) pair. + * @param index The index of a character in a file + * @returns A {line, column} location object with a 0-indexed column + */ + getLocFromIndex(index: number): TSESTree.Position; + /** + * Gets the deepest node containing a range index. + * @param index Range index of the desired node. + * @returns The node if found or `null` if not found. + */ + getNodeByRangeIndex(index: number): TSESTree.Node | null; + /** + * Gets the source code for the given node. + * @param node The AST node to get the text for. + * @param beforeCount The number of characters before the node to retrieve. + * @param afterCount The number of characters after the node to retrieve. + * @returns The text representing the AST node. + */ + getText(node?: TSESTree.Node | TSESTree.Token, beforeCount?: number, afterCount?: number): string; + /** + * The flag to indicate that the source code has Unicode BOM. + */ + hasBOM: boolean; + /** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * @param first The first node or token to check between. + * @param second The second node or token to check between. + * @returns True if there is a whitespace character between any of the tokens found between the two given nodes or tokens. + */ + isSpaceBetween(first: TSESTree.Node | TSESTree.Token, second: TSESTree.Node | TSESTree.Token): boolean; + /** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * For backward compatibility, this method returns true if there are + * `JSXText` tokens that contain whitespace between the two. + * @param first The first node or token to check between. + * @param second The second node or token to check between. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @deprecated in favor of isSpaceBetween + */ + isSpaceBetweenTokens(first: TSESTree.Token, second: TSESTree.Token): boolean; + /** + * Returns the scope of the given node. + * This information can be used track references to variables. + */ + getScope(node: TSESTree.Node): Scope.Scope; + /** + * Returns an array of the ancestors of the given node, starting at + * the root of the AST and continuing through the direct parent of the current node. + * This array does not include the currently-traversed node itself. + */ + getAncestors(node: TSESTree.Node): TSESTree.Node[]; + /** + * Returns a list of variables declared by the given node. + * This information can be used to track references to variables. + */ + getDeclaredVariables(node: TSESTree.Node): readonly Scope.Variable[]; + /** + * Marks a variable with the given name in the current scope as used. + * This affects the no-unused-vars rule. + */ + markVariableAsUsed(name: string, node: TSESTree.Node): boolean; + /** + * The source code split into lines according to ECMA-262 specification. + * This is done to avoid each rule needing to do so separately. + */ + lines: string[]; + /** + * The indexes in `text` that each line starts + */ + lineStartIndices: number[]; + /** + * The parser services of this source code. + */ + parserServices?: Partial; + /** + * The scope of this source code. + */ + scopeManager: Scope.ScopeManager | null; + /** + * The original text source code. BOM was stripped from this text. + */ + text: string; + /** + * All of the tokens and comments in the AST. + * + * TODO: rename to 'tokens' + */ + tokensAndComments: TSESTree.Token[]; + /** + * The visitor keys to traverse AST. + */ + visitorKeys: SourceCode.VisitorKeys; + /** + * Split the source code into multiple lines based on the line delimiters. + * @param text Source code as a string. + * @returns Array of source code lines. + */ + static splitLines(text: string): string[]; +} +declare namespace SourceCode { + interface Program extends TSESTree.Program { + comments: TSESTree.Comment[]; + tokens: TSESTree.Token[]; + } + interface SourceCodeConfig { + /** + * The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. + */ + ast: Program; + /** + * The parser services. + */ + parserServices: ParserServices | null; + /** + * The scope of this source code. + */ + scopeManager: Scope.ScopeManager | null; + /** + * The source code text. + */ + text: string; + /** + * The visitor keys to traverse AST. + */ + visitorKeys: VisitorKeys | null; + } + type VisitorKeys = Parser.VisitorKeys; + type FilterPredicate = (token: TSESTree.Token) => boolean; + type GetFilterPredicate = Filter extends ((token: TSESTree.Token) => token is infer U extends TSESTree.Token) ? U : Default; + type GetFilterPredicateFromOptions = Options extends { + filter?: FilterPredicate; + } ? GetFilterPredicate : GetFilterPredicate; + type ReturnTypeFromOptions = T extends { + includeComments: true; + } ? GetFilterPredicateFromOptions : GetFilterPredicateFromOptions>; + type CursorWithSkipOptions = number | FilterPredicate | { + /** + * The predicate function to choose tokens. + */ + filter?: FilterPredicate; + /** + * The flag to iterate comments as well. + */ + includeComments?: boolean; + /** + * The count of tokens the cursor skips. + */ + skip?: number; + }; + type CursorWithCountOptions = number | FilterPredicate | { + /** + * The maximum count of tokens the cursor iterates. + */ + count?: number; + /** + * The predicate function to choose tokens. + */ + filter?: FilterPredicate; + /** + * The flag to iterate comments as well. + */ + includeComments?: boolean; + }; +} +declare const SourceCode_base: typeof SourceCodeBase; +declare class SourceCode extends SourceCode_base { +} +export { SourceCode }; +//# sourceMappingURL=SourceCode.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/SourceCode.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/SourceCode.d.ts.map new file mode 100644 index 00000000..86085c41 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-esl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E,OAAO,CAAC,CAAC;IAC3C,KAAY,qBAAqB,CAAC,CAAC,IAAI,CAAC,SAAS;QAAE,eAAe,EAAE,IAAI,CAAA;KAAE,GACtE,6BAA6B,CAAC,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAC,GAChD,6BAA6B,CAC3B,CAAC,EACD,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,CAC1C,CAAC;IAEN,KAAY,qBAAqB,GAC7B,MAAM,GACN,eAAe,GACf;QACE;;WAEG;QACH,MAAM,CAAC,EAAE,eAAe,CAAC;QACzB;;WAEG;QACH,eAAe,CAAC,EAAE,OAAO,CAAC;QAC1B;;WAEG;QACH,IAAI,CAAC,EAAE,MAAM,CAAC;KACf,CAAC;IAEN,KAAY,sBAAsB,GAC9B,MAAM,GACN,eAAe,GACf;QACE;;WAEG;QACH,KAAK,CAAC,EAAE,MAAM,CAAC;QACf;;WAEG;QACH,MAAM,CAAC,EAAE,eAAe,CAAC;QACzB;;WAEG;QACH,eAAe,CAAC,EAAE,OAAO,CAAC;KAC3B,CAAC;CACP;+BAE6C,OAAO,cAAc;AAAnE,cAAM,UAAW,SAAQ,eAA2C;CAAG;AAEvE,OAAO,EAAE,UAAU,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/SourceCode.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/SourceCode.js new file mode 100644 index 00000000..a7769540 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/SourceCode.js @@ -0,0 +1,8 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-namespace, no-restricted-syntax */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SourceCode = void 0; +const eslint_1 = require("eslint"); +class SourceCode extends eslint_1.SourceCode { +} +exports.SourceCode = SourceCode; diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/ESLintShared.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/ESLintShared.d.ts new file mode 100644 index 00000000..9df2ae9e --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/ESLintShared.d.ts @@ -0,0 +1,382 @@ +import type { Linter } from '../Linter'; +import type { RuleMetaData } from '../Rule'; +export declare class ESLintBase> { + /** + * Creates a new instance of the main ESLint API. + * @param options The options for this instance. + */ + constructor(options?: Options); + /** + * This method calculates the configuration for a given file, which can be useful for debugging purposes. + * - It resolves and merges extends and overrides settings into the top level configuration. + * - It resolves the parser setting to absolute paths. + * - It normalizes the plugins setting to align short names. (e.g., eslint-plugin-foo → foo) + * - It adds the processor setting if a legacy file extension processor is matched. + * - It doesn't interpret the env setting to the globals and parserOptions settings, so the result object contains + * the env setting as is. + * @param filePath The path to the file whose configuration you would like to calculate. Directory paths are forbidden + * because ESLint cannot handle the overrides setting. + * @returns The promise that will be fulfilled with a configuration object. + */ + calculateConfigForFile(filePath: string): Promise; + getRulesMetaForResults(results: LintResult[]): Record>>; + /** + * This method checks if a given file is ignored by your configuration. + * @param filePath The path to the file you want to check. + * @returns The promise that will be fulfilled with whether the file is ignored or not. If the file is ignored, then + * it will return true. + */ + isPathIgnored(filePath: string): Promise; + /** + * This method lints the files that match the glob patterns and then returns the results. + * @param patterns The lint target files. This can contain any of file paths, directory paths, and glob patterns. + * @returns The promise that will be fulfilled with an array of LintResult objects. + */ + lintFiles(patterns: string | string[]): Promise; + /** + * This method lints the given source code text and then returns the results. + * + * By default, this method uses the configuration that applies to files in the current working directory (the cwd + * constructor option). If you want to use a different configuration, pass options.filePath, and ESLint will load the + * same configuration that eslint.lintFiles() would use for a file at options.filePath. + * + * If the options.filePath value is configured to be ignored, this method returns an empty array. If the + * options.warnIgnored option is set along with the options.filePath option, this method returns a LintResult object. + * In that case, the result may contain a warning that indicates the file was ignored. + * @param code The source code text to check. + * @returns The promise that will be fulfilled with an array of LintResult objects. This is an array (despite there + * being only one lint result) in order to keep the interfaces between this and the eslint.lintFiles() + * method similar. + */ + lintText(code: string, options?: LintTextOptions): Promise; + /** + * This method loads a formatter. Formatters convert lint results to a human- or machine-readable string. + * @param name TThe path to the file you want to check. + * The following values are allowed: + * - undefined. In this case, loads the "stylish" built-in formatter. + * - A name of built-in formatters. + * - A name of third-party formatters. For examples: + * -- `foo` will load eslint-formatter-foo. + * -- `@foo` will load `@foo/eslint-formatter`. + * -- `@foo/bar` will load `@foo/eslint-formatter-bar`. + * - A path to the file that defines a formatter. The path must contain one or more path separators (/) in order to distinguish if it's a path or not. For example, start with ./. + * @returns The promise that will be fulfilled with a Formatter object. + */ + loadFormatter(name?: string): Promise; + /** + * This method copies the given results and removes warnings. The returned value contains only errors. + * @param results The LintResult objects to filter. + * @returns The filtered LintResult objects. + */ + static getErrorResults(results: LintResult): LintResult; + /** + * This method writes code modified by ESLint's autofix feature into its respective file. If any of the modified + * files don't exist, this method does nothing. + * @param results The LintResult objects to write. + * @returns The promise that will be fulfilled after all files are written. + */ + static outputFixes(results: LintResult[]): Promise; + /** + * The version text. + */ + static readonly version: string; + /** + * The type of configuration used by this class. + */ + static readonly configType: Linter.ConfigTypeSpecifier; +} +export interface ESLintOptions { + /** + * If false is present, ESLint suppresses comment directives in source code. + * If this option is false, it overrides the noInlineConfig setting in your configurations. + * @default true + */ + allowInlineConfig?: boolean; + /** + * Configuration object, extended by all configurations used with this instance. + * You can use this option to define the default settings that will be used if your configuration files don't + * configure it. + * @default null + */ + baseConfig?: Config | null; + /** + * If `true` is present, the `eslint.lintFiles()` method caches lint results and uses it if each target file is not + * changed. Please mind that ESLint doesn't clear the cache when you upgrade ESLint plugins. In that case, you have + * to remove the cache file manually. The `eslint.lintText()` method doesn't use caches even if you pass the + * options.filePath to the method. + * @default false + */ + cache?: boolean; + /** + * The eslint.lintFiles() method writes caches into this file. + * @default '.eslintcache' + */ + cacheLocation?: string; + /** + * Strategy for the cache to use for detecting changed files. + * @default 'metadata' + */ + cacheStrategy?: 'content' | 'metadata'; + /** + * The working directory. This must be an absolute path. + * @default process.cwd() + */ + cwd?: string; + /** + * Unless set to false, the `eslint.lintFiles()` method will throw an error when no target files are found. + * @default true + */ + errorOnUnmatchedPattern?: boolean; + /** + * If `true` is present, the `eslint.lintFiles()` and `eslint.lintText()` methods work in autofix mode. + * If a predicate function is present, the methods pass each lint message to the function, then use only the + * lint messages for which the function returned true. + * @default false + */ + fix?: boolean | ((message: LintMessage) => boolean); + /** + * The types of the rules that the `eslint.lintFiles()` and `eslint.lintText()` methods use for autofix. + * @default null + */ + fixTypes?: ('directive' | 'problem' | 'suggestion')[] | null; + /** + * If false is present, the `eslint.lintFiles()` method doesn't interpret glob patterns. + * @default true + */ + globInputPaths?: boolean; + /** + * Configuration object, overrides all configurations used with this instance. + * You can use this option to define the settings that will be used even if your configuration files configure it. + * @default null + */ + overrideConfig?: Config | null; + /** + * When set to true, missing patterns cause the linting operation to short circuit and not report any failures. + * @default false + */ + passOnNoPatterns?: boolean; + /** + * The plugin implementations that ESLint uses for the plugins setting of your configuration. + * This is a map-like object. Those keys are plugin IDs and each value is implementation. + * @default null + */ + plugins?: Record | null; +} +export interface DeprecatedRuleInfo { + /** + * The rule IDs that replace this deprecated rule. + */ + replacedBy: string[]; + /** + * The rule ID. + */ + ruleId: string; +} +/** + * The LintResult value is the information of the linting result of each file. + */ +export interface LintResult { + /** + * The number of errors. This includes fixable errors. + */ + errorCount: number; + /** + * The number of fatal errors. + */ + fatalErrorCount: number; + /** + * The absolute path to the file of this result. This is the string "" if the file path is unknown (when you + * didn't pass the options.filePath option to the eslint.lintText() method). + */ + filePath: string; + /** + * The number of errors that can be fixed automatically by the fix constructor option. + */ + fixableErrorCount: number; + /** + * The number of warnings that can be fixed automatically by the fix constructor option. + */ + fixableWarningCount: number; + /** + * The array of LintMessage objects. + */ + messages: LintMessage[]; + /** + * The source code of the file that was linted, with as many fixes applied as possible. + */ + output?: string; + /** + * The original source code text. This property is undefined if any messages didn't exist or the output + * property exists. + */ + source?: string; + /** + * Timing information of the lint run. + * This exists if and only if the `--stats` CLI flag was added or the `stats: true` + * option was passed to the ESLint class + * @since 9.0.0 + */ + stats?: LintStats; + /** + * The array of SuppressedLintMessage objects. + */ + suppressedMessages: SuppressedLintMessage[]; + /** + * The information about the deprecated rules that were used to check this file. + */ + usedDeprecatedRules: DeprecatedRuleInfo[]; + /** + * The number of warnings. This includes fixable warnings. + */ + warningCount: number; +} +export interface LintStats { + /** + * The number of times ESLint has applied at least one fix after linting. + */ + fixPasses: number; + /** + * The times spent on (parsing, fixing, linting) a file, where the linting refers to the timing information for each rule. + */ + times: { + passes: LintStatsTimePass[]; + }; +} +export interface LintStatsTimePass { + /** + * The total time that is spent on applying fixes to the code. + */ + fix: LintStatsFixTime; + /** + * The total time that is spent when parsing a file. + */ + parse: LintStatsParseTime; + /** + * The total time that is spent on a rule. + */ + rules?: Record; + /** + * The cumulative total + */ + total: number; +} +export interface LintStatsParseTime { + total: number; +} +export interface LintStatsRuleTime { + total: number; +} +export interface LintStatsFixTime { + total: number; +} +export interface LintTextOptions { + /** + * The path to the file of the source code text. If omitted, the result.filePath becomes the string "". + */ + filePath?: string; + /** + * If true is present and the options.filePath is a file ESLint should ignore, this method returns a lint result + * contains a warning message. + */ + warnIgnored?: boolean; +} +/** + * The LintMessage value is the information of each linting error. + */ +export interface LintMessage { + /** + * The 1-based column number of the begin point of this message. + */ + column: number | undefined; + /** + * The 1-based column number of the end point of this message. This property is undefined if this message + * is not a range. + */ + endColumn: number | undefined; + /** + * The 1-based line number of the end point of this message. This property is undefined if this + * message is not a range. + */ + endLine: number | undefined; + /** + * `true` if this is a fatal error unrelated to a rule, like a parsing error. + */ + fatal?: boolean | undefined; + /** + * The EditInfo object of autofix. This property is undefined if this message is not fixable. + */ + fix: EditInfo | undefined; + /** + * The 1-based line number of the begin point of this message. + */ + line: number | undefined; + /** + * The error message + */ + message: string; + /** + * The rule name that generates this lint message. If this message is generated by the ESLint core rather than + * rules, this is null. + */ + ruleId: string | null; + /** + * The severity of this message. 1 means warning and 2 means error. + */ + severity: 1 | 2; + /** + * The list of suggestions. Each suggestion is the pair of a description and an EditInfo object to fix code. API + * users such as editor integrations can choose one of them to fix the problem of this message. This property is + * undefined if this message doesn't have any suggestions. + */ + suggestions: { + desc: string; + fix: EditInfo; + }[] | undefined; +} +/** + * The SuppressedLintMessage value is the information of each suppressed linting error. + */ +export interface SuppressedLintMessage extends LintMessage { + /** + * The list of suppressions. + */ + suppressions?: { + /** + * The free text description added after the `--` in the comment + */ + justification: string; + /** + * Right now, this is always `directive` + */ + kind: string; + }[]; +} +/** + * The EditInfo value is information to edit text. + * + * This edit information means replacing the range of the range property by the text property value. It's like + * sourceCodeText.slice(0, edit.range[0]) + edit.text + sourceCodeText.slice(edit.range[1]). Therefore, it's an add + * if the range[0] and range[1] property values are the same value, and it's removal if the text property value is + * empty string. + */ +export interface EditInfo { + /** + * The pair of 0-based indices in source code text to remove. + */ + range: [number, number]; + /** + * The text to add. + */ + text: string; +} +/** + * The Formatter value is the object to convert the LintResult objects to text. + */ +export interface Formatter { + /** + * The method to convert the LintResult objects to text. + * Promise return supported since 8.4.0 + */ + format(results: LintResult[]): string | Promise; +} +//# sourceMappingURL=ESLintShared.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/ESLintShared.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/ESLintShared.d.ts.map new file mode 100644 index 00000000..d9678ca1 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/ESLintShared.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ESLintShared.d.ts","sourceRoot":"","sources":["../../../src/ts-eslint/eslint/ESLintShared.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C,MAAM,CAAC,OAAO,OAAO,UAAU,CAC7B,MAAM,SAA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AAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC5B;;OAEG;IACH,GAAG,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC1B;;OAEG;IACH,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB;;OAEG;IACH,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC;IAChB;;;;OAIG;IACH,WAAW,EACP;QACE,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,EAAE,QAAQ,CAAC;KACf,EAAE,GACH,SAAS,CAAC;CACf;AAED;;GAEG;AACH,MAAM,WAAW,qBAAsB,SAAQ,WAAW;IACxD;;OAEG;IACH,YAAY,CAAC,EAAE;QACb;;WAEG;QACH,aAAa,EAAE,MAAM,CAAC;QACtB;;WAEG;QACH,IAAI,EAAE,MAAM,CAAC;KACd,EAAE,CAAC;CACL;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,QAAQ;IACvB;;OAEG;IACH,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB;;;OAGG;IACH,MAAM,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CACzD"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/ESLintShared.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/ESLintShared.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/ESLintShared.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/FlatESLint.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/FlatESLint.d.ts new file mode 100644 index 00000000..bb4ea72d --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/FlatESLint.d.ts @@ -0,0 +1,84 @@ +import type { FlatConfig } from '../Config'; +import type * as Shared from './ESLintShared'; +declare class FlatESLintBase extends Shared.ESLintBase { + static readonly configType: 'flat'; + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param filePath The path of the file to retrieve a config object for. + * @returns A configuration object for the file or `undefined` if there is no configuration data for the object. + */ + calculateConfigForFile(filePath: string): Promise; + /** + * Finds the config file being used by this instance based on the options + * passed to the constructor. + * @returns The path to the config file being used or `undefined` if no config file is being used. + */ + findConfigFile(): Promise; +} +declare const FlatESLint_base: typeof FlatESLintBase; +/** + * The ESLint class is the primary class to use in Node.js applications. + * This class depends on the Node.js fs module and the file system, so you cannot use it in browsers. + * + * If you want to lint code on browsers, use the Linter class instead. + */ +export declare class FlatESLint extends FlatESLint_base { +} +export declare namespace FlatESLint { + interface ESLintOptions extends Shared.ESLintOptions { + /** + * If false is present, the eslint.lintFiles() method doesn't respect `ignorePatterns` ignorePatterns in your configuration. + * @default true + */ + ignore?: boolean; + /** + * Ignore file patterns to use in addition to config ignores. These patterns are relative to cwd. + * @default null + */ + ignorePatterns?: string[] | null; + /** + * The path to a configuration file, overrides all configurations used with this instance. + * The options.overrideConfig option is applied after this option is applied. + * Searches for default config file when falsy; doesn't do any config file lookup when `true`; considered to be a config filename when a string. + * @default false + */ + overrideConfigFile?: boolean | string; + /** + * A predicate function that filters rules to be run. + * This function is called with an object containing `ruleId` and `severity`, and returns `true` if the rule should be run. + * @default () => true + */ + ruleFilter?: RuleFilter; + /** + * When set to true, additional statistics are added to the lint results. + * @see {@link https://eslint.org/docs/latest/extend/stats} + * @default false + */ + stats?: boolean; + /** + * Show warnings when the file list includes ignored files. + * @default true + */ + warnIgnored?: boolean; + } + type DeprecatedRuleInfo = Shared.DeprecatedRuleInfo; + type EditInfo = Shared.EditInfo; + type Formatter = Shared.Formatter; + type LintMessage = Shared.LintMessage; + type LintResult = Shared.LintResult; + type LintStats = Shared.LintStats; + type LintStatsFixTime = Shared.LintStatsFixTime; + type LintStatsParseTime = Shared.LintStatsParseTime; + type LintStatsRuleTime = Shared.LintStatsRuleTime; + type LintStatsTimePass = Shared.LintStatsTimePass; + type LintTextOptions = Shared.LintTextOptions; + type SuppressedLintMessage = Shared.SuppressedLintMessage; + type RuleFilter = (rule: { + ruleId: string; + severity: number; + }) => boolean; +} +export {}; +//# sourceMappingURL=FlatESLint.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/FlatESLint.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/FlatESLint.d.ts.map new file mode 100644 index 00000000..3afc310a --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/FlatESLint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"FlatESLint.d.ts","sourceRoot":"","sources":["../../../src/ts-eslint/eslint/FlatESLint.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,KAAK,MAAM,MAAM,gBAAgB,CAAC;AAG9C,OAAO,OAAO,cAAe,SAAQ,MAAM,CAAC,UAAU,CACpD,UAAU,CAAC,WAAW,EACtB,UAAU,CAAC,aAAa,CACzB;IACC,MAAM,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAEnC;;;;;;OAMG;IACH,sBAAsB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC;IAEzE;;;;OAIG;IACH,cAAc,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;CAC9C;+BAQoD,OAAO,cAAc;AAN1E;;;;;GAKG;AACH,qBAA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a/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/FlatESLint.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/FlatESLint.js new file mode 100644 index 00000000..37f84a2e --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/FlatESLint.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FlatESLint = void 0; +/* eslint-disable @typescript-eslint/no-namespace */ +const use_at_your_own_risk_1 = require("eslint/use-at-your-own-risk"); +/** + * The ESLint class is the primary class to use in Node.js applications. + * This class depends on the Node.js fs module and the file system, so you cannot use it in browsers. + * + * If you want to lint code on browsers, use the Linter class instead. + */ +class FlatESLint extends use_at_your_own_risk_1.FlatESLint { +} +exports.FlatESLint = FlatESLint; diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/LegacyESLint.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/LegacyESLint.d.ts new file mode 100644 index 00000000..698c0120 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/LegacyESLint.d.ts @@ -0,0 +1,73 @@ +import type { ClassicConfig } from '../Config'; +import type { Linter } from '../Linter'; +import type * as Shared from './ESLintShared'; +declare class LegacyESLintBase extends Shared.ESLintBase { + static readonly configType: 'eslintrc'; +} +declare const LegacyESLint_base: typeof LegacyESLintBase; +/** + * The ESLint class is the primary class to use in Node.js applications. + * This class depends on the Node.js fs module and the file system, so you cannot use it in browsers. + * + * If you want to lint code on browsers, use the Linter class instead. + */ +export declare class LegacyESLint extends LegacyESLint_base { +} +export declare namespace LegacyESLint { + interface ESLintOptions extends Shared.ESLintOptions { + /** + * If you pass directory paths to the eslint.lintFiles() method, ESLint checks the files in those directories that + * have the given extensions. For example, when passing the src/ directory and extensions is [".js", ".ts"], ESLint + * will lint *.js and *.ts files in src/. If extensions is null, ESLint checks *.js files and files that match + * overrides[].files patterns in your configuration. + * Note: This option only applies when you pass directory paths to the eslint.lintFiles() method. + * If you pass glob patterns, ESLint will lint all files matching the glob pattern regardless of extension. + */ + extensions?: string[] | null; + /** + * If false is present, the eslint.lintFiles() method doesn't respect `.eslintignore` files in your configuration. + * @default true + */ + ignore?: boolean; + /** + * The path to a file ESLint uses instead of `$CWD/.eslintignore`. + * If a path is present and the file doesn't exist, this constructor will throw an error. + */ + ignorePath?: string; + /** + * The path to a configuration file, overrides all configurations used with this instance. + * The options.overrideConfig option is applied after this option is applied. + */ + overrideConfigFile?: string | null; + /** + * The severity to report unused eslint-disable directives. + * If this option is a severity, it overrides the reportUnusedDisableDirectives setting in your configurations. + */ + reportUnusedDisableDirectives?: Linter.SeverityString | null; + /** + * The path to a directory where plugins should be resolved from. + * If null is present, ESLint loads plugins from the location of the configuration file that contains the plugin + * setting. + * If a path is present, ESLint loads all plugins from there. + */ + resolvePluginsRelativeTo?: string | null; + /** + * An array of paths to directories to load custom rules from. + */ + rulePaths?: string[]; + /** + * If false is present, ESLint doesn't load configuration files (.eslintrc.* files). + * Only the configuration of the constructor options is valid. + */ + useEslintrc?: boolean; + } + type DeprecatedRuleInfo = Shared.DeprecatedRuleInfo; + type EditInfo = Shared.EditInfo; + type Formatter = Shared.Formatter; + type LintMessage = Shared.LintMessage; + type LintResult = Omit; + type LintTextOptions = Shared.LintTextOptions; + type SuppressedLintMessage = Shared.SuppressedLintMessage; +} +export {}; +//# sourceMappingURL=LegacyESLint.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/LegacyESLint.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/LegacyESLint.d.ts.map new file mode 100644 index 00000000..e798f27c --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/LegacyESLint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"LegacyESLint.d.ts","sourceRoot":"","sources":["../../../src/ts-eslint/eslint/LegacyESLint.ts"],"names":[],"mappings":"AAIA,OAAO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AC,UAAU,EAAE,OAAO,CAAC,CAAC;IAC1D,KAAY,eAAe,GAAG,MAAM,CAAC,eAAe,CAAC;IACrD,KAAY,qBAAqB,GAAG,MAAM,CAAC,qBAAqB,CAAC;CAClE"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/LegacyESLint.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/LegacyESLint.js new file mode 100644 index 00000000..f40012bf --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/eslint/LegacyESLint.js @@ -0,0 +1,14 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-namespace */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LegacyESLint = void 0; +const use_at_your_own_risk_1 = require("eslint/use-at-your-own-risk"); +/** + * The ESLint class is the primary class to use in Node.js applications. + * This class depends on the Node.js fs module and the file system, so you cannot use it in browsers. + * + * If you want to lint code on browsers, use the Linter class instead. + */ +class LegacyESLint extends use_at_your_own_risk_1.LegacyESLint { +} +exports.LegacyESLint = LegacyESLint; diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/index.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-eslint/index.d.ts new file mode 100644 index 00000000..17edebe9 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/index.d.ts @@ -0,0 +1,12 @@ +export * from './AST'; +export * from './Config'; +export * from './ESLint'; +export * from './Linter'; +export * from './Parser'; +export * from './ParserOptions'; +export * from './Processor'; +export * from './Rule'; +export * from './RuleTester'; +export * from './Scope'; +export * from './SourceCode'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/index.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-eslint/index.d.ts.map new file mode 100644 index 00000000..31ec4265 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAC;AACtB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,CAAC;AAChC,cAAc,aAAa,CAAC;AAC5B,cAAc,QAAQ,CAAC;AACvB,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-eslint/index.js b/node_modules/@typescript-eslint/utils/dist/ts-eslint/index.js new file mode 100644 index 00000000..7ee906eb --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-eslint/index.js @@ -0,0 +1,27 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./AST"), exports); +__exportStar(require("./Config"), exports); +__exportStar(require("./ESLint"), exports); +__exportStar(require("./Linter"), exports); +__exportStar(require("./Parser"), exports); +__exportStar(require("./ParserOptions"), exports); +__exportStar(require("./Processor"), exports); +__exportStar(require("./Rule"), exports); +__exportStar(require("./RuleTester"), exports); +__exportStar(require("./Scope"), exports); +__exportStar(require("./SourceCode"), exports); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-estree.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-estree.d.ts new file mode 100644 index 00000000..43b2b754 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-estree.d.ts @@ -0,0 +1,3 @@ +export { AST_NODE_TYPES, AST_TOKEN_TYPES, TSESTree, } from '@typescript-eslint/types'; +export type { ParserServices, ParserServicesWithoutTypeInformation, ParserServicesWithTypeInformation, } from '@typescript-eslint/typescript-estree'; +//# sourceMappingURL=ts-estree.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-estree.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-estree.d.ts.map new file mode 100644 index 00000000..3a7063c3 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-estree.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ts-estree.d.ts","sourceRoot":"","sources":["../src/ts-estree.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,cAAc,EACd,eAAe,EACf,QAAQ,GACT,MAAM,0BAA0B,CAAC;AAElC,YAAY,EACV,cAAc,EACd,oCAAoC,EACpC,iCAAiC,GAClC,MAAM,sCAAsC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-estree.js b/node_modules/@typescript-eslint/utils/dist/ts-estree.js new file mode 100644 index 00000000..b5843b3f --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-estree.js @@ -0,0 +1,9 @@ +"use strict"; +// for convenience's sake - export the types directly from here so consumers +// don't need to reference/install both packages in their code +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TSESTree = exports.AST_TOKEN_TYPES = exports.AST_NODE_TYPES = void 0; +var types_1 = require("@typescript-eslint/types"); +Object.defineProperty(exports, "AST_NODE_TYPES", { enumerable: true, get: function () { return types_1.AST_NODE_TYPES; } }); +Object.defineProperty(exports, "AST_TOKEN_TYPES", { enumerable: true, get: function () { return types_1.AST_TOKEN_TYPES; } }); +Object.defineProperty(exports, "TSESTree", { enumerable: true, get: function () { return types_1.TSESTree; } }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-utils/NoInfer.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-utils/NoInfer.d.ts new file mode 100644 index 00000000..163c4043 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-utils/NoInfer.d.ts @@ -0,0 +1,10 @@ +/** + * We could use NoInfer typescript build-in utility + * introduced in typescript 5.4, however at the moment of creation + * the supported ts versions are >=4.8.4 <5.7.0 + * so for the moment we have to stick to this polyfill. + * + * @see https://github.com/millsp/ts-toolbelt/blob/master/sources/Function/NoInfer.ts + */ +export type NoInfer = [A][A extends unknown ? 0 : never]; +//# sourceMappingURL=NoInfer.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-utils/NoInfer.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-utils/NoInfer.d.ts.map new file mode 100644 index 00000000..44bb4ef9 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-utils/NoInfer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"NoInfer.d.ts","sourceRoot":"","sources":["../../src/ts-utils/NoInfer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,MAAM,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,OAAO,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-utils/NoInfer.js b/node_modules/@typescript-eslint/utils/dist/ts-utils/NoInfer.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-utils/NoInfer.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-utils/index.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-utils/index.d.ts new file mode 100644 index 00000000..da4764b0 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-utils/index.d.ts @@ -0,0 +1,3 @@ +export * from './isArray'; +export * from './NoInfer'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-utils/index.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-utils/index.d.ts.map new file mode 100644 index 00000000..d1bbe756 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-utils/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ts-utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-utils/index.js b/node_modules/@typescript-eslint/utils/dist/ts-utils/index.js new file mode 100644 index 00000000..aa68bbb7 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-utils/index.js @@ -0,0 +1,18 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./isArray"), exports); +__exportStar(require("./NoInfer"), exports); diff --git a/node_modules/@typescript-eslint/utils/dist/ts-utils/isArray.d.ts b/node_modules/@typescript-eslint/utils/dist/ts-utils/isArray.d.ts new file mode 100644 index 00000000..ddefcee8 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-utils/isArray.d.ts @@ -0,0 +1,2 @@ +export declare function isArray(arg: unknown): arg is readonly unknown[]; +//# sourceMappingURL=isArray.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-utils/isArray.d.ts.map b/node_modules/@typescript-eslint/utils/dist/ts-utils/isArray.d.ts.map new file mode 100644 index 00000000..55264f27 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-utils/isArray.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isArray.d.ts","sourceRoot":"","sources":["../../src/ts-utils/isArray.ts"],"names":[],"mappings":"AACA,wBAAgB,OAAO,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,SAAS,OAAO,EAAE,CAE/D"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/dist/ts-utils/isArray.js b/node_modules/@typescript-eslint/utils/dist/ts-utils/isArray.js new file mode 100644 index 00000000..7deedcf7 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/dist/ts-utils/isArray.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isArray = isArray; +// https://github.com/microsoft/TypeScript/issues/17002 +function isArray(arg) { + return Array.isArray(arg); +} diff --git a/node_modules/@typescript-eslint/utils/package.json b/node_modules/@typescript-eslint/utils/package.json new file mode 100644 index 00000000..33031c95 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/package.json @@ -0,0 +1,97 @@ +{ + "name": "@typescript-eslint/utils", + "version": "8.34.0", + "description": "Utilities for working with TypeScript + ESLint together", + "files": [ + "dist", + "!*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./ast-utils": { + "types": "./dist/ast-utils/index.d.ts", + "default": "./dist/ast-utils/index.js" + }, + "./eslint-utils": { + "types": "./dist/eslint-utils/index.d.ts", + "default": "./dist/eslint-utils/index.js" + }, + "./json-schema": { + "types": "./dist/json-schema.d.ts", + "default": "./dist/json-schema.js" + }, + "./ts-eslint": { + "types": "./dist/ts-eslint/index.d.ts", + "default": "./dist/ts-eslint/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/utils" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/utils", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "format": "yarn run -T format", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "dependencies": { + "@eslint-community/eslint-utils": "^4.7.0", + "@typescript-eslint/scope-manager": "8.34.0", + "@typescript-eslint/types": "8.34.0", + "@typescript-eslint/typescript-estree": "8.34.0" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + }, + "devDependencies": { + "@vitest/coverage-v8": "^3.1.3", + "rimraf": "*", + "typescript": "*", + "vitest": "^3.1.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "utils", + "includedScripts": [ + "clean" + ], + "targets": { + "test": { + "dependsOn": [ + "^build" + ] + } + } + } +} diff --git a/node_modules/@typescript-eslint/visitor-keys/LICENSE b/node_modules/@typescript-eslint/visitor-keys/LICENSE new file mode 100644 index 00000000..a1164108 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/visitor-keys/README.md b/node_modules/@typescript-eslint/visitor-keys/README.md new file mode 100644 index 00000000..1745172a --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/README.md @@ -0,0 +1,10 @@ +# `@typescript-eslint/visitor-keys` + +> Visitor keys used to help traverse the TypeScript-ESTree AST. + +## ✋ Internal Package + +This is an _internal package_ to the [typescript-eslint monorepo](https://github.com/typescript-eslint/typescript-eslint). +You likely don't want to use it directly. + +👉 See **https://typescript-eslint.io** for docs on typescript-eslint. diff --git a/node_modules/@typescript-eslint/visitor-keys/dist/get-keys.d.ts b/node_modules/@typescript-eslint/visitor-keys/dist/get-keys.d.ts new file mode 100644 index 00000000..1b6aad17 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/dist/get-keys.d.ts @@ -0,0 +1,3 @@ +import type { TSESTree } from '@typescript-eslint/types'; +export declare const getKeys: (node: TSESTree.Node) => readonly string[]; +//# sourceMappingURL=get-keys.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/visitor-keys/dist/get-keys.d.ts.map b/node_modules/@typescript-eslint/visitor-keys/dist/get-keys.d.ts.map new file mode 100644 index 00000000..8fdba2a7 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/dist/get-keys.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"get-keys.d.ts","sourceRoot":"","sources":["../src/get-keys.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAIzD,eAAO,MAAM,OAAO,EAAE,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,KAAK,SAAS,MAAM,EAC7C,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/visitor-keys/dist/get-keys.js b/node_modules/@typescript-eslint/visitor-keys/dist/get-keys.js new file mode 100644 index 00000000..58c14a5a --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/dist/get-keys.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getKeys = void 0; +const eslint_visitor_keys_1 = require("eslint-visitor-keys"); +exports.getKeys = eslint_visitor_keys_1.getKeys; diff --git a/node_modules/@typescript-eslint/visitor-keys/dist/index.d.ts b/node_modules/@typescript-eslint/visitor-keys/dist/index.d.ts new file mode 100644 index 00000000..f9eb5a97 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/dist/index.d.ts @@ -0,0 +1,3 @@ +export { getKeys } from './get-keys'; +export { visitorKeys, type VisitorKeys } from './visitor-keys'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/visitor-keys/dist/index.d.ts.map b/node_modules/@typescript-eslint/visitor-keys/dist/index.d.ts.map new file mode 100644 index 00000000..d9031764 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/visitor-keys/dist/index.js b/node_modules/@typescript-eslint/visitor-keys/dist/index.js new file mode 100644 index 00000000..b86a3284 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/dist/index.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.visitorKeys = exports.getKeys = void 0; +var get_keys_1 = require("./get-keys"); +Object.defineProperty(exports, "getKeys", { enumerable: true, get: function () { return get_keys_1.getKeys; } }); +var visitor_keys_1 = require("./visitor-keys"); +Object.defineProperty(exports, "visitorKeys", { enumerable: true, get: function () { return visitor_keys_1.visitorKeys; } }); diff --git a/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.d.ts b/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.d.ts new file mode 100644 index 00000000..97855608 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.d.ts @@ -0,0 +1,3 @@ +export type VisitorKeys = Record; +export declare const visitorKeys: VisitorKeys; +//# sourceMappingURL=visitor-keys.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.d.ts.map b/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.d.ts.map new file mode 100644 index 00000000..33cd6840 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"visitor-keys.d.ts","sourceRoot":"","sources":["../src/visitor-keys.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;AA0QxE,eAAO,MAAM,WAAW,EAAE,WACmB,CAAC"} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js b/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js new file mode 100644 index 00000000..0e13f57b --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js @@ -0,0 +1,194 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.visitorKeys = void 0; +const eslintVisitorKeys = __importStar(require("eslint-visitor-keys")); +/* + ********************************** IMPORTANT NOTE ******************************** + * * + * The key arrays should be sorted in the order in which you would want to visit * + * the child keys. * + * * + * DO NOT SORT THEM ALPHABETICALLY! * + * * + * They should be sorted in the order that they appear in the source code. * + * For example: * + * * + * class Foo extends Bar { prop: 1 } * + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ClassDeclaration * + * ^^^ id ^^^ superClass * + * ^^^^^^^^^^^ body * + * * + * It would be incorrect to provide the visitor keys ['body', 'id', 'superClass'] * + * because the body comes AFTER everything else in the source code. * + * Instead the correct ordering would be ['id', 'superClass', 'body']. * + * * + ********************************************************************************** + */ +const SharedVisitorKeys = (() => { + const FunctionType = ['typeParameters', 'params', 'returnType']; + const AnonymousFunction = [...FunctionType, 'body']; + const AbstractPropertyDefinition = [ + 'decorators', + 'key', + 'typeAnnotation', + ]; + return { + AbstractPropertyDefinition: ['decorators', 'key', 'typeAnnotation'], + AnonymousFunction, + AsExpression: ['expression', 'typeAnnotation'], + ClassDeclaration: [ + 'decorators', + 'id', + 'typeParameters', + 'superClass', + 'superTypeArguments', + 'implements', + 'body', + ], + Function: ['id', ...AnonymousFunction], + FunctionType, + PropertyDefinition: [...AbstractPropertyDefinition, 'value'], + }; +})(); +const additionalKeys = { + AccessorProperty: SharedVisitorKeys.PropertyDefinition, + ArrayPattern: ['decorators', 'elements', 'typeAnnotation'], + ArrowFunctionExpression: SharedVisitorKeys.AnonymousFunction, + AssignmentPattern: ['decorators', 'left', 'right', 'typeAnnotation'], + CallExpression: ['callee', 'typeArguments', 'arguments'], + ClassDeclaration: SharedVisitorKeys.ClassDeclaration, + ClassExpression: SharedVisitorKeys.ClassDeclaration, + Decorator: ['expression'], + ExportAllDeclaration: ['exported', 'source', 'attributes'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source', 'attributes'], + FunctionDeclaration: SharedVisitorKeys.Function, + FunctionExpression: SharedVisitorKeys.Function, + Identifier: ['decorators', 'typeAnnotation'], + ImportAttribute: ['key', 'value'], + ImportDeclaration: ['specifiers', 'source', 'attributes'], + ImportExpression: ['source', 'options'], + JSXClosingFragment: [], + JSXOpeningElement: ['name', 'typeArguments', 'attributes'], + JSXOpeningFragment: [], + JSXSpreadChild: ['expression'], + MethodDefinition: ['decorators', 'key', 'value'], + NewExpression: ['callee', 'typeArguments', 'arguments'], + ObjectPattern: ['decorators', 'properties', 'typeAnnotation'], + PropertyDefinition: SharedVisitorKeys.PropertyDefinition, + RestElement: ['decorators', 'argument', 'typeAnnotation'], + StaticBlock: ['body'], + TaggedTemplateExpression: ['tag', 'typeArguments', 'quasi'], + TSAbstractAccessorProperty: SharedVisitorKeys.AbstractPropertyDefinition, + TSAbstractKeyword: [], + TSAbstractMethodDefinition: ['key', 'value'], + TSAbstractPropertyDefinition: SharedVisitorKeys.AbstractPropertyDefinition, + TSAnyKeyword: [], + TSArrayType: ['elementType'], + TSAsExpression: SharedVisitorKeys.AsExpression, + TSAsyncKeyword: [], + TSBigIntKeyword: [], + TSBooleanKeyword: [], + TSCallSignatureDeclaration: SharedVisitorKeys.FunctionType, + TSClassImplements: ['expression', 'typeArguments'], + TSConditionalType: ['checkType', 'extendsType', 'trueType', 'falseType'], + TSConstructorType: SharedVisitorKeys.FunctionType, + TSConstructSignatureDeclaration: SharedVisitorKeys.FunctionType, + TSDeclareFunction: SharedVisitorKeys.Function, + TSDeclareKeyword: [], + TSEmptyBodyFunctionExpression: ['id', ...SharedVisitorKeys.FunctionType], + TSEnumBody: ['members'], + TSEnumDeclaration: ['id', 'body'], + TSEnumMember: ['id', 'initializer'], + TSExportAssignment: ['expression'], + TSExportKeyword: [], + TSExternalModuleReference: ['expression'], + TSFunctionType: SharedVisitorKeys.FunctionType, + TSImportEqualsDeclaration: ['id', 'moduleReference'], + TSImportType: ['argument', 'options', 'qualifier', 'typeArguments'], + TSIndexedAccessType: ['objectType', 'indexType'], + TSIndexSignature: ['parameters', 'typeAnnotation'], + TSInferType: ['typeParameter'], + TSInstantiationExpression: ['expression', 'typeArguments'], + TSInterfaceBody: ['body'], + TSInterfaceDeclaration: ['id', 'typeParameters', 'extends', 'body'], + TSInterfaceHeritage: ['expression', 'typeArguments'], + TSIntersectionType: ['types'], + TSIntrinsicKeyword: [], + TSLiteralType: ['literal'], + TSMappedType: ['key', 'constraint', 'nameType', 'typeAnnotation'], + TSMethodSignature: ['key', 'typeParameters', 'params', 'returnType'], + TSModuleBlock: ['body'], + TSModuleDeclaration: ['id', 'body'], + TSNamedTupleMember: ['label', 'elementType'], + TSNamespaceExportDeclaration: ['id'], + TSNeverKeyword: [], + TSNonNullExpression: ['expression'], + TSNullKeyword: [], + TSNumberKeyword: [], + TSObjectKeyword: [], + TSOptionalType: ['typeAnnotation'], + TSParameterProperty: ['decorators', 'parameter'], + TSPrivateKeyword: [], + TSPropertySignature: ['key', 'typeAnnotation'], + TSProtectedKeyword: [], + TSPublicKeyword: [], + TSQualifiedName: ['left', 'right'], + TSReadonlyKeyword: [], + TSRestType: ['typeAnnotation'], + TSSatisfiesExpression: SharedVisitorKeys.AsExpression, + TSStaticKeyword: [], + TSStringKeyword: [], + TSSymbolKeyword: [], + TSTemplateLiteralType: ['quasis', 'types'], + TSThisType: [], + TSTupleType: ['elementTypes'], + TSTypeAliasDeclaration: ['id', 'typeParameters', 'typeAnnotation'], + TSTypeAnnotation: ['typeAnnotation'], + TSTypeAssertion: ['typeAnnotation', 'expression'], + TSTypeLiteral: ['members'], + TSTypeOperator: ['typeAnnotation'], + TSTypeParameter: ['name', 'constraint', 'default'], + TSTypeParameterDeclaration: ['params'], + TSTypeParameterInstantiation: ['params'], + TSTypePredicate: ['parameterName', 'typeAnnotation'], + TSTypeQuery: ['exprName', 'typeArguments'], + TSTypeReference: ['typeName', 'typeArguments'], + TSUndefinedKeyword: [], + TSUnionType: ['types'], + TSUnknownKeyword: [], + TSVoidKeyword: [], +}; +exports.visitorKeys = eslintVisitorKeys.unionWith(additionalKeys); diff --git a/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE new file mode 100644 index 00000000..17a25538 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md new file mode 100644 index 00000000..aa860ba5 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md @@ -0,0 +1,121 @@ +# eslint-visitor-keys + +[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) +[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions) + +Constants and utilities about visitor keys to traverse AST. + +## 💿 Installation + +Use [npm] to install. + +```bash +$ npm install eslint-visitor-keys +``` + +### Requirements + +- [Node.js] `^18.18.0`, `^20.9.0`, or `>=21.1.0` + +## 📖 Usage + +To use in an ESM file: + +```js +import * as evk from "eslint-visitor-keys" +``` + +To use in a CommonJS file: + +```js +const evk = require("eslint-visitor-keys") +``` + +### evk.KEYS + +> type: `{ [type: string]: string[] | undefined }` + +Visitor keys. This keys are frozen. + +This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. + +For example: + +``` +console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] +``` + +### evk.getKeys(node) + +> type: `(node: object) => string[]` + +Get the visitor keys of a given AST node. + +This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. + +This will be used to traverse unknown nodes. + +For example: + +```js +const node = { + type: "AssignmentExpression", + left: { type: "Identifier", name: "foo" }, + right: { type: "Literal", value: 0 } +} +console.log(evk.getKeys(node)) // → ["type", "left", "right"] +``` + +### evk.unionWith(additionalKeys) + +> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` + +Make the union set with `evk.KEYS` and the given keys. + +- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. +- It removes duplicated keys as keeping the first one. + +For example: + +```js +console.log(evk.unionWith({ + MethodDefinition: ["decorators"] +})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } +``` + +## 📰 Change log + +See [GitHub releases](https://github.com/eslint/js/releases). + +## 🍻 Contributing + +Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). + +### Development commands + +- `npm test` runs tests and measures code coverage. +- `npm run lint` checks source codes with ESLint. +- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser. + +[npm]: https://www.npmjs.com/ +[Node.js]: https://nodejs.org/ +[ESTree]: https://github.com/estree/estree + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs new file mode 100644 index 00000000..afc433c7 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs @@ -0,0 +1,396 @@ +'use strict'; + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source", + "attributes" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source", + "attributes" + ], + ExportSpecifier: [ + "local", + "exported" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportAttribute: [ + "key", + "value" + ], + ImportDeclaration: [ + "specifiers", + "source", + "attributes" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source", + "options" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +function getKeys(node) { + return Object.keys(node).filter(filterKey); +} +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */ + +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +function unionWith(additionalKeys) { + const retv = /** @type {{ [type: string]: ReadonlyArray }} */ + (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.hasOwn(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +exports.KEYS = KEYS; +exports.getKeys = getKeys; +exports.unionWith = unionWith; diff --git a/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts new file mode 100644 index 00000000..34253c96 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts @@ -0,0 +1,28 @@ +type VisitorKeys$1 = { + readonly [type: string]: ReadonlyArray; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys$1; + +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +declare function getKeys(node: Object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys; + +type VisitorKeys = VisitorKeys$1; + +export { KEYS, getKeys, unionWith }; +export type { VisitorKeys }; diff --git a/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/index.d.ts b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/index.d.ts new file mode 100644 index 00000000..e65b7da3 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/index.d.ts @@ -0,0 +1,16 @@ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node: Object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys: VisitorKeys): VisitorKeys; +export { KEYS }; +export type VisitorKeys = import("./visitor-keys.js").VisitorKeys; +import KEYS from "./visitor-keys.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts new file mode 100644 index 00000000..2d7ada2f --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts @@ -0,0 +1,12 @@ +export default KEYS; +export type VisitorKeys = { + readonly [type: string]: ReadonlyArray; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys; +//# sourceMappingURL=visitor-keys.d.ts.map \ No newline at end of file diff --git a/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/index.js b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/index.js new file mode 100644 index 00000000..1fc89b43 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/index.js @@ -0,0 +1,67 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +import KEYS from "./visitor-keys.js"; + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node) { + return Object.keys(node).filter(filterKey); +} +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */ + +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys) { + const retv = /** @type {{ [type: string]: ReadonlyArray }} */ + (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.hasOwn(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +export { KEYS }; diff --git a/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/visitor-keys.js b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/visitor-keys.js new file mode 100644 index 00000000..c891e040 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/visitor-keys.js @@ -0,0 +1,327 @@ +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source", + "attributes" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source", + "attributes" + ], + ExportSpecifier: [ + "local", + "exported" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportAttribute: [ + "key", + "value" + ], + ImportDeclaration: [ + "specifiers", + "source", + "attributes" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source", + "options" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +export default KEYS; diff --git a/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/package.json b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/package.json new file mode 100644 index 00000000..852e4ddb --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/package.json @@ -0,0 +1,70 @@ +{ + "name": "eslint-visitor-keys", + "version": "4.2.1", + "description": "Constants and utilities about visitor keys to traverse AST.", + "type": "module", + "main": "dist/eslint-visitor-keys.cjs", + "types": "./dist/index.d.ts", + "exports": { + ".": [ + { + "import": "./lib/index.js", + "require": "./dist/eslint-visitor-keys.cjs" + }, + "./dist/eslint-visitor-keys.cjs" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist/index.d.ts", + "dist/visitor-keys.d.ts", + "dist/eslint-visitor-keys.cjs", + "dist/eslint-visitor-keys.d.cts", + "lib" + ], + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "devDependencies": { + "@types/estree": "^0.0.51", + "@types/estree-jsx": "^0.0.1", + "@typescript-eslint/parser": "^8.7.0", + "eslint-release": "^3.2.0", + "esquery": "^1.4.0", + "json-diff": "^0.7.3", + "opener": "^1.5.2", + "rollup": "^4.22.4", + "rollup-plugin-dts": "^6.1.1", + "tsd": "^0.31.2", + "typescript": "^5.6.2" + }, + "scripts": { + "build": "npm run build:cjs && npm run build:types", + "build:cjs": "rollup -c", + "build:debug": "npm run build:cjs -- -m && npm run build:types", + "build:types": "tsc -v && tsc", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "mocha tests/lib/**/*.cjs && c8 mocha tests/lib/**/*.js && npm run test:types", + "test:open-coverage": "c8 report --reporter lcov && opener coverage/lcov-report/index.html", + "test:types": "tsd" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/eslint-visitor-keys" + }, + "funding": "https://opencollective.com/eslint", + "keywords": [ + "eslint" + ], + "author": "Toru Nagashima (https://github.com/mysticatea)", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-visitor-keys/README.md" +} diff --git a/node_modules/@typescript-eslint/visitor-keys/package.json b/node_modules/@typescript-eslint/visitor-keys/package.json new file mode 100644 index 00000000..146e7611 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/package.json @@ -0,0 +1,68 @@ +{ + "name": "@typescript-eslint/visitor-keys", + "version": "8.34.0", + "description": "Visitor keys used to help traverse the TypeScript-ESTree AST", + "files": [ + "dist", + "!*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/visitor-keys" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "format": "yarn run -T format", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "dependencies": { + "@typescript-eslint/types": "8.34.0", + "eslint-visitor-keys": "^4.2.0" + }, + "devDependencies": { + "@vitest/coverage-v8": "^3.1.3", + "rimraf": "*", + "typescript": "*", + "vitest": "^3.1.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "visitor-keys", + "includedScripts": [ + "clean" + ] + } +} diff --git a/node_modules/acorn-jsx/LICENSE b/node_modules/acorn-jsx/LICENSE new file mode 100644 index 00000000..695d4b93 --- /dev/null +++ b/node_modules/acorn-jsx/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2017 by Ingvar Stepanyan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/acorn-jsx/README.md b/node_modules/acorn-jsx/README.md new file mode 100644 index 00000000..317c3ac4 --- /dev/null +++ b/node_modules/acorn-jsx/README.md @@ -0,0 +1,40 @@ +# Acorn-JSX + +[![Build Status](https://travis-ci.org/acornjs/acorn-jsx.svg?branch=master)](https://travis-ci.org/acornjs/acorn-jsx) +[![NPM version](https://img.shields.io/npm/v/acorn-jsx.svg)](https://www.npmjs.org/package/acorn-jsx) + +This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript. + +It was created as an experimental alternative, faster [React.js JSX](http://facebook.github.io/react/docs/jsx-in-depth.html) parser. Later, it replaced the [official parser](https://github.com/facebookarchive/esprima) and these days is used by many prominent development tools. + +## Transpiler + +Please note that this tool only parses source code to JSX AST, which is useful for various language tools and services. If you want to transpile your code to regular ES5-compliant JavaScript with source map, check out [Babel](https://babeljs.io/) and [Buble](https://buble.surge.sh/) transpilers which use `acorn-jsx` under the hood. + +## Usage + +Requiring this module provides you with an Acorn plugin that you can use like this: + +```javascript +var acorn = require("acorn"); +var jsx = require("acorn-jsx"); +acorn.Parser.extend(jsx()).parse("my(, 'code');"); +``` + +Note that official spec doesn't support mix of XML namespaces and object-style access in tag names (#27) like in ``, so it was deprecated in `acorn-jsx@3.0`. If you still want to opt-in to support of such constructions, you can pass the following option: + +```javascript +acorn.Parser.extend(jsx({ allowNamespacedObjects: true })) +``` + +Also, since most apps use pure React transformer, a new option was introduced that allows to prohibit namespaces completely: + +```javascript +acorn.Parser.extend(jsx({ allowNamespaces: false })) +``` + +Note that by default `allowNamespaces` is enabled for spec compliancy. + +## License + +This plugin is issued under the [MIT license](./LICENSE). diff --git a/node_modules/acorn-jsx/index.d.ts b/node_modules/acorn-jsx/index.d.ts new file mode 100644 index 00000000..f37b1df4 --- /dev/null +++ b/node_modules/acorn-jsx/index.d.ts @@ -0,0 +1,12 @@ +import { Parser } from 'acorn' + +declare const jsx: (options?: jsx.Options) => (BaseParser: typeof Parser) => typeof Parser; + +declare namespace jsx { + interface Options { + allowNamespacedObjects?: boolean; + allowNamespaces?: boolean; + } +} + +export = jsx; diff --git a/node_modules/acorn-jsx/index.js b/node_modules/acorn-jsx/index.js new file mode 100644 index 00000000..004e0809 --- /dev/null +++ b/node_modules/acorn-jsx/index.js @@ -0,0 +1,488 @@ +'use strict'; + +const XHTMLEntities = require('./xhtml'); + +const hexNumber = /^[\da-fA-F]+$/; +const decimalNumber = /^\d+$/; + +// The map to `acorn-jsx` tokens from `acorn` namespace objects. +const acornJsxMap = new WeakMap(); + +// Get the original tokens for the given `acorn` namespace object. +function getJsxTokens(acorn) { + acorn = acorn.Parser.acorn || acorn; + let acornJsx = acornJsxMap.get(acorn); + if (!acornJsx) { + const tt = acorn.tokTypes; + const TokContext = acorn.TokContext; + const TokenType = acorn.TokenType; + const tc_oTag = new TokContext('...', true, true); + const tokContexts = { + tc_oTag: tc_oTag, + tc_cTag: tc_cTag, + tc_expr: tc_expr + }; + const tokTypes = { + jsxName: new TokenType('jsxName'), + jsxText: new TokenType('jsxText', {beforeExpr: true}), + jsxTagStart: new TokenType('jsxTagStart', {startsExpr: true}), + jsxTagEnd: new TokenType('jsxTagEnd') + }; + + tokTypes.jsxTagStart.updateContext = function() { + this.context.push(tc_expr); // treat as beginning of JSX expression + this.context.push(tc_oTag); // start opening tag context + this.exprAllowed = false; + }; + tokTypes.jsxTagEnd.updateContext = function(prevType) { + let out = this.context.pop(); + if (out === tc_oTag && prevType === tt.slash || out === tc_cTag) { + this.context.pop(); + this.exprAllowed = this.curContext() === tc_expr; + } else { + this.exprAllowed = true; + } + }; + + acornJsx = { tokContexts: tokContexts, tokTypes: tokTypes }; + acornJsxMap.set(acorn, acornJsx); + } + + return acornJsx; +} + +// Transforms JSX element name to string. + +function getQualifiedJSXName(object) { + if (!object) + return object; + + if (object.type === 'JSXIdentifier') + return object.name; + + if (object.type === 'JSXNamespacedName') + return object.namespace.name + ':' + object.name.name; + + if (object.type === 'JSXMemberExpression') + return getQualifiedJSXName(object.object) + '.' + + getQualifiedJSXName(object.property); +} + +module.exports = function(options) { + options = options || {}; + return function(Parser) { + return plugin({ + allowNamespaces: options.allowNamespaces !== false, + allowNamespacedObjects: !!options.allowNamespacedObjects + }, Parser); + }; +}; + +// This is `tokTypes` of the peer dep. +// This can be different instances from the actual `tokTypes` this plugin uses. +Object.defineProperty(module.exports, "tokTypes", { + get: function get_tokTypes() { + return getJsxTokens(require("acorn")).tokTypes; + }, + configurable: true, + enumerable: true +}); + +function plugin(options, Parser) { + const acorn = Parser.acorn || require("acorn"); + const acornJsx = getJsxTokens(acorn); + const tt = acorn.tokTypes; + const tok = acornJsx.tokTypes; + const tokContexts = acorn.tokContexts; + const tc_oTag = acornJsx.tokContexts.tc_oTag; + const tc_cTag = acornJsx.tokContexts.tc_cTag; + const tc_expr = acornJsx.tokContexts.tc_expr; + const isNewLine = acorn.isNewLine; + const isIdentifierStart = acorn.isIdentifierStart; + const isIdentifierChar = acorn.isIdentifierChar; + + return class extends Parser { + // Expose actual `tokTypes` and `tokContexts` to other plugins. + static get acornJsx() { + return acornJsx; + } + + // Reads inline JSX contents token. + jsx_readToken() { + let out = '', chunkStart = this.pos; + for (;;) { + if (this.pos >= this.input.length) + this.raise(this.start, 'Unterminated JSX contents'); + let ch = this.input.charCodeAt(this.pos); + + switch (ch) { + case 60: // '<' + case 123: // '{' + if (this.pos === this.start) { + if (ch === 60 && this.exprAllowed) { + ++this.pos; + return this.finishToken(tok.jsxTagStart); + } + return this.getTokenFromCode(ch); + } + out += this.input.slice(chunkStart, this.pos); + return this.finishToken(tok.jsxText, out); + + case 38: // '&' + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readEntity(); + chunkStart = this.pos; + break; + + case 62: // '>' + case 125: // '}' + this.raise( + this.pos, + "Unexpected token `" + this.input[this.pos] + "`. Did you mean `" + + (ch === 62 ? ">" : "}") + "` or " + "`{\"" + this.input[this.pos] + "\"}" + "`?" + ); + + default: + if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readNewLine(true); + chunkStart = this.pos; + } else { + ++this.pos; + } + } + } + } + + jsx_readNewLine(normalizeCRLF) { + let ch = this.input.charCodeAt(this.pos); + let out; + ++this.pos; + if (ch === 13 && this.input.charCodeAt(this.pos) === 10) { + ++this.pos; + out = normalizeCRLF ? '\n' : '\r\n'; + } else { + out = String.fromCharCode(ch); + } + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + + return out; + } + + jsx_readString(quote) { + let out = '', chunkStart = ++this.pos; + for (;;) { + if (this.pos >= this.input.length) + this.raise(this.start, 'Unterminated string constant'); + let ch = this.input.charCodeAt(this.pos); + if (ch === quote) break; + if (ch === 38) { // '&' + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readEntity(); + chunkStart = this.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readNewLine(false); + chunkStart = this.pos; + } else { + ++this.pos; + } + } + out += this.input.slice(chunkStart, this.pos++); + return this.finishToken(tt.string, out); + } + + jsx_readEntity() { + let str = '', count = 0, entity; + let ch = this.input[this.pos]; + if (ch !== '&') + this.raise(this.pos, 'Entity must start with an ampersand'); + let startPos = ++this.pos; + while (this.pos < this.input.length && count++ < 10) { + ch = this.input[this.pos++]; + if (ch === ';') { + if (str[0] === '#') { + if (str[1] === 'x') { + str = str.substr(2); + if (hexNumber.test(str)) + entity = String.fromCharCode(parseInt(str, 16)); + } else { + str = str.substr(1); + if (decimalNumber.test(str)) + entity = String.fromCharCode(parseInt(str, 10)); + } + } else { + entity = XHTMLEntities[str]; + } + break; + } + str += ch; + } + if (!entity) { + this.pos = startPos; + return '&'; + } + return entity; + } + + // Read a JSX identifier (valid tag or attribute name). + // + // Optimized version since JSX identifiers can't contain + // escape characters and so can be read as single slice. + // Also assumes that first character was already checked + // by isIdentifierStart in readToken. + + jsx_readWord() { + let ch, start = this.pos; + do { + ch = this.input.charCodeAt(++this.pos); + } while (isIdentifierChar(ch) || ch === 45); // '-' + return this.finishToken(tok.jsxName, this.input.slice(start, this.pos)); + } + + // Parse next token as JSX identifier + + jsx_parseIdentifier() { + let node = this.startNode(); + if (this.type === tok.jsxName) + node.name = this.value; + else if (this.type.keyword) + node.name = this.type.keyword; + else + this.unexpected(); + this.next(); + return this.finishNode(node, 'JSXIdentifier'); + } + + // Parse namespaced identifier. + + jsx_parseNamespacedName() { + let startPos = this.start, startLoc = this.startLoc; + let name = this.jsx_parseIdentifier(); + if (!options.allowNamespaces || !this.eat(tt.colon)) return name; + var node = this.startNodeAt(startPos, startLoc); + node.namespace = name; + node.name = this.jsx_parseIdentifier(); + return this.finishNode(node, 'JSXNamespacedName'); + } + + // Parses element name in any form - namespaced, member + // or single identifier. + + jsx_parseElementName() { + if (this.type === tok.jsxTagEnd) return ''; + let startPos = this.start, startLoc = this.startLoc; + let node = this.jsx_parseNamespacedName(); + if (this.type === tt.dot && node.type === 'JSXNamespacedName' && !options.allowNamespacedObjects) { + this.unexpected(); + } + while (this.eat(tt.dot)) { + let newNode = this.startNodeAt(startPos, startLoc); + newNode.object = node; + newNode.property = this.jsx_parseIdentifier(); + node = this.finishNode(newNode, 'JSXMemberExpression'); + } + return node; + } + + // Parses any type of JSX attribute value. + + jsx_parseAttributeValue() { + switch (this.type) { + case tt.braceL: + let node = this.jsx_parseExpressionContainer(); + if (node.expression.type === 'JSXEmptyExpression') + this.raise(node.start, 'JSX attributes must only be assigned a non-empty expression'); + return node; + + case tok.jsxTagStart: + case tt.string: + return this.parseExprAtom(); + + default: + this.raise(this.start, 'JSX value should be either an expression or a quoted JSX text'); + } + } + + // JSXEmptyExpression is unique type since it doesn't actually parse anything, + // and so it should start at the end of last read token (left brace) and finish + // at the beginning of the next one (right brace). + + jsx_parseEmptyExpression() { + let node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc); + return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc); + } + + // Parses JSX expression enclosed into curly brackets. + + jsx_parseExpressionContainer() { + let node = this.startNode(); + this.next(); + node.expression = this.type === tt.braceR + ? this.jsx_parseEmptyExpression() + : this.parseExpression(); + this.expect(tt.braceR); + return this.finishNode(node, 'JSXExpressionContainer'); + } + + // Parses following JSX attribute name-value pair. + + jsx_parseAttribute() { + let node = this.startNode(); + if (this.eat(tt.braceL)) { + this.expect(tt.ellipsis); + node.argument = this.parseMaybeAssign(); + this.expect(tt.braceR); + return this.finishNode(node, 'JSXSpreadAttribute'); + } + node.name = this.jsx_parseNamespacedName(); + node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null; + return this.finishNode(node, 'JSXAttribute'); + } + + // Parses JSX opening tag starting after '<'. + + jsx_parseOpeningElementAt(startPos, startLoc) { + let node = this.startNodeAt(startPos, startLoc); + node.attributes = []; + let nodeName = this.jsx_parseElementName(); + if (nodeName) node.name = nodeName; + while (this.type !== tt.slash && this.type !== tok.jsxTagEnd) + node.attributes.push(this.jsx_parseAttribute()); + node.selfClosing = this.eat(tt.slash); + this.expect(tok.jsxTagEnd); + return this.finishNode(node, nodeName ? 'JSXOpeningElement' : 'JSXOpeningFragment'); + } + + // Parses JSX closing tag starting after ''); + } + } + let fragmentOrElement = openingElement.name ? 'Element' : 'Fragment'; + + node['opening' + fragmentOrElement] = openingElement; + node['closing' + fragmentOrElement] = closingElement; + node.children = children; + if (this.type === tt.relational && this.value === "<") { + this.raise(this.start, "Adjacent JSX elements must be wrapped in an enclosing tag"); + } + return this.finishNode(node, 'JSX' + fragmentOrElement); + } + + // Parse JSX text + + jsx_parseText() { + let node = this.parseLiteral(this.value); + node.type = "JSXText"; + return node; + } + + // Parses entire JSX element from current position. + + jsx_parseElement() { + let startPos = this.start, startLoc = this.startLoc; + this.next(); + return this.jsx_parseElementAt(startPos, startLoc); + } + + parseExprAtom(refShortHandDefaultPos) { + if (this.type === tok.jsxText) + return this.jsx_parseText(); + else if (this.type === tok.jsxTagStart) + return this.jsx_parseElement(); + else + return super.parseExprAtom(refShortHandDefaultPos); + } + + readToken(code) { + let context = this.curContext(); + + if (context === tc_expr) return this.jsx_readToken(); + + if (context === tc_oTag || context === tc_cTag) { + if (isIdentifierStart(code)) return this.jsx_readWord(); + + if (code == 62) { + ++this.pos; + return this.finishToken(tok.jsxTagEnd); + } + + if ((code === 34 || code === 39) && context == tc_oTag) + return this.jsx_readString(code); + } + + if (code === 60 && this.exprAllowed && this.input.charCodeAt(this.pos + 1) !== 33) { + ++this.pos; + return this.finishToken(tok.jsxTagStart); + } + return super.readToken(code); + } + + updateContext(prevType) { + if (this.type == tt.braceL) { + var curContext = this.curContext(); + if (curContext == tc_oTag) this.context.push(tokContexts.b_expr); + else if (curContext == tc_expr) this.context.push(tokContexts.b_tmpl); + else super.updateContext(prevType); + this.exprAllowed = true; + } else if (this.type === tt.slash && prevType === tok.jsxTagStart) { + this.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore + this.context.push(tc_cTag); // reconsider as closing tag context + this.exprAllowed = false; + } else { + return super.updateContext(prevType); + } + } + }; +} diff --git a/node_modules/acorn-jsx/package.json b/node_modules/acorn-jsx/package.json new file mode 100644 index 00000000..6debde9c --- /dev/null +++ b/node_modules/acorn-jsx/package.json @@ -0,0 +1,27 @@ +{ + "name": "acorn-jsx", + "description": "Modern, fast React.js JSX parser", + "homepage": "https://github.com/acornjs/acorn-jsx", + "version": "5.3.2", + "maintainers": [ + { + "name": "Ingvar Stepanyan", + "email": "me@rreverser.com", + "web": "http://rreverser.com/" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/acornjs/acorn-jsx" + }, + "license": "MIT", + "scripts": { + "test": "node test/run.js" + }, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "devDependencies": { + "acorn": "^8.0.1" + } +} diff --git a/node_modules/acorn-jsx/xhtml.js b/node_modules/acorn-jsx/xhtml.js new file mode 100644 index 00000000..c1520092 --- /dev/null +++ b/node_modules/acorn-jsx/xhtml.js @@ -0,0 +1,255 @@ +module.exports = { + quot: '\u0022', + amp: '&', + apos: '\u0027', + lt: '<', + gt: '>', + nbsp: '\u00A0', + iexcl: '\u00A1', + cent: '\u00A2', + pound: '\u00A3', + curren: '\u00A4', + yen: '\u00A5', + brvbar: '\u00A6', + sect: '\u00A7', + uml: '\u00A8', + copy: '\u00A9', + ordf: '\u00AA', + laquo: '\u00AB', + not: '\u00AC', + shy: '\u00AD', + reg: '\u00AE', + macr: '\u00AF', + deg: '\u00B0', + plusmn: '\u00B1', + sup2: '\u00B2', + sup3: '\u00B3', + acute: '\u00B4', + micro: '\u00B5', + para: '\u00B6', + middot: '\u00B7', + cedil: '\u00B8', + sup1: '\u00B9', + ordm: '\u00BA', + raquo: '\u00BB', + frac14: '\u00BC', + frac12: '\u00BD', + frac34: '\u00BE', + iquest: '\u00BF', + Agrave: '\u00C0', + Aacute: '\u00C1', + Acirc: '\u00C2', + Atilde: '\u00C3', + Auml: '\u00C4', + Aring: '\u00C5', + AElig: '\u00C6', + Ccedil: '\u00C7', + Egrave: '\u00C8', + Eacute: '\u00C9', + Ecirc: '\u00CA', + Euml: '\u00CB', + Igrave: '\u00CC', + Iacute: '\u00CD', + Icirc: '\u00CE', + Iuml: '\u00CF', + ETH: '\u00D0', + Ntilde: '\u00D1', + Ograve: '\u00D2', + Oacute: '\u00D3', + Ocirc: '\u00D4', + Otilde: '\u00D5', + Ouml: '\u00D6', + times: '\u00D7', + Oslash: '\u00D8', + Ugrave: '\u00D9', + Uacute: '\u00DA', + Ucirc: '\u00DB', + Uuml: '\u00DC', + Yacute: '\u00DD', + THORN: '\u00DE', + szlig: '\u00DF', + agrave: '\u00E0', + aacute: '\u00E1', + acirc: '\u00E2', + atilde: '\u00E3', + auml: '\u00E4', + aring: '\u00E5', + aelig: '\u00E6', + ccedil: '\u00E7', + egrave: '\u00E8', + eacute: '\u00E9', + ecirc: '\u00EA', + euml: '\u00EB', + igrave: '\u00EC', + iacute: '\u00ED', + icirc: '\u00EE', + iuml: '\u00EF', + eth: '\u00F0', + ntilde: '\u00F1', + ograve: '\u00F2', + oacute: '\u00F3', + ocirc: '\u00F4', + otilde: '\u00F5', + ouml: '\u00F6', + divide: '\u00F7', + oslash: '\u00F8', + ugrave: '\u00F9', + uacute: '\u00FA', + ucirc: '\u00FB', + uuml: '\u00FC', + yacute: '\u00FD', + thorn: '\u00FE', + yuml: '\u00FF', + OElig: '\u0152', + oelig: '\u0153', + Scaron: '\u0160', + scaron: '\u0161', + Yuml: '\u0178', + fnof: '\u0192', + circ: '\u02C6', + tilde: '\u02DC', + Alpha: '\u0391', + Beta: '\u0392', + Gamma: '\u0393', + Delta: '\u0394', + Epsilon: '\u0395', + Zeta: '\u0396', + Eta: '\u0397', + Theta: '\u0398', + Iota: '\u0399', + Kappa: '\u039A', + Lambda: '\u039B', + Mu: '\u039C', + Nu: '\u039D', + Xi: '\u039E', + Omicron: '\u039F', + Pi: '\u03A0', + Rho: '\u03A1', + Sigma: '\u03A3', + Tau: '\u03A4', + Upsilon: '\u03A5', + Phi: '\u03A6', + Chi: '\u03A7', + Psi: '\u03A8', + Omega: '\u03A9', + alpha: '\u03B1', + beta: '\u03B2', + gamma: '\u03B3', + delta: '\u03B4', + epsilon: '\u03B5', + zeta: '\u03B6', + eta: '\u03B7', + theta: '\u03B8', + iota: '\u03B9', + kappa: '\u03BA', + lambda: '\u03BB', + mu: '\u03BC', + nu: '\u03BD', + xi: '\u03BE', + omicron: '\u03BF', + pi: '\u03C0', + rho: '\u03C1', + sigmaf: '\u03C2', + sigma: '\u03C3', + tau: '\u03C4', + upsilon: '\u03C5', + phi: '\u03C6', + chi: '\u03C7', + psi: '\u03C8', + omega: '\u03C9', + thetasym: '\u03D1', + upsih: '\u03D2', + piv: '\u03D6', + ensp: '\u2002', + emsp: '\u2003', + thinsp: '\u2009', + zwnj: '\u200C', + zwj: '\u200D', + lrm: '\u200E', + rlm: '\u200F', + ndash: '\u2013', + mdash: '\u2014', + lsquo: '\u2018', + rsquo: '\u2019', + sbquo: '\u201A', + ldquo: '\u201C', + rdquo: '\u201D', + bdquo: '\u201E', + dagger: '\u2020', + Dagger: '\u2021', + bull: '\u2022', + hellip: '\u2026', + permil: '\u2030', + prime: '\u2032', + Prime: '\u2033', + lsaquo: '\u2039', + rsaquo: '\u203A', + oline: '\u203E', + frasl: '\u2044', + euro: '\u20AC', + image: '\u2111', + weierp: '\u2118', + real: '\u211C', + trade: '\u2122', + alefsym: '\u2135', + larr: '\u2190', + uarr: '\u2191', + rarr: '\u2192', + darr: '\u2193', + harr: '\u2194', + crarr: '\u21B5', + lArr: '\u21D0', + uArr: '\u21D1', + rArr: '\u21D2', + dArr: '\u21D3', + hArr: '\u21D4', + forall: '\u2200', + part: '\u2202', + exist: '\u2203', + empty: '\u2205', + nabla: '\u2207', + isin: '\u2208', + notin: '\u2209', + ni: '\u220B', + prod: '\u220F', + sum: '\u2211', + minus: '\u2212', + lowast: '\u2217', + radic: '\u221A', + prop: '\u221D', + infin: '\u221E', + ang: '\u2220', + and: '\u2227', + or: '\u2228', + cap: '\u2229', + cup: '\u222A', + 'int': '\u222B', + there4: '\u2234', + sim: '\u223C', + cong: '\u2245', + asymp: '\u2248', + ne: '\u2260', + equiv: '\u2261', + le: '\u2264', + ge: '\u2265', + sub: '\u2282', + sup: '\u2283', + nsub: '\u2284', + sube: '\u2286', + supe: '\u2287', + oplus: '\u2295', + otimes: '\u2297', + perp: '\u22A5', + sdot: '\u22C5', + lceil: '\u2308', + rceil: '\u2309', + lfloor: '\u230A', + rfloor: '\u230B', + lang: '\u2329', + rang: '\u232A', + loz: '\u25CA', + spades: '\u2660', + clubs: '\u2663', + hearts: '\u2665', + diams: '\u2666' +}; diff --git a/node_modules/acorn/CHANGELOG.md b/node_modules/acorn/CHANGELOG.md new file mode 100644 index 00000000..c86068cd --- /dev/null +++ b/node_modules/acorn/CHANGELOG.md @@ -0,0 +1,954 @@ +## 8.15.0 (2025-06-08) + +### New features + +Support `using` and `await using` syntax. + +The `AnyNode` type is now defined in such a way that plugins can extend it. + +### Bug fixes + +Fix an issue where the `bigint` property of literal nodes for non-decimal bigints had the wrong format. + +The `acorn` CLI tool no longer crashes when emitting a tree that contains a bigint. + +## 8.14.1 (2025-03-05) + +### Bug fixes + +Fix an issue where `await` expressions in class field initializers were inappropriately allowed. + +Properly allow await inside an async arrow function inside a class field initializer. + +Mention the source file name in syntax error messages when given. + +Properly add an empty `attributes` property to every form of `ExportNamedDeclaration`. + +## 8.14.0 (2024-10-27) + +### New features + +Support ES2025 import attributes. + +Support ES2025 RegExp modifiers. + +### Bug fixes + +Support some missing Unicode properties. + +## 8.13.0 (2024-10-16) + +### New features + +Upgrade to Unicode 16.0. + +## 8.12.1 (2024-07-03) + +### Bug fixes + +Fix a regression that caused Acorn to no longer run on Node versions <8.10. + +## 8.12.0 (2024-06-14) + +### New features + +Support ES2025 duplicate capture group names in regular expressions. + +### Bug fixes + +Include `VariableDeclarator` in the `AnyNode` type so that walker objects can refer to it without getting a type error. + +Properly raise a parse error for invalid `for`/`of` statements using `async` as binding name. + +Properly recognize \"use strict\" when preceded by a string with an escaped newline. + +Mark the `Parser` constructor as protected, not private, so plugins can extend it without type errors. + +Fix a bug where some invalid `delete` expressions were let through when the operand was parenthesized and `preserveParens` was enabled. + +Properly normalize line endings in raw strings of invalid template tokens. + +Properly track line numbers for escaped newlines in strings. + +Fix a bug that broke line number accounting after a template literal with invalid escape sequences. + +## 8.11.3 (2023-12-29) + +### Bug fixes + +Add `Function` and `Class` to the `AggregateType` type, so that they can be used in walkers without raising a type error. + +Make sure `onToken` get an `import` keyword token when parsing `import.meta`. + +Fix a bug where `.loc.start` could be undefined for `new.target` `meta` nodes. + +## 8.11.2 (2023-10-27) + +### Bug fixes + +Fix a bug that caused regular expressions after colon tokens to not be properly tokenized in some circumstances. + +## 8.11.1 (2023-10-26) + +### Bug fixes + +Fix a regression where `onToken` would receive 'name' tokens for 'new' keyword tokens. + +## 8.11.0 (2023-10-26) + +### Bug fixes + +Fix an issue where tokenizing (without parsing) an object literal with a property named `class` or `function` could, in some circumstance, put the tokenizer into an invalid state. + +Fix an issue where a slash after a call to a propery named the same as some keywords would be tokenized as a regular expression. + +### New features + +Upgrade to Unicode 15.1. + +Use a set of new, much more precise, TypeScript types. + +## 8.10.0 (2023-07-05) + +### New features + +Add a `checkPrivateFields` option that disables strict checking of private property use. + +## 8.9.0 (2023-06-16) + +### Bug fixes + +Forbid dynamic import after `new`, even when part of a member expression. + +### New features + +Add Unicode properties for ES2023. + +Add support for the `v` flag to regular expressions. + +## 8.8.2 (2023-01-23) + +### Bug fixes + +Fix a bug that caused `allowHashBang` to be set to false when not provided, even with `ecmaVersion >= 14`. + +Fix an exception when passing no option object to `parse` or `new Parser`. + +Fix incorrect parse error on `if (0) let\n[astral identifier char]`. + +## 8.8.1 (2022-10-24) + +### Bug fixes + +Make type for `Comment` compatible with estree types. + +## 8.8.0 (2022-07-21) + +### Bug fixes + +Allow parentheses around spread args in destructuring object assignment. + +Fix an issue where the tree contained `directive` properties in when parsing with a language version that doesn't support them. + +### New features + +Support hashbang comments by default in ECMAScript 2023 and later. + +## 8.7.1 (2021-04-26) + +### Bug fixes + +Stop handling `"use strict"` directives in ECMAScript versions before 5. + +Fix an issue where duplicate quoted export names in `export *` syntax were incorrectly checked. + +Add missing type for `tokTypes`. + +## 8.7.0 (2021-12-27) + +### New features + +Support quoted export names. + +Upgrade to Unicode 14. + +Add support for Unicode 13 properties in regular expressions. + +### Bug fixes + +Use a loop to find line breaks, because the existing regexp search would overrun the end of the searched range and waste a lot of time in minified code. + +## 8.6.0 (2021-11-18) + +### Bug fixes + +Fix a bug where an object literal with multiple `__proto__` properties would incorrectly be accepted if a later property value held an assigment. + +### New features + +Support class private fields with the `in` operator. + +## 8.5.0 (2021-09-06) + +### Bug fixes + +Improve context-dependent tokenization in a number of corner cases. + +Fix location tracking after a 0x2028 or 0x2029 character in a string literal (which before did not increase the line number). + +Fix an issue where arrow function bodies in for loop context would inappropriately consume `in` operators. + +Fix wrong end locations stored on SequenceExpression nodes. + +Implement restriction that `for`/`of` loop LHS can't start with `let`. + +### New features + +Add support for ES2022 class static blocks. + +Allow multiple input files to be passed to the CLI tool. + +## 8.4.1 (2021-06-24) + +### Bug fixes + +Fix a bug where `allowAwaitOutsideFunction` would allow `await` in class field initializers, and setting `ecmaVersion` to 13 or higher would allow top-level await in non-module sources. + +## 8.4.0 (2021-06-11) + +### New features + +A new option, `allowSuperOutsideMethod`, can be used to suppress the error when `super` is used in the wrong context. + +## 8.3.0 (2021-05-31) + +### New features + +Default `allowAwaitOutsideFunction` to true for ECMAScript 2022 an higher. + +Add support for the `d` ([indices](https://github.com/tc39/proposal-regexp-match-indices)) regexp flag. + +## 8.2.4 (2021-05-04) + +### Bug fixes + +Fix spec conformity in corner case 'for await (async of ...)'. + +## 8.2.3 (2021-05-04) + +### Bug fixes + +Fix an issue where the library couldn't parse 'for (async of ...)'. + +Fix a bug in UTF-16 decoding that would read characters incorrectly in some circumstances. + +## 8.2.2 (2021-04-29) + +### Bug fixes + +Fix a bug where a class field initialized to an async arrow function wouldn't allow await inside it. Same issue existed for generator arrow functions with yield. + +## 8.2.1 (2021-04-24) + +### Bug fixes + +Fix a regression introduced in 8.2.0 where static or async class methods with keyword names fail to parse. + +## 8.2.0 (2021-04-24) + +### New features + +Add support for ES2022 class fields and private methods. + +## 8.1.1 (2021-04-12) + +### Various + +Stop shipping source maps in the NPM package. + +## 8.1.0 (2021-03-09) + +### Bug fixes + +Fix a spurious error in nested destructuring arrays. + +### New features + +Expose `allowAwaitOutsideFunction` in CLI interface. + +Make `allowImportExportAnywhere` also apply to `import.meta`. + +## 8.0.5 (2021-01-25) + +### Bug fixes + +Adjust package.json to work with Node 12.16.0 and 13.0-13.6. + +## 8.0.4 (2020-10-05) + +### Bug fixes + +Make `await x ** y` an error, following the spec. + +Fix potentially exponential regular expression. + +## 8.0.3 (2020-10-02) + +### Bug fixes + +Fix a wasteful loop during `Parser` creation when setting `ecmaVersion` to `"latest"`. + +## 8.0.2 (2020-09-30) + +### Bug fixes + +Make the TypeScript types reflect the current allowed values for `ecmaVersion`. + +Fix another regexp/division tokenizer issue. + +## 8.0.1 (2020-08-12) + +### Bug fixes + +Provide the correct value in the `version` export. + +## 8.0.0 (2020-08-12) + +### Bug fixes + +Disallow expressions like `(a = b) = c`. + +Make non-octal escape sequences a syntax error in strict mode. + +### New features + +The package can now be loaded directly as an ECMAScript module in node 13+. + +Update to the set of Unicode properties from ES2021. + +### Breaking changes + +The `ecmaVersion` option is now required. For the moment, omitting it will still work with a warning, but that will change in a future release. + +Some changes to method signatures that may be used by plugins. + +## 7.4.0 (2020-08-03) + +### New features + +Add support for logical assignment operators. + +Add support for numeric separators. + +## 7.3.1 (2020-06-11) + +### Bug fixes + +Make the string in the `version` export match the actual library version. + +## 7.3.0 (2020-06-11) + +### Bug fixes + +Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail. + +### New features + +Add support for optional chaining (`?.`). + +## 7.2.0 (2020-05-09) + +### Bug fixes + +Fix precedence issue in parsing of async arrow functions. + +### New features + +Add support for nullish coalescing. + +Add support for `import.meta`. + +Support `export * as ...` syntax. + +Upgrade to Unicode 13. + +## 6.4.1 (2020-03-09) + +### Bug fixes + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.1 (2020-03-01) + +### Bug fixes + +Treat `\8` and `\9` as invalid escapes in template strings. + +Allow unicode escapes in property names that are keywords. + +Don't error on an exponential operator expression as argument to `await`. + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.0 (2019-09-24) + +### Bug fixes + +Disallow trailing object literal commas when ecmaVersion is less than 5. + +### New features + +Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on. + +## 7.0.0 (2019-08-13) + +### Breaking changes + +Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression). + +Makes 10 (ES2019) the default value for the `ecmaVersion` option. + +## 6.3.0 (2019-08-12) + +### New features + +`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard. + +## 6.2.1 (2019-07-21) + +### Bug fixes + +Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such. + +Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances. + +## 6.2.0 (2019-07-04) + +### Bug fixes + +Improve valid assignment checking in `for`/`in` and `for`/`of` loops. + +Disallow binding `let` in patterns. + +### New features + +Support bigint syntax with `ecmaVersion` >= 11. + +Support dynamic `import` syntax with `ecmaVersion` >= 11. + +Upgrade to Unicode version 12. + +## 6.1.1 (2019-02-27) + +### Bug fixes + +Fix bug that caused parsing default exports of with names to fail. + +## 6.1.0 (2019-02-08) + +### Bug fixes + +Fix scope checking when redefining a `var` as a lexical binding. + +### New features + +Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins. + +## 6.0.7 (2019-02-04) + +### Bug fixes + +Check that exported bindings are defined. + +Don't treat `\u180e` as a whitespace character. + +Check for duplicate parameter names in methods. + +Don't allow shorthand properties when they are generators or async methods. + +Forbid binding `await` in async arrow function's parameter list. + +## 6.0.6 (2019-01-30) + +### Bug fixes + +The content of class declarations and expressions is now always parsed in strict mode. + +Don't allow `let` or `const` to bind the variable name `let`. + +Treat class declarations as lexical. + +Don't allow a generator function declaration as the sole body of an `if` or `else`. + +Ignore `"use strict"` when after an empty statement. + +Allow string line continuations with special line terminator characters. + +Treat `for` bodies as part of the `for` scope when checking for conflicting bindings. + +Fix bug with parsing `yield` in a `for` loop initializer. + +Implement special cases around scope checking for functions. + +## 6.0.5 (2019-01-02) + +### Bug fixes + +Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type. + +Don't treat `let` as a keyword when the next token is `{` on the next line. + +Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on. + +## 6.0.4 (2018-11-05) + +### Bug fixes + +Further improvements to tokenizing regular expressions in corner cases. + +## 6.0.3 (2018-11-04) + +### Bug fixes + +Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression. + +Remove stray symlink in the package tarball. + +## 6.0.2 (2018-09-26) + +### Bug fixes + +Fix bug where default expressions could fail to parse inside an object destructuring assignment expression. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix wrong value in `version` export. + +## 6.0.0 (2018-09-14) + +### Bug fixes + +Better handle variable-redefinition checks for catch bindings and functions directly under if statements. + +Forbid `new.target` in top-level arrow functions. + +Fix issue with parsing a regexp after `yield` in some contexts. + +### New features + +The package now comes with TypeScript definitions. + +### Breaking changes + +The default value of the `ecmaVersion` option is now 9 (2018). + +Plugins work differently, and will have to be rewritten to work with this version. + +The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`). + +## 5.7.3 (2018-09-10) + +### Bug fixes + +Fix failure to tokenize regexps after expressions like `x.of`. + +Better error message for unterminated template literals. + +## 5.7.2 (2018-08-24) + +### Bug fixes + +Properly handle `allowAwaitOutsideFunction` in for statements. + +Treat function declarations at the top level of modules like let bindings. + +Don't allow async function declarations as the only statement under a label. + +## 5.7.0 (2018-06-15) + +### New features + +Upgraded to Unicode 11. + +## 5.6.0 (2018-05-31) + +### New features + +Allow U+2028 and U+2029 in string when ECMAVersion >= 10. + +Allow binding-less catch statements when ECMAVersion >= 10. + +Add `allowAwaitOutsideFunction` option for parsing top-level `await`. + +## 5.5.3 (2018-03-08) + +### Bug fixes + +A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps. + +## 5.5.2 (2018-03-08) + +### Bug fixes + +A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix misleading error message for octal escapes in template strings. + +## 5.5.0 (2018-02-27) + +### New features + +The identifier character categorization is now based on Unicode version 10. + +Acorn will now validate the content of regular expressions, including new ES9 features. + +## 5.4.0 (2018-02-01) + +### Bug fixes + +Disallow duplicate or escaped flags on regular expressions. + +Disallow octal escapes in strings in strict mode. + +### New features + +Add support for async iteration. + +Add support for object spread and rest. + +## 5.3.0 (2017-12-28) + +### Bug fixes + +Fix parsing of floating point literals with leading zeroes in loose mode. + +Allow duplicate property names in object patterns. + +Don't allow static class methods named `prototype`. + +Disallow async functions directly under `if` or `else`. + +Parse right-hand-side of `for`/`of` as an assignment expression. + +Stricter parsing of `for`/`in`. + +Don't allow unicode escapes in contextual keywords. + +### New features + +Parsing class members was factored into smaller methods to allow plugins to hook into it. + +## 5.2.1 (2017-10-30) + +### Bug fixes + +Fix a token context corruption bug. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +Fix token context tracking for `class` and `function` in property-name position. + +Make sure `%*` isn't parsed as a valid operator. + +Allow shorthand properties `get` and `set` to be followed by default values. + +Disallow `super` when not in callee or object position. + +### New features + +Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements. + +## 5.1.2 (2017-09-04) + +### Bug fixes + +Disable parsing of legacy HTML-style comments in modules. + +Fix parsing of async methods whose names are keywords. + +## 5.1.1 (2017-07-06) + +### Bug fixes + +Fix problem with disambiguating regexp and division after a class. + +## 5.1.0 (2017-07-05) + +### Bug fixes + +Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`. + +Parse zero-prefixed numbers with non-octal digits as decimal. + +Allow object/array patterns in rest parameters. + +Don't error when `yield` is used as a property name. + +Allow `async` as a shorthand object property. + +### New features + +Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9. + +## 5.0.3 (2017-04-01) + +### Bug fixes + +Fix spurious duplicate variable definition errors for named functions. + +## 5.0.2 (2017-03-30) + +### Bug fixes + +A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error. + +## 5.0.0 (2017-03-28) + +### Bug fixes + +Raise an error for duplicated lexical bindings. + +Fix spurious error when an assignement expression occurred after a spread expression. + +Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions. + +Allow labels in front or `var` declarations, even in strict mode. + +### Breaking changes + +Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`. + +## 4.0.11 (2017-02-07) + +### Bug fixes + +Allow all forms of member expressions to be parenthesized as lvalue. + +## 4.0.10 (2017-02-07) + +### Bug fixes + +Don't expect semicolons after default-exported functions or classes, even when they are expressions. + +Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode. + +## 4.0.9 (2017-02-06) + +### Bug fixes + +Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again. + +## 4.0.8 (2017-02-03) + +### Bug fixes + +Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet. + +## 4.0.7 (2017-02-02) + +### Bug fixes + +Accept invalidly rejected code like `(x).y = 2` again. + +Don't raise an error when a function _inside_ strict code has a non-simple parameter list. + +## 4.0.6 (2017-02-02) + +### Bug fixes + +Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check. + +## 4.0.5 (2017-02-02) + +### Bug fixes + +Disallow parenthesized pattern expressions. + +Allow keywords as export names. + +Don't allow the `async` keyword to be parenthesized. + +Properly raise an error when a keyword contains a character escape. + +Allow `"use strict"` to appear after other string literal expressions. + +Disallow labeled declarations. + +## 4.0.4 (2016-12-19) + +### Bug fixes + +Fix crash when `export` was followed by a keyword that can't be +exported. + +## 4.0.3 (2016-08-16) + +### Bug fixes + +Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode. + +Properly parse properties named `async` in ES2017 mode. + +Fix bug where reserved words were broken in ES2017 mode. + +## 4.0.2 (2016-08-11) + +### Bug fixes + +Don't ignore period or 'e' characters after octal numbers. + +Fix broken parsing for call expressions in default parameter values of arrow functions. + +## 4.0.1 (2016-08-08) + +### Bug fixes + +Fix false positives in duplicated export name errors. + +## 4.0.0 (2016-08-07) + +### Breaking changes + +The default `ecmaVersion` option value is now 7. + +A number of internal method signatures changed, so plugins might need to be updated. + +### Bug fixes + +The parser now raises errors on duplicated export names. + +`arguments` and `eval` can now be used in shorthand properties. + +Duplicate parameter names in non-simple argument lists now always produce an error. + +### New features + +The `ecmaVersion` option now also accepts year-style version numbers +(2015, etc). + +Support for `async`/`await` syntax when `ecmaVersion` is >= 8. + +Support for trailing commas in call expressions when `ecmaVersion` is >= 8. + +## 3.3.0 (2016-07-25) + +### Bug fixes + +Fix bug in tokenizing of regexp operator after a function declaration. + +Fix parser crash when parsing an array pattern with a hole. + +### New features + +Implement check against complex argument lists in functions that enable strict mode in ES7. + +## 3.2.0 (2016-06-07) + +### Bug fixes + +Improve handling of lack of unicode regexp support in host +environment. + +Properly reject shorthand properties whose name is a keyword. + +### New features + +Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object. + +## 3.1.0 (2016-04-18) + +### Bug fixes + +Properly tokenize the division operator directly after a function expression. + +Allow trailing comma in destructuring arrays. + +## 3.0.4 (2016-02-25) + +### Fixes + +Allow update expressions as left-hand-side of the ES7 exponential operator. + +## 3.0.2 (2016-02-10) + +### Fixes + +Fix bug that accidentally made `undefined` a reserved word when parsing ES7. + +## 3.0.0 (2016-02-10) + +### Breaking changes + +The default value of the `ecmaVersion` option is now 6 (used to be 5). + +Support for comprehension syntax (which was dropped from the draft spec) has been removed. + +### Fixes + +`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code. + +A parenthesized class or function expression after `export default` is now parsed correctly. + +### New features + +When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`). + +The identifier character ranges are now based on Unicode 8.0.0. + +Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled. + +## 2.7.0 (2016-01-04) + +### Fixes + +Stop allowing rest parameters in setters. + +Disallow `y` rexexp flag in ES5. + +Disallow `\00` and `\000` escapes in strict mode. + +Raise an error when an import name is a reserved word. + +## 2.6.2 (2015-11-10) + +### Fixes + +Don't crash when no options object is passed. + +## 2.6.0 (2015-11-09) + +### Fixes + +Add `await` as a reserved word in module sources. + +Disallow `yield` in a parameter default value for a generator. + +Forbid using a comma after a rest pattern in an array destructuring. + +### New features + +Support parsing stdin in command-line tool. + +## 2.5.0 (2015-10-27) + +### Fixes + +Fix tokenizer support in the command-line tool. + +Stop allowing `new.target` outside of functions. + +Remove legacy `guard` and `guardedHandler` properties from try nodes. + +Stop allowing multiple `__proto__` properties on an object literal in strict mode. + +Don't allow rest parameters to be non-identifier patterns. + +Check for duplicate paramter names in arrow functions. diff --git a/node_modules/acorn/LICENSE b/node_modules/acorn/LICENSE new file mode 100644 index 00000000..9d71cc63 --- /dev/null +++ b/node_modules/acorn/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2012-2022 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/acorn/README.md b/node_modules/acorn/README.md new file mode 100644 index 00000000..f7ff9662 --- /dev/null +++ b/node_modules/acorn/README.md @@ -0,0 +1,282 @@ +# Acorn + +A tiny, fast JavaScript parser written in JavaScript. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` + +## Interface + +**parse**`(input, options)` is the main interface to the library. The +`input` parameter is a string, `options` must be an object setting +some of the options listed below. The return value will be an abstract +syntax tree object as specified by the [ESTree +spec](https://github.com/estree/estree). + +```javascript +let acorn = require("acorn"); +console.log(acorn.parse("1 + 1", {ecmaVersion: 2020})); +``` + +When encountering a syntax error, the parser will raise a +`SyntaxError` object with a meaningful message. The error object will +have a `pos` property that indicates the string offset at which the +error occurred, and a `loc` object that contains a `{line, column}` +object referring to that same position. + +Options are provided by in a second argument, which should be an +object containing any of these fields (only `ecmaVersion` is +required): + +- **ecmaVersion**: Indicates the ECMAScript version to parse. Can be a + number, either in year (`2022`) or plain version number (`6`) form, + or `"latest"` (the latest the library supports). This influences + support for strict mode, the set of reserved words, and support for + new syntax features. + + **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being + implemented by Acorn. Other proposed new features must be + implemented through plugins. + +- **sourceType**: Indicate the mode the code should be parsed in. Can be + either `"script"` or `"module"`. This influences global strict mode + and parsing of `import` and `export` declarations. + + **NOTE**: If set to `"module"`, then static `import` / `export` syntax + will be valid, even if `ecmaVersion` is less than 6. + +- **onInsertedSemicolon**: If given a callback, that callback will be + called whenever a missing semicolon is inserted by the parser. The + callback will be given the character offset of the point where the + semicolon is inserted as argument, and if `locations` is on, also a + `{line, column}` object representing this position. + +- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing + commas. + +- **allowReserved**: If `false`, using a reserved word will generate + an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher + versions. When given the value `"never"`, reserved words and + keywords can also not be used as property names (as in Internet + Explorer's old parser). + +- **allowReturnOutsideFunction**: By default, a return statement at + the top level raises an error. Set this to `true` to accept such + code. + +- **allowImportExportEverywhere**: By default, `import` and `export` + declarations can only appear at a program's top level. Setting this + option to `true` allows them anywhere where a statement is allowed, + and also allows `import.meta` expressions to appear in scripts + (when `sourceType` is not `"module"`). + +- **allowAwaitOutsideFunction**: If `false`, `await` expressions can + only appear inside `async` functions. Defaults to `true` in modules + for `ecmaVersion` 2022 and later, `false` for lower versions. + Setting this option to `true` allows to have top-level `await` + expressions. They are still not allowed in non-`async` functions, + though. + +- **allowSuperOutsideMethod**: By default, `super` outside a method + raises an error. Set this to `true` to accept such code. + +- **allowHashBang**: When this is enabled, if the code starts with the + characters `#!` (as in a shellscript), the first line will be + treated as a comment. Defaults to true when `ecmaVersion` >= 2023. + +- **checkPrivateFields**: By default, the parser will verify that + private properties are only used in places where they are valid and + have been declared. Set this to false to turn such checks off. + +- **locations**: When `true`, each node has a `loc` object attached + with `start` and `end` subobjects, each of which contains the + one-based line and zero-based column numbers in `{line, column}` + form. Default is `false`. + +- **onToken**: If a function is passed for this option, each found + token will be passed in same format as tokens returned from + `tokenizer().getToken()`. + + If array is passed, each found token is pushed to it. + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **onComment**: If a function is passed for this option, whenever a + comment is encountered the function will be called with the + following parameters: + + - `block`: `true` if the comment is a block comment, false if it + is a line comment. + - `text`: The content of the comment. + - `start`: Character offset of the start of the comment. + - `end`: Character offset of the end of the comment. + + When the `locations` options is on, the `{line, column}` locations + of the comment’s start and end are passed as two additional + parameters. + + If array is passed for this option, each found comment is pushed + to it as object in Esprima format: + + ```javascript + { + "type": "Line" | "Block", + "value": "comment text", + "start": Number, + "end": Number, + // If `locations` option is on: + "loc": { + "start": {line: Number, column: Number} + "end": {line: Number, column: Number} + }, + // If `ranges` option is on: + "range": [Number, Number] + } + ``` + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **ranges**: Nodes have their start and end characters offsets + recorded in `start` and `end` properties (directly on the node, + rather than the `loc` object, which holds line/column data. To also + add a + [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) + `range` property holding a `[start, end]` array with the same + numbers, set the `ranges` option to `true`. + +- **program**: It is possible to parse multiple files into a single + AST by passing the tree produced by parsing the first file as the + `program` option in subsequent parses. This will add the toplevel + forms of the parsed file to the "Program" (top) node of an existing + parse tree. + +- **sourceFile**: When the `locations` option is `true`, you can pass + this option to add a `source` attribute in every node’s `loc` + object. Note that the contents of this option are not examined or + processed in any way; you are free to use whatever format you + choose. + +- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property + will be added (regardless of the `location` option) directly to the + nodes, rather than the `loc` object. + +- **preserveParens**: If this option is `true`, parenthesized expressions + are represented by (non-standard) `ParenthesizedExpression` nodes + that have a single `expression` property containing the expression + inside parentheses. + +**parseExpressionAt**`(input, offset, options)` will parse a single +expression in a string, and return its AST. It will not complain if +there is more of the string left after the expression. + +**tokenizer**`(input, options)` returns an object with a `getToken` +method that can be called repeatedly to get the next token, a `{start, +end, type, value}` object (with added `loc` property when the +`locations` option is enabled and `range` property when the `ranges` +option is enabled). When the token's type is `tokTypes.eof`, you +should stop calling the method, since it will keep returning that same +token forever. + +Note that tokenizing JavaScript without parsing it is, in modern +versions of the language, not really possible due to the way syntax is +overloaded in ways that can only be disambiguated by the parse +context. This package applies a bunch of heuristics to try and do a +reasonable job, but you are advised to use `parse` with the `onToken` +option instead of this. + +In ES6 environment, returned result can be used as any other +protocol-compliant iterable: + +```javascript +for (let token of acorn.tokenizer(str)) { + // iterate over the tokens +} + +// transform code to array of tokens: +var tokens = [...acorn.tokenizer(str)]; +``` + +**tokTypes** holds an object mapping names to the token type objects +that end up in the `type` properties of tokens. + +**getLineInfo**`(input, offset)` can be used to get a `{line, +column}` object for a given program string and offset. + +### The `Parser` class + +Instances of the **`Parser`** class contain all the state and logic +that drives a parse. It has static methods `parse`, +`parseExpressionAt`, and `tokenizer` that match the top-level +functions by the same name. + +When extending the parser with plugins, you need to call these methods +on the extended version of the class. To extend a parser with plugins, +you can use its static `extend` method. + +```javascript +var acorn = require("acorn"); +var jsx = require("acorn-jsx"); +var JSXParser = acorn.Parser.extend(jsx()); +JSXParser.parse("foo()", {ecmaVersion: 2020}); +``` + +The `extend` method takes any number of plugin values, and returns a +new `Parser` class that includes the extra parser logic provided by +the plugins. + +## Command line interface + +The `bin/acorn` utility can be used to parse a file from the command +line. It accepts as arguments its input file and the following +options: + +- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version + to parse. Default is version 9. + +- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. + +- `--locations`: Attaches a "loc" object to each node with "start" and + "end" subobjects, each of which contains the one-based line and + zero-based column numbers in `{line, column}` form. + +- `--allow-hash-bang`: If the code starts with the characters #! (as + in a shellscript), the first line will be treated as a comment. + +- `--allow-await-outside-function`: Allows top-level `await` expressions. + See the `allowAwaitOutsideFunction` option for more information. + +- `--compact`: No whitespace is used in the AST output. + +- `--silent`: Do not output the AST, just return the exit status. + +- `--help`: Print the usage information and quit. + +The utility spits out the syntax tree as JSON data. + +## Existing plugins + + - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) diff --git a/node_modules/acorn/bin/acorn b/node_modules/acorn/bin/acorn new file mode 100755 index 00000000..3ef3c124 --- /dev/null +++ b/node_modules/acorn/bin/acorn @@ -0,0 +1,4 @@ +#!/usr/bin/env node +"use strict" + +require("../dist/bin.js") diff --git a/node_modules/acorn/dist/acorn.d.mts b/node_modules/acorn/dist/acorn.d.mts new file mode 100644 index 00000000..f2ec5243 --- /dev/null +++ b/node_modules/acorn/dist/acorn.d.mts @@ -0,0 +1,883 @@ +export interface Node { + start: number + end: number + type: string + range?: [number, number] + loc?: SourceLocation | null +} + +export interface SourceLocation { + source?: string | null + start: Position + end: Position +} + +export interface Position { + /** 1-based */ + line: number + /** 0-based */ + column: number +} + +export interface Identifier extends Node { + type: "Identifier" + name: string +} + +export interface Literal extends Node { + type: "Literal" + value?: string | boolean | null | number | RegExp | bigint + raw?: string + regex?: { + pattern: string + flags: string + } + bigint?: string +} + +export interface Program extends Node { + type: "Program" + body: Array + sourceType: "script" | "module" +} + +export interface Function extends Node { + id?: Identifier | null + params: Array + body: BlockStatement | Expression + generator: boolean + expression: boolean + async: boolean +} + +export interface ExpressionStatement extends Node { + type: "ExpressionStatement" + expression: Expression | Literal + directive?: string +} + +export interface BlockStatement extends Node { + type: "BlockStatement" + body: Array +} + +export interface EmptyStatement extends Node { + type: "EmptyStatement" +} + +export interface DebuggerStatement extends Node { + type: "DebuggerStatement" +} + +export interface WithStatement extends Node { + type: "WithStatement" + object: Expression + body: Statement +} + +export interface ReturnStatement extends Node { + type: "ReturnStatement" + argument?: Expression | null +} + +export interface LabeledStatement extends Node { + type: "LabeledStatement" + label: Identifier + body: Statement +} + +export interface BreakStatement extends Node { + type: "BreakStatement" + label?: Identifier | null +} + +export interface ContinueStatement extends Node { + type: "ContinueStatement" + label?: Identifier | null +} + +export interface IfStatement extends Node { + type: "IfStatement" + test: Expression + consequent: Statement + alternate?: Statement | null +} + +export interface SwitchStatement extends Node { + type: "SwitchStatement" + discriminant: Expression + cases: Array +} + +export interface SwitchCase extends Node { + type: "SwitchCase" + test?: Expression | null + consequent: Array +} + +export interface ThrowStatement extends Node { + type: "ThrowStatement" + argument: Expression +} + +export interface TryStatement extends Node { + type: "TryStatement" + block: BlockStatement + handler?: CatchClause | null + finalizer?: BlockStatement | null +} + +export interface CatchClause extends Node { + type: "CatchClause" + param?: Pattern | null + body: BlockStatement +} + +export interface WhileStatement extends Node { + type: "WhileStatement" + test: Expression + body: Statement +} + +export interface DoWhileStatement extends Node { + type: "DoWhileStatement" + body: Statement + test: Expression +} + +export interface ForStatement extends Node { + type: "ForStatement" + init?: VariableDeclaration | Expression | null + test?: Expression | null + update?: Expression | null + body: Statement +} + +export interface ForInStatement extends Node { + type: "ForInStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement +} + +export interface FunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: Identifier + body: BlockStatement +} + +export interface VariableDeclaration extends Node { + type: "VariableDeclaration" + declarations: Array + kind: "var" | "let" | "const" | "using" | "await using" +} + +export interface VariableDeclarator extends Node { + type: "VariableDeclarator" + id: Pattern + init?: Expression | null +} + +export interface ThisExpression extends Node { + type: "ThisExpression" +} + +export interface ArrayExpression extends Node { + type: "ArrayExpression" + elements: Array +} + +export interface ObjectExpression extends Node { + type: "ObjectExpression" + properties: Array +} + +export interface Property extends Node { + type: "Property" + key: Expression + value: Expression + kind: "init" | "get" | "set" + method: boolean + shorthand: boolean + computed: boolean +} + +export interface FunctionExpression extends Function { + type: "FunctionExpression" + body: BlockStatement +} + +export interface UnaryExpression extends Node { + type: "UnaryExpression" + operator: UnaryOperator + prefix: boolean + argument: Expression +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" + +export interface UpdateExpression extends Node { + type: "UpdateExpression" + operator: UpdateOperator + argument: Expression + prefix: boolean +} + +export type UpdateOperator = "++" | "--" + +export interface BinaryExpression extends Node { + type: "BinaryExpression" + operator: BinaryOperator + left: Expression | PrivateIdentifier + right: Expression +} + +export type BinaryOperator = "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" | "**" + +export interface AssignmentExpression extends Node { + type: "AssignmentExpression" + operator: AssignmentOperator + left: Pattern + right: Expression +} + +export type AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "**=" | "||=" | "&&=" | "??=" + +export interface LogicalExpression extends Node { + type: "LogicalExpression" + operator: LogicalOperator + left: Expression + right: Expression +} + +export type LogicalOperator = "||" | "&&" | "??" + +export interface MemberExpression extends Node { + type: "MemberExpression" + object: Expression | Super + property: Expression | PrivateIdentifier + computed: boolean + optional: boolean +} + +export interface ConditionalExpression extends Node { + type: "ConditionalExpression" + test: Expression + alternate: Expression + consequent: Expression +} + +export interface CallExpression extends Node { + type: "CallExpression" + callee: Expression | Super + arguments: Array + optional: boolean +} + +export interface NewExpression extends Node { + type: "NewExpression" + callee: Expression + arguments: Array +} + +export interface SequenceExpression extends Node { + type: "SequenceExpression" + expressions: Array +} + +export interface ForOfStatement extends Node { + type: "ForOfStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement + await: boolean +} + +export interface Super extends Node { + type: "Super" +} + +export interface SpreadElement extends Node { + type: "SpreadElement" + argument: Expression +} + +export interface ArrowFunctionExpression extends Function { + type: "ArrowFunctionExpression" +} + +export interface YieldExpression extends Node { + type: "YieldExpression" + argument?: Expression | null + delegate: boolean +} + +export interface TemplateLiteral extends Node { + type: "TemplateLiteral" + quasis: Array + expressions: Array +} + +export interface TaggedTemplateExpression extends Node { + type: "TaggedTemplateExpression" + tag: Expression + quasi: TemplateLiteral +} + +export interface TemplateElement extends Node { + type: "TemplateElement" + tail: boolean + value: { + cooked?: string | null + raw: string + } +} + +export interface AssignmentProperty extends Node { + type: "Property" + key: Expression + value: Pattern + kind: "init" + method: false + shorthand: boolean + computed: boolean +} + +export interface ObjectPattern extends Node { + type: "ObjectPattern" + properties: Array +} + +export interface ArrayPattern extends Node { + type: "ArrayPattern" + elements: Array +} + +export interface RestElement extends Node { + type: "RestElement" + argument: Pattern +} + +export interface AssignmentPattern extends Node { + type: "AssignmentPattern" + left: Pattern + right: Expression +} + +export interface Class extends Node { + id?: Identifier | null + superClass?: Expression | null + body: ClassBody +} + +export interface ClassBody extends Node { + type: "ClassBody" + body: Array +} + +export interface MethodDefinition extends Node { + type: "MethodDefinition" + key: Expression | PrivateIdentifier + value: FunctionExpression + kind: "constructor" | "method" | "get" | "set" + computed: boolean + static: boolean +} + +export interface ClassDeclaration extends Class { + type: "ClassDeclaration" + id: Identifier +} + +export interface ClassExpression extends Class { + type: "ClassExpression" +} + +export interface MetaProperty extends Node { + type: "MetaProperty" + meta: Identifier + property: Identifier +} + +export interface ImportDeclaration extends Node { + type: "ImportDeclaration" + specifiers: Array + source: Literal + attributes: Array +} + +export interface ImportSpecifier extends Node { + type: "ImportSpecifier" + imported: Identifier | Literal + local: Identifier +} + +export interface ImportDefaultSpecifier extends Node { + type: "ImportDefaultSpecifier" + local: Identifier +} + +export interface ImportNamespaceSpecifier extends Node { + type: "ImportNamespaceSpecifier" + local: Identifier +} + +export interface ImportAttribute extends Node { + type: "ImportAttribute" + key: Identifier | Literal + value: Literal +} + +export interface ExportNamedDeclaration extends Node { + type: "ExportNamedDeclaration" + declaration?: Declaration | null + specifiers: Array + source?: Literal | null + attributes: Array +} + +export interface ExportSpecifier extends Node { + type: "ExportSpecifier" + exported: Identifier | Literal + local: Identifier | Literal +} + +export interface AnonymousFunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: null + body: BlockStatement +} + +export interface AnonymousClassDeclaration extends Class { + type: "ClassDeclaration" + id: null +} + +export interface ExportDefaultDeclaration extends Node { + type: "ExportDefaultDeclaration" + declaration: AnonymousFunctionDeclaration | FunctionDeclaration | AnonymousClassDeclaration | ClassDeclaration | Expression +} + +export interface ExportAllDeclaration extends Node { + type: "ExportAllDeclaration" + source: Literal + exported?: Identifier | Literal | null + attributes: Array +} + +export interface AwaitExpression extends Node { + type: "AwaitExpression" + argument: Expression +} + +export interface ChainExpression extends Node { + type: "ChainExpression" + expression: MemberExpression | CallExpression +} + +export interface ImportExpression extends Node { + type: "ImportExpression" + source: Expression + options: Expression | null +} + +export interface ParenthesizedExpression extends Node { + type: "ParenthesizedExpression" + expression: Expression +} + +export interface PropertyDefinition extends Node { + type: "PropertyDefinition" + key: Expression | PrivateIdentifier + value?: Expression | null + computed: boolean + static: boolean +} + +export interface PrivateIdentifier extends Node { + type: "PrivateIdentifier" + name: string +} + +export interface StaticBlock extends Node { + type: "StaticBlock" + body: Array +} + +export type Statement = +| ExpressionStatement +| BlockStatement +| EmptyStatement +| DebuggerStatement +| WithStatement +| ReturnStatement +| LabeledStatement +| BreakStatement +| ContinueStatement +| IfStatement +| SwitchStatement +| ThrowStatement +| TryStatement +| WhileStatement +| DoWhileStatement +| ForStatement +| ForInStatement +| ForOfStatement +| Declaration + +export type Declaration = +| FunctionDeclaration +| VariableDeclaration +| ClassDeclaration + +export type Expression = +| Identifier +| Literal +| ThisExpression +| ArrayExpression +| ObjectExpression +| FunctionExpression +| UnaryExpression +| UpdateExpression +| BinaryExpression +| AssignmentExpression +| LogicalExpression +| MemberExpression +| ConditionalExpression +| CallExpression +| NewExpression +| SequenceExpression +| ArrowFunctionExpression +| YieldExpression +| TemplateLiteral +| TaggedTemplateExpression +| ClassExpression +| MetaProperty +| AwaitExpression +| ChainExpression +| ImportExpression +| ParenthesizedExpression + +export type Pattern = +| Identifier +| MemberExpression +| ObjectPattern +| ArrayPattern +| RestElement +| AssignmentPattern + +export type ModuleDeclaration = +| ImportDeclaration +| ExportNamedDeclaration +| ExportDefaultDeclaration +| ExportAllDeclaration + +/** + * This interface is only used for defining {@link AnyNode}. + * It exists so that it can be extended by plugins: + * + * @example + * ```typescript + * declare module 'acorn' { + * interface NodeTypes { + * pluginName: FirstNode | SecondNode | ThirdNode | ... | LastNode + * } + * } + * ``` + */ +interface NodeTypes { + core: Statement | Expression | Declaration | ModuleDeclaration | Literal | Program | SwitchCase | CatchClause | Property | Super | SpreadElement | TemplateElement | AssignmentProperty | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | ClassBody | MethodDefinition | MetaProperty | ImportAttribute | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier | AnonymousFunctionDeclaration | AnonymousClassDeclaration | PropertyDefinition | PrivateIdentifier | StaticBlock | VariableDeclarator +} + +export type AnyNode = NodeTypes[keyof NodeTypes] + +export function parse(input: string, options: Options): Program + +export function parseExpressionAt(input: string, pos: number, options: Options): Expression + +export function tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator +} + +export type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | 2026 | "latest" + +export interface Options { + /** + * `ecmaVersion` indicates the ECMAScript version to parse. Can be a + * number, either in year (`2022`) or plain version number (`6`) form, + * or `"latest"` (the latest the library supports). This influences + * support for strict mode, the set of reserved words, and support for + * new syntax features. + */ + ecmaVersion: ecmaVersion + + /** + * `sourceType` indicates the mode the code should be parsed in. + * Can be either `"script"` or `"module"`. This influences global + * strict mode and parsing of `import` and `export` declarations. + */ + sourceType?: "script" | "module" + + /** + * a callback that will be called when a semicolon is automatically inserted. + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if {@link locations} is enabled + */ + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * similar to `onInsertedSemicolon`, but for trailing commas + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if `locations` is enabled + */ + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * By default, reserved words are only enforced if ecmaVersion >= 5. + * Set `allowReserved` to a boolean value to explicitly turn this on + * an off. When this option has the value "never", reserved words + * and keywords can also not be used as property names. + */ + allowReserved?: boolean | "never" + + /** + * When enabled, a return at the top level is not considered an error. + */ + allowReturnOutsideFunction?: boolean + + /** + * When enabled, import/export statements are not constrained to + * appearing at the top of the program, and an import.meta expression + * in a script isn't considered an error. + */ + allowImportExportEverywhere?: boolean + + /** + * By default, `await` identifiers are allowed to appear at the top-level scope only if {@link ecmaVersion} >= 2022. + * When enabled, await identifiers are allowed to appear at the top-level scope, + * but they are still not allowed in non-async functions. + */ + allowAwaitOutsideFunction?: boolean + + /** + * When enabled, super identifiers are not constrained to + * appearing in methods and do not raise an error when they appear elsewhere. + */ + allowSuperOutsideMethod?: boolean + + /** + * When enabled, hashbang directive in the beginning of file is + * allowed and treated as a line comment. Enabled by default when + * {@link ecmaVersion} >= 2023. + */ + allowHashBang?: boolean + + /** + * By default, the parser will verify that private properties are + * only used in places where they are valid and have been declared. + * Set this to false to turn such checks off. + */ + checkPrivateFields?: boolean + + /** + * When `locations` is on, `loc` properties holding objects with + * `start` and `end` properties as {@link Position} objects will be attached to the + * nodes. + */ + locations?: boolean + + /** + * a callback that will cause Acorn to call that export function with object in the same + * format as tokens returned from `tokenizer().getToken()`. Note + * that you are not allowed to call the parser from the + * callback—that will corrupt its internal state. + */ + onToken?: ((token: Token) => void) | Token[] + + + /** + * This takes a export function or an array. + * + * When a export function is passed, Acorn will call that export function with `(block, text, start, + * end)` parameters whenever a comment is skipped. `block` is a + * boolean indicating whether this is a block (`/* *\/`) comment, + * `text` is the content of the comment, and `start` and `end` are + * character offsets that denote the start and end of the comment. + * When the {@link locations} option is on, two more parameters are + * passed, the full locations of {@link Position} export type of the start and + * end of the comments. + * + * When a array is passed, each found comment of {@link Comment} export type is pushed to the array. + * + * Note that you are not allowed to call the + * parser from the callback—that will corrupt its internal state. + */ + onComment?: (( + isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, + endLoc?: Position + ) => void) | Comment[] + + /** + * Nodes have their start and end characters offsets recorded in + * `start` and `end` properties (directly on the node, rather than + * the `loc` object, which holds line/column data. To also add a + * [semi-standardized][range] `range` property holding a `[start, + * end]` array with the same numbers, set the `ranges` option to + * `true`. + */ + ranges?: boolean + + /** + * It is possible to parse multiple files into a single AST by + * passing the tree produced by parsing the first file as + * `program` option in subsequent parses. This will add the + * toplevel forms of the parsed file to the `Program` (top) node + * of an existing parse tree. + */ + program?: Node + + /** + * When {@link locations} is on, you can pass this to record the source + * file in every node's `loc` object. + */ + sourceFile?: string + + /** + * This value, if given, is stored in every node, whether {@link locations} is on or off. + */ + directSourceFile?: string + + /** + * When enabled, parenthesized expressions are represented by + * (non-standard) ParenthesizedExpression nodes + */ + preserveParens?: boolean +} + +export class Parser { + options: Options + input: string + + protected constructor(options: Options, input: string, startPos?: number) + parse(): Program + + static parse(input: string, options: Options): Program + static parseExpressionAt(input: string, pos: number, options: Options): Expression + static tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser +} + +export const defaultOptions: Options + +export function getLineInfo(input: string, offset: number): Position + +export class TokenType { + label: string + keyword: string | undefined +} + +export const tokTypes: { + num: TokenType + regexp: TokenType + string: TokenType + name: TokenType + privateId: TokenType + eof: TokenType + + bracketL: TokenType + bracketR: TokenType + braceL: TokenType + braceR: TokenType + parenL: TokenType + parenR: TokenType + comma: TokenType + semi: TokenType + colon: TokenType + dot: TokenType + question: TokenType + questionDot: TokenType + arrow: TokenType + template: TokenType + invalidTemplate: TokenType + ellipsis: TokenType + backQuote: TokenType + dollarBraceL: TokenType + + eq: TokenType + assign: TokenType + incDec: TokenType + prefix: TokenType + logicalOR: TokenType + logicalAND: TokenType + bitwiseOR: TokenType + bitwiseXOR: TokenType + bitwiseAND: TokenType + equality: TokenType + relational: TokenType + bitShift: TokenType + plusMin: TokenType + modulo: TokenType + star: TokenType + slash: TokenType + starstar: TokenType + coalesce: TokenType + + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType +} + +export interface Comment { + type: "Line" | "Block" + value: string + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export class Token { + type: TokenType + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export const version: string diff --git a/node_modules/acorn/dist/acorn.d.ts b/node_modules/acorn/dist/acorn.d.ts new file mode 100644 index 00000000..f2ec5243 --- /dev/null +++ b/node_modules/acorn/dist/acorn.d.ts @@ -0,0 +1,883 @@ +export interface Node { + start: number + end: number + type: string + range?: [number, number] + loc?: SourceLocation | null +} + +export interface SourceLocation { + source?: string | null + start: Position + end: Position +} + +export interface Position { + /** 1-based */ + line: number + /** 0-based */ + column: number +} + +export interface Identifier extends Node { + type: "Identifier" + name: string +} + +export interface Literal extends Node { + type: "Literal" + value?: string | boolean | null | number | RegExp | bigint + raw?: string + regex?: { + pattern: string + flags: string + } + bigint?: string +} + +export interface Program extends Node { + type: "Program" + body: Array + sourceType: "script" | "module" +} + +export interface Function extends Node { + id?: Identifier | null + params: Array + body: BlockStatement | Expression + generator: boolean + expression: boolean + async: boolean +} + +export interface ExpressionStatement extends Node { + type: "ExpressionStatement" + expression: Expression | Literal + directive?: string +} + +export interface BlockStatement extends Node { + type: "BlockStatement" + body: Array +} + +export interface EmptyStatement extends Node { + type: "EmptyStatement" +} + +export interface DebuggerStatement extends Node { + type: "DebuggerStatement" +} + +export interface WithStatement extends Node { + type: "WithStatement" + object: Expression + body: Statement +} + +export interface ReturnStatement extends Node { + type: "ReturnStatement" + argument?: Expression | null +} + +export interface LabeledStatement extends Node { + type: "LabeledStatement" + label: Identifier + body: Statement +} + +export interface BreakStatement extends Node { + type: "BreakStatement" + label?: Identifier | null +} + +export interface ContinueStatement extends Node { + type: "ContinueStatement" + label?: Identifier | null +} + +export interface IfStatement extends Node { + type: "IfStatement" + test: Expression + consequent: Statement + alternate?: Statement | null +} + +export interface SwitchStatement extends Node { + type: "SwitchStatement" + discriminant: Expression + cases: Array +} + +export interface SwitchCase extends Node { + type: "SwitchCase" + test?: Expression | null + consequent: Array +} + +export interface ThrowStatement extends Node { + type: "ThrowStatement" + argument: Expression +} + +export interface TryStatement extends Node { + type: "TryStatement" + block: BlockStatement + handler?: CatchClause | null + finalizer?: BlockStatement | null +} + +export interface CatchClause extends Node { + type: "CatchClause" + param?: Pattern | null + body: BlockStatement +} + +export interface WhileStatement extends Node { + type: "WhileStatement" + test: Expression + body: Statement +} + +export interface DoWhileStatement extends Node { + type: "DoWhileStatement" + body: Statement + test: Expression +} + +export interface ForStatement extends Node { + type: "ForStatement" + init?: VariableDeclaration | Expression | null + test?: Expression | null + update?: Expression | null + body: Statement +} + +export interface ForInStatement extends Node { + type: "ForInStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement +} + +export interface FunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: Identifier + body: BlockStatement +} + +export interface VariableDeclaration extends Node { + type: "VariableDeclaration" + declarations: Array + kind: "var" | "let" | "const" | "using" | "await using" +} + +export interface VariableDeclarator extends Node { + type: "VariableDeclarator" + id: Pattern + init?: Expression | null +} + +export interface ThisExpression extends Node { + type: "ThisExpression" +} + +export interface ArrayExpression extends Node { + type: "ArrayExpression" + elements: Array +} + +export interface ObjectExpression extends Node { + type: "ObjectExpression" + properties: Array +} + +export interface Property extends Node { + type: "Property" + key: Expression + value: Expression + kind: "init" | "get" | "set" + method: boolean + shorthand: boolean + computed: boolean +} + +export interface FunctionExpression extends Function { + type: "FunctionExpression" + body: BlockStatement +} + +export interface UnaryExpression extends Node { + type: "UnaryExpression" + operator: UnaryOperator + prefix: boolean + argument: Expression +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" + +export interface UpdateExpression extends Node { + type: "UpdateExpression" + operator: UpdateOperator + argument: Expression + prefix: boolean +} + +export type UpdateOperator = "++" | "--" + +export interface BinaryExpression extends Node { + type: "BinaryExpression" + operator: BinaryOperator + left: Expression | PrivateIdentifier + right: Expression +} + +export type BinaryOperator = "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" | "**" + +export interface AssignmentExpression extends Node { + type: "AssignmentExpression" + operator: AssignmentOperator + left: Pattern + right: Expression +} + +export type AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "**=" | "||=" | "&&=" | "??=" + +export interface LogicalExpression extends Node { + type: "LogicalExpression" + operator: LogicalOperator + left: Expression + right: Expression +} + +export type LogicalOperator = "||" | "&&" | "??" + +export interface MemberExpression extends Node { + type: "MemberExpression" + object: Expression | Super + property: Expression | PrivateIdentifier + computed: boolean + optional: boolean +} + +export interface ConditionalExpression extends Node { + type: "ConditionalExpression" + test: Expression + alternate: Expression + consequent: Expression +} + +export interface CallExpression extends Node { + type: "CallExpression" + callee: Expression | Super + arguments: Array + optional: boolean +} + +export interface NewExpression extends Node { + type: "NewExpression" + callee: Expression + arguments: Array +} + +export interface SequenceExpression extends Node { + type: "SequenceExpression" + expressions: Array +} + +export interface ForOfStatement extends Node { + type: "ForOfStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement + await: boolean +} + +export interface Super extends Node { + type: "Super" +} + +export interface SpreadElement extends Node { + type: "SpreadElement" + argument: Expression +} + +export interface ArrowFunctionExpression extends Function { + type: "ArrowFunctionExpression" +} + +export interface YieldExpression extends Node { + type: "YieldExpression" + argument?: Expression | null + delegate: boolean +} + +export interface TemplateLiteral extends Node { + type: "TemplateLiteral" + quasis: Array + expressions: Array +} + +export interface TaggedTemplateExpression extends Node { + type: "TaggedTemplateExpression" + tag: Expression + quasi: TemplateLiteral +} + +export interface TemplateElement extends Node { + type: "TemplateElement" + tail: boolean + value: { + cooked?: string | null + raw: string + } +} + +export interface AssignmentProperty extends Node { + type: "Property" + key: Expression + value: Pattern + kind: "init" + method: false + shorthand: boolean + computed: boolean +} + +export interface ObjectPattern extends Node { + type: "ObjectPattern" + properties: Array +} + +export interface ArrayPattern extends Node { + type: "ArrayPattern" + elements: Array +} + +export interface RestElement extends Node { + type: "RestElement" + argument: Pattern +} + +export interface AssignmentPattern extends Node { + type: "AssignmentPattern" + left: Pattern + right: Expression +} + +export interface Class extends Node { + id?: Identifier | null + superClass?: Expression | null + body: ClassBody +} + +export interface ClassBody extends Node { + type: "ClassBody" + body: Array +} + +export interface MethodDefinition extends Node { + type: "MethodDefinition" + key: Expression | PrivateIdentifier + value: FunctionExpression + kind: "constructor" | "method" | "get" | "set" + computed: boolean + static: boolean +} + +export interface ClassDeclaration extends Class { + type: "ClassDeclaration" + id: Identifier +} + +export interface ClassExpression extends Class { + type: "ClassExpression" +} + +export interface MetaProperty extends Node { + type: "MetaProperty" + meta: Identifier + property: Identifier +} + +export interface ImportDeclaration extends Node { + type: "ImportDeclaration" + specifiers: Array + source: Literal + attributes: Array +} + +export interface ImportSpecifier extends Node { + type: "ImportSpecifier" + imported: Identifier | Literal + local: Identifier +} + +export interface ImportDefaultSpecifier extends Node { + type: "ImportDefaultSpecifier" + local: Identifier +} + +export interface ImportNamespaceSpecifier extends Node { + type: "ImportNamespaceSpecifier" + local: Identifier +} + +export interface ImportAttribute extends Node { + type: "ImportAttribute" + key: Identifier | Literal + value: Literal +} + +export interface ExportNamedDeclaration extends Node { + type: "ExportNamedDeclaration" + declaration?: Declaration | null + specifiers: Array + source?: Literal | null + attributes: Array +} + +export interface ExportSpecifier extends Node { + type: "ExportSpecifier" + exported: Identifier | Literal + local: Identifier | Literal +} + +export interface AnonymousFunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: null + body: BlockStatement +} + +export interface AnonymousClassDeclaration extends Class { + type: "ClassDeclaration" + id: null +} + +export interface ExportDefaultDeclaration extends Node { + type: "ExportDefaultDeclaration" + declaration: AnonymousFunctionDeclaration | FunctionDeclaration | AnonymousClassDeclaration | ClassDeclaration | Expression +} + +export interface ExportAllDeclaration extends Node { + type: "ExportAllDeclaration" + source: Literal + exported?: Identifier | Literal | null + attributes: Array +} + +export interface AwaitExpression extends Node { + type: "AwaitExpression" + argument: Expression +} + +export interface ChainExpression extends Node { + type: "ChainExpression" + expression: MemberExpression | CallExpression +} + +export interface ImportExpression extends Node { + type: "ImportExpression" + source: Expression + options: Expression | null +} + +export interface ParenthesizedExpression extends Node { + type: "ParenthesizedExpression" + expression: Expression +} + +export interface PropertyDefinition extends Node { + type: "PropertyDefinition" + key: Expression | PrivateIdentifier + value?: Expression | null + computed: boolean + static: boolean +} + +export interface PrivateIdentifier extends Node { + type: "PrivateIdentifier" + name: string +} + +export interface StaticBlock extends Node { + type: "StaticBlock" + body: Array +} + +export type Statement = +| ExpressionStatement +| BlockStatement +| EmptyStatement +| DebuggerStatement +| WithStatement +| ReturnStatement +| LabeledStatement +| BreakStatement +| ContinueStatement +| IfStatement +| SwitchStatement +| ThrowStatement +| TryStatement +| WhileStatement +| DoWhileStatement +| ForStatement +| ForInStatement +| ForOfStatement +| Declaration + +export type Declaration = +| FunctionDeclaration +| VariableDeclaration +| ClassDeclaration + +export type Expression = +| Identifier +| Literal +| ThisExpression +| ArrayExpression +| ObjectExpression +| FunctionExpression +| UnaryExpression +| UpdateExpression +| BinaryExpression +| AssignmentExpression +| LogicalExpression +| MemberExpression +| ConditionalExpression +| CallExpression +| NewExpression +| SequenceExpression +| ArrowFunctionExpression +| YieldExpression +| TemplateLiteral +| TaggedTemplateExpression +| ClassExpression +| MetaProperty +| AwaitExpression +| ChainExpression +| ImportExpression +| ParenthesizedExpression + +export type Pattern = +| Identifier +| MemberExpression +| ObjectPattern +| ArrayPattern +| RestElement +| AssignmentPattern + +export type ModuleDeclaration = +| ImportDeclaration +| ExportNamedDeclaration +| ExportDefaultDeclaration +| ExportAllDeclaration + +/** + * This interface is only used for defining {@link AnyNode}. + * It exists so that it can be extended by plugins: + * + * @example + * ```typescript + * declare module 'acorn' { + * interface NodeTypes { + * pluginName: FirstNode | SecondNode | ThirdNode | ... | LastNode + * } + * } + * ``` + */ +interface NodeTypes { + core: Statement | Expression | Declaration | ModuleDeclaration | Literal | Program | SwitchCase | CatchClause | Property | Super | SpreadElement | TemplateElement | AssignmentProperty | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | ClassBody | MethodDefinition | MetaProperty | ImportAttribute | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier | AnonymousFunctionDeclaration | AnonymousClassDeclaration | PropertyDefinition | PrivateIdentifier | StaticBlock | VariableDeclarator +} + +export type AnyNode = NodeTypes[keyof NodeTypes] + +export function parse(input: string, options: Options): Program + +export function parseExpressionAt(input: string, pos: number, options: Options): Expression + +export function tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator +} + +export type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | 2026 | "latest" + +export interface Options { + /** + * `ecmaVersion` indicates the ECMAScript version to parse. Can be a + * number, either in year (`2022`) or plain version number (`6`) form, + * or `"latest"` (the latest the library supports). This influences + * support for strict mode, the set of reserved words, and support for + * new syntax features. + */ + ecmaVersion: ecmaVersion + + /** + * `sourceType` indicates the mode the code should be parsed in. + * Can be either `"script"` or `"module"`. This influences global + * strict mode and parsing of `import` and `export` declarations. + */ + sourceType?: "script" | "module" + + /** + * a callback that will be called when a semicolon is automatically inserted. + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if {@link locations} is enabled + */ + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * similar to `onInsertedSemicolon`, but for trailing commas + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if `locations` is enabled + */ + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * By default, reserved words are only enforced if ecmaVersion >= 5. + * Set `allowReserved` to a boolean value to explicitly turn this on + * an off. When this option has the value "never", reserved words + * and keywords can also not be used as property names. + */ + allowReserved?: boolean | "never" + + /** + * When enabled, a return at the top level is not considered an error. + */ + allowReturnOutsideFunction?: boolean + + /** + * When enabled, import/export statements are not constrained to + * appearing at the top of the program, and an import.meta expression + * in a script isn't considered an error. + */ + allowImportExportEverywhere?: boolean + + /** + * By default, `await` identifiers are allowed to appear at the top-level scope only if {@link ecmaVersion} >= 2022. + * When enabled, await identifiers are allowed to appear at the top-level scope, + * but they are still not allowed in non-async functions. + */ + allowAwaitOutsideFunction?: boolean + + /** + * When enabled, super identifiers are not constrained to + * appearing in methods and do not raise an error when they appear elsewhere. + */ + allowSuperOutsideMethod?: boolean + + /** + * When enabled, hashbang directive in the beginning of file is + * allowed and treated as a line comment. Enabled by default when + * {@link ecmaVersion} >= 2023. + */ + allowHashBang?: boolean + + /** + * By default, the parser will verify that private properties are + * only used in places where they are valid and have been declared. + * Set this to false to turn such checks off. + */ + checkPrivateFields?: boolean + + /** + * When `locations` is on, `loc` properties holding objects with + * `start` and `end` properties as {@link Position} objects will be attached to the + * nodes. + */ + locations?: boolean + + /** + * a callback that will cause Acorn to call that export function with object in the same + * format as tokens returned from `tokenizer().getToken()`. Note + * that you are not allowed to call the parser from the + * callback—that will corrupt its internal state. + */ + onToken?: ((token: Token) => void) | Token[] + + + /** + * This takes a export function or an array. + * + * When a export function is passed, Acorn will call that export function with `(block, text, start, + * end)` parameters whenever a comment is skipped. `block` is a + * boolean indicating whether this is a block (`/* *\/`) comment, + * `text` is the content of the comment, and `start` and `end` are + * character offsets that denote the start and end of the comment. + * When the {@link locations} option is on, two more parameters are + * passed, the full locations of {@link Position} export type of the start and + * end of the comments. + * + * When a array is passed, each found comment of {@link Comment} export type is pushed to the array. + * + * Note that you are not allowed to call the + * parser from the callback—that will corrupt its internal state. + */ + onComment?: (( + isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, + endLoc?: Position + ) => void) | Comment[] + + /** + * Nodes have their start and end characters offsets recorded in + * `start` and `end` properties (directly on the node, rather than + * the `loc` object, which holds line/column data. To also add a + * [semi-standardized][range] `range` property holding a `[start, + * end]` array with the same numbers, set the `ranges` option to + * `true`. + */ + ranges?: boolean + + /** + * It is possible to parse multiple files into a single AST by + * passing the tree produced by parsing the first file as + * `program` option in subsequent parses. This will add the + * toplevel forms of the parsed file to the `Program` (top) node + * of an existing parse tree. + */ + program?: Node + + /** + * When {@link locations} is on, you can pass this to record the source + * file in every node's `loc` object. + */ + sourceFile?: string + + /** + * This value, if given, is stored in every node, whether {@link locations} is on or off. + */ + directSourceFile?: string + + /** + * When enabled, parenthesized expressions are represented by + * (non-standard) ParenthesizedExpression nodes + */ + preserveParens?: boolean +} + +export class Parser { + options: Options + input: string + + protected constructor(options: Options, input: string, startPos?: number) + parse(): Program + + static parse(input: string, options: Options): Program + static parseExpressionAt(input: string, pos: number, options: Options): Expression + static tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser +} + +export const defaultOptions: Options + +export function getLineInfo(input: string, offset: number): Position + +export class TokenType { + label: string + keyword: string | undefined +} + +export const tokTypes: { + num: TokenType + regexp: TokenType + string: TokenType + name: TokenType + privateId: TokenType + eof: TokenType + + bracketL: TokenType + bracketR: TokenType + braceL: TokenType + braceR: TokenType + parenL: TokenType + parenR: TokenType + comma: TokenType + semi: TokenType + colon: TokenType + dot: TokenType + question: TokenType + questionDot: TokenType + arrow: TokenType + template: TokenType + invalidTemplate: TokenType + ellipsis: TokenType + backQuote: TokenType + dollarBraceL: TokenType + + eq: TokenType + assign: TokenType + incDec: TokenType + prefix: TokenType + logicalOR: TokenType + logicalAND: TokenType + bitwiseOR: TokenType + bitwiseXOR: TokenType + bitwiseAND: TokenType + equality: TokenType + relational: TokenType + bitShift: TokenType + plusMin: TokenType + modulo: TokenType + star: TokenType + slash: TokenType + starstar: TokenType + coalesce: TokenType + + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType +} + +export interface Comment { + type: "Line" | "Block" + value: string + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export class Token { + type: TokenType + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export const version: string diff --git a/node_modules/acorn/dist/acorn.js b/node_modules/acorn/dist/acorn.js new file mode 100644 index 00000000..cb5628bf --- /dev/null +++ b/node_modules/acorn/dist/acorn.js @@ -0,0 +1,6262 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.acorn = {})); +})(this, (function (exports) { 'use strict'; + + // This file was generated. Do not modify manually! + var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + + // This file was generated. Do not modify manually! + var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + + // These are a run-length and offset encoded representation of the + // >0xffff code points that are a valid part of identifiers. The + // offset starts at 0x10000, and each pair of numbers represents an + // offset to the next range, and then a size of the range. + + // Reserved word lists for various dialects of the language + + var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" + }; + + // And the keywords + + var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + + var keywords$1 = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" + }; + + var keywordRelationalOperator = /^in(stanceof)?$/; + + // ## Character categories + + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + + // This has a complexity linear to the value of the code. The + // assumption is that looking up astral identifier characters is + // rare. + function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } + } + return false + } + + // Test whether a given character code starts an identifier. + + function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) + } + + // Test whether a given character is part of an identifier. + + function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) + } + + // ## Token types + + // The assignment of fine-grained, information-carrying type objects + // allows the tokenizer to store the information it has about a + // token in a way that is very cheap for the parser to look up. + + // All token type variables start with an underscore, to make them + // easy to recognize. + + // The `beforeExpr` property is used to disambiguate between regular + // expressions and divisions. It is set on all token types that can + // be followed by an expression (thus, a slash after them would be a + // regular expression). + // + // The `startsExpr` property is used to check if the token ends a + // `yield` expression. It is set on all token types that either can + // directly start an expression (like a quotation mark) or can + // continue an expression (like the body of a string). + // + // `isLoop` marks a keyword as starting a loop, which is important + // to know when parsing a label, in order to allow or disallow + // continue jumps to that label. + + var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; + }; + + function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) + } + var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; + + // Map keyword names to token types. + + var keywords = {}; + + // Succinct definitions of keyword token types + function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name; + return keywords[name] = new TokenType(name, options) + } + + var types$1 = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + coalesce: binop("??", 1), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) + }; + + // Matches a whole line break (where CRLF is considered a single + // line break). Used to count lines. + + var lineBreak = /\r\n?|\n|\u2028|\u2029/; + var lineBreakG = new RegExp(lineBreak.source, "g"); + + function isNewLine(code) { + return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 + } + + function nextLineBreak(code, from, end) { + if ( end === void 0 ) end = code.length; + + for (var i = from; i < end; i++) { + var next = code.charCodeAt(i); + if (isNewLine(next)) + { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } + } + return -1 + } + + var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + + var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + + var ref = Object.prototype; + var hasOwnProperty = ref.hasOwnProperty; + var toString = ref.toString; + + var hasOwn = Object.hasOwn || (function (obj, propName) { return ( + hasOwnProperty.call(obj, propName) + ); }); + + var isArray = Array.isArray || (function (obj) { return ( + toString.call(obj) === "[object Array]" + ); }); + + var regexpCache = Object.create(null); + + function wordsRegexp(words) { + return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")) + } + + function codePointToString(code) { + // UTF-16 Decoding + if (code <= 0xFFFF) { return String.fromCharCode(code) } + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) + } + + var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; + + // These are used when `options.locations` is on, for the + // `startLoc` and `endLoc` properties. + + var Position = function Position(line, col) { + this.line = line; + this.column = col; + }; + + Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) + }; + + var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } + }; + + // The `getLineInfo` function is mostly useful when the + // `locations` option is off (for performance reasons) and you + // want to find the line/column position for a given character + // offset. `input` should be the code string that the offset refers + // into. + + function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + var nextBreak = nextLineBreak(input, cur, offset); + if (nextBreak < 0) { return new Position(line, offset - cur) } + ++line; + cur = nextBreak; + } + } + + // A second argument must be given to configure the parser process. + // These options are recognized (only `ecmaVersion` is required): + + var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + // (the latest version the library supports). This influences + // support for strict mode, the set of reserved words, and support + // for new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called when + // a semicolon is automatically inserted. It will be passed the + // position of the inserted semicolon as an offset, and if + // `locations` is enabled, it is given the location as a `{line, + // column}` object as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file is + // allowed and treated as a line comment. Enabled by default when + // `ecmaVersion` >= 2023. + allowHashBang: false, + // By default, the parser will verify that private properties are + // only used in places where they are valid and have been declared. + // Set this to false to turn such checks off. + checkPrivateFields: true, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + // When this option has an array as value, objects representing the + // comments are pushed to it. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false + }; + + // Interpret and default an options object + + var warnedAboutEcmaVersion = false; + + function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } + + if (!opts || opts.allowHashBang == null) + { options.allowHashBang = options.ecmaVersion >= 14; } + + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } + + return options + } + + function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); + } + } + + // Each scope gets a bitset that may contain these flags + var + SCOPE_TOP = 1, + SCOPE_FUNCTION = 2, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128, + SCOPE_CLASS_STATIC_BLOCK = 256, + SCOPE_CLASS_FIELD_INIT = 512, + SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; + + function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + } + + // Used in checkLVal* and declareName to determine the type of a binding + var + BIND_NONE = 0, // Not a binding + BIND_VAR = 1, // Var-style binding + BIND_LEXICAL = 2, // Let- or const-style binding + BIND_FUNCTION = 3, // Function declaration + BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding + BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + + var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + + // Properties of the current token: + // Its type + this.type = types$1.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + // Labels in scope. + this.labels = []; + // Thus-far undefined exports. + this.undefinedExports = Object.create(null); + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } + + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + + // For RegExp validation + this.regexpState = null; + + // The stack of private names. + // Each element has two properties: 'declared' and 'used'. + // When it exited from the outermost class definition, all used private names must be declared. + this.privateNameStack = []; + }; + + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; + + Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) + }; + + prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; + + prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }; + + prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; + + prototypeAccessors.canAwait.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var ref = this.scopeStack[i]; + var flags = ref.flags; + if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT)) { return false } + if (flags & SCOPE_FUNCTION) { return (flags & SCOPE_ASYNC) > 0 } + } + return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction + }; + + prototypeAccessors.allowSuper.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + return (flags & SCOPE_SUPER) > 0 || this.options.allowSuperOutsideMethod + }; + + prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + + prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + + prototypeAccessors.allowNewDotTarget.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var ref = this.scopeStack[i]; + var flags = ref.flags; + if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT) || + ((flags & SCOPE_FUNCTION) && !(flags & SCOPE_ARROW))) { return true } + } + return false + }; + + prototypeAccessors.inClassStaticBlock.get = function () { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 + }; + + Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; + + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls + }; + + Parser.parse = function parse (input, options) { + return new this(options, input).parse() + }; + + Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() + }; + + Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) + }; + + Object.defineProperties( Parser.prototype, prototypeAccessors ); + + var pp$9 = Parser.prototype; + + // ## Parser utilities + + var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/; + pp$9.strictDirective = function(start) { + if (this.options.ecmaVersion < 5) { return false } + for (;;) { + // Try to find string literal. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || + (lineBreak.test(spaceAfter[0]) && + !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) + } + start += match[0].length; + + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } + } + }; + + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. + + pp$9.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } + }; + + // Tests whether parsed token is a contextual keyword. + + pp$9.isContextual = function(name) { + return this.type === types$1.name && this.value === name && !this.containsEsc + }; + + // Consumes contextual keyword if possible. + + pp$9.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true + }; + + // Asserts that following token is given contextual keyword. + + pp$9.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } + }; + + // Test whether a semicolon can be inserted at the current position. + + pp$9.canInsertSemicolon = function() { + return this.type === types$1.eof || + this.type === types$1.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + pp$9.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } + }; + + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. + + pp$9.semicolon = function() { + if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } + }; + + pp$9.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true + } + }; + + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. + + pp$9.expect = function(type) { + this.eat(type) || this.unexpected(); + }; + + // Raise an unexpected token error. + + pp$9.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); + }; + + var DestructuringErrors = function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; + }; + + pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } + }; + + pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } + }; + + pp$9.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } + }; + + pp$9.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" + }; + + var pp$8 = Parser.prototype; + + // ### Statement parsing + + // Parse a program. Initializes the parser, reads any number of + // statements, and wraps them in a Program node. Optionally takes a + // `program` argument. If present, the statements will be appended + // to its body instead of creating a new node. + + pp$8.parseTopLevel = function(node) { + var exports = Object.create(null); + if (!node.body) { node.body = []; } + while (this.type !== types$1.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); + } + if (this.inModule) + { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) + { + var name = list[i]; + + this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); + } } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program") + }; + + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + + pp$8.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + // For ambiguous cases, determine if a LexicalDeclaration (or only a + // Statement) is allowed here. If context is not empty then only a Statement + // is allowed. However, `let [` is an explicit negative lookahead for + // ExpressionStatement, so special-case it first. + if (nextCh === 91 || nextCh === 92) { return true } // '[', '\' + if (context) { return false } + + if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } + if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } + } + return false + }; + + // check 'async [no LineTerminator here] function' + // - 'async /*foo*/ function' is OK. + // - 'async /*\n*/ function' is invalid. + pp$8.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || + !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) + }; + + pp$8.isUsingKeyword = function(isAwaitUsing, isFor) { + if (this.options.ecmaVersion < 17 || !this.isContextual(isAwaitUsing ? "await" : "using")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length; + + if (lineBreak.test(this.input.slice(this.pos, next))) { return false } + + if (isAwaitUsing) { + var awaitEndPos = next + 5 /* await */, after; + if (this.input.slice(next, awaitEndPos) !== "using" || + awaitEndPos === this.input.length || + isIdentifierChar(after = this.input.charCodeAt(awaitEndPos)) || + (after > 0xd7ff && after < 0xdc00) + ) { return false } + + skipWhiteSpace.lastIndex = awaitEndPos; + var skipAfterUsing = skipWhiteSpace.exec(this.input); + if (skipAfterUsing && lineBreak.test(this.input.slice(awaitEndPos, awaitEndPos + skipAfterUsing[0].length))) { return false } + } + + if (isFor) { + var ofEndPos = next + 2 /* of */, after$1; + if (this.input.slice(next, ofEndPos) === "of") { + if (ofEndPos === this.input.length || + (!isIdentifierChar(after$1 = this.input.charCodeAt(ofEndPos)) && !(after$1 > 0xd7ff && after$1 < 0xdc00))) { return false } + } + } + + var ch = this.input.charCodeAt(next); + return isIdentifierStart(ch, true) || ch === 92 // '\' + }; + + pp$8.isAwaitUsing = function(isFor) { + return this.isUsingKeyword(true, isFor) + }; + + pp$8.isUsing = function(isFor) { + return this.isUsingKeyword(false, isFor) + }; + + // Parse a single statement. + // + // If expecting a statement and finding a slash operator, parse a + // regular expression literal. This is to handle cases like + // `if (foo) /blah/.exec(foo)`, where looking at the previous token + // does not help. + + pp$8.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types$1._debugger: return this.parseDebuggerStatement(node) + case types$1._do: return this.parseDoStatement(node) + case types$1._for: return this.parseForStatement(node) + case types$1._function: + // Function as sole body of either an if statement or a labeled statement + // works, but not when it is part of a labeled statement that is the sole + // body of an if statement. + if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types$1._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types$1._if: return this.parseIfStatement(node) + case types$1._return: return this.parseReturnStatement(node) + case types$1._switch: return this.parseSwitchStatement(node) + case types$1._throw: return this.parseThrowStatement(node) + case types$1._try: return this.parseTryStatement(node) + case types$1._const: case types$1._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types$1._while: return this.parseWhileStatement(node) + case types$1._with: return this.parseWithStatement(node) + case types$1.braceL: return this.parseBlock(true, node) + case types$1.semi: return this.parseEmptyStatement(node) + case types$1._export: + case types$1._import: + if (this.options.ecmaVersion > 10 && starttype === types$1._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) // '(' or '.' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } + + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var usingKind = this.isAwaitUsing(false) ? "await using" : this.isUsing(false) ? "using" : null; + if (usingKind) { + if (topLevel && this.options.sourceType === "script") { + this.raise(this.start, "Using declaration cannot appear in the top level when source type is `script`"); + } + if (usingKind === "await using") { + if (!this.canAwait) { + this.raise(this.start, "Await using cannot appear outside of async function"); + } + this.next(); + } + this.next(); + this.parseVar(node, false, usingKind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } + } + }; + + pp$8.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types$1.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } + } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") + }; + + pp$8.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") + }; + + pp$8.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types$1._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types$1.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") + }; + + // Disambiguating between a `for` and a `for`/`in` or `for`/`of` + // loop is non-trivial. Basically, we have to parse the init `var` + // statement or expression, disallowing the `in` operator (see + // the second parameter to `parseExpression`), and then check + // whether the next token is `in` or `of`. When there is no init + // part (semicolon immediately after the opening parenthesis), it + // is a regular `for` loop. + + pp$8.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types$1.parenL); + if (this.type === types$1.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types$1._var || this.type === types$1._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + return this.parseForAfterInit(node, init$1, awaitAt) + } + var startsWithLet = this.isContextual("let"), isForOf = false; + + var usingKind = this.isUsing(true) ? "using" : this.isAwaitUsing(true) ? "await using" : null; + if (usingKind) { + var init$2 = this.startNode(); + this.next(); + if (usingKind === "await using") { this.next(); } + this.parseVar(init$2, true, usingKind); + this.finishNode(init$2, "VariableDeclaration"); + return this.parseForAfterInit(node, init$2, awaitAt) + } + var containsEsc = this.containsEsc; + var refDestructuringErrors = new DestructuringErrors; + var initPos = this.start; + var init = awaitAt > -1 + ? this.parseExprSubscripts(refDestructuringErrors, "await") + : this.parseExpression(true, refDestructuringErrors); + if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (awaitAt > -1) { // implies `ecmaVersion >= 9` (see declaration of awaitAt) + if (this.type === types$1._in) { this.unexpected(awaitAt); } + node.await = true; + } else if (isForOf && this.options.ecmaVersion >= 8) { + if (init.start === initPos && !containsEsc && init.type === "Identifier" && init.name === "async") { this.unexpected(); } + else if (this.options.ecmaVersion >= 9) { node.await = false; } + } + if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) + }; + + // Helper method to parse for loop after variable initialization + pp$8.parseForAfterInit = function(node, init, awaitAt) { + if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) + }; + + pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) + }; + + pp$8.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") + }; + + pp$8.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") + }; + + pp$8.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types$1.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types$1.braceR;) { + if (this.type === types$1._case || this.type === types$1._default) { + var isCase = this.type === types$1._case; + if (cur) { this.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this.expect(types$1.colon); + } else { + if (!cur) { this.unexpected(); } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") + }; + + pp$8.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") + }; + + // Reused empty array added for node fields that are always empty. + + var empty$1 = []; + + pp$8.parseCatchClauseParam = function() { + var param = this.parseBindingAtom(); + var simple = param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types$1.parenR); + + return param + }; + + pp$8.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types$1._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types$1.parenL)) { + clause.param = this.parseCatchClauseParam(); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") + }; + + pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") + }; + + pp$8.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") + }; + + pp$8.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") + }; + + pp$8.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") + }; + + pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") + }; + + pp$8.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") + }; + + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). + + pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); + + node.body = []; + this.expect(types$1.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + if (exitStrict) { this.strict = false; } + this.next(); + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") + }; + + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. + + pp$8.parseFor = function(node, init) { + node.init = init; + this.expect(types$1.semi); + node.test = this.type === types$1.semi ? null : this.parseExpression(); + this.expect(types$1.semi); + node.update = this.type === types$1.parenR ? null : this.parseExpression(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement") + }; + + // Parse a `for`/`in` and `for`/`of` loop, which are almost + // same from parser's perspective. + + pp$8.parseForIn = function(node, init) { + var isForIn = this.type === types$1._in; + this.next(); + + if ( + init.type === "VariableDeclaration" && + init.declarations[0].init != null && + ( + !isForIn || + this.options.ecmaVersion < 8 || + this.strict || + init.kind !== "var" || + init.declarations[0].id.type !== "Identifier" + ) + ) { + this.raise( + init.start, + ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") + ); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") + }; + + // Parse a list of variable declarations. + + pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) { + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types$1.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { + this.unexpected(); + } else if (!allowMissingInitializer && (kind === "using" || kind === "await using") && this.options.ecmaVersion >= 17 && this.type !== types$1._in && !this.isContextual("of")) { + this.raise(this.lastTokEnd, ("Missing initializer in " + kind + " declaration")); + } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) { break } + } + return node + }; + + pp$8.parseVarId = function(decl, kind) { + decl.id = kind === "using" || kind === "await using" + ? this.parseIdent() + : this.parseBindingAtom(); + + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); + }; + + var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + + // Parse a function declaration or literal (depending on the + // `statement & FUNC_STATEMENT`). + + // Remove `allowExpressionBody` for 7.0.0, as it is only called with false + pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) + { this.unexpected(); } + node.generator = this.eat(types$1.star); + } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + // If it is a regular function declaration in sloppy mode, then it is + // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding + // mode depends on properties of the current scope (see + // treatFunctionsAsVar). + { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } + + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types$1.name ? this.parseIdent() : null; } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") + }; + + pp$8.parseFunctionParams = function(node) { + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + }; + + // Parse a class declaration or literal (depending on the + // `isStatement` parameter). + + pp$8.parseClass = function(node, isStatement) { + this.next(); + + // ecma-262 14.6 Class Definitions + // A class definition is always strict mode code. + var oldStrict = this.strict; + this.strict = true; + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types$1.braceL); + while (this.type !== types$1.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; + + pp$8.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types$1.semi)) { return null } + + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + + if (this.eatContextual("static")) { + // Parse static init block + if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { + this.parseClassStaticBlock(node); + return node + } + if (this.isClassElementNameStart() || this.type === types$1.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node.static = isStatic; + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + + // Parse element name + if (keyName) { + // 'async', 'get', 'set', or 'static' were not a keyword contextually. + // The last token is any of those. Make it the element name. + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + + // Parse element value + if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. + if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + + return node + }; + + pp$8.isClassElementNameStart = function() { + return ( + this.type === types$1.name || + this.type === types$1.privateId || + this.type === types$1.num || + this.type === types$1.string || + this.type === types$1.bracketL || + this.type.keyword + ) + }; + + pp$8.parseClassElementName = function(element) { + if (this.type === types$1.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } + }; + + pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + // Check key and flags + var key = method.key; + if (method.kind === "constructor") { + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + + // Parse value + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + + // Check value + if (method.kind === "get" && value.params.length !== 0) + { this.raiseRecoverable(value.start, "getter should have no params"); } + if (method.kind === "set" && value.params.length !== 1) + { this.raiseRecoverable(value.start, "setter should have exactly one param"); } + if (method.kind === "set" && value.params[0].type === "RestElement") + { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } + + return this.finishNode(method, "MethodDefinition") + }; + + pp$8.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + + if (this.eat(types$1.eq)) { + // To raise SyntaxError if 'arguments' exists in the initializer. + this.enterScope(SCOPE_CLASS_FIELD_INIT | SCOPE_SUPER); + field.value = this.parseMaybeAssign(); + this.exitScope(); + } else { + field.value = null; + } + this.semicolon(); + + return this.finishNode(field, "PropertyDefinition") + }; + + pp$8.parseClassStaticBlock = function(node) { + node.body = []; + + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + this.next(); + this.exitScope(); + this.labels = oldLabels; + + return this.finishNode(node, "StaticBlock") + }; + + pp$8.parseClassId = function(node, isStatement) { + if (this.type === types$1.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLValSimple(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; + } + }; + + pp$8.parseClassSuper = function(node) { + node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; + }; + + pp$8.enterClassBody = function() { + var element = {declared: Object.create(null), used: []}; + this.privateNameStack.push(element); + return element.declared + }; + + pp$8.exitClassBody = function() { + var ref = this.privateNameStack.pop(); + var declared = ref.declared; + var used = ref.used; + if (!this.options.checkPrivateFields) { return } + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!hasOwn(declared, id.name)) { + if (parent) { + parent.used.push(id); + } else { + this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); + } + } + } + }; + + function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + + // `class { get #a(){}; static set #a(_){} }` is also conflict. + if ( + curr === "iget" && next === "iset" || + curr === "iset" && next === "iget" || + curr === "sget" && next === "sset" || + curr === "sset" && next === "sget" + ) { + privateNameMap[name] = "true"; + return false + } else if (!curr) { + privateNameMap[name] = next; + return false + } else { + return true + } + } + + function checkKeyName(node, name) { + var computed = node.computed; + var key = node.key; + return !computed && ( + key.type === "Identifier" && key.name === name || + key.type === "Literal" && key.value === name + ) + } + + // Parses module export declaration. + + pp$8.parseExportAllDeclaration = function(node, exports) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + this.checkExport(exports, node.exported, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + if (this.options.ecmaVersion >= 16) + { node.attributes = this.parseWithClause(); } + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") + }; + + pp$8.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types$1.star)) { + return this.parseExportAllDeclaration(node, exports) + } + if (this.eat(types$1._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + node.declaration = this.parseExportDefaultDeclaration(); + return this.finishNode(node, "ExportDefaultDeclaration") + } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseExportDeclaration(node); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + if (this.options.ecmaVersion >= 16) + { node.attributes = []; } + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + if (this.options.ecmaVersion >= 16) + { node.attributes = this.parseWithClause(); } + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); + } + } + + node.source = null; + if (this.options.ecmaVersion >= 16) + { node.attributes = []; } + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration") + }; + + pp$8.parseExportDeclaration = function(node) { + return this.parseStatement(null) + }; + + pp$8.parseExportDefaultDeclaration = function() { + var isAsync; + if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync) + } else if (this.type === types$1._class) { + var cNode = this.startNode(); + return this.parseClass(cNode, "nullableID") + } else { + var declaration = this.parseMaybeAssign(); + this.semicolon(); + return declaration + } + }; + + pp$8.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (typeof name !== "string") + { name = name.type === "Identifier" ? name.name : name.value; } + if (hasOwn(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; + }; + + pp$8.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } + }; + + pp$8.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this.checkPatternExport(exports, decl.id); + } + }; + + pp$8.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() + }; + + // Parses a comma-separated list of module exports. + + pp$8.parseExportSpecifier = function(exports) { + var node = this.startNode(); + node.local = this.parseModuleExportName(); + + node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; + this.checkExport( + exports, + node.exported, + node.exported.start + ); + + return this.finishNode(node, "ExportSpecifier") + }; + + pp$8.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseExportSpecifier(exports)); + } + return nodes + }; + + // Parses import declaration. + + pp$8.parseImport = function(node) { + this.next(); + + // import '...' + if (this.type === types$1.string) { + node.specifiers = empty$1; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); + } + if (this.options.ecmaVersion >= 16) + { node.attributes = this.parseWithClause(); } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") + }; + + // Parses a comma-separated list of module imports. + + pp$8.parseImportSpecifier = function() { + var node = this.startNode(); + node.imported = this.parseModuleExportName(); + + if (this.eatContextual("as")) { + node.local = this.parseIdent(); + } else { + this.checkUnreserved(node.imported); + node.local = node.imported; + } + this.checkLValSimple(node.local, BIND_LEXICAL); + + return this.finishNode(node, "ImportSpecifier") + }; + + pp$8.parseImportDefaultSpecifier = function() { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportDefaultSpecifier") + }; + + pp$8.parseImportNamespaceSpecifier = function() { + var node = this.startNode(); + this.next(); + this.expectContextual("as"); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportNamespaceSpecifier") + }; + + pp$8.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types$1.name) { + nodes.push(this.parseImportDefaultSpecifier()); + if (!this.eat(types$1.comma)) { return nodes } + } + if (this.type === types$1.star) { + nodes.push(this.parseImportNamespaceSpecifier()); + return nodes + } + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseImportSpecifier()); + } + return nodes + }; + + pp$8.parseWithClause = function() { + var nodes = []; + if (!this.eat(types$1._with)) { + return nodes + } + this.expect(types$1.braceL); + var attributeKeys = {}; + var first = true; + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + var attr = this.parseImportAttribute(); + var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value; + if (hasOwn(attributeKeys, keyName)) + { this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'"); } + attributeKeys[keyName] = true; + nodes.push(attr); + } + return nodes + }; + + pp$8.parseImportAttribute = function() { + var node = this.startNode(); + node.key = this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never"); + this.expect(types$1.colon); + if (this.type !== types$1.string) { + this.unexpected(); + } + node.value = this.parseExprAtom(); + return this.finishNode(node, "ImportAttribute") + }; + + pp$8.parseModuleExportName = function() { + if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { + var stringLiteral = this.parseLiteral(this.value); + if (loneSurrogate.test(stringLiteral.value)) { + this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); + } + return stringLiteral + } + return this.parseIdent(true) + }; + + // Set `ExpressionStatement#directive` property for directive prologues. + pp$8.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } + }; + pp$8.isDirectiveCandidate = function(statement) { + return ( + this.options.ecmaVersion >= 5 && + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) + }; + + var pp$7 = Parser.prototype; + + // Convert existing expression atom to assignable pattern + // if possible. + + pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (!isBinding) { break } + + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node + }; + + // Convert list of expression atoms to binding list. + + pp$7.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList + }; + + // Parses spread element. + + pp$7.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") + }; + + pp$7.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types$1.name) + { this.unexpected(); } + + node.argument = this.parseBindingAtom(); + + return this.finishNode(node, "RestElement") + }; + + // Parses lvalue (assignable) atom. + + pp$7.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types$1.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types$1.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") + + case types$1.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() + }; + + pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this.expect(types$1.comma); } + if (allowEmpty && this.type === types$1.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break + } else if (this.type === types$1.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } + this.expect(close); + break + } else { + elts.push(this.parseAssignableListItem(allowModifiers)); + } + } + return elts + }; + + pp$7.parseAssignableListItem = function(allowModifiers) { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + return elem + }; + + pp$7.parseBindingListItem = function(param) { + return param + }; + + // Parses assignment pattern around given atom if possible. + + pp$7.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") + }; + + // The following three functions all verify that a node is an lvalue — + // something that can be bound, or assigned to. In order to do so, they perform + // a variety of checks: + // + // - Check that none of the bound/assigned-to identifiers are reserved words. + // - Record name declarations for bindings in the appropriate scope. + // - Check duplicate argument names, if checkClashes is set. + // + // If a complex binding pattern is encountered (e.g., object and array + // destructuring), the entire pattern is recursively checked. + // + // There are three versions of checkLVal*() appropriate for different + // circumstances: + // + // - checkLValSimple() shall be used if the syntactic construct supports + // nothing other than identifiers and member expressions. Parenthesized + // expressions are also correctly handled. This is generally appropriate for + // constructs for which the spec says + // + // > It is a Syntax Error if AssignmentTargetType of [the production] is not + // > simple. + // + // It is also appropriate for checking if an identifier is valid and not + // defined elsewhere, like import declarations or function/class identifiers. + // + // Examples where this is used include: + // a += …; + // import a from '…'; + // where a is the node to be checked. + // + // - checkLValPattern() shall be used if the syntactic construct supports + // anything checkLValSimple() supports, as well as object and array + // destructuring patterns. This is generally appropriate for constructs for + // which the spec says + // + // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor + // > an ArrayLiteral and AssignmentTargetType of [the production] is not + // > simple. + // + // Examples where this is used include: + // (a = …); + // const a = …; + // try { … } catch (a) { … } + // where a is the node to be checked. + // + // - checkLValInnerPattern() shall be used if the syntactic construct supports + // anything checkLValPattern() supports, as well as default assignment + // patterns, rest elements, and other constructs that may appear within an + // object or array destructuring pattern. + // + // As a special case, function parameters also use checkLValInnerPattern(), + // as they also support defaults and rest constructs. + // + // These functions deliberately support both assignment and binding constructs, + // as the logic for both is exceedingly similar. If the node is the target of + // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it + // should be set to the appropriate BIND_* constant, like BIND_VAR or + // BIND_LEXICAL. + // + // If the function is called with a non-BIND_NONE bindingType, then + // additionally a checkClashes object may be specified to allow checking for + // duplicate argument names. checkClashes is ignored if the provided construct + // is an assignment (i.e., bindingType is BIND_NONE). + + pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + var isBind = bindingType !== BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (checkClashes) { + if (hasOwn(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + } + break + + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ParenthesizedExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } + return this.checkLValSimple(expr.expression, bindingType, checkClashes) + + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } + }; + + pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break + + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } + } + break + + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } + }; + + pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Property": + // AssignmentProperty has type === "Property" + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break + + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break + + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } + }; + + // The algorithm used to determine whether a regexp can appear at a + // given point in the program is loosely based on sweet.js' approach. + // See https://github.com/mozilla/sweet.js/wiki/design + + + var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; + }; + + var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) + }; + + var pp$6 = Parser.prototype; + + pp$6.initialContext = function() { + return [types.b_stat] + }; + + pp$6.curContext = function() { + return this.context[this.context.length - 1] + }; + + pp$6.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types.f_expr || parent === types.f_stat) + { return true } + if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) + { return true } + if (prevType === types$1.braceL) + { return parent === types.b_stat } + if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) + { return false } + return !this.exprAllowed + }; + + pp$6.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") + { return context.generator } + } + return false + }; + + pp$6.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types$1.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } + }; + + // Used to handle edge cases when token context could not be inferred correctly during tokenization phase + + pp$6.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } + }; + + // Token-specific context update code + + types$1.parenR.updateContext = types$1.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; + }; + + types$1.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); + this.exprAllowed = true; + }; + + types$1.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl); + this.exprAllowed = true; + }; + + types$1.parenL.updateContext = function(prevType) { + var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; + this.context.push(statementParens ? types.p_stat : types.p_expr); + this.exprAllowed = true; + }; + + types$1.incDec.updateContext = function() { + // tokExprAllowed stays unchanged + }; + + types$1._function.updateContext = types$1._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types$1._else && + !(prevType === types$1.semi && this.curContext() !== types.p_stat) && + !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) + { this.context.push(types.f_expr); } + else + { this.context.push(types.f_stat); } + this.exprAllowed = false; + }; + + types$1.colon.updateContext = function() { + if (this.curContext().token === "function") { this.context.pop(); } + this.exprAllowed = true; + }; + + types$1.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types.q_tmpl); } + this.exprAllowed = false; + }; + + types$1.star.updateContext = function(prevType) { + if (prevType === types$1._function) { + var index = this.context.length - 1; + if (this.context[index] === types.f_expr) + { this.context[index] = types.f_expr_gen; } + else + { this.context[index] = types.f_gen; } + } + this.exprAllowed = true; + }; + + types$1.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } + } + this.exprAllowed = allowed; + }; + + // A recursive descent parser operates by defining functions for all + // syntactic elements, and recursively calling those, each function + // advancing the input stream and returning an AST node. Precedence + // of constructs (for example, the fact that `!x[1]` means `!(x[1])` + // instead of `(!x)[1]` is handled by the fact that the parser + // function that parses unary prefix operators is called first, and + // in turn calls the function that parses `[]` subscripts — that + // way, it'll receive the node for `x[1]` already parsed, and wraps + // *that* in the unary operator node. + // + // Acorn uses an [operator precedence parser][opp] to handle binary + // operator precedence, because it is much more compact than using + // the technique outlined above, which uses different, nesting + // functions to specify precedence, for all of the ten binary + // precedence levels that JavaScript defines. + // + // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + + + var pp$5 = Parser.prototype; + + // Check if property name clashes with already added. + // Object/class getters and setters are not allowed to clash — + // either with each other or with an init property — and in + // strict mode, init properties are also not allowed to be repeated. + + pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) { + refDestructuringErrors.doubleProto = key.start; + } + } else { + this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); + } + } + propHash.proto = true; + } + return + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; + }; + + // ### Expression parsing + + // These nest, from the most general expression type at the top to + // 'atomic', nondivisible expression types at the bottom. Most of + // the functions will simply let the function(s) below them parse, + // and, *if* the syntactic construct they handle is present, wrap + // the AST node that the inner parser gave them in another node. + + // Parse a full expression. The optional arguments are used to + // forbid the `in` operator (in for loops initalization expressions) + // and provide reference for storing '=' operator inside shorthand + // property assignment in contexts where both object expression + // and object pattern might appear (so it's possible to raise + // delayed syntax error at correct position). + + pp$5.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types$1.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr + }; + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(forInit) } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } + } + + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } + + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types$1.parenL || this.type === types$1.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types$1.eq) + { left = this.toAssignable(left, false, refDestructuringErrors); } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly + if (this.type === types$1.eq) + { this.checkLValPattern(left); } + else + { this.checkLValSimple(left); } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + return left + }; + + // Parse a ternary conditional (`?:`) operator. + + pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types$1.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types$1.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression") + } + return expr + }; + + // Start the precedence parser. + + pp$5.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) + }; + + // Parse binary operators with the operator precedence parsing + // algorithm. `left` is the left-hand side of the operator. + // `minPrec` provides context that allows the function to stop and + // defer further parser to one of its callers when it encounters an + // operator that has a lower precedence than the set it is parsing. + + pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types$1._in)) { + if (prec > minPrec) { + var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; + var coalesce = this.type === types$1.coalesce; + if (coalesce) { + // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. + // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. + prec = types$1.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) + } + } + return left + }; + + pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { + if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") + }; + + // Parse unary operators, both prefix and postfix. + + pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types$1.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLValSimple(node.argument); } + else if (this.strict && node.operator === "delete" && isLocalVariableAccess(node.argument)) + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) + { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else if (!sawUnary && this.type === types$1.privateId) { + if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); } + expr = this.parsePrivateIdent(); + // only could be private fields in 'in', such as #x in obj + if (this.type !== types$1._in) { this.unexpected(); } + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + + if (!incDec && this.eat(types$1.starstar)) { + if (sawUnary) + { this.unexpected(this.lastTokStart); } + else + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } + } else { + return expr + } + }; + + function isLocalVariableAccess(node) { + return ( + node.type === "Identifier" || + node.type === "ParenthesizedExpression" && isLocalVariableAccess(node.expression) + ) + } + + function isPrivateFieldAccess(node) { + return ( + node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || + node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) || + node.type === "ParenthesizedExpression" && isPrivateFieldAccess(node.expression) + ) + } + + // Parse call, dot, and `[]`-subscript expressions. + + pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } + } + return result + }; + + pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && + this.potentialArrowAt === base.start; + var optionalChained = false; + + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + + if (element.optional) { optionalChained = true; } + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element + } + + base = element; + } + }; + + pp$5.shouldParseAsyncArrow = function() { + return !this.canInsertSemicolon() && this.eat(types$1.arrow) + }; + + pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) + }; + + pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types$1.questionDot); + if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + + var computed = this.eat(types$1.bracketL); + if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types$1.bracketR); + } else if (this.type === types$1.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types$1.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types$1.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({isTagged: true}); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base + }; + + // Parse an atomic expression — either a single token that is an + // expression, an expression started by a keyword like `function` or + // `new`, or an expression wrapped in punctuation like `()`, `[]`, + // or `{}`. + + pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types$1.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types$1._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types$1.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super ( Arguments ) + if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types$1._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types$1.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { + this.overrideContext(types.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types$1.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && + (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) + } + } + return id + + case types$1.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node + + case types$1.num: case types$1.string: + return this.parseLiteral(this.value) + + case types$1._null: case types$1._true: case types$1._false: + node = this.startNode(); + node.value = this.type === types$1._null ? null : this.type === types$1._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types$1.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr + + case types$1.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") + + case types$1.braceL: + this.overrideContext(types.b_expr); + return this.parseObj(false, refDestructuringErrors) + + case types$1._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) + + case types$1._class: + return this.parseClass(this.startNode(), false) + + case types$1._new: + return this.parseNew() + + case types$1.backQuote: + return this.parseTemplate() + + case types$1._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport(forNew) + } else { + return this.unexpected() + } + + default: + return this.parseExprAtomDefault() + } + }; + + pp$5.parseExprAtomDefault = function() { + this.unexpected(); + }; + + pp$5.parseExprImport = function(forNew) { + var node = this.startNode(); + + // Consume `import` as an identifier for `import.meta`. + // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } + this.next(); + + if (this.type === types$1.parenL && !forNew) { + return this.parseDynamicImport(node) + } else if (this.type === types$1.dot) { + var meta = this.startNodeAt(node.start, node.loc && node.loc.start); + meta.name = "import"; + node.meta = this.finishNode(meta, "Identifier"); + return this.parseImportMeta(node) + } else { + this.unexpected(); + } + }; + + pp$5.parseDynamicImport = function(node) { + this.next(); // skip `(` + + // Parse node.source. + node.source = this.parseMaybeAssign(); + + if (this.options.ecmaVersion >= 16) { + if (!this.eat(types$1.parenR)) { + this.expect(types$1.comma); + if (!this.afterTrailingComma(types$1.parenR)) { + node.options = this.parseMaybeAssign(); + if (!this.eat(types$1.parenR)) { + this.expect(types$1.comma); + if (!this.afterTrailingComma(types$1.parenR)) { + this.unexpected(); + } + } + } else { + node.options = null; + } + } else { + node.options = null; + } + } else { + // Verify ending. + if (!this.eat(types$1.parenR)) { + var errorPos = this.start; + if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + } + + return this.finishNode(node, "ImportExpression") + }; + + pp$5.parseImportMeta = function(node) { + this.next(); // skip `.` + + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + + if (node.property.name !== "meta") + { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) + { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + + return this.finishNode(node, "MetaProperty") + }; + + pp$5.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) + { node.bigint = node.value != null ? node.value.toString() : node.raw.slice(0, -1).replace(/_/g, ""); } + this.next(); + return this.finishNode(node, "Literal") + }; + + pp$5.parseParenExpression = function() { + this.expect(types$1.parenL); + var val = this.parseExpression(); + this.expect(types$1.parenR); + return val + }; + + pp$5.shouldParseArrow = function(exprList) { + return !this.canInsertSemicolon() + }; + + pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + // Do not save awaitIdentPos to allow checking awaits nested in parameters + while (this.type !== types$1.parenR) { + first ? first = false : this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { + lastIsComma = true; + break + } else if (this.type === types$1.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types$1.comma) { + this.raiseRecoverable( + this.start, + "Comma is not permitted after the rest element" + ); + } + break + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types$1.parenR); + + if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit) + } + + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val + } + }; + + pp$5.parseParenItem = function(item) { + return item + }; + + pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) + }; + + // New's precedence is slightly tricky. It must allow its argument to + // be a `[]` or dot subscript expression, but not a call — at least, + // not without wrapping it in parentheses. Thus, it uses the noCalls + // argument to parseSubscripts to prevent it from consuming the + // argument list. + + var empty = []; + + pp$5.parseNew = function() { + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } + var node = this.startNode(); + this.next(); + if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) { + var meta = this.startNodeAt(node.start, node.loc && node.loc.start); + meta.name = "new"; + node.meta = this.finishNode(meta, "Identifier"); + this.next(); + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } + if (!this.allowNewDotTarget) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc; + node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); + if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty; } + return this.finishNode(node, "NewExpression") + }; + + // Parse template expression. + + pp$5.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types$1.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value.replace(/\r\n?/g, "\n"), + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types$1.backQuote; + return this.finishNode(elem, "TemplateElement") + }; + + pp$5.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } + this.expect(types$1.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types$1.braceR); + node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); + } + this.next(); + return this.finishNode(node, "TemplateLiteral") + }; + + pp$5.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + // Parse an object literal or binding pattern. + + pp$5.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") + }; + + pp$5.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types$1.star); } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); + this.parsePropertyName(prop); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") + }; + + pp$5.parseGetterSetter = function(prop) { + var kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + prop.kind = kind; + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } + }; + + pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types$1.colon) + { this.unexpected(); } + + if (this.eat(types$1.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { + if (isPattern) { this.unexpected(); } + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + prop.kind = "init"; + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { + if (isGenerator || isAsync) { this.unexpected(); } + this.parseGetterSetter(prop); + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { this.unexpected(); } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = startPos; } + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types$1.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.kind = "init"; + prop.shorthand = true; + } else { this.unexpected(); } + }; + + pp$5.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types$1.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types$1.bracketR); + return prop.key + } else { + prop.computed = false; + } + } + return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") + }; + + // Initialize empty function node. + + pp$5.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } + }; + + // Parse object or class method. + + pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; + + // Parse arrow function expression with given parameters. + + pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; + + // Parse function body and check parameters. + + pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types$1.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(forInit); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } + node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); + }; + + pp$5.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true + }; + + // Checks function params for various disallowed patterns such as using "eval" + // or "arguments" and duplicate parameters. + + pp$5.checkParams = function(node, allowDuplicates) { + var nameHash = Object.create(null); + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } + }; + + // Parses a comma-separated list of expressions, and returns them as + // an array. `close` is the token type that ends the list, and + // `allowEmpty` can be turned on to allow subsequent commas with + // nothing in between them to be parsed as `null` (which is needed + // for array literals). + + pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this.type === types$1.comma) + { elt = null; } + else if (this.type === types$1.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this.start; } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts + }; + + pp$5.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } + if (!(this.currentThisScope().flags & SCOPE_VAR) && name === "arguments") + { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) + { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); + } + }; + + // Parse the next token as an identifier. If `liberal` is true (used + // when parsing properties), it will also convert keywords into + // identifiers. + + pp$5.parseIdent = function(liberal) { + var node = this.parseIdentNode(); + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node + }; + + pp$5.parseIdentNode = function() { + var node = this.startNode(); + if (this.type === types$1.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + this.type = types$1.name; + } else { + this.unexpected(); + } + return node + }; + + pp$5.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types$1.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + + // For validating existence + if (this.options.checkPrivateFields) { + if (this.privateNameStack.length === 0) { + this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + } + + return node + }; + + // Parses yield expression inside generator. + + pp$5.parseYield = function(forInit) { + if (!this.yieldPos) { this.yieldPos = this.start; } + + var node = this.startNode(); + this.next(); + if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types$1.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression") + }; + + pp$5.parseAwait = function(forInit) { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node, "AwaitExpression") + }; + + var pp$4 = Parser.prototype; + + // This function is used to raise exceptions on parse errors. It + // takes an offset integer (into the current `input`) to indicate + // the location of the error, attaches the position to the end + // of the error message, and then raises a `SyntaxError` with that + // message. + + pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + if (this.sourceFile) { + message += " in " + this.sourceFile; + } + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err + }; + + pp$4.raiseRecoverable = pp$4.raise; + + pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } + }; + + var pp$3 = Parser.prototype; + + var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; + // A list of lexically-declared FunctionDeclaration names in the current lexical scope + this.functions = []; + }; + + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + + pp$3.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; + + pp$3.exitScope = function() { + this.scopeStack.pop(); + }; + + // The spec says: + // > At the top level of a function, or script, function declarations are + // > treated like var declarations rather than like lexical declarations. + pp$3.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) + }; + + pp$3.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && (scope.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) + { redeclared = scope$2.lexical.indexOf(name) > -1; } + else + { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || + !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break + } + scope$3.var.push(name); + if (this.inModule && (scope$3.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + if (scope$3.flags & SCOPE_VAR) { break } + } + } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } + }; + + pp$3.checkLocalExport = function(id) { + // scope.functions must be empty as Module code is always strict. + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && + this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; + } + }; + + pp$3.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; + + pp$3.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK)) { return scope } + } + }; + + // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. + pp$3.currentThisScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK) && + !(scope.flags & SCOPE_ARROW)) { return scope } + } + }; + + var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } + }; + + // Start an AST node, attaching a start offset. + + var pp$2 = Parser.prototype; + + pp$2.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; + + pp$2.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) + }; + + // Finish an AST node, adding `type` and `end` properties. + + function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node + } + + pp$2.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; + + // Finish node at given position + + pp$2.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; + + pp$2.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode + }; + + // This file was generated by "bin/generate-unicode-script-values.js". Do not modify manually! + var scriptValuesAddedInUnicode = "Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"; + + // This file contains Unicode properties extracted from the ECMAScript specification. + // The lists are extracted like so: + // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) + + // #table-binary-unicode-properties + var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; + var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; + var ecma11BinaryProperties = ecma10BinaryProperties; + var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; + var ecma13BinaryProperties = ecma12BinaryProperties; + var ecma14BinaryProperties = ecma13BinaryProperties; + + var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties, + 13: ecma13BinaryProperties, + 14: ecma14BinaryProperties + }; + + // #table-binary-unicode-properties-of-strings + var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; + + var unicodeBinaryPropertiesOfStrings = { + 9: "", + 10: "", + 11: "", + 12: "", + 13: "", + 14: ecma14BinaryPropertiesOfStrings + }; + + // #table-unicode-general-category-values + var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; + + // #table-unicode-script-values + var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; + var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; + var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; + var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; + var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; + var ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode; + + var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues, + 13: ecma13ScriptValues, + 14: ecma14ScriptValues + }; + + var data = {}; + function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; + } + + for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) { + var ecmaVersion = list[i]; + + buildUnicodeData(ecmaVersion); + } + + var pp$1 = Parser.prototype; + + // Track disjunction structure to determine whether a duplicate + // capture group name is allowed because it is in a separate branch. + var BranchID = function BranchID(parent, base) { + // Parent disjunction branch + this.parent = parent; + // Identifies this set of sibling branches + this.base = base || this; + }; + + BranchID.prototype.separatedFrom = function separatedFrom (alt) { + // A branch is separate from another branch if they or any of + // their parents are siblings in a given disjunction + for (var self = this; self; self = self.parent) { + for (var other = alt; other; other = other.parent) { + if (self.base === other.base && self !== other) { return true } + } + } + return false + }; + + BranchID.prototype.sibling = function sibling () { + return new BranchID(this.parent, this.base) + }; + + var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchV = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = Object.create(null); + this.backReferenceNames = []; + this.branchID = null; + }; + + RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicodeSets = flags.indexOf("v") !== -1; + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + if (unicodeSets && this.parser.options.ecmaVersion >= 15) { + this.switchU = true; + this.switchV = true; + this.switchN = true; + } else { + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchV = false; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + } + }; + + RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); + }; + + // If u flag is given, this returns the code point at the index (it combines a surrogate pair). + // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). + RegExpValidationState.prototype.at = function at (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c + } + var next = s.charCodeAt(i + 1); + return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c + }; + + RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 + } + return i + 2 + }; + + RegExpValidationState.prototype.current = function current (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.pos, forceU) + }; + + RegExpValidationState.prototype.lookahead = function lookahead (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.nextIndex(this.pos, forceU), forceU) + }; + + RegExpValidationState.prototype.advance = function advance (forceU) { + if ( forceU === void 0 ) forceU = false; + + this.pos = this.nextIndex(this.pos, forceU); + }; + + RegExpValidationState.prototype.eat = function eat (ch, forceU) { + if ( forceU === void 0 ) forceU = false; + + if (this.current(forceU) === ch) { + this.advance(forceU); + return true + } + return false + }; + + RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) { + if ( forceU === void 0 ) forceU = false; + + var pos = this.pos; + for (var i = 0, list = chs; i < list.length; i += 1) { + var ch = list[i]; + + var current = this.at(pos, forceU); + if (current === -1 || current !== ch) { + return false + } + pos = this.nextIndex(pos, forceU); + } + this.pos = pos; + return true + }; + + /** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + + var u = false; + var v = false; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + if (flag === "u") { u = true; } + if (flag === "v") { v = true; } + } + if (this.options.ecmaVersion >= 15 && u && v) { + this.raise(state.start, "Invalid regular expression flag"); + } + }; + + function hasProp(obj) { + for (var _ in obj) { return true } + return false + } + + /** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && hasProp(state.groupNames)) { + state.switchN = true; + this.regexp_pattern(state); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern + pp$1.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames = Object.create(null); + state.backReferenceNames.length = 0; + state.branchID = null; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + + if (!state.groupNames[name]) { + state.raise("Invalid named capture referenced"); + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction + pp$1.regexp_disjunction = function(state) { + var trackDisjunction = this.options.ecmaVersion >= 16; + if (trackDisjunction) { state.branchID = new BranchID(state.branchID, null); } + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + if (trackDisjunction) { state.branchID = state.branchID.sibling(); } + this.regexp_alternative(state); + } + if (trackDisjunction) { state.branchID = state.branchID.parent; } + + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative + pp$1.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) {} + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term + pp$1.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } + + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion + pp$1.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } + + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } + + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } + + state.pos = start; + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier + pp$1.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; + + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix + pp$1.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) + }; + pp$1.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom + pp$1.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) + }; + pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */)) { + if (this.options.ecmaVersion >= 16) { + var addModifiers = this.regexp_eatModifiers(state); + var hasHyphen = state.eat(0x2D /* - */); + if (addModifiers || hasHyphen) { + for (var i = 0; i < addModifiers.length; i++) { + var modifier = addModifiers.charAt(i); + if (addModifiers.indexOf(modifier, i + 1) > -1) { + state.raise("Duplicate regular expression modifiers"); + } + } + if (hasHyphen) { + var removeModifiers = this.regexp_eatModifiers(state); + if (!addModifiers && !removeModifiers && state.current() === 0x3A /* : */) { + state.raise("Invalid regular expression modifiers"); + } + for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) { + var modifier$1 = removeModifiers.charAt(i$1); + if ( + removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 || + addModifiers.indexOf(modifier$1) > -1 + ) { + state.raise("Duplicate regular expression modifiers"); + } + } + } + } + } + if (state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true + } + state.raise("Unterminated group"); + } + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false + }; + // RegularExpressionModifiers :: + // [empty] + // RegularExpressionModifiers RegularExpressionModifier + pp$1.regexp_eatModifiers = function(state) { + var modifiers = ""; + var ch = 0; + while ((ch = state.current()) !== -1 && isRegularExpressionModifier(ch)) { + modifiers += codePointToString(ch); + state.advance(); + } + return modifiers + }; + // RegularExpressionModifier :: one of + // `i` `m` `s` + function isRegularExpressionModifier(ch) { + return ch === 0x69 /* i */ || ch === 0x6d /* m */ || ch === 0x73 /* s */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom + pp$1.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier + pp$1.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter + pp$1.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter + // But eat eager. + pp$1.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter + pp$1.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false + }; + + // GroupSpecifier :: + // [empty] + // `?` GroupName + pp$1.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (!this.regexp_eatGroupName(state)) { state.raise("Invalid group"); } + var trackDisjunction = this.options.ecmaVersion >= 16; + var known = state.groupNames[state.lastStringValue]; + if (known) { + if (trackDisjunction) { + for (var i = 0, list = known; i < list.length; i += 1) { + var altID = list[i]; + + if (!altID.separatedFrom(state.branchID)) + { state.raise("Duplicate capture group name"); } + } + } else { + state.raise("Duplicate capture group name"); + } + } + if (trackDisjunction) { + (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID); + } else { + state.groupNames[state.lastStringValue] = true; + } + } + }; + + // GroupName :: + // `<` RegExpIdentifierName `>` + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); + } + return false + }; + + // RegExpIdentifierName :: + // RegExpIdentifierStart + // RegExpIdentifierName RegExpIdentifierPart + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true + } + return false + }; + + // RegExpIdentifierStart :: + // UnicodeIDStart + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + pp$1.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ + } + + // RegExpIdentifierPart :: + // UnicodeIDContinue + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + // + // + pp$1.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape + pp$1.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false + }; + pp$1.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape + pp$1.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) + }; + pp$1.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape + pp$1.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter + pp$1.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence + pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if ( forceU === void 0 ) forceU = false; + + var start = state.pos; + var switchU = forceU || state.switchU; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true + } + if ( + switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + + return false + }; + function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape + pp$1.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false + } + + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape + pp$1.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false + }; + + // Return values used by character set parsing methods, needed to + // forbid negation of sets that can match strings. + var CharSetNone = 0; // Nothing parsed + var CharSetOk = 1; // Construct parsed, cannot contain strings + var CharSetString = 2; // Construct parsed, can contain strings + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape + pp$1.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return CharSetOk + } + + var negate = false; + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + var result; + if ( + state.eat(0x7B /* { */) && + (result = this.regexp_eatUnicodePropertyValueExpression(state)) && + state.eat(0x7D /* } */) + ) { + if (negate && result === CharSetString) { state.raise("Invalid property name"); } + return result + } + state.raise("Invalid property name"); + } + + return CharSetNone + }; + + function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) + } + + // UnicodePropertyValueExpression :: + // UnicodePropertyName `=` UnicodePropertyValue + // LoneUnicodePropertyNameOrValue + pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return CharSetOk + } + } + state.pos = start; + + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) + } + return CharSetNone + }; + + pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!hasOwn(state.unicodeProperties.nonBinary, name)) + { state.raise("Invalid property name"); } + if (!state.unicodeProperties.nonBinary[name].test(value)) + { state.raise("Invalid property value"); } + }; + + pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk } + if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString } + state.raise("Invalid property name"); + }; + + // UnicodePropertyName :: + // UnicodePropertyNameCharacters + pp$1.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + + function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ + } + + // UnicodePropertyValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) + } + + // LoneUnicodePropertyNameOrValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass + pp$1.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (!state.eat(0x5D /* ] */)) + { state.raise("Unterminated character class"); } + if (negate && result === CharSetString) + { state.raise("Negated character class may contain strings"); } + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassContents + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges + pp$1.regexp_classContents = function(state) { + if (state.current() === 0x5D /* ] */) { return CharSetOk } + if (state.switchV) { return this.regexp_classSetExpression(state) } + this.regexp_nonEmptyClassRanges(state); + return CharSetOk + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash + pp$1.regexp_nonEmptyClassRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash + pp$1.regexp_eatClassAtom = function(state) { + var start = state.pos; + + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + + var ch = state.current(); + if (ch !== 0x5D /* ] */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape + pp$1.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } + + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } + + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) + }; + + // https://tc39.es/ecma262/#prod-ClassSetExpression + // https://tc39.es/ecma262/#prod-ClassUnion + // https://tc39.es/ecma262/#prod-ClassIntersection + // https://tc39.es/ecma262/#prod-ClassSubtraction + pp$1.regexp_classSetExpression = function(state) { + var result = CharSetOk, subResult; + if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) { + if (subResult === CharSetString) { result = CharSetString; } + // https://tc39.es/ecma262/#prod-ClassIntersection + var start = state.pos; + while (state.eatChars([0x26, 0x26] /* && */)) { + if ( + state.current() !== 0x26 /* & */ && + (subResult = this.regexp_eatClassSetOperand(state)) + ) { + if (subResult !== CharSetString) { result = CharSetOk; } + continue + } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + // https://tc39.es/ecma262/#prod-ClassSubtraction + while (state.eatChars([0x2D, 0x2D] /* -- */)) { + if (this.regexp_eatClassSetOperand(state)) { continue } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + } else { + state.raise("Invalid character in character class"); + } + // https://tc39.es/ecma262/#prod-ClassUnion + for (;;) { + if (this.regexp_eatClassSetRange(state)) { continue } + subResult = this.regexp_eatClassSetOperand(state); + if (!subResult) { return result } + if (subResult === CharSetString) { result = CharSetString; } + } + }; + + // https://tc39.es/ecma262/#prod-ClassSetRange + pp$1.regexp_eatClassSetRange = function(state) { + var start = state.pos; + if (this.regexp_eatClassSetCharacter(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) { + var right = state.lastIntValue; + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + return true + } + state.pos = start; + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetOperand + pp$1.regexp_eatClassSetOperand = function(state) { + if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk } + return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state) + }; + + // https://tc39.es/ecma262/#prod-NestedClass + pp$1.regexp_eatNestedClass = function(state) { + var start = state.pos; + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (state.eat(0x5D /* ] */)) { + if (negate && result === CharSetString) { + state.raise("Negated character class may contain strings"); + } + return result + } + state.pos = start; + } + if (state.eat(0x5C /* \ */)) { + var result$1 = this.regexp_eatCharacterClassEscape(state); + if (result$1) { + return result$1 + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunction + pp$1.regexp_eatClassStringDisjunction = function(state) { + var start = state.pos; + if (state.eatChars([0x5C, 0x71] /* \q */)) { + if (state.eat(0x7B /* { */)) { + var result = this.regexp_classStringDisjunctionContents(state); + if (state.eat(0x7D /* } */)) { + return result + } + } else { + // Make the same message as V8. + state.raise("Invalid escape"); + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents + pp$1.regexp_classStringDisjunctionContents = function(state) { + var result = this.regexp_classString(state); + while (state.eat(0x7C /* | */)) { + if (this.regexp_classString(state) === CharSetString) { result = CharSetString; } + } + return result + }; + + // https://tc39.es/ecma262/#prod-ClassString + // https://tc39.es/ecma262/#prod-NonEmptyClassString + pp$1.regexp_classString = function(state) { + var count = 0; + while (this.regexp_eatClassSetCharacter(state)) { count++; } + return count === 1 ? CharSetOk : CharSetString + }; + + // https://tc39.es/ecma262/#prod-ClassSetCharacter + pp$1.regexp_eatClassSetCharacter = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if ( + this.regexp_eatCharacterEscape(state) || + this.regexp_eatClassSetReservedPunctuator(state) + ) { + return true + } + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + state.pos = start; + return false + } + var ch = state.current(); + if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false } + if (isClassSetSyntaxCharacter(ch)) { return false } + state.advance(); + state.lastIntValue = ch; + return true + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator + function isClassSetReservedDoublePunctuatorCharacter(ch) { + return ( + ch === 0x21 /* ! */ || + ch >= 0x23 /* # */ && ch <= 0x26 /* & */ || + ch >= 0x2A /* * */ && ch <= 0x2C /* , */ || + ch === 0x2E /* . */ || + ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ || + ch === 0x5E /* ^ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter + function isClassSetSyntaxCharacter(ch) { + return ( + ch === 0x28 /* ( */ || + ch === 0x29 /* ) */ || + ch === 0x2D /* - */ || + ch === 0x2F /* / */ || + ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + pp$1.regexp_eatClassSetReservedPunctuator = function(state) { + var ch = state.current(); + if (isClassSetReservedPunctuator(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + function isClassSetReservedPunctuator(ch) { + return ( + ch === 0x21 /* ! */ || + ch === 0x23 /* # */ || + ch === 0x25 /* % */ || + ch === 0x26 /* & */ || + ch === 0x2C /* , */ || + ch === 0x2D /* - */ || + ch >= 0x3A /* : */ && ch <= 0x3E /* > */ || + ch === 0x40 /* @ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter + pp$1.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits + pp$1.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } + return state.pos !== start + }; + function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits + pp$1.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start + }; + function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) + } + function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) + } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence + // Allows only 0-377(octal) i.e. 0-255(decimal). + pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit + pp$1.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false + }; + function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit + // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true + }; + + // Object type used to represent tokens. Note that normally, tokens + // simply exist as properties on the parser object. This is only + // used for the onToken callback and the external tokenizer. + + var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } + }; + + // ## Tokenizer + + var pp = Parser.prototype; + + // Move to the next token + + pp.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) + { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } + if (this.options.onToken) + { this.options.onToken(new Token(this)); } + + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); + }; + + pp.getToken = function() { + this.next(); + return new Token(this) + }; + + // If we're in an ES6 environment, make parsers iterable + if (typeof Symbol !== "undefined") + { pp[Symbol.iterator] = function() { + var this$1$1 = this; + + return { + next: function () { + var token = this$1$1.getToken(); + return { + done: token.type === types$1.eof, + value: token + } + } + } + }; } + + // Toggle strict mode. Re-reads the next number or string to please + // pedantic tests (`"use strict"; 010;` should fail). + + // Read a single token, updating the parser object's token-related + // properties. + + pp.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } + + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } + + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } + }; + + pp.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } + + return this.getTokenFromCode(code) + }; + + pp.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xdc00) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 + }; + + pp.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } + }; + + pp.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } + }; + + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and. + + pp.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this.pos; + break + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: case 8232: case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break + case 47: // '/' + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: // '*' + this.skipBlockComment(); + break + case 47: + this.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop + } + } + } + }; + + // Called at the end of every token. Sets `end`, `val`, and + // maintains `context` and `exprAllowed`, and skips the space after + // the token, so that the next one's `start` will point at the + // right position. + + pp.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; + + this.updateContext(prevType); + }; + + // ### Token reading + + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + pp.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types$1.ellipsis) + } else { + ++this.pos; + return this.finishToken(types$1.dot) + } + }; + + pp.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.slash, 1) + }; + + pp.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types$1.star : types$1.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types$1.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + + if (next === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(tokentype, size) + }; + + pp.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { return this.finishOp(types$1.assign, 3) } + } + return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) + }; + + pp.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.bitwiseXOR, 1) + }; + + pp.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) + }; + + pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) +}; + +pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // ` + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/eslint-scope/dist/eslint-scope.cjs b/node_modules/eslint-scope/dist/eslint-scope.cjs new file mode 100644 index 00000000..abb88e59 --- /dev/null +++ b/node_modules/eslint-scope/dist/eslint-scope.cjs @@ -0,0 +1,2339 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var estraverse = require('estraverse'); +var esrecurse = require('esrecurse'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var estraverse__default = /*#__PURE__*/_interopDefaultLegacy(estraverse); +var esrecurse__default = /*#__PURE__*/_interopDefaultLegacy(esrecurse); + +/** + * @fileoverview Assertion utilities. + * @author Nicholas C. Zakas + */ + +/** + * Throws an error if the given condition is not truthy. + * @param {boolean} condition The condition to check. + * @param {string} message The message to include with the error. + * @returns {void} + * @throws {Error} When the condition is not truthy. + */ +function assert(condition, message = "Assertion failed.") { + if (!condition) { + throw new Error(message); + } +} + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +const READ = 0x1; +const WRITE = 0x2; +const RW = READ | WRITE; + +/** + * A Reference represents a single occurrence of an identifier in code. + * @constructor Reference + */ +class Reference { + constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { + + /** + * Identifier syntax node. + * @member {espreeIdentifier} Reference#identifier + */ + this.identifier = ident; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { + + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; + + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; + + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * Whether the reference is static. + * @function Reference#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } + + /** + * Whether the reference is writeable. + * @function Reference#isWrite + * @returns {boolean} write + */ + isWrite() { + return !!(this.flag & Reference.WRITE); + } + + /** + * Whether the reference is readable. + * @function Reference#isRead + * @returns {boolean} read + */ + isRead() { + return !!(this.flag & Reference.READ); + } + + /** + * Whether the reference is read-only. + * @function Reference#isReadOnly + * @returns {boolean} read only + */ + isReadOnly() { + return this.flag === Reference.READ; + } + + /** + * Whether the reference is write-only. + * @function Reference#isWriteOnly + * @returns {boolean} write only + */ + isWriteOnly() { + return this.flag === Reference.WRITE; + } + + /** + * Whether the reference is read-write. + * @function Reference#isReadWrite + * @returns {boolean} read write + */ + isReadWrite() { + return this.flag === Reference.RW; + } +} + +/** + * @constant Reference.READ + * @private + */ +Reference.READ = READ; + +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; + +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @constructor Variable + */ +class Variable { + constructor(name, scope) { + + /** + * The variable name, as given in the source code. + * @member {string} Variable#name + */ + this.name = name; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {espree.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} + +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * @constructor Definition + */ +class Definition { + constructor(type, name, node, parent, index, kind) { + + /** + * @member {string} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; + + /** + * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; + + /** + * @member {espree.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; + + /** + * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; + + /** + * @member {number?} Definition#index - the index in the declaration statement. + */ + this.index = index; + + /** + * @member {string?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; + } +} + +/** + * @constructor ParameterDefinition + */ +class ParameterDefinition extends Definition { + constructor(name, node, index, rest) { + super(Variable.Parameter, name, node, null, index, null); + + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + this.rest = rest; + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +const { Syntax: Syntax$2 } = estraverse__default["default"]; + +/** + * Test if scope is struct + * @param {Scope} scope scope + * @param {Block} block block + * @param {boolean} isMethodDefinition is method definition + * @returns {boolean} is strict scope + */ +function isStrictScope(scope, block, isMethodDefinition) { + let body; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === "class" || scope.type === "module") { + return true; + } + + if (scope.type === "block" || scope.type === "switch") { + return false; + } + + if (scope.type === "function") { + if (block.type === Syntax$2.ArrowFunctionExpression && block.body.type !== Syntax$2.BlockStatement) { + return false; + } + + if (block.type === Syntax$2.Program) { + body = block; + } else { + body = block.body; + } + + if (!body) { + return false; + } + } else if (scope.type === "global") { + body = block; + } else { + return false; + } + + // Search for a 'use strict' directive. + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; + + /* + * Check if the current statement is a directive. + * If it isn't, then we're past the directive prologue + * so stop the search because directives cannot + * appear after this point. + * + * Some parsers set `directive:null` on non-directive + * statements, so the `typeof` check is safer than + * checking for property existence. + */ + if (typeof stmt.directive !== "string") { + break; + } + + if (stmt.directive === "use strict") { + return true; + } + } + + return false; +} + +/** + * Register scope + * @param {ScopeManager} scopeManager scope manager + * @param {Scope} scope scope + * @returns {void} + */ +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); + + const scopes = scopeManager.__nodeToScope.get(scope.block); + + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} + +/** + * Should be statically + * @param {Object} def def + * @returns {boolean} should be statically + */ +function shouldBeStatically(def) { + return ( + (def.type === Variable.ClassName) || + (def.type === Variable.Variable && def.parent.kind !== "var") + ); +} + +/** + * @constructor Scope + */ +class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + + /** + * One of "global", "module", "function", "function-expression-name", "block", "switch", "catch", "with", "for", + * "class", "class-field-initializer", "class-static-block". + * @member {string} Scope#type + */ + this.type = type; + + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints + */ + this.taints = new Map(); + + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its parent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; + + /** + * A reference to the scope-defining syntax node. + * @member {espree.Node} Scope#block + */ + this.block = block; + + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + this.type === "global" || + this.type === "module" || + this.type === "function" || + this.type === "class-field-initializer" || + this.type === "class-static-block" + ? this + : upperScope.variableScope; + + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + + this.__left = []; + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; + + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = scopeManager.isStrictModeSupported() + ? isStrictScope(this, block, isMethodDefinition) + : false; + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } + + this.__declaredVariables = scopeManager.__declaredVariables; + + registerScope(scopeManager, this); + } + + __shouldStaticallyClose(scopeManager) { + return (!this.dynamic || scopeManager.__isOptimistic()); + } + + __shouldStaticallyCloseForGlobal(ref) { + + // On global scope, let/const/class declarations should be resolved statically. + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + + const variable = this.set.get(name); + const defs = variable.defs; + + return defs.length > 0 && defs.every(shouldBeStatically); + } + + __staticCloseRef(ref) { + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + + __dynamicCloseRef(ref) { + + // notify all names are through to global + let current = this; + + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + + __globalCloseRef(ref) { + + // let/const/class declarations should be resolved statically. + // others should be resolved dynamically. + if (this.__shouldStaticallyCloseForGlobal(ref)) { + this.__staticCloseRef(ref); + } else { + this.__dynamicCloseRef(ref); + } + } + + __close(scopeManager) { + let closeRef; + + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else if (this.type !== "global") { + closeRef = this.__dynamicCloseRef; + } else { + closeRef = this.__globalCloseRef; + } + + // Try Resolving all references in this scope. + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + closeRef.call(this, ref); + } + this.__left = null; + + return this.upper; + } + + // To override by function scopes. + // References in default parameters isn't resolved to variables which are in their function body. + __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars -- Desired as instance method with signature + return true; + } + + __resolve(ref) { + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + const variable = this.set.get(name); + + if (!this.__isValidResolution(ref, variable)) { + return false; + } + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + + return true; + } + + __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } + + __addDeclaredVariablesOfNode(variable, node) { + if (node === null || node === void 0) { + return; + } + + let variables = this.__declaredVariables.get(node); + + if (variables === null || variables === void 0) { + variables = []; + this.__declaredVariables.set(node, variables); + } + if (!variables.includes(variable)) { + variables.push(variable); + } + } + + __defineGeneric(name, set, variables, node, def) { + let variable; + + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } + + if (def) { + variable.defs.push(def); + this.__addDeclaredVariablesOfNode(variable, def.node); + this.__addDeclaredVariablesOfNode(variable, def.parent); + } + if (node) { + variable.identifiers.push(node); + } + } + + __define(node, def) { + if (node && node.type === Syntax$2.Identifier) { + this.__defineGeneric( + node.name, + this.set, + this.variables, + node, + def + ); + } + } + + __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { + + // because Array element may be null + if (!node || (node.type !== Syntax$2.Identifier && node.type !== "JSXIdentifier")) { + return; + } + + // Specially handle like `this`. + if (node.name === "super") { + return; + } + + const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); + + this.references.push(ref); + this.__left.push(ref); + } + + __detectEval() { + let current = this; + + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } + + __detectThis() { + this.thisFound = true; + } + + __isClosed() { + return this.__left === null; + } + + /** + * returns resolved {Reference} + * @function Scope#resolve + * @param {Espree.Identifier} ident identifier to be resolved. + * @returns {Reference} reference + */ + resolve(ident) { + let ref, i, iz; + + assert(this.__isClosed(), "Scope should be closed."); + assert(ident.type === Syntax$2.Identifier, "Target should be identifier."); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } + + /** + * returns this scope is static + * @function Scope#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.dynamic; + } + + /** + * returns this scope has materialized arguments + * @function Scope#isArgumentsMaterialized + * @returns {boolean} arguemnts materialized + */ + isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this -- Desired as instance method + return true; + } + + /** + * returns this scope has materialized `this` reference + * @function Scope#isThisMaterialized + * @returns {boolean} this materialized + */ + isThisMaterialized() { // eslint-disable-line class-methods-use-this -- Desired as instance method + return true; + } + + isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (let i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } +} + +/** + * Global scope. + */ +class GlobalScope extends Scope { + constructor(scopeManager, block) { + super(scopeManager, "global", null, block, false); + this.implicit = { + set: new Map(), + variables: [], + + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] + }; + } + + __close(scopeManager) { + const implicit = []; + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (let i = 0, iz = implicit.length; i < iz; ++i) { + const info = implicit[i]; + + this.__defineImplicit(info.pattern, + new Definition( + Variable.ImplicitGlobalVariable, + info.pattern, + info.node, + null, + null, + null + )); + + } + + this.implicit.left = this.__left; + + return super.__close(scopeManager); + } + + __defineImplicit(node, def) { + if (node && node.type === Syntax$2.Identifier) { + this.__defineGeneric( + node.name, + this.implicit.set, + this.implicit.variables, + node, + def + ); + } + } +} + +/** + * Module scope. + */ +class ModuleScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "module", upperScope, block, false); + } +} + +/** + * Function expression name scope. + */ +class FunctionExpressionNameScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "function-expression-name", upperScope, block, false); + this.__define(block.id, + new Definition( + Variable.FunctionName, + block.id, + block, + null, + null, + null + )); + this.functionExpressionScope = true; + } +} + +/** + * Catch scope. + */ +class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "catch", upperScope, block, false); + } +} + +/** + * With statement scope. + */ +class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "with", upperScope, block, false); + } + + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; + + return this.upper; + } +} + +/** + * Block scope. + */ +class BlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "block", upperScope, block, false); + } +} + +/** + * Switch scope. + */ +class SwitchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "switch", upperScope, block, false); + } +} + +/** + * Function scope. + */ +class FunctionScope extends Scope { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, "function", upperScope, block, isMethodDefinition); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax$2.ArrowFunctionExpression) { + this.__defineArguments(); + } + } + + isArgumentsMaterialized() { + + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax$2.ArrowFunctionExpression) { + return false; + } + + if (!this.isStatic()) { + return true; + } + + const variable = this.set.get("arguments"); + + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } + + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } + + __defineArguments() { + this.__defineGeneric( + "arguments", + this.set, + this.variables, + null, + null + ); + this.taints.set("arguments", true); + } + + // References in default parameters isn't resolved to variables which are in their function body. + // const x = 1 + // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. + // const x = 2 + // console.log(a) + // } + __isValidResolution(ref, variable) { + + // If `options.nodejsScope` is true, `this.block` becomes a Program node. + if (this.block.type === "Program") { + return true; + } + + const bodyStart = this.block.body.range[0]; + + // It's invalid resolution in the following case: + return !( + variable.scope === this && + ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. + variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body. + ); + } +} + +/** + * Scope of for, for-in, and for-of statements. + */ +class ForScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "for", upperScope, block, false); + } +} + +/** + * Class scope. + */ +class ClassScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class", upperScope, block, false); + } +} + +/** + * Class field initializer scope. + */ +class ClassFieldInitializerScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-field-initializer", upperScope, block, true); + } +} + +/** + * Class static block scope. + */ +class ClassStaticBlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-static-block", upperScope, block, true); + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * @constructor ScopeManager + */ +class ScopeManager { + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + this.__declaredVariables = new WeakMap(); + } + + __isOptimistic() { + return this.__options.optimistic; + } + + __ignoreEval() { + return this.__options.ignoreEval; + } + + __isJSXEnabled() { + return this.__options.jsx === true; + } + + isGlobalReturn() { + return this.__options.nodejsScope || this.__options.sourceType === "commonjs"; + } + + isModule() { + return this.__options.sourceType === "module"; + } + + isImpliedStrict() { + return this.__options.impliedStrict; + } + + isStrictModeSupported() { + return this.__options.ecmaVersion >= 5; + } + + // Returns appropriate scope for this node. + __get(node) { + return this.__nodeToScope.get(node); + } + + /** + * Get variables that are declared by the node. + * + * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. + * If the node declares nothing, this method returns an empty array. + * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. + * @param {Espree.Node} node a node to get. + * @returns {Variable[]} variables that declared by the node. + */ + getDeclaredVariables(node) { + return this.__declaredVariables.get(node) || []; + } + + /** + * acquire scope from node. + * @function ScopeManager#acquire + * @param {Espree.Node} node node for the acquired scope. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} Scope from node + */ + acquire(node, inner) { + + /** + * predicate + * @param {Scope} testScope scope to test + * @returns {boolean} predicate + */ + function predicate(testScope) { + if (testScope.type === "function" && testScope.functionExpressionScope) { + return false; + } + return true; + } + + const scopes = this.__get(node); + + if (!scopes || scopes.length === 0) { + return null; + } + + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } + + if (inner) { + for (let i = scopes.length - 1; i >= 0; --i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } else { + for (let i = 0, iz = scopes.length; i < iz; ++i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } + + return null; + } + + /** + * acquire all scopes from node. + * @function ScopeManager#acquireAll + * @param {Espree.Node} node node for the acquired scope. + * @returns {Scopes?} Scope array + */ + acquireAll(node) { + return this.__get(node); + } + + /** + * release the node. + * @function ScopeManager#release + * @param {Espree.Node} node releasing node. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} upper scope for the node. + */ + release(node, inner) { + const scopes = this.__get(node); + + if (scopes && scopes.length) { + const scope = scopes[0].upper; + + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + + attach() { } // eslint-disable-line class-methods-use-this -- Desired as instance method + + detach() { } // eslint-disable-line class-methods-use-this -- Desired as instance method + + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } + + __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } + + __nestBlockScope(node) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); + } + + __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } + + __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + + __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } + + __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + + __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } + + __nestClassFieldInitializerScope(node) { + return this.__nestScope(new ClassFieldInitializerScope(this, this.__currentScope, node)); + } + + __nestClassStaticBlockScope(node) { + return this.__nestScope(new ClassStaticBlockScope(this, this.__currentScope, node)); + } + + __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } + + __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } + + __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } + + __isES6() { + return this.__options.ecmaVersion >= 6; + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +const { Syntax: Syntax$1 } = estraverse__default["default"]; + +/** + * Get last array element + * @param {Array} xs array + * @returns {any} Last elment + */ +function getLast(xs) { + return xs.at(-1) || null; +} + +/** + * Visitor for destructuring patterns. + */ +class PatternVisitor extends esrecurse__default["default"].Visitor { + static isPattern(node) { + const nodeType = node.type; + + return ( + nodeType === Syntax$1.Identifier || + nodeType === Syntax$1.ObjectPattern || + nodeType === Syntax$1.ArrayPattern || + nodeType === Syntax$1.SpreadElement || + nodeType === Syntax$1.RestElement || + nodeType === Syntax$1.AssignmentPattern + ); + } + + constructor(options, rootPattern, callback) { + super(null, options); + this.rootPattern = rootPattern; + this.callback = callback; + this.assignments = []; + this.rightHandNodes = []; + this.restElements = []; + } + + Identifier(pattern) { + const lastRestElement = getLast(this.restElements); + + this.callback(pattern, { + topLevel: pattern === this.rootPattern, + rest: lastRestElement !== null && lastRestElement !== void 0 && lastRestElement.argument === pattern, + assignments: this.assignments + }); + } + + Property(property) { + + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } + + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); + } + + ArrayPattern(pattern) { + for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { + const element = pattern.elements[i]; + + this.visit(element); + } + } + + AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); + } + + RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); + } + + MemberExpression(node) { + + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } + + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } + + // + // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. + // By spec, LeftHandSideExpression is Pattern or MemberExpression. + // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) + // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... + // + + SpreadElement(node) { + this.visit(node.argument); + } + + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } + + AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); + } + + CallExpression(node) { + + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +const { Syntax } = estraverse__default["default"]; + +/** + * Traverse identifier in pattern + * @param {Object} options options + * @param {pattern} rootPattern root pattern + * @param {Refencer} referencer referencer + * @param {callback} callback callback + * @returns {void} + */ +function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { + + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + const visitor = new PatternVisitor(options, rootPattern, callback); + + visitor.visit(rootPattern); + + // Process the right hand nodes recursively. + if (referencer !== null && referencer !== void 0) { + visitor.rightHandNodes.forEach(referencer.visit, referencer); + } +} + +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. + +/** + * Visitor for import specifiers. + */ +class Importer extends esrecurse__default["default"].Visitor { + constructor(declaration, referencer) { + super(null, referencer.options); + this.declaration = declaration; + this.referencer = referencer; + } + + visitImport(id, specifier) { + this.referencer.visitPattern(id, pattern => { + this.referencer.currentScope().__define(pattern, + new Definition( + Variable.ImportBinding, + pattern, + specifier, + this.declaration, + null, + null + )); + }); + } + + ImportNamespaceSpecifier(node) { + const local = (node.local || node.id); + + if (local) { + this.visitImport(local, node); + } + } + + ImportDefaultSpecifier(node) { + const local = (node.local || node.id); + + this.visitImport(local, node); + } + + ImportSpecifier(node) { + const local = (node.local || node.id); + + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } +} + +/** + * Referencing variables and creating bindings. + */ +class Referencer extends esrecurse__default["default"].Visitor { + constructor(options, scopeManager) { + super(null, options); + this.options = options; + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } + + currentScope() { + return this.scopeManager.__currentScope; + } + + close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + } + } + + pushInnerMethodDefinition(isInnerMethodDefinition) { + const previous = this.isInnerMethodDefinition; + + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } + + popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } + + referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + const scope = this.currentScope(); + + assignments.forEach(assignment => { + scope.__referencing( + pattern, + Reference.WRITE, + assignment.right, + maybeImplicitGlobal, + pattern !== assignment.left, + init + ); + }); + } + + visitPattern(node, options, callback) { + let visitPatternOptions = options; + let visitPatternCallback = callback; + + if (typeof options === "function") { + visitPatternCallback = options; + visitPatternOptions = { processRightHandNodes: false }; + } + + traverseIdentifierInPattern( + this.options, + node, + visitPatternOptions.processRightHandNodes ? this : null, + visitPatternCallback + ); + } + + visitFunction(node) { + let i, iz; + + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. + + if (node.type === Syntax.FunctionDeclaration) { + + // id is defined in upper scope + this.currentScope().__define(node.id, + new Definition( + Variable.FunctionName, + node.id, + node, + null, + null, + null + )); + } + + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } + + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); + + const that = this; + + /** + * Visit pattern callback + * @param {pattern} pattern pattern + * @param {Object} info info + * @returns {void} + */ + function visitPatternCallback(pattern, info) { + that.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + i, + info.rest + )); + + that.referencingDefaultValue(pattern, info.assignments, null, true); + } + + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); + } + + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: "RestElement", + argument: node.rest + }, pattern => { + this.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + node.params.length, + true + )); + }); + } + + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { + + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + } + + this.close(node); + } + + visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node, + null, + null, + null + )); + } + + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node + )); + } + + this.visit(node.superClass); + this.visit(node.body); + + this.close(node); + } + + visitProperty(node) { + let previous; + + if (node.computed) { + this.visit(node.key); + } + + const isMethodDefinition = node.type === Syntax.MethodDefinition; + + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } + + visitForIn(node) { + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, pattern => { + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); + }); + } else { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); + }); + } + this.visit(node.right); + this.visit(node.body); + + this.close(node); + } + + visitVariableDeclaration(variableTargetScope, type, node, index) { + + const decl = node.declarations[index]; + const init = decl.init; + + this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => { + variableTargetScope.__define( + pattern, + new Definition( + type, + pattern, + decl, + node, + index, + node.kind + ) + ); + + this.referencingDefaultValue(pattern, info.assignments, null, true); + if (init) { + this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); + } + }); + } + + AssignmentExpression(node) { + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + + CatchClause(node) { + this.scopeManager.__nestCatchScope(node); + + this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => { + this.currentScope().__define(pattern, + new Definition( + Variable.CatchClause, + pattern, + node, + null, + null, + null + )); + this.referencingDefaultValue(pattern, info.assignments, null, true); + }); + this.visit(node.body); + + this.close(node); + } + + Program(node) { + this.scopeManager.__nestGlobalScope(node); + + if (this.scopeManager.isGlobalReturn()) { + + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } + + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } + + if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; + } + + this.visitChildren(node); + this.close(node); + } + + Identifier(node) { + this.currentScope().__referencing(node); + } + + // eslint-disable-next-line class-methods-use-this -- Desired as instance method + PrivateIdentifier() { + + // Do nothing. + } + + UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } + + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + + Property(node) { + this.visitProperty(node); + } + + PropertyDefinition(node) { + const { computed, key, value } = node; + + if (computed) { + this.visit(key); + } + if (value) { + this.scopeManager.__nestClassFieldInitializerScope(value); + this.visit(value); + this.close(value); + } + } + + StaticBlock(node) { + this.scopeManager.__nestClassStaticBlockScope(node); + + this.visitChildren(node); + + this.close(node); + } + + MethodDefinition(node) { + this.visitProperty(node); + } + + BreakStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + ContinueStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + LabeledStatement(node) { + this.visit(node.body); + } + + ForStatement(node) { + + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ClassExpression(node) { + this.visitClass(node); + } + + ClassDeclaration(node) { + this.visitClass(node); + } + + CallExpression(node) { + + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } + + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + + WithStatement(node) { + this.visit(node.object); + + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + + this.visit(node.body); + + this.close(node); + } + + VariableDeclaration(node) { + const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); + + for (let i = 0, iz = node.declarations.length; i < iz; ++i) { + const decl = node.declarations[i]; + + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } + + // sec 13.11.8 + SwitchStatement(node) { + this.visit(node.discriminant); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } + + for (let i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } + + this.close(node); + } + + FunctionDeclaration(node) { + this.visitFunction(node); + } + + FunctionExpression(node) { + this.visitFunction(node); + } + + ForOfStatement(node) { + this.visitForIn(node); + } + + ForInStatement(node) { + this.visitForIn(node); + } + + ArrowFunctionExpression(node) { + this.visitFunction(node); + } + + ImportDeclaration(node) { + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); + + const importer = new Importer(node, this); + + importer.visit(node); + } + + visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } + + this.visitChildren(node); + } + + // TODO: ExportDeclaration doesn't exist. for bc? + ExportDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportAllDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportDefaultDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportSpecifier(node) { + + // TODO: `node.id` doesn't exist. for bc? + const local = (node.id || node.local); + + this.visit(local); + } + + MetaProperty() { // eslint-disable-line class-methods-use-this -- Desired as instance method + + // do nothing. + } + + JSXIdentifier(node) { + + // Special case: "this" should not count as a reference + if (this.scopeManager.__isJSXEnabled() && node.name !== "this") { + this.currentScope().__referencing(node); + } + } + + JSXMemberExpression(node) { + this.visit(node.object); + } + + JSXElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + this.visit(node.openingElement); + node.children.forEach(this.visit, this); + } else { + this.visitChildren(node); + } + } + + JSXOpeningElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + + const nameNode = node.name; + const isComponentName = nameNode.type === "JSXIdentifier" && nameNode.name[0].toUpperCase() === nameNode.name[0]; + const isComponent = isComponentName || nameNode.type === "JSXMemberExpression"; + + // we only want to visit JSXIdentifier nodes if they are capitalized + if (isComponent) { + this.visit(nameNode); + } + } + + node.attributes.forEach(this.visit, this); + } + + JSXAttribute(node) { + if (node.value) { + this.visit(node.value); + } + } + + JSXExpressionContainer(node) { + this.visit(node.expression); + } + + JSXNamespacedName(node) { + this.visit(node.namespace); + this.visit(node.name); + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +const version = "8.4.0"; + +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * Set the default options + * @returns {Object} options + */ +function defaultOptions() { + return { + optimistic: false, + nodejsScope: false, + impliedStrict: false, + sourceType: "script", // one of ['script', 'module', 'commonjs'] + ecmaVersion: 5, + childVisitorKeys: null, + fallback: "iteration" + }; +} + +/** + * Preform deep update on option object + * @param {Object} target Options + * @param {Object} override Updates + * @returns {Object} Updated options + */ +function updateDeeply(target, override) { + + /** + * Is hash object + * @param {Object} value Test value + * @returns {boolean} Result + */ + function isHashObject(value) { + return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); + } + + for (const key in override) { + if (Object.hasOwn(override, key)) { + const val = override[key]; + + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} + +/** + * Main interface function. Takes an Espree syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {espree.Tree} tree Abstract Syntax Tree + * @param {Object} providedOptions Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] the optimistic flag + * @param {boolean} [providedOptions.ignoreEval=false] whether to check 'eval()' calls + * @param {boolean} [providedOptions.nodejsScope=false] whether the whole + * script is executed under node.js environment. When enabled, escope adds + * a function scope immediately following the global scope. + * @param {boolean} [providedOptions.impliedStrict=false] implied strict mode + * (if ecmaVersion >= 5). + * @param {string} [providedOptions.sourceType='script'] the source type of the script. one of 'script', 'module', and 'commonjs' + * @param {number} [providedOptions.ecmaVersion=5] which ECMAScript version is considered + * @param {boolean} [providedOptions.jsx=false] support JSX references + * @param {Object} [providedOptions.childVisitorKeys=null] Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. + * @param {string} [providedOptions.fallback='iteration'] A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. + * @returns {ScopeManager} ScopeManager + */ +function analyze(tree, providedOptions) { + const options = updateDeeply(defaultOptions(), providedOptions); + const scopeManager = new ScopeManager(options); + const referencer = new Referencer(options, scopeManager); + + referencer.visit(tree); + + assert(scopeManager.__currentScope === null, "currentScope should be null."); + + return scopeManager; +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +exports.Definition = Definition; +exports.PatternVisitor = PatternVisitor; +exports.Reference = Reference; +exports.Referencer = Referencer; +exports.Scope = Scope; +exports.ScopeManager = ScopeManager; +exports.Variable = Variable; +exports.analyze = analyze; +exports.version = version; +//# sourceMappingURL=eslint-scope.cjs.map diff --git a/node_modules/eslint-scope/lib/assert.js b/node_modules/eslint-scope/lib/assert.js new file mode 100644 index 00000000..6300bce7 --- /dev/null +++ b/node_modules/eslint-scope/lib/assert.js @@ -0,0 +1,17 @@ +/** + * @fileoverview Assertion utilities. + * @author Nicholas C. Zakas + */ + +/** + * Throws an error if the given condition is not truthy. + * @param {boolean} condition The condition to check. + * @param {string} message The message to include with the error. + * @returns {void} + * @throws {Error} When the condition is not truthy. + */ +export function assert(condition, message = "Assertion failed.") { + if (!condition) { + throw new Error(message); + } +} diff --git a/node_modules/eslint-scope/lib/definition.js b/node_modules/eslint-scope/lib/definition.js new file mode 100644 index 00000000..9744ef48 --- /dev/null +++ b/node_modules/eslint-scope/lib/definition.js @@ -0,0 +1,85 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +import Variable from "./variable.js"; + +/** + * @constructor Definition + */ +class Definition { + constructor(type, name, node, parent, index, kind) { + + /** + * @member {string} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; + + /** + * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; + + /** + * @member {espree.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; + + /** + * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; + + /** + * @member {number?} Definition#index - the index in the declaration statement. + */ + this.index = index; + + /** + * @member {string?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; + } +} + +/** + * @constructor ParameterDefinition + */ +class ParameterDefinition extends Definition { + constructor(name, node, index, rest) { + super(Variable.Parameter, name, node, null, index, null); + + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + this.rest = rest; + } +} + +export { + ParameterDefinition, + Definition +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/index.js b/node_modules/eslint-scope/lib/index.js new file mode 100644 index 00000000..85f8b510 --- /dev/null +++ b/node_modules/eslint-scope/lib/index.js @@ -0,0 +1,170 @@ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * Escope (escope) is an ECMAScript + * scope analyzer extracted from the esmangle project. + *

+ * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

+ * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. espree is a parser + * that produces such syntax trees. + *

+ * The main interface is the {@link analyze} function. + * @module escope + */ + +import { assert } from "./assert.js"; + +import ScopeManager from "./scope-manager.js"; +import Referencer from "./referencer.js"; +import Reference from "./reference.js"; +import Variable from "./variable.js"; + +import eslintScopeVersion from "./version.js"; + +/** + * Set the default options + * @returns {Object} options + */ +function defaultOptions() { + return { + optimistic: false, + nodejsScope: false, + impliedStrict: false, + sourceType: "script", // one of ['script', 'module', 'commonjs'] + ecmaVersion: 5, + childVisitorKeys: null, + fallback: "iteration" + }; +} + +/** + * Preform deep update on option object + * @param {Object} target Options + * @param {Object} override Updates + * @returns {Object} Updated options + */ +function updateDeeply(target, override) { + + /** + * Is hash object + * @param {Object} value Test value + * @returns {boolean} Result + */ + function isHashObject(value) { + return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); + } + + for (const key in override) { + if (Object.hasOwn(override, key)) { + const val = override[key]; + + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} + +/** + * Main interface function. Takes an Espree syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {espree.Tree} tree Abstract Syntax Tree + * @param {Object} providedOptions Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] the optimistic flag + * @param {boolean} [providedOptions.ignoreEval=false] whether to check 'eval()' calls + * @param {boolean} [providedOptions.nodejsScope=false] whether the whole + * script is executed under node.js environment. When enabled, escope adds + * a function scope immediately following the global scope. + * @param {boolean} [providedOptions.impliedStrict=false] implied strict mode + * (if ecmaVersion >= 5). + * @param {string} [providedOptions.sourceType='script'] the source type of the script. one of 'script', 'module', and 'commonjs' + * @param {number} [providedOptions.ecmaVersion=5] which ECMAScript version is considered + * @param {boolean} [providedOptions.jsx=false] support JSX references + * @param {Object} [providedOptions.childVisitorKeys=null] Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. + * @param {string} [providedOptions.fallback='iteration'] A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. + * @returns {ScopeManager} ScopeManager + */ +function analyze(tree, providedOptions) { + const options = updateDeeply(defaultOptions(), providedOptions); + const scopeManager = new ScopeManager(options); + const referencer = new Referencer(options, scopeManager); + + referencer.visit(tree); + + assert(scopeManager.__currentScope === null, "currentScope should be null."); + + return scopeManager; +} + +export { + + /** @name module:escope.version */ + eslintScopeVersion as version, + + /** @name module:escope.Reference */ + Reference, + + /** @name module:escope.Variable */ + Variable, + + /** @name module:escope.ScopeManager */ + ScopeManager, + + /** @name module:escope.Referencer */ + Referencer, + + analyze +}; + +/** @name module:escope.Definition */ +export { Definition } from "./definition.js"; + +/** @name module:escope.PatternVisitor */ +export { default as PatternVisitor } from "./pattern-visitor.js"; + +/** @name module:escope.Scope */ +export { Scope } from "./scope.js"; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/pattern-visitor.js b/node_modules/eslint-scope/lib/pattern-visitor.js new file mode 100644 index 00000000..367a3773 --- /dev/null +++ b/node_modules/eslint-scope/lib/pattern-visitor.js @@ -0,0 +1,154 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +import estraverse from "estraverse"; +import esrecurse from "esrecurse"; + +const { Syntax } = estraverse; + +/** + * Get last array element + * @param {Array} xs array + * @returns {any} Last elment + */ +function getLast(xs) { + return xs.at(-1) || null; +} + +/** + * Visitor for destructuring patterns. + */ +class PatternVisitor extends esrecurse.Visitor { + static isPattern(node) { + const nodeType = node.type; + + return ( + nodeType === Syntax.Identifier || + nodeType === Syntax.ObjectPattern || + nodeType === Syntax.ArrayPattern || + nodeType === Syntax.SpreadElement || + nodeType === Syntax.RestElement || + nodeType === Syntax.AssignmentPattern + ); + } + + constructor(options, rootPattern, callback) { + super(null, options); + this.rootPattern = rootPattern; + this.callback = callback; + this.assignments = []; + this.rightHandNodes = []; + this.restElements = []; + } + + Identifier(pattern) { + const lastRestElement = getLast(this.restElements); + + this.callback(pattern, { + topLevel: pattern === this.rootPattern, + rest: lastRestElement !== null && lastRestElement !== void 0 && lastRestElement.argument === pattern, + assignments: this.assignments + }); + } + + Property(property) { + + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } + + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); + } + + ArrayPattern(pattern) { + for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { + const element = pattern.elements[i]; + + this.visit(element); + } + } + + AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); + } + + RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); + } + + MemberExpression(node) { + + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } + + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } + + // + // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. + // By spec, LeftHandSideExpression is Pattern or MemberExpression. + // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) + // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... + // + + SpreadElement(node) { + this.visit(node.argument); + } + + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } + + AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); + } + + CallExpression(node) { + + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } +} + +export default PatternVisitor; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/reference.js b/node_modules/eslint-scope/lib/reference.js new file mode 100644 index 00000000..e657d628 --- /dev/null +++ b/node_modules/eslint-scope/lib/reference.js @@ -0,0 +1,166 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +const READ = 0x1; +const WRITE = 0x2; +const RW = READ | WRITE; + +/** + * A Reference represents a single occurrence of an identifier in code. + * @constructor Reference + */ +class Reference { + constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { + + /** + * Identifier syntax node. + * @member {espreeIdentifier} Reference#identifier + */ + this.identifier = ident; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { + + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; + + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; + + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * Whether the reference is static. + * @function Reference#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } + + /** + * Whether the reference is writeable. + * @function Reference#isWrite + * @returns {boolean} write + */ + isWrite() { + return !!(this.flag & Reference.WRITE); + } + + /** + * Whether the reference is readable. + * @function Reference#isRead + * @returns {boolean} read + */ + isRead() { + return !!(this.flag & Reference.READ); + } + + /** + * Whether the reference is read-only. + * @function Reference#isReadOnly + * @returns {boolean} read only + */ + isReadOnly() { + return this.flag === Reference.READ; + } + + /** + * Whether the reference is write-only. + * @function Reference#isWriteOnly + * @returns {boolean} write only + */ + isWriteOnly() { + return this.flag === Reference.WRITE; + } + + /** + * Whether the reference is read-write. + * @function Reference#isReadWrite + * @returns {boolean} read write + */ + isReadWrite() { + return this.flag === Reference.RW; + } +} + +/** + * @constant Reference.READ + * @private + */ +Reference.READ = READ; + +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; + +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; + +export default Reference; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/referencer.js b/node_modules/eslint-scope/lib/referencer.js new file mode 100644 index 00000000..ad88ea20 --- /dev/null +++ b/node_modules/eslint-scope/lib/referencer.js @@ -0,0 +1,708 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +import estraverse from "estraverse"; +import esrecurse from "esrecurse"; +import Reference from "./reference.js"; +import Variable from "./variable.js"; +import PatternVisitor from "./pattern-visitor.js"; +import { Definition, ParameterDefinition } from "./definition.js"; +import { assert } from "./assert.js"; + +const { Syntax } = estraverse; + +/** + * Traverse identifier in pattern + * @param {Object} options options + * @param {pattern} rootPattern root pattern + * @param {Refencer} referencer referencer + * @param {callback} callback callback + * @returns {void} + */ +function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { + + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + const visitor = new PatternVisitor(options, rootPattern, callback); + + visitor.visit(rootPattern); + + // Process the right hand nodes recursively. + if (referencer !== null && referencer !== void 0) { + visitor.rightHandNodes.forEach(referencer.visit, referencer); + } +} + +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. + +/** + * Visitor for import specifiers. + */ +class Importer extends esrecurse.Visitor { + constructor(declaration, referencer) { + super(null, referencer.options); + this.declaration = declaration; + this.referencer = referencer; + } + + visitImport(id, specifier) { + this.referencer.visitPattern(id, pattern => { + this.referencer.currentScope().__define(pattern, + new Definition( + Variable.ImportBinding, + pattern, + specifier, + this.declaration, + null, + null + )); + }); + } + + ImportNamespaceSpecifier(node) { + const local = (node.local || node.id); + + if (local) { + this.visitImport(local, node); + } + } + + ImportDefaultSpecifier(node) { + const local = (node.local || node.id); + + this.visitImport(local, node); + } + + ImportSpecifier(node) { + const local = (node.local || node.id); + + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } +} + +/** + * Referencing variables and creating bindings. + */ +class Referencer extends esrecurse.Visitor { + constructor(options, scopeManager) { + super(null, options); + this.options = options; + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } + + currentScope() { + return this.scopeManager.__currentScope; + } + + close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + } + } + + pushInnerMethodDefinition(isInnerMethodDefinition) { + const previous = this.isInnerMethodDefinition; + + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } + + popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } + + referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + const scope = this.currentScope(); + + assignments.forEach(assignment => { + scope.__referencing( + pattern, + Reference.WRITE, + assignment.right, + maybeImplicitGlobal, + pattern !== assignment.left, + init + ); + }); + } + + visitPattern(node, options, callback) { + let visitPatternOptions = options; + let visitPatternCallback = callback; + + if (typeof options === "function") { + visitPatternCallback = options; + visitPatternOptions = { processRightHandNodes: false }; + } + + traverseIdentifierInPattern( + this.options, + node, + visitPatternOptions.processRightHandNodes ? this : null, + visitPatternCallback + ); + } + + visitFunction(node) { + let i, iz; + + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. + + if (node.type === Syntax.FunctionDeclaration) { + + // id is defined in upper scope + this.currentScope().__define(node.id, + new Definition( + Variable.FunctionName, + node.id, + node, + null, + null, + null + )); + } + + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } + + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); + + const that = this; + + /** + * Visit pattern callback + * @param {pattern} pattern pattern + * @param {Object} info info + * @returns {void} + */ + function visitPatternCallback(pattern, info) { + that.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + i, + info.rest + )); + + that.referencingDefaultValue(pattern, info.assignments, null, true); + } + + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); + } + + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: "RestElement", + argument: node.rest + }, pattern => { + this.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + node.params.length, + true + )); + }); + } + + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { + + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + } + + this.close(node); + } + + visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node, + null, + null, + null + )); + } + + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node + )); + } + + this.visit(node.superClass); + this.visit(node.body); + + this.close(node); + } + + visitProperty(node) { + let previous; + + if (node.computed) { + this.visit(node.key); + } + + const isMethodDefinition = node.type === Syntax.MethodDefinition; + + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } + + visitForIn(node) { + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, pattern => { + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); + }); + } else { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); + }); + } + this.visit(node.right); + this.visit(node.body); + + this.close(node); + } + + visitVariableDeclaration(variableTargetScope, type, node, index) { + + const decl = node.declarations[index]; + const init = decl.init; + + this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => { + variableTargetScope.__define( + pattern, + new Definition( + type, + pattern, + decl, + node, + index, + node.kind + ) + ); + + this.referencingDefaultValue(pattern, info.assignments, null, true); + if (init) { + this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); + } + }); + } + + AssignmentExpression(node) { + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + + CatchClause(node) { + this.scopeManager.__nestCatchScope(node); + + this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => { + this.currentScope().__define(pattern, + new Definition( + Variable.CatchClause, + pattern, + node, + null, + null, + null + )); + this.referencingDefaultValue(pattern, info.assignments, null, true); + }); + this.visit(node.body); + + this.close(node); + } + + Program(node) { + this.scopeManager.__nestGlobalScope(node); + + if (this.scopeManager.isGlobalReturn()) { + + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } + + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } + + if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; + } + + this.visitChildren(node); + this.close(node); + } + + Identifier(node) { + this.currentScope().__referencing(node); + } + + // eslint-disable-next-line class-methods-use-this -- Desired as instance method + PrivateIdentifier() { + + // Do nothing. + } + + UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } + + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + + Property(node) { + this.visitProperty(node); + } + + PropertyDefinition(node) { + const { computed, key, value } = node; + + if (computed) { + this.visit(key); + } + if (value) { + this.scopeManager.__nestClassFieldInitializerScope(value); + this.visit(value); + this.close(value); + } + } + + StaticBlock(node) { + this.scopeManager.__nestClassStaticBlockScope(node); + + this.visitChildren(node); + + this.close(node); + } + + MethodDefinition(node) { + this.visitProperty(node); + } + + BreakStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + ContinueStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + LabeledStatement(node) { + this.visit(node.body); + } + + ForStatement(node) { + + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ClassExpression(node) { + this.visitClass(node); + } + + ClassDeclaration(node) { + this.visitClass(node); + } + + CallExpression(node) { + + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } + + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + + WithStatement(node) { + this.visit(node.object); + + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + + this.visit(node.body); + + this.close(node); + } + + VariableDeclaration(node) { + const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); + + for (let i = 0, iz = node.declarations.length; i < iz; ++i) { + const decl = node.declarations[i]; + + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } + + // sec 13.11.8 + SwitchStatement(node) { + this.visit(node.discriminant); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } + + for (let i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } + + this.close(node); + } + + FunctionDeclaration(node) { + this.visitFunction(node); + } + + FunctionExpression(node) { + this.visitFunction(node); + } + + ForOfStatement(node) { + this.visitForIn(node); + } + + ForInStatement(node) { + this.visitForIn(node); + } + + ArrowFunctionExpression(node) { + this.visitFunction(node); + } + + ImportDeclaration(node) { + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); + + const importer = new Importer(node, this); + + importer.visit(node); + } + + visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } + + this.visitChildren(node); + } + + // TODO: ExportDeclaration doesn't exist. for bc? + ExportDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportAllDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportDefaultDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportSpecifier(node) { + + // TODO: `node.id` doesn't exist. for bc? + const local = (node.id || node.local); + + this.visit(local); + } + + MetaProperty() { // eslint-disable-line class-methods-use-this -- Desired as instance method + + // do nothing. + } + + JSXIdentifier(node) { + + // Special case: "this" should not count as a reference + if (this.scopeManager.__isJSXEnabled() && node.name !== "this") { + this.currentScope().__referencing(node); + } + } + + JSXMemberExpression(node) { + this.visit(node.object); + } + + JSXElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + this.visit(node.openingElement); + node.children.forEach(this.visit, this); + } else { + this.visitChildren(node); + } + } + + JSXOpeningElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + + const nameNode = node.name; + const isComponentName = nameNode.type === "JSXIdentifier" && nameNode.name[0].toUpperCase() === nameNode.name[0]; + const isComponent = isComponentName || nameNode.type === "JSXMemberExpression"; + + // we only want to visit JSXIdentifier nodes if they are capitalized + if (isComponent) { + this.visit(nameNode); + } + } + + node.attributes.forEach(this.visit, this); + } + + JSXAttribute(node) { + if (node.value) { + this.visit(node.value); + } + } + + JSXExpressionContainer(node) { + this.visit(node.expression); + } + + JSXNamespacedName(node) { + this.visit(node.namespace); + this.visit(node.name); + } +} + +export default Referencer; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/scope-manager.js b/node_modules/eslint-scope/lib/scope-manager.js new file mode 100644 index 00000000..b012b646 --- /dev/null +++ b/node_modules/eslint-scope/lib/scope-manager.js @@ -0,0 +1,253 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +import { + BlockScope, + CatchScope, + ClassFieldInitializerScope, + ClassStaticBlockScope, + ClassScope, + ForScope, + FunctionExpressionNameScope, + FunctionScope, + GlobalScope, + ModuleScope, + SwitchScope, + WithScope +} from "./scope.js"; +import { assert } from "./assert.js"; + +/** + * @constructor ScopeManager + */ +class ScopeManager { + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + this.__declaredVariables = new WeakMap(); + } + + __isOptimistic() { + return this.__options.optimistic; + } + + __ignoreEval() { + return this.__options.ignoreEval; + } + + __isJSXEnabled() { + return this.__options.jsx === true; + } + + isGlobalReturn() { + return this.__options.nodejsScope || this.__options.sourceType === "commonjs"; + } + + isModule() { + return this.__options.sourceType === "module"; + } + + isImpliedStrict() { + return this.__options.impliedStrict; + } + + isStrictModeSupported() { + return this.__options.ecmaVersion >= 5; + } + + // Returns appropriate scope for this node. + __get(node) { + return this.__nodeToScope.get(node); + } + + /** + * Get variables that are declared by the node. + * + * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. + * If the node declares nothing, this method returns an empty array. + * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. + * @param {Espree.Node} node a node to get. + * @returns {Variable[]} variables that declared by the node. + */ + getDeclaredVariables(node) { + return this.__declaredVariables.get(node) || []; + } + + /** + * acquire scope from node. + * @function ScopeManager#acquire + * @param {Espree.Node} node node for the acquired scope. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} Scope from node + */ + acquire(node, inner) { + + /** + * predicate + * @param {Scope} testScope scope to test + * @returns {boolean} predicate + */ + function predicate(testScope) { + if (testScope.type === "function" && testScope.functionExpressionScope) { + return false; + } + return true; + } + + const scopes = this.__get(node); + + if (!scopes || scopes.length === 0) { + return null; + } + + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } + + if (inner) { + for (let i = scopes.length - 1; i >= 0; --i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } else { + for (let i = 0, iz = scopes.length; i < iz; ++i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } + + return null; + } + + /** + * acquire all scopes from node. + * @function ScopeManager#acquireAll + * @param {Espree.Node} node node for the acquired scope. + * @returns {Scopes?} Scope array + */ + acquireAll(node) { + return this.__get(node); + } + + /** + * release the node. + * @function ScopeManager#release + * @param {Espree.Node} node releasing node. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} upper scope for the node. + */ + release(node, inner) { + const scopes = this.__get(node); + + if (scopes && scopes.length) { + const scope = scopes[0].upper; + + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + + attach() { } // eslint-disable-line class-methods-use-this -- Desired as instance method + + detach() { } // eslint-disable-line class-methods-use-this -- Desired as instance method + + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } + + __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } + + __nestBlockScope(node) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); + } + + __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } + + __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + + __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } + + __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + + __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } + + __nestClassFieldInitializerScope(node) { + return this.__nestScope(new ClassFieldInitializerScope(this, this.__currentScope, node)); + } + + __nestClassStaticBlockScope(node) { + return this.__nestScope(new ClassStaticBlockScope(this, this.__currentScope, node)); + } + + __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } + + __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } + + __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } + + __isES6() { + return this.__options.ecmaVersion >= 6; + } +} + +export default ScopeManager; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/scope.js b/node_modules/eslint-scope/lib/scope.js new file mode 100644 index 00000000..46eeb771 --- /dev/null +++ b/node_modules/eslint-scope/lib/scope.js @@ -0,0 +1,793 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +import estraverse from "estraverse"; + +import Reference from "./reference.js"; +import Variable from "./variable.js"; +import { Definition } from "./definition.js"; +import { assert } from "./assert.js"; + +const { Syntax } = estraverse; + +/** + * Test if scope is struct + * @param {Scope} scope scope + * @param {Block} block block + * @param {boolean} isMethodDefinition is method definition + * @returns {boolean} is strict scope + */ +function isStrictScope(scope, block, isMethodDefinition) { + let body; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === "class" || scope.type === "module") { + return true; + } + + if (scope.type === "block" || scope.type === "switch") { + return false; + } + + if (scope.type === "function") { + if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) { + return false; + } + + if (block.type === Syntax.Program) { + body = block; + } else { + body = block.body; + } + + if (!body) { + return false; + } + } else if (scope.type === "global") { + body = block; + } else { + return false; + } + + // Search for a 'use strict' directive. + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; + + /* + * Check if the current statement is a directive. + * If it isn't, then we're past the directive prologue + * so stop the search because directives cannot + * appear after this point. + * + * Some parsers set `directive:null` on non-directive + * statements, so the `typeof` check is safer than + * checking for property existence. + */ + if (typeof stmt.directive !== "string") { + break; + } + + if (stmt.directive === "use strict") { + return true; + } + } + + return false; +} + +/** + * Register scope + * @param {ScopeManager} scopeManager scope manager + * @param {Scope} scope scope + * @returns {void} + */ +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); + + const scopes = scopeManager.__nodeToScope.get(scope.block); + + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} + +/** + * Should be statically + * @param {Object} def def + * @returns {boolean} should be statically + */ +function shouldBeStatically(def) { + return ( + (def.type === Variable.ClassName) || + (def.type === Variable.Variable && def.parent.kind !== "var") + ); +} + +/** + * @constructor Scope + */ +class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + + /** + * One of "global", "module", "function", "function-expression-name", "block", "switch", "catch", "with", "for", + * "class", "class-field-initializer", "class-static-block". + * @member {string} Scope#type + */ + this.type = type; + + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints + */ + this.taints = new Map(); + + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its parent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; + + /** + * A reference to the scope-defining syntax node. + * @member {espree.Node} Scope#block + */ + this.block = block; + + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + this.type === "global" || + this.type === "module" || + this.type === "function" || + this.type === "class-field-initializer" || + this.type === "class-static-block" + ? this + : upperScope.variableScope; + + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + + this.__left = []; + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; + + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = scopeManager.isStrictModeSupported() + ? isStrictScope(this, block, isMethodDefinition) + : false; + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } + + this.__declaredVariables = scopeManager.__declaredVariables; + + registerScope(scopeManager, this); + } + + __shouldStaticallyClose(scopeManager) { + return (!this.dynamic || scopeManager.__isOptimistic()); + } + + __shouldStaticallyCloseForGlobal(ref) { + + // On global scope, let/const/class declarations should be resolved statically. + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + + const variable = this.set.get(name); + const defs = variable.defs; + + return defs.length > 0 && defs.every(shouldBeStatically); + } + + __staticCloseRef(ref) { + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + + __dynamicCloseRef(ref) { + + // notify all names are through to global + let current = this; + + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + + __globalCloseRef(ref) { + + // let/const/class declarations should be resolved statically. + // others should be resolved dynamically. + if (this.__shouldStaticallyCloseForGlobal(ref)) { + this.__staticCloseRef(ref); + } else { + this.__dynamicCloseRef(ref); + } + } + + __close(scopeManager) { + let closeRef; + + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else if (this.type !== "global") { + closeRef = this.__dynamicCloseRef; + } else { + closeRef = this.__globalCloseRef; + } + + // Try Resolving all references in this scope. + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + closeRef.call(this, ref); + } + this.__left = null; + + return this.upper; + } + + // To override by function scopes. + // References in default parameters isn't resolved to variables which are in their function body. + __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars -- Desired as instance method with signature + return true; + } + + __resolve(ref) { + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + const variable = this.set.get(name); + + if (!this.__isValidResolution(ref, variable)) { + return false; + } + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + + return true; + } + + __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } + + __addDeclaredVariablesOfNode(variable, node) { + if (node === null || node === void 0) { + return; + } + + let variables = this.__declaredVariables.get(node); + + if (variables === null || variables === void 0) { + variables = []; + this.__declaredVariables.set(node, variables); + } + if (!variables.includes(variable)) { + variables.push(variable); + } + } + + __defineGeneric(name, set, variables, node, def) { + let variable; + + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } + + if (def) { + variable.defs.push(def); + this.__addDeclaredVariablesOfNode(variable, def.node); + this.__addDeclaredVariablesOfNode(variable, def.parent); + } + if (node) { + variable.identifiers.push(node); + } + } + + __define(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.set, + this.variables, + node, + def + ); + } + } + + __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { + + // because Array element may be null + if (!node || (node.type !== Syntax.Identifier && node.type !== "JSXIdentifier")) { + return; + } + + // Specially handle like `this`. + if (node.name === "super") { + return; + } + + const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); + + this.references.push(ref); + this.__left.push(ref); + } + + __detectEval() { + let current = this; + + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } + + __detectThis() { + this.thisFound = true; + } + + __isClosed() { + return this.__left === null; + } + + /** + * returns resolved {Reference} + * @function Scope#resolve + * @param {Espree.Identifier} ident identifier to be resolved. + * @returns {Reference} reference + */ + resolve(ident) { + let ref, i, iz; + + assert(this.__isClosed(), "Scope should be closed."); + assert(ident.type === Syntax.Identifier, "Target should be identifier."); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } + + /** + * returns this scope is static + * @function Scope#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.dynamic; + } + + /** + * returns this scope has materialized arguments + * @function Scope#isArgumentsMaterialized + * @returns {boolean} arguemnts materialized + */ + isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this -- Desired as instance method + return true; + } + + /** + * returns this scope has materialized `this` reference + * @function Scope#isThisMaterialized + * @returns {boolean} this materialized + */ + isThisMaterialized() { // eslint-disable-line class-methods-use-this -- Desired as instance method + return true; + } + + isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (let i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } +} + +/** + * Global scope. + */ +class GlobalScope extends Scope { + constructor(scopeManager, block) { + super(scopeManager, "global", null, block, false); + this.implicit = { + set: new Map(), + variables: [], + + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] + }; + } + + __close(scopeManager) { + const implicit = []; + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (let i = 0, iz = implicit.length; i < iz; ++i) { + const info = implicit[i]; + + this.__defineImplicit(info.pattern, + new Definition( + Variable.ImplicitGlobalVariable, + info.pattern, + info.node, + null, + null, + null + )); + + } + + this.implicit.left = this.__left; + + return super.__close(scopeManager); + } + + __defineImplicit(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.implicit.set, + this.implicit.variables, + node, + def + ); + } + } +} + +/** + * Module scope. + */ +class ModuleScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "module", upperScope, block, false); + } +} + +/** + * Function expression name scope. + */ +class FunctionExpressionNameScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "function-expression-name", upperScope, block, false); + this.__define(block.id, + new Definition( + Variable.FunctionName, + block.id, + block, + null, + null, + null + )); + this.functionExpressionScope = true; + } +} + +/** + * Catch scope. + */ +class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "catch", upperScope, block, false); + } +} + +/** + * With statement scope. + */ +class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "with", upperScope, block, false); + } + + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; + + return this.upper; + } +} + +/** + * Block scope. + */ +class BlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "block", upperScope, block, false); + } +} + +/** + * Switch scope. + */ +class SwitchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "switch", upperScope, block, false); + } +} + +/** + * Function scope. + */ +class FunctionScope extends Scope { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, "function", upperScope, block, isMethodDefinition); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax.ArrowFunctionExpression) { + this.__defineArguments(); + } + } + + isArgumentsMaterialized() { + + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax.ArrowFunctionExpression) { + return false; + } + + if (!this.isStatic()) { + return true; + } + + const variable = this.set.get("arguments"); + + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } + + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } + + __defineArguments() { + this.__defineGeneric( + "arguments", + this.set, + this.variables, + null, + null + ); + this.taints.set("arguments", true); + } + + // References in default parameters isn't resolved to variables which are in their function body. + // const x = 1 + // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. + // const x = 2 + // console.log(a) + // } + __isValidResolution(ref, variable) { + + // If `options.nodejsScope` is true, `this.block` becomes a Program node. + if (this.block.type === "Program") { + return true; + } + + const bodyStart = this.block.body.range[0]; + + // It's invalid resolution in the following case: + return !( + variable.scope === this && + ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. + variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body. + ); + } +} + +/** + * Scope of for, for-in, and for-of statements. + */ +class ForScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "for", upperScope, block, false); + } +} + +/** + * Class scope. + */ +class ClassScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class", upperScope, block, false); + } +} + +/** + * Class field initializer scope. + */ +class ClassFieldInitializerScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-field-initializer", upperScope, block, true); + } +} + +/** + * Class static block scope. + */ +class ClassStaticBlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-static-block", upperScope, block, true); + } +} + +export { + Scope, + GlobalScope, + ModuleScope, + FunctionExpressionNameScope, + CatchScope, + WithScope, + BlockScope, + SwitchScope, + FunctionScope, + ForScope, + ClassScope, + ClassFieldInitializerScope, + ClassStaticBlockScope +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/variable.js b/node_modules/eslint-scope/lib/variable.js new file mode 100644 index 00000000..286202f7 --- /dev/null +++ b/node_modules/eslint-scope/lib/variable.js @@ -0,0 +1,87 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @constructor Variable + */ +class Variable { + constructor(name, scope) { + + /** + * The variable name, as given in the source code. + * @member {string} Variable#name + */ + this.name = name; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {espree.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} + +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + +export default Variable; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/version.js b/node_modules/eslint-scope/lib/version.js new file mode 100644 index 00000000..fc36b2b8 --- /dev/null +++ b/node_modules/eslint-scope/lib/version.js @@ -0,0 +1,3 @@ +const version = "8.4.0"; + +export default version; diff --git a/node_modules/eslint-scope/package.json b/node_modules/eslint-scope/package.json new file mode 100644 index 00000000..e634e45b --- /dev/null +++ b/node_modules/eslint-scope/package.json @@ -0,0 +1,64 @@ +{ + "name": "eslint-scope", + "description": "ECMAScript scope analyzer for ESLint", + "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-scope/README.md", + "main": "./dist/eslint-scope.cjs", + "type": "module", + "exports": { + ".": { + "import": "./lib/index.js", + "require": "./dist/eslint-scope.cjs" + }, + "./package.json": "./package.json" + }, + "version": "8.4.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/eslint-scope" + }, + "funding": "https://opencollective.com/eslint", + "keywords": [ + "eslint" + ], + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "license": "BSD-2-Clause", + "scripts": { + "build": "rollup -c", + "build:update-version": "node tools/update-version.js", + "prepublishOnly": "npm run build:update-version && npm run build", + "pretest": "npm run build", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "node Makefile.js test" + }, + "files": [ + "LICENSE", + "README.md", + "lib", + "dist/eslint-scope.cjs" + ], + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "devDependencies": { + "@typescript-eslint/parser": "^8.7.0", + "chai": "^4.3.4", + "eslint-release": "^3.2.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "npm-license": "^0.3.3", + "rollup": "^2.52.7", + "shelljs": "^0.8.5", + "typescript": "^5.4.2" + } +} diff --git a/node_modules/eslint-visitor-keys/LICENSE b/node_modules/eslint-visitor-keys/LICENSE new file mode 100644 index 00000000..17a25538 --- /dev/null +++ b/node_modules/eslint-visitor-keys/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/eslint-visitor-keys/README.md b/node_modules/eslint-visitor-keys/README.md new file mode 100644 index 00000000..cab81032 --- /dev/null +++ b/node_modules/eslint-visitor-keys/README.md @@ -0,0 +1,105 @@ +# eslint-visitor-keys + +[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) +[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) +[![Build Status](https://github.com/eslint/eslint-visitor-keys/workflows/CI/badge.svg)](https://github.com/eslint/eslint-visitor-keys/actions) + +Constants and utilities about visitor keys to traverse AST. + +## 💿 Installation + +Use [npm] to install. + +```bash +$ npm install eslint-visitor-keys +``` + +### Requirements + +- [Node.js] `^12.22.0`, `^14.17.0`, or `>=16.0.0` + + +## 📖 Usage + +To use in an ESM file: + +```js +import * as evk from "eslint-visitor-keys" +``` + +To use in a CommonJS file: + +```js +const evk = require("eslint-visitor-keys") +``` + +### evk.KEYS + +> type: `{ [type: string]: string[] | undefined }` + +Visitor keys. This keys are frozen. + +This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. + +For example: + +``` +console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] +``` + +### evk.getKeys(node) + +> type: `(node: object) => string[]` + +Get the visitor keys of a given AST node. + +This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. + +This will be used to traverse unknown nodes. + +For example: + +```js +const node = { + type: "AssignmentExpression", + left: { type: "Identifier", name: "foo" }, + right: { type: "Literal", value: 0 } +} +console.log(evk.getKeys(node)) // → ["type", "left", "right"] +``` + +### evk.unionWith(additionalKeys) + +> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` + +Make the union set with `evk.KEYS` and the given keys. + +- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. +- It removes duplicated keys as keeping the first one. + +For example: + +```js +console.log(evk.unionWith({ + MethodDefinition: ["decorators"] +})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } +``` + +## 📰 Change log + +See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). + +## 🍻 Contributing + +Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). + +### Development commands + +- `npm test` runs tests and measures code coverage. +- `npm run lint` checks source codes with ESLint. +- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser. + + +[npm]: https://www.npmjs.com/ +[Node.js]: https://nodejs.org/ +[ESTree]: https://github.com/estree/estree diff --git a/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs b/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs new file mode 100644 index 00000000..00f91bcc --- /dev/null +++ b/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs @@ -0,0 +1,384 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source" + ], + ExportSpecifier: [ + "exported", + "local" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportDeclaration: [ + "specifiers", + "source" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + +/** + * Get visitor keys of a given node. + * @param {object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +function getKeys(node) { + return Object.keys(node).filter(filterKey); +} + +// Disable valid-jsdoc rule because it reports syntax error on the type of @returns. +// eslint-disable-next-line valid-jsdoc +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +function unionWith(additionalKeys) { + const retv = /** @type {{ + [type: string]: ReadonlyArray + }} */ (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.prototype.hasOwnProperty.call(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +exports.KEYS = KEYS; +exports.getKeys = getKeys; +exports.unionWith = unionWith; diff --git a/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts b/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts new file mode 100644 index 00000000..c7c28ed3 --- /dev/null +++ b/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts @@ -0,0 +1,27 @@ +type VisitorKeys$1 = { + readonly [type: string]: readonly string[]; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys$1; + +/** + * Get visitor keys of a given node. + * @param {object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +declare function getKeys(node: object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys; + +type VisitorKeys = VisitorKeys$1; + +export { KEYS, VisitorKeys, getKeys, unionWith }; diff --git a/node_modules/eslint-visitor-keys/dist/index.d.ts b/node_modules/eslint-visitor-keys/dist/index.d.ts new file mode 100644 index 00000000..46bd87e2 --- /dev/null +++ b/node_modules/eslint-visitor-keys/dist/index.d.ts @@ -0,0 +1,16 @@ +/** + * Get visitor keys of a given node. + * @param {object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node: object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys: VisitorKeys): VisitorKeys; +export { KEYS }; +export type VisitorKeys = import('./visitor-keys.js').VisitorKeys; +import KEYS from "./visitor-keys.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts b/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts new file mode 100644 index 00000000..57a952c5 --- /dev/null +++ b/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts @@ -0,0 +1,12 @@ +export default KEYS; +export type VisitorKeys = { + readonly [type: string]: readonly string[]; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys; +//# sourceMappingURL=visitor-keys.d.ts.map \ No newline at end of file diff --git a/node_modules/eslint-visitor-keys/lib/index.js b/node_modules/eslint-visitor-keys/lib/index.js new file mode 100644 index 00000000..3622816d --- /dev/null +++ b/node_modules/eslint-visitor-keys/lib/index.js @@ -0,0 +1,65 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +import KEYS from "./visitor-keys.js"; + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + +/** + * Get visitor keys of a given node. + * @param {object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node) { + return Object.keys(node).filter(filterKey); +} + +// Disable valid-jsdoc rule because it reports syntax error on the type of @returns. +// eslint-disable-next-line valid-jsdoc +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys) { + const retv = /** @type {{ + [type: string]: ReadonlyArray + }} */ (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.prototype.hasOwnProperty.call(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +export { KEYS }; diff --git a/node_modules/eslint-visitor-keys/lib/visitor-keys.js b/node_modules/eslint-visitor-keys/lib/visitor-keys.js new file mode 100644 index 00000000..ccf2b1f9 --- /dev/null +++ b/node_modules/eslint-visitor-keys/lib/visitor-keys.js @@ -0,0 +1,315 @@ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source" + ], + ExportSpecifier: [ + "exported", + "local" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportDeclaration: [ + "specifiers", + "source" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +export default KEYS; diff --git a/node_modules/eslint-visitor-keys/package.json b/node_modules/eslint-visitor-keys/package.json new file mode 100644 index 00000000..b9d51ce0 --- /dev/null +++ b/node_modules/eslint-visitor-keys/package.json @@ -0,0 +1,74 @@ +{ + "name": "eslint-visitor-keys", + "version": "3.4.3", + "description": "Constants and utilities about visitor keys to traverse AST.", + "type": "module", + "main": "dist/eslint-visitor-keys.cjs", + "types": "./dist/index.d.ts", + "exports": { + ".": [ + { + "import": "./lib/index.js", + "require": "./dist/eslint-visitor-keys.cjs" + }, + "./dist/eslint-visitor-keys.cjs" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist/index.d.ts", + "dist/visitor-keys.d.ts", + "dist/eslint-visitor-keys.cjs", + "dist/eslint-visitor-keys.d.cts", + "lib" + ], + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "devDependencies": { + "@types/estree": "^0.0.51", + "@types/estree-jsx": "^0.0.1", + "@typescript-eslint/parser": "^5.14.0", + "c8": "^7.11.0", + "chai": "^4.3.6", + "eslint": "^7.29.0", + "eslint-config-eslint": "^7.0.0", + "eslint-plugin-jsdoc": "^35.4.0", + "eslint-plugin-node": "^11.1.0", + "eslint-release": "^3.2.0", + "esquery": "^1.4.0", + "json-diff": "^0.7.3", + "mocha": "^9.2.1", + "opener": "^1.5.2", + "rollup": "^2.70.0", + "rollup-plugin-dts": "^4.2.3", + "tsd": "^0.19.1", + "typescript": "^4.6.2" + }, + "scripts": { + "build": "npm run build:cjs && npm run build:types", + "build:cjs": "rollup -c", + "build:debug": "npm run build:cjs -- -m && npm run build:types", + "build:keys": "node tools/build-keys-from-ts", + "build:types": "tsc", + "lint": "eslint .", + "prepare": "npm run build", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "mocha tests/lib/**/*.cjs && c8 mocha tests/lib/**/*.js && npm run test:types", + "test:open-coverage": "c8 report --reporter lcov && opener coverage/lcov-report/index.html", + "test:types": "tsd" + }, + "repository": "eslint/eslint-visitor-keys", + "funding": "https://opencollective.com/eslint", + "keywords": [], + "author": "Toru Nagashima (https://github.com/mysticatea)", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/eslint-visitor-keys/issues" + }, + "homepage": "https://github.com/eslint/eslint-visitor-keys#readme" +} diff --git a/node_modules/eslint/LICENSE b/node_modules/eslint/LICENSE new file mode 100644 index 00000000..b607bb36 --- /dev/null +++ b/node_modules/eslint/LICENSE @@ -0,0 +1,19 @@ +Copyright OpenJS Foundation and other contributors, + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/eslint/README.md b/node_modules/eslint/README.md new file mode 100644 index 00000000..ae6b9358 --- /dev/null +++ b/node_modules/eslint/README.md @@ -0,0 +1,340 @@ +[![npm version](https://img.shields.io/npm/v/eslint.svg)](https://www.npmjs.com/package/eslint) +[![Downloads](https://img.shields.io/npm/dm/eslint.svg)](https://www.npmjs.com/package/eslint) +[![Build Status](https://github.com/eslint/eslint/workflows/CI/badge.svg)](https://github.com/eslint/eslint/actions) +
+[![Open Collective Backers](https://img.shields.io/opencollective/backers/eslint)](https://opencollective.com/eslint) +[![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/eslint)](https://opencollective.com/eslint) + +# ESLint + +[Website](https://eslint.org) | +[Configure ESLint](https://eslint.org/docs/latest/use/configure) | +[Rules](https://eslint.org/docs/rules/) | +[Contribute to ESLint](https://eslint.org/docs/latest/contribute) | +[Report Bugs](https://eslint.org/docs/latest/contribute/report-bugs) | +[Code of Conduct](https://eslint.org/conduct) | +[Twitter](https://twitter.com/geteslint) | +[Discord](https://eslint.org/chat) | +[Mastodon](https://fosstodon.org/@eslint) | +[Bluesky](https://bsky.app/profile/eslint.org) + +ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: + +- ESLint uses [Espree](https://github.com/eslint/js/tree/main/packages/espree) for JavaScript parsing. +- ESLint uses an AST to evaluate patterns in code. +- ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. + +## Table of Contents + +1. [Installation and Usage](#installation-and-usage) +1. [Configuration](#configuration) +1. [Version Support](#version-support) +1. [Code of Conduct](#code-of-conduct) +1. [Filing Issues](#filing-issues) +1. [Frequently Asked Questions](#frequently-asked-questions) +1. [Releases](#releases) +1. [Security Policy](#security-policy) +1. [Semantic Versioning Policy](#semantic-versioning-policy) +1. [License](#license) +1. [Team](#team) +1. [Sponsors](#sponsors) +1. [Technology Sponsors](#technology-sponsors) + +## Installation and Usage + +Prerequisites: [Node.js](https://nodejs.org/) (`^18.18.0`, `^20.9.0`, or `>=21.1.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) + +You can install and configure ESLint using this command: + +```shell +npm init @eslint/config@latest +``` + +After that, you can run ESLint on any file or directory like this: + +```shell +npx eslint yourfile.js +``` + +### pnpm Installation + +To use ESLint with pnpm, we recommend setting up a `.npmrc` file with at least the following settings: + +```text +auto-install-peers=true +node-linker=hoisted +``` + +This ensures that pnpm installs dependencies in a way that is more compatible with npm and is less likely to produce errors. + +## Configuration + +You can configure rules in your `eslint.config.js` files as in this example: + +```js +import { defineConfig } from "eslint/config"; + +export default defineConfig([ + { + files: ["**/*.js", "**/*.cjs", "**/*.mjs"], + rules: { + "prefer-const": "warn", + "no-constant-binary-expression": "error", + }, + }, +]); +``` + +The names `"prefer-const"` and `"no-constant-binary-expression"` are the names of [rules](https://eslint.org/docs/rules) in ESLint. The first value is the error level of the rule and can be one of these values: + +- `"off"` or `0` - turn the rule off +- `"warn"` or `1` - turn the rule on as a warning (doesn't affect exit code) +- `"error"` or `2` - turn the rule on as an error (exit code will be 1) + +The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/latest/use/configure)). + +## Version Support + +The ESLint team provides ongoing support for the current version and six months of limited support for the previous version. Limited support includes critical bug fixes, security issues, and compatibility issues only. + +ESLint offers commercial support for both current and previous versions through our partners, [Tidelift][tidelift] and [HeroDevs][herodevs]. + +See [Version Support](https://eslint.org/version-support) for more details. + +## Code of Conduct + +ESLint adheres to the [OpenJS Foundation Code of Conduct](https://eslint.org/conduct). + +## Filing Issues + +Before filing an issue, please be sure to read the guidelines for what you're reporting: + +- [Bug Report](https://eslint.org/docs/latest/contribute/report-bugs) +- [Propose a New Rule](https://eslint.org/docs/latest/contribute/propose-new-rule) +- [Proposing a Rule Change](https://eslint.org/docs/latest/contribute/propose-rule-change) +- [Request a Change](https://eslint.org/docs/latest/contribute/request-change) + +## Frequently Asked Questions + +### Does ESLint support JSX? + +Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/latest/use/configure)). Please note that supporting JSX syntax _is not_ the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics. + +### Does Prettier replace ESLint? + +No, ESLint and Prettier have different jobs: ESLint is a linter (looking for problematic patterns) and Prettier is a code formatter. Using both tools is common, refer to [Prettier's documentation](https://prettier.io/docs/en/install#eslint-and-other-linters) to learn how to configure them to work well with each other. + +### What ECMAScript versions does ESLint support? + +ESLint has full support for ECMAScript 3, 5, and every year from 2015 up until the most recent stage 4 specification (the default). You can set your desired ECMAScript syntax and other settings (like global variables) through [configuration](https://eslint.org/docs/latest/use/configure). + +### What about experimental features? + +ESLint's parser only officially supports the latest final ECMAScript standard. We will make changes to core rules in order to avoid crashes on stage 3 ECMAScript syntax proposals (as long as they are implemented using the correct experimental ESTree syntax). We may make changes to core rules to better work with language extensions (such as JSX, Flow, and TypeScript) on a case-by-case basis. + +In other cases (including if rules need to warn on more or fewer cases due to new syntax, rather than just not crashing), we recommend you use other parsers and/or rule plugins. If you are using Babel, you can use [@babel/eslint-parser](https://www.npmjs.com/package/@babel/eslint-parser) and [@babel/eslint-plugin](https://www.npmjs.com/package/@babel/eslint-plugin) to use any option available in Babel. + +Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](https://eslint.org/docs/latest/contribute). Until then, please use the appropriate parser and plugin(s) for your experimental feature. + +### Which Node.js versions does ESLint support? + +ESLint updates the supported Node.js versions with each major release of ESLint. At that time, ESLint's supported Node.js versions are updated to be: + +1. The most recent maintenance release of Node.js +1. The lowest minor version of the Node.js LTS release that includes the features the ESLint team wants to use. +1. The Node.js Current release + +ESLint is also expected to work with Node.js versions released after the Node.js Current release. + +Refer to the [Quick Start Guide](https://eslint.org/docs/latest/use/getting-started#prerequisites) for the officially supported Node.js versions for a given ESLint release. + +### Where to ask for help? + +Open a [discussion](https://github.com/eslint/eslint/discussions) or stop by our [Discord server](https://eslint.org/chat). + +### Why doesn't ESLint lock dependency versions? + +Lock files like `package-lock.json` are helpful for deployed applications. They ensure that dependencies are consistent between environments and across deployments. + +Packages like `eslint` that get published to the npm registry do not include lock files. `npm install eslint` as a user will respect version constraints in ESLint's `package.json`. ESLint and its dependencies will be included in the user's lock file if one exists, but ESLint's own lock file would not be used. + +We intentionally don't lock dependency versions so that we have the latest compatible dependency versions in development and CI that our users get when installing ESLint in a project. + +The Twilio blog has a [deeper dive](https://www.twilio.com/blog/lockfiles-nodejs) to learn more. + +## Releases + +We have scheduled releases every two weeks on Friday or Saturday. You can follow a [release issue](https://github.com/eslint/eslint/issues?q=is%3Aopen+is%3Aissue+label%3Arelease) for updates about the scheduling of any particular release. + +## Security Policy + +ESLint takes security seriously. We work hard to ensure that ESLint is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). + +## Semantic Versioning Policy + +ESLint follows [semantic versioning](https://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: + +- Patch release (intended to not break your lint build) + - A bug fix in a rule that results in ESLint reporting fewer linting errors. + - A bug fix to the CLI or core (including formatters). + - Improvements to documentation. + - Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage. + - Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone). +- Minor release (might break your lint build) + - A bug fix in a rule that results in ESLint reporting more linting errors. + - A new rule is created. + - A new option to an existing rule that does not result in ESLint reporting more linting errors by default. + - A new addition to an existing rule to support a newly-added language feature (within the last 12 months) that will result in ESLint reporting more linting errors by default. + - An existing rule is deprecated. + - A new CLI capability is created. + - New capabilities to the public API are added (new classes, new methods, new arguments to existing methods, etc.). + - A new formatter is created. + - `eslint:recommended` is updated and will result in strictly fewer linting errors (e.g., rule removals). +- Major release (likely to break your lint build) + - `eslint:recommended` is updated and may result in new linting errors (e.g., rule additions, most rule option updates). + - A new option to an existing rule that results in ESLint reporting more linting errors by default. + - An existing formatter is removed. + - Part of the public API is removed or changed in an incompatible way. The public API includes: + - Rule schemas + - Configuration schema + - Command-line options + - Node.js API + - Rule, formatter, parser, plugin APIs + +According to our policy, any minor update may report more linting errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. + +## License + +MIT License + +Copyright OpenJS Foundation and other contributors, + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +## Team + +These folks keep the project moving and are resources for help. + + + + + +### Technical Steering Committee (TSC) + +The people who manage releases, review feature requests, and meet regularly to ensure ESLint is properly maintained. + +
+ +Nicholas C. Zakas's Avatar
+Nicholas C. Zakas +
+
+ +Francesco Trotta's Avatar
+Francesco Trotta +
+
+ +Milos Djermanovic's Avatar
+Milos Djermanovic +
+
+ +### Reviewers + +The people who review and implement new features. + +
+ +唯然's Avatar
+唯然 +
+
+ +Nitin Kumar's Avatar
+Nitin Kumar +
+
+ +### Committers + +The people who review and fix bugs and help triage issues. + +
+ +Josh Goldberg ✨'s Avatar
+Josh Goldberg ✨ +
+
+ +Tanuj Kanti's Avatar
+Tanuj Kanti +
+
+ +루밀LuMir's Avatar
+루밀LuMir +
+
+ +### Website Team + +Team members who focus specifically on eslint.org + +
+ +Amaresh  S M's Avatar
+Amaresh S M +
+
+ +Harish's Avatar
+Harish +
+
+ +Percy Ma's Avatar
+Percy Ma +
+
+ + + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ + + +[tidelift]: https://tidelift.com/funding/github/npm/eslint +[herodevs]: https://www.herodevs.com/support/eslint-nes?utm_source=ESLintWebsite&utm_medium=ESLintWebsite&utm_campaign=ESLintNES&utm_id=ESLintNES diff --git a/node_modules/eslint/bin/eslint.js b/node_modules/eslint/bin/eslint.js new file mode 100755 index 00000000..9b202a98 --- /dev/null +++ b/node_modules/eslint/bin/eslint.js @@ -0,0 +1,196 @@ +#!/usr/bin/env node + +/** + * @fileoverview Main CLI that is run via the eslint command. + * @author Nicholas C. Zakas + */ + +/* eslint no-console:off -- CLI */ + +"use strict"; + +const mod = require("node:module"); + +// to use V8's code cache to speed up instantiation time +mod.enableCompileCache?.(); + +// must do this initialization *before* other requires in order to work +if (process.argv.includes("--debug")) { + require("debug").enable("eslint:*,-eslint:code-path,eslintrc:*"); +} + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Read data from stdin til the end. + * + * Note: See + * - https://github.com/nodejs/node/blob/master/doc/api/process.md#processstdin + * - https://github.com/nodejs/node/blob/master/doc/api/process.md#a-note-on-process-io + * - https://lists.gnu.org/archive/html/bug-gnu-emacs/2016-01/msg00419.html + * - https://github.com/nodejs/node/issues/7439 (historical) + * + * On Windows using `fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")` seems + * to read 4096 bytes before blocking and never drains to read further data. + * + * The investigation on the Emacs thread indicates: + * + * > Emacs on MS-Windows uses pipes to communicate with subprocesses; a + * > pipe on Windows has a 4K buffer. So as soon as Emacs writes more than + * > 4096 bytes to the pipe, the pipe becomes full, and Emacs then waits for + * > the subprocess to read its end of the pipe, at which time Emacs will + * > write the rest of the stuff. + * @returns {Promise} The read text. + */ +function readStdin() { + return new Promise((resolve, reject) => { + let content = ""; + let chunk = ""; + + process.stdin + .setEncoding("utf8") + .on("readable", () => { + while ((chunk = process.stdin.read()) !== null) { + content += chunk; + } + }) + .on("end", () => resolve(content)) + .on("error", reject); + }); +} + +/** + * Get the error message of a given value. + * @param {any} error The value to get. + * @returns {string} The error message. + */ +function getErrorMessage(error) { + // Lazy loading because this is used only if an error happened. + const util = require("node:util"); + + // Foolproof -- third-party module might throw non-object. + if (typeof error !== "object" || error === null) { + return String(error); + } + + // Use templates if `error.messageTemplate` is present. + if (typeof error.messageTemplate === "string") { + try { + const template = require(`../messages/${error.messageTemplate}.js`); + + return template(error.messageData || {}); + } catch { + // Ignore template error then fallback to use `error.stack`. + } + } + + // Use the stacktrace if it's an error object. + if (typeof error.stack === "string") { + return error.stack; + } + + // Otherwise, dump the object. + return util.format("%o", error); +} + +/** + * Tracks error messages that are shown to the user so we only ever show the + * same message once. + * @type {Set} + */ +const displayedErrors = new Set(); + +/** + * Tracks whether an unexpected error was caught + * @type {boolean} + */ +let hadFatalError = false; + +/** + * Catch and report unexpected error. + * @param {any} error The thrown error object. + * @returns {void} + */ +function onFatalError(error) { + process.exitCode = 2; + hadFatalError = true; + + const { version } = require("../package.json"); + const message = ` +Oops! Something went wrong! :( + +ESLint: ${version} + +${getErrorMessage(error)}`; + + if (!displayedErrors.has(message)) { + console.error(message); + displayedErrors.add(message); + } +} + +//------------------------------------------------------------------------------ +// Execution +//------------------------------------------------------------------------------ + +(async function main() { + process.on("uncaughtException", onFatalError); + process.on("unhandledRejection", onFatalError); + + // Call the config initializer if `--init` is present. + if (process.argv.includes("--init")) { + // `eslint --init` has been moved to `@eslint/create-config` + console.warn( + "You can also run this command directly using 'npm init @eslint/config@latest'.", + ); + + const spawn = require("cross-spawn"); + + spawn.sync("npm", ["init", "@eslint/config@latest"], { + encoding: "utf8", + stdio: "inherit", + }); + return; + } + + // start the MCP server if `--mcp` is present + if (process.argv.includes("--mcp")) { + console.warn( + "You can also run this command directly using 'npx @eslint/mcp@latest'.", + ); + + const spawn = require("cross-spawn"); + + spawn.sync("npx", ["@eslint/mcp@latest"], { + encoding: "utf8", + stdio: "inherit", + }); + return; + } + + // Otherwise, call the CLI. + const cli = require("../lib/cli"); + const exitCode = await cli.execute( + process.argv, + process.argv.includes("--stdin") ? await readStdin() : null, + true, + ); + + /* + * If an uncaught exception or unhandled rejection was detected in the meantime, + * keep the fatal exit code 2 that is already assigned to `process.exitCode`. + * Without this condition, exit code 2 (unsuccessful execution) could be overwritten with + * 1 (successful execution, lint problems found) or even 0 (successful execution, no lint problems found). + * This ensures that unexpected errors that seemingly don't affect the success + * of the execution will still cause a non-zero exit code, as it's a common + * practice and the default behavior of Node.js to exit with non-zero + * in case of an uncaught exception or unhandled rejection. + * + * Otherwise, assign the exit code returned from CLI. + */ + if (!hadFatalError) { + process.exitCode = exitCode; + } +})().catch(onFatalError); diff --git a/node_modules/eslint/conf/default-cli-options.js b/node_modules/eslint/conf/default-cli-options.js new file mode 100644 index 00000000..dda88d65 --- /dev/null +++ b/node_modules/eslint/conf/default-cli-options.js @@ -0,0 +1,32 @@ +/** + * @fileoverview Default CLIEngineOptions. + * @author Ian VanSchooten + */ + +"use strict"; + +module.exports = { + configFile: null, + baseConfig: false, + rulePaths: [], + useEslintrc: true, + envs: [], + globals: [], + extensions: null, + ignore: true, + ignorePath: void 0, + cache: false, + + /* + * in order to honor the cacheFile option if specified + * this option should not have a default value otherwise + * it will always be used + */ + cacheLocation: "", + cacheFile: ".eslintcache", + cacheStrategy: "metadata", + fix: false, + allowInlineConfig: true, + reportUnusedDisableDirectives: void 0, + globInputPaths: true, +}; diff --git a/node_modules/eslint/conf/ecma-version.js b/node_modules/eslint/conf/ecma-version.js new file mode 100644 index 00000000..e68d3020 --- /dev/null +++ b/node_modules/eslint/conf/ecma-version.js @@ -0,0 +1,16 @@ +/** + * @fileoverview Configuration related to ECMAScript versions + * @author Milos Djermanovic + */ + +"use strict"; + +/** + * The latest ECMAScript version supported by ESLint. + * @type {number} year-based ECMAScript version + */ +const LATEST_ECMA_VERSION = 2026; + +module.exports = { + LATEST_ECMA_VERSION, +}; diff --git a/node_modules/eslint/conf/globals.js b/node_modules/eslint/conf/globals.js new file mode 100644 index 00000000..b630b272 --- /dev/null +++ b/node_modules/eslint/conf/globals.js @@ -0,0 +1,169 @@ +/** + * @fileoverview Globals for ecmaVersion/sourceType + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Globals +//----------------------------------------------------------------------------- + +const commonjs = { + exports: true, + global: false, + module: false, + require: false, +}; + +const es3 = { + Array: false, + Boolean: false, + constructor: false, + Date: false, + decodeURI: false, + decodeURIComponent: false, + encodeURI: false, + encodeURIComponent: false, + Error: false, + escape: false, + eval: false, + EvalError: false, + Function: false, + hasOwnProperty: false, + Infinity: false, + isFinite: false, + isNaN: false, + isPrototypeOf: false, + Math: false, + NaN: false, + Number: false, + Object: false, + parseFloat: false, + parseInt: false, + propertyIsEnumerable: false, + RangeError: false, + ReferenceError: false, + RegExp: false, + String: false, + SyntaxError: false, + toLocaleString: false, + toString: false, + TypeError: false, + undefined: false, + unescape: false, + URIError: false, + valueOf: false, +}; + +const es5 = { + ...es3, + JSON: false, +}; + +const es2015 = { + ...es5, + ArrayBuffer: false, + DataView: false, + Float32Array: false, + Float64Array: false, + Int16Array: false, + Int32Array: false, + Int8Array: false, + Intl: false, + Map: false, + Promise: false, + Proxy: false, + Reflect: false, + Set: false, + Symbol: false, + Uint16Array: false, + Uint32Array: false, + Uint8Array: false, + Uint8ClampedArray: false, + WeakMap: false, + WeakSet: false, +}; + +// no new globals in ES2016 +const es2016 = { + ...es2015, +}; + +const es2017 = { + ...es2016, + Atomics: false, + SharedArrayBuffer: false, +}; + +// no new globals in ES2018 +const es2018 = { + ...es2017, +}; + +// no new globals in ES2019 +const es2019 = { + ...es2018, +}; + +const es2020 = { + ...es2019, + BigInt: false, + BigInt64Array: false, + BigUint64Array: false, + globalThis: false, +}; + +const es2021 = { + ...es2020, + AggregateError: false, + FinalizationRegistry: false, + WeakRef: false, +}; + +const es2022 = { + ...es2021, +}; + +const es2023 = { + ...es2022, +}; + +const es2024 = { + ...es2023, +}; + +const es2025 = { + ...es2024, + Float16Array: false, + Iterator: false, +}; + +const es2026 = { + ...es2025, + AsyncDisposableStack: false, + DisposableStack: false, + SuppressedError: false, +}; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + commonjs, + es3, + es5, + es2015, + es2016, + es2017, + es2018, + es2019, + es2020, + es2021, + es2022, + es2023, + es2024, + es2025, + es2026, +}; diff --git a/node_modules/eslint/conf/replacements.json b/node_modules/eslint/conf/replacements.json new file mode 100644 index 00000000..27329c4c --- /dev/null +++ b/node_modules/eslint/conf/replacements.json @@ -0,0 +1,26 @@ +{ + "rules": { + "generator-star": ["generator-star-spacing"], + "global-strict": ["strict"], + "no-arrow-condition": ["no-confusing-arrow", "no-constant-condition"], + "no-comma-dangle": ["comma-dangle"], + "no-empty-class": ["no-empty-character-class"], + "no-empty-label": ["no-labels"], + "no-extra-strict": ["strict"], + "no-reserved-keys": ["quote-props"], + "no-space-before-semi": ["semi-spacing"], + "no-wrap-func": ["no-extra-parens"], + "space-after-function-name": ["space-before-function-paren"], + "space-after-keywords": ["keyword-spacing"], + "space-before-function-parentheses": ["space-before-function-paren"], + "space-before-keywords": ["keyword-spacing"], + "space-in-brackets": [ + "object-curly-spacing", + "array-bracket-spacing", + "computed-property-spacing" + ], + "space-return-throw-case": ["keyword-spacing"], + "space-unary-word-ops": ["space-unary-ops"], + "spaced-line-comment": ["spaced-comment"] + } +} diff --git a/node_modules/eslint/conf/rule-type-list.json b/node_modules/eslint/conf/rule-type-list.json new file mode 100644 index 00000000..05ddd3cb --- /dev/null +++ b/node_modules/eslint/conf/rule-type-list.json @@ -0,0 +1,91 @@ +{ + "types": { + "problem": [], + "suggestion": [], + "layout": [] + }, + "deprecated": [], + "removed": [ + { + "removed": "generator-star", + "replacedBy": [{ "rule": { "name": "generator-star-spacing" } }] + }, + { + "removed": "global-strict", + "replacedBy": [{ "rule": { "name": "strict" } }] + }, + { + "removed": "no-arrow-condition", + "replacedBy": [ + { "rule": { "name": "no-confusing-arrow" } }, + { "rule": { "name": "no-constant-condition" } } + ] + }, + { + "removed": "no-comma-dangle", + "replacedBy": [{ "rule": { "name": "comma-dangle" } }] + }, + { + "removed": "no-empty-class", + "replacedBy": [{ "rule": { "name": "no-empty-character-class" } }] + }, + { + "removed": "no-empty-label", + "replacedBy": [{ "rule": { "name": "no-labels" } }] + }, + { + "removed": "no-extra-strict", + "replacedBy": [{ "rule": { "name": "strict" } }] + }, + { + "removed": "no-reserved-keys", + "replacedBy": [{ "rule": { "name": "quote-props" } }] + }, + { + "removed": "no-space-before-semi", + "replacedBy": [{ "rule": { "name": "semi-spacing" } }] + }, + { + "removed": "no-wrap-func", + "replacedBy": [{ "rule": { "name": "no-extra-parens" } }] + }, + { + "removed": "space-after-function-name", + "replacedBy": [{ "rule": { "name": "space-before-function-paren" } }] + }, + { + "removed": "space-after-keywords", + "replacedBy": [{ "rule": { "name": "keyword-spacing" } }] + }, + { + "removed": "space-before-function-parentheses", + "replacedBy": [{ "rule": { "name": "space-before-function-paren" } }] + }, + { + "removed": "space-before-keywords", + "replacedBy": [{ "rule": { "name": "keyword-spacing" } }] + }, + { + "removed": "space-in-brackets", + "replacedBy": [ + { "rule": { "name": "object-curly-spacing" } }, + { "rule": { "name": "array-bracket-spacing" } }, + { "rule": { "name": "computed-property-spacing" } } + ] + }, + { + "removed": "space-return-throw-case", + "replacedBy": [{ "rule": { "name": "keyword-spacing" } }] + }, + { + "removed": "space-unary-word-ops", + "replacedBy": [{ "rule": { "name": "space-unary-ops" } }] + }, + { + "removed": "spaced-line-comment", + "replacedBy": [{ "rule": { "name": "spaced-comment" } }] + }, + { "removed": "valid-jsdoc", "replacedBy": [] }, + { "removed": "require-jsdoc", "replacedBy": [] } + ] +} diff --git a/node_modules/eslint/lib/api.js b/node_modules/eslint/lib/api.js new file mode 100644 index 00000000..ce6102da --- /dev/null +++ b/node_modules/eslint/lib/api.js @@ -0,0 +1,50 @@ +/** + * @fileoverview Expose out ESLint and CLI to require. + * @author Ian Christian Myers + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { ESLint, shouldUseFlatConfig } = require("./eslint/eslint"); +const { LegacyESLint } = require("./eslint/legacy-eslint"); +const { Linter } = require("./linter"); +const { RuleTester } = require("./rule-tester"); +const { SourceCode } = require("./languages/js/source-code"); + +//----------------------------------------------------------------------------- +// Functions +//----------------------------------------------------------------------------- + +/** + * Loads the correct ESLint constructor given the options. + * @param {Object} [options] The options object + * @param {boolean} [options.useFlatConfig] Whether or not to use a flat config + * @returns {Promise} The ESLint constructor + */ +async function loadESLint({ useFlatConfig } = {}) { + /* + * Note: The v8.x version of this function also accepted a `cwd` option, but + * it is not used in this implementation so we silently ignore it. + */ + + const shouldESLintUseFlatConfig = + useFlatConfig ?? (await shouldUseFlatConfig()); + + return shouldESLintUseFlatConfig ? ESLint : LegacyESLint; +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + Linter, + loadESLint, + ESLint, + RuleTester, + SourceCode, +}; diff --git a/node_modules/eslint/lib/cli-engine/cli-engine.js b/node_modules/eslint/lib/cli-engine/cli-engine.js new file mode 100644 index 00000000..a0c3bc67 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/cli-engine.js @@ -0,0 +1,1109 @@ +/** + * @fileoverview Main CLI object. + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* + * The CLI object should *not* call process.exit() directly. It should only return + * exit codes. This allows other programs to use the CLI object and still control + * when the program exits. + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("node:fs"); +const path = require("node:path"); +const defaultOptions = require("../../conf/default-cli-options"); +const pkg = require("../../package.json"); + +const { + Legacy: { + ConfigOps, + naming, + CascadingConfigArrayFactory, + IgnorePattern, + getUsedExtractedConfigs, + ModuleResolver, + }, +} = require("@eslint/eslintrc"); + +const { FileEnumerator } = require("./file-enumerator"); + +const { Linter } = require("../linter"); +const builtInRules = require("../rules"); +const loadRules = require("./load-rules"); +const hash = require("./hash"); +const LintResultCache = require("./lint-result-cache"); + +const debug = require("debug")("eslint:cli-engine"); +const removedFormatters = new Set([ + "checkstyle", + "codeframe", + "compact", + "jslint-xml", + "junit", + "table", + "tap", + "unix", + "visualstudio", +]); +const validFixTypes = new Set(["directive", "problem", "suggestion", "layout"]); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +// For VSCode IntelliSense +/** @typedef {import("../types").ESLint.ConfigData} ConfigData */ +/** @typedef {import("../types").ESLint.DeprecatedRuleUse} DeprecatedRuleInfo */ +/** @typedef {import("../types").ESLint.FormatterFunction} FormatterFunction */ +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").Linter.ParserOptions} ParserOptions */ +/** @typedef {import("../types").ESLint.Plugin} Plugin */ +/** @typedef {import("../types").Rule.RuleModule} Rule */ +/** @typedef {import("../types").Linter.RuleEntry} RuleConf */ +/** @typedef {import("../types").Linter.SuppressedLintMessage} SuppressedLintMessage */ +/** @typedef {ReturnType} ConfigArray */ +/** @typedef {ReturnType} ExtractedConfig */ + +/** + * The options to configure a CLI engine with. + * @typedef {Object} CLIEngineOptions + * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. + * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this CLIEngine instance + * @property {boolean} [cache] Enable result caching. + * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. + * @property {string} [configFile] The configuration file to use. + * @property {string} [cwd] The value to use for the current working directory. + * @property {string[]} [envs] An array of environments to load. + * @property {string[]|null} [extensions] An array of file extensions to check. + * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. + * @property {string[]} [fixTypes] Array of rule types to apply fixes for. + * @property {string[]} [globals] An array of global variables to declare. + * @property {boolean} [ignore] False disables use of .eslintignore. + * @property {string} [ignorePath] The ignore file to use instead of .eslintignore. + * @property {string|string[]} [ignorePattern] One or more glob patterns to ignore. + * @property {boolean} [useEslintrc] False disables looking for .eslintrc + * @property {string} [parser] The name of the parser to use. + * @property {ParserOptions} [parserOptions] An object of parserOption settings to use. + * @property {string[]} [plugins] An array of plugins to load. + * @property {Record} [rules] An object of rules to use. + * @property {string[]} [rulePaths] An array of directories to load custom rules from. + * @property {boolean|string} [reportUnusedDisableDirectives] `true`, `"error"` or '"warn"' adds reports for unused eslint-disable directives + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD + */ + +/** + * A linting result. + * @typedef {Object} LintResult + * @property {string} filePath The path to the file that was linted. + * @property {LintMessage[]} messages All of the messages for the result. + * @property {SuppressedLintMessage[]} suppressedMessages All of the suppressed messages for the result. + * @property {number} errorCount Number of errors for the result. + * @property {number} fatalErrorCount Number of fatal errors for the result. + * @property {number} warningCount Number of warnings for the result. + * @property {number} fixableErrorCount Number of fixable errors for the result. + * @property {number} fixableWarningCount Number of fixable warnings for the result. + * @property {string} [source] The source code of the file that was linted. + * @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible. + */ + +/** + * Linting results. + * @typedef {Object} LintReport + * @property {LintResult[]} results All of the result. + * @property {number} errorCount Number of errors for the result. + * @property {number} fatalErrorCount Number of fatal errors for the result. + * @property {number} warningCount Number of warnings for the result. + * @property {number} fixableErrorCount Number of fixable errors for the result. + * @property {number} fixableWarningCount Number of fixable warnings for the result. + * @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules. + */ + +/** + * Private data for CLIEngine. + * @typedef {Object} CLIEngineInternalSlots + * @property {Map} additionalPluginPool The map for additional plugins. + * @property {string} cacheFilePath The path to the cache of lint results. + * @property {CascadingConfigArrayFactory} configArrayFactory The factory of configs. + * @property {(filePath: string) => boolean} defaultIgnores The default predicate function to check if a file ignored or not. + * @property {FileEnumerator} fileEnumerator The file enumerator. + * @property {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used. + * @property {LintResultCache|null} lintResultCache The cache of lint results. + * @property {Linter} linter The linter instance which has loaded rules. + * @property {CLIEngineOptions} options The normalized options of this instance. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Determines if each fix type in an array is supported by ESLint and throws + * an error if not. + * @param {string[]} fixTypes An array of fix types to check. + * @returns {void} + * @throws {Error} If an invalid fix type is found. + */ +function validateFixTypes(fixTypes) { + for (const fixType of fixTypes) { + if (!validFixTypes.has(fixType)) { + throw new Error(`Invalid fix type "${fixType}" found.`); + } + } +} + +/** + * It will calculate the error and warning count for collection of messages per file + * @param {LintMessage[]} messages Collection of messages + * @returns {Object} Contains the stats + * @private + */ +function calculateStatsPerFile(messages) { + const stat = { + errorCount: 0, + fatalErrorCount: 0, + warningCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; + + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + + if (message.fatal || message.severity === 2) { + stat.errorCount++; + if (message.fatal) { + stat.fatalErrorCount++; + } + if (message.fix) { + stat.fixableErrorCount++; + } + } else { + stat.warningCount++; + if (message.fix) { + stat.fixableWarningCount++; + } + } + } + return stat; +} + +/** + * It will calculate the error and warning count for collection of results from all files + * @param {LintResult[]} results Collection of messages from all the files + * @returns {Object} Contains the stats + * @private + */ +function calculateStatsPerRun(results) { + const stat = { + errorCount: 0, + fatalErrorCount: 0, + warningCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; + + for (let i = 0; i < results.length; i++) { + const result = results[i]; + + stat.errorCount += result.errorCount; + stat.fatalErrorCount += result.fatalErrorCount; + stat.warningCount += result.warningCount; + stat.fixableErrorCount += result.fixableErrorCount; + stat.fixableWarningCount += result.fixableWarningCount; + } + + return stat; +} + +/** + * Processes an source code using ESLint. + * @param {Object} config The config object. + * @param {string} config.text The source code to verify. + * @param {string} config.cwd The path to the current working directory. + * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses ``. + * @param {ConfigArray} config.config The config. + * @param {boolean} config.fix If `true` then it does fix. + * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments. + * @param {boolean|string} config.reportUnusedDisableDirectives If `true`, `"error"` or '"warn"', then it reports unused `eslint-disable` comments. + * @param {FileEnumerator} config.fileEnumerator The file enumerator to check if a path is a target or not. + * @param {Linter} config.linter The linter instance to verify. + * @returns {LintResult} The result of linting. + * @private + */ +function verifyText({ + text, + cwd, + filePath: providedFilePath, + config, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + fileEnumerator, + linter, +}) { + const filePath = providedFilePath || ""; + + debug(`Lint ${filePath}`); + + /* + * Verify. + * `config.extractConfig(filePath)` requires an absolute path, but `linter` + * doesn't know CWD, so it gives `linter` an absolute path always. + */ + const filePathToVerify = + filePath === "" ? path.join(cwd, filePath) : filePath; + const { fixed, messages, output } = linter.verifyAndFix(text, config, { + allowInlineConfig, + filename: filePathToVerify, + fix, + reportUnusedDisableDirectives, + + /** + * Check if the linter should adopt a given code block or not. + * @param {string} blockFilename The virtual filename of a code block. + * @returns {boolean} `true` if the linter should adopt the code block. + */ + filterCodeBlock(blockFilename) { + return fileEnumerator.isTargetPath(blockFilename); + }, + }); + + // Tweak and return. + const result = { + filePath, + messages, + suppressedMessages: linter.getSuppressedMessages(), + ...calculateStatsPerFile(messages), + }; + + if (fixed) { + result.output = output; + } + if ( + result.errorCount + result.warningCount > 0 && + typeof result.output === "undefined" + ) { + result.source = text; + } + + return result; +} + +/** + * Returns result with warning by ignore settings + * @param {string} filePath File path of checked code + * @param {string} baseDir Absolute path of base directory + * @returns {LintResult} Result with single warning + * @private + */ +function createIgnoreResult(filePath, baseDir) { + let message; + const isHidden = filePath + .split(path.sep) + .find(segment => /^\./u.test(segment)); + const isInNodeModules = + baseDir && path.relative(baseDir, filePath).startsWith("node_modules"); + + if (isHidden) { + message = + "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!'\") to override."; + } else if (isInNodeModules) { + message = + "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override."; + } else { + message = + 'File ignored because of a matching ignore pattern. Use "--no-ignore" to override.'; + } + + return { + filePath: path.resolve(filePath), + messages: [ + { + ruleId: null, + fatal: false, + severity: 1, + message, + nodeType: null, + }, + ], + suppressedMessages: [], + errorCount: 0, + fatalErrorCount: 0, + warningCount: 1, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; +} + +/** + * Get a rule. + * @param {string} ruleId The rule ID to get. + * @param {ConfigArray[]} configArrays The config arrays that have plugin rules. + * @returns {Rule|null} The rule or null. + */ +function getRule(ruleId, configArrays) { + for (const configArray of configArrays) { + const rule = configArray.pluginRules.get(ruleId); + + if (rule) { + return rule; + } + } + return builtInRules.get(ruleId) || null; +} + +/** + * Checks whether a message's rule type should be fixed. + * @param {LintMessage} message The message to check. + * @param {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used. + * @param {string[]} fixTypes An array of fix types to check. + * @returns {boolean} Whether the message should be fixed. + */ +function shouldMessageBeFixed(message, lastConfigArrays, fixTypes) { + if (!message.ruleId) { + return fixTypes.has("directive"); + } + + const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays); + + return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type)); +} + +/** + * Collect used deprecated rules. + * @param {ConfigArray[]} usedConfigArrays The config arrays which were used. + * @returns {IterableIterator} Used deprecated rules. + */ +function* iterateRuleDeprecationWarnings(usedConfigArrays) { + const processedRuleIds = new Set(); + + // Flatten used configs. + /** @type {ExtractedConfig[]} */ + const configs = usedConfigArrays.flatMap(getUsedExtractedConfigs); + + // Traverse rule configs. + for (const config of configs) { + for (const [ruleId, ruleConfig] of Object.entries(config.rules)) { + // Skip if it was processed. + if (processedRuleIds.has(ruleId)) { + continue; + } + processedRuleIds.add(ruleId); + + // Skip if it's not used. + if (!ConfigOps.getRuleSeverity(ruleConfig)) { + continue; + } + const rule = getRule(ruleId, usedConfigArrays); + + // Skip if it's not deprecated. + if (!(rule && rule.meta && rule.meta.deprecated)) { + continue; + } + + // This rule was used and deprecated. + yield { + ruleId, + replacedBy: rule.meta.replacedBy || [], + }; + } + } +} + +/** + * Checks if the given message is an error message. + * @param {LintMessage} message The message to check. + * @returns {boolean} Whether or not the message is an error message. + * @private + */ +function isErrorMessage(message) { + return message.severity === 2; +} + +/** + * return the cacheFile to be used by eslint, based on whether the provided parameter is + * a directory or looks like a directory (ends in `path.sep`), in which case the file + * name will be the `cacheFile/.cache_hashOfCWD` + * + * if cacheFile points to a file or looks like a file then it will just use that file + * @param {string} cacheFile The name of file to be used to store the cache + * @param {string} cwd Current working directory + * @returns {string} the resolved path to the cache file + */ +function getCacheFile(cacheFile, cwd) { + /* + * make sure the path separators are normalized for the environment/os + * keeping the trailing path separator if present + */ + const normalizedCacheFile = path.normalize(cacheFile); + + const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile); + const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep; + + /** + * return the name for the cache file in case the provided parameter is a directory + * @returns {string} the resolved path to the cacheFile + */ + function getCacheFileForDirectory() { + return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`); + } + + let fileStats; + + try { + fileStats = fs.lstatSync(resolvedCacheFile); + } catch { + fileStats = null; + } + + /* + * in case the file exists we need to verify if the provided path + * is a directory or a file. If it is a directory we want to create a file + * inside that directory + */ + if (fileStats) { + /* + * is a directory or is a file, but the original file the user provided + * looks like a directory but `path.resolve` removed the `last path.sep` + * so we need to still treat this like a directory + */ + if (fileStats.isDirectory() || looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + // is file so just use that file + return resolvedCacheFile; + } + + /* + * here we known the file or directory doesn't exist, + * so we will try to infer if its a directory if it looks like a directory + * for the current operating system. + */ + + // if the last character passed is a path separator we assume is a directory + if (looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + return resolvedCacheFile; +} + +/** + * Convert a string array to a boolean map. + * @param {string[]|null} keys The keys to assign true. + * @param {boolean} defaultValue The default value for each property. + * @param {string} displayName The property name which is used in error message. + * @throws {Error} Requires array. + * @returns {Record} The boolean map. + */ +function toBooleanMap(keys, defaultValue, displayName) { + if (keys && !Array.isArray(keys)) { + throw new Error(`${displayName} must be an array.`); + } + if (keys && keys.length > 0) { + return keys.reduce((map, def) => { + const [key, value] = def.split(":"); + + if (key !== "__proto__") { + map[key] = value === void 0 ? defaultValue : value === "true"; + } + + return map; + }, {}); + } + return void 0; +} + +/** + * Create a config data from CLI options. + * @param {CLIEngineOptions} options The options + * @returns {ConfigData|null} The created config data. + */ +function createConfigDataFromOptions(options) { + const { ignorePattern, parser, parserOptions, plugins, rules } = options; + const env = toBooleanMap(options.envs, true, "envs"); + const globals = toBooleanMap(options.globals, false, "globals"); + + if ( + env === void 0 && + globals === void 0 && + (ignorePattern === void 0 || ignorePattern.length === 0) && + parser === void 0 && + parserOptions === void 0 && + plugins === void 0 && + rules === void 0 + ) { + return null; + } + return { + env, + globals, + ignorePatterns: ignorePattern, + parser, + parserOptions, + plugins, + rules, + }; +} + +/** + * Checks whether a directory exists at the given location + * @param {string} resolvedPath A path from the CWD + * @throws {Error} As thrown by `fs.statSync` or `fs.isDirectory`. + * @returns {boolean} `true` if a directory exists + */ +function directoryExists(resolvedPath) { + try { + return fs.statSync(resolvedPath).isDirectory(); + } catch (error) { + if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) { + return false; + } + throw error; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Core CLI. + */ +class CLIEngine { + /** + * Creates a new instance of the core CLI engine. + * @param {CLIEngineOptions} providedOptions The options for this instance. + * @param {Object} [additionalData] Additional settings that are not CLIEngineOptions. + * @param {Record|null} [additionalData.preloadedPlugins] Preloaded plugins. + */ + constructor(providedOptions, { preloadedPlugins } = {}) { + const options = Object.assign( + Object.create(null), + defaultOptions, + { cwd: process.cwd() }, + providedOptions, + ); + + if (options.fix === void 0) { + options.fix = false; + } + + const additionalPluginPool = new Map(); + + if (preloadedPlugins) { + for (const [id, plugin] of Object.entries(preloadedPlugins)) { + additionalPluginPool.set(id, plugin); + } + } + + const cacheFilePath = getCacheFile( + options.cacheLocation || options.cacheFile, + options.cwd, + ); + const configArrayFactory = new CascadingConfigArrayFactory({ + additionalPluginPool, + baseConfig: options.baseConfig || null, + cliConfig: createConfigDataFromOptions(options), + cwd: options.cwd, + ignorePath: options.ignorePath, + resolvePluginsRelativeTo: options.resolvePluginsRelativeTo, + rulePaths: options.rulePaths, + specificConfigPath: options.configFile, + useEslintrc: options.useEslintrc, + builtInRules, + loadRules, + getEslintRecommendedConfig: () => + require("@eslint/js").configs.recommended, + getEslintAllConfig: () => require("@eslint/js").configs.all, + }); + const fileEnumerator = new FileEnumerator({ + configArrayFactory, + cwd: options.cwd, + extensions: options.extensions, + globInputPaths: options.globInputPaths, + errorOnUnmatchedPattern: options.errorOnUnmatchedPattern, + ignore: options.ignore, + }); + const lintResultCache = options.cache + ? new LintResultCache(cacheFilePath, options.cacheStrategy) + : null; + const linter = new Linter({ cwd: options.cwd, configType: "eslintrc" }); + + /** @type {ConfigArray[]} */ + const lastConfigArrays = [configArrayFactory.getConfigArrayForFile()]; + + // Store private data. + internalSlotsMap.set(this, { + additionalPluginPool, + cacheFilePath, + configArrayFactory, + defaultIgnores: IgnorePattern.createDefaultIgnore(options.cwd), + fileEnumerator, + lastConfigArrays, + lintResultCache, + linter, + options, + }); + + // setup special filter for fixes + if (options.fix && options.fixTypes && options.fixTypes.length > 0) { + debug(`Using fix types ${options.fixTypes}`); + + // throw an error if any invalid fix types are found + validateFixTypes(options.fixTypes); + + // convert to Set for faster lookup + const fixTypes = new Set(options.fixTypes); + + // save original value of options.fix in case it's a function + const originalFix = + typeof options.fix === "function" ? options.fix : () => true; + + options.fix = message => + shouldMessageBeFixed(message, lastConfigArrays, fixTypes) && + originalFix(message); + } + } + + getRules() { + const { lastConfigArrays } = internalSlotsMap.get(this); + + return new Map( + (function* () { + yield* builtInRules; + + for (const configArray of lastConfigArrays) { + yield* configArray.pluginRules; + } + })(), + ); + } + + /** + * Returns results that only contains errors. + * @param {LintResult[]} results The results to filter. + * @returns {LintResult[]} The filtered results. + */ + static getErrorResults(results) { + const filtered = []; + + results.forEach(result => { + const filteredMessages = result.messages.filter(isErrorMessage); + const filteredSuppressedMessages = + result.suppressedMessages.filter(isErrorMessage); + + if (filteredMessages.length > 0) { + filtered.push({ + ...result, + messages: filteredMessages, + suppressedMessages: filteredSuppressedMessages, + errorCount: filteredMessages.length, + warningCount: 0, + fixableErrorCount: result.fixableErrorCount, + fixableWarningCount: 0, + }); + } + }); + + return filtered; + } + + /** + * Outputs fixes from the given results to files. + * @param {LintReport} report The report object created by CLIEngine. + * @returns {void} + */ + static outputFixes(report) { + report.results + .filter(result => Object.hasOwn(result, "output")) + .forEach(result => { + fs.writeFileSync(result.filePath, result.output); + }); + } + + /** + * Resolves the patterns passed into executeOnFiles() into glob-based patterns + * for easier handling. + * @param {string[]} patterns The file patterns passed on the command line. + * @returns {string[]} The equivalent glob patterns. + */ + resolveFileGlobPatterns(patterns) { + const { options } = internalSlotsMap.get(this); + + if (options.globInputPaths === false) { + return patterns.filter(Boolean); + } + + const extensions = (options.extensions || [".js"]).map(ext => + ext.replace(/^\./u, ""), + ); + const dirSuffix = `/**/*.{${extensions.join(",")}}`; + + return patterns.filter(Boolean).map(pathname => { + const resolvedPath = path.resolve(options.cwd, pathname); + const newPath = directoryExists(resolvedPath) + ? pathname.replace(/[/\\]$/u, "") + dirSuffix + : pathname; + + return path.normalize(newPath).replace(/\\/gu, "/"); + }); + } + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string[]} patterns An array of file and directory names. + * @throws {Error} As may be thrown by `fs.unlinkSync`. + * @returns {LintReport} The results for all files that were linted. + */ + executeOnFiles(patterns) { + const { + cacheFilePath, + fileEnumerator, + lastConfigArrays, + lintResultCache, + linter, + options: { + allowInlineConfig, + cache, + cwd, + fix, + reportUnusedDisableDirectives, + }, + } = internalSlotsMap.get(this); + const results = []; + const startTime = Date.now(); + + // Clear the last used config arrays. + lastConfigArrays.length = 0; + + // Delete cache file; should this do here? + if (!cache) { + try { + fs.unlinkSync(cacheFilePath); + } catch (error) { + const errorCode = error && error.code; + + // Ignore errors when no such file exists or file system is read only (and cache file does not exist) + if ( + errorCode !== "ENOENT" && + !(errorCode === "EROFS" && !fs.existsSync(cacheFilePath)) + ) { + throw error; + } + } + } + + // Iterate source code files. + for (const { config, filePath, ignored } of fileEnumerator.iterateFiles( + patterns, + )) { + if (ignored) { + results.push(createIgnoreResult(filePath, cwd)); + continue; + } + + /* + * Store used configs for: + * - this method uses to collect used deprecated rules. + * - `getRules()` method uses to collect all loaded rules. + * - `--fix-type` option uses to get the loaded rule's meta data. + */ + if (!lastConfigArrays.includes(config)) { + lastConfigArrays.push(config); + } + + // Skip if there is cached result. + if (lintResultCache) { + const cachedResult = lintResultCache.getCachedLintResults( + filePath, + config, + ); + + if (cachedResult) { + const hadMessages = + cachedResult.messages && + cachedResult.messages.length > 0; + + if (hadMessages && fix) { + debug( + `Reprocessing cached file to allow autofix: ${filePath}`, + ); + } else { + debug( + `Skipping file since it hasn't changed: ${filePath}`, + ); + results.push(cachedResult); + continue; + } + } + } + + // Do lint. + const result = verifyText({ + text: fs.readFileSync(filePath, "utf8"), + filePath, + config, + cwd, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + fileEnumerator, + linter, + }); + + results.push(result); + + /* + * Store the lint result in the LintResultCache. + * NOTE: The LintResultCache will remove the file source and any + * other properties that are difficult to serialize, and will + * hydrate those properties back in on future lint runs. + */ + if (lintResultCache) { + lintResultCache.setCachedLintResults(filePath, config, result); + } + } + + // Persist the cache to disk. + if (lintResultCache) { + lintResultCache.reconcile(); + } + + debug(`Linting complete in: ${Date.now() - startTime}ms`); + let usedDeprecatedRules; + + return { + results, + ...calculateStatsPerRun(results), + + // Initialize it lazily because CLI and `ESLint` API don't use it. + get usedDeprecatedRules() { + if (!usedDeprecatedRules) { + usedDeprecatedRules = Array.from( + iterateRuleDeprecationWarnings(lastConfigArrays), + ); + } + return usedDeprecatedRules; + }, + }; + } + + /** + * Executes the current configuration on text. + * @param {string} text A string of JavaScript code to lint. + * @param {string} [filename] An optional string representing the texts filename. + * @param {boolean} [warnIgnored] Always warn when a file is ignored + * @returns {LintReport} The results for the linting. + */ + executeOnText(text, filename, warnIgnored) { + const { + configArrayFactory, + fileEnumerator, + lastConfigArrays, + linter, + options: { + allowInlineConfig, + cwd, + fix, + reportUnusedDisableDirectives, + }, + } = internalSlotsMap.get(this); + const results = []; + const startTime = Date.now(); + const resolvedFilename = filename && path.resolve(cwd, filename); + + // Clear the last used config arrays. + lastConfigArrays.length = 0; + if (resolvedFilename && this.isPathIgnored(resolvedFilename)) { + if (warnIgnored) { + results.push(createIgnoreResult(resolvedFilename, cwd)); + } + } else { + const config = configArrayFactory.getConfigArrayForFile( + resolvedFilename || "__placeholder__.js", + ); + + /* + * Store used configs for: + * - this method uses to collect used deprecated rules. + * - `getRules()` method uses to collect all loaded rules. + * - `--fix-type` option uses to get the loaded rule's meta data. + */ + lastConfigArrays.push(config); + + // Do lint. + results.push( + verifyText({ + text, + filePath: resolvedFilename, + config, + cwd, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + fileEnumerator, + linter, + }), + ); + } + + debug(`Linting complete in: ${Date.now() - startTime}ms`); + let usedDeprecatedRules; + + return { + results, + ...calculateStatsPerRun(results), + + // Initialize it lazily because CLI and `ESLint` API don't use it. + get usedDeprecatedRules() { + if (!usedDeprecatedRules) { + usedDeprecatedRules = Array.from( + iterateRuleDeprecationWarnings(lastConfigArrays), + ); + } + return usedDeprecatedRules; + }, + }; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file to retrieve a config object for. + * @throws {Error} If filepath a directory path. + * @returns {ConfigData} A configuration object for the file. + */ + getConfigForFile(filePath) { + const { configArrayFactory, options } = internalSlotsMap.get(this); + const absolutePath = path.resolve(options.cwd, filePath); + + if (directoryExists(absolutePath)) { + throw Object.assign( + new Error("'filePath' should not be a directory path."), + { messageTemplate: "print-config-with-directory-path" }, + ); + } + + return configArrayFactory + .getConfigArrayForFile(absolutePath) + .extractConfig(absolutePath) + .toCompatibleObjectAsConfigFileContent(); + } + + /** + * Checks if a given path is ignored by ESLint. + * @param {string} filePath The path of the file to check. + * @returns {boolean} Whether or not the given path is ignored. + */ + isPathIgnored(filePath) { + const { + configArrayFactory, + defaultIgnores, + options: { cwd, ignore }, + } = internalSlotsMap.get(this); + const absolutePath = path.resolve(cwd, filePath); + + if (ignore) { + const config = configArrayFactory + .getConfigArrayForFile(absolutePath) + .extractConfig(absolutePath); + const ignores = config.ignores || defaultIgnores; + + return ignores(absolutePath); + } + + return defaultIgnores(absolutePath); + } + + /** + * Returns the formatter representing the given format or null if the `format` is not a string. + * @param {string} [format] The name of the format to load or the path to a + * custom formatter. + * @throws {any} As may be thrown by requiring of formatter + * @returns {(FormatterFunction|null)} The formatter function or null if the `format` is not a string. + */ + getFormatter(format) { + // default is stylish + const resolvedFormatName = format || "stylish"; + + // only strings are valid formatters + if (typeof resolvedFormatName === "string") { + // replace \ with / for Windows compatibility + const normalizedFormatName = resolvedFormatName.replace( + /\\/gu, + "/", + ); + + const slots = internalSlotsMap.get(this); + const cwd = slots ? slots.options.cwd : process.cwd(); + const namespace = naming.getNamespaceFromTerm(normalizedFormatName); + + let formatterPath; + + // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages) + if (!namespace && normalizedFormatName.includes("/")) { + formatterPath = path.resolve(cwd, normalizedFormatName); + } else { + try { + const npmFormat = naming.normalizePackageName( + normalizedFormatName, + "eslint-formatter", + ); + + formatterPath = ModuleResolver.resolve( + npmFormat, + path.join(cwd, "__placeholder__.js"), + ); + } catch { + formatterPath = path.resolve( + __dirname, + "formatters", + normalizedFormatName, + ); + } + } + + try { + return require(formatterPath); + } catch (ex) { + if (removedFormatters.has(format)) { + ex.message = `The ${format} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${format}\``; + } else { + ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`; + } + throw ex; + } + } else { + return null; + } + } +} + +CLIEngine.version = pkg.version; +CLIEngine.getFormatter = CLIEngine.prototype.getFormatter; + +module.exports = { + CLIEngine, + + /** + * Get the internal slots of a given CLIEngine instance for tests. + * @param {CLIEngine} instance The CLIEngine instance to get. + * @returns {CLIEngineInternalSlots} The internal slots. + */ + getCLIEngineInternalSlots(instance) { + return internalSlotsMap.get(instance); + }, +}; diff --git a/node_modules/eslint/lib/cli-engine/file-enumerator.js b/node_modules/eslint/lib/cli-engine/file-enumerator.js new file mode 100644 index 00000000..a0788621 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/file-enumerator.js @@ -0,0 +1,541 @@ +/** + * @fileoverview `FileEnumerator` class. + * + * `FileEnumerator` class has two responsibilities: + * + * 1. Find target files by processing glob patterns. + * 2. Tie each target file and appropriate configuration. + * + * It provides a method: + * + * - `iterateFiles(patterns)` + * Iterate files which are matched by given patterns together with the + * corresponded configuration. This is for `CLIEngine#executeOnFiles()`. + * While iterating files, it loads the configuration file of each directory + * before iterate files on the directory, so we can use the configuration + * files to determine target files. + * + * @example + * const enumerator = new FileEnumerator(); + * const linter = new Linter(); + * + * for (const { config, filePath } of enumerator.iterateFiles(["*.js"])) { + * const code = fs.readFileSync(filePath, "utf8"); + * const messages = linter.verify(code, config, filePath); + * + * console.log(messages); + * } + * + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("node:fs"); +const path = require("node:path"); +const getGlobParent = require("glob-parent"); +const isGlob = require("is-glob"); +const escapeRegExp = require("escape-string-regexp"); +const { Minimatch } = require("minimatch"); + +const { + Legacy: { IgnorePattern, CascadingConfigArrayFactory }, +} = require("@eslint/eslintrc"); +const debug = require("debug")("eslint:file-enumerator"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const minimatchOpts = { dot: true, matchBase: true }; +const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/u; +const NONE = 0; +const IGNORED_SILENTLY = 1; +const IGNORED = 2; + +// For VSCode intellisense +/** @typedef {ReturnType} ConfigArray */ + +/** + * @typedef {Object} FileEnumeratorOptions + * @property {CascadingConfigArrayFactory} [configArrayFactory] The factory for config arrays. + * @property {string} [cwd] The base directory to start lookup. + * @property {string[]} [extensions] The extensions to match files for directory patterns. + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} [ignore] The flag to check ignored files. + * @property {string[]} [rulePaths] The value of `--rulesdir` option. + */ + +/** + * @typedef {Object} FileAndConfig + * @property {string} filePath The path to a target file. + * @property {ConfigArray} config The config entries of that file. + * @property {boolean} ignored If `true` then this file should be ignored and warned because it was directly specified. + */ + +/** + * @typedef {Object} FileEntry + * @property {string} filePath The path to a target file. + * @property {ConfigArray} config The config entries of that file. + * @property {NONE|IGNORED_SILENTLY|IGNORED} flag The flag. + * - `NONE` means the file is a target file. + * - `IGNORED_SILENTLY` means the file should be ignored silently. + * - `IGNORED` means the file should be ignored and warned because it was directly specified. + */ + +/** + * @typedef {Object} FileEnumeratorInternalSlots + * @property {CascadingConfigArrayFactory} configArrayFactory The factory for config arrays. + * @property {string} cwd The base directory to start lookup. + * @property {RegExp|null} extensionRegExp The RegExp to test if a string ends with specific file extensions. + * @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} ignoreFlag The flag to check ignored files. + * @property {(filePath:string, dot:boolean) => boolean} defaultIgnores The default predicate function to ignore files. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Check if a string is a glob pattern or not. + * @param {string} pattern A glob pattern. + * @returns {boolean} `true` if the string is a glob pattern. + */ +function isGlobPattern(pattern) { + return isGlob(path.sep === "\\" ? pattern.replace(/\\/gu, "/") : pattern); +} + +/** + * Get stats of a given path. + * @param {string} filePath The path to target file. + * @throws {Error} As may be thrown by `fs.statSync`. + * @returns {fs.Stats|null} The stats. + * @private + */ +function statSafeSync(filePath) { + try { + return fs.statSync(filePath); + } catch (error) { + /* c8 ignore next */ + if (error.code !== "ENOENT") { + throw error; + } + return null; + } +} + +/** + * Get filenames in a given path to a directory. + * @param {string} directoryPath The path to target directory. + * @throws {Error} As may be thrown by `fs.readdirSync`. + * @returns {import("fs").Dirent[]} The filenames. + * @private + */ +function readdirSafeSync(directoryPath) { + try { + return fs.readdirSync(directoryPath, { withFileTypes: true }); + } catch (error) { + /* c8 ignore next */ + if (error.code !== "ENOENT") { + throw error; + } + return []; + } +} + +/** + * Create a `RegExp` object to detect extensions. + * @param {string[] | null} extensions The extensions to create. + * @returns {RegExp | null} The created `RegExp` object or null. + */ +function createExtensionRegExp(extensions) { + if (extensions) { + const normalizedExts = extensions.map(ext => + escapeRegExp(ext.startsWith(".") ? ext.slice(1) : ext), + ); + + return new RegExp(`.\\.(?:${normalizedExts.join("|")})$`, "u"); + } + return null; +} + +/** + * The error type when no files match a glob. + */ +class NoFilesFoundError extends Error { + /** + * @param {string} pattern The glob pattern which was not found. + * @param {boolean} globDisabled If `true` then the pattern was a glob pattern, but glob was disabled. + */ + constructor(pattern, globDisabled) { + super( + `No files matching '${pattern}' were found${globDisabled ? " (glob was disabled)" : ""}.`, + ); + this.messageTemplate = "file-not-found"; + this.messageData = { pattern, globDisabled }; + } +} + +/** + * The error type when there are files matched by a glob, but all of them have been ignored. + */ +class AllFilesIgnoredError extends Error { + /** + * @param {string} pattern The glob pattern which was not found. + */ + constructor(pattern) { + super(`All files matched by '${pattern}' are ignored.`); + this.messageTemplate = "all-files-ignored"; + this.messageData = { pattern }; + } +} + +/** + * This class provides the functionality that enumerates every file which is + * matched by given glob patterns and that configuration. + */ +class FileEnumerator { + /** + * Initialize this enumerator. + * @param {FileEnumeratorOptions} options The options. + */ + constructor({ + cwd = process.cwd(), + configArrayFactory = new CascadingConfigArrayFactory({ + cwd, + getEslintRecommendedConfig: () => + require("@eslint/js").configs.recommended, + getEslintAllConfig: () => require("@eslint/js").configs.all, + }), + extensions = null, + globInputPaths = true, + errorOnUnmatchedPattern = true, + ignore = true, + } = {}) { + internalSlotsMap.set(this, { + configArrayFactory, + cwd, + defaultIgnores: IgnorePattern.createDefaultIgnore(cwd), + extensionRegExp: createExtensionRegExp(extensions), + globInputPaths, + errorOnUnmatchedPattern, + ignoreFlag: ignore, + }); + } + + /** + * Check if a given file is target or not. + * @param {string} filePath The path to a candidate file. + * @param {ConfigArray} [providedConfig] Optional. The configuration for the file. + * @returns {boolean} `true` if the file is a target. + */ + isTargetPath(filePath, providedConfig) { + const { configArrayFactory, extensionRegExp } = + internalSlotsMap.get(this); + + // If `--ext` option is present, use it. + if (extensionRegExp) { + return extensionRegExp.test(filePath); + } + + // `.js` file is target by default. + if (filePath.endsWith(".js")) { + return true; + } + + // use `overrides[].files` to check additional targets. + const config = + providedConfig || + configArrayFactory.getConfigArrayForFile(filePath, { + ignoreNotFoundError: true, + }); + + return config.isAdditionalTargetPath(filePath); + } + + /** + * Iterate files which are matched by given glob patterns. + * @param {string|string[]} patternOrPatterns The glob patterns to iterate files. + * @throws {NoFilesFoundError|AllFilesIgnoredError} On an unmatched pattern. + * @returns {IterableIterator} The found files. + */ + *iterateFiles(patternOrPatterns) { + const { globInputPaths, errorOnUnmatchedPattern } = + internalSlotsMap.get(this); + const patterns = Array.isArray(patternOrPatterns) + ? patternOrPatterns + : [patternOrPatterns]; + + debug("Start to iterate files: %o", patterns); + + // The set of paths to remove duplicate. + const set = new Set(); + + for (const pattern of patterns) { + let foundRegardlessOfIgnored = false; + let found = false; + + // Skip empty string. + if (!pattern) { + continue; + } + + // Iterate files of this pattern. + for (const { config, filePath, flag } of this._iterateFiles( + pattern, + )) { + foundRegardlessOfIgnored = true; + if (flag === IGNORED_SILENTLY) { + continue; + } + found = true; + + // Remove duplicate paths while yielding paths. + if (!set.has(filePath)) { + set.add(filePath); + yield { + config, + filePath, + ignored: flag === IGNORED, + }; + } + } + + // Raise an error if any files were not found. + if (errorOnUnmatchedPattern) { + if (!foundRegardlessOfIgnored) { + throw new NoFilesFoundError( + pattern, + !globInputPaths && isGlob(pattern), + ); + } + if (!found) { + throw new AllFilesIgnoredError(pattern); + } + } + } + + debug(`Complete iterating files: ${JSON.stringify(patterns)}`); + } + + /** + * Iterate files which are matched by a given glob pattern. + * @param {string} pattern The glob pattern to iterate files. + * @returns {IterableIterator} The found files. + */ + _iterateFiles(pattern) { + const { cwd, globInputPaths } = internalSlotsMap.get(this); + const absolutePath = path.resolve(cwd, pattern); + const isDot = dotfilesPattern.test(pattern); + const stat = statSafeSync(absolutePath); + + if (stat && stat.isDirectory()) { + return this._iterateFilesWithDirectory(absolutePath, isDot); + } + if (stat && stat.isFile()) { + return this._iterateFilesWithFile(absolutePath); + } + if (globInputPaths && isGlobPattern(pattern)) { + return this._iterateFilesWithGlob(pattern, isDot); + } + + return []; + } + + /** + * Iterate a file which is matched by a given path. + * @param {string} filePath The path to the target file. + * @returns {IterableIterator} The found files. + * @private + */ + _iterateFilesWithFile(filePath) { + debug(`File: ${filePath}`); + + const { configArrayFactory } = internalSlotsMap.get(this); + const config = configArrayFactory.getConfigArrayForFile(filePath); + const ignored = this._isIgnoredFile(filePath, { config, direct: true }); + const flag = ignored ? IGNORED : NONE; + + return [{ config, filePath, flag }]; + } + + /** + * Iterate files in a given path. + * @param {string} directoryPath The path to the target directory. + * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default. + * @returns {IterableIterator} The found files. + * @private + */ + _iterateFilesWithDirectory(directoryPath, dotfiles) { + debug(`Directory: ${directoryPath}`); + + return this._iterateFilesRecursive(directoryPath, { + dotfiles, + recursive: true, + selector: null, + }); + } + + /** + * Iterate files which are matched by a given glob pattern. + * @param {string} pattern The glob pattern to iterate files. + * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default. + * @returns {IterableIterator} The found files. + * @private + */ + _iterateFilesWithGlob(pattern, dotfiles) { + debug(`Glob: ${pattern}`); + + const { cwd } = internalSlotsMap.get(this); + const directoryPath = path.resolve(cwd, getGlobParent(pattern)); + const absolutePath = path.resolve(cwd, pattern); + const globPart = absolutePath.slice(directoryPath.length + 1); + + /* + * recursive if there are `**` or path separators in the glob part. + * Otherwise, patterns such as `src/*.js`, it doesn't need recursive. + */ + const recursive = /\*\*|\/|\\/u.test(globPart); + const selector = new Minimatch(absolutePath, minimatchOpts); + + debug(`recursive? ${recursive}`); + + return this._iterateFilesRecursive(directoryPath, { + dotfiles, + recursive, + selector, + }); + } + + /** + * Iterate files in a given path. + * @param {string} directoryPath The path to the target directory. + * @param {Object} options The options to iterate files. + * @param {boolean} [options.dotfiles] If `true` then it doesn't skip dot files by default. + * @param {boolean} [options.recursive] If `true` then it dives into sub directories. + * @param {InstanceType} [options.selector] The matcher to choose files. + * @returns {IterableIterator} The found files. + * @private + */ + *_iterateFilesRecursive(directoryPath, options) { + debug(`Enter the directory: ${directoryPath}`); + const { configArrayFactory } = internalSlotsMap.get(this); + + /** @type {ConfigArray|null} */ + let config = null; + + // Enumerate the files of this directory. + for (const entry of readdirSafeSync(directoryPath)) { + const filePath = path.join(directoryPath, entry.name); + const fileInfo = entry.isSymbolicLink() + ? statSafeSync(filePath) + : entry; + + if (!fileInfo) { + continue; + } + + // Check if the file is matched. + if (fileInfo.isFile()) { + if (!config) { + config = configArrayFactory.getConfigArrayForFile( + filePath, + + /* + * We must ignore `ConfigurationNotFoundError` at this + * point because we don't know if target files exist in + * this directory. + */ + { ignoreNotFoundError: true }, + ); + } + const matched = options.selector + ? // Started with a glob pattern; choose by the pattern. + options.selector.match(filePath) + : // Started with a directory path; choose by file extensions. + this.isTargetPath(filePath, config); + + if (matched) { + const ignored = this._isIgnoredFile(filePath, { + ...options, + config, + }); + const flag = ignored ? IGNORED_SILENTLY : NONE; + + debug( + `Yield: ${entry.name}${ignored ? " but ignored" : ""}`, + ); + yield { + config: configArrayFactory.getConfigArrayForFile( + filePath, + ), + filePath, + flag, + }; + } else { + debug(`Didn't match: ${entry.name}`); + } + + // Dive into the sub directory. + } else if (options.recursive && fileInfo.isDirectory()) { + if (!config) { + config = configArrayFactory.getConfigArrayForFile( + filePath, + { ignoreNotFoundError: true }, + ); + } + const ignored = this._isIgnoredFile(filePath + path.sep, { + ...options, + config, + }); + + if (!ignored) { + yield* this._iterateFilesRecursive(filePath, options); + } + } + } + + debug(`Leave the directory: ${directoryPath}`); + } + + /** + * Check if a given file should be ignored. + * @param {string} filePath The path to a file to check. + * @param {Object} options Options + * @param {ConfigArray} [options.config] The config for this file. + * @param {boolean} [options.dotfiles] If `true` then this is not ignore dot files by default. + * @param {boolean} [options.direct] If `true` then this is a direct specified file. + * @returns {boolean} `true` if the file should be ignored. + * @private + */ + _isIgnoredFile( + filePath, + { config: providedConfig, dotfiles = false, direct = false }, + ) { + const { configArrayFactory, defaultIgnores, ignoreFlag } = + internalSlotsMap.get(this); + + if (ignoreFlag) { + const config = + providedConfig || + configArrayFactory.getConfigArrayForFile(filePath, { + ignoreNotFoundError: true, + }); + const ignores = + config.extractConfig(filePath).ignores || defaultIgnores; + + return ignores(filePath, dotfiles); + } + + return !direct && defaultIgnores(filePath, dotfiles); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { FileEnumerator }; diff --git a/node_modules/eslint/lib/cli-engine/formatters/formatters-meta.json b/node_modules/eslint/lib/cli-engine/formatters/formatters-meta.json new file mode 100644 index 00000000..cf320529 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/formatters-meta.json @@ -0,0 +1,18 @@ +[ + { + "name": "html", + "description": "Outputs results to HTML. The `html` formatter is useful for visual presentation in the browser." + }, + { + "name": "json-with-metadata", + "description": "Outputs JSON-serialized results. The `json-with-metadata` provides the same linting results as the [`json`](#json) formatter with additional metadata about the rules applied. The linting results are included in the `results` property and the rules metadata is included in the `metadata` property.\n\nAlternatively, you can use the [ESLint Node.js API](../../integrate/nodejs-api) to programmatically use ESLint." + }, + { + "name": "json", + "description": "Outputs JSON-serialized results. The `json` formatter is useful when you want to programmatically work with the CLI's linting results.\n\nAlternatively, you can use the [ESLint Node.js API](../../integrate/nodejs-api) to programmatically use ESLint." + }, + { + "name": "stylish", + "description": "Human-readable output format. This is the default formatter." + } +] diff --git a/node_modules/eslint/lib/cli-engine/formatters/html.js b/node_modules/eslint/lib/cli-engine/formatters/html.js new file mode 100644 index 00000000..ef8d445a --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/html.js @@ -0,0 +1,359 @@ +/** + * @fileoverview HTML reporter + * @author Julian Laval + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const encodeHTML = (function () { + const encodeHTMLRules = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + }; + const matchHTML = /[&<>"']/gu; + + return function (code) { + return code + ? code.toString().replace(matchHTML, m => encodeHTMLRules[m] || m) + : ""; + }; +})(); + +/** + * Get the final HTML document. + * @param {Object} it data for the document. + * @returns {string} HTML document. + */ +function pageTemplate(it) { + const { reportColor, reportSummary, date, results } = it; + + return ` + + + + + ESLint Report + + + + + +
+

ESLint Report

+
+ ${reportSummary} - Generated on ${date} +
+
+ + + ${results} + +
+ + + +`.trimStart(); +} + +/** + * Given a word and a count, append an s if count is not one. + * @param {string} word A word in its singular form. + * @param {number} count A number controlling whether word should be pluralized. + * @returns {string} The original word with an s on the end if count is not one. + */ +function pluralize(word, count) { + return count === 1 ? word : `${word}s`; +} + +/** + * Renders text along the template of x problems (x errors, x warnings) + * @param {string} totalErrors Total errors + * @param {string} totalWarnings Total warnings + * @returns {string} The formatted string, pluralized where necessary + */ +function renderSummary(totalErrors, totalWarnings) { + const totalProblems = totalErrors + totalWarnings; + let renderedText = `${totalProblems} ${pluralize("problem", totalProblems)}`; + + if (totalProblems !== 0) { + renderedText += ` (${totalErrors} ${pluralize("error", totalErrors)}, ${totalWarnings} ${pluralize("warning", totalWarnings)})`; + } + return renderedText; +} + +/** + * Get the color based on whether there are errors/warnings... + * @param {string} totalErrors Total errors + * @param {string} totalWarnings Total warnings + * @returns {number} The color code (0 = green, 1 = yellow, 2 = red) + */ +function renderColor(totalErrors, totalWarnings) { + if (totalErrors !== 0) { + return 2; + } + if (totalWarnings !== 0) { + return 1; + } + return 0; +} + +/** + * Get HTML (table row) describing a single message. + * @param {Object} it data for the message. + * @returns {string} HTML (table row) describing the message. + */ +function messageTemplate(it) { + const { + parentIndex, + lineNumber, + columnNumber, + severityNumber, + severityName, + message, + ruleUrl, + ruleId, + } = it; + + return ` + + ${lineNumber}:${columnNumber} + ${severityName} + ${encodeHTML(message)} + + ${ruleId ? ruleId : ""} + + +`.trimStart(); +} + +/** + * Get HTML (table rows) describing the messages. + * @param {Array} messages Messages. + * @param {number} parentIndex Index of the parent HTML row. + * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis. + * @returns {string} HTML (table rows) describing the messages. + */ +function renderMessages(messages, parentIndex, rulesMeta) { + /** + * Get HTML (table row) describing a message. + * @param {Object} message Message. + * @returns {string} HTML (table row) describing a message. + */ + return messages + .map(message => { + const lineNumber = message.line || 0; + const columnNumber = message.column || 0; + let ruleUrl; + + if (rulesMeta) { + const meta = rulesMeta[message.ruleId]; + + if (meta && meta.docs && meta.docs.url) { + ruleUrl = meta.docs.url; + } + } + + return messageTemplate({ + parentIndex, + lineNumber, + columnNumber, + severityNumber: message.severity, + severityName: message.severity === 1 ? "Warning" : "Error", + message: message.message, + ruleId: message.ruleId, + ruleUrl, + }); + }) + .join("\n"); +} + +/** + * Get HTML (table row) describing the result for a single file. + * @param {Object} it data for the file. + * @returns {string} HTML (table row) describing the result for the file. + */ +function resultTemplate(it) { + const { color, index, filePath, summary } = it; + + return ` + + + [+] ${encodeHTML(filePath)} + ${encodeHTML(summary)} + + +`.trimStart(); +} + +/** + * Render the results. + * @param {Array} results Test results. + * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis. + * @returns {string} HTML string describing the results. + */ +function renderResults(results, rulesMeta) { + return results + .map( + (result, index) => + resultTemplate({ + index, + color: renderColor(result.errorCount, result.warningCount), + filePath: result.filePath, + summary: renderSummary( + result.errorCount, + result.warningCount, + ), + }) + renderMessages(result.messages, index, rulesMeta), + ) + .join("\n"); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function (results, data) { + let totalErrors, totalWarnings; + + const metaData = data ? data.rulesMeta : {}; + + totalErrors = 0; + totalWarnings = 0; + + // Iterate over results to get totals + results.forEach(result => { + totalErrors += result.errorCount; + totalWarnings += result.warningCount; + }); + + return pageTemplate({ + date: new Date(), + reportColor: renderColor(totalErrors, totalWarnings), + reportSummary: renderSummary(totalErrors, totalWarnings), + results: renderResults(results, metaData), + }); +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js b/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js new file mode 100644 index 00000000..44c785c7 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js @@ -0,0 +1,16 @@ +/** + * @fileoverview JSON reporter, including rules metadata + * @author Chris Meyer + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function (results, data) { + return JSON.stringify({ + results, + metadata: data, + }); +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/json.js b/node_modules/eslint/lib/cli-engine/formatters/json.js new file mode 100644 index 00000000..230f5c58 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/json.js @@ -0,0 +1,13 @@ +/** + * @fileoverview JSON reporter + * @author Burak Yigit Kaya aka BYK + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function (results) { + return JSON.stringify(results); +}; diff --git a/node_modules/eslint/lib/cli-engine/formatters/stylish.js b/node_modules/eslint/lib/cli-engine/formatters/stylish.js new file mode 100644 index 00000000..18aa5815 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/formatters/stylish.js @@ -0,0 +1,122 @@ +/** + * @fileoverview Stylish reporter + * @author Sindre Sorhus + */ +"use strict"; + +const chalk = require("chalk"), + util = require("node:util"), + table = require("../../shared/text-table"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Given a word and a count, append an s if count is not one. + * @param {string} word A word in its singular form. + * @param {number} count A number controlling whether word should be pluralized. + * @returns {string} The original word with an s on the end if count is not one. + */ +function pluralize(word, count) { + return count === 1 ? word : `${word}s`; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function (results) { + let output = "\n", + errorCount = 0, + warningCount = 0, + fixableErrorCount = 0, + fixableWarningCount = 0, + summaryColor = "yellow"; + + results.forEach(result => { + const messages = result.messages; + + if (messages.length === 0) { + return; + } + + errorCount += result.errorCount; + warningCount += result.warningCount; + fixableErrorCount += result.fixableErrorCount; + fixableWarningCount += result.fixableWarningCount; + + output += `${chalk.underline(result.filePath)}\n`; + + output += `${table( + messages.map(message => { + let messageType; + + if (message.fatal || message.severity === 2) { + messageType = chalk.red("error"); + summaryColor = "red"; + } else { + messageType = chalk.yellow("warning"); + } + + return [ + "", + String(message.line || 0), + String(message.column || 0), + messageType, + message.message.replace(/([^ ])\.$/u, "$1"), + chalk.dim(message.ruleId || ""), + ]; + }), + { + align: ["", "r", "l"], + stringLength(str) { + return util.stripVTControlCharacters(str).length; + }, + }, + ) + .split("\n") + .map(el => + el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => + chalk.dim(`${p1}:${p2}`), + ), + ) + .join("\n")}\n\n`; + }); + + const total = errorCount + warningCount; + + if (total > 0) { + output += chalk[summaryColor].bold( + [ + "\u2716 ", + total, + pluralize(" problem", total), + " (", + errorCount, + pluralize(" error", errorCount), + ", ", + warningCount, + pluralize(" warning", warningCount), + ")\n", + ].join(""), + ); + + if (fixableErrorCount > 0 || fixableWarningCount > 0) { + output += chalk[summaryColor].bold( + [ + " ", + fixableErrorCount, + pluralize(" error", fixableErrorCount), + " and ", + fixableWarningCount, + pluralize(" warning", fixableWarningCount), + " potentially fixable with the `--fix` option.\n", + ].join(""), + ); + } + } + + // Resets output color, for prevent change on top level + return total > 0 ? chalk.reset(output) : ""; +}; diff --git a/node_modules/eslint/lib/cli-engine/hash.js b/node_modules/eslint/lib/cli-engine/hash.js new file mode 100644 index 00000000..4c306b9b --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/hash.js @@ -0,0 +1,35 @@ +/** + * @fileoverview Defining the hashing function in one place. + * @author Michael Ficarra + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const murmur = require("imurmurhash"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +/** + * hash the given string + * @param {string} str the string to hash + * @returns {string} the hash + */ +function hash(str) { + return murmur(str).result().toString(36); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = hash; diff --git a/node_modules/eslint/lib/cli-engine/index.js b/node_modules/eslint/lib/cli-engine/index.js new file mode 100644 index 00000000..bba3fb0b --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/index.js @@ -0,0 +1,7 @@ +"use strict"; + +const { CLIEngine } = require("./cli-engine"); + +module.exports = { + CLIEngine, +}; diff --git a/node_modules/eslint/lib/cli-engine/lint-result-cache.js b/node_modules/eslint/lib/cli-engine/lint-result-cache.js new file mode 100644 index 00000000..1bca3e8a --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/lint-result-cache.js @@ -0,0 +1,202 @@ +/** + * @fileoverview Utility for caching lint results. + * @author Kevin Partington + */ +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const fs = require("node:fs"); +const fileEntryCache = require("file-entry-cache"); +const stringify = require("json-stable-stringify-without-jsonify"); +const pkg = require("../../package.json"); +const assert = require("../shared/assert"); +const hash = require("./hash"); + +const debug = require("debug")("eslint:lint-result-cache"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const configHashCache = new WeakMap(); +const nodeVersion = process && process.version; + +const validCacheStrategies = ["metadata", "content"]; +const invalidCacheStrategyErrorMessage = `Cache strategy must be one of: ${validCacheStrategies + .map(strategy => `"${strategy}"`) + .join(", ")}`; + +/** + * Tests whether a provided cacheStrategy is valid + * @param {string} cacheStrategy The cache strategy to use + * @returns {boolean} true if `cacheStrategy` is one of `validCacheStrategies`; false otherwise + */ +function isValidCacheStrategy(cacheStrategy) { + return validCacheStrategies.includes(cacheStrategy); +} + +/** + * Calculates the hash of the config + * @param {ConfigArray} config The config. + * @returns {string} The hash of the config + */ +function hashOfConfigFor(config) { + if (!configHashCache.has(config)) { + configHashCache.set( + config, + hash(`${pkg.version}_${nodeVersion}_${stringify(config)}`), + ); + } + + return configHashCache.get(config); +} + +//----------------------------------------------------------------------------- +// Public Interface +//----------------------------------------------------------------------------- + +/** + * Lint result cache. This wraps around the file-entry-cache module, + * transparently removing properties that are difficult or expensive to + * serialize and adding them back in on retrieval. + */ +class LintResultCache { + /** + * Creates a new LintResultCache instance. + * @param {string} cacheFileLocation The cache file location. + * @param {"metadata" | "content"} cacheStrategy The cache strategy to use. + */ + constructor(cacheFileLocation, cacheStrategy) { + assert(cacheFileLocation, "Cache file location is required"); + assert(cacheStrategy, "Cache strategy is required"); + assert( + isValidCacheStrategy(cacheStrategy), + invalidCacheStrategyErrorMessage, + ); + + debug(`Caching results to ${cacheFileLocation}`); + + const useChecksum = cacheStrategy === "content"; + + debug(`Using "${cacheStrategy}" strategy to detect changes`); + + this.fileEntryCache = fileEntryCache.create( + cacheFileLocation, + void 0, + useChecksum, + ); + this.cacheFileLocation = cacheFileLocation; + } + + /** + * Retrieve cached lint results for a given file path, if present in the + * cache. If the file is present and has not been changed, rebuild any + * missing result information. + * @param {string} filePath The file for which to retrieve lint results. + * @param {ConfigArray} config The config of the file. + * @returns {Object|null} The rebuilt lint results, or null if the file is + * changed or not in the filesystem. + */ + getCachedLintResults(filePath, config) { + /* + * Cached lint results are valid if and only if: + * 1. The file is present in the filesystem + * 2. The file has not changed since the time it was previously linted + * 3. The ESLint configuration has not changed since the time the file + * was previously linted + * If any of these are not true, we will not reuse the lint results. + */ + const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); + const hashOfConfig = hashOfConfigFor(config); + const changed = + fileDescriptor.changed || + fileDescriptor.meta.hashOfConfig !== hashOfConfig; + + if (fileDescriptor.notFound) { + debug(`File not found on the file system: ${filePath}`); + return null; + } + + if (changed) { + debug(`Cache entry not found or no longer valid: ${filePath}`); + return null; + } + + const cachedResults = fileDescriptor.meta.results; + + // Just in case, not sure if this can ever happen. + if (!cachedResults) { + return cachedResults; + } + + /* + * Shallow clone the object to ensure that any properties added or modified afterwards + * will not be accidentally stored in the cache file when `reconcile()` is called. + * https://github.com/eslint/eslint/issues/13507 + * All intentional changes to the cache file must be done through `setCachedLintResults()`. + */ + const results = { ...cachedResults }; + + // If source is present but null, need to reread the file from the filesystem. + if (results.source === null) { + debug( + `Rereading cached result source from filesystem: ${filePath}`, + ); + results.source = fs.readFileSync(filePath, "utf-8"); + } + + return results; + } + + /** + * Set the cached lint results for a given file path, after removing any + * information that will be both unnecessary and difficult to serialize. + * Avoids caching results with an "output" property (meaning fixes were + * applied), to prevent potentially incorrect results if fixes are not + * written to disk. + * @param {string} filePath The file for which to set lint results. + * @param {ConfigArray} config The config of the file. + * @param {Object} result The lint result to be set for the file. + * @returns {void} + */ + setCachedLintResults(filePath, config, result) { + if (result && Object.hasOwn(result, "output")) { + return; + } + + const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); + + if (fileDescriptor && !fileDescriptor.notFound) { + debug(`Updating cached result: ${filePath}`); + + // Serialize the result, except that we want to remove the file source if present. + const resultToSerialize = Object.assign({}, result); + + /* + * Set result.source to null. + * In `getCachedLintResults`, if source is explicitly null, we will + * read the file from the filesystem to set the value again. + */ + if (Object.hasOwn(resultToSerialize, "source")) { + resultToSerialize.source = null; + } + + fileDescriptor.meta.results = resultToSerialize; + fileDescriptor.meta.hashOfConfig = hashOfConfigFor(config); + } + } + + /** + * Persists the in-memory cache to disk. + * @returns {void} + */ + reconcile() { + debug(`Persisting cached results: ${this.cacheFileLocation}`); + this.fileEntryCache.reconcile(); + } +} + +module.exports = LintResultCache; diff --git a/node_modules/eslint/lib/cli-engine/load-rules.js b/node_modules/eslint/lib/cli-engine/load-rules.js new file mode 100644 index 00000000..5a7dc349 --- /dev/null +++ b/node_modules/eslint/lib/cli-engine/load-rules.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Module for loading rules from files and directories. + * @author Michael Ficarra + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("node:fs"), + path = require("node:path"); + +const rulesDirCache = {}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Load all rule modules from specified directory. + * @param {string} relativeRulesDir Path to rules directory, may be relative. + * @param {string} cwd Current working directory + * @returns {Object} Loaded rule modules. + */ +module.exports = function (relativeRulesDir, cwd) { + const rulesDir = path.resolve(cwd, relativeRulesDir); + + // cache will help performance as IO operation are expensive + if (rulesDirCache[rulesDir]) { + return rulesDirCache[rulesDir]; + } + + const rules = Object.create(null); + + fs.readdirSync(rulesDir).forEach(file => { + if (path.extname(file) !== ".js") { + return; + } + rules[file.slice(0, -3)] = require(path.join(rulesDir, file)); + }); + rulesDirCache[rulesDir] = rules; + + return rules; +}; diff --git a/node_modules/eslint/lib/cli.js b/node_modules/eslint/lib/cli.js new file mode 100644 index 00000000..a6babe86 --- /dev/null +++ b/node_modules/eslint/lib/cli.js @@ -0,0 +1,757 @@ +/** + * @fileoverview Main CLI object. + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* + * NOTE: The CLI object should *not* call process.exit() directly. It should only return + * exit codes. This allows other programs to use the CLI object and still control + * when the program exits. + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("node:fs"), + path = require("node:path"), + { promisify } = require("node:util"), + { LegacyESLint } = require("./eslint"), + { + ESLint, + shouldUseFlatConfig, + locateConfigFileToUse, + } = require("./eslint/eslint"), + createCLIOptions = require("./options"), + log = require("./shared/logging"), + RuntimeInfo = require("./shared/runtime-info"), + { normalizeSeverityToString } = require("./shared/severity"); +const { ModuleImporter } = require("@humanwhocodes/module-importer"); +const { getCacheFile } = require("./eslint/eslint-helpers"); +const { SuppressionsService } = require("./services/suppressions-service"); +const debug = require("debug")("eslint:cli"); +const { + normalizePackageName, + getShorthandName, +} = require("./shared/naming.js"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @import { ESLintOptions } from "./eslint/eslint.js" */ + +/** @typedef {import("./options").ParsedCLIOptions} ParsedCLIOptions */ +/** @typedef {import("./types").Linter.LintMessage} LintMessage */ +/** @typedef {import("./types").ESLint.LintResult} LintResult */ +/** @typedef {import("./types").ESLint.Plugin} Plugin */ +/** @typedef {import("./types").ESLint.ResultsMeta} ResultsMeta */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const mkdir = promisify(fs.mkdir); +const stat = promisify(fs.stat); +const writeFile = promisify(fs.writeFile); + +/** + * Loads plugins with the specified names. + * @param {{ "import": (name: string) => Promise }} importer An object with an `import` method called once for each plugin. + * @param {string[]} pluginNames The names of the plugins to be loaded, with or without the "eslint-plugin-" prefix. + * @returns {Promise>} A mapping of plugin short names to implementations. + */ +async function loadPlugins(importer, pluginNames) { + const plugins = {}; + + await Promise.all( + pluginNames.map(async pluginName => { + const longName = normalizePackageName(pluginName, "eslint-plugin"); + const module = await importer.import(longName); + + if (!("default" in module)) { + throw new Error( + `"${longName}" cannot be used with the \`--plugin\` option because its default module does not provide a \`default\` export`, + ); + } + + const shortName = getShorthandName(pluginName, "eslint-plugin"); + + plugins[shortName] = module.default; + }), + ); + + return plugins; +} + +/** + * Predicate function for whether or not to apply fixes in quiet mode. + * If a message is a warning, do not apply a fix. + * @param {LintMessage} message The lint result. + * @returns {boolean} True if the lint message is an error (and thus should be + * autofixed), false otherwise. + */ +function quietFixPredicate(message) { + return message.severity === 2; +} + +/** + * Predicate function for whether or not to run a rule in quiet mode. + * If a rule is set to warning, do not run it. + * @param {{ ruleId: string; severity: number; }} rule The rule id and severity. + * @returns {boolean} True if the lint rule should run, false otherwise. + */ +function quietRuleFilter(rule) { + return rule.severity === 2; +} + +/** + * Translates the CLI options into the options expected by the ESLint constructor. + * @param {ParsedCLIOptions} cliOptions The CLI options to translate. + * @param {"flat"|"eslintrc"} [configType="eslintrc"] The format of the + * config to generate. + * @returns {Promise} The options object for the ESLint constructor. + * @private + */ +async function translateOptions( + { + cache, + cacheFile, + cacheLocation, + cacheStrategy, + config, + configLookup, + env, + errorOnUnmatchedPattern, + eslintrc, + ext, + fix, + fixDryRun, + fixType, + flag, + global, + ignore, + ignorePath, + ignorePattern, + inlineConfig, + parser, + parserOptions, + plugin, + quiet, + reportUnusedDisableDirectives, + reportUnusedDisableDirectivesSeverity, + reportUnusedInlineConfigs, + resolvePluginsRelativeTo, + rule, + rulesdir, + stats, + warnIgnored, + passOnNoPatterns, + maxWarnings, + }, + configType, +) { + let overrideConfig, overrideConfigFile; + const importer = new ModuleImporter(); + + if (configType === "flat") { + overrideConfigFile = + typeof config === "string" ? config : !configLookup; + if (overrideConfigFile === false) { + overrideConfigFile = void 0; + } + + const languageOptions = {}; + + if (global) { + languageOptions.globals = global.reduce((obj, name) => { + if (name.endsWith(":true")) { + obj[name.slice(0, -5)] = "writable"; + } else { + obj[name] = "readonly"; + } + return obj; + }, {}); + } + + if (parserOptions) { + languageOptions.parserOptions = parserOptions; + } + + if (parser) { + languageOptions.parser = await importer.import(parser); + } + + overrideConfig = [ + { + ...(Object.keys(languageOptions).length > 0 + ? { languageOptions } + : {}), + rules: rule ? rule : {}, + }, + ]; + + if ( + reportUnusedDisableDirectives || + reportUnusedDisableDirectivesSeverity !== void 0 + ) { + overrideConfig[0].linterOptions = { + reportUnusedDisableDirectives: reportUnusedDisableDirectives + ? "error" + : normalizeSeverityToString( + reportUnusedDisableDirectivesSeverity, + ), + }; + } + + if (reportUnusedInlineConfigs !== void 0) { + overrideConfig[0].linterOptions = { + ...overrideConfig[0].linterOptions, + reportUnusedInlineConfigs: normalizeSeverityToString( + reportUnusedInlineConfigs, + ), + }; + } + + if (plugin) { + overrideConfig[0].plugins = await loadPlugins(importer, plugin); + } + + if (ext) { + overrideConfig.push({ + files: ext.map( + extension => + `**/*${extension.startsWith(".") ? "" : "."}${extension}`, + ), + }); + } + } else { + overrideConfigFile = config; + + overrideConfig = { + env: + env && + env.reduce((obj, name) => { + obj[name] = true; + return obj; + }, {}), + globals: + global && + global.reduce((obj, name) => { + if (name.endsWith(":true")) { + obj[name.slice(0, -5)] = "writable"; + } else { + obj[name] = "readonly"; + } + return obj; + }, {}), + ignorePatterns: ignorePattern, + parser, + parserOptions, + plugins: plugin, + rules: rule, + }; + } + + const options = { + allowInlineConfig: inlineConfig, + cache, + cacheLocation: cacheLocation || cacheFile, + cacheStrategy, + errorOnUnmatchedPattern, + fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true), + fixTypes: fixType, + ignore, + overrideConfig, + overrideConfigFile, + passOnNoPatterns, + }; + + if (configType === "flat") { + options.ignorePatterns = ignorePattern; + options.stats = stats; + options.warnIgnored = warnIgnored; + options.flags = flag; + + /* + * For performance reasons rules not marked as 'error' are filtered out in quiet mode. As maxWarnings + * requires rules set to 'warn' to be run, we only filter out 'warn' rules if maxWarnings is not specified. + */ + options.ruleFilter = + quiet && maxWarnings === -1 ? quietRuleFilter : () => true; + } else { + options.resolvePluginsRelativeTo = resolvePluginsRelativeTo; + options.rulePaths = rulesdir; + options.useEslintrc = eslintrc; + options.extensions = ext; + options.ignorePath = ignorePath; + if ( + reportUnusedDisableDirectives || + reportUnusedDisableDirectivesSeverity !== void 0 + ) { + options.reportUnusedDisableDirectives = + reportUnusedDisableDirectives + ? "error" + : normalizeSeverityToString( + reportUnusedDisableDirectivesSeverity, + ); + } + } + + return options; +} + +/** + * Count error messages. + * @param {LintResult[]} results The lint results. + * @returns {{errorCount:number;fatalErrorCount:number,warningCount:number}} The number of error messages. + */ +function countErrors(results) { + let errorCount = 0; + let fatalErrorCount = 0; + let warningCount = 0; + + for (const result of results) { + errorCount += result.errorCount; + fatalErrorCount += result.fatalErrorCount; + warningCount += result.warningCount; + } + + return { errorCount, fatalErrorCount, warningCount }; +} + +/** + * Check if a given file path is a directory or not. + * @param {string} filePath The path to a file to check. + * @returns {Promise} `true` if the given path is a directory. + */ +async function isDirectory(filePath) { + try { + return (await stat(filePath)).isDirectory(); + } catch (error) { + if (error.code === "ENOENT" || error.code === "ENOTDIR") { + return false; + } + throw error; + } +} + +/** + * Outputs the results of the linting. + * @param {ESLint} engine The ESLint instance to use. + * @param {LintResult[]} results The results to print. + * @param {string} format The name of the formatter to use or the path to the formatter. + * @param {string} outputFile The path for the output file. + * @param {ResultsMeta} resultsMeta Warning count and max threshold. + * @returns {Promise} True if the printing succeeds, false if not. + * @private + */ +async function printResults(engine, results, format, outputFile, resultsMeta) { + let formatter; + + try { + formatter = await engine.loadFormatter(format); + } catch (e) { + log.error(e.message); + return false; + } + + const output = await formatter.format(results, resultsMeta); + + if (outputFile) { + const filePath = path.resolve(process.cwd(), outputFile); + + if (await isDirectory(filePath)) { + log.error( + "Cannot write to output file path, it is a directory: %s", + outputFile, + ); + return false; + } + + try { + await mkdir(path.dirname(filePath), { recursive: true }); + await writeFile(filePath, output); + } catch (ex) { + log.error("There was a problem writing the output file:\n%s", ex); + return false; + } + } else if (output) { + log.info(output); + } + + return true; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as + * for other Node.js programs to effectively run the CLI. + */ +const cli = { + /** + * Calculates the command string for the --inspect-config operation. + * @param {string} configFile The path to the config file to inspect. + * @returns {Promise} The command string to execute. + */ + async calculateInspectConfigFlags(configFile) { + // find the config file + const { configFilePath, basePath } = await locateConfigFileToUse({ + cwd: process.cwd(), + configFile, + }); + + return ["--config", configFilePath, "--basePath", basePath]; + }, + + /** + * Executes the CLI based on an array of arguments that is passed in. + * @param {string|Array|Object} args The arguments to process. + * @param {string} [text] The text to lint (used for TTY). + * @param {boolean} [allowFlatConfig=true] Whether or not to allow flat config. + * @returns {Promise} The exit code for the operation. + */ + async execute(args, text, allowFlatConfig = true) { + if (Array.isArray(args)) { + debug("CLI args: %o", args.slice(2)); + } + + /* + * Before doing anything, we need to see if we are using a + * flat config file. If so, then we need to change the way command + * line args are parsed. This is temporary, and when we fully + * switch to flat config we can remove this logic. + */ + + const usingFlatConfig = + allowFlatConfig && (await shouldUseFlatConfig()); + + debug("Using flat config?", usingFlatConfig); + + if (allowFlatConfig && !usingFlatConfig) { + const { WarningService } = require("./services/warning-service"); + new WarningService().emitESLintRCWarning(); + } + + const CLIOptions = createCLIOptions(usingFlatConfig); + + /** @type {ParsedCLIOptions} */ + let options; + + try { + options = CLIOptions.parse(args); + } catch (error) { + debug("Error parsing CLI options:", error.message); + + let errorMessage = error.message; + + if (usingFlatConfig) { + errorMessage += + "\nYou're using eslint.config.js, some command line flags are no longer available. Please see https://eslint.org/docs/latest/use/command-line-interface for details."; + } + + log.error(errorMessage); + return 2; + } + + const files = options._; + const useStdin = typeof text === "string"; + + if (options.help) { + log.info(CLIOptions.generateHelp()); + return 0; + } + if (options.version) { + log.info(RuntimeInfo.version()); + return 0; + } + if (options.envInfo) { + try { + log.info(RuntimeInfo.environment()); + return 0; + } catch (err) { + debug("Error retrieving environment info"); + log.error(err.message); + return 2; + } + } + + if (options.printConfig) { + if (files.length) { + log.error( + "The --print-config option must be used with exactly one file name.", + ); + return 2; + } + if (useStdin) { + log.error( + "The --print-config option is not available for piped-in code.", + ); + return 2; + } + + const engine = usingFlatConfig + ? new ESLint(await translateOptions(options, "flat")) + : new LegacyESLint(await translateOptions(options)); + const fileConfig = await engine.calculateConfigForFile( + options.printConfig, + ); + + log.info(JSON.stringify(fileConfig, null, " ")); + return 0; + } + + if (options.inspectConfig) { + log.info( + "You can also run this command directly using 'npx @eslint/config-inspector@latest' in the same directory as your configuration file.", + ); + + try { + const flatOptions = await translateOptions(options, "flat"); + const spawn = require("cross-spawn"); + const flags = await cli.calculateInspectConfigFlags( + flatOptions.overrideConfigFile, + ); + + spawn.sync( + "npx", + ["@eslint/config-inspector@latest", ...flags], + { encoding: "utf8", stdio: "inherit" }, + ); + } catch (error) { + log.error(error); + return 2; + } + + return 0; + } + + debug(`Running on ${useStdin ? "text" : "files"}`); + + if (options.fix && options.fixDryRun) { + log.error( + "The --fix option and the --fix-dry-run option cannot be used together.", + ); + return 2; + } + if (useStdin && options.fix) { + log.error( + "The --fix option is not available for piped-in code; use --fix-dry-run instead.", + ); + return 2; + } + if (options.fixType && !options.fix && !options.fixDryRun) { + log.error( + "The --fix-type option requires either --fix or --fix-dry-run.", + ); + return 2; + } + + if ( + options.reportUnusedDisableDirectives && + options.reportUnusedDisableDirectivesSeverity !== void 0 + ) { + log.error( + "The --report-unused-disable-directives option and the --report-unused-disable-directives-severity option cannot be used together.", + ); + return 2; + } + + if (usingFlatConfig && options.ext) { + // Passing `--ext ""` results in `options.ext` being an empty array. + if (options.ext.length === 0) { + log.error("The --ext option value cannot be empty."); + return 2; + } + + // Passing `--ext ,ts` results in an empty string at index 0. Passing `--ext ts,,tsx` results in an empty string at index 1. + const emptyStringIndex = options.ext.indexOf(""); + + if (emptyStringIndex >= 0) { + log.error( + `The --ext option arguments cannot be empty strings. Found an empty string at index ${emptyStringIndex}.`, + ); + return 2; + } + } + + if (options.suppressAll && options.suppressRule) { + log.error( + "The --suppress-all option and the --suppress-rule option cannot be used together.", + ); + return 2; + } + + if (options.suppressAll && options.pruneSuppressions) { + log.error( + "The --suppress-all option and the --prune-suppressions option cannot be used together.", + ); + return 2; + } + + if (options.suppressRule && options.pruneSuppressions) { + log.error( + "The --suppress-rule option and the --prune-suppressions option cannot be used together.", + ); + return 2; + } + + if ( + useStdin && + (options.suppressAll || + options.suppressRule || + options.pruneSuppressions) + ) { + log.error( + "The --suppress-all, --suppress-rule, and --prune-suppressions options cannot be used with piped-in code.", + ); + return 2; + } + + const ActiveESLint = usingFlatConfig ? ESLint : LegacyESLint; + const eslintOptions = await translateOptions( + options, + usingFlatConfig ? "flat" : "eslintrc", + ); + const engine = new ActiveESLint(eslintOptions); + let results; + + if (useStdin) { + results = await engine.lintText(text, { + filePath: options.stdinFilename, + + // flatConfig respects CLI flag and constructor warnIgnored, eslintrc forces true for backwards compatibility + warnIgnored: usingFlatConfig ? void 0 : true, + }); + } else { + results = await engine.lintFiles(files); + } + + if (options.fix) { + debug("Fix mode enabled - applying fixes"); + await ActiveESLint.outputFixes(results); + } + + let unusedSuppressions = {}; + + if (!useStdin) { + const suppressionsFileLocation = getCacheFile( + options.suppressionsLocation || "eslint-suppressions.json", + process.cwd(), + { + prefix: "suppressions_", + }, + ); + + if ( + options.suppressionsLocation && + !fs.existsSync(suppressionsFileLocation) && + !options.suppressAll && + !options.suppressRule + ) { + log.error( + "The suppressions file does not exist. Please run the command with `--suppress-all` or `--suppress-rule` to create it.", + ); + return 2; + } + + if ( + options.suppressAll || + options.suppressRule || + options.pruneSuppressions || + fs.existsSync(suppressionsFileLocation) + ) { + const suppressions = new SuppressionsService({ + filePath: suppressionsFileLocation, + cwd: process.cwd(), + }); + + if (options.suppressAll || options.suppressRule) { + await suppressions.suppress(results, options.suppressRule); + } + + if (options.pruneSuppressions) { + await suppressions.prune(results); + } + + const suppressionResults = suppressions.applySuppressions( + results, + await suppressions.load(), + ); + + results = suppressionResults.results; + unusedSuppressions = suppressionResults.unused; + } + } + + let resultsToPrint = results; + + if (options.quiet) { + debug("Quiet mode enabled - filtering out warnings"); + resultsToPrint = ActiveESLint.getErrorResults(resultsToPrint); + } + + const resultCounts = countErrors(results); + const tooManyWarnings = + options.maxWarnings >= 0 && + resultCounts.warningCount > options.maxWarnings; + const resultsMeta = tooManyWarnings + ? { + maxWarningsExceeded: { + maxWarnings: options.maxWarnings, + foundWarnings: resultCounts.warningCount, + }, + } + : {}; + + if ( + await printResults( + engine, + resultsToPrint, + options.format, + options.outputFile, + resultsMeta, + ) + ) { + // Errors and warnings from the original unfiltered results should determine the exit code + const shouldExitForFatalErrors = + options.exitOnFatalError && resultCounts.fatalErrorCount > 0; + + if (!resultCounts.errorCount && tooManyWarnings) { + log.error( + "ESLint found too many warnings (maximum: %s).", + options.maxWarnings, + ); + } + + if (!options.passOnUnprunedSuppressions) { + const unusedSuppressionsCount = + Object.keys(unusedSuppressions).length; + + if (unusedSuppressionsCount > 0) { + log.error( + "There are suppressions left that do not occur anymore. Consider re-running the command with `--prune-suppressions`.", + ); + debug(JSON.stringify(unusedSuppressions, null, 2)); + + return 2; + } + } + + if (shouldExitForFatalErrors) { + return 2; + } + + return resultCounts.errorCount || tooManyWarnings ? 1 : 0; + } + + return 2; + }, +}; + +module.exports = cli; diff --git a/node_modules/eslint/lib/config-api.js b/node_modules/eslint/lib/config-api.js new file mode 100644 index 00000000..5050a631 --- /dev/null +++ b/node_modules/eslint/lib/config-api.js @@ -0,0 +1,12 @@ +/** + * @fileoverview exports for config helpers + * @author Nicholas C. Zakas + */ + +"use strict"; +const { defineConfig, globalIgnores } = require("@eslint/config-helpers"); + +module.exports = { + defineConfig, + globalIgnores, +}; diff --git a/node_modules/eslint/lib/config/config-loader.js b/node_modules/eslint/lib/config/config-loader.js new file mode 100644 index 00000000..3a2e3826 --- /dev/null +++ b/node_modules/eslint/lib/config/config-loader.js @@ -0,0 +1,843 @@ +/** + * @fileoverview Utility to load config files + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("node:path"); +const fs = require("node:fs/promises"); +const findUp = require("find-up"); +const { pathToFileURL } = require("node:url"); +const debug = require("debug")("eslint:config-loader"); +const { FlatConfigArray } = require("./flat-config-array"); +const { WarningService } = require("../services/warning-service"); + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("../types").Linter.Config} Config */ + +/** + * @typedef {Object} ConfigLoaderOptions + * @property {string|false|undefined} configFile The path to the config file to use. + * @property {string} cwd The current working directory. + * @property {boolean} ignoreEnabled Indicates if ignore patterns should be honored. + * @property {Config|Array} [baseConfig] The base config to use. + * @property {Array} [defaultConfigs] The default configs to use. + * @property {Array} [ignorePatterns] The ignore patterns to use. + * @property {Config|Array} [overrideConfig] The override config to use. + * @property {boolean} [hasUnstableNativeNodeJsTSConfigFlag] The flag to indicate whether the `unstable_native_nodejs_ts_config` flag is enabled. + * @property {WarningService} [warningService] The warning service to use. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const FLAT_CONFIG_FILENAMES = [ + "eslint.config.js", + "eslint.config.mjs", + "eslint.config.cjs", + "eslint.config.ts", + "eslint.config.mts", + "eslint.config.cts", +]; + +const importedConfigFileModificationTime = new Map(); + +/** + * Asserts that the given file path is valid. + * @param {string} filePath The file path to check. + * @returns {void} + * @throws {Error} If `filePath` is not a non-empty string. + */ +function assertValidFilePath(filePath) { + if (!filePath || typeof filePath !== "string") { + throw new Error("'filePath' must be a non-empty string"); + } +} + +/** + * Asserts that a configuration exists. A configuration exists if any + * of the following are true: + * - `configFilePath` is defined. + * - `useConfigFile` is `false`. + * @param {string|undefined} configFilePath The path to the config file. + * @param {ConfigLoaderOptions} loaderOptions The options to use when loading configuration files. + * @returns {void} + * @throws {Error} If no configuration exists. + */ +function assertConfigurationExists(configFilePath, loaderOptions) { + const { configFile: useConfigFile } = loaderOptions; + + if (!configFilePath && useConfigFile !== false) { + const error = new Error("Could not find config file."); + + error.messageTemplate = "config-file-missing"; + throw error; + } +} + +/** + * Check if the file is a TypeScript file. + * @param {string} filePath The file path to check. + * @returns {boolean} `true` if the file is a TypeScript file, `false` if it's not. + */ +function isFileTS(filePath) { + const fileExtension = path.extname(filePath); + + return /^\.[mc]?ts$/u.test(fileExtension); +} + +/** + * Check if ESLint is running in Bun. + * @returns {boolean} `true` if the ESLint is running Bun, `false` if it's not. + */ +function isRunningInBun() { + return !!globalThis.Bun; +} + +/** + * Check if ESLint is running in Deno. + * @returns {boolean} `true` if the ESLint is running in Deno, `false` if it's not. + */ +function isRunningInDeno() { + return !!globalThis.Deno; +} + +/** + * Checks if native TypeScript support is + * enabled in the current Node.js process. + * + * This function determines if the + * {@linkcode NodeJS.ProcessFeatures.typescript | typescript} + * feature is present in the + * {@linkcode process.features} object + * and if its value is either "strip" or "transform". + * @returns {boolean} `true` if native TypeScript support is enabled, otherwise `false`. + * @since 9.24.0 + */ +function isNativeTypeScriptSupportEnabled() { + return ( + // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it's still an experimental feature. + ["strip", "transform"].includes(process.features.typescript) + ); +} + +/** + * Load the TypeScript configuration file. + * @param {string} filePath The absolute file path to load. + * @param {URL} fileURL The file URL to load. + * @param {number} mtime The last modified timestamp of the file. + * @returns {Promise} The configuration loaded from the file. + * @since 9.24.0 + */ +async function loadTypeScriptConfigFileWithJiti(filePath, fileURL, mtime) { + const { createJiti, version: jitiVersion } = + // eslint-disable-next-line no-use-before-define -- `ConfigLoader.loadJiti` can be overwritten for testing + await ConfigLoader.loadJiti().catch(() => { + throw new Error( + "The 'jiti' library is required for loading TypeScript configuration files. Make sure to install it.", + ); + }); + + // `createJiti` was added in jiti v2. + if (typeof createJiti !== "function") { + throw new Error( + "You are using an outdated version of the 'jiti' library. Please update to the latest version of 'jiti' to ensure compatibility and access to the latest features.", + ); + } + + /* + * Disabling `moduleCache` allows us to reload a + * config file when the last modified timestamp changes. + */ + const jitiOptions = { + moduleCache: false, + }; + + if (jitiVersion.startsWith("2.1.")) { + jitiOptions.interopDefault = false; + } + + const jiti = createJiti(__filename, jitiOptions); + const config = await jiti.import(fileURL.href); + + importedConfigFileModificationTime.set(filePath, mtime); + + return config?.default ?? config; +} + +/** + * Dynamically imports a module from the given file path. + * @param {string} filePath The absolute file path of the module to import. + * @param {URL} fileURL The file URL to load. + * @param {number} mtime The last modified timestamp of the file. + * @returns {Promise} - A {@linkcode Promise | promise} that resolves to the imported ESLint config. + * @since 9.24.0 + */ +async function dynamicImportConfig(filePath, fileURL, mtime) { + const module = await import(fileURL.href); + + importedConfigFileModificationTime.set(filePath, mtime); + + return module.default; +} + +/** + * Load the config array from the given filename. + * @param {string} filePath The filename to load from. + * @param {boolean} hasUnstableNativeNodeJsTSConfigFlag The flag to indicate whether the `unstable_native_nodejs_ts_config` flag is enabled. + * @returns {Promise} The config loaded from the config file. + */ +async function loadConfigFile(filePath, hasUnstableNativeNodeJsTSConfigFlag) { + debug(`Loading config from ${filePath}`); + + const fileURL = pathToFileURL(filePath); + + debug(`Config file URL is ${fileURL}`); + + const mtime = (await fs.stat(filePath)).mtime.getTime(); + + /* + * Append a query with the config file's modification time (`mtime`) in order + * to import the current version of the config file. Without the query, `import()` would + * cache the config file module by the pathname only, and then always return + * the same version (the one that was actual when the module was imported for the first time). + * + * This ensures that the config file module is loaded and executed again + * if it has been changed since the last time it was imported. + * If it hasn't been changed, `import()` will just return the cached version. + * + * Note that we should not overuse queries (e.g., by appending the current time + * to always reload the config file module) as that could cause memory leaks + * because entries are never removed from the import cache. + */ + fileURL.searchParams.append("mtime", mtime); + + /* + * With queries, we can bypass the import cache. However, when import-ing a CJS module, + * Node.js uses the require infrastructure under the hood. That includes the require cache, + * which caches the config file module by its file path (queries have no effect). + * Therefore, we also need to clear the require cache before importing the config file module. + * In order to get the same behavior with ESM and CJS config files, in particular - to reload + * the config file only if it has been changed, we track file modification times and clear + * the require cache only if the file has been changed. + */ + if (importedConfigFileModificationTime.get(filePath) !== mtime) { + delete require.cache[filePath]; + } + + const isTS = isFileTS(filePath); + const isBun = isRunningInBun(); + const isDeno = isRunningInDeno(); + + /* + * If we are dealing with a TypeScript file, then we need to use `jiti` to load it + * in Node.js. Deno and Bun both allow native importing of TypeScript files. + * + * When Node.js supports native TypeScript imports, we can remove this check. + */ + + if (isTS) { + if (hasUnstableNativeNodeJsTSConfigFlag) { + if (isNativeTypeScriptSupportEnabled()) { + return await dynamicImportConfig(filePath, fileURL, mtime); + } + + if (!("typescript" in process.features)) { + throw new Error( + "The unstable_native_nodejs_ts_config flag is not supported in older versions of Node.js.", + ); + } + + throw new Error( + "The unstable_native_nodejs_ts_config flag is enabled, but native TypeScript support is not enabled in the current Node.js process. You need to either enable native TypeScript support by passing --experimental-strip-types or remove the unstable_native_nodejs_ts_config flag.", + ); + } + + if (!isDeno && !isBun) { + return await loadTypeScriptConfigFileWithJiti( + filePath, + fileURL, + mtime, + ); + } + } + + // fallback to normal runtime behavior + + return await dynamicImportConfig(filePath, fileURL, mtime); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Encapsulates the loading and caching of configuration files when looking up + * from the file being linted. + */ +class ConfigLoader { + /** + * Map of config file paths to the config arrays for those directories. + * @type {Map>} + */ + #configArrays = new Map(); + + /** + * Map of absolute directory names to the config file paths for those directories. + * @type {Map>} + */ + #configFilePaths = new Map(); + + /** + * The options to use when loading configuration files. + * @type {ConfigLoaderOptions} + */ + #options; + + /** + * Creates a new instance. + * @param {ConfigLoaderOptions} options The options to use when loading configuration files. + */ + constructor(options) { + this.#options = options.warningService + ? options + : { ...options, warningService: new WarningService() }; + } + + /** + * Determines which config file to use. This is determined by seeing if an + * override config file was specified, and if so, using it; otherwise, as long + * as override config file is not explicitly set to `false`, it will search + * upwards from `fromDirectory` for a file named `eslint.config.js`. + * @param {string} fromDirectory The directory from which to start searching. + * @returns {Promise<{configFilePath:string|undefined,basePath:string}>} Location information for + * the config file. + */ + async #locateConfigFileToUse(fromDirectory) { + // check cache first + if (this.#configFilePaths.has(fromDirectory)) { + return this.#configFilePaths.get(fromDirectory); + } + + const resultPromise = ConfigLoader.locateConfigFileToUse({ + useConfigFile: this.#options.configFile, + cwd: this.#options.cwd, + fromDirectory, + }); + + // ensure `ConfigLoader.locateConfigFileToUse` is called only once for `fromDirectory` + this.#configFilePaths.set(fromDirectory, resultPromise); + + // Unwrap the promise. This is primarily for the sync `getCachedConfigArrayForPath` method. + const result = await resultPromise; + + this.#configFilePaths.set(fromDirectory, result); + + return result; + } + + /** + * Calculates the config array for this run based on inputs. + * @param {string} configFilePath The absolute path to the config file to use if not overridden. + * @param {string} basePath The base path to use for relative paths in the config file. + * @returns {Promise} The config array for `eslint`. + */ + async #calculateConfigArray(configFilePath, basePath) { + // check for cached version first + if (this.#configArrays.has(configFilePath)) { + return this.#configArrays.get(configFilePath); + } + + const configsPromise = ConfigLoader.calculateConfigArray( + configFilePath, + basePath, + this.#options, + ); + + // ensure `ConfigLoader.calculateConfigArray` is called only once for `configFilePath` + this.#configArrays.set(configFilePath, configsPromise); + + // Unwrap the promise. This is primarily for the sync `getCachedConfigArrayForPath` method. + const configs = await configsPromise; + + this.#configArrays.set(configFilePath, configs); + + return configs; + } + + /** + * Returns the config file path for the given directory or file. This will either use + * the override config file that was specified in the constructor options or + * search for a config file from the directory. + * @param {string} fileOrDirPath The file or directory path to get the config file path for. + * @returns {Promise} The config file path or `undefined` if not found. + * @throws {Error} If `fileOrDirPath` is not a non-empty string. + * @throws {Error} If `fileOrDirPath` is not an absolute path. + */ + async findConfigFileForPath(fileOrDirPath) { + assertValidFilePath(fileOrDirPath); + + const absoluteDirPath = path.resolve( + this.#options.cwd, + path.dirname(fileOrDirPath), + ); + const { configFilePath } = + await this.#locateConfigFileToUse(absoluteDirPath); + + return configFilePath; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file or directory to retrieve config for. + * @returns {Promise} A configuration object for the file. + * @throws {Error} If no configuration for `filePath` exists. + */ + async loadConfigArrayForFile(filePath) { + assertValidFilePath(filePath); + + debug(`Calculating config for file ${filePath}`); + + const configFilePath = await this.findConfigFileForPath(filePath); + + assertConfigurationExists(configFilePath, this.#options); + + return this.loadConfigArrayForDirectory(filePath); + } + + /** + * Returns a configuration object for the given directory based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} dirPath The path of the directory to retrieve config for. + * @returns {Promise} A configuration object for the directory. + */ + async loadConfigArrayForDirectory(dirPath) { + assertValidFilePath(dirPath); + + debug(`Calculating config for directory ${dirPath}`); + + const absoluteDirPath = path.resolve( + this.#options.cwd, + path.dirname(dirPath), + ); + const { configFilePath, basePath } = + await this.#locateConfigFileToUse(absoluteDirPath); + + debug(`Using config file ${configFilePath} and base path ${basePath}`); + return this.#calculateConfigArray(configFilePath, basePath); + } + + /** + * Returns a configuration array for the given file based on the CLI options. + * This is a synchronous operation and does not read any files from disk. It's + * intended to be used in locations where we know the config file has already + * been loaded and we just need to get the configuration for a file. + * @param {string} filePath The path of the file to retrieve a config object for. + * @returns {FlatConfigArray} A configuration object for the file. + * @throws {Error} If `filePath` is not a non-empty string. + * @throws {Error} If `filePath` is not an absolute path. + * @throws {Error} If the config file was not already loaded. + */ + getCachedConfigArrayForFile(filePath) { + assertValidFilePath(filePath); + + debug(`Looking up cached config for ${filePath}`); + + return this.getCachedConfigArrayForPath(path.dirname(filePath)); + } + + /** + * Returns a configuration array for the given directory based on the CLI options. + * This is a synchronous operation and does not read any files from disk. It's + * intended to be used in locations where we know the config file has already + * been loaded and we just need to get the configuration for a file. + * @param {string} fileOrDirPath The path of the directory to retrieve a config object for. + * @returns {FlatConfigArray} A configuration object for the directory. + * @throws {Error} If `dirPath` is not a non-empty string. + * @throws {Error} If `dirPath` is not an absolute path. + * @throws {Error} If the config file was not already loaded. + */ + getCachedConfigArrayForPath(fileOrDirPath) { + assertValidFilePath(fileOrDirPath); + + debug(`Looking up cached config for ${fileOrDirPath}`); + + const absoluteDirPath = path.resolve(this.#options.cwd, fileOrDirPath); + + if (!this.#configFilePaths.has(absoluteDirPath)) { + throw new Error(`Could not find config file for ${fileOrDirPath}`); + } + + const configFilePathInfo = this.#configFilePaths.get(absoluteDirPath); + + if (typeof configFilePathInfo.then === "function") { + throw new Error( + `Config file path for ${fileOrDirPath} has not yet been calculated or an error occurred during the calculation`, + ); + } + + const { configFilePath } = configFilePathInfo; + + const configArray = this.#configArrays.get(configFilePath); + + if (!configArray || typeof configArray.then === "function") { + throw new Error( + `Config array for ${fileOrDirPath} has not yet been calculated or an error occurred during the calculation`, + ); + } + + return configArray; + } + + /** + * Used to import the jiti dependency. This method is exposed internally for testing purposes. + * @returns {Promise<{createJiti: Function|undefined, version: string;}>} A promise that fulfills with an object containing the jiti module's createJiti function and version. + */ + static async loadJiti() { + const { createJiti } = await import("jiti"); + const version = require("jiti/package.json").version; + return { createJiti, version }; + } + + /** + * Determines which config file to use. This is determined by seeing if an + * override config file was specified, and if so, using it; otherwise, as long + * as override config file is not explicitly set to `false`, it will search + * upwards from `fromDirectory` for a file named `eslint.config.js`. + * This method is exposed internally for testing purposes. + * @param {Object} [options] the options object + * @param {string|false|undefined} options.useConfigFile The path to the config file to use. + * @param {string} options.cwd Path to a directory that should be considered as the current working directory. + * @param {string} [options.fromDirectory] The directory from which to start searching. Defaults to `cwd`. + * @returns {Promise<{configFilePath:string|undefined,basePath:string}>} Location information for + * the config file. + */ + static async locateConfigFileToUse({ + useConfigFile, + cwd, + fromDirectory = cwd, + }) { + // determine where to load config file from + let configFilePath; + let basePath = cwd; + + if (typeof useConfigFile === "string") { + debug(`Override config file path is ${useConfigFile}`); + configFilePath = path.resolve(cwd, useConfigFile); + basePath = cwd; + } else if (useConfigFile !== false) { + debug("Searching for eslint.config.js"); + configFilePath = await findUp(FLAT_CONFIG_FILENAMES, { + cwd: fromDirectory, + }); + + if (configFilePath) { + basePath = path.dirname(configFilePath); + } + } + + return { + configFilePath, + basePath, + }; + } + + /** + * Calculates the config array for this run based on inputs. + * This method is exposed internally for testing purposes. + * @param {string} configFilePath The absolute path to the config file to use if not overridden. + * @param {string} basePath The base path to use for relative paths in the config file. + * @param {ConfigLoaderOptions} options The options to use when loading configuration files. + * @returns {Promise} The config array for `eslint`. + */ + static async calculateConfigArray(configFilePath, basePath, options) { + const { + cwd, + baseConfig, + ignoreEnabled, + ignorePatterns, + overrideConfig, + hasUnstableNativeNodeJsTSConfigFlag = false, + defaultConfigs = [], + warningService, + } = options; + + debug( + `Calculating config array from config file ${configFilePath} and base path ${basePath}`, + ); + + const configs = new FlatConfigArray(baseConfig || [], { + basePath, + shouldIgnore: ignoreEnabled, + }); + + // load config file + if (configFilePath) { + debug(`Loading config file ${configFilePath}`); + const fileConfig = await loadConfigFile( + configFilePath, + hasUnstableNativeNodeJsTSConfigFlag, + ); + + /* + * It's possible that a config file could be empty or else + * have an empty object or array. In this case, we want to + * warn the user that they have an empty config. + * + * An empty CommonJS file exports an empty object while + * an empty ESM file exports undefined. + */ + + let emptyConfig = typeof fileConfig === "undefined"; + + debug( + `Config file ${configFilePath} is ${emptyConfig ? "empty" : "not empty"}`, + ); + + if (!emptyConfig) { + if (Array.isArray(fileConfig)) { + if (fileConfig.length === 0) { + debug( + `Config file ${configFilePath} is an empty array`, + ); + emptyConfig = true; + } else { + configs.push(...fileConfig); + } + } else { + if ( + typeof fileConfig === "object" && + fileConfig !== null && + Object.keys(fileConfig).length === 0 + ) { + debug( + `Config file ${configFilePath} is an empty object`, + ); + emptyConfig = true; + } else { + configs.push(fileConfig); + } + } + } + + if (emptyConfig) { + warningService.emitEmptyConfigWarning(configFilePath); + } + } + + // add in any configured defaults + configs.push(...defaultConfigs); + + // append command line ignore patterns + if (ignorePatterns && ignorePatterns.length > 0) { + let relativeIgnorePatterns; + + /* + * If the config file basePath is different than the cwd, then + * the ignore patterns won't work correctly. Here, we adjust the + * ignore pattern to include the correct relative path. Patterns + * passed as `ignorePatterns` are relative to the cwd, whereas + * the config file basePath can be an ancestor of the cwd. + */ + if (basePath === cwd) { + relativeIgnorePatterns = ignorePatterns; + } else { + // relative path must only have Unix-style separators + const relativeIgnorePath = path + .relative(basePath, cwd) + .replace(/\\/gu, "/"); + + relativeIgnorePatterns = ignorePatterns.map(pattern => { + const negated = pattern.startsWith("!"); + const basePattern = negated ? pattern.slice(1) : pattern; + + return ( + (negated ? "!" : "") + + path.posix.join(relativeIgnorePath, basePattern) + ); + }); + } + + /* + * Ignore patterns are added to the end of the config array + * so they can override default ignores. + */ + configs.push({ + ignores: relativeIgnorePatterns, + }); + } + + if (overrideConfig) { + if (Array.isArray(overrideConfig)) { + configs.push(...overrideConfig); + } else { + configs.push(overrideConfig); + } + } + + await configs.normalize(); + + return configs; + } +} + +/** + * Encapsulates the loading and caching of configuration files when looking up + * from the current working directory. + */ +class LegacyConfigLoader extends ConfigLoader { + /** + * The options to use when loading configuration files. + * @type {ConfigLoaderOptions} + */ + #options; + + /** + * The cached config file path for this instance. + * @type {Promise<{configFilePath:string,basePath:string}|undefined>} + */ + #configFilePath; + + /** + * The cached config array for this instance. + * @type {FlatConfigArray|Promise} + */ + #configArray; + + /** + * Creates a new instance. + * @param {ConfigLoaderOptions} options The options to use when loading configuration files. + */ + constructor(options) { + const normalizedOptions = options.warningService + ? options + : { ...options, warningService: new WarningService() }; + super(normalizedOptions); + this.#options = normalizedOptions; + } + + /** + * Determines which config file to use. This is determined by seeing if an + * override config file was specified, and if so, using it; otherwise, as long + * as override config file is not explicitly set to `false`, it will search + * upwards from the cwd for a file named `eslint.config.js`. + * @returns {Promise<{configFilePath:string|undefined,basePath:string}>} Location information for + * the config file. + */ + #locateConfigFileToUse() { + if (!this.#configFilePath) { + this.#configFilePath = ConfigLoader.locateConfigFileToUse({ + useConfigFile: this.#options.configFile, + cwd: this.#options.cwd, + }); + } + + return this.#configFilePath; + } + + /** + * Calculates the config array for this run based on inputs. + * @param {string} configFilePath The absolute path to the config file to use if not overridden. + * @param {string} basePath The base path to use for relative paths in the config file. + * @returns {Promise} The config array for `eslint`. + */ + async #calculateConfigArray(configFilePath, basePath) { + // check for cached version first + if (this.#configArray) { + return this.#configArray; + } + + // ensure `ConfigLoader.calculateConfigArray` is called only once + this.#configArray = ConfigLoader.calculateConfigArray( + configFilePath, + basePath, + this.#options, + ); + + // Unwrap the promise. This is primarily for the sync `getCachedConfigArrayForPath` method. + this.#configArray = await this.#configArray; + + return this.#configArray; + } + + /** + * Returns the config file path for the given directory. This will either use + * the override config file that was specified in the constructor options or + * search for a config file from the directory of the file being linted. + * @param {string} dirPath The directory path to get the config file path for. + * @returns {Promise} The config file path or `undefined` if not found. + * @throws {Error} If `fileOrDirPath` is not a non-empty string. + * @throws {Error} If `fileOrDirPath` is not an absolute path. + */ + async findConfigFileForPath(dirPath) { + assertValidFilePath(dirPath); + + const { configFilePath } = await this.#locateConfigFileToUse(); + + return configFilePath; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} dirPath The path of the directory to retrieve config for. + * @returns {Promise} A configuration object for the file. + */ + async loadConfigArrayForDirectory(dirPath) { + assertValidFilePath(dirPath); + + debug(`[Legacy]: Calculating config for ${dirPath}`); + + const { configFilePath, basePath } = + await this.#locateConfigFileToUse(); + + debug( + `[Legacy]: Using config file ${configFilePath} and base path ${basePath}`, + ); + return this.#calculateConfigArray(configFilePath, basePath); + } + + /** + * Returns a configuration array for the given directory based on the CLI options. + * This is a synchronous operation and does not read any files from disk. It's + * intended to be used in locations where we know the config file has already + * been loaded and we just need to get the configuration for a file. + * @param {string} dirPath The path of the directory to retrieve a config object for. + * @returns {FlatConfigArray} A configuration object for the file. + * @throws {Error} If `dirPath` is not a non-empty string. + * @throws {Error} If `dirPath` is not an absolute path. + * @throws {Error} If the config file was not already loaded. + */ + getCachedConfigArrayForPath(dirPath) { + assertValidFilePath(dirPath); + + debug(`[Legacy]: Looking up cached config for ${dirPath}`); + + if (!this.#configArray) { + throw new Error(`Could not find config file for ${dirPath}`); + } + + if (typeof this.#configArray.then === "function") { + throw new Error( + `Config array for ${dirPath} has not yet been calculated or an error occurred during the calculation`, + ); + } + + return this.#configArray; + } +} + +module.exports = { ConfigLoader, LegacyConfigLoader }; diff --git a/node_modules/eslint/lib/config/config.js b/node_modules/eslint/lib/config/config.js new file mode 100644 index 00000000..22fd5cc4 --- /dev/null +++ b/node_modules/eslint/lib/config/config.js @@ -0,0 +1,674 @@ +/** + * @fileoverview The `Config` class + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { deepMergeArrays } = require("../shared/deep-merge-arrays"); +const { flatConfigSchema, hasMethod } = require("./flat-config-schema"); +const { ObjectSchema } = require("@eslint/config-array"); +const ajvImport = require("../shared/ajv"); +const ajv = ajvImport(); +const ruleReplacements = require("../../conf/replacements.json"); + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * @import { RuleDefinition } from "@eslint/core"; + * @import { Linter } from "eslint"; + */ + +//----------------------------------------------------------------------------- +// Private Members +//------------------------------------------------------------------------------ + +// JSON schema that disallows passing any options +const noOptionsSchema = Object.freeze({ + type: "array", + minItems: 0, + maxItems: 0, +}); + +const severities = new Map([ + [0, 0], + [1, 1], + [2, 2], + ["off", 0], + ["warn", 1], + ["error", 2], +]); + +/** + * A collection of compiled validators for rules that have already + * been validated. + * @type {WeakMap} + */ +const validators = new WeakMap(); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Throws a helpful error when a rule cannot be found. + * @param {Object} ruleId The rule identifier. + * @param {string} ruleId.pluginName The ID of the rule to find. + * @param {string} ruleId.ruleName The ID of the rule to find. + * @param {Object} config The config to search in. + * @throws {TypeError} For missing plugin or rule. + * @returns {void} + */ +function throwRuleNotFoundError({ pluginName, ruleName }, config) { + const ruleId = pluginName === "@" ? ruleName : `${pluginName}/${ruleName}`; + + const errorMessageHeader = `Key "rules": Key "${ruleId}"`; + + let errorMessage = `${errorMessageHeader}: Could not find plugin "${pluginName}" in configuration.`; + + const missingPluginErrorMessage = errorMessage; + + // if the plugin exists then we need to check if the rule exists + if (config.plugins && config.plugins[pluginName]) { + const replacementRuleName = ruleReplacements.rules[ruleName]; + + if (pluginName === "@" && replacementRuleName) { + errorMessage = `${errorMessageHeader}: Rule "${ruleName}" was removed and replaced by "${replacementRuleName}".`; + } else { + errorMessage = `${errorMessageHeader}: Could not find "${ruleName}" in plugin "${pluginName}".`; + + // otherwise, let's see if we can find the rule name elsewhere + for (const [otherPluginName, otherPlugin] of Object.entries( + config.plugins, + )) { + if (otherPlugin.rules && otherPlugin.rules[ruleName]) { + errorMessage += ` Did you mean "${otherPluginName}/${ruleName}"?`; + break; + } + } + } + + // falls through to throw error + } + + const error = new TypeError(errorMessage); + + if (errorMessage === missingPluginErrorMessage) { + error.messageTemplate = "config-plugin-missing"; + error.messageData = { pluginName, ruleId }; + } + + throw error; +} + +/** + * The error type when a rule has an invalid `meta.schema`. + */ +class InvalidRuleOptionsSchemaError extends Error { + /** + * Creates a new instance. + * @param {string} ruleId Id of the rule that has an invalid `meta.schema`. + * @param {Error} processingError Error caught while processing the `meta.schema`. + */ + constructor(ruleId, processingError) { + super( + `Error while processing options validation schema of rule '${ruleId}': ${processingError.message}`, + { cause: processingError }, + ); + this.code = "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"; + } +} + +/** + * Parses a ruleId into its plugin and rule parts. + * @param {string} ruleId The rule ID to parse. + * @returns {{pluginName:string,ruleName:string}} The plugin and rule + * parts of the ruleId; + */ +function parseRuleId(ruleId) { + let pluginName, ruleName; + + // distinguish between core rules and plugin rules + if (ruleId.includes("/")) { + // mimic scoped npm packages + if (ruleId.startsWith("@")) { + pluginName = ruleId.slice(0, ruleId.lastIndexOf("/")); + } else { + pluginName = ruleId.slice(0, ruleId.indexOf("/")); + } + + ruleName = ruleId.slice(pluginName.length + 1); + } else { + pluginName = "@"; + ruleName = ruleId; + } + + return { + pluginName, + ruleName, + }; +} + +/** + * Retrieves a rule instance from a given config based on the ruleId. + * @param {string} ruleId The rule ID to look for. + * @param {Linter.Config} config The config to search. + * @returns {RuleDefinition|undefined} The rule if found + * or undefined if not. + */ +function getRuleFromConfig(ruleId, config) { + const { pluginName, ruleName } = parseRuleId(ruleId); + + return config.plugins?.[pluginName]?.rules?.[ruleName]; +} + +/** + * Gets a complete options schema for a rule. + * @param {RuleDefinition} rule A rule object + * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`. + * @returns {Object|null} JSON Schema for the rule's options. `null` if `meta.schema` is `false`. + */ +function getRuleOptionsSchema(rule) { + if (!rule.meta) { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + const schema = rule.meta.schema; + + if (typeof schema === "undefined") { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + // `schema:false` is an allowed explicit opt-out of options validation for the rule + if (schema === false) { + return null; + } + + if (typeof schema !== "object" || schema === null) { + throw new TypeError("Rule's `meta.schema` must be an array or object"); + } + + // ESLint-specific array form needs to be converted into a valid JSON Schema definition + if (Array.isArray(schema)) { + if (schema.length) { + return { + type: "array", + items: schema, + minItems: 0, + maxItems: schema.length, + }; + } + + // `schema:[]` is an explicit way to specify that the rule does not accept any options + return { ...noOptionsSchema }; + } + + // `schema:` is assumed to be a valid JSON Schema definition + return schema; +} + +/** + * Splits a plugin identifier in the form a/b/c into two parts: a/b and c. + * @param {string} identifier The identifier to parse. + * @returns {{objectName: string, pluginName: string}} The parts of the plugin + * name. + */ +function splitPluginIdentifier(identifier) { + const parts = identifier.split("/"); + + return { + objectName: parts.pop(), + pluginName: parts.join("/"), + }; +} + +/** + * Returns the name of an object in the config by reading its `meta` key. + * @param {Object} object The object to check. + * @returns {string?} The name of the object if found or `null` if there + * is no name. + */ +function getObjectId(object) { + // first check old-style name + let name = object.name; + + if (!name) { + if (!object.meta) { + return null; + } + + name = object.meta.name; + + if (!name) { + return null; + } + } + + // now check for old-style version + let version = object.version; + + if (!version) { + version = object.meta && object.meta.version; + } + + // if there's a version then append that + if (version) { + return `${name}@${version}`; + } + + return name; +} + +/** + * Asserts that a value is not a function. + * @param {any} value The value to check. + * @param {string} key The key of the value in the object. + * @param {string} objectKey The key of the object being checked. + * @returns {void} + * @throws {TypeError} If the value is a function. + */ +function assertNotFunction(value, key, objectKey) { + if (typeof value === "function") { + const error = new TypeError( + `Cannot serialize key "${key}" in "${objectKey}": Function values are not supported.`, + ); + + error.messageTemplate = "config-serialize-function"; + error.messageData = { key, objectKey }; + + throw error; + } +} + +/** + * Converts a languageOptions object to a JSON representation. + * @param {Record} languageOptions The options to create a JSON + * representation of. + * @param {string} objectKey The key of the object being converted. + * @returns {Record} The JSON representation of the languageOptions. + * @throws {TypeError} If a function is found in the languageOptions. + */ +function languageOptionsToJSON(languageOptions, objectKey = "languageOptions") { + if (typeof languageOptions.toJSON === "function") { + const result = languageOptions.toJSON(); + + assertNotFunction(result, "toJSON", objectKey); + + return result; + } + + const result = {}; + + for (const [key, value] of Object.entries(languageOptions)) { + if (value) { + if (typeof value === "object") { + const name = getObjectId(value); + + if (typeof value.toJSON === "function") { + result[key] = value.toJSON(); + assertNotFunction(result[key], key, objectKey); + } else if (name && hasMethod(value)) { + result[key] = name; + } else { + result[key] = languageOptionsToJSON(value, key); + } + continue; + } + + assertNotFunction(value, key, objectKey); + } + + result[key] = value; + } + + return result; +} + +/** + * Gets or creates a validator for a rule. + * @param {Object} rule The rule to get a validator for. + * @param {string} ruleId The ID of the rule (for error reporting). + * @returns {Function|null} A validation function or null if no validation is needed. + * @throws {InvalidRuleOptionsSchemaError} If a rule's `meta.schema` is invalid. + */ +function getOrCreateValidator(rule, ruleId) { + if (!validators.has(rule)) { + try { + const schema = getRuleOptionsSchema(rule); + + if (schema) { + validators.set(rule, ajv.compile(schema)); + } + } catch (err) { + throw new InvalidRuleOptionsSchemaError(ruleId, err); + } + } + + return validators.get(rule); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Represents a normalized configuration object. + */ +class Config { + /** + * The name to use for the language when serializing to JSON. + * @type {string|undefined} + */ + #languageName; + + /** + * The name to use for the processor when serializing to JSON. + * @type {string|undefined} + */ + #processorName; + + /** + * Creates a new instance. + * @param {Object} config The configuration object. + */ + constructor(config) { + const { plugins, language, languageOptions, processor, ...otherKeys } = + config; + + // Validate config object + const schema = new ObjectSchema(flatConfigSchema); + + schema.validate(config); + + // first, copy all the other keys over + Object.assign(this, otherKeys); + + // ensure that a language is specified + if (!language) { + throw new TypeError("Key 'language' is required."); + } + + // copy the rest over + this.plugins = plugins; + this.language = language; + + // Check language value + const { + pluginName: languagePluginName, + objectName: localLanguageName, + } = splitPluginIdentifier(language); + + this.#languageName = language; + + if ( + !plugins || + !plugins[languagePluginName] || + !plugins[languagePluginName].languages || + !plugins[languagePluginName].languages[localLanguageName] + ) { + throw new TypeError( + `Key "language": Could not find "${localLanguageName}" in plugin "${languagePluginName}".`, + ); + } + + this.language = + plugins[languagePluginName].languages[localLanguageName]; + + if (this.language.defaultLanguageOptions ?? languageOptions) { + this.languageOptions = flatConfigSchema.languageOptions.merge( + this.language.defaultLanguageOptions, + languageOptions, + ); + } else { + this.languageOptions = {}; + } + + // Validate language options + try { + this.language.validateLanguageOptions(this.languageOptions); + } catch (error) { + throw new TypeError(`Key "languageOptions": ${error.message}`, { + cause: error, + }); + } + + // Normalize language options if necessary + if (this.language.normalizeLanguageOptions) { + this.languageOptions = this.language.normalizeLanguageOptions( + this.languageOptions, + ); + } + + // Check processor value + if (processor) { + this.processor = processor; + + if (typeof processor === "string") { + const { pluginName, objectName: localProcessorName } = + splitPluginIdentifier(processor); + + this.#processorName = processor; + + if ( + !plugins || + !plugins[pluginName] || + !plugins[pluginName].processors || + !plugins[pluginName].processors[localProcessorName] + ) { + throw new TypeError( + `Key "processor": Could not find "${localProcessorName}" in plugin "${pluginName}".`, + ); + } + + this.processor = + plugins[pluginName].processors[localProcessorName]; + } else if (typeof processor === "object") { + this.#processorName = getObjectId(processor); + this.processor = processor; + } else { + throw new TypeError( + "Key 'processor' must be a string or an object.", + ); + } + } + + // Process the rules + if (this.rules) { + this.#normalizeRulesConfig(); + this.validateRulesConfig(this.rules); + } + } + + /** + * Converts the configuration to a JSON representation. + * @returns {Record} The JSON representation of the configuration. + * @throws {Error} If the configuration cannot be serialized. + */ + toJSON() { + if (this.processor && !this.#processorName) { + throw new Error( + "Could not serialize processor object (missing 'meta' object).", + ); + } + + if (!this.#languageName) { + throw new Error( + "Could not serialize language object (missing 'meta' object).", + ); + } + + return { + ...this, + plugins: Object.entries(this.plugins).map(([namespace, plugin]) => { + const pluginId = getObjectId(plugin); + + if (!pluginId) { + return namespace; + } + + return `${namespace}:${pluginId}`; + }), + language: this.#languageName, + languageOptions: languageOptionsToJSON(this.languageOptions), + processor: this.#processorName, + }; + } + + /** + * Gets a rule configuration by its ID. + * @param {string} ruleId The ID of the rule to get. + * @returns {RuleDefinition|undefined} The rule definition from the plugin, or `undefined` if the rule is not found. + */ + getRuleDefinition(ruleId) { + return getRuleFromConfig(ruleId, this); + } + + /** + * Normalizes the rules configuration. Ensures that each rule config is + * an array and that the severity is a number. Applies meta.defaultOptions. + * This function modifies `this.rules`. + * @returns {void} + */ + #normalizeRulesConfig() { + for (const [ruleId, originalConfig] of Object.entries(this.rules)) { + // ensure rule config is an array + let ruleConfig = Array.isArray(originalConfig) + ? originalConfig + : [originalConfig]; + + // normalize severity + ruleConfig[0] = severities.get(ruleConfig[0]); + + const rule = getRuleFromConfig(ruleId, this); + + // apply meta.defaultOptions + const slicedOptions = ruleConfig.slice(1); + const mergedOptions = deepMergeArrays( + rule?.meta?.defaultOptions, + slicedOptions, + ); + + if (mergedOptions.length) { + ruleConfig = [ruleConfig[0], ...mergedOptions]; + } + + this.rules[ruleId] = ruleConfig; + } + } + + /** + * Validates all of the rule configurations in the given rules config + * against the plugins in this instance. This is used primarily to + * validate inline configuration rules while inting. + * @param {Object} rulesConfig The rules config to validate. + * @returns {void} + * @throws {Error} If a rule's configuration does not match its schema. + * @throws {TypeError} If the rulesConfig is not provided or is invalid. + * @throws {InvalidRuleOptionsSchemaError} If a rule's `meta.schema` is invalid. + * @throws {TypeError} If a rule is not found in the plugins. + */ + validateRulesConfig(rulesConfig) { + if (!rulesConfig) { + throw new TypeError("Config is required for validation."); + } + + for (const [ruleId, ruleOptions] of Object.entries(rulesConfig)) { + // check for edge case + if (ruleId === "__proto__") { + continue; + } + + /* + * If a rule is disabled, we don't do any validation. This allows + * users to safely set any value to 0 or "off" without worrying + * that it will cause a validation error. + * + * Note: ruleOptions is always an array at this point because + * this validation occurs after FlatConfigArray has merged and + * normalized values. + */ + if (ruleOptions[0] === 0) { + continue; + } + + const rule = getRuleFromConfig(ruleId, this); + + if (!rule) { + throwRuleNotFoundError(parseRuleId(ruleId), this); + } + + const validateRule = getOrCreateValidator(rule, ruleId); + + if (validateRule) { + validateRule(ruleOptions.slice(1)); + + if (validateRule.errors) { + throw new Error( + `Key "rules": Key "${ruleId}":\n${validateRule.errors + .map(error => { + if ( + error.keyword === "additionalProperties" && + error.schema === false && + typeof error.parentSchema?.properties === + "object" && + typeof error.params?.additionalProperty === + "string" + ) { + const expectedProperties = Object.keys( + error.parentSchema.properties, + ).map(property => `"${property}"`); + + return `\tValue ${JSON.stringify(error.data)} ${error.message}.\n\t\tUnexpected property "${error.params.additionalProperty}". Expected properties: ${expectedProperties.join(", ")}.\n`; + } + + return `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`; + }) + .join("")}`, + ); + } + } + } + } + + /** + * Gets a complete options schema for a rule. + * @param {RuleDefinition} ruleDefinition A rule definition object. + * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`. + * @returns {Object|null} JSON Schema for the rule's options. `null` if `meta.schema` is `false`. + */ + static getRuleOptionsSchema(ruleDefinition) { + return getRuleOptionsSchema(ruleDefinition); + } + + /** + * Normalizes the severity value of a rule's configuration to a number + * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally + * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0), + * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array + * whose first element is one of the above values. Strings are matched case-insensitively. + * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0. + */ + static getRuleNumericSeverity(ruleConfig) { + const severityValue = Array.isArray(ruleConfig) + ? ruleConfig[0] + : ruleConfig; + + if (severities.has(severityValue)) { + return severities.get(severityValue); + } + + if (typeof severityValue === "string") { + return severities.get(severityValue.toLowerCase()) ?? 0; + } + + return 0; + } +} + +module.exports = { Config }; diff --git a/node_modules/eslint/lib/config/default-config.js b/node_modules/eslint/lib/config/default-config.js new file mode 100644 index 00000000..aebf6e93 --- /dev/null +++ b/node_modules/eslint/lib/config/default-config.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Default configuration + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const Rules = require("../rules"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const sharedDefaultConfig = [ + // intentionally empty config to ensure these files are globbed by default + { + files: ["**/*.js", "**/*.mjs"], + }, + { + files: ["**/*.cjs"], + languageOptions: { + sourceType: "commonjs", + ecmaVersion: "latest", + }, + }, +]; + +exports.defaultConfig = Object.freeze([ + { + plugins: { + "@": { + languages: { + js: require("../languages/js"), + }, + + /* + * Because we try to delay loading rules until absolutely + * necessary, a proxy allows us to hook into the lazy-loading + * aspect of the rules map while still keeping all of the + * relevant configuration inside of the config array. + */ + rules: new Proxy( + {}, + { + get(target, property) { + return Rules.get(property); + }, + + has(target, property) { + return Rules.has(property); + }, + }, + ), + }, + }, + language: "@/js", + linterOptions: { + reportUnusedDisableDirectives: 1, + }, + }, + + // default ignores are listed here + { + ignores: ["**/node_modules/", ".git/"], + }, + + ...sharedDefaultConfig, +]); + +exports.defaultRuleTesterConfig = Object.freeze([ + { files: ["**"] }, // Make sure the default config matches for all files + + ...sharedDefaultConfig, +]); diff --git a/node_modules/eslint/lib/config/flat-config-array.js b/node_modules/eslint/lib/config/flat-config-array.js new file mode 100644 index 00000000..3cc355ad --- /dev/null +++ b/node_modules/eslint/lib/config/flat-config-array.js @@ -0,0 +1,217 @@ +/** + * @fileoverview Flat Config Array + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { ConfigArray, ConfigArraySymbol } = require("@eslint/config-array"); +const { flatConfigSchema } = require("./flat-config-schema"); +const { defaultConfig } = require("./default-config"); +const { Config } = require("./config"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Fields that are considered metadata and not part of the config object. + */ +const META_FIELDS = new Set(["name"]); + +/** + * Wraps a config error with details about where the error occurred. + * @param {Error} error The original error. + * @param {number} originalLength The original length of the config array. + * @param {number} baseLength The length of the base config. + * @returns {TypeError} The new error with details. + */ +function wrapConfigErrorWithDetails(error, originalLength, baseLength) { + let location = "user-defined"; + let configIndex = error.index; + + /* + * A config array is set up in this order: + * 1. Base config + * 2. Original configs + * 3. User-defined configs + * 4. CLI-defined configs + * + * So we need to adjust the index to account for the base config. + * + * - If the index is less than the base length, it's in the base config + * (as specified by `baseConfig` argument to `FlatConfigArray` constructor). + * - If the index is greater than the base length but less than the original + * length + base length, it's in the original config. The original config + * is passed to the `FlatConfigArray` constructor as the first argument. + * - Otherwise, it's in the user-defined config, which is loaded from the + * config file and merged with any command-line options. + */ + if (error.index < baseLength) { + location = "base"; + } else if (error.index < originalLength + baseLength) { + location = "original"; + configIndex = error.index - baseLength; + } else { + configIndex = error.index - originalLength - baseLength; + } + + return new TypeError( + `${error.message.slice(0, -1)} at ${location} index ${configIndex}.`, + { cause: error }, + ); +} + +const originalBaseConfig = Symbol("originalBaseConfig"); +const originalLength = Symbol("originalLength"); +const baseLength = Symbol("baseLength"); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Represents an array containing configuration information for ESLint. + */ +class FlatConfigArray extends ConfigArray { + /** + * Creates a new instance. + * @param {*[]} configs An array of configuration information. + * @param {{basePath: string, shouldIgnore: boolean, baseConfig: FlatConfig}} options The options + * to use for the config array instance. + */ + constructor( + configs, + { basePath, shouldIgnore = true, baseConfig = defaultConfig } = {}, + ) { + super(configs, { + basePath, + schema: flatConfigSchema, + }); + + /** + * The original length of the array before any modifications. + * @type {number} + */ + this[originalLength] = this.length; + + if (baseConfig[Symbol.iterator]) { + this.unshift(...baseConfig); + } else { + this.unshift(baseConfig); + } + + /** + * The length of the array after applying the base config. + * @type {number} + */ + this[baseLength] = this.length - this[originalLength]; + + /** + * The base config used to build the config array. + * @type {Array} + */ + this[originalBaseConfig] = baseConfig; + Object.defineProperty(this, originalBaseConfig, { writable: false }); + + /** + * Determines if `ignores` fields should be honored. + * If true, then all `ignores` fields are honored. + * if false, then only `ignores` fields in the baseConfig are honored. + * @type {boolean} + */ + this.shouldIgnore = shouldIgnore; + Object.defineProperty(this, "shouldIgnore", { writable: false }); + } + + /** + * Normalizes the array by calling the superclass method and catching/rethrowing + * any ConfigError exceptions with additional details. + * @param {any} [context] The context to use to normalize the array. + * @returns {Promise} A promise that resolves when the array is normalized. + */ + normalize(context) { + return super.normalize(context).catch(error => { + if (error.name === "ConfigError") { + throw wrapConfigErrorWithDetails( + error, + this[originalLength], + this[baseLength], + ); + } + + throw error; + }); + } + + /** + * Normalizes the array by calling the superclass method and catching/rethrowing + * any ConfigError exceptions with additional details. + * @param {any} [context] The context to use to normalize the array. + * @returns {FlatConfigArray} The current instance. + * @throws {TypeError} If the config is invalid. + */ + normalizeSync(context) { + try { + return super.normalizeSync(context); + } catch (error) { + if (error.name === "ConfigError") { + throw wrapConfigErrorWithDetails( + error, + this[originalLength], + this[baseLength], + ); + } + + throw error; + } + } + + /* eslint-disable class-methods-use-this -- Desired as instance method */ + /** + * Replaces a config with another config to allow us to put strings + * in the config array that will be replaced by objects before + * normalization. + * @param {Object} config The config to preprocess. + * @returns {Object} The preprocessed config. + */ + [ConfigArraySymbol.preprocessConfig](config) { + /* + * If a config object has `ignores` and no other non-meta fields, then it's an object + * for global ignores. If `shouldIgnore` is false, that object shouldn't apply, + * so we'll remove its `ignores`. + */ + if ( + !this.shouldIgnore && + !this[originalBaseConfig].includes(config) && + config.ignores && + Object.keys(config).filter(key => !META_FIELDS.has(key)).length === + 1 + ) { + /* eslint-disable-next-line no-unused-vars -- need to strip off other keys */ + const { ignores, ...otherKeys } = config; + + return otherKeys; + } + + return config; + } + + /** + * Finalizes the config by replacing plugin references with their objects + * and validating rule option schemas. + * @param {Object} config The config to finalize. + * @returns {Object} The finalized config. + * @throws {TypeError} If the config is invalid. + */ + [ConfigArraySymbol.finalizeConfig](config) { + return new Config(config); + } + /* eslint-enable class-methods-use-this -- Desired as instance method */ +} + +exports.FlatConfigArray = FlatConfigArray; diff --git a/node_modules/eslint/lib/config/flat-config-schema.js b/node_modules/eslint/lib/config/flat-config-schema.js new file mode 100644 index 00000000..ff977a76 --- /dev/null +++ b/node_modules/eslint/lib/config/flat-config-schema.js @@ -0,0 +1,598 @@ +/** + * @fileoverview Flat config schema + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { normalizeSeverityToNumber } = require("../shared/severity"); + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** + * @typedef ObjectPropertySchema + * @property {Function|string} merge The function or name of the function to call + * to merge multiple objects with this property. + * @property {Function|string} validate The function or name of the function to call + * to validate the value of this property. + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const ruleSeverities = new Map([ + [0, 0], + ["off", 0], + [1, 1], + ["warn", 1], + [2, 2], + ["error", 2], +]); + +/** + * Check if a value is a non-null object. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is a non-null object. + */ +function isNonNullObject(value) { + return typeof value === "object" && value !== null; +} + +/** + * Check if a value is a non-null non-array object. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is a non-null non-array object. + */ +function isNonArrayObject(value) { + return isNonNullObject(value) && !Array.isArray(value); +} + +/** + * Check if a value is undefined. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is undefined. + */ +function isUndefined(value) { + return typeof value === "undefined"; +} + +/** + * Deeply merges two non-array objects. + * @param {Object} first The base object. + * @param {Object} second The overrides object. + * @param {Map>} [mergeMap] Maps the combination of first and second arguments to a merged result. + * @returns {Object} An object with properties from both first and second. + */ +function deepMerge(first, second, mergeMap = new Map()) { + let secondMergeMap = mergeMap.get(first); + + if (secondMergeMap) { + const result = secondMergeMap.get(second); + + if (result) { + // If this combination of first and second arguments has been already visited, return the previously created result. + return result; + } + } else { + secondMergeMap = new Map(); + mergeMap.set(first, secondMergeMap); + } + + /* + * First create a result object where properties from the second object + * overwrite properties from the first. This sets up a baseline to use + * later rather than needing to inspect and change every property + * individually. + */ + const result = { + ...first, + ...second, + }; + + delete result.__proto__; // eslint-disable-line no-proto -- don't merge own property "__proto__" + + // Store the pending result for this combination of first and second arguments. + secondMergeMap.set(second, result); + + for (const key of Object.keys(second)) { + // avoid hairy edge case + if ( + key === "__proto__" || + !Object.prototype.propertyIsEnumerable.call(first, key) + ) { + continue; + } + + const firstValue = first[key]; + const secondValue = second[key]; + + if (isNonArrayObject(firstValue) && isNonArrayObject(secondValue)) { + result[key] = deepMerge(firstValue, secondValue, mergeMap); + } else if (isUndefined(secondValue)) { + result[key] = firstValue; + } + } + + return result; +} + +/** + * Normalizes the rule options config for a given rule by ensuring that + * it is an array and that the first item is 0, 1, or 2. + * @param {Array|string|number} ruleOptions The rule options config. + * @returns {Array} An array of rule options. + */ +function normalizeRuleOptions(ruleOptions) { + const finalOptions = Array.isArray(ruleOptions) + ? ruleOptions.slice(0) + : [ruleOptions]; + + finalOptions[0] = ruleSeverities.get(finalOptions[0]); + return structuredClone(finalOptions); +} + +/** + * Determines if an object has any methods. + * @param {Object} object The object to check. + * @returns {boolean} `true` if the object has any methods. + */ +function hasMethod(object) { + for (const key of Object.keys(object)) { + if (typeof object[key] === "function") { + return true; + } + } + + return false; +} + +//----------------------------------------------------------------------------- +// Assertions +//----------------------------------------------------------------------------- + +/** + * The error type when a rule's options are configured with an invalid type. + */ +class InvalidRuleOptionsError extends Error { + /** + * @param {string} ruleId Rule name being configured. + * @param {any} value The invalid value. + */ + constructor(ruleId, value) { + super( + `Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`, + ); + this.messageTemplate = "invalid-rule-options"; + this.messageData = { ruleId, value }; + } +} + +/** + * Validates that a value is a valid rule options entry. + * @param {string} ruleId Rule name being configured. + * @param {any} value The value to check. + * @returns {void} + * @throws {InvalidRuleOptionsError} If the value isn't a valid rule options. + */ +function assertIsRuleOptions(ruleId, value) { + if ( + typeof value !== "string" && + typeof value !== "number" && + !Array.isArray(value) + ) { + throw new InvalidRuleOptionsError(ruleId, value); + } +} + +/** + * The error type when a rule's severity is invalid. + */ +class InvalidRuleSeverityError extends Error { + /** + * @param {string} ruleId Rule name being configured. + * @param {any} value The invalid value. + */ + constructor(ruleId, value) { + super( + `Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`, + ); + this.messageTemplate = "invalid-rule-severity"; + this.messageData = { ruleId, value }; + } +} + +/** + * Validates that a value is valid rule severity. + * @param {string} ruleId Rule name being configured. + * @param {any} value The value to check. + * @returns {void} + * @throws {InvalidRuleSeverityError} If the value isn't a valid rule severity. + */ +function assertIsRuleSeverity(ruleId, value) { + const severity = ruleSeverities.get(value); + + if (typeof severity === "undefined") { + throw new InvalidRuleSeverityError(ruleId, value); + } +} + +/** + * Validates that a given string is the form pluginName/objectName. + * @param {string} value The string to check. + * @returns {void} + * @throws {TypeError} If the string isn't in the correct format. + */ +function assertIsPluginMemberName(value) { + if (!/[@a-z0-9-_$]+(?:\/(?:[a-z0-9-_$]+))+$/iu.test(value)) { + throw new TypeError( + `Expected string in the form "pluginName/objectName" but found "${value}".`, + ); + } +} + +/** + * Validates that a value is an object. + * @param {any} value The value to check. + * @returns {void} + * @throws {TypeError} If the value isn't an object. + */ +function assertIsObject(value) { + if (!isNonNullObject(value)) { + throw new TypeError("Expected an object."); + } +} + +/** + * The error type when there's an eslintrc-style options in a flat config. + */ +class IncompatibleKeyError extends Error { + /** + * @param {string} key The invalid key. + */ + constructor(key) { + super( + "This appears to be in eslintrc format rather than flat config format.", + ); + this.messageTemplate = "eslintrc-incompat"; + this.messageData = { key }; + } +} + +/** + * The error type when there's an eslintrc-style plugins array found. + */ +class IncompatiblePluginsError extends Error { + /** + * Creates a new instance. + * @param {Array} plugins The plugins array. + */ + constructor(plugins) { + super( + "This appears to be in eslintrc format (array of strings) rather than flat config format (object).", + ); + this.messageTemplate = "eslintrc-plugins"; + this.messageData = { plugins }; + } +} + +//----------------------------------------------------------------------------- +// Low-Level Schemas +//----------------------------------------------------------------------------- + +/** @type {ObjectPropertySchema} */ +const booleanSchema = { + merge: "replace", + validate: "boolean", +}; + +const ALLOWED_SEVERITIES = new Set(["error", "warn", "off", 2, 1, 0]); + +/** @type {ObjectPropertySchema} */ +const disableDirectiveSeveritySchema = { + merge(first, second) { + const value = second === void 0 ? first : second; + + if (typeof value === "boolean") { + return value ? "warn" : "off"; + } + + return normalizeSeverityToNumber(value); + }, + validate(value) { + if (!(ALLOWED_SEVERITIES.has(value) || typeof value === "boolean")) { + throw new TypeError( + 'Expected one of: "error", "warn", "off", 0, 1, 2, or a boolean.', + ); + } + }, +}; + +/** @type {ObjectPropertySchema} */ +const unusedInlineConfigsSeveritySchema = { + merge(first, second) { + const value = second === void 0 ? first : second; + + return normalizeSeverityToNumber(value); + }, + validate(value) { + if (!ALLOWED_SEVERITIES.has(value)) { + throw new TypeError( + 'Expected one of: "error", "warn", "off", 0, 1, or 2.', + ); + } + }, +}; + +/** @type {ObjectPropertySchema} */ +const deepObjectAssignSchema = { + merge(first = {}, second = {}) { + return deepMerge(first, second); + }, + validate: "object", +}; + +//----------------------------------------------------------------------------- +// High-Level Schemas +//----------------------------------------------------------------------------- + +/** @type {ObjectPropertySchema} */ +const languageOptionsSchema = { + merge(first = {}, second = {}) { + const result = deepMerge(first, second); + + for (const [key, value] of Object.entries(result)) { + /* + * Special case: Because the `parser` property is an object, it should + * not be deep merged. Instead, it should be replaced if it exists in + * the second object. To make this more generic, we just check for + * objects with methods and replace them if they exist in the second + * object. + */ + if (isNonArrayObject(value)) { + if (hasMethod(value)) { + result[key] = second[key] ?? first[key]; + continue; + } + + // for other objects, make sure we aren't reusing the same object + result[key] = { ...result[key] }; + continue; + } + } + + return result; + }, + validate: "object", +}; + +/** @type {ObjectPropertySchema} */ +const languageSchema = { + merge: "replace", + validate: assertIsPluginMemberName, +}; + +/** @type {ObjectPropertySchema} */ +const pluginsSchema = { + merge(first = {}, second = {}) { + const keys = new Set([...Object.keys(first), ...Object.keys(second)]); + const result = {}; + + // manually validate that plugins are not redefined + for (const key of keys) { + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + if (key in first && key in second && first[key] !== second[key]) { + throw new TypeError(`Cannot redefine plugin "${key}".`); + } + + result[key] = second[key] || first[key]; + } + + return result; + }, + validate(value) { + // first check the value to be sure it's an object + if (value === null || typeof value !== "object") { + throw new TypeError("Expected an object."); + } + + // make sure it's not an array, which would mean eslintrc-style is used + if (Array.isArray(value)) { + throw new IncompatiblePluginsError(value); + } + + // second check the keys to make sure they are objects + for (const key of Object.keys(value)) { + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + if (value[key] === null || typeof value[key] !== "object") { + throw new TypeError(`Key "${key}": Expected an object.`); + } + } + }, +}; + +/** @type {ObjectPropertySchema} */ +const processorSchema = { + merge: "replace", + validate(value) { + if (typeof value === "string") { + assertIsPluginMemberName(value); + } else if (value && typeof value === "object") { + if ( + typeof value.preprocess !== "function" || + typeof value.postprocess !== "function" + ) { + throw new TypeError( + "Object must have a preprocess() and a postprocess() method.", + ); + } + } else { + throw new TypeError("Expected an object or a string."); + } + }, +}; + +/** @type {ObjectPropertySchema} */ +const rulesSchema = { + merge(first = {}, second = {}) { + const result = { + ...first, + ...second, + }; + + for (const ruleId of Object.keys(result)) { + try { + // avoid hairy edge case + if (ruleId === "__proto__") { + /* eslint-disable-next-line no-proto -- Though deprecated, may still be present */ + delete result.__proto__; + continue; + } + + result[ruleId] = normalizeRuleOptions(result[ruleId]); + + /* + * If either rule config is missing, then the correct + * config is already present and we just need to normalize + * the severity. + */ + if (!(ruleId in first) || !(ruleId in second)) { + continue; + } + + const firstRuleOptions = normalizeRuleOptions(first[ruleId]); + const secondRuleOptions = normalizeRuleOptions(second[ruleId]); + + /* + * If the second rule config only has a severity (length of 1), + * then use that severity and keep the rest of the options from + * the first rule config. + */ + if (secondRuleOptions.length === 1) { + result[ruleId] = [ + secondRuleOptions[0], + ...firstRuleOptions.slice(1), + ]; + continue; + } + + /* + * In any other situation, then the second rule config takes + * precedence. That means the value at `result[ruleId]` is + * already correct and no further work is necessary. + */ + } catch (ex) { + throw new Error(`Key "${ruleId}": ${ex.message}`, { + cause: ex, + }); + } + } + + return result; + }, + + validate(value) { + assertIsObject(value); + + /* + * We are not checking the rule schema here because there is no + * guarantee that the rule definition is present at this point. Instead + * we wait and check the rule schema during the finalization step + * of calculating a config. + */ + for (const ruleId of Object.keys(value)) { + // avoid hairy edge case + if (ruleId === "__proto__") { + continue; + } + + const ruleOptions = value[ruleId]; + + assertIsRuleOptions(ruleId, ruleOptions); + + if (Array.isArray(ruleOptions)) { + assertIsRuleSeverity(ruleId, ruleOptions[0]); + } else { + assertIsRuleSeverity(ruleId, ruleOptions); + } + } + }, +}; + +/** + * Creates a schema that always throws an error. Useful for warning + * about eslintrc-style keys. + * @param {string} key The eslintrc key to create a schema for. + * @returns {ObjectPropertySchema} The schema. + */ +function createEslintrcErrorSchema(key) { + return { + merge: "replace", + validate() { + throw new IncompatibleKeyError(key); + }, + }; +} + +const eslintrcKeys = [ + "env", + "extends", + "globals", + "ignorePatterns", + "noInlineConfig", + "overrides", + "parser", + "parserOptions", + "reportUnusedDisableDirectives", + "root", +]; + +//----------------------------------------------------------------------------- +// Full schema +//----------------------------------------------------------------------------- + +const flatConfigSchema = { + // eslintrc-style keys that should always error + ...Object.fromEntries( + eslintrcKeys.map(key => [key, createEslintrcErrorSchema(key)]), + ), + + // flat config keys + settings: deepObjectAssignSchema, + linterOptions: { + schema: { + noInlineConfig: booleanSchema, + reportUnusedDisableDirectives: disableDirectiveSeveritySchema, + reportUnusedInlineConfigs: unusedInlineConfigsSeveritySchema, + }, + }, + language: languageSchema, + languageOptions: languageOptionsSchema, + processor: processorSchema, + plugins: pluginsSchema, + rules: rulesSchema, +}; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + flatConfigSchema, + hasMethod, + assertIsRuleSeverity, +}; diff --git a/node_modules/eslint/lib/eslint/eslint-helpers.js b/node_modules/eslint/lib/eslint/eslint-helpers.js new file mode 100644 index 00000000..b3bfa49c --- /dev/null +++ b/node_modules/eslint/lib/eslint/eslint-helpers.js @@ -0,0 +1,1042 @@ +/** + * @fileoverview Helper functions for ESLint class + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const path = require("node:path"); +const fs = require("node:fs"); +const fsp = fs.promises; +const isGlob = require("is-glob"); +const hash = require("../cli-engine/hash"); +const minimatch = require("minimatch"); +const globParent = require("glob-parent"); + +//----------------------------------------------------------------------------- +// Fixup references +//----------------------------------------------------------------------------- + +const Minimatch = minimatch.Minimatch; +const MINIMATCH_OPTIONS = { dot: true }; + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** + * @import { ESLintOptions } from "./eslint.js"; + * @import { ConfigLoader, LegacyConfigLoader } from "../config/config-loader.js"; + */ + +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").ESLint.LintResult} LintResult */ + +/** + * @typedef {Object} GlobSearch + * @property {Array} patterns The normalized patterns to use for a search. + * @property {Array} rawPatterns The patterns as entered by the user + * before doing any normalization. + */ + +//----------------------------------------------------------------------------- +// Errors +//----------------------------------------------------------------------------- + +/** + * The error type when no files match a glob. + */ +class NoFilesFoundError extends Error { + /** + * @param {string} pattern The glob pattern which was not found. + * @param {boolean} globEnabled If `false` then the pattern was a glob pattern, but glob was disabled. + */ + constructor(pattern, globEnabled) { + super( + `No files matching '${pattern}' were found${!globEnabled ? " (glob was disabled)" : ""}.`, + ); + this.messageTemplate = "file-not-found"; + this.messageData = { pattern, globDisabled: !globEnabled }; + } +} + +/** + * The error type when a search fails to match multiple patterns. + */ +class UnmatchedSearchPatternsError extends Error { + /** + * @param {Object} options The options for the error. + * @param {string} options.basePath The directory that was searched. + * @param {Array} options.unmatchedPatterns The glob patterns + * which were not found. + * @param {Array} options.patterns The glob patterns that were + * searched. + * @param {Array} options.rawPatterns The raw glob patterns that + * were searched. + */ + constructor({ basePath, unmatchedPatterns, patterns, rawPatterns }) { + super( + `No files matching '${rawPatterns}' in '${basePath}' were found.`, + ); + this.basePath = basePath; + this.unmatchedPatterns = unmatchedPatterns; + this.patterns = patterns; + this.rawPatterns = rawPatterns; + } +} + +/** + * The error type when there are files matched by a glob, but all of them have been ignored. + */ +class AllFilesIgnoredError extends Error { + /** + * @param {string} pattern The glob pattern which was not found. + */ + constructor(pattern) { + super(`All files matched by '${pattern}' are ignored.`); + this.messageTemplate = "all-matched-files-ignored"; + this.messageData = { pattern }; + } +} + +//----------------------------------------------------------------------------- +// General Helpers +//----------------------------------------------------------------------------- + +/** + * Check if a given value is a non-empty string or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is a non-empty string. + */ +function isNonEmptyString(value) { + return typeof value === "string" && value.trim() !== ""; +} + +/** + * Check if a given value is an array of non-empty strings or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an array of non-empty strings. + */ +function isArrayOfNonEmptyString(value) { + return ( + Array.isArray(value) && !!value.length && value.every(isNonEmptyString) + ); +} + +/** + * Check if a given value is an empty array or an array of non-empty strings. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an empty array or an array of non-empty + * strings. + */ +function isEmptyArrayOrArrayOfNonEmptyString(value) { + return Array.isArray(value) && value.every(isNonEmptyString); +} + +//----------------------------------------------------------------------------- +// File-related Helpers +//----------------------------------------------------------------------------- + +/** + * Normalizes slashes in a file pattern to posix-style. + * @param {string} pattern The pattern to replace slashes in. + * @returns {string} The pattern with slashes normalized. + */ +function normalizeToPosix(pattern) { + return pattern.replace(/\\/gu, "/"); +} + +/** + * Check if a string is a glob pattern or not. + * @param {string} pattern A glob pattern. + * @returns {boolean} `true` if the string is a glob pattern. + */ +function isGlobPattern(pattern) { + return isGlob(path.sep === "\\" ? normalizeToPosix(pattern) : pattern); +} + +/** + * Determines if a given glob pattern will return any results. + * Used primarily to help with useful error messages. + * @param {Object} options The options for the function. + * @param {string} options.basePath The directory to search. + * @param {string} options.pattern An absolute path glob pattern to match. + * @returns {Promise} True if there is a glob match, false if not. + */ +async function globMatch({ basePath, pattern }) { + let found = false; + const { hfs } = await import("@humanfs/node"); + const patternToUse = normalizeToPosix(path.relative(basePath, pattern)); + + const matcher = new Minimatch(patternToUse, MINIMATCH_OPTIONS); + + const walkSettings = { + directoryFilter(entry) { + return !found && matcher.match(entry.path, true); + }, + + entryFilter(entry) { + if (found || entry.isDirectory) { + return false; + } + + if (matcher.match(entry.path)) { + found = true; + return true; + } + + return false; + }, + }; + + if (await hfs.isDirectory(basePath)) { + return hfs + .walk(basePath, walkSettings) + .next() + .then(() => found); + } + + return found; +} + +/** + * Searches a directory looking for matching glob patterns. This uses + * the config array's logic to determine if a directory or file should + * be ignored, so it is consistent with how ignoring works throughout + * ESLint. + * @param {Object} options The options for this function. + * @param {string} options.basePath The directory to search. + * @param {Array} options.patterns An array of absolute path glob patterns + * to match. + * @param {Array} options.rawPatterns An array of glob patterns + * as the user inputted them. Used for errors. + * @param {ConfigLoader|LegacyConfigLoader} options.configLoader The config array to use for + * determining what to ignore. + * @param {boolean} options.errorOnUnmatchedPattern Determines if an error + * should be thrown when a pattern is unmatched. + * @returns {Promise>} An array of matching file paths + * or an empty array if there are no matches. + * @throws {UnmatchedSearchPatternsError} If there is a pattern that doesn't + * match any files. + */ +async function globSearch({ + basePath, + patterns, + rawPatterns, + configLoader, + errorOnUnmatchedPattern, +}) { + if (patterns.length === 0) { + return []; + } + + /* + * In this section we are converting the patterns into Minimatch + * instances for performance reasons. Because we are doing the same + * matches repeatedly, it's best to compile those patterns once and + * reuse them multiple times. + * + * To do that, we convert any patterns with an absolute path into a + * relative path and normalize it to Posix-style slashes. We also keep + * track of the relative patterns to map them back to the original + * patterns, which we need in order to throw an error if there are any + * unmatched patterns. + */ + const relativeToPatterns = new Map(); + const matchers = patterns.map((pattern, i) => { + const patternToUse = normalizeToPosix(path.relative(basePath, pattern)); + + relativeToPatterns.set(patternToUse, patterns[i]); + + return new Minimatch(patternToUse, MINIMATCH_OPTIONS); + }); + + /* + * We track unmatched patterns because we may want to throw an error when + * they occur. To start, this set is initialized with all of the patterns. + * Every time a match occurs, the pattern is removed from the set, making + * it easy to tell if we have any unmatched patterns left at the end of + * search. + */ + const unmatchedPatterns = new Set([...relativeToPatterns.keys()]); + const { hfs } = await import("@humanfs/node"); + + const walk = hfs.walk(basePath, { + async directoryFilter(entry) { + if (!matchers.some(matcher => matcher.match(entry.path, true))) { + return false; + } + + const absolutePath = path.resolve(basePath, entry.path); + const configs = + await configLoader.loadConfigArrayForDirectory(absolutePath); + + return !configs.isDirectoryIgnored(absolutePath); + }, + async entryFilter(entry) { + const absolutePath = path.resolve(basePath, entry.path); + + // entries may be directories or files so filter out directories + if (entry.isDirectory) { + return false; + } + + const configs = + await configLoader.loadConfigArrayForFile(absolutePath); + const config = configs.getConfig(absolutePath); + + /* + * Optimization: We need to track when patterns are left unmatched + * and so we use `unmatchedPatterns` to do that. There is a bit of + * complexity here because the same file can be matched by more than + * one pattern. So, when we start, we actually need to test every + * pattern against every file. Once we know there are no remaining + * unmatched patterns, then we can switch to just looking for the + * first matching pattern for improved speed. + */ + const matchesPattern = + unmatchedPatterns.size > 0 + ? matchers.reduce((previousValue, matcher) => { + const pathMatches = matcher.match(entry.path); + + /* + * We updated the unmatched patterns set only if the path + * matches and the file has a config. If the file has no + * config, that means there wasn't a match for the + * pattern so it should not be removed. + * + * Performance note: `getConfig()` aggressively caches + * results so there is no performance penalty for calling + * it multiple times with the same argument. + */ + if (pathMatches && config) { + unmatchedPatterns.delete(matcher.pattern); + } + + return pathMatches || previousValue; + }, false) + : matchers.some(matcher => matcher.match(entry.path)); + + return matchesPattern && config !== void 0; + }, + }); + + const filePaths = []; + + if (await hfs.isDirectory(basePath)) { + for await (const entry of walk) { + filePaths.push(path.resolve(basePath, entry.path)); + } + } + + // now check to see if we have any unmatched patterns + if (errorOnUnmatchedPattern && unmatchedPatterns.size > 0) { + throw new UnmatchedSearchPatternsError({ + basePath, + unmatchedPatterns: [...unmatchedPatterns].map(pattern => + relativeToPatterns.get(pattern), + ), + patterns, + rawPatterns, + }); + } + + return filePaths; +} + +/** + * Throws an error for unmatched patterns. The error will only contain information about the first one. + * Checks to see if there are any ignored results for a given search. + * @param {Object} options The options for this function. + * @param {string} options.basePath The directory to search. + * @param {Array} options.patterns An array of glob patterns + * that were used in the original search. + * @param {Array} options.rawPatterns An array of glob patterns + * as the user inputted them. Used for errors. + * @param {Array} options.unmatchedPatterns A non-empty array of absolute path glob patterns + * that were unmatched in the original search. + * @returns {Promise} Always throws an error. + * @throws {NoFilesFoundError} If the first unmatched pattern + * doesn't match any files even when there are no ignores. + * @throws {AllFilesIgnoredError} If the first unmatched pattern + * matches some files when there are no ignores. + */ +async function throwErrorForUnmatchedPatterns({ + basePath, + patterns, + rawPatterns, + unmatchedPatterns, +}) { + const pattern = unmatchedPatterns[0]; + const rawPattern = rawPatterns[patterns.indexOf(pattern)]; + + const patternHasMatch = await globMatch({ + basePath, + pattern, + }); + + if (patternHasMatch) { + throw new AllFilesIgnoredError(rawPattern); + } + + // if we get here there are truly no matches + throw new NoFilesFoundError(rawPattern, true); +} + +/** + * Performs multiple glob searches in parallel. + * @param {Object} options The options for this function. + * @param {Map} options.searches + * A map of absolute path glob patterns to match. + * @param {ConfigLoader|LegacyConfigLoader} options.configLoader The config loader to use for + * determining what to ignore. + * @param {boolean} options.errorOnUnmatchedPattern Determines if an + * unmatched glob pattern should throw an error. + * @returns {Promise>} An array of matching file paths + * or an empty array if there are no matches. + */ +async function globMultiSearch({ + searches, + configLoader, + errorOnUnmatchedPattern, +}) { + /* + * For convenience, we normalized the search map into an array of objects. + * Next, we filter out all searches that have no patterns. This happens + * primarily for the cwd, which is prepopulated in the searches map as an + * optimization. However, if it has no patterns, it means all patterns + * occur outside of the cwd and we can safely filter out that search. + */ + const normalizedSearches = [...searches] + .map(([basePath, { patterns, rawPatterns }]) => ({ + basePath, + patterns, + rawPatterns, + })) + .filter(({ patterns }) => patterns.length > 0); + + const results = await Promise.allSettled( + normalizedSearches.map(({ basePath, patterns, rawPatterns }) => + globSearch({ + basePath, + patterns, + rawPatterns, + configLoader, + errorOnUnmatchedPattern, + }), + ), + ); + + /* + * The first loop handles errors from the glob searches. Since we can't + * use `await` inside `flatMap`, we process errors separately in this loop. + * This results in two iterations over `results`, but since the length is + * less than or equal to the number of globs and directories passed on the + * command line, the performance impact should be minimal. + */ + for (let i = 0; i < results.length; i++) { + const result = results[i]; + const currentSearch = normalizedSearches[i]; + + if (result.status === "fulfilled") { + continue; + } + + // if we make it here then there was an error + const error = result.reason; + + // unexpected errors should be re-thrown + if (!error.basePath) { + throw error; + } + + if (errorOnUnmatchedPattern) { + await throwErrorForUnmatchedPatterns({ + ...currentSearch, + unmatchedPatterns: error.unmatchedPatterns, + }); + } + } + + // second loop for `fulfilled` results + return results.flatMap(result => result.value); +} + +/** + * Finds all files matching the options specified. + * @param {Object} args The arguments objects. + * @param {Array} args.patterns An array of glob patterns. + * @param {boolean} args.globInputPaths true to interpret glob patterns, + * false to not interpret glob patterns. + * @param {string} args.cwd The current working directory to find from. + * @param {ConfigLoader|LegacyConfigLoader} args.configLoader The config loeader for the current run. + * @param {boolean} args.errorOnUnmatchedPattern Determines if an unmatched pattern + * should throw an error. + * @returns {Promise>} The fully resolved file paths. + * @throws {AllFilesIgnoredError} If there are no results due to an ignore pattern. + * @throws {NoFilesFoundError} If no files matched the given patterns. + */ +async function findFiles({ + patterns, + globInputPaths, + cwd, + configLoader, + errorOnUnmatchedPattern, +}) { + const results = []; + const missingPatterns = []; + let globbyPatterns = []; + let rawPatterns = []; + const searches = new Map([ + [cwd, { patterns: globbyPatterns, rawPatterns: [] }], + ]); + + /* + * This part is a bit involved because we need to account for + * the different ways that the patterns can match directories. + * For each different way, we need to decide if we should look + * for a config file or just use the default config. (Directories + * without a config file always use the default config.) + * + * Here are the cases: + * + * 1. A directory is passed directly (e.g., "subdir"). In this case, we + * can assume that the user intends to lint this directory and we should + * not look for a config file in the parent directory, because the only + * reason to do that would be to ignore this directory (which we already + * know we don't want to do). Instead, we use the default config until we + * get to the directory that was passed, at which point we start looking + * for config files again. + * + * 2. A dot (".") or star ("*"). In this case, we want to read + * the config file in the current directory because the user is + * explicitly asking to lint the current directory. Note that "." + * will traverse into subdirectories while "*" will not. + * + * 3. A directory is passed in the form of "subdir/subsubdir". + * In this case, we don't want to look for a config file in the + * parent directory ("subdir"). We can skip looking for a config + * file until `entry.depth` is greater than 1 because there's no + * way that the pattern can match `entry.path` yet. + * + * 4. A directory glob pattern is passed (e.g., "subd*"). We want + * this case to act like case 2 because it's unclear whether or not + * any particular directory is meant to be traversed. + * + * 5. A recursive glob pattern is passed (e.g., "**"). We want this + * case to act like case 2. + */ + + // check to see if we have explicit files and directories + const filePaths = patterns.map(filePath => path.resolve(cwd, filePath)); + const stats = await Promise.all( + filePaths.map(filePath => fsp.stat(filePath).catch(() => {})), + ); + + stats.forEach((stat, index) => { + const filePath = filePaths[index]; + const pattern = normalizeToPosix(patterns[index]); + + if (stat) { + // files are added directly to the list + if (stat.isFile()) { + results.push(filePath); + } + + // directories need extensions attached + if (stat.isDirectory()) { + if (!searches.has(filePath)) { + searches.set(filePath, { patterns: [], rawPatterns: [] }); + } + ({ patterns: globbyPatterns, rawPatterns } = + searches.get(filePath)); + + globbyPatterns.push(`${normalizeToPosix(filePath)}/**`); + rawPatterns.push(pattern); + } + + return; + } + + // save patterns for later use based on whether globs are enabled + if (globInputPaths && isGlobPattern(pattern)) { + /* + * We are grouping patterns by their glob parent. This is done to + * make it easier to determine when a config file should be loaded. + */ + + const basePath = path.resolve(cwd, globParent(pattern)); + + if (!searches.has(basePath)) { + searches.set(basePath, { patterns: [], rawPatterns: [] }); + } + ({ patterns: globbyPatterns, rawPatterns } = + searches.get(basePath)); + + globbyPatterns.push(filePath); + rawPatterns.push(pattern); + } else { + missingPatterns.push(pattern); + } + }); + + // there were patterns that didn't match anything, tell the user + if (errorOnUnmatchedPattern && missingPatterns.length) { + throw new NoFilesFoundError(missingPatterns[0], globInputPaths); + } + + // now we are safe to do the search + const globbyResults = await globMultiSearch({ + searches, + configLoader, + errorOnUnmatchedPattern, + }); + + return [...new Set([...results, ...globbyResults])]; +} + +//----------------------------------------------------------------------------- +// Results-related Helpers +//----------------------------------------------------------------------------- + +/** + * Checks if the given message is an error message. + * @param {LintMessage} message The message to check. + * @returns {boolean} Whether or not the message is an error message. + * @private + */ +function isErrorMessage(message) { + return message.severity === 2; +} + +/** + * Returns result with warning by ignore settings + * @param {string} filePath Absolute file path of checked code + * @param {string} baseDir Absolute path of base directory + * @param {"ignored"|"external"|"unconfigured"} configStatus A status that determines why the file is ignored + * @returns {LintResult} Result with single warning + * @private + */ +function createIgnoreResult(filePath, baseDir, configStatus) { + let message; + + switch (configStatus) { + case "external": + message = "File ignored because outside of base path."; + break; + case "unconfigured": + message = + "File ignored because no matching configuration was supplied."; + break; + default: + { + const isInNodeModules = + baseDir && + path + .dirname(path.relative(baseDir, filePath)) + .split(path.sep) + .includes("node_modules"); + + if (isInNodeModules) { + message = + 'File ignored by default because it is located under the node_modules directory. Use ignore pattern "!**/node_modules/" to disable file ignore settings or use "--no-warn-ignored" to suppress this warning.'; + } else { + message = + 'File ignored because of a matching ignore pattern. Use "--no-ignore" to disable file ignore settings or use "--no-warn-ignored" to suppress this warning.'; + } + } + break; + } + + return { + filePath, + messages: [ + { + ruleId: null, + fatal: false, + severity: 1, + message, + nodeType: null, + }, + ], + suppressedMessages: [], + errorCount: 0, + warningCount: 1, + fatalErrorCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; +} + +/** + * It will calculate the error and warning count for collection of messages per file + * @param {LintMessage[]} messages Collection of messages + * @returns {Object} Contains the stats + * @private + */ +function calculateStatsPerFile(messages) { + const stat = { + errorCount: 0, + fatalErrorCount: 0, + warningCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; + + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + + if (message.fatal || message.severity === 2) { + stat.errorCount++; + if (message.fatal) { + stat.fatalErrorCount++; + } + if (message.fix) { + stat.fixableErrorCount++; + } + } else { + stat.warningCount++; + if (message.fix) { + stat.fixableWarningCount++; + } + } + } + return stat; +} + +//----------------------------------------------------------------------------- +// Options-related Helpers +//----------------------------------------------------------------------------- + +/** + * Check if a given value is a valid fix type or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is valid fix type. + */ +function isFixType(x) { + return ( + x === "directive" || + x === "problem" || + x === "suggestion" || + x === "layout" + ); +} + +/** + * Check if a given value is an array of fix types or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is an array of fix types. + */ +function isFixTypeArray(x) { + return Array.isArray(x) && x.every(isFixType); +} + +/** + * The error for invalid options. + */ +class ESLintInvalidOptionsError extends Error { + constructor(messages) { + super(`Invalid Options:\n- ${messages.join("\n- ")}`); + this.code = "ESLINT_INVALID_OPTIONS"; + Error.captureStackTrace(this, ESLintInvalidOptionsError); + } +} + +/** + * Validates and normalizes options for the wrapped CLIEngine instance. + * @param {ESLintOptions} options The options to process. + * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors. + * @returns {ESLintOptions} The normalized options. + */ +function processOptions({ + allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored. + baseConfig = null, + cache = false, + cacheLocation = ".eslintcache", + cacheStrategy = "metadata", + cwd = process.cwd(), + errorOnUnmatchedPattern = true, + fix = false, + fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property. + flags = [], + globInputPaths = true, + ignore = true, + ignorePatterns = null, + overrideConfig = null, + overrideConfigFile = null, + plugins = {}, + stats = false, + warnIgnored = true, + passOnNoPatterns = false, + ruleFilter = () => true, + ...unknownOptions +}) { + const errors = []; + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length >= 1) { + errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`); + if (unknownOptionKeys.includes("cacheFile")) { + errors.push( + "'cacheFile' has been removed. Please use the 'cacheLocation' option instead.", + ); + } + if (unknownOptionKeys.includes("configFile")) { + errors.push( + "'configFile' has been removed. Please use the 'overrideConfigFile' option instead.", + ); + } + if (unknownOptionKeys.includes("envs")) { + errors.push("'envs' has been removed."); + } + if (unknownOptionKeys.includes("extensions")) { + errors.push("'extensions' has been removed."); + } + if (unknownOptionKeys.includes("resolvePluginsRelativeTo")) { + errors.push("'resolvePluginsRelativeTo' has been removed."); + } + if (unknownOptionKeys.includes("globals")) { + errors.push( + "'globals' has been removed. Please use the 'overrideConfig.languageOptions.globals' option instead.", + ); + } + if (unknownOptionKeys.includes("ignorePath")) { + errors.push("'ignorePath' has been removed."); + } + if (unknownOptionKeys.includes("ignorePattern")) { + errors.push( + "'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.", + ); + } + if (unknownOptionKeys.includes("parser")) { + errors.push( + "'parser' has been removed. Please use the 'overrideConfig.languageOptions.parser' option instead.", + ); + } + if (unknownOptionKeys.includes("parserOptions")) { + errors.push( + "'parserOptions' has been removed. Please use the 'overrideConfig.languageOptions.parserOptions' option instead.", + ); + } + if (unknownOptionKeys.includes("rules")) { + errors.push( + "'rules' has been removed. Please use the 'overrideConfig.rules' option instead.", + ); + } + if (unknownOptionKeys.includes("rulePaths")) { + errors.push( + "'rulePaths' has been removed. Please define your rules using plugins.", + ); + } + if (unknownOptionKeys.includes("reportUnusedDisableDirectives")) { + errors.push( + "'reportUnusedDisableDirectives' has been removed. Please use the 'overrideConfig.linterOptions.reportUnusedDisableDirectives' option instead.", + ); + } + } + if (typeof allowInlineConfig !== "boolean") { + errors.push("'allowInlineConfig' must be a boolean."); + } + if (typeof baseConfig !== "object") { + errors.push("'baseConfig' must be an object or null."); + } + if (typeof cache !== "boolean") { + errors.push("'cache' must be a boolean."); + } + if (!isNonEmptyString(cacheLocation)) { + errors.push("'cacheLocation' must be a non-empty string."); + } + if (cacheStrategy !== "metadata" && cacheStrategy !== "content") { + errors.push('\'cacheStrategy\' must be any of "metadata", "content".'); + } + if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) { + errors.push("'cwd' must be an absolute path."); + } + if (typeof errorOnUnmatchedPattern !== "boolean") { + errors.push("'errorOnUnmatchedPattern' must be a boolean."); + } + if (typeof fix !== "boolean" && typeof fix !== "function") { + errors.push("'fix' must be a boolean or a function."); + } + if (fixTypes !== null && !isFixTypeArray(fixTypes)) { + errors.push( + '\'fixTypes\' must be an array of any of "directive", "problem", "suggestion", and "layout".', + ); + } + if (!isEmptyArrayOrArrayOfNonEmptyString(flags)) { + errors.push("'flags' must be an array of non-empty strings."); + } + if (typeof globInputPaths !== "boolean") { + errors.push("'globInputPaths' must be a boolean."); + } + if (typeof ignore !== "boolean") { + errors.push("'ignore' must be a boolean."); + } + if ( + !isEmptyArrayOrArrayOfNonEmptyString(ignorePatterns) && + ignorePatterns !== null + ) { + errors.push( + "'ignorePatterns' must be an array of non-empty strings or null.", + ); + } + if (typeof overrideConfig !== "object") { + errors.push("'overrideConfig' must be an object or null."); + } + if ( + !isNonEmptyString(overrideConfigFile) && + overrideConfigFile !== null && + overrideConfigFile !== true + ) { + errors.push( + "'overrideConfigFile' must be a non-empty string, null, or true.", + ); + } + if (typeof passOnNoPatterns !== "boolean") { + errors.push("'passOnNoPatterns' must be a boolean."); + } + if (typeof plugins !== "object") { + errors.push("'plugins' must be an object or null."); + } else if (plugins !== null && Object.keys(plugins).includes("")) { + errors.push("'plugins' must not include an empty string."); + } + if (Array.isArray(plugins)) { + errors.push( + "'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.", + ); + } + if (typeof stats !== "boolean") { + errors.push("'stats' must be a boolean."); + } + if (typeof warnIgnored !== "boolean") { + errors.push("'warnIgnored' must be a boolean."); + } + if (typeof ruleFilter !== "function") { + errors.push("'ruleFilter' must be a function."); + } + if (errors.length > 0) { + throw new ESLintInvalidOptionsError(errors); + } + + return { + allowInlineConfig, + baseConfig, + cache, + cacheLocation, + cacheStrategy, + + // when overrideConfigFile is true that means don't do config file lookup + configFile: overrideConfigFile === true ? false : overrideConfigFile, + overrideConfig, + cwd: path.normalize(cwd), + errorOnUnmatchedPattern, + fix, + fixTypes, + flags: [...flags], + globInputPaths, + ignore, + ignorePatterns, + stats, + passOnNoPatterns, + warnIgnored, + ruleFilter, + }; +} + +//----------------------------------------------------------------------------- +// Cache-related helpers +//----------------------------------------------------------------------------- + +/** + * return the cacheFile to be used by eslint, based on whether the provided parameter is + * a directory or looks like a directory (ends in `path.sep`), in which case the file + * name will be the `cacheFile/.cache_hashOfCWD` + * + * if cacheFile points to a file or looks like a file then in will just use that file + * @param {string} cacheFile The name of file to be used to store the cache + * @param {string} cwd Current working directory + * @param {Object} options The options + * @param {string} [options.prefix] The prefix to use for the cache file + * @returns {string} the resolved path to the cache file + */ +function getCacheFile(cacheFile, cwd, { prefix = ".cache_" } = {}) { + /* + * make sure the path separators are normalized for the environment/os + * keeping the trailing path separator if present + */ + const normalizedCacheFile = path.normalize(cacheFile); + + const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile); + const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep; + + /** + * return the name for the cache file in case the provided parameter is a directory + * @returns {string} the resolved path to the cacheFile + */ + function getCacheFileForDirectory() { + return path.join(resolvedCacheFile, `${prefix}${hash(cwd)}`); + } + + let fileStats; + + try { + fileStats = fs.lstatSync(resolvedCacheFile); + } catch { + fileStats = null; + } + + /* + * in case the file exists we need to verify if the provided path + * is a directory or a file. If it is a directory we want to create a file + * inside that directory + */ + if (fileStats) { + /* + * is a directory or is a file, but the original file the user provided + * looks like a directory but `path.resolve` removed the `last path.sep` + * so we need to still treat this like a directory + */ + if (fileStats.isDirectory() || looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + // is file so just use that file + return resolvedCacheFile; + } + + /* + * here we known the file or directory doesn't exist, + * so we will try to infer if its a directory if it looks like a directory + * for the current operating system. + */ + + // if the last character passed is a path separator we assume is a directory + if (looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + return resolvedCacheFile; +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + findFiles, + + isNonEmptyString, + isArrayOfNonEmptyString, + + createIgnoreResult, + isErrorMessage, + calculateStatsPerFile, + + processOptions, + + getCacheFile, +}; diff --git a/node_modules/eslint/lib/eslint/eslint.js b/node_modules/eslint/lib/eslint/eslint.js new file mode 100644 index 00000000..c504f175 --- /dev/null +++ b/node_modules/eslint/lib/eslint/eslint.js @@ -0,0 +1,1157 @@ +/** + * @fileoverview Main class using flat config + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("node:fs/promises"); +const { existsSync } = require("node:fs"); +const path = require("node:path"); +const { version } = require("../../package.json"); +const { Linter } = require("../linter"); +const { defaultConfig } = require("../config/default-config"); + +const { + findFiles, + getCacheFile, + + isNonEmptyString, + isArrayOfNonEmptyString, + + createIgnoreResult, + isErrorMessage, + calculateStatsPerFile, + + processOptions, +} = require("./eslint-helpers"); +const { pathToFileURL } = require("node:url"); +const LintResultCache = require("../cli-engine/lint-result-cache"); +const { Retrier } = require("@humanwhocodes/retry"); +const { ConfigLoader, LegacyConfigLoader } = require("../config/config-loader"); +const { WarningService } = require("../services/warning-service"); +const { Config } = require("../config/config.js"); +const { + getShorthandName, + getNamespaceFromTerm, + normalizePackageName, +} = require("../shared/naming.js"); +const { resolve } = require("../shared/relative-module-resolver.js"); + +/* + * This is necessary to allow overwriting writeFile for testing purposes. + * We can just use fs/promises once we drop Node.js 12 support. + */ + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +// For VSCode IntelliSense +/** + * @import { ConfigArray } from "../cli-engine/cli-engine.js"; + * @import { CLIEngineLintReport } from "./legacy-eslint.js"; + * @import { FlatConfigArray } from "../config/flat-config-array.js"; + * @import { RuleDefinition } from "@eslint/core"; + */ + +/** @typedef {ReturnType} ExtractedConfig */ +/** @typedef {import("../types").Linter.Config} Config */ +/** @typedef {import("../types").ESLint.DeprecatedRuleUse} DeprecatedRuleInfo */ +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").ESLint.LintResult} LintResult */ +/** @typedef {import("../types").ESLint.Plugin} Plugin */ +/** @typedef {import("../types").ESLint.ResultsMeta} ResultsMeta */ + +/** + * The options with which to configure the ESLint instance. + * @typedef {Object} ESLintOptions + * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. + * @property {Config|Array} [baseConfig] Base config, extended by all configs used with this instance + * @property {boolean} [cache] Enable result caching. + * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. + * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files. + * @property {string} [cwd] The value to use for the current working directory. + * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`. + * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. + * @property {string[]} [fixTypes] Array of rule types to apply fixes for. + * @property {string[]} [flags] Array of feature flags to enable. + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} [ignore] False disables all ignore patterns except for the default ones. + * @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to config ignores. These patterns are relative to `cwd`. + * @property {Config|Array} [overrideConfig] Override config, overrides all configs used with this instance + * @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy; + * doesn't do any config file lookup when `true`; considered to be a config filename + * when a string. + * @property {Record} [plugins] An array of plugin implementations. + * @property {boolean} [stats] True enables added statistics on lint results. + * @property {boolean} [warnIgnored] Show warnings when the file list includes ignored files + * @property {boolean} [passOnNoPatterns=false] When set to true, missing patterns cause + * the linting operation to short circuit and not report any failures. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const debug = require("debug")("eslint:eslint"); +const privateMembers = new WeakMap(); +const removedFormatters = new Set([ + "checkstyle", + "codeframe", + "compact", + "jslint-xml", + "junit", + "table", + "tap", + "unix", + "visualstudio", +]); + +/** + * Create rulesMeta object. + * @param {Map} rules a map of rules from which to generate the object. + * @returns {Object} metadata for all enabled rules. + */ +function createRulesMeta(rules) { + return Array.from(rules).reduce((retVal, [id, rule]) => { + retVal[id] = rule.meta; + return retVal; + }, {}); +} + +/** + * Return the absolute path of a file named `"__placeholder__.js"` in a given directory. + * This is used as a replacement for a missing file path. + * @param {string} cwd An absolute directory path. + * @returns {string} The absolute path of a file named `"__placeholder__.js"` in the given directory. + */ +function getPlaceholderPath(cwd) { + return path.join(cwd, "__placeholder__.js"); +} + +/** @type {WeakMap} */ +const usedDeprecatedRulesCache = new WeakMap(); + +/** + * Create used deprecated rule list. + * @param {ESLint} eslint The ESLint instance. + * @param {string} maybeFilePath The absolute path to a lint target file or `""`. + * @returns {DeprecatedRuleInfo[]} The used deprecated rule list. + */ +function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) { + const { + options: { cwd }, + configLoader, + } = privateMembers.get(eslint); + const filePath = path.isAbsolute(maybeFilePath) + ? maybeFilePath + : getPlaceholderPath(cwd); + const configs = configLoader.getCachedConfigArrayForFile(filePath); + const config = configs.getConfig(filePath); + + // Most files use the same config, so cache it. + if (config && !usedDeprecatedRulesCache.has(config)) { + const retv = []; + + if (config.rules) { + for (const [ruleId, ruleConf] of Object.entries(config.rules)) { + if (Config.getRuleNumericSeverity(ruleConf) === 0) { + continue; + } + const rule = config.getRuleDefinition(ruleId); + const meta = rule && rule.meta; + + if (meta && meta.deprecated) { + const usesNewFormat = typeof meta.deprecated === "object"; + + retv.push({ + ruleId, + replacedBy: usesNewFormat + ? (meta.deprecated.replacedBy?.map( + replacement => + `${replacement.plugin?.name !== void 0 ? `${getShorthandName(replacement.plugin.name, "eslint-plugin")}/` : ""}${replacement.rule?.name ?? ""}`, + ) ?? []) + : meta.replacedBy || [], + info: usesNewFormat ? meta.deprecated : void 0, + }); + } + } + } + + usedDeprecatedRulesCache.set(config, Object.freeze(retv)); + } + + return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]); +} + +/** + * Processes the linting results generated by a CLIEngine linting report to + * match the ESLint class's API. + * @param {ESLint} eslint The ESLint instance. + * @param {CLIEngineLintReport} report The CLIEngine linting report to process. + * @returns {LintResult[]} The processed linting results. + */ +function processLintReport(eslint, { results }) { + const descriptor = { + configurable: true, + enumerable: true, + get() { + return getOrFindUsedDeprecatedRules(eslint, this.filePath); + }, + }; + + for (const result of results) { + Object.defineProperty(result, "usedDeprecatedRules", descriptor); + } + + return results; +} + +/** + * An Array.prototype.sort() compatible compare function to order results by their file path. + * @param {LintResult} a The first lint result. + * @param {LintResult} b The second lint result. + * @returns {number} An integer representing the order in which the two results should occur. + */ +function compareResultsByFilePath(a, b) { + if (a.filePath < b.filePath) { + return -1; + } + + if (a.filePath > b.filePath) { + return 1; + } + + return 0; +} + +/** + * Determines which config file to use. This is determined by seeing if an + * override config file was passed, and if so, using it; otherwise, as long + * as override config file is not explicitly set to `false`, it will search + * upwards from the cwd for a file named `eslint.config.js`. + * + * This function is used primarily by the `--inspect-config` option. For now, + * we will maintain the existing behavior, which is to search up from the cwd. + * @param {ESLintOptions} options The ESLint instance options. + * @returns {Promise<{configFilePath:string|undefined;basePath:string}>} Location information for + * the config file. + */ +async function locateConfigFileToUse({ configFile, cwd }) { + const configLoader = new ConfigLoader({ + cwd, + configFile, + }); + + const configFilePath = await configLoader.findConfigFileForPath( + path.join(cwd, "__placeholder__.js"), + ); + + if (!configFilePath) { + throw new Error("No ESLint configuration file was found."); + } + + return { + configFilePath, + basePath: configFile ? cwd : path.dirname(configFilePath), + }; +} + +/** + * Processes an source code using ESLint. + * @param {Object} config The config object. + * @param {string} config.text The source code to verify. + * @param {string} config.cwd The path to the current working directory. + * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses ``. + * @param {FlatConfigArray} config.configs The config. + * @param {boolean} config.fix If `true` then it does fix. + * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments. + * @param {Function} config.ruleFilter A predicate function to filter which rules should be run. + * @param {boolean} config.stats If `true`, then if reports extra statistics with the lint results. + * @param {Linter} config.linter The linter instance to verify. + * @returns {LintResult} The result of linting. + * @private + */ +function verifyText({ + text, + cwd, + filePath: providedFilePath, + configs, + fix, + allowInlineConfig, + ruleFilter, + stats, + linter, +}) { + const filePath = providedFilePath || ""; + + debug(`Lint ${filePath}`); + + /* + * Verify. + * `config.extractConfig(filePath)` requires an absolute path, but `linter` + * doesn't know CWD, so it gives `linter` an absolute path always. + */ + const filePathToVerify = + filePath === "" ? getPlaceholderPath(cwd) : filePath; + const { fixed, messages, output } = linter.verifyAndFix(text, configs, { + allowInlineConfig, + filename: filePathToVerify, + fix, + ruleFilter, + stats, + + /** + * Check if the linter should adopt a given code block or not. + * @param {string} blockFilename The virtual filename of a code block. + * @returns {boolean} `true` if the linter should adopt the code block. + */ + filterCodeBlock(blockFilename) { + return configs.getConfig(blockFilename) !== void 0; + }, + }); + + // Tweak and return. + const result = { + filePath: filePath === "" ? filePath : path.resolve(filePath), + messages, + suppressedMessages: linter.getSuppressedMessages(), + ...calculateStatsPerFile(messages), + }; + + if (fixed) { + result.output = output; + } + + if ( + result.errorCount + result.warningCount > 0 && + typeof result.output === "undefined" + ) { + result.source = text; + } + + if (stats) { + result.stats = { + times: linter.getTimes(), + fixPasses: linter.getFixPassCount(), + }; + } + + return result; +} + +/** + * Checks whether a message's rule type should be fixed. + * @param {LintMessage} message The message to check. + * @param {FlatConfigArray} config The config for the file that generated the message. + * @param {string[]} fixTypes An array of fix types to check. + * @returns {boolean} Whether the message should be fixed. + */ +function shouldMessageBeFixed(message, config, fixTypes) { + if (!message.ruleId) { + return fixTypes.has("directive"); + } + + const rule = message.ruleId && config.getRuleDefinition(message.ruleId); + + return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type)); +} + +/** + * Creates an error to be thrown when an array of results passed to `getRulesMetaForResults` was not created by the current engine. + * @returns {TypeError} An error object. + */ +function createExtraneousResultsError() { + return new TypeError( + "Results object was not created from this ESLint instance.", + ); +} + +/** + * Creates a fixer function based on the provided fix, fixTypesSet, and config. + * @param {Function|boolean} fix The original fix option. + * @param {Set} fixTypesSet A set of fix types to filter messages for fixing. + * @param {FlatConfigArray} config The config for the file that generated the message. + * @returns {Function|boolean} The fixer function or the original fix value. + */ +function getFixerForFixTypes(fix, fixTypesSet, config) { + if (!fix || !fixTypesSet) { + return fix; + } + + const originalFix = typeof fix === "function" ? fix : () => true; + + return message => + shouldMessageBeFixed(message, config, fixTypesSet) && + originalFix(message); +} + +/** + * Retrieves flags from the environment variable ESLINT_FLAGS. + * @param {string[]} flags The flags defined via the API. + * @returns {string[]} The merged flags to use. + */ +function mergeEnvironmentFlags(flags) { + if (!process.env.ESLINT_FLAGS) { + return flags; + } + + const envFlags = process.env.ESLINT_FLAGS.trim().split(/\s*,\s*/gu); + return Array.from(new Set([...envFlags, ...flags])); +} + +//----------------------------------------------------------------------------- +// Main API +//----------------------------------------------------------------------------- + +/** + * Primary Node.js API for ESLint. + */ +class ESLint { + /** + * The type of configuration used by this class. + * @type {string} + */ + static configType = "flat"; + + /** + * The loader to use for finding config files. + * @type {ConfigLoader|LegacyConfigLoader} + */ + #configLoader; + + /** + * Creates a new instance of the main ESLint API. + * @param {ESLintOptions} options The options for this instance. + */ + constructor(options = {}) { + const defaultConfigs = []; + const processedOptions = processOptions(options); + const warningService = new WarningService(); + const linter = new Linter({ + cwd: processedOptions.cwd, + configType: "flat", + flags: mergeEnvironmentFlags(processedOptions.flags), + warningService, + }); + + const cacheFilePath = getCacheFile( + processedOptions.cacheLocation, + processedOptions.cwd, + ); + + const lintResultCache = processedOptions.cache + ? new LintResultCache(cacheFilePath, processedOptions.cacheStrategy) + : null; + + const configLoaderOptions = { + cwd: processedOptions.cwd, + baseConfig: processedOptions.baseConfig, + overrideConfig: processedOptions.overrideConfig, + configFile: processedOptions.configFile, + ignoreEnabled: processedOptions.ignore, + ignorePatterns: processedOptions.ignorePatterns, + defaultConfigs, + hasUnstableNativeNodeJsTSConfigFlag: linter.hasFlag( + "unstable_native_nodejs_ts_config", + ), + warningService, + }; + + this.#configLoader = linter.hasFlag("unstable_config_lookup_from_file") + ? new ConfigLoader(configLoaderOptions) + : new LegacyConfigLoader(configLoaderOptions); + + debug(`Using config loader ${this.#configLoader.constructor.name}`); + + privateMembers.set(this, { + options: processedOptions, + linter, + cacheFilePath, + lintResultCache, + defaultConfigs, + configs: null, + configLoader: this.#configLoader, + }); + + /** + * If additional plugins are passed in, add that to the default + * configs for this instance. + */ + if (options.plugins) { + const plugins = {}; + + for (const [pluginName, plugin] of Object.entries( + options.plugins, + )) { + plugins[getShorthandName(pluginName, "eslint-plugin")] = plugin; + } + + defaultConfigs.push({ + plugins, + }); + } + + // Check for the .eslintignore file, and warn if it's present. + if (existsSync(path.resolve(processedOptions.cwd, ".eslintignore"))) { + warningService.emitESLintIgnoreWarning(); + } + } + + /** + * The version text. + * @type {string} + */ + static get version() { + return version; + } + + /** + * The default configuration that ESLint uses internally. This is provided for tooling that wants to calculate configurations using the same defaults as ESLint. + * Keep in mind that the default configuration may change from version to version, so you shouldn't rely on any particular keys or values to be present. + * @type {ConfigArray} + */ + static get defaultConfig() { + return defaultConfig; + } + + /** + * Outputs fixes from the given results to files. + * @param {LintResult[]} results The lint results. + * @returns {Promise} Returns a promise that is used to track side effects. + */ + static async outputFixes(results) { + if (!Array.isArray(results)) { + throw new Error("'results' must be an array"); + } + + await Promise.all( + results + .filter(result => { + if (typeof result !== "object" || result === null) { + throw new Error("'results' must include only objects"); + } + return ( + typeof result.output === "string" && + path.isAbsolute(result.filePath) + ); + }) + .map(r => fs.writeFile(r.filePath, r.output)), + ); + } + + /** + * Returns results that only contains errors. + * @param {LintResult[]} results The results to filter. + * @returns {LintResult[]} The filtered results. + */ + static getErrorResults(results) { + const filtered = []; + + results.forEach(result => { + const filteredMessages = result.messages.filter(isErrorMessage); + const filteredSuppressedMessages = + result.suppressedMessages.filter(isErrorMessage); + + if (filteredMessages.length > 0) { + filtered.push({ + ...result, + messages: filteredMessages, + suppressedMessages: filteredSuppressedMessages, + errorCount: filteredMessages.length, + warningCount: 0, + fixableErrorCount: result.fixableErrorCount, + fixableWarningCount: 0, + }); + } + }); + + return filtered; + } + + /** + * Returns meta objects for each rule represented in the lint results. + * @param {LintResult[]} results The results to fetch rules meta for. + * @returns {Object} A mapping of ruleIds to rule meta objects. + * @throws {TypeError} When the results object wasn't created from this ESLint instance. + * @throws {TypeError} When a plugin or rule is missing. + */ + getRulesMetaForResults(results) { + // short-circuit simple case + if (results.length === 0) { + return {}; + } + + const resultRules = new Map(); + const { + configLoader, + options: { cwd }, + } = privateMembers.get(this); + + for (const result of results) { + /* + * Normalize filename for . + */ + const filePath = + result.filePath === "" + ? getPlaceholderPath(cwd) + : result.filePath; + const allMessages = result.messages.concat( + result.suppressedMessages, + ); + + for (const { ruleId } of allMessages) { + if (!ruleId) { + continue; + } + + /* + * All of the plugin and rule information is contained within the + * calculated config for the given file. + */ + let configs; + + try { + configs = + configLoader.getCachedConfigArrayForFile(filePath); + } catch { + throw createExtraneousResultsError(); + } + + const config = configs.getConfig(filePath); + + if (!config) { + throw createExtraneousResultsError(); + } + const rule = config.getRuleDefinition(ruleId); + + // ignore unknown rules + if (rule) { + resultRules.set(ruleId, rule); + } + } + } + + return createRulesMeta(resultRules); + } + + /** + * Indicates if the given feature flag is enabled for this instance. + * @param {string} flag The feature flag to check. + * @returns {boolean} `true` if the feature flag is enabled, `false` if not. + */ + hasFlag(flag) { + // note: Linter does validation of the flags + return privateMembers.get(this).linter.hasFlag(flag); + } + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string|string[]} patterns An array of file and directory names. + * @returns {Promise} The results of linting the file patterns given. + */ + async lintFiles(patterns) { + let normalizedPatterns = patterns; + const { + cacheFilePath, + lintResultCache, + linter, + options: eslintOptions, + } = privateMembers.get(this); + + /* + * Special cases: + * 1. `patterns` is an empty string + * 2. `patterns` is an empty array + * + * In both cases, we use the cwd as the directory to lint. + */ + if ( + patterns === "" || + (Array.isArray(patterns) && patterns.length === 0) + ) { + /* + * Special case: If `passOnNoPatterns` is true, then we just exit + * without doing any work. + */ + if (eslintOptions.passOnNoPatterns) { + return []; + } + + normalizedPatterns = ["."]; + } else { + if ( + !isNonEmptyString(patterns) && + !isArrayOfNonEmptyString(patterns) + ) { + throw new Error( + "'patterns' must be a non-empty string or an array of non-empty strings", + ); + } + + if (typeof patterns === "string") { + normalizedPatterns = [patterns]; + } + } + + debug(`Using file patterns: ${normalizedPatterns}`); + + const { + allowInlineConfig, + cache, + cwd, + fix, + fixTypes, + ruleFilter, + stats, + globInputPaths, + errorOnUnmatchedPattern, + warnIgnored, + } = eslintOptions; + const startTime = Date.now(); + const fixTypesSet = fixTypes ? new Set(fixTypes) : null; + + // Delete cache file; should this be done here? + if (!cache && cacheFilePath) { + debug(`Deleting cache file at ${cacheFilePath}`); + + try { + if (existsSync(cacheFilePath)) { + await fs.unlink(cacheFilePath); + } + } catch (error) { + if (existsSync(cacheFilePath)) { + throw error; + } + } + } + + const filePaths = await findFiles({ + patterns: normalizedPatterns, + cwd, + globInputPaths, + configLoader: this.#configLoader, + errorOnUnmatchedPattern, + }); + const controller = new AbortController(); + const retryCodes = new Set(["ENFILE", "EMFILE"]); + const retrier = new Retrier(error => retryCodes.has(error.code), { + concurrency: 100, + }); + + debug( + `${filePaths.length} files found in: ${Date.now() - startTime}ms`, + ); + + /* + * Because we need to process multiple files, including reading from disk, + * it is most efficient to start by reading each file via promises so that + * they can be done in parallel. Then, we can lint the returned text. This + * ensures we are waiting the minimum amount of time in between lints. + */ + const results = await Promise.all( + filePaths.map(async filePath => { + const configs = + await this.#configLoader.loadConfigArrayForFile(filePath); + const config = configs.getConfig(filePath); + + /* + * If a filename was entered that cannot be matched + * to a config, then notify the user. + */ + if (!config) { + if (warnIgnored) { + const configStatus = configs.getConfigStatus(filePath); + + return createIgnoreResult(filePath, cwd, configStatus); + } + + return void 0; + } + + // Skip if there is cached result. + if (lintResultCache) { + const cachedResult = lintResultCache.getCachedLintResults( + filePath, + config, + ); + + if (cachedResult) { + const hadMessages = + cachedResult.messages && + cachedResult.messages.length > 0; + + if (hadMessages && fix) { + debug( + `Reprocessing cached file to allow autofix: ${filePath}`, + ); + } else { + debug( + `Skipping file since it hasn't changed: ${filePath}`, + ); + return cachedResult; + } + } + } + + // set up fixer for fixTypes if necessary + const fixer = getFixerForFixTypes(fix, fixTypesSet, config); + + return retrier + .retry( + () => + fs + .readFile(filePath, { + encoding: "utf8", + signal: controller.signal, + }) + .then(text => { + // fail immediately if an error occurred in another file + controller.signal.throwIfAborted(); + + // do the linting + const result = verifyText({ + text, + filePath, + configs, + cwd, + fix: fixer, + allowInlineConfig, + ruleFilter, + stats, + linter, + }); + + /* + * Store the lint result in the LintResultCache. + * NOTE: The LintResultCache will remove the file source and any + * other properties that are difficult to serialize, and will + * hydrate those properties back in on future lint runs. + */ + if (lintResultCache) { + lintResultCache.setCachedLintResults( + filePath, + config, + result, + ); + } + + return result; + }), + { signal: controller.signal }, + ) + .catch(error => { + controller.abort(error); + throw error; + }); + }), + ); + + // Persist the cache to disk. + if (lintResultCache) { + lintResultCache.reconcile(); + } + + const finalResults = results.filter(result => !!result); + + return processLintReport(this, { + results: finalResults, + }); + } + + /** + * Executes the current configuration on text. + * @param {string} code A string of JavaScript code to lint. + * @param {Object} [options] The options. + * @param {string} [options.filePath] The path to the file of the source code. + * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path. + * @returns {Promise} The results of linting the string of code given. + */ + async lintText(code, options = {}) { + // Parameter validation + + if (typeof code !== "string") { + throw new Error("'code' must be a string"); + } + + if (typeof options !== "object") { + throw new Error("'options' must be an object, null, or undefined"); + } + + // Options validation + + const { filePath, warnIgnored, ...unknownOptions } = options || {}; + + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length > 0) { + throw new Error( + `'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`, + ); + } + + if (filePath !== void 0 && !isNonEmptyString(filePath)) { + throw new Error( + "'options.filePath' must be a non-empty string or undefined", + ); + } + + if ( + typeof warnIgnored !== "boolean" && + typeof warnIgnored !== "undefined" + ) { + throw new Error( + "'options.warnIgnored' must be a boolean or undefined", + ); + } + + // Now we can get down to linting + + const { linter, options: eslintOptions } = privateMembers.get(this); + const { + allowInlineConfig, + cwd, + fix, + fixTypes, + warnIgnored: constructorWarnIgnored, + ruleFilter, + stats, + } = eslintOptions; + const results = []; + const startTime = Date.now(); + const fixTypesSet = fixTypes ? new Set(fixTypes) : null; + const resolvedFilename = path.resolve( + cwd, + filePath || "__placeholder__.js", + ); + const configs = + await this.#configLoader.loadConfigArrayForFile(resolvedFilename); + const configStatus = + configs?.getConfigStatus(resolvedFilename) ?? "unconfigured"; + + // Clear the last used config arrays. + if (resolvedFilename && configStatus !== "matched") { + const shouldWarnIgnored = + typeof warnIgnored === "boolean" + ? warnIgnored + : constructorWarnIgnored; + + if (shouldWarnIgnored) { + results.push( + createIgnoreResult(resolvedFilename, cwd, configStatus), + ); + } + } else { + const config = configs.getConfig(resolvedFilename); + const fixer = getFixerForFixTypes(fix, fixTypesSet, config); + + // Do lint. + results.push( + verifyText({ + text: code, + filePath: resolvedFilename.endsWith("__placeholder__.js") + ? "" + : resolvedFilename, + configs, + cwd, + fix: fixer, + allowInlineConfig, + ruleFilter, + stats, + linter, + }), + ); + } + + debug(`Linting complete in: ${Date.now() - startTime}ms`); + + return processLintReport(this, { + results, + }); + } + + /** + * Returns the formatter representing the given formatter name. + * @param {string} [name] The name of the formatter to load. + * The following values are allowed: + * - `undefined` ... Load `stylish` builtin formatter. + * - A builtin formatter name ... Load the builtin formatter. + * - A third-party formatter name: + * - `foo` → `eslint-formatter-foo` + * - `@foo` → `@foo/eslint-formatter` + * - `@foo/bar` → `@foo/eslint-formatter-bar` + * - A file path ... Load the file. + * @returns {Promise} A promise resolving to the formatter object. + * This promise will be rejected if the given formatter was not found or not + * a function. + */ + async loadFormatter(name = "stylish") { + if (typeof name !== "string") { + throw new Error("'name' must be a string"); + } + + // replace \ with / for Windows compatibility + const normalizedFormatName = name.replace(/\\/gu, "/"); + const namespace = getNamespaceFromTerm(normalizedFormatName); + + // grab our options + const { cwd } = privateMembers.get(this).options; + + let formatterPath; + + // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages) + if (!namespace && normalizedFormatName.includes("/")) { + formatterPath = path.resolve(cwd, normalizedFormatName); + } else { + try { + const npmFormat = normalizePackageName( + normalizedFormatName, + "eslint-formatter", + ); + + // TODO: This is pretty dirty...would be nice to clean up at some point. + formatterPath = resolve(npmFormat, getPlaceholderPath(cwd)); + } catch { + formatterPath = path.resolve( + __dirname, + "../", + "cli-engine", + "formatters", + `${normalizedFormatName}.js`, + ); + } + } + + let formatter; + + try { + formatter = (await import(pathToFileURL(formatterPath))).default; + } catch (ex) { + // check for formatters that have been removed + if (removedFormatters.has(name)) { + ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``; + } else { + ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`; + } + + throw ex; + } + + if (typeof formatter !== "function") { + throw new TypeError( + `Formatter must be a function, but got a ${typeof formatter}.`, + ); + } + + const eslint = this; + + return { + /** + * The main formatter method. + * @param {LintResult[]} results The lint results to format. + * @param {ResultsMeta} resultsMeta Warning count and max threshold. + * @returns {string} The formatted lint results. + */ + format(results, resultsMeta) { + let rulesMeta = null; + + results.sort(compareResultsByFilePath); + + return formatter(results, { + ...resultsMeta, + cwd, + get rulesMeta() { + if (!rulesMeta) { + rulesMeta = eslint.getRulesMetaForResults(results); + } + + return rulesMeta; + }, + }); + }, + }; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file to retrieve a config object for. + * @returns {Promise} A configuration object for the file + * or `undefined` if there is no configuration data for the object. + */ + async calculateConfigForFile(filePath) { + if (!isNonEmptyString(filePath)) { + throw new Error("'filePath' must be a non-empty string"); + } + const options = privateMembers.get(this).options; + const absolutePath = path.resolve(options.cwd, filePath); + const configs = + await this.#configLoader.loadConfigArrayForFile(absolutePath); + + if (!configs) { + const error = new Error("Could not find config file."); + + error.messageTemplate = "config-file-missing"; + throw error; + } + + return configs.getConfig(absolutePath); + } + + /** + * Finds the config file being used by this instance based on the options + * passed to the constructor. + * @param {string} [filePath] The path of the file to find the config file for. + * @returns {Promise} The path to the config file being used or + * `undefined` if no config file is being used. + */ + findConfigFile(filePath) { + const options = privateMembers.get(this).options; + + /* + * Because the new config lookup scheme skips the current directory + * and looks into the parent directories, we need to use a placeholder + * directory to ensure the file in cwd is checked. + */ + const fakeCwd = path.join(options.cwd, "__placeholder__"); + + return this.#configLoader + .findConfigFileForPath(filePath ?? fakeCwd) + .catch(() => void 0); + } + + /** + * Checks if a given path is ignored by ESLint. + * @param {string} filePath The path of the file to check. + * @returns {Promise} Whether or not the given path is ignored. + */ + async isPathIgnored(filePath) { + const config = await this.calculateConfigForFile(filePath); + + return config === void 0; + } +} + +/** + * Returns whether flat config should be used. + * @returns {Promise} Whether flat config should be used. + */ +async function shouldUseFlatConfig() { + return process.env.ESLINT_USE_FLAT_CONFIG !== "false"; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + ESLint, + shouldUseFlatConfig, + locateConfigFileToUse, +}; diff --git a/node_modules/eslint/lib/eslint/index.js b/node_modules/eslint/lib/eslint/index.js new file mode 100644 index 00000000..40588d5d --- /dev/null +++ b/node_modules/eslint/lib/eslint/index.js @@ -0,0 +1,9 @@ +"use strict"; + +const { ESLint } = require("./eslint"); +const { LegacyESLint } = require("./legacy-eslint"); + +module.exports = { + ESLint, + LegacyESLint, +}; diff --git a/node_modules/eslint/lib/eslint/legacy-eslint.js b/node_modules/eslint/lib/eslint/legacy-eslint.js new file mode 100644 index 00000000..36d30e5a --- /dev/null +++ b/node_modules/eslint/lib/eslint/legacy-eslint.js @@ -0,0 +1,786 @@ +/** + * @fileoverview Main API Class + * @author Kai Cataldo + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("node:path"); +const fs = require("node:fs"); +const { promisify } = require("node:util"); +const { + CLIEngine, + getCLIEngineInternalSlots, +} = require("../cli-engine/cli-engine"); +const BuiltinRules = require("../rules"); +const { + Legacy: { + ConfigOps: { getRuleSeverity }, + }, +} = require("@eslint/eslintrc"); +const { version } = require("../../package.json"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */ +/** @typedef {import("../types").ESLint.ConfigData} ConfigData */ +/** @typedef {import("../types").ESLint.DeprecatedRuleUse} DeprecatedRuleInfo */ +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").ESLint.LintResult} LintResult */ +/** @typedef {import("../types").ESLint.Plugin} Plugin */ +/** @typedef {import("../types").ESLint.ResultsMeta} ResultsMeta */ +/** @typedef {import("../types").Rule.RuleModule} Rule */ +/** @typedef {import("../types").Linter.SuppressedLintMessage} SuppressedLintMessage */ + +/** + * The main formatter object. + * @typedef LoadedFormatter + * @property {(results: LintResult[], resultsMeta: ResultsMeta) => string | Promise} format format function. + */ + +/** + * The options with which to configure the LegacyESLint instance. + * @typedef {Object} LegacyESLintOptions + * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. + * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance + * @property {boolean} [cache] Enable result caching. + * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. + * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files. + * @property {string} [cwd] The value to use for the current working directory. + * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`. + * @property {string[]} [extensions] An array of file extensions to check. + * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. + * @property {string[]} [fixTypes] Array of rule types to apply fixes for. + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} [ignore] False disables use of .eslintignore. + * @property {string} [ignorePath] The ignore file to use instead of .eslintignore. + * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance + * @property {string} [overrideConfigFile] The configuration file to use. + * @property {Record|null} [plugins] Preloaded plugins. This is a map-like object, keys are plugin IDs and each value is implementation. + * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives. + * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD. + * @property {string[]} [rulePaths] An array of directories to load custom rules from. + * @property {boolean} [useEslintrc] False disables looking for .eslintrc.* files. + * @property {boolean} [passOnNoPatterns=false] When set to true, missing patterns cause + * the linting operation to short circuit and not report any failures. + */ + +/** + * A rules metadata object. + * @typedef {Object} RulesMeta + * @property {string} id The plugin ID. + * @property {Object} definition The plugin definition. + */ + +/** + * Private members for the `ESLint` instance. + * @typedef {Object} ESLintPrivateMembers + * @property {CLIEngine} cliEngine The wrapped CLIEngine instance. + * @property {LegacyESLintOptions} options The options used to instantiate the ESLint instance. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const writeFile = promisify(fs.writeFile); + +/** + * The map with which to store private class members. + * @type {WeakMap} + */ +const privateMembersMap = new WeakMap(); + +/** + * Check if a given value is a non-empty string or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is a non-empty string. + */ +function isNonEmptyString(value) { + return typeof value === "string" && value.trim() !== ""; +} + +/** + * Check if a given value is an array of non-empty strings or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an array of non-empty strings. + */ +function isArrayOfNonEmptyString(value) { + return ( + Array.isArray(value) && value.length && value.every(isNonEmptyString) + ); +} + +/** + * Check if a given value is an empty array or an array of non-empty strings. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an empty array or an array of non-empty + * strings. + */ +function isEmptyArrayOrArrayOfNonEmptyString(value) { + return Array.isArray(value) && value.every(isNonEmptyString); +} + +/** + * Check if a given value is a valid fix type or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is valid fix type. + */ +function isFixType(value) { + return ( + value === "directive" || + value === "problem" || + value === "suggestion" || + value === "layout" + ); +} + +/** + * Check if a given value is an array of fix types or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an array of fix types. + */ +function isFixTypeArray(value) { + return Array.isArray(value) && value.every(isFixType); +} + +/** + * The error for invalid options. + */ +class ESLintInvalidOptionsError extends Error { + constructor(messages) { + super(`Invalid Options:\n- ${messages.join("\n- ")}`); + this.code = "ESLINT_INVALID_OPTIONS"; + Error.captureStackTrace(this, ESLintInvalidOptionsError); + } +} + +/** + * Validates and normalizes options for the wrapped CLIEngine instance. + * @param {LegacyESLintOptions} options The options to process. + * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors. + * @returns {LegacyESLintOptions} The normalized options. + */ +function processOptions({ + allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored. + baseConfig = null, + cache = false, + cacheLocation = ".eslintcache", + cacheStrategy = "metadata", + cwd = process.cwd(), + errorOnUnmatchedPattern = true, + extensions = null, // ← should be null by default because if it's an array then it suppresses RFC20 feature. + fix = false, + fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property. + flags /* eslint-disable-line no-unused-vars -- leaving for compatibility with ESLint#hasFlag */, + globInputPaths = true, + ignore = true, + ignorePath = null, // ← should be null by default because if it's a string then it may throw ENOENT. + overrideConfig = null, + overrideConfigFile = null, + plugins = {}, + reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that. + resolvePluginsRelativeTo = null, // ← should be null by default because if it's a string then it suppresses RFC47 feature. + rulePaths = [], + useEslintrc = true, + passOnNoPatterns = false, + ...unknownOptions +}) { + const errors = []; + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length >= 1) { + errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`); + if (unknownOptionKeys.includes("cacheFile")) { + errors.push( + "'cacheFile' has been removed. Please use the 'cacheLocation' option instead.", + ); + } + if (unknownOptionKeys.includes("configFile")) { + errors.push( + "'configFile' has been removed. Please use the 'overrideConfigFile' option instead.", + ); + } + if (unknownOptionKeys.includes("envs")) { + errors.push( + "'envs' has been removed. Please use the 'overrideConfig.env' option instead.", + ); + } + if (unknownOptionKeys.includes("globals")) { + errors.push( + "'globals' has been removed. Please use the 'overrideConfig.globals' option instead.", + ); + } + if (unknownOptionKeys.includes("ignorePattern")) { + errors.push( + "'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.", + ); + } + if (unknownOptionKeys.includes("parser")) { + errors.push( + "'parser' has been removed. Please use the 'overrideConfig.parser' option instead.", + ); + } + if (unknownOptionKeys.includes("parserOptions")) { + errors.push( + "'parserOptions' has been removed. Please use the 'overrideConfig.parserOptions' option instead.", + ); + } + if (unknownOptionKeys.includes("rules")) { + errors.push( + "'rules' has been removed. Please use the 'overrideConfig.rules' option instead.", + ); + } + } + if (typeof allowInlineConfig !== "boolean") { + errors.push("'allowInlineConfig' must be a boolean."); + } + if (typeof baseConfig !== "object") { + errors.push("'baseConfig' must be an object or null."); + } + if (typeof cache !== "boolean") { + errors.push("'cache' must be a boolean."); + } + if (!isNonEmptyString(cacheLocation)) { + errors.push("'cacheLocation' must be a non-empty string."); + } + if (cacheStrategy !== "metadata" && cacheStrategy !== "content") { + errors.push('\'cacheStrategy\' must be any of "metadata", "content".'); + } + if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) { + errors.push("'cwd' must be an absolute path."); + } + if (typeof errorOnUnmatchedPattern !== "boolean") { + errors.push("'errorOnUnmatchedPattern' must be a boolean."); + } + if ( + !isEmptyArrayOrArrayOfNonEmptyString(extensions) && + extensions !== null + ) { + errors.push( + "'extensions' must be an array of non-empty strings or null.", + ); + } + if (typeof fix !== "boolean" && typeof fix !== "function") { + errors.push("'fix' must be a boolean or a function."); + } + if (fixTypes !== null && !isFixTypeArray(fixTypes)) { + errors.push( + '\'fixTypes\' must be an array of any of "directive", "problem", "suggestion", and "layout".', + ); + } + if (typeof globInputPaths !== "boolean") { + errors.push("'globInputPaths' must be a boolean."); + } + if (typeof ignore !== "boolean") { + errors.push("'ignore' must be a boolean."); + } + if (!isNonEmptyString(ignorePath) && ignorePath !== null) { + errors.push("'ignorePath' must be a non-empty string or null."); + } + if (typeof overrideConfig !== "object") { + errors.push("'overrideConfig' must be an object or null."); + } + if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null) { + errors.push("'overrideConfigFile' must be a non-empty string or null."); + } + if (typeof plugins !== "object") { + errors.push("'plugins' must be an object or null."); + } else if (plugins !== null && Object.keys(plugins).includes("")) { + errors.push("'plugins' must not include an empty string."); + } + if (Array.isArray(plugins)) { + errors.push( + "'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.", + ); + } + if ( + reportUnusedDisableDirectives !== "error" && + reportUnusedDisableDirectives !== "warn" && + reportUnusedDisableDirectives !== "off" && + reportUnusedDisableDirectives !== null + ) { + errors.push( + '\'reportUnusedDisableDirectives\' must be any of "error", "warn", "off", and null.', + ); + } + if ( + !isNonEmptyString(resolvePluginsRelativeTo) && + resolvePluginsRelativeTo !== null + ) { + errors.push( + "'resolvePluginsRelativeTo' must be a non-empty string or null.", + ); + } + if (!isEmptyArrayOrArrayOfNonEmptyString(rulePaths)) { + errors.push("'rulePaths' must be an array of non-empty strings."); + } + if (typeof useEslintrc !== "boolean") { + errors.push("'useEslintrc' must be a boolean."); + } + if (typeof passOnNoPatterns !== "boolean") { + errors.push("'passOnNoPatterns' must be a boolean."); + } + + if (errors.length > 0) { + throw new ESLintInvalidOptionsError(errors); + } + + return { + allowInlineConfig, + baseConfig, + cache, + cacheLocation, + cacheStrategy, + configFile: overrideConfigFile, + cwd: path.normalize(cwd), + errorOnUnmatchedPattern, + extensions, + fix, + fixTypes, + flags: [], // LegacyESLint does not support flags, so just ignore them. + globInputPaths, + ignore, + ignorePath, + reportUnusedDisableDirectives, + resolvePluginsRelativeTo, + rulePaths, + useEslintrc, + passOnNoPatterns, + }; +} + +/** + * Check if a value has one or more properties and that value is not undefined. + * @param {any} obj The value to check. + * @returns {boolean} `true` if `obj` has one or more properties that value is not undefined. + */ +function hasDefinedProperty(obj) { + if (typeof obj === "object" && obj !== null) { + for (const key in obj) { + if (typeof obj[key] !== "undefined") { + return true; + } + } + } + return false; +} + +/** + * Create rulesMeta object. + * @param {Map} rules a map of rules from which to generate the object. + * @returns {Object} metadata for all enabled rules. + */ +function createRulesMeta(rules) { + return Array.from(rules).reduce((retVal, [id, rule]) => { + retVal[id] = rule.meta; + return retVal; + }, {}); +} + +/** @type {WeakMap} */ +const usedDeprecatedRulesCache = new WeakMap(); + +/** + * Create used deprecated rule list. + * @param {CLIEngine} cliEngine The CLIEngine instance. + * @param {string} maybeFilePath The absolute path to a lint target file or `""`. + * @returns {DeprecatedRuleInfo[]} The used deprecated rule list. + */ +function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) { + const { + configArrayFactory, + options: { cwd }, + } = getCLIEngineInternalSlots(cliEngine); + const filePath = path.isAbsolute(maybeFilePath) + ? maybeFilePath + : path.join(cwd, "__placeholder__.js"); + const configArray = configArrayFactory.getConfigArrayForFile(filePath); + const config = configArray.extractConfig(filePath); + + // Most files use the same config, so cache it. + if (!usedDeprecatedRulesCache.has(config)) { + const pluginRules = configArray.pluginRules; + const retv = []; + + for (const [ruleId, ruleConf] of Object.entries(config.rules)) { + if (getRuleSeverity(ruleConf) === 0) { + continue; + } + const rule = pluginRules.get(ruleId) || BuiltinRules.get(ruleId); + const meta = rule && rule.meta; + + if (meta && meta.deprecated) { + retv.push({ ruleId, replacedBy: meta.replacedBy || [] }); + } + } + + usedDeprecatedRulesCache.set(config, Object.freeze(retv)); + } + + return usedDeprecatedRulesCache.get(config); +} + +/** + * Processes the linting results generated by a CLIEngine linting report to + * match the ESLint class's API. + * @param {CLIEngine} cliEngine The CLIEngine instance. + * @param {CLIEngineLintReport} report The CLIEngine linting report to process. + * @returns {LintResult[]} The processed linting results. + */ +function processCLIEngineLintReport(cliEngine, { results }) { + const descriptor = { + configurable: true, + enumerable: true, + get() { + return getOrFindUsedDeprecatedRules(cliEngine, this.filePath); + }, + }; + + for (const result of results) { + Object.defineProperty(result, "usedDeprecatedRules", descriptor); + } + + return results; +} + +/** + * An Array.prototype.sort() compatible compare function to order results by their file path. + * @param {LintResult} a The first lint result. + * @param {LintResult} b The second lint result. + * @returns {number} An integer representing the order in which the two results should occur. + */ +function compareResultsByFilePath(a, b) { + if (a.filePath < b.filePath) { + return -1; + } + + if (a.filePath > b.filePath) { + return 1; + } + + return 0; +} + +/** + * Main API. + */ +class LegacyESLint { + /** + * The type of configuration used by this class. + * @type {string} + */ + static configType = "eslintrc"; + + /** + * Creates a new instance of the main ESLint API. + * @param {LegacyESLintOptions} options The options for this instance. + */ + constructor(options = {}) { + const processedOptions = processOptions(options); + const cliEngine = new CLIEngine(processedOptions, { + preloadedPlugins: options.plugins, + }); + const { configArrayFactory, lastConfigArrays } = + getCLIEngineInternalSlots(cliEngine); + let updated = false; + + /* + * Address `overrideConfig` to set override config. + * Operate the `configArrayFactory` internal slot directly because this + * functionality doesn't exist as the public API of CLIEngine. + */ + if (hasDefinedProperty(options.overrideConfig)) { + configArrayFactory.setOverrideConfig(options.overrideConfig); + updated = true; + } + + // Update caches. + if (updated) { + configArrayFactory.clearCache(); + lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile(); + } + + // Initialize private properties. + privateMembersMap.set(this, { + cliEngine, + options: processedOptions, + }); + } + + /** + * The version text. + * @type {string} + */ + static get version() { + return version; + } + + /** + * Outputs fixes from the given results to files. + * @param {LintResult[]} results The lint results. + * @returns {Promise} Returns a promise that is used to track side effects. + */ + static async outputFixes(results) { + if (!Array.isArray(results)) { + throw new Error("'results' must be an array"); + } + + await Promise.all( + results + .filter(result => { + if (typeof result !== "object" || result === null) { + throw new Error("'results' must include only objects"); + } + return ( + typeof result.output === "string" && + path.isAbsolute(result.filePath) + ); + }) + .map(r => writeFile(r.filePath, r.output)), + ); + } + + /** + * Returns results that only contains errors. + * @param {LintResult[]} results The results to filter. + * @returns {LintResult[]} The filtered results. + */ + static getErrorResults(results) { + return CLIEngine.getErrorResults(results); + } + + /** + * Returns meta objects for each rule represented in the lint results. + * @param {LintResult[]} results The results to fetch rules meta for. + * @returns {Object} A mapping of ruleIds to rule meta objects. + */ + getRulesMetaForResults(results) { + const resultRuleIds = new Set(); + + // first gather all ruleIds from all results + + for (const result of results) { + for (const { ruleId } of result.messages) { + resultRuleIds.add(ruleId); + } + for (const { ruleId } of result.suppressedMessages) { + resultRuleIds.add(ruleId); + } + } + + // create a map of all rules in the results + + const { cliEngine } = privateMembersMap.get(this); + const rules = cliEngine.getRules(); + const resultRules = new Map(); + + for (const [ruleId, rule] of rules) { + if (resultRuleIds.has(ruleId)) { + resultRules.set(ruleId, rule); + } + } + + return createRulesMeta(resultRules); + } + + /* eslint-disable no-unused-vars, class-methods-use-this -- leaving for compatibility with ESLint#hasFlag */ + /** + * Indicates if the given feature flag is enabled for this instance. For this + * class, this always returns `false` because it does not support feature flags. + * @param {string} flag The feature flag to check. + * @returns {boolean} Always false. + */ + hasFlag(flag) { + return false; + } + /* eslint-enable no-unused-vars, class-methods-use-this -- reenable rules for the rest of the file */ + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string[]} patterns An array of file and directory names. + * @returns {Promise} The results of linting the file patterns given. + */ + async lintFiles(patterns) { + const { cliEngine, options } = privateMembersMap.get(this); + + if ( + options.passOnNoPatterns && + (patterns === "" || + (Array.isArray(patterns) && patterns.length === 0)) + ) { + return []; + } + + if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) { + throw new Error( + "'patterns' must be a non-empty string or an array of non-empty strings", + ); + } + + return processCLIEngineLintReport( + cliEngine, + cliEngine.executeOnFiles(patterns), + ); + } + + /** + * Executes the current configuration on text. + * @param {string} code A string of JavaScript code to lint. + * @param {Object} [options] The options. + * @param {string} [options.filePath] The path to the file of the source code. + * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path. + * @returns {Promise} The results of linting the string of code given. + */ + async lintText(code, options = {}) { + if (typeof code !== "string") { + throw new Error("'code' must be a string"); + } + if (typeof options !== "object") { + throw new Error("'options' must be an object, null, or undefined"); + } + const { + filePath, + warnIgnored = false, + ...unknownOptions + } = options || {}; + + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length > 0) { + throw new Error( + `'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`, + ); + } + + if (filePath !== void 0 && !isNonEmptyString(filePath)) { + throw new Error( + "'options.filePath' must be a non-empty string or undefined", + ); + } + if (typeof warnIgnored !== "boolean") { + throw new Error( + "'options.warnIgnored' must be a boolean or undefined", + ); + } + + const { cliEngine } = privateMembersMap.get(this); + + return processCLIEngineLintReport( + cliEngine, + cliEngine.executeOnText(code, filePath, warnIgnored), + ); + } + + /** + * Returns the formatter representing the given formatter name. + * @param {string} [name] The name of the formatter to load. + * The following values are allowed: + * - `undefined` ... Load `stylish` builtin formatter. + * - A builtin formatter name ... Load the builtin formatter. + * - A third-party formatter name: + * - `foo` → `eslint-formatter-foo` + * - `@foo` → `@foo/eslint-formatter` + * - `@foo/bar` → `@foo/eslint-formatter-bar` + * - A file path ... Load the file. + * @returns {Promise} A promise resolving to the formatter object. + * This promise will be rejected if the given formatter was not found or not + * a function. + */ + async loadFormatter(name = "stylish") { + if (typeof name !== "string") { + throw new Error("'name' must be a string"); + } + + const { cliEngine, options } = privateMembersMap.get(this); + const formatter = cliEngine.getFormatter(name); + + if (typeof formatter !== "function") { + throw new Error( + `Formatter must be a function, but got a ${typeof formatter}.`, + ); + } + + return { + /** + * The main formatter method. + * @param {LintResult[]} results The lint results to format. + * @param {ResultsMeta} resultsMeta Warning count and max threshold. + * @returns {string | Promise} The formatted lint results. + */ + format(results, resultsMeta) { + let rulesMeta = null; + + results.sort(compareResultsByFilePath); + + return formatter(results, { + ...resultsMeta, + get cwd() { + return options.cwd; + }, + get rulesMeta() { + if (!rulesMeta) { + rulesMeta = createRulesMeta(cliEngine.getRules()); + } + + return rulesMeta; + }, + }); + }, + }; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file to retrieve a config object for. + * @returns {Promise} A configuration object for the file. + */ + async calculateConfigForFile(filePath) { + if (!isNonEmptyString(filePath)) { + throw new Error("'filePath' must be a non-empty string"); + } + const { cliEngine } = privateMembersMap.get(this); + + return cliEngine.getConfigForFile(filePath); + } + + /** + * Checks if a given path is ignored by ESLint. + * @param {string} filePath The path of the file to check. + * @returns {Promise} Whether or not the given path is ignored. + */ + async isPathIgnored(filePath) { + if (!isNonEmptyString(filePath)) { + throw new Error("'filePath' must be a non-empty string"); + } + const { cliEngine } = privateMembersMap.get(this); + + return cliEngine.isPathIgnored(filePath); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + LegacyESLint, + + /** + * Get the private class members of a given ESLint instance for tests. + * @param {ESLint} instance The ESLint instance to get. + * @returns {ESLintPrivateMembers} The instance's private class members. + */ + getESLintPrivateMembers(instance) { + return privateMembersMap.get(instance); + }, +}; diff --git a/node_modules/eslint/lib/languages/js/index.js b/node_modules/eslint/lib/languages/js/index.js new file mode 100644 index 00000000..a6bf0d7f --- /dev/null +++ b/node_modules/eslint/lib/languages/js/index.js @@ -0,0 +1,336 @@ +/** + * @fileoverview JavaScript Language Object + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { SourceCode } = require("./source-code"); +const createDebug = require("debug"); +const astUtils = require("../../shared/ast-utils"); +const espree = require("espree"); +const eslintScope = require("eslint-scope"); +const evk = require("eslint-visitor-keys"); +const { validateLanguageOptions } = require("./validate-language-options"); +const { LATEST_ECMA_VERSION } = require("../../../conf/ecma-version"); + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").File} File */ +/** @typedef {import("@eslint/core").Language} Language */ +/** @typedef {import("@eslint/core").OkParseResult} OkParseResult */ +/** @typedef {import("../../types").Linter.LanguageOptions} JSLanguageOptions */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const debug = createDebug("eslint:languages:js"); +const DEFAULT_ECMA_VERSION = 5; +const parserSymbol = Symbol.for("eslint.RuleTester.parser"); + +/** + * Analyze scope of the given AST. + * @param {ASTNode} ast The `Program` node to analyze. + * @param {JSLanguageOptions} languageOptions The parser options. + * @param {Record} visitorKeys The visitor keys. + * @returns {ScopeManager} The analysis result. + */ +function analyzeScope(ast, languageOptions, visitorKeys) { + const parserOptions = languageOptions.parserOptions; + const ecmaFeatures = parserOptions.ecmaFeatures || {}; + const ecmaVersion = languageOptions.ecmaVersion || DEFAULT_ECMA_VERSION; + + return eslintScope.analyze(ast, { + ignoreEval: true, + nodejsScope: ecmaFeatures.globalReturn, + impliedStrict: ecmaFeatures.impliedStrict, + ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 6, + sourceType: languageOptions.sourceType || "script", + childVisitorKeys: visitorKeys || evk.KEYS, + fallback: evk.getKeys, + }); +} + +/** + * Determines if a given object is Espree. + * @param {Object} parser The parser to check. + * @returns {boolean} True if the parser is Espree or false if not. + */ +function isEspree(parser) { + return !!(parser === espree || parser[parserSymbol] === espree); +} + +/** + * Normalize ECMAScript version from the initial config into languageOptions (year) + * format. + * @param {any} [ecmaVersion] ECMAScript version from the initial config + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersionForLanguageOptions(ecmaVersion) { + switch (ecmaVersion) { + case 3: + return 3; + + // void 0 = no ecmaVersion specified so use the default + case 5: + case void 0: + return 5; + + default: + if (typeof ecmaVersion === "number") { + return ecmaVersion >= 2015 ? ecmaVersion : ecmaVersion + 2009; + } + } + + /* + * We default to the latest supported ecmaVersion for everything else. + * Remember, this is for languageOptions.ecmaVersion, which sets the version + * that is used for a number of processes inside of ESLint. It's normally + * safe to assume people want the latest unless otherwise specified. + */ + return LATEST_ECMA_VERSION; +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * @type {Language} + */ +module.exports = { + fileType: "text", + lineStart: 1, + columnStart: 0, + nodeTypeKey: "type", + visitorKeys: evk.KEYS, + + defaultLanguageOptions: { + sourceType: "module", + ecmaVersion: "latest", + parser: espree, + parserOptions: {}, + }, + + validateLanguageOptions, + + /** + * Normalizes the language options. + * @param {Object} languageOptions The language options to normalize. + * @returns {Object} The normalized language options. + */ + normalizeLanguageOptions(languageOptions) { + languageOptions.ecmaVersion = normalizeEcmaVersionForLanguageOptions( + languageOptions.ecmaVersion, + ); + + // Espree expects this information to be passed in + if (isEspree(languageOptions.parser)) { + const parserOptions = languageOptions.parserOptions; + + if (languageOptions.sourceType) { + parserOptions.sourceType = languageOptions.sourceType; + + if ( + parserOptions.sourceType === "module" && + parserOptions.ecmaFeatures && + parserOptions.ecmaFeatures.globalReturn + ) { + parserOptions.ecmaFeatures.globalReturn = false; + } + } + } + + return languageOptions; + }, + + /** + * Determines if a given node matches a given selector class. + * @param {string} className The class name to check. + * @param {ASTNode} node The node to check. + * @param {Array} ancestry The ancestry of the node. + * @returns {boolean} True if there's a match, false if not. + * @throws {Error} When an unknown class name is passed. + */ + matchesSelectorClass(className, node, ancestry) { + /* + * Copyright (c) 2013, Joel Feenstra + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the ESQuery nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL JOEL FEENSTRA BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + switch (className.toLowerCase()) { + case "statement": + if (node.type.slice(-9) === "Statement") { + return true; + } + + // fallthrough: interface Declaration <: Statement { } + + case "declaration": + return node.type.slice(-11) === "Declaration"; + + case "pattern": + if (node.type.slice(-7) === "Pattern") { + return true; + } + + // fallthrough: interface Expression <: Node, Pattern { } + + case "expression": + return ( + node.type.slice(-10) === "Expression" || + node.type.slice(-7) === "Literal" || + (node.type === "Identifier" && + (ancestry.length === 0 || + ancestry[0].type !== "MetaProperty")) || + node.type === "MetaProperty" + ); + + case "function": + return ( + node.type === "FunctionDeclaration" || + node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression" + ); + + default: + throw new Error(`Unknown class name: ${className}`); + } + }, + + /** + * Parses the given file into an AST. + * @param {File} file The virtual file to parse. + * @param {Object} options Additional options passed from ESLint. + * @param {JSLanguageOptions} options.languageOptions The language options. + * @returns {Object} The result of parsing. + */ + parse(file, { languageOptions }) { + // Note: BOM already removed + const { body: text, path: filePath } = file; + const textToParse = text.replace( + astUtils.shebangPattern, + (match, captured) => `//${captured}`, + ); + const { ecmaVersion, sourceType, parser } = languageOptions; + const parserOptions = Object.assign( + { ecmaVersion, sourceType }, + languageOptions.parserOptions, + { + loc: true, + range: true, + raw: true, + tokens: true, + comment: true, + eslintVisitorKeys: true, + eslintScopeManager: true, + filePath, + }, + ); + + /* + * Check for parsing errors first. If there's a parsing error, nothing + * else can happen. However, a parsing error does not throw an error + * from this method - it's just considered a fatal error message, a + * problem that ESLint identified just like any other. + */ + try { + debug("Parsing:", filePath); + const parseResult = + typeof parser.parseForESLint === "function" + ? parser.parseForESLint(textToParse, parserOptions) + : { ast: parser.parse(textToParse, parserOptions) }; + + debug("Parsing successful:", filePath); + + const { + ast, + services: parserServices = {}, + visitorKeys = evk.KEYS, + scopeManager, + } = parseResult; + + return { + ok: true, + ast, + parserServices, + visitorKeys, + scopeManager, + }; + } catch (ex) { + // If the message includes a leading line number, strip it: + const message = ex.message.replace(/^line \d+:/iu, "").trim(); + + debug("%s\n%s", message, ex.stack); + + return { + ok: false, + errors: [ + { + message, + line: ex.lineNumber, + column: ex.column, + }, + ], + }; + } + }, + + /** + * Creates a new `SourceCode` object from the given information. + * @param {File} file The virtual file to create a `SourceCode` object from. + * @param {OkParseResult} parseResult The result returned from `parse()`. + * @param {Object} options Additional options passed from ESLint. + * @param {JSLanguageOptions} options.languageOptions The language options. + * @returns {SourceCode} The new `SourceCode` object. + */ + createSourceCode(file, parseResult, { languageOptions }) { + const { body: text, path: filePath, bom: hasBOM } = file; + const { ast, parserServices, visitorKeys } = parseResult; + + debug("Scope analysis:", filePath); + const scopeManager = + parseResult.scopeManager || + analyzeScope(ast, languageOptions, visitorKeys); + + debug("Scope analysis successful:", filePath); + + return new SourceCode({ + text, + ast, + hasBOM, + parserServices, + scopeManager, + visitorKeys, + }); + }, +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/index.js b/node_modules/eslint/lib/languages/js/source-code/index.js new file mode 100644 index 00000000..f4003e39 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/index.js @@ -0,0 +1,7 @@ +"use strict"; + +const SourceCode = require("./source-code"); + +module.exports = { + SourceCode, +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/source-code.js b/node_modules/eslint/lib/languages/js/source-code/source-code.js new file mode 100644 index 00000000..159f3913 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/source-code.js @@ -0,0 +1,1358 @@ +/** + * @fileoverview Abstraction of JavaScript source code. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { isCommentToken } = require("@eslint-community/eslint-utils"), + TokenStore = require("./token-store"), + astUtils = require("../../../shared/ast-utils"), + Traverser = require("../../../shared/traverser"), + globals = require("../../../../conf/globals"), + { directivesPattern } = require("../../../shared/directives"), + CodePathAnalyzer = require("../../../linter/code-path-analysis/code-path-analyzer"), + { + ConfigCommentParser, + VisitNodeStep, + CallMethodStep, + Directive, + } = require("@eslint/plugin-kit"), + eslintScope = require("eslint-scope"); + +//------------------------------------------------------------------------------ +// Type Definitions +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("@eslint/core").SourceCode} ISourceCode */ +/** @typedef {import("@eslint/core").Directive} IDirective */ +/** @typedef {import("@eslint/core").TraversalStep} ITraversalStep */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +const commentParser = new ConfigCommentParser(); + +/** + * Validates that the given AST has the required information. + * @param {ASTNode} ast The Program node of the AST to check. + * @throws {TypeError} If the AST doesn't contain the correct information. + * @returns {void} + * @private + */ +function validate(ast) { + if (!ast) { + throw new TypeError(`Unexpected empty AST. (${ast})`); + } + + if (!ast.tokens) { + throw new TypeError("AST is missing the tokens array."); + } + + if (!ast.comments) { + throw new TypeError("AST is missing the comments array."); + } + + if (!ast.loc) { + throw new TypeError("AST is missing location information."); + } + + if (!ast.range) { + throw new TypeError("AST is missing range information"); + } +} + +/** + * Retrieves globals for the given ecmaVersion. + * @param {number} ecmaVersion The version to retrieve globals for. + * @returns {Object} The globals for the given ecmaVersion. + */ +function getGlobalsForEcmaVersion(ecmaVersion) { + switch (ecmaVersion) { + case 3: + return globals.es3; + + case 5: + return globals.es5; + + default: + if (ecmaVersion < 2015) { + return globals[`es${ecmaVersion + 2009}`]; + } + + return globals[`es${ecmaVersion}`]; + } +} + +/** + * Check to see if its a ES6 export declaration. + * @param {ASTNode} astNode An AST node. + * @returns {boolean} whether the given node represents an export declaration. + * @private + */ +function looksLikeExport(astNode) { + return ( + astNode.type === "ExportDefaultDeclaration" || + astNode.type === "ExportNamedDeclaration" || + astNode.type === "ExportAllDeclaration" || + astNode.type === "ExportSpecifier" + ); +} + +/** + * Merges two sorted lists into a larger sorted list in O(n) time. + * @param {Token[]} tokens The list of tokens. + * @param {Token[]} comments The list of comments. + * @returns {Token[]} A sorted list of tokens and comments. + * @private + */ +function sortedMerge(tokens, comments) { + const result = []; + let tokenIndex = 0; + let commentIndex = 0; + + while (tokenIndex < tokens.length || commentIndex < comments.length) { + if ( + commentIndex >= comments.length || + (tokenIndex < tokens.length && + tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) + ) { + result.push(tokens[tokenIndex++]); + } else { + result.push(comments[commentIndex++]); + } + } + + return result; +} + +/** + * Normalizes a value for a global in a config + * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in + * a global directive comment + * @returns {("readonly"|"writable"|"off")} The value normalized as a string + * @throws {Error} if global value is invalid + */ +function normalizeConfigGlobal(configuredValue) { + switch (configuredValue) { + case "off": + return "off"; + + case true: + case "true": + case "writeable": + case "writable": + return "writable"; + + case null: + case false: + case "false": + case "readable": + case "readonly": + return "readonly"; + + default: + throw new Error( + `'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`, + ); + } +} + +/** + * Determines if two nodes or tokens overlap. + * @param {ASTNode|Token} first The first node or token to check. + * @param {ASTNode|Token} second The second node or token to check. + * @returns {boolean} True if the two nodes or tokens overlap. + * @private + */ +function nodesOrTokensOverlap(first, second) { + return ( + (first.range[0] <= second.range[0] && + first.range[1] >= second.range[0]) || + (second.range[0] <= first.range[0] && second.range[1] >= first.range[0]) + ); +} + +/** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * @param {SourceCode} sourceCode The source code object. + * @param {ASTNode|Token} first The first node or token to check between. + * @param {ASTNode|Token} second The second node or token to check between. + * @param {boolean} checkInsideOfJSXText If `true` is present, check inside of JSXText tokens for backward compatibility. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @public + */ +function isSpaceBetween(sourceCode, first, second, checkInsideOfJSXText) { + if (nodesOrTokensOverlap(first, second)) { + return false; + } + + const [startingNodeOrToken, endingNodeOrToken] = + first.range[1] <= second.range[0] ? [first, second] : [second, first]; + const firstToken = + sourceCode.getLastToken(startingNodeOrToken) || startingNodeOrToken; + const finalToken = + sourceCode.getFirstToken(endingNodeOrToken) || endingNodeOrToken; + let currentToken = firstToken; + + while (currentToken !== finalToken) { + const nextToken = sourceCode.getTokenAfter(currentToken, { + includeComments: true, + }); + + if ( + currentToken.range[1] !== nextToken.range[0] || + /* + * For backward compatibility, check spaces in JSXText. + * https://github.com/eslint/eslint/issues/12614 + */ + (checkInsideOfJSXText && + nextToken !== finalToken && + nextToken.type === "JSXText" && + /\s/u.test(nextToken.value)) + ) { + return true; + } + + currentToken = nextToken; + } + + return false; +} + +/** + * Performs binary search to find the line number containing a given character index. + * Returns the lower bound - the index of the first element greater than the target. + * **Please note that the `lineStartIndices` should be sorted in ascending order**. + * - Time Complexity: O(log n) - Significantly faster than linear search for large files. + * @param {number[]} lineStartIndices Sorted array of line start indices. + * @param {number} target The character index to find the line number for. + * @returns {number} The 1-based line number for the target index. + * @private + */ +function findLineNumberBinarySearch(lineStartIndices, target) { + let low = 0; + let high = lineStartIndices.length; + + while (low < high) { + const mid = ((low + high) / 2) | 0; // Use bitwise OR to floor the division + + if (target < lineStartIndices[mid]) { + high = mid; + } else { + low = mid + 1; + } + } + + return low; +} + +//----------------------------------------------------------------------------- +// Directive Comments +//----------------------------------------------------------------------------- + +/** + * Ensures that variables representing built-in properties of the Global Object, + * and any globals declared by special block comments, are present in the global + * scope. + * @param {Scope} globalScope The global scope. + * @param {Object|undefined} configGlobals The globals declared in configuration + * @param {Object|undefined} inlineGlobals The globals declared in the source code + * @returns {void} + */ +function addDeclaredGlobals( + globalScope, + configGlobals = {}, + inlineGlobals = {}, +) { + // Define configured global variables. + for (const id of new Set([ + ...Object.keys(configGlobals), + ...Object.keys(inlineGlobals), + ])) { + /* + * `normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would + * typically be caught when validating a config anyway (validity for inline global comments is checked separately). + */ + const configValue = + configGlobals[id] === void 0 + ? void 0 + : normalizeConfigGlobal(configGlobals[id]); + const commentValue = inlineGlobals[id] && inlineGlobals[id].value; + const value = commentValue || configValue; + const sourceComments = inlineGlobals[id] && inlineGlobals[id].comments; + + if (value === "off") { + continue; + } + + let variable = globalScope.set.get(id); + + if (!variable) { + variable = new eslintScope.Variable(id, globalScope); + + globalScope.variables.push(variable); + globalScope.set.set(id, variable); + } + + variable.eslintImplicitGlobalSetting = configValue; + variable.eslintExplicitGlobal = sourceComments !== void 0; + variable.eslintExplicitGlobalComments = sourceComments; + variable.writeable = value === "writable"; + } + + /* + * "through" contains all references which definitions cannot be found. + * Since we augment the global scope using configuration, we need to update + * references and remove the ones that were added by configuration. + */ + globalScope.through = globalScope.through.filter(reference => { + const name = reference.identifier.name; + const variable = globalScope.set.get(name); + + if (variable) { + /* + * Links the variable and the reference. + * And this reference is removed from `Scope#through`. + */ + reference.resolved = variable; + variable.references.push(reference); + + return false; + } + + return true; + }); + + /* + * "implicit" contains information about implicit global variables (those created + * implicitly by assigning values to undeclared variables in non-strict code). + * Since we augment the global scope using configuration, we need to remove + * the ones that were added by configuration, as they are either built-in + * or declared elsewhere, therefore not implicit. + * Since the "implicit" property was not documented, first we'll check if it exists + * because it's possible that not all custom scope managers create this property. + * If it exists, we assume it has properties `variables` and `set`. Property + * `left` is considered optional (for example, typescript-eslint's scope manage + * has this property named `leftToBeResolved`). + */ + const { implicit } = globalScope; + if (typeof implicit === "object" && implicit !== null) { + implicit.variables = implicit.variables.filter(variable => { + const name = variable.name; + if (globalScope.set.has(name)) { + implicit.set.delete(name); + return false; + } + return true; + }); + + if (implicit.left) { + implicit.left = implicit.left.filter( + reference => !globalScope.set.has(reference.identifier.name), + ); + } + } +} + +/** + * Sets the given variable names as exported so they won't be triggered by + * the `no-unused-vars` rule. + * @param {eslint.Scope} globalScope The global scope to define exports in. + * @param {Record} variables An object whose keys are the variable + * names to export. + * @returns {void} + */ +function markExportedVariables(globalScope, variables) { + Object.keys(variables).forEach(name => { + const variable = globalScope.set.get(name); + + if (variable) { + variable.eslintUsed = true; + variable.eslintExported = true; + } + }); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +const caches = Symbol("caches"); + +/** + * Represents parsed source code. + * @implements {ISourceCode} + */ +class SourceCode extends TokenStore { + /** + * The cache of steps that were taken while traversing the source code. + * @type {Array} + */ + #steps; + + /** + * Creates a new instance. + * @param {string|Object} textOrConfig The source code text or config object. + * @param {string} textOrConfig.text The source code text. + * @param {ASTNode} textOrConfig.ast The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. + * @param {boolean} textOrConfig.hasBOM Indicates if the text has a Unicode BOM. + * @param {Object|null} textOrConfig.parserServices The parser services. + * @param {ScopeManager|null} textOrConfig.scopeManager The scope of this source code. + * @param {Object|null} textOrConfig.visitorKeys The visitor keys to traverse AST. + * @param {ASTNode} [astIfNoConfig] The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. + */ + constructor(textOrConfig, astIfNoConfig) { + let text, hasBOM, ast, parserServices, scopeManager, visitorKeys; + + // Process overloading of arguments + if (typeof textOrConfig === "string") { + text = textOrConfig; + ast = astIfNoConfig; + hasBOM = false; + } else if (typeof textOrConfig === "object" && textOrConfig !== null) { + text = textOrConfig.text; + ast = textOrConfig.ast; + hasBOM = textOrConfig.hasBOM; + parserServices = textOrConfig.parserServices; + scopeManager = textOrConfig.scopeManager; + visitorKeys = textOrConfig.visitorKeys; + } + + validate(ast); + super(ast.tokens, ast.comments); + + /** + * General purpose caching for the class. + */ + this[caches] = new Map([ + ["scopes", new WeakMap()], + ["vars", new Map()], + ["configNodes", void 0], + ["isGlobalReference", new WeakMap()], + ]); + + /** + * Indicates if the AST is ESTree compatible. + * @type {boolean} + */ + this.isESTree = ast.type === "Program"; + + /* + * Backwards compatibility for BOM handling. + * + * The `hasBOM` property has been available on the `SourceCode` object + * for a long time and is used to indicate if the source contains a BOM. + * The linter strips the BOM and just passes the `hasBOM` property to the + * `SourceCode` constructor to make it easier for languages to not deal with + * the BOM. + * + * However, the text passed in to the `SourceCode` constructor might still + * have a BOM if the constructor is called outside of the linter, so we still + * need to check for the BOM in the text. + */ + const textHasBOM = text.charCodeAt(0) === 0xfeff; + + /** + * The flag to indicate that the source code has Unicode BOM. + * @type {boolean} + */ + this.hasBOM = textHasBOM || !!hasBOM; + + /** + * The original text source code. + * BOM was stripped from this text. + * @type {string} + */ + this.text = textHasBOM ? text.slice(1) : text; + + /** + * The parsed AST for the source code. + * @type {ASTNode} + */ + this.ast = ast; + + /** + * The parser services of this source code. + * @type {Object} + */ + this.parserServices = parserServices || {}; + + /** + * The scope of this source code. + * @type {ScopeManager|null} + */ + this.scopeManager = scopeManager || null; + + /** + * The visitor keys to traverse AST. + * @type {Object} + */ + this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS; + + // Check the source text for the presence of a shebang since it is parsed as a standard line comment. + const shebangMatched = this.text.match(astUtils.shebangPattern); + const hasShebang = + shebangMatched && + ast.comments.length && + ast.comments[0].value === shebangMatched[1]; + + if (hasShebang) { + ast.comments[0].type = "Shebang"; + } + + this.tokensAndComments = sortedMerge(ast.tokens, ast.comments); + + /** + * The source code split into lines according to ECMA-262 specification. + * This is done to avoid each rule needing to do so separately. + * @type {string[]} + */ + this.lines = []; + + /** + * @type {number[]} + */ + this.lineStartIndices = [0]; + + const lineEndingPattern = astUtils.createGlobalLinebreakMatcher(); + let match; + + /* + * Previously, this was implemented using a regex that + * matched a sequence of non-linebreak characters followed by a + * linebreak, then adding the lengths of the matches. However, + * this caused a catastrophic backtracking issue when the end + * of a file contained a large number of non-newline characters. + * To avoid this, the current implementation just matches newlines + * and uses match.index to get the correct line start indices. + */ + while ((match = lineEndingPattern.exec(this.text))) { + this.lines.push( + this.text.slice(this.lineStartIndices.at(-1), match.index), + ); + this.lineStartIndices.push(match.index + match[0].length); + } + this.lines.push(this.text.slice(this.lineStartIndices.at(-1))); + + // don't allow further modification of this object + Object.freeze(this); + Object.freeze(this.lines); + } + + /** + * Split the source code into multiple lines based on the line delimiters. + * @param {string} text Source code as a string. + * @returns {string[]} Array of source code lines. + * @public + */ + static splitLines(text) { + return text.split(astUtils.createGlobalLinebreakMatcher()); + } + + /** + * Gets the source code for the given node. + * @param {ASTNode} [node] The AST node to get the text for. + * @param {number} [beforeCount] The number of characters before the node to retrieve. + * @param {number} [afterCount] The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + * @public + */ + getText(node, beforeCount, afterCount) { + if (node) { + return this.text.slice( + Math.max(node.range[0] - (beforeCount || 0), 0), + node.range[1] + (afterCount || 0), + ); + } + return this.text; + } + + /** + * Gets the entire source text split into an array of lines. + * @returns {string[]} The source text as an array of lines. + * @public + */ + getLines() { + return this.lines; + } + + /** + * Retrieves an array containing all comments in the source code. + * @returns {ASTNode[]} An array of comment nodes. + * @public + */ + getAllComments() { + return this.ast.comments; + } + + /** + * Retrieves the JSDoc comment for a given node. + * @param {ASTNode} node The AST node to get the comment for. + * @returns {Token|null} The Block comment token containing the JSDoc comment + * for the given node or null if not found. + * @public + * @deprecated + */ + getJSDocComment(node) { + /** + * Checks for the presence of a JSDoc comment for the given node and returns it. + * @param {ASTNode} astNode The AST node to get the comment for. + * @returns {Token|null} The Block comment token containing the JSDoc comment + * for the given node or null if not found. + * @private + */ + const findJSDocComment = astNode => { + const tokenBefore = this.getTokenBefore(astNode, { + includeComments: true, + }); + + if ( + tokenBefore && + isCommentToken(tokenBefore) && + tokenBefore.type === "Block" && + tokenBefore.value.charAt(0) === "*" && + astNode.loc.start.line - tokenBefore.loc.end.line <= 1 + ) { + return tokenBefore; + } + + return null; + }; + let parent = node.parent; + + switch (node.type) { + case "ClassDeclaration": + case "FunctionDeclaration": + return findJSDocComment( + looksLikeExport(parent) ? parent : node, + ); + + case "ClassExpression": + return findJSDocComment(parent.parent); + + case "ArrowFunctionExpression": + case "FunctionExpression": + if ( + parent.type !== "CallExpression" && + parent.type !== "NewExpression" + ) { + while ( + !this.getCommentsBefore(parent).length && + !/Function/u.test(parent.type) && + parent.type !== "MethodDefinition" && + parent.type !== "Property" + ) { + parent = parent.parent; + + if (!parent) { + break; + } + } + + if ( + parent && + parent.type !== "FunctionDeclaration" && + parent.type !== "Program" + ) { + return findJSDocComment(parent); + } + } + + return findJSDocComment(node); + + // falls through + default: + return null; + } + } + + /** + * Gets the deepest node containing a range index. + * @param {number} index Range index of the desired node. + * @returns {ASTNode} The node if found or null if not found. + * @public + */ + getNodeByRangeIndex(index) { + let result = null; + + Traverser.traverse(this.ast, { + visitorKeys: this.visitorKeys, + enter(node) { + if (node.range[0] <= index && index < node.range[1]) { + result = node; + } else { + this.skip(); + } + }, + leave(node) { + if (node === result) { + this.break(); + } + }, + }); + + return result; + } + + /** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * @param {ASTNode|Token} first The first node or token to check between. + * @param {ASTNode|Token} second The second node or token to check between. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @public + */ + isSpaceBetween(first, second) { + return isSpaceBetween(this, first, second, false); + } + + /** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * For backward compatibility, this method returns true if there are + * `JSXText` tokens that contain whitespaces between the two. + * @param {ASTNode|Token} first The first node or token to check between. + * @param {ASTNode|Token} second The second node or token to check between. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @deprecated in favor of isSpaceBetween(). + * @public + */ + isSpaceBetweenTokens(first, second) { + return isSpaceBetween(this, first, second, true); + } + + /** + * Converts a source text index into a (line, column) pair. + * @param {number} index The index of a character in a file. + * @throws {TypeError|RangeError} If non-numeric index or index out of range. + * @returns {{line: number, column: number}} A {line, column} location object with 1-indexed line and 0-indexed column. + * @public + */ + getLocFromIndex(index) { + if (typeof index !== "number") { + throw new TypeError("Expected `index` to be a number."); + } + + if (index < 0 || index > this.text.length) { + throw new RangeError( + `Index out of range (requested index ${index}, but source text has length ${this.text.length}).`, + ); + } + + /* + * For an argument of this.text.length, return the location one "spot" past the last character + * of the file. If the last character is a linebreak, the location will be column 0 of the next + * line; otherwise, the location will be in the next column on the same line. + * + * See getIndexFromLoc for the motivation for this special case. + */ + if (index === this.text.length) { + return { + line: this.lines.length, + column: this.lines.at(-1).length, + }; + } + + /* + * To figure out which line index is on, determine the last place at which index could + * be inserted into lineStartIndices to keep the list sorted. + */ + const lineNumber = + index >= this.lineStartIndices.at(-1) + ? this.lineStartIndices.length + : findLineNumberBinarySearch(this.lineStartIndices, index); + + return { + line: lineNumber, + column: index - this.lineStartIndices[lineNumber - 1], + }; + } + + /** + * Converts a (line, column) pair into a range index. + * @param {Object} loc A line/column location + * @param {number} loc.line The line number of the location (1-indexed) + * @param {number} loc.column The column number of the location (0-indexed) + * @throws {TypeError|RangeError} If `loc` is not an object with a numeric + * `line` and `column`, if the `line` is less than or equal to zero or + * the line or column is out of the expected range. + * @returns {number} The range index of the location in the file. + * @public + */ + getIndexFromLoc(loc) { + if ( + typeof loc !== "object" || + typeof loc.line !== "number" || + typeof loc.column !== "number" + ) { + throw new TypeError( + "Expected `loc` to be an object with numeric `line` and `column` properties.", + ); + } + + if (loc.line <= 0) { + throw new RangeError( + `Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`, + ); + } + + if (loc.line > this.lineStartIndices.length) { + throw new RangeError( + `Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`, + ); + } + + const lineStartIndex = this.lineStartIndices[loc.line - 1]; + const lineEndIndex = + loc.line === this.lineStartIndices.length + ? this.text.length + : this.lineStartIndices[loc.line]; + const positionIndex = lineStartIndex + loc.column; + + /* + * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of + * the given line, provided that the line number is valid element of this.lines. Since the + * last element of this.lines is an empty string for files with trailing newlines, add a + * special case where getting the index for the first location after the end of the file + * will return the length of the file, rather than throwing an error. This allows rules to + * use getIndexFromLoc consistently without worrying about edge cases at the end of a file. + */ + if ( + (loc.line === this.lineStartIndices.length && + positionIndex > lineEndIndex) || + (loc.line < this.lineStartIndices.length && + positionIndex >= lineEndIndex) + ) { + throw new RangeError( + `Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`, + ); + } + + return positionIndex; + } + + /** + * Gets the scope for the given node + * @param {ASTNode} currentNode The node to get the scope of + * @returns {Scope} The scope information for this node + * @throws {TypeError} If the `currentNode` argument is missing. + */ + getScope(currentNode) { + if (!currentNode) { + throw new TypeError("Missing required argument: node."); + } + + // check cache first + const cache = this[caches].get("scopes"); + const cachedScope = cache.get(currentNode); + + if (cachedScope) { + return cachedScope; + } + + // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope. + const inner = currentNode.type !== "Program"; + + for (let node = currentNode; node; node = node.parent) { + const scope = this.scopeManager.acquire(node, inner); + + if (scope) { + if (scope.type === "function-expression-name") { + cache.set(currentNode, scope.childScopes[0]); + return scope.childScopes[0]; + } + + cache.set(currentNode, scope); + return scope; + } + } + + cache.set(currentNode, this.scopeManager.scopes[0]); + return this.scopeManager.scopes[0]; + } + + /** + * Get the variables that `node` defines. + * This is a convenience method that passes through + * to the same method on the `scopeManager`. + * @param {ASTNode} node The node for which the variables are obtained. + * @returns {Array} An array of variable nodes representing + * the variables that `node` defines. + */ + getDeclaredVariables(node) { + return this.scopeManager.getDeclaredVariables(node); + } + + /* eslint-disable class-methods-use-this -- node is owned by SourceCode */ + /** + * Gets all the ancestors of a given node + * @param {ASTNode} node The node + * @returns {Array} All the ancestor nodes in the AST, not including the provided node, starting + * from the root node at index 0 and going inwards to the parent node. + * @throws {TypeError} When `node` is missing. + */ + getAncestors(node) { + if (!node) { + throw new TypeError("Missing required argument: node."); + } + + const ancestorsStartingAtParent = []; + + for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) { + ancestorsStartingAtParent.push(ancestor); + } + + return ancestorsStartingAtParent.reverse(); + } + + /** + * Determines whether the given identifier node is a reference to a global variable. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} True if the identifier is a reference to a global variable. + */ + isGlobalReference(node) { + if (!node) { + throw new TypeError("Missing required argument: node."); + } + + const cache = this[caches].get("isGlobalReference"); + + if (cache.has(node)) { + return cache.get(node); + } + + if (node.type !== "Identifier") { + cache.set(node, false); + return false; + } + + const variable = this.scopeManager.scopes[0].set.get(node.name); + + if (!variable || variable.defs.length > 0) { + cache.set(node, false); + return false; + } + + const result = variable.references.some( + ({ identifier }) => identifier === node, + ); + cache.set(node, result); + return result; + } + + /** + * Returns the location of the given node or token. + * @param {ASTNode|Token} nodeOrToken The node or token to get the location of. + * @returns {SourceLocation} The location of the node or token. + */ + getLoc(nodeOrToken) { + return nodeOrToken.loc; + } + + /** + * Returns the range of the given node or token. + * @param {ASTNode|Token} nodeOrToken The node or token to get the range of. + * @returns {[number, number]} The range of the node or token. + */ + getRange(nodeOrToken) { + return nodeOrToken.range; + } + + /* eslint-enable class-methods-use-this -- node is owned by SourceCode */ + + /** + * Marks a variable as used in the current scope + * @param {string} name The name of the variable to mark as used. + * @param {ASTNode} [refNode] The closest node to the variable reference. + * @returns {boolean} True if the variable was found and marked as used, false if not. + */ + markVariableAsUsed(name, refNode = this.ast) { + const currentScope = this.getScope(refNode); + let initialScope = currentScope; + + /* + * When we are in an ESM or CommonJS module, we need to start searching + * from the top-level scope, not the global scope. For ESM the top-level + * scope is the module scope; for CommonJS the top-level scope is the + * outer function scope. + * + * Without this check, we might miss a variable declared with `var` at + * the top-level because it won't exist in the global scope. + */ + if ( + currentScope.type === "global" && + currentScope.childScopes.length > 0 && + // top-level scopes refer to a `Program` node + currentScope.childScopes[0].block === this.ast + ) { + initialScope = currentScope.childScopes[0]; + } + + for (let scope = initialScope; scope; scope = scope.upper) { + const variable = scope.variables.find( + scopeVar => scopeVar.name === name, + ); + + if (variable) { + variable.eslintUsed = true; + return true; + } + } + + return false; + } + + /** + * Returns an array of all inline configuration nodes found in the + * source code. + * @returns {Array} An array of all inline configuration nodes. + */ + getInlineConfigNodes() { + // check the cache first + let configNodes = this[caches].get("configNodes"); + + if (configNodes) { + return configNodes; + } + + // calculate fresh config nodes + configNodes = this.ast.comments.filter(comment => { + // shebang comments are never directives + if (comment.type === "Shebang") { + return false; + } + + const directive = commentParser.parseDirective(comment.value); + + if (!directive) { + return false; + } + + if (!directivesPattern.test(directive.label)) { + return false; + } + + // only certain comment types are supported as line comments + return ( + comment.type !== "Line" || + !!/^eslint-disable-(next-)?line$/u.test(directive.label) + ); + }); + + this[caches].set("configNodes", configNodes); + + return configNodes; + } + + /** + * Returns an all directive nodes that enable or disable rules along with any problems + * encountered while parsing the directives. + * @returns {{problems:Array,directives:Array}} Information + * that ESLint needs to further process the directives. + */ + getDisableDirectives() { + // check the cache first + const cachedDirectives = this[caches].get("disableDirectives"); + + if (cachedDirectives) { + return cachedDirectives; + } + + const problems = []; + const directives = []; + + this.getInlineConfigNodes().forEach(comment => { + // Step 1: Parse the directive + const { + label, + value, + justification: justificationPart, + } = commentParser.parseDirective(comment.value); + + // Step 2: Extract the directive value + const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test( + label, + ); + + if (comment.type === "Line" && !lineCommentSupported) { + return; + } + + // Step 3: Validate the directive does not span multiple lines + if ( + label === "eslint-disable-line" && + comment.loc.start.line !== comment.loc.end.line + ) { + const message = `${label} comment should not span multiple lines.`; + + problems.push({ + ruleId: null, + message, + loc: comment.loc, + }); + return; + } + + // Step 4: Extract the directive value and create the Directive object + switch (label) { + case "eslint-disable": + case "eslint-enable": + case "eslint-disable-next-line": + case "eslint-disable-line": { + const directiveType = label.slice("eslint-".length); + + directives.push( + new Directive({ + type: directiveType, + node: comment, + value, + justification: justificationPart, + }), + ); + } + + // no default + } + }); + + const result = { problems, directives }; + + this[caches].set("disableDirectives", result); + + return result; + } + + /** + * Applies language options sent in from the core. + * @param {Object} languageOptions The language options for this run. + * @returns {void} + */ + applyLanguageOptions(languageOptions) { + /* + * Add configured globals and language globals + * + * Using Object.assign instead of object spread for performance reasons + * https://github.com/eslint/eslint/issues/16302 + */ + const configGlobals = Object.assign( + Object.create(null), // https://github.com/eslint/eslint/issues/18363 + getGlobalsForEcmaVersion(languageOptions.ecmaVersion), + languageOptions.sourceType === "commonjs" + ? globals.commonjs + : void 0, + languageOptions.globals, + ); + const varsCache = this[caches].get("vars"); + + varsCache.set("configGlobals", configGlobals); + } + + /** + * Applies configuration found inside of the source code. This method is only + * called when ESLint is running with inline configuration allowed. + * @returns {{problems:Array,configs:{config:FlatConfigArray,loc:Location}}} Information + * that ESLint needs to further process the inline configuration. + */ + applyInlineConfig() { + const problems = []; + const configs = []; + const exportedVariables = {}; + const inlineGlobals = Object.create(null); + + this.getInlineConfigNodes().forEach(comment => { + const { label, value } = commentParser.parseDirective( + comment.value, + ); + + switch (label) { + case "exported": + Object.assign( + exportedVariables, + commentParser.parseListConfig(value), + ); + break; + + case "globals": + case "global": + for (const [id, idSetting] of Object.entries( + commentParser.parseStringConfig(value), + )) { + let normalizedValue; + + try { + normalizedValue = normalizeConfigGlobal(idSetting); + } catch (err) { + problems.push({ + ruleId: null, + loc: comment.loc, + message: err.message, + }); + continue; + } + + if (inlineGlobals[id]) { + inlineGlobals[id].comments.push(comment); + inlineGlobals[id].value = normalizedValue; + } else { + inlineGlobals[id] = { + comments: [comment], + value: normalizedValue, + }; + } + } + break; + + case "eslint": { + const parseResult = + commentParser.parseJSONLikeConfig(value); + + if (parseResult.ok) { + configs.push({ + config: { + rules: parseResult.config, + }, + loc: comment.loc, + }); + } else { + problems.push({ + ruleId: null, + loc: comment.loc, + message: parseResult.error.message, + }); + } + + break; + } + + // no default + } + }); + + // save all the new variables for later + const varsCache = this[caches].get("vars"); + + varsCache.set("inlineGlobals", inlineGlobals); + varsCache.set("exportedVariables", exportedVariables); + + return { + configs, + problems, + }; + } + + /** + * Called by ESLint core to indicate that it has finished providing + * information. We now add in all the missing variables and ensure that + * state-changing methods cannot be called by rules. + * @returns {void} + */ + finalize() { + const varsCache = this[caches].get("vars"); + const configGlobals = varsCache.get("configGlobals"); + const inlineGlobals = varsCache.get("inlineGlobals"); + const exportedVariables = varsCache.get("exportedVariables"); + const globalScope = this.scopeManager.scopes[0]; + + addDeclaredGlobals(globalScope, configGlobals, inlineGlobals); + + if (exportedVariables) { + markExportedVariables(globalScope, exportedVariables); + } + } + + /** + * Traverse the source code and return the steps that were taken. + * @returns {Array} The steps that were taken while traversing the source code. + */ + traverse() { + // Because the AST doesn't mutate, we can cache the steps + if (this.#steps) { + return this.#steps; + } + + const steps = (this.#steps = []); + + /* + * This logic works for any AST, not just ESTree. Because ESLint has allowed + * custom parsers to return any AST, we need to ensure that the traversal + * logic works for any AST. + */ + let analyzer = { + enterNode(node) { + steps.push( + new VisitNodeStep({ + target: node, + phase: 1, + args: [node, node.parent], + }), + ); + }, + leaveNode(node) { + steps.push( + new VisitNodeStep({ + target: node, + phase: 2, + args: [node, node.parent], + }), + ); + }, + emit(eventName, args) { + steps.push( + new CallMethodStep({ + target: eventName, + args, + }), + ); + }, + }; + + /* + * We do code path analysis for ESTree only. Code path analysis is not + * necessary for other ASTs, and it's also not possible to do for other + * ASTs because the necessary information is not available. + * + * Generally speaking, we can tell that the AST is an ESTree if it has a + * Program node at the top level. This is not a perfect heuristic, but it + * is good enough for now. + */ + if (this.isESTree) { + analyzer = new CodePathAnalyzer(analyzer); + } + + /* + * The actual AST traversal is done by the `Traverser` class. This class + * is responsible for walking the AST and calling the appropriate methods + * on the `analyzer` object, which is appropriate for the given AST. + */ + Traverser.traverse(this.ast, { + enter(node, parent) { + // save the parent node on a property for backwards compatibility + node.parent = parent; + + analyzer.enterNode(node); + }, + leave(node) { + analyzer.leaveNode(node); + }, + visitorKeys: this.visitorKeys, + }); + + return steps; + } +} + +module.exports = SourceCode; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js new file mode 100644 index 00000000..56f920a4 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js @@ -0,0 +1,61 @@ +/** + * @fileoverview Define the cursor which iterates tokens and comments in reverse. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const utils = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens and comments in reverse. + */ +module.exports = class BackwardTokenCommentCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.comments = comments; + this.tokenIndex = utils.getLastIndex(tokens, indexMap, endLoc); + this.commentIndex = utils.search(comments, endLoc) - 1; + this.border = startLoc; + } + + /** @inheritdoc */ + moveNext() { + const token = + this.tokenIndex >= 0 ? this.tokens[this.tokenIndex] : null; + const comment = + this.commentIndex >= 0 ? this.comments[this.commentIndex] : null; + + if (token && (!comment || token.range[1] > comment.range[1])) { + this.current = token; + this.tokenIndex -= 1; + } else if (comment) { + this.current = comment; + this.commentIndex -= 1; + } else { + this.current = null; + } + + return ( + Boolean(this.current) && + (this.border === -1 || this.current.range[0] >= this.border) + ); + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-cursor.js new file mode 100644 index 00000000..b6b2e120 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-cursor.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Define the cursor which iterates tokens only in reverse. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const { getLastIndex, getFirstIndex } = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens only in reverse. + */ +module.exports = class BackwardTokenCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.index = getLastIndex(tokens, indexMap, endLoc); + this.indexEnd = getFirstIndex(tokens, indexMap, startLoc); + } + + /** @inheritdoc */ + moveNext() { + if (this.index >= this.indexEnd) { + this.current = this.tokens[this.index]; + this.index -= 1; + return true; + } + return false; + } + + /* + * + * Shorthand for performance. + * + */ + + /** @inheritdoc */ + getOneToken() { + return this.index >= this.indexEnd ? this.tokens[this.index] : null; + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/cursor.js new file mode 100644 index 00000000..e640d23f --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/cursor.js @@ -0,0 +1,76 @@ +/** + * @fileoverview Define the abstract class about cursors which iterate tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The abstract class about cursors which iterate tokens. + * + * This class has 2 abstract methods. + * + * - `current: Token | Comment | null` ... The current token. + * - `moveNext(): boolean` ... Moves this cursor to the next token. If the next token didn't exist, it returns `false`. + * + * This is similar to ES2015 Iterators. + * However, Iterators were slow (at 2017-01), so I created this class as similar to C# IEnumerable. + * + * There are the following known sub classes. + * + * - ForwardTokenCursor .......... The cursor which iterates tokens only. + * - BackwardTokenCursor ......... The cursor which iterates tokens only in reverse. + * - ForwardTokenCommentCursor ... The cursor which iterates tokens and comments. + * - BackwardTokenCommentCursor .. The cursor which iterates tokens and comments in reverse. + * - DecorativeCursor + * - FilterCursor ............ The cursor which ignores the specified tokens. + * - SkipCursor .............. The cursor which ignores the first few tokens. + * - LimitCursor ............. The cursor which limits the count of tokens. + * + */ +module.exports = class Cursor { + /** + * Initializes this cursor. + */ + constructor() { + this.current = null; + } + + /** + * Gets the first token. + * This consumes this cursor. + * @returns {Token|Comment} The first token or null. + */ + getOneToken() { + return this.moveNext() ? this.current : null; + } + + /** + * Gets the first tokens. + * This consumes this cursor. + * @returns {(Token|Comment)[]} All tokens. + */ + getAllTokens() { + const tokens = []; + + while (this.moveNext()) { + tokens.push(this.current); + } + + return tokens; + } + + /** + * Moves this cursor to the next token. + * @returns {boolean} `true` if the next token exists. + * @abstract + */ + /* c8 ignore next */ + // eslint-disable-next-line class-methods-use-this -- Unused + moveNext() { + throw new Error("Not implemented."); + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/cursors.js b/node_modules/eslint/lib/languages/js/source-code/token-store/cursors.js new file mode 100644 index 00000000..1e9c084c --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/cursors.js @@ -0,0 +1,120 @@ +/** + * @fileoverview Define 2 token factories; forward and backward. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const BackwardTokenCommentCursor = require("./backward-token-comment-cursor"); +const BackwardTokenCursor = require("./backward-token-cursor"); +const FilterCursor = require("./filter-cursor"); +const ForwardTokenCommentCursor = require("./forward-token-comment-cursor"); +const ForwardTokenCursor = require("./forward-token-cursor"); +const LimitCursor = require("./limit-cursor"); +const SkipCursor = require("./skip-cursor"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * The cursor factory. + * @private + */ +class CursorFactory { + /** + * Initializes this cursor. + * @param {Function} TokenCursor The class of the cursor which iterates tokens only. + * @param {Function} TokenCommentCursor The class of the cursor which iterates the mix of tokens and comments. + */ + constructor(TokenCursor, TokenCommentCursor) { + this.TokenCursor = TokenCursor; + this.TokenCommentCursor = TokenCommentCursor; + } + + /** + * Creates a base cursor instance that can be decorated by createCursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {boolean} includeComments The flag to iterate comments as well. + * @returns {Cursor} The created base cursor. + */ + createBaseCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + ) { + const Cursor = includeComments + ? this.TokenCommentCursor + : this.TokenCursor; + + return new Cursor(tokens, comments, indexMap, startLoc, endLoc); + } + + /** + * Creates a cursor that iterates tokens with normalized options. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {boolean} includeComments The flag to iterate comments as well. + * @param {Function|null} filter The predicate function to choose tokens. + * @param {number} skip The count of tokens the cursor skips. + * @param {number} count The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. + * @returns {Cursor} The created cursor. + */ + createCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + filter, + skip, + count, + ) { + let cursor = this.createBaseCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + ); + + if (filter) { + cursor = new FilterCursor(cursor, filter); + } + if (skip >= 1) { + cursor = new SkipCursor(cursor, skip); + } + if (count >= 0) { + cursor = new LimitCursor(cursor, count); + } + + return cursor; + } +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +module.exports = { + forward: new CursorFactory(ForwardTokenCursor, ForwardTokenCommentCursor), + backward: new CursorFactory( + BackwardTokenCursor, + BackwardTokenCommentCursor, + ), +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/decorative-cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/decorative-cursor.js new file mode 100644 index 00000000..3a1d21ec --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/decorative-cursor.js @@ -0,0 +1,38 @@ +/** + * @fileoverview Define the abstract class about cursors which manipulate another cursor. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The abstract class about cursors which manipulate another cursor. + */ +module.exports = class DecorativeCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + */ + constructor(cursor) { + super(); + this.cursor = cursor; + } + + /** @inheritdoc */ + moveNext() { + const retv = this.cursor.moveNext(); + + this.current = this.cursor.current; + + return retv; + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/filter-cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/filter-cursor.js new file mode 100644 index 00000000..1e2ec996 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/filter-cursor.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Define the cursor which ignores specified tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const DecorativeCursor = require("./decorative-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The decorative cursor which ignores specified tokens. + */ +module.exports = class FilterCursor extends DecorativeCursor { + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + * @param {Function} predicate The predicate function to decide tokens this cursor iterates. + */ + constructor(cursor, predicate) { + super(cursor); + this.predicate = predicate; + } + + /** @inheritdoc */ + moveNext() { + const predicate = this.predicate; + + while (super.moveNext()) { + if (predicate(this.current)) { + return true; + } + } + return false; + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js new file mode 100644 index 00000000..d4a1439f --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js @@ -0,0 +1,65 @@ +/** + * @fileoverview Define the cursor which iterates tokens and comments. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const { getFirstIndex, search } = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens and comments. + */ +module.exports = class ForwardTokenCommentCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.comments = comments; + this.tokenIndex = getFirstIndex(tokens, indexMap, startLoc); + this.commentIndex = search(comments, startLoc); + this.border = endLoc; + } + + /** @inheritdoc */ + moveNext() { + const token = + this.tokenIndex < this.tokens.length + ? this.tokens[this.tokenIndex] + : null; + const comment = + this.commentIndex < this.comments.length + ? this.comments[this.commentIndex] + : null; + + if (token && (!comment || token.range[0] < comment.range[0])) { + this.current = token; + this.tokenIndex += 1; + } else if (comment) { + this.current = comment; + this.commentIndex += 1; + } else { + this.current = null; + } + + return ( + Boolean(this.current) && + (this.border === -1 || this.current.range[1] <= this.border) + ); + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-cursor.js new file mode 100644 index 00000000..5ca2290f --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-cursor.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Define the cursor which iterates tokens only. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const { getFirstIndex, getLastIndex } = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens only. + */ +module.exports = class ForwardTokenCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.index = getFirstIndex(tokens, indexMap, startLoc); + this.indexEnd = getLastIndex(tokens, indexMap, endLoc); + } + + /** @inheritdoc */ + moveNext() { + if (this.index <= this.indexEnd) { + this.current = this.tokens[this.index]; + this.index += 1; + return true; + } + return false; + } + + /* + * + * Shorthand for performance. + * + */ + + /** @inheritdoc */ + getOneToken() { + return this.index <= this.indexEnd ? this.tokens[this.index] : null; + } + + /** @inheritdoc */ + getAllTokens() { + return this.tokens.slice(this.index, this.indexEnd + 1); + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/index.js b/node_modules/eslint/lib/languages/js/source-code/token-store/index.js new file mode 100644 index 00000000..120438a9 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/index.js @@ -0,0 +1,721 @@ +/** + * @fileoverview Object to handle access and retrieval of tokens. + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { isCommentToken } = require("@eslint-community/eslint-utils"); +const assert = require("../../../../shared/assert"); +const cursors = require("./cursors"); +const ForwardTokenCursor = require("./forward-token-cursor"); +const PaddedTokenCursor = require("./padded-token-cursor"); +const utils = require("./utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TOKENS = Symbol("tokens"); +const COMMENTS = Symbol("comments"); +const INDEX_MAP = Symbol("indexMap"); + +/** + * Creates the map from locations to indices in `tokens`. + * + * The first/last location of tokens is mapped to the index of the token. + * The first/last location of comments is mapped to the index of the next token of each comment. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @returns {Object} The map from locations to indices in `tokens`. + * @private + */ +function createIndexMap(tokens, comments) { + const map = Object.create(null); + let tokenIndex = 0; + let commentIndex = 0; + let nextStart; + let range; + + while (tokenIndex < tokens.length || commentIndex < comments.length) { + nextStart = + commentIndex < comments.length + ? comments[commentIndex].range[0] + : Number.MAX_SAFE_INTEGER; + while ( + tokenIndex < tokens.length && + (range = tokens[tokenIndex].range)[0] < nextStart + ) { + map[range[0]] = tokenIndex; + map[range[1] - 1] = tokenIndex; + tokenIndex += 1; + } + + nextStart = + tokenIndex < tokens.length + ? tokens[tokenIndex].range[0] + : Number.MAX_SAFE_INTEGER; + while ( + commentIndex < comments.length && + (range = comments[commentIndex].range)[0] < nextStart + ) { + map[range[0]] = tokenIndex; + map[range[1] - 1] = tokenIndex; + commentIndex += 1; + } + } + + return map; +} + +/** + * Creates the cursor iterates tokens with options. + * @param {CursorFactory} factory The cursor factory to initialize cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.skip`. If this is a function then it's `opts.filter`. + * @param {boolean} [opts.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. + * @param {number} [opts.skip=0] The count of tokens the cursor skips. + * @returns {Cursor} The created cursor. + * @private + */ +function createCursorWithSkip( + factory, + tokens, + comments, + indexMap, + startLoc, + endLoc, + opts, +) { + let includeComments = false; + let skip = 0; + let filter = null; + + if (typeof opts === "number") { + skip = opts | 0; + } else if (typeof opts === "function") { + filter = opts; + } else if (opts) { + includeComments = !!opts.includeComments; + skip = opts.skip | 0; + filter = opts.filter || null; + } + assert(skip >= 0, "options.skip should be zero or a positive integer."); + assert( + !filter || typeof filter === "function", + "options.filter should be a function.", + ); + + return factory.createCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + filter, + skip, + -1, + ); +} + +/** + * Creates the cursor iterates tokens with options. + * @param {CursorFactory} factory The cursor factory to initialize cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.count`. If this is a function then it's `opts.filter`. + * @param {boolean} [opts.includeComments] The flag to iterate comments as well. + * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. + * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. + * @returns {Cursor} The created cursor. + * @private + */ +function createCursorWithCount( + factory, + tokens, + comments, + indexMap, + startLoc, + endLoc, + opts, +) { + let includeComments = false; + let count = 0; + let countExists = false; + let filter = null; + + if (typeof opts === "number") { + count = opts | 0; + countExists = true; + } else if (typeof opts === "function") { + filter = opts; + } else if (opts) { + includeComments = !!opts.includeComments; + count = opts.count | 0; + countExists = typeof opts.count === "number"; + filter = opts.filter || null; + } + assert(count >= 0, "options.count should be zero or a positive integer."); + assert( + !filter || typeof filter === "function", + "options.filter should be a function.", + ); + + return factory.createCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + filter, + 0, + countExists ? count : -1, + ); +} + +/** + * Creates the cursor iterates tokens with options. + * This is overload function of the below. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {Function|Object} opts The option object. If this is a function then it's `opts.filter`. + * @param {boolean} [opts.includeComments] The flag to iterate comments as well. + * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. + * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. + * @returns {Cursor} The created cursor. + * @private + */ +/** + * Creates the cursor iterates tokens with options. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number} [beforeCount=0] The number of tokens before the node to retrieve. + * @param {boolean} [afterCount=0] The number of tokens after the node to retrieve. + * @returns {Cursor} The created cursor. + * @private + */ +function createCursorWithPadding( + tokens, + comments, + indexMap, + startLoc, + endLoc, + beforeCount, + afterCount, +) { + if ( + typeof beforeCount === "undefined" && + typeof afterCount === "undefined" + ) { + return new ForwardTokenCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + ); + } + if (typeof beforeCount === "number" || typeof beforeCount === "undefined") { + return new PaddedTokenCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + beforeCount | 0, + afterCount | 0, + ); + } + return createCursorWithCount( + cursors.forward, + tokens, + comments, + indexMap, + startLoc, + endLoc, + beforeCount, + ); +} + +/** + * Gets comment tokens that are adjacent to the current cursor position. + * @param {Cursor} cursor A cursor instance. + * @returns {Array} An array of comment tokens adjacent to the current cursor position. + * @private + */ +function getAdjacentCommentTokensFromCursor(cursor) { + const tokens = []; + let currentToken = cursor.getOneToken(); + + while (currentToken && isCommentToken(currentToken)) { + tokens.push(currentToken); + currentToken = cursor.getOneToken(); + } + + return tokens; +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The token store. + * + * This class provides methods to get tokens by locations as fast as possible. + * The methods are a part of public API, so we should be careful if it changes this class. + * + * People can get tokens in O(1) by the hash map which is mapping from the location of tokens/comments to tokens. + * Also people can get a mix of tokens and comments in O(log k), the k is the number of comments. + * Assuming that comments to be much fewer than tokens, this does not make hash map from token's locations to comments to reduce memory cost. + * This uses binary-searching instead for comments. + */ +module.exports = class TokenStore { + /** + * Initializes this token store. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + */ + constructor(tokens, comments) { + this[TOKENS] = tokens; + this[COMMENTS] = comments; + this[INDEX_MAP] = createIndexMap(tokens, comments); + } + + //-------------------------------------------------------------------------- + // Gets single token. + //-------------------------------------------------------------------------- + + /** + * Gets the token starting at the specified index. + * @param {number} offset Index of the start of the token's range. + * @param {Object} [options=0] The option object. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @returns {Token|null} The token starting at index, or null if no such token. + */ + getTokenByRangeStart(offset, options) { + const includeComments = options && options.includeComments; + const token = cursors.forward + .createBaseCursor( + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + offset, + -1, + includeComments, + ) + .getOneToken(); + + if (token && token.range[0] === offset) { + return token; + } + return null; + } + + /** + * Gets the first token of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.skip=0] The count of tokens the cursor skips. + * @returns {Token|null} An object representing the token. + */ + getFirstToken(node, options) { + return createCursorWithSkip( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options, + ).getOneToken(); + } + + /** + * Gets the last token of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getLastToken(node, options) { + return createCursorWithSkip( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options, + ).getOneToken(); + } + + /** + * Gets the token that precedes a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getTokenBefore(node, options) { + return createCursorWithSkip( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + -1, + node.range[0], + options, + ).getOneToken(); + } + + /** + * Gets the token that follows a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getTokenAfter(node, options) { + return createCursorWithSkip( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[1], + -1, + options, + ).getOneToken(); + } + + /** + * Gets the first token between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getFirstTokenBetween(left, right, options) { + return createCursorWithSkip( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options, + ).getOneToken(); + } + + /** + * Gets the last token between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getLastTokenBetween(left, right, options) { + return createCursorWithSkip( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options, + ).getOneToken(); + } + + /** + * Gets the token that precedes a given node or token in the token stream. + * This is defined for backward compatibility. Use `includeComments` option instead. + * TODO: We have a plan to remove this in a future major version. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number} [skip=0] A number of tokens to skip. + * @returns {Token|null} An object representing the token. + * @deprecated + */ + getTokenOrCommentBefore(node, skip) { + return this.getTokenBefore(node, { includeComments: true, skip }); + } + + /** + * Gets the token that follows a given node or token in the token stream. + * This is defined for backward compatibility. Use `includeComments` option instead. + * TODO: We have a plan to remove this in a future major version. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number} [skip=0] A number of tokens to skip. + * @returns {Token|null} An object representing the token. + * @deprecated + */ + getTokenOrCommentAfter(node, skip) { + return this.getTokenAfter(node, { includeComments: true, skip }); + } + + //-------------------------------------------------------------------------- + // Gets multiple tokens. + //-------------------------------------------------------------------------- + + /** + * Gets the first `count` tokens of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. + * @returns {Token[]} Tokens. + */ + getFirstTokens(node, options) { + return createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options, + ).getAllTokens(); + } + + /** + * Gets the last `count` tokens of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens. + */ + getLastTokens(node, options) { + return createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options, + ) + .getAllTokens() + .reverse(); + } + + /** + * Gets the `count` tokens that precedes a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens. + */ + getTokensBefore(node, options) { + return createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + -1, + node.range[0], + options, + ) + .getAllTokens() + .reverse(); + } + + /** + * Gets the `count` tokens that follows a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens. + */ + getTokensAfter(node, options) { + return createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[1], + -1, + options, + ).getAllTokens(); + } + + /** + * Gets the first `count` tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens between left and right. + */ + getFirstTokensBetween(left, right, options) { + return createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options, + ).getAllTokens(); + } + + /** + * Gets the last `count` tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens between left and right. + */ + getLastTokensBetween(left, right, options) { + return createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options, + ) + .getAllTokens() + .reverse(); + } + + /** + * Gets all tokens that are related to the given node. + * @param {ASTNode} node The AST node. + * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. + * @returns {Token[]} Array of objects representing tokens. + */ + /** + * Gets all tokens that are related to the given node. + * @param {ASTNode} node The AST node. + * @param {number} [beforeCount=0] The number of tokens before the node to retrieve. + * @param {number} [afterCount=0] The number of tokens after the node to retrieve. + * @returns {Token[]} Array of objects representing tokens. + */ + getTokens(node, beforeCount, afterCount) { + return createCursorWithPadding( + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + beforeCount, + afterCount, + ).getAllTokens(); + } + + /** + * Gets all of the tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. + * @returns {Token[]} Tokens between left and right. + */ + /** + * Gets all of the tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number} [padding=0] Number of extra tokens on either side of center. + * @returns {Token[]} Tokens between left and right. + */ + getTokensBetween(left, right, padding) { + return createCursorWithPadding( + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + padding, + padding, + ).getAllTokens(); + } + + //-------------------------------------------------------------------------- + // Others. + //-------------------------------------------------------------------------- + + /** + * Checks whether any comments exist or not between the given 2 nodes. + * @param {ASTNode} left The node to check. + * @param {ASTNode} right The node to check. + * @returns {boolean} `true` if one or more comments exist. + */ + commentsExistBetween(left, right) { + const index = utils.search(this[COMMENTS], left.range[1]); + + return ( + index < this[COMMENTS].length && + this[COMMENTS][index].range[1] <= right.range[0] + ); + } + + /** + * Gets all comment tokens directly before the given node or token. + * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. + * @returns {Array} An array of comments in occurrence order. + */ + getCommentsBefore(nodeOrToken) { + const cursor = createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + -1, + nodeOrToken.range[0], + { includeComments: true }, + ); + + return getAdjacentCommentTokensFromCursor(cursor).reverse(); + } + + /** + * Gets all comment tokens directly after the given node or token. + * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. + * @returns {Array} An array of comments in occurrence order. + */ + getCommentsAfter(nodeOrToken) { + const cursor = createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + nodeOrToken.range[1], + -1, + { includeComments: true }, + ); + + return getAdjacentCommentTokensFromCursor(cursor); + } + + /** + * Gets all comment tokens inside the given node. + * @param {ASTNode} node The AST node to get the comments for. + * @returns {Array} An array of comments in occurrence order. + */ + getCommentsInside(node) { + return this.getTokens(node, { + includeComments: true, + filter: isCommentToken, + }); + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/limit-cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/limit-cursor.js new file mode 100644 index 00000000..301d7f54 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/limit-cursor.js @@ -0,0 +1,39 @@ +/** + * @fileoverview Define the cursor which limits the number of tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const DecorativeCursor = require("./decorative-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The decorative cursor which limits the number of tokens. + */ +module.exports = class LimitCursor extends DecorativeCursor { + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + * @param {number} count The count of tokens this cursor iterates. + */ + constructor(cursor, count) { + super(cursor); + this.count = count; + } + + /** @inheritdoc */ + moveNext() { + if (this.count > 0) { + this.count -= 1; + return super.moveNext(); + } + return false; + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/padded-token-cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/padded-token-cursor.js new file mode 100644 index 00000000..3d3ce04f --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/padded-token-cursor.js @@ -0,0 +1,45 @@ +/** + * @fileoverview Define the cursor which iterates tokens only, with inflated range. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const ForwardTokenCursor = require("./forward-token-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens only, with inflated range. + * This is for the backward compatibility of padding options. + */ +module.exports = class PaddedTokenCursor extends ForwardTokenCursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number} beforeCount The number of tokens this cursor iterates before start. + * @param {number} afterCount The number of tokens this cursor iterates after end. + */ + constructor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + beforeCount, + afterCount, + ) { + super(tokens, comments, indexMap, startLoc, endLoc); + this.index = Math.max(0, this.index - beforeCount); + this.indexEnd = Math.min(tokens.length - 1, this.indexEnd + afterCount); + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/skip-cursor.js b/node_modules/eslint/lib/languages/js/source-code/token-store/skip-cursor.js new file mode 100644 index 00000000..6bc43d85 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/skip-cursor.js @@ -0,0 +1,41 @@ +/** + * @fileoverview Define the cursor which ignores the first few tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const DecorativeCursor = require("./decorative-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The decorative cursor which ignores the first few tokens. + */ +module.exports = class SkipCursor extends DecorativeCursor { + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + * @param {number} count The count of tokens this cursor skips. + */ + constructor(cursor, count) { + super(cursor); + this.count = count; + } + + /** @inheritdoc */ + moveNext() { + while (this.count > 0) { + this.count -= 1; + if (!super.moveNext()) { + return false; + } + } + return super.moveNext(); + } +}; diff --git a/node_modules/eslint/lib/languages/js/source-code/token-store/utils.js b/node_modules/eslint/lib/languages/js/source-code/token-store/utils.js new file mode 100644 index 00000000..94e456c9 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/source-code/token-store/utils.js @@ -0,0 +1,110 @@ +/** + * @fileoverview Define utility functions for token store. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * Finds the index of the first token which is after the given location. + * If it was not found, this returns `tokens.length`. + * @param {(Token|Comment)[]} tokens It searches the token in this list. + * @param {number} location The location to search. + * @returns {number} The found index or `tokens.length`. + */ +exports.search = function search(tokens, location) { + for ( + let minIndex = 0, maxIndex = tokens.length - 1; + minIndex <= maxIndex; + + ) { + /* + * Calculate the index in the middle between minIndex and maxIndex. + * `| 0` is used to round a fractional value down to the nearest integer: this is similar to + * using `Math.trunc()` or `Math.floor()`, but performance tests have shown this method to + * be faster. + */ + const index = ((minIndex + maxIndex) / 2) | 0; + const token = tokens[index]; + const tokenStartLocation = token.range[0]; + + if (location <= tokenStartLocation) { + if (index === minIndex) { + return index; + } + maxIndex = index; + } else { + minIndex = index + 1; + } + } + return tokens.length; +}; + +/** + * Gets the index of the `startLoc` in `tokens`. + * `startLoc` can be the value of `node.range[1]`, so this checks about `startLoc - 1` as well. + * @param {(Token|Comment)[]} tokens The tokens to find an index. + * @param {Object} indexMap The map from locations to indices. + * @param {number} startLoc The location to get an index. + * @returns {number} The index. + */ +exports.getFirstIndex = function getFirstIndex(tokens, indexMap, startLoc) { + if (startLoc in indexMap) { + return indexMap[startLoc]; + } + if (startLoc - 1 in indexMap) { + const index = indexMap[startLoc - 1]; + const token = tokens[index]; + + // If the mapped index is out of bounds, the returned cursor index will point after the end of the tokens array. + if (!token) { + return tokens.length; + } + + /* + * For the map of "comment's location -> token's index", it points the next token of a comment. + * In that case, +1 is unnecessary. + */ + if (token.range[0] >= startLoc) { + return index; + } + return index + 1; + } + return 0; +}; + +/** + * Gets the index of the `endLoc` in `tokens`. + * The information of end locations are recorded at `endLoc - 1` in `indexMap`, so this checks about `endLoc - 1` as well. + * @param {(Token|Comment)[]} tokens The tokens to find an index. + * @param {Object} indexMap The map from locations to indices. + * @param {number} endLoc The location to get an index. + * @returns {number} The index. + */ +exports.getLastIndex = function getLastIndex(tokens, indexMap, endLoc) { + if (endLoc in indexMap) { + return indexMap[endLoc] - 1; + } + if (endLoc - 1 in indexMap) { + const index = indexMap[endLoc - 1]; + const token = tokens[index]; + + // If the mapped index is out of bounds, the returned cursor index will point before the end of the tokens array. + if (!token) { + return tokens.length - 1; + } + + /* + * For the map of "comment's location -> token's index", it points the next token of a comment. + * In that case, -1 is necessary. + */ + if (token.range[1] > endLoc) { + return index - 1; + } + return index; + } + return tokens.length - 1; +}; diff --git a/node_modules/eslint/lib/languages/js/validate-language-options.js b/node_modules/eslint/lib/languages/js/validate-language-options.js new file mode 100644 index 00000000..23ed2666 --- /dev/null +++ b/node_modules/eslint/lib/languages/js/validate-language-options.js @@ -0,0 +1,196 @@ +/** + * @fileoverview The schema to validate language options + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Data +//----------------------------------------------------------------------------- + +const globalVariablesValues = new Set([ + true, + "true", + "writable", + "writeable", + false, + "false", + "readonly", + "readable", + null, + "off", +]); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Check if a value is a non-null object. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is a non-null object. + */ +function isNonNullObject(value) { + return typeof value === "object" && value !== null; +} + +/** + * Check if a value is a non-null non-array object. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is a non-null non-array object. + */ +function isNonArrayObject(value) { + return isNonNullObject(value) && !Array.isArray(value); +} + +/** + * Check if a value is undefined. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is undefined. + */ +function isUndefined(value) { + return typeof value === "undefined"; +} + +//----------------------------------------------------------------------------- +// Schemas +//----------------------------------------------------------------------------- + +/** + * Validates the ecmaVersion property. + * @param {string|number} ecmaVersion The value to check. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ +function validateEcmaVersion(ecmaVersion) { + if (isUndefined(ecmaVersion)) { + throw new TypeError( + 'Key "ecmaVersion": Expected an "ecmaVersion" property.', + ); + } + + if (typeof ecmaVersion !== "number" && ecmaVersion !== "latest") { + throw new TypeError( + 'Key "ecmaVersion": Expected a number or "latest".', + ); + } +} + +/** + * Validates the sourceType property. + * @param {string} sourceType The value to check. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ +function validateSourceType(sourceType) { + if ( + typeof sourceType !== "string" || + !/^(?:script|module|commonjs)$/u.test(sourceType) + ) { + throw new TypeError( + 'Key "sourceType": Expected "script", "module", or "commonjs".', + ); + } +} + +/** + * Validates the globals property. + * @param {Object} globals The value to check. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ +function validateGlobals(globals) { + if (!isNonArrayObject(globals)) { + throw new TypeError('Key "globals": Expected an object.'); + } + + for (const key of Object.keys(globals)) { + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + if (key !== key.trim()) { + throw new TypeError( + `Key "globals": Global "${key}" has leading or trailing whitespace.`, + ); + } + + if (!globalVariablesValues.has(globals[key])) { + throw new TypeError( + `Key "globals": Key "${key}": Expected "readonly", "writable", or "off".`, + ); + } + } +} + +/** + * Validates the parser property. + * @param {Object} parser The value to check. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ +function validateParser(parser) { + if ( + !parser || + typeof parser !== "object" || + (typeof parser.parse !== "function" && + typeof parser.parseForESLint !== "function") + ) { + throw new TypeError( + 'Key "parser": Expected object with parse() or parseForESLint() method.', + ); + } +} + +/** + * Validates the language options. + * @param {Object} languageOptions The language options to validate. + * @returns {void} + * @throws {TypeError} If the language options are invalid. + */ +function validateLanguageOptions(languageOptions) { + if (!isNonArrayObject(languageOptions)) { + throw new TypeError("Expected an object."); + } + + const { + ecmaVersion, + sourceType, + globals, + parser, + parserOptions, + ...otherOptions + } = languageOptions; + + if ("ecmaVersion" in languageOptions) { + validateEcmaVersion(ecmaVersion); + } + + if ("sourceType" in languageOptions) { + validateSourceType(sourceType); + } + + if ("globals" in languageOptions) { + validateGlobals(globals); + } + + if ("parser" in languageOptions) { + validateParser(parser); + } + + if ("parserOptions" in languageOptions) { + if (!isNonArrayObject(parserOptions)) { + throw new TypeError('Key "parserOptions": Expected an object.'); + } + } + + const otherOptionKeys = Object.keys(otherOptions); + + if (otherOptionKeys.length > 0) { + throw new TypeError(`Unexpected key "${otherOptionKeys[0]}" found.`); + } +} + +module.exports = { validateLanguageOptions }; diff --git a/node_modules/eslint/lib/linter/apply-disable-directives.js b/node_modules/eslint/lib/linter/apply-disable-directives.js new file mode 100644 index 00000000..529be9e7 --- /dev/null +++ b/node_modules/eslint/lib/linter/apply-disable-directives.js @@ -0,0 +1,584 @@ +/** + * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments + * @author Teddy Katz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("@eslint/core").Language} Language */ +/** @typedef {import("@eslint/core").Position} Position */ +/** @typedef {import("@eslint/core").RulesConfig} RulesConfig */ + +//------------------------------------------------------------------------------ +// Module Definition +//------------------------------------------------------------------------------ + +const escapeRegExp = require("escape-string-regexp"); +const { Config } = require("../config/config.js"); + +/** + * Compares the locations of two objects in a source file + * @param {Position} itemA The first object + * @param {Position} itemB The second object + * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if + * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location. + */ +function compareLocations(itemA, itemB) { + return itemA.line - itemB.line || itemA.column - itemB.column; +} + +/** + * Groups a set of directives into sub-arrays by their parent comment. + * @param {Iterable} directives Unused directives to be removed. + * @returns {Directive[][]} Directives grouped by their parent comment. + */ +function groupByParentDirective(directives) { + const groups = new Map(); + + for (const directive of directives) { + const { + unprocessedDirective: { parentDirective }, + } = directive; + + if (groups.has(parentDirective)) { + groups.get(parentDirective).push(directive); + } else { + groups.set(parentDirective, [directive]); + } + } + + return [...groups.values()]; +} + +/** + * Creates removal details for a set of directives within the same comment. + * @param {Directive[]} directives Unused directives to be removed. + * @param {{node: Token, value: string}} parentDirective Data about the backing directive. + * @param {SourceCode} sourceCode The source code object for the file being linted. + * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems. + */ +function createIndividualDirectivesRemoval( + directives, + parentDirective, + sourceCode, +) { + /* + * Get the list of the rules text without any surrounding whitespace. In order to preserve the original + * formatting, we don't want to change that whitespace. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + */ + const listText = parentDirective.value.trim(); + + // Calculate where it starts in the source code text + const listStart = sourceCode.text.indexOf( + listText, + sourceCode.getRange(parentDirective.node)[0], + ); + + /* + * We can assume that `listText` contains multiple elements. + * Otherwise, this function wouldn't be called - if there is + * only one rule in the list, then the whole comment must be removed. + */ + + return directives.map(directive => { + const { ruleId } = directive; + + const regex = new RegExp( + String.raw`(?:^|\s*,\s*)(?['"]?)${escapeRegExp(ruleId)}\k(?:\s*,\s*|$)`, + "u", + ); + const match = regex.exec(listText); + const matchedText = match[0]; + const matchStart = listStart + match.index; + const matchEnd = matchStart + matchedText.length; + + const firstIndexOfComma = matchedText.indexOf(","); + const lastIndexOfComma = matchedText.lastIndexOf(","); + + let removalStart, removalEnd; + + if (firstIndexOfComma !== lastIndexOfComma) { + /* + * Since there are two commas, this must one of the elements in the middle of the list. + * Matched range starts where the previous rule name ends, and ends where the next rule name starts. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^^^^ + * + * We want to remove only the content between the two commas, and also one of the commas. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^ + */ + removalStart = matchStart + firstIndexOfComma; + removalEnd = matchStart + lastIndexOfComma; + } else { + /* + * This is either the first element or the last element. + * + * If this is the first element, matched range starts where the first rule name starts + * and ends where the second rule name starts. This is exactly the range we want + * to remove so that the second rule name will start where the first one was starting + * and thus preserve the original formatting. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^ + * + * Similarly, if this is the last element, we've already matched the range we want to + * remove. The previous rule name will end where the last one was ending, relative + * to the content on the right side. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^^^ + */ + removalStart = matchStart; + removalEnd = matchEnd; + } + + return { + description: `'${ruleId}'`, + fix: { + range: [removalStart, removalEnd], + text: "", + }, + unprocessedDirective: directive.unprocessedDirective, + }; + }); +} + +/** + * Creates a description of deleting an entire unused disable directive. + * @param {Directive[]} directives Unused directives to be removed. + * @param {Token} node The backing Comment token. + * @param {SourceCode} sourceCode The source code object for the file being linted. + * @returns {{ description, fix, unprocessedDirective }} Details for later creation of an output problem. + */ +function createDirectiveRemoval(directives, node, sourceCode) { + const range = sourceCode.getRange(node); + const ruleIds = directives + .filter(directive => directive.ruleId) + .map(directive => `'${directive.ruleId}'`); + + return { + description: + ruleIds.length <= 2 + ? ruleIds.join(" or ") + : `${ruleIds.slice(0, ruleIds.length - 1).join(", ")}, or ${ruleIds.at(-1)}`, + fix: { + range, + text: " ", + }, + unprocessedDirective: directives[0].unprocessedDirective, + }; +} + +/** + * Parses details from directives to create output Problems. + * @param {Iterable} allDirectives Unused directives to be removed. + * @param {SourceCode} sourceCode The source code object for the file being linted. + * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems. + */ +function processUnusedDirectives(allDirectives, sourceCode) { + const directiveGroups = groupByParentDirective(allDirectives); + + return directiveGroups.flatMap(directives => { + const { parentDirective } = directives[0].unprocessedDirective; + const remainingRuleIds = new Set(parentDirective.ruleIds); + + for (const directive of directives) { + remainingRuleIds.delete(directive.ruleId); + } + + return remainingRuleIds.size + ? createIndividualDirectivesRemoval( + directives, + parentDirective, + sourceCode, + ) + : [ + createDirectiveRemoval( + directives, + parentDirective.node, + sourceCode, + ), + ]; + }); +} + +/** + * Collect eslint-enable comments that are removing suppressions by eslint-disable comments. + * @param {Directive[]} directives The directives to check. + * @returns {Set} The used eslint-enable comments + */ +function collectUsedEnableDirectives(directives) { + /** + * A Map of `eslint-enable` keyed by ruleIds that may be marked as used. + * If `eslint-enable` does not have a ruleId, the key will be `null`. + * @type {Map} + */ + const enabledRules = new Map(); + + /** + * A Set of `eslint-enable` marked as used. + * It is also the return value of `collectUsedEnableDirectives` function. + * @type {Set} + */ + const usedEnableDirectives = new Set(); + + /* + * Checks the directives backwards to see if the encountered `eslint-enable` is used by the previous `eslint-disable`, + * and if so, stores the `eslint-enable` in `usedEnableDirectives`. + */ + for (let index = directives.length - 1; index >= 0; index--) { + const directive = directives[index]; + + if (directive.type === "disable") { + if (enabledRules.size === 0) { + continue; + } + if (directive.ruleId === null) { + // If encounter `eslint-disable` without ruleId, + // mark all `eslint-enable` currently held in enabledRules as used. + // e.g. + // /* eslint-disable */ <- current directive + // /* eslint-enable rule-id1 */ <- used + // /* eslint-enable rule-id2 */ <- used + // /* eslint-enable */ <- used + for (const enableDirective of enabledRules.values()) { + usedEnableDirectives.add(enableDirective); + } + enabledRules.clear(); + } else { + const enableDirective = enabledRules.get(directive.ruleId); + + if (enableDirective) { + // If encounter `eslint-disable` with ruleId, and there is an `eslint-enable` with the same ruleId in enabledRules, + // mark `eslint-enable` with ruleId as used. + // e.g. + // /* eslint-disable rule-id */ <- current directive + // /* eslint-enable rule-id */ <- used + usedEnableDirectives.add(enableDirective); + } else { + const enabledDirectiveWithoutRuleId = + enabledRules.get(null); + + if (enabledDirectiveWithoutRuleId) { + // If encounter `eslint-disable` with ruleId, and there is no `eslint-enable` with the same ruleId in enabledRules, + // mark `eslint-enable` without ruleId as used. + // e.g. + // /* eslint-disable rule-id */ <- current directive + // /* eslint-enable */ <- used + usedEnableDirectives.add(enabledDirectiveWithoutRuleId); + } + } + } + } else if (directive.type === "enable") { + if (directive.ruleId === null) { + // If encounter `eslint-enable` without ruleId, the `eslint-enable` that follows it are unused. + // So clear enabledRules. + // e.g. + // /* eslint-enable */ <- current directive + // /* eslint-enable rule-id *// <- unused + // /* eslint-enable */ <- unused + enabledRules.clear(); + enabledRules.set(null, directive); + } else { + enabledRules.set(directive.ruleId, directive); + } + } + } + return usedEnableDirectives; +} + +/** + * This is the same as the exported function, except that it + * doesn't handle disable-line and disable-next-line directives, and it always reports unused + * disable directives. + * @param {Object} options options for applying directives. This is the same as the options + * for the exported function, except that `reportUnusedDisableDirectives` is not supported + * (this function always reports unused disable directives). + * @returns {{problems: LintMessage[], unusedDirectives: LintMessage[]}} An object with a list + * of problems (including suppressed ones) and unused eslint-disable directives + */ +function applyDirectives(options) { + const problems = []; + const usedDisableDirectives = new Set(); + const { sourceCode } = options; + + for (const problem of options.problems) { + let disableDirectivesForProblem = []; + let nextDirectiveIndex = 0; + + while ( + nextDirectiveIndex < options.directives.length && + compareLocations(options.directives[nextDirectiveIndex], problem) <= + 0 + ) { + const directive = options.directives[nextDirectiveIndex++]; + + if ( + directive.ruleId === null || + directive.ruleId === problem.ruleId + ) { + switch (directive.type) { + case "disable": + disableDirectivesForProblem.push(directive); + break; + + case "enable": + disableDirectivesForProblem = []; + break; + + // no default + } + } + } + + if (disableDirectivesForProblem.length > 0) { + const suppressions = disableDirectivesForProblem.map(directive => ({ + kind: "directive", + justification: directive.unprocessedDirective.justification, + })); + + if (problem.suppressions) { + problem.suppressions = + problem.suppressions.concat(suppressions); + } else { + problem.suppressions = suppressions; + usedDisableDirectives.add(disableDirectivesForProblem.at(-1)); + } + } + + problems.push(problem); + } + + const unusedDisableDirectivesToReport = options.directives.filter( + directive => + directive.type === "disable" && + !usedDisableDirectives.has(directive) && + !options.rulesToIgnore.has(directive.ruleId), + ); + + const unusedEnableDirectivesToReport = new Set( + options.directives.filter( + directive => + directive.unprocessedDirective.type === "enable" && + !options.rulesToIgnore.has(directive.ruleId), + ), + ); + + /* + * If directives has the eslint-enable directive, + * check whether the eslint-enable comment is used. + */ + if (unusedEnableDirectivesToReport.size > 0) { + for (const directive of collectUsedEnableDirectives( + options.directives, + )) { + unusedEnableDirectivesToReport.delete(directive); + } + } + + const processed = processUnusedDirectives( + unusedDisableDirectivesToReport, + sourceCode, + ).concat( + processUnusedDirectives(unusedEnableDirectivesToReport, sourceCode), + ); + const columnOffset = options.language.columnStart === 1 ? 0 : 1; + const lineOffset = options.language.lineStart === 1 ? 0 : 1; + + const unusedDirectives = processed.map( + ({ description, fix, unprocessedDirective }) => { + const { parentDirective, type, line, column } = + unprocessedDirective; + + let message; + + if (type === "enable") { + message = description + ? `Unused eslint-enable directive (no matching eslint-disable directives were found for ${description}).` + : "Unused eslint-enable directive (no matching eslint-disable directives were found)."; + } else { + message = description + ? `Unused eslint-disable directive (no problems were reported from ${description}).` + : "Unused eslint-disable directive (no problems were reported)."; + } + + const loc = sourceCode.getLoc(parentDirective.node); + + return { + ruleId: null, + message, + line: + type === "disable-next-line" + ? loc.start.line + lineOffset + : line, + column: + type === "disable-next-line" + ? loc.start.column + columnOffset + : column, + severity: + options.reportUnusedDisableDirectives === "warn" ? 1 : 2, + nodeType: null, + ...(options.disableFixes ? {} : { fix }), + }; + }, + ); + + return { problems, unusedDirectives }; +} + +/** + * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list + * of reported problems, adds the suppression information to the problems. + * @param {Object} options Information about directives and problems + * @param {Language} options.language The language being linted. + * @param {SourceCode} options.sourceCode The source code object for the file being linted. + * @param {{ + * type: ("disable"|"enable"|"disable-line"|"disable-next-line"), + * ruleId: (string|null), + * line: number, + * column: number, + * justification: string + * }} options.directives Directive comments found in the file, with one-based columns. + * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable + * comment for two different rules is represented as two directives). + * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems + * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns. + * @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives + * @param {RulesConfig} options.configuredRules The rules configuration. + * @param {Function} options.ruleFilter A predicate function to filter which rules should be executed. + * @param {boolean} options.disableFixes If true, it doesn't make `fix` properties. + * @returns {{ruleId: (string|null), line: number, column: number, suppressions?: {kind: string, justification: string}}[]} + * An object with a list of reported problems, the suppressed of which contain the suppression information. + */ +module.exports = ({ + language, + sourceCode, + directives, + disableFixes, + problems, + configuredRules, + ruleFilter, + reportUnusedDisableDirectives = "off", +}) => { + const blockDirectives = directives + .filter( + directive => + directive.type === "disable" || directive.type === "enable", + ) + .map(directive => + Object.assign({}, directive, { unprocessedDirective: directive }), + ) + .sort(compareLocations); + + const lineDirectives = directives + .flatMap(directive => { + switch (directive.type) { + case "disable": + case "enable": + return []; + + case "disable-line": + return [ + { + type: "disable", + line: directive.line, + column: 1, + ruleId: directive.ruleId, + unprocessedDirective: directive, + }, + { + type: "enable", + line: directive.line + 1, + column: 0, + ruleId: directive.ruleId, + unprocessedDirective: directive, + }, + ]; + + case "disable-next-line": + return [ + { + type: "disable", + line: directive.line + 1, + column: 1, + ruleId: directive.ruleId, + unprocessedDirective: directive, + }, + { + type: "enable", + line: directive.line + 2, + column: 0, + ruleId: directive.ruleId, + unprocessedDirective: directive, + }, + ]; + + default: + throw new TypeError( + `Unrecognized directive type '${directive.type}'`, + ); + } + }) + .sort(compareLocations); + + // This determines a list of rules that are not being run by the given ruleFilter, if present. + const rulesToIgnore = + configuredRules && ruleFilter + ? new Set( + Object.keys(configuredRules).filter(ruleId => { + const severity = Config.getRuleNumericSeverity( + configuredRules[ruleId], + ); + + // Ignore for disabled rules. + if (severity === 0) { + return false; + } + + return !ruleFilter({ severity, ruleId }); + }), + ) + : new Set(); + + // If no ruleId is supplied that means this directive is applied to all rules, so we can't determine if it's unused if any rules are filtered out. + if (rulesToIgnore.size > 0) { + rulesToIgnore.add(null); + } + + const blockDirectivesResult = applyDirectives({ + language, + sourceCode, + problems, + directives: blockDirectives, + disableFixes, + reportUnusedDisableDirectives, + rulesToIgnore, + }); + const lineDirectivesResult = applyDirectives({ + language, + sourceCode, + problems: blockDirectivesResult.problems, + directives: lineDirectives, + disableFixes, + reportUnusedDisableDirectives, + rulesToIgnore, + }); + + return reportUnusedDisableDirectives !== "off" + ? lineDirectivesResult.problems + .concat(blockDirectivesResult.unusedDirectives) + .concat(lineDirectivesResult.unusedDirectives) + .sort(compareLocations) + : lineDirectivesResult.problems; +}; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js b/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js new file mode 100644 index 00000000..fc728d10 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js @@ -0,0 +1,828 @@ +/** + * @fileoverview A class of the code path analyzer. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("../../shared/assert"), + { breakableTypePattern } = require("../../shared/ast-utils"), + CodePath = require("./code-path"), + CodePathSegment = require("./code-path-segment"), + IdGenerator = require("./id-generator"), + debug = require("./debug-helpers"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a `case` node (not `default` node). + * @param {ASTNode} node A `SwitchCase` node to check. + * @returns {boolean} `true` if the node is a `case` node (not `default` node). + */ +function isCaseNode(node) { + return Boolean(node.test); +} + +/** + * Checks if a given node appears as the value of a PropertyDefinition node. + * @param {ASTNode} node THe node to check. + * @returns {boolean} `true` if the node is a PropertyDefinition value, + * false if not. + */ +function isPropertyDefinitionValue(node) { + const parent = node.parent; + + return ( + parent && parent.type === "PropertyDefinition" && parent.value === node + ); +} + +/** + * Checks whether the given logical operator is taken into account for the code + * path analysis. + * @param {string} operator The operator found in the LogicalExpression node + * @returns {boolean} `true` if the operator is "&&" or "||" or "??" + */ +function isHandledLogicalOperator(operator) { + return operator === "&&" || operator === "||" || operator === "??"; +} + +/** + * Checks whether the given assignment operator is a logical assignment operator. + * Logical assignments are taken into account for the code path analysis + * because of their short-circuiting semantics. + * @param {string} operator The operator found in the AssignmentExpression node + * @returns {boolean} `true` if the operator is "&&=" or "||=" or "??=" + */ +function isLogicalAssignmentOperator(operator) { + return operator === "&&=" || operator === "||=" || operator === "??="; +} + +/** + * Gets the label if the parent node of a given node is a LabeledStatement. + * @param {ASTNode} node A node to get. + * @returns {string|null} The label or `null`. + */ +function getLabel(node) { + if (node.parent.type === "LabeledStatement") { + return node.parent.label.name; + } + return null; +} + +/** + * Checks whether or not a given logical expression node goes different path + * between the `true` case and the `false` case. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a test of a choice statement. + */ +function isForkingByTrueOrFalse(node) { + const parent = node.parent; + + switch (parent.type) { + case "ConditionalExpression": + case "IfStatement": + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + return parent.test === node; + + case "LogicalExpression": + return isHandledLogicalOperator(parent.operator); + + case "AssignmentExpression": + return isLogicalAssignmentOperator(parent.operator); + + default: + return false; + } +} + +/** + * Gets the boolean value of a given literal node. + * + * This is used to detect infinity loops (e.g. `while (true) {}`). + * Statements preceded by an infinity loop are unreachable if the loop didn't + * have any `break` statement. + * @param {ASTNode} node A node to get. + * @returns {boolean|undefined} a boolean value if the node is a Literal node, + * otherwise `undefined`. + */ +function getBooleanValueIfSimpleConstant(node) { + if (node.type === "Literal") { + return Boolean(node.value); + } + return void 0; +} + +/** + * Checks that a given identifier node is a reference or not. + * + * This is used to detect the first throwable node in a `try` block. + * @param {ASTNode} node An Identifier node to check. + * @returns {boolean} `true` if the node is a reference. + */ +function isIdentifierReference(node) { + const parent = node.parent; + + switch (parent.type) { + case "LabeledStatement": + case "BreakStatement": + case "ContinueStatement": + case "ArrayPattern": + case "RestElement": + case "ImportSpecifier": + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "CatchClause": + return false; + + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "ClassDeclaration": + case "ClassExpression": + case "VariableDeclarator": + return parent.id !== node; + + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + return parent.key !== node || parent.computed || parent.shorthand; + + case "AssignmentPattern": + return parent.key !== node; + + default: + return true; + } +} + +/** + * Updates the current segment with the head segment. + * This is similar to local branches and tracking branches of git. + * + * To separate the current and the head is in order to not make useless segments. + * + * In this process, both "onCodePathSegmentStart" and "onCodePathSegmentEnd" + * events are fired. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function forwardCurrentToHead(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + const currentSegments = state.currentSegments; + const headSegments = state.headSegments; + const end = Math.max(currentSegments.length, headSegments.length); + let i, currentSegment, headSegment; + + // Fires leaving events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + + if (currentSegment !== headSegment && currentSegment) { + const eventName = currentSegment.reachable + ? "onCodePathSegmentEnd" + : "onUnreachableCodePathSegmentEnd"; + + debug.dump(`${eventName} ${currentSegment.id}`); + + analyzer.emit(eventName, [currentSegment, node]); + } + } + + // Update state. + state.currentSegments = headSegments; + + // Fires entering events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + + if (currentSegment !== headSegment && headSegment) { + const eventName = headSegment.reachable + ? "onCodePathSegmentStart" + : "onUnreachableCodePathSegmentStart"; + + debug.dump(`${eventName} ${headSegment.id}`); + CodePathSegment.markUsed(headSegment); + analyzer.emit(eventName, [headSegment, node]); + } + } +} + +/** + * Updates the current segment with empty. + * This is called at the last of functions or the program. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function leaveFromCurrentSegment(analyzer, node) { + const state = CodePath.getState(analyzer.codePath); + const currentSegments = state.currentSegments; + + for (let i = 0; i < currentSegments.length; ++i) { + const currentSegment = currentSegments[i]; + const eventName = currentSegment.reachable + ? "onCodePathSegmentEnd" + : "onUnreachableCodePathSegmentEnd"; + + debug.dump(`${eventName} ${currentSegment.id}`); + + analyzer.emit(eventName, [currentSegment, node]); + } + + state.currentSegments = []; +} + +/** + * Updates the code path due to the position of a given node in the parent node + * thereof. + * + * For example, if the node is `parent.consequent`, this creates a fork from the + * current path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function preprocess(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + const parent = node.parent; + + switch (parent.type) { + // The `arguments.length == 0` case is in `postprocess` function. + case "CallExpression": + if ( + parent.optional === true && + parent.arguments.length >= 1 && + parent.arguments[0] === node + ) { + state.makeOptionalRight(); + } + break; + case "MemberExpression": + if (parent.optional === true && parent.property === node) { + state.makeOptionalRight(); + } + break; + + case "LogicalExpression": + if ( + parent.right === node && + isHandledLogicalOperator(parent.operator) + ) { + state.makeLogicalRight(); + } + break; + + case "AssignmentExpression": + if ( + parent.right === node && + isLogicalAssignmentOperator(parent.operator) + ) { + state.makeLogicalRight(); + } + break; + + case "ConditionalExpression": + case "IfStatement": + /* + * Fork if this node is at `consequent`/`alternate`. + * `popForkContext()` exists at `IfStatement:exit` and + * `ConditionalExpression:exit`. + */ + if (parent.consequent === node) { + state.makeIfConsequent(); + } else if (parent.alternate === node) { + state.makeIfAlternate(); + } + break; + + case "SwitchCase": + if (parent.consequent[0] === node) { + state.makeSwitchCaseBody(false, !parent.test); + } + break; + + case "TryStatement": + if (parent.handler === node) { + state.makeCatchBlock(); + } else if (parent.finalizer === node) { + state.makeFinallyBlock(); + } + break; + + case "WhileStatement": + if (parent.test === node) { + state.makeWhileTest(getBooleanValueIfSimpleConstant(node)); + } else { + assert(parent.body === node); + state.makeWhileBody(); + } + break; + + case "DoWhileStatement": + if (parent.body === node) { + state.makeDoWhileBody(); + } else { + assert(parent.test === node); + state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node)); + } + break; + + case "ForStatement": + if (parent.test === node) { + state.makeForTest(getBooleanValueIfSimpleConstant(node)); + } else if (parent.update === node) { + state.makeForUpdate(); + } else if (parent.body === node) { + state.makeForBody(); + } + break; + + case "ForInStatement": + case "ForOfStatement": + if (parent.left === node) { + state.makeForInOfLeft(); + } else if (parent.right === node) { + state.makeForInOfRight(); + } else { + assert(parent.body === node); + state.makeForInOfBody(); + } + break; + + case "AssignmentPattern": + /* + * Fork if this node is at `right`. + * `left` is executed always, so it uses the current path. + * `popForkContext()` exists at `AssignmentPattern:exit`. + */ + if (parent.right === node) { + state.pushForkContext(); + state.forkBypassPath(); + state.forkPath(); + } + break; + + default: + break; + } +} + +/** + * Updates the code path due to the type of a given node in entering. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function processCodePathToEnter(analyzer, node) { + let codePath = analyzer.codePath; + let state = codePath && CodePath.getState(codePath); + const parent = node.parent; + + /** + * Creates a new code path and trigger the onCodePathStart event + * based on the currently selected node. + * @param {string} origin The reason the code path was started. + * @returns {void} + */ + function startCodePath(origin) { + if (codePath) { + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + debug.dumpState(node, state, false); + } + + // Create the code path of this scope. + codePath = analyzer.codePath = new CodePath({ + id: analyzer.idGenerator.next(), + origin, + upper: codePath, + onLooped: analyzer.onLooped, + }); + state = CodePath.getState(codePath); + + // Emits onCodePathStart events. + debug.dump(`onCodePathStart ${codePath.id}`); + analyzer.emit("onCodePathStart", [codePath, node]); + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to start a new code path in this + * case. + */ + if (isPropertyDefinitionValue(node)) { + startCodePath("class-field-initializer"); + + /* + * Intentional fall through because `node` needs to also be + * processed by the code below. For example, if we have: + * + * class Foo { + * a = () => {} + * } + * + * In this case, we also need start a second code path. + */ + } + + switch (node.type) { + case "Program": + startCodePath("program"); + break; + + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + startCodePath("function"); + break; + + case "StaticBlock": + startCodePath("class-static-block"); + break; + + case "ChainExpression": + state.pushChainContext(); + break; + case "CallExpression": + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + case "MemberExpression": + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + + case "LogicalExpression": + if (isHandledLogicalOperator(node.operator)) { + state.pushChoiceContext( + node.operator, + isForkingByTrueOrFalse(node), + ); + } + break; + + case "AssignmentExpression": + if (isLogicalAssignmentOperator(node.operator)) { + state.pushChoiceContext( + node.operator.slice(0, -1), // removes `=` from the end + isForkingByTrueOrFalse(node), + ); + } + break; + + case "ConditionalExpression": + case "IfStatement": + state.pushChoiceContext("test", false); + break; + + case "SwitchStatement": + state.pushSwitchContext( + node.cases.some(isCaseNode), + getLabel(node), + ); + break; + + case "TryStatement": + state.pushTryContext(Boolean(node.finalizer)); + break; + + case "SwitchCase": + /* + * Fork if this node is after the 2st node in `cases`. + * It's similar to `else` blocks. + * The next `test` node is processed in this path. + */ + if (parent.discriminant !== node && parent.cases[0] !== node) { + state.forkPath(); + } + break; + + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + state.pushLoopContext(node.type, getLabel(node)); + break; + + case "LabeledStatement": + if (!breakableTypePattern.test(node.body.type)) { + state.pushBreakContext(false, node.label.name); + } + break; + + default: + break; + } + + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + debug.dumpState(node, state, false); +} + +/** + * Updates the code path due to the type of a given node in leaving. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function processCodePathToExit(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + let dontForward = false; + + switch (node.type) { + case "ChainExpression": + state.popChainContext(); + break; + + case "IfStatement": + case "ConditionalExpression": + state.popChoiceContext(); + break; + + case "LogicalExpression": + if (isHandledLogicalOperator(node.operator)) { + state.popChoiceContext(); + } + break; + + case "AssignmentExpression": + if (isLogicalAssignmentOperator(node.operator)) { + state.popChoiceContext(); + } + break; + + case "SwitchStatement": + state.popSwitchContext(); + break; + + case "SwitchCase": + /* + * This is the same as the process at the 1st `consequent` node in + * `preprocess` function. + * Must do if this `consequent` is empty. + */ + if (node.consequent.length === 0) { + state.makeSwitchCaseBody(true, !node.test); + } + if (state.forkContext.reachable) { + dontForward = true; + } + break; + + case "TryStatement": + state.popTryContext(); + break; + + case "BreakStatement": + forwardCurrentToHead(analyzer, node); + state.makeBreak(node.label && node.label.name); + dontForward = true; + break; + + case "ContinueStatement": + forwardCurrentToHead(analyzer, node); + state.makeContinue(node.label && node.label.name); + dontForward = true; + break; + + case "ReturnStatement": + forwardCurrentToHead(analyzer, node); + state.makeReturn(); + dontForward = true; + break; + + case "ThrowStatement": + forwardCurrentToHead(analyzer, node); + state.makeThrow(); + dontForward = true; + break; + + case "Identifier": + if (isIdentifierReference(node)) { + state.makeFirstThrowablePathInTryBlock(); + dontForward = true; + } + break; + + case "CallExpression": + case "ImportExpression": + case "MemberExpression": + case "NewExpression": + case "YieldExpression": + state.makeFirstThrowablePathInTryBlock(); + break; + + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + state.popLoopContext(); + break; + + case "AssignmentPattern": + state.popForkContext(); + break; + + case "LabeledStatement": + if (!breakableTypePattern.test(node.body.type)) { + state.popBreakContext(); + } + break; + + default: + break; + } + + // Emits onCodePathSegmentStart events if updated. + if (!dontForward) { + forwardCurrentToHead(analyzer, node); + } + debug.dumpState(node, state, true); +} + +/** + * Updates the code path to finalize the current code path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function postprocess(analyzer, node) { + /** + * Ends the code path for the current node. + * @returns {void} + */ + function endCodePath() { + let codePath = analyzer.codePath; + + // Mark the current path as the final node. + CodePath.getState(codePath).makeFinal(); + + // Emits onCodePathSegmentEnd event of the current segments. + leaveFromCurrentSegment(analyzer, node); + + // Emits onCodePathEnd event of this code path. + debug.dump(`onCodePathEnd ${codePath.id}`); + analyzer.emit("onCodePathEnd", [codePath, node]); + debug.dumpDot(codePath); + + codePath = analyzer.codePath = analyzer.codePath.upper; + if (codePath) { + debug.dumpState(node, CodePath.getState(codePath), true); + } + } + + switch (node.type) { + case "Program": + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "StaticBlock": { + endCodePath(); + break; + } + + // The `arguments.length >= 1` case is in `preprocess` function. + case "CallExpression": + if (node.optional === true && node.arguments.length === 0) { + CodePath.getState(analyzer.codePath).makeOptionalRight(); + } + break; + + default: + break; + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to end a code path in this + * case. + * + * We need to check after the other checks in order to close the + * code paths in the correct order for code like this: + * + * + * class Foo { + * a = () => {} + * } + * + * In this case, The ArrowFunctionExpression code path is closed first + * and then we need to close the code path for the PropertyDefinition + * value. + */ + if (isPropertyDefinitionValue(node)) { + endCodePath(); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The class to analyze code paths. + * This class implements the EventGenerator interface. + */ +class CodePathAnalyzer { + /** + * @param {EventGenerator} eventGenerator An event generator to wrap. + */ + constructor(eventGenerator) { + this.original = eventGenerator; + this.emit = eventGenerator.emit; + this.codePath = null; + this.idGenerator = new IdGenerator("s"); + this.currentNode = null; + this.onLooped = this.onLooped.bind(this); + } + + /** + * Does the process to enter a given AST node. + * This updates state of analysis and calls `enterNode` of the wrapped. + * @param {ASTNode} node A node which is entering. + * @returns {void} + */ + enterNode(node) { + this.currentNode = node; + + // Updates the code path due to node's position in its parent node. + if (node.parent) { + preprocess(this, node); + } + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToEnter(this, node); + + // Emits node events. + this.original.enterNode(node); + + this.currentNode = null; + } + + /** + * Does the process to leave a given AST node. + * This updates state of analysis and calls `leaveNode` of the wrapped. + * @param {ASTNode} node A node which is leaving. + * @returns {void} + */ + leaveNode(node) { + this.currentNode = node; + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToExit(this, node); + + // Emits node events. + this.original.leaveNode(node); + + // Emits the last onCodePathStart/onCodePathSegmentStart events. + postprocess(this, node); + + this.currentNode = null; + } + + /** + * This is called on a code path looped. + * Then this raises a looped event. + * @param {CodePathSegment} fromSegment A segment of prev. + * @param {CodePathSegment} toSegment A segment of next. + * @returns {void} + */ + onLooped(fromSegment, toSegment) { + if (fromSegment.reachable && toSegment.reachable) { + debug.dump( + `onCodePathSegmentLoop ${fromSegment.id} -> ${toSegment.id}`, + ); + this.emit("onCodePathSegmentLoop", [ + fromSegment, + toSegment, + this.currentNode, + ]); + } + } +} + +module.exports = CodePathAnalyzer; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js b/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js new file mode 100644 index 00000000..fa495018 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js @@ -0,0 +1,262 @@ +/** + * @fileoverview The CodePathSegment class. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const debug = require("./debug-helpers"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given segment is reachable. + * @param {CodePathSegment} segment A segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A code path segment. + * + * Each segment is arranged in a series of linked lists (implemented by arrays) + * that keep track of the previous and next segments in a code path. In this way, + * you can navigate between all segments in any code path so long as you have a + * reference to any segment in that code path. + * + * When first created, the segment is in a detached state, meaning that it knows the + * segments that came before it but those segments don't know that this new segment + * follows it. Only when `CodePathSegment#markUsed()` is called on a segment does it + * officially become part of the code path by updating the previous segments to know + * that this new segment follows. + */ +class CodePathSegment { + /** + * Creates a new instance. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * This array includes unreachable segments. + * @param {boolean} reachable A flag which shows this is reachable. + */ + constructor(id, allPrevSegments, reachable) { + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * An array of the next reachable segments. + * @type {CodePathSegment[]} + */ + this.nextSegments = []; + + /** + * An array of the previous reachable segments. + * @type {CodePathSegment[]} + */ + this.prevSegments = allPrevSegments.filter(isReachable); + + /** + * An array of all next segments including reachable and unreachable. + * @type {CodePathSegment[]} + */ + this.allNextSegments = []; + + /** + * An array of all previous segments including reachable and unreachable. + * @type {CodePathSegment[]} + */ + this.allPrevSegments = allPrevSegments; + + /** + * A flag which shows this is reachable. + * @type {boolean} + */ + this.reachable = reachable; + + // Internal data. + Object.defineProperty(this, "internal", { + value: { + // determines if the segment has been attached to the code path + used: false, + + // array of previous segments coming from the end of a loop + loopedPrevSegments: [], + }, + }); + + /* c8 ignore start */ + if (debug.enabled) { + this.internal.nodes = []; + } /* c8 ignore stop */ + } + + /** + * Checks a given previous segment is coming from the end of a loop. + * @param {CodePathSegment} segment A previous segment to check. + * @returns {boolean} `true` if the segment is coming from the end of a loop. + */ + isLoopedPrevSegment(segment) { + return this.internal.loopedPrevSegments.includes(segment); + } + + /** + * Creates the root segment. + * @param {string} id An identifier. + * @returns {CodePathSegment} The created segment. + */ + static newRoot(id) { + return new CodePathSegment(id, [], true); + } + + /** + * Creates a new segment and appends it after the given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments + * to append to. + * @returns {CodePathSegment} The created segment. + */ + static newNext(id, allPrevSegments) { + return new CodePathSegment( + id, + CodePathSegment.flattenUnusedSegments(allPrevSegments), + allPrevSegments.some(isReachable), + ); + } + + /** + * Creates an unreachable segment and appends it after the given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newUnreachable(id, allPrevSegments) { + const segment = new CodePathSegment( + id, + CodePathSegment.flattenUnusedSegments(allPrevSegments), + false, + ); + + /* + * In `if (a) return a; foo();` case, the unreachable segment preceded by + * the return statement is not used but must not be removed. + */ + CodePathSegment.markUsed(segment); + + return segment; + } + + /** + * Creates a segment that follows given segments. + * This factory method does not connect with `allPrevSegments`. + * But this inherits `reachable` flag. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newDisconnected(id, allPrevSegments) { + return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); + } + + /** + * Marks a given segment as used. + * + * And this function registers the segment into the previous segments as a next. + * @param {CodePathSegment} segment A segment to mark. + * @returns {void} + */ + static markUsed(segment) { + if (segment.internal.used) { + return; + } + segment.internal.used = true; + + let i; + + if (segment.reachable) { + /* + * If the segment is reachable, then it's officially part of the + * code path. This loops through all previous segments to update + * their list of next segments. Because the segment is reachable, + * it's added to both `nextSegments` and `allNextSegments`. + */ + for (i = 0; i < segment.allPrevSegments.length; ++i) { + const prevSegment = segment.allPrevSegments[i]; + + prevSegment.allNextSegments.push(segment); + prevSegment.nextSegments.push(segment); + } + } else { + /* + * If the segment is not reachable, then it's not officially part of the + * code path. This loops through all previous segments to update + * their list of next segments. Because the segment is not reachable, + * it's added only to `allNextSegments`. + */ + for (i = 0; i < segment.allPrevSegments.length; ++i) { + segment.allPrevSegments[i].allNextSegments.push(segment); + } + } + } + + /** + * Marks a previous segment as looped. + * @param {CodePathSegment} segment A segment. + * @param {CodePathSegment} prevSegment A previous segment to mark. + * @returns {void} + */ + static markPrevSegmentAsLooped(segment, prevSegment) { + segment.internal.loopedPrevSegments.push(prevSegment); + } + + /** + * Creates a new array based on an array of segments. If any segment in the + * array is unused, then it is replaced by all of its previous segments. + * All used segments are returned as-is without replacement. + * @param {CodePathSegment[]} segments The array of segments to flatten. + * @returns {CodePathSegment[]} The flattened array. + */ + static flattenUnusedSegments(segments) { + const done = new Set(); + + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + // Ignores duplicated. + if (done.has(segment)) { + continue; + } + + // Use previous segments if unused. + if (!segment.internal.used) { + for (let j = 0; j < segment.allPrevSegments.length; ++j) { + const prevSegment = segment.allPrevSegments[j]; + + if (!done.has(prevSegment)) { + done.add(prevSegment); + } + } + } else { + done.add(segment); + } + } + + return [...done]; + } +} + +module.exports = CodePathSegment; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js b/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js new file mode 100644 index 00000000..3ed4a7bc --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js @@ -0,0 +1,2370 @@ +/** + * @fileoverview A class to manage state of generating a code path. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const CodePathSegment = require("./code-path-segment"), + ForkContext = require("./fork-context"); + +//----------------------------------------------------------------------------- +// Contexts +//----------------------------------------------------------------------------- + +/** + * Represents the context in which a `break` statement can be used. + * + * A `break` statement without a label is only valid in a few places in + * JavaScript: any type of loop or a `switch` statement. Otherwise, `break` + * without a label causes a syntax error. For these contexts, `breakable` is + * set to `true` to indicate that a `break` without a label is valid. + * + * However, a `break` statement with a label is also valid inside of a labeled + * statement. For example, this is valid: + * + * a : { + * break a; + * } + * + * The `breakable` property is set false for labeled statements to indicate + * that `break` without a label is invalid. + */ +class BreakContext { + /** + * Creates a new instance. + * @param {BreakContext} upperContext The previous `BreakContext`. + * @param {boolean} breakable Indicates if we are inside a statement where + * `break` without a label will exit the statement. + * @param {string|null} label The label for the statement. + * @param {ForkContext} forkContext The current fork context. + */ + constructor(upperContext, breakable, label, forkContext) { + /** + * The previous `BreakContext` + * @type {BreakContext} + */ + this.upper = upperContext; + + /** + * Indicates if we are inside a statement where `break` without a label + * will exit the statement. + * @type {boolean} + */ + this.breakable = breakable; + + /** + * The label associated with the statement. + * @type {string|null} + */ + this.label = label; + + /** + * The fork context for the `break`. + * @type {ForkContext} + */ + this.brokenForkContext = ForkContext.newEmpty(forkContext); + } +} + +/** + * Represents the context for `ChainExpression` nodes. + */ +class ChainContext { + /** + * Creates a new instance. + * @param {ChainContext} upperContext The previous `ChainContext`. + */ + constructor(upperContext) { + /** + * The previous `ChainContext` + * @type {ChainContext} + */ + this.upper = upperContext; + + /** + * The number of choice contexts inside of the `ChainContext`. + * @type {number} + */ + this.choiceContextCount = 0; + } +} + +/** + * Represents a choice in the code path. + * + * Choices are created by logical operators such as `&&`, loops, conditionals, + * and `if` statements. This is the point at which the code path has a choice of + * which direction to go. + * + * The result of a choice might be in the left (test) expression of another choice, + * and in that case, may create a new fork. For example, `a || b` is a choice + * but does not create a new fork because the result of the expression is + * not used as the test expression in another expression. In this case, + * `isForkingAsResult` is false. In the expression `a || b || c`, the `a || b` + * expression appears as the test expression for `|| c`, so the + * result of `a || b` creates a fork because execution may or may not + * continue to `|| c`. `isForkingAsResult` for `a || b` in this case is true + * while `isForkingAsResult` for `|| c` is false. (`isForkingAsResult` is always + * false for `if` statements, conditional expressions, and loops.) + * + * All of the choices except one (`??`) operate on a true/false fork, meaning if + * true go one way and if false go the other (tracked by `trueForkContext` and + * `falseForkContext`). The `??` operator doesn't operate on true/false because + * the left expression is evaluated to be nullish or not, so only if nullish do + * we fork to the right expression (tracked by `nullishForkContext`). + */ +class ChoiceContext { + /** + * Creates a new instance. + * @param {ChoiceContext} upperContext The previous `ChoiceContext`. + * @param {string} kind The kind of choice. If it's a logical or assignment expression, this + * is `"&&"` or `"||"` or `"??"`; if it's an `if` statement or + * conditional expression, this is `"test"`; otherwise, this is `"loop"`. + * @param {boolean} isForkingAsResult Indicates if the result of the choice + * creates a fork. + * @param {ForkContext} forkContext The containing `ForkContext`. + */ + constructor(upperContext, kind, isForkingAsResult, forkContext) { + /** + * The previous `ChoiceContext` + * @type {ChoiceContext} + */ + this.upper = upperContext; + + /** + * The kind of choice. If it's a logical or assignment expression, this + * is `"&&"` or `"||"` or `"??"`; if it's an `if` statement or + * conditional expression, this is `"test"`; otherwise, this is `"loop"`. + * @type {string} + */ + this.kind = kind; + + /** + * Indicates if the result of the choice forks the code path. + * @type {boolean} + */ + this.isForkingAsResult = isForkingAsResult; + + /** + * The fork context for the `true` path of the choice. + * @type {ForkContext} + */ + this.trueForkContext = ForkContext.newEmpty(forkContext); + + /** + * The fork context for the `false` path of the choice. + * @type {ForkContext} + */ + this.falseForkContext = ForkContext.newEmpty(forkContext); + + /** + * The fork context for when the choice result is `null` or `undefined`. + * @type {ForkContext} + */ + this.nullishForkContext = ForkContext.newEmpty(forkContext); + + /** + * Indicates if any of `trueForkContext`, `falseForkContext`, or + * `nullishForkContext` have been updated with segments from a child context. + * @type {boolean} + */ + this.processed = false; + } +} + +/** + * Base class for all loop contexts. + */ +class LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string} type The AST node's `type` for the loop. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, type, label, breakContext) { + /** + * The previous `LoopContext`. + * @type {LoopContext} + */ + this.upper = upperContext; + + /** + * The AST node's `type` for the loop. + * @type {string} + */ + this.type = type; + + /** + * The label for the loop from an enclosing `LabeledStatement`. + * @type {string|null} + */ + this.label = label; + + /** + * The fork context for when `break` is encountered. + * @type {ForkContext} + */ + this.brokenForkContext = breakContext.brokenForkContext; + } +} + +/** + * Represents the context for a `while` loop. + */ +class WhileLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, label, breakContext) { + super(upperContext, "WhileStatement", label, breakContext); + + /** + * The hardcoded literal boolean test condition for + * the loop. Used to catch infinite or skipped loops. + * @type {boolean|undefined} + */ + this.test = void 0; + + /** + * The segments representing the test condition where `continue` will + * jump to. The test condition will typically have just one segment but + * it's possible for there to be more than one. + * @type {Array|null} + */ + this.continueDestSegments = null; + } +} + +/** + * Represents the context for a `do-while` loop. + */ +class DoWhileLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + * @param {ForkContext} forkContext The enclosing fork context. + */ + constructor(upperContext, label, breakContext, forkContext) { + super(upperContext, "DoWhileStatement", label, breakContext); + + /** + * The hardcoded literal boolean test condition for + * the loop. Used to catch infinite or skipped loops. + * @type {boolean|undefined} + */ + this.test = void 0; + + /** + * The segments at the start of the loop body. This is the only loop + * where the test comes at the end, so the first iteration always + * happens and we need a reference to the first statements. + * @type {Array|null} + */ + this.entrySegments = null; + + /** + * The fork context to follow when a `continue` is found. + * @type {ForkContext} + */ + this.continueForkContext = ForkContext.newEmpty(forkContext); + } +} + +/** + * Represents the context for a `for` loop. + */ +class ForLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, label, breakContext) { + super(upperContext, "ForStatement", label, breakContext); + + /** + * The hardcoded literal boolean test condition for + * the loop. Used to catch infinite or skipped loops. + * @type {boolean|undefined} + */ + this.test = void 0; + + /** + * The end of the init expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * an init expression. + * @type {Array|null} + */ + this.endOfInitSegments = null; + + /** + * The start of the test expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * a test expression. + * @type {Array|null} + */ + this.testSegments = null; + + /** + * The end of the test expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * a test expression. + * @type {Array|null} + */ + this.endOfTestSegments = null; + + /** + * The start of the update expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * an update expression. + * @type {Array|null} + */ + this.updateSegments = null; + + /** + * The end of the update expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * an update expression. + * @type {Array|null} + */ + this.endOfUpdateSegments = null; + + /** + * The segments representing the test condition where `continue` will + * jump to. The test condition will typically have just one segment but + * it's possible for there to be more than one. This may change during the + * lifetime of the instance as we traverse the loop because some loops + * don't have an update expression. When there is an update expression, this + * will end up pointing to that expression; otherwise it will end up pointing + * to the test expression. + * @type {Array|null} + */ + this.continueDestSegments = null; + } +} + +/** + * Represents the context for a `for-in` loop. + * + * Terminology: + * - "left" means the part of the loop to the left of the `in` keyword. For + * example, in `for (var x in y)`, the left is `var x`. + * - "right" means the part of the loop to the right of the `in` keyword. For + * example, in `for (var x in y)`, the right is `y`. + */ +class ForInLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, label, breakContext) { + super(upperContext, "ForInStatement", label, breakContext); + + /** + * The segments that came immediately before the start of the loop. + * This allows you to traverse backwards out of the loop into the + * surrounding code. This is necessary to evaluate the right expression + * correctly, as it must be evaluated in the same way as the left + * expression, but the pointer to these segments would otherwise be + * lost if not stored on the instance. Once the right expression has + * been evaluated, this property is no longer used. + * @type {Array|null} + */ + this.prevSegments = null; + + /** + * Segments representing the start of everything to the left of the + * `in` keyword. This can be used to move forward towards + * `endOfLeftSegments`. `leftSegments` and `endOfLeftSegments` are + * effectively the head and tail of a doubly-linked list. + * @type {Array|null} + */ + this.leftSegments = null; + + /** + * Segments representing the end of everything to the left of the + * `in` keyword. This can be used to move backward towards `leftSegments`. + * `leftSegments` and `endOfLeftSegments` are effectively the head + * and tail of a doubly-linked list. + * @type {Array|null} + */ + this.endOfLeftSegments = null; + + /** + * The segments representing the left expression where `continue` will + * jump to. In `for-in` loops, `continue` must always re-execute the + * left expression each time through the loop. This contains the same + * segments as `leftSegments`, but is duplicated here so each loop + * context has the same property pointing to where `continue` should + * end up. + * @type {Array|null} + */ + this.continueDestSegments = null; + } +} + +/** + * Represents the context for a `for-of` loop. + */ +class ForOfLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, label, breakContext) { + super(upperContext, "ForOfStatement", label, breakContext); + + /** + * The segments that came immediately before the start of the loop. + * This allows you to traverse backwards out of the loop into the + * surrounding code. This is necessary to evaluate the right expression + * correctly, as it must be evaluated in the same way as the left + * expression, but the pointer to these segments would otherwise be + * lost if not stored on the instance. Once the right expression has + * been evaluated, this property is no longer used. + * @type {Array|null} + */ + this.prevSegments = null; + + /** + * Segments representing the start of everything to the left of the + * `of` keyword. This can be used to move forward towards + * `endOfLeftSegments`. `leftSegments` and `endOfLeftSegments` are + * effectively the head and tail of a doubly-linked list. + * @type {Array|null} + */ + this.leftSegments = null; + + /** + * Segments representing the end of everything to the left of the + * `of` keyword. This can be used to move backward towards `leftSegments`. + * `leftSegments` and `endOfLeftSegments` are effectively the head + * and tail of a doubly-linked list. + * @type {Array|null} + */ + this.endOfLeftSegments = null; + + /** + * The segments representing the left expression where `continue` will + * jump to. In `for-in` loops, `continue` must always re-execute the + * left expression each time through the loop. This contains the same + * segments as `leftSegments`, but is duplicated here so each loop + * context has the same property pointing to where `continue` should + * end up. + * @type {Array|null} + */ + this.continueDestSegments = null; + } +} + +/** + * Represents the context for any loop. + * @typedef {WhileLoopContext|DoWhileLoopContext|ForLoopContext|ForInLoopContext|ForOfLoopContext} LoopContext + */ + +/** + * Represents the context for a `switch` statement. + */ +class SwitchContext { + /** + * Creates a new instance. + * @param {SwitchContext} upperContext The previous context. + * @param {boolean} hasCase Indicates if there is at least one `case` statement. + * `default` doesn't count. + */ + constructor(upperContext, hasCase) { + /** + * The previous context. + * @type {SwitchContext} + */ + this.upper = upperContext; + + /** + * Indicates if there is at least one `case` statement. `default` doesn't count. + * @type {boolean} + */ + this.hasCase = hasCase; + + /** + * The `default` keyword. + * @type {Array|null} + */ + this.defaultSegments = null; + + /** + * The default case body starting segments. + * @type {Array|null} + */ + this.defaultBodySegments = null; + + /** + * Indicates if a `default` case and is empty exists. + * @type {boolean} + */ + this.foundEmptyDefault = false; + + /** + * Indicates that a `default` exists and is the last case. + * @type {boolean} + */ + this.lastIsDefault = false; + + /** + * The number of fork contexts created. This is equivalent to the + * number of `case` statements plus a `default` statement (if present). + * @type {number} + */ + this.forkCount = 0; + } +} + +/** + * Represents the context for a `try` statement. + */ +class TryContext { + /** + * Creates a new instance. + * @param {TryContext} upperContext The previous context. + * @param {boolean} hasFinalizer Indicates if the `try` statement has a + * `finally` block. + * @param {ForkContext} forkContext The enclosing fork context. + */ + constructor(upperContext, hasFinalizer, forkContext) { + /** + * The previous context. + * @type {TryContext} + */ + this.upper = upperContext; + + /** + * Indicates if the `try` statement has a `finally` block. + * @type {boolean} + */ + this.hasFinalizer = hasFinalizer; + + /** + * Tracks the traversal position inside of the `try` statement. This is + * used to help determine the context necessary to create paths because + * a `try` statement may or may not have `catch` or `finally` blocks, + * and code paths behave differently in those blocks. + * @type {"try"|"catch"|"finally"} + */ + this.position = "try"; + + /** + * If the `try` statement has a `finally` block, this affects how a + * `return` statement behaves in the `try` block. Without `finally`, + * `return` behaves as usual and doesn't require a fork; with `finally`, + * `return` forks into the `finally` block, so we need a fork context + * to track it. + * @type {ForkContext|null} + */ + this.returnedForkContext = hasFinalizer + ? ForkContext.newEmpty(forkContext) + : null; + + /** + * When a `throw` occurs inside of a `try` block, the code path forks + * into the `catch` or `finally` blocks, and this fork context tracks + * that path. + * @type {ForkContext} + */ + this.thrownForkContext = ForkContext.newEmpty(forkContext); + + /** + * Indicates if the last segment in the `try` block is reachable. + * @type {boolean} + */ + this.lastOfTryIsReachable = false; + + /** + * Indicates if the last segment in the `catch` block is reachable. + * @type {boolean} + */ + this.lastOfCatchIsReachable = false; + } +} + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Adds given segments into the `dest` array. + * If the `others` array does not include the given segments, adds to the `all` + * array as well. + * + * This adds only reachable and used segments. + * @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} all The unified destination array (`finalSegments`). + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ +function addToReturnedOrThrown(dest, others, all, segments) { + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + dest.push(segment); + if (!others.includes(segment)) { + all.push(segment); + } + } +} + +/** + * Gets a loop context for a `continue` statement based on a given label. + * @param {CodePathState} state The state to search within. + * @param {string|null} label The label of a `continue` statement. + * @returns {LoopContext} A loop-context for a `continue` statement. + */ +function getContinueContext(state, label) { + if (!label) { + return state.loopContext; + } + + let context = state.loopContext; + + while (context) { + if (context.label === label) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; +} + +/** + * Gets a context for a `break` statement. + * @param {CodePathState} state The state to search within. + * @param {string|null} label The label of a `break` statement. + * @returns {BreakContext} A context for a `break` statement. + */ +function getBreakContext(state, label) { + let context = state.breakContext; + + while (context) { + if (label ? context.label === label : context.breakable) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; +} + +/** + * Gets a context for a `return` statement. There is just one special case: + * if there is a `try` statement with a `finally` block, because that alters + * how `return` behaves; otherwise, this just passes through the given state. + * @param {CodePathState} state The state to search within + * @returns {TryContext|CodePathState} A context for a `return` statement. + */ +function getReturnContext(state) { + let context = state.tryContext; + + while (context) { + if (context.hasFinalizer && context.position !== "finally") { + return context; + } + context = context.upper; + } + + return state; +} + +/** + * Gets a context for a `throw` statement. There is just one special case: + * if there is a `try` statement with a `finally` block and we are inside of + * a `catch` because that changes how `throw` behaves; otherwise, this just + * passes through the given state. + * @param {CodePathState} state The state to search within. + * @returns {TryContext|CodePathState} A context for a `throw` statement. + */ +function getThrowContext(state) { + let context = state.tryContext; + + while (context) { + if ( + context.position === "try" || + (context.hasFinalizer && context.position === "catch") + ) { + return context; + } + context = context.upper; + } + + return state; +} + +/** + * Removes a given value from a given array. + * @param {any[]} elements An array to remove the specific element. + * @param {any} value The value to be removed. + * @returns {void} + */ +function removeFromArray(elements, value) { + elements.splice(elements.indexOf(value), 1); +} + +/** + * Disconnect given segments. + * + * This is used in a process for switch statements. + * If there is the "default" chunk before other cases, the order is different + * between node's and running's. + * @param {CodePathSegment[]} prevSegments Forward segments to disconnect. + * @param {CodePathSegment[]} nextSegments Backward segments to disconnect. + * @returns {void} + */ +function disconnectSegments(prevSegments, nextSegments) { + for (let i = 0; i < prevSegments.length; ++i) { + const prevSegment = prevSegments[i]; + const nextSegment = nextSegments[i]; + + removeFromArray(prevSegment.nextSegments, nextSegment); + removeFromArray(prevSegment.allNextSegments, nextSegment); + removeFromArray(nextSegment.prevSegments, prevSegment); + removeFromArray(nextSegment.allPrevSegments, prevSegment); + } +} + +/** + * Creates looping path between two arrays of segments, ensuring that there are + * paths going between matching segments in the arrays. + * @param {CodePathState} state The state to operate on. + * @param {CodePathSegment[]} unflattenedFromSegments Segments which are source. + * @param {CodePathSegment[]} unflattenedToSegments Segments which are destination. + * @returns {void} + */ +function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) { + const fromSegments = CodePathSegment.flattenUnusedSegments( + unflattenedFromSegments, + ); + const toSegments = CodePathSegment.flattenUnusedSegments( + unflattenedToSegments, + ); + const end = Math.min(fromSegments.length, toSegments.length); + + /* + * This loop effectively updates a doubly-linked list between two collections + * of segments making sure that segments in the same array indices are + * combined to create a path. + */ + for (let i = 0; i < end; ++i) { + // get the segments in matching array indices + const fromSegment = fromSegments[i]; + const toSegment = toSegments[i]; + + /* + * If the destination segment is reachable, then create a path from the + * source segment to the destination segment. + */ + if (toSegment.reachable) { + fromSegment.nextSegments.push(toSegment); + } + + /* + * If the source segment is reachable, then create a path from the + * destination segment back to the source segment. + */ + if (fromSegment.reachable) { + toSegment.prevSegments.push(fromSegment); + } + + /* + * Also update the arrays that don't care if the segments are reachable + * or not. This should always happen regardless of anything else. + */ + fromSegment.allNextSegments.push(toSegment); + toSegment.allPrevSegments.push(fromSegment); + + /* + * If the destination segment has at least two previous segments in its + * path then that means there was one previous segment before this iteration + * of the loop was executed. So, we need to mark the source segment as + * looped. + */ + if (toSegment.allPrevSegments.length >= 2) { + CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment); + } + + // let the code path analyzer know that there's been a loop created + state.notifyLooped(fromSegment, toSegment); + } +} + +/** + * Finalizes segments of `test` chunk of a ForStatement. + * + * - Adds `false` paths to paths which are leaving from the loop. + * - Sets `true` paths to paths which go to the body. + * @param {LoopContext} context A loop context to modify. + * @param {ChoiceContext} choiceContext A choice context of this loop. + * @param {CodePathSegment[]} head The current head paths. + * @returns {void} + */ +function finalizeTestSegmentsOfFor(context, choiceContext, head) { + /* + * If this choice context doesn't already contain paths from a + * child context, then add the current head to each potential path. + */ + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(head); + choiceContext.falseForkContext.add(head); + choiceContext.nullishForkContext.add(head); + } + + /* + * If the test condition isn't a hardcoded truthy value, then `break` + * must follow the same path as if the test condition is false. To represent + * that, we append the path for when the loop test is false (represented by + * `falseForkContext`) to the `brokenForkContext`. + */ + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + + context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A class which manages state to analyze code paths. + */ +class CodePathState { + /** + * Creates a new instance. + * @param {IdGenerator} idGenerator An id generator to generate id for code + * path segments. + * @param {Function} onLooped A callback function to notify looping. + */ + constructor(idGenerator, onLooped) { + /** + * The ID generator to use when creating new segments. + * @type {IdGenerator} + */ + this.idGenerator = idGenerator; + + /** + * A callback function to call when there is a loop. + * @type {Function} + */ + this.notifyLooped = onLooped; + + /** + * The root fork context for this state. + * @type {ForkContext} + */ + this.forkContext = ForkContext.newRoot(idGenerator); + + /** + * Context for logical expressions, conditional expressions, `if` statements, + * and loops. + * @type {ChoiceContext} + */ + this.choiceContext = null; + + /** + * Context for `switch` statements. + * @type {SwitchContext} + */ + this.switchContext = null; + + /** + * Context for `try` statements. + * @type {TryContext} + */ + this.tryContext = null; + + /** + * Context for loop statements. + * @type {LoopContext} + */ + this.loopContext = null; + + /** + * Context for `break` statements. + * @type {BreakContext} + */ + this.breakContext = null; + + /** + * Context for `ChainExpression` nodes. + * @type {ChainContext} + */ + this.chainContext = null; + + /** + * An array that tracks the current segments in the state. The array + * starts empty and segments are added with each `onCodePathSegmentStart` + * event and removed with each `onCodePathSegmentEnd` event. Effectively, + * this is tracking the code path segment traversal as the state is + * modified. + * @type {Array} + */ + this.currentSegments = []; + + /** + * Tracks the starting segment for this path. This value never changes. + * @type {CodePathSegment} + */ + this.initialSegment = this.forkContext.head[0]; + + /** + * The final segments of the code path which are either `return` or `throw`. + * This is a union of the segments in `returnedForkContext` and `thrownForkContext`. + * @type {Array} + */ + this.finalSegments = []; + + /** + * The final segments of the code path which are `return`. These + * segments are also contained in `finalSegments`. + * @type {Array} + */ + this.returnedForkContext = []; + + /** + * The final segments of the code path which are `throw`. These + * segments are also contained in `finalSegments`. + * @type {Array} + */ + this.thrownForkContext = []; + + /* + * We add an `add` method so that these look more like fork contexts and + * can be used interchangeably when a fork context is needed to add more + * segments to a path. + * + * Ultimately, we want anything added to `returned` or `thrown` to also + * be added to `final`. We only add reachable and used segments to these + * arrays. + */ + const final = this.finalSegments; + const returned = this.returnedForkContext; + const thrown = this.thrownForkContext; + + returned.add = addToReturnedOrThrown.bind( + null, + returned, + thrown, + final, + ); + thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); + } + + /** + * A passthrough property exposing the current pointer as part of the API. + * @type {CodePathSegment[]} + */ + get headSegments() { + return this.forkContext.head; + } + + /** + * The parent forking context. + * This is used for the root of new forks. + * @type {ForkContext} + */ + get parentForkContext() { + const current = this.forkContext; + + return current && current.upper; + } + + /** + * Creates and stacks new forking context. + * @param {boolean} forkLeavingPath A flag which shows being in a + * "finally" block. + * @returns {ForkContext} The created context. + */ + pushForkContext(forkLeavingPath) { + this.forkContext = ForkContext.newEmpty( + this.forkContext, + forkLeavingPath, + ); + + return this.forkContext; + } + + /** + * Pops and merges the last forking context. + * @returns {ForkContext} The last context. + */ + popForkContext() { + const lastContext = this.forkContext; + + this.forkContext = lastContext.upper; + this.forkContext.replaceHead(lastContext.makeNext(0, -1)); + + return lastContext; + } + + /** + * Creates a new path. + * @returns {void} + */ + forkPath() { + this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); + } + + /** + * Creates a bypass path. + * This is used for such as IfStatement which does not have "else" chunk. + * @returns {void} + */ + forkBypassPath() { + this.forkContext.add(this.parentForkContext.head); + } + + //-------------------------------------------------------------------------- + // ConditionalExpression, LogicalExpression, IfStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context for ConditionalExpression, LogicalExpression, AssignmentExpression (logical assignments only), + * IfStatement, WhileStatement, DoWhileStatement, or ForStatement. + * + * LogicalExpressions have cases that it goes different paths between the + * `true` case and the `false` case. + * + * For Example: + * + * if (a || b) { + * foo(); + * } else { + * bar(); + * } + * + * In this case, `b` is evaluated always in the code path of the `else` + * block, but it's not so in the code path of the `if` block. + * So there are 3 paths. + * + * a -> foo(); + * a -> b -> foo(); + * a -> b -> bar(); + * @param {string} kind A kind string. + * If the new context is LogicalExpression's or AssignmentExpression's, this is `"&&"` or `"||"` or `"??"`. + * If it's IfStatement's or ConditionalExpression's, this is `"test"`. + * Otherwise, this is `"loop"`. + * @param {boolean} isForkingAsResult Indicates if the result of the choice + * creates a fork. + * @returns {void} + */ + pushChoiceContext(kind, isForkingAsResult) { + this.choiceContext = new ChoiceContext( + this.choiceContext, + kind, + isForkingAsResult, + this.forkContext, + ); + } + + /** + * Pops the last choice context and finalizes it. + * This is called upon leaving a node that represents a choice. + * @throws {Error} (Unreachable.) + * @returns {ChoiceContext} The popped context. + */ + popChoiceContext() { + const poppedChoiceContext = this.choiceContext; + const forkContext = this.forkContext; + const head = forkContext.head; + + this.choiceContext = poppedChoiceContext.upper; + + switch (poppedChoiceContext.kind) { + case "&&": + case "||": + case "??": + /* + * The `head` are the path of the right-hand operand. + * If we haven't previously added segments from child contexts, + * then we add these segments to all possible forks. + */ + if (!poppedChoiceContext.processed) { + poppedChoiceContext.trueForkContext.add(head); + poppedChoiceContext.falseForkContext.add(head); + poppedChoiceContext.nullishForkContext.add(head); + } + + /* + * If this context is the left (test) expression for another choice + * context, such as `a || b` in the expression `a || b || c`, + * then we take the segments for this context and move them up + * to the parent context. + */ + if (poppedChoiceContext.isForkingAsResult) { + const parentContext = this.choiceContext; + + parentContext.trueForkContext.addAll( + poppedChoiceContext.trueForkContext, + ); + parentContext.falseForkContext.addAll( + poppedChoiceContext.falseForkContext, + ); + parentContext.nullishForkContext.addAll( + poppedChoiceContext.nullishForkContext, + ); + parentContext.processed = true; + + // Exit early so we don't collapse all paths into one. + return poppedChoiceContext; + } + + break; + + case "test": + if (!poppedChoiceContext.processed) { + /* + * The head segments are the path of the `if` block here. + * Updates the `true` path with the end of the `if` block. + */ + poppedChoiceContext.trueForkContext.clear(); + poppedChoiceContext.trueForkContext.add(head); + } else { + /* + * The head segments are the path of the `else` block here. + * Updates the `false` path with the end of the `else` + * block. + */ + poppedChoiceContext.falseForkContext.clear(); + poppedChoiceContext.falseForkContext.add(head); + } + + break; + + case "loop": + /* + * Loops are addressed in `popLoopContext()` so just return + * the context without modification. + */ + return poppedChoiceContext; + + /* c8 ignore next */ + default: + throw new Error("unreachable"); + } + + /* + * Merge the true path with the false path to create a single path. + */ + const combinedForkContext = poppedChoiceContext.trueForkContext; + + combinedForkContext.addAll(poppedChoiceContext.falseForkContext); + forkContext.replaceHead(combinedForkContext.makeNext(0, -1)); + + return poppedChoiceContext; + } + + /** + * Creates a code path segment to represent right-hand operand of a logical + * expression. + * This is called in the preprocessing phase when entering a node. + * @throws {Error} (Unreachable.) + * @returns {void} + */ + makeLogicalRight() { + const currentChoiceContext = this.choiceContext; + const forkContext = this.forkContext; + + if (currentChoiceContext.processed) { + /* + * This context was already assigned segments from a child + * choice context. In this case, we are concerned only about + * the path that does not short-circuit and so ends up on the + * right-hand operand of the logical expression. + */ + let prevForkContext; + + switch (currentChoiceContext.kind) { + case "&&": // if true then go to the right-hand side. + prevForkContext = currentChoiceContext.trueForkContext; + break; + case "||": // if false then go to the right-hand side. + prevForkContext = currentChoiceContext.falseForkContext; + break; + case "??": // Both true/false can short-circuit, so needs the third path to go to the right-hand side. That's nullishForkContext. + prevForkContext = currentChoiceContext.nullishForkContext; + break; + default: + throw new Error("unreachable"); + } + + /* + * Create the segment for the right-hand operand of the logical expression + * and adjust the fork context pointer to point there. The right-hand segment + * is added at the end of all segments in `prevForkContext`. + */ + forkContext.replaceHead(prevForkContext.makeNext(0, -1)); + + /* + * We no longer need this list of segments. + * + * Reset `processed` because we've removed the segments from the child + * choice context. This allows `popChoiceContext()` to continue adding + * segments later. + */ + prevForkContext.clear(); + currentChoiceContext.processed = false; + } else { + /* + * This choice context was not assigned segments from a child + * choice context, which means that it's a terminal logical + * expression. + * + * `head` is the segments for the left-hand operand of the + * logical expression. + * + * Each of the fork contexts below are empty at this point. We choose + * the path(s) that will short-circuit and add the segment for the + * left-hand operand to it. Ultimately, this will be the only segment + * in that path due to the short-circuting, so we are just seeding + * these paths to start. + */ + switch (currentChoiceContext.kind) { + case "&&": + /* + * In most contexts, when a && expression evaluates to false, + * it short circuits, so we need to account for that by setting + * the `falseForkContext` to the left operand. + * + * When a && expression is the left-hand operand for a ?? + * expression, such as `(a && b) ?? c`, a nullish value will + * also short-circuit in a different way than a false value, + * so we also set the `nullishForkContext` to the left operand. + * This path is only used with a ?? expression and is thrown + * away for any other type of logical expression, so it's safe + * to always add. + */ + currentChoiceContext.falseForkContext.add(forkContext.head); + currentChoiceContext.nullishForkContext.add( + forkContext.head, + ); + break; + case "||": // the true path can short-circuit. + currentChoiceContext.trueForkContext.add(forkContext.head); + break; + case "??": // both can short-circuit. + currentChoiceContext.trueForkContext.add(forkContext.head); + currentChoiceContext.falseForkContext.add(forkContext.head); + break; + default: + throw new Error("unreachable"); + } + + /* + * Create the segment for the right-hand operand of the logical expression + * and adjust the fork context pointer to point there. + */ + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + } + + /** + * Makes a code path segment of the `if` block. + * @returns {void} + */ + makeIfConsequent() { + const context = this.choiceContext; + const forkContext = this.forkContext; + + /* + * If any result were not transferred from child contexts, + * this sets the head segments to both cases. + * The head segments are the path of the test expression. + */ + if (!context.processed) { + context.trueForkContext.add(forkContext.head); + context.falseForkContext.add(forkContext.head); + context.nullishForkContext.add(forkContext.head); + } + + context.processed = false; + + // Creates new path from the `true` case. + forkContext.replaceHead(context.trueForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment of the `else` block. + * @returns {void} + */ + makeIfAlternate() { + const context = this.choiceContext; + const forkContext = this.forkContext; + + /* + * The head segments are the path of the `if` block. + * Updates the `true` path with the end of the `if` block. + */ + context.trueForkContext.clear(); + context.trueForkContext.add(forkContext.head); + context.processed = true; + + // Creates new path from the `false` case. + forkContext.replaceHead(context.falseForkContext.makeNext(0, -1)); + } + + //-------------------------------------------------------------------------- + // ChainExpression + //-------------------------------------------------------------------------- + + /** + * Pushes a new `ChainExpression` context to the stack. This method is + * called when entering a `ChainExpression` node. A chain context is used to + * count forking in the optional chain then merge them on the exiting from the + * `ChainExpression` node. + * @returns {void} + */ + pushChainContext() { + this.chainContext = new ChainContext(this.chainContext); + } + + /** + * Pop a `ChainExpression` context from the stack. This method is called on + * exiting from each `ChainExpression` node. This merges all forks of the + * last optional chaining. + * @returns {void} + */ + popChainContext() { + const context = this.chainContext; + + this.chainContext = context.upper; + + // pop all choice contexts of this. + for (let i = context.choiceContextCount; i > 0; --i) { + this.popChoiceContext(); + } + } + + /** + * Create a choice context for optional access. + * This method is called on entering to each `(Call|Member)Expression[optional=true]` node. + * This creates a choice context as similar to `LogicalExpression[operator="??"]` node. + * @returns {void} + */ + makeOptionalNode() { + if (this.chainContext) { + this.chainContext.choiceContextCount += 1; + this.pushChoiceContext("??", false); + } + } + + /** + * Create a fork. + * This method is called on entering to the `arguments|property` property of each `(Call|Member)Expression` node. + * @returns {void} + */ + makeOptionalRight() { + if (this.chainContext) { + this.makeLogicalRight(); + } + } + + //-------------------------------------------------------------------------- + // SwitchStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of SwitchStatement and stacks it. + * @param {boolean} hasCase `true` if the switch statement has one or more + * case parts. + * @param {string|null} label The label text. + * @returns {void} + */ + pushSwitchContext(hasCase, label) { + this.switchContext = new SwitchContext(this.switchContext, hasCase); + this.pushBreakContext(true, label); + } + + /** + * Pops the last context of SwitchStatement and finalizes it. + * + * - Disposes all forking stack for `case` and `default`. + * - Creates the next code path segment from `context.brokenForkContext`. + * - If the last `SwitchCase` node is not a `default` part, creates a path + * to the `default` body. + * @returns {void} + */ + popSwitchContext() { + const context = this.switchContext; + + this.switchContext = context.upper; + + const forkContext = this.forkContext; + const brokenForkContext = this.popBreakContext().brokenForkContext; + + if (context.forkCount === 0) { + /* + * When there is only one `default` chunk and there is one or more + * `break` statements, even if forks are nothing, it needs to merge + * those. + */ + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.makeNext(-1, -1)); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + + return; + } + + const lastSegments = forkContext.head; + + this.forkBypassPath(); + const lastCaseSegments = forkContext.head; + + /* + * `brokenForkContext` is used to make the next segment. + * It must add the last segment into `brokenForkContext`. + */ + brokenForkContext.add(lastSegments); + + /* + * Any value that doesn't match a `case` test should flow to the default + * case. That happens normally when the default case is last in the `switch`, + * but if it's not, we need to rewire some of the paths to be correct. + */ + if (!context.lastIsDefault) { + if (context.defaultBodySegments) { + /* + * There is a non-empty default case, so remove the path from the `default` + * label to its body for an accurate representation. + */ + disconnectSegments( + context.defaultSegments, + context.defaultBodySegments, + ); + + /* + * Connect the path from the last non-default case to the body of the + * default case. + */ + makeLooped(this, lastCaseSegments, context.defaultBodySegments); + } else { + /* + * There is no default case, so we treat this as if the last case + * had a `break` in it. + */ + brokenForkContext.add(lastCaseSegments); + } + } + + // Traverse up to the original fork context for the `switch` statement + for (let i = 0; i < context.forkCount; ++i) { + this.forkContext = this.forkContext.upper; + } + + /* + * Creates a path from all `brokenForkContext` paths. + * This is a path after `switch` statement. + */ + this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for a `SwitchCase` node. + * @param {boolean} isCaseBodyEmpty `true` if the body is empty. + * @param {boolean} isDefaultCase `true` if the body is the default case. + * @returns {void} + */ + makeSwitchCaseBody(isCaseBodyEmpty, isDefaultCase) { + const context = this.switchContext; + + if (!context.hasCase) { + return; + } + + /* + * Merge forks. + * The parent fork context has two segments. + * Those are from the current `case` and the body of the previous case. + */ + const parentForkContext = this.forkContext; + const forkContext = this.pushForkContext(); + + forkContext.add(parentForkContext.makeNext(0, -1)); + + /* + * Add information about the default case. + * + * The purpose of this is to identify the starting segments for the + * default case to make sure there is a path there. + */ + if (isDefaultCase) { + /* + * This is the default case in the `switch`. + * + * We first save the current pointer as `defaultSegments` to point + * to the `default` keyword. + */ + context.defaultSegments = parentForkContext.head; + + /* + * If the body of the case is empty then we just set + * `foundEmptyDefault` to true; otherwise, we save a reference + * to the current pointer as `defaultBodySegments`. + */ + if (isCaseBodyEmpty) { + context.foundEmptyDefault = true; + } else { + context.defaultBodySegments = forkContext.head; + } + } else { + /* + * This is not the default case in the `switch`. + * + * If it's not empty and there is already an empty default case found, + * that means the default case actually comes before this case, + * and that it will fall through to this case. So, we can now + * ignore the previous default case (reset `foundEmptyDefault` to false) + * and set `defaultBodySegments` to the current segments because this is + * effectively the new default case. + */ + if (!isCaseBodyEmpty && context.foundEmptyDefault) { + context.foundEmptyDefault = false; + context.defaultBodySegments = forkContext.head; + } + } + + // keep track if the default case ends up last + context.lastIsDefault = isDefaultCase; + context.forkCount += 1; + } + + //-------------------------------------------------------------------------- + // TryStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of TryStatement and stacks it. + * @param {boolean} hasFinalizer `true` if the try statement has a + * `finally` block. + * @returns {void} + */ + pushTryContext(hasFinalizer) { + this.tryContext = new TryContext( + this.tryContext, + hasFinalizer, + this.forkContext, + ); + } + + /** + * Pops the last context of TryStatement and finalizes it. + * @returns {void} + */ + popTryContext() { + const context = this.tryContext; + + this.tryContext = context.upper; + + /* + * If we're inside the `catch` block, that means there is no `finally`, + * so we can process the `try` and `catch` blocks the simple way and + * merge their two paths. + */ + if (context.position === "catch") { + this.popForkContext(); + return; + } + + /* + * The following process is executed only when there is a `finally` + * block. + */ + + const originalReturnedForkContext = context.returnedForkContext; + const originalThrownForkContext = context.thrownForkContext; + + // no `return` or `throw` in `try` or `catch` so there's nothing left to do + if ( + originalReturnedForkContext.empty && + originalThrownForkContext.empty + ) { + return; + } + + /* + * The following process is executed only when there is a `finally` + * block and there was a `return` or `throw` in the `try` or `catch` + * blocks. + */ + + // Separate head to normal paths and leaving paths. + const headSegments = this.forkContext.head; + + this.forkContext = this.forkContext.upper; + const normalSegments = headSegments.slice( + 0, + (headSegments.length / 2) | 0, + ); + const leavingSegments = headSegments.slice( + (headSegments.length / 2) | 0, + ); + + // Forwards the leaving path to upper contexts. + if (!originalReturnedForkContext.empty) { + getReturnContext(this).returnedForkContext.add(leavingSegments); + } + if (!originalThrownForkContext.empty) { + getThrowContext(this).thrownForkContext.add(leavingSegments); + } + + // Sets the normal path as the next. + this.forkContext.replaceHead(normalSegments); + + /* + * If both paths of the `try` block and the `catch` block are + * unreachable, the next path becomes unreachable as well. + */ + if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { + this.forkContext.makeUnreachable(); + } + } + + /** + * Makes a code path segment for a `catch` block. + * @returns {void} + */ + makeCatchBlock() { + const context = this.tryContext; + const forkContext = this.forkContext; + const originalThrownForkContext = context.thrownForkContext; + + /* + * We are now in a catch block so we need to update the context + * with that information. This includes creating a new fork + * context in case we encounter any `throw` statements here. + */ + context.position = "catch"; + context.thrownForkContext = ForkContext.newEmpty(forkContext); + context.lastOfTryIsReachable = forkContext.reachable; + + // Merge the thrown paths from the `try` and `catch` blocks + originalThrownForkContext.add(forkContext.head); + const thrownSegments = originalThrownForkContext.makeNext(0, -1); + + // Fork to a bypass and the merged thrown path. + this.pushForkContext(); + this.forkBypassPath(); + this.forkContext.add(thrownSegments); + } + + /** + * Makes a code path segment for a `finally` block. + * + * In the `finally` block, parallel paths are created. The parallel paths + * are used as leaving-paths. The leaving-paths are paths from `return` + * statements and `throw` statements in a `try` block or a `catch` block. + * @returns {void} + */ + makeFinallyBlock() { + const context = this.tryContext; + let forkContext = this.forkContext; + const originalReturnedForkContext = context.returnedForkContext; + const originalThrownForContext = context.thrownForkContext; + const headOfLeavingSegments = forkContext.head; + + // Update state. + if (context.position === "catch") { + // Merges two paths from the `try` block and `catch` block. + this.popForkContext(); + forkContext = this.forkContext; + + context.lastOfCatchIsReachable = forkContext.reachable; + } else { + context.lastOfTryIsReachable = forkContext.reachable; + } + + context.position = "finally"; + + /* + * If there was no `return` or `throw` in either the `try` or `catch` + * blocks, then there's no further code paths to create for `finally`. + */ + if ( + originalReturnedForkContext.empty && + originalThrownForContext.empty + ) { + // This path does not leave. + return; + } + + /* + * Create a parallel segment from merging returned and thrown. + * This segment will leave at the end of this `finally` block. + */ + const segments = forkContext.makeNext(-1, -1); + + for (let i = 0; i < forkContext.count; ++i) { + const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]]; + + for ( + let j = 0; + j < originalReturnedForkContext.segmentsList.length; + ++j + ) { + prevSegsOfLeavingSegment.push( + originalReturnedForkContext.segmentsList[j][i], + ); + } + for ( + let j = 0; + j < originalThrownForContext.segmentsList.length; + ++j + ) { + prevSegsOfLeavingSegment.push( + originalThrownForContext.segmentsList[j][i], + ); + } + + segments.push( + CodePathSegment.newNext( + this.idGenerator.next(), + prevSegsOfLeavingSegment, + ), + ); + } + + this.pushForkContext(true); + this.forkContext.add(segments); + } + + /** + * Makes a code path segment from the first throwable node to the `catch` + * block or the `finally` block. + * @returns {void} + */ + makeFirstThrowablePathInTryBlock() { + const forkContext = this.forkContext; + + if (!forkContext.reachable) { + return; + } + + const context = getThrowContext(this); + + if ( + context === this || + context.position !== "try" || + !context.thrownForkContext.empty + ) { + return; + } + + context.thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + + //-------------------------------------------------------------------------- + // Loop Statements + //-------------------------------------------------------------------------- + + /** + * Creates a context object of a loop statement and stacks it. + * @param {string} type The type of the node which was triggered. One of + * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`, + * and `ForStatement`. + * @param {string|null} label A label of the node which was triggered. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + pushLoopContext(type, label) { + const forkContext = this.forkContext; + + // All loops need a path to account for `break` statements + const breakContext = this.pushBreakContext(true, label); + + switch (type) { + case "WhileStatement": + this.pushChoiceContext("loop", false); + this.loopContext = new WhileLoopContext( + this.loopContext, + label, + breakContext, + ); + break; + + case "DoWhileStatement": + this.pushChoiceContext("loop", false); + this.loopContext = new DoWhileLoopContext( + this.loopContext, + label, + breakContext, + forkContext, + ); + break; + + case "ForStatement": + this.pushChoiceContext("loop", false); + this.loopContext = new ForLoopContext( + this.loopContext, + label, + breakContext, + ); + break; + + case "ForInStatement": + this.loopContext = new ForInLoopContext( + this.loopContext, + label, + breakContext, + ); + break; + + case "ForOfStatement": + this.loopContext = new ForOfLoopContext( + this.loopContext, + label, + breakContext, + ); + break; + + /* c8 ignore next */ + default: + throw new Error(`unknown type: "${type}"`); + } + } + + /** + * Pops the last context of a loop statement and finalizes it. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + popLoopContext() { + const context = this.loopContext; + + this.loopContext = context.upper; + + const forkContext = this.forkContext; + const brokenForkContext = this.popBreakContext().brokenForkContext; + + // Creates a looped path. + switch (context.type) { + case "WhileStatement": + case "ForStatement": + this.popChoiceContext(); + + /* + * Creates the path from the end of the loop body up to the + * location where `continue` would jump to. + */ + makeLooped( + this, + forkContext.head, + context.continueDestSegments, + ); + break; + + case "DoWhileStatement": { + const choiceContext = this.popChoiceContext(); + + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + + /* + * If this isn't a hardcoded `true` condition, then `break` + * should continue down the path as if the condition evaluated + * to false. + */ + if (context.test !== true) { + brokenForkContext.addAll(choiceContext.falseForkContext); + } + + /* + * When the condition is true, the loop continues back to the top, + * so create a path from each possible true condition back to the + * top of the loop. + */ + const segmentsList = choiceContext.trueForkContext.segmentsList; + + for (let i = 0; i < segmentsList.length; ++i) { + makeLooped(this, segmentsList[i], context.entrySegments); + } + break; + } + + case "ForInStatement": + case "ForOfStatement": + brokenForkContext.add(forkContext.head); + + /* + * Creates the path from the end of the loop body up to the + * left expression (left of `in` or `of`) of the loop. + */ + makeLooped(this, forkContext.head, context.leftSegments); + break; + + /* c8 ignore next */ + default: + throw new Error("unreachable"); + } + + /* + * If there wasn't a `break` statement in the loop, then we're at + * the end of the loop's path, so we make an unreachable segment + * to mark that. + * + * If there was a `break` statement, then we continue on into the + * `brokenForkContext`. + */ + if (brokenForkContext.empty) { + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } else { + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + + /** + * Makes a code path segment for the test part of a WhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeWhileTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + const testSegments = forkContext.makeNext(0, -1); + + // Update state. + context.test = test; + context.continueDestSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the body part of a WhileStatement. + * @returns {void} + */ + makeWhileBody() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + + /* + * If this isn't a hardcoded `true` condition, then `break` + * should continue down the path as if the condition evaluated + * to false. + */ + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for the body part of a DoWhileStatement. + * @returns {void} + */ + makeDoWhileBody() { + const context = this.loopContext; + const forkContext = this.forkContext; + const bodySegments = forkContext.makeNext(-1, -1); + + // Update state. + context.entrySegments = bodySegments; + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the test part of a DoWhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeDoWhileTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + + context.test = test; + + /* + * If there is a `continue` statement in the loop then `continueForkContext` + * won't be empty. We wire up the path from `continue` to the loop + * test condition and then continue the traversal in the root fork context. + */ + if (!context.continueForkContext.empty) { + context.continueForkContext.add(forkContext.head); + const testSegments = context.continueForkContext.makeNext(0, -1); + + forkContext.replaceHead(testSegments); + } + } + + /** + * Makes a code path segment for the test part of a ForStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeForTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + const endOfInitSegments = forkContext.head; + const testSegments = forkContext.makeNext(-1, -1); + + /* + * Update the state. + * + * The `continueDestSegments` are set to `testSegments` because we + * don't yet know if there is an update expression in this loop. So, + * from what we already know at this point, a `continue` statement + * will jump back to the test expression. + */ + context.test = test; + context.endOfInitSegments = endOfInitSegments; + context.continueDestSegments = context.testSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the update part of a ForStatement. + * @returns {void} + */ + makeForUpdate() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + // Make the next paths of the test. + if (context.testSegments) { + finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head); + } else { + context.endOfInitSegments = forkContext.head; + } + + /* + * Update the state. + * + * The `continueDestSegments` are now set to `updateSegments` because we + * know there is an update expression in this loop. So, a `continue` statement + * in the loop will jump to the update expression first, and then to any + * test expression the loop might have. + */ + const updateSegments = forkContext.makeDisconnected(-1, -1); + + context.continueDestSegments = context.updateSegments = updateSegments; + forkContext.replaceHead(updateSegments); + } + + /** + * Makes a code path segment for the body part of a ForStatement. + * @returns {void} + */ + makeForBody() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + /* + * Determine what to do based on which part of the `for` loop are present. + * 1. If there is an update expression, then `updateSegments` is not null and + * we need to assign `endOfUpdateSegments`, and if there is a test + * expression, we then need to create the looped path to get back to + * the test condition. + * 2. If there is no update expression but there is a test expression, + * then we only need to update the test segment information. + * 3. If there is no update expression and no test expression, then we + * just save `endOfInitSegments`. + */ + if (context.updateSegments) { + context.endOfUpdateSegments = forkContext.head; + + /* + * In a `for` loop that has both an update expression and a test + * condition, execution flows from the test expression into the + * loop body, to the update expression, and then back to the test + * expression to determine if the loop should continue. + * + * To account for that, we need to make a path from the end of the + * update expression to the start of the test expression. This is + * effectively what creates the loop in the code path. + */ + if (context.testSegments) { + makeLooped( + this, + context.endOfUpdateSegments, + context.testSegments, + ); + } + } else if (context.testSegments) { + finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head); + } else { + context.endOfInitSegments = forkContext.head; + } + + let bodySegments = context.endOfTestSegments; + + /* + * If there is a test condition, then there `endOfTestSegments` is also + * the start of the loop body. If there isn't a test condition then + * `bodySegments` will be null and we need to look elsewhere to find + * the start of the body. + * + * The body starts at the end of the init expression and ends at the end + * of the update expression, so we use those locations to determine the + * body segments. + */ + if (!bodySegments) { + const prevForkContext = ForkContext.newEmpty(forkContext); + + prevForkContext.add(context.endOfInitSegments); + if (context.endOfUpdateSegments) { + prevForkContext.add(context.endOfUpdateSegments); + } + + bodySegments = prevForkContext.makeNext(0, -1); + } + + /* + * If there was no test condition and no update expression, then + * `continueDestSegments` will be null. In that case, a + * `continue` should skip directly to the body of the loop. + * Otherwise, we want to keep the current `continueDestSegments`. + */ + context.continueDestSegments = + context.continueDestSegments || bodySegments; + + // move pointer to the body + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the left part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfLeft() { + const context = this.loopContext; + const forkContext = this.forkContext; + const leftSegments = forkContext.makeDisconnected(-1, -1); + + // Update state. + context.prevSegments = forkContext.head; + context.leftSegments = context.continueDestSegments = leftSegments; + forkContext.replaceHead(leftSegments); + } + + /** + * Makes a code path segment for the right part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfRight() { + const context = this.loopContext; + const forkContext = this.forkContext; + const temp = ForkContext.newEmpty(forkContext); + + temp.add(context.prevSegments); + const rightSegments = temp.makeNext(-1, -1); + + // Update state. + context.endOfLeftSegments = forkContext.head; + forkContext.replaceHead(rightSegments); + } + + /** + * Makes a code path segment for the body part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfBody() { + const context = this.loopContext; + const forkContext = this.forkContext; + const temp = ForkContext.newEmpty(forkContext); + + temp.add(context.endOfLeftSegments); + const bodySegments = temp.makeNext(-1, -1); + + // Make a path: `right` -> `left`. + makeLooped(this, forkContext.head, context.leftSegments); + + // Update state. + context.brokenForkContext.add(forkContext.head); + forkContext.replaceHead(bodySegments); + } + + //-------------------------------------------------------------------------- + // Control Statements + //-------------------------------------------------------------------------- + + /** + * Creates new context in which a `break` statement can be used. This occurs inside of a loop, + * labeled statement, or switch statement. + * @param {boolean} breakable Indicates if we are inside a statement where + * `break` without a label will exit the statement. + * @param {string|null} label The label associated with the statement. + * @returns {BreakContext} The new context. + */ + pushBreakContext(breakable, label) { + this.breakContext = new BreakContext( + this.breakContext, + breakable, + label, + this.forkContext, + ); + return this.breakContext; + } + + /** + * Removes the top item of the break context stack. + * @returns {Object} The removed context. + */ + popBreakContext() { + const context = this.breakContext; + const forkContext = this.forkContext; + + this.breakContext = context.upper; + + // Process this context here for other than switches and loops. + if (!context.breakable) { + const brokenForkContext = context.brokenForkContext; + + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.head); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + + return context; + } + + /** + * Makes a path for a `break` statement. + * + * It registers the head segment to a context of `break`. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string|null} label A label of the break statement. + * @returns {void} + */ + makeBreak(label) { + const forkContext = this.forkContext; + + if (!forkContext.reachable) { + return; + } + + const context = getBreakContext(this, label); + + if (context) { + context.brokenForkContext.add(forkContext.head); + } + + /* c8 ignore next */ + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `continue` statement. + * + * It makes a looping path. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string|null} label A label of the continue statement. + * @returns {void} + */ + makeContinue(label) { + const forkContext = this.forkContext; + + if (!forkContext.reachable) { + return; + } + + const context = getContinueContext(this, label); + + if (context) { + if (context.continueDestSegments) { + makeLooped( + this, + forkContext.head, + context.continueDestSegments, + ); + + // If the context is a for-in/of loop, this affects a break also. + if ( + context.type === "ForInStatement" || + context.type === "ForOfStatement" + ) { + context.brokenForkContext.add(forkContext.head); + } + } else { + context.continueForkContext.add(forkContext.head); + } + } + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `return` statement. + * + * It registers the head segment to a context of `return`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeReturn() { + const forkContext = this.forkContext; + + if (forkContext.reachable) { + getReturnContext(this).returnedForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes a path for a `throw` statement. + * + * It registers the head segment to a context of `throw`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeThrow() { + const forkContext = this.forkContext; + + if (forkContext.reachable) { + getThrowContext(this).thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes the final path. + * @returns {void} + */ + makeFinal() { + const segments = this.currentSegments; + + if (segments.length > 0 && segments[0].reachable) { + this.returnedForkContext.add(segments); + } + } +} + +module.exports = CodePathState; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/code-path.js b/node_modules/eslint/lib/linter/code-path-analysis/code-path.js new file mode 100644 index 00000000..36ff8c53 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/code-path.js @@ -0,0 +1,332 @@ +/** + * @fileoverview A class of the code path. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const CodePathState = require("./code-path-state"); +const IdGenerator = require("./id-generator"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A code path. + */ +class CodePath { + /** + * Creates a new instance. + * @param {Object} options Options for the function (see below). + * @param {string} options.id An identifier. + * @param {string} options.origin The type of code path origin. + * @param {CodePath|null} options.upper The code path of the upper function scope. + * @param {Function} options.onLooped A callback function to notify looping. + */ + constructor({ id, origin, upper, onLooped }) { + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * The reason that this code path was started. May be "program", + * "function", "class-field-initializer", or "class-static-block". + * @type {string} + */ + this.origin = origin; + + /** + * The code path of the upper function scope. + * @type {CodePath|null} + */ + this.upper = upper; + + /** + * The code paths of nested function scopes. + * @type {CodePath[]} + */ + this.childCodePaths = []; + + // Initializes internal state. + Object.defineProperty(this, "internal", { + value: new CodePathState(new IdGenerator(`${id}_`), onLooped), + }); + + // Adds this into `childCodePaths` of `upper`. + if (upper) { + upper.childCodePaths.push(this); + } + } + + /** + * Gets the state of a given code path. + * @param {CodePath} codePath A code path to get. + * @returns {CodePathState} The state of the code path. + */ + static getState(codePath) { + return codePath.internal; + } + + /** + * The initial code path segment. This is the segment that is at the head + * of the code path. + * This is a passthrough to the underlying `CodePathState`. + * @type {CodePathSegment} + */ + get initialSegment() { + return this.internal.initialSegment; + } + + /** + * Final code path segments. These are the terminal (tail) segments in the + * code path, which is the combination of `returnedSegments` and `thrownSegments`. + * All segments in this array are reachable. + * This is a passthrough to the underlying `CodePathState`. + * @type {CodePathSegment[]} + */ + get finalSegments() { + return this.internal.finalSegments; + } + + /** + * Final code path segments that represent normal completion of the code path. + * For functions, this means both explicit `return` statements and implicit returns, + * such as the last reachable segment in a function that does not have an + * explicit `return` as this implicitly returns `undefined`. For scripts, + * modules, class field initializers, and class static blocks, this means + * all lines of code have been executed. + * These segments are also present in `finalSegments`. + * This is a passthrough to the underlying `CodePathState`. + * @type {CodePathSegment[]} + */ + get returnedSegments() { + return this.internal.returnedForkContext; + } + + /** + * Final code path segments that represent `throw` statements. + * This is a passthrough to the underlying `CodePathState`. + * These segments are also present in `finalSegments`. + * @type {CodePathSegment[]} + */ + get thrownSegments() { + return this.internal.thrownForkContext; + } + + /** + * Traverses all segments in this code path. + * + * codePath.traverseSegments((segment, controller) => { + * // do something. + * }); + * + * This method enumerates segments in order from the head. + * + * The `controller` argument has two methods: + * + * - `skip()` - skips the following segments in this branch + * - `break()` - skips all following segments in the traversal + * + * A note on the parameters: the `options` argument is optional. This means + * the first argument might be an options object or the callback function. + * @param {Object} [optionsOrCallback] Optional first and last segments to traverse. + * @param {CodePathSegment} [optionsOrCallback.first] The first segment to traverse. + * @param {CodePathSegment} [optionsOrCallback.last] The last segment to traverse. + * @param {Function} callback A callback function. + * @returns {void} + */ + traverseSegments(optionsOrCallback, callback) { + // normalize the arguments into a callback and options + let resolvedOptions; + let resolvedCallback; + + if (typeof optionsOrCallback === "function") { + resolvedCallback = optionsOrCallback; + resolvedOptions = {}; + } else { + resolvedOptions = optionsOrCallback || {}; + resolvedCallback = callback; + } + + // determine where to start traversing from based on the options + const startSegment = + resolvedOptions.first || this.internal.initialSegment; + const lastSegment = resolvedOptions.last; + + // set up initial location information + let record; + let index; + let end; + let segment = null; + + // segments that have already been visited during traversal + const visited = new Set(); + + // tracks the traversal steps + const stack = [[startSegment, 0]]; + + // segments that have been skipped during traversal + const skipped = new Set(); + + // indicates if we exited early from the traversal + let broken = false; + + /** + * Maintains traversal state. + */ + const controller = { + /** + * Skip the following segments in this branch. + * @returns {void} + */ + skip() { + skipped.add(segment); + }, + + /** + * Stop traversal completely - do not traverse to any + * other segments. + * @returns {void} + */ + break() { + broken = true; + }, + }; + + /** + * Checks if a given previous segment has been visited. + * @param {CodePathSegment} prevSegment A previous segment to check. + * @returns {boolean} `true` if the segment has been visited. + */ + function isVisited(prevSegment) { + return ( + visited.has(prevSegment) || + segment.isLoopedPrevSegment(prevSegment) + ); + } + + /** + * Checks if a given previous segment has been skipped. + * @param {CodePathSegment} prevSegment A previous segment to check. + * @returns {boolean} `true` if the segment has been skipped. + */ + function isSkipped(prevSegment) { + return ( + skipped.has(prevSegment) || + segment.isLoopedPrevSegment(prevSegment) + ); + } + + // the traversal + while (stack.length > 0) { + /* + * This isn't a pure stack. We use the top record all the time + * but don't always pop it off. The record is popped only if + * one of the following is true: + * + * 1) We have already visited the segment. + * 2) We have not visited *all* of the previous segments. + * 3) We have traversed past the available next segments. + * + * Otherwise, we just read the value and sometimes modify the + * record as we traverse. + */ + record = stack.at(-1); + segment = record[0]; + index = record[1]; + + if (index === 0) { + // Skip if this segment has been visited already. + if (visited.has(segment)) { + stack.pop(); + continue; + } + + // Skip if all previous segments have not been visited. + if ( + segment !== startSegment && + segment.prevSegments.length > 0 && + !segment.prevSegments.every(isVisited) + ) { + stack.pop(); + continue; + } + + visited.add(segment); + + // Skips the segment if all previous segments have been skipped. + const shouldSkip = + skipped.size > 0 && + segment.prevSegments.length > 0 && + segment.prevSegments.every(isSkipped); + + /* + * If the most recent segment hasn't been skipped, then we call + * the callback, passing in the segment and the controller. + */ + if (!shouldSkip) { + resolvedCallback.call(this, segment, controller); + + // exit if we're at the last segment + if (segment === lastSegment) { + controller.skip(); + } + + /* + * If the previous statement was executed, or if the callback + * called a method on the controller, we might need to exit the + * loop, so check for that and break accordingly. + */ + if (broken) { + break; + } + } else { + // If the most recent segment has been skipped, then mark it as skipped. + skipped.add(segment); + } + } + + // Update the stack. + end = segment.nextSegments.length - 1; + if (index < end) { + /* + * If we haven't yet visited all of the next segments, update + * the current top record on the stack to the next index to visit + * and then push a record for the current segment on top. + * + * Setting the current top record's index lets us know how many + * times we've been here and ensures that the segment won't be + * reprocessed (because we only process segments with an index + * of 0). + */ + record[1] += 1; + stack.push([segment.nextSegments[index], 0]); + } else if (index === end) { + /* + * If we are at the last next segment, then reset the top record + * in the stack to next segment and set its index to 0 so it will + * be processed next. + */ + record[0] = segment.nextSegments[index]; + record[1] = 0; + } else { + /* + * If index > end, that means we have no more segments that need + * processing. So, we pop that record off of the stack in order to + * continue traversing at the next level up. + */ + stack.pop(); + } + } + } +} + +module.exports = CodePath; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js b/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js new file mode 100644 index 00000000..6a65ca7b --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js @@ -0,0 +1,223 @@ +/** + * @fileoverview Helpers to debug for code path analysis. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const debug = require("debug")("eslint:code-path"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets id of a given segment. + * @param {CodePathSegment} segment A segment to get. + * @returns {string} Id of the segment. + */ +/* c8 ignore next */ +// eslint-disable-next-line jsdoc/require-jsdoc -- Ignoring +function getId(segment) { + return segment.id + (segment.reachable ? "" : "!"); +} + +/** + * Get string for the given node and operation. + * @param {ASTNode} node The node to convert. + * @param {"enter" | "exit" | undefined} label The operation label. + * @returns {string} The string representation. + */ +function nodeToString(node, label) { + const suffix = label ? `:${label}` : ""; + + switch (node.type) { + case "Identifier": + return `${node.type}${suffix} (${node.name})`; + case "Literal": + return `${node.type}${suffix} (${node.value})`; + default: + return `${node.type}${suffix}`; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + /** + * A flag that debug dumping is enabled or not. + * @type {boolean} + */ + enabled: debug.enabled, + + /** + * Dumps given objects. + * @param {...any} args objects to dump. + * @returns {void} + */ + dump: debug, + + /** + * Dumps the current analyzing state. + * @param {ASTNode} node A node to dump. + * @param {CodePathState} state A state to dump. + * @param {boolean} leaving A flag whether or not it's leaving + * @returns {void} + */ + dumpState: !debug.enabled + ? debug + : /* c8 ignore next */ function (node, state, leaving) { + for (let i = 0; i < state.currentSegments.length; ++i) { + const segInternal = state.currentSegments[i].internal; + + if (leaving) { + const last = segInternal.nodes.length - 1; + + if ( + last >= 0 && + segInternal.nodes[last] === + nodeToString(node, "enter") + ) { + segInternal.nodes[last] = nodeToString( + node, + void 0, + ); + } else { + segInternal.nodes.push(nodeToString(node, "exit")); + } + } else { + segInternal.nodes.push(nodeToString(node, "enter")); + } + } + + debug( + [ + `${state.currentSegments.map(getId).join(",")})`, + `${node.type}${leaving ? ":exit" : ""}`, + ].join(" "), + ); + }, + + /** + * Dumps a DOT code of a given code path. + * The DOT code can be visualized with Graphvis. + * @param {CodePath} codePath A code path to dump. + * @returns {void} + * @see http://www.graphviz.org + * @see http://www.webgraphviz.com + */ + dumpDot: !debug.enabled + ? debug + : /* c8 ignore next */ function (codePath) { + let text = + "\n" + + "digraph {\n" + + 'node[shape=box,style="rounded,filled",fillcolor=white];\n' + + 'initial[label="",shape=circle,style=filled,fillcolor=black,width=0.25,height=0.25];\n'; + + if (codePath.returnedSegments.length > 0) { + text += + 'final[label="",shape=doublecircle,style=filled,fillcolor=black,width=0.25,height=0.25];\n'; + } + if (codePath.thrownSegments.length > 0) { + text += + 'thrown[label="✘",shape=circle,width=0.3,height=0.3,fixedsize=true];\n'; + } + + const traceMap = Object.create(null); + const arrows = this.makeDotArrows(codePath, traceMap); + + // eslint-disable-next-line guard-for-in -- Want ability to traverse prototype + for (const id in traceMap) { + const segment = traceMap[id]; + + text += `${id}[`; + + if (segment.reachable) { + text += 'label="'; + } else { + text += + 'style="rounded,dashed,filled",fillcolor="#FF9800",label="<>\\n'; + } + + if (segment.internal.nodes.length > 0) { + text += segment.internal.nodes.join("\\n"); + } else { + text += "????"; + } + + text += '"];\n'; + } + + text += `${arrows}\n`; + text += "}"; + debug("DOT", text); + }, + + /** + * Makes a DOT code of a given code path. + * The DOT code can be visualized with Graphvis. + * @param {CodePath} codePath A code path to make DOT. + * @param {Object} traceMap Optional. A map to check whether or not segments had been done. + * @returns {string} A DOT code of the code path. + */ + makeDotArrows(codePath, traceMap) { + const stack = [[codePath.initialSegment, 0]]; + const done = traceMap || Object.create(null); + let lastId = codePath.initialSegment.id; + let text = `initial->${codePath.initialSegment.id}`; + + while (stack.length > 0) { + const item = stack.pop(); + const segment = item[0]; + const index = item[1]; + + if (done[segment.id] && index === 0) { + continue; + } + done[segment.id] = segment; + + const nextSegment = segment.allNextSegments[index]; + + if (!nextSegment) { + continue; + } + + if (lastId === segment.id) { + text += `->${nextSegment.id}`; + } else { + text += `;\n${segment.id}->${nextSegment.id}`; + } + lastId = nextSegment.id; + + stack.unshift([segment, 1 + index]); + stack.push([nextSegment, 0]); + } + + codePath.returnedSegments.forEach(finalSegment => { + if (lastId === finalSegment.id) { + text += "->final"; + } else { + text += `;\n${finalSegment.id}->final`; + } + lastId = null; + }); + + codePath.thrownSegments.forEach(finalSegment => { + if (lastId === finalSegment.id) { + text += "->thrown"; + } else { + text += `;\n${finalSegment.id}->thrown`; + } + lastId = null; + }); + + return `${text};`; + }, +}; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js b/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js new file mode 100644 index 00000000..93d33162 --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js @@ -0,0 +1,374 @@ +/** + * @fileoverview A class to operate forking. + * + * This is state of forking. + * This has a fork list and manages it. + * + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("../../shared/assert"), + CodePathSegment = require("./code-path-segment"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether or not a given segment is reachable. + * @param {CodePathSegment} segment The segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +/** + * Creates a new segment for each fork in the given context and appends it + * to the end of the specified range of segments. Ultimately, this ends up calling + * `new CodePathSegment()` for each of the forks using the `create` argument + * as a wrapper around special behavior. + * + * The `startIndex` and `endIndex` arguments specify a range of segments in + * `context` that should become `allPrevSegments` for the newly created + * `CodePathSegment` objects. + * + * When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and + * `end` is `-1`, this creates two new segments, `[g, h]`. This `g` is appended to + * the end of the path from `a`, `c`, and `e`. This `h` is appended to the end of + * `b`, `d`, and `f`. + * @param {ForkContext} context An instance from which the previous segments + * will be obtained. + * @param {number} startIndex The index of the first segment in the context + * that should be specified as previous segments for the newly created segments. + * @param {number} endIndex The index of the last segment in the context + * that should be specified as previous segments for the newly created segments. + * @param {Function} create A function that creates new `CodePathSegment` + * instances in a particular way. See the `CodePathSegment.new*` methods. + * @returns {Array} An array of the newly-created segments. + */ +function createSegments(context, startIndex, endIndex, create) { + /** @type {Array>} */ + const list = context.segmentsList; + + /* + * Both `startIndex` and `endIndex` work the same way: if the number is zero + * or more, then the number is used as-is. If the number is negative, + * then that number is added to the length of the segments list to + * determine the index to use. That means -1 for either argument + * is the last element, -2 is the second to last, and so on. + * + * So if `startIndex` is 0, `endIndex` is -1, and `list.length` is 3, the + * effective `startIndex` is 0 and the effective `endIndex` is 2, so this function + * will include items at indices 0, 1, and 2. + * + * Therefore, if `startIndex` is -1 and `endIndex` is -1, that means we'll only + * be using the last segment in `list`. + */ + const normalizedBegin = + startIndex >= 0 ? startIndex : list.length + startIndex; + const normalizedEnd = endIndex >= 0 ? endIndex : list.length + endIndex; + + /** @type {Array} */ + const segments = []; + + for (let i = 0; i < context.count; ++i) { + // this is passed into `new CodePathSegment` to add to code path. + const allPrevSegments = []; + + for (let j = normalizedBegin; j <= normalizedEnd; ++j) { + allPrevSegments.push(list[j][i]); + } + + // note: `create` is just a wrapper that augments `new CodePathSegment`. + segments.push(create(context.idGenerator.next(), allPrevSegments)); + } + + return segments; +} + +/** + * Inside of a `finally` block we end up with two parallel paths. If the code path + * exits by a control statement (such as `break` or `continue`) from the `finally` + * block, then we need to merge the remaining parallel paths back into one. + * @param {ForkContext} context The fork context to work on. + * @param {Array} segments Segments to merge. + * @returns {Array} The merged segments. + */ +function mergeExtraSegments(context, segments) { + let currentSegments = segments; + + /* + * We need to ensure that the array returned from this function contains no more + * than the number of segments that the context allows. `context.count` indicates + * how many items should be in the returned array to ensure that the new segment + * entries will line up with the already existing segment entries. + */ + while (currentSegments.length > context.count) { + const merged = []; + + /* + * Because `context.count` is a factor of 2 inside of a `finally` block, + * we can divide the segment count by 2 to merge the paths together. + * This loops through each segment in the list and creates a new `CodePathSegment` + * that has the segment and the segment two slots away as previous segments. + * + * If `currentSegments` is [a,b,c,d], this will create new segments e and f, such + * that: + * + * When `i` is 0: + * a->e + * c->e + * + * When `i` is 1: + * b->f + * d->f + */ + for ( + let i = 0, length = Math.floor(currentSegments.length / 2); + i < length; + ++i + ) { + merged.push( + CodePathSegment.newNext(context.idGenerator.next(), [ + currentSegments[i], + currentSegments[i + length], + ]), + ); + } + + /* + * Go through the loop condition one more time to see if we have the + * number of segments for the context. If not, we'll keep merging paths + * of the merged segments until we get there. + */ + currentSegments = merged; + } + + return currentSegments; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Manages the forking of code paths. + */ +class ForkContext { + /** + * Creates a new instance. + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @param {ForkContext|null} upper The preceding fork context. + * @param {number} count The number of parallel segments in each element + * of `segmentsList`. + */ + constructor(idGenerator, upper, count) { + /** + * The ID generator that will generate segment IDs for any new + * segments that are created. + * @type {IdGenerator} + */ + this.idGenerator = idGenerator; + + /** + * The preceding fork context. + * @type {ForkContext|null} + */ + this.upper = upper; + + /** + * The number of elements in each element of `segmentsList`. In most + * cases, this is 1 but can be 2 when there is a `finally` present, + * which forks the code path outside of normal flow. In the case of nested + * `finally` blocks, this can be a multiple of 2. + * @type {number} + */ + this.count = count; + + /** + * The segments within this context. Each element in this array has + * `count` elements that represent one step in each fork. For example, + * when `segmentsList` is `[[a, b], [c, d], [e, f]]`, there is one path + * a->c->e and one path b->d->f, and `count` is 2 because each element + * is an array with two elements. + * @type {Array>} + */ + this.segmentsList = []; + } + + /** + * The segments that begin this fork context. + * @type {Array} + */ + get head() { + const list = this.segmentsList; + + return list.length === 0 ? [] : list.at(-1); + } + + /** + * Indicates if the context contains no segments. + * @type {boolean} + */ + get empty() { + return this.segmentsList.length === 0; + } + + /** + * Indicates if there are any segments that are reachable. + * @type {boolean} + */ + get reachable() { + const segments = this.head; + + return segments.length > 0 && segments.some(isReachable); + } + + /** + * Creates new segments in this context and appends them to the end of the + * already existing `CodePathSegment`s specified by `startIndex` and + * `endIndex`. + * @param {number} startIndex The index of the first segment in the context + * that should be specified as previous segments for the newly created segments. + * @param {number} endIndex The index of the last segment in the context + * that should be specified as previous segments for the newly created segments. + * @returns {Array} An array of the newly created segments. + */ + makeNext(startIndex, endIndex) { + return createSegments( + this, + startIndex, + endIndex, + CodePathSegment.newNext, + ); + } + + /** + * Creates new unreachable segments in this context and appends them to the end of the + * already existing `CodePathSegment`s specified by `startIndex` and + * `endIndex`. + * @param {number} startIndex The index of the first segment in the context + * that should be specified as previous segments for the newly created segments. + * @param {number} endIndex The index of the last segment in the context + * that should be specified as previous segments for the newly created segments. + * @returns {Array} An array of the newly created segments. + */ + makeUnreachable(startIndex, endIndex) { + return createSegments( + this, + startIndex, + endIndex, + CodePathSegment.newUnreachable, + ); + } + + /** + * Creates new segments in this context and does not append them to the end + * of the already existing `CodePathSegment`s specified by `startIndex` and + * `endIndex`. The `startIndex` and `endIndex` are only used to determine if + * the new segments should be reachable. If any of the segments in this range + * are reachable then the new segments are also reachable; otherwise, the new + * segments are unreachable. + * @param {number} startIndex The index of the first segment in the context + * that should be considered for reachability. + * @param {number} endIndex The index of the last segment in the context + * that should be considered for reachability. + * @returns {Array} An array of the newly created segments. + */ + makeDisconnected(startIndex, endIndex) { + return createSegments( + this, + startIndex, + endIndex, + CodePathSegment.newDisconnected, + ); + } + + /** + * Adds segments to the head of this context. + * @param {Array} segments The segments to add. + * @returns {void} + */ + add(segments) { + assert( + segments.length >= this.count, + `${segments.length} >= ${this.count}`, + ); + this.segmentsList.push(mergeExtraSegments(this, segments)); + } + + /** + * Replaces the head segments with the given segments. + * The current head segments are removed. + * @param {Array} replacementHeadSegments The new head segments. + * @returns {void} + */ + replaceHead(replacementHeadSegments) { + assert( + replacementHeadSegments.length >= this.count, + `${replacementHeadSegments.length} >= ${this.count}`, + ); + this.segmentsList.splice( + -1, + 1, + mergeExtraSegments(this, replacementHeadSegments), + ); + } + + /** + * Adds all segments of a given fork context into this context. + * @param {ForkContext} otherForkContext The fork context to add from. + * @returns {void} + */ + addAll(otherForkContext) { + assert(otherForkContext.count === this.count); + this.segmentsList.push(...otherForkContext.segmentsList); + } + + /** + * Clears all segments in this context. + * @returns {void} + */ + clear() { + this.segmentsList = []; + } + + /** + * Creates a new root context, meaning that there are no parent + * fork contexts. + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @returns {ForkContext} New fork context. + */ + static newRoot(idGenerator) { + const context = new ForkContext(idGenerator, null, 1); + + context.add([CodePathSegment.newRoot(idGenerator.next())]); + + return context; + } + + /** + * Creates an empty fork context preceded by a given context. + * @param {ForkContext} parentContext The parent fork context. + * @param {boolean} shouldForkLeavingPath Indicates that we are inside of + * a `finally` block and should therefore fork the path that leaves + * `finally`. + * @returns {ForkContext} New fork context. + */ + static newEmpty(parentContext, shouldForkLeavingPath) { + return new ForkContext( + parentContext.idGenerator, + parentContext, + (shouldForkLeavingPath ? 2 : 1) * parentContext.count, + ); + } +} + +module.exports = ForkContext; diff --git a/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js b/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js new file mode 100644 index 00000000..9cb4d33b --- /dev/null +++ b/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js @@ -0,0 +1,44 @@ +/** + * @fileoverview A class of identifiers generator for code path segments. + * + * Each rule uses the identifier of code path segments to store additional + * information of the code path. + * + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A generator for unique ids. + */ +class IdGenerator { + /** + * @param {string} prefix Optional. A prefix of generated ids. + */ + constructor(prefix) { + this.prefix = String(prefix); + this.n = 0; + } + + /** + * Generates id. + * @returns {string} A generated id. + */ + next() { + this.n = (1 + this.n) | 0; + + /* c8 ignore start */ + if (this.n < 0) { + this.n = 1; + } /* c8 ignore stop */ + + return this.prefix + this.n; + } +} + +module.exports = IdGenerator; diff --git a/node_modules/eslint/lib/linter/esquery.js b/node_modules/eslint/lib/linter/esquery.js new file mode 100644 index 00000000..08361508 --- /dev/null +++ b/node_modules/eslint/lib/linter/esquery.js @@ -0,0 +1,329 @@ +/** + * @fileoverview ESQuery wrapper for ESLint. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const esquery = require("esquery"); + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * @typedef {import("esquery").Selector} ESQuerySelector + * @typedef {import("esquery").ESQueryOptions} ESQueryOptions + */ + +//------------------------------------------------------------------------------ +// Classes +//------------------------------------------------------------------------------ + +/** + * The result of parsing and analyzing an ESQuery selector. + */ +class ESQueryParsedSelector { + /** + * The raw selector string that was parsed + * @type {string} + */ + source; + + /** + * Whether this selector is an exit selector + * @type {boolean} + */ + isExit; + + /** + * An object (from esquery) describing the matching behavior of the selector + * @type {ESQuerySelector} + */ + root; + + /** + * The node types that could possibly trigger this selector, or `null` if all node types could trigger it + * @type {string[]|null} + */ + nodeTypes; + + /** + * The number of class, pseudo-class, and attribute queries in this selector + * @type {number} + */ + attributeCount; + + /** + * The number of identifier queries in this selector + * @type {number} + */ + identifierCount; + + /** + * Creates a new parsed selector. + * @param {string} source The raw selector string that was parsed + * @param {boolean} isExit Whether this selector is an exit selector + * @param {ESQuerySelector} root An object (from esquery) describing the matching behavior of the selector + * @param {string[]|null} nodeTypes The node types that could possibly trigger this selector, or `null` if all node types could trigger it + * @param {number} attributeCount The number of class, pseudo-class, and attribute queries in this selector + * @param {number} identifierCount The number of identifier queries in this selector + */ + constructor( + source, + isExit, + root, + nodeTypes, + attributeCount, + identifierCount, + ) { + this.source = source; + this.isExit = isExit; + this.root = root; + this.nodeTypes = nodeTypes; + this.attributeCount = attributeCount; + this.identifierCount = identifierCount; + } + + /** + * Compares this selector's specifity to another selector for sorting purposes. + * @param {ESQueryParsedSelector} otherSelector The selector to compare against + * @returns {number} + * a value less than 0 if this selector is less specific than otherSelector + * a value greater than 0 if this selector is more specific than otherSelector + * a value less than 0 if this selector and otherSelector have the same specificity, and this selector <= otherSelector alphabetically + * a value greater than 0 if this selector and otherSelector have the same specificity, and this selector > otherSelector alphabetically + */ + compare(otherSelector) { + return ( + this.attributeCount - otherSelector.attributeCount || + this.identifierCount - otherSelector.identifierCount || + (this.source <= otherSelector.source ? -1 : 1) + ); + } +} + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const selectorCache = new Map(); + +/** + * Computes the union of one or more arrays + * @param {...any[]} arrays One or more arrays to union + * @returns {any[]} The union of the input arrays + */ +function union(...arrays) { + return [...new Set(arrays.flat())]; +} + +/** + * Computes the intersection of one or more arrays + * @param {...any[]} arrays One or more arrays to intersect + * @returns {any[]} The intersection of the input arrays + */ +function intersection(...arrays) { + if (arrays.length === 0) { + return []; + } + + let result = [...new Set(arrays[0])]; + + for (const array of arrays.slice(1)) { + result = result.filter(x => array.includes(x)); + } + return result; +} + +/** + * Analyzes a parsed selector and returns combined data about it + * @param {ESQuerySelector} parsedSelector An object (from esquery) describing the matching behavior of the selector + * @returns {{nodeTypes:string[]|null, attributeCount:number, identifierCount:number}} Object containing selector data. + */ +function analyzeParsedSelector(parsedSelector) { + let attributeCount = 0; + let identifierCount = 0; + + /** + * Analyzes a selector and returns the node types that could possibly trigger it. + * @param {ESQuerySelector} selector The selector to analyze. + * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it + */ + function analyzeSelector(selector) { + switch (selector.type) { + case "identifier": + identifierCount++; + return [selector.value]; + + case "not": + selector.selectors.map(analyzeSelector); + return null; + + case "matches": { + const typesForComponents = + selector.selectors.map(analyzeSelector); + + if (typesForComponents.every(Boolean)) { + return union(...typesForComponents); + } + return null; + } + + case "compound": { + const typesForComponents = selector.selectors + .map(analyzeSelector) + .filter(typesForComponent => typesForComponent); + + // If all of the components could match any type, then the compound could also match any type. + if (!typesForComponents.length) { + return null; + } + + /* + * If at least one of the components could only match a particular type, the compound could only match + * the intersection of those types. + */ + return intersection(...typesForComponents); + } + + case "attribute": + case "field": + case "nth-child": + case "nth-last-child": + attributeCount++; + return null; + + case "child": + case "descendant": + case "sibling": + case "adjacent": + analyzeSelector(selector.left); + return analyzeSelector(selector.right); + + case "class": + // TODO: abstract into JSLanguage somehow + if (selector.name === "function") { + return [ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", + ]; + } + return null; + + default: + return null; + } + } + + const nodeTypes = analyzeSelector(parsedSelector); + + return { + nodeTypes, + attributeCount, + identifierCount, + }; +} + +/** + * Tries to parse a simple selector string, such as a single identifier or wildcard. + * This saves time by avoiding the overhead of esquery parsing for simple cases. + * @param {string} selector The selector string to parse. + * @returns {Object|null} An object describing the selector if it is simple, or `null` if it is not. + */ +function trySimpleParseSelector(selector) { + if (selector === "*") { + return { + type: "wildcard", + value: "*", + }; + } + + if (/^[a-z]+$/iu.test(selector)) { + return { + type: "identifier", + value: selector, + }; + } + + return null; +} + +/** + * Parses a raw selector string, and throws a useful error if parsing fails. + * @param {string} selector The selector string to parse. + * @returns {Object} An object (from esquery) describing the matching behavior of this selector + * @throws {Error} An error if the selector is invalid + */ +function tryParseSelector(selector) { + try { + return esquery.parse(selector); + } catch (err) { + if ( + err.location && + err.location.start && + typeof err.location.start.offset === "number" + ) { + throw new SyntaxError( + `Syntax error in selector "${selector}" at position ${err.location.start.offset}: ${err.message}`, + ); + } + throw err; + } +} + +/** + * Parses a raw selector string, and returns the parsed selector along with specificity and type information. + * @param {string} source A raw AST selector + * @returns {ESQueryParsedSelector} A selector descriptor + */ +function parse(source) { + if (selectorCache.has(source)) { + return selectorCache.get(source); + } + + const cleanSource = source.replace(/:exit$/u, ""); + const parsedSelector = + trySimpleParseSelector(cleanSource) ?? tryParseSelector(cleanSource); + const { nodeTypes, attributeCount, identifierCount } = + analyzeParsedSelector(parsedSelector); + + const result = new ESQueryParsedSelector( + source, + source.endsWith(":exit"), + parsedSelector, + nodeTypes, + attributeCount, + identifierCount, + ); + + selectorCache.set(source, result); + return result; +} + +/** + * Checks if a node matches a given selector. + * @param {Object} node The node to check against the selector. + * @param {ESQuerySelector} root The root of the selector to match against. + * @param {Object[]} ancestry The ancestry of the node being checked, which is an array of nodes from the current node to the root. + * @param {ESQueryOptions} options The options to use for matching. + * @returns {boolean} `true` if the node matches the selector, `false` otherwise. + */ +function matches(node, root, ancestry, options) { + return esquery.matches(node, root, ancestry, options); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + parse, + matches, + ESQueryParsedSelector, +}; diff --git a/node_modules/eslint/lib/linter/file-context.js b/node_modules/eslint/lib/linter/file-context.js new file mode 100644 index 00000000..40acdd63 --- /dev/null +++ b/node_modules/eslint/lib/linter/file-context.js @@ -0,0 +1,144 @@ +/** + * @fileoverview The FileContext class. + * @author Nicholas C. Zakas + */ + +"use strict"; + +/** + * Represents a file context that the linter can use to lint a file. + */ +class FileContext { + /** + * The current working directory. + * @type {string} + */ + cwd; + + /** + * The filename of the file being linted. + * @type {string} + */ + filename; + + /** + * The physical filename of the file being linted. + * @type {string} + */ + physicalFilename; + + /** + * The source code of the file being linted. + * @type {SourceCode} + */ + sourceCode; + + /** + * The parser options for the file being linted. + * @type {Record} + * @deprecated Use `languageOptions` instead. + */ + parserOptions; + + /** + * The path to the parser used to parse this file. + * @type {string} + * @deprecated No longer supported. + */ + parserPath; + + /** + * The language options used when parsing this file. + * @type {Record} + */ + languageOptions; + + /** + * The settings for the file being linted. + * @type {Record} + */ + settings; + + /** + * Creates a new instance. + * @param {Object} config The configuration object for the file context. + * @param {string} config.cwd The current working directory. + * @param {string} config.filename The filename of the file being linted. + * @param {string} config.physicalFilename The physical filename of the file being linted. + * @param {SourceCode} config.sourceCode The source code of the file being linted. + * @param {Record} config.parserOptions The parser options for the file being linted. + * @param {string} config.parserPath The path to the parser used to parse this file. + * @param {Record} config.languageOptions The language options used when parsing this file. + * @param {Record} config.settings The settings for the file being linted. + */ + constructor({ + cwd, + filename, + physicalFilename, + sourceCode, + parserOptions, + parserPath, + languageOptions, + settings, + }) { + this.cwd = cwd; + this.filename = filename; + this.physicalFilename = physicalFilename; + this.sourceCode = sourceCode; + this.parserOptions = parserOptions; + this.parserPath = parserPath; + this.languageOptions = languageOptions; + this.settings = settings; + + Object.freeze(this); + } + + /** + * Gets the current working directory. + * @returns {string} The current working directory. + * @deprecated Use `cwd` instead. + */ + getCwd() { + return this.cwd; + } + + /** + * Gets the filename of the file being linted. + * @returns {string} The filename of the file being linted. + * @deprecated Use `filename` instead. + */ + getFilename() { + return this.filename; + } + + /** + * Gets the physical filename of the file being linted. + * @returns {string} The physical filename of the file being linted. + * @deprecated Use `physicalFilename` instead. + */ + getPhysicalFilename() { + return this.physicalFilename; + } + + /** + * Gets the source code of the file being linted. + * @returns {SourceCode} The source code of the file being linted. + * @deprecated Use `sourceCode` instead. + */ + getSourceCode() { + return this.sourceCode; + } + + /** + * Creates a new object with the current object as the prototype and + * the specified properties as its own properties. + * @param {Object} extension The properties to add to the new object. + * @returns {FileContext} A new object with the current object as the prototype + * and the specified properties as its own properties. + */ + extend(extension) { + return Object.freeze(Object.assign(Object.create(this), extension)); + } +} + +exports.FileContext = FileContext; diff --git a/node_modules/eslint/lib/linter/index.js b/node_modules/eslint/lib/linter/index.js new file mode 100644 index 00000000..5a86f71c --- /dev/null +++ b/node_modules/eslint/lib/linter/index.js @@ -0,0 +1,11 @@ +"use strict"; + +const { Linter } = require("./linter"); +const SourceCodeFixer = require("./source-code-fixer"); + +module.exports = { + Linter, + + // For testers. + SourceCodeFixer, +}; diff --git a/node_modules/eslint/lib/linter/interpolate.js b/node_modules/eslint/lib/linter/interpolate.js new file mode 100644 index 00000000..b1275181 --- /dev/null +++ b/node_modules/eslint/lib/linter/interpolate.js @@ -0,0 +1,50 @@ +/** + * @fileoverview Interpolate keys from an object into a string with {{ }} markers. + * @author Jed Fox + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Returns a global expression matching placeholders in messages. + * @returns {RegExp} Global regular expression matching placeholders + */ +function getPlaceholderMatcher() { + return /\{\{([^{}]+?)\}\}/gu; +} + +/** + * Replaces {{ placeholders }} in the message with the provided data. + * Does not replace placeholders not available in the data. + * @param {string} text Original message with potential placeholders + * @param {Record} data Map of placeholder name to its value + * @returns {string} Message with replaced placeholders + */ +function interpolate(text, data) { + if (!data) { + return text; + } + + const matcher = getPlaceholderMatcher(); + + // Substitution content for any {{ }} markers. + return text.replace(matcher, (fullMatch, termWithWhitespace) => { + const term = termWithWhitespace.trim(); + + if (term in data) { + return data[term]; + } + + // Preserve old behavior: If parameter name not provided, don't replace it. + return fullMatch; + }); +} + +module.exports = { + getPlaceholderMatcher, + interpolate, +}; diff --git a/node_modules/eslint/lib/linter/linter.js b/node_modules/eslint/lib/linter/linter.js new file mode 100644 index 00000000..db059b26 --- /dev/null +++ b/node_modules/eslint/lib/linter/linter.js @@ -0,0 +1,2816 @@ +/** + * @fileoverview Main Linter Class + * @author Gyandeep Singh + * @author aladdin-add + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("node:path"), + eslintScope = require("eslint-scope"), + evk = require("eslint-visitor-keys"), + espree = require("espree"), + merge = require("lodash.merge"), + pkg = require("../../package.json"), + { + Legacy: { + ConfigOps, + ConfigValidator, + environments: BuiltInEnvironments, + }, + } = require("@eslint/eslintrc/universal"), + Traverser = require("../shared/traverser"), + { SourceCode } = require("../languages/js/source-code"), + applyDisableDirectives = require("./apply-disable-directives"), + { ConfigCommentParser } = require("@eslint/plugin-kit"), + createReportTranslator = require("./report-translator"), + Rules = require("./rules"), + SourceCodeFixer = require("./source-code-fixer"), + { SourceCodeVisitor } = require("./source-code-visitor"), + timing = require("./timing"), + ruleReplacements = require("../../conf/replacements.json"); +const { FlatConfigArray } = require("../config/flat-config-array"); +const { startTime, endTime } = require("../shared/stats"); +const { assertIsRuleSeverity } = require("../config/flat-config-schema"); +const { + normalizeSeverityToString, + normalizeSeverityToNumber, +} = require("../shared/severity"); +const { deepMergeArrays } = require("../shared/deep-merge-arrays"); +const jslang = require("../languages/js"); +const { + activeFlags, + inactiveFlags, + getInactivityReasonMessage, +} = require("../shared/flags"); +const debug = require("debug")("eslint:linter"); +const MAX_AUTOFIX_PASSES = 10; +const DEFAULT_PARSER_NAME = "espree"; +const DEFAULT_ECMA_VERSION = 5; +const commentParser = new ConfigCommentParser(); +const DEFAULT_ERROR_LOC = { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 }, +}; +const parserSymbol = Symbol.for("eslint.RuleTester.parser"); +const { LATEST_ECMA_VERSION } = require("../../conf/ecma-version"); +const { VFile } = require("./vfile"); +const { ParserService } = require("../services/parser-service"); +const { FileContext } = require("./file-context"); +const { ProcessorService } = require("../services/processor-service"); +const { containsDifferentProperty } = require("../shared/option-utils"); +const { Config } = require("../config/config"); +const { WarningService } = require("../services/warning-service"); +const { SourceCodeTraverser } = require("./source-code-traverser"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @import { Language, LanguageOptions, RuleConfig, RuleDefinition, RuleSeverity } from "@eslint/core" */ + +/** @typedef {import("../types").Linter.Config} Config */ +/** @typedef {import("../types").ESLint.ConfigData} ConfigData */ +/** @typedef {import("../types").ESLint.Environment} Environment */ +/** @typedef {import("../types").Linter.GlobalConf} GlobalConf */ +/** @typedef {import("../types").Linter.LanguageOptions} JSLanguageOptions */ +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").Linter.Parser} Parser */ +/** @typedef {import("../types").Linter.ParserOptions} ParserOptions */ +/** @typedef {import("../types").Linter.Processor} Processor */ +/** @typedef {import("../types").Rule.RuleModule} Rule */ +/** @typedef {import("../types").Linter.StringSeverity} StringSeverity */ +/** @typedef {import("../types").Linter.SuppressedLintMessage} SuppressedLintMessage */ +/** @typedef {import("../types").Linter.TimePass} TimePass */ + +/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */ +/** + * @template T + * @typedef {{ [P in keyof T]-?: T[P] }} Required + */ +/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */ + +/** + * @typedef {Object} DisableDirective + * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type Type of directive + * @property {number} line The line number + * @property {number} column The column number + * @property {(string|null)} ruleId The rule ID + * @property {string} justification The justification of directive + */ + +/** + * The private data for `Linter` instance. + * @typedef {Object} LinterInternalSlots + * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used. + * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used. + * @property {SuppressedLintMessage[]} lastSuppressedMessages The `SuppressedLintMessage[]` instance that the last `verify()` call produced. + * @property {Map} parserMap The loaded parsers. + * @property {{ passes: TimePass[]; }} times The times spent on applying a rule to a file (see `stats` option). + * @property {Rules} ruleMap The loaded rules. + * @property {WarningService} warningService The warning service. + */ + +/** + * @typedef {Object} VerifyOptions + * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability + * to change config once it is set. Defaults to true if not supplied. + * Useful if you want to validate JS without comments overriding rules. + * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix` + * properties into the lint result. + * @property {string} [filename] the filename of the source code. + * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for + * unused `eslint-disable` directives. + * @property {Function} [ruleFilter] A predicate function that determines whether a given rule should run. + */ + +/** + * @typedef {Object} ProcessorOptions + * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the + * predicate function that selects adopt code blocks. + * @property {Processor.postprocess} [postprocess] postprocessor for report + * messages. If provided, this should accept an array of the message lists + * for each code block returned from the preprocessor, apply a mapping to + * the messages as appropriate, and return a one-dimensional array of + * messages. + * @property {Processor.preprocess} [preprocess] preprocessor for source text. + * If provided, this should accept a string of source text, and return an + * array of code blocks to lint. + */ + +/** + * @typedef {Object} FixOptions + * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines + * whether fixes should be applied. + */ + +/** + * @typedef {Object} InternalOptions + * @property {string | null} warnInlineConfig The config name what `noInlineConfig` setting came from. If `noInlineConfig` setting didn't exist, this is null. If this is a config name, then the linter warns directive comments. + * @property {StringSeverity} reportUnusedDisableDirectives Severity to report unused disable directives, if not "off" (boolean values were normalized). + * @property {StringSeverity} reportUnusedInlineConfigs Severity to report unused inline configs, if not "off". + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if a given object is Espree. + * @param {Object} parser The parser to check. + * @returns {boolean} True if the parser is Espree or false if not. + */ +function isEspree(parser) { + return !!(parser === espree || parser[parserSymbol] === espree); +} + +/** + * Ensures that variables representing built-in properties of the Global Object, + * and any globals declared by special block comments, are present in the global + * scope. + * @param {Scope} globalScope The global scope. + * @param {Object} configGlobals The globals declared in configuration + * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration + * @returns {void} + */ +function addDeclaredGlobals( + globalScope, + configGlobals, + { exportedVariables, enabledGlobals }, +) { + // Define configured global variables. + for (const id of new Set([ + ...Object.keys(configGlobals), + ...Object.keys(enabledGlobals), + ])) { + /* + * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would + * typically be caught when validating a config anyway (validity for inline global comments is checked separately). + */ + const configValue = + configGlobals[id] === void 0 + ? void 0 + : ConfigOps.normalizeConfigGlobal(configGlobals[id]); + const commentValue = enabledGlobals[id] && enabledGlobals[id].value; + const value = commentValue || configValue; + const sourceComments = + enabledGlobals[id] && enabledGlobals[id].comments; + + if (value === "off") { + continue; + } + + let variable = globalScope.set.get(id); + + if (!variable) { + variable = new eslintScope.Variable(id, globalScope); + + globalScope.variables.push(variable); + globalScope.set.set(id, variable); + } + + variable.eslintImplicitGlobalSetting = configValue; + variable.eslintExplicitGlobal = sourceComments !== void 0; + variable.eslintExplicitGlobalComments = sourceComments; + variable.writeable = value === "writable"; + } + + // mark all exported variables as such + Object.keys(exportedVariables).forEach(name => { + const variable = globalScope.set.get(name); + + if (variable) { + variable.eslintUsed = true; + variable.eslintExported = true; + } + }); + + /* + * "through" contains all references which definitions cannot be found. + * Since we augment the global scope using configuration, we need to update + * references and remove the ones that were added by configuration. + */ + globalScope.through = globalScope.through.filter(reference => { + const name = reference.identifier.name; + const variable = globalScope.set.get(name); + + if (variable) { + /* + * Links the variable and the reference. + * And this reference is removed from `Scope#through`. + */ + reference.resolved = variable; + variable.references.push(reference); + + return false; + } + + return true; + }); +} + +/** + * creates a missing-rule message. + * @param {string} ruleId the ruleId to create + * @returns {string} created error message + * @private + */ +function createMissingRuleMessage(ruleId) { + return Object.hasOwn(ruleReplacements.rules, ruleId) + ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}` + : `Definition for rule '${ruleId}' was not found.`; +} + +/** + * Updates a given location based on the language offsets. This allows us to + * change 0-based locations to 1-based locations. We always want ESLint + * reporting lines and columns starting from 1. + * @param {Object} location The location to update. + * @param {number} location.line The starting line number. + * @param {number} location.column The starting column number. + * @param {number} [location.endLine] The ending line number. + * @param {number} [location.endColumn] The ending column number. + * @param {Language} language The language to use to adjust the location information. + * @returns {Object} The updated location. + */ +function updateLocationInformation( + { line, column, endLine, endColumn }, + language, +) { + const columnOffset = language.columnStart === 1 ? 0 : 1; + const lineOffset = language.lineStart === 1 ? 0 : 1; + + // calculate separately to account for undefined + const finalEndLine = endLine === void 0 ? endLine : endLine + lineOffset; + const finalEndColumn = + endColumn === void 0 ? endColumn : endColumn + columnOffset; + + return { + line: line + lineOffset, + column: column + columnOffset, + endLine: finalEndLine, + endColumn: finalEndColumn, + }; +} + +/** + * creates a linting problem + * @param {Object} options to create linting error + * @param {string} [options.ruleId] the ruleId to report + * @param {Object} [options.loc] the loc to report + * @param {string} [options.message] the error message to report + * @param {RuleSeverity} [options.severity] the error message to report + * @param {Language} [options.language] the language to use to adjust the location information + * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId. + * @private + */ +function createLintingProblem(options) { + const { + ruleId = null, + loc = DEFAULT_ERROR_LOC, + message = createMissingRuleMessage(options.ruleId), + severity = 2, + + // fallback for eslintrc mode + language = { + columnStart: 0, + lineStart: 1, + }, + } = options; + + return { + ruleId, + message, + ...updateLocationInformation( + { + line: loc.start.line, + column: loc.start.column, + endLine: loc.end.line, + endColumn: loc.end.column, + }, + language, + ), + severity, + nodeType: null, + }; +} + +/** + * Wraps the value in an Array if it isn't already one. + * @template T + * @param {T|T[]} value Value to be wrapped. + * @returns {Array} The value as an array. + */ +function asArray(value) { + return Array.isArray(value) ? value : [value]; +} + +/** + * Pushes a problem to inlineConfigProblems if ruleOptions are redundant. + * @param {Config} config Provided config. + * @param {Object} loc A line/column location + * @param {Array} problems Problems that may be added to. + * @param {string} ruleId The rule ID. + * @param {Array} ruleOptions The rule options, merged with the config's. + * @param {Array} ruleOptionsInline The rule options from the comment. + * @param {"error"|"warn"} severity The severity to report. + * @returns {void} + */ +function addProblemIfSameSeverityAndOptions( + config, + loc, + problems, + ruleId, + ruleOptions, + ruleOptionsInline, + severity, +) { + const existingConfigRaw = config.rules?.[ruleId]; + const existingConfig = existingConfigRaw + ? asArray(existingConfigRaw) + : ["off"]; + const existingSeverity = normalizeSeverityToString(existingConfig[0]); + const inlineSeverity = normalizeSeverityToString(ruleOptions[0]); + const sameSeverity = existingSeverity === inlineSeverity; + + if (!sameSeverity) { + return; + } + + const alreadyConfigured = existingConfigRaw + ? `is already configured to '${existingSeverity}'` + : "is not enabled so can't be turned off"; + let message; + + if ( + (existingConfig.length === 1 && ruleOptions.length === 1) || + existingSeverity === "off" + ) { + message = `Unused inline config ('${ruleId}' ${alreadyConfigured}).`; + } else if ( + !containsDifferentProperty( + ruleOptions.slice(1), + existingConfig.slice(1), + ) + ) { + message = + ruleOptionsInline.length === 1 + ? `Unused inline config ('${ruleId}' ${alreadyConfigured}).` + : `Unused inline config ('${ruleId}' ${alreadyConfigured} with the same options).`; + } + + if (message) { + problems.push( + createLintingProblem({ + ruleId: null, + message, + loc, + language: config.language, + severity: normalizeSeverityToNumber(severity), + }), + ); + } +} + +/** + * Creates a collection of disable directives from a comment + * @param {Object} options to create disable directives + * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment + * @param {string} options.value The value after the directive in the comment + * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`) + * @param {string} options.justification The justification of the directive + * @param {ASTNode|token} options.node The Comment node/token. + * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules + * @param {Language} language The language to use to adjust the location information. + * @param {SourceCode} sourceCode The SourceCode object to get comments from. + * @returns {Object} Directives and problems from the comment + */ +function createDisableDirectives( + { type, value, justification, node }, + ruleMapper, + language, + sourceCode, +) { + const ruleIds = Object.keys(commentParser.parseListConfig(value)); + const directiveRules = ruleIds.length ? ruleIds : [null]; + const result = { + directives: [], // valid disable directives + directiveProblems: [], // problems in directives + }; + const parentDirective = { node, value, ruleIds }; + + for (const ruleId of directiveRules) { + const loc = sourceCode.getLoc(node); + + // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/) + if (ruleId === null || !!ruleMapper(ruleId)) { + if (type === "disable-next-line") { + const { line, column } = updateLocationInformation( + loc.end, + language, + ); + + result.directives.push({ + parentDirective, + type, + line, + column, + ruleId, + justification, + }); + } else { + const { line, column } = updateLocationInformation( + loc.start, + language, + ); + + result.directives.push({ + parentDirective, + type, + line, + column, + ruleId, + justification, + }); + } + } else { + result.directiveProblems.push( + createLintingProblem({ ruleId, loc, language }), + ); + } + } + return result; +} + +/** + * Parses comments in file to extract file-specific config of rules, globals + * and environments and merges them with global config; also code blocks + * where reporting is disabled or enabled and merges them with reporting config. + * @param {SourceCode} sourceCode The SourceCode object to get comments from. + * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules + * @param {string|null} warnInlineConfig If a string then it should warn directive comments as disabled. The string value is the config name what the setting came from. + * @param {ConfigData} config Provided config. + * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, problems: LintMessage[], disableDirectives: DisableDirective[]}} + * A collection of the directive comments that were found, along with any problems that occurred when parsing + */ +function getDirectiveComments( + sourceCode, + ruleMapper, + warnInlineConfig, + config, +) { + const configuredRules = {}; + const enabledGlobals = Object.create(null); + const exportedVariables = {}; + const problems = []; + const disableDirectives = []; + const validator = new ConfigValidator({ + builtInRules: Rules, + }); + + sourceCode + .getInlineConfigNodes() + .filter(token => token.type !== "Shebang") + .forEach(comment => { + const directive = commentParser.parseDirective(comment.value); + + if (!directive) { + return; + } + + const { + label, + value, + justification: justificationPart, + } = directive; + + const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test( + label, + ); + + if (comment.type === "Line" && !lineCommentSupported) { + return; + } + + const loc = sourceCode.getLoc(comment); + + if (warnInlineConfig) { + const kind = + comment.type === "Block" ? `/*${label}*/` : `//${label}`; + + problems.push( + createLintingProblem({ + ruleId: null, + message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`, + loc, + severity: 1, + }), + ); + return; + } + + if ( + label === "eslint-disable-line" && + loc.start.line !== loc.end.line + ) { + const message = `${label} comment should not span multiple lines.`; + + problems.push( + createLintingProblem({ + ruleId: null, + message, + loc, + }), + ); + return; + } + + switch (label) { + case "eslint-disable": + case "eslint-enable": + case "eslint-disable-next-line": + case "eslint-disable-line": { + const directiveType = label.slice("eslint-".length); + const { directives, directiveProblems } = + createDisableDirectives( + { + type: directiveType, + value, + justification: justificationPart, + node: comment, + }, + ruleMapper, + jslang, + sourceCode, + ); + + disableDirectives.push(...directives); + problems.push(...directiveProblems); + break; + } + + case "exported": + Object.assign( + exportedVariables, + commentParser.parseListConfig(value), + ); + break; + + case "globals": + case "global": + for (const [id, idSetting] of Object.entries( + commentParser.parseStringConfig(value), + )) { + let normalizedValue; + + try { + normalizedValue = + ConfigOps.normalizeConfigGlobal(idSetting); + } catch (err) { + problems.push( + createLintingProblem({ + ruleId: null, + loc, + message: err.message, + }), + ); + continue; + } + + if (enabledGlobals[id]) { + enabledGlobals[id].comments.push(comment); + enabledGlobals[id].value = normalizedValue; + } else { + enabledGlobals[id] = { + comments: [comment], + value: normalizedValue, + }; + } + } + break; + + case "eslint": { + const parseResult = + commentParser.parseJSONLikeConfig(value); + + if (parseResult.ok) { + Object.keys(parseResult.config).forEach(name => { + const rule = ruleMapper(name); + const ruleValue = parseResult.config[name]; + + if (!rule) { + problems.push( + createLintingProblem({ ruleId: name, loc }), + ); + return; + } + + if (Object.hasOwn(configuredRules, name)) { + problems.push( + createLintingProblem({ + message: `Rule "${name}" is already configured by another configuration comment in the preceding code. This configuration is ignored.`, + loc, + }), + ); + return; + } + + let ruleOptions = asArray(ruleValue); + + /* + * If the rule was already configured, inline rule configuration that + * only has severity should retain options from the config and just override the severity. + * + * Example: + * + * { + * rules: { + * curly: ["error", "multi"] + * } + * } + * + * /* eslint curly: ["warn"] * / + * + * Results in: + * + * curly: ["warn", "multi"] + */ + if ( + /* + * If inline config for the rule has only severity + */ + ruleOptions.length === 1 && + /* + * And the rule was already configured + */ + config.rules && + Object.hasOwn(config.rules, name) + ) { + /* + * Then use severity from the inline config and options from the provided config + */ + ruleOptions = [ + ruleOptions[0], // severity from the inline config + ...asArray(config.rules[name]).slice(1), // options from the provided config + ]; + } + + try { + validator.validateRuleOptions( + rule, + name, + ruleOptions, + ); + } catch (err) { + /* + * If the rule has invalid `meta.schema`, throw the error because + * this is not an invalid inline configuration but an invalid rule. + */ + if ( + err.code === + "ESLINT_INVALID_RULE_OPTIONS_SCHEMA" + ) { + throw err; + } + + problems.push( + createLintingProblem({ + ruleId: name, + message: err.message, + loc, + }), + ); + + // do not apply the config, if found invalid options. + return; + } + + configuredRules[name] = ruleOptions; + }); + } else { + const problem = createLintingProblem({ + ruleId: null, + loc, + message: parseResult.error.message, + }); + + problem.fatal = true; + problems.push(problem); + } + + break; + } + + // no default + } + }); + + return { + configuredRules, + enabledGlobals, + exportedVariables, + problems, + disableDirectives, + }; +} + +/** + * Parses comments in file to extract disable directives. + * @param {SourceCode} sourceCode The SourceCode object to get comments from. + * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules + * @param {Language} language The language to use to adjust the location information + * @returns {{problems: LintMessage[], disableDirectives: DisableDirective[]}} + * A collection of the directive comments that were found, along with any problems that occurred when parsing + */ +function getDirectiveCommentsForFlatConfig(sourceCode, ruleMapper, language) { + const disableDirectives = []; + const problems = []; + + if (sourceCode.getDisableDirectives) { + const { directives: directivesSources, problems: directivesProblems } = + sourceCode.getDisableDirectives(); + + problems.push( + ...directivesProblems.map(directiveProblem => + createLintingProblem({ + ...directiveProblem, + language, + }), + ), + ); + + directivesSources.forEach(directive => { + const { directives, directiveProblems } = createDisableDirectives( + directive, + ruleMapper, + language, + sourceCode, + ); + + disableDirectives.push(...directives); + problems.push(...directiveProblems); + }); + } + + return { + problems, + disableDirectives, + }; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {Parser} parser The parser which uses this options. + * @param {number} ecmaVersion ECMAScript version from the initial config + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersion(parser, ecmaVersion) { + if (isEspree(parser)) { + if (ecmaVersion === "latest") { + return espree.latestEcmaVersion; + } + } + + /* + * Calculate ECMAScript edition number from official year version starting with + * ES2015, which corresponds with ES6 (or a difference of 2009). + */ + return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion; +} + +/** + * Normalize ECMAScript version from the initial config into languageOptions (year) + * format. + * @param {any} [ecmaVersion] ECMAScript version from the initial config + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersionForLanguageOptions(ecmaVersion) { + switch (ecmaVersion) { + case 3: + return 3; + + // void 0 = no ecmaVersion specified so use the default + case 5: + case void 0: + return 5; + + default: + if (typeof ecmaVersion === "number") { + return ecmaVersion >= 2015 ? ecmaVersion : ecmaVersion + 2009; + } + } + + /* + * We default to the latest supported ecmaVersion for everything else. + * Remember, this is for languageOptions.ecmaVersion, which sets the version + * that is used for a number of processes inside of ESLint. It's normally + * safe to assume people want the latest unless otherwise specified. + */ + return LATEST_ECMA_VERSION; +} + +const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)(?:\*\/|$)/gsu; + +/** + * Checks whether or not there is a comment which has "eslint-env *" in a given text. + * @param {string} text A source code text to check. + * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment. + */ +function findEslintEnv(text) { + let match, retv; + + eslintEnvPattern.lastIndex = 0; + + while ((match = eslintEnvPattern.exec(text)) !== null) { + if (match[0].endsWith("*/")) { + retv = Object.assign( + retv || {}, + commentParser.parseListConfig( + commentParser.parseDirective(match[0].slice(2, -2)).value, + ), + ); + } + } + + return retv; +} + +/** + * Convert "/path/to/" to "". + * `CLIEngine#executeOnText()` method gives "/path/to/" if the filename + * was omitted because `configArray.extractConfig()` requires an absolute path. + * But the linter should pass `` to `RuleContext#filename` in that + * case. + * Also, code blocks can have their virtual filename. If the parent filename was + * ``, the virtual filename is `/0_foo.js` or something like (i.e., + * it's not an absolute path). + * @param {string} filename The filename to normalize. + * @returns {string} The normalized filename. + */ +function normalizeFilename(filename) { + const parts = filename.split(path.sep); + const index = parts.lastIndexOf(""); + + return index === -1 ? filename : parts.slice(index).join(path.sep); +} + +/** + * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a + * consistent shape. + * @param {VerifyOptions} providedOptions Options + * @param {Config|ConfigData} config Config. + * @returns {Required & InternalOptions} Normalized options + */ +function normalizeVerifyOptions(providedOptions, config) { + const linterOptions = config.linterOptions || config; + + // .noInlineConfig for eslintrc, .linterOptions.noInlineConfig for flat + const disableInlineConfig = linterOptions.noInlineConfig === true; + const ignoreInlineConfig = providedOptions.allowInlineConfig === false; + const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig + ? ` (${config.configNameOfNoInlineConfig})` + : ""; + + let reportUnusedDisableDirectives = + providedOptions.reportUnusedDisableDirectives; + + if (typeof reportUnusedDisableDirectives === "boolean") { + reportUnusedDisableDirectives = reportUnusedDisableDirectives + ? "error" + : "off"; + } + if (typeof reportUnusedDisableDirectives !== "string") { + if (typeof linterOptions.reportUnusedDisableDirectives === "boolean") { + reportUnusedDisableDirectives = + linterOptions.reportUnusedDisableDirectives ? "warn" : "off"; + } else { + reportUnusedDisableDirectives = + linterOptions.reportUnusedDisableDirectives === void 0 + ? "off" + : normalizeSeverityToString( + linterOptions.reportUnusedDisableDirectives, + ); + } + } + + const reportUnusedInlineConfigs = + linterOptions.reportUnusedInlineConfigs === void 0 + ? "off" + : normalizeSeverityToString( + linterOptions.reportUnusedInlineConfigs, + ); + + let ruleFilter = providedOptions.ruleFilter; + + if (typeof ruleFilter !== "function") { + ruleFilter = () => true; + } + + return { + filename: normalizeFilename(providedOptions.filename || ""), + allowInlineConfig: !ignoreInlineConfig, + warnInlineConfig: + disableInlineConfig && !ignoreInlineConfig + ? `your config${configNameOfNoInlineConfig}` + : null, + reportUnusedDisableDirectives, + reportUnusedInlineConfigs, + disableFixes: Boolean(providedOptions.disableFixes), + stats: providedOptions.stats, + ruleFilter, + }; +} + +/** + * Combines the provided parserOptions with the options from environments + * @param {Parser} parser The parser which uses this options. + * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config + * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments + * @returns {ParserOptions} Resulting parser options after merge + */ +function resolveParserOptions(parser, providedOptions, enabledEnvironments) { + const parserOptionsFromEnv = enabledEnvironments + .filter(env => env.parserOptions) + .reduce( + (parserOptions, env) => merge(parserOptions, env.parserOptions), + {}, + ); + const mergedParserOptions = merge( + parserOptionsFromEnv, + providedOptions || {}, + ); + const isModule = mergedParserOptions.sourceType === "module"; + + if (isModule) { + /* + * can't have global return inside of modules + * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add) + */ + mergedParserOptions.ecmaFeatures = Object.assign( + {}, + mergedParserOptions.ecmaFeatures, + { globalReturn: false }, + ); + } + + mergedParserOptions.ecmaVersion = normalizeEcmaVersion( + parser, + mergedParserOptions.ecmaVersion, + ); + + return mergedParserOptions; +} + +/** + * Converts parserOptions to languageOptions for backwards compatibility with eslintrc. + * @param {ConfigData} config Config object. + * @param {Object} config.globals Global variable definitions. + * @param {Parser} config.parser The parser to use. + * @param {ParserOptions} config.parserOptions The parserOptions to use. + * @returns {JSLanguageOptions} The languageOptions equivalent. + */ +function createLanguageOptions({ + globals: configuredGlobals, + parser, + parserOptions, +}) { + const { ecmaVersion, sourceType } = parserOptions; + + return { + globals: configuredGlobals, + ecmaVersion: normalizeEcmaVersionForLanguageOptions(ecmaVersion), + sourceType, + parser, + parserOptions, + }; +} + +/** + * Combines the provided globals object with the globals from environments + * @param {Record} providedGlobals The 'globals' key in a config + * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments + * @returns {Record} The resolved globals object + */ +function resolveGlobals(providedGlobals, enabledEnvironments) { + return Object.assign( + Object.create(null), + ...enabledEnvironments + .filter(env => env.globals) + .map(env => env.globals), + providedGlobals, + ); +} + +/** + * Store time measurements in map + * @param {number} time Time measurement + * @param {Object} timeOpts Options relating which time was measured + * @param {WeakMap} slots Linter internal slots map + * @returns {void} + */ +function storeTime(time, timeOpts, slots) { + const { type, key } = timeOpts; + + if (!slots.times) { + slots.times = { passes: [{}] }; + } + + const passIndex = slots.fixPasses; + + if (passIndex > slots.times.passes.length - 1) { + slots.times.passes.push({}); + } + + if (key) { + slots.times.passes[passIndex][type] ??= {}; + slots.times.passes[passIndex][type][key] ??= { total: 0 }; + slots.times.passes[passIndex][type][key].total += time; + } else { + slots.times.passes[passIndex][type] ??= { total: 0 }; + slots.times.passes[passIndex][type].total += time; + } +} + +/** + * Get the options for a rule (not including severity), if any + * @param {RuleConfig} ruleConfig rule configuration + * @param {Object|undefined} defaultOptions rule.meta.defaultOptions + * @returns {Array} of rule options, empty Array if none + */ +function getRuleOptions(ruleConfig, defaultOptions) { + if (Array.isArray(ruleConfig)) { + return deepMergeArrays(defaultOptions, ruleConfig.slice(1)); + } + return defaultOptions ?? []; +} + +/** + * Analyze scope of the given AST. + * @param {ASTNode} ast The `Program` node to analyze. + * @param {JSLanguageOptions} languageOptions The language options. + * @param {Record} visitorKeys The visitor keys. + * @returns {ScopeManager} The analysis result. + */ +function analyzeScope(ast, languageOptions, visitorKeys) { + const parserOptions = languageOptions.parserOptions; + const ecmaFeatures = parserOptions.ecmaFeatures || {}; + const ecmaVersion = languageOptions.ecmaVersion || DEFAULT_ECMA_VERSION; + + return eslintScope.analyze(ast, { + ignoreEval: true, + nodejsScope: ecmaFeatures.globalReturn, + impliedStrict: ecmaFeatures.impliedStrict, + ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 6, + sourceType: languageOptions.sourceType || "script", + childVisitorKeys: visitorKeys || evk.KEYS, + fallback: Traverser.getKeys, + }); +} + +/** + * Runs a rule, and gets its listeners + * @param {RuleDefinition} rule A rule object + * @param {Context} ruleContext The context that should be passed to the rule + * @throws {TypeError} If `rule` is not an object with a `create` method + * @throws {any} Any error during the rule's `create` + * @returns {Object} A map of selector listeners provided by the rule + */ +function createRuleListeners(rule, ruleContext) { + if ( + !rule || + typeof rule !== "object" || + typeof rule.create !== "function" + ) { + throw new TypeError( + `Error while loading rule '${ruleContext.id}': Rule must be an object with a \`create\` method`, + ); + } + + try { + return rule.create(ruleContext); + } catch (ex) { + ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`; + throw ex; + } +} + +/** + * Runs the given rules on the given SourceCode object + * @param {SourceCode} sourceCode A SourceCode object for the given text + * @param {Object} configuredRules The rules configuration + * @param {function(string): RuleDefinition} ruleMapper A mapper function from rule names to rules + * @param {string | undefined} parserName The name of the parser in the config + * @param {Language} language The language object used for parsing. + * @param {LanguageOptions} languageOptions The options for parsing the code. + * @param {Object} settings The settings that were enabled in the config + * @param {string} filename The reported filename of the code + * @param {boolean} applyDefaultOptions If true, apply rules' meta.defaultOptions in computing their config options. + * @param {boolean} disableFixes If true, it doesn't make `fix` properties. + * @param {string | undefined} cwd cwd of the cli + * @param {string} physicalFilename The full path of the file on disk without any code block information + * @param {Function} ruleFilter A predicate function to filter which rules should be executed. + * @param {boolean} stats If true, stats are collected appended to the result + * @param {WeakMap} slots InternalSlotsMap of linter + * @returns {LintMessage[]} An array of reported problems + * @throws {Error} If traversal into a node fails. + */ +function runRules( + sourceCode, + configuredRules, + ruleMapper, + parserName, + language, + languageOptions, + settings, + filename, + applyDefaultOptions, + disableFixes, + cwd, + physicalFilename, + ruleFilter, + stats, + slots, +) { + const visitor = new SourceCodeVisitor(); + + /* + * Create a frozen object with the ruleContext properties and methods that are shared by all rules. + * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the + * properties once for each rule. + */ + const fileContext = new FileContext({ + cwd, + filename, + physicalFilename: physicalFilename || filename, + sourceCode, + parserOptions: { + ...languageOptions.parserOptions, + }, + parserPath: parserName, + languageOptions, + settings, + }); + + const lintingProblems = []; + const steps = sourceCode.traverse(); + + Object.keys(configuredRules).forEach(ruleId => { + const severity = Config.getRuleNumericSeverity(configuredRules[ruleId]); + + // not load disabled rules + if (severity === 0) { + return; + } + + if (ruleFilter && !ruleFilter({ ruleId, severity })) { + return; + } + + const rule = ruleMapper(ruleId); + + if (!rule) { + lintingProblems.push(createLintingProblem({ ruleId, language })); + return; + } + + const messageIds = rule.meta && rule.meta.messages; + let reportTranslator = null; + const ruleContext = fileContext.extend({ + id: ruleId, + options: getRuleOptions( + configuredRules[ruleId], + applyDefaultOptions ? rule.meta?.defaultOptions : void 0, + ), + report(...args) { + /* + * Create a report translator lazily. + * In a vast majority of cases, any given rule reports zero errors on a given + * piece of code. Creating a translator lazily avoids the performance cost of + * creating a new translator function for each rule that usually doesn't get + * called. + * + * Using lazy report translators improves end-to-end performance by about 3% + * with Node 8.4.0. + */ + if (reportTranslator === null) { + reportTranslator = createReportTranslator({ + ruleId, + severity, + sourceCode, + messageIds, + disableFixes, + language, + }); + } + const problem = reportTranslator(...args); + + if (problem.fix && !(rule.meta && rule.meta.fixable)) { + throw new Error( + 'Fixable rules must set the `meta.fixable` property to "code" or "whitespace".', + ); + } + if ( + problem.suggestions && + !(rule.meta && rule.meta.hasSuggestions === true) + ) { + if ( + rule.meta && + rule.meta.docs && + typeof rule.meta.docs.suggestion !== "undefined" + ) { + // Encourage migration from the former property name. + throw new Error( + "Rules with suggestions must set the `meta.hasSuggestions` property to `true`. `meta.docs.suggestion` is ignored by ESLint.", + ); + } + throw new Error( + "Rules with suggestions must set the `meta.hasSuggestions` property to `true`.", + ); + } + lintingProblems.push(problem); + }, + }); + + const ruleListenersReturn = + timing.enabled || stats + ? timing.time( + ruleId, + createRuleListeners, + stats, + )(rule, ruleContext) + : createRuleListeners(rule, ruleContext); + + const ruleListeners = stats + ? ruleListenersReturn.result + : ruleListenersReturn; + + if (stats) { + storeTime( + ruleListenersReturn.tdiff, + { type: "rules", key: ruleId }, + slots, + ); + } + + /** + * Include `ruleId` in error logs + * @param {Function} ruleListener A rule method that listens for a node. + * @returns {Function} ruleListener wrapped in error handler + */ + function addRuleErrorHandler(ruleListener) { + return function ruleErrorHandler(...listenerArgs) { + try { + const ruleListenerReturn = ruleListener(...listenerArgs); + + const ruleListenerResult = stats + ? ruleListenerReturn.result + : ruleListenerReturn; + + if (stats) { + storeTime( + ruleListenerReturn.tdiff, + { type: "rules", key: ruleId }, + slots, + ); + } + + return ruleListenerResult; + } catch (e) { + e.ruleId = ruleId; + throw e; + } + }; + } + + if (typeof ruleListeners === "undefined" || ruleListeners === null) { + throw new Error( + `The create() function for rule '${ruleId}' did not return an object.`, + ); + } + + // add all the selectors from the rule as listeners + Object.keys(ruleListeners).forEach(selector => { + const ruleListener = + timing.enabled || stats + ? timing.time(ruleId, ruleListeners[selector], stats) + : ruleListeners[selector]; + + visitor.add(selector, addRuleErrorHandler(ruleListener)); + }); + }); + + const traverser = SourceCodeTraverser.getInstance(language); + + traverser.traverseSync(sourceCode, visitor, { steps }); + + return lintingProblems; +} + +/** + * Ensure the source code to be a string. + * @param {string|SourceCode} textOrSourceCode The text or source code object. + * @returns {string} The source code text. + */ +function ensureText(textOrSourceCode) { + if (typeof textOrSourceCode === "object") { + const { hasBOM, text } = textOrSourceCode; + const bom = hasBOM ? "\uFEFF" : ""; + + return bom + text; + } + + return String(textOrSourceCode); +} + +/** + * Get an environment. + * @param {LinterInternalSlots} slots The internal slots of Linter. + * @param {string} envId The environment ID to get. + * @returns {Environment|null} The environment. + */ +function getEnv(slots, envId) { + return ( + (slots.lastConfigArray && + slots.lastConfigArray.pluginEnvironments.get(envId)) || + BuiltInEnvironments.get(envId) || + null + ); +} + +/** + * Get a rule. + * @param {LinterInternalSlots} slots The internal slots of Linter. + * @param {string} ruleId The rule ID to get. + * @returns {Rule|null} The rule. + */ +function getRule(slots, ruleId) { + return ( + (slots.lastConfigArray && + slots.lastConfigArray.pluginRules.get(ruleId)) || + slots.ruleMap.get(ruleId) + ); +} + +/** + * Normalize the value of the cwd + * @param {string | undefined} cwd raw value of the cwd, path to a directory that should be considered as the current working directory, can be undefined. + * @returns {string | undefined} normalized cwd + */ +function normalizeCwd(cwd) { + if (cwd) { + return cwd; + } + if (typeof process === "object") { + return process.cwd(); + } + + // It's more explicit to assign the undefined + // eslint-disable-next-line no-undefined -- Consistently returning a value + return undefined; +} + +/** + * The map to store private data. + * @type {WeakMap} + */ +const internalSlotsMap = new WeakMap(); + +/** + * Throws an error when the given linter is in flat config mode. + * @param {Linter} linter The linter to check. + * @returns {void} + * @throws {Error} If the linter is in flat config mode. + */ +function assertEslintrcConfig(linter) { + const { configType } = internalSlotsMap.get(linter); + + if (configType === "flat") { + throw new Error( + "This method cannot be used with flat config. Add your entries directly into the config array.", + ); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Object that is responsible for verifying JavaScript text + * @name Linter + */ +class Linter { + /** + * Initialize the Linter. + * @param {Object} [config] the config object + * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined. + * @param {Array} [config.flags] the feature flags to enable. + * @param {"flat"|"eslintrc"} [config.configType="flat"] the type of config used. + * @param {WarningService} [config.warningService] The warning service to use. + */ + constructor({ + cwd, + configType = "flat", + flags = [], + warningService = new WarningService(), + } = {}) { + const processedFlags = []; + + flags.forEach(flag => { + if (inactiveFlags.has(flag)) { + const inactiveFlagData = inactiveFlags.get(flag); + const inactivityReason = + getInactivityReasonMessage(inactiveFlagData); + const message = `The flag '${flag}' is inactive: ${inactivityReason}`; + + if (typeof inactiveFlagData.replacedBy === "undefined") { + throw new Error(message); + } + + // if there's a replacement, enable it instead of original + if (typeof inactiveFlagData.replacedBy === "string") { + processedFlags.push(inactiveFlagData.replacedBy); + } + + warningService.emitInactiveFlagWarning(flag, message); + + return; + } + + if (!activeFlags.has(flag)) { + throw new Error(`Unknown flag '${flag}'.`); + } + + processedFlags.push(flag); + }); + + internalSlotsMap.set(this, { + cwd: normalizeCwd(cwd), + flags: processedFlags, + lastConfigArray: null, + lastSourceCode: null, + lastSuppressedMessages: [], + configType, // TODO: Remove after flat config conversion + parserMap: new Map([["espree", espree]]), + ruleMap: new Rules(), + warningService, + }); + + this.version = pkg.version; + } + + /** + * Getter for package version. + * @static + * @returns {string} The version from package.json. + */ + static get version() { + return pkg.version; + } + + /** + * Indicates if the given feature flag is enabled for this instance. + * @param {string} flag The feature flag to check. + * @returns {boolean} `true` if the feature flag is enabled, `false` if not. + */ + hasFlag(flag) { + return internalSlotsMap.get(this).flags.includes(flag); + } + + /** + * Lint using eslintrc and without processors. + * @param {VFile} file The file to lint. + * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + #eslintrcVerifyWithoutProcessors(file, providedConfig, providedOptions) { + const slots = internalSlotsMap.get(this); + const config = providedConfig || {}; + const options = normalizeVerifyOptions(providedOptions, config); + + // Resolve parser. + let parserName = DEFAULT_PARSER_NAME; + let parser = espree; + + if (typeof config.parser === "object" && config.parser !== null) { + parserName = config.parser.filePath; + parser = config.parser.definition; + } else if (typeof config.parser === "string") { + if (!slots.parserMap.has(config.parser)) { + return [ + { + ruleId: null, + fatal: true, + severity: 2, + message: `Configured parser '${config.parser}' was not found.`, + line: 0, + column: 0, + nodeType: null, + }, + ]; + } + parserName = config.parser; + parser = slots.parserMap.get(config.parser); + } + + // search and apply "eslint-env *". + const envInFile = + options.allowInlineConfig && !options.warnInlineConfig + ? findEslintEnv(file.body) + : {}; + const resolvedEnvConfig = Object.assign( + { builtin: true }, + config.env, + envInFile, + ); + const enabledEnvs = Object.keys(resolvedEnvConfig) + .filter(envName => resolvedEnvConfig[envName]) + .map(envName => getEnv(slots, envName)) + .filter(env => env); + + const parserOptions = resolveParserOptions( + parser, + config.parserOptions || {}, + enabledEnvs, + ); + const configuredGlobals = resolveGlobals( + config.globals || {}, + enabledEnvs, + ); + const settings = config.settings || {}; + const languageOptions = createLanguageOptions({ + globals: config.globals, + parser, + parserOptions, + }); + + if (!slots.lastSourceCode) { + let t; + + if (options.stats) { + t = startTime(); + } + + const parserService = new ParserService(); + const parseResult = parserService.parseSync(file, { + language: jslang, + languageOptions, + }); + + if (options.stats) { + const time = endTime(t); + const timeOpts = { type: "parse" }; + + storeTime(time, timeOpts, slots); + } + + if (!parseResult.ok) { + return parseResult.errors; + } + + slots.lastSourceCode = parseResult.sourceCode; + } else { + /* + * If the given source code object as the first argument does not have scopeManager, analyze the scope. + * This is for backward compatibility (SourceCode is frozen so it cannot rebind). + */ + if (!slots.lastSourceCode.scopeManager) { + slots.lastSourceCode = new SourceCode({ + text: slots.lastSourceCode.text, + ast: slots.lastSourceCode.ast, + hasBOM: slots.lastSourceCode.hasBOM, + parserServices: slots.lastSourceCode.parserServices, + visitorKeys: slots.lastSourceCode.visitorKeys, + scopeManager: analyzeScope( + slots.lastSourceCode.ast, + languageOptions, + ), + }); + } + } + + const sourceCode = slots.lastSourceCode; + const commentDirectives = options.allowInlineConfig + ? getDirectiveComments( + sourceCode, + ruleId => getRule(slots, ruleId), + options.warnInlineConfig, + config, + ) + : { + configuredRules: {}, + enabledGlobals: {}, + exportedVariables: {}, + problems: [], + disableDirectives: [], + }; + + addDeclaredGlobals( + sourceCode.scopeManager.scopes[0], + configuredGlobals, + { + exportedVariables: commentDirectives.exportedVariables, + enabledGlobals: commentDirectives.enabledGlobals, + }, + ); + + const configuredRules = Object.assign( + {}, + config.rules, + commentDirectives.configuredRules, + ); + + let lintingProblems; + + try { + lintingProblems = runRules( + sourceCode, + configuredRules, + ruleId => getRule(slots, ruleId), + parserName, + jslang, + languageOptions, + settings, + options.filename, + true, + options.disableFixes, + slots.cwd, + providedOptions.physicalFilename, + null, + options.stats, + slots, + ); + } catch (err) { + err.message += `\nOccurred while linting ${options.filename}`; + debug("An error occurred while traversing"); + debug("Filename:", options.filename); + if (err.currentNode) { + const { line } = sourceCode.getLoc(err.currentNode).start; + + debug("Line:", line); + err.message += `:${line}`; + } + debug("Parser Options:", parserOptions); + debug("Parser Path:", parserName); + debug("Settings:", settings); + + if (err.ruleId) { + err.message += `\nRule: "${err.ruleId}"`; + } + + throw err; + } + + return applyDisableDirectives({ + language: jslang, + sourceCode, + directives: commentDirectives.disableDirectives, + disableFixes: options.disableFixes, + problems: lintingProblems + .concat(commentDirectives.problems) + .sort( + (problemA, problemB) => + problemA.line - problemB.line || + problemA.column - problemB.column, + ), + reportUnusedDisableDirectives: + options.reportUnusedDisableDirectives, + }); + } + + /** + * Same as linter.verify, except without support for processors. + * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. + * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + _verifyWithoutProcessors( + textOrSourceCode, + providedConfig, + providedOptions, + ) { + const slots = internalSlotsMap.get(this); + const filename = normalizeFilename( + providedOptions.filename || "", + ); + let text; + + // evaluate arguments + if (typeof textOrSourceCode === "string") { + slots.lastSourceCode = null; + text = textOrSourceCode; + } else { + slots.lastSourceCode = textOrSourceCode; + text = textOrSourceCode.text; + } + + const file = new VFile(filename, text, { + physicalPath: providedOptions.physicalFilename, + }); + + return this.#eslintrcVerifyWithoutProcessors( + file, + providedConfig, + providedOptions, + ); + } + + /** + * Verifies the text against the rules specified by the second argument. + * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. + * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything. + * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked. + * If this is not set, the filename will default to '' in the rule context. If + * an object, then it has "filename", "allowInlineConfig", and some properties. + * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages. + */ + verify(textOrSourceCode, config, filenameOrOptions) { + debug("Verify"); + + const { configType, cwd } = internalSlotsMap.get(this); + + const options = + typeof filenameOrOptions === "string" + ? { filename: filenameOrOptions } + : filenameOrOptions || {}; + + const configToUse = config ?? {}; + + if (configType !== "eslintrc") { + /* + * Because of how Webpack packages up the files, we can't + * compare directly to `FlatConfigArray` using `instanceof` + * because it's not the same `FlatConfigArray` as in the tests. + * So, we work around it by assuming an array is, in fact, a + * `FlatConfigArray` if it has a `getConfig()` method. + */ + let configArray = configToUse; + + if ( + !Array.isArray(configToUse) || + typeof configToUse.getConfig !== "function" + ) { + configArray = new FlatConfigArray(configToUse, { + basePath: cwd, + }); + configArray.normalizeSync(); + } + + return this._distinguishSuppressedMessages( + this._verifyWithFlatConfigArray( + textOrSourceCode, + configArray, + options, + true, + ), + ); + } + + if (typeof configToUse.extractConfig === "function") { + return this._distinguishSuppressedMessages( + this._verifyWithConfigArray( + textOrSourceCode, + configToUse, + options, + ), + ); + } + + /* + * If we get to here, it means `config` is just an object rather + * than a config array so we can go right into linting. + */ + + /* + * `Linter` doesn't support `overrides` property in configuration. + * So we cannot apply multiple processors. + */ + if (options.preprocess || options.postprocess) { + return this._distinguishSuppressedMessages( + this._verifyWithProcessor( + textOrSourceCode, + configToUse, + options, + ), + ); + } + return this._distinguishSuppressedMessages( + this._verifyWithoutProcessors( + textOrSourceCode, + configToUse, + options, + ), + ); + } + + /** + * Verify with a processor. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {Config} config The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {FlatConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively. + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithFlatConfigArrayAndProcessor( + textOrSourceCode, + config, + options, + configForRecursive, + ) { + const slots = internalSlotsMap.get(this); + const filename = options.filename || ""; + const filenameToExpose = normalizeFilename(filename); + const physicalFilename = options.physicalFilename || filenameToExpose; + const text = ensureText(textOrSourceCode); + const file = new VFile(filenameToExpose, text, { + physicalPath: physicalFilename, + }); + + const preprocess = options.preprocess || (rawText => [rawText]); + const postprocess = + options.postprocess || (messagesList => messagesList.flat()); + + const processorService = new ProcessorService(); + const preprocessResult = processorService.preprocessSync(file, { + processor: { + preprocess, + postprocess, + }, + }); + + if (!preprocessResult.ok) { + return preprocessResult.errors; + } + + const filterCodeBlock = + options.filterCodeBlock || + (blockFilename => blockFilename.endsWith(".js")); + const originalExtname = path.extname(filename); + const { files } = preprocessResult; + + const messageLists = files.map(block => { + debug("A code block was found: %o", block.path || "(unnamed)"); + + // Keep the legacy behavior. + if (typeof block === "string") { + return this._verifyWithFlatConfigArrayAndWithoutProcessors( + block, + config, + options, + ); + } + + // Skip this block if filtered. + if (!filterCodeBlock(block.path, block.body)) { + debug("This code block was skipped."); + return []; + } + + // Resolve configuration again if the file content or extension was changed. + if ( + configForRecursive && + (text !== block.rawBody || + path.extname(block.path) !== originalExtname) + ) { + debug( + "Resolving configuration again because the file content or extension was changed.", + ); + return this._verifyWithFlatConfigArray( + block.rawBody, + configForRecursive, + { + ...options, + filename: block.path, + physicalFilename: block.physicalPath, + }, + ); + } + + slots.lastSourceCode = null; + + // Does lint. + return this.#flatVerifyWithoutProcessors(block, config, { + ...options, + filename: block.path, + physicalFilename: block.physicalPath, + }); + }); + + return processorService.postprocessSync(file, messageLists, { + processor: { + preprocess, + postprocess, + }, + }); + } + + /** + * Verify using flat config and without any processors. + * @param {VFile} file The file to lint. + * @param {Config} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + #flatVerifyWithoutProcessors(file, providedConfig, providedOptions) { + const slots = internalSlotsMap.get(this); + const config = providedConfig || {}; + const { settings = {}, languageOptions } = config; + const options = normalizeVerifyOptions(providedOptions, config); + + if (!slots.lastSourceCode) { + let t; + + if (options.stats) { + t = startTime(); + } + + const parserService = new ParserService(); + const parseResult = parserService.parseSync(file, config); + + if (options.stats) { + const time = endTime(t); + + storeTime(time, { type: "parse" }, slots); + } + + if (!parseResult.ok) { + return parseResult.errors; + } + + slots.lastSourceCode = parseResult.sourceCode; + } else { + /* + * If the given source code object as the first argument does not have scopeManager, analyze the scope. + * This is for backward compatibility (SourceCode is frozen so it cannot rebind). + * + * We check explicitly for `null` to ensure that this is a JS-flavored language. + * For non-JS languages we don't want to do this. + * + * TODO: Remove this check when we stop exporting the `SourceCode` object. + */ + if (slots.lastSourceCode.scopeManager === null) { + slots.lastSourceCode = new SourceCode({ + text: slots.lastSourceCode.text, + ast: slots.lastSourceCode.ast, + hasBOM: slots.lastSourceCode.hasBOM, + parserServices: slots.lastSourceCode.parserServices, + visitorKeys: slots.lastSourceCode.visitorKeys, + scopeManager: analyzeScope( + slots.lastSourceCode.ast, + languageOptions, + ), + }); + } + } + + const sourceCode = slots.lastSourceCode; + + /* + * Make adjustments based on the language options. For JavaScript, + * this is primarily about adding variables into the global scope + * to account for ecmaVersion and configured globals. + */ + sourceCode.applyLanguageOptions?.(languageOptions); + + const mergedInlineConfig = { + rules: {}, + }; + const inlineConfigProblems = []; + + /* + * Inline config can be either enabled or disabled. If disabled, it's possible + * to detect the inline config and emit a warning (though this is not required). + * So we first check to see if inline config is allowed at all, and if so, we + * need to check if it's a warning or not. + */ + if (options.allowInlineConfig) { + // if inline config should warn then add the warnings + if (options.warnInlineConfig) { + if (sourceCode.getInlineConfigNodes) { + sourceCode.getInlineConfigNodes().forEach(node => { + const loc = sourceCode.getLoc(node); + const range = sourceCode.getRange(node); + + inlineConfigProblems.push( + createLintingProblem({ + ruleId: null, + message: `'${sourceCode.text.slice(range[0], range[1])}' has no effect because you have 'noInlineConfig' setting in ${options.warnInlineConfig}.`, + loc, + severity: 1, + language: config.language, + }), + ); + }); + } + } else { + const inlineConfigResult = sourceCode.applyInlineConfig?.(); + + if (inlineConfigResult) { + inlineConfigProblems.push( + ...inlineConfigResult.problems + .map(problem => + createLintingProblem({ + ...problem, + language: config.language, + }), + ) + .map(problem => { + problem.fatal = true; + return problem; + }), + ); + + for (const { + config: inlineConfig, + loc, + } of inlineConfigResult.configs) { + Object.keys(inlineConfig.rules).forEach(ruleId => { + const rule = config.getRuleDefinition(ruleId); + const ruleValue = inlineConfig.rules[ruleId]; + + if (!rule) { + inlineConfigProblems.push( + createLintingProblem({ + ruleId, + loc, + language: config.language, + }), + ); + return; + } + + if ( + Object.hasOwn(mergedInlineConfig.rules, ruleId) + ) { + inlineConfigProblems.push( + createLintingProblem({ + message: `Rule "${ruleId}" is already configured by another configuration comment in the preceding code. This configuration is ignored.`, + loc, + language: config.language, + }), + ); + return; + } + + try { + const ruleOptionsInline = asArray(ruleValue); + let ruleOptions = ruleOptionsInline; + + assertIsRuleSeverity(ruleId, ruleOptions[0]); + + /* + * If the rule was already configured, inline rule configuration that + * only has severity should retain options from the config and just override the severity. + * + * Example: + * + * { + * rules: { + * curly: ["error", "multi"] + * } + * } + * + * /* eslint curly: ["warn"] * / + * + * Results in: + * + * curly: ["warn", "multi"] + */ + + let shouldValidateOptions = true; + + if ( + /* + * If inline config for the rule has only severity + */ + ruleOptions.length === 1 && + /* + * And the rule was already configured + */ + config.rules && + Object.hasOwn(config.rules, ruleId) + ) { + /* + * Then use severity from the inline config and options from the provided config + */ + ruleOptions = [ + ruleOptions[0], // severity from the inline config + ...config.rules[ruleId].slice(1), // options from the provided config + ]; + + // if the rule was enabled, the options have already been validated + if (config.rules[ruleId][0] > 0) { + shouldValidateOptions = false; + } + } else { + /** + * Since we know the user provided options, apply defaults on top of them + */ + const slicedOptions = ruleOptions.slice(1); + const mergedOptions = deepMergeArrays( + rule.meta?.defaultOptions, + slicedOptions, + ); + + if (mergedOptions.length) { + ruleOptions = [ + ruleOptions[0], + ...mergedOptions, + ]; + } + } + + if ( + options.reportUnusedInlineConfigs !== "off" + ) { + addProblemIfSameSeverityAndOptions( + config, + loc, + inlineConfigProblems, + ruleId, + ruleOptions, + ruleOptionsInline, + options.reportUnusedInlineConfigs, + ); + } + + if (shouldValidateOptions) { + config.validateRulesConfig({ + [ruleId]: ruleOptions, + }); + } + + mergedInlineConfig.rules[ruleId] = ruleOptions; + } catch (err) { + /* + * If the rule has invalid `meta.schema`, throw the error because + * this is not an invalid inline configuration but an invalid rule. + */ + if ( + err.code === + "ESLINT_INVALID_RULE_OPTIONS_SCHEMA" + ) { + throw err; + } + + let baseMessage = err.message + .slice( + err.message.startsWith('Key "rules":') + ? err.message.indexOf(":", 12) + 1 + : err.message.indexOf(":") + 1, + ) + .trim(); + + if (err.messageTemplate) { + baseMessage += ` You passed "${ruleValue}".`; + } + + inlineConfigProblems.push( + createLintingProblem({ + ruleId, + message: `Inline configuration for rule "${ruleId}" is invalid:\n\t${baseMessage}\n`, + loc, + language: config.language, + }), + ); + } + }); + } + } + } + } + + const commentDirectives = + options.allowInlineConfig && !options.warnInlineConfig + ? getDirectiveCommentsForFlatConfig( + sourceCode, + ruleId => config.getRuleDefinition(ruleId), + config.language, + ) + : { problems: [], disableDirectives: [] }; + + const configuredRules = Object.assign( + {}, + config.rules, + mergedInlineConfig.rules, + ); + + let lintingProblems; + + sourceCode.finalize?.(); + + try { + lintingProblems = runRules( + sourceCode, + configuredRules, + ruleId => config.getRuleDefinition(ruleId), + void 0, + config.language, + languageOptions, + settings, + options.filename, + false, + options.disableFixes, + slots.cwd, + providedOptions.physicalFilename, + options.ruleFilter, + options.stats, + slots, + ); + } catch (err) { + err.message += `\nOccurred while linting ${options.filename}`; + debug("An error occurred while traversing"); + debug("Filename:", options.filename); + if (err.currentNode) { + const { line } = sourceCode.getLoc(err.currentNode).start; + + debug("Line:", line); + err.message += `:${line}`; + } + debug("Parser Options:", languageOptions.parserOptions); + + // debug("Parser Path:", parserName); + debug("Settings:", settings); + + if (err.ruleId) { + err.message += `\nRule: "${err.ruleId}"`; + } + + throw err; + } + + return applyDisableDirectives({ + language: config.language, + sourceCode, + directives: commentDirectives.disableDirectives, + disableFixes: options.disableFixes, + problems: lintingProblems + .concat(commentDirectives.problems) + .concat(inlineConfigProblems) + .sort( + (problemA, problemB) => + problemA.line - problemB.line || + problemA.column - problemB.column, + ), + reportUnusedDisableDirectives: + options.reportUnusedDisableDirectives, + ruleFilter: options.ruleFilter, + configuredRules, + }); + } + + /** + * Same as linter.verify, except without support for processors. + * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. + * @param {Config} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + _verifyWithFlatConfigArrayAndWithoutProcessors( + textOrSourceCode, + providedConfig, + providedOptions, + ) { + const slots = internalSlotsMap.get(this); + const filename = normalizeFilename( + providedOptions.filename || "", + ); + let text; + + // evaluate arguments + if (typeof textOrSourceCode === "string") { + slots.lastSourceCode = null; + text = textOrSourceCode; + } else { + slots.lastSourceCode = textOrSourceCode; + text = textOrSourceCode.text; + } + + const file = new VFile(filename, text, { + physicalPath: providedOptions.physicalFilename, + }); + + return this.#flatVerifyWithoutProcessors( + file, + providedConfig, + providedOptions, + ); + } + + /** + * Verify a given code with `ConfigArray`. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {ConfigArray} configArray The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithConfigArray(textOrSourceCode, configArray, options) { + debug("With ConfigArray: %s", options.filename); + + // Store the config array in order to get plugin envs and rules later. + internalSlotsMap.get(this).lastConfigArray = configArray; + + // Extract the final config for this file. + const config = configArray.extractConfig(options.filename); + const processor = + config.processor && + configArray.pluginProcessors.get(config.processor); + + // Verify. + if (processor) { + debug("Apply the processor: %o", config.processor); + const { preprocess, postprocess, supportsAutofix } = processor; + const disableFixes = options.disableFixes || !supportsAutofix; + + return this._verifyWithProcessor( + textOrSourceCode, + config, + { ...options, disableFixes, postprocess, preprocess }, + configArray, + ); + } + return this._verifyWithoutProcessors(textOrSourceCode, config, options); + } + + /** + * Verify a given code with a flat config. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {FlatConfigArray} configArray The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {boolean} [firstCall=false] Indicates if this is being called directly + * from verify(). (TODO: Remove once eslintrc is removed.) + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithFlatConfigArray( + textOrSourceCode, + configArray, + options, + firstCall = false, + ) { + debug("With flat config: %s", options.filename); + + // we need a filename to match configs against + const filename = options.filename || "__placeholder__.js"; + + // Store the config array in order to get plugin envs and rules later. + internalSlotsMap.get(this).lastConfigArray = configArray; + const config = configArray.getConfig(filename); + + if (!config) { + return [ + { + ruleId: null, + severity: 1, + message: `No matching configuration found for ${filename}.`, + line: 0, + column: 0, + nodeType: null, + }, + ]; + } + + // Verify. + if (config.processor) { + debug("Apply the processor: %o", config.processor); + const { preprocess, postprocess, supportsAutofix } = + config.processor; + const disableFixes = options.disableFixes || !supportsAutofix; + + return this._verifyWithFlatConfigArrayAndProcessor( + textOrSourceCode, + config, + { ...options, filename, disableFixes, postprocess, preprocess }, + configArray, + ); + } + + // check for options-based processing + if (firstCall && (options.preprocess || options.postprocess)) { + return this._verifyWithFlatConfigArrayAndProcessor( + textOrSourceCode, + config, + options, + ); + } + + return this._verifyWithFlatConfigArrayAndWithoutProcessors( + textOrSourceCode, + config, + options, + ); + } + + /** + * Verify with a processor. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {ConfigData|ExtractedConfig} config The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively. + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithProcessor( + textOrSourceCode, + config, + options, + configForRecursive, + ) { + const slots = internalSlotsMap.get(this); + const filename = options.filename || ""; + const filenameToExpose = normalizeFilename(filename); + const physicalFilename = options.physicalFilename || filenameToExpose; + const text = ensureText(textOrSourceCode); + const file = new VFile(filenameToExpose, text, { + physicalPath: physicalFilename, + }); + + const preprocess = options.preprocess || (rawText => [rawText]); + const postprocess = + options.postprocess || (messagesList => messagesList.flat()); + + const processorService = new ProcessorService(); + const preprocessResult = processorService.preprocessSync(file, { + processor: { + preprocess, + postprocess, + }, + }); + + if (!preprocessResult.ok) { + return preprocessResult.errors; + } + + const filterCodeBlock = + options.filterCodeBlock || + (blockFilePath => blockFilePath.endsWith(".js")); + const originalExtname = path.extname(filename); + + const { files } = preprocessResult; + + const messageLists = files.map(block => { + debug("A code block was found: %o", block.path ?? "(unnamed)"); + + // Keep the legacy behavior. + if (typeof block === "string") { + return this._verifyWithoutProcessors(block, config, options); + } + + // Skip this block if filtered. + if (!filterCodeBlock(block.path, block.body)) { + debug("This code block was skipped."); + return []; + } + + // Resolve configuration again if the file content or extension was changed. + if ( + configForRecursive && + (text !== block.rawBody || + path.extname(block.path) !== originalExtname) + ) { + debug( + "Resolving configuration again because the file content or extension was changed.", + ); + return this._verifyWithConfigArray( + block.rawBody, + configForRecursive, + { + ...options, + filename: block.path, + physicalFilename: block.physicalPath, + }, + ); + } + + slots.lastSourceCode = null; + + // Does lint. + return this.#eslintrcVerifyWithoutProcessors(block, config, { + ...options, + filename: block.path, + physicalFilename: block.physicalPath, + }); + }); + + return processorService.postprocessSync(file, messageLists, { + processor: { + preprocess, + postprocess, + }, + }); + } + + /** + * Given a list of reported problems, distinguish problems between normal messages and suppressed messages. + * The normal messages will be returned and the suppressed messages will be stored as lastSuppressedMessages. + * @param {Array} problems A list of reported problems. + * @returns {LintMessage[]} A list of LintMessage. + */ + _distinguishSuppressedMessages(problems) { + const messages = []; + const suppressedMessages = []; + const slots = internalSlotsMap.get(this); + + for (const problem of problems) { + if (problem.suppressions) { + suppressedMessages.push(problem); + } else { + messages.push(problem); + } + } + + slots.lastSuppressedMessages = suppressedMessages; + + return messages; + } + + /** + * Gets the SourceCode object representing the parsed source. + * @returns {SourceCode} The SourceCode object. + */ + getSourceCode() { + return internalSlotsMap.get(this).lastSourceCode; + } + + /** + * Gets the times spent on (parsing, fixing, linting) a file. + * @returns {{ passes: TimePass[]; }} The times. + */ + getTimes() { + return internalSlotsMap.get(this).times ?? { passes: [] }; + } + + /** + * Gets the number of autofix passes that were made in the last run. + * @returns {number} The number of autofix passes. + */ + getFixPassCount() { + return internalSlotsMap.get(this).fixPasses ?? 0; + } + + /** + * Gets the list of SuppressedLintMessage produced in the last running. + * @returns {SuppressedLintMessage[]} The list of SuppressedLintMessage + */ + getSuppressedMessages() { + return internalSlotsMap.get(this).lastSuppressedMessages; + } + + /** + * Defines a new linting rule. + * @param {string} ruleId A unique rule identifier + * @param {Rule} rule A rule object + * @returns {void} + */ + defineRule(ruleId, rule) { + assertEslintrcConfig(this); + internalSlotsMap.get(this).ruleMap.define(ruleId, rule); + } + + /** + * Defines many new linting rules. + * @param {Record} rulesToDefine map from unique rule identifier to rule + * @returns {void} + */ + defineRules(rulesToDefine) { + assertEslintrcConfig(this); + Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => { + this.defineRule(ruleId, rulesToDefine[ruleId]); + }); + } + + /** + * Gets an object with all loaded rules. + * @returns {Map} All loaded rules + */ + getRules() { + assertEslintrcConfig(this); + const { lastConfigArray, ruleMap } = internalSlotsMap.get(this); + + return new Map( + (function* () { + yield* ruleMap; + + if (lastConfigArray) { + yield* lastConfigArray.pluginRules; + } + })(), + ); + } + + /** + * Define a new parser module + * @param {string} parserId Name of the parser + * @param {Parser} parserModule The parser object + * @returns {void} + */ + defineParser(parserId, parserModule) { + assertEslintrcConfig(this); + internalSlotsMap.get(this).parserMap.set(parserId, parserModule); + } + + /** + * Performs multiple autofix passes over the text until as many fixes as possible + * have been applied. + * @param {string} text The source text to apply fixes to. + * @param {ConfigData|ConfigArray|FlatConfigArray} config The ESLint config object to use. + * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use. + * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the + * SourceCodeFixer. + */ + verifyAndFix(text, config, options) { + let messages, + fixedResult, + fixed = false, + passNumber = 0, + currentText = text, + secondPreviousText, + previousText; + const debugTextDescription = + (options && options.filename) || `${text.slice(0, 10)}...`; + const shouldFix = + options && typeof options.fix !== "undefined" ? options.fix : true; + const stats = options?.stats; + + const slots = internalSlotsMap.get(this); + + // Remove lint times from the last run. + if (stats) { + delete slots.times; + slots.fixPasses = 0; + } + + /** + * This loop continues until one of the following is true: + * + * 1. No more fixes have been applied. + * 2. Ten passes have been made. + * + * That means anytime a fix is successfully applied, there will be another pass. + * Essentially, guaranteeing a minimum of two passes. + */ + do { + passNumber++; + let tTotal; + + if (stats) { + tTotal = startTime(); + } + + debug( + `Linting code for ${debugTextDescription} (pass ${passNumber})`, + ); + messages = this.verify(currentText, config, options); + + debug( + `Generating fixed text for ${debugTextDescription} (pass ${passNumber})`, + ); + let t; + + if (stats) { + t = startTime(); + } + + fixedResult = SourceCodeFixer.applyFixes( + currentText, + messages, + shouldFix, + ); + + if (stats) { + if (fixedResult.fixed) { + const time = endTime(t); + + storeTime(time, { type: "fix" }, slots); + slots.fixPasses++; + } else { + storeTime(0, { type: "fix" }, slots); + } + } + + /* + * stop if there are any syntax errors. + * 'fixedResult.output' is a empty string. + */ + if (messages.length === 1 && messages[0].fatal) { + break; + } + + // keep track if any fixes were ever applied - important for return value + fixed = fixed || fixedResult.fixed; + + // update to use the fixed output instead of the original text + secondPreviousText = previousText; + previousText = currentText; + currentText = fixedResult.output; + + if (stats) { + tTotal = endTime(tTotal); + const passIndex = slots.times.passes.length - 1; + + slots.times.passes[passIndex].total = tTotal; + } + + // Stop if we've made a circular fix + if ( + passNumber > 1 && + currentText.length === secondPreviousText.length && + currentText === secondPreviousText + ) { + debug( + `Circular fixes detected after pass ${passNumber}. Exiting fix loop.`, + ); + slots.warningService.emitCircularFixesWarning( + options?.filename ?? "text", + ); + break; + } + } while (fixedResult.fixed && passNumber < MAX_AUTOFIX_PASSES); + + /* + * If the last result had fixes, we need to lint again to be sure we have + * the most up-to-date information. + */ + if (fixedResult.fixed) { + let tTotal; + + if (stats) { + tTotal = startTime(); + } + + fixedResult.messages = this.verify(currentText, config, options); + + if (stats) { + storeTime(0, { type: "fix" }, slots); + slots.times.passes.at(-1).total = endTime(tTotal); + } + } + + // ensure the last result properly reflects if fixes were done + fixedResult.fixed = fixed; + fixedResult.output = currentText; + + return fixedResult; + } +} + +module.exports = { + Linter, + + /** + * Get the internal slots of a given Linter instance for tests. + * @param {Linter} instance The Linter instance to get. + * @returns {LinterInternalSlots} The internal slots. + */ + getLinterInternalSlots(instance) { + return internalSlotsMap.get(instance); + }, +}; diff --git a/node_modules/eslint/lib/linter/report-translator.js b/node_modules/eslint/lib/linter/report-translator.js new file mode 100644 index 00000000..f4243186 --- /dev/null +++ b/node_modules/eslint/lib/linter/report-translator.js @@ -0,0 +1,414 @@ +/** + * @fileoverview A helper that translates context.report() calls from the rule API into generic problem objects + * @author Teddy Katz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("../shared/assert"); +const { RuleFixer } = require("./rule-fixer"); +const { interpolate } = require("./interpolate"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").Linter.LintSuggestion} SuggestionResult */ + +/** + * An error message description + * @typedef {Object} MessageDescriptor + * @property {ASTNode} [node] The reported node + * @property {Location} loc The location of the problem. + * @property {string} message The problem message. + * @property {Object} [data] Optional data to use to fill in placeholders in the + * message. + * @property {Function} [fix] The function to call that creates a fix command. + * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes. + */ + +//------------------------------------------------------------------------------ +// Module Definition +//------------------------------------------------------------------------------ + +/** + * Translates a multi-argument context.report() call into a single object argument call + * @param {...*} args A list of arguments passed to `context.report` + * @returns {MessageDescriptor} A normalized object containing report information + */ +function normalizeMultiArgReportCall(...args) { + // If there is one argument, it is considered to be a new-style call already. + if (args.length === 1) { + // Shallow clone the object to avoid surprises if reusing the descriptor + return Object.assign({}, args[0]); + } + + // If the second argument is a string, the arguments are interpreted as [node, message, data, fix]. + if (typeof args[1] === "string") { + return { + node: args[0], + message: args[1], + data: args[2], + fix: args[3], + }; + } + + // Otherwise, the arguments are interpreted as [node, loc, message, data, fix]. + return { + node: args[0], + loc: args[1], + message: args[2], + data: args[3], + fix: args[4], + }; +} + +/** + * Asserts that either a loc or a node was provided, and the node is valid if it was provided. + * @param {MessageDescriptor} descriptor A descriptor to validate + * @returns {void} + * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object + */ +function assertValidNodeInfo(descriptor) { + if (descriptor.node) { + assert(typeof descriptor.node === "object", "Node must be an object"); + } else { + assert( + descriptor.loc, + "Node must be provided when reporting error if location is not provided", + ); + } +} + +/** + * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties + * @param {MessageDescriptor} descriptor A descriptor for the report from a rule. + * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties + * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor. + */ +function normalizeReportLoc(descriptor) { + if (descriptor.loc.start) { + return descriptor.loc; + } + return { start: descriptor.loc, end: null }; +} + +/** + * Clones the given fix object. + * @param {Fix|null} fix The fix to clone. + * @returns {Fix|null} Deep cloned fix object or `null` if `null` or `undefined` was passed in. + */ +function cloneFix(fix) { + if (!fix) { + return null; + } + + return { + range: [fix.range[0], fix.range[1]], + text: fix.text, + }; +} + +/** + * Check that a fix has a valid range. + * @param {Fix|null} fix The fix to validate. + * @returns {void} + */ +function assertValidFix(fix) { + if (fix) { + assert( + fix.range && + typeof fix.range[0] === "number" && + typeof fix.range[1] === "number", + `Fix has invalid range: ${JSON.stringify(fix, null, 2)}`, + ); + } +} + +/** + * Compares items in a fixes array by range. + * @param {Fix} a The first message. + * @param {Fix} b The second message. + * @returns {number} -1 if a comes before b, 1 if a comes after b, 0 if equal. + * @private + */ +function compareFixesByRange(a, b) { + return a.range[0] - b.range[0] || a.range[1] - b.range[1]; +} + +/** + * Merges the given fixes array into one. + * @param {Fix[]} fixes The fixes to merge. + * @param {SourceCode} sourceCode The source code object to get the text between fixes. + * @returns {{text: string, range: number[]}} The merged fixes + */ +function mergeFixes(fixes, sourceCode) { + for (const fix of fixes) { + assertValidFix(fix); + } + + if (fixes.length === 0) { + return null; + } + if (fixes.length === 1) { + return cloneFix(fixes[0]); + } + + fixes.sort(compareFixesByRange); + + const originalText = sourceCode.text; + const start = fixes[0].range[0]; + const end = fixes.at(-1).range[1]; + let text = ""; + let lastPos = Number.MIN_SAFE_INTEGER; + + for (const fix of fixes) { + assert( + fix.range[0] >= lastPos, + "Fix objects must not be overlapped in a report.", + ); + + if (fix.range[0] >= 0) { + text += originalText.slice( + Math.max(0, start, lastPos), + fix.range[0], + ); + } + text += fix.text; + lastPos = fix.range[1]; + } + text += originalText.slice(Math.max(0, start, lastPos), end); + + return { range: [start, end], text }; +} + +/** + * Gets one fix object from the given descriptor. + * If the descriptor retrieves multiple fixes, this merges those to one. + * @param {MessageDescriptor} descriptor The report descriptor. + * @param {SourceCode} sourceCode The source code object to get text between fixes. + * @returns {({text: string, range: number[]}|null)} The fix for the descriptor + */ +function normalizeFixes(descriptor, sourceCode) { + if (typeof descriptor.fix !== "function") { + return null; + } + + const ruleFixer = new RuleFixer({ sourceCode }); + + // @type {null | Fix | Fix[] | IterableIterator} + const fix = descriptor.fix(ruleFixer); + + // Merge to one. + if (fix && Symbol.iterator in fix) { + return mergeFixes(Array.from(fix), sourceCode); + } + + assertValidFix(fix); + return cloneFix(fix); +} + +/** + * Gets an array of suggestion objects from the given descriptor. + * @param {MessageDescriptor} descriptor The report descriptor. + * @param {SourceCode} sourceCode The source code object to get text between fixes. + * @param {Object} messages Object of meta messages for the rule. + * @returns {Array} The suggestions for the descriptor + */ +function mapSuggestions(descriptor, sourceCode, messages) { + if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) { + return []; + } + + return ( + descriptor.suggest + .map(suggestInfo => { + const computedDesc = + suggestInfo.desc || messages[suggestInfo.messageId]; + + return { + ...suggestInfo, + desc: interpolate(computedDesc, suggestInfo.data), + fix: normalizeFixes(suggestInfo, sourceCode), + }; + }) + + // Remove suggestions that didn't provide a fix + .filter(({ fix }) => fix) + ); +} + +/** + * Creates information about the report from a descriptor + * @param {Object} options Information about the problem + * @param {string} options.ruleId Rule ID + * @param {(0|1|2)} options.severity Rule severity + * @param {(ASTNode|null)} options.node Node + * @param {string} options.message Error message + * @param {string} [options.messageId] The error message ID. + * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location + * @param {{text: string, range: (number[]|null)}} options.fix The fix object + * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects + * @param {Language} [options.language] The language to use to adjust line and column offsets. + * @returns {LintMessage} Information about the report + */ +function createProblem(options) { + const { language } = options; + + // calculate offsets based on the language in use + const columnOffset = language.columnStart === 1 ? 0 : 1; + const lineOffset = language.lineStart === 1 ? 0 : 1; + + const problem = { + ruleId: options.ruleId, + severity: options.severity, + message: options.message, + line: options.loc.start.line + lineOffset, + column: options.loc.start.column + columnOffset, + nodeType: (options.node && options.node.type) || null, + }; + + /* + * If this isn’t in the conditional, some of the tests fail + * because `messageId` is present in the problem object + */ + if (options.messageId) { + problem.messageId = options.messageId; + } + + if (options.loc.end) { + problem.endLine = options.loc.end.line + lineOffset; + problem.endColumn = options.loc.end.column + columnOffset; + } + + if (options.fix) { + problem.fix = options.fix; + } + + if (options.suggestions && options.suggestions.length > 0) { + problem.suggestions = options.suggestions; + } + + return problem; +} + +/** + * Validates that suggestions are properly defined. Throws if an error is detected. + * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data. + * @param {Object} messages Object of meta messages for the rule. + * @returns {void} + */ +function validateSuggestions(suggest, messages) { + if (suggest && Array.isArray(suggest)) { + suggest.forEach(suggestion => { + if (suggestion.messageId) { + const { messageId } = suggestion; + + if (!messages) { + throw new TypeError( + `context.report() called with a suggest option with a messageId '${messageId}', but no messages were present in the rule metadata.`, + ); + } + + if (!messages[messageId]) { + throw new TypeError( + `context.report() called with a suggest option with a messageId '${messageId}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`, + ); + } + + if (suggestion.desc) { + throw new TypeError( + "context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one.", + ); + } + } else if (!suggestion.desc) { + throw new TypeError( + "context.report() called with a suggest option that doesn't have either a `desc` or `messageId`", + ); + } + + if (typeof suggestion.fix !== "function") { + throw new TypeError( + `context.report() called with a suggest option without a fix function. See: ${suggestion}`, + ); + } + }); + } +} + +/** + * Returns a function that converts the arguments of a `context.report` call from a rule into a reported + * problem for the Node.js API. + * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean, language:Language}} metadata Metadata for the reported problem + * @returns {function(...args): LintMessage} Function that returns information about the report + */ + +module.exports = function createReportTranslator(metadata) { + /* + * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant. + * The report translator itself (i.e. the function that `createReportTranslator` returns) gets + * called every time a rule reports a problem, which happens much less frequently (usually, the vast + * majority of rules don't report any problems for a given file). + */ + return (...args) => { + const descriptor = normalizeMultiArgReportCall(...args); + const messages = metadata.messageIds; + const { sourceCode } = metadata; + + assertValidNodeInfo(descriptor); + + let computedMessage; + + if (descriptor.messageId) { + if (!messages) { + throw new TypeError( + "context.report() called with a messageId, but no messages were present in the rule metadata.", + ); + } + const id = descriptor.messageId; + + if (descriptor.message) { + throw new TypeError( + "context.report() called with a message and a messageId. Please only pass one.", + ); + } + if (!messages || !Object.hasOwn(messages, id)) { + throw new TypeError( + `context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`, + ); + } + computedMessage = messages[id]; + } else if (descriptor.message) { + computedMessage = descriptor.message; + } else { + throw new TypeError( + "Missing `message` property in report() call; add a message that describes the linting problem.", + ); + } + + validateSuggestions(descriptor.suggest, messages); + + return createProblem({ + ruleId: metadata.ruleId, + severity: metadata.severity, + node: descriptor.node, + message: interpolate(computedMessage, descriptor.data), + messageId: descriptor.messageId, + loc: descriptor.loc + ? normalizeReportLoc(descriptor) + : sourceCode.getLoc(descriptor.node), + fix: metadata.disableFixes + ? null + : normalizeFixes(descriptor, sourceCode), + suggestions: metadata.disableFixes + ? [] + : mapSuggestions(descriptor, sourceCode, messages), + language: metadata.language, + }); + }; +}; diff --git a/node_modules/eslint/lib/linter/rule-fixer.js b/node_modules/eslint/lib/linter/rule-fixer.js new file mode 100644 index 00000000..e73dac67 --- /dev/null +++ b/node_modules/eslint/lib/linter/rule-fixer.js @@ -0,0 +1,169 @@ +/** + * @fileoverview An object that creates fix commands for rules. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceRange } from "@eslint/core"; + */ + +/* eslint class-methods-use-this: off -- Methods desired on instance */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Creates a fix command that inserts text at the specified index in the source text. + * @param {number} index The 0-based index at which to insert the new text. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + * @private + */ +function insertTextAt(index, text) { + return { + range: [index, index], + text, + }; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Creates code fixing commands for rules. + */ +class RuleFixer { + /** + * The source code object representing the text to be fixed. + * @type {SourceCode} + */ + #sourceCode; + + /** + * Creates a new instance. + * @param {Object} options The options for the fixer. + * @param {SourceCode} options.sourceCode The source code object representing the text to be fixed. + */ + constructor({ sourceCode }) { + this.#sourceCode = sourceCode; + } + + /** + * Creates a fix command that inserts text after the given node or token. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to insert after. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextAfter(nodeOrToken, text) { + const range = this.#sourceCode.getRange(nodeOrToken); + + return this.insertTextAfterRange(range, text); + } + + /** + * Creates a fix command that inserts text after the specified range in the source text. + * The fix is not applied until applyFixes() is called. + * @param {SourceRange} range The range to replace, first item is start of range, second + * is end of range. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextAfterRange(range, text) { + return insertTextAt(range[1], text); + } + + /** + * Creates a fix command that inserts text before the given node or token. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to insert before. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextBefore(nodeOrToken, text) { + const range = this.#sourceCode.getRange(nodeOrToken); + + return this.insertTextBeforeRange(range, text); + } + + /** + * Creates a fix command that inserts text before the specified range in the source text. + * The fix is not applied until applyFixes() is called. + * @param {SourceRange} range The range to replace, first item is start of range, second + * is end of range. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextBeforeRange(range, text) { + return insertTextAt(range[0], text); + } + + /** + * Creates a fix command that replaces text at the node or token. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to remove. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + replaceText(nodeOrToken, text) { + const range = this.#sourceCode.getRange(nodeOrToken); + + return this.replaceTextRange(range, text); + } + + /** + * Creates a fix command that replaces text at the specified range in the source text. + * The fix is not applied until applyFixes() is called. + * @param {SourceRange} range The range to replace, first item is start of range, second + * is end of range. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + replaceTextRange(range, text) { + return { + range, + text, + }; + } + + /** + * Creates a fix command that removes the node or token from the source. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to remove. + * @returns {Object} The fix command. + */ + remove(nodeOrToken) { + const range = this.#sourceCode.getRange(nodeOrToken); + + return this.removeRange(range); + } + + /** + * Creates a fix command that removes the specified range of text from the source. + * The fix is not applied until applyFixes() is called. + * @param {SourceRange} range The range to remove, first item is start of range, second + * is end of range. + * @returns {Object} The fix command. + */ + removeRange(range) { + return { + range, + text: "", + }; + } +} + +module.exports = { RuleFixer }; diff --git a/node_modules/eslint/lib/linter/rules.js b/node_modules/eslint/lib/linter/rules.js new file mode 100644 index 00000000..ec017eef --- /dev/null +++ b/node_modules/eslint/lib/linter/rules.js @@ -0,0 +1,71 @@ +/** + * @fileoverview Defines a storage for rules. + * @author Nicholas C. Zakas + * @author aladdin-add + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const builtInRules = require("../rules"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../types").Rule.RuleModule} Rule */ + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A storage for rules. + */ +class Rules { + constructor() { + this._rules = Object.create(null); + } + + /** + * Registers a rule module for rule id in storage. + * @param {string} ruleId Rule id (file name). + * @param {Rule} rule Rule object. + * @returns {void} + */ + define(ruleId, rule) { + this._rules[ruleId] = rule; + } + + /** + * Access rule handler by id (file name). + * @param {string} ruleId Rule id (file name). + * @returns {Rule} Rule object. + */ + get(ruleId) { + if (typeof this._rules[ruleId] === "string") { + this.define(ruleId, require(this._rules[ruleId])); + } + if (this._rules[ruleId]) { + return this._rules[ruleId]; + } + if (builtInRules.has(ruleId)) { + return builtInRules.get(ruleId); + } + + return null; + } + + *[Symbol.iterator]() { + yield* builtInRules; + + for (const ruleId of Object.keys(this._rules)) { + yield [ruleId, this.get(ruleId)]; + } + } +} + +module.exports = Rules; diff --git a/node_modules/eslint/lib/linter/source-code-fixer.js b/node_modules/eslint/lib/linter/source-code-fixer.js new file mode 100644 index 00000000..2cea2c60 --- /dev/null +++ b/node_modules/eslint/lib/linter/source-code-fixer.js @@ -0,0 +1,154 @@ +/** + * @fileoverview An object that caches and applies source code fixes. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const debug = require("debug")("eslint:source-code-fixer"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const BOM = "\uFEFF"; + +/** + * Compares items in a messages array by range. + * @param {Message} a The first message. + * @param {Message} b The second message. + * @returns {number} -1 if a comes before b, 1 if a comes after b, 0 if equal. + * @private + */ +function compareMessagesByFixRange(a, b) { + return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1]; +} + +/** + * Compares items in a messages array by line and column. + * @param {Message} a The first message. + * @param {Message} b The second message. + * @returns {number} -1 if a comes before b, 1 if a comes after b, 0 if equal. + * @private + */ +function compareMessagesByLocation(a, b) { + return a.line - b.line || a.column - b.column; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Utility for apply fixes to source code. + * @constructor + */ +function SourceCodeFixer() { + Object.freeze(this); +} + +/** + * Applies the fixes specified by the messages to the given text. Tries to be + * smart about the fixes and won't apply fixes over the same area in the text. + * @param {string} sourceText The text to apply the changes to. + * @param {Message[]} messages The array of messages reported by ESLint. + * @param {boolean|Function} [shouldFix=true] Determines whether each message should be fixed + * @returns {Object} An object containing the fixed text and any unfixed messages. + */ +SourceCodeFixer.applyFixes = function (sourceText, messages, shouldFix) { + debug("Applying fixes"); + + if (shouldFix === false) { + debug("shouldFix parameter was false, not attempting fixes"); + return { + fixed: false, + messages, + output: sourceText, + }; + } + + // clone the array + const remainingMessages = [], + fixes = [], + bom = sourceText.startsWith(BOM) ? BOM : "", + text = bom ? sourceText.slice(1) : sourceText; + let lastPos = Number.NEGATIVE_INFINITY, + output = bom; + + /** + * Try to use the 'fix' from a problem. + * @param {Message} problem The message object to apply fixes from + * @returns {boolean} Whether fix was successfully applied + */ + function attemptFix(problem) { + const fix = problem.fix; + const start = fix.range[0]; + const end = fix.range[1]; + + // Remain it as a problem if it's overlapped or it's a negative range + if (lastPos >= start || start > end) { + remainingMessages.push(problem); + return false; + } + + // Remove BOM. + if ( + (start < 0 && end >= 0) || + (start === 0 && fix.text.startsWith(BOM)) + ) { + output = ""; + } + + // Make output to this fix. + output += text.slice(Math.max(0, lastPos), Math.max(0, start)); + output += fix.text; + lastPos = end; + return true; + } + + messages.forEach(problem => { + if (Object.hasOwn(problem, "fix") && problem.fix) { + fixes.push(problem); + } else { + remainingMessages.push(problem); + } + }); + + if (fixes.length) { + debug("Found fixes to apply"); + let fixesWereApplied = false; + + for (const problem of fixes.sort(compareMessagesByFixRange)) { + if (typeof shouldFix !== "function" || shouldFix(problem)) { + attemptFix(problem); + + /* + * The only time attemptFix will fail is if a previous fix was + * applied which conflicts with it. So we can mark this as true. + */ + fixesWereApplied = true; + } else { + remainingMessages.push(problem); + } + } + output += text.slice(Math.max(0, lastPos)); + + return { + fixed: fixesWereApplied, + messages: remainingMessages.sort(compareMessagesByLocation), + output, + }; + } + + debug("No fixes to apply"); + return { + fixed: false, + messages, + output: bom + text, + }; +}; + +module.exports = SourceCodeFixer; diff --git a/node_modules/eslint/lib/linter/source-code-traverser.js b/node_modules/eslint/lib/linter/source-code-traverser.js new file mode 100644 index 00000000..32b94b1f --- /dev/null +++ b/node_modules/eslint/lib/linter/source-code-traverser.js @@ -0,0 +1,327 @@ +/** + * @fileoverview Traverser for SourceCode objects. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { parse, matches } = require("./esquery"); +const vk = require("eslint-visitor-keys"); + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * @import { ESQueryParsedSelector } from "./esquery.js"; + * @import { Language, SourceCode } from "@eslint/core"; + * @import { SourceCodeVisitor } from "./source-code-visitor.js"; + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const STEP_KIND_VISIT = 1; +const STEP_KIND_CALL = 2; + +/** + * Compares two ESQuery selectors by specificity. + * @param {ESQueryParsedSelector} a The first selector to compare. + * @param {ESQueryParsedSelector} b The second selector to compare. + * @returns {number} A negative number if `a` is less specific than `b` or they are equally specific and `a` <= `b` alphabetically, a positive number if `a` is more specific than `b`. + */ +function compareSpecificity(a, b) { + return a.compare(b); +} + +/** + * Helper to wrap ESQuery operations. + */ +class ESQueryHelper { + /** + * Creates a new instance. + * @param {SourceCodeVisitor} visitor The visitor containing the functions to call. + * @param {ESQueryOptions} esqueryOptions `esquery` options for traversing custom nodes. + * @returns {NodeEventGenerator} new instance + */ + constructor(visitor, esqueryOptions) { + /** + * The emitter to use during traversal. + * @type {SourceCodeVisitor} + */ + this.visitor = visitor; + + /** + * The options for `esquery` to use during matching. + * @type {ESQueryOptions} + */ + this.esqueryOptions = esqueryOptions; + + /** + * A map of node type to selectors targeting that node type on the + * enter phase of traversal. + * @type {Map} + */ + this.enterSelectorsByNodeType = new Map(); + + /** + * A map of node type to selectors targeting that node type on the + * exit phase of traversal. + * @type {Map} + */ + this.exitSelectorsByNodeType = new Map(); + + /** + * An array of selectors that match any node type on the + * enter phase of traversal. + * @type {ESQueryParsedSelector[]} + */ + this.anyTypeEnterSelectors = []; + + /** + * An array of selectors that match any node type on the + * exit phase of traversal. + * @type {ESQueryParsedSelector[]} + */ + this.anyTypeExitSelectors = []; + + visitor.forEachName(rawSelector => { + const selector = parse(rawSelector); + + /* + * If this selector has identified specific node types, + * add it to the map for these node types for faster lookup. + */ + if (selector.nodeTypes) { + const typeMap = selector.isExit + ? this.exitSelectorsByNodeType + : this.enterSelectorsByNodeType; + + selector.nodeTypes.forEach(nodeType => { + if (!typeMap.has(nodeType)) { + typeMap.set(nodeType, []); + } + typeMap.get(nodeType).push(selector); + }); + return; + } + + /* + * Remaining selectors are added to the "any type" selectors + * list for the appropriate phase of traversal. This ensures + * that all selectors will still be applied even if no + * specific node type is matched. + */ + const selectors = selector.isExit + ? this.anyTypeExitSelectors + : this.anyTypeEnterSelectors; + + selectors.push(selector); + }); + + // sort all selectors by specificity for prioritizing call order + this.anyTypeEnterSelectors.sort(compareSpecificity); + this.anyTypeExitSelectors.sort(compareSpecificity); + this.enterSelectorsByNodeType.forEach(selectorList => + selectorList.sort(compareSpecificity), + ); + this.exitSelectorsByNodeType.forEach(selectorList => + selectorList.sort(compareSpecificity), + ); + } + + /** + * Checks if a node matches a given selector. + * @param {ASTNode} node The node to check + * @param {ASTNode[]} ancestry The ancestry of the node being checked. + * @param {ESQueryParsedSelector} selector An AST selector descriptor + * @returns {boolean} `true` if the selector matches the node, `false` otherwise + */ + matches(node, ancestry, selector) { + return matches(node, selector.root, ancestry, this.esqueryOptions); + } + + /** + * Calculates all appropriate selectors to a node, in specificity order + * @param {ASTNode} node The node to check + * @param {ASTNode[]} ancestry The ancestry of the node being checked. + * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited + * @returns {string[]} An array of selectors that match the node. + */ + calculateSelectors(node, ancestry, isExit) { + const nodeTypeKey = this.esqueryOptions?.nodeTypeKey || "type"; + const selectors = []; + + /* + * Get the selectors that may match this node. First, check + * to see if the node type has specific selectors, + * then gather the "any type" selectors. + */ + const selectorsByNodeType = + (isExit + ? this.exitSelectorsByNodeType + : this.enterSelectorsByNodeType + ).get(node[nodeTypeKey]) || []; + const anyTypeSelectors = isExit + ? this.anyTypeExitSelectors + : this.anyTypeEnterSelectors; + + /* + * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor. + * Iterate through each of them, applying selectors in the right order. + */ + let selectorsByNodeTypeIndex = 0; + let anyTypeSelectorsIndex = 0; + + while ( + selectorsByNodeTypeIndex < selectorsByNodeType.length || + anyTypeSelectorsIndex < anyTypeSelectors.length + ) { + /* + * If we've already exhausted the selectors for this node type, + * or if the next any type selector is more specific than the + * next selector for this node type, apply the any type selector. + */ + const hasMoreNodeTypeSelectors = + selectorsByNodeTypeIndex < selectorsByNodeType.length; + const hasMoreAnyTypeSelectors = + anyTypeSelectorsIndex < anyTypeSelectors.length; + const anyTypeSelector = anyTypeSelectors[anyTypeSelectorsIndex]; + const nodeTypeSelector = + selectorsByNodeType[selectorsByNodeTypeIndex]; + + // Only compare specificity if both selectors exist + const isAnyTypeSelectorLessSpecific = + hasMoreAnyTypeSelectors && + hasMoreNodeTypeSelectors && + anyTypeSelector.compare(nodeTypeSelector) < 0; + + if (!hasMoreNodeTypeSelectors || isAnyTypeSelectorLessSpecific) { + anyTypeSelectorsIndex++; + + if (this.matches(node, ancestry, anyTypeSelector)) { + selectors.push(anyTypeSelector.source); + } + } else { + selectorsByNodeTypeIndex++; + + if (this.matches(node, ancestry, nodeTypeSelector)) { + selectors.push(nodeTypeSelector.source); + } + } + } + + return selectors; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Traverses source code and ensures that visitor methods are called when + * entering and leaving each node. + */ +class SourceCodeTraverser { + /** + * The language of the source code being traversed. + * @type {Language} + */ + #language; + + /** + * Map of languages to instances of this class. + * @type {WeakMap} + */ + static instances = new WeakMap(); + + /** + * Creates a new instance. + * @param {Language} language The language of the source code being traversed. + */ + constructor(language) { + this.#language = language; + } + + static getInstance(language) { + if (!this.instances.has(language)) { + this.instances.set(language, new this(language)); + } + + return this.instances.get(language); + } + + /** + * Traverses the given source code synchronously. + * @param {SourceCode} sourceCode The source code to traverse. + * @param {SourceCodeVisitor} visitor The emitter to use for events. + * @param {Object} options Options for traversal. + * @param {ReturnType} options.steps The steps to take during traversal. + * @returns {void} + * @throws {Error} If an error occurs during traversal. + */ + traverseSync(sourceCode, visitor, { steps } = {}) { + const esquery = new ESQueryHelper(visitor, { + visitorKeys: sourceCode.visitorKeys ?? this.#language.visitorKeys, + fallback: vk.getKeys, + matchClass: this.#language.matchesSelectorClass ?? (() => false), + nodeTypeKey: this.#language.nodeTypeKey, + }); + + const currentAncestry = []; + + for (const step of steps ?? sourceCode.traverse()) { + switch (step.kind) { + case STEP_KIND_VISIT: { + try { + if (step.phase === 1) { + esquery + .calculateSelectors( + step.target, + currentAncestry, + false, + ) + .forEach(selector => { + visitor.callSync(selector, step.target); + }); + currentAncestry.unshift(step.target); + } else { + currentAncestry.shift(); + esquery + .calculateSelectors( + step.target, + currentAncestry, + true, + ) + .forEach(selector => { + visitor.callSync(selector, step.target); + }); + } + } catch (err) { + err.currentNode = step.target; + throw err; + } + break; + } + + case STEP_KIND_CALL: { + visitor.callSync(step.target, ...step.args); + break; + } + + default: + throw new Error( + `Invalid traversal step found: "${step.kind}".`, + ); + } + } + } +} + +module.exports = { SourceCodeTraverser }; diff --git a/node_modules/eslint/lib/linter/source-code-visitor.js b/node_modules/eslint/lib/linter/source-code-visitor.js new file mode 100644 index 00000000..0f5af565 --- /dev/null +++ b/node_modules/eslint/lib/linter/source-code-visitor.js @@ -0,0 +1,81 @@ +/** + * @fileoverview SourceCodeVisitor class + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const emptyArray = Object.freeze([]); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * A structure to hold a list of functions to call for a given name. + * This is used to allow multiple rules to register functions for a given name + * without having to know about each other. + */ +class SourceCodeVisitor { + /** + * The functions to call for a given name. + * @type {Map} + */ + #functions = new Map(); + + /** + * Adds a function to the list of functions to call for a given name. + * @param {string} name The name of the function to call. + * @param {Function} func The function to call. + * @returns {void} + */ + add(name, func) { + if (this.#functions.has(name)) { + this.#functions.get(name).push(func); + } else { + this.#functions.set(name, [func]); + } + } + + /** + * Gets the list of functions to call for a given name. + * @param {string} name The name of the function to call. + * @returns {Function[]} The list of functions to call. + */ + get(name) { + if (this.#functions.has(name)) { + return this.#functions.get(name); + } + + return emptyArray; + } + + /** + * Iterates over all names and calls the callback with the name. + * @param {(name:string) => void} callback The callback to call for each name. + * @returns {void} + */ + forEachName(callback) { + this.#functions.forEach((funcs, name) => { + callback(name); + }); + } + + /** + * Calls the functions for a given name with the given arguments. + * @param {string} name The name of the function to call. + * @param {any[]} args The arguments to pass to the function. + * @returns {void} + */ + callSync(name, ...args) { + if (this.#functions.has(name)) { + this.#functions.get(name).forEach(func => func(...args)); + } + } +} + +module.exports = { SourceCodeVisitor }; diff --git a/node_modules/eslint/lib/linter/timing.js b/node_modules/eslint/lib/linter/timing.js new file mode 100644 index 00000000..f0aa1d2e --- /dev/null +++ b/node_modules/eslint/lib/linter/timing.js @@ -0,0 +1,172 @@ +/** + * @fileoverview Tracks performance of individual rules. + * @author Brandon Mills + */ + +"use strict"; + +const { startTime, endTime } = require("../shared/stats"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/* c8 ignore next */ +/** + * Align the string to left + * @param {string} str string to evaluate + * @param {number} len length of the string + * @param {string} ch delimiter character + * @returns {string} modified string + * @private + */ +function alignLeft(str, len, ch) { + return str + new Array(len - str.length + 1).join(ch || " "); +} + +/* c8 ignore next */ +/** + * Align the string to right + * @param {string} str string to evaluate + * @param {number} len length of the string + * @param {string} ch delimiter character + * @returns {string} modified string + * @private + */ +function alignRight(str, len, ch) { + return new Array(len - str.length + 1).join(ch || " ") + str; +} + +//------------------------------------------------------------------------------ +// Module definition +//------------------------------------------------------------------------------ + +const enabled = !!process.env.TIMING; + +const HEADERS = ["Rule", "Time (ms)", "Relative"]; +const ALIGN = [alignLeft, alignRight, alignRight]; + +/** + * Decide how many rules to show in the output list. + * @returns {number} the number of rules to show + */ +function getListSize() { + const MINIMUM_SIZE = 10; + + if (typeof process.env.TIMING !== "string") { + return MINIMUM_SIZE; + } + + if (process.env.TIMING.toLowerCase() === "all") { + return Number.POSITIVE_INFINITY; + } + + const TIMING_ENV_VAR_AS_INTEGER = Number.parseInt(process.env.TIMING, 10); + + return TIMING_ENV_VAR_AS_INTEGER > 10 + ? TIMING_ENV_VAR_AS_INTEGER + : MINIMUM_SIZE; +} + +/* c8 ignore next */ +/** + * display the data + * @param {Object} data Data object to be displayed + * @returns {void} prints modified string with console.log + * @private + */ +function display(data) { + let total = 0; + const rows = Object.keys(data) + .map(key => { + const time = data[key]; + + total += time; + return [key, time]; + }) + .sort((a, b) => b[1] - a[1]) + .slice(0, getListSize()); + + rows.forEach(row => { + row.push(`${((row[1] * 100) / total).toFixed(1)}%`); + row[1] = row[1].toFixed(3); + }); + + rows.unshift(HEADERS); + + const widths = []; + + rows.forEach(row => { + const len = row.length; + + for (let i = 0; i < len; i++) { + const n = row[i].length; + + if (!widths[i] || n > widths[i]) { + widths[i] = n; + } + } + }); + + const table = rows.map(row => + row.map((cell, index) => ALIGN[index](cell, widths[index])).join(" | "), + ); + + table.splice( + 1, + 0, + widths + .map((width, index) => { + const extraAlignment = + index !== 0 && index !== widths.length - 1 ? 2 : 1; + + return ALIGN[index](":", width + extraAlignment, "-"); + }) + .join("|"), + ); + + console.log(table.join("\n")); // eslint-disable-line no-console -- Debugging function +} + +/* c8 ignore next */ +module.exports = (function () { + const data = Object.create(null); + + /** + * Time the run + * @param {any} key key from the data object + * @param {Function} fn function to be called + * @param {boolean} stats if 'stats' is true, return the result and the time difference + * @returns {Function} function to be executed + * @private + */ + function time(key, fn, stats) { + return function (...args) { + const t = startTime(); + const result = fn(...args); + const tdiff = endTime(t); + + if (enabled) { + if (typeof data[key] === "undefined") { + data[key] = 0; + } + + data[key] += tdiff; + } + + return stats ? { result, tdiff } : result; + }; + } + + if (enabled) { + process.on("exit", () => { + display(data); + }); + } + + return { + time, + enabled, + getListSize, + }; +})(); diff --git a/node_modules/eslint/lib/linter/vfile.js b/node_modules/eslint/lib/linter/vfile.js new file mode 100644 index 00000000..4bdbf991 --- /dev/null +++ b/node_modules/eslint/lib/linter/vfile.js @@ -0,0 +1,115 @@ +/** + * @fileoverview Virtual file + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").File} File */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if a given value has a byte order mark (BOM). + * @param {string|Uint8Array} value The value to check. + * @returns {boolean} `true` if the value has a BOM, `false` otherwise. + */ +function hasUnicodeBOM(value) { + return typeof value === "string" + ? value.charCodeAt(0) === 0xfeff + : value[0] === 0xef && value[1] === 0xbb && value[2] === 0xbf; +} + +/** + * Strips Unicode BOM from the given value. + * @param {string|Uint8Array} value The value to remove the BOM from. + * @returns {string|Uint8Array} The stripped value. + */ +function stripUnicodeBOM(value) { + if (!hasUnicodeBOM(value)) { + return value; + } + + if (typeof value === "string") { + /* + * Check Unicode BOM. + * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF. + * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters + */ + return value.slice(1); + } + + /* + * In a Uint8Array, the BOM is represented by three bytes: 0xEF, 0xBB, and 0xBF, + * so we can just remove the first three bytes. + */ + return value.slice(3); +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * Represents a virtual file inside of ESLint. + * @implements {File} + */ +class VFile { + /** + * The file path including any processor-created virtual path. + * @type {string} + * @readonly + */ + path; + + /** + * The file path on disk. + * @type {string} + * @readonly + */ + physicalPath; + + /** + * The file contents. + * @type {string|Uint8Array} + * @readonly + */ + body; + + /** + * The raw body of the file, including a BOM if present. + * @type {string|Uint8Array} + * @readonly + */ + rawBody; + + /** + * Indicates whether the file has a byte order mark (BOM). + * @type {boolean} + * @readonly + */ + bom; + + /** + * Creates a new instance. + * @param {string} path The file path. + * @param {string|Uint8Array} body The file contents. + * @param {Object} [options] Additional options. + * @param {string} [options.physicalPath] The file path on disk. + */ + constructor(path, body, { physicalPath } = {}) { + this.path = path; + this.physicalPath = physicalPath ?? path; + this.bom = hasUnicodeBOM(body); + this.body = stripUnicodeBOM(body); + this.rawBody = body; + } +} + +module.exports = { VFile }; diff --git a/node_modules/eslint/lib/options.js b/node_modules/eslint/lib/options.js new file mode 100644 index 00000000..cdf1a581 --- /dev/null +++ b/node_modules/eslint/lib/options.js @@ -0,0 +1,522 @@ +/** + * @fileoverview Options configuration for optionator. + * @author George Zahariev + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const optionator = require("optionator"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * The options object parsed by Optionator. + * @typedef {Object} ParsedCLIOptions + * @property {boolean} cache Only check changed files + * @property {string} cacheFile Path to the cache file. Deprecated: use --cache-location + * @property {string} [cacheLocation] Path to the cache file or directory + * @property {"metadata" | "content"} cacheStrategy Strategy to use for detecting changed files in the cache + * @property {boolean} [color] Force enabling/disabling of color + * @property {string} [config] Use this configuration, overriding .eslintrc.* config options if present + * @property {boolean} debug Output debugging information + * @property {string[]} [env] Specify environments + * @property {boolean} envInfo Output execution environment information + * @property {boolean} errorOnUnmatchedPattern Prevent errors when pattern is unmatched + * @property {boolean} eslintrc Disable use of configuration from .eslintrc.* + * @property {string[]} [ext] Specify JavaScript file extensions + * @property {string[]} [flag] Feature flags + * @property {boolean} fix Automatically fix problems + * @property {boolean} fixDryRun Automatically fix problems without saving the changes to the file system + * @property {("directive" | "problem" | "suggestion" | "layout")[]} [fixType] Specify the types of fixes to apply (directive, problem, suggestion, layout) + * @property {string} format Use a specific output format + * @property {string[]} [global] Define global variables + * @property {boolean} [help] Show help + * @property {boolean} ignore Disable use of ignore files and patterns + * @property {string} [ignorePath] Specify path of ignore file + * @property {string[]} [ignorePattern] Patterns of files to ignore. In eslintrc mode, these are in addition to `.eslintignore` + * @property {boolean} init Run config initialization wizard + * @property {boolean} inlineConfig Prevent comments from changing config or rules + * @property {number} maxWarnings Number of warnings to trigger nonzero exit code + * @property {string} [outputFile] Specify file to write report to + * @property {string} [parser] Specify the parser to be used + * @property {Object} [parserOptions] Specify parser options + * @property {string[]} [plugin] Specify plugins + * @property {string} [printConfig] Print the configuration for the given file + * @property {boolean | undefined} reportUnusedDisableDirectives Adds reported errors for unused eslint-disable and eslint-enable directives + * @property {string | undefined} reportUnusedDisableDirectivesSeverity A severity string indicating if and how unused disable and enable directives should be tracked and reported. + * @property {string} [resolvePluginsRelativeTo] A folder where plugins should be resolved from, CWD by default + * @property {Object} [rule] Specify rules + * @property {string[]} [rulesdir] Load additional rules from this directory. Deprecated: Use rules from plugins + * @property {boolean} stdin Lint code provided on + * @property {string} [stdinFilename] Specify filename to process STDIN as + * @property {boolean} quiet Report errors only + * @property {boolean} [version] Output the version number + * @property {boolean} warnIgnored Show warnings when the file list includes ignored files + * @property {boolean} [passOnNoPatterns=false] When set to true, missing patterns cause + * the linting operation to short circuit and not report any failures. + * @property {string[]} _ Positional filenames or patterns + * @property {boolean} [stats] Report additional statistics + * @property {boolean} [suppressAll] Suppress all error violations + * @property {string[]} [suppressRule] Suppress specific rules + * @property {string} [suppressionsLocation] Path to the suppressions file or directory + * @property {boolean} [pruneSuppressions] Prune unused suppressions + * @property {boolean} [passOnUnprunedSuppressions] Ignore unused suppressions + */ + +//------------------------------------------------------------------------------ +// Initialization and Public Interface +//------------------------------------------------------------------------------ + +// exports "parse(args)", "generateHelp()", and "generateHelpForOption(optionName)" + +/** + * Creates the CLI options for ESLint. + * @param {boolean} usingFlatConfig Indicates if flat config is being used. + * @returns {Object} The optionator instance. + */ +module.exports = function (usingFlatConfig) { + let lookupFlag; + + if (usingFlatConfig) { + lookupFlag = { + option: "config-lookup", + type: "Boolean", + default: "true", + description: "Disable look up for eslint.config.js", + }; + } else { + lookupFlag = { + option: "eslintrc", + type: "Boolean", + default: "true", + description: "Disable use of configuration from .eslintrc.*", + }; + } + + let envFlag; + + if (!usingFlatConfig) { + envFlag = { + option: "env", + type: "[String]", + description: "Specify environments", + }; + } + + let inspectConfigFlag; + + if (usingFlatConfig) { + inspectConfigFlag = { + option: "inspect-config", + type: "Boolean", + description: + "Open the config inspector with the current configuration", + }; + } + + let extFlag; + + if (!usingFlatConfig) { + extFlag = { + option: "ext", + type: "[String]", + description: "Specify JavaScript file extensions", + }; + } else { + extFlag = { + option: "ext", + type: "[String]", + description: "Specify additional file extensions to lint", + }; + } + + let resolvePluginsFlag; + + if (!usingFlatConfig) { + resolvePluginsFlag = { + option: "resolve-plugins-relative-to", + type: "path::String", + description: + "A folder where plugins should be resolved from, CWD by default", + }; + } + + let rulesDirFlag; + + if (!usingFlatConfig) { + rulesDirFlag = { + option: "rulesdir", + type: "[path::String]", + description: + "Load additional rules from this directory. Deprecated: Use rules from plugins", + }; + } + + let ignorePathFlag; + + if (!usingFlatConfig) { + ignorePathFlag = { + option: "ignore-path", + type: "path::String", + description: "Specify path of ignore file", + }; + } + + let statsFlag; + + if (usingFlatConfig) { + statsFlag = { + option: "stats", + type: "Boolean", + default: "false", + description: "Add statistics to the lint report", + }; + } + + let warnIgnoredFlag; + + if (usingFlatConfig) { + warnIgnoredFlag = { + option: "warn-ignored", + type: "Boolean", + default: "true", + description: + "Suppress warnings when the file list includes ignored files", + }; + } + + let flagFlag; + + if (usingFlatConfig) { + flagFlag = { + option: "flag", + type: "[String]", + description: "Enable a feature flag", + }; + } + + let reportUnusedInlineConfigsFlag; + + if (usingFlatConfig) { + reportUnusedInlineConfigsFlag = { + option: "report-unused-inline-configs", + type: "String", + default: void 0, + description: + "Adds reported errors for unused eslint inline config comments", + enum: ["off", "warn", "error", "0", "1", "2"], + }; + } + + let mcpFlag; + + if (usingFlatConfig) { + mcpFlag = { + option: "mcp", + type: "Boolean", + description: "Start the ESLint MCP server", + }; + } + + return optionator({ + prepend: "eslint [options] file.js [file.js] [dir]", + defaults: { + concatRepeatedArrays: true, + mergeRepeatedObjects: true, + }, + options: [ + { + heading: "Basic configuration", + }, + lookupFlag, + { + option: "config", + alias: "c", + type: "path::String", + description: usingFlatConfig + ? "Use this configuration instead of eslint.config.js, eslint.config.mjs, or eslint.config.cjs" + : "Use this configuration, overriding .eslintrc.* config options if present", + }, + inspectConfigFlag, + envFlag, + extFlag, + { + option: "global", + type: "[String]", + description: "Define global variables", + }, + { + option: "parser", + type: "String", + description: "Specify the parser to be used", + }, + { + option: "parser-options", + type: "Object", + description: "Specify parser options", + }, + resolvePluginsFlag, + { + heading: "Specify Rules and Plugins", + }, + { + option: "plugin", + type: "[String]", + description: "Specify plugins", + }, + { + option: "rule", + type: "Object", + description: "Specify rules", + }, + rulesDirFlag, + { + heading: "Fix Problems", + }, + { + option: "fix", + type: "Boolean", + default: false, + description: "Automatically fix problems", + }, + { + option: "fix-dry-run", + type: "Boolean", + default: false, + description: + "Automatically fix problems without saving the changes to the file system", + }, + { + option: "fix-type", + type: "Array", + description: + "Specify the types of fixes to apply (directive, problem, suggestion, layout)", + }, + { + heading: "Ignore Files", + }, + ignorePathFlag, + { + option: "ignore", + type: "Boolean", + default: "true", + description: "Disable use of ignore files and patterns", + }, + { + option: "ignore-pattern", + type: "[String]", + description: `Patterns of files to ignore${usingFlatConfig ? "" : " (in addition to those in .eslintignore)"}`, + concatRepeatedArrays: [ + true, + { + oneValuePerFlag: true, + }, + ], + }, + { + heading: "Use stdin", + }, + { + option: "stdin", + type: "Boolean", + default: "false", + description: "Lint code provided on ", + }, + { + option: "stdin-filename", + type: "String", + description: "Specify filename to process STDIN as", + }, + { + heading: "Handle Warnings", + }, + { + option: "quiet", + type: "Boolean", + default: "false", + description: "Report errors only", + }, + { + option: "max-warnings", + type: "Int", + default: "-1", + description: "Number of warnings to trigger nonzero exit code", + }, + { + heading: "Output", + }, + { + option: "output-file", + alias: "o", + type: "path::String", + description: "Specify file to write report to", + }, + { + option: "format", + alias: "f", + type: "String", + default: "stylish", + description: "Use a specific output format", + }, + { + option: "color", + type: "Boolean", + alias: "no-color", + description: "Force enabling/disabling of color", + }, + { + heading: "Inline configuration comments", + }, + { + option: "inline-config", + type: "Boolean", + default: "true", + description: "Prevent comments from changing config or rules", + }, + { + option: "report-unused-disable-directives", + type: "Boolean", + default: void 0, + description: + "Adds reported errors for unused eslint-disable and eslint-enable directives", + }, + { + option: "report-unused-disable-directives-severity", + type: "String", + default: void 0, + description: + "Chooses severity level for reporting unused eslint-disable and eslint-enable directives", + enum: ["off", "warn", "error", "0", "1", "2"], + }, + reportUnusedInlineConfigsFlag, + { + heading: "Caching", + }, + { + option: "cache", + type: "Boolean", + default: "false", + description: "Only check changed files", + }, + { + option: "cache-file", + type: "path::String", + default: ".eslintcache", + description: + "Path to the cache file. Deprecated: use --cache-location", + }, + { + option: "cache-location", + type: "path::String", + description: "Path to the cache file or directory", + }, + { + option: "cache-strategy", + dependsOn: ["cache"], + type: "String", + default: "metadata", + enum: ["metadata", "content"], + description: + "Strategy to use for detecting changed files in the cache", + }, + { + heading: "Suppressing Violations", + }, + { + option: "suppress-all", + type: "Boolean", + default: "false", + description: "Suppress all violations", + }, + { + option: "suppress-rule", + type: "[String]", + description: "Suppress specific rules", + }, + { + option: "suppressions-location", + type: "path::String", + description: "Specify the location of the suppressions file", + }, + { + option: "prune-suppressions", + type: "Boolean", + default: "false", + description: "Prune unused suppressions", + }, + { + option: "pass-on-unpruned-suppressions", + type: "Boolean", + default: "false", + description: "Ignore unused suppressions", + }, + { + heading: "Miscellaneous", + }, + { + option: "init", + type: "Boolean", + default: "false", + description: "Run config initialization wizard", + }, + { + option: "env-info", + type: "Boolean", + default: "false", + description: "Output execution environment information", + }, + { + option: "error-on-unmatched-pattern", + type: "Boolean", + default: "true", + description: "Prevent errors when pattern is unmatched", + }, + { + option: "exit-on-fatal-error", + type: "Boolean", + default: "false", + description: "Exit with exit code 2 in case of fatal error", + }, + warnIgnoredFlag, + { + option: "pass-on-no-patterns", + type: "Boolean", + default: false, + description: + "Exit with exit code 0 in case no file patterns are passed", + }, + { + option: "debug", + type: "Boolean", + default: false, + description: "Output debugging information", + }, + { + option: "help", + alias: "h", + type: "Boolean", + description: "Show help", + }, + { + option: "version", + alias: "v", + type: "Boolean", + description: "Output the version number", + }, + { + option: "print-config", + type: "path::String", + description: "Print the configuration for the given file", + }, + statsFlag, + flagFlag, + mcpFlag, + ].filter(value => !!value), + }); +}; diff --git a/node_modules/eslint/lib/rule-tester/index.js b/node_modules/eslint/lib/rule-tester/index.js new file mode 100644 index 00000000..4fa651eb --- /dev/null +++ b/node_modules/eslint/lib/rule-tester/index.js @@ -0,0 +1,7 @@ +"use strict"; + +const RuleTester = require("./rule-tester"); + +module.exports = { + RuleTester, +}; diff --git a/node_modules/eslint/lib/rule-tester/rule-tester.js b/node_modules/eslint/lib/rule-tester/rule-tester.js new file mode 100644 index 00000000..382a3d19 --- /dev/null +++ b/node_modules/eslint/lib/rule-tester/rule-tester.js @@ -0,0 +1,1577 @@ +/** + * @fileoverview Mocha/Jest test wrapper + * @author Ilya Volodin + */ +"use strict"; + +/* globals describe, it -- Mocha globals */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("node:assert"), + util = require("node:util"), + path = require("node:path"), + equal = require("fast-deep-equal"), + Traverser = require("../shared/traverser"), + { Config } = require("../config/config"), + { Linter, SourceCodeFixer } = require("../linter"), + { interpolate, getPlaceholderMatcher } = require("../linter/interpolate"), + stringify = require("json-stable-stringify-without-jsonify"); + +const { FlatConfigArray } = require("../config/flat-config-array"); +const { + defaultConfig, + defaultRuleTesterConfig, +} = require("../config/default-config"); + +const ajv = require("../shared/ajv")({ strictDefaults: true }); + +const parserSymbol = Symbol.for("eslint.RuleTester.parser"); +const { ConfigArraySymbol } = require("@eslint/config-array"); +const { isSerializable } = require("../shared/serialization"); + +const jslang = require("../languages/js"); +const { SourceCode } = require("../languages/js/source-code"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @import { LanguageOptions, RuleDefinition } from "@eslint/core" */ + +/** @typedef {import("../types").Linter.Parser} Parser */ + +/** + * A test case that is expected to pass lint. + * @typedef {Object} ValidTestCase + * @property {string} [name] Name for the test case. + * @property {string} code Code for the test case. + * @property {any[]} [options] Options for the test case. + * @property {Function} [before] Function to execute before testing the case. + * @property {Function} [after] Function to execute after testing the case regardless of its result. + * @property {LanguageOptions} [languageOptions] The language options to use in the test case. + * @property {{ [name: string]: any }} [settings] Settings for the test case. + * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. + * @property {boolean} [only] Run only this test case or the subset of test cases with this property. + */ + +/** + * A test case that is expected to fail lint. + * @typedef {Object} InvalidTestCase + * @property {string} [name] Name for the test case. + * @property {string} code Code for the test case. + * @property {number | Array} errors Expected errors. + * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested. + * @property {any[]} [options] Options for the test case. + * @property {Function} [before] Function to execute before testing the case. + * @property {Function} [after] Function to execute after testing the case regardless of its result. + * @property {{ [name: string]: any }} [settings] Settings for the test case. + * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. + * @property {LanguageOptions} [languageOptions] The language options to use in the test case. + * @property {boolean} [only] Run only this test case or the subset of test cases with this property. + */ + +/** + * A description of a reported error used in a rule tester test. + * @typedef {Object} TestCaseError + * @property {string | RegExp} [message] Message. + * @property {string} [messageId] Message ID. + * @property {string} [type] The type of the reported AST node. + * @property {{ [name: string]: string }} [data] The data used to fill the message template. + * @property {number} [line] The 1-based line number of the reported start location. + * @property {number} [column] The 1-based column number of the reported start location. + * @property {number} [endLine] The 1-based line number of the reported end location. + * @property {number} [endColumn] The 1-based column number of the reported end location. + */ + +//------------------------------------------------------------------------------ +// Private Members +//------------------------------------------------------------------------------ + +/* + * testerDefaultConfig must not be modified as it allows to reset the tester to + * the initial default configuration + */ +const testerDefaultConfig = { rules: {} }; + +/* + * RuleTester uses this config as its default. This can be overwritten via + * setDefaultConfig(). + */ +let sharedDefaultConfig = { rules: {} }; + +/* + * List every parameters possible on a test case that are not related to eslint + * configuration + */ +const RuleTesterParameters = [ + "name", + "code", + "filename", + "options", + "before", + "after", + "errors", + "output", + "only", +]; + +/* + * All allowed property names in error objects. + */ +const errorObjectParameters = new Set([ + "message", + "messageId", + "data", + "type", + "line", + "column", + "endLine", + "endColumn", + "suggestions", +]); +const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`; + +/* + * All allowed property names in suggestion objects. + */ +const suggestionObjectParameters = new Set([ + "desc", + "messageId", + "data", + "output", +]); +const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`; + +/* + * Ignored test case properties when checking for test case duplicates. + */ +const duplicationIgnoredParameters = new Set(["name", "errors", "output"]); + +const forbiddenMethods = [ + "applyInlineConfig", + "applyLanguageOptions", + "finalize", +]; + +/** @type {Map} */ +const forbiddenMethodCalls = new Map( + forbiddenMethods.map(methodName => [methodName, new WeakSet()]), +); + +const hasOwnProperty = Function.call.bind(Object.hasOwnProperty); + +/** + * Clones a given value deeply. + * Note: This ignores `parent` property. + * @param {any} x A value to clone. + * @returns {any} A cloned value. + */ +function cloneDeeplyExcludesParent(x) { + if (typeof x === "object" && x !== null) { + if (Array.isArray(x)) { + return x.map(cloneDeeplyExcludesParent); + } + + const retv = {}; + + for (const key in x) { + if (key !== "parent" && hasOwnProperty(x, key)) { + retv[key] = cloneDeeplyExcludesParent(x[key]); + } + } + + return retv; + } + + return x; +} + +/** + * Freezes a given value deeply. + * @param {any} x A value to freeze. + * @param {Set} seenObjects Objects already seen during the traversal. + * @returns {void} + */ +function freezeDeeply(x, seenObjects = new Set()) { + if (typeof x === "object" && x !== null) { + if (seenObjects.has(x)) { + return; // skip to avoid infinite recursion + } + seenObjects.add(x); + + if (Array.isArray(x)) { + x.forEach(element => { + freezeDeeply(element, seenObjects); + }); + } else { + for (const key in x) { + if (key !== "parent" && hasOwnProperty(x, key)) { + freezeDeeply(x[key], seenObjects); + } + } + } + Object.freeze(x); + } +} + +/** + * Replace control characters by `\u00xx` form. + * @param {string} text The text to sanitize. + * @returns {string} The sanitized text. + */ +function sanitize(text) { + if (typeof text !== "string") { + return ""; + } + return text.replace( + /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls + c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`, + ); +} + +/** + * Define `start`/`end` properties as throwing error. + * @param {string} objName Object name used for error messages. + * @param {ASTNode} node The node to define. + * @returns {void} + */ +function defineStartEndAsError(objName, node) { + Object.defineProperties(node, { + start: { + get() { + throw new Error( + `Use ${objName}.range[0] instead of ${objName}.start`, + ); + }, + configurable: true, + enumerable: false, + }, + end: { + get() { + throw new Error( + `Use ${objName}.range[1] instead of ${objName}.end`, + ); + }, + configurable: true, + enumerable: false, + }, + }); +} + +/** + * Define `start`/`end` properties of all nodes of the given AST as throwing error. + * @param {ASTNode} ast The root node to errorize `start`/`end` properties. + * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast. + * @returns {void} + */ +function defineStartEndAsErrorInTree(ast, visitorKeys) { + Traverser.traverse(ast, { + visitorKeys, + enter: defineStartEndAsError.bind(null, "node"), + }); + ast.tokens.forEach(defineStartEndAsError.bind(null, "token")); + ast.comments.forEach(defineStartEndAsError.bind(null, "token")); +} + +/** + * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes. + * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties. + * @param {Parser} parser Parser object. + * @returns {Parser} Wrapped parser object. + */ +function wrapParser(parser) { + if (typeof parser.parseForESLint === "function") { + return { + [parserSymbol]: parser, + parseForESLint(...args) { + const ret = parser.parseForESLint(...args); + + defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys); + return ret; + }, + }; + } + + return { + [parserSymbol]: parser, + parse(...args) { + const ast = parser.parse(...args); + + defineStartEndAsErrorInTree(ast); + return ast; + }, + }; +} + +/** + * Function to replace forbidden `SourceCode` methods. Allows just one call per method. + * @param {string} methodName The name of the method to forbid. + * @param {Function} prototype The prototype with the original method to call. + * @returns {Function} The function that throws the error. + */ +function throwForbiddenMethodError(methodName, prototype) { + const original = prototype[methodName]; + + return function (...args) { + const called = forbiddenMethodCalls.get(methodName); + + /* eslint-disable no-invalid-this -- needed to operate as a method. */ + if (!called.has(this)) { + called.add(this); + + return original.apply(this, args); + } + /* eslint-enable no-invalid-this -- not needed past this point */ + + throw new Error( + `\`SourceCode#${methodName}()\` cannot be called inside a rule.`, + ); + }; +} + +/** + * Extracts names of {{ placeholders }} from the reported message. + * @param {string} message Reported message + * @returns {string[]} Array of placeholder names + */ +function getMessagePlaceholders(message) { + const matcher = getPlaceholderMatcher(); + + return Array.from(message.matchAll(matcher), ([, name]) => name.trim()); +} + +/** + * Returns the placeholders in the reported messages but + * only includes the placeholders available in the raw message and not in the provided data. + * @param {string} message The reported message + * @param {string} raw The raw message specified in the rule meta.messages + * @param {undefined|Record} data The passed + * @returns {string[]} Missing placeholder names + */ +function getUnsubstitutedMessagePlaceholders(message, raw, data = {}) { + const unsubstituted = getMessagePlaceholders(message); + + if (unsubstituted.length === 0) { + return []; + } + + // Remove false positives by only counting placeholders in the raw message, which were not provided in the data matcher or added with a data property + const known = getMessagePlaceholders(raw); + const provided = Object.keys(data); + + return unsubstituted.filter( + name => known.includes(name) && !provided.includes(name), + ); +} + +const metaSchemaDescription = ` +\t- If the rule has options, set \`meta.schema\` to an array or non-empty object to enable options validation. +\t- If the rule doesn't have options, omit \`meta.schema\` to enforce that no options can be passed to the rule. +\t- You can also set \`meta.schema\` to \`false\` to opt-out of options validation (not recommended). + +\thttps://eslint.org/docs/latest/extend/custom-rules#options-schemas +`; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +// default separators for testing +const DESCRIBE = Symbol("describe"); +const IT = Symbol("it"); +const IT_ONLY = Symbol("itOnly"); + +/** + * This is `it` default handler if `it` don't exist. + * @this {Mocha} + * @param {string} text The description of the test case. + * @param {Function} method The logic of the test case. + * @throws {Error} Any error upon execution of `method`. + * @returns {any} Returned value of `method`. + */ +function itDefaultHandler(text, method) { + try { + return method.call(this); + } catch (err) { + if (err instanceof assert.AssertionError) { + err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`; + } + throw err; + } +} + +/** + * This is `describe` default handler if `describe` don't exist. + * @this {Mocha} + * @param {string} text The description of the test case. + * @param {Function} method The logic of the test case. + * @returns {any} Returned value of `method`. + */ +function describeDefaultHandler(text, method) { + return method.call(this); +} + +/** + * Mocha test wrapper. + */ +class RuleTester { + /** + * Creates a new instance of RuleTester. + * @param {Object} [testerConfig] Optional, extra configuration for the tester + */ + constructor(testerConfig = {}) { + /** + * The configuration to use for this tester. Combination of the tester + * configuration and the default configuration. + * @type {Object} + */ + this.testerConfig = [ + sharedDefaultConfig, + testerConfig, + { rules: { "rule-tester/validate-ast": "error" } }, + ]; + + this.linter = new Linter({ configType: "flat" }); + } + + /** + * Set the configuration to use for all future tests + * @param {Object} config the configuration to use. + * @throws {TypeError} If non-object config. + * @returns {void} + */ + static setDefaultConfig(config) { + if (typeof config !== "object" || config === null) { + throw new TypeError( + "RuleTester.setDefaultConfig: config must be an object", + ); + } + sharedDefaultConfig = config; + + // Make sure the rules object exists since it is assumed to exist later + sharedDefaultConfig.rules = sharedDefaultConfig.rules || {}; + } + + /** + * Get the current configuration used for all tests + * @returns {Object} the current configuration + */ + static getDefaultConfig() { + return sharedDefaultConfig; + } + + /** + * Reset the configuration to the initial configuration of the tester removing + * any changes made until now. + * @returns {void} + */ + static resetDefaultConfig() { + sharedDefaultConfig = { + rules: { + ...testerDefaultConfig.rules, + }, + }; + } + + /* + * If people use `mocha test.js --watch` command, `describe` and `it` function + * instances are different for each execution. So `describe` and `it` should get fresh instance + * always. + */ + static get describe() { + return ( + this[DESCRIBE] || + (typeof describe === "function" ? describe : describeDefaultHandler) + ); + } + + static set describe(value) { + this[DESCRIBE] = value; + } + + static get it() { + return this[IT] || (typeof it === "function" ? it : itDefaultHandler); + } + + static set it(value) { + this[IT] = value; + } + + /** + * Adds the `only` property to a test to run it in isolation. + * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself. + * @returns {ValidTestCase | InvalidTestCase} The test with `only` set. + */ + static only(item) { + if (typeof item === "string") { + return { code: item, only: true }; + } + + return { ...item, only: true }; + } + + static get itOnly() { + if (typeof this[IT_ONLY] === "function") { + return this[IT_ONLY]; + } + if ( + typeof this[IT] === "function" && + typeof this[IT].only === "function" + ) { + return Function.bind.call(this[IT].only, this[IT]); + } + if (typeof it === "function" && typeof it.only === "function") { + return Function.bind.call(it.only, it); + } + + if ( + typeof this[DESCRIBE] === "function" || + typeof this[IT] === "function" + ) { + throw new Error( + "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" + + "See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more.", + ); + } + if (typeof it === "function") { + throw new Error( + "The current test framework does not support exclusive tests with `only`.", + ); + } + throw new Error( + "To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.", + ); + } + + static set itOnly(value) { + this[IT_ONLY] = value; + } + + /** + * Adds a new rule test to execute. + * @param {string} ruleName The name of the rule to run. + * @param {RuleDefinition} rule The rule to test. + * @param {{ + * valid: (ValidTestCase | string)[], + * invalid: InvalidTestCase[] + * }} test The collection of tests to run. + * @throws {TypeError|Error} If `rule` is not an object with a `create` method, + * or if non-object `test`, or if a required scenario of the given type is missing. + * @returns {void} + */ + run(ruleName, rule, test) { + const testerConfig = this.testerConfig, + requiredScenarios = ["valid", "invalid"], + scenarioErrors = [], + linter = this.linter, + ruleId = `rule-to-test/${ruleName}`; + + const seenValidTestCases = new Set(); + const seenInvalidTestCases = new Set(); + + if ( + !rule || + typeof rule !== "object" || + typeof rule.create !== "function" + ) { + throw new TypeError( + "Rule must be an object with a `create` method", + ); + } + + if (!test || typeof test !== "object") { + throw new TypeError( + `Test Scenarios for rule ${ruleName} : Could not find test scenario object`, + ); + } + + requiredScenarios.forEach(scenarioType => { + if (!test[scenarioType]) { + scenarioErrors.push( + `Could not find any ${scenarioType} test scenarios`, + ); + } + }); + + if (scenarioErrors.length > 0) { + throw new Error( + [`Test Scenarios for rule ${ruleName} is invalid:`] + .concat(scenarioErrors) + .join("\n"), + ); + } + + const baseConfig = [ + { + plugins: { + // copy root plugin over + "@": { + /* + * Parsers are wrapped to detect more errors, so this needs + * to be a new object for each call to run(), otherwise the + * parsers will be wrapped multiple times. + */ + parsers: { + ...defaultConfig[0].plugins["@"].parsers, + }, + + /* + * The rules key on the default plugin is a proxy to lazy-load + * just the rules that are needed. So, don't create a new object + * here, just use the default one to keep that performance + * enhancement. + */ + rules: defaultConfig[0].plugins["@"].rules, + languages: defaultConfig[0].plugins["@"].languages, + }, + "rule-to-test": { + rules: { + [ruleName]: Object.assign({}, rule, { + // Create a wrapper rule that freezes the `context` properties. + create(context) { + freezeDeeply(context.options); + freezeDeeply(context.settings); + freezeDeeply(context.parserOptions); + + // freezeDeeply(context.languageOptions); + + return rule.create(context); + }, + }), + }, + }, + }, + language: defaultConfig[0].language, + }, + ...defaultRuleTesterConfig, + ]; + + /** + * Runs a hook on the given item when it's assigned to the given property + * @param {string|Object} item Item to run the hook on + * @param {string} prop The property having the hook assigned to + * @throws {Error} If the property is not a function or that function throws an error + * @returns {void} + * @private + */ + function runHook(item, prop) { + if (typeof item === "object" && hasOwnProperty(item, prop)) { + assert.strictEqual( + typeof item[prop], + "function", + `Optional test case property '${prop}' must be a function`, + ); + item[prop](); + } + } + + /** + * Run the rule for the given item + * @param {string|Object} item Item to run the rule against + * @throws {Error} If an invalid schema. + * @returns {Object} Eslint run result + * @private + */ + function runRuleForItem(item) { + const flatConfigArrayOptions = { + baseConfig, + }; + + if (item.filename) { + flatConfigArrayOptions.basePath = + path.parse(item.filename).root || void 0; + } + + const configs = new FlatConfigArray( + testerConfig, + flatConfigArrayOptions, + ); + + /* + * Modify the returned config so that the parser is wrapped to catch + * access of the start/end properties. This method is called just + * once per code snippet being tested, so each test case gets a clean + * parser. + */ + configs[ConfigArraySymbol.finalizeConfig] = function (...args) { + // can't do super here :( + const proto = Object.getPrototypeOf(this); + const calculatedConfig = proto[ + ConfigArraySymbol.finalizeConfig + ].apply(this, args); + + // wrap the parser to catch start/end property access + if (calculatedConfig.language === jslang) { + calculatedConfig.languageOptions.parser = wrapParser( + calculatedConfig.languageOptions.parser, + ); + } + + return calculatedConfig; + }; + + let code, filename, output, beforeAST, afterAST; + + if (typeof item === "string") { + code = item; + } else { + code = item.code; + + /* + * Assumes everything on the item is a config except for the + * parameters used by this tester + */ + const itemConfig = { ...item }; + + for (const parameter of RuleTesterParameters) { + delete itemConfig[parameter]; + } + + /* + * Create the config object from the tester config and this item + * specific configurations. + */ + configs.push(itemConfig); + } + + if (hasOwnProperty(item, "only")) { + assert.ok( + typeof item.only === "boolean", + "Optional test case property 'only' must be a boolean", + ); + } + if (hasOwnProperty(item, "filename")) { + assert.ok( + typeof item.filename === "string", + "Optional test case property 'filename' must be a string", + ); + filename = item.filename; + } + + let ruleConfig = 1; + + if (hasOwnProperty(item, "options")) { + assert(Array.isArray(item.options), "options must be an array"); + ruleConfig = [1, ...item.options]; + } + + configs.push({ + rules: { + [ruleId]: ruleConfig, + }, + }); + + let schema; + + try { + schema = Config.getRuleOptionsSchema(rule); + } catch (err) { + err.message += metaSchemaDescription; + throw err; + } + + /* + * Check and throw an error if the schema is an empty object (`schema:{}`), because such schema + * doesn't validate or enforce anything and is therefore considered a possible error. If the intent + * was to skip options validation, `schema:false` should be set instead (explicit opt-out). + * + * For this purpose, a schema object is considered empty if it doesn't have any own enumerable string-keyed + * properties. While `ajv.compile()` does use enumerable properties from the prototype chain as well, + * it caches compiled schemas by serializing only own enumerable properties, so it's generally not a good idea + * to use inherited properties in schemas because schemas that differ only in inherited properties would end up + * having the same cache entry that would be correct for only one of them. + * + * At this point, `schema` can only be an object or `null`. + */ + if (schema && Object.keys(schema).length === 0) { + throw new Error( + `\`schema: {}\` is a no-op${metaSchemaDescription}`, + ); + } + + /* + * Setup AST getters. + * The goal is to check whether or not AST was modified when + * running the rule under test. + */ + configs.push({ + plugins: { + "rule-tester": { + rules: { + "validate-ast": { + create() { + return { + Program(node) { + beforeAST = + cloneDeeplyExcludesParent(node); + }, + "Program:exit"(node) { + afterAST = node; + }, + }; + }, + }, + }, + }, + }, + }); + + if (schema) { + ajv.validateSchema(schema); + + if (ajv.errors) { + const errors = ajv.errors + .map(error => { + const field = + error.dataPath[0] === "." + ? error.dataPath.slice(1) + : error.dataPath; + + return `\t${field}: ${error.message}`; + }) + .join("\n"); + + throw new Error([ + `Schema for rule ${ruleName} is invalid:`, + errors, + ]); + } + + /* + * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"), + * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling + * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result, + * the schema is compiled here separately from checking for `validateSchema` errors. + */ + try { + ajv.compile(schema); + } catch (err) { + throw new Error( + `Schema for rule ${ruleName} is invalid: ${err.message}`, + ); + } + } + + // check for validation errors + try { + configs.normalizeSync(); + configs.getConfig("test.js"); + } catch (error) { + error.message = `ESLint configuration in rule-tester is invalid: ${error.message}`; + throw error; + } + + // Verify the code. + const { applyLanguageOptions, applyInlineConfig, finalize } = + SourceCode.prototype; + let messages; + + try { + forbiddenMethods.forEach(methodName => { + SourceCode.prototype[methodName] = + throwForbiddenMethodError( + methodName, + SourceCode.prototype, + ); + }); + + messages = linter.verify(code, configs, filename); + } finally { + SourceCode.prototype.applyInlineConfig = applyInlineConfig; + SourceCode.prototype.applyLanguageOptions = + applyLanguageOptions; + SourceCode.prototype.finalize = finalize; + } + + const fatalErrorMessage = messages.find(m => m.fatal); + + assert( + !fatalErrorMessage, + `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`, + ); + + // Verify if autofix makes a syntax error or not. + if (messages.some(m => m.fix)) { + output = SourceCodeFixer.applyFixes(code, messages).output; + const errorMessageInFix = linter + .verify(output, configs, filename) + .find(m => m.fatal); + + assert( + !errorMessageInFix, + [ + "A fatal parsing error occurred in autofix.", + `Error: ${errorMessageInFix && errorMessageInFix.message}`, + "Autofix output:", + output, + ].join("\n"), + ); + } else { + output = code; + } + + return { + messages, + output, + beforeAST, + afterAST: cloneDeeplyExcludesParent(afterAST), + configs, + filename, + }; + } + + /** + * Check if the AST was changed + * @param {ASTNode} beforeAST AST node before running + * @param {ASTNode} afterAST AST node after running + * @returns {void} + * @private + */ + function assertASTDidntChange(beforeAST, afterAST) { + if (!equal(beforeAST, afterAST)) { + assert.fail("Rule should not modify AST."); + } + } + + /** + * Check if this test case is a duplicate of one we have seen before. + * @param {string|Object} item test case object + * @param {Set} seenTestCases set of serialized test cases we have seen so far (managed by this function) + * @returns {void} + * @private + */ + function checkDuplicateTestCase(item, seenTestCases) { + if (!isSerializable(item)) { + /* + * If we can't serialize a test case (because it contains a function, RegExp, etc), skip the check. + * This might happen with properties like: options, plugins, settings, languageOptions.parser, languageOptions.parserOptions. + */ + return; + } + + const normalizedItem = + typeof item === "string" ? { code: item } : item; + const serializedTestCase = stringify(normalizedItem, { + replacer(key, value) { + // "this" is the currently stringified object --> only ignore top-level properties + return normalizedItem !== this || + !duplicationIgnoredParameters.has(key) + ? value + : void 0; + }, + }); + + assert( + !seenTestCases.has(serializedTestCase), + "detected duplicate test case", + ); + seenTestCases.add(serializedTestCase); + } + + /** + * Check if the template is valid or not + * all valid cases go through this + * @param {string|Object} item Item to run the rule against + * @returns {void} + * @private + */ + function testValidTemplate(item) { + const code = typeof item === "object" ? item.code : item; + + assert.ok( + typeof code === "string", + "Test case must specify a string value for 'code'", + ); + if (item.name) { + assert.ok( + typeof item.name === "string", + "Optional test case property 'name' must be a string", + ); + } + + checkDuplicateTestCase(item, seenValidTestCases); + + const result = runRuleForItem(item); + const messages = result.messages; + + assert.strictEqual( + messages.length, + 0, + util.format( + "Should have no errors but had %d: %s", + messages.length, + util.inspect(messages), + ), + ); + + assertASTDidntChange(result.beforeAST, result.afterAST); + } + + /** + * Asserts that the message matches its expected value. If the expected + * value is a regular expression, it is checked against the actual + * value. + * @param {string} actual Actual value + * @param {string|RegExp} expected Expected value + * @returns {void} + * @private + */ + function assertMessageMatches(actual, expected) { + if (expected instanceof RegExp) { + // assert.js doesn't have a built-in RegExp match function + assert.ok( + expected.test(actual), + `Expected '${actual}' to match ${expected}`, + ); + } else { + assert.strictEqual(actual, expected); + } + } + + /** + * Check if the template is invalid or not + * all invalid cases go through this. + * @param {string|Object} item Item to run the rule against + * @returns {void} + * @private + */ + function testInvalidTemplate(item) { + assert.ok( + typeof item.code === "string", + "Test case must specify a string value for 'code'", + ); + if (item.name) { + assert.ok( + typeof item.name === "string", + "Optional test case property 'name' must be a string", + ); + } + assert.ok( + item.errors || item.errors === 0, + `Did not specify errors for an invalid test of ${ruleName}`, + ); + + if (Array.isArray(item.errors) && item.errors.length === 0) { + assert.fail("Invalid cases must have at least one error"); + } + + checkDuplicateTestCase(item, seenInvalidTestCases); + + const ruleHasMetaMessages = + hasOwnProperty(rule, "meta") && + hasOwnProperty(rule.meta, "messages"); + const friendlyIDList = ruleHasMetaMessages + ? `[${Object.keys(rule.meta.messages) + .map(key => `'${key}'`) + .join(", ")}]` + : null; + + const result = runRuleForItem(item); + const messages = result.messages; + + for (const message of messages) { + if (hasOwnProperty(message, "suggestions")) { + /** @type {Map} */ + const seenMessageIndices = new Map(); + + for (let i = 0; i < message.suggestions.length; i += 1) { + const suggestionMessage = message.suggestions[i].desc; + const previous = + seenMessageIndices.get(suggestionMessage); + + assert.ok( + !seenMessageIndices.has(suggestionMessage), + `Suggestion message '${suggestionMessage}' reported from suggestion ${i} was previously reported by suggestion ${previous}. Suggestion messages should be unique within an error.`, + ); + seenMessageIndices.set(suggestionMessage, i); + } + } + } + + if (typeof item.errors === "number") { + if (item.errors === 0) { + assert.fail( + "Invalid cases must have 'error' value greater than 0", + ); + } + + assert.strictEqual( + messages.length, + item.errors, + util.format( + "Should have %d error%s but had %d: %s", + item.errors, + item.errors === 1 ? "" : "s", + messages.length, + util.inspect(messages), + ), + ); + } else { + assert.strictEqual( + messages.length, + item.errors.length, + util.format( + "Should have %d error%s but had %d: %s", + item.errors.length, + item.errors.length === 1 ? "" : "s", + messages.length, + util.inspect(messages), + ), + ); + + const hasMessageOfThisRule = messages.some( + m => m.ruleId === ruleId, + ); + + for (let i = 0, l = item.errors.length; i < l; i++) { + const error = item.errors[i]; + const message = messages[i]; + + assert( + hasMessageOfThisRule, + "Error rule name should be the same as the name of the rule being tested", + ); + + if (typeof error === "string" || error instanceof RegExp) { + // Just an error message. + assertMessageMatches(message.message, error); + assert.ok( + message.suggestions === void 0, + `Error at index ${i} has suggestions. Please convert the test error into an object and specify 'suggestions' property on it to test suggestions.`, + ); + } else if (typeof error === "object" && error !== null) { + /* + * Error object. + * This may have a message, messageId, data, node type, line, and/or + * column. + */ + + Object.keys(error).forEach(propertyName => { + assert.ok( + errorObjectParameters.has(propertyName), + `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`, + ); + }); + + if (hasOwnProperty(error, "message")) { + assert.ok( + !hasOwnProperty(error, "messageId"), + "Error should not specify both 'message' and a 'messageId'.", + ); + assert.ok( + !hasOwnProperty(error, "data"), + "Error should not specify both 'data' and 'message'.", + ); + assertMessageMatches( + message.message, + error.message, + ); + } else if (hasOwnProperty(error, "messageId")) { + assert.ok( + ruleHasMetaMessages, + "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'.", + ); + if ( + !hasOwnProperty( + rule.meta.messages, + error.messageId, + ) + ) { + assert( + false, + `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`, + ); + } + assert.strictEqual( + message.messageId, + error.messageId, + `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`, + ); + + const unsubstitutedPlaceholders = + getUnsubstitutedMessagePlaceholders( + message.message, + rule.meta.messages[message.messageId], + error.data, + ); + + assert.ok( + unsubstitutedPlaceholders.length === 0, + `The reported message has ${unsubstitutedPlaceholders.length > 1 ? `unsubstituted placeholders: ${unsubstitutedPlaceholders.map(name => `'${name}'`).join(", ")}` : `an unsubstituted placeholder '${unsubstitutedPlaceholders[0]}'`}. Please provide the missing ${unsubstitutedPlaceholders.length > 1 ? "values" : "value"} via the 'data' property in the context.report() call.`, + ); + + if (hasOwnProperty(error, "data")) { + /* + * if data was provided, then directly compare the returned message to a synthetic + * interpolated message using the same message ID and data provided in the test. + * See https://github.com/eslint/eslint/issues/9890 for context. + */ + const unformattedOriginalMessage = + rule.meta.messages[error.messageId]; + const rehydratedMessage = interpolate( + unformattedOriginalMessage, + error.data, + ); + + assert.strictEqual( + message.message, + rehydratedMessage, + `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`, + ); + } + } else { + assert.fail( + "Test error must specify either a 'messageId' or 'message'.", + ); + } + + if (error.type) { + assert.strictEqual( + message.nodeType, + error.type, + `Error type should be ${error.type}, found ${message.nodeType}`, + ); + } + + if (hasOwnProperty(error, "line")) { + assert.strictEqual( + message.line, + error.line, + `Error line should be ${error.line}`, + ); + } + + if (hasOwnProperty(error, "column")) { + assert.strictEqual( + message.column, + error.column, + `Error column should be ${error.column}`, + ); + } + + if (hasOwnProperty(error, "endLine")) { + assert.strictEqual( + message.endLine, + error.endLine, + `Error endLine should be ${error.endLine}`, + ); + } + + if (hasOwnProperty(error, "endColumn")) { + assert.strictEqual( + message.endColumn, + error.endColumn, + `Error endColumn should be ${error.endColumn}`, + ); + } + + assert.ok( + !message.suggestions || + hasOwnProperty(error, "suggestions"), + `Error at index ${i} has suggestions. Please specify 'suggestions' property on the test error object.`, + ); + if (hasOwnProperty(error, "suggestions")) { + // Support asserting there are no suggestions + const expectsSuggestions = Array.isArray( + error.suggestions, + ) + ? error.suggestions.length > 0 + : Boolean(error.suggestions); + const hasSuggestions = + message.suggestions !== void 0; + + if (!hasSuggestions && expectsSuggestions) { + assert.ok( + !error.suggestions, + `Error should have suggestions on error with message: "${message.message}"`, + ); + } else if (hasSuggestions) { + assert.ok( + expectsSuggestions, + `Error should have no suggestions on error with message: "${message.message}"`, + ); + if (typeof error.suggestions === "number") { + assert.strictEqual( + message.suggestions.length, + error.suggestions, + `Error should have ${error.suggestions} suggestions. Instead found ${message.suggestions.length} suggestions`, + ); + } else if (Array.isArray(error.suggestions)) { + assert.strictEqual( + message.suggestions.length, + error.suggestions.length, + `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`, + ); + + error.suggestions.forEach( + (expectedSuggestion, index) => { + assert.ok( + typeof expectedSuggestion === + "object" && + expectedSuggestion !== null, + "Test suggestion in 'suggestions' array must be an object.", + ); + Object.keys( + expectedSuggestion, + ).forEach(propertyName => { + assert.ok( + suggestionObjectParameters.has( + propertyName, + ), + `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`, + ); + }); + + const actualSuggestion = + message.suggestions[index]; + const suggestionPrefix = `Error Suggestion at index ${index}:`; + + if ( + hasOwnProperty( + expectedSuggestion, + "desc", + ) + ) { + assert.ok( + !hasOwnProperty( + expectedSuggestion, + "data", + ), + `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`, + ); + assert.ok( + !hasOwnProperty( + expectedSuggestion, + "messageId", + ), + `${suggestionPrefix} Test should not specify both 'desc' and 'messageId'.`, + ); + assert.strictEqual( + actualSuggestion.desc, + expectedSuggestion.desc, + `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`, + ); + } else if ( + hasOwnProperty( + expectedSuggestion, + "messageId", + ) + ) { + assert.ok( + ruleHasMetaMessages, + `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`, + ); + assert.ok( + hasOwnProperty( + rule.meta.messages, + expectedSuggestion.messageId, + ), + `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`, + ); + assert.strictEqual( + actualSuggestion.messageId, + expectedSuggestion.messageId, + `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`, + ); + + const unsubstitutedPlaceholders = + getUnsubstitutedMessagePlaceholders( + actualSuggestion.desc, + rule.meta.messages[ + expectedSuggestion + .messageId + ], + expectedSuggestion.data, + ); + + assert.ok( + unsubstitutedPlaceholders.length === + 0, + `The message of the suggestion has ${unsubstitutedPlaceholders.length > 1 ? `unsubstituted placeholders: ${unsubstitutedPlaceholders.map(name => `'${name}'`).join(", ")}` : `an unsubstituted placeholder '${unsubstitutedPlaceholders[0]}'`}. Please provide the missing ${unsubstitutedPlaceholders.length > 1 ? "values" : "value"} via the 'data' property for the suggestion in the context.report() call.`, + ); + + if ( + hasOwnProperty( + expectedSuggestion, + "data", + ) + ) { + const unformattedMetaMessage = + rule.meta.messages[ + expectedSuggestion + .messageId + ]; + const rehydratedDesc = + interpolate( + unformattedMetaMessage, + expectedSuggestion.data, + ); + + assert.strictEqual( + actualSuggestion.desc, + rehydratedDesc, + `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`, + ); + } + } else if ( + hasOwnProperty( + expectedSuggestion, + "data", + ) + ) { + assert.fail( + `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`, + ); + } else { + assert.fail( + `${suggestionPrefix} Test must specify either 'messageId' or 'desc'.`, + ); + } + + assert.ok( + hasOwnProperty( + expectedSuggestion, + "output", + ), + `${suggestionPrefix} The "output" property is required.`, + ); + const codeWithAppliedSuggestion = + SourceCodeFixer.applyFixes( + item.code, + [actualSuggestion], + ).output; + + // Verify if suggestion fix makes a syntax error or not. + const errorMessageInSuggestion = + linter + .verify( + codeWithAppliedSuggestion, + result.configs, + result.filename, + ) + .find(m => m.fatal); + + assert( + !errorMessageInSuggestion, + [ + "A fatal parsing error occurred in suggestion fix.", + `Error: ${errorMessageInSuggestion && errorMessageInSuggestion.message}`, + "Suggestion output:", + codeWithAppliedSuggestion, + ].join("\n"), + ); + + assert.strictEqual( + codeWithAppliedSuggestion, + expectedSuggestion.output, + `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`, + ); + assert.notStrictEqual( + expectedSuggestion.output, + item.code, + `The output of a suggestion should differ from the original source code for suggestion at index: ${index} on error with message: "${message.message}"`, + ); + }, + ); + } else { + assert.fail( + "Test error object property 'suggestions' should be an array or a number", + ); + } + } + } + } else { + // Message was an unexpected type + assert.fail( + `Error should be a string, object, or RegExp, but found (${util.inspect(message)})`, + ); + } + } + } + + if (hasOwnProperty(item, "output")) { + if (item.output === null) { + assert.strictEqual( + result.output, + item.code, + "Expected no autofixes to be suggested", + ); + } else { + assert.strictEqual( + result.output, + item.output, + "Output is incorrect.", + ); + assert.notStrictEqual( + item.code, + item.output, + "Test property 'output' matches 'code'. If no autofix is expected, then omit the 'output' property or set it to null.", + ); + } + } else { + assert.strictEqual( + result.output, + item.code, + "The rule fixed the code. Please add 'output' property.", + ); + } + + assertASTDidntChange(result.beforeAST, result.afterAST); + } + + /* + * This creates a mocha test suite and pipes all supplied info through + * one of the templates above. + * The test suites for valid/invalid are created conditionally as + * test runners (eg. vitest) fail for empty test suites. + */ + this.constructor.describe(ruleName, () => { + if (test.valid.length > 0) { + this.constructor.describe("valid", () => { + test.valid.forEach(valid => { + this.constructor[valid.only ? "itOnly" : "it"]( + sanitize( + typeof valid === "object" + ? valid.name || valid.code + : valid, + ), + () => { + try { + runHook(valid, "before"); + testValidTemplate(valid); + } finally { + runHook(valid, "after"); + } + }, + ); + }); + }); + } + + if (test.invalid.length > 0) { + this.constructor.describe("invalid", () => { + test.invalid.forEach(invalid => { + this.constructor[invalid.only ? "itOnly" : "it"]( + sanitize(invalid.name || invalid.code), + () => { + try { + runHook(invalid, "before"); + testInvalidTemplate(invalid); + } finally { + runHook(invalid, "after"); + } + }, + ); + }); + }); + } + }); + } +} + +RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null; + +module.exports = RuleTester; diff --git a/node_modules/eslint/lib/rules/accessor-pairs.js b/node_modules/eslint/lib/rules/accessor-pairs.js new file mode 100644 index 00000000..c7e2e261 --- /dev/null +++ b/node_modules/eslint/lib/rules/accessor-pairs.js @@ -0,0 +1,385 @@ +/** + * @fileoverview Rule to enforce getter and setter pairs in objects and classes. + * @author Gyandeep Singh + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * Property name if it can be computed statically, otherwise the list of the tokens of the key node. + * @typedef {string|Token[]} Key + */ + +/** + * Accessor nodes with the same key. + * @typedef {Object} AccessorData + * @property {Key} key Accessor's key + * @property {ASTNode[]} getters List of getter nodes. + * @property {ASTNode[]} setters List of setter nodes. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not the given lists represent the equal tokens in the same order. + * Tokens are compared by their properties, not by instance. + * @param {Token[]} left First list of tokens. + * @param {Token[]} right Second list of tokens. + * @returns {boolean} `true` if the lists have same tokens. + */ +function areEqualTokenLists(left, right) { + if (left.length !== right.length) { + return false; + } + + for (let i = 0; i < left.length; i++) { + const leftToken = left[i], + rightToken = right[i]; + + if ( + leftToken.type !== rightToken.type || + leftToken.value !== rightToken.value + ) { + return false; + } + } + + return true; +} + +/** + * Checks whether or not the given keys are equal. + * @param {Key} left First key. + * @param {Key} right Second key. + * @returns {boolean} `true` if the keys are equal. + */ +function areEqualKeys(left, right) { + if (typeof left === "string" && typeof right === "string") { + // Statically computed names. + return left === right; + } + if (Array.isArray(left) && Array.isArray(right)) { + // Token lists. + return areEqualTokenLists(left, right); + } + + return false; +} + +/** + * Checks whether or not a given node is of an accessor kind ('get' or 'set'). + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is of an accessor kind. + */ +function isAccessorKind(node) { + return node.kind === "get" || node.kind === "set"; +} + +/** + * Checks whether or not a given node is an argument of a specified method call. + * @param {ASTNode} node A node to check. + * @param {number} index An expected index of the node in arguments. + * @param {string} object An expected name of the object of the method. + * @param {string} property An expected name of the method. + * @returns {boolean} `true` if the node is an argument of the specified method call. + */ +function isArgumentOfMethodCall(node, index, object, property) { + const parent = node.parent; + + return ( + parent.type === "CallExpression" && + astUtils.isSpecificMemberAccess(parent.callee, object, property) && + parent.arguments[index] === node + ); +} + +/** + * Checks whether or not a given node is a property descriptor. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a property descriptor. + */ +function isPropertyDescriptor(node) { + // Object.defineProperty(obj, "foo", {set: ...}) + if ( + isArgumentOfMethodCall(node, 2, "Object", "defineProperty") || + isArgumentOfMethodCall(node, 2, "Reflect", "defineProperty") + ) { + return true; + } + + /* + * Object.defineProperties(obj, {foo: {set: ...}}) + * Object.create(proto, {foo: {set: ...}}) + */ + const grandparent = node.parent.parent; + + return ( + grandparent.type === "ObjectExpression" && + (isArgumentOfMethodCall(grandparent, 1, "Object", "create") || + isArgumentOfMethodCall( + grandparent, + 1, + "Object", + "defineProperties", + )) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + enforceForClassMembers: true, + getWithoutSet: false, + setWithoutGet: true, + }, + ], + + docs: { + description: + "Enforce getter and setter pairs in objects and classes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/accessor-pairs", + }, + + schema: [ + { + type: "object", + properties: { + getWithoutSet: { + type: "boolean", + }, + setWithoutGet: { + type: "boolean", + }, + enforceForClassMembers: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingGetterInPropertyDescriptor: + "Getter is not present in property descriptor.", + missingSetterInPropertyDescriptor: + "Setter is not present in property descriptor.", + missingGetterInObjectLiteral: + "Getter is not present for {{ name }}.", + missingSetterInObjectLiteral: + "Setter is not present for {{ name }}.", + missingGetterInClass: "Getter is not present for class {{ name }}.", + missingSetterInClass: "Setter is not present for class {{ name }}.", + }, + }, + create(context) { + const [ + { + getWithoutSet: checkGetWithoutSet, + setWithoutGet: checkSetWithoutGet, + enforceForClassMembers, + }, + ] = context.options; + const sourceCode = context.sourceCode; + + /** + * Reports the given node. + * @param {ASTNode} node The node to report. + * @param {string} messageKind "missingGetter" or "missingSetter". + * @returns {void} + * @private + */ + function report(node, messageKind) { + if (node.type === "Property") { + context.report({ + node, + messageId: `${messageKind}InObjectLiteral`, + loc: astUtils.getFunctionHeadLoc(node.value, sourceCode), + data: { + name: astUtils.getFunctionNameWithKind(node.value), + }, + }); + } else if (node.type === "MethodDefinition") { + context.report({ + node, + messageId: `${messageKind}InClass`, + loc: astUtils.getFunctionHeadLoc(node.value, sourceCode), + data: { + name: astUtils.getFunctionNameWithKind(node.value), + }, + }); + } else { + context.report({ + node, + messageId: `${messageKind}InPropertyDescriptor`, + }); + } + } + + /** + * Reports each of the nodes in the given list using the same messageId. + * @param {ASTNode[]} nodes Nodes to report. + * @param {string} messageKind "missingGetter" or "missingSetter". + * @returns {void} + * @private + */ + function reportList(nodes, messageKind) { + for (const node of nodes) { + report(node, messageKind); + } + } + + /** + * Checks accessor pairs in the given list of nodes. + * @param {ASTNode[]} nodes The list to check. + * @returns {void} + * @private + */ + function checkList(nodes) { + const accessors = []; + let found = false; + + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + + if (isAccessorKind(node)) { + // Creates a new `AccessorData` object for the given getter or setter node. + const name = astUtils.getStaticPropertyName(node); + const key = + name !== null ? name : sourceCode.getTokens(node.key); + + // Merges the given `AccessorData` object into the given accessors list. + for (let j = 0; j < accessors.length; j++) { + const accessor = accessors[j]; + + if (areEqualKeys(accessor.key, key)) { + accessor.getters.push( + ...(node.kind === "get" ? [node] : []), + ); + accessor.setters.push( + ...(node.kind === "set" ? [node] : []), + ); + found = true; + break; + } + } + if (!found) { + accessors.push({ + key, + getters: node.kind === "get" ? [node] : [], + setters: node.kind === "set" ? [node] : [], + }); + } + found = false; + } + } + + for (const { getters, setters } of accessors) { + if (checkSetWithoutGet && setters.length && !getters.length) { + reportList(setters, "missingGetter"); + } + if (checkGetWithoutSet && getters.length && !setters.length) { + reportList(getters, "missingSetter"); + } + } + } + + /** + * Checks accessor pairs in an object literal. + * @param {ASTNode} node `ObjectExpression` node to check. + * @returns {void} + * @private + */ + function checkObjectLiteral(node) { + checkList(node.properties.filter(p => p.type === "Property")); + } + + /** + * Checks accessor pairs in a property descriptor. + * @param {ASTNode} node Property descriptor `ObjectExpression` node to check. + * @returns {void} + * @private + */ + function checkPropertyDescriptor(node) { + const namesToCheck = new Set( + node.properties + .filter( + p => + p.type === "Property" && + p.kind === "init" && + !p.computed, + ) + .map(({ key }) => key.name), + ); + + const hasGetter = namesToCheck.has("get"); + const hasSetter = namesToCheck.has("set"); + + if (checkSetWithoutGet && hasSetter && !hasGetter) { + report(node, "missingGetter"); + } + if (checkGetWithoutSet && hasGetter && !hasSetter) { + report(node, "missingSetter"); + } + } + + /** + * Checks the given object expression as an object literal and as a possible property descriptor. + * @param {ASTNode} node `ObjectExpression` node to check. + * @returns {void} + * @private + */ + function checkObjectExpression(node) { + checkObjectLiteral(node); + if (isPropertyDescriptor(node)) { + checkPropertyDescriptor(node); + } + } + + /** + * Checks the given class body. + * @param {ASTNode} node `ClassBody` node to check. + * @returns {void} + * @private + */ + function checkClassBody(node) { + const methodDefinitions = node.body.filter( + m => m.type === "MethodDefinition", + ); + + checkList(methodDefinitions.filter(m => m.static)); + checkList(methodDefinitions.filter(m => !m.static)); + } + + const listeners = {}; + + if (checkSetWithoutGet || checkGetWithoutSet) { + listeners.ObjectExpression = checkObjectExpression; + if (enforceForClassMembers) { + listeners.ClassBody = checkClassBody; + } + } + + return listeners; + }, +}; diff --git a/node_modules/eslint/lib/rules/array-bracket-newline.js b/node_modules/eslint/lib/rules/array-bracket-newline.js new file mode 100644 index 00000000..bf33d669 --- /dev/null +++ b/node_modules/eslint/lib/rules/array-bracket-newline.js @@ -0,0 +1,291 @@ +/** + * @fileoverview Rule to enforce linebreaks after open and before close array brackets + * @author Jan Peer Stöcklmair + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "array-bracket-newline", + url: "https://eslint.style/rules/js/array-bracket-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce linebreaks after opening and before closing array brackets", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-bracket-newline", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never", "consistent"], + }, + { + type: "object", + properties: { + multiline: { + type: "boolean", + }, + minItems: { + type: ["integer", "null"], + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + unexpectedOpeningLinebreak: + "There should be no linebreak after '['.", + unexpectedClosingLinebreak: + "There should be no linebreak before ']'.", + missingOpeningLinebreak: "A linebreak is required after '['.", + missingClosingLinebreak: "A linebreak is required before ']'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} option An option value to parse. + * @returns {{multiline: boolean, minItems: number}} Normalized option object. + */ + function normalizeOptionValue(option) { + let consistent = false; + let multiline = false; + let minItems; + + if (option) { + if (option === "consistent") { + consistent = true; + minItems = Number.POSITIVE_INFINITY; + } else if (option === "always" || option.minItems === 0) { + minItems = 0; + } else if (option === "never") { + minItems = Number.POSITIVE_INFINITY; + } else { + multiline = Boolean(option.multiline); + minItems = option.minItems || Number.POSITIVE_INFINITY; + } + } else { + consistent = false; + multiline = true; + minItems = Number.POSITIVE_INFINITY; + } + + return { consistent, multiline, minItems }; + } + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} options An option value to parse. + * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. + */ + function normalizeOptions(options) { + const value = normalizeOptionValue(options); + + return { ArrayExpression: value, ArrayPattern: value }; + } + + /** + * Reports that there shouldn't be a linebreak after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoBeginningLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "unexpectedOpeningLinebreak", + fix(fixer) { + const nextToken = sourceCode.getTokenAfter(token, { + includeComments: true, + }); + + if (astUtils.isCommentToken(nextToken)) { + return null; + } + + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + + /** + * Reports that there shouldn't be a linebreak before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoEndingLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "unexpectedClosingLinebreak", + fix(fixer) { + const previousToken = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + if (astUtils.isCommentToken(previousToken)) { + return null; + } + + return fixer.removeRange([ + previousToken.range[1], + token.range[0], + ]); + }, + }); + } + + /** + * Reports that there should be a linebreak after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingOpeningLinebreak", + fix(fixer) { + return fixer.insertTextAfter(token, "\n"); + }, + }); + } + + /** + * Reports that there should be a linebreak before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingClosingLinebreak", + fix(fixer) { + return fixer.insertTextBefore(token, "\n"); + }, + }); + } + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node A node to check. This is an ArrayExpression node or an ArrayPattern node. + * @returns {void} + */ + function check(node) { + const elements = node.elements; + const normalizedOptions = normalizeOptions(context.options[0]); + const options = normalizedOptions[node.type]; + const openBracket = sourceCode.getFirstToken(node); + const closeBracket = sourceCode.getLastToken(node); + const firstIncComment = sourceCode.getTokenAfter(openBracket, { + includeComments: true, + }); + const lastIncComment = sourceCode.getTokenBefore(closeBracket, { + includeComments: true, + }); + const first = sourceCode.getTokenAfter(openBracket); + const last = sourceCode.getTokenBefore(closeBracket); + + const needsLinebreaks = + elements.length >= options.minItems || + (options.multiline && + elements.length > 0 && + firstIncComment.loc.start.line !== + lastIncComment.loc.end.line) || + (elements.length === 0 && + firstIncComment.type === "Block" && + firstIncComment.loc.start.line !== + lastIncComment.loc.end.line && + firstIncComment === lastIncComment) || + (options.consistent && + openBracket.loc.end.line !== first.loc.start.line); + + /* + * Use tokens or comments to check multiline or not. + * But use only tokens to check whether linebreaks are needed. + * This allows: + * var arr = [ // eslint-disable-line foo + * 'a' + * ] + */ + + if (needsLinebreaks) { + if (astUtils.isTokenOnSameLine(openBracket, first)) { + reportRequiredBeginningLinebreak(node, openBracket); + } + if (astUtils.isTokenOnSameLine(last, closeBracket)) { + reportRequiredEndingLinebreak(node, closeBracket); + } + } else { + if (!astUtils.isTokenOnSameLine(openBracket, first)) { + reportNoBeginningLinebreak(node, openBracket); + } + if (!astUtils.isTokenOnSameLine(last, closeBracket)) { + reportNoEndingLinebreak(node, closeBracket); + } + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + ArrayPattern: check, + ArrayExpression: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/array-bracket-spacing.js b/node_modules/eslint/lib/rules/array-bracket-spacing.js new file mode 100644 index 00000000..749d93a9 --- /dev/null +++ b/node_modules/eslint/lib/rules/array-bracket-spacing.js @@ -0,0 +1,301 @@ +/** + * @fileoverview Disallows or enforces spaces inside of array brackets. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "array-bracket-spacing", + url: "https://eslint.style/rules/js/array-bracket-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing inside array brackets", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-bracket-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + singleValue: { + type: "boolean", + }, + objectsInArrays: { + type: "boolean", + }, + arraysInArrays: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedSpaceAfter: + "There should be no space after '{{tokenValue}}'.", + unexpectedSpaceBefore: + "There should be no space before '{{tokenValue}}'.", + missingSpaceAfter: "A space is required after '{{tokenValue}}'.", + missingSpaceBefore: "A space is required before '{{tokenValue}}'.", + }, + }, + create(context) { + const spaced = context.options[0] === "always", + sourceCode = context.sourceCode; + + /** + * Determines whether an option is set, relative to the spacing option. + * If spaced is "always", then check whether option is set to false. + * If spaced is "never", then check whether option is set to true. + * @param {Object} option The option to exclude. + * @returns {boolean} Whether or not the property is excluded. + */ + function isOptionSet(option) { + return context.options[1] + ? context.options[1][option] === !spaced + : false; + } + + const options = { + spaced, + singleElementException: isOptionSet("singleValue"), + objectsInArraysException: isOptionSet("objectsInArrays"), + arraysInArraysException: isOptionSet("arraysInArrays"), + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoBeginningSpace(node, token) { + const nextToken = sourceCode.getTokenAfter(token); + + context.report({ + node, + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "unexpectedSpaceAfter", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoEndingSpace(node, token) { + const previousToken = sourceCode.getTokenBefore(token); + + context.report({ + node, + loc: { start: previousToken.loc.end, end: token.loc.start }, + messageId: "unexpectedSpaceBefore", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + previousToken.range[1], + token.range[0], + ]); + }, + }); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceAfter", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceBefore", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + + /** + * Determines if a node is an object type + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node is an object type. + */ + function isObjectType(node) { + return ( + node && + (node.type === "ObjectExpression" || + node.type === "ObjectPattern") + ); + } + + /** + * Determines if a node is an array type + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node is an array type. + */ + function isArrayType(node) { + return ( + node && + (node.type === "ArrayExpression" || + node.type === "ArrayPattern") + ); + } + + /** + * Validates the spacing around array brackets + * @param {ASTNode} node The node we're checking for spacing + * @returns {void} + */ + function validateArraySpacing(node) { + if (options.spaced && node.elements.length === 0) { + return; + } + + const first = sourceCode.getFirstToken(node), + second = sourceCode.getFirstToken(node, 1), + last = node.typeAnnotation + ? sourceCode.getTokenBefore(node.typeAnnotation) + : sourceCode.getLastToken(node), + penultimate = sourceCode.getTokenBefore(last), + firstElement = node.elements[0], + lastElement = node.elements.at(-1); + + const openingBracketMustBeSpaced = + (options.objectsInArraysException && + isObjectType(firstElement)) || + (options.arraysInArraysException && + isArrayType(firstElement)) || + (options.singleElementException && node.elements.length === 1) + ? !options.spaced + : options.spaced; + + const closingBracketMustBeSpaced = + (options.objectsInArraysException && + isObjectType(lastElement)) || + (options.arraysInArraysException && isArrayType(lastElement)) || + (options.singleElementException && node.elements.length === 1) + ? !options.spaced + : options.spaced; + + if (astUtils.isTokenOnSameLine(first, second)) { + if ( + openingBracketMustBeSpaced && + !sourceCode.isSpaceBetweenTokens(first, second) + ) { + reportRequiredBeginningSpace(node, first); + } + if ( + !openingBracketMustBeSpaced && + sourceCode.isSpaceBetweenTokens(first, second) + ) { + reportNoBeginningSpace(node, first); + } + } + + if ( + first !== penultimate && + astUtils.isTokenOnSameLine(penultimate, last) + ) { + if ( + closingBracketMustBeSpaced && + !sourceCode.isSpaceBetweenTokens(penultimate, last) + ) { + reportRequiredEndingSpace(node, last); + } + if ( + !closingBracketMustBeSpaced && + sourceCode.isSpaceBetweenTokens(penultimate, last) + ) { + reportNoEndingSpace(node, last); + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ArrayPattern: validateArraySpacing, + ArrayExpression: validateArraySpacing, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/array-callback-return.js b/node_modules/eslint/lib/rules/array-callback-return.js new file mode 100644 index 00000000..7a2e4b64 --- /dev/null +++ b/node_modules/eslint/lib/rules/array-callback-return.js @@ -0,0 +1,494 @@ +/** + * @fileoverview Rule to enforce return statements in callbacks of array's methods + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u; +const TARGET_METHODS = + /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|reduce(?:Right)?|some|sort|toSorted)$/u; + +/** + * Checks a given node is a member access which has the specified name's + * property. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a member access which has + * the specified name's property. The node may be a `(Chain|Member)Expression` node. + */ +function isTargetMethod(node) { + return astUtils.isSpecificMemberAccess(node, null, TARGET_METHODS); +} + +/** + * Checks all segments in a set and returns true if any are reachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if any segment is reachable; false otherwise. + */ +function isAnySegmentReachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return true; + } + } + + return false; +} + +/** + * Returns a human-legible description of an array method + * @param {string} arrayMethodName A method name to fully qualify + * @returns {string} the method name prefixed with `Array.` if it is a class method, + * or else `Array.prototype.` if it is an instance method. + */ +function fullMethodName(arrayMethodName) { + if (["from", "of", "isArray"].includes(arrayMethodName)) { + return "Array.".concat(arrayMethodName); + } + return "Array.prototype.".concat(arrayMethodName); +} + +/** + * Checks whether or not a given node is a function expression which is the + * callback of an array method, returning the method name. + * @param {ASTNode} node A node to check. This is one of + * FunctionExpression or ArrowFunctionExpression. + * @returns {string} The method name if the node is a callback method, + * null otherwise. + */ +function getArrayMethodName(node) { + let currentNode = node; + + while (currentNode) { + const parent = currentNode.parent; + + switch (parent.type) { + /* + * Looks up the destination. e.g., + * foo.every(nativeFoo || function foo() { ... }); + */ + case "LogicalExpression": + case "ConditionalExpression": + case "ChainExpression": + currentNode = parent; + break; + + /* + * If the upper function is IIFE, checks the destination of the return value. + * e.g. + * foo.every((function() { + * // setup... + * return function callback() { ... }; + * })()); + */ + case "ReturnStatement": { + const func = astUtils.getUpperFunction(parent); + + if (func === null || !astUtils.isCallee(func)) { + return null; + } + currentNode = func.parent; + break; + } + + /* + * e.g. + * Array.from([], function() {}); + * list.every(function() {}); + */ + case "CallExpression": + if (astUtils.isArrayFromMethod(parent.callee)) { + if ( + parent.arguments.length >= 2 && + parent.arguments[1] === currentNode + ) { + return "from"; + } + } + if (isTargetMethod(parent.callee)) { + if ( + parent.arguments.length >= 1 && + parent.arguments[0] === currentNode + ) { + return astUtils.getStaticPropertyName(parent.callee); + } + } + return null; + + // Otherwise this node is not target. + default: + return null; + } + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks if the given node is a void expression. + * @param {ASTNode} node The node to check. + * @returns {boolean} - `true` if the node is a void expression + */ +function isExpressionVoid(node) { + return node.type === "UnaryExpression" && node.operator === "void"; +} + +/** + * Fixes the linting error by prepending "void " to the given node + * @param {Object} sourceCode context given by context.sourceCode + * @param {ASTNode} node The node to fix. + * @param {Object} fixer The fixer object provided by ESLint. + * @returns {Array} - An array of fix objects to apply to the node. + */ +function voidPrependFixer(sourceCode, node, fixer) { + const requiresParens = + // prepending `void ` will fail if the node has a lower precedence than void + astUtils.getPrecedence(node) < + astUtils.getPrecedence({ + type: "UnaryExpression", + operator: "void", + }) && + // check if there are parentheses around the node to avoid redundant parentheses + !astUtils.isParenthesised(sourceCode, node); + + // avoid parentheses issues + const returnOrArrowToken = sourceCode.getTokenBefore( + node, + node.parent.type === "ArrowFunctionExpression" + ? astUtils.isArrowToken + : // isReturnToken + token => token.type === "Keyword" && token.value === "return", + ); + + const firstToken = sourceCode.getTokenAfter(returnOrArrowToken); + + const prependSpace = + // is return token, as => allows void to be adjacent + returnOrArrowToken.value === "return" && + // If two tokens (return and "(") are adjacent + returnOrArrowToken.range[1] === firstToken.range[0]; + + return [ + fixer.insertTextBefore( + firstToken, + `${prependSpace ? " " : ""}void ${requiresParens ? "(" : ""}`, + ), + fixer.insertTextAfter(node, requiresParens ? ")" : ""), + ]; +} + +/** + * Fixes the linting error by `wrapping {}` around the given node's body. + * @param {Object} sourceCode context given by context.sourceCode + * @param {ASTNode} node The node to fix. + * @param {Object} fixer The fixer object provided by ESLint. + * @returns {Array} - An array of fix objects to apply to the node. + */ +function curlyWrapFixer(sourceCode, node, fixer) { + const arrowToken = sourceCode.getTokenBefore( + node.body, + astUtils.isArrowToken, + ); + const firstToken = sourceCode.getTokenAfter(arrowToken); + const lastToken = sourceCode.getLastToken(node); + + return [ + fixer.insertTextBefore(firstToken, "{"), + fixer.insertTextAfter(lastToken, "}"), + ]; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowImplicit: false, + checkForEach: false, + allowVoid: false, + }, + ], + + docs: { + description: + "Enforce `return` statements in callbacks of array methods", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-callback-return", + }, + + // eslint-disable-next-line eslint-plugin/require-meta-has-suggestions -- false positive + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + allowImplicit: { + type: "boolean", + }, + checkForEach: { + type: "boolean", + }, + allowVoid: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expectedAtEnd: + "{{arrayMethodName}}() expects a value to be returned at the end of {{name}}.", + expectedInside: + "{{arrayMethodName}}() expects a return value from {{name}}.", + expectedReturnValue: + "{{arrayMethodName}}() expects a return value from {{name}}.", + expectedNoReturnValue: + "{{arrayMethodName}}() expects no useless return value from {{name}}.", + wrapBraces: "Wrap the expression in `{}`.", + prependVoid: "Prepend `void` to the expression.", + }, + }, + + create(context) { + const [options] = context.options; + const sourceCode = context.sourceCode; + + let funcInfo = { + arrayMethodName: null, + upper: null, + codePath: null, + hasReturn: false, + shouldCheck: false, + node: null, + }; + + /** + * Checks whether or not the last code path segment is reachable. + * Then reports this function if the segment is reachable. + * + * If the last code path segment is reachable, there are paths which are not + * returned or thrown. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function checkLastSegment(node) { + if (!funcInfo.shouldCheck) { + return; + } + + const messageAndSuggestions = { messageId: "", suggest: [] }; + + if (funcInfo.arrayMethodName === "forEach") { + if ( + options.checkForEach && + node.type === "ArrowFunctionExpression" && + node.expression + ) { + if (options.allowVoid) { + if (isExpressionVoid(node.body)) { + return; + } + + messageAndSuggestions.messageId = + "expectedNoReturnValue"; + messageAndSuggestions.suggest = [ + { + messageId: "wrapBraces", + fix(fixer) { + return curlyWrapFixer( + sourceCode, + node, + fixer, + ); + }, + }, + { + messageId: "prependVoid", + fix(fixer) { + return voidPrependFixer( + sourceCode, + node.body, + fixer, + ); + }, + }, + ]; + } else { + messageAndSuggestions.messageId = + "expectedNoReturnValue"; + messageAndSuggestions.suggest = [ + { + messageId: "wrapBraces", + fix(fixer) { + return curlyWrapFixer( + sourceCode, + node, + fixer, + ); + }, + }, + ]; + } + } + } else { + if ( + node.body.type === "BlockStatement" && + isAnySegmentReachable(funcInfo.currentSegments) + ) { + messageAndSuggestions.messageId = funcInfo.hasReturn + ? "expectedAtEnd" + : "expectedInside"; + } + } + + if (messageAndSuggestions.messageId) { + const name = astUtils.getFunctionNameWithKind(node); + + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId: messageAndSuggestions.messageId, + data: { + name, + arrayMethodName: fullMethodName( + funcInfo.arrayMethodName, + ), + }, + suggest: + messageAndSuggestions.suggest.length !== 0 + ? messageAndSuggestions.suggest + : null, + }); + } + } + + return { + // Stacks this function's information. + onCodePathStart(codePath, node) { + let methodName = null; + + if (TARGET_NODE_TYPE.test(node.type)) { + methodName = getArrayMethodName(node); + } + + funcInfo = { + arrayMethodName: methodName, + upper: funcInfo, + codePath, + hasReturn: false, + shouldCheck: methodName && !node.async && !node.generator, + node, + currentSegments: new Set(), + }; + }, + + // Pops this function's information. + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + // Checks the return statement is valid. + ReturnStatement(node) { + if (!funcInfo.shouldCheck) { + return; + } + + funcInfo.hasReturn = true; + + const messageAndSuggestions = { messageId: "", suggest: [] }; + + if (funcInfo.arrayMethodName === "forEach") { + // if checkForEach: true, returning a value at any path inside a forEach is not allowed + if (options.checkForEach && node.argument) { + if (options.allowVoid) { + if (isExpressionVoid(node.argument)) { + return; + } + + messageAndSuggestions.messageId = + "expectedNoReturnValue"; + messageAndSuggestions.suggest = [ + { + messageId: "prependVoid", + fix(fixer) { + return voidPrependFixer( + sourceCode, + node.argument, + fixer, + ); + }, + }, + ]; + } else { + messageAndSuggestions.messageId = + "expectedNoReturnValue"; + } + } + } else { + // if allowImplicit: false, should also check node.argument + if (!options.allowImplicit && !node.argument) { + messageAndSuggestions.messageId = "expectedReturnValue"; + } + } + + if (messageAndSuggestions.messageId) { + context.report({ + node, + messageId: messageAndSuggestions.messageId, + data: { + name: astUtils.getFunctionNameWithKind( + funcInfo.node, + ), + arrayMethodName: fullMethodName( + funcInfo.arrayMethodName, + ), + }, + suggest: + messageAndSuggestions.suggest.length !== 0 + ? messageAndSuggestions.suggest + : null, + }); + } + }, + + // Reports a given function if the last path is reachable. + "FunctionExpression:exit": checkLastSegment, + "ArrowFunctionExpression:exit": checkLastSegment, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/array-element-newline.js b/node_modules/eslint/lib/rules/array-element-newline.js new file mode 100644 index 00000000..df3e3a15 --- /dev/null +++ b/node_modules/eslint/lib/rules/array-element-newline.js @@ -0,0 +1,374 @@ +/** + * @fileoverview Rule to enforce line breaks after each array element + * @author Jan Peer Stöcklmair + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "array-element-newline", + url: "https://eslint.style/rules/js/array-element-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce line breaks after each array element", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-element-newline", + }, + + fixable: "whitespace", + + schema: { + definitions: { + basicConfig: { + oneOf: [ + { + enum: ["always", "never", "consistent"], + }, + { + type: "object", + properties: { + multiline: { + type: "boolean", + }, + minItems: { + type: ["integer", "null"], + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + }, + type: "array", + items: [ + { + oneOf: [ + { + $ref: "#/definitions/basicConfig", + }, + { + type: "object", + properties: { + ArrayExpression: { + $ref: "#/definitions/basicConfig", + }, + ArrayPattern: { + $ref: "#/definitions/basicConfig", + }, + }, + additionalProperties: false, + minProperties: 1, + }, + ], + }, + ], + }, + + messages: { + unexpectedLineBreak: "There should be no linebreak here.", + missingLineBreak: "There should be a linebreak after this element.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} providedOption An option value to parse. + * @returns {{multiline: boolean, minItems: number}} Normalized option object. + */ + function normalizeOptionValue(providedOption) { + let consistent = false; + let multiline = false; + let minItems; + + const option = providedOption || "always"; + + if (!option || option === "always" || option.minItems === 0) { + minItems = 0; + } else if (option === "never") { + minItems = Number.POSITIVE_INFINITY; + } else if (option === "consistent") { + consistent = true; + minItems = Number.POSITIVE_INFINITY; + } else { + multiline = Boolean(option.multiline); + minItems = option.minItems || Number.POSITIVE_INFINITY; + } + + return { consistent, multiline, minItems }; + } + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} options An option value to parse. + * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. + */ + function normalizeOptions(options) { + if (options && (options.ArrayExpression || options.ArrayPattern)) { + let expressionOptions, patternOptions; + + if (options.ArrayExpression) { + expressionOptions = normalizeOptionValue( + options.ArrayExpression, + ); + } + + if (options.ArrayPattern) { + patternOptions = normalizeOptionValue(options.ArrayPattern); + } + + return { + ArrayExpression: expressionOptions, + ArrayPattern: patternOptions, + }; + } + + const value = normalizeOptionValue(options); + + return { ArrayExpression: value, ArrayPattern: value }; + } + + /** + * Reports that there shouldn't be a line break after the first token + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoLineBreak(token) { + const tokenBefore = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + context.report({ + loc: { + start: tokenBefore.loc.end, + end: token.loc.start, + }, + messageId: "unexpectedLineBreak", + fix(fixer) { + if (astUtils.isCommentToken(tokenBefore)) { + return null; + } + + if (!astUtils.isTokenOnSameLine(tokenBefore, token)) { + return fixer.replaceTextRange( + [tokenBefore.range[1], token.range[0]], + " ", + ); + } + + /* + * This will check if the comma is on the same line as the next element + * Following array: + * [ + * 1 + * , 2 + * , 3 + * ] + * + * will be fixed to: + * [ + * 1, 2, 3 + * ] + */ + const twoTokensBefore = sourceCode.getTokenBefore( + tokenBefore, + { includeComments: true }, + ); + + if (astUtils.isCommentToken(twoTokensBefore)) { + return null; + } + + return fixer.replaceTextRange( + [twoTokensBefore.range[1], tokenBefore.range[0]], + "", + ); + }, + }); + } + + /** + * Reports that there should be a line break after the first token + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredLineBreak(token) { + const tokenBefore = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + context.report({ + loc: { + start: tokenBefore.loc.end, + end: token.loc.start, + }, + messageId: "missingLineBreak", + fix(fixer) { + return fixer.replaceTextRange( + [tokenBefore.range[1], token.range[0]], + "\n", + ); + }, + }); + } + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node A node to check. This is an ObjectExpression node or an ObjectPattern node. + * @returns {void} + */ + function check(node) { + const elements = node.elements; + const normalizedOptions = normalizeOptions(context.options[0]); + const options = normalizedOptions[node.type]; + + if (!options) { + return; + } + + let elementBreak = false; + + /* + * MULTILINE: true + * loop through every element and check + * if at least one element has linebreaks inside + * this ensures that following is not valid (due to elements are on the same line): + * + * [ + * 1, + * 2, + * 3 + * ] + */ + if (options.multiline) { + elementBreak = elements + .filter(element => element !== null) + .some( + element => + element.loc.start.line !== element.loc.end.line, + ); + } + + let linebreaksCount = 0; + + for (let i = 0; i < node.elements.length; i++) { + const element = node.elements[i]; + + const previousElement = elements[i - 1]; + + if (i === 0 || element === null || previousElement === null) { + continue; + } + + const commaToken = sourceCode.getFirstTokenBetween( + previousElement, + element, + astUtils.isCommaToken, + ); + const lastTokenOfPreviousElement = + sourceCode.getTokenBefore(commaToken); + const firstTokenOfCurrentElement = + sourceCode.getTokenAfter(commaToken); + + if ( + !astUtils.isTokenOnSameLine( + lastTokenOfPreviousElement, + firstTokenOfCurrentElement, + ) + ) { + linebreaksCount++; + } + } + + const needsLinebreaks = + elements.length >= options.minItems || + (options.multiline && elementBreak) || + (options.consistent && + linebreaksCount > 0 && + linebreaksCount < node.elements.length); + + elements.forEach((element, i) => { + const previousElement = elements[i - 1]; + + if (i === 0 || element === null || previousElement === null) { + return; + } + + const commaToken = sourceCode.getFirstTokenBetween( + previousElement, + element, + astUtils.isCommaToken, + ); + const lastTokenOfPreviousElement = + sourceCode.getTokenBefore(commaToken); + const firstTokenOfCurrentElement = + sourceCode.getTokenAfter(commaToken); + + if (needsLinebreaks) { + if ( + astUtils.isTokenOnSameLine( + lastTokenOfPreviousElement, + firstTokenOfCurrentElement, + ) + ) { + reportRequiredLineBreak(firstTokenOfCurrentElement); + } + } else { + if ( + !astUtils.isTokenOnSameLine( + lastTokenOfPreviousElement, + firstTokenOfCurrentElement, + ) + ) { + reportNoLineBreak(firstTokenOfCurrentElement); + } + } + }); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + ArrayPattern: check, + ArrayExpression: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/arrow-body-style.js b/node_modules/eslint/lib/rules/arrow-body-style.js new file mode 100644 index 00000000..8272317b --- /dev/null +++ b/node_modules/eslint/lib/rules/arrow-body-style.js @@ -0,0 +1,418 @@ +/** + * @fileoverview Rule to require braces in arrow function body. + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["as-needed"], + + docs: { + description: "Require braces around arrow function bodies", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/arrow-body-style", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always", "never"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["as-needed"], + }, + { + type: "object", + properties: { + requireReturnForObjectLiteral: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + fixable: "code", + + messages: { + unexpectedOtherBlock: + "Unexpected block statement surrounding arrow body.", + unexpectedEmptyBlock: + "Unexpected block statement surrounding arrow body; put a value of `undefined` immediately after the `=>`.", + unexpectedObjectBlock: + "Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the `=>`.", + unexpectedSingleBlock: + "Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`.", + expectedBlock: "Expected block statement surrounding arrow body.", + }, + }, + + create(context) { + const options = context.options; + const always = options[0] === "always"; + const asNeeded = options[0] === "as-needed"; + const never = options[0] === "never"; + const requireReturnForObjectLiteral = + options[1] && options[1].requireReturnForObjectLiteral; + const sourceCode = context.sourceCode; + let funcInfo = null; + + /** + * Checks whether the given node has ASI problem or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed. + */ + function hasASIProblem(token) { + return ( + token && + token.type === "Punctuator" && + /^[([/`+-]/u.test(token.value) + ); + } + + /** + * Gets the closing parenthesis by the given node. + * @param {ASTNode} node first node after an opening parenthesis. + * @returns {Token} The found closing parenthesis token. + */ + function findClosingParen(node) { + let nodeToCheck = node; + + while (!astUtils.isParenthesised(sourceCode, nodeToCheck)) { + nodeToCheck = nodeToCheck.parent; + } + return sourceCode.getTokenAfter(nodeToCheck); + } + + /** + * Check whether the node is inside of a for loop's init + * @param {ASTNode} node node is inside for loop + * @returns {boolean} `true` if the node is inside of a for loop, else `false` + */ + function isInsideForLoopInitializer(node) { + if (node && node.parent) { + if ( + node.parent.type === "ForStatement" && + node.parent.init === node + ) { + return true; + } + return isInsideForLoopInitializer(node.parent); + } + return false; + } + + /** + * Determines whether a arrow function body needs braces + * @param {ASTNode} node The arrow function node. + * @returns {void} + */ + function validate(node) { + const arrowBody = node.body; + + if (arrowBody.type === "BlockStatement") { + const blockBody = arrowBody.body; + + if (blockBody.length !== 1 && !never) { + return; + } + + if ( + asNeeded && + requireReturnForObjectLiteral && + blockBody[0].type === "ReturnStatement" && + blockBody[0].argument && + blockBody[0].argument.type === "ObjectExpression" + ) { + return; + } + + if ( + never || + (asNeeded && blockBody[0].type === "ReturnStatement") + ) { + let messageId; + + if (blockBody.length === 0) { + messageId = "unexpectedEmptyBlock"; + } else if ( + blockBody.length > 1 || + blockBody[0].type !== "ReturnStatement" + ) { + messageId = "unexpectedOtherBlock"; + } else if (blockBody[0].argument === null) { + messageId = "unexpectedSingleBlock"; + } else if ( + astUtils.isOpeningBraceToken( + sourceCode.getFirstToken(blockBody[0], { skip: 1 }), + ) + ) { + messageId = "unexpectedObjectBlock"; + } else { + messageId = "unexpectedSingleBlock"; + } + + context.report({ + node, + loc: arrowBody.loc, + messageId, + fix(fixer) { + const fixes = []; + + if ( + blockBody.length !== 1 || + blockBody[0].type !== "ReturnStatement" || + !blockBody[0].argument || + hasASIProblem( + sourceCode.getTokenAfter(arrowBody), + ) + ) { + return fixes; + } + + const openingBrace = + sourceCode.getFirstToken(arrowBody); + const closingBrace = + sourceCode.getLastToken(arrowBody); + const firstValueToken = sourceCode.getFirstToken( + blockBody[0], + 1, + ); + const lastValueToken = sourceCode.getLastToken( + blockBody[0], + ); + const commentsExist = + sourceCode.commentsExistBetween( + openingBrace, + firstValueToken, + ) || + sourceCode.commentsExistBetween( + lastValueToken, + closingBrace, + ); + + /* + * Remove tokens around the return value. + * If comments don't exist, remove extra spaces as well. + */ + if (commentsExist) { + fixes.push( + fixer.remove(openingBrace), + fixer.remove(closingBrace), + fixer.remove( + sourceCode.getTokenAfter(openingBrace), + ), // return keyword + ); + } else { + fixes.push( + fixer.removeRange([ + openingBrace.range[0], + firstValueToken.range[0], + ]), + fixer.removeRange([ + lastValueToken.range[1], + closingBrace.range[1], + ]), + ); + } + + /* + * If the first token of the return value is `{` or the return value is a sequence expression, + * enclose the return value by parentheses to avoid syntax error. + */ + if ( + astUtils.isOpeningBraceToken(firstValueToken) || + blockBody[0].argument.type === + "SequenceExpression" || + (funcInfo.hasInOperator && + isInsideForLoopInitializer(node)) + ) { + if ( + !astUtils.isParenthesised( + sourceCode, + blockBody[0].argument, + ) + ) { + fixes.push( + fixer.insertTextBefore( + firstValueToken, + "(", + ), + fixer.insertTextAfter( + lastValueToken, + ")", + ), + ); + } + } + + /* + * If the last token of the return statement is semicolon, remove it. + * Non-block arrow body is an expression, not a statement. + */ + if (astUtils.isSemicolonToken(lastValueToken)) { + fixes.push(fixer.remove(lastValueToken)); + } + + return fixes; + }, + }); + } + } else { + if ( + always || + (asNeeded && + requireReturnForObjectLiteral && + arrowBody.type === "ObjectExpression") + ) { + context.report({ + node, + loc: arrowBody.loc, + messageId: "expectedBlock", + fix(fixer) { + const fixes = []; + const arrowToken = sourceCode.getTokenBefore( + arrowBody, + astUtils.isArrowToken, + ); + const [ + firstTokenAfterArrow, + secondTokenAfterArrow, + ] = sourceCode.getTokensAfter(arrowToken, { + count: 2, + }); + const lastToken = sourceCode.getLastToken(node); + + let parenthesisedObjectLiteral = null; + + if ( + astUtils.isOpeningParenToken( + firstTokenAfterArrow, + ) && + astUtils.isOpeningBraceToken( + secondTokenAfterArrow, + ) + ) { + const braceNode = + sourceCode.getNodeByRangeIndex( + secondTokenAfterArrow.range[0], + ); + + if (braceNode.type === "ObjectExpression") { + parenthesisedObjectLiteral = braceNode; + } + } + + // If the value is object literal, remove parentheses which were forced by syntax. + if (parenthesisedObjectLiteral) { + const openingParenToken = firstTokenAfterArrow; + const openingBraceToken = secondTokenAfterArrow; + + if ( + astUtils.isTokenOnSameLine( + openingParenToken, + openingBraceToken, + ) + ) { + fixes.push( + fixer.replaceText( + openingParenToken, + "{return ", + ), + ); + } else { + // Avoid ASI + fixes.push( + fixer.replaceText( + openingParenToken, + "{", + ), + fixer.insertTextBefore( + openingBraceToken, + "return ", + ), + ); + } + + // Closing paren for the object doesn't have to be lastToken, e.g.: () => ({}).foo() + fixes.push( + fixer.remove( + findClosingParen( + parenthesisedObjectLiteral, + ), + ), + ); + fixes.push( + fixer.insertTextAfter(lastToken, "}"), + ); + } else { + fixes.push( + fixer.insertTextBefore( + firstTokenAfterArrow, + "{return ", + ), + ); + fixes.push( + fixer.insertTextAfter(lastToken, "}"), + ); + } + + return fixes; + }, + }); + } + } + } + + return { + "BinaryExpression[operator='in']"() { + let info = funcInfo; + + while (info) { + info.hasInOperator = true; + info = info.upper; + } + }, + ArrowFunctionExpression() { + funcInfo = { + upper: funcInfo, + hasInOperator: false, + }; + }, + "ArrowFunctionExpression:exit"(node) { + validate(node); + funcInfo = funcInfo.upper; + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/arrow-parens.js b/node_modules/eslint/lib/rules/arrow-parens.js new file mode 100644 index 00000000..ed93c3f6 --- /dev/null +++ b/node_modules/eslint/lib/rules/arrow-parens.js @@ -0,0 +1,237 @@ +/** + * @fileoverview Rule to require parens in arrow function arguments. + * @author Jxck + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if the given arrow function has block body. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @returns {boolean} `true` if the function has block body. + */ +function hasBlockBody(node) { + return node.body.type === "BlockStatement"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "arrow-parens", + url: "https://eslint.style/rules/js/arrow-parens", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require parentheses around arrow function arguments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/arrow-parens", + }, + + fixable: "code", + + schema: [ + { + enum: ["always", "as-needed"], + }, + { + type: "object", + properties: { + requireForBlockBody: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedParens: + "Unexpected parentheses around single function argument.", + expectedParens: + "Expected parentheses around arrow function argument.", + + unexpectedParensInline: + "Unexpected parentheses around single function argument having a body with no curly braces.", + expectedParensBlock: + "Expected parentheses around arrow function argument having a body with curly braces.", + }, + }, + + create(context) { + const asNeeded = context.options[0] === "as-needed"; + const requireForBlockBody = + asNeeded && + context.options[1] && + context.options[1].requireForBlockBody === true; + + const sourceCode = context.sourceCode; + + /** + * Finds opening paren of parameters for the given arrow function, if it exists. + * It is assumed that the given arrow function has exactly one parameter. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @returns {Token|null} the opening paren, or `null` if the given arrow function doesn't have parens of parameters. + */ + function findOpeningParenOfParams(node) { + const tokenBeforeParams = sourceCode.getTokenBefore(node.params[0]); + + if ( + tokenBeforeParams && + astUtils.isOpeningParenToken(tokenBeforeParams) && + node.range[0] <= tokenBeforeParams.range[0] + ) { + return tokenBeforeParams; + } + + return null; + } + + /** + * Finds closing paren of parameters for the given arrow function. + * It is assumed that the given arrow function has parens of parameters and that it has exactly one parameter. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @returns {Token} the closing paren of parameters. + */ + function getClosingParenOfParams(node) { + return sourceCode.getTokenAfter( + node.params[0], + astUtils.isClosingParenToken, + ); + } + + /** + * Determines whether the given arrow function has comments inside parens of parameters. + * It is assumed that the given arrow function has parens of parameters. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @param {Token} openingParen Opening paren of parameters. + * @returns {boolean} `true` if the function has at least one comment inside of parens of parameters. + */ + function hasCommentsInParensOfParams(node, openingParen) { + return sourceCode.commentsExistBetween( + openingParen, + getClosingParenOfParams(node), + ); + } + + /** + * Determines whether the given arrow function has unexpected tokens before opening paren of parameters, + * in which case it will be assumed that the existing parens of parameters are necessary. + * Only tokens within the range of the arrow function (tokens that are part of the arrow function) are taken into account. + * Example: (a) => b + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @param {Token} openingParen Opening paren of parameters. + * @returns {boolean} `true` if the function has at least one unexpected token. + */ + function hasUnexpectedTokensBeforeOpeningParen(node, openingParen) { + const expectedCount = node.async ? 1 : 0; + + return ( + sourceCode.getFirstToken(node, { skip: expectedCount }) !== + openingParen + ); + } + + return { + "ArrowFunctionExpression[params.length=1]"(node) { + const shouldHaveParens = + !asNeeded || (requireForBlockBody && hasBlockBody(node)); + const openingParen = findOpeningParenOfParams(node); + const hasParens = openingParen !== null; + const [param] = node.params; + + if (shouldHaveParens && !hasParens) { + context.report({ + node, + messageId: requireForBlockBody + ? "expectedParensBlock" + : "expectedParens", + loc: param.loc, + *fix(fixer) { + yield fixer.insertTextBefore(param, "("); + yield fixer.insertTextAfter(param, ")"); + }, + }); + } + + if ( + !shouldHaveParens && + hasParens && + param.type === "Identifier" && + !param.typeAnnotation && + !node.returnType && + !hasCommentsInParensOfParams(node, openingParen) && + !hasUnexpectedTokensBeforeOpeningParen(node, openingParen) + ) { + context.report({ + node, + messageId: requireForBlockBody + ? "unexpectedParensInline" + : "unexpectedParens", + loc: param.loc, + *fix(fixer) { + const tokenBeforeOpeningParen = + sourceCode.getTokenBefore(openingParen); + const closingParen = getClosingParenOfParams(node); + + if ( + tokenBeforeOpeningParen && + tokenBeforeOpeningParen.range[1] === + openingParen.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBeforeOpeningParen, + sourceCode.getFirstToken(param), + ) + ) { + yield fixer.insertTextBefore(openingParen, " "); + } + + // remove parens, whitespace inside parens, and possible trailing comma + yield fixer.removeRange([ + openingParen.range[0], + param.range[0], + ]); + yield fixer.removeRange([ + param.range[1], + closingParen.range[1], + ]); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/arrow-spacing.js b/node_modules/eslint/lib/rules/arrow-spacing.js new file mode 100644 index 00000000..b25c2667 --- /dev/null +++ b/node_modules/eslint/lib/rules/arrow-spacing.js @@ -0,0 +1,188 @@ +/** + * @fileoverview Rule to define spacing before/after arrow function's arrow. + * @author Jxck + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "arrow-spacing", + url: "https://eslint.style/rules/js/arrow-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing before and after the arrow in arrow functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/arrow-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { + type: "boolean", + default: true, + }, + after: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expectedBefore: "Missing space before =>.", + unexpectedBefore: "Unexpected space before =>.", + + expectedAfter: "Missing space after =>.", + unexpectedAfter: "Unexpected space after =>.", + }, + }, + + create(context) { + // merge rules with default + const rule = Object.assign({}, context.options[0]); + + rule.before = rule.before !== false; + rule.after = rule.after !== false; + + const sourceCode = context.sourceCode; + + /** + * Get tokens of arrow(`=>`) and before/after arrow. + * @param {ASTNode} node The arrow function node. + * @returns {Object} Tokens of arrow and before/after arrow. + */ + function getTokens(node) { + const arrow = sourceCode.getTokenBefore( + node.body, + astUtils.isArrowToken, + ); + + return { + before: sourceCode.getTokenBefore(arrow), + arrow, + after: sourceCode.getTokenAfter(arrow), + }; + } + + /** + * Count spaces before/after arrow(`=>`) token. + * @param {Object} tokens Tokens before/after arrow. + * @returns {Object} count of space before/after arrow. + */ + function countSpaces(tokens) { + const before = tokens.arrow.range[0] - tokens.before.range[1]; + const after = tokens.after.range[0] - tokens.arrow.range[1]; + + return { before, after }; + } + + /** + * Determines whether space(s) before after arrow(`=>`) is satisfy rule. + * if before/after value is `true`, there should be space(s). + * if before/after value is `false`, there should be no space. + * @param {ASTNode} node The arrow function node. + * @returns {void} + */ + function spaces(node) { + const tokens = getTokens(node); + const countSpace = countSpaces(tokens); + + if (rule.before) { + // should be space(s) before arrow + if (countSpace.before === 0) { + context.report({ + node: tokens.before, + messageId: "expectedBefore", + fix(fixer) { + return fixer.insertTextBefore(tokens.arrow, " "); + }, + }); + } + } else { + // should be no space before arrow + if (countSpace.before > 0) { + context.report({ + node: tokens.before, + messageId: "unexpectedBefore", + fix(fixer) { + return fixer.removeRange([ + tokens.before.range[1], + tokens.arrow.range[0], + ]); + }, + }); + } + } + + if (rule.after) { + // should be space(s) after arrow + if (countSpace.after === 0) { + context.report({ + node: tokens.after, + messageId: "expectedAfter", + fix(fixer) { + return fixer.insertTextAfter(tokens.arrow, " "); + }, + }); + } + } else { + // should be no space after arrow + if (countSpace.after > 0) { + context.report({ + node: tokens.after, + messageId: "unexpectedAfter", + fix(fixer) { + return fixer.removeRange([ + tokens.arrow.range[1], + tokens.after.range[0], + ]); + }, + }); + } + } + } + + return { + ArrowFunctionExpression: spaces, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/block-scoped-var.js b/node_modules/eslint/lib/rules/block-scoped-var.js new file mode 100644 index 00000000..e79bec51 --- /dev/null +++ b/node_modules/eslint/lib/rules/block-scoped-var.js @@ -0,0 +1,137 @@ +/** + * @fileoverview Rule to check for "block scoped" variables by binding context + * @author Matt DuVall + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce the use of variables within the scope they are defined", + recommended: false, + url: "https://eslint.org/docs/latest/rules/block-scoped-var", + }, + + schema: [], + + messages: { + outOfScope: + "'{{name}}' declared on line {{definitionLine}} column {{definitionColumn}} is used outside of binding context.", + }, + }, + + create(context) { + let stack = []; + const sourceCode = context.sourceCode; + + /** + * Makes a block scope. + * @param {ASTNode} node A node of a scope. + * @returns {void} + */ + function enterScope(node) { + stack.push(node.range); + } + + /** + * Pops the last block scope. + * @returns {void} + */ + function exitScope() { + stack.pop(); + } + + /** + * Reports a given reference. + * @param {eslint-scope.Reference} reference A reference to report. + * @param {eslint-scope.Definition} definition A definition for which to report reference. + * @returns {void} + */ + function report(reference, definition) { + const identifier = reference.identifier; + const definitionPosition = definition.name.loc.start; + + context.report({ + node: identifier, + messageId: "outOfScope", + data: { + name: identifier.name, + definitionLine: definitionPosition.line, + definitionColumn: definitionPosition.column + 1, + }, + }); + } + + /** + * Finds and reports references which are outside of valid scopes. + * @param {ASTNode} node A node to get variables. + * @returns {void} + */ + function checkForVariables(node) { + if (node.kind !== "var") { + return; + } + + // Defines a predicate to check whether or not a given reference is outside of valid scope. + const scopeRange = stack.at(-1); + + /** + * Check if a reference is out of scope + * @param {ASTNode} reference node to examine + * @returns {boolean} True is its outside the scope + * @private + */ + function isOutsideOfScope(reference) { + const idRange = reference.identifier.range; + + return idRange[0] < scopeRange[0] || idRange[1] > scopeRange[1]; + } + + // Gets declared variables, and checks its references. + const variables = sourceCode.getDeclaredVariables(node); + + for (let i = 0; i < variables.length; ++i) { + // Reports. + variables[i].references.filter(isOutsideOfScope).forEach(ref => + report( + ref, + variables[i].defs.find(def => def.parent === node), + ), + ); + } + } + + return { + Program(node) { + stack = [node.range]; + }, + + // Manages scopes. + BlockStatement: enterScope, + "BlockStatement:exit": exitScope, + ForStatement: enterScope, + "ForStatement:exit": exitScope, + ForInStatement: enterScope, + "ForInStatement:exit": exitScope, + ForOfStatement: enterScope, + "ForOfStatement:exit": exitScope, + SwitchStatement: enterScope, + "SwitchStatement:exit": exitScope, + CatchClause: enterScope, + "CatchClause:exit": exitScope, + StaticBlock: enterScope, + "StaticBlock:exit": exitScope, + + // Finds and reports references which are outside of valid scope. + VariableDeclaration: checkForVariables, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/block-spacing.js b/node_modules/eslint/lib/rules/block-spacing.js new file mode 100644 index 00000000..aafd2a12 --- /dev/null +++ b/node_modules/eslint/lib/rules/block-spacing.js @@ -0,0 +1,202 @@ +/** + * @fileoverview A rule to disallow or enforce spaces inside of single line blocks. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const util = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "block-spacing", + url: "https://eslint.style/rules/js/block-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Disallow or enforce spaces inside of blocks after opening block and before closing block", + recommended: false, + url: "https://eslint.org/docs/latest/rules/block-spacing", + }, + + fixable: "whitespace", + + schema: [{ enum: ["always", "never"] }], + + messages: { + missing: "Requires a space {{location}} '{{token}}'.", + extra: "Unexpected space(s) {{location}} '{{token}}'.", + }, + }, + + create(context) { + const always = context.options[0] !== "never", + messageId = always ? "missing" : "extra", + sourceCode = context.sourceCode; + + /** + * Gets the open brace token from a given node. + * @param {ASTNode} node A BlockStatement/StaticBlock/SwitchStatement node to get. + * @returns {Token} The token of the open brace. + */ + function getOpenBrace(node) { + if (node.type === "SwitchStatement") { + if (node.cases.length > 0) { + return sourceCode.getTokenBefore(node.cases[0]); + } + return sourceCode.getLastToken(node, 1); + } + + if (node.type === "StaticBlock") { + return sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token + } + + // "BlockStatement" + return sourceCode.getFirstToken(node); + } + + /** + * Checks whether or not: + * - given tokens are on same line. + * - there is/isn't a space between given tokens. + * @param {Token} left A token to check. + * @param {Token} right The token which is next to `left`. + * @returns {boolean} + * When the option is `"always"`, `true` if there are one or more spaces between given tokens. + * When the option is `"never"`, `true` if there are not any spaces between given tokens. + * If given tokens are not on same line, it's always `true`. + */ + function isValid(left, right) { + return ( + !util.isTokenOnSameLine(left, right) || + sourceCode.isSpaceBetweenTokens(left, right) === always + ); + } + + /** + * Checks and reports invalid spacing style inside braces. + * @param {ASTNode} node A BlockStatement/StaticBlock/SwitchStatement node to check. + * @returns {void} + */ + function checkSpacingInsideBraces(node) { + // Gets braces and the first/last token of content. + const openBrace = getOpenBrace(node); + const closeBrace = sourceCode.getLastToken(node); + const firstToken = sourceCode.getTokenAfter(openBrace, { + includeComments: true, + }); + const lastToken = sourceCode.getTokenBefore(closeBrace, { + includeComments: true, + }); + + // Skip if the node is invalid or empty. + if ( + openBrace.type !== "Punctuator" || + openBrace.value !== "{" || + closeBrace.type !== "Punctuator" || + closeBrace.value !== "}" || + firstToken === closeBrace + ) { + return; + } + + // Skip line comments for option never + if (!always && firstToken.type === "Line") { + return; + } + + // Check. + if (!isValid(openBrace, firstToken)) { + let loc = openBrace.loc; + + if (messageId === "extra") { + loc = { + start: openBrace.loc.end, + end: firstToken.loc.start, + }; + } + + context.report({ + node, + loc, + messageId, + data: { + location: "after", + token: openBrace.value, + }, + fix(fixer) { + if (always) { + return fixer.insertTextBefore(firstToken, " "); + } + + return fixer.removeRange([ + openBrace.range[1], + firstToken.range[0], + ]); + }, + }); + } + if (!isValid(lastToken, closeBrace)) { + let loc = closeBrace.loc; + + if (messageId === "extra") { + loc = { + start: lastToken.loc.end, + end: closeBrace.loc.start, + }; + } + context.report({ + node, + loc, + messageId, + data: { + location: "before", + token: closeBrace.value, + }, + fix(fixer) { + if (always) { + return fixer.insertTextAfter(lastToken, " "); + } + + return fixer.removeRange([ + lastToken.range[1], + closeBrace.range[0], + ]); + }, + }); + } + } + + return { + BlockStatement: checkSpacingInsideBraces, + StaticBlock: checkSpacingInsideBraces, + SwitchStatement: checkSpacingInsideBraces, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/brace-style.js b/node_modules/eslint/lib/rules/brace-style.js new file mode 100644 index 00000000..72e47a17 --- /dev/null +++ b/node_modules/eslint/lib/rules/brace-style.js @@ -0,0 +1,278 @@ +/** + * @fileoverview Rule to flag block statements that do not use the one true brace style + * @author Ian Christian Myers + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "brace-style", + url: "https://eslint.style/rules/js/brace-style", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent brace style for blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/brace-style", + }, + + schema: [ + { + enum: ["1tbs", "stroustrup", "allman"], + }, + { + type: "object", + properties: { + allowSingleLine: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + fixable: "whitespace", + + messages: { + nextLineOpen: + "Opening curly brace does not appear on the same line as controlling statement.", + sameLineOpen: + "Opening curly brace appears on the same line as controlling statement.", + blockSameLine: + "Statement inside of curly braces should be on next line.", + nextLineClose: + "Closing curly brace does not appear on the same line as the subsequent block.", + singleLineClose: + "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.", + sameLineClose: + "Closing curly brace appears on the same line as the subsequent block.", + }, + }, + + create(context) { + const style = context.options[0] || "1tbs", + params = context.options[1] || {}, + sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Fixes a place where a newline unexpectedly appears + * @param {Token} firstToken The token before the unexpected newline + * @param {Token} secondToken The token after the unexpected newline + * @returns {Function} A fixer function to remove the newlines between the tokens + */ + function removeNewlineBetween(firstToken, secondToken) { + const textRange = [firstToken.range[1], secondToken.range[0]]; + const textBetween = sourceCode.text.slice( + textRange[0], + textRange[1], + ); + + // Don't do a fix if there is a comment between the tokens + if (textBetween.trim()) { + return null; + } + return fixer => fixer.replaceTextRange(textRange, " "); + } + + /** + * Validates a pair of curly brackets based on the user's config + * @param {Token} openingCurly The opening curly bracket + * @param {Token} closingCurly The closing curly bracket + * @returns {void} + */ + function validateCurlyPair(openingCurly, closingCurly) { + const tokenBeforeOpeningCurly = + sourceCode.getTokenBefore(openingCurly); + const tokenAfterOpeningCurly = + sourceCode.getTokenAfter(openingCurly); + const tokenBeforeClosingCurly = + sourceCode.getTokenBefore(closingCurly); + const singleLineException = + params.allowSingleLine && + astUtils.isTokenOnSameLine(openingCurly, closingCurly); + + if ( + style !== "allman" && + !astUtils.isTokenOnSameLine( + tokenBeforeOpeningCurly, + openingCurly, + ) + ) { + context.report({ + node: openingCurly, + messageId: "nextLineOpen", + fix: removeNewlineBetween( + tokenBeforeOpeningCurly, + openingCurly, + ), + }); + } + + if ( + style === "allman" && + astUtils.isTokenOnSameLine( + tokenBeforeOpeningCurly, + openingCurly, + ) && + !singleLineException + ) { + context.report({ + node: openingCurly, + messageId: "sameLineOpen", + fix: fixer => fixer.insertTextBefore(openingCurly, "\n"), + }); + } + + if ( + astUtils.isTokenOnSameLine( + openingCurly, + tokenAfterOpeningCurly, + ) && + tokenAfterOpeningCurly !== closingCurly && + !singleLineException + ) { + context.report({ + node: openingCurly, + messageId: "blockSameLine", + fix: fixer => fixer.insertTextAfter(openingCurly, "\n"), + }); + } + + if ( + tokenBeforeClosingCurly !== openingCurly && + !singleLineException && + astUtils.isTokenOnSameLine( + tokenBeforeClosingCurly, + closingCurly, + ) + ) { + context.report({ + node: closingCurly, + messageId: "singleLineClose", + fix: fixer => fixer.insertTextBefore(closingCurly, "\n"), + }); + } + } + + /** + * Validates the location of a token that appears before a keyword (e.g. a newline before `else`) + * @param {Token} curlyToken The closing curly token. This is assumed to precede a keyword token (such as `else` or `finally`). + * @returns {void} + */ + function validateCurlyBeforeKeyword(curlyToken) { + const keywordToken = sourceCode.getTokenAfter(curlyToken); + + if ( + style === "1tbs" && + !astUtils.isTokenOnSameLine(curlyToken, keywordToken) + ) { + context.report({ + node: curlyToken, + messageId: "nextLineClose", + fix: removeNewlineBetween(curlyToken, keywordToken), + }); + } + + if ( + style !== "1tbs" && + astUtils.isTokenOnSameLine(curlyToken, keywordToken) + ) { + context.report({ + node: curlyToken, + messageId: "sameLineClose", + fix: fixer => fixer.insertTextAfter(curlyToken, "\n"), + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + BlockStatement(node) { + if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { + validateCurlyPair( + sourceCode.getFirstToken(node), + sourceCode.getLastToken(node), + ); + } + }, + StaticBlock(node) { + validateCurlyPair( + sourceCode.getFirstToken(node, { skip: 1 }), // skip the `static` token + sourceCode.getLastToken(node), + ); + }, + ClassBody(node) { + validateCurlyPair( + sourceCode.getFirstToken(node), + sourceCode.getLastToken(node), + ); + }, + SwitchStatement(node) { + const closingCurly = sourceCode.getLastToken(node); + const openingCurly = sourceCode.getTokenBefore( + node.cases.length ? node.cases[0] : closingCurly, + ); + + validateCurlyPair(openingCurly, closingCurly); + }, + IfStatement(node) { + if ( + node.consequent.type === "BlockStatement" && + node.alternate + ) { + // Handle the keyword after the `if` block (before `else`) + validateCurlyBeforeKeyword( + sourceCode.getLastToken(node.consequent), + ); + } + }, + TryStatement(node) { + // Handle the keyword after the `try` block (before `catch` or `finally`) + validateCurlyBeforeKeyword(sourceCode.getLastToken(node.block)); + + if (node.handler && node.finalizer) { + // Handle the keyword after the `catch` block (before `finally`) + validateCurlyBeforeKeyword( + sourceCode.getLastToken(node.handler.body), + ); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/callback-return.js b/node_modules/eslint/lib/rules/callback-return.js new file mode 100644 index 00000000..7cf9328c --- /dev/null +++ b/node_modules/eslint/lib/rules/callback-return.js @@ -0,0 +1,216 @@ +/** + * @fileoverview Enforce return after a callback. + * @author Jamund Ferguson + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "callback-return", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/callback-return.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Require `return` statements after callbacks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/callback-return", + }, + + schema: [ + { + type: "array", + items: { type: "string" }, + }, + ], + + messages: { + missingReturn: "Expected return with your callback function.", + }, + }, + + create(context) { + const callbacks = context.options[0] || ["callback", "cb", "next"], + sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Find the closest parent matching a list of types. + * @param {ASTNode} node The node whose parents we are searching + * @param {Array} types The node types to match + * @returns {ASTNode} The matched node or undefined. + */ + function findClosestParentOfType(node, types) { + if (!node.parent) { + return null; + } + if (!types.includes(node.parent.type)) { + return findClosestParentOfType(node.parent, types); + } + return node.parent; + } + + /** + * Check to see if a node contains only identifiers + * @param {ASTNode} node The node to check + * @returns {boolean} Whether or not the node contains only identifiers + */ + function containsOnlyIdentifiers(node) { + if (node.type === "Identifier") { + return true; + } + + if (node.type === "MemberExpression") { + if (node.object.type === "Identifier") { + return true; + } + if (node.object.type === "MemberExpression") { + return containsOnlyIdentifiers(node.object); + } + } + + return false; + } + + /** + * Check to see if a CallExpression is in our callback list. + * @param {ASTNode} node The node to check against our callback names list. + * @returns {boolean} Whether or not this function matches our callback name. + */ + function isCallback(node) { + return ( + containsOnlyIdentifiers(node.callee) && + callbacks.includes(sourceCode.getText(node.callee)) + ); + } + + /** + * Determines whether or not the callback is part of a callback expression. + * @param {ASTNode} node The callback node + * @param {ASTNode} parentNode The expression node + * @returns {boolean} Whether or not this is part of a callback expression + */ + function isCallbackExpression(node, parentNode) { + // ensure the parent node exists and is an expression + if (!parentNode || parentNode.type !== "ExpressionStatement") { + return false; + } + + // cb() + if (parentNode.expression === node) { + return true; + } + + // special case for cb && cb() and similar + if ( + parentNode.expression.type === "BinaryExpression" || + parentNode.expression.type === "LogicalExpression" + ) { + if (parentNode.expression.right === node) { + return true; + } + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + CallExpression(node) { + // if we're not a callback we can return + if (!isCallback(node)) { + return; + } + + // find the closest block, return or loop + const closestBlock = + findClosestParentOfType(node, [ + "BlockStatement", + "ReturnStatement", + "ArrowFunctionExpression", + ]) || {}; + + // if our parent is a return we know we're ok + if (closestBlock.type === "ReturnStatement") { + return; + } + + // arrow functions don't always have blocks and implicitly return + if (closestBlock.type === "ArrowFunctionExpression") { + return; + } + + // block statements are part of functions and most if statements + if (closestBlock.type === "BlockStatement") { + // find the last item in the block + const lastItem = closestBlock.body.at(-1); + + // if the callback is the last thing in a block that might be ok + if (isCallbackExpression(node, lastItem)) { + const parentType = closestBlock.parent.type; + + // but only if the block is part of a function + if ( + parentType === "FunctionExpression" || + parentType === "FunctionDeclaration" || + parentType === "ArrowFunctionExpression" + ) { + return; + } + } + + // ending a block with a return is also ok + if (lastItem.type === "ReturnStatement") { + // but only if the callback is immediately before + if ( + isCallbackExpression(node, closestBlock.body.at(-2)) + ) { + return; + } + } + } + + // as long as you're the child of a function at this point you should be asked to return + if ( + findClosestParentOfType(node, [ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", + ]) + ) { + context.report({ node, messageId: "missingReturn" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/camelcase.js b/node_modules/eslint/lib/rules/camelcase.js new file mode 100644 index 00000000..dad6b120 --- /dev/null +++ b/node_modules/eslint/lib/rules/camelcase.js @@ -0,0 +1,422 @@ +/** + * @fileoverview Rule to flag non-camelcased identifiers + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allow: [], + ignoreDestructuring: false, + ignoreGlobals: false, + ignoreImports: false, + properties: "always", + }, + ], + + docs: { + description: "Enforce camelcase naming convention", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/camelcase", + }, + + schema: [ + { + type: "object", + properties: { + ignoreDestructuring: { + type: "boolean", + }, + ignoreImports: { + type: "boolean", + }, + ignoreGlobals: { + type: "boolean", + }, + properties: { + enum: ["always", "never"], + }, + allow: { + type: "array", + items: { + type: "string", + }, + minItems: 0, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + notCamelCase: "Identifier '{{name}}' is not in camel case.", + notCamelCasePrivate: "#{{name}} is not in camel case.", + }, + }, + + create(context) { + const [ + { + allow, + ignoreDestructuring, + ignoreGlobals, + ignoreImports, + properties, + }, + ] = context.options; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // contains reported nodes to avoid reporting twice on destructuring with shorthand notation + const reported = new Set(); + + /** + * Checks if a string contains an underscore and isn't all upper-case + * @param {string} name The string to check. + * @returns {boolean} if the string is underscored + * @private + */ + function isUnderscored(name) { + const nameBody = name.replace(/^_+|_+$/gu, ""); + + // if there's an underscore, it might be A_CONSTANT, which is okay + return ( + nameBody.includes("_") && nameBody !== nameBody.toUpperCase() + ); + } + + /** + * Checks if a string match the ignore list + * @param {string} name The string to check. + * @returns {boolean} if the string is ignored + * @private + */ + function isAllowed(name) { + return allow.some( + entry => name === entry || name.match(new RegExp(entry, "u")), + ); + } + + /** + * Checks if a given name is good or not. + * @param {string} name The name to check. + * @returns {boolean} `true` if the name is good. + * @private + */ + function isGoodName(name) { + return !isUnderscored(name) || isAllowed(name); + } + + /** + * Checks if a given identifier reference or member expression is an assignment + * target. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is an assignment target. + */ + function isAssignmentTarget(node) { + const parent = node.parent; + + switch (parent.type) { + case "AssignmentExpression": + case "AssignmentPattern": + return parent.left === node; + + case "Property": + return ( + parent.parent.type === "ObjectPattern" && + parent.value === node + ); + case "ArrayPattern": + case "RestElement": + return true; + + default: + return false; + } + } + + /** + * Checks if a given binding identifier uses the original name as-is. + * - If it's in object destructuring or object expression, the original name is its property name. + * - If it's in import declaration, the original name is its exported name. + * @param {ASTNode} node The `Identifier` node to check. + * @returns {boolean} `true` if the identifier uses the original name as-is. + */ + function equalsToOriginalName(node) { + const localName = node.name; + const valueNode = + node.parent.type === "AssignmentPattern" ? node.parent : node; + const parent = valueNode.parent; + + switch (parent.type) { + case "Property": + return ( + (parent.parent.type === "ObjectPattern" || + parent.parent.type === "ObjectExpression") && + parent.value === valueNode && + !parent.computed && + parent.key.type === "Identifier" && + parent.key.name === localName + ); + + case "ImportSpecifier": + return ( + parent.local === node && + astUtils.getModuleExportName(parent.imported) === + localName + ); + + default: + return false; + } + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + if (reported.has(node.range[0])) { + return; + } + reported.add(node.range[0]); + + // Report it. + context.report({ + node, + messageId: + node.type === "PrivateIdentifier" + ? "notCamelCasePrivate" + : "notCamelCase", + data: { name: node.name }, + }); + } + + /** + * Reports an identifier reference or a binding identifier. + * @param {ASTNode} node The `Identifier` node to report. + * @returns {void} + */ + function reportReferenceId(node) { + /* + * For backward compatibility, if it's in callings then ignore it. + * Not sure why it is. + */ + if ( + node.parent.type === "CallExpression" || + node.parent.type === "NewExpression" + ) { + return; + } + + /* + * For backward compatibility, if it's a default value of + * destructuring/parameters then ignore it. + * Not sure why it is. + */ + if ( + node.parent.type === "AssignmentPattern" && + node.parent.right === node + ) { + return; + } + + /* + * The `ignoreDestructuring` flag skips the identifiers that uses + * the property name as-is. + */ + if (ignoreDestructuring && equalsToOriginalName(node)) { + return; + } + + /* + * Import attribute keys are always ignored + */ + if (astUtils.isImportAttributeKey(node)) { + return; + } + + report(node); + } + + return { + // Report camelcase of global variable references ------------------ + Program(node) { + const scope = sourceCode.getScope(node); + + if (!ignoreGlobals) { + // Defined globals in config files or directive comments. + for (const variable of scope.variables) { + if ( + variable.identifiers.length > 0 || + isGoodName(variable.name) + ) { + continue; + } + for (const reference of variable.references) { + /* + * For backward compatibility, this rule reports read-only + * references as well. + */ + reportReferenceId(reference.identifier); + } + } + } + + // Undefined globals. + for (const reference of scope.through) { + const id = reference.identifier; + + if ( + isGoodName(id.name) || + astUtils.isImportAttributeKey(id) + ) { + continue; + } + + /* + * For backward compatibility, this rule reports read-only + * references as well. + */ + reportReferenceId(id); + } + }, + + // Report camelcase of declared variables -------------------------- + [[ + "VariableDeclaration", + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", + "ClassDeclaration", + "ClassExpression", + "CatchClause", + ]](node) { + for (const variable of sourceCode.getDeclaredVariables(node)) { + if (isGoodName(variable.name)) { + continue; + } + const id = variable.identifiers[0]; + + // Report declaration. + if (!(ignoreDestructuring && equalsToOriginalName(id))) { + report(id); + } + + /* + * For backward compatibility, report references as well. + * It looks unnecessary because declarations are reported. + */ + for (const reference of variable.references) { + if (reference.init) { + continue; // Skip the write references of initializers. + } + reportReferenceId(reference.identifier); + } + } + }, + + // Report camelcase in properties ---------------------------------- + [[ + "ObjectExpression > Property[computed!=true] > Identifier.key", + "MethodDefinition[computed!=true] > Identifier.key", + "PropertyDefinition[computed!=true] > Identifier.key", + "MethodDefinition > PrivateIdentifier.key", + "PropertyDefinition > PrivateIdentifier.key", + ]](node) { + if ( + properties === "never" || + astUtils.isImportAttributeKey(node) || + isGoodName(node.name) + ) { + return; + } + report(node); + }, + "MemberExpression[computed!=true] > Identifier.property"(node) { + if ( + properties === "never" || + !isAssignmentTarget(node.parent) || // ← ignore read-only references. + isGoodName(node.name) + ) { + return; + } + report(node); + }, + + // Report camelcase in import -------------------------------------- + ImportDeclaration(node) { + for (const variable of sourceCode.getDeclaredVariables(node)) { + if (isGoodName(variable.name)) { + continue; + } + const id = variable.identifiers[0]; + + // Report declaration. + if (!(ignoreImports && equalsToOriginalName(id))) { + report(id); + } + + /* + * For backward compatibility, report references as well. + * It looks unnecessary because declarations are reported. + */ + for (const reference of variable.references) { + reportReferenceId(reference.identifier); + } + } + }, + + // Report camelcase in re-export ----------------------------------- + [[ + "ExportAllDeclaration > Identifier.exported", + "ExportSpecifier > Identifier.exported", + ]](node) { + if (isGoodName(node.name)) { + return; + } + report(node); + }, + + // Report camelcase in labels -------------------------------------- + [[ + "LabeledStatement > Identifier.label", + + /* + * For backward compatibility, report references as well. + * It looks unnecessary because declarations are reported. + */ + "BreakStatement > Identifier.label", + "ContinueStatement > Identifier.label", + ]](node) { + if (isGoodName(node.name)) { + return; + } + report(node); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/capitalized-comments.js b/node_modules/eslint/lib/rules/capitalized-comments.js new file mode 100644 index 00000000..17c53fc8 --- /dev/null +++ b/node_modules/eslint/lib/rules/capitalized-comments.js @@ -0,0 +1,325 @@ +/** + * @fileoverview enforce or disallow capitalization of the first letter of a comment + * @author Kevin Partington + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN, + WHITESPACE = /\s/gu, + MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/u, // TODO: Combine w/ max-len pattern? + LETTER_PATTERN = /\p{L}/u; + +/* + * Base schema body for defining the basic capitalization rule, ignorePattern, + * and ignoreInlineComments values. + * This can be used in a few different ways in the actual schema. + */ +const SCHEMA_BODY = { + type: "object", + properties: { + ignorePattern: { + type: "string", + }, + ignoreInlineComments: { + type: "boolean", + }, + ignoreConsecutiveComments: { + type: "boolean", + }, + }, + additionalProperties: false, +}; +const DEFAULTS = { + ignorePattern: "", + ignoreInlineComments: false, + ignoreConsecutiveComments: false, +}; + +/** + * Get normalized options for either block or line comments from the given + * user-provided options. + * - If the user-provided options is just a string, returns a normalized + * set of options using default values for all other options. + * - If the user-provided options is an object, then a normalized option + * set is returned. Options specified in overrides will take priority + * over options specified in the main options object, which will in + * turn take priority over the rule's defaults. + * @param {Object|string} rawOptions The user-provided options. + * @param {string} which Either "line" or "block". + * @returns {Object} The normalized options. + */ +function getNormalizedOptions(rawOptions, which) { + return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions); +} + +/** + * Get normalized options for block and line comments. + * @param {Object|string} rawOptions The user-provided options. + * @returns {Object} An object with "Line" and "Block" keys and corresponding + * normalized options objects. + */ +function getAllNormalizedOptions(rawOptions = {}) { + return { + Line: getNormalizedOptions(rawOptions, "line"), + Block: getNormalizedOptions(rawOptions, "block"), + }; +} + +/** + * Creates a regular expression for each ignorePattern defined in the rule + * options. + * + * This is done in order to avoid invoking the RegExp constructor repeatedly. + * @param {Object} normalizedOptions The normalized rule options. + * @returns {void} + */ +function createRegExpForIgnorePatterns(normalizedOptions) { + Object.keys(normalizedOptions).forEach(key => { + const ignorePatternStr = normalizedOptions[key].ignorePattern; + + if (ignorePatternStr) { + const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`, "u"); + + normalizedOptions[key].ignorePatternRegExp = regExp; + } + }); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce or disallow capitalization of the first letter of a comment", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/capitalized-comments", + }, + + fixable: "code", + + schema: [ + { enum: ["always", "never"] }, + { + oneOf: [ + SCHEMA_BODY, + { + type: "object", + properties: { + line: SCHEMA_BODY, + block: SCHEMA_BODY, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + unexpectedLowercaseComment: + "Comments should not begin with a lowercase character.", + unexpectedUppercaseComment: + "Comments should not begin with an uppercase character.", + }, + }, + + create(context) { + const capitalize = context.options[0] || "always", + normalizedOptions = getAllNormalizedOptions(context.options[1]), + sourceCode = context.sourceCode; + + createRegExpForIgnorePatterns(normalizedOptions); + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks whether a comment is an inline comment. + * + * For the purpose of this rule, a comment is inline if: + * 1. The comment is preceded by a token on the same line; and + * 2. The command is followed by a token on the same line. + * + * Note that the comment itself need not be single-line! + * + * Also, it follows from this definition that only block comments can + * be considered as possibly inline. This is because line comments + * would consume any following tokens on the same line as the comment. + * @param {ASTNode} comment The comment node to check. + * @returns {boolean} True if the comment is an inline comment, false + * otherwise. + */ + function isInlineComment(comment) { + const previousToken = sourceCode.getTokenBefore(comment, { + includeComments: true, + }), + nextToken = sourceCode.getTokenAfter(comment, { + includeComments: true, + }); + + return Boolean( + previousToken && + nextToken && + comment.loc.start.line === previousToken.loc.end.line && + comment.loc.end.line === nextToken.loc.start.line, + ); + } + + /** + * Determine if a comment follows another comment. + * @param {ASTNode} comment The comment to check. + * @returns {boolean} True if the comment follows a valid comment. + */ + function isConsecutiveComment(comment) { + const previousTokenOrComment = sourceCode.getTokenBefore(comment, { + includeComments: true, + }); + + return Boolean( + previousTokenOrComment && + ["Block", "Line"].includes(previousTokenOrComment.type), + ); + } + + /** + * Check a comment to determine if it is valid for this rule. + * @param {ASTNode} comment The comment node to process. + * @param {Object} options The options for checking this comment. + * @returns {boolean} True if the comment is valid, false otherwise. + */ + function isCommentValid(comment, options) { + // 1. Check for default ignore pattern. + if (DEFAULT_IGNORE_PATTERN.test(comment.value)) { + return true; + } + + // 2. Check for custom ignore pattern. + const commentWithoutAsterisks = comment.value.replace(/\*/gu, ""); + + if ( + options.ignorePatternRegExp && + options.ignorePatternRegExp.test(commentWithoutAsterisks) + ) { + return true; + } + + // 3. Check for inline comments. + if (options.ignoreInlineComments && isInlineComment(comment)) { + return true; + } + + // 4. Is this a consecutive comment (and are we tolerating those)? + if ( + options.ignoreConsecutiveComments && + isConsecutiveComment(comment) + ) { + return true; + } + + // 5. Does the comment start with a possible URL? + if (MAYBE_URL.test(commentWithoutAsterisks)) { + return true; + } + + // 6. Is the initial word character a letter? + const commentWordCharsOnly = commentWithoutAsterisks.replace( + WHITESPACE, + "", + ); + + if (commentWordCharsOnly.length === 0) { + return true; + } + + // Get the first Unicode character (1 or 2 code units). + const [firstWordChar] = commentWordCharsOnly; + + if (!LETTER_PATTERN.test(firstWordChar)) { + return true; + } + + // 7. Check the case of the initial word character. + const isUppercase = + firstWordChar !== firstWordChar.toLocaleLowerCase(), + isLowercase = + firstWordChar !== firstWordChar.toLocaleUpperCase(); + + if (capitalize === "always" && isLowercase) { + return false; + } + if (capitalize === "never" && isUppercase) { + return false; + } + + return true; + } + + /** + * Process a comment to determine if it needs to be reported. + * @param {ASTNode} comment The comment node to process. + * @returns {void} + */ + function processComment(comment) { + const options = normalizedOptions[comment.type], + commentValid = isCommentValid(comment, options); + + if (!commentValid) { + const messageId = + capitalize === "always" + ? "unexpectedLowercaseComment" + : "unexpectedUppercaseComment"; + + context.report({ + node: null, // Intentionally using loc instead + loc: comment.loc, + messageId, + fix(fixer) { + const match = comment.value.match(LETTER_PATTERN); + const char = match[0]; + + // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*) + const charIndex = comment.range[0] + match.index + 2; + + return fixer.replaceTextRange( + [charIndex, charIndex + char.length], + capitalize === "always" + ? char.toLocaleUpperCase() + : char.toLocaleLowerCase(), + ); + }, + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments + .filter(token => token.type !== "Shebang") + .forEach(processComment); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/class-methods-use-this.js b/node_modules/eslint/lib/rules/class-methods-use-this.js new file mode 100644 index 00000000..5ce4893d --- /dev/null +++ b/node_modules/eslint/lib/rules/class-methods-use-this.js @@ -0,0 +1,250 @@ +/** + * @fileoverview Rule to enforce that all class methods use 'this'. + * @author Patrick Williams + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + defaultOptions: [ + { + enforceForClassFields: true, + exceptMethods: [], + ignoreOverrideMethods: false, + }, + ], + + docs: { + description: "Enforce that class methods utilize `this`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/class-methods-use-this", + }, + + schema: [ + { + type: "object", + properties: { + exceptMethods: { + type: "array", + items: { + type: "string", + }, + }, + enforceForClassFields: { + type: "boolean", + }, + ignoreOverrideMethods: { + type: "boolean", + }, + ignoreClassesWithImplements: { + enum: ["all", "public-fields"], + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingThis: "Expected 'this' to be used by class {{name}}.", + }, + }, + create(context) { + const [options] = context.options; + const { + enforceForClassFields, + ignoreOverrideMethods, + ignoreClassesWithImplements, + } = options; + const exceptMethods = new Set(options.exceptMethods); + + const stack = []; + + /** + * Push `this` used flag initialized with `false` onto the stack. + * @returns {void} + */ + function pushContext() { + stack.push(false); + } + + /** + * Pop `this` used flag from the stack. + * @returns {boolean | undefined} `this` used flag + */ + function popContext() { + return stack.pop(); + } + + /** + * Initializes the current context to false and pushes it onto the stack. + * These booleans represent whether 'this' has been used in the context. + * @returns {void} + * @private + */ + function enterFunction() { + pushContext(); + } + + /** + * Check if the node is an instance method + * @param {ASTNode} node node to check + * @returns {boolean} True if its an instance method + * @private + */ + function isInstanceMethod(node) { + switch (node.type) { + case "MethodDefinition": + return !node.static && node.kind !== "constructor"; + case "AccessorProperty": + case "PropertyDefinition": + return !node.static && enforceForClassFields; + default: + return false; + } + } + + /** + * Check if the node's parent class implements any interfaces + * @param {ASTNode} node node to check + * @returns {boolean} True if parent class implements interfaces + * @private + */ + function hasImplements(node) { + const classNode = node.parent.parent; + return ( + classNode?.type === "ClassDeclaration" && + classNode.implements?.length > 0 + ); + } + + /** + * Check if the node is an instance method not excluded by config + * @param {ASTNode} node node to check + * @returns {boolean} True if it is an instance method, and not excluded by config + * @private + */ + function isIncludedInstanceMethod(node) { + if (isInstanceMethod(node)) { + if (node.computed) { + return true; + } + + if (ignoreOverrideMethods && node.override) { + return false; + } + + if (ignoreClassesWithImplements) { + const implementsInterfaces = hasImplements(node); + if (implementsInterfaces) { + if ( + ignoreClassesWithImplements === "all" || + (ignoreClassesWithImplements === "public-fields" && + node.key.type !== "PrivateIdentifier" && + (!node.accessibility || + node.accessibility === "public")) + ) { + return false; + } + } + } + + const hashIfNeeded = + node.key.type === "PrivateIdentifier" ? "#" : ""; + const name = + node.key.type === "Literal" + ? astUtils.getStaticStringValue(node.key) + : node.key.name || ""; + + return !exceptMethods.has(hashIfNeeded + name); + } + return false; + } + + /** + * Checks if we are leaving a function that is a method, and reports if 'this' has not been used. + * Static methods and the constructor are exempt. + * Then pops the context off the stack. + * @param {ASTNode} node A function node that was entered. + * @returns {void} + * @private + */ + function exitFunction(node) { + const methodUsesThis = popContext(); + + if (isIncludedInstanceMethod(node.parent) && !methodUsesThis) { + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, context.sourceCode), + messageId: "missingThis", + data: { + name: astUtils.getFunctionNameWithKind(node), + }, + }); + } + } + + /** + * Mark the current context as having used 'this'. + * @returns {void} + * @private + */ + function markThisUsed() { + if (stack.length) { + stack[stack.length - 1] = true; + } + } + + return { + FunctionDeclaration: enterFunction, + "FunctionDeclaration:exit": exitFunction, + FunctionExpression: enterFunction, + "FunctionExpression:exit": exitFunction, + + /* + * Class field value are implicit functions. + */ + "AccessorProperty > *.key:exit": pushContext, + "AccessorProperty:exit": popContext, + "PropertyDefinition > *.key:exit": pushContext, + "PropertyDefinition:exit": popContext, + + /* + * Class static blocks are implicit functions. They aren't required to use `this`, + * but we have to push context so that it captures any use of `this` in the static block + * separately from enclosing contexts, because static blocks have their own `this` and it + * shouldn't count as used `this` in enclosing contexts. + */ + StaticBlock: pushContext, + "StaticBlock:exit": popContext, + + ThisExpression: markThisUsed, + Super: markThisUsed, + ...(enforceForClassFields && { + "AccessorProperty > ArrowFunctionExpression.value": + enterFunction, + "AccessorProperty > ArrowFunctionExpression.value:exit": + exitFunction, + "PropertyDefinition > ArrowFunctionExpression.value": + enterFunction, + "PropertyDefinition > ArrowFunctionExpression.value:exit": + exitFunction, + }), + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/comma-dangle.js b/node_modules/eslint/lib/rules/comma-dangle.js new file mode 100644 index 00000000..4ee91d45 --- /dev/null +++ b/node_modules/eslint/lib/rules/comma-dangle.js @@ -0,0 +1,424 @@ +/** + * @fileoverview Rule to forbid or enforce dangling commas. + * @author Ian Christian Myers + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_OPTIONS = Object.freeze({ + arrays: "never", + objects: "never", + imports: "never", + exports: "never", + functions: "never", +}); + +/** + * Checks whether or not a trailing comma is allowed in a given node. + * If the `lastItem` is `RestElement` or `RestProperty`, it disallows trailing commas. + * @param {ASTNode} lastItem The node of the last element in the given node. + * @returns {boolean} `true` if a trailing comma is allowed. + */ +function isTrailingCommaAllowed(lastItem) { + return !( + lastItem.type === "RestElement" || + lastItem.type === "RestProperty" || + lastItem.type === "ExperimentalRestProperty" + ); +} + +/** + * Normalize option value. + * @param {string|Object|undefined} optionValue The 1st option value to normalize. + * @param {number} ecmaVersion The normalized ECMAScript version. + * @returns {Object} The normalized option value. + */ +function normalizeOptions(optionValue, ecmaVersion) { + if (typeof optionValue === "string") { + return { + arrays: optionValue, + objects: optionValue, + imports: optionValue, + exports: optionValue, + functions: ecmaVersion < 2017 ? "ignore" : optionValue, + }; + } + if (typeof optionValue === "object" && optionValue !== null) { + return { + arrays: optionValue.arrays || DEFAULT_OPTIONS.arrays, + objects: optionValue.objects || DEFAULT_OPTIONS.objects, + imports: optionValue.imports || DEFAULT_OPTIONS.imports, + exports: optionValue.exports || DEFAULT_OPTIONS.exports, + functions: optionValue.functions || DEFAULT_OPTIONS.functions, + }; + } + + return DEFAULT_OPTIONS; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "comma-dangle", + url: "https://eslint.style/rules/js/comma-dangle", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow trailing commas", + recommended: false, + url: "https://eslint.org/docs/latest/rules/comma-dangle", + }, + + fixable: "code", + + schema: { + definitions: { + value: { + enum: [ + "always-multiline", + "always", + "never", + "only-multiline", + ], + }, + valueWithIgnore: { + enum: [ + "always-multiline", + "always", + "ignore", + "never", + "only-multiline", + ], + }, + }, + type: "array", + items: [ + { + oneOf: [ + { + $ref: "#/definitions/value", + }, + { + type: "object", + properties: { + arrays: { + $ref: "#/definitions/valueWithIgnore", + }, + objects: { + $ref: "#/definitions/valueWithIgnore", + }, + imports: { + $ref: "#/definitions/valueWithIgnore", + }, + exports: { + $ref: "#/definitions/valueWithIgnore", + }, + functions: { + $ref: "#/definitions/valueWithIgnore", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + additionalItems: false, + }, + + messages: { + unexpected: "Unexpected trailing comma.", + missing: "Missing trailing comma.", + }, + }, + + create(context) { + const options = normalizeOptions( + context.options[0], + context.languageOptions.ecmaVersion, + ); + + const sourceCode = context.sourceCode; + + /** + * Gets the last item of the given node. + * @param {ASTNode} node The node to get. + * @returns {ASTNode|null} The last node or null. + */ + function getLastItem(node) { + /** + * Returns the last element of an array + * @param {any[]} array The input array + * @returns {any} The last element + */ + function last(array) { + return array.at(-1); + } + + switch (node.type) { + case "ObjectExpression": + case "ObjectPattern": + return last(node.properties); + case "ArrayExpression": + case "ArrayPattern": + return last(node.elements); + case "ImportDeclaration": + case "ExportNamedDeclaration": + return last(node.specifiers); + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + return last(node.params); + case "CallExpression": + case "NewExpression": + return last(node.arguments); + default: + return null; + } + } + + /** + * Gets the trailing comma token of the given node. + * If the trailing comma does not exist, this returns the token which is + * the insertion point of the trailing comma token. + * @param {ASTNode} node The node to get. + * @param {ASTNode} lastItem The last item of the node. + * @returns {Token} The trailing comma token or the insertion point. + */ + function getTrailingToken(node, lastItem) { + switch (node.type) { + case "ObjectExpression": + case "ArrayExpression": + case "CallExpression": + case "NewExpression": + return sourceCode.getLastToken(node, 1); + default: { + const nextToken = sourceCode.getTokenAfter(lastItem); + + if (astUtils.isCommaToken(nextToken)) { + return nextToken; + } + return sourceCode.getLastToken(lastItem); + } + } + } + + /** + * Checks whether or not a given node is multiline. + * This rule handles a given node as multiline when the closing parenthesis + * and the last element are not on the same line. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is multiline. + */ + function isMultiline(node) { + const lastItem = getLastItem(node); + + if (!lastItem) { + return false; + } + + const penultimateToken = getTrailingToken(node, lastItem); + const lastToken = sourceCode.getTokenAfter(penultimateToken); + + return lastToken.loc.end.line !== penultimateToken.loc.end.line; + } + + /** + * Reports a trailing comma if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function forbidTrailingComma(node) { + const lastItem = getLastItem(node); + + if ( + !lastItem || + (node.type === "ImportDeclaration" && + lastItem.type !== "ImportSpecifier") + ) { + return; + } + + const trailingToken = getTrailingToken(node, lastItem); + + if (astUtils.isCommaToken(trailingToken)) { + context.report({ + node: lastItem, + loc: trailingToken.loc, + messageId: "unexpected", + *fix(fixer) { + yield fixer.remove(trailingToken); + + /* + * Extend the range of the fix to include surrounding tokens to ensure + * that the element after which the comma is removed stays _last_. + * This intentionally makes conflicts in fix ranges with rules that may be + * adding or removing elements in the same autofix pass. + * https://github.com/eslint/eslint/issues/15660 + */ + yield fixer.insertTextBefore( + sourceCode.getTokenBefore(trailingToken), + "", + ); + yield fixer.insertTextAfter( + sourceCode.getTokenAfter(trailingToken), + "", + ); + }, + }); + } + } + + /** + * Reports the last element of a given node if it does not have a trailing + * comma. + * + * If a given node is `ArrayPattern` which has `RestElement`, the trailing + * comma is disallowed, so report if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function forceTrailingComma(node) { + const lastItem = getLastItem(node); + + if ( + !lastItem || + (node.type === "ImportDeclaration" && + lastItem.type !== "ImportSpecifier") + ) { + return; + } + if (!isTrailingCommaAllowed(lastItem)) { + forbidTrailingComma(node); + return; + } + + const trailingToken = getTrailingToken(node, lastItem); + + if (trailingToken.value !== ",") { + context.report({ + node: lastItem, + loc: { + start: trailingToken.loc.end, + end: astUtils.getNextLocation( + sourceCode, + trailingToken.loc.end, + ), + }, + messageId: "missing", + *fix(fixer) { + yield fixer.insertTextAfter(trailingToken, ","); + + /* + * Extend the range of the fix to include surrounding tokens to ensure + * that the element after which the comma is inserted stays _last_. + * This intentionally makes conflicts in fix ranges with rules that may be + * adding or removing elements in the same autofix pass. + * https://github.com/eslint/eslint/issues/15660 + */ + yield fixer.insertTextBefore(trailingToken, ""); + yield fixer.insertTextAfter( + sourceCode.getTokenAfter(trailingToken), + "", + ); + }, + }); + } + } + + /** + * If a given node is multiline, reports the last element of a given node + * when it does not have a trailing comma. + * Otherwise, reports a trailing comma if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function forceTrailingCommaIfMultiline(node) { + if (isMultiline(node)) { + forceTrailingComma(node); + } else { + forbidTrailingComma(node); + } + } + + /** + * Only if a given node is not multiline, reports the last element of a given node + * when it does not have a trailing comma. + * Otherwise, reports a trailing comma if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function allowTrailingCommaIfMultiline(node) { + if (!isMultiline(node)) { + forbidTrailingComma(node); + } + } + + const predicate = { + always: forceTrailingComma, + "always-multiline": forceTrailingCommaIfMultiline, + "only-multiline": allowTrailingCommaIfMultiline, + never: forbidTrailingComma, + ignore() {}, + }; + + return { + ObjectExpression: predicate[options.objects], + ObjectPattern: predicate[options.objects], + + ArrayExpression: predicate[options.arrays], + ArrayPattern: predicate[options.arrays], + + ImportDeclaration: predicate[options.imports], + + ExportNamedDeclaration: predicate[options.exports], + + FunctionDeclaration: predicate[options.functions], + FunctionExpression: predicate[options.functions], + ArrowFunctionExpression: predicate[options.functions], + CallExpression: predicate[options.functions], + NewExpression: predicate[options.functions], + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/comma-spacing.js b/node_modules/eslint/lib/rules/comma-spacing.js new file mode 100644 index 00000000..4cdd2a64 --- /dev/null +++ b/node_modules/eslint/lib/rules/comma-spacing.js @@ -0,0 +1,208 @@ +/** + * @fileoverview Comma spacing - validates spacing before and after comma + * @author Vignesh Anand aka vegetableman. + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "comma-spacing", + url: "https://eslint.style/rules/js/comma-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing before and after commas", + recommended: false, + url: "https://eslint.org/docs/latest/rules/comma-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { + type: "boolean", + default: false, + }, + after: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missing: "A space is required {{loc}} ','.", + unexpected: "There should be no space {{loc}} ','.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const tokensAndComments = sourceCode.tokensAndComments; + + const options = { + before: context.options[0] ? context.options[0].before : false, + after: context.options[0] ? context.options[0].after : true, + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // list of comma tokens to ignore for the check of leading whitespace + const commaTokensToIgnore = []; + + /** + * Reports a spacing error with an appropriate message. + * @param {ASTNode} node The binary expression node to report. + * @param {string} loc Is the error "before" or "after" the comma? + * @param {ASTNode} otherNode The node at the left or right of `node` + * @returns {void} + * @private + */ + function report(node, loc, otherNode) { + context.report({ + node, + fix(fixer) { + if (options[loc]) { + if (loc === "before") { + return fixer.insertTextBefore(node, " "); + } + return fixer.insertTextAfter(node, " "); + } + let start, end; + const newText = ""; + + if (loc === "before") { + start = otherNode.range[1]; + end = node.range[0]; + } else { + start = node.range[1]; + end = otherNode.range[0]; + } + + return fixer.replaceTextRange([start, end], newText); + }, + messageId: options[loc] ? "missing" : "unexpected", + data: { + loc, + }, + }); + } + + /** + * Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list. + * @param {ASTNode} node An ArrayExpression or ArrayPattern node. + * @returns {void} + */ + function addNullElementsToIgnoreList(node) { + let previousToken = sourceCode.getFirstToken(node); + + node.elements.forEach(element => { + let token; + + if (element === null) { + token = sourceCode.getTokenAfter(previousToken); + + if (astUtils.isCommaToken(token)) { + commaTokensToIgnore.push(token); + } + } else { + token = sourceCode.getTokenAfter(element); + } + + previousToken = token; + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program:exit"() { + tokensAndComments.forEach((token, i) => { + if (!astUtils.isCommaToken(token)) { + return; + } + + const previousToken = tokensAndComments[i - 1]; + const nextToken = tokensAndComments[i + 1]; + + if ( + previousToken && + !astUtils.isCommaToken(previousToken) && // ignore spacing between two commas + /* + * `commaTokensToIgnore` are ending commas of `null` elements (array holes/elisions). + * In addition to spacing between two commas, this can also ignore: + * + * - Spacing after `[` (controlled by array-bracket-spacing) + * Example: [ , ] + * ^ + * - Spacing after a comment (for backwards compatibility, this was possibly unintentional) + * Example: [a, /* * / ,] + * ^ + */ + !commaTokensToIgnore.includes(token) && + astUtils.isTokenOnSameLine(previousToken, token) && + options.before !== + sourceCode.isSpaceBetweenTokens( + previousToken, + token, + ) + ) { + report(token, "before", previousToken); + } + + if ( + nextToken && + !astUtils.isCommaToken(nextToken) && // ignore spacing between two commas + !astUtils.isClosingParenToken(nextToken) && // controlled by space-in-parens + !astUtils.isClosingBracketToken(nextToken) && // controlled by array-bracket-spacing + !astUtils.isClosingBraceToken(nextToken) && // controlled by object-curly-spacing + !(!options.after && nextToken.type === "Line") && // special case, allow space before line comment + astUtils.isTokenOnSameLine(token, nextToken) && + options.after !== + sourceCode.isSpaceBetweenTokens(token, nextToken) + ) { + report(token, "after", nextToken); + } + }); + }, + ArrayExpression: addNullElementsToIgnoreList, + ArrayPattern: addNullElementsToIgnoreList, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/comma-style.js b/node_modules/eslint/lib/rules/comma-style.js new file mode 100644 index 00000000..e96c151f --- /dev/null +++ b/node_modules/eslint/lib/rules/comma-style.js @@ -0,0 +1,391 @@ +/** + * @fileoverview Comma style - enforces comma styles of two types: last and first + * @author Vignesh Anand aka vegetableman + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "comma-style", + url: "https://eslint.style/rules/js/comma-style", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent comma style", + recommended: false, + url: "https://eslint.org/docs/latest/rules/comma-style", + }, + + fixable: "code", + + schema: [ + { + enum: ["first", "last"], + }, + { + type: "object", + properties: { + exceptions: { + type: "object", + additionalProperties: { + type: "boolean", + }, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedLineBeforeAndAfterComma: + "Bad line breaking before and after ','.", + expectedCommaFirst: "',' should be placed first.", + expectedCommaLast: "',' should be placed last.", + }, + }, + + create(context) { + const style = context.options[0] || "last", + sourceCode = context.sourceCode; + const exceptions = { + ArrayPattern: true, + ArrowFunctionExpression: true, + CallExpression: true, + FunctionDeclaration: true, + FunctionExpression: true, + ImportDeclaration: true, + ObjectPattern: true, + NewExpression: true, + }; + + if ( + context.options.length === 2 && + Object.hasOwn(context.options[1], "exceptions") + ) { + const keys = Object.keys(context.options[1].exceptions); + + for (let i = 0; i < keys.length; i++) { + exceptions[keys[i]] = context.options[1].exceptions[keys[i]]; + } + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Modified text based on the style + * @param {string} styleType Style type + * @param {string} text Source code text + * @returns {string} modified text + * @private + */ + function getReplacedText(styleType, text) { + switch (styleType) { + case "between": + return `,${text.replace(astUtils.LINEBREAK_MATCHER, "")}`; + + case "first": + return `${text},`; + + case "last": + return `,${text}`; + + default: + return ""; + } + } + + /** + * Determines the fixer function for a given style. + * @param {string} styleType comma style + * @param {ASTNode} previousItemToken The token to check. + * @param {ASTNode} commaToken The token to check. + * @param {ASTNode} currentItemToken The token to check. + * @returns {Function} Fixer function + * @private + */ + function getFixerFunction( + styleType, + previousItemToken, + commaToken, + currentItemToken, + ) { + const text = + sourceCode.text.slice( + previousItemToken.range[1], + commaToken.range[0], + ) + + sourceCode.text.slice( + commaToken.range[1], + currentItemToken.range[0], + ); + const range = [ + previousItemToken.range[1], + currentItemToken.range[0], + ]; + + return function (fixer) { + return fixer.replaceTextRange( + range, + getReplacedText(styleType, text), + ); + }; + } + + /** + * Validates the spacing around single items in lists. + * @param {Token} previousItemToken The last token from the previous item. + * @param {Token} commaToken The token representing the comma. + * @param {Token} currentItemToken The first token of the current item. + * @param {Token} reportItem The item to use when reporting an error. + * @returns {void} + * @private + */ + function validateCommaItemSpacing( + previousItemToken, + commaToken, + currentItemToken, + reportItem, + ) { + // if single line + if ( + astUtils.isTokenOnSameLine(commaToken, currentItemToken) && + astUtils.isTokenOnSameLine(previousItemToken, commaToken) + ) { + // do nothing. + } else if ( + !astUtils.isTokenOnSameLine(commaToken, currentItemToken) && + !astUtils.isTokenOnSameLine(previousItemToken, commaToken) + ) { + const comment = sourceCode.getCommentsAfter(commaToken)[0]; + const styleType = + comment && + comment.type === "Block" && + astUtils.isTokenOnSameLine(commaToken, comment) + ? style + : "between"; + + // lone comma + context.report({ + node: reportItem, + loc: commaToken.loc, + messageId: "unexpectedLineBeforeAndAfterComma", + fix: getFixerFunction( + styleType, + previousItemToken, + commaToken, + currentItemToken, + ), + }); + } else if ( + style === "first" && + !astUtils.isTokenOnSameLine(commaToken, currentItemToken) + ) { + context.report({ + node: reportItem, + loc: commaToken.loc, + messageId: "expectedCommaFirst", + fix: getFixerFunction( + style, + previousItemToken, + commaToken, + currentItemToken, + ), + }); + } else if ( + style === "last" && + astUtils.isTokenOnSameLine(commaToken, currentItemToken) + ) { + context.report({ + node: reportItem, + loc: commaToken.loc, + messageId: "expectedCommaLast", + fix: getFixerFunction( + style, + previousItemToken, + commaToken, + currentItemToken, + ), + }); + } + } + + /** + * Checks the comma placement with regards to a declaration/property/element + * @param {ASTNode} node The binary expression node to check + * @param {string} property The property of the node containing child nodes. + * @private + * @returns {void} + */ + function validateComma(node, property) { + const items = node[property], + arrayLiteral = + node.type === "ArrayExpression" || + node.type === "ArrayPattern"; + + if (items.length > 1 || arrayLiteral) { + // seed as opening [ + let previousItemToken = sourceCode.getFirstToken(node); + + items.forEach(item => { + const commaToken = item + ? sourceCode.getTokenBefore(item) + : previousItemToken, + currentItemToken = item + ? sourceCode.getFirstToken(item) + : sourceCode.getTokenAfter(commaToken), + reportItem = item || currentItemToken; + + /* + * This works by comparing three token locations: + * - previousItemToken is the last token of the previous item + * - commaToken is the location of the comma before the current item + * - currentItemToken is the first token of the current item + * + * These values get switched around if item is undefined. + * previousItemToken will refer to the last token not belonging + * to the current item, which could be a comma or an opening + * square bracket. currentItemToken could be a comma. + * + * All comparisons are done based on these tokens directly, so + * they are always valid regardless of an undefined item. + */ + if (astUtils.isCommaToken(commaToken)) { + validateCommaItemSpacing( + previousItemToken, + commaToken, + currentItemToken, + reportItem, + ); + } + + if (item) { + const tokenAfterItem = sourceCode.getTokenAfter( + item, + astUtils.isNotClosingParenToken, + ); + + previousItemToken = tokenAfterItem + ? sourceCode.getTokenBefore(tokenAfterItem) + : sourceCode.ast.tokens.at(-1); + } else { + previousItemToken = currentItemToken; + } + }); + + /* + * Special case for array literals that have empty last items, such + * as [ 1, 2, ]. These arrays only have two items show up in the + * AST, so we need to look at the token to verify that there's no + * dangling comma. + */ + if (arrayLiteral) { + const lastToken = sourceCode.getLastToken(node), + nextToLastToken = sourceCode.getTokenBefore(lastToken); + + if (astUtils.isCommaToken(nextToLastToken)) { + validateCommaItemSpacing( + sourceCode.getTokenBefore(nextToLastToken), + nextToLastToken, + lastToken, + lastToken, + ); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + const nodes = {}; + + if (!exceptions.VariableDeclaration) { + nodes.VariableDeclaration = function (node) { + validateComma(node, "declarations"); + }; + } + if (!exceptions.ObjectExpression) { + nodes.ObjectExpression = function (node) { + validateComma(node, "properties"); + }; + } + if (!exceptions.ObjectPattern) { + nodes.ObjectPattern = function (node) { + validateComma(node, "properties"); + }; + } + if (!exceptions.ArrayExpression) { + nodes.ArrayExpression = function (node) { + validateComma(node, "elements"); + }; + } + if (!exceptions.ArrayPattern) { + nodes.ArrayPattern = function (node) { + validateComma(node, "elements"); + }; + } + if (!exceptions.FunctionDeclaration) { + nodes.FunctionDeclaration = function (node) { + validateComma(node, "params"); + }; + } + if (!exceptions.FunctionExpression) { + nodes.FunctionExpression = function (node) { + validateComma(node, "params"); + }; + } + if (!exceptions.ArrowFunctionExpression) { + nodes.ArrowFunctionExpression = function (node) { + validateComma(node, "params"); + }; + } + if (!exceptions.CallExpression) { + nodes.CallExpression = function (node) { + validateComma(node, "arguments"); + }; + } + if (!exceptions.ImportDeclaration) { + nodes.ImportDeclaration = function (node) { + validateComma(node, "specifiers"); + }; + } + if (!exceptions.NewExpression) { + nodes.NewExpression = function (node) { + validateComma(node, "arguments"); + }; + } + + return nodes; + }, +}; diff --git a/node_modules/eslint/lib/rules/complexity.js b/node_modules/eslint/lib/rules/complexity.js new file mode 100644 index 00000000..acab4126 --- /dev/null +++ b/node_modules/eslint/lib/rules/complexity.js @@ -0,0 +1,196 @@ +/** + * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity. + * Counts the number of if, conditional, for, while, try, switch/case, + * @author Patrick Brosset + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const THRESHOLD_DEFAULT = 20; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [THRESHOLD_DEFAULT], + + docs: { + description: + "Enforce a maximum cyclomatic complexity allowed in a program", + recommended: false, + url: "https://eslint.org/docs/latest/rules/complexity", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + variant: { + enum: ["classic", "modified"], + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + complex: + "{{name}} has a complexity of {{complexity}}. Maximum allowed is {{max}}.", + }, + }, + + create(context) { + const option = context.options[0]; + let threshold = THRESHOLD_DEFAULT; + let VARIANT = "classic"; + + if (typeof option === "object") { + if ( + Object.hasOwn(option, "maximum") || + Object.hasOwn(option, "max") + ) { + threshold = option.maximum || option.max; + } + + if (Object.hasOwn(option, "variant")) { + VARIANT = option.variant; + } + } else if (typeof option === "number") { + threshold = option; + } + + const IS_MODIFIED_COMPLEXITY = VARIANT === "modified"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // Using a stack to store complexity per code path + const complexities = []; + + /** + * Increase the complexity of the code path in context + * @returns {void} + * @private + */ + function increaseComplexity() { + complexities[complexities.length - 1]++; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + onCodePathStart() { + // The initial complexity is 1, representing one execution path in the CodePath + complexities.push(1); + }, + + // Each branching in the code adds 1 to the complexity + CatchClause: increaseComplexity, + ConditionalExpression: increaseComplexity, + LogicalExpression: increaseComplexity, + ForStatement: increaseComplexity, + ForInStatement: increaseComplexity, + ForOfStatement: increaseComplexity, + IfStatement: increaseComplexity, + WhileStatement: increaseComplexity, + DoWhileStatement: increaseComplexity, + AssignmentPattern: increaseComplexity, + + // Avoid `default` + "SwitchCase[test]": () => + IS_MODIFIED_COMPLEXITY || increaseComplexity(), + SwitchStatement: () => + IS_MODIFIED_COMPLEXITY && increaseComplexity(), + + // Logical assignment operators have short-circuiting behavior + AssignmentExpression(node) { + if (astUtils.isLogicalAssignmentOperator(node.operator)) { + increaseComplexity(); + } + }, + + MemberExpression(node) { + if (node.optional === true) { + increaseComplexity(); + } + }, + + CallExpression(node) { + if (node.optional === true) { + increaseComplexity(); + } + }, + + onCodePathEnd(codePath, node) { + const complexity = complexities.pop(); + + /* + * This rule only evaluates complexity of functions, so "program" is excluded. + * Class field initializers and class static blocks are implicit functions. Therefore, + * they shouldn't contribute to the enclosing function's complexity, but their + * own complexity should be evaluated. + */ + if ( + codePath.origin !== "function" && + codePath.origin !== "class-field-initializer" && + codePath.origin !== "class-static-block" + ) { + return; + } + + if (complexity > threshold) { + let name; + + if (codePath.origin === "class-field-initializer") { + name = "class field initializer"; + } else if (codePath.origin === "class-static-block") { + name = "class static block"; + } else { + name = astUtils.getFunctionNameWithKind(node); + } + + context.report({ + node, + messageId: "complex", + data: { + name: upperCaseFirst(name), + complexity, + max: threshold, + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/computed-property-spacing.js b/node_modules/eslint/lib/rules/computed-property-spacing.js new file mode 100644 index 00000000..55cbba0c --- /dev/null +++ b/node_modules/eslint/lib/rules/computed-property-spacing.js @@ -0,0 +1,251 @@ +/** + * @fileoverview Disallows or enforces spaces inside computed properties. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "computed-property-spacing", + url: "https://eslint.style/rules/js/computed-property-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing inside computed property brackets", + recommended: false, + url: "https://eslint.org/docs/latest/rules/computed-property-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + enforceForClassMembers: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedSpaceBefore: + "There should be no space before '{{tokenValue}}'.", + unexpectedSpaceAfter: + "There should be no space after '{{tokenValue}}'.", + + missingSpaceBefore: "A space is required before '{{tokenValue}}'.", + missingSpaceAfter: "A space is required after '{{tokenValue}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never" + const enforceForClassMembers = + !context.options[1] || context.options[1].enforceForClassMembers; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @param {Token} tokenAfter The token after `token`. + * @returns {void} + */ + function reportNoBeginningSpace(node, token, tokenAfter) { + context.report({ + node, + loc: { start: token.loc.end, end: tokenAfter.loc.start }, + messageId: "unexpectedSpaceAfter", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + token.range[1], + tokenAfter.range[0], + ]); + }, + }); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @param {Token} tokenBefore The token before `token`. + * @returns {void} + */ + function reportNoEndingSpace(node, token, tokenBefore) { + context.report({ + node, + loc: { start: tokenBefore.loc.end, end: token.loc.start }, + messageId: "unexpectedSpaceBefore", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + tokenBefore.range[1], + token.range[0], + ]); + }, + }); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceAfter", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceBefore", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + + /** + * Returns a function that checks the spacing of a node on the property name + * that was passed in. + * @param {string} propertyName The property on the node to check for spacing + * @returns {Function} A function that will check spacing on a node + */ + function checkSpacing(propertyName) { + return function (node) { + if (!node.computed) { + return; + } + + const property = node[propertyName]; + + const before = sourceCode.getTokenBefore( + property, + astUtils.isOpeningBracketToken, + ), + first = sourceCode.getTokenAfter(before, { + includeComments: true, + }), + after = sourceCode.getTokenAfter( + property, + astUtils.isClosingBracketToken, + ), + last = sourceCode.getTokenBefore(after, { + includeComments: true, + }); + + if (astUtils.isTokenOnSameLine(before, first)) { + if (propertyNameMustBeSpaced) { + if ( + !sourceCode.isSpaceBetweenTokens(before, first) && + astUtils.isTokenOnSameLine(before, first) + ) { + reportRequiredBeginningSpace(node, before); + } + } else { + if (sourceCode.isSpaceBetweenTokens(before, first)) { + reportNoBeginningSpace(node, before, first); + } + } + } + + if (astUtils.isTokenOnSameLine(last, after)) { + if (propertyNameMustBeSpaced) { + if ( + !sourceCode.isSpaceBetweenTokens(last, after) && + astUtils.isTokenOnSameLine(last, after) + ) { + reportRequiredEndingSpace(node, after); + } + } else { + if (sourceCode.isSpaceBetweenTokens(last, after)) { + reportNoEndingSpace(node, after, last); + } + } + } + }; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + const listeners = { + Property: checkSpacing("key"), + MemberExpression: checkSpacing("property"), + }; + + if (enforceForClassMembers) { + listeners.MethodDefinition = listeners.PropertyDefinition = + listeners.Property; + } + + return listeners; + }, +}; diff --git a/node_modules/eslint/lib/rules/consistent-return.js b/node_modules/eslint/lib/rules/consistent-return.js new file mode 100644 index 00000000..6407739b --- /dev/null +++ b/node_modules/eslint/lib/rules/consistent-return.js @@ -0,0 +1,221 @@ +/** + * @fileoverview Rule to flag consistent return values + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks all segments in a set and returns true if all are unreachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if all segments are unreachable; false otherwise. + */ +function areAllSegmentsUnreachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return false; + } + } + + return true; +} + +/** + * Checks whether a given node is a `constructor` method in an ES6 class + * @param {ASTNode} node A node to check + * @returns {boolean} `true` if the node is a `constructor` method + */ +function isClassConstructor(node) { + return ( + node.type === "FunctionExpression" && + node.parent && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor" + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require `return` statements to either always or never specify values", + recommended: false, + url: "https://eslint.org/docs/latest/rules/consistent-return", + }, + + schema: [ + { + type: "object", + properties: { + treatUndefinedAsUnspecified: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [{ treatUndefinedAsUnspecified: false }], + + messages: { + missingReturn: "Expected to return a value at the end of {{name}}.", + missingReturnValue: "{{name}} expected a return value.", + unexpectedReturnValue: "{{name}} expected no return value.", + }, + }, + + create(context) { + const [{ treatUndefinedAsUnspecified }] = context.options; + let funcInfo = null; + + /** + * Checks whether of not the implicit returning is consistent if the last + * code path segment is reachable. + * @param {ASTNode} node A program/function node to check. + * @returns {void} + */ + function checkLastSegment(node) { + let loc, name; + + /* + * Skip if it expected no return value or unreachable. + * When unreachable, all paths are returned or thrown. + */ + if ( + !funcInfo.hasReturnValue || + areAllSegmentsUnreachable(funcInfo.currentSegments) || + astUtils.isES5Constructor(node) || + isClassConstructor(node) + ) { + return; + } + + // Adjust a location and a message. + if (node.type === "Program") { + // The head of program. + loc = { line: 1, column: 0 }; + name = "program"; + } else if (node.type === "ArrowFunctionExpression") { + // `=>` token + loc = context.sourceCode.getTokenBefore( + node.body, + astUtils.isArrowToken, + ).loc; + } else if ( + node.parent.type === "MethodDefinition" || + (node.parent.type === "Property" && node.parent.method) + ) { + // Method name. + loc = node.parent.key.loc; + } else { + // Function name or `function` keyword. + loc = (node.id || context.sourceCode.getFirstToken(node)).loc; + } + + if (!name) { + name = astUtils.getFunctionNameWithKind(node); + } + + // Reports. + context.report({ + node, + loc, + messageId: "missingReturn", + data: { name }, + }); + } + + return { + // Initializes/Disposes state of each code path. + onCodePathStart(codePath, node) { + funcInfo = { + upper: funcInfo, + codePath, + hasReturn: false, + hasReturnValue: false, + messageId: "", + node, + currentSegments: new Set(), + }; + }, + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + // Reports a given return statement if it's inconsistent. + ReturnStatement(node) { + const argument = node.argument; + let hasReturnValue = Boolean(argument); + + if (treatUndefinedAsUnspecified && hasReturnValue) { + hasReturnValue = + !astUtils.isSpecificId(argument, "undefined") && + argument.operator !== "void"; + } + + if (!funcInfo.hasReturn) { + funcInfo.hasReturn = true; + funcInfo.hasReturnValue = hasReturnValue; + funcInfo.messageId = hasReturnValue + ? "missingReturnValue" + : "unexpectedReturnValue"; + funcInfo.data = { + name: + funcInfo.node.type === "Program" + ? "Program" + : upperCaseFirst( + astUtils.getFunctionNameWithKind( + funcInfo.node, + ), + ), + }; + } else if (funcInfo.hasReturnValue !== hasReturnValue) { + context.report({ + node, + messageId: funcInfo.messageId, + data: funcInfo.data, + }); + } + }, + + // Reports a given program/function if the implicit returning is not consistent. + "Program:exit": checkLastSegment, + "FunctionDeclaration:exit": checkLastSegment, + "FunctionExpression:exit": checkLastSegment, + "ArrowFunctionExpression:exit": checkLastSegment, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/consistent-this.js b/node_modules/eslint/lib/rules/consistent-this.js new file mode 100644 index 00000000..8e9372d2 --- /dev/null +++ b/node_modules/eslint/lib/rules/consistent-this.js @@ -0,0 +1,179 @@ +/** + * @fileoverview Rule to enforce consistent naming of "this" context variables + * @author Raphael Pigulla + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce consistent naming when capturing the current execution context", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/consistent-this", + }, + + schema: { + type: "array", + items: { + type: "string", + minLength: 1, + }, + uniqueItems: true, + }, + + defaultOptions: ["that"], + + messages: { + aliasNotAssignedToThis: + "Designated alias '{{name}}' is not assigned to 'this'.", + unexpectedAlias: "Unexpected alias '{{name}}' for 'this'.", + }, + }, + + create(context) { + const aliases = context.options; + const sourceCode = context.sourceCode; + + /** + * Reports that a variable declarator or assignment expression is assigning + * a non-'this' value to the specified alias. + * @param {ASTNode} node The assigning node. + * @param {string} name the name of the alias that was incorrectly used. + * @returns {void} + */ + function reportBadAssignment(node, name) { + context.report({ + node, + messageId: "aliasNotAssignedToThis", + data: { name }, + }); + } + + /** + * Checks that an assignment to an identifier only assigns 'this' to the + * appropriate alias, and the alias is only assigned to 'this'. + * @param {ASTNode} node The assigning node. + * @param {Identifier} name The name of the variable assigned to. + * @param {Expression} value The value of the assignment. + * @returns {void} + */ + function checkAssignment(node, name, value) { + const isThis = value.type === "ThisExpression"; + + if (aliases.includes(name)) { + if (!isThis || (node.operator && node.operator !== "=")) { + reportBadAssignment(node, name); + } + } else if (isThis) { + context.report({ + node, + messageId: "unexpectedAlias", + data: { name }, + }); + } + } + + /** + * Ensures that a variable declaration of the alias in a program or function + * is assigned to the correct value. + * @param {string} alias alias the check the assignment of. + * @param {Object} scope scope of the current code we are checking. + * @private + * @returns {void} + */ + function checkWasAssigned(alias, scope) { + const variable = scope.set.get(alias); + + if (!variable) { + return; + } + + if ( + variable.defs.some( + def => + def.node.type === "VariableDeclarator" && + def.node.init !== null, + ) + ) { + return; + } + + /* + * The alias has been declared and not assigned: check it was + * assigned later in the same scope. + */ + if ( + !variable.references.some(reference => { + const write = reference.writeExpr; + + return ( + reference.from === scope && + write && + write.type === "ThisExpression" && + write.parent.operator === "=" + ); + }) + ) { + variable.defs + .map(def => def.node) + .forEach(node => { + reportBadAssignment(node, alias); + }); + } + } + + /** + * Check each alias to ensure that is was assigned to the correct value. + * @param {ASTNode} node The node that represents the scope to check. + * @returns {void} + */ + function ensureWasAssigned(node) { + const scope = sourceCode.getScope(node); + + // if this is program scope we also need to check module scope + const extraScope = + node.type === "Program" && node.sourceType === "module" + ? scope.childScopes[0] + : null; + + aliases.forEach(alias => { + checkWasAssigned(alias, scope); + + if (extraScope) { + checkWasAssigned(alias, extraScope); + } + }); + } + + return { + "Program:exit": ensureWasAssigned, + "FunctionExpression:exit": ensureWasAssigned, + "FunctionDeclaration:exit": ensureWasAssigned, + + VariableDeclarator(node) { + const id = node.id; + const isDestructuring = + id.type === "ArrayPattern" || id.type === "ObjectPattern"; + + if (node.init !== null && !isDestructuring) { + checkAssignment(node, id.name, node.init); + } + }, + + AssignmentExpression(node) { + if (node.left.type === "Identifier") { + checkAssignment(node, node.left.name, node.right); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/constructor-super.js b/node_modules/eslint/lib/rules/constructor-super.js new file mode 100644 index 00000000..2262677d --- /dev/null +++ b/node_modules/eslint/lib/rules/constructor-super.js @@ -0,0 +1,453 @@ +/** + * @fileoverview A rule to verify `super()` callings in constructor. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a constructor. + * @param {ASTNode} node A node to check. This node type is one of + * `Program`, `FunctionDeclaration`, `FunctionExpression`, and + * `ArrowFunctionExpression`. + * @returns {boolean} `true` if the node is a constructor. + */ +function isConstructorFunction(node) { + return ( + node.type === "FunctionExpression" && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor" + ); +} + +/** + * Checks whether a given node can be a constructor or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node can be a constructor. + */ +function isPossibleConstructor(node) { + if (!node) { + return false; + } + + switch (node.type) { + case "ClassExpression": + case "FunctionExpression": + case "ThisExpression": + case "MemberExpression": + case "CallExpression": + case "NewExpression": + case "ChainExpression": + case "YieldExpression": + case "TaggedTemplateExpression": + case "MetaProperty": + return true; + + case "Identifier": + return node.name !== "undefined"; + + case "AssignmentExpression": + if (["=", "&&="].includes(node.operator)) { + return isPossibleConstructor(node.right); + } + + if (["||=", "??="].includes(node.operator)) { + return ( + isPossibleConstructor(node.left) || + isPossibleConstructor(node.right) + ); + } + + /** + * All other assignment operators are mathematical assignment operators (arithmetic or bitwise). + * An assignment expression with a mathematical operator can either evaluate to a primitive value, + * or throw, depending on the operands. Thus, it cannot evaluate to a constructor function. + */ + return false; + + case "LogicalExpression": + /* + * If the && operator short-circuits, the left side was falsy and therefore not a constructor, and if + * it doesn't short-circuit, it takes the value from the right side, so the right side must always be a + * possible constructor. A future improvement could verify that the left side could be truthy by + * excluding falsy literals. + */ + if (node.operator === "&&") { + return isPossibleConstructor(node.right); + } + + return ( + isPossibleConstructor(node.left) || + isPossibleConstructor(node.right) + ); + + case "ConditionalExpression": + return ( + isPossibleConstructor(node.alternate) || + isPossibleConstructor(node.consequent) + ); + + case "SequenceExpression": { + const lastExpression = node.expressions.at(-1); + + return isPossibleConstructor(lastExpression); + } + + default: + return false; + } +} + +/** + * A class to store information about a code path segment. + */ +class SegmentInfo { + /** + * Indicates if super() is called in all code paths. + * @type {boolean} + */ + calledInEveryPaths = false; + + /** + * Indicates if super() is called in any code paths. + * @type {boolean} + */ + calledInSomePaths = false; + + /** + * The nodes which have been validated and don't need to be reconsidered. + * @type {ASTNode[]} + */ + validNodes = []; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Require `super()` calls in constructors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/constructor-super", + }, + + schema: [], + + messages: { + missingSome: "Lacked a call of 'super()' in some code paths.", + missingAll: "Expected to call 'super()'.", + + duplicate: "Unexpected duplicate 'super()'.", + badSuper: + "Unexpected 'super()' because 'super' is not a constructor.", + }, + }, + + create(context) { + /* + * {{hasExtends: boolean, scope: Scope, codePath: CodePath}[]} + * Information for each constructor. + * - upper: Information of the upper constructor. + * - hasExtends: A flag which shows whether own class has a valid `extends` + * part. + * - scope: The scope of own class. + * - codePath: The code path object of the constructor. + */ + let funcInfo = null; + + /** + * @type {Record} + */ + const segInfoMap = Object.create(null); + + /** + * Gets the flag which shows `super()` is called in some paths. + * @param {CodePathSegment} segment A code path segment to get. + * @returns {boolean} The flag which shows `super()` is called in some paths + */ + function isCalledInSomePath(segment) { + return ( + segment.reachable && segInfoMap[segment.id].calledInSomePaths + ); + } + + /** + * Determines if a segment has been seen in the traversal. + * @param {CodePathSegment} segment A code path segment to check. + * @returns {boolean} `true` if the segment has been seen. + */ + function hasSegmentBeenSeen(segment) { + return !!segInfoMap[segment.id]; + } + + /** + * Gets the flag which shows `super()` is called in all paths. + * @param {CodePathSegment} segment A code path segment to get. + * @returns {boolean} The flag which shows `super()` is called in all paths. + */ + function isCalledInEveryPath(segment) { + return ( + segment.reachable && segInfoMap[segment.id].calledInEveryPaths + ); + } + + return { + /** + * Stacks a constructor information. + * @param {CodePath} codePath A code path which was started. + * @param {ASTNode} node The current node. + * @returns {void} + */ + onCodePathStart(codePath, node) { + if (isConstructorFunction(node)) { + // Class > ClassBody > MethodDefinition > FunctionExpression + const classNode = node.parent.parent.parent; + const superClass = classNode.superClass; + + funcInfo = { + upper: funcInfo, + isConstructor: true, + hasExtends: Boolean(superClass), + superIsConstructor: isPossibleConstructor(superClass), + codePath, + currentSegments: new Set(), + }; + } else { + funcInfo = { + upper: funcInfo, + isConstructor: false, + hasExtends: false, + superIsConstructor: false, + codePath, + currentSegments: new Set(), + }; + } + }, + + /** + * Pops a constructor information. + * And reports if `super()` lacked. + * @param {CodePath} codePath A code path which was ended. + * @param {ASTNode} node The current node. + * @returns {void} + */ + onCodePathEnd(codePath, node) { + const hasExtends = funcInfo.hasExtends; + + // Pop. + funcInfo = funcInfo.upper; + + if (!hasExtends) { + return; + } + + // Reports if `super()` lacked. + const returnedSegments = codePath.returnedSegments; + const calledInEveryPaths = + returnedSegments.every(isCalledInEveryPath); + const calledInSomePaths = + returnedSegments.some(isCalledInSomePath); + + if (!calledInEveryPaths) { + context.report({ + messageId: calledInSomePaths + ? "missingSome" + : "missingAll", + node: node.parent, + }); + } + }, + + /** + * Initialize information of a given code path segment. + * @param {CodePathSegment} segment A code path segment to initialize. + * @param {CodePathSegment} node Node that starts the segment. + * @returns {void} + */ + onCodePathSegmentStart(segment, node) { + funcInfo.currentSegments.add(segment); + + if (!(funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + // Initialize info. + const info = (segInfoMap[segment.id] = new SegmentInfo()); + + const seenPrevSegments = + segment.prevSegments.filter(hasSegmentBeenSeen); + + // When there are previous segments, aggregates these. + if (seenPrevSegments.length > 0) { + info.calledInSomePaths = + seenPrevSegments.some(isCalledInSomePath); + info.calledInEveryPaths = + seenPrevSegments.every(isCalledInEveryPath); + } + + /* + * ForStatement > *.update segments are a special case as they are created in advance, + * without seen previous segments. Since they logically don't affect `calledInEveryPaths` + * calculations, and they can never be a lone previous segment of another one, we'll set + * their `calledInEveryPaths` to `true` to effectively ignore them in those calculations. + * . + */ + if ( + node.parent && + node.parent.type === "ForStatement" && + node.parent.update === node + ) { + info.calledInEveryPaths = true; + } + }, + + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + /** + * Update information of the code path segment when a code path was + * looped. + * @param {CodePathSegment} fromSegment The code path segment of the + * end of a loop. + * @param {CodePathSegment} toSegment A code path segment of the head + * of a loop. + * @returns {void} + */ + onCodePathSegmentLoop(fromSegment, toSegment) { + if (!(funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + funcInfo.codePath.traverseSegments( + { first: toSegment, last: fromSegment }, + (segment, controller) => { + const info = segInfoMap[segment.id]; + + // skip segments after the loop + if (!info) { + controller.skip(); + return; + } + + const seenPrevSegments = + segment.prevSegments.filter(hasSegmentBeenSeen); + const calledInSomePreviousPaths = + seenPrevSegments.some(isCalledInSomePath); + const calledInEveryPreviousPaths = + seenPrevSegments.every(isCalledInEveryPath); + + info.calledInSomePaths ||= calledInSomePreviousPaths; + info.calledInEveryPaths ||= calledInEveryPreviousPaths; + + // If flags become true anew, reports the valid nodes. + if (calledInSomePreviousPaths) { + const nodes = info.validNodes; + + info.validNodes = []; + + for (let i = 0; i < nodes.length; ++i) { + const node = nodes[i]; + + context.report({ + messageId: "duplicate", + node, + }); + } + } + }, + ); + }, + + /** + * Checks for a call of `super()`. + * @param {ASTNode} node A CallExpression node to check. + * @returns {void} + */ + "CallExpression:exit"(node) { + if (!(funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + // Skips except `super()`. + if (node.callee.type !== "Super") { + return; + } + + // Reports if needed. + const segments = funcInfo.currentSegments; + let duplicate = false; + let info = null; + + for (const segment of segments) { + if (segment.reachable) { + info = segInfoMap[segment.id]; + + duplicate = duplicate || info.calledInSomePaths; + info.calledInSomePaths = info.calledInEveryPaths = true; + } + } + + if (info) { + if (duplicate) { + context.report({ + messageId: "duplicate", + node, + }); + } else if (!funcInfo.superIsConstructor) { + context.report({ + messageId: "badSuper", + node, + }); + } else { + info.validNodes.push(node); + } + } + }, + + /** + * Set the mark to the returned path as `super()` was called. + * @param {ASTNode} node A ReturnStatement node to check. + * @returns {void} + */ + ReturnStatement(node) { + if (!(funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + // Skips if no argument. + if (!node.argument) { + return; + } + + // Returning argument is a substitute of 'super()'. + const segments = funcInfo.currentSegments; + + for (const segment of segments) { + if (segment.reachable) { + const info = segInfoMap[segment.id]; + + info.calledInSomePaths = info.calledInEveryPaths = true; + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/curly.js b/node_modules/eslint/lib/rules/curly.js new file mode 100644 index 00000000..fd4438d3 --- /dev/null +++ b/node_modules/eslint/lib/rules/curly.js @@ -0,0 +1,425 @@ +/** + * @fileoverview Rule to flag statements without curly braces + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce consistent brace style for all control statements", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/curly", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["all"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["multi", "multi-line", "multi-or-nest"], + }, + { + enum: ["consistent"], + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + defaultOptions: ["all"], + + fixable: "code", + + messages: { + missingCurlyAfter: "Expected { after '{{name}}'.", + missingCurlyAfterCondition: + "Expected { after '{{name}}' condition.", + unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.", + unexpectedCurlyAfterCondition: + "Unnecessary { after '{{name}}' condition.", + }, + }, + + create(context) { + const multiOnly = context.options[0] === "multi"; + const multiLine = context.options[0] === "multi-line"; + const multiOrNest = context.options[0] === "multi-or-nest"; + const consistent = context.options[1] === "consistent"; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines if a given node is a one-liner that's on the same line as it's preceding code. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code. + * @private + */ + function isCollapsedOneLiner(node) { + const before = sourceCode.getTokenBefore(node); + const last = sourceCode.getLastToken(node); + const lastExcludingSemicolon = astUtils.isSemicolonToken(last) + ? sourceCode.getTokenBefore(last) + : last; + + return ( + before.loc.start.line === lastExcludingSemicolon.loc.end.line + ); + } + + /** + * Determines if a given node is a one-liner. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a one-liner. + * @private + */ + function isOneLiner(node) { + if (node.type === "EmptyStatement") { + return true; + } + + const first = sourceCode.getFirstToken(node); + const last = sourceCode.getLastToken(node); + const lastExcludingSemicolon = astUtils.isSemicolonToken(last) + ? sourceCode.getTokenBefore(last) + : last; + + return first.loc.start.line === lastExcludingSemicolon.loc.end.line; + } + + /** + * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError. + * @param {Token} closingBracket The } token + * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block. + */ + function needsSemicolon(closingBracket) { + const tokenBefore = sourceCode.getTokenBefore(closingBracket); + const tokenAfter = sourceCode.getTokenAfter(closingBracket); + const lastBlockNode = sourceCode.getNodeByRangeIndex( + tokenBefore.range[0], + ); + + if (astUtils.isSemicolonToken(tokenBefore)) { + // If the last statement already has a semicolon, don't add another one. + return false; + } + + if (!tokenAfter) { + // If there are no statements after this block, there is no need to add a semicolon. + return false; + } + + if ( + lastBlockNode.type === "BlockStatement" && + lastBlockNode.parent.type !== "FunctionExpression" && + lastBlockNode.parent.type !== "ArrowFunctionExpression" + ) { + /* + * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression), + * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause + * a SyntaxError if it was followed by `else`. + */ + return false; + } + + if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) { + // If the next token is on the same line, insert a semicolon. + return true; + } + + if (/^[([/`+-]/u.test(tokenAfter.value)) { + // If the next token starts with a character that would disrupt ASI, insert a semicolon. + return true; + } + + if ( + tokenBefore.type === "Punctuator" && + (tokenBefore.value === "++" || tokenBefore.value === "--") + ) { + // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI. + return true; + } + + // Otherwise, do not insert a semicolon. + return false; + } + + /** + * Prepares to check the body of a node to see if it's a block statement. + * @param {ASTNode} node The node to report if there's a problem. + * @param {ASTNode} body The body node to check for blocks. + * @param {string} name The name to report if there's a problem. + * @param {{ condition: boolean }} opts Options to pass to the report functions + * @returns {Object} a prepared check object, with "actual", "expected", "check" properties. + * "actual" will be `true` or `false` whether the body is already a block statement. + * "expected" will be `true` or `false` if the body should be a block statement or not, or + * `null` if it doesn't matter, depending on the rule options. It can be modified to change + * the final behavior of "check". + * "check" will be a function reporting appropriate problems depending on the other + * properties. + */ + function prepareCheck(node, body, name, opts) { + const hasBlock = body.type === "BlockStatement"; + let expected = null; + + if ( + hasBlock && + (body.body.length !== 1 || + astUtils.areBracesNecessary(body, sourceCode)) + ) { + expected = true; + } else if (multiOnly) { + expected = false; + } else if (multiLine) { + if (!isCollapsedOneLiner(body)) { + expected = true; + } + + // otherwise, the body is allowed to have braces or not to have braces + } else if (multiOrNest) { + if (hasBlock) { + const statement = body.body[0]; + const leadingCommentsInBlock = + sourceCode.getCommentsBefore(statement); + + expected = + !isOneLiner(statement) || + leadingCommentsInBlock.length > 0; + } else { + expected = !isOneLiner(body); + } + } else { + // default "all" + expected = true; + } + + return { + actual: hasBlock, + expected, + check() { + if ( + this.expected !== null && + this.expected !== this.actual + ) { + if (this.expected) { + context.report({ + node, + loc: body.loc, + messageId: + opts && opts.condition + ? "missingCurlyAfterCondition" + : "missingCurlyAfter", + data: { + name, + }, + fix: fixer => + fixer.replaceText( + body, + `{${sourceCode.getText(body)}}`, + ), + }); + } else { + context.report({ + node, + loc: body.loc, + messageId: + opts && opts.condition + ? "unexpectedCurlyAfterCondition" + : "unexpectedCurlyAfter", + data: { + name, + }, + fix(fixer) { + /* + * `do while` expressions sometimes need a space to be inserted after `do`. + * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)` + */ + const needsPrecedingSpace = + node.type === "DoWhileStatement" && + sourceCode.getTokenBefore(body) + .range[1] === body.range[0] && + !astUtils.canTokensBeAdjacent( + "do", + sourceCode.getFirstToken(body, { + skip: 1, + }), + ); + + const openingBracket = + sourceCode.getFirstToken(body); + const closingBracket = + sourceCode.getLastToken(body); + const lastTokenInBlock = + sourceCode.getTokenBefore( + closingBracket, + ); + + if (needsSemicolon(closingBracket)) { + /* + * If removing braces would cause a SyntaxError due to multiple statements on the same line (or + * change the semantics of the code due to ASI), don't perform a fix. + */ + return null; + } + + const resultingBodyText = + sourceCode + .getText() + .slice( + openingBracket.range[1], + lastTokenInBlock.range[0], + ) + + sourceCode.getText(lastTokenInBlock) + + sourceCode + .getText() + .slice( + lastTokenInBlock.range[1], + closingBracket.range[0], + ); + + return fixer.replaceText( + body, + (needsPrecedingSpace ? " " : "") + + resultingBodyText, + ); + }, + }); + } + } + }, + }; + } + + /** + * Prepares to check the bodies of a "if", "else if" and "else" chain. + * @param {ASTNode} node The first IfStatement node of the chain. + * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more + * information. + */ + function prepareIfChecks(node) { + const preparedChecks = []; + + for ( + let currentNode = node; + currentNode; + currentNode = currentNode.alternate + ) { + preparedChecks.push( + prepareCheck(currentNode, currentNode.consequent, "if", { + condition: true, + }), + ); + if ( + currentNode.alternate && + currentNode.alternate.type !== "IfStatement" + ) { + preparedChecks.push( + prepareCheck( + currentNode, + currentNode.alternate, + "else", + ), + ); + break; + } + } + + if (consistent) { + /* + * If any node should have or already have braces, make sure they + * all have braces. + * If all nodes shouldn't have braces, make sure they don't. + */ + const expected = preparedChecks.some(preparedCheck => { + if (preparedCheck.expected !== null) { + return preparedCheck.expected; + } + return preparedCheck.actual; + }); + + preparedChecks.forEach(preparedCheck => { + preparedCheck.expected = expected; + }); + } + + return preparedChecks; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + IfStatement(node) { + const parent = node.parent; + const isElseIf = + parent.type === "IfStatement" && parent.alternate === node; + + if (!isElseIf) { + // This is a top `if`, check the whole `if-else-if` chain + prepareIfChecks(node).forEach(preparedCheck => { + preparedCheck.check(); + }); + } + + // Skip `else if`, it's already checked (when the top `if` was visited) + }, + + WhileStatement(node) { + prepareCheck(node, node.body, "while", { + condition: true, + }).check(); + }, + + DoWhileStatement(node) { + prepareCheck(node, node.body, "do").check(); + }, + + ForStatement(node) { + prepareCheck(node, node.body, "for", { + condition: true, + }).check(); + }, + + ForInStatement(node) { + prepareCheck(node, node.body, "for-in").check(); + }, + + ForOfStatement(node) { + prepareCheck(node, node.body, "for-of").check(); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/default-case-last.js b/node_modules/eslint/lib/rules/default-case-last.js new file mode 100644 index 00000000..1c6170b4 --- /dev/null +++ b/node_modules/eslint/lib/rules/default-case-last.js @@ -0,0 +1,51 @@ +/** + * @fileoverview Rule to enforce `default` clauses in `switch` statements to be last + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce `default` clauses in `switch` statements to be last", + recommended: false, + url: "https://eslint.org/docs/latest/rules/default-case-last", + }, + + schema: [], + + messages: { + notLast: "Default clause should be the last clause.", + }, + }, + + create(context) { + return { + SwitchStatement(node) { + const cases = node.cases, + indexOfDefault = cases.findIndex(c => c.test === null); + + if ( + indexOfDefault !== -1 && + indexOfDefault !== cases.length - 1 + ) { + const defaultClause = cases[indexOfDefault]; + + context.report({ + node: defaultClause, + messageId: "notLast", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/default-case.js b/node_modules/eslint/lib/rules/default-case.js new file mode 100644 index 00000000..23e2f6ef --- /dev/null +++ b/node_modules/eslint/lib/rules/default-case.js @@ -0,0 +1,103 @@ +/** + * @fileoverview require default case in switch statements + * @author Aliaksei Shytkin + */ +"use strict"; + +const DEFAULT_COMMENT_PATTERN = /^no default$/iu; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{}], + + docs: { + description: "Require `default` cases in `switch` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/default-case", + }, + + schema: [ + { + type: "object", + properties: { + commentPattern: { + type: "string", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingDefaultCase: "Expected a default case.", + }, + }, + + create(context) { + const [options] = context.options; + const commentPattern = options.commentPattern + ? new RegExp(options.commentPattern, "u") + : DEFAULT_COMMENT_PATTERN; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Shortcut to get last element of array + * @param {*[]} collection Array + * @returns {any} Last element + */ + function last(collection) { + return collection.at(-1); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + SwitchStatement(node) { + if (!node.cases.length) { + /* + * skip check of empty switch because there is no easy way + * to extract comments inside it now + */ + return; + } + + const hasDefault = node.cases.some(v => v.test === null); + + if (!hasDefault) { + let comment; + + const lastCase = last(node.cases); + const comments = sourceCode.getCommentsAfter(lastCase); + + if (comments.length) { + comment = last(comments); + } + + if ( + !comment || + !commentPattern.test(comment.value.trim()) + ) { + context.report({ + node, + messageId: "missingDefaultCase", + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/default-param-last.js b/node_modules/eslint/lib/rules/default-param-last.js new file mode 100644 index 00000000..101b89ff --- /dev/null +++ b/node_modules/eslint/lib/rules/default-param-last.js @@ -0,0 +1,78 @@ +/** + * @fileoverview enforce default parameters to be last + * @author Chiawen Chen + */ + +"use strict"; + +/** + * Checks if node is required: i.e. does not have a default value or ? optional indicator. + * @param {ASTNode} node the node to be evaluated + * @returns {boolean} true if the node is required, false if not. + */ +function isRequiredParameter(node) { + return !( + node.type === "AssignmentPattern" || + node.type === "RestElement" || + node.optional + ); +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Enforce default parameters to be last", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/default-param-last", + }, + + schema: [], + + messages: { + shouldBeLast: "Default parameters should be last.", + }, + }, + + create(context) { + /** + * Handler for function contexts. + * @param {ASTNode} node function node + * @returns {void} + */ + function handleFunction(node) { + let hasSeenRequiredParameter = false; + + for (let i = node.params.length - 1; i >= 0; i -= 1) { + const current = node.params[i]; + const param = + current.type === "TSParameterProperty" + ? current.parameter + : current; + + if (isRequiredParameter(param)) { + hasSeenRequiredParameter = true; + continue; + } + + if (hasSeenRequiredParameter) { + context.report({ + node: current, + messageId: "shouldBeLast", + }); + } + } + } + + return { + FunctionDeclaration: handleFunction, + FunctionExpression: handleFunction, + ArrowFunctionExpression: handleFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/dot-location.js b/node_modules/eslint/lib/rules/dot-location.js new file mode 100644 index 00000000..742952c3 --- /dev/null +++ b/node_modules/eslint/lib/rules/dot-location.js @@ -0,0 +1,138 @@ +/** + * @fileoverview Validates newlines before and after dots + * @author Greg Cochard + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "dot-location", + url: "https://eslint.style/rules/js/dot-location", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent newlines before and after dots", + recommended: false, + url: "https://eslint.org/docs/latest/rules/dot-location", + }, + + schema: [ + { + enum: ["object", "property"], + }, + ], + + fixable: "code", + + messages: { + expectedDotAfterObject: + "Expected dot to be on same line as object.", + expectedDotBeforeProperty: + "Expected dot to be on same line as property.", + }, + }, + + create(context) { + const config = context.options[0]; + + // default to onObject if no preference is passed + const onObject = config === "object" || !config; + + const sourceCode = context.sourceCode; + + /** + * Reports if the dot between object and property is on the correct location. + * @param {ASTNode} node The `MemberExpression` node. + * @returns {void} + */ + function checkDotLocation(node) { + const property = node.property; + const dotToken = sourceCode.getTokenBefore(property); + + if (onObject) { + // `obj` expression can be parenthesized, but those paren tokens are not a part of the `obj` node. + const tokenBeforeDot = sourceCode.getTokenBefore(dotToken); + + if (!astUtils.isTokenOnSameLine(tokenBeforeDot, dotToken)) { + context.report({ + node, + loc: dotToken.loc, + messageId: "expectedDotAfterObject", + *fix(fixer) { + if ( + dotToken.value.startsWith(".") && + astUtils.isDecimalIntegerNumericToken( + tokenBeforeDot, + ) + ) { + yield fixer.insertTextAfter( + tokenBeforeDot, + ` ${dotToken.value}`, + ); + } else { + yield fixer.insertTextAfter( + tokenBeforeDot, + dotToken.value, + ); + } + yield fixer.remove(dotToken); + }, + }); + } + } else if (!astUtils.isTokenOnSameLine(dotToken, property)) { + context.report({ + node, + loc: dotToken.loc, + messageId: "expectedDotBeforeProperty", + *fix(fixer) { + yield fixer.remove(dotToken); + yield fixer.insertTextBefore(property, dotToken.value); + }, + }); + } + } + + /** + * Checks the spacing of the dot within a member expression. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNode(node) { + if (!node.computed) { + checkDotLocation(node); + } + } + + return { + MemberExpression: checkNode, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/dot-notation.js b/node_modules/eslint/lib/rules/dot-notation.js new file mode 100644 index 00000000..707789a1 --- /dev/null +++ b/node_modules/eslint/lib/rules/dot-notation.js @@ -0,0 +1,216 @@ +/** + * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible. + * @author Josh Perez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const keywords = require("./utils/keywords"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u; + +// `null` literal must be handled separately. +const literalTypesToCheck = new Set(["string", "boolean"]); + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowKeywords: true, + allowPattern: "", + }, + ], + + docs: { + description: "Enforce dot notation whenever possible", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/dot-notation", + }, + + schema: [ + { + type: "object", + properties: { + allowKeywords: { + type: "boolean", + }, + allowPattern: { + type: "string", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + useDot: "[{{key}}] is better written in dot notation.", + useBrackets: ".{{key}} is a syntax error.", + }, + }, + + create(context) { + const [options] = context.options; + const allowKeywords = options.allowKeywords; + const sourceCode = context.sourceCode; + + let allowPattern; + + if (options.allowPattern) { + allowPattern = new RegExp(options.allowPattern, "u"); + } + + /** + * Check if the property is valid dot notation + * @param {ASTNode} node The dot notation node + * @param {string} value Value which is to be checked + * @returns {void} + */ + function checkComputedProperty(node, value) { + if ( + validIdentifier.test(value) && + (allowKeywords || !keywords.includes(String(value))) && + !(allowPattern && allowPattern.test(value)) + ) { + const formattedValue = + node.property.type === "Literal" + ? JSON.stringify(value) + : `\`${value}\``; + + context.report({ + node: node.property, + messageId: "useDot", + data: { + key: formattedValue, + }, + *fix(fixer) { + const leftBracket = sourceCode.getTokenAfter( + node.object, + astUtils.isOpeningBracketToken, + ); + const rightBracket = sourceCode.getLastToken(node); + const nextToken = sourceCode.getTokenAfter(node); + + // Don't perform any fixes if there are comments inside the brackets. + if ( + sourceCode.commentsExistBetween( + leftBracket, + rightBracket, + ) + ) { + return; + } + + // Replace the brackets by an identifier. + if (!node.optional) { + yield fixer.insertTextBefore( + leftBracket, + astUtils.isDecimalInteger(node.object) + ? " ." + : ".", + ); + } + yield fixer.replaceTextRange( + [leftBracket.range[0], rightBracket.range[1]], + value, + ); + + // Insert a space after the property if it will be connected to the next token. + if ( + nextToken && + rightBracket.range[1] === nextToken.range[0] && + !astUtils.canTokensBeAdjacent( + String(value), + nextToken, + ) + ) { + yield fixer.insertTextAfter(node, " "); + } + }, + }); + } + } + + return { + MemberExpression(node) { + if ( + node.computed && + node.property.type === "Literal" && + (literalTypesToCheck.has(typeof node.property.value) || + astUtils.isNullLiteral(node.property)) + ) { + checkComputedProperty(node, node.property.value); + } + if ( + node.computed && + astUtils.isStaticTemplateLiteral(node.property) + ) { + checkComputedProperty( + node, + node.property.quasis[0].value.cooked, + ); + } + if ( + !allowKeywords && + !node.computed && + node.property.type === "Identifier" && + keywords.includes(String(node.property.name)) + ) { + context.report({ + node: node.property, + messageId: "useBrackets", + data: { + key: node.property.name, + }, + *fix(fixer) { + const dotToken = sourceCode.getTokenBefore( + node.property, + ); + + // A statement that starts with `let[` is parsed as a destructuring variable declaration, not a MemberExpression. + if ( + node.object.type === "Identifier" && + node.object.name === "let" && + !node.optional + ) { + return; + } + + // Don't perform any fixes if there are comments between the dot and the property name. + if ( + sourceCode.commentsExistBetween( + dotToken, + node.property, + ) + ) { + return; + } + + // Replace the identifier to brackets. + if (!node.optional) { + yield fixer.remove(dotToken); + } + yield fixer.replaceText( + node.property, + `["${node.property.name}"]`, + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/eol-last.js b/node_modules/eslint/lib/rules/eol-last.js new file mode 100644 index 00000000..981a5b61 --- /dev/null +++ b/node_modules/eslint/lib/rules/eol-last.js @@ -0,0 +1,135 @@ +/** + * @fileoverview Require or disallow newline at the end of files + * @author Nodeca Team + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "eol-last", + url: "https://eslint.style/rules/js/eol-last", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow newline at the end of files", + recommended: false, + url: "https://eslint.org/docs/latest/rules/eol-last", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never", "unix", "windows"], + }, + ], + + messages: { + missing: "Newline required at end of file but not found.", + unexpected: "Newline not allowed at end of file.", + }, + }, + create(context) { + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkBadEOF(node) { + const sourceCode = context.sourceCode, + src = sourceCode.getText(), + lastLine = sourceCode.lines.at(-1), + location = { + column: lastLine.length, + line: sourceCode.lines.length, + }, + LF = "\n", + CRLF = `\r${LF}`, + endsWithNewline = src.endsWith(LF); + + /* + * Empty source is always valid: No content in file so we don't + * need to lint for a newline on the last line of content. + */ + if (!src.length) { + return; + } + + let mode = context.options[0] || "always", + appendCRLF = false; + + if (mode === "unix") { + // `"unix"` should behave exactly as `"always"` + mode = "always"; + } + if (mode === "windows") { + // `"windows"` should behave exactly as `"always"`, but append CRLF in the fixer for backwards compatibility + mode = "always"; + appendCRLF = true; + } + if (mode === "always" && !endsWithNewline) { + // File is not newline-terminated, but should be + context.report({ + node, + loc: location, + messageId: "missing", + fix(fixer) { + return fixer.insertTextAfterRange( + [0, src.length], + appendCRLF ? CRLF : LF, + ); + }, + }); + } else if (mode === "never" && endsWithNewline) { + const secondLastLine = sourceCode.lines.at(-2); + + // File is newline-terminated, but shouldn't be + context.report({ + node, + loc: { + start: { + line: sourceCode.lines.length - 1, + column: secondLastLine.length, + }, + end: { line: sourceCode.lines.length, column: 0 }, + }, + messageId: "unexpected", + fix(fixer) { + const finalEOLs = /(?:\r?\n)+$/u, + match = finalEOLs.exec(sourceCode.text), + start = match.index, + end = sourceCode.text.length; + + return fixer.replaceTextRange([start, end], ""); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/eqeqeq.js b/node_modules/eslint/lib/rules/eqeqeq.js new file mode 100644 index 00000000..cfe5bd4c --- /dev/null +++ b/node_modules/eslint/lib/rules/eqeqeq.js @@ -0,0 +1,210 @@ +/** + * @fileoverview Rule to flag statements that use != and == instead of !== and === + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + hasSuggestions: true, + + docs: { + description: "Require the use of `===` and `!==`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/eqeqeq", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always"], + }, + { + type: "object", + properties: { + null: { + enum: ["always", "never", "ignore"], + }, + }, + additionalProperties: false, + }, + ], + additionalItems: false, + }, + { + type: "array", + items: [ + { + enum: ["smart", "allow-null"], + }, + ], + additionalItems: false, + }, + ], + }, + + fixable: "code", + + messages: { + unexpected: + "Expected '{{expectedOperator}}' and instead saw '{{actualOperator}}'.", + replaceOperator: + "Use '{{expectedOperator}}' instead of '{{actualOperator}}'.", + }, + }, + + create(context) { + const config = context.options[0] || "always"; + const options = context.options[1] || {}; + const sourceCode = context.sourceCode; + + const nullOption = + config === "always" ? options.null || "always" : "ignore"; + const enforceRuleForNull = nullOption === "always"; + const enforceInverseRuleForNull = nullOption === "never"; + + /** + * Checks if an expression is a typeof expression + * @param {ASTNode} node The node to check + * @returns {boolean} if the node is a typeof expression + */ + function isTypeOf(node) { + return ( + node.type === "UnaryExpression" && node.operator === "typeof" + ); + } + + /** + * Checks if either operand of a binary expression is a typeof operation + * @param {ASTNode} node The node to check + * @returns {boolean} if one of the operands is typeof + * @private + */ + function isTypeOfBinary(node) { + return isTypeOf(node.left) || isTypeOf(node.right); + } + + /** + * Checks if operands are literals of the same type (via typeof) + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are of same type + * @private + */ + function areLiteralsAndSameType(node) { + return ( + node.left.type === "Literal" && + node.right.type === "Literal" && + typeof node.left.value === typeof node.right.value + ); + } + + /** + * Checks if one of the operands is a literal null + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are null + * @private + */ + function isNullCheck(node) { + return ( + astUtils.isNullLiteral(node.right) || + astUtils.isNullLiteral(node.left) + ); + } + + /** + * Reports a message for this rule. + * @param {ASTNode} node The binary expression node that was checked + * @param {string} expectedOperator The operator that was expected (either '==', '!=', '===', or '!==') + * @returns {void} + * @private + */ + function report(node, expectedOperator) { + const operatorToken = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + + const commonReportParams = { + node, + loc: operatorToken.loc, + messageId: "unexpected", + data: { expectedOperator, actualOperator: node.operator }, + }; + + if (isTypeOfBinary(node) || areLiteralsAndSameType(node)) { + context.report({ + ...commonReportParams, + fix(fixer) { + return fixer.replaceText( + operatorToken, + expectedOperator, + ); + }, + }); + } else { + context.report({ + ...commonReportParams, + suggest: [ + { + messageId: "replaceOperator", + data: { + expectedOperator, + actualOperator: node.operator, + }, + fix: fixer => + fixer.replaceText( + operatorToken, + expectedOperator, + ), + }, + ], + }); + } + } + + return { + BinaryExpression(node) { + const isNull = isNullCheck(node); + + if (node.operator !== "==" && node.operator !== "!=") { + if (enforceInverseRuleForNull && isNull) { + report(node, node.operator.slice(0, -1)); + } + return; + } + + if ( + config === "smart" && + (isTypeOfBinary(node) || + areLiteralsAndSameType(node) || + isNull) + ) { + return; + } + + if (!enforceRuleForNull && isNull) { + return; + } + + report(node, `${node.operator}=`); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/for-direction.js b/node_modules/eslint/lib/rules/for-direction.js new file mode 100644 index 00000000..078d121f --- /dev/null +++ b/node_modules/eslint/lib/rules/for-direction.js @@ -0,0 +1,165 @@ +/** + * @fileoverview enforce `for` loop update clause moving the counter in the right direction.(for-direction) + * @author Aladdin-ADD + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getStaticValue } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Enforce `for` loop update clause moving the counter in the right direction", + recommended: true, + url: "https://eslint.org/docs/latest/rules/for-direction", + }, + + fixable: null, + schema: [], + + messages: { + incorrectDirection: + "The update clause in this loop moves the variable in the wrong direction.", + }, + }, + + create(context) { + const { sourceCode } = context; + + /** + * report an error. + * @param {ASTNode} node the node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "incorrectDirection", + }); + } + + /** + * check the right side of the assignment + * @param {ASTNode} update UpdateExpression to check + * @param {number} dir expected direction that could either be turned around or invalidated + * @returns {number} return dir, the negated dir, or zero if the counter does not change or the direction is not clear + */ + function getRightDirection(update, dir) { + const staticValue = getStaticValue( + update.right, + sourceCode.getScope(update), + ); + + if ( + staticValue && + ["bigint", "boolean", "number"].includes( + typeof staticValue.value, + ) + ) { + const sign = Math.sign(Number(staticValue.value)) || 0; // convert NaN to 0 + + return dir * sign; + } + return 0; + } + + /** + * check UpdateExpression add/sub the counter + * @param {ASTNode} update UpdateExpression to check + * @param {string} counter variable name to check + * @returns {number} if add return 1, if sub return -1, if nochange, return 0 + */ + function getUpdateDirection(update, counter) { + if ( + update.argument.type === "Identifier" && + update.argument.name === counter + ) { + if (update.operator === "++") { + return 1; + } + if (update.operator === "--") { + return -1; + } + } + return 0; + } + + /** + * check AssignmentExpression add/sub the counter + * @param {ASTNode} update AssignmentExpression to check + * @param {string} counter variable name to check + * @returns {number} if add return 1, if sub return -1, if nochange, return 0 + */ + function getAssignmentDirection(update, counter) { + if (update.left.name === counter) { + if (update.operator === "+=") { + return getRightDirection(update, 1); + } + if (update.operator === "-=") { + return getRightDirection(update, -1); + } + } + return 0; + } + + return { + ForStatement(node) { + if ( + node.test && + node.test.type === "BinaryExpression" && + node.update + ) { + for (const counterPosition of ["left", "right"]) { + if (node.test[counterPosition].type !== "Identifier") { + continue; + } + + const counter = node.test[counterPosition].name; + const operator = node.test.operator; + const update = node.update; + + let wrongDirection; + + if (operator === "<" || operator === "<=") { + wrongDirection = + counterPosition === "left" ? -1 : 1; + } else if (operator === ">" || operator === ">=") { + wrongDirection = + counterPosition === "left" ? 1 : -1; + } else { + return; + } + + if (update.type === "UpdateExpression") { + if ( + getUpdateDirection(update, counter) === + wrongDirection + ) { + report(node); + } + } else if ( + update.type === "AssignmentExpression" && + getAssignmentDirection(update, counter) === + wrongDirection + ) { + report(node); + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/func-call-spacing.js b/node_modules/eslint/lib/rules/func-call-spacing.js new file mode 100644 index 00000000..addbf012 --- /dev/null +++ b/node_modules/eslint/lib/rules/func-call-spacing.js @@ -0,0 +1,281 @@ +/** + * @fileoverview Rule to control spacing within function calls + * @author Matt DuVall + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "function-call-spacing", + url: "https://eslint.style/rules/js/function-call-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow spacing between function identifiers and their invocations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/func-call-spacing", + }, + + fixable: "whitespace", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["never"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["always"], + }, + { + type: "object", + properties: { + allowNewlines: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + messages: { + unexpectedWhitespace: + "Unexpected whitespace between function name and paren.", + unexpectedNewline: + "Unexpected newline between function name and paren.", + missing: "Missing space between function name and paren.", + }, + }, + + create(context) { + const never = context.options[0] !== "always"; + const allowNewlines = + !never && context.options[1] && context.options[1].allowNewlines; + const sourceCode = context.sourceCode; + const text = sourceCode.getText(); + + /** + * Check if open space is present in a function name + * @param {ASTNode} node node to evaluate + * @param {Token} leftToken The last token of the callee. This may be the closing parenthesis that encloses the callee. + * @param {Token} rightToken Tha first token of the arguments. this is the opening parenthesis that encloses the arguments. + * @returns {void} + * @private + */ + function checkSpacing(node, leftToken, rightToken) { + const textBetweenTokens = text + .slice(leftToken.range[1], rightToken.range[0]) + .replace(/\/\*.*?\*\//gu, ""); + const hasWhitespace = /\s/u.test(textBetweenTokens); + const hasNewline = + hasWhitespace && + astUtils.LINEBREAK_MATCHER.test(textBetweenTokens); + + /* + * never allowNewlines hasWhitespace hasNewline message + * F F F F Missing space between function name and paren. + * F F F T (Invalid `!hasWhitespace && hasNewline`) + * F F T T Unexpected newline between function name and paren. + * F F T F (OK) + * F T T F (OK) + * F T T T (OK) + * F T F T (Invalid `!hasWhitespace && hasNewline`) + * F T F F Missing space between function name and paren. + * T T F F (Invalid `never && allowNewlines`) + * T T F T (Invalid `!hasWhitespace && hasNewline`) + * T T T T (Invalid `never && allowNewlines`) + * T T T F (Invalid `never && allowNewlines`) + * T F T F Unexpected space between function name and paren. + * T F T T Unexpected space between function name and paren. + * T F F T (Invalid `!hasWhitespace && hasNewline`) + * T F F F (OK) + * + * T T Unexpected space between function name and paren. + * F F Missing space between function name and paren. + * F F T Unexpected newline between function name and paren. + */ + + if (never && hasWhitespace) { + context.report({ + node, + loc: { + start: leftToken.loc.end, + end: { + line: rightToken.loc.start.line, + column: rightToken.loc.start.column - 1, + }, + }, + messageId: "unexpectedWhitespace", + fix(fixer) { + // Don't remove comments. + if ( + sourceCode.commentsExistBetween( + leftToken, + rightToken, + ) + ) { + return null; + } + + // If `?.` exists, it doesn't hide no-unexpected-multiline errors + if (node.optional) { + return fixer.replaceTextRange( + [leftToken.range[1], rightToken.range[0]], + "?.", + ); + } + + /* + * Only autofix if there is no newline + * https://github.com/eslint/eslint/issues/7787 + */ + if (hasNewline) { + return null; + } + return fixer.removeRange([ + leftToken.range[1], + rightToken.range[0], + ]); + }, + }); + } else if (!never && !hasWhitespace) { + context.report({ + node, + loc: { + start: { + line: leftToken.loc.end.line, + column: leftToken.loc.end.column - 1, + }, + end: rightToken.loc.start, + }, + messageId: "missing", + fix(fixer) { + if (node.optional) { + return null; // Not sure if inserting a space to either before/after `?.` token. + } + return fixer.insertTextBefore(rightToken, " "); + }, + }); + } else if (!never && !allowNewlines && hasNewline) { + context.report({ + node, + loc: { + start: leftToken.loc.end, + end: rightToken.loc.start, + }, + messageId: "unexpectedNewline", + fix(fixer) { + /* + * Only autofix if there is no newline + * https://github.com/eslint/eslint/issues/7787 + * But if `?.` exists, it doesn't hide no-unexpected-multiline errors + */ + if (!node.optional) { + return null; + } + + // Don't remove comments. + if ( + sourceCode.commentsExistBetween( + leftToken, + rightToken, + ) + ) { + return null; + } + + const range = [leftToken.range[1], rightToken.range[0]]; + const qdToken = sourceCode.getTokenAfter(leftToken); + + if (qdToken.range[0] === leftToken.range[1]) { + return fixer.replaceTextRange(range, "?. "); + } + if (qdToken.range[1] === rightToken.range[0]) { + return fixer.replaceTextRange(range, " ?."); + } + return fixer.replaceTextRange(range, " ?. "); + }, + }); + } + } + + return { + "CallExpression, NewExpression"(node) { + const lastToken = sourceCode.getLastToken(node); + const lastCalleeToken = sourceCode.getLastToken(node.callee); + const parenToken = sourceCode.getFirstTokenBetween( + lastCalleeToken, + lastToken, + astUtils.isOpeningParenToken, + ); + const prevToken = + parenToken && + sourceCode.getTokenBefore( + parenToken, + astUtils.isNotQuestionDotToken, + ); + + // Parens in NewExpression are optional + if (!(parenToken && parenToken.range[1] < node.range[1])) { + return; + } + + checkSpacing(node, prevToken, parenToken); + }, + + ImportExpression(node) { + const leftToken = sourceCode.getFirstToken(node); + const rightToken = sourceCode.getTokenAfter(leftToken); + + checkSpacing(node, leftToken, rightToken); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/func-name-matching.js b/node_modules/eslint/lib/rules/func-name-matching.js new file mode 100644 index 00000000..4643bfbc --- /dev/null +++ b/node_modules/eslint/lib/rules/func-name-matching.js @@ -0,0 +1,338 @@ +/** + * @fileoverview Rule to require function names to match the name of the variable or property to which they are assigned. + * @author Annie Zhang, Pavel Strashkin + */ + +"use strict"; + +//-------------------------------------------------------------------------- +// Requirements +//-------------------------------------------------------------------------- + +const astUtils = require("./utils/ast-utils"); +const esutils = require("esutils"); + +//-------------------------------------------------------------------------- +// Helpers +//-------------------------------------------------------------------------- + +/** + * Determines if a pattern is `module.exports` or `module["exports"]` + * @param {ASTNode} pattern The left side of the AssignmentExpression + * @returns {boolean} True if the pattern is `module.exports` or `module["exports"]` + */ +function isModuleExports(pattern) { + if ( + pattern.type === "MemberExpression" && + pattern.object.type === "Identifier" && + pattern.object.name === "module" + ) { + // module.exports + if ( + pattern.property.type === "Identifier" && + pattern.property.name === "exports" + ) { + return true; + } + + // module["exports"] + if ( + pattern.property.type === "Literal" && + pattern.property.value === "exports" + ) { + return true; + } + } + return false; +} + +/** + * Determines if a string name is a valid identifier + * @param {string} name The string to be checked + * @param {number} ecmaVersion The ECMAScript version if specified in the parserOptions config + * @returns {boolean} True if the string is a valid identifier + */ +function isIdentifier(name, ecmaVersion) { + if (ecmaVersion >= 2015) { + return esutils.keyword.isIdentifierES6(name); + } + return esutils.keyword.isIdentifierES5(name); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const alwaysOrNever = { enum: ["always", "never"] }; +const optionsObject = { + type: "object", + properties: { + considerPropertyDescriptor: { + type: "boolean", + }, + includeCommonJSModuleExports: { + type: "boolean", + }, + }, + additionalProperties: false, +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require function names to match the name of the variable or property to which they are assigned", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/func-name-matching", + }, + + schema: { + anyOf: [ + { + type: "array", + additionalItems: false, + items: [alwaysOrNever, optionsObject], + }, + { + type: "array", + additionalItems: false, + items: [optionsObject], + }, + ], + }, + + messages: { + matchProperty: + "Function name `{{funcName}}` should match property name `{{name}}`.", + matchVariable: + "Function name `{{funcName}}` should match variable name `{{name}}`.", + notMatchProperty: + "Function name `{{funcName}}` should not match property name `{{name}}`.", + notMatchVariable: + "Function name `{{funcName}}` should not match variable name `{{name}}`.", + }, + }, + + create(context) { + const options = + (typeof context.options[0] === "object" + ? context.options[0] + : context.options[1]) || {}; + const nameMatches = + typeof context.options[0] === "string" + ? context.options[0] + : "always"; + const considerPropertyDescriptor = options.considerPropertyDescriptor; + const includeModuleExports = options.includeCommonJSModuleExports; + const ecmaVersion = context.languageOptions.ecmaVersion; + + /** + * Check whether node is a certain CallExpression. + * @param {string} objName object name + * @param {string} funcName function name + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if node matches CallExpression + */ + function isPropertyCall(objName, funcName, node) { + if (!node) { + return false; + } + return ( + node.type === "CallExpression" && + astUtils.isSpecificMemberAccess(node.callee, objName, funcName) + ); + } + + /** + * Compares identifiers based on the nameMatches option + * @param {string} x the first identifier + * @param {string} y the second identifier + * @returns {boolean} whether the two identifiers should warn. + */ + function shouldWarn(x, y) { + return ( + (nameMatches === "always" && x !== y) || + (nameMatches === "never" && x === y) + ); + } + + /** + * Reports + * @param {ASTNode} node The node to report + * @param {string} name The variable or property name + * @param {string} funcName The function name + * @param {boolean} isProp True if the reported node is a property assignment + * @returns {void} + */ + function report(node, name, funcName, isProp) { + let messageId; + + if (nameMatches === "always" && isProp) { + messageId = "matchProperty"; + } else if (nameMatches === "always") { + messageId = "matchVariable"; + } else if (isProp) { + messageId = "notMatchProperty"; + } else { + messageId = "notMatchVariable"; + } + context.report({ + node, + messageId, + data: { + name, + funcName, + }, + }); + } + + /** + * Determines whether a given node is a string literal + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if the node is a string literal + */ + function isStringLiteral(node) { + return node.type === "Literal" && typeof node.value === "string"; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclarator(node) { + if ( + !node.init || + node.init.type !== "FunctionExpression" || + node.id.type !== "Identifier" + ) { + return; + } + if ( + node.init.id && + shouldWarn(node.id.name, node.init.id.name) + ) { + report(node, node.id.name, node.init.id.name, false); + } + }, + + AssignmentExpression(node) { + if ( + node.right.type !== "FunctionExpression" || + (node.left.computed && + node.left.property.type !== "Literal") || + (!includeModuleExports && isModuleExports(node.left)) || + (node.left.type !== "Identifier" && + node.left.type !== "MemberExpression") + ) { + return; + } + + const isProp = node.left.type === "MemberExpression"; + const name = isProp + ? astUtils.getStaticPropertyName(node.left) + : node.left.name; + + if ( + node.right.id && + name && + isIdentifier(name) && + shouldWarn(name, node.right.id.name) + ) { + report(node, name, node.right.id.name, isProp); + } + }, + + "Property, PropertyDefinition[value]"(node) { + if ( + !(node.value.type === "FunctionExpression" && node.value.id) + ) { + return; + } + + if (node.key.type === "Identifier" && !node.computed) { + const functionName = node.value.id.name; + let propertyName = node.key.name; + + if ( + considerPropertyDescriptor && + propertyName === "value" && + node.parent.type === "ObjectExpression" + ) { + if ( + isPropertyCall( + "Object", + "defineProperty", + node.parent.parent, + ) || + isPropertyCall( + "Reflect", + "defineProperty", + node.parent.parent, + ) + ) { + const property = node.parent.parent.arguments[1]; + + if ( + isStringLiteral(property) && + shouldWarn(property.value, functionName) + ) { + report( + node, + property.value, + functionName, + true, + ); + } + } else if ( + isPropertyCall( + "Object", + "defineProperties", + node.parent.parent.parent.parent, + ) + ) { + propertyName = node.parent.parent.key.name; + if ( + !node.parent.parent.computed && + shouldWarn(propertyName, functionName) + ) { + report(node, propertyName, functionName, true); + } + } else if ( + isPropertyCall( + "Object", + "create", + node.parent.parent.parent.parent, + ) + ) { + propertyName = node.parent.parent.key.name; + if ( + !node.parent.parent.computed && + shouldWarn(propertyName, functionName) + ) { + report(node, propertyName, functionName, true); + } + } else if (shouldWarn(propertyName, functionName)) { + report(node, propertyName, functionName, true); + } + } else if (shouldWarn(propertyName, functionName)) { + report(node, propertyName, functionName, true); + } + return; + } + + if ( + isStringLiteral(node.key) && + isIdentifier(node.key.value, ecmaVersion) && + shouldWarn(node.key.value, node.value.id.name) + ) { + report(node, node.key.value, node.value.id.name, true); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/func-names.js b/node_modules/eslint/lib/rules/func-names.js new file mode 100644 index 00000000..bef70e32 --- /dev/null +++ b/node_modules/eslint/lib/rules/func-names.js @@ -0,0 +1,192 @@ +/** + * @fileoverview Rule to warn when a function expression does not have a name. + * @author Kyle T. Nunery + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +/** + * Checks whether or not a given variable is a function name. + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is a function name. + */ +function isFunctionName(variable) { + return variable && variable.defs[0].type === "FunctionName"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["always", {}], + + docs: { + description: "Require or disallow named `function` expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/func-names", + }, + + schema: { + definitions: { + value: { + enum: ["always", "as-needed", "never"], + }, + }, + items: [ + { + $ref: "#/definitions/value", + }, + { + type: "object", + properties: { + generators: { + $ref: "#/definitions/value", + }, + }, + additionalProperties: false, + }, + ], + }, + + messages: { + unnamed: "Unexpected unnamed {{name}}.", + named: "Unexpected named {{name}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Returns the config option for the given node. + * @param {ASTNode} node A node to get the config for. + * @returns {string} The config option. + */ + function getConfigForNode(node) { + if (node.generator && context.options[1].generators) { + return context.options[1].generators; + } + + return context.options[0]; + } + + /** + * Determines whether the current FunctionExpression node is a get, set, or + * shorthand method in an object literal or a class. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is a get, set, or shorthand method. + */ + function isObjectOrClassMethod(node) { + const parent = node.parent; + + return ( + parent.type === "MethodDefinition" || + (parent.type === "Property" && + (parent.method || + parent.kind === "get" || + parent.kind === "set")) + ); + } + + /** + * Determines whether the current FunctionExpression node has a name that would be + * inferred from context in a conforming ES6 environment. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node would have a name assigned automatically. + */ + function hasInferredName(node) { + const parent = node.parent; + + return ( + isObjectOrClassMethod(node) || + (parent.type === "VariableDeclarator" && + parent.id.type === "Identifier" && + parent.init === node) || + (parent.type === "Property" && parent.value === node) || + (parent.type === "PropertyDefinition" && + parent.value === node) || + (parent.type === "AssignmentExpression" && + parent.left.type === "Identifier" && + parent.right === node) || + (parent.type === "AssignmentPattern" && + parent.left.type === "Identifier" && + parent.right === node) + ); + } + + /** + * Reports that an unnamed function should be named + * @param {ASTNode} node The node to report in the event of an error. + * @returns {void} + */ + function reportUnexpectedUnnamedFunction(node) { + context.report({ + node, + messageId: "unnamed", + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + data: { name: astUtils.getFunctionNameWithKind(node) }, + }); + } + + /** + * Reports that a named function should be unnamed + * @param {ASTNode} node The node to report in the event of an error. + * @returns {void} + */ + function reportUnexpectedNamedFunction(node) { + context.report({ + node, + messageId: "named", + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + data: { name: astUtils.getFunctionNameWithKind(node) }, + }); + } + + /** + * The listener for function nodes. + * @param {ASTNode} node function node + * @returns {void} + */ + function handleFunction(node) { + // Skip recursive functions. + const nameVar = sourceCode.getDeclaredVariables(node)[0]; + + if (isFunctionName(nameVar) && nameVar.references.length > 0) { + return; + } + + const hasName = Boolean(node.id && node.id.name); + const config = getConfigForNode(node); + + if (config === "never") { + if (hasName && node.type !== "FunctionDeclaration") { + reportUnexpectedNamedFunction(node); + } + } else if (config === "as-needed") { + if (!hasName && !hasInferredName(node)) { + reportUnexpectedUnnamedFunction(node); + } + } else { + if (!hasName && !isObjectOrClassMethod(node)) { + reportUnexpectedUnnamedFunction(node); + } + } + } + + return { + "FunctionExpression:exit": handleFunction, + "ExportDefaultDeclaration > FunctionDeclaration": handleFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/func-style.js b/node_modules/eslint/lib/rules/func-style.js new file mode 100644 index 00000000..dcd4ae9f --- /dev/null +++ b/node_modules/eslint/lib/rules/func-style.js @@ -0,0 +1,221 @@ +/** + * @fileoverview Rule to enforce a particular function style + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + defaultOptions: [ + "expression", + { + allowArrowFunctions: false, + allowTypeAnnotation: false, + overrides: {}, + }, + ], + + docs: { + description: + "Enforce the consistent use of either `function` declarations or expressions assigned to variables", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/func-style", + }, + + schema: [ + { + enum: ["declaration", "expression"], + }, + { + type: "object", + properties: { + allowArrowFunctions: { + type: "boolean", + }, + allowTypeAnnotation: { + type: "boolean", + }, + overrides: { + type: "object", + properties: { + namedExports: { + enum: ["declaration", "expression", "ignore"], + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expression: "Expected a function expression.", + declaration: "Expected a function declaration.", + }, + }, + + create(context) { + const [style, { allowArrowFunctions, allowTypeAnnotation, overrides }] = + context.options; + const enforceDeclarations = style === "declaration"; + const { namedExports: exportFunctionStyle } = overrides; + const stack = []; + + /** + * Checks if a function declaration is part of an overloaded function + * @param {ASTNode} node The function declaration node to check + * @returns {boolean} True if the function is overloaded + */ + function isOverloadedFunction(node) { + const functionName = node.id.name; + + if (node.parent.type === "ExportNamedDeclaration") { + return node.parent.parent.body.some( + member => + member.type === "ExportNamedDeclaration" && + member.declaration?.type === "TSDeclareFunction" && + member.declaration.id.name === functionName, + ); + } + + if (node.parent.type === "SwitchCase") { + return node.parent.parent.cases.some(switchCase => + switchCase.consequent.some( + member => + member.type === "TSDeclareFunction" && + member.id.name === functionName, + ), + ); + } + + return ( + Array.isArray(node.parent.body) && + node.parent.body.some( + member => + member.type === "TSDeclareFunction" && + member.id.name === functionName, + ) + ); + } + + const nodesToCheck = { + FunctionDeclaration(node) { + stack.push(false); + + if ( + !enforceDeclarations && + node.parent.type !== "ExportDefaultDeclaration" && + (typeof exportFunctionStyle === "undefined" || + node.parent.type !== "ExportNamedDeclaration") && + !isOverloadedFunction(node) + ) { + context.report({ node, messageId: "expression" }); + } + + if ( + node.parent.type === "ExportNamedDeclaration" && + exportFunctionStyle === "expression" && + !isOverloadedFunction(node) + ) { + context.report({ node, messageId: "expression" }); + } + }, + "FunctionDeclaration:exit"() { + stack.pop(); + }, + + FunctionExpression(node) { + stack.push(false); + + if ( + enforceDeclarations && + node.parent.type === "VariableDeclarator" && + (typeof exportFunctionStyle === "undefined" || + node.parent.parent.parent.type !== + "ExportNamedDeclaration") && + !(allowTypeAnnotation && node.parent.id.typeAnnotation) + ) { + context.report({ + node: node.parent, + messageId: "declaration", + }); + } + + if ( + node.parent.type === "VariableDeclarator" && + node.parent.parent.parent.type === + "ExportNamedDeclaration" && + exportFunctionStyle === "declaration" && + !(allowTypeAnnotation && node.parent.id.typeAnnotation) + ) { + context.report({ + node: node.parent, + messageId: "declaration", + }); + } + }, + "FunctionExpression:exit"() { + stack.pop(); + }, + + "ThisExpression, Super"() { + if (stack.length > 0) { + stack[stack.length - 1] = true; + } + }, + }; + + if (!allowArrowFunctions) { + nodesToCheck.ArrowFunctionExpression = function () { + stack.push(false); + }; + + nodesToCheck["ArrowFunctionExpression:exit"] = function (node) { + const hasThisOrSuperExpr = stack.pop(); + + if ( + !hasThisOrSuperExpr && + node.parent.type === "VariableDeclarator" + ) { + if ( + enforceDeclarations && + (typeof exportFunctionStyle === "undefined" || + node.parent.parent.parent.type !== + "ExportNamedDeclaration") && + !(allowTypeAnnotation && node.parent.id.typeAnnotation) + ) { + context.report({ + node: node.parent, + messageId: "declaration", + }); + } + + if ( + node.parent.parent.parent.type === + "ExportNamedDeclaration" && + exportFunctionStyle === "declaration" && + !(allowTypeAnnotation && node.parent.id.typeAnnotation) + ) { + context.report({ + node: node.parent, + messageId: "declaration", + }); + } + } + }; + } + + return nodesToCheck; + }, +}; diff --git a/node_modules/eslint/lib/rules/function-call-argument-newline.js b/node_modules/eslint/lib/rules/function-call-argument-newline.js new file mode 100644 index 00000000..fd480b94 --- /dev/null +++ b/node_modules/eslint/lib/rules/function-call-argument-newline.js @@ -0,0 +1,166 @@ +/** + * @fileoverview Rule to enforce line breaks between arguments of a function call + * @author Alexey Gonchar + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "function-call-argument-newline", + url: "https://eslint.style/rules/js/function-call-argument-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce line breaks between arguments of a function call", + recommended: false, + url: "https://eslint.org/docs/latest/rules/function-call-argument-newline", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never", "consistent"], + }, + ], + + messages: { + unexpectedLineBreak: "There should be no line break here.", + missingLineBreak: + "There should be a line break after this argument.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const checkers = { + unexpected: { + messageId: "unexpectedLineBreak", + check: (prevToken, currentToken) => + prevToken.loc.end.line !== currentToken.loc.start.line, + createFix: (token, tokenBefore) => fixer => + fixer.replaceTextRange( + [tokenBefore.range[1], token.range[0]], + " ", + ), + }, + missing: { + messageId: "missingLineBreak", + check: (prevToken, currentToken) => + prevToken.loc.end.line === currentToken.loc.start.line, + createFix: (token, tokenBefore) => fixer => + fixer.replaceTextRange( + [tokenBefore.range[1], token.range[0]], + "\n", + ), + }, + }; + + /** + * Check all arguments for line breaks in the CallExpression + * @param {CallExpression} node node to evaluate + * @param {{ messageId: string, check: Function }} checker selected checker + * @returns {void} + * @private + */ + function checkArguments(node, checker) { + for (let i = 1; i < node.arguments.length; i++) { + const prevArgToken = sourceCode.getLastToken( + node.arguments[i - 1], + ); + const currentArgToken = sourceCode.getFirstToken( + node.arguments[i], + ); + + if (checker.check(prevArgToken, currentArgToken)) { + const tokenBefore = sourceCode.getTokenBefore( + currentArgToken, + { includeComments: true }, + ); + + const hasLineCommentBefore = tokenBefore.type === "Line"; + + context.report({ + node, + loc: { + start: tokenBefore.loc.end, + end: currentArgToken.loc.start, + }, + messageId: checker.messageId, + fix: hasLineCommentBefore + ? null + : checker.createFix(currentArgToken, tokenBefore), + }); + } + } + } + + /** + * Check if open space is present in a function name + * @param {CallExpression} node node to evaluate + * @returns {void} + * @private + */ + function check(node) { + if (node.arguments.length < 2) { + return; + } + + const option = context.options[0] || "always"; + + if (option === "never") { + checkArguments(node, checkers.unexpected); + } else if (option === "always") { + checkArguments(node, checkers.missing); + } else if (option === "consistent") { + const firstArgToken = sourceCode.getLastToken( + node.arguments[0], + ); + const secondArgToken = sourceCode.getFirstToken( + node.arguments[1], + ); + + if ( + firstArgToken.loc.end.line === secondArgToken.loc.start.line + ) { + checkArguments(node, checkers.unexpected); + } else { + checkArguments(node, checkers.missing); + } + } + } + + return { + CallExpression: check, + NewExpression: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/function-paren-newline.js b/node_modules/eslint/lib/rules/function-paren-newline.js new file mode 100644 index 00000000..bdff3b9e --- /dev/null +++ b/node_modules/eslint/lib/rules/function-paren-newline.js @@ -0,0 +1,368 @@ +/** + * @fileoverview enforce consistent line breaks inside function parentheses + * @author Teddy Katz + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "function-paren-newline", + url: "https://eslint.style/rules/js/function-paren-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent line breaks inside function parentheses", + recommended: false, + url: "https://eslint.org/docs/latest/rules/function-paren-newline", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: [ + "always", + "never", + "consistent", + "multiline", + "multiline-arguments", + ], + }, + { + type: "object", + properties: { + minItems: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + expectedBefore: "Expected newline before ')'.", + expectedAfter: "Expected newline after '('.", + expectedBetween: "Expected newline between arguments/params.", + unexpectedBefore: "Unexpected newline before ')'.", + unexpectedAfter: "Unexpected newline after '('.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const rawOption = context.options[0] || "multiline"; + const multilineOption = rawOption === "multiline"; + const multilineArgumentsOption = rawOption === "multiline-arguments"; + const consistentOption = rawOption === "consistent"; + let minItems; + + if (typeof rawOption === "object") { + minItems = rawOption.minItems; + } else if (rawOption === "always") { + minItems = 0; + } else if (rawOption === "never") { + minItems = Infinity; + } else { + minItems = null; + } + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Determines whether there should be newlines inside function parens + * @param {ASTNode[]} elements The arguments or parameters in the list + * @param {boolean} hasLeftNewline `true` if the left paren has a newline in the current code. + * @returns {boolean} `true` if there should be newlines inside the function parens + */ + function shouldHaveNewlines(elements, hasLeftNewline) { + if (multilineArgumentsOption && elements.length === 1) { + return hasLeftNewline; + } + if (multilineOption || multilineArgumentsOption) { + return elements.some( + (element, index) => + index !== elements.length - 1 && + element.loc.end.line !== + elements[index + 1].loc.start.line, + ); + } + if (consistentOption) { + return hasLeftNewline; + } + return elements.length >= minItems; + } + + /** + * Validates parens + * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token + * @param {ASTNode[]} elements The arguments or parameters in the list + * @returns {void} + */ + function validateParens(parens, elements) { + const leftParen = parens.leftParen; + const rightParen = parens.rightParen; + const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); + const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen); + const hasLeftNewline = !astUtils.isTokenOnSameLine( + leftParen, + tokenAfterLeftParen, + ); + const hasRightNewline = !astUtils.isTokenOnSameLine( + tokenBeforeRightParen, + rightParen, + ); + const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); + + if (hasLeftNewline && !needsNewlines) { + context.report({ + node: leftParen, + messageId: "unexpectedAfter", + fix(fixer) { + return sourceCode + .getText() + .slice( + leftParen.range[1], + tokenAfterLeftParen.range[0], + ) + .trim() + ? // If there is a comment between the ( and the first element, don't do a fix. + null + : fixer.removeRange([ + leftParen.range[1], + tokenAfterLeftParen.range[0], + ]); + }, + }); + } else if (!hasLeftNewline && needsNewlines) { + context.report({ + node: leftParen, + messageId: "expectedAfter", + fix: fixer => fixer.insertTextAfter(leftParen, "\n"), + }); + } + + if (hasRightNewline && !needsNewlines) { + context.report({ + node: rightParen, + messageId: "unexpectedBefore", + fix(fixer) { + return sourceCode + .getText() + .slice( + tokenBeforeRightParen.range[1], + rightParen.range[0], + ) + .trim() + ? // If there is a comment between the last element and the ), don't do a fix. + null + : fixer.removeRange([ + tokenBeforeRightParen.range[1], + rightParen.range[0], + ]); + }, + }); + } else if (!hasRightNewline && needsNewlines) { + context.report({ + node: rightParen, + messageId: "expectedBefore", + fix: fixer => fixer.insertTextBefore(rightParen, "\n"), + }); + } + } + + /** + * Validates a list of arguments or parameters + * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token + * @param {ASTNode[]} elements The arguments or parameters in the list + * @returns {void} + */ + function validateArguments(parens, elements) { + const leftParen = parens.leftParen; + const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); + const hasLeftNewline = !astUtils.isTokenOnSameLine( + leftParen, + tokenAfterLeftParen, + ); + const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); + + for (let i = 0; i <= elements.length - 2; i++) { + const currentElement = elements[i]; + const nextElement = elements[i + 1]; + const hasNewLine = + currentElement.loc.end.line !== nextElement.loc.start.line; + + if (!hasNewLine && needsNewlines) { + context.report({ + node: currentElement, + messageId: "expectedBetween", + fix: fixer => fixer.insertTextBefore(nextElement, "\n"), + }); + } + } + } + + /** + * Gets the left paren and right paren tokens of a node. + * @param {ASTNode} node The node with parens + * @throws {TypeError} Unexpected node type. + * @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token. + * Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression + * with a single parameter) + */ + function getParenTokens(node) { + switch (node.type) { + case "NewExpression": + if ( + !node.arguments.length && + !( + astUtils.isOpeningParenToken( + sourceCode.getLastToken(node, { skip: 1 }), + ) && + astUtils.isClosingParenToken( + sourceCode.getLastToken(node), + ) && + node.callee.range[1] < node.range[1] + ) + ) { + // If the NewExpression does not have parens (e.g. `new Foo`), return null. + return null; + } + + // falls through + + case "CallExpression": + return { + leftParen: sourceCode.getTokenAfter( + node.callee, + astUtils.isOpeningParenToken, + ), + rightParen: sourceCode.getLastToken(node), + }; + + case "FunctionDeclaration": + case "FunctionExpression": { + const leftParen = sourceCode.getFirstToken( + node, + astUtils.isOpeningParenToken, + ); + const rightParen = node.params.length + ? sourceCode.getTokenAfter( + node.params.at(-1), + astUtils.isClosingParenToken, + ) + : sourceCode.getTokenAfter(leftParen); + + return { leftParen, rightParen }; + } + + case "ArrowFunctionExpression": { + const firstToken = sourceCode.getFirstToken(node, { + skip: node.async ? 1 : 0, + }); + + if (!astUtils.isOpeningParenToken(firstToken)) { + // If the ArrowFunctionExpression has a single param without parens, return null. + return null; + } + + const rightParen = node.params.length + ? sourceCode.getTokenAfter( + node.params.at(-1), + astUtils.isClosingParenToken, + ) + : sourceCode.getTokenAfter(firstToken); + + return { + leftParen: firstToken, + rightParen, + }; + } + + case "ImportExpression": { + const leftParen = sourceCode.getFirstToken(node, 1); + const rightParen = sourceCode.getLastToken(node); + + return { leftParen, rightParen }; + } + + default: + throw new TypeError( + `unexpected node with type ${node.type}`, + ); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + [[ + "ArrowFunctionExpression", + "CallExpression", + "FunctionDeclaration", + "FunctionExpression", + "ImportExpression", + "NewExpression", + ]](node) { + const parens = getParenTokens(node); + let params; + + if (node.type === "ImportExpression") { + params = [node.source]; + } else if (astUtils.isFunction(node)) { + params = node.params; + } else { + params = node.arguments; + } + + if (parens) { + validateParens(parens, params); + + if (multilineArgumentsOption) { + validateArguments(parens, params); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/generator-star-spacing.js b/node_modules/eslint/lib/rules/generator-star-spacing.js new file mode 100644 index 00000000..c046ea7f --- /dev/null +++ b/node_modules/eslint/lib/rules/generator-star-spacing.js @@ -0,0 +1,246 @@ +/** + * @fileoverview Rule to check the spacing around the * in generator functions. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const OVERRIDE_SCHEMA = { + oneOf: [ + { + enum: ["before", "after", "both", "neither"], + }, + { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "generator-star-spacing", + url: "https://eslint.style/rules/js/generator-star-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing around `*` operators in generator functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/generator-star-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["before", "after", "both", "neither"], + }, + { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" }, + named: OVERRIDE_SCHEMA, + anonymous: OVERRIDE_SCHEMA, + method: OVERRIDE_SCHEMA, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + missingBefore: "Missing space before *.", + missingAfter: "Missing space after *.", + unexpectedBefore: "Unexpected space before *.", + unexpectedAfter: "Unexpected space after *.", + }, + }, + + create(context) { + const optionDefinitions = { + before: { before: true, after: false }, + after: { before: false, after: true }, + both: { before: true, after: true }, + neither: { before: false, after: false }, + }; + + /** + * Returns resolved option definitions based on an option and defaults + * @param {any} option The option object or string value + * @param {Object} defaults The defaults to use if options are not present + * @returns {Object} the resolved object definition + */ + function optionToDefinition(option, defaults) { + if (!option) { + return defaults; + } + + return typeof option === "string" + ? optionDefinitions[option] + : Object.assign({}, defaults, option); + } + + const modes = (function (option) { + const defaults = optionToDefinition( + option, + optionDefinitions.before, + ); + + return { + named: optionToDefinition(option.named, defaults), + anonymous: optionToDefinition(option.anonymous, defaults), + method: optionToDefinition(option.method, defaults), + }; + })(context.options[0] || {}); + + const sourceCode = context.sourceCode; + + /** + * Checks if the given token is a star token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a star token. + */ + function isStarToken(token) { + return token.value === "*" && token.type === "Punctuator"; + } + + /** + * Gets the generator star token of the given function node. + * @param {ASTNode} node The function node to get. + * @returns {Token} Found star token. + */ + function getStarToken(node) { + return sourceCode.getFirstToken( + node.parent.method || node.parent.type === "MethodDefinition" + ? node.parent + : node, + isStarToken, + ); + } + + /** + * capitalize a given string. + * @param {string} str the given string. + * @returns {string} the capitalized string. + */ + function capitalize(str) { + return str[0].toUpperCase() + str.slice(1); + } + + /** + * Checks the spacing between two tokens before or after the star token. + * @param {string} kind Either "named", "anonymous", or "method" + * @param {string} side Either "before" or "after". + * @param {Token} leftToken `function` keyword token if side is "before", or + * star token if side is "after". + * @param {Token} rightToken Star token if side is "before", or identifier + * token if side is "after". + * @returns {void} + */ + function checkSpacing(kind, side, leftToken, rightToken) { + if ( + !!(rightToken.range[0] - leftToken.range[1]) !== + modes[kind][side] + ) { + const after = leftToken.value === "*"; + const spaceRequired = modes[kind][side]; + const node = after ? leftToken : rightToken; + const messageId = `${spaceRequired ? "missing" : "unexpected"}${capitalize(side)}`; + + context.report({ + node, + messageId, + fix(fixer) { + if (spaceRequired) { + if (after) { + return fixer.insertTextAfter(node, " "); + } + return fixer.insertTextBefore(node, " "); + } + return fixer.removeRange([ + leftToken.range[1], + rightToken.range[0], + ]); + }, + }); + } + } + + /** + * Enforces the spacing around the star if node is a generator function. + * @param {ASTNode} node A function expression or declaration node. + * @returns {void} + */ + function checkFunction(node) { + if (!node.generator) { + return; + } + + const starToken = getStarToken(node); + const prevToken = sourceCode.getTokenBefore(starToken); + const nextToken = sourceCode.getTokenAfter(starToken); + + let kind = "named"; + + if ( + node.parent.type === "MethodDefinition" || + (node.parent.type === "Property" && node.parent.method) + ) { + kind = "method"; + } else if (!node.id) { + kind = "anonymous"; + } + + // Only check before when preceded by `function`|`static` keyword + if ( + !( + kind === "method" && + starToken === sourceCode.getFirstToken(node.parent) + ) + ) { + checkSpacing(kind, "before", prevToken, starToken); + } + + checkSpacing(kind, "after", starToken, nextToken); + } + + return { + FunctionDeclaration: checkFunction, + FunctionExpression: checkFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/getter-return.js b/node_modules/eslint/lib/rules/getter-return.js new file mode 100644 index 00000000..9915597d --- /dev/null +++ b/node_modules/eslint/lib/rules/getter-return.js @@ -0,0 +1,242 @@ +/** + * @fileoverview Enforces that a return statement is present in property getters. + * @author Aladdin-ADD(hh_2013@foxmail.com) + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u; + +/** + * Checks all segments in a set and returns true if any are reachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if any segment is reachable; false otherwise. + */ +function isAnySegmentReachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return true; + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowImplicit: false, + }, + ], + + docs: { + description: "Enforce `return` statements in getters", + recommended: true, + url: "https://eslint.org/docs/latest/rules/getter-return", + }, + + fixable: null, + + schema: [ + { + type: "object", + properties: { + allowImplicit: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expected: "Expected to return a value in {{name}}.", + expectedAlways: "Expected {{name}} to always return a value.", + }, + }, + + create(context) { + const [{ allowImplicit }] = context.options; + const sourceCode = context.sourceCode; + + let funcInfo = { + upper: null, + codePath: null, + hasReturn: false, + shouldCheck: false, + node: null, + currentSegments: [], + }; + + /** + * Checks whether or not the last code path segment is reachable. + * Then reports this function if the segment is reachable. + * + * If the last code path segment is reachable, there are paths which are not + * returned or thrown. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function checkLastSegment(node) { + if ( + funcInfo.shouldCheck && + isAnySegmentReachable(funcInfo.currentSegments) + ) { + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId: funcInfo.hasReturn + ? "expectedAlways" + : "expected", + data: { + name: astUtils.getFunctionNameWithKind(funcInfo.node), + }, + }); + } + } + + /** + * Checks whether a node means a getter function. + * @param {ASTNode} node a node to check. + * @returns {boolean} if node means a getter, return true; else return false. + */ + function isGetter(node) { + const parent = node.parent; + + if ( + TARGET_NODE_TYPE.test(node.type) && + node.body.type === "BlockStatement" + ) { + if (parent.kind === "get") { + return true; + } + if ( + parent.type === "Property" && + astUtils.getStaticPropertyName(parent) === "get" && + parent.parent.type === "ObjectExpression" + ) { + // Object.defineProperty() or Reflect.defineProperty() + if (parent.parent.parent.type === "CallExpression") { + const callNode = parent.parent.parent.callee; + + if ( + astUtils.isSpecificMemberAccess( + callNode, + "Object", + "defineProperty", + ) || + astUtils.isSpecificMemberAccess( + callNode, + "Reflect", + "defineProperty", + ) + ) { + return true; + } + } + + // Object.defineProperties() or Object.create() + if ( + parent.parent.parent.type === "Property" && + parent.parent.parent.parent.type === + "ObjectExpression" && + parent.parent.parent.parent.parent.type === + "CallExpression" + ) { + const callNode = + parent.parent.parent.parent.parent.callee; + + return ( + astUtils.isSpecificMemberAccess( + callNode, + "Object", + "defineProperties", + ) || + astUtils.isSpecificMemberAccess( + callNode, + "Object", + "create", + ) + ); + } + } + } + return false; + } + return { + // Stacks this function's information. + onCodePathStart(codePath, node) { + funcInfo = { + upper: funcInfo, + codePath, + hasReturn: false, + shouldCheck: isGetter(node), + node, + currentSegments: new Set(), + }; + }, + + // Pops this function's information. + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + // Checks the return statement is valid. + ReturnStatement(node) { + if (funcInfo.shouldCheck) { + funcInfo.hasReturn = true; + + // if allowImplicit: false, should also check node.argument + if (!allowImplicit && !node.argument) { + context.report({ + node, + messageId: "expected", + data: { + name: astUtils.getFunctionNameWithKind( + funcInfo.node, + ), + }, + }); + } + } + }, + + // Reports a given function if the last path is reachable. + "FunctionExpression:exit": checkLastSegment, + "ArrowFunctionExpression:exit": checkLastSegment, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/global-require.js b/node_modules/eslint/lib/rules/global-require.js new file mode 100644 index 00000000..dc9bf1e3 --- /dev/null +++ b/node_modules/eslint/lib/rules/global-require.js @@ -0,0 +1,117 @@ +/** + * @fileoverview Rule for disallowing require() outside of the top-level module context + * @author Jamund Ferguson + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +const ACCEPTABLE_PARENTS = new Set([ + "AssignmentExpression", + "VariableDeclarator", + "MemberExpression", + "ExpressionStatement", + "CallExpression", + "ConditionalExpression", + "Program", + "VariableDeclaration", + "ChainExpression", +]); + +/** + * Finds the eslint-scope reference in the given scope. + * @param {Object} scope The scope to search. + * @param {ASTNode} node The identifier node. + * @returns {Reference|null} Returns the found reference or null if none were found. + */ +function findReference(scope, node) { + const references = scope.references.filter( + reference => + reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1], + ); + + if (references.length === 1) { + return references[0]; + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks if the given identifier node is shadowed in the given scope. + * @param {Object} scope The current scope. + * @param {ASTNode} node The identifier node to check. + * @returns {boolean} Whether or not the name is shadowed. + */ +function isShadowed(scope, node) { + const reference = findReference(scope, node); + + return ( + reference && reference.resolved && reference.resolved.defs.length > 0 + ); +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "global-require", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/global-require.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: + "Require `require()` calls to be placed at top-level module scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/global-require", + }, + + schema: [], + messages: { + unexpected: "Unexpected require().", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + const currentScope = sourceCode.getScope(node); + + if ( + node.callee.name === "require" && + !isShadowed(currentScope, node.callee) + ) { + const isGoodRequire = sourceCode + .getAncestors(node) + .every(parent => ACCEPTABLE_PARENTS.has(parent.type)); + + if (!isGoodRequire) { + context.report({ node, messageId: "unexpected" }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/grouped-accessor-pairs.js b/node_modules/eslint/lib/rules/grouped-accessor-pairs.js new file mode 100644 index 00000000..ad6783f0 --- /dev/null +++ b/node_modules/eslint/lib/rules/grouped-accessor-pairs.js @@ -0,0 +1,237 @@ +/** + * @fileoverview Rule to require grouped accessor pairs in object literals and classes + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * Property name if it can be computed statically, otherwise the list of the tokens of the key node. + * @typedef {string|Token[]} Key + */ + +/** + * Accessor nodes with the same key. + * @typedef {Object} AccessorData + * @property {Key} key Accessor's key + * @property {ASTNode[]} getters List of getter nodes. + * @property {ASTNode[]} setters List of setter nodes. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not the given lists represent the equal tokens in the same order. + * Tokens are compared by their properties, not by instance. + * @param {Token[]} left First list of tokens. + * @param {Token[]} right Second list of tokens. + * @returns {boolean} `true` if the lists have same tokens. + */ +function areEqualTokenLists(left, right) { + if (left.length !== right.length) { + return false; + } + + for (let i = 0; i < left.length; i++) { + const leftToken = left[i], + rightToken = right[i]; + + if ( + leftToken.type !== rightToken.type || + leftToken.value !== rightToken.value + ) { + return false; + } + } + + return true; +} + +/** + * Checks whether or not the given keys are equal. + * @param {Key} left First key. + * @param {Key} right Second key. + * @returns {boolean} `true` if the keys are equal. + */ +function areEqualKeys(left, right) { + if (typeof left === "string" && typeof right === "string") { + // Statically computed names. + return left === right; + } + if (Array.isArray(left) && Array.isArray(right)) { + // Token lists. + return areEqualTokenLists(left, right); + } + + return false; +} + +/** + * Checks whether or not a given node is of an accessor kind ('get' or 'set'). + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is of an accessor kind. + */ +function isAccessorKind(node) { + return node.kind === "get" || node.kind === "set"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["anyOrder"], + + docs: { + description: + "Require grouped accessor pairs in object literals and classes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/grouped-accessor-pairs", + }, + + schema: [ + { + enum: ["anyOrder", "getBeforeSet", "setBeforeGet"], + }, + ], + + messages: { + notGrouped: + "Accessor pair {{ formerName }} and {{ latterName }} should be grouped.", + invalidOrder: + "Expected {{ latterName }} to be before {{ formerName }}.", + }, + }, + + create(context) { + const [order] = context.options; + const sourceCode = context.sourceCode; + + /** + * Reports the given accessor pair. + * @param {string} messageId messageId to report. + * @param {ASTNode} formerNode getter/setter node that is defined before `latterNode`. + * @param {ASTNode} latterNode getter/setter node that is defined after `formerNode`. + * @returns {void} + * @private + */ + function report(messageId, formerNode, latterNode) { + context.report({ + node: latterNode, + messageId, + loc: astUtils.getFunctionHeadLoc(latterNode.value, sourceCode), + data: { + formerName: astUtils.getFunctionNameWithKind( + formerNode.value, + ), + latterName: astUtils.getFunctionNameWithKind( + latterNode.value, + ), + }, + }); + } + + /** + * Checks accessor pairs in the given list of nodes. + * @param {ASTNode[]} nodes The list to check. + * @param {Function} shouldCheck – Predicate that returns `true` if the node should be checked. + * @returns {void} + * @private + */ + function checkList(nodes, shouldCheck) { + const accessors = []; + let found = false; + + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + + if (shouldCheck(node) && isAccessorKind(node)) { + // Creates a new `AccessorData` object for the given getter or setter node. + const name = astUtils.getStaticPropertyName(node); + const key = + name !== null ? name : sourceCode.getTokens(node.key); + + // Merges the given `AccessorData` object into the given accessors list. + for (let j = 0; j < accessors.length; j++) { + const accessor = accessors[j]; + + if (areEqualKeys(accessor.key, key)) { + accessor.getters.push( + ...(node.kind === "get" ? [node] : []), + ); + accessor.setters.push( + ...(node.kind === "set" ? [node] : []), + ); + found = true; + break; + } + } + if (!found) { + accessors.push({ + key, + getters: node.kind === "get" ? [node] : [], + setters: node.kind === "set" ? [node] : [], + }); + } + found = false; + } + } + + for (const { getters, setters } of accessors) { + // Don't report accessor properties that have duplicate getters or setters. + if (getters.length === 1 && setters.length === 1) { + const [getter] = getters, + [setter] = setters, + getterIndex = nodes.indexOf(getter), + setterIndex = nodes.indexOf(setter), + formerNode = + getterIndex < setterIndex ? getter : setter, + latterNode = + getterIndex < setterIndex ? setter : getter; + + if (Math.abs(getterIndex - setterIndex) > 1) { + report("notGrouped", formerNode, latterNode); + } else if ( + (order === "getBeforeSet" && + getterIndex > setterIndex) || + (order === "setBeforeGet" && getterIndex < setterIndex) + ) { + report("invalidOrder", formerNode, latterNode); + } + } + } + } + + return { + ObjectExpression(node) { + checkList(node.properties, n => n.type === "Property"); + }, + ClassBody(node) { + checkList( + node.body, + n => n.type === "MethodDefinition" && !n.static, + ); + checkList( + node.body, + n => n.type === "MethodDefinition" && n.static, + ); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/guard-for-in.js b/node_modules/eslint/lib/rules/guard-for-in.js new file mode 100644 index 00000000..f648aa40 --- /dev/null +++ b/node_modules/eslint/lib/rules/guard-for-in.js @@ -0,0 +1,85 @@ +/** + * @fileoverview Rule to flag for-in loops without if statements inside + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `for-in` loops to include an `if` statement", + recommended: false, + url: "https://eslint.org/docs/latest/rules/guard-for-in", + }, + + schema: [], + messages: { + wrap: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype.", + }, + }, + + create(context) { + return { + ForInStatement(node) { + const body = node.body; + + // empty statement + if (body.type === "EmptyStatement") { + return; + } + + // if statement + if (body.type === "IfStatement") { + return; + } + + // empty block + if (body.type === "BlockStatement" && body.body.length === 0) { + return; + } + + // block with just if statement + if ( + body.type === "BlockStatement" && + body.body.length === 1 && + body.body[0].type === "IfStatement" + ) { + return; + } + + // block that starts with if statement + if ( + body.type === "BlockStatement" && + body.body.length >= 1 && + body.body[0].type === "IfStatement" + ) { + const i = body.body[0]; + + // ... whose consequent is a continue + if (i.consequent.type === "ContinueStatement") { + return; + } + + // ... whose consequent is a block that contains only a continue + if ( + i.consequent.type === "BlockStatement" && + i.consequent.body.length === 1 && + i.consequent.body[0].type === "ContinueStatement" + ) { + return; + } + } + + context.report({ node, messageId: "wrap" }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/handle-callback-err.js b/node_modules/eslint/lib/rules/handle-callback-err.js new file mode 100644 index 00000000..83683b55 --- /dev/null +++ b/node_modules/eslint/lib/rules/handle-callback-err.js @@ -0,0 +1,122 @@ +/** + * @fileoverview Ensure handling of errors when we know they exist. + * @author Jamund Ferguson + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "handle-callback-err", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/handle-callback-err.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Require error handling in callbacks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/handle-callback-err", + }, + + schema: [ + { + type: "string", + }, + ], + messages: { + expected: "Expected error to be handled.", + }, + }, + + create(context) { + const errorArgument = context.options[0] || "err"; + const sourceCode = context.sourceCode; + + /** + * Checks if the given argument should be interpreted as a regexp pattern. + * @param {string} stringToCheck The string which should be checked. + * @returns {boolean} Whether or not the string should be interpreted as a pattern. + */ + function isPattern(stringToCheck) { + const firstChar = stringToCheck[0]; + + return firstChar === "^"; + } + + /** + * Checks if the given name matches the configured error argument. + * @param {string} name The name which should be compared. + * @returns {boolean} Whether or not the given name matches the configured error variable name. + */ + function matchesConfiguredErrorName(name) { + if (isPattern(errorArgument)) { + const regexp = new RegExp(errorArgument, "u"); + + return regexp.test(name); + } + return name === errorArgument; + } + + /** + * Get the parameters of a given function scope. + * @param {Object} scope The function scope. + * @returns {Array} All parameters of the given scope. + */ + function getParameters(scope) { + return scope.variables.filter( + variable => + variable.defs[0] && variable.defs[0].type === "Parameter", + ); + } + + /** + * Check to see if we're handling the error object properly. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function checkForError(node) { + const scope = sourceCode.getScope(node), + parameters = getParameters(scope), + firstParameter = parameters[0]; + + if ( + firstParameter && + matchesConfiguredErrorName(firstParameter.name) + ) { + if (firstParameter.references.length === 0) { + context.report({ node, messageId: "expected" }); + } + } + } + + return { + FunctionDeclaration: checkForError, + FunctionExpression: checkForError, + ArrowFunctionExpression: checkForError, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/id-blacklist.js b/node_modules/eslint/lib/rules/id-blacklist.js new file mode 100644 index 00000000..528f2e9d --- /dev/null +++ b/node_modules/eslint/lib/rules/id-blacklist.js @@ -0,0 +1,241 @@ +/** + * @fileoverview Rule that warns when identifier names that are + * specified in the configuration are used. + * @author Keith Cirkel (http://keithcirkel.co.uk) + * @deprecated in ESLint v7.5.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given node represents assignment target in a normal assignment or destructuring. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is assignment target. + */ +function isAssignmentTarget(node) { + const parent = node.parent; + + return ( + // normal assignment + (parent.type === "AssignmentExpression" && parent.left === node) || + // destructuring + parent.type === "ArrayPattern" || + parent.type === "RestElement" || + (parent.type === "Property" && + parent.value === node && + parent.parent.type === "ObjectPattern") || + (parent.type === "AssignmentPattern" && parent.left === node) + ); +} + +/** + * Checks whether the given node represents an imported name that is renamed in the same import/export specifier. + * + * Examples: + * import { a as b } from 'mod'; // node `a` is renamed import + * export { a as b } from 'mod'; // node `a` is renamed import + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a renamed import. + */ +function isRenamedImport(node) { + const parent = node.parent; + + return ( + (parent.type === "ImportSpecifier" && + parent.imported !== parent.local && + parent.imported === node) || + (parent.type === "ExportSpecifier" && + parent.parent.source && // re-export + parent.local !== parent.exported && + parent.local === node) + ); +} + +/** + * Checks whether the given node is a renamed identifier node in an ObjectPattern destructuring. + * + * Examples: + * const { a : b } = foo; // node `a` is renamed node. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a renamed node in an ObjectPattern destructuring. + */ +function isRenamedInDestructuring(node) { + const parent = node.parent; + + return ( + !parent.computed && + parent.type === "Property" && + parent.parent.type === "ObjectPattern" && + parent.value !== node && + parent.key === node + ); +} + +/** + * Checks whether the given node represents shorthand definition of a property in an object literal. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a shorthand property definition. + */ +function isShorthandPropertyDefinition(node) { + const parent = node.parent; + + return ( + parent.type === "Property" && + parent.parent.type === "ObjectExpression" && + parent.shorthand + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "The rule was renamed.", + url: "https://eslint.org/blog/2020/07/eslint-v7.5.0-released/#deprecating-id-blacklist", + deprecatedSince: "7.5.0", + availableUntil: null, + replacedBy: [ + { + rule: { + name: "id-denylist", + url: "https://eslint.org/docs/rules/id-denylist", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow specified identifiers", + recommended: false, + url: "https://eslint.org/docs/latest/rules/id-blacklist", + }, + + schema: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + messages: { + restricted: "Identifier '{{name}}' is restricted.", + }, + }, + + create(context) { + const denyList = new Set(context.options); + const reportedNodes = new Set(); + const sourceCode = context.sourceCode; + + let globalScope; + + /** + * Checks whether the given name is restricted. + * @param {string} name The name to check. + * @returns {boolean} `true` if the name is restricted. + * @private + */ + function isRestricted(name) { + return denyList.has(name); + } + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return ( + variable && + variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node) + ); + } + + /** + * Determines whether the given node should be checked. + * @param {ASTNode} node `Identifier` node. + * @returns {boolean} `true` if the node should be checked. + */ + function shouldCheck(node) { + const parent = node.parent; + + /* + * Member access has special rules for checking property names. + * Read access to a property with a restricted name is allowed, because it can be on an object that user has no control over. + * Write access isn't allowed, because it potentially creates a new property with a restricted name. + */ + if ( + parent.type === "MemberExpression" && + parent.property === node && + !parent.computed + ) { + return isAssignmentTarget(parent); + } + + return ( + parent.type !== "CallExpression" && + parent.type !== "NewExpression" && + !isRenamedImport(node) && + !isRenamedInDestructuring(node) && + !( + isReferenceToGlobalVariable(node) && + !isShorthandPropertyDefinition(node) + ) + ); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (!reportedNodes.has(node.range.toString())) { + context.report({ + node, + messageId: "restricted", + data: { + name: node.name, + }, + }); + reportedNodes.add(node.range.toString()); + } + } + + return { + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + Identifier(node) { + if (isRestricted(node.name) && shouldCheck(node)) { + report(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/id-denylist.js b/node_modules/eslint/lib/rules/id-denylist.js new file mode 100644 index 00000000..5b9a7f4a --- /dev/null +++ b/node_modules/eslint/lib/rules/id-denylist.js @@ -0,0 +1,223 @@ +/** + * @fileoverview Rule that warns when identifier names that are + * specified in the configuration are used. + * @author Keith Cirkel (http://keithcirkel.co.uk) + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given node represents assignment target in a normal assignment or destructuring. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is assignment target. + */ +function isAssignmentTarget(node) { + const parent = node.parent; + + return ( + // normal assignment + (parent.type === "AssignmentExpression" && parent.left === node) || + // destructuring + parent.type === "ArrayPattern" || + parent.type === "RestElement" || + (parent.type === "Property" && + parent.value === node && + parent.parent.type === "ObjectPattern") || + (parent.type === "AssignmentPattern" && parent.left === node) + ); +} + +/** + * Checks whether the given node represents an imported name that is renamed in the same import/export specifier. + * + * Examples: + * import { a as b } from 'mod'; // node `a` is renamed import + * export { a as b } from 'mod'; // node `a` is renamed import + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a renamed import. + */ +function isRenamedImport(node) { + const parent = node.parent; + + return ( + (parent.type === "ImportSpecifier" && + parent.imported !== parent.local && + parent.imported === node) || + (parent.type === "ExportSpecifier" && + parent.parent.source && // re-export + parent.local !== parent.exported && + parent.local === node) + ); +} + +/** + * Checks whether the given node is an ObjectPattern destructuring. + * + * Examples: + * const { a : b } = foo; + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is in an ObjectPattern destructuring. + */ +function isPropertyNameInDestructuring(node) { + const parent = node.parent; + + return ( + !parent.computed && + parent.type === "Property" && + parent.parent.type === "ObjectPattern" && + parent.key === node + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [], + + docs: { + description: "Disallow specified identifiers", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/id-denylist", + }, + + schema: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + messages: { + restricted: "Identifier '{{name}}' is restricted.", + restrictedPrivate: "Identifier '#{{name}}' is restricted.", + }, + }, + + create(context) { + const denyList = new Set(context.options); + const reportedNodes = new Set(); + const sourceCode = context.sourceCode; + + let globalScope; + + /** + * Checks whether the given name is restricted. + * @param {string} name The name to check. + * @returns {boolean} `true` if the name is restricted. + * @private + */ + function isRestricted(name) { + return denyList.has(name); + } + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return ( + variable && + variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node) + ); + } + + /** + * Determines whether the given node should be checked. + * @param {ASTNode} node `Identifier` node. + * @returns {boolean} `true` if the node should be checked. + */ + function shouldCheck(node) { + // Import attributes are defined by environments, so naming conventions shouldn't apply to them + if (astUtils.isImportAttributeKey(node)) { + return false; + } + + const parent = node.parent; + + /* + * Member access has special rules for checking property names. + * Read access to a property with a restricted name is allowed, because it can be on an object that user has no control over. + * Write access isn't allowed, because it potentially creates a new property with a restricted name. + */ + if ( + parent.type === "MemberExpression" && + parent.property === node && + !parent.computed + ) { + return isAssignmentTarget(parent); + } + + return ( + parent.type !== "CallExpression" && + parent.type !== "NewExpression" && + !isRenamedImport(node) && + !isPropertyNameInDestructuring(node) && + !isReferenceToGlobalVariable(node) + ); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (!reportedNodes.has(node.range.toString())) { + const isPrivate = node.type === "PrivateIdentifier"; + + context.report({ + node, + messageId: isPrivate ? "restrictedPrivate" : "restricted", + data: { + name: node.name, + }, + }); + reportedNodes.add(node.range.toString()); + } + } + + return { + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + [["Identifier", "PrivateIdentifier"]](node) { + if (isRestricted(node.name) && shouldCheck(node)) { + report(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/id-length.js b/node_modules/eslint/lib/rules/id-length.js new file mode 100644 index 00000000..133b8419 --- /dev/null +++ b/node_modules/eslint/lib/rules/id-length.js @@ -0,0 +1,217 @@ +/** + * @fileoverview Rule that warns when identifier names are shorter or longer + * than the values provided in configuration. + * @author Burak Yigit Kaya aka BYK + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getGraphemeCount } = require("../shared/string-utils"); +const { + getModuleExportName, + isImportAttributeKey, +} = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + exceptionPatterns: [], + exceptions: [], + min: 2, + properties: "always", + }, + ], + + docs: { + description: "Enforce minimum and maximum identifier lengths", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/id-length", + }, + + schema: [ + { + type: "object", + properties: { + min: { + type: "integer", + }, + max: { + type: "integer", + }, + exceptions: { + type: "array", + uniqueItems: true, + items: { + type: "string", + }, + }, + exceptionPatterns: { + type: "array", + uniqueItems: true, + items: { + type: "string", + }, + }, + properties: { + enum: ["always", "never"], + }, + }, + additionalProperties: false, + }, + ], + messages: { + tooShort: "Identifier name '{{name}}' is too short (< {{min}}).", + tooShortPrivate: + "Identifier name '#{{name}}' is too short (< {{min}}).", + tooLong: "Identifier name '{{name}}' is too long (> {{max}}).", + tooLongPrivate: + "Identifier name #'{{name}}' is too long (> {{max}}).", + }, + }, + + create(context) { + const [options] = context.options; + const { max: maxLength = Infinity, min: minLength } = options; + const properties = options.properties !== "never"; + const exceptions = new Set(options.exceptions); + const exceptionPatterns = options.exceptionPatterns.map( + pattern => new RegExp(pattern, "u"), + ); + const reportedNodes = new Set(); + + /** + * Checks if a string matches the provided exception patterns + * @param {string} name The string to check. + * @returns {boolean} if the string is a match + * @private + */ + function matchesExceptionPattern(name) { + return exceptionPatterns.some(pattern => pattern.test(name)); + } + + const SUPPORTED_EXPRESSIONS = { + MemberExpression: + properties && + function (parent) { + return ( + !parent.computed && + // regular property assignment + ((parent.parent.left === parent && + parent.parent.type === "AssignmentExpression") || + // or the last identifier in an ObjectPattern destructuring + (parent.parent.type === "Property" && + parent.parent.value === parent && + parent.parent.parent.type === "ObjectPattern" && + parent.parent.parent.parent.left === + parent.parent.parent)) + ); + }, + AssignmentPattern(parent, node) { + return parent.left === node; + }, + VariableDeclarator(parent, node) { + return parent.id === node; + }, + Property(parent, node) { + if (parent.parent.type === "ObjectPattern") { + const isKeyAndValueSame = + parent.value.name === parent.key.name; + + return ( + (!isKeyAndValueSame && parent.value === node) || + (isKeyAndValueSame && parent.key === node && properties) + ); + } + return ( + properties && + !isImportAttributeKey(node) && + !parent.computed && + parent.key.name === node.name + ); + }, + ImportSpecifier(parent, node) { + return ( + parent.local === node && + getModuleExportName(parent.imported) !== + getModuleExportName(parent.local) + ); + }, + ImportDefaultSpecifier: true, + ImportNamespaceSpecifier: true, + RestElement: true, + FunctionExpression: true, + ArrowFunctionExpression: true, + ClassDeclaration: true, + FunctionDeclaration: true, + MethodDefinition: true, + PropertyDefinition: true, + CatchClause: true, + ArrayPattern: true, + }; + + return { + [["Identifier", "PrivateIdentifier"]](node) { + const name = node.name; + const parent = node.parent; + + const nameLength = getGraphemeCount(name); + + const isShort = nameLength < minLength; + const isLong = nameLength > maxLength; + + if ( + !(isShort || isLong) || + exceptions.has(name) || + matchesExceptionPattern(name) + ) { + return; // Nothing to report + } + + const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type]; + + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if ( + isValidExpression && + !reportedNodes.has(node.range.toString()) && + (isValidExpression === true || + isValidExpression(parent, node)) + ) { + reportedNodes.add(node.range.toString()); + + let messageId = isShort ? "tooShort" : "tooLong"; + + if (node.type === "PrivateIdentifier") { + messageId += "Private"; + } + + context.report({ + node, + messageId, + data: { name, min: minLength, max: maxLength }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/id-match.js b/node_modules/eslint/lib/rules/id-match.js new file mode 100644 index 00000000..2e70cc72 --- /dev/null +++ b/node_modules/eslint/lib/rules/id-match.js @@ -0,0 +1,363 @@ +/** + * @fileoverview Rule to flag non-matching identifiers + * @author Matthieu Larcher + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + "^.+$", + { + classFields: false, + ignoreDestructuring: false, + onlyDeclarations: false, + properties: false, + }, + ], + + docs: { + description: + "Require identifiers to match a specified regular expression", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/id-match", + }, + + schema: [ + { + type: "string", + }, + { + type: "object", + properties: { + properties: { + type: "boolean", + }, + classFields: { + type: "boolean", + }, + onlyDeclarations: { + type: "boolean", + }, + ignoreDestructuring: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + notMatch: + "Identifier '{{name}}' does not match the pattern '{{pattern}}'.", + notMatchPrivate: + "Identifier '#{{name}}' does not match the pattern '{{pattern}}'.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Options + //-------------------------------------------------------------------------- + const [ + pattern, + { + classFields: checkClassFields, + ignoreDestructuring, + onlyDeclarations, + properties: checkProperties, + }, + ] = context.options; + const regexp = new RegExp(pattern, "u"); + + const sourceCode = context.sourceCode; + let globalScope; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // contains reported nodes to avoid reporting twice on destructuring with shorthand notation + const reportedNodes = new Set(); + const ALLOWED_PARENT_TYPES = new Set([ + "CallExpression", + "NewExpression", + ]); + const DECLARATION_TYPES = new Set([ + "FunctionDeclaration", + "VariableDeclarator", + ]); + const IMPORT_TYPES = new Set([ + "ImportSpecifier", + "ImportNamespaceSpecifier", + "ImportDefaultSpecifier", + ]); + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return ( + variable && + variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node) + ); + } + + /** + * Checks if a string matches the provided pattern + * @param {string} name The string to check. + * @returns {boolean} if the string is a match + * @private + */ + function isInvalid(name) { + return !regexp.test(name); + } + + /** + * Checks if a parent of a node is an ObjectPattern. + * @param {ASTNode} node The node to check. + * @returns {boolean} if the node is inside an ObjectPattern + * @private + */ + function isInsideObjectPattern(node) { + let { parent } = node; + + while (parent) { + if (parent.type === "ObjectPattern") { + return true; + } + + parent = parent.parent; + } + + return false; + } + + /** + * Verifies if we should report an error or not based on the effective + * parent node and the identifier name. + * @param {ASTNode} effectiveParent The effective parent node of the node to be reported + * @param {string} name The identifier name of the identifier node + * @returns {boolean} whether an error should be reported or not + */ + function shouldReport(effectiveParent, name) { + return ( + (!onlyDeclarations || + DECLARATION_TYPES.has(effectiveParent.type)) && + !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && + isInvalid(name) + ); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (!reportedNodes.has(node.range.toString())) { + const messageId = + node.type === "PrivateIdentifier" + ? "notMatchPrivate" + : "notMatch"; + + context.report({ + node, + messageId, + data: { + name: node.name, + pattern, + }, + }); + reportedNodes.add(node.range.toString()); + } + } + + return { + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + Identifier(node) { + const name = node.name, + parent = node.parent, + effectiveParent = + parent.type === "MemberExpression" + ? parent.parent + : parent; + + if ( + isReferenceToGlobalVariable(node) || + astUtils.isImportAttributeKey(node) + ) { + return; + } + + if (parent.type === "MemberExpression") { + if (!checkProperties) { + return; + } + + // Always check object names + if ( + parent.object.type === "Identifier" && + parent.object.name === name + ) { + if (isInvalid(name)) { + report(node); + } + + // Report AssignmentExpressions left side's assigned variable id + } else if ( + effectiveParent.type === "AssignmentExpression" && + effectiveParent.left.type === "MemberExpression" && + effectiveParent.left.property.name === node.name + ) { + if (isInvalid(name)) { + report(node); + } + + // Report AssignmentExpressions only if they are the left side of the assignment + } else if ( + effectiveParent.type === "AssignmentExpression" && + effectiveParent.right.type !== "MemberExpression" + ) { + if (isInvalid(name)) { + report(node); + } + } + + // For https://github.com/eslint/eslint/issues/15123 + } else if ( + parent.type === "Property" && + parent.parent.type === "ObjectExpression" && + parent.key === node && + !parent.computed + ) { + if (checkProperties && isInvalid(name)) { + report(node); + } + + /* + * Properties have their own rules, and + * AssignmentPattern nodes can be treated like Properties: + * e.g.: const { no_camelcased = false } = bar; + */ + } else if ( + parent.type === "Property" || + parent.type === "AssignmentPattern" + ) { + if ( + parent.parent && + parent.parent.type === "ObjectPattern" + ) { + if ( + !ignoreDestructuring && + parent.shorthand && + parent.value.left && + isInvalid(name) + ) { + report(node); + } + + const assignmentKeyEqualsValue = + parent.key.name === parent.value.name; + + // prevent checking righthand side of destructured object + if (!assignmentKeyEqualsValue && parent.key === node) { + return; + } + + const valueIsInvalid = + parent.value.name && isInvalid(name); + + // ignore destructuring if the option is set, unless a new identifier is created + if ( + valueIsInvalid && + !(assignmentKeyEqualsValue && ignoreDestructuring) + ) { + report(node); + } + } + + // never check properties or always ignore destructuring + if ( + (!checkProperties && !parent.computed) || + (ignoreDestructuring && isInsideObjectPattern(node)) + ) { + return; + } + + // don't check right hand side of AssignmentExpression to prevent duplicate warnings + if ( + parent.right !== node && + shouldReport(effectiveParent, name) + ) { + report(node); + } + + // Check if it's an import specifier + } else if (IMPORT_TYPES.has(parent.type)) { + // Report only if the local imported identifier is invalid + if ( + parent.local && + parent.local.name === node.name && + isInvalid(name) + ) { + report(node); + } + } else if (parent.type === "PropertyDefinition") { + if (checkClassFields && isInvalid(name)) { + report(node); + } + + // Report anything that is invalid that isn't a CallExpression + } else if (shouldReport(effectiveParent, name)) { + report(node); + } + }, + + PrivateIdentifier(node) { + const isClassField = node.parent.type === "PropertyDefinition"; + + if (isClassField && !checkClassFields) { + return; + } + + if (isInvalid(node.name)) { + report(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js b/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js new file mode 100644 index 00000000..7f4b51b6 --- /dev/null +++ b/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js @@ -0,0 +1,125 @@ +/** + * @fileoverview enforce the location of arrow function bodies + * @author Sharmila Jesupaul + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const { isCommentToken, isNotOpeningParenToken } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "implicit-arrow-linebreak", + url: "https://eslint.style/rules/js/implicit-arrow-linebreak", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce the location of arrow function bodies", + recommended: false, + url: "https://eslint.org/docs/latest/rules/implicit-arrow-linebreak", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["beside", "below"], + }, + ], + messages: { + expected: "Expected a linebreak before this expression.", + unexpected: "Expected no linebreak before this expression.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0] || "beside"; + + /** + * Validates the location of an arrow function body + * @param {ASTNode} node The arrow function body + * @returns {void} + */ + function validateExpression(node) { + if (node.body.type === "BlockStatement") { + return; + } + + const arrowToken = sourceCode.getTokenBefore( + node.body, + isNotOpeningParenToken, + ); + const firstTokenOfBody = sourceCode.getTokenAfter(arrowToken); + + if ( + arrowToken.loc.end.line === firstTokenOfBody.loc.start.line && + option === "below" + ) { + context.report({ + node: firstTokenOfBody, + messageId: "expected", + fix: fixer => + fixer.insertTextBefore(firstTokenOfBody, "\n"), + }); + } else if ( + arrowToken.loc.end.line !== firstTokenOfBody.loc.start.line && + option === "beside" + ) { + context.report({ + node: firstTokenOfBody, + messageId: "unexpected", + fix(fixer) { + if ( + sourceCode.getFirstTokenBetween( + arrowToken, + firstTokenOfBody, + { + includeComments: true, + filter: isCommentToken, + }, + ) + ) { + return null; + } + + return fixer.replaceTextRange( + [arrowToken.range[1], firstTokenOfBody.range[0]], + " ", + ); + }, + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + return { + ArrowFunctionExpression: node => validateExpression(node), + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/indent-legacy.js b/node_modules/eslint/lib/rules/indent-legacy.js new file mode 100644 index 00000000..0f589c4f --- /dev/null +++ b/node_modules/eslint/lib/rules/indent-legacy.js @@ -0,0 +1,1368 @@ +/** + * @fileoverview This option sets a specific tab width for your code + * + * This rule has been ported and modified from nodeca. + * @author Vitaly Puzrin + * @author Gyandeep Singh + * @deprecated in ESLint v4.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +// this rule has known coverage issues, but it's deprecated and shouldn't be updated in the future anyway. +/* c8 ignore next */ +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent indentation", + recommended: false, + url: "https://eslint.org/docs/latest/rules/indent-legacy", + }, + + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "4.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "indent", + url: "https://eslint.style/rules/js/indent", + }, + }, + ], + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["tab"], + }, + { + type: "integer", + minimum: 0, + }, + ], + }, + { + type: "object", + properties: { + SwitchCase: { + type: "integer", + minimum: 0, + }, + VariableDeclarator: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + var: { + type: "integer", + minimum: 0, + }, + let: { + type: "integer", + minimum: 0, + }, + const: { + type: "integer", + minimum: 0, + }, + }, + }, + ], + }, + outerIIFEBody: { + type: "integer", + minimum: 0, + }, + MemberExpression: { + type: "integer", + minimum: 0, + }, + FunctionDeclaration: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + body: { + type: "integer", + minimum: 0, + }, + }, + }, + FunctionExpression: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + body: { + type: "integer", + minimum: 0, + }, + }, + }, + CallExpression: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + }, + }, + ArrayExpression: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + ObjectExpression: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + }, + additionalProperties: false, + }, + ], + messages: { + expected: + "Expected indentation of {{expected}} but found {{actual}}.", + }, + }, + + create(context) { + const DEFAULT_VARIABLE_INDENT = 1; + const DEFAULT_PARAMETER_INDENT = null; // For backwards compatibility, don't check parameter indentation unless specified in the config + const DEFAULT_FUNCTION_BODY_INDENT = 1; + + let indentType = "space"; + let indentSize = 4; + const options = { + SwitchCase: 0, + VariableDeclarator: { + var: DEFAULT_VARIABLE_INDENT, + let: DEFAULT_VARIABLE_INDENT, + const: DEFAULT_VARIABLE_INDENT, + }, + outerIIFEBody: null, + FunctionDeclaration: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + FunctionExpression: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + CallExpression: { + arguments: DEFAULT_PARAMETER_INDENT, + }, + ArrayExpression: 1, + ObjectExpression: 1, + }; + + const sourceCode = context.sourceCode; + + if (context.options.length) { + if (context.options[0] === "tab") { + indentSize = 1; + indentType = "tab"; + } /* c8 ignore start */ else if ( + typeof context.options[0] === "number" + ) { + indentSize = context.options[0]; + indentType = "space"; + } /* c8 ignore stop */ + + if (context.options[1]) { + const opts = context.options[1]; + + options.SwitchCase = opts.SwitchCase || 0; + const variableDeclaratorRules = opts.VariableDeclarator; + + if (typeof variableDeclaratorRules === "number") { + options.VariableDeclarator = { + var: variableDeclaratorRules, + let: variableDeclaratorRules, + const: variableDeclaratorRules, + }; + } else if (typeof variableDeclaratorRules === "object") { + Object.assign( + options.VariableDeclarator, + variableDeclaratorRules, + ); + } + + if (typeof opts.outerIIFEBody === "number") { + options.outerIIFEBody = opts.outerIIFEBody; + } + + if (typeof opts.MemberExpression === "number") { + options.MemberExpression = opts.MemberExpression; + } + + if (typeof opts.FunctionDeclaration === "object") { + Object.assign( + options.FunctionDeclaration, + opts.FunctionDeclaration, + ); + } + + if (typeof opts.FunctionExpression === "object") { + Object.assign( + options.FunctionExpression, + opts.FunctionExpression, + ); + } + + if (typeof opts.CallExpression === "object") { + Object.assign(options.CallExpression, opts.CallExpression); + } + + if ( + typeof opts.ArrayExpression === "number" || + typeof opts.ArrayExpression === "string" + ) { + options.ArrayExpression = opts.ArrayExpression; + } + + if ( + typeof opts.ObjectExpression === "number" || + typeof opts.ObjectExpression === "string" + ) { + options.ObjectExpression = opts.ObjectExpression; + } + } + } + + const caseIndentStore = {}; + + /** + * Creates an error message for a line, given the expected/actual indentation. + * @param {number} expectedAmount The expected amount of indentation characters for this line + * @param {number} actualSpaces The actual number of indentation spaces that were found on this line + * @param {number} actualTabs The actual number of indentation tabs that were found on this line + * @returns {string} An error message for this line + */ + function createErrorMessageData( + expectedAmount, + actualSpaces, + actualTabs, + ) { + const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" + const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" + const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" + let foundStatement; + + if (actualSpaces > 0 && actualTabs > 0) { + foundStatement = `${actualSpaces} ${foundSpacesWord} and ${actualTabs} ${foundTabsWord}`; // e.g. "1 space and 2 tabs" + } else if (actualSpaces > 0) { + /* + * Abbreviate the message if the expected indentation is also spaces. + * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + */ + foundStatement = + indentType === "space" + ? actualSpaces + : `${actualSpaces} ${foundSpacesWord}`; + } else if (actualTabs > 0) { + foundStatement = + indentType === "tab" + ? actualTabs + : `${actualTabs} ${foundTabsWord}`; + } else { + foundStatement = "0"; + } + return { + expected: expectedStatement, + actual: foundStatement, + }; + } + + /** + * Reports a given indent violation + * @param {ASTNode} node Node violating the indent rule + * @param {number} needed Expected indentation character count + * @param {number} gottenSpaces Indentation space count in the actual node/code + * @param {number} gottenTabs Indentation tab count in the actual node/code + * @param {Object} [loc] Error line and column location + * @param {boolean} isLastNodeCheck Is the error for last node check + * @returns {void} + */ + function report( + node, + needed, + gottenSpaces, + gottenTabs, + loc, + isLastNodeCheck, + ) { + if (gottenSpaces && gottenTabs) { + // To avoid conflicts with `no-mixed-spaces-and-tabs`, don't report lines that have both spaces and tabs. + return; + } + + const desiredIndent = (indentType === "space" ? " " : "\t").repeat( + needed, + ); + + const textRange = isLastNodeCheck + ? [ + node.range[1] - node.loc.end.column, + node.range[1] - + node.loc.end.column + + gottenSpaces + + gottenTabs, + ] + : [ + node.range[0] - node.loc.start.column, + node.range[0] - + node.loc.start.column + + gottenSpaces + + gottenTabs, + ]; + + context.report({ + node, + loc, + messageId: "expected", + data: createErrorMessageData(needed, gottenSpaces, gottenTabs), + fix: fixer => fixer.replaceTextRange(textRange, desiredIndent), + }); + } + + /** + * Get the actual indent of node + * @param {ASTNode|Token} node Node to examine + * @param {boolean} [byLastLine=false] get indent of node's last line + * @returns {Object} The node's indent. Contains keys `space` and `tab`, representing the indent of each character. Also + * contains keys `goodChar` and `badChar`, where `goodChar` is the amount of the user's desired indentation character, and + * `badChar` is the amount of the other indentation character. + */ + function getNodeIndent(node, byLastLine) { + const token = byLastLine + ? sourceCode.getLastToken(node) + : sourceCode.getFirstToken(node); + const srcCharsBeforeNode = sourceCode + .getText(token, token.loc.start.column) + .split(""); + const indentChars = srcCharsBeforeNode.slice( + 0, + srcCharsBeforeNode.findIndex( + char => char !== " " && char !== "\t", + ), + ); + const spaces = indentChars.filter(char => char === " ").length; + const tabs = indentChars.filter(char => char === "\t").length; + + return { + space: spaces, + tab: tabs, + goodChar: indentType === "space" ? spaces : tabs, + badChar: indentType === "space" ? tabs : spaces, + }; + } + + /** + * Checks node is the first in its own start line. By default it looks by start line. + * @param {ASTNode} node The node to check + * @param {boolean} [byEndLocation=false] Lookup based on start position or end + * @returns {boolean} true if its the first in the its start line + */ + function isNodeFirstInLine(node, byEndLocation) { + const firstToken = + byEndLocation === true + ? sourceCode.getLastToken(node, 1) + : sourceCode.getTokenBefore(node), + startLine = + byEndLocation === true + ? node.loc.end.line + : node.loc.start.line, + endLine = firstToken ? firstToken.loc.end.line : -1; + + return startLine !== endLine; + } + + /** + * Check indent for node + * @param {ASTNode} node Node to check + * @param {number} neededIndent needed indent + * @returns {void} + */ + function checkNodeIndent(node, neededIndent) { + const actualIndent = getNodeIndent(node, false); + + if ( + node.type !== "ArrayExpression" && + node.type !== "ObjectExpression" && + (actualIndent.goodChar !== neededIndent || + actualIndent.badChar !== 0) && + isNodeFirstInLine(node) + ) { + report( + node, + neededIndent, + actualIndent.space, + actualIndent.tab, + ); + } + + if (node.type === "IfStatement" && node.alternate) { + const elseToken = sourceCode.getTokenBefore(node.alternate); + + checkNodeIndent(elseToken, neededIndent); + + if (!isNodeFirstInLine(node.alternate)) { + checkNodeIndent(node.alternate, neededIndent); + } + } + + if (node.type === "TryStatement" && node.handler) { + const catchToken = sourceCode.getFirstToken(node.handler); + + checkNodeIndent(catchToken, neededIndent); + } + + if (node.type === "TryStatement" && node.finalizer) { + const finallyToken = sourceCode.getTokenBefore(node.finalizer); + + checkNodeIndent(finallyToken, neededIndent); + } + + if (node.type === "DoWhileStatement") { + const whileToken = sourceCode.getTokenAfter(node.body); + + checkNodeIndent(whileToken, neededIndent); + } + } + + /** + * Check indent for nodes list + * @param {ASTNode[]} nodes list of node objects + * @param {number} indent needed indent + * @returns {void} + */ + function checkNodesIndent(nodes, indent) { + nodes.forEach(node => checkNodeIndent(node, indent)); + } + + /** + * Check last node line indent this detects, that block closed correctly + * @param {ASTNode} node Node to examine + * @param {number} lastLineIndent needed indent + * @returns {void} + */ + function checkLastNodeLineIndent(node, lastLineIndent) { + const lastToken = sourceCode.getLastToken(node); + const endIndent = getNodeIndent(lastToken, true); + + if ( + (endIndent.goodChar !== lastLineIndent || + endIndent.badChar !== 0) && + isNodeFirstInLine(node, true) + ) { + report( + node, + lastLineIndent, + endIndent.space, + endIndent.tab, + { + line: lastToken.loc.start.line, + column: lastToken.loc.start.column, + }, + true, + ); + } + } + + /** + * Check last node line indent this detects, that block closed correctly + * This function for more complicated return statement case, where closing parenthesis may be followed by ';' + * @param {ASTNode} node Node to examine + * @param {number} firstLineIndent first line needed indent + * @returns {void} + */ + function checkLastReturnStatementLineIndent(node, firstLineIndent) { + /* + * in case if return statement ends with ');' we have traverse back to ')' + * otherwise we'll measure indent for ';' and replace ')' + */ + const lastToken = sourceCode.getLastToken( + node, + astUtils.isClosingParenToken, + ); + const textBeforeClosingParenthesis = sourceCode + .getText(lastToken, lastToken.loc.start.column) + .slice(0, -1); + + if (textBeforeClosingParenthesis.trim()) { + // There are tokens before the closing paren, don't report this case + return; + } + + const endIndent = getNodeIndent(lastToken, true); + + if (endIndent.goodChar !== firstLineIndent) { + report( + node, + firstLineIndent, + endIndent.space, + endIndent.tab, + { + line: lastToken.loc.start.line, + column: lastToken.loc.start.column, + }, + true, + ); + } + } + + /** + * Check first node line indent is correct + * @param {ASTNode} node Node to examine + * @param {number} firstLineIndent needed indent + * @returns {void} + */ + function checkFirstNodeLineIndent(node, firstLineIndent) { + const startIndent = getNodeIndent(node, false); + + if ( + (startIndent.goodChar !== firstLineIndent || + startIndent.badChar !== 0) && + isNodeFirstInLine(node) + ) { + report( + node, + firstLineIndent, + startIndent.space, + startIndent.tab, + { + line: node.loc.start.line, + column: node.loc.start.column, + }, + ); + } + } + + /** + * Returns a parent node of given node based on a specified type + * if not present then return null + * @param {ASTNode} node node to examine + * @param {string} type type that is being looked for + * @param {string} stopAtList end points for the evaluating code + * @returns {ASTNode|void} if found then node otherwise null + */ + function getParentNodeByType(node, type, stopAtList) { + let parent = node.parent; + const stopAtSet = new Set(stopAtList || ["Program"]); + + while ( + parent.type !== type && + !stopAtSet.has(parent.type) && + parent.type !== "Program" + ) { + parent = parent.parent; + } + + return parent.type === type ? parent : null; + } + + /** + * Returns the VariableDeclarator based on the current node + * if not present then return null + * @param {ASTNode} node node to examine + * @returns {ASTNode|void} if found then node otherwise null + */ + function getVariableDeclaratorNode(node) { + return getParentNodeByType(node, "VariableDeclarator"); + } + + /** + * Check to see if the node is part of the multi-line variable declaration. + * Also if its on the same line as the varNode + * @param {ASTNode} node node to check + * @param {ASTNode} varNode variable declaration node to check against + * @returns {boolean} True if all the above condition satisfy + */ + function isNodeInVarOnTop(node, varNode) { + return ( + varNode && + varNode.parent.loc.start.line === node.loc.start.line && + varNode.parent.declarations.length > 1 + ); + } + + /** + * Check to see if the argument before the callee node is multi-line and + * there should only be 1 argument before the callee node + * @param {ASTNode} node node to check + * @returns {boolean} True if arguments are multi-line + */ + function isArgBeforeCalleeNodeMultiline(node) { + const parent = node.parent; + + if (parent.arguments.length >= 2 && parent.arguments[1] === node) { + return ( + parent.arguments[0].loc.end.line > + parent.arguments[0].loc.start.line + ); + } + + return false; + } + + /** + * Check to see if the node is a file level IIFE + * @param {ASTNode} node The function node to check. + * @returns {boolean} True if the node is the outer IIFE + */ + function isOuterIIFE(node) { + const parent = node.parent; + let stmt = parent.parent; + + /* + * Verify that the node is an IIEF + */ + if (parent.type !== "CallExpression" || parent.callee !== node) { + return false; + } + + /* + * Navigate legal ancestors to determine whether this IIEF is outer + */ + while ( + (stmt.type === "UnaryExpression" && + (stmt.operator === "!" || + stmt.operator === "~" || + stmt.operator === "+" || + stmt.operator === "-")) || + stmt.type === "AssignmentExpression" || + stmt.type === "LogicalExpression" || + stmt.type === "SequenceExpression" || + stmt.type === "VariableDeclarator" + ) { + stmt = stmt.parent; + } + + return ( + (stmt.type === "ExpressionStatement" || + stmt.type === "VariableDeclaration") && + stmt.parent && + stmt.parent.type === "Program" + ); + } + + /** + * Check indent for function block content + * @param {ASTNode} node A BlockStatement node that is inside of a function. + * @returns {void} + */ + function checkIndentInFunctionBlock(node) { + /* + * Search first caller in chain. + * Ex.: + * + * Models <- Identifier + * .User + * .find() + * .exec(function() { + * // function body + * }); + * + * Looks for 'Models' + */ + const calleeNode = node.parent; // FunctionExpression + let indent; + + if ( + calleeNode.parent && + (calleeNode.parent.type === "Property" || + calleeNode.parent.type === "ArrayExpression") + ) { + // If function is part of array or object, comma can be put at left + indent = getNodeIndent(calleeNode, false).goodChar; + } else { + // If function is standalone, simple calculate indent + indent = getNodeIndent(calleeNode).goodChar; + } + + if (calleeNode.parent.type === "CallExpression") { + const calleeParent = calleeNode.parent; + + if ( + calleeNode.type !== "FunctionExpression" && + calleeNode.type !== "ArrowFunctionExpression" + ) { + if ( + calleeParent && + calleeParent.loc.start.line < node.loc.start.line + ) { + indent = getNodeIndent(calleeParent).goodChar; + } + } else { + if ( + isArgBeforeCalleeNodeMultiline(calleeNode) && + calleeParent.callee.loc.start.line === + calleeParent.callee.loc.end.line && + !isNodeFirstInLine(calleeNode) + ) { + indent = getNodeIndent(calleeParent).goodChar; + } + } + } + + /* + * function body indent should be indent + indent size, unless this + * is a FunctionDeclaration, FunctionExpression, or outer IIFE and the corresponding options are enabled. + */ + let functionOffset = indentSize; + + if (options.outerIIFEBody !== null && isOuterIIFE(calleeNode)) { + functionOffset = options.outerIIFEBody * indentSize; + } else if (calleeNode.type === "FunctionExpression") { + functionOffset = options.FunctionExpression.body * indentSize; + } else if (calleeNode.type === "FunctionDeclaration") { + functionOffset = options.FunctionDeclaration.body * indentSize; + } + indent += functionOffset; + + // check if the node is inside a variable + const parentVarNode = getVariableDeclaratorNode(node); + + if (parentVarNode && isNodeInVarOnTop(node, parentVarNode)) { + indent += + indentSize * + options.VariableDeclarator[parentVarNode.parent.kind]; + } + + if (node.body.length > 0) { + checkNodesIndent(node.body, indent); + } + + checkLastNodeLineIndent(node, indent - functionOffset); + } + + /** + * Checks if the given node starts and ends on the same line + * @param {ASTNode} node The node to check + * @returns {boolean} Whether or not the block starts and ends on the same line. + */ + function isSingleLineNode(node) { + const lastToken = sourceCode.getLastToken(node), + startLine = node.loc.start.line, + endLine = lastToken.loc.end.line; + + return startLine === endLine; + } + + /** + * Check indent for array block content or object block content + * @param {ASTNode} node node to examine + * @returns {void} + */ + function checkIndentInArrayOrObjectBlock(node) { + // Skip inline + if (isSingleLineNode(node)) { + return; + } + + let elements = + node.type === "ArrayExpression" + ? node.elements + : node.properties; + + // filter out empty elements example would be [ , 2] so remove first element as espree considers it as null + elements = elements.filter(elem => elem !== null); + + let nodeIndent; + let elementsIndent; + const parentVarNode = getVariableDeclaratorNode(node); + + // TODO - come up with a better strategy in future + if (isNodeFirstInLine(node)) { + const parent = node.parent; + + nodeIndent = getNodeIndent(parent).goodChar; + if ( + !parentVarNode || + parentVarNode.loc.start.line !== node.loc.start.line + ) { + if ( + parent.type !== "VariableDeclarator" || + parentVarNode === parentVarNode.parent.declarations[0] + ) { + if ( + parent.type === "VariableDeclarator" && + parentVarNode.loc.start.line === + parent.loc.start.line + ) { + nodeIndent += + indentSize * + options.VariableDeclarator[ + parentVarNode.parent.kind + ]; + } else if ( + parent.type === "ObjectExpression" || + parent.type === "ArrayExpression" + ) { + const parentElements = + node.parent.type === "ObjectExpression" + ? node.parent.properties + : node.parent.elements; + + if ( + parentElements[0] && + parentElements[0].loc.start.line === + parent.loc.start.line && + parentElements[0].loc.end.line !== + parent.loc.start.line + ) { + /* + * If the first element of the array spans multiple lines, don't increase the expected indentation of the rest. + * e.g. [{ + * foo: 1 + * }, + * { + * bar: 1 + * }] + * the second object is not indented. + */ + } else if ( + typeof options[parent.type] === "number" + ) { + nodeIndent += options[parent.type] * indentSize; + } else { + nodeIndent = parentElements[0].loc.start.column; + } + } else if ( + parent.type === "CallExpression" || + parent.type === "NewExpression" + ) { + if ( + typeof options.CallExpression.arguments === + "number" + ) { + nodeIndent += + options.CallExpression.arguments * + indentSize; + } else if ( + options.CallExpression.arguments === "first" + ) { + if (parent.arguments.includes(node)) { + nodeIndent = + parent.arguments[0].loc.start.column; + } + } else { + nodeIndent += indentSize; + } + } else if ( + parent.type === "LogicalExpression" || + parent.type === "ArrowFunctionExpression" + ) { + nodeIndent += indentSize; + } + } + } + + checkFirstNodeLineIndent(node, nodeIndent); + } else { + nodeIndent = getNodeIndent(node).goodChar; + } + + if (options[node.type] === "first") { + elementsIndent = elements.length + ? elements[0].loc.start.column + : 0; // If there are no elements, elementsIndent doesn't matter. + } else { + elementsIndent = nodeIndent + indentSize * options[node.type]; + } + + /* + * Check if the node is a multiple variable declaration; if so, then + * make sure indentation takes that into account. + */ + if (isNodeInVarOnTop(node, parentVarNode)) { + elementsIndent += + indentSize * + options.VariableDeclarator[parentVarNode.parent.kind]; + } + + checkNodesIndent(elements, elementsIndent); + + if (elements.length > 0) { + // Skip last block line check if last item in same line + if (elements.at(-1).loc.end.line === node.loc.end.line) { + return; + } + } + + checkLastNodeLineIndent( + node, + nodeIndent + + (isNodeInVarOnTop(node, parentVarNode) + ? options.VariableDeclarator[ + parentVarNode.parent.kind + ] * indentSize + : 0), + ); + } + + /** + * Check if the node or node body is a BlockStatement or not + * @param {ASTNode} node node to test + * @returns {boolean} True if it or its body is a block statement + */ + function isNodeBodyBlock(node) { + return ( + node.type === "BlockStatement" || + node.type === "ClassBody" || + (node.body && node.body.type === "BlockStatement") || + (node.consequent && node.consequent.type === "BlockStatement") + ); + } + + /** + * Check indentation for blocks + * @param {ASTNode} node node to check + * @returns {void} + */ + function blockIndentationCheck(node) { + // Skip inline blocks + if (isSingleLineNode(node)) { + return; + } + + if ( + node.parent && + (node.parent.type === "FunctionExpression" || + node.parent.type === "FunctionDeclaration" || + node.parent.type === "ArrowFunctionExpression") + ) { + checkIndentInFunctionBlock(node); + return; + } + + let indent; + let nodesToCheck; + + /* + * For this statements we should check indent from statement beginning, + * not from the beginning of the block. + */ + const statementsWithProperties = [ + "IfStatement", + "WhileStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", + "DoWhileStatement", + "ClassDeclaration", + "TryStatement", + ]; + + if ( + node.parent && + statementsWithProperties.includes(node.parent.type) && + isNodeBodyBlock(node) + ) { + indent = getNodeIndent(node.parent).goodChar; + } else if (node.parent && node.parent.type === "CatchClause") { + indent = getNodeIndent(node.parent.parent).goodChar; + } else { + indent = getNodeIndent(node).goodChar; + } + + if ( + node.type === "IfStatement" && + node.consequent.type !== "BlockStatement" + ) { + nodesToCheck = [node.consequent]; + } else if (Array.isArray(node.body)) { + nodesToCheck = node.body; + } else { + nodesToCheck = [node.body]; + } + + if (nodesToCheck.length > 0) { + checkNodesIndent(nodesToCheck, indent + indentSize); + } + + if (node.type === "BlockStatement") { + checkLastNodeLineIndent(node, indent); + } + } + + /** + * Filter out the elements which are on the same line of each other or the node. + * basically have only 1 elements from each line except the variable declaration line. + * @param {ASTNode} node Variable declaration node + * @returns {ASTNode[]} Filtered elements + */ + function filterOutSameLineVars(node) { + return node.declarations.reduce((finalCollection, elem) => { + const lastElem = finalCollection.at(-1); + + if ( + (elem.loc.start.line !== node.loc.start.line && + !lastElem) || + (lastElem && + lastElem.loc.start.line !== elem.loc.start.line) + ) { + finalCollection.push(elem); + } + + return finalCollection; + }, []); + } + + /** + * Check indentation for variable declarations + * @param {ASTNode} node node to examine + * @returns {void} + */ + function checkIndentInVariableDeclarations(node) { + const elements = filterOutSameLineVars(node); + const nodeIndent = getNodeIndent(node).goodChar; + const lastElement = elements.at(-1); + + const elementsIndent = + nodeIndent + indentSize * options.VariableDeclarator[node.kind]; + + checkNodesIndent(elements, elementsIndent); + + // Only check the last line if there is any token after the last item + if ( + sourceCode.getLastToken(node).loc.end.line <= + lastElement.loc.end.line + ) { + return; + } + + const tokenBeforeLastElement = + sourceCode.getTokenBefore(lastElement); + + if (tokenBeforeLastElement.value === ",") { + // Special case for comma-first syntax where the semicolon is indented + checkLastNodeLineIndent( + node, + getNodeIndent(tokenBeforeLastElement).goodChar, + ); + } else { + checkLastNodeLineIndent(node, elementsIndent - indentSize); + } + } + + /** + * Check and decide whether to check for indentation for blockless nodes + * Scenarios are for or while statements without braces around them + * @param {ASTNode} node node to examine + * @returns {void} + */ + function blockLessNodes(node) { + if (node.body.type !== "BlockStatement") { + blockIndentationCheck(node); + } + } + + /** + * Returns the expected indentation for the case statement + * @param {ASTNode} node node to examine + * @param {number} [providedSwitchIndent] indent for switch statement + * @returns {number} indent size + */ + function expectedCaseIndent(node, providedSwitchIndent) { + const switchNode = + node.type === "SwitchStatement" ? node : node.parent; + const switchIndent = + typeof providedSwitchIndent === "undefined" + ? getNodeIndent(switchNode).goodChar + : providedSwitchIndent; + let caseIndent; + + if (caseIndentStore[switchNode.loc.start.line]) { + return caseIndentStore[switchNode.loc.start.line]; + } + + if (switchNode.cases.length > 0 && options.SwitchCase === 0) { + caseIndent = switchIndent; + } else { + caseIndent = switchIndent + indentSize * options.SwitchCase; + } + + caseIndentStore[switchNode.loc.start.line] = caseIndent; + return caseIndent; + } + + /** + * Checks whether a return statement is wrapped in () + * @param {ASTNode} node node to examine + * @returns {boolean} the result + */ + function isWrappedInParenthesis(node) { + const regex = /^return\s*?\(\s*?\);*?/u; + + const statementWithoutArgument = sourceCode + .getText(node) + .replace(sourceCode.getText(node.argument), ""); + + return regex.test(statementWithoutArgument); + } + + return { + Program(node) { + if (node.body.length > 0) { + // Root nodes should have no indent + checkNodesIndent(node.body, getNodeIndent(node).goodChar); + } + }, + + ClassBody: blockIndentationCheck, + + BlockStatement: blockIndentationCheck, + + WhileStatement: blockLessNodes, + + ForStatement: blockLessNodes, + + ForInStatement: blockLessNodes, + + ForOfStatement: blockLessNodes, + + DoWhileStatement: blockLessNodes, + + IfStatement(node) { + if ( + node.consequent.type !== "BlockStatement" && + node.consequent.loc.start.line > node.loc.start.line + ) { + blockIndentationCheck(node); + } + }, + + VariableDeclaration(node) { + if ( + node.declarations.at(-1).loc.start.line > + node.declarations[0].loc.start.line + ) { + checkIndentInVariableDeclarations(node); + } + }, + + ObjectExpression(node) { + checkIndentInArrayOrObjectBlock(node); + }, + + ArrayExpression(node) { + checkIndentInArrayOrObjectBlock(node); + }, + + MemberExpression(node) { + if (typeof options.MemberExpression === "undefined") { + return; + } + + if (isSingleLineNode(node)) { + return; + } + + /* + * The typical layout of variable declarations and assignments + * alter the expectation of correct indentation. Skip them. + * TODO: Add appropriate configuration options for variable + * declarations and assignments. + */ + if ( + getParentNodeByType(node, "VariableDeclarator", [ + "FunctionExpression", + "ArrowFunctionExpression", + ]) + ) { + return; + } + + if ( + getParentNodeByType(node, "AssignmentExpression", [ + "FunctionExpression", + ]) + ) { + return; + } + + const propertyIndent = + getNodeIndent(node).goodChar + + indentSize * options.MemberExpression; + + const checkNodes = [node.property]; + + const dot = sourceCode.getTokenBefore(node.property); + + if (dot.type === "Punctuator" && dot.value === ".") { + checkNodes.push(dot); + } + + checkNodesIndent(checkNodes, propertyIndent); + }, + + SwitchStatement(node) { + // Switch is not a 'BlockStatement' + const switchIndent = getNodeIndent(node).goodChar; + const caseIndent = expectedCaseIndent(node, switchIndent); + + checkNodesIndent(node.cases, caseIndent); + + checkLastNodeLineIndent(node, switchIndent); + }, + + SwitchCase(node) { + // Skip inline cases + if (isSingleLineNode(node)) { + return; + } + const caseIndent = expectedCaseIndent(node); + + checkNodesIndent(node.consequent, caseIndent + indentSize); + }, + + FunctionDeclaration(node) { + if (isSingleLineNode(node)) { + return; + } + if ( + options.FunctionDeclaration.parameters === "first" && + node.params.length + ) { + checkNodesIndent( + node.params.slice(1), + node.params[0].loc.start.column, + ); + } else if (options.FunctionDeclaration.parameters !== null) { + checkNodesIndent( + node.params, + getNodeIndent(node).goodChar + + indentSize * options.FunctionDeclaration.parameters, + ); + } + }, + + FunctionExpression(node) { + if (isSingleLineNode(node)) { + return; + } + if ( + options.FunctionExpression.parameters === "first" && + node.params.length + ) { + checkNodesIndent( + node.params.slice(1), + node.params[0].loc.start.column, + ); + } else if (options.FunctionExpression.parameters !== null) { + checkNodesIndent( + node.params, + getNodeIndent(node).goodChar + + indentSize * options.FunctionExpression.parameters, + ); + } + }, + + ReturnStatement(node) { + if (isSingleLineNode(node)) { + return; + } + + const firstLineIndent = getNodeIndent(node).goodChar; + + // in case if return statement is wrapped in parenthesis + if (isWrappedInParenthesis(node)) { + checkLastReturnStatementLineIndent(node, firstLineIndent); + } else { + checkNodeIndent(node, firstLineIndent); + } + }, + + CallExpression(node) { + if (isSingleLineNode(node)) { + return; + } + if ( + options.CallExpression.arguments === "first" && + node.arguments.length + ) { + checkNodesIndent( + node.arguments.slice(1), + node.arguments[0].loc.start.column, + ); + } else if (options.CallExpression.arguments !== null) { + checkNodesIndent( + node.arguments, + getNodeIndent(node).goodChar + + indentSize * options.CallExpression.arguments, + ); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/indent.js b/node_modules/eslint/lib/rules/indent.js new file mode 100644 index 00000000..029564a3 --- /dev/null +++ b/node_modules/eslint/lib/rules/indent.js @@ -0,0 +1,2334 @@ +/** + * @fileoverview This rule sets a specific indentation style and width for your code + * + * @author Teddy Katz + * @author Vitaly Puzrin + * @author Gyandeep Singh + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const KNOWN_NODES = new Set([ + "AssignmentExpression", + "AssignmentPattern", + "ArrayExpression", + "ArrayPattern", + "ArrowFunctionExpression", + "AwaitExpression", + "BlockStatement", + "BinaryExpression", + "BreakStatement", + "CallExpression", + "CatchClause", + "ChainExpression", + "ClassBody", + "ClassDeclaration", + "ClassExpression", + "ConditionalExpression", + "ContinueStatement", + "DoWhileStatement", + "DebuggerStatement", + "EmptyStatement", + "ExperimentalRestProperty", + "ExperimentalSpreadProperty", + "ExpressionStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", + "FunctionDeclaration", + "FunctionExpression", + "Identifier", + "IfStatement", + "Literal", + "LabeledStatement", + "LogicalExpression", + "MemberExpression", + "MetaProperty", + "MethodDefinition", + "NewExpression", + "ObjectExpression", + "ObjectPattern", + "PrivateIdentifier", + "Program", + "Property", + "PropertyDefinition", + "RestElement", + "ReturnStatement", + "SequenceExpression", + "SpreadElement", + "StaticBlock", + "Super", + "SwitchCase", + "SwitchStatement", + "TaggedTemplateExpression", + "TemplateElement", + "TemplateLiteral", + "ThisExpression", + "ThrowStatement", + "TryStatement", + "UnaryExpression", + "UpdateExpression", + "VariableDeclaration", + "VariableDeclarator", + "WhileStatement", + "WithStatement", + "YieldExpression", + "JSXFragment", + "JSXOpeningFragment", + "JSXClosingFragment", + "JSXIdentifier", + "JSXNamespacedName", + "JSXMemberExpression", + "JSXEmptyExpression", + "JSXExpressionContainer", + "JSXElement", + "JSXClosingElement", + "JSXOpeningElement", + "JSXAttribute", + "JSXSpreadAttribute", + "JSXText", + "ExportDefaultDeclaration", + "ExportNamedDeclaration", + "ExportAllDeclaration", + "ExportSpecifier", + "ImportDeclaration", + "ImportSpecifier", + "ImportDefaultSpecifier", + "ImportNamespaceSpecifier", + "ImportExpression", +]); + +/* + * General rule strategy: + * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another + * specified token or to the first column. + * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a + * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly + * brace of the BlockStatement. + * 3. After traversing the AST, calculate the expected indentation levels of every token according to the + * OffsetStorage container. + * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file, + * and report the token if the two values are not equal. + */ + +/** + * A mutable map that stores (key, value) pairs. The keys are numeric indices, and must be unique. + * This is intended to be a generic wrapper around a map with non-negative integer keys, so that the underlying implementation + * can easily be swapped out. + */ +class IndexMap { + /** + * Creates an empty map + * @param {number} maxKey The maximum key + */ + constructor(maxKey) { + // Initializing the array with the maximum expected size avoids dynamic reallocations that could degrade performance. + this._values = Array(maxKey + 1); + } + + /** + * Inserts an entry into the map. + * @param {number} key The entry's key + * @param {any} value The entry's value + * @returns {void} + */ + insert(key, value) { + this._values[key] = value; + } + + /** + * Finds the value of the entry with the largest key less than or equal to the provided key + * @param {number} key The provided key + * @returns {*|undefined} The value of the found entry, or undefined if no such entry exists. + */ + findLastNotAfter(key) { + const values = this._values; + + for (let index = key; index >= 0; index--) { + const value = values[index]; + + if (value) { + return value; + } + } + return void 0; + } + + /** + * Deletes all of the keys in the interval [start, end) + * @param {number} start The start of the range + * @param {number} end The end of the range + * @returns {void} + */ + deleteRange(start, end) { + this._values.fill(void 0, start, end); + } +} + +/** + * A helper class to get token-based info related to indentation + */ +class TokenInfo { + /** + * @param {SourceCode} sourceCode A SourceCode object + */ + constructor(sourceCode) { + this.sourceCode = sourceCode; + this.firstTokensByLineNumber = new Map(); + const tokens = sourceCode.tokensAndComments; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + + if (!this.firstTokensByLineNumber.has(token.loc.start.line)) { + this.firstTokensByLineNumber.set(token.loc.start.line, token); + } + if ( + !this.firstTokensByLineNumber.has(token.loc.end.line) && + sourceCode.text + .slice( + token.range[1] - token.loc.end.column, + token.range[1], + ) + .trim() + ) { + this.firstTokensByLineNumber.set(token.loc.end.line, token); + } + } + } + + /** + * Gets the first token on a given token's line + * @param {Token|ASTNode} token a node or token + * @returns {Token} The first token on the given line + */ + getFirstTokenOfLine(token) { + return this.firstTokensByLineNumber.get(token.loc.start.line); + } + + /** + * Determines whether a token is the first token in its line + * @param {Token} token The token + * @returns {boolean} `true` if the token is the first on its line + */ + isFirstTokenOfLine(token) { + return this.getFirstTokenOfLine(token) === token; + } + + /** + * Get the actual indent of a token + * @param {Token} token Token to examine. This should be the first token on its line. + * @returns {string} The indentation characters that precede the token + */ + getTokenIndent(token) { + return this.sourceCode.text.slice( + token.range[0] - token.loc.start.column, + token.range[0], + ); + } +} + +/** + * A class to store information on desired offsets of tokens from each other + */ +class OffsetStorage { + /** + * @param {TokenInfo} tokenInfo a TokenInfo instance + * @param {number} indentSize The desired size of each indentation level + * @param {string} indentType The indentation character + * @param {number} maxIndex The maximum end index of any token + */ + constructor(tokenInfo, indentSize, indentType, maxIndex) { + this._tokenInfo = tokenInfo; + this._indentSize = indentSize; + this._indentType = indentType; + + this._indexMap = new IndexMap(maxIndex); + this._indexMap.insert(0, { offset: 0, from: null, force: false }); + + this._lockedFirstTokens = new WeakMap(); + this._desiredIndentCache = new WeakMap(); + this._ignoredTokens = new WeakSet(); + } + + _getOffsetDescriptor(token) { + return this._indexMap.findLastNotAfter(token.range[0]); + } + + /** + * Sets the offset column of token B to match the offset column of token A. + * - **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In + * most cases, `setDesiredOffset` should be used instead. + * @param {Token} baseToken The first token + * @param {Token} offsetToken The second token, whose offset should be matched to the first token + * @returns {void} + */ + matchOffsetOf(baseToken, offsetToken) { + /* + * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to + * the token that it depends on. For example, with the `ArrayExpression: first` option, the first + * token of each element in the array after the first will be mapped to the first token of the first + * element. The desired indentation of each of these tokens is computed based on the desired indentation + * of the "first" element, rather than through the normal offset mechanism. + */ + this._lockedFirstTokens.set(offsetToken, baseToken); + } + + /** + * Sets the desired offset of a token. + * + * This uses a line-based offset collapsing behavior to handle tokens on the same line. + * For example, consider the following two cases: + * + * ( + * [ + * bar + * ] + * ) + * + * ([ + * bar + * ]) + * + * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from + * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is + * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces) + * from the start of its line. + * + * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level + * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the + * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented + * by 1 indent level from the start of the line. + * + * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node, + * without needing to check which lines those tokens are on. + * + * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive + * behavior can occur. For example, consider the following cases: + * + * foo( + * ). + * bar( + * baz + * ) + * + * foo( + * ).bar( + * baz + * ) + * + * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz` + * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz` + * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no + * collapsing would occur). + * + * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and + * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed + * in the second case. + * @param {Token} token The token + * @param {Token} fromToken The token that `token` should be offset from + * @param {number} offset The desired indent level + * @returns {void} + */ + setDesiredOffset(token, fromToken, offset) { + return this.setDesiredOffsets(token.range, fromToken, offset); + } + + /** + * Sets the desired offset of all tokens in a range + * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens. + * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains + * it). This means that the offset of each token is updated O(AST depth) times. + * It would not be performant to store and update the offsets for each token independently, because the rule would end + * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files. + * + * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following + * list could represent the state of the offset tree at a given point: + * + * - Tokens starting in the interval [0, 15) are aligned with the beginning of the file + * - Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token + * - Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token + * - Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token + * - Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token + * + * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using: + * `setDesiredOffsets([30, 43], fooToken, 1);` + * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied. + * @param {Token} fromToken The token that this is offset from + * @param {number} offset The desired indent level + * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false. + * @returns {void} + */ + setDesiredOffsets(range, fromToken, offset, force) { + /* + * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset + * descriptor. The tree for the example above would have the following nodes: + * + * * key: 0, value: { offset: 0, from: null } + * * key: 15, value: { offset: 1, from: barToken } + * * key: 30, value: { offset: 1, from: fooToken } + * * key: 43, value: { offset: 2, from: barToken } + * * key: 820, value: { offset: 1, from: bazToken } + * + * To find the offset descriptor for any given token, one needs to find the node with the largest key + * which is <= token.start. To make this operation fast, the nodes are stored in a map indexed by key. + */ + + const descriptorToInsert = { offset, from: fromToken, force }; + + const descriptorAfterRange = this._indexMap.findLastNotAfter(range[1]); + + const fromTokenIsInRange = + fromToken && + fromToken.range[0] >= range[0] && + fromToken.range[1] <= range[1]; + const fromTokenDescriptor = + fromTokenIsInRange && this._getOffsetDescriptor(fromToken); + + // First, remove any existing nodes in the range from the map. + this._indexMap.deleteRange(range[0] + 1, range[1]); + + // Insert a new node into the map for this range + this._indexMap.insert(range[0], descriptorToInsert); + + /* + * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously, + * even if it's in the current range. + */ + if (fromTokenIsInRange) { + this._indexMap.insert(fromToken.range[0], fromTokenDescriptor); + this._indexMap.insert(fromToken.range[1], descriptorToInsert); + } + + /* + * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following + * tokens the same as it was before. + */ + this._indexMap.insert(range[1], descriptorAfterRange); + } + + /** + * Gets the desired indent of a token + * @param {Token} token The token + * @returns {string} The desired indent of the token + */ + getDesiredIndent(token) { + if (!this._desiredIndentCache.has(token)) { + if (this._ignoredTokens.has(token)) { + /* + * If the token is ignored, use the actual indent of the token as the desired indent. + * This ensures that no errors are reported for this token. + */ + this._desiredIndentCache.set( + token, + this._tokenInfo.getTokenIndent(token), + ); + } else if (this._lockedFirstTokens.has(token)) { + const firstToken = this._lockedFirstTokens.get(token); + + this._desiredIndentCache.set( + token, + + // (indentation for the first element's line) + this.getDesiredIndent( + this._tokenInfo.getFirstTokenOfLine(firstToken), + ) + + // (space between the start of the first element's line and the first element) + this._indentType.repeat( + firstToken.loc.start.column - + this._tokenInfo.getFirstTokenOfLine(firstToken) + .loc.start.column, + ), + ); + } else { + const offsetInfo = this._getOffsetDescriptor(token); + const offset = + offsetInfo.from && + offsetInfo.from.loc.start.line === token.loc.start.line && + !/^\s*?\n/u.test(token.value) && + !offsetInfo.force + ? 0 + : offsetInfo.offset * this._indentSize; + + this._desiredIndentCache.set( + token, + (offsetInfo.from + ? this.getDesiredIndent(offsetInfo.from) + : "") + this._indentType.repeat(offset), + ); + } + } + return this._desiredIndentCache.get(token); + } + + /** + * Ignores a token, preventing it from being reported. + * @param {Token} token The token + * @returns {void} + */ + ignoreToken(token) { + if (this._tokenInfo.isFirstTokenOfLine(token)) { + this._ignoredTokens.add(token); + } + } + + /** + * Gets the first token that the given token's indentation is dependent on + * @param {Token} token The token + * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level + */ + getFirstDependency(token) { + return this._getOffsetDescriptor(token).from; + } +} + +const ELEMENT_LIST_SCHEMA = { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first", "off"], + }, + ], +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "indent", + url: "https://eslint.style/rules/js/indent", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent indentation", + recommended: false, + url: "https://eslint.org/docs/latest/rules/indent", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["tab"], + }, + { + type: "integer", + minimum: 0, + }, + ], + }, + { + type: "object", + properties: { + SwitchCase: { + type: "integer", + minimum: 0, + default: 0, + }, + VariableDeclarator: { + oneOf: [ + ELEMENT_LIST_SCHEMA, + { + type: "object", + properties: { + var: ELEMENT_LIST_SCHEMA, + let: ELEMENT_LIST_SCHEMA, + const: ELEMENT_LIST_SCHEMA, + }, + additionalProperties: false, + }, + ], + }, + outerIIFEBody: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["off"], + }, + ], + }, + MemberExpression: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["off"], + }, + ], + }, + FunctionDeclaration: { + type: "object", + properties: { + parameters: ELEMENT_LIST_SCHEMA, + body: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + FunctionExpression: { + type: "object", + properties: { + parameters: ELEMENT_LIST_SCHEMA, + body: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + StaticBlock: { + type: "object", + properties: { + body: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + CallExpression: { + type: "object", + properties: { + arguments: ELEMENT_LIST_SCHEMA, + }, + additionalProperties: false, + }, + ArrayExpression: ELEMENT_LIST_SCHEMA, + ObjectExpression: ELEMENT_LIST_SCHEMA, + ImportDeclaration: ELEMENT_LIST_SCHEMA, + flatTernaryExpressions: { + type: "boolean", + default: false, + }, + offsetTernaryExpressions: { + type: "boolean", + default: false, + }, + ignoredNodes: { + type: "array", + items: { + type: "string", + not: { + pattern: ":exit$", + }, + }, + }, + ignoreComments: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + messages: { + wrongIndentation: + "Expected indentation of {{expected}} but found {{actual}}.", + }, + }, + + create(context) { + const DEFAULT_VARIABLE_INDENT = 1; + const DEFAULT_PARAMETER_INDENT = 1; + const DEFAULT_FUNCTION_BODY_INDENT = 1; + + let indentType = "space"; + let indentSize = 4; + const options = { + SwitchCase: 0, + VariableDeclarator: { + var: DEFAULT_VARIABLE_INDENT, + let: DEFAULT_VARIABLE_INDENT, + const: DEFAULT_VARIABLE_INDENT, + }, + outerIIFEBody: 1, + FunctionDeclaration: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + FunctionExpression: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + StaticBlock: { + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + CallExpression: { + arguments: DEFAULT_PARAMETER_INDENT, + }, + MemberExpression: 1, + ArrayExpression: 1, + ObjectExpression: 1, + ImportDeclaration: 1, + flatTernaryExpressions: false, + ignoredNodes: [], + ignoreComments: false, + }; + + if (context.options.length) { + if (context.options[0] === "tab") { + indentSize = 1; + indentType = "tab"; + } else { + indentSize = context.options[0]; + indentType = "space"; + } + + if (context.options[1]) { + Object.assign(options, context.options[1]); + + if ( + typeof options.VariableDeclarator === "number" || + options.VariableDeclarator === "first" + ) { + options.VariableDeclarator = { + var: options.VariableDeclarator, + let: options.VariableDeclarator, + const: options.VariableDeclarator, + }; + } + } + } + + const sourceCode = context.sourceCode; + const tokenInfo = new TokenInfo(sourceCode); + const offsets = new OffsetStorage( + tokenInfo, + indentSize, + indentType === "space" ? " " : "\t", + sourceCode.text.length, + ); + const parameterParens = new WeakSet(); + + /** + * Creates an error message for a line, given the expected/actual indentation. + * @param {number} expectedAmount The expected amount of indentation characters for this line + * @param {number} actualSpaces The actual number of indentation spaces that were found on this line + * @param {number} actualTabs The actual number of indentation tabs that were found on this line + * @returns {string} An error message for this line + */ + function createErrorMessageData( + expectedAmount, + actualSpaces, + actualTabs, + ) { + const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" + const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" + const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" + let foundStatement; + + if (actualSpaces > 0) { + /* + * Abbreviate the message if the expected indentation is also spaces. + * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + */ + foundStatement = + indentType === "space" + ? actualSpaces + : `${actualSpaces} ${foundSpacesWord}`; + } else if (actualTabs > 0) { + foundStatement = + indentType === "tab" + ? actualTabs + : `${actualTabs} ${foundTabsWord}`; + } else { + foundStatement = "0"; + } + return { + expected: expectedStatement, + actual: foundStatement, + }; + } + + /** + * Reports a given indent violation + * @param {Token} token Token violating the indent rule + * @param {string} neededIndent Expected indentation string + * @returns {void} + */ + function report(token, neededIndent) { + const actualIndent = Array.from(tokenInfo.getTokenIndent(token)); + const numSpaces = actualIndent.filter(char => char === " ").length; + const numTabs = actualIndent.filter(char => char === "\t").length; + + context.report({ + node: token, + messageId: "wrongIndentation", + data: createErrorMessageData( + neededIndent.length, + numSpaces, + numTabs, + ), + loc: { + start: { line: token.loc.start.line, column: 0 }, + end: { + line: token.loc.start.line, + column: token.loc.start.column, + }, + }, + fix(fixer) { + const range = [ + token.range[0] - token.loc.start.column, + token.range[0], + ]; + const newText = neededIndent; + + return fixer.replaceTextRange(range, newText); + }, + }); + } + + /** + * Checks if a token's indentation is correct + * @param {Token} token Token to examine + * @param {string} desiredIndent Desired indentation of the string + * @returns {boolean} `true` if the token's indentation is correct + */ + function validateTokenIndent(token, desiredIndent) { + const indentation = tokenInfo.getTokenIndent(token); + + return ( + indentation === desiredIndent || + // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs. + (indentation.includes(" ") && indentation.includes("\t")) + ); + } + + /** + * Check to see if the node is a file level IIFE + * @param {ASTNode} node The function node to check. + * @returns {boolean} True if the node is the outer IIFE + */ + function isOuterIIFE(node) { + /* + * Verify that the node is an IIFE + */ + if ( + !node.parent || + node.parent.type !== "CallExpression" || + node.parent.callee !== node + ) { + return false; + } + + /* + * Navigate legal ancestors to determine whether this IIFE is outer. + * A "legal ancestor" is an expression or statement that causes the function to get executed immediately. + * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator. + */ + let statement = node.parent && node.parent.parent; + + while ( + (statement.type === "UnaryExpression" && + ["!", "~", "+", "-"].includes(statement.operator)) || + statement.type === "AssignmentExpression" || + statement.type === "LogicalExpression" || + statement.type === "SequenceExpression" || + statement.type === "VariableDeclarator" + ) { + statement = statement.parent; + } + + return ( + (statement.type === "ExpressionStatement" || + statement.type === "VariableDeclaration") && + statement.parent.type === "Program" + ); + } + + /** + * Counts the number of linebreaks that follow the last non-whitespace character in a string + * @param {string} string The string to check + * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character, + * or the total number of linebreaks if the string is all whitespace. + */ + function countTrailingLinebreaks(string) { + const trailingWhitespace = string.match(/\s*$/u)[0]; + const linebreakMatches = trailingWhitespace.match( + astUtils.createGlobalLinebreakMatcher(), + ); + + return linebreakMatches === null ? 0 : linebreakMatches.length; + } + + /** + * Check indentation for lists of elements (arrays, objects, function params) + * @param {ASTNode[]} elements List of elements that should be offset + * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '[' + * @param {Token} endToken The end token of the list, e.g. ']' + * @param {number|string} offset The amount that the elements should be offset + * @returns {void} + */ + function addElementListIndent(elements, startToken, endToken, offset) { + /** + * Gets the first token of a given element, including surrounding parentheses. + * @param {ASTNode} element A node in the `elements` list + * @returns {Token} The first token of this element + */ + function getFirstToken(element) { + let token = sourceCode.getTokenBefore(element); + + while ( + astUtils.isOpeningParenToken(token) && + token !== startToken + ) { + token = sourceCode.getTokenBefore(token); + } + return sourceCode.getTokenAfter(token); + } + + // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden) + offsets.setDesiredOffsets( + [startToken.range[1], endToken.range[0]], + startToken, + typeof offset === "number" ? offset : 1, + ); + offsets.setDesiredOffset(endToken, startToken, 0); + + // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level. + if (offset === "first" && elements.length && !elements[0]) { + return; + } + elements.forEach((element, index) => { + if (!element) { + // Skip holes in arrays + return; + } + if (offset === "off") { + // Ignore the first token of every element if the "off" option is used + offsets.ignoreToken(getFirstToken(element)); + } + + // Offset the following elements correctly relative to the first element + if (index === 0) { + return; + } + if ( + offset === "first" && + tokenInfo.isFirstTokenOfLine(getFirstToken(element)) + ) { + offsets.matchOffsetOf( + getFirstToken(elements[0]), + getFirstToken(element), + ); + } else { + const previousElement = elements[index - 1]; + const firstTokenOfPreviousElement = + previousElement && getFirstToken(previousElement); + const previousElementLastToken = + previousElement && + sourceCode.getLastToken(previousElement); + + if ( + previousElement && + previousElementLastToken.loc.end.line - + countTrailingLinebreaks( + previousElementLastToken.value, + ) > + startToken.loc.end.line + ) { + offsets.setDesiredOffsets( + [previousElement.range[1], element.range[1]], + firstTokenOfPreviousElement, + 0, + ); + } + } + }); + } + + /** + * Check and decide whether to check for indentation for blockless nodes + * Scenarios are for or while statements without braces around them + * @param {ASTNode} node node to examine + * @returns {void} + */ + function addBlocklessNodeIndent(node) { + if (node.type !== "BlockStatement") { + const lastParentToken = sourceCode.getTokenBefore( + node, + astUtils.isNotOpeningParenToken, + ); + + let firstBodyToken = sourceCode.getFirstToken(node); + let lastBodyToken = sourceCode.getLastToken(node); + + while ( + astUtils.isOpeningParenToken( + sourceCode.getTokenBefore(firstBodyToken), + ) && + astUtils.isClosingParenToken( + sourceCode.getTokenAfter(lastBodyToken), + ) + ) { + firstBodyToken = sourceCode.getTokenBefore(firstBodyToken); + lastBodyToken = sourceCode.getTokenAfter(lastBodyToken); + } + + offsets.setDesiredOffsets( + [firstBodyToken.range[0], lastBodyToken.range[1]], + lastParentToken, + 1, + ); + } + } + + /** + * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`) + * @param {ASTNode} node A CallExpression or NewExpression node + * @returns {void} + */ + function addFunctionCallIndent(node) { + let openingParen; + + if (node.arguments.length) { + openingParen = sourceCode.getFirstTokenBetween( + node.callee, + node.arguments[0], + astUtils.isOpeningParenToken, + ); + } else { + openingParen = sourceCode.getLastToken(node, 1); + } + const closingParen = sourceCode.getLastToken(node); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + + /* + * If `?.` token exists, set desired offset for that. + * This logic is copied from `MemberExpression`'s. + */ + if (node.optional) { + const dotToken = sourceCode.getTokenAfter( + node.callee, + astUtils.isQuestionDotToken, + ); + const calleeParenCount = sourceCode.getTokensBetween( + node.callee, + dotToken, + { filter: astUtils.isClosingParenToken }, + ).length; + const firstTokenOfCallee = calleeParenCount + ? sourceCode.getTokenBefore(node.callee, { + skip: calleeParenCount - 1, + }) + : sourceCode.getFirstToken(node.callee); + const lastTokenOfCallee = sourceCode.getTokenBefore(dotToken); + const offsetBase = + lastTokenOfCallee.loc.end.line === + openingParen.loc.start.line + ? lastTokenOfCallee + : firstTokenOfCallee; + + offsets.setDesiredOffset(dotToken, offsetBase, 1); + } + + const offsetAfterToken = + node.callee.type === "TaggedTemplateExpression" + ? sourceCode.getFirstToken(node.callee.quasi) + : openingParen; + const offsetToken = sourceCode.getTokenBefore(offsetAfterToken); + + offsets.setDesiredOffset(openingParen, offsetToken, 0); + + addElementListIndent( + node.arguments, + openingParen, + closingParen, + options.CallExpression.arguments, + ); + } + + /** + * Checks the indentation of parenthesized values, given a list of tokens in a program + * @param {Token[]} tokens A list of tokens + * @returns {void} + */ + function addParensIndent(tokens) { + const parenStack = []; + const parenPairs = []; + + for (let i = 0; i < tokens.length; i++) { + const nextToken = tokens[i]; + + if (astUtils.isOpeningParenToken(nextToken)) { + parenStack.push(nextToken); + } else if (astUtils.isClosingParenToken(nextToken)) { + parenPairs.push({ + left: parenStack.pop(), + right: nextToken, + }); + } + } + + for (let i = parenPairs.length - 1; i >= 0; i--) { + const leftParen = parenPairs[i].left; + const rightParen = parenPairs[i].right; + + // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments. + if ( + !parameterParens.has(leftParen) && + !parameterParens.has(rightParen) + ) { + const parenthesizedTokens = new Set( + sourceCode.getTokensBetween(leftParen, rightParen), + ); + + parenthesizedTokens.forEach(token => { + if ( + !parenthesizedTokens.has( + offsets.getFirstDependency(token), + ) + ) { + offsets.setDesiredOffset(token, leftParen, 1); + } + }); + } + + offsets.setDesiredOffset(rightParen, leftParen, 0); + } + } + + /** + * Ignore all tokens within an unknown node whose offset do not depend + * on another token's offset within the unknown node + * @param {ASTNode} node Unknown Node + * @returns {void} + */ + function ignoreNode(node) { + const unknownNodeTokens = new Set( + sourceCode.getTokens(node, { includeComments: true }), + ); + + unknownNodeTokens.forEach(token => { + if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) { + const firstTokenOfLine = + tokenInfo.getFirstTokenOfLine(token); + + if (token === firstTokenOfLine) { + offsets.ignoreToken(token); + } else { + offsets.setDesiredOffset(token, firstTokenOfLine, 0); + } + } + }); + } + + /** + * Check whether the given token is on the first line of a statement. + * @param {Token} token The token to check. + * @param {ASTNode} leafNode The expression node that the token belongs directly. + * @returns {boolean} `true` if the token is on the first line of a statement. + */ + function isOnFirstLineOfStatement(token, leafNode) { + let node = leafNode; + + while ( + node.parent && + !node.parent.type.endsWith("Statement") && + !node.parent.type.endsWith("Declaration") + ) { + node = node.parent; + } + node = node.parent; + + return !node || node.loc.start.line === token.loc.start.line; + } + + /** + * Check whether there are any blank (whitespace-only) lines between + * two tokens on separate lines. + * @param {Token} firstToken The first token. + * @param {Token} secondToken The second token. + * @returns {boolean} `true` if the tokens are on separate lines and + * there exists a blank line between them, `false` otherwise. + */ + function hasBlankLinesBetween(firstToken, secondToken) { + const firstTokenLine = firstToken.loc.end.line; + const secondTokenLine = secondToken.loc.start.line; + + if ( + firstTokenLine === secondTokenLine || + firstTokenLine === secondTokenLine - 1 + ) { + return false; + } + + for ( + let line = firstTokenLine + 1; + line < secondTokenLine; + ++line + ) { + if (!tokenInfo.firstTokensByLineNumber.has(line)) { + return true; + } + } + + return false; + } + + const ignoredNodeFirstTokens = new Set(); + + const baseOffsetListeners = { + "ArrayExpression, ArrayPattern"(node) { + const openingBracket = sourceCode.getFirstToken(node); + const closingBracket = sourceCode.getTokenAfter( + [...node.elements].reverse().find(_ => _) || openingBracket, + astUtils.isClosingBracketToken, + ); + + addElementListIndent( + node.elements, + openingBracket, + closingBracket, + options.ArrayExpression, + ); + }, + + "ObjectExpression, ObjectPattern"(node) { + const openingCurly = sourceCode.getFirstToken(node); + const closingCurly = sourceCode.getTokenAfter( + node.properties.length + ? node.properties.at(-1) + : openingCurly, + astUtils.isClosingBraceToken, + ); + + addElementListIndent( + node.properties, + openingCurly, + closingCurly, + options.ObjectExpression, + ); + }, + + ArrowFunctionExpression(node) { + const maybeOpeningParen = sourceCode.getFirstToken(node, { + skip: node.async ? 1 : 0, + }); + + if (astUtils.isOpeningParenToken(maybeOpeningParen)) { + const openingParen = maybeOpeningParen; + const closingParen = sourceCode.getTokenBefore( + node.body, + astUtils.isClosingParenToken, + ); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + addElementListIndent( + node.params, + openingParen, + closingParen, + options.FunctionExpression.parameters, + ); + } + + addBlocklessNodeIndent(node.body); + }, + + AssignmentExpression(node) { + const operator = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + + offsets.setDesiredOffsets( + [operator.range[0], node.range[1]], + sourceCode.getLastToken(node.left), + 1, + ); + offsets.ignoreToken(operator); + offsets.ignoreToken(sourceCode.getTokenAfter(operator)); + }, + + "BinaryExpression, LogicalExpression"(node) { + const operator = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + + /* + * For backwards compatibility, don't check BinaryExpression indents, e.g. + * var foo = bar && + * baz; + */ + + const tokenAfterOperator = sourceCode.getTokenAfter(operator); + + offsets.ignoreToken(operator); + offsets.ignoreToken(tokenAfterOperator); + offsets.setDesiredOffset(tokenAfterOperator, operator, 0); + }, + + "BlockStatement, ClassBody"(node) { + let blockIndentLevel; + + if (node.parent && isOuterIIFE(node.parent)) { + blockIndentLevel = options.outerIIFEBody; + } else if ( + node.parent && + (node.parent.type === "FunctionExpression" || + node.parent.type === "ArrowFunctionExpression") + ) { + blockIndentLevel = options.FunctionExpression.body; + } else if ( + node.parent && + node.parent.type === "FunctionDeclaration" + ) { + blockIndentLevel = options.FunctionDeclaration.body; + } else { + blockIndentLevel = 1; + } + + /* + * For blocks that aren't lone statements, ensure that the opening curly brace + * is aligned with the parent. + */ + if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { + offsets.setDesiredOffset( + sourceCode.getFirstToken(node), + sourceCode.getFirstToken(node.parent), + 0, + ); + } + + addElementListIndent( + node.body, + sourceCode.getFirstToken(node), + sourceCode.getLastToken(node), + blockIndentLevel, + ); + }, + + CallExpression: addFunctionCallIndent, + + "ClassDeclaration[superClass], ClassExpression[superClass]"(node) { + const classToken = sourceCode.getFirstToken(node); + const extendsToken = sourceCode.getTokenBefore( + node.superClass, + astUtils.isNotOpeningParenToken, + ); + + offsets.setDesiredOffsets( + [extendsToken.range[0], node.body.range[0]], + classToken, + 1, + ); + }, + + ConditionalExpression(node) { + const firstToken = sourceCode.getFirstToken(node); + + // `flatTernaryExpressions` option is for the following style: + // var a = + // foo > 0 ? bar : + // foo < 0 ? baz : + // /*else*/ qiz ; + if ( + !options.flatTernaryExpressions || + !astUtils.isTokenOnSameLine(node.test, node.consequent) || + isOnFirstLineOfStatement(firstToken, node) + ) { + const questionMarkToken = sourceCode.getFirstTokenBetween( + node.test, + node.consequent, + token => + token.type === "Punctuator" && token.value === "?", + ); + const colonToken = sourceCode.getFirstTokenBetween( + node.consequent, + node.alternate, + token => + token.type === "Punctuator" && token.value === ":", + ); + + const firstConsequentToken = + sourceCode.getTokenAfter(questionMarkToken); + const lastConsequentToken = + sourceCode.getTokenBefore(colonToken); + const firstAlternateToken = + sourceCode.getTokenAfter(colonToken); + + offsets.setDesiredOffset(questionMarkToken, firstToken, 1); + offsets.setDesiredOffset(colonToken, firstToken, 1); + + offsets.setDesiredOffset( + firstConsequentToken, + firstToken, + firstConsequentToken.type === "Punctuator" && + options.offsetTernaryExpressions + ? 2 + : 1, + ); + + /* + * The alternate and the consequent should usually have the same indentation. + * If they share part of a line, align the alternate against the first token of the consequent. + * This allows the alternate to be indented correctly in cases like this: + * foo ? ( + * bar + * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo` + * baz // as a result, `baz` is offset by 1 rather than 2 + * ) + */ + if ( + lastConsequentToken.loc.end.line === + firstAlternateToken.loc.start.line + ) { + offsets.setDesiredOffset( + firstAlternateToken, + firstConsequentToken, + 0, + ); + } else { + /** + * If the alternate and consequent do not share part of a line, offset the alternate from the first + * token of the conditional expression. For example: + * foo ? bar + * : baz + * + * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up + * having no expected indentation. + */ + offsets.setDesiredOffset( + firstAlternateToken, + firstToken, + firstAlternateToken.type === "Punctuator" && + options.offsetTernaryExpressions + ? 2 + : 1, + ); + } + } + }, + + "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement, WithStatement": + node => addBlocklessNodeIndent(node.body), + + ExportNamedDeclaration(node) { + if (node.declaration === null) { + const closingCurly = sourceCode.getLastToken( + node, + astUtils.isClosingBraceToken, + ); + + // Indent the specifiers in `export {foo, bar, baz}` + addElementListIndent( + node.specifiers, + sourceCode.getFirstToken(node, { skip: 1 }), + closingCurly, + 1, + ); + + if (node.source) { + // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'` + offsets.setDesiredOffsets( + [closingCurly.range[1], node.range[1]], + sourceCode.getFirstToken(node), + 1, + ); + } + } + }, + + ForStatement(node) { + const forOpeningParen = sourceCode.getFirstToken(node, 1); + + if (node.init) { + offsets.setDesiredOffsets( + node.init.range, + forOpeningParen, + 1, + ); + } + if (node.test) { + offsets.setDesiredOffsets( + node.test.range, + forOpeningParen, + 1, + ); + } + if (node.update) { + offsets.setDesiredOffsets( + node.update.range, + forOpeningParen, + 1, + ); + } + addBlocklessNodeIndent(node.body); + }, + + "FunctionDeclaration, FunctionExpression"(node) { + const closingParen = sourceCode.getTokenBefore(node.body); + const openingParen = sourceCode.getTokenBefore( + node.params.length ? node.params[0] : closingParen, + ); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + addElementListIndent( + node.params, + openingParen, + closingParen, + options[node.type].parameters, + ); + }, + + IfStatement(node) { + addBlocklessNodeIndent(node.consequent); + if (node.alternate) { + addBlocklessNodeIndent(node.alternate); + } + }, + + /* + * For blockless nodes with semicolon-first style, don't indent the semicolon. + * e.g. + * if (foo) + * bar() + * ; [1, 2, 3].map(foo) + * + * Traversal into the node sets indentation of the semicolon, so we need to override it on exit. + */ + ":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement, WithStatement):exit"( + node, + ) { + let nodesToCheck; + + if (node.type === "IfStatement") { + nodesToCheck = [node.consequent]; + if (node.alternate) { + nodesToCheck.push(node.alternate); + } + } else { + nodesToCheck = [node.body]; + } + + for (const nodeToCheck of nodesToCheck) { + const lastToken = sourceCode.getLastToken(nodeToCheck); + + if (astUtils.isSemicolonToken(lastToken)) { + const tokenBeforeLast = + sourceCode.getTokenBefore(lastToken); + const tokenAfterLast = + sourceCode.getTokenAfter(lastToken); + + // override indentation of `;` only if its line looks like a semicolon-first style line + if ( + !astUtils.isTokenOnSameLine( + tokenBeforeLast, + lastToken, + ) && + tokenAfterLast && + astUtils.isTokenOnSameLine( + lastToken, + tokenAfterLast, + ) + ) { + offsets.setDesiredOffset( + lastToken, + sourceCode.getFirstToken(node), + 0, + ); + } + } + } + }, + + ImportDeclaration(node) { + if ( + node.specifiers.some( + specifier => specifier.type === "ImportSpecifier", + ) + ) { + const openingCurly = sourceCode.getFirstToken( + node, + astUtils.isOpeningBraceToken, + ); + const closingCurly = sourceCode.getLastToken( + node, + astUtils.isClosingBraceToken, + ); + + addElementListIndent( + node.specifiers.filter( + specifier => specifier.type === "ImportSpecifier", + ), + openingCurly, + closingCurly, + options.ImportDeclaration, + ); + } + + const fromToken = sourceCode.getLastToken( + node, + token => + token.type === "Identifier" && token.value === "from", + ); + const sourceToken = sourceCode.getLastToken( + node, + token => token.type === "String", + ); + const semiToken = sourceCode.getLastToken( + node, + token => token.type === "Punctuator" && token.value === ";", + ); + + if (fromToken) { + const end = + semiToken && semiToken.range[1] === sourceToken.range[1] + ? node.range[1] + : sourceToken.range[1]; + + offsets.setDesiredOffsets( + [fromToken.range[0], end], + sourceCode.getFirstToken(node), + 1, + ); + } + }, + + ImportExpression(node) { + const openingParen = sourceCode.getFirstToken(node, 1); + const closingParen = sourceCode.getLastToken(node); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + offsets.setDesiredOffset( + openingParen, + sourceCode.getTokenBefore(openingParen), + 0, + ); + + addElementListIndent( + [node.source], + openingParen, + closingParen, + options.CallExpression.arguments, + ); + }, + + "MemberExpression, JSXMemberExpression, MetaProperty"(node) { + const object = + node.type === "MetaProperty" ? node.meta : node.object; + const firstNonObjectToken = sourceCode.getFirstTokenBetween( + object, + node.property, + astUtils.isNotClosingParenToken, + ); + const secondNonObjectToken = + sourceCode.getTokenAfter(firstNonObjectToken); + + const objectParenCount = sourceCode.getTokensBetween( + object, + node.property, + { filter: astUtils.isClosingParenToken }, + ).length; + const firstObjectToken = objectParenCount + ? sourceCode.getTokenBefore(object, { + skip: objectParenCount - 1, + }) + : sourceCode.getFirstToken(object); + const lastObjectToken = + sourceCode.getTokenBefore(firstNonObjectToken); + const firstPropertyToken = node.computed + ? firstNonObjectToken + : secondNonObjectToken; + + if (node.computed) { + // For computed MemberExpressions, match the closing bracket with the opening bracket. + offsets.setDesiredOffset( + sourceCode.getLastToken(node), + firstNonObjectToken, + 0, + ); + offsets.setDesiredOffsets( + node.property.range, + firstNonObjectToken, + 1, + ); + } + + /* + * If the object ends on the same line that the property starts, match against the last token + * of the object, to ensure that the MemberExpression is not indented. + * + * Otherwise, match against the first token of the object, e.g. + * foo + * .bar + * .baz // <-- offset by 1 from `foo` + */ + const offsetBase = + lastObjectToken.loc.end.line === + firstPropertyToken.loc.start.line + ? lastObjectToken + : firstObjectToken; + + if (typeof options.MemberExpression === "number") { + // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object. + offsets.setDesiredOffset( + firstNonObjectToken, + offsetBase, + options.MemberExpression, + ); + + /* + * For computed MemberExpressions, match the first token of the property against the opening bracket. + * Otherwise, match the first token of the property against the object. + */ + offsets.setDesiredOffset( + secondNonObjectToken, + node.computed ? firstNonObjectToken : offsetBase, + options.MemberExpression, + ); + } else { + // If the MemberExpression option is off, ignore the dot and the first token of the property. + offsets.ignoreToken(firstNonObjectToken); + offsets.ignoreToken(secondNonObjectToken); + + // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens. + offsets.setDesiredOffset( + firstNonObjectToken, + offsetBase, + 0, + ); + offsets.setDesiredOffset( + secondNonObjectToken, + firstNonObjectToken, + 0, + ); + } + }, + + NewExpression(node) { + // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo` + if ( + node.arguments.length > 0 || + (astUtils.isClosingParenToken( + sourceCode.getLastToken(node), + ) && + astUtils.isOpeningParenToken( + sourceCode.getLastToken(node, 1), + )) + ) { + addFunctionCallIndent(node); + } + }, + + Property(node) { + if (!node.shorthand && !node.method && node.kind === "init") { + const colon = sourceCode.getFirstTokenBetween( + node.key, + node.value, + astUtils.isColonToken, + ); + + offsets.ignoreToken(sourceCode.getTokenAfter(colon)); + } + }, + + PropertyDefinition(node) { + const firstToken = sourceCode.getFirstToken(node); + const maybeSemicolonToken = sourceCode.getLastToken(node); + let keyLastToken; + + // Indent key. + if (node.computed) { + const bracketTokenL = sourceCode.getTokenBefore( + node.key, + astUtils.isOpeningBracketToken, + ); + const bracketTokenR = (keyLastToken = + sourceCode.getTokenAfter( + node.key, + astUtils.isClosingBracketToken, + )); + const keyRange = [ + bracketTokenL.range[1], + bracketTokenR.range[0], + ]; + + if (bracketTokenL !== firstToken) { + offsets.setDesiredOffset(bracketTokenL, firstToken, 0); + } + offsets.setDesiredOffsets(keyRange, bracketTokenL, 1); + offsets.setDesiredOffset(bracketTokenR, bracketTokenL, 0); + } else { + const idToken = (keyLastToken = sourceCode.getFirstToken( + node.key, + )); + + if (idToken !== firstToken) { + offsets.setDesiredOffset(idToken, firstToken, 1); + } + } + + // Indent initializer. + if (node.value) { + const eqToken = sourceCode.getTokenBefore( + node.value, + astUtils.isEqToken, + ); + const valueToken = sourceCode.getTokenAfter(eqToken); + + offsets.setDesiredOffset(eqToken, keyLastToken, 1); + offsets.setDesiredOffset(valueToken, eqToken, 1); + if (astUtils.isSemicolonToken(maybeSemicolonToken)) { + offsets.setDesiredOffset( + maybeSemicolonToken, + eqToken, + 1, + ); + } + } else if (astUtils.isSemicolonToken(maybeSemicolonToken)) { + offsets.setDesiredOffset( + maybeSemicolonToken, + keyLastToken, + 1, + ); + } + }, + + StaticBlock(node) { + const openingCurly = sourceCode.getFirstToken(node, { + skip: 1, + }); // skip the `static` token + const closingCurly = sourceCode.getLastToken(node); + + addElementListIndent( + node.body, + openingCurly, + closingCurly, + options.StaticBlock.body, + ); + }, + + SwitchStatement(node) { + const openingCurly = sourceCode.getTokenAfter( + node.discriminant, + astUtils.isOpeningBraceToken, + ); + const closingCurly = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets( + [openingCurly.range[1], closingCurly.range[0]], + openingCurly, + options.SwitchCase, + ); + + if (node.cases.length) { + sourceCode + .getTokensBetween(node.cases.at(-1), closingCurly, { + includeComments: true, + filter: astUtils.isCommentToken, + }) + .forEach(token => offsets.ignoreToken(token)); + } + }, + + SwitchCase(node) { + if ( + !( + node.consequent.length === 1 && + node.consequent[0].type === "BlockStatement" + ) + ) { + const caseKeyword = sourceCode.getFirstToken(node); + const tokenAfterCurrentCase = + sourceCode.getTokenAfter(node); + + offsets.setDesiredOffsets( + [caseKeyword.range[1], tokenAfterCurrentCase.range[0]], + caseKeyword, + 1, + ); + } + }, + + TemplateLiteral(node) { + node.expressions.forEach((expression, index) => { + const previousQuasi = node.quasis[index]; + const nextQuasi = node.quasis[index + 1]; + const tokenToAlignFrom = + previousQuasi.loc.start.line === + previousQuasi.loc.end.line + ? sourceCode.getFirstToken(previousQuasi) + : null; + + offsets.setDesiredOffsets( + [previousQuasi.range[1], nextQuasi.range[0]], + tokenToAlignFrom, + 1, + ); + offsets.setDesiredOffset( + sourceCode.getFirstToken(nextQuasi), + tokenToAlignFrom, + 0, + ); + }); + }, + + VariableDeclaration(node) { + let variableIndent = Object.hasOwn( + options.VariableDeclarator, + node.kind, + ) + ? options.VariableDeclarator[node.kind] + : DEFAULT_VARIABLE_INDENT; + + const firstToken = sourceCode.getFirstToken(node), + lastToken = sourceCode.getLastToken(node); + + if (options.VariableDeclarator[node.kind] === "first") { + if (node.declarations.length > 1) { + addElementListIndent( + node.declarations, + firstToken, + lastToken, + "first", + ); + return; + } + + variableIndent = DEFAULT_VARIABLE_INDENT; + } + + if ( + node.declarations.at(-1).loc.start.line > + node.loc.start.line + ) { + /* + * VariableDeclarator indentation is a bit different from other forms of indentation, in that the + * indentation of an opening bracket sometimes won't match that of a closing bracket. For example, + * the following indentations are correct: + * + * var foo = { + * ok: true + * }; + * + * var foo = { + * ok: true, + * }, + * bar = 1; + * + * Account for when exiting the AST (after indentations have already been set for the nodes in + * the declaration) by manually increasing the indentation level of the tokens in this declarator + * on the same line as the start of the declaration, provided that there are declarators that + * follow this one. + */ + offsets.setDesiredOffsets( + node.range, + firstToken, + variableIndent, + true, + ); + } else { + offsets.setDesiredOffsets( + node.range, + firstToken, + variableIndent, + ); + } + + if (astUtils.isSemicolonToken(lastToken)) { + offsets.ignoreToken(lastToken); + } + }, + + VariableDeclarator(node) { + if (node.init) { + const equalOperator = sourceCode.getTokenBefore( + node.init, + astUtils.isNotOpeningParenToken, + ); + const tokenAfterOperator = + sourceCode.getTokenAfter(equalOperator); + + offsets.ignoreToken(equalOperator); + offsets.ignoreToken(tokenAfterOperator); + offsets.setDesiredOffsets( + [tokenAfterOperator.range[0], node.range[1]], + equalOperator, + 1, + ); + offsets.setDesiredOffset( + equalOperator, + sourceCode.getLastToken(node.id), + 0, + ); + } + }, + + "JSXAttribute[value]"(node) { + const equalsToken = sourceCode.getFirstTokenBetween( + node.name, + node.value, + token => token.type === "Punctuator" && token.value === "=", + ); + + offsets.setDesiredOffsets( + [equalsToken.range[0], node.value.range[1]], + sourceCode.getFirstToken(node.name), + 1, + ); + }, + + JSXElement(node) { + if (node.closingElement) { + addElementListIndent( + node.children, + sourceCode.getFirstToken(node.openingElement), + sourceCode.getFirstToken(node.closingElement), + 1, + ); + } + }, + + JSXOpeningElement(node) { + const firstToken = sourceCode.getFirstToken(node); + let closingToken; + + if (node.selfClosing) { + closingToken = sourceCode.getLastToken(node, { skip: 1 }); + offsets.setDesiredOffset( + sourceCode.getLastToken(node), + closingToken, + 0, + ); + } else { + closingToken = sourceCode.getLastToken(node); + } + offsets.setDesiredOffsets( + node.name.range, + sourceCode.getFirstToken(node), + ); + addElementListIndent( + node.attributes, + firstToken, + closingToken, + 1, + ); + }, + + JSXClosingElement(node) { + const firstToken = sourceCode.getFirstToken(node); + + offsets.setDesiredOffsets(node.name.range, firstToken, 1); + }, + + JSXFragment(node) { + const firstOpeningToken = sourceCode.getFirstToken( + node.openingFragment, + ); + const firstClosingToken = sourceCode.getFirstToken( + node.closingFragment, + ); + + addElementListIndent( + node.children, + firstOpeningToken, + firstClosingToken, + 1, + ); + }, + + JSXOpeningFragment(node) { + const firstToken = sourceCode.getFirstToken(node); + const closingToken = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets(node.range, firstToken, 1); + offsets.matchOffsetOf(firstToken, closingToken); + }, + + JSXClosingFragment(node) { + const firstToken = sourceCode.getFirstToken(node); + const slashToken = sourceCode.getLastToken(node, { skip: 1 }); + const closingToken = sourceCode.getLastToken(node); + const tokenToMatch = astUtils.isTokenOnSameLine( + slashToken, + closingToken, + ) + ? slashToken + : closingToken; + + offsets.setDesiredOffsets(node.range, firstToken, 1); + offsets.matchOffsetOf(firstToken, tokenToMatch); + }, + + JSXExpressionContainer(node) { + const openingCurly = sourceCode.getFirstToken(node); + const closingCurly = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets( + [openingCurly.range[1], closingCurly.range[0]], + openingCurly, + 1, + ); + }, + + JSXSpreadAttribute(node) { + const openingCurly = sourceCode.getFirstToken(node); + const closingCurly = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets( + [openingCurly.range[1], closingCurly.range[0]], + openingCurly, + 1, + ); + }, + + "*"(node) { + const firstToken = sourceCode.getFirstToken(node); + + // Ensure that the children of every node are indented at least as much as the first token. + if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) { + offsets.setDesiredOffsets(node.range, firstToken, 0); + } + }, + }; + + const listenerCallQueue = []; + + /* + * To ignore the indentation of a node: + * 1. Don't call the node's listener when entering it (if it has a listener) + * 2. Don't set any offsets against the first token of the node. + * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets. + */ + const offsetListeners = {}; + + for (const [selector, listener] of Object.entries( + baseOffsetListeners, + )) { + /* + * Offset listener calls are deferred until traversal is finished, and are called as + * part of the final `Program:exit` listener. This is necessary because a node might + * be matched by multiple selectors. + * + * Example: Suppose there is an offset listener for `Identifier`, and the user has + * specified in configuration that `MemberExpression > Identifier` should be ignored. + * Due to selector specificity rules, the `Identifier` listener will get called first. However, + * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener + * should not have been called at all. Without doing extra selector matching, we don't know + * whether the Identifier matches the `MemberExpression > Identifier` selector until the + * `MemberExpression > Identifier` listener is called. + * + * To avoid this, the `Identifier` listener isn't called until traversal finishes and all + * ignored nodes are known. + */ + offsetListeners[selector] = node => + listenerCallQueue.push({ listener, node }); + } + + // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set. + const ignoredNodes = new Set(); + + /** + * Ignores a node + * @param {ASTNode} node The node to ignore + * @returns {void} + */ + function addToIgnoredNodes(node) { + ignoredNodes.add(node); + ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node)); + } + + const ignoredNodeListeners = options.ignoredNodes.reduce( + (listeners, ignoredSelector) => + Object.assign(listeners, { + [ignoredSelector]: addToIgnoredNodes, + }), + {}, + ); + + /* + * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation + * at the end. + * + * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears + * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored, + * so those listeners wouldn't be called anyway. + */ + return Object.assign(offsetListeners, ignoredNodeListeners, { + "*:exit"(node) { + // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it. + if (!KNOWN_NODES.has(node.type)) { + addToIgnoredNodes(node); + } + }, + "Program:exit"() { + // If ignoreComments option is enabled, ignore all comment tokens. + if (options.ignoreComments) { + sourceCode + .getAllComments() + .forEach(comment => offsets.ignoreToken(comment)); + } + + // Invoke the queued offset listeners for the nodes that aren't ignored. + for (let i = 0; i < listenerCallQueue.length; i++) { + const nodeInfo = listenerCallQueue[i]; + + if (!ignoredNodes.has(nodeInfo.node)) { + nodeInfo.listener(nodeInfo.node); + } + } + + // Update the offsets for ignored nodes to prevent their child tokens from being reported. + ignoredNodes.forEach(ignoreNode); + + addParensIndent(sourceCode.ast.tokens); + + /* + * Create a Map from (tokenOrComment) => (precedingToken). + * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly. + */ + const precedingTokens = new WeakMap(); + + for (let i = 0; i < sourceCode.ast.comments.length; i++) { + const comment = sourceCode.ast.comments[i]; + + const tokenOrCommentBefore = sourceCode.getTokenBefore( + comment, + { includeComments: true }, + ); + const hasToken = precedingTokens.has(tokenOrCommentBefore) + ? precedingTokens.get(tokenOrCommentBefore) + : tokenOrCommentBefore; + + precedingTokens.set(comment, hasToken); + } + + for (let i = 1; i < sourceCode.lines.length + 1; i++) { + if (!tokenInfo.firstTokensByLineNumber.has(i)) { + // Don't check indentation on blank lines + continue; + } + + const firstTokenOfLine = + tokenInfo.firstTokensByLineNumber.get(i); + + if (firstTokenOfLine.loc.start.line !== i) { + // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice. + continue; + } + + if (astUtils.isCommentToken(firstTokenOfLine)) { + const tokenBefore = + precedingTokens.get(firstTokenOfLine); + const tokenAfter = tokenBefore + ? sourceCode.getTokenAfter(tokenBefore) + : sourceCode.ast.tokens[0]; + const mayAlignWithBefore = + tokenBefore && + !hasBlankLinesBetween( + tokenBefore, + firstTokenOfLine, + ); + const mayAlignWithAfter = + tokenAfter && + !hasBlankLinesBetween(firstTokenOfLine, tokenAfter); + + /* + * If a comment precedes a line that begins with a semicolon token, align to that token, i.e. + * + * let foo + * // comment + * ;(async () => {})() + */ + if ( + tokenAfter && + astUtils.isSemicolonToken(tokenAfter) && + !astUtils.isTokenOnSameLine( + firstTokenOfLine, + tokenAfter, + ) + ) { + offsets.setDesiredOffset( + firstTokenOfLine, + tokenAfter, + 0, + ); + } + + // If a comment matches the expected indentation of the token immediately before or after, don't report it. + if ( + (mayAlignWithBefore && + validateTokenIndent( + firstTokenOfLine, + offsets.getDesiredIndent(tokenBefore), + )) || + (mayAlignWithAfter && + validateTokenIndent( + firstTokenOfLine, + offsets.getDesiredIndent(tokenAfter), + )) + ) { + continue; + } + } + + // If the token matches the expected indentation, don't report it. + if ( + validateTokenIndent( + firstTokenOfLine, + offsets.getDesiredIndent(firstTokenOfLine), + ) + ) { + continue; + } + + // Otherwise, report the token/comment. + report( + firstTokenOfLine, + offsets.getDesiredIndent(firstTokenOfLine), + ); + } + }, + }); + }, +}; diff --git a/node_modules/eslint/lib/rules/index.js b/node_modules/eslint/lib/rules/index.js new file mode 100644 index 00000000..0034ac05 --- /dev/null +++ b/node_modules/eslint/lib/rules/index.js @@ -0,0 +1,331 @@ +/** + * @fileoverview Collects the built-in rules into a map structure so that they can be imported all at once and without + * using the file-system directly. + * @author Peter (Somogyvari) Metz + */ + +"use strict"; + +/* eslint sort-keys: ["error", "asc"] -- More readable for long list */ + +const { LazyLoadingRuleMap } = require("./utils/lazy-loading-rule-map"); + +/** @type {Map} */ +module.exports = new LazyLoadingRuleMap( + Object.entries({ + "accessor-pairs": () => require("./accessor-pairs"), + "array-bracket-newline": () => require("./array-bracket-newline"), + "array-bracket-spacing": () => require("./array-bracket-spacing"), + "array-callback-return": () => require("./array-callback-return"), + "array-element-newline": () => require("./array-element-newline"), + "arrow-body-style": () => require("./arrow-body-style"), + "arrow-parens": () => require("./arrow-parens"), + "arrow-spacing": () => require("./arrow-spacing"), + "block-scoped-var": () => require("./block-scoped-var"), + "block-spacing": () => require("./block-spacing"), + "brace-style": () => require("./brace-style"), + "callback-return": () => require("./callback-return"), + camelcase: () => require("./camelcase"), + "capitalized-comments": () => require("./capitalized-comments"), + "class-methods-use-this": () => require("./class-methods-use-this"), + "comma-dangle": () => require("./comma-dangle"), + "comma-spacing": () => require("./comma-spacing"), + "comma-style": () => require("./comma-style"), + complexity: () => require("./complexity"), + "computed-property-spacing": () => + require("./computed-property-spacing"), + "consistent-return": () => require("./consistent-return"), + "consistent-this": () => require("./consistent-this"), + "constructor-super": () => require("./constructor-super"), + curly: () => require("./curly"), + "default-case": () => require("./default-case"), + "default-case-last": () => require("./default-case-last"), + "default-param-last": () => require("./default-param-last"), + "dot-location": () => require("./dot-location"), + "dot-notation": () => require("./dot-notation"), + "eol-last": () => require("./eol-last"), + eqeqeq: () => require("./eqeqeq"), + "for-direction": () => require("./for-direction"), + "func-call-spacing": () => require("./func-call-spacing"), + "func-name-matching": () => require("./func-name-matching"), + "func-names": () => require("./func-names"), + "func-style": () => require("./func-style"), + "function-call-argument-newline": () => + require("./function-call-argument-newline"), + "function-paren-newline": () => require("./function-paren-newline"), + "generator-star-spacing": () => require("./generator-star-spacing"), + "getter-return": () => require("./getter-return"), + "global-require": () => require("./global-require"), + "grouped-accessor-pairs": () => require("./grouped-accessor-pairs"), + "guard-for-in": () => require("./guard-for-in"), + "handle-callback-err": () => require("./handle-callback-err"), + "id-blacklist": () => require("./id-blacklist"), + "id-denylist": () => require("./id-denylist"), + "id-length": () => require("./id-length"), + "id-match": () => require("./id-match"), + "implicit-arrow-linebreak": () => require("./implicit-arrow-linebreak"), + indent: () => require("./indent"), + "indent-legacy": () => require("./indent-legacy"), + "init-declarations": () => require("./init-declarations"), + "jsx-quotes": () => require("./jsx-quotes"), + "key-spacing": () => require("./key-spacing"), + "keyword-spacing": () => require("./keyword-spacing"), + "line-comment-position": () => require("./line-comment-position"), + "linebreak-style": () => require("./linebreak-style"), + "lines-around-comment": () => require("./lines-around-comment"), + "lines-around-directive": () => require("./lines-around-directive"), + "lines-between-class-members": () => + require("./lines-between-class-members"), + "logical-assignment-operators": () => + require("./logical-assignment-operators"), + "max-classes-per-file": () => require("./max-classes-per-file"), + "max-depth": () => require("./max-depth"), + "max-len": () => require("./max-len"), + "max-lines": () => require("./max-lines"), + "max-lines-per-function": () => require("./max-lines-per-function"), + "max-nested-callbacks": () => require("./max-nested-callbacks"), + "max-params": () => require("./max-params"), + "max-statements": () => require("./max-statements"), + "max-statements-per-line": () => require("./max-statements-per-line"), + "multiline-comment-style": () => require("./multiline-comment-style"), + "multiline-ternary": () => require("./multiline-ternary"), + "new-cap": () => require("./new-cap"), + "new-parens": () => require("./new-parens"), + "newline-after-var": () => require("./newline-after-var"), + "newline-before-return": () => require("./newline-before-return"), + "newline-per-chained-call": () => require("./newline-per-chained-call"), + "no-alert": () => require("./no-alert"), + "no-array-constructor": () => require("./no-array-constructor"), + "no-async-promise-executor": () => + require("./no-async-promise-executor"), + "no-await-in-loop": () => require("./no-await-in-loop"), + "no-bitwise": () => require("./no-bitwise"), + "no-buffer-constructor": () => require("./no-buffer-constructor"), + "no-caller": () => require("./no-caller"), + "no-case-declarations": () => require("./no-case-declarations"), + "no-catch-shadow": () => require("./no-catch-shadow"), + "no-class-assign": () => require("./no-class-assign"), + "no-compare-neg-zero": () => require("./no-compare-neg-zero"), + "no-cond-assign": () => require("./no-cond-assign"), + "no-confusing-arrow": () => require("./no-confusing-arrow"), + "no-console": () => require("./no-console"), + "no-const-assign": () => require("./no-const-assign"), + "no-constant-binary-expression": () => + require("./no-constant-binary-expression"), + "no-constant-condition": () => require("./no-constant-condition"), + "no-constructor-return": () => require("./no-constructor-return"), + "no-continue": () => require("./no-continue"), + "no-control-regex": () => require("./no-control-regex"), + "no-debugger": () => require("./no-debugger"), + "no-delete-var": () => require("./no-delete-var"), + "no-div-regex": () => require("./no-div-regex"), + "no-dupe-args": () => require("./no-dupe-args"), + "no-dupe-class-members": () => require("./no-dupe-class-members"), + "no-dupe-else-if": () => require("./no-dupe-else-if"), + "no-dupe-keys": () => require("./no-dupe-keys"), + "no-duplicate-case": () => require("./no-duplicate-case"), + "no-duplicate-imports": () => require("./no-duplicate-imports"), + "no-else-return": () => require("./no-else-return"), + "no-empty": () => require("./no-empty"), + "no-empty-character-class": () => require("./no-empty-character-class"), + "no-empty-function": () => require("./no-empty-function"), + "no-empty-pattern": () => require("./no-empty-pattern"), + "no-empty-static-block": () => require("./no-empty-static-block"), + "no-eq-null": () => require("./no-eq-null"), + "no-eval": () => require("./no-eval"), + "no-ex-assign": () => require("./no-ex-assign"), + "no-extend-native": () => require("./no-extend-native"), + "no-extra-bind": () => require("./no-extra-bind"), + "no-extra-boolean-cast": () => require("./no-extra-boolean-cast"), + "no-extra-label": () => require("./no-extra-label"), + "no-extra-parens": () => require("./no-extra-parens"), + "no-extra-semi": () => require("./no-extra-semi"), + "no-fallthrough": () => require("./no-fallthrough"), + "no-floating-decimal": () => require("./no-floating-decimal"), + "no-func-assign": () => require("./no-func-assign"), + "no-global-assign": () => require("./no-global-assign"), + "no-implicit-coercion": () => require("./no-implicit-coercion"), + "no-implicit-globals": () => require("./no-implicit-globals"), + "no-implied-eval": () => require("./no-implied-eval"), + "no-import-assign": () => require("./no-import-assign"), + "no-inline-comments": () => require("./no-inline-comments"), + "no-inner-declarations": () => require("./no-inner-declarations"), + "no-invalid-regexp": () => require("./no-invalid-regexp"), + "no-invalid-this": () => require("./no-invalid-this"), + "no-irregular-whitespace": () => require("./no-irregular-whitespace"), + "no-iterator": () => require("./no-iterator"), + "no-label-var": () => require("./no-label-var"), + "no-labels": () => require("./no-labels"), + "no-lone-blocks": () => require("./no-lone-blocks"), + "no-lonely-if": () => require("./no-lonely-if"), + "no-loop-func": () => require("./no-loop-func"), + "no-loss-of-precision": () => require("./no-loss-of-precision"), + "no-magic-numbers": () => require("./no-magic-numbers"), + "no-misleading-character-class": () => + require("./no-misleading-character-class"), + "no-mixed-operators": () => require("./no-mixed-operators"), + "no-mixed-requires": () => require("./no-mixed-requires"), + "no-mixed-spaces-and-tabs": () => require("./no-mixed-spaces-and-tabs"), + "no-multi-assign": () => require("./no-multi-assign"), + "no-multi-spaces": () => require("./no-multi-spaces"), + "no-multi-str": () => require("./no-multi-str"), + "no-multiple-empty-lines": () => require("./no-multiple-empty-lines"), + "no-native-reassign": () => require("./no-native-reassign"), + "no-negated-condition": () => require("./no-negated-condition"), + "no-negated-in-lhs": () => require("./no-negated-in-lhs"), + "no-nested-ternary": () => require("./no-nested-ternary"), + "no-new": () => require("./no-new"), + "no-new-func": () => require("./no-new-func"), + "no-new-native-nonconstructor": () => + require("./no-new-native-nonconstructor"), + "no-new-object": () => require("./no-new-object"), + "no-new-require": () => require("./no-new-require"), + "no-new-symbol": () => require("./no-new-symbol"), + "no-new-wrappers": () => require("./no-new-wrappers"), + "no-nonoctal-decimal-escape": () => + require("./no-nonoctal-decimal-escape"), + "no-obj-calls": () => require("./no-obj-calls"), + "no-object-constructor": () => require("./no-object-constructor"), + "no-octal": () => require("./no-octal"), + "no-octal-escape": () => require("./no-octal-escape"), + "no-param-reassign": () => require("./no-param-reassign"), + "no-path-concat": () => require("./no-path-concat"), + "no-plusplus": () => require("./no-plusplus"), + "no-process-env": () => require("./no-process-env"), + "no-process-exit": () => require("./no-process-exit"), + "no-promise-executor-return": () => + require("./no-promise-executor-return"), + "no-proto": () => require("./no-proto"), + "no-prototype-builtins": () => require("./no-prototype-builtins"), + "no-redeclare": () => require("./no-redeclare"), + "no-regex-spaces": () => require("./no-regex-spaces"), + "no-restricted-exports": () => require("./no-restricted-exports"), + "no-restricted-globals": () => require("./no-restricted-globals"), + "no-restricted-imports": () => require("./no-restricted-imports"), + "no-restricted-modules": () => require("./no-restricted-modules"), + "no-restricted-properties": () => require("./no-restricted-properties"), + "no-restricted-syntax": () => require("./no-restricted-syntax"), + "no-return-assign": () => require("./no-return-assign"), + "no-return-await": () => require("./no-return-await"), + "no-script-url": () => require("./no-script-url"), + "no-self-assign": () => require("./no-self-assign"), + "no-self-compare": () => require("./no-self-compare"), + "no-sequences": () => require("./no-sequences"), + "no-setter-return": () => require("./no-setter-return"), + "no-shadow": () => require("./no-shadow"), + "no-shadow-restricted-names": () => + require("./no-shadow-restricted-names"), + "no-spaced-func": () => require("./no-spaced-func"), + "no-sparse-arrays": () => require("./no-sparse-arrays"), + "no-sync": () => require("./no-sync"), + "no-tabs": () => require("./no-tabs"), + "no-template-curly-in-string": () => + require("./no-template-curly-in-string"), + "no-ternary": () => require("./no-ternary"), + "no-this-before-super": () => require("./no-this-before-super"), + "no-throw-literal": () => require("./no-throw-literal"), + "no-trailing-spaces": () => require("./no-trailing-spaces"), + "no-unassigned-vars": () => require("./no-unassigned-vars"), + "no-undef": () => require("./no-undef"), + "no-undef-init": () => require("./no-undef-init"), + "no-undefined": () => require("./no-undefined"), + "no-underscore-dangle": () => require("./no-underscore-dangle"), + "no-unexpected-multiline": () => require("./no-unexpected-multiline"), + "no-unmodified-loop-condition": () => + require("./no-unmodified-loop-condition"), + "no-unneeded-ternary": () => require("./no-unneeded-ternary"), + "no-unreachable": () => require("./no-unreachable"), + "no-unreachable-loop": () => require("./no-unreachable-loop"), + "no-unsafe-finally": () => require("./no-unsafe-finally"), + "no-unsafe-negation": () => require("./no-unsafe-negation"), + "no-unsafe-optional-chaining": () => + require("./no-unsafe-optional-chaining"), + "no-unused-expressions": () => require("./no-unused-expressions"), + "no-unused-labels": () => require("./no-unused-labels"), + "no-unused-private-class-members": () => + require("./no-unused-private-class-members"), + "no-unused-vars": () => require("./no-unused-vars"), + "no-use-before-define": () => require("./no-use-before-define"), + "no-useless-assignment": () => require("./no-useless-assignment"), + "no-useless-backreference": () => require("./no-useless-backreference"), + "no-useless-call": () => require("./no-useless-call"), + "no-useless-catch": () => require("./no-useless-catch"), + "no-useless-computed-key": () => require("./no-useless-computed-key"), + "no-useless-concat": () => require("./no-useless-concat"), + "no-useless-constructor": () => require("./no-useless-constructor"), + "no-useless-escape": () => require("./no-useless-escape"), + "no-useless-rename": () => require("./no-useless-rename"), + "no-useless-return": () => require("./no-useless-return"), + "no-var": () => require("./no-var"), + "no-void": () => require("./no-void"), + "no-warning-comments": () => require("./no-warning-comments"), + "no-whitespace-before-property": () => + require("./no-whitespace-before-property"), + "no-with": () => require("./no-with"), + "nonblock-statement-body-position": () => + require("./nonblock-statement-body-position"), + "object-curly-newline": () => require("./object-curly-newline"), + "object-curly-spacing": () => require("./object-curly-spacing"), + "object-property-newline": () => require("./object-property-newline"), + "object-shorthand": () => require("./object-shorthand"), + "one-var": () => require("./one-var"), + "one-var-declaration-per-line": () => + require("./one-var-declaration-per-line"), + "operator-assignment": () => require("./operator-assignment"), + "operator-linebreak": () => require("./operator-linebreak"), + "padded-blocks": () => require("./padded-blocks"), + "padding-line-between-statements": () => + require("./padding-line-between-statements"), + "prefer-arrow-callback": () => require("./prefer-arrow-callback"), + "prefer-const": () => require("./prefer-const"), + "prefer-destructuring": () => require("./prefer-destructuring"), + "prefer-exponentiation-operator": () => + require("./prefer-exponentiation-operator"), + "prefer-named-capture-group": () => + require("./prefer-named-capture-group"), + "prefer-numeric-literals": () => require("./prefer-numeric-literals"), + "prefer-object-has-own": () => require("./prefer-object-has-own"), + "prefer-object-spread": () => require("./prefer-object-spread"), + "prefer-promise-reject-errors": () => + require("./prefer-promise-reject-errors"), + "prefer-reflect": () => require("./prefer-reflect"), + "prefer-regex-literals": () => require("./prefer-regex-literals"), + "prefer-rest-params": () => require("./prefer-rest-params"), + "prefer-spread": () => require("./prefer-spread"), + "prefer-template": () => require("./prefer-template"), + "quote-props": () => require("./quote-props"), + quotes: () => require("./quotes"), + radix: () => require("./radix"), + "require-atomic-updates": () => require("./require-atomic-updates"), + "require-await": () => require("./require-await"), + "require-unicode-regexp": () => require("./require-unicode-regexp"), + "require-yield": () => require("./require-yield"), + "rest-spread-spacing": () => require("./rest-spread-spacing"), + semi: () => require("./semi"), + "semi-spacing": () => require("./semi-spacing"), + "semi-style": () => require("./semi-style"), + "sort-imports": () => require("./sort-imports"), + "sort-keys": () => require("./sort-keys"), + "sort-vars": () => require("./sort-vars"), + "space-before-blocks": () => require("./space-before-blocks"), + "space-before-function-paren": () => + require("./space-before-function-paren"), + "space-in-parens": () => require("./space-in-parens"), + "space-infix-ops": () => require("./space-infix-ops"), + "space-unary-ops": () => require("./space-unary-ops"), + "spaced-comment": () => require("./spaced-comment"), + strict: () => require("./strict"), + "switch-colon-spacing": () => require("./switch-colon-spacing"), + "symbol-description": () => require("./symbol-description"), + "template-curly-spacing": () => require("./template-curly-spacing"), + "template-tag-spacing": () => require("./template-tag-spacing"), + "unicode-bom": () => require("./unicode-bom"), + "use-isnan": () => require("./use-isnan"), + "valid-typeof": () => require("./valid-typeof"), + "vars-on-top": () => require("./vars-on-top"), + "wrap-iife": () => require("./wrap-iife"), + "wrap-regex": () => require("./wrap-regex"), + "yield-star-spacing": () => require("./yield-star-spacing"), + yoda: () => require("./yoda"), + }), +); diff --git a/node_modules/eslint/lib/rules/init-declarations.js b/node_modules/eslint/lib/rules/init-declarations.js new file mode 100644 index 00000000..e5b97605 --- /dev/null +++ b/node_modules/eslint/lib/rules/init-declarations.js @@ -0,0 +1,170 @@ +/** + * @fileoverview A rule to control the style of variable initializations. + * @author Colin Ihrig + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a for loop. + * @param {ASTNode} block A node to check. + * @returns {boolean} `true` when the node is a for loop. + */ +function isForLoop(block) { + return ( + block.type === "ForInStatement" || + block.type === "ForOfStatement" || + block.type === "ForStatement" + ); +} + +/** + * Checks whether or not a given declarator node has its initializer. + * @param {ASTNode} node A declarator node to check. + * @returns {boolean} `true` when the node has its initializer. + */ +function isInitialized(node) { + const declaration = node.parent; + const block = declaration.parent; + + if (isForLoop(block)) { + if (block.type === "ForStatement") { + return block.init === declaration; + } + return block.left === declaration; + } + return Boolean(node.init); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: + "Require or disallow initialization in variable declarations", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/init-declarations", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["never"], + }, + { + type: "object", + properties: { + ignoreForLoopInit: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + messages: { + initialized: + "Variable '{{idName}}' should be initialized on declaration.", + notInitialized: + "Variable '{{idName}}' should not be initialized on declaration.", + }, + }, + + create(context) { + const MODE_ALWAYS = "always", + MODE_NEVER = "never"; + + const mode = context.options[0] || MODE_ALWAYS; + const params = context.options[1] || {}; + + // Track whether we're inside a declared namespace + let insideDeclaredNamespace = false; + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + TSModuleDeclaration(node) { + if (node.declare) { + insideDeclaredNamespace = true; + } + }, + + "TSModuleDeclaration:exit"(node) { + if (node.declare) { + insideDeclaredNamespace = false; + } + }, + + "VariableDeclaration:exit"(node) { + const kind = node.kind, + declarations = node.declarations; + + if (node.declare || insideDeclaredNamespace) { + return; + } + + for (let i = 0; i < declarations.length; ++i) { + const declaration = declarations[i], + id = declaration.id, + initialized = isInitialized(declaration), + isIgnoredForLoop = + params.ignoreForLoopInit && isForLoop(node.parent); + let messageId = ""; + + if (mode === MODE_ALWAYS && !initialized) { + messageId = "initialized"; + } else if ( + mode === MODE_NEVER && + kind !== "const" && + initialized && + !isIgnoredForLoop + ) { + messageId = "notInitialized"; + } + + if (id.type === "Identifier" && messageId) { + context.report({ + node: declaration, + messageId, + data: { + idName: id.name, + }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/jsx-quotes.js b/node_modules/eslint/lib/rules/jsx-quotes.js new file mode 100644 index 00000000..80424c2c --- /dev/null +++ b/node_modules/eslint/lib/rules/jsx-quotes.js @@ -0,0 +1,128 @@ +/** + * @fileoverview A rule to ensure consistent quotes used in jsx syntax. + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const QUOTE_SETTINGS = { + "prefer-double": { + quote: '"', + description: "singlequote", + convert(str) { + return str.replace(/'/gu, '"'); + }, + }, + "prefer-single": { + quote: "'", + description: "doublequote", + convert(str) { + return str.replace(/"/gu, "'"); + }, + }, +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "jsx-quotes", + url: "https://eslint.style/rules/js/jsx-quotes", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce the consistent use of either double or single quotes in JSX attributes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/jsx-quotes", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["prefer-single", "prefer-double"], + }, + ], + messages: { + unexpected: "Unexpected usage of {{description}}.", + }, + }, + + create(context) { + const quoteOption = context.options[0] || "prefer-double", + setting = QUOTE_SETTINGS[quoteOption]; + + /** + * Checks if the given string literal node uses the expected quotes + * @param {ASTNode} node A string literal node. + * @returns {boolean} Whether or not the string literal used the expected quotes. + * @public + */ + function usesExpectedQuotes(node) { + return ( + node.value.includes(setting.quote) || + astUtils.isSurroundedBy(node.raw, setting.quote) + ); + } + + return { + JSXAttribute(node) { + const attributeValue = node.value; + + if ( + attributeValue && + astUtils.isStringLiteral(attributeValue) && + !usesExpectedQuotes(attributeValue) + ) { + context.report({ + node: attributeValue, + messageId: "unexpected", + data: { + description: setting.description, + }, + fix(fixer) { + return fixer.replaceText( + attributeValue, + setting.convert(attributeValue.raw), + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/key-spacing.js b/node_modules/eslint/lib/rules/key-spacing.js new file mode 100644 index 00000000..fec88248 --- /dev/null +++ b/node_modules/eslint/lib/rules/key-spacing.js @@ -0,0 +1,822 @@ +/** + * @fileoverview Rule to specify spacing of object literal keys and values + * @author Brandon Mills + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { getGraphemeCount } = require("../shared/string-utils"); + +/** + * Checks whether a string contains a line terminator as defined in + * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3 + * @param {string} str String to test. + * @returns {boolean} True if str contains a line terminator. + */ +function containsLineTerminator(str) { + return astUtils.LINEBREAK_MATCHER.test(str); +} + +/** + * Gets the last element of an array. + * @param {Array} arr An array. + * @returns {any} Last element of arr. + */ +function last(arr) { + return arr.at(-1); +} + +/** + * Checks whether a node is contained on a single line. + * @param {ASTNode} node AST Node being evaluated. + * @returns {boolean} True if the node is a single line. + */ +function isSingleLine(node) { + return node.loc.end.line === node.loc.start.line; +} + +/** + * Checks whether the properties on a single line. + * @param {ASTNode[]} properties List of Property AST nodes. + * @returns {boolean} True if all properties is on a single line. + */ +function isSingleLineProperties(properties) { + const [firstProp] = properties, + lastProp = last(properties); + + return firstProp.loc.start.line === lastProp.loc.end.line; +} + +/** + * Initializes a single option property from the configuration with defaults for undefined values + * @param {Object} toOptions Object to be initialized + * @param {Object} fromOptions Object to be initialized from + * @returns {Object} The object with correctly initialized options and values + */ +function initOptionProperty(toOptions, fromOptions) { + toOptions.mode = fromOptions.mode || "strict"; + + // Set value of beforeColon + if (typeof fromOptions.beforeColon !== "undefined") { + toOptions.beforeColon = +fromOptions.beforeColon; + } else { + toOptions.beforeColon = 0; + } + + // Set value of afterColon + if (typeof fromOptions.afterColon !== "undefined") { + toOptions.afterColon = +fromOptions.afterColon; + } else { + toOptions.afterColon = 1; + } + + // Set align if exists + if (typeof fromOptions.align !== "undefined") { + if (typeof fromOptions.align === "object") { + toOptions.align = fromOptions.align; + } else { + // "string" + toOptions.align = { + on: fromOptions.align, + mode: toOptions.mode, + beforeColon: toOptions.beforeColon, + afterColon: toOptions.afterColon, + }; + } + } + + return toOptions; +} + +/** + * Initializes all the option values (singleLine, multiLine and align) from the configuration with defaults for undefined values + * @param {Object} toOptions Object to be initialized + * @param {Object} fromOptions Object to be initialized from + * @returns {Object} The object with correctly initialized options and values + */ +function initOptions(toOptions, fromOptions) { + if (typeof fromOptions.align === "object") { + // Initialize the alignment configuration + toOptions.align = initOptionProperty({}, fromOptions.align); + toOptions.align.on = fromOptions.align.on || "colon"; + toOptions.align.mode = fromOptions.align.mode || "strict"; + + toOptions.multiLine = initOptionProperty( + {}, + fromOptions.multiLine || fromOptions, + ); + toOptions.singleLine = initOptionProperty( + {}, + fromOptions.singleLine || fromOptions, + ); + } else { + // string or undefined + toOptions.multiLine = initOptionProperty( + {}, + fromOptions.multiLine || fromOptions, + ); + toOptions.singleLine = initOptionProperty( + {}, + fromOptions.singleLine || fromOptions, + ); + + // If alignment options are defined in multiLine, pull them out into the general align configuration + if (toOptions.multiLine.align) { + toOptions.align = { + on: toOptions.multiLine.align.on, + mode: + toOptions.multiLine.align.mode || toOptions.multiLine.mode, + beforeColon: toOptions.multiLine.align.beforeColon, + afterColon: toOptions.multiLine.align.afterColon, + }; + } + } + + return toOptions; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "key-spacing", + url: "https://eslint.style/rules/js/key-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing between keys and values in object literal properties", + recommended: false, + url: "https://eslint.org/docs/latest/rules/key-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + anyOf: [ + { + type: "object", + properties: { + align: { + anyOf: [ + { + enum: ["colon", "value"], + }, + { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + on: { + enum: ["colon", "value"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + singleLine: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + multiLine: { + type: "object", + properties: { + align: { + anyOf: [ + { + enum: ["colon", "value"], + }, + { + type: "object", + properties: { + mode: { + enum: [ + "strict", + "minimum", + ], + }, + on: { + enum: [ + "colon", + "value", + ], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + singleLine: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + multiLine: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + align: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + on: { + enum: ["colon", "value"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + extraKey: "Extra space after {{computed}}key '{{key}}'.", + extraValue: + "Extra space before value for {{computed}}key '{{key}}'.", + missingKey: "Missing space after {{computed}}key '{{key}}'.", + missingValue: + "Missing space before value for {{computed}}key '{{key}}'.", + }, + }, + + create(context) { + /** + * OPTIONS + * "key-spacing": [2, { + * beforeColon: false, + * afterColon: true, + * align: "colon" // Optional, or "value" + * } + */ + const options = context.options[0] || {}, + ruleOptions = initOptions({}, options), + multiLineOptions = ruleOptions.multiLine, + singleLineOptions = ruleOptions.singleLine, + alignmentOptions = ruleOptions.align || null; + + const sourceCode = context.sourceCode; + + /** + * Determines if the given property is key-value property. + * @param {ASTNode} property Property node to check. + * @returns {boolean} Whether the property is a key-value property. + */ + function isKeyValueProperty(property) { + return !( + ( + property.method || + property.shorthand || + property.kind !== "init" || + property.type !== "Property" + ) // Could be "ExperimentalSpreadProperty" or "SpreadElement" + ); + } + + /** + * Starting from the given node (a property.key node here) looks forward + * until it finds the colon punctuator and returns it. + * @param {ASTNode} node The node to start looking from. + * @returns {ASTNode} The colon punctuator. + */ + function getNextColon(node) { + return sourceCode.getTokenAfter(node, astUtils.isColonToken); + } + + /** + * Starting from the given node (a property.key node here) looks forward + * until it finds the last token before a colon punctuator and returns it. + * @param {ASTNode} node The node to start looking from. + * @returns {ASTNode} The last token before a colon punctuator. + */ + function getLastTokenBeforeColon(node) { + const colonToken = getNextColon(node); + + return sourceCode.getTokenBefore(colonToken); + } + + /** + * Starting from the given node (a property.key node here) looks forward + * until it finds the first token after a colon punctuator and returns it. + * @param {ASTNode} node The node to start looking from. + * @returns {ASTNode} The first token after a colon punctuator. + */ + function getFirstTokenAfterColon(node) { + const colonToken = getNextColon(node); + + return sourceCode.getTokenAfter(colonToken); + } + + /** + * Checks whether a property is a member of the property group it follows. + * @param {ASTNode} lastMember The last Property known to be in the group. + * @param {ASTNode} candidate The next Property that might be in the group. + * @returns {boolean} True if the candidate property is part of the group. + */ + function continuesPropertyGroup(lastMember, candidate) { + const groupEndLine = lastMember.loc.start.line, + candidateValueStartLine = ( + isKeyValueProperty(candidate) + ? getFirstTokenAfterColon(candidate.key) + : candidate + ).loc.start.line; + + if (candidateValueStartLine - groupEndLine <= 1) { + return true; + } + + /* + * Check that the first comment is adjacent to the end of the group, the + * last comment is adjacent to the candidate property, and that successive + * comments are adjacent to each other. + */ + const leadingComments = sourceCode.getCommentsBefore(candidate); + + if ( + leadingComments.length && + leadingComments[0].loc.start.line - groupEndLine <= 1 && + candidateValueStartLine - last(leadingComments).loc.end.line <= + 1 + ) { + for (let i = 1; i < leadingComments.length; i++) { + if ( + leadingComments[i].loc.start.line - + leadingComments[i - 1].loc.end.line > + 1 + ) { + return false; + } + } + return true; + } + + return false; + } + + /** + * Gets an object literal property's key as the identifier name or string value. + * @param {ASTNode} property Property node whose key to retrieve. + * @returns {string} The property's key. + */ + function getKey(property) { + const key = property.key; + + if (property.computed) { + return sourceCode.getText().slice(key.range[0], key.range[1]); + } + return astUtils.getStaticPropertyName(property); + } + + /** + * Reports an appropriately-formatted error if spacing is incorrect on one + * side of the colon. + * @param {ASTNode} property Key-value pair in an object literal. + * @param {string} side Side being verified - either "key" or "value". + * @param {string} whitespace Actual whitespace string. + * @param {number} expected Expected whitespace length. + * @param {string} mode Value of the mode as "strict" or "minimum" + * @returns {void} + */ + function report(property, side, whitespace, expected, mode) { + const diff = whitespace.length - expected; + + if ( + ((diff && mode === "strict") || + (diff < 0 && mode === "minimum") || + (diff > 0 && !expected && mode === "minimum")) && + !(expected && containsLineTerminator(whitespace)) + ) { + const nextColon = getNextColon(property.key), + tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { + includeComments: true, + }), + tokenAfterColon = sourceCode.getTokenAfter(nextColon, { + includeComments: true, + }), + isKeySide = side === "key", + isExtra = diff > 0, + diffAbs = Math.abs(diff), + spaces = Array(diffAbs + 1).join(" "); + + const locStart = isKeySide + ? tokenBeforeColon.loc.end + : nextColon.loc.start; + const locEnd = isKeySide + ? nextColon.loc.start + : tokenAfterColon.loc.start; + const missingLoc = isKeySide + ? tokenBeforeColon.loc + : tokenAfterColon.loc; + const loc = isExtra + ? { start: locStart, end: locEnd } + : missingLoc; + + let fix; + + if (isExtra) { + let range; + + // Remove whitespace + if (isKeySide) { + range = [ + tokenBeforeColon.range[1], + tokenBeforeColon.range[1] + diffAbs, + ]; + } else { + range = [ + tokenAfterColon.range[0] - diffAbs, + tokenAfterColon.range[0], + ]; + } + fix = function (fixer) { + return fixer.removeRange(range); + }; + } else { + // Add whitespace + if (isKeySide) { + fix = function (fixer) { + return fixer.insertTextAfter( + tokenBeforeColon, + spaces, + ); + }; + } else { + fix = function (fixer) { + return fixer.insertTextBefore( + tokenAfterColon, + spaces, + ); + }; + } + } + + let messageId; + + if (isExtra) { + messageId = side === "key" ? "extraKey" : "extraValue"; + } else { + messageId = side === "key" ? "missingKey" : "missingValue"; + } + + context.report({ + node: property[side], + loc, + messageId, + data: { + computed: property.computed ? "computed " : "", + key: getKey(property), + }, + fix, + }); + } + } + + /** + * Gets the number of characters in a key, including quotes around string + * keys and braces around computed property keys. + * @param {ASTNode} property Property of on object literal. + * @returns {number} Width of the key. + */ + function getKeyWidth(property) { + const startToken = sourceCode.getFirstToken(property); + const endToken = getLastTokenBeforeColon(property.key); + + return getGraphemeCount( + sourceCode + .getText() + .slice(startToken.range[0], endToken.range[1]), + ); + } + + /** + * Gets the whitespace around the colon in an object literal property. + * @param {ASTNode} property Property node from an object literal. + * @returns {Object} Whitespace before and after the property's colon. + */ + function getPropertyWhitespace(property) { + const whitespace = /(\s*):(\s*)/u.exec( + sourceCode + .getText() + .slice(property.key.range[1], property.value.range[0]), + ); + + if (whitespace) { + return { + beforeColon: whitespace[1], + afterColon: whitespace[2], + }; + } + return null; + } + + /** + * Creates groups of properties. + * @param {ASTNode} node ObjectExpression node being evaluated. + * @returns {Array} Groups of property AST node lists. + */ + function createGroups(node) { + if (node.properties.length === 1) { + return [node.properties]; + } + + return node.properties.reduce( + (groups, property) => { + const currentGroup = last(groups), + prev = last(currentGroup); + + if (!prev || continuesPropertyGroup(prev, property)) { + currentGroup.push(property); + } else { + groups.push([property]); + } + + return groups; + }, + [[]], + ); + } + + /** + * Verifies correct vertical alignment of a group of properties. + * @param {ASTNode[]} properties List of Property AST nodes. + * @returns {void} + */ + function verifyGroupAlignment(properties) { + const length = properties.length, + widths = properties.map(getKeyWidth), // Width of keys, including quotes + align = alignmentOptions.on; // "value" or "colon" + let targetWidth = Math.max(...widths), + beforeColon, + afterColon, + mode; + + if (alignmentOptions && length > 1) { + // When aligning values within a group, use the alignment configuration. + beforeColon = alignmentOptions.beforeColon; + afterColon = alignmentOptions.afterColon; + mode = alignmentOptions.mode; + } else { + beforeColon = multiLineOptions.beforeColon; + afterColon = multiLineOptions.afterColon; + mode = alignmentOptions.mode; + } + + // Conditionally include one space before or after colon + targetWidth += align === "colon" ? beforeColon : afterColon; + + for (let i = 0; i < length; i++) { + const property = properties[i]; + const whitespace = getPropertyWhitespace(property); + + if (whitespace) { + // Object literal getters/setters lack a colon + const width = widths[i]; + + if (align === "value") { + report( + property, + "key", + whitespace.beforeColon, + beforeColon, + mode, + ); + report( + property, + "value", + whitespace.afterColon, + targetWidth - width, + mode, + ); + } else { + // align = "colon" + report( + property, + "key", + whitespace.beforeColon, + targetWidth - width, + mode, + ); + report( + property, + "value", + whitespace.afterColon, + afterColon, + mode, + ); + } + } + } + } + + /** + * Verifies spacing of property conforms to specified options. + * @param {ASTNode} node Property node being evaluated. + * @param {Object} lineOptions Configured singleLine or multiLine options + * @returns {void} + */ + function verifySpacing(node, lineOptions) { + const actual = getPropertyWhitespace(node); + + if (actual) { + // Object literal getters/setters lack colons + report( + node, + "key", + actual.beforeColon, + lineOptions.beforeColon, + lineOptions.mode, + ); + report( + node, + "value", + actual.afterColon, + lineOptions.afterColon, + lineOptions.mode, + ); + } + } + + /** + * Verifies spacing of each property in a list. + * @param {ASTNode[]} properties List of Property AST nodes. + * @param {Object} lineOptions Configured singleLine or multiLine options + * @returns {void} + */ + function verifyListSpacing(properties, lineOptions) { + const length = properties.length; + + for (let i = 0; i < length; i++) { + verifySpacing(properties[i], lineOptions); + } + } + + /** + * Verifies vertical alignment, taking into account groups of properties. + * @param {ASTNode} node ObjectExpression node being evaluated. + * @returns {void} + */ + function verifyAlignment(node) { + createGroups(node).forEach(group => { + const properties = group.filter(isKeyValueProperty); + + if ( + properties.length > 0 && + isSingleLineProperties(properties) + ) { + verifyListSpacing(properties, multiLineOptions); + } else { + verifyGroupAlignment(properties); + } + }); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + if (alignmentOptions) { + // Verify vertical alignment + + return { + ObjectExpression(node) { + if (isSingleLine(node)) { + verifyListSpacing( + node.properties.filter(isKeyValueProperty), + singleLineOptions, + ); + } else { + verifyAlignment(node); + } + }, + }; + } + + // Obey beforeColon and afterColon in each property as configured + return { + Property(node) { + verifySpacing( + node, + isSingleLine(node.parent) + ? singleLineOptions + : multiLineOptions, + ); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/keyword-spacing.js b/node_modules/eslint/lib/rules/keyword-spacing.js new file mode 100644 index 00000000..b6d2560c --- /dev/null +++ b/node_modules/eslint/lib/rules/keyword-spacing.js @@ -0,0 +1,701 @@ +/** + * @fileoverview Rule to enforce spacing before and after keywords. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + keywords = require("./utils/keywords"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const PREV_TOKEN = /^[)\]}>]$/u; +const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/u; +const PREV_TOKEN_M = /^[)\]}>*]$/u; +const NEXT_TOKEN_M = /^[{*]$/u; +const TEMPLATE_OPEN_PAREN = /\$\{$/u; +const TEMPLATE_CLOSE_PAREN = /^\}/u; +const CHECK_TYPE = + /^(?:JSXElement|RegularExpression|String|Template|PrivateIdentifier)$/u; +const KEYS = keywords.concat([ + "as", + "async", + "await", + "from", + "get", + "let", + "of", + "set", + "yield", +]); + +// check duplications. +(function () { + KEYS.sort(); + for (let i = 1; i < KEYS.length; ++i) { + if (KEYS[i] === KEYS[i - 1]) { + throw new Error( + `Duplication was found in the keyword list: ${KEYS[i]}`, + ); + } + } +})(); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given token is a "Template" token ends with "${". + * @param {Token} token A token to check. + * @returns {boolean} `true` if the token is a "Template" token ends with "${". + */ +function isOpenParenOfTemplate(token) { + return token.type === "Template" && TEMPLATE_OPEN_PAREN.test(token.value); +} + +/** + * Checks whether or not a given token is a "Template" token starts with "}". + * @param {Token} token A token to check. + * @returns {boolean} `true` if the token is a "Template" token starts with "}". + */ +function isCloseParenOfTemplate(token) { + return token.type === "Template" && TEMPLATE_CLOSE_PAREN.test(token.value); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "keyword-spacing", + url: "https://eslint.style/rules/js/keyword-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing before and after keywords", + recommended: false, + url: "https://eslint.org/docs/latest/rules/keyword-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { type: "boolean", default: true }, + after: { type: "boolean", default: true }, + overrides: { + type: "object", + properties: KEYS.reduce((retv, key) => { + retv[key] = { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" }, + }, + additionalProperties: false, + }; + return retv; + }, {}), + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + messages: { + expectedBefore: 'Expected space(s) before "{{value}}".', + expectedAfter: 'Expected space(s) after "{{value}}".', + unexpectedBefore: 'Unexpected space(s) before "{{value}}".', + unexpectedAfter: 'Unexpected space(s) after "{{value}}".', + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const tokensToIgnore = new WeakSet(); + + /** + * Reports a given token if there are not space(s) before the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the previous token to check. + * @returns {void} + */ + function expectSpaceBefore(token, pattern) { + const prevToken = sourceCode.getTokenBefore(token); + + if ( + prevToken && + (CHECK_TYPE.test(prevToken.type) || + pattern.test(prevToken.value)) && + !isOpenParenOfTemplate(prevToken) && + !tokensToIgnore.has(prevToken) && + astUtils.isTokenOnSameLine(prevToken, token) && + !sourceCode.isSpaceBetweenTokens(prevToken, token) + ) { + context.report({ + loc: token.loc, + messageId: "expectedBefore", + data: token, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + } + + /** + * Reports a given token if there are space(s) before the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the previous token to check. + * @returns {void} + */ + function unexpectSpaceBefore(token, pattern) { + const prevToken = sourceCode.getTokenBefore(token); + + if ( + prevToken && + (CHECK_TYPE.test(prevToken.type) || + pattern.test(prevToken.value)) && + !isOpenParenOfTemplate(prevToken) && + !tokensToIgnore.has(prevToken) && + astUtils.isTokenOnSameLine(prevToken, token) && + sourceCode.isSpaceBetweenTokens(prevToken, token) + ) { + context.report({ + loc: { start: prevToken.loc.end, end: token.loc.start }, + messageId: "unexpectedBefore", + data: token, + fix(fixer) { + return fixer.removeRange([ + prevToken.range[1], + token.range[0], + ]); + }, + }); + } + } + + /** + * Reports a given token if there are not space(s) after the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the next token to check. + * @returns {void} + */ + function expectSpaceAfter(token, pattern) { + const nextToken = sourceCode.getTokenAfter(token); + + if ( + nextToken && + (CHECK_TYPE.test(nextToken.type) || + pattern.test(nextToken.value)) && + !isCloseParenOfTemplate(nextToken) && + !tokensToIgnore.has(nextToken) && + astUtils.isTokenOnSameLine(token, nextToken) && + !sourceCode.isSpaceBetweenTokens(token, nextToken) + ) { + context.report({ + loc: token.loc, + messageId: "expectedAfter", + data: token, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + } + + /** + * Reports a given token if there are space(s) after the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the next token to check. + * @returns {void} + */ + function unexpectSpaceAfter(token, pattern) { + const nextToken = sourceCode.getTokenAfter(token); + + if ( + nextToken && + (CHECK_TYPE.test(nextToken.type) || + pattern.test(nextToken.value)) && + !isCloseParenOfTemplate(nextToken) && + !tokensToIgnore.has(nextToken) && + astUtils.isTokenOnSameLine(token, nextToken) && + sourceCode.isSpaceBetweenTokens(token, nextToken) + ) { + context.report({ + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "unexpectedAfter", + data: token, + fix(fixer) { + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + } + + /** + * Parses the option object and determines check methods for each keyword. + * @param {Object|undefined} options The option object to parse. + * @returns {Object} - Normalized option object. + * Keys are keywords (there are for every keyword). + * Values are instances of `{"before": function, "after": function}`. + */ + function parseOptions(options = {}) { + const before = options.before !== false; + const after = options.after !== false; + const defaultValue = { + before: before ? expectSpaceBefore : unexpectSpaceBefore, + after: after ? expectSpaceAfter : unexpectSpaceAfter, + }; + const overrides = (options && options.overrides) || {}; + const retv = Object.create(null); + + for (let i = 0; i < KEYS.length; ++i) { + const key = KEYS[i]; + const override = overrides[key]; + + if (override) { + const thisBefore = + "before" in override ? override.before : before; + const thisAfter = + "after" in override ? override.after : after; + + retv[key] = { + before: thisBefore + ? expectSpaceBefore + : unexpectSpaceBefore, + after: thisAfter + ? expectSpaceAfter + : unexpectSpaceAfter, + }; + } else { + retv[key] = defaultValue; + } + } + + return retv; + } + + const checkMethodMap = parseOptions(context.options[0]); + + /** + * Reports a given token if usage of spacing followed by the token is + * invalid. + * @param {Token} token A token to report. + * @param {RegExp} [pattern] Optional. A pattern of the previous + * token to check. + * @returns {void} + */ + function checkSpacingBefore(token, pattern) { + checkMethodMap[token.value].before(token, pattern || PREV_TOKEN); + } + + /** + * Reports a given token if usage of spacing preceded by the token is + * invalid. + * @param {Token} token A token to report. + * @param {RegExp} [pattern] Optional. A pattern of the next + * token to check. + * @returns {void} + */ + function checkSpacingAfter(token, pattern) { + checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN); + } + + /** + * Reports a given token if usage of spacing around the token is invalid. + * @param {Token} token A token to report. + * @returns {void} + */ + function checkSpacingAround(token) { + checkSpacingBefore(token); + checkSpacingAfter(token); + } + + /** + * Reports the first token of a given node if the first token is a keyword + * and usage of spacing around the token is invalid. + * @param {ASTNode|null} node A node to report. + * @returns {void} + */ + function checkSpacingAroundFirstToken(node) { + const firstToken = node && sourceCode.getFirstToken(node); + + if (firstToken && firstToken.type === "Keyword") { + checkSpacingAround(firstToken); + } + } + + /** + * Reports the first token of a given node if the first token is a keyword + * and usage of spacing followed by the token is invalid. + * + * This is used for unary operators (e.g. `typeof`), `function`, and `super`. + * Other rules are handling usage of spacing preceded by those keywords. + * @param {ASTNode|null} node A node to report. + * @returns {void} + */ + function checkSpacingBeforeFirstToken(node) { + const firstToken = node && sourceCode.getFirstToken(node); + + if (firstToken && firstToken.type === "Keyword") { + checkSpacingBefore(firstToken); + } + } + + /** + * Reports the previous token of a given node if the token is a keyword and + * usage of spacing around the token is invalid. + * @param {ASTNode|null} node A node to report. + * @returns {void} + */ + function checkSpacingAroundTokenBefore(node) { + if (node) { + const token = sourceCode.getTokenBefore( + node, + astUtils.isKeywordToken, + ); + + checkSpacingAround(token); + } + } + + /** + * Reports `async` or `function` keywords of a given node if usage of + * spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForFunction(node) { + const firstToken = node && sourceCode.getFirstToken(node); + + if ( + firstToken && + ((firstToken.type === "Keyword" && + firstToken.value === "function") || + firstToken.value === "async") + ) { + checkSpacingBefore(firstToken); + } + } + + /** + * Reports `class` and `extends` keywords of a given node if usage of + * spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForClass(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundTokenBefore(node.superClass); + } + + /** + * Reports `if` and `else` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForIfStatement(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundTokenBefore(node.alternate); + } + + /** + * Reports `try`, `catch`, and `finally` keywords of a given node if usage + * of spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForTryStatement(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundFirstToken(node.handler); + checkSpacingAroundTokenBefore(node.finalizer); + } + + /** + * Reports `do` and `while` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForDoWhileStatement(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundTokenBefore(node.test); + } + + /** + * Reports `for` and `in` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForForInStatement(node) { + checkSpacingAroundFirstToken(node); + + const inToken = sourceCode.getTokenBefore( + node.right, + astUtils.isNotOpeningParenToken, + ); + const previousToken = sourceCode.getTokenBefore(inToken); + + if (previousToken.type !== "PrivateIdentifier") { + checkSpacingBefore(inToken); + } + + checkSpacingAfter(inToken); + } + + /** + * Reports `for` and `of` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForForOfStatement(node) { + if (node.await) { + checkSpacingBefore(sourceCode.getFirstToken(node, 0)); + checkSpacingAfter(sourceCode.getFirstToken(node, 1)); + } else { + checkSpacingAroundFirstToken(node); + } + + const ofToken = sourceCode.getTokenBefore( + node.right, + astUtils.isNotOpeningParenToken, + ); + const previousToken = sourceCode.getTokenBefore(ofToken); + + if (previousToken.type !== "PrivateIdentifier") { + checkSpacingBefore(ofToken); + } + + checkSpacingAfter(ofToken); + } + + /** + * Reports `import`, `export`, `as`, and `from` keywords of a given node if + * usage of spacing around those keywords is invalid. + * + * This rule handles the `*` token in module declarations. + * + * import*as A from "./a"; /*error Expected space(s) after "import". + * error Expected space(s) before "as". + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForModuleDeclaration(node) { + const firstToken = sourceCode.getFirstToken(node); + + checkSpacingBefore(firstToken, PREV_TOKEN_M); + checkSpacingAfter(firstToken, NEXT_TOKEN_M); + + if (node.type === "ExportDefaultDeclaration") { + checkSpacingAround(sourceCode.getTokenAfter(firstToken)); + } + + if (node.type === "ExportAllDeclaration" && node.exported) { + const asToken = sourceCode.getTokenBefore(node.exported); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + checkSpacingAfter(asToken, NEXT_TOKEN_M); + } + + if (node.source) { + const fromToken = sourceCode.getTokenBefore(node.source); + + checkSpacingBefore(fromToken, PREV_TOKEN_M); + checkSpacingAfter(fromToken, NEXT_TOKEN_M); + } + } + + /** + * Reports `as` keyword of a given node if usage of spacing around this + * keyword is invalid. + * @param {ASTNode} node An `ImportSpecifier` node to check. + * @returns {void} + */ + function checkSpacingForImportSpecifier(node) { + if (node.imported.range[0] !== node.local.range[0]) { + const asToken = sourceCode.getTokenBefore(node.local); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + } + } + + /** + * Reports `as` keyword of a given node if usage of spacing around this + * keyword is invalid. + * @param {ASTNode} node An `ExportSpecifier` node to check. + * @returns {void} + */ + function checkSpacingForExportSpecifier(node) { + if (node.local.range[0] !== node.exported.range[0]) { + const asToken = sourceCode.getTokenBefore(node.exported); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + checkSpacingAfter(asToken, NEXT_TOKEN_M); + } + } + + /** + * Reports `as` keyword of a given node if usage of spacing around this + * keyword is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForImportNamespaceSpecifier(node) { + const asToken = sourceCode.getFirstToken(node, 1); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + } + + /** + * Reports `static`, `get`, and `set` keywords of a given node if usage of + * spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @throws {Error} If unable to find token get, set, or async beside method name. + * @returns {void} + */ + function checkSpacingForProperty(node) { + if (node.static) { + checkSpacingAroundFirstToken(node); + } + if ( + node.kind === "get" || + node.kind === "set" || + ((node.method || node.type === "MethodDefinition") && + node.value.async) + ) { + const token = sourceCode.getTokenBefore(node.key, tok => { + switch (tok.value) { + case "get": + case "set": + case "async": + return true; + default: + return false; + } + }); + + if (!token) { + throw new Error( + "Failed to find token get, set, or async beside method name", + ); + } + + checkSpacingAround(token); + } + } + + /** + * Reports `await` keyword of a given node if usage of spacing before + * this keyword is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForAwaitExpression(node) { + checkSpacingBefore(sourceCode.getFirstToken(node)); + } + + return { + // Statements + DebuggerStatement: checkSpacingAroundFirstToken, + WithStatement: checkSpacingAroundFirstToken, + + // Statements - Control flow + BreakStatement: checkSpacingAroundFirstToken, + ContinueStatement: checkSpacingAroundFirstToken, + ReturnStatement: checkSpacingAroundFirstToken, + ThrowStatement: checkSpacingAroundFirstToken, + TryStatement: checkSpacingForTryStatement, + + // Statements - Choice + IfStatement: checkSpacingForIfStatement, + SwitchStatement: checkSpacingAroundFirstToken, + SwitchCase: checkSpacingAroundFirstToken, + + // Statements - Loops + DoWhileStatement: checkSpacingForDoWhileStatement, + ForInStatement: checkSpacingForForInStatement, + ForOfStatement: checkSpacingForForOfStatement, + ForStatement: checkSpacingAroundFirstToken, + WhileStatement: checkSpacingAroundFirstToken, + + // Statements - Declarations + ClassDeclaration: checkSpacingForClass, + ExportNamedDeclaration: checkSpacingForModuleDeclaration, + ExportDefaultDeclaration: checkSpacingForModuleDeclaration, + ExportAllDeclaration: checkSpacingForModuleDeclaration, + FunctionDeclaration: checkSpacingForFunction, + ImportDeclaration: checkSpacingForModuleDeclaration, + VariableDeclaration: checkSpacingAroundFirstToken, + + // Expressions + ArrowFunctionExpression: checkSpacingForFunction, + AwaitExpression: checkSpacingForAwaitExpression, + ClassExpression: checkSpacingForClass, + FunctionExpression: checkSpacingForFunction, + NewExpression: checkSpacingBeforeFirstToken, + Super: checkSpacingBeforeFirstToken, + ThisExpression: checkSpacingBeforeFirstToken, + UnaryExpression: checkSpacingBeforeFirstToken, + YieldExpression: checkSpacingBeforeFirstToken, + + // Others + ImportSpecifier: checkSpacingForImportSpecifier, + ExportSpecifier: checkSpacingForExportSpecifier, + ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier, + MethodDefinition: checkSpacingForProperty, + PropertyDefinition: checkSpacingForProperty, + StaticBlock: checkSpacingAroundFirstToken, + Property: checkSpacingForProperty, + + // To avoid conflicts with `space-infix-ops`, e.g. `a > this.b` + "BinaryExpression[operator='>']"(node) { + const operatorToken = sourceCode.getTokenBefore( + node.right, + astUtils.isNotOpeningParenToken, + ); + + tokensToIgnore.add(operatorToken); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/line-comment-position.js b/node_modules/eslint/lib/rules/line-comment-position.js new file mode 100644 index 00000000..a7ca61cc --- /dev/null +++ b/node_modules/eslint/lib/rules/line-comment-position.js @@ -0,0 +1,157 @@ +/** + * @fileoverview Rule to enforce the position of line comments + * @author Alberto Rodríguez + * @deprecated in ESLint v9.3.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "9.3.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "line-comment-position", + url: "https://eslint.style/rules/js/line-comment-position", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce position of line comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/line-comment-position", + }, + + schema: [ + { + oneOf: [ + { + enum: ["above", "beside"], + }, + { + type: "object", + properties: { + position: { + enum: ["above", "beside"], + }, + ignorePattern: { + type: "string", + }, + applyDefaultPatterns: { + type: "boolean", + }, + applyDefaultIgnorePatterns: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + above: "Expected comment to be above code.", + beside: "Expected comment to be beside code.", + }, + }, + + create(context) { + const options = context.options[0]; + + let above, + ignorePattern, + applyDefaultIgnorePatterns = true; + + if (!options || typeof options === "string") { + above = !options || options === "above"; + } else { + above = !options.position || options.position === "above"; + ignorePattern = options.ignorePattern; + + if (Object.hasOwn(options, "applyDefaultIgnorePatterns")) { + applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns; + } else { + applyDefaultIgnorePatterns = + options.applyDefaultPatterns !== false; + } + } + + const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; + const fallThroughRegExp = /^\s*falls?\s?through/u; + const customIgnoreRegExp = new RegExp(ignorePattern, "u"); + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments + .filter(token => token.type === "Line") + .forEach(node => { + if ( + applyDefaultIgnorePatterns && + (defaultIgnoreRegExp.test(node.value) || + fallThroughRegExp.test(node.value)) + ) { + return; + } + + if ( + ignorePattern && + customIgnoreRegExp.test(node.value) + ) { + return; + } + + const previous = sourceCode.getTokenBefore(node, { + includeComments: true, + }); + const isOnSameLine = + previous && + previous.loc.end.line === node.loc.start.line; + + if (above) { + if (isOnSameLine) { + context.report({ + node, + messageId: "above", + }); + } + } else { + if (!isOnSameLine) { + context.report({ + node, + messageId: "beside", + }); + } + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/linebreak-style.js b/node_modules/eslint/lib/rules/linebreak-style.js new file mode 100644 index 00000000..e7f415b7 --- /dev/null +++ b/node_modules/eslint/lib/rules/linebreak-style.js @@ -0,0 +1,135 @@ +/** + * @fileoverview Rule to enforce a single linebreak style. + * @author Erik Mueller + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceRange } from "@eslint/core"; + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "linebreak-style", + url: "https://eslint.style/rules/js/linebreak-style", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent linebreak style", + recommended: false, + url: "https://eslint.org/docs/latest/rules/linebreak-style", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["unix", "windows"], + }, + ], + messages: { + expectedLF: "Expected linebreaks to be 'LF' but found 'CRLF'.", + expectedCRLF: "Expected linebreaks to be 'CRLF' but found 'LF'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Builds a fix function that replaces text at the specified range in the source text. + * @param {SourceRange} range The range to replace + * @param {string} text The text to insert. + * @returns {Function} Fixer function + * @private + */ + function createFix(range, text) { + return function (fixer) { + return fixer.replaceTextRange(range, text); + }; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkForLinebreakStyle(node) { + const linebreakStyle = context.options[0] || "unix", + expectedLF = linebreakStyle === "unix", + expectedLFChars = expectedLF ? "\n" : "\r\n", + source = sourceCode.getText(), + pattern = astUtils.createGlobalLinebreakMatcher(); + let match; + + let i = 0; + + while ((match = pattern.exec(source)) !== null) { + i++; + if (match[0] === expectedLFChars) { + continue; + } + + const index = match.index; + const range = [index, index + match[0].length]; + + context.report({ + node, + loc: { + start: { + line: i, + column: sourceCode.lines[i - 1].length, + }, + end: { + line: i + 1, + column: 0, + }, + }, + messageId: expectedLF ? "expectedLF" : "expectedCRLF", + fix: createFix(range, expectedLFChars), + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/lines-around-comment.js b/node_modules/eslint/lib/rules/lines-around-comment.js new file mode 100644 index 00000000..8e8a6791 --- /dev/null +++ b/node_modules/eslint/lib/rules/lines-around-comment.js @@ -0,0 +1,581 @@ +/** + * @fileoverview Enforces empty lines around comments. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Return an array with any line numbers that are empty. + * @param {Array} lines An array of each line of the file. + * @returns {Array} An array of line numbers. + */ +function getEmptyLineNums(lines) { + const emptyLines = lines + .map((line, i) => ({ + code: line.trim(), + num: i + 1, + })) + .filter(line => !line.code) + .map(line => line.num); + + return emptyLines; +} + +/** + * Return an array with any line numbers that contain comments. + * @param {Array} comments An array of comment tokens. + * @returns {Array} An array of line numbers. + */ +function getCommentLineNums(comments) { + const lines = []; + + comments.forEach(token => { + const start = token.loc.start.line; + const end = token.loc.end.line; + + lines.push(start, end); + }); + return lines; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "lines-around-comment", + url: "https://eslint.style/rules/js/lines-around-comment", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require empty lines around comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/lines-around-comment", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + beforeBlockComment: { + type: "boolean", + default: true, + }, + afterBlockComment: { + type: "boolean", + default: false, + }, + beforeLineComment: { + type: "boolean", + default: false, + }, + afterLineComment: { + type: "boolean", + default: false, + }, + allowBlockStart: { + type: "boolean", + default: false, + }, + allowBlockEnd: { + type: "boolean", + default: false, + }, + allowClassStart: { + type: "boolean", + }, + allowClassEnd: { + type: "boolean", + }, + allowObjectStart: { + type: "boolean", + }, + allowObjectEnd: { + type: "boolean", + }, + allowArrayStart: { + type: "boolean", + }, + allowArrayEnd: { + type: "boolean", + }, + ignorePattern: { + type: "string", + }, + applyDefaultIgnorePatterns: { + type: "boolean", + }, + afterHashbangComment: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + messages: { + after: "Expected line after comment.", + before: "Expected line before comment.", + }, + }, + + create(context) { + const options = Object.assign({}, context.options[0]); + const ignorePattern = options.ignorePattern; + const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; + const customIgnoreRegExp = new RegExp(ignorePattern, "u"); + const applyDefaultIgnorePatterns = + options.applyDefaultIgnorePatterns !== false; + + options.beforeBlockComment = + typeof options.beforeBlockComment !== "undefined" + ? options.beforeBlockComment + : true; + + const sourceCode = context.sourceCode; + + const lines = sourceCode.lines, + numLines = lines.length + 1, + comments = sourceCode.getAllComments(), + commentLines = getCommentLineNums(comments), + emptyLines = getEmptyLineNums(lines), + commentAndEmptyLines = new Set(commentLines.concat(emptyLines)); + + /** + * Returns whether or not comments are on lines starting with or ending with code + * @param {token} token The comment token to check. + * @returns {boolean} True if the comment is not alone. + */ + function codeAroundComment(token) { + let currentToken = token; + + do { + currentToken = sourceCode.getTokenBefore(currentToken, { + includeComments: true, + }); + } while (currentToken && astUtils.isCommentToken(currentToken)); + + if ( + currentToken && + astUtils.isTokenOnSameLine(currentToken, token) + ) { + return true; + } + + currentToken = token; + do { + currentToken = sourceCode.getTokenAfter(currentToken, { + includeComments: true, + }); + } while (currentToken && astUtils.isCommentToken(currentToken)); + + if ( + currentToken && + astUtils.isTokenOnSameLine(token, currentToken) + ) { + return true; + } + + return false; + } + + /** + * Returns whether or not comments are inside a node type or not. + * @param {ASTNode} parent The Comment parent node. + * @param {string} nodeType The parent type to check against. + * @returns {boolean} True if the comment is inside nodeType. + */ + function isParentNodeType(parent, nodeType) { + return ( + parent.type === nodeType || + (parent.body && parent.body.type === nodeType) || + (parent.consequent && parent.consequent.type === nodeType) + ); + } + + /** + * Returns the parent node that contains the given token. + * @param {token} token The token to check. + * @returns {ASTNode|null} The parent node that contains the given token. + */ + function getParentNodeOfToken(token) { + const node = sourceCode.getNodeByRangeIndex(token.range[0]); + + /* + * For the purpose of this rule, the comment token is in a `StaticBlock` node only + * if it's inside the braces of that `StaticBlock` node. + * + * Example where this function returns `null`: + * + * static + * // comment + * { + * } + * + * Example where this function returns `StaticBlock` node: + * + * static + * { + * // comment + * } + * + */ + if (node && node.type === "StaticBlock") { + const openingBrace = sourceCode.getFirstToken(node, { + skip: 1, + }); // skip the `static` token + + return token.range[0] >= openingBrace.range[0] ? node : null; + } + + return node; + } + + /** + * Returns whether or not comments are at the parent start or not. + * @param {token} token The Comment token. + * @param {string} nodeType The parent type to check against. + * @returns {boolean} True if the comment is at parent start. + */ + function isCommentAtParentStart(token, nodeType) { + const parent = getParentNodeOfToken(token); + + if (parent && isParentNodeType(parent, nodeType)) { + let parentStartNodeOrToken = parent; + + if (parent.type === "StaticBlock") { + parentStartNodeOrToken = sourceCode.getFirstToken(parent, { + skip: 1, + }); // opening brace of the static block + } else if (parent.type === "SwitchStatement") { + parentStartNodeOrToken = sourceCode.getTokenAfter( + parent.discriminant, + { + filter: astUtils.isOpeningBraceToken, + }, + ); // opening brace of the switch statement + } + + return ( + token.loc.start.line - + parentStartNodeOrToken.loc.start.line === + 1 + ); + } + + return false; + } + + /** + * Returns whether or not comments are at the parent end or not. + * @param {token} token The Comment token. + * @param {string} nodeType The parent type to check against. + * @returns {boolean} True if the comment is at parent end. + */ + function isCommentAtParentEnd(token, nodeType) { + const parent = getParentNodeOfToken(token); + + return ( + !!parent && + isParentNodeType(parent, nodeType) && + parent.loc.end.line - token.loc.end.line === 1 + ); + } + + /** + * Returns whether or not comments are at the block start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at block start. + */ + function isCommentAtBlockStart(token) { + return ( + isCommentAtParentStart(token, "ClassBody") || + isCommentAtParentStart(token, "BlockStatement") || + isCommentAtParentStart(token, "StaticBlock") || + isCommentAtParentStart(token, "SwitchCase") || + isCommentAtParentStart(token, "SwitchStatement") + ); + } + + /** + * Returns whether or not comments are at the block end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at block end. + */ + function isCommentAtBlockEnd(token) { + return ( + isCommentAtParentEnd(token, "ClassBody") || + isCommentAtParentEnd(token, "BlockStatement") || + isCommentAtParentEnd(token, "StaticBlock") || + isCommentAtParentEnd(token, "SwitchCase") || + isCommentAtParentEnd(token, "SwitchStatement") + ); + } + + /** + * Returns whether or not comments are at the class start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at class start. + */ + function isCommentAtClassStart(token) { + return isCommentAtParentStart(token, "ClassBody"); + } + + /** + * Returns whether or not comments are at the class end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at class end. + */ + function isCommentAtClassEnd(token) { + return isCommentAtParentEnd(token, "ClassBody"); + } + + /** + * Returns whether or not comments are at the object start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at object start. + */ + function isCommentAtObjectStart(token) { + return ( + isCommentAtParentStart(token, "ObjectExpression") || + isCommentAtParentStart(token, "ObjectPattern") + ); + } + + /** + * Returns whether or not comments are at the object end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at object end. + */ + function isCommentAtObjectEnd(token) { + return ( + isCommentAtParentEnd(token, "ObjectExpression") || + isCommentAtParentEnd(token, "ObjectPattern") + ); + } + + /** + * Returns whether or not comments are at the array start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at array start. + */ + function isCommentAtArrayStart(token) { + return ( + isCommentAtParentStart(token, "ArrayExpression") || + isCommentAtParentStart(token, "ArrayPattern") + ); + } + + /** + * Returns whether or not comments are at the array end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at array end. + */ + function isCommentAtArrayEnd(token) { + return ( + isCommentAtParentEnd(token, "ArrayExpression") || + isCommentAtParentEnd(token, "ArrayPattern") + ); + } + + /** + * Checks if a comment token has lines around it (ignores inline comments) + * @param {token} token The Comment token. + * @param {Object} opts Options to determine the newline. + * @param {boolean} opts.after Should have a newline after this line. + * @param {boolean} opts.before Should have a newline before this line. + * @returns {void} + */ + function checkForEmptyLine(token, opts) { + if ( + applyDefaultIgnorePatterns && + defaultIgnoreRegExp.test(token.value) + ) { + return; + } + + if (ignorePattern && customIgnoreRegExp.test(token.value)) { + return; + } + + let after = opts.after, + before = opts.before; + + const prevLineNum = token.loc.start.line - 1, + nextLineNum = token.loc.end.line + 1, + commentIsNotAlone = codeAroundComment(token); + + const blockStartAllowed = + options.allowBlockStart && + isCommentAtBlockStart(token) && + !( + options.allowClassStart === false && + isCommentAtClassStart(token) + ), + blockEndAllowed = + options.allowBlockEnd && + isCommentAtBlockEnd(token) && + !( + options.allowClassEnd === false && + isCommentAtClassEnd(token) + ), + classStartAllowed = + options.allowClassStart && isCommentAtClassStart(token), + classEndAllowed = + options.allowClassEnd && isCommentAtClassEnd(token), + objectStartAllowed = + options.allowObjectStart && isCommentAtObjectStart(token), + objectEndAllowed = + options.allowObjectEnd && isCommentAtObjectEnd(token), + arrayStartAllowed = + options.allowArrayStart && isCommentAtArrayStart(token), + arrayEndAllowed = + options.allowArrayEnd && isCommentAtArrayEnd(token); + + const exceptionStartAllowed = + blockStartAllowed || + classStartAllowed || + objectStartAllowed || + arrayStartAllowed; + const exceptionEndAllowed = + blockEndAllowed || + classEndAllowed || + objectEndAllowed || + arrayEndAllowed; + + // ignore top of the file and bottom of the file + if (prevLineNum < 1) { + before = false; + } + if (nextLineNum >= numLines) { + after = false; + } + + // we ignore all inline comments + if (commentIsNotAlone) { + return; + } + + const previousTokenOrComment = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + const nextTokenOrComment = sourceCode.getTokenAfter(token, { + includeComments: true, + }); + + // check for newline before + if ( + !exceptionStartAllowed && + before && + !commentAndEmptyLines.has(prevLineNum) && + !( + astUtils.isCommentToken(previousTokenOrComment) && + astUtils.isTokenOnSameLine(previousTokenOrComment, token) + ) + ) { + const lineStart = token.range[0] - token.loc.start.column; + const range = [lineStart, lineStart]; + + context.report({ + node: token, + messageId: "before", + fix(fixer) { + return fixer.insertTextBeforeRange(range, "\n"); + }, + }); + } + + // check for newline after + if ( + !exceptionEndAllowed && + after && + !commentAndEmptyLines.has(nextLineNum) && + !( + astUtils.isCommentToken(nextTokenOrComment) && + astUtils.isTokenOnSameLine(token, nextTokenOrComment) + ) + ) { + context.report({ + node: token, + messageId: "after", + fix(fixer) { + return fixer.insertTextAfter(token, "\n"); + }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + comments.forEach(token => { + if (token.type === "Line") { + if ( + options.beforeLineComment || + options.afterLineComment + ) { + checkForEmptyLine(token, { + after: options.afterLineComment, + before: options.beforeLineComment, + }); + } + } else if (token.type === "Block") { + if ( + options.beforeBlockComment || + options.afterBlockComment + ) { + checkForEmptyLine(token, { + after: options.afterBlockComment, + before: options.beforeBlockComment, + }); + } + } else if (token.type === "Shebang") { + if (options.afterHashbangComment) { + checkForEmptyLine(token, { + after: options.afterHashbangComment, + before: false, + }); + } + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/lines-around-directive.js b/node_modules/eslint/lib/rules/lines-around-directive.js new file mode 100644 index 00000000..2ee0062a --- /dev/null +++ b/node_modules/eslint/lib/rules/lines-around-directive.js @@ -0,0 +1,249 @@ +/** + * @fileoverview Require or disallow newlines around directives. + * @author Kai Cataldo + * @deprecated in ESLint v4.0.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow newlines around directives", + recommended: false, + url: "https://eslint.org/docs/latest/rules/lines-around-directive", + }, + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + before: { + enum: ["always", "never"], + }, + after: { + enum: ["always", "never"], + }, + }, + additionalProperties: false, + minProperties: 2, + }, + ], + }, + ], + + fixable: "whitespace", + messages: { + expected: 'Expected newline {{location}} "{{value}}" directive.', + unexpected: + 'Unexpected newline {{location}} "{{value}}" directive.', + }, + deprecated: { + message: "The rule was replaced with a more general rule.", + url: "https://eslint.org/blog/2017/06/eslint-v4.0.0-released/", + deprecatedSince: "4.0.0", + availableUntil: null, + replacedBy: [ + { + message: "The new rule moved to a plugin.", + url: "https://eslint.org/docs/latest/rules/padding-line-between-statements#examples", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "padding-line-between-statements", + url: "https://eslint.style/rules/js/padding-line-between-statements", + }, + }, + ], + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const config = context.options[0] || "always"; + const expectLineBefore = + typeof config === "string" ? config : config.before; + const expectLineAfter = + typeof config === "string" ? config : config.after; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if node is preceded by a blank newline. + * @param {ASTNode} node Node to check. + * @returns {boolean} Whether or not the passed in node is preceded by a blank newline. + */ + function hasNewlineBefore(node) { + const tokenBefore = sourceCode.getTokenBefore(node, { + includeComments: true, + }); + const tokenLineBefore = tokenBefore ? tokenBefore.loc.end.line : 0; + + return node.loc.start.line - tokenLineBefore >= 2; + } + + /** + * Gets the last token of a node that is on the same line as the rest of the node. + * This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing + * semicolon on a different line. + * @param {ASTNode} node A directive node + * @returns {Token} The last token of the node on the line + */ + function getLastTokenOnLine(node) { + const lastToken = sourceCode.getLastToken(node); + const secondToLastToken = sourceCode.getTokenBefore(lastToken); + + return astUtils.isSemicolonToken(lastToken) && + lastToken.loc.start.line > secondToLastToken.loc.end.line + ? secondToLastToken + : lastToken; + } + + /** + * Check if node is followed by a blank newline. + * @param {ASTNode} node Node to check. + * @returns {boolean} Whether or not the passed in node is followed by a blank newline. + */ + function hasNewlineAfter(node) { + const lastToken = getLastTokenOnLine(node); + const tokenAfter = sourceCode.getTokenAfter(lastToken, { + includeComments: true, + }); + + return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2; + } + + /** + * Report errors for newlines around directives. + * @param {ASTNode} node Node to check. + * @param {string} location Whether the error was found before or after the directive. + * @param {boolean} expected Whether or not a newline was expected or unexpected. + * @returns {void} + */ + function reportError(node, location, expected) { + context.report({ + node, + messageId: expected ? "expected" : "unexpected", + data: { + value: node.expression.value, + location, + }, + fix(fixer) { + const lastToken = getLastTokenOnLine(node); + + if (expected) { + return location === "before" + ? fixer.insertTextBefore(node, "\n") + : fixer.insertTextAfter(lastToken, "\n"); + } + return fixer.removeRange( + location === "before" + ? [node.range[0] - 1, node.range[0]] + : [lastToken.range[1], lastToken.range[1] + 1], + ); + }, + }); + } + + /** + * Check lines around directives in node + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkDirectives(node) { + const directives = astUtils.getDirectivePrologue(node); + + if (!directives.length) { + return; + } + + const firstDirective = directives[0]; + const leadingComments = + sourceCode.getCommentsBefore(firstDirective); + + /* + * Only check before the first directive if it is preceded by a comment or if it is at the top of + * the file and expectLineBefore is set to "never". This is to not force a newline at the top of + * the file if there are no comments as well as for compatibility with padded-blocks. + */ + if (leadingComments.length) { + if ( + expectLineBefore === "always" && + !hasNewlineBefore(firstDirective) + ) { + reportError(firstDirective, "before", true); + } + + if ( + expectLineBefore === "never" && + hasNewlineBefore(firstDirective) + ) { + reportError(firstDirective, "before", false); + } + } else if ( + node.type === "Program" && + expectLineBefore === "never" && + !leadingComments.length && + hasNewlineBefore(firstDirective) + ) { + reportError(firstDirective, "before", false); + } + + const lastDirective = directives.at(-1); + const statements = + node.type === "Program" ? node.body : node.body.body; + + /* + * Do not check after the last directive if the body only + * contains a directive prologue and isn't followed by a comment to ensure + * this rule behaves well with padded-blocks. + */ + if ( + lastDirective === statements.at(-1) && + !lastDirective.trailingComments + ) { + return; + } + + if ( + expectLineAfter === "always" && + !hasNewlineAfter(lastDirective) + ) { + reportError(lastDirective, "after", true); + } + + if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) { + reportError(lastDirective, "after", false); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: checkDirectives, + FunctionDeclaration: checkDirectives, + FunctionExpression: checkDirectives, + ArrowFunctionExpression: checkDirectives, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/lines-between-class-members.js b/node_modules/eslint/lib/rules/lines-between-class-members.js new file mode 100644 index 00000000..80ff4cb8 --- /dev/null +++ b/node_modules/eslint/lib/rules/lines-between-class-members.js @@ -0,0 +1,358 @@ +/** + * @fileoverview Rule to check empty newline between class members + * @author 薛定谔的猫 + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Types of class members. + * Those have `test` method to check it matches to the given class member. + * @private + */ +const ClassMemberTypes = { + "*": { test: () => true }, + field: { test: node => node.type === "PropertyDefinition" }, + method: { test: node => node.type === "MethodDefinition" }, +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "lines-between-class-members", + url: "https://eslint.style/rules/js/lines-between-class-members", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow an empty line between class members", + recommended: false, + url: "https://eslint.org/docs/latest/rules/lines-between-class-members", + }, + + fixable: "whitespace", + + schema: [ + { + anyOf: [ + { + type: "object", + properties: { + enforce: { + type: "array", + items: { + type: "object", + properties: { + blankLine: { + enum: ["always", "never"], + }, + prev: { + enum: ["method", "field", "*"], + }, + next: { + enum: ["method", "field", "*"], + }, + }, + additionalProperties: false, + required: ["blankLine", "prev", "next"], + }, + minItems: 1, + }, + }, + additionalProperties: false, + required: ["enforce"], + }, + { + enum: ["always", "never"], + }, + ], + }, + { + type: "object", + properties: { + exceptAfterSingleLine: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + messages: { + never: "Unexpected blank line between class members.", + always: "Expected blank line between class members.", + }, + }, + + create(context) { + const options = []; + + options[0] = context.options[0] || "always"; + options[1] = context.options[1] || { exceptAfterSingleLine: false }; + + const configureList = + typeof options[0] === "object" + ? options[0].enforce + : [{ blankLine: options[0], prev: "*", next: "*" }]; + const sourceCode = context.sourceCode; + + /** + * Gets a pair of tokens that should be used to check lines between two class member nodes. + * + * In most cases, this returns the very last token of the current node and + * the very first token of the next node. + * For example: + * + * class C { + * x = 1; // curLast: `;` nextFirst: `in` + * in = 2 + * } + * + * There is only one exception. If the given node ends with a semicolon, and it looks like + * a semicolon-less style's semicolon - one that is not on the same line as the preceding + * token, but is on the line where the next class member starts - this returns the preceding + * token and the semicolon as boundary tokens. + * For example: + * + * class C { + * x = 1 // curLast: `1` nextFirst: `;` + * ;in = 2 + * } + * When determining the desired layout of the code, we should treat this semicolon as + * a part of the next class member node instead of the one it technically belongs to. + * @param {ASTNode} curNode Current class member node. + * @param {ASTNode} nextNode Next class member node. + * @returns {Token} The actual last token of `node`. + * @private + */ + function getBoundaryTokens(curNode, nextNode) { + const lastToken = sourceCode.getLastToken(curNode); + const prevToken = sourceCode.getTokenBefore(lastToken); + const nextToken = sourceCode.getFirstToken(nextNode); // skip possible lone `;` between nodes + + const isSemicolonLessStyle = + astUtils.isSemicolonToken(lastToken) && + !astUtils.isTokenOnSameLine(prevToken, lastToken) && + astUtils.isTokenOnSameLine(lastToken, nextToken); + + return isSemicolonLessStyle + ? { curLast: prevToken, nextFirst: lastToken } + : { curLast: lastToken, nextFirst: nextToken }; + } + + /** + * Return the last token among the consecutive tokens that have no exceed max line difference in between, before the first token in the next member. + * @param {Token} prevLastToken The last token in the previous member node. + * @param {Token} nextFirstToken The first token in the next member node. + * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens. + * @returns {Token} The last token among the consecutive tokens. + */ + function findLastConsecutiveTokenAfter( + prevLastToken, + nextFirstToken, + maxLine, + ) { + const after = sourceCode.getTokenAfter(prevLastToken, { + includeComments: true, + }); + + if ( + after !== nextFirstToken && + after.loc.start.line - prevLastToken.loc.end.line <= maxLine + ) { + return findLastConsecutiveTokenAfter( + after, + nextFirstToken, + maxLine, + ); + } + return prevLastToken; + } + + /** + * Return the first token among the consecutive tokens that have no exceed max line difference in between, after the last token in the previous member. + * @param {Token} nextFirstToken The first token in the next member node. + * @param {Token} prevLastToken The last token in the previous member node. + * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens. + * @returns {Token} The first token among the consecutive tokens. + */ + function findFirstConsecutiveTokenBefore( + nextFirstToken, + prevLastToken, + maxLine, + ) { + const before = sourceCode.getTokenBefore(nextFirstToken, { + includeComments: true, + }); + + if ( + before !== prevLastToken && + nextFirstToken.loc.start.line - before.loc.end.line <= maxLine + ) { + return findFirstConsecutiveTokenBefore( + before, + prevLastToken, + maxLine, + ); + } + return nextFirstToken; + } + + /** + * Checks if there is a token or comment between two tokens. + * @param {Token} before The token before. + * @param {Token} after The token after. + * @returns {boolean} True if there is a token or comment between two tokens. + */ + function hasTokenOrCommentBetween(before, after) { + return ( + sourceCode.getTokensBetween(before, after, { + includeComments: true, + }).length !== 0 + ); + } + + /** + * Checks whether the given node matches the given type. + * @param {ASTNode} node The class member node to check. + * @param {string} type The class member type to check. + * @returns {boolean} `true` if the class member node matched the type. + * @private + */ + function match(node, type) { + return ClassMemberTypes[type].test(node); + } + + /** + * Finds the last matched configuration from the configureList. + * @param {ASTNode} prevNode The previous node to match. + * @param {ASTNode} nextNode The current node to match. + * @returns {string|null} Padding type or `null` if no matches were found. + * @private + */ + function getPaddingType(prevNode, nextNode) { + for (let i = configureList.length - 1; i >= 0; --i) { + const configure = configureList[i]; + const matched = + match(prevNode, configure.prev) && + match(nextNode, configure.next); + + if (matched) { + return configure.blankLine; + } + } + return null; + } + + return { + ClassBody(node) { + const body = node.body; + + for (let i = 0; i < body.length - 1; i++) { + const curFirst = sourceCode.getFirstToken(body[i]); + const { curLast, nextFirst } = getBoundaryTokens( + body[i], + body[i + 1], + ); + const isMulti = !astUtils.isTokenOnSameLine( + curFirst, + curLast, + ); + const skip = !isMulti && options[1].exceptAfterSingleLine; + const beforePadding = findLastConsecutiveTokenAfter( + curLast, + nextFirst, + 1, + ); + const afterPadding = findFirstConsecutiveTokenBefore( + nextFirst, + curLast, + 1, + ); + const isPadded = + afterPadding.loc.start.line - + beforePadding.loc.end.line > + 1; + const hasTokenInPadding = hasTokenOrCommentBetween( + beforePadding, + afterPadding, + ); + const curLineLastToken = findLastConsecutiveTokenAfter( + curLast, + nextFirst, + 0, + ); + const paddingType = getPaddingType(body[i], body[i + 1]); + + if (paddingType === "never" && isPadded) { + context.report({ + node: body[i + 1], + messageId: "never", + + fix(fixer) { + if (hasTokenInPadding) { + return null; + } + return fixer.replaceTextRange( + [ + beforePadding.range[1], + afterPadding.range[0], + ], + "\n", + ); + }, + }); + } else if (paddingType === "always" && !skip && !isPadded) { + context.report({ + node: body[i + 1], + messageId: "always", + + fix(fixer) { + if (hasTokenInPadding) { + return null; + } + return fixer.insertTextAfter( + curLineLastToken, + "\n", + ); + }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/logical-assignment-operators.js b/node_modules/eslint/lib/rules/logical-assignment-operators.js new file mode 100644 index 00000000..38103f16 --- /dev/null +++ b/node_modules/eslint/lib/rules/logical-assignment-operators.js @@ -0,0 +1,688 @@ +/** + * @fileoverview Rule to replace assignment expressions with logical operator assignment + * @author Daniel Martens + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ +const astUtils = require("./utils/ast-utils.js"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const baseTypes = new Set(["Identifier", "Super", "ThisExpression"]); + +/** + * Returns true iff either "undefined" or a void expression (eg. "void 0") + * @param {ASTNode} expression Expression to check + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} True iff "undefined" or "void ..." + */ +function isUndefined(expression, scope) { + if (expression.type === "Identifier" && expression.name === "undefined") { + return astUtils.isReferenceToGlobalVariable(scope, expression); + } + + return ( + expression.type === "UnaryExpression" && + expression.operator === "void" && + expression.argument.type === "Literal" && + expression.argument.value === 0 + ); +} + +/** + * Returns true iff the reference is either an identifier or member expression + * @param {ASTNode} expression Expression to check + * @returns {boolean} True for identifiers and member expressions + */ +function isReference(expression) { + return ( + (expression.type === "Identifier" && expression.name !== "undefined") || + expression.type === "MemberExpression" + ); +} + +/** + * Returns true iff the expression checks for nullish with loose equals. + * Examples: value == null, value == void 0 + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} True iff implicit nullish comparison + */ +function isImplicitNullishComparison(expression, scope) { + if ( + expression.type !== "BinaryExpression" || + expression.operator !== "==" + ) { + return false; + } + + const reference = isReference(expression.left) ? "left" : "right"; + const nullish = reference === "left" ? "right" : "left"; + + return ( + isReference(expression[reference]) && + (astUtils.isNullLiteral(expression[nullish]) || + isUndefined(expression[nullish], scope)) + ); +} + +/** + * Condition with two equal comparisons. + * @param {ASTNode} expression Condition + * @returns {boolean} True iff matches ? === ? || ? === ? + */ +function isDoubleComparison(expression) { + return ( + expression.type === "LogicalExpression" && + expression.operator === "||" && + expression.left.type === "BinaryExpression" && + expression.left.operator === "===" && + expression.right.type === "BinaryExpression" && + expression.right.operator === "===" + ); +} + +/** + * Returns true iff the expression checks for undefined and null. + * Example: value === null || value === undefined + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} True iff explicit nullish comparison + */ +function isExplicitNullishComparison(expression, scope) { + if (!isDoubleComparison(expression)) { + return false; + } + const leftReference = isReference(expression.left.left) ? "left" : "right"; + const leftNullish = leftReference === "left" ? "right" : "left"; + const rightReference = isReference(expression.right.left) + ? "left" + : "right"; + const rightNullish = rightReference === "left" ? "right" : "left"; + + return ( + astUtils.isSameReference( + expression.left[leftReference], + expression.right[rightReference], + ) && + ((astUtils.isNullLiteral(expression.left[leftNullish]) && + isUndefined(expression.right[rightNullish], scope)) || + (isUndefined(expression.left[leftNullish], scope) && + astUtils.isNullLiteral(expression.right[rightNullish]))) + ); +} + +/** + * Returns true for Boolean(arg) calls + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {boolean} Whether the expression is a boolean cast + */ +function isBooleanCast(expression, scope) { + return ( + expression.type === "CallExpression" && + expression.callee.name === "Boolean" && + expression.arguments.length === 1 && + astUtils.isReferenceToGlobalVariable(scope, expression.callee) + ); +} + +/** + * Returns true for: + * truthiness checks: value, Boolean(value), !!value + * falsiness checks: !value, !Boolean(value) + * nullish checks: value == null, value === undefined || value === null + * @param {ASTNode} expression Test condition + * @param {import('eslint-scope').Scope} scope Scope of the expression + * @returns {?{ reference: ASTNode, operator: '??'|'||'|'&&'}} Null if not a known existence + */ +function getExistence(expression, scope) { + const isNegated = + expression.type === "UnaryExpression" && expression.operator === "!"; + const base = isNegated ? expression.argument : expression; + + switch (true) { + case isReference(base): + return { reference: base, operator: isNegated ? "||" : "&&" }; + case base.type === "UnaryExpression" && + base.operator === "!" && + isReference(base.argument): + return { reference: base.argument, operator: "&&" }; + case isBooleanCast(base, scope) && isReference(base.arguments[0]): + return { + reference: base.arguments[0], + operator: isNegated ? "||" : "&&", + }; + case isImplicitNullishComparison(expression, scope): + return { + reference: isReference(expression.left) + ? expression.left + : expression.right, + operator: "??", + }; + case isExplicitNullishComparison(expression, scope): + return { + reference: isReference(expression.left.left) + ? expression.left.left + : expression.left.right, + operator: "??", + }; + default: + return null; + } +} + +/** + * Returns true iff the node is inside a with block + * @param {ASTNode} node Node to check + * @returns {boolean} True iff passed node is inside a with block + */ +function isInsideWithBlock(node) { + if (node.type === "Program") { + return false; + } + + return node.parent.type === "WithStatement" && node.parent.body === node + ? true + : isInsideWithBlock(node.parent); +} + +/** + * Gets the leftmost operand of a consecutive logical expression. + * @param {SourceCode} sourceCode The ESLint source code object + * @param {LogicalExpression} node LogicalExpression + * @returns {Expression} Leftmost operand + */ +function getLeftmostOperand(sourceCode, node) { + let left = node.left; + + while ( + left.type === "LogicalExpression" && + left.operator === node.operator + ) { + if (astUtils.isParenthesised(sourceCode, left)) { + /* + * It should have associativity, + * but ignore it if use parentheses to make the evaluation order clear. + */ + return left; + } + left = left.left; + } + return left; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require or disallow logical assignment operator shorthand", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/logical-assignment-operators", + }, + + schema: { + type: "array", + oneOf: [ + { + items: [ + { const: "always" }, + { + type: "object", + properties: { + enforceForIfStatements: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, // 0 for allowing passing no options + maxItems: 2, + }, + { + items: [{ const: "never" }], + minItems: 1, + maxItems: 1, + }, + ], + }, + fixable: "code", + hasSuggestions: true, + messages: { + assignment: + "Assignment (=) can be replaced with operator assignment ({{operator}}).", + useLogicalOperator: + "Convert this assignment to use the operator {{ operator }}.", + logical: + "Logical expression can be replaced with an assignment ({{ operator }}).", + convertLogical: + "Replace this logical expression with an assignment with the operator {{ operator }}.", + if: "'if' statement can be replaced with a logical operator assignment with operator {{ operator }}.", + convertIf: + "Replace this 'if' statement with a logical assignment with operator {{ operator }}.", + unexpected: + "Unexpected logical operator assignment ({{operator}}) shorthand.", + separate: + "Separate the logical assignment into an assignment with a logical operator.", + }, + }, + + create(context) { + const mode = context.options[0] === "never" ? "never" : "always"; + const checkIf = + mode === "always" && + context.options.length > 1 && + context.options[1].enforceForIfStatements; + const sourceCode = context.sourceCode; + const isStrict = sourceCode.getScope(sourceCode.ast).isStrict; + + /** + * Returns false if the access could be a getter + * @param {ASTNode} node Assignment expression + * @returns {boolean} True iff the fix is safe + */ + function cannotBeGetter(node) { + return ( + node.type === "Identifier" && + (isStrict || !isInsideWithBlock(node)) + ); + } + + /** + * Check whether only a single property is accessed + * @param {ASTNode} node reference + * @returns {boolean} True iff a single property is accessed + */ + function accessesSingleProperty(node) { + if (!isStrict && isInsideWithBlock(node)) { + return node.type === "Identifier"; + } + + return ( + node.type === "MemberExpression" && + baseTypes.has(node.object.type) && + (!node.computed || + (node.property.type !== "MemberExpression" && + node.property.type !== "ChainExpression")) + ); + } + + /** + * Adds a fixer or suggestion whether on the fix is safe. + * @param {{ messageId: string, node: ASTNode }} descriptor Report descriptor without fix or suggest + * @param {{ messageId: string, fix: Function }} suggestion Adds the fix or the whole suggestion as only element in "suggest" to suggestion + * @param {boolean} shouldBeFixed Fix iff the condition is true + * @returns {Object} Descriptor with either an added fix or suggestion + */ + function createConditionalFixer(descriptor, suggestion, shouldBeFixed) { + if (shouldBeFixed) { + return { + ...descriptor, + fix: suggestion.fix, + }; + } + + return { + ...descriptor, + suggest: [suggestion], + }; + } + + /** + * Returns the operator token for assignments and binary expressions + * @param {ASTNode} node AssignmentExpression or BinaryExpression + * @returns {import('eslint').AST.Token} Operator token between the left and right expression + */ + function getOperatorToken(node) { + return sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + } + + if (mode === "never") { + return { + // foo ||= bar + AssignmentExpression(assignment) { + if ( + !astUtils.isLogicalAssignmentOperator( + assignment.operator, + ) + ) { + return; + } + + const descriptor = { + messageId: "unexpected", + node: assignment, + data: { operator: assignment.operator }, + }; + const suggestion = { + messageId: "separate", + *fix(ruleFixer) { + if ( + sourceCode.getCommentsInside(assignment) + .length > 0 + ) { + return; + } + + const operatorToken = getOperatorToken(assignment); + + // -> foo = bar + yield ruleFixer.replaceText(operatorToken, "="); + + const assignmentText = sourceCode.getText( + assignment.left, + ); + const operator = assignment.operator.slice(0, -1); + + // -> foo = foo || bar + yield ruleFixer.insertTextAfter( + operatorToken, + ` ${assignmentText} ${operator}`, + ); + + const precedence = + astUtils.getPrecedence(assignment.right) <= + astUtils.getPrecedence({ + type: "LogicalExpression", + operator, + }); + + // ?? and || / && cannot be mixed but have same precedence + const mixed = + assignment.operator === "??=" && + astUtils.isLogicalExpression(assignment.right); + + if ( + !astUtils.isParenthesised( + sourceCode, + assignment.right, + ) && + (precedence || mixed) + ) { + // -> foo = foo || (bar) + yield ruleFixer.insertTextBefore( + assignment.right, + "(", + ); + yield ruleFixer.insertTextAfter( + assignment.right, + ")", + ); + } + }, + }; + + context.report( + createConditionalFixer( + descriptor, + suggestion, + cannotBeGetter(assignment.left), + ), + ); + }, + }; + } + + return { + // foo = foo || bar + "AssignmentExpression[operator='='][right.type='LogicalExpression']"( + assignment, + ) { + const leftOperand = getLeftmostOperand( + sourceCode, + assignment.right, + ); + + if (!astUtils.isSameReference(assignment.left, leftOperand)) { + return; + } + + const descriptor = { + messageId: "assignment", + node: assignment, + data: { operator: `${assignment.right.operator}=` }, + }; + const suggestion = { + messageId: "useLogicalOperator", + data: { operator: `${assignment.right.operator}=` }, + *fix(ruleFixer) { + if ( + sourceCode.getCommentsInside(assignment).length > 0 + ) { + return; + } + + // No need for parenthesis around the assignment based on precedence as the precedence stays the same even with changed operator + const assignmentOperatorToken = + getOperatorToken(assignment); + + // -> foo ||= foo || bar + yield ruleFixer.insertTextBefore( + assignmentOperatorToken, + assignment.right.operator, + ); + + // -> foo ||= bar + const logicalOperatorToken = getOperatorToken( + leftOperand.parent, + ); + const firstRightOperandToken = + sourceCode.getTokenAfter(logicalOperatorToken); + + yield ruleFixer.removeRange([ + leftOperand.parent.range[0], + firstRightOperandToken.range[0], + ]); + }, + }; + + context.report( + createConditionalFixer( + descriptor, + suggestion, + cannotBeGetter(assignment.left), + ), + ); + }, + + // foo || (foo = bar) + 'LogicalExpression[right.type="AssignmentExpression"][right.operator="="]'( + logical, + ) { + // Right side has to be parenthesized, otherwise would be parsed as (foo || foo) = bar which is illegal + if ( + isReference(logical.left) && + astUtils.isSameReference(logical.left, logical.right.left) + ) { + const descriptor = { + messageId: "logical", + node: logical, + data: { operator: `${logical.operator}=` }, + }; + const suggestion = { + messageId: "convertLogical", + data: { operator: `${logical.operator}=` }, + *fix(ruleFixer) { + if ( + sourceCode.getCommentsInside(logical).length > 0 + ) { + return; + } + + const parentPrecedence = astUtils.getPrecedence( + logical.parent, + ); + const requiresOuterParenthesis = + logical.parent.type !== "ExpressionStatement" && + (parentPrecedence === -1 || + astUtils.getPrecedence({ + type: "AssignmentExpression", + }) < parentPrecedence); + + if ( + !astUtils.isParenthesised( + sourceCode, + logical, + ) && + requiresOuterParenthesis + ) { + yield ruleFixer.insertTextBefore(logical, "("); + yield ruleFixer.insertTextAfter(logical, ")"); + } + + // Also removes all opening parenthesis + yield ruleFixer.removeRange([ + logical.range[0], + logical.right.range[0], + ]); // -> foo = bar) + + // Also removes all ending parenthesis + yield ruleFixer.removeRange([ + logical.right.range[1], + logical.range[1], + ]); // -> foo = bar + + const operatorToken = getOperatorToken( + logical.right, + ); + + yield ruleFixer.insertTextBefore( + operatorToken, + logical.operator, + ); // -> foo ||= bar + }, + }; + const fix = + cannotBeGetter(logical.left) || + accessesSingleProperty(logical.left); + + context.report( + createConditionalFixer(descriptor, suggestion, fix), + ); + } + }, + + // if (foo) foo = bar + "IfStatement[alternate=null]"(ifNode) { + if (!checkIf) { + return; + } + + const hasBody = ifNode.consequent.type === "BlockStatement"; + + if (hasBody && ifNode.consequent.body.length !== 1) { + return; + } + + const body = hasBody + ? ifNode.consequent.body[0] + : ifNode.consequent; + const scope = sourceCode.getScope(ifNode); + const existence = getExistence(ifNode.test, scope); + + if ( + body.type === "ExpressionStatement" && + body.expression.type === "AssignmentExpression" && + body.expression.operator === "=" && + existence !== null && + astUtils.isSameReference( + existence.reference, + body.expression.left, + ) + ) { + const descriptor = { + messageId: "if", + node: ifNode, + data: { operator: `${existence.operator}=` }, + }; + const suggestion = { + messageId: "convertIf", + data: { operator: `${existence.operator}=` }, + *fix(ruleFixer) { + if ( + sourceCode.getCommentsInside(ifNode).length > 0 + ) { + return; + } + + const firstBodyToken = + sourceCode.getFirstToken(body); + const prevToken = sourceCode.getTokenBefore(ifNode); + + if ( + prevToken !== null && + prevToken.value !== ";" && + prevToken.value !== "{" && + firstBodyToken.type !== "Identifier" && + firstBodyToken.type !== "Keyword" + ) { + // Do not fix if the fixed statement could be part of the previous statement (eg. fn() if (a == null) (a) = b --> fn()(a) ??= b) + return; + } + + const operatorToken = getOperatorToken( + body.expression, + ); + + yield ruleFixer.insertTextBefore( + operatorToken, + existence.operator, + ); // -> if (foo) foo ||= bar + + yield ruleFixer.removeRange([ + ifNode.range[0], + body.range[0], + ]); // -> foo ||= bar + + yield ruleFixer.removeRange([ + body.range[1], + ifNode.range[1], + ]); // -> foo ||= bar, only present if "if" had a body + + const nextToken = sourceCode.getTokenAfter( + body.expression, + ); + + if ( + hasBody && + nextToken !== null && + nextToken.value !== ";" + ) { + yield ruleFixer.insertTextAfter(ifNode, ";"); + } + }, + }; + const shouldBeFixed = + cannotBeGetter(existence.reference) || + (ifNode.test.type !== "LogicalExpression" && + accessesSingleProperty(existence.reference)); + + context.report( + createConditionalFixer( + descriptor, + suggestion, + shouldBeFixed, + ), + ); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/max-classes-per-file.js b/node_modules/eslint/lib/rules/max-classes-per-file.js new file mode 100644 index 00000000..3ede9edf --- /dev/null +++ b/node_modules/eslint/lib/rules/max-classes-per-file.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Enforce a maximum number of classes per file + * @author James Garbutt + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum number of classes per file", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-classes-per-file", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 1, + }, + { + type: "object", + properties: { + ignoreExpressions: { + type: "boolean", + }, + max: { + type: "integer", + minimum: 1, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + maximumExceeded: + "File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}.", + }, + }, + create(context) { + const [option = {}] = context.options; + const [ignoreExpressions, max] = + typeof option === "number" + ? [false, option || 1] + : [option.ignoreExpressions, option.max || 1]; + + let classCount = 0; + + return { + Program() { + classCount = 0; + }, + "Program:exit"(node) { + if (classCount > max) { + context.report({ + node, + messageId: "maximumExceeded", + data: { + classCount, + max, + }, + }); + } + }, + ClassDeclaration() { + classCount++; + }, + ClassExpression() { + if (!ignoreExpressions) { + classCount++; + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/max-depth.js b/node_modules/eslint/lib/rules/max-depth.js new file mode 100644 index 00000000..f3c66b7a --- /dev/null +++ b/node_modules/eslint/lib/rules/max-depth.js @@ -0,0 +1,159 @@ +/** + * @fileoverview A rule to set the maximum depth block can be nested in a function. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum depth that blocks can be nested", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-depth", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + tooDeeply: + "Blocks are nested too deeply ({{depth}}). Maximum allowed is {{maxDepth}}.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const functionStack = [], + option = context.options[0]; + let maxDepth = 4; + + if ( + typeof option === "object" && + (Object.hasOwn(option, "maximum") || Object.hasOwn(option, "max")) + ) { + maxDepth = option.maximum || option.max; + } + if (typeof option === "number") { + maxDepth = option; + } + + /** + * When parsing a new function, store it in our function stack + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push(0); + } + + /** + * When parsing is done then pop out the reference + * @returns {void} + * @private + */ + function endFunction() { + functionStack.pop(); + } + + /** + * Save the block and Evaluate the node + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function pushBlock(node) { + const len = ++functionStack[functionStack.length - 1]; + + if (len > maxDepth) { + context.report({ + node, + messageId: "tooDeeply", + data: { depth: len, maxDepth }, + }); + } + } + + /** + * Pop the saved block + * @returns {void} + * @private + */ + function popBlock() { + functionStack[functionStack.length - 1]--; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Program: startFunction, + FunctionDeclaration: startFunction, + FunctionExpression: startFunction, + ArrowFunctionExpression: startFunction, + StaticBlock: startFunction, + + IfStatement(node) { + if (node.parent.type !== "IfStatement") { + pushBlock(node); + } + }, + SwitchStatement: pushBlock, + TryStatement: pushBlock, + DoWhileStatement: pushBlock, + WhileStatement: pushBlock, + WithStatement: pushBlock, + ForStatement: pushBlock, + ForInStatement: pushBlock, + ForOfStatement: pushBlock, + + "IfStatement:exit": popBlock, + "SwitchStatement:exit": popBlock, + "TryStatement:exit": popBlock, + "DoWhileStatement:exit": popBlock, + "WhileStatement:exit": popBlock, + "WithStatement:exit": popBlock, + "ForStatement:exit": popBlock, + "ForInStatement:exit": popBlock, + "ForOfStatement:exit": popBlock, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "StaticBlock:exit": endFunction, + "Program:exit": endFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/max-len.js b/node_modules/eslint/lib/rules/max-len.js new file mode 100644 index 00000000..12cc248e --- /dev/null +++ b/node_modules/eslint/lib/rules/max-len.js @@ -0,0 +1,497 @@ +/** + * @fileoverview Rule to check for max length on a line. + * @author Matt DuVall + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const OPTIONS_SCHEMA = { + type: "object", + properties: { + code: { + type: "integer", + minimum: 0, + }, + comments: { + type: "integer", + minimum: 0, + }, + tabWidth: { + type: "integer", + minimum: 0, + }, + ignorePattern: { + type: "string", + }, + ignoreComments: { + type: "boolean", + }, + ignoreStrings: { + type: "boolean", + }, + ignoreUrls: { + type: "boolean", + }, + ignoreTemplateLiterals: { + type: "boolean", + }, + ignoreRegExpLiterals: { + type: "boolean", + }, + ignoreTrailingComments: { + type: "boolean", + }, + }, + additionalProperties: false, +}; + +const OPTIONS_OR_INTEGER_SCHEMA = { + anyOf: [ + OPTIONS_SCHEMA, + { + type: "integer", + minimum: 0, + }, + ], +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "max-len", + url: "https://eslint.style/rules/js/max-len", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce a maximum line length", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-len", + }, + + schema: [ + OPTIONS_OR_INTEGER_SCHEMA, + OPTIONS_OR_INTEGER_SCHEMA, + OPTIONS_SCHEMA, + ], + messages: { + max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.", + maxComment: + "This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}.", + }, + }, + + create(context) { + /* + * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however: + * - They're matching an entire string that we know is a URI + * - We're matching part of a string where we think there *might* be a URL + * - We're only concerned about URLs, as picking out any URI would cause + * too many false positives + * - We don't care about matching the entire URL, any small segment is fine + */ + const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u; + + const sourceCode = context.sourceCode; + + /** + * Computes the length of a line that may contain tabs. The width of each + * tab will be the number of spaces to the next tab stop. + * @param {string} line The line. + * @param {number} tabWidth The width of each tab stop in spaces. + * @returns {number} The computed line length. + * @private + */ + function computeLineLength(line, tabWidth) { + let extraCharacterCount = 0; + + line.replace(/\t/gu, (match, offset) => { + const totalOffset = offset + extraCharacterCount, + previousTabStopOffset = tabWidth + ? totalOffset % tabWidth + : 0, + spaceCount = tabWidth - previousTabStopOffset; + + extraCharacterCount += spaceCount - 1; // -1 for the replaced tab + }); + return Array.from(line).length + extraCharacterCount; + } + + // The options object must be the last option specified… + const options = Object.assign({}, context.options.at(-1)); + + // …but max code length… + if (typeof context.options[0] === "number") { + options.code = context.options[0]; + } + + // …and tabWidth can be optionally specified directly as integers. + if (typeof context.options[1] === "number") { + options.tabWidth = context.options[1]; + } + + const maxLength = typeof options.code === "number" ? options.code : 80, + tabWidth = + typeof options.tabWidth === "number" ? options.tabWidth : 4, + ignoreComments = !!options.ignoreComments, + ignoreStrings = !!options.ignoreStrings, + ignoreTemplateLiterals = !!options.ignoreTemplateLiterals, + ignoreRegExpLiterals = !!options.ignoreRegExpLiterals, + ignoreTrailingComments = + !!options.ignoreTrailingComments || !!options.ignoreComments, + ignoreUrls = !!options.ignoreUrls, + maxCommentLength = options.comments; + let ignorePattern = options.ignorePattern || null; + + if (ignorePattern) { + ignorePattern = new RegExp(ignorePattern, "u"); + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tells if a given comment is trailing: it starts on the current line and + * extends to or past the end of the current line. + * @param {string} line The source line we want to check for a trailing comment on + * @param {number} lineNumber The one-indexed line number for line + * @param {ASTNode} comment The comment to inspect + * @returns {boolean} If the comment is trailing on the given line + */ + function isTrailingComment(line, lineNumber, comment) { + return ( + comment && + comment.loc.start.line === lineNumber && + lineNumber <= comment.loc.end.line && + (comment.loc.end.line > lineNumber || + comment.loc.end.column === line.length) + ); + } + + /** + * Tells if a comment encompasses the entire line. + * @param {string} line The source line with a trailing comment + * @param {number} lineNumber The one-indexed line number this is on + * @param {ASTNode} comment The comment to remove + * @returns {boolean} If the comment covers the entire line + */ + function isFullLineComment(line, lineNumber, comment) { + const start = comment.loc.start, + end = comment.loc.end, + isFirstTokenOnLine = !line + .slice(0, comment.loc.start.column) + .trim(); + + return ( + comment && + (start.line < lineNumber || + (start.line === lineNumber && isFirstTokenOnLine)) && + (end.line > lineNumber || + (end.line === lineNumber && end.column === line.length)) + ); + } + + /** + * Check if a node is a JSXEmptyExpression contained in a single line JSXExpressionContainer. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is a JSXEmptyExpression contained in a single line JSXExpressionContainer. + */ + function isJSXEmptyExpressionInSingleLineContainer(node) { + if ( + !node || + !node.parent || + node.type !== "JSXEmptyExpression" || + node.parent.type !== "JSXExpressionContainer" + ) { + return false; + } + + const parent = node.parent; + + return parent.loc.start.line === parent.loc.end.line; + } + + /** + * Gets the line after the comment and any remaining trailing whitespace is + * stripped. + * @param {string} line The source line with a trailing comment + * @param {ASTNode} comment The comment to remove + * @returns {string} Line without comment and trailing whitespace + */ + function stripTrailingComment(line, comment) { + // loc.column is zero-indexed + return line.slice(0, comment.loc.start.column).replace(/\s+$/u, ""); + } + + /** + * Ensure that an array exists at [key] on `object`, and add `value` to it. + * @param {Object} object the object to mutate + * @param {string} key the object's key + * @param {any} value the value to add + * @returns {void} + * @private + */ + function ensureArrayAndPush(object, key, value) { + if (!Array.isArray(object[key])) { + object[key] = []; + } + object[key].push(value); + } + + /** + * Retrieves an array containing all strings (" or ') in the source code. + * @returns {ASTNode[]} An array of string nodes. + */ + function getAllStrings() { + return sourceCode.ast.tokens.filter( + token => + token.type === "String" || + (token.type === "JSXText" && + sourceCode.getNodeByRangeIndex(token.range[0] - 1) + .type === "JSXAttribute"), + ); + } + + /** + * Retrieves an array containing all template literals in the source code. + * @returns {ASTNode[]} An array of template literal nodes. + */ + function getAllTemplateLiterals() { + return sourceCode.ast.tokens.filter( + token => token.type === "Template", + ); + } + + /** + * Retrieves an array containing all RegExp literals in the source code. + * @returns {ASTNode[]} An array of RegExp literal nodes. + */ + function getAllRegExpLiterals() { + return sourceCode.ast.tokens.filter( + token => token.type === "RegularExpression", + ); + } + + /** + * + * reduce an array of AST nodes by line number, both start and end. + * @param {ASTNode[]} arr array of AST nodes + * @returns {Object} accululated AST nodes + */ + function groupArrayByLineNumber(arr) { + const obj = {}; + + for (let i = 0; i < arr.length; i++) { + const node = arr[i]; + + for (let j = node.loc.start.line; j <= node.loc.end.line; ++j) { + ensureArrayAndPush(obj, j, node); + } + } + return obj; + } + + /** + * Returns an array of all comments in the source code. + * If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer, + * the element is changed with JSXExpressionContainer node. + * @returns {ASTNode[]} An array of comment nodes + */ + function getAllComments() { + const comments = []; + + sourceCode.getAllComments().forEach(commentNode => { + const containingNode = sourceCode.getNodeByRangeIndex( + commentNode.range[0], + ); + + if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) { + // push a unique node only + if (comments.at(-1) !== containingNode.parent) { + comments.push(containingNode.parent); + } + } else { + comments.push(commentNode); + } + }); + + return comments; + } + + /** + * Check the program for max length + * @param {ASTNode} node Node to examine + * @returns {void} + * @private + */ + function checkProgramForMaxLength(node) { + // split (honors line-ending) + const lines = sourceCode.lines, + // list of comments to ignore + comments = + ignoreComments || maxCommentLength || ignoreTrailingComments + ? getAllComments() + : []; + + // we iterate over comments in parallel with the lines + let commentsIndex = 0; + + const strings = getAllStrings(); + const stringsByLine = groupArrayByLineNumber(strings); + + const templateLiterals = getAllTemplateLiterals(); + const templateLiteralsByLine = + groupArrayByLineNumber(templateLiterals); + + const regExpLiterals = getAllRegExpLiterals(); + const regExpLiteralsByLine = groupArrayByLineNumber(regExpLiterals); + + lines.forEach((line, i) => { + // i is zero-indexed, line numbers are one-indexed + const lineNumber = i + 1; + + /* + * if we're checking comment length; we need to know whether this + * line is a comment + */ + let lineIsComment = false; + let textToMeasure; + + /* + * We can short-circuit the comment checks if we're already out of + * comments to check. + */ + if (commentsIndex < comments.length) { + let comment; + + // iterate over comments until we find one past the current line + do { + comment = comments[++commentsIndex]; + } while (comment && comment.loc.start.line <= lineNumber); + + // and step back by one + comment = comments[--commentsIndex]; + + if (isFullLineComment(line, lineNumber, comment)) { + lineIsComment = true; + textToMeasure = line; + } else if ( + ignoreTrailingComments && + isTrailingComment(line, lineNumber, comment) + ) { + textToMeasure = stripTrailingComment(line, comment); + + // ignore multiple trailing comments in the same line + let lastIndex = commentsIndex; + + while ( + isTrailingComment( + textToMeasure, + lineNumber, + comments[--lastIndex], + ) + ) { + textToMeasure = stripTrailingComment( + textToMeasure, + comments[lastIndex], + ); + } + } else { + textToMeasure = line; + } + } else { + textToMeasure = line; + } + if ( + (ignorePattern && ignorePattern.test(textToMeasure)) || + (ignoreUrls && URL_REGEXP.test(textToMeasure)) || + (ignoreStrings && stringsByLine[lineNumber]) || + (ignoreTemplateLiterals && + templateLiteralsByLine[lineNumber]) || + (ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]) + ) { + // ignore this line + return; + } + + const lineLength = computeLineLength(textToMeasure, tabWidth); + const commentLengthApplies = lineIsComment && maxCommentLength; + + if (lineIsComment && ignoreComments) { + return; + } + + const loc = { + start: { + line: lineNumber, + column: 0, + }, + end: { + line: lineNumber, + column: textToMeasure.length, + }, + }; + + if (commentLengthApplies) { + if (lineLength > maxCommentLength) { + context.report({ + node, + loc, + messageId: "maxComment", + data: { + lineLength, + maxCommentLength, + }, + }); + } + } else if (lineLength > maxLength) { + context.report({ + node, + loc, + messageId: "max", + data: { + lineLength, + maxLength, + }, + }); + } + }); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Program: checkProgramForMaxLength, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/max-lines-per-function.js b/node_modules/eslint/lib/rules/max-lines-per-function.js new file mode 100644 index 00000000..fd9a783f --- /dev/null +++ b/node_modules/eslint/lib/rules/max-lines-per-function.js @@ -0,0 +1,238 @@ +/** + * @fileoverview A rule to set the maximum number of line of code in a function. + * @author Pete Ward + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const OPTIONS_SCHEMA = { + type: "object", + properties: { + max: { + type: "integer", + minimum: 0, + }, + skipComments: { + type: "boolean", + }, + skipBlankLines: { + type: "boolean", + }, + IIFEs: { + type: "boolean", + }, + }, + additionalProperties: false, +}; + +const OPTIONS_OR_INTEGER_SCHEMA = { + oneOf: [ + OPTIONS_SCHEMA, + { + type: "integer", + minimum: 1, + }, + ], +}; + +/** + * Given a list of comment nodes, return a map with numeric keys (source code line numbers) and comment token values. + * @param {Array} comments An array of comment nodes. + * @returns {Map} A map with numeric keys (source code line numbers) and comment token values. + */ +function getCommentLineNumbers(comments) { + const map = new Map(); + + comments.forEach(comment => { + for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) { + map.set(i, comment); + } + }); + return map; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce a maximum number of lines of code in a function", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-lines-per-function", + }, + + schema: [OPTIONS_OR_INTEGER_SCHEMA], + messages: { + exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const lines = sourceCode.lines; + + const option = context.options[0]; + let maxLines = 50; + let skipComments = false; + let skipBlankLines = false; + let IIFEs = false; + + if (typeof option === "object") { + maxLines = typeof option.max === "number" ? option.max : 50; + skipComments = !!option.skipComments; + skipBlankLines = !!option.skipBlankLines; + IIFEs = !!option.IIFEs; + } else if (typeof option === "number") { + maxLines = option; + } + + const commentLineNumbers = getCommentLineNumbers( + sourceCode.getAllComments(), + ); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tells if a comment encompasses the entire line. + * @param {string} line The source line with a trailing comment + * @param {number} lineNumber The one-indexed line number this is on + * @param {ASTNode} comment The comment to remove + * @returns {boolean} If the comment covers the entire line + */ + function isFullLineComment(line, lineNumber, comment) { + const start = comment.loc.start, + end = comment.loc.end, + isFirstTokenOnLine = + start.line === lineNumber && + !line.slice(0, start.column).trim(), + isLastTokenOnLine = + end.line === lineNumber && !line.slice(end.column).trim(); + + return ( + comment && + (start.line < lineNumber || isFirstTokenOnLine) && + (end.line > lineNumber || isLastTokenOnLine) + ); + } + + /** + * Identifies is a node is a FunctionExpression which is part of an IIFE + * @param {ASTNode} node Node to test + * @returns {boolean} True if it's an IIFE + */ + function isIIFE(node) { + return ( + (node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression") && + node.parent && + node.parent.type === "CallExpression" && + node.parent.callee === node + ); + } + + /** + * Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property + * @param {ASTNode} node Node to test + * @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property + */ + function isEmbedded(node) { + if (!node.parent) { + return false; + } + if (node !== node.parent.value) { + return false; + } + if (node.parent.type === "MethodDefinition") { + return true; + } + if (node.parent.type === "Property") { + return ( + node.parent.method === true || + node.parent.kind === "get" || + node.parent.kind === "set" + ); + } + return false; + } + + /** + * Count the lines in the function + * @param {ASTNode} funcNode Function AST node + * @returns {void} + * @private + */ + function processFunction(funcNode) { + const node = isEmbedded(funcNode) ? funcNode.parent : funcNode; + + if (!IIFEs && isIIFE(node)) { + return; + } + let lineCount = 0; + + for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) { + const line = lines[i]; + + if (skipComments) { + if ( + commentLineNumbers.has(i + 1) && + isFullLineComment( + line, + i + 1, + commentLineNumbers.get(i + 1), + ) + ) { + continue; + } + } + + if (skipBlankLines) { + if (line.match(/^\s*$/u)) { + continue; + } + } + + lineCount++; + } + + if (lineCount > maxLines) { + const name = upperCaseFirst( + astUtils.getFunctionNameWithKind(funcNode), + ); + + context.report({ + node, + messageId: "exceed", + data: { name, lineCount, maxLines }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: processFunction, + FunctionExpression: processFunction, + ArrowFunctionExpression: processFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/max-lines.js b/node_modules/eslint/lib/rules/max-lines.js new file mode 100644 index 00000000..eb8aeb1a --- /dev/null +++ b/node_modules/eslint/lib/rules/max-lines.js @@ -0,0 +1,189 @@ +/** + * @fileoverview enforce a maximum file length + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Creates an array of numbers from `start` up to, but not including, `end` + * @param {number} start The start of the range + * @param {number} end The end of the range + * @returns {number[]} The range of numbers + */ +function range(start, end) { + return [...Array(end - start).keys()].map(x => x + start); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum number of lines per file", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-lines", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + max: { + type: "integer", + minimum: 0, + }, + skipComments: { + type: "boolean", + }, + skipBlankLines: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + exceed: "File has too many lines ({{actual}}). Maximum allowed is {{max}}.", + }, + }, + + create(context) { + const option = context.options[0]; + let max = 300; + + if (typeof option === "object" && Object.hasOwn(option, "max")) { + max = option.max; + } else if (typeof option === "number") { + max = option; + } + + const skipComments = option && option.skipComments; + const skipBlankLines = option && option.skipBlankLines; + + const sourceCode = context.sourceCode; + + /** + * Returns whether or not a token is a comment node type + * @param {Token} token The token to check + * @returns {boolean} True if the token is a comment node + */ + function isCommentNodeType(token) { + return token && (token.type === "Block" || token.type === "Line"); + } + + /** + * Returns the line numbers of a comment that don't have any code on the same line + * @param {Node} comment The comment node to check + * @returns {number[]} The line numbers + */ + function getLinesWithoutCode(comment) { + let start = comment.loc.start.line; + let end = comment.loc.end.line; + + let token; + + token = comment; + do { + token = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + } while (isCommentNodeType(token)); + + if (token && astUtils.isTokenOnSameLine(token, comment)) { + start += 1; + } + + token = comment; + do { + token = sourceCode.getTokenAfter(token, { + includeComments: true, + }); + } while (isCommentNodeType(token)); + + if (token && astUtils.isTokenOnSameLine(comment, token)) { + end -= 1; + } + + if (start <= end) { + return range(start, end + 1); + } + return []; + } + + return { + "Program:exit"() { + let lines = sourceCode.lines.map((text, i) => ({ + lineNumber: i + 1, + text, + })); + + /* + * If file ends with a linebreak, `sourceCode.lines` will have one extra empty line at the end. + * That isn't a real line, so we shouldn't count it. + */ + if (lines.length > 1 && lines.at(-1).text === "") { + lines.pop(); + } + + if (skipBlankLines) { + lines = lines.filter(l => l.text.trim() !== ""); + } + + if (skipComments) { + const comments = sourceCode.getAllComments(); + + const commentLines = new Set( + comments.flatMap(getLinesWithoutCode), + ); + + lines = lines.filter(l => !commentLines.has(l.lineNumber)); + } + + if (lines.length > max) { + const loc = { + start: { + line: lines[max].lineNumber, + column: 0, + }, + end: { + line: sourceCode.lines.length, + column: sourceCode.lines.at(-1).length, + }, + }; + + context.report({ + loc, + messageId: "exceed", + data: { + max, + actual: lines.length, + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/max-nested-callbacks.js b/node_modules/eslint/lib/rules/max-nested-callbacks.js new file mode 100644 index 00000000..e97483a6 --- /dev/null +++ b/node_modules/eslint/lib/rules/max-nested-callbacks.js @@ -0,0 +1,115 @@ +/** + * @fileoverview Rule to enforce a maximum number of nested callbacks. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Enforce a maximum depth that callbacks can be nested", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-nested-callbacks", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + exceed: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Constants + //-------------------------------------------------------------------------- + const option = context.options[0]; + let THRESHOLD = 10; + + if ( + typeof option === "object" && + (Object.hasOwn(option, "maximum") || Object.hasOwn(option, "max")) + ) { + THRESHOLD = option.maximum || option.max; + } else if (typeof option === "number") { + THRESHOLD = option; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const callbackStack = []; + + /** + * Checks a given function node for too many callbacks. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkFunction(node) { + const parent = node.parent; + + if (parent.type === "CallExpression") { + callbackStack.push(node); + } + + if (callbackStack.length > THRESHOLD) { + const opts = { num: callbackStack.length, max: THRESHOLD }; + + context.report({ node, messageId: "exceed", data: opts }); + } + } + + /** + * Pops the call stack. + * @returns {void} + * @private + */ + function popStack() { + callbackStack.pop(); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + ArrowFunctionExpression: checkFunction, + "ArrowFunctionExpression:exit": popStack, + + FunctionExpression: checkFunction, + "FunctionExpression:exit": popStack, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/max-params.js b/node_modules/eslint/lib/rules/max-params.js new file mode 100644 index 00000000..eeb61edd --- /dev/null +++ b/node_modules/eslint/lib/rules/max-params.js @@ -0,0 +1,129 @@ +/** + * @fileoverview Rule to flag when a function has too many parameters + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: + "Enforce a maximum number of parameters in function definitions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-params", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + countVoidThis: { + type: "boolean", + description: + "Whether to count a `this` declaration when the type is `void`.", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + exceed: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0]; + let numParams = 3; + let countVoidThis = false; + + if (typeof option === "object") { + if ( + Object.hasOwn(option, "maximum") || + Object.hasOwn(option, "max") + ) { + numParams = option.maximum || option.max; + } + countVoidThis = option.countVoidThis; + } + if (typeof option === "number") { + numParams = option; + } + + /** + * Checks a function to see if it has too many parameters. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkFunction(node) { + const hasVoidThisParam = + node.params.length > 0 && + node.params[0].type === "Identifier" && + node.params[0].name === "this" && + node.params[0].typeAnnotation?.typeAnnotation.type === + "TSVoidKeyword"; + + const effectiveParamCount = + hasVoidThisParam && !countVoidThis + ? node.params.length - 1 + : node.params.length; + + if (effectiveParamCount > numParams) { + context.report({ + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + node, + messageId: "exceed", + data: { + name: upperCaseFirst( + astUtils.getFunctionNameWithKind(node), + ), + count: effectiveParamCount, + max: numParams, + }, + }); + } + } + + return { + FunctionDeclaration: checkFunction, + ArrowFunctionExpression: checkFunction, + FunctionExpression: checkFunction, + TSDeclareFunction: checkFunction, + TSFunctionType: checkFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/max-statements-per-line.js b/node_modules/eslint/lib/rules/max-statements-per-line.js new file mode 100644 index 00000000..537fe661 --- /dev/null +++ b/node_modules/eslint/lib/rules/max-statements-per-line.js @@ -0,0 +1,224 @@ +/** + * @fileoverview Specify the maximum number of statements allowed per line. + * @author Kenneth Williams + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "max-statements-per-line", + url: "https://eslint.style/rules/js/max-statements-per-line", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce a maximum number of statements allowed per line", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-statements-per-line", + }, + + schema: [ + { + type: "object", + properties: { + max: { + type: "integer", + minimum: 1, + default: 1, + }, + }, + additionalProperties: false, + }, + ], + messages: { + exceed: "This line has {{numberOfStatementsOnThisLine}} {{statements}}. Maximum allowed is {{maxStatementsPerLine}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode, + options = context.options[0] || {}, + maxStatementsPerLine = + typeof options.max !== "undefined" ? options.max : 1; + + let lastStatementLine = 0, + numberOfStatementsOnThisLine = 0, + firstExtraStatement; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const SINGLE_CHILD_ALLOWED = + /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/u; + + /** + * Reports with the first extra statement, and clears it. + * @returns {void} + */ + function reportFirstExtraStatementAndClear() { + if (firstExtraStatement) { + context.report({ + node: firstExtraStatement, + messageId: "exceed", + data: { + numberOfStatementsOnThisLine, + maxStatementsPerLine, + statements: + numberOfStatementsOnThisLine === 1 + ? "statement" + : "statements", + }, + }); + } + firstExtraStatement = null; + } + + /** + * Gets the actual last token of a given node. + * @param {ASTNode} node A node to get. This is a node except EmptyStatement. + * @returns {Token} The actual last token. + */ + function getActualLastToken(node) { + return sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); + } + + /** + * Addresses a given node. + * It updates the state of this rule, then reports the node if the node violated this rule. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function enterStatement(node) { + const line = node.loc.start.line; + + /* + * Skip to allow non-block statements if this is direct child of control statements. + * `if (a) foo();` is counted as 1. + * But `if (a) foo(); else foo();` should be counted as 2. + */ + if ( + SINGLE_CHILD_ALLOWED.test(node.parent.type) && + node.parent.alternate !== node + ) { + return; + } + + // Update state. + if (line === lastStatementLine) { + numberOfStatementsOnThisLine += 1; + } else { + reportFirstExtraStatementAndClear(); + numberOfStatementsOnThisLine = 1; + lastStatementLine = line; + } + + // Reports if the node violated this rule. + if (numberOfStatementsOnThisLine === maxStatementsPerLine + 1) { + firstExtraStatement = firstExtraStatement || node; + } + } + + /** + * Updates the state of this rule with the end line of leaving node to check with the next statement. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function leaveStatement(node) { + const line = getActualLastToken(node).loc.end.line; + + // Update state. + if (line !== lastStatementLine) { + reportFirstExtraStatementAndClear(); + numberOfStatementsOnThisLine = 1; + lastStatementLine = line; + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + BreakStatement: enterStatement, + ClassDeclaration: enterStatement, + ContinueStatement: enterStatement, + DebuggerStatement: enterStatement, + DoWhileStatement: enterStatement, + ExpressionStatement: enterStatement, + ForInStatement: enterStatement, + ForOfStatement: enterStatement, + ForStatement: enterStatement, + FunctionDeclaration: enterStatement, + IfStatement: enterStatement, + ImportDeclaration: enterStatement, + LabeledStatement: enterStatement, + ReturnStatement: enterStatement, + SwitchStatement: enterStatement, + ThrowStatement: enterStatement, + TryStatement: enterStatement, + VariableDeclaration: enterStatement, + WhileStatement: enterStatement, + WithStatement: enterStatement, + ExportNamedDeclaration: enterStatement, + ExportDefaultDeclaration: enterStatement, + ExportAllDeclaration: enterStatement, + + "BreakStatement:exit": leaveStatement, + "ClassDeclaration:exit": leaveStatement, + "ContinueStatement:exit": leaveStatement, + "DebuggerStatement:exit": leaveStatement, + "DoWhileStatement:exit": leaveStatement, + "ExpressionStatement:exit": leaveStatement, + "ForInStatement:exit": leaveStatement, + "ForOfStatement:exit": leaveStatement, + "ForStatement:exit": leaveStatement, + "FunctionDeclaration:exit": leaveStatement, + "IfStatement:exit": leaveStatement, + "ImportDeclaration:exit": leaveStatement, + "LabeledStatement:exit": leaveStatement, + "ReturnStatement:exit": leaveStatement, + "SwitchStatement:exit": leaveStatement, + "ThrowStatement:exit": leaveStatement, + "TryStatement:exit": leaveStatement, + "VariableDeclaration:exit": leaveStatement, + "WhileStatement:exit": leaveStatement, + "WithStatement:exit": leaveStatement, + "ExportNamedDeclaration:exit": leaveStatement, + "ExportDefaultDeclaration:exit": leaveStatement, + "ExportAllDeclaration:exit": leaveStatement, + "Program:exit": reportFirstExtraStatementAndClear, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/max-statements.js b/node_modules/eslint/lib/rules/max-statements.js new file mode 100644 index 00000000..c38482cd --- /dev/null +++ b/node_modules/eslint/lib/rules/max-statements.js @@ -0,0 +1,188 @@ +/** + * @fileoverview A rule to set the maximum number of statements in a function. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce a maximum number of statements allowed in function blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/max-statements", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + { + type: "object", + properties: { + ignoreTopLevelFunctions: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + exceed: "{{name}} has too many statements ({{count}}). Maximum allowed is {{max}}.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const functionStack = [], + option = context.options[0], + ignoreTopLevelFunctions = + (context.options[1] && + context.options[1].ignoreTopLevelFunctions) || + false, + topLevelFunctions = []; + let maxStatements = 10; + + if ( + typeof option === "object" && + (Object.hasOwn(option, "maximum") || Object.hasOwn(option, "max")) + ) { + maxStatements = option.maximum || option.max; + } else if (typeof option === "number") { + maxStatements = option; + } + + /** + * Reports a node if it has too many statements + * @param {ASTNode} node node to evaluate + * @param {number} count Number of statements in node + * @param {number} max Maximum number of statements allowed + * @returns {void} + * @private + */ + function reportIfTooManyStatements(node, count, max) { + if (count > max) { + const name = upperCaseFirst( + astUtils.getFunctionNameWithKind(node), + ); + + context.report({ + node, + messageId: "exceed", + data: { name, count, max }, + }); + } + } + + /** + * When parsing a new function, store it in our function stack + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push(0); + } + + /** + * Evaluate the node at the end of function + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function endFunction(node) { + const count = functionStack.pop(); + + /* + * This rule does not apply to class static blocks, but we have to track them so + * that statements in them do not count as statements in the enclosing function. + */ + if (node.type === "StaticBlock") { + return; + } + + if (ignoreTopLevelFunctions && functionStack.length === 0) { + topLevelFunctions.push({ node, count }); + } else { + reportIfTooManyStatements(node, count, maxStatements); + } + } + + /** + * Increment the count of the functions + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function countStatements(node) { + functionStack[functionStack.length - 1] += node.body.length; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: startFunction, + FunctionExpression: startFunction, + ArrowFunctionExpression: startFunction, + StaticBlock: startFunction, + + BlockStatement: countStatements, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "StaticBlock:exit": endFunction, + + "Program:exit"() { + if (topLevelFunctions.length === 1) { + return; + } + + topLevelFunctions.forEach(element => { + const count = element.count; + const node = element.node; + + reportIfTooManyStatements(node, count, maxStatements); + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/multiline-comment-style.js b/node_modules/eslint/lib/rules/multiline-comment-style.js new file mode 100644 index 00000000..fd31c27b --- /dev/null +++ b/node_modules/eslint/lib/rules/multiline-comment-style.js @@ -0,0 +1,652 @@ +/** + * @fileoverview enforce a particular style for multiline comments + * @author Teddy Katz + * @deprecated in ESLint v9.3.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "9.3.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "multiline-comment-style", + url: "https://eslint.style/rules/js/multiline-comment-style", + }, + }, + ], + }, + type: "suggestion", + docs: { + description: "Enforce a particular style for multiline comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/multiline-comment-style", + }, + + fixable: "whitespace", + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["starred-block", "bare-block"], + }, + ], + additionalItems: false, + }, + { + type: "array", + items: [ + { + enum: ["separate-lines"], + }, + { + type: "object", + properties: { + checkJSDoc: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + additionalItems: false, + }, + ], + }, + messages: { + expectedBlock: + "Expected a block comment instead of consecutive line comments.", + expectedBareBlock: + "Expected a block comment without padding stars.", + startNewline: "Expected a linebreak after '/*'.", + endNewline: "Expected a linebreak before '*/'.", + missingStar: "Expected a '*' at the start of this line.", + alignment: + "Expected this line to be aligned with the start of the comment.", + expectedLines: + "Expected multiple line comments instead of a block comment.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0] || "starred-block"; + const params = context.options[1] || {}; + const checkJSDoc = !!params.checkJSDoc; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks if a comment line is starred. + * @param {string} line A string representing a comment line. + * @returns {boolean} Whether or not the comment line is starred. + */ + function isStarredCommentLine(line) { + return /^\s*\*/u.test(line); + } + + /** + * Checks if a comment group is in starred-block form. + * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment. + * @returns {boolean} Whether or not the comment group is in starred block form. + */ + function isStarredBlockComment([firstComment]) { + if (firstComment.type !== "Block") { + return false; + } + + const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); + + // The first and last lines can only contain whitespace. + return ( + lines.length > 0 && + lines.every((line, i) => + (i === 0 || i === lines.length - 1 + ? /^\s*$/u + : /^\s*\*/u + ).test(line), + ) + ); + } + + /** + * Checks if a comment group is in JSDoc form. + * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment. + * @returns {boolean} Whether or not the comment group is in JSDoc form. + */ + function isJSDocComment([firstComment]) { + if (firstComment.type !== "Block") { + return false; + } + + const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); + + return ( + /^\*\s*$/u.test(lines[0]) && + lines.slice(1, -1).every(line => /^\s* /u.test(line)) && + /^\s*$/u.test(lines.at(-1)) + ); + } + + /** + * Processes a comment group that is currently in separate-line form, calculating the offset for each line. + * @param {Token[]} commentGroup A group of comments containing multiple line comments. + * @returns {string[]} An array of the processed lines. + */ + function processSeparateLineComments(commentGroup) { + const allLinesHaveLeadingSpace = commentGroup + .map(({ value }) => value) + .filter(line => line.trim().length) + .every(line => line.startsWith(" ")); + + return commentGroup.map(({ value }) => + allLinesHaveLeadingSpace ? value.replace(/^ /u, "") : value, + ); + } + + /** + * Processes a comment group that is currently in starred-block form, calculating the offset for each line. + * @param {Token} comment A single block comment token in starred-block form. + * @returns {string[]} An array of the processed lines. + */ + function processStarredBlockComment(comment) { + const lines = comment.value + .split(astUtils.LINEBREAK_MATCHER) + .filter( + (line, i, linesArr) => + !(i === 0 || i === linesArr.length - 1), + ) + .map(line => line.replace(/^\s*$/u, "")); + const allLinesHaveLeadingSpace = lines + .map(line => line.replace(/\s*\*/u, "")) + .filter(line => line.trim().length) + .every(line => line.startsWith(" ")); + + return lines.map(line => + line.replace( + allLinesHaveLeadingSpace ? /\s*\* ?/u : /\s*\*/u, + "", + ), + ); + } + + /** + * Processes a comment group that is currently in bare-block form, calculating the offset for each line. + * @param {Token} comment A single block comment token in bare-block form. + * @returns {string[]} An array of the processed lines. + */ + function processBareBlockComment(comment) { + const lines = comment.value + .split(astUtils.LINEBREAK_MATCHER) + .map(line => line.replace(/^\s*$/u, "")); + const leadingWhitespace = `${sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0])} `; + let offset = ""; + + /* + * Calculate the offset of the least indented line and use that as the basis for offsetting all the lines. + * The first line should not be checked because it is inline with the opening block comment delimiter. + */ + for (const [i, line] of lines.entries()) { + if (!line.trim().length || i === 0) { + continue; + } + + const [, lineOffset] = line.match(/^(\s*\*?\s*)/u); + + if (lineOffset.length < leadingWhitespace.length) { + const newOffset = leadingWhitespace.slice( + lineOffset.length - leadingWhitespace.length, + ); + + if (newOffset.length > offset.length) { + offset = newOffset; + } + } + } + + return lines.map(line => { + const match = line.match(/^(\s*\*?\s*)(.*)/u); + const [, lineOffset, lineContents] = match; + + if (lineOffset.length > leadingWhitespace.length) { + return `${lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))}${lineContents}`; + } + + if (lineOffset.length < leadingWhitespace.length) { + return `${lineOffset.slice(leadingWhitespace.length)}${lineContents}`; + } + + return lineContents; + }); + } + + /** + * Gets a list of comment lines in a group, formatting leading whitespace as necessary. + * @param {Token[]} commentGroup A group of comments containing either multiple line comments or a single block comment. + * @returns {string[]} A list of comment lines. + */ + function getCommentLines(commentGroup) { + const [firstComment] = commentGroup; + + if (firstComment.type === "Line") { + return processSeparateLineComments(commentGroup); + } + + if (isStarredBlockComment(commentGroup)) { + return processStarredBlockComment(firstComment); + } + + return processBareBlockComment(firstComment); + } + + /** + * Gets the initial offset (whitespace) from the beginning of a line to a given comment token. + * @param {Token} comment The token to check. + * @returns {string} The offset from the beginning of a line to the token. + */ + function getInitialOffset(comment) { + return sourceCode.text.slice( + comment.range[0] - comment.loc.start.column, + comment.range[0], + ); + } + + /** + * Converts a comment into starred-block form + * @param {Token} firstComment The first comment of the group being converted + * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment + * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers + */ + function convertToStarredBlock(firstComment, commentLinesList) { + const initialOffset = getInitialOffset(firstComment); + + return `/*\n${commentLinesList.map(line => `${initialOffset} * ${line}`).join("\n")}\n${initialOffset} */`; + } + + /** + * Converts a comment into separate-line form + * @param {Token} firstComment The first comment of the group being converted + * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment + * @returns {string} A representation of the comment value in separate-line form + */ + function convertToSeparateLines(firstComment, commentLinesList) { + return commentLinesList + .map(line => `// ${line}`) + .join(`\n${getInitialOffset(firstComment)}`); + } + + /** + * Converts a comment into bare-block form + * @param {Token} firstComment The first comment of the group being converted + * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment + * @returns {string} A representation of the comment value in bare-block form + */ + function convertToBlock(firstComment, commentLinesList) { + return `/* ${commentLinesList.join(`\n${getInitialOffset(firstComment)} `)} */`; + } + + /** + * Each method checks a group of comments to see if it's valid according to the given option. + * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single + * block comment or multiple line comments. + * @returns {void} + */ + const commentGroupCheckers = { + "starred-block"(commentGroup) { + const [firstComment] = commentGroup; + const commentLines = getCommentLines(commentGroup); + + if (commentLines.some(value => value.includes("*/"))) { + return; + } + + if (commentGroup.length > 1) { + context.report({ + loc: { + start: firstComment.loc.start, + end: commentGroup.at(-1).loc.end, + }, + messageId: "expectedBlock", + fix(fixer) { + const range = [ + firstComment.range[0], + commentGroup.at(-1).range[1], + ]; + + return commentLines.some(value => + value.startsWith("/"), + ) + ? null + : fixer.replaceTextRange( + range, + convertToStarredBlock( + firstComment, + commentLines, + ), + ); + }, + }); + } else { + const lines = firstComment.value.split( + astUtils.LINEBREAK_MATCHER, + ); + const expectedLeadingWhitespace = + getInitialOffset(firstComment); + const expectedLinePrefix = `${expectedLeadingWhitespace} *`; + + if (!/^\*?\s*$/u.test(lines[0])) { + const start = firstComment.value.startsWith("*") + ? firstComment.range[0] + 1 + : firstComment.range[0]; + + context.report({ + loc: { + start: firstComment.loc.start, + end: { + line: firstComment.loc.start.line, + column: firstComment.loc.start.column + 2, + }, + }, + messageId: "startNewline", + fix: fixer => + fixer.insertTextAfterRange( + [start, start + 2], + `\n${expectedLinePrefix}`, + ), + }); + } + + if (!/^\s*$/u.test(lines.at(-1))) { + context.report({ + loc: { + start: { + line: firstComment.loc.end.line, + column: firstComment.loc.end.column - 2, + }, + end: firstComment.loc.end, + }, + messageId: "endNewline", + fix: fixer => + fixer.replaceTextRange( + [ + firstComment.range[1] - 2, + firstComment.range[1], + ], + `\n${expectedLinePrefix}/`, + ), + }); + } + + for ( + let lineNumber = firstComment.loc.start.line + 1; + lineNumber <= firstComment.loc.end.line; + lineNumber++ + ) { + const lineText = sourceCode.lines[lineNumber - 1]; + const errorType = isStarredCommentLine(lineText) + ? "alignment" + : "missingStar"; + + if (!lineText.startsWith(expectedLinePrefix)) { + context.report({ + loc: { + start: { line: lineNumber, column: 0 }, + end: { + line: lineNumber, + column: lineText.length, + }, + }, + messageId: errorType, + fix(fixer) { + const lineStartIndex = + sourceCode.getIndexFromLoc({ + line: lineNumber, + column: 0, + }); + + if (errorType === "alignment") { + const [, commentTextPrefix = ""] = + lineText.match(/^(\s*\*)/u) || []; + const commentTextStartIndex = + lineStartIndex + + commentTextPrefix.length; + + return fixer.replaceTextRange( + [ + lineStartIndex, + commentTextStartIndex, + ], + expectedLinePrefix, + ); + } + + const [, commentTextPrefix = ""] = + lineText.match(/^(\s*)/u) || []; + const commentTextStartIndex = + lineStartIndex + + commentTextPrefix.length; + let offset; + + for (const [idx, line] of lines.entries()) { + if (!/\S+/u.test(line)) { + continue; + } + + const lineTextToAlignWith = + sourceCode.lines[ + firstComment.loc.start.line - + 1 + + idx + ]; + const [ + , + prefix = "", + initialOffset = "", + ] = + lineTextToAlignWith.match( + /^(\s*(?:\/?\*)?(\s*))/u, + ) || []; + + offset = `${commentTextPrefix.slice(prefix.length)}${initialOffset}`; + + if ( + /^\s*\//u.test(lineText) && + offset.length === 0 + ) { + offset += " "; + } + break; + } + + return fixer.replaceTextRange( + [lineStartIndex, commentTextStartIndex], + `${expectedLinePrefix}${offset}`, + ); + }, + }); + } + } + } + }, + "separate-lines"(commentGroup) { + const [firstComment] = commentGroup; + + const isJSDoc = isJSDocComment(commentGroup); + + if (firstComment.type !== "Block" || (!checkJSDoc && isJSDoc)) { + return; + } + + let commentLines = getCommentLines(commentGroup); + + if (isJSDoc) { + commentLines = commentLines.slice( + 1, + commentLines.length - 1, + ); + } + + const tokenAfter = sourceCode.getTokenAfter(firstComment, { + includeComments: true, + }); + + if ( + tokenAfter && + firstComment.loc.end.line === tokenAfter.loc.start.line + ) { + return; + } + + context.report({ + loc: { + start: firstComment.loc.start, + end: { + line: firstComment.loc.start.line, + column: firstComment.loc.start.column + 2, + }, + }, + messageId: "expectedLines", + fix(fixer) { + return fixer.replaceText( + firstComment, + convertToSeparateLines(firstComment, commentLines), + ); + }, + }); + }, + "bare-block"(commentGroup) { + if (isJSDocComment(commentGroup)) { + return; + } + + const [firstComment] = commentGroup; + const commentLines = getCommentLines(commentGroup); + + // Disallows consecutive line comments in favor of using a block comment. + if ( + firstComment.type === "Line" && + commentLines.length > 1 && + !commentLines.some(value => value.includes("*/")) + ) { + context.report({ + loc: { + start: firstComment.loc.start, + end: commentGroup.at(-1).loc.end, + }, + messageId: "expectedBlock", + fix(fixer) { + return fixer.replaceTextRange( + [ + firstComment.range[0], + commentGroup.at(-1).range[1], + ], + convertToBlock(firstComment, commentLines), + ); + }, + }); + } + + // Prohibits block comments from having a * at the beginning of each line. + if (isStarredBlockComment(commentGroup)) { + context.report({ + loc: { + start: firstComment.loc.start, + end: { + line: firstComment.loc.start.line, + column: firstComment.loc.start.column + 2, + }, + }, + messageId: "expectedBareBlock", + fix(fixer) { + return fixer.replaceText( + firstComment, + convertToBlock(firstComment, commentLines), + ); + }, + }); + } + }, + }; + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + Program() { + return sourceCode + .getAllComments() + .filter(comment => comment.type !== "Shebang") + .filter( + comment => + !astUtils.COMMENTS_IGNORE_PATTERN.test( + comment.value, + ), + ) + .filter(comment => { + const tokenBefore = sourceCode.getTokenBefore(comment, { + includeComments: true, + }); + + return ( + !tokenBefore || + tokenBefore.loc.end.line < comment.loc.start.line + ); + }) + .reduce((commentGroups, comment, index, commentList) => { + const tokenBefore = sourceCode.getTokenBefore(comment, { + includeComments: true, + }); + + if ( + comment.type === "Line" && + index && + commentList[index - 1].type === "Line" && + tokenBefore && + tokenBefore.loc.end.line === + comment.loc.start.line - 1 && + tokenBefore === commentList[index - 1] + ) { + commentGroups.at(-1).push(comment); + } else { + commentGroups.push([comment]); + } + + return commentGroups; + }, []) + .filter( + commentGroup => + !( + commentGroup.length === 1 && + commentGroup[0].loc.start.line === + commentGroup[0].loc.end.line + ), + ) + .forEach(commentGroupCheckers[option]); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/multiline-ternary.js b/node_modules/eslint/lib/rules/multiline-ternary.js new file mode 100644 index 00000000..e9db5cc9 --- /dev/null +++ b/node_modules/eslint/lib/rules/multiline-ternary.js @@ -0,0 +1,257 @@ +/** + * @fileoverview Enforce newlines between operands of ternary expressions + * @author Kai Cataldo + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "multiline-ternary", + url: "https://eslint.style/rules/js/multiline-ternary", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce newlines between operands of ternary expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/multiline-ternary", + }, + + schema: [ + { + enum: ["always", "always-multiline", "never"], + }, + ], + + messages: { + expectedTestCons: + "Expected newline between test and consequent of ternary expression.", + expectedConsAlt: + "Expected newline between consequent and alternate of ternary expression.", + unexpectedTestCons: + "Unexpected newline between test and consequent of ternary expression.", + unexpectedConsAlt: + "Unexpected newline between consequent and alternate of ternary expression.", + }, + + fixable: "whitespace", + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0]; + const multiline = option !== "never"; + const allowSingleLine = option === "always-multiline"; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ConditionalExpression(node) { + const questionToken = sourceCode.getTokenAfter( + node.test, + astUtils.isNotClosingParenToken, + ); + const colonToken = sourceCode.getTokenAfter( + node.consequent, + astUtils.isNotClosingParenToken, + ); + + const firstTokenOfTest = sourceCode.getFirstToken(node); + const lastTokenOfTest = + sourceCode.getTokenBefore(questionToken); + const firstTokenOfConsequent = + sourceCode.getTokenAfter(questionToken); + const lastTokenOfConsequent = + sourceCode.getTokenBefore(colonToken); + const firstTokenOfAlternate = + sourceCode.getTokenAfter(colonToken); + + const areTestAndConsequentOnSameLine = + astUtils.isTokenOnSameLine( + lastTokenOfTest, + firstTokenOfConsequent, + ); + const areConsequentAndAlternateOnSameLine = + astUtils.isTokenOnSameLine( + lastTokenOfConsequent, + firstTokenOfAlternate, + ); + + const hasComments = !!sourceCode.getCommentsInside(node).length; + + if (!multiline) { + if (!areTestAndConsequentOnSameLine) { + context.report({ + node: node.test, + loc: { + start: firstTokenOfTest.loc.start, + end: lastTokenOfTest.loc.end, + }, + messageId: "unexpectedTestCons", + fix(fixer) { + if (hasComments) { + return null; + } + const fixers = []; + const areTestAndQuestionOnSameLine = + astUtils.isTokenOnSameLine( + lastTokenOfTest, + questionToken, + ); + const areQuestionAndConsOnSameLine = + astUtils.isTokenOnSameLine( + questionToken, + firstTokenOfConsequent, + ); + + if (!areTestAndQuestionOnSameLine) { + fixers.push( + fixer.removeRange([ + lastTokenOfTest.range[1], + questionToken.range[0], + ]), + ); + } + if (!areQuestionAndConsOnSameLine) { + fixers.push( + fixer.removeRange([ + questionToken.range[1], + firstTokenOfConsequent.range[0], + ]), + ); + } + + return fixers; + }, + }); + } + + if (!areConsequentAndAlternateOnSameLine) { + context.report({ + node: node.consequent, + loc: { + start: firstTokenOfConsequent.loc.start, + end: lastTokenOfConsequent.loc.end, + }, + messageId: "unexpectedConsAlt", + fix(fixer) { + if (hasComments) { + return null; + } + const fixers = []; + const areConsAndColonOnSameLine = + astUtils.isTokenOnSameLine( + lastTokenOfConsequent, + colonToken, + ); + const areColonAndAltOnSameLine = + astUtils.isTokenOnSameLine( + colonToken, + firstTokenOfAlternate, + ); + + if (!areConsAndColonOnSameLine) { + fixers.push( + fixer.removeRange([ + lastTokenOfConsequent.range[1], + colonToken.range[0], + ]), + ); + } + if (!areColonAndAltOnSameLine) { + fixers.push( + fixer.removeRange([ + colonToken.range[1], + firstTokenOfAlternate.range[0], + ]), + ); + } + + return fixers; + }, + }); + } + } else { + if ( + allowSingleLine && + node.loc.start.line === node.loc.end.line + ) { + return; + } + + if (areTestAndConsequentOnSameLine) { + context.report({ + node: node.test, + loc: { + start: firstTokenOfTest.loc.start, + end: lastTokenOfTest.loc.end, + }, + messageId: "expectedTestCons", + fix: fixer => + hasComments + ? null + : fixer.replaceTextRange( + [ + lastTokenOfTest.range[1], + questionToken.range[0], + ], + "\n", + ), + }); + } + + if (areConsequentAndAlternateOnSameLine) { + context.report({ + node: node.consequent, + loc: { + start: firstTokenOfConsequent.loc.start, + end: lastTokenOfConsequent.loc.end, + }, + messageId: "expectedConsAlt", + fix: fixer => + hasComments + ? null + : fixer.replaceTextRange( + [ + lastTokenOfConsequent.range[1], + colonToken.range[0], + ], + "\n", + ), + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/new-cap.js b/node_modules/eslint/lib/rules/new-cap.js new file mode 100644 index 00000000..caea1a8b --- /dev/null +++ b/node_modules/eslint/lib/rules/new-cap.js @@ -0,0 +1,277 @@ +/** + * @fileoverview Rule to flag use of constructors without capital letters + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const CAPS_ALLOWED = [ + "Array", + "Boolean", + "Date", + "Error", + "Function", + "Number", + "Object", + "RegExp", + "String", + "Symbol", + "BigInt", +]; + +/** + * A reducer function to invert an array to an Object mapping the string form of the key, to `true`. + * @param {Object} map Accumulator object for the reduce. + * @param {string} key Object key to set to `true`. + * @returns {Object} Returns the updated Object for further reduction. + */ +function invert(map, key) { + map[key] = true; + return map; +} + +/** + * Creates an object with the cap is new exceptions as its keys and true as their values. + * @param {Object} config Rule configuration + * @returns {Object} Object with cap is new exceptions. + */ +function calculateCapIsNewExceptions(config) { + const capIsNewExceptions = Array.from( + new Set([...config.capIsNewExceptions, ...CAPS_ALLOWED]), + ); + + return capIsNewExceptions.reduce(invert, {}); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require constructor names to begin with a capital letter", + recommended: false, + url: "https://eslint.org/docs/latest/rules/new-cap", + }, + + schema: [ + { + type: "object", + properties: { + newIsCap: { + type: "boolean", + }, + capIsNew: { + type: "boolean", + }, + newIsCapExceptions: { + type: "array", + items: { + type: "string", + }, + }, + newIsCapExceptionPattern: { + type: "string", + }, + capIsNewExceptions: { + type: "array", + items: { + type: "string", + }, + }, + capIsNewExceptionPattern: { + type: "string", + }, + properties: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + capIsNew: true, + capIsNewExceptions: CAPS_ALLOWED, + newIsCap: true, + newIsCapExceptions: [], + properties: true, + }, + ], + + messages: { + upper: "A function with a name starting with an uppercase letter should only be used as a constructor.", + lower: "A constructor name should not start with a lowercase letter.", + }, + }, + + create(context) { + const [config] = context.options; + const skipProperties = !config.properties; + + const newIsCapExceptions = config.newIsCapExceptions.reduce(invert, {}); + const newIsCapExceptionPattern = config.newIsCapExceptionPattern + ? new RegExp(config.newIsCapExceptionPattern, "u") + : null; + + const capIsNewExceptions = calculateCapIsNewExceptions(config); + const capIsNewExceptionPattern = config.capIsNewExceptionPattern + ? new RegExp(config.capIsNewExceptionPattern, "u") + : null; + + const listeners = {}; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Get exact callee name from expression + * @param {ASTNode} node CallExpression or NewExpression node + * @returns {string} name + */ + function extractNameFromExpression(node) { + return node.callee.type === "Identifier" + ? node.callee.name + : astUtils.getStaticPropertyName(node.callee) || ""; + } + + /** + * Returns the capitalization state of the string - + * Whether the first character is uppercase, lowercase, or non-alphabetic + * @param {string} str String + * @returns {string} capitalization state: "non-alpha", "lower", or "upper" + */ + function getCap(str) { + const firstChar = str.charAt(0); + + const firstCharLower = firstChar.toLowerCase(); + const firstCharUpper = firstChar.toUpperCase(); + + if (firstCharLower === firstCharUpper) { + // char has no uppercase variant, so it's non-alphabetic + return "non-alpha"; + } + if (firstChar === firstCharLower) { + return "lower"; + } + return "upper"; + } + + /** + * Check if capitalization is allowed for a CallExpression + * @param {Object} allowedMap Object mapping calleeName to a Boolean + * @param {ASTNode} node CallExpression node + * @param {string} calleeName Capitalized callee name from a CallExpression + * @param {Object} pattern RegExp object from options pattern + * @returns {boolean} Returns true if the callee may be capitalized + */ + function isCapAllowed(allowedMap, node, calleeName, pattern) { + const sourceText = sourceCode.getText(node.callee); + + if (allowedMap[calleeName] || allowedMap[sourceText]) { + return true; + } + + if (pattern && pattern.test(sourceText)) { + return true; + } + + const callee = astUtils.skipChainExpression(node.callee); + + if (calleeName === "UTC" && callee.type === "MemberExpression") { + // allow if callee is Date.UTC + return ( + callee.object.type === "Identifier" && + callee.object.name === "Date" + ); + } + + return skipProperties && callee.type === "MemberExpression"; + } + + /** + * Reports the given messageId for the given node. The location will be the start of the property or the callee. + * @param {ASTNode} node CallExpression or NewExpression node. + * @param {string} messageId The messageId to report. + * @returns {void} + */ + function report(node, messageId) { + let callee = astUtils.skipChainExpression(node.callee); + + if (callee.type === "MemberExpression") { + callee = callee.property; + } + + context.report({ node, loc: callee.loc, messageId }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + if (config.newIsCap) { + listeners.NewExpression = function (node) { + const constructorName = extractNameFromExpression(node); + + if (constructorName) { + const capitalization = getCap(constructorName); + const isAllowed = + capitalization !== "lower" || + isCapAllowed( + newIsCapExceptions, + node, + constructorName, + newIsCapExceptionPattern, + ); + + if (!isAllowed) { + report(node, "lower"); + } + } + }; + } + + if (config.capIsNew) { + listeners.CallExpression = function (node) { + const calleeName = extractNameFromExpression(node); + + if (calleeName) { + const capitalization = getCap(calleeName); + const isAllowed = + capitalization !== "upper" || + isCapAllowed( + capIsNewExceptions, + node, + calleeName, + capIsNewExceptionPattern, + ); + + if (!isAllowed) { + report(node, "upper"); + } + } + }; + } + + return listeners; + }, +}; diff --git a/node_modules/eslint/lib/rules/new-parens.js b/node_modules/eslint/lib/rules/new-parens.js new file mode 100644 index 00000000..3b070e3a --- /dev/null +++ b/node_modules/eslint/lib/rules/new-parens.js @@ -0,0 +1,120 @@ +/** + * @fileoverview Rule to flag when using constructor without parentheses + * @author Ilya Volodin + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "new-parens", + url: "https://eslint.style/rules/js/new-parens", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce or disallow parentheses when invoking a constructor with no arguments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/new-parens", + }, + + fixable: "code", + schema: [ + { + enum: ["always", "never"], + }, + ], + messages: { + missing: "Missing '()' invoking a constructor.", + unnecessary: + "Unnecessary '()' invoking a constructor with no arguments.", + }, + }, + + create(context) { + const options = context.options; + const always = options[0] !== "never"; // Default is always + + const sourceCode = context.sourceCode; + + return { + NewExpression(node) { + if (node.arguments.length !== 0) { + return; // if there are arguments, there have to be parens + } + + const lastToken = sourceCode.getLastToken(node); + const hasLastParen = + lastToken && astUtils.isClosingParenToken(lastToken); + + // `hasParens` is true only if the new expression ends with its own parens, e.g., new new foo() does not end with its own parens + const hasParens = + hasLastParen && + astUtils.isOpeningParenToken( + sourceCode.getTokenBefore(lastToken), + ) && + node.callee.range[1] < node.range[1]; + + if (always) { + if (!hasParens) { + context.report({ + node, + messageId: "missing", + fix: fixer => fixer.insertTextAfter(node, "()"), + }); + } + } else { + if (hasParens) { + context.report({ + node, + messageId: "unnecessary", + fix: fixer => [ + fixer.remove( + sourceCode.getTokenBefore(lastToken), + ), + fixer.remove(lastToken), + fixer.insertTextBefore(node, "("), + fixer.insertTextAfter(node, ")"), + ], + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/newline-after-var.js b/node_modules/eslint/lib/rules/newline-after-var.js new file mode 100644 index 00000000..0ad20bf1 --- /dev/null +++ b/node_modules/eslint/lib/rules/newline-after-var.js @@ -0,0 +1,307 @@ +/** + * @fileoverview Rule to check empty newline after "var" statement + * @author Gopal Venkatesan + * @deprecated in ESLint v4.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: + "Require or disallow an empty line after variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/newline-after-var", + }, + schema: [ + { + enum: ["never", "always"], + }, + ], + fixable: "whitespace", + messages: { + expected: "Expected blank line after variable declarations.", + unexpected: "Unexpected blank line after variable declarations.", + }, + + deprecated: { + message: "The rule was replaced with a more general rule.", + url: "https://eslint.org/blog/2017/06/eslint-v4.0.0-released/", + deprecatedSince: "4.0.0", + availableUntil: null, + replacedBy: [ + { + message: "The new rule moved to a plugin.", + url: "https://eslint.org/docs/latest/rules/padding-line-between-statements#examples", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "padding-line-between-statements", + url: "https://eslint.style/rules/js/padding-line-between-statements", + }, + }, + ], + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + // Default `mode` to "always". + const mode = context.options[0] === "never" ? "never" : "always"; + + // Cache starting and ending line numbers of comments for faster lookup + const commentEndLine = sourceCode + .getAllComments() + .reduce((result, token) => { + result[token.loc.start.line] = token.loc.end.line; + return result; + }, {}); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Gets a token from the given node to compare line to the next statement. + * + * In general, the token is the last token of the node. However, the token is the second last token if the following conditions satisfy. + * + * - The last token is semicolon. + * - The semicolon is on a different line from the previous token of the semicolon. + * + * This behavior would address semicolon-less style code. e.g.: + * + * var foo = 1 + * + * ;(a || b).doSomething() + * @param {ASTNode} node The node to get. + * @returns {Token} The token to compare line to the next statement. + */ + function getLastToken(node) { + const lastToken = sourceCode.getLastToken(node); + + if (lastToken.type === "Punctuator" && lastToken.value === ";") { + const prevToken = sourceCode.getTokenBefore(lastToken); + + if (prevToken.loc.end.line !== lastToken.loc.start.line) { + return prevToken; + } + } + + return lastToken; + } + + /** + * Determine if provided keyword is a variable declaration + * @private + * @param {string} keyword keyword to test + * @returns {boolean} True if `keyword` is a type of var + */ + function isVar(keyword) { + return ( + keyword === "var" || keyword === "let" || keyword === "const" + ); + } + + /** + * Determine if provided keyword is a variant of for specifiers + * @private + * @param {string} keyword keyword to test + * @returns {boolean} True if `keyword` is a variant of for specifier + */ + function isForTypeSpecifier(keyword) { + return ( + keyword === "ForStatement" || + keyword === "ForInStatement" || + keyword === "ForOfStatement" + ); + } + + /** + * Determine if provided keyword is an export specifiers + * @private + * @param {string} nodeType nodeType to test + * @returns {boolean} True if `nodeType` is an export specifier + */ + function isExportSpecifier(nodeType) { + return ( + nodeType === "ExportNamedDeclaration" || + nodeType === "ExportSpecifier" || + nodeType === "ExportDefaultDeclaration" || + nodeType === "ExportAllDeclaration" + ); + } + + /** + * Determine if provided node is the last of their parent block. + * @private + * @param {ASTNode} node node to test + * @returns {boolean} True if `node` is last of their parent block. + */ + function isLastNode(node) { + const token = sourceCode.getTokenAfter(node); + + return ( + !token || (token.type === "Punctuator" && token.value === "}") + ); + } + + /** + * Gets the last line of a group of consecutive comments + * @param {number} commentStartLine The starting line of the group + * @returns {number} The number of the last comment line of the group + */ + function getLastCommentLineOfBlock(commentStartLine) { + const currentCommentEnd = commentEndLine[commentStartLine]; + + return commentEndLine[currentCommentEnd + 1] + ? getLastCommentLineOfBlock(currentCommentEnd + 1) + : currentCommentEnd; + } + + /** + * Determine if a token starts more than one line after a comment ends + * @param {token} token The token being checked + * @param {integer} commentStartLine The line number on which the comment starts + * @returns {boolean} True if `token` does not start immediately after a comment + */ + function hasBlankLineAfterComment(token, commentStartLine) { + return ( + token.loc.start.line > + getLastCommentLineOfBlock(commentStartLine) + 1 + ); + } + + /** + * Checks that a blank line exists after a variable declaration when mode is + * set to "always", or checks that there is no blank line when mode is set + * to "never" + * @private + * @param {ASTNode} node `VariableDeclaration` node to test + * @returns {void} + */ + function checkForBlankLine(node) { + /* + * lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will + * sometimes be second-last if there is a semicolon on a different line. + */ + const lastToken = getLastToken(node), + /* + * If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken + * is the last token of the node. + */ + nextToken = + lastToken === sourceCode.getLastToken(node) + ? sourceCode.getTokenAfter(node) + : sourceCode.getLastToken(node), + nextLineNum = lastToken.loc.end.line + 1; + + // Ignore if there is no following statement + if (!nextToken) { + return; + } + + // Ignore if parent of node is a for variant + if (isForTypeSpecifier(node.parent.type)) { + return; + } + + // Ignore if parent of node is an export specifier + if (isExportSpecifier(node.parent.type)) { + return; + } + + /* + * Some coding styles use multiple `var` statements, so do nothing if + * the next token is a `var` statement. + */ + if (nextToken.type === "Keyword" && isVar(nextToken.value)) { + return; + } + + // Ignore if it is last statement in a block + if (isLastNode(node)) { + return; + } + + // Next statement is not a `var`... + const noNextLineToken = nextToken.loc.start.line > nextLineNum; + const hasNextLineComment = + typeof commentEndLine[nextLineNum] !== "undefined"; + + if (mode === "never" && noNextLineToken && !hasNextLineComment) { + context.report({ + node, + messageId: "unexpected", + fix(fixer) { + const linesBetween = sourceCode + .getText() + .slice(lastToken.range[1], nextToken.range[0]) + .split(astUtils.LINEBREAK_MATCHER); + + return fixer.replaceTextRange( + [lastToken.range[1], nextToken.range[0]], + `${linesBetween.slice(0, -1).join("")}\n${linesBetween.at(-1)}`, + ); + }, + }); + } + + // Token on the next line, or comment without blank line + if ( + mode === "always" && + (!noNextLineToken || + (hasNextLineComment && + !hasBlankLineAfterComment(nextToken, nextLineNum))) + ) { + context.report({ + node, + messageId: "expected", + fix(fixer) { + if ( + (noNextLineToken + ? getLastCommentLineOfBlock(nextLineNum) + : lastToken.loc.end.line) === + nextToken.loc.start.line + ) { + return fixer.insertTextBefore(nextToken, "\n\n"); + } + + return fixer.insertTextBeforeRange( + [ + nextToken.range[0] - nextToken.loc.start.column, + nextToken.range[1], + ], + "\n", + ); + }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclaration: checkForBlankLine, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/newline-before-return.js b/node_modules/eslint/lib/rules/newline-before-return.js new file mode 100644 index 00000000..8d972eef --- /dev/null +++ b/node_modules/eslint/lib/rules/newline-before-return.js @@ -0,0 +1,242 @@ +/** + * @fileoverview Rule to require newlines before `return` statement + * @author Kai Cataldo + * @deprecated in ESLint v4.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require an empty line before `return` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/newline-before-return", + }, + + fixable: "whitespace", + schema: [], + messages: { + expected: "Expected newline before return statement.", + }, + + deprecated: { + message: "The rule was replaced with a more general rule.", + url: "https://eslint.org/blog/2017/06/eslint-v4.0.0-released/", + deprecatedSince: "4.0.0", + availableUntil: null, + replacedBy: [ + { + message: "The new rule moved to a plugin.", + url: "https://eslint.org/docs/latest/rules/padding-line-between-statements#examples", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "padding-line-between-statements", + url: "https://eslint.style/rules/js/padding-line-between-statements", + }, + }, + ], + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tests whether node is preceded by supplied tokens + * @param {ASTNode} node node to check + * @param {Array} testTokens array of tokens to test against + * @returns {boolean} Whether or not the node is preceded by one of the supplied tokens + * @private + */ + function isPrecededByTokens(node, testTokens) { + const tokenBefore = sourceCode.getTokenBefore(node); + + return testTokens.includes(tokenBefore.value); + } + + /** + * Checks whether node is the first node after statement or in block + * @param {ASTNode} node node to check + * @returns {boolean} Whether or not the node is the first node after statement or in block + * @private + */ + function isFirstNode(node) { + const parentType = node.parent.type; + + if (node.parent.body) { + return Array.isArray(node.parent.body) + ? node.parent.body[0] === node + : node.parent.body === node; + } + + if (parentType === "IfStatement") { + return isPrecededByTokens(node, ["else", ")"]); + } + if (parentType === "DoWhileStatement") { + return isPrecededByTokens(node, ["do"]); + } + if (parentType === "SwitchCase") { + return isPrecededByTokens(node, [":"]); + } + return isPrecededByTokens(node, [")"]); + } + + /** + * Returns the number of lines of comments that precede the node + * @param {ASTNode} node node to check for overlapping comments + * @param {number} lineNumTokenBefore line number of previous token, to check for overlapping comments + * @returns {number} Number of lines of comments that precede the node + * @private + */ + function calcCommentLines(node, lineNumTokenBefore) { + const comments = sourceCode.getCommentsBefore(node); + let numLinesComments = 0; + + if (!comments.length) { + return numLinesComments; + } + + comments.forEach(comment => { + numLinesComments++; + + if (comment.type === "Block") { + numLinesComments += + comment.loc.end.line - comment.loc.start.line; + } + + // avoid counting lines with inline comments twice + if (comment.loc.start.line === lineNumTokenBefore) { + numLinesComments--; + } + + if (comment.loc.end.line === node.loc.start.line) { + numLinesComments--; + } + }); + + return numLinesComments; + } + + /** + * Returns the line number of the token before the node that is passed in as an argument + * @param {ASTNode} node The node to use as the start of the calculation + * @returns {number} Line number of the token before `node` + * @private + */ + function getLineNumberOfTokenBefore(node) { + const tokenBefore = sourceCode.getTokenBefore(node); + let lineNumTokenBefore; + + /** + * Global return (at the beginning of a script) is a special case. + * If there is no token before `return`, then we expect no line + * break before the return. Comments are allowed to occupy lines + * before the global return, just no blank lines. + * Setting lineNumTokenBefore to zero in that case results in the + * desired behavior. + */ + if (tokenBefore) { + lineNumTokenBefore = tokenBefore.loc.end.line; + } else { + lineNumTokenBefore = 0; // global return at beginning of script + } + + return lineNumTokenBefore; + } + + /** + * Checks whether node is preceded by a newline + * @param {ASTNode} node node to check + * @returns {boolean} Whether or not the node is preceded by a newline + * @private + */ + function hasNewlineBefore(node) { + const lineNumNode = node.loc.start.line; + const lineNumTokenBefore = getLineNumberOfTokenBefore(node); + const commentLines = calcCommentLines(node, lineNumTokenBefore); + + return lineNumNode - lineNumTokenBefore - commentLines > 1; + } + + /** + * Checks whether it is safe to apply a fix to a given return statement. + * + * The fix is not considered safe if the given return statement has leading comments, + * as we cannot safely determine if the newline should be added before or after the comments. + * For more information, see: https://github.com/eslint/eslint/issues/5958#issuecomment-222767211 + * @param {ASTNode} node The return statement node to check. + * @returns {boolean} `true` if it can fix the node. + * @private + */ + function canFix(node) { + const leadingComments = sourceCode.getCommentsBefore(node); + const lastLeadingComment = leadingComments.at(-1); + const tokenBefore = sourceCode.getTokenBefore(node); + + if (leadingComments.length === 0) { + return true; + } + + /* + * if the last leading comment ends in the same line as the previous token and + * does not share a line with the `return` node, we can consider it safe to fix. + * Example: + * function a() { + * var b; //comment + * return; + * } + */ + if ( + lastLeadingComment.loc.end.line === tokenBefore.loc.end.line && + lastLeadingComment.loc.end.line !== node.loc.start.line + ) { + return true; + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ReturnStatement(node) { + if (!isFirstNode(node) && !hasNewlineBefore(node)) { + context.report({ + node, + messageId: "expected", + fix(fixer) { + if (canFix(node)) { + const tokenBefore = + sourceCode.getTokenBefore(node); + const newlines = + node.loc.start.line === + tokenBefore.loc.end.line + ? "\n\n" + : "\n"; + + return fixer.insertTextBefore(node, newlines); + } + return null; + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/newline-per-chained-call.js b/node_modules/eslint/lib/rules/newline-per-chained-call.js new file mode 100644 index 00000000..a06384f4 --- /dev/null +++ b/node_modules/eslint/lib/rules/newline-per-chained-call.js @@ -0,0 +1,159 @@ +/** + * @fileoverview Rule to ensure newline per method call when chaining calls + * @author Rajendra Patil + * @author Burak Yigit Kaya + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "newline-per-chained-call", + url: "https://eslint.style/rules/js/newline-per-chained-call", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require a newline after each call in a method chain", + recommended: false, + url: "https://eslint.org/docs/latest/rules/newline-per-chained-call", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + ignoreChainWithDepth: { + type: "integer", + minimum: 1, + maximum: 10, + default: 2, + }, + }, + additionalProperties: false, + }, + ], + messages: { + expected: "Expected line break before `{{callee}}`.", + }, + }, + + create(context) { + const options = context.options[0] || {}, + ignoreChainWithDepth = options.ignoreChainWithDepth || 2; + + const sourceCode = context.sourceCode; + + /** + * Get the prefix of a given MemberExpression node. + * If the MemberExpression node is a computed value it returns a + * left bracket. If not it returns a period. + * @param {ASTNode} node A MemberExpression node to get + * @returns {string} The prefix of the node. + */ + function getPrefix(node) { + if (node.computed) { + if (node.optional) { + return "?.["; + } + return "["; + } + if (node.optional) { + return "?."; + } + return "."; + } + + /** + * Gets the property text of a given MemberExpression node. + * If the text is multiline, this returns only the first line. + * @param {ASTNode} node A MemberExpression node to get. + * @returns {string} The property text of the node. + */ + function getPropertyText(node) { + const prefix = getPrefix(node); + const lines = sourceCode + .getText(node.property) + .split(astUtils.LINEBREAK_MATCHER); + const suffix = node.computed && lines.length === 1 ? "]" : ""; + + return prefix + lines[0] + suffix; + } + + return { + "CallExpression:exit"(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type !== "MemberExpression") { + return; + } + + let parent = astUtils.skipChainExpression(callee.object); + let depth = 1; + + while (parent && parent.callee) { + depth += 1; + parent = astUtils.skipChainExpression( + astUtils.skipChainExpression(parent.callee).object, + ); + } + + if ( + depth > ignoreChainWithDepth && + astUtils.isTokenOnSameLine(callee.object, callee.property) + ) { + const firstTokenAfterObject = sourceCode.getTokenAfter( + callee.object, + astUtils.isNotClosingParenToken, + ); + + context.report({ + node: callee.property, + loc: { + start: firstTokenAfterObject.loc.start, + end: callee.loc.end, + }, + messageId: "expected", + data: { + callee: getPropertyText(callee), + }, + fix(fixer) { + return fixer.insertTextBefore( + firstTokenAfterObject, + "\n", + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-alert.js b/node_modules/eslint/lib/rules/no-alert.js new file mode 100644 index 00000000..c77cd1c6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-alert.js @@ -0,0 +1,149 @@ +/** + * @fileoverview Rule to flag use of alert, confirm, prompt + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + getStaticPropertyName: getPropertyName, + getVariableByName, + skipChainExpression, +} = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks if the given name is a prohibited identifier. + * @param {string} name The name to check + * @returns {boolean} Whether or not the name is prohibited. + */ +function isProhibitedIdentifier(name) { + return /^(alert|confirm|prompt)$/u.test(name); +} + +/** + * Finds the eslint-scope reference in the given scope. + * @param {Object} scope The scope to search. + * @param {ASTNode} node The identifier node. + * @returns {Reference|null} Returns the found reference or null if none were found. + */ +function findReference(scope, node) { + const references = scope.references.filter( + reference => + reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1], + ); + + if (references.length === 1) { + return references[0]; + } + return null; +} + +/** + * Checks if the given identifier node is shadowed in the given scope. + * @param {Object} scope The current scope. + * @param {string} node The identifier node to check + * @returns {boolean} Whether or not the name is shadowed. + */ +function isShadowed(scope, node) { + const reference = findReference(scope, node); + + return ( + reference && reference.resolved && reference.resolved.defs.length > 0 + ); +} + +/** + * Checks if the given identifier node is a ThisExpression in the global scope or the global window property. + * @param {Object} scope The current scope. + * @param {string} node The identifier node to check + * @returns {boolean} Whether or not the node is a reference to the global object. + */ +function isGlobalThisReferenceOrGlobalWindow(scope, node) { + if (scope.type === "global" && node.type === "ThisExpression") { + return true; + } + if ( + node.type === "Identifier" && + (node.name === "window" || + (node.name === "globalThis" && + getVariableByName(scope, "globalThis"))) + ) { + return !isShadowed(scope, node); + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `alert`, `confirm`, and `prompt`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-alert", + }, + + schema: [], + + messages: { + unexpected: "Unexpected {{name}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + const callee = skipChainExpression(node.callee), + currentScope = sourceCode.getScope(node); + + // without window. + if (callee.type === "Identifier") { + const name = callee.name; + + if ( + !isShadowed(currentScope, callee) && + isProhibitedIdentifier(callee.name) + ) { + context.report({ + node, + messageId: "unexpected", + data: { name }, + }); + } + } else if ( + callee.type === "MemberExpression" && + isGlobalThisReferenceOrGlobalWindow( + currentScope, + callee.object, + ) + ) { + const name = getPropertyName(callee); + + if (isProhibitedIdentifier(name)) { + context.report({ + node, + messageId: "unexpected", + data: { name }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-array-constructor.js b/node_modules/eslint/lib/rules/no-array-constructor.js new file mode 100644 index 00000000..46e8f6b7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-array-constructor.js @@ -0,0 +1,195 @@ +/** + * @fileoverview Disallow construction of dense arrays using the Array constructor + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + getVariableByName, + isClosingParenToken, + isOpeningParenToken, + isStartOfExpressionStatement, + needsPrecedingSemicolon, +} = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Disallow `Array` constructors", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-array-constructor", + }, + + fixable: "code", + + hasSuggestions: true, + + schema: [], + + messages: { + preferLiteral: "The array literal notation [] is preferable.", + useLiteral: "Replace with an array literal.", + useLiteralAfterSemicolon: + "Replace with an array literal, add preceding semicolon.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks if there are comments in Array constructor expressions. + * @param {ASTNode} node A CallExpression or NewExpression node. + * @returns {boolean} True if there are comments, false otherwise. + */ + function hasCommentsInArrayConstructor(node) { + const firstToken = sourceCode.getFirstToken(node); + const lastToken = sourceCode.getLastToken(node); + + let lastRelevantToken = sourceCode.getLastToken(node.callee); + + while ( + lastRelevantToken !== lastToken && + !isOpeningParenToken(lastRelevantToken) + ) { + lastRelevantToken = sourceCode.getTokenAfter(lastRelevantToken); + } + + return sourceCode.commentsExistBetween( + firstToken, + lastRelevantToken, + ); + } + + /** + * Gets the text between the calling parentheses of a CallExpression or NewExpression. + * @param {ASTNode} node A CallExpression or NewExpression node. + * @returns {string} The text between the calling parentheses, or an empty string if there are none. + */ + function getArgumentsText(node) { + const lastToken = sourceCode.getLastToken(node); + + if (!isClosingParenToken(lastToken)) { + return ""; + } + + let firstToken = node.callee; + + do { + firstToken = sourceCode.getTokenAfter(firstToken); + if (!firstToken || firstToken === lastToken) { + return ""; + } + } while (!isOpeningParenToken(firstToken)); + + return sourceCode.text.slice( + firstToken.range[1], + lastToken.range[0], + ); + } + + /** + * Disallow construction of dense arrays using the Array constructor + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function check(node) { + if ( + node.callee.type !== "Identifier" || + node.callee.name !== "Array" || + node.typeArguments || + (node.arguments.length === 1 && + node.arguments[0].type !== "SpreadElement") + ) { + return; + } + + const variable = getVariableByName( + sourceCode.getScope(node), + "Array", + ); + + /* + * Check if `Array` is a predefined global variable: predefined globals have no declarations, + * meaning that the `identifiers` list of the variable object is empty. + */ + if (variable && variable.identifiers.length === 0) { + const argsText = getArgumentsText(node); + let fixText; + let messageId; + + const nonSpreadCount = node.arguments.reduce( + (count, arg) => + arg.type !== "SpreadElement" ? count + 1 : count, + 0, + ); + + const shouldSuggest = + node.optional || + (node.arguments.length > 0 && nonSpreadCount < 2) || + hasCommentsInArrayConstructor(node); + + /* + * Check if the suggested change should include a preceding semicolon or not. + * Due to JavaScript's ASI rules, a missing semicolon may be inserted automatically + * before an expression like `Array()` or `new Array()`, but not when the expression + * is changed into an array literal like `[]`. + */ + if ( + isStartOfExpressionStatement(node) && + needsPrecedingSemicolon(sourceCode, node) + ) { + fixText = `;[${argsText}]`; + messageId = "useLiteralAfterSemicolon"; + } else { + fixText = `[${argsText}]`; + messageId = "useLiteral"; + } + + context.report({ + node, + messageId: "preferLiteral", + fix(fixer) { + if (shouldSuggest) { + return null; + } + + return fixer.replaceText(node, fixText); + }, + suggest: [ + { + messageId, + fix(fixer) { + if (shouldSuggest) { + return fixer.replaceText(node, fixText); + } + + return null; + }, + }, + ], + }); + } + } + + return { + CallExpression: check, + NewExpression: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-async-promise-executor.js b/node_modules/eslint/lib/rules/no-async-promise-executor.js new file mode 100644 index 00000000..22edd48f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-async-promise-executor.js @@ -0,0 +1,45 @@ +/** + * @fileoverview disallow using an async function as a Promise executor + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow using an async function as a Promise executor", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-async-promise-executor", + }, + + fixable: null, + schema: [], + messages: { + async: "Promise executor functions should not be async.", + }, + }, + + create(context) { + return { + "NewExpression[callee.name='Promise'][arguments.0.async=true]"( + node, + ) { + context.report({ + node: context.sourceCode.getFirstToken( + node.arguments[0], + token => token.value === "async", + ), + messageId: "async", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-await-in-loop.js b/node_modules/eslint/lib/rules/no-await-in-loop.js new file mode 100644 index 00000000..205e5bcf --- /dev/null +++ b/node_modules/eslint/lib/rules/no-await-in-loop.js @@ -0,0 +1,104 @@ +/** + * @fileoverview Rule to disallow uses of await inside of loops. + * @author Nat Mote (nmote) + */ +"use strict"; + +/** + * Check whether it should stop traversing ancestors at the given node. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if it should stop traversing. + */ +function isBoundary(node) { + const t = node.type; + + return ( + t === "FunctionDeclaration" || + t === "FunctionExpression" || + t === "ArrowFunctionExpression" || + /* + * Don't report the await expressions on for-await-of loop since it's + * asynchronous iteration intentionally. + */ + (t === "ForOfStatement" && node.await === true) + ); +} + +/** + * Check whether the given node is in loop. + * @param {ASTNode} node A node to check. + * @param {ASTNode} parent A parent node to check. + * @returns {boolean} `true` if the node is in loop. + */ +function isLooped(node, parent) { + switch (parent.type) { + case "ForStatement": + return ( + node === parent.test || + node === parent.update || + node === parent.body + ); + + case "ForOfStatement": + case "ForInStatement": + return node === parent.body; + + case "WhileStatement": + case "DoWhileStatement": + return node === parent.test || node === parent.body; + + default: + return false; + } +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow `await` inside of loops", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-await-in-loop", + }, + + schema: [], + + messages: { + unexpectedAwait: "Unexpected `await` inside a loop.", + }, + }, + create(context) { + /** + * Validate an await expression. + * @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate. + * @returns {void} + */ + function validate(awaitNode) { + if (awaitNode.type === "ForOfStatement" && !awaitNode.await) { + return; + } + + let node = awaitNode; + let parent = node.parent; + + while (parent && !isBoundary(parent)) { + if (isLooped(node, parent)) { + context.report({ + node: awaitNode, + messageId: "unexpectedAwait", + }); + return; + } + node = parent; + parent = parent.parent; + } + } + + return { + AwaitExpression: validate, + ForOfStatement: validate, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-bitwise.js b/node_modules/eslint/lib/rules/no-bitwise.js new file mode 100644 index 00000000..10149ed6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-bitwise.js @@ -0,0 +1,145 @@ +/** + * @fileoverview Rule to flag bitwise identifiers + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* + * + * Set of bitwise operators. + * + */ +const BITWISE_OPERATORS = [ + "^", + "|", + "&", + "<<", + ">>", + ">>>", + "^=", + "|=", + "&=", + "<<=", + ">>=", + ">>>=", + "~", +]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allow: [], + int32Hint: false, + }, + ], + + docs: { + description: "Disallow bitwise operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-bitwise", + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { + enum: BITWISE_OPERATORS, + }, + uniqueItems: true, + }, + int32Hint: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Unexpected use of '{{operator}}'.", + }, + }, + + create(context) { + const [{ allow: allowed, int32Hint }] = context.options; + + /** + * Reports an unexpected use of a bitwise operator. + * @param {ASTNode} node Node which contains the bitwise operator. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "unexpected", + data: { operator: node.operator }, + }); + } + + /** + * Checks if the given node has a bitwise operator. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node has a bitwise operator. + */ + function hasBitwiseOperator(node) { + return BITWISE_OPERATORS.includes(node.operator); + } + + /** + * Checks if exceptions were provided, e.g. `{ allow: ['~', '|'] }`. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node has a bitwise operator. + */ + function allowedOperator(node) { + return allowed.includes(node.operator); + } + + /** + * Checks if the given bitwise operator is used for integer typecasting, i.e. "|0" + * @param {ASTNode} node The node to check. + * @returns {boolean} whether the node is used in integer typecasting. + */ + function isInt32Hint(node) { + return ( + int32Hint && + node.operator === "|" && + node.right && + node.right.type === "Literal" && + node.right.value === 0 + ); + } + + /** + * Report if the given node contains a bitwise operator. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNodeForBitwiseOperator(node) { + if ( + hasBitwiseOperator(node) && + !allowedOperator(node) && + !isInt32Hint(node) + ) { + report(node); + } + } + + return { + AssignmentExpression: checkNodeForBitwiseOperator, + BinaryExpression: checkNodeForBitwiseOperator, + UnaryExpression: checkNodeForBitwiseOperator, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-buffer-constructor.js b/node_modules/eslint/lib/rules/no-buffer-constructor.js new file mode 100644 index 00000000..3fa6632f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-buffer-constructor.js @@ -0,0 +1,74 @@ +/** + * @fileoverview disallow use of the Buffer() constructor + * @author Teddy Katz + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-deprecated-api", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-deprecated-api.md", + }, + }, + ], + }, + + type: "problem", + + docs: { + description: "Disallow use of the `Buffer()` constructor", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-buffer-constructor", + }, + + schema: [], + + messages: { + deprecated: + "{{expr}} is deprecated. Use Buffer.from(), Buffer.alloc(), or Buffer.allocUnsafe() instead.", + }, + }, + + create(context) { + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + "CallExpression[callee.name='Buffer'], NewExpression[callee.name='Buffer']"( + node, + ) { + context.report({ + node, + messageId: "deprecated", + data: { + expr: + node.type === "CallExpression" + ? "Buffer()" + : "new Buffer()", + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-caller.js b/node_modules/eslint/lib/rules/no-caller.js new file mode 100644 index 00000000..50790ff0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-caller.js @@ -0,0 +1,52 @@ +/** + * @fileoverview Rule to flag use of arguments.callee and arguments.caller. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow the use of `arguments.caller` or `arguments.callee`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-caller", + }, + + schema: [], + + messages: { + unexpected: "Avoid arguments.{{prop}}.", + }, + }, + + create(context) { + return { + MemberExpression(node) { + const objectName = node.object.name, + propertyName = node.property.name; + + if ( + objectName === "arguments" && + !node.computed && + propertyName && + propertyName.match(/^calle[er]$/u) + ) { + context.report({ + node, + messageId: "unexpected", + data: { prop: propertyName }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-case-declarations.js b/node_modules/eslint/lib/rules/no-case-declarations.js new file mode 100644 index 00000000..168594aa --- /dev/null +++ b/node_modules/eslint/lib/rules/no-case-declarations.js @@ -0,0 +1,80 @@ +/** + * @fileoverview Rule to flag use of an lexical declarations inside a case clause + * @author Erik Arvidsson + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow lexical declarations in case clauses", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-case-declarations", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + addBrackets: "Add {} brackets around the case block.", + unexpected: "Unexpected lexical declaration in case block.", + }, + }, + + create(context) { + /** + * Checks whether or not a node is a lexical declaration. + * @param {ASTNode} node A direct child statement of a switch case. + * @returns {boolean} Whether or not the node is a lexical declaration. + */ + function isLexicalDeclaration(node) { + switch (node.type) { + case "FunctionDeclaration": + case "ClassDeclaration": + return true; + case "VariableDeclaration": + return node.kind !== "var"; + default: + return false; + } + } + + return { + SwitchCase(node) { + for (let i = 0; i < node.consequent.length; i++) { + const statement = node.consequent[i]; + + if (isLexicalDeclaration(statement)) { + context.report({ + node: statement, + messageId: "unexpected", + suggest: [ + { + messageId: "addBrackets", + fix: fixer => [ + fixer.insertTextBefore( + node.consequent[0], + "{ ", + ), + fixer.insertTextAfter( + node.consequent.at(-1), + " }", + ), + ], + }, + ], + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-catch-shadow.js b/node_modules/eslint/lib/rules/no-catch-shadow.js new file mode 100644 index 00000000..e4c0718e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-catch-shadow.js @@ -0,0 +1,96 @@ +/** + * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier + * @author Ian Christian Myers + * @deprecated in ESLint v5.1.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `catch` clause parameters from shadowing variables in the outer scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-catch-shadow", + }, + + deprecated: { + message: "This rule was renamed.", + url: "https://eslint.org/blog/2018/07/eslint-v5.1.0-released/", + deprecatedSince: "5.1.0", + availableUntil: null, + replacedBy: [ + { + rule: { + name: "no-shadow", + url: "https://eslint.org/docs/rules/no-shadow", + }, + }, + ], + }, + schema: [], + + messages: { + mutable: + "Value of '{{name}}' may be overwritten in IE 8 and earlier.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the parameters are been shadowed + * @param {Object} scope current scope + * @param {string} name parameter name + * @returns {boolean} True is its been shadowed + */ + function paramIsShadowing(scope, name) { + return astUtils.getVariableByName(scope, name) !== null; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "CatchClause[param!=null]"(node) { + let scope = sourceCode.getScope(node); + + /* + * When ecmaVersion >= 6, CatchClause creates its own scope + * so start from one upper scope to exclude the current node + */ + if (scope.block === node) { + scope = scope.upper; + } + + if (paramIsShadowing(scope, node.param.name)) { + context.report({ + node, + messageId: "mutable", + data: { name: node.param.name }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-class-assign.js b/node_modules/eslint/lib/rules/no-class-assign.js new file mode 100644 index 00000000..64976959 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-class-assign.js @@ -0,0 +1,66 @@ +/** + * @fileoverview A rule to disallow modifying variables of class declarations + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning class members", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-class-assign", + }, + + schema: [], + + messages: { + class: "'{{name}}' is a class.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + astUtils + .getModifyingReferences(variable.references) + .forEach(reference => { + context.report({ + node: reference.identifier, + messageId: "class", + data: { name: reference.identifier.name }, + }); + }); + } + + /** + * Finds and reports references that are non initializer and writable. + * @param {ASTNode} node A ClassDeclaration/ClassExpression node to check. + * @returns {void} + */ + function checkForClass(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + + return { + ClassDeclaration: checkForClass, + ClassExpression: checkForClass, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-compare-neg-zero.js b/node_modules/eslint/lib/rules/no-compare-neg-zero.js new file mode 100644 index 00000000..a5683164 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-compare-neg-zero.js @@ -0,0 +1,74 @@ +/** + * @fileoverview The rule should warn against code that tries to compare against -0. + * @author Aladdin-ADD + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow comparing against `-0`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-compare-neg-zero", + }, + + fixable: null, + schema: [], + + messages: { + unexpected: + "Do not use the '{{operator}}' operator to compare against -0.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks a given node is -0 + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is -0. + */ + function isNegZero(node) { + return ( + node.type === "UnaryExpression" && + node.operator === "-" && + node.argument.type === "Literal" && + node.argument.value === 0 + ); + } + const OPERATORS_TO_CHECK = new Set([ + ">", + ">=", + "<", + "<=", + "==", + "===", + "!=", + "!==", + ]); + + return { + BinaryExpression(node) { + if (OPERATORS_TO_CHECK.has(node.operator)) { + if (isNegZero(node.left) || isNegZero(node.right)) { + context.report({ + node, + messageId: "unexpected", + data: { operator: node.operator }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-cond-assign.js b/node_modules/eslint/lib/rules/no-cond-assign.js new file mode 100644 index 00000000..a686e690 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-cond-assign.js @@ -0,0 +1,175 @@ +/** + * @fileoverview Rule to flag assignment in a conditional statement's test expression + * @author Stephen Murray + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TEST_CONDITION_PARENT_TYPES = new Set([ + "IfStatement", + "WhileStatement", + "DoWhileStatement", + "ForStatement", + "ConditionalExpression", +]); + +const NODE_DESCRIPTIONS = { + DoWhileStatement: "a 'do...while' statement", + ForStatement: "a 'for' statement", + IfStatement: "an 'if' statement", + WhileStatement: "a 'while' statement", +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: ["except-parens"], + + docs: { + description: + "Disallow assignment operators in conditional expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-cond-assign", + }, + + schema: [ + { + enum: ["except-parens", "always"], + }, + ], + + messages: { + unexpected: "Unexpected assignment within {{type}}.", + + // must match JSHint's error message + missing: + "Expected a conditional expression and instead saw an assignment.", + }, + }, + + create(context) { + const [prohibitAssign] = context.options; + const sourceCode = context.sourceCode; + + /** + * Check whether an AST node is the test expression for a conditional statement. + * @param {!Object} node The node to test. + * @returns {boolean} `true` if the node is the text expression for a conditional statement; otherwise, `false`. + */ + function isConditionalTestExpression(node) { + return ( + node.parent && + TEST_CONDITION_PARENT_TYPES.has(node.parent.type) && + node === node.parent.test + ); + } + + /** + * Given an AST node, perform a bottom-up search for the first ancestor that represents a conditional statement. + * @param {!Object} node The node to use at the start of the search. + * @returns {?Object} The closest ancestor node that represents a conditional statement. + */ + function findConditionalAncestor(node) { + let currentAncestor = node; + + do { + if (isConditionalTestExpression(currentAncestor)) { + return currentAncestor.parent; + } + } while ( + (currentAncestor = currentAncestor.parent) && + !astUtils.isFunction(currentAncestor) + ); + + return null; + } + + /** + * Check whether the code represented by an AST node is enclosed in two sets of parentheses. + * @param {!Object} node The node to test. + * @returns {boolean} `true` if the code is enclosed in two sets of parentheses; otherwise, `false`. + */ + function isParenthesisedTwice(node) { + const previousToken = sourceCode.getTokenBefore(node, 1), + nextToken = sourceCode.getTokenAfter(node, 1); + + return ( + astUtils.isParenthesised(sourceCode, node) && + previousToken && + astUtils.isOpeningParenToken(previousToken) && + previousToken.range[1] <= node.range[0] && + astUtils.isClosingParenToken(nextToken) && + nextToken.range[0] >= node.range[1] + ); + } + + /** + * Check a conditional statement's test expression for top-level assignments that are not enclosed in parentheses. + * @param {!Object} node The node for the conditional statement. + * @returns {void} + */ + function testForAssign(node) { + if ( + node.test && + node.test.type === "AssignmentExpression" && + (node.type === "ForStatement" + ? !astUtils.isParenthesised(sourceCode, node.test) + : !isParenthesisedTwice(node.test)) + ) { + context.report({ + node: node.test, + messageId: "missing", + }); + } + } + + /** + * Check whether an assignment expression is descended from a conditional statement's test expression. + * @param {!Object} node The node for the assignment expression. + * @returns {void} + */ + function testForConditionalAncestor(node) { + const ancestor = findConditionalAncestor(node); + + if (ancestor) { + context.report({ + node, + messageId: "unexpected", + data: { + type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type, + }, + }); + } + } + + if (prohibitAssign === "always") { + return { + AssignmentExpression: testForConditionalAncestor, + }; + } + + return { + DoWhileStatement: testForAssign, + ForStatement: testForAssign, + IfStatement: testForAssign, + WhileStatement: testForAssign, + ConditionalExpression: testForAssign, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-confusing-arrow.js b/node_modules/eslint/lib/rules/no-confusing-arrow.js new file mode 100644 index 00000000..9d7244db --- /dev/null +++ b/node_modules/eslint/lib/rules/no-confusing-arrow.js @@ -0,0 +1,127 @@ +/** + * @fileoverview A rule to warn against using arrow functions when they could be + * confused with comparisons + * @author Jxck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils.js"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a node is a conditional expression. + * @param {ASTNode} node node to test + * @returns {boolean} `true` if the node is a conditional expression. + */ +function isConditional(node) { + return node && node.type === "ConditionalExpression"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-confusing-arrow", + url: "https://eslint.style/rules/js/no-confusing-arrow", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: + "Disallow arrow functions where they could be confused with comparisons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-confusing-arrow", + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + allowParens: { type: "boolean", default: true }, + onlyOneSimpleParam: { type: "boolean", default: false }, + }, + additionalProperties: false, + }, + ], + + messages: { + confusing: + "Arrow function used ambiguously with a conditional expression.", + }, + }, + + create(context) { + const config = context.options[0] || {}; + const allowParens = config.allowParens || config.allowParens === void 0; + const onlyOneSimpleParam = config.onlyOneSimpleParam; + const sourceCode = context.sourceCode; + + /** + * Reports if an arrow function contains an ambiguous conditional. + * @param {ASTNode} node A node to check and report. + * @returns {void} + */ + function checkArrowFunc(node) { + const body = node.body; + + if ( + isConditional(body) && + !(allowParens && astUtils.isParenthesised(sourceCode, body)) && + !( + onlyOneSimpleParam && + !( + node.params.length === 1 && + node.params[0].type === "Identifier" + ) + ) + ) { + context.report({ + node, + messageId: "confusing", + fix(fixer) { + // if `allowParens` is not set to true don't bother wrapping in parens + return ( + allowParens && + fixer.replaceText( + node.body, + `(${sourceCode.getText(node.body)})`, + ) + ); + }, + }); + } + } + + return { + ArrowFunctionExpression: checkArrowFunc, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-console.js b/node_modules/eslint/lib/rules/no-console.js new file mode 100644 index 00000000..1d734442 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-console.js @@ -0,0 +1,221 @@ +/** + * @fileoverview Rule to flag use of console object + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{}], + + docs: { + description: "Disallow the use of `console`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-console", + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + hasSuggestions: true, + + messages: { + unexpected: "Unexpected console statement.", + limited: + "Unexpected console statement. Only these console methods are allowed: {{ allowed }}.", + removeConsole: "Remove the console.{{ propertyName }}().", + removeMethodCall: "Remove the console method call.", + }, + }, + + create(context) { + const [{ allow: allowed = [] }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Checks whether the given reference is 'console' or not. + * @param {eslint-scope.Reference} reference The reference to check. + * @returns {boolean} `true` if the reference is 'console'. + */ + function isConsole(reference) { + const id = reference.identifier; + + return id && id.name === "console"; + } + + /** + * Checks whether the property name of the given MemberExpression node + * is allowed by options or not. + * @param {ASTNode} node The MemberExpression node to check. + * @returns {boolean} `true` if the property name of the node is allowed. + */ + function isAllowed(node) { + const propertyName = astUtils.getStaticPropertyName(node); + + return propertyName && allowed.includes(propertyName); + } + + /** + * Checks whether the given reference is a member access which is not + * allowed by options or not. + * @param {eslint-scope.Reference} reference The reference to check. + * @returns {boolean} `true` if the reference is a member access which + * is not allowed by options. + */ + function isMemberAccessExceptAllowed(reference) { + const node = reference.identifier; + const parent = node.parent; + + return ( + parent.type === "MemberExpression" && + parent.object === node && + !isAllowed(parent) + ); + } + + /** + * Checks if removing the ExpressionStatement node will cause ASI to + * break. + * eg. + * foo() + * console.log(); + * [1, 2, 3].forEach(a => doSomething(a)) + * + * Removing the console.log(); statement should leave two statements, but + * here the two statements will become one because [ causes continuation after + * foo(). + * @param {ASTNode} node The ExpressionStatement node to check. + * @returns {boolean} `true` if ASI will break after removing the ExpressionStatement + * node. + */ + function maybeAsiHazard(node) { + const SAFE_TOKENS_BEFORE = /^[:;{]$/u; // One of :;{ + const UNSAFE_CHARS_AFTER = /^[-[(/+`]/u; // One of [(/+-` + + const tokenBefore = sourceCode.getTokenBefore(node); + const tokenAfter = sourceCode.getTokenAfter(node); + + return ( + Boolean(tokenAfter) && + UNSAFE_CHARS_AFTER.test(tokenAfter.value) && + tokenAfter.value !== "++" && + tokenAfter.value !== "--" && + Boolean(tokenBefore) && + !SAFE_TOKENS_BEFORE.test(tokenBefore.value) + ); + } + + /** + * Checks if the MemberExpression node's parent.parent.parent is a + * Program, BlockStatement, StaticBlock, or SwitchCase node. This check + * is necessary to avoid providing a suggestion that might cause a syntax error. + * + * eg. if (a) console.log(b), removing console.log() here will lead to a + * syntax error. + * if (a) { console.log(b) }, removing console.log() here is acceptable. + * + * Additionally, it checks if the callee of the CallExpression node is + * the node itself. + * + * eg. foo(console.log), cannot provide a suggestion here. + * @param {ASTNode} node The MemberExpression node to check. + * @returns {boolean} `true` if a suggestion can be provided for a node. + */ + function canProvideSuggestions(node) { + return ( + node.parent.type === "CallExpression" && + node.parent.callee === node && + node.parent.parent.type === "ExpressionStatement" && + astUtils.STATEMENT_LIST_PARENTS.has( + node.parent.parent.parent.type, + ) && + !maybeAsiHazard(node.parent.parent) + ); + } + + /** + * Reports the given reference as a violation. + * @param {eslint-scope.Reference} reference The reference to report. + * @returns {void} + */ + function report(reference) { + const node = reference.identifier.parent; + + const suggest = []; + + if (canProvideSuggestions(node)) { + const suggestion = { + fix(fixer) { + return fixer.remove(node.parent.parent); + }, + }; + + if (node.computed) { + suggestion.messageId = "removeMethodCall"; + } else { + suggestion.messageId = "removeConsole"; + suggestion.data = { propertyName: node.property.name }; + } + suggest.push(suggestion); + } + context.report({ + node, + loc: node.loc, + messageId: allowed.length ? "limited" : "unexpected", + data: { allowed: allowed.join(", ") }, + suggest, + }); + } + + return { + "Program:exit"(node) { + const scope = sourceCode.getScope(node); + const consoleVar = astUtils.getVariableByName(scope, "console"); + const shadowed = consoleVar && consoleVar.defs.length > 0; + + /* + * 'scope.through' includes all references to undefined + * variables. If the variable 'console' is not defined, it uses + * 'scope.through'. + */ + const references = consoleVar + ? consoleVar.references + : scope.through.filter(isConsole); + + if (!shadowed) { + references + .filter(isMemberAccessExceptAllowed) + .forEach(report); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-const-assign.js b/node_modules/eslint/lib/rules/no-const-assign.js new file mode 100644 index 00000000..2f24a504 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-const-assign.js @@ -0,0 +1,62 @@ +/** + * @fileoverview A rule to disallow modifying variables that are declared using `const` + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning `const` variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-const-assign", + }, + + schema: [], + + messages: { + const: "'{{name}}' is constant.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + astUtils + .getModifyingReferences(variable.references) + .forEach(reference => { + context.report({ + node: reference.identifier, + messageId: "const", + data: { name: reference.identifier.name }, + }); + }); + } + + return { + VariableDeclaration(node) { + if (node.kind === "const") { + sourceCode + .getDeclaredVariables(node) + .forEach(checkVariable); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-constant-binary-expression.js b/node_modules/eslint/lib/rules/no-constant-binary-expression.js new file mode 100644 index 00000000..e3606311 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-constant-binary-expression.js @@ -0,0 +1,603 @@ +/** + * @fileoverview Rule to flag constant comparisons and logical expressions that always/never short circuit + * @author Jordan Eldredge + */ + +"use strict"; + +const { + isNullLiteral, + isConstant, + isReferenceToGlobalVariable, + isLogicalAssignmentOperator, + ECMASCRIPT_GLOBALS, +} = require("./utils/ast-utils"); + +const NUMERIC_OR_STRING_BINARY_OPERATORS = new Set([ + "+", + "-", + "*", + "/", + "%", + "|", + "^", + "&", + "**", + "<<", + ">>", + ">>>", +]); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a node is `null` or `undefined`. Similar to the one + * found in ast-utils.js, but this one correctly handles the edge case that + * `undefined` has been redefined. + * @param {Scope} scope Scope in which the expression was found. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `null` or `undefined`. + * @public + */ +function isNullOrUndefined(scope, node) { + return ( + isNullLiteral(node) || + (node.type === "Identifier" && + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node)) || + (node.type === "UnaryExpression" && node.operator === "void") + ); +} + +/** + * Test if an AST node has a statically knowable constant nullishness. Meaning, + * it will always resolve to a constant value of either: `null`, `undefined` + * or not `null` _or_ `undefined`. An expression that can vary between those + * three states at runtime would return `false`. + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The AST node being tested. + * @param {boolean} nonNullish if `true` then nullish values are not considered constant. + * @returns {boolean} Does `node` have constant nullishness? + */ +function hasConstantNullishness(scope, node, nonNullish) { + if (nonNullish && isNullOrUndefined(scope, node)) { + return false; + } + + switch (node.type) { + case "ObjectExpression": // Objects are never nullish + case "ArrayExpression": // Arrays are never nullish + case "ArrowFunctionExpression": // Functions never nullish + case "FunctionExpression": // Functions are never nullish + case "ClassExpression": // Classes are never nullish + case "NewExpression": // Objects are never nullish + case "Literal": // Nullish, or non-nullish, literals never change + case "TemplateLiteral": // A string is never nullish + case "UpdateExpression": // Numbers are never nullish + case "BinaryExpression": // Numbers, strings, or booleans are never nullish + return true; + case "CallExpression": { + if (node.callee.type !== "Identifier") { + return false; + } + const functionName = node.callee.name; + + return ( + (functionName === "Boolean" || + functionName === "String" || + functionName === "Number") && + isReferenceToGlobalVariable(scope, node.callee) + ); + } + case "LogicalExpression": { + return ( + node.operator === "??" && + hasConstantNullishness(scope, node.right, true) + ); + } + case "AssignmentExpression": + if (node.operator === "=") { + return hasConstantNullishness(scope, node.right, nonNullish); + } + + /* + * Handling short-circuiting assignment operators would require + * walking the scope. We won't attempt that (for now...) / + */ + if (isLogicalAssignmentOperator(node.operator)) { + return false; + } + + /* + * The remaining assignment expressions all result in a numeric or + * string (non-nullish) value: + * "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=" + */ + + return true; + case "UnaryExpression": + /* + * "void" Always returns `undefined` + * "typeof" All types are strings, and thus non-nullish + * "!" Boolean is never nullish + * "delete" Returns a boolean, which is never nullish + * Math operators always return numbers or strings, neither of which + * are non-nullish "+", "-", "~" + */ + + return true; + case "SequenceExpression": { + const last = node.expressions.at(-1); + + return hasConstantNullishness(scope, last, nonNullish); + } + case "Identifier": + return ( + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node) + ); + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Test if an AST node is a boolean value that never changes. Specifically we + * test for: + * 1. Literal booleans (`true` or `false`) + * 2. Unary `!` expressions with a constant value + * 3. Constant booleans created via the `Boolean` global function + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The node to test + * @returns {boolean} Is `node` guaranteed to be a boolean? + */ +function isStaticBoolean(scope, node) { + switch (node.type) { + case "Literal": + return typeof node.value === "boolean"; + case "CallExpression": + return ( + node.callee.type === "Identifier" && + node.callee.name === "Boolean" && + isReferenceToGlobalVariable(scope, node.callee) && + (node.arguments.length === 0 || + isConstant(scope, node.arguments[0], true)) + ); + case "UnaryExpression": + return ( + node.operator === "!" && isConstant(scope, node.argument, true) + ); + default: + return false; + } +} + +/** + * Test if an AST node will always give the same result when compared to a + * boolean value. Note that comparison to boolean values is different than + * truthiness. + * https://262.ecma-international.org/5.1/#sec-11.9.3 + * + * JavaScript `==` operator works by converting the boolean to `1` (true) or + * `+0` (false) and then checks the values `==` equality to that number. + * @param {Scope} scope The scope in which node was found. + * @param {ASTNode} node The node to test. + * @returns {boolean} Will `node` always coerce to the same boolean value? + */ +function hasConstantLooseBooleanComparison(scope, node) { + switch (node.type) { + case "ObjectExpression": + case "ClassExpression": + /** + * In theory objects like: + * + * `{toString: () => a}` + * `{valueOf: () => a}` + * + * Or a classes like: + * + * `class { static toString() { return a } }` + * `class { static valueOf() { return a } }` + * + * Are not constant verifiably when `inBooleanPosition` is + * false, but it's an edge case we've opted not to handle. + */ + return true; + case "ArrayExpression": { + const nonSpreadElements = node.elements.filter( + e => + // Elements can be `null` in sparse arrays: `[,,]`; + e !== null && e.type !== "SpreadElement", + ); + + /* + * Possible future direction if needed: We could check if the + * single value would result in variable boolean comparison. + * For now we will err on the side of caution since `[x]` could + * evaluate to `[0]` or `[1]`. + */ + return node.elements.length === 0 || nonSpreadElements.length > 1; + } + case "ArrowFunctionExpression": + case "FunctionExpression": + return true; + case "UnaryExpression": + if ( + node.operator === "void" || // Always returns `undefined` + node.operator === "typeof" // All `typeof` strings, when coerced to number, are not 0 or 1. + ) { + return true; + } + if (node.operator === "!") { + return isConstant(scope, node.argument, true); + } + + /* + * We won't try to reason about +, -, ~, or delete + * In theory, for the mathematical operators, we could look at the + * argument and try to determine if it coerces to a constant numeric + * value. + */ + return false; + case "NewExpression": // Objects might have custom `.valueOf` or `.toString`. + return false; + case "CallExpression": { + if ( + node.callee.type === "Identifier" && + node.callee.name === "Boolean" && + isReferenceToGlobalVariable(scope, node.callee) + ) { + return ( + node.arguments.length === 0 || + isConstant(scope, node.arguments[0], true) + ); + } + return false; + } + case "Literal": // True or false, literals never change + return true; + case "Identifier": + return ( + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node) + ); + case "TemplateLiteral": + /* + * In theory we could try to check if the quasi are sufficient to + * prove that the expression will always be true, but it would be + * tricky to get right. For example: `000.${foo}000` + */ + return node.expressions.length === 0; + case "AssignmentExpression": + if (node.operator === "=") { + return hasConstantLooseBooleanComparison(scope, node.right); + } + + /* + * Handling short-circuiting assignment operators would require + * walking the scope. We won't attempt that (for now...) + * + * The remaining assignment expressions all result in a numeric or + * string (non-nullish) values which could be truthy or falsy: + * "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=" + */ + return false; + case "SequenceExpression": { + const last = node.expressions.at(-1); + + return hasConstantLooseBooleanComparison(scope, last); + } + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Test if an AST node will always give the same result when _strictly_ compared + * to a boolean value. This can happen if the expression can never be boolean, or + * if it is always the same boolean value. + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The node to test + * @returns {boolean} Will `node` always give the same result when compared to a + * static boolean value? + */ +function hasConstantStrictBooleanComparison(scope, node) { + switch (node.type) { + case "ObjectExpression": // Objects are not booleans + case "ArrayExpression": // Arrays are not booleans + case "ArrowFunctionExpression": // Functions are not booleans + case "FunctionExpression": + case "ClassExpression": // Classes are not booleans + case "NewExpression": // Objects are not booleans + case "TemplateLiteral": // Strings are not booleans + case "Literal": // True, false, or not boolean, literals never change. + case "UpdateExpression": // Numbers are not booleans + return true; + case "BinaryExpression": + return NUMERIC_OR_STRING_BINARY_OPERATORS.has(node.operator); + case "UnaryExpression": { + if (node.operator === "delete") { + return false; + } + if (node.operator === "!") { + return isConstant(scope, node.argument, true); + } + + /* + * The remaining operators return either strings or numbers, neither + * of which are boolean. + */ + return true; + } + case "SequenceExpression": { + const last = node.expressions.at(-1); + + return hasConstantStrictBooleanComparison(scope, last); + } + case "Identifier": + return ( + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node) + ); + case "AssignmentExpression": + if (node.operator === "=") { + return hasConstantStrictBooleanComparison(scope, node.right); + } + + /* + * Handling short-circuiting assignment operators would require + * walking the scope. We won't attempt that (for now...) + */ + if (isLogicalAssignmentOperator(node.operator)) { + return false; + } + + /* + * The remaining assignment expressions all result in either a number + * or a string, neither of which can ever be boolean. + */ + return true; + case "CallExpression": { + if (node.callee.type !== "Identifier") { + return false; + } + const functionName = node.callee.name; + + if ( + (functionName === "String" || functionName === "Number") && + isReferenceToGlobalVariable(scope, node.callee) + ) { + return true; + } + if ( + functionName === "Boolean" && + isReferenceToGlobalVariable(scope, node.callee) + ) { + return ( + node.arguments.length === 0 || + isConstant(scope, node.arguments[0], true) + ); + } + return false; + } + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Test if an AST node will always result in a newly constructed object + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The node to test + * @returns {boolean} Will `node` always be new? + */ +function isAlwaysNew(scope, node) { + switch (node.type) { + case "ObjectExpression": + case "ArrayExpression": + case "ArrowFunctionExpression": + case "FunctionExpression": + case "ClassExpression": + return true; + case "NewExpression": { + if (node.callee.type !== "Identifier") { + return false; + } + + /* + * All the built-in constructors are always new, but + * user-defined constructors could return a sentinel + * object. + * + * Catching these is especially useful for primitive constructors + * which return boxed values, a surprising gotcha' in JavaScript. + */ + return ( + Object.hasOwn(ECMASCRIPT_GLOBALS, node.callee.name) && + isReferenceToGlobalVariable(scope, node.callee) + ); + } + case "Literal": + // Regular expressions are objects, and thus always new + return typeof node.regex === "object"; + case "SequenceExpression": { + const last = node.expressions.at(-1); + + return isAlwaysNew(scope, last); + } + case "AssignmentExpression": + if (node.operator === "=") { + return isAlwaysNew(scope, node.right); + } + return false; + case "ConditionalExpression": + return ( + isAlwaysNew(scope, node.consequent) && + isAlwaysNew(scope, node.alternate) + ); + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Checks if one operand will cause the result to be constant. + * @param {Scope} scope Scope in which the expression was found. + * @param {ASTNode} a One side of the expression + * @param {ASTNode} b The other side of the expression + * @param {string} operator The binary expression operator + * @returns {ASTNode | null} The node which will cause the expression to have a constant result. + */ +function findBinaryExpressionConstantOperand(scope, a, b, operator) { + if (operator === "==" || operator === "!=") { + if ( + (isNullOrUndefined(scope, a) && + hasConstantNullishness(scope, b, false)) || + (isStaticBoolean(scope, a) && + hasConstantLooseBooleanComparison(scope, b)) + ) { + return b; + } + } else if (operator === "===" || operator === "!==") { + if ( + (isNullOrUndefined(scope, a) && + hasConstantNullishness(scope, b, false)) || + (isStaticBoolean(scope, a) && + hasConstantStrictBooleanComparison(scope, b)) + ) { + return b; + } + } + return null; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + docs: { + description: + "Disallow expressions where the operation doesn't affect the value", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-constant-binary-expression", + }, + schema: [], + messages: { + constantBinaryOperand: + "Unexpected constant binary expression. Compares constantly with the {{otherSide}}-hand side of the `{{operator}}`.", + constantShortCircuit: + "Unexpected constant {{property}} on the left-hand side of a `{{operator}}` expression.", + alwaysNew: + "Unexpected comparison to newly constructed object. These two values can never be equal.", + bothAlwaysNew: + "Unexpected comparison of two newly constructed objects. These two values can never be equal.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + LogicalExpression(node) { + const { operator, left } = node; + const scope = sourceCode.getScope(node); + + if ( + (operator === "&&" || operator === "||") && + isConstant(scope, left, true) + ) { + context.report({ + node: left, + messageId: "constantShortCircuit", + data: { property: "truthiness", operator }, + }); + } else if ( + operator === "??" && + hasConstantNullishness(scope, left, false) + ) { + context.report({ + node: left, + messageId: "constantShortCircuit", + data: { property: "nullishness", operator }, + }); + } + }, + BinaryExpression(node) { + const scope = sourceCode.getScope(node); + const { right, left, operator } = node; + const rightConstantOperand = + findBinaryExpressionConstantOperand( + scope, + left, + right, + operator, + ); + const leftConstantOperand = findBinaryExpressionConstantOperand( + scope, + right, + left, + operator, + ); + + if (rightConstantOperand) { + context.report({ + node: rightConstantOperand, + messageId: "constantBinaryOperand", + data: { operator, otherSide: "left" }, + }); + } else if (leftConstantOperand) { + context.report({ + node: leftConstantOperand, + messageId: "constantBinaryOperand", + data: { operator, otherSide: "right" }, + }); + } else if (operator === "===" || operator === "!==") { + if (isAlwaysNew(scope, left)) { + context.report({ node: left, messageId: "alwaysNew" }); + } else if (isAlwaysNew(scope, right)) { + context.report({ node: right, messageId: "alwaysNew" }); + } + } else if (operator === "==" || operator === "!=") { + /* + * If both sides are "new", then both sides are objects and + * therefore they will be compared by reference even with `==` + * equality. + */ + if (isAlwaysNew(scope, left) && isAlwaysNew(scope, right)) { + context.report({ + node: left, + messageId: "bothAlwaysNew", + }); + } + } + }, + + /* + * In theory we could handle short-circuiting assignment operators, + * for some constant values, but that would require walking the + * scope to find the value of the variable being assigned. This is + * dependent on https://github.com/eslint/eslint/issues/13776 + * + * AssignmentExpression() {}, + */ + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-constant-condition.js b/node_modules/eslint/lib/rules/no-constant-condition.js new file mode 100644 index 00000000..4ecd5a3d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-constant-condition.js @@ -0,0 +1,177 @@ +/** + * @fileoverview Rule to flag use constant conditions + * @author Christian Schulz + */ + +"use strict"; + +const { isConstant } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [{ checkLoops: "allExceptWhileTrue" }], + + docs: { + description: "Disallow constant expressions in conditions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-constant-condition", + }, + + schema: [ + { + type: "object", + properties: { + checkLoops: { + enum: [ + "all", + "allExceptWhileTrue", + "none", + true, + false, + ], + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Unexpected constant condition.", + }, + }, + + create(context) { + const loopSetStack = []; + const sourceCode = context.sourceCode; + let [{ checkLoops }] = context.options; + + if (checkLoops === true) { + checkLoops = "all"; + } else if (checkLoops === false) { + checkLoops = "none"; + } + + let loopsInCurrentScope = new Set(); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tracks when the given node contains a constant condition. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function trackConstantConditionLoop(node) { + if ( + node.test && + isConstant(sourceCode.getScope(node), node.test, true) + ) { + loopsInCurrentScope.add(node); + } + } + + /** + * Reports when the set contains the given constant condition node + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkConstantConditionLoopInSet(node) { + if (loopsInCurrentScope.has(node)) { + loopsInCurrentScope.delete(node); + context.report({ node: node.test, messageId: "unexpected" }); + } + } + + /** + * Reports when the given node contains a constant condition. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function reportIfConstant(node) { + if ( + node.test && + isConstant(sourceCode.getScope(node), node.test, true) + ) { + context.report({ node: node.test, messageId: "unexpected" }); + } + } + + /** + * Stores current set of constant loops in loopSetStack temporarily + * and uses a new set to track constant loops + * @returns {void} + * @private + */ + function enterFunction() { + loopSetStack.push(loopsInCurrentScope); + loopsInCurrentScope = new Set(); + } + + /** + * Reports when the set still contains stored constant conditions + * @returns {void} + * @private + */ + function exitFunction() { + loopsInCurrentScope = loopSetStack.pop(); + } + + /** + * Checks node when checkLoops option is enabled + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkLoop(node) { + if (checkLoops === "all" || checkLoops === "allExceptWhileTrue") { + trackConstantConditionLoop(node); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ConditionalExpression: reportIfConstant, + IfStatement: reportIfConstant, + WhileStatement(node) { + if ( + node.test.type === "Literal" && + node.test.value === true && + checkLoops === "allExceptWhileTrue" + ) { + return; + } + + checkLoop(node); + }, + "WhileStatement:exit": checkConstantConditionLoopInSet, + DoWhileStatement: checkLoop, + "DoWhileStatement:exit": checkConstantConditionLoopInSet, + ForStatement: checkLoop, + "ForStatement > .test": node => checkLoop(node.parent), + "ForStatement:exit": checkConstantConditionLoopInSet, + FunctionDeclaration: enterFunction, + "FunctionDeclaration:exit": exitFunction, + FunctionExpression: enterFunction, + "FunctionExpression:exit": exitFunction, + YieldExpression: () => loopsInCurrentScope.clear(), + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-constructor-return.js b/node_modules/eslint/lib/rules/no-constructor-return.js new file mode 100644 index 00000000..ed9e03db --- /dev/null +++ b/node_modules/eslint/lib/rules/no-constructor-return.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Rule to disallow returning value from constructor. + * @author Pig Fang + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow returning value from constructor", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-constructor-return", + }, + + schema: [], + + fixable: null, + + messages: { + unexpected: "Unexpected return statement in constructor.", + }, + }, + + create(context) { + const stack = []; + + return { + onCodePathStart(_, node) { + stack.push(node); + }, + onCodePathEnd() { + stack.pop(); + }, + ReturnStatement(node) { + const last = stack.at(-1); + + if (!last.parent) { + return; + } + + if ( + last.parent.type === "MethodDefinition" && + last.parent.kind === "constructor" && + node.argument + ) { + context.report({ + node, + messageId: "unexpected", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-continue.js b/node_modules/eslint/lib/rules/no-continue.js new file mode 100644 index 00000000..6671c619 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-continue.js @@ -0,0 +1,38 @@ +/** + * @fileoverview Rule to flag use of continue statement + * @author Borislav Zhivkov + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `continue` statements", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-continue", + }, + + schema: [], + + messages: { + unexpected: "Unexpected use of continue statement.", + }, + }, + + create(context) { + return { + ContinueStatement(node) { + context.report({ node, messageId: "unexpected" }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-control-regex.js b/node_modules/eslint/lib/rules/no-control-regex.js new file mode 100644 index 00000000..a0221b4b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-control-regex.js @@ -0,0 +1,142 @@ +/** + * @fileoverview Rule to forbid control characters from regular expressions. + * @author Nicholas C. Zakas + */ + +"use strict"; + +const RegExpValidator = require("@eslint-community/regexpp").RegExpValidator; +const collector = new (class { + constructor() { + this._source = ""; + this._controlChars = []; + this._validator = new RegExpValidator(this); + } + + onPatternEnter() { + /* + * `RegExpValidator` may parse the pattern twice in one `validatePattern`. + * So `this._controlChars` should be cleared here as well. + * + * For example, the `/(?\x1f)/` regex will parse the pattern twice. + * This is based on the content described in Annex B. + * If the regex contains a `GroupName` and the `u` flag is not used, `ParseText` will be called twice. + * See https://tc39.es/ecma262/2023/multipage/additional-ecmascript-features-for-web-browsers.html#sec-parsepattern-annexb + */ + this._controlChars = []; + } + + onCharacter(start, end, cp) { + if ( + cp >= 0x00 && + cp <= 0x1f && + (this._source.codePointAt(start) === cp || + this._source.slice(start, end).startsWith("\\x") || + this._source.slice(start, end).startsWith("\\u")) + ) { + this._controlChars.push(`\\x${`0${cp.toString(16)}`.slice(-2)}`); + } + } + + collectControlChars(regexpStr, flags) { + const uFlag = typeof flags === "string" && flags.includes("u"); + const vFlag = typeof flags === "string" && flags.includes("v"); + + this._controlChars = []; + this._source = regexpStr; + + try { + this._validator.validatePattern(regexpStr, void 0, void 0, { + unicode: uFlag, + unicodeSets: vFlag, + }); // Call onCharacter hook + } catch { + // Ignore syntax errors in RegExp. + } + return this._controlChars; + } +})(); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow control characters in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-control-regex", + }, + + schema: [], + + messages: { + unexpected: + "Unexpected control character(s) in regular expression: {{controlChars}}.", + }, + }, + + create(context) { + /** + * Get the regex expression + * @param {ASTNode} node `Literal` node to evaluate + * @returns {{ pattern: string, flags: string | null } | null} Regex if found (the given node is either a regex literal + * or a string literal that is the pattern argument of a RegExp constructor call). Otherwise `null`. If flags cannot be determined, + * the `flags` property will be `null`. + * @private + */ + function getRegExp(node) { + if (node.regex) { + return node.regex; + } + if ( + typeof node.value === "string" && + (node.parent.type === "NewExpression" || + node.parent.type === "CallExpression") && + node.parent.callee.type === "Identifier" && + node.parent.callee.name === "RegExp" && + node.parent.arguments[0] === node + ) { + const pattern = node.value; + const flags = + node.parent.arguments.length > 1 && + node.parent.arguments[1].type === "Literal" && + typeof node.parent.arguments[1].value === "string" + ? node.parent.arguments[1].value + : null; + + return { pattern, flags }; + } + + return null; + } + + return { + Literal(node) { + const regExp = getRegExp(node); + + if (regExp) { + const { pattern, flags } = regExp; + const controlCharacters = collector.collectControlChars( + pattern, + flags, + ); + + if (controlCharacters.length > 0) { + context.report({ + node, + messageId: "unexpected", + data: { + controlChars: controlCharacters.join(", "), + }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-debugger.js b/node_modules/eslint/lib/rules/no-debugger.js new file mode 100644 index 00000000..66bc1be1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-debugger.js @@ -0,0 +1,41 @@ +/** + * @fileoverview Rule to flag use of a debugger statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow the use of `debugger`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-debugger", + }, + + fixable: null, + schema: [], + + messages: { + unexpected: "Unexpected 'debugger' statement.", + }, + }, + + create(context) { + return { + DebuggerStatement(node) { + context.report({ + node, + messageId: "unexpected", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-delete-var.js b/node_modules/eslint/lib/rules/no-delete-var.js new file mode 100644 index 00000000..7dfe002a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-delete-var.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Rule to flag when deleting variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow deleting variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-delete-var", + }, + + schema: [], + + messages: { + unexpected: "Variables should not be deleted.", + }, + }, + + create(context) { + return { + UnaryExpression(node) { + if ( + node.operator === "delete" && + node.argument.type === "Identifier" + ) { + context.report({ node, messageId: "unexpected" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-div-regex.js b/node_modules/eslint/lib/rules/no-div-regex.js new file mode 100644 index 00000000..69845bbd --- /dev/null +++ b/node_modules/eslint/lib/rules/no-div-regex.js @@ -0,0 +1,60 @@ +/** + * @fileoverview Rule to check for ambiguous div operator in regexes + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow equal signs explicitly at the beginning of regular expressions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-div-regex", + }, + + fixable: "code", + + schema: [], + + messages: { + unexpected: + "A regular expression literal can be confused with '/='.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Literal(node) { + const token = sourceCode.getFirstToken(node); + + if ( + token.type === "RegularExpression" && + token.value[1] === "=" + ) { + context.report({ + node, + messageId: "unexpected", + fix(fixer) { + return fixer.replaceTextRange( + [token.range[0] + 1, token.range[0] + 2], + "[=]", + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-args.js b/node_modules/eslint/lib/rules/no-dupe-args.js new file mode 100644 index 00000000..cfde8ecf --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-args.js @@ -0,0 +1,81 @@ +/** + * @fileoverview Rule to flag duplicate arguments + * @author Jamund Ferguson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow duplicate arguments in `function` definitions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-args", + }, + + schema: [], + + messages: { + unexpected: "Duplicate param '{{name}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whether or not a given definition is a parameter's. + * @param {eslint-scope.DefEntry} def A definition to check. + * @returns {boolean} `true` if the definition is a parameter's. + */ + function isParameter(def) { + return def.type === "Parameter"; + } + + /** + * Determines if a given node has duplicate parameters. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkParams(node) { + const variables = sourceCode.getDeclaredVariables(node); + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + + // Checks and reports duplications. + const defs = variable.defs.filter(isParameter); + + if (defs.length >= 2) { + context.report({ + node, + messageId: "unexpected", + data: { name: variable.name }, + }); + } + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: checkParams, + FunctionExpression: checkParams, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-class-members.js b/node_modules/eslint/lib/rules/no-dupe-class-members.js new file mode 100644 index 00000000..f99b1a07 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-class-members.js @@ -0,0 +1,117 @@ +/** + * @fileoverview A rule to disallow duplicate name in class members. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + dialects: ["javascript", "typescript"], + language: "javascript", + + docs: { + description: "Disallow duplicate class members", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-class-members", + }, + + schema: [], + + messages: { + unexpected: "Duplicate name '{{name}}'.", + }, + }, + + create(context) { + let stack = []; + + /** + * Gets state of a given member name. + * @param {string} name A name of a member. + * @param {boolean} isStatic A flag which specifies that is a static member. + * @returns {Object} A state of a given member name. + * - retv.init {boolean} A flag which shows the name is declared as normal member. + * - retv.get {boolean} A flag which shows the name is declared as getter. + * - retv.set {boolean} A flag which shows the name is declared as setter. + */ + function getState(name, isStatic) { + const stateMap = stack.at(-1); + const key = `$${name}`; // to avoid "__proto__". + + if (!stateMap[key]) { + stateMap[key] = { + nonStatic: { init: false, get: false, set: false }, + static: { init: false, get: false, set: false }, + }; + } + + return stateMap[key][isStatic ? "static" : "nonStatic"]; + } + + return { + // Initializes the stack of state of member declarations. + Program() { + stack = []; + }, + + // Initializes state of member declarations for the class. + ClassBody() { + stack.push(Object.create(null)); + }, + + // Disposes the state for the class. + "ClassBody:exit"() { + stack.pop(); + }, + + // Reports the node if its name has been declared already. + "MethodDefinition, PropertyDefinition"(node) { + if ( + node.value && + node.value.type === "TSEmptyBodyFunctionExpression" + ) { + return; + } + + const name = astUtils.getStaticPropertyName(node); + const kind = + node.type === "MethodDefinition" ? node.kind : "field"; + + if (name === null || kind === "constructor") { + return; + } + + const state = getState(name, node.static); + let isDuplicate; + + if (kind === "get") { + isDuplicate = state.init || state.get; + state.get = true; + } else if (kind === "set") { + isDuplicate = state.init || state.set; + state.set = true; + } else { + isDuplicate = state.init || state.get || state.set; + state.init = true; + } + + if (isDuplicate) { + context.report({ + node, + messageId: "unexpected", + data: { name }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-else-if.js b/node_modules/eslint/lib/rules/no-dupe-else-if.js new file mode 100644 index 00000000..7c419581 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-else-if.js @@ -0,0 +1,145 @@ +/** + * @fileoverview Rule to disallow duplicate conditions in if-else-if chains + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the first given array is a subset of the second given array. + * @param {Function} comparator A function to compare two elements, should return `true` if they are equal. + * @param {Array} arrA The array to compare from. + * @param {Array} arrB The array to compare against. + * @returns {boolean} `true` if the array `arrA` is a subset of the array `arrB`. + */ +function isSubsetByComparator(comparator, arrA, arrB) { + return arrA.every(a => arrB.some(b => comparator(a, b))); +} + +/** + * Splits the given node by the given logical operator. + * @param {string} operator Logical operator `||` or `&&`. + * @param {ASTNode} node The node to split. + * @returns {ASTNode[]} Array of conditions that makes the node when joined by the operator. + */ +function splitByLogicalOperator(operator, node) { + if (node.type === "LogicalExpression" && node.operator === operator) { + return [ + ...splitByLogicalOperator(operator, node.left), + ...splitByLogicalOperator(operator, node.right), + ]; + } + return [node]; +} + +const splitByOr = splitByLogicalOperator.bind(null, "||"); +const splitByAnd = splitByLogicalOperator.bind(null, "&&"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate conditions in if-else-if chains", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-else-if", + }, + + schema: [], + + messages: { + unexpected: + "This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether the two given nodes are considered to be equal. In particular, given that the nodes + * represent expressions in a boolean context, `||` and `&&` can be considered as commutative operators. + * @param {ASTNode} a First node. + * @param {ASTNode} b Second node. + * @returns {boolean} `true` if the nodes are considered to be equal. + */ + function equal(a, b) { + if (a.type !== b.type) { + return false; + } + + if ( + a.type === "LogicalExpression" && + (a.operator === "||" || a.operator === "&&") && + a.operator === b.operator + ) { + return ( + (equal(a.left, b.left) && equal(a.right, b.right)) || + (equal(a.left, b.right) && equal(a.right, b.left)) + ); + } + + return astUtils.equalTokens(a, b, sourceCode); + } + + const isSubset = isSubsetByComparator.bind(null, equal); + + return { + IfStatement(node) { + const test = node.test, + conditionsToCheck = + test.type === "LogicalExpression" && + test.operator === "&&" + ? [test, ...splitByAnd(test)] + : [test]; + let current = node, + listToCheck = conditionsToCheck.map(c => + splitByOr(c).map(splitByAnd), + ); + + while ( + current.parent && + current.parent.type === "IfStatement" && + current.parent.alternate === current + ) { + current = current.parent; + + const currentOrOperands = splitByOr(current.test).map( + splitByAnd, + ); + + listToCheck = listToCheck.map(orOperands => + orOperands.filter( + orOperand => + !currentOrOperands.some(currentOrOperand => + isSubset(currentOrOperand, orOperand), + ), + ), + ); + + if ( + listToCheck.some(orOperands => orOperands.length === 0) + ) { + context.report({ node: test, messageId: "unexpected" }); + break; + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-keys.js b/node_modules/eslint/lib/rules/no-dupe-keys.js new file mode 100644 index 00000000..a17cb343 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-keys.js @@ -0,0 +1,165 @@ +/** + * @fileoverview Rule to flag use of duplicate keys in an object. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const GET_KIND = /^(?:init|get)$/u; +const SET_KIND = /^(?:init|set)$/u; + +/** + * The class which stores properties' information of an object. + */ +class ObjectInfo { + /** + * @param {ObjectInfo|null} upper The information of the outer object. + * @param {ASTNode} node The ObjectExpression node of this information. + */ + constructor(upper, node) { + this.upper = upper; + this.node = node; + this.properties = new Map(); + } + + /** + * Gets the information of the given Property node. + * @param {ASTNode} node The Property node to get. + * @returns {{get: boolean, set: boolean}} The information of the property. + */ + getPropertyInfo(node) { + const name = astUtils.getStaticPropertyName(node); + + if (!this.properties.has(name)) { + this.properties.set(name, { get: false, set: false }); + } + return this.properties.get(name); + } + + /** + * Checks whether the given property has been defined already or not. + * @param {ASTNode} node The Property node to check. + * @returns {boolean} `true` if the property has been defined. + */ + isPropertyDefined(node) { + const entry = this.getPropertyInfo(node); + + return ( + (GET_KIND.test(node.kind) && entry.get) || + (SET_KIND.test(node.kind) && entry.set) + ); + } + + /** + * Defines the given property. + * @param {ASTNode} node The Property node to define. + * @returns {void} + */ + defineProperty(node) { + const entry = this.getPropertyInfo(node); + + if (GET_KIND.test(node.kind)) { + entry.get = true; + } + if (SET_KIND.test(node.kind)) { + entry.set = true; + } + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate keys in object literals", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-keys", + }, + + schema: [], + + messages: { + unexpected: "Duplicate key '{{name}}'.", + }, + }, + + create(context) { + let info = null; + + return { + ObjectExpression(node) { + info = new ObjectInfo(info, node); + }, + "ObjectExpression:exit"() { + info = info.upper; + }, + + Property(node) { + const name = astUtils.getStaticPropertyName(node); + + // Skip destructuring. + if (node.parent.type !== "ObjectExpression") { + return; + } + + // Skip if the name is not static. + if (name === null) { + return; + } + + /* + * Skip if the property node is a proto setter. + * Proto setter is a special syntax that sets + * object's prototype instead of creating a property. + * It can be in one of the following forms: + * + * __proto__: + * '__proto__': + * "__proto__": + * + * Duplicate proto setters produce parsing errors, + * so we can just skip them to not interfere with + * regular properties named "__proto__". + */ + if ( + name === "__proto__" && + node.kind === "init" && + !node.computed && + !node.shorthand && + !node.method + ) { + return; + } + + // Reports if the name is defined already. + if (info.isPropertyDefined(node)) { + context.report({ + node: info.node, + loc: node.key.loc, + messageId: "unexpected", + data: { name }, + }); + } + + // Update info. + info.defineProperty(node); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-duplicate-case.js b/node_modules/eslint/lib/rules/no-duplicate-case.js new file mode 100644 index 00000000..161b1a0b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-duplicate-case.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Rule to disallow a duplicate case label. + * @author Dieter Oberkofler + * @author Burak Yigit Kaya + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate case labels", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-duplicate-case", + }, + + schema: [], + + messages: { + unexpected: "Duplicate case label.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether the two given nodes are considered to be equal. + * @param {ASTNode} a First node. + * @param {ASTNode} b Second node. + * @returns {boolean} `true` if the nodes are considered to be equal. + */ + function equal(a, b) { + if (a.type !== b.type) { + return false; + } + + return astUtils.equalTokens(a, b, sourceCode); + } + return { + SwitchStatement(node) { + const previousTests = []; + + for (const switchCase of node.cases) { + if (switchCase.test) { + const test = switchCase.test; + + if ( + previousTests.some(previousTest => + equal(previousTest, test), + ) + ) { + context.report({ + node: switchCase, + messageId: "unexpected", + }); + } else { + previousTests.push(test); + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-duplicate-imports.js b/node_modules/eslint/lib/rules/no-duplicate-imports.js new file mode 100644 index 00000000..f573696a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-duplicate-imports.js @@ -0,0 +1,296 @@ +/** + * @fileoverview Restrict usage of duplicate imports. + * @author Simen Bekkhus + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const NAMED_TYPES = ["ImportSpecifier", "ExportSpecifier"]; +const NAMESPACE_TYPES = [ + "ImportNamespaceSpecifier", + "ExportNamespaceSpecifier", +]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Check if an import/export type belongs to (ImportSpecifier|ExportSpecifier) or (ImportNamespaceSpecifier|ExportNamespaceSpecifier). + * @param {string} importExportType An import/export type to check. + * @param {string} type Can be "named" or "namespace" + * @returns {boolean} True if import/export type belongs to (ImportSpecifier|ExportSpecifier) or (ImportNamespaceSpecifier|ExportNamespaceSpecifier) and false if it doesn't. + */ +function isImportExportSpecifier(importExportType, type) { + const arrayToCheck = type === "named" ? NAMED_TYPES : NAMESPACE_TYPES; + + return arrayToCheck.includes(importExportType); +} + +/** + * Return the type of (import|export). + * @param {ASTNode} node A node to get. + * @returns {string} The type of the (import|export). + */ +function getImportExportType(node) { + if (node.specifiers && node.specifiers.length > 0) { + const nodeSpecifiers = node.specifiers; + const index = nodeSpecifiers.findIndex( + ({ type }) => + isImportExportSpecifier(type, "named") || + isImportExportSpecifier(type, "namespace"), + ); + const i = index > -1 ? index : 0; + + return nodeSpecifiers[i].type; + } + if (node.type === "ExportAllDeclaration") { + if (node.exported) { + return "ExportNamespaceSpecifier"; + } + return "ExportAll"; + } + return "SideEffectImport"; +} + +/** + * Returns a boolean indicates if two (import|export) can be merged + * @param {ASTNode} node1 A node to check. + * @param {ASTNode} node2 A node to check. + * @returns {boolean} True if two (import|export) can be merged, false if they can't. + */ +function isImportExportCanBeMerged(node1, node2) { + const importExportType1 = getImportExportType(node1); + const importExportType2 = getImportExportType(node2); + + if ( + (importExportType1 === "ExportAll" && + importExportType2 !== "ExportAll" && + importExportType2 !== "SideEffectImport") || + (importExportType1 !== "ExportAll" && + importExportType1 !== "SideEffectImport" && + importExportType2 === "ExportAll") + ) { + return false; + } + if ( + (isImportExportSpecifier(importExportType1, "namespace") && + isImportExportSpecifier(importExportType2, "named")) || + (isImportExportSpecifier(importExportType2, "namespace") && + isImportExportSpecifier(importExportType1, "named")) + ) { + return false; + } + return true; +} + +/** + * Returns a boolean if we should report (import|export). + * @param {ASTNode} node A node to be reported or not. + * @param {[ASTNode]} previousNodes An array contains previous nodes of the module imported or exported. + * @returns {boolean} True if the (import|export) should be reported. + */ +function shouldReportImportExport(node, previousNodes) { + let i = 0; + + while (i < previousNodes.length) { + if (isImportExportCanBeMerged(node, previousNodes[i])) { + return true; + } + i++; + } + return false; +} + +/** + * Returns array contains only nodes with declarations types equal to type. + * @param {[{node: ASTNode, declarationType: string}]} nodes An array contains objects, each object contains a node and a declaration type. + * @param {string} type Declaration type. + * @returns {[ASTNode]} An array contains only nodes with declarations types equal to type. + */ +function getNodesByDeclarationType(nodes, type) { + return nodes + .filter(({ declarationType }) => declarationType === type) + .map(({ node }) => node); +} + +/** + * Returns the name of the module imported or re-exported. + * @param {ASTNode} node A node to get. + * @returns {string} The name of the module, or empty string if no name. + */ +function getModule(node) { + if (node && node.source && node.source.value) { + return node.source.value.trim(); + } + return ""; +} + +/** + * Checks if the (import|export) can be merged with at least one import or one export, and reports if so. + * @param {RuleContext} context The ESLint rule context object. + * @param {ASTNode} node A node to get. + * @param {Map} modules A Map object contains as a key a module name and as value an array contains objects, each object contains a node and a declaration type. + * @param {string} declarationType A declaration type can be an import or export. + * @param {boolean} includeExports Whether or not to check for exports in addition to imports. + * @returns {void} No return value. + */ +function checkAndReport( + context, + node, + modules, + declarationType, + includeExports, +) { + const module = getModule(node); + + if (modules.has(module)) { + const previousNodes = modules.get(module); + const messagesIds = []; + const importNodes = getNodesByDeclarationType(previousNodes, "import"); + let exportNodes; + + if (includeExports) { + exportNodes = getNodesByDeclarationType(previousNodes, "export"); + } + if (declarationType === "import") { + if (shouldReportImportExport(node, importNodes)) { + messagesIds.push("import"); + } + if (includeExports) { + if (shouldReportImportExport(node, exportNodes)) { + messagesIds.push("importAs"); + } + } + } else if (declarationType === "export") { + if (shouldReportImportExport(node, exportNodes)) { + messagesIds.push("export"); + } + if (shouldReportImportExport(node, importNodes)) { + messagesIds.push("exportAs"); + } + } + messagesIds.forEach(messageId => + context.report({ + node, + messageId, + data: { + module, + }, + }), + ); + } +} + +/** + * @callback nodeCallback + * @param {ASTNode} node A node to handle. + */ + +/** + * Returns a function handling the (imports|exports) of a given file + * @param {RuleContext} context The ESLint rule context object. + * @param {Map} modules A Map object contains as a key a module name and as value an array contains objects, each object contains a node and a declaration type. + * @param {string} declarationType A declaration type can be an import or export. + * @param {boolean} includeExports Whether or not to check for exports in addition to imports. + * @returns {nodeCallback} A function passed to ESLint to handle the statement. + */ +function handleImportsExports( + context, + modules, + declarationType, + includeExports, +) { + return function (node) { + const module = getModule(node); + + if (module) { + checkAndReport( + context, + node, + modules, + declarationType, + includeExports, + ); + const currentNode = { node, declarationType }; + let nodes = [currentNode]; + + if (modules.has(module)) { + const previousNodes = modules.get(module); + + nodes = [...previousNodes, currentNode]; + } + modules.set(module, nodes); + } + }; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + includeExports: false, + }, + ], + + docs: { + description: "Disallow duplicate module imports", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-duplicate-imports", + }, + + schema: [ + { + type: "object", + properties: { + includeExports: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + import: "'{{module}}' import is duplicated.", + importAs: "'{{module}}' import is duplicated as export.", + export: "'{{module}}' export is duplicated.", + exportAs: "'{{module}}' export is duplicated as import.", + }, + }, + + create(context) { + const [{ includeExports }] = context.options; + const modules = new Map(); + const handlers = { + ImportDeclaration: handleImportsExports( + context, + modules, + "import", + includeExports, + ), + }; + + if (includeExports) { + handlers.ExportNamedDeclaration = handleImportsExports( + context, + modules, + "export", + includeExports, + ); + handlers.ExportAllDeclaration = handleImportsExports( + context, + modules, + "export", + includeExports, + ); + } + return handlers; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-else-return.js b/node_modules/eslint/lib/rules/no-else-return.js new file mode 100644 index 00000000..40e11dbd --- /dev/null +++ b/node_modules/eslint/lib/rules/no-else-return.js @@ -0,0 +1,450 @@ +/** + * @fileoverview Rule to flag `else` after a `return` in `if` + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const FixTracker = require("./utils/fix-tracker"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ allowElseIf: true }], + + docs: { + description: + "Disallow `else` blocks after `return` statements in `if` statements", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-else-return", + }, + + schema: [ + { + type: "object", + properties: { + allowElseIf: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + unexpected: "Unnecessary 'else' after 'return'.", + }, + }, + + create(context) { + const [{ allowElseIf }] = context.options; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whether the given names can be safely used to declare block-scoped variables + * in the given scope. Name collisions can produce redeclaration syntax errors, + * or silently change references and modify behavior of the original code. + * + * This is not a generic function. In particular, it is assumed that the scope is a function scope or + * a function's inner scope, and that the names can be valid identifiers in the given scope. + * @param {string[]} names Array of variable names. + * @param {eslint-scope.Scope} scope Function scope or a function's inner scope. + * @returns {boolean} True if all names can be safely declared, false otherwise. + */ + function isSafeToDeclare(names, scope) { + if (names.length === 0) { + return true; + } + + const functionScope = scope.variableScope; + + /* + * If this is a function scope, scope.variables will contain parameters, implicit variables such as "arguments", + * all function-scoped variables ('var'), and block-scoped variables defined in the scope. + * If this is an inner scope, scope.variables will contain block-scoped variables defined in the scope. + * + * Redeclaring any of these would cause a syntax error, except for the implicit variables. + */ + const declaredVariables = scope.variables.filter( + ({ defs }) => defs.length > 0, + ); + + if (declaredVariables.some(({ name }) => names.includes(name))) { + return false; + } + + // Redeclaring a catch variable would also cause a syntax error. + if (scope !== functionScope && scope.upper.type === "catch") { + if ( + scope.upper.variables.some(({ name }) => + names.includes(name), + ) + ) { + return false; + } + } + + /* + * Redeclaring an implicit variable, such as "arguments", would not cause a syntax error. + * However, if the variable was used, declaring a new one with the same name would change references + * and modify behavior. + */ + const usedImplicitVariables = scope.variables.filter( + ({ defs, references }) => + defs.length === 0 && references.length > 0, + ); + + if ( + usedImplicitVariables.some(({ name }) => names.includes(name)) + ) { + return false; + } + + /* + * Declaring a variable with a name that was already used to reference a variable from an upper scope + * would change references and modify behavior. + */ + if (scope.through.some(t => names.includes(t.identifier.name))) { + return false; + } + + /* + * If the scope is an inner scope (not the function scope), an uninitialized `var` variable declared inside + * the scope node (directly or in one of its descendants) is neither declared nor 'through' in the scope. + * + * For example, this would be a syntax error "Identifier 'a' has already been declared": + * function foo() { if (bar) { let a; if (baz) { var a; } } } + */ + if (scope !== functionScope) { + const scopeNodeRange = scope.block.range; + const variablesToCheck = functionScope.variables.filter( + ({ name }) => names.includes(name), + ); + + if ( + variablesToCheck.some(v => + v.defs.some( + ({ node: { range } }) => + scopeNodeRange[0] <= range[0] && + range[1] <= scopeNodeRange[1], + ), + ) + ) { + return false; + } + } + + return true; + } + + /** + * Checks whether the removal of `else` and its braces is safe from variable name collisions. + * @param {Node} node The 'else' node. + * @param {eslint-scope.Scope} scope The scope in which the node and the whole 'if' statement is. + * @returns {boolean} True if it is safe, false otherwise. + */ + function isSafeFromNameCollisions(node, scope) { + if (node.type === "FunctionDeclaration") { + // Conditional function declaration. Scope and hoisting are unpredictable, different engines work differently. + return false; + } + + if (node.type !== "BlockStatement") { + return true; + } + + const elseBlockScope = scope.childScopes.find( + ({ block }) => block === node, + ); + + if (!elseBlockScope) { + // ecmaVersion < 6, `else` block statement cannot have its own scope, no possible collisions. + return true; + } + + /* + * elseBlockScope is supposed to merge into its upper scope. elseBlockScope.variables array contains + * only block-scoped variables (such as let and const variables or class and function declarations) + * defined directly in the elseBlockScope. These are exactly the only names that could cause collisions. + */ + const namesToCheck = elseBlockScope.variables.map( + ({ name }) => name, + ); + + return isSafeToDeclare(namesToCheck, scope); + } + + /** + * Display the context report if rule is violated + * @param {Node} elseNode The 'else' node + * @returns {void} + */ + function displayReport(elseNode) { + const currentScope = sourceCode.getScope(elseNode.parent); + + context.report({ + node: elseNode, + messageId: "unexpected", + fix(fixer) { + if (!isSafeFromNameCollisions(elseNode, currentScope)) { + return null; + } + + const startToken = sourceCode.getFirstToken(elseNode); + const elseToken = sourceCode.getTokenBefore(startToken); + const source = sourceCode.getText(elseNode); + const lastIfToken = sourceCode.getTokenBefore(elseToken); + let fixedSource, firstTokenOfElseBlock; + + if ( + startToken.type === "Punctuator" && + startToken.value === "{" + ) { + firstTokenOfElseBlock = + sourceCode.getTokenAfter(startToken); + } else { + firstTokenOfElseBlock = startToken; + } + + /* + * If the if block does not have curly braces and does not end in a semicolon + * and the else block starts with (, [, /, +, ` or -, then it is not + * safe to remove the else keyword, because ASI will not add a semicolon + * after the if block + */ + const ifBlockMaybeUnsafe = + elseNode.parent.consequent.type !== "BlockStatement" && + lastIfToken.value !== ";"; + const elseBlockUnsafe = /^[([/+`-]/u.test( + firstTokenOfElseBlock.value, + ); + + if (ifBlockMaybeUnsafe && elseBlockUnsafe) { + return null; + } + + const endToken = sourceCode.getLastToken(elseNode); + const lastTokenOfElseBlock = + sourceCode.getTokenBefore(endToken); + + if (lastTokenOfElseBlock.value !== ";") { + const nextToken = sourceCode.getTokenAfter(endToken); + + const nextTokenUnsafe = + nextToken && /^[([/+`-]/u.test(nextToken.value); + const nextTokenOnSameLine = + nextToken && + nextToken.loc.start.line === + lastTokenOfElseBlock.loc.start.line; + + /* + * If the else block contents does not end in a semicolon, + * and the else block starts with (, [, /, +, ` or -, then it is not + * safe to remove the else block, because ASI will not add a semicolon + * after the remaining else block contents + */ + if ( + nextTokenUnsafe || + (nextTokenOnSameLine && nextToken.value !== "}") + ) { + return null; + } + } + + if ( + startToken.type === "Punctuator" && + startToken.value === "{" + ) { + fixedSource = source.slice(1, -1); + } else { + fixedSource = source; + } + + /* + * Extend the replacement range to include the entire + * function to avoid conflicting with no-useless-return. + * https://github.com/eslint/eslint/issues/8026 + * + * Also, to avoid name collisions between two else blocks. + */ + return new FixTracker(fixer, sourceCode) + .retainEnclosingFunction(elseNode) + .replaceTextRange( + [elseToken.range[0], elseNode.range[1]], + fixedSource, + ); + }, + }); + } + + /** + * Check to see if the node is a ReturnStatement + * @param {Node} node The node being evaluated + * @returns {boolean} True if node is a return + */ + function checkForReturn(node) { + return node.type === "ReturnStatement"; + } + + /** + * Naive return checking, does not iterate through the whole + * BlockStatement because we make the assumption that the ReturnStatement + * will be the last node in the body of the BlockStatement. + * @param {Node} node The consequent/alternate node + * @returns {boolean} True if it has a return + */ + function naiveHasReturn(node) { + if (node.type === "BlockStatement") { + const body = node.body, + lastChildNode = body.at(-1); + + return lastChildNode && checkForReturn(lastChildNode); + } + return checkForReturn(node); + } + + /** + * Check to see if the node is valid for evaluation, + * meaning it has an else. + * @param {Node} node The node being evaluated + * @returns {boolean} True if the node is valid + */ + function hasElse(node) { + return node.alternate && node.consequent; + } + + /** + * If the consequent is an IfStatement, check to see if it has an else + * and both its consequent and alternate path return, meaning this is + * a nested case of rule violation. If-Else not considered currently. + * @param {Node} node The consequent node + * @returns {boolean} True if this is a nested rule violation + */ + function checkForIf(node) { + return ( + node.type === "IfStatement" && + hasElse(node) && + naiveHasReturn(node.alternate) && + naiveHasReturn(node.consequent) + ); + } + + /** + * Check the consequent/body node to make sure it is not + * a ReturnStatement or an IfStatement that returns on both + * code paths. + * @param {Node} node The consequent or body node + * @returns {boolean} `true` if it is a Return/If node that always returns. + */ + function checkForReturnOrIf(node) { + return checkForReturn(node) || checkForIf(node); + } + + /** + * Check whether a node returns in every codepath. + * @param {Node} node The node to be checked + * @returns {boolean} `true` if it returns on every codepath. + */ + function alwaysReturns(node) { + if (node.type === "BlockStatement") { + // If we have a BlockStatement, check each consequent body node. + return node.body.some(checkForReturnOrIf); + } + + /* + * If not a block statement, make sure the consequent isn't a + * ReturnStatement or an IfStatement with returns on both paths. + */ + return checkForReturnOrIf(node); + } + + /** + * Check the if statement, but don't catch else-if blocks. + * @returns {void} + * @param {Node} node The node for the if statement to check + * @private + */ + function checkIfWithoutElse(node) { + const parent = node.parent; + + /* + * Fixing this would require splitting one statement into two, so no error should + * be reported if this node is in a position where only one statement is allowed. + */ + if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { + return; + } + + const consequents = []; + let alternate; + + for ( + let currentNode = node; + currentNode.type === "IfStatement"; + currentNode = currentNode.alternate + ) { + if (!currentNode.alternate) { + return; + } + consequents.push(currentNode.consequent); + alternate = currentNode.alternate; + } + + if (consequents.every(alwaysReturns)) { + displayReport(alternate); + } + } + + /** + * Check the if statement + * @returns {void} + * @param {Node} node The node for the if statement to check + * @private + */ + function checkIfWithElse(node) { + const parent = node.parent; + + /* + * Fixing this would require splitting one statement into two, so no error should + * be reported if this node is in a position where only one statement is allowed. + */ + if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { + return; + } + + const alternate = node.alternate; + + if (alternate && alwaysReturns(node.consequent)) { + displayReport(alternate); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "IfStatement:exit": allowElseIf + ? checkIfWithoutElse + : checkIfWithElse, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty-character-class.js b/node_modules/eslint/lib/rules/no-empty-character-class.js new file mode 100644 index 00000000..eccee1d1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-character-class.js @@ -0,0 +1,83 @@ +/** + * @fileoverview Rule to flag the use of empty character classes in regular expressions + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const parser = new RegExpParser(); +const QUICK_TEST_REGEX = /\[\]/u; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow empty character classes in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty-character-class", + }, + + schema: [], + + messages: { + unexpected: "Empty class.", + }, + }, + + create(context) { + return { + "Literal[regex]"(node) { + const { pattern, flags } = node.regex; + + if (!QUICK_TEST_REGEX.test(pattern)) { + return; + } + + let regExpAST; + + try { + regExpAST = parser.parsePattern( + pattern, + 0, + pattern.length, + { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }, + ); + } catch { + // Ignore regular expressions that regexpp cannot parse + return; + } + + visitRegExpAST(regExpAST, { + onCharacterClassEnter(characterClass) { + if ( + !characterClass.negate && + characterClass.elements.length === 0 + ) { + context.report({ node, messageId: "unexpected" }); + } + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty-function.js b/node_modules/eslint/lib/rules/no-empty-function.js new file mode 100644 index 00000000..8bf6e002 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-function.js @@ -0,0 +1,217 @@ +/** + * @fileoverview Rule to disallow empty functions. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const ALLOW_OPTIONS = Object.freeze([ + "functions", + "arrowFunctions", + "generatorFunctions", + "methods", + "generatorMethods", + "getters", + "setters", + "constructors", + "asyncFunctions", + "asyncMethods", + "privateConstructors", + "protectedConstructors", + "decoratedFunctions", + "overrideMethods", +]); + +/** + * Gets the kind of a given function node. + * @param {ASTNode} node A function node to get. This is one of + * an ArrowFunctionExpression, a FunctionDeclaration, or a + * FunctionExpression. + * @returns {string} The kind of the function. This is one of "functions", + * "arrowFunctions", "generatorFunctions", "asyncFunctions", "methods", + * "generatorMethods", "asyncMethods", "getters", "setters", and + * "constructors". + */ +function getKind(node) { + const parent = node.parent; + let kind; + + if (node.type === "ArrowFunctionExpression") { + return "arrowFunctions"; + } + + // Detects main kind. + if (parent.type === "Property") { + if (parent.kind === "get") { + return "getters"; + } + if (parent.kind === "set") { + return "setters"; + } + kind = parent.method ? "methods" : "functions"; + } else if (parent.type === "MethodDefinition") { + if (parent.kind === "get") { + return "getters"; + } + if (parent.kind === "set") { + return "setters"; + } + if (parent.kind === "constructor") { + return "constructors"; + } + kind = "methods"; + } else { + kind = "functions"; + } + + // Detects prefix. + let prefix; + + if (node.generator) { + prefix = "generator"; + } else if (node.async) { + prefix = "async"; + } else { + return kind; + } + return prefix + kind[0].toUpperCase() + kind.slice(1); +} + +/** + * Checks if a constructor function has parameter properties. + * @param {ASTNode} node The function node to examine. + * @returns {boolean} True if the constructor has parameter properties, false otherwise. + */ +function isParameterPropertiesConstructor(node) { + return node.params.some(param => param.type === "TSParameterProperty"); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + defaultOptions: [{ allow: [] }], + + docs: { + description: "Disallow empty functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-empty-function", + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { enum: ALLOW_OPTIONS }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Unexpected empty {{name}}.", + }, + }, + + create(context) { + const [{ allow }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Checks if the given function node is allowed to be empty. + * @param {ASTNode} node The function node to check. + * @returns {boolean} True if the function is allowed to be empty, false otherwise. + */ + function isAllowedEmptyFunction(node) { + const kind = getKind(node); + + if (allow.includes(kind)) { + return true; + } + + if (kind === "constructors") { + if ( + (node.parent.accessibility === "private" && + allow.includes("privateConstructors")) || + (node.parent.accessibility === "protected" && + allow.includes("protectedConstructors")) || + isParameterPropertiesConstructor(node) + ) { + return true; + } + } + + if (/(g|s)etters|methods$/iu.test(kind)) { + if ( + (node.parent.decorators?.length && + allow.includes("decoratedFunctions")) || + (node.parent.override && allow.includes("overrideMethods")) + ) { + return true; + } + } + + return false; + } + + /** + * Reports a given function node if the node matches the following patterns. + * + * - Not allowed by options. + * - The body is empty. + * - The body doesn't have any comments. + * @param {ASTNode} node A function node to report. This is one of + * an ArrowFunctionExpression, a FunctionDeclaration, or a + * FunctionExpression. + * @returns {void} + */ + function reportIfEmpty(node) { + const name = astUtils.getFunctionNameWithKind(node); + const innerComments = sourceCode.getTokens(node.body, { + includeComments: true, + filter: astUtils.isCommentToken, + }); + + if ( + !isAllowedEmptyFunction(node) && + node.body.type === "BlockStatement" && + node.body.body.length === 0 && + innerComments.length === 0 + ) { + context.report({ + node, + loc: node.body.loc, + messageId: "unexpected", + data: { name }, + }); + } + } + + return { + ArrowFunctionExpression: reportIfEmpty, + FunctionDeclaration: reportIfEmpty, + FunctionExpression: reportIfEmpty, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty-pattern.js b/node_modules/eslint/lib/rules/no-empty-pattern.js new file mode 100644 index 00000000..da75ad95 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-pattern.js @@ -0,0 +1,85 @@ +/** + * @fileoverview Rule to disallow an empty pattern + * @author Alberto Rodríguez + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowObjectPatternsAsParameters: false, + }, + ], + + docs: { + description: "Disallow empty destructuring patterns", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty-pattern", + }, + + schema: [ + { + type: "object", + properties: { + allowObjectPatternsAsParameters: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Unexpected empty {{type}} pattern.", + }, + }, + + create(context) { + const [{ allowObjectPatternsAsParameters }] = context.options; + + return { + ObjectPattern(node) { + if (node.properties.length > 0) { + return; + } + + // Allow {} and {} = {} empty object patterns as parameters when allowObjectPatternsAsParameters is true + if ( + allowObjectPatternsAsParameters && + (astUtils.isFunction(node.parent) || + (node.parent.type === "AssignmentPattern" && + astUtils.isFunction(node.parent.parent) && + node.parent.right.type === "ObjectExpression" && + node.parent.right.properties.length === 0)) + ) { + return; + } + + context.report({ + node, + messageId: "unexpected", + data: { type: "object" }, + }); + }, + ArrayPattern(node) { + if (node.elements.length === 0) { + context.report({ + node, + messageId: "unexpected", + data: { type: "array" }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty-static-block.js b/node_modules/eslint/lib/rules/no-empty-static-block.js new file mode 100644 index 00000000..5741ee3b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-static-block.js @@ -0,0 +1,49 @@ +/** + * @fileoverview Rule to disallow empty static blocks. + * @author Sosuke Suzuki + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow empty static blocks", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty-static-block", + }, + + schema: [], + + messages: { + unexpected: "Unexpected empty static block.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + StaticBlock(node) { + if (node.body.length === 0) { + const closingBrace = sourceCode.getLastToken(node); + + if ( + sourceCode.getCommentsBefore(closingBrace).length === 0 + ) { + context.report({ + node, + messageId: "unexpected", + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty.js b/node_modules/eslint/lib/rules/no-empty.js new file mode 100644 index 00000000..bcd23d0f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty.js @@ -0,0 +1,116 @@ +/** + * @fileoverview Rule to flag use of an empty block statement + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + defaultOptions: [ + { + allowEmptyCatch: false, + }, + ], + + docs: { + description: "Disallow empty block statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty", + }, + + schema: [ + { + type: "object", + properties: { + allowEmptyCatch: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Empty {{type}} statement.", + suggestComment: "Add comment inside empty {{type}} statement.", + }, + }, + + create(context) { + const [{ allowEmptyCatch }] = context.options; + const sourceCode = context.sourceCode; + + return { + BlockStatement(node) { + // if the body is not empty, we can just return immediately + if (node.body.length !== 0) { + return; + } + + // a function is generally allowed to be empty + if (astUtils.isFunction(node.parent)) { + return; + } + + if (allowEmptyCatch && node.parent.type === "CatchClause") { + return; + } + + // any other block is only allowed to be empty, if it contains a comment + if (sourceCode.getCommentsInside(node).length > 0) { + return; + } + + context.report({ + node, + messageId: "unexpected", + data: { type: "block" }, + suggest: [ + { + messageId: "suggestComment", + data: { type: "block" }, + fix(fixer) { + const range = [ + node.range[0] + 1, + node.range[1] - 1, + ]; + + return fixer.replaceTextRange( + range, + " /* empty */ ", + ); + }, + }, + ], + }); + }, + + SwitchStatement(node) { + if ( + typeof node.cases === "undefined" || + node.cases.length === 0 + ) { + context.report({ + node, + messageId: "unexpected", + data: { type: "switch" }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-eq-null.js b/node_modules/eslint/lib/rules/no-eq-null.js new file mode 100644 index 00000000..edda5e6c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-eq-null.js @@ -0,0 +1,51 @@ +/** + * @fileoverview Rule to flag comparisons to null without a type-checking + * operator. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `null` comparisons without type-checking operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-eq-null", + }, + + schema: [], + + messages: { + unexpected: "Use '===' to compare with null.", + }, + }, + + create(context) { + return { + BinaryExpression(node) { + const badOperator = + node.operator === "==" || node.operator === "!="; + + if ( + (node.right.type === "Literal" && + node.right.raw === "null" && + badOperator) || + (node.left.type === "Literal" && + node.left.raw === "null" && + badOperator) + ) { + context.report({ node, messageId: "unexpected" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-eval.js b/node_modules/eslint/lib/rules/no-eval.js new file mode 100644 index 00000000..9b771284 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-eval.js @@ -0,0 +1,293 @@ +/** + * @fileoverview Rule to flag use of eval() statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const candidatesOfGlobalObject = Object.freeze([ + "global", + "window", + "globalThis", +]); + +/** + * Checks a given node is a MemberExpression node which has the specified name's + * property. + * @param {ASTNode} node A node to check. + * @param {string} name A name to check. + * @returns {boolean} `true` if the node is a MemberExpression node which has + * the specified name's property + */ +function isMember(node, name) { + return astUtils.isSpecificMemberAccess(node, null, name); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowIndirect: false, + }, + ], + + docs: { + description: "Disallow the use of `eval()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-eval", + }, + + schema: [ + { + type: "object", + properties: { + allowIndirect: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "eval can be harmful.", + }, + }, + + create(context) { + const [{ allowIndirect }] = context.options; + const sourceCode = context.sourceCode; + let funcInfo = null; + + /** + * Pushes a `this` scope (non-arrow function, class static block, or class field initializer) information to the stack. + * Top-level scopes are handled separately. + * + * This is used in order to check whether or not `this` binding is a + * reference to the global object. + * @param {ASTNode} node A node of the scope. + * For functions, this is one of FunctionDeclaration, FunctionExpression. + * For class static blocks, this is StaticBlock. + * For class field initializers, this can be any node that is PropertyDefinition#value. + * @returns {void} + */ + function enterThisScope(node) { + const strict = sourceCode.getScope(node).isStrict; + + funcInfo = { + upper: funcInfo, + node, + strict, + isTopLevelOfScript: false, + defaultThis: false, + initialized: strict, + }; + } + + /** + * Pops a variable scope from the stack. + * @returns {void} + */ + function exitThisScope() { + funcInfo = funcInfo.upper; + } + + /** + * Reports a given node. + * + * `node` is `Identifier` or `MemberExpression`. + * The parent of `node` might be `CallExpression`. + * + * The location of the report is always `eval` `Identifier` (or possibly + * `Literal`). The type of the report is `CallExpression` if the parent is + * `CallExpression`. Otherwise, it's the given node type. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function report(node) { + const parent = node.parent; + const locationNode = + node.type === "MemberExpression" ? node.property : node; + + const reportNode = + parent.type === "CallExpression" && parent.callee === node + ? parent + : node; + + context.report({ + node: reportNode, + loc: locationNode.loc, + messageId: "unexpected", + }); + } + + /** + * Reports accesses of `eval` via the global object. + * @param {eslint-scope.Scope} globalScope The global scope. + * @returns {void} + */ + function reportAccessingEvalViaGlobalObject(globalScope) { + for (let i = 0; i < candidatesOfGlobalObject.length; ++i) { + const name = candidatesOfGlobalObject[i]; + const variable = astUtils.getVariableByName(globalScope, name); + + if (!variable) { + continue; + } + + const references = variable.references; + + for (let j = 0; j < references.length; ++j) { + const identifier = references[j].identifier; + let node = identifier.parent; + + // To detect code like `window.window.eval`. + while (isMember(node, name)) { + node = node.parent; + } + + // Reports. + if (isMember(node, "eval")) { + report(node); + } + } + } + } + + /** + * Reports all accesses of `eval` (excludes direct calls to eval). + * @param {eslint-scope.Scope} globalScope The global scope. + * @returns {void} + */ + function reportAccessingEval(globalScope) { + const variable = astUtils.getVariableByName(globalScope, "eval"); + + if (!variable) { + return; + } + + const references = variable.references; + + for (let i = 0; i < references.length; ++i) { + const reference = references[i]; + const id = reference.identifier; + + if (id.name === "eval" && !astUtils.isCallee(id)) { + // Is accessing to eval (excludes direct calls to eval) + report(id); + } + } + } + + if (allowIndirect) { + // Checks only direct calls to eval. It's simple! + return { + "CallExpression:exit"(node) { + const callee = node.callee; + + /* + * Optional call (`eval?.("code")`) is not direct eval. + * The direct eval is only step 6.a.vi of https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation + * But the optional call is https://tc39.es/ecma262/#sec-optional-chaining-chain-evaluation + */ + if ( + !node.optional && + astUtils.isSpecificId(callee, "eval") + ) { + report(callee); + } + }, + }; + } + + return { + "CallExpression:exit"(node) { + const callee = node.callee; + + if (astUtils.isSpecificId(callee, "eval")) { + report(callee); + } + }, + + Program(node) { + const scope = sourceCode.getScope(node), + features = context.parserOptions.ecmaFeatures || {}, + strict = + scope.isStrict || + node.sourceType === "module" || + (features.globalReturn && + scope.childScopes[0].isStrict), + isTopLevelOfScript = + node.sourceType !== "module" && !features.globalReturn; + + funcInfo = { + upper: null, + node, + strict, + isTopLevelOfScript, + defaultThis: true, + initialized: true, + }; + }, + + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + exitThisScope(); + reportAccessingEval(globalScope); + reportAccessingEvalViaGlobalObject(globalScope); + }, + + FunctionDeclaration: enterThisScope, + "FunctionDeclaration:exit": exitThisScope, + FunctionExpression: enterThisScope, + "FunctionExpression:exit": exitThisScope, + "PropertyDefinition > *.value": enterThisScope, + "PropertyDefinition > *.value:exit": exitThisScope, + StaticBlock: enterThisScope, + "StaticBlock:exit": exitThisScope, + + ThisExpression(node) { + if (!isMember(node.parent, "eval")) { + return; + } + + /* + * `this.eval` is found. + * Checks whether or not the value of `this` is the global object. + */ + if (!funcInfo.initialized) { + funcInfo.initialized = true; + funcInfo.defaultThis = astUtils.isDefaultThisBinding( + funcInfo.node, + sourceCode, + ); + } + + // `this` at the top level of scripts always refers to the global object + if ( + funcInfo.isTopLevelOfScript || + (!funcInfo.strict && funcInfo.defaultThis) + ) { + // `this.eval` is possible built-in `eval`. + report(node.parent); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-ex-assign.js b/node_modules/eslint/lib/rules/no-ex-assign.js new file mode 100644 index 00000000..6215a5e0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-ex-assign.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Rule to flag assignment of the exception parameter + * @author Stephen Murray + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning exceptions in `catch` clauses", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-ex-assign", + }, + + schema: [], + + messages: { + unexpected: "Do not assign to the exception parameter.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + astUtils + .getModifyingReferences(variable.references) + .forEach(reference => { + context.report({ + node: reference.identifier, + messageId: "unexpected", + }); + }); + } + + return { + CatchClause(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extend-native.js b/node_modules/eslint/lib/rules/no-extend-native.js new file mode 100644 index 00000000..4d3b8c20 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extend-native.js @@ -0,0 +1,180 @@ +/** + * @fileoverview Rule to flag adding properties to native object's prototypes. + * @author David Nelson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ exceptions: [] }], + + docs: { + description: "Disallow extending native types", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extend-native", + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: + "{{builtin}} prototype is read only, properties should not be added.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const exceptions = new Set(context.options[0].exceptions); + const modifiedBuiltins = new Set( + Object.keys(astUtils.ECMASCRIPT_GLOBALS) + .filter(builtin => builtin[0].toUpperCase() === builtin[0]) + .filter(builtin => !exceptions.has(builtin)), + ); + + /** + * Reports a lint error for the given node. + * @param {ASTNode} node The node to report. + * @param {string} builtin The name of the native builtin being extended. + * @returns {void} + */ + function reportNode(node, builtin) { + context.report({ + node, + messageId: "unexpected", + data: { + builtin, + }, + }); + } + + /** + * Check to see if the `prototype` property of the given object + * identifier node is being accessed. + * @param {ASTNode} identifierNode The Identifier representing the object + * to check. + * @returns {boolean} True if the identifier is the object of a + * MemberExpression and its `prototype` property is being accessed, + * false otherwise. + */ + function isPrototypePropertyAccessed(identifierNode) { + return Boolean( + identifierNode && + identifierNode.parent && + identifierNode.parent.type === "MemberExpression" && + identifierNode.parent.object === identifierNode && + astUtils.getStaticPropertyName(identifierNode.parent) === + "prototype", + ); + } + + /** + * Check if it's an assignment to the property of the given node. + * Example: `*.prop = 0` // the `*` is the given node. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if an assignment to the property of the node. + */ + function isAssigningToPropertyOf(node) { + return ( + node.parent.type === "MemberExpression" && + node.parent.object === node && + node.parent.parent.type === "AssignmentExpression" && + node.parent.parent.left === node.parent + ); + } + + /** + * Checks if the given node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`. + */ + function isInDefinePropertyCall(node) { + return ( + node.parent.type === "CallExpression" && + node.parent.arguments[0] === node && + astUtils.isSpecificMemberAccess( + node.parent.callee, + "Object", + /^definePropert(?:y|ies)$/u, + ) + ); + } + + /** + * Check to see if object prototype access is part of a prototype + * extension. There are three ways a prototype can be extended: + * 1. Assignment to prototype property (Object.prototype.foo = 1) + * 2. Object.defineProperty()/Object.defineProperties() on a prototype + * If prototype extension is detected, report the AssignmentExpression + * or CallExpression node. + * @param {ASTNode} identifierNode The Identifier representing the object + * which prototype is being accessed and possibly extended. + * @returns {void} + */ + function checkAndReportPrototypeExtension(identifierNode) { + if (!isPrototypePropertyAccessed(identifierNode)) { + return; // This is not `*.prototype` access. + } + + /* + * `identifierNode.parent` is a MemberExpression `*.prototype`. + * If it's an optional member access, it may be wrapped by a `ChainExpression` node. + */ + const prototypeNode = + identifierNode.parent.parent.type === "ChainExpression" + ? identifierNode.parent.parent + : identifierNode.parent; + + if (isAssigningToPropertyOf(prototypeNode)) { + // `*.prototype` -> MemberExpression -> AssignmentExpression + reportNode(prototypeNode.parent.parent, identifierNode.name); + } else if (isInDefinePropertyCall(prototypeNode)) { + // `*.prototype` -> CallExpression + reportNode(prototypeNode.parent, identifierNode.name); + } + } + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + modifiedBuiltins.forEach(builtin => { + const builtinVar = globalScope.set.get(builtin); + + if (builtinVar && builtinVar.references) { + builtinVar.references + .map(ref => ref.identifier) + .forEach(checkAndReportPrototypeExtension); + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-bind.js b/node_modules/eslint/lib/rules/no-extra-bind.js new file mode 100644 index 00000000..73164f8d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-bind.js @@ -0,0 +1,224 @@ +/** + * @fileoverview Rule to flag unnecessary bind calls + * @author Bence Dányi + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SIDE_EFFECT_FREE_NODE_TYPES = new Set([ + "Literal", + "Identifier", + "ThisExpression", + "FunctionExpression", +]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary calls to `.bind()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extra-bind", + }, + + schema: [], + fixable: "code", + + messages: { + unexpected: "The function binding is unnecessary.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Checks if a node is free of side effects. + * + * This check is stricter than it needs to be, in order to keep the implementation simple. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is known to be side-effect free, false otherwise. + */ + function isSideEffectFree(node) { + return SIDE_EFFECT_FREE_NODE_TYPES.has(node.type); + } + + /** + * Reports a given function node. + * @param {ASTNode} node A node to report. This is a FunctionExpression or + * an ArrowFunctionExpression. + * @returns {void} + */ + function report(node) { + const memberNode = node.parent; + const callNode = + memberNode.parent.type === "ChainExpression" + ? memberNode.parent.parent + : memberNode.parent; + + context.report({ + node: callNode, + messageId: "unexpected", + loc: memberNode.property.loc, + + fix(fixer) { + if (!isSideEffectFree(callNode.arguments[0])) { + return null; + } + + /* + * The list of the first/last token pair of a removal range. + * This is two parts because closing parentheses may exist between the method name and arguments. + * E.g. `(function(){}.bind ) (obj)` + * ^^^^^ ^^^^^ < removal ranges + * E.g. `(function(){}?.['bind'] ) ?.(obj)` + * ^^^^^^^^^^ ^^^^^^^ < removal ranges + */ + const tokenPairs = [ + [ + // `.`, `?.`, or `[` token. + sourceCode.getTokenAfter( + memberNode.object, + astUtils.isNotClosingParenToken, + ), + + // property name or `]` token. + sourceCode.getLastToken(memberNode), + ], + [ + // `?.` or `(` token of arguments. + sourceCode.getTokenAfter( + memberNode, + astUtils.isNotClosingParenToken, + ), + + // `)` token of arguments. + sourceCode.getLastToken(callNode), + ], + ]; + const firstTokenToRemove = tokenPairs[0][0]; + const lastTokenToRemove = tokenPairs[1][1]; + + if ( + sourceCode.commentsExistBetween( + firstTokenToRemove, + lastTokenToRemove, + ) + ) { + return null; + } + + return tokenPairs.map(([start, end]) => + fixer.removeRange([start.range[0], end.range[1]]), + ); + }, + }); + } + + /** + * Checks whether or not a given function node is the callee of `.bind()` + * method. + * + * e.g. `(function() {}.bind(foo))` + * @param {ASTNode} node A node to report. This is a FunctionExpression or + * an ArrowFunctionExpression. + * @returns {boolean} `true` if the node is the callee of `.bind()` method. + */ + function isCalleeOfBindMethod(node) { + if (!astUtils.isSpecificMemberAccess(node.parent, null, "bind")) { + return false; + } + + // The node of `*.bind` member access. + const bindNode = + node.parent.parent.type === "ChainExpression" + ? node.parent.parent + : node.parent; + + return ( + bindNode.parent.type === "CallExpression" && + bindNode.parent.callee === bindNode && + bindNode.parent.arguments.length === 1 && + bindNode.parent.arguments[0].type !== "SpreadElement" + ); + } + + /** + * Adds a scope information object to the stack. + * @param {ASTNode} node A node to add. This node is a FunctionExpression + * or a FunctionDeclaration node. + * @returns {void} + */ + function enterFunction(node) { + scopeInfo = { + isBound: isCalleeOfBindMethod(node), + thisFound: false, + upper: scopeInfo, + }; + } + + /** + * Removes the scope information object from the top of the stack. + * At the same time, this reports the function node if the function has + * `.bind()` and the `this` keywords found. + * @param {ASTNode} node A node to remove. This node is a + * FunctionExpression or a FunctionDeclaration node. + * @returns {void} + */ + function exitFunction(node) { + if (scopeInfo.isBound && !scopeInfo.thisFound) { + report(node); + } + + scopeInfo = scopeInfo.upper; + } + + /** + * Reports a given arrow function if the function is callee of `.bind()` + * method. + * @param {ASTNode} node A node to report. This node is an + * ArrowFunctionExpression. + * @returns {void} + */ + function exitArrowFunction(node) { + if (isCalleeOfBindMethod(node)) { + report(node); + } + } + + /** + * Set the mark as the `this` keyword was found in this scope. + * @returns {void} + */ + function markAsThisFound() { + if (scopeInfo) { + scopeInfo.thisFound = true; + } + } + + return { + "ArrowFunctionExpression:exit": exitArrowFunction, + FunctionDeclaration: enterFunction, + "FunctionDeclaration:exit": exitFunction, + FunctionExpression: enterFunction, + "FunctionExpression:exit": exitFunction, + ThisExpression: markAsThisFound, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-boolean-cast.js b/node_modules/eslint/lib/rules/no-extra-boolean-cast.js new file mode 100644 index 00000000..18019a8c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-boolean-cast.js @@ -0,0 +1,420 @@ +/** + * @fileoverview Rule to flag unnecessary double negation in Boolean contexts + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const eslintUtils = require("@eslint-community/eslint-utils"); + +const precedence = astUtils.getPrecedence; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{}], + + docs: { + description: "Disallow unnecessary boolean casts", + recommended: true, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-extra-boolean-cast", + }, + + schema: [ + { + anyOf: [ + { + type: "object", + properties: { + enforceForInnerExpressions: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + + // deprecated + { + type: "object", + properties: { + enforceForLogicalOperands: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + fixable: "code", + + messages: { + unexpectedCall: "Redundant Boolean call.", + unexpectedNegation: "Redundant double negation.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ enforceForLogicalOperands, enforceForInnerExpressions }] = + context.options; + + // Node types which have a test which will coerce values to booleans. + const BOOLEAN_NODE_TYPES = new Set([ + "IfStatement", + "DoWhileStatement", + "WhileStatement", + "ConditionalExpression", + "ForStatement", + ]); + + /** + * Check if a node is a Boolean function or constructor. + * @param {ASTNode} node the node + * @returns {boolean} If the node is Boolean function or constructor + */ + function isBooleanFunctionOrConstructorCall(node) { + // Boolean() and new Boolean() + return ( + (node.type === "CallExpression" || + node.type === "NewExpression") && + node.callee.type === "Identifier" && + node.callee.name === "Boolean" + ); + } + + /** + * Check if a node is in a context where its value would be coerced to a boolean at runtime. + * @param {ASTNode} node The node + * @returns {boolean} If it is in a boolean context + */ + function isInBooleanContext(node) { + return ( + (isBooleanFunctionOrConstructorCall(node.parent) && + node === node.parent.arguments[0]) || + (BOOLEAN_NODE_TYPES.has(node.parent.type) && + node === node.parent.test) || + // ! + (node.parent.type === "UnaryExpression" && + node.parent.operator === "!") + ); + } + + /** + * Checks whether the node is a context that should report an error + * Acts recursively if it is in a logical context + * @param {ASTNode} node the node + * @returns {boolean} If the node is in one of the flagged contexts + */ + function isInFlaggedContext(node) { + if (node.parent.type === "ChainExpression") { + return isInFlaggedContext(node.parent); + } + + /* + * legacy behavior - enforceForLogicalOperands will only recurse on + * logical expressions, not on other contexts. + * enforceForInnerExpressions will recurse on logical expressions + * as well as the other recursive syntaxes. + */ + + if (enforceForLogicalOperands || enforceForInnerExpressions) { + if (node.parent.type === "LogicalExpression") { + if ( + node.parent.operator === "||" || + node.parent.operator === "&&" + ) { + return isInFlaggedContext(node.parent); + } + + // Check the right hand side of a `??` operator. + if ( + enforceForInnerExpressions && + node.parent.operator === "??" && + node.parent.right === node + ) { + return isInFlaggedContext(node.parent); + } + } + } + + if (enforceForInnerExpressions) { + if ( + node.parent.type === "ConditionalExpression" && + (node.parent.consequent === node || + node.parent.alternate === node) + ) { + return isInFlaggedContext(node.parent); + } + + /* + * Check last expression only in a sequence, i.e. if ((1, 2, Boolean(3))) {}, since + * the others don't affect the result of the expression. + */ + if ( + node.parent.type === "SequenceExpression" && + node.parent.expressions.at(-1) === node + ) { + return isInFlaggedContext(node.parent); + } + } + + return isInBooleanContext(node); + } + + /** + * Check if a node has comments inside. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if it has comments inside. + */ + function hasCommentsInside(node) { + return Boolean(sourceCode.getCommentsInside(node).length); + } + + /** + * Checks if the given node is wrapped in grouping parentheses. Parentheses for constructs such as if() don't count. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is parenthesized. + * @private + */ + function isParenthesized(node) { + return eslintUtils.isParenthesized(1, node, sourceCode); + } + + /** + * Determines whether the given node needs to be parenthesized when replacing the previous node. + * It assumes that `previousNode` is the node to be reported by this rule, so it has a limited list + * of possible parent node types. By the same assumption, the node's role in a particular parent is already known. + * @param {ASTNode} previousNode Previous node. + * @param {ASTNode} node The node to check. + * @throws {Error} (Unreachable.) + * @returns {boolean} `true` if the node needs to be parenthesized. + */ + function needsParens(previousNode, node) { + if (previousNode.parent.type === "ChainExpression") { + return needsParens(previousNode.parent, node); + } + + if (isParenthesized(previousNode)) { + // parentheses around the previous node will stay, so there is no need for an additional pair + return false; + } + + // parent of the previous node will become parent of the replacement node + const parent = previousNode.parent; + + switch (parent.type) { + case "CallExpression": + case "NewExpression": + return node.type === "SequenceExpression"; + case "IfStatement": + case "DoWhileStatement": + case "WhileStatement": + case "ForStatement": + case "SequenceExpression": + return false; + case "ConditionalExpression": + if (previousNode === parent.test) { + return precedence(node) <= precedence(parent); + } + if ( + previousNode === parent.consequent || + previousNode === parent.alternate + ) { + return ( + precedence(node) < + precedence({ type: "AssignmentExpression" }) + ); + } + + /* c8 ignore next */ + throw new Error( + "Ternary child must be test, consequent, or alternate.", + ); + case "UnaryExpression": + return precedence(node) < precedence(parent); + case "LogicalExpression": + if ( + astUtils.isMixedLogicalAndCoalesceExpressions( + node, + parent, + ) + ) { + return true; + } + if (previousNode === parent.left) { + return precedence(node) < precedence(parent); + } + return precedence(node) <= precedence(parent); + + /* c8 ignore next */ + default: + throw new Error(`Unexpected parent type: ${parent.type}`); + } + } + + return { + UnaryExpression(node) { + const parent = node.parent; + + // Exit early if it's guaranteed not to match + if ( + node.operator !== "!" || + parent.type !== "UnaryExpression" || + parent.operator !== "!" + ) { + return; + } + + if (isInFlaggedContext(parent)) { + context.report({ + node: parent, + messageId: "unexpectedNegation", + fix(fixer) { + if (hasCommentsInside(parent)) { + return null; + } + + if (needsParens(parent, node.argument)) { + return fixer.replaceText( + parent, + `(${sourceCode.getText(node.argument)})`, + ); + } + + let prefix = ""; + const tokenBefore = + sourceCode.getTokenBefore(parent); + const firstReplacementToken = + sourceCode.getFirstToken(node.argument); + + if ( + tokenBefore && + tokenBefore.range[1] === parent.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + firstReplacementToken, + ) + ) { + prefix = " "; + } + + return fixer.replaceText( + parent, + prefix + sourceCode.getText(node.argument), + ); + }, + }); + } + }, + + CallExpression(node) { + if ( + node.callee.type !== "Identifier" || + node.callee.name !== "Boolean" + ) { + return; + } + + if (isInFlaggedContext(node)) { + context.report({ + node, + messageId: "unexpectedCall", + fix(fixer) { + const parent = node.parent; + + if (node.arguments.length === 0) { + if ( + parent.type === "UnaryExpression" && + parent.operator === "!" + ) { + /* + * !Boolean() -> true + */ + + if (hasCommentsInside(parent)) { + return null; + } + + const replacement = "true"; + let prefix = ""; + const tokenBefore = + sourceCode.getTokenBefore(parent); + + if ( + tokenBefore && + tokenBefore.range[1] === + parent.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + replacement, + ) + ) { + prefix = " "; + } + + return fixer.replaceText( + parent, + prefix + replacement, + ); + } + + /* + * Boolean() -> false + */ + + if (hasCommentsInside(node)) { + return null; + } + + return fixer.replaceText(node, "false"); + } + + if (node.arguments.length === 1) { + const argument = node.arguments[0]; + + if ( + argument.type === "SpreadElement" || + hasCommentsInside(node) + ) { + return null; + } + + /* + * Boolean(expression) -> expression + */ + + if (needsParens(node, argument)) { + return fixer.replaceText( + node, + `(${sourceCode.getText(argument)})`, + ); + } + + return fixer.replaceText( + node, + sourceCode.getText(argument), + ); + } + + // two or more arguments + return null; + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-label.js b/node_modules/eslint/lib/rules/no-extra-label.js new file mode 100644 index 00000000..c191eee7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-label.js @@ -0,0 +1,169 @@ +/** + * @fileoverview Rule to disallow unnecessary labels + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary labels", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-extra-label", + }, + + schema: [], + fixable: "code", + + messages: { + unexpected: "This label '{{name}}' is unnecessary.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Creates a new scope with a breakable statement. + * @param {ASTNode} node A node to create. This is a BreakableStatement. + * @returns {void} + */ + function enterBreakableStatement(node) { + scopeInfo = { + label: + node.parent.type === "LabeledStatement" + ? node.parent.label + : null, + breakable: true, + upper: scopeInfo, + }; + } + + /** + * Removes the top scope of the stack. + * @returns {void} + */ + function exitBreakableStatement() { + scopeInfo = scopeInfo.upper; + } + + /** + * Creates a new scope with a labeled statement. + * + * This ignores it if the body is a breakable statement. + * In this case it's handled in the `enterBreakableStatement` function. + * @param {ASTNode} node A node to create. This is a LabeledStatement. + * @returns {void} + */ + function enterLabeledStatement(node) { + if (!astUtils.isBreakableStatement(node.body)) { + scopeInfo = { + label: node.label, + breakable: false, + upper: scopeInfo, + }; + } + } + + /** + * Removes the top scope of the stack. + * + * This ignores it if the body is a breakable statement. + * In this case it's handled in the `exitBreakableStatement` function. + * @param {ASTNode} node A node. This is a LabeledStatement. + * @returns {void} + */ + function exitLabeledStatement(node) { + if (!astUtils.isBreakableStatement(node.body)) { + scopeInfo = scopeInfo.upper; + } + } + + /** + * Reports a given control node if it's unnecessary. + * @param {ASTNode} node A node. This is a BreakStatement or a + * ContinueStatement. + * @returns {void} + */ + function reportIfUnnecessary(node) { + if (!node.label) { + return; + } + + const labelNode = node.label; + + for (let info = scopeInfo; info !== null; info = info.upper) { + if ( + info.breakable || + (info.label && info.label.name === labelNode.name) + ) { + if ( + info.breakable && + info.label && + info.label.name === labelNode.name + ) { + context.report({ + node: labelNode, + messageId: "unexpected", + data: labelNode, + fix(fixer) { + const breakOrContinueToken = + sourceCode.getFirstToken(node); + + if ( + sourceCode.commentsExistBetween( + breakOrContinueToken, + labelNode, + ) + ) { + return null; + } + + return fixer.removeRange([ + breakOrContinueToken.range[1], + labelNode.range[1], + ]); + }, + }); + } + return; + } + } + } + + return { + WhileStatement: enterBreakableStatement, + "WhileStatement:exit": exitBreakableStatement, + DoWhileStatement: enterBreakableStatement, + "DoWhileStatement:exit": exitBreakableStatement, + ForStatement: enterBreakableStatement, + "ForStatement:exit": exitBreakableStatement, + ForInStatement: enterBreakableStatement, + "ForInStatement:exit": exitBreakableStatement, + ForOfStatement: enterBreakableStatement, + "ForOfStatement:exit": exitBreakableStatement, + SwitchStatement: enterBreakableStatement, + "SwitchStatement:exit": exitBreakableStatement, + LabeledStatement: enterLabeledStatement, + "LabeledStatement:exit": exitLabeledStatement, + BreakStatement: reportIfUnnecessary, + ContinueStatement: reportIfUnnecessary, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-parens.js b/node_modules/eslint/lib/rules/no-extra-parens.js new file mode 100644 index 00000000..4f65b8ac --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-parens.js @@ -0,0 +1,1669 @@ +/** + * @fileoverview Disallow parenthesising higher precedence subexpressions. + * @author Michael Ficarra + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const { + isParenthesized: isParenthesizedRaw, +} = require("@eslint-community/eslint-utils"); +const astUtils = require("./utils/ast-utils.js"); + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-extra-parens", + url: "https://eslint.style/rules/js/no-extra-parens", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow unnecessary parentheses", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extra-parens", + }, + + fixable: "code", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["functions"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["all"], + }, + { + type: "object", + properties: { + conditionalAssign: { type: "boolean" }, + ternaryOperandBinaryExpressions: { + type: "boolean", + }, + nestedBinaryExpressions: { type: "boolean" }, + returnAssign: { type: "boolean" }, + ignoreJSX: { + enum: [ + "none", + "all", + "single-line", + "multi-line", + ], + }, + enforceForArrowConditionals: { + type: "boolean", + }, + enforceForSequenceExpressions: { + type: "boolean", + }, + enforceForNewInMemberExpressions: { + type: "boolean", + }, + enforceForFunctionPrototypeMethods: { + type: "boolean", + }, + allowParensAfterCommentPattern: { + type: "string", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + messages: { + unexpected: "Unnecessary parentheses around expression.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const tokensToIgnore = new WeakSet(); + const precedence = astUtils.getPrecedence; + const ALL_NODES = context.options[0] !== "functions"; + const EXCEPT_COND_ASSIGN = + ALL_NODES && + context.options[1] && + context.options[1].conditionalAssign === false; + const EXCEPT_COND_TERNARY = + ALL_NODES && + context.options[1] && + context.options[1].ternaryOperandBinaryExpressions === false; + const NESTED_BINARY = + ALL_NODES && + context.options[1] && + context.options[1].nestedBinaryExpressions === false; + const EXCEPT_RETURN_ASSIGN = + ALL_NODES && + context.options[1] && + context.options[1].returnAssign === false; + const IGNORE_JSX = + ALL_NODES && context.options[1] && context.options[1].ignoreJSX; + const IGNORE_ARROW_CONDITIONALS = + ALL_NODES && + context.options[1] && + context.options[1].enforceForArrowConditionals === false; + const IGNORE_SEQUENCE_EXPRESSIONS = + ALL_NODES && + context.options[1] && + context.options[1].enforceForSequenceExpressions === false; + const IGNORE_NEW_IN_MEMBER_EXPR = + ALL_NODES && + context.options[1] && + context.options[1].enforceForNewInMemberExpressions === false; + const IGNORE_FUNCTION_PROTOTYPE_METHODS = + ALL_NODES && + context.options[1] && + context.options[1].enforceForFunctionPrototypeMethods === false; + const ALLOW_PARENS_AFTER_COMMENT_PATTERN = + ALL_NODES && + context.options[1] && + context.options[1].allowParensAfterCommentPattern; + + const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({ + type: "AssignmentExpression", + }); + const PRECEDENCE_OF_UPDATE_EXPR = precedence({ + type: "UpdateExpression", + }); + + let reportsBuffer; + + /** + * Determines whether the given node is a `call` or `apply` method call, invoked directly on a `FunctionExpression` node. + * Example: function(){}.call() + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is an immediate `call` or `apply` method call. + * @private + */ + function isImmediateFunctionPrototypeMethodCall(node) { + const callNode = astUtils.skipChainExpression(node); + + if (callNode.type !== "CallExpression") { + return false; + } + const callee = astUtils.skipChainExpression(callNode.callee); + + return ( + callee.type === "MemberExpression" && + callee.object.type === "FunctionExpression" && + ["call", "apply"].includes( + astUtils.getStaticPropertyName(callee), + ) + ); + } + + /** + * Determines if this rule should be enforced for a node given the current configuration. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the rule should be enforced for this node. + * @private + */ + function ruleApplies(node) { + if (node.type === "JSXElement" || node.type === "JSXFragment") { + const isSingleLine = node.loc.start.line === node.loc.end.line; + + switch (IGNORE_JSX) { + // Exclude this JSX element from linting + case "all": + return false; + + // Exclude this JSX element if it is multi-line element + case "multi-line": + return isSingleLine; + + // Exclude this JSX element if it is single-line element + case "single-line": + return !isSingleLine; + + // Nothing special to be done for JSX elements + case "none": + break; + + // no default + } + } + + if ( + node.type === "SequenceExpression" && + IGNORE_SEQUENCE_EXPRESSIONS + ) { + return false; + } + + if ( + isImmediateFunctionPrototypeMethodCall(node) && + IGNORE_FUNCTION_PROTOTYPE_METHODS + ) { + return false; + } + + return ( + ALL_NODES || + node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression" + ); + } + + /** + * Determines if a node is surrounded by parentheses. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is parenthesised. + * @private + */ + function isParenthesised(node) { + return isParenthesizedRaw(1, node, sourceCode); + } + + /** + * Determines if a node is surrounded by parentheses twice. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is doubly parenthesised. + * @private + */ + function isParenthesisedTwice(node) { + return isParenthesizedRaw(2, node, sourceCode); + } + + /** + * Determines if a node is surrounded by (potentially) invalid parentheses. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is incorrectly parenthesised. + * @private + */ + function hasExcessParens(node) { + return ruleApplies(node) && isParenthesised(node); + } + + /** + * Determines if a node that is expected to be parenthesised is surrounded by + * (potentially) invalid extra parentheses. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is has an unexpected extra pair of parentheses. + * @private + */ + function hasDoubleExcessParens(node) { + return ruleApplies(node) && isParenthesisedTwice(node); + } + + /** + * Determines if a node that is expected to be parenthesised is surrounded by + * (potentially) invalid extra parentheses with considering precedence level of the node. + * If the preference level of the node is not higher or equal to precedence lower limit, it also checks + * whether the node is surrounded by parentheses twice or not. + * @param {ASTNode} node The node to be checked. + * @param {number} precedenceLowerLimit The lower limit of precedence. + * @returns {boolean} True if the node is has an unexpected extra pair of parentheses. + * @private + */ + function hasExcessParensWithPrecedence(node, precedenceLowerLimit) { + if (ruleApplies(node) && isParenthesised(node)) { + if ( + precedence(node) >= precedenceLowerLimit || + isParenthesisedTwice(node) + ) { + return true; + } + } + return false; + } + + /** + * Determines if a node test expression is allowed to have a parenthesised assignment + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the assignment can be parenthesised. + * @private + */ + function isCondAssignException(node) { + return ( + EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression" + ); + } + + /** + * Determines if a node is in a return statement + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is in a return statement. + * @private + */ + function isInReturnStatement(node) { + for ( + let currentNode = node; + currentNode; + currentNode = currentNode.parent + ) { + if ( + currentNode.type === "ReturnStatement" || + (currentNode.type === "ArrowFunctionExpression" && + currentNode.body.type !== "BlockStatement") + ) { + return true; + } + } + + return false; + } + + /** + * Determines if a constructor function is newed-up with parens + * @param {ASTNode} newExpression The NewExpression node to be checked. + * @returns {boolean} True if the constructor is called with parens. + * @private + */ + function isNewExpressionWithParens(newExpression) { + const lastToken = sourceCode.getLastToken(newExpression); + const penultimateToken = sourceCode.getTokenBefore(lastToken); + + return ( + newExpression.arguments.length > 0 || + // The expression should end with its own parens, e.g., new new foo() is not a new expression with parens + (astUtils.isOpeningParenToken(penultimateToken) && + astUtils.isClosingParenToken(lastToken) && + newExpression.callee.range[1] < newExpression.range[1]) + ); + } + + /** + * Determines if a node is or contains an assignment expression + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is or contains an assignment expression. + * @private + */ + function containsAssignment(node) { + if (node.type === "AssignmentExpression") { + return true; + } + if ( + node.type === "ConditionalExpression" && + (node.consequent.type === "AssignmentExpression" || + node.alternate.type === "AssignmentExpression") + ) { + return true; + } + if ( + (node.left && node.left.type === "AssignmentExpression") || + (node.right && node.right.type === "AssignmentExpression") + ) { + return true; + } + + return false; + } + + /** + * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the assignment can be parenthesised. + * @private + */ + function isReturnAssignException(node) { + if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) { + return false; + } + + if (node.type === "ReturnStatement") { + return node.argument && containsAssignment(node.argument); + } + if ( + node.type === "ArrowFunctionExpression" && + node.body.type !== "BlockStatement" + ) { + return containsAssignment(node.body); + } + return containsAssignment(node); + } + + /** + * Determines if a node following a [no LineTerminator here] restriction is + * surrounded by (potentially) invalid extra parentheses. + * @param {Token} token The token preceding the [no LineTerminator here] restriction. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is incorrectly parenthesised. + * @private + */ + function hasExcessParensNoLineTerminator(token, node) { + if (token.loc.end.line === node.loc.start.line) { + return hasExcessParens(node); + } + + return hasDoubleExcessParens(node); + } + + /** + * Determines whether a node should be preceded by an additional space when removing parens + * @param {ASTNode} node node to evaluate; must be surrounded by parentheses + * @returns {boolean} `true` if a space should be inserted before the node + * @private + */ + function requiresLeadingSpace(node) { + const leftParenToken = sourceCode.getTokenBefore(node); + const tokenBeforeLeftParen = sourceCode.getTokenBefore( + leftParenToken, + { includeComments: true }, + ); + const tokenAfterLeftParen = sourceCode.getTokenAfter( + leftParenToken, + { includeComments: true }, + ); + + return ( + tokenBeforeLeftParen && + tokenBeforeLeftParen.range[1] === leftParenToken.range[0] && + leftParenToken.range[1] === tokenAfterLeftParen.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBeforeLeftParen, + tokenAfterLeftParen, + ) + ); + } + + /** + * Determines whether a node should be followed by an additional space when removing parens + * @param {ASTNode} node node to evaluate; must be surrounded by parentheses + * @returns {boolean} `true` if a space should be inserted after the node + * @private + */ + function requiresTrailingSpace(node) { + const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 }); + const rightParenToken = nextTwoTokens[0]; + const tokenAfterRightParen = nextTwoTokens[1]; + const tokenBeforeRightParen = sourceCode.getLastToken(node); + + return ( + rightParenToken && + tokenAfterRightParen && + !sourceCode.isSpaceBetweenTokens( + rightParenToken, + tokenAfterRightParen, + ) && + !astUtils.canTokensBeAdjacent( + tokenBeforeRightParen, + tokenAfterRightParen, + ) + ); + } + + /** + * Determines if a given expression node is an IIFE + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if the given node is an IIFE + */ + function isIIFE(node) { + const maybeCallNode = astUtils.skipChainExpression(node); + + return ( + maybeCallNode.type === "CallExpression" && + maybeCallNode.callee.type === "FunctionExpression" + ); + } + + /** + * Determines if the given node can be the assignment target in destructuring or the LHS of an assignment. + * This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax, + * such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary. + * @param {ASTNode} [node] The node to check + * @returns {boolean} `true` if the given node can be a valid assignment target + */ + function canBeAssignmentTarget(node) { + return ( + node && + (node.type === "Identifier" || node.type === "MemberExpression") + ); + } + + /** + * Checks if a node is fixable. + * A node is fixable if removing a single pair of surrounding parentheses does not turn it + * into a directive after fixing other nodes. + * Almost all nodes are fixable, except if all of the following conditions are met: + * The node is a string Literal + * It has a single pair of parentheses + * It is the only child of an ExpressionStatement + * @param {ASTNode} node The node to evaluate. + * @returns {boolean} Whether or not the node is fixable. + * @private + */ + function isFixable(node) { + // if it's not a string literal it can be autofixed + if (node.type !== "Literal" || typeof node.value !== "string") { + return true; + } + if (isParenthesisedTwice(node)) { + return true; + } + return !astUtils.isTopLevelExpressionStatement(node.parent); + } + + /** + * Report the node + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function report(node) { + const leftParenToken = sourceCode.getTokenBefore(node); + const rightParenToken = sourceCode.getTokenAfter(node); + + if (!isParenthesisedTwice(node)) { + if (tokensToIgnore.has(sourceCode.getFirstToken(node))) { + return; + } + + if (isIIFE(node) && !isParenthesised(node.callee)) { + return; + } + + if (ALLOW_PARENS_AFTER_COMMENT_PATTERN) { + const commentsBeforeLeftParenToken = + sourceCode.getCommentsBefore(leftParenToken); + const totalCommentsBeforeLeftParenTokenCount = + commentsBeforeLeftParenToken.length; + const ignorePattern = new RegExp( + ALLOW_PARENS_AFTER_COMMENT_PATTERN, + "u", + ); + + if ( + totalCommentsBeforeLeftParenTokenCount > 0 && + ignorePattern.test( + commentsBeforeLeftParenToken[ + totalCommentsBeforeLeftParenTokenCount - 1 + ].value, + ) + ) { + return; + } + } + } + + /** + * Finishes reporting + * @returns {void} + * @private + */ + function finishReport() { + context.report({ + node, + loc: leftParenToken.loc, + messageId: "unexpected", + fix: isFixable(node) + ? fixer => { + const parenthesizedSource = + sourceCode.text.slice( + leftParenToken.range[1], + rightParenToken.range[0], + ); + + return fixer.replaceTextRange( + [ + leftParenToken.range[0], + rightParenToken.range[1], + ], + (requiresLeadingSpace(node) ? " " : "") + + parenthesizedSource + + (requiresTrailingSpace(node) + ? " " + : ""), + ); + } + : null, + }); + } + + if (reportsBuffer) { + reportsBuffer.reports.push({ node, finishReport }); + return; + } + + finishReport(); + } + + /** + * Evaluate a argument of the node. + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkArgumentWithPrecedence(node) { + if ( + hasExcessParensWithPrecedence(node.argument, precedence(node)) + ) { + report(node.argument); + } + } + + /** + * Check if a member expression contains a call expression + * @param {ASTNode} node MemberExpression node to evaluate + * @returns {boolean} true if found, false if not + */ + function doesMemberExpressionContainCallExpression(node) { + let currentNode = node.object; + let currentNodeType = node.object.type; + + while (currentNodeType === "MemberExpression") { + currentNode = currentNode.object; + currentNodeType = currentNode.type; + } + + return currentNodeType === "CallExpression"; + } + + /** + * Evaluate a new call + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkCallNew(node) { + const callee = node.callee; + + if (hasExcessParensWithPrecedence(callee, precedence(node))) { + if ( + hasDoubleExcessParens(callee) || + !( + isIIFE(node) || + // (new A)(); new (new A)(); + (callee.type === "NewExpression" && + !isNewExpressionWithParens(callee) && + !( + node.type === "NewExpression" && + !isNewExpressionWithParens(node) + )) || + // new (a().b)(); new (a.b().c); + (node.type === "NewExpression" && + callee.type === "MemberExpression" && + doesMemberExpressionContainCallExpression( + callee, + )) || + // (a?.b)(); (a?.())(); + (!node.optional && callee.type === "ChainExpression") + ) + ) { + report(node.callee); + } + } + node.arguments + .filter(arg => + hasExcessParensWithPrecedence( + arg, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ), + ) + .forEach(report); + } + + /** + * Evaluate binary logicals + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkBinaryLogical(node) { + const prec = precedence(node); + const leftPrecedence = precedence(node.left); + const rightPrecedence = precedence(node.right); + const isExponentiation = node.operator === "**"; + const shouldSkipLeft = + NESTED_BINARY && + (node.left.type === "BinaryExpression" || + node.left.type === "LogicalExpression"); + const shouldSkipRight = + NESTED_BINARY && + (node.right.type === "BinaryExpression" || + node.right.type === "LogicalExpression"); + + if (!shouldSkipLeft && hasExcessParens(node.left)) { + if ( + (!( + ["AwaitExpression", "UnaryExpression"].includes( + node.left.type, + ) && isExponentiation + ) && + !astUtils.isMixedLogicalAndCoalesceExpressions( + node.left, + node, + ) && + (leftPrecedence > prec || + (leftPrecedence === prec && !isExponentiation))) || + isParenthesisedTwice(node.left) + ) { + report(node.left); + } + } + + if (!shouldSkipRight && hasExcessParens(node.right)) { + if ( + (!astUtils.isMixedLogicalAndCoalesceExpressions( + node.right, + node, + ) && + (rightPrecedence > prec || + (rightPrecedence === prec && isExponentiation))) || + isParenthesisedTwice(node.right) + ) { + report(node.right); + } + } + } + + /** + * Check the parentheses around the super class of the given class definition. + * @param {ASTNode} node The node of class declarations to check. + * @returns {void} + */ + function checkClass(node) { + if (!node.superClass) { + return; + } + + /* + * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. + * Otherwise, parentheses are needed. + */ + const hasExtraParens = + precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR + ? hasExcessParens(node.superClass) + : hasDoubleExcessParens(node.superClass); + + if (hasExtraParens) { + report(node.superClass); + } + } + + /** + * Check the parentheses around the argument of the given spread operator. + * @param {ASTNode} node The node of spread elements/properties to check. + * @returns {void} + */ + function checkSpreadOperator(node) { + if ( + hasExcessParensWithPrecedence( + node.argument, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.argument); + } + } + + /** + * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration + * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node + * @returns {void} + */ + function checkExpressionOrExportStatement(node) { + const firstToken = isParenthesised(node) + ? sourceCode.getTokenBefore(node) + : sourceCode.getFirstToken(node); + const secondToken = sourceCode.getTokenAfter( + firstToken, + astUtils.isNotOpeningParenToken, + ); + const thirdToken = secondToken + ? sourceCode.getTokenAfter(secondToken) + : null; + const tokenAfterClosingParens = secondToken + ? sourceCode.getTokenAfter( + secondToken, + astUtils.isNotClosingParenToken, + ) + : null; + + if ( + astUtils.isOpeningParenToken(firstToken) && + (astUtils.isOpeningBraceToken(secondToken) || + (secondToken.type === "Keyword" && + (secondToken.value === "function" || + secondToken.value === "class" || + (secondToken.value === "let" && + tokenAfterClosingParens && + (astUtils.isOpeningBracketToken( + tokenAfterClosingParens, + ) || + tokenAfterClosingParens.type === + "Identifier")))) || + (secondToken && + secondToken.type === "Identifier" && + secondToken.value === "async" && + thirdToken && + thirdToken.type === "Keyword" && + thirdToken.value === "function")) + ) { + tokensToIgnore.add(secondToken); + } + + const hasExtraParens = + node.parent.type === "ExportDefaultDeclaration" + ? hasExcessParensWithPrecedence( + node, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + : hasExcessParens(node); + + if (hasExtraParens) { + report(node); + } + } + + /** + * Finds the path from the given node to the specified ancestor. + * @param {ASTNode} node First node in the path. + * @param {ASTNode} ancestor Last node in the path. + * @returns {ASTNode[]} Path, including both nodes. + * @throws {Error} If the given node does not have the specified ancestor. + */ + function pathToAncestor(node, ancestor) { + const path = [node]; + let currentNode = node; + + while (currentNode !== ancestor) { + currentNode = currentNode.parent; + + /* c8 ignore start */ + if (currentNode === null) { + throw new Error( + "Nodes are not in the ancestor-descendant relationship.", + ); + } /* c8 ignore stop */ + + path.push(currentNode); + } + + return path; + } + + /** + * Finds the path from the given node to the specified descendant. + * @param {ASTNode} node First node in the path. + * @param {ASTNode} descendant Last node in the path. + * @returns {ASTNode[]} Path, including both nodes. + * @throws {Error} If the given node does not have the specified descendant. + */ + function pathToDescendant(node, descendant) { + return pathToAncestor(descendant, node).reverse(); + } + + /** + * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer + * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop. + * @param {ASTNode} node Ancestor of an 'in' expression. + * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself. + * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis. + */ + function isSafelyEnclosingInExpression(node, child) { + switch (node.type) { + case "ArrayExpression": + case "ArrayPattern": + case "BlockStatement": + case "ObjectExpression": + case "ObjectPattern": + case "TemplateLiteral": + return true; + case "ArrowFunctionExpression": + case "FunctionExpression": + return node.params.includes(child); + case "CallExpression": + case "NewExpression": + return node.arguments.includes(child); + case "MemberExpression": + return node.computed && node.property === child; + case "ConditionalExpression": + return node.consequent === child; + default: + return false; + } + } + + /** + * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately. + * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings. + * @returns {void} + */ + function startNewReportsBuffering() { + reportsBuffer = { + upper: reportsBuffer, + inExpressionNodes: [], + reports: [], + }; + } + + /** + * Ends the current reports buffering. + * @returns {void} + */ + function endCurrentReportsBuffering() { + const { upper, inExpressionNodes, reports } = reportsBuffer; + + if (upper) { + upper.inExpressionNodes.push(...inExpressionNodes); + upper.reports.push(...reports); + } else { + // flush remaining reports + reports.forEach(({ finishReport }) => finishReport()); + } + + reportsBuffer = upper; + } + + /** + * Checks whether the given node is in the current reports buffer. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is in the current buffer, false otherwise. + */ + function isInCurrentReportsBuffer(node) { + return reportsBuffer.reports.some(r => r.node === node); + } + + /** + * Removes the given node from the current reports buffer. + * @param {ASTNode} node Node to remove. + * @returns {void} + */ + function removeFromCurrentReportsBuffer(node) { + reportsBuffer.reports = reportsBuffer.reports.filter( + r => r.node !== node, + ); + } + + /** + * Checks whether a node is a MemberExpression at NewExpression's callee. + * @param {ASTNode} node node to check. + * @returns {boolean} True if the node is a MemberExpression at NewExpression's callee. false otherwise. + */ + function isMemberExpInNewCallee(node) { + if (node.type === "MemberExpression") { + return node.parent.type === "NewExpression" && + node.parent.callee === node + ? true + : node.parent.object === node && + isMemberExpInNewCallee(node.parent); + } + return false; + } + + /** + * Checks if the left-hand side of an assignment is an identifier, the operator is one of + * `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous class or function. + * + * As per https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation, an + * assignment involving one of the operators `=`, `&&=`, `||=` or `??=` where the right-hand + * side is an anonymous class or function and the left-hand side is an *unparenthesized* + * identifier has different semantics than other assignments. + * Specifically, when an expression like `foo = function () {}` is evaluated, `foo.name` + * will be set to the string "foo", i.e. the identifier name. The same thing does not happen + * when evaluating `(foo) = function () {}`. + * Since the parenthesizing of the identifier in the left-hand side is significant in this + * special case, the parentheses, if present, should not be flagged as unnecessary. + * @param {ASTNode} node an AssignmentExpression node. + * @returns {boolean} `true` if the left-hand side of the assignment is an identifier, the + * operator is one of `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous + * class or function; otherwise, `false`. + */ + function isAnonymousFunctionAssignmentException({ + left, + operator, + right, + }) { + if ( + left.type === "Identifier" && + ["=", "&&=", "||=", "??="].includes(operator) + ) { + const rhsType = right.type; + + if (rhsType === "ArrowFunctionExpression") { + return true; + } + if ( + (rhsType === "FunctionExpression" || + rhsType === "ClassExpression") && + !right.id + ) { + return true; + } + } + return false; + } + + return { + ArrayExpression(node) { + node.elements + .filter( + e => + e && + hasExcessParensWithPrecedence( + e, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ), + ) + .forEach(report); + }, + + ArrayPattern(node) { + node.elements + .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e)) + .forEach(report); + }, + + ArrowFunctionExpression(node) { + if (isReturnAssignException(node)) { + return; + } + + if ( + node.body.type === "ConditionalExpression" && + IGNORE_ARROW_CONDITIONALS + ) { + return; + } + + if (node.body.type !== "BlockStatement") { + const firstBodyToken = sourceCode.getFirstToken( + node.body, + astUtils.isNotOpeningParenToken, + ); + const tokenBeforeFirst = + sourceCode.getTokenBefore(firstBodyToken); + + if ( + astUtils.isOpeningParenToken(tokenBeforeFirst) && + astUtils.isOpeningBraceToken(firstBodyToken) + ) { + tokensToIgnore.add(firstBodyToken); + } + if ( + hasExcessParensWithPrecedence( + node.body, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.body); + } + } + }, + + AssignmentExpression(node) { + if ( + canBeAssignmentTarget(node.left) && + hasExcessParens(node.left) && + (!isAnonymousFunctionAssignmentException(node) || + isParenthesisedTwice(node.left)) + ) { + report(node.left); + } + + if ( + !isReturnAssignException(node) && + hasExcessParensWithPrecedence(node.right, precedence(node)) + ) { + report(node.right); + } + }, + + BinaryExpression(node) { + if (reportsBuffer && node.operator === "in") { + reportsBuffer.inExpressionNodes.push(node); + } + + checkBinaryLogical(node); + }, + + CallExpression: checkCallNew, + + ConditionalExpression(node) { + if (isReturnAssignException(node)) { + return; + } + + const availableTypes = new Set([ + "BinaryExpression", + "LogicalExpression", + ]); + + if ( + !( + EXCEPT_COND_TERNARY && + availableTypes.has(node.test.type) + ) && + !isCondAssignException(node) && + hasExcessParensWithPrecedence( + node.test, + precedence({ + type: "LogicalExpression", + operator: "||", + }), + ) + ) { + report(node.test); + } + + if ( + !( + EXCEPT_COND_TERNARY && + availableTypes.has(node.consequent.type) + ) && + hasExcessParensWithPrecedence( + node.consequent, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.consequent); + } + + if ( + !( + EXCEPT_COND_TERNARY && + availableTypes.has(node.alternate.type) + ) && + hasExcessParensWithPrecedence( + node.alternate, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.alternate); + } + }, + + DoWhileStatement(node) { + if ( + hasExcessParens(node.test) && + !isCondAssignException(node) + ) { + report(node.test); + } + }, + + ExportDefaultDeclaration: node => + checkExpressionOrExportStatement(node.declaration), + ExpressionStatement: node => + checkExpressionOrExportStatement(node.expression), + + ForInStatement(node) { + if (node.left.type !== "VariableDeclaration") { + const firstLeftToken = sourceCode.getFirstToken( + node.left, + astUtils.isNotOpeningParenToken, + ); + + if ( + firstLeftToken.value === "let" && + astUtils.isOpeningBracketToken( + sourceCode.getTokenAfter( + firstLeftToken, + astUtils.isNotClosingParenToken, + ), + ) + ) { + // ForInStatement#left expression cannot start with `let[`. + tokensToIgnore.add(firstLeftToken); + } + } + + if (hasExcessParens(node.left)) { + report(node.left); + } + + if (hasExcessParens(node.right)) { + report(node.right); + } + }, + + ForOfStatement(node) { + if (node.left.type !== "VariableDeclaration") { + const firstLeftToken = sourceCode.getFirstToken( + node.left, + astUtils.isNotOpeningParenToken, + ); + + if (firstLeftToken.value === "let") { + // ForOfStatement#left expression cannot start with `let`. + tokensToIgnore.add(firstLeftToken); + } + } + + if (hasExcessParens(node.left)) { + report(node.left); + } + + if ( + hasExcessParensWithPrecedence( + node.right, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.right); + } + }, + + ForStatement(node) { + if ( + node.test && + hasExcessParens(node.test) && + !isCondAssignException(node) + ) { + report(node.test); + } + + if (node.update && hasExcessParens(node.update)) { + report(node.update); + } + + if (node.init) { + if (node.init.type !== "VariableDeclaration") { + const firstToken = sourceCode.getFirstToken( + node.init, + astUtils.isNotOpeningParenToken, + ); + + if ( + firstToken.value === "let" && + astUtils.isOpeningBracketToken( + sourceCode.getTokenAfter( + firstToken, + astUtils.isNotClosingParenToken, + ), + ) + ) { + // ForStatement#init expression cannot start with `let[`. + tokensToIgnore.add(firstToken); + } + } + + startNewReportsBuffering(); + + if (hasExcessParens(node.init)) { + report(node.init); + } + } + }, + + "ForStatement > *.init:exit"(node) { + /* + * Removing parentheses around `in` expressions might change semantics and cause errors. + * + * For example, this valid for loop: + * for (let a = (b in c); ;); + * after removing parentheses would be treated as an invalid for-in loop: + * for (let a = b in c; ;); + */ + + if (reportsBuffer.reports.length) { + reportsBuffer.inExpressionNodes.forEach( + inExpressionNode => { + const path = pathToDescendant( + node, + inExpressionNode, + ); + let nodeToExclude; + + for (let i = 0; i < path.length; i++) { + const pathNode = path[i]; + + if (i < path.length - 1) { + const nextPathNode = path[i + 1]; + + if ( + isSafelyEnclosingInExpression( + pathNode, + nextPathNode, + ) + ) { + // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]'). + return; + } + } + + if (isParenthesised(pathNode)) { + if (isInCurrentReportsBuffer(pathNode)) { + // This node was supposed to be reported, but parentheses might be necessary. + + if (isParenthesisedTwice(pathNode)) { + /* + * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses. + * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses. + * The remaining pair is safely enclosing the 'in' expression. + */ + return; + } + + // Exclude the outermost node only. + if (!nodeToExclude) { + nodeToExclude = pathNode; + } + + // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside. + } else { + // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'. + return; + } + } + } + + // Exclude the node from the list (i.e. treat parentheses as necessary) + removeFromCurrentReportsBuffer(nodeToExclude); + }, + ); + } + + endCurrentReportsBuffering(); + }, + + IfStatement(node) { + if ( + hasExcessParens(node.test) && + !isCondAssignException(node) + ) { + report(node.test); + } + }, + + ImportExpression(node) { + const { source } = node; + + if (source.type === "SequenceExpression") { + if (hasDoubleExcessParens(source)) { + report(source); + } + } else if (hasExcessParens(source)) { + report(source); + } + }, + + LogicalExpression: checkBinaryLogical, + + MemberExpression(node) { + const shouldAllowWrapOnce = + isMemberExpInNewCallee(node) && + doesMemberExpressionContainCallExpression(node); + const nodeObjHasExcessParens = shouldAllowWrapOnce + ? hasDoubleExcessParens(node.object) + : hasExcessParens(node.object) && + !( + isImmediateFunctionPrototypeMethodCall( + node.parent, + ) && + node.parent.callee === node && + IGNORE_FUNCTION_PROTOTYPE_METHODS + ); + + if ( + nodeObjHasExcessParens && + precedence(node.object) >= precedence(node) && + (node.computed || + !( + astUtils.isDecimalInteger(node.object) || + // RegExp literal is allowed to have parens (#1589) + (node.object.type === "Literal" && + node.object.regex) + )) + ) { + report(node.object); + } + + if ( + nodeObjHasExcessParens && + node.object.type === "CallExpression" + ) { + report(node.object); + } + + if ( + nodeObjHasExcessParens && + !IGNORE_NEW_IN_MEMBER_EXPR && + node.object.type === "NewExpression" && + isNewExpressionWithParens(node.object) + ) { + report(node.object); + } + + if ( + nodeObjHasExcessParens && + node.optional && + node.object.type === "ChainExpression" + ) { + report(node.object); + } + + if (node.computed && hasExcessParens(node.property)) { + report(node.property); + } + }, + + "MethodDefinition[computed=true]"(node) { + if ( + hasExcessParensWithPrecedence( + node.key, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.key); + } + }, + + NewExpression: checkCallNew, + + ObjectExpression(node) { + node.properties + .filter( + property => + property.value && + hasExcessParensWithPrecedence( + property.value, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ), + ) + .forEach(property => report(property.value)); + }, + + ObjectPattern(node) { + node.properties + .filter(property => { + const value = property.value; + + return ( + canBeAssignmentTarget(value) && + hasExcessParens(value) + ); + }) + .forEach(property => report(property.value)); + }, + + Property(node) { + if (node.computed) { + const { key } = node; + + if ( + key && + hasExcessParensWithPrecedence( + key, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(key); + } + } + }, + + PropertyDefinition(node) { + if ( + node.computed && + hasExcessParensWithPrecedence( + node.key, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.key); + } + + if ( + node.value && + hasExcessParensWithPrecedence( + node.value, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.value); + } + }, + + RestElement(node) { + const argument = node.argument; + + if ( + canBeAssignmentTarget(argument) && + hasExcessParens(argument) + ) { + report(argument); + } + }, + + ReturnStatement(node) { + const returnToken = sourceCode.getFirstToken(node); + + if (isReturnAssignException(node)) { + return; + } + + if ( + node.argument && + hasExcessParensNoLineTerminator( + returnToken, + node.argument, + ) && + // RegExp literal is allowed to have parens (#1589) + !(node.argument.type === "Literal" && node.argument.regex) + ) { + report(node.argument); + } + }, + + SequenceExpression(node) { + const precedenceOfNode = precedence(node); + + node.expressions + .filter(e => + hasExcessParensWithPrecedence(e, precedenceOfNode), + ) + .forEach(report); + }, + + SwitchCase(node) { + if (node.test && hasExcessParens(node.test)) { + report(node.test); + } + }, + + SwitchStatement(node) { + if (hasExcessParens(node.discriminant)) { + report(node.discriminant); + } + }, + + ThrowStatement(node) { + const throwToken = sourceCode.getFirstToken(node); + + if ( + hasExcessParensNoLineTerminator(throwToken, node.argument) + ) { + report(node.argument); + } + }, + + UnaryExpression: checkArgumentWithPrecedence, + UpdateExpression(node) { + if (node.prefix) { + checkArgumentWithPrecedence(node); + } else { + const { argument } = node; + const operatorToken = sourceCode.getLastToken(node); + + if ( + argument.loc.end.line === operatorToken.loc.start.line + ) { + checkArgumentWithPrecedence(node); + } else { + if (hasDoubleExcessParens(argument)) { + report(argument); + } + } + } + }, + AwaitExpression: checkArgumentWithPrecedence, + + VariableDeclarator(node) { + if ( + node.init && + hasExcessParensWithPrecedence( + node.init, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) && + // RegExp literal is allowed to have parens (#1589) + !(node.init.type === "Literal" && node.init.regex) + ) { + report(node.init); + } + }, + + WhileStatement(node) { + if ( + hasExcessParens(node.test) && + !isCondAssignException(node) + ) { + report(node.test); + } + }, + + WithStatement(node) { + if (hasExcessParens(node.object)) { + report(node.object); + } + }, + + YieldExpression(node) { + if (node.argument) { + const yieldToken = sourceCode.getFirstToken(node); + + if ( + (precedence(node.argument) >= precedence(node) && + hasExcessParensNoLineTerminator( + yieldToken, + node.argument, + )) || + hasDoubleExcessParens(node.argument) + ) { + report(node.argument); + } + } + }, + + ClassDeclaration: checkClass, + ClassExpression: checkClass, + + SpreadElement: checkSpreadOperator, + SpreadProperty: checkSpreadOperator, + ExperimentalSpreadProperty: checkSpreadOperator, + + TemplateLiteral(node) { + node.expressions + .filter(e => e && hasExcessParens(e)) + .forEach(report); + }, + + AssignmentPattern(node) { + const { left, right } = node; + + if (canBeAssignmentTarget(left) && hasExcessParens(left)) { + report(left); + } + + if ( + right && + hasExcessParensWithPrecedence( + right, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(right); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-semi.js b/node_modules/eslint/lib/rules/no-extra-semi.js new file mode 100644 index 00000000..11f5fcf6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-semi.js @@ -0,0 +1,167 @@ +/** + * @fileoverview Rule to flag use of unnecessary semicolons + * @author Nicholas C. Zakas + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-extra-semi", + url: "https://eslint.style/rules/js/no-extra-semi", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: "Disallow unnecessary semicolons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extra-semi", + }, + + fixable: "code", + schema: [], + + messages: { + unexpected: "Unnecessary semicolon.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks if a node or token is fixable. + * A node is fixable if it can be removed without turning a subsequent statement into a directive after fixing other nodes. + * @param {Token} nodeOrToken The node or token to check. + * @returns {boolean} Whether or not the node is fixable. + */ + function isFixable(nodeOrToken) { + const nextToken = sourceCode.getTokenAfter(nodeOrToken); + + if (!nextToken || nextToken.type !== "String") { + return true; + } + const stringNode = sourceCode.getNodeByRangeIndex( + nextToken.range[0], + ); + + return !astUtils.isTopLevelExpressionStatement(stringNode.parent); + } + + /** + * Reports an unnecessary semicolon error. + * @param {Node|Token} nodeOrToken A node or a token to be reported. + * @returns {void} + */ + function report(nodeOrToken) { + context.report({ + node: nodeOrToken, + messageId: "unexpected", + fix: isFixable(nodeOrToken) + ? fixer => + /* + * Expand the replacement range to include the surrounding + * tokens to avoid conflicting with semi. + * https://github.com/eslint/eslint/issues/7928 + */ + new FixTracker(fixer, context.sourceCode) + .retainSurroundingTokens(nodeOrToken) + .remove(nodeOrToken) + : null, + }); + } + + /** + * Checks for a part of a class body. + * This checks tokens from a specified token to a next MethodDefinition or the end of class body. + * @param {Token} firstToken The first token to check. + * @returns {void} + */ + function checkForPartOfClassBody(firstToken) { + for ( + let token = firstToken; + token.type === "Punctuator" && + !astUtils.isClosingBraceToken(token); + token = sourceCode.getTokenAfter(token) + ) { + if (astUtils.isSemicolonToken(token)) { + report(token); + } + } + } + + return { + /** + * Reports this empty statement, except if the parent node is a loop. + * @param {Node} node A EmptyStatement node to be reported. + * @returns {void} + */ + EmptyStatement(node) { + const parent = node.parent, + allowedParentTypes = [ + "ForStatement", + "ForInStatement", + "ForOfStatement", + "WhileStatement", + "DoWhileStatement", + "IfStatement", + "LabeledStatement", + "WithStatement", + ]; + + if (!allowedParentTypes.includes(parent.type)) { + report(node); + } + }, + + /** + * Checks tokens from the head of this class body to the first MethodDefinition or the end of this class body. + * @param {Node} node A ClassBody node to check. + * @returns {void} + */ + ClassBody(node) { + checkForPartOfClassBody(sourceCode.getFirstToken(node, 1)); // 0 is `{`. + }, + + /** + * Checks tokens from this MethodDefinition to the next MethodDefinition or the end of this class body. + * @param {Node} node A MethodDefinition node of the start point. + * @returns {void} + */ + "MethodDefinition, PropertyDefinition, StaticBlock"(node) { + checkForPartOfClassBody(sourceCode.getTokenAfter(node)); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-fallthrough.js b/node_modules/eslint/lib/rules/no-fallthrough.js new file mode 100644 index 00000000..4dd210d7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-fallthrough.js @@ -0,0 +1,260 @@ +/** + * @fileoverview Rule to flag fall-through cases in switch statements. + * @author Matt DuVall + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { directivesPattern } = require("../shared/directives"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/iu; + +/** + * Checks all segments in a set and returns true if any are reachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if any segment is reachable; false otherwise. + */ +function isAnySegmentReachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return true; + } + } + + return false; +} + +/** + * Checks whether or not a given comment string is really a fallthrough comment and not an ESLint directive. + * @param {string} comment The comment string to check. + * @param {RegExp} fallthroughCommentPattern The regular expression used for checking for fallthrough comments. + * @returns {boolean} `true` if the comment string is truly a fallthrough comment. + */ +function isFallThroughComment(comment, fallthroughCommentPattern) { + return ( + fallthroughCommentPattern.test(comment) && + !directivesPattern.test(comment.trim()) + ); +} + +/** + * Checks whether or not a given case has a fallthrough comment. + * @param {ASTNode} caseWhichFallsThrough SwitchCase node which falls through. + * @param {ASTNode} subsequentCase The case after caseWhichFallsThrough. + * @param {RuleContext} context A rule context which stores comments. + * @param {RegExp} fallthroughCommentPattern A pattern to match comment to. + * @returns {null | object} the comment if the case has a valid fallthrough comment, otherwise null + */ +function getFallthroughComment( + caseWhichFallsThrough, + subsequentCase, + context, + fallthroughCommentPattern, +) { + const sourceCode = context.sourceCode; + + if ( + caseWhichFallsThrough.consequent.length === 1 && + caseWhichFallsThrough.consequent[0].type === "BlockStatement" + ) { + const trailingCloseBrace = sourceCode.getLastToken( + caseWhichFallsThrough.consequent[0], + ); + const commentInBlock = sourceCode + .getCommentsBefore(trailingCloseBrace) + .pop(); + + if ( + commentInBlock && + isFallThroughComment( + commentInBlock.value, + fallthroughCommentPattern, + ) + ) { + return commentInBlock; + } + } + + const comment = sourceCode.getCommentsBefore(subsequentCase).pop(); + + if ( + comment && + isFallThroughComment(comment.value, fallthroughCommentPattern) + ) { + return comment; + } + + return null; +} + +/** + * Checks whether a node and a token are separated by blank lines + * @param {ASTNode} node The node to check + * @param {Token} token The token to compare against + * @returns {boolean} `true` if there are blank lines between node and token + */ +function hasBlankLinesBetween(node, token) { + return token.loc.start.line > node.loc.end.line + 1; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowEmptyCase: false, + reportUnusedFallthroughComment: false, + }, + ], + + docs: { + description: "Disallow fallthrough of `case` statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-fallthrough", + }, + + schema: [ + { + type: "object", + properties: { + commentPattern: { + type: "string", + }, + allowEmptyCase: { + type: "boolean", + }, + reportUnusedFallthroughComment: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + unusedFallthroughComment: + "Found a comment that would permit fallthrough, but case cannot fall through.", + case: "Expected a 'break' statement before 'case'.", + default: "Expected a 'break' statement before 'default'.", + }, + }, + + create(context) { + const codePathSegments = []; + let currentCodePathSegments = new Set(); + const sourceCode = context.sourceCode; + const [ + { allowEmptyCase, commentPattern, reportUnusedFallthroughComment }, + ] = context.options; + const fallthroughCommentPattern = commentPattern + ? new RegExp(commentPattern, "u") + : DEFAULT_FALLTHROUGH_COMMENT; + + /* + * We need to use leading comments of the next SwitchCase node because + * trailing comments is wrong if semicolons are omitted. + */ + let previousCase = null; + + return { + onCodePathStart() { + codePathSegments.push(currentCodePathSegments); + currentCodePathSegments = new Set(); + }, + + onCodePathEnd() { + currentCodePathSegments = codePathSegments.pop(); + }, + + onUnreachableCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + onCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + SwitchCase(node) { + /* + * Checks whether or not there is a fallthrough comment. + * And reports the previous fallthrough node if that does not exist. + */ + + if (previousCase && previousCase.node.parent === node.parent) { + const previousCaseFallthroughComment = + getFallthroughComment( + previousCase.node, + node, + context, + fallthroughCommentPattern, + ); + + if ( + previousCase.isFallthrough && + !previousCaseFallthroughComment + ) { + context.report({ + messageId: node.test ? "case" : "default", + node, + }); + } else if ( + reportUnusedFallthroughComment && + !previousCase.isSwitchExitReachable && + previousCaseFallthroughComment + ) { + context.report({ + messageId: "unusedFallthroughComment", + node: previousCaseFallthroughComment, + }); + } + } + previousCase = null; + }, + + "SwitchCase:exit"(node) { + const nextToken = sourceCode.getTokenAfter(node); + + /* + * `reachable` meant fall through because statements preceded by + * `break`, `return`, or `throw` are unreachable. + * And allows empty cases and the last case. + */ + const isSwitchExitReachable = isAnySegmentReachable( + currentCodePathSegments, + ); + const isFallthrough = + isSwitchExitReachable && + (node.consequent.length > 0 || + (!allowEmptyCase && + hasBlankLinesBetween(node, nextToken))) && + node.parent.cases.at(-1) !== node; + + previousCase = { + node, + isSwitchExitReachable, + isFallthrough, + }; + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-floating-decimal.js b/node_modules/eslint/lib/rules/no-floating-decimal.js new file mode 100644 index 00000000..cbd15793 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-floating-decimal.js @@ -0,0 +1,99 @@ +/** + * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal + * @author James Allardice + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-floating-decimal", + url: "https://eslint.style/rules/js/no-floating-decimal", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: + "Disallow leading or trailing decimal points in numeric literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-floating-decimal", + }, + + schema: [], + fixable: "code", + messages: { + leading: "A leading decimal point can be confused with a dot.", + trailing: "A trailing decimal point can be confused with a dot.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Literal(node) { + if (typeof node.value === "number") { + if (node.raw.startsWith(".")) { + context.report({ + node, + messageId: "leading", + fix(fixer) { + const tokenBefore = + sourceCode.getTokenBefore(node); + const needsSpaceBefore = + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + `0${node.raw}`, + ); + + return fixer.insertTextBefore( + node, + needsSpaceBefore ? " 0" : "0", + ); + }, + }); + } + if (node.raw.indexOf(".") === node.raw.length - 1) { + context.report({ + node, + messageId: "trailing", + fix: fixer => fixer.insertTextAfter(node, "0"), + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-func-assign.js b/node_modules/eslint/lib/rules/no-func-assign.js new file mode 100644 index 00000000..a17d4b8e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-func-assign.js @@ -0,0 +1,77 @@ +/** + * @fileoverview Rule to flag use of function declaration identifiers as variables. + * @author Ian Christian Myers + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning `function` declarations", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-func-assign", + }, + + schema: [], + + messages: { + isAFunction: "'{{name}}' is a function.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Reports a reference if is non initializer and writable. + * @param {References} references Collection of reference to check. + * @returns {void} + */ + function checkReference(references) { + astUtils.getModifyingReferences(references).forEach(reference => { + context.report({ + node: reference.identifier, + messageId: "isAFunction", + data: { + name: reference.identifier.name, + }, + }); + }); + } + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if (variable.defs[0].type === "FunctionName") { + checkReference(variable.references); + } + } + + /** + * Checks parameters of a given function node. + * @param {ASTNode} node A function node to check. + * @returns {void} + */ + function checkForFunction(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + + return { + FunctionDeclaration: checkForFunction, + FunctionExpression: checkForFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-global-assign.js b/node_modules/eslint/lib/rules/no-global-assign.js new file mode 100644 index 00000000..6f238449 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-global-assign.js @@ -0,0 +1,101 @@ +/** + * @fileoverview Rule to disallow assignments to native objects or read-only global variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ exceptions: [] }], + + docs: { + description: + "Disallow assignments to native objects or read-only global variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-global-assign", + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + globalShouldNotBeModified: + "Read-only global '{{name}}' should not be modified.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ exceptions }] = context.options; + + /** + * Reports write references. + * @param {Reference} reference A reference to check. + * @param {number} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {void} + */ + function checkReference(reference, index, references) { + const identifier = reference.identifier; + + if ( + reference.init === false && + reference.isWrite() && + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ + (index === 0 || references[index - 1].identifier !== identifier) + ) { + context.report({ + node: identifier, + messageId: "globalShouldNotBeModified", + data: { + name: identifier.name, + }, + }); + } + } + + /** + * Reports write references if a given variable is read-only builtin. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if ( + variable.writeable === false && + !exceptions.includes(variable.name) + ) { + variable.references.forEach(checkReference); + } + } + + return { + Program(node) { + const globalScope = sourceCode.getScope(node); + + globalScope.variables.forEach(checkVariable); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-implicit-coercion.js b/node_modules/eslint/lib/rules/no-implicit-coercion.js new file mode 100644 index 00000000..fb6d6a8e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-implicit-coercion.js @@ -0,0 +1,468 @@ +/** + * @fileoverview A rule to disallow the type conversions with shorter notations. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/u; +const ALLOWABLE_OPERATORS = ["~", "!!", "+", "- -", "-", "*"]; + +/** + * Checks whether or not a node is a double logical negating. + * @param {ASTNode} node An UnaryExpression node to check. + * @returns {boolean} Whether or not the node is a double logical negating. + */ +function isDoubleLogicalNegating(node) { + return ( + node.operator === "!" && + node.argument.type === "UnaryExpression" && + node.argument.operator === "!" + ); +} + +/** + * Checks whether or not a node is a binary negating of `.indexOf()` method calling. + * @param {ASTNode} node An UnaryExpression node to check. + * @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling. + */ +function isBinaryNegatingOfIndexOf(node) { + if (node.operator !== "~") { + return false; + } + const callNode = astUtils.skipChainExpression(node.argument); + + return ( + callNode.type === "CallExpression" && + astUtils.isSpecificMemberAccess(callNode.callee, null, INDEX_OF_PATTERN) + ); +} + +/** + * Checks whether or not a node is a multiplying by one. + * @param {BinaryExpression} node A BinaryExpression node to check. + * @returns {boolean} Whether or not the node is a multiplying by one. + */ +function isMultiplyByOne(node) { + return ( + node.operator === "*" && + ((node.left.type === "Literal" && node.left.value === 1) || + (node.right.type === "Literal" && node.right.value === 1)) + ); +} + +/** + * Checks whether the given node logically represents multiplication by a fraction of `1`. + * For example, `a * 1` in `a * 1 / b` is technically multiplication by `1`, but the + * whole expression can be logically interpreted as `a * (1 / b)` rather than `(a * 1) / b`. + * @param {BinaryExpression} node A BinaryExpression node to check. + * @param {SourceCode} sourceCode The source code object. + * @returns {boolean} Whether or not the node is a multiplying by a fraction of `1`. + */ +function isMultiplyByFractionOfOne(node, sourceCode) { + return ( + node.type === "BinaryExpression" && + node.operator === "*" && + node.right.type === "Literal" && + node.right.value === 1 && + node.parent.type === "BinaryExpression" && + node.parent.operator === "/" && + node.parent.left === node && + !astUtils.isParenthesised(sourceCode, node) + ); +} + +/** + * Checks whether the result of a node is numeric or not + * @param {ASTNode} node The node to test + * @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call + */ +function isNumeric(node) { + return ( + (node.type === "Literal" && typeof node.value === "number") || + (node.type === "CallExpression" && + (node.callee.name === "Number" || + node.callee.name === "parseInt" || + node.callee.name === "parseFloat")) + ); +} + +/** + * Returns the first non-numeric operand in a BinaryExpression. Designed to be + * used from bottom to up since it walks up the BinaryExpression trees using + * node.parent to find the result. + * @param {BinaryExpression} node The BinaryExpression node to be walked up on + * @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null + */ +function getNonNumericOperand(node) { + const left = node.left, + right = node.right; + + if (right.type !== "BinaryExpression" && !isNumeric(right)) { + return right; + } + + if (left.type !== "BinaryExpression" && !isNumeric(left)) { + return left; + } + + return null; +} + +/** + * Checks whether an expression evaluates to a string. + * @param {ASTNode} node node that represents the expression to check. + * @returns {boolean} Whether or not the expression evaluates to a string. + */ +function isStringType(node) { + return ( + astUtils.isStringLiteral(node) || + (node.type === "CallExpression" && + node.callee.type === "Identifier" && + node.callee.name === "String") + ); +} + +/** + * Checks whether a node is an empty string literal or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the passed in node is an + * empty string literal or not. + */ +function isEmptyString(node) { + return ( + astUtils.isStringLiteral(node) && + (node.value === "" || + (node.type === "TemplateLiteral" && + node.quasis.length === 1 && + node.quasis[0].value.cooked === "")) + ); +} + +/** + * Checks whether or not a node is a concatenating with an empty string. + * @param {ASTNode} node A BinaryExpression node to check. + * @returns {boolean} Whether or not the node is a concatenating with an empty string. + */ +function isConcatWithEmptyString(node) { + return ( + node.operator === "+" && + ((isEmptyString(node.left) && !isStringType(node.right)) || + (isEmptyString(node.right) && !isStringType(node.left))) + ); +} + +/** + * Checks whether or not a node is appended with an empty string. + * @param {ASTNode} node An AssignmentExpression node to check. + * @returns {boolean} Whether or not the node is appended with an empty string. + */ +function isAppendEmptyString(node) { + return node.operator === "+=" && isEmptyString(node.right); +} + +/** + * Returns the operand that is not an empty string from a flagged BinaryExpression. + * @param {ASTNode} node The flagged BinaryExpression node to check. + * @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression. + */ +function getNonEmptyOperand(node) { + return isEmptyString(node.left) ? node.right : node.left; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + docs: { + description: "Disallow shorthand type conversions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-implicit-coercion", + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + boolean: { + type: "boolean", + }, + number: { + type: "boolean", + }, + string: { + type: "boolean", + }, + disallowTemplateShorthand: { + type: "boolean", + }, + allow: { + type: "array", + items: { + enum: ALLOWABLE_OPERATORS, + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + allow: [], + boolean: true, + disallowTemplateShorthand: false, + number: true, + string: true, + }, + ], + + messages: { + implicitCoercion: + "Unexpected implicit coercion encountered. Use `{{recommendation}}` instead.", + useRecommendation: "Use `{{recommendation}}` instead.", + }, + }, + + create(context) { + const [options] = context.options; + const sourceCode = context.sourceCode; + + /** + * Reports an error and autofixes the node + * @param {ASTNode} node An ast node to report the error on. + * @param {string} recommendation The recommended code for the issue + * @param {bool} shouldSuggest Whether this report should offer a suggestion + * @param {bool} shouldFix Whether this report should fix the node + * @returns {void} + */ + function report(node, recommendation, shouldSuggest, shouldFix) { + /** + * Fix function + * @param {RuleFixer} fixer The fixer to fix. + * @returns {Fix} The fix object. + */ + function fix(fixer) { + const tokenBefore = sourceCode.getTokenBefore(node); + + if ( + tokenBefore?.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, recommendation) + ) { + return fixer.replaceText(node, ` ${recommendation}`); + } + + return fixer.replaceText(node, recommendation); + } + + context.report({ + node, + messageId: "implicitCoercion", + data: { recommendation }, + fix(fixer) { + if (!shouldFix) { + return null; + } + + return fix(fixer); + }, + suggest: [ + { + messageId: "useRecommendation", + data: { recommendation }, + fix(fixer) { + if (shouldFix || !shouldSuggest) { + return null; + } + + return fix(fixer); + }, + }, + ], + }); + } + + return { + UnaryExpression(node) { + let operatorAllowed; + + // !!foo + operatorAllowed = options.allow.includes("!!"); + if ( + !operatorAllowed && + options.boolean && + isDoubleLogicalNegating(node) + ) { + const recommendation = `Boolean(${sourceCode.getText(node.argument.argument)})`; + const variable = astUtils.getVariableByName( + sourceCode.getScope(node), + "Boolean", + ); + const booleanExists = variable?.identifiers.length === 0; + + report(node, recommendation, true, booleanExists); + } + + // ~foo.indexOf(bar) + operatorAllowed = options.allow.includes("~"); + if ( + !operatorAllowed && + options.boolean && + isBinaryNegatingOfIndexOf(node) + ) { + // `foo?.indexOf(bar) !== -1` will be true (== found) if the `foo` is nullish. So use `>= 0` in that case. + const comparison = + node.argument.type === "ChainExpression" + ? ">= 0" + : "!== -1"; + const recommendation = `${sourceCode.getText(node.argument)} ${comparison}`; + + report(node, recommendation, false, false); + } + + // +foo + operatorAllowed = options.allow.includes("+"); + if ( + !operatorAllowed && + options.number && + node.operator === "+" && + !isNumeric(node.argument) + ) { + const recommendation = `Number(${sourceCode.getText(node.argument)})`; + + report(node, recommendation, true, false); + } + + // -(-foo) + operatorAllowed = options.allow.includes("- -"); + if ( + !operatorAllowed && + options.number && + node.operator === "-" && + node.argument.type === "UnaryExpression" && + node.argument.operator === "-" && + !isNumeric(node.argument.argument) + ) { + const recommendation = `Number(${sourceCode.getText(node.argument.argument)})`; + + report(node, recommendation, true, false); + } + }, + + // Use `:exit` to prevent double reporting + "BinaryExpression:exit"(node) { + let operatorAllowed; + + // 1 * foo + operatorAllowed = options.allow.includes("*"); + const nonNumericOperand = + !operatorAllowed && + options.number && + isMultiplyByOne(node) && + !isMultiplyByFractionOfOne(node, sourceCode) && + getNonNumericOperand(node); + + if (nonNumericOperand) { + const recommendation = `Number(${sourceCode.getText(nonNumericOperand)})`; + + report(node, recommendation, true, false); + } + + // foo - 0 + operatorAllowed = options.allow.includes("-"); + if ( + !operatorAllowed && + options.number && + node.operator === "-" && + node.right.type === "Literal" && + node.right.value === 0 && + !isNumeric(node.left) + ) { + const recommendation = `Number(${sourceCode.getText(node.left)})`; + + report(node, recommendation, true, false); + } + + // "" + foo + operatorAllowed = options.allow.includes("+"); + if ( + !operatorAllowed && + options.string && + isConcatWithEmptyString(node) + ) { + const recommendation = `String(${sourceCode.getText(getNonEmptyOperand(node))})`; + + report(node, recommendation, true, false); + } + }, + + AssignmentExpression(node) { + // foo += "" + const operatorAllowed = options.allow.includes("+"); + + if ( + !operatorAllowed && + options.string && + isAppendEmptyString(node) + ) { + const code = sourceCode.getText(getNonEmptyOperand(node)); + const recommendation = `${code} = String(${code})`; + + report(node, recommendation, true, false); + } + }, + + TemplateLiteral(node) { + if (!options.disallowTemplateShorthand) { + return; + } + + // tag`${foo}` + if (node.parent.type === "TaggedTemplateExpression") { + return; + } + + // `` or `${foo}${bar}` + if (node.expressions.length !== 1) { + return; + } + + // `prefix${foo}` + if (node.quasis[0].value.cooked !== "") { + return; + } + + // `${foo}postfix` + if (node.quasis[1].value.cooked !== "") { + return; + } + + // if the expression is already a string, then this isn't a coercion + if (isStringType(node.expressions[0])) { + return; + } + + const code = sourceCode.getText(node.expressions[0]); + const recommendation = `String(${code})`; + + report(node, recommendation, true, false); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-implicit-globals.js b/node_modules/eslint/lib/rules/no-implicit-globals.js new file mode 100644 index 00000000..c291cd86 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-implicit-globals.js @@ -0,0 +1,187 @@ +/** + * @fileoverview Rule to check for implicit global variables, functions and classes. + * @author Joshua Peek + */ + +"use strict"; + +const ASSIGNMENT_NODES = new Set([ + "AssignmentExpression", + "ForInStatement", + "ForOfStatement", +]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + lexicalBindings: false, + }, + ], + + docs: { + description: "Disallow declarations in the global scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-implicit-globals", + }, + + schema: [ + { + type: "object", + properties: { + lexicalBindings: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + globalNonLexicalBinding: + "Unexpected {{kind}} declaration in the global scope, wrap in an IIFE for a local variable, assign as global property for a global variable.", + globalLexicalBinding: + "Unexpected {{kind}} declaration in the global scope, wrap in a block or in an IIFE.", + globalVariableLeak: + "Global variable leak, declare the variable if it is intended to be local.", + assignmentToReadonlyGlobal: + "Unexpected assignment to read-only global variable.", + redeclarationOfReadonlyGlobal: + "Unexpected redeclaration of read-only global variable.", + }, + }, + + create(context) { + const [{ lexicalBindings: checkLexicalBindings }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Reports the node. + * @param {ASTNode} node Node to report. + * @param {string} messageId Id of the message to report. + * @param {string|undefined} kind Declaration kind, can be 'var', 'const', 'let', function or class. + * @returns {void} + */ + function report(node, messageId, kind) { + context.report({ + node, + messageId, + data: { + kind, + }, + }); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + + scope.variables.forEach(variable => { + // Only ESLint global variables have the `writable` key. + const isReadonlyEslintGlobalVariable = + variable.writeable === false; + const isWritableEslintGlobalVariable = + variable.writeable === true; + + if (isWritableEslintGlobalVariable) { + // Everything is allowed with writable ESLint global variables. + return; + } + + // Variables exported by "exported" block comments + if (variable.eslintExported) { + return; + } + + variable.defs.forEach(def => { + const defNode = def.node; + + if ( + def.type === "FunctionName" || + (def.type === "Variable" && + def.parent.kind === "var") + ) { + if (isReadonlyEslintGlobalVariable) { + report( + defNode, + "redeclarationOfReadonlyGlobal", + ); + } else { + report( + defNode, + "globalNonLexicalBinding", + def.type === "FunctionName" + ? "function" + : `'${def.parent.kind}'`, + ); + } + } + + if (checkLexicalBindings) { + if ( + def.type === "ClassName" || + (def.type === "Variable" && + (def.parent.kind === "let" || + def.parent.kind === "const")) + ) { + if (isReadonlyEslintGlobalVariable) { + report( + defNode, + "redeclarationOfReadonlyGlobal", + ); + } else { + report( + defNode, + "globalLexicalBinding", + def.type === "ClassName" + ? "class" + : `'${def.parent.kind}'`, + ); + } + } + } + }); + + if ( + isReadonlyEslintGlobalVariable && + variable.defs.length === 0 + ) { + variable.references.forEach(reference => { + if (reference.isWrite() && !reference.isRead()) { + let assignmentParent = + reference.identifier.parent; + + while ( + assignmentParent && + !ASSIGNMENT_NODES.has(assignmentParent.type) + ) { + assignmentParent = assignmentParent.parent; + } + + report( + assignmentParent ?? reference.identifier, + "assignmentToReadonlyGlobal", + ); + } + }); + } + }); + + // Undeclared assigned variables. + scope.implicit.variables.forEach(variable => { + // def.node is an AssignmentExpression, ForInStatement or ForOfStatement. + variable.defs.forEach(def => { + report(def.node, "globalVariableLeak"); + }); + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-implied-eval.js b/node_modules/eslint/lib/rules/no-implied-eval.js new file mode 100644 index 00000000..70adde2a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-implied-eval.js @@ -0,0 +1,160 @@ +/** + * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { getStaticValue } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `eval()`-like methods", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-implied-eval", + }, + + schema: [], + + messages: { + impliedEval: + "Implied eval. Consider passing a function instead of a string.", + }, + }, + + create(context) { + const GLOBAL_CANDIDATES = Object.freeze([ + "global", + "window", + "globalThis", + ]); + const EVAL_LIKE_FUNC_PATTERN = + /^(?:set(?:Interval|Timeout)|execScript)$/u; + const sourceCode = context.sourceCode; + + /** + * Checks whether a node is evaluated as a string or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is evaluated as a string. + */ + function isEvaluatedString(node) { + if ( + (node.type === "Literal" && typeof node.value === "string") || + node.type === "TemplateLiteral" + ) { + return true; + } + if (node.type === "BinaryExpression" && node.operator === "+") { + return ( + isEvaluatedString(node.left) || + isEvaluatedString(node.right) + ); + } + return false; + } + + /** + * Reports if the `CallExpression` node has evaluated argument. + * @param {ASTNode} node A CallExpression to check. + * @returns {void} + */ + function reportImpliedEvalCallExpression(node) { + const [firstArgument] = node.arguments; + + if (firstArgument) { + const staticValue = getStaticValue( + firstArgument, + sourceCode.getScope(node), + ); + const isStaticString = + staticValue && typeof staticValue.value === "string"; + const isString = + isStaticString || isEvaluatedString(firstArgument); + + if (isString) { + context.report({ + node, + messageId: "impliedEval", + }); + } + } + } + + /** + * Reports calls of `implied eval` via the global references. + * @param {Variable} globalVar A global variable to check. + * @returns {void} + */ + function reportImpliedEvalViaGlobal(globalVar) { + const { references, name } = globalVar; + + references.forEach(ref => { + const identifier = ref.identifier; + let node = identifier.parent; + + while (astUtils.isSpecificMemberAccess(node, null, name)) { + node = node.parent; + } + + if ( + astUtils.isSpecificMemberAccess( + node, + null, + EVAL_LIKE_FUNC_PATTERN, + ) + ) { + const calleeNode = + node.parent.type === "ChainExpression" + ? node.parent + : node; + const parent = calleeNode.parent; + + if ( + parent.type === "CallExpression" && + parent.callee === calleeNode + ) { + reportImpliedEvalCallExpression(parent); + } + } + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + CallExpression(node) { + if ( + astUtils.isSpecificId(node.callee, EVAL_LIKE_FUNC_PATTERN) + ) { + reportImpliedEvalCallExpression(node); + } + }, + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + GLOBAL_CANDIDATES.map(candidate => + astUtils.getVariableByName(globalScope, candidate), + ) + .filter( + globalVar => !!globalVar && globalVar.defs.length === 0, + ) + .forEach(reportImpliedEvalViaGlobal); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-import-assign.js b/node_modules/eslint/lib/rules/no-import-assign.js new file mode 100644 index 00000000..7fe526b6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-import-assign.js @@ -0,0 +1,227 @@ +/** + * @fileoverview Rule to flag updates of imported bindings. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const { findVariable } = require("@eslint-community/eslint-utils"); +const astUtils = require("./utils/ast-utils"); + +const WellKnownMutationFunctions = { + Object: /^(?:assign|definePropert(?:y|ies)|freeze|setPrototypeOf)$/u, + Reflect: /^(?:(?:define|delete)Property|set(?:PrototypeOf)?)$/u, +}; + +/** + * Check if a given node is LHS of an assignment node. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is LHS. + */ +function isAssignmentLeft(node) { + const { parent } = node; + + return ( + (parent.type === "AssignmentExpression" && parent.left === node) || + // Destructuring assignments + parent.type === "ArrayPattern" || + (parent.type === "Property" && + parent.value === node && + parent.parent.type === "ObjectPattern") || + parent.type === "RestElement" || + (parent.type === "AssignmentPattern" && parent.left === node) + ); +} + +/** + * Check if a given node is the operand of mutation unary operator. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is the operand of mutation unary operator. + */ +function isOperandOfMutationUnaryOperator(node) { + const argumentNode = + node.parent.type === "ChainExpression" ? node.parent : node; + const { parent } = argumentNode; + + return ( + (parent.type === "UpdateExpression" && + parent.argument === argumentNode) || + (parent.type === "UnaryExpression" && + parent.operator === "delete" && + parent.argument === argumentNode) + ); +} + +/** + * Check if a given node is the iteration variable of `for-in`/`for-of` syntax. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is the iteration variable. + */ +function isIterationVariable(node) { + const { parent } = node; + + return ( + (parent.type === "ForInStatement" && parent.left === node) || + (parent.type === "ForOfStatement" && parent.left === node) + ); +} + +/** + * Check if a given node is at the first argument of a well-known mutation function. + * - `Object.assign` + * - `Object.defineProperty` + * - `Object.defineProperties` + * - `Object.freeze` + * - `Object.setPrototypeOf` + * - `Reflect.defineProperty` + * - `Reflect.deleteProperty` + * - `Reflect.set` + * - `Reflect.setPrototypeOf` + * @param {ASTNode} node The node to check. + * @param {Scope} scope A `escope.Scope` object to find variable (whichever). + * @returns {boolean} `true` if the node is at the first argument of a well-known mutation function. + */ +function isArgumentOfWellKnownMutationFunction(node, scope) { + const { parent } = node; + + if (parent.type !== "CallExpression" || parent.arguments[0] !== node) { + return false; + } + const callee = astUtils.skipChainExpression(parent.callee); + + if ( + !astUtils.isSpecificMemberAccess( + callee, + "Object", + WellKnownMutationFunctions.Object, + ) && + !astUtils.isSpecificMemberAccess( + callee, + "Reflect", + WellKnownMutationFunctions.Reflect, + ) + ) { + return false; + } + const variable = findVariable(scope, callee.object); + + return variable !== null && variable.scope.type === "global"; +} + +/** + * Check if the identifier node is placed at to update members. + * @param {ASTNode} id The Identifier node to check. + * @param {Scope} scope A `escope.Scope` object to find variable (whichever). + * @returns {boolean} `true` if the member of `id` was updated. + */ +function isMemberWrite(id, scope) { + const { parent } = id; + + return ( + (parent.type === "MemberExpression" && + parent.object === id && + (isAssignmentLeft(parent) || + isOperandOfMutationUnaryOperator(parent) || + isIterationVariable(parent))) || + isArgumentOfWellKnownMutationFunction(id, scope) + ); +} + +/** + * Get the mutation node. + * @param {ASTNode} id The Identifier node to get. + * @returns {ASTNode} The mutation node. + */ +function getWriteNode(id) { + let node = id.parent; + + while ( + node && + node.type !== "AssignmentExpression" && + node.type !== "UpdateExpression" && + node.type !== "UnaryExpression" && + node.type !== "CallExpression" && + node.type !== "ForInStatement" && + node.type !== "ForOfStatement" + ) { + node = node.parent; + } + + return node || id; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow assigning to imported bindings", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-import-assign", + }, + + schema: [], + + messages: { + readonly: "'{{name}}' is read-only.", + readonlyMember: "The members of '{{name}}' are read-only.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + ImportDeclaration(node) { + const scope = sourceCode.getScope(node); + + for (const variable of sourceCode.getDeclaredVariables(node)) { + const shouldCheckMembers = variable.defs.some( + d => d.node.type === "ImportNamespaceSpecifier", + ); + let prevIdNode = null; + + for (const reference of variable.references) { + const idNode = reference.identifier; + + /* + * AssignmentPattern (e.g. `[a = 0] = b`) makes two write + * references for the same identifier. This should skip + * the one of the two in order to prevent redundant reports. + */ + if (idNode === prevIdNode) { + continue; + } + prevIdNode = idNode; + + if (reference.isWrite()) { + context.report({ + node: getWriteNode(idNode), + messageId: "readonly", + data: { name: idNode.name }, + }); + } else if ( + shouldCheckMembers && + isMemberWrite(idNode, scope) + ) { + context.report({ + node: getWriteNode(idNode), + messageId: "readonlyMember", + data: { name: idNode.name }, + }); + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-inline-comments.js b/node_modules/eslint/lib/rules/no-inline-comments.js new file mode 100644 index 00000000..dac9eec1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-inline-comments.js @@ -0,0 +1,115 @@ +/** + * @fileoverview Enforces or disallows inline comments. + * @author Greg Cochard + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{}], + + docs: { + description: "Disallow inline comments after code", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-inline-comments", + }, + + schema: [ + { + type: "object", + properties: { + ignorePattern: { + type: "string", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedInlineComment: "Unexpected comment inline with code.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ ignorePattern }] = context.options; + const customIgnoreRegExp = + ignorePattern && new RegExp(ignorePattern, "u"); + + /** + * Will check that comments are not on lines starting with or ending with code + * @param {ASTNode} node The comment node to check + * @private + * @returns {void} + */ + function testCodeAroundComment(node) { + const startLine = String(sourceCode.lines[node.loc.start.line - 1]), + endLine = String(sourceCode.lines[node.loc.end.line - 1]), + preamble = startLine.slice(0, node.loc.start.column).trim(), + postamble = endLine.slice(node.loc.end.column).trim(), + isPreambleEmpty = !preamble, + isPostambleEmpty = !postamble; + + // Nothing on both sides + if (isPreambleEmpty && isPostambleEmpty) { + return; + } + + // Matches the ignore pattern + if (customIgnoreRegExp && customIgnoreRegExp.test(node.value)) { + return; + } + + // JSX Exception + if ( + (isPreambleEmpty || preamble === "{") && + (isPostambleEmpty || postamble === "}") + ) { + const enclosingNode = sourceCode.getNodeByRangeIndex( + node.range[0], + ); + + if ( + enclosingNode && + enclosingNode.type === "JSXEmptyExpression" + ) { + return; + } + } + + // Don't report ESLint directive comments + if (astUtils.isDirectiveComment(node)) { + return; + } + + context.report({ + node, + messageId: "unexpectedInlineComment", + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + sourceCode + .getAllComments() + .filter(token => token.type !== "Shebang") + .forEach(testCodeAroundComment); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-inner-declarations.js b/node_modules/eslint/lib/rules/no-inner-declarations.js new file mode 100644 index 00000000..ec6c4952 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-inner-declarations.js @@ -0,0 +1,147 @@ +/** + * @fileoverview Rule to enforce declarations in program or function body root. + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const validParent = new Set([ + "Program", + "StaticBlock", + "ExportNamedDeclaration", + "ExportDefaultDeclaration", +]); +const validBlockStatementParent = new Set([ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", +]); + +/** + * Finds the nearest enclosing context where this rule allows declarations and returns its description. + * @param {ASTNode} node Node to search from. + * @returns {string} Description. One of "program", "function body", "class static block body". + */ +function getAllowedBodyDescription(node) { + let { parent } = node; + + while (parent) { + if (parent.type === "StaticBlock") { + return "class static block body"; + } + + if (astUtils.isFunction(parent)) { + return "function body"; + } + + ({ parent } = parent); + } + + return "program"; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: ["functions", { blockScopedFunctions: "allow" }], + + docs: { + description: + "Disallow variable or `function` declarations in nested blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-inner-declarations", + }, + + schema: [ + { + enum: ["functions", "both"], + }, + { + type: "object", + properties: { + blockScopedFunctions: { + enum: ["allow", "disallow"], + }, + }, + additionalProperties: false, + }, + ], + + messages: { + moveDeclToRoot: "Move {{type}} declaration to {{body}} root.", + }, + }, + + create(context) { + const both = context.options[0] === "both"; + const { blockScopedFunctions } = context.options[1]; + + const sourceCode = context.sourceCode; + const ecmaVersion = context.languageOptions.ecmaVersion; + + /** + * Ensure that a given node is at a program or function body's root. + * @param {ASTNode} node Declaration node to check. + * @returns {void} + */ + function check(node) { + const parent = node.parent; + + if ( + parent.type === "BlockStatement" && + validBlockStatementParent.has(parent.parent.type) + ) { + return; + } + + if (validParent.has(parent.type)) { + return; + } + + context.report({ + node, + messageId: "moveDeclToRoot", + data: { + type: + node.type === "FunctionDeclaration" + ? "function" + : "variable", + body: getAllowedBodyDescription(node), + }, + }); + } + + return { + FunctionDeclaration(node) { + const isInStrictCode = sourceCode.getScope(node).upper.isStrict; + + if ( + blockScopedFunctions === "allow" && + ecmaVersion >= 2015 && + isInStrictCode + ) { + return; + } + + check(node); + }, + VariableDeclaration(node) { + if (both && node.kind === "var") { + check(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-invalid-regexp.js b/node_modules/eslint/lib/rules/no-invalid-regexp.js new file mode 100644 index 00000000..c3937a41 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-invalid-regexp.js @@ -0,0 +1,243 @@ +/** + * @fileoverview Validate strings passed to the RegExp constructor + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const RegExpValidator = require("@eslint-community/regexpp").RegExpValidator; +const validator = new RegExpValidator(); +const validFlags = "dgimsuvy"; +const undefined1 = void 0; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [{}], + + docs: { + description: + "Disallow invalid regular expression strings in `RegExp` constructors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-invalid-regexp", + }, + + schema: [ + { + type: "object", + properties: { + allowConstructorFlags: { + type: "array", + items: { + type: "string", + }, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + regexMessage: "{{message}}.", + }, + }, + + create(context) { + const [{ allowConstructorFlags }] = context.options; + let allowedFlags = []; + + if (allowConstructorFlags) { + const temp = allowConstructorFlags + .join("") + .replace(new RegExp(`[${validFlags}]`, "gu"), ""); + + if (temp) { + allowedFlags = [...new Set(temp)]; + } + } + + /** + * Reports error with the provided message. + * @param {ASTNode} node The node holding the invalid RegExp + * @param {string} message The message to report. + * @returns {void} + */ + function report(node, message) { + context.report({ + node, + messageId: "regexMessage", + data: { message }, + }); + } + + /** + * Check if node is a string + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if its a string + * @private + */ + function isString(node) { + return ( + node && + node.type === "Literal" && + typeof node.value === "string" + ); + } + + /** + * Gets flags of a regular expression created by the given `RegExp()` or `new RegExp()` call + * Examples: + * new RegExp(".") // => "" + * new RegExp(".", "gu") // => "gu" + * new RegExp(".", flags) // => null + * @param {ASTNode} node `CallExpression` or `NewExpression` node + * @returns {string|null} flags if they can be determined, `null` otherwise + * @private + */ + function getFlags(node) { + if (node.arguments.length < 2) { + return ""; + } + + if (isString(node.arguments[1])) { + return node.arguments[1].value; + } + + return null; + } + + /** + * Check syntax error in a given pattern. + * @param {string} pattern The RegExp pattern to validate. + * @param {Object} flags The RegExp flags to validate. + * @param {boolean} [flags.unicode] The Unicode flag. + * @param {boolean} [flags.unicodeSets] The UnicodeSets flag. + * @returns {string|null} The syntax error. + */ + function validateRegExpPattern(pattern, flags) { + try { + validator.validatePattern( + pattern, + undefined1, + undefined1, + flags, + ); + return null; + } catch (err) { + return err.message; + } + } + + /** + * Check syntax error in a given flags. + * @param {string|null} flags The RegExp flags to validate. + * @param {string|null} flagsToCheck The RegExp invalid flags. + * @param {string} allFlags all valid and allowed flags. + * @returns {string|null} The syntax error. + */ + function validateRegExpFlags(flags, flagsToCheck, allFlags) { + const duplicateFlags = []; + + if (typeof flagsToCheck === "string") { + for (const flag of flagsToCheck) { + if (allFlags.includes(flag)) { + duplicateFlags.push(flag); + } + } + } + + /* + * `regexpp` checks the combination of `u` and `v` flags when parsing `Pattern` according to `ecma262`, + * but this rule may check only the flag when the pattern is unidentifiable, so check it here. + * https://tc39.es/ecma262/multipage/text-processing.html#sec-parsepattern + */ + if (flags && flags.includes("u") && flags.includes("v")) { + return "Regex 'u' and 'v' flags cannot be used together"; + } + + if (duplicateFlags.length > 0) { + return `Duplicate flags ('${duplicateFlags.join("")}') supplied to RegExp constructor`; + } + + if (!flagsToCheck) { + return null; + } + + return `Invalid flags supplied to RegExp constructor '${flagsToCheck}'`; + } + + return { + "CallExpression, NewExpression"(node) { + if ( + node.callee.type !== "Identifier" || + node.callee.name !== "RegExp" + ) { + return; + } + + const flags = getFlags(node); + let flagsToCheck = flags; + const allFlags = + allowedFlags.length > 0 + ? validFlags.split("").concat(allowedFlags) + : validFlags.split(""); + + if (flags) { + allFlags.forEach(flag => { + flagsToCheck = flagsToCheck.replace(flag, ""); + }); + } + + let message = validateRegExpFlags( + flags, + flagsToCheck, + allFlags, + ); + + if (message) { + report(node, message); + return; + } + + if (!isString(node.arguments[0])) { + return; + } + + const pattern = node.arguments[0].value; + + message = + // If flags are unknown, report the regex only if its pattern is invalid both with and without the "u" flag + flags === null + ? validateRegExpPattern(pattern, { + unicode: true, + unicodeSets: false, + }) && + validateRegExpPattern(pattern, { + unicode: false, + unicodeSets: true, + }) && + validateRegExpPattern(pattern, { + unicode: false, + unicodeSets: false, + }) + : validateRegExpPattern(pattern, { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }); + + if (message) { + report(node, message); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-invalid-this.js b/node_modules/eslint/lib/rules/no-invalid-this.js new file mode 100644 index 00000000..9e2f97ce --- /dev/null +++ b/node_modules/eslint/lib/rules/no-invalid-this.js @@ -0,0 +1,178 @@ +/** + * @fileoverview A rule to disallow `this` keywords in contexts where the value of `this` is `undefined`. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if the given code path is a code path with lexical `this` binding. + * That is, if `this` within the code path refers to `this` of surrounding code path. + * @param {CodePath} codePath Code path. + * @param {ASTNode} node Node that started the code path. + * @returns {boolean} `true` if it is a code path with lexical `this` binding. + */ +function isCodePathWithLexicalThis(codePath, node) { + return ( + codePath.origin === "function" && + node.type === "ArrowFunctionExpression" + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + defaultOptions: [{ capIsConstructor: true }], + + docs: { + description: + "Disallow use of `this` in contexts where the value of `this` is `undefined`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-invalid-this", + }, + + schema: [ + { + type: "object", + properties: { + capIsConstructor: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedThis: "Unexpected 'this'.", + }, + }, + + create(context) { + const [{ capIsConstructor }] = context.options; + const stack = [], + sourceCode = context.sourceCode; + + /** + * Gets the current checking context. + * + * The return value has a flag that whether or not `this` keyword is valid. + * The flag is initialized when got at the first time. + * @returns {{valid: boolean}} + * an object which has a flag that whether or not `this` keyword is valid. + */ + stack.getCurrent = function () { + const current = this.at(-1); + + if (!current.init) { + current.init = true; + current.valid = !astUtils.isDefaultThisBinding( + current.node, + sourceCode, + { capIsConstructor }, + ); + } + return current; + }; + + return { + onCodePathStart(codePath, node) { + if (isCodePathWithLexicalThis(codePath, node)) { + return; + } + + if (codePath.origin === "program") { + const scope = sourceCode.getScope(node); + const features = + context.languageOptions.parserOptions.ecmaFeatures || + {}; + + // `this` at the top level of scripts always refers to the global object + stack.push({ + init: true, + node, + valid: !( + node.sourceType === "module" || + (features.globalReturn && + scope.childScopes[0].isStrict) + ), + }); + + return; + } + + /* + * `init: false` means that `valid` isn't determined yet. + * Most functions don't use `this`, and the calculation for `valid` + * is relatively costly, so we'll calculate it lazily when the first + * `this` within the function is traversed. A special case are non-strict + * functions, because `this` refers to the global object and therefore is + * always valid, so we can set `init: true` right away. + */ + stack.push({ + init: !sourceCode.getScope(node).isStrict, + node, + valid: true, + }); + }, + + onCodePathEnd(codePath, node) { + if (isCodePathWithLexicalThis(codePath, node)) { + return; + } + + stack.pop(); + }, + + "AccessorProperty > *.value"(node) { + stack.push({ + init: true, + node, + valid: true, + }); + }, + + "AccessorProperty:exit"() { + stack.pop(); + }, + + // Reports if `this` of the current context is invalid. + ThisExpression(node) { + // Special case: skip `this` if it's the value of an AccessorProperty + if ( + node.parent.type === "AccessorProperty" && + node.parent.value === node + ) { + return; + } + + const current = stack.getCurrent(); + + if (current && !current.valid) { + context.report({ + node, + messageId: "unexpectedThis", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-irregular-whitespace.js b/node_modules/eslint/lib/rules/no-irregular-whitespace.js new file mode 100644 index 00000000..60669c7c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-irregular-whitespace.js @@ -0,0 +1,292 @@ +/** + * @fileoverview Rule to disallow whitespace that is not a tab or space, whitespace inside strings and comments are allowed + * @author Jonathan Kingston + * @author Christophe Porteneuve + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const ALL_IRREGULARS = + /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000\u2028\u2029]/u; +const IRREGULAR_WHITESPACE = + /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/gmu; +const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/gmu; +const LINE_BREAK = astUtils.createGlobalLinebreakMatcher(); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + skipComments: false, + skipJSXText: false, + skipRegExps: false, + skipStrings: true, + skipTemplates: false, + }, + ], + + docs: { + description: "Disallow irregular whitespace", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-irregular-whitespace", + }, + + schema: [ + { + type: "object", + properties: { + skipComments: { + type: "boolean", + }, + skipStrings: { + type: "boolean", + }, + skipTemplates: { + type: "boolean", + }, + skipRegExps: { + type: "boolean", + }, + skipJSXText: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + noIrregularWhitespace: "Irregular whitespace not allowed.", + }, + }, + + create(context) { + const [ + { + skipComments, + skipStrings, + skipRegExps, + skipTemplates, + skipJSXText, + }, + ] = context.options; + + const sourceCode = context.sourceCode; + const commentNodes = sourceCode.getAllComments(); + + // Module store of errors that we have found + let errors = []; + + /** + * Removes errors that occur inside the given node + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeWhitespaceError(node) { + const locStart = node.loc.start; + const locEnd = node.loc.end; + + errors = errors.filter( + ({ loc: { start: errorLocStart } }) => + errorLocStart.line < locStart.line || + (errorLocStart.line === locStart.line && + errorLocStart.column < locStart.column) || + (errorLocStart.line === locEnd.line && + errorLocStart.column >= locEnd.column) || + errorLocStart.line > locEnd.line, + ); + } + + /** + * Checks literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInLiteral(node) { + const shouldCheckStrings = + skipStrings && typeof node.value === "string"; + const shouldCheckRegExps = skipRegExps && Boolean(node.regex); + + if (shouldCheckStrings || shouldCheckRegExps) { + // If we have irregular characters remove them from the errors list + if (ALL_IRREGULARS.test(node.raw)) { + removeWhitespaceError(node); + } + } + } + + /** + * Checks template string literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInTemplateLiteral(node) { + if (typeof node.value.raw === "string") { + if (ALL_IRREGULARS.test(node.value.raw)) { + removeWhitespaceError(node); + } + } + } + + /** + * Checks comment nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInComment(node) { + if (ALL_IRREGULARS.test(node.value)) { + removeWhitespaceError(node); + } + } + + /** + * Checks JSX nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInJSXText(node) { + if (ALL_IRREGULARS.test(node.raw)) { + removeWhitespaceError(node); + } + } + + /** + * Checks the program source for irregular whitespace + * @param {ASTNode} node The program node + * @returns {void} + * @private + */ + function checkForIrregularWhitespace(node) { + const sourceLines = sourceCode.lines; + + sourceLines.forEach((sourceLine, lineIndex) => { + const lineNumber = lineIndex + 1; + let match; + + while ( + (match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null + ) { + errors.push({ + node, + messageId: "noIrregularWhitespace", + loc: { + start: { + line: lineNumber, + column: match.index, + }, + end: { + line: lineNumber, + column: match.index + match[0].length, + }, + }, + }); + } + }); + } + + /** + * Checks the program source for irregular line terminators + * @param {ASTNode} node The program node + * @returns {void} + * @private + */ + function checkForIrregularLineTerminators(node) { + const source = sourceCode.getText(), + sourceLines = sourceCode.lines, + linebreaks = source.match(LINE_BREAK); + let lastLineIndex = -1, + match; + + while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) { + const lineIndex = + linebreaks.indexOf(match[0], lastLineIndex + 1) || 0; + + errors.push({ + node, + messageId: "noIrregularWhitespace", + loc: { + start: { + line: lineIndex + 1, + column: sourceLines[lineIndex].length, + }, + end: { + line: lineIndex + 2, + column: 0, + }, + }, + }); + + lastLineIndex = lineIndex; + } + } + + /** + * A no-op function to act as placeholder for comment accumulation when the `skipComments` option is `false`. + * @returns {void} + * @private + */ + function noop() {} + + const nodes = {}; + + if (ALL_IRREGULARS.test(sourceCode.getText())) { + nodes.Program = function (node) { + /* + * As we can easily fire warnings for all white space issues with + * all the source its simpler to fire them here. + * This means we can check all the application code without having + * to worry about issues caused in the parser tokens. + * When writing this code also evaluating per node was missing out + * connecting tokens in some cases. + * We can later filter the errors when they are found to be not an + * issue in nodes we don't care about. + */ + checkForIrregularWhitespace(node); + checkForIrregularLineTerminators(node); + }; + + nodes.Literal = removeInvalidNodeErrorsInLiteral; + nodes.TemplateElement = skipTemplates + ? removeInvalidNodeErrorsInTemplateLiteral + : noop; + nodes.JSXText = skipJSXText + ? removeInvalidNodeErrorsInJSXText + : noop; + nodes["Program:exit"] = function () { + if (skipComments) { + // First strip errors occurring in comment nodes. + commentNodes.forEach(removeInvalidNodeErrorsInComment); + } + + // If we have any errors remaining report on them + errors.forEach(error => context.report(error)); + }; + } else { + nodes.Program = noop; + } + + return nodes; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-iterator.js b/node_modules/eslint/lib/rules/no-iterator.js new file mode 100644 index 00000000..6451e334 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-iterator.js @@ -0,0 +1,48 @@ +/** + * @fileoverview Rule to flag usage of __iterator__ property + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getStaticPropertyName } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of the `__iterator__` property", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-iterator", + }, + + schema: [], + + messages: { + noIterator: "Reserved name '__iterator__'.", + }, + }, + + create(context) { + return { + MemberExpression(node) { + if (getStaticPropertyName(node) === "__iterator__") { + context.report({ + node, + messageId: "noIterator", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-label-var.js b/node_modules/eslint/lib/rules/no-label-var.js new file mode 100644 index 00000000..a8789413 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-label-var.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Rule to flag labels that are the same as an identifier + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow labels that share a name with a variable", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-label-var", + }, + + schema: [], + + messages: { + identifierClashWithLabel: + "Found identifier with same name as label.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the identifier is present inside current scope + * @param {Object} scope current scope + * @param {string} name To evaluate + * @returns {boolean} True if its present + * @private + */ + function findIdentifier(scope, name) { + return astUtils.getVariableByName(scope, name) !== null; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + LabeledStatement(node) { + // Fetch the innermost scope. + const scope = sourceCode.getScope(node); + + /* + * Recursively find the identifier walking up the scope, starting + * with the innermost scope. + */ + if (findIdentifier(scope, node.label.name)) { + context.report({ + node, + messageId: "identifierClashWithLabel", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-labels.js b/node_modules/eslint/lib/rules/no-labels.js new file mode 100644 index 00000000..45eb8af7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-labels.js @@ -0,0 +1,156 @@ +/** + * @fileoverview Disallow Labeled Statements + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowLoop: false, + allowSwitch: false, + }, + ], + + docs: { + description: "Disallow labeled statements", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-labels", + }, + + schema: [ + { + type: "object", + properties: { + allowLoop: { + type: "boolean", + }, + allowSwitch: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedLabel: "Unexpected labeled statement.", + unexpectedLabelInBreak: "Unexpected label in break statement.", + unexpectedLabelInContinue: + "Unexpected label in continue statement.", + }, + }, + + create(context) { + const [{ allowLoop, allowSwitch }] = context.options; + let scopeInfo = null; + + /** + * Gets the kind of a given node. + * @param {ASTNode} node A node to get. + * @returns {string} The kind of the node. + */ + function getBodyKind(node) { + if (astUtils.isLoop(node)) { + return "loop"; + } + if (node.type === "SwitchStatement") { + return "switch"; + } + return "other"; + } + + /** + * Checks whether the label of a given kind is allowed or not. + * @param {string} kind A kind to check. + * @returns {boolean} `true` if the kind is allowed. + */ + function isAllowed(kind) { + switch (kind) { + case "loop": + return allowLoop; + case "switch": + return allowSwitch; + default: + return false; + } + } + + /** + * Checks whether a given name is a label of a loop or not. + * @param {string} label A name of a label to check. + * @returns {boolean} `true` if the name is a label of a loop. + */ + function getKind(label) { + let info = scopeInfo; + + while (info) { + if (info.label === label) { + return info.kind; + } + info = info.upper; + } + + /* c8 ignore next */ + return "other"; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + LabeledStatement(node) { + scopeInfo = { + label: node.label.name, + kind: getBodyKind(node.body), + upper: scopeInfo, + }; + }, + + "LabeledStatement:exit"(node) { + if (!isAllowed(scopeInfo.kind)) { + context.report({ + node, + messageId: "unexpectedLabel", + }); + } + + scopeInfo = scopeInfo.upper; + }, + + BreakStatement(node) { + if (node.label && !isAllowed(getKind(node.label.name))) { + context.report({ + node, + messageId: "unexpectedLabelInBreak", + }); + } + }, + + ContinueStatement(node) { + if (node.label && !isAllowed(getKind(node.label.name))) { + context.report({ + node, + messageId: "unexpectedLabelInContinue", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-lone-blocks.js b/node_modules/eslint/lib/rules/no-lone-blocks.js new file mode 100644 index 00000000..94421b8f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-lone-blocks.js @@ -0,0 +1,140 @@ +/** + * @fileoverview Rule to flag blocks with no reason to exist + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary nested blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-lone-blocks", + }, + + schema: [], + + messages: { + redundantBlock: "Block is redundant.", + redundantNestedBlock: "Nested block is redundant.", + }, + }, + + create(context) { + // A stack of lone blocks to be checked for block-level bindings + const loneBlocks = []; + let ruleDef; + const sourceCode = context.sourceCode; + + /** + * Reports a node as invalid. + * @param {ASTNode} node The node to be reported. + * @returns {void} + */ + function report(node) { + const messageId = + node.parent.type === "BlockStatement" || + node.parent.type === "StaticBlock" + ? "redundantNestedBlock" + : "redundantBlock"; + + context.report({ + node, + messageId, + }); + } + + /** + * Checks for any occurrence of a BlockStatement in a place where lists of statements can appear + * @param {ASTNode} node The node to check + * @returns {boolean} True if the node is a lone block. + */ + function isLoneBlock(node) { + return ( + node.parent.type === "BlockStatement" || + node.parent.type === "StaticBlock" || + node.parent.type === "Program" || + // Don't report blocks in switch cases if the block is the only statement of the case. + (node.parent.type === "SwitchCase" && + !( + node.parent.consequent[0] === node && + node.parent.consequent.length === 1 + )) + ); + } + + /** + * Checks the enclosing block of the current node for block-level bindings, + * and "marks it" as valid if any. + * @param {ASTNode} node The current node to check. + * @returns {void} + */ + function markLoneBlock(node) { + if (loneBlocks.length === 0) { + return; + } + + const block = node.parent; + + if (loneBlocks.at(-1) === block) { + loneBlocks.pop(); + } + } + + // Default rule definition: report all lone blocks + ruleDef = { + BlockStatement(node) { + if (isLoneBlock(node)) { + report(node); + } + }, + }; + + // ES6: report blocks without block-level bindings, or that's only child of another block + if (context.languageOptions.ecmaVersion >= 2015) { + ruleDef = { + BlockStatement(node) { + if (isLoneBlock(node)) { + loneBlocks.push(node); + } + }, + "BlockStatement:exit"(node) { + if (loneBlocks.length > 0 && loneBlocks.at(-1) === node) { + loneBlocks.pop(); + report(node); + } else if ( + (node.parent.type === "BlockStatement" || + node.parent.type === "StaticBlock") && + node.parent.body.length === 1 + ) { + report(node); + } + }, + }; + + ruleDef.VariableDeclaration = function (node) { + if (node.kind !== "var") { + markLoneBlock(node); + } + }; + + ruleDef.FunctionDeclaration = function (node) { + if (sourceCode.getScope(node).isStrict) { + markLoneBlock(node); + } + }; + + ruleDef.ClassDeclaration = markLoneBlock; + } + + return ruleDef; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-lonely-if.js b/node_modules/eslint/lib/rules/no-lonely-if.js new file mode 100644 index 00000000..65af9607 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-lonely-if.js @@ -0,0 +1,126 @@ +/** + * @fileoverview Rule to disallow if as the only statement in an else block + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `if` statements as the only statement in `else` blocks", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-lonely-if", + }, + + schema: [], + fixable: "code", + + messages: { + unexpectedLonelyIf: + "Unexpected if as the only statement in an else block.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + IfStatement(node) { + const parent = node.parent, + grandparent = parent.parent; + + if ( + parent && + parent.type === "BlockStatement" && + parent.body.length === 1 && + !astUtils.areBracesNecessary(parent, sourceCode) && + grandparent && + grandparent.type === "IfStatement" && + parent === grandparent.alternate + ) { + context.report({ + node, + messageId: "unexpectedLonelyIf", + fix(fixer) { + const openingElseCurly = + sourceCode.getFirstToken(parent); + const closingElseCurly = + sourceCode.getLastToken(parent); + const elseKeyword = + sourceCode.getTokenBefore(openingElseCurly); + const tokenAfterElseBlock = + sourceCode.getTokenAfter(closingElseCurly); + const lastIfToken = sourceCode.getLastToken( + node.consequent, + ); + const sourceText = sourceCode.getText(); + + if ( + sourceText + .slice( + openingElseCurly.range[1], + node.range[0], + ) + .trim() || + sourceText + .slice( + node.range[1], + closingElseCurly.range[0], + ) + .trim() + ) { + // Don't fix if there are any non-whitespace characters interfering (e.g. comments) + return null; + } + + if ( + node.consequent.type !== "BlockStatement" && + lastIfToken.value !== ";" && + tokenAfterElseBlock && + (node.consequent.loc.end.line === + tokenAfterElseBlock.loc.start.line || + /^[([/+`-]/u.test( + tokenAfterElseBlock.value, + ) || + lastIfToken.value === "++" || + lastIfToken.value === "--") + ) { + /* + * If the `if` statement has no block, and is not followed by a semicolon, make sure that fixing + * the issue would not change semantics due to ASI. If this would happen, don't do a fix. + */ + return null; + } + + return fixer.replaceTextRange( + [ + openingElseCurly.range[0], + closingElseCurly.range[1], + ], + (elseKeyword.range[1] === + openingElseCurly.range[0] + ? " " + : "") + sourceCode.getText(node), + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-loop-func.js b/node_modules/eslint/lib/rules/no-loop-func.js new file mode 100644 index 00000000..5403bd5c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-loop-func.js @@ -0,0 +1,265 @@ +/** + * @fileoverview Rule to flag creation of function inside a loop + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Identifies is a node is a FunctionExpression which is part of an IIFE + * @param {ASTNode} node Node to test + * @returns {boolean} True if it's an IIFE + */ +function isIIFE(node) { + return ( + (node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression") && + node.parent && + node.parent.type === "CallExpression" && + node.parent.callee === node + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: + "Disallow function declarations that contain unsafe references inside loop statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-loop-func", + }, + + schema: [], + + messages: { + unsafeRefs: + "Function declared in a loop contains unsafe references to variable(s) {{ varNames }}.", + }, + }, + + create(context) { + const SKIPPED_IIFE_NODES = new Set(); + const sourceCode = context.sourceCode; + + /** + * Gets the containing loop node of a specified node. + * + * We don't need to check nested functions, so this ignores those, with the exception of IIFE. + * `Scope.through` contains references of nested functions. + * @param {ASTNode} node An AST node to get. + * @returns {ASTNode|null} The containing loop node of the specified node, or + * `null`. + */ + function getContainingLoopNode(node) { + for ( + let currentNode = node; + currentNode.parent; + currentNode = currentNode.parent + ) { + const parent = currentNode.parent; + + switch (parent.type) { + case "WhileStatement": + case "DoWhileStatement": + return parent; + + case "ForStatement": + // `init` is outside of the loop. + if (parent.init !== currentNode) { + return parent; + } + break; + + case "ForInStatement": + case "ForOfStatement": + // `right` is outside of the loop. + if (parent.right !== currentNode) { + return parent; + } + break; + + case "ArrowFunctionExpression": + case "FunctionExpression": + case "FunctionDeclaration": + // We need to check nested functions only in case of IIFE. + if (SKIPPED_IIFE_NODES.has(parent)) { + break; + } + + return null; + default: + break; + } + } + + return null; + } + + /** + * Gets the containing loop node of a given node. + * If the loop was nested, this returns the most outer loop. + * @param {ASTNode} node A node to get. This is a loop node. + * @param {ASTNode|null} excludedNode A node that the result node should not + * include. + * @returns {ASTNode} The most outer loop node. + */ + function getTopLoopNode(node, excludedNode) { + const border = excludedNode ? excludedNode.range[1] : 0; + let retv = node; + let containingLoopNode = node; + + while ( + containingLoopNode && + containingLoopNode.range[0] >= border + ) { + retv = containingLoopNode; + containingLoopNode = getContainingLoopNode(containingLoopNode); + } + + return retv; + } + + /** + * Checks whether a given reference which refers to an upper scope's variable is + * safe or not. + * @param {ASTNode} loopNode A containing loop node. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is safe or not. + */ + function isSafe(loopNode, reference) { + const variable = reference.resolved; + const definition = variable && variable.defs[0]; + const declaration = definition && definition.parent; + const kind = + declaration && declaration.type === "VariableDeclaration" + ? declaration.kind + : ""; + + // Variables which are declared by `const` is safe. + if (kind === "const") { + return true; + } + + /* + * Variables which are declared by `let` in the loop is safe. + * It's a different instance from the next loop step's. + */ + if ( + kind === "let" && + declaration.range[0] > loopNode.range[0] && + declaration.range[1] < loopNode.range[1] + ) { + return true; + } + + /* + * WriteReferences which exist after this border are unsafe because those + * can modify the variable. + */ + const border = getTopLoopNode( + loopNode, + kind === "let" ? declaration : null, + ).range[0]; + + /** + * Checks whether a given reference is safe or not. + * The reference is every reference of the upper scope's variable we are + * looking now. + * + * It's safe if the reference matches one of the following condition. + * - is readonly. + * - doesn't exist inside a local function and after the border. + * @param {eslint-scope.Reference} upperRef A reference to check. + * @returns {boolean} `true` if the reference is safe. + */ + function isSafeReference(upperRef) { + const id = upperRef.identifier; + + return ( + !upperRef.isWrite() || + (variable.scope.variableScope === + upperRef.from.variableScope && + id.range[0] < border) + ); + } + + return ( + Boolean(variable) && variable.references.every(isSafeReference) + ); + } + + /** + * Reports functions which match the following condition: + * + * - has a loop node in ancestors. + * - has any references which refers to an unsafe variable. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function checkForLoops(node) { + const loopNode = getContainingLoopNode(node); + + if (!loopNode) { + return; + } + + const references = sourceCode.getScope(node).through; + + // Check if the function is not asynchronous or a generator function + if (!(node.async || node.generator)) { + if (isIIFE(node)) { + const isFunctionExpression = + node.type === "FunctionExpression"; + + // Check if the function is referenced elsewhere in the code + const isFunctionReferenced = + isFunctionExpression && node.id + ? references.some( + r => r.identifier.name === node.id.name, + ) + : false; + + if (!isFunctionReferenced) { + SKIPPED_IIFE_NODES.add(node); + return; + } + } + } + + const unsafeRefs = [ + ...new Set( + references + .filter(r => r.resolved && !isSafe(loopNode, r)) + .map(r => r.identifier.name), + ), + ]; + + if (unsafeRefs.length > 0) { + context.report({ + node, + messageId: "unsafeRefs", + data: { varNames: `'${unsafeRefs.join("', '")}'` }, + }); + } + } + + return { + ArrowFunctionExpression: checkForLoops, + FunctionExpression: checkForLoops, + FunctionDeclaration: checkForLoops, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-loss-of-precision.js b/node_modules/eslint/lib/rules/no-loss-of-precision.js new file mode 100644 index 00000000..7fc02401 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-loss-of-precision.js @@ -0,0 +1,231 @@ +/** + * @fileoverview Rule to flag numbers that will lose significant figure precision at runtime + * @author Jacob Moore + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: "Disallow literal numbers that lose precision", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-loss-of-precision", + }, + schema: [], + messages: { + noLossOfPrecision: + "This number literal will lose precision at runtime.", + }, + }, + + create(context) { + /** + * Returns whether the node is number literal + * @param {Node} node the node literal being evaluated + * @returns {boolean} true if the node is a number literal + */ + function isNumber(node) { + return typeof node.value === "number"; + } + + /** + * Gets the source code of the given number literal. Removes `_` numeric separators from the result. + * @param {Node} node the number `Literal` node + * @returns {string} raw source code of the literal, without numeric separators + */ + function getRaw(node) { + return node.raw.replace(/_/gu, ""); + } + + /** + * Checks whether the number is base ten + * @param {ASTNode} node the node being evaluated + * @returns {boolean} true if the node is in base ten + */ + function isBaseTen(node) { + const prefixes = ["0x", "0X", "0b", "0B", "0o", "0O"]; + + return ( + prefixes.every(prefix => !node.raw.startsWith(prefix)) && + !/^0[0-7]+$/u.test(node.raw) + ); + } + + /** + * Checks that the user-intended non-base ten number equals the actual number after is has been converted to the Number type + * @param {Node} node the node being evaluated + * @returns {boolean} true if they do not match + */ + function notBaseTenLosesPrecision(node) { + const rawString = getRaw(node).toUpperCase(); + let base; + + if (rawString.startsWith("0B")) { + base = 2; + } else if (rawString.startsWith("0X")) { + base = 16; + } else { + base = 8; + } + + return !rawString.endsWith(node.value.toString(base).toUpperCase()); + } + + /** + * Adds a decimal point to the numeric string at index 1 + * @param {string} stringNumber the numeric string without any decimal point + * @returns {string} the numeric string with a decimal point in the proper place + */ + function addDecimalPointToNumber(stringNumber) { + return `${stringNumber[0]}.${stringNumber.slice(1)}`; + } + + /** + * Returns the number stripped of leading zeros + * @param {string} numberAsString the string representation of the number + * @returns {string} the stripped string + */ + function removeLeadingZeros(numberAsString) { + for (let i = 0; i < numberAsString.length; i++) { + if (numberAsString[i] !== "0") { + return numberAsString.slice(i); + } + } + return numberAsString; + } + + /** + * Returns the number stripped of trailing zeros + * @param {string} numberAsString the string representation of the number + * @returns {string} the stripped string + */ + function removeTrailingZeros(numberAsString) { + for (let i = numberAsString.length - 1; i >= 0; i--) { + if (numberAsString[i] !== "0") { + return numberAsString.slice(0, i + 1); + } + } + return numberAsString; + } + + /** + * Converts an integer to an object containing the integer's coefficient and order of magnitude + * @param {string} stringInteger the string representation of the integer being converted + * @returns {Object} the object containing the integer's coefficient and order of magnitude + */ + function normalizeInteger(stringInteger) { + const significantDigits = removeTrailingZeros( + removeLeadingZeros(stringInteger), + ); + + return { + magnitude: stringInteger.startsWith("0") + ? stringInteger.length - 2 + : stringInteger.length - 1, + coefficient: addDecimalPointToNumber(significantDigits), + }; + } + + /** + * + * Converts a float to an object containing the floats's coefficient and order of magnitude + * @param {string} stringFloat the string representation of the float being converted + * @returns {Object} the object containing the integer's coefficient and order of magnitude + */ + function normalizeFloat(stringFloat) { + const trimmedFloat = removeLeadingZeros(stringFloat); + + if (trimmedFloat.startsWith(".")) { + const decimalDigits = trimmedFloat.slice(1); + const significantDigits = removeLeadingZeros(decimalDigits); + + return { + magnitude: + significantDigits.length - decimalDigits.length - 1, + coefficient: addDecimalPointToNumber(significantDigits), + }; + } + return { + magnitude: trimmedFloat.indexOf(".") - 1, + coefficient: addDecimalPointToNumber( + trimmedFloat.replace(".", ""), + ), + }; + } + + /** + * Converts a base ten number to proper scientific notation + * @param {string} stringNumber the string representation of the base ten number to be converted + * @returns {string} the number converted to scientific notation + */ + function convertNumberToScientificNotation(stringNumber) { + const splitNumber = stringNumber.replace("E", "e").split("e"); + const originalCoefficient = splitNumber[0]; + const normalizedNumber = stringNumber.includes(".") + ? normalizeFloat(originalCoefficient) + : normalizeInteger(originalCoefficient); + const normalizedCoefficient = normalizedNumber.coefficient; + const magnitude = + splitNumber.length > 1 + ? parseInt(splitNumber[1], 10) + normalizedNumber.magnitude + : normalizedNumber.magnitude; + + return `${normalizedCoefficient}e${magnitude}`; + } + + /** + * Checks that the user-intended base ten number equals the actual number after is has been converted to the Number type + * @param {Node} node the node being evaluated + * @returns {boolean} true if they do not match + */ + function baseTenLosesPrecision(node) { + const normalizedRawNumber = convertNumberToScientificNotation( + getRaw(node), + ); + const requestedPrecision = normalizedRawNumber + .split("e")[0] + .replace(".", "").length; + + if (requestedPrecision > 100) { + return true; + } + const storedNumber = node.value.toPrecision(requestedPrecision); + const normalizedStoredNumber = + convertNumberToScientificNotation(storedNumber); + + return normalizedRawNumber !== normalizedStoredNumber; + } + + /** + * Checks that the user-intended number equals the actual number after is has been converted to the Number type + * @param {Node} node the node being evaluated + * @returns {boolean} true if they do not match + */ + function losesPrecision(node) { + return isBaseTen(node) + ? baseTenLosesPrecision(node) + : notBaseTenLosesPrecision(node); + } + + return { + Literal(node) { + if (node.value && isNumber(node) && losesPrecision(node)) { + context.report({ + messageId: "noLossOfPrecision", + node, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-magic-numbers.js b/node_modules/eslint/lib/rules/no-magic-numbers.js new file mode 100644 index 00000000..bed61a06 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-magic-numbers.js @@ -0,0 +1,365 @@ +/** + * @fileoverview Rule to flag statements that use magic numbers (adapted from https://github.com/danielstjules/buddy.js) + * @author Vincent Lemeunier + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +// Maximum array length by the ECMAScript Specification. +const MAX_ARRAY_LENGTH = 2 ** 32 - 1; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Convert the value to bigint if it's a string. Otherwise return the value as-is. + * @param {bigint|number|string} x The value to normalize. + * @returns {bigint|number} The normalized value. + */ +function normalizeIgnoreValue(x) { + if (typeof x === "string") { + return BigInt(x.slice(0, -1)); + } + return x; +} + +/** + * Checks if the node parent is a TypeScript enum member + * @param {ASTNode} node The node to be validated + * @returns {boolean} True if the node parent is a TypeScript enum member + */ +function isParentTSEnumDeclaration(node) { + return node.parent.type === "TSEnumMember"; +} + +/** + * Checks if the node is a valid TypeScript numeric literal type. + * @param {ASTNode} node The node to be validated + * @returns {boolean} True if the node is a TypeScript numeric literal type + */ +function isTSNumericLiteralType(node) { + let ancestor = node.parent; + + // Go up while we're part of a type union + while (ancestor.parent.type === "TSUnionType") { + ancestor = ancestor.parent; + } + + // Check if the final ancestor is in a type alias declaration + return ancestor.parent.type === "TSTypeAliasDeclaration"; +} + +/** + * Checks if the node parent is a readonly class property + * @param {ASTNode} node The node to be validated + * @returns {boolean} True if the node parent is a readonly class property + */ +function isParentTSReadonlyPropertyDefinition(node) { + if (node.parent?.type === "PropertyDefinition" && node.parent.readonly) { + return true; + } + + return false; +} + +/** + * Checks if the node is part of a type indexed access (eg. Foo[4]) + * @param {ASTNode} node The node to be validated + * @returns {boolean} True if the node is part of an indexed access + */ +function isAncestorTSIndexedAccessType(node) { + let ancestor = node.parent; + + /* + * Go up another level while we're part of a type union (eg. 1 | 2) or + * intersection (eg. 1 & 2) + */ + while ( + ancestor.parent.type === "TSUnionType" || + ancestor.parent.type === "TSIntersectionType" + ) { + ancestor = ancestor.parent; + } + + return ancestor.parent.type === "TSIndexedAccessType"; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: "Disallow magic numbers", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-magic-numbers", + }, + + schema: [ + { + type: "object", + properties: { + detectObjects: { + type: "boolean", + default: false, + }, + enforceConst: { + type: "boolean", + default: false, + }, + ignore: { + type: "array", + items: { + anyOf: [ + { type: "number" }, + { + type: "string", + pattern: "^[+-]?(?:0|[1-9][0-9]*)n$", + }, + ], + }, + uniqueItems: true, + }, + ignoreArrayIndexes: { + type: "boolean", + default: false, + }, + ignoreDefaultValues: { + type: "boolean", + default: false, + }, + ignoreClassFieldInitialValues: { + type: "boolean", + default: false, + }, + ignoreEnums: { + type: "boolean", + default: false, + }, + ignoreNumericLiteralTypes: { + type: "boolean", + default: false, + }, + ignoreReadonlyClassProperties: { + type: "boolean", + default: false, + }, + ignoreTypeIndexes: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + useConst: "Number constants declarations must use 'const'.", + noMagic: "No magic number: {{raw}}.", + }, + }, + + create(context) { + const config = context.options[0] || {}, + detectObjects = !!config.detectObjects, + enforceConst = !!config.enforceConst, + ignore = new Set((config.ignore || []).map(normalizeIgnoreValue)), + ignoreArrayIndexes = !!config.ignoreArrayIndexes, + ignoreDefaultValues = !!config.ignoreDefaultValues, + ignoreClassFieldInitialValues = + !!config.ignoreClassFieldInitialValues, + ignoreEnums = !!config.ignoreEnums, + ignoreNumericLiteralTypes = !!config.ignoreNumericLiteralTypes, + ignoreReadonlyClassProperties = + !!config.ignoreReadonlyClassProperties, + ignoreTypeIndexes = !!config.ignoreTypeIndexes; + + const okTypes = detectObjects + ? [] + : ["ObjectExpression", "Property", "AssignmentExpression"]; + + /** + * Returns whether the rule is configured to ignore the given value + * @param {bigint|number} value The value to check + * @returns {boolean} true if the value is ignored + */ + function isIgnoredValue(value) { + return ignore.has(value); + } + + /** + * Returns whether the number is a default value assignment. + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the number is a default value + */ + function isDefaultValue(fullNumberNode) { + const parent = fullNumberNode.parent; + + return ( + parent.type === "AssignmentPattern" && + parent.right === fullNumberNode + ); + } + + /** + * Returns whether the number is the initial value of a class field. + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the number is the initial value of a class field. + */ + function isClassFieldInitialValue(fullNumberNode) { + const parent = fullNumberNode.parent; + + return ( + parent.type === "PropertyDefinition" && + parent.value === fullNumberNode + ); + } + + /** + * Returns whether the given node is used as a radix within parseInt() or Number.parseInt() + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the node is radix + */ + function isParseIntRadix(fullNumberNode) { + const parent = fullNumberNode.parent; + + return ( + parent.type === "CallExpression" && + fullNumberNode === parent.arguments[1] && + (astUtils.isSpecificId(parent.callee, "parseInt") || + astUtils.isSpecificMemberAccess( + parent.callee, + "Number", + "parseInt", + )) + ); + } + + /** + * Returns whether the given node is a direct child of a JSX node. + * In particular, it aims to detect numbers used as prop values in JSX tags. + * Example: + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the node is a JSX number + */ + function isJSXNumber(fullNumberNode) { + return fullNumberNode.parent.type.indexOf("JSX") === 0; + } + + /** + * Returns whether the given node is used as an array index. + * Value must coerce to a valid array index name: "0", "1", "2" ... "4294967294". + * + * All other values, like "-1", "2.5", or "4294967295", are just "normal" object properties, + * which can be created and accessed on an array in addition to the array index properties, + * but they don't affect array's length and are not considered by methods such as .map(), .forEach() etc. + * + * The maximum array length by the specification is 2 ** 32 - 1 = 4294967295, + * thus the maximum valid index is 2 ** 32 - 2 = 4294967294. + * + * All notations are allowed, as long as the value coerces to one of "0", "1", "2" ... "4294967294". + * + * Valid examples: + * a[0], a[1], a[1.2e1], a[0xAB], a[0n], a[1n] + * a[-0] (same as a[0] because -0 coerces to "0") + * a[-0n] (-0n evaluates to 0n) + * + * Invalid examples: + * a[-1], a[-0xAB], a[-1n], a[2.5], a[1.23e1], a[12e-1] + * a[4294967295] (above the max index, it's an access to a regular property a["4294967295"]) + * a[999999999999999999999] (even if it wasn't above the max index, it would be a["1e+21"]) + * a[1e310] (same as a["Infinity"]) + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @param {bigint|number} value Value expressed by the fullNumberNode + * @returns {boolean} true if the node is a valid array index + */ + function isArrayIndex(fullNumberNode, value) { + const parent = fullNumberNode.parent; + + return ( + parent.type === "MemberExpression" && + parent.property === fullNumberNode && + (Number.isInteger(value) || typeof value === "bigint") && + value >= 0 && + value < MAX_ARRAY_LENGTH + ); + } + + return { + Literal(node) { + if (!astUtils.isNumericLiteral(node)) { + return; + } + + let fullNumberNode; + let value; + let raw; + + // Treat unary minus/plus as a part of the number + if ( + node.parent.type === "UnaryExpression" && + ["-", "+"].includes(node.parent.operator) + ) { + fullNumberNode = node.parent; + value = + node.parent.operator === "-" ? -node.value : node.value; + raw = `${node.parent.operator}${node.raw}`; + } else { + fullNumberNode = node; + value = node.value; + raw = node.raw; + } + + const parent = fullNumberNode.parent; + + // Always allow radix arguments and JSX props + if ( + isIgnoredValue(value) || + (ignoreDefaultValues && isDefaultValue(fullNumberNode)) || + (ignoreClassFieldInitialValues && + isClassFieldInitialValue(fullNumberNode)) || + (ignoreEnums && + isParentTSEnumDeclaration(fullNumberNode)) || + (ignoreNumericLiteralTypes && + isTSNumericLiteralType(fullNumberNode)) || + (ignoreTypeIndexes && + isAncestorTSIndexedAccessType(fullNumberNode)) || + (ignoreReadonlyClassProperties && + isParentTSReadonlyPropertyDefinition(fullNumberNode)) || + isParseIntRadix(fullNumberNode) || + isJSXNumber(fullNumberNode) || + (ignoreArrayIndexes && isArrayIndex(fullNumberNode, value)) + ) { + return; + } + + if (parent.type === "VariableDeclarator") { + if (enforceConst && parent.parent.kind !== "const") { + context.report({ + node: fullNumberNode, + messageId: "useConst", + }); + } + } else if ( + !okTypes.includes(parent.type) || + (parent.type === "AssignmentExpression" && + parent.left.type === "Identifier") + ) { + context.report({ + node: fullNumberNode, + messageId: "noMagic", + data: { + raw, + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-misleading-character-class.js b/node_modules/eslint/lib/rules/no-misleading-character-class.js new file mode 100644 index 00000000..2e1318aa --- /dev/null +++ b/node_modules/eslint/lib/rules/no-misleading-character-class.js @@ -0,0 +1,590 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStaticValue, + getStringIfConstant, +} = require("@eslint-community/eslint-utils"); +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); +const { + isCombiningCharacter, + isEmojiModifier, + isRegionalIndicatorSymbol, + isSurrogatePair, +} = require("./utils/unicode"); +const astUtils = require("./utils/ast-utils.js"); +const { isValidWithUnicodeFlag } = require("./utils/regular-expressions"); +const { + parseStringLiteral, + parseTemplateToken, +} = require("./utils/char-source"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * @typedef {import('@eslint-community/regexpp').AST.Character} Character + * @typedef {import('@eslint-community/regexpp').AST.CharacterClassElement} CharacterClassElement + */ + +/** + * Iterate character sequences of a given nodes. + * + * CharacterClassRange syntax can steal a part of character sequence, + * so this function reverts CharacterClassRange syntax and restore the sequence. + * @param {CharacterClassElement[]} nodes The node list to iterate character sequences. + * @returns {IterableIterator} The list of character sequences. + */ +function* iterateCharacterSequence(nodes) { + /** @type {Character[]} */ + let seq = []; + + for (const node of nodes) { + switch (node.type) { + case "Character": + seq.push(node); + break; + + case "CharacterClassRange": + seq.push(node.min); + yield seq; + seq = [node.max]; + break; + + case "CharacterSet": + case "CharacterClass": // [[]] nesting character class + case "ClassStringDisjunction": // \q{...} + case "ExpressionCharacterClass": // [A--B] + if (seq.length > 0) { + yield seq; + seq = []; + } + break; + + // no default + } + } + + if (seq.length > 0) { + yield seq; + } +} + +/** + * Checks whether the given character node is a Unicode code point escape or not. + * @param {Character} char the character node to check. + * @returns {boolean} `true` if the character node is a Unicode code point escape. + */ +function isUnicodeCodePointEscape(char) { + return /^\\u\{[\da-f]+\}$/iu.test(char.raw); +} + +/** + * Each function returns matched characters if it detects that kind of problem. + * @type {Record IterableIterator>} + */ +const findCharacterSequences = { + *surrogatePairWithoutUFlag(chars) { + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + + if ( + previous && + char && + isSurrogatePair(previous.value, char.value) && + !isUnicodeCodePointEscape(previous) && + !isUnicodeCodePointEscape(char) + ) { + yield [previous, char]; + } + } + }, + + *surrogatePair(chars) { + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + + if ( + previous && + char && + isSurrogatePair(previous.value, char.value) && + (isUnicodeCodePointEscape(previous) || + isUnicodeCodePointEscape(char)) + ) { + yield [previous, char]; + } + } + }, + + *combiningClass(chars, unfilteredChars) { + /* + * When `allowEscape` is `true`, a combined character should only be allowed if the combining mark appears as an escape sequence. + * This means that the base character should be considered even if it's escaped. + */ + for (const [index, char] of chars.entries()) { + const previous = unfilteredChars[index - 1]; + + if ( + previous && + char && + isCombiningCharacter(char.value) && + !isCombiningCharacter(previous.value) + ) { + yield [previous, char]; + } + } + }, + + *emojiModifier(chars) { + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + + if ( + previous && + char && + isEmojiModifier(char.value) && + !isEmojiModifier(previous.value) + ) { + yield [previous, char]; + } + } + }, + + *regionalIndicatorSymbol(chars) { + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + + if ( + previous && + char && + isRegionalIndicatorSymbol(char.value) && + isRegionalIndicatorSymbol(previous.value) + ) { + yield [previous, char]; + } + } + }, + + *zwj(chars) { + let sequence = null; + + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + const next = chars[index + 1]; + + if ( + previous && + char && + next && + char.value === 0x200d && + previous.value !== 0x200d && + next.value !== 0x200d + ) { + if (sequence) { + if (sequence.at(-1) === previous) { + sequence.push(char, next); // append to the sequence + } else { + yield sequence; + sequence = chars.slice(index - 1, index + 2); + } + } else { + sequence = chars.slice(index - 1, index + 2); + } + } + } + + if (sequence) { + yield sequence; + } + }, +}; + +const kinds = Object.keys(findCharacterSequences); + +/** + * Gets the value of the given node if it's a static value other than a regular expression object, + * or the node's `regex` property. + * The purpose of this method is to provide a replacement for `getStaticValue` in environments where certain regular expressions cannot be evaluated. + * A known example is Node.js 18 which does not support the `v` flag. + * Calling `getStaticValue` on a regular expression node with the `v` flag on Node.js 18 always returns `null`. + * A limitation of this method is that it can only detect a regular expression if the specified node is itself a regular expression literal node. + * @param {ASTNode | undefined} node The node to be inspected. + * @param {Scope} initialScope Scope to start finding variables. This function tries to resolve identifier references which are in the given scope. + * @returns {{ value: any } | { regex: { pattern: string, flags: string } } | null} The static value of the node, or `null`. + */ +function getStaticValueOrRegex(node, initialScope) { + if (!node) { + return null; + } + if (node.type === "Literal" && node.regex) { + return { regex: node.regex }; + } + + const staticValue = getStaticValue(node, initialScope); + + if (staticValue?.value instanceof RegExp) { + return null; + } + return staticValue; +} + +/** + * Checks whether a specified regexpp character is represented as an acceptable escape sequence. + * This function requires the source text of the character to be known. + * @param {Character} char Character to check. + * @param {string} charSource Source text of the character to check. + * @returns {boolean} Whether the specified regexpp character is represented as an acceptable escape sequence. + */ +function checkForAcceptableEscape(char, charSource) { + if (!charSource.startsWith("\\")) { + return false; + } + const match = /(?<=^\\+).$/su.exec(charSource); + + return match?.[0] !== String.fromCodePoint(char.value); +} + +/** + * Checks whether a specified regexpp character is represented as an acceptable escape sequence. + * This function works with characters that are produced by a string or template literal. + * It requires the source text and the CodeUnit list of the literal to be known. + * @param {Character} char Character to check. + * @param {string} nodeSource Source text of the string or template literal that produces the character. + * @param {CodeUnit[]} codeUnits List of CodeUnit objects of the literal that produces the character. + * @returns {boolean} Whether the specified regexpp character is represented as an acceptable escape sequence. + */ +function checkForAcceptableEscapeInString(char, nodeSource, codeUnits) { + const firstIndex = char.start; + const lastIndex = char.end - 1; + const start = codeUnits[firstIndex].start; + const end = codeUnits[lastIndex].end; + const charSource = nodeSource.slice(start, end); + + return checkForAcceptableEscape(char, charSource); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow characters which are made with multiple code points in character class syntax", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-misleading-character-class", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + allowEscape: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + surrogatePairWithoutUFlag: + "Unexpected surrogate pair in character class. Use 'u' flag.", + surrogatePair: "Unexpected surrogate pair in character class.", + combiningClass: "Unexpected combined character in character class.", + emojiModifier: "Unexpected modified Emoji in character class.", + regionalIndicatorSymbol: + "Unexpected national flag in character class.", + zwj: "Unexpected joined character sequence in character class.", + suggestUnicodeFlag: "Add unicode 'u' flag to regex.", + }, + }, + create(context) { + const allowEscape = context.options[0]?.allowEscape; + const sourceCode = context.sourceCode; + const parser = new RegExpParser(); + const checkedPatternNodes = new Set(); + + /** + * Verify a given regular expression. + * @param {Node} node The node to report. + * @param {string} pattern The regular expression pattern to verify. + * @param {string} flags The flags of the regular expression. + * @param {Function} unicodeFixer Fixer for missing "u" flag. + * @returns {void} + */ + function verify(node, pattern, flags, unicodeFixer) { + let patternNode; + + try { + patternNode = parser.parsePattern(pattern, 0, pattern.length, { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }); + } catch { + // Ignore regular expressions with syntax errors + return; + } + + let codeUnits = null; + + /** + * Checks whether a specified regexpp character is represented as an acceptable escape sequence. + * For the purposes of this rule, an escape sequence is considered acceptable if it consists of one or more backslashes followed by the character being escaped. + * @param {Character} char Character to check. + * @returns {boolean} Whether the specified regexpp character is represented as an acceptable escape sequence. + */ + function isAcceptableEscapeSequence(char) { + if (node.type === "Literal" && node.regex) { + return checkForAcceptableEscape(char, char.raw); + } + if (node.type === "Literal" && typeof node.value === "string") { + const nodeSource = node.raw; + + codeUnits ??= parseStringLiteral(nodeSource); + + return checkForAcceptableEscapeInString( + char, + nodeSource, + codeUnits, + ); + } + if (astUtils.isStaticTemplateLiteral(node)) { + const nodeSource = sourceCode.getText(node); + + codeUnits ??= parseTemplateToken(nodeSource); + + return checkForAcceptableEscapeInString( + char, + nodeSource, + codeUnits, + ); + } + return false; + } + + const foundKindMatches = new Map(); + + visitRegExpAST(patternNode, { + onCharacterClassEnter(ccNode) { + for (const unfilteredChars of iterateCharacterSequence( + ccNode.elements, + )) { + let chars; + + if (allowEscape) { + // Replace escape sequences with null to avoid having them flagged. + chars = unfilteredChars.map(char => + isAcceptableEscapeSequence(char) ? null : char, + ); + } else { + chars = unfilteredChars; + } + for (const kind of kinds) { + const matches = findCharacterSequences[kind]( + chars, + unfilteredChars, + ); + + if (foundKindMatches.has(kind)) { + foundKindMatches.get(kind).push(...matches); + } else { + foundKindMatches.set(kind, [...matches]); + } + } + } + }, + }); + + /** + * Finds the report loc(s) for a range of matches. + * Only literals and expression-less templates generate granular errors. + * @param {Character[][]} matches Lists of individual characters being reported on. + * @returns {Location[]} locs for context.report. + * @see https://github.com/eslint/eslint/pull/17515 + */ + function getNodeReportLocations(matches) { + if ( + !astUtils.isStaticTemplateLiteral(node) && + node.type !== "Literal" + ) { + return matches.length ? [node.loc] : []; + } + return matches.map(chars => { + const firstIndex = chars[0].start; + const lastIndex = chars.at(-1).end - 1; + let start; + let end; + + if (node.type === "TemplateLiteral") { + const source = sourceCode.getText(node); + const offset = node.range[0]; + + codeUnits ??= parseTemplateToken(source); + start = offset + codeUnits[firstIndex].start; + end = offset + codeUnits[lastIndex].end; + } else if (typeof node.value === "string") { + // String Literal + const source = node.raw; + const offset = node.range[0]; + + codeUnits ??= parseStringLiteral(source); + start = offset + codeUnits[firstIndex].start; + end = offset + codeUnits[lastIndex].end; + } else { + // RegExp Literal + const offset = node.range[0] + 1; // Add 1 to skip the leading slash. + + start = offset + firstIndex; + end = offset + lastIndex + 1; + } + + return { + start: sourceCode.getLocFromIndex(start), + end: sourceCode.getLocFromIndex(end), + }; + }); + } + + for (const [kind, matches] of foundKindMatches) { + let suggest; + + if (kind === "surrogatePairWithoutUFlag") { + suggest = [ + { + messageId: "suggestUnicodeFlag", + fix: unicodeFixer, + }, + ]; + } + + const locs = getNodeReportLocations(matches); + + for (const loc of locs) { + context.report({ + node, + loc, + messageId: kind, + suggest, + }); + } + } + } + + return { + "Literal[regex]"(node) { + if (checkedPatternNodes.has(node)) { + return; + } + verify(node, node.regex.pattern, node.regex.flags, fixer => { + if ( + !isValidWithUnicodeFlag( + context.languageOptions.ecmaVersion, + node.regex.pattern, + ) + ) { + return null; + } + + return fixer.insertTextAfter(node, "u"); + }); + }, + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + + /* + * Iterate calls of RegExp. + * E.g., `new RegExp()`, `RegExp()`, `new window.RegExp()`, + * `const {RegExp: a} = window; new a()`, etc... + */ + for (const { node: refNode } of tracker.iterateGlobalReferences( + { + RegExp: { [CALL]: true, [CONSTRUCT]: true }, + }, + )) { + let pattern, flags; + const [patternNode, flagsNode] = refNode.arguments; + const evaluatedPattern = getStaticValueOrRegex( + patternNode, + scope, + ); + + if (!evaluatedPattern) { + continue; + } + if (flagsNode) { + if (evaluatedPattern.regex) { + pattern = evaluatedPattern.regex.pattern; + checkedPatternNodes.add(patternNode); + } else { + pattern = String(evaluatedPattern.value); + } + flags = getStringIfConstant(flagsNode, scope); + } else { + if (evaluatedPattern.regex) { + continue; + } + pattern = String(evaluatedPattern.value); + flags = ""; + } + + if (typeof flags === "string") { + verify(patternNode, pattern, flags, fixer => { + if ( + !isValidWithUnicodeFlag( + context.languageOptions.ecmaVersion, + pattern, + ) + ) { + return null; + } + + if (refNode.arguments.length === 1) { + const penultimateToken = + sourceCode.getLastToken(refNode, { + skip: 1, + }); // skip closing parenthesis + + return fixer.insertTextAfter( + penultimateToken, + astUtils.isCommaToken(penultimateToken) + ? ' "u",' + : ', "u"', + ); + } + + if ( + (flagsNode.type === "Literal" && + typeof flagsNode.value === "string") || + flagsNode.type === "TemplateLiteral" + ) { + const range = [ + flagsNode.range[0], + flagsNode.range[1] - 1, + ]; + + return fixer.insertTextAfterRange(range, "u"); + } + + return null; + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-mixed-operators.js b/node_modules/eslint/lib/rules/no-mixed-operators.js new file mode 100644 index 00000000..b6835f53 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-mixed-operators.js @@ -0,0 +1,253 @@ +/** + * @fileoverview Rule to disallow mixed binary operators. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils.js"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const ARITHMETIC_OPERATORS = ["+", "-", "*", "/", "%", "**"]; +const BITWISE_OPERATORS = ["&", "|", "^", "~", "<<", ">>", ">>>"]; +const COMPARISON_OPERATORS = ["==", "!=", "===", "!==", ">", ">=", "<", "<="]; +const LOGICAL_OPERATORS = ["&&", "||"]; +const RELATIONAL_OPERATORS = ["in", "instanceof"]; +const TERNARY_OPERATOR = ["?:"]; +const COALESCE_OPERATOR = ["??"]; +const ALL_OPERATORS = [].concat( + ARITHMETIC_OPERATORS, + BITWISE_OPERATORS, + COMPARISON_OPERATORS, + LOGICAL_OPERATORS, + RELATIONAL_OPERATORS, + TERNARY_OPERATOR, + COALESCE_OPERATOR, +); +const DEFAULT_GROUPS = [ + ARITHMETIC_OPERATORS, + BITWISE_OPERATORS, + COMPARISON_OPERATORS, + LOGICAL_OPERATORS, + RELATIONAL_OPERATORS, +]; +const TARGET_NODE_TYPE = /^(?:Binary|Logical|Conditional)Expression$/u; + +/** + * Normalizes options. + * @param {Object|undefined} options A options object to normalize. + * @returns {Object} Normalized option object. + */ +function normalizeOptions(options = {}) { + const hasGroups = options.groups && options.groups.length > 0; + const groups = hasGroups ? options.groups : DEFAULT_GROUPS; + const allowSamePrecedence = options.allowSamePrecedence !== false; + + return { + groups, + allowSamePrecedence, + }; +} + +/** + * Checks whether any group which includes both given operator exists or not. + * @param {Array} groups A list of groups to check. + * @param {string} left An operator. + * @param {string} right Another operator. + * @returns {boolean} `true` if such group existed. + */ +function includesBothInAGroup(groups, left, right) { + return groups.some(group => group.includes(left) && group.includes(right)); +} + +/** + * Checks whether the given node is a conditional expression and returns the test node else the left node. + * @param {ASTNode} node A node which can be a BinaryExpression or a LogicalExpression node. + * This parent node can be BinaryExpression, LogicalExpression + * , or a ConditionalExpression node + * @returns {ASTNode} node the appropriate node(left or test). + */ +function getChildNode(node) { + return node.type === "ConditionalExpression" ? node.test : node.left; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-mixed-operators", + url: "https://eslint.style/rules/js/no-mixed-operators", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: "Disallow mixed binary operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-mixed-operators", + }, + + schema: [ + { + type: "object", + properties: { + groups: { + type: "array", + items: { + type: "array", + items: { enum: ALL_OPERATORS }, + minItems: 2, + uniqueItems: true, + }, + uniqueItems: true, + }, + allowSamePrecedence: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedMixedOperator: + "Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'. Use parentheses to clarify the intended order of operations.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = normalizeOptions(context.options[0]); + + /** + * Checks whether a given node should be ignored by options or not. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. This parent node is one of + * them, too. + * @returns {boolean} `true` if the node should be ignored. + */ + function shouldIgnore(node) { + const a = node; + const b = node.parent; + + return ( + !includesBothInAGroup( + options.groups, + a.operator, + b.type === "ConditionalExpression" ? "?:" : b.operator, + ) || + (options.allowSamePrecedence && + astUtils.getPrecedence(a) === astUtils.getPrecedence(b)) + ); + } + + /** + * Checks whether the operator of a given node is mixed with parent + * node's operator or not. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. This parent node is one of + * them, too. + * @returns {boolean} `true` if the node was mixed. + */ + function isMixedWithParent(node) { + return ( + node.operator !== node.parent.operator && + !astUtils.isParenthesised(sourceCode, node) + ); + } + + /** + * Gets the operator token of a given node. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. + * @returns {Token} The operator token of the node. + */ + function getOperatorToken(node) { + return sourceCode.getTokenAfter( + getChildNode(node), + astUtils.isNotClosingParenToken, + ); + } + + /** + * Reports both the operator of a given node and the operator of the + * parent node. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. This parent node is one of + * them, too. + * @returns {void} + */ + function reportBothOperators(node) { + const parent = node.parent; + const left = getChildNode(parent) === node ? node : parent; + const right = getChildNode(parent) !== node ? node : parent; + const data = { + leftOperator: left.operator || "?:", + rightOperator: right.operator || "?:", + }; + + context.report({ + node: left, + loc: getOperatorToken(left).loc, + messageId: "unexpectedMixedOperator", + data, + }); + context.report({ + node: right, + loc: getOperatorToken(right).loc, + messageId: "unexpectedMixedOperator", + data, + }); + } + + /** + * Checks between the operator of this node and the operator of the + * parent node. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function check(node) { + if ( + TARGET_NODE_TYPE.test(node.parent.type) && + isMixedWithParent(node) && + !shouldIgnore(node) + ) { + reportBothOperators(node); + } + } + + return { + BinaryExpression: check, + LogicalExpression: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-mixed-requires.js b/node_modules/eslint/lib/rules/no-mixed-requires.js new file mode 100644 index 00000000..cbab7310 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-mixed-requires.js @@ -0,0 +1,267 @@ +/** + * @fileoverview Rule to enforce grouped require statements for Node.JS + * @author Raphael Pigulla + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-mixed-requires", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-mixed-requires.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: + "Disallow `require` calls to be mixed with regular variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-mixed-requires", + }, + + schema: [ + { + oneOf: [ + { + type: "boolean", + }, + { + type: "object", + properties: { + grouping: { + type: "boolean", + }, + allowCall: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + noMixRequire: "Do not mix 'require' and other declarations.", + noMixCoreModuleFileComputed: + "Do not mix core, module, file and computed requires.", + }, + }, + + create(context) { + const options = context.options[0]; + let grouping = false, + allowCall = false; + + if (typeof options === "object") { + grouping = options.grouping; + allowCall = options.allowCall; + } else { + grouping = !!options; + } + + /** + * Returns the list of built-in modules. + * @returns {string[]} An array of built-in Node.js modules. + */ + function getBuiltinModules() { + /* + * This list is generated using: + * `require("repl")._builtinLibs.concat('repl').sort()` + * This particular list is as per nodejs v0.12.2 and iojs v0.7.1 + */ + return [ + "assert", + "buffer", + "child_process", + "cluster", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "net", + "os", + "path", + "punycode", + "querystring", + "readline", + "repl", + "smalloc", + "stream", + "string_decoder", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib", + ]; + } + + const BUILTIN_MODULES = getBuiltinModules(); + + const DECL_REQUIRE = "require", + DECL_UNINITIALIZED = "uninitialized", + DECL_OTHER = "other"; + + const REQ_CORE = "core", + REQ_FILE = "file", + REQ_MODULE = "module", + REQ_COMPUTED = "computed"; + + /** + * Determines the type of a declaration statement. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The type of declaration represented by the expression. + */ + function getDeclarationType(initExpression) { + if (!initExpression) { + // "var x;" + return DECL_UNINITIALIZED; + } + + if ( + initExpression.type === "CallExpression" && + initExpression.callee.type === "Identifier" && + initExpression.callee.name === "require" + ) { + // "var x = require('util');" + return DECL_REQUIRE; + } + if ( + allowCall && + initExpression.type === "CallExpression" && + initExpression.callee.type === "CallExpression" + ) { + // "var x = require('diagnose')('sub-module');" + return getDeclarationType(initExpression.callee); + } + if (initExpression.type === "MemberExpression") { + // "var x = require('glob').Glob;" + return getDeclarationType(initExpression.object); + } + + // "var x = 42;" + return DECL_OTHER; + } + + /** + * Determines the type of module that is loaded via require. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The module type. + */ + function inferModuleType(initExpression) { + if (initExpression.type === "MemberExpression") { + // "var x = require('glob').Glob;" + return inferModuleType(initExpression.object); + } + if (initExpression.arguments.length === 0) { + // "var x = require();" + return REQ_COMPUTED; + } + + const arg = initExpression.arguments[0]; + + if (arg.type !== "Literal" || typeof arg.value !== "string") { + // "var x = require(42);" + return REQ_COMPUTED; + } + + if (BUILTIN_MODULES.includes(arg.value)) { + // "var fs = require('fs');" + return REQ_CORE; + } + if (/^\.{0,2}\//u.test(arg.value)) { + // "var utils = require('./utils');" + return REQ_FILE; + } + + // "var async = require('async');" + return REQ_MODULE; + } + + /** + * Check if the list of variable declarations is mixed, i.e. whether it + * contains both require and other declarations. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are mixed, false if not. + */ + function isMixed(declarations) { + const contains = {}; + + declarations.forEach(declaration => { + const type = getDeclarationType(declaration.init); + + contains[type] = true; + }); + + return !!( + contains[DECL_REQUIRE] && + (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER]) + ); + } + + /** + * Check if all require declarations in the given list are of the same + * type. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are grouped, false if not. + */ + function isGrouped(declarations) { + const found = {}; + + declarations.forEach(declaration => { + if (getDeclarationType(declaration.init) === DECL_REQUIRE) { + found[inferModuleType(declaration.init)] = true; + } + }); + + return Object.keys(found).length <= 1; + } + + return { + VariableDeclaration(node) { + if (isMixed(node.declarations)) { + context.report({ + node, + messageId: "noMixRequire", + }); + } else if (grouping && !isGrouped(node.declarations)) { + context.report({ + node, + messageId: "noMixCoreModuleFileComputed", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js b/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js new file mode 100644 index 00000000..7be203c9 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js @@ -0,0 +1,147 @@ +/** + * @fileoverview Disallow mixed spaces and tabs for indentation + * @author Jary Niebur + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-mixed-spaces-and-tabs", + url: "https://eslint.style/rules/js/no-mixed-spaces-and-tabs", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow mixed spaces and tabs for indentation", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-mixed-spaces-and-tabs", + }, + + schema: [ + { + enum: ["smart-tabs", true, false], + }, + ], + + messages: { + mixedSpacesAndTabs: "Mixed spaces and tabs.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + let smartTabs; + + switch (context.options[0]) { + case true: // Support old syntax, maybe add deprecation warning here + case "smart-tabs": + smartTabs = true; + break; + default: + smartTabs = false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program:exit"(node) { + const lines = sourceCode.lines, + comments = sourceCode.getAllComments(), + ignoredCommentLines = new Set(); + + // Add all lines except the first ones. + comments.forEach(comment => { + for ( + let i = comment.loc.start.line + 1; + i <= comment.loc.end.line; + i++ + ) { + ignoredCommentLines.add(i); + } + }); + + /* + * At least one space followed by a tab + * or the reverse before non-tab/-space + * characters begin. + */ + let regex = /^(?=( +|\t+))\1(?:\t| )/u; + + if (smartTabs) { + /* + * At least one space followed by a tab + * before non-tab/-space characters begin. + */ + regex = /^(?=(\t*))\1(?=( +))\2\t/u; + } + + lines.forEach((line, i) => { + const match = regex.exec(line); + + if (match) { + const lineNumber = i + 1; + const loc = { + start: { + line: lineNumber, + column: match[0].length - 2, + }, + end: { + line: lineNumber, + column: match[0].length, + }, + }; + + if (!ignoredCommentLines.has(lineNumber)) { + const containingNode = + sourceCode.getNodeByRangeIndex( + sourceCode.getIndexFromLoc(loc.start), + ); + + if ( + !( + containingNode && + ["Literal", "TemplateElement"].includes( + containingNode.type, + ) + ) + ) { + context.report({ + node, + loc, + messageId: "mixedSpacesAndTabs", + }); + } + } + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-multi-assign.js b/node_modules/eslint/lib/rules/no-multi-assign.js new file mode 100644 index 00000000..b4d6ddb4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multi-assign.js @@ -0,0 +1,66 @@ +/** + * @fileoverview Rule to check use of chained assignment expressions + * @author Stewart Rand + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + ignoreNonDeclaration: false, + }, + ], + + docs: { + description: "Disallow use of chained assignment expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multi-assign", + }, + + schema: [ + { + type: "object", + properties: { + ignoreNonDeclaration: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedChain: "Unexpected chained assignment.", + }, + }, + + create(context) { + const [{ ignoreNonDeclaration }] = context.options; + const selectors = [ + "VariableDeclarator > AssignmentExpression.init", + "PropertyDefinition > AssignmentExpression.value", + ]; + + if (!ignoreNonDeclaration) { + selectors.push("AssignmentExpression > AssignmentExpression.right"); + } + + return { + [selectors](node) { + context.report({ + node, + messageId: "unexpectedChain", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-multi-spaces.js b/node_modules/eslint/lib/rules/no-multi-spaces.js new file mode 100644 index 00000000..04b507e4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multi-spaces.js @@ -0,0 +1,179 @@ +/** + * @fileoverview Disallow use of multiple spaces. + * @author Nicholas C. Zakas + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-multi-spaces", + url: "https://eslint.style/rules/js/no-multi-spaces", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow multiple spaces", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multi-spaces", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "object", + patternProperties: { + "^([A-Z][a-z]*)+$": { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ignoreEOLComments: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + multipleSpaces: "Multiple spaces found before '{{displayValue}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = context.options[0] || {}; + const ignoreEOLComments = options.ignoreEOLComments; + const exceptions = Object.assign( + { Property: true }, + options.exceptions, + ); + const hasExceptions = Object.keys(exceptions).some( + key => exceptions[key], + ); + + /** + * Formats value of given comment token for error message by truncating its length. + * @param {Token} token comment token + * @returns {string} formatted value + * @private + */ + function formatReportedCommentValue(token) { + const valueLines = token.value.split("\n"); + const value = valueLines[0]; + const formattedValue = `${value.slice(0, 12)}...`; + + return valueLines.length === 1 && value.length <= 12 + ? value + : formattedValue; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + sourceCode.tokensAndComments.forEach( + (leftToken, leftIndex, tokensAndComments) => { + if (leftIndex === tokensAndComments.length - 1) { + return; + } + const rightToken = tokensAndComments[leftIndex + 1]; + + // Ignore tokens that don't have 2 spaces between them or are on different lines + if ( + !sourceCode.text + .slice(leftToken.range[1], rightToken.range[0]) + .includes(" ") || + leftToken.loc.end.line < rightToken.loc.start.line + ) { + return; + } + + // Ignore comments that are the last token on their line if `ignoreEOLComments` is active. + if ( + ignoreEOLComments && + astUtils.isCommentToken(rightToken) && + (leftIndex === tokensAndComments.length - 2 || + rightToken.loc.end.line < + tokensAndComments[leftIndex + 2].loc.start + .line) + ) { + return; + } + + // Ignore tokens that are in a node in the "exceptions" object + if (hasExceptions) { + const parentNode = sourceCode.getNodeByRangeIndex( + rightToken.range[0] - 1, + ); + + if (parentNode && exceptions[parentNode.type]) { + return; + } + } + + let displayValue; + + if (rightToken.type === "Block") { + displayValue = `/*${formatReportedCommentValue(rightToken)}*/`; + } else if (rightToken.type === "Line") { + displayValue = `//${formatReportedCommentValue(rightToken)}`; + } else { + displayValue = rightToken.value; + } + + context.report({ + node: rightToken, + loc: { + start: leftToken.loc.end, + end: rightToken.loc.start, + }, + messageId: "multipleSpaces", + data: { displayValue }, + fix: fixer => + fixer.replaceTextRange( + [leftToken.range[1], rightToken.range[0]], + " ", + ), + }); + }, + ); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-multi-str.js b/node_modules/eslint/lib/rules/no-multi-str.js new file mode 100644 index 00000000..4258dc2e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multi-str.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Rule to flag when using multiline strings + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow multiline strings", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-multi-str", + }, + + schema: [], + + messages: { + multilineString: + "Multiline support is limited to browsers supporting ES5 only.", + }, + }, + + create(context) { + /** + * Determines if a given node is part of JSX syntax. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a JSX node, false if not. + * @private + */ + function isJSXElement(node) { + return node.type.indexOf("JSX") === 0; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Literal(node) { + if ( + astUtils.LINEBREAK_MATCHER.test(node.raw) && + !isJSXElement(node.parent) + ) { + context.report({ + node, + messageId: "multilineString", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-multiple-empty-lines.js b/node_modules/eslint/lib/rules/no-multiple-empty-lines.js new file mode 100644 index 00000000..e75b733f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multiple-empty-lines.js @@ -0,0 +1,210 @@ +/** + * @fileoverview Disallows multiple blank lines. + * implementation adapted from the no-trailing-spaces rule. + * @author Greg Cochard + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-multiple-empty-lines", + url: "https://eslint.style/rules/js/no-multiple-empty-lines", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow multiple empty lines", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multiple-empty-lines", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + max: { + type: "integer", + minimum: 0, + }, + maxEOF: { + type: "integer", + minimum: 0, + }, + maxBOF: { + type: "integer", + minimum: 0, + }, + }, + required: ["max"], + additionalProperties: false, + }, + ], + + messages: { + blankBeginningOfFile: + "Too many blank lines at the beginning of file. Max of {{max}} allowed.", + blankEndOfFile: + "Too many blank lines at the end of file. Max of {{max}} allowed.", + consecutiveBlank: + "More than {{max}} blank {{pluralizedLines}} not allowed.", + }, + }, + + create(context) { + // Use options.max or 2 as default + let max = 2, + maxEOF = max, + maxBOF = max; + + if (context.options.length) { + max = context.options[0].max; + maxEOF = + typeof context.options[0].maxEOF !== "undefined" + ? context.options[0].maxEOF + : max; + maxBOF = + typeof context.options[0].maxBOF !== "undefined" + ? context.options[0].maxBOF + : max; + } + + const sourceCode = context.sourceCode; + + // Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue + const allLines = + sourceCode.lines.at(-1) === "" + ? sourceCode.lines.slice(0, -1) + : sourceCode.lines; + const templateLiteralLines = new Set(); + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + TemplateLiteral(node) { + node.quasis.forEach(literalPart => { + // Empty lines have a semantic meaning if they're inside template literals. Don't count these as empty lines. + for ( + let ignoredLine = literalPart.loc.start.line; + ignoredLine < literalPart.loc.end.line; + ignoredLine++ + ) { + templateLiteralLines.add(ignoredLine); + } + }); + }, + "Program:exit"(node) { + return ( + allLines + + // Given a list of lines, first get a list of line numbers that are non-empty. + .reduce((nonEmptyLineNumbers, line, index) => { + if ( + line.trim() || + templateLiteralLines.has(index + 1) + ) { + nonEmptyLineNumbers.push(index + 1); + } + return nonEmptyLineNumbers; + }, []) + + // Add a value at the end to allow trailing empty lines to be checked. + .concat(allLines.length + 1) + + // Given two line numbers of non-empty lines, report the lines between if the difference is too large. + .reduce((lastLineNumber, lineNumber) => { + let messageId, maxAllowed; + + if (lastLineNumber === 0) { + messageId = "blankBeginningOfFile"; + maxAllowed = maxBOF; + } else if (lineNumber === allLines.length + 1) { + messageId = "blankEndOfFile"; + maxAllowed = maxEOF; + } else { + messageId = "consecutiveBlank"; + maxAllowed = max; + } + + if (lineNumber - lastLineNumber - 1 > maxAllowed) { + context.report({ + node, + loc: { + start: { + line: + lastLineNumber + maxAllowed + 1, + column: 0, + }, + end: { line: lineNumber, column: 0 }, + }, + messageId, + data: { + max: maxAllowed, + pluralizedLines: + maxAllowed === 1 ? "line" : "lines", + }, + fix(fixer) { + const rangeStart = + sourceCode.getIndexFromLoc({ + line: lastLineNumber + 1, + column: 0, + }); + + /* + * The end of the removal range is usually the start index of the next line. + * However, at the end of the file there is no next line, so the end of the + * range is just the length of the text. + */ + const lineNumberAfterRemovedLines = + lineNumber - maxAllowed; + const rangeEnd = + lineNumberAfterRemovedLines <= + allLines.length + ? sourceCode.getIndexFromLoc({ + line: lineNumberAfterRemovedLines, + column: 0, + }) + : sourceCode.text.length; + + return fixer.removeRange([ + rangeStart, + rangeEnd, + ]); + }, + }); + } + + return lineNumber; + }, 0) + ); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-native-reassign.js b/node_modules/eslint/lib/rules/no-native-reassign.js new file mode 100644 index 00000000..b3949c2f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-native-reassign.js @@ -0,0 +1,114 @@ +/** + * @fileoverview Rule to disallow assignments to native objects or read-only global variables + * @author Ilya Volodin + * @deprecated in ESLint v3.3.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow assignments to native objects or read-only global variables", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-native-reassign", + }, + + deprecated: { + message: "Renamed rule.", + url: "https://eslint.org/blog/2016/08/eslint-v3.3.0-released/#deprecated-rules", + deprecatedSince: "3.3.0", + availableUntil: null, + replacedBy: [ + { + rule: { + name: "no-global-assign", + url: "https://eslint.org/docs/rules/no-global-assign", + }, + }, + ], + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + nativeReassign: + "Read-only global '{{name}}' should not be modified.", + }, + }, + + create(context) { + const config = context.options[0]; + const exceptions = (config && config.exceptions) || []; + const sourceCode = context.sourceCode; + + /** + * Reports write references. + * @param {Reference} reference A reference to check. + * @param {number} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {void} + */ + function checkReference(reference, index, references) { + const identifier = reference.identifier; + + if ( + reference.init === false && + reference.isWrite() && + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ + (index === 0 || references[index - 1].identifier !== identifier) + ) { + context.report({ + node: identifier, + messageId: "nativeReassign", + data: identifier, + }); + } + } + + /** + * Reports write references if a given variable is read-only builtin. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if ( + variable.writeable === false && + !exceptions.includes(variable.name) + ) { + variable.references.forEach(checkReference); + } + } + + return { + Program(node) { + const globalScope = sourceCode.getScope(node); + + globalScope.variables.forEach(checkVariable); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-negated-condition.js b/node_modules/eslint/lib/rules/no-negated-condition.js new file mode 100644 index 00000000..33c150e8 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-negated-condition.js @@ -0,0 +1,100 @@ +/** + * @fileoverview Rule to disallow a negated condition + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow negated conditions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-negated-condition", + }, + + schema: [], + + messages: { + unexpectedNegated: "Unexpected negated condition.", + }, + }, + + create(context) { + /** + * Determines if a given node is an if-else without a condition on the else + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node has an else without an if. + * @private + */ + function hasElseWithoutCondition(node) { + return node.alternate && node.alternate.type !== "IfStatement"; + } + + /** + * Determines if a given node is a negated unary expression + * @param {Object} test The test object to check. + * @returns {boolean} True if the node is a negated unary expression. + * @private + */ + function isNegatedUnaryExpression(test) { + return test.type === "UnaryExpression" && test.operator === "!"; + } + + /** + * Determines if a given node is a negated binary expression + * @param {Test} test The test to check. + * @returns {boolean} True if the node is a negated binary expression. + * @private + */ + function isNegatedBinaryExpression(test) { + return ( + test.type === "BinaryExpression" && + (test.operator === "!=" || test.operator === "!==") + ); + } + + /** + * Determines if a given node has a negated if expression + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node has a negated if expression. + * @private + */ + function isNegatedIf(node) { + return ( + isNegatedUnaryExpression(node.test) || + isNegatedBinaryExpression(node.test) + ); + } + + return { + IfStatement(node) { + if (!hasElseWithoutCondition(node)) { + return; + } + + if (isNegatedIf(node)) { + context.report({ + node, + messageId: "unexpectedNegated", + }); + } + }, + ConditionalExpression(node) { + if (isNegatedIf(node)) { + context.report({ + node, + messageId: "unexpectedNegated", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-negated-in-lhs.js b/node_modules/eslint/lib/rules/no-negated-in-lhs.js new file mode 100644 index 00000000..4804414f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-negated-in-lhs.js @@ -0,0 +1,59 @@ +/** + * @fileoverview A rule to disallow negated left operands of the `in` operator + * @author Michael Ficarra + * @deprecated in ESLint v3.3.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow negating the left operand in `in` expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-negated-in-lhs", + }, + + deprecated: { + message: "Renamed rule.", + url: "https://eslint.org/blog/2016/08/eslint-v3.3.0-released/#deprecated-rules", + deprecatedSince: "3.3.0", + availableUntil: null, + replacedBy: [ + { + rule: { + name: "no-unsafe-negation", + url: "https://eslint.org/docs/rules/no-unsafe-negation", + }, + }, + ], + }, + schema: [], + + messages: { + negatedLHS: "The 'in' expression's left operand is negated.", + }, + }, + + create(context) { + return { + BinaryExpression(node) { + if ( + node.operator === "in" && + node.left.type === "UnaryExpression" && + node.left.operator === "!" + ) { + context.report({ node, messageId: "negatedLHS" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-nested-ternary.js b/node_modules/eslint/lib/rules/no-nested-ternary.js new file mode 100644 index 00000000..8e5dbb78 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-nested-ternary.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Rule to flag nested ternary expressions + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow nested ternary expressions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-nested-ternary", + }, + + schema: [], + + messages: { + noNestedTernary: "Do not nest ternary expressions.", + }, + }, + + create(context) { + return { + ConditionalExpression(node) { + if ( + node.alternate.type === "ConditionalExpression" || + node.consequent.type === "ConditionalExpression" + ) { + context.report({ + node, + messageId: "noNestedTernary", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-func.js b/node_modules/eslint/lib/rules/no-new-func.js new file mode 100644 index 00000000..760dc640 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-func.js @@ -0,0 +1,96 @@ +/** + * @fileoverview Rule to flag when using new Function + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const callMethods = new Set(["apply", "bind", "call"]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `new` operators with the `Function` object", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-func", + }, + + schema: [], + + messages: { + noFunctionConstructor: "The Function constructor is eval.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + const variable = globalScope.set.get("Function"); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(ref => { + const idNode = ref.identifier; + const { parent } = idNode; + let evalNode; + + if (parent) { + if ( + idNode === parent.callee && + (parent.type === "NewExpression" || + parent.type === "CallExpression") + ) { + evalNode = parent; + } else if ( + parent.type === "MemberExpression" && + idNode === parent.object && + callMethods.has( + astUtils.getStaticPropertyName(parent), + ) + ) { + const maybeCallee = + parent.parent.type === "ChainExpression" + ? parent.parent + : parent; + + if ( + maybeCallee.parent.type === + "CallExpression" && + maybeCallee.parent.callee === maybeCallee + ) { + evalNode = maybeCallee.parent; + } + } + } + + if (evalNode) { + context.report({ + node: evalNode, + messageId: "noFunctionConstructor", + }); + } + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js b/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js new file mode 100644 index 00000000..0ae892cd --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js @@ -0,0 +1,70 @@ +/** + * @fileoverview Rule to disallow use of the new operator with global non-constructor functions + * @author Sosuke Suzuki + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const nonConstructorGlobalFunctionNames = ["Symbol", "BigInt"]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow `new` operators with global non-constructor functions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-new-native-nonconstructor", + }, + + schema: [], + + messages: { + noNewNonconstructor: + "`{{name}}` cannot be called as a constructor.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + for (const nonConstructorName of nonConstructorGlobalFunctionNames) { + const variable = globalScope.set.get(nonConstructorName); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(ref => { + const idNode = ref.identifier; + const parent = idNode.parent; + + if ( + parent && + parent.type === "NewExpression" && + parent.callee === idNode + ) { + context.report({ + node: idNode, + messageId: "noNewNonconstructor", + data: { name: nonConstructorName }, + }); + } + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-object.js b/node_modules/eslint/lib/rules/no-new-object.js new file mode 100644 index 00000000..c564a76d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-object.js @@ -0,0 +1,76 @@ +/** + * @fileoverview A rule to disallow calls to the Object constructor + * @author Matt DuVall + * @deprecated in ESLint v8.50.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `Object` constructors", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-object", + }, + + deprecated: { + message: + "The new rule flags more situations where object literal syntax can be used, and it does not report a problem when the `Object` constructor is invoked with an argument.", + url: "https://eslint.org/blog/2023/09/eslint-v8.50.0-released/", + deprecatedSince: "8.50.0", + availableUntil: null, + replacedBy: [ + { + rule: { + name: "no-object-constructor", + url: "https://eslint.org/docs/rules/no-object-constructor", + }, + }, + ], + }, + + schema: [], + + messages: { + preferLiteral: "The object literal notation {} is preferable.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + NewExpression(node) { + const variable = astUtils.getVariableByName( + sourceCode.getScope(node), + node.callee.name, + ); + + if (variable && variable.identifiers.length > 0) { + return; + } + + if (node.callee.name === "Object") { + context.report({ + node, + messageId: "preferLiteral", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-require.js b/node_modules/eslint/lib/rules/no-new-require.js new file mode 100644 index 00000000..5a8ea5c2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-require.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Rule to disallow use of new operator with the `require` function + * @author Wil Moore III + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-new-require", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-new-require.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow `new` operators with calls to `require`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-require", + }, + + schema: [], + + messages: { + noNewRequire: "Unexpected use of new with require.", + }, + }, + + create(context) { + return { + NewExpression(node) { + if ( + node.callee.type === "Identifier" && + node.callee.name === "require" + ) { + context.report({ + node, + messageId: "noNewRequire", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-symbol.js b/node_modules/eslint/lib/rules/no-new-symbol.js new file mode 100644 index 00000000..6a8127fc --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-symbol.js @@ -0,0 +1,74 @@ +/** + * @fileoverview Rule to disallow use of the new operator with the `Symbol` object + * @author Alberto Rodríguez + * @deprecated in ESLint v9.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow `new` operators with the `Symbol` object", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-symbol", + }, + + deprecated: { + message: "The rule was replaced with a more general rule.", + url: "https://eslint.org/docs/latest/use/migrate-to-9.0.0#eslint-recommended", + deprecatedSince: "9.0.0", + availableUntil: null, + replacedBy: [ + { + rule: { + name: "no-new-native-nonconstructor", + url: "https://eslint.org/docs/latest/rules/no-new-native-nonconstructor", + }, + }, + ], + }, + + schema: [], + + messages: { + noNewSymbol: "`Symbol` cannot be called as a constructor.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + const variable = globalScope.set.get("Symbol"); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(ref => { + const idNode = ref.identifier; + const parent = idNode.parent; + + if ( + parent && + parent.type === "NewExpression" && + parent.callee === idNode + ) { + context.report({ + node: idNode, + messageId: "noNewSymbol", + }); + } + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-wrappers.js b/node_modules/eslint/lib/rules/no-new-wrappers.js new file mode 100644 index 00000000..84025dbf --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-wrappers.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Rule to flag when using constructor for wrapper objects + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getVariableByName } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `new` operators with the `String`, `Number`, and `Boolean` objects", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-wrappers", + }, + + schema: [], + + messages: { + noConstructor: "Do not use {{fn}} as a constructor.", + }, + }, + + create(context) { + const { sourceCode } = context; + + return { + NewExpression(node) { + const wrapperObjects = ["String", "Number", "Boolean"]; + const { name } = node.callee; + + if (wrapperObjects.includes(name)) { + const variable = getVariableByName( + sourceCode.getScope(node), + name, + ); + + if (variable && variable.identifiers.length === 0) { + context.report({ + node, + messageId: "noConstructor", + data: { fn: name }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new.js b/node_modules/eslint/lib/rules/no-new.js new file mode 100644 index 00000000..8f91835b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Rule to flag statements with function invocation preceded by + * "new" and not part of assignment + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `new` operators outside of assignments or comparisons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new", + }, + + schema: [], + + messages: { + noNewStatement: "Do not use 'new' for side effects.", + }, + }, + + create(context) { + return { + "ExpressionStatement > NewExpression"(node) { + context.report({ + node: node.parent, + messageId: "noNewStatement", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js b/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js new file mode 100644 index 00000000..d09b7994 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js @@ -0,0 +1,176 @@ +/** + * @fileoverview Rule to disallow `\8` and `\9` escape sequences in string literals. + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceRange } from "@eslint/core"; + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const QUICK_TEST_REGEX = /\\[89]/u; + +/** + * Returns unicode escape sequence that represents the given character. + * @param {string} character A single code unit. + * @returns {string} "\uXXXX" sequence. + */ +function getUnicodeEscape(character) { + return `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `\\8` and `\\9` escape sequences in string literals", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-nonoctal-decimal-escape", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + decimalEscape: "Don't use '{{decimalEscape}}' escape sequence.", + + // suggestions + refactor: + "Replace '{{original}}' with '{{replacement}}'. This maintains the current functionality.", + escapeBackslash: + "Replace '{{original}}' with '{{replacement}}' to include the actual backslash character.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Creates a new Suggestion object. + * @param {string} messageId "refactor" or "escapeBackslash". + * @param {SourceRange} range The range to replace. + * @param {string} replacement New text for the range. + * @returns {Object} Suggestion + */ + function createSuggestion(messageId, range, replacement) { + return { + messageId, + data: { + original: sourceCode.getText().slice(...range), + replacement, + }, + fix(fixer) { + return fixer.replaceTextRange(range, replacement); + }, + }; + } + + return { + Literal(node) { + if (typeof node.value !== "string") { + return; + } + + if (!QUICK_TEST_REGEX.test(node.raw)) { + return; + } + + const regex = + /(?:[^\\]|(?\\.))*?(?\\[89])/suy; + let match; + + while ((match = regex.exec(node.raw))) { + const { previousEscape, decimalEscape } = match.groups; + const decimalEscapeRangeEnd = + node.range[0] + match.index + match[0].length; + const decimalEscapeRangeStart = + decimalEscapeRangeEnd - decimalEscape.length; + const decimalEscapeRange = [ + decimalEscapeRangeStart, + decimalEscapeRangeEnd, + ]; + const suggest = []; + + // When `regex` is matched, `previousEscape` can only capture characters adjacent to `decimalEscape` + if (previousEscape === "\\0") { + /* + * Now we have a NULL escape "\0" immediately followed by a decimal escape, e.g.: "\0\8". + * Fixing this to "\08" would turn "\0" into a legacy octal escape. To avoid producing + * an octal escape while fixing a decimal escape, we provide different suggestions. + */ + suggest.push( + createSuggestion( + // "\0\8" -> "\u00008" + "refactor", + [ + decimalEscapeRangeStart - + previousEscape.length, + decimalEscapeRangeEnd, + ], + `${getUnicodeEscape("\0")}${decimalEscape[1]}`, + ), + createSuggestion( + // "\8" -> "\u0038" + "refactor", + decimalEscapeRange, + getUnicodeEscape(decimalEscape[1]), + ), + ); + } else { + suggest.push( + createSuggestion( + // "\8" -> "8" + "refactor", + decimalEscapeRange, + decimalEscape[1], + ), + ); + } + + suggest.push( + createSuggestion( + // "\8" -> "\\8" + "escapeBackslash", + decimalEscapeRange, + `\\${decimalEscape}`, + ), + ); + + context.report({ + node, + loc: { + start: sourceCode.getLocFromIndex( + decimalEscapeRangeStart, + ), + end: sourceCode.getLocFromIndex( + decimalEscapeRangeEnd, + ), + }, + messageId: "decimalEscape", + data: { + decimalEscape, + }, + suggest, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-obj-calls.js b/node_modules/eslint/lib/rules/no-obj-calls.js new file mode 100644 index 00000000..df76b482 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-obj-calls.js @@ -0,0 +1,99 @@ +/** + * @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, +} = require("@eslint-community/eslint-utils"); +const getPropertyName = require("./utils/ast-utils").getStaticPropertyName; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const nonCallableGlobals = ["Atomics", "JSON", "Math", "Reflect", "Intl"]; + +/** + * Returns the name of the node to report + * @param {ASTNode} node A node to report + * @returns {string} name to report + */ +function getReportNodeName(node) { + if (node.type === "ChainExpression") { + return getReportNodeName(node.expression); + } + if (node.type === "MemberExpression") { + return getPropertyName(node); + } + return node.name; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow calling global object properties as functions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-obj-calls", + }, + + schema: [], + + messages: { + unexpectedCall: "'{{name}}' is not a function.", + unexpectedRefCall: + "'{{name}}' is reference to '{{ref}}', which is not a function.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const traceMap = {}; + + for (const g of nonCallableGlobals) { + traceMap[g] = { + [CALL]: true, + [CONSTRUCT]: true, + }; + } + + for (const { + node: refNode, + path, + } of tracker.iterateGlobalReferences(traceMap)) { + const name = getReportNodeName(refNode.callee); + const ref = path[0]; + const messageId = + name === ref ? "unexpectedCall" : "unexpectedRefCall"; + + context.report({ + node: refNode, + messageId, + data: { name, ref }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-object-constructor.js b/node_modules/eslint/lib/rules/no-object-constructor.js new file mode 100644 index 00000000..fffa6122 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-object-constructor.js @@ -0,0 +1,124 @@ +/** + * @fileoverview Rule to disallow calls to the `Object` constructor without an argument + * @author Francesco Trotta + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + getVariableByName, + isArrowToken, + isStartOfExpressionStatement, + needsPrecedingSemicolon, +} = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow calls to the `Object` constructor without an argument", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-object-constructor", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + preferLiteral: "The object literal notation {} is preferable.", + useLiteral: "Replace with '{{replacement}}'.", + useLiteralAfterSemicolon: + "Replace with '{{replacement}}', add preceding semicolon.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether or not an object literal that replaces a specified node needs to be enclosed in parentheses. + * @param {ASTNode} node The node to be replaced. + * @returns {boolean} Whether or not parentheses around the object literal are required. + */ + function needsParentheses(node) { + if (isStartOfExpressionStatement(node)) { + return true; + } + + const prevToken = sourceCode.getTokenBefore(node); + + if (prevToken && isArrowToken(prevToken)) { + return true; + } + + return false; + } + + /** + * Reports on nodes where the `Object` constructor is called without arguments. + * @param {ASTNode} node The node to evaluate. + * @returns {void} + */ + function check(node) { + if ( + node.callee.type !== "Identifier" || + node.callee.name !== "Object" || + node.arguments.length + ) { + return; + } + + const variable = getVariableByName( + sourceCode.getScope(node), + "Object", + ); + + if (variable && variable.identifiers.length === 0) { + let replacement; + let fixText; + let messageId = "useLiteral"; + + if (needsParentheses(node)) { + replacement = "({})"; + if (needsPrecedingSemicolon(sourceCode, node)) { + fixText = ";({})"; + messageId = "useLiteralAfterSemicolon"; + } else { + fixText = "({})"; + } + } else { + replacement = fixText = "{}"; + } + + context.report({ + node, + messageId: "preferLiteral", + suggest: [ + { + messageId, + data: { replacement }, + fix: fixer => fixer.replaceText(node, fixText), + }, + ], + }); + } + } + + return { + CallExpression: check, + NewExpression: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-octal-escape.js b/node_modules/eslint/lib/rules/no-octal-escape.js new file mode 100644 index 00000000..975b3085 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-octal-escape.js @@ -0,0 +1,53 @@ +/** + * @fileoverview Rule to flag octal escape sequences in string literals. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow octal escape sequences in string literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-octal-escape", + }, + + schema: [], + + messages: { + octalEscapeSequence: + "Don't use octal: '\\{{sequence}}'. Use '\\u....' instead.", + }, + }, + + create(context) { + return { + Literal(node) { + if (typeof node.value !== "string") { + return; + } + + // \0 represents a valid NULL character if it isn't followed by a digit. + const match = node.raw.match( + /^(?:[^\\]|\\.)*?\\([0-3][0-7]{1,2}|[4-7][0-7]|0(?=[89])|[1-7])/su, + ); + + if (match) { + context.report({ + node, + messageId: "octalEscapeSequence", + data: { sequence: match[1] }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-octal.js b/node_modules/eslint/lib/rules/no-octal.js new file mode 100644 index 00000000..28dd9108 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-octal.js @@ -0,0 +1,45 @@ +/** + * @fileoverview Rule to flag when initializing octal literal + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow octal literals", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-octal", + }, + + schema: [], + + messages: { + noOctal: "Octal literals should not be used.", + }, + }, + + create(context) { + return { + Literal(node) { + if ( + typeof node.value === "number" && + /^0[0-9]/u.test(node.raw) + ) { + context.report({ + node, + messageId: "noOctal", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-param-reassign.js b/node_modules/eslint/lib/rules/no-param-reassign.js new file mode 100644 index 00000000..ec22030a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-param-reassign.js @@ -0,0 +1,248 @@ +/** + * @fileoverview Disallow reassigning function parameters. + * @author Nat Burns + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const stopNodePattern = + /(?:Statement|Declaration|Function(?:Expression)?|Program)$/u; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow reassigning function parameters", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-param-reassign", + }, + + schema: [ + { + oneOf: [ + { + type: "object", + properties: { + props: { + enum: [false], + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + props: { + enum: [true], + }, + ignorePropertyModificationsFor: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + ignorePropertyModificationsForRegex: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + assignmentToFunctionParam: + "Assignment to function parameter '{{name}}'.", + assignmentToFunctionParamProp: + "Assignment to property of function parameter '{{name}}'.", + }, + }, + + create(context) { + const props = context.options[0] && context.options[0].props; + const ignoredPropertyAssignmentsFor = + (context.options[0] && + context.options[0].ignorePropertyModificationsFor) || + []; + const ignoredPropertyAssignmentsForRegex = + (context.options[0] && + context.options[0].ignorePropertyModificationsForRegex) || + []; + const sourceCode = context.sourceCode; + + /** + * Checks whether or not the reference modifies properties of its variable. + * @param {Reference} reference A reference to check. + * @returns {boolean} Whether or not the reference modifies properties of its variable. + */ + function isModifyingProp(reference) { + let node = reference.identifier; + let parent = node.parent; + + while ( + parent && + (!stopNodePattern.test(parent.type) || + parent.type === "ForInStatement" || + parent.type === "ForOfStatement") + ) { + switch (parent.type) { + // e.g. foo.a = 0; + case "AssignmentExpression": + return parent.left === node; + + // e.g. ++foo.a; + case "UpdateExpression": + return true; + + // e.g. delete foo.a; + case "UnaryExpression": + if (parent.operator === "delete") { + return true; + } + break; + + // e.g. for (foo.a in b) {} + case "ForInStatement": + case "ForOfStatement": + if (parent.left === node) { + return true; + } + + // this is a stop node for parent.right and parent.body + return false; + + // EXCLUDES: e.g. cache.get(foo.a).b = 0; + case "CallExpression": + if (parent.callee !== node) { + return false; + } + break; + + // EXCLUDES: e.g. cache[foo.a] = 0; + case "MemberExpression": + if (parent.property === node) { + return false; + } + break; + + // EXCLUDES: e.g. ({ [foo]: a }) = bar; + case "Property": + if (parent.key === node) { + return false; + } + + break; + + // EXCLUDES: e.g. (foo ? a : b).c = bar; + case "ConditionalExpression": + if (parent.test === node) { + return false; + } + + break; + + // no default + } + + node = parent; + parent = node.parent; + } + + return false; + } + + /** + * Tests that an identifier name matches any of the ignored property assignments. + * First we test strings in ignoredPropertyAssignmentsFor. + * Then we instantiate and test RegExp objects from ignoredPropertyAssignmentsForRegex strings. + * @param {string} identifierName A string that describes the name of an identifier to + * ignore property assignments for. + * @returns {boolean} Whether the string matches an ignored property assignment regular expression or not. + */ + function isIgnoredPropertyAssignment(identifierName) { + return ( + ignoredPropertyAssignmentsFor.includes(identifierName) || + ignoredPropertyAssignmentsForRegex.some(ignored => + new RegExp(ignored, "u").test(identifierName), + ) + ); + } + + /** + * Reports a reference if is non initializer and writable. + * @param {Reference} reference A reference to check. + * @param {number} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {void} + */ + function checkReference(reference, index, references) { + const identifier = reference.identifier; + + if ( + identifier && + !reference.init && + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ + (index === 0 || references[index - 1].identifier !== identifier) + ) { + if (reference.isWrite()) { + context.report({ + node: identifier, + messageId: "assignmentToFunctionParam", + data: { name: identifier.name }, + }); + } else if ( + props && + isModifyingProp(reference) && + !isIgnoredPropertyAssignment(identifier.name) + ) { + context.report({ + node: identifier, + messageId: "assignmentToFunctionParamProp", + data: { name: identifier.name }, + }); + } + } + } + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if (variable.defs[0].type === "Parameter") { + variable.references.forEach(checkReference); + } + } + + /** + * Checks parameters of a given function node. + * @param {ASTNode} node A function node to check. + * @returns {void} + */ + function checkForFunction(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + + return { + // `:exit` is needed for the `node.parent` property of identifier nodes. + "FunctionDeclaration:exit": checkForFunction, + "FunctionExpression:exit": checkForFunction, + "ArrowFunctionExpression:exit": checkForFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-path-concat.js b/node_modules/eslint/lib/rules/no-path-concat.js new file mode 100644 index 00000000..7d69fc11 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-path-concat.js @@ -0,0 +1,79 @@ +/** + * @fileoverview Disallow string concatenation when using __dirname and __filename + * @author Nicholas C. Zakas + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-path-concat", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-path-concat.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: + "Disallow string concatenation with `__dirname` and `__filename`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-path-concat", + }, + + schema: [], + + messages: { + usePathFunctions: + "Use path.join() or path.resolve() instead of + to create paths.", + }, + }, + + create(context) { + const MATCHER = /^__(?:dir|file)name$/u; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + BinaryExpression(node) { + const left = node.left, + right = node.right; + + if ( + node.operator === "+" && + ((left.type === "Identifier" && MATCHER.test(left.name)) || + (right.type === "Identifier" && + MATCHER.test(right.name))) + ) { + context.report({ + node, + messageId: "usePathFunctions", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-plusplus.js b/node_modules/eslint/lib/rules/no-plusplus.js new file mode 100644 index 00000000..1f3a9f0f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-plusplus.js @@ -0,0 +1,102 @@ +/** + * @fileoverview Rule to flag use of unary increment and decrement operators. + * @author Ian Christian Myers + * @author Brody McKee (github.com/mrmckeb) + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is the update node of a `ForStatement`. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is `ForStatement` update. + */ +function isForStatementUpdate(node) { + const parent = node.parent; + + return parent.type === "ForStatement" && parent.update === node; +} + +/** + * Determines whether the given node is considered to be a for loop "afterthought" by the logic of this rule. + * In particular, it returns `true` if the given node is either: + * - The update node of a `ForStatement`: for (;; i++) {} + * - An operand of a sequence expression that is the update node: for (;; foo(), i++) {} + * - An operand of a sequence expression that is child of another sequence expression, etc., + * up to the sequence expression that is the update node: for (;; foo(), (bar(), (baz(), i++))) {} + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a for loop afterthought. + */ +function isForLoopAfterthought(node) { + const parent = node.parent; + + if (parent.type === "SequenceExpression") { + return isForLoopAfterthought(parent); + } + + return isForStatementUpdate(node); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowForLoopAfterthoughts: false, + }, + ], + + docs: { + description: "Disallow the unary operators `++` and `--`", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-plusplus", + }, + + schema: [ + { + type: "object", + properties: { + allowForLoopAfterthoughts: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedUnaryOp: "Unary operator '{{operator}}' used.", + }, + }, + + create(context) { + const [{ allowForLoopAfterthoughts }] = context.options; + + return { + UpdateExpression(node) { + if (allowForLoopAfterthoughts && isForLoopAfterthought(node)) { + return; + } + + context.report({ + node, + messageId: "unexpectedUnaryOp", + data: { + operator: node.operator, + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-process-env.js b/node_modules/eslint/lib/rules/no-process-env.js new file mode 100644 index 00000000..a2e23384 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-process-env.js @@ -0,0 +1,68 @@ +/** + * @fileoverview Disallow the use of process.env() + * @author Vignesh Anand + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-process-env", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-process-env.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow the use of `process.env`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-process-env", + }, + + schema: [], + + messages: { + unexpectedProcessEnv: "Unexpected use of process.env.", + }, + }, + + create(context) { + return { + MemberExpression(node) { + const objectName = node.object.name, + propertyName = node.property.name; + + if ( + objectName === "process" && + !node.computed && + propertyName && + propertyName === "env" + ) { + context.report({ node, messageId: "unexpectedProcessEnv" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-process-exit.js b/node_modules/eslint/lib/rules/no-process-exit.js new file mode 100644 index 00000000..aab19740 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-process-exit.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Disallow the use of process.exit() + * @author Nicholas C. Zakas + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-process-exit", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-process-exit.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow the use of `process.exit()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-process-exit", + }, + + schema: [], + + messages: { + noProcessExit: "Don't use process.exit(); throw an error instead.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "CallExpression > MemberExpression.callee[object.name = 'process'][property.name = 'exit']"( + node, + ) { + context.report({ + node: node.parent, + messageId: "noProcessExit", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-promise-executor-return.js b/node_modules/eslint/lib/rules/no-promise-executor-return.js new file mode 100644 index 00000000..647f3ac0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-promise-executor-return.js @@ -0,0 +1,264 @@ +/** + * @fileoverview Rule to disallow returning values from Promise executor functions + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const functionTypesToCheck = new Set([ + "ArrowFunctionExpression", + "FunctionExpression", +]); + +/** + * Determines whether the given function node is used as a Promise executor. + * @param {ASTNode} node The node to check. + * @param {SourceCode} sourceCode Source code to which the node belongs. + * @returns {boolean} `true` if the node is a Promise executor. + */ +function isPromiseExecutor(node, sourceCode) { + const parent = node.parent; + + return ( + parent.type === "NewExpression" && + parent.arguments[0] === node && + parent.callee.type === "Identifier" && + parent.callee.name === "Promise" && + sourceCode.isGlobalReference(parent.callee) + ); +} + +/** + * Checks if the given node is a void expression. + * @param {ASTNode} node The node to check. + * @returns {boolean} - `true` if the node is a void expression + */ +function expressionIsVoid(node) { + return node.type === "UnaryExpression" && node.operator === "void"; +} + +/** + * Fixes the linting error by prepending "void " to the given node + * @param {Object} sourceCode context given by context.sourceCode + * @param {ASTNode} node The node to fix. + * @param {Object} fixer The fixer object provided by ESLint. + * @returns {Array} - An array of fix objects to apply to the node. + */ +function voidPrependFixer(sourceCode, node, fixer) { + const requiresParens = + // prepending `void ` will fail if the node has a lower precedence than void + astUtils.getPrecedence(node) < + astUtils.getPrecedence({ + type: "UnaryExpression", + operator: "void", + }) && + // check if there are parentheses around the node to avoid redundant parentheses + !astUtils.isParenthesised(sourceCode, node); + + // avoid parentheses issues + const returnOrArrowToken = sourceCode.getTokenBefore( + node, + node.parent.type === "ArrowFunctionExpression" + ? astUtils.isArrowToken + : // isReturnToken + token => token.type === "Keyword" && token.value === "return", + ); + + const firstToken = sourceCode.getTokenAfter(returnOrArrowToken); + + const prependSpace = + // is return token, as => allows void to be adjacent + returnOrArrowToken.value === "return" && + // If two tokens (return and "(") are adjacent + returnOrArrowToken.range[1] === firstToken.range[0]; + + return [ + fixer.insertTextBefore( + firstToken, + `${prependSpace ? " " : ""}void ${requiresParens ? "(" : ""}`, + ), + fixer.insertTextAfter(node, requiresParens ? ")" : ""), + ]; +} + +/** + * Fixes the linting error by `wrapping {}` around the given node's body. + * @param {Object} sourceCode context given by context.sourceCode + * @param {ASTNode} node The node to fix. + * @param {Object} fixer The fixer object provided by ESLint. + * @returns {Array} - An array of fix objects to apply to the node. + */ +function curlyWrapFixer(sourceCode, node, fixer) { + // https://github.com/eslint/eslint/pull/17282#issuecomment-1592795923 + const arrowToken = sourceCode.getTokenBefore( + node.body, + astUtils.isArrowToken, + ); + const firstToken = sourceCode.getTokenAfter(arrowToken); + const lastToken = sourceCode.getLastToken(node); + + return [ + fixer.insertTextBefore(firstToken, "{"), + fixer.insertTextAfter(lastToken, "}"), + ]; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowVoid: false, + }, + ], + + docs: { + description: + "Disallow returning values from Promise executor functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-promise-executor-return", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + allowVoid: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + returnsValue: + "Return values from promise executor functions cannot be read.", + + // arrow and function suggestions + prependVoid: "Prepend `void` to the expression.", + + // only arrow suggestions + wrapBraces: "Wrap the expression in `{}`.", + }, + }, + + create(context) { + let funcInfo = null; + const sourceCode = context.sourceCode; + const [{ allowVoid }] = context.options; + + return { + onCodePathStart(_, node) { + funcInfo = { + upper: funcInfo, + shouldCheck: + functionTypesToCheck.has(node.type) && + isPromiseExecutor(node, sourceCode), + }; + + if ( + // Is a Promise executor + funcInfo.shouldCheck && + node.type === "ArrowFunctionExpression" && + node.expression && + // Except void + !(allowVoid && expressionIsVoid(node.body)) + ) { + const suggest = []; + + // prevent useless refactors + if (allowVoid) { + suggest.push({ + messageId: "prependVoid", + fix(fixer) { + return voidPrependFixer( + sourceCode, + node.body, + fixer, + ); + }, + }); + } + + // Do not suggest wrapping an unnamed FunctionExpression in braces as that would be invalid syntax. + if ( + !( + node.body.type === "FunctionExpression" && + !node.body.id + ) + ) { + suggest.push({ + messageId: "wrapBraces", + fix(fixer) { + return curlyWrapFixer(sourceCode, node, fixer); + }, + }); + } + + context.report({ + node: node.body, + messageId: "returnsValue", + suggest, + }); + } + }, + + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + ReturnStatement(node) { + if (!(funcInfo.shouldCheck && node.argument)) { + return; + } + + // node is `return ` + if (!allowVoid) { + context.report({ node, messageId: "returnsValue" }); + return; + } + + if (expressionIsVoid(node.argument)) { + return; + } + + // allowVoid && !expressionIsVoid + context.report({ + node, + messageId: "returnsValue", + suggest: [ + { + messageId: "prependVoid", + fix(fixer) { + return voidPrependFixer( + sourceCode, + node.argument, + fixer, + ); + }, + }, + ], + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-proto.js b/node_modules/eslint/lib/rules/no-proto.js new file mode 100644 index 00000000..d68509e1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-proto.js @@ -0,0 +1,45 @@ +/** + * @fileoverview Rule to flag usage of __proto__ property + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getStaticPropertyName } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of the `__proto__` property", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-proto", + }, + + schema: [], + + messages: { + unexpectedProto: "The '__proto__' property is deprecated.", + }, + }, + + create(context) { + return { + MemberExpression(node) { + if (getStaticPropertyName(node) === "__proto__") { + context.report({ node, messageId: "unexpectedProto" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-prototype-builtins.js b/node_modules/eslint/lib/rules/no-prototype-builtins.js new file mode 100644 index 00000000..c75fdacf --- /dev/null +++ b/node_modules/eslint/lib/rules/no-prototype-builtins.js @@ -0,0 +1,181 @@ +/** + * @fileoverview Rule to disallow use of Object.prototype builtins on objects + * @author Andrew Levine + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Returns true if the node or any of the objects + * to the left of it in the member/call chain is optional. + * + * e.g. `a?.b`, `a?.b.c`, `a?.()`, `a()?.()` + * @param {ASTNode} node The expression to check + * @returns {boolean} `true` if there is a short-circuiting optional `?.` + * in the same option chain to the left of this call or member expression, + * or the node itself is an optional call or member `?.`. + */ +function isAfterOptional(node) { + let leftNode; + + if (node.type === "MemberExpression") { + leftNode = node.object; + } else if (node.type === "CallExpression") { + leftNode = node.callee; + } else { + return false; + } + if (node.optional) { + return true; + } + return isAfterOptional(leftNode); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow calling some `Object.prototype` methods directly on objects", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-prototype-builtins", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + prototypeBuildIn: + "Do not access Object.prototype method '{{prop}}' from target object.", + callObjectPrototype: "Call Object.prototype.{{prop}} explicitly.", + }, + }, + + create(context) { + const DISALLOWED_PROPS = new Set([ + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + ]); + + /** + * Reports if a disallowed property is used in a CallExpression + * @param {ASTNode} node The CallExpression node. + * @returns {void} + */ + function disallowBuiltIns(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type !== "MemberExpression") { + return; + } + + const propName = astUtils.getStaticPropertyName(callee); + + if (propName !== null && DISALLOWED_PROPS.has(propName)) { + context.report({ + messageId: "prototypeBuildIn", + loc: callee.property.loc, + data: { prop: propName }, + node, + suggest: [ + { + messageId: "callObjectPrototype", + data: { prop: propName }, + fix(fixer) { + const sourceCode = context.sourceCode; + + /* + * A call after an optional chain (e.g. a?.b.hasOwnProperty(c)) + * must be fixed manually because the call can be short-circuited + */ + if (isAfterOptional(node)) { + return null; + } + + /* + * A call on a ChainExpression (e.g. (a?.hasOwnProperty)(c)) will trigger + * no-unsafe-optional-chaining which should be fixed before this suggestion + */ + if (node.callee.type === "ChainExpression") { + return null; + } + + const objectVariable = + astUtils.getVariableByName( + sourceCode.getScope(node), + "Object", + ); + + /* + * We can't use Object if the global Object was shadowed, + * or Object does not exist in the global scope for some reason + */ + if ( + !objectVariable || + objectVariable.scope.type !== "global" || + objectVariable.defs.length > 0 + ) { + return null; + } + + let objectText = sourceCode.getText( + callee.object, + ); + + if ( + astUtils.getPrecedence(callee.object) <= + astUtils.getPrecedence({ + type: "SequenceExpression", + }) + ) { + objectText = `(${objectText})`; + } + + const openParenToken = sourceCode.getTokenAfter( + node.callee, + astUtils.isOpeningParenToken, + ); + const isEmptyParameters = + node.arguments.length === 0; + const delim = isEmptyParameters ? "" : ", "; + const fixes = [ + fixer.replaceText( + callee, + `Object.prototype.${propName}.call`, + ), + fixer.insertTextAfter( + openParenToken, + objectText + delim, + ), + ]; + + return fixes; + }, + }, + ], + }); + } + } + + return { + CallExpression: disallowBuiltIns, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-redeclare.js b/node_modules/eslint/lib/rules/no-redeclare.js new file mode 100644 index 00000000..4f8c06c9 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-redeclare.js @@ -0,0 +1,173 @@ +/** + * @fileoverview Rule to flag when the same variable is declared more then once. + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ builtinGlobals: true }], + + docs: { + description: "Disallow variable redeclaration", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-redeclare", + }, + + messages: { + redeclared: "'{{id}}' is already defined.", + redeclaredAsBuiltin: + "'{{id}}' is already defined as a built-in global variable.", + redeclaredBySyntax: + "'{{id}}' is already defined by a variable declaration.", + }, + + schema: [ + { + type: "object", + properties: { + builtinGlobals: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + }, + + create(context) { + const [{ builtinGlobals }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Iterate declarations of a given variable. + * @param {escope.variable} variable The variable object to iterate declarations. + * @returns {IterableIterator<{type:string,node:ASTNode,loc:SourceLocation}>} The declarations. + */ + function* iterateDeclarations(variable) { + if ( + builtinGlobals && + (variable.eslintImplicitGlobalSetting === "readonly" || + variable.eslintImplicitGlobalSetting === "writable") + ) { + yield { type: "builtin" }; + } + + for (const id of variable.identifiers) { + yield { type: "syntax", node: id, loc: id.loc }; + } + + if (variable.eslintExplicitGlobalComments) { + for (const comment of variable.eslintExplicitGlobalComments) { + yield { + type: "comment", + node: comment, + loc: astUtils.getNameLocationInGlobalDirectiveComment( + sourceCode, + comment, + variable.name, + ), + }; + } + } + } + + /** + * Find variables in a given scope and flag redeclared ones. + * @param {Scope} scope An eslint-scope scope object. + * @returns {void} + * @private + */ + function findVariablesInScope(scope) { + for (const variable of scope.variables) { + const [declaration, ...extraDeclarations] = + iterateDeclarations(variable); + + if (extraDeclarations.length === 0) { + continue; + } + + /* + * If the type of a declaration is different from the type of + * the first declaration, it shows the location of the first + * declaration. + */ + const detailMessageId = + declaration.type === "builtin" + ? "redeclaredAsBuiltin" + : "redeclaredBySyntax"; + const data = { id: variable.name }; + + // Report extra declarations. + for (const { type, node, loc } of extraDeclarations) { + const messageId = + type === declaration.type + ? "redeclared" + : detailMessageId; + + context.report({ node, loc, messageId, data }); + } + } + } + + /** + * Find variables in the current scope. + * @param {ASTNode} node The node of the current scope. + * @returns {void} + * @private + */ + function checkForBlock(node) { + const scope = sourceCode.getScope(node); + + /* + * In ES5, some node type such as `BlockStatement` doesn't have that scope. + * `scope.block` is a different node in such a case. + */ + if (scope.block === node) { + findVariablesInScope(scope); + } + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + + findVariablesInScope(scope); + + // Node.js or ES modules has a special scope. + if ( + scope.type === "global" && + scope.childScopes[0] && + // The special scope's block is the Program node. + scope.block === scope.childScopes[0].block + ) { + findVariablesInScope(scope.childScopes[0]); + } + }, + + FunctionDeclaration: checkForBlock, + FunctionExpression: checkForBlock, + ArrowFunctionExpression: checkForBlock, + + StaticBlock: checkForBlock, + + BlockStatement: checkForBlock, + ForStatement: checkForBlock, + ForInStatement: checkForBlock, + ForOfStatement: checkForBlock, + SwitchStatement: checkForBlock, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-regex-spaces.js b/node_modules/eslint/lib/rules/no-regex-spaces.js new file mode 100644 index 00000000..71924097 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-regex-spaces.js @@ -0,0 +1,219 @@ +/** + * @fileoverview Rule to count multiple spaces in regular expressions + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const regexpp = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const regExpParser = new regexpp.RegExpParser(); +const DOUBLE_SPACE = / {2}/u; + +/** + * Check if node is a string + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if its a string + * @private + */ +function isString(node) { + return node && node.type === "Literal" && typeof node.value === "string"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow multiple spaces in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-regex-spaces", + }, + + schema: [], + fixable: "code", + + messages: { + multipleSpaces: "Spaces are hard to count. Use {{{length}}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Validate regular expression + * @param {ASTNode} nodeToReport Node to report. + * @param {string} pattern Regular expression pattern to validate. + * @param {string} rawPattern Raw representation of the pattern in the source code. + * @param {number} rawPatternStartRange Start range of the pattern in the source code. + * @param {string} flags Regular expression flags. + * @returns {void} + * @private + */ + function checkRegex( + nodeToReport, + pattern, + rawPattern, + rawPatternStartRange, + flags, + ) { + // Skip if there are no consecutive spaces in the source code, to avoid reporting e.g., RegExp(' \ '). + if (!DOUBLE_SPACE.test(rawPattern)) { + return; + } + + const characterClassNodes = []; + let regExpAST; + + try { + regExpAST = regExpParser.parsePattern( + pattern, + 0, + pattern.length, + { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }, + ); + } catch { + // Ignore regular expressions with syntax errors + return; + } + + regexpp.visitRegExpAST(regExpAST, { + onCharacterClassEnter(ccNode) { + characterClassNodes.push(ccNode); + }, + }); + + const spacesPattern = /( {2,})(?: [+*{?]|[^+*{?]|$)/gu; + let match; + + while ((match = spacesPattern.exec(pattern))) { + const { + 1: { length }, + index, + } = match; + + // Report only consecutive spaces that are not in character classes. + if ( + characterClassNodes.every( + ({ start, end }) => index < start || end <= index, + ) + ) { + context.report({ + node: nodeToReport, + messageId: "multipleSpaces", + data: { length }, + fix(fixer) { + if (pattern !== rawPattern) { + return null; + } + return fixer.replaceTextRange( + [ + rawPatternStartRange + index, + rawPatternStartRange + index + length, + ], + ` {${length}}`, + ); + }, + }); + + // Report only the first occurrence of consecutive spaces + return; + } + } + } + + /** + * Validate regular expression literals + * @param {ASTNode} node node to validate + * @returns {void} + * @private + */ + function checkLiteral(node) { + if (node.regex) { + const pattern = node.regex.pattern; + const rawPattern = node.raw.slice(1, node.raw.lastIndexOf("/")); + const rawPatternStartRange = node.range[0] + 1; + const flags = node.regex.flags; + + checkRegex( + node, + pattern, + rawPattern, + rawPatternStartRange, + flags, + ); + } + } + + /** + * Validate strings passed to the RegExp constructor + * @param {ASTNode} node node to validate + * @returns {void} + * @private + */ + function checkFunction(node) { + const scope = sourceCode.getScope(node); + const regExpVar = astUtils.getVariableByName(scope, "RegExp"); + const shadowed = regExpVar && regExpVar.defs.length > 0; + const patternNode = node.arguments[0]; + + if ( + node.callee.type === "Identifier" && + node.callee.name === "RegExp" && + isString(patternNode) && + !shadowed + ) { + const pattern = patternNode.value; + const rawPattern = patternNode.raw.slice(1, -1); + const rawPatternStartRange = patternNode.range[0] + 1; + let flags; + + if (node.arguments.length < 2) { + // It has no flags. + flags = ""; + } else { + const flagsNode = node.arguments[1]; + + if (isString(flagsNode)) { + flags = flagsNode.value; + } else { + // The flags cannot be determined. + return; + } + } + + checkRegex( + node, + pattern, + rawPattern, + rawPatternStartRange, + flags, + ); + } + } + + return { + Literal: checkLiteral, + CallExpression: checkFunction, + NewExpression: checkFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-exports.js b/node_modules/eslint/lib/rules/no-restricted-exports.js new file mode 100644 index 00000000..fd5ff4b5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-exports.js @@ -0,0 +1,227 @@ +/** + * @fileoverview Rule to disallow specified names in exports + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified names in exports", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-exports", + }, + + schema: [ + { + anyOf: [ + { + type: "object", + properties: { + restrictedNamedExports: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + restrictedNamedExportsPattern: { type: "string" }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + restrictedNamedExports: { + type: "array", + items: { + type: "string", + pattern: "^(?!default$)", + }, + uniqueItems: true, + }, + restrictedNamedExportsPattern: { type: "string" }, + restrictDefaultExports: { + type: "object", + properties: { + // Allow/Disallow `export default foo; export default 42; export default function foo() {}` format + direct: { + type: "boolean", + }, + + // Allow/Disallow `export { foo as default };` declarations + named: { + type: "boolean", + }, + + // Allow/Disallow `export { default } from "mod"; export { default as default } from "mod";` declarations + defaultFrom: { + type: "boolean", + }, + + // Allow/Disallow `export { foo as default } from "mod";` declarations + namedFrom: { + type: "boolean", + }, + + // Allow/Disallow `export * as default from "mod"`; declarations + namespaceFrom: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + restrictedNamed: + "'{{name}}' is restricted from being used as an exported name.", + restrictedDefault: "Exporting 'default' is restricted.", + }, + }, + + create(context) { + const restrictedNames = new Set( + context.options[0] && context.options[0].restrictedNamedExports, + ); + const restrictedNamePattern = + context.options[0] && + context.options[0].restrictedNamedExportsPattern; + const restrictDefaultExports = + context.options[0] && context.options[0].restrictDefaultExports; + const sourceCode = context.sourceCode; + + /** + * Checks and reports given exported name. + * @param {ASTNode} node exported `Identifier` or string `Literal` node to check. + * @returns {void} + */ + function checkExportedName(node) { + const name = astUtils.getModuleExportName(node); + + let matchesRestrictedNamePattern = false; + + if (restrictedNamePattern && name !== "default") { + const patternRegex = new RegExp(restrictedNamePattern, "u"); + + matchesRestrictedNamePattern = patternRegex.test(name); + } + + if (matchesRestrictedNamePattern || restrictedNames.has(name)) { + context.report({ + node, + messageId: "restrictedNamed", + data: { name }, + }); + return; + } + + if (name === "default") { + if (node.parent.type === "ExportAllDeclaration") { + if ( + restrictDefaultExports && + restrictDefaultExports.namespaceFrom + ) { + context.report({ + node, + messageId: "restrictedDefault", + }); + } + } else { + // ExportSpecifier + const isSourceSpecified = !!node.parent.parent.source; + const specifierLocalName = astUtils.getModuleExportName( + node.parent.local, + ); + + if ( + !isSourceSpecified && + restrictDefaultExports && + restrictDefaultExports.named + ) { + context.report({ + node, + messageId: "restrictedDefault", + }); + return; + } + + if (isSourceSpecified && restrictDefaultExports) { + if ( + (specifierLocalName === "default" && + restrictDefaultExports.defaultFrom) || + (specifierLocalName !== "default" && + restrictDefaultExports.namedFrom) + ) { + context.report({ + node, + messageId: "restrictedDefault", + }); + } + } + } + } + } + + return { + ExportAllDeclaration(node) { + if (node.exported) { + checkExportedName(node.exported); + } + }, + + ExportDefaultDeclaration(node) { + if (restrictDefaultExports && restrictDefaultExports.direct) { + context.report({ + node, + messageId: "restrictedDefault", + }); + } + }, + + ExportNamedDeclaration(node) { + const declaration = node.declaration; + + if (declaration) { + if ( + declaration.type === "FunctionDeclaration" || + declaration.type === "ClassDeclaration" + ) { + checkExportedName(declaration.id); + } else if (declaration.type === "VariableDeclaration") { + sourceCode + .getDeclaredVariables(declaration) + .map(v => + v.defs.find(d => d.parent === declaration), + ) + .map(d => d.name) // Identifier nodes + .forEach(checkExportedName); + } + } else { + node.specifiers + .map(s => s.exported) + .forEach(checkExportedName); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-globals.js b/node_modules/eslint/lib/rules/no-restricted-globals.js new file mode 100644 index 00000000..046356f1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-globals.js @@ -0,0 +1,156 @@ +/** + * @fileoverview Restrict usage of specified globals. + * @author Benoît Zugmeyer + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TYPE_NODES = new Set([ + "TSTypeReference", + "TSInterfaceHeritage", + "TSClassImplements", + "TSTypeQuery", + "TSQualifiedName", +]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Disallow specified global variables", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-globals", + }, + + schema: { + type: "array", + items: { + oneOf: [ + { + type: "string", + }, + { + type: "object", + properties: { + name: { type: "string" }, + message: { type: "string" }, + }, + required: ["name"], + additionalProperties: false, + }, + ], + }, + uniqueItems: true, + minItems: 0, + }, + + messages: { + defaultMessage: "Unexpected use of '{{name}}'.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + customMessage: "Unexpected use of '{{name}}'. {{customMessage}}", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + // If no globals are restricted, we don't need to do anything + if (context.options.length === 0) { + return {}; + } + + const restrictedGlobalMessages = context.options.reduce( + (memo, option) => { + if (typeof option === "string") { + memo[option] = null; + } else { + memo[option.name] = option.message; + } + + return memo; + }, + {}, + ); + + /** + * Report a variable to be used as a restricted global. + * @param {Reference} reference the variable reference + * @returns {void} + * @private + */ + function reportReference(reference) { + const name = reference.identifier.name, + customMessage = restrictedGlobalMessages[name], + messageId = customMessage ? "customMessage" : "defaultMessage"; + + context.report({ + node: reference.identifier, + messageId, + data: { + name, + customMessage, + }, + }); + } + + /** + * Check if the given name is a restricted global name. + * @param {string} name name of a variable + * @returns {boolean} whether the variable is a restricted global or not + * @private + */ + function isRestricted(name) { + return Object.hasOwn(restrictedGlobalMessages, name); + } + + /** + * Check if the given reference occurs within a TypeScript type context. + * @param {Reference} reference The variable reference to check. + * @returns {boolean} Whether the reference is in a type context. + * @private + */ + function isInTypeContext(reference) { + const parent = reference.identifier.parent; + + return TYPE_NODES.has(parent.type); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + + // Report variables declared elsewhere (ex: variables defined as "global" by eslint) + scope.variables.forEach(variable => { + if (!variable.defs.length && isRestricted(variable.name)) { + variable.references.forEach(reference => { + if (!isInTypeContext(reference)) { + reportReference(reference); + } + }); + } + }); + + // Report variables not declared at all + scope.through.forEach(reference => { + if ( + isRestricted(reference.identifier.name) && + !isInTypeContext(reference) + ) { + reportReference(reference); + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-imports.js b/node_modules/eslint/lib/rules/no-restricted-imports.js new file mode 100644 index 00000000..20ec3c2e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-imports.js @@ -0,0 +1,683 @@ +/** + * @fileoverview Restrict usage of specified node imports. + * @author Guy Ellis + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const ignore = require("ignore"); + +const arrayOfStringsOrObjects = { + type: "array", + items: { + anyOf: [ + { type: "string" }, + { + type: "object", + properties: { + name: { type: "string" }, + message: { + type: "string", + minLength: 1, + }, + importNames: { + type: "array", + items: { + type: "string", + }, + }, + allowImportNames: { + type: "array", + items: { + type: "string", + }, + }, + }, + additionalProperties: false, + required: ["name"], + not: { required: ["importNames", "allowImportNames"] }, + }, + ], + }, + uniqueItems: true, +}; + +const arrayOfStringsOrObjectPatterns = { + anyOf: [ + { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + { + type: "array", + items: { + type: "object", + properties: { + importNames: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + uniqueItems: true, + }, + allowImportNames: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + uniqueItems: true, + }, + group: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + uniqueItems: true, + }, + regex: { + type: "string", + }, + importNamePattern: { + type: "string", + }, + allowImportNamePattern: { + type: "string", + }, + message: { + type: "string", + minLength: 1, + }, + caseSensitive: { + type: "boolean", + }, + }, + additionalProperties: false, + not: { + anyOf: [ + { required: ["importNames", "allowImportNames"] }, + { + required: [ + "importNamePattern", + "allowImportNamePattern", + ], + }, + { required: ["importNames", "allowImportNamePattern"] }, + { required: ["importNamePattern", "allowImportNames"] }, + { + required: [ + "allowImportNames", + "allowImportNamePattern", + ], + }, + ], + }, + oneOf: [{ required: ["group"] }, { required: ["regex"] }], + }, + uniqueItems: true, + }, + ], +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified modules when loaded by `import`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-imports", + }, + + messages: { + path: "'{{importSource}}' import is restricted from being used.", + pathWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importSource}}' import is restricted from being used. {{customMessage}}", + + patterns: + "'{{importSource}}' import is restricted from being used by a pattern.", + patternWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importSource}}' import is restricted from being used by a pattern. {{customMessage}}", + + patternAndImportName: + "'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern.", + patternAndImportNameWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}", + + patternAndEverything: + "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted from being used by a pattern.", + + patternAndEverythingWithRegexImportName: + "* import is invalid because import name matching '{{importNames}}' pattern from '{{importSource}}' is restricted from being used.", + patternAndEverythingWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}", + patternAndEverythingWithRegexImportNameAndCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because import name matching '{{importNames}}' pattern from '{{importSource}}' is restricted from being used. {{customMessage}}", + + everything: + "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.", + everythingWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted. {{customMessage}}", + + importName: + "'{{importName}}' import from '{{importSource}}' is restricted.", + importNameWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importName}}' import from '{{importSource}}' is restricted. {{customMessage}}", + + allowedImportName: + "'{{importName}}' import from '{{importSource}}' is restricted because only '{{allowedImportNames}}' import(s) is/are allowed.", + allowedImportNameWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importName}}' import from '{{importSource}}' is restricted because only '{{allowedImportNames}}' import(s) is/are allowed. {{customMessage}}", + + everythingWithAllowImportNames: + "* import is invalid because only '{{allowedImportNames}}' from '{{importSource}}' is/are allowed.", + everythingWithAllowImportNamesAndCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because only '{{allowedImportNames}}' from '{{importSource}}' is/are allowed. {{customMessage}}", + + allowedImportNamePattern: + "'{{importName}}' import from '{{importSource}}' is restricted because only imports that match the pattern '{{allowedImportNamePattern}}' are allowed from '{{importSource}}'.", + allowedImportNamePatternWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importName}}' import from '{{importSource}}' is restricted because only imports that match the pattern '{{allowedImportNamePattern}}' are allowed from '{{importSource}}'. {{customMessage}}", + + everythingWithAllowedImportNamePattern: + "* import is invalid because only imports that match the pattern '{{allowedImportNamePattern}}' from '{{importSource}}' are allowed.", + everythingWithAllowedImportNamePatternWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because only imports that match the pattern '{{allowedImportNamePattern}}' from '{{importSource}}' are allowed. {{customMessage}}", + }, + + schema: { + anyOf: [ + arrayOfStringsOrObjects, + { + type: "array", + items: [ + { + type: "object", + properties: { + paths: arrayOfStringsOrObjects, + patterns: arrayOfStringsOrObjectPatterns, + }, + additionalProperties: false, + }, + ], + additionalItems: false, + }, + ], + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = Array.isArray(context.options) ? context.options : []; + const isPathAndPatternsObject = + typeof options[0] === "object" && + (Object.hasOwn(options[0], "paths") || + Object.hasOwn(options[0], "patterns")); + + const restrictedPaths = + (isPathAndPatternsObject ? options[0].paths : context.options) || + []; + const groupedRestrictedPaths = restrictedPaths.reduce( + (memo, importSource) => { + const path = + typeof importSource === "string" + ? importSource + : importSource.name; + + if (!memo[path]) { + memo[path] = []; + } + + if (typeof importSource === "string") { + memo[path].push({}); + } else { + memo[path].push({ + message: importSource.message, + importNames: importSource.importNames, + allowImportNames: importSource.allowImportNames, + }); + } + return memo; + }, + Object.create(null), + ); + + // Handle patterns too, either as strings or groups + let restrictedPatterns = + (isPathAndPatternsObject ? options[0].patterns : []) || []; + + // standardize to array of objects if we have an array of strings + if ( + restrictedPatterns.length > 0 && + typeof restrictedPatterns[0] === "string" + ) { + restrictedPatterns = [{ group: restrictedPatterns }]; + } + + // relative paths are supported for this rule + const restrictedPatternGroups = restrictedPatterns.map( + ({ + group, + regex, + message, + caseSensitive, + importNames, + importNamePattern, + allowImportNames, + allowImportNamePattern, + }) => ({ + ...(group + ? { + matcher: ignore({ + allowRelativePaths: true, + ignorecase: !caseSensitive, + }).add(group), + } + : {}), + ...(typeof regex === "string" + ? { + regexMatcher: new RegExp( + regex, + caseSensitive ? "u" : "iu", + ), + } + : {}), + customMessage: message, + importNames, + importNamePattern, + allowImportNames, + allowImportNamePattern, + }), + ); + + // if no imports are restricted we don't need to check + if ( + Object.keys(restrictedPaths).length === 0 && + restrictedPatternGroups.length === 0 + ) { + return {}; + } + + /** + * Report a restricted path. + * @param {string} importSource path of the import + * @param {Map} importNames Map of import names that are being imported + * @param {node} node representing the restricted path reference + * @returns {void} + * @private + */ + function checkRestrictedPathAndReport(importSource, importNames, node) { + if (!Object.hasOwn(groupedRestrictedPaths, importSource)) { + return; + } + + groupedRestrictedPaths[importSource].forEach( + restrictedPathEntry => { + const customMessage = restrictedPathEntry.message; + const restrictedImportNames = + restrictedPathEntry.importNames; + const allowedImportNames = + restrictedPathEntry.allowImportNames; + + if (!restrictedImportNames && !allowedImportNames) { + context.report({ + node, + messageId: customMessage + ? "pathWithCustomMessage" + : "path", + data: { + importSource, + customMessage, + }, + }); + + return; + } + + importNames.forEach((specifiers, importName) => { + if (importName === "*") { + const [specifier] = specifiers; + + if (restrictedImportNames) { + context.report({ + node, + messageId: customMessage + ? "everythingWithCustomMessage" + : "everything", + loc: specifier.loc, + data: { + importSource, + importNames: restrictedImportNames, + customMessage, + }, + }); + } else if (allowedImportNames) { + context.report({ + node, + messageId: customMessage + ? "everythingWithAllowImportNamesAndCustomMessage" + : "everythingWithAllowImportNames", + loc: specifier.loc, + data: { + importSource, + allowedImportNames, + customMessage, + }, + }); + } + + return; + } + + if ( + restrictedImportNames && + restrictedImportNames.includes(importName) + ) { + specifiers.forEach(specifier => { + context.report({ + node, + messageId: customMessage + ? "importNameWithCustomMessage" + : "importName", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName, + }, + }); + }); + } + + if ( + allowedImportNames && + !allowedImportNames.includes(importName) + ) { + specifiers.forEach(specifier => { + context.report({ + node, + loc: specifier.loc, + messageId: customMessage + ? "allowedImportNameWithCustomMessage" + : "allowedImportName", + data: { + importSource, + customMessage, + importName, + allowedImportNames, + }, + }); + }); + } + }); + }, + ); + } + + /** + * Report a restricted path specifically for patterns. + * @param {node} node representing the restricted path reference + * @param {Object} group contains an Ignore instance for paths, the customMessage to show on failure, + * and any restricted import names that have been specified in the config + * @param {Map} importNames Map of import names that are being imported + * @returns {void} + * @private + */ + function reportPathForPatterns(node, group, importNames) { + const importSource = node.source.value.trim(); + + const customMessage = group.customMessage; + const restrictedImportNames = group.importNames; + const restrictedImportNamePattern = group.importNamePattern + ? new RegExp(group.importNamePattern, "u") + : null; + const allowedImportNames = group.allowImportNames; + const allowedImportNamePattern = group.allowImportNamePattern + ? new RegExp(group.allowImportNamePattern, "u") + : null; + + /** + * If we are not restricting to any specific import names and just the pattern itself, + * report the error and move on + */ + if ( + !restrictedImportNames && + !allowedImportNames && + !restrictedImportNamePattern && + !allowedImportNamePattern + ) { + context.report({ + node, + messageId: customMessage + ? "patternWithCustomMessage" + : "patterns", + data: { + importSource, + customMessage, + }, + }); + return; + } + + importNames.forEach((specifiers, importName) => { + if (importName === "*") { + const [specifier] = specifiers; + + if (restrictedImportNames) { + context.report({ + node, + messageId: customMessage + ? "patternAndEverythingWithCustomMessage" + : "patternAndEverything", + loc: specifier.loc, + data: { + importSource, + importNames: restrictedImportNames, + customMessage, + }, + }); + } else if (allowedImportNames) { + context.report({ + node, + messageId: customMessage + ? "everythingWithAllowImportNamesAndCustomMessage" + : "everythingWithAllowImportNames", + loc: specifier.loc, + data: { + importSource, + allowedImportNames, + customMessage, + }, + }); + } else if (allowedImportNamePattern) { + context.report({ + node, + messageId: customMessage + ? "everythingWithAllowedImportNamePatternWithCustomMessage" + : "everythingWithAllowedImportNamePattern", + loc: specifier.loc, + data: { + importSource, + allowedImportNamePattern, + customMessage, + }, + }); + } else { + context.report({ + node, + messageId: customMessage + ? "patternAndEverythingWithRegexImportNameAndCustomMessage" + : "patternAndEverythingWithRegexImportName", + loc: specifier.loc, + data: { + importSource, + importNames: restrictedImportNamePattern, + customMessage, + }, + }); + } + + return; + } + + if ( + (restrictedImportNames && + restrictedImportNames.includes(importName)) || + (restrictedImportNamePattern && + restrictedImportNamePattern.test(importName)) + ) { + specifiers.forEach(specifier => { + context.report({ + node, + messageId: customMessage + ? "patternAndImportNameWithCustomMessage" + : "patternAndImportName", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName, + }, + }); + }); + } + + if ( + allowedImportNames && + !allowedImportNames.includes(importName) + ) { + specifiers.forEach(specifier => { + context.report({ + node, + messageId: customMessage + ? "allowedImportNameWithCustomMessage" + : "allowedImportName", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName, + allowedImportNames, + }, + }); + }); + } else if ( + allowedImportNamePattern && + !allowedImportNamePattern.test(importName) + ) { + specifiers.forEach(specifier => { + context.report({ + node, + messageId: customMessage + ? "allowedImportNamePatternWithCustomMessage" + : "allowedImportNamePattern", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName, + allowedImportNamePattern, + }, + }); + }); + } + }); + } + + /** + * Check if the given importSource is restricted by a pattern. + * @param {string} importSource path of the import + * @param {Object} group contains a Ignore instance for paths, and the customMessage to show if it fails + * @returns {boolean} whether the variable is a restricted pattern or not + * @private + */ + function isRestrictedPattern(importSource, group) { + return group.regexMatcher + ? group.regexMatcher.test(importSource) + : group.matcher.ignores(importSource); + } + + /** + * Checks a node to see if any problems should be reported. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkNode(node) { + const importSource = node.source.value.trim(); + const importNames = new Map(); + + if (node.type === "ExportAllDeclaration") { + const starToken = sourceCode.getFirstToken(node, 1); + + importNames.set("*", [{ loc: starToken.loc }]); + } else if (node.specifiers) { + for (const specifier of node.specifiers) { + let name; + const specifierData = { loc: specifier.loc }; + + if (specifier.type === "ImportDefaultSpecifier") { + name = "default"; + } else if (specifier.type === "ImportNamespaceSpecifier") { + name = "*"; + } else if (specifier.imported) { + name = astUtils.getModuleExportName(specifier.imported); + } else if (specifier.local) { + name = astUtils.getModuleExportName(specifier.local); + } + + if (typeof name === "string") { + if (importNames.has(name)) { + importNames.get(name).push(specifierData); + } else { + importNames.set(name, [specifierData]); + } + } + } + } + + checkRestrictedPathAndReport(importSource, importNames, node); + restrictedPatternGroups.forEach(group => { + if (isRestrictedPattern(importSource, group)) { + reportPathForPatterns(node, group, importNames); + } + }); + } + + return { + ImportDeclaration: checkNode, + ExportNamedDeclaration(node) { + if (node.source) { + checkNode(node); + } + }, + ExportAllDeclaration: checkNode, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-modules.js b/node_modules/eslint/lib/rules/no-restricted-modules.js new file mode 100644 index 00000000..d6a72ec8 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-modules.js @@ -0,0 +1,249 @@ +/** + * @fileoverview Restrict usage of specified node modules. + * @author Christian Schulz + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const ignore = require("ignore"); + +const arrayOfStrings = { + type: "array", + items: { type: "string" }, + uniqueItems: true, +}; + +const arrayOfStringsOrObjects = { + type: "array", + items: { + anyOf: [ + { type: "string" }, + { + type: "object", + properties: { + name: { type: "string" }, + message: { + type: "string", + minLength: 1, + }, + }, + additionalProperties: false, + required: ["name"], + }, + ], + }, + uniqueItems: true, +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-restricted-require", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-restricted-require.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow specified modules when loaded by `require`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-modules", + }, + + schema: { + anyOf: [ + arrayOfStringsOrObjects, + { + type: "array", + items: { + type: "object", + properties: { + paths: arrayOfStringsOrObjects, + patterns: arrayOfStrings, + }, + additionalProperties: false, + }, + additionalItems: false, + }, + ], + }, + + messages: { + defaultMessage: "'{{name}}' module is restricted from being used.", + customMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{name}}' module is restricted from being used. {{customMessage}}", + patternMessage: + "'{{name}}' module is restricted from being used by a pattern.", + }, + }, + + create(context) { + const options = Array.isArray(context.options) ? context.options : []; + const isPathAndPatternsObject = + typeof options[0] === "object" && + (Object.hasOwn(options[0], "paths") || + Object.hasOwn(options[0], "patterns")); + + const restrictedPaths = + (isPathAndPatternsObject ? options[0].paths : context.options) || + []; + const restrictedPatterns = + (isPathAndPatternsObject ? options[0].patterns : []) || []; + + const restrictedPathMessages = restrictedPaths.reduce( + (memo, importName) => { + if (typeof importName === "string") { + memo[importName] = null; + } else { + memo[importName.name] = importName.message; + } + return memo; + }, + {}, + ); + + // if no imports are restricted we don't need to check + if ( + Object.keys(restrictedPaths).length === 0 && + restrictedPatterns.length === 0 + ) { + return {}; + } + + // relative paths are supported for this rule + const ig = ignore({ allowRelativePaths: true }).add(restrictedPatterns); + + /** + * Function to check if a node is a string literal. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a string literal. + */ + function isStringLiteral(node) { + return ( + node && + node.type === "Literal" && + typeof node.value === "string" + ); + } + + /** + * Function to check if a node is a require call. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a require call. + */ + function isRequireCall(node) { + return ( + node.callee.type === "Identifier" && + node.callee.name === "require" + ); + } + + /** + * Extract string from Literal or TemplateLiteral node + * @param {ASTNode} node The node to extract from + * @returns {string|null} Extracted string or null if node doesn't represent a string + */ + function getFirstArgumentString(node) { + if (isStringLiteral(node)) { + return node.value.trim(); + } + + if (astUtils.isStaticTemplateLiteral(node)) { + return node.quasis[0].value.cooked.trim(); + } + + return null; + } + + /** + * Report a restricted path. + * @param {node} node representing the restricted path reference + * @param {string} name restricted path + * @returns {void} + * @private + */ + function reportPath(node, name) { + const customMessage = restrictedPathMessages[name]; + const messageId = customMessage + ? "customMessage" + : "defaultMessage"; + + context.report({ + node, + messageId, + data: { + name, + customMessage, + }, + }); + } + + /** + * Check if the given name is a restricted path name + * @param {string} name name of a variable + * @returns {boolean} whether the variable is a restricted path or not + * @private + */ + function isRestrictedPath(name) { + return Object.hasOwn(restrictedPathMessages, name); + } + + return { + CallExpression(node) { + if (isRequireCall(node)) { + // node has arguments + if (node.arguments.length) { + const name = getFirstArgumentString(node.arguments[0]); + + // if first argument is a string literal or a static string template literal + if (name) { + // check if argument value is in restricted modules array + if (isRestrictedPath(name)) { + reportPath(node, name); + } + + if ( + restrictedPatterns.length > 0 && + ig.ignores(name) + ) { + context.report({ + node, + messageId: "patternMessage", + data: { name }, + }); + } + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-properties.js b/node_modules/eslint/lib/rules/no-restricted-properties.js new file mode 100644 index 00000000..0e19f388 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-properties.js @@ -0,0 +1,224 @@ +/** + * @fileoverview Rule to disallow certain object properties + * @author Will Klein & Eli White + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow certain properties on certain objects", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-properties", + }, + + schema: { + type: "array", + items: { + type: "object", + properties: { + object: { + type: "string", + }, + property: { + type: "string", + }, + allowObjects: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + allowProperties: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + message: { + type: "string", + }, + }, + anyOf: [ + { + required: ["object"], + }, + { + required: ["property"], + }, + ], + not: { + anyOf: [ + { required: ["allowObjects", "object"] }, + { required: ["allowProperties", "property"] }, + ], + }, + additionalProperties: false, + }, + uniqueItems: true, + }, + + messages: { + restrictedObjectProperty: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}", + restrictedProperty: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{propertyName}}' is restricted from being used.{{message}}", + }, + }, + + create(context) { + const restrictedCalls = context.options; + + if (restrictedCalls.length === 0) { + return {}; + } + + const restrictedProperties = new Map(); + const globallyRestrictedObjects = new Map(); + const globallyRestrictedProperties = new Map(); + + restrictedCalls.forEach(option => { + const objectName = option.object; + const propertyName = option.property; + + if (typeof objectName === "undefined") { + globallyRestrictedProperties.set(propertyName, { + allowObjects: option.allowObjects, + message: option.message, + }); + } else if (typeof propertyName === "undefined") { + globallyRestrictedObjects.set(objectName, { + allowProperties: option.allowProperties, + message: option.message, + }); + } else { + if (!restrictedProperties.has(objectName)) { + restrictedProperties.set(objectName, new Map()); + } + + restrictedProperties.get(objectName).set(propertyName, { + message: option.message, + }); + } + }); + + /** + * Checks if a name is in the allowed list. + * @param {string} name The name to check + * @param {string[]} [allowedList] The list of allowed names + * @returns {boolean} True if the name is allowed, false otherwise + */ + function isAllowed(name, allowedList) { + if (!allowedList) { + return false; + } + + return allowedList.includes(name); + } + + /** + * Checks to see whether a property access is restricted, and reports it if so. + * @param {ASTNode} node The node to report + * @param {string} objectName The name of the object + * @param {string} propertyName The name of the property + * @returns {undefined} + */ + function checkPropertyAccess(node, objectName, propertyName) { + if (propertyName === null) { + return; + } + const matchedObject = restrictedProperties.get(objectName); + const matchedObjectProperty = matchedObject + ? matchedObject.get(propertyName) + : globallyRestrictedObjects.get(objectName); + const globalMatchedProperty = + globallyRestrictedProperties.get(propertyName); + + if ( + matchedObjectProperty && + !isAllowed(propertyName, matchedObjectProperty.allowProperties) + ) { + const message = matchedObjectProperty.message + ? ` ${matchedObjectProperty.message}` + : ""; + + context.report({ + node, + messageId: "restrictedObjectProperty", + data: { + objectName, + propertyName, + message, + }, + }); + } else if ( + globalMatchedProperty && + !isAllowed(objectName, globalMatchedProperty.allowObjects) + ) { + const message = globalMatchedProperty.message + ? ` ${globalMatchedProperty.message}` + : ""; + + context.report({ + node, + messageId: "restrictedProperty", + data: { + propertyName, + message, + }, + }); + } + } + + return { + MemberExpression(node) { + checkPropertyAccess( + node, + node.object && node.object.name, + astUtils.getStaticPropertyName(node), + ); + }, + ObjectPattern(node) { + let objectName = null; + + if (node.parent.type === "VariableDeclarator") { + if ( + node.parent.init && + node.parent.init.type === "Identifier" + ) { + objectName = node.parent.init.name; + } + } else if ( + node.parent.type === "AssignmentExpression" || + node.parent.type === "AssignmentPattern" + ) { + if (node.parent.right.type === "Identifier") { + objectName = node.parent.right.name; + } + } + + node.properties.forEach(property => { + checkPropertyAccess( + node, + objectName, + astUtils.getStaticPropertyName(property), + ); + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-syntax.js b/node_modules/eslint/lib/rules/no-restricted-syntax.js new file mode 100644 index 00000000..447d29cf --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-syntax.js @@ -0,0 +1,74 @@ +/** + * @fileoverview Rule to flag use of certain node types + * @author Burak Yigit Kaya + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified syntax", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-syntax", + }, + + schema: { + type: "array", + items: { + oneOf: [ + { + type: "string", + }, + { + type: "object", + properties: { + selector: { type: "string" }, + message: { type: "string" }, + }, + required: ["selector"], + additionalProperties: false, + }, + ], + }, + uniqueItems: true, + minItems: 0, + }, + + messages: { + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + restrictedSyntax: "{{message}}", + }, + }, + + create(context) { + return context.options.reduce((result, selectorOrObject) => { + const isStringFormat = typeof selectorOrObject === "string"; + const hasCustomMessage = + !isStringFormat && Boolean(selectorOrObject.message); + + const selector = isStringFormat + ? selectorOrObject + : selectorOrObject.selector; + const message = hasCustomMessage + ? selectorOrObject.message + : `Using '${selector}' is not allowed.`; + + return Object.assign(result, { + [selector](node) { + context.report({ + node, + messageId: "restrictedSyntax", + data: { message }, + }); + }, + }); + }, {}); + }, +}; diff --git a/node_modules/eslint/lib/rules/no-return-assign.js b/node_modules/eslint/lib/rules/no-return-assign.js new file mode 100644 index 00000000..92999ddf --- /dev/null +++ b/node_modules/eslint/lib/rules/no-return-assign.js @@ -0,0 +1,87 @@ +/** + * @fileoverview Rule to flag when return statement contains assignment + * @author Ilya Volodin + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_TYPE = + /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/u; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["except-parens"], + + docs: { + description: "Disallow assignment operators in `return` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-return-assign", + }, + + schema: [ + { + enum: ["except-parens", "always"], + }, + ], + + messages: { + returnAssignment: "Return statement should not contain assignment.", + arrowAssignment: "Arrow function should not return assignment.", + }, + }, + + create(context) { + const always = context.options[0] !== "except-parens"; + const sourceCode = context.sourceCode; + + return { + AssignmentExpression(node) { + if (!always && astUtils.isParenthesised(sourceCode, node)) { + return; + } + + let currentChild = node; + let parent = currentChild.parent; + + // Find ReturnStatement or ArrowFunctionExpression in ancestors. + while (parent && !SENTINEL_TYPE.test(parent.type)) { + currentChild = parent; + parent = parent.parent; + } + + // Reports. + if (parent && parent.type === "ReturnStatement") { + context.report({ + node: parent, + messageId: "returnAssignment", + }); + } else if ( + parent && + parent.type === "ArrowFunctionExpression" && + parent.body === currentChild + ) { + context.report({ + node: parent, + messageId: "arrowAssignment", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-return-await.js b/node_modules/eslint/lib/rules/no-return-await.js new file mode 100644 index 00000000..21627edd --- /dev/null +++ b/node_modules/eslint/lib/rules/no-return-await.js @@ -0,0 +1,162 @@ +/** + * @fileoverview Disallows unnecessary `return await` + * @author Jordan Harband + * @deprecated in ESLint v8.46.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + docs: { + description: "Disallow unnecessary `return await`", + + recommended: false, + + url: "https://eslint.org/docs/latest/rules/no-return-await", + }, + + fixable: null, + + deprecated: { + message: + "The original assumption of the rule no longer holds true because of engine optimization.", + deprecatedSince: "8.46.0", + availableUntil: null, + replacedBy: [], + }, + + schema: [], + + messages: { + removeAwait: "Remove redundant `await`.", + redundantUseOfAwait: "Redundant use of `await` on a return value.", + }, + }, + + create(context) { + /** + * Reports a found unnecessary `await` expression. + * @param {ASTNode} node The node representing the `await` expression to report + * @returns {void} + */ + function reportUnnecessaryAwait(node) { + context.report({ + node: context.sourceCode.getFirstToken(node), + loc: node.loc, + messageId: "redundantUseOfAwait", + suggest: [ + { + messageId: "removeAwait", + fix(fixer) { + const sourceCode = context.sourceCode; + const [awaitToken, tokenAfterAwait] = + sourceCode.getFirstTokens(node, 2); + + const areAwaitAndAwaitedExpressionOnTheSameLine = + awaitToken.loc.start.line === + tokenAfterAwait.loc.start.line; + + if (!areAwaitAndAwaitedExpressionOnTheSameLine) { + return null; + } + + const [startOfAwait, endOfAwait] = awaitToken.range; + + const characterAfterAwait = + sourceCode.text[endOfAwait]; + const trimLength = + characterAfterAwait === " " ? 1 : 0; + + const range = [ + startOfAwait, + endOfAwait + trimLength, + ]; + + return fixer.removeRange(range); + }, + }, + ], + }); + } + + /** + * Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting + * this function. For example, a statement in a `try` block will always have an error handler. A statement in + * a `catch` block will only have an error handler if there is also a `finally` block. + * @param {ASTNode} node A node representing a location where an could be thrown + * @returns {boolean} `true` if a thrown error will be caught/handled in this function + */ + function hasErrorHandler(node) { + let ancestor = node; + + while ( + !astUtils.isFunction(ancestor) && + ancestor.type !== "Program" + ) { + if ( + ancestor.parent.type === "TryStatement" && + (ancestor === ancestor.parent.block || + (ancestor === ancestor.parent.handler && + ancestor.parent.finalizer)) + ) { + return true; + } + ancestor = ancestor.parent; + } + return false; + } + + /** + * Checks if a node is placed in tail call position. Once `return` arguments (or arrow function expressions) can be a complex expression, + * an `await` expression could or could not be unnecessary by the definition of this rule. So we're looking for `await` expressions that are in tail position. + * @param {ASTNode} node A node representing the `await` expression to check + * @returns {boolean} The checking result + */ + function isInTailCallPosition(node) { + if (node.parent.type === "ArrowFunctionExpression") { + return true; + } + if (node.parent.type === "ReturnStatement") { + return !hasErrorHandler(node.parent); + } + if ( + node.parent.type === "ConditionalExpression" && + (node === node.parent.consequent || + node === node.parent.alternate) + ) { + return isInTailCallPosition(node.parent); + } + if ( + node.parent.type === "LogicalExpression" && + node === node.parent.right + ) { + return isInTailCallPosition(node.parent); + } + if ( + node.parent.type === "SequenceExpression" && + node === node.parent.expressions.at(-1) + ) { + return isInTailCallPosition(node.parent); + } + return false; + } + + return { + AwaitExpression(node) { + if (isInTailCallPosition(node) && !hasErrorHandler(node)) { + reportUnnecessaryAwait(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-script-url.js b/node_modules/eslint/lib/rules/no-script-url.js new file mode 100644 index 00000000..fe550b6d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-script-url.js @@ -0,0 +1,68 @@ +/** + * @fileoverview Rule to disallow `javascript:` URLs + * @author Ilya Volodin + */ +/* eslint no-script-url: 0 -- Code is checking to report such URLs */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `javascript:` URLs", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-script-url", + }, + + schema: [], + + messages: { + unexpectedScriptURL: "Script URL is a form of eval.", + }, + }, + + create(context) { + /** + * Check whether a node's static value starts with `javascript:` or not. + * And report an error for unexpected script URL. + * @param {ASTNode} node node to check + * @returns {void} + */ + function check(node) { + const value = astUtils.getStaticStringValue(node); + + if ( + typeof value === "string" && + value.toLowerCase().indexOf("javascript:") === 0 + ) { + context.report({ node, messageId: "unexpectedScriptURL" }); + } + } + return { + Literal(node) { + if (node.value && typeof node.value === "string") { + check(node); + } + }, + TemplateLiteral(node) { + if ( + !( + node.parent && + node.parent.type === "TaggedTemplateExpression" + ) + ) { + check(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-self-assign.js b/node_modules/eslint/lib/rules/no-self-assign.js new file mode 100644 index 00000000..c1831bb0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-self-assign.js @@ -0,0 +1,186 @@ +/** + * @fileoverview Rule to disallow assignments where both sides are exactly the same + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SPACES = /\s+/gu; + +/** + * Traverses 2 Pattern nodes in parallel, then reports self-assignments. + * @param {ASTNode|null} left A left node to traverse. This is a Pattern or + * a Property. + * @param {ASTNode|null} right A right node to traverse. This is a Pattern or + * a Property. + * @param {boolean} props The flag to check member expressions as well. + * @param {Function} report A callback function to report. + * @returns {void} + */ +function eachSelfAssignment(left, right, props, report) { + if (!left || !right) { + // do nothing + } else if ( + left.type === "Identifier" && + right.type === "Identifier" && + left.name === right.name + ) { + report(right); + } else if ( + left.type === "ArrayPattern" && + right.type === "ArrayExpression" + ) { + const end = Math.min(left.elements.length, right.elements.length); + + for (let i = 0; i < end; ++i) { + const leftElement = left.elements[i]; + const rightElement = right.elements[i]; + + // Avoid cases such as [...a] = [...a, 1] + if ( + leftElement && + leftElement.type === "RestElement" && + i < right.elements.length - 1 + ) { + break; + } + + eachSelfAssignment(leftElement, rightElement, props, report); + + // After a spread element, those indices are unknown. + if (rightElement && rightElement.type === "SpreadElement") { + break; + } + } + } else if (left.type === "RestElement" && right.type === "SpreadElement") { + eachSelfAssignment(left.argument, right.argument, props, report); + } else if ( + left.type === "ObjectPattern" && + right.type === "ObjectExpression" && + right.properties.length >= 1 + ) { + /* + * Gets the index of the last spread property. + * It's possible to overwrite properties followed by it. + */ + let startJ = 0; + + for (let i = right.properties.length - 1; i >= 0; --i) { + const propType = right.properties[i].type; + + if ( + propType === "SpreadElement" || + propType === "ExperimentalSpreadProperty" + ) { + startJ = i + 1; + break; + } + } + + for (let i = 0; i < left.properties.length; ++i) { + for (let j = startJ; j < right.properties.length; ++j) { + eachSelfAssignment( + left.properties[i], + right.properties[j], + props, + report, + ); + } + } + } else if ( + left.type === "Property" && + right.type === "Property" && + right.kind === "init" && + !right.method + ) { + const leftName = astUtils.getStaticPropertyName(left); + + if ( + leftName !== null && + leftName === astUtils.getStaticPropertyName(right) + ) { + eachSelfAssignment(left.value, right.value, props, report); + } + } else if ( + props && + astUtils.skipChainExpression(left).type === "MemberExpression" && + astUtils.skipChainExpression(right).type === "MemberExpression" && + astUtils.isSameReference(left, right) + ) { + report(right); + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [{ props: true }], + + docs: { + description: + "Disallow assignments where both sides are exactly the same", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-self-assign", + }, + + schema: [ + { + type: "object", + properties: { + props: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + selfAssignment: "'{{name}}' is assigned to itself.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ props }] = context.options; + + /** + * Reports a given node as self assignments. + * @param {ASTNode} node A node to report. This is an Identifier node. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "selfAssignment", + data: { + name: sourceCode.getText(node).replace(SPACES, ""), + }, + }); + } + + return { + AssignmentExpression(node) { + if (["=", "&&=", "||=", "??="].includes(node.operator)) { + eachSelfAssignment(node.left, node.right, props, report); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-self-compare.js b/node_modules/eslint/lib/rules/no-self-compare.js new file mode 100644 index 00000000..ee05d3a6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-self-compare.js @@ -0,0 +1,77 @@ +/** + * @fileoverview Rule to flag comparison where left part is the same as the right + * part. + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow comparisons where both sides are exactly the same", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-self-compare", + }, + + schema: [], + + messages: { + comparingToSelf: "Comparing to itself is potentially pointless.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether two nodes are composed of the same tokens. + * @param {ASTNode} nodeA The first node + * @param {ASTNode} nodeB The second node + * @returns {boolean} true if the nodes have identical token representations + */ + function hasSameTokens(nodeA, nodeB) { + const tokensA = sourceCode.getTokens(nodeA); + const tokensB = sourceCode.getTokens(nodeB); + + return ( + tokensA.length === tokensB.length && + tokensA.every( + (token, index) => + token.type === tokensB[index].type && + token.value === tokensB[index].value, + ) + ); + } + + return { + BinaryExpression(node) { + const operators = new Set([ + "===", + "==", + "!==", + "!=", + ">", + "<", + ">=", + "<=", + ]); + + if ( + operators.has(node.operator) && + hasSameTokens(node.left, node.right) + ) { + context.report({ node, messageId: "comparingToSelf" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-sequences.js b/node_modules/eslint/lib/rules/no-sequences.js new file mode 100644 index 00000000..96a8ba4e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-sequences.js @@ -0,0 +1,158 @@ +/** + * @fileoverview Rule to flag use of comma operator + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow comma operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-sequences", + }, + + schema: [ + { + type: "object", + properties: { + allowInParentheses: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + allowInParentheses: true, + }, + ], + + messages: { + unexpectedCommaExpression: "Unexpected use of comma operator.", + }, + }, + + create(context) { + const [{ allowInParentheses }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Parts of the grammar that are required to have parens. + */ + const parenthesized = { + DoWhileStatement: "test", + IfStatement: "test", + SwitchStatement: "discriminant", + WhileStatement: "test", + WithStatement: "object", + ArrowFunctionExpression: "body", + + /* + * Omitting CallExpression - commas are parsed as argument separators + * Omitting NewExpression - commas are parsed as argument separators + * Omitting ForInStatement - parts aren't individually parenthesised + * Omitting ForStatement - parts aren't individually parenthesised + */ + }; + + /** + * Determines whether a node is required by the grammar to be wrapped in + * parens, e.g. the test of an if statement. + * @param {ASTNode} node The AST node + * @returns {boolean} True if parens around node belong to parent node. + */ + function requiresExtraParens(node) { + return ( + node.parent && + parenthesized[node.parent.type] && + node === node.parent[parenthesized[node.parent.type]] + ); + } + + /** + * Check if a node is wrapped in parens. + * @param {ASTNode} node The AST node + * @returns {boolean} True if the node has a paren on each side. + */ + function isParenthesised(node) { + return astUtils.isParenthesised(sourceCode, node); + } + + /** + * Check if a node is wrapped in two levels of parens. + * @param {ASTNode} node The AST node + * @returns {boolean} True if two parens surround the node on each side. + */ + function isParenthesisedTwice(node) { + const previousToken = sourceCode.getTokenBefore(node, 1), + nextToken = sourceCode.getTokenAfter(node, 1); + + return ( + isParenthesised(node) && + previousToken && + nextToken && + astUtils.isOpeningParenToken(previousToken) && + previousToken.range[1] <= node.range[0] && + astUtils.isClosingParenToken(nextToken) && + nextToken.range[0] >= node.range[1] + ); + } + + return { + SequenceExpression(node) { + // Always allow sequences in for statement update + if ( + node.parent.type === "ForStatement" && + (node === node.parent.init || node === node.parent.update) + ) { + return; + } + + // Wrapping a sequence in extra parens indicates intent + if (allowInParentheses) { + if (requiresExtraParens(node)) { + if (isParenthesisedTwice(node)) { + return; + } + } else { + if (isParenthesised(node)) { + return; + } + } + } + + const firstCommaToken = sourceCode.getTokenAfter( + node.expressions[0], + astUtils.isCommaToken, + ); + + context.report({ + node, + loc: firstCommaToken.loc, + messageId: "unexpectedCommaExpression", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-setter-return.js b/node_modules/eslint/lib/rules/no-setter-return.js new file mode 100644 index 00000000..63e0de53 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-setter-return.js @@ -0,0 +1,224 @@ +/** + * @fileoverview Rule to disallow returning values from setters + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is an argument of the specified global method call, at the given `index` position. + * E.g., for given `index === 1`, this function checks for `objectName.methodName(foo, node)`, where objectName is a global variable. + * @param {ASTNode} node The node to check. + * @param {SourceCode} sourceCode Source code to which the node belongs. + * @param {string} objectName Name of the global object. + * @param {string} methodName Name of the method. + * @param {number} index The given position. + * @returns {boolean} `true` if the node is argument at the given position. + */ +function isArgumentOfGlobalMethodCall( + node, + sourceCode, + objectName, + methodName, + index, +) { + const callNode = node.parent; + + return ( + callNode.type === "CallExpression" && + callNode.arguments[index] === node && + astUtils.isSpecificMemberAccess( + callNode.callee, + objectName, + methodName, + ) && + sourceCode.isGlobalReference( + astUtils.skipChainExpression(callNode.callee).object, + ) + ); +} + +/** + * Determines whether the given node is used as a property descriptor. + * @param {ASTNode} node The node to check. + * @param {SourceCode} sourceCode Source code to which the node belongs. + * @returns {boolean} `true` if the node is a property descriptor. + */ +function isPropertyDescriptor(node, sourceCode) { + if ( + isArgumentOfGlobalMethodCall( + node, + sourceCode, + "Object", + "defineProperty", + 2, + ) || + isArgumentOfGlobalMethodCall( + node, + sourceCode, + "Reflect", + "defineProperty", + 2, + ) + ) { + return true; + } + + const parent = node.parent; + + if (parent.type === "Property" && parent.value === node) { + const grandparent = parent.parent; + + if ( + grandparent.type === "ObjectExpression" && + (isArgumentOfGlobalMethodCall( + grandparent, + sourceCode, + "Object", + "create", + 1, + ) || + isArgumentOfGlobalMethodCall( + grandparent, + sourceCode, + "Object", + "defineProperties", + 1, + )) + ) { + return true; + } + } + + return false; +} + +/** + * Determines whether the given function node is used as a setter function. + * @param {ASTNode} node The node to check. + * @param {SourceCode} sourceCode Source code to which the node belongs. + * @returns {boolean} `true` if the node is a setter. + */ +function isSetter(node, sourceCode) { + const parent = node.parent; + + if ( + (parent.type === "Property" || parent.type === "MethodDefinition") && + parent.kind === "set" && + parent.value === node + ) { + // Setter in an object literal or in a class + return true; + } + + if ( + parent.type === "Property" && + parent.value === node && + astUtils.getStaticPropertyName(parent) === "set" && + parent.parent.type === "ObjectExpression" && + isPropertyDescriptor(parent.parent, sourceCode) + ) { + // Setter in a property descriptor + return true; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow returning values from setters", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-setter-return", + }, + + schema: [], + + messages: { + returnsValue: "Setter cannot return a value.", + }, + }, + + create(context) { + let funcInfo = null; + const sourceCode = context.sourceCode; + + /** + * Creates and pushes to the stack a function info object for the given function node. + * @param {ASTNode} node The function node. + * @returns {void} + */ + function enterFunction(node) { + funcInfo = { + upper: funcInfo, + isSetter: isSetter(node, sourceCode), + }; + } + + /** + * Pops the current function info object from the stack. + * @returns {void} + */ + function exitFunction() { + funcInfo = funcInfo.upper; + } + + /** + * Reports the given node. + * @param {ASTNode} node Node to report. + * @returns {void} + */ + function report(node) { + context.report({ node, messageId: "returnsValue" }); + } + + return { + /* + * Function declarations cannot be setters, but we still have to track them in the `funcInfo` stack to avoid + * false positives, because a ReturnStatement node can belong to a function declaration inside a setter. + * + * Note: A previously declared function can be referenced and actually used as a setter in a property descriptor, + * but that's out of scope for this rule. + */ + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression(node) { + enterFunction(node); + + if (funcInfo.isSetter && node.expression) { + // { set: foo => bar } property descriptor. Report implicit return 'bar' as the equivalent for a return statement. + report(node.body); + } + }, + + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + "ArrowFunctionExpression:exit": exitFunction, + + ReturnStatement(node) { + // Global returns (e.g., at the top level of a Node module) don't have `funcInfo`. + if (funcInfo && funcInfo.isSetter && node.argument) { + report(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-shadow-restricted-names.js b/node_modules/eslint/lib/rules/no-shadow-restricted-names.js new file mode 100644 index 00000000..949eed8e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-shadow-restricted-names.js @@ -0,0 +1,113 @@ +/** + * @fileoverview Disallow shadowing of globalThis, NaN, undefined, and Infinity (ES2020 section 18.1) + * @author Michael Ficarra + */ +"use strict"; + +/** + * Determines if a variable safely shadows undefined. + * This is the case when a variable named `undefined` is never assigned to a value (i.e. it always shares the same value + * as the global). + * @param {eslintScope.Variable} variable The variable to check + * @returns {boolean} true if this variable safely shadows `undefined` + */ +function safelyShadowsUndefined(variable) { + return ( + variable.name === "undefined" && + variable.references.every(ref => !ref.isWrite()) && + variable.defs.every( + def => + def.node.type === "VariableDeclarator" && + def.node.init === null, + ) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + reportGlobalThis: false, + }, + ], + + docs: { + description: "Disallow identifiers from shadowing restricted names", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-shadow-restricted-names", + }, + + schema: [ + { + type: "object", + properties: { + reportGlobalThis: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + shadowingRestrictedName: "Shadowing of global property '{{name}}'.", + }, + }, + + create(context) { + const [{ reportGlobalThis }] = context.options; + + const RESTRICTED = new Set([ + "undefined", + "NaN", + "Infinity", + "arguments", + "eval", + ]); + + if (reportGlobalThis) { + RESTRICTED.add("globalThis"); + } + + const sourceCode = context.sourceCode; + + // Track reported nodes to avoid duplicate reports. For example, on class declarations. + const reportedNodes = new Set(); + + return { + "VariableDeclaration, :function, CatchClause, ImportDeclaration, ClassDeclaration, ClassExpression"( + node, + ) { + for (const variable of sourceCode.getDeclaredVariables(node)) { + if ( + variable.defs.length > 0 && + RESTRICTED.has(variable.name) && + !safelyShadowsUndefined(variable) + ) { + for (const def of variable.defs) { + const nodeToReport = def.name; + + if (!reportedNodes.has(nodeToReport)) { + reportedNodes.add(nodeToReport); + context.report({ + node: nodeToReport, + messageId: "shadowingRestrictedName", + data: { + name: variable.name, + }, + }); + } + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-shadow.js b/node_modules/eslint/lib/rules/no-shadow.js new file mode 100644 index 00000000..bbd0f9e4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-shadow.js @@ -0,0 +1,624 @@ +/** + * @fileoverview Rule to flag on declaring variables already declared in the outer scope + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const FUNC_EXPR_NODE_TYPES = new Set([ + "ArrowFunctionExpression", + "FunctionExpression", +]); +const CALL_EXPR_NODE_TYPE = new Set(["CallExpression"]); +const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u; +const SENTINEL_TYPE = + /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u; + +// TS-specific node types +const TYPES_HOISTED_NODES = new Set([ + "TSInterfaceDeclaration", + "TSTypeAliasDeclaration", +]); + +// TS-specific function variable def types +const ALLOWED_FUNCTION_VARIABLE_DEF_TYPES = new Set([ + "TSCallSignatureDeclaration", + "TSFunctionType", + "TSMethodSignature", + "TSEmptyBodyFunctionExpression", + "TSDeclareFunction", + "TSConstructSignatureDeclaration", + "TSConstructorType", +]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["typescript", "javascript"], + language: "javascript", + + defaultOptions: [ + { + allow: [], + builtinGlobals: false, + hoist: "functions", + ignoreOnInitialization: false, + ignoreTypeValueShadow: true, + ignoreFunctionTypeParameterNameValueShadow: true, + }, + ], + + docs: { + description: + "Disallow variable declarations from shadowing variables declared in the outer scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-shadow", + }, + + schema: [ + { + type: "object", + properties: { + builtinGlobals: { type: "boolean" }, + hoist: { + enum: [ + "all", + "functions", + "never", + "types", + "functions-and-types", + ], + }, + allow: { + type: "array", + items: { + type: "string", + }, + }, + ignoreOnInitialization: { type: "boolean" }, + ignoreTypeValueShadow: { type: "boolean" }, + ignoreFunctionTypeParameterNameValueShadow: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + noShadow: + "'{{name}}' is already declared in the upper scope on line {{shadowedLine}} column {{shadowedColumn}}.", + noShadowGlobal: "'{{name}}' is already a global variable.", + }, + }, + + create(context) { + const [ + { + builtinGlobals, + hoist, + allow, + ignoreOnInitialization, + ignoreTypeValueShadow, + ignoreFunctionTypeParameterNameValueShadow, + }, + ] = context.options; + const sourceCode = context.sourceCode; + + /** + * Check if a scope is a TypeScript module augmenting the global namespace. + * @param {Scope} scope The scope to check + * @returns {boolean} Whether the scope is a global augmentation + */ + function isGlobalAugmentation(scope) { + return ( + scope.block.kind === "global" || + (!!scope.upper && isGlobalAugmentation(scope.upper)) + ); + } + + /** + * Check if variable is a `this` parameter. + * @param {Object} variable The variable to check + * @returns {boolean} Whether the variable is a this parameter + */ + function isThisParam(variable) { + return variable.name === "this"; + } + + /** + * Checks if type and value shadows each other + * @param {Object} variable The variable to check + * @param {Object} shadowedVariable The shadowed variable + * @returns {boolean} Whether it's a type/value shadow case to ignore + */ + function isTypeValueShadow(variable, shadowedVariable) { + if (ignoreTypeValueShadow !== true) { + return false; + } + + if (!("isValueVariable" in variable)) { + return false; + } + + const firstDefinition = shadowedVariable.defs[0]; + + // Check if shadowedVariable is a type import + const isTypeImport = + firstDefinition && + firstDefinition.parent?.type === "ImportDeclaration" && + (firstDefinition.parent.importKind === "type" || + firstDefinition.parent.specifiers.some( + s => s.importKind === "type", + )); + + const isShadowedValue = + !firstDefinition || + (isTypeImport ? false : shadowedVariable.isValueVariable); + + return variable.isValueVariable !== isShadowedValue; + } + + /** + * Checks if it's a function type parameter shadow + * @param {Object} variable The variable to check + * @returns {boolean} Whether it's a function type parameter shadow case to ignore + */ + function isFunctionTypeParameterNameValueShadow(variable) { + if (ignoreFunctionTypeParameterNameValueShadow !== true) { + return false; + } + + return variable.defs.some(def => + ALLOWED_FUNCTION_VARIABLE_DEF_TYPES.has(def.node.type), + ); + } + + /** + * Checks if the variable is a generic of a static method + * @param {Object} variable The variable to check + * @returns {boolean} Whether the variable is a generic of a static method + */ + function isTypeParameterOfStaticMethod(variable) { + const typeParameter = variable.identifiers[0].parent; + const typeParameterDecl = typeParameter.parent; + if (typeParameterDecl.type !== "TSTypeParameterDeclaration") { + return false; + } + const functionExpr = typeParameterDecl.parent; + const methodDefinition = functionExpr.parent; + return methodDefinition.static; + } + + /** + * Checks for static method generic shadowing class generic + * @param {Object} variable The variable to check + * @returns {boolean} Whether it's a static method generic shadowing class generic + */ + function isGenericOfAStaticMethodShadow(variable) { + return isTypeParameterOfStaticMethod(variable); + } + + /** + * Checks whether or not a given location is inside of the range of a given node. + * @param {ASTNode} node An node to check. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of the range of the node. + */ + function isInRange(node, location) { + return ( + node && node.range[0] <= location && location <= node.range[1] + ); + } + + /** + * Searches from the current node through its ancestry to find a matching node. + * @param {ASTNode} node a node to get. + * @param {(node: ASTNode) => boolean} match a callback that checks whether or not the node verifies its condition or not. + * @returns {ASTNode|null} the matching node. + */ + function findSelfOrAncestor(node, match) { + let currentNode = node; + + while (currentNode && !match(currentNode)) { + currentNode = currentNode.parent; + } + return currentNode; + } + + /** + * Finds function's outer scope. + * @param {Scope} scope Function's own scope. + * @returns {Scope} Function's outer scope. + */ + function getOuterScope(scope) { + const upper = scope.upper; + + if (upper && upper.type === "function-expression-name") { + return upper.upper; + } + return upper; + } + + /** + * Checks if a variable and a shadowedVariable have the same init pattern ancestor. + * @param {Object} variable a variable to check. + * @param {Object} shadowedVariable a shadowedVariable to check. + * @returns {boolean} Whether or not the variable and the shadowedVariable have the same init pattern ancestor. + */ + function isInitPatternNode(variable, shadowedVariable) { + const outerDef = shadowedVariable.defs[0]; + + if (!outerDef) { + return false; + } + + const { variableScope } = variable.scope; + + if ( + !( + FUNC_EXPR_NODE_TYPES.has(variableScope.block.type) && + getOuterScope(variableScope) === shadowedVariable.scope + ) + ) { + return false; + } + + const fun = variableScope.block; + const { parent } = fun; + + const callExpression = findSelfOrAncestor(parent, node => + CALL_EXPR_NODE_TYPE.has(node.type), + ); + + if (!callExpression) { + return false; + } + + let node = outerDef.name; + const location = callExpression.range[1]; + + while (node) { + if (node.type === "VariableDeclarator") { + if (isInRange(node.init, location)) { + return true; + } + if ( + FOR_IN_OF_TYPE.test(node.parent.parent.type) && + isInRange(node.parent.parent.right, location) + ) { + return true; + } + break; + } else if (node.type === "AssignmentPattern") { + if (isInRange(node.right, location)) { + return true; + } + } else if (SENTINEL_TYPE.test(node.type)) { + break; + } + + node = node.parent; + } + + return false; + } + + /** + * Check if variable name is allowed. + * @param {ASTNode} variable The variable to check. + * @returns {boolean} Whether or not the variable name is allowed. + */ + function isAllowed(variable) { + return allow.includes(variable.name); + } + + /** + * Checks if a variable of the class name in the class scope of ClassDeclaration. + * + * ClassDeclaration creates two variables of its name into its outer scope and its class scope. + * So we should ignore the variable in the class scope. + * @param {Object} variable The variable to check. + * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration. + */ + function isDuplicatedClassNameVariable(variable) { + const block = variable.scope.block; + + return ( + block.type === "ClassDeclaration" && + block.id === variable.identifiers[0] + ); + } + + /** + * Checks if a variable is inside the initializer of scopeVar. + * + * To avoid reporting at declarations such as `var a = function a() {};`. + * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`. + * @param {Object} variable The variable to check. + * @param {Object} scopeVar The scope variable to look for. + * @returns {boolean} Whether or not the variable is inside initializer of scopeVar. + */ + function isOnInitializer(variable, scopeVar) { + const outerScope = scopeVar.scope; + const outerDef = scopeVar.defs[0]; + const outer = outerDef && outerDef.parent && outerDef.parent.range; + const innerScope = variable.scope; + const innerDef = variable.defs[0]; + const inner = innerDef && innerDef.name.range; + + return ( + outer && + inner && + outer[0] < inner[0] && + inner[1] < outer[1] && + ((innerDef.type === "FunctionName" && + innerDef.node.type === "FunctionExpression") || + innerDef.node.type === "ClassExpression") && + outerScope === innerScope.upper + ); + } + + /** + * Get a range of a variable's identifier node. + * @param {Object} variable The variable to get. + * @returns {Array|undefined} The range of the variable's identifier node. + */ + function getNameRange(variable) { + const def = variable.defs[0]; + + return def && def.name.range; + } + + /** + * Get declared line and column of a variable. + * @param {eslint-scope.Variable} variable The variable to get. + * @returns {Object} The declared line and column of the variable. + */ + function getDeclaredLocation(variable) { + const identifier = variable.identifiers[0]; + let obj; + + if (identifier) { + obj = { + global: false, + line: identifier.loc.start.line, + column: identifier.loc.start.column + 1, + }; + } else { + obj = { + global: true, + }; + } + return obj; + } + + /** + * Checks if a variable is in TDZ of scopeVar. + * @param {Object} variable The variable to check. + * @param {Object} scopeVar The variable of TDZ. + * @returns {boolean} Whether or not the variable is in TDZ of scopeVar. + */ + function isInTdz(variable, scopeVar) { + const outerDef = scopeVar.defs[0]; + const inner = getNameRange(variable); + const outer = getNameRange(scopeVar); + + if (!outer || inner[1] >= outer[0]) { + return false; + } + + if (hoist === "types") { + return !TYPES_HOISTED_NODES.has(outerDef.node.type); + } + + if (hoist === "functions-and-types") { + return ( + outerDef.node.type !== "FunctionDeclaration" && + !TYPES_HOISTED_NODES.has(outerDef.node.type) + ); + } + + return ( + inner && + outer && + inner[1] < outer[0] && + // Excepts FunctionDeclaration if is {"hoist":"function"}. + (hoist !== "functions" || + !outerDef || + outerDef.node.type !== "FunctionDeclaration") + ); + } + + /** + * Checks if the initialization of a variable has the declare modifier in a + * definition file. + * @param {Object} variable The variable to check + * @returns {boolean} Whether the variable is declared in a definition file + */ + function isDeclareInDTSFile(variable) { + const fileName = context.filename; + if ( + !fileName.endsWith(".d.ts") && + !fileName.endsWith(".d.cts") && + !fileName.endsWith(".d.mts") + ) { + return false; + } + return variable.defs.some( + def => + (def.type === "Variable" && def.parent.declare) || + (def.type === "ClassName" && def.node.declare) || + (def.type === "TSEnumName" && def.node.declare) || + (def.type === "TSModuleName" && def.node.declare), + ); + } + + /** + * Checks if a variable is a duplicate of an enum name in the enum scope + * @param {Object} variable The variable to check + * @returns {boolean} Whether it's a duplicate enum name variable + */ + function isDuplicatedEnumNameVariable(variable) { + const block = variable.scope.block; + + return ( + block.type === "TSEnumDeclaration" && + block.id === variable.identifiers[0] + ); + } + + /** + * Check if this is an external module declaration merging with a type import + * @param {Scope} scope Current scope + * @param {Object} variable Current variable + * @param {Object} shadowedVariable Shadowed variable + * @returns {boolean} Whether it's an external declaration merging + */ + function isExternalDeclarationMerging( + scope, + variable, + shadowedVariable, + ) { + const firstDefinition = shadowedVariable.defs[0]; + + if (!firstDefinition || !firstDefinition.parent) { + return false; + } + + // Check if the shadowed variable is a type import + const isTypeImport = + firstDefinition.parent.type === "ImportDeclaration" && + (firstDefinition.parent.importKind === "type" || + firstDefinition.parent.specifiers?.some( + s => + s.type === "ImportSpecifier" && + s.importKind === "type" && + s.local.name === shadowedVariable.name, + )); + + if (!isTypeImport) { + return false; + } + + // Check if the current variable is within a module declaration + const moduleDecl = findSelfOrAncestor( + variable.identifiers[0]?.parent, + node => node.type === "TSModuleDeclaration", + ); + + if (!moduleDecl) { + return false; + } + + /* + * Module declaration merging should only happen within the same module + * Check if the module name matches the import source + */ + const importSource = firstDefinition.parent.source.value; + const moduleName = + moduleDecl.id.type === "Literal" + ? moduleDecl.id.value + : moduleDecl.id.name; + + return importSource === moduleName; + } + + /** + * Checks the current context for shadowed variables. + * @param {Scope} scope Fixme + * @returns {void} + */ + function checkForShadows(scope) { + // ignore global augmentation + if (isGlobalAugmentation(scope)) { + return; + } + + const variables = scope.variables; + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + + // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration. + if ( + variable.identifiers.length === 0 || + isDuplicatedClassNameVariable(variable) || + isDuplicatedEnumNameVariable(variable) || + isAllowed(variable) || + isDeclareInDTSFile(variable) || + isThisParam(variable) + ) { + continue; + } + + // Gets shadowed variable. + const shadowed = astUtils.getVariableByName( + scope.upper, + variable.name, + ); + + if ( + shadowed && + (shadowed.identifiers.length > 0 || + (builtinGlobals && "writeable" in shadowed)) && + !isOnInitializer(variable, shadowed) && + !( + ignoreOnInitialization && + isInitPatternNode(variable, shadowed) + ) && + !(hoist !== "all" && isInTdz(variable, shadowed)) && + !isTypeValueShadow(variable, shadowed) && + !isFunctionTypeParameterNameValueShadow(variable) && + !isGenericOfAStaticMethodShadow(variable, shadowed) && + !isExternalDeclarationMerging(scope, variable, shadowed) + ) { + const location = getDeclaredLocation(shadowed); + const messageId = location.global + ? "noShadowGlobal" + : "noShadow"; + const data = { name: variable.name }; + + if (!location.global) { + data.shadowedLine = location.line; + data.shadowedColumn = location.column; + } + context.report({ + node: variable.identifiers[0], + messageId, + data, + }); + } + } + } + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + const stack = globalScope.childScopes.slice(); + + while (stack.length) { + const scope = stack.pop(); + + stack.push(...scope.childScopes); + checkForShadows(scope); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-spaced-func.js b/node_modules/eslint/lib/rules/no-spaced-func.js new file mode 100644 index 00000000..3452219c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-spaced-func.js @@ -0,0 +1,105 @@ +/** + * @fileoverview Rule to check that spaced function application + * @author Matt DuVall + * @deprecated in ESLint v3.3.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: + "Disallow spacing between function identifiers and their applications (deprecated)", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-spaced-func", + }, + + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2016/08/eslint-v3.3.0-released/#deprecated-rules", + deprecatedSince: "3.3.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "function-call-spacing", + url: "https://eslint.style/rules/js/function-call-spacing", + }, + }, + ], + }, + + fixable: "whitespace", + schema: [], + + messages: { + noSpacedFunction: + "Unexpected space between function name and paren.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Check if open space is present in a function name + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function detectOpenSpaces(node) { + const lastCalleeToken = sourceCode.getLastToken(node.callee); + let prevToken = lastCalleeToken, + parenToken = sourceCode.getTokenAfter(lastCalleeToken); + + // advances to an open parenthesis. + while ( + parenToken && + parenToken.range[1] < node.range[1] && + parenToken.value !== "(" + ) { + prevToken = parenToken; + parenToken = sourceCode.getTokenAfter(parenToken); + } + + // look for a space between the callee and the open paren + if ( + parenToken && + parenToken.range[1] < node.range[1] && + sourceCode.isSpaceBetweenTokens(prevToken, parenToken) + ) { + context.report({ + node, + loc: lastCalleeToken.loc.start, + messageId: "noSpacedFunction", + fix(fixer) { + return fixer.removeRange([ + prevToken.range[1], + parenToken.range[0], + ]); + }, + }); + } + } + + return { + CallExpression: detectOpenSpaces, + NewExpression: detectOpenSpaces, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-sparse-arrays.js b/node_modules/eslint/lib/rules/no-sparse-arrays.js new file mode 100644 index 00000000..f805ecef --- /dev/null +++ b/node_modules/eslint/lib/rules/no-sparse-arrays.js @@ -0,0 +1,68 @@ +/** + * @fileoverview Disallow sparse arrays + * @author Nicholas C. Zakas + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow sparse arrays", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-sparse-arrays", + }, + + schema: [], + + messages: { + unexpectedSparseArray: "Unexpected comma in middle of array.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ArrayExpression(node) { + if (!node.elements.includes(null)) { + return; + } + + const { sourceCode } = context; + let commaToken; + + for (const [index, element] of node.elements.entries()) { + if (index === node.elements.length - 1 && element) { + return; + } + + commaToken = sourceCode.getTokenAfter( + element ?? commaToken ?? sourceCode.getFirstToken(node), + astUtils.isCommaToken, + ); + + if (element) { + continue; + } + + context.report({ + node, + loc: commaToken.loc, + messageId: "unexpectedSparseArray", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-sync.js b/node_modules/eslint/lib/rules/no-sync.js new file mode 100644 index 00000000..aee74aa6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-sync.js @@ -0,0 +1,81 @@ +/** + * @fileoverview Rule to check for properties whose identifier ends with the string Sync + * @author Matt DuVall + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: null, + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-sync", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-sync.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow synchronous methods", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-sync", + }, + + schema: [ + { + type: "object", + properties: { + allowAtRootLevel: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + noSync: "Unexpected sync method: '{{propertyName}}'.", + }, + }, + + create(context) { + const selector = + context.options[0] && context.options[0].allowAtRootLevel + ? ":function MemberExpression[property.name=/.*Sync$/]" + : "MemberExpression[property.name=/.*Sync$/]"; + + return { + [selector](node) { + context.report({ + node, + messageId: "noSync", + data: { + propertyName: node.property.name, + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-tabs.js b/node_modules/eslint/lib/rules/no-tabs.js new file mode 100644 index 00000000..555a31bc --- /dev/null +++ b/node_modules/eslint/lib/rules/no-tabs.js @@ -0,0 +1,110 @@ +/** + * @fileoverview Rule to check for tabs inside a file + * @author Gyandeep Singh + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const tabRegex = /\t+/gu; +const anyNonWhitespaceRegex = /\S/u; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-tabs", + url: "https://eslint.style/rules/js/no-tabs", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow all tabs", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-tabs", + }, + schema: [ + { + type: "object", + properties: { + allowIndentationTabs: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedTab: "Unexpected tab character.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const allowIndentationTabs = + context.options && + context.options[0] && + context.options[0].allowIndentationTabs; + + return { + Program(node) { + sourceCode.getLines().forEach((line, index) => { + let match; + + while ((match = tabRegex.exec(line)) !== null) { + if ( + allowIndentationTabs && + !anyNonWhitespaceRegex.test( + line.slice(0, match.index), + ) + ) { + continue; + } + + context.report({ + node, + loc: { + start: { + line: index + 1, + column: match.index, + }, + end: { + line: index + 1, + column: match.index + match[0].length, + }, + }, + messageId: "unexpectedTab", + }); + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-template-curly-in-string.js b/node_modules/eslint/lib/rules/no-template-curly-in-string.js new file mode 100644 index 00000000..901e1aea --- /dev/null +++ b/node_modules/eslint/lib/rules/no-template-curly-in-string.js @@ -0,0 +1,45 @@ +/** + * @fileoverview Warn when using template string syntax in regular strings + * @author Jeroen Engels + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow template literal placeholder syntax in regular strings", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-template-curly-in-string", + }, + + schema: [], + + messages: { + unexpectedTemplateExpression: + "Unexpected template string expression.", + }, + }, + + create(context) { + const regex = /\$\{[^}]+\}/u; + + return { + Literal(node) { + if (typeof node.value === "string" && regex.test(node.value)) { + context.report({ + node, + messageId: "unexpectedTemplateExpression", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-ternary.js b/node_modules/eslint/lib/rules/no-ternary.js new file mode 100644 index 00000000..f58136d5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-ternary.js @@ -0,0 +1,38 @@ +/** + * @fileoverview Rule to flag use of ternary operators. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow ternary operators", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-ternary", + }, + + schema: [], + + messages: { + noTernaryOperator: "Ternary operator used.", + }, + }, + + create(context) { + return { + ConditionalExpression(node) { + context.report({ node, messageId: "noTernaryOperator" }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-this-before-super.js b/node_modules/eslint/lib/rules/no-this-before-super.js new file mode 100644 index 00000000..16d049c4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-this-before-super.js @@ -0,0 +1,365 @@ +/** + * @fileoverview A rule to disallow using `this`/`super` before `super()`. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a constructor. + * @param {ASTNode} node A node to check. This node type is one of + * `Program`, `FunctionDeclaration`, `FunctionExpression`, and + * `ArrowFunctionExpression`. + * @returns {boolean} `true` if the node is a constructor. + */ +function isConstructorFunction(node) { + return ( + node.type === "FunctionExpression" && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor" + ); +} + +/* + * Information for each code path segment. + * - superCalled: The flag which shows `super()` called in all code paths. + * - invalidNodes: The array of invalid ThisExpression and Super nodes. + */ +/** + * + */ +class SegmentInfo { + /** + * Indicates whether `super()` is called in all code paths. + * @type {boolean} + */ + superCalled = false; + + /** + * The array of invalid ThisExpression and Super nodes. + * @type {ASTNode[]} + */ + invalidNodes = []; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow `this`/`super` before calling `super()` in constructors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-this-before-super", + }, + + schema: [], + + messages: { + noBeforeSuper: "'{{kind}}' is not allowed before 'super()'.", + }, + }, + + create(context) { + /* + * Information for each constructor. + * - upper: Information of the upper constructor. + * - hasExtends: A flag which shows whether the owner class has a valid + * `extends` part. + * - scope: The scope of the owner class. + * - codePath: The code path of this constructor. + */ + let funcInfo = null; + + /** @type {Record} */ + let segInfoMap = Object.create(null); + + /** + * Gets whether or not `super()` is called in a given code path segment. + * @param {CodePathSegment} segment A code path segment to get. + * @returns {boolean} `true` if `super()` is called. + */ + function isCalled(segment) { + return !segment.reachable || segInfoMap[segment.id]?.superCalled; + } + + /** + * Checks whether or not this is in a constructor. + * @returns {boolean} `true` if this is in a constructor. + */ + function isInConstructorOfDerivedClass() { + return Boolean( + funcInfo && funcInfo.isConstructor && funcInfo.hasExtends, + ); + } + + /** + * Determines if every segment in a set has been called. + * @param {Set} segments The segments to search. + * @returns {boolean} True if every segment has been called; false otherwise. + */ + function isEverySegmentCalled(segments) { + for (const segment of segments) { + if (!isCalled(segment)) { + return false; + } + } + + return true; + } + + /** + * Checks whether or not this is before `super()` is called. + * @returns {boolean} `true` if this is before `super()` is called. + */ + function isBeforeCallOfSuper() { + return ( + isInConstructorOfDerivedClass() && + !isEverySegmentCalled(funcInfo.currentSegments) + ); + } + + /** + * Sets a given node as invalid. + * @param {ASTNode} node A node to set as invalid. This is one of + * a ThisExpression and a Super. + * @returns {void} + */ + function setInvalid(node) { + const segments = funcInfo.currentSegments; + + for (const segment of segments) { + if (segment.reachable) { + segInfoMap[segment.id].invalidNodes.push(node); + } + } + } + + /** + * Sets the current segment as `super` was called. + * @returns {void} + */ + function setSuperCalled() { + const segments = funcInfo.currentSegments; + + for (const segment of segments) { + if (segment.reachable) { + segInfoMap[segment.id].superCalled = true; + } + } + } + + return { + /** + * Adds information of a constructor into the stack. + * @param {CodePath} codePath A code path which was started. + * @param {ASTNode} node The current node. + * @returns {void} + */ + onCodePathStart(codePath, node) { + if (isConstructorFunction(node)) { + // Class > ClassBody > MethodDefinition > FunctionExpression + const classNode = node.parent.parent.parent; + + funcInfo = { + upper: funcInfo, + isConstructor: true, + hasExtends: Boolean( + classNode.superClass && + !astUtils.isNullOrUndefined( + classNode.superClass, + ), + ), + codePath, + currentSegments: new Set(), + }; + } else { + funcInfo = { + upper: funcInfo, + isConstructor: false, + hasExtends: false, + codePath, + currentSegments: new Set(), + }; + } + }, + + /** + * Removes the top of stack item. + * + * And this traverses all segments of this code path then reports every + * invalid node. + * @param {CodePath} codePath A code path which was ended. + * @returns {void} + */ + onCodePathEnd(codePath) { + const isDerivedClass = funcInfo.hasExtends; + + funcInfo = funcInfo.upper; + if (!isDerivedClass) { + return; + } + + /** + * A collection of nodes to avoid duplicate reports. + * @type {Set} + */ + const reported = new Set(); + + codePath.traverseSegments((segment, controller) => { + const info = segInfoMap[segment.id]; + const invalidNodes = info.invalidNodes.filter( + /* + * Avoid duplicate reports. + * When there is a `finally`, invalidNodes may contain already reported node. + */ + node => !reported.has(node), + ); + + for (const invalidNode of invalidNodes) { + reported.add(invalidNode); + + context.report({ + messageId: "noBeforeSuper", + node: invalidNode, + data: { + kind: + invalidNode.type === "Super" + ? "super" + : "this", + }, + }); + } + + if (info.superCalled) { + controller.skip(); + } + }); + }, + + /** + * Initialize information of a given code path segment. + * @param {CodePathSegment} segment A code path segment to initialize. + * @returns {void} + */ + onCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + + if (!isInConstructorOfDerivedClass()) { + return; + } + + // Initialize info. + segInfoMap[segment.id] = { + superCalled: + segment.prevSegments.length > 0 && + segment.prevSegments.every(isCalled), + invalidNodes: [], + }; + }, + + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + /** + * Update information of the code path segment when a code path was + * looped. + * @param {CodePathSegment} fromSegment The code path segment of the + * end of a loop. + * @param {CodePathSegment} toSegment A code path segment of the head + * of a loop. + * @returns {void} + */ + onCodePathSegmentLoop(fromSegment, toSegment) { + if (!isInConstructorOfDerivedClass()) { + return; + } + + // Update information inside of the loop. + funcInfo.codePath.traverseSegments( + { first: toSegment, last: fromSegment }, + (segment, controller) => { + const info = + segInfoMap[segment.id] ?? new SegmentInfo(); + + if (info.superCalled) { + controller.skip(); + } else if ( + segment.prevSegments.length > 0 && + segment.prevSegments.every(isCalled) + ) { + info.superCalled = true; + } + + segInfoMap[segment.id] = info; + }, + ); + }, + + /** + * Reports if this is before `super()`. + * @param {ASTNode} node A target node. + * @returns {void} + */ + ThisExpression(node) { + if (isBeforeCallOfSuper()) { + setInvalid(node); + } + }, + + /** + * Reports if this is before `super()`. + * @param {ASTNode} node A target node. + * @returns {void} + */ + Super(node) { + if (!astUtils.isCallee(node) && isBeforeCallOfSuper()) { + setInvalid(node); + } + }, + + /** + * Marks `super()` called. + * @param {ASTNode} node A target node. + * @returns {void} + */ + "CallExpression:exit"(node) { + if (node.callee.type === "Super" && isBeforeCallOfSuper()) { + setSuperCalled(); + } + }, + + /** + * Resets state. + * @returns {void} + */ + "Program:exit"() { + segInfoMap = Object.create(null); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-throw-literal.js b/node_modules/eslint/lib/rules/no-throw-literal.js new file mode 100644 index 00000000..877224be --- /dev/null +++ b/node_modules/eslint/lib/rules/no-throw-literal.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Rule to restrict what can be thrown as an exception. + * @author Dieter Oberkofler + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow throwing literals as exceptions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-throw-literal", + }, + + schema: [], + + messages: { + object: "Expected an error object to be thrown.", + undef: "Do not throw undefined.", + }, + }, + + create(context) { + return { + ThrowStatement(node) { + if (!astUtils.couldBeError(node.argument)) { + context.report({ node, messageId: "object" }); + } else if (node.argument.type === "Identifier") { + if (node.argument.name === "undefined") { + context.report({ node, messageId: "undef" }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-trailing-spaces.js b/node_modules/eslint/lib/rules/no-trailing-spaces.js new file mode 100644 index 00000000..28038e2a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-trailing-spaces.js @@ -0,0 +1,226 @@ +/** + * @fileoverview Disallow trailing spaces at the end of lines. + * @author Nodeca Team + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceLocation, SourceRange } from "@eslint/core"; + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-trailing-spaces", + url: "https://eslint.style/rules/js/no-trailing-spaces", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow trailing whitespace at the end of lines", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-trailing-spaces", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + skipBlankLines: { + type: "boolean", + default: false, + }, + ignoreComments: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + trailingSpace: "Trailing spaces not allowed.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const BLANK_CLASS = "[ \t\u00a0\u2000-\u200b\u3000]", + SKIP_BLANK = `^${BLANK_CLASS}*$`, + NONBLANK = `${BLANK_CLASS}+$`; + + const options = context.options[0] || {}, + skipBlankLines = options.skipBlankLines || false, + ignoreComments = options.ignoreComments || false; + + /** + * Report the error message + * @param {ASTNode} node node to report + * @param {SourceLocation} location range information + * @param {SourceRange} fixRange Range based on the whole program + * @returns {void} + */ + function report(node, location, fixRange) { + /* + * Passing node is a bit dirty, because message data will contain big + * text in `source`. But... who cares :) ? + * One more kludge will not make worse the bloody wizardry of this + * plugin. + */ + context.report({ + node, + loc: location, + messageId: "trailingSpace", + fix(fixer) { + return fixer.removeRange(fixRange); + }, + }); + } + + /** + * Given a list of comment nodes, return the line numbers for those comments. + * @param {Array} comments An array of comment nodes. + * @returns {number[]} An array of line numbers containing comments. + */ + function getCommentLineNumbers(comments) { + const lines = new Set(); + + comments.forEach(comment => { + const endLine = + comment.type === "Block" + ? comment.loc.end.line - 1 + : comment.loc.end.line; + + for (let i = comment.loc.start.line; i <= endLine; i++) { + lines.add(i); + } + }); + + return lines; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkTrailingSpaces(node) { + /* + * Let's hack. Since Espree does not return whitespace nodes, + * fetch the source code and do matching via regexps. + */ + + const re = new RegExp(NONBLANK, "u"), + skipMatch = new RegExp(SKIP_BLANK, "u"), + lines = sourceCode.lines, + linebreaks = sourceCode + .getText() + .match(astUtils.createGlobalLinebreakMatcher()), + comments = sourceCode.getAllComments(), + commentLineNumbers = getCommentLineNumbers(comments); + + let totalLength = 0; + + for (let i = 0, ii = lines.length; i < ii; i++) { + const lineNumber = i + 1; + + /* + * Always add linebreak length to line length to accommodate for line break (\n or \r\n) + * Because during the fix time they also reserve one spot in the array. + * Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF) + */ + const linebreakLength = + linebreaks && linebreaks[i] ? linebreaks[i].length : 1; + const lineLength = lines[i].length + linebreakLength; + + const matches = re.exec(lines[i]); + + if (matches) { + const location = { + start: { + line: lineNumber, + column: matches.index, + }, + end: { + line: lineNumber, + column: lineLength - linebreakLength, + }, + }; + + const rangeStart = totalLength + location.start.column; + const rangeEnd = totalLength + location.end.column; + const containingNode = + sourceCode.getNodeByRangeIndex(rangeStart); + + if ( + containingNode && + containingNode.type === "TemplateElement" && + rangeStart > containingNode.parent.range[0] && + rangeEnd < containingNode.parent.range[1] + ) { + totalLength += lineLength; + continue; + } + + /* + * If the line has only whitespace, and skipBlankLines + * is true, don't report it + */ + if (skipBlankLines && skipMatch.test(lines[i])) { + totalLength += lineLength; + continue; + } + + const fixRange = [rangeStart, rangeEnd]; + + if ( + !ignoreComments || + !commentLineNumbers.has(lineNumber) + ) { + report(node, location, fixRange); + } + } + + totalLength += lineLength; + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unassigned-vars.js b/node_modules/eslint/lib/rules/no-unassigned-vars.js new file mode 100644 index 00000000..3fcd8395 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unassigned-vars.js @@ -0,0 +1,80 @@ +/** + * @fileoverview Rule to flag variables that are never assigned + * @author Jacob Bandes-Storch + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: + "Disallow `let` or `var` variables that are read but never assigned", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unassigned-vars", + }, + + schema: [], + messages: { + unassigned: + "'{{name}}' is always 'undefined' because it's never assigned.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let insideDeclareModule = false; + + return { + "TSModuleDeclaration[declare=true]"() { + insideDeclareModule = true; + }, + "TSModuleDeclaration[declare=true]:exit"() { + insideDeclareModule = false; + }, + VariableDeclarator(node) { + /** @type {import('estree').VariableDeclaration} */ + const declaration = node.parent; + const shouldSkip = + node.init || + node.id.type !== "Identifier" || + declaration.kind === "const" || + declaration.declare || + insideDeclareModule; + if (shouldSkip) { + return; + } + const [variable] = sourceCode.getDeclaredVariables(node); + if (!variable) { + return; + } + let hasRead = false; + for (const reference of variable.references) { + if (reference.isWrite()) { + return; + } + if (reference.isRead()) { + hasRead = true; + } + } + if (!hasRead) { + // Variables that are never read should be flagged by no-unused-vars instead + return; + } + context.report({ + node, + messageId: "unassigned", + data: { name: node.id.name }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-undef-init.js b/node_modules/eslint/lib/rules/no-undef-init.js new file mode 100644 index 00000000..9f8153d3 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-undef-init.js @@ -0,0 +1,91 @@ +/** + * @fileoverview Rule to flag when initializing to undefined + * @author Ilya Volodin + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow initializing variables to `undefined`", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-undef-init", + }, + + schema: [], + fixable: "code", + + messages: { + unnecessaryUndefinedInit: + "It's not necessary to initialize '{{name}}' to undefined.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + VariableDeclarator(node) { + const name = sourceCode.getText(node.id), + init = node.init && node.init.name, + scope = sourceCode.getScope(node), + undefinedVar = astUtils.getVariableByName( + scope, + "undefined", + ), + shadowed = undefinedVar && undefinedVar.defs.length > 0, + lastToken = sourceCode.getLastToken(node); + + if ( + init === "undefined" && + node.parent.kind !== "const" && + !shadowed + ) { + context.report({ + node, + messageId: "unnecessaryUndefinedInit", + data: { name }, + fix(fixer) { + if (node.parent.kind === "var") { + return null; + } + + if ( + node.id.type === "ArrayPattern" || + node.id.type === "ObjectPattern" + ) { + // Don't fix destructuring assignment to `undefined`. + return null; + } + + if ( + sourceCode.commentsExistBetween( + node.id, + lastToken, + ) + ) { + return null; + } + + return fixer.removeRange([ + node.id.range[1], + node.range[1], + ]); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-undef.js b/node_modules/eslint/lib/rules/no-undef.js new file mode 100644 index 00000000..fbda8773 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-undef.js @@ -0,0 +1,84 @@ +/** + * @fileoverview Rule to flag references to undeclared variables. + * @author Mark Macdonald + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks if the given node is the argument of a typeof operator. + * @param {ASTNode} node The AST node being checked. + * @returns {boolean} Whether or not the node is the argument of a typeof operator. + */ +function hasTypeOfOperator(node) { + const parent = node.parent; + + return parent.type === "UnaryExpression" && parent.operator === "typeof"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + typeof: false, + }, + ], + + docs: { + description: + "Disallow the use of undeclared variables unless mentioned in `/*global */` comments", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-undef", + }, + + schema: [ + { + type: "object", + properties: { + typeof: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + undef: "'{{name}}' is not defined.", + }, + }, + + create(context) { + const [{ typeof: considerTypeOf }] = context.options; + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + globalScope.through.forEach(ref => { + const identifier = ref.identifier; + + if (!considerTypeOf && hasTypeOfOperator(identifier)) { + return; + } + + context.report({ + node: identifier, + messageId: "undef", + data: identifier, + }); + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-undefined.js b/node_modules/eslint/lib/rules/no-undefined.js new file mode 100644 index 00000000..044efeab --- /dev/null +++ b/node_modules/eslint/lib/rules/no-undefined.js @@ -0,0 +1,85 @@ +/** + * @fileoverview Rule to flag references to the undefined variable. + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `undefined` as an identifier", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-undefined", + }, + + schema: [], + + messages: { + unexpectedUndefined: "Unexpected use of undefined.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Report an invalid "undefined" identifier node. + * @param {ASTNode} node The node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "unexpectedUndefined", + }); + } + + /** + * Checks the given scope for references to `undefined` and reports + * all references found. + * @param {eslint-scope.Scope} scope The scope to check. + * @returns {void} + */ + function checkScope(scope) { + const undefinedVar = scope.set.get("undefined"); + + if (!undefinedVar) { + return; + } + + const references = undefinedVar.references; + + const defs = undefinedVar.defs; + + // Report non-initializing references (those are covered in defs below) + references + .filter(ref => !ref.init) + .forEach(ref => report(ref.identifier)); + + defs.forEach(def => report(def.name)); + } + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + const stack = [globalScope]; + + while (stack.length) { + const scope = stack.pop(); + + stack.push(...scope.childScopes); + checkScope(scope); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-underscore-dangle.js b/node_modules/eslint/lib/rules/no-underscore-dangle.js new file mode 100644 index 00000000..24b72370 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-underscore-dangle.js @@ -0,0 +1,383 @@ +/** + * @fileoverview Rule to flag dangling underscores in variable declarations. + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allow: [], + allowAfterSuper: false, + allowAfterThis: false, + allowAfterThisConstructor: false, + allowFunctionParams: true, + allowInArrayDestructuring: true, + allowInObjectDestructuring: true, + enforceInClassFields: false, + enforceInMethodNames: false, + }, + ], + + docs: { + description: "Disallow dangling underscores in identifiers", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-underscore-dangle", + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { + type: "string", + }, + }, + allowAfterThis: { + type: "boolean", + }, + allowAfterSuper: { + type: "boolean", + }, + allowAfterThisConstructor: { + type: "boolean", + }, + enforceInMethodNames: { + type: "boolean", + }, + allowFunctionParams: { + type: "boolean", + }, + enforceInClassFields: { + type: "boolean", + }, + allowInArrayDestructuring: { + type: "boolean", + }, + allowInObjectDestructuring: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedUnderscore: + "Unexpected dangling '_' in '{{identifier}}'.", + }, + }, + + create(context) { + const [ + { + allow, + allowAfterSuper, + allowAfterThis, + allowAfterThisConstructor, + allowFunctionParams, + allowInArrayDestructuring, + allowInObjectDestructuring, + enforceInClassFields, + enforceInMethodNames, + }, + ] = context.options; + const sourceCode = context.sourceCode; + + //------------------------------------------------------------------------- + // Helpers + //------------------------------------------------------------------------- + + /** + * Check if identifier is present inside the allowed option + * @param {string} identifier name of the node + * @returns {boolean} true if its is present + * @private + */ + function isAllowed(identifier) { + return allow.includes(identifier); + } + + /** + * Check if identifier has a dangling underscore + * @param {string} identifier name of the node + * @returns {boolean} true if its is present + * @private + */ + function hasDanglingUnderscore(identifier) { + const len = identifier.length; + + return ( + identifier !== "_" && + (identifier[0] === "_" || identifier[len - 1] === "_") + ); + } + + /** + * Check if identifier is a special case member expression + * @param {string} identifier name of the node + * @returns {boolean} true if its is a special case + * @private + */ + function isSpecialCaseIdentifierForMemberExpression(identifier) { + return identifier === "__proto__"; + } + + /** + * Check if identifier is a special case variable expression + * @param {string} identifier name of the node + * @returns {boolean} true if its is a special case + * @private + */ + function isSpecialCaseIdentifierInVariableExpression(identifier) { + // Checks for the underscore library usage here + return identifier === "_"; + } + + /** + * Check if a node is a member reference of this.constructor + * @param {ASTNode} node node to evaluate + * @returns {boolean} true if it is a reference on this.constructor + * @private + */ + function isThisConstructorReference(node) { + return ( + node.object.type === "MemberExpression" && + node.object.property.name === "constructor" && + node.object.object.type === "ThisExpression" + ); + } + + /** + * Check if function parameter has a dangling underscore. + * @param {ASTNode} node function node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInFunctionParameters(node) { + if (!allowFunctionParams) { + node.params.forEach(param => { + const { type } = param; + let nodeToCheck; + + if (type === "RestElement") { + nodeToCheck = param.argument; + } else if (type === "AssignmentPattern") { + nodeToCheck = param.left; + } else { + nodeToCheck = param; + } + + if (nodeToCheck.type === "Identifier") { + const identifier = nodeToCheck.name; + + if ( + hasDanglingUnderscore(identifier) && + !isAllowed(identifier) + ) { + context.report({ + node: param, + messageId: "unexpectedUnderscore", + data: { + identifier, + }, + }); + } + } + }); + } + } + + /** + * Check if function has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInFunction(node) { + if (node.type === "FunctionDeclaration" && node.id) { + const identifier = node.id.name; + + if ( + typeof identifier !== "undefined" && + hasDanglingUnderscore(identifier) && + !isAllowed(identifier) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier, + }, + }); + } + } + checkForDanglingUnderscoreInFunctionParameters(node); + } + + /** + * Check if variable expression has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInVariableExpression(node) { + sourceCode.getDeclaredVariables(node).forEach(variable => { + const definition = variable.defs.find(def => def.node === node); + const identifierNode = definition.name; + const identifier = identifierNode.name; + let parent = identifierNode.parent; + + while ( + ![ + "VariableDeclarator", + "ArrayPattern", + "ObjectPattern", + ].includes(parent.type) + ) { + parent = parent.parent; + } + + if ( + hasDanglingUnderscore(identifier) && + !isSpecialCaseIdentifierInVariableExpression(identifier) && + !isAllowed(identifier) && + !( + allowInArrayDestructuring && + parent.type === "ArrayPattern" + ) && + !( + allowInObjectDestructuring && + parent.type === "ObjectPattern" + ) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier, + }, + }); + } + }); + } + + /** + * Check if member expression has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInMemberExpression(node) { + const identifier = node.property.name, + isMemberOfThis = node.object.type === "ThisExpression", + isMemberOfSuper = node.object.type === "Super", + isMemberOfThisConstructor = isThisConstructorReference(node); + + if ( + typeof identifier !== "undefined" && + hasDanglingUnderscore(identifier) && + !(isMemberOfThis && allowAfterThis) && + !(isMemberOfSuper && allowAfterSuper) && + !(isMemberOfThisConstructor && allowAfterThisConstructor) && + !isSpecialCaseIdentifierForMemberExpression(identifier) && + !isAllowed(identifier) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier, + }, + }); + } + } + + /** + * Check if method declaration or method property has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInMethod(node) { + const identifier = node.key.name; + const isMethod = + node.type === "MethodDefinition" || + (node.type === "Property" && node.method); + + if ( + typeof identifier !== "undefined" && + enforceInMethodNames && + isMethod && + hasDanglingUnderscore(identifier) && + !isAllowed(identifier) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier: + node.key.type === "PrivateIdentifier" + ? `#${identifier}` + : identifier, + }, + }); + } + } + + /** + * Check if a class field has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInClassField(node) { + const identifier = node.key.name; + + if ( + typeof identifier !== "undefined" && + hasDanglingUnderscore(identifier) && + enforceInClassFields && + !isAllowed(identifier) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier: + node.key.type === "PrivateIdentifier" + ? `#${identifier}` + : identifier, + }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: checkForDanglingUnderscoreInFunction, + VariableDeclarator: checkForDanglingUnderscoreInVariableExpression, + MemberExpression: checkForDanglingUnderscoreInMemberExpression, + MethodDefinition: checkForDanglingUnderscoreInMethod, + PropertyDefinition: checkForDanglingUnderscoreInClassField, + Property: checkForDanglingUnderscoreInMethod, + FunctionExpression: checkForDanglingUnderscoreInFunction, + ArrowFunctionExpression: checkForDanglingUnderscoreInFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unexpected-multiline.js b/node_modules/eslint/lib/rules/no-unexpected-multiline.js new file mode 100644 index 00000000..0e91cdca --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unexpected-multiline.js @@ -0,0 +1,130 @@ +/** + * @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not. + * @author Glen Mailer + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow confusing multiline expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unexpected-multiline", + }, + + schema: [], + messages: { + function: + "Unexpected newline between function and ( of function call.", + property: + "Unexpected newline between object and [ of property access.", + taggedTemplate: + "Unexpected newline between template tag and template literal.", + division: + "Unexpected newline between numerator and division operator.", + }, + }, + + create(context) { + const REGEX_FLAG_MATCHER = /^[gimsuy]+$/u; + + const sourceCode = context.sourceCode; + + /** + * Check to see if there is a newline between the node and the following open bracket + * line's expression + * @param {ASTNode} node The node to check. + * @param {string} messageId The error messageId to use. + * @returns {void} + * @private + */ + function checkForBreakAfter(node, messageId) { + const openParen = sourceCode.getTokenAfter( + node, + astUtils.isNotClosingParenToken, + ); + const nodeExpressionEnd = sourceCode.getTokenBefore(openParen); + + if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { + context.report({ + node, + loc: openParen.loc, + messageId, + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + MemberExpression(node) { + if (!node.computed || node.optional) { + return; + } + checkForBreakAfter(node.object, "property"); + }, + + TaggedTemplateExpression(node) { + const { quasi } = node; + + // handles common tags, parenthesized tags, and typescript's generic type arguments + const tokenBefore = sourceCode.getTokenBefore(quasi); + + if (tokenBefore.loc.end.line !== quasi.loc.start.line) { + context.report({ + node, + loc: { + start: quasi.loc.start, + end: { + line: quasi.loc.start.line, + column: quasi.loc.start.column + 1, + }, + }, + messageId: "taggedTemplate", + }); + } + }, + + CallExpression(node) { + if (node.arguments.length === 0 || node.optional) { + return; + } + checkForBreakAfter(node.callee, "function"); + }, + + "BinaryExpression[operator='/'] > BinaryExpression[operator='/'].left"( + node, + ) { + const secondSlash = sourceCode.getTokenAfter( + node, + token => token.value === "/", + ); + const tokenAfterOperator = + sourceCode.getTokenAfter(secondSlash); + + if ( + tokenAfterOperator.type === "Identifier" && + REGEX_FLAG_MATCHER.test(tokenAfterOperator.value) && + secondSlash.range[1] === tokenAfterOperator.range[0] + ) { + checkForBreakAfter(node.left, "division"); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js b/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js new file mode 100644 index 00000000..17964892 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js @@ -0,0 +1,360 @@ +/** + * @fileoverview Rule to disallow use of unmodified expressions in loop conditions + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Traverser = require("../shared/traverser"), + astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_PATTERN = + /(?:(?:Call|Class|Function|Member|New|Yield)Expression|Statement|Declaration)$/u; +const LOOP_PATTERN = /^(?:DoWhile|For|While)Statement$/u; // for-in/of statements don't have `test` property. +const GROUP_PATTERN = /^(?:BinaryExpression|ConditionalExpression)$/u; +const SKIP_PATTERN = /^(?:ArrowFunction|Class|Function)Expression$/u; +const DYNAMIC_PATTERN = /^(?:Call|Member|New|TaggedTemplate|Yield)Expression$/u; + +/** + * @typedef {Object} LoopConditionInfo + * @property {eslint-scope.Reference} reference - The reference. + * @property {ASTNode} group - BinaryExpression or ConditionalExpression nodes + * that the reference is belonging to. + * @property {Function} isInLoop - The predicate which checks a given reference + * is in this loop. + * @property {boolean} modified - The flag that the reference is modified in + * this loop. + */ + +/** + * Checks whether or not a given reference is a write reference. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is a write reference. + */ +function isWriteReference(reference) { + if (reference.init) { + const def = reference.resolved && reference.resolved.defs[0]; + + if (!def || def.type !== "Variable" || def.parent.kind !== "var") { + return false; + } + } + return reference.isWrite(); +} + +/** + * Checks whether or not a given loop condition info does not have the modified + * flag. + * @param {LoopConditionInfo} condition A loop condition info to check. + * @returns {boolean} `true` if the loop condition info is "unmodified". + */ +function isUnmodified(condition) { + return !condition.modified; +} + +/** + * Checks whether or not a given loop condition info does not have the modified + * flag and does not have the group this condition belongs to. + * @param {LoopConditionInfo} condition A loop condition info to check. + * @returns {boolean} `true` if the loop condition info is "unmodified". + */ +function isUnmodifiedAndNotBelongToGroup(condition) { + return !(condition.modified || condition.group); +} + +/** + * Checks whether or not a given reference is inside of a given node. + * @param {ASTNode} node A node to check. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is inside of the node. + */ +function isInRange(node, reference) { + const or = node.range; + const ir = reference.identifier.range; + + return or[0] <= ir[0] && ir[1] <= or[1]; +} + +/** + * Checks whether or not a given reference is inside of a loop node's condition. + * @param {ASTNode} node A node to check. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is inside of the loop node's + * condition. + */ +const isInLoop = { + WhileStatement: isInRange, + DoWhileStatement: isInRange, + ForStatement(node, reference) { + return ( + isInRange(node, reference) && + !(node.init && isInRange(node.init, reference)) + ); + }, +}; + +/** + * Gets the function which encloses a given reference. + * This supports only FunctionDeclaration. + * @param {eslint-scope.Reference} reference A reference to get. + * @returns {ASTNode|null} The function node or null. + */ +function getEncloseFunctionDeclaration(reference) { + let node = reference.identifier; + + while (node) { + if (node.type === "FunctionDeclaration") { + return node.id ? node : null; + } + + node = node.parent; + } + + return null; +} + +/** + * Updates the "modified" flags of given loop conditions with given modifiers. + * @param {LoopConditionInfo[]} conditions The loop conditions to be updated. + * @param {eslint-scope.Reference[]} modifiers The references to update. + * @returns {void} + */ +function updateModifiedFlag(conditions, modifiers) { + for (let i = 0; i < conditions.length; ++i) { + const condition = conditions[i]; + + for (let j = 0; !condition.modified && j < modifiers.length; ++j) { + const modifier = modifiers[j]; + let funcNode, funcVar; + + /* + * Besides checking for the condition being in the loop, we want to + * check the function that this modifier is belonging to is called + * in the loop. + * FIXME: This should probably be extracted to a function. + */ + const inLoop = + condition.isInLoop(modifier) || + Boolean( + (funcNode = getEncloseFunctionDeclaration(modifier)) && + (funcVar = astUtils.getVariableByName( + modifier.from.upper, + funcNode.id.name, + )) && + funcVar.references.some(condition.isInLoop), + ); + + condition.modified = inLoop; + } + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow unmodified loop conditions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unmodified-loop-condition", + }, + + schema: [], + + messages: { + loopConditionNotModified: + "'{{name}}' is not modified in this loop.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let groupMap = null; + + /** + * Reports a given condition info. + * @param {LoopConditionInfo} condition A loop condition info to report. + * @returns {void} + */ + function report(condition) { + const node = condition.reference.identifier; + + context.report({ + node, + messageId: "loopConditionNotModified", + data: node, + }); + } + + /** + * Registers given conditions to the group the condition belongs to. + * @param {LoopConditionInfo[]} conditions A loop condition info to + * register. + * @returns {void} + */ + function registerConditionsToGroup(conditions) { + for (let i = 0; i < conditions.length; ++i) { + const condition = conditions[i]; + + if (condition.group) { + let group = groupMap.get(condition.group); + + if (!group) { + group = []; + groupMap.set(condition.group, group); + } + group.push(condition); + } + } + } + + /** + * Reports references which are inside of unmodified groups. + * @param {LoopConditionInfo[]} conditions A loop condition info to report. + * @returns {void} + */ + function checkConditionsInGroup(conditions) { + if (conditions.every(isUnmodified)) { + conditions.forEach(report); + } + } + + /** + * Checks whether or not a given group node has any dynamic elements. + * @param {ASTNode} root A node to check. + * This node is one of BinaryExpression or ConditionalExpression. + * @returns {boolean} `true` if the node is dynamic. + */ + function hasDynamicExpressions(root) { + let retv = false; + + Traverser.traverse(root, { + visitorKeys: sourceCode.visitorKeys, + enter(node) { + if (DYNAMIC_PATTERN.test(node.type)) { + retv = true; + this.break(); + } else if (SKIP_PATTERN.test(node.type)) { + this.skip(); + } + }, + }); + + return retv; + } + + /** + * Creates the loop condition information from a given reference. + * @param {eslint-scope.Reference} reference A reference to create. + * @returns {LoopConditionInfo|null} Created loop condition info, or null. + */ + function toLoopCondition(reference) { + if (reference.init) { + return null; + } + + let group = null; + let child = reference.identifier; + let node = child.parent; + + while (node) { + if (SENTINEL_PATTERN.test(node.type)) { + if (LOOP_PATTERN.test(node.type) && node.test === child) { + // This reference is inside of a loop condition. + return { + reference, + group, + isInLoop: isInLoop[node.type].bind(null, node), + modified: false, + }; + } + + // This reference is outside of a loop condition. + break; + } + + /* + * If it's inside of a group, OK if either operand is modified. + * So stores the group this reference belongs to. + */ + if (GROUP_PATTERN.test(node.type)) { + // If this expression is dynamic, no need to check. + if (hasDynamicExpressions(node)) { + break; + } else { + group = node; + } + } + + child = node; + node = node.parent; + } + + return null; + } + + /** + * Finds unmodified references which are inside of a loop condition. + * Then reports the references which are outside of groups. + * @param {eslint-scope.Variable} variable A variable to report. + * @returns {void} + */ + function checkReferences(variable) { + // Gets references that exist in loop conditions. + const conditions = variable.references + .map(toLoopCondition) + .filter(Boolean); + + if (conditions.length === 0) { + return; + } + + // Registers the conditions to belonging groups. + registerConditionsToGroup(conditions); + + // Check the conditions are modified. + const modifiers = variable.references.filter(isWriteReference); + + if (modifiers.length > 0) { + updateModifiedFlag(conditions, modifiers); + } + + /* + * Reports the conditions which are not belonging to groups. + * Others will be reported after all variables are done. + */ + conditions.filter(isUnmodifiedAndNotBelongToGroup).forEach(report); + } + + return { + "Program:exit"(node) { + const queue = [sourceCode.getScope(node)]; + + groupMap = new Map(); + + let scope; + + while ((scope = queue.pop())) { + queue.push(...scope.childScopes); + scope.variables.forEach(checkReferences); + } + + groupMap.forEach(checkConditionsInGroup); + groupMap = null; + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unneeded-ternary.js b/node_modules/eslint/lib/rules/no-unneeded-ternary.js new file mode 100644 index 00000000..24e65b67 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unneeded-ternary.js @@ -0,0 +1,232 @@ +/** + * @fileoverview Rule to flag no-unneeded-ternary + * @author Gyandeep Singh + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +// Operators that always result in a boolean value +const BOOLEAN_OPERATORS = new Set([ + "==", + "===", + "!=", + "!==", + ">", + ">=", + "<", + "<=", + "in", + "instanceof", +]); +const OPERATOR_INVERSES = { + "==": "!=", + "!=": "==", + "===": "!==", + "!==": "===", + + // Operators like < and >= are not true inverses, since both will return false with NaN. +}; +const OR_PRECEDENCE = astUtils.getPrecedence({ + type: "LogicalExpression", + operator: "||", +}); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ defaultAssignment: true }], + + docs: { + description: + "Disallow ternary operators when simpler alternatives exist", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-unneeded-ternary", + }, + + schema: [ + { + type: "object", + properties: { + defaultAssignment: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + unnecessaryConditionalExpression: + "Unnecessary use of boolean literals in conditional expression.", + unnecessaryConditionalAssignment: + "Unnecessary use of conditional expression for default assignment.", + }, + }, + + create(context) { + const [{ defaultAssignment }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Test if the node is a boolean literal + * @param {ASTNode} node The node to report. + * @returns {boolean} True if the its a boolean literal + * @private + */ + function isBooleanLiteral(node) { + return node.type === "Literal" && typeof node.value === "boolean"; + } + + /** + * Creates an expression that represents the boolean inverse of the expression represented by the original node + * @param {ASTNode} node A node representing an expression + * @returns {string} A string representing an inverted expression + */ + function invertExpression(node) { + if ( + node.type === "BinaryExpression" && + Object.hasOwn(OPERATOR_INVERSES, node.operator) + ) { + const operatorToken = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + const text = sourceCode.getText(); + + return ( + text.slice(node.range[0], operatorToken.range[0]) + + OPERATOR_INVERSES[node.operator] + + text.slice(operatorToken.range[1], node.range[1]) + ); + } + + if ( + astUtils.getPrecedence(node) < + astUtils.getPrecedence({ type: "UnaryExpression" }) + ) { + return `!(${astUtils.getParenthesisedText(sourceCode, node)})`; + } + return `!${astUtils.getParenthesisedText(sourceCode, node)}`; + } + + /** + * Tests if a given node always evaluates to a boolean value + * @param {ASTNode} node An expression node + * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value + */ + function isBooleanExpression(node) { + return ( + (node.type === "BinaryExpression" && + BOOLEAN_OPERATORS.has(node.operator)) || + (node.type === "UnaryExpression" && node.operator === "!") + ); + } + + /** + * Test if the node matches the pattern id ? id : expression + * @param {ASTNode} node The ConditionalExpression to check. + * @returns {boolean} True if the pattern is matched, and false otherwise + * @private + */ + function matchesDefaultAssignment(node) { + return ( + node.test.type === "Identifier" && + node.consequent.type === "Identifier" && + node.test.name === node.consequent.name + ); + } + + return { + ConditionalExpression(node) { + if ( + isBooleanLiteral(node.alternate) && + isBooleanLiteral(node.consequent) + ) { + context.report({ + node, + messageId: "unnecessaryConditionalExpression", + fix(fixer) { + if ( + node.consequent.value === node.alternate.value + ) { + // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true` + return node.test.type === "Identifier" + ? fixer.replaceText( + node, + node.consequent.value.toString(), + ) + : null; + } + if (node.alternate.value) { + // Replace `foo() ? false : true` with `!(foo())` + return fixer.replaceText( + node, + invertExpression(node.test), + ); + } + + // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise. + + return fixer.replaceText( + node, + isBooleanExpression(node.test) + ? astUtils.getParenthesisedText( + sourceCode, + node.test, + ) + : `!${invertExpression(node.test)}`, + ); + }, + }); + } else if ( + !defaultAssignment && + matchesDefaultAssignment(node) + ) { + context.report({ + node, + messageId: "unnecessaryConditionalAssignment", + fix(fixer) { + const shouldParenthesizeAlternate = + (astUtils.getPrecedence(node.alternate) < + OR_PRECEDENCE || + astUtils.isCoalesceExpression( + node.alternate, + )) && + !astUtils.isParenthesised( + sourceCode, + node.alternate, + ); + const alternateText = shouldParenthesizeAlternate + ? `(${sourceCode.getText(node.alternate)})` + : astUtils.getParenthesisedText( + sourceCode, + node.alternate, + ); + const testText = astUtils.getParenthesisedText( + sourceCode, + node.test, + ); + + return fixer.replaceText( + node, + `${testText} || ${alternateText}`, + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unreachable-loop.js b/node_modules/eslint/lib/rules/no-unreachable-loop.js new file mode 100644 index 00000000..63e3c977 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unreachable-loop.js @@ -0,0 +1,190 @@ +/** + * @fileoverview Rule to disallow loops with a body that allows only one iteration + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const allLoopTypes = [ + "WhileStatement", + "DoWhileStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", +]; + +/** + * Checks all segments in a set and returns true if any are reachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if any segment is reachable; false otherwise. + */ +function isAnySegmentReachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return true; + } + } + + return false; +} + +/** + * Determines whether the given node is the first node in the code path to which a loop statement + * 'loops' for the next iteration. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a looping target. + */ +function isLoopingTarget(node) { + const parent = node.parent; + + if (parent) { + switch (parent.type) { + case "WhileStatement": + return node === parent.test; + case "DoWhileStatement": + return node === parent.body; + case "ForStatement": + return node === (parent.update || parent.test || parent.body); + case "ForInStatement": + case "ForOfStatement": + return node === parent.left; + + // no default + } + } + + return false; +} + +/** + * Creates an array with elements from the first given array that are not included in the second given array. + * @param {Array} arrA The array to compare from. + * @param {Array} arrB The array to compare against. + * @returns {Array} a new array that represents `arrA \ arrB`. + */ +function getDifference(arrA, arrB) { + return arrA.filter(a => !arrB.includes(a)); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [{ ignore: [] }], + + docs: { + description: + "Disallow loops with a body that allows only one iteration", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unreachable-loop", + }, + + schema: [ + { + type: "object", + properties: { + ignore: { + type: "array", + items: { + enum: allLoopTypes, + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + invalid: "Invalid loop. Its body allows only one iteration.", + }, + }, + + create(context) { + const [{ ignore: ignoredLoopTypes }] = context.options; + const loopTypesToCheck = getDifference(allLoopTypes, ignoredLoopTypes), + loopSelector = loopTypesToCheck.join(","), + loopsByTargetSegments = new Map(), + loopsToReport = new Set(); + + const codePathSegments = []; + let currentCodePathSegments = new Set(); + + return { + onCodePathStart() { + codePathSegments.push(currentCodePathSegments); + currentCodePathSegments = new Set(); + }, + + onCodePathEnd() { + currentCodePathSegments = codePathSegments.pop(); + }, + + onUnreachableCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentStart(segment, node) { + currentCodePathSegments.add(segment); + + if (isLoopingTarget(node)) { + const loop = node.parent; + + loopsByTargetSegments.set(segment, loop); + } + }, + + onCodePathSegmentLoop(_, toSegment, node) { + const loop = loopsByTargetSegments.get(toSegment); + + /** + * The second iteration is reachable, meaning that the loop is valid by the logic of this rule, + * only if there is at least one loop event with the appropriate target (which has been already + * determined in the `loopsByTargetSegments` map), raised from either: + * + * - the end of the loop's body (in which case `node === loop`) + * - a `continue` statement + * + * This condition skips loop events raised from `ForInStatement > .right` and `ForOfStatement > .right` nodes. + */ + if (node === loop || node.type === "ContinueStatement") { + // Removes loop if it exists in the set. Otherwise, `Set#delete` has no effect and doesn't throw. + loopsToReport.delete(loop); + } + }, + + [loopSelector](node) { + /** + * Ignore unreachable loop statements to avoid unnecessary complexity in the implementation, or false positives otherwise. + * For unreachable segments, the code path analysis does not raise events required for this implementation. + */ + if (isAnySegmentReachable(currentCodePathSegments)) { + loopsToReport.add(node); + } + }, + + "Program:exit"() { + loopsToReport.forEach(node => + context.report({ node, messageId: "invalid" }), + ); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unreachable.js b/node_modules/eslint/lib/rules/no-unreachable.js new file mode 100644 index 00000000..7be94bb3 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unreachable.js @@ -0,0 +1,300 @@ +/** + * @fileoverview Checks for unreachable code due to return, throws, break, and continue. + * @author Joel Feenstra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * @typedef {Object} ConstructorInfo + * @property {ConstructorInfo | null} upper Info about the constructor that encloses this constructor. + * @property {boolean} hasSuperCall The flag about having `super()` expressions. + */ + +/** + * Checks whether or not a given variable declarator has the initializer. + * @param {ASTNode} node A VariableDeclarator node to check. + * @returns {boolean} `true` if the node has the initializer. + */ +function isInitialized(node) { + return Boolean(node.init); +} + +/** + * Checks all segments in a set and returns true if all are unreachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if all segments are unreachable; false otherwise. + */ +function areAllSegmentsUnreachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return false; + } + } + + return true; +} + +/** + * The class to distinguish consecutive unreachable statements. + */ +class ConsecutiveRange { + constructor(sourceCode) { + this.sourceCode = sourceCode; + this.startNode = null; + this.endNode = null; + } + + /** + * The location object of this range. + * @type {Object} + */ + get location() { + return { + start: this.startNode.loc.start, + end: this.endNode.loc.end, + }; + } + + /** + * `true` if this range is empty. + * @type {boolean} + */ + get isEmpty() { + return !(this.startNode && this.endNode); + } + + /** + * Checks whether the given node is inside of this range. + * @param {ASTNode|Token} node The node to check. + * @returns {boolean} `true` if the node is inside of this range. + */ + contains(node) { + return ( + node.range[0] >= this.startNode.range[0] && + node.range[1] <= this.endNode.range[1] + ); + } + + /** + * Checks whether the given node is consecutive to this range. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is consecutive to this range. + */ + isConsecutive(node) { + return this.contains(this.sourceCode.getTokenBefore(node)); + } + + /** + * Merges the given node to this range. + * @param {ASTNode} node The node to merge. + * @returns {void} + */ + merge(node) { + this.endNode = node; + } + + /** + * Resets this range by the given node or null. + * @param {ASTNode|null} node The node to reset, or null. + * @returns {void} + */ + reset(node) { + this.startNode = this.endNode = node; + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow unreachable code after `return`, `throw`, `continue`, and `break` statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unreachable", + }, + + schema: [], + + messages: { + unreachableCode: "Unreachable code.", + }, + }, + + create(context) { + /** @type {ConstructorInfo | null} */ + let constructorInfo = null; + + /** @type {ConsecutiveRange} */ + const range = new ConsecutiveRange(context.sourceCode); + + /** @type {Array>} */ + const codePathSegments = []; + + /** @type {Set} */ + let currentCodePathSegments = new Set(); + + /** + * Reports a given node if it's unreachable. + * @param {ASTNode} node A statement node to report. + * @returns {void} + */ + function reportIfUnreachable(node) { + let nextNode = null; + + if ( + node && + (node.type === "PropertyDefinition" || + areAllSegmentsUnreachable(currentCodePathSegments)) + ) { + // Store this statement to distinguish consecutive statements. + if (range.isEmpty) { + range.reset(node); + return; + } + + // Skip if this statement is inside of the current range. + if (range.contains(node)) { + return; + } + + // Merge if this statement is consecutive to the current range. + if (range.isConsecutive(node)) { + range.merge(node); + return; + } + + nextNode = node; + } + + /* + * Report the current range since this statement is reachable or is + * not consecutive to the current range. + */ + if (!range.isEmpty) { + context.report({ + messageId: "unreachableCode", + loc: range.location, + node: range.startNode, + }); + } + + // Update the current range. + range.reset(nextNode); + } + + return { + // Manages the current code path. + onCodePathStart() { + codePathSegments.push(currentCodePathSegments); + currentCodePathSegments = new Set(); + }, + + onCodePathEnd() { + currentCodePathSegments = codePathSegments.pop(); + }, + + onUnreachableCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + // Registers for all statement nodes (excludes FunctionDeclaration). + BlockStatement: reportIfUnreachable, + BreakStatement: reportIfUnreachable, + ClassDeclaration: reportIfUnreachable, + ContinueStatement: reportIfUnreachable, + DebuggerStatement: reportIfUnreachable, + DoWhileStatement: reportIfUnreachable, + ExpressionStatement: reportIfUnreachable, + ForInStatement: reportIfUnreachable, + ForOfStatement: reportIfUnreachable, + ForStatement: reportIfUnreachable, + IfStatement: reportIfUnreachable, + ImportDeclaration: reportIfUnreachable, + LabeledStatement: reportIfUnreachable, + ReturnStatement: reportIfUnreachable, + SwitchStatement: reportIfUnreachable, + ThrowStatement: reportIfUnreachable, + TryStatement: reportIfUnreachable, + + VariableDeclaration(node) { + if ( + node.kind !== "var" || + node.declarations.some(isInitialized) + ) { + reportIfUnreachable(node); + } + }, + + WhileStatement: reportIfUnreachable, + WithStatement: reportIfUnreachable, + ExportNamedDeclaration: reportIfUnreachable, + ExportDefaultDeclaration: reportIfUnreachable, + ExportAllDeclaration: reportIfUnreachable, + + "Program:exit"() { + reportIfUnreachable(); + }, + + /* + * Instance fields defined in a subclass are never created if the constructor of the subclass + * doesn't call `super()`, so their definitions are unreachable code. + */ + "MethodDefinition[kind='constructor']"() { + constructorInfo = { + upper: constructorInfo, + hasSuperCall: false, + }; + }, + "MethodDefinition[kind='constructor']:exit"(node) { + const { hasSuperCall } = constructorInfo; + + constructorInfo = constructorInfo.upper; + + // skip typescript constructors without the body + if (!node.value.body) { + return; + } + + const classDefinition = node.parent.parent; + + if (classDefinition.superClass && !hasSuperCall) { + for (const element of classDefinition.body.body) { + if ( + element.type === "PropertyDefinition" && + !element.static + ) { + reportIfUnreachable(element); + } + } + } + }, + "CallExpression > Super.callee"() { + if (constructorInfo) { + constructorInfo.hasSuperCall = true; + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unsafe-finally.js b/node_modules/eslint/lib/rules/no-unsafe-finally.js new file mode 100644 index 00000000..4c6393e6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unsafe-finally.js @@ -0,0 +1,119 @@ +/** + * @fileoverview Rule to flag unsafe statements in finally block + * @author Onur Temizkan + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_NODE_TYPE_RETURN_THROW = + /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/u; +const SENTINEL_NODE_TYPE_BREAK = + /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/u; +const SENTINEL_NODE_TYPE_CONTINUE = + /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/u; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow control flow statements in `finally` blocks", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unsafe-finally", + }, + + schema: [], + + messages: { + unsafeUsage: "Unsafe usage of {{nodeType}}.", + }, + }, + create(context) { + /** + * Checks if the node is the finalizer of a TryStatement + * @param {ASTNode} node node to check. + * @returns {boolean} - true if the node is the finalizer of a TryStatement + */ + function isFinallyBlock(node) { + return ( + node.parent.type === "TryStatement" && + node.parent.finalizer === node + ); + } + + /** + * Climbs up the tree if the node is not a sentinel node + * @param {ASTNode} node node to check. + * @param {string} label label of the break or continue statement + * @returns {boolean} - return whether the node is a finally block or a sentinel node + */ + function isInFinallyBlock(node, label) { + let labelInside = false; + let sentinelNodeType; + + if (node.type === "BreakStatement" && !node.label) { + sentinelNodeType = SENTINEL_NODE_TYPE_BREAK; + } else if (node.type === "ContinueStatement") { + sentinelNodeType = SENTINEL_NODE_TYPE_CONTINUE; + } else { + sentinelNodeType = SENTINEL_NODE_TYPE_RETURN_THROW; + } + + for ( + let currentNode = node; + currentNode && !sentinelNodeType.test(currentNode.type); + currentNode = currentNode.parent + ) { + if ( + currentNode.parent.label && + label && + currentNode.parent.label.name === label.name + ) { + labelInside = true; + } + if (isFinallyBlock(currentNode)) { + if (label && labelInside) { + return false; + } + return true; + } + } + return false; + } + + /** + * Checks whether the possibly-unsafe statement is inside a finally block. + * @param {ASTNode} node node to check. + * @returns {void} + */ + function check(node) { + if (isInFinallyBlock(node, node.label)) { + context.report({ + messageId: "unsafeUsage", + data: { + nodeType: node.type, + }, + node, + line: node.loc.line, + column: node.loc.column, + }); + } + } + + return { + ReturnStatement: check, + ThrowStatement: check, + BreakStatement: check, + ContinueStatement: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unsafe-negation.js b/node_modules/eslint/lib/rules/no-unsafe-negation.js new file mode 100644 index 00000000..17e02710 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unsafe-negation.js @@ -0,0 +1,152 @@ +/** + * @fileoverview Rule to disallow negating the left operand of relational operators + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given operator is `in` or `instanceof` + * @param {string} op The operator type to check. + * @returns {boolean} `true` if the operator is `in` or `instanceof` + */ +function isInOrInstanceOfOperator(op) { + return op === "in" || op === "instanceof"; +} + +/** + * Checks whether the given operator is an ordering relational operator or not. + * @param {string} op The operator type to check. + * @returns {boolean} `true` if the operator is an ordering relational operator. + */ +function isOrderingRelationalOperator(op) { + return op === "<" || op === ">" || op === ">=" || op === "<="; +} + +/** + * Checks whether the given node is a logical negation expression or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a logical negation expression. + */ +function isNegation(node) { + return node.type === "UnaryExpression" && node.operator === "!"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + enforceForOrderingRelations: false, + }, + ], + + docs: { + description: + "Disallow negating the left operand of relational operators", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unsafe-negation", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + enforceForOrderingRelations: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: null, + + messages: { + unexpected: + "Unexpected negating the left operand of '{{operator}}' operator.", + suggestNegatedExpression: + "Negate '{{operator}}' expression instead of its left operand. This changes the current behavior.", + suggestParenthesisedNegation: + "Wrap negation in '()' to make the intention explicit. This preserves the current behavior.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ enforceForOrderingRelations }] = context.options; + + return { + BinaryExpression(node) { + const operator = node.operator; + const orderingRelationRuleApplies = + enforceForOrderingRelations && + isOrderingRelationalOperator(operator); + + if ( + (isInOrInstanceOfOperator(operator) || + orderingRelationRuleApplies) && + isNegation(node.left) && + !astUtils.isParenthesised(sourceCode, node.left) + ) { + context.report({ + node, + loc: node.left.loc, + messageId: "unexpected", + data: { operator }, + suggest: [ + { + messageId: "suggestNegatedExpression", + data: { operator }, + fix(fixer) { + const negationToken = + sourceCode.getFirstToken(node.left); + const fixRange = [ + negationToken.range[1], + node.range[1], + ]; + const text = sourceCode.text.slice( + fixRange[0], + fixRange[1], + ); + + return fixer.replaceTextRange( + fixRange, + `(${text})`, + ); + }, + }, + { + messageId: "suggestParenthesisedNegation", + fix(fixer) { + return fixer.replaceText( + node.left, + `(${sourceCode.getText(node.left)})`, + ); + }, + }, + ], + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js b/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js new file mode 100644 index 00000000..95875b7e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js @@ -0,0 +1,221 @@ +/** + * @fileoverview Rule to disallow unsafe optional chaining + * @author Yeon JuAn + */ + +"use strict"; + +const UNSAFE_ARITHMETIC_OPERATORS = new Set(["+", "-", "/", "*", "%", "**"]); +const UNSAFE_ASSIGNMENT_OPERATORS = new Set([ + "+=", + "-=", + "/=", + "*=", + "%=", + "**=", +]); +const UNSAFE_RELATIONAL_OPERATORS = new Set(["in", "instanceof"]); + +/** + * Checks whether a node is a destructuring pattern or not + * @param {ASTNode} node node to check + * @returns {boolean} `true` if a node is a destructuring pattern, otherwise `false` + */ +function isDestructuringPattern(node) { + return node.type === "ObjectPattern" || node.type === "ArrayPattern"; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + disallowArithmeticOperators: false, + }, + ], + + docs: { + description: + "Disallow use of optional chaining in contexts where the `undefined` value is not allowed", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unsafe-optional-chaining", + }, + schema: [ + { + type: "object", + properties: { + disallowArithmeticOperators: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + fixable: null, + messages: { + unsafeOptionalChain: + "Unsafe usage of optional chaining. If it short-circuits with 'undefined' the evaluation will throw TypeError.", + unsafeArithmetic: + "Unsafe arithmetic operation on optional chaining. It can result in NaN.", + }, + }, + + create(context) { + const [{ disallowArithmeticOperators }] = context.options; + + /** + * Reports unsafe usage of optional chaining + * @param {ASTNode} node node to report + * @returns {void} + */ + function reportUnsafeUsage(node) { + context.report({ + messageId: "unsafeOptionalChain", + node, + }); + } + + /** + * Reports unsafe arithmetic operation on optional chaining + * @param {ASTNode} node node to report + * @returns {void} + */ + function reportUnsafeArithmetic(node) { + context.report({ + messageId: "unsafeArithmetic", + node, + }); + } + + /** + * Checks and reports if a node can short-circuit with `undefined` by optional chaining. + * @param {ASTNode} [node] node to check + * @param {Function} reportFunc report function + * @returns {void} + */ + function checkUndefinedShortCircuit(node, reportFunc) { + if (!node) { + return; + } + switch (node.type) { + case "LogicalExpression": + if (node.operator === "||" || node.operator === "??") { + checkUndefinedShortCircuit(node.right, reportFunc); + } else if (node.operator === "&&") { + checkUndefinedShortCircuit(node.left, reportFunc); + checkUndefinedShortCircuit(node.right, reportFunc); + } + break; + case "SequenceExpression": + checkUndefinedShortCircuit( + node.expressions.at(-1), + reportFunc, + ); + break; + case "ConditionalExpression": + checkUndefinedShortCircuit(node.consequent, reportFunc); + checkUndefinedShortCircuit(node.alternate, reportFunc); + break; + case "AwaitExpression": + checkUndefinedShortCircuit(node.argument, reportFunc); + break; + case "ChainExpression": + reportFunc(node); + break; + default: + break; + } + } + + /** + * Checks unsafe usage of optional chaining + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkUnsafeUsage(node) { + checkUndefinedShortCircuit(node, reportUnsafeUsage); + } + + /** + * Checks unsafe arithmetic operations on optional chaining + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkUnsafeArithmetic(node) { + checkUndefinedShortCircuit(node, reportUnsafeArithmetic); + } + + return { + "AssignmentExpression, AssignmentPattern"(node) { + if (isDestructuringPattern(node.left)) { + checkUnsafeUsage(node.right); + } + }, + "ClassDeclaration, ClassExpression"(node) { + checkUnsafeUsage(node.superClass); + }, + CallExpression(node) { + if (!node.optional) { + checkUnsafeUsage(node.callee); + } + }, + NewExpression(node) { + checkUnsafeUsage(node.callee); + }, + VariableDeclarator(node) { + if (isDestructuringPattern(node.id)) { + checkUnsafeUsage(node.init); + } + }, + MemberExpression(node) { + if (!node.optional) { + checkUnsafeUsage(node.object); + } + }, + TaggedTemplateExpression(node) { + checkUnsafeUsage(node.tag); + }, + ForOfStatement(node) { + checkUnsafeUsage(node.right); + }, + SpreadElement(node) { + if (node.parent && node.parent.type !== "ObjectExpression") { + checkUnsafeUsage(node.argument); + } + }, + BinaryExpression(node) { + if (UNSAFE_RELATIONAL_OPERATORS.has(node.operator)) { + checkUnsafeUsage(node.right); + } + if ( + disallowArithmeticOperators && + UNSAFE_ARITHMETIC_OPERATORS.has(node.operator) + ) { + checkUnsafeArithmetic(node.right); + checkUnsafeArithmetic(node.left); + } + }, + WithStatement(node) { + checkUnsafeUsage(node.object); + }, + UnaryExpression(node) { + if ( + disallowArithmeticOperators && + UNSAFE_ARITHMETIC_OPERATORS.has(node.operator) + ) { + checkUnsafeArithmetic(node.argument); + } + }, + AssignmentExpression(node) { + if ( + disallowArithmeticOperators && + UNSAFE_ASSIGNMENT_OPERATORS.has(node.operator) + ) { + checkUnsafeArithmetic(node.right); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unused-expressions.js b/node_modules/eslint/lib/rules/no-unused-expressions.js new file mode 100644 index 00000000..3c530e6e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-expressions.js @@ -0,0 +1,227 @@ +/** + * @fileoverview Flag expressions in statement position that do not side effect + * @author Michael Ficarra + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Returns `true`. + * @returns {boolean} `true`. + */ +function alwaysTrue() { + return true; +} + +/** + * Returns `false`. + * @returns {boolean} `false`. + */ +function alwaysFalse() { + return false; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Disallow unused expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unused-expressions", + }, + + schema: [ + { + type: "object", + properties: { + allowShortCircuit: { + type: "boolean", + }, + allowTernary: { + type: "boolean", + }, + allowTaggedTemplates: { + type: "boolean", + }, + enforceForJSX: { + type: "boolean", + }, + ignoreDirectives: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + allowShortCircuit: false, + allowTernary: false, + allowTaggedTemplates: false, + enforceForJSX: false, + ignoreDirectives: false, + }, + ], + + messages: { + unusedExpression: + "Expected an assignment or function call and instead saw an expression.", + }, + }, + + create(context) { + const [ + { + allowShortCircuit, + allowTernary, + allowTaggedTemplates, + enforceForJSX, + ignoreDirectives, + }, + ] = context.options; + + /** + * Has AST suggesting a directive. + * @param {ASTNode} node any node + * @returns {boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return ( + node.type === "ExpressionStatement" && + node.expression.type === "Literal" && + typeof node.expression.value === "string" + ); + } + + /** + * Gets the leading sequence of members in a list that pass the predicate. + * @param {Function} predicate ([a] -> Boolean) the function used to make the determination + * @param {a[]} list the input list + * @returns {a[]} the leading sequence of members in the given list that pass the given predicate + */ + function takeWhile(predicate, list) { + for (let i = 0; i < list.length; ++i) { + if (!predicate(list[i])) { + return list.slice(0, i); + } + } + return list.slice(); + } + + /** + * Gets leading directives nodes in a Node body. + * @param {ASTNode} node a Program or BlockStatement node + * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body + */ + function directives(node) { + return takeWhile(looksLikeDirective, node.body); + } + + /** + * Detect if a Node is a directive. + * @param {ASTNode} node any node + * @returns {boolean} whether the given node is considered a directive in its current position + */ + function isDirective(node) { + /** + * https://tc39.es/ecma262/#directive-prologue + * + * Only `FunctionBody`, `ScriptBody` and `ModuleBody` can have directive prologue. + * Class static blocks do not have directive prologue. + */ + return ( + astUtils.isTopLevelExpressionStatement(node) && + directives(node.parent).includes(node) + ); + } + + /** + * The member functions return `true` if the type has no side-effects. + * Unknown nodes are handled as `false`, then this rule ignores those. + */ + const Checker = Object.assign(Object.create(null), { + isDisallowed(node) { + return (Checker[node.type] || alwaysFalse)(node); + }, + + ArrayExpression: alwaysTrue, + ArrowFunctionExpression: alwaysTrue, + BinaryExpression: alwaysTrue, + ChainExpression(node) { + return Checker.isDisallowed(node.expression); + }, + ClassExpression: alwaysTrue, + ConditionalExpression(node) { + if (allowTernary) { + return ( + Checker.isDisallowed(node.consequent) || + Checker.isDisallowed(node.alternate) + ); + } + return true; + }, + FunctionExpression: alwaysTrue, + Identifier: alwaysTrue, + JSXElement() { + return enforceForJSX; + }, + JSXFragment() { + return enforceForJSX; + }, + Literal: alwaysTrue, + LogicalExpression(node) { + if (allowShortCircuit) { + return Checker.isDisallowed(node.right); + } + return true; + }, + MemberExpression: alwaysTrue, + MetaProperty: alwaysTrue, + ObjectExpression: alwaysTrue, + SequenceExpression: alwaysTrue, + TaggedTemplateExpression() { + return !allowTaggedTemplates; + }, + TemplateLiteral: alwaysTrue, + ThisExpression: alwaysTrue, + UnaryExpression(node) { + return node.operator !== "void" && node.operator !== "delete"; + }, + // TypeScript-specific node types + TSAsExpression(node) { + return Checker.isDisallowed(node.expression); + }, + TSTypeAssertion(node) { + return Checker.isDisallowed(node.expression); + }, + TSNonNullExpression(node) { + return Checker.isDisallowed(node.expression); + }, + TSInstantiationExpression(node) { + return Checker.isDisallowed(node.expression); + }, + }); + + return { + ExpressionStatement(node) { + if ( + Checker.isDisallowed(node.expression) && + !astUtils.isDirective(node) && + !(ignoreDirectives && isDirective(node)) + ) { + context.report({ node, messageId: "unusedExpression" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unused-labels.js b/node_modules/eslint/lib/rules/no-unused-labels.js new file mode 100644 index 00000000..d7fe3e42 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-labels.js @@ -0,0 +1,158 @@ +/** + * @fileoverview Rule to disallow unused labels. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unused labels", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unused-labels", + }, + + schema: [], + + fixable: "code", + + messages: { + unused: "'{{name}}:' is defined but never used.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Adds a scope info to the stack. + * @param {ASTNode} node A node to add. This is a LabeledStatement. + * @returns {void} + */ + function enterLabeledScope(node) { + scopeInfo = { + label: node.label.name, + used: false, + upper: scopeInfo, + }; + } + + /** + * Checks if a `LabeledStatement` node is fixable. + * For a node to be fixable, there must be no comments between the label and the body. + * Furthermore, is must be possible to remove the label without turning the body statement into a + * directive after other fixes are applied. + * @param {ASTNode} node The node to evaluate. + * @returns {boolean} Whether or not the node is fixable. + */ + function isFixable(node) { + /* + * Only perform a fix if there are no comments between the label and the body. This will be the case + * when there is exactly one token/comment (the ":") between the label and the body. + */ + if ( + sourceCode.getTokenAfter(node.label, { + includeComments: true, + }) !== + sourceCode.getTokenBefore(node.body, { includeComments: true }) + ) { + return false; + } + + // Looking for the node's deepest ancestor which is not a `LabeledStatement`. + let ancestor = node.parent; + + while (ancestor.type === "LabeledStatement") { + ancestor = ancestor.parent; + } + + if ( + ancestor.type === "Program" || + (ancestor.type === "BlockStatement" && + astUtils.isFunction(ancestor.parent)) + ) { + const { body } = node; + + if ( + body.type === "ExpressionStatement" && + ((body.expression.type === "Literal" && + typeof body.expression.value === "string") || + astUtils.isStaticTemplateLiteral(body.expression)) + ) { + return false; // potential directive + } + } + return true; + } + + /** + * Removes the top of the stack. + * At the same time, this reports the label if it's never used. + * @param {ASTNode} node A node to report. This is a LabeledStatement. + * @returns {void} + */ + function exitLabeledScope(node) { + if (!scopeInfo.used) { + context.report({ + node: node.label, + messageId: "unused", + data: node.label, + fix: isFixable(node) + ? fixer => + fixer.removeRange([ + node.range[0], + node.body.range[0], + ]) + : null, + }); + } + + scopeInfo = scopeInfo.upper; + } + + /** + * Marks the label of a given node as used. + * @param {ASTNode} node A node to mark. This is a BreakStatement or + * ContinueStatement. + * @returns {void} + */ + function markAsUsed(node) { + if (!node.label) { + return; + } + + const label = node.label.name; + let info = scopeInfo; + + while (info) { + if (info.label === label) { + info.used = true; + break; + } + info = info.upper; + } + } + + return { + LabeledStatement: enterLabeledScope, + "LabeledStatement:exit": exitLabeledScope, + BreakStatement: markAsUsed, + ContinueStatement: markAsUsed, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unused-private-class-members.js b/node_modules/eslint/lib/rules/no-unused-private-class-members.js new file mode 100644 index 00000000..51029cc4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-private-class-members.js @@ -0,0 +1,219 @@ +/** + * @fileoverview Rule to flag declared but unused private class members + * @author Tim van der Lippe + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow unused private class members", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unused-private-class-members", + }, + + schema: [], + + messages: { + unusedPrivateClassMember: + "'{{classMemberName}}' is defined but never used.", + }, + }, + + create(context) { + const trackedClasses = []; + + /** + * Check whether the current node is in a write only assignment. + * @param {ASTNode} privateIdentifierNode Node referring to a private identifier + * @returns {boolean} Whether the node is in a write only assignment + * @private + */ + function isWriteOnlyAssignment(privateIdentifierNode) { + const parentStatement = privateIdentifierNode.parent.parent; + const isAssignmentExpression = + parentStatement.type === "AssignmentExpression"; + + if ( + !isAssignmentExpression && + parentStatement.type !== "ForInStatement" && + parentStatement.type !== "ForOfStatement" && + parentStatement.type !== "AssignmentPattern" + ) { + return false; + } + + // It is a write-only usage, since we still allow usages on the right for reads + if (parentStatement.left !== privateIdentifierNode.parent) { + return false; + } + + // For any other operator (such as '+=') we still consider it a read operation + if (isAssignmentExpression && parentStatement.operator !== "=") { + /* + * However, if the read operation is "discarded" in an empty statement, then + * we consider it write only. + */ + return parentStatement.parent.type === "ExpressionStatement"; + } + + return true; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + // Collect all declared members up front and assume they are all unused + ClassBody(classBodyNode) { + const privateMembers = new Map(); + + trackedClasses.unshift(privateMembers); + for (const bodyMember of classBodyNode.body) { + if ( + bodyMember.type === "PropertyDefinition" || + bodyMember.type === "MethodDefinition" + ) { + if (bodyMember.key.type === "PrivateIdentifier") { + privateMembers.set(bodyMember.key.name, { + declaredNode: bodyMember, + isAccessor: + bodyMember.type === "MethodDefinition" && + (bodyMember.kind === "set" || + bodyMember.kind === "get"), + }); + } + } + } + }, + + /* + * Process all usages of the private identifier and remove a member from + * `declaredAndUnusedPrivateMembers` if we deem it used. + */ + PrivateIdentifier(privateIdentifierNode) { + const classBody = trackedClasses.find(classProperties => + classProperties.has(privateIdentifierNode.name), + ); + + // Can't happen, as it is a parser to have a missing class body, but let's code defensively here. + if (!classBody) { + return; + } + + // In case any other usage was already detected, we can short circuit the logic here. + const memberDefinition = classBody.get( + privateIdentifierNode.name, + ); + + if (memberDefinition.isUsed) { + return; + } + + // The definition of the class member itself + if ( + privateIdentifierNode.parent.type === + "PropertyDefinition" || + privateIdentifierNode.parent.type === "MethodDefinition" + ) { + return; + } + + /* + * Any usage of an accessor is considered a read, as the getter/setter can have + * side-effects in its definition. + */ + if (memberDefinition.isAccessor) { + memberDefinition.isUsed = true; + return; + } + + // Any assignments to this member, except for assignments that also read + if (isWriteOnlyAssignment(privateIdentifierNode)) { + return; + } + + const wrappingExpressionType = + privateIdentifierNode.parent.parent.type; + const parentOfWrappingExpressionType = + privateIdentifierNode.parent.parent.parent.type; + + // A statement which only increments (`this.#x++;`) + if ( + wrappingExpressionType === "UpdateExpression" && + parentOfWrappingExpressionType === "ExpressionStatement" + ) { + return; + } + + /* + * ({ x: this.#usedInDestructuring } = bar); + * + * But should treat the following as a read: + * ({ [this.#x]: a } = foo); + */ + if ( + wrappingExpressionType === "Property" && + parentOfWrappingExpressionType === "ObjectPattern" && + privateIdentifierNode.parent.parent.value === + privateIdentifierNode.parent + ) { + return; + } + + // [...this.#unusedInRestPattern] = bar; + if (wrappingExpressionType === "RestElement") { + return; + } + + // [this.#unusedInAssignmentPattern] = bar; + if (wrappingExpressionType === "ArrayPattern") { + return; + } + + /* + * We can't delete the memberDefinition, as we need to keep track of which member we are marking as used. + * In the case of nested classes, we only mark the first member we encounter as used. If you were to delete + * the member, then any subsequent usage could incorrectly mark the member of an encapsulating parent class + * as used, which is incorrect. + */ + memberDefinition.isUsed = true; + }, + + /* + * Post-process the class members and report any remaining members. + * Since private members can only be accessed in the current class context, + * we can safely assume that all usages are within the current class body. + */ + "ClassBody:exit"() { + const unusedPrivateMembers = trackedClasses.shift(); + + for (const [ + classMemberName, + { declaredNode, isUsed }, + ] of unusedPrivateMembers.entries()) { + if (isUsed) { + continue; + } + context.report({ + node: declaredNode, + loc: declaredNode.key.loc, + messageId: "unusedPrivateClassMember", + data: { + classMemberName: `#${classMemberName}`, + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unused-vars.js b/node_modules/eslint/lib/rules/no-unused-vars.js new file mode 100644 index 00000000..d29be30a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-vars.js @@ -0,0 +1,1712 @@ +/** + * @fileoverview Rule to flag declared but unused variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * A simple name for the types of variables that this rule supports + * @typedef {'array-destructure'|'catch-clause'|'parameter'|'variable'} VariableType + */ + +/** + * Bag of data used for formatting the `unusedVar` lint message. + * @typedef {Object} UnusedVarMessageData + * @property {string} varName The name of the unused var. + * @property {'defined'|'assigned a value'} action Description of the vars state. + * @property {string} additional Any additional info to be appended at the end. + */ + +/** + * Bag of data used for formatting the `usedIgnoredVar` lint message. + * @typedef {Object} UsedIgnoredVarMessageData + * @property {string} varName The name of the unused var. + * @property {string} additional Any additional info to be appended at the end. + */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow unused variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unused-vars", + }, + + hasSuggestions: true, + + schema: [ + { + oneOf: [ + { + enum: ["all", "local"], + }, + { + type: "object", + properties: { + vars: { + enum: ["all", "local"], + }, + varsIgnorePattern: { + type: "string", + }, + args: { + enum: ["all", "after-used", "none"], + }, + ignoreRestSiblings: { + type: "boolean", + }, + argsIgnorePattern: { + type: "string", + }, + caughtErrors: { + enum: ["all", "none"], + }, + caughtErrorsIgnorePattern: { + type: "string", + }, + destructuredArrayIgnorePattern: { + type: "string", + }, + ignoreClassWithStaticInitBlock: { + type: "boolean", + }, + reportUsedIgnorePattern: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + unusedVar: + "'{{varName}}' is {{action}} but never used{{additional}}.", + usedIgnoredVar: + "'{{varName}}' is marked as ignored but is used{{additional}}.", + removeVar: "Remove unused variable '{{varName}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const REST_PROPERTY_TYPE = + /^(?:RestElement|(?:Experimental)?RestProperty)$/u; + + const config = { + vars: "all", + args: "after-used", + ignoreRestSiblings: false, + caughtErrors: "all", + ignoreClassWithStaticInitBlock: false, + reportUsedIgnorePattern: false, + }; + + const firstOption = context.options[0]; + + if (firstOption) { + if (typeof firstOption === "string") { + config.vars = firstOption; + } else { + config.vars = firstOption.vars || config.vars; + config.args = firstOption.args || config.args; + config.ignoreRestSiblings = + firstOption.ignoreRestSiblings || config.ignoreRestSiblings; + config.caughtErrors = + firstOption.caughtErrors || config.caughtErrors; + config.ignoreClassWithStaticInitBlock = + firstOption.ignoreClassWithStaticInitBlock || + config.ignoreClassWithStaticInitBlock; + config.reportUsedIgnorePattern = + firstOption.reportUsedIgnorePattern || + config.reportUsedIgnorePattern; + + if (firstOption.varsIgnorePattern) { + config.varsIgnorePattern = new RegExp( + firstOption.varsIgnorePattern, + "u", + ); + } + + if (firstOption.argsIgnorePattern) { + config.argsIgnorePattern = new RegExp( + firstOption.argsIgnorePattern, + "u", + ); + } + + if (firstOption.caughtErrorsIgnorePattern) { + config.caughtErrorsIgnorePattern = new RegExp( + firstOption.caughtErrorsIgnorePattern, + "u", + ); + } + + if (firstOption.destructuredArrayIgnorePattern) { + config.destructuredArrayIgnorePattern = new RegExp( + firstOption.destructuredArrayIgnorePattern, + "u", + ); + } + } + } + + /** + * Determines what variable type a def is. + * @param {Object} def the declaration to check + * @returns {VariableType} a simple name for the types of variables that this rule supports + */ + function defToVariableType(def) { + /* + * This `destructuredArrayIgnorePattern` error report works differently from the catch + * clause and parameter error reports. _Both_ the `varsIgnorePattern` and the + * `destructuredArrayIgnorePattern` will be checked for array destructuring. However, + * for the purposes of the report, the currently defined behavior is to only inform the + * user of the `destructuredArrayIgnorePattern` if it's present (regardless of the fact + * that the `varsIgnorePattern` would also apply). If it's not present, the user will be + * informed of the `varsIgnorePattern`, assuming that's present. + */ + if ( + config.destructuredArrayIgnorePattern && + def.name.parent.type === "ArrayPattern" + ) { + return "array-destructure"; + } + + switch (def.type) { + case "CatchClause": + return "catch-clause"; + case "Parameter": + return "parameter"; + + default: + return "variable"; + } + } + + /** + * Gets a given variable's description and configured ignore pattern + * based on the provided variableType + * @param {VariableType} variableType a simple name for the types of variables that this rule supports + * @throws {Error} (Unreachable) + * @returns {[string | undefined, string | undefined]} the given variable's description and + * ignore pattern + */ + function getVariableDescription(variableType) { + let pattern; + let variableDescription; + + switch (variableType) { + case "array-destructure": + pattern = config.destructuredArrayIgnorePattern; + variableDescription = "elements of array destructuring"; + break; + + case "catch-clause": + pattern = config.caughtErrorsIgnorePattern; + variableDescription = "caught errors"; + break; + + case "parameter": + pattern = config.argsIgnorePattern; + variableDescription = "args"; + break; + + case "variable": + pattern = config.varsIgnorePattern; + variableDescription = "vars"; + break; + + default: + throw new Error( + `Unexpected variable type: ${variableType}`, + ); + } + + if (pattern) { + pattern = pattern.toString(); + } + + return [variableDescription, pattern]; + } + + /** + * Generates the message data about the variable being defined and unused, + * including the ignore pattern if configured. + * @param {Variable} unusedVar eslint-scope variable object. + * @returns {UnusedVarMessageData} The message data to be used with this unused variable. + */ + function getDefinedMessageData(unusedVar) { + const def = unusedVar.defs && unusedVar.defs[0]; + let additionalMessageData = ""; + + if (def) { + const [variableDescription, pattern] = getVariableDescription( + defToVariableType(def), + ); + + if (pattern && variableDescription) { + additionalMessageData = `. Allowed unused ${variableDescription} must match ${pattern}`; + } + } + + return { + varName: unusedVar.name, + action: "defined", + additional: additionalMessageData, + }; + } + + /** + * Generate the warning message about the variable being + * assigned and unused, including the ignore pattern if configured. + * @param {Variable} unusedVar eslint-scope variable object. + * @returns {UnusedVarMessageData} The message data to be used with this unused variable. + */ + function getAssignedMessageData(unusedVar) { + const def = unusedVar.defs && unusedVar.defs[0]; + let additionalMessageData = ""; + + if (def) { + const [variableDescription, pattern] = getVariableDescription( + defToVariableType(def), + ); + + if (pattern && variableDescription) { + additionalMessageData = `. Allowed unused ${variableDescription} must match ${pattern}`; + } + } + + return { + varName: unusedVar.name, + action: "assigned a value", + additional: additionalMessageData, + }; + } + + /** + * Generate the warning message about a variable being used even though + * it is marked as being ignored. + * @param {Variable} variable eslint-scope variable object + * @param {VariableType} variableType a simple name for the types of variables that this rule supports + * @returns {UsedIgnoredVarMessageData} The message data to be used with + * this used ignored variable. + */ + function getUsedIgnoredMessageData(variable, variableType) { + const [variableDescription, pattern] = + getVariableDescription(variableType); + + let additionalMessageData = ""; + + if (pattern && variableDescription) { + additionalMessageData = `. Used ${variableDescription} must not match ${pattern}`; + } + + return { + varName: variable.name, + additional: additionalMessageData, + }; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const STATEMENT_TYPE = /(?:Statement|Declaration)$/u; + + /** + * Determines if a given variable is being exported from a module. + * @param {Variable} variable eslint-scope variable object. + * @returns {boolean} True if the variable is exported, false if not. + * @private + */ + function isExported(variable) { + const definition = variable.defs[0]; + + if (definition) { + let node = definition.node; + + if (node.type === "VariableDeclarator") { + node = node.parent; + } else if (definition.type === "Parameter") { + return false; + } + + return node.parent.type.indexOf("Export") === 0; + } + return false; + } + + /** + * Checks whether a node is a sibling of the rest property or not. + * @param {ASTNode} node a node to check + * @returns {boolean} True if the node is a sibling of the rest property, otherwise false. + */ + function hasRestSibling(node) { + return ( + node.type === "Property" && + node.parent.type === "ObjectPattern" && + REST_PROPERTY_TYPE.test(node.parent.properties.at(-1).type) + ); + } + + /** + * Determines if a variable has a sibling rest property + * @param {Variable} variable eslint-scope variable object. + * @returns {boolean} True if the variable has a sibling rest property, false if not. + * @private + */ + function hasRestSpreadSibling(variable) { + if (config.ignoreRestSiblings) { + const hasRestSiblingDefinition = variable.defs.some(def => + hasRestSibling(def.name.parent), + ); + const hasRestSiblingReference = variable.references.some(ref => + hasRestSibling(ref.identifier.parent), + ); + + return hasRestSiblingDefinition || hasRestSiblingReference; + } + + return false; + } + + /** + * Determines if a reference is a read operation. + * @param {Reference} ref An eslint-scope Reference + * @returns {boolean} whether the given reference represents a read operation + * @private + */ + function isReadRef(ref) { + return ref.isRead(); + } + + /** + * Determine if an identifier is referencing an enclosing function name. + * @param {Reference} ref The reference to check. + * @param {ASTNode[]} nodes The candidate function nodes. + * @returns {boolean} True if it's a self-reference, false if not. + * @private + */ + function isSelfReference(ref, nodes) { + let scope = ref.from; + + while (scope) { + if (nodes.includes(scope.block)) { + return true; + } + + scope = scope.upper; + } + + return false; + } + + /** + * Gets a list of function definitions for a specified variable. + * @param {Variable} variable eslint-scope variable object. + * @returns {ASTNode[]} Function nodes. + * @private + */ + function getFunctionDefinitions(variable) { + const functionDefinitions = []; + + variable.defs.forEach(def => { + const { type, node } = def; + + // FunctionDeclarations + if (type === "FunctionName") { + functionDefinitions.push(node); + } + + // FunctionExpressions + if ( + type === "Variable" && + node.init && + (node.init.type === "FunctionExpression" || + node.init.type === "ArrowFunctionExpression") + ) { + functionDefinitions.push(node.init); + } + }); + return functionDefinitions; + } + + /** + * Checks the position of given nodes. + * @param {ASTNode} inner A node which is expected as inside. + * @param {ASTNode} outer A node which is expected as outside. + * @returns {boolean} `true` if the `inner` node exists in the `outer` node. + * @private + */ + function isInside(inner, outer) { + return ( + inner.range[0] >= outer.range[0] && + inner.range[1] <= outer.range[1] + ); + } + + /** + * Checks whether a given node is unused expression or not. + * @param {ASTNode} node The node itself + * @returns {boolean} The node is an unused expression. + * @private + */ + function isUnusedExpression(node) { + const parent = node.parent; + + if (parent.type === "ExpressionStatement") { + return true; + } + + if (parent.type === "SequenceExpression") { + const isLastExpression = parent.expressions.at(-1) === node; + + if (!isLastExpression) { + return true; + } + return isUnusedExpression(parent); + } + + return false; + } + + /** + * If a given reference is left-hand side of an assignment, this gets + * the right-hand side node of the assignment. + * + * In the following cases, this returns null. + * + * - The reference is not the LHS of an assignment expression. + * - The reference is inside of a loop. + * - The reference is inside of a function scope which is different from + * the declaration. + * @param {eslint-scope.Reference} ref A reference to check. + * @param {ASTNode} prevRhsNode The previous RHS node. + * @returns {ASTNode|null} The RHS node or null. + * @private + */ + function getRhsNode(ref, prevRhsNode) { + const id = ref.identifier; + const parent = id.parent; + const refScope = ref.from.variableScope; + const varScope = ref.resolved.scope.variableScope; + const canBeUsedLater = + refScope !== varScope || astUtils.isInLoop(id); + + /* + * Inherits the previous node if this reference is in the node. + * This is for `a = a + a`-like code. + */ + if (prevRhsNode && isInside(id, prevRhsNode)) { + return prevRhsNode; + } + + if ( + parent.type === "AssignmentExpression" && + isUnusedExpression(parent) && + id === parent.left && + !canBeUsedLater + ) { + return parent.right; + } + return null; + } + + /** + * Checks whether a given function node is stored to somewhere or not. + * If the function node is stored, the function can be used later. + * @param {ASTNode} funcNode A function node to check. + * @param {ASTNode} rhsNode The RHS node of the previous assignment. + * @returns {boolean} `true` if under the following conditions: + * - the funcNode is assigned to a variable. + * - the funcNode is bound as an argument of a function call. + * - the function is bound to a property and the object satisfies above conditions. + * @private + */ + function isStorableFunction(funcNode, rhsNode) { + let node = funcNode; + let parent = funcNode.parent; + + while (parent && isInside(parent, rhsNode)) { + switch (parent.type) { + case "SequenceExpression": + if (parent.expressions.at(-1) !== node) { + return false; + } + break; + + case "CallExpression": + case "NewExpression": + return parent.callee !== node; + + case "AssignmentExpression": + case "TaggedTemplateExpression": + case "YieldExpression": + return true; + + default: + if (STATEMENT_TYPE.test(parent.type)) { + /* + * If it encountered statements, this is a complex pattern. + * Since analyzing complex patterns is hard, this returns `true` to avoid false positive. + */ + return true; + } + } + + node = parent; + parent = parent.parent; + } + + return false; + } + + /** + * Checks whether a given Identifier node exists inside of a function node which can be used later. + * + * "can be used later" means: + * - the function is assigned to a variable. + * - the function is bound to a property and the object can be used later. + * - the function is bound as an argument of a function call. + * + * If a reference exists in a function which can be used later, the reference is read when the function is called. + * @param {ASTNode} id An Identifier node to check. + * @param {ASTNode} rhsNode The RHS node of the previous assignment. + * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later. + * @private + */ + function isInsideOfStorableFunction(id, rhsNode) { + const funcNode = astUtils.getUpperFunction(id); + + return ( + funcNode && + isInside(funcNode, rhsNode) && + isStorableFunction(funcNode, rhsNode) + ); + } + + /** + * Checks whether a given reference is a read to update itself or not. + * @param {eslint-scope.Reference} ref A reference to check. + * @param {ASTNode} rhsNode The RHS node of the previous assignment. + * @returns {boolean} The reference is a read to update itself. + * @private + */ + function isReadForItself(ref, rhsNode) { + const id = ref.identifier; + const parent = id.parent; + + return ( + ref.isRead() && + // self update. e.g. `a += 1`, `a++` + ((parent.type === "AssignmentExpression" && + parent.left === id && + isUnusedExpression(parent) && + !astUtils.isLogicalAssignmentOperator(parent.operator)) || + (parent.type === "UpdateExpression" && + isUnusedExpression(parent)) || + // in RHS of an assignment for itself. e.g. `a = a + 1` + (rhsNode && + isInside(id, rhsNode) && + !isInsideOfStorableFunction(id, rhsNode))) + ); + } + + /** + * Determine if an identifier is used either in for-in or for-of loops. + * @param {Reference} ref The reference to check. + * @returns {boolean} whether reference is used in the for-in loops + * @private + */ + function isForInOfRef(ref) { + let target = ref.identifier.parent; + + // "for (var ...) { return; }" + if (target.type === "VariableDeclarator") { + target = target.parent.parent; + } + + if ( + target.type !== "ForInStatement" && + target.type !== "ForOfStatement" + ) { + return false; + } + + // "for (...) { return; }" + if (target.body.type === "BlockStatement") { + target = target.body.body[0]; + + // "for (...) return;" + } else { + target = target.body; + } + + // For empty loop body + if (!target) { + return false; + } + + return target.type === "ReturnStatement"; + } + + /** + * Determines if the variable is used. + * @param {Variable} variable The variable to check. + * @returns {boolean} True if the variable is used + * @private + */ + function isUsedVariable(variable) { + if (variable.eslintUsed) { + return true; + } + + const functionNodes = getFunctionDefinitions(variable); + const isFunctionDefinition = functionNodes.length > 0; + + let rhsNode = null; + + return variable.references.some(ref => { + if (isForInOfRef(ref)) { + return true; + } + + const forItself = isReadForItself(ref, rhsNode); + + rhsNode = getRhsNode(ref, rhsNode); + + return ( + isReadRef(ref) && + !forItself && + !( + isFunctionDefinition && + isSelfReference(ref, functionNodes) + ) + ); + }); + } + + /** + * Checks whether the given variable is after the last used parameter. + * @param {eslint-scope.Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is defined after the last + * used parameter. + */ + function isAfterLastUsedArg(variable) { + const def = variable.defs[0]; + const params = sourceCode.getDeclaredVariables(def.node); + const posteriorParams = params.slice(params.indexOf(variable) + 1); + + // If any used parameters occur after this parameter, do not report. + return !posteriorParams.some( + v => v.references.length > 0 || v.eslintUsed, + ); + } + + /** + * Gets an array of variables without read references. + * @param {Scope} scope an eslint-scope Scope object. + * @param {Variable[]} unusedVars an array that saving result. + * @returns {Variable[]} unused variables of the scope and descendant scopes. + * @private + */ + function collectUnusedVariables(scope, unusedVars) { + const variables = scope.variables; + const childScopes = scope.childScopes; + let i, l; + + if (scope.type !== "global" || config.vars === "all") { + for (i = 0, l = variables.length; i < l; ++i) { + const variable = variables[i]; + + // skip a variable of class itself name in the class scope + if ( + scope.type === "class" && + scope.block.id === variable.identifiers[0] + ) { + continue; + } + + // skip function expression names + if (scope.functionExpressionScope) { + continue; + } + + // skip variables marked with markVariableAsUsed() + if ( + !config.reportUsedIgnorePattern && + variable.eslintUsed + ) { + continue; + } + + // skip implicit "arguments" variable + if ( + scope.type === "function" && + variable.name === "arguments" && + variable.identifiers.length === 0 + ) { + continue; + } + + // explicit global variables don't have definitions. + const def = variable.defs[0]; + + if (def) { + const type = def.type; + const refUsedInArrayPatterns = variable.references.some( + ref => + ref.identifier.parent.type === "ArrayPattern", + ); + + // skip elements of array destructuring patterns + if ( + (def.name.parent.type === "ArrayPattern" || + refUsedInArrayPatterns) && + config.destructuredArrayIgnorePattern && + config.destructuredArrayIgnorePattern.test( + def.name.name, + ) + ) { + if ( + config.reportUsedIgnorePattern && + isUsedVariable(variable) + ) { + context.report({ + node: def.name, + messageId: "usedIgnoredVar", + data: getUsedIgnoredMessageData( + variable, + "array-destructure", + ), + }); + } + + continue; + } + + if (type === "ClassName") { + const hasStaticBlock = def.node.body.body.some( + node => node.type === "StaticBlock", + ); + + if ( + config.ignoreClassWithStaticInitBlock && + hasStaticBlock + ) { + continue; + } + } + + // skip catch variables + if (type === "CatchClause") { + if (config.caughtErrors === "none") { + continue; + } + + // skip ignored parameters + if ( + config.caughtErrorsIgnorePattern && + config.caughtErrorsIgnorePattern.test( + def.name.name, + ) + ) { + if ( + config.reportUsedIgnorePattern && + isUsedVariable(variable) + ) { + context.report({ + node: def.name, + messageId: "usedIgnoredVar", + data: getUsedIgnoredMessageData( + variable, + "catch-clause", + ), + }); + } + + continue; + } + } else if (type === "Parameter") { + // skip any setter argument + if ( + (def.node.parent.type === "Property" || + def.node.parent.type === + "MethodDefinition") && + def.node.parent.kind === "set" + ) { + continue; + } + + // if "args" option is "none", skip any parameter + if (config.args === "none") { + continue; + } + + // skip ignored parameters + if ( + config.argsIgnorePattern && + config.argsIgnorePattern.test(def.name.name) + ) { + if ( + config.reportUsedIgnorePattern && + isUsedVariable(variable) + ) { + context.report({ + node: def.name, + messageId: "usedIgnoredVar", + data: getUsedIgnoredMessageData( + variable, + "parameter", + ), + }); + } + + continue; + } + + // if "args" option is "after-used", skip used variables + if ( + config.args === "after-used" && + astUtils.isFunction(def.name.parent) && + !isAfterLastUsedArg(variable) + ) { + continue; + } + } else { + // skip ignored variables + if ( + config.varsIgnorePattern && + config.varsIgnorePattern.test(def.name.name) + ) { + if ( + config.reportUsedIgnorePattern && + isUsedVariable(variable) + ) { + context.report({ + node: def.name, + messageId: "usedIgnoredVar", + data: getUsedIgnoredMessageData( + variable, + "variable", + ), + }); + } + + continue; + } + } + } + + if ( + !isUsedVariable(variable) && + !isExported(variable) && + !hasRestSpreadSibling(variable) + ) { + unusedVars.push(variable); + } + } + } + + for (i = 0, l = childScopes.length; i < l; ++i) { + collectUnusedVariables(childScopes[i], unusedVars); + } + + return unusedVars; + } + + /** + * fixes unused variables + * @param {Object} fixer fixer object + * @param {Object} unusedVar unused variable to fix + * @returns {Object} fixer object + */ + function handleFixes(fixer, unusedVar) { + const id = unusedVar.identifiers[0]; + const parent = id.parent; + const parentType = parent.type; + const tokenBefore = sourceCode.getTokenBefore(id); + const tokenAfter = sourceCode.getTokenAfter(id); + const isFunction = astUtils.isFunction; + const isLoop = astUtils.isLoop; + const allWriteReferences = unusedVar.references.filter(ref => + ref.isWrite(), + ); + + /** + * get range from token before of a given node + * @param {ASTNode} node node of identifier + * @param {number} skips number of token to skip + * @returns {number} start range of token before the identifier + */ + function getPreviousTokenStart(node, skips) { + return sourceCode.getTokenBefore(node, skips).range[0]; + } + + /** + * get range to token after of a given node + * @param {ASTNode} node node of identifier + * @param {number} skips number of token to skip + * @returns {number} end range of token after the identifier + */ + function getNextTokenEnd(node, skips) { + return sourceCode.getTokenAfter(node, skips).range[1]; + } + + /** + * get the value of token before of a given node + * @param {ASTNode} node node of identifier + * @returns {string} value of token before the identifier + */ + function getTokenBeforeValue(node) { + return sourceCode.getTokenBefore(node).value; + } + + /** + * get the value of token after of a given node + * @param {ASTNode} node node of identifier + * @returns {string} value of token after the identifier + */ + function getTokenAfterValue(node) { + return sourceCode.getTokenAfter(node).value; + } + + /** + * Check if an array has a single element with null as other element. + * @param {ASTNode} node ArrayPattern node + * @returns {boolean} true if array has single element with other null elements + */ + function hasSingleElement(node) { + return node.elements.filter(e => e !== null).length === 1; + } + + /** + * check whether import specifier has an import of particular type + * @param {ASTNode} node ImportDeclaration node + * @param {string} type type of import to check + * @returns {boolean} true if import specifier has import of specified type + */ + function hasImportOfCertainType(node, type) { + return node.specifiers.some(e => e.type === type); + } + + /** + * Check whether declaration is safe to remove or not + * @param {ASTNode} nextToken next token of unused variable + * @param {ASTNode} prevToken previous token of unused variable + * @returns {boolean} true if declaration is not safe to remove + */ + function isDeclarationNotSafeToRemove(nextToken, prevToken) { + return ( + nextToken.type === "String" || + (prevToken && + !astUtils.isSemicolonToken(prevToken) && + !astUtils.isOpeningBraceToken(prevToken)) + ); + } + + /** + * give fixes for unused variables in function parameters + * @param {ASTNode} node node to check + * @returns {Object} fixer object + */ + function fixFunctionParameters(node) { + const parentNode = node.parent; + + if (isFunction(parentNode)) { + // remove unused function parameter if there is only a single parameter + if (parentNode.params.length === 1) { + return fixer.removeRange(node.range); + } + + // remove first unused function parameter when there are multiple parameters + if ( + getTokenBeforeValue(node) === "(" && + getTokenAfterValue(node) === "," + ) { + return fixer.removeRange([ + node.range[0], + getNextTokenEnd(node), + ]); + } + + // remove unused function parameters except first one when there are multiple parameters + return fixer.removeRange([ + getPreviousTokenStart(node), + node.range[1], + ]); + } + + return null; + } + + /** + * fix unused variable declarations and function parameters + * @param {ASTNode} node parent node to identifier + * @returns {Object} fixer object + */ + function fixVariables(node) { + const parentNode = node.parent; + + // remove unused declared variables such as var a = b; or var a = b, c; + if (parentNode.type === "VariableDeclarator") { + // skip variable in for (const [ foo ] of bar); + if (isLoop(parentNode.parent.parent)) { + return null; + } + + /* + * remove unused declared variable with single declaration such as 'var a = b;' + * remove complete declaration when there is an unused variable in 'const { a } = foo;', same for arrays. + */ + if (parentNode.parent.declarations.length === 1) { + // if next token is a string it could become a directive if node is removed -> no suggestion. + const nextToken = sourceCode.getTokenAfter( + parentNode.parent, + ); + + // if previous token exists and is not ";" or "{" not sure about ASI rules -> no suggestion. + const prevToken = sourceCode.getTokenBefore( + parentNode.parent, + ); + + if ( + nextToken && + isDeclarationNotSafeToRemove(nextToken, prevToken) + ) { + return null; + } + + return fixer.removeRange(parentNode.parent.range); + } + + /* + * remove unused declared variable with multiple declaration except first one such as 'var a = b, c = d;' + * fix 'let bar = "hello", { a } = foo;' to 'let bar = "hello";' if 'a' is unused, same for arrays. + */ + if (getTokenBeforeValue(parentNode) === ",") { + return fixer.removeRange([ + getPreviousTokenStart(parentNode), + parentNode.range[1], + ]); + } + + /* + * remove first unused declared variable when there are multiple declarations + * fix 'let { a } = foo, bar = "hello";' to 'let bar = "hello";' if 'a' is unused, same for arrays. + */ + return fixer.removeRange([ + parentNode.range[0], + getNextTokenEnd(parentNode), + ]); + } + + // fixes [{a: {k}}], [{a: [k]}] + if (getTokenBeforeValue(node) === ":") { + if (parentNode.parent.type === "ObjectPattern") { + // eslint-disable-next-line no-use-before-define -- due to interdependency of functions + return fixObjectWithValueSeparator(node); + } + } + + // fix unused function parameters + return fixFunctionParameters(node); + } + + /** + * fix nested object like { a: { b } } + * @param {ASTNode} node parent node to check + * @returns {Object} fixer object + */ + function fixNestedObjectVariable(node) { + const parentNode = node.parent; + + // fix for { a: { b: { c: { d } } } } + if ( + parentNode.parent.parent.parent.type === "ObjectPattern" && + parentNode.parent.properties.length === 1 + ) { + return fixNestedObjectVariable(parentNode.parent); + } + + // fix for { a: { b } } + if (parentNode.parent.type === "ObjectPattern") { + // fix for unused variables in dectructured object with single property in variable decalartion and function parameter + if (parentNode.parent.properties.length === 1) { + return fixVariables(parentNode.parent); + } + + // fix for first unused property when there are multiple properties such as '{ a: { b }, c }' + if (getTokenBeforeValue(parentNode) === "{") { + return fixer.removeRange([ + parentNode.range[0], + getNextTokenEnd(parentNode), + ]); + } + + // fix for unused property except first one when there are multiple properties such as '{ k, a: { b } }' + return fixer.removeRange([ + getPreviousTokenStart(parentNode), + parentNode.range[1], + ]); + } + + return null; + } + + /** + * fix unused variables in array and nested array + * @param {ASTNode} node parent node to check + * @returns {Object} fixer object + */ + function fixNestedArrayVariable(node) { + const parentNode = node.parent; + + // fix for nested arrays [[ a ]] + if ( + parentNode.parent.type === "ArrayPattern" && + hasSingleElement(parentNode) + ) { + return fixNestedArrayVariable(parentNode); + } + + if (hasSingleElement(parentNode)) { + // fixes { a: [{ b }] } or { a: [[ b ]] } + if (getTokenBeforeValue(parentNode) === ":") { + return fixVariables(parentNode); + } + + // fixes [a, ...[[ b ]]] or [a, ...[{ b }]] + if (parentNode.parent.type === "RestElement") { + // eslint-disable-next-line no-use-before-define -- due to interdependency of functions + return fixRestInPattern(parentNode.parent); + } + + // fix unused variables in destructured array in variable declaration or function parameter + return fixVariables(parentNode); + } + + // remove last unused array element + if ( + getTokenBeforeValue(node) === "," && + getTokenAfterValue(node) === "]" + ) { + return fixer.removeRange([ + getPreviousTokenStart(node), + node.range[1], + ]); + } + + // remove unused array element + return fixer.removeRange(node.range); + } + + /** + * fix cases like {a: {k}} or {a: [k]} + * @param {ASTNode} node parent node to check + * @returns {Object} fixer object + */ + function fixObjectWithValueSeparator(node) { + const parentNode = node.parent.parent; + + // fix cases like [{a : { b }}] or [{a : [ b ]}] + if ( + parentNode.parent.type === "ArrayPattern" && + parentNode.properties.length === 1 + ) { + return fixNestedArrayVariable(parentNode); + } + + // fix cases like {a: {k}} or {a: [k]} + return fixNestedObjectVariable(node); + } + + /** + * fix ...[[a]] or ...[{a}] like patterns + * @param {ASTNode} node parent node to check + * @returns {Object} fixer object + */ + function fixRestInPattern(node) { + const parentNode = node.parent; + + // fix ...[[a]] or ...[{a}] in function parameters + if (isFunction(parentNode)) { + if (parentNode.params.length === 1) { + return fixer.removeRange(node.range); + } + + return fixer.removeRange([ + getPreviousTokenStart(node), + node.range[1], + ]); + } + + // fix rest in nested array pattern like [[a, ...[b]]] + if (parentNode.type === "ArrayPattern") { + // fix [[...[b]]] + if (hasSingleElement(parentNode)) { + if (parentNode.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parentNode); + } + + // fix 'const [...[b]] = foo; and function foo([...[b]]) {} + return fixVariables(parentNode); + } + + // fix [[a, ...[b]]] + return fixer.removeRange([ + getPreviousTokenStart(node), + node.range[1], + ]); + } + + return null; + } + + // skip fix when variable has references that would be left behind + if ( + allWriteReferences.some( + ref => ref.identifier.range[0] !== id.range[0], + ) + ) { + return null; + } + + // remove declared variables such as var a; or var a, b; + if (parentType === "VariableDeclarator") { + if (parent.parent.declarations.length === 1) { + // prevent fix of variable in forOf and forIn loops. + if ( + isLoop(parent.parent.parent) && + parent.parent.parent.body !== parent.parent + ) { + return null; + } + + // removes only variable not semicolon in 'if (foo()) var bar;' or in 'loops' or in 'with' statement. + if ( + parent.parent.parent.type === "IfStatement" || + isLoop(parent.parent.parent) || + (parent.parent.parent.type === "WithStatement" && + parent.parent.parent.body === parent.parent) + ) { + return fixer.replaceText(parent.parent, ";"); + } + + // if next token is a string it could become a directive if node is removed -> no suggestion. + const nextToken = sourceCode.getTokenAfter(parent.parent); + + // if previous token exists and is not ";" or "{" not sure about ASI rules -> no suggestion. + const prevToken = sourceCode.getTokenBefore(parent.parent); + + if ( + nextToken && + isDeclarationNotSafeToRemove(nextToken, prevToken) + ) { + return null; + } + + // remove unused declared variable with single declaration like 'var a = b;' + return fixer.removeRange(parent.parent.range); + } + + // remove unused declared variable with multiple declaration except first one like 'var a = b, c = d;' + if (tokenBefore.value === ",") { + return fixer.removeRange([ + tokenBefore.range[0], + parent.range[1], + ]); + } + + // remove first unused declared variable when there are multiple declarations + return fixer.removeRange([ + parent.range[0], + getNextTokenEnd(parent), + ]); + } + + // remove variables in object patterns + if (parent.parent.type === "ObjectPattern") { + if (parent.parent.properties.length === 1) { + // fix [a, ...{b}] + if (parent.parent.parent.type === "RestElement") { + return fixRestInPattern(parent.parent.parent); + } + + // fix [{ a }] + if (parent.parent.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parent.parent); + } + + /* + * var {a} = foo; + * function a({a}) {} + * fix const { a: { b } } = foo; + */ + return fixVariables(parent.parent); + } + + // fix const { a:b } = foo; + if (tokenBefore.value === ":") { + // remove first unused variable in const { a:b } = foo; + if ( + getTokenBeforeValue(parent) === "{" && + getTokenAfterValue(parent) === "," + ) { + return fixer.removeRange([ + parent.range[0], + getNextTokenEnd(parent), + ]); + } + + // remove unused variables in const { a: b, c: d } = foo; except first one + return fixer.removeRange([ + getPreviousTokenStart(parent), + id.range[1], + ]); + } + } + + // remove unused variables inside an array + if (parentType === "ArrayPattern") { + if (hasSingleElement(parent)) { + // fix [a, ...[b]] + if (parent.parent.type === "RestElement") { + return fixRestInPattern(parent.parent); + } + + // fix [ [a] ] + if (parent.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parent); + } + + /* + * fix var [a] = foo; + * fix function foo([a]) {} + * fix const { a: [b] } = foo; + */ + return fixVariables(parent); + } + + // if "a" is unused in [a, b ,c] fixes to [, b, c] + if (tokenBefore.value === "," && tokenAfter.value === ",") { + return fixer.removeRange(id.range); + } + } + + // remove unused rest elements + if (parentType === "RestElement") { + // fix [a, ...rest] + if (parent.parent.type === "ArrayPattern") { + if (hasSingleElement(parent.parent)) { + // fix [[...rest]] when there is only rest element + if (parent.parent.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parent.parent); + } + + // fix 'const [...rest] = foo;' and 'function foo([...rest]) {}' + return fixVariables(parent.parent); + } + + // fix [a, ...rest] + return fixer.removeRange([ + getPreviousTokenStart(id, 1), + id.range[1], + ]); + } + + // fix { a, ...rest} + if (parent.parent.type === "ObjectPattern") { + // fix 'const {...rest} = foo;' and 'function foo({...rest}) {}' + if (parent.parent.properties.length === 1) { + return fixVariables(parent.parent); + } + + // fix { a, ...rest} when there are multiple properties + return fixer.removeRange([ + getPreviousTokenStart(id, 1), + id.range[1], + ]); + } + + // fix function foo(...rest) {} + if (isFunction(parent.parent)) { + // remove unused rest in function parameter if there is only single parameter + if (parent.parent.params.length === 1) { + return fixer.removeRange(parent.range); + } + + // remove unused rest in function parameter if there multiple parameter + return fixer.removeRange([ + getPreviousTokenStart(parent), + parent.range[1], + ]); + } + } + + if (parentType === "AssignmentPattern") { + // fix [a = aDefault] + if (parent.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parent); + } + + // fix {a = aDefault} + if (parent.parent.parent.type === "ObjectPattern") { + if (parent.parent.parent.properties.length === 1) { + // fixes [{a = aDefault}] + if ( + parent.parent.parent.parent.type === "ArrayPattern" + ) { + return fixNestedArrayVariable(parent.parent.parent); + } + + // fix 'const {a = aDefault} = foo;' and 'function foo({a = aDefault}) {}' + return fixVariables(parent.parent.parent); + } + + // fix unused 'a' in {a = aDefault} if it is the first property + if ( + getTokenBeforeValue(parent.parent) === "{" && + getTokenAfterValue(parent.parent) === "," + ) { + return fixer.removeRange([ + parent.parent.range[0], + getNextTokenEnd(parent.parent), + ]); + } + + // fix unused 'b' in {a, b = aDefault} if it is not the first property + return fixer.removeRange([ + getPreviousTokenStart(parent.parent), + parent.parent.range[1], + ]); + } + + // fix unused assignment patterns in function parameters + if (isFunction(parent.parent)) { + return fixFunctionParameters(parent); + } + } + + // remove unused functions + if (parentType === "FunctionDeclaration" && parent.id === id) { + return fixer.removeRange(parent.range); + } + + // remove unused default import + if (parentType === "ImportDefaultSpecifier") { + // remove unused default import when there are not other imports + if ( + !hasImportOfCertainType(parent.parent, "ImportSpecifier") && + !hasImportOfCertainType( + parent.parent, + "ImportNamespaceSpecifier", + ) + ) { + return fixer.removeRange([ + parent.range[0], + parent.parent.source.range[0], + ]); + } + + // remove unused default import when there are other imports also + return fixer.removeRange([id.range[0], tokenAfter.range[1]]); + } + + if (parentType === "ImportSpecifier") { + // remove unused imports when there is a single import + if ( + parent.parent.specifiers.filter( + e => e.type === "ImportSpecifier", + ).length === 1 + ) { + // remove unused import when there is no default import + if ( + !hasImportOfCertainType( + parent.parent, + "ImportDefaultSpecifier", + ) + ) { + return fixer.removeRange(parent.parent.range); + } + + // fixes "import foo from 'module';" to "import 'module';" + return fixer.removeRange([ + getPreviousTokenStart(parent, 1), + tokenAfter.range[1], + ]); + } + + if (getTokenBeforeValue(parent) === "{") { + return fixer.removeRange([ + parent.range[0], + getNextTokenEnd(parent), + ]); + } + + return fixer.removeRange([ + getPreviousTokenStart(parent), + parent.range[1], + ]); + } + + if (parentType === "ImportNamespaceSpecifier") { + if ( + hasImportOfCertainType( + parent.parent, + "ImportDefaultSpecifier", + ) + ) { + return fixer.removeRange([ + getPreviousTokenStart(parent), + parent.range[1], + ]); + } + + // fixes "import * as foo from 'module';" to "import 'module';" + return fixer.removeRange([ + parent.range[0], + parent.parent.source.range[0], + ]); + } + + // skip error in catch(error) variable + if (parentType === "CatchClause") { + return null; + } + + // remove unused declared classes + if (parentType === "ClassDeclaration") { + return fixer.removeRange(parent.range); + } + + // remove unused variable that is in a sequence [a,b] fixes to [a] + if (tokenBefore?.value === ",") { + return fixer.removeRange([tokenBefore.range[0], id.range[1]]); + } + + // remove unused variable that is in a sequence inside function arguments and object pattern + if (tokenAfter.value === ",") { + // fix function foo(a, b) {} + if (tokenBefore.value === "(") { + return fixer.removeRange([ + id.range[0], + tokenAfter.range[1], + ]); + } + + // fix const {a, b} = foo; + if (tokenBefore.value === "{") { + return fixer.removeRange([ + id.range[0], + tokenAfter.range[1], + ]); + } + } + + if ( + parentType === "ArrowFunctionExpression" && + parent.params.length === 1 && + tokenAfter?.value !== ")" + ) { + return fixer.replaceText(id, "()"); + } + + return fixer.removeRange(id.range); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program:exit"(programNode) { + const unusedVars = collectUnusedVariables( + sourceCode.getScope(programNode), + [], + ); + + for (let i = 0, l = unusedVars.length; i < l; ++i) { + const unusedVar = unusedVars[i]; + + // Report the first declaration. + if (unusedVar.defs.length > 0) { + // report last write reference, https://github.com/eslint/eslint/issues/14324 + const writeReferences = unusedVar.references.filter( + ref => + ref.isWrite() && + ref.from.variableScope === + unusedVar.scope.variableScope, + ); + + let referenceToReport; + + if (writeReferences.length > 0) { + referenceToReport = writeReferences.at(-1); + } + + context.report({ + node: referenceToReport + ? referenceToReport.identifier + : unusedVar.identifiers[0], + messageId: "unusedVar", + data: unusedVar.references.some(ref => + ref.isWrite(), + ) + ? getAssignedMessageData(unusedVar) + : getDefinedMessageData(unusedVar), + suggest: [ + { + messageId: "removeVar", + data: { + varName: unusedVar.name, + }, + fix(fixer) { + return handleFixes(fixer, unusedVar); + }, + }, + ], + }); + + // If there are no regular declaration, report the first `/*globals*/` comment directive. + } else if (unusedVar.eslintExplicitGlobalComments) { + const directiveComment = + unusedVar.eslintExplicitGlobalComments[0]; + + context.report({ + node: programNode, + loc: astUtils.getNameLocationInGlobalDirectiveComment( + sourceCode, + directiveComment, + unusedVar.name, + ), + messageId: "unusedVar", + data: getDefinedMessageData(unusedVar), + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-use-before-define.js b/node_modules/eslint/lib/rules/no-use-before-define.js new file mode 100644 index 00000000..870a3679 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-use-before-define.js @@ -0,0 +1,446 @@ +/** + * @fileoverview Rule to flag use of variables before they are defined + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_TYPE = + /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u; +const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u; + +/** + * Parses a given value as options. + * @param {any} options A value to parse. + * @returns {Object} The parsed options. + */ +function parseOptions(options) { + if (typeof options === "object" && options !== null) { + return options; + } + + const functions = typeof options === "string" ? options !== "nofunc" : true; + + return { + functions, + classes: true, + variables: true, + allowNamedExports: false, + enums: true, + typedefs: true, + ignoreTypeReferences: true, + }; +} + +/** + * Checks whether or not a given location is inside of the range of a given node. + * @param {ASTNode} node An node to check. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of the range of the node. + */ +function isInRange(node, location) { + return node && node.range[0] <= location && location <= node.range[1]; +} + +/** + * Checks whether or not a given location is inside of the range of a class static initializer. + * Static initializers are static blocks and initializers of static fields. + * @param {ASTNode} node `ClassBody` node to check static initializers. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of a class static initializer. + */ +function isInClassStaticInitializerRange(node, location) { + return node.body.some( + classMember => + (classMember.type === "StaticBlock" && + isInRange(classMember, location)) || + (classMember.type === "PropertyDefinition" && + classMember.static && + classMember.value && + isInRange(classMember.value, location)), + ); +} + +/** + * Checks whether a given scope is the scope of a class static initializer. + * Static initializers are static blocks and initializers of static fields. + * @param {eslint-scope.Scope} scope A scope to check. + * @returns {boolean} `true` if the scope is a class static initializer scope. + */ +function isClassStaticInitializerScope(scope) { + if (scope.type === "class-static-block") { + return true; + } + + if (scope.type === "class-field-initializer") { + // `scope.block` is PropertyDefinition#value node + const propertyDefinition = scope.block.parent; + + return propertyDefinition.static; + } + + return false; +} + +/** + * Checks whether a given reference is evaluated in an execution context + * that isn't the one where the variable it refers to is defined. + * Execution contexts are: + * - top-level + * - functions + * - class field initializers (implicit functions) + * - class static blocks (implicit functions) + * Static class field initializers and class static blocks are automatically run during the class definition evaluation, + * and therefore we'll consider them as a part of the parent execution context. + * Example: + * + * const x = 1; + * + * x; // returns `false` + * () => x; // returns `true` + * + * class C { + * field = x; // returns `true` + * static field = x; // returns `false` + * + * method() { + * x; // returns `true` + * } + * + * static method() { + * x; // returns `true` + * } + * + * static { + * x; // returns `false` + * } + * } + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is from a separate execution context. + */ +function isFromSeparateExecutionContext(reference) { + const variable = reference.resolved; + let scope = reference.from; + + // Scope#variableScope represents execution context + while (variable.scope.variableScope !== scope.variableScope) { + if (isClassStaticInitializerScope(scope.variableScope)) { + scope = scope.variableScope.upper; + } else { + return true; + } + } + + return false; +} + +/** + * Checks whether or not a given reference is evaluated during the initialization of its variable. + * + * This returns `true` in the following cases: + * + * var a = a + * var [a = a] = list + * var {a = a} = obj + * for (var a in a) {} + * for (var a of a) {} + * var C = class { [C]; }; + * var C = class { static foo = C; }; + * var C = class { static { foo = C; } }; + * class C extends C {} + * class C extends (class { static foo = C; }) {} + * class C { [C]; } + * @param {Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is evaluated during the initialization. + */ +function isEvaluatedDuringInitialization(reference) { + if (isFromSeparateExecutionContext(reference)) { + /* + * Even if the reference appears in the initializer, it isn't evaluated during the initialization. + * For example, `const x = () => x;` is valid. + */ + return false; + } + + const location = reference.identifier.range[1]; + const definition = reference.resolved.defs[0]; + + if (definition.type === "ClassName") { + // `ClassDeclaration` or `ClassExpression` + const classDefinition = definition.node; + + return ( + isInRange(classDefinition, location) && + /* + * Class binding is initialized before running static initializers. + * For example, `class C { static foo = C; static { bar = C; } }` is valid. + */ + !isInClassStaticInitializerRange(classDefinition.body, location) + ); + } + + let node = definition.name.parent; + + while (node) { + if (node.type === "VariableDeclarator") { + if (isInRange(node.init, location)) { + return true; + } + if ( + FOR_IN_OF_TYPE.test(node.parent.parent.type) && + isInRange(node.parent.parent.right, location) + ) { + return true; + } + break; + } else if (node.type === "AssignmentPattern") { + if (isInRange(node.right, location)) { + return true; + } + } else if (SENTINEL_TYPE.test(node.type)) { + break; + } + + node = node.parent; + } + + return false; +} + +/** + * check whether the reference contains a type query. + * @param {ASTNode} node Identifier node to check. + * @returns {boolean} true if reference contains type query. + */ +function referenceContainsTypeQuery(node) { + switch (node.type) { + case "TSTypeQuery": + return true; + + case "TSQualifiedName": + case "Identifier": + return referenceContainsTypeQuery(node.parent); + + default: + // if we find a different node, there's no chance that we're in a TSTypeQuery + return false; + } +} + +/** + * Decorators are transpiled such that the decorator is placed after the class declaration + * So it is considered safe + * @param {Variable} variable The variable to check. + * @param {Reference} reference The reference to check. + * @returns {boolean} `true` if the reference is in a class decorator. + */ +function isClassRefInClassDecorator(variable, reference) { + if (variable.defs[0].type !== "ClassName") { + return false; + } + + if ( + !variable.defs[0].node.decorators || + variable.defs[0].node.decorators.length === 0 + ) { + return false; + } + + for (const deco of variable.defs[0].node.decorators) { + if ( + reference.identifier.range[0] >= deco.range[0] && + reference.identifier.range[1] <= deco.range[1] + ) { + return true; + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "problem", + + docs: { + description: + "Disallow the use of variables before they are defined", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-use-before-define", + }, + + schema: [ + { + oneOf: [ + { + enum: ["nofunc"], + }, + { + type: "object", + properties: { + functions: { type: "boolean" }, + classes: { type: "boolean" }, + variables: { type: "boolean" }, + allowNamedExports: { type: "boolean" }, + enums: { type: "boolean" }, + typedefs: { type: "boolean" }, + ignoreTypeReferences: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + }, + ], + + defaultOptions: [ + { + classes: true, + functions: true, + variables: true, + allowNamedExports: false, + enums: true, + typedefs: true, + ignoreTypeReferences: true, + }, + ], + + messages: { + usedBeforeDefined: "'{{name}}' was used before it was defined.", + }, + }, + + create(context) { + const options = parseOptions(context.options[0]); + const sourceCode = context.sourceCode; + + /** + * Determines whether a given reference should be checked. + * + * Returns `false` if the reference is: + * - initialization's (e.g., `let a = 1`). + * - referring to an undefined variable (i.e., if it's an unresolved reference). + * - referring to a variable that is defined, but not in the given source code + * (e.g., global environment variable or `arguments` in functions). + * - allowed by options. + * @param {eslint-scope.Reference} reference The reference + * @returns {boolean} `true` if the reference should be checked + */ + function shouldCheck(reference) { + if (reference.init) { + return false; + } + + const { identifier } = reference; + + if ( + options.allowNamedExports && + identifier.parent.type === "ExportSpecifier" && + identifier.parent.local === identifier + ) { + return false; + } + + const variable = reference.resolved; + + if (!variable || variable.defs.length === 0) { + return false; + } + + const definitionType = variable.defs[0].type; + + if (!options.functions && definitionType === "FunctionName") { + return false; + } + + if ( + ((!options.variables && definitionType === "Variable") || + (!options.classes && definitionType === "ClassName")) && + // don't skip checking the reference if it's in the same execution context, because of TDZ + isFromSeparateExecutionContext(reference) + ) { + return false; + } + + if (!options.enums && definitionType === "TSEnumName") { + return false; + } + + if (!options.typedefs && definitionType === "Type") { + return false; + } + + if ( + options.ignoreTypeReferences && + (referenceContainsTypeQuery(identifier) || + identifier.parent.type === "TSTypeReference") + ) { + return false; + } + + // skip nested namespace aliases as variable references + if (identifier.parent.type === "TSQualifiedName") { + let currentNode = identifier.parent; + + while (currentNode.type === "TSQualifiedName") { + currentNode = currentNode.left; + } + + if (currentNode === identifier) { + return true; + } + + return false; + } + + if (isClassRefInClassDecorator(variable, reference)) { + return false; + } + + return true; + } + + /** + * Finds and validates all references in a given scope and its child scopes. + * @param {eslint-scope.Scope} scope The scope object. + * @returns {void} + */ + function checkReferencesInScope(scope) { + scope.references.filter(shouldCheck).forEach(reference => { + const variable = reference.resolved; + const definitionIdentifier = variable.defs[0].name; + + if ( + reference.identifier.range[1] < + definitionIdentifier.range[1] || + (isEvaluatedDuringInitialization(reference) && + reference.identifier.parent.type !== "TSTypeReference") + ) { + context.report({ + node: reference.identifier, + messageId: "usedBeforeDefined", + data: reference.identifier, + }); + } + }); + + scope.childScopes.forEach(checkReferencesInScope); + } + + return { + Program(node) { + checkReferencesInScope(sourceCode.getScope(node)); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-assignment.js b/node_modules/eslint/lib/rules/no-useless-assignment.js new file mode 100644 index 00000000..78674463 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-assignment.js @@ -0,0 +1,654 @@ +/** + * @fileoverview A rule to disallow unnecessary assignments`. + * @author Yosuke Ota + */ + +"use strict"; + +const { findVariable } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("estree").Node} ASTNode */ +/** @typedef {import("estree").Pattern} Pattern */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").VariableDeclarator} VariableDeclarator */ +/** @typedef {import("estree").AssignmentExpression} AssignmentExpression */ +/** @typedef {import("estree").UpdateExpression} UpdateExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("../linter/code-path-analysis/code-path")} CodePath */ +/** @typedef {import("../linter/code-path-analysis/code-path-segment")} CodePathSegment */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Extract identifier from the given pattern node used on the left-hand side of the assignment. + * @param {Pattern} pattern The pattern node to extract identifier + * @returns {Iterable} The extracted identifier + */ +function* extractIdentifiersFromPattern(pattern) { + switch (pattern.type) { + case "Identifier": + yield pattern; + return; + case "ObjectPattern": + for (const property of pattern.properties) { + yield* extractIdentifiersFromPattern( + property.type === "Property" ? property.value : property, + ); + } + return; + case "ArrayPattern": + for (const element of pattern.elements) { + if (!element) { + continue; + } + yield* extractIdentifiersFromPattern(element); + } + return; + case "RestElement": + yield* extractIdentifiersFromPattern(pattern.argument); + return; + case "AssignmentPattern": + yield* extractIdentifiersFromPattern(pattern.left); + + // no default + } +} + +/** + * Checks whether the given identifier node is evaluated after the assignment identifier. + * @param {AssignmentInfo} assignment The assignment info. + * @param {Identifier} identifier The identifier to check. + * @returns {boolean} `true` if the given identifier node is evaluated after the assignment identifier. + */ +function isIdentifierEvaluatedAfterAssignment(assignment, identifier) { + if (identifier.range[0] < assignment.identifier.range[1]) { + return false; + } + if ( + assignment.expression && + assignment.expression.range[0] <= identifier.range[0] && + identifier.range[1] <= assignment.expression.range[1] + ) { + /* + * The identifier node is in an expression that is evaluated before the assignment. + * e.g. x = id; + * ^^ identifier to check + * ^ assignment identifier + */ + return false; + } + + /* + * e.g. + * x = 42; id; + * ^^ identifier to check + * ^ assignment identifier + * let { x, y = id } = obj; + * ^^ identifier to check + * ^ assignment identifier + */ + return true; +} + +/** + * Checks whether the given identifier node is used between the assigned identifier and the equal sign. + * + * e.g. let { x, y = x } = obj; + * ^ identifier to check + * ^ assigned identifier + * @param {AssignmentInfo} assignment The assignment info. + * @param {Identifier} identifier The identifier to check. + * @returns {boolean} `true` if the given identifier node is used between the assigned identifier and the equal sign. + */ +function isIdentifierUsedBetweenAssignedAndEqualSign(assignment, identifier) { + if (!assignment.expression) { + return false; + } + return ( + assignment.identifier.range[1] <= identifier.range[0] && + identifier.range[1] <= assignment.expression.range[0] + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow variable assignments when the value is not used", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-assignment", + }, + + schema: [], + + messages: { + unnecessaryAssignment: + "This assigned value is not used in subsequent statements.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * @typedef {Object} ScopeStack + * @property {CodePath} codePath The code path of this scope stack. + * @property {Scope} scope The scope of this scope stack. + * @property {ScopeStack} upper The upper scope stack. + * @property {Record} segments The map of ScopeStackSegmentInfo. + * @property {Set} currentSegments The current CodePathSegments. + * @property {Map} assignments The map of list of AssignmentInfo for each variable. + * @property {Array} tryStatementBlocks The array of TryStatement block nodes in this scope stack. + */ + /** + * @typedef {Object} ScopeStackSegmentInfo + * @property {CodePathSegment} segment The code path segment. + * @property {Identifier|null} first The first identifier that appears within the segment. + * @property {Identifier|null} last The last identifier that appears within the segment. + * `first` and `last` are used to determine whether an identifier exists within the segment position range. + * Since it is used as a range of segments, we should originally hold all nodes, not just identifiers, + * but since the only nodes to be judged are identifiers, it is sufficient to have a range of identifiers. + */ + /** + * @typedef {Object} AssignmentInfo + * @property {Variable} variable The variable that is assigned. + * @property {Identifier} identifier The identifier that is assigned. + * @property {VariableDeclarator|AssignmentExpression|UpdateExpression} node The node where the variable was updated. + * @property {Expression|null} expression The expression that is evaluated before the assignment. + * @property {CodePathSegment[]} segments The code path segments where the assignment was made. + */ + + /** @type {ScopeStack} */ + let scopeStack = null; + + /** @type {Set} */ + const codePathStartScopes = new Set(); + + /** + * Gets the scope of code path start from given scope + * @param {Scope} scope The initial scope + * @returns {Scope} The scope of code path start + * @throws {Error} Unexpected error + */ + function getCodePathStartScope(scope) { + let target = scope; + + while (target) { + if (codePathStartScopes.has(target)) { + return target; + } + target = target.upper; + } + + // Should be unreachable + return null; + } + + /** + * Verify the given scope stack. + * @param {ScopeStack} target The scope stack to verify. + * @returns {void} + */ + function verify(target) { + /** + * Checks whether the given identifier is used in the segment. + * @param {CodePathSegment} segment The code path segment. + * @param {Identifier} identifier The identifier to check. + * @returns {boolean} `true` if the identifier is used in the segment. + */ + function isIdentifierUsedInSegment(segment, identifier) { + const segmentInfo = target.segments[segment.id]; + + return ( + segmentInfo.first && + segmentInfo.last && + segmentInfo.first.range[0] <= identifier.range[0] && + identifier.range[1] <= segmentInfo.last.range[1] + ); + } + + /** + * Verifies whether the given assignment info is an used assignment. + * Report if it is an unused assignment. + * @param {AssignmentInfo} targetAssignment The assignment info to verify. + * @param {AssignmentInfo[]} allAssignments The list of all assignment info for variables. + * @returns {void} + */ + function verifyAssignmentIsUsed(targetAssignment, allAssignments) { + // Skip assignment if it is in a try block. + const isAssignmentInTryBlock = target.tryStatementBlocks.some( + tryBlock => + tryBlock.range[0] <= + targetAssignment.identifier.range[0] && + targetAssignment.identifier.range[1] <= + tryBlock.range[1], + ); + + if (isAssignmentInTryBlock) { + return; + } + + /** + * @typedef {Object} SubsequentSegmentData + * @property {CodePathSegment} segment The code path segment + * @property {AssignmentInfo} [assignment] The first occurrence of the assignment within the segment. + * There is no need to check if the variable is used after this assignment, + * as the value it was assigned will be used. + */ + + /** + * Information used in `getSubsequentSegments()`. + * To avoid unnecessary iterations, cache information that has already been iterated over, + * and if additional iterations are needed, start iterating from the retained position. + */ + const subsequentSegmentData = { + /** + * Cache of subsequent segment information list that have already been iterated. + * @type {SubsequentSegmentData[]} + */ + results: [], + + /** + * Subsequent segments that have already been iterated on. Used to avoid infinite loops. + * @type {Set} + */ + subsequentSegments: new Set(), + + /** + * Unexplored code path segment. + * If additional iterations are needed, consume this information and iterate. + * @type {CodePathSegment[]} + */ + queueSegments: targetAssignment.segments.flatMap( + segment => segment.nextSegments, + ), + }; + + /** + * Gets the subsequent segments from the segment of + * the assignment currently being validated (targetAssignment). + * @returns {Iterable} the subsequent segments + */ + function* getSubsequentSegments() { + yield* subsequentSegmentData.results; + + while (subsequentSegmentData.queueSegments.length > 0) { + const nextSegment = + subsequentSegmentData.queueSegments.shift(); + + if ( + subsequentSegmentData.subsequentSegments.has( + nextSegment, + ) + ) { + continue; + } + subsequentSegmentData.subsequentSegments.add( + nextSegment, + ); + + const assignmentInSegment = allAssignments.find( + otherAssignment => + otherAssignment.segments.includes( + nextSegment, + ) && + !isIdentifierUsedBetweenAssignedAndEqualSign( + otherAssignment, + targetAssignment.identifier, + ), + ); + + if (!assignmentInSegment) { + /* + * Stores the next segment to explore. + * If `assignmentInSegment` exists, + * we are guarding it because we don't need to explore the next segment. + */ + subsequentSegmentData.queueSegments.push( + ...nextSegment.nextSegments, + ); + } + + /** @type {SubsequentSegmentData} */ + const result = { + segment: nextSegment, + assignment: assignmentInSegment, + }; + + subsequentSegmentData.results.push(result); + yield result; + } + } + + if ( + targetAssignment.variable.references.some( + ref => ref.identifier.type !== "Identifier", + ) + ) { + /** + * Skip checking for a variable that has at least one non-identifier reference. + * It's generated by plugins and cannot be handled reliably in the core rule. + */ + return; + } + + const readReferences = + targetAssignment.variable.references.filter(reference => + reference.isRead(), + ); + + if (!readReferences.length) { + /* + * It is not just an unnecessary assignment, but an unnecessary (unused) variable + * and thus should not be reported by this rule because it is reported by `no-unused-vars`. + */ + return; + } + + /** + * Other assignment on the current segment and after current assignment. + */ + const otherAssignmentAfterTargetAssignment = + allAssignments.find(assignment => { + if ( + assignment === targetAssignment || + (assignment.segments.length && + assignment.segments.every( + segment => + !targetAssignment.segments.includes( + segment, + ), + )) + ) { + return false; + } + if ( + isIdentifierEvaluatedAfterAssignment( + targetAssignment, + assignment.identifier, + ) + ) { + return true; + } + if ( + assignment.expression && + assignment.expression.range[0] <= + targetAssignment.identifier.range[0] && + targetAssignment.identifier.range[1] <= + assignment.expression.range[1] + ) { + /* + * The target assignment is in an expression that is evaluated before the assignment. + * e.g. x=(x=1); + * ^^^ targetAssignment + * ^^^^^^^ assignment + */ + return true; + } + + return false; + }); + + for (const reference of readReferences) { + /* + * If the scope of the reference is outside the current code path scope, + * we cannot track whether this assignment is not used. + * For example, it can also be called asynchronously. + */ + if ( + target.scope !== getCodePathStartScope(reference.from) + ) { + return; + } + + // Checks if it is used in the same segment as the target assignment. + if ( + isIdentifierEvaluatedAfterAssignment( + targetAssignment, + reference.identifier, + ) && + (isIdentifierUsedBetweenAssignedAndEqualSign( + targetAssignment, + reference.identifier, + ) || + targetAssignment.segments.some(segment => + isIdentifierUsedInSegment( + segment, + reference.identifier, + ), + )) + ) { + if ( + otherAssignmentAfterTargetAssignment && + isIdentifierEvaluatedAfterAssignment( + otherAssignmentAfterTargetAssignment, + reference.identifier, + ) + ) { + // There was another assignment before the reference. Therefore, it has not been used yet. + continue; + } + + // Uses in statements after the written identifier. + return; + } + + if (otherAssignmentAfterTargetAssignment) { + /* + * The assignment was followed by another assignment in the same segment. + * Therefore, there is no need to check the next segment. + */ + continue; + } + + // Check subsequent segments. + for (const subsequentSegment of getSubsequentSegments()) { + if ( + isIdentifierUsedInSegment( + subsequentSegment.segment, + reference.identifier, + ) + ) { + if ( + subsequentSegment.assignment && + isIdentifierEvaluatedAfterAssignment( + subsequentSegment.assignment, + reference.identifier, + ) + ) { + // There was another assignment before the reference. Therefore, it has not been used yet. + continue; + } + + // It is used + return; + } + } + } + context.report({ + node: targetAssignment.identifier, + messageId: "unnecessaryAssignment", + }); + } + + // Verify that each assignment in the code path is used. + for (const assignments of target.assignments.values()) { + assignments.sort( + (a, b) => a.identifier.range[0] - b.identifier.range[0], + ); + for (const assignment of assignments) { + verifyAssignmentIsUsed(assignment, assignments); + } + } + } + + return { + onCodePathStart(codePath, node) { + const scope = sourceCode.getScope(node); + + scopeStack = { + upper: scopeStack, + codePath, + scope, + segments: Object.create(null), + currentSegments: new Set(), + assignments: new Map(), + tryStatementBlocks: [], + }; + codePathStartScopes.add(scopeStack.scope); + }, + onCodePathEnd() { + verify(scopeStack); + + scopeStack = scopeStack.upper; + }, + onCodePathSegmentStart(segment) { + const segmentInfo = { segment, first: null, last: null }; + + scopeStack.segments[segment.id] = segmentInfo; + scopeStack.currentSegments.add(segment); + }, + onCodePathSegmentEnd(segment) { + scopeStack.currentSegments.delete(segment); + }, + TryStatement(node) { + scopeStack.tryStatementBlocks.push(node.block); + }, + Identifier(node) { + for (const segment of scopeStack.currentSegments) { + const segmentInfo = scopeStack.segments[segment.id]; + + if (!segmentInfo.first) { + segmentInfo.first = node; + } + segmentInfo.last = node; + } + }, + ":matches(VariableDeclarator[init!=null], AssignmentExpression, UpdateExpression):exit"( + node, + ) { + if (scopeStack.currentSegments.size === 0) { + // Ignore unreachable segments + return; + } + + const assignments = scopeStack.assignments; + + let pattern; + let expression = null; + + if (node.type === "VariableDeclarator") { + pattern = node.id; + expression = node.init; + } else if (node.type === "AssignmentExpression") { + pattern = node.left; + expression = node.right; + } else { + // UpdateExpression + pattern = node.argument; + } + + for (const identifier of extractIdentifiersFromPattern( + pattern, + )) { + const scope = sourceCode.getScope(identifier); + + /** @type {Variable} */ + const variable = findVariable(scope, identifier); + + if (!variable) { + continue; + } + + // We don't know where global variables are used. + if ( + variable.scope.type === "global" && + variable.defs.length === 0 + ) { + continue; + } + + /* + * If the scope of the variable is outside the current code path scope, + * we cannot track whether this assignment is not used. + */ + if ( + scopeStack.scope !== + getCodePathStartScope(variable.scope) + ) { + continue; + } + + // Variables marked by `markVariableAsUsed()` or + // exported by "exported" block comment. + if (variable.eslintUsed) { + continue; + } + + // Variables exported by ESM export syntax + if (variable.scope.type === "module") { + if ( + variable.defs.some( + def => + (def.type === "Variable" && + def.parent.parent.type === + "ExportNamedDeclaration") || + (def.type === "FunctionName" && + (def.node.parent.type === + "ExportNamedDeclaration" || + def.node.parent.type === + "ExportDefaultDeclaration")) || + (def.type === "ClassName" && + (def.node.parent.type === + "ExportNamedDeclaration" || + def.node.parent.type === + "ExportDefaultDeclaration")), + ) + ) { + continue; + } + if ( + variable.references.some( + reference => + reference.identifier.parent.type === + "ExportSpecifier", + ) + ) { + // It have `export { ... }` reference. + continue; + } + } + + let list = assignments.get(variable); + + if (!list) { + list = []; + assignments.set(variable, list); + } + list.push({ + variable, + identifier, + node, + expression, + segments: [...scopeStack.currentSegments], + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-backreference.js b/node_modules/eslint/lib/rules/no-useless-backreference.js new file mode 100644 index 00000000..73cce577 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-backreference.js @@ -0,0 +1,263 @@ +/** + * @fileoverview Rule to disallow useless backreferences in regular expressions + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStringIfConstant, +} = require("@eslint-community/eslint-utils"); +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const parser = new RegExpParser(); + +/** + * Finds the path from the given `regexpp` AST node to the root node. + * @param {regexpp.Node} node Node. + * @returns {regexpp.Node[]} Array that starts with the given node and ends with the root node. + */ +function getPathToRoot(node) { + const path = []; + let current = node; + + do { + path.push(current); + current = current.parent; + } while (current); + + return path; +} + +/** + * Determines whether the given `regexpp` AST node is a lookaround node. + * @param {regexpp.Node} node Node. + * @returns {boolean} `true` if it is a lookaround node. + */ +function isLookaround(node) { + return ( + node.type === "Assertion" && + (node.kind === "lookahead" || node.kind === "lookbehind") + ); +} + +/** + * Determines whether the given `regexpp` AST node is a negative lookaround node. + * @param {regexpp.Node} node Node. + * @returns {boolean} `true` if it is a negative lookaround node. + */ +function isNegativeLookaround(node) { + return isLookaround(node) && node.negate; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow useless backreferences in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-backreference", + }, + + schema: [], + + messages: { + nested: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} from within that group.", + forward: + "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} which appears later in the pattern.", + backward: + "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} which appears before in the same lookbehind.", + disjunctive: + "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} which is in another alternative.", + intoNegativeLookaround: + "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} which is in a negative lookaround.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks and reports useless backreferences in the given regular expression. + * @param {ASTNode} node Node that represents regular expression. A regex literal or RegExp constructor call. + * @param {string} pattern Regular expression pattern. + * @param {string} flags Regular expression flags. + * @returns {void} + */ + function checkRegex(node, pattern, flags) { + let regExpAST; + + try { + regExpAST = parser.parsePattern(pattern, 0, pattern.length, { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }); + } catch { + // Ignore regular expressions with syntax errors + return; + } + + visitRegExpAST(regExpAST, { + onBackreferenceEnter(bref) { + const groups = [bref.resolved].flat(), + brefPath = getPathToRoot(bref); + + const problems = groups.map(group => { + const groupPath = getPathToRoot(group); + + if (brefPath.includes(group)) { + // group is bref's ancestor => bref is nested ('nested reference') => group hasn't matched yet when bref starts to match. + return { + messageId: "nested", + group, + }; + } + + // Start from the root to find the lowest common ancestor. + let i = brefPath.length - 1, + j = groupPath.length - 1; + + do { + i--; + j--; + } while (brefPath[i] === groupPath[j]); + + const indexOfLowestCommonAncestor = j + 1, + groupCut = groupPath.slice( + 0, + indexOfLowestCommonAncestor, + ), + commonPath = groupPath.slice( + indexOfLowestCommonAncestor, + ), + lowestCommonLookaround = + commonPath.find(isLookaround), + isMatchingBackward = + lowestCommonLookaround && + lowestCommonLookaround.kind === "lookbehind"; + + if (groupCut.at(-1).type === "Alternative") { + // group's and bref's ancestor nodes below the lowest common ancestor are sibling alternatives => they're disjunctive. + return { + messageId: "disjunctive", + group, + }; + } + if (!isMatchingBackward && bref.end <= group.start) { + // bref is left, group is right ('forward reference') => group hasn't matched yet when bref starts to match. + return { + messageId: "forward", + group, + }; + } + if (isMatchingBackward && group.end <= bref.start) { + // the opposite of the previous when the regex is matching backward in a lookbehind context. + return { + messageId: "backward", + group, + }; + } + if (groupCut.some(isNegativeLookaround)) { + // group is in a negative lookaround which isn't bref's ancestor => group has already failed when bref starts to match. + return { + messageId: "intoNegativeLookaround", + group, + }; + } + + return null; + }); + + if ( + problems.length === 0 || + problems.some(problem => !problem) + ) { + // If there are no problems or no problems with any group then do not report it. + return; + } + + let problemsToReport; + + // Gets problems that appear in the same disjunction. + const problemsInSameDisjunction = problems.filter( + problem => problem.messageId !== "disjunctive", + ); + + if (problemsInSameDisjunction.length) { + // Only report problems that appear in the same disjunction. + problemsToReport = problemsInSameDisjunction; + } else { + // If all groups appear in different disjunctions, report it. + problemsToReport = problems; + } + + const [{ messageId, group }, ...other] = problemsToReport; + let otherGroups = ""; + + if (other.length === 1) { + otherGroups = " and another group"; + } else if (other.length > 1) { + otherGroups = ` and other ${other.length} groups`; + } + context.report({ + node, + messageId, + data: { + bref: bref.raw, + group: group.raw, + otherGroups, + }, + }); + }, + }); + } + + return { + "Literal[regex]"(node) { + const { pattern, flags } = node.regex; + + checkRegex(node, pattern, flags); + }, + Program(node) { + const scope = sourceCode.getScope(node), + tracker = new ReferenceTracker(scope), + traceMap = { + RegExp: { + [CALL]: true, + [CONSTRUCT]: true, + }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + traceMap, + )) { + const [patternNode, flagsNode] = refNode.arguments, + pattern = getStringIfConstant(patternNode, scope), + flags = getStringIfConstant(flagsNode, scope); + + if (typeof pattern === "string") { + checkRegex(refNode, pattern, flags || ""); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-call.js b/node_modules/eslint/lib/rules/no-useless-call.js new file mode 100644 index 00000000..2a04ad29 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-call.js @@ -0,0 +1,95 @@ +/** + * @fileoverview A rule to disallow unnecessary `.call()` and `.apply()`. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a node is a `.call()`/`.apply()`. + * @param {ASTNode} node A CallExpression node to check. + * @returns {boolean} Whether or not the node is a `.call()`/`.apply()`. + */ +function isCallOrNonVariadicApply(node) { + const callee = astUtils.skipChainExpression(node.callee); + + return ( + callee.type === "MemberExpression" && + callee.property.type === "Identifier" && + callee.computed === false && + ((callee.property.name === "call" && node.arguments.length >= 1) || + (callee.property.name === "apply" && + node.arguments.length === 2 && + node.arguments[1].type === "ArrayExpression")) + ); +} + +/** + * Checks whether or not `thisArg` is not changed by `.call()`/`.apply()`. + * @param {ASTNode|null} expectedThis The node that is the owner of the applied function. + * @param {ASTNode} thisArg The node that is given to the first argument of the `.call()`/`.apply()`. + * @param {SourceCode} sourceCode The ESLint source code object. + * @returns {boolean} Whether or not `thisArg` is not changed by `.call()`/`.apply()`. + */ +function isValidThisArg(expectedThis, thisArg, sourceCode) { + if (!expectedThis) { + return astUtils.isNullOrUndefined(thisArg); + } + return astUtils.equalTokens(expectedThis, thisArg, sourceCode); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow unnecessary calls to `.call()` and `.apply()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-call", + }, + + schema: [], + + messages: { + unnecessaryCall: "Unnecessary '.{{name}}()'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + if (!isCallOrNonVariadicApply(node)) { + return; + } + + const callee = astUtils.skipChainExpression(node.callee); + const applied = astUtils.skipChainExpression(callee.object); + const expectedThis = + applied.type === "MemberExpression" ? applied.object : null; + const thisArg = node.arguments[0]; + + if (isValidThisArg(expectedThis, thisArg, sourceCode)) { + context.report({ + node, + messageId: "unnecessaryCall", + data: { name: callee.property.name }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-catch.js b/node_modules/eslint/lib/rules/no-useless-catch.js new file mode 100644 index 00000000..e3df3093 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-catch.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Reports useless `catch` clauses that just rethrow their error. + * @author Teddy Katz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary `catch` clauses", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-catch", + }, + + schema: [], + + messages: { + unnecessaryCatchClause: "Unnecessary catch clause.", + unnecessaryCatch: "Unnecessary try/catch wrapper.", + }, + }, + + create(context) { + return { + CatchClause(node) { + if ( + node.param && + node.param.type === "Identifier" && + node.body.body.length && + node.body.body[0].type === "ThrowStatement" && + node.body.body[0].argument.type === "Identifier" && + node.body.body[0].argument.name === node.param.name + ) { + if (node.parent.finalizer) { + context.report({ + node, + messageId: "unnecessaryCatchClause", + }); + } else { + context.report({ + node: node.parent, + messageId: "unnecessaryCatch", + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-computed-key.js b/node_modules/eslint/lib/rules/no-useless-computed-key.js new file mode 100644 index 00000000..3c61c767 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-computed-key.js @@ -0,0 +1,204 @@ +/** + * @fileoverview Rule to disallow unnecessary computed property keys in object literals + * @author Burak Yigit Kaya + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the computed key syntax is unnecessarily used for the given node. + * In particular, it determines whether removing the square brackets and using the content between them + * directly as the key (e.g. ['foo'] -> 'foo') would produce valid syntax and preserve the same behavior. + * Valid non-computed keys are only: identifiers, number literals and string literals. + * Only literals can preserve the same behavior, with a few exceptions for specific node types: + * Property + * - { ["__proto__"]: foo } defines a property named "__proto__" + * { "__proto__": foo } defines object's prototype + * PropertyDefinition + * - class C { ["constructor"]; } defines an instance field named "constructor" + * class C { "constructor"; } produces a parsing error + * - class C { static ["constructor"]; } defines a static field named "constructor" + * class C { static "constructor"; } produces a parsing error + * - class C { static ["prototype"]; } produces a runtime error (doesn't break the whole script) + * class C { static "prototype"; } produces a parsing error (breaks the whole script) + * MethodDefinition + * - class C { ["constructor"]() {} } defines a prototype method named "constructor" + * class C { "constructor"() {} } defines the constructor + * - class C { static ["prototype"]() {} } produces a runtime error (doesn't break the whole script) + * class C { static "prototype"() {} } produces a parsing error (breaks the whole script) + * @param {ASTNode} node The node to check. It can be `Property`, `PropertyDefinition` or `MethodDefinition`. + * @throws {Error} (Unreachable.) + * @returns {void} `true` if the node has useless computed key. + */ +function hasUselessComputedKey(node) { + if (!node.computed) { + return false; + } + + const { key } = node; + + if (key.type !== "Literal") { + return false; + } + + const { value } = key; + + if (typeof value !== "number" && typeof value !== "string") { + return false; + } + + switch (node.type) { + case "Property": + if (node.parent.type === "ObjectExpression") { + return value !== "__proto__"; + } + return true; + + case "PropertyDefinition": + if (node.static) { + return value !== "constructor" && value !== "prototype"; + } + + return value !== "constructor"; + + case "MethodDefinition": + if (node.static) { + return value !== "prototype"; + } + + return value !== "constructor"; + + /* c8 ignore next */ + default: + throw new Error(`Unexpected node type: ${node.type}`); + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + enforceForClassMembers: true, + }, + ], + + docs: { + description: + "Disallow unnecessary computed property keys in objects and classes", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-useless-computed-key", + }, + + schema: [ + { + type: "object", + properties: { + enforceForClassMembers: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + fixable: "code", + + messages: { + unnecessarilyComputedProperty: + "Unnecessarily computed property [{{property}}] found.", + }, + }, + create(context) { + const sourceCode = context.sourceCode; + const [{ enforceForClassMembers }] = context.options; + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function check(node) { + if (hasUselessComputedKey(node)) { + const { key } = node; + + context.report({ + node, + messageId: "unnecessarilyComputedProperty", + data: { property: sourceCode.getText(key) }, + fix(fixer) { + const leftSquareBracket = sourceCode.getTokenBefore( + key, + astUtils.isOpeningBracketToken, + ); + const rightSquareBracket = sourceCode.getTokenAfter( + key, + astUtils.isClosingBracketToken, + ); + + // If there are comments between the brackets and the property name, don't do a fix. + if ( + sourceCode.commentsExistBetween( + leftSquareBracket, + rightSquareBracket, + ) + ) { + return null; + } + + const tokenBeforeLeftBracket = + sourceCode.getTokenBefore(leftSquareBracket); + + // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} }) + const needsSpaceBeforeKey = + tokenBeforeLeftBracket.range[1] === + leftSquareBracket.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBeforeLeftBracket, + sourceCode.getFirstToken(key), + ); + + const replacementKey = + (needsSpaceBeforeKey ? " " : "") + key.raw; + + return fixer.replaceTextRange( + [ + leftSquareBracket.range[0], + rightSquareBracket.range[1], + ], + replacementKey, + ); + }, + }); + } + } + + /** + * A no-op function to act as placeholder for checking a node when the `enforceForClassMembers` option is `false`. + * @returns {void} + * @private + */ + function noop() {} + + return { + Property: check, + MethodDefinition: enforceForClassMembers ? check : noop, + PropertyDefinition: enforceForClassMembers ? check : noop, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-concat.js b/node_modules/eslint/lib/rules/no-useless-concat.js new file mode 100644 index 00000000..d1d12748 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-concat.js @@ -0,0 +1,121 @@ +/** + * @fileoverview disallow unnecessary concatenation of template strings + * @author Henry Zhu + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a concatenation. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a concatenation. + */ +function isConcatenation(node) { + return node.type === "BinaryExpression" && node.operator === "+"; +} + +/** + * Checks if the given token is a `+` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a `+` token. + */ +function isConcatOperatorToken(token) { + return token.value === "+" && token.type === "Punctuator"; +} + +/** + * Get's the right most node on the left side of a BinaryExpression with + operator. + * @param {ASTNode} node A BinaryExpression node to check. + * @returns {ASTNode} node + */ +function getLeft(node) { + let left = node.left; + + while (isConcatenation(left)) { + left = left.right; + } + return left; +} + +/** + * Get's the left most node on the right side of a BinaryExpression with + operator. + * @param {ASTNode} node A BinaryExpression node to check. + * @returns {ASTNode} node + */ +function getRight(node) { + let right = node.right; + + while (isConcatenation(right)) { + right = right.left; + } + return right; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow unnecessary concatenation of literals or template literals", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-useless-concat", + }, + + schema: [], + + messages: { + unexpectedConcat: "Unexpected string concatenation of literals.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + BinaryExpression(node) { + // check if not concatenation + if (node.operator !== "+") { + return; + } + + // account for the `foo + "a" + "b"` case + const left = getLeft(node); + const right = getRight(node); + + if ( + astUtils.isStringLiteral(left) && + astUtils.isStringLiteral(right) && + astUtils.isTokenOnSameLine(left, right) + ) { + const operatorToken = sourceCode.getFirstTokenBetween( + left, + right, + isConcatOperatorToken, + ); + + context.report({ + node, + loc: operatorToken.loc, + messageId: "unexpectedConcat", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-constructor.js b/node_modules/eslint/lib/rules/no-useless-constructor.js new file mode 100644 index 00000000..123dce31 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-constructor.js @@ -0,0 +1,252 @@ +/** + * @fileoverview Rule to flag the use of redundant constructors in classes. + * @author Alberto Rodríguez + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether any of a method's parameters have a decorator or are a parameter property. + * @param {ASTNode} node A method definition node. + * @returns {boolean} `true` if any parameter had a decorator or is a parameter property. + */ +function hasDecoratorsOrParameterProperty(node) { + return node.value.params.some( + param => + param.decorators?.length || param.type === "TSParameterProperty", + ); +} + +/** + * Checks whether a node's accessibility makes it not useless. + * @param {ASTNode} node A method definition node. + * @returns {boolean} `true` if the node has a useful accessibility. + */ +function hasUsefulAccessibility(node) { + switch (node.accessibility) { + case "protected": + case "private": + return true; + case "public": + return !!node.parent.parent.superClass; + default: + return false; + } +} + +/** + * Checks whether a given array of statements is a single call of `super`. + * @param {ASTNode[]} body An array of statements to check. + * @returns {boolean} `true` if the body is a single call of `super`. + */ +function isSingleSuperCall(body) { + return ( + body.length === 1 && + body[0].type === "ExpressionStatement" && + body[0].expression.type === "CallExpression" && + body[0].expression.callee.type === "Super" + ); +} + +/** + * Checks whether a given node is a pattern which doesn't have any side effects. + * Default parameters and Destructuring parameters can have side effects. + * @param {ASTNode} node A pattern node. + * @returns {boolean} `true` if the node doesn't have any side effects. + */ +function isSimple(node) { + return node.type === "Identifier" || node.type === "RestElement"; +} + +/** + * Checks whether a given array of expressions is `...arguments` or not. + * `super(...arguments)` passes all arguments through. + * @param {ASTNode[]} superArgs An array of expressions to check. + * @returns {boolean} `true` if the superArgs is `...arguments`. + */ +function isSpreadArguments(superArgs) { + return ( + superArgs.length === 1 && + superArgs[0].type === "SpreadElement" && + superArgs[0].argument.type === "Identifier" && + superArgs[0].argument.name === "arguments" + ); +} + +/** + * Checks whether given 2 nodes are identifiers which have the same name or not. + * @param {ASTNode} ctorParam A node to check. + * @param {ASTNode} superArg A node to check. + * @returns {boolean} `true` if the nodes are identifiers which have the same + * name. + */ +function isValidIdentifierPair(ctorParam, superArg) { + return ( + ctorParam.type === "Identifier" && + superArg.type === "Identifier" && + ctorParam.name === superArg.name + ); +} + +/** + * Checks whether given 2 nodes are a rest/spread pair which has the same values. + * @param {ASTNode} ctorParam A node to check. + * @param {ASTNode} superArg A node to check. + * @returns {boolean} `true` if the nodes are a rest/spread pair which has the + * same values. + */ +function isValidRestSpreadPair(ctorParam, superArg) { + return ( + ctorParam.type === "RestElement" && + superArg.type === "SpreadElement" && + isValidIdentifierPair(ctorParam.argument, superArg.argument) + ); +} + +/** + * Checks whether given 2 nodes have the same value or not. + * @param {ASTNode} ctorParam A node to check. + * @param {ASTNode} superArg A node to check. + * @returns {boolean} `true` if the nodes have the same value or not. + */ +function isValidPair(ctorParam, superArg) { + return ( + isValidIdentifierPair(ctorParam, superArg) || + isValidRestSpreadPair(ctorParam, superArg) + ); +} + +/** + * Checks whether the parameters of a constructor and the arguments of `super()` + * have the same values or not. + * @param {ASTNode} ctorParams The parameters of a constructor to check. + * @param {ASTNode} superArgs The arguments of `super()` to check. + * @returns {boolean} `true` if those have the same values. + */ +function isPassingThrough(ctorParams, superArgs) { + if (ctorParams.length !== superArgs.length) { + return false; + } + + for (let i = 0; i < ctorParams.length; ++i) { + if (!isValidPair(ctorParams[i], superArgs[i])) { + return false; + } + } + + return true; +} + +/** + * Checks whether the constructor body is a redundant super call. + * @param {Array} body constructor body content. + * @param {Array} ctorParams The params to check against super call. + * @returns {boolean} true if the constructor body is redundant + */ +function isRedundantSuperCall(body, ctorParams) { + return ( + isSingleSuperCall(body) && + ctorParams.every(isSimple) && + (isSpreadArguments(body[0].expression.arguments) || + isPassingThrough(ctorParams, body[0].expression.arguments)) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Disallow unnecessary constructors", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-constructor", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + noUselessConstructor: "Useless constructor.", + removeConstructor: "Remove the constructor.", + }, + }, + + create(context) { + /** + * Checks whether a node is a redundant constructor + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkForConstructor(node) { + if ( + node.kind !== "constructor" || + node.value.type !== "FunctionExpression" || + hasDecoratorsOrParameterProperty(node) || + hasUsefulAccessibility(node) + ) { + return; + } + + /* + * Prevent crashing on parsers which do not require class constructor + * to have a body, e.g. typescript and flow + */ + if (!node.value.body) { + return; + } + + const body = node.value.body.body; + const ctorParams = node.value.params; + const superClass = node.parent.parent.superClass; + + if ( + superClass + ? isRedundantSuperCall(body, ctorParams) + : body.length === 0 + ) { + context.report({ + node, + messageId: "noUselessConstructor", + suggest: [ + { + messageId: "removeConstructor", + *fix(fixer) { + const nextToken = + context.sourceCode.getTokenAfter(node); + const addSemiColon = + nextToken.type === "Punctuator" && + nextToken.value === "[" && + astUtils.needsPrecedingSemicolon( + context.sourceCode, + node, + ); + + yield fixer.replaceText( + node, + addSemiColon ? ";" : "", + ); + }, + }, + ], + }); + } + } + + return { + MethodDefinition: checkForConstructor, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-escape.js b/node_modules/eslint/lib/rules/no-useless-escape.js new file mode 100644 index 00000000..541b3a52 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-escape.js @@ -0,0 +1,406 @@ +/** + * @fileoverview Look for useless escapes in strings and regexes + * @author Onur Temizkan + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); + +/** + * @typedef {import('@eslint-community/regexpp').AST.CharacterClass} CharacterClass + * @typedef {import('@eslint-community/regexpp').AST.ExpressionCharacterClass} ExpressionCharacterClass + */ +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Returns the union of two sets. + * @param {Set} setA The first set + * @param {Set} setB The second set + * @returns {Set} The union of the two sets + */ +function union(setA, setB) { + return new Set( + (function* () { + yield* setA; + yield* setB; + })(), + ); +} + +const VALID_STRING_ESCAPES = union(new Set("\\nrvtbfux"), astUtils.LINEBREAKS); +const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnpPrsStvwWxu0123456789]"); +const REGEX_NON_CHARCLASS_ESCAPES = union( + REGEX_GENERAL_ESCAPES, + new Set("^/.$*+?[{}|()Bk"), +); + +/* + * Set of characters that require escaping in character classes in `unicodeSets` mode. + * ( ) [ ] { } / - \ | are ClassSetSyntaxCharacter + */ +const REGEX_CLASSSET_CHARACTER_ESCAPES = union( + REGEX_GENERAL_ESCAPES, + new Set("q/[{}|()-"), +); + +/* + * A single character set of ClassSetReservedDoublePunctuator. + * && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ `` ~~ are ClassSetReservedDoublePunctuator + */ +const REGEX_CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR = new Set( + "!#$%&*+,.:;<=>?@^`~", +); + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowRegexCharacters: [], + }, + ], + + docs: { + description: "Disallow unnecessary escape characters", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-escape", + }, + + hasSuggestions: true, + + messages: { + unnecessaryEscape: "Unnecessary escape character: \\{{character}}.", + removeEscape: + "Remove the `\\`. This maintains the current functionality.", + removeEscapeDoNotKeepSemantics: + "Remove the `\\` if it was inserted by mistake.", + escapeBackslash: + "Replace the `\\` with `\\\\` to include the actual backslash character.", + }, + + schema: [ + { + type: "object", + properties: { + allowRegexCharacters: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ allowRegexCharacters }] = context.options; + const parser = new RegExpParser(); + + /** + * Reports a node + * @param {ASTNode} node The node to report + * @param {number} startOffset The backslash's offset from the start of the node + * @param {string} character The uselessly escaped character (not including the backslash) + * @param {boolean} [disableEscapeBackslashSuggest] `true` if escapeBackslash suggestion should be turned off. + * @returns {void} + */ + function report( + node, + startOffset, + character, + disableEscapeBackslashSuggest, + ) { + const rangeStart = node.range[0] + startOffset; + const range = [rangeStart, rangeStart + 1]; + const start = sourceCode.getLocFromIndex(rangeStart); + + context.report({ + node, + loc: { + start, + end: { line: start.line, column: start.column + 1 }, + }, + messageId: "unnecessaryEscape", + data: { character }, + suggest: [ + { + // Removing unnecessary `\` characters in a directive is not guaranteed to maintain functionality. + messageId: astUtils.isDirective(node.parent) + ? "removeEscapeDoNotKeepSemantics" + : "removeEscape", + fix(fixer) { + return fixer.removeRange(range); + }, + }, + ...(disableEscapeBackslashSuggest + ? [] + : [ + { + messageId: "escapeBackslash", + fix(fixer) { + return fixer.insertTextBeforeRange( + range, + "\\", + ); + }, + }, + ]), + ], + }); + } + + /** + * Checks if the escape character in given string slice is unnecessary. + * @private + * @param {ASTNode} node node to validate. + * @param {string} match string slice to validate. + * @returns {void} + */ + function validateString(node, match) { + const isTemplateElement = node.type === "TemplateElement"; + const escapedChar = match[0][1]; + let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar); + let isQuoteEscape; + + if (isTemplateElement) { + isQuoteEscape = escapedChar === "`"; + + if (escapedChar === "$") { + // Warn if `\$` is not followed by `{` + isUnnecessaryEscape = match.input[match.index + 2] !== "{"; + } else if (escapedChar === "{") { + /* + * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping + * is necessary and the rule should not warn. If preceded by `/$`, the rule + * will warn for the `/$` instead, as it is the first unnecessarily escaped character. + */ + isUnnecessaryEscape = match.input[match.index - 1] !== "$"; + } + } else { + isQuoteEscape = escapedChar === node.raw[0]; + } + + if (isUnnecessaryEscape && !isQuoteEscape) { + report(node, match.index, match[0].slice(1)); + } + } + + /** + * Checks if the escape character in given regexp is unnecessary. + * @private + * @param {ASTNode} node node to validate. + * @returns {void} + */ + function validateRegExp(node) { + const { pattern, flags } = node.regex; + let patternNode; + const unicode = flags.includes("u"); + const unicodeSets = flags.includes("v"); + + try { + patternNode = parser.parsePattern(pattern, 0, pattern.length, { + unicode, + unicodeSets, + }); + } catch { + // Ignore regular expressions with syntax errors + return; + } + + /** @type {(CharacterClass | ExpressionCharacterClass)[]} */ + const characterClassStack = []; + + visitRegExpAST(patternNode, { + onCharacterClassEnter: characterClassNode => + characterClassStack.unshift(characterClassNode), + onCharacterClassLeave: () => characterClassStack.shift(), + onExpressionCharacterClassEnter: characterClassNode => + characterClassStack.unshift(characterClassNode), + onExpressionCharacterClassLeave: () => + characterClassStack.shift(), + onCharacterEnter(characterNode) { + if (!characterNode.raw.startsWith("\\")) { + // It's not an escaped character. + return; + } + + const escapedChar = characterNode.raw.slice(1); + + if ( + escapedChar !== + String.fromCodePoint(characterNode.value) || + allowRegexCharacters.includes(escapedChar) + ) { + // It's a valid escape. + return; + } + let allowedEscapes; + + if (characterClassStack.length) { + allowedEscapes = unicodeSets + ? REGEX_CLASSSET_CHARACTER_ESCAPES + : REGEX_GENERAL_ESCAPES; + } else { + allowedEscapes = REGEX_NON_CHARCLASS_ESCAPES; + } + if (allowedEscapes.has(escapedChar)) { + return; + } + + const reportedIndex = characterNode.start + 1; + let disableEscapeBackslashSuggest = false; + + if (characterClassStack.length) { + const characterClassNode = characterClassStack[0]; + + if (escapedChar === "^") { + /* + * The '^' character is also a special case; it must always be escaped outside of character classes, but + * it only needs to be escaped in character classes if it's at the beginning of the character class. To + * account for this, consider it to be a valid escape character outside of character classes, and filter + * out '^' characters that appear at the start of a character class. + */ + if ( + characterClassNode.start + 1 === + characterNode.start + ) { + return; + } + } + if (!unicodeSets) { + if (escapedChar === "-") { + /* + * The '-' character is a special case, because it's only valid to escape it if it's in a character + * class, and is not at either edge of the character class. To account for this, don't consider '-' + * characters to be valid in general, and filter out '-' characters that appear in the middle of a + * character class. + */ + if ( + characterClassNode.start + 1 !== + characterNode.start && + characterNode.end !== + characterClassNode.end - 1 + ) { + return; + } + } + } else { + // unicodeSets mode + if ( + REGEX_CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR.has( + escapedChar, + ) + ) { + // Escaping is valid if it is a ClassSetReservedDoublePunctuator. + if ( + pattern[characterNode.end] === escapedChar + ) { + return; + } + if ( + pattern[characterNode.start - 1] === + escapedChar + ) { + if (escapedChar !== "^") { + return; + } + + // If the previous character is a `negate` caret(`^`), escape to caret is unnecessary. + + if (!characterClassNode.negate) { + return; + } + const negateCaretIndex = + characterClassNode.start + 1; + + if ( + negateCaretIndex < + characterNode.start - 1 + ) { + return; + } + } + } + + if ( + characterNode.parent.type === + "ClassIntersection" || + characterNode.parent.type === "ClassSubtraction" + ) { + disableEscapeBackslashSuggest = true; + } + } + } + + report( + node, + reportedIndex, + escapedChar, + disableEscapeBackslashSuggest, + ); + }, + }); + } + + /** + * Checks if a node has an escape. + * @param {ASTNode} node node to check. + * @returns {void} + */ + function check(node) { + const isTemplateElement = node.type === "TemplateElement"; + + if ( + isTemplateElement && + node.parent && + node.parent.parent && + node.parent.parent.type === "TaggedTemplateExpression" && + node.parent === node.parent.parent.quasi + ) { + // Don't report tagged template literals, because the backslash character is accessible to the tag function. + return; + } + + if (typeof node.value === "string" || isTemplateElement) { + /* + * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/. + * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25. + */ + if ( + node.parent.type === "JSXAttribute" || + node.parent.type === "JSXElement" || + node.parent.type === "JSXFragment" + ) { + return; + } + + const value = isTemplateElement + ? sourceCode.getText(node) + : node.raw; + const pattern = /\\[^\d]/gu; + let match; + + while ((match = pattern.exec(value))) { + validateString(node, match); + } + } else if (node.regex) { + validateRegExp(node); + } + } + + return { + Literal: check, + TemplateElement: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-rename.js b/node_modules/eslint/lib/rules/no-useless-rename.js new file mode 100644 index 00000000..13c76861 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-rename.js @@ -0,0 +1,202 @@ +/** + * @fileoverview Disallow renaming import, export, and destructured assignments to the same name. + * @author Kai Cataldo + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + ignoreDestructuring: false, + ignoreImport: false, + ignoreExport: false, + }, + ], + + docs: { + description: + "Disallow renaming import, export, and destructured assignments to the same name", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-rename", + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + ignoreDestructuring: { type: "boolean" }, + ignoreImport: { type: "boolean" }, + ignoreExport: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + + messages: { + unnecessarilyRenamed: "{{type}} {{name}} unnecessarily renamed.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ ignoreDestructuring, ignoreImport, ignoreExport }] = + context.options; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports error for unnecessarily renamed assignments + * @param {ASTNode} node node to report + * @param {ASTNode} initial node with initial name value + * @param {string} type the type of the offending node + * @returns {void} + */ + function reportError(node, initial, type) { + const name = + initial.type === "Identifier" ? initial.name : initial.value; + + return context.report({ + node, + messageId: "unnecessarilyRenamed", + data: { + name, + type, + }, + fix(fixer) { + const replacementNode = + node.type === "Property" ? node.value : node.local; + + if ( + sourceCode.getCommentsInside(node).length > + sourceCode.getCommentsInside(replacementNode).length + ) { + return null; + } + + // Don't autofix code such as `({foo: (foo) = a} = obj);`, parens are not allowed in shorthand properties. + if ( + replacementNode.type === "AssignmentPattern" && + astUtils.isParenthesised( + sourceCode, + replacementNode.left, + ) + ) { + return null; + } + + return fixer.replaceText( + node, + sourceCode.getText(replacementNode), + ); + }, + }); + } + + /** + * Checks whether a destructured assignment is unnecessarily renamed + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkDestructured(node) { + if (ignoreDestructuring) { + return; + } + + for (const property of node.properties) { + /** + * Properties using shorthand syntax and rest elements can not be renamed. + * If the property is computed, we have no idea if a rename is useless or not. + */ + if ( + property.type !== "Property" || + property.shorthand || + property.computed + ) { + continue; + } + + const key = + (property.key.type === "Identifier" && property.key.name) || + (property.key.type === "Literal" && property.key.value); + const renamedKey = + property.value.type === "AssignmentPattern" + ? property.value.left.name + : property.value.name; + + if (key === renamedKey) { + reportError( + property, + property.key, + "Destructuring assignment", + ); + } + } + } + + /** + * Checks whether an import is unnecessarily renamed + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkImport(node) { + if (ignoreImport) { + return; + } + + if ( + node.imported.range[0] !== node.local.range[0] && + astUtils.getModuleExportName(node.imported) === node.local.name + ) { + reportError(node, node.imported, "Import"); + } + } + + /** + * Checks whether an export is unnecessarily renamed + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkExport(node) { + if (ignoreExport) { + return; + } + + if ( + node.local.range[0] !== node.exported.range[0] && + astUtils.getModuleExportName(node.local) === + astUtils.getModuleExportName(node.exported) + ) { + reportError(node, node.local, "Export"); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ObjectPattern: checkDestructured, + ImportSpecifier: checkImport, + ExportSpecifier: checkExport, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-return.js b/node_modules/eslint/lib/rules/no-useless-return.js new file mode 100644 index 00000000..e911885a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-return.js @@ -0,0 +1,401 @@ +/** + * @fileoverview Disallow redundant return statements + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + FixTracker = require("./utils/fix-tracker"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Removes the given element from the array. + * @param {Array} array The source array to remove. + * @param {any} element The target item to remove. + * @returns {void} + */ +function remove(array, element) { + const index = array.indexOf(element); + + if (index !== -1) { + array.splice(index, 1); + } +} + +/** + * Checks whether it can remove the given return statement or not. + * @param {ASTNode} node The return statement node to check. + * @returns {boolean} `true` if the node is removable. + */ +function isRemovable(node) { + return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type); +} + +/** + * Checks whether the given return statement is in a `finally` block or not. + * @param {ASTNode} node The return statement node to check. + * @returns {boolean} `true` if the node is in a `finally` block. + */ +function isInFinally(node) { + for ( + let currentNode = node; + currentNode && currentNode.parent && !astUtils.isFunction(currentNode); + currentNode = currentNode.parent + ) { + if ( + currentNode.parent.type === "TryStatement" && + currentNode.parent.finalizer === currentNode + ) { + return true; + } + } + + return false; +} + +/** + * Checks all segments in a set and returns true if any are reachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if any segment is reachable; false otherwise. + */ +function isAnySegmentReachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return true; + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow redundant return statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-return", + }, + + fixable: "code", + schema: [], + + messages: { + unnecessaryReturn: "Unnecessary return statement.", + }, + }, + + create(context) { + const segmentInfoMap = new WeakMap(); + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Checks whether the given segment is terminated by a return statement or not. + * @param {CodePathSegment} segment The segment to check. + * @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable. + */ + function isReturned(segment) { + const info = segmentInfoMap.get(segment); + + return !info || info.returned; + } + + /** + * Collects useless return statements from the given previous segments. + * + * A previous segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * @param {ASTNode[]} uselessReturns The collected return statements. + * @param {CodePathSegment[]} prevSegments The previous segments to traverse. + * @param {WeakSet} [providedTraversedSegments] A set of segments that have already been traversed in this call + * @returns {ASTNode[]} `uselessReturns`. + */ + function getUselessReturns( + uselessReturns, + prevSegments, + providedTraversedSegments, + ) { + const traversedSegments = + providedTraversedSegments || new WeakSet(); + + for (const segment of prevSegments) { + if (!segment.reachable) { + if (!traversedSegments.has(segment)) { + traversedSegments.add(segment); + getUselessReturns( + uselessReturns, + segment.allPrevSegments.filter(isReturned), + traversedSegments, + ); + } + continue; + } + + if (segmentInfoMap.has(segment)) { + uselessReturns.push( + ...segmentInfoMap.get(segment).uselessReturns, + ); + } + } + + return uselessReturns; + } + + /** + * Removes the return statements on the given segment from the useless return + * statement list. + * + * This segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * @param {CodePathSegment} segment The segment to get return statements. + * @param {Set} usedUnreachableSegments A set of segments that have already been traversed in this call. + * @returns {void} + */ + function markReturnStatementsOnSegmentAsUsed( + segment, + usedUnreachableSegments, + ) { + if (!segment.reachable) { + usedUnreachableSegments.add(segment); + segment.allPrevSegments + .filter(isReturned) + .filter( + prevSegment => + !usedUnreachableSegments.has(prevSegment), + ) + .forEach(prevSegment => + markReturnStatementsOnSegmentAsUsed( + prevSegment, + usedUnreachableSegments, + ), + ); + return; + } + + const info = segmentInfoMap.get(segment); + + if (!info) { + return; + } + + info.uselessReturns = info.uselessReturns.filter(node => { + if ( + scopeInfo.traversedTryBlockStatements && + scopeInfo.traversedTryBlockStatements.length > 0 + ) { + const returnInitialRange = node.range[0]; + const returnFinalRange = node.range[1]; + + const areBlocksInRange = + scopeInfo.traversedTryBlockStatements.some( + tryBlockStatement => { + const blockInitialRange = + tryBlockStatement.range[0]; + const blockFinalRange = + tryBlockStatement.range[1]; + + return ( + returnInitialRange >= blockInitialRange && + returnFinalRange <= blockFinalRange + ); + }, + ); + + if (areBlocksInRange) { + return true; + } + } + + remove(scopeInfo.uselessReturns, node); + return false; + }); + } + + /** + * Removes the return statements on the current segments from the useless + * return statement list. + * + * This function will be called at every statement except FunctionDeclaration, + * BlockStatement, and BreakStatement. + * + * - FunctionDeclarations are always executed whether it's returned or not. + * - BlockStatements do nothing. + * - BreakStatements go the next merely. + * @returns {void} + */ + function markReturnStatementsOnCurrentSegmentsAsUsed() { + scopeInfo.currentSegments.forEach(segment => + markReturnStatementsOnSegmentAsUsed(segment, new Set()), + ); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + // Makes and pushes a new scope information. + onCodePathStart(codePath) { + scopeInfo = { + upper: scopeInfo, + uselessReturns: [], + traversedTryBlockStatements: [], + codePath, + currentSegments: new Set(), + }; + }, + + // Reports useless return statements if exist. + onCodePathEnd() { + for (const node of scopeInfo.uselessReturns) { + context.report({ + node, + loc: node.loc, + messageId: "unnecessaryReturn", + fix(fixer) { + if ( + isRemovable(node) && + !sourceCode.getCommentsInside(node).length + ) { + /* + * Extend the replacement range to include the + * entire function to avoid conflicting with + * no-else-return. + * https://github.com/eslint/eslint/issues/8026 + */ + return new FixTracker(fixer, sourceCode) + .retainEnclosingFunction(node) + .remove(node); + } + return null; + }, + }); + } + + scopeInfo = scopeInfo.upper; + }, + + /* + * Initializes segments. + * NOTE: This event is notified for only reachable segments. + */ + onCodePathSegmentStart(segment) { + scopeInfo.currentSegments.add(segment); + + const info = { + uselessReturns: getUselessReturns( + [], + segment.allPrevSegments, + ), + returned: false, + }; + + // Stores the info. + segmentInfoMap.set(segment, info); + }, + + onUnreachableCodePathSegmentStart(segment) { + scopeInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + scopeInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + scopeInfo.currentSegments.delete(segment); + }, + + // Adds ReturnStatement node to check whether it's useless or not. + ReturnStatement(node) { + if (node.argument) { + markReturnStatementsOnCurrentSegmentsAsUsed(); + } + if ( + node.argument || + astUtils.isInLoop(node) || + isInFinally(node) || + // Ignore `return` statements in unreachable places (https://github.com/eslint/eslint/issues/11647). + !isAnySegmentReachable(scopeInfo.currentSegments) + ) { + return; + } + + for (const segment of scopeInfo.currentSegments) { + const info = segmentInfoMap.get(segment); + + if (info) { + info.uselessReturns.push(node); + info.returned = true; + } + } + scopeInfo.uselessReturns.push(node); + }, + + "TryStatement > BlockStatement.block:exit"(node) { + scopeInfo.traversedTryBlockStatements.push(node); + }, + + "TryStatement:exit"() { + scopeInfo.traversedTryBlockStatements.pop(); + }, + + /* + * Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. + * Removes return statements of the current segments from the useless return statement list. + */ + ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportDefaultDeclaration: + markReturnStatementsOnCurrentSegmentsAsUsed, + ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-var.js b/node_modules/eslint/lib/rules/no-var.js new file mode 100644 index 00000000..39562d82 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-var.js @@ -0,0 +1,367 @@ +/** + * @fileoverview Rule to check for the usage of var. + * @author Jamund Ferguson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Check whether a given variable is a global variable or not. + * @param {eslint-scope.Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is a global variable. + */ +function isGlobal(variable) { + return Boolean(variable.scope) && variable.scope.type === "global"; +} + +/** + * Finds the nearest function scope or global scope walking up the scope + * hierarchy. + * @param {eslint-scope.Scope} scope The scope to traverse. + * @returns {eslint-scope.Scope} a function scope or global scope containing the given + * scope. + */ +function getEnclosingFunctionScope(scope) { + let currentScope = scope; + + while (currentScope.type !== "function" && currentScope.type !== "global") { + currentScope = currentScope.upper; + } + return currentScope; +} + +/** + * Checks whether the given variable has any references from a more specific + * function expression (i.e. a closure). + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is used from a closure. + */ +function isReferencedInClosure(variable) { + const enclosingFunctionScope = getEnclosingFunctionScope(variable.scope); + + return variable.references.some( + reference => + getEnclosingFunctionScope(reference.from) !== + enclosingFunctionScope, + ); +} + +/** + * Checks whether the given node is the assignee of a loop. + * @param {ASTNode} node A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration is assigned as part of loop + * iteration. + */ +function isLoopAssignee(node) { + return ( + (node.parent.type === "ForOfStatement" || + node.parent.type === "ForInStatement") && + node === node.parent.left + ); +} + +/** + * Checks whether the given variable declaration is immediately initialized. + * @param {ASTNode} node A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration has an initializer. + */ +function isDeclarationInitialized(node) { + return node.declarations.every(declarator => declarator.init !== null); +} + +const SCOPE_NODE_TYPE = + /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/u; + +/** + * Gets the scope node which directly contains a given node. + * @param {ASTNode} node A node to get. This is a `VariableDeclaration` or + * an `Identifier`. + * @returns {ASTNode} A scope node. This is one of `Program`, `BlockStatement`, + * `SwitchStatement`, `ForStatement`, `ForInStatement`, and + * `ForOfStatement`. + */ +function getScopeNode(node) { + for ( + let currentNode = node; + currentNode; + currentNode = currentNode.parent + ) { + if (SCOPE_NODE_TYPE.test(currentNode.type)) { + return currentNode; + } + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks whether a given variable is redeclared or not. + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is redeclared. + */ +function isRedeclared(variable) { + return variable.defs.length >= 2; +} + +/** + * Checks whether a given variable is used from outside of the specified scope. + * @param {ASTNode} scopeNode A scope node to check. + * @returns {Function} The predicate function which checks whether a given + * variable is used from outside of the specified scope. + */ +function isUsedFromOutsideOf(scopeNode) { + /** + * Checks whether a given reference is inside of the specified scope or not. + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is inside of the specified + * scope. + */ + function isOutsideOfScope(reference) { + const scope = scopeNode.range; + const id = reference.identifier.range; + + return id[0] < scope[0] || id[1] > scope[1]; + } + + return function (variable) { + return variable.references.some(isOutsideOfScope); + }; +} + +/** + * Creates the predicate function which checks whether a variable has their references in TDZ. + * + * The predicate function would return `true`: + * + * - if a reference is before the declarator. E.g. (var a = b, b = 1;)(var {a = b, b} = {};) + * - if a reference is in the expression of their default value. E.g. (var {a = a} = {};) + * - if a reference is in the expression of their initializer. E.g. (var a = a;) + * @param {ASTNode} node The initializer node of VariableDeclarator. + * @returns {Function} The predicate function. + * @private + */ +function hasReferenceInTDZ(node) { + const initStart = node.range[0]; + const initEnd = node.range[1]; + + return variable => { + const id = variable.defs[0].name; + const idStart = id.range[0]; + const defaultValue = + id.parent.type === "AssignmentPattern" ? id.parent.right : null; + const defaultStart = defaultValue && defaultValue.range[0]; + const defaultEnd = defaultValue && defaultValue.range[1]; + + return variable.references.some(reference => { + const start = reference.identifier.range[0]; + const end = reference.identifier.range[1]; + + return ( + !reference.init && + (start < idStart || + (defaultValue !== null && + start >= defaultStart && + end <= defaultEnd) || + (!astUtils.isFunction(node) && + start >= initStart && + end <= initEnd)) + ); + }); + }; +} + +/** + * Checks whether a given variable has name that is allowed for 'var' declarations, + * but disallowed for `let` declarations. + * @param {eslint-scope.Variable} variable The variable to check. + * @returns {boolean} `true` if the variable has a disallowed name. + */ +function hasNameDisallowedForLetDeclarations(variable) { + return variable.name === "let"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: "Require `let` or `const` instead of `var`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-var", + }, + + schema: [], + fixable: "code", + + messages: { + unexpectedVar: "Unexpected var, use let or const instead.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks whether the variables which are defined by the given declarator node have their references in TDZ. + * @param {ASTNode} declarator The VariableDeclarator node to check. + * @returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ. + */ + function hasSelfReferenceInTDZ(declarator) { + if (!declarator.init) { + return false; + } + const variables = sourceCode.getDeclaredVariables(declarator); + + return variables.some(hasReferenceInTDZ(declarator.init)); + } + + /** + * Checks whether it can fix a given variable declaration or not. + * It cannot fix if the following cases: + * + * - A variable is a global variable. + * - A variable is declared on a SwitchCase node. + * - A variable is redeclared. + * - A variable is used from outside the scope. + * - A variable is used from a closure within a loop. + * - A variable might be used before it is assigned within a loop. + * - A variable might be used in TDZ. + * - A variable is declared in statement position (e.g. a single-line `IfStatement`) + * - A variable has name that is disallowed for `let` declarations. + * + * ## A variable is declared on a SwitchCase node. + * + * If this rule modifies 'var' declarations on a SwitchCase node, it + * would generate the warnings of 'no-case-declarations' rule. And the + * 'eslint:recommended' preset includes 'no-case-declarations' rule, so + * this rule doesn't modify those declarations. + * + * ## A variable is redeclared. + * + * The language spec disallows redeclarations of `let` declarations. + * Those variables would cause syntax errors. + * + * ## A variable is used from outside the scope. + * + * The language spec disallows accesses from outside of the scope for + * `let` declarations. Those variables would cause reference errors. + * + * ## A variable is used from a closure within a loop. + * + * A `var` declaration within a loop shares the same variable instance + * across all loop iterations, while a `let` declaration creates a new + * instance for each iteration. This means if a variable in a loop is + * referenced by any closure, changing it from `var` to `let` would + * change the behavior in a way that is generally unsafe. + * + * ## A variable might be used before it is assigned within a loop. + * + * Within a loop, a `let` declaration without an initializer will be + * initialized to null, while a `var` declaration will retain its value + * from the previous iteration, so it is only safe to change `var` to + * `let` if we can statically determine that the variable is always + * assigned a value before its first access in the loop body. To keep + * the implementation simple, we only convert `var` to `let` within + * loops when the variable is a loop assignee or the declaration has an + * initializer. + * @param {ASTNode} node A variable declaration node to check. + * @returns {boolean} `true` if it can fix the node. + */ + function canFix(node) { + const variables = sourceCode.getDeclaredVariables(node); + const scopeNode = getScopeNode(node); + + if ( + node.parent.type === "SwitchCase" || + node.declarations.some(hasSelfReferenceInTDZ) || + variables.some(isGlobal) || + variables.some(isRedeclared) || + variables.some(isUsedFromOutsideOf(scopeNode)) || + variables.some(hasNameDisallowedForLetDeclarations) + ) { + return false; + } + + if (astUtils.isInLoop(node)) { + if (variables.some(isReferencedInClosure)) { + return false; + } + if (!isLoopAssignee(node) && !isDeclarationInitialized(node)) { + return false; + } + } + + if ( + !isLoopAssignee(node) && + !( + node.parent.type === "ForStatement" && + node.parent.init === node + ) && + !astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type) + ) { + // If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed. + return false; + } + + return true; + } + + /** + * Reports a given variable declaration node. + * @param {ASTNode} node A variable declaration node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "unexpectedVar", + + fix(fixer) { + const varToken = sourceCode.getFirstToken(node, { + filter: t => t.value === "var", + }); + + return canFix(node) + ? fixer.replaceText(varToken, "let") + : null; + }, + }); + } + + return { + "VariableDeclaration:exit"(node) { + if (node.kind !== "var") { + return; + } + + if ( + node.parent.type === "TSModuleBlock" && + node.parent.parent.type === "TSModuleDeclaration" && + node.parent.parent.global + ) { + return; + } + + report(node); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-void.js b/node_modules/eslint/lib/rules/no-void.js new file mode 100644 index 00000000..7e99fd3c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-void.js @@ -0,0 +1,69 @@ +/** + * @fileoverview Rule to disallow use of void operator. + * @author Mike Sidorov + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowAsStatement: false, + }, + ], + + docs: { + description: "Disallow `void` operators", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-void", + }, + + messages: { + noVoid: "Expected 'undefined' and instead saw 'void'.", + }, + + schema: [ + { + type: "object", + properties: { + allowAsStatement: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + + create(context) { + const [{ allowAsStatement }] = context.options; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + 'UnaryExpression[operator="void"]'(node) { + if ( + allowAsStatement && + node.parent && + node.parent.type === "ExpressionStatement" + ) { + return; + } + context.report({ + node, + messageId: "noVoid", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-warning-comments.js b/node_modules/eslint/lib/rules/no-warning-comments.js new file mode 100644 index 00000000..8f1a7c36 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-warning-comments.js @@ -0,0 +1,209 @@ +/** + * @fileoverview Rule that warns about used warning comments + * @author Alexander Schmidt + */ + +"use strict"; + +const escapeRegExp = require("escape-string-regexp"); +const astUtils = require("./utils/ast-utils"); + +const CHAR_LIMIT = 40; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + location: "start", + terms: ["todo", "fixme", "xxx"], + }, + ], + + docs: { + description: "Disallow specified warning terms in comments", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-warning-comments", + }, + + schema: [ + { + type: "object", + properties: { + terms: { + type: "array", + items: { + type: "string", + }, + }, + location: { + enum: ["start", "anywhere"], + }, + decoration: { + type: "array", + items: { + type: "string", + pattern: "^\\S$", + }, + minItems: 1, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedComment: + "Unexpected '{{matchedTerm}}' comment: '{{comment}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ decoration, location, terms: warningTerms }] = context.options; + const escapedDecoration = escapeRegExp( + decoration ? decoration.join("") : "", + ); + const selfConfigRegEx = /\bno-warning-comments\b/u; + + /** + * Convert a warning term into a RegExp which will match a comment containing that whole word in the specified + * location ("start" or "anywhere"). If the term starts or ends with non word characters, then the match will not + * require word boundaries on that side. + * @param {string} term A term to convert to a RegExp + * @returns {RegExp} The term converted to a RegExp + */ + function convertToRegExp(term) { + const escaped = escapeRegExp(term); + + /* + * When matching at the start, ignore leading whitespace, and + * there's no need to worry about word boundaries. + * + * These expressions for the prefix and suffix are designed as follows: + * ^ handles any terms at the beginning of a comment. + * e.g. terms ["TODO"] matches `//TODO something` + * $ handles any terms at the end of a comment + * e.g. terms ["TODO"] matches `// something TODO` + * \b handles terms preceded/followed by word boundary + * e.g. terms: ["!FIX", "FIX!"] matches `// FIX!something` or `// something!FIX` + * terms: ["FIX"] matches `// FIX!` or `// !FIX`, but not `// fixed or affix` + * + * For location start: + * [\s]* handles optional leading spaces + * e.g. terms ["TODO"] matches `// TODO something` + * [\s\*]* (where "\*" is the escaped string of decoration) + * handles optional leading spaces or decoration characters (for "start" location only) + * e.g. terms ["TODO"] matches `/**** TODO something ... ` + */ + const wordBoundary = "\\b"; + + let prefix = ""; + + if (location === "start") { + prefix = `^[\\s${escapedDecoration}]*`; + } else if (/^\w/u.test(term)) { + prefix = wordBoundary; + } + + const suffix = /\w$/u.test(term) ? wordBoundary : ""; + const flags = "iu"; // Case-insensitive with Unicode case folding. + + /* + * For location "start", the typical regex is: + * /^[\s]*ESCAPED_TERM\b/iu. + * Or if decoration characters are specified (e.g. "*"), then any of + * those characters may appear in any order at the start: + * /^[\s\*]*ESCAPED_TERM\b/iu. + * + * For location "anywhere" the typical regex is + * /\bESCAPED_TERM\b/iu + * + * If it starts or ends with non-word character, the prefix and suffix are empty, respectively. + */ + return new RegExp(`${prefix}${escaped}${suffix}`, flags); + } + + const warningRegExps = warningTerms.map(convertToRegExp); + + /** + * Checks the specified comment for matches of the configured warning terms and returns the matches. + * @param {string} comment The comment which is checked. + * @returns {Array} All matched warning terms for this comment. + */ + function commentContainsWarningTerm(comment) { + const matches = []; + + warningRegExps.forEach((regex, index) => { + if (regex.test(comment)) { + matches.push(warningTerms[index]); + } + }); + + return matches; + } + + /** + * Checks the specified node for matching warning comments and reports them. + * @param {ASTNode} node The AST node being checked. + * @returns {void} undefined. + */ + function checkComment(node) { + const comment = node.value; + + if ( + astUtils.isDirectiveComment(node) && + selfConfigRegEx.test(comment) + ) { + return; + } + + const matches = commentContainsWarningTerm(comment); + + matches.forEach(matchedTerm => { + let commentToDisplay = ""; + let truncated = false; + + for (const c of comment.trim().split(/\s+/u)) { + const tmp = commentToDisplay + ? `${commentToDisplay} ${c}` + : c; + + if (tmp.length <= CHAR_LIMIT) { + commentToDisplay = tmp; + } else { + truncated = true; + break; + } + } + + context.report({ + node, + messageId: "unexpectedComment", + data: { + matchedTerm, + comment: `${commentToDisplay}${truncated ? "..." : ""}`, + }, + }); + }); + } + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments + .filter(token => token.type !== "Shebang") + .forEach(checkComment); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-whitespace-before-property.js b/node_modules/eslint/lib/rules/no-whitespace-before-property.js new file mode 100644 index 00000000..f9b6fe45 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-whitespace-before-property.js @@ -0,0 +1,150 @@ +/** + * @fileoverview Rule to disallow whitespace before properties + * @author Kai Cataldo + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "no-whitespace-before-property", + url: "https://eslint.style/rules/js/no-whitespace-before-property", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow whitespace before properties", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-whitespace-before-property", + }, + + fixable: "whitespace", + schema: [], + + messages: { + unexpectedWhitespace: + "Unexpected whitespace before property {{propName}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports whitespace before property token + * @param {ASTNode} node the node to report in the event of an error + * @param {Token} leftToken the left token + * @param {Token} rightToken the right token + * @returns {void} + * @private + */ + function reportError(node, leftToken, rightToken) { + context.report({ + node, + messageId: "unexpectedWhitespace", + data: { + propName: sourceCode.getText(node.property), + }, + fix(fixer) { + let replacementText = ""; + + if ( + !node.computed && + !node.optional && + astUtils.isDecimalInteger(node.object) + ) { + /* + * If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError. + * Don't fix this case. + */ + return null; + } + + // Don't fix if comments exist. + if ( + sourceCode.commentsExistBetween(leftToken, rightToken) + ) { + return null; + } + + if (node.optional) { + replacementText = "?."; + } else if (!node.computed) { + replacementText = "."; + } + + return fixer.replaceTextRange( + [leftToken.range[1], rightToken.range[0]], + replacementText, + ); + }, + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + MemberExpression(node) { + let rightToken; + let leftToken; + + if (!astUtils.isTokenOnSameLine(node.object, node.property)) { + return; + } + + if (node.computed) { + rightToken = sourceCode.getTokenBefore( + node.property, + astUtils.isOpeningBracketToken, + ); + leftToken = sourceCode.getTokenBefore( + rightToken, + node.optional ? 1 : 0, + ); + } else { + rightToken = sourceCode.getFirstToken(node.property); + leftToken = sourceCode.getTokenBefore(rightToken, 1); + } + + if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken)) { + reportError(node, leftToken, rightToken); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-with.js b/node_modules/eslint/lib/rules/no-with.js new file mode 100644 index 00000000..d8be31f7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-with.js @@ -0,0 +1,37 @@ +/** + * @fileoverview Rule to flag use of with statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `with` statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-with", + }, + + schema: [], + + messages: { + unexpectedWith: "Unexpected use of 'with' statement.", + }, + }, + + create(context) { + return { + WithStatement(node) { + context.report({ node, messageId: "unexpectedWith" }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/nonblock-statement-body-position.js b/node_modules/eslint/lib/rules/nonblock-statement-body-position.js new file mode 100644 index 00000000..241848f3 --- /dev/null +++ b/node_modules/eslint/lib/rules/nonblock-statement-body-position.js @@ -0,0 +1,164 @@ +/** + * @fileoverview enforce the location of single-line statements + * @author Teddy Katz + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const POSITION_SCHEMA = { enum: ["beside", "below", "any"] }; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "nonblock-statement-body-position", + url: "https://eslint.style/rules/js/nonblock-statement-body-position", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce the location of single-line statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/nonblock-statement-body-position", + }, + + fixable: "whitespace", + + schema: [ + POSITION_SCHEMA, + { + properties: { + overrides: { + properties: { + if: POSITION_SCHEMA, + else: POSITION_SCHEMA, + while: POSITION_SCHEMA, + do: POSITION_SCHEMA, + for: POSITION_SCHEMA, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expectNoLinebreak: "Expected no linebreak before this statement.", + expectLinebreak: "Expected a linebreak before this statement.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Gets the applicable preference for a particular keyword + * @param {string} keywordName The name of a keyword, e.g. 'if' + * @returns {string} The applicable option for the keyword, e.g. 'beside' + */ + function getOption(keywordName) { + return ( + (context.options[1] && + context.options[1].overrides && + context.options[1].overrides[keywordName]) || + context.options[0] || + "beside" + ); + } + + /** + * Validates the location of a single-line statement + * @param {ASTNode} node The single-line statement + * @param {string} keywordName The applicable keyword name for the single-line statement + * @returns {void} + */ + function validateStatement(node, keywordName) { + const option = getOption(keywordName); + + if (node.type === "BlockStatement" || option === "any") { + return; + } + + const tokenBefore = sourceCode.getTokenBefore(node); + + if ( + tokenBefore.loc.end.line === node.loc.start.line && + option === "below" + ) { + context.report({ + node, + messageId: "expectLinebreak", + fix: fixer => fixer.insertTextBefore(node, "\n"), + }); + } else if ( + tokenBefore.loc.end.line !== node.loc.start.line && + option === "beside" + ) { + context.report({ + node, + messageId: "expectNoLinebreak", + fix(fixer) { + if ( + sourceCode + .getText() + .slice(tokenBefore.range[1], node.range[0]) + .trim() + ) { + return null; + } + return fixer.replaceTextRange( + [tokenBefore.range[1], node.range[0]], + " ", + ); + }, + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + IfStatement(node) { + validateStatement(node.consequent, "if"); + + // Check the `else` node, but don't check 'else if' statements. + if (node.alternate && node.alternate.type !== "IfStatement") { + validateStatement(node.alternate, "else"); + } + }, + WhileStatement: node => validateStatement(node.body, "while"), + DoWhileStatement: node => validateStatement(node.body, "do"), + ForStatement: node => validateStatement(node.body, "for"), + ForInStatement: node => validateStatement(node.body, "for"), + ForOfStatement: node => validateStatement(node.body, "for"), + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/object-curly-newline.js b/node_modules/eslint/lib/rules/object-curly-newline.js new file mode 100644 index 00000000..3935f8af --- /dev/null +++ b/node_modules/eslint/lib/rules/object-curly-newline.js @@ -0,0 +1,383 @@ +/** + * @fileoverview Rule to require or disallow line breaks inside braces. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Schema objects. +const OPTION_VALUE = { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + multiline: { + type: "boolean", + }, + minProperties: { + type: "integer", + minimum: 0, + }, + consistent: { + type: "boolean", + }, + }, + additionalProperties: false, + minProperties: 1, + }, + ], +}; + +/** + * Normalizes a given option value. + * @param {string|Object|undefined} value An option value to parse. + * @returns {{multiline: boolean, minProperties: number, consistent: boolean}} Normalized option object. + */ +function normalizeOptionValue(value) { + let multiline = false; + let minProperties = Number.POSITIVE_INFINITY; + let consistent = false; + + if (value) { + if (value === "always") { + minProperties = 0; + } else if (value === "never") { + minProperties = Number.POSITIVE_INFINITY; + } else { + multiline = Boolean(value.multiline); + minProperties = value.minProperties || Number.POSITIVE_INFINITY; + consistent = Boolean(value.consistent); + } + } else { + consistent = true; + } + + return { multiline, minProperties, consistent }; +} + +/** + * Checks if a value is an object. + * @param {any} value The value to check + * @returns {boolean} `true` if the value is an object, otherwise `false` + */ +function isObject(value) { + return typeof value === "object" && value !== null; +} + +/** + * Checks if an option is a node-specific option + * @param {any} option The option to check + * @returns {boolean} `true` if the option is node-specific, otherwise `false` + */ +function isNodeSpecificOption(option) { + return isObject(option) || typeof option === "string"; +} + +/** + * Normalizes a given option value. + * @param {string|Object|undefined} options An option value to parse. + * @returns {{ + * ObjectExpression: {multiline: boolean, minProperties: number, consistent: boolean}, + * ObjectPattern: {multiline: boolean, minProperties: number, consistent: boolean}, + * ImportDeclaration: {multiline: boolean, minProperties: number, consistent: boolean}, + * ExportNamedDeclaration : {multiline: boolean, minProperties: number, consistent: boolean} + * }} Normalized option object. + */ +function normalizeOptions(options) { + if ( + isObject(options) && + Object.values(options).some(isNodeSpecificOption) + ) { + return { + ObjectExpression: normalizeOptionValue(options.ObjectExpression), + ObjectPattern: normalizeOptionValue(options.ObjectPattern), + ImportDeclaration: normalizeOptionValue(options.ImportDeclaration), + ExportNamedDeclaration: normalizeOptionValue( + options.ExportDeclaration, + ), + }; + } + + const value = normalizeOptionValue(options); + + return { + ObjectExpression: value, + ObjectPattern: value, + ImportDeclaration: value, + ExportNamedDeclaration: value, + }; +} + +/** + * Determines if ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration + * node needs to be checked for missing line breaks + * @param {ASTNode} node Node under inspection + * @param {Object} options option specific to node type + * @param {Token} first First object property + * @param {Token} last Last object property + * @returns {boolean} `true` if node needs to be checked for missing line breaks + */ +function areLineBreaksRequired(node, options, first, last) { + let objectProperties; + + if (node.type === "ObjectExpression" || node.type === "ObjectPattern") { + objectProperties = node.properties; + } else { + // is ImportDeclaration or ExportNamedDeclaration + objectProperties = node.specifiers.filter( + s => s.type === "ImportSpecifier" || s.type === "ExportSpecifier", + ); + } + + return ( + objectProperties.length >= options.minProperties || + (options.multiline && + objectProperties.length > 0 && + first.loc.start.line !== last.loc.end.line) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "object-curly-newline", + url: "https://eslint.style/rules/js/object-curly-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent line breaks after opening and before closing braces", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-curly-newline", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + OPTION_VALUE, + { + type: "object", + properties: { + ObjectExpression: OPTION_VALUE, + ObjectPattern: OPTION_VALUE, + ImportDeclaration: OPTION_VALUE, + ExportDeclaration: OPTION_VALUE, + }, + additionalProperties: false, + minProperties: 1, + }, + ], + }, + ], + + messages: { + unexpectedLinebreakBeforeClosingBrace: + "Unexpected line break before this closing brace.", + unexpectedLinebreakAfterOpeningBrace: + "Unexpected line break after this opening brace.", + expectedLinebreakBeforeClosingBrace: + "Expected a line break before this closing brace.", + expectedLinebreakAfterOpeningBrace: + "Expected a line break after this opening brace.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const normalizedOptions = normalizeOptions(context.options[0]); + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node A node to check. This is an ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration node. + * @returns {void} + */ + function check(node) { + const options = normalizedOptions[node.type]; + + if ( + (node.type === "ImportDeclaration" && + !node.specifiers.some( + specifier => specifier.type === "ImportSpecifier", + )) || + (node.type === "ExportNamedDeclaration" && + !node.specifiers.some( + specifier => specifier.type === "ExportSpecifier", + )) + ) { + return; + } + + const openBrace = sourceCode.getFirstToken( + node, + token => token.value === "{", + ); + + let closeBrace; + + if (node.typeAnnotation) { + closeBrace = sourceCode.getTokenBefore(node.typeAnnotation); + } else { + closeBrace = sourceCode.getLastToken( + node, + token => token.value === "}", + ); + } + + let first = sourceCode.getTokenAfter(openBrace, { + includeComments: true, + }); + let last = sourceCode.getTokenBefore(closeBrace, { + includeComments: true, + }); + + const needsLineBreaks = areLineBreaksRequired( + node, + options, + first, + last, + ); + + const hasCommentsFirstToken = astUtils.isCommentToken(first); + const hasCommentsLastToken = astUtils.isCommentToken(last); + + /* + * Use tokens or comments to check multiline or not. + * But use only tokens to check whether line breaks are needed. + * This allows: + * var obj = { // eslint-disable-line foo + * a: 1 + * } + */ + first = sourceCode.getTokenAfter(openBrace); + last = sourceCode.getTokenBefore(closeBrace); + + if (needsLineBreaks) { + if (astUtils.isTokenOnSameLine(openBrace, first)) { + context.report({ + messageId: "expectedLinebreakAfterOpeningBrace", + node, + loc: openBrace.loc, + fix(fixer) { + if (hasCommentsFirstToken) { + return null; + } + + return fixer.insertTextAfter(openBrace, "\n"); + }, + }); + } + if (astUtils.isTokenOnSameLine(last, closeBrace)) { + context.report({ + messageId: "expectedLinebreakBeforeClosingBrace", + node, + loc: closeBrace.loc, + fix(fixer) { + if (hasCommentsLastToken) { + return null; + } + + return fixer.insertTextBefore(closeBrace, "\n"); + }, + }); + } + } else { + const consistent = options.consistent; + const hasLineBreakBetweenOpenBraceAndFirst = + !astUtils.isTokenOnSameLine(openBrace, first); + const hasLineBreakBetweenCloseBraceAndLast = + !astUtils.isTokenOnSameLine(last, closeBrace); + + if ( + (!consistent && hasLineBreakBetweenOpenBraceAndFirst) || + (consistent && + hasLineBreakBetweenOpenBraceAndFirst && + !hasLineBreakBetweenCloseBraceAndLast) + ) { + context.report({ + messageId: "unexpectedLinebreakAfterOpeningBrace", + node, + loc: openBrace.loc, + fix(fixer) { + if (hasCommentsFirstToken) { + return null; + } + + return fixer.removeRange([ + openBrace.range[1], + first.range[0], + ]); + }, + }); + } + if ( + (!consistent && hasLineBreakBetweenCloseBraceAndLast) || + (consistent && + !hasLineBreakBetweenOpenBraceAndFirst && + hasLineBreakBetweenCloseBraceAndLast) + ) { + context.report({ + messageId: "unexpectedLinebreakBeforeClosingBrace", + node, + loc: closeBrace.loc, + fix(fixer) { + if (hasCommentsLastToken) { + return null; + } + + return fixer.removeRange([ + last.range[1], + closeBrace.range[0], + ]); + }, + }); + } + } + } + + return { + ObjectExpression: check, + ObjectPattern: check, + ImportDeclaration: check, + ExportNamedDeclaration: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/object-curly-spacing.js b/node_modules/eslint/lib/rules/object-curly-spacing.js new file mode 100644 index 00000000..cedb144e --- /dev/null +++ b/node_modules/eslint/lib/rules/object-curly-spacing.js @@ -0,0 +1,375 @@ +/** + * @fileoverview Disallows or enforces spaces inside of object literals. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "object-curly-spacing", + url: "https://eslint.style/rules/js/object-curly-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing inside braces", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-curly-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + arraysInObjects: { + type: "boolean", + }, + objectsInObjects: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + requireSpaceBefore: "A space is required before '{{token}}'.", + requireSpaceAfter: "A space is required after '{{token}}'.", + unexpectedSpaceBefore: + "There should be no space before '{{token}}'.", + unexpectedSpaceAfter: "There should be no space after '{{token}}'.", + }, + }, + + create(context) { + const spaced = context.options[0] === "always", + sourceCode = context.sourceCode; + + /** + * Determines whether an option is set, relative to the spacing option. + * If spaced is "always", then check whether option is set to false. + * If spaced is "never", then check whether option is set to true. + * @param {Object} option The option to exclude. + * @returns {boolean} Whether or not the property is excluded. + */ + function isOptionSet(option) { + return context.options[1] + ? context.options[1][option] === !spaced + : false; + } + + const options = { + spaced, + arraysInObjectsException: isOptionSet("arraysInObjects"), + objectsInObjectsException: isOptionSet("objectsInObjects"), + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoBeginningSpace(node, token) { + const nextToken = context.sourceCode.getTokenAfter(token, { + includeComments: true, + }); + + context.report({ + node, + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "unexpectedSpaceAfter", + data: { + token: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoEndingSpace(node, token) { + const previousToken = context.sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + context.report({ + node, + loc: { start: previousToken.loc.end, end: token.loc.start }, + messageId: "unexpectedSpaceBefore", + data: { + token: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + previousToken.range[1], + token.range[0], + ]); + }, + }); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "requireSpaceAfter", + data: { + token: token.value, + }, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "requireSpaceBefore", + data: { + token: token.value, + }, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + + /** + * Determines if spacing in curly braces is valid. + * @param {ASTNode} node The AST node to check. + * @param {Token} first The first token to check (should be the opening brace) + * @param {Token} second The second token to check (should be first after the opening brace) + * @param {Token} penultimate The penultimate token to check (should be last before closing brace) + * @param {Token} last The last token to check (should be closing brace) + * @returns {void} + */ + function validateBraceSpacing(node, first, second, penultimate, last) { + if (astUtils.isTokenOnSameLine(first, second)) { + const firstSpaced = sourceCode.isSpaceBetweenTokens( + first, + second, + ); + + if (options.spaced && !firstSpaced) { + reportRequiredBeginningSpace(node, first); + } + if (!options.spaced && firstSpaced && second.type !== "Line") { + reportNoBeginningSpace(node, first); + } + } + + if (astUtils.isTokenOnSameLine(penultimate, last)) { + const shouldCheckPenultimate = + (options.arraysInObjectsException && + astUtils.isClosingBracketToken(penultimate)) || + (options.objectsInObjectsException && + astUtils.isClosingBraceToken(penultimate)); + const penultimateType = + shouldCheckPenultimate && + sourceCode.getNodeByRangeIndex(penultimate.range[0]).type; + + const closingCurlyBraceMustBeSpaced = + (options.arraysInObjectsException && + penultimateType === "ArrayExpression") || + (options.objectsInObjectsException && + (penultimateType === "ObjectExpression" || + penultimateType === "ObjectPattern")) + ? !options.spaced + : options.spaced; + + const lastSpaced = sourceCode.isSpaceBetweenTokens( + penultimate, + last, + ); + + if (closingCurlyBraceMustBeSpaced && !lastSpaced) { + reportRequiredEndingSpace(node, last); + } + if (!closingCurlyBraceMustBeSpaced && lastSpaced) { + reportNoEndingSpace(node, last); + } + } + } + + /** + * Gets '}' token of an object node. + * + * Because the last token of object patterns might be a type annotation, + * this traverses tokens preceded by the last property, then returns the + * first '}' token. + * @param {ASTNode} node The node to get. This node is an + * ObjectExpression or an ObjectPattern. And this node has one or + * more properties. + * @returns {Token} '}' token. + */ + function getClosingBraceOfObject(node) { + const lastProperty = node.properties.at(-1); + + return sourceCode.getTokenAfter( + lastProperty, + astUtils.isClosingBraceToken, + ); + } + + /** + * Reports a given object node if spacing in curly braces is invalid. + * @param {ASTNode} node An ObjectExpression or ObjectPattern node to check. + * @returns {void} + */ + function checkForObject(node) { + if (node.properties.length === 0) { + return; + } + + const first = sourceCode.getFirstToken(node), + last = getClosingBraceOfObject(node), + second = sourceCode.getTokenAfter(first, { + includeComments: true, + }), + penultimate = sourceCode.getTokenBefore(last, { + includeComments: true, + }); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + /** + * Reports a given import node if spacing in curly braces is invalid. + * @param {ASTNode} node An ImportDeclaration node to check. + * @returns {void} + */ + function checkForImport(node) { + if (node.specifiers.length === 0) { + return; + } + + let firstSpecifier = node.specifiers[0]; + const lastSpecifier = node.specifiers.at(-1); + + if (lastSpecifier.type !== "ImportSpecifier") { + return; + } + if (firstSpecifier.type !== "ImportSpecifier") { + firstSpecifier = node.specifiers[1]; + } + + const first = sourceCode.getTokenBefore(firstSpecifier), + last = sourceCode.getTokenAfter( + lastSpecifier, + astUtils.isNotCommaToken, + ), + second = sourceCode.getTokenAfter(first, { + includeComments: true, + }), + penultimate = sourceCode.getTokenBefore(last, { + includeComments: true, + }); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + /** + * Reports a given export node if spacing in curly braces is invalid. + * @param {ASTNode} node An ExportNamedDeclaration node to check. + * @returns {void} + */ + function checkForExport(node) { + if (node.specifiers.length === 0) { + return; + } + + const firstSpecifier = node.specifiers[0], + lastSpecifier = node.specifiers.at(-1), + first = sourceCode.getTokenBefore(firstSpecifier), + last = sourceCode.getTokenAfter( + lastSpecifier, + astUtils.isNotCommaToken, + ), + second = sourceCode.getTokenAfter(first, { + includeComments: true, + }), + penultimate = sourceCode.getTokenBefore(last, { + includeComments: true, + }); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + // var {x} = y; + ObjectPattern: checkForObject, + + // var y = {x: 'y'} + ObjectExpression: checkForObject, + + // import {y} from 'x'; + ImportDeclaration: checkForImport, + + // export {name} from 'yo'; + ExportNamedDeclaration: checkForExport, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/object-property-newline.js b/node_modules/eslint/lib/rules/object-property-newline.js new file mode 100644 index 00000000..fcf92591 --- /dev/null +++ b/node_modules/eslint/lib/rules/object-property-newline.js @@ -0,0 +1,151 @@ +/** + * @fileoverview Rule to enforce placing object properties on separate lines. + * @author Vitor Balocco + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "object-property-newline", + url: "https://eslint.style/rules/js/object-property-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce placing object properties on separate lines", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-property-newline", + }, + + schema: [ + { + type: "object", + properties: { + allowAllPropertiesOnSameLine: { + type: "boolean", + default: false, + }, + allowMultiplePropertiesPerLine: { + // Deprecated + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + fixable: "whitespace", + + messages: { + propertiesOnNewlineAll: + "Object properties must go on a new line if they aren't all on the same line.", + propertiesOnNewline: "Object properties must go on a new line.", + }, + }, + + create(context) { + const allowSameLine = + context.options[0] && + (context.options[0].allowAllPropertiesOnSameLine || + context.options[0] + .allowMultiplePropertiesPerLine); /* Deprecated */ + const messageId = allowSameLine + ? "propertiesOnNewlineAll" + : "propertiesOnNewline"; + + const sourceCode = context.sourceCode; + + return { + ObjectExpression(node) { + if (allowSameLine) { + if (node.properties.length > 1) { + const firstTokenOfFirstProperty = + sourceCode.getFirstToken(node.properties[0]); + const lastTokenOfLastProperty = sourceCode.getLastToken( + node.properties.at(-1), + ); + + if ( + firstTokenOfFirstProperty.loc.end.line === + lastTokenOfLastProperty.loc.start.line + ) { + // All keys and values are on the same line + return; + } + } + } + + for (let i = 1; i < node.properties.length; i++) { + const lastTokenOfPreviousProperty = sourceCode.getLastToken( + node.properties[i - 1], + ); + const firstTokenOfCurrentProperty = + sourceCode.getFirstToken(node.properties[i]); + + if ( + lastTokenOfPreviousProperty.loc.end.line === + firstTokenOfCurrentProperty.loc.start.line + ) { + context.report({ + node, + loc: firstTokenOfCurrentProperty.loc, + messageId, + fix(fixer) { + const comma = sourceCode.getTokenBefore( + firstTokenOfCurrentProperty, + ); + const rangeAfterComma = [ + comma.range[1], + firstTokenOfCurrentProperty.range[0], + ]; + + // Don't perform a fix if there are any comments between the comma and the next property. + if ( + sourceCode.text + .slice( + rangeAfterComma[0], + rangeAfterComma[1], + ) + .trim() + ) { + return null; + } + + return fixer.replaceTextRange( + rangeAfterComma, + "\n", + ); + }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/object-shorthand.js b/node_modules/eslint/lib/rules/object-shorthand.js new file mode 100644 index 00000000..5ada21da --- /dev/null +++ b/node_modules/eslint/lib/rules/object-shorthand.js @@ -0,0 +1,627 @@ +/** + * @fileoverview Rule to enforce concise object methods and properties. + * @author Jamund Ferguson + */ + +"use strict"; + +const OPTIONS = { + always: "always", + never: "never", + methods: "methods", + properties: "properties", + consistent: "consistent", + consistentAsNeeded: "consistent-as-needed", +}; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require or disallow method and property shorthand syntax for object literals", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/object-shorthand", + }, + + fixable: "code", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: [ + "always", + "methods", + "properties", + "never", + "consistent", + "consistent-as-needed", + ], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["always", "methods", "properties"], + }, + { + type: "object", + properties: { + avoidQuotes: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + { + type: "array", + items: [ + { + enum: ["always", "methods"], + }, + { + type: "object", + properties: { + ignoreConstructors: { + type: "boolean", + }, + methodsIgnorePattern: { + type: "string", + }, + avoidQuotes: { + type: "boolean", + }, + avoidExplicitReturnArrows: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + messages: { + expectedAllPropertiesShorthanded: + "Expected shorthand for all properties.", + expectedLiteralMethodLongform: + "Expected longform method syntax for string literal keys.", + expectedPropertyShorthand: "Expected property shorthand.", + expectedPropertyLongform: "Expected longform property syntax.", + expectedMethodShorthand: "Expected method shorthand.", + expectedMethodLongform: "Expected longform method syntax.", + unexpectedMix: + "Unexpected mix of shorthand and non-shorthand properties.", + }, + }, + + create(context) { + const APPLY = context.options[0] || OPTIONS.always; + const APPLY_TO_METHODS = + APPLY === OPTIONS.methods || APPLY === OPTIONS.always; + const APPLY_TO_PROPS = + APPLY === OPTIONS.properties || APPLY === OPTIONS.always; + const APPLY_NEVER = APPLY === OPTIONS.never; + const APPLY_CONSISTENT = APPLY === OPTIONS.consistent; + const APPLY_CONSISTENT_AS_NEEDED = APPLY === OPTIONS.consistentAsNeeded; + + const PARAMS = context.options[1] || {}; + const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors; + const METHODS_IGNORE_PATTERN = PARAMS.methodsIgnorePattern + ? new RegExp(PARAMS.methodsIgnorePattern, "u") + : null; + const AVOID_QUOTES = PARAMS.avoidQuotes; + const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const CTOR_PREFIX_REGEX = /[^_$0-9]/u; + + /** + * Determines if the first character of the name is a capital letter. + * @param {string} name The name of the node to evaluate. + * @returns {boolean} True if the first character of the property name is a capital letter, false if not. + * @private + */ + function isConstructor(name) { + const match = CTOR_PREFIX_REGEX.exec(name); + + // Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8' + if (!match) { + return false; + } + + const firstChar = name.charAt(match.index); + + return firstChar === firstChar.toUpperCase(); + } + + /** + * Determines if the property can have a shorthand form. + * @param {ASTNode} property Property AST node + * @returns {boolean} True if the property can have a shorthand form + * @private + */ + function canHaveShorthand(property) { + return ( + property.kind !== "set" && + property.kind !== "get" && + property.type !== "SpreadElement" && + property.type !== "SpreadProperty" && + property.type !== "ExperimentalSpreadProperty" + ); + } + + /** + * Checks whether a node is a string literal. + * @param {ASTNode} node Any AST node. + * @returns {boolean} `true` if it is a string literal. + */ + function isStringLiteral(node) { + return node.type === "Literal" && typeof node.value === "string"; + } + + /** + * Determines if the property is a shorthand or not. + * @param {ASTNode} property Property AST node + * @returns {boolean} True if the property is considered shorthand, false if not. + * @private + */ + function isShorthand(property) { + // property.method is true when `{a(){}}`. + return property.shorthand || property.method; + } + + /** + * Determines if the property's key and method or value are named equally. + * @param {ASTNode} property Property AST node + * @returns {boolean} True if the key and value are named equally, false if not. + * @private + */ + function isRedundant(property) { + const value = property.value; + + if (value.type === "FunctionExpression") { + return !value.id; // Only anonymous should be shorthand method. + } + if (value.type === "Identifier") { + return astUtils.getStaticPropertyName(property) === value.name; + } + + return false; + } + + /** + * Ensures that an object's properties are consistently shorthand, or not shorthand at all. + * @param {ASTNode} node Property AST node + * @param {boolean} checkRedundancy Whether to check longform redundancy + * @returns {void} + */ + function checkConsistency(node, checkRedundancy) { + // We are excluding getters/setters and spread properties as they are considered neither longform nor shorthand. + const properties = node.properties.filter(canHaveShorthand); + + // Do we still have properties left after filtering the getters and setters? + if (properties.length > 0) { + const shorthandProperties = properties.filter(isShorthand); + + /* + * If we do not have an equal number of longform properties as + * shorthand properties, we are using the annotations inconsistently + */ + if (shorthandProperties.length !== properties.length) { + // We have at least 1 shorthand property + if (shorthandProperties.length > 0) { + context.report({ node, messageId: "unexpectedMix" }); + } else if (checkRedundancy) { + /* + * If all properties of the object contain a method or value with a name matching it's key, + * all the keys are redundant. + */ + const canAlwaysUseShorthand = + properties.every(isRedundant); + + if (canAlwaysUseShorthand) { + context.report({ + node, + messageId: "expectedAllPropertiesShorthanded", + }); + } + } + } + } + } + + /** + * Fixes a FunctionExpression node by making it into a shorthand property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionShorthand(fixer, node) { + const firstKeyToken = node.computed + ? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken) + : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed + ? sourceCode.getFirstTokenBetween( + node.key, + node.value, + astUtils.isClosingBracketToken, + ) + : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice( + firstKeyToken.range[0], + lastKeyToken.range[1], + ); + let keyPrefix = ""; + + // key: /* */ () => {} + if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) { + return null; + } + + if (node.value.async) { + keyPrefix += "async "; + } + if (node.value.generator) { + keyPrefix += "*"; + } + + const fixRange = [firstKeyToken.range[0], node.range[1]]; + const methodPrefix = keyPrefix + keyText; + + if (node.value.type === "FunctionExpression") { + const functionToken = sourceCode + .getTokens(node.value) + .find( + token => + token.type === "Keyword" && + token.value === "function", + ); + const tokenBeforeParams = node.value.generator + ? sourceCode.getTokenAfter(functionToken) + : functionToken; + + return fixer.replaceTextRange( + fixRange, + methodPrefix + + sourceCode.text.slice( + tokenBeforeParams.range[1], + node.value.range[1], + ), + ); + } + + const arrowToken = sourceCode.getTokenBefore( + node.value.body, + astUtils.isArrowToken, + ); + const fnBody = sourceCode.text.slice( + arrowToken.range[1], + node.value.range[1], + ); + + // First token should not be `async` + const firstValueToken = sourceCode.getFirstToken(node.value, { + skip: node.value.async ? 1 : 0, + }); + + const sliceStart = firstValueToken.range[0]; + const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1]; + const shouldAddParens = + node.value.params.length === 1 && + node.value.params[0].range[0] === sliceStart; + + const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd); + const newParamText = shouldAddParens + ? `(${oldParamText})` + : oldParamText; + + return fixer.replaceTextRange( + fixRange, + methodPrefix + newParamText + fnBody, + ); + } + + /** + * Fixes a FunctionExpression node by making it into a longform property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionLongform(fixer, node) { + const firstKeyToken = node.computed + ? sourceCode.getTokens(node).find(token => token.value === "[") + : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed + ? sourceCode + .getTokensBetween(node.key, node.value) + .find(token => token.value === "]") + : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice( + firstKeyToken.range[0], + lastKeyToken.range[1], + ); + let functionHeader = "function"; + + if (node.value.async) { + functionHeader = `async ${functionHeader}`; + } + if (node.value.generator) { + functionHeader = `${functionHeader}*`; + } + + return fixer.replaceTextRange( + [node.range[0], lastKeyToken.range[1]], + `${keyText}: ${functionHeader}`, + ); + } + + /* + * To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`), + * create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is + * traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical + * scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered, + * keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited. + * When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them + * to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule, + * because converting it into a method would change the value of one of the lexical identifiers. + */ + const lexicalScopeStack = []; + const arrowsWithLexicalIdentifiers = new WeakSet(); + const argumentsIdentifiers = new WeakSet(); + + /** + * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack. + * Also, this marks all `arguments` identifiers so that they can be detected later. + * @param {ASTNode} node The node representing the function. + * @returns {void} + */ + function enterFunction(node) { + lexicalScopeStack.unshift(new Set()); + sourceCode + .getScope(node) + .variables.filter(variable => variable.name === "arguments") + .forEach(variable => { + variable.references + .map(ref => ref.identifier) + .forEach(identifier => + argumentsIdentifiers.add(identifier), + ); + }); + } + + /** + * Exits a function. This pops the current set of arrow functions off the lexical scope stack. + * @returns {void} + */ + function exitFunction() { + lexicalScopeStack.shift(); + } + + /** + * Marks the current function as having a lexical keyword. This implies that all arrow functions + * in the current lexical scope contain a reference to this lexical keyword. + * @returns {void} + */ + function reportLexicalIdentifier() { + lexicalScopeStack[0].forEach(arrowFunction => + arrowsWithLexicalIdentifiers.add(arrowFunction), + ); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: enterFunction, + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + "Program:exit": exitFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + + ArrowFunctionExpression(node) { + lexicalScopeStack[0].add(node); + }, + "ArrowFunctionExpression:exit"(node) { + lexicalScopeStack[0].delete(node); + }, + + ThisExpression: reportLexicalIdentifier, + Super: reportLexicalIdentifier, + MetaProperty(node) { + if ( + node.meta.name === "new" && + node.property.name === "target" + ) { + reportLexicalIdentifier(); + } + }, + Identifier(node) { + if (argumentsIdentifiers.has(node)) { + reportLexicalIdentifier(); + } + }, + + ObjectExpression(node) { + if (APPLY_CONSISTENT) { + checkConsistency(node, false); + } else if (APPLY_CONSISTENT_AS_NEEDED) { + checkConsistency(node, true); + } + }, + + "Property:exit"(node) { + const isConciseProperty = node.method || node.shorthand; + + // Ignore destructuring assignment + if (node.parent.type === "ObjectPattern") { + return; + } + + // getters and setters are ignored + if (node.kind === "get" || node.kind === "set") { + return; + } + + // only computed methods can fail the following checks + if ( + node.computed && + node.value.type !== "FunctionExpression" && + node.value.type !== "ArrowFunctionExpression" + ) { + return; + } + + //-------------------------------------------------------------- + // Checks for property/method shorthand. + if (isConciseProperty) { + if ( + node.method && + (APPLY_NEVER || + (AVOID_QUOTES && isStringLiteral(node.key))) + ) { + const messageId = APPLY_NEVER + ? "expectedMethodLongform" + : "expectedLiteralMethodLongform"; + + // { x() {} } should be written as { x: function() {} } + context.report({ + node, + messageId, + fix: fixer => makeFunctionLongform(fixer, node), + }); + } else if (APPLY_NEVER) { + // { x } should be written as { x: x } + context.report({ + node, + messageId: "expectedPropertyLongform", + fix: fixer => + fixer.insertTextAfter( + node.key, + `: ${node.key.name}`, + ), + }); + } + } else if ( + APPLY_TO_METHODS && + !node.value.id && + (node.value.type === "FunctionExpression" || + node.value.type === "ArrowFunctionExpression") + ) { + if ( + IGNORE_CONSTRUCTORS && + node.key.type === "Identifier" && + isConstructor(node.key.name) + ) { + return; + } + + if (METHODS_IGNORE_PATTERN) { + const propertyName = + astUtils.getStaticPropertyName(node); + + if ( + propertyName !== null && + METHODS_IGNORE_PATTERN.test(propertyName) + ) { + return; + } + } + + if (AVOID_QUOTES && isStringLiteral(node.key)) { + return; + } + + // {[x]: function(){}} should be written as {[x]() {}} + if ( + node.value.type === "FunctionExpression" || + (node.value.type === "ArrowFunctionExpression" && + node.value.body.type === "BlockStatement" && + AVOID_EXPLICIT_RETURN_ARROWS && + !arrowsWithLexicalIdentifiers.has(node.value)) + ) { + context.report({ + node, + messageId: "expectedMethodShorthand", + fix: fixer => makeFunctionShorthand(fixer, node), + }); + } + } else if ( + node.value.type === "Identifier" && + node.key.name === node.value.name && + APPLY_TO_PROPS + ) { + // {x: x} should be written as {x} + context.report({ + node, + messageId: "expectedPropertyShorthand", + fix(fixer) { + // x: /* */ x + // x: (/* */ x) + if (sourceCode.getCommentsInside(node).length > 0) { + return null; + } + + return fixer.replaceText(node, node.value.name); + }, + }); + } else if ( + node.value.type === "Identifier" && + node.key.type === "Literal" && + node.key.value === node.value.name && + APPLY_TO_PROPS + ) { + if (AVOID_QUOTES) { + return; + } + + // {"x": x} should be written as {x} + context.report({ + node, + messageId: "expectedPropertyShorthand", + fix(fixer) { + // "x": /* */ x + // "x": (/* */ x) + if (sourceCode.getCommentsInside(node).length > 0) { + return null; + } + + return fixer.replaceText(node, node.value.name); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/one-var-declaration-per-line.js b/node_modules/eslint/lib/rules/one-var-declaration-per-line.js new file mode 100644 index 00000000..e8d919be --- /dev/null +++ b/node_modules/eslint/lib/rules/one-var-declaration-per-line.js @@ -0,0 +1,117 @@ +/** + * @fileoverview Rule to check multiple var declarations per line + * @author Alberto Rodríguez + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "one-var-declaration-per-line", + url: "https://eslint.style/rules/js/one-var-declaration-per-line", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: + "Require or disallow newlines around variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/one-var-declaration-per-line", + }, + + schema: [ + { + enum: ["always", "initializations"], + }, + ], + + fixable: "whitespace", + + messages: { + expectVarOnNewline: + "Expected variable declaration to be on a new line.", + }, + }, + + create(context) { + const always = context.options[0] === "always"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determine if provided keyword is a variant of for specifiers + * @private + * @param {string} keyword keyword to test + * @returns {boolean} True if `keyword` is a variant of for specifier + */ + function isForTypeSpecifier(keyword) { + return ( + keyword === "ForStatement" || + keyword === "ForInStatement" || + keyword === "ForOfStatement" + ); + } + + /** + * Checks newlines around variable declarations. + * @private + * @param {ASTNode} node `VariableDeclaration` node to test + * @returns {void} + */ + function checkForNewLine(node) { + if (isForTypeSpecifier(node.parent.type)) { + return; + } + + const declarations = node.declarations; + let prev; + + declarations.forEach(current => { + if (prev && prev.loc.end.line === current.loc.start.line) { + if (always || prev.init || current.init) { + context.report({ + node, + messageId: "expectVarOnNewline", + loc: current.loc, + fix: fixer => fixer.insertTextBefore(current, "\n"), + }); + } + } + prev = current; + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclaration: checkForNewLine, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/one-var.js b/node_modules/eslint/lib/rules/one-var.js new file mode 100644 index 00000000..c49fc601 --- /dev/null +++ b/node_modules/eslint/lib/rules/one-var.js @@ -0,0 +1,684 @@ +/** + * @fileoverview A rule to control the use of single variable declarations. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is in a statement list. + * @param {ASTNode} node node to check + * @returns {boolean} `true` if the given node is in a statement list + */ +function isInStatementList(node) { + return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce variables to be declared either together or separately in functions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/one-var", + }, + + fixable: "code", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never", "consecutive"], + }, + { + type: "object", + properties: { + separateRequires: { + type: "boolean", + }, + var: { + enum: ["always", "never", "consecutive"], + }, + let: { + enum: ["always", "never", "consecutive"], + }, + const: { + enum: ["always", "never", "consecutive"], + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + initialized: { + enum: ["always", "never", "consecutive"], + }, + uninitialized: { + enum: ["always", "never", "consecutive"], + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + combineUninitialized: + "Combine this with the previous '{{type}}' statement with uninitialized variables.", + combineInitialized: + "Combine this with the previous '{{type}}' statement with initialized variables.", + splitUninitialized: + "Split uninitialized '{{type}}' declarations into multiple statements.", + splitInitialized: + "Split initialized '{{type}}' declarations into multiple statements.", + splitRequires: + "Split requires to be separated into a single block.", + combine: "Combine this with the previous '{{type}}' statement.", + split: "Split '{{type}}' declarations into multiple statements.", + }, + }, + + create(context) { + const MODE_ALWAYS = "always"; + const MODE_NEVER = "never"; + const MODE_CONSECUTIVE = "consecutive"; + const mode = context.options[0] || MODE_ALWAYS; + + const options = {}; + + if (typeof mode === "string") { + // simple options configuration with just a string + options.var = { uninitialized: mode, initialized: mode }; + options.let = { uninitialized: mode, initialized: mode }; + options.const = { uninitialized: mode, initialized: mode }; + } else if (typeof mode === "object") { + // options configuration is an object + options.separateRequires = !!mode.separateRequires; + options.var = { uninitialized: mode.var, initialized: mode.var }; + options.let = { uninitialized: mode.let, initialized: mode.let }; + options.const = { + uninitialized: mode.const, + initialized: mode.const, + }; + if (Object.hasOwn(mode, "uninitialized")) { + options.var.uninitialized = mode.uninitialized; + options.let.uninitialized = mode.uninitialized; + options.const.uninitialized = mode.uninitialized; + } + if (Object.hasOwn(mode, "initialized")) { + options.var.initialized = mode.initialized; + options.let.initialized = mode.initialized; + options.const.initialized = mode.initialized; + } + } + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const functionStack = []; + const blockStack = []; + + /** + * Increments the blockStack counter. + * @returns {void} + * @private + */ + function startBlock() { + blockStack.push({ + let: { initialized: false, uninitialized: false }, + const: { initialized: false, uninitialized: false }, + }); + } + + /** + * Increments the functionStack counter. + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push({ initialized: false, uninitialized: false }); + startBlock(); + } + + /** + * Decrements the blockStack counter. + * @returns {void} + * @private + */ + function endBlock() { + blockStack.pop(); + } + + /** + * Decrements the functionStack counter. + * @returns {void} + * @private + */ + function endFunction() { + functionStack.pop(); + endBlock(); + } + + /** + * Check if a variable declaration is a require. + * @param {ASTNode} decl variable declaration Node + * @returns {bool} if decl is a require, return true; else return false. + * @private + */ + function isRequire(decl) { + return ( + decl.init && + decl.init.type === "CallExpression" && + decl.init.callee.name === "require" + ); + } + + /** + * Records whether initialized/uninitialized/required variables are defined in current scope. + * @param {string} statementType node.kind, one of: "var", "let", or "const" + * @param {ASTNode[]} declarations List of declarations + * @param {Object} currentScope The scope being investigated + * @returns {void} + * @private + */ + function recordTypes(statementType, declarations, currentScope) { + for (let i = 0; i < declarations.length; i++) { + if (declarations[i].init === null) { + if ( + options[statementType] && + options[statementType].uninitialized === MODE_ALWAYS + ) { + currentScope.uninitialized = true; + } + } else { + if ( + options[statementType] && + options[statementType].initialized === MODE_ALWAYS + ) { + if ( + options.separateRequires && + isRequire(declarations[i]) + ) { + currentScope.required = true; + } else { + currentScope.initialized = true; + } + } + } + } + } + + /** + * Determines the current scope (function or block) + * @param {string} statementType node.kind, one of: "var", "let", or "const" + * @returns {Object} The scope associated with statementType + */ + function getCurrentScope(statementType) { + let currentScope; + + if (statementType === "var") { + currentScope = functionStack.at(-1); + } else if (statementType === "let") { + currentScope = blockStack.at(-1).let; + } else if (statementType === "const") { + currentScope = blockStack.at(-1).const; + } + return currentScope; + } + + /** + * Counts the number of initialized and uninitialized declarations in a list of declarations + * @param {ASTNode[]} declarations List of declarations + * @returns {Object} Counts of 'uninitialized' and 'initialized' declarations + * @private + */ + function countDeclarations(declarations) { + const counts = { uninitialized: 0, initialized: 0 }; + + for (let i = 0; i < declarations.length; i++) { + if (declarations[i].init === null) { + counts.uninitialized++; + } else { + counts.initialized++; + } + } + return counts; + } + + /** + * Determines if there is more than one var statement in the current scope. + * @param {string} statementType node.kind, one of: "var", "let", or "const" + * @param {ASTNode[]} declarations List of declarations + * @returns {boolean} Returns true if it is the first var declaration, false if not. + * @private + */ + function hasOnlyOneStatement(statementType, declarations) { + const declarationCounts = countDeclarations(declarations); + const currentOptions = options[statementType] || {}; + const currentScope = getCurrentScope(statementType); + const hasRequires = declarations.some(isRequire); + + if ( + currentOptions.uninitialized === MODE_ALWAYS && + currentOptions.initialized === MODE_ALWAYS + ) { + if (currentScope.uninitialized || currentScope.initialized) { + if (!hasRequires) { + return false; + } + } + } + + if (declarationCounts.uninitialized > 0) { + if ( + currentOptions.uninitialized === MODE_ALWAYS && + currentScope.uninitialized + ) { + return false; + } + } + if (declarationCounts.initialized > 0) { + if ( + currentOptions.initialized === MODE_ALWAYS && + currentScope.initialized + ) { + if (!hasRequires) { + return false; + } + } + } + if (currentScope.required && hasRequires) { + return false; + } + recordTypes(statementType, declarations, currentScope); + return true; + } + + /** + * Fixer to join VariableDeclaration's into a single declaration + * @param {VariableDeclarator[]} declarations The `VariableDeclaration` to join + * @returns {Function} The fixer function + */ + function joinDeclarations(declarations) { + const declaration = declarations[0]; + const body = Array.isArray(declaration.parent.parent.body) + ? declaration.parent.parent.body + : []; + const currentIndex = body.findIndex( + node => node.range[0] === declaration.parent.range[0], + ); + const previousNode = body[currentIndex - 1]; + + return fixer => { + const type = sourceCode.getTokenBefore(declaration); + const prevSemi = sourceCode.getTokenBefore(type); + const res = []; + + if ( + previousNode && + previousNode.kind === sourceCode.getText(type) + ) { + if (prevSemi.value === ";") { + res.push(fixer.replaceText(prevSemi, ",")); + } else { + res.push(fixer.insertTextAfter(prevSemi, ",")); + } + res.push(fixer.replaceText(type, "")); + } + + return res; + }; + } + + /** + * Fixer to split a VariableDeclaration into individual declarations + * @param {VariableDeclaration} declaration The `VariableDeclaration` to split + * @returns {Function|null} The fixer function + */ + function splitDeclarations(declaration) { + const { parent } = declaration; + + // don't autofix code such as: if (foo) var x, y; + if ( + !isInStatementList( + parent.type === "ExportNamedDeclaration" + ? parent + : declaration, + ) + ) { + return null; + } + + return fixer => + declaration.declarations + .map(declarator => { + const tokenAfterDeclarator = + sourceCode.getTokenAfter(declarator); + + if (tokenAfterDeclarator === null) { + return null; + } + + const afterComma = sourceCode.getTokenAfter( + tokenAfterDeclarator, + { includeComments: true }, + ); + + if (tokenAfterDeclarator.value !== ",") { + return null; + } + + const exportPlacement = + declaration.parent.type === "ExportNamedDeclaration" + ? "export " + : ""; + + /* + * `var x,y` + * tokenAfterDeclarator ^^ afterComma + */ + if ( + afterComma.range[0] === + tokenAfterDeclarator.range[1] + ) { + return fixer.replaceText( + tokenAfterDeclarator, + `; ${exportPlacement}${declaration.kind} `, + ); + } + + /* + * `var x, + * tokenAfterDeclarator ^ + * y` + * ^ afterComma + */ + if ( + afterComma.loc.start.line > + tokenAfterDeclarator.loc.end.line || + afterComma.type === "Line" || + afterComma.type === "Block" + ) { + let lastComment = afterComma; + + while ( + lastComment.type === "Line" || + lastComment.type === "Block" + ) { + lastComment = sourceCode.getTokenAfter( + lastComment, + { includeComments: true }, + ); + } + + return fixer.replaceTextRange( + [ + tokenAfterDeclarator.range[0], + lastComment.range[0], + ], + `;${sourceCode.text.slice(tokenAfterDeclarator.range[1], lastComment.range[0])}${exportPlacement}${declaration.kind} `, + ); + } + + return fixer.replaceText( + tokenAfterDeclarator, + `; ${exportPlacement}${declaration.kind}`, + ); + }) + .filter(x => x); + } + + /** + * Checks a given VariableDeclaration node for errors. + * @param {ASTNode} node The VariableDeclaration node to check + * @returns {void} + * @private + */ + function checkVariableDeclaration(node) { + const parent = node.parent; + const type = node.kind; + + if (!options[type]) { + return; + } + + const declarations = node.declarations; + const declarationCounts = countDeclarations(declarations); + const mixedRequires = + declarations.some(isRequire) && !declarations.every(isRequire); + + if (options[type].initialized === MODE_ALWAYS) { + if (options.separateRequires && mixedRequires) { + context.report({ + node, + messageId: "splitRequires", + }); + } + } + + // consecutive + const nodeIndex = + (parent.body && + parent.body.length > 0 && + parent.body.indexOf(node)) || + 0; + + if (nodeIndex > 0) { + const previousNode = parent.body[nodeIndex - 1]; + const isPreviousNodeDeclaration = + previousNode.type === "VariableDeclaration"; + const declarationsWithPrevious = declarations.concat( + previousNode.declarations || [], + ); + + if ( + isPreviousNodeDeclaration && + previousNode.kind === type && + !( + declarationsWithPrevious.some(isRequire) && + !declarationsWithPrevious.every(isRequire) + ) + ) { + const previousDeclCounts = countDeclarations( + previousNode.declarations, + ); + + if ( + options[type].initialized === MODE_CONSECUTIVE && + options[type].uninitialized === MODE_CONSECUTIVE + ) { + context.report({ + node, + messageId: "combine", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } else if ( + options[type].initialized === MODE_CONSECUTIVE && + declarationCounts.initialized > 0 && + previousDeclCounts.initialized > 0 + ) { + context.report({ + node, + messageId: "combineInitialized", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } else if ( + options[type].uninitialized === MODE_CONSECUTIVE && + declarationCounts.uninitialized > 0 && + previousDeclCounts.uninitialized > 0 + ) { + context.report({ + node, + messageId: "combineUninitialized", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } + } + } + + // always + if (!hasOnlyOneStatement(type, declarations)) { + if ( + options[type].initialized === MODE_ALWAYS && + options[type].uninitialized === MODE_ALWAYS + ) { + context.report({ + node, + messageId: "combine", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } else { + if ( + options[type].initialized === MODE_ALWAYS && + declarationCounts.initialized > 0 + ) { + context.report({ + node, + messageId: "combineInitialized", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } + if ( + options[type].uninitialized === MODE_ALWAYS && + declarationCounts.uninitialized > 0 + ) { + if ( + node.parent.left === node && + (node.parent.type === "ForInStatement" || + node.parent.type === "ForOfStatement") + ) { + return; + } + context.report({ + node, + messageId: "combineUninitialized", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } + } + } + + // never + if (parent.type !== "ForStatement" || parent.init !== node) { + const totalDeclarations = + declarationCounts.uninitialized + + declarationCounts.initialized; + + if (totalDeclarations > 1) { + if ( + options[type].initialized === MODE_NEVER && + options[type].uninitialized === MODE_NEVER + ) { + // both initialized and uninitialized + context.report({ + node, + messageId: "split", + data: { + type, + }, + fix: splitDeclarations(node), + }); + } else if ( + options[type].initialized === MODE_NEVER && + declarationCounts.initialized > 0 + ) { + // initialized + context.report({ + node, + messageId: "splitInitialized", + data: { + type, + }, + fix: splitDeclarations(node), + }); + } else if ( + options[type].uninitialized === MODE_NEVER && + declarationCounts.uninitialized > 0 + ) { + // uninitialized + context.report({ + node, + messageId: "splitUninitialized", + data: { + type, + }, + fix: splitDeclarations(node), + }); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Program: startFunction, + FunctionDeclaration: startFunction, + FunctionExpression: startFunction, + ArrowFunctionExpression: startFunction, + StaticBlock: startFunction, // StaticBlock creates a new scope for `var` variables + + BlockStatement: startBlock, + ForStatement: startBlock, + ForInStatement: startBlock, + ForOfStatement: startBlock, + SwitchStatement: startBlock, + VariableDeclaration: checkVariableDeclaration, + "ForStatement:exit": endBlock, + "ForOfStatement:exit": endBlock, + "ForInStatement:exit": endBlock, + "SwitchStatement:exit": endBlock, + "BlockStatement:exit": endBlock, + + "Program:exit": endFunction, + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "StaticBlock:exit": endFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/operator-assignment.js b/node_modules/eslint/lib/rules/operator-assignment.js new file mode 100644 index 00000000..50ae9996 --- /dev/null +++ b/node_modules/eslint/lib/rules/operator-assignment.js @@ -0,0 +1,270 @@ +/** + * @fileoverview Rule to replace assignment expressions with operator assignment + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether an operator is commutative and has an operator assignment + * shorthand form. + * @param {string} operator Operator to check. + * @returns {boolean} True if the operator is commutative and has a + * shorthand form. + */ +function isCommutativeOperatorWithShorthand(operator) { + return ["*", "&", "^", "|"].includes(operator); +} + +/** + * Checks whether an operator is not commutative and has an operator assignment + * shorthand form. + * @param {string} operator Operator to check. + * @returns {boolean} True if the operator is not commutative and has + * a shorthand form. + */ +function isNonCommutativeOperatorWithShorthand(operator) { + return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].includes(operator); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and) + * toString calls regardless of whether assignment shorthand is used) + * @param {ASTNode} node The node on the left side of the expression + * @returns {boolean} `true` if the node can be fixed + */ +function canBeFixed(node) { + return ( + node.type === "Identifier" || + (node.type === "MemberExpression" && + (node.object.type === "Identifier" || + node.object.type === "ThisExpression") && + (!node.computed || node.property.type === "Literal")) + ); +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["always"], + + docs: { + description: + "Require or disallow assignment operator shorthand where possible", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/operator-assignment", + }, + + schema: [ + { + enum: ["always", "never"], + }, + ], + + fixable: "code", + messages: { + replaced: + "Assignment (=) can be replaced with operator assignment ({{operator}}).", + unexpected: + "Unexpected operator assignment ({{operator}}) shorthand.", + }, + }, + + create(context) { + const never = context.options[0] === "never"; + const sourceCode = context.sourceCode; + + /** + * Returns the operator token of an AssignmentExpression or BinaryExpression + * @param {ASTNode} node An AssignmentExpression or BinaryExpression node + * @returns {Token} The operator token in the node + */ + function getOperatorToken(node) { + return sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + } + + /** + * Ensures that an assignment uses the shorthand form where possible. + * @param {ASTNode} node An AssignmentExpression node. + * @returns {void} + */ + function verify(node) { + if ( + node.operator !== "=" || + node.right.type !== "BinaryExpression" + ) { + return; + } + + const left = node.left; + const expr = node.right; + const operator = expr.operator; + + if ( + isCommutativeOperatorWithShorthand(operator) || + isNonCommutativeOperatorWithShorthand(operator) + ) { + const replacementOperator = `${operator}=`; + + if (astUtils.isSameReference(left, expr.left, true)) { + context.report({ + node, + messageId: "replaced", + data: { operator: replacementOperator }, + fix(fixer) { + if (canBeFixed(left) && canBeFixed(expr.left)) { + const equalsToken = getOperatorToken(node); + const operatorToken = getOperatorToken(expr); + const leftText = sourceCode + .getText() + .slice(node.range[0], equalsToken.range[0]); + const rightText = sourceCode + .getText() + .slice( + operatorToken.range[1], + node.right.range[1], + ); + + // Check for comments that would be removed. + if ( + sourceCode.commentsExistBetween( + equalsToken, + operatorToken, + ) + ) { + return null; + } + + return fixer.replaceText( + node, + `${leftText}${replacementOperator}${rightText}`, + ); + } + return null; + }, + }); + } else if ( + astUtils.isSameReference(left, expr.right, true) && + isCommutativeOperatorWithShorthand(operator) + ) { + /* + * This case can't be fixed safely. + * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would + * change the execution order of the valueOf() functions. + */ + context.report({ + node, + messageId: "replaced", + data: { operator: replacementOperator }, + }); + } + } + } + + /** + * Warns if an assignment expression uses operator assignment shorthand. + * @param {ASTNode} node An AssignmentExpression node. + * @returns {void} + */ + function prohibit(node) { + if ( + node.operator !== "=" && + !astUtils.isLogicalAssignmentOperator(node.operator) + ) { + context.report({ + node, + messageId: "unexpected", + data: { operator: node.operator }, + fix(fixer) { + if (canBeFixed(node.left)) { + const firstToken = sourceCode.getFirstToken(node); + const operatorToken = getOperatorToken(node); + const leftText = sourceCode + .getText() + .slice(node.range[0], operatorToken.range[0]); + const newOperator = node.operator.slice(0, -1); + let rightText; + + // Check for comments that would be duplicated. + if ( + sourceCode.commentsExistBetween( + firstToken, + operatorToken, + ) + ) { + return null; + } + + // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side. + if ( + astUtils.getPrecedence(node.right) <= + astUtils.getPrecedence({ + type: "BinaryExpression", + operator: newOperator, + }) && + !astUtils.isParenthesised( + sourceCode, + node.right, + ) + ) { + rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`; + } else { + const tokenAfterOperator = + sourceCode.getTokenAfter(operatorToken, { + includeComments: true, + }); + let rightTextPrefix = ""; + + if ( + operatorToken.range[1] === + tokenAfterOperator.range[0] && + !astUtils.canTokensBeAdjacent( + { + type: "Punctuator", + value: newOperator, + }, + tokenAfterOperator, + ) + ) { + rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar + } + + rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`; + } + + return fixer.replaceText( + node, + `${leftText}= ${leftText}${newOperator}${rightText}`, + ); + } + return null; + }, + }); + } + } + + return { + AssignmentExpression: !never ? verify : prohibit, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/operator-linebreak.js b/node_modules/eslint/lib/rules/operator-linebreak.js new file mode 100644 index 00000000..63076181 --- /dev/null +++ b/node_modules/eslint/lib/rules/operator-linebreak.js @@ -0,0 +1,315 @@ +/** + * @fileoverview Operator linebreak - enforces operator linebreak style of two types: after and before + * @author Benoît Zugmeyer + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "operator-linebreak", + url: "https://eslint.style/rules/js/operator-linebreak", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent linebreak style for operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/operator-linebreak", + }, + + schema: [ + { + enum: ["after", "before", "none", null], + }, + { + type: "object", + properties: { + overrides: { + type: "object", + additionalProperties: { + enum: ["after", "before", "none", "ignore"], + }, + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + operatorAtBeginning: + "'{{operator}}' should be placed at the beginning of the line.", + operatorAtEnd: + "'{{operator}}' should be placed at the end of the line.", + badLinebreak: "Bad line breaking before and after '{{operator}}'.", + noLinebreak: + "There should be no line break before or after '{{operator}}'.", + }, + }, + + create(context) { + const usedDefaultGlobal = !context.options[0]; + const globalStyle = context.options[0] || "after"; + const options = context.options[1] || {}; + const styleOverrides = options.overrides + ? Object.assign({}, options.overrides) + : {}; + + if (usedDefaultGlobal && !styleOverrides["?"]) { + styleOverrides["?"] = "before"; + } + + if (usedDefaultGlobal && !styleOverrides[":"]) { + styleOverrides[":"] = "before"; + } + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Gets a fixer function to fix rule issues + * @param {Token} operatorToken The operator token of an expression + * @param {string} desiredStyle The style for the rule. One of 'before', 'after', 'none' + * @returns {Function} A fixer function + */ + function getFixer(operatorToken, desiredStyle) { + return fixer => { + const tokenBefore = sourceCode.getTokenBefore(operatorToken); + const tokenAfter = sourceCode.getTokenAfter(operatorToken); + const textBefore = sourceCode.text.slice( + tokenBefore.range[1], + operatorToken.range[0], + ); + const textAfter = sourceCode.text.slice( + operatorToken.range[1], + tokenAfter.range[0], + ); + const hasLinebreakBefore = !astUtils.isTokenOnSameLine( + tokenBefore, + operatorToken, + ); + const hasLinebreakAfter = !astUtils.isTokenOnSameLine( + operatorToken, + tokenAfter, + ); + let newTextBefore, newTextAfter; + + if ( + hasLinebreakBefore !== hasLinebreakAfter && + desiredStyle !== "none" + ) { + // If there is a comment before and after the operator, don't do a fix. + if ( + sourceCode.getTokenBefore(operatorToken, { + includeComments: true, + }) !== tokenBefore && + sourceCode.getTokenAfter(operatorToken, { + includeComments: true, + }) !== tokenAfter + ) { + return null; + } + + /* + * If there is only one linebreak and it's on the wrong side of the operator, swap the text before and after the operator. + * foo && + * bar + * would get fixed to + * foo + * && bar + */ + newTextBefore = textAfter; + newTextAfter = textBefore; + } else { + const LINEBREAK_REGEX = + astUtils.createGlobalLinebreakMatcher(); + + // Otherwise, if no linebreak is desired and no comments interfere, replace the linebreaks with empty strings. + newTextBefore = + desiredStyle === "before" || textBefore.trim() + ? textBefore + : textBefore.replace(LINEBREAK_REGEX, ""); + newTextAfter = + desiredStyle === "after" || textAfter.trim() + ? textAfter + : textAfter.replace(LINEBREAK_REGEX, ""); + + // If there was no change (due to interfering comments), don't output a fix. + if ( + newTextBefore === textBefore && + newTextAfter === textAfter + ) { + return null; + } + } + + if ( + newTextAfter === "" && + tokenAfter.type === "Punctuator" && + "+-".includes(operatorToken.value) && + tokenAfter.value === operatorToken.value + ) { + // To avoid accidentally creating a ++ or -- operator, insert a space if the operator is a +/- and the following token is a unary +/-. + newTextAfter += " "; + } + + return fixer.replaceTextRange( + [tokenBefore.range[1], tokenAfter.range[0]], + newTextBefore + operatorToken.value + newTextAfter, + ); + }; + } + + /** + * Checks the operator placement + * @param {ASTNode} node The node to check + * @param {ASTNode} rightSide The node that comes after the operator in `node` + * @param {string} operator The operator + * @private + * @returns {void} + */ + function validateNode(node, rightSide, operator) { + /* + * Find the operator token by searching from the right side, because between the left side and the operator + * there could be additional tokens from type annotations. Search specifically for the token which + * value equals the operator, in order to skip possible opening parentheses before the right side node. + */ + const operatorToken = sourceCode.getTokenBefore( + rightSide, + token => token.value === operator, + ); + const leftToken = sourceCode.getTokenBefore(operatorToken); + const rightToken = sourceCode.getTokenAfter(operatorToken); + const operatorStyleOverride = styleOverrides[operator]; + const style = operatorStyleOverride || globalStyle; + const fix = getFixer(operatorToken, style); + + // if single line + if ( + astUtils.isTokenOnSameLine(leftToken, operatorToken) && + astUtils.isTokenOnSameLine(operatorToken, rightToken) + ) { + // do nothing. + } else if ( + operatorStyleOverride !== "ignore" && + !astUtils.isTokenOnSameLine(leftToken, operatorToken) && + !astUtils.isTokenOnSameLine(operatorToken, rightToken) + ) { + // lone operator + context.report({ + node, + loc: operatorToken.loc, + messageId: "badLinebreak", + data: { + operator, + }, + fix, + }); + } else if ( + style === "before" && + astUtils.isTokenOnSameLine(leftToken, operatorToken) + ) { + context.report({ + node, + loc: operatorToken.loc, + messageId: "operatorAtBeginning", + data: { + operator, + }, + fix, + }); + } else if ( + style === "after" && + astUtils.isTokenOnSameLine(operatorToken, rightToken) + ) { + context.report({ + node, + loc: operatorToken.loc, + messageId: "operatorAtEnd", + data: { + operator, + }, + fix, + }); + } else if (style === "none") { + context.report({ + node, + loc: operatorToken.loc, + messageId: "noLinebreak", + data: { + operator, + }, + fix, + }); + } + } + + /** + * Validates a binary expression using `validateNode` + * @param {BinaryExpression|LogicalExpression|AssignmentExpression} node node to be validated + * @returns {void} + */ + function validateBinaryExpression(node) { + validateNode(node, node.right, node.operator); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + BinaryExpression: validateBinaryExpression, + LogicalExpression: validateBinaryExpression, + AssignmentExpression: validateBinaryExpression, + VariableDeclarator(node) { + if (node.init) { + validateNode(node, node.init, "="); + } + }, + PropertyDefinition(node) { + if (node.value) { + validateNode(node, node.value, "="); + } + }, + ConditionalExpression(node) { + validateNode(node, node.consequent, "?"); + validateNode(node, node.alternate, ":"); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/padded-blocks.js b/node_modules/eslint/lib/rules/padded-blocks.js new file mode 100644 index 00000000..1160cb01 --- /dev/null +++ b/node_modules/eslint/lib/rules/padded-blocks.js @@ -0,0 +1,366 @@ +/** + * @fileoverview A rule to ensure blank lines within blocks. + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "padded-blocks", + url: "https://eslint.style/rules/js/padded-blocks", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow padding within blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/padded-blocks", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + blocks: { + enum: ["always", "never"], + }, + switches: { + enum: ["always", "never"], + }, + classes: { + enum: ["always", "never"], + }, + }, + additionalProperties: false, + minProperties: 1, + }, + ], + }, + { + type: "object", + properties: { + allowSingleLineBlocks: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + alwaysPadBlock: "Block must be padded by blank lines.", + neverPadBlock: "Block must not be padded by blank lines.", + }, + }, + + create(context) { + const options = {}; + const typeOptions = context.options[0] || "always"; + const exceptOptions = context.options[1] || {}; + + if (typeof typeOptions === "string") { + const shouldHavePadding = typeOptions === "always"; + + options.blocks = shouldHavePadding; + options.switches = shouldHavePadding; + options.classes = shouldHavePadding; + } else { + if (Object.hasOwn(typeOptions, "blocks")) { + options.blocks = typeOptions.blocks === "always"; + } + if (Object.hasOwn(typeOptions, "switches")) { + options.switches = typeOptions.switches === "always"; + } + if (Object.hasOwn(typeOptions, "classes")) { + options.classes = typeOptions.classes === "always"; + } + } + + if (Object.hasOwn(exceptOptions, "allowSingleLineBlocks")) { + options.allowSingleLineBlocks = + exceptOptions.allowSingleLineBlocks === true; + } + + const sourceCode = context.sourceCode; + + /** + * Gets the open brace token from a given node. + * @param {ASTNode} node A BlockStatement or SwitchStatement node from which to get the open brace. + * @returns {Token} The token of the open brace. + */ + function getOpenBrace(node) { + if (node.type === "SwitchStatement") { + return sourceCode.getTokenBefore(node.cases[0]); + } + + if (node.type === "StaticBlock") { + return sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token + } + + // `BlockStatement` or `ClassBody` + return sourceCode.getFirstToken(node); + } + + /** + * Checks if the given parameter is a comment node + * @param {ASTNode|Token} node An AST node or token + * @returns {boolean} True if node is a comment + */ + function isComment(node) { + return node.type === "Line" || node.type === "Block"; + } + + /** + * Checks if there is padding between two tokens + * @param {Token} first The first token + * @param {Token} second The second token + * @returns {boolean} True if there is at least a line between the tokens + */ + function isPaddingBetweenTokens(first, second) { + return second.loc.start.line - first.loc.end.line >= 2; + } + + /** + * Checks if the given token has a blank line after it. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is followed by a blank line. + */ + function getFirstBlockToken(token) { + let prev, + first = token; + + do { + prev = first; + first = sourceCode.getTokenAfter(first, { + includeComments: true, + }); + } while ( + isComment(first) && + first.loc.start.line === prev.loc.end.line + ); + + return first; + } + + /** + * Checks if the given token is preceded by a blank line. + * @param {Token} token The token to check + * @returns {boolean} Whether or not the token is preceded by a blank line + */ + function getLastBlockToken(token) { + let last = token, + next; + + do { + next = last; + last = sourceCode.getTokenBefore(last, { + includeComments: true, + }); + } while ( + isComment(last) && + last.loc.end.line === next.loc.start.line + ); + + return last; + } + + /** + * Checks if a node should be padded, according to the rule config. + * @param {ASTNode} node The AST node to check. + * @throws {Error} (Unreachable) + * @returns {boolean} True if the node should be padded, false otherwise. + */ + function requirePaddingFor(node) { + switch (node.type) { + case "BlockStatement": + case "StaticBlock": + return options.blocks; + case "SwitchStatement": + return options.switches; + case "ClassBody": + return options.classes; + + /* c8 ignore next */ + default: + throw new Error("unreachable"); + } + } + + /** + * Checks the given BlockStatement node to be padded if the block is not empty. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPadding(node) { + const openBrace = getOpenBrace(node), + firstBlockToken = getFirstBlockToken(openBrace), + tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { + includeComments: true, + }), + closeBrace = sourceCode.getLastToken(node), + lastBlockToken = getLastBlockToken(closeBrace), + tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { + includeComments: true, + }), + blockHasTopPadding = isPaddingBetweenTokens( + tokenBeforeFirst, + firstBlockToken, + ), + blockHasBottomPadding = isPaddingBetweenTokens( + lastBlockToken, + tokenAfterLast, + ); + + if ( + options.allowSingleLineBlocks && + astUtils.isTokenOnSameLine(tokenBeforeFirst, tokenAfterLast) + ) { + return; + } + + if (requirePaddingFor(node)) { + if (!blockHasTopPadding) { + context.report({ + node, + loc: { + start: tokenBeforeFirst.loc.start, + end: firstBlockToken.loc.start, + }, + fix(fixer) { + return fixer.insertTextAfter( + tokenBeforeFirst, + "\n", + ); + }, + messageId: "alwaysPadBlock", + }); + } + if (!blockHasBottomPadding) { + context.report({ + node, + loc: { + end: tokenAfterLast.loc.start, + start: lastBlockToken.loc.end, + }, + fix(fixer) { + return fixer.insertTextBefore(tokenAfterLast, "\n"); + }, + messageId: "alwaysPadBlock", + }); + } + } else { + if (blockHasTopPadding) { + context.report({ + node, + loc: { + start: tokenBeforeFirst.loc.start, + end: firstBlockToken.loc.start, + }, + fix(fixer) { + return fixer.replaceTextRange( + [ + tokenBeforeFirst.range[1], + firstBlockToken.range[0] - + firstBlockToken.loc.start.column, + ], + "\n", + ); + }, + messageId: "neverPadBlock", + }); + } + + if (blockHasBottomPadding) { + context.report({ + node, + loc: { + end: tokenAfterLast.loc.start, + start: lastBlockToken.loc.end, + }, + messageId: "neverPadBlock", + fix(fixer) { + return fixer.replaceTextRange( + [ + lastBlockToken.range[1], + tokenAfterLast.range[0] - + tokenAfterLast.loc.start.column, + ], + "\n", + ); + }, + }); + } + } + } + + const rule = {}; + + if (Object.hasOwn(options, "switches")) { + rule.SwitchStatement = function (node) { + if (node.cases.length === 0) { + return; + } + checkPadding(node); + }; + } + + if (Object.hasOwn(options, "blocks")) { + rule.BlockStatement = function (node) { + if (node.body.length === 0) { + return; + } + checkPadding(node); + }; + rule.StaticBlock = rule.BlockStatement; + } + + if (Object.hasOwn(options, "classes")) { + rule.ClassBody = function (node) { + if (node.body.length === 0) { + return; + } + checkPadding(node); + }; + } + + return rule; + }, +}; diff --git a/node_modules/eslint/lib/rules/padding-line-between-statements.js b/node_modules/eslint/lib/rules/padding-line-between-statements.js new file mode 100644 index 00000000..7d7720f4 --- /dev/null +++ b/node_modules/eslint/lib/rules/padding-line-between-statements.js @@ -0,0 +1,612 @@ +/** + * @fileoverview Rule to require or disallow newlines between statements + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const LT = `[${Array.from(astUtils.LINEBREAKS).join("")}]`; +const PADDING_LINE_SEQUENCE = new RegExp( + String.raw`^(\s*?${LT})\s*${LT}(\s*;?)$`, + "u", +); +const CJS_EXPORT = /^(?:module\s*\.\s*)?exports(?:\s*\.|\s*\[|$)/u; +const CJS_IMPORT = /^require\(/u; + +/** + * Creates tester which check if a node starts with specific keyword. + * @param {string} keyword The keyword to test. + * @returns {Object} the created tester. + * @private + */ +function newKeywordTester(keyword) { + return { + test: (node, sourceCode) => + sourceCode.getFirstToken(node).value === keyword, + }; +} + +/** + * Creates tester which check if a node starts with specific keyword and spans a single line. + * @param {string} keyword The keyword to test. + * @returns {Object} the created tester. + * @private + */ +function newSinglelineKeywordTester(keyword) { + return { + test: (node, sourceCode) => + node.loc.start.line === node.loc.end.line && + sourceCode.getFirstToken(node).value === keyword, + }; +} + +/** + * Creates tester which check if a node starts with specific keyword and spans multiple lines. + * @param {string} keyword The keyword to test. + * @returns {Object} the created tester. + * @private + */ +function newMultilineKeywordTester(keyword) { + return { + test: (node, sourceCode) => + node.loc.start.line !== node.loc.end.line && + sourceCode.getFirstToken(node).value === keyword, + }; +} + +/** + * Creates tester which check if a node is specific type. + * @param {string} type The node type to test. + * @returns {Object} the created tester. + * @private + */ +function newNodeTypeTester(type) { + return { + test: node => node.type === type, + }; +} + +/** + * Checks the given node is an expression statement of IIFE. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is an expression statement of IIFE. + * @private + */ +function isIIFEStatement(node) { + if (node.type === "ExpressionStatement") { + let call = astUtils.skipChainExpression(node.expression); + + if (call.type === "UnaryExpression") { + call = astUtils.skipChainExpression(call.argument); + } + return ( + call.type === "CallExpression" && astUtils.isFunction(call.callee) + ); + } + return false; +} + +/** + * Checks whether the given node is a block-like statement. + * This checks the last token of the node is the closing brace of a block. + * @param {SourceCode} sourceCode The source code to get tokens. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a block-like statement. + * @private + */ +function isBlockLikeStatement(sourceCode, node) { + // do-while with a block is a block-like statement. + if ( + node.type === "DoWhileStatement" && + node.body.type === "BlockStatement" + ) { + return true; + } + + /* + * IIFE is a block-like statement specially from + * JSCS#disallowPaddingNewLinesAfterBlocks. + */ + if (isIIFEStatement(node)) { + return true; + } + + // Checks the last token is a closing brace of blocks. + const lastToken = sourceCode.getLastToken( + node, + astUtils.isNotSemicolonToken, + ); + const belongingNode = + lastToken && astUtils.isClosingBraceToken(lastToken) + ? sourceCode.getNodeByRangeIndex(lastToken.range[0]) + : null; + + return ( + Boolean(belongingNode) && + (belongingNode.type === "BlockStatement" || + belongingNode.type === "SwitchStatement") + ); +} + +/** + * Gets the actual last token. + * + * If a semicolon is semicolon-less style's semicolon, this ignores it. + * For example: + * + * foo() + * ;[1, 2, 3].forEach(bar) + * @param {SourceCode} sourceCode The source code to get tokens. + * @param {ASTNode} node The node to get. + * @returns {Token} The actual last token. + * @private + */ +function getActualLastToken(sourceCode, node) { + const semiToken = sourceCode.getLastToken(node); + const prevToken = sourceCode.getTokenBefore(semiToken); + const nextToken = sourceCode.getTokenAfter(semiToken); + const isSemicolonLessStyle = Boolean( + prevToken && + nextToken && + prevToken.range[0] >= node.range[0] && + astUtils.isSemicolonToken(semiToken) && + semiToken.loc.start.line !== prevToken.loc.end.line && + semiToken.loc.end.line === nextToken.loc.start.line, + ); + + return isSemicolonLessStyle ? prevToken : semiToken; +} + +/** + * This returns the concatenation of the first 2 captured strings. + * @param {string} _ Unused. Whole matched string. + * @param {string} trailingSpaces The trailing spaces of the first line. + * @param {string} indentSpaces The indentation spaces of the last line. + * @returns {string} The concatenation of trailingSpaces and indentSpaces. + * @private + */ +function replacerToRemovePaddingLines(_, trailingSpaces, indentSpaces) { + return trailingSpaces + indentSpaces; +} + +/** + * Check and report statements for `any` configuration. + * It does nothing. + * @returns {void} + * @private + */ +function verifyForAny() {} + +/** + * Check and report statements for `never` configuration. + * This autofix removes blank lines between the given 2 statements. + * However, if comments exist between 2 blank lines, it does not remove those + * blank lines automatically. + * @param {RuleContext} context The rule context to report. + * @param {ASTNode} _ Unused. The previous node to check. + * @param {ASTNode} nextNode The next node to check. + * @param {Array} paddingLines The array of token pairs that blank + * lines exist between the pair. + * @returns {void} + * @private + */ +function verifyForNever(context, _, nextNode, paddingLines) { + if (paddingLines.length === 0) { + return; + } + + context.report({ + node: nextNode, + messageId: "unexpectedBlankLine", + fix(fixer) { + if (paddingLines.length >= 2) { + return null; + } + + const prevToken = paddingLines[0][0]; + const nextToken = paddingLines[0][1]; + const start = prevToken.range[1]; + const end = nextToken.range[0]; + const text = context.sourceCode.text + .slice(start, end) + .replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines); + + return fixer.replaceTextRange([start, end], text); + }, + }); +} + +/** + * Check and report statements for `always` configuration. + * This autofix inserts a blank line between the given 2 statements. + * If the `prevNode` has trailing comments, it inserts a blank line after the + * trailing comments. + * @param {RuleContext} context The rule context to report. + * @param {ASTNode} prevNode The previous node to check. + * @param {ASTNode} nextNode The next node to check. + * @param {Array} paddingLines The array of token pairs that blank + * lines exist between the pair. + * @returns {void} + * @private + */ +function verifyForAlways(context, prevNode, nextNode, paddingLines) { + if (paddingLines.length > 0) { + return; + } + + context.report({ + node: nextNode, + messageId: "expectedBlankLine", + fix(fixer) { + const sourceCode = context.sourceCode; + let prevToken = getActualLastToken(sourceCode, prevNode); + const nextToken = + sourceCode.getFirstTokenBetween(prevToken, nextNode, { + includeComments: true, + + /** + * Skip the trailing comments of the previous node. + * This inserts a blank line after the last trailing comment. + * + * For example: + * + * foo(); // trailing comment. + * // comment. + * bar(); + * + * Get fixed to: + * + * foo(); // trailing comment. + * + * // comment. + * bar(); + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is not a trailing comment. + * @private + */ + filter(token) { + if (astUtils.isTokenOnSameLine(prevToken, token)) { + prevToken = token; + return false; + } + return true; + }, + }) || nextNode; + const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken) + ? "\n\n" + : "\n"; + + return fixer.insertTextAfter(prevToken, insertText); + }, + }); +} + +/** + * Types of blank lines. + * `any`, `never`, and `always` are defined. + * Those have `verify` method to check and report statements. + * @private + */ +const PaddingTypes = { + any: { verify: verifyForAny }, + never: { verify: verifyForNever }, + always: { verify: verifyForAlways }, +}; + +/** + * Types of statements. + * Those have `test` method to check it matches to the given statement. + * @private + */ +const StatementTypes = { + "*": { test: () => true }, + "block-like": { + test: (node, sourceCode) => isBlockLikeStatement(sourceCode, node), + }, + "cjs-export": { + test: (node, sourceCode) => + node.type === "ExpressionStatement" && + node.expression.type === "AssignmentExpression" && + CJS_EXPORT.test(sourceCode.getText(node.expression.left)), + }, + "cjs-import": { + test: (node, sourceCode) => + node.type === "VariableDeclaration" && + node.declarations.length > 0 && + Boolean(node.declarations[0].init) && + CJS_IMPORT.test(sourceCode.getText(node.declarations[0].init)), + }, + directive: { + test: astUtils.isDirective, + }, + expression: { + test: node => + node.type === "ExpressionStatement" && !astUtils.isDirective(node), + }, + iife: { + test: isIIFEStatement, + }, + "multiline-block-like": { + test: (node, sourceCode) => + node.loc.start.line !== node.loc.end.line && + isBlockLikeStatement(sourceCode, node), + }, + "multiline-expression": { + test: node => + node.loc.start.line !== node.loc.end.line && + node.type === "ExpressionStatement" && + !astUtils.isDirective(node), + }, + + "multiline-const": newMultilineKeywordTester("const"), + "multiline-let": newMultilineKeywordTester("let"), + "multiline-var": newMultilineKeywordTester("var"), + "singleline-const": newSinglelineKeywordTester("const"), + "singleline-let": newSinglelineKeywordTester("let"), + "singleline-var": newSinglelineKeywordTester("var"), + + block: newNodeTypeTester("BlockStatement"), + empty: newNodeTypeTester("EmptyStatement"), + function: newNodeTypeTester("FunctionDeclaration"), + + break: newKeywordTester("break"), + case: newKeywordTester("case"), + class: newKeywordTester("class"), + const: newKeywordTester("const"), + continue: newKeywordTester("continue"), + debugger: newKeywordTester("debugger"), + default: newKeywordTester("default"), + do: newKeywordTester("do"), + export: newKeywordTester("export"), + for: newKeywordTester("for"), + if: newKeywordTester("if"), + import: newKeywordTester("import"), + let: newKeywordTester("let"), + return: newKeywordTester("return"), + switch: newKeywordTester("switch"), + throw: newKeywordTester("throw"), + try: newKeywordTester("try"), + var: newKeywordTester("var"), + while: newKeywordTester("while"), + with: newKeywordTester("with"), +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "padding-line-between-statements", + url: "https://eslint.style/rules/js/padding-line-between-statements", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow padding lines between statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/padding-line-between-statements", + }, + + fixable: "whitespace", + + schema: { + definitions: { + paddingType: { + enum: Object.keys(PaddingTypes), + }, + statementType: { + anyOf: [ + { enum: Object.keys(StatementTypes) }, + { + type: "array", + items: { enum: Object.keys(StatementTypes) }, + minItems: 1, + uniqueItems: true, + }, + ], + }, + }, + type: "array", + items: { + type: "object", + properties: { + blankLine: { $ref: "#/definitions/paddingType" }, + prev: { $ref: "#/definitions/statementType" }, + next: { $ref: "#/definitions/statementType" }, + }, + additionalProperties: false, + required: ["blankLine", "prev", "next"], + }, + }, + + messages: { + unexpectedBlankLine: "Unexpected blank line before this statement.", + expectedBlankLine: "Expected blank line before this statement.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const configureList = context.options || []; + let scopeInfo = null; + + /** + * Processes to enter to new scope. + * This manages the current previous statement. + * @returns {void} + * @private + */ + function enterScope() { + scopeInfo = { + upper: scopeInfo, + prevNode: null, + }; + } + + /** + * Processes to exit from the current scope. + * @returns {void} + * @private + */ + function exitScope() { + scopeInfo = scopeInfo.upper; + } + + /** + * Checks whether the given node matches the given type. + * @param {ASTNode} node The statement node to check. + * @param {string|string[]} type The statement type to check. + * @returns {boolean} `true` if the statement node matched the type. + * @private + */ + function match(node, type) { + let innerStatementNode = node; + + while (innerStatementNode.type === "LabeledStatement") { + innerStatementNode = innerStatementNode.body; + } + if (Array.isArray(type)) { + return type.some(match.bind(null, innerStatementNode)); + } + return StatementTypes[type].test(innerStatementNode, sourceCode); + } + + /** + * Finds the last matched configure from configureList. + * @param {ASTNode} prevNode The previous statement to match. + * @param {ASTNode} nextNode The current statement to match. + * @returns {Object} The tester of the last matched configure. + * @private + */ + function getPaddingType(prevNode, nextNode) { + for (let i = configureList.length - 1; i >= 0; --i) { + const configure = configureList[i]; + const matched = + match(prevNode, configure.prev) && + match(nextNode, configure.next); + + if (matched) { + return PaddingTypes[configure.blankLine]; + } + } + return PaddingTypes.any; + } + + /** + * Gets padding line sequences between the given 2 statements. + * Comments are separators of the padding line sequences. + * @param {ASTNode} prevNode The previous statement to count. + * @param {ASTNode} nextNode The current statement to count. + * @returns {Array} The array of token pairs. + * @private + */ + function getPaddingLineSequences(prevNode, nextNode) { + const pairs = []; + let prevToken = getActualLastToken(sourceCode, prevNode); + + if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) { + do { + const token = sourceCode.getTokenAfter(prevToken, { + includeComments: true, + }); + + if (token.loc.start.line - prevToken.loc.end.line >= 2) { + pairs.push([prevToken, token]); + } + prevToken = token; + } while (prevToken.range[0] < nextNode.range[0]); + } + + return pairs; + } + + /** + * Verify padding lines between the given node and the previous node. + * @param {ASTNode} node The node to verify. + * @returns {void} + * @private + */ + function verify(node) { + const parentType = node.parent.type; + const validParent = + astUtils.STATEMENT_LIST_PARENTS.has(parentType) || + parentType === "SwitchStatement"; + + if (!validParent) { + return; + } + + // Save this node as the current previous statement. + const prevNode = scopeInfo.prevNode; + + // Verify. + if (prevNode) { + const type = getPaddingType(prevNode, node); + const paddingLines = getPaddingLineSequences(prevNode, node); + + type.verify(context, prevNode, node, paddingLines); + } + + scopeInfo.prevNode = node; + } + + /** + * Verify padding lines between the given node and the previous node. + * Then process to enter to new scope. + * @param {ASTNode} node The node to verify. + * @returns {void} + * @private + */ + function verifyThenEnterScope(node) { + verify(node); + enterScope(); + } + + return { + Program: enterScope, + BlockStatement: enterScope, + SwitchStatement: enterScope, + StaticBlock: enterScope, + "Program:exit": exitScope, + "BlockStatement:exit": exitScope, + "SwitchStatement:exit": exitScope, + "StaticBlock:exit": exitScope, + + ":statement": verify, + + SwitchCase: verifyThenEnterScope, + "SwitchCase:exit": exitScope, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-arrow-callback.js b/node_modules/eslint/lib/rules/prefer-arrow-callback.js new file mode 100644 index 00000000..0f05b52a --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-arrow-callback.js @@ -0,0 +1,437 @@ +/** + * @fileoverview A rule to suggest using arrow functions as callbacks. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given variable is a function name. + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is a function name. + */ +function isFunctionName(variable) { + return variable && variable.defs[0].type === "FunctionName"; +} + +/** + * Checks whether or not a given MetaProperty node equals to a given value. + * @param {ASTNode} node A MetaProperty node to check. + * @param {string} metaName The name of `MetaProperty.meta`. + * @param {string} propertyName The name of `MetaProperty.property`. + * @returns {boolean} `true` if the node is the specific value. + */ +function checkMetaProperty(node, metaName, propertyName) { + return node.meta.name === metaName && node.property.name === propertyName; +} + +/** + * Gets the variable object of `arguments` which is defined implicitly. + * @param {eslint-scope.Scope} scope A scope to get. + * @returns {eslint-scope.Variable} The found variable object. + */ +function getVariableOfArguments(scope) { + const variables = scope.variables; + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + + if (variable.name === "arguments") { + /* + * If there was a parameter which is named "arguments", the + * implicit "arguments" is not defined. + * So does fast return with null. + */ + return variable.identifiers.length === 0 ? variable : null; + } + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks whether or not a given node is a callback. + * @param {ASTNode} node A node to check. + * @throws {Error} (Unreachable.) + * @returns {Object} + * {boolean} retv.isCallback - `true` if the node is a callback. + * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`. + */ +function getCallbackInfo(node) { + const retv = { isCallback: false, isLexicalThis: false }; + let currentNode = node; + let parent = node.parent; + let bound = false; + + while (currentNode) { + switch (parent.type) { + // Checks parents recursively. + + case "LogicalExpression": + case "ChainExpression": + case "ConditionalExpression": + break; + + // Checks whether the parent node is `.bind(this)` call. + case "MemberExpression": + if ( + parent.object === currentNode && + !parent.property.computed && + parent.property.type === "Identifier" && + parent.property.name === "bind" + ) { + const maybeCallee = + parent.parent.type === "ChainExpression" + ? parent.parent + : parent; + + if (astUtils.isCallee(maybeCallee)) { + if (!bound) { + bound = true; // Use only the first `.bind()` to make `isLexicalThis` value. + retv.isLexicalThis = + maybeCallee.parent.arguments.length === 1 && + maybeCallee.parent.arguments[0].type === + "ThisExpression"; + } + parent = maybeCallee.parent; + } else { + return retv; + } + } else { + return retv; + } + break; + + // Checks whether the node is a callback. + case "CallExpression": + case "NewExpression": + if (parent.callee !== currentNode) { + retv.isCallback = true; + } + return retv; + + default: + return retv; + } + + currentNode = parent; + parent = parent.parent; + } + + /* c8 ignore next */ + throw new Error("unreachable"); +} + +/** + * Checks whether a simple list of parameters contains any duplicates. This does not handle complex + * parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate + * parameter names anyway. Instead, it always returns `false` for complex parameter lists. + * @param {ASTNode[]} paramsList The list of parameters for a function + * @returns {boolean} `true` if the list of parameters contains any duplicates + */ +function hasDuplicateParams(paramsList) { + return ( + paramsList.every(param => param.type === "Identifier") && + paramsList.length !== new Set(paramsList.map(param => param.name)).size + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["javascript", "typescript"], + language: "javascript", + + defaultOptions: [ + { allowNamedFunctions: false, allowUnboundThis: true }, + ], + + docs: { + description: "Require using arrow functions for callbacks", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-arrow-callback", + }, + + schema: [ + { + type: "object", + properties: { + allowNamedFunctions: { + type: "boolean", + }, + allowUnboundThis: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + preferArrowCallback: "Unexpected function expression.", + }, + }, + + create(context) { + const [{ allowNamedFunctions, allowUnboundThis }] = context.options; + const sourceCode = context.sourceCode; + + /* + * {Array<{this: boolean, super: boolean, meta: boolean}>} + * - this - A flag which shows there are one or more ThisExpression. + * - super - A flag which shows there are one or more Super. + * - meta - A flag which shows there are one or more MethProperty. + */ + let stack = []; + + /** + * Pushes new function scope with all `false` flags. + * @returns {void} + */ + function enterScope() { + stack.push({ this: false, super: false, meta: false }); + } + + /** + * Pops a function scope from the stack. + * @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope. + */ + function exitScope() { + return stack.pop(); + } + + return { + // Reset internal state. + Program() { + stack = []; + }, + + // If there are below, it cannot replace with arrow functions merely. + ThisExpression() { + const info = stack.at(-1); + + if (info) { + info.this = true; + } + }, + + Super() { + const info = stack.at(-1); + + if (info) { + info.super = true; + } + }, + + MetaProperty(node) { + const info = stack.at(-1); + + if (info && checkMetaProperty(node, "new", "target")) { + info.meta = true; + } + }, + + // To skip nested scopes. + FunctionDeclaration: enterScope, + "FunctionDeclaration:exit": exitScope, + + // Main. + FunctionExpression: enterScope, + "FunctionExpression:exit"(node) { + const scopeInfo = exitScope(); + + // Skip named function expressions + if (allowNamedFunctions && node.id && node.id.name) { + return; + } + + // Skip generators. + if (node.generator) { + return; + } + + // Skip recursive functions. + const nameVar = sourceCode.getDeclaredVariables(node)[0]; + + if (isFunctionName(nameVar) && nameVar.references.length > 0) { + return; + } + + // Skip if it's using arguments. + const variable = getVariableOfArguments( + sourceCode.getScope(node), + ); + + if (variable && variable.references.length > 0) { + return; + } + + // Reports if it's a callback which can replace with arrows. + const callbackInfo = getCallbackInfo(node); + + if ( + callbackInfo.isCallback && + (!allowUnboundThis || + !scopeInfo.this || + callbackInfo.isLexicalThis) && + !scopeInfo.super && + !scopeInfo.meta + ) { + context.report({ + node, + messageId: "preferArrowCallback", + *fix(fixer) { + if ( + (!callbackInfo.isLexicalThis && + scopeInfo.this) || + hasDuplicateParams(node.params) + ) { + /* + * If the callback function does not have .bind(this) and contains a reference to `this`, there + * is no way to determine what `this` should be, so don't perform any fixes. + * If the callback function has duplicates in its list of parameters (possible in sloppy mode), + * don't replace it with an arrow function, because this is a SyntaxError with arrow functions. + */ + return; + } + + if ( + node.params.length && + node.params[0].name === "this" + ) { + return; + } + + // Remove `.bind(this)` if exists. + if (callbackInfo.isLexicalThis) { + const memberNode = node.parent; + + /* + * If `.bind(this)` exists but the parent is not `.bind(this)`, don't remove it automatically. + * E.g. `(foo || function(){}).bind(this)` + */ + if (memberNode.type !== "MemberExpression") { + return; + } + + const callNode = memberNode.parent; + const firstTokenToRemove = + sourceCode.getTokenAfter( + memberNode.object, + astUtils.isNotClosingParenToken, + ); + const lastTokenToRemove = + sourceCode.getLastToken(callNode); + + /* + * If the member expression is parenthesized, don't remove the right paren. + * E.g. `(function(){}.bind)(this)` + * ^^^^^^^^^^^^ + */ + if ( + astUtils.isParenthesised( + sourceCode, + memberNode, + ) + ) { + return; + } + + // If comments exist in the `.bind(this)`, don't remove those. + if ( + sourceCode.commentsExistBetween( + firstTokenToRemove, + lastTokenToRemove, + ) + ) { + return; + } + + yield fixer.removeRange([ + firstTokenToRemove.range[0], + lastTokenToRemove.range[1], + ]); + } + + // Convert the function expression to an arrow function. + const functionToken = sourceCode.getFirstToken( + node, + node.async ? 1 : 0, + ); + const leftParenToken = sourceCode.getTokenAfter( + functionToken, + astUtils.isOpeningParenToken, + ); + const tokenBeforeBody = sourceCode.getTokenBefore( + node.body, + ); + + if ( + sourceCode.commentsExistBetween( + functionToken, + leftParenToken, + ) + ) { + // Remove only extra tokens to keep comments. + yield fixer.remove(functionToken); + if (node.id) { + yield fixer.remove(node.id); + } + } else { + // Remove extra tokens and spaces. + yield fixer.removeRange([ + functionToken.range[0], + leftParenToken.range[0], + ]); + } + yield fixer.insertTextAfter(tokenBeforeBody, " =>"); + + // Get the node that will become the new arrow function. + let replacedNode = callbackInfo.isLexicalThis + ? node.parent.parent + : node; + + if (replacedNode.type === "ChainExpression") { + replacedNode = replacedNode.parent; + } + + /* + * If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then + * the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even + * though `foo || function() {}` is valid. + */ + if ( + replacedNode.parent.type !== "CallExpression" && + replacedNode.parent.type !== + "ConditionalExpression" && + !astUtils.isParenthesised( + sourceCode, + replacedNode, + ) && + !astUtils.isParenthesised(sourceCode, node) + ) { + yield fixer.insertTextBefore(replacedNode, "("); + yield fixer.insertTextAfter(replacedNode, ")"); + } + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-const.js b/node_modules/eslint/lib/rules/prefer-const.js new file mode 100644 index 00000000..8d5ae29a --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-const.js @@ -0,0 +1,546 @@ +/** + * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const PATTERN_TYPE = + /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/u; +const DECLARATION_HOST_TYPE = + /^(?:Program|BlockStatement|StaticBlock|SwitchCase)$/u; +const DESTRUCTURING_HOST_TYPE = + /^(?:VariableDeclarator|AssignmentExpression)$/u; + +/** + * Checks whether a given node is located at `ForStatement.init` or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is located at `ForStatement.init`. + */ +function isInitOfForStatement(node) { + return node.parent.type === "ForStatement" && node.parent.init === node; +} + +/** + * Checks whether a given Identifier node becomes a VariableDeclaration or not. + * @param {ASTNode} identifier An Identifier node to check. + * @returns {boolean} `true` if the node can become a VariableDeclaration. + */ +function canBecomeVariableDeclaration(identifier) { + let node = identifier.parent; + + while (PATTERN_TYPE.test(node.type)) { + node = node.parent; + } + + return ( + node.type === "VariableDeclarator" || + (node.type === "AssignmentExpression" && + node.parent.type === "ExpressionStatement" && + DECLARATION_HOST_TYPE.test(node.parent.parent.type)) + ); +} + +/** + * Checks if an property or element is from outer scope or function parameters + * in destructing pattern. + * @param {string} name A variable name to be checked. + * @param {eslint-scope.Scope} initScope A scope to start find. + * @returns {boolean} Indicates if the variable is from outer scope or function parameters. + */ +function isOuterVariableInDestructing(name, initScope) { + if ( + initScope.through.some( + ref => ref.resolved && ref.resolved.name === name, + ) + ) { + return true; + } + + const variable = astUtils.getVariableByName(initScope, name); + + if (variable !== null) { + return variable.defs.some(def => def.type === "Parameter"); + } + + return false; +} + +/** + * Gets the VariableDeclarator/AssignmentExpression node that a given reference + * belongs to. + * This is used to detect a mix of reassigned and never reassigned in a + * destructuring. + * @param {eslint-scope.Reference} reference A reference to get. + * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or + * null. + */ +function getDestructuringHost(reference) { + if (!reference.isWrite()) { + return null; + } + let node = reference.identifier.parent; + + while (PATTERN_TYPE.test(node.type)) { + node = node.parent; + } + + if (!DESTRUCTURING_HOST_TYPE.test(node.type)) { + return null; + } + return node; +} + +/** + * Determines if a destructuring assignment node contains + * any MemberExpression nodes. This is used to determine if a + * variable that is only written once using destructuring can be + * safely converted into a const declaration. + * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check. + * @returns {boolean} True if the destructuring pattern contains + * a MemberExpression, false if not. + */ +function hasMemberExpressionAssignment(node) { + switch (node.type) { + case "ObjectPattern": + return node.properties.some(prop => { + if (prop) { + /* + * Spread elements have an argument property while + * others have a value property. Because different + * parsers use different node types for spread elements, + * we just check if there is an argument property. + */ + return hasMemberExpressionAssignment( + prop.argument || prop.value, + ); + } + + return false; + }); + + case "ArrayPattern": + return node.elements.some(element => { + if (element) { + return hasMemberExpressionAssignment(element); + } + + return false; + }); + + case "AssignmentPattern": + return hasMemberExpressionAssignment(node.left); + + case "MemberExpression": + return true; + + // no default + } + + return false; +} + +/** + * Gets an identifier node of a given variable. + * + * If the initialization exists or one or more reading references exist before + * the first assignment, the identifier node is the node of the declaration. + * Otherwise, the identifier node is the node of the first assignment. + * + * If the variable should not change to const, this function returns null. + * - If the variable is reassigned. + * - If the variable is never initialized nor assigned. + * - If the variable is initialized in a different scope from the declaration. + * - If the unique assignment of the variable cannot change to a declaration. + * e.g. `if (a) b = 1` / `return (b = 1)` + * - If the variable is declared in the global scope and `eslintUsed` is `true`. + * `/*exported foo` directive comment makes such variables. This rule does not + * warn such variables because this rule cannot distinguish whether the + * exported variables are reassigned or not. + * @param {eslint-scope.Variable} variable A variable to get. + * @param {boolean} ignoreReadBeforeAssign + * The value of `ignoreReadBeforeAssign` option. + * @returns {ASTNode|null} + * An Identifier node if the variable should change to const. + * Otherwise, null. + */ +function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { + if (variable.eslintUsed && variable.scope.type === "global") { + return null; + } + + // Finds the unique WriteReference. + let writer = null; + let isReadBeforeInit = false; + const references = variable.references; + + for (let i = 0; i < references.length; ++i) { + const reference = references[i]; + + if (reference.isWrite()) { + const isReassigned = + writer !== null && writer.identifier !== reference.identifier; + + if (isReassigned) { + return null; + } + + const destructuringHost = getDestructuringHost(reference); + + if ( + destructuringHost !== null && + destructuringHost.left !== void 0 + ) { + const leftNode = destructuringHost.left; + let hasOuterVariables = false, + hasNonIdentifiers = false; + + if (leftNode.type === "ObjectPattern") { + const properties = leftNode.properties; + + hasOuterVariables = properties + .filter(prop => prop.value) + .map(prop => prop.value.name) + .some(name => + isOuterVariableInDestructing(name, variable.scope), + ); + + hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); + } else if (leftNode.type === "ArrayPattern") { + const elements = leftNode.elements; + + hasOuterVariables = elements + .map(element => element && element.name) + .some(name => + isOuterVariableInDestructing(name, variable.scope), + ); + + hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); + } + + if (hasOuterVariables || hasNonIdentifiers) { + return null; + } + } + + writer = reference; + } else if (reference.isRead() && writer === null) { + if (ignoreReadBeforeAssign) { + return null; + } + isReadBeforeInit = true; + } + } + + /* + * If the assignment is from a different scope, ignore it. + * If the assignment cannot change to a declaration, ignore it. + */ + const shouldBeConst = + writer !== null && + writer.from === variable.scope && + canBecomeVariableDeclaration(writer.identifier); + + if (!shouldBeConst) { + return null; + } + + if (isReadBeforeInit) { + return variable.defs[0].name; + } + + return writer.identifier; +} + +/** + * Groups by the VariableDeclarator/AssignmentExpression node that each + * reference of given variables belongs to. + * This is used to detect a mix of reassigned and never reassigned in a + * destructuring. + * @param {eslint-scope.Variable[]} variables Variables to group by destructuring. + * @param {boolean} ignoreReadBeforeAssign + * The value of `ignoreReadBeforeAssign` option. + * @returns {Map} Grouped identifier nodes. + */ +function groupByDestructuring(variables, ignoreReadBeforeAssign) { + const identifierMap = new Map(); + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + const references = variable.references; + const identifier = getIdentifierIfShouldBeConst( + variable, + ignoreReadBeforeAssign, + ); + let prevId = null; + + for (let j = 0; j < references.length; ++j) { + const reference = references[j]; + const id = reference.identifier; + + /* + * Avoid counting a reference twice or more for default values of + * destructuring. + */ + if (id === prevId) { + continue; + } + prevId = id; + + // Add the identifier node into the destructuring group. + const group = getDestructuringHost(reference); + + if (group) { + if (identifierMap.has(group)) { + identifierMap.get(group).push(identifier); + } else { + identifierMap.set(group, [identifier]); + } + } + } + } + + return identifierMap; +} + +/** + * Finds the nearest parent of node with a given type. + * @param {ASTNode} node The node to search from. + * @param {string} type The type field of the parent node. + * @param {Function} shouldStop A predicate that returns true if the traversal should stop, and false otherwise. + * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists. + */ +function findUp(node, type, shouldStop) { + if (!node || shouldStop(node)) { + return null; + } + if (node.type === type) { + return node; + } + return findUp(node.parent, type, shouldStop); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + destructuring: "any", + ignoreReadBeforeAssign: false, + }, + ], + + docs: { + description: + "Require `const` declarations for variables that are never reassigned after declared", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-const", + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + destructuring: { enum: ["any", "all"] }, + ignoreReadBeforeAssign: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + messages: { + useConst: "'{{name}}' is never reassigned. Use 'const' instead.", + }, + }, + + create(context) { + const [{ destructuring, ignoreReadBeforeAssign }] = context.options; + const shouldMatchAnyDestructuredVariable = destructuring !== "all"; + const sourceCode = context.sourceCode; + const variables = []; + let reportCount = 0; + let checkedId = null; + let checkedName = ""; + + /** + * Reports given identifier nodes if all of the nodes should be declared + * as const. + * + * The argument 'nodes' is an array of Identifier nodes. + * This node is the result of 'getIdentifierIfShouldBeConst()', so it's + * nullable. In simple declaration or assignment cases, the length of + * the array is 1. In destructuring cases, the length of the array can + * be 2 or more. + * @param {(eslint-scope.Reference|null)[]} nodes + * References which are grouped by destructuring to report. + * @returns {void} + */ + function checkGroup(nodes) { + const nodesToReport = nodes.filter(Boolean); + + if ( + nodes.length && + (shouldMatchAnyDestructuredVariable || + nodesToReport.length === nodes.length) + ) { + const varDeclParent = findUp( + nodes[0], + "VariableDeclaration", + parentNode => parentNode.type.endsWith("Statement"), + ); + const isVarDecParentNull = varDeclParent === null; + + if ( + !isVarDecParentNull && + varDeclParent.declarations.length > 0 + ) { + const firstDeclaration = varDeclParent.declarations[0]; + + if (firstDeclaration.init) { + const firstDecParent = firstDeclaration.init.parent; + + /* + * First we check the declaration type and then depending on + * if the type is a "VariableDeclarator" or its an "ObjectPattern" + * we compare the name and id from the first identifier, if the names are different + * we assign the new name, id and reset the count of reportCount and nodeCount in + * order to check each block for the number of reported errors and base our fix + * based on comparing nodes.length and nodesToReport.length. + */ + + if (firstDecParent.type === "VariableDeclarator") { + if (firstDecParent.id.name !== checkedName) { + checkedName = firstDecParent.id.name; + reportCount = 0; + } + + if (firstDecParent.id.type === "ObjectPattern") { + if (firstDecParent.init.name !== checkedName) { + checkedName = firstDecParent.init.name; + reportCount = 0; + } + } + + if (firstDecParent.id !== checkedId) { + checkedId = firstDecParent.id; + reportCount = 0; + } + } + } + } + + let shouldFix = + varDeclParent && + // Don't do a fix unless all variables in the declarations are initialized (or it's in a for-in or for-of loop) + (varDeclParent.parent.type === "ForInStatement" || + varDeclParent.parent.type === "ForOfStatement" || + varDeclParent.declarations.every( + declaration => declaration.init, + )) && + /* + * If options.destructuring is "all", then this warning will not occur unless + * every assignment in the destructuring should be const. In that case, it's safe + * to apply the fix. + */ + nodesToReport.length === nodes.length; + + if ( + !isVarDecParentNull && + varDeclParent.declarations && + varDeclParent.declarations.length !== 1 + ) { + if ( + varDeclParent && + varDeclParent.declarations && + varDeclParent.declarations.length >= 1 + ) { + /* + * Add nodesToReport.length to a count, then comparing the count to the length + * of the declarations in the current block. + */ + + reportCount += nodesToReport.length; + + let totalDeclarationsCount = 0; + + varDeclParent.declarations.forEach(declaration => { + if (declaration.id.type === "ObjectPattern") { + totalDeclarationsCount += + declaration.id.properties.length; + } else if (declaration.id.type === "ArrayPattern") { + totalDeclarationsCount += + declaration.id.elements.length; + } else { + totalDeclarationsCount += 1; + } + }); + + shouldFix = + shouldFix && reportCount === totalDeclarationsCount; + } + } + + nodesToReport.forEach(node => { + context.report({ + node, + messageId: "useConst", + data: node, + fix: shouldFix + ? fixer => { + const letKeywordToken = + sourceCode.getFirstToken( + varDeclParent, + t => t.value === varDeclParent.kind, + ); + + /** + * Extend the replacement range to the whole declaration, + * in order to prevent other fixes in the same pass + * https://github.com/eslint/eslint/issues/13899 + */ + return new FixTracker(fixer, sourceCode) + .retainRange(varDeclParent.range) + .replaceTextRange( + letKeywordToken.range, + "const", + ); + } + : null, + }); + }); + } + } + + return { + "Program:exit"() { + groupByDestructuring(variables, ignoreReadBeforeAssign).forEach( + checkGroup, + ); + }, + + VariableDeclaration(node) { + if (node.kind === "let" && !isInitOfForStatement(node)) { + variables.push(...sourceCode.getDeclaredVariables(node)); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-destructuring.js b/node_modules/eslint/lib/rules/prefer-destructuring.js new file mode 100644 index 00000000..cf108aac --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-destructuring.js @@ -0,0 +1,324 @@ +/** + * @fileoverview Prefer destructuring from arrays and objects + * @author Alex LaFroscia + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const PRECEDENCE_OF_ASSIGNMENT_EXPR = astUtils.getPrecedence({ + type: "AssignmentExpression", +}); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require destructuring from arrays and/or objects", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-destructuring", + }, + + fixable: "code", + + schema: [ + { + /* + * old support {array: Boolean, object: Boolean} + * new support {VariableDeclarator: {}, AssignmentExpression: {}} + */ + oneOf: [ + { + type: "object", + properties: { + VariableDeclarator: { + type: "object", + properties: { + array: { + type: "boolean", + }, + object: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + AssignmentExpression: { + type: "object", + properties: { + array: { + type: "boolean", + }, + object: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + array: { + type: "boolean", + }, + object: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + { + type: "object", + properties: { + enforceForRenamedProperties: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + preferDestructuring: "Use {{type}} destructuring.", + }, + }, + create(context) { + const enabledTypes = context.options[0]; + const enforceForRenamedProperties = + context.options[1] && + context.options[1].enforceForRenamedProperties; + let normalizedOptions = { + VariableDeclarator: { array: true, object: true }, + AssignmentExpression: { array: true, object: true }, + }; + + if (enabledTypes) { + normalizedOptions = + typeof enabledTypes.array !== "undefined" || + typeof enabledTypes.object !== "undefined" + ? { + VariableDeclarator: enabledTypes, + AssignmentExpression: enabledTypes, + } + : enabledTypes; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks if destructuring type should be checked. + * @param {string} nodeType "AssignmentExpression" or "VariableDeclarator" + * @param {string} destructuringType "array" or "object" + * @returns {boolean} `true` if the destructuring type should be checked for the given node + */ + function shouldCheck(nodeType, destructuringType) { + return ( + normalizedOptions && + normalizedOptions[nodeType] && + normalizedOptions[nodeType][destructuringType] + ); + } + + /** + * Determines if the given node is accessing an array index + * + * This is used to differentiate array index access from object property + * access. + * @param {ASTNode} node the node to evaluate + * @returns {boolean} whether or not the node is an integer + */ + function isArrayIndexAccess(node) { + return Number.isInteger(node.property.value); + } + + /** + * Report that the given node should use destructuring + * @param {ASTNode} reportNode the node to report + * @param {string} type the type of destructuring that should have been done + * @param {Function|null} fix the fix function or null to pass to context.report + * @returns {void} + */ + function report(reportNode, type, fix) { + context.report({ + node: reportNode, + messageId: "preferDestructuring", + data: { type }, + fix, + }); + } + + /** + * Determines if a node should be fixed into object destructuring + * + * The fixer only fixes the simplest case of object destructuring, + * like: `let x = a.x`; + * + * Assignment expression is not fixed. + * Array destructuring is not fixed. + * Renamed property is not fixed. + * @param {ASTNode} node the node to evaluate + * @returns {boolean} whether or not the node should be fixed + */ + function shouldFix(node) { + return ( + node.type === "VariableDeclarator" && + node.id.type === "Identifier" && + node.init.type === "MemberExpression" && + !node.init.computed && + node.init.property.type === "Identifier" && + node.id.name === node.init.property.name + ); + } + + /** + * Fix a node into object destructuring. + * This function only handles the simplest case of object destructuring, + * see {@link shouldFix}. + * @param {SourceCodeFixer} fixer the fixer object + * @param {ASTNode} node the node to be fixed. + * @returns {Object} a fix for the node + */ + function fixIntoObjectDestructuring(fixer, node) { + const rightNode = node.init; + const sourceCode = context.sourceCode; + + // Don't fix if that would remove any comments. Only comments inside `rightNode.object` can be preserved. + if ( + sourceCode.getCommentsInside(node).length > + sourceCode.getCommentsInside(rightNode.object).length + ) { + return null; + } + + let objectText = sourceCode.getText(rightNode.object); + + if ( + astUtils.getPrecedence(rightNode.object) < + PRECEDENCE_OF_ASSIGNMENT_EXPR + ) { + objectText = `(${objectText})`; + } + + return fixer.replaceText( + node, + `{${rightNode.property.name}} = ${objectText}`, + ); + } + + /** + * Check that the `prefer-destructuring` rules are followed based on the + * given left- and right-hand side of the assignment. + * + * Pulled out into a separate method so that VariableDeclarators and + * AssignmentExpressions can share the same verification logic. + * @param {ASTNode} leftNode the left-hand side of the assignment + * @param {ASTNode} rightNode the right-hand side of the assignment + * @param {ASTNode} reportNode the node to report the error on + * @returns {void} + */ + function performCheck(leftNode, rightNode, reportNode) { + if ( + rightNode.type !== "MemberExpression" || + rightNode.object.type === "Super" || + rightNode.property.type === "PrivateIdentifier" + ) { + return; + } + + if (isArrayIndexAccess(rightNode)) { + if (shouldCheck(reportNode.type, "array")) { + report(reportNode, "array", null); + } + return; + } + + const fix = shouldFix(reportNode) + ? fixer => fixIntoObjectDestructuring(fixer, reportNode) + : null; + + if ( + shouldCheck(reportNode.type, "object") && + enforceForRenamedProperties + ) { + report(reportNode, "object", fix); + return; + } + + if (shouldCheck(reportNode.type, "object")) { + const property = rightNode.property; + + if ( + (property.type === "Literal" && + leftNode.name === property.value) || + (property.type === "Identifier" && + leftNode.name === property.name && + !rightNode.computed) + ) { + report(reportNode, "object", fix); + } + } + } + + /** + * Check if a given variable declarator is coming from an property access + * that should be using destructuring instead + * @param {ASTNode} node the variable declarator to check + * @returns {void} + */ + function checkVariableDeclarator(node) { + // Skip if variable is declared without assignment + if (!node.init) { + return; + } + + // We only care about member expressions past this point + if (node.init.type !== "MemberExpression") { + return; + } + + performCheck(node.id, node.init, node); + } + + /** + * Run the `prefer-destructuring` check on an AssignmentExpression + * @param {ASTNode} node the AssignmentExpression node + * @returns {void} + */ + function checkAssignmentExpression(node) { + if (node.operator === "=") { + performCheck(node.left, node.right, node); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclarator: checkVariableDeclarator, + AssignmentExpression: checkAssignmentExpression, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js b/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js new file mode 100644 index 00000000..beb78438 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js @@ -0,0 +1,235 @@ +/** + * @fileoverview Rule to disallow Math.pow in favor of the ** operator + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { CALL, ReferenceTracker } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const PRECEDENCE_OF_EXPONENTIATION_EXPR = astUtils.getPrecedence({ + type: "BinaryExpression", + operator: "**", +}); + +/** + * Determines whether the given node needs parens if used as the base in an exponentiation binary expression. + * @param {ASTNode} base The node to check. + * @returns {boolean} `true` if the node needs to be parenthesised. + */ +function doesBaseNeedParens(base) { + return ( + // '**' is right-associative, parens are needed when Math.pow(a ** b, c) is converted to (a ** b) ** c + astUtils.getPrecedence(base) <= PRECEDENCE_OF_EXPONENTIATION_EXPR || + // An unary operator cannot be used immediately before an exponentiation expression + base.type === "AwaitExpression" || + base.type === "UnaryExpression" + ); +} + +/** + * Determines whether the given node needs parens if used as the exponent in an exponentiation binary expression. + * @param {ASTNode} exponent The node to check. + * @returns {boolean} `true` if the node needs to be parenthesised. + */ +function doesExponentNeedParens(exponent) { + // '**' is right-associative, there is no need for parens when Math.pow(a, b ** c) is converted to a ** b ** c + return astUtils.getPrecedence(exponent) < PRECEDENCE_OF_EXPONENTIATION_EXPR; +} + +/** + * Determines whether an exponentiation binary expression at the place of the given node would need parens. + * @param {ASTNode} node A node that would be replaced by an exponentiation binary expression. + * @param {SourceCode} sourceCode A SourceCode object. + * @returns {boolean} `true` if the expression needs to be parenthesised. + */ +function doesExponentiationExpressionNeedParens(node, sourceCode) { + const parent = + node.parent.type === "ChainExpression" + ? node.parent.parent + : node.parent; + + const parentPrecedence = astUtils.getPrecedence(parent); + const needsParens = + parent.type === "ClassDeclaration" || + (parent.type.endsWith("Expression") && + (parentPrecedence === -1 || + parentPrecedence >= PRECEDENCE_OF_EXPONENTIATION_EXPR) && + !( + parent.type === "BinaryExpression" && + parent.operator === "**" && + parent.right === node + ) && + !( + (parent.type === "CallExpression" || + parent.type === "NewExpression") && + parent.arguments.includes(node) + ) && + !( + parent.type === "MemberExpression" && + parent.computed && + parent.property === node + ) && + !(parent.type === "ArrayExpression")); + + return needsParens && !astUtils.isParenthesised(sourceCode, node); +} + +/** + * Optionally parenthesizes given text. + * @param {string} text The text to parenthesize. + * @param {boolean} shouldParenthesize If `true`, the text will be parenthesised. + * @returns {string} parenthesised or unchanged text. + */ +function parenthesizeIfShould(text, shouldParenthesize) { + return shouldParenthesize ? `(${text})` : text; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow the use of `Math.pow` in favor of the `**` operator", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-exponentiation-operator", + }, + + schema: [], + fixable: "code", + + messages: { + useExponentiation: "Use the '**' operator instead of 'Math.pow'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Reports the given node. + * @param {ASTNode} node 'Math.pow()' node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "useExponentiation", + fix(fixer) { + if ( + node.arguments.length !== 2 || + node.arguments.some( + arg => arg.type === "SpreadElement", + ) || + sourceCode.getCommentsInside(node).length > 0 + ) { + return null; + } + + const base = node.arguments[0], + exponent = node.arguments[1], + baseText = sourceCode.getText(base), + exponentText = sourceCode.getText(exponent), + shouldParenthesizeBase = doesBaseNeedParens(base), + shouldParenthesizeExponent = + doesExponentNeedParens(exponent), + shouldParenthesizeAll = + doesExponentiationExpressionNeedParens( + node, + sourceCode, + ); + + let prefix = "", + suffix = ""; + + if (!shouldParenthesizeAll) { + if (!shouldParenthesizeBase) { + const firstReplacementToken = + sourceCode.getFirstToken(base), + tokenBefore = sourceCode.getTokenBefore(node); + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + firstReplacementToken, + ) + ) { + prefix = " "; // a+Math.pow(++b, c) -> a+ ++b**c + } + } + if (!shouldParenthesizeExponent) { + const lastReplacementToken = + sourceCode.getLastToken(exponent), + tokenAfter = sourceCode.getTokenAfter(node); + + if ( + tokenAfter && + node.range[1] === tokenAfter.range[0] && + !astUtils.canTokensBeAdjacent( + lastReplacementToken, + tokenAfter, + ) + ) { + suffix = " "; // Math.pow(a, b)in c -> a**b in c + } + } + } + + const baseReplacement = parenthesizeIfShould( + baseText, + shouldParenthesizeBase, + ), + exponentReplacement = parenthesizeIfShould( + exponentText, + shouldParenthesizeExponent, + ), + replacement = parenthesizeIfShould( + `${baseReplacement}**${exponentReplacement}`, + shouldParenthesizeAll, + ); + + return fixer.replaceText( + node, + `${prefix}${replacement}${suffix}`, + ); + }, + }); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const trackMap = { + Math: { + pow: { [CALL]: true }, + }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + trackMap, + )) { + report(refNode); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-named-capture-group.js b/node_modules/eslint/lib/rules/prefer-named-capture-group.js new file mode 100644 index 00000000..d5c1f460 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-named-capture-group.js @@ -0,0 +1,197 @@ +/** + * @fileoverview Rule to enforce requiring named capture groups in regular expression. + * @author Pig Fang + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStringIfConstant, +} = require("@eslint-community/eslint-utils"); +const regexpp = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @import { SuggestedEdit } from "@eslint/core"; */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const parser = new regexpp.RegExpParser(); + +/** + * Creates fixer suggestions for the regex, if statically determinable. + * @param {number} groupStart Starting index of the regex group. + * @param {string} pattern The regular expression pattern to be checked. + * @param {string} rawText Source text of the regexNode. + * @param {ASTNode} regexNode AST node which contains the regular expression. + * @returns {Array} Fixer suggestions for the regex, if statically determinable. + */ +function suggestIfPossible(groupStart, pattern, rawText, regexNode) { + switch (regexNode.type) { + case "Literal": + if (typeof regexNode.value === "string" && rawText.includes("\\")) { + return null; + } + break; + case "TemplateLiteral": + if ( + regexNode.expressions.length || + rawText.slice(1, -1) !== pattern + ) { + return null; + } + break; + default: + return null; + } + + const start = regexNode.range[0] + groupStart + 2; + + return [ + { + fix(fixer) { + const existingTemps = pattern.match(/temp\d+/gu) || []; + const highestTempCount = existingTemps.reduce( + (previous, next) => + Math.max(previous, Number(next.slice("temp".length))), + 0, + ); + + return fixer.insertTextBeforeRange( + [start, start], + `?`, + ); + }, + messageId: "addGroupName", + }, + { + fix(fixer) { + return fixer.insertTextBeforeRange([start, start], "?:"); + }, + messageId: "addNonCapture", + }, + ]; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce using named capture group in regular expression", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-named-capture-group", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + addGroupName: "Add name to capture group.", + addNonCapture: "Convert group to non-capturing.", + required: + "Capture group '{{group}}' should be converted to a named or non-capturing group.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Function to check regular expression. + * @param {string} pattern The regular expression pattern to be checked. + * @param {ASTNode} node AST node which contains the regular expression or a call/new expression. + * @param {ASTNode} regexNode AST node which contains the regular expression. + * @param {string|null} flags The regular expression flags to be checked. + * @returns {void} + */ + function checkRegex(pattern, node, regexNode, flags) { + let ast; + + try { + ast = parser.parsePattern(pattern, 0, pattern.length, { + unicode: Boolean(flags && flags.includes("u")), + unicodeSets: Boolean(flags && flags.includes("v")), + }); + } catch { + // ignore regex syntax errors + return; + } + + regexpp.visitRegExpAST(ast, { + onCapturingGroupEnter(group) { + if (!group.name) { + const rawText = sourceCode.getText(regexNode); + const suggest = suggestIfPossible( + group.start, + pattern, + rawText, + regexNode, + ); + + context.report({ + node, + messageId: "required", + data: { + group: group.raw, + }, + suggest, + }); + } + }, + }); + } + + return { + Literal(node) { + if (node.regex) { + checkRegex( + node.regex.pattern, + node, + node, + node.regex.flags, + ); + } + }, + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const traceMap = { + RegExp: { + [CALL]: true, + [CONSTRUCT]: true, + }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + traceMap, + )) { + const regex = getStringIfConstant(refNode.arguments[0]); + const flags = getStringIfConstant(refNode.arguments[1]); + + if (regex) { + checkRegex(regex, refNode, refNode.arguments[0], flags); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-numeric-literals.js b/node_modules/eslint/lib/rules/prefer-numeric-literals.js new file mode 100644 index 00000000..86dec887 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-numeric-literals.js @@ -0,0 +1,157 @@ +/** + * @fileoverview Rule to disallow `parseInt()` in favor of binary, octal, and hexadecimal literals + * @author Annie Zhang, Henry Zhu + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const radixMap = new Map([ + [2, { system: "binary", literalPrefix: "0b" }], + [8, { system: "octal", literalPrefix: "0o" }], + [16, { system: "hexadecimal", literalPrefix: "0x" }], +]); + +/** + * Checks to see if a CallExpression's callee node is `parseInt` or + * `Number.parseInt`. + * @param {ASTNode} calleeNode The callee node to evaluate. + * @returns {boolean} True if the callee is `parseInt` or `Number.parseInt`, + * false otherwise. + */ +function isParseInt(calleeNode) { + return ( + astUtils.isSpecificId(calleeNode, "parseInt") || + astUtils.isSpecificMemberAccess(calleeNode, "Number", "parseInt") + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-numeric-literals", + }, + + schema: [], + + messages: { + useLiteral: + "Use {{system}} literals instead of {{functionName}}().", + }, + + fixable: "code", + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + "CallExpression[arguments.length=2]"(node) { + const [strNode, radixNode] = node.arguments, + str = astUtils.getStaticStringValue(strNode), + radix = radixNode.value; + + if ( + str !== null && + astUtils.isStringLiteral(strNode) && + radixNode.type === "Literal" && + typeof radix === "number" && + radixMap.has(radix) && + isParseInt(node.callee) + ) { + const { system, literalPrefix } = radixMap.get(radix); + + context.report({ + node, + messageId: "useLiteral", + data: { + system, + functionName: sourceCode.getText(node.callee), + }, + fix(fixer) { + if (sourceCode.getCommentsInside(node).length) { + return null; + } + + const replacement = `${literalPrefix}${str}`; + + if (+replacement !== parseInt(str, radix)) { + /* + * If the newly-produced literal would be invalid, (e.g. 0b1234), + * or it would yield an incorrect parseInt result for some other reason, don't make a fix. + * + * If `str` had numeric separators, `+replacement` will evaluate to `NaN` because unary `+` + * per the specification doesn't support numeric separators. Thus, the above condition will be `true` + * (`NaN !== anything` is always `true`) regardless of the `parseInt(str, radix)` value. + * Consequently, no autofixes will be made. This is correct behavior because `parseInt` also + * doesn't support numeric separators, but it does parse part of the string before the first `_`, + * so the autofix would be invalid: + * + * parseInt("1_1", 2) // === 1 + * 0b1_1 // === 3 + */ + return null; + } + + const tokenBefore = sourceCode.getTokenBefore(node), + tokenAfter = sourceCode.getTokenAfter(node); + let prefix = "", + suffix = ""; + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + replacement, + ) + ) { + prefix = " "; + } + + if ( + tokenAfter && + node.range[1] === tokenAfter.range[0] && + !astUtils.canTokensBeAdjacent( + replacement, + tokenAfter, + ) + ) { + suffix = " "; + } + + return fixer.replaceText( + node, + `${prefix}${replacement}${suffix}`, + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-object-has-own.js b/node_modules/eslint/lib/rules/prefer-object-has-own.js new file mode 100644 index 00000000..3e0bb520 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-object-has-own.js @@ -0,0 +1,148 @@ +/** + * @fileoverview Prefers Object.hasOwn() instead of Object.prototype.hasOwnProperty.call() + * @author Nitin Kumar + * @author Gautam Arora + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks if the given node is considered to be an access to a property of `Object.prototype`. + * @param {ASTNode} node `MemberExpression` node to evaluate. + * @returns {boolean} `true` if `node.object` is `Object`, `Object.prototype`, or `{}` (empty 'ObjectExpression' node). + */ +function hasLeftHandObject(node) { + /* + * ({}).hasOwnProperty.call(obj, prop) - `true` + * ({ foo }.hasOwnProperty.call(obj, prop)) - `false`, object literal should be empty + */ + if ( + node.object.type === "ObjectExpression" && + node.object.properties.length === 0 + ) { + return true; + } + + const objectNodeToCheck = + node.object.type === "MemberExpression" && + astUtils.getStaticPropertyName(node.object) === "prototype" + ? node.object.object + : node.object; + + if ( + objectNodeToCheck.type === "Identifier" && + objectNodeToCheck.name === "Object" + ) { + return true; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + docs: { + description: + "Disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-object-has-own", + }, + schema: [], + messages: { + useHasOwn: + "Use 'Object.hasOwn()' instead of 'Object.prototype.hasOwnProperty.call()'.", + }, + fixable: "code", + }, + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + if ( + !( + node.callee.type === "MemberExpression" && + node.callee.object.type === "MemberExpression" + ) + ) { + return; + } + + const calleePropertyName = astUtils.getStaticPropertyName( + node.callee, + ); + const objectPropertyName = astUtils.getStaticPropertyName( + node.callee.object, + ); + const isObject = hasLeftHandObject(node.callee.object); + + // check `Object` scope + const scope = sourceCode.getScope(node); + const variable = astUtils.getVariableByName(scope, "Object"); + + if ( + calleePropertyName === "call" && + objectPropertyName === "hasOwnProperty" && + isObject && + variable && + variable.scope.type === "global" + ) { + context.report({ + node, + messageId: "useHasOwn", + fix(fixer) { + if ( + sourceCode.getCommentsInside(node.callee) + .length > 0 + ) { + return null; + } + + const tokenJustBeforeNode = + sourceCode.getTokenBefore(node.callee, { + includeComments: true, + }); + + // for https://github.com/eslint/eslint/pull/15346#issuecomment-991417335 + if ( + tokenJustBeforeNode && + tokenJustBeforeNode.range[1] === + node.callee.range[0] && + !astUtils.canTokensBeAdjacent( + tokenJustBeforeNode, + "Object.hasOwn", + ) + ) { + return fixer.replaceText( + node.callee, + " Object.hasOwn", + ); + } + + return fixer.replaceText( + node.callee, + "Object.hasOwn", + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-object-spread.js b/node_modules/eslint/lib/rules/prefer-object-spread.js new file mode 100644 index 00000000..6827e2c2 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-object-spread.js @@ -0,0 +1,319 @@ +/** + * @fileoverview Rule to disallow using `Object.assign` with an object literal as the first argument and prefer the use of object spread instead + * @author Sharmila Jesupaul + */ + +"use strict"; + +const { CALL, ReferenceTracker } = require("@eslint-community/eslint-utils"); +const { + isCommaToken, + isOpeningParenToken, + isClosingParenToken, + isParenthesised, +} = require("./utils/ast-utils"); + +const ANY_SPACE = /\s/u; + +/** + * Helper that checks if the Object.assign call has array spread + * @param {ASTNode} node The node that the rule warns on + * @returns {boolean} - Returns true if the Object.assign call has array spread + */ +function hasArraySpread(node) { + return node.arguments.some(arg => arg.type === "SpreadElement"); +} + +/** + * Determines whether the given node is an accessor property (getter/setter). + * @param {ASTNode} node Node to check. + * @returns {boolean} `true` if the node is a getter or a setter. + */ +function isAccessorProperty(node) { + return ( + node.type === "Property" && (node.kind === "get" || node.kind === "set") + ); +} + +/** + * Determines whether the given object expression node has accessor properties (getters/setters). + * @param {ASTNode} node `ObjectExpression` node to check. + * @returns {boolean} `true` if the node has at least one getter/setter. + */ +function hasAccessors(node) { + return node.properties.some(isAccessorProperty); +} + +/** + * Determines whether the given call expression node has object expression arguments with accessor properties (getters/setters). + * @param {ASTNode} node `CallExpression` node to check. + * @returns {boolean} `true` if the node has at least one argument that is an object expression with at least one getter/setter. + */ +function hasArgumentsWithAccessors(node) { + return node.arguments + .filter(arg => arg.type === "ObjectExpression") + .some(hasAccessors); +} + +/** + * Helper that checks if the node needs parentheses to be valid JS. + * The default is to wrap the node in parentheses to avoid parsing errors. + * @param {ASTNode} node The node that the rule warns on + * @param {Object} sourceCode in context sourcecode object + * @returns {boolean} - Returns true if the node needs parentheses + */ +function needsParens(node, sourceCode) { + const parent = node.parent; + + switch (parent.type) { + case "VariableDeclarator": + case "ArrayExpression": + case "ReturnStatement": + case "CallExpression": + case "Property": + return false; + case "AssignmentExpression": + return parent.left === node && !isParenthesised(sourceCode, node); + default: + return !isParenthesised(sourceCode, node); + } +} + +/** + * Determines if an argument needs parentheses. The default is to not add parens. + * @param {ASTNode} node The node to be checked. + * @param {Object} sourceCode in context sourcecode object + * @returns {boolean} True if the node needs parentheses + */ +function argNeedsParens(node, sourceCode) { + switch (node.type) { + case "AssignmentExpression": + case "ArrowFunctionExpression": + case "ConditionalExpression": + return !isParenthesised(sourceCode, node); + default: + return false; + } +} + +/** + * Get the parenthesis tokens of a given ObjectExpression node. + * This includes the braces of the object literal and enclosing parentheses. + * @param {ASTNode} node The node to get. + * @param {Token} leftArgumentListParen The opening paren token of the argument list. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token[]} The parenthesis tokens of the node. This is sorted by the location. + */ +function getParenTokens(node, leftArgumentListParen, sourceCode) { + const parens = [ + sourceCode.getFirstToken(node), + sourceCode.getLastToken(node), + ]; + let leftNext = sourceCode.getTokenBefore(node); + let rightNext = sourceCode.getTokenAfter(node); + + // Note: don't include the parens of the argument list. + while ( + leftNext && + rightNext && + leftNext.range[0] > leftArgumentListParen.range[0] && + isOpeningParenToken(leftNext) && + isClosingParenToken(rightNext) + ) { + parens.push(leftNext, rightNext); + leftNext = sourceCode.getTokenBefore(leftNext); + rightNext = sourceCode.getTokenAfter(rightNext); + } + + return parens.sort((a, b) => a.range[0] - b.range[0]); +} + +/** + * Get the range of a given token and around whitespaces. + * @param {Token} token The token to get range. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {number} The end of the range of the token and around whitespaces. + */ +function getStartWithSpaces(token, sourceCode) { + const text = sourceCode.text; + let start = token.range[0]; + + // If the previous token is a line comment then skip this step to avoid commenting this token out. + { + const prevToken = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + if (prevToken && prevToken.type === "Line") { + return start; + } + } + + // Detect spaces before the token. + while (ANY_SPACE.test(text[start - 1] || "")) { + start -= 1; + } + + return start; +} + +/** + * Get the range of a given token and around whitespaces. + * @param {Token} token The token to get range. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {number} The start of the range of the token and around whitespaces. + */ +function getEndWithSpaces(token, sourceCode) { + const text = sourceCode.text; + let end = token.range[1]; + + // Detect spaces after the token. + while (ANY_SPACE.test(text[end] || "")) { + end += 1; + } + + return end; +} + +/** + * Autofixes the Object.assign call to use an object spread instead. + * @param {ASTNode|null} node The node that the rule warns on, i.e. the Object.assign call + * @param {string} sourceCode sourceCode of the Object.assign call + * @returns {Function} autofixer - replaces the Object.assign with a spread object. + */ +function defineFixer(node, sourceCode) { + return function* (fixer) { + const leftParen = sourceCode.getTokenAfter( + node.callee, + isOpeningParenToken, + ); + const rightParen = sourceCode.getLastToken(node); + + // Remove everything before the opening paren: callee `Object.assign`, type arguments, and whitespace between the callee and the paren. + yield fixer.removeRange([node.range[0], leftParen.range[0]]); + + // Replace the parens of argument list to braces. + if (needsParens(node, sourceCode)) { + yield fixer.replaceText(leftParen, "({"); + yield fixer.replaceText(rightParen, "})"); + } else { + yield fixer.replaceText(leftParen, "{"); + yield fixer.replaceText(rightParen, "}"); + } + + // Process arguments. + for (const argNode of node.arguments) { + const innerParens = getParenTokens(argNode, leftParen, sourceCode); + const left = innerParens.shift(); + const right = innerParens.pop(); + + if (argNode.type === "ObjectExpression") { + const maybeTrailingComma = sourceCode.getLastToken(argNode, 1); + const maybeArgumentComma = sourceCode.getTokenAfter(right); + + /* + * Make bare this object literal. + * And remove spaces inside of the braces for better formatting. + */ + for (const innerParen of innerParens) { + yield fixer.remove(innerParen); + } + const leftRange = [ + left.range[0], + getEndWithSpaces(left, sourceCode), + ]; + const rightRange = [ + Math.max( + getStartWithSpaces(right, sourceCode), + leftRange[1], + ), // Ensure ranges don't overlap + right.range[1], + ]; + + yield fixer.removeRange(leftRange); + yield fixer.removeRange(rightRange); + + // Remove the comma of this argument if it's duplication. + if ( + (argNode.properties.length === 0 || + isCommaToken(maybeTrailingComma)) && + isCommaToken(maybeArgumentComma) + ) { + yield fixer.remove(maybeArgumentComma); + } + } else { + // Make spread. + if (argNeedsParens(argNode, sourceCode)) { + yield fixer.insertTextBefore(left, "...("); + yield fixer.insertTextAfter(right, ")"); + } else { + yield fixer.insertTextBefore(left, "..."); + } + } + } + }; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow using `Object.assign` with an object literal as the first argument and prefer the use of object spread instead", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-object-spread", + }, + + schema: [], + fixable: "code", + + messages: { + useSpreadMessage: + "Use an object spread instead of `Object.assign` eg: `{ ...foo }`.", + useLiteralMessage: + "Use an object literal instead of `Object.assign`. eg: `{ foo: bar }`.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const trackMap = { + Object: { + assign: { [CALL]: true }, + }, + }; + + // Iterate all calls of `Object.assign` (only of the global variable `Object`). + for (const { node: refNode } of tracker.iterateGlobalReferences( + trackMap, + )) { + if ( + refNode.arguments.length >= 1 && + refNode.arguments[0].type === "ObjectExpression" && + !hasArraySpread(refNode) && + !( + refNode.arguments.length > 1 && + hasArgumentsWithAccessors(refNode) + ) + ) { + const messageId = + refNode.arguments.length === 1 + ? "useLiteralMessage" + : "useSpreadMessage"; + const fix = defineFixer(refNode, sourceCode); + + context.report({ node: refNode, messageId, fix }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js b/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js new file mode 100644 index 00000000..7043f296 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js @@ -0,0 +1,154 @@ +/** + * @fileoverview restrict values that can be used as Promise rejection reasons + * @author Teddy Katz + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowEmptyReject: false, + }, + ], + + docs: { + description: + "Require using Error objects as Promise rejection reasons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-promise-reject-errors", + }, + + fixable: null, + + schema: [ + { + type: "object", + properties: { + allowEmptyReject: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + + messages: { + rejectAnError: + "Expected the Promise rejection reason to be an Error.", + }, + }, + + create(context) { + const [{ allowEmptyReject }] = context.options; + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks the argument of a reject() or Promise.reject() CallExpression, and reports it if it can't be an Error + * @param {ASTNode} callExpression A CallExpression node which is used to reject a Promise + * @returns {void} + */ + function checkRejectCall(callExpression) { + if (!callExpression.arguments.length && allowEmptyReject) { + return; + } + if ( + !callExpression.arguments.length || + !astUtils.couldBeError(callExpression.arguments[0]) || + (callExpression.arguments[0].type === "Identifier" && + callExpression.arguments[0].name === "undefined") + ) { + context.report({ + node: callExpression, + messageId: "rejectAnError", + }); + } + } + + /** + * Determines whether a function call is a Promise.reject() call + * @param {ASTNode} node A CallExpression node + * @returns {boolean} `true` if the call is a Promise.reject() call + */ + function isPromiseRejectCall(node) { + return astUtils.isSpecificMemberAccess( + node.callee, + "Promise", + "reject", + ); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + // Check `Promise.reject(value)` calls. + CallExpression(node) { + if (isPromiseRejectCall(node)) { + checkRejectCall(node); + } + }, + + /* + * Check for `new Promise((resolve, reject) => {})`, and check for reject() calls. + * This function is run on "NewExpression:exit" instead of "NewExpression" to ensure that + * the nodes in the expression already have the `parent` property. + */ + "NewExpression:exit"(node) { + if ( + node.callee.type === "Identifier" && + node.callee.name === "Promise" && + node.arguments.length && + astUtils.isFunction(node.arguments[0]) && + node.arguments[0].params.length > 1 && + node.arguments[0].params[1].type === "Identifier" + ) { + sourceCode + .getDeclaredVariables(node.arguments[0]) + + /* + * Find the first variable that matches the second parameter's name. + * If the first parameter has the same name as the second parameter, then the variable will actually + * be "declared" when the first parameter is evaluated, but then it will be immediately overwritten + * by the second parameter. It's not possible for an expression with the variable to be evaluated before + * the variable is overwritten, because functions with duplicate parameters cannot have destructuring or + * default assignments in their parameter lists. Therefore, it's not necessary to explicitly account for + * this case. + */ + .find( + variable => + variable.name === + node.arguments[0].params[1].name, + ) + + // Get the references to that variable. + .references // Only check the references that read the parameter's value. + .filter(ref => ref.isRead()) + + // Only check the references that are used as the callee in a function call, e.g. `reject(foo)`. + .filter( + ref => + ref.identifier.parent.type === + "CallExpression" && + ref.identifier === ref.identifier.parent.callee, + ) + + // Check the argument of the function call to determine whether it's an Error. + .forEach(ref => checkRejectCall(ref.identifier.parent)); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-reflect.js b/node_modules/eslint/lib/rules/prefer-reflect.js new file mode 100644 index 00000000..4eae98af --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-reflect.js @@ -0,0 +1,150 @@ +/** + * @fileoverview Rule to suggest using "Reflect" api over Function/Object methods + * @author Keith Cirkel + * @deprecated in ESLint v3.9.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `Reflect` methods where applicable", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-reflect", + }, + + deprecated: { + message: "The original intention of this rule was misguided.", + deprecatedSince: "3.9.0", + availableUntil: null, + replacedBy: [], + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + enum: [ + "apply", + "call", + "delete", + "defineProperty", + "getOwnPropertyDescriptor", + "getPrototypeOf", + "setPrototypeOf", + "isExtensible", + "getOwnPropertyNames", + "preventExtensions", + ], + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + preferReflect: + "Avoid using {{existing}}, instead use {{substitute}}.", + }, + }, + + create(context) { + const existingNames = { + apply: "Function.prototype.apply", + call: "Function.prototype.call", + defineProperty: "Object.defineProperty", + getOwnPropertyDescriptor: "Object.getOwnPropertyDescriptor", + getPrototypeOf: "Object.getPrototypeOf", + setPrototypeOf: "Object.setPrototypeOf", + isExtensible: "Object.isExtensible", + getOwnPropertyNames: "Object.getOwnPropertyNames", + preventExtensions: "Object.preventExtensions", + }; + + const reflectSubstitutes = { + apply: "Reflect.apply", + call: "Reflect.apply", + defineProperty: "Reflect.defineProperty", + getOwnPropertyDescriptor: "Reflect.getOwnPropertyDescriptor", + getPrototypeOf: "Reflect.getPrototypeOf", + setPrototypeOf: "Reflect.setPrototypeOf", + isExtensible: "Reflect.isExtensible", + getOwnPropertyNames: "Reflect.getOwnPropertyNames", + preventExtensions: "Reflect.preventExtensions", + }; + + const exceptions = (context.options[0] || {}).exceptions || []; + + /** + * Reports the Reflect violation based on the `existing` and `substitute` + * @param {Object} node The node that violates the rule. + * @param {string} existing The existing method name that has been used. + * @param {string} substitute The Reflect substitute that should be used. + * @returns {void} + */ + function report(node, existing, substitute) { + context.report({ + node, + messageId: "preferReflect", + data: { + existing, + substitute, + }, + }); + } + + return { + CallExpression(node) { + const methodName = (node.callee.property || {}).name; + const isReflectCall = + (node.callee.object || {}).name === "Reflect"; + const hasReflectSubstitute = Object.hasOwn( + reflectSubstitutes, + methodName, + ); + const userConfiguredException = exceptions.includes(methodName); + + if ( + hasReflectSubstitute && + !isReflectCall && + !userConfiguredException + ) { + report( + node, + existingNames[methodName], + reflectSubstitutes[methodName], + ); + } + }, + UnaryExpression(node) { + const isDeleteOperator = node.operator === "delete"; + const targetsIdentifier = node.argument.type === "Identifier"; + const userConfiguredException = exceptions.includes("delete"); + + if ( + isDeleteOperator && + !targetsIdentifier && + !userConfiguredException + ) { + report( + node, + "the delete keyword", + "Reflect.deleteProperty", + ); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-regex-literals.js b/node_modules/eslint/lib/rules/prefer-regex-literals.js new file mode 100644 index 00000000..ce2e8235 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-regex-literals.js @@ -0,0 +1,605 @@ +/** + * @fileoverview Rule to disallow use of the `RegExp` constructor in favor of regular expression literals + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { + CALL, + CONSTRUCT, + ReferenceTracker, +} = require("@eslint-community/eslint-utils"); +const { + RegExpValidator, + visitRegExpAST, + RegExpParser, +} = require("@eslint-community/regexpp"); +const { canTokensBeAdjacent } = require("./utils/ast-utils"); +const { REGEXPP_LATEST_ECMA_VERSION } = require("./utils/regular-expressions"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is a string literal. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a string literal. + */ +function isStringLiteral(node) { + return node.type === "Literal" && typeof node.value === "string"; +} + +/** + * Determines whether the given node is a regex literal. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a regex literal. + */ +function isRegexLiteral(node) { + return node.type === "Literal" && Object.hasOwn(node, "regex"); +} + +const validPrecedingTokens = new Set([ + "(", + ";", + "[", + ",", + "=", + "+", + "*", + "-", + "?", + "~", + "%", + "**", + "!", + "typeof", + "instanceof", + "&&", + "||", + "??", + "return", + "...", + "delete", + "void", + "in", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "<<", + ">>", + ">>>", + "&", + "|", + "^", + ":", + "{", + "=>", + "*=", + "<<=", + ">>=", + ">>>=", + "^=", + "|=", + "&=", + "??=", + "||=", + "&&=", + "**=", + "+=", + "-=", + "/=", + "%=", + "/", + "do", + "break", + "continue", + "debugger", + "case", + "throw", +]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + disallowRedundantWrapping: false, + }, + ], + + docs: { + description: + "Disallow use of the `RegExp` constructor in favor of regular expression literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-regex-literals", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + disallowRedundantWrapping: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedRegExp: + "Use a regular expression literal instead of the 'RegExp' constructor.", + replaceWithLiteral: + "Replace with an equivalent regular expression literal.", + replaceWithLiteralAndFlags: + "Replace with an equivalent regular expression literal with flags '{{ flags }}'.", + replaceWithIntendedLiteralAndFlags: + "Replace with a regular expression literal with flags '{{ flags }}'.", + unexpectedRedundantRegExp: + "Regular expression literal is unnecessarily wrapped within a 'RegExp' constructor.", + unexpectedRedundantRegExpWithFlags: + "Use regular expression literal with flags instead of the 'RegExp' constructor.", + }, + }, + + create(context) { + const [{ disallowRedundantWrapping }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Determines whether the given node is a String.raw`` tagged template expression + * with a static template literal. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is String.raw`` with a static template. + */ + function isStringRawTaggedStaticTemplateLiteral(node) { + return ( + node.type === "TaggedTemplateExpression" && + astUtils.isSpecificMemberAccess(node.tag, "String", "raw") && + sourceCode.isGlobalReference( + astUtils.skipChainExpression(node.tag).object, + ) && + astUtils.isStaticTemplateLiteral(node.quasi) + ); + } + + /** + * Gets the value of a string + * @param {ASTNode} node The node to get the string of. + * @returns {string|null} The value of the node. + */ + function getStringValue(node) { + if (isStringLiteral(node)) { + return node.value; + } + + if (astUtils.isStaticTemplateLiteral(node)) { + return node.quasis[0].value.cooked; + } + + if (isStringRawTaggedStaticTemplateLiteral(node)) { + return node.quasi.quasis[0].value.raw; + } + + return null; + } + + /** + * Determines whether the given node is considered to be a static string by the logic of this rule. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a static string. + */ + function isStaticString(node) { + return ( + isStringLiteral(node) || + astUtils.isStaticTemplateLiteral(node) || + isStringRawTaggedStaticTemplateLiteral(node) + ); + } + + /** + * Determines whether the relevant arguments of the given are all static string literals. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if all arguments are static strings. + */ + function hasOnlyStaticStringArguments(node) { + const args = node.arguments; + + if ( + (args.length === 1 || args.length === 2) && + args.every(isStaticString) + ) { + return true; + } + + return false; + } + + /** + * Determines whether the arguments of the given node indicate that a regex literal is unnecessarily wrapped. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node already contains a regex literal argument. + */ + function isUnnecessarilyWrappedRegexLiteral(node) { + const args = node.arguments; + + if (args.length === 1 && isRegexLiteral(args[0])) { + return true; + } + + if ( + args.length === 2 && + isRegexLiteral(args[0]) && + isStaticString(args[1]) + ) { + return true; + } + + return false; + } + + /** + * Returns a ecmaVersion compatible for regexpp. + * @param {number} ecmaVersion The ecmaVersion to convert. + * @returns {import("@eslint-community/regexpp/ecma-versions").EcmaVersion} The resulting ecmaVersion compatible for regexpp. + */ + function getRegexppEcmaVersion(ecmaVersion) { + if (ecmaVersion <= 5) { + return 5; + } + return Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION); + } + + const regexppEcmaVersion = getRegexppEcmaVersion( + context.languageOptions.ecmaVersion, + ); + + /** + * Makes a character escaped or else returns null. + * @param {string} character The character to escape. + * @returns {string} The resulting escaped character. + */ + function resolveEscapes(character) { + switch (character) { + case "\n": + case "\\\n": + return "\\n"; + + case "\r": + case "\\\r": + return "\\r"; + + case "\t": + case "\\\t": + return "\\t"; + + case "\v": + case "\\\v": + return "\\v"; + + case "\f": + case "\\\f": + return "\\f"; + + case "/": + return "\\/"; + + default: + return null; + } + } + + /** + * Checks whether the given regex and flags are valid for the ecma version or not. + * @param {string} pattern The regex pattern to check. + * @param {string | undefined} flags The regex flags to check. + * @returns {boolean} True if the given regex pattern and flags are valid for the ecma version. + */ + function isValidRegexForEcmaVersion(pattern, flags) { + const validator = new RegExpValidator({ + ecmaVersion: regexppEcmaVersion, + }); + + try { + validator.validatePattern(pattern, 0, pattern.length, { + unicode: flags ? flags.includes("u") : false, + unicodeSets: flags ? flags.includes("v") : false, + }); + if (flags) { + validator.validateFlags(flags); + } + return true; + } catch { + return false; + } + } + + /** + * Checks whether two given regex flags contain the same flags or not. + * @param {string} flagsA The regex flags. + * @param {string} flagsB The regex flags. + * @returns {boolean} True if two regex flags contain same flags. + */ + function areFlagsEqual(flagsA, flagsB) { + return [...flagsA].sort().join("") === [...flagsB].sort().join(""); + } + + /** + * Merges two regex flags. + * @param {string} flagsA The regex flags. + * @param {string} flagsB The regex flags. + * @returns {string} The merged regex flags. + */ + function mergeRegexFlags(flagsA, flagsB) { + const flagsSet = new Set([...flagsA, ...flagsB]); + + return [...flagsSet].join(""); + } + + /** + * Checks whether a give node can be fixed to the given regex pattern and flags. + * @param {ASTNode} node The node to check. + * @param {string} pattern The regex pattern to check. + * @param {string} flags The regex flags + * @returns {boolean} True if a node can be fixed to the given regex pattern and flags. + */ + function canFixTo(node, pattern, flags) { + const tokenBefore = sourceCode.getTokenBefore(node); + + return ( + sourceCode.getCommentsInside(node).length === 0 && + (!tokenBefore || validPrecedingTokens.has(tokenBefore.value)) && + isValidRegexForEcmaVersion(pattern, flags) + ); + } + + /** + * Returns a safe output code considering the before and after tokens. + * @param {ASTNode} node The regex node. + * @param {string} newRegExpValue The new regex expression value. + * @returns {string} The output code. + */ + function getSafeOutput(node, newRegExpValue) { + const tokenBefore = sourceCode.getTokenBefore(node); + const tokenAfter = sourceCode.getTokenAfter(node); + + return ( + (tokenBefore && + !canTokensBeAdjacent(tokenBefore, newRegExpValue) && + tokenBefore.range[1] === node.range[0] + ? " " + : "") + + newRegExpValue + + (tokenAfter && + !canTokensBeAdjacent(newRegExpValue, tokenAfter) && + node.range[1] === tokenAfter.range[0] + ? " " + : "") + ); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const traceMap = { + RegExp: { + [CALL]: true, + [CONSTRUCT]: true, + }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + traceMap, + )) { + if ( + disallowRedundantWrapping && + isUnnecessarilyWrappedRegexLiteral(refNode) + ) { + const regexNode = refNode.arguments[0]; + + if (refNode.arguments.length === 2) { + const suggests = []; + + const argFlags = + getStringValue(refNode.arguments[1]) || ""; + + if ( + canFixTo( + refNode, + regexNode.regex.pattern, + argFlags, + ) + ) { + suggests.push({ + messageId: "replaceWithLiteralAndFlags", + pattern: regexNode.regex.pattern, + flags: argFlags, + }); + } + + const literalFlags = regexNode.regex.flags || ""; + const mergedFlags = mergeRegexFlags( + literalFlags, + argFlags, + ); + + if ( + !areFlagsEqual(mergedFlags, argFlags) && + canFixTo( + refNode, + regexNode.regex.pattern, + mergedFlags, + ) + ) { + suggests.push({ + messageId: + "replaceWithIntendedLiteralAndFlags", + pattern: regexNode.regex.pattern, + flags: mergedFlags, + }); + } + + context.report({ + node: refNode, + messageId: "unexpectedRedundantRegExpWithFlags", + suggest: suggests.map( + ({ flags, pattern, messageId }) => ({ + messageId, + data: { + flags, + }, + fix(fixer) { + return fixer.replaceText( + refNode, + getSafeOutput( + refNode, + `/${pattern}/${flags}`, + ), + ); + }, + }), + ), + }); + } else { + const outputs = []; + + if ( + canFixTo( + refNode, + regexNode.regex.pattern, + regexNode.regex.flags, + ) + ) { + outputs.push(sourceCode.getText(regexNode)); + } + + context.report({ + node: refNode, + messageId: "unexpectedRedundantRegExp", + suggest: outputs.map(output => ({ + messageId: "replaceWithLiteral", + fix(fixer) { + return fixer.replaceText( + refNode, + getSafeOutput(refNode, output), + ); + }, + })), + }); + } + } else if (hasOnlyStaticStringArguments(refNode)) { + let regexContent = getStringValue(refNode.arguments[0]); + let noFix = false; + let flags; + + if (refNode.arguments[1]) { + flags = getStringValue(refNode.arguments[1]); + } + + if (!canFixTo(refNode, regexContent, flags)) { + noFix = true; + } + + if ( + !/^[-a-zA-Z0-9\\[\](){} \t\r\n\v\f!@#$%^&*+^_=/~`.> + accumulator + + sourceText.slice( + token.range[1], + allTokens[index + 1].range[0], + ), + "", + ); + } + + /** + * Returns a template literal form of the given node. + * @param {ASTNode} currentNode A node that should be converted to a template literal + * @param {string} textBeforeNode Text that should appear before the node + * @param {string} textAfterNode Text that should appear after the node + * @returns {string} A string form of this node, represented as a template literal + */ + function getTemplateLiteral( + currentNode, + textBeforeNode, + textAfterNode, + ) { + if ( + currentNode.type === "Literal" && + typeof currentNode.value === "string" + ) { + /* + * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted + * as a template placeholder. However, if the code already contains a backslash before the ${ or ` + * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause + * an actual backslash character to appear before the dollar sign). + */ + return `\`${currentNode.raw + .slice(1, -1) + .replace(/\\*(\$\{|`)/gu, matched => { + if (matched.lastIndexOf("\\") % 2) { + return `\\${matched}`; + } + return matched; + + // Unescape any quotes that appear in the original Literal that no longer need to be escaped. + }) + .replace( + new RegExp(`\\\\${currentNode.raw[0]}`, "gu"), + currentNode.raw[0], + )}\``; + } + + if (currentNode.type === "TemplateLiteral") { + return sourceCode.getText(currentNode); + } + + if (isConcatenation(currentNode) && hasStringLiteral(currentNode)) { + const plusSign = sourceCode.getFirstTokenBetween( + currentNode.left, + currentNode.right, + token => token.value === "+", + ); + const textBeforePlus = getTextBetween( + currentNode.left, + plusSign, + ); + const textAfterPlus = getTextBetween( + plusSign, + currentNode.right, + ); + const leftEndsWithCurly = endsWithTemplateCurly( + currentNode.left, + ); + const rightStartsWithCurly = startsWithTemplateCurly( + currentNode.right, + ); + + if (leftEndsWithCurly) { + // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket. + // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}` + return ( + getTemplateLiteral( + currentNode.left, + textBeforeNode, + textBeforePlus + textAfterPlus, + ).slice(0, -1) + + getTemplateLiteral( + currentNode.right, + null, + textAfterNode, + ).slice(1) + ); + } + if (rightStartsWithCurly) { + // Otherwise, if the right side of the expression starts with a template curly, add the text there. + // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz` + return ( + getTemplateLiteral( + currentNode.left, + textBeforeNode, + null, + ).slice(0, -1) + + getTemplateLiteral( + currentNode.right, + textBeforePlus + textAfterPlus, + textAfterNode, + ).slice(1) + ); + } + + /* + * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put + * the text between them. + */ + return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`; + } + + return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``; + } + + /** + * Returns a fixer object that converts a non-string binary expression to a template literal + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A node that should be converted to a template literal + * @returns {Object} A fix for this binary expression + */ + function fixNonStringBinaryExpression(fixer, node) { + const topBinaryExpr = getTopConcatBinaryExpression(node.parent); + + if (hasOctalOrNonOctalDecimalEscapeSequence(topBinaryExpr)) { + return null; + } + + return fixer.replaceText( + topBinaryExpr, + getTemplateLiteral(topBinaryExpr, null, null), + ); + } + + /** + * Reports if a given node is string concatenation with non string literals. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function checkForStringConcat(node) { + if ( + !astUtils.isStringLiteral(node) || + !isConcatenation(node.parent) + ) { + return; + } + + const topBinaryExpr = getTopConcatBinaryExpression(node.parent); + + // Checks whether or not this node had been checked already. + if (done[topBinaryExpr.range[0]]) { + return; + } + done[topBinaryExpr.range[0]] = true; + + if (hasNonStringLiteral(topBinaryExpr)) { + context.report({ + node: topBinaryExpr, + messageId: "unexpectedStringConcatenation", + fix: fixer => fixNonStringBinaryExpression(fixer, node), + }); + } + } + + return { + Program() { + done = Object.create(null); + }, + + Literal: checkForStringConcat, + TemplateLiteral: checkForStringConcat, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/quote-props.js b/node_modules/eslint/lib/rules/quote-props.js new file mode 100644 index 00000000..fc03cbf0 --- /dev/null +++ b/node_modules/eslint/lib/rules/quote-props.js @@ -0,0 +1,394 @@ +/** + * @fileoverview Rule to flag non-quoted property names in object literals. + * @author Mathias Bynens + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const espree = require("espree"); +const astUtils = require("./utils/ast-utils"); +const keywords = require("./utils/keywords"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "quote-props", + url: "https://eslint.style/rules/js/quote-props", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: "Require quotes around object literal property names", + recommended: false, + url: "https://eslint.org/docs/latest/rules/quote-props", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: [ + "always", + "as-needed", + "consistent", + "consistent-as-needed", + ], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: [ + "always", + "as-needed", + "consistent", + "consistent-as-needed", + ], + }, + { + type: "object", + properties: { + keywords: { + type: "boolean", + }, + unnecessary: { + type: "boolean", + }, + numbers: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + fixable: "code", + messages: { + requireQuotesDueToReservedWord: + "Properties should be quoted as '{{property}}' is a reserved word.", + inconsistentlyQuotedProperty: + "Inconsistently quoted property '{{key}}' found.", + unnecessarilyQuotedProperty: + "Unnecessarily quoted property '{{property}}' found.", + unquotedReservedProperty: + "Unquoted reserved word '{{property}}' used as key.", + unquotedNumericProperty: + "Unquoted number literal '{{property}}' used as key.", + unquotedPropertyFound: "Unquoted property '{{property}}' found.", + redundantQuoting: + "Properties shouldn't be quoted as all quotes are redundant.", + }, + }, + + create(context) { + const MODE = context.options[0], + KEYWORDS = context.options[1] && context.options[1].keywords, + CHECK_UNNECESSARY = + !context.options[1] || context.options[1].unnecessary !== false, + NUMBERS = context.options[1] && context.options[1].numbers, + sourceCode = context.sourceCode; + + /** + * Checks whether a certain string constitutes an ES3 token + * @param {string} tokenStr The string to be checked. + * @returns {boolean} `true` if it is an ES3 token. + */ + function isKeyword(tokenStr) { + return keywords.includes(tokenStr); + } + + /** + * Checks if an espree-tokenized key has redundant quotes (i.e. whether quotes are unnecessary) + * @param {string} rawKey The raw key value from the source + * @param {espreeTokens} tokens The espree-tokenized node key + * @param {boolean} [skipNumberLiterals=false] Indicates whether number literals should be checked + * @returns {boolean} Whether or not a key has redundant quotes. + * @private + */ + function areQuotesRedundant(rawKey, tokens, skipNumberLiterals) { + return ( + tokens.length === 1 && + tokens[0].start === 0 && + tokens[0].end === rawKey.length && + (["Identifier", "Keyword", "Null", "Boolean"].includes( + tokens[0].type, + ) || + (tokens[0].type === "Numeric" && + !skipNumberLiterals && + String(+tokens[0].value) === tokens[0].value)) + ); + } + + /** + * Returns a string representation of a property node with quotes removed + * @param {ASTNode} key Key AST Node, which may or may not be quoted + * @returns {string} A replacement string for this property + */ + function getUnquotedKey(key) { + return key.type === "Identifier" ? key.name : key.value; + } + + /** + * Returns a string representation of a property node with quotes added + * @param {ASTNode} key Key AST Node, which may or may not be quoted + * @returns {string} A replacement string for this property + */ + function getQuotedKey(key) { + if (key.type === "Literal" && typeof key.value === "string") { + // If the key is already a string literal, don't replace the quotes with double quotes. + return sourceCode.getText(key); + } + + // Otherwise, the key is either an identifier or a number literal. + return `"${key.type === "Identifier" ? key.name : key.value}"`; + } + + /** + * Ensures that a property's key is quoted only when necessary + * @param {ASTNode} node Property AST node + * @returns {void} + */ + function checkUnnecessaryQuotes(node) { + const key = node.key; + + if (node.method || node.computed || node.shorthand) { + return; + } + + if (key.type === "Literal" && typeof key.value === "string") { + let tokens; + + try { + tokens = espree.tokenize(key.value); + } catch { + return; + } + + if (tokens.length !== 1) { + return; + } + + const isKeywordToken = isKeyword(tokens[0].value); + + if (isKeywordToken && KEYWORDS) { + return; + } + + if ( + CHECK_UNNECESSARY && + areQuotesRedundant(key.value, tokens, NUMBERS) + ) { + context.report({ + node, + messageId: "unnecessarilyQuotedProperty", + data: { property: key.value }, + fix: fixer => + fixer.replaceText(key, getUnquotedKey(key)), + }); + } + } else if ( + KEYWORDS && + key.type === "Identifier" && + isKeyword(key.name) + ) { + context.report({ + node, + messageId: "unquotedReservedProperty", + data: { property: key.name }, + fix: fixer => fixer.replaceText(key, getQuotedKey(key)), + }); + } else if ( + NUMBERS && + key.type === "Literal" && + astUtils.isNumericLiteral(key) + ) { + context.report({ + node, + messageId: "unquotedNumericProperty", + data: { property: key.value }, + fix: fixer => fixer.replaceText(key, getQuotedKey(key)), + }); + } + } + + /** + * Ensures that a property's key is quoted + * @param {ASTNode} node Property AST node + * @returns {void} + */ + function checkOmittedQuotes(node) { + const key = node.key; + + if ( + !node.method && + !node.computed && + !node.shorthand && + !(key.type === "Literal" && typeof key.value === "string") + ) { + context.report({ + node, + messageId: "unquotedPropertyFound", + data: { property: key.name || key.value }, + fix: fixer => fixer.replaceText(key, getQuotedKey(key)), + }); + } + } + + /** + * Ensures that an object's keys are consistently quoted, optionally checks for redundancy of quotes + * @param {ASTNode} node Property AST node + * @param {boolean} checkQuotesRedundancy Whether to check quotes' redundancy + * @returns {void} + */ + function checkConsistency(node, checkQuotesRedundancy) { + const quotedProps = [], + unquotedProps = []; + let keywordKeyName = null, + necessaryQuotes = false; + + node.properties.forEach(property => { + const key = property.key; + + if ( + !key || + property.method || + property.computed || + property.shorthand + ) { + return; + } + + if (key.type === "Literal" && typeof key.value === "string") { + quotedProps.push(property); + + if (checkQuotesRedundancy) { + let tokens; + + try { + tokens = espree.tokenize(key.value); + } catch { + necessaryQuotes = true; + return; + } + + necessaryQuotes = + necessaryQuotes || + !areQuotesRedundant(key.value, tokens) || + (KEYWORDS && isKeyword(tokens[0].value)); + } + } else if ( + KEYWORDS && + checkQuotesRedundancy && + key.type === "Identifier" && + isKeyword(key.name) + ) { + unquotedProps.push(property); + necessaryQuotes = true; + keywordKeyName = key.name; + } else { + unquotedProps.push(property); + } + }); + + if ( + checkQuotesRedundancy && + quotedProps.length && + !necessaryQuotes + ) { + quotedProps.forEach(property => { + context.report({ + node: property, + messageId: "redundantQuoting", + fix: fixer => + fixer.replaceText( + property.key, + getUnquotedKey(property.key), + ), + }); + }); + } else if (unquotedProps.length && keywordKeyName) { + unquotedProps.forEach(property => { + context.report({ + node: property, + messageId: "requireQuotesDueToReservedWord", + data: { property: keywordKeyName }, + fix: fixer => + fixer.replaceText( + property.key, + getQuotedKey(property.key), + ), + }); + }); + } else if (quotedProps.length && unquotedProps.length) { + unquotedProps.forEach(property => { + context.report({ + node: property, + messageId: "inconsistentlyQuotedProperty", + data: { key: property.key.name || property.key.value }, + fix: fixer => + fixer.replaceText( + property.key, + getQuotedKey(property.key), + ), + }); + }); + } + } + + return { + Property(node) { + if (MODE === "always" || !MODE) { + checkOmittedQuotes(node); + } + if (MODE === "as-needed") { + checkUnnecessaryQuotes(node); + } + }, + ObjectExpression(node) { + if (MODE === "consistent") { + checkConsistency(node, false); + } + if (MODE === "consistent-as-needed") { + checkConsistency(node, true); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/quotes.js b/node_modules/eslint/lib/rules/quotes.js new file mode 100644 index 00000000..fcf73c23 --- /dev/null +++ b/node_modules/eslint/lib/rules/quotes.js @@ -0,0 +1,416 @@ +/** + * @fileoverview A rule to choose between single and double quote marks + * @author Matt DuVall , Brandon Payton + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const QUOTE_SETTINGS = { + double: { + quote: '"', + alternateQuote: "'", + description: "doublequote", + }, + single: { + quote: "'", + alternateQuote: '"', + description: "singlequote", + }, + backtick: { + quote: "`", + alternateQuote: '"', + description: "backtick", + }, +}; + +// An unescaped newline is a newline preceded by an even number of backslashes. +const UNESCAPED_LINEBREAK_PATTERN = new RegExp( + String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`, + "u", +); + +/** + * Switches quoting of javascript string between ' " and ` + * escaping and unescaping as necessary. + * Only escaping of the minimal set of characters is changed. + * Note: escaping of newlines when switching from backtick to other quotes is not handled. + * @param {string} str A string to convert. + * @returns {string} The string with changed quotes. + * @private + */ +QUOTE_SETTINGS.double.convert = + QUOTE_SETTINGS.single.convert = + QUOTE_SETTINGS.backtick.convert = + function (str) { + const newQuote = this.quote; + const oldQuote = str[0]; + + if (newQuote === oldQuote) { + return str; + } + return ( + newQuote + + str + .slice(1, -1) + .replace( + /\\(\$\{|\r\n?|\n|.)|["'`]|\$\{|(\r\n?|\n)/gu, + (match, escaped, newline) => { + if ( + escaped === oldQuote || + (oldQuote === "`" && escaped === "${") + ) { + return escaped; // unescape + } + if ( + match === newQuote || + (newQuote === "`" && match === "${") + ) { + return `\\${match}`; // escape + } + if (newline && oldQuote === "`") { + return "\\n"; // escape newlines + } + return match; + }, + ) + + newQuote + ); + }; + +const AVOID_ESCAPE = "avoid-escape"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "quotes", + url: "https://eslint.style/rules/js/quotes", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce the consistent use of either backticks, double, or single quotes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/quotes", + }, + + fixable: "code", + + schema: [ + { + enum: ["single", "double", "backtick"], + }, + { + anyOf: [ + { + enum: ["avoid-escape"], + }, + { + type: "object", + properties: { + avoidEscape: { + type: "boolean", + }, + allowTemplateLiterals: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + wrongQuotes: "Strings must use {{description}}.", + }, + }, + + create(context) { + const quoteOption = context.options[0], + settings = QUOTE_SETTINGS[quoteOption || "double"], + options = context.options[1], + allowTemplateLiterals = + options && options.allowTemplateLiterals === true, + sourceCode = context.sourceCode; + let avoidEscape = options && options.avoidEscape === true; + + // deprecated + if (options === AVOID_ESCAPE) { + avoidEscape = true; + } + + /** + * Determines if a given node is part of JSX syntax. + * + * This function returns `true` in the following cases: + * + * - `
` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`. + * - `
foo
` ... If the literal is a text content, the parent of the literal is `JSXElement`. + * - `<>foo` ... If the literal is a text content, the parent of the literal is `JSXFragment`. + * + * In particular, this function returns `false` in the following cases: + * + * - `
` + * - `
{"foo"}
` + * + * In both cases, inside of the braces is handled as normal JavaScript. + * The braces are `JSXExpressionContainer` nodes. + * @param {ASTNode} node The Literal node to check. + * @returns {boolean} True if the node is a part of JSX, false if not. + * @private + */ + function isJSXLiteral(node) { + return ( + node.parent.type === "JSXAttribute" || + node.parent.type === "JSXElement" || + node.parent.type === "JSXFragment" + ); + } + + /** + * Checks whether or not a given node is a directive. + * The directive is a `ExpressionStatement` which has only a string literal not surrounded by + * parentheses. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a directive. + * @private + */ + function isDirective(node) { + return ( + node.type === "ExpressionStatement" && + node.expression.type === "Literal" && + typeof node.expression.value === "string" && + !astUtils.isParenthesised(sourceCode, node.expression) + ); + } + + /** + * Checks whether a specified node is either part of, or immediately follows a (possibly empty) directive prologue. + * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive} + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether a specified node is either part of, or immediately follows a (possibly empty) directive prologue. + * @private + */ + function isExpressionInOrJustAfterDirectivePrologue(node) { + if (!astUtils.isTopLevelExpressionStatement(node.parent)) { + return false; + } + const block = node.parent.parent; + + // Check the node is at a prologue. + for (let i = 0; i < block.body.length; ++i) { + const statement = block.body[i]; + + if (statement === node.parent) { + return true; + } + if (!isDirective(statement)) { + break; + } + } + + return false; + } + + /** + * Checks whether or not a given node is allowed as non backtick. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is allowed as non backtick. + * @private + */ + function isAllowedAsNonBacktick(node) { + const parent = node.parent; + + switch (parent.type) { + // Directive Prologues. + case "ExpressionStatement": + return ( + !astUtils.isParenthesised(sourceCode, node) && + isExpressionInOrJustAfterDirectivePrologue(node) + ); + + // LiteralPropertyName. + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + return parent.key === node && !parent.computed; + + // ModuleSpecifier. + case "ImportDeclaration": + case "ExportNamedDeclaration": + return parent.source === node; + + // ModuleExportName or ModuleSpecifier. + case "ExportAllDeclaration": + return parent.exported === node || parent.source === node; + + // ModuleExportName. + case "ImportSpecifier": + return parent.imported === node; + + // ModuleExportName. + case "ExportSpecifier": + return parent.local === node || parent.exported === node; + + // Others don't allow. + default: + return false; + } + } + + /** + * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings. + * @param {ASTNode} node A TemplateLiteral node to check. + * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings. + * @private + */ + function isUsingFeatureOfTemplateLiteral(node) { + const hasTag = + node.parent.type === "TaggedTemplateExpression" && + node === node.parent.quasi; + + if (hasTag) { + return true; + } + + const hasStringInterpolation = node.expressions.length > 0; + + if (hasStringInterpolation) { + return true; + } + + const isMultilineString = + node.quasis.length >= 1 && + UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw); + + if (isMultilineString) { + return true; + } + + return false; + } + + return { + Literal(node) { + const val = node.value, + rawVal = node.raw; + + if (settings && typeof val === "string") { + let isValid = + (quoteOption === "backtick" && + isAllowedAsNonBacktick(node)) || + isJSXLiteral(node) || + astUtils.isSurroundedBy(rawVal, settings.quote); + + if (!isValid && avoidEscape) { + isValid = + astUtils.isSurroundedBy( + rawVal, + settings.alternateQuote, + ) && rawVal.includes(settings.quote); + } + + if (!isValid) { + context.report({ + node, + messageId: "wrongQuotes", + data: { + description: settings.description, + }, + fix(fixer) { + if ( + quoteOption === "backtick" && + astUtils.hasOctalOrNonOctalDecimalEscapeSequence( + rawVal, + ) + ) { + /* + * An octal or non-octal decimal escape sequence in a template literal would + * produce syntax error, even in non-strict mode. + */ + return null; + } + + return fixer.replaceText( + node, + settings.convert(node.raw), + ); + }, + }); + } + } + }, + + TemplateLiteral(node) { + // Don't throw an error if backticks are expected or a template literal feature is in use. + if ( + allowTemplateLiterals || + quoteOption === "backtick" || + isUsingFeatureOfTemplateLiteral(node) + ) { + return; + } + + context.report({ + node, + messageId: "wrongQuotes", + data: { + description: settings.description, + }, + fix(fixer) { + if ( + astUtils.isTopLevelExpressionStatement( + node.parent, + ) && + !astUtils.isParenthesised(sourceCode, node) + ) { + /* + * TemplateLiterals aren't actually directives, but fixing them might turn + * them into directives and change the behavior of the code. + */ + return null; + } + return fixer.replaceText( + node, + settings.convert(sourceCode.getText(node)), + ); + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/radix.js b/node_modules/eslint/lib/rules/radix.js new file mode 100644 index 00000000..b342636c --- /dev/null +++ b/node_modules/eslint/lib/rules/radix.js @@ -0,0 +1,216 @@ +/** + * @fileoverview Rule to flag use of parseInt without a radix argument + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const MODE_ALWAYS = "always", + MODE_AS_NEEDED = "as-needed"; + +const validRadixValues = new Set( + Array.from({ length: 37 - 2 }, (_, index) => index + 2), +); + +/** + * Checks whether a given variable is shadowed or not. + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is shadowed. + */ +function isShadowed(variable) { + return variable.defs.length >= 1; +} + +/** + * Checks whether a given node is a MemberExpression of `parseInt` method or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a MemberExpression of `parseInt` + * method. + */ +function isParseIntMethod(node) { + return ( + node.type === "MemberExpression" && + !node.computed && + node.property.type === "Identifier" && + node.property.name === "parseInt" + ); +} + +/** + * Checks whether a given node is a valid value of radix or not. + * + * The following values are invalid. + * + * - A literal except integers between 2 and 36. + * - undefined. + * @param {ASTNode} radix A node of radix to check. + * @returns {boolean} `true` if the node is valid. + */ +function isValidRadix(radix) { + return !( + (radix.type === "Literal" && !validRadixValues.has(radix.value)) || + (radix.type === "Identifier" && radix.name === "undefined") + ); +} + +/** + * Checks whether a given node is a default value of radix or not. + * @param {ASTNode} radix A node of radix to check. + * @returns {boolean} `true` if the node is the literal node of `10`. + */ +function isDefaultRadix(radix) { + return radix.type === "Literal" && radix.value === 10; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [MODE_ALWAYS], + + docs: { + description: + "Enforce the consistent use of the radix argument when using `parseInt()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/radix", + }, + + hasSuggestions: true, + + schema: [ + { + enum: ["always", "as-needed"], + }, + ], + + messages: { + missingParameters: "Missing parameters.", + redundantRadix: "Redundant radix parameter.", + missingRadix: "Missing radix parameter.", + invalidRadix: + "Invalid radix parameter, must be an integer between 2 and 36.", + addRadixParameter10: + "Add radix parameter `10` for parsing decimal numbers.", + }, + }, + + create(context) { + const [mode] = context.options; + const sourceCode = context.sourceCode; + + /** + * Checks the arguments of a given CallExpression node and reports it if it + * offends this rule. + * @param {ASTNode} node A CallExpression node to check. + * @returns {void} + */ + function checkArguments(node) { + const args = node.arguments; + + switch (args.length) { + case 0: + context.report({ + node, + messageId: "missingParameters", + }); + break; + + case 1: + if (mode === MODE_ALWAYS) { + context.report({ + node, + messageId: "missingRadix", + suggest: [ + { + messageId: "addRadixParameter10", + fix(fixer) { + const tokens = + sourceCode.getTokens(node); + const lastToken = tokens.at(-1); // Parenthesis. + const secondToLastToken = tokens.at(-2); // May or may not be a comma. + const hasTrailingComma = + secondToLastToken.type === + "Punctuator" && + secondToLastToken.value === ","; + + return fixer.insertTextBefore( + lastToken, + hasTrailingComma ? " 10," : ", 10", + ); + }, + }, + ], + }); + } + break; + + default: + if (mode === MODE_AS_NEEDED && isDefaultRadix(args[1])) { + context.report({ + node, + messageId: "redundantRadix", + }); + } else if (!isValidRadix(args[1])) { + context.report({ + node, + messageId: "invalidRadix", + }); + } + break; + } + } + + return { + "Program:exit"(node) { + const scope = sourceCode.getScope(node); + let variable; + + // Check `parseInt()` + variable = astUtils.getVariableByName(scope, "parseInt"); + if (variable && !isShadowed(variable)) { + variable.references.forEach(reference => { + const idNode = reference.identifier; + + if (astUtils.isCallee(idNode)) { + checkArguments(idNode.parent); + } + }); + } + + // Check `Number.parseInt()` + variable = astUtils.getVariableByName(scope, "Number"); + if (variable && !isShadowed(variable)) { + variable.references.forEach(reference => { + const parentNode = reference.identifier.parent; + const maybeCallee = + parentNode.parent.type === "ChainExpression" + ? parentNode.parent + : parentNode; + + if ( + isParseIntMethod(parentNode) && + astUtils.isCallee(maybeCallee) + ) { + checkArguments(maybeCallee.parent); + } + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/require-atomic-updates.js b/node_modules/eslint/lib/rules/require-atomic-updates.js new file mode 100644 index 00000000..c3935cca --- /dev/null +++ b/node_modules/eslint/lib/rules/require-atomic-updates.js @@ -0,0 +1,365 @@ +/** + * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield` + * @author Teddy Katz + * @author Toru Nagashima + */ +"use strict"; + +/** + * Make the map from identifiers to each reference. + * @param {escope.Scope} scope The scope to get references. + * @param {Map} [outReferenceMap] The map from identifier nodes to each reference object. + * @returns {Map} `referenceMap`. + */ +function createReferenceMap(scope, outReferenceMap = new Map()) { + for (const reference of scope.references) { + if (reference.resolved === null) { + continue; + } + + outReferenceMap.set(reference.identifier, reference); + } + for (const childScope of scope.childScopes) { + if (childScope.type !== "function") { + createReferenceMap(childScope, outReferenceMap); + } + } + + return outReferenceMap; +} + +/** + * Get `reference.writeExpr` of a given reference. + * If it's the read reference of MemberExpression in LHS, returns RHS in order to address `a.b = await a` + * @param {escope.Reference} reference The reference to get. + * @returns {Expression|null} The `reference.writeExpr`. + */ +function getWriteExpr(reference) { + if (reference.writeExpr) { + return reference.writeExpr; + } + let node = reference.identifier; + + while (node) { + const t = node.parent.type; + + if (t === "AssignmentExpression" && node.parent.left === node) { + return node.parent.right; + } + if (t === "MemberExpression" && node.parent.object === node) { + node = node.parent; + continue; + } + + break; + } + + return null; +} + +/** + * Checks if an expression is a variable that can only be observed within the given function. + * @param {Variable|null} variable The variable to check + * @param {boolean} isMemberAccess If `true` then this is a member access. + * @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure. + */ +function isLocalVariableWithoutEscape(variable, isMemberAccess) { + if (!variable) { + return false; // A global variable which was not defined. + } + + // If the reference is a property access and the variable is a parameter, it handles the variable is not local. + if (isMemberAccess && variable.defs.some(d => d.type === "Parameter")) { + return false; + } + + const functionScope = variable.scope.variableScope; + + return variable.references.every( + reference => reference.from.variableScope === functionScope, + ); +} + +/** + * Represents segment information. + */ +class SegmentInfo { + constructor() { + this.info = new WeakMap(); + } + + /** + * Initialize the segment information. + * @param {PathSegment} segment The segment to initialize. + * @returns {void} + */ + initialize(segment) { + const outdatedReadVariables = new Set(); + const freshReadVariables = new Set(); + + for (const prevSegment of segment.prevSegments) { + const info = this.info.get(prevSegment); + + if (info) { + info.outdatedReadVariables.forEach( + Set.prototype.add, + outdatedReadVariables, + ); + info.freshReadVariables.forEach( + Set.prototype.add, + freshReadVariables, + ); + } + } + + this.info.set(segment, { outdatedReadVariables, freshReadVariables }); + } + + /** + * Mark a given variable as read on given segments. + * @param {PathSegment[]} segments The segments that it read the variable on. + * @param {Variable} variable The variable to be read. + * @returns {void} + */ + markAsRead(segments, variable) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info) { + info.freshReadVariables.add(variable); + + // If a variable is freshly read again, then it's no more out-dated. + info.outdatedReadVariables.delete(variable); + } + } + } + + /** + * Move `freshReadVariables` to `outdatedReadVariables`. + * @param {PathSegment[]} segments The segments to process. + * @returns {void} + */ + makeOutdated(segments) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info) { + info.freshReadVariables.forEach( + Set.prototype.add, + info.outdatedReadVariables, + ); + info.freshReadVariables.clear(); + } + } + } + + /** + * Check if a given variable is outdated on the current segments. + * @param {PathSegment[]} segments The current segments. + * @param {Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is outdated on the segments. + */ + isOutdated(segments, variable) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info && info.outdatedReadVariables.has(variable)) { + return true; + } + } + return false; + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowProperties: false, + }, + ], + + docs: { + description: + "Disallow assignments that can lead to race conditions due to usage of `await` or `yield`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-atomic-updates", + }, + + fixable: null, + + schema: [ + { + type: "object", + properties: { + allowProperties: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + nonAtomicUpdate: + "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`.", + nonAtomicObjectUpdate: + "Possible race condition: `{{value}}` might be assigned based on an outdated state of `{{object}}`.", + }, + }, + + create(context) { + const [{ allowProperties }] = context.options; + + const sourceCode = context.sourceCode; + const assignmentReferences = new Map(); + const segmentInfo = new SegmentInfo(); + let stack = null; + + return { + onCodePathStart(codePath, node) { + const scope = sourceCode.getScope(node); + const shouldVerify = + scope.type === "function" && + (scope.block.async || scope.block.generator); + + stack = { + upper: stack, + codePath, + referenceMap: shouldVerify + ? createReferenceMap(scope) + : null, + currentSegments: new Set(), + }; + }, + onCodePathEnd() { + stack = stack.upper; + }, + + // Initialize the segment information. + onCodePathSegmentStart(segment) { + segmentInfo.initialize(segment); + stack.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentStart(segment) { + stack.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + stack.currentSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + stack.currentSegments.delete(segment); + }, + + // Handle references to prepare verification. + Identifier(node) { + const { referenceMap } = stack; + const reference = referenceMap && referenceMap.get(node); + + // Ignore if this is not a valid variable reference. + if (!reference) { + return; + } + const variable = reference.resolved; + const writeExpr = getWriteExpr(reference); + const isMemberAccess = + reference.identifier.parent.type === "MemberExpression"; + + // Add a fresh read variable. + if ( + reference.isRead() && + !(writeExpr && writeExpr.parent.operator === "=") + ) { + segmentInfo.markAsRead(stack.currentSegments, variable); + } + + /* + * Register the variable to verify after ESLint traversed the `writeExpr` node + * if this reference is an assignment to a variable which is referred from other closure. + */ + if ( + writeExpr && + writeExpr.parent.right === writeExpr && // ← exclude variable declarations. + !isLocalVariableWithoutEscape(variable, isMemberAccess) + ) { + let refs = assignmentReferences.get(writeExpr); + + if (!refs) { + refs = []; + assignmentReferences.set(writeExpr, refs); + } + + refs.push(reference); + } + }, + + /* + * Verify assignments. + * If the reference exists in `outdatedReadVariables` list, report it. + */ + ":expression:exit"(node) { + // referenceMap exists if this is in a resumable function scope. + if (!stack.referenceMap) { + return; + } + + // Mark the read variables on this code path as outdated. + if ( + node.type === "AwaitExpression" || + node.type === "YieldExpression" + ) { + segmentInfo.makeOutdated(stack.currentSegments); + } + + // Verify. + const references = assignmentReferences.get(node); + + if (references) { + assignmentReferences.delete(node); + + for (const reference of references) { + const variable = reference.resolved; + + if ( + segmentInfo.isOutdated( + stack.currentSegments, + variable, + ) + ) { + if (node.parent.left === reference.identifier) { + context.report({ + node: node.parent, + messageId: "nonAtomicUpdate", + data: { + value: variable.name, + }, + }); + } else if (!allowProperties) { + context.report({ + node: node.parent, + messageId: "nonAtomicObjectUpdate", + data: { + value: sourceCode.getText( + node.parent.left, + ), + object: variable.name, + }, + }); + } + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/require-await.js b/node_modules/eslint/lib/rules/require-await.js new file mode 100644 index 00000000..2663e78e --- /dev/null +++ b/node_modules/eslint/lib/rules/require-await.js @@ -0,0 +1,175 @@ +/** + * @fileoverview Rule to disallow async functions which have no `await` expression. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Capitalize the 1st letter of the given text. + * @param {string} text The text to capitalize. + * @returns {string} The text that the 1st letter was capitalized. + */ +function capitalizeFirstLetter(text) { + return text[0].toUpperCase() + text.slice(1); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow async functions which have no `await` expression", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-await", + }, + + schema: [], + + messages: { + missingAwait: "{{name}} has no 'await' expression.", + removeAsync: "Remove 'async'.", + }, + + hasSuggestions: true, + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Push the scope info object to the stack. + * @returns {void} + */ + function enterFunction() { + scopeInfo = { + upper: scopeInfo, + hasAwait: false, + }; + } + + /** + * Pop the top scope info object from the stack. + * Also, it reports the function if needed. + * @param {ASTNode} node The node to report. + * @returns {void} + */ + function exitFunction(node) { + if ( + !node.generator && + node.async && + !scopeInfo.hasAwait && + !astUtils.isEmptyFunction(node) + ) { + /* + * If the function belongs to a method definition or + * property, then the function's range may not include the + * `async` keyword and we should look at the parent instead. + */ + const nodeWithAsyncKeyword = + (node.parent.type === "MethodDefinition" && + node.parent.value === node) || + (node.parent.type === "Property" && + node.parent.method && + node.parent.value === node) + ? node.parent + : node; + + const asyncToken = sourceCode.getFirstToken( + nodeWithAsyncKeyword, + token => token.value === "async", + ); + const asyncRange = [ + asyncToken.range[0], + sourceCode.getTokenAfter(asyncToken, { + includeComments: true, + }).range[0], + ]; + + /* + * Removing the `async` keyword can cause parsing errors if the current + * statement is relying on automatic semicolon insertion. If ASI is currently + * being used, then we should replace the `async` keyword with a semicolon. + */ + const nextToken = sourceCode.getTokenAfter(asyncToken); + const addSemiColon = + nextToken.type === "Punctuator" && + (nextToken.value === "[" || nextToken.value === "(") && + (nodeWithAsyncKeyword.type === "MethodDefinition" || + astUtils.isStartOfExpressionStatement( + nodeWithAsyncKeyword, + )) && + astUtils.needsPrecedingSemicolon( + sourceCode, + nodeWithAsyncKeyword, + ); + + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId: "missingAwait", + data: { + name: capitalizeFirstLetter( + astUtils.getFunctionNameWithKind(node), + ), + }, + suggest: [ + { + messageId: "removeAsync", + fix: fixer => + fixer.replaceTextRange( + asyncRange, + addSemiColon ? ";" : "", + ), + }, + ], + }); + } + + scopeInfo = scopeInfo.upper; + } + + return { + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression: enterFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + "ArrowFunctionExpression:exit": exitFunction, + + AwaitExpression() { + if (!scopeInfo) { + return; + } + + scopeInfo.hasAwait = true; + }, + ForOfStatement(node) { + if (!scopeInfo) { + return; + } + + if (node.await) { + scopeInfo.hasAwait = true; + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/require-unicode-regexp.js b/node_modules/eslint/lib/rules/require-unicode-regexp.js new file mode 100644 index 00000000..8d5ca102 --- /dev/null +++ b/node_modules/eslint/lib/rules/require-unicode-regexp.js @@ -0,0 +1,315 @@ +/** + * @fileoverview Rule to enforce the use of `u` or `v` flag on regular expressions. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStringIfConstant, +} = require("@eslint-community/eslint-utils"); +const astUtils = require("./utils/ast-utils.js"); +const { isValidWithUnicodeFlag } = require("./utils/regular-expressions"); + +/** + * Checks whether the flag configuration should be treated as a missing flag. + * @param {"u"|"v"|undefined} requireFlag A particular flag to require + * @param {string} flags The regex flags + * @returns {boolean} Whether the flag configuration results in a missing flag. + */ +function checkFlags(requireFlag, flags) { + let missingFlag; + + if (requireFlag === "v") { + missingFlag = !flags.includes("v"); + } else if (requireFlag === "u") { + missingFlag = !flags.includes("u"); + } else { + missingFlag = !flags.includes("u") && !flags.includes("v"); + } + + return missingFlag; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce the use of `u` or `v` flag on regular expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-unicode-regexp", + }, + + hasSuggestions: true, + + messages: { + addUFlag: "Add the 'u' flag.", + addVFlag: "Add the 'v' flag.", + requireUFlag: "Use the 'u' flag.", + requireVFlag: "Use the 'v' flag.", + }, + + schema: [ + { + type: "object", + properties: { + requireFlag: { + enum: ["u", "v"], + }, + }, + additionalProperties: false, + }, + ], + }, + + create(context) { + const sourceCode = context.sourceCode; + + const { requireFlag } = context.options[0] ?? {}; + + return { + "Literal[regex]"(node) { + const flags = node.regex.flags || ""; + + const missingFlag = checkFlags(requireFlag, flags); + + if (missingFlag) { + context.report({ + messageId: + requireFlag === "v" + ? "requireVFlag" + : "requireUFlag", + node, + suggest: isValidWithUnicodeFlag( + context.languageOptions.ecmaVersion, + node.regex.pattern, + requireFlag, + ) + ? [ + { + fix(fixer) { + const replaceFlag = + requireFlag ?? "u"; + const regex = + sourceCode.getText(node); + const slashPos = + regex.lastIndexOf("/"); + + if (requireFlag) { + const flag = + requireFlag === "u" + ? "v" + : "u"; + + if ( + regex.includes( + flag, + slashPos, + ) + ) { + return fixer.replaceText( + node, + regex.slice( + 0, + slashPos, + ) + + regex + .slice(slashPos) + .replace( + flag, + requireFlag, + ), + ); + } + } + + return fixer.insertTextAfter( + node, + replaceFlag, + ); + }, + messageId: + requireFlag === "v" + ? "addVFlag" + : "addUFlag", + }, + ] + : null, + }); + } + }, + + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const trackMap = { + RegExp: { [CALL]: true, [CONSTRUCT]: true }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + trackMap, + )) { + const [patternNode, flagsNode] = refNode.arguments; + + if (patternNode && patternNode.type === "SpreadElement") { + continue; + } + const pattern = getStringIfConstant(patternNode, scope); + const flags = getStringIfConstant(flagsNode, scope); + + let missingFlag = !flagsNode; + + if (typeof flags === "string") { + missingFlag = checkFlags(requireFlag, flags); + } + + if (missingFlag) { + context.report({ + messageId: + requireFlag === "v" + ? "requireVFlag" + : "requireUFlag", + node: refNode, + suggest: + typeof pattern === "string" && + isValidWithUnicodeFlag( + context.languageOptions.ecmaVersion, + pattern, + requireFlag, + ) + ? [ + { + fix(fixer) { + const replaceFlag = + requireFlag ?? "u"; + + if (flagsNode) { + if ( + (flagsNode.type === + "Literal" && + typeof flagsNode.value === + "string") || + flagsNode.type === + "TemplateLiteral" + ) { + const flagsNodeText = + sourceCode.getText( + flagsNode, + ); + const flag = + requireFlag === + "u" + ? "v" + : "u"; + + if ( + flags.includes( + flag, + ) + ) { + // Avoid replacing "u" in escapes like `\uXXXX` + if ( + flagsNode.type === + "Literal" && + flagsNode.raw.includes( + "\\", + ) + ) { + return null; + } + + // Avoid replacing "u" in expressions like "`${regularFlags}g`" + if ( + flagsNode.type === + "TemplateLiteral" && + (flagsNode + .expressions + .length || + flagsNode.quasis.some( + ({ + value: { + raw, + }, + }) => + raw.includes( + "\\", + ), + )) + ) { + return null; + } + + return fixer.replaceText( + flagsNode, + flagsNodeText.replace( + flag, + replaceFlag, + ), + ); + } + + return fixer.replaceText( + flagsNode, + [ + flagsNodeText.slice( + 0, + flagsNodeText.length - + 1, + ), + flagsNodeText.slice( + flagsNodeText.length - + 1, + ), + ].join( + replaceFlag, + ), + ); + } + + // We intentionally don't suggest concatenating + "u" to non-literals + return null; + } + + const penultimateToken = + sourceCode.getLastToken( + refNode, + { skip: 1 }, + ); // skip closing parenthesis + + return fixer.insertTextAfter( + penultimateToken, + astUtils.isCommaToken( + penultimateToken, + ) + ? ` "${replaceFlag}",` + : `, "${replaceFlag}"`, + ); + }, + messageId: + requireFlag === "v" + ? "addVFlag" + : "addUFlag", + }, + ] + : null, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/require-yield.js b/node_modules/eslint/lib/rules/require-yield.js new file mode 100644 index 00000000..0cc8d20c --- /dev/null +++ b/node_modules/eslint/lib/rules/require-yield.js @@ -0,0 +1,76 @@ +/** + * @fileoverview Rule to flag the generator functions that does not have yield. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require generator functions to contain `yield`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/require-yield", + }, + + schema: [], + + messages: { + missingYield: "This generator function does not have 'yield'.", + }, + }, + + create(context) { + const stack = []; + + /** + * If the node is a generator function, start counting `yield` keywords. + * @param {Node} node A function node to check. + * @returns {void} + */ + function beginChecking(node) { + if (node.generator) { + stack.push(0); + } + } + + /** + * If the node is a generator function, end counting `yield` keywords, then + * reports result. + * @param {Node} node A function node to check. + * @returns {void} + */ + function endChecking(node) { + if (!node.generator) { + return; + } + + const countYield = stack.pop(); + + if (countYield === 0 && node.body.body.length > 0) { + context.report({ node, messageId: "missingYield" }); + } + } + + return { + FunctionDeclaration: beginChecking, + "FunctionDeclaration:exit": endChecking, + FunctionExpression: beginChecking, + "FunctionExpression:exit": endChecking, + + // Increases the count of `yield` keyword. + YieldExpression() { + if (stack.length > 0) { + stack[stack.length - 1] += 1; + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/rest-spread-spacing.js b/node_modules/eslint/lib/rules/rest-spread-spacing.js new file mode 100644 index 00000000..0e369019 --- /dev/null +++ b/node_modules/eslint/lib/rules/rest-spread-spacing.js @@ -0,0 +1,153 @@ +/** + * @fileoverview Enforce spacing between rest and spread operators and their expressions. + * @author Kai Cataldo + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "rest-spread-spacing", + url: "https://eslint.style/rules/js/rest-spread-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce spacing between rest and spread operators and their expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/rest-spread-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + ], + + messages: { + unexpectedWhitespace: + "Unexpected whitespace after {{type}} operator.", + expectedWhitespace: "Expected whitespace after {{type}} operator.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode, + alwaysSpace = context.options[0] === "always"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whitespace between rest/spread operators and their expressions + * @param {ASTNode} node The node to check + * @returns {void} + */ + function checkWhiteSpace(node) { + const operator = sourceCode.getFirstToken(node), + nextToken = sourceCode.getTokenAfter(operator), + hasWhitespace = sourceCode.isSpaceBetweenTokens( + operator, + nextToken, + ); + let type; + + switch (node.type) { + case "SpreadElement": + type = "spread"; + if (node.parent.type === "ObjectExpression") { + type += " property"; + } + break; + case "RestElement": + type = "rest"; + if (node.parent.type === "ObjectPattern") { + type += " property"; + } + break; + case "ExperimentalSpreadProperty": + type = "spread property"; + break; + case "ExperimentalRestProperty": + type = "rest property"; + break; + default: + return; + } + + if (alwaysSpace && !hasWhitespace) { + context.report({ + node, + loc: operator.loc, + messageId: "expectedWhitespace", + data: { + type, + }, + fix(fixer) { + return fixer.replaceTextRange( + [operator.range[1], nextToken.range[0]], + " ", + ); + }, + }); + } else if (!alwaysSpace && hasWhitespace) { + context.report({ + node, + loc: { + start: operator.loc.end, + end: nextToken.loc.start, + }, + messageId: "unexpectedWhitespace", + data: { + type, + }, + fix(fixer) { + return fixer.removeRange([ + operator.range[1], + nextToken.range[0], + ]); + }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + SpreadElement: checkWhiteSpace, + RestElement: checkWhiteSpace, + ExperimentalSpreadProperty: checkWhiteSpace, + ExperimentalRestProperty: checkWhiteSpace, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/semi-spacing.js b/node_modules/eslint/lib/rules/semi-spacing.js new file mode 100644 index 00000000..65b1a7b4 --- /dev/null +++ b/node_modules/eslint/lib/rules/semi-spacing.js @@ -0,0 +1,297 @@ +/** + * @fileoverview Validates spacing before and after semicolon + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "semi-spacing", + url: "https://eslint.style/rules/js/semi-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing before and after semicolons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/semi-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { + type: "boolean", + default: false, + }, + after: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedWhitespaceBefore: + "Unexpected whitespace before semicolon.", + unexpectedWhitespaceAfter: "Unexpected whitespace after semicolon.", + missingWhitespaceBefore: "Missing whitespace before semicolon.", + missingWhitespaceAfter: "Missing whitespace after semicolon.", + }, + }, + + create(context) { + const config = context.options[0], + sourceCode = context.sourceCode; + let requireSpaceBefore = false, + requireSpaceAfter = true; + + if (typeof config === "object") { + requireSpaceBefore = config.before; + requireSpaceAfter = config.after; + } + + /** + * Checks if a given token has leading whitespace. + * @param {Object} token The token to check. + * @returns {boolean} True if the given token has leading space, false if not. + */ + function hasLeadingSpace(token) { + const tokenBefore = sourceCode.getTokenBefore(token); + + return ( + tokenBefore && + astUtils.isTokenOnSameLine(tokenBefore, token) && + sourceCode.isSpaceBetweenTokens(tokenBefore, token) + ); + } + + /** + * Checks if a given token has trailing whitespace. + * @param {Object} token The token to check. + * @returns {boolean} True if the given token has trailing space, false if not. + */ + function hasTrailingSpace(token) { + const tokenAfter = sourceCode.getTokenAfter(token); + + return ( + tokenAfter && + astUtils.isTokenOnSameLine(token, tokenAfter) && + sourceCode.isSpaceBetweenTokens(token, tokenAfter) + ); + } + + /** + * Checks if the given token is the last token in its line. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is the last in its line. + */ + function isLastTokenInCurrentLine(token) { + const tokenAfter = sourceCode.getTokenAfter(token); + + return !( + tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) + ); + } + + /** + * Checks if the given token is the first token in its line + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is the first in its line. + */ + function isFirstTokenInCurrentLine(token) { + const tokenBefore = sourceCode.getTokenBefore(token); + + return !( + tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore) + ); + } + + /** + * Checks if the next token of a given token is a closing parenthesis. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the next token of a given token is a closing parenthesis. + */ + function isBeforeClosingParen(token) { + const nextToken = sourceCode.getTokenAfter(token); + + return ( + (nextToken && astUtils.isClosingBraceToken(nextToken)) || + astUtils.isClosingParenToken(nextToken) + ); + } + + /** + * Report location example : + * + * for unexpected space `before` + * + * var a = 'b' ; + * ^^^ + * + * for unexpected space `after` + * + * var a = 'b'; c = 10; + * ^^ + * + * Reports if the given token has invalid spacing. + * @param {Token} token The semicolon token to check. + * @param {ASTNode} node The corresponding node of the token. + * @returns {void} + */ + function checkSemicolonSpacing(token, node) { + if (astUtils.isSemicolonToken(token)) { + if (hasLeadingSpace(token)) { + if (!requireSpaceBefore) { + const tokenBefore = sourceCode.getTokenBefore(token); + const loc = { + start: tokenBefore.loc.end, + end: token.loc.start, + }; + + context.report({ + node, + loc, + messageId: "unexpectedWhitespaceBefore", + fix(fixer) { + return fixer.removeRange([ + tokenBefore.range[1], + token.range[0], + ]); + }, + }); + } + } else { + if (requireSpaceBefore) { + const loc = token.loc; + + context.report({ + node, + loc, + messageId: "missingWhitespaceBefore", + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + } + + if ( + !isFirstTokenInCurrentLine(token) && + !isLastTokenInCurrentLine(token) && + !isBeforeClosingParen(token) + ) { + if (hasTrailingSpace(token)) { + if (!requireSpaceAfter) { + const tokenAfter = sourceCode.getTokenAfter(token); + const loc = { + start: token.loc.end, + end: tokenAfter.loc.start, + }; + + context.report({ + node, + loc, + messageId: "unexpectedWhitespaceAfter", + fix(fixer) { + return fixer.removeRange([ + token.range[1], + tokenAfter.range[0], + ]); + }, + }); + } + } else { + if (requireSpaceAfter) { + const loc = token.loc; + + context.report({ + node, + loc, + messageId: "missingWhitespaceAfter", + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + } + } + } + } + + /** + * Checks the spacing of the semicolon with the assumption that the last token is the semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNode(node) { + const token = sourceCode.getLastToken(node); + + checkSemicolonSpacing(token, node); + } + + return { + VariableDeclaration: checkNode, + ExpressionStatement: checkNode, + BreakStatement: checkNode, + ContinueStatement: checkNode, + DebuggerStatement: checkNode, + DoWhileStatement: checkNode, + ReturnStatement: checkNode, + ThrowStatement: checkNode, + ImportDeclaration: checkNode, + ExportNamedDeclaration: checkNode, + ExportAllDeclaration: checkNode, + ExportDefaultDeclaration: checkNode, + ForStatement(node) { + if (node.init) { + checkSemicolonSpacing( + sourceCode.getTokenAfter(node.init), + node, + ); + } + + if (node.test) { + checkSemicolonSpacing( + sourceCode.getTokenAfter(node.test), + node, + ); + } + }, + PropertyDefinition: checkNode, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/semi-style.js b/node_modules/eslint/lib/rules/semi-style.js new file mode 100644 index 00000000..5550caa6 --- /dev/null +++ b/node_modules/eslint/lib/rules/semi-style.js @@ -0,0 +1,218 @@ +/** + * @fileoverview Rule to enforce location of semicolons. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const SELECTOR = [ + "BreakStatement", + "ContinueStatement", + "DebuggerStatement", + "DoWhileStatement", + "ExportAllDeclaration", + "ExportDefaultDeclaration", + "ExportNamedDeclaration", + "ExpressionStatement", + "ImportDeclaration", + "ReturnStatement", + "ThrowStatement", + "VariableDeclaration", + "PropertyDefinition", +].join(","); + +/** + * Get the child node list of a given node. + * This returns `BlockStatement#body`, `StaticBlock#body`, `Program#body`, + * `ClassBody#body`, or `SwitchCase#consequent`. + * This is used to check whether a node is the first/last child. + * @param {Node} node A node to get child node list. + * @returns {Node[]|null} The child node list. + */ +function getChildren(node) { + const t = node.type; + + if ( + t === "BlockStatement" || + t === "StaticBlock" || + t === "Program" || + t === "ClassBody" + ) { + return node.body; + } + if (t === "SwitchCase") { + return node.consequent; + } + return null; +} + +/** + * Check whether a given node is the last statement in the parent block. + * @param {Node} node A node to check. + * @returns {boolean} `true` if the node is the last statement in the parent block. + */ +function isLastChild(node) { + const t = node.parent.type; + + if ( + t === "IfStatement" && + node.parent.consequent === node && + node.parent.alternate + ) { + // before `else` keyword. + return true; + } + if (t === "DoWhileStatement") { + // before `while` keyword. + return true; + } + const nodeList = getChildren(node.parent); + + return nodeList !== null && nodeList.at(-1) === node; // before `}` or etc. +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "semi-style", + url: "https://eslint.style/rules/js/semi-style", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce location of semicolons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/semi-style", + }, + + schema: [{ enum: ["last", "first"] }], + fixable: "whitespace", + + messages: { + expectedSemiColon: "Expected this semicolon to be at {{pos}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0] || "last"; + + /** + * Check the given semicolon token. + * @param {Token} semiToken The semicolon token to check. + * @param {"first"|"last"} expected The expected location to check. + * @returns {void} + */ + function check(semiToken, expected) { + const prevToken = sourceCode.getTokenBefore(semiToken); + const nextToken = sourceCode.getTokenAfter(semiToken); + const prevIsSameLine = + !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken); + const nextIsSameLine = + !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken); + + if ( + (expected === "last" && !prevIsSameLine) || + (expected === "first" && !nextIsSameLine) + ) { + context.report({ + loc: semiToken.loc, + messageId: "expectedSemiColon", + data: { + pos: + expected === "last" + ? "the end of the previous line" + : "the beginning of the next line", + }, + fix(fixer) { + if ( + prevToken && + nextToken && + sourceCode.commentsExistBetween( + prevToken, + nextToken, + ) + ) { + return null; + } + + const start = prevToken + ? prevToken.range[1] + : semiToken.range[0]; + const end = nextToken + ? nextToken.range[0] + : semiToken.range[1]; + const text = expected === "last" ? ";\n" : "\n;"; + + return fixer.replaceTextRange([start, end], text); + }, + }); + } + } + + return { + [SELECTOR](node) { + if (option === "first" && isLastChild(node)) { + return; + } + + const lastToken = sourceCode.getLastToken(node); + + if (astUtils.isSemicolonToken(lastToken)) { + check(lastToken, option); + } + }, + + ForStatement(node) { + const firstSemi = + node.init && + sourceCode.getTokenAfter( + node.init, + astUtils.isSemicolonToken, + ); + const secondSemi = + node.test && + sourceCode.getTokenAfter( + node.test, + astUtils.isSemicolonToken, + ); + + if (firstSemi) { + check(firstSemi, "last"); + } + if (secondSemi) { + check(secondSemi, "last"); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/semi.js b/node_modules/eslint/lib/rules/semi.js new file mode 100644 index 00000000..f99dc39b --- /dev/null +++ b/node_modules/eslint/lib/rules/semi.js @@ -0,0 +1,476 @@ +/** + * @fileoverview Rule to flag missing semicolons. + * @author Nicholas C. Zakas + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "semi", + url: "https://eslint.style/rules/js/semi", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow semicolons instead of ASI", + recommended: false, + url: "https://eslint.org/docs/latest/rules/semi", + }, + + fixable: "code", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["never"], + }, + { + type: "object", + properties: { + beforeStatementContinuationChars: { + enum: ["always", "any", "never"], + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + { + type: "array", + items: [ + { + enum: ["always"], + }, + { + type: "object", + properties: { + omitLastInOneLineBlock: { type: "boolean" }, + omitLastInOneLineClassBody: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + messages: { + missingSemi: "Missing semicolon.", + extraSemi: "Extra semicolon.", + }, + }, + + create(context) { + const OPT_OUT_PATTERN = /^[-[(/+`]/u; // One of [(/+-` + const unsafeClassFieldNames = new Set(["get", "set", "static"]); + const unsafeClassFieldFollowers = new Set(["*", "in", "instanceof"]); + const options = context.options[1]; + const never = context.options[0] === "never"; + const exceptOneLine = Boolean( + options && options.omitLastInOneLineBlock, + ); + const exceptOneLineClassBody = Boolean( + options && options.omitLastInOneLineClassBody, + ); + const beforeStatementContinuationChars = + (options && options.beforeStatementContinuationChars) || "any"; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports a semicolon error with appropriate location and message. + * @param {ASTNode} node The node with an extra or missing semicolon. + * @param {boolean} missing True if the semicolon is missing. + * @returns {void} + */ + function report(node, missing) { + const lastToken = sourceCode.getLastToken(node); + let messageId, fix, loc; + + if (!missing) { + messageId = "missingSemi"; + loc = { + start: lastToken.loc.end, + end: astUtils.getNextLocation( + sourceCode, + lastToken.loc.end, + ), + }; + fix = function (fixer) { + return fixer.insertTextAfter(lastToken, ";"); + }; + } else { + messageId = "extraSemi"; + loc = lastToken.loc; + fix = function (fixer) { + /* + * Expand the replacement range to include the surrounding + * tokens to avoid conflicting with no-extra-semi. + * https://github.com/eslint/eslint/issues/7928 + */ + return new FixTracker(fixer, sourceCode) + .retainSurroundingTokens(lastToken) + .remove(lastToken); + }; + } + + context.report({ + node, + loc, + messageId, + fix, + }); + } + + /** + * Check whether a given semicolon token is redundant. + * @param {Token} semiToken A semicolon token to check. + * @returns {boolean} `true` if the next token is `;` or `}`. + */ + function isRedundantSemi(semiToken) { + const nextToken = sourceCode.getTokenAfter(semiToken); + + return ( + !nextToken || + astUtils.isClosingBraceToken(nextToken) || + astUtils.isSemicolonToken(nextToken) + ); + } + + /** + * Check whether a given token is the closing brace of an arrow function. + * @param {Token} lastToken A token to check. + * @returns {boolean} `true` if the token is the closing brace of an arrow function. + */ + function isEndOfArrowBlock(lastToken) { + if (!astUtils.isClosingBraceToken(lastToken)) { + return false; + } + const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]); + + return ( + node.type === "BlockStatement" && + node.parent.type === "ArrowFunctionExpression" + ); + } + + /** + * Checks if a given PropertyDefinition node followed by a semicolon + * can safely remove that semicolon. It is not to safe to remove if + * the class field name is "get", "set", or "static", or if + * followed by a generator method. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node cannot have the semicolon + * removed. + */ + function maybeClassFieldAsiHazard(node) { + if (node.type !== "PropertyDefinition") { + return false; + } + + /* + * Computed property names and non-identifiers are always safe + * as they can be distinguished from keywords easily. + */ + const needsNameCheck = + !node.computed && node.key.type === "Identifier"; + + /* + * Certain names are problematic unless they also have a + * a way to distinguish between keywords and property + * names. + */ + if (needsNameCheck && unsafeClassFieldNames.has(node.key.name)) { + /* + * Special case: If the field name is `static`, + * it is only valid if the field is marked as static, + * so "static static" is okay but "static" is not. + */ + const isStaticStatic = + node.static && node.key.name === "static"; + + /* + * For other unsafe names, we only care if there is no + * initializer. No initializer = hazard. + */ + if (!isStaticStatic && !node.value) { + return true; + } + } + + const followingToken = sourceCode.getTokenAfter(node); + + return unsafeClassFieldFollowers.has(followingToken.value); + } + + /** + * Check whether a given node is on the same line with the next token. + * @param {Node} node A statement node to check. + * @returns {boolean} `true` if the node is on the same line with the next token. + */ + function isOnSameLineWithNextToken(node) { + const prevToken = sourceCode.getLastToken(node, 1); + const nextToken = sourceCode.getTokenAfter(node); + + return ( + !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken) + ); + } + + /** + * Check whether a given node can connect the next line if the next line is unreliable. + * @param {Node} node A statement node to check. + * @returns {boolean} `true` if the node can connect the next line. + */ + function maybeAsiHazardAfter(node) { + const t = node.type; + + if ( + t === "DoWhileStatement" || + t === "BreakStatement" || + t === "ContinueStatement" || + t === "DebuggerStatement" || + t === "ImportDeclaration" || + t === "ExportAllDeclaration" + ) { + return false; + } + if (t === "ReturnStatement") { + return Boolean(node.argument); + } + if (t === "ExportNamedDeclaration") { + return Boolean(node.declaration); + } + if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) { + return false; + } + + return true; + } + + /** + * Check whether a given token can connect the previous statement. + * @param {Token} token A token to check. + * @returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`. + */ + function maybeAsiHazardBefore(token) { + return ( + Boolean(token) && + OPT_OUT_PATTERN.test(token.value) && + token.value !== "++" && + token.value !== "--" + ); + } + + /** + * Check if the semicolon of a given node is unnecessary, only true if: + * - next token is a valid statement divider (`;` or `}`). + * - next token is on a new line and the node is not connectable to the new line. + * @param {Node} node A statement node to check. + * @returns {boolean} whether the semicolon is unnecessary. + */ + function canRemoveSemicolon(node) { + if (isRedundantSemi(sourceCode.getLastToken(node))) { + return true; // `;;` or `;}` + } + if (maybeClassFieldAsiHazard(node)) { + return false; + } + if (isOnSameLineWithNextToken(node)) { + return false; // One liner. + } + + // continuation characters should not apply to class fields + if ( + node.type !== "PropertyDefinition" && + beforeStatementContinuationChars === "never" && + !maybeAsiHazardAfter(node) + ) { + return true; // ASI works. This statement doesn't connect to the next. + } + if (!maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) { + return true; // ASI works. The next token doesn't connect to this statement. + } + + return false; + } + + /** + * Checks a node to see if it's the last item in a one-liner block. + * Block is any `BlockStatement` or `StaticBlock` node. Block is a one-liner if its + * braces (and consequently everything between them) are on the same line. + * @param {ASTNode} node The node to check. + * @returns {boolean} whether the node is the last item in a one-liner block. + */ + function isLastInOneLinerBlock(node) { + const parent = node.parent; + const nextToken = sourceCode.getTokenAfter(node); + + if (!nextToken || nextToken.value !== "}") { + return false; + } + + if (parent.type === "BlockStatement") { + return parent.loc.start.line === parent.loc.end.line; + } + + if (parent.type === "StaticBlock") { + const openingBrace = sourceCode.getFirstToken(parent, { + skip: 1, + }); // skip the `static` token + + return openingBrace.loc.start.line === parent.loc.end.line; + } + + return false; + } + + /** + * Checks a node to see if it's the last item in a one-liner `ClassBody` node. + * ClassBody is a one-liner if its braces (and consequently everything between them) are on the same line. + * @param {ASTNode} node The node to check. + * @returns {boolean} whether the node is the last item in a one-liner ClassBody. + */ + function isLastInOneLinerClassBody(node) { + const parent = node.parent; + const nextToken = sourceCode.getTokenAfter(node); + + if (!nextToken || nextToken.value !== "}") { + return false; + } + + if (parent.type === "ClassBody") { + return parent.loc.start.line === parent.loc.end.line; + } + + return false; + } + + /** + * Checks a node to see if it's followed by a semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolon(node) { + const isSemi = astUtils.isSemicolonToken( + sourceCode.getLastToken(node), + ); + + if (never) { + if (isSemi && canRemoveSemicolon(node)) { + report(node, true); + } else if ( + !isSemi && + beforeStatementContinuationChars === "always" && + node.type !== "PropertyDefinition" && + maybeAsiHazardBefore(sourceCode.getTokenAfter(node)) + ) { + report(node); + } + } else { + const oneLinerBlock = + exceptOneLine && isLastInOneLinerBlock(node); + const oneLinerClassBody = + exceptOneLineClassBody && isLastInOneLinerClassBody(node); + const oneLinerBlockOrClassBody = + oneLinerBlock || oneLinerClassBody; + + if (isSemi && oneLinerBlockOrClassBody) { + report(node, true); + } else if (!isSemi && !oneLinerBlockOrClassBody) { + report(node); + } + } + } + + /** + * Checks to see if there's a semicolon after a variable declaration. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolonForVariableDeclaration(node) { + const parent = node.parent; + + if ( + (parent.type !== "ForStatement" || parent.init !== node) && + (!/^For(?:In|Of)Statement/u.test(parent.type) || + parent.left !== node) + ) { + checkForSemicolon(node); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + VariableDeclaration: checkForSemicolonForVariableDeclaration, + ExpressionStatement: checkForSemicolon, + ReturnStatement: checkForSemicolon, + ThrowStatement: checkForSemicolon, + DoWhileStatement: checkForSemicolon, + DebuggerStatement: checkForSemicolon, + BreakStatement: checkForSemicolon, + ContinueStatement: checkForSemicolon, + ImportDeclaration: checkForSemicolon, + ExportAllDeclaration: checkForSemicolon, + ExportNamedDeclaration(node) { + if (!node.declaration) { + checkForSemicolon(node); + } + }, + ExportDefaultDeclaration(node) { + if ( + !/(?:Class|Function)Declaration/u.test( + node.declaration.type, + ) + ) { + checkForSemicolon(node); + } + }, + PropertyDefinition: checkForSemicolon, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/sort-imports.js b/node_modules/eslint/lib/rules/sort-imports.js new file mode 100644 index 00000000..e97f3f05 --- /dev/null +++ b/node_modules/eslint/lib/rules/sort-imports.js @@ -0,0 +1,319 @@ +/** + * @fileoverview Rule to enforce sorted `import` declarations within modules + * @author Christian Schuller + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowSeparatedGroups: false, + ignoreCase: false, + ignoreDeclarationSort: false, + ignoreMemberSort: false, + memberSyntaxSortOrder: ["none", "all", "multiple", "single"], + }, + ], + + docs: { + description: "Enforce sorted `import` declarations within modules", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/sort-imports", + }, + + schema: [ + { + type: "object", + properties: { + ignoreCase: { + type: "boolean", + }, + memberSyntaxSortOrder: { + type: "array", + items: { + enum: ["none", "all", "multiple", "single"], + }, + uniqueItems: true, + minItems: 4, + maxItems: 4, + }, + ignoreDeclarationSort: { + type: "boolean", + }, + ignoreMemberSort: { + type: "boolean", + }, + allowSeparatedGroups: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + sortImportsAlphabetically: + "Imports should be sorted alphabetically.", + sortMembersAlphabetically: + "Member '{{memberName}}' of the import declaration should be sorted alphabetically.", + unexpectedSyntaxOrder: + "Expected '{{syntaxA}}' syntax before '{{syntaxB}}' syntax.", + }, + }, + + create(context) { + const [ + { + ignoreCase, + ignoreDeclarationSort, + ignoreMemberSort, + memberSyntaxSortOrder, + allowSeparatedGroups, + }, + ] = context.options; + const sourceCode = context.sourceCode; + let previousDeclaration = null; + + /** + * Gets the used member syntax style. + * + * import "my-module.js" --> none + * import * as myModule from "my-module.js" --> all + * import {myMember} from "my-module.js" --> single + * import {foo, bar} from "my-module.js" --> multiple + * @param {ASTNode} node the ImportDeclaration node. + * @returns {string} used member parameter style, ["all", "multiple", "single"] + */ + function usedMemberSyntax(node) { + if (node.specifiers.length === 0) { + return "none"; + } + if (node.specifiers[0].type === "ImportNamespaceSpecifier") { + return "all"; + } + if (node.specifiers.length === 1) { + return "single"; + } + return "multiple"; + } + + /** + * Gets the group by member parameter index for given declaration. + * @param {ASTNode} node the ImportDeclaration node. + * @returns {number} the declaration group by member index. + */ + function getMemberParameterGroupIndex(node) { + return memberSyntaxSortOrder.indexOf(usedMemberSyntax(node)); + } + + /** + * Gets the local name of the first imported module. + * @param {ASTNode} node the ImportDeclaration node. + * @returns {?string} the local name of the first imported module. + */ + function getFirstLocalMemberName(node) { + if (node.specifiers[0]) { + return node.specifiers[0].local.name; + } + return null; + } + + /** + * Calculates number of lines between two nodes. It is assumed that the given `left` node appears before + * the given `right` node in the source code. Lines are counted from the end of the `left` node till the + * start of the `right` node. If the given nodes are on the same line, it returns `0`, same as if they were + * on two consecutive lines. + * @param {ASTNode} left node that appears before the given `right` node. + * @param {ASTNode} right node that appears after the given `left` node. + * @returns {number} number of lines between nodes. + */ + function getNumberOfLinesBetween(left, right) { + return Math.max(right.loc.start.line - left.loc.end.line - 1, 0); + } + + return { + ImportDeclaration(node) { + if (!ignoreDeclarationSort) { + if ( + previousDeclaration && + allowSeparatedGroups && + getNumberOfLinesBetween(previousDeclaration, node) > 0 + ) { + // reset declaration sort + previousDeclaration = null; + } + + if (previousDeclaration) { + const currentMemberSyntaxGroupIndex = + getMemberParameterGroupIndex(node), + previousMemberSyntaxGroupIndex = + getMemberParameterGroupIndex( + previousDeclaration, + ); + let currentLocalMemberName = + getFirstLocalMemberName(node), + previousLocalMemberName = + getFirstLocalMemberName(previousDeclaration); + + if (ignoreCase) { + previousLocalMemberName = + previousLocalMemberName && + previousLocalMemberName.toLowerCase(); + currentLocalMemberName = + currentLocalMemberName && + currentLocalMemberName.toLowerCase(); + } + + /* + * When the current declaration uses a different member syntax, + * then check if the ordering is correct. + * Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name. + */ + if ( + currentMemberSyntaxGroupIndex !== + previousMemberSyntaxGroupIndex + ) { + if ( + currentMemberSyntaxGroupIndex < + previousMemberSyntaxGroupIndex + ) { + context.report({ + node, + messageId: "unexpectedSyntaxOrder", + data: { + syntaxA: + memberSyntaxSortOrder[ + currentMemberSyntaxGroupIndex + ], + syntaxB: + memberSyntaxSortOrder[ + previousMemberSyntaxGroupIndex + ], + }, + }); + } + } else { + if ( + previousLocalMemberName && + currentLocalMemberName && + currentLocalMemberName < previousLocalMemberName + ) { + context.report({ + node, + messageId: "sortImportsAlphabetically", + }); + } + } + } + + previousDeclaration = node; + } + + if (!ignoreMemberSort) { + const importSpecifiers = node.specifiers.filter( + specifier => specifier.type === "ImportSpecifier", + ); + const getSortableName = ignoreCase + ? specifier => specifier.local.name.toLowerCase() + : specifier => specifier.local.name; + const firstUnsortedIndex = importSpecifiers + .map(getSortableName) + .findIndex( + (name, index, array) => array[index - 1] > name, + ); + + if (firstUnsortedIndex !== -1) { + context.report({ + node: importSpecifiers[firstUnsortedIndex], + messageId: "sortMembersAlphabetically", + data: { + memberName: + importSpecifiers[firstUnsortedIndex].local + .name, + }, + fix(fixer) { + if ( + importSpecifiers.some( + specifier => + sourceCode.getCommentsBefore( + specifier, + ).length || + sourceCode.getCommentsAfter( + specifier, + ).length, + ) + ) { + // If there are comments in the ImportSpecifier list, don't rearrange the specifiers. + return null; + } + + return fixer.replaceTextRange( + [ + importSpecifiers[0].range[0], + importSpecifiers.at(-1).range[1], + ], + importSpecifiers + + // Clone the importSpecifiers array to avoid mutating it + .slice() + + // Sort the array into the desired order + .sort((specifierA, specifierB) => { + const aName = + getSortableName(specifierA); + const bName = + getSortableName(specifierB); + + return aName > bName ? 1 : -1; + }) + + // Build a string out of the sorted list of import specifiers and the text between the originals + .reduce( + (sourceText, specifier, index) => { + const textAfterSpecifier = + index === + importSpecifiers.length - 1 + ? "" + : sourceCode + .getText() + .slice( + importSpecifiers[ + index + ].range[1], + importSpecifiers[ + index + + 1 + ].range[0], + ); + + return ( + sourceText + + sourceCode.getText( + specifier, + ) + + textAfterSpecifier + ); + }, + "", + ), + ); + }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/sort-keys.js b/node_modules/eslint/lib/rules/sort-keys.js new file mode 100644 index 00000000..bbb2dc2b --- /dev/null +++ b/node_modules/eslint/lib/rules/sort-keys.js @@ -0,0 +1,268 @@ +/** + * @fileoverview Rule to require object keys to be sorted + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + naturalCompare = require("natural-compare"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets the property name of the given `Property` node. + * + * - If the property's key is an `Identifier` node, this returns the key's name + * whether it's a computed property or not. + * - If the property has a static name, this returns the static name. + * - Otherwise, this returns null. + * @param {ASTNode} node The `Property` node to get. + * @returns {string|null} The property name or null. + * @private + */ +function getPropertyName(node) { + const staticName = astUtils.getStaticPropertyName(node); + + if (staticName !== null) { + return staticName; + } + + return node.key.name || null; +} + +/** + * Functions which check that the given 2 names are in specific order. + * + * Postfix `I` is meant insensitive. + * Postfix `N` is meant natural. + * @private + */ +const isValidOrders = { + asc(a, b) { + return a <= b; + }, + ascI(a, b) { + return a.toLowerCase() <= b.toLowerCase(); + }, + ascN(a, b) { + return naturalCompare(a, b) <= 0; + }, + ascIN(a, b) { + return naturalCompare(a.toLowerCase(), b.toLowerCase()) <= 0; + }, + desc(a, b) { + return isValidOrders.asc(b, a); + }, + descI(a, b) { + return isValidOrders.ascI(b, a); + }, + descN(a, b) { + return isValidOrders.ascN(b, a); + }, + descIN(a, b) { + return isValidOrders.ascIN(b, a); + }, +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + "asc", + { + allowLineSeparatedGroups: false, + caseSensitive: true, + ignoreComputedKeys: false, + minKeys: 2, + natural: false, + }, + ], + + docs: { + description: "Require object keys to be sorted", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/sort-keys", + }, + + schema: [ + { + enum: ["asc", "desc"], + }, + { + type: "object", + properties: { + caseSensitive: { + type: "boolean", + }, + natural: { + type: "boolean", + }, + minKeys: { + type: "integer", + minimum: 2, + }, + allowLineSeparatedGroups: { + type: "boolean", + }, + ignoreComputedKeys: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + sortKeys: + "Expected object keys to be in {{natural}}{{insensitive}}{{order}}ending order. '{{thisName}}' should be before '{{prevName}}'.", + }, + }, + + create(context) { + const [ + order, + { + caseSensitive, + natural, + minKeys, + allowLineSeparatedGroups, + ignoreComputedKeys, + }, + ] = context.options; + const insensitive = !caseSensitive; + const isValidOrder = + isValidOrders[ + order + (insensitive ? "I" : "") + (natural ? "N" : "") + ]; + + // The stack to save the previous property's name for each object literals. + let stack = null; + const sourceCode = context.sourceCode; + + return { + ObjectExpression(node) { + stack = { + upper: stack, + prevNode: null, + prevBlankLine: false, + prevName: null, + numKeys: node.properties.length, + }; + }, + + "ObjectExpression:exit"() { + stack = stack.upper; + }, + + SpreadElement(node) { + if (node.parent.type === "ObjectExpression") { + stack.prevName = null; + } + }, + + Property(node) { + if (node.parent.type === "ObjectPattern") { + return; + } + + if (ignoreComputedKeys && node.computed) { + stack.prevName = null; // reset sort + return; + } + + const prevName = stack.prevName; + const numKeys = stack.numKeys; + const thisName = getPropertyName(node); + + // Get tokens between current node and previous node + const tokens = + stack.prevNode && + sourceCode.getTokensBetween(stack.prevNode, node, { + includeComments: true, + }); + + let isBlankLineBetweenNodes = stack.prevBlankLine; + + if (tokens) { + // check blank line between tokens + tokens.forEach((token, index) => { + const previousToken = tokens[index - 1]; + + if ( + previousToken && + token.loc.start.line - previousToken.loc.end.line > + 1 + ) { + isBlankLineBetweenNodes = true; + } + }); + + // check blank line between the current node and the last token + if ( + !isBlankLineBetweenNodes && + node.loc.start.line - tokens.at(-1).loc.end.line > 1 + ) { + isBlankLineBetweenNodes = true; + } + + // check blank line between the first token and the previous node + if ( + !isBlankLineBetweenNodes && + tokens[0].loc.start.line - stack.prevNode.loc.end.line > + 1 + ) { + isBlankLineBetweenNodes = true; + } + } + + stack.prevNode = node; + + if (thisName !== null) { + stack.prevName = thisName; + } + + if (allowLineSeparatedGroups && isBlankLineBetweenNodes) { + stack.prevBlankLine = thisName === null; + return; + } + + if ( + prevName === null || + thisName === null || + numKeys < minKeys + ) { + return; + } + + if (!isValidOrder(prevName, thisName)) { + context.report({ + node, + loc: node.key.loc, + messageId: "sortKeys", + data: { + thisName, + prevName, + order, + insensitive: insensitive ? "insensitive " : "", + natural: natural ? "natural " : "", + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/sort-vars.js b/node_modules/eslint/lib/rules/sort-vars.js new file mode 100644 index 00000000..34081b95 --- /dev/null +++ b/node_modules/eslint/lib/rules/sort-vars.js @@ -0,0 +1,140 @@ +/** + * @fileoverview Rule to require sorting of variables within a single Variable Declaration block + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + ignoreCase: false, + }, + ], + + docs: { + description: + "Require variables within the same declaration block to be sorted", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/sort-vars", + }, + + schema: [ + { + type: "object", + properties: { + ignoreCase: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + sortVars: + "Variables within the same declaration block should be sorted alphabetically.", + }, + }, + + create(context) { + const [{ ignoreCase }] = context.options; + const sourceCode = context.sourceCode; + + return { + VariableDeclaration(node) { + const idDeclarations = node.declarations.filter( + decl => decl.id.type === "Identifier", + ); + const getSortableName = ignoreCase + ? decl => decl.id.name.toLowerCase() + : decl => decl.id.name; + const unfixable = idDeclarations.some( + decl => decl.init !== null && decl.init.type !== "Literal", + ); + let fixed = false; + + idDeclarations.slice(1).reduce((memo, decl) => { + const lastVariableName = getSortableName(memo), + currentVariableName = getSortableName(decl); + + if (currentVariableName < lastVariableName) { + context.report({ + node: decl, + messageId: "sortVars", + fix(fixer) { + if (unfixable || fixed) { + return null; + } + return fixer.replaceTextRange( + [ + idDeclarations[0].range[0], + idDeclarations.at(-1).range[1], + ], + idDeclarations + + // Clone the idDeclarations array to avoid mutating it + .slice() + + // Sort the array into the desired order + .sort((declA, declB) => { + const aName = + getSortableName(declA); + const bName = + getSortableName(declB); + + return aName > bName ? 1 : -1; + }) + + // Build a string out of the sorted list of identifier declarations and the text between the originals + .reduce( + (sourceText, identifier, index) => { + const textAfterIdentifier = + index === + idDeclarations.length - 1 + ? "" + : sourceCode + .getText() + .slice( + idDeclarations[ + index + ].range[1], + idDeclarations[ + index + + 1 + ].range[0], + ); + + return ( + sourceText + + sourceCode.getText( + identifier, + ) + + textAfterIdentifier + ); + }, + "", + ), + ); + }, + }); + fixed = true; + return memo; + } + return decl; + }, idDeclarations[0]); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-before-blocks.js b/node_modules/eslint/lib/rules/space-before-blocks.js new file mode 100644 index 00000000..c9f55b8b --- /dev/null +++ b/node_modules/eslint/lib/rules/space-before-blocks.js @@ -0,0 +1,232 @@ +/** + * @fileoverview A rule to ensure whitespace before blocks. + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given node represents the body of a function. + * @param {ASTNode} node the node to check. + * @returns {boolean} `true` if the node is function body. + */ +function isFunctionBody(node) { + const parent = node.parent; + + return ( + node.type === "BlockStatement" && + astUtils.isFunction(parent) && + parent.body === node + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "space-before-blocks", + url: "https://eslint.style/rules/js/space-before-blocks", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing before blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-before-blocks", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + keywords: { + enum: ["always", "never", "off"], + }, + functions: { + enum: ["always", "never", "off"], + }, + classes: { + enum: ["always", "never", "off"], + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + unexpectedSpace: "Unexpected space before opening brace.", + missingSpace: "Missing space before opening brace.", + }, + }, + + create(context) { + const config = context.options[0], + sourceCode = context.sourceCode; + let alwaysFunctions = true, + alwaysKeywords = true, + alwaysClasses = true, + neverFunctions = false, + neverKeywords = false, + neverClasses = false; + + if (typeof config === "object") { + alwaysFunctions = config.functions === "always"; + alwaysKeywords = config.keywords === "always"; + alwaysClasses = config.classes === "always"; + neverFunctions = config.functions === "never"; + neverKeywords = config.keywords === "never"; + neverClasses = config.classes === "never"; + } else if (config === "never") { + alwaysFunctions = false; + alwaysKeywords = false; + alwaysClasses = false; + neverFunctions = true; + neverKeywords = true; + neverClasses = true; + } + + /** + * Checks whether the spacing before the given block is already controlled by another rule: + * - `arrow-spacing` checks spaces after `=>`. + * - `keyword-spacing` checks spaces after keywords in certain contexts. + * - `switch-colon-spacing` checks spaces after `:` of switch cases. + * @param {Token} precedingToken first token before the block. + * @param {ASTNode|Token} node `BlockStatement` node or `{` token of a `SwitchStatement` node. + * @returns {boolean} `true` if requiring or disallowing spaces before the given block could produce conflicts with other rules. + */ + function isConflicted(precedingToken, node) { + return ( + astUtils.isArrowToken(precedingToken) || + (astUtils.isKeywordToken(precedingToken) && + !isFunctionBody(node)) || + (astUtils.isColonToken(precedingToken) && + node.parent && + node.parent.type === "SwitchCase" && + precedingToken === + astUtils.getSwitchCaseColonToken( + node.parent, + sourceCode, + )) + ); + } + + /** + * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line. + * @param {ASTNode|Token} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPrecedingSpace(node) { + const precedingToken = sourceCode.getTokenBefore(node); + + if ( + precedingToken && + !isConflicted(precedingToken, node) && + astUtils.isTokenOnSameLine(precedingToken, node) + ) { + const hasSpace = sourceCode.isSpaceBetweenTokens( + precedingToken, + node, + ); + let requireSpace; + let requireNoSpace; + + if (isFunctionBody(node)) { + requireSpace = alwaysFunctions; + requireNoSpace = neverFunctions; + } else if (node.type === "ClassBody") { + requireSpace = alwaysClasses; + requireNoSpace = neverClasses; + } else { + requireSpace = alwaysKeywords; + requireNoSpace = neverKeywords; + } + + if (requireSpace && !hasSpace) { + context.report({ + node, + messageId: "missingSpace", + fix(fixer) { + return fixer.insertTextBefore(node, " "); + }, + }); + } else if (requireNoSpace && hasSpace) { + context.report({ + node, + messageId: "unexpectedSpace", + fix(fixer) { + return fixer.removeRange([ + precedingToken.range[1], + node.range[0], + ]); + }, + }); + } + } + } + + /** + * Checks if the CaseBlock of an given SwitchStatement node has a preceding space. + * @param {ASTNode} node The node of a SwitchStatement. + * @returns {void} undefined. + */ + function checkSpaceBeforeCaseBlock(node) { + const cases = node.cases; + let openingBrace; + + if (cases.length > 0) { + openingBrace = sourceCode.getTokenBefore(cases[0]); + } else { + openingBrace = sourceCode.getLastToken(node, 1); + } + + checkPrecedingSpace(openingBrace); + } + + return { + BlockStatement: checkPrecedingSpace, + ClassBody: checkPrecedingSpace, + SwitchStatement: checkSpaceBeforeCaseBlock, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-before-function-paren.js b/node_modules/eslint/lib/rules/space-before-function-paren.js new file mode 100644 index 00000000..501fcf28 --- /dev/null +++ b/node_modules/eslint/lib/rules/space-before-function-paren.js @@ -0,0 +1,205 @@ +/** + * @fileoverview Rule to validate spacing before function paren. + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "space-before-function-paren", + url: "https://eslint.style/rules/js/space-before-function-paren", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing before `function` definition opening parenthesis", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-before-function-paren", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + anonymous: { + enum: ["always", "never", "ignore"], + }, + named: { + enum: ["always", "never", "ignore"], + }, + asyncArrow: { + enum: ["always", "never", "ignore"], + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + unexpectedSpace: "Unexpected space before function parentheses.", + missingSpace: "Missing space before function parentheses.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const baseConfig = + typeof context.options[0] === "string" + ? context.options[0] + : "always"; + const overrideConfig = + typeof context.options[0] === "object" ? context.options[0] : {}; + + /** + * Determines whether a function has a name. + * @param {ASTNode} node The function node. + * @returns {boolean} Whether the function has a name. + */ + function isNamedFunction(node) { + if (node.id) { + return true; + } + + const parent = node.parent; + + return ( + parent.type === "MethodDefinition" || + (parent.type === "Property" && + (parent.kind === "get" || + parent.kind === "set" || + parent.method)) + ); + } + + /** + * Gets the config for a given function + * @param {ASTNode} node The function node + * @returns {string} "always", "never", or "ignore" + */ + function getConfigForFunction(node) { + if (node.type === "ArrowFunctionExpression") { + // Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar + if ( + node.async && + astUtils.isOpeningParenToken( + sourceCode.getFirstToken(node, { skip: 1 }), + ) + ) { + return overrideConfig.asyncArrow || baseConfig; + } + } else if (isNamedFunction(node)) { + return overrideConfig.named || baseConfig; + + // `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}` + } else if (!node.generator) { + return overrideConfig.anonymous || baseConfig; + } + + return "ignore"; + } + + /** + * Checks the parens of a function node + * @param {ASTNode} node A function node + * @returns {void} + */ + function checkFunction(node) { + const functionConfig = getConfigForFunction(node); + + if (functionConfig === "ignore") { + return; + } + + const rightToken = sourceCode.getFirstToken( + node, + astUtils.isOpeningParenToken, + ); + const leftToken = sourceCode.getTokenBefore(rightToken); + const hasSpacing = sourceCode.isSpaceBetweenTokens( + leftToken, + rightToken, + ); + + if (hasSpacing && functionConfig === "never") { + context.report({ + node, + loc: { + start: leftToken.loc.end, + end: rightToken.loc.start, + }, + messageId: "unexpectedSpace", + fix(fixer) { + const comments = + sourceCode.getCommentsBefore(rightToken); + + // Don't fix anything if there's a single line comment between the left and the right token + if (comments.some(comment => comment.type === "Line")) { + return null; + } + return fixer.replaceTextRange( + [leftToken.range[1], rightToken.range[0]], + comments.reduce( + (text, comment) => + text + sourceCode.getText(comment), + "", + ), + ); + }, + }); + } else if (!hasSpacing && functionConfig === "always") { + context.report({ + node, + loc: rightToken.loc, + messageId: "missingSpace", + fix: fixer => fixer.insertTextAfter(leftToken, " "), + }); + } + } + + return { + ArrowFunctionExpression: checkFunction, + FunctionDeclaration: checkFunction, + FunctionExpression: checkFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-in-parens.js b/node_modules/eslint/lib/rules/space-in-parens.js new file mode 100644 index 00000000..e18adceb --- /dev/null +++ b/node_modules/eslint/lib/rules/space-in-parens.js @@ -0,0 +1,374 @@ +/** + * @fileoverview Disallows or enforces spaces inside of parentheses. + * @author Jonathan Rajavuori + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "space-in-parens", + url: "https://eslint.style/rules/js/space-in-parens", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing inside parentheses", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-in-parens", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + enum: ["{}", "[]", "()", "empty"], + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingOpeningSpace: "There must be a space after this paren.", + missingClosingSpace: "There must be a space before this paren.", + rejectedOpeningSpace: "There should be no space after this paren.", + rejectedClosingSpace: "There should be no space before this paren.", + }, + }, + + create(context) { + const ALWAYS = context.options[0] === "always", + exceptionsArrayOptions = + (context.options[1] && context.options[1].exceptions) || [], + options = {}; + + let exceptions; + + if (exceptionsArrayOptions.length) { + options.braceException = exceptionsArrayOptions.includes("{}"); + options.bracketException = exceptionsArrayOptions.includes("[]"); + options.parenException = exceptionsArrayOptions.includes("()"); + options.empty = exceptionsArrayOptions.includes("empty"); + } + + /** + * Produces an object with the opener and closer exception values + * @returns {Object} `openers` and `closers` exception values + * @private + */ + function getExceptions() { + const openers = [], + closers = []; + + if (options.braceException) { + openers.push("{"); + closers.push("}"); + } + + if (options.bracketException) { + openers.push("["); + closers.push("]"); + } + + if (options.parenException) { + openers.push("("); + closers.push(")"); + } + + if (options.empty) { + openers.push(")"); + closers.push("("); + } + + return { + openers, + closers, + }; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + const sourceCode = context.sourceCode; + + /** + * Determines if a token is one of the exceptions for the opener paren + * @param {Object} token The token to check + * @returns {boolean} True if the token is one of the exceptions for the opener paren + */ + function isOpenerException(token) { + return exceptions.openers.includes(token.value); + } + + /** + * Determines if a token is one of the exceptions for the closer paren + * @param {Object} token The token to check + * @returns {boolean} True if the token is one of the exceptions for the closer paren + */ + function isCloserException(token) { + return exceptions.closers.includes(token.value); + } + + /** + * Determines if an opening paren is immediately followed by a required space + * @param {Object} openingParenToken The paren token + * @param {Object} tokenAfterOpeningParen The token after it + * @returns {boolean} True if the opening paren is missing a required space + */ + function openerMissingSpace(openingParenToken, tokenAfterOpeningParen) { + if ( + sourceCode.isSpaceBetweenTokens( + openingParenToken, + tokenAfterOpeningParen, + ) + ) { + return false; + } + + if ( + !options.empty && + astUtils.isClosingParenToken(tokenAfterOpeningParen) + ) { + return false; + } + + if (ALWAYS) { + return !isOpenerException(tokenAfterOpeningParen); + } + return isOpenerException(tokenAfterOpeningParen); + } + + /** + * Determines if an opening paren is immediately followed by a disallowed space + * @param {Object} openingParenToken The paren token + * @param {Object} tokenAfterOpeningParen The token after it + * @returns {boolean} True if the opening paren has a disallowed space + */ + function openerRejectsSpace(openingParenToken, tokenAfterOpeningParen) { + if ( + !astUtils.isTokenOnSameLine( + openingParenToken, + tokenAfterOpeningParen, + ) + ) { + return false; + } + + if (tokenAfterOpeningParen.type === "Line") { + return false; + } + + if ( + !sourceCode.isSpaceBetweenTokens( + openingParenToken, + tokenAfterOpeningParen, + ) + ) { + return false; + } + + if (ALWAYS) { + return isOpenerException(tokenAfterOpeningParen); + } + return !isOpenerException(tokenAfterOpeningParen); + } + + /** + * Determines if a closing paren is immediately preceded by a required space + * @param {Object} tokenBeforeClosingParen The token before the paren + * @param {Object} closingParenToken The paren token + * @returns {boolean} True if the closing paren is missing a required space + */ + function closerMissingSpace( + tokenBeforeClosingParen, + closingParenToken, + ) { + if ( + sourceCode.isSpaceBetweenTokens( + tokenBeforeClosingParen, + closingParenToken, + ) + ) { + return false; + } + + if ( + !options.empty && + astUtils.isOpeningParenToken(tokenBeforeClosingParen) + ) { + return false; + } + + if (ALWAYS) { + return !isCloserException(tokenBeforeClosingParen); + } + return isCloserException(tokenBeforeClosingParen); + } + + /** + * Determines if a closer paren is immediately preceded by a disallowed space + * @param {Object} tokenBeforeClosingParen The token before the paren + * @param {Object} closingParenToken The paren token + * @returns {boolean} True if the closing paren has a disallowed space + */ + function closerRejectsSpace( + tokenBeforeClosingParen, + closingParenToken, + ) { + if ( + !astUtils.isTokenOnSameLine( + tokenBeforeClosingParen, + closingParenToken, + ) + ) { + return false; + } + + if ( + !sourceCode.isSpaceBetweenTokens( + tokenBeforeClosingParen, + closingParenToken, + ) + ) { + return false; + } + + if (ALWAYS) { + return isCloserException(tokenBeforeClosingParen); + } + return !isCloserException(tokenBeforeClosingParen); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkParenSpaces(node) { + exceptions = getExceptions(); + const tokens = sourceCode.tokensAndComments; + + tokens.forEach((token, i) => { + const prevToken = tokens[i - 1]; + const nextToken = tokens[i + 1]; + + // if token is not an opening or closing paren token, do nothing + if ( + !astUtils.isOpeningParenToken(token) && + !astUtils.isClosingParenToken(token) + ) { + return; + } + + // if token is an opening paren and is not followed by a required space + if ( + token.value === "(" && + openerMissingSpace(token, nextToken) + ) { + context.report({ + node, + loc: token.loc, + messageId: "missingOpeningSpace", + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + + // if token is an opening paren and is followed by a disallowed space + if ( + token.value === "(" && + openerRejectsSpace(token, nextToken) + ) { + context.report({ + node, + loc: { + start: token.loc.end, + end: nextToken.loc.start, + }, + messageId: "rejectedOpeningSpace", + fix(fixer) { + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + + // if token is a closing paren and is not preceded by a required space + if ( + token.value === ")" && + closerMissingSpace(prevToken, token) + ) { + context.report({ + node, + loc: token.loc, + messageId: "missingClosingSpace", + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + + // if token is a closing paren and is preceded by a disallowed space + if ( + token.value === ")" && + closerRejectsSpace(prevToken, token) + ) { + context.report({ + node, + loc: { + start: prevToken.loc.end, + end: token.loc.start, + }, + messageId: "rejectedClosingSpace", + fix(fixer) { + return fixer.removeRange([ + prevToken.range[1], + token.range[0], + ]); + }, + }); + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-infix-ops.js b/node_modules/eslint/lib/rules/space-infix-ops.js new file mode 100644 index 00000000..f9a5e660 --- /dev/null +++ b/node_modules/eslint/lib/rules/space-infix-ops.js @@ -0,0 +1,252 @@ +/** + * @fileoverview Require spaces around infix operators + * @author Michael Ficarra + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const { isEqToken } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "space-infix-ops", + url: "https://eslint.style/rules/js/space-infix-ops", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require spacing around infix operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-infix-ops", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + int32Hint: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingSpace: "Operator '{{operator}}' must be spaced.", + }, + }, + + create(context) { + const int32Hint = context.options[0] + ? context.options[0].int32Hint === true + : false; + const sourceCode = context.sourceCode; + + /** + * Returns the first token which violates the rule + * @param {ASTNode} left The left node of the main node + * @param {ASTNode} right The right node of the main node + * @param {string} op The operator of the main node + * @returns {Object} The violator token or null + * @private + */ + function getFirstNonSpacedToken(left, right, op) { + const operator = sourceCode.getFirstTokenBetween( + left, + right, + token => token.value === op, + ); + const prev = sourceCode.getTokenBefore(operator); + const next = sourceCode.getTokenAfter(operator); + + if ( + !sourceCode.isSpaceBetweenTokens(prev, operator) || + !sourceCode.isSpaceBetweenTokens(operator, next) + ) { + return operator; + } + + return null; + } + + /** + * Reports an AST node as a rule violation + * @param {ASTNode} mainNode The node to report + * @param {Object} culpritToken The token which has a problem + * @returns {void} + * @private + */ + function report(mainNode, culpritToken) { + context.report({ + node: mainNode, + loc: culpritToken.loc, + messageId: "missingSpace", + data: { + operator: culpritToken.value, + }, + fix(fixer) { + const previousToken = + sourceCode.getTokenBefore(culpritToken); + const afterToken = sourceCode.getTokenAfter(culpritToken); + let fixString = ""; + + if (culpritToken.range[0] - previousToken.range[1] === 0) { + fixString = " "; + } + + fixString += culpritToken.value; + + if (afterToken.range[0] - culpritToken.range[1] === 0) { + fixString += " "; + } + + return fixer.replaceText(culpritToken, fixString); + }, + }); + } + + /** + * Check if the node is binary then report + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkBinary(node) { + const leftNode = node.left.typeAnnotation + ? node.left.typeAnnotation + : node.left; + const rightNode = node.right; + + // search for = in AssignmentPattern nodes + const operator = node.operator || "="; + + const nonSpacedNode = getFirstNonSpacedToken( + leftNode, + rightNode, + operator, + ); + + if (nonSpacedNode) { + if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) { + report(node, nonSpacedNode); + } + } + } + + /** + * Check if the node is conditional + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkConditional(node) { + const nonSpacedConsequentNode = getFirstNonSpacedToken( + node.test, + node.consequent, + "?", + ); + const nonSpacedAlternateNode = getFirstNonSpacedToken( + node.consequent, + node.alternate, + ":", + ); + + if (nonSpacedConsequentNode) { + report(node, nonSpacedConsequentNode); + } + + if (nonSpacedAlternateNode) { + report(node, nonSpacedAlternateNode); + } + } + + /** + * Check if the node is a variable + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkVar(node) { + const leftNode = node.id.typeAnnotation + ? node.id.typeAnnotation + : node.id; + const rightNode = node.init; + + if (rightNode) { + const nonSpacedNode = getFirstNonSpacedToken( + leftNode, + rightNode, + "=", + ); + + if (nonSpacedNode) { + report(node, nonSpacedNode); + } + } + } + + return { + AssignmentExpression: checkBinary, + AssignmentPattern: checkBinary, + BinaryExpression: checkBinary, + LogicalExpression: checkBinary, + ConditionalExpression: checkConditional, + VariableDeclarator: checkVar, + + PropertyDefinition(node) { + if (!node.value) { + return; + } + + /* + * Because of computed properties and type annotations, some + * tokens may exist between `node.key` and `=`. + * Therefore, find the `=` from the right. + */ + const operatorToken = sourceCode.getTokenBefore( + node.value, + isEqToken, + ); + const leftToken = sourceCode.getTokenBefore(operatorToken); + const rightToken = sourceCode.getTokenAfter(operatorToken); + + if ( + !sourceCode.isSpaceBetweenTokens( + leftToken, + operatorToken, + ) || + !sourceCode.isSpaceBetweenTokens(operatorToken, rightToken) + ) { + report(node, operatorToken); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-unary-ops.js b/node_modules/eslint/lib/rules/space-unary-ops.js new file mode 100644 index 00000000..2ccc32b0 --- /dev/null +++ b/node_modules/eslint/lib/rules/space-unary-ops.js @@ -0,0 +1,400 @@ +/** + * @fileoverview This rule should require or disallow spaces before or after unary operations. + * @author Marcin Kumorek + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "space-unary-ops", + url: "https://eslint.style/rules/js/space-unary-ops", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing before or after unary operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-unary-ops", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + words: { + type: "boolean", + default: true, + }, + nonwords: { + type: "boolean", + default: false, + }, + overrides: { + type: "object", + additionalProperties: { + type: "boolean", + }, + }, + }, + additionalProperties: false, + }, + ], + messages: { + unexpectedBefore: + "Unexpected space before unary operator '{{operator}}'.", + unexpectedAfter: + "Unexpected space after unary operator '{{operator}}'.", + unexpectedAfterWord: + "Unexpected space after unary word operator '{{word}}'.", + wordOperator: + "Unary word operator '{{word}}' must be followed by whitespace.", + operator: + "Unary operator '{{operator}}' must be followed by whitespace.", + beforeUnaryExpressions: + "Space is required before unary expressions '{{token}}'.", + }, + }, + + create(context) { + const options = context.options[0] || { words: true, nonwords: false }; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the node is the first "!" in a "!!" convert to Boolean expression + * @param {ASTnode} node AST node + * @returns {boolean} Whether or not the node is first "!" in "!!" + */ + function isFirstBangInBangBangExpression(node) { + return ( + node && + node.type === "UnaryExpression" && + node.argument.operator === "!" && + node.argument && + node.argument.type === "UnaryExpression" && + node.argument.operator === "!" + ); + } + + /** + * Checks if an override exists for a given operator. + * @param {string} operator Operator + * @returns {boolean} Whether or not an override has been provided for the operator + */ + function overrideExistsForOperator(operator) { + return ( + options.overrides && Object.hasOwn(options.overrides, operator) + ); + } + + /** + * Gets the value that the override was set to for this operator + * @param {string} operator Operator + * @returns {boolean} Whether or not an override enforces a space with this operator + */ + function overrideEnforcesSpaces(operator) { + return options.overrides[operator]; + } + + /** + * Verify Unary Word Operator has spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ + function verifyWordHasSpaces(node, firstToken, secondToken, word) { + if (secondToken.range[0] === firstToken.range[1]) { + context.report({ + node, + messageId: "wordOperator", + data: { + word, + }, + fix(fixer) { + return fixer.insertTextAfter(firstToken, " "); + }, + }); + } + } + + /** + * Verify Unary Word Operator doesn't have spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ + function verifyWordDoesntHaveSpaces( + node, + firstToken, + secondToken, + word, + ) { + if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) { + if (secondToken.range[0] > firstToken.range[1]) { + context.report({ + node, + messageId: "unexpectedAfterWord", + data: { + word, + }, + fix(fixer) { + return fixer.removeRange([ + firstToken.range[1], + secondToken.range[0], + ]); + }, + }); + } + } + } + + /** + * Check Unary Word Operators for spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ + function checkUnaryWordOperatorForSpaces( + node, + firstToken, + secondToken, + word, + ) { + if (overrideExistsForOperator(word)) { + if (overrideEnforcesSpaces(word)) { + verifyWordHasSpaces(node, firstToken, secondToken, word); + } else { + verifyWordDoesntHaveSpaces( + node, + firstToken, + secondToken, + word, + ); + } + } else if (options.words) { + verifyWordHasSpaces(node, firstToken, secondToken, word); + } else { + verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); + } + } + + /** + * Verifies YieldExpressions satisfy spacing requirements + * @param {ASTnode} node AST node + * @returns {void} + */ + function checkForSpacesAfterYield(node) { + const tokens = sourceCode.getFirstTokens(node, 3), + word = "yield"; + + if (!node.argument || node.delegate) { + return; + } + + checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], word); + } + + /** + * Verifies AwaitExpressions satisfy spacing requirements + * @param {ASTNode} node AwaitExpression AST node + * @returns {void} + */ + function checkForSpacesAfterAwait(node) { + const tokens = sourceCode.getFirstTokens(node, 3); + + checkUnaryWordOperatorForSpaces( + node, + tokens[0], + tokens[1], + "await", + ); + } + + /** + * Verifies UnaryExpression, UpdateExpression and NewExpression have spaces before or after the operator + * @param {ASTnode} node AST node + * @param {Object} firstToken First token in the expression + * @param {Object} secondToken Second token in the expression + * @returns {void} + */ + function verifyNonWordsHaveSpaces(node, firstToken, secondToken) { + if (node.prefix) { + if (isFirstBangInBangBangExpression(node)) { + return; + } + if (firstToken.range[1] === secondToken.range[0]) { + context.report({ + node, + messageId: "operator", + data: { + operator: firstToken.value, + }, + fix(fixer) { + return fixer.insertTextAfter(firstToken, " "); + }, + }); + } + } else { + if (firstToken.range[1] === secondToken.range[0]) { + context.report({ + node, + messageId: "beforeUnaryExpressions", + data: { + token: secondToken.value, + }, + fix(fixer) { + return fixer.insertTextBefore(secondToken, " "); + }, + }); + } + } + } + + /** + * Verifies UnaryExpression, UpdateExpression and NewExpression don't have spaces before or after the operator + * @param {ASTnode} node AST node + * @param {Object} firstToken First token in the expression + * @param {Object} secondToken Second token in the expression + * @returns {void} + */ + function verifyNonWordsDontHaveSpaces(node, firstToken, secondToken) { + if (node.prefix) { + if (secondToken.range[0] > firstToken.range[1]) { + context.report({ + node, + messageId: "unexpectedAfter", + data: { + operator: firstToken.value, + }, + fix(fixer) { + if ( + astUtils.canTokensBeAdjacent( + firstToken, + secondToken, + ) + ) { + return fixer.removeRange([ + firstToken.range[1], + secondToken.range[0], + ]); + } + return null; + }, + }); + } + } else { + if (secondToken.range[0] > firstToken.range[1]) { + context.report({ + node, + messageId: "unexpectedBefore", + data: { + operator: secondToken.value, + }, + fix(fixer) { + return fixer.removeRange([ + firstToken.range[1], + secondToken.range[0], + ]); + }, + }); + } + } + } + + /** + * Verifies UnaryExpression, UpdateExpression and NewExpression satisfy spacing requirements + * @param {ASTnode} node AST node + * @returns {void} + */ + function checkForSpaces(node) { + const tokens = + node.type === "UpdateExpression" && !node.prefix + ? sourceCode.getLastTokens(node, 2) + : sourceCode.getFirstTokens(node, 2); + const firstToken = tokens[0]; + const secondToken = tokens[1]; + + if ( + (node.type === "NewExpression" || node.prefix) && + firstToken.type === "Keyword" + ) { + checkUnaryWordOperatorForSpaces( + node, + firstToken, + secondToken, + firstToken.value, + ); + return; + } + + const operator = node.prefix ? tokens[0].value : tokens[1].value; + + if (overrideExistsForOperator(operator)) { + if (overrideEnforcesSpaces(operator)) { + verifyNonWordsHaveSpaces(node, firstToken, secondToken); + } else { + verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); + } + } else if (options.nonwords) { + verifyNonWordsHaveSpaces(node, firstToken, secondToken); + } else { + verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + UnaryExpression: checkForSpaces, + UpdateExpression: checkForSpaces, + NewExpression: checkForSpaces, + YieldExpression: checkForSpacesAfterYield, + AwaitExpression: checkForSpacesAfterAwait, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/spaced-comment.js b/node_modules/eslint/lib/rules/spaced-comment.js new file mode 100644 index 00000000..a4624ec1 --- /dev/null +++ b/node_modules/eslint/lib/rules/spaced-comment.js @@ -0,0 +1,447 @@ +/** + * @fileoverview Source code for spaced-comments rule + * @author Gyandeep Singh + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const escapeRegExp = require("escape-string-regexp"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Escapes the control characters of a given string. + * @param {string} s A string to escape. + * @returns {string} An escaped string. + */ +function escape(s) { + return `(?:${escapeRegExp(s)})`; +} + +/** + * Escapes the control characters of a given string. + * And adds a repeat flag. + * @param {string} s A string to escape. + * @returns {string} An escaped string. + */ +function escapeAndRepeat(s) { + return `${escape(s)}+`; +} + +/** + * Parses `markers` option. + * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments. + * @param {string[]} [markers] A marker list. + * @returns {string[]} A marker list. + */ +function parseMarkersOption(markers) { + // `*` is a marker for JSDoc comments. + if (!markers.includes("*")) { + return markers.concat("*"); + } + + return markers; +} + +/** + * Creates string pattern for exceptions. + * Generated pattern: + * + * 1. A space or an exception pattern sequence. + * @param {string[]} exceptions An exception pattern list. + * @returns {string} A regular expression string for exceptions. + */ +function createExceptionsPattern(exceptions) { + let pattern = ""; + + /* + * A space or an exception pattern sequence. + * [] ==> "\s" + * ["-"] ==> "(?:\s|\-+$)" + * ["-", "="] ==> "(?:\s|(?:\-+|=+)$)" + * ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24) + */ + if (exceptions.length === 0) { + // a space. + pattern += "\\s"; + } else { + // a space or... + pattern += "(?:\\s|"; + + if (exceptions.length === 1) { + // a sequence of the exception pattern. + pattern += escapeAndRepeat(exceptions[0]); + } else { + // a sequence of one of the exception patterns. + pattern += "(?:"; + pattern += exceptions.map(escapeAndRepeat).join("|"); + pattern += ")"; + } + pattern += `(?:$|[${Array.from(astUtils.LINEBREAKS).join("")}]))`; + } + + return pattern; +} + +/** + * Creates RegExp object for `always` mode. + * Generated pattern for beginning of comment: + * + * 1. First, a marker or nothing. + * 2. Next, a space or an exception pattern sequence. + * @param {string[]} markers A marker list. + * @param {string[]} exceptions An exception pattern list. + * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode. + */ +function createAlwaysStylePattern(markers, exceptions) { + let pattern = "^"; + + /* + * A marker or nothing. + * ["*"] ==> "\*?" + * ["*", "!"] ==> "(?:\*|!)?" + * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F + */ + if (markers.length === 1) { + // the marker. + pattern += escape(markers[0]); + } else { + // one of markers. + pattern += "(?:"; + pattern += markers.map(escape).join("|"); + pattern += ")"; + } + + pattern += "?"; // or nothing. + pattern += createExceptionsPattern(exceptions); + + return new RegExp(pattern, "u"); +} + +/** + * Creates RegExp object for `never` mode. + * Generated pattern for beginning of comment: + * + * 1. First, a marker or nothing (captured). + * 2. Next, a space or a tab. + * @param {string[]} markers A marker list. + * @returns {RegExp} A RegExp object for `never` mode. + */ +function createNeverStylePattern(markers) { + const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`; + + return new RegExp(pattern, "u"); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "spaced-comment", + url: "https://eslint.style/rules/js/spaced-comment", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: + "Enforce consistent spacing after the `//` or `/*` in a comment", + recommended: false, + url: "https://eslint.org/docs/latest/rules/spaced-comment", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string", + }, + }, + markers: { + type: "array", + items: { + type: "string", + }, + }, + line: { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string", + }, + }, + markers: { + type: "array", + items: { + type: "string", + }, + }, + }, + additionalProperties: false, + }, + block: { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string", + }, + }, + markers: { + type: "array", + items: { + type: "string", + }, + }, + balanced: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedSpaceAfterMarker: + "Unexpected space or tab after marker ({{refChar}}) in comment.", + expectedExceptionAfter: + "Expected exception block, space or tab after '{{refChar}}' in comment.", + unexpectedSpaceBefore: + "Unexpected space or tab before '*/' in comment.", + unexpectedSpaceAfter: + "Unexpected space or tab after '{{refChar}}' in comment.", + expectedSpaceBefore: + "Expected space or tab before '*/' in comment.", + expectedSpaceAfter: + "Expected space or tab after '{{refChar}}' in comment.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + // Unless the first option is never, require a space + const requireSpace = context.options[0] !== "never"; + + /* + * Parse the second options. + * If markers don't include `"*"`, it's added automatically for JSDoc + * comments. + */ + const config = context.options[1] || {}; + const balanced = config.block && config.block.balanced; + + const styleRules = ["block", "line"].reduce((rule, type) => { + const markers = parseMarkersOption( + (config[type] && config[type].markers) || config.markers || [], + ); + const exceptions = + (config[type] && config[type].exceptions) || + config.exceptions || + []; + const endNeverPattern = "[ \t]+$"; + + // Create RegExp object for valid patterns. + rule[type] = { + beginRegex: requireSpace + ? createAlwaysStylePattern(markers, exceptions) + : createNeverStylePattern(markers), + endRegex: + balanced && requireSpace + ? new RegExp( + `${createExceptionsPattern(exceptions)}$`, + "u", + ) + : new RegExp(endNeverPattern, "u"), + hasExceptions: exceptions.length > 0, + captureMarker: new RegExp( + `^(${markers.map(escape).join("|")})`, + "u", + ), + markers: new Set(markers), + }; + + return rule; + }, {}); + + /** + * Reports a beginning spacing error with an appropriate message. + * @param {ASTNode} node A comment node to check. + * @param {string} messageId An error message to report. + * @param {Array} match An array of match results for markers. + * @param {string} refChar Character used for reference in the error message. + * @returns {void} + */ + function reportBegin(node, messageId, match, refChar) { + const type = node.type.toLowerCase(), + commentIdentifier = type === "block" ? "/*" : "//"; + + context.report({ + node, + fix(fixer) { + const start = node.range[0]; + let end = start + 2; + + if (requireSpace) { + if (match) { + end += match[0].length; + } + return fixer.insertTextAfterRange([start, end], " "); + } + end += match[0].length; + return fixer.replaceTextRange( + [start, end], + commentIdentifier + (match[1] ? match[1] : ""), + ); + }, + messageId, + data: { refChar }, + }); + } + + /** + * Reports an ending spacing error with an appropriate message. + * @param {ASTNode} node A comment node to check. + * @param {string} messageId An error message to report. + * @param {string} match An array of the matched whitespace characters. + * @returns {void} + */ + function reportEnd(node, messageId, match) { + context.report({ + node, + fix(fixer) { + if (requireSpace) { + return fixer.insertTextAfterRange( + [node.range[0], node.range[1] - 2], + " ", + ); + } + const end = node.range[1] - 2, + start = end - match[0].length; + + return fixer.replaceTextRange([start, end], ""); + }, + messageId, + }); + } + + /** + * Reports a given comment if it's invalid. + * @param {ASTNode} node a comment node to check. + * @returns {void} + */ + function checkCommentForSpace(node) { + const type = node.type.toLowerCase(), + rule = styleRules[type], + commentIdentifier = type === "block" ? "/*" : "//"; + + // Ignores empty comments and comments that consist only of a marker. + if (node.value.length === 0 || rule.markers.has(node.value)) { + return; + } + + const beginMatch = rule.beginRegex.exec(node.value); + const endMatch = rule.endRegex.exec(node.value); + + // Checks. + if (requireSpace) { + if (!beginMatch) { + const hasMarker = rule.captureMarker.exec(node.value); + const marker = hasMarker + ? commentIdentifier + hasMarker[0] + : commentIdentifier; + + if (rule.hasExceptions) { + reportBegin( + node, + "expectedExceptionAfter", + hasMarker, + marker, + ); + } else { + reportBegin( + node, + "expectedSpaceAfter", + hasMarker, + marker, + ); + } + } + + if (balanced && type === "block" && !endMatch) { + reportEnd(node, "expectedSpaceBefore"); + } + } else { + if (beginMatch) { + if (!beginMatch[1]) { + reportBegin( + node, + "unexpectedSpaceAfter", + beginMatch, + commentIdentifier, + ); + } else { + reportBegin( + node, + "unexpectedSpaceAfterMarker", + beginMatch, + beginMatch[1], + ); + } + } + + if (balanced && type === "block" && endMatch) { + reportEnd(node, "unexpectedSpaceBefore", endMatch); + } + } + } + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments + .filter(token => token.type !== "Shebang") + .forEach(checkCommentForSpace); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/strict.js b/node_modules/eslint/lib/rules/strict.js new file mode 100644 index 00000000..a427139a --- /dev/null +++ b/node_modules/eslint/lib/rules/strict.js @@ -0,0 +1,313 @@ +/** + * @fileoverview Rule to control usage of strict mode directives. + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets all of the Use Strict Directives in the Directive Prologue of a group of + * statements. + * @param {ASTNode[]} statements Statements in the program or function body. + * @returns {ASTNode[]} All of the Use Strict Directives. + */ +function getUseStrictDirectives(statements) { + const directives = []; + + for (let i = 0; i < statements.length; i++) { + const statement = statements[i]; + + if ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + statement.expression.value === "use strict" + ) { + directives[i] = statement; + } else { + break; + } + } + + return directives; +} + +/** + * Checks whether a given parameter is a simple parameter. + * @param {ASTNode} node A pattern node to check. + * @returns {boolean} `true` if the node is an Identifier node. + */ +function isSimpleParameter(node) { + return node.type === "Identifier"; +} + +/** + * Checks whether a given parameter list is a simple parameter list. + * @param {ASTNode[]} params A parameter list to check. + * @returns {boolean} `true` if the every parameter is an Identifier node. + */ +function isSimpleParameterList(params) { + return params.every(isSimpleParameter); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["safe"], + + docs: { + description: "Require or disallow strict mode directives", + recommended: false, + url: "https://eslint.org/docs/latest/rules/strict", + }, + + schema: [ + { + enum: ["never", "global", "function", "safe"], + }, + ], + + fixable: "code", + messages: { + function: "Use the function form of 'use strict'.", + global: "Use the global form of 'use strict'.", + multiple: "Multiple 'use strict' directives.", + never: "Strict mode is not permitted.", + unnecessary: "Unnecessary 'use strict' directive.", + module: "'use strict' is unnecessary inside of modules.", + implied: + "'use strict' is unnecessary when implied strict mode is enabled.", + unnecessaryInClasses: + "'use strict' is unnecessary inside of classes.", + nonSimpleParameterList: + "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.", + wrap: "Wrap {{name}} in a function with 'use strict' directive.", + }, + }, + + create(context) { + const ecmaFeatures = context.parserOptions.ecmaFeatures || {}, + scopes = [], + classScopes = []; + let [mode] = context.options; + + if (ecmaFeatures.impliedStrict) { + mode = "implied"; + } else if (mode === "safe") { + mode = + ecmaFeatures.globalReturn || + context.languageOptions.sourceType === "commonjs" + ? "global" + : "function"; + } + + /** + * Determines whether a reported error should be fixed, depending on the error type. + * @param {string} errorType The type of error + * @returns {boolean} `true` if the reported error should be fixed + */ + function shouldFix(errorType) { + return ( + errorType === "multiple" || + errorType === "unnecessary" || + errorType === "module" || + errorType === "implied" || + errorType === "unnecessaryInClasses" + ); + } + + /** + * Gets a fixer function to remove a given 'use strict' directive. + * @param {ASTNode} node The directive that should be removed + * @returns {Function} A fixer function + */ + function getFixFunction(node) { + return fixer => fixer.remove(node); + } + + /** + * Report a slice of an array of nodes with a given message. + * @param {ASTNode[]} nodes Nodes. + * @param {string} start Index to start from. + * @param {string} end Index to end before. + * @param {string} messageId Message to display. + * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) + * @returns {void} + */ + function reportSlice(nodes, start, end, messageId, fix) { + nodes.slice(start, end).forEach(node => { + context.report({ + node, + messageId, + fix: fix ? getFixFunction(node) : null, + }); + }); + } + + /** + * Report all nodes in an array with a given message. + * @param {ASTNode[]} nodes Nodes. + * @param {string} messageId Message id to display. + * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) + * @returns {void} + */ + function reportAll(nodes, messageId, fix) { + reportSlice(nodes, 0, nodes.length, messageId, fix); + } + + /** + * Report all nodes in an array, except the first, with a given message. + * @param {ASTNode[]} nodes Nodes. + * @param {string} messageId Message id to display. + * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) + * @returns {void} + */ + function reportAllExceptFirst(nodes, messageId, fix) { + reportSlice(nodes, 1, nodes.length, messageId, fix); + } + + /** + * Entering a function in 'function' mode pushes a new nested scope onto the + * stack. The new scope is true if the nested function is strict mode code. + * @param {ASTNode} node The function declaration or expression. + * @param {ASTNode[]} useStrictDirectives The Use Strict Directives of the node. + * @returns {void} + */ + function enterFunctionInFunctionMode(node, useStrictDirectives) { + const isInClass = classScopes.length > 0, + isParentGlobal = + scopes.length === 0 && classScopes.length === 0, + isParentStrict = scopes.length > 0 && scopes.at(-1), + isStrict = useStrictDirectives.length > 0; + + if (isStrict) { + if (!isSimpleParameterList(node.params)) { + context.report({ + node: useStrictDirectives[0], + messageId: "nonSimpleParameterList", + }); + } else if (isParentStrict) { + context.report({ + node: useStrictDirectives[0], + messageId: "unnecessary", + fix: getFixFunction(useStrictDirectives[0]), + }); + } else if (isInClass) { + context.report({ + node: useStrictDirectives[0], + messageId: "unnecessaryInClasses", + fix: getFixFunction(useStrictDirectives[0]), + }); + } + + reportAllExceptFirst(useStrictDirectives, "multiple", true); + } else if (isParentGlobal) { + if (isSimpleParameterList(node.params)) { + context.report({ node, messageId: "function" }); + } else { + context.report({ + node, + messageId: "wrap", + data: { name: astUtils.getFunctionNameWithKind(node) }, + }); + } + } + + scopes.push(isParentStrict || isStrict); + } + + /** + * Exiting a function in 'function' mode pops its scope off the stack. + * @returns {void} + */ + function exitFunctionInFunctionMode() { + scopes.pop(); + } + + /** + * Enter a function and either: + * - Push a new nested scope onto the stack (in 'function' mode). + * - Report all the Use Strict Directives (in the other modes). + * @param {ASTNode} node The function declaration or expression. + * @returns {void} + */ + function enterFunction(node) { + const isBlock = node.body.type === "BlockStatement", + useStrictDirectives = isBlock + ? getUseStrictDirectives(node.body.body) + : []; + + if (mode === "function") { + enterFunctionInFunctionMode(node, useStrictDirectives); + } else if (useStrictDirectives.length > 0) { + if (isSimpleParameterList(node.params)) { + reportAll(useStrictDirectives, mode, shouldFix(mode)); + } else { + context.report({ + node: useStrictDirectives[0], + messageId: "nonSimpleParameterList", + }); + reportAllExceptFirst(useStrictDirectives, "multiple", true); + } + } + } + + const rule = { + Program(node) { + const useStrictDirectives = getUseStrictDirectives(node.body); + + if (node.sourceType === "module") { + mode = "module"; + } + + if (mode === "global") { + if ( + node.body.length > 0 && + useStrictDirectives.length === 0 + ) { + context.report({ node, messageId: "global" }); + } + reportAllExceptFirst(useStrictDirectives, "multiple", true); + } else { + reportAll(useStrictDirectives, mode, shouldFix(mode)); + } + }, + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression: enterFunction, + }; + + if (mode === "function") { + Object.assign(rule, { + // Inside of class bodies are always strict mode. + ClassBody() { + classScopes.push(true); + }, + "ClassBody:exit"() { + classScopes.pop(); + }, + + "FunctionDeclaration:exit": exitFunctionInFunctionMode, + "FunctionExpression:exit": exitFunctionInFunctionMode, + "ArrowFunctionExpression:exit": exitFunctionInFunctionMode, + }); + } + + return rule; + }, +}; diff --git a/node_modules/eslint/lib/rules/switch-colon-spacing.js b/node_modules/eslint/lib/rules/switch-colon-spacing.js new file mode 100644 index 00000000..e6878373 --- /dev/null +++ b/node_modules/eslint/lib/rules/switch-colon-spacing.js @@ -0,0 +1,158 @@ +/** + * @fileoverview Rule to enforce spacing around colons of switch statements. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "switch-colon-spacing", + url: "https://eslint.style/rules/js/switch-colon-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce spacing around colons of switch statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/switch-colon-spacing", + }, + + schema: [ + { + type: "object", + properties: { + before: { type: "boolean", default: false }, + after: { type: "boolean", default: true }, + }, + additionalProperties: false, + }, + ], + fixable: "whitespace", + messages: { + expectedBefore: "Expected space(s) before this colon.", + expectedAfter: "Expected space(s) after this colon.", + unexpectedBefore: "Unexpected space(s) before this colon.", + unexpectedAfter: "Unexpected space(s) after this colon.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = context.options[0] || {}; + const beforeSpacing = options.before === true; // false by default + const afterSpacing = options.after !== false; // true by default + + /** + * Check whether the spacing between the given 2 tokens is valid or not. + * @param {Token} left The left token to check. + * @param {Token} right The right token to check. + * @param {boolean} expected The expected spacing to check. `true` if there should be a space. + * @returns {boolean} `true` if the spacing between the tokens is valid. + */ + function isValidSpacing(left, right, expected) { + return ( + astUtils.isClosingBraceToken(right) || + !astUtils.isTokenOnSameLine(left, right) || + sourceCode.isSpaceBetweenTokens(left, right) === expected + ); + } + + /** + * Check whether comments exist between the given 2 tokens. + * @param {Token} left The left token to check. + * @param {Token} right The right token to check. + * @returns {boolean} `true` if comments exist between the given 2 tokens. + */ + function commentsExistBetween(left, right) { + return ( + sourceCode.getFirstTokenBetween(left, right, { + includeComments: true, + filter: astUtils.isCommentToken, + }) !== null + ); + } + + /** + * Fix the spacing between the given 2 tokens. + * @param {RuleFixer} fixer The fixer to fix. + * @param {Token} left The left token of fix range. + * @param {Token} right The right token of fix range. + * @param {boolean} spacing The spacing style. `true` if there should be a space. + * @returns {Fix|null} The fix object. + */ + function fix(fixer, left, right, spacing) { + if (commentsExistBetween(left, right)) { + return null; + } + if (spacing) { + return fixer.insertTextAfter(left, " "); + } + return fixer.removeRange([left.range[1], right.range[0]]); + } + + return { + SwitchCase(node) { + const colonToken = astUtils.getSwitchCaseColonToken( + node, + sourceCode, + ); + const beforeToken = sourceCode.getTokenBefore(colonToken); + const afterToken = sourceCode.getTokenAfter(colonToken); + + if (!isValidSpacing(beforeToken, colonToken, beforeSpacing)) { + context.report({ + node, + loc: colonToken.loc, + messageId: beforeSpacing + ? "expectedBefore" + : "unexpectedBefore", + fix: fixer => + fix(fixer, beforeToken, colonToken, beforeSpacing), + }); + } + if (!isValidSpacing(colonToken, afterToken, afterSpacing)) { + context.report({ + node, + loc: colonToken.loc, + messageId: afterSpacing + ? "expectedAfter" + : "unexpectedAfter", + fix: fixer => + fix(fixer, colonToken, afterToken, afterSpacing), + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/symbol-description.js b/node_modules/eslint/lib/rules/symbol-description.js new file mode 100644 index 00000000..054c16be --- /dev/null +++ b/node_modules/eslint/lib/rules/symbol-description.js @@ -0,0 +1,70 @@ +/** + * @fileoverview Rule to enforce description with the `Symbol` object + * @author Jarek Rencz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require symbol descriptions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/symbol-description", + }, + fixable: null, + schema: [], + messages: { + expected: "Expected Symbol to have a description.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Reports if node does not conform the rule in case rule is set to + * report missing description + * @param {ASTNode} node A CallExpression node to check. + * @returns {void} + */ + function checkArgument(node) { + if (node.arguments.length === 0) { + context.report({ + node, + messageId: "expected", + }); + } + } + + return { + "Program:exit"(node) { + const scope = sourceCode.getScope(node); + const variable = astUtils.getVariableByName(scope, "Symbol"); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(reference => { + const idNode = reference.identifier; + + if (astUtils.isCallee(idNode)) { + checkArgument(idNode.parent); + } + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/template-curly-spacing.js b/node_modules/eslint/lib/rules/template-curly-spacing.js new file mode 100644 index 00000000..169f712e --- /dev/null +++ b/node_modules/eslint/lib/rules/template-curly-spacing.js @@ -0,0 +1,168 @@ +/** + * @fileoverview Rule to enforce spacing around embedded expressions of template strings + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "template-curly-spacing", + url: "https://eslint.style/rules/js/template-curly-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow spacing around embedded expressions of template strings", + recommended: false, + url: "https://eslint.org/docs/latest/rules/template-curly-spacing", + }, + + fixable: "whitespace", + + schema: [{ enum: ["always", "never"] }], + messages: { + expectedBefore: "Expected space(s) before '}'.", + expectedAfter: "Expected space(s) after '${'.", + unexpectedBefore: "Unexpected space(s) before '}'.", + unexpectedAfter: "Unexpected space(s) after '${'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const always = context.options[0] === "always"; + + /** + * Checks spacing before `}` of a given token. + * @param {Token} token A token to check. This is a Template token. + * @returns {void} + */ + function checkSpacingBefore(token) { + if (!token.value.startsWith("}")) { + return; // starts with a backtick, this is the first template element in the template literal + } + + const prevToken = sourceCode.getTokenBefore(token, { + includeComments: true, + }), + hasSpace = sourceCode.isSpaceBetween(prevToken, token); + + if (!astUtils.isTokenOnSameLine(prevToken, token)) { + return; + } + + if (always && !hasSpace) { + context.report({ + loc: { + start: token.loc.start, + end: { + line: token.loc.start.line, + column: token.loc.start.column + 1, + }, + }, + messageId: "expectedBefore", + fix: fixer => fixer.insertTextBefore(token, " "), + }); + } + + if (!always && hasSpace) { + context.report({ + loc: { + start: prevToken.loc.end, + end: token.loc.start, + }, + messageId: "unexpectedBefore", + fix: fixer => + fixer.removeRange([prevToken.range[1], token.range[0]]), + }); + } + } + + /** + * Checks spacing after `${` of a given token. + * @param {Token} token A token to check. This is a Template token. + * @returns {void} + */ + function checkSpacingAfter(token) { + if (!token.value.endsWith("${")) { + return; // ends with a backtick, this is the last template element in the template literal + } + + const nextToken = sourceCode.getTokenAfter(token, { + includeComments: true, + }), + hasSpace = sourceCode.isSpaceBetween(token, nextToken); + + if (!astUtils.isTokenOnSameLine(token, nextToken)) { + return; + } + + if (always && !hasSpace) { + context.report({ + loc: { + start: { + line: token.loc.end.line, + column: token.loc.end.column - 2, + }, + end: token.loc.end, + }, + messageId: "expectedAfter", + fix: fixer => fixer.insertTextAfter(token, " "), + }); + } + + if (!always && hasSpace) { + context.report({ + loc: { + start: token.loc.end, + end: nextToken.loc.start, + }, + messageId: "unexpectedAfter", + fix: fixer => + fixer.removeRange([token.range[1], nextToken.range[0]]), + }); + } + } + + return { + TemplateElement(node) { + const token = sourceCode.getFirstToken(node); + + checkSpacingBefore(token); + checkSpacingAfter(token); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/template-tag-spacing.js b/node_modules/eslint/lib/rules/template-tag-spacing.js new file mode 100644 index 00000000..b9115a9a --- /dev/null +++ b/node_modules/eslint/lib/rules/template-tag-spacing.js @@ -0,0 +1,121 @@ +/** + * @fileoverview Rule to check spacing between template tags and their literals + * @author Jonathan Wilsson + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "template-tag-spacing", + url: "https://eslint.style/rules/js/template-tag-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow spacing between template tags and their literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/template-tag-spacing", + }, + + fixable: "whitespace", + + schema: [{ enum: ["always", "never"] }], + messages: { + unexpected: + "Unexpected space between template tag and template literal.", + missing: "Missing space between template tag and template literal.", + }, + }, + + create(context) { + const never = context.options[0] !== "always"; + const sourceCode = context.sourceCode; + + /** + * Check if a space is present between a template tag and its literal + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkSpacing(node) { + const tagToken = sourceCode.getTokenBefore(node.quasi); + const literalToken = sourceCode.getFirstToken(node.quasi); + const hasWhitespace = sourceCode.isSpaceBetweenTokens( + tagToken, + literalToken, + ); + + if (never && hasWhitespace) { + context.report({ + node, + loc: { + start: tagToken.loc.end, + end: literalToken.loc.start, + }, + messageId: "unexpected", + fix(fixer) { + const comments = sourceCode.getCommentsBefore( + node.quasi, + ); + + // Don't fix anything if there's a single line comment after the template tag + if (comments.some(comment => comment.type === "Line")) { + return null; + } + + return fixer.replaceTextRange( + [tagToken.range[1], literalToken.range[0]], + comments.reduce( + (text, comment) => + text + sourceCode.getText(comment), + "", + ), + ); + }, + }); + } else if (!never && !hasWhitespace) { + context.report({ + node, + loc: { + start: node.loc.start, + end: literalToken.loc.start, + }, + messageId: "missing", + fix(fixer) { + return fixer.insertTextAfter(tagToken, " "); + }, + }); + } + } + + return { + TaggedTemplateExpression: checkSpacing, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/unicode-bom.js b/node_modules/eslint/lib/rules/unicode-bom.js new file mode 100644 index 00000000..7b054489 --- /dev/null +++ b/node_modules/eslint/lib/rules/unicode-bom.js @@ -0,0 +1,73 @@ +/** + * @fileoverview Require or disallow Unicode BOM + * @author Andrew Johnston + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + defaultOptions: ["never"], + + docs: { + description: "Require or disallow Unicode byte order mark (BOM)", + recommended: false, + url: "https://eslint.org/docs/latest/rules/unicode-bom", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + ], + messages: { + expected: "Expected Unicode BOM (Byte Order Mark).", + unexpected: "Unexpected Unicode BOM (Byte Order Mark).", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkUnicodeBOM(node) { + const sourceCode = context.sourceCode, + location = { column: 0, line: 1 }; + const [requireBOM] = context.options; + + if (!sourceCode.hasBOM && requireBOM === "always") { + context.report({ + node, + loc: location, + messageId: "expected", + fix(fixer) { + return fixer.insertTextBeforeRange( + [0, 1], + "\uFEFF", + ); + }, + }); + } else if (sourceCode.hasBOM && requireBOM === "never") { + context.report({ + node, + loc: location, + messageId: "unexpected", + fix(fixer) { + return fixer.removeRange([-1, 0]); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/use-isnan.js b/node_modules/eslint/lib/rules/use-isnan.js new file mode 100644 index 00000000..2c73acf7 --- /dev/null +++ b/node_modules/eslint/lib/rules/use-isnan.js @@ -0,0 +1,268 @@ +/** + * @fileoverview Rule to flag comparisons to the value NaN + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if the given node is a NaN `Identifier` node. + * @param {ASTNode|null} node The node to check. + * @returns {boolean} `true` if the node is 'NaN' identifier. + */ +function isNaNIdentifier(node) { + if (!node) { + return false; + } + + const nodeToCheck = + node.type === "SequenceExpression" ? node.expressions.at(-1) : node; + + return ( + astUtils.isSpecificId(nodeToCheck, "NaN") || + astUtils.isSpecificMemberAccess(nodeToCheck, "Number", "NaN") + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "problem", + + docs: { + description: "Require calls to `isNaN()` when checking for `NaN`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/use-isnan", + }, + + schema: [ + { + type: "object", + properties: { + enforceForSwitchCase: { + type: "boolean", + }, + enforceForIndexOf: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + enforceForIndexOf: false, + enforceForSwitchCase: true, + }, + ], + + messages: { + comparisonWithNaN: "Use the isNaN function to compare with NaN.", + switchNaN: + "'switch(NaN)' can never match a case clause. Use Number.isNaN instead of the switch.", + caseNaN: + "'case NaN' can never match. Use Number.isNaN before the switch.", + indexOfNaN: + "Array prototype method '{{ methodName }}' cannot find NaN.", + replaceWithIsNaN: "Replace with Number.isNaN.", + replaceWithCastingAndIsNaN: + "Replace with Number.isNaN and cast to a Number.", + replaceWithFindIndex: + "Replace with Array.prototype.{{ methodName }}.", + }, + }, + + create(context) { + const [{ enforceForIndexOf, enforceForSwitchCase }] = context.options; + const sourceCode = context.sourceCode; + + const fixableOperators = new Set(["==", "===", "!=", "!=="]); + const castableOperators = new Set(["==", "!="]); + + /** + * Get a fixer for a binary expression that compares to NaN. + * @param {ASTNode} node The node to fix. + * @param {function(string): string} wrapValue A function that wraps the compared value with a fix. + * @returns {function(Fixer): Fix} The fixer function. + */ + function getBinaryExpressionFixer(node, wrapValue) { + return fixer => { + const comparedValue = isNaNIdentifier(node.left) + ? node.right + : node.left; + const shouldWrap = comparedValue.type === "SequenceExpression"; + const shouldNegate = node.operator[0] === "!"; + + const negation = shouldNegate ? "!" : ""; + let comparedValueText = sourceCode.getText(comparedValue); + + if (shouldWrap) { + comparedValueText = `(${comparedValueText})`; + } + + const fixedValue = wrapValue(comparedValueText); + + return fixer.replaceText(node, `${negation}${fixedValue}`); + }; + } + + /** + * Checks the given `BinaryExpression` node for `foo === NaN` and other comparisons. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkBinaryExpression(node) { + if ( + /^(?:[<>]|[!=]=)=?$/u.test(node.operator) && + (isNaNIdentifier(node.left) || isNaNIdentifier(node.right)) + ) { + const suggestedFixes = []; + const NaNNode = isNaNIdentifier(node.left) + ? node.left + : node.right; + + const isSequenceExpression = + NaNNode.type === "SequenceExpression"; + const isSuggestable = + fixableOperators.has(node.operator) && + !isSequenceExpression; + const isCastable = castableOperators.has(node.operator); + + if (isSuggestable) { + suggestedFixes.push({ + messageId: "replaceWithIsNaN", + fix: getBinaryExpressionFixer( + node, + value => `Number.isNaN(${value})`, + ), + }); + + if (isCastable) { + suggestedFixes.push({ + messageId: "replaceWithCastingAndIsNaN", + fix: getBinaryExpressionFixer( + node, + value => `Number.isNaN(Number(${value}))`, + ), + }); + } + } + + context.report({ + node, + messageId: "comparisonWithNaN", + suggest: suggestedFixes, + }); + } + } + + /** + * Checks the discriminant and all case clauses of the given `SwitchStatement` node for `switch(NaN)` and `case NaN:` + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkSwitchStatement(node) { + if (isNaNIdentifier(node.discriminant)) { + context.report({ node, messageId: "switchNaN" }); + } + + for (const switchCase of node.cases) { + if (isNaNIdentifier(switchCase.test)) { + context.report({ node: switchCase, messageId: "caseNaN" }); + } + } + } + + /** + * Checks the given `CallExpression` node for `.indexOf(NaN)` and `.lastIndexOf(NaN)`. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkCallExpression(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type === "MemberExpression") { + const methodName = astUtils.getStaticPropertyName(callee); + + if ( + (methodName === "indexOf" || + methodName === "lastIndexOf") && + node.arguments.length <= 2 && + isNaNIdentifier(node.arguments[0]) + ) { + /* + * To retain side effects, it's essential to address `NaN` beforehand, which + * is not possible with fixes like `arr.findIndex(Number.isNaN)`. + */ + const isSuggestable = + node.arguments[0].type !== "SequenceExpression" && + !node.arguments[1]; + const suggestedFixes = []; + + if (isSuggestable) { + const shouldWrap = callee.computed; + const findIndexMethod = + methodName === "indexOf" + ? "findIndex" + : "findLastIndex"; + const propertyName = shouldWrap + ? `"${findIndexMethod}"` + : findIndexMethod; + + suggestedFixes.push({ + messageId: "replaceWithFindIndex", + data: { methodName: findIndexMethod }, + fix: fixer => [ + fixer.replaceText( + callee.property, + propertyName, + ), + fixer.replaceText( + node.arguments[0], + "Number.isNaN", + ), + ], + }); + } + + context.report({ + node, + messageId: "indexOfNaN", + data: { methodName }, + suggest: suggestedFixes, + }); + } + } + } + + const listeners = { + BinaryExpression: checkBinaryExpression, + }; + + if (enforceForSwitchCase) { + listeners.SwitchStatement = checkSwitchStatement; + } + + if (enforceForIndexOf) { + listeners.CallExpression = checkCallExpression; + } + + return listeners; + }, +}; diff --git a/node_modules/eslint/lib/rules/utils/ast-utils.js b/node_modules/eslint/lib/rules/utils/ast-utils.js new file mode 100644 index 00000000..c5004d05 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/ast-utils.js @@ -0,0 +1,2667 @@ +/** + * @fileoverview Common utils for AST. + * @author Gyandeep Singh + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { KEYS: eslintVisitorKeys } = require("eslint-visitor-keys"); +const esutils = require("esutils"); +const espree = require("espree"); +const escapeRegExp = require("escape-string-regexp"); +const { + breakableTypePattern, + createGlobalLinebreakMatcher, + lineBreakPattern, + shebangPattern, +} = require("../../shared/ast-utils"); +const globals = require("../../../conf/globals"); +const { LATEST_ECMA_VERSION } = require("../../../conf/ecma-version"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const anyFunctionPattern = + /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u; +const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u; +const arrayMethodWithThisArgPattern = + /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|some)$/u; +const arrayOrTypedArrayPattern = /Array$/u; +const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u; +const thisTagPattern = /^[\s*]*@this/mu; + +const COMMENTS_IGNORE_PATTERN = + /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u; +const ESLINT_DIRECTIVE_PATTERN = /^(?:eslint[- ]|(?:globals?|exported) )/u; +const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]); + +// A set of node types that can contain a list of statements +const STATEMENT_LIST_PARENTS = new Set([ + "Program", + "BlockStatement", + "StaticBlock", + "SwitchCase", +]); + +const DECIMAL_INTEGER_PATTERN = /^(?:0|0[0-7]*[89]\d*|[1-9](?:_?\d)*)$/u; + +// Tests the presence of at least one LegacyOctalEscapeSequence or NonOctalDecimalEscapeSequence in a raw string +const OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN = + /^(?:[^\\]|\\.)*\\(?:[1-9]|0[0-9])/su; + +const LOGICAL_ASSIGNMENT_OPERATORS = new Set(["&&=", "||=", "??="]); + +/** + * All builtin global variables defined in the latest ECMAScript specification. + * @type {Record} Key is the name of the variable. Value is `true` if the variable is considered writable, `false` otherwise. + */ +const ECMASCRIPT_GLOBALS = globals[`es${LATEST_ECMA_VERSION}`]; + +/** + * Checks reference if is non initializer and writable. + * @param {Reference} reference A reference to check. + * @param {number} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {boolean} Success/Failure + * @private + */ +function isModifyingReference(reference, index, references) { + const identifier = reference.identifier; + + /* + * Destructuring assignments can have multiple default value, so + * possibly there are multiple writeable references for the same + * identifier. + */ + const modifyingDifferentIdentifier = + index === 0 || references[index - 1].identifier !== identifier; + + return ( + identifier && + reference.init === false && + reference.isWrite() && + modifyingDifferentIdentifier + ); +} + +/** + * Checks whether the given string starts with uppercase or not. + * @param {string} s The string to check. + * @returns {boolean} `true` if the string starts with uppercase. + */ +function startsWithUpperCase(s) { + return s[0] !== s[0].toLocaleLowerCase(); +} + +/** + * Checks whether or not a node is a constructor. + * @param {ASTNode} node A function node to check. + * @returns {boolean} Whether or not a node is a constructor. + */ +function isES5Constructor(node) { + return node.id && startsWithUpperCase(node.id.name); +} + +/** + * Finds a function node from ancestors of a node. + * @param {ASTNode} node A start node to find. + * @returns {Node|null} A found function node. + */ +function getUpperFunction(node) { + for ( + let currentNode = node; + currentNode; + currentNode = currentNode.parent + ) { + if (anyFunctionPattern.test(currentNode.type)) { + return currentNode; + } + } + return null; +} + +/** + * Checks whether a given node is a function node or not. + * The following types are function nodes: + * + * - ArrowFunctionExpression + * - FunctionDeclaration + * - FunctionExpression + * @param {ASTNode|null} node A node to check. + * @returns {boolean} `true` if the node is a function node. + */ +function isFunction(node) { + return Boolean(node && anyFunctionPattern.test(node.type)); +} + +/** + * Checks whether a given node is a loop node or not. + * The following types are loop nodes: + * + * - DoWhileStatement + * - ForInStatement + * - ForOfStatement + * - ForStatement + * - WhileStatement + * @param {ASTNode|null} node A node to check. + * @returns {boolean} `true` if the node is a loop node. + */ +function isLoop(node) { + return Boolean(node && anyLoopPattern.test(node.type)); +} + +/** + * Checks whether the given node is in a loop or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is in a loop. + */ +function isInLoop(node) { + for ( + let currentNode = node; + currentNode && !isFunction(currentNode); + currentNode = currentNode.parent + ) { + if (isLoop(currentNode)) { + return true; + } + } + + return false; +} + +/** + * Determines whether the given node is a `null` literal. + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if the node is a `null` literal + */ +function isNullLiteral(node) { + /* + * Checking `node.value === null` does not guarantee that a literal is a null literal. + * When parsing values that cannot be represented in the current environment (e.g. unicode + * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to + * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check + * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020 + */ + return ( + node.type === "Literal" && + node.value === null && + !node.regex && + !node.bigint + ); +} + +/** + * Checks whether or not a node is `null` or `undefined`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `null` or `undefined`. + * @public + */ +function isNullOrUndefined(node) { + return ( + isNullLiteral(node) || + (node.type === "Identifier" && node.name === "undefined") || + (node.type === "UnaryExpression" && node.operator === "void") + ); +} + +/** + * Checks whether or not a node is callee. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is callee. + */ +function isCallee(node) { + return node.parent.type === "CallExpression" && node.parent.callee === node; +} + +/** + * Returns the result of the string conversion applied to the evaluated value of the given expression node, + * if it can be determined statically. + * + * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only. + * In all other cases, this function returns `null`. + * @param {ASTNode} node Expression node. + * @returns {string|null} String value if it can be determined. Otherwise, `null`. + */ +function getStaticStringValue(node) { + switch (node.type) { + case "Literal": + if (node.value === null) { + if (isNullLiteral(node)) { + return String(node.value); // "null" + } + if (node.regex) { + return `/${node.regex.pattern}/${node.regex.flags}`; + } + if (node.bigint) { + return node.bigint; + } + + // Otherwise, this is an unknown literal. The function will return null. + } else { + return String(node.value); + } + break; + case "TemplateLiteral": + if (node.expressions.length === 0 && node.quasis.length === 1) { + return node.quasis[0].value.cooked; + } + break; + + // no default + } + + return null; +} + +/** + * Gets the property name of a given node. + * The node can be a MemberExpression, a Property, or a MethodDefinition. + * + * If the name is dynamic, this returns `null`. + * + * For examples: + * + * a.b // => "b" + * a["b"] // => "b" + * a['b'] // => "b" + * a[`b`] // => "b" + * a[100] // => "100" + * a[b] // => null + * a["a" + "b"] // => null + * a[tag`b`] // => null + * a[`${b}`] // => null + * + * let a = {b: 1} // => "b" + * let a = {["b"]: 1} // => "b" + * let a = {['b']: 1} // => "b" + * let a = {[`b`]: 1} // => "b" + * let a = {[100]: 1} // => "100" + * let a = {[b]: 1} // => null + * let a = {["a" + "b"]: 1} // => null + * let a = {[tag`b`]: 1} // => null + * let a = {[`${b}`]: 1} // => null + * @param {ASTNode} node The node to get. + * @returns {string|null} The property name if static. Otherwise, null. + */ +function getStaticPropertyName(node) { + let prop; + + switch (node && node.type) { + case "ChainExpression": + return getStaticPropertyName(node.expression); + + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + prop = node.key; + break; + + case "MemberExpression": + prop = node.property; + break; + + // no default + } + + if (prop) { + if (prop.type === "Identifier" && !node.computed) { + return prop.name; + } + + return getStaticStringValue(prop); + } + + return null; +} + +/** + * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it. + * @param {ASTNode} node The node to address. + * @returns {ASTNode} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node. + */ +function skipChainExpression(node) { + return node && node.type === "ChainExpression" ? node.expression : node; +} + +/** + * Check if the `actual` is an expected value. + * @param {string} actual The string value to check. + * @param {string | RegExp} expected The expected string value or pattern. + * @returns {boolean} `true` if the `actual` is an expected value. + */ +function checkText(actual, expected) { + return typeof expected === "string" + ? actual === expected + : expected.test(actual); +} + +/** + * Check if a given node is an Identifier node with a given name. + * @param {ASTNode} node The node to check. + * @param {string | RegExp} name The expected name or the expected pattern of the object name. + * @returns {boolean} `true` if the node is an Identifier node with the name. + */ +function isSpecificId(node, name) { + return node.type === "Identifier" && checkText(node.name, name); +} + +/** + * Check if a given node is member access with a given object name and property name pair. + * This is regardless of optional or not. + * @param {ASTNode} node The node to check. + * @param {string | RegExp | null} objectName The expected name or the expected pattern of the object name. If this is nullish, this method doesn't check object. + * @param {string | RegExp | null} propertyName The expected name or the expected pattern of the property name. If this is nullish, this method doesn't check property. + * @returns {boolean} `true` if the node is member access with the object name and property name pair. + * The node is a `MemberExpression` or `ChainExpression`. + */ +function isSpecificMemberAccess(node, objectName, propertyName) { + const checkNode = skipChainExpression(node); + + if (checkNode.type !== "MemberExpression") { + return false; + } + + if (objectName && !isSpecificId(checkNode.object, objectName)) { + return false; + } + + if (propertyName) { + const actualPropertyName = getStaticPropertyName(checkNode); + + if ( + typeof actualPropertyName !== "string" || + !checkText(actualPropertyName, propertyName) + ) { + return false; + } + } + + return true; +} + +/** + * Check if two literal nodes are the same value. + * @param {ASTNode} left The Literal node to compare. + * @param {ASTNode} right The other Literal node to compare. + * @returns {boolean} `true` if the two literal nodes are the same value. + */ +function equalLiteralValue(left, right) { + // RegExp literal. + if (left.regex || right.regex) { + return Boolean( + left.regex && + right.regex && + left.regex.pattern === right.regex.pattern && + left.regex.flags === right.regex.flags, + ); + } + + // BigInt literal. + if (left.bigint || right.bigint) { + return left.bigint === right.bigint; + } + + return left.value === right.value; +} + +/** + * Check if two expressions reference the same value. For example: + * a = a + * a.b = a.b + * a[0] = a[0] + * a['b'] = a['b'] + * @param {ASTNode} left The left side of the comparison. + * @param {ASTNode} right The right side of the comparison. + * @param {boolean} [disableStaticComputedKey] Don't address `a.b` and `a["b"]` are the same if `true`. For backward compatibility. + * @returns {boolean} `true` if both sides match and reference the same value. + */ +function isSameReference(left, right, disableStaticComputedKey = false) { + if (left.type !== right.type) { + // Handle `a.b` and `a?.b` are samely. + if (left.type === "ChainExpression") { + return isSameReference( + left.expression, + right, + disableStaticComputedKey, + ); + } + if (right.type === "ChainExpression") { + return isSameReference( + left, + right.expression, + disableStaticComputedKey, + ); + } + + return false; + } + + switch (left.type) { + case "Super": + case "ThisExpression": + return true; + + case "Identifier": + case "PrivateIdentifier": + return left.name === right.name; + case "Literal": + return equalLiteralValue(left, right); + + case "ChainExpression": + return isSameReference( + left.expression, + right.expression, + disableStaticComputedKey, + ); + + case "MemberExpression": { + if (!disableStaticComputedKey) { + const nameA = getStaticPropertyName(left); + + // x.y = x["y"] + if (nameA !== null) { + return ( + isSameReference( + left.object, + right.object, + disableStaticComputedKey, + ) && nameA === getStaticPropertyName(right) + ); + } + } + + /* + * x[0] = x[0] + * x[y] = x[y] + * x.y = x.y + */ + return ( + left.computed === right.computed && + isSameReference( + left.object, + right.object, + disableStaticComputedKey, + ) && + isSameReference( + left.property, + right.property, + disableStaticComputedKey, + ) + ); + } + + default: + return false; + } +} + +/** + * Checks whether or not a node is `Reflect.apply`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `Reflect.apply`. + */ +function isReflectApply(node) { + return isSpecificMemberAccess(node, "Reflect", "apply"); +} + +/** + * Checks whether or not a node is `Array.from`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `Array.from`. + */ +function isArrayFromMethod(node) { + return isSpecificMemberAccess(node, arrayOrTypedArrayPattern, "from"); +} + +/** + * Checks whether or not a node is a method which expects a function as a first argument, and `thisArg` as a second argument. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a method which expects a function as a first argument, and `thisArg` as a second argument. + */ +function isMethodWhichHasThisArg(node) { + return isSpecificMemberAccess(node, null, arrayMethodWithThisArgPattern); +} + +/** + * Creates the negate function of the given function. + * @param {Function} f The function to negate. + * @returns {Function} Negated function. + */ +function negate(f) { + return token => !f(token); +} + +/** + * Checks whether or not a node has a `@this` tag in its comments. + * @param {ASTNode} node A node to check. + * @param {SourceCode} sourceCode A SourceCode instance to get comments. + * @returns {boolean} Whether or not the node has a `@this` tag in its comments. + */ +function hasJSDocThisTag(node, sourceCode) { + const jsdocComment = sourceCode.getJSDocComment(node); + + if (jsdocComment && thisTagPattern.test(jsdocComment.value)) { + return true; + } + + // Checks `@this` in its leading comments for callbacks, + // because callbacks don't have its JSDoc comment. + // e.g. + // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); }); + return sourceCode + .getCommentsBefore(node) + .some(comment => thisTagPattern.test(comment.value)); +} + +/** + * Determines if a node is surrounded by parentheses. + * @param {SourceCode} sourceCode The ESLint source code object + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is parenthesised. + * @private + */ +function isParenthesised(sourceCode, node) { + const previousToken = sourceCode.getTokenBefore(node), + nextToken = sourceCode.getTokenAfter(node); + + return ( + Boolean(previousToken && nextToken) && + previousToken.value === "(" && + previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && + nextToken.range[0] >= node.range[1] + ); +} + +/** + * Checks if the given token is a `=` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a `=` token. + */ +function isEqToken(token) { + return token.value === "=" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an arrow token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an arrow token. + */ +function isArrowToken(token) { + return token.value === "=>" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a comma token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a comma token. + */ +function isCommaToken(token) { + return token.value === "," && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a dot token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a dot token. + */ +function isDotToken(token) { + return token.value === "." && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a `?.` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a `?.` token. + */ +function isQuestionDotToken(token) { + return token.value === "?." && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a semicolon token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a semicolon token. + */ +function isSemicolonToken(token) { + return token.value === ";" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a colon token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a colon token. + */ +function isColonToken(token) { + return token.value === ":" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an opening parenthesis token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an opening parenthesis token. + */ +function isOpeningParenToken(token) { + return token.value === "(" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a closing parenthesis token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a closing parenthesis token. + */ +function isClosingParenToken(token) { + return token.value === ")" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an opening square bracket token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an opening square bracket token. + */ +function isOpeningBracketToken(token) { + return token.value === "[" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a closing square bracket token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a closing square bracket token. + */ +function isClosingBracketToken(token) { + return token.value === "]" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an opening brace token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an opening brace token. + */ +function isOpeningBraceToken(token) { + return token.value === "{" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a closing brace token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a closing brace token. + */ +function isClosingBraceToken(token) { + return token.value === "}" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a comment token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a comment token. + */ +function isCommentToken(token) { + return ( + token.type === "Line" || + token.type === "Block" || + token.type === "Shebang" + ); +} + +/** + * Checks if the given token is a keyword token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a keyword token. + */ +function isKeywordToken(token) { + return token.type === "Keyword"; +} + +/** + * Gets the `(` token of the given function node. + * @param {ASTNode} node The function node to get. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token} `(` token. + */ +function getOpeningParenOfParams(node, sourceCode) { + // If the node is an arrow function and doesn't have parens, this returns the identifier of the first param. + if (node.type === "ArrowFunctionExpression" && node.params.length === 1) { + const argToken = sourceCode.getFirstToken(node.params[0]); + const maybeParenToken = sourceCode.getTokenBefore(argToken); + + return isOpeningParenToken(maybeParenToken) + ? maybeParenToken + : argToken; + } + + // Otherwise, returns paren. + return node.id + ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) + : sourceCode.getFirstToken(node, isOpeningParenToken); +} + +/** + * Checks whether or not the tokens of two given nodes are same. + * @param {ASTNode} left A node 1 to compare. + * @param {ASTNode} right A node 2 to compare. + * @param {SourceCode} sourceCode The ESLint source code object. + * @returns {boolean} the source code for the given node. + */ +function equalTokens(left, right, sourceCode) { + const tokensL = sourceCode.getTokens(left); + const tokensR = sourceCode.getTokens(right); + + if (tokensL.length !== tokensR.length) { + return false; + } + for (let i = 0; i < tokensL.length; ++i) { + if ( + tokensL[i].type !== tokensR[i].type || + tokensL[i].value !== tokensR[i].value + ) { + return false; + } + } + + return true; +} + +/** + * Check if the given node is a true logical expression or not. + * + * The three binary expressions logical-or (`||`), logical-and (`&&`), and + * coalesce (`??`) are known as `ShortCircuitExpression`. + * But ESTree represents those by `LogicalExpression` node. + * + * This function rejects coalesce expressions of `LogicalExpression` node. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is `&&` or `||`. + * @see https://tc39.es/ecma262/#prod-ShortCircuitExpression + */ +function isLogicalExpression(node) { + return ( + node.type === "LogicalExpression" && + (node.operator === "&&" || node.operator === "||") + ); +} + +/** + * Check if the given node is a nullish coalescing expression or not. + * + * The three binary expressions logical-or (`||`), logical-and (`&&`), and + * coalesce (`??`) are known as `ShortCircuitExpression`. + * But ESTree represents those by `LogicalExpression` node. + * + * This function finds only coalesce expressions of `LogicalExpression` node. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is `??`. + */ +function isCoalesceExpression(node) { + return node.type === "LogicalExpression" && node.operator === "??"; +} + +/** + * Check if given two nodes are the pair of a logical expression and a coalesce expression. + * @param {ASTNode} left A node to check. + * @param {ASTNode} right Another node to check. + * @returns {boolean} `true` if the two nodes are the pair of a logical expression and a coalesce expression. + */ +function isMixedLogicalAndCoalesceExpressions(left, right) { + return ( + (isLogicalExpression(left) && isCoalesceExpression(right)) || + (isCoalesceExpression(left) && isLogicalExpression(right)) + ); +} + +/** + * Checks if the given operator is a logical assignment operator. + * @param {string} operator The operator to check. + * @returns {boolean} `true` if the operator is a logical assignment operator. + */ +function isLogicalAssignmentOperator(operator) { + return LOGICAL_ASSIGNMENT_OPERATORS.has(operator); +} + +/** + * Get the colon token of the given SwitchCase node. + * @param {ASTNode} node The SwitchCase node to get. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token} The colon token of the node. + */ +function getSwitchCaseColonToken(node, sourceCode) { + if (node.test) { + return sourceCode.getTokenAfter(node.test, isColonToken); + } + return sourceCode.getFirstToken(node, 1); +} + +/** + * Gets ESM module export name represented by the given node. + * @param {ASTNode} node `Identifier` or string `Literal` node in a position + * that represents a module export name: + * - `ImportSpecifier#imported` + * - `ExportSpecifier#local` (if it is a re-export from another module) + * - `ExportSpecifier#exported` + * - `ExportAllDeclaration#exported` + * @returns {string} The module export name. + */ +function getModuleExportName(node) { + if (node.type === "Identifier") { + return node.name; + } + + // string literal + return node.value; +} + +/** + * Returns literal's value converted to the Boolean type + * @param {ASTNode} node any `Literal` node + * @returns {boolean | null} `true` when node is truthy, `false` when node is falsy, + * `null` when it cannot be determined. + */ +function getBooleanValue(node) { + if (node.value === null) { + /* + * it might be a null literal or bigint/regex literal in unsupported environments . + * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es5.md#regexpliteral + * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es2020.md#bigintliteral + */ + + if (node.raw === "null") { + return false; + } + + // regex is always truthy + if (typeof node.regex === "object") { + return true; + } + + return null; + } + + return !!node.value; +} + +/** + * Checks if a branch node of LogicalExpression short circuits the whole condition + * @param {ASTNode} node The branch of main condition which needs to be checked + * @param {string} operator The operator of the main LogicalExpression. + * @returns {boolean} true when condition short circuits whole condition + */ +function isLogicalIdentity(node, operator) { + switch (node.type) { + case "Literal": + return ( + (operator === "||" && getBooleanValue(node) === true) || + (operator === "&&" && getBooleanValue(node) === false) + ); + + case "UnaryExpression": + return operator === "&&" && node.operator === "void"; + + case "LogicalExpression": + /* + * handles `a && false || b` + * `false` is an identity element of `&&` but not `||` + */ + return ( + operator === node.operator && + (isLogicalIdentity(node.left, operator) || + isLogicalIdentity(node.right, operator)) + ); + + case "AssignmentExpression": + return ( + ["||=", "&&="].includes(node.operator) && + operator === node.operator.slice(0, -1) && + isLogicalIdentity(node.right, operator) + ); + + // no default + } + return false; +} + +/** + * Checks if an identifier is a reference to a global variable. + * @param {Scope} scope The scope in which the identifier is referenced. + * @param {ASTNode} node An identifier node to check. + * @returns {boolean} `true` if the identifier is a reference to a global variable. + */ +function isReferenceToGlobalVariable(scope, node) { + const reference = scope.references.find(ref => ref.identifier === node); + + return Boolean( + reference && + reference.resolved && + reference.resolved.scope.type === "global" && + reference.resolved.defs.length === 0, + ); +} + +/** + * Checks if a node has a constant truthiness value. + * @param {Scope} scope Scope in which the node appears. + * @param {ASTNode} node The AST node to check. + * @param {boolean} inBooleanPosition `true` if checking the test of a + * condition. `false` in all other cases. When `false`, checks if -- for + * both string and number -- if coerced to that type, the value will + * be constant. + * @returns {boolean} true when node's truthiness is constant + * @private + */ +function isConstant(scope, node, inBooleanPosition) { + // node.elements can return null values in the case of sparse arrays ex. [,] + if (!node) { + return true; + } + switch (node.type) { + case "Literal": + case "ArrowFunctionExpression": + case "FunctionExpression": + return true; + case "ClassExpression": + case "ObjectExpression": + /** + * In theory objects like: + * + * `{toString: () => a}` + * `{valueOf: () => a}` + * + * Or a classes like: + * + * `class { static toString() { return a } }` + * `class { static valueOf() { return a } }` + * + * Are not constant verifiably when `inBooleanPosition` is + * false, but it's an edge case we've opted not to handle. + */ + return true; + case "TemplateLiteral": + return ( + (inBooleanPosition && + node.quasis.some(quasi => quasi.value.cooked.length)) || + node.expressions.every(exp => isConstant(scope, exp, false)) + ); + + case "ArrayExpression": { + if (!inBooleanPosition) { + return node.elements.every(element => + isConstant(scope, element, false), + ); + } + return true; + } + + case "UnaryExpression": + if ( + node.operator === "void" || + (node.operator === "typeof" && inBooleanPosition) + ) { + return true; + } + + if (node.operator === "!") { + return isConstant(scope, node.argument, true); + } + + return isConstant(scope, node.argument, false); + + case "BinaryExpression": + return ( + isConstant(scope, node.left, false) && + isConstant(scope, node.right, false) && + node.operator !== "in" + ); + + case "LogicalExpression": { + const isLeftConstant = isConstant( + scope, + node.left, + inBooleanPosition, + ); + const isRightConstant = isConstant( + scope, + node.right, + inBooleanPosition, + ); + const isLeftShortCircuit = + isLeftConstant && isLogicalIdentity(node.left, node.operator); + const isRightShortCircuit = + inBooleanPosition && + isRightConstant && + isLogicalIdentity(node.right, node.operator); + + return ( + (isLeftConstant && isRightConstant) || + isLeftShortCircuit || + isRightShortCircuit + ); + } + case "NewExpression": + return inBooleanPosition; + case "AssignmentExpression": + if (node.operator === "=") { + return isConstant(scope, node.right, inBooleanPosition); + } + + if (["||=", "&&="].includes(node.operator) && inBooleanPosition) { + return isLogicalIdentity( + node.right, + node.operator.slice(0, -1), + ); + } + + return false; + + case "SequenceExpression": + return isConstant( + scope, + node.expressions.at(-1), + inBooleanPosition, + ); + case "SpreadElement": + return isConstant(scope, node.argument, inBooleanPosition); + case "CallExpression": + if ( + node.callee.type === "Identifier" && + node.callee.name === "Boolean" + ) { + if ( + node.arguments.length === 0 || + isConstant(scope, node.arguments[0], true) + ) { + return isReferenceToGlobalVariable(scope, node.callee); + } + } + return false; + case "Identifier": + return ( + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node) + ); + + // no default + } + return false; +} + +/** + * Checks whether a node is an ExpressionStatement at the top level of a file, function body, or TypeScript module block. + * A top-level ExpressionStatement node is a directive if it contains a single unparenthesized + * string literal and if it occurs either as the first sibling or immediately after another + * directive. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node is an ExpressionStatement at the top level of a + * file, function body, or TypeScript module block. + */ +function isTopLevelExpressionStatement(node) { + if (node.type !== "ExpressionStatement") { + return false; + } + const parent = node.parent; + + return ( + parent.type === "Program" || + parent.type === "TSModuleBlock" || + (parent.type === "BlockStatement" && isFunction(parent.parent)) + ); +} + +/** + * Check whether the given node is a part of a directive prologue or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a part of directive prologue. + */ +function isDirective(node) { + return ( + node.type === "ExpressionStatement" && + typeof node.directive === "string" + ); +} + +/** + * Tests if a node appears at the beginning of an ancestor ExpressionStatement node. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether the node appears at the beginning of an ancestor ExpressionStatement node. + */ +function isStartOfExpressionStatement(node) { + const start = node.range[0]; + let ancestor = node; + + while ((ancestor = ancestor.parent) && ancestor.range[0] === start) { + if (ancestor.type === "ExpressionStatement") { + return true; + } + } + return false; +} + +/** + * Determines whether an opening parenthesis `(`, bracket `[` or backtick ``` ` ``` needs to be preceded by a semicolon. + * This opening parenthesis or bracket should be at the start of an `ExpressionStatement`, a `MethodDefinition` or at + * the start of the body of an `ArrowFunctionExpression`. + * @type {(sourceCode: SourceCode, node: ASTNode) => boolean} + * @param {SourceCode} sourceCode The source code object. + * @param {ASTNode} node A node at the position where an opening parenthesis or bracket will be inserted. + * @returns {boolean} Whether a semicolon is required before the opening parenthesis or bracket. + */ +let needsPrecedingSemicolon; + +{ + const BREAK_OR_CONTINUE = new Set(["BreakStatement", "ContinueStatement"]); + + // Declaration types that cannot be continued by a punctuator when ending with a string Literal that is a direct child. + const DECLARATIONS = new Set([ + "ExportAllDeclaration", + "ExportNamedDeclaration", + "ImportDeclaration", + ]); + + const IDENTIFIER_OR_KEYWORD = new Set(["Identifier", "Keyword"]); + + // Keywords that can immediately precede an ExpressionStatement node, mapped to the their node types. + const NODE_TYPES_BY_KEYWORD = { + __proto__: null, + break: "BreakStatement", + continue: "ContinueStatement", + debugger: "DebuggerStatement", + do: "DoWhileStatement", + else: "IfStatement", + return: "ReturnStatement", + yield: "YieldExpression", + }; + + /* + * Before an opening parenthesis, postfix `++` and `--` always trigger ASI; + * the tokens `:`, `;`, `{` and `=>` don't expect a semicolon, as that would count as an empty statement. + */ + const PUNCTUATORS = new Set([":", ";", "{", "=>", "++", "--"]); + + /* + * Statements that can contain an `ExpressionStatement` after a closing parenthesis. + * DoWhileStatement is an exception in that it always triggers ASI after the closing parenthesis. + */ + const STATEMENTS = new Set([ + "DoWhileStatement", + "ForInStatement", + "ForOfStatement", + "ForStatement", + "IfStatement", + "WhileStatement", + "WithStatement", + ]); + + needsPrecedingSemicolon = function (sourceCode, node) { + const prevToken = sourceCode.getTokenBefore(node); + + if ( + !prevToken || + (prevToken.type === "Punctuator" && + PUNCTUATORS.has(prevToken.value)) + ) { + return false; + } + + const prevNode = sourceCode.getNodeByRangeIndex(prevToken.range[0]); + + if (isClosingParenToken(prevToken)) { + return !STATEMENTS.has(prevNode.type); + } + + if (isClosingBraceToken(prevToken)) { + return ( + (prevNode.type === "BlockStatement" && + prevNode.parent.type === "FunctionExpression" && + prevNode.parent.parent.type !== "MethodDefinition") || + (prevNode.type === "ClassBody" && + prevNode.parent.type === "ClassExpression") || + prevNode.type === "ObjectExpression" + ); + } + + if (IDENTIFIER_OR_KEYWORD.has(prevToken.type)) { + if (BREAK_OR_CONTINUE.has(prevNode.parent.type)) { + return false; + } + + const keyword = prevToken.value; + const nodeType = NODE_TYPES_BY_KEYWORD[keyword]; + + return prevNode.type !== nodeType; + } + + if (prevToken.type === "String") { + return !DECLARATIONS.has(prevNode.parent.type); + } + + return true; + }; +} + +/** + * Checks if a node is used as an import attribute key, either in a static or dynamic import. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether the node is used as an import attribute key. + */ +function isImportAttributeKey(node) { + const { parent } = node; + + // static import/re-export + if (parent.type === "ImportAttribute" && parent.key === node) { + return true; + } + + // dynamic import + if ( + parent.type === "Property" && + !parent.computed && + (parent.key === node || + (parent.value === node && parent.shorthand && !parent.method)) && + parent.parent.type === "ObjectExpression" + ) { + const objectExpression = parent.parent; + const objectExpressionParent = objectExpression.parent; + + if ( + objectExpressionParent.type === "ImportExpression" && + objectExpressionParent.options === objectExpression + ) { + return true; + } + + // nested key + if ( + objectExpressionParent.type === "Property" && + objectExpressionParent.value === objectExpression + ) { + return isImportAttributeKey(objectExpressionParent.key); + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + COMMENTS_IGNORE_PATTERN, + LINEBREAKS, + LINEBREAK_MATCHER: lineBreakPattern, + SHEBANG_MATCHER: shebangPattern, + STATEMENT_LIST_PARENTS, + ECMASCRIPT_GLOBALS, + + /** + * Determines whether two adjacent tokens are on the same line. + * @param {Object} left The left token object. + * @param {Object} right The right token object. + * @returns {boolean} Whether or not the tokens are on the same line. + * @public + */ + isTokenOnSameLine(left, right) { + return left.loc.end.line === right.loc.start.line; + }, + + isNullOrUndefined, + isCallee, + isES5Constructor, + getUpperFunction, + isFunction, + isLoop, + isInLoop, + isArrayFromMethod, + isParenthesised, + createGlobalLinebreakMatcher, + equalTokens, + + isArrowToken, + isClosingBraceToken, + isClosingBracketToken, + isClosingParenToken, + isColonToken, + isCommaToken, + isCommentToken, + isDotToken, + isQuestionDotToken, + isKeywordToken, + isNotClosingBraceToken: negate(isClosingBraceToken), + isNotClosingBracketToken: negate(isClosingBracketToken), + isNotClosingParenToken: negate(isClosingParenToken), + isNotColonToken: negate(isColonToken), + isNotCommaToken: negate(isCommaToken), + isNotDotToken: negate(isDotToken), + isNotQuestionDotToken: negate(isQuestionDotToken), + isNotOpeningBraceToken: negate(isOpeningBraceToken), + isNotOpeningBracketToken: negate(isOpeningBracketToken), + isNotOpeningParenToken: negate(isOpeningParenToken), + isNotSemicolonToken: negate(isSemicolonToken), + isOpeningBraceToken, + isOpeningBracketToken, + isOpeningParenToken, + isSemicolonToken, + isEqToken, + + /** + * Checks whether or not a given node is a string literal. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a string literal. + */ + isStringLiteral(node) { + return ( + (node.type === "Literal" && typeof node.value === "string") || + node.type === "TemplateLiteral" + ); + }, + + /** + * Checks whether a given node is a breakable statement or not. + * The node is breakable if the node is one of the following type: + * + * - DoWhileStatement + * - ForInStatement + * - ForOfStatement + * - ForStatement + * - SwitchStatement + * - WhileStatement + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is breakable. + */ + isBreakableStatement(node) { + return breakableTypePattern.test(node.type); + }, + + /** + * Gets references which are non initializer and writable. + * @param {Reference[]} references An array of references. + * @returns {Reference[]} An array of only references which are non initializer and writable. + * @public + */ + getModifyingReferences(references) { + return references.filter(isModifyingReference); + }, + + /** + * Validate that a string passed in is surrounded by the specified character + * @param {string} val The text to check. + * @param {string} character The character to see if it's surrounded by. + * @returns {boolean} True if the text is surrounded by the character, false if not. + * @private + */ + isSurroundedBy(val, character) { + return val[0] === character && val.at(-1) === character; + }, + + /** + * Returns whether the provided node is an ESLint directive comment or not + * @param {Line|Block} node The comment token to be checked + * @returns {boolean} `true` if the node is an ESLint directive comment + */ + isDirectiveComment(node) { + const comment = node.value.trim(); + + return ( + (node.type === "Line" && comment.startsWith("eslint-")) || + (node.type === "Block" && ESLINT_DIRECTIVE_PATTERN.test(comment)) + ); + }, + + /** + * Gets the trailing statement of a given node. + * + * if (code) + * consequent; + * + * When taking this `IfStatement`, returns `consequent;` statement. + * @param {ASTNode} A node to get. + * @returns {ASTNode|null} The trailing statement's node. + */ + getTrailingStatement: esutils.ast.trailingStatement, + + /** + * Finds the variable by a given name in a given scope and its upper scopes. + * @param {eslint-scope.Scope} initScope A scope to start find. + * @param {string} name A variable name to find. + * @returns {eslint-scope.Variable|null} A found variable or `null`. + */ + getVariableByName(initScope, name) { + let scope = initScope; + + while (scope) { + const variable = scope.set.get(name); + + if (variable) { + return variable; + } + + scope = scope.upper; + } + + return null; + }, + + /** + * Checks whether or not a given function node is the default `this` binding. + * + * First, this checks the node: + * + * - The given node is not in `PropertyDefinition#value` position. + * - The given node is not `StaticBlock`. + * - The function name does not start with uppercase. It's a convention to capitalize the names + * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`. + * - The function does not have a JSDoc comment that has a @this tag. + * + * Next, this checks the location of the node. + * If the location is below, this judges `this` is valid. + * + * - The location is not on an object literal. + * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous + * functions only, as the name of the variable is considered to be the name of the function in this case. + * This check is not performed if `capIsConstructor` is set to `false`. + * - The location is not on an ES2015 class. + * - Its `bind`/`call`/`apply` method is not called directly. + * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given. + * @param {ASTNode} node A function node to check. It also can be an implicit function, like `StaticBlock` + * or any expression that is `PropertyDefinition#value` node. + * @param {SourceCode} sourceCode A SourceCode instance to get comments. + * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts + * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors. + * @returns {boolean} The function node is the default `this` binding. + */ + isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) { + /* + * Class field initializers are implicit functions, but ESTree doesn't have the AST node of field initializers. + * Therefore, A expression node at `PropertyDefinition#value` is a function. + * In this case, `this` is always not default binding. + */ + if ( + node.parent.type === "PropertyDefinition" && + node.parent.value === node + ) { + return false; + } + + // Class static blocks are implicit functions. In this case, `this` is always not default binding. + if (node.type === "StaticBlock") { + return false; + } + + // Check if the function has a parameter named `this`. + if ( + (node.type === "FunctionDeclaration" || + node.type === "FunctionExpression") && + node.params.some( + param => param.type === "Identifier" && param.name === "this", + ) + ) { + return false; + } + + if ( + (capIsConstructor && isES5Constructor(node)) || + hasJSDocThisTag(node, sourceCode) + ) { + return false; + } + const isAnonymous = node.id === null; + let currentNode = node; + + while (currentNode) { + const parent = currentNode.parent; + + switch (parent.type) { + /* + * Looks up the destination. + * e.g., obj.foo = nativeFoo || function foo() { ... }; + */ + case "LogicalExpression": + case "ConditionalExpression": + case "ChainExpression": + currentNode = parent; + break; + + /* + * If the upper function is IIFE, checks the destination of the return value. + * e.g. + * obj.foo = (function() { + * // setup... + * return function foo() { ... }; + * })(); + * obj.foo = (() => + * function foo() { ... } + * )(); + */ + case "ReturnStatement": { + const func = getUpperFunction(parent); + + if (func === null || !isCallee(func)) { + return true; + } + currentNode = func.parent; + break; + } + case "ArrowFunctionExpression": + if (currentNode !== parent.body || !isCallee(parent)) { + return true; + } + currentNode = parent.parent; + break; + + /* + * e.g. + * var obj = { foo() { ... } }; + * var obj = { foo: function() { ... } }; + * class A { constructor() { ... } } + * class A { foo() { ... } } + * class A { get foo() { ... } } + * class A { set foo() { ... } } + * class A { static foo() { ... } } + * class A { foo = function() { ... } } + */ + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + return parent.value !== currentNode; + + /* + * e.g. + * obj.foo = function foo() { ... }; + * Foo = function() { ... }; + * [obj.foo = function foo() { ... }] = a; + * [Foo = function() { ... }] = a; + */ + case "AssignmentExpression": + case "AssignmentPattern": + if (parent.left.type === "MemberExpression") { + return false; + } + if ( + capIsConstructor && + isAnonymous && + parent.left.type === "Identifier" && + startsWithUpperCase(parent.left.name) + ) { + return false; + } + return true; + + /* + * e.g. + * var Foo = function() { ... }; + */ + case "VariableDeclarator": + return !( + capIsConstructor && + isAnonymous && + parent.init === currentNode && + parent.id.type === "Identifier" && + startsWithUpperCase(parent.id.name) + ); + + /* + * e.g. + * var foo = function foo() { ... }.bind(obj); + * (function foo() { ... }).call(obj); + * (function foo() { ... }).apply(obj, []); + */ + case "MemberExpression": + if ( + parent.object === currentNode && + isSpecificMemberAccess( + parent, + null, + bindOrCallOrApplyPattern, + ) + ) { + const maybeCalleeNode = + parent.parent.type === "ChainExpression" + ? parent.parent + : parent; + + return !( + isCallee(maybeCalleeNode) && + maybeCalleeNode.parent.arguments.length >= 1 && + !isNullOrUndefined( + maybeCalleeNode.parent.arguments[0], + ) + ); + } + return true; + + /* + * e.g. + * Reflect.apply(function() {}, obj, []); + * Array.from([], function() {}, obj); + * list.forEach(function() {}, obj); + */ + case "CallExpression": + if (isReflectApply(parent.callee)) { + return ( + parent.arguments.length !== 3 || + parent.arguments[0] !== currentNode || + isNullOrUndefined(parent.arguments[1]) + ); + } + if (isArrayFromMethod(parent.callee)) { + return ( + parent.arguments.length !== 3 || + parent.arguments[1] !== currentNode || + isNullOrUndefined(parent.arguments[2]) + ); + } + if (isMethodWhichHasThisArg(parent.callee)) { + return ( + parent.arguments.length !== 2 || + parent.arguments[0] !== currentNode || + isNullOrUndefined(parent.arguments[1]) + ); + } + return true; + + // Otherwise `this` is default. + default: + return true; + } + } + + /* c8 ignore next */ + return true; + }, + + /** + * Get the precedence level based on the node type + * @param {ASTNode} node node to evaluate + * @returns {number} precedence level + * @private + */ + getPrecedence(node) { + switch (node.type) { + case "SequenceExpression": + return 0; + + case "AssignmentExpression": + case "ArrowFunctionExpression": + case "YieldExpression": + return 1; + + case "ConditionalExpression": + return 3; + + case "LogicalExpression": + switch (node.operator) { + case "||": + case "??": + return 4; + case "&&": + return 5; + + // no default + } + + /* falls through */ + + case "BinaryExpression": + switch (node.operator) { + case "|": + return 6; + case "^": + return 7; + case "&": + return 8; + case "==": + case "!=": + case "===": + case "!==": + return 9; + case "<": + case "<=": + case ">": + case ">=": + case "in": + case "instanceof": + return 10; + case "<<": + case ">>": + case ">>>": + return 11; + case "+": + case "-": + return 12; + case "*": + case "/": + case "%": + return 13; + case "**": + return 15; + + // no default + } + + /* falls through */ + + case "UnaryExpression": + case "AwaitExpression": + return 16; + + case "UpdateExpression": + return 17; + + case "CallExpression": + case "ChainExpression": + case "ImportExpression": + return 18; + + case "NewExpression": + return 19; + + default: + if (node.type in eslintVisitorKeys) { + return 20; + } + + /* + * if the node is not a standard node that we know about, then assume it has the lowest precedence + * this will mean that rules will wrap unknown nodes in parentheses where applicable instead of + * unwrapping them and potentially changing the meaning of the code or introducing a syntax error. + */ + return -1; + } + }, + + /** + * Checks whether the given node is an empty block node or not. + * @param {ASTNode|null} node The node to check. + * @returns {boolean} `true` if the node is an empty block. + */ + isEmptyBlock(node) { + return Boolean( + node && node.type === "BlockStatement" && node.body.length === 0, + ); + }, + + /** + * Checks whether the given node is an empty function node or not. + * @param {ASTNode|null} node The node to check. + * @returns {boolean} `true` if the node is an empty function. + */ + isEmptyFunction(node) { + return isFunction(node) && module.exports.isEmptyBlock(node.body); + }, + + /** + * Get directives from directive prologue of a Program or Function node. + * @param {ASTNode} node The node to check. + * @returns {ASTNode[]} The directives found in the directive prologue. + */ + getDirectivePrologue(node) { + const directives = []; + + // Directive prologues only occur at the top of files or functions. + if ( + node.type === "Program" || + node.type === "FunctionDeclaration" || + node.type === "FunctionExpression" || + /* + * Do not check arrow functions with implicit return. + * `() => "use strict";` returns the string `"use strict"`. + */ + (node.type === "ArrowFunctionExpression" && + node.body.type === "BlockStatement") + ) { + const statements = + node.type === "Program" ? node.body : node.body.body; + + for (const statement of statements) { + if ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" + ) { + directives.push(statement); + } else { + break; + } + } + } + + return directives; + }, + + /** + * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added + * after the node will be parsed as a decimal point, rather than a property-access dot. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if this node is a decimal integer. + * @example + * + * 0 // true + * 5 // true + * 50 // true + * 5_000 // true + * 1_234_56 // true + * 08 // true + * 0192 // true + * 5. // false + * .5 // false + * 5.0 // false + * 5.00_00 // false + * 05 // false + * 0x5 // false + * 0b101 // false + * 0b11_01 // false + * 0o5 // false + * 5e0 // false + * 5e1_000 // false + * 5n // false + * 1_000n // false + * "5" // false + * + */ + isDecimalInteger(node) { + return ( + node.type === "Literal" && + typeof node.value === "number" && + DECIMAL_INTEGER_PATTERN.test(node.raw) + ); + }, + + /** + * Determines whether this token is a decimal integer numeric token. + * This is similar to isDecimalInteger(), but for tokens. + * @param {Token} token The token to check. + * @returns {boolean} `true` if this token is a decimal integer. + */ + isDecimalIntegerNumericToken(token) { + return ( + token.type === "Numeric" && + DECIMAL_INTEGER_PATTERN.test(token.value) + ); + }, + + /** + * Gets the name and kind of the given function node. + * + * - `function foo() {}` .................... `function 'foo'` + * - `(function foo() {})` .................. `function 'foo'` + * - `(function() {})` ...................... `function` + * - `function* foo() {}` ................... `generator function 'foo'` + * - `(function* foo() {})` ................. `generator function 'foo'` + * - `(function*() {})` ..................... `generator function` + * - `() => {}` ............................. `arrow function` + * - `async () => {}` ....................... `async arrow function` + * - `({ foo: function foo() {} })` ......... `method 'foo'` + * - `({ foo: function() {} })` ............. `method 'foo'` + * - `({ ['foo']: function() {} })` ......... `method 'foo'` + * - `({ [foo]: function() {} })` ........... `method` + * - `({ foo() {} })` ....................... `method 'foo'` + * - `({ foo: function* foo() {} })` ........ `generator method 'foo'` + * - `({ foo: function*() {} })` ............ `generator method 'foo'` + * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'` + * - `({ [foo]: function*() {} })` .......... `generator method` + * - `({ *foo() {} })` ...................... `generator method 'foo'` + * - `({ foo: async function foo() {} })` ... `async method 'foo'` + * - `({ foo: async function() {} })` ....... `async method 'foo'` + * - `({ ['foo']: async function() {} })` ... `async method 'foo'` + * - `({ [foo]: async function() {} })` ..... `async method` + * - `({ async foo() {} })` ................. `async method 'foo'` + * - `({ get foo() {} })` ................... `getter 'foo'` + * - `({ set foo(a) {} })` .................. `setter 'foo'` + * - `class A { constructor() {} }` ......... `constructor` + * - `class A { foo() {} }` ................. `method 'foo'` + * - `class A { *foo() {} }` ................ `generator method 'foo'` + * - `class A { async foo() {} }` ........... `async method 'foo'` + * - `class A { ['foo']() {} }` ............. `method 'foo'` + * - `class A { *['foo']() {} }` ............ `generator method 'foo'` + * - `class A { async ['foo']() {} }` ....... `async method 'foo'` + * - `class A { [foo]() {} }` ............... `method` + * - `class A { *[foo]() {} }` .............. `generator method` + * - `class A { async [foo]() {} }` ......... `async method` + * - `class A { get foo() {} }` ............. `getter 'foo'` + * - `class A { set foo(a) {} }` ............ `setter 'foo'` + * - `class A { static foo() {} }` .......... `static method 'foo'` + * - `class A { static *foo() {} }` ......... `static generator method 'foo'` + * - `class A { static async foo() {} }` .... `static async method 'foo'` + * - `class A { static get foo() {} }` ...... `static getter 'foo'` + * - `class A { static set foo(a) {} }` ..... `static setter 'foo'` + * - `class A { foo = () => {}; }` .......... `method 'foo'` + * - `class A { foo = function() {}; }` ..... `method 'foo'` + * - `class A { foo = function bar() {}; }` . `method 'foo'` + * - `class A { static foo = () => {}; }` ... `static method 'foo'` + * - `class A { '#foo' = () => {}; }` ....... `method '#foo'` + * - `class A { #foo = () => {}; }` ......... `private method #foo` + * - `class A { static #foo = () => {}; }` .. `static private method #foo` + * - `class A { '#foo'() {} }` .............. `method '#foo'` + * - `class A { #foo() {} }` ................ `private method #foo` + * - `class A { static #foo() {} }` ......... `static private method #foo` + * @param {ASTNode} node The function node to get. + * @returns {string} The name and kind of the function node. + */ + getFunctionNameWithKind(node) { + const parent = node.parent; + const tokens = []; + + if ( + parent.type === "MethodDefinition" || + parent.type === "PropertyDefinition" + ) { + // The proposal uses `static` word consistently before visibility words: https://github.com/tc39/proposal-static-class-features + if (parent.static) { + tokens.push("static"); + } + if (!parent.computed && parent.key.type === "PrivateIdentifier") { + tokens.push("private"); + } + } + if (node.async) { + tokens.push("async"); + } + if (node.generator) { + tokens.push("generator"); + } + + if (parent.type === "Property" || parent.type === "MethodDefinition") { + if (parent.kind === "constructor") { + return "constructor"; + } + if (parent.kind === "get") { + tokens.push("getter"); + } else if (parent.kind === "set") { + tokens.push("setter"); + } else { + tokens.push("method"); + } + } else if (parent.type === "PropertyDefinition") { + tokens.push("method"); + } else { + if (node.type === "ArrowFunctionExpression") { + tokens.push("arrow"); + } + tokens.push("function"); + } + + if ( + parent.type === "Property" || + parent.type === "MethodDefinition" || + parent.type === "PropertyDefinition" + ) { + if (!parent.computed && parent.key.type === "PrivateIdentifier") { + tokens.push(`#${parent.key.name}`); + } else { + const name = getStaticPropertyName(parent); + + if (name !== null) { + tokens.push(`'${name}'`); + } else if (node.id) { + tokens.push(`'${node.id.name}'`); + } + } + } else if (node.id) { + tokens.push(`'${node.id.name}'`); + } + + return tokens.join(" "); + }, + + /** + * Gets the location of the given function node for reporting. + * + * - `function foo() {}` + * ^^^^^^^^^^^^ + * - `(function foo() {})` + * ^^^^^^^^^^^^ + * - `(function() {})` + * ^^^^^^^^ + * - `function* foo() {}` + * ^^^^^^^^^^^^^ + * - `(function* foo() {})` + * ^^^^^^^^^^^^^ + * - `(function*() {})` + * ^^^^^^^^^ + * - `() => {}` + * ^^ + * - `async () => {}` + * ^^ + * - `({ foo: function foo() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ foo: function() {} })` + * ^^^^^^^^^^^^^ + * - `({ ['foo']: function() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function() {} })` + * ^^^^^^^^^^^^^^^ + * - `({ foo() {} })` + * ^^^ + * - `({ foo: function* foo() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ foo: function*() {} })` + * ^^^^^^^^^^^^^^ + * - `({ ['foo']: function*() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function*() {} })` + * ^^^^^^^^^^^^^^^^ + * - `({ *foo() {} })` + * ^^^^ + * - `({ foo: async function foo() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ foo: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^ + * - `({ ['foo']: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `({ async foo() {} })` + * ^^^^^^^^^ + * - `({ get foo() {} })` + * ^^^^^^^ + * - `({ set foo(a) {} })` + * ^^^^^^^ + * - `class A { constructor() {} }` + * ^^^^^^^^^^^ + * - `class A { foo() {} }` + * ^^^ + * - `class A { *foo() {} }` + * ^^^^ + * - `class A { async foo() {} }` + * ^^^^^^^^^ + * - `class A { ['foo']() {} }` + * ^^^^^^^ + * - `class A { *['foo']() {} }` + * ^^^^^^^^ + * - `class A { async ['foo']() {} }` + * ^^^^^^^^^^^^^ + * - `class A { [foo]() {} }` + * ^^^^^ + * - `class A { *[foo]() {} }` + * ^^^^^^ + * - `class A { async [foo]() {} }` + * ^^^^^^^^^^^ + * - `class A { get foo() {} }` + * ^^^^^^^ + * - `class A { set foo(a) {} }` + * ^^^^^^^ + * - `class A { static foo() {} }` + * ^^^^^^^^^^ + * - `class A { static *foo() {} }` + * ^^^^^^^^^^^ + * - `class A { static async foo() {} }` + * ^^^^^^^^^^^^^^^^ + * - `class A { static get foo() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static set foo(a) {} }` + * ^^^^^^^^^^^^^^ + * - `class A { foo = function() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static foo = function() {} }` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `class A { foo = (a, b) => {} }` + * ^^^^^^ + * @param {ASTNode} node The function node to get. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {string} The location of the function node for reporting. + */ + getFunctionHeadLoc(node, sourceCode) { + const parent = node.parent; + let start; + let end; + + if ( + parent.type === "Property" || + parent.type === "MethodDefinition" || + parent.type === "PropertyDefinition" + ) { + start = parent.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } else if (node.type === "ArrowFunctionExpression") { + const arrowToken = sourceCode.getTokenBefore( + node.body, + isArrowToken, + ); + + start = arrowToken.loc.start; + end = arrowToken.loc.end; + } else { + start = node.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + + return { + start: Object.assign({}, start), + end: Object.assign({}, end), + }; + }, + + /** + * Gets next location when the result is not out of bound, otherwise returns null. + * + * Assumptions: + * + * - The given location represents a valid location in the given source code. + * - Columns are 0-based. + * - Lines are 1-based. + * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location. + * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end. + * The start (column 0) of that extra line is considered to be a valid location. + * + * Examples of successive locations (line, column): + * + * code: foo + * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null + * + * code: foo + * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null + * + * code: foo + * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null + * + * code: ab + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null + * + * code: ab + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null + * + * code: ab + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null + * + * code: a + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null + * + * code: + * locations: (1, 0) -> (2, 0) -> null + * + * code: + * locations: (1, 0) -> null + * @param {SourceCode} sourceCode The sourceCode + * @param {{line: number, column: number}} location The location + * @returns {{line: number, column: number} | null} Next location + */ + getNextLocation(sourceCode, { line, column }) { + if (column < sourceCode.lines[line - 1].length) { + return { + line, + column: column + 1, + }; + } + + if (line < sourceCode.lines.length) { + return { + line: line + 1, + column: 0, + }; + } + + return null; + }, + + /** + * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses + * surrounding the node. + * @param {SourceCode} sourceCode The source code object + * @param {ASTNode} node An expression node + * @returns {string} The text representing the node, with all surrounding parentheses included + */ + getParenthesisedText(sourceCode, node) { + let leftToken = sourceCode.getFirstToken(node); + let rightToken = sourceCode.getLastToken(node); + + while ( + sourceCode.getTokenBefore(leftToken) && + sourceCode.getTokenBefore(leftToken).type === "Punctuator" && + sourceCode.getTokenBefore(leftToken).value === "(" && + sourceCode.getTokenAfter(rightToken) && + sourceCode.getTokenAfter(rightToken).type === "Punctuator" && + sourceCode.getTokenAfter(rightToken).value === ")" + ) { + leftToken = sourceCode.getTokenBefore(leftToken); + rightToken = sourceCode.getTokenAfter(rightToken); + } + + return sourceCode + .getText() + .slice(leftToken.range[0], rightToken.range[1]); + }, + + /** + * Determine if a node has a possibility to be an Error object + * @param {ASTNode} node ASTNode to check + * @returns {boolean} True if there is a chance it contains an Error obj + */ + couldBeError(node) { + switch (node.type) { + case "Identifier": + case "CallExpression": + case "NewExpression": + case "MemberExpression": + case "TaggedTemplateExpression": + case "YieldExpression": + case "AwaitExpression": + case "ChainExpression": + return true; // possibly an error object. + + case "AssignmentExpression": + if (["=", "&&="].includes(node.operator)) { + return module.exports.couldBeError(node.right); + } + + if (["||=", "??="].includes(node.operator)) { + return ( + module.exports.couldBeError(node.left) || + module.exports.couldBeError(node.right) + ); + } + + /** + * All other assignment operators are mathematical assignment operators (arithmetic or bitwise). + * An assignment expression with a mathematical operator can either evaluate to a primitive value, + * or throw, depending on the operands. Thus, it cannot evaluate to an `Error` object. + */ + return false; + + case "SequenceExpression": { + const exprs = node.expressions; + + return ( + exprs.length !== 0 && + module.exports.couldBeError(exprs.at(-1)) + ); + } + + case "LogicalExpression": + /* + * If the && operator short-circuits, the left side was falsy and therefore not an error, and if it + * doesn't short-circuit, it takes the value from the right side, so the right side must always be + * a plausible error. A future improvement could verify that the left side could be truthy by + * excluding falsy literals. + */ + if (node.operator === "&&") { + return module.exports.couldBeError(node.right); + } + + return ( + module.exports.couldBeError(node.left) || + module.exports.couldBeError(node.right) + ); + + case "ConditionalExpression": + return ( + module.exports.couldBeError(node.consequent) || + module.exports.couldBeError(node.alternate) + ); + + default: + return false; + } + }, + + /** + * Check if a given node is a numeric literal or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a number or bigint literal. + */ + isNumericLiteral(node) { + return ( + node.type === "Literal" && + (typeof node.value === "number" || Boolean(node.bigint)) + ); + }, + + /** + * Determines whether two tokens can safely be placed next to each other without merging into a single token + * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used. + * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used. + * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed + * next to each other, behavior is undefined (although it should return `true` in most cases). + */ + canTokensBeAdjacent(leftValue, rightValue) { + const espreeOptions = { + ecmaVersion: espree.latestEcmaVersion, + comment: true, + range: true, + }; + + let leftToken; + + if (typeof leftValue === "string") { + let tokens; + + try { + tokens = espree.tokenize(leftValue, espreeOptions); + } catch { + return false; + } + + const comments = tokens.comments; + + leftToken = tokens.at(-1); + if (comments.length) { + const lastComment = comments.at(-1); + + if (!leftToken || lastComment.range[0] > leftToken.range[0]) { + leftToken = lastComment; + } + } + } else { + leftToken = leftValue; + } + + /* + * If a hashbang comment was passed as a token object from SourceCode, + * its type will be "Shebang" because of the way ESLint itself handles hashbangs. + * If a hashbang comment was passed in a string and then tokenized in this function, + * its type will be "Hashbang" because of the way Espree tokenizes hashbangs. + */ + if (leftToken.type === "Shebang" || leftToken.type === "Hashbang") { + return false; + } + + let rightToken; + + if (typeof rightValue === "string") { + let tokens; + + try { + tokens = espree.tokenize(rightValue, espreeOptions); + } catch { + return false; + } + + const comments = tokens.comments; + + rightToken = tokens[0]; + if (comments.length) { + const firstComment = comments[0]; + + if ( + !rightToken || + firstComment.range[0] < rightToken.range[0] + ) { + rightToken = firstComment; + } + } + } else { + rightToken = rightValue; + } + + if ( + leftToken.type === "Punctuator" || + rightToken.type === "Punctuator" + ) { + if ( + leftToken.type === "Punctuator" && + rightToken.type === "Punctuator" + ) { + const PLUS_TOKENS = new Set(["+", "++"]); + const MINUS_TOKENS = new Set(["-", "--"]); + + return !( + (PLUS_TOKENS.has(leftToken.value) && + PLUS_TOKENS.has(rightToken.value)) || + (MINUS_TOKENS.has(leftToken.value) && + MINUS_TOKENS.has(rightToken.value)) + ); + } + if (leftToken.type === "Punctuator" && leftToken.value === "/") { + return !["Block", "Line", "RegularExpression"].includes( + rightToken.type, + ); + } + return true; + } + + if ( + leftToken.type === "String" || + rightToken.type === "String" || + leftToken.type === "Template" || + rightToken.type === "Template" + ) { + return true; + } + + if ( + leftToken.type !== "Numeric" && + rightToken.type === "Numeric" && + rightToken.value.startsWith(".") + ) { + return true; + } + + if ( + leftToken.type === "Block" || + rightToken.type === "Block" || + rightToken.type === "Line" + ) { + return true; + } + + if (rightToken.type === "PrivateIdentifier") { + return true; + } + + return false; + }, + + /** + * Get the `loc` object of a given name in a `/*globals` directive comment. + * @param {SourceCode} sourceCode The source code to convert index to loc. + * @param {Comment} comment The `/*globals` directive comment which include the name. + * @param {string} name The name to find. + * @returns {SourceLocation} The `loc` object. + */ + getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) { + const namePattern = new RegExp( + `[\\s,]${escapeRegExp(name)}(?:$|[\\s,:])`, + "gu", + ); + + // To ignore the first text "global". + namePattern.lastIndex = comment.value.indexOf("global") + 6; + + // Search a given variable name. + const match = namePattern.exec(comment.value); + + // Convert the index to loc. + const start = sourceCode.getLocFromIndex( + comment.range[0] + "/*".length + (match ? match.index + 1 : 0), + ); + const end = { + line: start.line, + column: start.column + (match ? name.length : 1), + }; + + return { start, end }; + }, + + /** + * Determines whether the given raw string contains an octal escape sequence + * or a non-octal decimal escape sequence ("\8", "\9"). + * + * "\1", "\2" ... "\7", "\8", "\9" + * "\00", "\01" ... "\07", "\08", "\09" + * + * "\0", when not followed by a digit, is not an octal escape sequence. + * @param {string} rawString A string in its raw representation. + * @returns {boolean} `true` if the string contains at least one octal escape sequence + * or at least one non-octal decimal escape sequence. + */ + hasOctalOrNonOctalDecimalEscapeSequence(rawString) { + return OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN.test(rawString); + }, + + /** + * Determines whether the given node is a template literal without expressions. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a template literal without expressions. + */ + isStaticTemplateLiteral(node) { + return node.type === "TemplateLiteral" && node.expressions.length === 0; + }, + + /** + * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code. + * The braces, which make the given block body, are necessary in either of the following situations: + * + * 1. The statement is a lexical declaration. + * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace: + * + * if (a) { + * if (b) + * foo(); + * } + * else + * bar(); + * + * if (a) + * while (b) + * while (c) { + * while (d) + * if (e) + * while(f) + * foo(); + * } + * else + * bar(); + * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements. + * @param {SourceCode} sourceCode The source code + * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content) + * would change the semantics of the code or produce a syntax error. + */ + areBracesNecessary(node, sourceCode) { + /** + * Determines if the given node is a lexical declaration (let, const, function, or class) + * @param {ASTNode} nodeToCheck The node to check + * @returns {boolean} True if the node is a lexical declaration + * @private + */ + function isLexicalDeclaration(nodeToCheck) { + if (nodeToCheck.type === "VariableDeclaration") { + return ( + nodeToCheck.kind === "const" || nodeToCheck.kind === "let" + ); + } + + return ( + nodeToCheck.type === "FunctionDeclaration" || + nodeToCheck.type === "ClassDeclaration" + ); + } + + /** + * Checks if the given token is an `else` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an `else` token. + */ + function isElseKeywordToken(token) { + return token.value === "else" && token.type === "Keyword"; + } + + /** + * Determines whether the given node has an `else` keyword token as the first token after. + * @param {ASTNode} nodeToCheck The node to check. + * @returns {boolean} `true` if the node is followed by an `else` keyword token. + */ + function isFollowedByElseKeyword(nodeToCheck) { + const nextToken = sourceCode.getTokenAfter(nodeToCheck); + + return Boolean(nextToken) && isElseKeywordToken(nextToken); + } + + /** + * Determines whether the code represented by the given node contains an `if` statement + * that would become associated with an `else` keyword directly appended to that code. + * + * Examples where it returns `true`: + * + * if (a) + * foo(); + * + * if (a) { + * foo(); + * } + * + * if (a) + * foo(); + * else if (b) + * bar(); + * + * while (a) + * if (b) + * if(c) + * foo(); + * else + * bar(); + * + * Examples where it returns `false`: + * + * if (a) + * foo(); + * else + * bar(); + * + * while (a) { + * if (b) + * if(c) + * foo(); + * else + * bar(); + * } + * + * while (a) + * if (b) { + * if(c) + * foo(); + * } + * else + * bar(); + * @param {ASTNode} nodeToCheck Node representing the code to check. + * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code. + */ + function hasUnsafeIf(nodeToCheck) { + switch (nodeToCheck.type) { + case "IfStatement": + if (!nodeToCheck.alternate) { + return true; + } + return hasUnsafeIf(nodeToCheck.alternate); + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + case "LabeledStatement": + case "WithStatement": + case "WhileStatement": + return hasUnsafeIf(nodeToCheck.body); + default: + return false; + } + } + + const statement = node.body[0]; + + return ( + isLexicalDeclaration(statement) || + (hasUnsafeIf(statement) && isFollowedByElseKeyword(node)) + ); + }, + + isReferenceToGlobalVariable, + isLogicalExpression, + isCoalesceExpression, + isMixedLogicalAndCoalesceExpressions, + isNullLiteral, + getStaticStringValue, + getStaticPropertyName, + skipChainExpression, + isSpecificId, + isSpecificMemberAccess, + equalLiteralValue, + isSameReference, + isLogicalAssignmentOperator, + getSwitchCaseColonToken, + getModuleExportName, + isConstant, + isTopLevelExpressionStatement, + isDirective, + isStartOfExpressionStatement, + needsPrecedingSemicolon, + isImportAttributeKey, +}; diff --git a/node_modules/eslint/lib/rules/utils/char-source.js b/node_modules/eslint/lib/rules/utils/char-source.js new file mode 100644 index 00000000..6e9719ca --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/char-source.js @@ -0,0 +1,247 @@ +/** + * @fileoverview Utility functions to locate the source text of each code unit in the value of a string literal or template token. + * @author Francesco Trotta + */ + +"use strict"; + +/** + * Represents a code unit produced by the evaluation of a JavaScript common token like a string + * literal or template token. + */ +class CodeUnit { + constructor(start, source) { + this.start = start; + this.source = source; + } + + get end() { + return this.start + this.length; + } + + get length() { + return this.source.length; + } +} + +/** + * An object used to keep track of the position in a source text where the next characters will be read. + */ +class TextReader { + constructor(source) { + this.source = source; + this.pos = 0; + } + + /** + * Advances the reading position of the specified number of characters. + * @param {number} length Number of characters to advance. + * @returns {void} + */ + advance(length) { + this.pos += length; + } + + /** + * Reads characters from the source. + * @param {number} [offset=0] The offset where reading starts, relative to the current position. + * @param {number} [length=1] Number of characters to read. + * @returns {string} A substring of source characters. + */ + read(offset = 0, length = 1) { + const start = offset + this.pos; + + return this.source.slice(start, start + length); + } +} + +const SIMPLE_ESCAPE_SEQUENCES = { + __proto__: null, + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + v: "\v", +}; + +/** + * Reads a hex escape sequence. + * @param {TextReader} reader The reader should be positioned on the first hexadecimal digit. + * @param {number} length The number of hexadecimal digits. + * @returns {string} A code unit. + */ +function readHexSequence(reader, length) { + const str = reader.read(0, length); + const charCode = parseInt(str, 16); + + reader.advance(length); + return String.fromCharCode(charCode); +} + +/** + * Reads a Unicode escape sequence. + * @param {TextReader} reader The reader should be positioned after the "u". + * @returns {string} A code unit. + */ +function readUnicodeSequence(reader) { + const regExp = /\{(?[\dA-Fa-f]+)\}/uy; + + regExp.lastIndex = reader.pos; + const match = regExp.exec(reader.source); + + if (match) { + const codePoint = parseInt(match.groups.hexDigits, 16); + + reader.pos = regExp.lastIndex; + return String.fromCodePoint(codePoint); + } + return readHexSequence(reader, 4); +} + +/** + * Reads an octal escape sequence. + * @param {TextReader} reader The reader should be positioned after the first octal digit. + * @param {number} maxLength The maximum number of octal digits. + * @returns {string} A code unit. + */ +function readOctalSequence(reader, maxLength) { + const [octalStr] = reader.read(-1, maxLength).match(/^[0-7]+/u); + + reader.advance(octalStr.length - 1); + const octal = parseInt(octalStr, 8); + + return String.fromCharCode(octal); +} + +/** + * Reads an escape sequence or line continuation. + * @param {TextReader} reader The reader should be positioned on the backslash. + * @returns {string} A string of zero, one or two code units. + */ +function readEscapeSequenceOrLineContinuation(reader) { + const char = reader.read(1); + + reader.advance(2); + const unitChar = SIMPLE_ESCAPE_SEQUENCES[char]; + + if (unitChar) { + return unitChar; + } + switch (char) { + case "x": + return readHexSequence(reader, 2); + case "u": + return readUnicodeSequence(reader); + case "\r": + if (reader.read() === "\n") { + reader.advance(1); + } + + // fallthrough + case "\n": + case "\u2028": + case "\u2029": + return ""; + case "0": + case "1": + case "2": + case "3": + return readOctalSequence(reader, 3); + case "4": + case "5": + case "6": + case "7": + return readOctalSequence(reader, 2); + default: + return char; + } +} + +/** + * Reads an escape sequence or line continuation and generates the respective `CodeUnit` elements. + * @param {TextReader} reader The reader should be positioned on the backslash. + * @returns {Generator} Zero, one or two `CodeUnit` elements. + */ +function* mapEscapeSequenceOrLineContinuation(reader) { + const start = reader.pos; + const str = readEscapeSequenceOrLineContinuation(reader); + const end = reader.pos; + const source = reader.source.slice(start, end); + + switch (str.length) { + case 0: + break; + case 1: + yield new CodeUnit(start, source); + break; + default: + yield new CodeUnit(start, source); + yield new CodeUnit(start, source); + break; + } +} + +/** + * Parses a string literal. + * @param {string} source The string literal to parse, including the delimiting quotes. + * @returns {CodeUnit[]} A list of code units produced by the string literal. + */ +function parseStringLiteral(source) { + const reader = new TextReader(source); + const quote = reader.read(); + + reader.advance(1); + const codeUnits = []; + + for (;;) { + const char = reader.read(); + + if (char === quote) { + break; + } + if (char === "\\") { + codeUnits.push(...mapEscapeSequenceOrLineContinuation(reader)); + } else { + codeUnits.push(new CodeUnit(reader.pos, char)); + reader.advance(1); + } + } + return codeUnits; +} + +/** + * Parses a template token. + * @param {string} source The template token to parse, including the delimiting sequences `` ` ``, `${` and `}`. + * @returns {CodeUnit[]} A list of code units produced by the template token. + */ +function parseTemplateToken(source) { + const reader = new TextReader(source); + + reader.advance(1); + const codeUnits = []; + + for (;;) { + const char = reader.read(); + + if (char === "`" || (char === "$" && reader.read(1) === "{")) { + break; + } + if (char === "\\") { + codeUnits.push(...mapEscapeSequenceOrLineContinuation(reader)); + } else { + let unitSource; + + if (char === "\r" && reader.read(1) === "\n") { + unitSource = "\r\n"; + } else { + unitSource = char; + } + codeUnits.push(new CodeUnit(reader.pos, unitSource)); + reader.advance(unitSource.length); + } + } + return codeUnits; +} + +module.exports = { parseStringLiteral, parseTemplateToken }; diff --git a/node_modules/eslint/lib/rules/utils/fix-tracker.js b/node_modules/eslint/lib/rules/utils/fix-tracker.js new file mode 100644 index 00000000..5721717b --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/fix-tracker.js @@ -0,0 +1,125 @@ +/** + * @fileoverview Helper class to aid in constructing fix commands. + * @author Alan Pierce + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceRange } from "@eslint/core"; + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./ast-utils"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A helper class to combine fix options into a fix command. Currently, it + * exposes some "retain" methods that extend the range of the text being + * replaced so that other fixes won't touch that region in the same pass. + */ +class FixTracker { + /** + * Create a new FixTracker. + * @param {ruleFixer} fixer A ruleFixer instance. + * @param {SourceCode} sourceCode A SourceCode object for the current code. + */ + constructor(fixer, sourceCode) { + this.fixer = fixer; + this.sourceCode = sourceCode; + this.retainedRange = null; + } + + /** + * Mark the given range as "retained", meaning that other fixes may not + * may not modify this region in the same pass. + * @param {SourceRange} range The range to retain. + * @returns {FixTracker} The same RuleFixer, for chained calls. + */ + retainRange(range) { + this.retainedRange = range; + return this; + } + + /** + * Given a node, find the function containing it (or the entire program) and + * mark it as retained, meaning that other fixes may not modify it in this + * pass. This is useful for avoiding conflicts in fixes that modify control + * flow. + * @param {ASTNode} node The node to use as a starting point. + * @returns {FixTracker} The same RuleFixer, for chained calls. + */ + retainEnclosingFunction(node) { + const functionNode = astUtils.getUpperFunction(node); + + return this.retainRange( + functionNode ? functionNode.range : this.sourceCode.ast.range, + ); + } + + /** + * Given a node or token, find the token before and afterward, and mark that + * range as retained, meaning that other fixes may not modify it in this + * pass. This is useful for avoiding conflicts in fixes that make a small + * change to the code where the AST should not be changed. + * @param {ASTNode|Token} nodeOrToken The node or token to use as a starting + * point. The token to the left and right are use in the range. + * @returns {FixTracker} The same RuleFixer, for chained calls. + */ + retainSurroundingTokens(nodeOrToken) { + const tokenBefore = + this.sourceCode.getTokenBefore(nodeOrToken) || nodeOrToken; + const tokenAfter = + this.sourceCode.getTokenAfter(nodeOrToken) || nodeOrToken; + + return this.retainRange([tokenBefore.range[0], tokenAfter.range[1]]); + } + + /** + * Create a fix command that replaces the given range with the given text, + * accounting for any retained ranges. + * @param {SourceRange} range The range to remove in the fix. + * @param {string} text The text to insert in place of the range. + * @returns {Object} The fix command. + */ + replaceTextRange(range, text) { + let actualRange; + + if (this.retainedRange) { + actualRange = [ + Math.min(this.retainedRange[0], range[0]), + Math.max(this.retainedRange[1], range[1]), + ]; + } else { + actualRange = range; + } + + return this.fixer.replaceTextRange( + actualRange, + this.sourceCode.text.slice(actualRange[0], range[0]) + + text + + this.sourceCode.text.slice(range[1], actualRange[1]), + ); + } + + /** + * Create a fix command that removes the given node or token, accounting for + * any retained ranges. + * @param {ASTNode|Token} nodeOrToken The node or token to remove. + * @returns {Object} The fix command. + */ + remove(nodeOrToken) { + return this.replaceTextRange(nodeOrToken.range, ""); + } +} + +module.exports = FixTracker; diff --git a/node_modules/eslint/lib/rules/utils/keywords.js b/node_modules/eslint/lib/rules/utils/keywords.js new file mode 100644 index 00000000..eca2076e --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/keywords.js @@ -0,0 +1,67 @@ +/** + * @fileoverview A shared list of ES3 keywords. + * @author Josh Perez + */ +"use strict"; + +module.exports = [ + "abstract", + "boolean", + "break", + "byte", + "case", + "catch", + "char", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "double", + "else", + "enum", + "export", + "extends", + "false", + "final", + "finally", + "float", + "for", + "function", + "goto", + "if", + "implements", + "import", + "in", + "instanceof", + "int", + "interface", + "long", + "native", + "new", + "null", + "package", + "private", + "protected", + "public", + "return", + "short", + "static", + "super", + "switch", + "synchronized", + "this", + "throw", + "throws", + "transient", + "true", + "try", + "typeof", + "var", + "void", + "volatile", + "while", + "with", +]; diff --git a/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js b/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js new file mode 100644 index 00000000..b9339509 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js @@ -0,0 +1,118 @@ +/** + * @fileoverview `Map` to load rules lazily. + * @author Toru Nagashima + */ +"use strict"; + +const debug = require("debug")("eslint:rules"); + +/** @typedef {import("../../types").Rule.RuleModule} Rule */ + +/** + * The `Map` object that loads each rule when it's accessed. + * @example + * const rules = new LazyLoadingRuleMap([ + * ["eqeqeq", () => require("eqeqeq")], + * ["semi", () => require("semi")], + * ["no-unused-vars", () => require("no-unused-vars")] + * ]); + * + * rules.get("semi"); // call `() => require("semi")` here. + * + * @extends {Map} + */ +class LazyLoadingRuleMap extends Map { + /** + * Initialize this map. + * @param {Array<[string, function(): Rule]>} loaders The rule loaders. + */ + constructor(loaders) { + let remaining = loaders.length; + + super( + debug.enabled + ? loaders.map(([ruleId, load]) => { + let cache = null; + + return [ + ruleId, + () => { + if (!cache) { + debug( + "Loading rule %o (remaining=%d)", + ruleId, + --remaining, + ); + cache = load(); + } + return cache; + }, + ]; + }) + : loaders, + ); + + // `super(...iterable)` uses `this.set()`, so disable it here. + Object.defineProperty(LazyLoadingRuleMap.prototype, "set", { + configurable: true, + value: void 0, + }); + } + + /** + * Get a rule. + * Each rule will be loaded on the first access. + * @param {string} ruleId The rule ID to get. + * @returns {Rule|undefined} The rule. + */ + get(ruleId) { + const load = super.get(ruleId); + + return load && load(); + } + + /** + * Iterate rules. + * @returns {IterableIterator} Rules. + */ + *values() { + for (const load of super.values()) { + yield load(); + } + } + + /** + * Iterate rules. + * @returns {IterableIterator<[string, Rule]>} Rules. + */ + *entries() { + for (const [ruleId, load] of super.entries()) { + yield [ruleId, load()]; + } + } + + /** + * Call a function with each rule. + * @param {Function} callbackFn The callback function. + * @param {any} [thisArg] The object to pass to `this` of the callback function. + * @returns {void} + */ + forEach(callbackFn, thisArg) { + for (const [ruleId, load] of super.entries()) { + callbackFn.call(thisArg, load(), ruleId, this); + } + } +} + +// Forbid mutation. +Object.defineProperties(LazyLoadingRuleMap.prototype, { + clear: { configurable: true, value: void 0 }, + delete: { configurable: true, value: void 0 }, + [Symbol.iterator]: { + configurable: true, + writable: true, + value: LazyLoadingRuleMap.prototype.entries, + }, +}); + +module.exports = { LazyLoadingRuleMap }; diff --git a/node_modules/eslint/lib/rules/utils/regular-expressions.js b/node_modules/eslint/lib/rules/utils/regular-expressions.js new file mode 100644 index 00000000..6d80654b --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/regular-expressions.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Common utils for regular expressions. + * @author Josh Goldberg + * @author Toru Nagashima + */ + +"use strict"; + +const { RegExpValidator } = require("@eslint-community/regexpp"); + +const REGEXPP_LATEST_ECMA_VERSION = 2025; + +/** + * Checks if the given regular expression pattern would be valid with the `u` flag. + * @param {number} ecmaVersion ECMAScript version to parse in. + * @param {string} pattern The regular expression pattern to verify. + * @param {"u"|"v"} flag The type of Unicode flag + * @returns {boolean} `true` if the pattern would be valid with the `u` flag. + * `false` if the pattern would be invalid with the `u` flag or the configured + * ecmaVersion doesn't support the `u` flag. + */ +function isValidWithUnicodeFlag(ecmaVersion, pattern, flag = "u") { + if (flag === "u" && ecmaVersion <= 5) { + // ecmaVersion <= 5 doesn't support the 'u' flag + return false; + } + if (flag === "v" && ecmaVersion <= 2023) { + return false; + } + + const validator = new RegExpValidator({ + ecmaVersion: Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION), + }); + + try { + validator.validatePattern( + pattern, + void 0, + void 0, + flag === "u" + ? { + unicode: /* uFlag = */ true, + } + : { + unicodeSets: true, + }, + ); + } catch { + return false; + } + + return true; +} + +module.exports = { + isValidWithUnicodeFlag, + REGEXPP_LATEST_ECMA_VERSION, +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/index.js b/node_modules/eslint/lib/rules/utils/unicode/index.js new file mode 100644 index 00000000..0e7d5d53 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/index.js @@ -0,0 +1,16 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +const isCombiningCharacter = require("./is-combining-character"); +const isEmojiModifier = require("./is-emoji-modifier"); +const isRegionalIndicatorSymbol = require("./is-regional-indicator-symbol"); +const isSurrogatePair = require("./is-surrogate-pair"); + +module.exports = { + isCombiningCharacter, + isEmojiModifier, + isRegionalIndicatorSymbol, + isSurrogatePair, +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js b/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js new file mode 100644 index 00000000..8a36b223 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js @@ -0,0 +1,13 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether a given character is a combining mark or not. + * @param {number} codePoint The character code to check. + * @returns {boolean} `true` if the character belongs to the category, any of `Mc`, `Me`, and `Mn`. + */ +module.exports = function isCombiningCharacter(codePoint) { + return /^[\p{Mc}\p{Me}\p{Mn}]$/u.test(String.fromCodePoint(codePoint)); +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js b/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js new file mode 100644 index 00000000..526ac91d --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js @@ -0,0 +1,13 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether a given character is an emoji modifier. + * @param {number} code The character code to check. + * @returns {boolean} `true` if the character is an emoji modifier. + */ +module.exports = function isEmojiModifier(code) { + return code >= 0x1f3fb && code <= 0x1f3ff; +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js b/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js new file mode 100644 index 00000000..019d9da0 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js @@ -0,0 +1,13 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether a given character is a regional indicator symbol. + * @param {number} code The character code to check. + * @returns {boolean} `true` if the character is a regional indicator symbol. + */ +module.exports = function isRegionalIndicatorSymbol(code) { + return code >= 0x1f1e6 && code <= 0x1f1ff; +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js b/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js new file mode 100644 index 00000000..fbe6a401 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js @@ -0,0 +1,14 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether given two characters are a surrogate pair. + * @param {number} lead The code of the lead character. + * @param {number} tail The code of the tail character. + * @returns {boolean} `true` if the character pair is a surrogate pair. + */ +module.exports = function isSurrogatePair(lead, tail) { + return lead >= 0xd800 && lead < 0xdc00 && tail >= 0xdc00 && tail < 0xe000; +}; diff --git a/node_modules/eslint/lib/rules/valid-typeof.js b/node_modules/eslint/lib/rules/valid-typeof.js new file mode 100644 index 00000000..fd4f3d20 --- /dev/null +++ b/node_modules/eslint/lib/rules/valid-typeof.js @@ -0,0 +1,171 @@ +/** + * @fileoverview Ensures that the results of typeof are compared against a valid string + * @author Ian Christian Myers + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + requireStringLiterals: false, + }, + ], + + docs: { + description: + "Enforce comparing `typeof` expressions against valid strings", + recommended: true, + url: "https://eslint.org/docs/latest/rules/valid-typeof", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + requireStringLiterals: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + invalidValue: "Invalid typeof comparison value.", + notString: "Typeof comparisons should be to string literals.", + suggestString: 'Use `"{{type}}"` instead of `{{type}}`.', + }, + }, + + create(context) { + const VALID_TYPES = new Set([ + "symbol", + "undefined", + "object", + "boolean", + "number", + "string", + "function", + "bigint", + ]), + OPERATORS = new Set(["==", "===", "!=", "!=="]); + const sourceCode = context.sourceCode; + const [{ requireStringLiterals }] = context.options; + + let globalScope; + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return ( + variable && + variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node) + ); + } + + /** + * Determines whether a node is a typeof expression. + * @param {ASTNode} node The node + * @returns {boolean} `true` if the node is a typeof expression + */ + function isTypeofExpression(node) { + return ( + node.type === "UnaryExpression" && node.operator === "typeof" + ); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + UnaryExpression(node) { + if (isTypeofExpression(node)) { + const { parent } = node; + + if ( + parent.type === "BinaryExpression" && + OPERATORS.has(parent.operator) + ) { + const sibling = + parent.left === node ? parent.right : parent.left; + + if ( + sibling.type === "Literal" || + astUtils.isStaticTemplateLiteral(sibling) + ) { + const value = + sibling.type === "Literal" + ? sibling.value + : sibling.quasis[0].value.cooked; + + if (!VALID_TYPES.has(value)) { + context.report({ + node: sibling, + messageId: "invalidValue", + }); + } + } else if ( + sibling.type === "Identifier" && + sibling.name === "undefined" && + isReferenceToGlobalVariable(sibling) + ) { + context.report({ + node: sibling, + messageId: requireStringLiterals + ? "notString" + : "invalidValue", + suggest: [ + { + messageId: "suggestString", + data: { type: "undefined" }, + fix(fixer) { + return fixer.replaceText( + sibling, + '"undefined"', + ); + }, + }, + ], + }); + } else if ( + requireStringLiterals && + !isTypeofExpression(sibling) + ) { + context.report({ + node: sibling, + messageId: "notString", + }); + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/vars-on-top.js b/node_modules/eslint/lib/rules/vars-on-top.js new file mode 100644 index 00000000..c790ccbd --- /dev/null +++ b/node_modules/eslint/lib/rules/vars-on-top.js @@ -0,0 +1,165 @@ +/** + * @fileoverview Rule to enforce var declarations are only at the top of a function. + * @author Danny Fritz + * @author Gyandeep Singh + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require `var` declarations be placed at the top of their containing scope", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/vars-on-top", + }, + + schema: [], + messages: { + top: "All 'var' declarations must be at the top of the function scope.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Has AST suggesting a directive. + * @param {ASTNode} node any node + * @returns {boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return ( + node.type === "ExpressionStatement" && + node.expression.type === "Literal" && + typeof node.expression.value === "string" + ); + } + + /** + * Check to see if its a ES6 import declaration + * @param {ASTNode} node any node + * @returns {boolean} whether the given node represents a import declaration + */ + function looksLikeImport(node) { + return ( + node.type === "ImportDeclaration" || + node.type === "ImportSpecifier" || + node.type === "ImportDefaultSpecifier" || + node.type === "ImportNamespaceSpecifier" + ); + } + + /** + * Checks whether a given node is a variable declaration or not. + * @param {ASTNode} node any node + * @returns {boolean} `true` if the node is a variable declaration. + */ + function isVariableDeclaration(node) { + return ( + node.type === "VariableDeclaration" || + (node.type === "ExportNamedDeclaration" && + node.declaration && + node.declaration.type === "VariableDeclaration") + ); + } + + /** + * Checks whether this variable is on top of the block body + * @param {ASTNode} node The node to check + * @param {ASTNode[]} statements collection of ASTNodes for the parent node block + * @returns {boolean} True if var is on top otherwise false + */ + function isVarOnTop(node, statements) { + const l = statements.length; + let i = 0; + + // Skip over directives and imports. Static blocks don't have either. + if (node.parent.type !== "StaticBlock") { + for (; i < l; ++i) { + if ( + !looksLikeDirective(statements[i]) && + !looksLikeImport(statements[i]) + ) { + break; + } + } + } + + for (; i < l; ++i) { + if (!isVariableDeclaration(statements[i])) { + return false; + } + if (statements[i] === node) { + return true; + } + } + + return false; + } + + /** + * Checks whether variable is on top at the global level + * @param {ASTNode} node The node to check + * @param {ASTNode} parent Parent of the node + * @returns {void} + */ + function globalVarCheck(node, parent) { + if (!isVarOnTop(node, parent.body)) { + context.report({ node, messageId: "top" }); + } + } + + /** + * Checks whether variable is on top at functional block scope level + * @param {ASTNode} node The node to check + * @returns {void} + */ + function blockScopeVarCheck(node) { + const { parent } = node; + + if ( + parent.type === "BlockStatement" && + /Function/u.test(parent.parent.type) && + isVarOnTop(node, parent.body) + ) { + return; + } + + if ( + parent.type === "StaticBlock" && + isVarOnTop(node, parent.body) + ) { + return; + } + + context.report({ node, messageId: "top" }); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "VariableDeclaration[kind='var']"(node) { + if (node.parent.type === "ExportNamedDeclaration") { + globalVarCheck(node.parent, node.parent.parent); + } else if (node.parent.type === "Program") { + globalVarCheck(node, node.parent); + } else { + blockScopeVarCheck(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/wrap-iife.js b/node_modules/eslint/lib/rules/wrap-iife.js new file mode 100644 index 00000000..9e846f3e --- /dev/null +++ b/node_modules/eslint/lib/rules/wrap-iife.js @@ -0,0 +1,238 @@ +/** + * @fileoverview Rule to flag when IIFE is not wrapped in parens + * @author Ilya Volodin + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const eslintUtils = require("@eslint-community/eslint-utils"); + +//---------------------------------------------------------------------- +// Helpers +//---------------------------------------------------------------------- + +/** + * Check if the given node is callee of a `NewExpression` node + * @param {ASTNode} node node to check + * @returns {boolean} True if the node is callee of a `NewExpression` node + * @private + */ +function isCalleeOfNewExpression(node) { + const maybeCallee = + node.parent.type === "ChainExpression" ? node.parent : node; + + return ( + maybeCallee.parent.type === "NewExpression" && + maybeCallee.parent.callee === maybeCallee + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "wrap-iife", + url: "https://eslint.style/rules/js/wrap-iife", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require parentheses around immediate `function` invocations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/wrap-iife", + }, + + schema: [ + { + enum: ["outside", "inside", "any"], + }, + { + type: "object", + properties: { + functionPrototypeMethods: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + messages: { + wrapInvocation: + "Wrap an immediate function invocation in parentheses.", + wrapExpression: "Wrap only the function expression in parens.", + moveInvocation: + "Move the invocation into the parens that contain the function.", + }, + }, + + create(context) { + const style = context.options[0] || "outside"; + const includeFunctionPrototypeMethods = + context.options[1] && context.options[1].functionPrototypeMethods; + + const sourceCode = context.sourceCode; + + /** + * Check if the node is wrapped in any (). All parens count: grouping parens and parens for constructs such as if() + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if it is wrapped in any parens + * @private + */ + function isWrappedInAnyParens(node) { + return astUtils.isParenthesised(sourceCode, node); + } + + /** + * Check if the node is wrapped in grouping (). Parens for constructs such as if() don't count + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if it is wrapped in grouping parens + * @private + */ + function isWrappedInGroupingParens(node) { + return eslintUtils.isParenthesized(1, node, sourceCode); + } + + /** + * Get the function node from an IIFE + * @param {ASTNode} node node to evaluate + * @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist + */ + function getFunctionNodeFromIIFE(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type === "FunctionExpression") { + return callee; + } + + if ( + includeFunctionPrototypeMethods && + callee.type === "MemberExpression" && + callee.object.type === "FunctionExpression" && + (astUtils.getStaticPropertyName(callee) === "call" || + astUtils.getStaticPropertyName(callee) === "apply") + ) { + return callee.object; + } + + return null; + } + + return { + CallExpression(node) { + const innerNode = getFunctionNodeFromIIFE(node); + + if (!innerNode) { + return; + } + + const isCallExpressionWrapped = isWrappedInAnyParens(node), + isFunctionExpressionWrapped = + isWrappedInAnyParens(innerNode); + + if (!isCallExpressionWrapped && !isFunctionExpressionWrapped) { + context.report({ + node, + messageId: "wrapInvocation", + fix(fixer) { + const nodeToSurround = + style === "inside" ? innerNode : node; + + return fixer.replaceText( + nodeToSurround, + `(${sourceCode.getText(nodeToSurround)})`, + ); + }, + }); + } else if (style === "inside" && !isFunctionExpressionWrapped) { + context.report({ + node, + messageId: "wrapExpression", + fix(fixer) { + // The outer call expression will always be wrapped at this point. + + if ( + isWrappedInGroupingParens(node) && + !isCalleeOfNewExpression(node) + ) { + /* + * Parenthesize the function expression and remove unnecessary grouping parens around the call expression. + * Replace the range between the end of the function expression and the end of the call expression. + * for example, in `(function(foo) {}(bar))`, the range `(bar))` should get replaced with `)(bar)`. + */ + + const parenAfter = + sourceCode.getTokenAfter(node); + + return fixer.replaceTextRange( + [innerNode.range[1], parenAfter.range[1]], + `)${sourceCode.getText().slice(innerNode.range[1], parenAfter.range[0])}`, + ); + } + + /* + * Call expression is wrapped in mandatory parens such as if(), or in necessary grouping parens. + * These parens cannot be removed, so just parenthesize the function expression. + */ + + return fixer.replaceText( + innerNode, + `(${sourceCode.getText(innerNode)})`, + ); + }, + }); + } else if (style === "outside" && !isCallExpressionWrapped) { + context.report({ + node, + messageId: "moveInvocation", + fix(fixer) { + /* + * The inner function expression will always be wrapped at this point. + * It's only necessary to replace the range between the end of the function expression + * and the call expression. For example, in `(function(foo) {})(bar)`, the range `)(bar)` + * should get replaced with `(bar))`. + */ + const parenAfter = + sourceCode.getTokenAfter(innerNode); + + return fixer.replaceTextRange( + [parenAfter.range[0], node.range[1]], + `${sourceCode.getText().slice(parenAfter.range[1], node.range[1])})`, + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/wrap-regex.js b/node_modules/eslint/lib/rules/wrap-regex.js new file mode 100644 index 00000000..1badfd8e --- /dev/null +++ b/node_modules/eslint/lib/rules/wrap-regex.js @@ -0,0 +1,91 @@ +/** + * @fileoverview Rule to flag when regex literals are not wrapped in parens + * @author Matt DuVall + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "wrap-regex", + url: "https://eslint.style/rules/js/wrap-regex", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require parenthesis around regex literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/wrap-regex", + }, + + schema: [], + fixable: "code", + + messages: { + requireParens: + "Wrap the regexp literal in parens to disambiguate the slash.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Literal(node) { + const token = sourceCode.getFirstToken(node), + nodeType = token.type; + + if (nodeType === "RegularExpression") { + const beforeToken = sourceCode.getTokenBefore(node); + const afterToken = sourceCode.getTokenAfter(node); + const { parent } = node; + + if ( + parent.type === "MemberExpression" && + parent.object === node && + !( + beforeToken && + beforeToken.value === "(" && + afterToken && + afterToken.value === ")" + ) + ) { + context.report({ + node, + messageId: "requireParens", + fix: fixer => + fixer.replaceText( + node, + `(${sourceCode.getText(node)})`, + ), + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/yield-star-spacing.js b/node_modules/eslint/lib/rules/yield-star-spacing.js new file mode 100644 index 00000000..68db5730 --- /dev/null +++ b/node_modules/eslint/lib/rules/yield-star-spacing.js @@ -0,0 +1,159 @@ +/** + * @fileoverview Rule to check the spacing around the * in yield* expressions. + * @author Bryan Smith + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "10.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin-js", + url: "https://eslint.style/packages/js", + }, + rule: { + name: "yield-star-spacing", + url: "https://eslint.style/rules/js/yield-star-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow spacing around the `*` in `yield*` expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/yield-star-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["before", "after", "both", "neither"], + }, + { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + missingBefore: "Missing space before *.", + missingAfter: "Missing space after *.", + unexpectedBefore: "Unexpected space before *.", + unexpectedAfter: "Unexpected space after *.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const mode = (function (option) { + if (!option || typeof option === "string") { + return { + before: { before: true, after: false }, + after: { before: false, after: true }, + both: { before: true, after: true }, + neither: { before: false, after: false }, + }[option || "after"]; + } + return option; + })(context.options[0]); + + /** + * Checks the spacing between two tokens before or after the star token. + * @param {string} side Either "before" or "after". + * @param {Token} leftToken `function` keyword token if side is "before", or + * star token if side is "after". + * @param {Token} rightToken Star token if side is "before", or identifier + * token if side is "after". + * @returns {void} + */ + function checkSpacing(side, leftToken, rightToken) { + if ( + sourceCode.isSpaceBetweenTokens(leftToken, rightToken) !== + mode[side] + ) { + const after = leftToken.value === "*"; + const spaceRequired = mode[side]; + const node = after ? leftToken : rightToken; + let messageId; + + if (spaceRequired) { + messageId = + side === "before" ? "missingBefore" : "missingAfter"; + } else { + messageId = + side === "before" + ? "unexpectedBefore" + : "unexpectedAfter"; + } + + context.report({ + node, + messageId, + fix(fixer) { + if (spaceRequired) { + if (after) { + return fixer.insertTextAfter(node, " "); + } + return fixer.insertTextBefore(node, " "); + } + return fixer.removeRange([ + leftToken.range[1], + rightToken.range[0], + ]); + }, + }); + } + } + + /** + * Enforces the spacing around the star if node is a yield* expression. + * @param {ASTNode} node A yield expression node. + * @returns {void} + */ + function checkExpression(node) { + if (!node.delegate) { + return; + } + + const tokens = sourceCode.getFirstTokens(node, 3); + const yieldToken = tokens[0]; + const starToken = tokens[1]; + const nextToken = tokens[2]; + + checkSpacing("before", yieldToken, starToken); + checkSpacing("after", starToken, nextToken); + } + + return { + YieldExpression: checkExpression, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/yoda.js b/node_modules/eslint/lib/rules/yoda.js new file mode 100644 index 00000000..6b689349 --- /dev/null +++ b/node_modules/eslint/lib/rules/yoda.js @@ -0,0 +1,362 @@ +/** + * @fileoverview Rule to require or disallow yoda comparisons + * @author Nicholas C. Zakas + */ +"use strict"; + +//-------------------------------------------------------------------------- +// Requirements +//-------------------------------------------------------------------------- + +const astUtils = require("./utils/ast-utils"); + +//-------------------------------------------------------------------------- +// Helpers +//-------------------------------------------------------------------------- + +/** + * Determines whether an operator is a comparison operator. + * @param {string} operator The operator to check. + * @returns {boolean} Whether or not it is a comparison operator. + */ +function isComparisonOperator(operator) { + return /^(==|===|!=|!==|<|>|<=|>=)$/u.test(operator); +} + +/** + * Determines whether an operator is an equality operator. + * @param {string} operator The operator to check. + * @returns {boolean} Whether or not it is an equality operator. + */ +function isEqualityOperator(operator) { + return /^(==|===)$/u.test(operator); +} + +/** + * Determines whether an operator is one used in a range test. + * Allowed operators are `<` and `<=`. + * @param {string} operator The operator to check. + * @returns {boolean} Whether the operator is used in range tests. + */ +function isRangeTestOperator(operator) { + return ["<", "<="].includes(operator); +} + +/** + * Determines whether a non-Literal node is a negative number that should be + * treated as if it were a single Literal node. + * @param {ASTNode} node Node to test. + * @returns {boolean} True if the node is a negative number that looks like a + * real literal and should be treated as such. + */ +function isNegativeNumericLiteral(node) { + return ( + node.type === "UnaryExpression" && + node.operator === "-" && + node.prefix && + astUtils.isNumericLiteral(node.argument) + ); +} + +/** + * Determines whether a non-Literal node should be treated as a single Literal node. + * @param {ASTNode} node Node to test + * @returns {boolean} True if the node should be treated as a single Literal node. + */ +function looksLikeLiteral(node) { + return ( + isNegativeNumericLiteral(node) || astUtils.isStaticTemplateLiteral(node) + ); +} + +/** + * Attempts to derive a Literal node from nodes that are treated like literals. + * @param {ASTNode} node Node to normalize. + * @returns {ASTNode} One of the following options. + * 1. The original node if the node is already a Literal + * 2. A normalized Literal node with the negative number as the value if the + * node represents a negative number literal. + * 3. A normalized Literal node with the string as the value if the node is + * a Template Literal without expression. + * 4. Otherwise `null`. + */ +function getNormalizedLiteral(node) { + if (node.type === "Literal") { + return node; + } + + if (isNegativeNumericLiteral(node)) { + return { + type: "Literal", + value: -node.argument.value, + raw: `-${node.argument.value}`, + }; + } + + if (astUtils.isStaticTemplateLiteral(node)) { + return { + type: "Literal", + value: node.quasis[0].value.cooked, + raw: node.quasis[0].value.raw, + }; + } + + return null; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + "never", + { + exceptRange: false, + onlyEquality: false, + }, + ], + + docs: { + description: 'Require or disallow "Yoda" conditions', + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/yoda", + }, + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + exceptRange: { + type: "boolean", + }, + onlyEquality: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + messages: { + expected: + "Expected literal to be on the {{expectedSide}} side of {{operator}}.", + }, + }, + + create(context) { + const [when, { exceptRange, onlyEquality }] = context.options; + const always = when === "always"; + const sourceCode = context.sourceCode; + + /** + * Determines whether node represents a range test. + * A range test is a "between" test like `(0 <= x && x < 1)` or an "outside" + * test like `(x < 0 || 1 <= x)`. It must be wrapped in parentheses, and + * both operators must be `<` or `<=`. Finally, the literal on the left side + * must be less than or equal to the literal on the right side so that the + * test makes any sense. + * @param {ASTNode} node LogicalExpression node to test. + * @returns {boolean} Whether node is a range test. + */ + function isRangeTest(node) { + const left = node.left, + right = node.right; + + /** + * Determines whether node is of the form `0 <= x && x < 1`. + * @returns {boolean} Whether node is a "between" range test. + */ + function isBetweenTest() { + if ( + node.operator === "&&" && + astUtils.isSameReference(left.right, right.left) + ) { + const leftLiteral = getNormalizedLiteral(left.left); + const rightLiteral = getNormalizedLiteral(right.right); + + if (leftLiteral === null && rightLiteral === null) { + return false; + } + + if (rightLiteral === null || leftLiteral === null) { + return true; + } + + if (leftLiteral.value <= rightLiteral.value) { + return true; + } + } + return false; + } + + /** + * Determines whether node is of the form `x < 0 || 1 <= x`. + * @returns {boolean} Whether node is an "outside" range test. + */ + function isOutsideTest() { + if ( + node.operator === "||" && + astUtils.isSameReference(left.left, right.right) + ) { + const leftLiteral = getNormalizedLiteral(left.right); + const rightLiteral = getNormalizedLiteral(right.left); + + if (leftLiteral === null && rightLiteral === null) { + return false; + } + + if (rightLiteral === null || leftLiteral === null) { + return true; + } + + if (leftLiteral.value <= rightLiteral.value) { + return true; + } + } + + return false; + } + + /** + * Determines whether node is wrapped in parentheses. + * @returns {boolean} Whether node is preceded immediately by an open + * paren token and followed immediately by a close + * paren token. + */ + function isParenWrapped() { + return astUtils.isParenthesised(sourceCode, node); + } + + return ( + node.type === "LogicalExpression" && + left.type === "BinaryExpression" && + right.type === "BinaryExpression" && + isRangeTestOperator(left.operator) && + isRangeTestOperator(right.operator) && + (isBetweenTest() || isOutsideTest()) && + isParenWrapped() + ); + } + + const OPERATOR_FLIP_MAP = { + "===": "===", + "!==": "!==", + "==": "==", + "!=": "!=", + "<": ">", + ">": "<", + "<=": ">=", + ">=": "<=", + }; + + /** + * Returns a string representation of a BinaryExpression node with its sides/operator flipped around. + * @param {ASTNode} node The BinaryExpression node + * @returns {string} A string representation of the node with the sides and operator flipped + */ + function getFlippedString(node) { + const operatorToken = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + const lastLeftToken = sourceCode.getTokenBefore(operatorToken); + const firstRightToken = sourceCode.getTokenAfter(operatorToken); + + const source = sourceCode.getText(); + + const leftText = source.slice( + node.range[0], + lastLeftToken.range[1], + ); + const textBeforeOperator = source.slice( + lastLeftToken.range[1], + operatorToken.range[0], + ); + const textAfterOperator = source.slice( + operatorToken.range[1], + firstRightToken.range[0], + ); + const rightText = source.slice( + firstRightToken.range[0], + node.range[1], + ); + + const tokenBefore = sourceCode.getTokenBefore(node); + const tokenAfter = sourceCode.getTokenAfter(node); + let prefix = ""; + let suffix = ""; + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, firstRightToken) + ) { + prefix = " "; + } + + if ( + tokenAfter && + node.range[1] === tokenAfter.range[0] && + !astUtils.canTokensBeAdjacent(lastLeftToken, tokenAfter) + ) { + suffix = " "; + } + + return ( + prefix + + rightText + + textBeforeOperator + + OPERATOR_FLIP_MAP[operatorToken.value] + + textAfterOperator + + leftText + + suffix + ); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + BinaryExpression(node) { + const expectedLiteral = always ? node.left : node.right; + const expectedNonLiteral = always ? node.right : node.left; + + // If `expectedLiteral` is not a literal, and `expectedNonLiteral` is a literal, raise an error. + if ( + (expectedNonLiteral.type === "Literal" || + looksLikeLiteral(expectedNonLiteral)) && + !( + expectedLiteral.type === "Literal" || + looksLikeLiteral(expectedLiteral) + ) && + !(!isEqualityOperator(node.operator) && onlyEquality) && + isComparisonOperator(node.operator) && + !(exceptRange && isRangeTest(node.parent)) + ) { + context.report({ + node, + messageId: "expected", + data: { + operator: node.operator, + expectedSide: always ? "left" : "right", + }, + fix: fixer => + fixer.replaceText(node, getFlippedString(node)), + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/services/parser-service.js b/node_modules/eslint/lib/services/parser-service.js new file mode 100644 index 00000000..580bb69d --- /dev/null +++ b/node_modules/eslint/lib/services/parser-service.js @@ -0,0 +1,65 @@ +/** + * @fileoverview ESLint Parser + * @author Nicholas C. Zakas + */ +/* eslint class-methods-use-this: off -- Anticipate future constructor arguments. */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("../linter/vfile.js").VFile} VFile */ +/** @typedef {import("@eslint/core").Language} Language */ +/** @typedef {import("@eslint/core").LanguageOptions} LanguageOptions */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * The parser for ESLint. + */ +class ParserService { + /** + * Parses the given file synchronously. + * @param {VFile} file The file to parse. + * @param {{language:Language,languageOptions:LanguageOptions}} config The configuration to use. + * @returns {Object} An object with the parsed source code or errors. + * @throws {Error} If the parser returns a promise. + */ + parseSync(file, config) { + const { language, languageOptions } = config; + const result = language.parse(file, { languageOptions }); + + if (typeof result.then === "function") { + throw new Error("Unsupported: Language parser returned a promise."); + } + + if (result.ok) { + return { + ok: true, + sourceCode: language.createSourceCode(file, result, { + languageOptions, + }), + }; + } + + // if we made it to here there was an error + return { + ok: false, + errors: result.errors.map(error => ({ + ruleId: null, + nodeType: null, + fatal: true, + severity: 2, + message: `Parsing error: ${error.message}`, + line: error.line, + column: error.column, + })), + }; + } +} + +module.exports = { ParserService }; diff --git a/node_modules/eslint/lib/services/processor-service.js b/node_modules/eslint/lib/services/processor-service.js new file mode 100644 index 00000000..a5447a80 --- /dev/null +++ b/node_modules/eslint/lib/services/processor-service.js @@ -0,0 +1,101 @@ +/** + * @fileoverview ESLint Processor Service + * @author Nicholas C. Zakas + */ +/* eslint class-methods-use-this: off -- Anticipate future constructor arguments. */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const path = require("node:path"); +const { VFile } = require("../linter/vfile.js"); + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../linter/vfile.js").VFile} VFile */ +/** @typedef {import("@eslint/core").Language} Language */ +/** @typedef {import("eslint").Linter.Processor} Processor */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * The service that applies processors to files. + */ +class ProcessorService { + /** + * Preprocesses the given file synchronously. + * @param {VFile} file The file to preprocess. + * @param {{processor:Processor}} config The configuration to use. + * @returns {{ok:boolean, files?: Array, errors?: Array}} An array of preprocessed files or errors. + * @throws {Error} If the preprocessor returns a promise. + */ + preprocessSync(file, config) { + const { processor } = config; + let blocks; + + try { + blocks = processor.preprocess(file.rawBody, file.path); + } catch (ex) { + // If the message includes a leading line number, strip it: + const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`; + + return { + ok: false, + errors: [ + { + ruleId: null, + fatal: true, + severity: 2, + message, + line: ex.lineNumber, + column: ex.column, + nodeType: null, + }, + ], + }; + } + + if (typeof blocks.then === "function") { + throw new Error("Unsupported: Preprocessor returned a promise."); + } + + return { + ok: true, + files: blocks.map((block, i) => { + // Legacy behavior: return the block as a string + if (typeof block === "string") { + return block; + } + + const filePath = path.join(file.path, `${i}_${block.filename}`); + + return new VFile(filePath, block.text, { + physicalPath: file.physicalPath, + }); + }), + }; + } + + /** + * Postprocesses the given messages synchronously. + * @param {VFile} file The file to postprocess. + * @param {LintMessage[][]} messages The messages to postprocess. + * @param {{processor:Processor}} config The configuration to use. + * @returns {LintMessage[]} The postprocessed messages. + */ + postprocessSync(file, messages, config) { + const { processor } = config; + + return processor.postprocess(messages, file.path); + } +} + +module.exports = { ProcessorService }; diff --git a/node_modules/eslint/lib/services/suppressions-service.js b/node_modules/eslint/lib/services/suppressions-service.js new file mode 100644 index 00000000..0aeb2bed --- /dev/null +++ b/node_modules/eslint/lib/services/suppressions-service.js @@ -0,0 +1,299 @@ +/** + * @fileoverview Manages the suppressed violations. + * @author Iacovos Constantinou + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const fs = require("node:fs"); +const path = require("node:path"); +const { calculateStatsPerFile } = require("../eslint/eslint-helpers"); +const stringify = require("json-stable-stringify-without-jsonify"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +// For VSCode IntelliSense +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").ESLint.LintResult} LintResult */ +/** @typedef {Record>} SuppressedViolations */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Manages the suppressed violations. + */ +class SuppressionsService { + filePath = ""; + cwd = ""; + + /** + * Creates a new instance of SuppressionsService. + * @param {Object} options The options. + * @param {string} [options.filePath] The location of the suppressions file. + * @param {string} [options.cwd] The current working directory. + */ + constructor({ filePath, cwd }) { + this.filePath = filePath; + this.cwd = cwd; + } + + /** + * Updates the suppressions file based on the current violations and the provided rules. + * If no rules are provided, all violations are suppressed. + * @param {LintResult[]|undefined} results The lint results. + * @param {string[]|undefined} rules The rules to suppress. + * @returns {Promise} + */ + async suppress(results, rules) { + const suppressions = await this.load(); + + for (const result of results) { + const relativeFilePath = this.getRelativeFilePath(result.filePath); + const violationsByRule = SuppressionsService.countViolationsByRule( + result.messages, + ); + + for (const ruleId in violationsByRule) { + if (rules && !rules.includes(ruleId)) { + continue; + } + + suppressions[relativeFilePath] ??= {}; + suppressions[relativeFilePath][ruleId] = + violationsByRule[ruleId]; + } + } + + return this.save(suppressions); + } + + /** + * Removes old, unused suppressions for violations that do not occur anymore. + * @param {LintResult[]} results The lint results. + * @returns {Promise} No return value. + */ + async prune(results) { + const suppressions = await this.load(); + const { unused } = this.applySuppressions(results, suppressions); + + for (const file in unused) { + if (!suppressions[file]) { + continue; + } + + for (const rule in unused[file]) { + if (!suppressions[file][rule]) { + continue; + } + + const suppressionsCount = suppressions[file][rule].count; + const violationsCount = unused[file][rule].count; + + if (suppressionsCount === violationsCount) { + // Remove unused rules + delete suppressions[file][rule]; + } else { + // Update the count to match the new number of violations + suppressions[file][rule].count -= violationsCount; + } + } + + // Cleanup files with no rules + if (Object.keys(suppressions[file]).length === 0) { + delete suppressions[file]; + } + } + + for (const file of Object.keys(suppressions)) { + const absolutePath = path.resolve(this.cwd, file); + + if (!fs.existsSync(absolutePath)) { + delete suppressions[file]; + } + } + + return this.save(suppressions); + } + + /** + * Checks the provided suppressions against the lint results. + * + * For each file, counts the number of violations per rule. + * For each rule in each file, compares the number of violations against the counter from the suppressions file. + * If the number of violations is less or equal to the counter, messages are moved to `LintResult#suppressedMessages` and ignored. + * Otherwise, all violations are reported as usual. + * @param {LintResult[]} results The lint results. + * @param {SuppressedViolations} suppressions The suppressions. + * @returns {{ + * results: LintResult[], + * unused: SuppressedViolations + * }} The updated results and the unused suppressions. + */ + applySuppressions(results, suppressions) { + /** + * We copy the results to avoid modifying the original objects + * We remove only result messages that are matched and hence suppressed + * We leave the rest untouched to minimize the risk of losing parts of the original data + */ + const filtered = structuredClone(results); + const unused = {}; + + for (const result of filtered) { + const relativeFilePath = this.getRelativeFilePath(result.filePath); + + if (!suppressions[relativeFilePath]) { + continue; + } + + const violationsByRule = SuppressionsService.countViolationsByRule( + result.messages, + ); + let wasSuppressed = false; + + for (const ruleId in violationsByRule) { + if (!suppressions[relativeFilePath][ruleId]) { + continue; + } + + const suppressionsCount = + suppressions[relativeFilePath][ruleId].count; + const violationsCount = violationsByRule[ruleId].count; + + // Suppress messages if the number of violations is less or equal to the suppressions count + if (violationsCount <= suppressionsCount) { + SuppressionsService.suppressMessagesByRule(result, ruleId); + wasSuppressed = true; + } + + // Update the count to match the new number of violations, otherwise remove the rule entirely + if (violationsCount < suppressionsCount) { + unused[relativeFilePath] ??= {}; + unused[relativeFilePath][ruleId] ??= {}; + unused[relativeFilePath][ruleId].count = + suppressionsCount - violationsCount; + } + } + + // Mark as unused all the suppressions that were not matched against a rule + for (const ruleId in suppressions[relativeFilePath]) { + if (violationsByRule[ruleId]) { + continue; + } + + unused[relativeFilePath] ??= {}; + unused[relativeFilePath][ruleId] = + suppressions[relativeFilePath][ruleId]; + } + + // Recalculate stats if messages were suppressed + if (wasSuppressed) { + Object.assign(result, calculateStatsPerFile(result.messages)); + } + } + + return { + results: filtered, + unused, + }; + } + + /** + * Loads the suppressions file. + * @throws {Error} If the suppressions file cannot be parsed. + * @returns {Promise} The suppressions. + */ + async load() { + try { + const data = await fs.promises.readFile(this.filePath, "utf8"); + + return JSON.parse(data); + } catch (err) { + if (err.code === "ENOENT") { + return {}; + } + throw new Error( + `Failed to parse suppressions file at ${this.filePath}`, + ); + } + } + + /** + * Updates the suppressions file. + * @param {SuppressedViolations} suppressions The suppressions to save. + * @returns {Promise} + * @private + */ + save(suppressions) { + return fs.promises.writeFile( + this.filePath, + stringify(suppressions, { space: 2 }), + ); + } + + /** + * Counts the violations by rule, ignoring warnings. + * @param {LintMessage[]} messages The messages to count. + * @returns {Record} The number of violations by rule. + */ + static countViolationsByRule(messages) { + return messages.reduce((totals, message) => { + if (message.severity === 2 && message.ruleId) { + totals[message.ruleId] ??= { count: 0 }; + totals[message.ruleId].count++; + } + return totals; + }, {}); + } + + /** + * Returns the relative path of a file to the current working directory. + * Always in POSIX format for consistency and interoperability. + * @param {string} filePath The file path. + * @returns {string} The relative file path. + */ + getRelativeFilePath(filePath) { + return path + .relative(this.cwd, filePath) + .split(path.sep) + .join(path.posix.sep); + } + + /** + * Moves the messages matching the rule to `LintResult#suppressedMessages` and updates the stats. + * @param {LintResult} result The result to update. + * @param {string} ruleId The rule to suppress. + * @returns {void} + */ + static suppressMessagesByRule(result, ruleId) { + const suppressedMessages = result.messages.filter( + message => message.ruleId === ruleId, + ); + + result.suppressedMessages = result.suppressedMessages.concat( + suppressedMessages.map(message => { + message.suppressions = [ + { + kind: "file", + justification: "", + }, + ]; + + return message; + }), + ); + + result.messages = result.messages.filter( + message => message.ruleId !== ruleId, + ); + } +} + +module.exports = { SuppressionsService }; diff --git a/node_modules/eslint/lib/services/warning-service.js b/node_modules/eslint/lib/services/warning-service.js new file mode 100644 index 00000000..13007b85 --- /dev/null +++ b/node_modules/eslint/lib/services/warning-service.js @@ -0,0 +1,85 @@ +/** + * @fileoverview Emits warnings for ESLint. + * @author Francesco Trotta + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A service that emits warnings for ESLint. + */ +class WarningService { + /** + * Creates a new instance of the service. + * @param {{ emitWarning?: ((warning: string, type: string) => void) | undefined }} [options] A function called internally to emit warnings using API provided by the runtime. + */ + constructor({ + emitWarning = globalThis.process?.emitWarning ?? (() => {}), + } = {}) { + this.emitWarning = emitWarning; + } + + /** + * Emits a warning when circular fixes are detected while fixing a file. + * This method is used by the Linter and is safe to call outside Node.js. + * @param {string} filename The name of the file being fixed. + * @returns {void} + */ + emitCircularFixesWarning(filename) { + this.emitWarning( + `Circular fixes detected while fixing ${filename}. It is likely that you have conflicting rules in your configuration.`, + "ESLintCircularFixesWarning", + ); + } + + /** + * Emits a warning when an empty config file has been loaded. + * @param {string} configFilePath The path to the config file. + * @returns {void} + */ + emitEmptyConfigWarning(configFilePath) { + this.emitWarning( + `Running ESLint with an empty config (from ${configFilePath}). Please double-check that this is what you want. If you want to run ESLint with an empty config, export [{}] to remove this warning.`, + "ESLintEmptyConfigWarning", + ); + } + + /** + * Emits a warning when an ".eslintignore" file is found. + * @returns {void} + */ + emitESLintIgnoreWarning() { + this.emitWarning( + 'The ".eslintignore" file is no longer supported. Switch to using the "ignores" property in "eslint.config.js": https://eslint.org/docs/latest/use/configure/migration-guide#ignoring-files', + "ESLintIgnoreWarning", + ); + } + + /** + * Emits a warning when the ESLINT_USE_FLAT_CONFIG environment variable is set to "false". + * @returns {void} + */ + emitESLintRCWarning() { + this.emitWarning( + "You are using an eslintrc configuration file, which is deprecated and support will be removed in v10.0.0. Please migrate to an eslint.config.js file. See https://eslint.org/docs/latest/use/configure/migration-guide for details. An eslintrc configuration file is used because you have the ESLINT_USE_FLAT_CONFIG environment variable set to false. If you want to use an eslint.config.js file, remove the environment variable. If you want to find the location of the eslintrc configuration file, use the --debug flag.", + "ESLintRCWarning", + ); + } + + /** + * Emits a warning when an inactive flag is used. + * This method is used by the Linter and is safe to call outside Node.js. + * @param {string} flag The name of the flag. + * @param {string} message The warning message. + * @returns {void} + */ + emitInactiveFlagWarning(flag, message) { + this.emitWarning(message, `ESLintInactiveFlag_${flag}`); + } +} + +module.exports = { WarningService }; diff --git a/node_modules/eslint/lib/shared/ajv.js b/node_modules/eslint/lib/shared/ajv.js new file mode 100644 index 00000000..5c5c41bd --- /dev/null +++ b/node_modules/eslint/lib/shared/ajv.js @@ -0,0 +1,34 @@ +/** + * @fileoverview The instance of Ajv validator. + * @author Evgeny Poberezkin + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Ajv = require("ajv"), + metaSchema = require("ajv/lib/refs/json-schema-draft-04.json"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = (additionalOptions = {}) => { + const ajv = new Ajv({ + meta: false, + useDefaults: true, + validateSchema: false, + missingRefs: "ignore", + verbose: true, + schemaId: "auto", + ...additionalOptions, + }); + + ajv.addMetaSchema(metaSchema); + // eslint-disable-next-line no-underscore-dangle -- Ajv's API + ajv._opts.defaultMeta = metaSchema.id; + + return ajv; +}; diff --git a/node_modules/eslint/lib/shared/assert.js b/node_modules/eslint/lib/shared/assert.js new file mode 100644 index 00000000..4dcaf41f --- /dev/null +++ b/node_modules/eslint/lib/shared/assert.js @@ -0,0 +1,21 @@ +/** + * @fileoverview Assertion utilities equivalent to the Node.js node:asserts module. + * @author Josh Goldberg + */ + +"use strict"; + +/** + * Throws an error if the input is not truthy. + * @param {unknown} value The input that is checked for being truthy. + * @param {string} message Message to throw if the input is not truthy. + * @returns {void} + * @throws {Error} When the condition is not truthy. + */ +function ok(value, message = "Assertion failed.") { + if (!value) { + throw new Error(message); + } +} + +module.exports = ok; diff --git a/node_modules/eslint/lib/shared/ast-utils.js b/node_modules/eslint/lib/shared/ast-utils.js new file mode 100644 index 00000000..f7736828 --- /dev/null +++ b/node_modules/eslint/lib/shared/ast-utils.js @@ -0,0 +1,30 @@ +/** + * @fileoverview Common utils for AST. + * + * This file contains only shared items for core and rules. + * If you make a utility for rules, please see `../rules/utils/ast-utils.js`. + * + * @author Toru Nagashima + */ +"use strict"; + +const breakableTypePattern = + /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u; +const lineBreakPattern = /\r\n|[\r\n\u2028\u2029]/u; +const shebangPattern = /^#!([^\r\n]+)/u; + +/** + * Creates a version of the `lineBreakPattern` regex with the global flag. + * Global regexes are mutable, so this needs to be a function instead of a constant. + * @returns {RegExp} A global regular expression that matches line terminators + */ +function createGlobalLinebreakMatcher() { + return new RegExp(lineBreakPattern.source, "gu"); +} + +module.exports = { + breakableTypePattern, + lineBreakPattern, + createGlobalLinebreakMatcher, + shebangPattern, +}; diff --git a/node_modules/eslint/lib/shared/deep-merge-arrays.js b/node_modules/eslint/lib/shared/deep-merge-arrays.js new file mode 100644 index 00000000..4a8289c4 --- /dev/null +++ b/node_modules/eslint/lib/shared/deep-merge-arrays.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Applies default rule options + * @author JoshuaKGoldberg + */ + +"use strict"; + +/** + * Check if the variable contains an object strictly rejecting arrays + * @param {unknown} value an object + * @returns {boolean} Whether value is an object + */ +function isObjectNotArray(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Deeply merges second on top of first, creating a new {} object if needed. + * @param {T} first Base, default value. + * @param {U} second User-specified value. + * @returns {T | U | (T & U)} Merged equivalent of second on top of first. + */ +function deepMergeObjects(first, second) { + if (second === void 0) { + return first; + } + + if (!isObjectNotArray(first) || !isObjectNotArray(second)) { + return second; + } + + const result = { ...first, ...second }; + + for (const key of Object.keys(second)) { + if (Object.prototype.propertyIsEnumerable.call(first, key)) { + result[key] = deepMergeObjects(first[key], second[key]); + } + } + + return result; +} + +/** + * Deeply merges second on top of first, creating a new [] array if needed. + * @param {T[]} first Base, default values. + * @param {U[]} second User-specified values. + * @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first. + */ +function deepMergeArrays(first, second) { + if (!first || !second) { + return second || first || []; + } + + return [ + ...first.map((value, i) => + deepMergeObjects(value, i < second.length ? second[i] : void 0), + ), + ...second.slice(first.length), + ]; +} + +module.exports = { deepMergeArrays }; diff --git a/node_modules/eslint/lib/shared/directives.js b/node_modules/eslint/lib/shared/directives.js new file mode 100644 index 00000000..f1dddf59 --- /dev/null +++ b/node_modules/eslint/lib/shared/directives.js @@ -0,0 +1,16 @@ +/** + * @fileoverview Common utils for directives. + * + * This file contains only shared items for directives. + * If you make a utility for rules, please see `../rules/utils/ast-utils.js`. + * + * @author gfyoung + */ +"use strict"; + +const directivesPattern = + /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u; + +module.exports = { + directivesPattern, +}; diff --git a/node_modules/eslint/lib/shared/flags.js b/node_modules/eslint/lib/shared/flags.js new file mode 100644 index 00000000..526cf910 --- /dev/null +++ b/node_modules/eslint/lib/shared/flags.js @@ -0,0 +1,100 @@ +/** + * @fileoverview Shared flags for ESLint. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @typedef {Object} InactiveFlagData + * @property {string} description Flag description + * @property {string | null} [replacedBy] Can be either: + * - An active flag (string) that enables the same feature. + * - `null` if the feature is now enabled by default. + * - Omitted if the feature has been abandoned. + */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * The set of flags that change ESLint behavior with a description. + * @type {Map} + */ +const activeFlags = new Map([ + ["test_only", "Used only for testing."], + ["test_only_2", "Used only for testing."], + [ + "unstable_config_lookup_from_file", + "Look up `eslint.config.js` from the file being linted.", + ], + [ + "unstable_native_nodejs_ts_config", + "Use native Node.js to load TypeScript configuration.", + ], +]); + +/** + * The set of flags that used to be active. + * @type {Map} + */ +const inactiveFlags = new Map([ + [ + "test_only_replaced", + { + description: + "Used only for testing flags that have been replaced by other flags.", + replacedBy: "test_only", + }, + ], + [ + "test_only_enabled_by_default", + { + description: + "Used only for testing flags whose features have been enabled by default.", + replacedBy: null, + }, + ], + [ + "test_only_abandoned", + { + description: + "Used only for testing flags whose features have been abandoned.", + }, + ], + [ + "unstable_ts_config", + { + description: "Enable TypeScript configuration files.", + replacedBy: null, + }, + ], +]); + +/** + * Creates a message that describes the reason the flag is inactive. + * @param {InactiveFlagData} inactiveFlagData Data for the inactive flag. + * @returns {string} Message describing the reason the flag is inactive. + */ +function getInactivityReasonMessage({ replacedBy }) { + if (typeof replacedBy === "undefined") { + return "This feature has been abandoned."; + } + + if (typeof replacedBy === "string") { + return `This flag has been renamed '${replacedBy}' to reflect its stabilization. Please use '${replacedBy}' instead.`; + } + + // null + return "This feature is now enabled by default."; +} + +module.exports = { + activeFlags, + inactiveFlags, + getInactivityReasonMessage, +}; diff --git a/node_modules/eslint/lib/shared/logging.js b/node_modules/eslint/lib/shared/logging.js new file mode 100644 index 00000000..3e8dfb0b --- /dev/null +++ b/node_modules/eslint/lib/shared/logging.js @@ -0,0 +1,38 @@ +/** + * @fileoverview Handle logging for ESLint + * @author Gyandeep Singh + */ + +"use strict"; + +/* eslint no-console: "off" -- Logging util */ + +/* c8 ignore next */ +module.exports = { + /** + * Cover for console.info + * @param {...any} args The elements to log. + * @returns {void} + */ + info(...args) { + console.log(...args); + }, + + /** + * Cover for console.warn + * @param {...any} args The elements to log. + * @returns {void} + */ + warn(...args) { + console.warn(...args); + }, + + /** + * Cover for console.error + * @param {...any} args The elements to log. + * @returns {void} + */ + error(...args) { + console.error(...args); + }, +}; diff --git a/node_modules/eslint/lib/shared/naming.js b/node_modules/eslint/lib/shared/naming.js new file mode 100644 index 00000000..a9d065f8 --- /dev/null +++ b/node_modules/eslint/lib/shared/naming.js @@ -0,0 +1,109 @@ +/** + * @fileoverview Common helpers for naming of plugins, formatters and configs + */ + +"use strict"; + +const NAMESPACE_REGEX = /^@.*\//iu; + +/** + * Brings package name to correct format based on prefix + * @param {string} name The name of the package. + * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter" + * @returns {string} Normalized name of the package + * @private + */ +function normalizePackageName(name, prefix) { + let normalizedName = name; + + /** + * On Windows, name can come in with Windows slashes instead of Unix slashes. + * Normalize to Unix first to avoid errors later on. + * https://github.com/eslint/eslint/issues/5644 + */ + if (normalizedName.includes("\\")) { + normalizedName = normalizedName.replace(/\\/gu, "/"); + } + + if (normalizedName.charAt(0) === "@") { + /** + * it's a scoped package + * package name is the prefix, or just a username + */ + const scopedPackageShortcutRegex = new RegExp( + `^(@[^/]+)(?:/(?:${prefix})?)?$`, + "u", + ), + scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u"); + + if (scopedPackageShortcutRegex.test(normalizedName)) { + normalizedName = normalizedName.replace( + scopedPackageShortcutRegex, + `$1/${prefix}`, + ); + } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) { + /** + * for scoped packages, insert the prefix after the first / unless + * the path is already @scope/eslint or @scope/eslint-xxx-yyy + */ + normalizedName = normalizedName.replace( + /^@([^/]+)\/(.*)$/u, + `@$1/${prefix}-$2`, + ); + } + } else if (!normalizedName.startsWith(`${prefix}-`)) { + normalizedName = `${prefix}-${normalizedName}`; + } + + return normalizedName; +} + +/** + * Removes the prefix from a fullname. + * @param {string} fullname The term which may have the prefix. + * @param {string} prefix The prefix to remove. + * @returns {string} The term without prefix. + */ +function getShorthandName(fullname, prefix) { + if (fullname[0] === "@") { + let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec( + fullname, + ); + + if (matchResult) { + return matchResult[1]; + } + + matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec( + fullname, + ); + if (matchResult) { + return `${matchResult[1]}/${matchResult[2]}`; + } + } else if (fullname.startsWith(`${prefix}-`)) { + return fullname.slice(prefix.length + 1); + } + + return fullname; +} + +/** + * Gets the scope (namespace) of a term. + * @param {string} term The term which may have the namespace. + * @returns {string} The namespace of the term if it has one. + */ +function getNamespaceFromTerm(term) { + const match = term.match(NAMESPACE_REGEX); + + return match ? match[0] : ""; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + normalizePackageName, + getShorthandName, + getNamespaceFromTerm, +}; diff --git a/node_modules/eslint/lib/shared/option-utils.js b/node_modules/eslint/lib/shared/option-utils.js new file mode 100644 index 00000000..0917ba52 --- /dev/null +++ b/node_modules/eslint/lib/shared/option-utils.js @@ -0,0 +1,63 @@ +/** + * @fileoverview Utilities to operate on option objects. + * @author Josh Goldberg + */ + +"use strict"; + +/** + * Determines whether any of input's properties are different + * from values that already exist in original. + * @template T + * @param {Partial} input New value. + * @param {T} original Original value. + * @returns {boolean} Whether input includes an explicit difference. + */ +function containsDifferentProperty(input, original) { + if (input === original) { + return false; + } + + if ( + typeof input !== typeof original || + Array.isArray(input) !== Array.isArray(original) + ) { + return true; + } + + if (Array.isArray(input)) { + return ( + input.length !== original.length || + input.some((value, i) => + containsDifferentProperty(value, original[i]), + ) + ); + } + + if (typeof input === "object") { + if (input === null || original === null) { + return true; + } + + const inputKeys = Object.keys(input); + const originalKeys = Object.keys(original); + + return ( + inputKeys.length !== originalKeys.length || + inputKeys.some( + inputKey => + !Object.hasOwn(original, inputKey) || + containsDifferentProperty( + input[inputKey], + original[inputKey], + ), + ) + ); + } + + return true; +} + +module.exports = { + containsDifferentProperty, +}; diff --git a/node_modules/eslint/lib/shared/relative-module-resolver.js b/node_modules/eslint/lib/shared/relative-module-resolver.js new file mode 100644 index 00000000..14e7eec1 --- /dev/null +++ b/node_modules/eslint/lib/shared/relative-module-resolver.js @@ -0,0 +1,28 @@ +/** + * Utility for resolving a module relative to another module + * @author Teddy Katz + */ + +"use strict"; + +const Module = require("node:module"); + +/* + * `Module.createRequire` is added in v12.2.0. It supports URL as well. + * We only support the case where the argument is a filepath, not a URL. + */ +const createRequire = Module.createRequire; + +/** + * Resolves a Node module relative to another module + * @param {string} moduleName The name of a Node module, or a path to a Node module. + * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be + * a file rather than a directory, but the file need not actually exist. + * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath` + * @throws {Error} When the module cannot be resolved. + */ +function resolve(moduleName, relativeToPath) { + return createRequire(relativeToPath).resolve(moduleName); +} + +exports.resolve = resolve; diff --git a/node_modules/eslint/lib/shared/runtime-info.js b/node_modules/eslint/lib/shared/runtime-info.js new file mode 100644 index 00000000..5e5533b2 --- /dev/null +++ b/node_modules/eslint/lib/shared/runtime-info.js @@ -0,0 +1,177 @@ +/** + * @fileoverview Utility to get information about the execution environment. + * @author Kai Cataldo + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("node:path"); +const spawn = require("cross-spawn"); +const os = require("node:os"); +const log = require("../shared/logging"); +const packageJson = require("../../package.json"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Generates and returns execution environment information. + * @returns {string} A string that contains execution environment information. + */ +function environment() { + const cache = new Map(); + + /** + * Checks if a path is a child of a directory. + * @param {string} parentPath The parent path to check. + * @param {string} childPath The path to check. + * @returns {boolean} Whether or not the given path is a child of a directory. + */ + function isChildOfDirectory(parentPath, childPath) { + return !path.relative(parentPath, childPath).startsWith(".."); + } + + /** + * Synchronously executes a shell command and formats the result. + * @param {string} cmd The command to execute. + * @param {Array} args The arguments to be executed with the command. + * @throws {Error} As may be collected by `cross-spawn.sync`. + * @returns {string} The version returned by the command. + */ + function execCommand(cmd, args) { + const key = [cmd, ...args].join(" "); + + if (cache.has(key)) { + return cache.get(key); + } + + const process = spawn.sync(cmd, args, { encoding: "utf8" }); + + if (process.error) { + throw process.error; + } + + const result = process.stdout.trim(); + + cache.set(key, result); + return result; + } + + /** + * Normalizes a version number. + * @param {string} versionStr The string to normalize. + * @returns {string} The normalized version number. + */ + function normalizeVersionStr(versionStr) { + return versionStr.startsWith("v") ? versionStr : `v${versionStr}`; + } + + /** + * Gets bin version. + * @param {string} bin The bin to check. + * @throws {Error} As may be collected by `cross-spawn.sync`. + * @returns {string} The normalized version returned by the command. + */ + function getBinVersion(bin) { + const binArgs = ["--version"]; + + try { + return normalizeVersionStr(execCommand(bin, binArgs)); + } catch (e) { + log.error( + `Error finding ${bin} version running the command \`${bin} ${binArgs.join(" ")}\``, + ); + throw e; + } + } + + /** + * Gets installed npm package version. + * @param {string} pkg The package to check. + * @param {boolean} global Whether to check globally or not. + * @throws {Error} As may be collected by `cross-spawn.sync`. + * @returns {string} The normalized version returned by the command. + */ + function getNpmPackageVersion(pkg, { global = false } = {}) { + const npmBinArgs = ["bin", "-g"]; + const npmLsArgs = ["ls", "--depth=0", "--json", pkg]; + + if (global) { + npmLsArgs.push("-g"); + } + + try { + const parsedStdout = JSON.parse(execCommand("npm", npmLsArgs)); + + /* + * Checking globally returns an empty JSON object, while local checks + * include the name and version of the local project. + */ + if ( + Object.keys(parsedStdout).length === 0 || + !(parsedStdout.dependencies && parsedStdout.dependencies.eslint) + ) { + return "Not found"; + } + + const [, processBinPath] = process.argv; + let npmBinPath; + + try { + npmBinPath = execCommand("npm", npmBinArgs); + } catch (e) { + log.error( + `Error finding npm binary path when running command \`npm ${npmBinArgs.join(" ")}\``, + ); + throw e; + } + + const isGlobal = isChildOfDirectory(npmBinPath, processBinPath); + let pkgVersion = parsedStdout.dependencies.eslint.version; + + if ((global && isGlobal) || (!global && !isGlobal)) { + pkgVersion += " (Currently used)"; + } + + return normalizeVersionStr(pkgVersion); + } catch (e) { + log.error( + `Error finding ${pkg} version running the command \`npm ${npmLsArgs.join(" ")}\``, + ); + throw e; + } + } + + return [ + "Environment Info:", + "", + `Node version: ${getBinVersion("node")}`, + `npm version: ${getBinVersion("npm")}`, + `Local ESLint version: ${getNpmPackageVersion("eslint", { global: false })}`, + `Global ESLint version: ${getNpmPackageVersion("eslint", { global: true })}`, + `Operating System: ${os.platform()} ${os.release()}`, + ].join("\n"); +} + +/** + * Returns version of currently executing ESLint. + * @returns {string} The version from the currently executing ESLint's package.json. + */ +function version() { + return `v${packageJson.version}`; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + __esModule: true, // Indicate intent for imports, remove ambiguity for Knip (see: https://github.com/eslint/eslint/pull/18005#discussion_r1484422616) + environment, + version, +}; diff --git a/node_modules/eslint/lib/shared/serialization.js b/node_modules/eslint/lib/shared/serialization.js new file mode 100644 index 00000000..afc73f9b --- /dev/null +++ b/node_modules/eslint/lib/shared/serialization.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Serialization utils. + * @author Bryan Mishkin + */ + +"use strict"; + +/** + * Check if a value is a primitive or plain object created by the Object constructor. + * @param {any} val the value to check + * @returns {boolean} true if so + * @private + */ +function isSerializablePrimitiveOrPlainObject(val) { + return ( + val === null || + typeof val === "string" || + typeof val === "boolean" || + typeof val === "number" || + (typeof val === "object" && val.constructor === Object) || + Array.isArray(val) + ); +} + +/** + * Check if a value is serializable. + * Functions or objects like RegExp cannot be serialized by JSON.stringify(). + * Inspired by: https://stackoverflow.com/questions/30579940/reliable-way-to-check-if-objects-is-serializable-in-javascript + * @param {any} val The value + * @param {Set} seenObjects Objects already seen in this path from the root object. + * @returns {boolean} `true` if the value is serializable + */ +function isSerializable(val, seenObjects = new Set()) { + if (!isSerializablePrimitiveOrPlainObject(val)) { + return false; + } + if (typeof val === "object" && val !== null) { + if (seenObjects.has(val)) { + /* + * Since this is a depth-first traversal, encountering + * the same object again means there is a circular reference. + * Objects with circular references are not serializable. + */ + return false; + } + for (const property in val) { + if (Object.hasOwn(val, property)) { + if (!isSerializablePrimitiveOrPlainObject(val[property])) { + return false; + } + if ( + typeof val[property] === "object" && + val[property] !== null + ) { + if ( + /* + * We're creating a new Set of seen objects because we want to + * ensure that `val` doesn't appear again in this path, but it can appear + * in other paths. This allows for resuing objects in the graph, as long as + * there are no cycles. + */ + !isSerializable( + val[property], + new Set([...seenObjects, val]), + ) + ) { + return false; + } + } + } + } + } + return true; +} + +module.exports = { + isSerializable, +}; diff --git a/node_modules/eslint/lib/shared/severity.js b/node_modules/eslint/lib/shared/severity.js new file mode 100644 index 00000000..382704b5 --- /dev/null +++ b/node_modules/eslint/lib/shared/severity.js @@ -0,0 +1,49 @@ +/** + * @fileoverview Helpers for severity values (e.g. normalizing different types). + * @author Bryan Mishkin + */ + +"use strict"; + +/** + * Convert severity value of different types to a string. + * @param {string|number} severity severity value + * @throws error if severity is invalid + * @returns {string} severity string + */ +function normalizeSeverityToString(severity) { + if ([2, "2", "error"].includes(severity)) { + return "error"; + } + if ([1, "1", "warn"].includes(severity)) { + return "warn"; + } + if ([0, "0", "off"].includes(severity)) { + return "off"; + } + throw new Error(`Invalid severity value: ${severity}`); +} + +/** + * Convert severity value of different types to a number. + * @param {string|number} severity severity value + * @throws error if severity is invalid + * @returns {number} severity number + */ +function normalizeSeverityToNumber(severity) { + if ([2, "2", "error"].includes(severity)) { + return 2; + } + if ([1, "1", "warn"].includes(severity)) { + return 1; + } + if ([0, "0", "off"].includes(severity)) { + return 0; + } + throw new Error(`Invalid severity value: ${severity}`); +} + +module.exports = { + normalizeSeverityToString, + normalizeSeverityToNumber, +}; diff --git a/node_modules/eslint/lib/shared/stats.js b/node_modules/eslint/lib/shared/stats.js new file mode 100644 index 00000000..791b7708 --- /dev/null +++ b/node_modules/eslint/lib/shared/stats.js @@ -0,0 +1,30 @@ +/** + * @fileoverview Provides helper functions to start/stop the time measurements + * that are provided by the ESLint 'stats' option. + * @author Mara Kiefer + */ +"use strict"; + +/** + * Start time measurement + * @returns {[number, number]} t variable for tracking time + */ +function startTime() { + return process.hrtime(); +} + +/** + * End time measurement + * @param {[number, number]} t Variable for tracking time + * @returns {number} The measured time in milliseconds + */ +function endTime(t) { + const time = process.hrtime(t); + + return time[0] * 1e3 + time[1] / 1e6; +} + +module.exports = { + startTime, + endTime, +}; diff --git a/node_modules/eslint/lib/shared/string-utils.js b/node_modules/eslint/lib/shared/string-utils.js new file mode 100644 index 00000000..954c5bff --- /dev/null +++ b/node_modules/eslint/lib/shared/string-utils.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Utilities to operate on strings. + * @author Stephen Wade + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// eslint-disable-next-line no-control-regex -- intentionally including control characters +const ASCII_REGEX = /^[\u0000-\u007f]*$/u; + +/** @type {Intl.Segmenter | undefined} */ +let segmenter; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Converts the first letter of a string to uppercase. + * @param {string} string The string to operate on + * @returns {string} The converted string + */ +function upperCaseFirst(string) { + if (string.length <= 1) { + return string.toUpperCase(); + } + return string[0].toUpperCase() + string.slice(1); +} + +/** + * Counts graphemes in a given string. + * @param {string} value A string to count graphemes. + * @returns {number} The number of graphemes in `value`. + */ +function getGraphemeCount(value) { + if (ASCII_REGEX.test(value)) { + return value.length; + } + + segmenter ??= new Intl.Segmenter("en-US"); // en-US locale should be supported everywhere + let graphemeCount = 0; + + // eslint-disable-next-line no-unused-vars -- for-of needs a variable + for (const unused of segmenter.segment(value)) { + graphemeCount++; + } + + return graphemeCount; +} + +module.exports = { + upperCaseFirst, + getGraphemeCount, +}; diff --git a/node_modules/eslint/lib/shared/text-table.js b/node_modules/eslint/lib/shared/text-table.js new file mode 100644 index 00000000..1dfd4816 --- /dev/null +++ b/node_modules/eslint/lib/shared/text-table.js @@ -0,0 +1,68 @@ +/** + * @fileoverview Optimized version of the `text-table` npm module to improve performance by replacing inefficient regex-based + * whitespace trimming with a modern built-in method. + * + * This modification addresses a performance issue reported in https://github.com/eslint/eslint/issues/18709 + * + * The `text-table` module is published under the MIT License. For the original source, refer to: + * https://www.npmjs.com/package/text-table. + */ + +/* + * + * This software is released under the MIT license: + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +"use strict"; + +module.exports = function (rows_, opts) { + const hsep = " "; + const align = opts.align; + const stringLength = opts.stringLength; + + const sizes = rows_.reduce((acc, row) => { + row.forEach((c, ix) => { + const n = stringLength(c); + + if (!acc[ix] || n > acc[ix]) { + acc[ix] = n; + } + }); + return acc; + }, []); + + return rows_ + .map(row => + row + .map((c, ix) => { + const n = sizes[ix] - stringLength(c) || 0; + const s = Array(Math.max(n + 1, 1)).join(" "); + + if (align[ix] === "r") { + return s + c; + } + + return c + s; + }) + .join(hsep) + .trimEnd(), + ) + .join("\n"); +}; diff --git a/node_modules/eslint/lib/shared/traverser.js b/node_modules/eslint/lib/shared/traverser.js new file mode 100644 index 00000000..e13b2cfa --- /dev/null +++ b/node_modules/eslint/lib/shared/traverser.js @@ -0,0 +1,202 @@ +/** + * @fileoverview Traverser to traverse AST trees. + * @author Nicholas C. Zakas + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const vk = require("eslint-visitor-keys"); +const debug = require("debug")("eslint:traverser"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Do nothing. + * @returns {void} + */ +function noop() { + // do nothing. +} + +/** + * Check whether the given value is an ASTNode or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an ASTNode. + */ +function isNode(x) { + return x !== null && typeof x === "object" && typeof x.type === "string"; +} + +/** + * Get the visitor keys of a given node. + * @param {Object} visitorKeys The map of visitor keys. + * @param {ASTNode} node The node to get their visitor keys. + * @returns {string[]} The visitor keys of the node. + */ +function getVisitorKeys(visitorKeys, node) { + let keys = visitorKeys[node.type]; + + if (!keys) { + keys = vk.getKeys(node); + debug( + 'Unknown node type "%s": Estimated visitor keys %j', + node.type, + keys, + ); + } + + return keys; +} + +/** + * The traverser class to traverse AST trees. + */ +class Traverser { + constructor() { + this._current = null; + this._parents = []; + this._skipped = false; + this._broken = false; + this._visitorKeys = null; + this._enter = null; + this._leave = null; + } + + /** + * Gives current node. + * @returns {ASTNode} The current node. + */ + current() { + return this._current; + } + + /** + * Gives a copy of the ancestor nodes. + * @returns {ASTNode[]} The ancestor nodes. + */ + parents() { + return this._parents.slice(0); + } + + /** + * Break the current traversal. + * @returns {void} + */ + break() { + this._broken = true; + } + + /** + * Skip child nodes for the current traversal. + * @returns {void} + */ + skip() { + this._skipped = true; + } + + /** + * Traverse the given AST tree. + * @param {ASTNode} node The root node to traverse. + * @param {Object} options The option object. + * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. + * @param {Function} [options.enter=noop] The callback function which is called on entering each node. + * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. + * @returns {void} + */ + traverse(node, options) { + this._current = null; + this._parents = []; + this._skipped = false; + this._broken = false; + this._visitorKeys = options.visitorKeys || vk.KEYS; + this._enter = options.enter || noop; + this._leave = options.leave || noop; + this._traverse(node, null); + } + + /** + * Traverse the given AST tree recursively. + * @param {ASTNode} node The current node. + * @param {ASTNode|null} parent The parent node. + * @returns {void} + * @private + */ + _traverse(node, parent) { + if (!isNode(node)) { + return; + } + + this._current = node; + this._skipped = false; + this._enter(node, parent); + + if (!this._skipped && !this._broken) { + const keys = getVisitorKeys(this._visitorKeys, node); + + if (keys.length >= 1) { + this._parents.push(node); + for (let i = 0; i < keys.length && !this._broken; ++i) { + const child = node[keys[i]]; + + if (Array.isArray(child)) { + for ( + let j = 0; + j < child.length && !this._broken; + ++j + ) { + this._traverse(child[j], node); + } + } else { + this._traverse(child, node); + } + } + this._parents.pop(); + } + } + + if (!this._broken) { + this._leave(node, parent); + } + + this._current = parent; + } + + /** + * Calculates the keys to use for traversal. + * @param {ASTNode} node The node to read keys from. + * @returns {string[]} An array of keys to visit on the node. + * @private + */ + static getKeys(node) { + return vk.getKeys(node); + } + + /** + * Traverse the given AST tree. + * @param {ASTNode} node The root node to traverse. + * @param {Object} options The option object. + * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. + * @param {Function} [options.enter=noop] The callback function which is called on entering each node. + * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. + * @returns {void} + */ + static traverse(node, options) { + new Traverser().traverse(node, options); + } + + /** + * The default visitor keys. + * @type {Object} + */ + static get DEFAULT_VISITOR_KEYS() { + return vk.KEYS; + } +} + +module.exports = Traverser; diff --git a/node_modules/eslint/lib/types/config-api.d.ts b/node_modules/eslint/lib/types/config-api.d.ts new file mode 100644 index 00000000..bcb8e61c --- /dev/null +++ b/node_modules/eslint/lib/types/config-api.d.ts @@ -0,0 +1,8 @@ +/** + * @fileoverview typings for "eslint/config" module + * @author Nicholas C. Zakas + */ + +import { defineConfig, globalIgnores } from "@eslint/config-helpers"; + +export { defineConfig, globalIgnores }; diff --git a/node_modules/eslint/lib/types/index.d.ts b/node_modules/eslint/lib/types/index.d.ts new file mode 100644 index 00000000..9f567dea --- /dev/null +++ b/node_modules/eslint/lib/types/index.d.ts @@ -0,0 +1,2306 @@ +/** + * @fileoverview This file contains the core types for ESLint. It was initially extracted + * from the `@types/eslint` package. + */ + +/* + * MIT License + * Copyright (c) Microsoft Corporation. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE + */ + +import * as ESTree from "estree"; +import type { + RuleVisitor, + TextSourceCode, + Language, + SourceRange, + TraversalStep, + LanguageOptions as GenericLanguageOptions, + RuleDefinition, + RuleContext as CoreRuleContext, + DeprecatedInfo, +} from "@eslint/core"; +import { JSONSchema4 } from "json-schema"; +import { LegacyESLint } from "./use-at-your-own-risk.js"; + +export namespace AST { + type TokenType = + | "Boolean" + | "Null" + | "Identifier" + | "Keyword" + | "Punctuator" + | "JSXIdentifier" + | "JSXText" + | "Numeric" + | "String" + | "RegularExpression"; + + interface Token { + type: TokenType; + value: string; + range: Range; + loc: SourceLocation; + } + + interface SourceLocation { + start: ESTree.Position; + end: ESTree.Position; + } + + type Range = [number, number]; + + interface Program extends ESTree.Program { + comments: ESTree.Comment[]; + tokens: Token[]; + loc: SourceLocation; + range: Range; + } +} + +export namespace Scope { + interface ScopeManager { + scopes: Scope[]; + globalScope: Scope | null; + + acquire(node: ESTree.Node, inner?: boolean): Scope | null; + + getDeclaredVariables(node: ESTree.Node): Variable[]; + } + + interface Scope { + type: + | "block" + | "catch" + | "class" + | "for" + | "function" + | "function-expression-name" + | "global" + | "module" + | "switch" + | "with" + | "TDZ"; + isStrict: boolean; + upper: Scope | null; + childScopes: Scope[]; + variableScope: Scope; + block: ESTree.Node; + variables: Variable[]; + set: Map; + references: Reference[]; + through: Reference[]; + functionExpressionScope: boolean; + } + + interface Variable { + name: string; + scope: Scope; + identifiers: ESTree.Identifier[]; + references: Reference[]; + defs: Definition[]; + } + + interface Reference { + identifier: ESTree.Identifier; + from: Scope; + resolved: Variable | null; + writeExpr: ESTree.Node | null; + init: boolean; + + isWrite(): boolean; + + isRead(): boolean; + + isWriteOnly(): boolean; + + isReadOnly(): boolean; + + isReadWrite(): boolean; + } + + type DefinitionType = + | { type: "CatchClause"; node: ESTree.CatchClause; parent: null } + | { + type: "ClassName"; + node: ESTree.ClassDeclaration | ESTree.ClassExpression; + parent: null; + } + | { + type: "FunctionName"; + node: ESTree.FunctionDeclaration | ESTree.FunctionExpression; + parent: null; + } + | { type: "ImplicitGlobalVariable"; node: ESTree.Program; parent: null } + | { + type: "ImportBinding"; + node: + | ESTree.ImportSpecifier + | ESTree.ImportDefaultSpecifier + | ESTree.ImportNamespaceSpecifier; + parent: ESTree.ImportDeclaration; + } + | { + type: "Parameter"; + node: + | ESTree.FunctionDeclaration + | ESTree.FunctionExpression + | ESTree.ArrowFunctionExpression; + parent: null; + } + | { type: "TDZ"; node: any; parent: null } + | { + type: "Variable"; + node: ESTree.VariableDeclarator; + parent: ESTree.VariableDeclaration; + }; + + type Definition = DefinitionType & { name: ESTree.Identifier }; +} + +// #region SourceCode + +export class SourceCode + implements + TextSourceCode<{ + LangOptions: Linter.LanguageOptions; + RootNode: AST.Program; + SyntaxElementWithLoc: AST.Token | ESTree.Node; + ConfigNode: ESTree.Comment; + }> +{ + text: string; + ast: AST.Program; + lines: string[]; + hasBOM: boolean; + parserServices: SourceCode.ParserServices; + scopeManager: Scope.ScopeManager; + visitorKeys: SourceCode.VisitorKeys; + + constructor(text: string, ast: AST.Program); + constructor(config: SourceCode.Config); + + static splitLines(text: string): string[]; + + getLoc(syntaxElement: AST.Token | ESTree.Node): ESTree.SourceLocation; + getRange(syntaxElement: AST.Token | ESTree.Node): SourceRange; + + getText( + node?: ESTree.Node, + beforeCount?: number, + afterCount?: number, + ): string; + + getLines(): string[]; + + getAllComments(): ESTree.Comment[]; + + getAncestors(node: ESTree.Node): ESTree.Node[]; + + getDeclaredVariables(node: ESTree.Node): Scope.Variable[]; + + getJSDocComment(node: ESTree.Node): ESTree.Comment | null; + + getNodeByRangeIndex(index: number): ESTree.Node | null; + + isSpaceBetweenTokens(first: AST.Token, second: AST.Token): boolean; + + getLocFromIndex(index: number): ESTree.Position; + + getIndexFromLoc(location: ESTree.Position): number; + + // Inherited methods from TokenStore + // --------------------------------- + + getTokenByRangeStart( + offset: number, + options?: { includeComments: false }, + ): AST.Token | null; + getTokenByRangeStart( + offset: number, + options: { includeComments: boolean }, + ): AST.Token | ESTree.Comment | null; + + getFirstToken: SourceCode.UnaryNodeCursorWithSkipOptions; + + getFirstTokens: SourceCode.UnaryNodeCursorWithCountOptions; + + getLastToken: SourceCode.UnaryNodeCursorWithSkipOptions; + + getLastTokens: SourceCode.UnaryNodeCursorWithCountOptions; + + getTokenBefore: SourceCode.UnaryCursorWithSkipOptions; + + getTokensBefore: SourceCode.UnaryCursorWithCountOptions; + + getTokenAfter: SourceCode.UnaryCursorWithSkipOptions; + + getTokensAfter: SourceCode.UnaryCursorWithCountOptions; + + getFirstTokenBetween: SourceCode.BinaryCursorWithSkipOptions; + + getFirstTokensBetween: SourceCode.BinaryCursorWithCountOptions; + + getLastTokenBetween: SourceCode.BinaryCursorWithSkipOptions; + + getLastTokensBetween: SourceCode.BinaryCursorWithCountOptions; + + getTokensBetween: SourceCode.BinaryCursorWithCountOptions; + + getTokens: (( + node: ESTree.Node, + beforeCount?: number, + afterCount?: number, + ) => AST.Token[]) & + SourceCode.UnaryNodeCursorWithCountOptions; + + commentsExistBetween( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + ): boolean; + + getCommentsBefore(nodeOrToken: ESTree.Node | AST.Token): ESTree.Comment[]; + + getCommentsAfter(nodeOrToken: ESTree.Node | AST.Token): ESTree.Comment[]; + + getCommentsInside(node: ESTree.Node): ESTree.Comment[]; + + getScope(node: ESTree.Node): Scope.Scope; + + isSpaceBetween( + first: ESTree.Node | AST.Token, + second: ESTree.Node | AST.Token, + ): boolean; + + isGlobalReference(node: ESTree.Identifier): boolean; + + markVariableAsUsed(name: string, refNode?: ESTree.Node): boolean; + + traverse(): Iterable; +} + +export namespace SourceCode { + interface Config { + text: string; + ast: AST.Program; + parserServices?: ParserServices | undefined; + scopeManager?: Scope.ScopeManager | undefined; + visitorKeys?: VisitorKeys | undefined; + } + + type ParserServices = any; + + interface VisitorKeys { + [nodeType: string]: string[]; + } + + interface UnaryNodeCursorWithSkipOptions { + ( + node: ESTree.Node, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + skip?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token | null; + ( + node: ESTree.Node, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + skip?: number | undefined; + }, + ): AST.Token | ESTree.Comment | null; + } + + interface UnaryNodeCursorWithCountOptions { + ( + node: ESTree.Node, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + count?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token[]; + ( + node: ESTree.Node, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + count?: number | undefined; + }, + ): Array; + } + + interface UnaryCursorWithSkipOptions { + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + skip?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token | null; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + skip?: number | undefined; + }, + ): AST.Token | ESTree.Comment | null; + } + + interface UnaryCursorWithCountOptions { + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + count?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token[]; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + count?: number | undefined; + }, + ): Array; + } + + interface BinaryCursorWithSkipOptions { + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + skip?: number | undefined; + }, + ): T | null; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + skip?: number | undefined; + }, + ): T | null; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + skip?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token | null; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + skip?: number | undefined; + }, + ): AST.Token | ESTree.Comment | null; + } + + interface BinaryCursorWithCountOptions { + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + count?: number | undefined; + }, + ): T[]; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + count?: number | undefined; + }, + ): T[]; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + count?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token[]; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + count?: number | undefined; + }, + ): Array; + } +} + +// #endregion + +export type JSSyntaxElement = { + type: string; + loc?: ESTree.SourceLocation | null | undefined; +}; + +export namespace Rule { + interface RuleModule + extends RuleDefinition<{ + LangOptions: Linter.LanguageOptions; + Code: SourceCode; + RuleOptions: any[]; + Visitor: NodeListener; + Node: JSSyntaxElement; + MessageIds: string; + ExtRuleDocs: {}; + }> { + create(context: RuleContext): NodeListener; + } + + type NodeTypes = ESTree.Node["type"]; + interface NodeListener extends RuleVisitor { + ArrayExpression?: + | ((node: ESTree.ArrayExpression & NodeParentExtension) => void) + | undefined; + "ArrayExpression:exit"?: + | ((node: ESTree.ArrayExpression & NodeParentExtension) => void) + | undefined; + ArrayPattern?: + | ((node: ESTree.ArrayPattern & NodeParentExtension) => void) + | undefined; + "ArrayPattern:exit"?: + | ((node: ESTree.ArrayPattern & NodeParentExtension) => void) + | undefined; + ArrowFunctionExpression?: + | (( + node: ESTree.ArrowFunctionExpression & NodeParentExtension, + ) => void) + | undefined; + "ArrowFunctionExpression:exit"?: + | (( + node: ESTree.ArrowFunctionExpression & NodeParentExtension, + ) => void) + | undefined; + AssignmentExpression?: + | (( + node: ESTree.AssignmentExpression & NodeParentExtension, + ) => void) + | undefined; + "AssignmentExpression:exit"?: + | (( + node: ESTree.AssignmentExpression & NodeParentExtension, + ) => void) + | undefined; + AssignmentPattern?: + | ((node: ESTree.AssignmentPattern & NodeParentExtension) => void) + | undefined; + "AssignmentPattern:exit"?: + | ((node: ESTree.AssignmentPattern & NodeParentExtension) => void) + | undefined; + AwaitExpression?: + | ((node: ESTree.AwaitExpression & NodeParentExtension) => void) + | undefined; + "AwaitExpression:exit"?: + | ((node: ESTree.AwaitExpression & NodeParentExtension) => void) + | undefined; + BinaryExpression?: + | ((node: ESTree.BinaryExpression & NodeParentExtension) => void) + | undefined; + "BinaryExpression:exit"?: + | ((node: ESTree.BinaryExpression & NodeParentExtension) => void) + | undefined; + BlockStatement?: + | ((node: ESTree.BlockStatement & NodeParentExtension) => void) + | undefined; + "BlockStatement:exit"?: + | ((node: ESTree.BlockStatement & NodeParentExtension) => void) + | undefined; + BreakStatement?: + | ((node: ESTree.BreakStatement & NodeParentExtension) => void) + | undefined; + "BreakStatement:exit"?: + | ((node: ESTree.BreakStatement & NodeParentExtension) => void) + | undefined; + CallExpression?: + | ((node: ESTree.CallExpression & NodeParentExtension) => void) + | undefined; + "CallExpression:exit"?: + | ((node: ESTree.CallExpression & NodeParentExtension) => void) + | undefined; + CatchClause?: + | ((node: ESTree.CatchClause & NodeParentExtension) => void) + | undefined; + "CatchClause:exit"?: + | ((node: ESTree.CatchClause & NodeParentExtension) => void) + | undefined; + ChainExpression?: + | ((node: ESTree.ChainExpression & NodeParentExtension) => void) + | undefined; + "ChainExpression:exit"?: + | ((node: ESTree.ChainExpression & NodeParentExtension) => void) + | undefined; + ClassBody?: + | ((node: ESTree.ClassBody & NodeParentExtension) => void) + | undefined; + "ClassBody:exit"?: + | ((node: ESTree.ClassBody & NodeParentExtension) => void) + | undefined; + ClassDeclaration?: + | ((node: ESTree.ClassDeclaration & NodeParentExtension) => void) + | undefined; + "ClassDeclaration:exit"?: + | ((node: ESTree.ClassDeclaration & NodeParentExtension) => void) + | undefined; + ClassExpression?: + | ((node: ESTree.ClassExpression & NodeParentExtension) => void) + | undefined; + "ClassExpression:exit"?: + | ((node: ESTree.ClassExpression & NodeParentExtension) => void) + | undefined; + ConditionalExpression?: + | (( + node: ESTree.ConditionalExpression & NodeParentExtension, + ) => void) + | undefined; + "ConditionalExpression:exit"?: + | (( + node: ESTree.ConditionalExpression & NodeParentExtension, + ) => void) + | undefined; + ContinueStatement?: + | ((node: ESTree.ContinueStatement & NodeParentExtension) => void) + | undefined; + "ContinueStatement:exit"?: + | ((node: ESTree.ContinueStatement & NodeParentExtension) => void) + | undefined; + DebuggerStatement?: + | ((node: ESTree.DebuggerStatement & NodeParentExtension) => void) + | undefined; + "DebuggerStatement:exit"?: + | ((node: ESTree.DebuggerStatement & NodeParentExtension) => void) + | undefined; + DoWhileStatement?: + | ((node: ESTree.DoWhileStatement & NodeParentExtension) => void) + | undefined; + "DoWhileStatement:exit"?: + | ((node: ESTree.DoWhileStatement & NodeParentExtension) => void) + | undefined; + EmptyStatement?: + | ((node: ESTree.EmptyStatement & NodeParentExtension) => void) + | undefined; + "EmptyStatement:exit"?: + | ((node: ESTree.EmptyStatement & NodeParentExtension) => void) + | undefined; + ExportAllDeclaration?: + | (( + node: ESTree.ExportAllDeclaration & NodeParentExtension, + ) => void) + | undefined; + "ExportAllDeclaration:exit"?: + | (( + node: ESTree.ExportAllDeclaration & NodeParentExtension, + ) => void) + | undefined; + ExportDefaultDeclaration?: + | (( + node: ESTree.ExportDefaultDeclaration & NodeParentExtension, + ) => void) + | undefined; + "ExportDefaultDeclaration:exit"?: + | (( + node: ESTree.ExportDefaultDeclaration & NodeParentExtension, + ) => void) + | undefined; + ExportNamedDeclaration?: + | (( + node: ESTree.ExportNamedDeclaration & NodeParentExtension, + ) => void) + | undefined; + "ExportNamedDeclaration:exit"?: + | (( + node: ESTree.ExportNamedDeclaration & NodeParentExtension, + ) => void) + | undefined; + ExportSpecifier?: + | ((node: ESTree.ExportSpecifier & NodeParentExtension) => void) + | undefined; + "ExportSpecifier:exit"?: + | ((node: ESTree.ExportSpecifier & NodeParentExtension) => void) + | undefined; + ExpressionStatement?: + | ((node: ESTree.ExpressionStatement & NodeParentExtension) => void) + | undefined; + "ExpressionStatement:exit"?: + | ((node: ESTree.ExpressionStatement & NodeParentExtension) => void) + | undefined; + ForInStatement?: + | ((node: ESTree.ForInStatement & NodeParentExtension) => void) + | undefined; + "ForInStatement:exit"?: + | ((node: ESTree.ForInStatement & NodeParentExtension) => void) + | undefined; + ForOfStatement?: + | ((node: ESTree.ForOfStatement & NodeParentExtension) => void) + | undefined; + "ForOfStatement:exit"?: + | ((node: ESTree.ForOfStatement & NodeParentExtension) => void) + | undefined; + ForStatement?: + | ((node: ESTree.ForStatement & NodeParentExtension) => void) + | undefined; + "ForStatement:exit"?: + | ((node: ESTree.ForStatement & NodeParentExtension) => void) + | undefined; + FunctionDeclaration?: + | ((node: ESTree.FunctionDeclaration & NodeParentExtension) => void) + | undefined; + "FunctionDeclaration:exit"?: + | ((node: ESTree.FunctionDeclaration & NodeParentExtension) => void) + | undefined; + FunctionExpression?: + | ((node: ESTree.FunctionExpression & NodeParentExtension) => void) + | undefined; + "FunctionExpression:exit"?: + | ((node: ESTree.FunctionExpression & NodeParentExtension) => void) + | undefined; + Identifier?: + | ((node: ESTree.Identifier & NodeParentExtension) => void) + | undefined; + "Identifier:exit"?: + | ((node: ESTree.Identifier & NodeParentExtension) => void) + | undefined; + IfStatement?: + | ((node: ESTree.IfStatement & NodeParentExtension) => void) + | undefined; + "IfStatement:exit"?: + | ((node: ESTree.IfStatement & NodeParentExtension) => void) + | undefined; + ImportDeclaration?: + | ((node: ESTree.ImportDeclaration & NodeParentExtension) => void) + | undefined; + "ImportDeclaration:exit"?: + | ((node: ESTree.ImportDeclaration & NodeParentExtension) => void) + | undefined; + ImportDefaultSpecifier?: + | (( + node: ESTree.ImportDefaultSpecifier & NodeParentExtension, + ) => void) + | undefined; + "ImportDefaultSpecifier:exit"?: + | (( + node: ESTree.ImportDefaultSpecifier & NodeParentExtension, + ) => void) + | undefined; + ImportExpression?: + | ((node: ESTree.ImportExpression & NodeParentExtension) => void) + | undefined; + "ImportExpression:exit"?: + | ((node: ESTree.ImportExpression & NodeParentExtension) => void) + | undefined; + ImportNamespaceSpecifier?: + | (( + node: ESTree.ImportNamespaceSpecifier & NodeParentExtension, + ) => void) + | undefined; + "ImportNamespaceSpecifier:exit"?: + | (( + node: ESTree.ImportNamespaceSpecifier & NodeParentExtension, + ) => void) + | undefined; + ImportSpecifier?: + | ((node: ESTree.ImportSpecifier & NodeParentExtension) => void) + | undefined; + "ImportSpecifier:exit"?: + | ((node: ESTree.ImportSpecifier & NodeParentExtension) => void) + | undefined; + LabeledStatement?: + | ((node: ESTree.LabeledStatement & NodeParentExtension) => void) + | undefined; + "LabeledStatement:exit"?: + | ((node: ESTree.LabeledStatement & NodeParentExtension) => void) + | undefined; + Literal?: + | ((node: ESTree.Literal & NodeParentExtension) => void) + | undefined; + "Literal:exit"?: + | ((node: ESTree.Literal & NodeParentExtension) => void) + | undefined; + LogicalExpression?: + | ((node: ESTree.LogicalExpression & NodeParentExtension) => void) + | undefined; + "LogicalExpression:exit"?: + | ((node: ESTree.LogicalExpression & NodeParentExtension) => void) + | undefined; + MemberExpression?: + | ((node: ESTree.MemberExpression & NodeParentExtension) => void) + | undefined; + "MemberExpression:exit"?: + | ((node: ESTree.MemberExpression & NodeParentExtension) => void) + | undefined; + MetaProperty?: + | ((node: ESTree.MetaProperty & NodeParentExtension) => void) + | undefined; + "MetaProperty:exit"?: + | ((node: ESTree.MetaProperty & NodeParentExtension) => void) + | undefined; + MethodDefinition?: + | ((node: ESTree.MethodDefinition & NodeParentExtension) => void) + | undefined; + "MethodDefinition:exit"?: + | ((node: ESTree.MethodDefinition & NodeParentExtension) => void) + | undefined; + NewExpression?: + | ((node: ESTree.NewExpression & NodeParentExtension) => void) + | undefined; + "NewExpression:exit"?: + | ((node: ESTree.NewExpression & NodeParentExtension) => void) + | undefined; + ObjectExpression?: + | ((node: ESTree.ObjectExpression & NodeParentExtension) => void) + | undefined; + "ObjectExpression:exit"?: + | ((node: ESTree.ObjectExpression & NodeParentExtension) => void) + | undefined; + ObjectPattern?: + | ((node: ESTree.ObjectPattern & NodeParentExtension) => void) + | undefined; + "ObjectPattern:exit"?: + | ((node: ESTree.ObjectPattern & NodeParentExtension) => void) + | undefined; + PrivateIdentifier?: + | ((node: ESTree.PrivateIdentifier & NodeParentExtension) => void) + | undefined; + "PrivateIdentifier:exit"?: + | ((node: ESTree.PrivateIdentifier & NodeParentExtension) => void) + | undefined; + Program?: ((node: ESTree.Program) => void) | undefined; + "Program:exit"?: ((node: ESTree.Program) => void) | undefined; + Property?: + | ((node: ESTree.Property & NodeParentExtension) => void) + | undefined; + "Property:exit"?: + | ((node: ESTree.Property & NodeParentExtension) => void) + | undefined; + PropertyDefinition?: + | ((node: ESTree.PropertyDefinition & NodeParentExtension) => void) + | undefined; + "PropertyDefinition:exit"?: + | ((node: ESTree.PropertyDefinition & NodeParentExtension) => void) + | undefined; + RestElement?: + | ((node: ESTree.RestElement & NodeParentExtension) => void) + | undefined; + "RestElement:exit"?: + | ((node: ESTree.RestElement & NodeParentExtension) => void) + | undefined; + ReturnStatement?: + | ((node: ESTree.ReturnStatement & NodeParentExtension) => void) + | undefined; + "ReturnStatement:exit"?: + | ((node: ESTree.ReturnStatement & NodeParentExtension) => void) + | undefined; + SequenceExpression?: + | ((node: ESTree.SequenceExpression & NodeParentExtension) => void) + | undefined; + "SequenceExpression:exit"?: + | ((node: ESTree.SequenceExpression & NodeParentExtension) => void) + | undefined; + SpreadElement?: + | ((node: ESTree.SpreadElement & NodeParentExtension) => void) + | undefined; + "SpreadElement:exit"?: + | ((node: ESTree.SpreadElement & NodeParentExtension) => void) + | undefined; + StaticBlock?: + | ((node: ESTree.StaticBlock & NodeParentExtension) => void) + | undefined; + "StaticBlock:exit"?: + | ((node: ESTree.StaticBlock & NodeParentExtension) => void) + | undefined; + Super?: + | ((node: ESTree.Super & NodeParentExtension) => void) + | undefined; + "Super:exit"?: + | ((node: ESTree.Super & NodeParentExtension) => void) + | undefined; + SwitchCase?: + | ((node: ESTree.SwitchCase & NodeParentExtension) => void) + | undefined; + "SwitchCase:exit"?: + | ((node: ESTree.SwitchCase & NodeParentExtension) => void) + | undefined; + SwitchStatement?: + | ((node: ESTree.SwitchStatement & NodeParentExtension) => void) + | undefined; + "SwitchStatement:exit"?: + | ((node: ESTree.SwitchStatement & NodeParentExtension) => void) + | undefined; + TaggedTemplateExpression?: + | (( + node: ESTree.TaggedTemplateExpression & NodeParentExtension, + ) => void) + | undefined; + "TaggedTemplateExpression:exit"?: + | (( + node: ESTree.TaggedTemplateExpression & NodeParentExtension, + ) => void) + | undefined; + TemplateElement?: + | ((node: ESTree.TemplateElement & NodeParentExtension) => void) + | undefined; + "TemplateElement:exit"?: + | ((node: ESTree.TemplateElement & NodeParentExtension) => void) + | undefined; + TemplateLiteral?: + | ((node: ESTree.TemplateLiteral & NodeParentExtension) => void) + | undefined; + "TemplateLiteral:exit"?: + | ((node: ESTree.TemplateLiteral & NodeParentExtension) => void) + | undefined; + ThisExpression?: + | ((node: ESTree.ThisExpression & NodeParentExtension) => void) + | undefined; + "ThisExpression:exit"?: + | ((node: ESTree.ThisExpression & NodeParentExtension) => void) + | undefined; + ThrowStatement?: + | ((node: ESTree.ThrowStatement & NodeParentExtension) => void) + | undefined; + "ThrowStatement:exit"?: + | ((node: ESTree.ThrowStatement & NodeParentExtension) => void) + | undefined; + TryStatement?: + | ((node: ESTree.TryStatement & NodeParentExtension) => void) + | undefined; + "TryStatement:exit"?: + | ((node: ESTree.TryStatement & NodeParentExtension) => void) + | undefined; + UnaryExpression?: + | ((node: ESTree.UnaryExpression & NodeParentExtension) => void) + | undefined; + "UnaryExpression:exit"?: + | ((node: ESTree.UnaryExpression & NodeParentExtension) => void) + | undefined; + UpdateExpression?: + | ((node: ESTree.UpdateExpression & NodeParentExtension) => void) + | undefined; + "UpdateExpression:exit"?: + | ((node: ESTree.UpdateExpression & NodeParentExtension) => void) + | undefined; + VariableDeclaration?: + | ((node: ESTree.VariableDeclaration & NodeParentExtension) => void) + | undefined; + "VariableDeclaration:exit"?: + | ((node: ESTree.VariableDeclaration & NodeParentExtension) => void) + | undefined; + VariableDeclarator?: + | ((node: ESTree.VariableDeclarator & NodeParentExtension) => void) + | undefined; + "VariableDeclarator:exit"?: + | ((node: ESTree.VariableDeclarator & NodeParentExtension) => void) + | undefined; + WhileStatement?: + | ((node: ESTree.WhileStatement & NodeParentExtension) => void) + | undefined; + "WhileStatement:exit"?: + | ((node: ESTree.WhileStatement & NodeParentExtension) => void) + | undefined; + WithStatement?: + | ((node: ESTree.WithStatement & NodeParentExtension) => void) + | undefined; + "WithStatement:exit"?: + | ((node: ESTree.WithStatement & NodeParentExtension) => void) + | undefined; + YieldExpression?: + | ((node: ESTree.YieldExpression & NodeParentExtension) => void) + | undefined; + "YieldExpression:exit"?: + | ((node: ESTree.YieldExpression & NodeParentExtension) => void) + | undefined; + } + + interface NodeParentExtension { + parent: Node; + } + type Node = ESTree.Node & NodeParentExtension; + + interface RuleListener extends NodeListener { + onCodePathStart?(codePath: CodePath, node: Node): void; + + onCodePathEnd?(codePath: CodePath, node: Node): void; + + onCodePathSegmentStart?(segment: CodePathSegment, node: Node): void; + + onCodePathSegmentEnd?(segment: CodePathSegment, node: Node): void; + + onCodePathSegmentLoop?( + fromSegment: CodePathSegment, + toSegment: CodePathSegment, + node: Node, + ): void; + + [key: string]: + | ((codePath: CodePath, node: Node) => void) + | ((segment: CodePathSegment, node: Node) => void) + | (( + fromSegment: CodePathSegment, + toSegment: CodePathSegment, + node: Node, + ) => void) + | ((node: Node) => void) + | NodeListener[keyof NodeListener] + | undefined; + } + + type CodePathOrigin = + | "program" + | "function" + | "class-field-initializer" + | "class-static-block"; + + interface CodePath { + id: string; + origin: CodePathOrigin; + initialSegment: CodePathSegment; + finalSegments: CodePathSegment[]; + returnedSegments: CodePathSegment[]; + thrownSegments: CodePathSegment[]; + upper: CodePath | null; + childCodePaths: CodePath[]; + } + + interface CodePathSegment { + id: string; + nextSegments: CodePathSegment[]; + prevSegments: CodePathSegment[]; + reachable: boolean; + } + + interface RuleMetaData { + /** Properties often used for documentation generation and tooling. */ + docs?: + | { + /** Provides a short description of the rule. Commonly used when generating lists of rules. */ + description?: string | undefined; + /** Historically used by some plugins that divide rules into categories in their documentation. */ + category?: string | undefined; + /** Historically used by some plugins to indicate a rule belongs in their `recommended` configuration. */ + recommended?: boolean | undefined; + /** Specifies the URL at which the full documentation can be accessed. Code editors often use this to provide a helpful link on highlighted rule violations. */ + url?: string | undefined; + } + | undefined; + /** Violation and suggestion messages. */ + messages?: { [messageId: string]: string } | undefined; + /** + * Specifies if the `--fix` option on the command line automatically fixes problems reported by the rule. + * Mandatory for fixable rules. + */ + fixable?: "code" | "whitespace" | undefined; + /** + * Specifies the [options](https://eslint.org/docs/latest/extend/custom-rules#options-schemas) + * so ESLint can prevent invalid [rule configurations](https://eslint.org/docs/latest/use/configure/rules#configuring-rules). + * Mandatory for rules with options. + */ + schema?: JSONSchema4 | JSONSchema4[] | false | undefined; + + /** Any default options to be recursively merged on top of any user-provided options. */ + defaultOptions?: unknown[]; + + /** Indicates whether the rule has been deprecated or provides additional metadata about the deprecation. Omit if not deprecated. */ + deprecated?: boolean | DeprecatedInfo | undefined; + /** + * @deprecated Use deprecated.replacedBy instead. + * The name of the rule(s) this rule was replaced by, if it was deprecated. + */ + replacedBy?: readonly string[]; + + /** + * Indicates the type of rule: + * - `"problem"` means the rule is identifying code that either will cause an error or may cause a confusing behavior. Developers should consider this a high priority to resolve. + * - `"suggestion"` means the rule is identifying something that could be done in a better way but no errors will occur if the code isn't changed. + * - `"layout"` means the rule cares primarily about whitespace, semicolons, commas, and parentheses, + * all the parts of the program that determine how the code looks rather than how it executes. + * These rules work on parts of the code that aren't specified in the AST. + */ + type?: "problem" | "suggestion" | "layout" | undefined; + /** + * Specifies whether the rule can return suggestions (defaults to `false` if omitted). + * Mandatory for rules that provide suggestions. + */ + hasSuggestions?: boolean | undefined; + } + + interface RuleContext + extends CoreRuleContext<{ + LangOptions: Linter.LanguageOptions; + Code: SourceCode; + RuleOptions: any[]; + Node: JSSyntaxElement; + MessageIds: string; + }> { + /* + * Need to extend the `RuleContext` interface to include the + * deprecated methods that have not yet been removed. + * TODO: Remove in v10.0.0. + */ + + /** @deprecated Use `sourceCode.getAncestors()` instead */ + getAncestors(): ESTree.Node[]; + + /** @deprecated Use `sourceCode.getDeclaredVariables()` instead */ + getDeclaredVariables(node: ESTree.Node): Scope.Variable[]; + + /** @deprecated Use `sourceCode.getScope()` instead */ + getScope(): Scope.Scope; + + /** @deprecated Use `sourceCode.markVariableAsUsed()` instead */ + markVariableAsUsed(name: string): boolean; + } + + type ReportFixer = ( + fixer: RuleFixer, + ) => null | Fix | IterableIterator | Fix[]; + + interface ReportDescriptorOptionsBase { + data?: { [key: string]: string }; + + fix?: null | ReportFixer; + } + + interface SuggestionReportOptions { + data?: { [key: string]: string }; + + fix: ReportFixer; + } + + type SuggestionDescriptorMessage = { desc: string } | { messageId: string }; + type SuggestionReportDescriptor = SuggestionDescriptorMessage & + SuggestionReportOptions; + + interface ReportDescriptorOptions extends ReportDescriptorOptionsBase { + suggest?: SuggestionReportDescriptor[] | null | undefined; + } + + type ReportDescriptor = ReportDescriptorMessage & + ReportDescriptorLocation & + ReportDescriptorOptions; + type ReportDescriptorMessage = { message: string } | { messageId: string }; + type ReportDescriptorLocation = + | { node: ESTree.Node } + | { loc: AST.SourceLocation | { line: number; column: number } }; + + interface RuleFixer { + insertTextAfter( + nodeOrToken: ESTree.Node | AST.Token, + text: string, + ): Fix; + + insertTextAfterRange(range: AST.Range, text: string): Fix; + + insertTextBefore( + nodeOrToken: ESTree.Node | AST.Token, + text: string, + ): Fix; + + insertTextBeforeRange(range: AST.Range, text: string): Fix; + + remove(nodeOrToken: ESTree.Node | AST.Token): Fix; + + removeRange(range: AST.Range): Fix; + + replaceText(nodeOrToken: ESTree.Node | AST.Token, text: string): Fix; + + replaceTextRange(range: AST.Range, text: string): Fix; + } + + interface Fix { + range: AST.Range; + text: string; + } +} + +export type JSRuleDefinitionTypeOptions = { + RuleOptions: unknown[]; + MessageIds: string; + ExtRuleDocs: Record; +}; + +export type JSRuleDefinition< + Options extends Partial = {}, +> = RuleDefinition< + // Language specific type options (non-configurable) + { + LangOptions: Linter.LanguageOptions; + Code: SourceCode; + Visitor: Rule.NodeListener; + Node: JSSyntaxElement; + } & Required< + // Rule specific type options (custom) + Options & + // Rule specific type options (defaults) + Omit + > +>; + +// #region Linter + +export class Linter { + static readonly version: string; + + version: string; + + constructor(options?: { + cwd?: string | undefined; + configType?: "flat" | "eslintrc"; + }); + + verify( + code: SourceCode | string, + config: Linter.LegacyConfig | Linter.Config | Linter.Config[], + filename?: string, + ): Linter.LintMessage[]; + verify( + code: SourceCode | string, + config: Linter.LegacyConfig | Linter.Config | Linter.Config[], + options: Linter.LintOptions, + ): Linter.LintMessage[]; + + verifyAndFix( + code: string, + config: Linter.LegacyConfig | Linter.Config | Linter.Config[], + filename?: string, + ): Linter.FixReport; + verifyAndFix( + code: string, + config: Linter.LegacyConfig | Linter.Config | Linter.Config[], + options: Linter.FixOptions, + ): Linter.FixReport; + + getSourceCode(): SourceCode; + + defineRule(name: string, rule: Rule.RuleModule): void; + + defineRules(rules: { [name: string]: Rule.RuleModule }): void; + + getRules(): Map; + + defineParser(name: string, parser: Linter.Parser): void; + + getTimes(): Linter.Stats["times"]; + + getFixPassCount(): Linter.Stats["fixPasses"]; +} + +export namespace Linter { + /** + * The numeric severity level for a rule. + * + * - `0` means off. + * - `1` means warn. + * - `2` means error. + * + * @see [Rule Severities](https://eslint.org/docs/latest/use/configure/rules#rule-severities) + */ + type Severity = 0 | 1 | 2; + + /** + * The human readable severity level for a rule. + * + * @see [Rule Severities](https://eslint.org/docs/latest/use/configure/rules#rule-severities) + */ + type StringSeverity = "off" | "warn" | "error"; + + /** + * The numeric or human readable severity level for a rule. + * + * @see [Rule Severities](https://eslint.org/docs/latest/use/configure/rules#rule-severities) + */ + type RuleSeverity = Severity | StringSeverity; + + /** + * An array containing the rule severity level, followed by the rule options. + * + * @see [Rules](https://eslint.org/docs/latest/use/configure/rules) + */ + type RuleSeverityAndOptions = [ + RuleSeverity, + ...Partial, + ]; + + /** + * The severity level for the rule or an array containing the rule severity level, followed by the rule options. + * + * @see [Rules](https://eslint.org/docs/latest/use/configure/rules) + */ + type RuleEntry = + | RuleSeverity + | RuleSeverityAndOptions; + + /** + * The rules config object is a key/value map of rule names and their severity and options. + */ + interface RulesRecord { + [rule: string]: RuleEntry; + } + + /** + * A configuration object that may have a `rules` block. + */ + interface HasRules { + rules?: Partial | undefined; + } + + /** + * The ECMAScript version of the code being linted. + */ + type EcmaVersion = + | 3 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 16 + | 17 + | 2015 + | 2016 + | 2017 + | 2018 + | 2019 + | 2020 + | 2021 + | 2022 + | 2023 + | 2024 + | 2025 + | 2026 + | "latest"; + + /** + * The type of JavaScript source code. + */ + type SourceType = "script" | "module" | "commonjs"; + + /** + * ESLint legacy configuration. + * + * @see [ESLint Legacy Configuration](https://eslint.org/docs/latest/use/configure/) + */ + interface BaseConfig< + Rules extends RulesRecord = RulesRecord, + OverrideRules extends RulesRecord = Rules, + > extends HasRules { + $schema?: string | undefined; + + /** + * An environment provides predefined global variables. + * + * @see [Environments](https://eslint.org/docs/latest/use/configure/language-options-deprecated#specifying-environments) + */ + env?: { [name: string]: boolean } | undefined; + + /** + * Extending configuration files. + * + * @see [Extends](https://eslint.org/docs/latest/use/configure/configuration-files-deprecated#extending-configuration-files) + */ + extends?: string | string[] | undefined; + + /** + * Specifying globals. + * + * @see [Globals](https://eslint.org/docs/latest/use/configure/language-options-deprecated#specifying-globals) + */ + globals?: Linter.Globals | undefined; + + /** + * Disable processing of inline comments. + * + * @see [Disabling Inline Comments](https://eslint.org/docs/latest/use/configure/rules-deprecated#disabling-inline-comments) + */ + noInlineConfig?: boolean | undefined; + + /** + * Overrides can be used to use a differing configuration for matching sub-directories and files. + * + * @see [How do overrides work](https://eslint.org/docs/latest/use/configure/configuration-files-deprecated#how-do-overrides-work) + */ + overrides?: Array> | undefined; + + /** + * Parser. + * + * @see [Working with Custom Parsers](https://eslint.org/docs/latest/extend/custom-parsers) + * @see [Specifying Parser](https://eslint.org/docs/latest/use/configure/parser-deprecated) + */ + parser?: string | undefined; + + /** + * Parser options. + * + * @see [Working with Custom Parsers](https://eslint.org/docs/latest/extend/custom-parsers) + * @see [Specifying Parser Options](https://eslint.org/docs/latest/use/configure/language-options-deprecated#specifying-parser-options) + */ + parserOptions?: ParserOptions | undefined; + + /** + * Which third-party plugins define additional rules, environments, configs, etc. for ESLint to use. + * + * @see [Configuring Plugins](https://eslint.org/docs/latest/use/configure/plugins-deprecated#configure-plugins) + */ + plugins?: string[] | undefined; + + /** + * Specifying processor. + * + * @see [processor](https://eslint.org/docs/latest/use/configure/plugins-deprecated#specify-a-processor) + */ + processor?: string | undefined; + + /** + * Report unused eslint-disable comments as warning. + * + * @see [Report unused eslint-disable comments](https://eslint.org/docs/latest/use/configure/rules-deprecated#report-unused-eslint-disable-comments) + */ + reportUnusedDisableDirectives?: boolean | undefined; + + /** + * Settings. + * + * @see [Settings](https://eslint.org/docs/latest/use/configure/configuration-files-deprecated#adding-shared-settings) + */ + settings?: { [name: string]: any } | undefined; + } + + /** + * The overwrites that apply more differing configuration to specific files or directories. + */ + interface ConfigOverride + extends BaseConfig { + /** + * The glob patterns for excluded files. + */ + excludedFiles?: string | string[] | undefined; + + /** + * The glob patterns for target files. + */ + files: string | string[]; + } + + /** + * ESLint legacy configuration. + * + * @see [ESLint Legacy Configuration](https://eslint.org/docs/latest/use/configure/) + */ + // https://github.com/eslint/eslint/blob/v8.57.0/conf/config-schema.js + interface LegacyConfig< + Rules extends RulesRecord = RulesRecord, + OverrideRules extends RulesRecord = Rules, + > extends BaseConfig { + /** + * Tell ESLint to ignore specific files and directories. + * + * @see [Ignore Patterns](https://eslint.org/docs/latest/use/configure/ignore-deprecated#ignorepatterns-in-config-files) + */ + ignorePatterns?: string | string[] | undefined; + + /** + * @see [Using Configuration Files](https://eslint.org/docs/latest/use/configure/configuration-files-deprecated#using-configuration-files) + */ + root?: boolean | undefined; + } + + /** + * Parser options. + * + * @see [Specifying Parser Options](https://eslint.org/docs/latest/use/configure/language-options#specifying-parser-options) + */ + interface ParserOptions { + /** + * Allow the use of reserved words as identifiers (if `ecmaVersion` is 3). + * + * @default false + */ + allowReserved?: boolean | undefined; + + /** + * Accepts any valid ECMAScript version number or `'latest'`: + * + * - A version: es3, es5, es6, es7, es8, es9, es10, es11, es12, es13, es14, ..., or + * - A year: es2015, es2016, es2017, es2018, es2019, es2020, es2021, es2022, es2023, ..., or + * - `'latest'` + * + * When it's a version or a year, the value must be a number - so do not include the `es` prefix. + * + * Specifies the version of ECMAScript syntax you want to use. This is used by the parser to determine how to perform scope analysis, and it affects the default + * + * @default 5 + */ + ecmaVersion?: EcmaVersion | undefined; + + /** + * The type of JavaScript source code. Possible values are "script" for + * traditional script files, "module" for ECMAScript modules (ESM), and + * "commonjs" for CommonJS files. + * + * @default 'script' + * + * @see https://eslint.org/docs/latest/use/configure/language-options-deprecated#specifying-parser-options + */ + sourceType?: SourceType | undefined; + + /** + * An object indicating which additional language features you'd like to use. + * + * @see https://eslint.org/docs/latest/use/configure/language-options-deprecated#specifying-parser-options + */ + ecmaFeatures?: + | { + globalReturn?: boolean | undefined; + impliedStrict?: boolean | undefined; + jsx?: boolean | undefined; + experimentalObjectRestSpread?: boolean | undefined; + [key: string]: any; + } + | undefined; + [key: string]: any; + } + + interface LintOptions { + filename?: string | undefined; + preprocess?: ((code: string) => string[]) | undefined; + postprocess?: + | ((problemLists: LintMessage[][]) => LintMessage[]) + | undefined; + filterCodeBlock?: + | ((filename: string, text: string) => boolean) + | undefined; + disableFixes?: boolean | undefined; + allowInlineConfig?: boolean | undefined; + reportUnusedDisableDirectives?: boolean | undefined; + } + + interface LintSuggestion { + /** A short description. */ + desc: string; + + /** Fix result info. */ + fix: Rule.Fix; + + /** Id referencing a message for the description. */ + messageId?: string | undefined; + } + + interface LintMessage { + /** The 1-based column number. */ + column: number; + + /** The 1-based line number. */ + line: number; + + /** The 1-based column number of the end location. */ + endColumn?: number | undefined; + + /** The 1-based line number of the end location. */ + endLine?: number | undefined; + + /** The ID of the rule which makes this message. */ + ruleId: string | null; + + /** The reported message. */ + message: string; + + /** The ID of the message in the rule's meta. */ + messageId?: string | undefined; + + /** + * Type of node. + * @deprecated `nodeType` is deprecated and will be removed in the next major version. + */ + nodeType?: string | undefined; + + /** If `true` then this is a fatal error. */ + fatal?: true | undefined; + + /** The severity of this message. */ + severity: Exclude; + + /** Information for autofix. */ + fix?: Rule.Fix | undefined; + + /** Information for suggestions. */ + suggestions?: LintSuggestion[] | undefined; + } + + interface LintSuppression { + kind: string; + justification: string; + } + + interface SuppressedLintMessage extends LintMessage { + /** The suppression info. */ + suppressions: LintSuppression[]; + } + + interface FixOptions extends LintOptions { + fix?: boolean | undefined; + } + + interface FixReport { + fixed: boolean; + output: string; + messages: LintMessage[]; + } + + // Temporarily loosen type for just flat config files (see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/68232) + type NonESTreeParser = ESLint.ObjectMetaProperties & + ( + | { + parse(text: string, options?: any): unknown; + } + | { + parseForESLint( + text: string, + options?: any, + ): Omit & { + ast: unknown; + scopeManager?: unknown; + }; + } + ); + + type ESTreeParser = ESLint.ObjectMetaProperties & + ( + | { parse(text: string, options?: any): AST.Program } + | { parseForESLint(text: string, options?: any): ESLintParseResult } + ); + + type Parser = NonESTreeParser | ESTreeParser; + + interface ESLintParseResult { + /** The AST object. */ + ast: AST.Program; + + /** The services that the parser provides. */ + services?: SourceCode.ParserServices | undefined; + + /** The scope manager of the AST. */ + scopeManager?: Scope.ScopeManager | undefined; + + /** The visitor keys of the AST. */ + visitorKeys?: SourceCode.VisitorKeys | undefined; + } + + interface ProcessorFile { + text: string; + filename: string; + } + + // https://eslint.org/docs/latest/extend/plugins#processors-in-plugins + interface Processor< + T extends string | ProcessorFile = string | ProcessorFile, + > extends ESLint.ObjectMetaProperties { + /** If `true` then it means the processor supports autofix. */ + supportsAutofix?: boolean | undefined; + + /** The function to extract code blocks. */ + preprocess?(text: string, filename: string): T[]; + + /** The function to merge messages. */ + postprocess?( + messages: LintMessage[][], + filename: string, + ): LintMessage[]; + } + + interface Config { + /** + * An string to identify the configuration object. Used in error messages and + * inspection tools. + */ + name?: string; + + /** + * An array of glob patterns indicating the files that the configuration + * object should apply to. If not specified, the configuration object applies + * to all files + */ + files?: Array; + + /** + * An array of glob patterns indicating the files that the configuration + * object should not apply to. If not specified, the configuration object + * applies to all files matched by files + */ + ignores?: string[]; + + /** + * The name of the language used for linting. This is used to determine the + * parser and other language-specific settings. + * @since 9.7.0 + */ + language?: string; + + /** + * An object containing settings related to how JavaScript is configured for + * linting. + */ + languageOptions?: LanguageOptions; + + /** + * An object containing settings related to the linting process + */ + linterOptions?: LinterOptions; + + /** + * Either an object containing preprocess() and postprocess() methods or a + * string indicating the name of a processor inside of a plugin + * (i.e., "pluginName/processorName"). + */ + processor?: string | Processor; + + /** + * An object containing a name-value mapping of plugin names to plugin objects. + * When files is specified, these plugins are only available to the matching files. + */ + plugins?: Record; + + /** + * An object containing the configured rules. When files or ignores are specified, + * these rule configurations are only available to the matching files. + */ + rules?: Partial; + + /** + * An object containing name-value pairs of information that should be + * available to all rules. + */ + settings?: Record; + } + + /** @deprecated Use `Config` instead of `FlatConfig` */ + type FlatConfig = Config; + + type GlobalConf = + | boolean + | "off" + | "readable" + | "readonly" + | "writable" + | "writeable"; + + interface Globals { + [name: string]: GlobalConf; + } + + interface LanguageOptions extends GenericLanguageOptions { + /** + * The version of ECMAScript to support. May be any year (i.e., 2022) or + * version (i.e., 5). Set to "latest" for the most recent supported version. + * @default "latest" + */ + ecmaVersion?: EcmaVersion | undefined; + + /** + * The type of JavaScript source code. Possible values are "script" for + * traditional script files, "module" for ECMAScript modules (ESM), and + * "commonjs" for CommonJS files. (default: "module" for .js and .mjs + * files; "commonjs" for .cjs files) + */ + sourceType?: SourceType | undefined; + + /** + * An object specifying additional objects that should be added to the + * global scope during linting. + */ + globals?: Globals | undefined; + + /** + * An object containing a parse() or parseForESLint() method. + * If not configured, the default ESLint parser (Espree) will be used. + */ + parser?: Parser | undefined; + + /** + * An object specifying additional options that are passed directly to the + * parser() method on the parser. The available options are parser-dependent + */ + parserOptions?: Linter.ParserOptions | undefined; + } + + interface LinterOptions { + /** + * A boolean value indicating if inline configuration is allowed. + */ + noInlineConfig?: boolean; + + /** + * A severity value indicating if and how unused disable directives should be + * tracked and reported. + */ + reportUnusedDisableDirectives?: Severity | StringSeverity | boolean; + + /** + * A severity value indicating if and how unused inline configs should be + * tracked and reported. + */ + reportUnusedInlineConfigs?: Severity | StringSeverity; + } + + /** + * Performance statistics. + */ + interface Stats { + /** + * The number of times ESLint has applied at least one fix after linting. + */ + fixPasses: number; + + /** + * The times spent on (parsing, fixing, linting) a file, where the linting refers to the timing information for each rule. + */ + times: { passes: TimePass[] }; + } + + interface TimePass { + /** + * The parse object containing all parse time information. + */ + parse: { total: number }; + + /** + * The rules object containing all lint time information for each rule. + */ + rules?: Record; + + /** + * The fix object containing all fix time information. + */ + fix: { total: number }; + + /** + * The total time that is spent on (parsing, fixing, linting) a file. + */ + total: number; + } +} + +// #endregion + +// #region ESLint + +export class ESLint { + static configType: "flat"; + + static readonly version: string; + + /** + * The default configuration that ESLint uses internally. This is provided for tooling that wants to calculate configurations using the same defaults as ESLint. + * Keep in mind that the default configuration may change from version to version, so you shouldn't rely on any particular keys or values to be present. + */ + static readonly defaultConfig: Linter.Config[]; + + static outputFixes(results: ESLint.LintResult[]): Promise; + + static getErrorResults(results: ESLint.LintResult[]): ESLint.LintResult[]; + + constructor(options?: ESLint.Options); + + lintFiles(patterns: string | string[]): Promise; + + lintText( + code: string, + options?: { + filePath?: string | undefined; + warnIgnored?: boolean | undefined; + }, + ): Promise; + + getRulesMetaForResults( + results: ESLint.LintResult[], + ): ESLint.LintResultData["rulesMeta"]; + + hasFlag(flag: string): boolean; + + calculateConfigForFile(filePath: string): Promise; + + findConfigFile(): Promise; + + isPathIgnored(filePath: string): Promise; + + loadFormatter(nameOrPath?: string): Promise; +} + +export namespace ESLint { + type ConfigData = + Omit, "$schema">; + + interface Environment { + /** The definition of global variables. */ + globals?: Linter.Globals | undefined; + + /** The parser options that will be enabled under this environment. */ + parserOptions?: Linter.ParserOptions | undefined; + } + + interface ObjectMetaProperties { + /** @deprecated Use `meta.name` instead. */ + name?: string | undefined; + + /** @deprecated Use `meta.version` instead. */ + version?: string | undefined; + + meta?: { + name?: string | undefined; + version?: string | undefined; + }; + } + + interface Plugin extends ObjectMetaProperties { + meta?: ObjectMetaProperties["meta"] & { + namespace?: string | undefined; + }; + configs?: + | Record< + string, + Linter.LegacyConfig | Linter.Config | Linter.Config[] + > + | undefined; + environments?: Record | undefined; + languages?: Record | undefined; + processors?: Record | undefined; + rules?: Record | undefined; + } + + type FixType = "directive" | "problem" | "suggestion" | "layout"; + + type CacheStrategy = "content" | "metadata"; + + interface Options { + // File enumeration + cwd?: string | undefined; + errorOnUnmatchedPattern?: boolean | undefined; + globInputPaths?: boolean | undefined; + ignore?: boolean | undefined; + ignorePatterns?: string[] | null | undefined; + passOnNoPatterns?: boolean | undefined; + warnIgnored?: boolean | undefined; + + // Linting + allowInlineConfig?: boolean | undefined; + baseConfig?: Linter.Config | Linter.Config[] | null | undefined; + overrideConfig?: Linter.Config | Linter.Config[] | null | undefined; + overrideConfigFile?: string | true | null | undefined; + plugins?: Record | null | undefined; + ruleFilter?: + | ((arg: { + ruleId: string; + severity: Exclude; + }) => boolean) + | undefined; + stats?: boolean | undefined; + + // Autofix + fix?: boolean | ((message: Linter.LintMessage) => boolean) | undefined; + fixTypes?: FixType[] | undefined; + + // Cache-related + cache?: boolean | undefined; + cacheLocation?: string | undefined; + cacheStrategy?: CacheStrategy | undefined; + + // Other Options + flags?: string[] | undefined; + } + + interface LegacyOptions { + // File enumeration + cwd?: string | undefined; + errorOnUnmatchedPattern?: boolean | undefined; + extensions?: string[] | undefined; + globInputPaths?: boolean | undefined; + ignore?: boolean | undefined; + ignorePath?: string | undefined; + + // Linting + allowInlineConfig?: boolean | undefined; + baseConfig?: Linter.LegacyConfig | undefined; + overrideConfig?: Linter.LegacyConfig | undefined; + overrideConfigFile?: string | undefined; + plugins?: Record | undefined; + reportUnusedDisableDirectives?: Linter.StringSeverity | undefined; + resolvePluginsRelativeTo?: string | undefined; + rulePaths?: string[] | undefined; + useEslintrc?: boolean | undefined; + + // Autofix + fix?: boolean | ((message: Linter.LintMessage) => boolean) | undefined; + fixTypes?: FixType[] | undefined; + + // Cache-related + cache?: boolean | undefined; + cacheLocation?: string | undefined; + cacheStrategy?: CacheStrategy | undefined; + + // Other Options + flags?: string[] | undefined; + } + + /** A linting result. */ + interface LintResult { + /** The path to the file that was linted. */ + filePath: string; + + /** All of the messages for the result. */ + messages: Linter.LintMessage[]; + + /** All of the suppressed messages for the result. */ + suppressedMessages: Linter.SuppressedLintMessage[]; + + /** Number of errors for the result. */ + errorCount: number; + + /** Number of fatal errors for the result. */ + fatalErrorCount: number; + + /** Number of warnings for the result. */ + warningCount: number; + + /** Number of fixable errors for the result. */ + fixableErrorCount: number; + + /** Number of fixable warnings for the result. */ + fixableWarningCount: number; + + /** The source code of the file that was linted, with as many fixes applied as possible. */ + output?: string | undefined; + + /** The source code of the file that was linted. */ + source?: string | undefined; + + /** The performance statistics collected with the `stats` flag. */ + stats?: Linter.Stats | undefined; + + /** The list of used deprecated rules. */ + usedDeprecatedRules: DeprecatedRuleUse[]; + } + + /** + * Information provided when the maximum warning threshold is exceeded. + */ + interface MaxWarningsExceeded { + /** + * Number of warnings to trigger nonzero exit code. + */ + maxWarnings: number; + + /** + * Number of warnings found while linting. + */ + foundWarnings: number; + } + + interface LintResultData { + cwd: string; + maxWarningsExceeded?: MaxWarningsExceeded | undefined; + rulesMeta: { + [ruleId: string]: Rule.RuleMetaData; + }; + } + + /** + * Information about deprecated rules. + */ + interface DeprecatedRuleUse { + /** + * The rule ID. + */ + ruleId: string; + + /** + * The rule IDs that replace this deprecated rule. + */ + replacedBy: string[]; + + /** + * The raw deprecated info provided by the rule. + * Unset if the rule's `meta.deprecated` property is a boolean. + */ + info?: DeprecatedInfo; + } + + /** + * Metadata about results for formatters. + */ + interface ResultsMeta { + /** + * Present if the maxWarnings threshold was exceeded. + */ + maxWarningsExceeded?: MaxWarningsExceeded | undefined; + } + + /** The type of an object resolved by {@link ESLint.loadFormatter}. */ + interface LoadedFormatter { + /** + * Used to call the underlying formatter. + * @param results An array of lint results to format. + * @param resultsMeta An object with an optional `maxWarningsExceeded` property that will be + * passed to the underlying formatter function along with other properties set by ESLint. + * This argument can be omitted if `maxWarningsExceeded` is not needed. + * @return The formatter output. + */ + format( + results: LintResult[], + resultsMeta?: ResultsMeta, + ): string | Promise; + } + + // The documented type name is `LoadedFormatter`, but `Formatter` has been historically more used. + type Formatter = LoadedFormatter; + + /** + * The expected signature of a custom formatter. + * @param results An array of lint results to format. + * @param context Additional information for the formatter. + * @return The formatter output. + */ + type FormatterFunction = ( + results: LintResult[], + context: LintResultData, + ) => string | Promise; + + // Docs reference the types by those name + type EditInfo = Rule.Fix; +} + +// #endregion + +export function loadESLint(options: { + useFlatConfig: true; +}): Promise; +export function loadESLint(options: { + useFlatConfig: false; +}): Promise; +export function loadESLint(options?: { + useFlatConfig?: boolean | undefined; +}): Promise; + +// #region RuleTester + +export class RuleTester { + static describe: ((...args: any) => any) | null; + static it: ((...args: any) => any) | null; + static itOnly: ((...args: any) => any) | null; + + constructor(config?: Linter.Config); + + run( + name: string, + rule: RuleDefinition, + tests: { + valid: Array; + invalid: RuleTester.InvalidTestCase[]; + }, + ): void; + + static only( + item: string | RuleTester.ValidTestCase | RuleTester.InvalidTestCase, + ): RuleTester.ValidTestCase | RuleTester.InvalidTestCase; +} + +export namespace RuleTester { + interface ValidTestCase { + name?: string; + code: string; + options?: any; + filename?: string | undefined; + only?: boolean; + languageOptions?: Linter.LanguageOptions | undefined; + settings?: { [name: string]: any } | undefined; + } + + interface SuggestionOutput { + messageId?: string; + desc?: string; + data?: Record | undefined; + output: string; + } + + interface InvalidTestCase extends ValidTestCase { + errors: number | Array; + output?: string | null | undefined; + } + + interface TestCaseError { + message?: string | RegExp; + messageId?: string; + /** + * @deprecated `type` is deprecated and will be removed in the next major version. + */ + type?: string | undefined; + data?: any; + line?: number | undefined; + column?: number | undefined; + endLine?: number | undefined; + endColumn?: number | undefined; + suggestions?: SuggestionOutput[] | undefined; + } +} + +// #endregion diff --git a/node_modules/eslint/lib/types/rules.d.ts b/node_modules/eslint/lib/types/rules.d.ts new file mode 100644 index 00000000..e17ff5d0 --- /dev/null +++ b/node_modules/eslint/lib/types/rules.d.ts @@ -0,0 +1,5407 @@ +/** + * @fileoverview This file contains the rule types for ESLint. It was initially extracted + * from the `@types/eslint` package. + */ + +/* + * MIT License + * Copyright (c) Microsoft Corporation. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import { Linter } from "./index"; + +//----------------------------------------------------------------------------- +// Helper types +//----------------------------------------------------------------------------- + +interface NoRestrictedImportPathCommonOptions { + name: string; + message?: string; +} + +type EitherImportNamesOrAllowImportName = + | { importNames?: string[]; allowImportNames?: never } + | { allowImportNames?: string[]; importNames?: never }; + +type ValidNoRestrictedImportPathOptions = NoRestrictedImportPathCommonOptions & + EitherImportNamesOrAllowImportName; + +interface NoRestrictedImportPatternCommonOptions { + message?: string; + caseSensitive?: boolean; +} + +// Base type for group or regex constraint, ensuring mutual exclusivity +type EitherGroupOrRegEx = + | { group: string[]; regex?: never } + | { regex: string; group?: never }; + +// Base type for import name specifiers, ensuring mutual exclusivity +type EitherNameSpecifiers = + | { + importNames: string[]; + allowImportNames?: never; + importNamePattern?: never; + allowImportNamePattern?: never; + } + | { + importNamePattern: string; + allowImportNames?: never; + importNames?: never; + allowImportNamePattern?: never; + } + | { + allowImportNames: string[]; + importNames?: never; + importNamePattern?: never; + allowImportNamePattern?: never; + } + | { + allowImportNamePattern: string; + importNames?: never; + allowImportNames?: never; + importNamePattern?: never; + }; + +// Adds oneOf and not constraints, ensuring group or regex are present and mutually exclusive sets for importNames, allowImportNames, etc., as per the schema. +type ValidNoRestrictedImportPatternOptions = + NoRestrictedImportPatternCommonOptions & + EitherGroupOrRegEx & + EitherNameSpecifiers; + +//----------------------------------------------------------------------------- +// Public types +//----------------------------------------------------------------------------- + +export interface ESLintRules extends Linter.RulesRecord { + /** + * Rule to enforce getter and setter pairs in objects and classes. + * + * @since 0.22.0 + * @see https://eslint.org/docs/latest/rules/accessor-pairs + */ + "accessor-pairs": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + setWithoutGet: boolean; + /** + * @default false + */ + getWithoutSet: boolean; + /** + * @default true + */ + enforceForClassMembers: boolean; + }>, + ] + >; + + /** + * Rule to enforce linebreaks after opening and before closing array brackets. + * + * @since 4.0.0-alpha.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`array-bracket-newline`](https://eslint.style/rules/js/array-bracket-newline) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/array-bracket-newline + */ + "array-bracket-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | "consistent" + | Partial<{ + /** + * @default true + */ + multiline: boolean; + /** + * @default null + */ + minItems: number | null; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing inside array brackets. + * + * @since 0.24.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`array-bracket-spacing`](https://eslint.style/rules/js/array-bracket-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/array-bracket-spacing + */ + "array-bracket-spacing": + | Linter.RuleEntry< + [ + "never", + Partial<{ + /** + * @default false + */ + singleValue: boolean; + /** + * @default false + */ + objectsInArrays: boolean; + /** + * @default false + */ + arraysInArrays: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default true + */ + singleValue: boolean; + /** + * @default true + */ + objectsInArrays: boolean; + /** + * @default true + */ + arraysInArrays: boolean; + }>, + ] + >; + + /** + * Rule to enforce `return` statements in callbacks of array methods. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/latest/rules/array-callback-return + */ + "array-callback-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowImplicit: boolean; + /** + * @default false + */ + checkForEach: boolean; + /** + * @default false + */ + allowVoid: boolean; + }>, + ] + >; + + /** + * Rule to enforce line breaks after each array element. + * + * @since 4.0.0-rc.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`array-element-newline`](https://eslint.style/rules/js/array-element-newline) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/array-element-newline + */ + "array-element-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | "consistent" + | Partial<{ + /** + * @default true + */ + multiline: boolean; + /** + * @default null + */ + minItems: number | null; + }>, + ] + >; + + /** + * Rule to require braces around arrow function bodies. + * + * @since 1.8.0 + * @see https://eslint.org/docs/latest/rules/arrow-body-style + */ + "arrow-body-style": + | Linter.RuleEntry< + [ + "as-needed", + Partial<{ + /** + * @default false + */ + requireReturnForObjectLiteral: boolean; + }>, + ] + > + | Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require parentheses around arrow function arguments. + * + * @since 1.0.0-rc-1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`arrow-parens`](https://eslint.style/rules/js/arrow-parens) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/arrow-parens + */ + "arrow-parens": + | Linter.RuleEntry<["always"]> + | Linter.RuleEntry< + [ + "as-needed", + Partial<{ + /** + * @default false + */ + requireForBlockBody: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before and after the arrow in arrow functions. + * + * @since 1.0.0-rc-1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`arrow-spacing`](https://eslint.style/rules/js/arrow-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/arrow-spacing + */ + "arrow-spacing": Linter.RuleEntry<[]>; + + /** + * Rule to enforce the use of variables within the scope they are defined. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/block-scoped-var + */ + "block-scoped-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow or enforce spaces inside of blocks after opening block and before closing block. + * + * @since 1.2.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`block-spacing`](https://eslint.style/rules/js/block-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/block-spacing + */ + "block-spacing": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to enforce consistent brace style for blocks. + * + * @since 0.0.7 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`brace-style`](https://eslint.style/rules/js/brace-style) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/brace-style + */ + "brace-style": Linter.RuleEntry< + [ + "1tbs" | "stroustrup" | "allman", + Partial<{ + /** + * @default false + */ + allowSingleLine: boolean; + }>, + ] + >; + + /** + * Rule to require `return` statements after callbacks. + * + * @since 1.0.0-rc-1 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`callback-return`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/callback-return.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/callback-return + */ + "callback-return": Linter.RuleEntry<[string[]]>; + + /** + * Rule to enforce camelcase naming convention. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/camelcase + */ + camelcase: Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'always' + */ + properties: "always" | "never"; + /** + * @default false + */ + ignoreDestructuring: boolean; + /** + * @since 6.7.0 + * @default false + */ + ignoreImports: boolean; + /** + * @since 7.4.0 + * @default false + */ + ignoreGlobals: boolean; + /** + * @remarks + * Also accept for regular expression patterns + */ + allow: string[]; + }>, + ] + >; + + /** + * Rule to enforce or disallow capitalization of the first letter of a comment. + * + * @since 3.11.0 + * @see https://eslint.org/docs/latest/rules/capitalized-comments + */ + "capitalized-comments": Linter.RuleEntry< + [ + "always" | "never", + Partial<{ + ignorePattern: string; + /** + * @default false + */ + ignoreInlineComments: boolean; + /** + * @default false + */ + ignoreConsecutiveComments: boolean; + }>, + ] + >; + + /** + * Rule to enforce that class methods utilize `this`. + * + * @since 3.4.0 + * @see https://eslint.org/docs/latest/rules/class-methods-use-this + */ + "class-methods-use-this": Linter.RuleEntry< + [ + Partial<{ + exceptMethods: string[]; + /** + * @default true + */ + enforceForClassFields: boolean; + /** + * @default false + */ + ignoreOverrideMethods: boolean; + ignoreClassesWithImplements: "all" | "public-fields"; + }>, + ] + >; + + /** + * Rule to require or disallow trailing commas. + * + * @since 0.16.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`comma-dangle`](https://eslint.style/rules/js/comma-dangle) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/comma-dangle + */ + "comma-dangle": Linter.RuleEntry< + [ + | "never" + | "always" + | "always-multiline" + | "only-multiline" + | Partial<{ + /** + * @default 'never' + */ + arrays: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + /** + * @default 'never' + */ + objects: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + /** + * @default 'never' + */ + imports: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + /** + * @default 'never' + */ + exports: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + /** + * @default 'never' + */ + functions: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before and after commas. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`comma-spacing`](https://eslint.style/rules/js/comma-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/comma-spacing + */ + "comma-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + before: boolean; + /** + * @default true + */ + after: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent comma style. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`comma-style`](https://eslint.style/rules/js/comma-style) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/comma-style + */ + "comma-style": Linter.RuleEntry< + [ + "last" | "first", + Partial<{ + exceptions: Record; + }>, + ] + >; + + /** + * Rule to enforce a maximum cyclomatic complexity allowed in a program. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/complexity + */ + complexity: Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 20 + */ + max: number; + /** + * @deprecated + * @default 20 + */ + maximum: number; + /** + * @default "classic" + * @since 9.12.0 + */ + variant: "classic" | "modified"; + }> + | number, + ] + >; + + /** + * Rule to enforce consistent spacing inside computed property brackets. + * + * @since 0.23.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`computed-property-spacing`](https://eslint.style/rules/js/computed-property-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/computed-property-spacing + */ + "computed-property-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require `return` statements to either always or never specify values. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/consistent-return + */ + "consistent-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + treatUndefinedAsUnspecified: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent naming when capturing the current execution context. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/consistent-this + */ + "consistent-this": Linter.RuleEntry<[...string[]]>; + + /** + * Rule to require `super()` calls in constructors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.24.0 + * @see https://eslint.org/docs/latest/rules/constructor-super + */ + "constructor-super": Linter.RuleEntry<[]>; + + /** + * Rule to enforce consistent brace style for all control statements. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/curly + */ + curly: Linter.RuleEntry< + ["all"] | ["multi" | "multi-line" | "multi-or-nest", "consistent"?] + >; + + /** + * Rule to require `default` cases in `switch` statements. + * + * @since 0.6.0 + * @see https://eslint.org/docs/latest/rules/default-case + */ + "default-case": Linter.RuleEntry< + [ + Partial<{ + /** + * @default '^no default$' + */ + commentPattern: string; + }>, + ] + >; + + /** + * Rule to enforce `default` clauses in `switch` statements to be last. + * + * @since 7.0.0-alpha.0 + * @see https://eslint.org/docs/latest/rules/default-case-last + */ + "default-case-last": Linter.RuleEntry<[]>; + + /** + * Rule to enforce default parameters to be last. + * + * @since 6.4.0 + * @see https://eslint.org/docs/latest/rules/default-param-last + */ + "default-param-last": Linter.RuleEntry<[]>; + + /** + * Rule to enforce consistent newlines before and after dots. + * + * @since 0.21.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`dot-location`](https://eslint.style/rules/js/dot-location) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/dot-location + */ + "dot-location": Linter.RuleEntry<["object" | "property"]>; + + /** + * Rule to enforce dot notation whenever possible. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/dot-notation + */ + "dot-notation": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + allowKeywords: boolean; + allowPattern: string; + }>, + ] + >; + + /** + * Rule to require or disallow newline at the end of files. + * + * @since 0.7.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`eol-last`](https://eslint.style/rules/js/eol-last) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/eol-last + */ + "eol-last": Linter.RuleEntry< + [ + "always" | "never", // | 'unix' | 'windows' + ] + >; + + /** + * Rule to require the use of `===` and `!==`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/eqeqeq + */ + eqeqeq: + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default 'always' + */ + null: "always" | "never" | "ignore"; + }>, + ] + > + | Linter.RuleEntry<["smart" | "allow-null"]>; + + /** + * Rule to enforce `for` loop update clause moving the counter in the right direction. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 4.0.0-beta.0 + * @see https://eslint.org/docs/latest/rules/for-direction + */ + "for-direction": Linter.RuleEntry<[]>; + + /** + * Rule to require or disallow spacing between function identifiers and their invocations. + * + * @since 3.3.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`function-call-spacing`](https://eslint.style/rules/js/function-call-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/func-call-spacing + */ + "func-call-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require function names to match the name of the variable or property to which they are assigned. + * + * @since 3.8.0 + * @see https://eslint.org/docs/latest/rules/func-name-matching + */ + "func-name-matching": + | Linter.RuleEntry< + [ + "always" | "never", + Partial<{ + /** + * @default false + */ + considerPropertyDescriptor: boolean; + /** + * @default false + */ + includeCommonJSModuleExports: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + considerPropertyDescriptor: boolean; + /** + * @default false + */ + includeCommonJSModuleExports: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow named `function` expressions. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/func-names + */ + "func-names": Linter.RuleEntry< + [ + "always" | "as-needed" | "never", + Partial<{ + generators: "always" | "as-needed" | "never"; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of either `function` declarations or expressions assigned to variables. + * + * @since 0.2.0 + * @see https://eslint.org/docs/latest/rules/func-style + */ + "func-style": Linter.RuleEntry< + [ + "expression" | "declaration", + Partial<{ + /** + * @default false + */ + allowArrowFunctions: boolean; + /** + * @default false + */ + allowTypeAnnotation: boolean; + overrides: { + namedExports: "declaration" | "expression" | "ignore"; + }; + }>, + ] + >; + + /** + * Rule to enforce line breaks between arguments of a function call. + * + * @since 6.2.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`function-call-argument-newline`](https://eslint.style/rules/js/function-call-argument-newline) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/function-call-argument-newline + */ + "function-call-argument-newline": Linter.RuleEntry< + [ + /** + * @default "always" + */ + "always" | "never" | "consistent", + ] + >; + + /** + * Rule to enforce consistent line breaks inside function parentheses. + * + * @since 4.6.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`function-paren-newline`](https://eslint.style/rules/js/function-paren-newline) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/function-paren-newline + */ + "function-paren-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | "multiline" + | "multiline-arguments" + | "consistent" + | Partial<{ + minItems: number; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing around `*` operators in generator functions. + * + * @since 0.17.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`generator-star-spacing`](https://eslint.style/rules/js/generator-star-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/generator-star-spacing + */ + "generator-star-spacing": Linter.RuleEntry< + [ + | Partial<{ + before: boolean; + after: boolean; + named: + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither"; + anonymous: + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither"; + method: + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither"; + }> + | "before" + | "after" + | "both" + | "neither", + ] + >; + + /** + * Rule to enforce `return` statements in getters. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 4.2.0 + * @see https://eslint.org/docs/latest/rules/getter-return + */ + "getter-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowImplicit: boolean; + }>, + ] + >; + + /** + * Rule to require `require()` calls to be placed at top-level module scope. + * + * @since 1.4.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`global-require`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/global-require.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/global-require + */ + "global-require": Linter.RuleEntry<[]>; + + /** + * Rule to require grouped accessor pairs in object literals and classes. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/grouped-accessor-pairs + */ + "grouped-accessor-pairs": Linter.RuleEntry< + ["anyOrder" | "getBeforeSet" | "setBeforeGet"] + >; + + /** + * Rule to require `for-in` loops to include an `if` statement. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/guard-for-in + */ + "guard-for-in": Linter.RuleEntry<[]>; + + /** + * Rule to require error handling in callbacks. + * + * @since 0.4.5 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`handle-callback-err`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/handle-callback-err.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/handle-callback-err + */ + "handle-callback-err": Linter.RuleEntry<[string]>; + + /** + * Rule to disallow specified identifiers. + * + * @since 2.0.0-beta.2 + * @deprecated since 7.5.0. + * The rule was renamed. + * Please, use [`id-denylist`](https://eslint.org/docs/rules/id-denylist). + * @see https://eslint.org/docs/latest/rules/id-blacklist + */ + "id-blacklist": Linter.RuleEntry<[...string[]]>; + + /** + * Rule to disallow specified identifiers. + * + * @since 7.4.0 + * @see https://eslint.org/docs/latest/rules/id-denylist + */ + "id-denylist": Linter.RuleEntry; + + /** + * Rule to enforce minimum and maximum identifier lengths. + * + * @since 1.0.0 + * @see https://eslint.org/docs/latest/rules/id-length + */ + "id-length": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 2 + */ + min: number; + /** + * @default Infinity + */ + max: number; + /** + * @default 'always' + */ + properties: "always" | "never"; + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to require identifiers to match a specified regular expression. + * + * @since 1.0.0 + * @see https://eslint.org/docs/latest/rules/id-match + */ + "id-match": Linter.RuleEntry< + [ + string, + Partial<{ + /** + * @default false + */ + properties: boolean; + /** + * @default false + */ + onlyDeclarations: boolean; + /** + * @default false + */ + ignoreDestructuring: boolean; + }>, + ] + >; + + /** + * Rule to enforce the location of arrow function bodies. + * + * @since 4.12.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`implicit-arrow-linebreak`](https://eslint.style/rules/js/implicit-arrow-linebreak) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/implicit-arrow-linebreak + */ + "implicit-arrow-linebreak": Linter.RuleEntry<["beside" | "below"]>; + + /** + * Rule to enforce consistent indentation. + * + * @since 0.14.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`indent`](https://eslint.style/rules/js/indent) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/indent + */ + indent: Linter.RuleEntry< + [ + number | "tab", + Partial<{ + /** + * @default 0 + */ + SwitchCase: number; + /** + * @default 1 + */ + VariableDeclarator: + | Partial<{ + /** + * @default 1 + */ + var: number | "first"; + /** + * @default 1 + */ + let: number | "first"; + /** + * @default 1 + */ + const: number | "first"; + }> + | number + | "first"; + /** + * @default 1 + */ + outerIIFEBody: number; + /** + * @default 1 + */ + MemberExpression: number | "off"; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionDeclaration: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionExpression: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { arguments: 1 } + */ + CallExpression: Partial<{ + /** + * @default 1 + */ + arguments: number | "first" | "off"; + }>; + /** + * @default 1 + */ + ArrayExpression: number | "first" | "off"; + /** + * @default 1 + */ + ObjectExpression: number | "first" | "off"; + /** + * @default 1 + */ + ImportDeclaration: number | "first" | "off"; + /** + * @default false + */ + flatTernaryExpressions: boolean; + ignoredNodes: string[]; + /** + * @default false + */ + ignoreComments: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent indentation. + * + * @since 4.0.0-alpha.0 + * @deprecated since 4.0.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`indent`](https://eslint.style/rules/js/indent) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/indent-legacy + */ + "indent-legacy": Linter.RuleEntry< + [ + number | "tab", + Partial<{ + /** + * @default 0 + */ + SwitchCase: number; + /** + * @default 1 + */ + VariableDeclarator: + | Partial<{ + /** + * @default 1 + */ + var: number | "first"; + /** + * @default 1 + */ + let: number | "first"; + /** + * @default 1 + */ + const: number | "first"; + }> + | number + | "first"; + /** + * @default 1 + */ + outerIIFEBody: number; + /** + * @default 1 + */ + MemberExpression: number | "off"; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionDeclaration: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionExpression: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { arguments: 1 } + */ + CallExpression: Partial<{ + /** + * @default 1 + */ + arguments: number | "first" | "off"; + }>; + /** + * @default 1 + */ + ArrayExpression: number | "first" | "off"; + /** + * @default 1 + */ + ObjectExpression: number | "first" | "off"; + /** + * @default 1 + */ + ImportDeclaration: number | "first" | "off"; + /** + * @default false + */ + flatTernaryExpressions: boolean; + ignoredNodes: string[]; + /** + * @default false + */ + ignoreComments: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow initialization in variable declarations. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/init-declarations + */ + "init-declarations": + | Linter.RuleEntry<["always"]> + | Linter.RuleEntry< + [ + "never", + Partial<{ + ignoreForLoopInit: boolean; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of either double or single quotes in JSX attributes. + * + * @since 1.4.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`jsx-quotes`](https://eslint.style/rules/js/jsx-quotes) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/jsx-quotes + */ + "jsx-quotes": Linter.RuleEntry<["prefer-double" | "prefer-single"]>; + + /** + * Rule to enforce consistent spacing between keys and values in object literal properties. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`key-spacing`](https://eslint.style/rules/js/key-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/key-spacing + */ + "key-spacing": Linter.RuleEntry< + [ + | Partial< + | { + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + align: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'colon' + */ + on: "value" | "colon"; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | "value" + | "colon"; + } + | { + singleLine?: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | undefined; + multiLine?: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + align: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'colon' + */ + on: "value" | "colon"; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | "value" + | "colon"; + }> + | undefined; + } + > + | { + align: Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'colon' + */ + on: "value" | "colon"; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }>; + singleLine?: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | undefined; + multiLine?: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | undefined; + }, + ] + >; + + /** + * Rule to enforce consistent spacing before and after keywords. + * + * @since 2.0.0-beta.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`keyword-spacing`](https://eslint.style/rules/js/keyword-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/keyword-spacing + */ + "keyword-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + before: boolean; + /** + * @default true + */ + after: boolean; + overrides: Record< + string, + Partial<{ + before: boolean; + after: boolean; + }> + >; + }>, + ] + >; + + /** + * Rule to enforce position of line comments. + * + * @since 3.5.0 + * @deprecated since 9.3.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`line-comment-position`](https://eslint.style/rules/js/line-comment-position) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/line-comment-position + */ + "line-comment-position": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'above' + */ + position: "above" | "beside"; + ignorePattern: string; + /** + * @default true + */ + applyDefaultIgnorePatterns: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent linebreak style. + * + * @since 0.21.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`linebreak-style`](https://eslint.style/rules/js/linebreak-style) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/linebreak-style + */ + "linebreak-style": Linter.RuleEntry<["unix" | "windows"]>; + + /** + * Rule to require empty lines around comments. + * + * @since 0.22.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`lines-around-comment`](https://eslint.style/rules/js/lines-around-comment) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/lines-around-comment + */ + "lines-around-comment": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + beforeBlockComment: boolean; + /** + * @default false + */ + afterBlockComment: boolean; + /** + * @default false + */ + beforeLineComment: boolean; + /** + * @default false + */ + afterLineComment: boolean; + /** + * @default false + */ + allowBlockStart: boolean; + /** + * @default false + */ + allowBlockEnd: boolean; + /** + * @default false + */ + allowObjectStart: boolean; + /** + * @default false + */ + allowObjectEnd: boolean; + /** + * @default false + */ + allowArrayStart: boolean; + /** + * @default false + */ + allowArrayEnd: boolean; + /** + * @default false + */ + allowClassStart: boolean; + /** + * @default false + */ + allowClassEnd: boolean; + ignorePattern: string; + /** + * @default true + */ + applyDefaultIgnorePatterns: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow newlines around directives. + * + * @since 3.5.0 + * @deprecated since 4.0.0. + * The rule was replaced with a more general rule. + * Please, use [`padding-line-between-statements`](https://eslint.style/rules/js/padding-line-between-statements) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/lines-around-directive + */ + "lines-around-directive": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require or disallow an empty line between class members. + * + * @since 4.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`lines-between-class-members`](https://eslint.style/rules/js/lines-between-class-members) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/lines-between-class-members + */ + "lines-between-class-members": Linter.RuleEntry< + [ + ( + | "always" + | "never" + | { + enforce: Array<{ + blankLine: "always" | "never"; + prev: "method" | "field" | "*"; + next: "method" | "field" | "*"; + }>; + } + ), + Partial<{ + /** + * @default false + */ + exceptAfterSingleLine: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow logical assignment operator shorthand. + * + * @since 8.24.0 + * @see https://eslint.org/docs/latest/rules/logical-assignment-operators + */ + "logical-assignment-operators": + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default false + */ + enforceForIfStatements: boolean; + }>, + ] + > + | Linter.RuleEntry<["never"]>; + + /** + * Rule to enforce a maximum number of classes per file. + * + * @since 5.0.0-alpha.3 + * @see https://eslint.org/docs/latest/rules/max-classes-per-file + */ + "max-classes-per-file": Linter.RuleEntry<[number]>; + + /** + * Rule to enforce a maximum depth that blocks can be nested. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/max-depth + */ + "max-depth": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 4 + */ + max: number; + }>, + ] + >; + + /** + * Rule to enforce a maximum line length. + * + * @since 0.0.9 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`max-len`](https://eslint.style/rules/js/max-len) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/max-len + */ + "max-len": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 80 + */ + code: number; + /** + * @default 4 + */ + tabWidth: number; + comments: number; + ignorePattern: string; + /** + * @default false + */ + ignoreComments: boolean; + /** + * @default false + */ + ignoreTrailingComments: boolean; + /** + * @default false + */ + ignoreUrls: boolean; + /** + * @default false + */ + ignoreStrings: boolean; + /** + * @default false + */ + ignoreTemplateLiterals: boolean; + /** + * @default false + */ + ignoreRegExpLiterals: boolean; + }>, + ] + >; + + /** + * Rule to enforce a maximum number of lines per file. + * + * @since 2.12.0 + * @see https://eslint.org/docs/latest/rules/max-lines + */ + "max-lines": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 300 + */ + max: number; + /** + * @default false + */ + skipBlankLines: boolean; + /** + * @default false + */ + skipComments: boolean; + }> + | number, + ] + >; + + /** + * Rule to enforce a maximum number of lines of code in a function. + * + * @since 5.0.0 + * @see https://eslint.org/docs/latest/rules/max-lines-per-function + */ + "max-lines-per-function": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 50 + */ + max: number; + /** + * @default false + */ + skipBlankLines: boolean; + /** + * @default false + */ + skipComments: boolean; + /** + * @default false + */ + IIFEs: boolean; + }>, + ] + >; + + /** + * Rule to enforce a maximum depth that callbacks can be nested. + * + * @since 0.2.0 + * @see https://eslint.org/docs/latest/rules/max-nested-callbacks + */ + "max-nested-callbacks": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 10 + */ + max: number; + }> + | number, + ] + >; + + /** + * Rule to enforce a maximum number of parameters in function definitions. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/max-params + */ + "max-params": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 3 + */ + max: number; + /** + * @default false + */ + countVoidThis: boolean; + }> + | number, + ] + >; + + /** + * Rule to enforce a maximum number of statements allowed in function blocks. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/max-statements + */ + "max-statements": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 10 + */ + max: number; + /** + * @default false + */ + ignoreTopLevelFunctions: boolean; + }> + | number, + ] + >; + + /** + * Rule to enforce a maximum number of statements allowed per line. + * + * @since 2.5.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`max-statements-per-line`](https://eslint.style/rules/js/max-statements-per-line) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/max-statements-per-line + */ + "max-statements-per-line": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 1 + */ + max: number; + }> + | number, + ] + >; + + /** + * Rule to enforce a particular style for multiline comments. + * + * @since 4.10.0 + * @deprecated since 9.3.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`multiline-comment-style`](https://eslint.style/rules/js/multiline-comment-style) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/multiline-comment-style + */ + "multiline-comment-style": Linter.RuleEntry< + ["starred-block" | "bare-block" | "separate-lines"] + >; + + /** + * Rule to enforce newlines between operands of ternary expressions. + * + * @since 3.1.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`multiline-ternary`](https://eslint.style/rules/js/multiline-ternary) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/multiline-ternary + */ + "multiline-ternary": Linter.RuleEntry< + ["always" | "always-multiline" | "never"] + >; + + /** + * Rule to require constructor names to begin with a capital letter. + * + * @since 0.0.3-0 + * @see https://eslint.org/docs/latest/rules/new-cap + */ + "new-cap": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + newIsCap: boolean; + /** + * @default true + */ + capIsNew: boolean; + newIsCapExceptions: string[]; + newIsCapExceptionPattern: string; + capIsNewExceptions: string[]; + capIsNewExceptionPattern: string; + /** + * @default true + */ + properties: boolean; + }>, + ] + >; + + /** + * Rule to enforce or disallow parentheses when invoking a constructor with no arguments. + * + * @since 0.0.6 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`new-parens`](https://eslint.style/rules/js/new-parens) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/new-parens + */ + "new-parens": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require or disallow an empty line after variable declarations. + * + * @since 0.18.0 + * @deprecated since 4.0.0. + * The rule was replaced with a more general rule. + * Please, use [`padding-line-between-statements`](https://eslint.style/rules/js/padding-line-between-statements) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/newline-after-var + */ + "newline-after-var": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require an empty line before `return` statements. + * + * @since 2.3.0 + * @deprecated since 4.0.0. + * The rule was replaced with a more general rule. + * Please, use [`padding-line-between-statements`](https://eslint.style/rules/js/padding-line-between-statements) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/newline-before-return + */ + "newline-before-return": Linter.RuleEntry<[]>; + + /** + * Rule to require a newline after each call in a method chain. + * + * @since 2.0.0-rc.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`newline-per-chained-call`](https://eslint.style/rules/js/newline-per-chained-call) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/newline-per-chained-call + */ + "newline-per-chained-call": Linter.RuleEntry< + [ + { + /** + * @default 2 + */ + ignoreChainWithDepth: number; + }, + ] + >; + + /** + * Rule to disallow the use of `alert`, `confirm`, and `prompt`. + * + * @since 0.0.5 + * @see https://eslint.org/docs/latest/rules/no-alert + */ + "no-alert": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `Array` constructors. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-array-constructor + */ + "no-array-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow using an async function as a Promise executor. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.3.0 + * @see https://eslint.org/docs/latest/rules/no-async-promise-executor + */ + "no-async-promise-executor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `await` inside of loops. + * + * @since 3.12.0 + * @see https://eslint.org/docs/latest/rules/no-await-in-loop + */ + "no-await-in-loop": Linter.RuleEntry<[]>; + + /** + * Rule to disallow bitwise operators. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-bitwise + */ + "no-bitwise": Linter.RuleEntry< + [ + Partial<{ + allow: string[]; + /** + * @default false + */ + int32Hint: boolean; + }>, + ] + >; + + /** + * Rule to disallow use of the `Buffer()` constructor. + * + * @since 4.0.0-alpha.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-deprecated-api`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-deprecated-api.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-buffer-constructor + */ + "no-buffer-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `arguments.caller` or `arguments.callee`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-caller + */ + "no-caller": Linter.RuleEntry<[]>; + + /** + * Rule to disallow lexical declarations in case clauses. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.9.0 + * @see https://eslint.org/docs/latest/rules/no-case-declarations + */ + "no-case-declarations": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `catch` clause parameters from shadowing variables in the outer scope. + * + * @since 0.0.9 + * @deprecated since 5.1.0. + * This rule was renamed. + * Please, use [`no-shadow`](https://eslint.org/docs/rules/no-shadow). + * @see https://eslint.org/docs/latest/rules/no-catch-shadow + */ + "no-catch-shadow": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassigning class members. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/no-class-assign + */ + "no-class-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow comparing against `-0`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 3.17.0 + * @see https://eslint.org/docs/latest/rules/no-compare-neg-zero + */ + "no-compare-neg-zero": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignment operators in conditional expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-cond-assign + */ + "no-cond-assign": Linter.RuleEntry<["except-parens" | "always"]>; + + /** + * Rule to disallow arrow functions where they could be confused with comparisons. + * + * @since 2.0.0-alpha-2 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-confusing-arrow`](https://eslint.style/rules/js/no-confusing-arrow) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-confusing-arrow + */ + "no-confusing-arrow": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + allowParens: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of `console`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-console + */ + "no-console": Linter.RuleEntry< + [ + Partial<{ + allow: Array; + }>, + ] + >; + + /** + * Rule to disallow reassigning `const` variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/no-const-assign + */ + "no-const-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow expressions where the operation doesn't affect the value. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 8.14.0 + * @see https://eslint.org/docs/latest/rules/no-constant-binary-expression + */ + "no-constant-binary-expression": Linter.RuleEntry<[]>; + + /** + * Rule to disallow constant expressions in conditions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.1 + * @see https://eslint.org/docs/latest/rules/no-constant-condition + */ + "no-constant-condition": Linter.RuleEntry< + [ + { + /** + * @default true + */ + checkLoops: boolean; + }, + ] + >; + + /** + * Rule to disallow returning value from constructor. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/no-constructor-return + */ + "no-constructor-return": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `continue` statements. + * + * @since 0.19.0 + * @see https://eslint.org/docs/latest/rules/no-continue + */ + "no-continue": Linter.RuleEntry<[]>; + + /** + * Rule to disallow control characters in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/no-control-regex + */ + "no-control-regex": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `debugger`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-debugger + */ + "no-debugger": Linter.RuleEntry<[]>; + + /** + * Rule to disallow deleting variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-delete-var + */ + "no-delete-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow equal signs explicitly at the beginning of regular expressions. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/no-div-regex + */ + "no-div-regex": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate arguments in `function` definitions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.16.0 + * @see https://eslint.org/docs/latest/rules/no-dupe-args + */ + "no-dupe-args": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate class members. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.2.0 + * @see https://eslint.org/docs/latest/rules/no-dupe-class-members + */ + "no-dupe-class-members": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate conditions in if-else-if chains. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/no-dupe-else-if + */ + "no-dupe-else-if": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate keys in object literals. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-dupe-keys + */ + "no-dupe-keys": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate case labels. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.17.0 + * @see https://eslint.org/docs/latest/rules/no-duplicate-case + */ + "no-duplicate-case": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate module imports. + * + * @since 2.5.0 + * @see https://eslint.org/docs/latest/rules/no-duplicate-imports + */ + "no-duplicate-imports": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + includeExports: boolean; + }>, + ] + >; + + /** + * Rule to disallow `else` blocks after `return` statements in `if` statements. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-else-return + */ + "no-else-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + allowElseIf: boolean; + }>, + ] + >; + + /** + * Rule to disallow empty block statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-empty + */ + "no-empty": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowEmptyCatch: boolean; + }>, + ] + >; + + /** + * Rule to disallow empty character classes in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.22.0 + * @see https://eslint.org/docs/latest/rules/no-empty-character-class + */ + "no-empty-character-class": Linter.RuleEntry<[]>; + + /** + * Rule to disallow empty functions. + * + * @since 2.0.0 + * @see https://eslint.org/docs/latest/rules/no-empty-function + */ + "no-empty-function": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + allow: Array< + | "functions" + | "arrowFunctions" + | "generatorFunctions" + | "methods" + | "generatorMethods" + | "getters" + | "setters" + | "constructors" + | "asyncFunctions" + | "asyncMethods" + | "privateConstructors" + | "protectedConstructors" + | "decoratedFunctions" + | "overrideMethods" + >; + }>, + ] + >; + + /** + * Rule to disallow empty destructuring patterns. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.7.0 + * @see https://eslint.org/docs/latest/rules/no-empty-pattern + */ + "no-empty-pattern": Linter.RuleEntry<[]>; + + /** + * Rule to disallow empty static blocks. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 8.27.0 + * @see https://eslint.org/docs/latest/rules/no-empty-static-block + */ + "no-empty-static-block": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `null` comparisons without type-checking operators. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-eq-null + */ + "no-eq-null": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `eval()`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-eval + */ + "no-eval": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowIndirect: boolean; + }>, + ] + >; + + /** + * Rule to disallow reassigning exceptions in `catch` clauses. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-ex-assign + */ + "no-ex-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow extending native types. + * + * @since 0.1.4 + * @see https://eslint.org/docs/latest/rules/no-extend-native + */ + "no-extend-native": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow unnecessary calls to `.bind()`. + * + * @since 0.8.0 + * @see https://eslint.org/docs/latest/rules/no-extra-bind + */ + "no-extra-bind": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary boolean casts. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-extra-boolean-cast + */ + "no-extra-boolean-cast": Linter.RuleEntry< + [ + | Partial<{ + /** + * @since 9.3.0 + * @default false + */ + enforceForInnerExpressions: boolean; + /** + * @deprecated + */ + enforceForLogicalOperands: never; + }> + | Partial<{ + /** + * @deprecated + * @since 7.0.0-alpha.2 + * @default false + */ + enforceForLogicalOperands: boolean; + enforceForInnerExpressions: never; + }>, + ] + >; + + /** + * Rule to disallow unnecessary labels. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/latest/rules/no-extra-label + */ + "no-extra-label": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary parentheses. + * + * @since 0.1.4 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-extra-parens`](https://eslint.style/rules/js/no-extra-parens) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-extra-parens + */ + "no-extra-parens": + | Linter.RuleEntry< + [ + "all", + Partial<{ + /** + * @default true, + */ + conditionalAssign: boolean; + /** + * @default true + */ + returnAssign: boolean; + /** + * @default true + */ + nestedBinaryExpressions: boolean; + /** + * @default 'none' + */ + ignoreJSX: + | "none" + | "all" + | "multi-line" + | "single-line"; + /** + * @default true + */ + enforceForArrowConditionals: boolean; + }>, + ] + > + | Linter.RuleEntry<["functions"]>; + + /** + * Rule to disallow unnecessary semicolons. + * + * @since 0.0.9 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-extra-semi`](https://eslint.style/rules/js/no-extra-semi) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-extra-semi + */ + "no-extra-semi": Linter.RuleEntry<[]>; + + /** + * Rule to disallow fallthrough of `case` statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/no-fallthrough + */ + "no-fallthrough": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'falls?\s?through' + */ + commentPattern: string; + /** + * @default false + */ + allowEmptyCase: boolean; + /** + * @default false + */ + reportUnusedFallthroughComment: boolean; + }>, + ] + >; + + /** + * Rule to disallow leading or trailing decimal points in numeric literals. + * + * @since 0.0.6 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-floating-decimal`](https://eslint.style/rules/js/no-floating-decimal) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-floating-decimal + */ + "no-floating-decimal": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassigning `function` declarations. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-func-assign + */ + "no-func-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignments to native objects or read-only global variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 3.3.0 + * @see https://eslint.org/docs/latest/rules/no-global-assign + */ + "no-global-assign": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow shorthand type conversions. + * + * @since 1.0.0-rc-2 + * @see https://eslint.org/docs/latest/rules/no-implicit-coercion + */ + "no-implicit-coercion": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + boolean: boolean; + /** + * @default true + */ + number: boolean; + /** + * @default true + */ + string: boolean; + /** + * @default false + */ + disallowTemplateShorthand: boolean; + /** + * @default [] + */ + allow: Array<"~" | "!!" | "+" | "- -" | "-" | "*">; + }>, + ] + >; + + /** + * Rule to disallow declarations in the global scope. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/latest/rules/no-implicit-globals + */ + "no-implicit-globals": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `eval()`-like methods. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/no-implied-eval + */ + "no-implied-eval": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assigning to imported bindings. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 6.4.0 + * @see https://eslint.org/docs/latest/rules/no-import-assign + */ + "no-import-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow inline comments after code. + * + * @since 0.10.0 + * @see https://eslint.org/docs/latest/rules/no-inline-comments + */ + "no-inline-comments": Linter.RuleEntry<[]>; + + /** + * Rule to disallow variable or `function` declarations in nested blocks. + * + * @since 0.6.0 + * @see https://eslint.org/docs/latest/rules/no-inner-declarations + */ + "no-inner-declarations": Linter.RuleEntry<["functions" | "both"]>; + + /** + * Rule to disallow invalid regular expression strings in `RegExp` constructors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.1.4 + * @see https://eslint.org/docs/latest/rules/no-invalid-regexp + */ + "no-invalid-regexp": Linter.RuleEntry< + [ + Partial<{ + allowConstructorFlags: string[]; + }>, + ] + >; + + /** + * Rule to disallow use of `this` in contexts where the value of `this` is `undefined`. + * + * @since 1.0.0-rc-2 + * @see https://eslint.org/docs/latest/rules/no-invalid-this + */ + "no-invalid-this": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + capIsConstructor: boolean; + }>, + ] + >; + + /** + * Rule to disallow irregular whitespace. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.9.0 + * @see https://eslint.org/docs/latest/rules/no-irregular-whitespace + */ + "no-irregular-whitespace": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + skipStrings: boolean; + /** + * @default false + */ + skipComments: boolean; + /** + * @default false + */ + skipRegExps: boolean; + /** + * @default false + */ + skipTemplates: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of the `__iterator__` property. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-iterator + */ + "no-iterator": Linter.RuleEntry<[]>; + + /** + * Rule to disallow labels that share a name with a variable. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-label-var + */ + "no-label-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow labeled statements. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-labels + */ + "no-labels": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowLoop: boolean; + /** + * @default false + */ + allowSwitch: boolean; + }>, + ] + >; + + /** + * Rule to disallow unnecessary nested blocks. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-lone-blocks + */ + "no-lone-blocks": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `if` statements as the only statement in `else` blocks. + * + * @since 0.6.0 + * @see https://eslint.org/docs/latest/rules/no-lonely-if + */ + "no-lonely-if": Linter.RuleEntry<[]>; + + /** + * Rule to disallow function declarations that contain unsafe references inside loop statements. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-loop-func + */ + "no-loop-func": Linter.RuleEntry<[]>; + + /** + * Rule to disallow literal numbers that lose precision. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 7.1.0 + * @see https://eslint.org/docs/latest/rules/no-loss-of-precision + */ + "no-loss-of-precision": Linter.RuleEntry<[]>; + + /** + * Rule to disallow magic numbers. + * + * @since 1.7.0 + * @see https://eslint.org/docs/latest/rules/no-magic-numbers + */ + "no-magic-numbers": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + ignore: number[]; + /** + * @default false + */ + ignoreArrayIndexes: boolean; + /** + * @default false + */ + enforceConst: boolean; + /** + * @default false + */ + detectObjects: boolean; + /** + * @default false + */ + ignoreEnums: boolean; + /** + * @default false + */ + ignoreNumericLiteralTypes: boolean; + /** + * @default false + */ + ignoreReadonlyClassProperties: boolean; + /** + * @default false + */ + ignoreTypeIndexes: boolean; + }>, + ] + >; + + /** + * Rule to disallow characters which are made with multiple code points in character class syntax. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.3.0 + * @see https://eslint.org/docs/latest/rules/no-misleading-character-class + */ + "no-misleading-character-class": Linter.RuleEntry< + [ + Partial<{ + /** + * @since 9.3.0 + * @default false + */ + allowEscape: boolean; + }>, + ] + >; + + /** + * Rule to disallow mixed binary operators. + * + * @since 2.12.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-mixed-operators`](https://eslint.style/rules/js/no-mixed-operators) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-mixed-operators + */ + "no-mixed-operators": Linter.RuleEntry< + [ + Partial<{ + /** + * @default + * [ + * ["+", "-", "*", "/", "%", "**"], + * ["&", "|", "^", "~", "<<", ">>", ">>>"], + * ["==", "!=", "===", "!==", ">", ">=", "<", "<="], + * ["&&", "||"], + * ["in", "instanceof"] + * ] + */ + groups: string[][]; + /** + * @default true + */ + allowSamePrecedence: boolean; + }>, + ] + >; + + /** + * Rule to disallow `require` calls to be mixed with regular variable declarations. + * + * @since 0.0.9 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-mixed-requires`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-mixed-requires.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-mixed-requires + */ + "no-mixed-requires": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + grouping: boolean; + /** + * @default false + */ + allowCall: boolean; + }>, + ] + >; + + /** + * Rule to disallow mixed spaces and tabs for indentation. + * + * @since 0.7.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-mixed-spaces-and-tabs`](https://eslint.style/rules/js/no-mixed-spaces-and-tabs) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-mixed-spaces-and-tabs + */ + "no-mixed-spaces-and-tabs": Linter.RuleEntry<["smart-tabs"]>; + + /** + * Rule to disallow use of chained assignment expressions. + * + * @since 3.14.0 + * @see https://eslint.org/docs/latest/rules/no-multi-assign + */ + "no-multi-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow multiple spaces. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-multi-spaces`](https://eslint.style/rules/js/no-multi-spaces) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-multi-spaces + */ + "no-multi-spaces": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreEOLComments: boolean; + /** + * @default { Property: true } + */ + exceptions: Record; + }>, + ] + >; + + /** + * Rule to disallow multiline strings. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-multi-str + */ + "no-multi-str": Linter.RuleEntry<[]>; + + /** + * Rule to disallow multiple empty lines. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-multiple-empty-lines`](https://eslint.style/rules/js/no-multiple-empty-lines) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-multiple-empty-lines + */ + "no-multiple-empty-lines": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 2 + */ + max: number; + maxEOF: number; + maxBOF: number; + }> + | number, + ] + >; + + /** + * Rule to disallow assignments to native objects or read-only global variables. + * + * @since 0.0.9 + * @deprecated since 3.3.0. + * Renamed rule. + * Please, use [`no-global-assign`](https://eslint.org/docs/rules/no-global-assign). + * @see https://eslint.org/docs/latest/rules/no-native-reassign + */ + "no-native-reassign": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow negated conditions. + * + * @since 1.6.0 + * @see https://eslint.org/docs/latest/rules/no-negated-condition + */ + "no-negated-condition": Linter.RuleEntry<[]>; + + /** + * Rule to disallow negating the left operand in `in` expressions. + * + * @since 0.1.2 + * @deprecated since 3.3.0. + * Renamed rule. + * Please, use [`no-unsafe-negation`](https://eslint.org/docs/rules/no-unsafe-negation). + * @see https://eslint.org/docs/latest/rules/no-negated-in-lhs + */ + "no-negated-in-lhs": Linter.RuleEntry<[]>; + + /** + * Rule to disallow nested ternary expressions. + * + * @since 0.2.0 + * @see https://eslint.org/docs/latest/rules/no-nested-ternary + */ + "no-nested-ternary": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators outside of assignments or comparisons. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/no-new + */ + "no-new": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with the `Function` object. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/no-new-func + */ + "no-new-func": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with global non-constructor functions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 8.27.0 + * @see https://eslint.org/docs/latest/rules/no-new-native-nonconstructor + */ + "no-new-native-nonconstructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `Object` constructors. + * + * @since 0.0.9 + * @deprecated since 8.50.0. + * The new rule flags more situations where object literal syntax can be used, and it does not report a problem when the `Object` constructor is invoked with an argument. + * Please, use [`no-object-constructor`](https://eslint.org/docs/rules/no-object-constructor). + * @see https://eslint.org/docs/latest/rules/no-new-object + */ + "no-new-object": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with calls to `require`. + * + * @since 0.6.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-new-require`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-new-require.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-new-require + */ + "no-new-require": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with the `Symbol` object. + * + * @since 2.0.0-beta.1 + * @deprecated since 9.0.0. + * The rule was replaced with a more general rule. + * Please, use [`no-new-native-nonconstructor`](https://eslint.org/docs/latest/rules/no-new-native-nonconstructor). + * @see https://eslint.org/docs/latest/rules/no-new-symbol + */ + "no-new-symbol": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with the `String`, `Number`, and `Boolean` objects. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-new-wrappers + */ + "no-new-wrappers": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `\8` and `\9` escape sequences in string literals. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 7.14.0 + * @see https://eslint.org/docs/latest/rules/no-nonoctal-decimal-escape + */ + "no-nonoctal-decimal-escape": Linter.RuleEntry<[]>; + + /** + * Rule to disallow calling global object properties as functions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-obj-calls + */ + "no-obj-calls": Linter.RuleEntry<[]>; + + /** + * Rule to disallow calls to the `Object` constructor without an argument. + * + * @since 8.50.0 + * @see https://eslint.org/docs/latest/rules/no-object-constructor + */ + "no-object-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow octal literals. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-octal + */ + "no-octal": Linter.RuleEntry<[]>; + + /** + * Rule to disallow octal escape sequences in string literals. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-octal-escape + */ + "no-octal-escape": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassigning function parameters. + * + * @since 0.18.0 + * @see https://eslint.org/docs/latest/rules/no-param-reassign + */ + "no-param-reassign": Linter.RuleEntry< + [ + | { + props?: false; + } + | ({ + props: true; + } & Partial<{ + /** + * @default [] + */ + ignorePropertyModificationsFor: string[]; + /** + * @since 6.6.0 + * @default [] + */ + ignorePropertyModificationsForRegex: string[]; + }>), + ] + >; + + /** + * Rule to disallow string concatenation with `__dirname` and `__filename`. + * + * @since 0.4.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-path-concat`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-path-concat.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-path-concat + */ + "no-path-concat": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the unary operators `++` and `--`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-plusplus + */ + "no-plusplus": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowForLoopAfterthoughts: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of `process.env`. + * + * @since 0.9.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-process-env`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-process-env.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-process-env + */ + "no-process-env": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `process.exit()`. + * + * @since 0.4.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-process-exit`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-process-exit.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-process-exit + */ + "no-process-exit": Linter.RuleEntry<[]>; + + /** + * Rule to disallow returning values from Promise executor functions. + * + * @since 7.3.0 + * @see https://eslint.org/docs/latest/rules/no-promise-executor-return + */ + "no-promise-executor-return": Linter.RuleEntry< + [ + { + /** + * @default false + */ + allowVoid?: boolean; + }, + ] + >; + + /** + * Rule to disallow the use of the `__proto__` property. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-proto + */ + "no-proto": Linter.RuleEntry<[]>; + + /** + * Rule to disallow calling some `Object.prototype` methods directly on objects. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.11.0 + * @see https://eslint.org/docs/latest/rules/no-prototype-builtins + */ + "no-prototype-builtins": Linter.RuleEntry<[]>; + + /** + * Rule to disallow variable redeclaration. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-redeclare + */ + "no-redeclare": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + builtinGlobals: boolean; + }>, + ] + >; + + /** + * Rule to disallow multiple spaces in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-regex-spaces + */ + "no-regex-spaces": Linter.RuleEntry<[]>; + + /** + * Rule to disallow specified names in exports. + * + * @since 7.0.0-alpha.0 + * @see https://eslint.org/docs/latest/rules/no-restricted-exports + */ + "no-restricted-exports": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + restrictedNamedExports: string[]; + /** + * @since 9.3.0 + */ + restrictedNamedExportsPattern: string; + /** + * @since 8.33.0 + */ + restrictDefaultExports: Partial<{ + /** + * @default false + */ + direct: boolean; + /** + * @default false + */ + named: boolean; + /** + * @default false + */ + defaultFrom: boolean; + /** + * @default false + */ + namedFrom: boolean; + /** + * @default false + */ + namespaceFrom: boolean; + }>; + }>, + ] + >; + + /** + * Rule to disallow specified global variables. + * + * @since 2.3.0 + * @see https://eslint.org/docs/latest/rules/no-restricted-globals + */ + "no-restricted-globals": Linter.RuleEntry< + [ + ...Array< + | string + | { + name: string; + message?: string | undefined; + } + >, + ] + >; + + /** + * Rule to disallow specified modules when loaded by `import`. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/latest/rules/no-restricted-imports + */ + "no-restricted-imports": Linter.RuleEntry< + [ + ...Array< + | string + | ValidNoRestrictedImportPathOptions + | Partial<{ + paths: Array< + string | ValidNoRestrictedImportPathOptions + >; + patterns: Array< + string | ValidNoRestrictedImportPatternOptions + >; + }> + >, + ] + >; + + /** + * Rule to disallow specified modules when loaded by `require`. + * + * @since 0.6.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-restricted-require`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-restricted-require.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-restricted-modules + */ + "no-restricted-modules": Linter.RuleEntry< + [ + ...Array< + | string + | { + name: string; + message?: string | undefined; + } + | Partial<{ + paths: Array< + | string + | { + name: string; + message?: string | undefined; + } + >; + patterns: string[]; + }> + >, + ] + >; + + /** + * Rule to disallow certain properties on certain objects. + * + * @since 3.5.0 + * @see https://eslint.org/docs/latest/rules/no-restricted-properties + */ + "no-restricted-properties": Linter.RuleEntry< + [ + ...Array< + | { + object: string; + property?: string | undefined; + message?: string | undefined; + } + | { + property: string; + allowObjects?: string[]; + message?: string | undefined; + } + | { + object: string; + allowProperties?: string[]; + message?: string | undefined; + } + >, + ] + >; + + /** + * Rule to disallow specified syntax. + * + * @since 1.4.0 + * @see https://eslint.org/docs/latest/rules/no-restricted-syntax + */ + "no-restricted-syntax": Linter.RuleEntry< + [ + ...Array< + | string + | { + selector: string; + message?: string | undefined; + } + >, + ] + >; + + /** + * Rule to disallow assignment operators in `return` statements. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-return-assign + */ + "no-return-assign": Linter.RuleEntry<["except-parens" | "always"]>; + + /** + * Rule to disallow unnecessary `return await`. + * + * @since 3.10.0 + * @deprecated since 8.46.0. + * The original assumption of the rule no longer holds true because of engine optimization. + * @see https://eslint.org/docs/latest/rules/no-return-await + */ + "no-return-await": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `javascript:` URLs. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-script-url + */ + "no-script-url": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignments where both sides are exactly the same. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/latest/rules/no-self-assign + */ + "no-self-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow comparisons where both sides are exactly the same. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-self-compare + */ + "no-self-compare": Linter.RuleEntry<[]>; + + /** + * Rule to disallow comma operators. + * + * @since 0.5.1 + * @see https://eslint.org/docs/latest/rules/no-sequences + */ + "no-sequences": Linter.RuleEntry< + [ + Partial<{ + /** + * @since 7.23.0 + * @default true + */ + allowInParentheses: boolean; + }>, + ] + >; + + /** + * Rule to disallow returning values from setters. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/no-setter-return + */ + "no-setter-return": Linter.RuleEntry<[]>; + + /** + * Rule to disallow variable declarations from shadowing variables declared in the outer scope. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-shadow + */ + "no-shadow": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + builtinGlobals: boolean; + /** + * @default 'functions' + */ + hoist: + | "functions" + | "all" + | "never" + | "types" + | "functions-and-types"; + allow: string[]; + /** + * @since 8.10.0 + * @default false + */ + ignoreOnInitialization: boolean; + /** + * @default true + */ + ignoreTypeValueShadow: boolean; + /** + * @default true + */ + ignoreFunctionTypeParameterNameValueShadow: boolean; + }>, + ] + >; + + /** + * Rule to disallow identifiers from shadowing restricted names. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.1.4 + * @see https://eslint.org/docs/latest/rules/no-shadow-restricted-names + */ + "no-shadow-restricted-names": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + reportGlobalThis: boolean; + }>, + ] + >; + + /** + * Rule to disallow spacing between function identifiers and their applications (deprecated). + * + * @since 0.1.2 + * @deprecated since 3.3.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`function-call-spacing`](https://eslint.style/rules/js/function-call-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-spaced-func + */ + "no-spaced-func": Linter.RuleEntry<[]>; + + /** + * Rule to disallow sparse arrays. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-sparse-arrays + */ + "no-sparse-arrays": Linter.RuleEntry<[]>; + + /** + * Rule to disallow synchronous methods. + * + * @since 0.0.9 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-sync`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-sync.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-sync + */ + "no-sync": Linter.RuleEntry< + [ + { + /** + * @default false + */ + allowAtRootLevel: boolean; + }, + ] + >; + + /** + * Rule to disallow all tabs. + * + * @since 3.2.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-tabs`](https://eslint.style/rules/js/no-tabs) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-tabs + */ + "no-tabs": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowIndentationTabs: boolean; + }>, + ] + >; + + /** + * Rule to disallow template literal placeholder syntax in regular strings. + * + * @since 3.3.0 + * @see https://eslint.org/docs/latest/rules/no-template-curly-in-string + */ + "no-template-curly-in-string": Linter.RuleEntry<[]>; + + /** + * Rule to disallow ternary operators. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-ternary + */ + "no-ternary": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `this`/`super` before calling `super()` in constructors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.24.0 + * @see https://eslint.org/docs/latest/rules/no-this-before-super + */ + "no-this-before-super": Linter.RuleEntry<[]>; + + /** + * Rule to disallow throwing literals as exceptions. + * + * @since 0.15.0 + * @see https://eslint.org/docs/latest/rules/no-throw-literal + */ + "no-throw-literal": Linter.RuleEntry<[]>; + + /** + * Rule to disallow trailing whitespace at the end of lines. + * + * @since 0.7.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-trailing-spaces`](https://eslint.style/rules/js/no-trailing-spaces) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-trailing-spaces + */ + "no-trailing-spaces": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + skipBlankLines: boolean; + /** + * @default false + */ + ignoreComments: boolean; + }>, + ] + >; + + /** + * Rule to disallow `let` or `var` variables that are read but never assigned. + * + * @since 9.27.0 + * @see https://eslint.org/docs/latest/rules/no-unassigned-vars + */ + "no-unassigned-vars": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of undeclared variables unless mentioned in \/*global *\/ comments. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-undef + */ + "no-undef": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + typeof: boolean; + }>, + ] + >; + + /** + * Rule to disallow initializing variables to `undefined`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-undef-init + */ + "no-undef-init": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `undefined` as an identifier. + * + * @since 0.7.1 + * @see https://eslint.org/docs/latest/rules/no-undefined + */ + "no-undefined": Linter.RuleEntry<[]>; + + /** + * Rule to disallow dangling underscores in identifiers. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-underscore-dangle + */ + "no-underscore-dangle": Linter.RuleEntry< + [ + Partial<{ + allow: string[]; + /** + * @default false + */ + allowAfterThis: boolean; + /** + * @default false + */ + allowAfterSuper: boolean; + /** + * @since 6.7.0 + * @default false + */ + allowAfterThisConstructor: boolean; + /** + * @default false + */ + enforceInMethodNames: boolean; + /** + * @since 8.15.0 + * @default false + */ + enforceInClassFields: boolean; + /** + * @since 8.31.0 + * @default true + */ + allowInArrayDestructuring: boolean; + /** + * @since 8.31.0 + * @default true + */ + allowInObjectDestructuring: boolean; + /** + * @since 7.7.0 + * @default true + */ + allowFunctionParams: boolean; + }>, + ] + >; + + /** + * Rule to disallow confusing multiline expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.24.0 + * @see https://eslint.org/docs/latest/rules/no-unexpected-multiline + */ + "no-unexpected-multiline": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unmodified loop conditions. + * + * @since 2.0.0-alpha-2 + * @see https://eslint.org/docs/latest/rules/no-unmodified-loop-condition + */ + "no-unmodified-loop-condition": Linter.RuleEntry<[]>; + + /** + * Rule to disallow ternary operators when simpler alternatives exist. + * + * @since 0.21.0 + * @see https://eslint.org/docs/latest/rules/no-unneeded-ternary + */ + "no-unneeded-ternary": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + defaultAssignment: boolean; + }>, + ] + >; + + /** + * Rule to disallow unreachable code after `return`, `throw`, `continue`, and `break` statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-unreachable + */ + "no-unreachable": Linter.RuleEntry<[]>; + + /** + * Rule to disallow loops with a body that allows only one iteration. + * + * @since 7.3.0 + * @see https://eslint.org/docs/latest/rules/no-unreachable-loop + */ + "no-unreachable-loop": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + ignore: + | "WhileStatement" + | "DoWhileStatement" + | "ForStatement" + | "ForInStatement" + | "ForOfStatement"; + }>, + ] + >; + + /** + * Rule to disallow control flow statements in `finally` blocks. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.9.0 + * @see https://eslint.org/docs/latest/rules/no-unsafe-finally + */ + "no-unsafe-finally": Linter.RuleEntry<[]>; + + /** + * Rule to disallow negating the left operand of relational operators. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 3.3.0 + * @see https://eslint.org/docs/latest/rules/no-unsafe-negation + */ + "no-unsafe-negation": Linter.RuleEntry< + [ + Partial<{ + /** + * @since 6.6.0 + * @default false + */ + enforceForOrderingRelations: boolean; + }>, + ] + >; + + /** + * Rule to disallow use of optional chaining in contexts where the `undefined` value is not allowed. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 7.15.0 + * @see https://eslint.org/docs/latest/rules/no-unsafe-optional-chaining + */ + "no-unsafe-optional-chaining": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + disallowArithmeticOperators: boolean; + }>, + ] + >; + + /** + * Rule to disallow unused expressions. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/no-unused-expressions + */ + "no-unused-expressions": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowShortCircuit: boolean; + /** + * @default false + */ + allowTernary: boolean; + /** + * @default false + */ + allowTaggedTemplates: boolean; + /** + * @since 7.20.0 + * @default false + */ + enforceForJSX: boolean; + /** + * @default false + */ + ignoreDirectives: boolean; + }>, + ] + >; + + /** + * Rule to disallow unused labels. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/latest/rules/no-unused-labels + */ + "no-unused-labels": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unused private class members. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 8.1.0 + * @see https://eslint.org/docs/latest/rules/no-unused-private-class-members + */ + "no-unused-private-class-members": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unused variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-unused-vars + */ + "no-unused-vars": Linter.RuleEntry< + [ + | "all" + | "local" + | Partial<{ + /** + * @default 'all' + */ + vars: "all" | "local"; + varsIgnorePattern: string; + /** + * @default 'after-used' + */ + args: "after-used" | "all" | "none"; + /** + * @default false + */ + ignoreRestSiblings: boolean; + argsIgnorePattern: string; + /** + * @default 'all' + */ + caughtErrors: "none" | "all"; + caughtErrorsIgnorePattern: string; + destructuredArrayIgnorePattern: string; + /** + * @default false + */ + ignoreClassWithStaticInitBlock: boolean; + /** + * @default false + */ + reportUsedIgnorePattern: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of variables before they are defined. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-use-before-define + */ + "no-use-before-define": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default true + */ + functions: boolean; + /** + * @default true + */ + classes: boolean; + /** + * @default true + */ + variables: boolean; + /** + * @default false + */ + allowNamedExports: boolean; + /** + * @default true + */ + enums: boolean; + /** + * @default true + */ + typedefs: boolean; + /** + * @default true + */ + ignoreTypeReferences: boolean; + }> + | "nofunc", + ] + >; + + /** + * Rule to disallow variable assignments when the value is not used. + * + * @since 9.0.0-alpha.1 + * @see https://eslint.org/docs/latest/rules/no-useless-assignment + */ + "no-useless-assignment": Linter.RuleEntry<[]>; + + /** + * Rule to disallow useless backreferences in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 7.0.0-alpha.0 + * @see https://eslint.org/docs/latest/rules/no-useless-backreference + */ + "no-useless-backreference": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary calls to `.call()` and `.apply()`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/no-useless-call + */ + "no-useless-call": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary `catch` clauses. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.11.0 + * @see https://eslint.org/docs/latest/rules/no-useless-catch + */ + "no-useless-catch": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary computed property keys in objects and classes. + * + * @since 2.9.0 + * @see https://eslint.org/docs/latest/rules/no-useless-computed-key + */ + "no-useless-computed-key": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + enforceForClassMembers: boolean; + }>, + ] + >; + + /** + * Rule to disallow unnecessary concatenation of literals or template literals. + * + * @since 1.3.0 + * @see https://eslint.org/docs/latest/rules/no-useless-concat + */ + "no-useless-concat": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary constructors. + * + * @since 2.0.0-beta.1 + * @see https://eslint.org/docs/latest/rules/no-useless-constructor + */ + "no-useless-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary escape characters. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.5.0 + * @see https://eslint.org/docs/latest/rules/no-useless-escape + */ + "no-useless-escape": Linter.RuleEntry< + [ + Partial<{ + allowRegexCharacters: string[]; + }>, + ] + >; + + /** + * Rule to disallow renaming import, export, and destructured assignments to the same name. + * + * @since 2.11.0 + * @see https://eslint.org/docs/latest/rules/no-useless-rename + */ + "no-useless-rename": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreImport: boolean; + /** + * @default false + */ + ignoreExport: boolean; + /** + * @default false + */ + ignoreDestructuring: boolean; + }>, + ] + >; + + /** + * Rule to disallow redundant return statements. + * + * @since 3.9.0 + * @see https://eslint.org/docs/latest/rules/no-useless-return + */ + "no-useless-return": Linter.RuleEntry<[]>; + + /** + * Rule to require `let` or `const` instead of `var`. + * + * @since 0.12.0 + * @see https://eslint.org/docs/latest/rules/no-var + */ + "no-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `void` operators. + * + * @since 0.8.0 + * @see https://eslint.org/docs/latest/rules/no-void + */ + "no-void": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowAsStatement: boolean; + }>, + ] + >; + + /** + * Rule to disallow specified warning terms in comments. + * + * @since 0.4.4 + * @see https://eslint.org/docs/latest/rules/no-warning-comments + */ + "no-warning-comments": Linter.RuleEntry< + [ + { + /** + * @default ["todo", "fixme", "xxx"] + */ + terms: string[]; + /** + * @default 'start' + */ + location: "start" | "anywhere"; + }, + ] + >; + + /** + * Rule to disallow whitespace before properties. + * + * @since 2.0.0-beta.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-whitespace-before-property`](https://eslint.style/rules/js/no-whitespace-before-property) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/no-whitespace-before-property + */ + "no-whitespace-before-property": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `with` statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-with + */ + "no-with": Linter.RuleEntry<[]>; + + /** + * Rule to enforce the location of single-line statements. + * + * @since 3.17.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`nonblock-statement-body-position`](https://eslint.style/rules/js/nonblock-statement-body-position) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/nonblock-statement-body-position + */ + "nonblock-statement-body-position": Linter.RuleEntry< + [ + "beside" | "below" | "any", + Partial<{ + overrides: Record; + }>, + ] + >; + + /** + * Rule to enforce consistent line breaks after opening and before closing braces. + * + * @since 2.12.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`object-curly-newline`](https://eslint.style/rules/js/object-curly-newline) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/object-curly-newline + */ + "object-curly-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | Partial<{ + /** + * @default false + */ + multiline: boolean; + minProperties: number; + /** + * @default true + */ + consistent: boolean; + }> + | Partial< + Record< + | "ObjectExpression" + | "ObjectPattern" + | "ImportDeclaration" + | "ExportDeclaration", + | "always" + | "never" + | Partial<{ + /** + * @default false + */ + multiline: boolean; + minProperties: number; + /** + * @default true + */ + consistent: boolean; + }> + > + >, + ] + >; + + /** + * Rule to enforce consistent spacing inside braces. + * + * @since 0.22.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`object-curly-spacing`](https://eslint.style/rules/js/object-curly-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/object-curly-spacing + */ + "object-curly-spacing": + | Linter.RuleEntry< + [ + "never", + { + /** + * @default false + */ + arraysInObjects: boolean; + /** + * @default false + */ + objectsInObjects: boolean; + }, + ] + > + | Linter.RuleEntry< + [ + "always", + { + /** + * @default true + */ + arraysInObjects: boolean; + /** + * @default true + */ + objectsInObjects: boolean; + }, + ] + >; + + /** + * Rule to enforce placing object properties on separate lines. + * + * @since 2.10.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`object-property-newline`](https://eslint.style/rules/js/object-property-newline) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/object-property-newline + */ + "object-property-newline": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowAllPropertiesOnSameLine: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow method and property shorthand syntax for object literals. + * + * @since 0.20.0 + * @see https://eslint.org/docs/latest/rules/object-shorthand + */ + "object-shorthand": + | Linter.RuleEntry< + [ + "always" | "methods", + Partial<{ + /** + * @default false + */ + avoidQuotes: boolean; + /** + * @default false + */ + ignoreConstructors: boolean; + /** + * @since 8.22.0 + */ + methodsIgnorePattern: string; + /** + * @default false + */ + avoidExplicitReturnArrows: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "properties", + Partial<{ + /** + * @default false + */ + avoidQuotes: boolean; + }>, + ] + > + | Linter.RuleEntry<["never" | "consistent" | "consistent-as-needed"]>; + + /** + * Rule to enforce variables to be declared either together or separately in functions. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/one-var + */ + "one-var": Linter.RuleEntry< + [ + | "always" + | "never" + | "consecutive" + | Partial< + { + /** + * @default false + */ + separateRequires: boolean; + } & Record< + "var" | "let" | "const", + "always" | "never" | "consecutive" + > + > + | Partial< + Record< + "initialized" | "uninitialized", + "always" | "never" | "consecutive" + > + >, + ] + >; + + /** + * Rule to require or disallow newlines around variable declarations. + * + * @since 2.0.0-beta.3 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`one-var-declaration-per-line`](https://eslint.style/rules/js/one-var-declaration-per-line) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/one-var-declaration-per-line + */ + "one-var-declaration-per-line": Linter.RuleEntry< + ["initializations" | "always"] + >; + + /** + * Rule to require or disallow assignment operator shorthand where possible. + * + * @since 0.10.0 + * @see https://eslint.org/docs/latest/rules/operator-assignment + */ + "operator-assignment": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to enforce consistent linebreak style for operators. + * + * @since 0.19.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`operator-linebreak`](https://eslint.style/rules/js/operator-linebreak) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/operator-linebreak + */ + "operator-linebreak": Linter.RuleEntry< + [ + "after" | "before" | "none", + Partial<{ + overrides: Record; + }>, + ] + >; + + /** + * Rule to require or disallow padding within blocks. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`padded-blocks`](https://eslint.style/rules/js/padded-blocks) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/padded-blocks + */ + "padded-blocks": Linter.RuleEntry< + [ + ( + | "always" + | "never" + | Partial< + Record< + "blocks" | "classes" | "switches", + "always" | "never" + > + > + ), + { + /** + * @default false + */ + allowSingleLineBlocks: boolean; + }, + ] + >; + + /** + * Rule to require or disallow padding lines between statements. + * + * @since 4.0.0-beta.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`padding-line-between-statements`](https://eslint.style/rules/js/padding-line-between-statements) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/padding-line-between-statements + */ + "padding-line-between-statements": Linter.RuleEntry< + [ + ...Array< + { + blankLine: "any" | "never" | "always"; + } & Record<"prev" | "next", string | string[]> + >, + ] + >; + + /** + * Rule to require using arrow functions for callbacks. + * + * @since 1.2.0 + * @see https://eslint.org/docs/latest/rules/prefer-arrow-callback + */ + "prefer-arrow-callback": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowNamedFunctions: boolean; + /** + * @default true + */ + allowUnboundThis: boolean; + }>, + ] + >; + + /** + * Rule to require `const` declarations for variables that are never reassigned after declared. + * + * @since 0.23.0 + * @see https://eslint.org/docs/latest/rules/prefer-const + */ + "prefer-const": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'any' + */ + destructuring: "any" | "all"; + /** + * @default false + */ + ignoreReadBeforeAssign: boolean; + }>, + ] + >; + + /** + * Rule to require destructuring from arrays and/or objects. + * + * @since 3.13.0 + * @see https://eslint.org/docs/latest/rules/prefer-destructuring + */ + "prefer-destructuring": Linter.RuleEntry< + [ + Partial< + | { + VariableDeclarator: Partial<{ + array: boolean; + object: boolean; + }>; + AssignmentExpression: Partial<{ + array: boolean; + object: boolean; + }>; + } + | { + array: boolean; + object: boolean; + } + >, + Partial<{ + enforceForRenamedProperties: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of `Math.pow` in favor of the `**` operator. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/prefer-exponentiation-operator + */ + "prefer-exponentiation-operator": Linter.RuleEntry<[]>; + + /** + * Rule to enforce using named capture group in regular expression. + * + * @since 5.15.0 + * @see https://eslint.org/docs/latest/rules/prefer-named-capture-group + */ + "prefer-named-capture-group": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals. + * + * @since 3.5.0 + * @see https://eslint.org/docs/latest/rules/prefer-numeric-literals + */ + "prefer-numeric-literals": Linter.RuleEntry<[]>; + + /** + * Rule to disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()`. + * + * @since 8.5.0 + * @see https://eslint.org/docs/latest/rules/prefer-object-has-own + */ + "prefer-object-has-own": Linter.RuleEntry<[]>; + + /** + * Rule to disallow using `Object.assign` with an object literal as the first argument and prefer the use of object spread instead. + * + * @since 5.0.0-alpha.3 + * @see https://eslint.org/docs/latest/rules/prefer-object-spread + */ + "prefer-object-spread": Linter.RuleEntry<[]>; + + /** + * Rule to require using Error objects as Promise rejection reasons. + * + * @since 3.14.0 + * @see https://eslint.org/docs/latest/rules/prefer-promise-reject-errors + */ + "prefer-promise-reject-errors": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowEmptyReject: boolean; + }>, + ] + >; + + /** + * Rule to require `Reflect` methods where applicable. + * + * @since 1.0.0-rc-2 + * @deprecated since 3.9.0. + * The original intention of this rule was misguided. + * @see https://eslint.org/docs/latest/rules/prefer-reflect + */ + "prefer-reflect": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow use of the `RegExp` constructor in favor of regular expression literals. + * + * @since 6.4.0 + * @see https://eslint.org/docs/latest/rules/prefer-regex-literals + */ + "prefer-regex-literals": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + disallowRedundantWrapping: boolean; + }>, + ] + >; + + /** + * Rule to require rest parameters instead of `arguments`. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/latest/rules/prefer-rest-params + */ + "prefer-rest-params": Linter.RuleEntry<[]>; + + /** + * Rule to require spread operators instead of `.apply()`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/prefer-spread + */ + "prefer-spread": Linter.RuleEntry<[]>; + + /** + * Rule to require template literals instead of string concatenation. + * + * @since 1.2.0 + * @see https://eslint.org/docs/latest/rules/prefer-template + */ + "prefer-template": Linter.RuleEntry<[]>; + + /** + * Rule to require quotes around object literal property names. + * + * @since 0.0.6 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`quote-props`](https://eslint.style/rules/js/quote-props) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/quote-props + */ + "quote-props": + | Linter.RuleEntry<["always" | "consistent"]> + | Linter.RuleEntry< + [ + "as-needed", + Partial<{ + /** + * @default false + */ + keywords: boolean; + /** + * @default true + */ + unnecessary: boolean; + /** + * @default false + */ + numbers: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "consistent-as-needed", + Partial<{ + /** + * @default false + */ + keywords: boolean; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of either backticks, double, or single quotes. + * + * @since 0.0.7 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`quotes`](https://eslint.style/rules/js/quotes) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/quotes + */ + quotes: Linter.RuleEntry< + [ + "double" | "single" | "backtick", + Partial<{ + /** + * @default false + */ + avoidEscape: boolean; + /** + * @default false + */ + allowTemplateLiterals: boolean; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of the radix argument when using `parseInt()`. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/radix + */ + radix: Linter.RuleEntry<["always" | "as-needed"]>; + + /** + * Rule to disallow assignments that can lead to race conditions due to usage of `await` or `yield`. + * + * @since 5.3.0 + * @see https://eslint.org/docs/latest/rules/require-atomic-updates + */ + "require-atomic-updates": Linter.RuleEntry< + [ + Partial<{ + /** + * @since 8.3.0 + * @default false + */ + allowProperties: boolean; + }>, + ] + >; + + /** + * Rule to disallow async functions which have no `await` expression. + * + * @since 3.11.0 + * @see https://eslint.org/docs/latest/rules/require-await + */ + "require-await": Linter.RuleEntry<[]>; + + /** + * Rule to enforce the use of `u` or `v` flag on regular expressions. + * + * @since 5.3.0 + * @see https://eslint.org/docs/latest/rules/require-unicode-regexp + */ + "require-unicode-regexp": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + requireFlag: "u" | "v"; + }>, + ] + >; + + /** + * Rule to require generator functions to contain `yield`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/require-yield + */ + "require-yield": Linter.RuleEntry<[]>; + + /** + * Rule to enforce spacing between rest and spread operators and their expressions. + * + * @since 2.12.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`rest-spread-spacing`](https://eslint.style/rules/js/rest-spread-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/rest-spread-spacing + */ + "rest-spread-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require or disallow semicolons instead of ASI. + * + * @since 0.0.6 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`semi`](https://eslint.style/rules/js/semi) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/semi + */ + semi: + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default false + */ + omitLastInOneLineBlock: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "never", + Partial<{ + /** + * @default 'any' + */ + beforeStatementContinuationChars: + | "any" + | "always" + | "never"; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before and after semicolons. + * + * @since 0.16.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`semi-spacing`](https://eslint.style/rules/js/semi-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/semi-spacing + */ + "semi-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + before: boolean; + /** + * @default true + */ + after: boolean; + }>, + ] + >; + + /** + * Rule to enforce location of semicolons. + * + * @since 4.0.0-beta.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`semi-style`](https://eslint.style/rules/js/semi-style) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/semi-style + */ + "semi-style": Linter.RuleEntry<["last" | "first"]>; + + /** + * Rule to enforce sorted `import` declarations within modules. + * + * @since 2.0.0-beta.1 + * @see https://eslint.org/docs/latest/rules/sort-imports + */ + "sort-imports": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreCase: boolean; + /** + * @default false + */ + ignoreDeclarationSort: boolean; + /** + * @default false + */ + ignoreMemberSort: boolean; + /** + * @default ['none', 'all', 'multiple', 'single'] + */ + memberSyntaxSortOrder: Array< + "none" | "all" | "multiple" | "single" + >; + /** + * @default false + */ + allowSeparatedGroups: boolean; + }>, + ] + >; + + /** + * Rule to require object keys to be sorted. + * + * @since 3.3.0 + * @see https://eslint.org/docs/latest/rules/sort-keys + */ + "sort-keys": Linter.RuleEntry< + [ + "asc" | "desc", + Partial<{ + /** + * @default true + */ + caseSensitive: boolean; + /** + * @default 2 + */ + minKeys: number; + /** + * @default false + */ + natural: boolean; + /** + * @default false + */ + allowLineSeparatedGroups: boolean; + /** + * @default false + */ + ignoreComputedKeys: boolean; + }>, + ] + >; + + /** + * Rule to require variables within the same declaration block to be sorted. + * + * @since 0.2.0 + * @see https://eslint.org/docs/latest/rules/sort-vars + */ + "sort-vars": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreCase: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before blocks. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-before-blocks`](https://eslint.style/rules/js/space-before-blocks) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/space-before-blocks + */ + "space-before-blocks": Linter.RuleEntry< + [ + | "always" + | "never" + | Partial< + Record< + "functions" | "keywords" | "classes", + "always" | "never" | "off" + > + >, + ] + >; + + /** + * Rule to enforce consistent spacing before `function` definition opening parenthesis. + * + * @since 0.18.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-before-function-paren`](https://eslint.style/rules/js/space-before-function-paren) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/space-before-function-paren + */ + "space-before-function-paren": Linter.RuleEntry< + [ + | "always" + | "never" + | Partial< + Record< + "anonymous" | "named" | "asyncArrow", + "always" | "never" | "ignore" + > + >, + ] + >; + + /** + * Rule to enforce consistent spacing inside parentheses. + * + * @since 0.8.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-in-parens`](https://eslint.style/rules/js/space-in-parens) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/space-in-parens + */ + "space-in-parens": Linter.RuleEntry< + [ + "never" | "always", + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to require spacing around infix operators. + * + * @since 0.2.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-infix-ops`](https://eslint.style/rules/js/space-infix-ops) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/space-infix-ops + */ + "space-infix-ops": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + int32Hint: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before or after unary operators. + * + * @since 0.10.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-unary-ops`](https://eslint.style/rules/js/space-unary-ops) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/space-unary-ops + */ + "space-unary-ops": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + words: boolean; + /** + * @default false + */ + nonwords: boolean; + overrides: Record; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing after the `//` or `/*` in a comment. + * + * @since 0.23.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`spaced-comment`](https://eslint.style/rules/js/spaced-comment) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/spaced-comment + */ + "spaced-comment": Linter.RuleEntry< + [ + "always" | "never", + { + exceptions: string[]; + markers: string[]; + line: { + exceptions: string[]; + markers: string[]; + }; + block: { + exceptions: string[]; + markers: string[]; + /** + * @default false + */ + balanced: boolean; + }; + }, + ] + >; + + /** + * Rule to require or disallow strict mode directives. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/strict + */ + strict: Linter.RuleEntry<["safe" | "global" | "function" | "never"]>; + + /** + * Rule to enforce spacing around colons of switch statements. + * + * @since 4.0.0-beta.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`switch-colon-spacing`](https://eslint.style/rules/js/switch-colon-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/switch-colon-spacing + */ + "switch-colon-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + before: boolean; + /** + * @default true + */ + after: boolean; + }>, + ] + >; + + /** + * Rule to require symbol descriptions. + * + * @since 3.4.0 + * @see https://eslint.org/docs/latest/rules/symbol-description + */ + "symbol-description": Linter.RuleEntry<[]>; + + /** + * Rule to require or disallow spacing around embedded expressions of template strings. + * + * @since 2.0.0-rc.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`template-curly-spacing`](https://eslint.style/rules/js/template-curly-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/template-curly-spacing + */ + "template-curly-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require or disallow spacing between template tags and their literals. + * + * @since 3.15.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`template-tag-spacing`](https://eslint.style/rules/js/template-tag-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/template-tag-spacing + */ + "template-tag-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require or disallow Unicode byte order mark (BOM). + * + * @since 2.11.0 + * @see https://eslint.org/docs/latest/rules/unicode-bom + */ + "unicode-bom": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require calls to `isNaN()` when checking for `NaN`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/use-isnan + */ + "use-isnan": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + enforceForSwitchCase: boolean; + /** + * @default true + */ + enforceForIndexOf: boolean; + }>, + ] + >; + + /** + * Rule to enforce comparing `typeof` expressions against valid strings. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.5.0 + * @see https://eslint.org/docs/latest/rules/valid-typeof + */ + "valid-typeof": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + requireStringLiterals: boolean; + }>, + ] + >; + + /** + * Rule to require `var` declarations be placed at the top of their containing scope. + * + * @since 0.8.0 + * @see https://eslint.org/docs/latest/rules/vars-on-top + */ + "vars-on-top": Linter.RuleEntry<[]>; + + /** + * Rule to require parentheses around immediate `function` invocations. + * + * @since 0.0.9 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`wrap-iife`](https://eslint.style/rules/js/wrap-iife) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/wrap-iife + */ + "wrap-iife": Linter.RuleEntry< + [ + "outside" | "inside" | "any", + Partial<{ + /** + * @default false + */ + functionPrototypeMethods: boolean; + }>, + ] + >; + + /** + * Rule to require parenthesis around regex literals. + * + * @since 0.1.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`wrap-regex`](https://eslint.style/rules/js/wrap-regex) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/wrap-regex + */ + "wrap-regex": Linter.RuleEntry<[]>; + + /** + * Rule to require or disallow spacing around the `*` in `yield*` expressions. + * + * @since 2.0.0-alpha-1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`yield-star-spacing`](https://eslint.style/rules/js/yield-star-spacing) in [`@stylistic/eslint-plugin-js`](https://eslint.style/packages/js). + * @see https://eslint.org/docs/latest/rules/yield-star-spacing + */ + "yield-star-spacing": Linter.RuleEntry< + [ + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither", + ] + >; + + /** + * Rule to require or disallow "Yoda" conditions. + * + * @since 0.7.1 + * @see https://eslint.org/docs/latest/rules/yoda + */ + yoda: + | Linter.RuleEntry< + [ + "never", + Partial<{ + exceptRange: boolean; + onlyEquality: boolean; + }>, + ] + > + | Linter.RuleEntry<["always"]>; +} diff --git a/node_modules/eslint/lib/types/universal.d.ts b/node_modules/eslint/lib/types/universal.d.ts new file mode 100644 index 00000000..df4fdecd --- /dev/null +++ b/node_modules/eslint/lib/types/universal.d.ts @@ -0,0 +1,6 @@ +/** + * @fileoverview typings for "eslint/universal" module + * @author 唯然 + */ + +export { Linter } from "./index"; diff --git a/node_modules/eslint/lib/types/use-at-your-own-risk.d.ts b/node_modules/eslint/lib/types/use-at-your-own-risk.d.ts new file mode 100644 index 00000000..f97f4f34 --- /dev/null +++ b/node_modules/eslint/lib/types/use-at-your-own-risk.d.ts @@ -0,0 +1,87 @@ +/** + * @fileoverview This file contains the types for the use-at-your-own-risk + * entrypoint. It was initially extracted from the `@types/eslint` package. + */ + +/* + * MIT License + * Copyright (c) Microsoft Corporation. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE + */ + +import { ESLint, Rule } from "./index.js"; + +/** @deprecated */ +export const builtinRules: Map; + +/** @deprecated */ +export class FileEnumerator { + constructor(params?: { + cwd?: string; + configArrayFactory?: any; + extensions?: any; + globInputPaths?: boolean; + errorOnUnmatchedPattern?: boolean; + ignore?: boolean; + }); + isTargetPath(filePath: string, providedConfig?: any): boolean; + iterateFiles( + patternOrPatterns: string | string[], + ): IterableIterator<{ config: any; filePath: string; ignored: boolean }>; +} + +export { /** @deprecated */ ESLint as FlatESLint }; + +/** @deprecated */ +export class LegacyESLint { + static configType: "eslintrc"; + + static readonly version: string; + + static outputFixes(results: ESLint.LintResult[]): Promise; + + static getErrorResults(results: ESLint.LintResult[]): ESLint.LintResult[]; + + constructor(options?: ESLint.LegacyOptions); + + lintFiles(patterns: string | string[]): Promise; + + lintText( + code: string, + options?: { + filePath?: string | undefined; + warnIgnored?: boolean | undefined; + }, + ): Promise; + + getRulesMetaForResults( + results: ESLint.LintResult[], + ): ESLint.LintResultData["rulesMeta"]; + + hasFlag(flag: string): false; + + calculateConfigForFile(filePath: string): Promise; + + isPathIgnored(filePath: string): Promise; + + loadFormatter(nameOrPath?: string): Promise; +} + +/** @deprecated */ +export function shouldUseFlatConfig(): Promise; diff --git a/node_modules/eslint/lib/universal.js b/node_modules/eslint/lib/universal.js new file mode 100644 index 00000000..51bac584 --- /dev/null +++ b/node_modules/eslint/lib/universal.js @@ -0,0 +1,10 @@ +/** + * @fileoverview exports for browsers + * @author 唯然 + */ + +"use strict"; + +const { Linter } = require("./linter/linter"); + +module.exports = { Linter }; diff --git a/node_modules/eslint/lib/unsupported-api.js b/node_modules/eslint/lib/unsupported-api.js new file mode 100644 index 00000000..2287728e --- /dev/null +++ b/node_modules/eslint/lib/unsupported-api.js @@ -0,0 +1,29 @@ +/** + * @fileoverview APIs that are not officially supported by ESLint. + * These APIs may change or be removed at any time. Use at your + * own risk. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { FileEnumerator } = require("./cli-engine/file-enumerator"); +const { ESLint: FlatESLint, shouldUseFlatConfig } = require("./eslint/eslint"); +const { LegacyESLint } = require("./eslint/legacy-eslint"); +const builtinRules = require("./rules"); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + builtinRules, + FlatESLint, + shouldUseFlatConfig, + FileEnumerator, + LegacyESLint, +}; diff --git a/node_modules/eslint/messages/all-files-ignored.js b/node_modules/eslint/messages/all-files-ignored.js new file mode 100644 index 00000000..3e795c9a --- /dev/null +++ b/node_modules/eslint/messages/all-files-ignored.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function (it) { + const { pattern } = it; + + return ` +You are linting "${pattern}", but all of the files matching the glob pattern "${pattern}" are ignored. + +If you don't want to lint these files, remove the pattern "${pattern}" from the list of arguments passed to ESLint. + +If you do want to lint these files, try the following solutions: + +* Check your .eslintignore file, or the eslintIgnore property in package.json, to ensure that the files are not configured to be ignored. +* Explicitly list the files from this glob that you'd like to lint on the command-line, rather than providing a glob as an argument. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/all-matched-files-ignored.js b/node_modules/eslint/messages/all-matched-files-ignored.js new file mode 100644 index 00000000..2621343b --- /dev/null +++ b/node_modules/eslint/messages/all-matched-files-ignored.js @@ -0,0 +1,21 @@ +"use strict"; + +module.exports = function (it) { + const { pattern } = it; + + return ` +You are linting "${pattern}", but all of the files matching the glob pattern "${pattern}" are ignored. + +If you don't want to lint these files, remove the pattern "${pattern}" from the list of arguments passed to ESLint. + +If you do want to lint these files, explicitly list one or more of the files from this glob that you'd like to lint to see more details about why they are ignored. + + * If the file is ignored because of a matching ignore pattern, check global ignores in your config file. + https://eslint.org/docs/latest/use/configure/ignore + + * If the file is ignored because no matching configuration was supplied, check file patterns in your config file. + https://eslint.org/docs/latest/use/configure/configuration-files#specifying-files-with-arbitrary-extensions + + * If the file is ignored because it is located outside of the base path, change the location of your config file to be in a parent directory. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/config-file-missing.js b/node_modules/eslint/messages/config-file-missing.js new file mode 100644 index 00000000..c4f8ecdb --- /dev/null +++ b/node_modules/eslint/messages/config-file-missing.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function () { + return ` +ESLint couldn't find an eslint.config.(js|mjs|cjs) file. + +From ESLint v9.0.0, the default configuration file is now eslint.config.js. +If you are using a .eslintrc.* file, please follow the migration guide +to update your configuration file to the new format: + +https://eslint.org/docs/latest/use/configure/migration-guide + +If you still have problems after following the migration guide, please stop by +https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/config-plugin-missing.js b/node_modules/eslint/messages/config-plugin-missing.js new file mode 100644 index 00000000..20736749 --- /dev/null +++ b/node_modules/eslint/messages/config-plugin-missing.js @@ -0,0 +1,14 @@ +"use strict"; + +module.exports = function (it) { + const { pluginName, ruleId } = it; + + return ` +A configuration object specifies rule "${ruleId}", but could not find plugin "${pluginName}". + +Common causes of this problem include: + +1. The "${pluginName}" plugin is not defined in your configuration file. +2. The "${pluginName}" plugin is not defined within the same configuration object in which the "${ruleId}" rule is applied. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/config-serialize-function.js b/node_modules/eslint/messages/config-serialize-function.js new file mode 100644 index 00000000..4300e47e --- /dev/null +++ b/node_modules/eslint/messages/config-serialize-function.js @@ -0,0 +1,30 @@ +"use strict"; + +module.exports = function ({ key, objectKey }) { + // special case for parsers + const isParser = + objectKey === "parser" && (key === "parse" || key === "parseForESLint"); + const parserMessage = ` + This typically happens when you're using a custom parser that does not +provide a "meta" property, which is how ESLint determines the serialized +representation. Please open an issue with the maintainer of the custom parser +and share this link: + +https://eslint.org/docs/latest/extend/custom-parsers#meta-data-in-custom-parsers +`.trim(); + + return ` +The requested operation requires ESLint to serialize configuration data, +but the configuration key "${objectKey}.${key}" contains a function value, +which cannot be serialized. + +${ + isParser + ? parserMessage + : "Please double-check your configuration for errors." +} + +If you still have problems, please stop by https://eslint.org/chat/help to chat +with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/eslintrc-incompat.js b/node_modules/eslint/messages/eslintrc-incompat.js new file mode 100644 index 00000000..27fe8c9f --- /dev/null +++ b/node_modules/eslint/messages/eslintrc-incompat.js @@ -0,0 +1,117 @@ +"use strict"; + +/* eslint consistent-return: 0 -- no default case */ + +const messages = { + env: ` +A config object is using the "env" key, which is not supported in flat config system. + +Flat config uses "languageOptions.globals" to define global variables for your files. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#configuring-language-options + +If you're not using "env" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#using-eslintrc-configs-in-flat-config +`, + + extends: ` +A config object is using the "extends" key, which is not supported in flat config system. + +Instead of "extends", you can include config objects that you'd like to extend from directly in the flat config array. + +If you're using "extends" in your config file, please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#predefined-and-shareable-configs + +If you're not using "extends" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#using-eslintrc-configs-in-flat-config +`, + + globals: ` +A config object is using the "globals" key, which is not supported in flat config system. + +Flat config uses "languageOptions.globals" to define global variables for your files. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#configuring-language-options + +If you're not using "globals" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#using-eslintrc-configs-in-flat-config +`, + + ignorePatterns: ` +A config object is using the "ignorePatterns" key, which is not supported in flat config system. + +Flat config uses "ignores" to specify files to ignore. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#ignoring-files + +If you're not using "ignorePatterns" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#using-eslintrc-configs-in-flat-config +`, + + noInlineConfig: ` +A config object is using the "noInlineConfig" key, which is not supported in flat config system. + +Flat config uses "linterOptions.noInlineConfig" to specify files to ignore. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#linter-options +`, + + overrides: ` +A config object is using the "overrides" key, which is not supported in flat config system. + +Flat config is an array that acts like the eslintrc "overrides" array. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#glob-based-configs + +If you're not using "overrides" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#using-eslintrc-configs-in-flat-config +`, + + parser: ` +A config object is using the "parser" key, which is not supported in flat config system. + +Flat config uses "languageOptions.parser" to override the default parser. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#custom-parsers + +If you're not using "parser" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#using-eslintrc-configs-in-flat-config +`, + + parserOptions: ` +A config object is using the "parserOptions" key, which is not supported in flat config system. + +Flat config uses "languageOptions.parserOptions" to specify parser options. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#configuring-language-options + +If you're not using "parserOptions" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#using-eslintrc-configs-in-flat-config +`, + + reportUnusedDisableDirectives: ` +A config object is using the "reportUnusedDisableDirectives" key, which is not supported in flat config system. + +Flat config uses "linterOptions.reportUnusedDisableDirectives" to specify files to ignore. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#linter-options +`, + + root: ` +A config object is using the "root" key, which is not supported in flat config system. + +Flat configs always act as if they are the root config file, so this key can be safely removed. +`, +}; + +module.exports = function ({ key }) { + return messages[key].trim(); +}; diff --git a/node_modules/eslint/messages/eslintrc-plugins.js b/node_modules/eslint/messages/eslintrc-plugins.js new file mode 100644 index 00000000..68cee209 --- /dev/null +++ b/node_modules/eslint/messages/eslintrc-plugins.js @@ -0,0 +1,27 @@ +"use strict"; + +module.exports = function ({ plugins }) { + const isArrayOfStrings = typeof plugins[0] === "string"; + + return ` +A config object has a "plugins" key defined as an array${isArrayOfStrings ? " of strings" : ""}. It looks something like this: + + { + "plugins": ${JSON.stringify(plugins)} + } + +Flat config requires "plugins" to be an object, like this: + + { + plugins: { + ${isArrayOfStrings && plugins[0] ? plugins[0] : "namespace"}: pluginObject + } + } + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#importing-plugins-and-custom-parsers + +If you're using a shareable config that you cannot rewrite in flat config format, then use the compatibility utility: +https://eslint.org/docs/latest/use/configure/migration-guide#using-eslintrc-configs-in-flat-config +`; +}; diff --git a/node_modules/eslint/messages/extend-config-missing.js b/node_modules/eslint/messages/extend-config-missing.js new file mode 100644 index 00000000..32e41e96 --- /dev/null +++ b/node_modules/eslint/messages/extend-config-missing.js @@ -0,0 +1,13 @@ +"use strict"; + +module.exports = function (it) { + const { configName, importerName } = it; + + return ` +ESLint couldn't find the config "${configName}" to extend from. Please check that the name of the config is correct. + +The config "${configName}" was referenced from the config file in "${importerName}". + +If you still have problems, please stop by https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/failed-to-read-json.js b/node_modules/eslint/messages/failed-to-read-json.js new file mode 100644 index 00000000..3244e842 --- /dev/null +++ b/node_modules/eslint/messages/failed-to-read-json.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = function (it) { + const { path, message } = it; + + return ` +Failed to read JSON file at ${path}: + +${message} +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/file-not-found.js b/node_modules/eslint/messages/file-not-found.js new file mode 100644 index 00000000..50e483bc --- /dev/null +++ b/node_modules/eslint/messages/file-not-found.js @@ -0,0 +1,10 @@ +"use strict"; + +module.exports = function (it) { + const { pattern, globDisabled } = it; + + return ` +No files matching the pattern "${pattern}"${globDisabled ? " (with disabling globs)" : ""} were found. +Please check for typing mistakes in the pattern. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/invalid-rule-options.js b/node_modules/eslint/messages/invalid-rule-options.js new file mode 100644 index 00000000..05354cb4 --- /dev/null +++ b/node_modules/eslint/messages/invalid-rule-options.js @@ -0,0 +1,17 @@ +"use strict"; + +const { stringifyValueForError } = require("./shared"); + +module.exports = function ({ ruleId, value }) { + return ` +Configuration for rule "${ruleId}" is invalid. Each rule must have a severity ("off", 0, "warn", 1, "error", or 2) and may be followed by additional options for the rule. + +You passed '${stringifyValueForError(value, 4)}', which doesn't contain a valid severity. + +If you're attempting to configure rule options, perhaps you meant: + + "${ruleId}": ["error", ${stringifyValueForError(value, 8)}] + +See https://eslint.org/docs/latest/use/configure/rules#using-configuration-files for configuring rules. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/invalid-rule-severity.js b/node_modules/eslint/messages/invalid-rule-severity.js new file mode 100644 index 00000000..17e9b5d4 --- /dev/null +++ b/node_modules/eslint/messages/invalid-rule-severity.js @@ -0,0 +1,13 @@ +"use strict"; + +const { stringifyValueForError } = require("./shared"); + +module.exports = function ({ ruleId, value }) { + return ` +Configuration for rule "${ruleId}" is invalid. Expected severity of "off", 0, "warn", 1, "error", or 2. + +You passed '${stringifyValueForError(value, 4)}'. + +See https://eslint.org/docs/latest/use/configure/rules#using-configuration-files for configuring rules. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/no-config-found.js b/node_modules/eslint/messages/no-config-found.js new file mode 100644 index 00000000..4421206d --- /dev/null +++ b/node_modules/eslint/messages/no-config-found.js @@ -0,0 +1,15 @@ +"use strict"; + +module.exports = function (it) { + const { directoryPath } = it; + + return ` +ESLint couldn't find a configuration file. To set up a configuration file for this project, please run: + + npm init @eslint/config@latest + +ESLint looked for configuration files in ${directoryPath} and its ancestors. If it found none, it then looked in your home directory. + +If you think you already have a configuration file or if you need more help, please stop by the ESLint Discord server: https://eslint.org/chat +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/plugin-conflict.js b/node_modules/eslint/messages/plugin-conflict.js new file mode 100644 index 00000000..d90df0ca --- /dev/null +++ b/node_modules/eslint/messages/plugin-conflict.js @@ -0,0 +1,22 @@ +"use strict"; + +module.exports = function (it) { + const { pluginId, plugins } = it; + + let result = `ESLint couldn't determine the plugin "${pluginId}" uniquely. +`; + + for (const { filePath, importerName } of plugins) { + result += ` +- ${filePath} (loaded in "${importerName}")`; + } + + result += ` + +Please remove the "plugins" setting from either config or remove either plugin installation. + +If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting. +`; + + return result; +}; diff --git a/node_modules/eslint/messages/plugin-invalid.js b/node_modules/eslint/messages/plugin-invalid.js new file mode 100644 index 00000000..fc9ff6ab --- /dev/null +++ b/node_modules/eslint/messages/plugin-invalid.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function (it) { + const { configName, importerName } = it; + + return ` +"${configName}" is invalid syntax for a config specifier. + +* If your intention is to extend from a configuration exported from the plugin, add the configuration name after a slash: e.g. "${configName}/myConfig". +* If this is the name of a shareable config instead of a plugin, remove the "plugin:" prefix: i.e. "${configName.slice("plugin:".length)}". + +"${configName}" was referenced from the config file in "${importerName}". + +If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/plugin-missing.js b/node_modules/eslint/messages/plugin-missing.js new file mode 100644 index 00000000..6152a6a4 --- /dev/null +++ b/node_modules/eslint/messages/plugin-missing.js @@ -0,0 +1,19 @@ +"use strict"; + +module.exports = function (it) { + const { pluginName, resolvePluginsRelativeTo, importerName } = it; + + return ` +ESLint couldn't find the plugin "${pluginName}". + +(The package "${pluginName}" was not found when loaded as a Node module from the directory "${resolvePluginsRelativeTo}".) + +It's likely that the plugin isn't installed correctly. Try reinstalling by running the following: + + npm install ${pluginName}@latest --save-dev + +The plugin "${pluginName}" was referenced from the config file in "${importerName}". + +If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/print-config-with-directory-path.js b/node_modules/eslint/messages/print-config-with-directory-path.js new file mode 100644 index 00000000..9f37745f --- /dev/null +++ b/node_modules/eslint/messages/print-config-with-directory-path.js @@ -0,0 +1,8 @@ +"use strict"; + +module.exports = function () { + return ` +The '--print-config' CLI option requires a path to a source code file rather than a directory. +See also: https://eslint.org/docs/latest/use/command-line-interface#--print-config +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/shared.js b/node_modules/eslint/messages/shared.js new file mode 100644 index 00000000..4244ed68 --- /dev/null +++ b/node_modules/eslint/messages/shared.js @@ -0,0 +1,23 @@ +/** + * @fileoverview Shared utilities for error messages. + * @author Josh Goldberg + */ + +"use strict"; + +/** + * Converts a value to a string that may be printed in errors. + * @param {any} value The invalid value. + * @param {number} indentation How many spaces to indent + * @returns {string} The value, stringified. + */ +function stringifyValueForError(value, indentation) { + return value + ? JSON.stringify(value, null, 4).replace( + /\n/gu, + `\n${" ".repeat(indentation)}`, + ) + : `${value}`; +} + +module.exports = { stringifyValueForError }; diff --git a/node_modules/eslint/messages/whitespace-found.js b/node_modules/eslint/messages/whitespace-found.js new file mode 100644 index 00000000..c6160216 --- /dev/null +++ b/node_modules/eslint/messages/whitespace-found.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = function (it) { + const { pluginName } = it; + + return ` +ESLint couldn't find the plugin "${pluginName}". because there is whitespace in the name. Please check your configuration and remove all whitespace from the plugin name. + +If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/node_modules/brace-expansion/LICENSE b/node_modules/eslint/node_modules/brace-expansion/LICENSE new file mode 100644 index 00000000..de322667 --- /dev/null +++ b/node_modules/eslint/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/eslint/node_modules/brace-expansion/README.md b/node_modules/eslint/node_modules/brace-expansion/README.md new file mode 100644 index 00000000..6b4e0e16 --- /dev/null +++ b/node_modules/eslint/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/eslint/node_modules/brace-expansion/index.js b/node_modules/eslint/node_modules/brace-expansion/index.js new file mode 100644 index 00000000..bd19fe68 --- /dev/null +++ b/node_modules/eslint/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/eslint/node_modules/brace-expansion/package.json b/node_modules/eslint/node_modules/brace-expansion/package.json new file mode 100644 index 00000000..34478881 --- /dev/null +++ b/node_modules/eslint/node_modules/brace-expansion/package.json @@ -0,0 +1,50 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "1.1.12", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "publishConfig": { + "tag": "1.x" + } +} diff --git a/node_modules/eslint/node_modules/eslint-visitor-keys/LICENSE b/node_modules/eslint/node_modules/eslint-visitor-keys/LICENSE new file mode 100644 index 00000000..17a25538 --- /dev/null +++ b/node_modules/eslint/node_modules/eslint-visitor-keys/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/eslint/node_modules/eslint-visitor-keys/README.md b/node_modules/eslint/node_modules/eslint-visitor-keys/README.md new file mode 100644 index 00000000..aa860ba5 --- /dev/null +++ b/node_modules/eslint/node_modules/eslint-visitor-keys/README.md @@ -0,0 +1,121 @@ +# eslint-visitor-keys + +[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) +[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions) + +Constants and utilities about visitor keys to traverse AST. + +## 💿 Installation + +Use [npm] to install. + +```bash +$ npm install eslint-visitor-keys +``` + +### Requirements + +- [Node.js] `^18.18.0`, `^20.9.0`, or `>=21.1.0` + +## 📖 Usage + +To use in an ESM file: + +```js +import * as evk from "eslint-visitor-keys" +``` + +To use in a CommonJS file: + +```js +const evk = require("eslint-visitor-keys") +``` + +### evk.KEYS + +> type: `{ [type: string]: string[] | undefined }` + +Visitor keys. This keys are frozen. + +This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. + +For example: + +``` +console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] +``` + +### evk.getKeys(node) + +> type: `(node: object) => string[]` + +Get the visitor keys of a given AST node. + +This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. + +This will be used to traverse unknown nodes. + +For example: + +```js +const node = { + type: "AssignmentExpression", + left: { type: "Identifier", name: "foo" }, + right: { type: "Literal", value: 0 } +} +console.log(evk.getKeys(node)) // → ["type", "left", "right"] +``` + +### evk.unionWith(additionalKeys) + +> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` + +Make the union set with `evk.KEYS` and the given keys. + +- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. +- It removes duplicated keys as keeping the first one. + +For example: + +```js +console.log(evk.unionWith({ + MethodDefinition: ["decorators"] +})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } +``` + +## 📰 Change log + +See [GitHub releases](https://github.com/eslint/js/releases). + +## 🍻 Contributing + +Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). + +### Development commands + +- `npm test` runs tests and measures code coverage. +- `npm run lint` checks source codes with ESLint. +- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser. + +[npm]: https://www.npmjs.com/ +[Node.js]: https://nodejs.org/ +[ESTree]: https://github.com/estree/estree + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/eslint/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs b/node_modules/eslint/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs new file mode 100644 index 00000000..afc433c7 --- /dev/null +++ b/node_modules/eslint/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs @@ -0,0 +1,396 @@ +'use strict'; + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source", + "attributes" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source", + "attributes" + ], + ExportSpecifier: [ + "local", + "exported" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportAttribute: [ + "key", + "value" + ], + ImportDeclaration: [ + "specifiers", + "source", + "attributes" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source", + "options" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +function getKeys(node) { + return Object.keys(node).filter(filterKey); +} +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */ + +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +function unionWith(additionalKeys) { + const retv = /** @type {{ [type: string]: ReadonlyArray }} */ + (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.hasOwn(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +exports.KEYS = KEYS; +exports.getKeys = getKeys; +exports.unionWith = unionWith; diff --git a/node_modules/eslint/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts b/node_modules/eslint/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts new file mode 100644 index 00000000..34253c96 --- /dev/null +++ b/node_modules/eslint/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts @@ -0,0 +1,28 @@ +type VisitorKeys$1 = { + readonly [type: string]: ReadonlyArray; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys$1; + +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +declare function getKeys(node: Object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys; + +type VisitorKeys = VisitorKeys$1; + +export { KEYS, getKeys, unionWith }; +export type { VisitorKeys }; diff --git a/node_modules/eslint/node_modules/eslint-visitor-keys/dist/index.d.ts b/node_modules/eslint/node_modules/eslint-visitor-keys/dist/index.d.ts new file mode 100644 index 00000000..e65b7da3 --- /dev/null +++ b/node_modules/eslint/node_modules/eslint-visitor-keys/dist/index.d.ts @@ -0,0 +1,16 @@ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node: Object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys: VisitorKeys): VisitorKeys; +export { KEYS }; +export type VisitorKeys = import("./visitor-keys.js").VisitorKeys; +import KEYS from "./visitor-keys.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/eslint/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts b/node_modules/eslint/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts new file mode 100644 index 00000000..2d7ada2f --- /dev/null +++ b/node_modules/eslint/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts @@ -0,0 +1,12 @@ +export default KEYS; +export type VisitorKeys = { + readonly [type: string]: ReadonlyArray; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys; +//# sourceMappingURL=visitor-keys.d.ts.map \ No newline at end of file diff --git a/node_modules/eslint/node_modules/eslint-visitor-keys/lib/index.js b/node_modules/eslint/node_modules/eslint-visitor-keys/lib/index.js new file mode 100644 index 00000000..1fc89b43 --- /dev/null +++ b/node_modules/eslint/node_modules/eslint-visitor-keys/lib/index.js @@ -0,0 +1,67 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +import KEYS from "./visitor-keys.js"; + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node) { + return Object.keys(node).filter(filterKey); +} +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */ + +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys) { + const retv = /** @type {{ [type: string]: ReadonlyArray }} */ + (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.hasOwn(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +export { KEYS }; diff --git a/node_modules/eslint/node_modules/eslint-visitor-keys/lib/visitor-keys.js b/node_modules/eslint/node_modules/eslint-visitor-keys/lib/visitor-keys.js new file mode 100644 index 00000000..c891e040 --- /dev/null +++ b/node_modules/eslint/node_modules/eslint-visitor-keys/lib/visitor-keys.js @@ -0,0 +1,327 @@ +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source", + "attributes" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source", + "attributes" + ], + ExportSpecifier: [ + "local", + "exported" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportAttribute: [ + "key", + "value" + ], + ImportDeclaration: [ + "specifiers", + "source", + "attributes" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source", + "options" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +export default KEYS; diff --git a/node_modules/eslint/node_modules/eslint-visitor-keys/package.json b/node_modules/eslint/node_modules/eslint-visitor-keys/package.json new file mode 100644 index 00000000..852e4ddb --- /dev/null +++ b/node_modules/eslint/node_modules/eslint-visitor-keys/package.json @@ -0,0 +1,70 @@ +{ + "name": "eslint-visitor-keys", + "version": "4.2.1", + "description": "Constants and utilities about visitor keys to traverse AST.", + "type": "module", + "main": "dist/eslint-visitor-keys.cjs", + "types": "./dist/index.d.ts", + "exports": { + ".": [ + { + "import": "./lib/index.js", + "require": "./dist/eslint-visitor-keys.cjs" + }, + "./dist/eslint-visitor-keys.cjs" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist/index.d.ts", + "dist/visitor-keys.d.ts", + "dist/eslint-visitor-keys.cjs", + "dist/eslint-visitor-keys.d.cts", + "lib" + ], + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "devDependencies": { + "@types/estree": "^0.0.51", + "@types/estree-jsx": "^0.0.1", + "@typescript-eslint/parser": "^8.7.0", + "eslint-release": "^3.2.0", + "esquery": "^1.4.0", + "json-diff": "^0.7.3", + "opener": "^1.5.2", + "rollup": "^4.22.4", + "rollup-plugin-dts": "^6.1.1", + "tsd": "^0.31.2", + "typescript": "^5.6.2" + }, + "scripts": { + "build": "npm run build:cjs && npm run build:types", + "build:cjs": "rollup -c", + "build:debug": "npm run build:cjs -- -m && npm run build:types", + "build:types": "tsc -v && tsc", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "mocha tests/lib/**/*.cjs && c8 mocha tests/lib/**/*.js && npm run test:types", + "test:open-coverage": "c8 report --reporter lcov && opener coverage/lcov-report/index.html", + "test:types": "tsd" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/eslint-visitor-keys" + }, + "funding": "https://opencollective.com/eslint", + "keywords": [ + "eslint" + ], + "author": "Toru Nagashima (https://github.com/mysticatea)", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-visitor-keys/README.md" +} diff --git a/node_modules/eslint/node_modules/fast-deep-equal/LICENSE b/node_modules/eslint/node_modules/fast-deep-equal/LICENSE new file mode 100644 index 00000000..7f154356 --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/eslint/node_modules/fast-deep-equal/README.md b/node_modules/eslint/node_modules/fast-deep-equal/README.md new file mode 100644 index 00000000..d3f4ffcc --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/README.md @@ -0,0 +1,96 @@ +# fast-deep-equal +The fastest deep equal with ES6 Map, Set and Typed arrays support. + +[![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) +[![npm](https://img.shields.io/npm/v/fast-deep-equal.svg)](https://www.npmjs.com/package/fast-deep-equal) +[![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) + + +## Install + +```bash +npm install fast-deep-equal +``` + + +## Features + +- ES5 compatible +- works in node.js (8+) and browsers (IE9+) +- checks equality of Date and RegExp objects by value. + +ES6 equal (`require('fast-deep-equal/es6')`) also supports: +- Maps +- Sets +- Typed arrays + + +## Usage + +```javascript +var equal = require('fast-deep-equal'); +console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true +``` + +To support ES6 Maps, Sets and Typed arrays equality use: + +```javascript +var equal = require('fast-deep-equal/es6'); +console.log(equal(Int16Array([1, 2]), Int16Array([1, 2]))); // true +``` + +To use with React (avoiding the traversal of React elements' _owner +property that contains circular references and is not needed when +comparing the elements - borrowed from [react-fast-compare](https://github.com/FormidableLabs/react-fast-compare)): + +```javascript +var equal = require('fast-deep-equal/react'); +var equal = require('fast-deep-equal/es6/react'); +``` + + +## Performance benchmark + +Node.js v12.6.0: + +``` +fast-deep-equal x 261,950 ops/sec ±0.52% (89 runs sampled) +fast-deep-equal/es6 x 212,991 ops/sec ±0.34% (92 runs sampled) +fast-equals x 230,957 ops/sec ±0.83% (85 runs sampled) +nano-equal x 187,995 ops/sec ±0.53% (88 runs sampled) +shallow-equal-fuzzy x 138,302 ops/sec ±0.49% (90 runs sampled) +underscore.isEqual x 74,423 ops/sec ±0.38% (89 runs sampled) +lodash.isEqual x 36,637 ops/sec ±0.72% (90 runs sampled) +deep-equal x 2,310 ops/sec ±0.37% (90 runs sampled) +deep-eql x 35,312 ops/sec ±0.67% (91 runs sampled) +ramda.equals x 12,054 ops/sec ±0.40% (91 runs sampled) +util.isDeepStrictEqual x 46,440 ops/sec ±0.43% (90 runs sampled) +assert.deepStrictEqual x 456 ops/sec ±0.71% (88 runs sampled) + +The fastest is fast-deep-equal +``` + +To run benchmark (requires node.js 6+): + +```bash +npm run benchmark +``` + +__Please note__: this benchmark runs against the available test cases. To choose the most performant library for your application, it is recommended to benchmark against your data and to NOT expect this benchmark to reflect the performance difference in your application. + + +## Enterprise support + +fast-deep-equal package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-deep-equal?utm_source=npm-fast-deep-equal&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. + + +## Security contact + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. + + +## License + +[MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE) diff --git a/node_modules/eslint/node_modules/fast-deep-equal/es6/index.d.ts b/node_modules/eslint/node_modules/fast-deep-equal/es6/index.d.ts new file mode 100644 index 00000000..c7eb9c79 --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/es6/index.d.ts @@ -0,0 +1,2 @@ +declare const equal: (a: any, b: any) => boolean; +export = equal; diff --git a/node_modules/eslint/node_modules/fast-deep-equal/es6/index.js b/node_modules/eslint/node_modules/fast-deep-equal/es6/index.js new file mode 100644 index 00000000..d980be25 --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/es6/index.js @@ -0,0 +1,72 @@ +'use strict'; + +// do not edit .js files directly - edit src/index.jst + + + var envHasBigInt64Array = typeof BigInt64Array !== 'undefined'; + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + if ((a instanceof Map) && (b instanceof Map)) { + if (a.size !== b.size) return false; + for (i of a.entries()) + if (!b.has(i[0])) return false; + for (i of a.entries()) + if (!equal(i[1], b.get(i[0]))) return false; + return true; + } + + if ((a instanceof Set) && (b instanceof Set)) { + if (a.size !== b.size) return false; + for (i of a.entries()) + if (!b.has(i[0])) return false; + return true; + } + + if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (a[i] !== b[i]) return false; + return true; + } + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; diff --git a/node_modules/eslint/node_modules/fast-deep-equal/es6/react.d.ts b/node_modules/eslint/node_modules/fast-deep-equal/es6/react.d.ts new file mode 100644 index 00000000..c7eb9c79 --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/es6/react.d.ts @@ -0,0 +1,2 @@ +declare const equal: (a: any, b: any) => boolean; +export = equal; diff --git a/node_modules/eslint/node_modules/fast-deep-equal/es6/react.js b/node_modules/eslint/node_modules/fast-deep-equal/es6/react.js new file mode 100644 index 00000000..98e2f9b7 --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/es6/react.js @@ -0,0 +1,79 @@ +'use strict'; + +// do not edit .js files directly - edit src/index.jst + + + var envHasBigInt64Array = typeof BigInt64Array !== 'undefined'; + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + if ((a instanceof Map) && (b instanceof Map)) { + if (a.size !== b.size) return false; + for (i of a.entries()) + if (!b.has(i[0])) return false; + for (i of a.entries()) + if (!equal(i[1], b.get(i[0]))) return false; + return true; + } + + if ((a instanceof Set) && (b instanceof Set)) { + if (a.size !== b.size) return false; + for (i of a.entries()) + if (!b.has(i[0])) return false; + return true; + } + + if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (a[i] !== b[i]) return false; + return true; + } + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (key === '_owner' && a.$$typeof) { + // React-specific: avoid traversing React elements' _owner. + // _owner contains circular references + // and is not needed when comparing the actual elements (and not their owners) + continue; + } + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; diff --git a/node_modules/eslint/node_modules/fast-deep-equal/index.d.ts b/node_modules/eslint/node_modules/fast-deep-equal/index.d.ts new file mode 100644 index 00000000..3c042caa --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/index.d.ts @@ -0,0 +1,4 @@ +declare module 'fast-deep-equal' { + const equal: (a: any, b: any) => boolean; + export = equal; +} diff --git a/node_modules/eslint/node_modules/fast-deep-equal/index.js b/node_modules/eslint/node_modules/fast-deep-equal/index.js new file mode 100644 index 00000000..30dd1ba7 --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/index.js @@ -0,0 +1,46 @@ +'use strict'; + +// do not edit .js files directly - edit src/index.jst + + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; diff --git a/node_modules/eslint/node_modules/fast-deep-equal/package.json b/node_modules/eslint/node_modules/fast-deep-equal/package.json new file mode 100644 index 00000000..3cfe66c6 --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/package.json @@ -0,0 +1,61 @@ +{ + "name": "fast-deep-equal", + "version": "3.1.3", + "description": "Fast deep equal", + "main": "index.js", + "scripts": { + "eslint": "eslint *.js benchmark/*.js spec/*.js", + "build": "node build", + "benchmark": "npm i && npm run build && cd ./benchmark && npm i && node ./", + "test-spec": "mocha spec/*.spec.js -R spec", + "test-cov": "nyc npm run test-spec", + "test-ts": "tsc --target ES5 --noImplicitAny index.d.ts", + "test": "npm run build && npm run eslint && npm run test-ts && npm run test-cov", + "prepublish": "npm run build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/epoberezkin/fast-deep-equal.git" + }, + "keywords": [ + "fast", + "equal", + "deep-equal" + ], + "author": "Evgeny Poberezkin", + "license": "MIT", + "bugs": { + "url": "https://github.com/epoberezkin/fast-deep-equal/issues" + }, + "homepage": "https://github.com/epoberezkin/fast-deep-equal#readme", + "devDependencies": { + "coveralls": "^3.1.0", + "dot": "^1.1.2", + "eslint": "^7.2.0", + "mocha": "^7.2.0", + "nyc": "^15.1.0", + "pre-commit": "^1.2.2", + "react": "^16.12.0", + "react-test-renderer": "^16.12.0", + "sinon": "^9.0.2", + "typescript": "^3.9.5" + }, + "nyc": { + "exclude": [ + "**/spec/**", + "node_modules" + ], + "reporter": [ + "lcov", + "text-summary" + ] + }, + "files": [ + "index.js", + "index.d.ts", + "react.js", + "react.d.ts", + "es6/" + ], + "types": "index.d.ts" +} diff --git a/node_modules/eslint/node_modules/fast-deep-equal/react.d.ts b/node_modules/eslint/node_modules/fast-deep-equal/react.d.ts new file mode 100644 index 00000000..c7eb9c79 --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/react.d.ts @@ -0,0 +1,2 @@ +declare const equal: (a: any, b: any) => boolean; +export = equal; diff --git a/node_modules/eslint/node_modules/fast-deep-equal/react.js b/node_modules/eslint/node_modules/fast-deep-equal/react.js new file mode 100644 index 00000000..3489b983 --- /dev/null +++ b/node_modules/eslint/node_modules/fast-deep-equal/react.js @@ -0,0 +1,53 @@ +'use strict'; + +// do not edit .js files directly - edit src/index.jst + + + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (key === '_owner' && a.$$typeof) { + // React-specific: avoid traversing React elements' _owner. + // _owner contains circular references + // and is not needed when comparing the actual elements (and not their owners) + continue; + } + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; diff --git a/node_modules/eslint/node_modules/ignore/LICENSE-MIT b/node_modules/eslint/node_modules/ignore/LICENSE-MIT new file mode 100644 index 00000000..825533e3 --- /dev/null +++ b/node_modules/eslint/node_modules/ignore/LICENSE-MIT @@ -0,0 +1,21 @@ +Copyright (c) 2013 Kael Zhang , contributors +http://kael.me/ + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/eslint/node_modules/ignore/README.md b/node_modules/eslint/node_modules/ignore/README.md new file mode 100644 index 00000000..50d88822 --- /dev/null +++ b/node_modules/eslint/node_modules/ignore/README.md @@ -0,0 +1,412 @@ + + + + + + + + + + + + + +
LinuxOS XWindowsCoverageDownloads
+ + Build Status + + + Windows Build Status + + + Coverage Status + + + npm module downloads per month +
+ +# ignore + +`ignore` is a manager, filter and parser which implemented in pure JavaScript according to the [.gitignore spec 2.22.1](http://git-scm.com/docs/gitignore). + +`ignore` is used by eslint, gitbook and [many others](https://www.npmjs.com/browse/depended/ignore). + +Pay **ATTENTION** that [`minimatch`](https://www.npmjs.org/package/minimatch) (which used by `fstream-ignore`) does not follow the gitignore spec. + +To filter filenames according to a .gitignore file, I recommend this npm package, `ignore`. + +To parse an `.npmignore` file, you should use `minimatch`, because an `.npmignore` file is parsed by npm using `minimatch` and it does not work in the .gitignore way. + +### Tested on + +`ignore` is fully tested, and has more than **five hundreds** of unit tests. + +- Linux + Node: `0.8` - `7.x` +- Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. + +Actually, `ignore` does not rely on any versions of node specially. + +Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). + +## Table Of Main Contents + +- [Usage](#usage) +- [`Pathname` Conventions](#pathname-conventions) +- See Also: + - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. +- [Upgrade Guide](#upgrade-guide) + +## Install + +```sh +npm i ignore +``` + +## Usage + +```js +import ignore from 'ignore' +const ig = ignore().add(['.abc/*', '!.abc/d/']) +``` + +### Filter the given paths + +```js +const paths = [ + '.abc/a.js', // filtered out + '.abc/d/e.js' // included +] + +ig.filter(paths) // ['.abc/d/e.js'] +ig.ignores('.abc/a.js') // true +``` + +### As the filter function + +```js +paths.filter(ig.createFilter()); // ['.abc/d/e.js'] +``` + +### Win32 paths will be handled + +```js +ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) +// if the code above runs on windows, the result will be +// ['.abc\\d\\e.js'] +``` + +## Why another ignore? + +- `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. + +- `ignore` only contains utility methods to filter paths according to the specified ignore rules, so + - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. + - `ignore` don't cares about sub-modules of git projects. + +- Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: + - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. + - '`**/foo`' should match '`foo`' anywhere. + - Prevent re-including a file if a parent directory of that file is excluded. + - Handle trailing whitespaces: + - `'a '`(one space) should not match `'a '`(two spaces). + - `'a \ '` matches `'a '` + - All test cases are verified with the result of `git check-ignore`. + +# Methods + +## .add(pattern: string | Ignore): this +## .add(patterns: Array): this + +- **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance +- **patterns** `Array` Array of ignore patterns. + +Adds a rule or several rules to the current manager. + +Returns `this` + +Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. + +```js +ignore().add('#abc').ignores('#abc') // false +ignore().add('\\#abc').ignores('#abc') // true +``` + +`pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: + +```js +ignore() +.add(fs.readFileSync(filenameOfGitignore).toString()) +.filter(filenames) +``` + +`pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. + +## .addIgnoreFile(path) + +REMOVED in `3.x` for now. + +To upgrade `ignore@2.x` up to `3.x`, use + +```js +import fs from 'fs' + +if (fs.existsSync(filename)) { + ignore().add(fs.readFileSync(filename).toString()) +} +``` + +instead. + +## .filter(paths: Array<Pathname>): Array<Pathname> + +```ts +type Pathname = string +``` + +Filters the given array of pathnames, and returns the filtered array. + +- **paths** `Array.` The array of `pathname`s to be filtered. + +### `Pathname` Conventions: + +#### 1. `Pathname` should be a `path.relative()`d pathname + +`Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory, + +```js +// WRONG, an error will be thrown +ig.ignores('./abc') + +// WRONG, for it will never happen, and an error will be thrown +// If the gitignore rule locates at the root directory, +// `'/abc'` should be changed to `'abc'`. +// ``` +// path.relative('/', '/abc') -> 'abc' +// ``` +ig.ignores('/abc') + +// WRONG, that it is an absolute path on Windows, an error will be thrown +ig.ignores('C:\\abc') + +// Right +ig.ignores('abc') + +// Right +ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' +``` + +In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. + +Suppose the dir structure is: + +``` +/path/to/your/repo + |-- a + | |-- a.js + | + |-- .b + | + |-- .c + |-- .DS_store +``` + +Then the `paths` might be like this: + +```js +[ + 'a/a.js' + '.b', + '.c/.DS_store' +] +``` + +#### 2. filenames and dirnames + +`node-ignore` does NO `fs.stat` during path matching, so for the example below: + +```js +// First, we add a ignore pattern to ignore a directory +ig.add('config/') + +// `ig` does NOT know if 'config', in the real world, +// is a normal file, directory or something. + +ig.ignores('config') +// `ig` treats `config` as a file, so it returns `false` + +ig.ignores('config/') +// returns `true` +``` + +Specially for people who develop some library based on `node-ignore`, it is important to understand that. + +Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: + +```js +import glob from 'glob' + +glob('**', { + // Adds a / character to directory matches. + mark: true +}, (err, files) => { + if (err) { + return console.error(err) + } + + let filtered = ignore().add(patterns).filter(files) + console.log(filtered) +}) +``` + +## .ignores(pathname: Pathname): boolean + +> new in 3.2.0 + +Returns `Boolean` whether `pathname` should be ignored. + +```js +ig.ignores('.abc/a.js') // true +``` + +## .createFilter() + +Creates a filter function which could filter an array of paths with `Array.prototype.filter`. + +Returns `function(path)` the filter function. + +## .test(pathname: Pathname) since 5.0.0 + +Returns `TestResult` + +```ts +interface TestResult { + ignored: boolean + // true if the `pathname` is finally unignored by some negative pattern + unignored: boolean +} +``` + +- `{ignored: true, unignored: false}`: the `pathname` is ignored +- `{ignored: false, unignored: true}`: the `pathname` is unignored +- `{ignored: false, unignored: false}`: the `pathname` is never matched by any ignore rules. + +## static `ignore.isPathValid(pathname): boolean` since 5.0.0 + +Check whether the `pathname` is an valid `path.relative()`d path according to the [convention](#1-pathname-should-be-a-pathrelatived-pathname). + +This method is **NOT** used to check if an ignore pattern is valid. + +```js +ignore.isPathValid('./foo') // false +``` + +## ignore(options) + +### `options.ignorecase` since 4.0.0 + +Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (the default value), otherwise case sensitive. + +```js +const ig = ignore({ + ignorecase: false +}) + +ig.add('*.png') + +ig.ignores('*.PNG') // false +``` + +### `options.ignoreCase?: boolean` since 5.2.0 + +Which is alternative to `options.ignoreCase` + +### `options.allowRelativePaths?: boolean` since 5.2.0 + +This option brings backward compatibility with projects which based on `ignore@4.x`. If `options.allowRelativePaths` is `true`, `ignore` will not check whether the given path to be tested is [`path.relative()`d](#pathname-conventions). + +However, passing a relative path, such as `'./foo'` or `'../foo'`, to test if it is ignored or not is not a good practise, which might lead to unexpected behavior + +```js +ignore({ + allowRelativePaths: true +}).ignores('../foo/bar.js') // And it will not throw +``` + +**** + +# Upgrade Guide + +## Upgrade 4.x -> 5.x + +Since `5.0.0`, if an invalid `Pathname` passed into `ig.ignores()`, an error will be thrown, unless `options.allowRelative = true` is passed to the `Ignore` factory. + +While `ignore < 5.0.0` did not make sure what the return value was, as well as + +```ts +.ignores(pathname: Pathname): boolean + +.filter(pathnames: Array): Array + +.createFilter(): (pathname: Pathname) => boolean + +.test(pathname: Pathname): {ignored: boolean, unignored: boolean} +``` + +See the convention [here](#1-pathname-should-be-a-pathrelatived-pathname) for details. + +If there are invalid pathnames, the conversion and filtration should be done by users. + +```js +import {isPathValid} from 'ignore' // introduced in 5.0.0 + +const paths = [ + // invalid + ////////////////// + '', + false, + '../foo', + '.', + ////////////////// + + // valid + 'foo' +] +.filter(isValidPath) + +ig.filter(paths) +``` + +## Upgrade 3.x -> 4.x + +Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: + +```js +var ignore = require('ignore/legacy') +``` + +## Upgrade 2.x -> 3.x + +- All `options` of 2.x are unnecessary and removed, so just remove them. +- `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. +- `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. + +**** + +# Collaborators + +- [@whitecolor](https://github.com/whitecolor) *Alex* +- [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* +- [@azproduction](https://github.com/azproduction) *Mikhail Davydov* +- [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* +- [@JanMattner](https://github.com/JanMattner) *Jan Mattner* +- [@ntwb](https://github.com/ntwb) *Stephen Edgar* +- [@kasperisager](https://github.com/kasperisager) *Kasper Isager* +- [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* diff --git a/node_modules/eslint/node_modules/ignore/index.d.ts b/node_modules/eslint/node_modules/ignore/index.d.ts new file mode 100644 index 00000000..970631e2 --- /dev/null +++ b/node_modules/eslint/node_modules/ignore/index.d.ts @@ -0,0 +1,61 @@ +type Pathname = string + +interface TestResult { + ignored: boolean + unignored: boolean +} + +export interface Ignore { + /** + * Adds one or several rules to the current manager. + * @param {string[]} patterns + * @returns IgnoreBase + */ + add(patterns: string | Ignore | readonly (string | Ignore)[]): this + + /** + * Filters the given array of pathnames, and returns the filtered array. + * NOTICE that each path here should be a relative path to the root of your repository. + * @param paths the array of paths to be filtered. + * @returns The filtered array of paths + */ + filter(pathnames: readonly Pathname[]): Pathname[] + + /** + * Creates a filter function which could filter + * an array of paths with Array.prototype.filter. + */ + createFilter(): (pathname: Pathname) => boolean + + /** + * Returns Boolean whether pathname should be ignored. + * @param {string} pathname a path to check + * @returns boolean + */ + ignores(pathname: Pathname): boolean + + /** + * Returns whether pathname should be ignored or unignored + * @param {string} pathname a path to check + * @returns TestResult + */ + test(pathname: Pathname): TestResult +} + +export interface Options { + ignorecase?: boolean + // For compatibility + ignoreCase?: boolean + allowRelativePaths?: boolean +} + +/** + * Creates new ignore manager. + */ +declare function ignore(options?: Options): Ignore + +declare namespace ignore { + export function isPathValid (pathname: string): boolean +} + +export default ignore diff --git a/node_modules/eslint/node_modules/ignore/index.js b/node_modules/eslint/node_modules/ignore/index.js new file mode 100644 index 00000000..9f0dbfeb --- /dev/null +++ b/node_modules/eslint/node_modules/ignore/index.js @@ -0,0 +1,636 @@ +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} + +const EMPTY = '' +const SPACE = ' ' +const ESCAPE = '\\' +const REGEX_TEST_BLANK_LINE = /^\s+$/ +const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/ +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ +const REGEX_SPLITALL_CRLF = /\r?\n/g +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ + +const SLASH = '/' + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +let TMP_KEY_IGNORE = 'node-ignore' +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol.for('node-ignore') +} +const KEY_IGNORE = TMP_KEY_IGNORE + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}) + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g + +const RETURN_FALSE = () => false + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY +) + +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes + return slashes.slice(0, length - length % 2) +} + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ + + [ + // remove BOM + // TODO: + // Other similar zero-width characters? + /^\uFEFF/, + () => EMPTY + ], + + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a ) -> (a) + // (a \ ) -> (a ) + /((?:\\\\)*?)(\\?\s+)$/, + (_, m1, m2) => m1 + ( + m2.indexOf('\\') === 0 + ? SPACE + : EMPTY + ) + ], + + // replace (\ ) with ' ' + // (\ ) -> ' ' + // (\\ ) -> '\\ ' + // (\\\ ) -> '\\ ' + [ + /(\\+?)\s/g, + (_, m1) => { + const {length} = m1 + return m1.slice(0, length - length % 2) + SPACE + } + ], + + // Escape metacharacters + // which is written down by users but means special for regular expressions. + + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + match => `\\${match}` + ], + + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], + + // leading slash + [ + + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], + + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], + + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], + + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], + + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, + + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer + + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], + + // normal intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' + + // 'abc.*/' -> go + // 'abc.*' -> skip this rule, + // coz trailing single wildcard will be handed by [trailing wildcard] + /(^|[^\\]+)(\\\*)+(?=.+)/g, + + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1, p2) => { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + const unescaped = p2.replace(/\\\*/g, '[^\\/]*') + return p1 + unescaped + } + ], + + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], + + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], + + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. + + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` + : close === ']' + ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? `[${sanitizeRange(range)}${endEscape}]` + // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' + : '[]' + ], + + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, + + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' + + return `${prefix}(?=$|\\/$)` + } + ], +] + +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null) + +// @param {pattern} +const makeRegex = (pattern, ignoreCase) => { + let source = regexCache[pattern] + + if (!source) { + source = REPLACERS.reduce( + (prev, [matcher, replacer]) => + prev.replace(matcher, replacer.bind(pattern)), + pattern + ) + regexCache[pattern] = source + } + + return ignoreCase + ? new RegExp(source, 'i') + : new RegExp(source) +} + +const isString = subject => typeof subject === 'string' + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0 + +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) + +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin + this.pattern = pattern + this.negative = negative + this.regex = regex + } +} + +const createRule = (pattern, ignoreCase) => { + const origin = pattern + let negative = false + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true + pattern = pattern.substr(1) + } + + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') + + const regex = makeRegex(pattern, ignoreCase) + + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +} + +const throwError = (message, Ctor) => { + throw new Ctor(message) +} + +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d' + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + + return true +} + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + +checkPath.isNotRelative = isNotRelative +checkPath.convert = p => p + +class Ignore { + constructor ({ + ignorecase = true, + ignoreCase = ignorecase, + allowRelativePaths = false + } = {}) { + define(this, KEY_IGNORE, true) + + this._rules = [] + this._ignoreCase = ignoreCase + this._allowRelativePaths = allowRelativePaths + this._initCache() + } + + _initCache () { + this._ignoreCache = Object.create(null) + this._testCache = Object.create(null) + } + + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules) + this._added = true + return + } + + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignoreCase) + this._added = true + this._rules.push(rule) + } + } + + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false + + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this) + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache() + } + + return this + } + + // legacy + addPattern (pattern) { + return this.add(pattern) + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false + let unignored = false + + this._rules.forEach(rule => { + const {negative} = rule + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } + + const matched = rule.regex.test(path) + + if (matched) { + ignored = !negative + unignored = negative + } + }) + + return { + ignored, + unignored + } + } + + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath) + + checkPath( + path, + originalPath, + this._allowRelativePaths + ? RETURN_FALSE + : throwError + ) + + return this._t(path, cache, checkUnignored, slices) + } + + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH) + } + + slices.pop() + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ) + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } + + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + + createFilter () { + return path => !this.ignores(path) + } + + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } + + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} + +const factory = options => new Ignore(options) + +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, RETURN_FALSE) + +factory.isPathValid = isPathValid + +// Fixes typescript +factory.default = factory + +module.exports = factory + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/') + + checkPath.convert = makePosix + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path) +} diff --git a/node_modules/eslint/node_modules/ignore/legacy.js b/node_modules/eslint/node_modules/ignore/legacy.js new file mode 100644 index 00000000..de3f66ce --- /dev/null +++ b/node_modules/eslint/node_modules/ignore/legacy.js @@ -0,0 +1,559 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +// A simple implementation of make-array +function makeArray(subject) { + return Array.isArray(subject) ? subject : [subject]; +} +var EMPTY = ''; +var SPACE = ' '; +var ESCAPE = '\\'; +var REGEX_TEST_BLANK_LINE = /^\s+$/; +var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/; +var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; +var REGEX_SPLITALL_CRLF = /\r?\n/g; +// /foo, +// ./foo, +// ../foo, +// . +// .. +var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; +var SLASH = '/'; + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +var TMP_KEY_IGNORE = 'node-ignore'; +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol["for"]('node-ignore'); +} +var KEY_IGNORE = TMP_KEY_IGNORE; +var define = function define(object, key, value) { + return Object.defineProperty(object, key, { + value: value + }); +}; +var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; +var RETURN_FALSE = function RETURN_FALSE() { + return false; +}; + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +var sanitizeRange = function sanitizeRange(range) { + return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) { + return from.charCodeAt(0) <= to.charCodeAt(0) ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY; + }); +}; + +// See fixtures #59 +var cleanRangeBackSlash = function cleanRangeBackSlash(slashes) { + var length = slashes.length; + return slashes.slice(0, length - length % 2); +}; + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +var REPLACERS = [[ +// remove BOM +// TODO: +// Other similar zero-width characters? +/^\uFEFF/, function () { + return EMPTY; +}], +// > Trailing spaces are ignored unless they are quoted with backslash ("\") +[ +// (a\ ) -> (a ) +// (a ) -> (a) +// (a ) -> (a) +// (a \ ) -> (a ) +/((?:\\\\)*?)(\\?\s+)$/, function (_, m1, m2) { + return m1 + (m2.indexOf('\\') === 0 ? SPACE : EMPTY); +}], +// replace (\ ) with ' ' +// (\ ) -> ' ' +// (\\ ) -> '\\ ' +// (\\\ ) -> '\\ ' +[/(\\+?)\s/g, function (_, m1) { + var length = m1.length; + return m1.slice(0, length - length % 2) + SPACE; +}], +// Escape metacharacters +// which is written down by users but means special for regular expressions. + +// > There are 12 characters with special meanings: +// > - the backslash \, +// > - the caret ^, +// > - the dollar sign $, +// > - the period or dot ., +// > - the vertical bar or pipe symbol |, +// > - the question mark ?, +// > - the asterisk or star *, +// > - the plus sign +, +// > - the opening parenthesis (, +// > - the closing parenthesis ), +// > - and the opening square bracket [, +// > - the opening curly brace {, +// > These special characters are often called "metacharacters". +[/[\\$.|*+(){^]/g, function (match) { + return "\\".concat(match); +}], [ +// > a question mark (?) matches a single character +/(?!\\)\?/g, function () { + return '[^/]'; +}], +// leading slash +[ +// > A leading slash matches the beginning of the pathname. +// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". +// A leading slash matches the beginning of the pathname +/^\//, function () { + return '^'; +}], +// replace special metacharacter slash after the leading slash +[/\//g, function () { + return '\\/'; +}], [ +// > A leading "**" followed by a slash means match in all directories. +// > For example, "**/foo" matches file or directory "foo" anywhere, +// > the same as pattern "foo". +// > "**/foo/bar" matches file or directory "bar" anywhere that is directly +// > under directory "foo". +// Notice that the '*'s have been replaced as '\\*' +/^\^*\\\*\\\*\\\//, +// '**/foo' <-> 'foo' +function () { + return '^(?:.*\\/)?'; +}], +// starting +[ +// there will be no leading '/' +// (which has been replaced by section "leading slash") +// If starts with '**', adding a '^' to the regular expression also works +/^(?=[^^])/, function startingReplacer() { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^'; +}], +// two globstars +[ +// Use lookahead assertions so that we could match more than one `'/**'` +/\\\/\\\*\\\*(?=\\\/|$)/g, +// Zero, one or several directories +// should not use '*', or it will be replaced by the next replacer + +// Check if it is not the last `'/**'` +function (_, index, str) { + return index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+'; +}], +// normal intermediate wildcards +[ +// Never replace escaped '*' +// ignore rule '\*' will match the path '*' + +// 'abc.*/' -> go +// 'abc.*' -> skip this rule, +// coz trailing single wildcard will be handed by [trailing wildcard] +/(^|[^\\]+)(\\\*)+(?=.+)/g, +// '*.js' matches '.js' +// '*.js' doesn't match 'abc' +function (_, p1, p2) { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + var unescaped = p2.replace(/\\\*/g, '[^\\/]*'); + return p1 + unescaped; +}], [ +// unescape, revert step 3 except for back slash +// For example, if a user escape a '\\*', +// after step 3, the result will be '\\\\\\*' +/\\\\\\(?=[$.|*+(){^])/g, function () { + return ESCAPE; +}], [ +// '\\\\' -> '\\' +/\\\\/g, function () { + return ESCAPE; +}], [ +// > The range notation, e.g. [a-zA-Z], +// > can be used to match one of the characters in a range. + +// `\` is escaped by step 3 +/(\\)?\[([^\]/]*?)(\\*)($|\])/g, function (match, leadEscape, range, endEscape, close) { + return leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? "\\[".concat(range).concat(cleanRangeBackSlash(endEscape)).concat(close) : close === ']' ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? "[".concat(sanitizeRange(range)).concat(endEscape, "]") // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' : '[]'; +}], +// ending +[ +// 'js' will not match 'js.' +// 'ab' will not match 'abc' +/(?:[^*])$/, +// WTF! +// https://git-scm.com/docs/gitignore +// changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) +// which re-fixes #24, #38 + +// > If there is a separator at the end of the pattern then the pattern +// > will only match directories, otherwise the pattern can match both +// > files and directories. + +// 'js*' will not match 'a.js' +// 'js/' will not match 'a.js' +// 'js' will match 'a.js' and 'a.js/' +function (match) { + return /\/$/.test(match) + // foo/ will not match 'foo' + ? "".concat(match, "$") // foo matches 'foo' and 'foo/' + : "".concat(match, "(?=$|\\/$)"); +}], +// trailing wildcard +[/(\^|\\\/)?\\\*$/, function (_, p1) { + var prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? "".concat(p1, "[^/]+") // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + return "".concat(prefix, "(?=$|\\/$)"); +}]]; + +// A simple cache, because an ignore rule only has only one certain meaning +var regexCache = Object.create(null); + +// @param {pattern} +var makeRegex = function makeRegex(pattern, ignoreCase) { + var source = regexCache[pattern]; + if (!source) { + source = REPLACERS.reduce(function (prev, _ref) { + var _ref2 = _slicedToArray(_ref, 2), + matcher = _ref2[0], + replacer = _ref2[1]; + return prev.replace(matcher, replacer.bind(pattern)); + }, pattern); + regexCache[pattern] = source; + } + return ignoreCase ? new RegExp(source, 'i') : new RegExp(source); +}; +var isString = function isString(subject) { + return typeof subject === 'string'; +}; + +// > A blank line matches no files, so it can serve as a separator for readability. +var checkPattern = function checkPattern(pattern) { + return pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0; +}; +var splitPattern = function splitPattern(pattern) { + return pattern.split(REGEX_SPLITALL_CRLF); +}; +var IgnoreRule = /*#__PURE__*/_createClass(function IgnoreRule(origin, pattern, negative, regex) { + _classCallCheck(this, IgnoreRule); + this.origin = origin; + this.pattern = pattern; + this.negative = negative; + this.regex = regex; +}); +var createRule = function createRule(pattern, ignoreCase) { + var origin = pattern; + var negative = false; + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); + var regex = makeRegex(pattern, ignoreCase); + return new IgnoreRule(origin, pattern, negative, regex); +}; +var throwError = function throwError(message, Ctor) { + throw new Ctor(message); +}; +var checkPath = function checkPath(path, originalPath, doThrow) { + if (!isString(path)) { + return doThrow("path must be a string, but got `".concat(originalPath, "`"), TypeError); + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow("path must not be empty", TypeError); + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + var r = '`path.relative()`d'; + return doThrow("path should be a ".concat(r, " string, but got \"").concat(originalPath, "\""), RangeError); + } + return true; +}; +var isNotRelative = function isNotRelative(path) { + return REGEX_TEST_INVALID_PATH.test(path); +}; +checkPath.isNotRelative = isNotRelative; +checkPath.convert = function (p) { + return p; +}; +var Ignore = /*#__PURE__*/function () { + function Ignore() { + var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref3$ignorecase = _ref3.ignorecase, + ignorecase = _ref3$ignorecase === void 0 ? true : _ref3$ignorecase, + _ref3$ignoreCase = _ref3.ignoreCase, + ignoreCase = _ref3$ignoreCase === void 0 ? ignorecase : _ref3$ignoreCase, + _ref3$allowRelativePa = _ref3.allowRelativePaths, + allowRelativePaths = _ref3$allowRelativePa === void 0 ? false : _ref3$allowRelativePa; + _classCallCheck(this, Ignore); + define(this, KEY_IGNORE, true); + this._rules = []; + this._ignoreCase = ignoreCase; + this._allowRelativePaths = allowRelativePaths; + this._initCache(); + } + _createClass(Ignore, [{ + key: "_initCache", + value: function _initCache() { + this._ignoreCache = Object.create(null); + this._testCache = Object.create(null); + } + }, { + key: "_addPattern", + value: function _addPattern(pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } + if (checkPattern(pattern)) { + var rule = createRule(pattern, this._ignoreCase); + this._added = true; + this._rules.push(rule); + } + } + + // @param {Array | string | Ignore} pattern + }, { + key: "add", + value: function add(pattern) { + this._added = false; + makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache(); + } + return this; + } + + // legacy + }, { + key: "addPattern", + value: function addPattern(pattern) { + return this.add(pattern); + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + }, { + key: "_testOne", + value: function _testOne(path, checkUnignored) { + var ignored = false; + var unignored = false; + this._rules.forEach(function (rule) { + var negative = rule.negative; + if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) { + return; + } + var matched = rule.regex.test(path); + if (matched) { + ignored = !negative; + unignored = negative; + } + }); + return { + ignored: ignored, + unignored: unignored + }; + } + + // @returns {TestResult} + }, { + key: "_test", + value: function _test(originalPath, cache, checkUnignored, slices) { + var path = originalPath + // Supports nullable path + && checkPath.convert(originalPath); + checkPath(path, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError); + return this._t(path, cache, checkUnignored, slices); + } + }, { + key: "_t", + value: function _t(path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path]; + } + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH); + } + slices.pop(); + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored); + } + var parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices); + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent : this._testOne(path, checkUnignored); + } + }, { + key: "ignores", + value: function ignores(path) { + return this._test(path, this._ignoreCache, false).ignored; + } + }, { + key: "createFilter", + value: function createFilter() { + var _this = this; + return function (path) { + return !_this.ignores(path); + }; + } + }, { + key: "filter", + value: function filter(paths) { + return makeArray(paths).filter(this.createFilter()); + } + + // @returns {TestResult} + }, { + key: "test", + value: function test(path) { + return this._test(path, this._testCache, true); + } + }]); + return Ignore; +}(); +var factory = function factory(options) { + return new Ignore(options); +}; +var isPathValid = function isPathValid(path) { + return checkPath(path && checkPath.convert(path), path, RETURN_FALSE); +}; +factory.isPathValid = isPathValid; + +// Fixes typescript +factory["default"] = factory; +module.exports = factory; + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( +// Detect `process` so that it can run in browsers. +typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) { + /* eslint no-control-regex: "off" */ + var makePosix = function makePosix(str) { + return /^\\\\\?\\/.test(str) || /[\0-\x1F"<>\|]+/.test(str) ? str : str.replace(/\\/g, '/'); + }; + checkPath.convert = makePosix; + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + var REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + checkPath.isNotRelative = function (path) { + return REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path); + }; +} diff --git a/node_modules/eslint/node_modules/ignore/package.json b/node_modules/eslint/node_modules/ignore/package.json new file mode 100644 index 00000000..b7f684e9 --- /dev/null +++ b/node_modules/eslint/node_modules/ignore/package.json @@ -0,0 +1,74 @@ +{ + "name": "ignore", + "version": "5.3.2", + "description": "Ignore is a manager and filter for .gitignore rules, the one used by eslint, gitbook and many others.", + "files": [ + "legacy.js", + "index.js", + "index.d.ts", + "LICENSE-MIT" + ], + "scripts": { + "prepublishOnly": "npm run build", + "build": "babel -o legacy.js index.js", + "test:lint": "eslint .", + "test:tsc": "tsc ./test/ts/simple.ts --lib ES6", + "test:ts": "node ./test/ts/simple.js", + "tap": "tap --reporter classic", + "test:git": "npm run tap test/git-check-ignore.js", + "test:ignore": "npm run tap test/ignore.js", + "test:ignore:only": "IGNORE_ONLY_IGNORES=1 npm run tap test/ignore.js", + "test:others": "npm run tap test/others.js", + "test:cases": "npm run tap test/*.js -- --coverage", + "test:no-coverage": "npm run tap test/*.js -- --no-check-coverage", + "test:only": "npm run test:lint && npm run test:tsc && npm run test:ts && npm run test:cases", + "test": "npm run test:only", + "test:win32": "IGNORE_TEST_WIN32=1 npm run test", + "report": "tap --coverage-report=html", + "posttest": "npm run report && codecov" + }, + "repository": { + "type": "git", + "url": "git@github.com:kaelzhang/node-ignore.git" + }, + "keywords": [ + "ignore", + ".gitignore", + "gitignore", + "npmignore", + "rules", + "manager", + "filter", + "regexp", + "regex", + "fnmatch", + "glob", + "asterisks", + "regular-expression" + ], + "author": "kael", + "license": "MIT", + "bugs": { + "url": "https://github.com/kaelzhang/node-ignore/issues" + }, + "devDependencies": { + "@babel/cli": "^7.22.9", + "@babel/core": "^7.22.9", + "@babel/preset-env": "^7.22.9", + "codecov": "^3.8.2", + "debug": "^4.3.4", + "eslint": "^8.46.0", + "eslint-config-ostai": "^3.0.0", + "eslint-plugin-import": "^2.28.0", + "mkdirp": "^3.0.1", + "pre-suf": "^1.1.1", + "rimraf": "^6.0.1", + "spawn-sync": "^2.0.0", + "tap": "^16.3.9", + "tmp": "0.2.3", + "typescript": "^5.1.6" + }, + "engines": { + "node": ">= 4" + } +} diff --git a/node_modules/eslint/node_modules/minimatch/LICENSE b/node_modules/eslint/node_modules/minimatch/LICENSE new file mode 100644 index 00000000..19129e31 --- /dev/null +++ b/node_modules/eslint/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/eslint/node_modules/minimatch/README.md b/node_modules/eslint/node_modules/minimatch/README.md new file mode 100644 index 00000000..33ede1d6 --- /dev/null +++ b/node_modules/eslint/node_modules/minimatch/README.md @@ -0,0 +1,230 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` + +### allowWindowsEscape + +Windows path separator `\` is by default converted to `/`, which +prohibits the usage of `\` as a escape character. This flag skips that +behavior and allows using the escape character. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/eslint/node_modules/minimatch/minimatch.js b/node_modules/eslint/node_modules/minimatch/minimatch.js new file mode 100644 index 00000000..fda45ade --- /dev/null +++ b/node_modules/eslint/node_modules/minimatch/minimatch.js @@ -0,0 +1,947 @@ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = (function () { try { return require('path') } catch (e) {}}()) || { + sep: '/' +} +minimatch.sep = path.sep + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + b = b || {} + var t = {} + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch + } + + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) + } + + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + } + + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) + } + + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } + + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + assertValidPattern(pattern) + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + assertValidPattern(pattern) + + if (!options) options = {} + + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + assertValidPattern(pattern) + + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } + + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + assertValidPattern(pattern) + + var options = this.options + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + /* istanbul ignore next */ + case '/': { + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + } + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '[': case '.': case '(': addPatternStart = true + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] + + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') partial = this.partial + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} diff --git a/node_modules/eslint/node_modules/minimatch/package.json b/node_modules/eslint/node_modules/minimatch/package.json new file mode 100644 index 00000000..566efdfe --- /dev/null +++ b/node_modules/eslint/node_modules/minimatch/package.json @@ -0,0 +1,33 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "3.1.2", + "publishConfig": { + "tag": "v3-legacy" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "devDependencies": { + "tap": "^15.1.6" + }, + "license": "ISC", + "files": [ + "minimatch.js" + ] +} diff --git a/node_modules/eslint/package.json b/node_modules/eslint/package.json new file mode 100644 index 00000000..e5dfbb2d --- /dev/null +++ b/node_modules/eslint/package.json @@ -0,0 +1,226 @@ +{ + "name": "eslint", + "version": "9.29.0", + "author": "Nicholas C. Zakas ", + "description": "An AST-based pattern checker for JavaScript.", + "type": "commonjs", + "bin": { + "eslint": "./bin/eslint.js" + }, + "main": "./lib/api.js", + "types": "./lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/api.js" + }, + "./config": { + "types": "./lib/types/config-api.d.ts", + "default": "./lib/config-api.js" + }, + "./package.json": "./package.json", + "./use-at-your-own-risk": { + "types": "./lib/types/use-at-your-own-risk.d.ts", + "default": "./lib/unsupported-api.js" + }, + "./rules": { + "types": "./lib/types/rules.d.ts" + }, + "./universal": { + "types": "./lib/types/universal.d.ts", + "default": "./lib/universal.js" + } + }, + "typesVersions": { + "*": { + "use-at-your-own-risk": [ + "./lib/types/use-at-your-own-risk.d.ts" + ], + "rules": [ + "./lib/types/rules.d.ts" + ], + "universal": [ + "./lib/types/universal.d.ts" + ], + "config": [ + "./lib/types/config-api.d.ts" + ] + } + }, + "scripts": { + "build:docs:update-links": "node tools/fetch-docs-links.js", + "build:site": "node Makefile.js gensite", + "build:webpack": "node Makefile.js webpack", + "build:readme": "node tools/update-readme.js", + "build:rules-index": "node Makefile.js generateRuleIndexPage", + "lint": "trunk check --no-fix --ignore=docs/**/*.js -a --filter=eslint && trunk check --no-fix --ignore=docs/**/*.js", + "lint:docs:js": "trunk check --no-fix --ignore=** --ignore=!docs/**/*.js -a --filter=eslint && trunk check --no-fix --ignore=** --ignore=!docs/**/*.js", + "lint:docs:rule-examples": "node Makefile.js checkRuleExamples", + "lint:unused": "knip", + "lint:fix": "trunk check -y --ignore=docs/**/*.js -a --filter=eslint && trunk check -y --ignore=docs/**/*.js", + "lint:fix:docs:js": "trunk check -y --ignore=** --ignore=!docs/**/*.js -a --filter=eslint && trunk check -y --ignore=** --ignore=!docs/**/*.js", + "lint:rule-types": "node tools/update-rule-type-headers.js --check", + "lint:types": "attw --pack", + "release:generate:alpha": "node Makefile.js generatePrerelease -- alpha", + "release:generate:beta": "node Makefile.js generatePrerelease -- beta", + "release:generate:latest": "node Makefile.js generateRelease -- latest", + "release:generate:maintenance": "node Makefile.js generateRelease -- maintenance", + "release:generate:rc": "node Makefile.js generatePrerelease -- rc", + "release:publish": "node Makefile.js publishRelease", + "test": "node Makefile.js test", + "test:browser": "node Makefile.js cypress", + "test:cli": "mocha", + "test:fuzz": "node Makefile.js fuzz", + "test:performance": "node Makefile.js perf", + "test:emfile": "node tools/check-emfile-handling.js", + "test:types": "tsc -p tests/lib/types/tsconfig.json" + }, + "gitHooks": { + "pre-commit": "lint-staged" + }, + "lint-staged": { + "*": "trunk check --fix", + "lib/rules/*.js": [ + "node tools/update-eslint-all.js", + "node tools/update-rule-type-headers.js", + "git add packages/js/src/configs/eslint-all.js lib/types/rules.d.ts" + ], + "docs/src/rules/*.md": [ + "node tools/check-rule-examples.js", + "node tools/fetch-docs-links.js", + "git add docs/src/_data/further_reading_links.json" + ] + }, + "files": [ + "LICENSE", + "README.md", + "bin", + "conf", + "lib", + "messages" + ], + "repository": "eslint/eslint", + "funding": "https://eslint.org/donate", + "homepage": "https://eslint.org", + "bugs": "https://github.com/eslint/eslint/issues/", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.20.1", + "@eslint/config-helpers": "^0.2.1", + "@eslint/core": "^0.14.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.29.0", + "@eslint/plugin-kit": "^0.3.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "@types/json-schema": "^7.0.15", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.18.0", + "@babel/core": "^7.4.3", + "@babel/preset-env": "^7.4.3", + "@cypress/webpack-preprocessor": "^6.0.2", + "@eslint/json": "^0.12.0", + "@trunkio/launcher": "^1.3.4", + "@types/esquery": "^1.5.4", + "@types/node": "^22.13.14", + "@typescript-eslint/parser": "^8.4.0", + "babel-loader": "^8.0.5", + "c8": "^7.12.0", + "chai": "^4.0.1", + "cheerio": "^0.22.0", + "common-tags": "^1.8.0", + "core-js": "^3.1.3", + "cypress": "^14.1.0", + "ejs": "^3.0.2", + "eslint": "file:.", + "eslint-config-eslint": "file:packages/eslint-config-eslint", + "eslint-plugin-eslint-plugin": "^6.0.0", + "eslint-plugin-expect-type": "^0.6.0", + "eslint-plugin-yml": "^1.14.0", + "eslint-release": "^3.3.0", + "eslint-rule-composer": "^0.3.0", + "eslump": "^3.0.0", + "esprima": "^4.0.1", + "fast-glob": "^3.2.11", + "fs-teardown": "^0.1.3", + "glob": "^10.0.0", + "globals": "^16.2.0", + "got": "^11.8.3", + "gray-matter": "^4.0.3", + "jiti": "^2.2.0", + "jiti-v2.0": "npm:jiti@2.0.x", + "jiti-v2.1": "npm:jiti@2.1.x", + "knip": "^5.60.2", + "lint-staged": "^11.0.0", + "load-perf": "^0.2.0", + "markdown-it": "^12.2.0", + "markdown-it-container": "^3.0.0", + "marked": "^4.0.8", + "metascraper": "^5.25.7", + "metascraper-description": "^5.25.7", + "metascraper-image": "^5.29.3", + "metascraper-logo": "^5.25.7", + "metascraper-logo-favicon": "^5.25.7", + "metascraper-title": "^5.25.7", + "mocha": "^10.7.3", + "node-polyfill-webpack-plugin": "^1.0.3", + "npm-license": "^0.3.3", + "pirates": "^4.0.5", + "progress": "^2.0.3", + "proxyquire": "^2.0.1", + "recast": "^0.23.0", + "regenerator-runtime": "^0.14.0", + "semver": "^7.5.3", + "shelljs": "^0.10.0", + "sinon": "^11.0.0", + "typescript": "^5.3.3", + "webpack": "^5.23.0", + "webpack-cli": "^4.5.0", + "yorkie": "^2.0.0" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + }, + "keywords": [ + "ast", + "lint", + "javascript", + "ecmascript", + "espree" + ], + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/node_modules/espree/LICENSE b/node_modules/espree/LICENSE new file mode 100644 index 00000000..b18469ff --- /dev/null +++ b/node_modules/espree/LICENSE @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) Open JS Foundation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/espree/README.md b/node_modules/espree/README.md new file mode 100644 index 00000000..e8e73ee5 --- /dev/null +++ b/node_modules/espree/README.md @@ -0,0 +1,262 @@ +[![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree) +[![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/js/espree/actions) +[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE) + +# Espree + +Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima. + +## Usage + +Install: + +``` +npm i espree +``` + +To use in an ESM file: + +```js +import * as espree from "espree"; + +const ast = espree.parse(code); +``` + +To use in a Common JS file: + +```js +const espree = require("espree"); + +const ast = espree.parse(code); +``` + +## API + +### `parse()` + +`parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters. + +- `code` [string]() - the code which needs to be parsed. +- `options (Optional)` [Object]() - read more about this [here](#options). + +```js +import * as espree from "espree"; + +const ast = espree.parse(code); +``` + +**Example :** + +```js +const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 }); +console.log(ast); +``` + +
Output +

+ +``` +Node { + type: 'Program', + start: 0, + end: 15, + body: [ + Node { + type: 'VariableDeclaration', + start: 0, + end: 15, + declarations: [Array], + kind: 'let' + } + ], + sourceType: 'script' +} +``` + +

+
+ +### `tokenize()` + +`tokenize` returns the tokens of a given code. It takes two parameters. + +- `code` [string]() - the code which needs to be parsed. +- `options (Optional)` [Object]() - read more about this [here](#options). + +Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array + +**Example :** + +```js +import * as espree from "espree"; + +const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 }); +console.log(tokens); +``` + +
Output +

+ +``` +Token { type: 'Keyword', value: 'let', start: 0, end: 3 }, +Token { type: 'Identifier', value: 'foo', start: 4, end: 7 }, +Token { type: 'Punctuator', value: '=', start: 8, end: 9 }, +Token { type: 'String', value: '"bar"', start: 10, end: 15 } +``` + +

+
+ +### `version` + +Returns the current `espree` version + +### `VisitorKeys` + +Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/js/tree/main/packages/eslint-visitor-keys) + +### `latestEcmaVersion` + +Returns the latest ECMAScript supported by `espree` + +### `supportedEcmaVersions` + +Returns an array of all supported ECMAScript versions + +## Options + +```js +const options = { + // attach range information to each node + range: false, + + // attach line/column location information to each node + loc: false, + + // create a top-level comments array containing all comments + comment: false, + + // create a top-level tokens array containing all tokens + tokens: false, + + // Set to 3, 5 (the default), 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 or 17 to specify the version of ECMAScript syntax you want to use. + // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), 2022 (same as 13), 2023 (same as 14), 2024 (same as 15), 2025 (same as 16) or 2026 (same as 17) to use the year-based naming. + // You can also set "latest" to use the most recently supported version. + ecmaVersion: 3, + + allowReserved: true, // only allowed when ecmaVersion is 3 + + // specify which type of script you're parsing ("script", "module", or "commonjs") + sourceType: "script", + + // specify additional language features + ecmaFeatures: { + + // enable JSX parsing + jsx: false, + + // enable return in global scope (set to true automatically when sourceType is "commonjs") + globalReturn: false, + + // enable implied strict mode (if ecmaVersion >= 5) + impliedStrict: false + } +} +``` + +## Esprima Compatibility Going Forward + +The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. + +Espree may also deviate from Esprima in the interface it exposes. + +## Contributing + +Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/js/issues). + +Espree is licensed under a permissive BSD 2-clause license. + +## Security Policy + +We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). + +## Build Commands + +* `npm test` - run all tests +* `npm run lint` - run all linting + +## Differences from Espree 2.x + +* The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics. +* Trailing whitespace no longer is counted as part of a node. +* `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`. +* The `esparse` and `esvalidate` binary scripts have been removed. +* There is no `tolerant` option. We will investigate adding this back in the future. + +## Known Incompatibilities + +In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. + +### Esprima 1.2.2 + +* Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs. +* Espree does not parse `let` and `const` declarations by default. +* Error messages returned for parsing errors are different. +* There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn. + +### Esprima 2.x + +* Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. + +## Frequently Asked Questions + +### Why another parser + +[ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration. + +We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. + +With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima. + +### Have you tried working with Esprima? + +Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support. + +### Why don't you just use Acorn? + +Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. + +We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better. + +### What ECMAScript features do you support? + +Espree supports all ECMAScript 2025 features and partially supports ECMAScript 2026 features. + +Because ECMAScript 2026 is still under development, we are implementing features as they are finalized. Currently, Espree supports: + +* [Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management) + +See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized. + +### How do you determine which experimental features to support? + +In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features. + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/espree/dist/espree.cjs b/node_modules/espree/dist/espree.cjs new file mode 100644 index 00000000..0abd6b27 --- /dev/null +++ b/node_modules/espree/dist/espree.cjs @@ -0,0 +1,940 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var acorn = require('acorn'); +var jsx = require('acorn-jsx'); +var visitorKeys = require('eslint-visitor-keys'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var acorn__namespace = /*#__PURE__*/_interopNamespace(acorn); +var jsx__default = /*#__PURE__*/_interopDefaultLegacy(jsx); +var visitorKeys__namespace = /*#__PURE__*/_interopNamespace(visitorKeys); + +/** + * @fileoverview Translates tokens between Acorn format and Esprima format. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + + +// Esprima Token Types +const Token = { + Boolean: "Boolean", + EOF: "", + Identifier: "Identifier", + PrivateIdentifier: "PrivateIdentifier", + Keyword: "Keyword", + Null: "Null", + Numeric: "Numeric", + Punctuator: "Punctuator", + String: "String", + RegularExpression: "RegularExpression", + Template: "Template", + JSXIdentifier: "JSXIdentifier", + JSXText: "JSXText" +}; + +/** + * Converts part of a template into an Esprima token. + * @param {AcornToken[]} tokens The Acorn tokens representing the template. + * @param {string} code The source code. + * @returns {EsprimaToken} The Esprima equivalent of the template token. + * @private + */ +function convertTemplatePart(tokens, code) { + const firstToken = tokens[0], + lastTemplateToken = tokens.at(-1); + + const token = { + type: Token.Template, + value: code.slice(firstToken.start, lastTemplateToken.end) + }; + + if (firstToken.loc) { + token.loc = { + start: firstToken.loc.start, + end: lastTemplateToken.loc.end + }; + } + + if (firstToken.range) { + token.start = firstToken.range[0]; + token.end = lastTemplateToken.range[1]; + token.range = [token.start, token.end]; + } + + return token; +} + +/** + * Contains logic to translate Acorn tokens into Esprima tokens. + * @param {Object} acornTokTypes The Acorn token types. + * @param {string} code The source code Acorn is parsing. This is necessary + * to correct the "value" property of some tokens. + * @constructor + */ +function TokenTranslator(acornTokTypes, code) { + + // token types + this._acornTokTypes = acornTokTypes; + + // token buffer for templates + this._tokens = []; + + // track the last curly brace + this._curlyBrace = null; + + // the source code + this._code = code; + +} + +TokenTranslator.prototype = { + constructor: TokenTranslator, + + /** + * Translates a single Esprima token to a single Acorn token. This may be + * inaccurate due to how templates are handled differently in Esprima and + * Acorn, but should be accurate for all other tokens. + * @param {AcornToken} token The Acorn token to translate. + * @param {Object} extra Espree extra object. + * @returns {EsprimaToken} The Esprima version of the token. + */ + translate(token, extra) { + + const type = token.type, + tt = this._acornTokTypes; + + if (type === tt.name) { + token.type = Token.Identifier; + + // TODO: See if this is an Acorn bug + if (token.value === "static") { + token.type = Token.Keyword; + } + + if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) { + token.type = Token.Keyword; + } + + } else if (type === tt.privateId) { + token.type = Token.PrivateIdentifier; + + } else if (type === tt.semi || type === tt.comma || + type === tt.parenL || type === tt.parenR || + type === tt.braceL || type === tt.braceR || + type === tt.dot || type === tt.bracketL || + type === tt.colon || type === tt.question || + type === tt.bracketR || type === tt.ellipsis || + type === tt.arrow || type === tt.jsxTagStart || + type === tt.incDec || type === tt.starstar || + type === tt.jsxTagEnd || type === tt.prefix || + type === tt.questionDot || + (type.binop && !type.keyword) || + type.isAssign) { + + token.type = Token.Punctuator; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.jsxName) { + token.type = Token.JSXIdentifier; + } else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) { + token.type = Token.JSXText; + } else if (type.keyword) { + if (type.keyword === "true" || type.keyword === "false") { + token.type = Token.Boolean; + } else if (type.keyword === "null") { + token.type = Token.Null; + } else { + token.type = Token.Keyword; + } + } else if (type === tt.num) { + token.type = Token.Numeric; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.string) { + + if (extra.jsxAttrValueToken) { + extra.jsxAttrValueToken = false; + token.type = Token.JSXText; + } else { + token.type = Token.String; + } + + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.regexp) { + token.type = Token.RegularExpression; + const value = token.value; + + token.regex = { + flags: value.flags, + pattern: value.pattern + }; + token.value = `/${value.pattern}/${value.flags}`; + } + + return token; + }, + + /** + * Function to call during Acorn's onToken handler. + * @param {AcornToken} token The Acorn token. + * @param {Object} extra The Espree extra object. + * @returns {void} + */ + onToken(token, extra) { + + const tt = this._acornTokTypes, + tokens = extra.tokens, + templateTokens = this._tokens; + + /** + * Flushes the buffered template tokens and resets the template + * tracking. + * @returns {void} + * @private + */ + const translateTemplateTokens = () => { + tokens.push(convertTemplatePart(this._tokens, this._code)); + this._tokens = []; + }; + + if (token.type === tt.eof) { + + // might be one last curlyBrace + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + return; + } + + if (token.type === tt.backQuote) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + templateTokens.push(token); + + // it's the end + if (templateTokens.length > 1) { + translateTemplateTokens(); + } + + return; + } + if (token.type === tt.dollarBraceL) { + templateTokens.push(token); + translateTemplateTokens(); + return; + } + if (token.type === tt.braceR) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + // store new curly for later + this._curlyBrace = token; + return; + } + if (token.type === tt.template || token.type === tt.invalidTemplate) { + if (this._curlyBrace) { + templateTokens.push(this._curlyBrace); + this._curlyBrace = null; + } + + templateTokens.push(token); + return; + } + + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + tokens.push(this.translate(token, extra)); + } +}; + +/** + * @fileoverview A collection of methods for processing Espree's options. + * @author Kai Cataldo + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SUPPORTED_VERSIONS = [ + 3, + 5, + 6, // 2015 + 7, // 2016 + 8, // 2017 + 9, // 2018 + 10, // 2019 + 11, // 2020 + 12, // 2021 + 13, // 2022 + 14, // 2023 + 15, // 2024 + 16, // 2025 + 17 // 2026 +]; + +/** + * Get the latest ECMAScript version supported by Espree. + * @returns {number} The latest ECMAScript version. + */ +function getLatestEcmaVersion() { + return SUPPORTED_VERSIONS.at(-1); +} + +/** + * Get the list of ECMAScript versions supported by Espree. + * @returns {number[]} An array containing the supported ECMAScript versions. + */ +function getSupportedEcmaVersions() { + return [...SUPPORTED_VERSIONS]; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {(number|"latest")} ecmaVersion ECMAScript version from the initial config + * @throws {Error} throws an error if the ecmaVersion is invalid. + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersion(ecmaVersion = 5) { + + let version = ecmaVersion === "latest" ? getLatestEcmaVersion() : ecmaVersion; + + if (typeof version !== "number") { + throw new Error(`ecmaVersion must be a number or "latest". Received value of type ${typeof ecmaVersion} instead.`); + } + + // Calculate ECMAScript edition number from official year version starting with + // ES2015, which corresponds with ES6 (or a difference of 2009). + if (version >= 2015) { + version -= 2009; + } + + if (!SUPPORTED_VERSIONS.includes(version)) { + throw new Error("Invalid ecmaVersion."); + } + + return version; +} + +/** + * Normalize sourceType from the initial config + * @param {string} sourceType to normalize + * @throws {Error} throw an error if sourceType is invalid + * @returns {string} normalized sourceType + */ +function normalizeSourceType(sourceType = "script") { + if (sourceType === "script" || sourceType === "module") { + return sourceType; + } + + if (sourceType === "commonjs") { + return "script"; + } + + throw new Error("Invalid sourceType."); +} + +/** + * Normalize parserOptions + * @param {Object} options the parser options to normalize + * @throws {Error} throw an error if found invalid option. + * @returns {Object} normalized options + */ +function normalizeOptions(options) { + const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); + const sourceType = normalizeSourceType(options.sourceType); + const ranges = options.range === true; + const locations = options.loc === true; + + if (ecmaVersion !== 3 && options.allowReserved) { + + // a value of `false` is intentionally allowed here, so a shared config can overwrite it when needed + throw new Error("`allowReserved` is only supported when ecmaVersion is 3"); + } + if (typeof options.allowReserved !== "undefined" && typeof options.allowReserved !== "boolean") { + throw new Error("`allowReserved`, when present, must be `true` or `false`"); + } + const allowReserved = ecmaVersion === 3 ? (options.allowReserved || "never") : false; + const ecmaFeatures = options.ecmaFeatures || {}; + const allowReturnOutsideFunction = options.sourceType === "commonjs" || + Boolean(ecmaFeatures.globalReturn); + + if (sourceType === "module" && ecmaVersion < 6) { + throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options."); + } + + return Object.assign({}, options, { + ecmaVersion, + sourceType, + ranges, + locations, + allowReserved, + allowReturnOutsideFunction + }); +} + +/* eslint no-param-reassign: 0 -- stylistic choice */ + + +const STATE = Symbol("espree's internal state"); +const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode"); + + +/** + * Converts an Acorn comment to a Esprima comment. + * @param {boolean} block True if it's a block comment, false if not. + * @param {string} text The text of the comment. + * @param {int} start The index at which the comment starts. + * @param {int} end The index at which the comment ends. + * @param {Location} startLoc The location at which the comment starts. + * @param {Location} endLoc The location at which the comment ends. + * @param {string} code The source code being parsed. + * @returns {Object} The comment object. + * @private + */ +function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code) { + let type; + + if (block) { + type = "Block"; + } else if (code.slice(start, start + 2) === "#!") { + type = "Hashbang"; + } else { + type = "Line"; + } + + const comment = { + type, + value: text + }; + + if (typeof start === "number") { + comment.start = start; + comment.end = end; + comment.range = [start, end]; + } + + if (typeof startLoc === "object") { + comment.loc = { + start: startLoc, + end: endLoc + }; + } + + return comment; +} + +var espree = () => Parser => { + const tokTypes = Object.assign({}, Parser.acorn.tokTypes); + + if (Parser.acornJsx) { + Object.assign(tokTypes, Parser.acornJsx.tokTypes); + } + + return class Espree extends Parser { + constructor(opts, code) { + if (typeof opts !== "object" || opts === null) { + opts = {}; + } + if (typeof code !== "string" && !(code instanceof String)) { + code = String(code); + } + + // save original source type in case of commonjs + const originalSourceType = opts.sourceType; + const options = normalizeOptions(opts); + const ecmaFeatures = options.ecmaFeatures || {}; + const tokenTranslator = + options.tokens === true + ? new TokenTranslator(tokTypes, code) + : null; + + /* + * Data that is unique to Espree and is not represented internally + * in Acorn. + * + * For ES2023 hashbangs, Espree will call `onComment()` during the + * constructor, so we must define state before having access to + * `this`. + */ + const state = { + originalSourceType: originalSourceType || options.sourceType, + tokens: tokenTranslator ? [] : null, + comments: options.comment === true ? [] : null, + impliedStrict: ecmaFeatures.impliedStrict === true && options.ecmaVersion >= 5, + ecmaVersion: options.ecmaVersion, + jsxAttrValueToken: false, + lastToken: null, + templateElements: [] + }; + + // Initialize acorn parser. + super({ + + // do not use spread, because we don't want to pass any unknown options to acorn + ecmaVersion: options.ecmaVersion, + sourceType: options.sourceType, + ranges: options.ranges, + locations: options.locations, + allowReserved: options.allowReserved, + + // Truthy value is true for backward compatibility. + allowReturnOutsideFunction: options.allowReturnOutsideFunction, + + // Collect tokens + onToken(token) { + if (tokenTranslator) { + + // Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state. + tokenTranslator.onToken(token, state); + } + if (token.type !== tokTypes.eof) { + state.lastToken = token; + } + }, + + // Collect comments + onComment(block, text, start, end, startLoc, endLoc) { + if (state.comments) { + const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code); + + state.comments.push(comment); + } + } + }, code); + + /* + * We put all of this data into a symbol property as a way to avoid + * potential naming conflicts with future versions of Acorn. + */ + this[STATE] = state; + } + + tokenize() { + do { + this.next(); + } while (this.type !== tokTypes.eof); + + // Consume the final eof token + this.next(); + + const extra = this[STATE]; + const tokens = extra.tokens; + + if (extra.comments) { + tokens.comments = extra.comments; + } + + return tokens; + } + + finishNode(...args) { + const result = super.finishNode(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + finishNodeAt(...args) { + const result = super.finishNodeAt(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + parse() { + const extra = this[STATE]; + const program = super.parse(); + + program.sourceType = extra.originalSourceType; + + if (extra.comments) { + program.comments = extra.comments; + } + if (extra.tokens) { + program.tokens = extra.tokens; + } + + /* + * Adjust opening and closing position of program to match Esprima. + * Acorn always starts programs at range 0 whereas Esprima starts at the + * first AST node's start (the only real difference is when there's leading + * whitespace or leading comments). Acorn also counts trailing whitespace + * as part of the program whereas Esprima only counts up to the last token. + */ + if (program.body.length) { + const [firstNode] = program.body; + + if (program.range) { + program.range[0] = firstNode.range[0]; + } + if (program.loc) { + program.loc.start = firstNode.loc.start; + } + program.start = firstNode.start; + } + if (extra.lastToken) { + if (program.range) { + program.range[1] = extra.lastToken.range[1]; + } + if (program.loc) { + program.loc.end = extra.lastToken.loc.end; + } + program.end = extra.lastToken.end; + } + + + /* + * https://github.com/eslint/espree/issues/349 + * Ensure that template elements have correct range information. + * This is one location where Acorn produces a different value + * for its start and end properties vs. the values present in the + * range property. In order to avoid confusion, we set the start + * and end properties to the values that are present in range. + * This is done here, instead of in finishNode(), because Acorn + * uses the values of start and end internally while parsing, making + * it dangerous to change those values while parsing is ongoing. + * By waiting until the end of parsing, we can safely change these + * values without affect any other part of the process. + */ + this[STATE].templateElements.forEach(templateElement => { + const startOffset = -1; + const endOffset = templateElement.tail ? 1 : 2; + + templateElement.start += startOffset; + templateElement.end += endOffset; + + if (templateElement.range) { + templateElement.range[0] += startOffset; + templateElement.range[1] += endOffset; + } + + if (templateElement.loc) { + templateElement.loc.start.column += startOffset; + templateElement.loc.end.column += endOffset; + } + }); + + return program; + } + + parseTopLevel(node) { + if (this[STATE].impliedStrict) { + this.strict = true; + } + return super.parseTopLevel(node); + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raise(pos, message) { + const loc = Parser.acorn.getLineInfo(this.input, pos); + const err = new SyntaxError(message); + + err.index = pos; + err.lineNumber = loc.line; + err.column = loc.column + 1; // acorn uses 0-based columns + throw err; + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raiseRecoverable(pos, message) { + this.raise(pos, message); + } + + /** + * Overwrites the default unexpected method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + unexpected(pos) { + let message = "Unexpected token"; + + if (pos !== null && pos !== void 0) { + this.pos = pos; + + if (this.options.locations) { + while (this.pos < this.lineStart) { + this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; + --this.curLine; + } + } + + this.nextToken(); + } + + if (this.end > this.start) { + message += ` ${this.input.slice(this.start, this.end)}`; + } + + this.raise(this.start, message); + } + + /* + * Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX + * uses regular tt.string without any distinction between this and regular JS + * strings. As such, we intercept an attempt to read a JSX string and set a flag + * on extra so that when tokens are converted, the next token will be switched + * to JSXText via onToken. + */ + jsx_readString(quote) { // eslint-disable-line camelcase -- required by API + const result = super.jsx_readString(quote); + + if (this.type === tokTypes.string) { + this[STATE].jsxAttrValueToken = true; + } + return result; + } + + /** + * Performs last-minute Esprima-specific compatibility checks and fixes. + * @param {ASTNode} result The node to check. + * @returns {ASTNode} The finished node. + */ + [ESPRIMA_FINISH_NODE](result) { + + // Acorn doesn't count the opening and closing backticks as part of templates + // so we have to adjust ranges/locations appropriately. + if (result.type === "TemplateElement") { + + // save template element references to fix start/end later + this[STATE].templateElements.push(result); + } + + if (result.type.includes("Function") && !result.generator) { + result.generator = false; + } + + return result; + } + }; +}; + +const version$1 = "10.4.0"; + +/** + * @fileoverview Main Espree file that converts Acorn into Esprima output. + * + * This file contains code from the following MIT-licensed projects: + * 1. Acorn + * 2. Babylon + * 3. Babel-ESLint + * + * This file also contains code from Esprima, which is BSD licensed. + * + * Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS) + * Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS) + * Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +// To initialize lazily. +const parsers = { + _regular: null, + _jsx: null, + + get regular() { + if (this._regular === null) { + this._regular = acorn__namespace.Parser.extend(espree()); + } + return this._regular; + }, + + get jsx() { + if (this._jsx === null) { + this._jsx = acorn__namespace.Parser.extend(jsx__default["default"](), espree()); + } + return this._jsx; + }, + + get(options) { + const useJsx = Boolean( + options && + options.ecmaFeatures && + options.ecmaFeatures.jsx + ); + + return useJsx ? this.jsx : this.regular; + } +}; + +//------------------------------------------------------------------------------ +// Tokenizer +//------------------------------------------------------------------------------ + +/** + * Tokenizes the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {Token[]} An array of tokens. + * @throws {SyntaxError} If the input code is invalid. + * @private + */ +function tokenize(code, options) { + const Parser = parsers.get(options); + + // Ensure to collect tokens. + if (!options || options.tokens !== true) { + options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign -- stylistic choice + } + + return new Parser(options, code).tokenize(); +} + +//------------------------------------------------------------------------------ +// Parser +//------------------------------------------------------------------------------ + +/** + * Parses the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {ASTNode} The "Program" AST node. + * @throws {SyntaxError} If the input code is invalid. + */ +function parse(code, options) { + const Parser = parsers.get(options); + + return new Parser(options, code).parse(); +} + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +const version = version$1; +const name = "espree"; + +/* istanbul ignore next */ +const VisitorKeys = (function() { + return visitorKeys__namespace.KEYS; +}()); + +// Derive node types from VisitorKeys +/* istanbul ignore next */ +const Syntax = (function() { + let key, + types = {}; + + if (typeof Object.create === "function") { + types = Object.create(null); + } + + for (key in VisitorKeys) { + if (Object.hasOwn(VisitorKeys, key)) { + types[key] = key; + } + } + + if (typeof Object.freeze === "function") { + Object.freeze(types); + } + + return types; +}()); + +const latestEcmaVersion = getLatestEcmaVersion(); + +const supportedEcmaVersions = getSupportedEcmaVersions(); + +exports.Syntax = Syntax; +exports.VisitorKeys = VisitorKeys; +exports.latestEcmaVersion = latestEcmaVersion; +exports.name = name; +exports.parse = parse; +exports.supportedEcmaVersions = supportedEcmaVersions; +exports.tokenize = tokenize; +exports.version = version; diff --git a/node_modules/espree/espree.js b/node_modules/espree/espree.js new file mode 100644 index 00000000..15e0ce52 --- /dev/null +++ b/node_modules/espree/espree.js @@ -0,0 +1,174 @@ +/** + * @fileoverview Main Espree file that converts Acorn into Esprima output. + * + * This file contains code from the following MIT-licensed projects: + * 1. Acorn + * 2. Babylon + * 3. Babel-ESLint + * + * This file also contains code from Esprima, which is BSD licensed. + * + * Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS) + * Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS) + * Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +import * as acorn from "acorn"; +import jsx from "acorn-jsx"; +import espree from "./lib/espree.js"; +import espreeVersion from "./lib/version.js"; +import * as visitorKeys from "eslint-visitor-keys"; +import { getLatestEcmaVersion, getSupportedEcmaVersions } from "./lib/options.js"; + + +// To initialize lazily. +const parsers = { + _regular: null, + _jsx: null, + + get regular() { + if (this._regular === null) { + this._regular = acorn.Parser.extend(espree()); + } + return this._regular; + }, + + get jsx() { + if (this._jsx === null) { + this._jsx = acorn.Parser.extend(jsx(), espree()); + } + return this._jsx; + }, + + get(options) { + const useJsx = Boolean( + options && + options.ecmaFeatures && + options.ecmaFeatures.jsx + ); + + return useJsx ? this.jsx : this.regular; + } +}; + +//------------------------------------------------------------------------------ +// Tokenizer +//------------------------------------------------------------------------------ + +/** + * Tokenizes the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {Token[]} An array of tokens. + * @throws {SyntaxError} If the input code is invalid. + * @private + */ +export function tokenize(code, options) { + const Parser = parsers.get(options); + + // Ensure to collect tokens. + if (!options || options.tokens !== true) { + options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign -- stylistic choice + } + + return new Parser(options, code).tokenize(); +} + +//------------------------------------------------------------------------------ +// Parser +//------------------------------------------------------------------------------ + +/** + * Parses the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {ASTNode} The "Program" AST node. + * @throws {SyntaxError} If the input code is invalid. + */ +export function parse(code, options) { + const Parser = parsers.get(options); + + return new Parser(options, code).parse(); +} + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export const version = espreeVersion; +export const name = "espree"; + +/* istanbul ignore next */ +export const VisitorKeys = (function() { + return visitorKeys.KEYS; +}()); + +// Derive node types from VisitorKeys +/* istanbul ignore next */ +export const Syntax = (function() { + let key, + types = {}; + + if (typeof Object.create === "function") { + types = Object.create(null); + } + + for (key in VisitorKeys) { + if (Object.hasOwn(VisitorKeys, key)) { + types[key] = key; + } + } + + if (typeof Object.freeze === "function") { + Object.freeze(types); + } + + return types; +}()); + +export const latestEcmaVersion = getLatestEcmaVersion(); + +export const supportedEcmaVersions = getSupportedEcmaVersions(); diff --git a/node_modules/espree/lib/espree.js b/node_modules/espree/lib/espree.js new file mode 100644 index 00000000..2be1b56d --- /dev/null +++ b/node_modules/espree/lib/espree.js @@ -0,0 +1,349 @@ +/* eslint no-param-reassign: 0 -- stylistic choice */ + +import TokenTranslator from "./token-translator.js"; +import { normalizeOptions } from "./options.js"; + + +const STATE = Symbol("espree's internal state"); +const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode"); + + +/** + * Converts an Acorn comment to a Esprima comment. + * @param {boolean} block True if it's a block comment, false if not. + * @param {string} text The text of the comment. + * @param {int} start The index at which the comment starts. + * @param {int} end The index at which the comment ends. + * @param {Location} startLoc The location at which the comment starts. + * @param {Location} endLoc The location at which the comment ends. + * @param {string} code The source code being parsed. + * @returns {Object} The comment object. + * @private + */ +function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code) { + let type; + + if (block) { + type = "Block"; + } else if (code.slice(start, start + 2) === "#!") { + type = "Hashbang"; + } else { + type = "Line"; + } + + const comment = { + type, + value: text + }; + + if (typeof start === "number") { + comment.start = start; + comment.end = end; + comment.range = [start, end]; + } + + if (typeof startLoc === "object") { + comment.loc = { + start: startLoc, + end: endLoc + }; + } + + return comment; +} + +export default () => Parser => { + const tokTypes = Object.assign({}, Parser.acorn.tokTypes); + + if (Parser.acornJsx) { + Object.assign(tokTypes, Parser.acornJsx.tokTypes); + } + + return class Espree extends Parser { + constructor(opts, code) { + if (typeof opts !== "object" || opts === null) { + opts = {}; + } + if (typeof code !== "string" && !(code instanceof String)) { + code = String(code); + } + + // save original source type in case of commonjs + const originalSourceType = opts.sourceType; + const options = normalizeOptions(opts); + const ecmaFeatures = options.ecmaFeatures || {}; + const tokenTranslator = + options.tokens === true + ? new TokenTranslator(tokTypes, code) + : null; + + /* + * Data that is unique to Espree and is not represented internally + * in Acorn. + * + * For ES2023 hashbangs, Espree will call `onComment()` during the + * constructor, so we must define state before having access to + * `this`. + */ + const state = { + originalSourceType: originalSourceType || options.sourceType, + tokens: tokenTranslator ? [] : null, + comments: options.comment === true ? [] : null, + impliedStrict: ecmaFeatures.impliedStrict === true && options.ecmaVersion >= 5, + ecmaVersion: options.ecmaVersion, + jsxAttrValueToken: false, + lastToken: null, + templateElements: [] + }; + + // Initialize acorn parser. + super({ + + // do not use spread, because we don't want to pass any unknown options to acorn + ecmaVersion: options.ecmaVersion, + sourceType: options.sourceType, + ranges: options.ranges, + locations: options.locations, + allowReserved: options.allowReserved, + + // Truthy value is true for backward compatibility. + allowReturnOutsideFunction: options.allowReturnOutsideFunction, + + // Collect tokens + onToken(token) { + if (tokenTranslator) { + + // Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state. + tokenTranslator.onToken(token, state); + } + if (token.type !== tokTypes.eof) { + state.lastToken = token; + } + }, + + // Collect comments + onComment(block, text, start, end, startLoc, endLoc) { + if (state.comments) { + const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code); + + state.comments.push(comment); + } + } + }, code); + + /* + * We put all of this data into a symbol property as a way to avoid + * potential naming conflicts with future versions of Acorn. + */ + this[STATE] = state; + } + + tokenize() { + do { + this.next(); + } while (this.type !== tokTypes.eof); + + // Consume the final eof token + this.next(); + + const extra = this[STATE]; + const tokens = extra.tokens; + + if (extra.comments) { + tokens.comments = extra.comments; + } + + return tokens; + } + + finishNode(...args) { + const result = super.finishNode(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + finishNodeAt(...args) { + const result = super.finishNodeAt(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + parse() { + const extra = this[STATE]; + const program = super.parse(); + + program.sourceType = extra.originalSourceType; + + if (extra.comments) { + program.comments = extra.comments; + } + if (extra.tokens) { + program.tokens = extra.tokens; + } + + /* + * Adjust opening and closing position of program to match Esprima. + * Acorn always starts programs at range 0 whereas Esprima starts at the + * first AST node's start (the only real difference is when there's leading + * whitespace or leading comments). Acorn also counts trailing whitespace + * as part of the program whereas Esprima only counts up to the last token. + */ + if (program.body.length) { + const [firstNode] = program.body; + + if (program.range) { + program.range[0] = firstNode.range[0]; + } + if (program.loc) { + program.loc.start = firstNode.loc.start; + } + program.start = firstNode.start; + } + if (extra.lastToken) { + if (program.range) { + program.range[1] = extra.lastToken.range[1]; + } + if (program.loc) { + program.loc.end = extra.lastToken.loc.end; + } + program.end = extra.lastToken.end; + } + + + /* + * https://github.com/eslint/espree/issues/349 + * Ensure that template elements have correct range information. + * This is one location where Acorn produces a different value + * for its start and end properties vs. the values present in the + * range property. In order to avoid confusion, we set the start + * and end properties to the values that are present in range. + * This is done here, instead of in finishNode(), because Acorn + * uses the values of start and end internally while parsing, making + * it dangerous to change those values while parsing is ongoing. + * By waiting until the end of parsing, we can safely change these + * values without affect any other part of the process. + */ + this[STATE].templateElements.forEach(templateElement => { + const startOffset = -1; + const endOffset = templateElement.tail ? 1 : 2; + + templateElement.start += startOffset; + templateElement.end += endOffset; + + if (templateElement.range) { + templateElement.range[0] += startOffset; + templateElement.range[1] += endOffset; + } + + if (templateElement.loc) { + templateElement.loc.start.column += startOffset; + templateElement.loc.end.column += endOffset; + } + }); + + return program; + } + + parseTopLevel(node) { + if (this[STATE].impliedStrict) { + this.strict = true; + } + return super.parseTopLevel(node); + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raise(pos, message) { + const loc = Parser.acorn.getLineInfo(this.input, pos); + const err = new SyntaxError(message); + + err.index = pos; + err.lineNumber = loc.line; + err.column = loc.column + 1; // acorn uses 0-based columns + throw err; + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raiseRecoverable(pos, message) { + this.raise(pos, message); + } + + /** + * Overwrites the default unexpected method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + unexpected(pos) { + let message = "Unexpected token"; + + if (pos !== null && pos !== void 0) { + this.pos = pos; + + if (this.options.locations) { + while (this.pos < this.lineStart) { + this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; + --this.curLine; + } + } + + this.nextToken(); + } + + if (this.end > this.start) { + message += ` ${this.input.slice(this.start, this.end)}`; + } + + this.raise(this.start, message); + } + + /* + * Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX + * uses regular tt.string without any distinction between this and regular JS + * strings. As such, we intercept an attempt to read a JSX string and set a flag + * on extra so that when tokens are converted, the next token will be switched + * to JSXText via onToken. + */ + jsx_readString(quote) { // eslint-disable-line camelcase -- required by API + const result = super.jsx_readString(quote); + + if (this.type === tokTypes.string) { + this[STATE].jsxAttrValueToken = true; + } + return result; + } + + /** + * Performs last-minute Esprima-specific compatibility checks and fixes. + * @param {ASTNode} result The node to check. + * @returns {ASTNode} The finished node. + */ + [ESPRIMA_FINISH_NODE](result) { + + // Acorn doesn't count the opening and closing backticks as part of templates + // so we have to adjust ranges/locations appropriately. + if (result.type === "TemplateElement") { + + // save template element references to fix start/end later + this[STATE].templateElements.push(result); + } + + if (result.type.includes("Function") && !result.generator) { + result.generator = false; + } + + return result; + } + }; +}; diff --git a/node_modules/espree/lib/features.js b/node_modules/espree/lib/features.js new file mode 100644 index 00000000..31467d28 --- /dev/null +++ b/node_modules/espree/lib/features.js @@ -0,0 +1,27 @@ +/** + * @fileoverview The list of feature flags supported by the parser and their default + * settings. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// None! + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export default { + + // React JSX parsing + jsx: false, + + // allow return statement in global scope + globalReturn: false, + + // allow implied strict mode + impliedStrict: false +}; diff --git a/node_modules/espree/lib/options.js b/node_modules/espree/lib/options.js new file mode 100644 index 00000000..85bb9029 --- /dev/null +++ b/node_modules/espree/lib/options.js @@ -0,0 +1,125 @@ +/** + * @fileoverview A collection of methods for processing Espree's options. + * @author Kai Cataldo + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SUPPORTED_VERSIONS = [ + 3, + 5, + 6, // 2015 + 7, // 2016 + 8, // 2017 + 9, // 2018 + 10, // 2019 + 11, // 2020 + 12, // 2021 + 13, // 2022 + 14, // 2023 + 15, // 2024 + 16, // 2025 + 17 // 2026 +]; + +/** + * Get the latest ECMAScript version supported by Espree. + * @returns {number} The latest ECMAScript version. + */ +export function getLatestEcmaVersion() { + return SUPPORTED_VERSIONS.at(-1); +} + +/** + * Get the list of ECMAScript versions supported by Espree. + * @returns {number[]} An array containing the supported ECMAScript versions. + */ +export function getSupportedEcmaVersions() { + return [...SUPPORTED_VERSIONS]; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {(number|"latest")} ecmaVersion ECMAScript version from the initial config + * @throws {Error} throws an error if the ecmaVersion is invalid. + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersion(ecmaVersion = 5) { + + let version = ecmaVersion === "latest" ? getLatestEcmaVersion() : ecmaVersion; + + if (typeof version !== "number") { + throw new Error(`ecmaVersion must be a number or "latest". Received value of type ${typeof ecmaVersion} instead.`); + } + + // Calculate ECMAScript edition number from official year version starting with + // ES2015, which corresponds with ES6 (or a difference of 2009). + if (version >= 2015) { + version -= 2009; + } + + if (!SUPPORTED_VERSIONS.includes(version)) { + throw new Error("Invalid ecmaVersion."); + } + + return version; +} + +/** + * Normalize sourceType from the initial config + * @param {string} sourceType to normalize + * @throws {Error} throw an error if sourceType is invalid + * @returns {string} normalized sourceType + */ +function normalizeSourceType(sourceType = "script") { + if (sourceType === "script" || sourceType === "module") { + return sourceType; + } + + if (sourceType === "commonjs") { + return "script"; + } + + throw new Error("Invalid sourceType."); +} + +/** + * Normalize parserOptions + * @param {Object} options the parser options to normalize + * @throws {Error} throw an error if found invalid option. + * @returns {Object} normalized options + */ +export function normalizeOptions(options) { + const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); + const sourceType = normalizeSourceType(options.sourceType); + const ranges = options.range === true; + const locations = options.loc === true; + + if (ecmaVersion !== 3 && options.allowReserved) { + + // a value of `false` is intentionally allowed here, so a shared config can overwrite it when needed + throw new Error("`allowReserved` is only supported when ecmaVersion is 3"); + } + if (typeof options.allowReserved !== "undefined" && typeof options.allowReserved !== "boolean") { + throw new Error("`allowReserved`, when present, must be `true` or `false`"); + } + const allowReserved = ecmaVersion === 3 ? (options.allowReserved || "never") : false; + const ecmaFeatures = options.ecmaFeatures || {}; + const allowReturnOutsideFunction = options.sourceType === "commonjs" || + Boolean(ecmaFeatures.globalReturn); + + if (sourceType === "module" && ecmaVersion < 6) { + throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options."); + } + + return Object.assign({}, options, { + ecmaVersion, + sourceType, + ranges, + locations, + allowReserved, + allowReturnOutsideFunction + }); +} diff --git a/node_modules/espree/lib/token-translator.js b/node_modules/espree/lib/token-translator.js new file mode 100644 index 00000000..6daf865a --- /dev/null +++ b/node_modules/espree/lib/token-translator.js @@ -0,0 +1,263 @@ +/** + * @fileoverview Translates tokens between Acorn format and Esprima format. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + + +// Esprima Token Types +const Token = { + Boolean: "Boolean", + EOF: "", + Identifier: "Identifier", + PrivateIdentifier: "PrivateIdentifier", + Keyword: "Keyword", + Null: "Null", + Numeric: "Numeric", + Punctuator: "Punctuator", + String: "String", + RegularExpression: "RegularExpression", + Template: "Template", + JSXIdentifier: "JSXIdentifier", + JSXText: "JSXText" +}; + +/** + * Converts part of a template into an Esprima token. + * @param {AcornToken[]} tokens The Acorn tokens representing the template. + * @param {string} code The source code. + * @returns {EsprimaToken} The Esprima equivalent of the template token. + * @private + */ +function convertTemplatePart(tokens, code) { + const firstToken = tokens[0], + lastTemplateToken = tokens.at(-1); + + const token = { + type: Token.Template, + value: code.slice(firstToken.start, lastTemplateToken.end) + }; + + if (firstToken.loc) { + token.loc = { + start: firstToken.loc.start, + end: lastTemplateToken.loc.end + }; + } + + if (firstToken.range) { + token.start = firstToken.range[0]; + token.end = lastTemplateToken.range[1]; + token.range = [token.start, token.end]; + } + + return token; +} + +/** + * Contains logic to translate Acorn tokens into Esprima tokens. + * @param {Object} acornTokTypes The Acorn token types. + * @param {string} code The source code Acorn is parsing. This is necessary + * to correct the "value" property of some tokens. + * @constructor + */ +function TokenTranslator(acornTokTypes, code) { + + // token types + this._acornTokTypes = acornTokTypes; + + // token buffer for templates + this._tokens = []; + + // track the last curly brace + this._curlyBrace = null; + + // the source code + this._code = code; + +} + +TokenTranslator.prototype = { + constructor: TokenTranslator, + + /** + * Translates a single Esprima token to a single Acorn token. This may be + * inaccurate due to how templates are handled differently in Esprima and + * Acorn, but should be accurate for all other tokens. + * @param {AcornToken} token The Acorn token to translate. + * @param {Object} extra Espree extra object. + * @returns {EsprimaToken} The Esprima version of the token. + */ + translate(token, extra) { + + const type = token.type, + tt = this._acornTokTypes; + + if (type === tt.name) { + token.type = Token.Identifier; + + // TODO: See if this is an Acorn bug + if (token.value === "static") { + token.type = Token.Keyword; + } + + if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) { + token.type = Token.Keyword; + } + + } else if (type === tt.privateId) { + token.type = Token.PrivateIdentifier; + + } else if (type === tt.semi || type === tt.comma || + type === tt.parenL || type === tt.parenR || + type === tt.braceL || type === tt.braceR || + type === tt.dot || type === tt.bracketL || + type === tt.colon || type === tt.question || + type === tt.bracketR || type === tt.ellipsis || + type === tt.arrow || type === tt.jsxTagStart || + type === tt.incDec || type === tt.starstar || + type === tt.jsxTagEnd || type === tt.prefix || + type === tt.questionDot || + (type.binop && !type.keyword) || + type.isAssign) { + + token.type = Token.Punctuator; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.jsxName) { + token.type = Token.JSXIdentifier; + } else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) { + token.type = Token.JSXText; + } else if (type.keyword) { + if (type.keyword === "true" || type.keyword === "false") { + token.type = Token.Boolean; + } else if (type.keyword === "null") { + token.type = Token.Null; + } else { + token.type = Token.Keyword; + } + } else if (type === tt.num) { + token.type = Token.Numeric; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.string) { + + if (extra.jsxAttrValueToken) { + extra.jsxAttrValueToken = false; + token.type = Token.JSXText; + } else { + token.type = Token.String; + } + + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.regexp) { + token.type = Token.RegularExpression; + const value = token.value; + + token.regex = { + flags: value.flags, + pattern: value.pattern + }; + token.value = `/${value.pattern}/${value.flags}`; + } + + return token; + }, + + /** + * Function to call during Acorn's onToken handler. + * @param {AcornToken} token The Acorn token. + * @param {Object} extra The Espree extra object. + * @returns {void} + */ + onToken(token, extra) { + + const tt = this._acornTokTypes, + tokens = extra.tokens, + templateTokens = this._tokens; + + /** + * Flushes the buffered template tokens and resets the template + * tracking. + * @returns {void} + * @private + */ + const translateTemplateTokens = () => { + tokens.push(convertTemplatePart(this._tokens, this._code)); + this._tokens = []; + }; + + if (token.type === tt.eof) { + + // might be one last curlyBrace + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + return; + } + + if (token.type === tt.backQuote) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + templateTokens.push(token); + + // it's the end + if (templateTokens.length > 1) { + translateTemplateTokens(); + } + + return; + } + if (token.type === tt.dollarBraceL) { + templateTokens.push(token); + translateTemplateTokens(); + return; + } + if (token.type === tt.braceR) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + // store new curly for later + this._curlyBrace = token; + return; + } + if (token.type === tt.template || token.type === tt.invalidTemplate) { + if (this._curlyBrace) { + templateTokens.push(this._curlyBrace); + this._curlyBrace = null; + } + + templateTokens.push(token); + return; + } + + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + tokens.push(this.translate(token, extra)); + } +}; + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export default TokenTranslator; diff --git a/node_modules/espree/lib/version.js b/node_modules/espree/lib/version.js new file mode 100644 index 00000000..26f3eced --- /dev/null +++ b/node_modules/espree/lib/version.js @@ -0,0 +1,3 @@ +const version = "10.4.0"; + +export default version; diff --git a/node_modules/espree/node_modules/eslint-visitor-keys/LICENSE b/node_modules/espree/node_modules/eslint-visitor-keys/LICENSE new file mode 100644 index 00000000..17a25538 --- /dev/null +++ b/node_modules/espree/node_modules/eslint-visitor-keys/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/espree/node_modules/eslint-visitor-keys/README.md b/node_modules/espree/node_modules/eslint-visitor-keys/README.md new file mode 100644 index 00000000..aa860ba5 --- /dev/null +++ b/node_modules/espree/node_modules/eslint-visitor-keys/README.md @@ -0,0 +1,121 @@ +# eslint-visitor-keys + +[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) +[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions) + +Constants and utilities about visitor keys to traverse AST. + +## 💿 Installation + +Use [npm] to install. + +```bash +$ npm install eslint-visitor-keys +``` + +### Requirements + +- [Node.js] `^18.18.0`, `^20.9.0`, or `>=21.1.0` + +## 📖 Usage + +To use in an ESM file: + +```js +import * as evk from "eslint-visitor-keys" +``` + +To use in a CommonJS file: + +```js +const evk = require("eslint-visitor-keys") +``` + +### evk.KEYS + +> type: `{ [type: string]: string[] | undefined }` + +Visitor keys. This keys are frozen. + +This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. + +For example: + +``` +console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] +``` + +### evk.getKeys(node) + +> type: `(node: object) => string[]` + +Get the visitor keys of a given AST node. + +This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. + +This will be used to traverse unknown nodes. + +For example: + +```js +const node = { + type: "AssignmentExpression", + left: { type: "Identifier", name: "foo" }, + right: { type: "Literal", value: 0 } +} +console.log(evk.getKeys(node)) // → ["type", "left", "right"] +``` + +### evk.unionWith(additionalKeys) + +> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` + +Make the union set with `evk.KEYS` and the given keys. + +- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. +- It removes duplicated keys as keeping the first one. + +For example: + +```js +console.log(evk.unionWith({ + MethodDefinition: ["decorators"] +})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } +``` + +## 📰 Change log + +See [GitHub releases](https://github.com/eslint/js/releases). + +## 🍻 Contributing + +Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). + +### Development commands + +- `npm test` runs tests and measures code coverage. +- `npm run lint` checks source codes with ESLint. +- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser. + +[npm]: https://www.npmjs.com/ +[Node.js]: https://nodejs.org/ +[ESTree]: https://github.com/estree/estree + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/espree/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs b/node_modules/espree/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs new file mode 100644 index 00000000..afc433c7 --- /dev/null +++ b/node_modules/espree/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs @@ -0,0 +1,396 @@ +'use strict'; + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source", + "attributes" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source", + "attributes" + ], + ExportSpecifier: [ + "local", + "exported" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportAttribute: [ + "key", + "value" + ], + ImportDeclaration: [ + "specifiers", + "source", + "attributes" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source", + "options" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +function getKeys(node) { + return Object.keys(node).filter(filterKey); +} +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */ + +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +function unionWith(additionalKeys) { + const retv = /** @type {{ [type: string]: ReadonlyArray }} */ + (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.hasOwn(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +exports.KEYS = KEYS; +exports.getKeys = getKeys; +exports.unionWith = unionWith; diff --git a/node_modules/espree/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts b/node_modules/espree/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts new file mode 100644 index 00000000..34253c96 --- /dev/null +++ b/node_modules/espree/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts @@ -0,0 +1,28 @@ +type VisitorKeys$1 = { + readonly [type: string]: ReadonlyArray; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys$1; + +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +declare function getKeys(node: Object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys; + +type VisitorKeys = VisitorKeys$1; + +export { KEYS, getKeys, unionWith }; +export type { VisitorKeys }; diff --git a/node_modules/espree/node_modules/eslint-visitor-keys/dist/index.d.ts b/node_modules/espree/node_modules/eslint-visitor-keys/dist/index.d.ts new file mode 100644 index 00000000..e65b7da3 --- /dev/null +++ b/node_modules/espree/node_modules/eslint-visitor-keys/dist/index.d.ts @@ -0,0 +1,16 @@ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node: Object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys: VisitorKeys): VisitorKeys; +export { KEYS }; +export type VisitorKeys = import("./visitor-keys.js").VisitorKeys; +import KEYS from "./visitor-keys.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/espree/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts b/node_modules/espree/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts new file mode 100644 index 00000000..2d7ada2f --- /dev/null +++ b/node_modules/espree/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts @@ -0,0 +1,12 @@ +export default KEYS; +export type VisitorKeys = { + readonly [type: string]: ReadonlyArray; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys; +//# sourceMappingURL=visitor-keys.d.ts.map \ No newline at end of file diff --git a/node_modules/espree/node_modules/eslint-visitor-keys/lib/index.js b/node_modules/espree/node_modules/eslint-visitor-keys/lib/index.js new file mode 100644 index 00000000..1fc89b43 --- /dev/null +++ b/node_modules/espree/node_modules/eslint-visitor-keys/lib/index.js @@ -0,0 +1,67 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +import KEYS from "./visitor-keys.js"; + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node) { + return Object.keys(node).filter(filterKey); +} +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */ + +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys) { + const retv = /** @type {{ [type: string]: ReadonlyArray }} */ + (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.hasOwn(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +export { KEYS }; diff --git a/node_modules/espree/node_modules/eslint-visitor-keys/lib/visitor-keys.js b/node_modules/espree/node_modules/eslint-visitor-keys/lib/visitor-keys.js new file mode 100644 index 00000000..c891e040 --- /dev/null +++ b/node_modules/espree/node_modules/eslint-visitor-keys/lib/visitor-keys.js @@ -0,0 +1,327 @@ +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source", + "attributes" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source", + "attributes" + ], + ExportSpecifier: [ + "local", + "exported" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportAttribute: [ + "key", + "value" + ], + ImportDeclaration: [ + "specifiers", + "source", + "attributes" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source", + "options" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +export default KEYS; diff --git a/node_modules/espree/node_modules/eslint-visitor-keys/package.json b/node_modules/espree/node_modules/eslint-visitor-keys/package.json new file mode 100644 index 00000000..852e4ddb --- /dev/null +++ b/node_modules/espree/node_modules/eslint-visitor-keys/package.json @@ -0,0 +1,70 @@ +{ + "name": "eslint-visitor-keys", + "version": "4.2.1", + "description": "Constants and utilities about visitor keys to traverse AST.", + "type": "module", + "main": "dist/eslint-visitor-keys.cjs", + "types": "./dist/index.d.ts", + "exports": { + ".": [ + { + "import": "./lib/index.js", + "require": "./dist/eslint-visitor-keys.cjs" + }, + "./dist/eslint-visitor-keys.cjs" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist/index.d.ts", + "dist/visitor-keys.d.ts", + "dist/eslint-visitor-keys.cjs", + "dist/eslint-visitor-keys.d.cts", + "lib" + ], + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "devDependencies": { + "@types/estree": "^0.0.51", + "@types/estree-jsx": "^0.0.1", + "@typescript-eslint/parser": "^8.7.0", + "eslint-release": "^3.2.0", + "esquery": "^1.4.0", + "json-diff": "^0.7.3", + "opener": "^1.5.2", + "rollup": "^4.22.4", + "rollup-plugin-dts": "^6.1.1", + "tsd": "^0.31.2", + "typescript": "^5.6.2" + }, + "scripts": { + "build": "npm run build:cjs && npm run build:types", + "build:cjs": "rollup -c", + "build:debug": "npm run build:cjs -- -m && npm run build:types", + "build:types": "tsc -v && tsc", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "mocha tests/lib/**/*.cjs && c8 mocha tests/lib/**/*.js && npm run test:types", + "test:open-coverage": "c8 report --reporter lcov && opener coverage/lcov-report/index.html", + "test:types": "tsd" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/eslint-visitor-keys" + }, + "funding": "https://opencollective.com/eslint", + "keywords": [ + "eslint" + ], + "author": "Toru Nagashima (https://github.com/mysticatea)", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-visitor-keys/README.md" +} diff --git a/node_modules/espree/package.json b/node_modules/espree/package.json new file mode 100644 index 00000000..20b6dc6f --- /dev/null +++ b/node_modules/espree/package.json @@ -0,0 +1,77 @@ +{ + "name": "espree", + "description": "An Esprima-compatible JavaScript parser built on Acorn", + "author": "Nicholas C. Zakas ", + "homepage": "https://github.com/eslint/js/blob/main/packages/espree/README.md", + "main": "dist/espree.cjs", + "type": "module", + "exports": { + ".": [ + { + "import": "./espree.js", + "require": "./dist/espree.cjs", + "default": "./dist/espree.cjs" + }, + "./dist/espree.cjs" + ], + "./package.json": "./package.json" + }, + "version": "10.4.0", + "files": [ + "lib", + "dist/espree.cjs", + "espree.js" + ], + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/espree" + }, + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "funding": "https://opencollective.com/eslint", + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^28.0.0", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^15.3.0", + "eslint-release": "^3.2.0", + "esprima-fb": "^8001.2001.0-dev-harmony-fb", + "npm-run-all2": "^6.2.2", + "rollup": "^2.79.1", + "shelljs": "^0.8.5" + }, + "keywords": [ + "ast", + "ecmascript", + "javascript", + "parser", + "syntax", + "acorn" + ], + "scripts": { + "build": "rollup -c rollup.config.js", + "build:debug": "npm run build -- -m", + "build:docs": "node tools/sync-docs.js", + "build:update-version": "node tools/update-version.js", + "prepublishOnly": "npm run build:update-version && npm run build", + "pretest": "npm run build", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "npm-run-all -s test:*", + "test:cjs": "mocha --color --reporter progress --timeout 30000 tests/lib/commonjs.cjs", + "test:esm": "c8 mocha --color --reporter progress --timeout 30000 tests/lib/**/*.js" + } +} diff --git a/node_modules/esquery/README.md b/node_modules/esquery/README.md new file mode 100644 index 00000000..16809a79 --- /dev/null +++ b/node_modules/esquery/README.md @@ -0,0 +1,27 @@ +ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system. Check out the demo: + +[demo](https://estools.github.io/esquery/) + +The following selectors are supported: +* AST node type: `ForStatement` +* [wildcard](http://dev.w3.org/csswg/selectors4/#universal-selector): `*` +* [attribute existence](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr]` +* [attribute value](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr="foo"]` or `[attr=123]` +* attribute regex: `[attr=/foo.*/]` or (with flags) `[attr=/foo.*/is]` +* attribute conditions: `[attr!="foo"]`, `[attr>2]`, `[attr<3]`, `[attr>=2]`, or `[attr<=3]` +* nested attribute: `[attr.level2="foo"]` +* field: `FunctionDeclaration > Identifier.id` +* [First](http://dev.w3.org/csswg/selectors4/#the-first-child-pseudo) or [last](http://dev.w3.org/csswg/selectors4/#the-last-child-pseudo) child: `:first-child` or `:last-child` +* [nth-child](http://dev.w3.org/csswg/selectors4/#the-nth-child-pseudo) (no ax+b support): `:nth-child(2)` +* [nth-last-child](http://dev.w3.org/csswg/selectors4/#the-nth-last-child-pseudo) (no ax+b support): `:nth-last-child(1)` +* [descendant](http://dev.w3.org/csswg/selectors4/#descendant-combinators): `ancestor descendant` +* [child](http://dev.w3.org/csswg/selectors4/#child-combinators): `parent > child` +* [following sibling](http://dev.w3.org/csswg/selectors4/#general-sibling-combinators): `node ~ sibling` +* [adjacent sibling](http://dev.w3.org/csswg/selectors4/#adjacent-sibling-combinators): `node + adjacent` +* [negation](http://dev.w3.org/csswg/selectors4/#negation-pseudo): `:not(ForStatement)` +* [has](https://drafts.csswg.org/selectors-4/#has-pseudo): `:has(ForStatement)`, `:has(> ForStatement)` +* [matches-any](http://dev.w3.org/csswg/selectors4/#matches): `:matches([attr] > :first-child, :last-child)` +* [subject indicator](http://dev.w3.org/csswg/selectors4/#subject): `!IfStatement > [name="foo"]` +* class of AST node: `:statement`, `:expression`, `:declaration`, `:function`, or `:pattern` + +[![Build Status](https://travis-ci.org/estools/esquery.png?branch=master)](https://travis-ci.org/estools/esquery) diff --git a/node_modules/esquery/dist/esquery.esm.js b/node_modules/esquery/dist/esquery.esm.js new file mode 100644 index 00000000..61caabaf --- /dev/null +++ b/node_modules/esquery/dist/esquery.esm.js @@ -0,0 +1,4172 @@ +function _iterableToArrayLimit(arr, i) { + var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; + if (null != _i) { + var _s, + _e, + _x, + _r, + _arr = [], + _n = !0, + _d = !1; + try { + if (_x = (_i = _i.call(arr)).next, 0 === i) { + if (Object(_i) !== _i) return; + _n = !1; + } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); + } catch (err) { + _d = !0, _e = err; + } finally { + try { + if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; + } finally { + if (_d) throw _e; + } + } + return _arr; + } +} +function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); +} +function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); +} +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); +} +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); +} +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); +} +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; +} +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var estraverse = createCommonjsModule(function (module, exports) { + /* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + /*jslint vars:false, bitwise:true*/ + /*jshint indent:4*/ + /*global exports:true*/ + (function clone(exports) { + + var Syntax, VisitorOption, VisitorKeys, BREAK, SKIP, REMOVE; + function deepCopy(obj) { + var ret = {}, + key, + val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + len = array.length; + i = 0; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', + // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ChainExpression: 'ChainExpression', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', + // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', + // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', + // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + PrivateIdentifier: 'PrivateIdentifier', + Program: 'Program', + Property: 'Property', + PropertyDefinition: 'PropertyDefinition', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], + // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ChainExpression: ['expression'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], + // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], + // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], + // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + PrivateIdentifier: [], + Program: ['body'], + Property: ['key', 'value'], + PropertyDefinition: ['key', 'value'], + RestElement: ['argument'], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + function Controller() {} + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + result = undefined; + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + Controller.prototype.__initialize = function (root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + function candidateExistsInLeaveList(leavelist, candidate) { + for (var i = leavelist.length - 1; i >= 0; --i) { + if (leavelist[i].node === candidate) { + return true; + } + } + return false; + } + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel; + this.__initialize(root, visitor); + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + ret = this.__execute(visitor.leave, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + if (element.node) { + ret = this.__execute(visitor.enter, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || ret === SKIP) { + continue; + } + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (candidateExistsInLeaveList(leavelist, candidate[current2])) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + if (candidateExistsInLeaveList(leavelist, candidate)) { + continue; + } + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + Controller.prototype.replace = function replace(root, visitor) { + var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key; + function removeElem(element) { + var i, key, nextElem, parent; + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + this.__initialize(root, visitor); + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || target === SKIP) { + continue; + } + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + return outer.root; + }; + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + function extendCommentRange(comment, tokens) { + var target; + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + comment.extendedRange = [comment.range[0], comment.range[1]]; + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + return comment; + } + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], + comment, + len, + i, + cursor; + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + return tree; + } + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { + return clone({}); + }; + return exports; + })(exports); + /* vim: set sw=4 ts=4 et tw=80 : */ +}); + +var parser = createCommonjsModule(function (module) { + /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function (root, factory) { + if ( module.exports) { + module.exports = factory(); + } + })(commonjsGlobal, function () { + + function peg$subclass(child, parent) { + function ctor() { + this.constructor = child; + } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + peg$subclass(peg$SyntaxError, Error); + peg$SyntaxError.buildMessage = function (expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function literal(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + "class": function _class(expectation) { + var escapedParts = "", + i; + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); + } + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + any: function any(expectation) { + return "any character"; + }, + end: function end(expectation) { + return "end of input"; + }, + other: function other(expectation) { + return expectation.description; + } + }; + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + function literalEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function classEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/\]/g, '\\]').replace(/\^/g, '\\^').replace(/-/g, '\\-').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, + j; + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + descriptions.sort(); + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + switch (descriptions.length) { + case 1: + return descriptions[0]; + case 2: + return descriptions[0] + " or " + descriptions[1]; + default: + return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; + } + } + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + var peg$FAILED = {}, + peg$startRuleFunctions = { + start: peg$parsestart + }, + peg$startRuleFunction = peg$parsestart, + peg$c0 = function peg$c0(ss) { + return ss.length === 1 ? ss[0] : { + type: 'matches', + selectors: ss + }; + }, + peg$c1 = function peg$c1() { + return void 0; + }, + peg$c2 = " ", + peg$c3 = peg$literalExpectation(" ", false), + peg$c4 = /^[^ [\],():#!=><~+.]/, + peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), + peg$c6 = function peg$c6(i) { + return i.join(''); + }, + peg$c7 = ">", + peg$c8 = peg$literalExpectation(">", false), + peg$c9 = function peg$c9() { + return 'child'; + }, + peg$c10 = "~", + peg$c11 = peg$literalExpectation("~", false), + peg$c12 = function peg$c12() { + return 'sibling'; + }, + peg$c13 = "+", + peg$c14 = peg$literalExpectation("+", false), + peg$c15 = function peg$c15() { + return 'adjacent'; + }, + peg$c16 = function peg$c16() { + return 'descendant'; + }, + peg$c17 = ",", + peg$c18 = peg$literalExpectation(",", false), + peg$c19 = function peg$c19(s, ss) { + return [s].concat(ss.map(function (s) { + return s[3]; + })); + }, + peg$c20 = function peg$c20(op, s) { + if (!op) return s; + return { + type: op, + left: { + type: 'exactNode' + }, + right: s + }; + }, + peg$c21 = function peg$c21(a, ops) { + return ops.reduce(function (memo, rhs) { + return { + type: rhs[0], + left: memo, + right: rhs[1] + }; + }, a); + }, + peg$c22 = "!", + peg$c23 = peg$literalExpectation("!", false), + peg$c24 = function peg$c24(subject, as) { + var b = as.length === 1 ? as[0] : { + type: 'compound', + selectors: as + }; + if (subject) b.subject = true; + return b; + }, + peg$c25 = "*", + peg$c26 = peg$literalExpectation("*", false), + peg$c27 = function peg$c27(a) { + return { + type: 'wildcard', + value: a + }; + }, + peg$c28 = "#", + peg$c29 = peg$literalExpectation("#", false), + peg$c30 = function peg$c30(i) { + return { + type: 'identifier', + value: i + }; + }, + peg$c31 = "[", + peg$c32 = peg$literalExpectation("[", false), + peg$c33 = "]", + peg$c34 = peg$literalExpectation("]", false), + peg$c35 = function peg$c35(v) { + return v; + }, + peg$c36 = /^[>", "<", "!"], false, false), + peg$c38 = "=", + peg$c39 = peg$literalExpectation("=", false), + peg$c40 = function peg$c40(a) { + return (a || '') + '='; + }, + peg$c41 = /^[><]/, + peg$c42 = peg$classExpectation([">", "<"], false, false), + peg$c43 = ".", + peg$c44 = peg$literalExpectation(".", false), + peg$c45 = function peg$c45(a, as) { + return [].concat.apply([a], as).join(''); + }, + peg$c46 = function peg$c46(name, op, value) { + return { + type: 'attribute', + name: name, + operator: op, + value: value + }; + }, + peg$c47 = function peg$c47(name) { + return { + type: 'attribute', + name: name + }; + }, + peg$c48 = "\"", + peg$c49 = peg$literalExpectation("\"", false), + peg$c50 = /^[^\\"]/, + peg$c51 = peg$classExpectation(["\\", "\""], true, false), + peg$c52 = "\\", + peg$c53 = peg$literalExpectation("\\", false), + peg$c54 = peg$anyExpectation(), + peg$c55 = function peg$c55(a, b) { + return a + b; + }, + peg$c56 = function peg$c56(d) { + return { + type: 'literal', + value: strUnescape(d.join('')) + }; + }, + peg$c57 = "'", + peg$c58 = peg$literalExpectation("'", false), + peg$c59 = /^[^\\']/, + peg$c60 = peg$classExpectation(["\\", "'"], true, false), + peg$c61 = /^[0-9]/, + peg$c62 = peg$classExpectation([["0", "9"]], false, false), + peg$c63 = function peg$c63(a, b) { + // Can use `a.flat().join('')` once supported + var leadingDecimals = a ? [].concat.apply([], a).join('') : ''; + return { + type: 'literal', + value: parseFloat(leadingDecimals + b.join('')) + }; + }, + peg$c64 = function peg$c64(i) { + return { + type: 'literal', + value: i + }; + }, + peg$c65 = "type(", + peg$c66 = peg$literalExpectation("type(", false), + peg$c67 = /^[^ )]/, + peg$c68 = peg$classExpectation([" ", ")"], true, false), + peg$c69 = ")", + peg$c70 = peg$literalExpectation(")", false), + peg$c71 = function peg$c71(t) { + return { + type: 'type', + value: t.join('') + }; + }, + peg$c72 = /^[imsu]/, + peg$c73 = peg$classExpectation(["i", "m", "s", "u"], false, false), + peg$c74 = "/", + peg$c75 = peg$literalExpectation("/", false), + peg$c76 = /^[^\/]/, + peg$c77 = peg$classExpectation(["/"], true, false), + peg$c78 = function peg$c78(d, flgs) { + return { + type: 'regexp', + value: new RegExp(d.join(''), flgs ? flgs.join('') : '') + }; + }, + peg$c79 = function peg$c79(i, is) { + return { + type: 'field', + name: is.reduce(function (memo, p) { + return memo + p[0] + p[1]; + }, i) + }; + }, + peg$c80 = ":not(", + peg$c81 = peg$literalExpectation(":not(", false), + peg$c82 = function peg$c82(ss) { + return { + type: 'not', + selectors: ss + }; + }, + peg$c83 = ":matches(", + peg$c84 = peg$literalExpectation(":matches(", false), + peg$c85 = function peg$c85(ss) { + return { + type: 'matches', + selectors: ss + }; + }, + peg$c86 = ":has(", + peg$c87 = peg$literalExpectation(":has(", false), + peg$c88 = function peg$c88(ss) { + return { + type: 'has', + selectors: ss + }; + }, + peg$c89 = ":first-child", + peg$c90 = peg$literalExpectation(":first-child", false), + peg$c91 = function peg$c91() { + return nth(1); + }, + peg$c92 = ":last-child", + peg$c93 = peg$literalExpectation(":last-child", false), + peg$c94 = function peg$c94() { + return nthLast(1); + }, + peg$c95 = ":nth-child(", + peg$c96 = peg$literalExpectation(":nth-child(", false), + peg$c97 = function peg$c97(n) { + return nth(parseInt(n.join(''), 10)); + }, + peg$c98 = ":nth-last-child(", + peg$c99 = peg$literalExpectation(":nth-last-child(", false), + peg$c100 = function peg$c100(n) { + return nthLast(parseInt(n.join(''), 10)); + }, + peg$c101 = ":", + peg$c102 = peg$literalExpectation(":", false), + peg$c103 = function peg$c103(c) { + return { + type: 'class', + name: c + }; + }, + peg$currPos = 0, + peg$posDetailsCache = [{ + line: 1, + column: 1 + }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$resultsCache = {}, + peg$result; + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + function peg$literalExpectation(text, ignoreCase) { + return { + type: "literal", + text: text, + ignoreCase: ignoreCase + }; + } + function peg$classExpectation(parts, inverted, ignoreCase) { + return { + type: "class", + parts: parts, + inverted: inverted, + ignoreCase: ignoreCase + }; + } + function peg$anyExpectation() { + return { + type: "any" + }; + } + function peg$endExpectation() { + return { + type: "end" + }; + } + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], + p; + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + p++; + } + peg$posDetailsCache[pos] = details; + return details; + } + } + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { + return; + } + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + peg$maxFailExpected.push(expected); + } + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location); + } + function peg$parsestart() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 0, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$parseselectors(); + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c0(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s1 = peg$c1(); + } + s0 = s1; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parse_() { + var s0, s1; + var key = peg$currPos * 32 + 1, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifierName() { + var s0, s1, s2; + var key = peg$currPos * 32 + 2, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = []; + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s1 = peg$c6(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsebinaryOp() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 3, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c8); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c9(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c10; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c11); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c12(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c13; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c14); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c15(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s1 = peg$c16(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 32 + 4, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsehasSelector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 32 + 5, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseselector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelector() { + var s0, s1, s2; + var key = peg$currPos * 32 + 6, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsebinaryOp(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseselector(); + if (s2 !== peg$FAILED) { + s1 = peg$c20(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselector() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 7, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsesequence(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c21(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsesequence() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 8, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseatom(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseatom(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c24(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseatom() { + var s0; + var key = peg$currPos * 32 + 9, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$parsewildcard(); + if (s0 === peg$FAILED) { + s0 = peg$parseidentifier(); + if (s0 === peg$FAILED) { + s0 = peg$parseattr(); + if (s0 === peg$FAILED) { + s0 = peg$parsefield(); + if (s0 === peg$FAILED) { + s0 = peg$parsenegation(); + if (s0 === peg$FAILED) { + s0 = peg$parsematches(); + if (s0 === peg$FAILED) { + s0 = peg$parsehas(); + if (s0 === peg$FAILED) { + s0 = peg$parsefirstChild(); + if (s0 === peg$FAILED) { + s0 = peg$parselastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthLastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parseclass(); + } + } + } + } + } + } + } + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsewildcard() { + var s0, s1; + var key = peg$currPos * 32 + 10, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c25; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c26); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c27(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifier() { + var s0, s1, s2; + var key = peg$currPos * 32 + 11, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c28; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c30(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattr() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 12, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c32); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrValue(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c33; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c34); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c35(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrOps() { + var s0, s1, s2; + var key = peg$currPos * 32 + 13, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (peg$c36.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (peg$c41.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + { + peg$fail(peg$c42); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrEqOps() { + var s0, s1, s2; + var key = peg$currPos * 32 + 14, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrName() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 15, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c45(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrValue() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 16, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrEqOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetype(); + if (s5 === peg$FAILED) { + s5 = peg$parseregex(); + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsestring(); + if (s5 === peg$FAILED) { + s5 = peg$parsenumber(); + if (s5 === peg$FAILED) { + s5 = peg$parsepath(); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s1 = peg$c47(s1); + } + s0 = s1; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsestring() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 17, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c48; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c48; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c57; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c57; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenumber() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 18, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c43; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c63(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsepath() { + var s0, s1; + var key = peg$currPos * 32 + 19, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s1 = peg$c64(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsetype() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 20, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c65) { + s1 = peg$c65; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c66); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c71(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseflags() { + var s0, s1; + var key = peg$currPos * 32 + 21, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + } + } else { + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseregex() { + var s0, s1, s2, s3, s4; + var key = peg$currPos * 32 + 22, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c74; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c76.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c77); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c76.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c77); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s3 = peg$c74; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseflags(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = peg$c78(s2, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefield() { + var s0, s1, s2, s3, s4, s5, s6; + var key = peg$currPos * 32 + 23, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c43; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c79(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenegation() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 24, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c80) { + s1 = peg$c80; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c81); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c82(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsematches() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 25, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c83) { + s1 = peg$c83; + peg$currPos += 9; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c84); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c85(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehas() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 26, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c86) { + s1 = peg$c86; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c87); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehasSelectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c88(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefirstChild() { + var s0, s1; + var key = peg$currPos * 32 + 27, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 12) === peg$c89) { + s1 = peg$c89; + peg$currPos += 12; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c90); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c91(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parselastChild() { + var s0, s1; + var key = peg$currPos * 32 + 28, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c92) { + s1 = peg$c92; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c93); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c94(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 29, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c95) { + s1 = peg$c95; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c96); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c97(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthLastChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 30, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 16) === peg$c98) { + s1 = peg$c98; + peg$currPos += 16; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c99); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c100(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseclass() { + var s0, s1, s2; + var key = peg$currPos * 32 + 31, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c101; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c102); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c103(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function nth(n) { + return { + type: 'nth-child', + index: { + type: 'literal', + value: n + } + }; + } + function nthLast(n) { + return { + type: 'nth-last-child', + index: { + type: 'literal', + value: n + } + }; + } + function strUnescape(s) { + return s.replace(/\\(.)/g, function (match, ch) { + switch (ch) { + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + default: + return ch; + } + }); + } + peg$result = peg$startRuleFunction(); + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); + } + } + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + }); +}); + +/** +* @typedef {"LEFT_SIDE"|"RIGHT_SIDE"} Side +*/ + +var LEFT_SIDE = 'LEFT_SIDE'; +var RIGHT_SIDE = 'RIGHT_SIDE'; + +/** + * @external AST + * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html + */ + +/** + * One of the rules of `grammar.pegjs` + * @typedef {PlainObject} SelectorAST + * @see grammar.pegjs +*/ + +/** + * The `sequence` production of `grammar.pegjs` + * @typedef {PlainObject} SelectorSequenceAST +*/ + +/** + * Get the value of a property which may be multiple levels down + * in the object. + * @param {?PlainObject} obj + * @param {string[]} keys + * @returns {undefined|boolean|string|number|external:AST} + */ +function getPath(obj, keys) { + for (var i = 0; i < keys.length; ++i) { + if (obj == null) { + return obj; + } + obj = obj[keys[i]]; + } + return obj; +} + +/** + * Determine whether `node` can be reached by following `path`, + * starting at `ancestor`. + * @param {?external:AST} node + * @param {?external:AST} ancestor + * @param {string[]} path + * @param {Integer} fromPathIndex + * @returns {boolean} + */ +function inPath(node, ancestor, path, fromPathIndex) { + var current = ancestor; + for (var i = fromPathIndex; i < path.length; ++i) { + if (current == null) { + return false; + } + var field = current[path[i]]; + if (Array.isArray(field)) { + for (var k = 0; k < field.length; ++k) { + if (inPath(node, field[k], path, i + 1)) { + return true; + } + } + return false; + } + current = field; + } + return node === current; +} + +/** + * A generated matcher function for a selector. + * @callback SelectorMatcher + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @returns {void} +*/ + +/** + * A WeakMap for holding cached matcher functions for selectors. + * @type {WeakMap} +*/ +var MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap() : null; + +/** + * Look up a matcher function for `selector` in the cache. + * If it does not exist, generate it with `generateMatcher` and add it to the cache. + * In engines without WeakMap, the caching is skipped and matchers are generated with every call. + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ +function getMatcher(selector) { + if (selector == null) { + return function () { + return true; + }; + } + if (MATCHER_CACHE != null) { + var matcher = MATCHER_CACHE.get(selector); + if (matcher != null) { + return matcher; + } + matcher = generateMatcher(selector); + MATCHER_CACHE.set(selector, matcher); + return matcher; + } + return generateMatcher(selector); +} + +/** + * Create a matcher function for `selector`, + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ +function generateMatcher(selector) { + switch (selector.type) { + case 'wildcard': + return function () { + return true; + }; + case 'identifier': + { + var value = selector.value.toLowerCase(); + return function (node, ancestry, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return value === node[nodeTypeKey].toLowerCase(); + }; + } + case 'exactNode': + return function (node, ancestry) { + return ancestry.length === 0; + }; + case 'field': + { + var path = selector.name.split('.'); + return function (node, ancestry) { + var ancestor = ancestry[path.length - 1]; + return inPath(node, ancestor, path, 0); + }; + } + case 'matches': + { + var matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < matchers.length; ++i) { + if (matchers[i](node, ancestry, options)) { + return true; + } + } + return false; + }; + } + case 'compound': + { + var _matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers.length; ++i) { + if (!_matchers[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'not': + { + var _matchers2 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers2.length; ++i) { + if (_matchers2[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'has': + { + var _matchers3 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + var result = false; + var a = []; + estraverse.traverse(node, { + enter: function enter(node, parent) { + if (parent != null) { + a.unshift(parent); + } + for (var i = 0; i < _matchers3.length; ++i) { + if (_matchers3[i](node, a, options)) { + result = true; + this["break"](); + return; + } + } + }, + leave: function leave() { + a.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + return result; + }; + } + case 'child': + { + var left = getMatcher(selector.left); + var right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (ancestry.length > 0 && right(node, ancestry, options)) { + return left(ancestry[0], ancestry.slice(1), options); + } + return false; + }; + } + case 'descendant': + { + var _left = getMatcher(selector.left); + var _right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (_right(node, ancestry, options)) { + for (var i = 0, l = ancestry.length; i < l; ++i) { + if (_left(ancestry[i], ancestry.slice(i + 1), options)) { + return true; + } + } + } + return false; + }; + } + case 'attribute': + { + var _path = selector.name.split('.'); + switch (selector.operator) { + case void 0: + return function (node) { + return getPath(node, _path) != null; + }; + case '=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + var p = getPath(node, _path); + return typeof p === 'string' && selector.value.value.test(p); + }; + case 'literal': + { + var literal = "".concat(selector.value.value); + return function (node) { + return literal === "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value === _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '!=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + return !selector.value.value.test(getPath(node, _path)); + }; + case 'literal': + { + var _literal = "".concat(selector.value.value); + return function (node) { + return _literal !== "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value !== _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '<=': + return function (node) { + return getPath(node, _path) <= selector.value.value; + }; + case '<': + return function (node) { + return getPath(node, _path) < selector.value.value; + }; + case '>': + return function (node) { + return getPath(node, _path) > selector.value.value; + }; + case '>=': + return function (node) { + return getPath(node, _path) >= selector.value.value; + }; + } + throw new Error("Unknown operator: ".concat(selector.operator)); + } + case 'sibling': + { + var _left2 = getMatcher(selector.left); + var _right2 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right2(node, ancestry, options) && sibling(node, _left2, ancestry, LEFT_SIDE, options) || selector.left.subject && _left2(node, ancestry, options) && sibling(node, _right2, ancestry, RIGHT_SIDE, options); + }; + } + case 'adjacent': + { + var _left3 = getMatcher(selector.left); + var _right3 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right3(node, ancestry, options) && adjacent(node, _left3, ancestry, LEFT_SIDE, options) || selector.right.subject && _left3(node, ancestry, options) && adjacent(node, _right3, ancestry, RIGHT_SIDE, options); + }; + } + case 'nth-child': + { + var nth = selector.index.value; + var _right4 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right4(node, ancestry, options) && nthChild(node, ancestry, nth, options); + }; + } + case 'nth-last-child': + { + var _nth = -selector.index.value; + var _right5 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right5(node, ancestry, options) && nthChild(node, ancestry, _nth, options); + }; + } + case 'class': + { + var name = selector.name.toLowerCase(); + return function (node, ancestry, options) { + if (options && options.matchClass) { + return options.matchClass(selector.name, node, ancestry); + } + if (options && options.nodeTypeKey) return false; + switch (name) { + case 'statement': + if (node.type.slice(-9) === 'Statement') return true; + // fallthrough: interface Declaration <: Statement { } + case 'declaration': + return node.type.slice(-11) === 'Declaration'; + case 'pattern': + if (node.type.slice(-7) === 'Pattern') return true; + // fallthrough: interface Expression <: Node, Pattern { } + case 'expression': + return node.type.slice(-10) === 'Expression' || node.type.slice(-7) === 'Literal' || node.type === 'Identifier' && (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty') || node.type === 'MetaProperty'; + case 'function': + return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; + } + throw new Error("Unknown class name: ".concat(selector.name)); + }; + } + } + throw new Error("Unknown selector type: ".concat(selector.type)); +} + +/** + * @callback TraverseOptionFallback + * @param {external:AST} node The given node. + * @returns {string[]} An array of visitor keys for the given node. + */ + +/** + * @callback ClassMatcher + * @param {string} className The name of the class to match. + * @param {external:AST} node The node to match against. + * @param {Array} ancestry The ancestry of the node. + * @returns {boolean} True if the node matches the class, false if not. + */ + +/** + * @typedef {object} ESQueryOptions + * @property {string} [nodeTypeKey="type"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery. + * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node. + * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes. + * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes. + */ + +/** + * Given a `node` and its ancestors, determine if `node` is matched + * by `selector`. + * @param {?external:AST} node + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @throws {Error} Unknowns (operator, class name, selector type, or + * selector value type) + * @returns {boolean} + */ +function matches(node, selector, ancestry, options) { + if (!selector) { + return true; + } + if (!node) { + return false; + } + if (!ancestry) { + ancestry = []; + } + return getMatcher(selector)(node, ancestry, options); +} + +/** + * Get visitor keys of a given node. + * @param {external:AST} node The AST node to get keys. + * @param {ESQueryOptions|undefined} options + * @returns {string[]} Visitor keys of the node. + */ +function getVisitorKeys(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + var nodeType = node[nodeTypeKey]; + if (options && options.visitorKeys && options.visitorKeys[nodeType]) { + return options.visitorKeys[nodeType]; + } + if (estraverse.VisitorKeys[nodeType]) { + return estraverse.VisitorKeys[nodeType]; + } + if (options && typeof options.fallback === 'function') { + return options.fallback(node); + } + // 'iteration' fallback + return Object.keys(node).filter(function (key) { + return key !== nodeTypeKey; + }); +} + +/** + * Check whether the given value is an ASTNode or not. + * @param {any} node The value to check. + * @param {ESQueryOptions|undefined} options The options to use. + * @returns {boolean} `true` if the value is an ASTNode. + */ +function isNode(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return node !== null && _typeof(node) === 'object' && typeof node[nodeTypeKey] === 'string'; +} + +/** + * Determines if the given node has a sibling that matches the + * given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ +function sibling(node, matcher, ancestry, side, options) { + var _ancestry = _slicedToArray(ancestry, 1), + parent = _ancestry[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var startIndex = listProp.indexOf(node); + if (startIndex < 0) { + continue; + } + var lowerBound = void 0, + upperBound = void 0; + if (side === LEFT_SIDE) { + lowerBound = 0; + upperBound = startIndex; + } else { + lowerBound = startIndex + 1; + upperBound = listProp.length; + } + for (var k = lowerBound; k < upperBound; ++k) { + if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) { + return true; + } + } + } + } + return false; +} + +/** + * Determines if the given node has an adjacent sibling that matches + * the given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ +function adjacent(node, matcher, ancestry, side, options) { + var _ancestry2 = _slicedToArray(ancestry, 1), + parent = _ancestry2[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = listProp.indexOf(node); + if (idx < 0) { + continue; + } + if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) { + return true; + } + if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) { + return true; + } + } + } + return false; +} + +/** + * Determines if the given node is the `nth` child. + * If `nth` is negative then the position is counted + * from the end of the list of children. + * @param {external:AST} node + * @param {external:AST[]} ancestry + * @param {Integer} nth + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ +function nthChild(node, ancestry, nth, options) { + if (nth === 0) { + return false; + } + var _ancestry3 = _slicedToArray(ancestry, 1), + parent = _ancestry3[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = nth < 0 ? listProp.length + nth : nth - 1; + if (idx >= 0 && idx < listProp.length && listProp[idx] === node) { + return true; + } + } + } + return false; +} + +/** + * For each selector node marked as a subject, find the portion of the + * selector that the subject must match. + * @param {SelectorAST} selector + * @param {SelectorAST} [ancestor] Defaults to `selector` + * @returns {SelectorAST[]} + */ +function subjects(selector, ancestor) { + if (selector == null || _typeof(selector) != 'object') { + return []; + } + if (ancestor == null) { + ancestor = selector; + } + var results = selector.subject ? [ancestor] : []; + var keys = Object.keys(selector); + for (var i = 0; i < keys.length; ++i) { + var p = keys[i]; + var sel = selector[p]; + results.push.apply(results, _toConsumableArray(subjects(sel, p === 'left' ? sel : ancestor))); + } + return results; +} + +/** +* @callback TraverseVisitor +* @param {?external:AST} node +* @param {?external:AST} parent +* @param {external:AST[]} ancestry +*/ + +/** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {TraverseVisitor} visitor + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ +function traverse(ast, selector, visitor, options) { + if (!selector) { + return; + } + var ancestry = []; + var matcher = getMatcher(selector); + var altSubjects = subjects(selector).map(getMatcher); + estraverse.traverse(ast, { + enter: function enter(node, parent) { + if (parent != null) { + ancestry.unshift(parent); + } + if (matcher(node, ancestry, options)) { + if (altSubjects.length) { + for (var i = 0, l = altSubjects.length; i < l; ++i) { + if (altSubjects[i](node, ancestry, options)) { + visitor(node, parent, ancestry); + } + for (var k = 0, m = ancestry.length; k < m; ++k) { + var succeedingAncestry = ancestry.slice(k + 1); + if (altSubjects[i](ancestry[k], succeedingAncestry, options)) { + visitor(ancestry[k], parent, succeedingAncestry); + } + } + } + } else { + visitor(node, parent, ancestry); + } + } + }, + leave: function leave() { + ancestry.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); +} + +/** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ +function match(ast, selector, options) { + var results = []; + traverse(ast, selector, function (node) { + results.push(node); + }, options); + return results; +} + +/** + * Parse a selector string and return its AST. + * @param {string} selector + * @returns {SelectorAST} + */ +function parse(selector) { + return parser.parse(selector); +} + +/** + * Query the code AST using the selector string. + * @param {external:AST} ast + * @param {string} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ +function query(ast, selector, options) { + return match(ast, parse(selector), options); +} +query.parse = parse; +query.match = match; +query.traverse = traverse; +query.matches = matches; +query.query = query; + +export default query; diff --git a/node_modules/esquery/dist/esquery.esm.min.js b/node_modules/esquery/dist/esquery.esm.min.js new file mode 100644 index 00000000..ca723b80 --- /dev/null +++ b/node_modules/esquery/dist/esquery.esm.min.js @@ -0,0 +1,2 @@ +function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,s=[],u=!0,l=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){l=!0,o=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(l)throw o}}return s}}(e,t)||n(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||n(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(e,t){if(e){if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0;--r)if(e[r].node===t)return!0;return!1}function d(e,t){return(new f).traverse(e,t)}function m(e,t){var r;return r=function(e,t){var r,n,o,a;for(n=e.length,o=0;n;)t(e[a=o+(r=n>>>1)])?n=r:(o=a+1,n-=r+1);return o}(t,(function(t){return t.range[0]>e.range[0]})),e.extendedRange=[e.range[0],e.range[1]],r!==t.length&&(e.extendedRange[1]=t[r].range[0]),(r-=1)>=0&&(e.extendedRange[0]=t[r].range[1]),e}return r={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ChainExpression:"ChainExpression",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",PrivateIdentifier:"PrivateIdentifier",Program:"Program",Property:"Property",PropertyDefinition:"PropertyDefinition",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},o={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ChainExpression:["expression"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateIdentifier:[],Program:["body"],Property:["key","value"],PropertyDefinition:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],Super:[],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]},n={Break:a={},Skip:i={},Remove:s={}},l.prototype.replace=function(e){this.parent[this.key]=e},l.prototype.remove=function(){return Array.isArray(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},f.prototype.path=function(){var e,t,r,n,o;function a(e,t){if(Array.isArray(t))for(r=0,n=t.length;r=0;)if(v=s[f=x[d]])if(Array.isArray(v)){for(m=v.length;(m-=1)>=0;)if(v[m]&&!y(n,v[m])){if(h(u,x[d]))o=new c(v[m],[f,m],"Property",null);else{if(!p(v[m]))continue;o=new c(v[m],[f,m],null,null)}r.push(o)}}else if(p(v)){if(y(n,v))continue;r.push(new c(v,f,null,null))}}}else if(o=n.pop(),l=this.__execute(t.leave,o),this.__state===a||l===a)return},f.prototype.replace=function(e,t){var r,n,o,u,f,y,d,m,x,v,g,A,E;function b(e){var t,n,o,a;if(e.ref.remove())for(n=e.ref.key,a=e.ref.parent,t=r.length;t--;)if((o=r[t]).ref&&o.ref.parent===a){if(o.ref.key=0;)if(v=o[E=x[d]])if(Array.isArray(v)){for(m=v.length;(m-=1)>=0;)if(v[m]){if(h(u,x[d]))y=new c(v[m],[E,m],"Property",new l(v,m));else{if(!p(v[m]))continue;y=new c(v[m],[E,m],null,new l(v,m))}r.push(y)}}else p(v)&&r.push(new c(v,E,null,new l(o,E)))}}else if(y=n.pop(),void 0!==(f=this.__execute(t.leave,y))&&f!==a&&f!==i&&f!==s&&y.ref.replace(f),this.__state!==s&&f!==s||b(y),this.__state===a||f===a)return A.root;return A.root},t.Syntax=r,t.traverse=d,t.replace=function(e,t){return(new f).replace(e,t)},t.attachComments=function(e,t,r){var o,a,i,s,l=[];if(!e.range)throw new Error("attachComments needs range information");if(!r.length){if(t.length){for(i=0,a=t.length;ie.range[0]);)t.extendedRange[1]===e.range[0]?(e.leadingComments||(e.leadingComments=[]),e.leadingComments.push(t),l.splice(s,1)):s+=1;return s===l.length?n.Break:l[s].extendedRange[0]>e.range[1]?n.Skip:void 0}}),s=0,d(e,{leave:function(e){for(var t;se.range[1]?n.Skip:void 0}}),e},t.VisitorKeys=o,t.VisitorOption=n,t.Controller=f,t.cloneEnvironment=function(){return e({})},t}(t)})),s=a((function(e){e.exports&&(e.exports=function(){function e(t,r,n,o){this.message=t,this.expected=r,this.found=n,this.location=o,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}return function(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}(e,Error),e.buildMessage=function(e,t){var r={literal:function(e){return'"'+o(e.text)+'"'},class:function(e){var t,r="";for(t=0;t0){for(t=1,n=1;t<~+.]/,p=pe([" ","[","]",",","(",")",":","#","!","=",">","<","~","+","."],!0,!1),h=fe(">",!1),y=fe("~",!1),d=fe("+",!1),m=fe(",",!1),x=function(e,t){return[e].concat(t.map((function(e){return e[3]})))},v=fe("!",!1),g=fe("*",!1),A=fe("#",!1),E=fe("[",!1),b=fe("]",!1),S=/^[>","<","!"],!1,!1),C=fe("=",!1),w=function(e){return(e||"")+"="},P=/^[><]/,k=pe([">","<"],!1,!1),D=fe(".",!1),I=function(e,t,r){return{type:"attribute",name:e,operator:t,value:r}},j=fe('"',!1),T=/^[^\\"]/,F=pe(["\\",'"'],!0,!1),R=fe("\\",!1),O={type:"any"},L=function(e,t){return e+t},M=function(e){return{type:"literal",value:(t=e.join(""),t.replace(/\\(.)/g,(function(e,t){switch(t){case"b":return"\b";case"f":return"\f";case"n":return"\n";case"r":return"\r";case"t":return"\t";case"v":return"\v";default:return t}})))};var t},B=fe("'",!1),U=/^[^\\']/,K=pe(["\\","'"],!0,!1),N=/^[0-9]/,W=pe([["0","9"]],!1,!1),V=fe("type(",!1),q=/^[^ )]/,G=pe([" ",")"],!0,!1),z=fe(")",!1),H=/^[imsu]/,Y=pe(["i","m","s","u"],!1,!1),$=fe("/",!1),J=/^[^\/]/,Q=pe(["/"],!0,!1),X=fe(":not(",!1),Z=fe(":matches(",!1),ee=fe(":has(",!1),te=fe(":first-child",!1),re=fe(":last-child",!1),ne=fe(":nth-child(",!1),oe=fe(":nth-last-child(",!1),ae=fe(":",!1),ie=0,se=[{line:1,column:1}],ue=0,le=[],ce={};if("startRule"in r){if(!(r.startRule in u))throw new Error("Can't start parsing from rule \""+r.startRule+'".');l=u[r.startRule]}function fe(e,t){return{type:"literal",text:e,ignoreCase:t}}function pe(e,t,r){return{type:"class",parts:e,inverted:t,ignoreCase:r}}function he(e){var r,n=se[e];if(n)return n;for(r=e-1;!se[r];)r--;for(n={line:(n=se[r]).line,column:n.column};rue&&(ue=ie,le=[]),le.push(e))}function me(){var e,t,r,n,o=32*ie+0,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,(t=xe())!==s&&(r=Ae())!==s&&xe()!==s?e=t=1===(n=r).length?n[0]:{type:"matches",selectors:n}:(ie=e,e=s),e===s&&(e=ie,(t=xe())!==s&&(t=void 0),e=t),ce[o]={nextPos:ie,result:e},e)}function xe(){var e,r,n=32*ie+1,o=ce[n];if(o)return ie=o.nextPos,o.result;for(e=[],32===t.charCodeAt(ie)?(r=" ",ie++):(r=s,de(c));r!==s;)e.push(r),32===t.charCodeAt(ie)?(r=" ",ie++):(r=s,de(c));return ce[n]={nextPos:ie,result:e},e}function ve(){var e,r,n,o=32*ie+2,a=ce[o];if(a)return ie=a.nextPos,a.result;if(r=[],f.test(t.charAt(ie))?(n=t.charAt(ie),ie++):(n=s,de(p)),n!==s)for(;n!==s;)r.push(n),f.test(t.charAt(ie))?(n=t.charAt(ie),ie++):(n=s,de(p));else r=s;return r!==s&&(r=r.join("")),e=r,ce[o]={nextPos:ie,result:e},e}function ge(){var e,r,n,o=32*ie+3,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,(r=xe())!==s?(62===t.charCodeAt(ie)?(n=">",ie++):(n=s,de(h)),n!==s&&xe()!==s?e=r="child":(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,(r=xe())!==s?(126===t.charCodeAt(ie)?(n="~",ie++):(n=s,de(y)),n!==s&&xe()!==s?e=r="sibling":(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,(r=xe())!==s?(43===t.charCodeAt(ie)?(n="+",ie++):(n=s,de(d)),n!==s&&xe()!==s?e=r="adjacent":(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,32===t.charCodeAt(ie)?(r=" ",ie++):(r=s,de(c)),r!==s&&(n=xe())!==s?e=r="descendant":(ie=e,e=s)))),ce[o]={nextPos:ie,result:e},e)}function Ae(){var e,r,n,o,a,i,u,l,c=32*ie+5,f=ce[c];if(f)return ie=f.nextPos,f.result;if(e=ie,(r=be())!==s){for(n=[],o=ie,(a=xe())!==s?(44===t.charCodeAt(ie)?(i=",",ie++):(i=s,de(m)),i!==s&&(u=xe())!==s&&(l=be())!==s?o=a=[a,i,u,l]:(ie=o,o=s)):(ie=o,o=s);o!==s;)n.push(o),o=ie,(a=xe())!==s?(44===t.charCodeAt(ie)?(i=",",ie++):(i=s,de(m)),i!==s&&(u=xe())!==s&&(l=be())!==s?o=a=[a,i,u,l]:(ie=o,o=s)):(ie=o,o=s);n!==s?e=r=x(r,n):(ie=e,e=s)}else ie=e,e=s;return ce[c]={nextPos:ie,result:e},e}function Ee(){var e,t,r,n,o,a=32*ie+6,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,(t=ge())===s&&(t=null),t!==s&&(r=be())!==s?(o=r,e=t=(n=t)?{type:n,left:{type:"exactNode"},right:o}:o):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}function be(){var e,t,r,n,o,a,i,u=32*ie+7,l=ce[u];if(l)return ie=l.nextPos,l.result;if(e=ie,(t=Se())!==s){for(r=[],n=ie,(o=ge())!==s&&(a=Se())!==s?n=o=[o,a]:(ie=n,n=s);n!==s;)r.push(n),n=ie,(o=ge())!==s&&(a=Se())!==s?n=o=[o,a]:(ie=n,n=s);r!==s?(i=t,e=t=r.reduce((function(e,t){return{type:t[0],left:e,right:t[1]}}),i)):(ie=e,e=s)}else ie=e,e=s;return ce[u]={nextPos:ie,result:e},e}function Se(){var e,r,n,o,a,i,u,l=32*ie+8,c=ce[l];if(c)return ie=c.nextPos,c.result;if(e=ie,33===t.charCodeAt(ie)?(r="!",ie++):(r=s,de(v)),r===s&&(r=null),r!==s){if(n=[],(o=_e())!==s)for(;o!==s;)n.push(o),o=_e();else n=s;n!==s?(a=r,u=1===(i=n).length?i[0]:{type:"compound",selectors:i},a&&(u.subject=!0),e=r=u):(ie=e,e=s)}else ie=e,e=s;return ce[l]={nextPos:ie,result:e},e}function _e(){var e,r=32*ie+9,n=ce[r];return n?(ie=n.nextPos,n.result):((e=function(){var e,r,n=32*ie+10,o=ce[n];return o?(ie=o.nextPos,o.result):(42===t.charCodeAt(ie)?(r="*",ie++):(r=s,de(g)),r!==s&&(r={type:"wildcard",value:r}),e=r,ce[n]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o=32*ie+11,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,35===t.charCodeAt(ie)?(r="#",ie++):(r=s,de(A)),r===s&&(r=null),r!==s&&(n=ve())!==s?e=r={type:"identifier",value:n}:(ie=e,e=s),ce[o]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=32*ie+12,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,91===t.charCodeAt(ie)?(r="[",ie++):(r=s,de(E)),r!==s&&xe()!==s&&(n=function(){var e,r,n,o,a=32*ie+16,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,(r=Ce())!==s&&xe()!==s&&(n=function(){var e,r,n,o=32*ie+14,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,33===t.charCodeAt(ie)?(r="!",ie++):(r=s,de(v)),r===s&&(r=null),r!==s?(61===t.charCodeAt(ie)?(n="=",ie++):(n=s,de(C)),n!==s?(r=w(r),e=r):(ie=e,e=s)):(ie=e,e=s),ce[o]={nextPos:ie,result:e},e)}())!==s&&xe()!==s?((o=function(){var e,r,n,o,a,i=32*ie+20,u=ce[i];if(u)return ie=u.nextPos,u.result;if(e=ie,"type("===t.substr(ie,5)?(r="type(",ie+=5):(r=s,de(V)),r!==s)if(xe()!==s){if(n=[],q.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(G)),o!==s)for(;o!==s;)n.push(o),q.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(G));else n=s;n!==s&&(o=xe())!==s?(41===t.charCodeAt(ie)?(a=")",ie++):(a=s,de(z)),a!==s?(r={type:"type",value:n.join("")},e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;else ie=e,e=s;return ce[i]={nextPos:ie,result:e},e}())===s&&(o=function(){var e,r,n,o,a,i,u=32*ie+22,l=ce[u];if(l)return ie=l.nextPos,l.result;if(e=ie,47===t.charCodeAt(ie)?(r="/",ie++):(r=s,de($)),r!==s){if(n=[],J.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(Q)),o!==s)for(;o!==s;)n.push(o),J.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(Q));else n=s;n!==s?(47===t.charCodeAt(ie)?(o="/",ie++):(o=s,de($)),o!==s?((a=function(){var e,r,n=32*ie+21,o=ce[n];if(o)return ie=o.nextPos,o.result;if(e=[],H.test(t.charAt(ie))?(r=t.charAt(ie),ie++):(r=s,de(Y)),r!==s)for(;r!==s;)e.push(r),H.test(t.charAt(ie))?(r=t.charAt(ie),ie++):(r=s,de(Y));else e=s;return ce[n]={nextPos:ie,result:e},e}())===s&&(a=null),a!==s?(i=a,r={type:"regexp",value:new RegExp(n.join(""),i?i.join(""):"")},e=r):(ie=e,e=s)):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;return ce[u]={nextPos:ie,result:e},e}()),o!==s?(r=I(r,n,o),e=r):(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,(r=Ce())!==s&&xe()!==s&&(n=function(){var e,r,n,o=32*ie+13,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,S.test(t.charAt(ie))?(r=t.charAt(ie),ie++):(r=s,de(_)),r===s&&(r=null),r!==s?(61===t.charCodeAt(ie)?(n="=",ie++):(n=s,de(C)),n!==s?(r=w(r),e=r):(ie=e,e=s)):(ie=e,e=s),e===s&&(P.test(t.charAt(ie))?(e=t.charAt(ie),ie++):(e=s,de(k))),ce[o]={nextPos:ie,result:e},e)}())!==s&&xe()!==s?((o=function(){var e,r,n,o,a,i,u=32*ie+17,l=ce[u];if(l)return ie=l.nextPos,l.result;if(e=ie,34===t.charCodeAt(ie)?(r='"',ie++):(r=s,de(j)),r!==s){for(n=[],T.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(F)),o===s&&(o=ie,92===t.charCodeAt(ie)?(a="\\",ie++):(a=s,de(R)),a!==s?(t.length>ie?(i=t.charAt(ie),ie++):(i=s,de(O)),i!==s?(a=L(a,i),o=a):(ie=o,o=s)):(ie=o,o=s));o!==s;)n.push(o),T.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(F)),o===s&&(o=ie,92===t.charCodeAt(ie)?(a="\\",ie++):(a=s,de(R)),a!==s?(t.length>ie?(i=t.charAt(ie),ie++):(i=s,de(O)),i!==s?(a=L(a,i),o=a):(ie=o,o=s)):(ie=o,o=s));n!==s?(34===t.charCodeAt(ie)?(o='"',ie++):(o=s,de(j)),o!==s?(r=M(n),e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;if(e===s)if(e=ie,39===t.charCodeAt(ie)?(r="'",ie++):(r=s,de(B)),r!==s){for(n=[],U.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(K)),o===s&&(o=ie,92===t.charCodeAt(ie)?(a="\\",ie++):(a=s,de(R)),a!==s?(t.length>ie?(i=t.charAt(ie),ie++):(i=s,de(O)),i!==s?(a=L(a,i),o=a):(ie=o,o=s)):(ie=o,o=s));o!==s;)n.push(o),U.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(K)),o===s&&(o=ie,92===t.charCodeAt(ie)?(a="\\",ie++):(a=s,de(R)),a!==s?(t.length>ie?(i=t.charAt(ie),ie++):(i=s,de(O)),i!==s?(a=L(a,i),o=a):(ie=o,o=s)):(ie=o,o=s));n!==s?(39===t.charCodeAt(ie)?(o="'",ie++):(o=s,de(B)),o!==s?(r=M(n),e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;return ce[u]={nextPos:ie,result:e},e}())===s&&(o=function(){var e,r,n,o,a,i,u,l=32*ie+18,c=ce[l];if(c)return ie=c.nextPos,c.result;for(e=ie,r=ie,n=[],N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));o!==s;)n.push(o),N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));if(n!==s?(46===t.charCodeAt(ie)?(o=".",ie++):(o=s,de(D)),o!==s?r=n=[n,o]:(ie=r,r=s)):(ie=r,r=s),r===s&&(r=null),r!==s){if(n=[],N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));else n=s;n!==s?(i=n,u=(a=r)?[].concat.apply([],a).join(""):"",r={type:"literal",value:parseFloat(u+i.join(""))},e=r):(ie=e,e=s)}else ie=e,e=s;return ce[l]={nextPos:ie,result:e},e}())===s&&(o=function(){var e,t,r=32*ie+19,n=ce[r];return n?(ie=n.nextPos,n.result):((t=ve())!==s&&(t={type:"literal",value:t}),e=t,ce[r]={nextPos:ie,result:e},e)}()),o!==s?(r=I(r,n,o),e=r):(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,(r=Ce())!==s&&(r={type:"attribute",name:r}),e=r)),ce[a]={nextPos:ie,result:e},e)}())!==s&&xe()!==s?(93===t.charCodeAt(ie)?(o="]",ie++):(o=s,de(b)),o!==s?e=r=n:(ie=e,e=s)):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a,i,u,l,c=32*ie+23,f=ce[c];if(f)return ie=f.nextPos,f.result;if(e=ie,46===t.charCodeAt(ie)?(r=".",ie++):(r=s,de(D)),r!==s)if((n=ve())!==s){for(o=[],a=ie,46===t.charCodeAt(ie)?(i=".",ie++):(i=s,de(D)),i!==s&&(u=ve())!==s?a=i=[i,u]:(ie=a,a=s);a!==s;)o.push(a),a=ie,46===t.charCodeAt(ie)?(i=".",ie++):(i=s,de(D)),i!==s&&(u=ve())!==s?a=i=[i,u]:(ie=a,a=s);o!==s?(l=n,r={type:"field",name:o.reduce((function(e,t){return e+t[0]+t[1]}),l)},e=r):(ie=e,e=s)}else ie=e,e=s;else ie=e,e=s;return ce[c]={nextPos:ie,result:e},e}())===s&&(e=function(){var e,r,n,o,a=32*ie+24,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,":not("===t.substr(ie,5)?(r=":not(",ie+=5):(r=s,de(X)),r!==s&&xe()!==s&&(n=Ae())!==s&&xe()!==s?(41===t.charCodeAt(ie)?(o=")",ie++):(o=s,de(z)),o!==s?e=r={type:"not",selectors:n}:(ie=e,e=s)):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=32*ie+25,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,":matches("===t.substr(ie,9)?(r=":matches(",ie+=9):(r=s,de(Z)),r!==s&&xe()!==s&&(n=Ae())!==s&&xe()!==s?(41===t.charCodeAt(ie)?(o=")",ie++):(o=s,de(z)),o!==s?e=r={type:"matches",selectors:n}:(ie=e,e=s)):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=32*ie+26,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,":has("===t.substr(ie,5)?(r=":has(",ie+=5):(r=s,de(ee)),r!==s&&xe()!==s&&(n=function(){var e,r,n,o,a,i,u,l,c=32*ie+4,f=ce[c];if(f)return ie=f.nextPos,f.result;if(e=ie,(r=Ee())!==s){for(n=[],o=ie,(a=xe())!==s?(44===t.charCodeAt(ie)?(i=",",ie++):(i=s,de(m)),i!==s&&(u=xe())!==s&&(l=Ee())!==s?o=a=[a,i,u,l]:(ie=o,o=s)):(ie=o,o=s);o!==s;)n.push(o),o=ie,(a=xe())!==s?(44===t.charCodeAt(ie)?(i=",",ie++):(i=s,de(m)),i!==s&&(u=xe())!==s&&(l=Ee())!==s?o=a=[a,i,u,l]:(ie=o,o=s)):(ie=o,o=s);n!==s?e=r=x(r,n):(ie=e,e=s)}else ie=e,e=s;return ce[c]={nextPos:ie,result:e},e}())!==s&&xe()!==s?(41===t.charCodeAt(ie)?(o=")",ie++):(o=s,de(z)),o!==s?e=r={type:"has",selectors:n}:(ie=e,e=s)):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n=32*ie+27,o=ce[n];return o?(ie=o.nextPos,o.result):(":first-child"===t.substr(ie,12)?(r=":first-child",ie+=12):(r=s,de(te)),r!==s&&(r=we(1)),e=r,ce[n]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n=32*ie+28,o=ce[n];return o?(ie=o.nextPos,o.result):(":last-child"===t.substr(ie,11)?(r=":last-child",ie+=11):(r=s,de(re)),r!==s&&(r=Pe(1)),e=r,ce[n]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a,i=32*ie+29,u=ce[i];if(u)return ie=u.nextPos,u.result;if(e=ie,":nth-child("===t.substr(ie,11)?(r=":nth-child(",ie+=11):(r=s,de(ne)),r!==s)if(xe()!==s){if(n=[],N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));else n=s;n!==s&&(o=xe())!==s?(41===t.charCodeAt(ie)?(a=")",ie++):(a=s,de(z)),a!==s?(r=we(parseInt(n.join(""),10)),e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;else ie=e,e=s;return ce[i]={nextPos:ie,result:e},e}())===s&&(e=function(){var e,r,n,o,a,i=32*ie+30,u=ce[i];if(u)return ie=u.nextPos,u.result;if(e=ie,":nth-last-child("===t.substr(ie,16)?(r=":nth-last-child(",ie+=16):(r=s,de(oe)),r!==s)if(xe()!==s){if(n=[],N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));else n=s;n!==s&&(o=xe())!==s?(41===t.charCodeAt(ie)?(a=")",ie++):(a=s,de(z)),a!==s?(r=Pe(parseInt(n.join(""),10)),e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;else ie=e,e=s;return ce[i]={nextPos:ie,result:e},e}())===s&&(e=function(){var e,r,n,o=32*ie+31,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,58===t.charCodeAt(ie)?(r=":",ie++):(r=s,de(ae)),r!==s&&(n=ve())!==s?e=r={type:"class",name:n}:(ie=e,e=s),ce[o]={nextPos:ie,result:e},e)}()),ce[r]={nextPos:ie,result:e},e)}function Ce(){var e,r,n,o,a,i,u,l,c=32*ie+15,f=ce[c];if(f)return ie=f.nextPos,f.result;if(e=ie,(r=ve())!==s){for(n=[],o=ie,46===t.charCodeAt(ie)?(a=".",ie++):(a=s,de(D)),a!==s&&(i=ve())!==s?o=a=[a,i]:(ie=o,o=s);o!==s;)n.push(o),o=ie,46===t.charCodeAt(ie)?(a=".",ie++):(a=s,de(D)),a!==s&&(i=ve())!==s?o=a=[a,i]:(ie=o,o=s);n!==s?(u=r,l=n,e=r=[].concat.apply([u],l).join("")):(ie=e,e=s)}else ie=e,e=s;return ce[c]={nextPos:ie,result:e},e}function we(e){return{type:"nth-child",index:{type:"literal",value:e}}}function Pe(e){return{type:"nth-last-child",index:{type:"literal",value:e}}}if((n=l())!==s&&ie===t.length)return n;throw n!==s&&ie0&&p(e,t,r))&&f(t[0],t.slice(1),r)};case"descendant":var h=c(t.left),x=c(t.right);return function(e,t,r){if(x(e,t,r))for(var n=0,o=t.length;n":return function(e){return u(e,v)>t.value.value};case">=":return function(e){return u(e,v)>=t.value.value}}throw new Error("Unknown operator: ".concat(t.operator));case"sibling":var E=c(t.left),b=c(t.right);return function(e,r,n){return b(e,r,n)&&y(e,E,r,"LEFT_SIDE",n)||t.left.subject&&E(e,r,n)&&y(e,b,r,"RIGHT_SIDE",n)};case"adjacent":var S=c(t.left),_=c(t.right);return function(e,r,n){return _(e,r,n)&&d(e,S,r,"LEFT_SIDE",n)||t.right.subject&&S(e,r,n)&&d(e,_,r,"RIGHT_SIDE",n)};case"nth-child":var C=t.index.value,w=c(t.right);return function(e,t,r){return w(e,t,r)&&m(e,t,C,r)};case"nth-last-child":var P=-t.index.value,k=c(t.right);return function(e,t,r){return k(e,t,r)&&m(e,t,P,r)};case"class":var D=t.name.toLowerCase();return function(e,r,n){if(n&&n.matchClass)return n.matchClass(t.name,e,r);if(n&&n.nodeTypeKey)return!1;switch(D){case"statement":if("Statement"===e.type.slice(-9))return!0;case"declaration":return"Declaration"===e.type.slice(-11);case"pattern":if("Pattern"===e.type.slice(-7))return!0;case"expression":return"Expression"===e.type.slice(-10)||"Literal"===e.type.slice(-7)||"Identifier"===e.type&&(0===r.length||"MetaProperty"!==r[0].type)||"MetaProperty"===e.type;case"function":return"FunctionDeclaration"===e.type||"FunctionExpression"===e.type||"ArrowFunctionExpression"===e.type}throw new Error("Unknown class name: ".concat(t.name))}}throw new Error("Unknown selector type: ".concat(t.type))}function p(e,t){var r=t&&t.nodeTypeKey||"type",n=e[r];return t&&t.visitorKeys&&t.visitorKeys[n]?t.visitorKeys[n]:i.VisitorKeys[n]?i.VisitorKeys[n]:t&&"function"==typeof t.fallback?t.fallback(e):Object.keys(e).filter((function(e){return e!==r}))}function h(t,r){var n=r&&r.nodeTypeKey||"type";return null!==t&&"object"===e(t)&&"string"==typeof t[n]}function y(e,r,n,o,a){var i=t(n,1)[0];if(!i)return!1;for(var s=p(i,a),u=0;u0&&h(l[c-1],a)&&r(l[c-1],n,a))return!0;if("RIGHT_SIDE"===o&&c=0&&l\n Copyright (C) 2012 Ariya Hidayat \n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*jslint vars:false, bitwise:true*/\n/*jshint indent:4*/\n/*global exports:true*/\n(function clone(exports) {\n 'use strict';\n\n var Syntax,\n VisitorOption,\n VisitorKeys,\n BREAK,\n SKIP,\n REMOVE;\n\n function deepCopy(obj) {\n var ret = {}, key, val;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) {\n val = obj[key];\n if (typeof val === 'object' && val !== null) {\n ret[key] = deepCopy(val);\n } else {\n ret[key] = val;\n }\n }\n }\n return ret;\n }\n\n // based on LLVM libc++ upper_bound / lower_bound\n // MIT License\n\n function upperBound(array, func) {\n var diff, len, i, current;\n\n len = array.length;\n i = 0;\n\n while (len) {\n diff = len >>> 1;\n current = i + diff;\n if (func(array[current])) {\n len = diff;\n } else {\n i = current + 1;\n len -= diff + 1;\n }\n }\n return i;\n }\n\n Syntax = {\n AssignmentExpression: 'AssignmentExpression',\n AssignmentPattern: 'AssignmentPattern',\n ArrayExpression: 'ArrayExpression',\n ArrayPattern: 'ArrayPattern',\n ArrowFunctionExpression: 'ArrowFunctionExpression',\n AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.\n BlockStatement: 'BlockStatement',\n BinaryExpression: 'BinaryExpression',\n BreakStatement: 'BreakStatement',\n CallExpression: 'CallExpression',\n CatchClause: 'CatchClause',\n ChainExpression: 'ChainExpression',\n ClassBody: 'ClassBody',\n ClassDeclaration: 'ClassDeclaration',\n ClassExpression: 'ClassExpression',\n ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.\n ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.\n ConditionalExpression: 'ConditionalExpression',\n ContinueStatement: 'ContinueStatement',\n DebuggerStatement: 'DebuggerStatement',\n DirectiveStatement: 'DirectiveStatement',\n DoWhileStatement: 'DoWhileStatement',\n EmptyStatement: 'EmptyStatement',\n ExportAllDeclaration: 'ExportAllDeclaration',\n ExportDefaultDeclaration: 'ExportDefaultDeclaration',\n ExportNamedDeclaration: 'ExportNamedDeclaration',\n ExportSpecifier: 'ExportSpecifier',\n ExpressionStatement: 'ExpressionStatement',\n ForStatement: 'ForStatement',\n ForInStatement: 'ForInStatement',\n ForOfStatement: 'ForOfStatement',\n FunctionDeclaration: 'FunctionDeclaration',\n FunctionExpression: 'FunctionExpression',\n GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.\n Identifier: 'Identifier',\n IfStatement: 'IfStatement',\n ImportExpression: 'ImportExpression',\n ImportDeclaration: 'ImportDeclaration',\n ImportDefaultSpecifier: 'ImportDefaultSpecifier',\n ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',\n ImportSpecifier: 'ImportSpecifier',\n Literal: 'Literal',\n LabeledStatement: 'LabeledStatement',\n LogicalExpression: 'LogicalExpression',\n MemberExpression: 'MemberExpression',\n MetaProperty: 'MetaProperty',\n MethodDefinition: 'MethodDefinition',\n ModuleSpecifier: 'ModuleSpecifier',\n NewExpression: 'NewExpression',\n ObjectExpression: 'ObjectExpression',\n ObjectPattern: 'ObjectPattern',\n PrivateIdentifier: 'PrivateIdentifier',\n Program: 'Program',\n Property: 'Property',\n PropertyDefinition: 'PropertyDefinition',\n RestElement: 'RestElement',\n ReturnStatement: 'ReturnStatement',\n SequenceExpression: 'SequenceExpression',\n SpreadElement: 'SpreadElement',\n Super: 'Super',\n SwitchStatement: 'SwitchStatement',\n SwitchCase: 'SwitchCase',\n TaggedTemplateExpression: 'TaggedTemplateExpression',\n TemplateElement: 'TemplateElement',\n TemplateLiteral: 'TemplateLiteral',\n ThisExpression: 'ThisExpression',\n ThrowStatement: 'ThrowStatement',\n TryStatement: 'TryStatement',\n UnaryExpression: 'UnaryExpression',\n UpdateExpression: 'UpdateExpression',\n VariableDeclaration: 'VariableDeclaration',\n VariableDeclarator: 'VariableDeclarator',\n WhileStatement: 'WhileStatement',\n WithStatement: 'WithStatement',\n YieldExpression: 'YieldExpression'\n };\n\n VisitorKeys = {\n AssignmentExpression: ['left', 'right'],\n AssignmentPattern: ['left', 'right'],\n ArrayExpression: ['elements'],\n ArrayPattern: ['elements'],\n ArrowFunctionExpression: ['params', 'body'],\n AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.\n BlockStatement: ['body'],\n BinaryExpression: ['left', 'right'],\n BreakStatement: ['label'],\n CallExpression: ['callee', 'arguments'],\n CatchClause: ['param', 'body'],\n ChainExpression: ['expression'],\n ClassBody: ['body'],\n ClassDeclaration: ['id', 'superClass', 'body'],\n ClassExpression: ['id', 'superClass', 'body'],\n ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.\n ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n ConditionalExpression: ['test', 'consequent', 'alternate'],\n ContinueStatement: ['label'],\n DebuggerStatement: [],\n DirectiveStatement: [],\n DoWhileStatement: ['body', 'test'],\n EmptyStatement: [],\n ExportAllDeclaration: ['source'],\n ExportDefaultDeclaration: ['declaration'],\n ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],\n ExportSpecifier: ['exported', 'local'],\n ExpressionStatement: ['expression'],\n ForStatement: ['init', 'test', 'update', 'body'],\n ForInStatement: ['left', 'right', 'body'],\n ForOfStatement: ['left', 'right', 'body'],\n FunctionDeclaration: ['id', 'params', 'body'],\n FunctionExpression: ['id', 'params', 'body'],\n GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n Identifier: [],\n IfStatement: ['test', 'consequent', 'alternate'],\n ImportExpression: ['source'],\n ImportDeclaration: ['specifiers', 'source'],\n ImportDefaultSpecifier: ['local'],\n ImportNamespaceSpecifier: ['local'],\n ImportSpecifier: ['imported', 'local'],\n Literal: [],\n LabeledStatement: ['label', 'body'],\n LogicalExpression: ['left', 'right'],\n MemberExpression: ['object', 'property'],\n MetaProperty: ['meta', 'property'],\n MethodDefinition: ['key', 'value'],\n ModuleSpecifier: [],\n NewExpression: ['callee', 'arguments'],\n ObjectExpression: ['properties'],\n ObjectPattern: ['properties'],\n PrivateIdentifier: [],\n Program: ['body'],\n Property: ['key', 'value'],\n PropertyDefinition: ['key', 'value'],\n RestElement: [ 'argument' ],\n ReturnStatement: ['argument'],\n SequenceExpression: ['expressions'],\n SpreadElement: ['argument'],\n Super: [],\n SwitchStatement: ['discriminant', 'cases'],\n SwitchCase: ['test', 'consequent'],\n TaggedTemplateExpression: ['tag', 'quasi'],\n TemplateElement: [],\n TemplateLiteral: ['quasis', 'expressions'],\n ThisExpression: [],\n ThrowStatement: ['argument'],\n TryStatement: ['block', 'handler', 'finalizer'],\n UnaryExpression: ['argument'],\n UpdateExpression: ['argument'],\n VariableDeclaration: ['declarations'],\n VariableDeclarator: ['id', 'init'],\n WhileStatement: ['test', 'body'],\n WithStatement: ['object', 'body'],\n YieldExpression: ['argument']\n };\n\n // unique id\n BREAK = {};\n SKIP = {};\n REMOVE = {};\n\n VisitorOption = {\n Break: BREAK,\n Skip: SKIP,\n Remove: REMOVE\n };\n\n function Reference(parent, key) {\n this.parent = parent;\n this.key = key;\n }\n\n Reference.prototype.replace = function replace(node) {\n this.parent[this.key] = node;\n };\n\n Reference.prototype.remove = function remove() {\n if (Array.isArray(this.parent)) {\n this.parent.splice(this.key, 1);\n return true;\n } else {\n this.replace(null);\n return false;\n }\n };\n\n function Element(node, path, wrap, ref) {\n this.node = node;\n this.path = path;\n this.wrap = wrap;\n this.ref = ref;\n }\n\n function Controller() { }\n\n // API:\n // return property path array from root to current node\n Controller.prototype.path = function path() {\n var i, iz, j, jz, result, element;\n\n function addToPath(result, path) {\n if (Array.isArray(path)) {\n for (j = 0, jz = path.length; j < jz; ++j) {\n result.push(path[j]);\n }\n } else {\n result.push(path);\n }\n }\n\n // root node\n if (!this.__current.path) {\n return null;\n }\n\n // first node is sentinel, second node is root element\n result = [];\n for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {\n element = this.__leavelist[i];\n addToPath(result, element.path);\n }\n addToPath(result, this.__current.path);\n return result;\n };\n\n // API:\n // return type of current node\n Controller.prototype.type = function () {\n var node = this.current();\n return node.type || this.__current.wrap;\n };\n\n // API:\n // return array of parent elements\n Controller.prototype.parents = function parents() {\n var i, iz, result;\n\n // first node is sentinel\n result = [];\n for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {\n result.push(this.__leavelist[i].node);\n }\n\n return result;\n };\n\n // API:\n // return current node\n Controller.prototype.current = function current() {\n return this.__current.node;\n };\n\n Controller.prototype.__execute = function __execute(callback, element) {\n var previous, result;\n\n result = undefined;\n\n previous = this.__current;\n this.__current = element;\n this.__state = null;\n if (callback) {\n result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);\n }\n this.__current = previous;\n\n return result;\n };\n\n // API:\n // notify control skip / break\n Controller.prototype.notify = function notify(flag) {\n this.__state = flag;\n };\n\n // API:\n // skip child nodes of current node\n Controller.prototype.skip = function () {\n this.notify(SKIP);\n };\n\n // API:\n // break traversals\n Controller.prototype['break'] = function () {\n this.notify(BREAK);\n };\n\n // API:\n // remove node\n Controller.prototype.remove = function () {\n this.notify(REMOVE);\n };\n\n Controller.prototype.__initialize = function(root, visitor) {\n this.visitor = visitor;\n this.root = root;\n this.__worklist = [];\n this.__leavelist = [];\n this.__current = null;\n this.__state = null;\n this.__fallback = null;\n if (visitor.fallback === 'iteration') {\n this.__fallback = Object.keys;\n } else if (typeof visitor.fallback === 'function') {\n this.__fallback = visitor.fallback;\n }\n\n this.__keys = VisitorKeys;\n if (visitor.keys) {\n this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);\n }\n };\n\n function isNode(node) {\n if (node == null) {\n return false;\n }\n return typeof node === 'object' && typeof node.type === 'string';\n }\n\n function isProperty(nodeType, key) {\n return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;\n }\n \n function candidateExistsInLeaveList(leavelist, candidate) {\n for (var i = leavelist.length - 1; i >= 0; --i) {\n if (leavelist[i].node === candidate) {\n return true;\n }\n }\n return false;\n }\n\n Controller.prototype.traverse = function traverse(root, visitor) {\n var worklist,\n leavelist,\n element,\n node,\n nodeType,\n ret,\n key,\n current,\n current2,\n candidates,\n candidate,\n sentinel;\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n worklist.push(new Element(root, null, null, null));\n leavelist.push(new Element(null, null, null, null));\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n ret = this.__execute(visitor.leave, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n continue;\n }\n\n if (element.node) {\n\n ret = this.__execute(visitor.enter, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || ret === SKIP) {\n continue;\n }\n\n node = element.node;\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n\n if (candidateExistsInLeaveList(leavelist, candidate[current2])) {\n continue;\n }\n\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', null);\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, null);\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n if (candidateExistsInLeaveList(leavelist, candidate)) {\n continue;\n }\n\n worklist.push(new Element(candidate, key, null, null));\n }\n }\n }\n }\n };\n\n Controller.prototype.replace = function replace(root, visitor) {\n var worklist,\n leavelist,\n node,\n nodeType,\n target,\n element,\n current,\n current2,\n candidates,\n candidate,\n sentinel,\n outer,\n key;\n\n function removeElem(element) {\n var i,\n key,\n nextElem,\n parent;\n\n if (element.ref.remove()) {\n // When the reference is an element of an array.\n key = element.ref.key;\n parent = element.ref.parent;\n\n // If removed from array, then decrease following items' keys.\n i = worklist.length;\n while (i--) {\n nextElem = worklist[i];\n if (nextElem.ref && nextElem.ref.parent === parent) {\n if (nextElem.ref.key < key) {\n break;\n }\n --nextElem.ref.key;\n }\n }\n }\n }\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n outer = {\n root: root\n };\n element = new Element(root, null, null, new Reference(outer, 'root'));\n worklist.push(element);\n leavelist.push(element);\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n target = this.__execute(visitor.leave, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n continue;\n }\n\n target = this.__execute(visitor.enter, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n element.node = target;\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n element.node = null;\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n\n // node may be null\n node = element.node;\n if (!node) {\n continue;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || target === SKIP) {\n continue;\n }\n\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n worklist.push(new Element(candidate, key, null, new Reference(node, key)));\n }\n }\n }\n\n return outer.root;\n };\n\n function traverse(root, visitor) {\n var controller = new Controller();\n return controller.traverse(root, visitor);\n }\n\n function replace(root, visitor) {\n var controller = new Controller();\n return controller.replace(root, visitor);\n }\n\n function extendCommentRange(comment, tokens) {\n var target;\n\n target = upperBound(tokens, function search(token) {\n return token.range[0] > comment.range[0];\n });\n\n comment.extendedRange = [comment.range[0], comment.range[1]];\n\n if (target !== tokens.length) {\n comment.extendedRange[1] = tokens[target].range[0];\n }\n\n target -= 1;\n if (target >= 0) {\n comment.extendedRange[0] = tokens[target].range[1];\n }\n\n return comment;\n }\n\n function attachComments(tree, providedComments, tokens) {\n // At first, we should calculate extended comment ranges.\n var comments = [], comment, len, i, cursor;\n\n if (!tree.range) {\n throw new Error('attachComments needs range information');\n }\n\n // tokens array is empty, we attach comments to tree as 'leadingComments'\n if (!tokens.length) {\n if (providedComments.length) {\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comment = deepCopy(providedComments[i]);\n comment.extendedRange = [0, tree.range[0]];\n comments.push(comment);\n }\n tree.leadingComments = comments;\n }\n return tree;\n }\n\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));\n }\n\n // This is based on John Freeman's implementation.\n cursor = 0;\n traverse(tree, {\n enter: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (comment.extendedRange[1] > node.range[0]) {\n break;\n }\n\n if (comment.extendedRange[1] === node.range[0]) {\n if (!node.leadingComments) {\n node.leadingComments = [];\n }\n node.leadingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n cursor = 0;\n traverse(tree, {\n leave: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (node.range[1] < comment.extendedRange[0]) {\n break;\n }\n\n if (node.range[1] === comment.extendedRange[0]) {\n if (!node.trailingComments) {\n node.trailingComments = [];\n }\n node.trailingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n return tree;\n }\n\n exports.Syntax = Syntax;\n exports.traverse = traverse;\n exports.replace = replace;\n exports.attachComments = attachComments;\n exports.VisitorKeys = VisitorKeys;\n exports.VisitorOption = VisitorOption;\n exports.Controller = Controller;\n exports.cloneEnvironment = function () { return clone({}); };\n\n return exports;\n}(exports));\n/* vim: set sw=4 ts=4 et tw=80 : */\n","/*\n * Generated by PEG.js 0.10.0.\n *\n * http://pegjs.org/\n */\n(function(root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define([], factory);\n } else if (typeof module === \"object\" && module.exports) {\n module.exports = factory();\n }\n})(this, function() {\n \"use strict\";\n\n function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }\n\n function peg$SyntaxError(message, expected, found, location) {\n this.message = message;\n this.expected = expected;\n this.found = found;\n this.location = location;\n this.name = \"SyntaxError\";\n\n if (typeof Error.captureStackTrace === \"function\") {\n Error.captureStackTrace(this, peg$SyntaxError);\n }\n }\n\n peg$subclass(peg$SyntaxError, Error);\n\n peg$SyntaxError.buildMessage = function(expected, found) {\n var DESCRIBE_EXPECTATION_FNS = {\n literal: function(expectation) {\n return \"\\\"\" + literalEscape(expectation.text) + \"\\\"\";\n },\n\n \"class\": function(expectation) {\n var escapedParts = \"\",\n i;\n\n for (i = 0; i < expectation.parts.length; i++) {\n escapedParts += expectation.parts[i] instanceof Array\n ? classEscape(expectation.parts[i][0]) + \"-\" + classEscape(expectation.parts[i][1])\n : classEscape(expectation.parts[i]);\n }\n\n return \"[\" + (expectation.inverted ? \"^\" : \"\") + escapedParts + \"]\";\n },\n\n any: function(expectation) {\n return \"any character\";\n },\n\n end: function(expectation) {\n return \"end of input\";\n },\n\n other: function(expectation) {\n return expectation.description;\n }\n };\n\n function hex(ch) {\n return ch.charCodeAt(0).toString(16).toUpperCase();\n }\n\n function literalEscape(s) {\n return s\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\0/g, '\\\\0')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/[\\x00-\\x0F]/g, function(ch) { return '\\\\x0' + hex(ch); })\n .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return '\\\\x' + hex(ch); });\n }\n\n function classEscape(s) {\n return s\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\]/g, '\\\\]')\n .replace(/\\^/g, '\\\\^')\n .replace(/-/g, '\\\\-')\n .replace(/\\0/g, '\\\\0')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/[\\x00-\\x0F]/g, function(ch) { return '\\\\x0' + hex(ch); })\n .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return '\\\\x' + hex(ch); });\n }\n\n function describeExpectation(expectation) {\n return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);\n }\n\n function describeExpected(expected) {\n var descriptions = new Array(expected.length),\n i, j;\n\n for (i = 0; i < expected.length; i++) {\n descriptions[i] = describeExpectation(expected[i]);\n }\n\n descriptions.sort();\n\n if (descriptions.length > 0) {\n for (i = 1, j = 1; i < descriptions.length; i++) {\n if (descriptions[i - 1] !== descriptions[i]) {\n descriptions[j] = descriptions[i];\n j++;\n }\n }\n descriptions.length = j;\n }\n\n switch (descriptions.length) {\n case 1:\n return descriptions[0];\n\n case 2:\n return descriptions[0] + \" or \" + descriptions[1];\n\n default:\n return descriptions.slice(0, -1).join(\", \")\n + \", or \"\n + descriptions[descriptions.length - 1];\n }\n }\n\n function describeFound(found) {\n return found ? \"\\\"\" + literalEscape(found) + \"\\\"\" : \"end of input\";\n }\n\n return \"Expected \" + describeExpected(expected) + \" but \" + describeFound(found) + \" found.\";\n };\n\n function peg$parse(input, options) {\n options = options !== void 0 ? options : {};\n\n var peg$FAILED = {},\n\n peg$startRuleFunctions = { start: peg$parsestart },\n peg$startRuleFunction = peg$parsestart,\n\n peg$c0 = function(ss) {\n return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss };\n },\n peg$c1 = function() { return void 0; },\n peg$c2 = \" \",\n peg$c3 = peg$literalExpectation(\" \", false),\n peg$c4 = /^[^ [\\],():#!=><~+.]/,\n peg$c5 = peg$classExpectation([\" \", \"[\", \"]\", \",\", \"(\", \")\", \":\", \"#\", \"!\", \"=\", \">\", \"<\", \"~\", \"+\", \".\"], true, false),\n peg$c6 = function(i) { return i.join(''); },\n peg$c7 = \">\",\n peg$c8 = peg$literalExpectation(\">\", false),\n peg$c9 = function() { return 'child'; },\n peg$c10 = \"~\",\n peg$c11 = peg$literalExpectation(\"~\", false),\n peg$c12 = function() { return 'sibling'; },\n peg$c13 = \"+\",\n peg$c14 = peg$literalExpectation(\"+\", false),\n peg$c15 = function() { return 'adjacent'; },\n peg$c16 = function() { return 'descendant'; },\n peg$c17 = \",\",\n peg$c18 = peg$literalExpectation(\",\", false),\n peg$c19 = function(s, ss) {\n return [s].concat(ss.map(function (s) { return s[3]; }));\n },\n peg$c20 = function(op, s) {\n if (!op) return s;\n return { type: op, left: { type: 'exactNode' }, right: s };\n },\n peg$c21 = function(a, ops) {\n return ops.reduce(function (memo, rhs) {\n return { type: rhs[0], left: memo, right: rhs[1] };\n }, a);\n },\n peg$c22 = \"!\",\n peg$c23 = peg$literalExpectation(\"!\", false),\n peg$c24 = function(subject, as) {\n const b = as.length === 1 ? as[0] : { type: 'compound', selectors: as };\n if(subject) b.subject = true;\n return b;\n },\n peg$c25 = \"*\",\n peg$c26 = peg$literalExpectation(\"*\", false),\n peg$c27 = function(a) { return { type: 'wildcard', value: a }; },\n peg$c28 = \"#\",\n peg$c29 = peg$literalExpectation(\"#\", false),\n peg$c30 = function(i) { return { type: 'identifier', value: i }; },\n peg$c31 = \"[\",\n peg$c32 = peg$literalExpectation(\"[\", false),\n peg$c33 = \"]\",\n peg$c34 = peg$literalExpectation(\"]\", false),\n peg$c35 = function(v) { return v; },\n peg$c36 = /^[>\", \"<\", \"!\"], false, false),\n peg$c38 = \"=\",\n peg$c39 = peg$literalExpectation(\"=\", false),\n peg$c40 = function(a) { return (a || '') + '='; },\n peg$c41 = /^[><]/,\n peg$c42 = peg$classExpectation([\">\", \"<\"], false, false),\n peg$c43 = \".\",\n peg$c44 = peg$literalExpectation(\".\", false),\n peg$c45 = function(a, as) {\n return [].concat.apply([a], as).join('');\n },\n peg$c46 = function(name, op, value) {\n return { type: 'attribute', name: name, operator: op, value: value };\n },\n peg$c47 = function(name) { return { type: 'attribute', name: name }; },\n peg$c48 = \"\\\"\",\n peg$c49 = peg$literalExpectation(\"\\\"\", false),\n peg$c50 = /^[^\\\\\"]/,\n peg$c51 = peg$classExpectation([\"\\\\\", \"\\\"\"], true, false),\n peg$c52 = \"\\\\\",\n peg$c53 = peg$literalExpectation(\"\\\\\", false),\n peg$c54 = peg$anyExpectation(),\n peg$c55 = function(a, b) { return a + b; },\n peg$c56 = function(d) {\n return { type: 'literal', value: strUnescape(d.join('')) };\n },\n peg$c57 = \"'\",\n peg$c58 = peg$literalExpectation(\"'\", false),\n peg$c59 = /^[^\\\\']/,\n peg$c60 = peg$classExpectation([\"\\\\\", \"'\"], true, false),\n peg$c61 = /^[0-9]/,\n peg$c62 = peg$classExpectation([[\"0\", \"9\"]], false, false),\n peg$c63 = function(a, b) {\n // Can use `a.flat().join('')` once supported\n const leadingDecimals = a ? [].concat.apply([], a).join('') : '';\n return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) };\n },\n peg$c64 = function(i) { return { type: 'literal', value: i }; },\n peg$c65 = \"type(\",\n peg$c66 = peg$literalExpectation(\"type(\", false),\n peg$c67 = /^[^ )]/,\n peg$c68 = peg$classExpectation([\" \", \")\"], true, false),\n peg$c69 = \")\",\n peg$c70 = peg$literalExpectation(\")\", false),\n peg$c71 = function(t) { return { type: 'type', value: t.join('') }; },\n peg$c72 = /^[imsu]/,\n peg$c73 = peg$classExpectation([\"i\", \"m\", \"s\", \"u\"], false, false),\n peg$c74 = \"/\",\n peg$c75 = peg$literalExpectation(\"/\", false),\n peg$c76 = /^[^\\/]/,\n peg$c77 = peg$classExpectation([\"/\"], true, false),\n peg$c78 = function(d, flgs) { return {\n type: 'regexp', value: new RegExp(d.join(''), flgs ? flgs.join('') : '') };\n },\n peg$c79 = function(i, is) {\n return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)};\n },\n peg$c80 = \":not(\",\n peg$c81 = peg$literalExpectation(\":not(\", false),\n peg$c82 = function(ss) { return { type: 'not', selectors: ss }; },\n peg$c83 = \":matches(\",\n peg$c84 = peg$literalExpectation(\":matches(\", false),\n peg$c85 = function(ss) { return { type: 'matches', selectors: ss }; },\n peg$c86 = \":has(\",\n peg$c87 = peg$literalExpectation(\":has(\", false),\n peg$c88 = function(ss) { return { type: 'has', selectors: ss }; },\n peg$c89 = \":first-child\",\n peg$c90 = peg$literalExpectation(\":first-child\", false),\n peg$c91 = function() { return nth(1); },\n peg$c92 = \":last-child\",\n peg$c93 = peg$literalExpectation(\":last-child\", false),\n peg$c94 = function() { return nthLast(1); },\n peg$c95 = \":nth-child(\",\n peg$c96 = peg$literalExpectation(\":nth-child(\", false),\n peg$c97 = function(n) { return nth(parseInt(n.join(''), 10)); },\n peg$c98 = \":nth-last-child(\",\n peg$c99 = peg$literalExpectation(\":nth-last-child(\", false),\n peg$c100 = function(n) { return nthLast(parseInt(n.join(''), 10)); },\n peg$c101 = \":\",\n peg$c102 = peg$literalExpectation(\":\", false),\n peg$c103 = function(c) {\n return { type: 'class', name: c };\n },\n\n peg$currPos = 0,\n peg$savedPos = 0,\n peg$posDetailsCache = [{ line: 1, column: 1 }],\n peg$maxFailPos = 0,\n peg$maxFailExpected = [],\n peg$silentFails = 0,\n\n peg$resultsCache = {},\n\n peg$result;\n\n if (\"startRule\" in options) {\n if (!(options.startRule in peg$startRuleFunctions)) {\n throw new Error(\"Can't start parsing from rule \\\"\" + options.startRule + \"\\\".\");\n }\n\n peg$startRuleFunction = peg$startRuleFunctions[options.startRule];\n }\n\n function text() {\n return input.substring(peg$savedPos, peg$currPos);\n }\n\n function location() {\n return peg$computeLocation(peg$savedPos, peg$currPos);\n }\n\n function expected(description, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildStructuredError(\n [peg$otherExpectation(description)],\n input.substring(peg$savedPos, peg$currPos),\n location\n );\n }\n\n function error(message, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildSimpleError(message, location);\n }\n\n function peg$literalExpectation(text, ignoreCase) {\n return { type: \"literal\", text: text, ignoreCase: ignoreCase };\n }\n\n function peg$classExpectation(parts, inverted, ignoreCase) {\n return { type: \"class\", parts: parts, inverted: inverted, ignoreCase: ignoreCase };\n }\n\n function peg$anyExpectation() {\n return { type: \"any\" };\n }\n\n function peg$endExpectation() {\n return { type: \"end\" };\n }\n\n function peg$otherExpectation(description) {\n return { type: \"other\", description: description };\n }\n\n function peg$computePosDetails(pos) {\n var details = peg$posDetailsCache[pos], p;\n\n if (details) {\n return details;\n } else {\n p = pos - 1;\n while (!peg$posDetailsCache[p]) {\n p--;\n }\n\n details = peg$posDetailsCache[p];\n details = {\n line: details.line,\n column: details.column\n };\n\n while (p < pos) {\n if (input.charCodeAt(p) === 10) {\n details.line++;\n details.column = 1;\n } else {\n details.column++;\n }\n\n p++;\n }\n\n peg$posDetailsCache[pos] = details;\n return details;\n }\n }\n\n function peg$computeLocation(startPos, endPos) {\n var startPosDetails = peg$computePosDetails(startPos),\n endPosDetails = peg$computePosDetails(endPos);\n\n return {\n start: {\n offset: startPos,\n line: startPosDetails.line,\n column: startPosDetails.column\n },\n end: {\n offset: endPos,\n line: endPosDetails.line,\n column: endPosDetails.column\n }\n };\n }\n\n function peg$fail(expected) {\n if (peg$currPos < peg$maxFailPos) { return; }\n\n if (peg$currPos > peg$maxFailPos) {\n peg$maxFailPos = peg$currPos;\n peg$maxFailExpected = [];\n }\n\n peg$maxFailExpected.push(expected);\n }\n\n function peg$buildSimpleError(message, location) {\n return new peg$SyntaxError(message, null, null, location);\n }\n\n function peg$buildStructuredError(expected, found, location) {\n return new peg$SyntaxError(\n peg$SyntaxError.buildMessage(expected, found),\n expected,\n found,\n location\n );\n }\n\n function peg$parsestart() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 0,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselectors();\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c0(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c1();\n }\n s0 = s1;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parse_() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 1,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifierName() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 2,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = [];\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n if (s2 !== peg$FAILED) {\n while (s2 !== peg$FAILED) {\n s1.push(s2);\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n }\n } else {\n s1 = peg$FAILED;\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c6(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsebinaryOp() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 3,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 62) {\n s2 = peg$c7;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c8); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c9();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 126) {\n s2 = peg$c10;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c11); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c12();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 43) {\n s2 = peg$c13;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c14); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c15();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c16();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 32 + 4,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsehasSelector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 32 + 5,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseselector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelector() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 6,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsebinaryOp();\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselector();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c20(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselector() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 7,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsesequence();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c21(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsesequence() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 8,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$parseatom();\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$parseatom();\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c24(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseatom() {\n var s0;\n\n var key = peg$currPos * 32 + 9,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$parsewildcard();\n if (s0 === peg$FAILED) {\n s0 = peg$parseidentifier();\n if (s0 === peg$FAILED) {\n s0 = peg$parseattr();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefield();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenegation();\n if (s0 === peg$FAILED) {\n s0 = peg$parsematches();\n if (s0 === peg$FAILED) {\n s0 = peg$parsehas();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefirstChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parselastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthLastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parseclass();\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsewildcard() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 10,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 42) {\n s1 = peg$c25;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c26); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c27(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifier() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 11,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 35) {\n s1 = peg$c28;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c29); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c30(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattr() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 12,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 91) {\n s1 = peg$c31;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c32); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrValue();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 93) {\n s5 = peg$c33;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c34); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c35(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 13,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (peg$c36.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c37); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n if (peg$c41.test(input.charAt(peg$currPos))) {\n s0 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s0 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c42); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrEqOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 14,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrName() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 15,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c45(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrValue() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 16,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrEqOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsetype();\n if (s5 === peg$FAILED) {\n s5 = peg$parseregex();\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsestring();\n if (s5 === peg$FAILED) {\n s5 = peg$parsenumber();\n if (s5 === peg$FAILED) {\n s5 = peg$parsepath();\n }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c47(s1);\n }\n s0 = s1;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsestring() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 17,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 34) {\n s1 = peg$c48;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 34) {\n s3 = peg$c48;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 39) {\n s1 = peg$c57;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 39) {\n s3 = peg$c57;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenumber() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 18,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$currPos;\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 46) {\n s3 = peg$c43;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s3 !== peg$FAILED) {\n s2 = [s2, s3];\n s1 = s2;\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c63(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsepath() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 19,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c64(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsetype() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 20,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c65) {\n s1 = peg$c65;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c66); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c71(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseflags() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 21,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n if (s1 !== peg$FAILED) {\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n }\n } else {\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseregex() {\n var s0, s1, s2, s3, s4;\n\n var key = peg$currPos * 32 + 22,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 47) {\n s1 = peg$c74;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c76.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c77); }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c76.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c77); }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 47) {\n s3 = peg$c74;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parseflags();\n if (s4 === peg$FAILED) {\n s4 = null;\n }\n if (s4 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c78(s2, s4);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefield() {\n var s0, s1, s2, s3, s4, s5, s6;\n\n var key = peg$currPos * 32 + 23,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s1 = peg$c43;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n s3 = [];\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c79(s2, s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenegation() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 24,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c80) {\n s1 = peg$c80;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c81); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c82(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsematches() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 25,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 9) === peg$c83) {\n s1 = peg$c83;\n peg$currPos += 9;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c84); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c85(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehas() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 26,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c86) {\n s1 = peg$c86;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c87); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parsehasSelectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c88(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefirstChild() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 27,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 12) === peg$c89) {\n s1 = peg$c89;\n peg$currPos += 12;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c90); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c91();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parselastChild() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 28,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c92) {\n s1 = peg$c92;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c93); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c94();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 29,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c95) {\n s1 = peg$c95;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c96); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c97(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthLastChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 30,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 16) === peg$c98) {\n s1 = peg$c98;\n peg$currPos += 16;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c99); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c100(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseclass() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 31,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 58) {\n s1 = peg$c101;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c102); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c103(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n\n function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; }\n function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; }\n function strUnescape(s) {\n return s.replace(/\\\\(.)/g, function(match, ch) {\n switch(ch) {\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n case 'v': return '\\v';\n default: return ch;\n }\n });\n }\n\n\n peg$result = peg$startRuleFunction();\n\n if (peg$result !== peg$FAILED && peg$currPos === input.length) {\n return peg$result;\n } else {\n if (peg$result !== peg$FAILED && peg$currPos < input.length) {\n peg$fail(peg$endExpectation());\n }\n\n throw peg$buildStructuredError(\n peg$maxFailExpected,\n peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,\n peg$maxFailPos < input.length\n ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)\n : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)\n );\n }\n }\n\n return {\n SyntaxError: peg$SyntaxError,\n parse: peg$parse\n };\n});\n","/* vim: set sw=4 sts=4 : */\nimport estraverse from 'estraverse';\nimport parser from './parser.js';\n\n/**\n* @typedef {\"LEFT_SIDE\"|\"RIGHT_SIDE\"} Side\n*/\n\nconst LEFT_SIDE = 'LEFT_SIDE';\nconst RIGHT_SIDE = 'RIGHT_SIDE';\n\n/**\n * @external AST\n * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html\n */\n\n/**\n * One of the rules of `grammar.pegjs`\n * @typedef {PlainObject} SelectorAST\n * @see grammar.pegjs\n*/\n\n/**\n * The `sequence` production of `grammar.pegjs`\n * @typedef {PlainObject} SelectorSequenceAST\n*/\n\n/**\n * Get the value of a property which may be multiple levels down\n * in the object.\n * @param {?PlainObject} obj\n * @param {string[]} keys\n * @returns {undefined|boolean|string|number|external:AST}\n */\nfunction getPath(obj, keys) {\n for (let i = 0; i < keys.length; ++i) {\n if (obj == null) { return obj; }\n obj = obj[keys[i]];\n }\n return obj;\n}\n\n/**\n * Determine whether `node` can be reached by following `path`,\n * starting at `ancestor`.\n * @param {?external:AST} node\n * @param {?external:AST} ancestor\n * @param {string[]} path\n * @param {Integer} fromPathIndex\n * @returns {boolean}\n */\nfunction inPath(node, ancestor, path, fromPathIndex) {\n let current = ancestor;\n for (let i = fromPathIndex; i < path.length; ++i) {\n if (current == null) {\n return false;\n }\n const field = current[path[i]];\n if (Array.isArray(field)) {\n for (let k = 0; k < field.length; ++k) {\n if (inPath(node, field[k], path, i + 1)) {\n return true;\n }\n }\n return false;\n }\n current = field;\n }\n return node === current;\n}\n\n/**\n * A generated matcher function for a selector.\n * @callback SelectorMatcher\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @returns {void}\n*/\n\n/**\n * A WeakMap for holding cached matcher functions for selectors.\n * @type {WeakMap}\n*/\nconst MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap : null;\n\n/**\n * Look up a matcher function for `selector` in the cache.\n * If it does not exist, generate it with `generateMatcher` and add it to the cache.\n * In engines without WeakMap, the caching is skipped and matchers are generated with every call.\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction getMatcher(selector) {\n if (selector == null) {\n return () => true;\n }\n\n if (MATCHER_CACHE != null) {\n let matcher = MATCHER_CACHE.get(selector);\n if (matcher != null) {\n return matcher;\n }\n matcher = generateMatcher(selector);\n MATCHER_CACHE.set(selector, matcher);\n return matcher;\n }\n\n return generateMatcher(selector);\n}\n\n/**\n * Create a matcher function for `selector`,\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction generateMatcher(selector) {\n switch(selector.type) {\n case 'wildcard':\n return () => true;\n\n case 'identifier': {\n const value = selector.value.toLowerCase();\n return (node, ancestry, options) => {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return value === node[nodeTypeKey].toLowerCase();\n };\n }\n\n case 'exactNode':\n return (node, ancestry) => {\n return ancestry.length === 0;\n };\n\n case 'field': {\n const path = selector.name.split('.');\n return (node, ancestry) => {\n const ancestor = ancestry[path.length - 1];\n return inPath(node, ancestor, path, 0);\n };\n }\n\n case 'matches': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return true; }\n }\n return false;\n };\n }\n\n case 'compound': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (!matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'not': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'has': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n let result = false;\n\n const a = [];\n estraverse.traverse(node, {\n enter (node, parent) {\n if (parent != null) { a.unshift(parent); }\n\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, a, options)) {\n result = true;\n this.break();\n return;\n }\n }\n },\n leave () { a.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n\n return result;\n };\n }\n\n case 'child': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (ancestry.length > 0 && right(node, ancestry, options)) {\n return left(ancestry[0], ancestry.slice(1), options);\n }\n return false;\n };\n }\n\n case 'descendant': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (right(node, ancestry, options)) {\n for (let i = 0, l = ancestry.length; i < l; ++i) {\n if (left(ancestry[i], ancestry.slice(i + 1), options)) {\n return true;\n }\n }\n }\n return false;\n };\n }\n\n case 'attribute': {\n const path = selector.name.split('.');\n switch (selector.operator) {\n case void 0:\n return (node) => getPath(node, path) != null;\n case '=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => {\n const p = getPath(node, path);\n return typeof p === 'string' && selector.value.value.test(p);\n };\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal === `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value === typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '!=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => !selector.value.value.test(getPath(node, path));\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal !== `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value !== typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '<=':\n return (node) => getPath(node, path) <= selector.value.value;\n case '<':\n return (node) => getPath(node, path) < selector.value.value;\n case '>':\n return (node) => getPath(node, path) > selector.value.value;\n case '>=':\n return (node) => getPath(node, path) >= selector.value.value;\n }\n throw new Error(`Unknown operator: ${selector.operator}`);\n }\n\n case 'sibling': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n sibling(node, left, ancestry, LEFT_SIDE, options) ||\n selector.left.subject &&\n left(node, ancestry, options) &&\n sibling(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'adjacent': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n adjacent(node, left, ancestry, LEFT_SIDE, options) ||\n selector.right.subject &&\n left(node, ancestry, options) &&\n adjacent(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'nth-child': {\n const nth = selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'nth-last-child': {\n const nth = -selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'class': {\n \n const name = selector.name.toLowerCase();\n\n return (node, ancestry, options) => {\n \n if (options && options.matchClass) {\n return options.matchClass(selector.name, node, ancestry);\n }\n \n if (options && options.nodeTypeKey) return false; \n\n switch(name){\n case 'statement':\n if(node.type.slice(-9) === 'Statement') return true;\n // fallthrough: interface Declaration <: Statement { }\n case 'declaration':\n return node.type.slice(-11) === 'Declaration';\n case 'pattern':\n if(node.type.slice(-7) === 'Pattern') return true;\n // fallthrough: interface Expression <: Node, Pattern { }\n case 'expression':\n return node.type.slice(-10) === 'Expression' ||\n node.type.slice(-7) === 'Literal' ||\n (\n node.type === 'Identifier' &&\n (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty')\n ) ||\n node.type === 'MetaProperty';\n case 'function':\n return node.type === 'FunctionDeclaration' ||\n node.type === 'FunctionExpression' ||\n node.type === 'ArrowFunctionExpression';\n }\n throw new Error(`Unknown class name: ${selector.name}`);\n };\n }\n }\n\n throw new Error(`Unknown selector type: ${selector.type}`);\n}\n\n/**\n * @callback TraverseOptionFallback\n * @param {external:AST} node The given node.\n * @returns {string[]} An array of visitor keys for the given node.\n */\n\n/**\n * @callback ClassMatcher\n * @param {string} className The name of the class to match.\n * @param {external:AST} node The node to match against.\n * @param {Array} ancestry The ancestry of the node.\n * @returns {boolean} True if the node matches the class, false if not.\n */\n\n/**\n * @typedef {object} ESQueryOptions\n * @property {string} [nodeTypeKey=\"type\"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery.\n * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node.\n * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes.\n * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes.\n */\n\n/**\n * Given a `node` and its ancestors, determine if `node` is matched\n * by `selector`.\n * @param {?external:AST} node\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @throws {Error} Unknowns (operator, class name, selector type, or\n * selector value type)\n * @returns {boolean}\n */\nfunction matches(node, selector, ancestry, options) {\n if (!selector) { return true; }\n if (!node) { return false; }\n if (!ancestry) { ancestry = []; }\n\n return getMatcher(selector)(node, ancestry, options);\n}\n\n/**\n * Get visitor keys of a given node.\n * @param {external:AST} node The AST node to get keys.\n * @param {ESQueryOptions|undefined} options\n * @returns {string[]} Visitor keys of the node.\n */\nfunction getVisitorKeys(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n\n const nodeType = node[nodeTypeKey];\n if (options && options.visitorKeys && options.visitorKeys[nodeType]) {\n return options.visitorKeys[nodeType];\n }\n if (estraverse.VisitorKeys[nodeType]) {\n return estraverse.VisitorKeys[nodeType];\n }\n if (options && typeof options.fallback === 'function') {\n return options.fallback(node);\n }\n // 'iteration' fallback\n return Object.keys(node).filter(function (key) {\n return key !== nodeTypeKey;\n });\n}\n\n\n/**\n * Check whether the given value is an ASTNode or not.\n * @param {any} node The value to check.\n * @param {ESQueryOptions|undefined} options The options to use.\n * @returns {boolean} `true` if the value is an ASTNode.\n */\nfunction isNode(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return node !== null && typeof node === 'object' && typeof node[nodeTypeKey] === 'string';\n}\n\n/**\n * Determines if the given node has a sibling that matches the\n * given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction sibling(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const startIndex = listProp.indexOf(node);\n if (startIndex < 0) { continue; }\n let lowerBound, upperBound;\n if (side === LEFT_SIDE) {\n lowerBound = 0;\n upperBound = startIndex;\n } else {\n lowerBound = startIndex + 1;\n upperBound = listProp.length;\n }\n for (let k = lowerBound; k < upperBound; ++k) {\n if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node has an adjacent sibling that matches\n * the given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction adjacent(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const idx = listProp.indexOf(node);\n if (idx < 0) { continue; }\n if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) {\n return true;\n }\n if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node is the `nth` child.\n * If `nth` is negative then the position is counted\n * from the end of the list of children.\n * @param {external:AST} node\n * @param {external:AST[]} ancestry\n * @param {Integer} nth\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction nthChild(node, ancestry, nth, options) {\n if (nth === 0) { return false; }\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)){\n const idx = nth < 0 ? listProp.length + nth : nth - 1;\n if (idx >= 0 && idx < listProp.length && listProp[idx] === node) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * For each selector node marked as a subject, find the portion of the\n * selector that the subject must match.\n * @param {SelectorAST} selector\n * @param {SelectorAST} [ancestor] Defaults to `selector`\n * @returns {SelectorAST[]}\n */\nfunction subjects(selector, ancestor) {\n if (selector == null || typeof selector != 'object') { return []; }\n if (ancestor == null) { ancestor = selector; }\n const results = selector.subject ? [ancestor] : [];\n const keys = Object.keys(selector);\n for (let i = 0; i < keys.length; ++i) {\n const p = keys[i];\n const sel = selector[p];\n results.push(...subjects(sel, p === 'left' ? sel : ancestor));\n }\n return results;\n}\n\n/**\n* @callback TraverseVisitor\n* @param {?external:AST} node\n* @param {?external:AST} parent\n* @param {external:AST[]} ancestry\n*/\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {TraverseVisitor} visitor\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction traverse(ast, selector, visitor, options) {\n if (!selector) { return; }\n const ancestry = [];\n const matcher = getMatcher(selector);\n const altSubjects = subjects(selector).map(getMatcher);\n estraverse.traverse(ast, {\n enter (node, parent) {\n if (parent != null) { ancestry.unshift(parent); }\n if (matcher(node, ancestry, options)) {\n if (altSubjects.length) {\n for (let i = 0, l = altSubjects.length; i < l; ++i) {\n if (altSubjects[i](node, ancestry, options)) {\n visitor(node, parent, ancestry);\n }\n for (let k = 0, m = ancestry.length; k < m; ++k) {\n const succeedingAncestry = ancestry.slice(k + 1);\n if (altSubjects[i](ancestry[k], succeedingAncestry, options)) {\n visitor(ancestry[k], parent, succeedingAncestry);\n }\n }\n }\n } else {\n visitor(node, parent, ancestry);\n }\n }\n },\n leave () { ancestry.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n}\n\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction match(ast, selector, options) {\n const results = [];\n traverse(ast, selector, function (node) {\n results.push(node);\n }, options);\n return results;\n}\n\n/**\n * Parse a selector string and return its AST.\n * @param {string} selector\n * @returns {SelectorAST}\n */\nfunction parse(selector) {\n return parser.parse(selector);\n}\n\n/**\n * Query the code AST using the selector string.\n * @param {external:AST} ast\n * @param {string} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction query(ast, selector, options) {\n return match(ast, parse(selector), options);\n}\n\nquery.parse = parse;\nquery.match = match;\nquery.traverse = traverse;\nquery.matches = matches;\nquery.query = query;\n\nexport default query;\n"],"names":["clone","exports","Syntax","VisitorOption","VisitorKeys","BREAK","SKIP","REMOVE","deepCopy","obj","key","val","ret","hasOwnProperty","Reference","parent","this","Element","node","path","wrap","ref","Controller","isNode","type","isProperty","nodeType","ObjectExpression","ObjectPattern","candidateExistsInLeaveList","leavelist","candidate","i","length","traverse","root","visitor","extendCommentRange","comment","tokens","target","array","func","diff","len","current","upperBound","token","range","extendedRange","AssignmentExpression","AssignmentPattern","ArrayExpression","ArrayPattern","ArrowFunctionExpression","AwaitExpression","BlockStatement","BinaryExpression","BreakStatement","CallExpression","CatchClause","ChainExpression","ClassBody","ClassDeclaration","ClassExpression","ComprehensionBlock","ComprehensionExpression","ConditionalExpression","ContinueStatement","DebuggerStatement","DirectiveStatement","DoWhileStatement","EmptyStatement","ExportAllDeclaration","ExportDefaultDeclaration","ExportNamedDeclaration","ExportSpecifier","ExpressionStatement","ForStatement","ForInStatement","ForOfStatement","FunctionDeclaration","FunctionExpression","GeneratorExpression","Identifier","IfStatement","ImportExpression","ImportDeclaration","ImportDefaultSpecifier","ImportNamespaceSpecifier","ImportSpecifier","Literal","LabeledStatement","LogicalExpression","MemberExpression","MetaProperty","MethodDefinition","ModuleSpecifier","NewExpression","PrivateIdentifier","Program","Property","PropertyDefinition","RestElement","ReturnStatement","SequenceExpression","SpreadElement","Super","SwitchStatement","SwitchCase","TaggedTemplateExpression","TemplateElement","TemplateLiteral","ThisExpression","ThrowStatement","TryStatement","UnaryExpression","UpdateExpression","VariableDeclaration","VariableDeclarator","WhileStatement","WithStatement","YieldExpression","Break","Skip","Remove","prototype","replace","remove","Array","isArray","splice","iz","j","jz","result","addToPath","push","__current","__leavelist","parents","__execute","callback","element","previous","undefined","__state","call","notify","flag","skip","__initialize","__worklist","__fallback","fallback","Object","keys","__keys","assign","create","worklist","current2","candidates","sentinel","pop","enter","Error","leave","outer","removeElem","nextElem","attachComments","tree","providedComments","cursor","comments","leadingComments","trailingComments","cloneEnvironment","module","peg$SyntaxError","message","expected","found","location","name","captureStackTrace","child","ctor","constructor","peg$subclass","buildMessage","DESCRIBE_EXPECTATION_FNS","literal","expectation","literalEscape","text","class","escapedParts","parts","classEscape","inverted","any","end","other","description","hex","ch","charCodeAt","toString","toUpperCase","s","descriptions","sort","slice","join","describeExpected","describeFound","SyntaxError","parse","input","options","peg$result","peg$FAILED","peg$startRuleFunctions","start","peg$parsestart","peg$startRuleFunction","peg$c3","peg$literalExpectation","peg$c4","peg$c5","peg$classExpectation","peg$c8","peg$c11","peg$c14","peg$c18","peg$c19","ss","concat","map","peg$c23","peg$c26","peg$c29","peg$c32","peg$c34","peg$c36","peg$c37","peg$c39","peg$c40","a","peg$c41","peg$c42","peg$c44","peg$c46","op","value","operator","peg$c49","peg$c50","peg$c51","peg$c53","peg$c54","peg$c55","b","peg$c56","d","match","peg$c58","peg$c59","peg$c60","peg$c61","peg$c62","peg$c66","peg$c67","peg$c68","peg$c70","peg$c72","peg$c73","peg$c75","peg$c76","peg$c77","peg$c81","peg$c84","peg$c87","peg$c90","peg$c93","peg$c96","peg$c99","peg$c102","peg$currPos","peg$posDetailsCache","line","column","peg$maxFailPos","peg$maxFailExpected","peg$silentFails","startRule","ignoreCase","peg$computePosDetails","pos","p","details","peg$computeLocation","startPos","endPos","startPosDetails","endPosDetails","offset","peg$fail","s0","s1","s2","cached","peg$resultsCache","nextPos","peg$parse_","peg$parseselectors","selectors","peg$c1","peg$parseidentifierName","test","charAt","peg$parsebinaryOp","s3","s4","s5","s6","s7","peg$parseselector","peg$parsehasSelector","left","right","peg$parsesequence","reduce","memo","rhs","subject","as","peg$parseatom","peg$parsewildcard","peg$parseidentifier","peg$parseattrName","peg$parseattrEqOps","substr","peg$parsetype","flgs","peg$parseflags","RegExp","peg$parseregex","peg$parseattrOps","peg$parsestring","leadingDecimals","apply","parseFloat","peg$parsenumber","peg$parsepath","peg$parseattrValue","peg$parseattr","peg$parsefield","peg$parsenegation","peg$parsematches","peg$parsehasSelectors","peg$parsehas","nth","peg$parsefirstChild","nthLast","peg$parselastChild","parseInt","peg$parsenthChild","peg$parsenthLastChild","peg$parseclass","n","index","factory","getPath","MATCHER_CACHE","WeakMap","getMatcher","selector","matcher","get","generateMatcher","set","toLowerCase","ancestry","nodeTypeKey","split","inPath","ancestor","fromPathIndex","field","k","matchers","estraverse","unshift","shift","visitorKeys","l","sibling","adjacent","nthChild","matchClass","getVisitorKeys","filter","_typeof","side","listProp","startIndex","indexOf","lowerBound","idx","ast","altSubjects","subjects","results","sel","m","succeedingAncestry","parser","query","matches"],"mappings":"u0DA2BC,SAASA,E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UM,EAAUpK,GACvC,OAAK8J,KACAzW,IACA+W,IAAYA,EAAW,IAErBP,EAAWC,EAAXD,CAAqBxW,EAAM+W,EAAUpK,KAmPhDuM,EAAMA,MAAQA"} \ No newline at end of file diff --git a/node_modules/esquery/dist/esquery.js b/node_modules/esquery/dist/esquery.js new file mode 100644 index 00000000..ace60614 --- /dev/null +++ b/node_modules/esquery/dist/esquery.js @@ -0,0 +1,4180 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.esquery = factory()); +}(this, (function () { 'use strict'; + + function _iterableToArrayLimit(arr, i) { + var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; + if (null != _i) { + var _s, + _e, + _x, + _r, + _arr = [], + _n = !0, + _d = !1; + try { + if (_x = (_i = _i.call(arr)).next, 0 === i) { + if (Object(_i) !== _i) return; + _n = !1; + } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); + } catch (err) { + _d = !0, _e = err; + } finally { + try { + if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; + } finally { + if (_d) throw _e; + } + } + return _arr; + } + } + function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); + } + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); + } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); + } + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + } + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; + } + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var estraverse = createCommonjsModule(function (module, exports) { + /* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + /*jslint vars:false, bitwise:true*/ + /*jshint indent:4*/ + /*global exports:true*/ + (function clone(exports) { + + var Syntax, VisitorOption, VisitorKeys, BREAK, SKIP, REMOVE; + function deepCopy(obj) { + var ret = {}, + key, + val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + len = array.length; + i = 0; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', + // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ChainExpression: 'ChainExpression', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', + // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', + // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', + // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + PrivateIdentifier: 'PrivateIdentifier', + Program: 'Program', + Property: 'Property', + PropertyDefinition: 'PropertyDefinition', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], + // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ChainExpression: ['expression'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], + // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], + // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], + // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + PrivateIdentifier: [], + Program: ['body'], + Property: ['key', 'value'], + PropertyDefinition: ['key', 'value'], + RestElement: ['argument'], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + function Controller() {} + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + result = undefined; + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + Controller.prototype.__initialize = function (root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + function candidateExistsInLeaveList(leavelist, candidate) { + for (var i = leavelist.length - 1; i >= 0; --i) { + if (leavelist[i].node === candidate) { + return true; + } + } + return false; + } + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel; + this.__initialize(root, visitor); + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + ret = this.__execute(visitor.leave, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + if (element.node) { + ret = this.__execute(visitor.enter, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || ret === SKIP) { + continue; + } + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (candidateExistsInLeaveList(leavelist, candidate[current2])) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + if (candidateExistsInLeaveList(leavelist, candidate)) { + continue; + } + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + Controller.prototype.replace = function replace(root, visitor) { + var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key; + function removeElem(element) { + var i, key, nextElem, parent; + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + this.__initialize(root, visitor); + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || target === SKIP) { + continue; + } + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + return outer.root; + }; + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + function extendCommentRange(comment, tokens) { + var target; + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + comment.extendedRange = [comment.range[0], comment.range[1]]; + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + return comment; + } + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], + comment, + len, + i, + cursor; + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + return tree; + } + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { + return clone({}); + }; + return exports; + })(exports); + /* vim: set sw=4 ts=4 et tw=80 : */ + }); + + var parser = createCommonjsModule(function (module) { + /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function (root, factory) { + if ( module.exports) { + module.exports = factory(); + } + })(commonjsGlobal, function () { + + function peg$subclass(child, parent) { + function ctor() { + this.constructor = child; + } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + peg$subclass(peg$SyntaxError, Error); + peg$SyntaxError.buildMessage = function (expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function literal(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + "class": function _class(expectation) { + var escapedParts = "", + i; + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); + } + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + any: function any(expectation) { + return "any character"; + }, + end: function end(expectation) { + return "end of input"; + }, + other: function other(expectation) { + return expectation.description; + } + }; + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + function literalEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function classEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/\]/g, '\\]').replace(/\^/g, '\\^').replace(/-/g, '\\-').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, + j; + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + descriptions.sort(); + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + switch (descriptions.length) { + case 1: + return descriptions[0]; + case 2: + return descriptions[0] + " or " + descriptions[1]; + default: + return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; + } + } + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + var peg$FAILED = {}, + peg$startRuleFunctions = { + start: peg$parsestart + }, + peg$startRuleFunction = peg$parsestart, + peg$c0 = function peg$c0(ss) { + return ss.length === 1 ? ss[0] : { + type: 'matches', + selectors: ss + }; + }, + peg$c1 = function peg$c1() { + return void 0; + }, + peg$c2 = " ", + peg$c3 = peg$literalExpectation(" ", false), + peg$c4 = /^[^ [\],():#!=><~+.]/, + peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), + peg$c6 = function peg$c6(i) { + return i.join(''); + }, + peg$c7 = ">", + peg$c8 = peg$literalExpectation(">", false), + peg$c9 = function peg$c9() { + return 'child'; + }, + peg$c10 = "~", + peg$c11 = peg$literalExpectation("~", false), + peg$c12 = function peg$c12() { + return 'sibling'; + }, + peg$c13 = "+", + peg$c14 = peg$literalExpectation("+", false), + peg$c15 = function peg$c15() { + return 'adjacent'; + }, + peg$c16 = function peg$c16() { + return 'descendant'; + }, + peg$c17 = ",", + peg$c18 = peg$literalExpectation(",", false), + peg$c19 = function peg$c19(s, ss) { + return [s].concat(ss.map(function (s) { + return s[3]; + })); + }, + peg$c20 = function peg$c20(op, s) { + if (!op) return s; + return { + type: op, + left: { + type: 'exactNode' + }, + right: s + }; + }, + peg$c21 = function peg$c21(a, ops) { + return ops.reduce(function (memo, rhs) { + return { + type: rhs[0], + left: memo, + right: rhs[1] + }; + }, a); + }, + peg$c22 = "!", + peg$c23 = peg$literalExpectation("!", false), + peg$c24 = function peg$c24(subject, as) { + var b = as.length === 1 ? as[0] : { + type: 'compound', + selectors: as + }; + if (subject) b.subject = true; + return b; + }, + peg$c25 = "*", + peg$c26 = peg$literalExpectation("*", false), + peg$c27 = function peg$c27(a) { + return { + type: 'wildcard', + value: a + }; + }, + peg$c28 = "#", + peg$c29 = peg$literalExpectation("#", false), + peg$c30 = function peg$c30(i) { + return { + type: 'identifier', + value: i + }; + }, + peg$c31 = "[", + peg$c32 = peg$literalExpectation("[", false), + peg$c33 = "]", + peg$c34 = peg$literalExpectation("]", false), + peg$c35 = function peg$c35(v) { + return v; + }, + peg$c36 = /^[>", "<", "!"], false, false), + peg$c38 = "=", + peg$c39 = peg$literalExpectation("=", false), + peg$c40 = function peg$c40(a) { + return (a || '') + '='; + }, + peg$c41 = /^[><]/, + peg$c42 = peg$classExpectation([">", "<"], false, false), + peg$c43 = ".", + peg$c44 = peg$literalExpectation(".", false), + peg$c45 = function peg$c45(a, as) { + return [].concat.apply([a], as).join(''); + }, + peg$c46 = function peg$c46(name, op, value) { + return { + type: 'attribute', + name: name, + operator: op, + value: value + }; + }, + peg$c47 = function peg$c47(name) { + return { + type: 'attribute', + name: name + }; + }, + peg$c48 = "\"", + peg$c49 = peg$literalExpectation("\"", false), + peg$c50 = /^[^\\"]/, + peg$c51 = peg$classExpectation(["\\", "\""], true, false), + peg$c52 = "\\", + peg$c53 = peg$literalExpectation("\\", false), + peg$c54 = peg$anyExpectation(), + peg$c55 = function peg$c55(a, b) { + return a + b; + }, + peg$c56 = function peg$c56(d) { + return { + type: 'literal', + value: strUnescape(d.join('')) + }; + }, + peg$c57 = "'", + peg$c58 = peg$literalExpectation("'", false), + peg$c59 = /^[^\\']/, + peg$c60 = peg$classExpectation(["\\", "'"], true, false), + peg$c61 = /^[0-9]/, + peg$c62 = peg$classExpectation([["0", "9"]], false, false), + peg$c63 = function peg$c63(a, b) { + // Can use `a.flat().join('')` once supported + var leadingDecimals = a ? [].concat.apply([], a).join('') : ''; + return { + type: 'literal', + value: parseFloat(leadingDecimals + b.join('')) + }; + }, + peg$c64 = function peg$c64(i) { + return { + type: 'literal', + value: i + }; + }, + peg$c65 = "type(", + peg$c66 = peg$literalExpectation("type(", false), + peg$c67 = /^[^ )]/, + peg$c68 = peg$classExpectation([" ", ")"], true, false), + peg$c69 = ")", + peg$c70 = peg$literalExpectation(")", false), + peg$c71 = function peg$c71(t) { + return { + type: 'type', + value: t.join('') + }; + }, + peg$c72 = /^[imsu]/, + peg$c73 = peg$classExpectation(["i", "m", "s", "u"], false, false), + peg$c74 = "/", + peg$c75 = peg$literalExpectation("/", false), + peg$c76 = /^[^\/]/, + peg$c77 = peg$classExpectation(["/"], true, false), + peg$c78 = function peg$c78(d, flgs) { + return { + type: 'regexp', + value: new RegExp(d.join(''), flgs ? flgs.join('') : '') + }; + }, + peg$c79 = function peg$c79(i, is) { + return { + type: 'field', + name: is.reduce(function (memo, p) { + return memo + p[0] + p[1]; + }, i) + }; + }, + peg$c80 = ":not(", + peg$c81 = peg$literalExpectation(":not(", false), + peg$c82 = function peg$c82(ss) { + return { + type: 'not', + selectors: ss + }; + }, + peg$c83 = ":matches(", + peg$c84 = peg$literalExpectation(":matches(", false), + peg$c85 = function peg$c85(ss) { + return { + type: 'matches', + selectors: ss + }; + }, + peg$c86 = ":has(", + peg$c87 = peg$literalExpectation(":has(", false), + peg$c88 = function peg$c88(ss) { + return { + type: 'has', + selectors: ss + }; + }, + peg$c89 = ":first-child", + peg$c90 = peg$literalExpectation(":first-child", false), + peg$c91 = function peg$c91() { + return nth(1); + }, + peg$c92 = ":last-child", + peg$c93 = peg$literalExpectation(":last-child", false), + peg$c94 = function peg$c94() { + return nthLast(1); + }, + peg$c95 = ":nth-child(", + peg$c96 = peg$literalExpectation(":nth-child(", false), + peg$c97 = function peg$c97(n) { + return nth(parseInt(n.join(''), 10)); + }, + peg$c98 = ":nth-last-child(", + peg$c99 = peg$literalExpectation(":nth-last-child(", false), + peg$c100 = function peg$c100(n) { + return nthLast(parseInt(n.join(''), 10)); + }, + peg$c101 = ":", + peg$c102 = peg$literalExpectation(":", false), + peg$c103 = function peg$c103(c) { + return { + type: 'class', + name: c + }; + }, + peg$currPos = 0, + peg$posDetailsCache = [{ + line: 1, + column: 1 + }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$resultsCache = {}, + peg$result; + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + function peg$literalExpectation(text, ignoreCase) { + return { + type: "literal", + text: text, + ignoreCase: ignoreCase + }; + } + function peg$classExpectation(parts, inverted, ignoreCase) { + return { + type: "class", + parts: parts, + inverted: inverted, + ignoreCase: ignoreCase + }; + } + function peg$anyExpectation() { + return { + type: "any" + }; + } + function peg$endExpectation() { + return { + type: "end" + }; + } + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], + p; + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + p++; + } + peg$posDetailsCache[pos] = details; + return details; + } + } + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { + return; + } + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + peg$maxFailExpected.push(expected); + } + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location); + } + function peg$parsestart() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 0, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$parseselectors(); + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c0(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s1 = peg$c1(); + } + s0 = s1; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parse_() { + var s0, s1; + var key = peg$currPos * 32 + 1, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifierName() { + var s0, s1, s2; + var key = peg$currPos * 32 + 2, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = []; + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s1 = peg$c6(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsebinaryOp() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 3, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c8); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c9(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c10; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c11); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c12(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c13; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c14); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c15(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s1 = peg$c16(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 32 + 4, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsehasSelector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 32 + 5, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseselector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelector() { + var s0, s1, s2; + var key = peg$currPos * 32 + 6, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsebinaryOp(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseselector(); + if (s2 !== peg$FAILED) { + s1 = peg$c20(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselector() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 7, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsesequence(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c21(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsesequence() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 8, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseatom(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseatom(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c24(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseatom() { + var s0; + var key = peg$currPos * 32 + 9, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$parsewildcard(); + if (s0 === peg$FAILED) { + s0 = peg$parseidentifier(); + if (s0 === peg$FAILED) { + s0 = peg$parseattr(); + if (s0 === peg$FAILED) { + s0 = peg$parsefield(); + if (s0 === peg$FAILED) { + s0 = peg$parsenegation(); + if (s0 === peg$FAILED) { + s0 = peg$parsematches(); + if (s0 === peg$FAILED) { + s0 = peg$parsehas(); + if (s0 === peg$FAILED) { + s0 = peg$parsefirstChild(); + if (s0 === peg$FAILED) { + s0 = peg$parselastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthLastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parseclass(); + } + } + } + } + } + } + } + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsewildcard() { + var s0, s1; + var key = peg$currPos * 32 + 10, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c25; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c26); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c27(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifier() { + var s0, s1, s2; + var key = peg$currPos * 32 + 11, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c28; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c30(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattr() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 12, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c32); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrValue(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c33; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c34); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c35(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrOps() { + var s0, s1, s2; + var key = peg$currPos * 32 + 13, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (peg$c36.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (peg$c41.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + { + peg$fail(peg$c42); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrEqOps() { + var s0, s1, s2; + var key = peg$currPos * 32 + 14, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrName() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 15, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c45(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrValue() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 16, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrEqOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetype(); + if (s5 === peg$FAILED) { + s5 = peg$parseregex(); + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsestring(); + if (s5 === peg$FAILED) { + s5 = peg$parsenumber(); + if (s5 === peg$FAILED) { + s5 = peg$parsepath(); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s1 = peg$c47(s1); + } + s0 = s1; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsestring() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 17, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c48; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c48; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c57; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c57; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenumber() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 18, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c43; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c63(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsepath() { + var s0, s1; + var key = peg$currPos * 32 + 19, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s1 = peg$c64(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsetype() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 20, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c65) { + s1 = peg$c65; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c66); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c71(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseflags() { + var s0, s1; + var key = peg$currPos * 32 + 21, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + } + } else { + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseregex() { + var s0, s1, s2, s3, s4; + var key = peg$currPos * 32 + 22, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c74; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c76.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c77); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c76.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c77); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s3 = peg$c74; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseflags(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = peg$c78(s2, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefield() { + var s0, s1, s2, s3, s4, s5, s6; + var key = peg$currPos * 32 + 23, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c43; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c79(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenegation() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 24, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c80) { + s1 = peg$c80; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c81); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c82(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsematches() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 25, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c83) { + s1 = peg$c83; + peg$currPos += 9; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c84); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c85(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehas() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 26, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c86) { + s1 = peg$c86; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c87); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehasSelectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c88(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefirstChild() { + var s0, s1; + var key = peg$currPos * 32 + 27, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 12) === peg$c89) { + s1 = peg$c89; + peg$currPos += 12; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c90); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c91(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parselastChild() { + var s0, s1; + var key = peg$currPos * 32 + 28, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c92) { + s1 = peg$c92; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c93); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c94(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 29, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c95) { + s1 = peg$c95; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c96); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c97(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthLastChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 30, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 16) === peg$c98) { + s1 = peg$c98; + peg$currPos += 16; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c99); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c100(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseclass() { + var s0, s1, s2; + var key = peg$currPos * 32 + 31, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c101; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c102); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c103(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function nth(n) { + return { + type: 'nth-child', + index: { + type: 'literal', + value: n + } + }; + } + function nthLast(n) { + return { + type: 'nth-last-child', + index: { + type: 'literal', + value: n + } + }; + } + function strUnescape(s) { + return s.replace(/\\(.)/g, function (match, ch) { + switch (ch) { + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + default: + return ch; + } + }); + } + peg$result = peg$startRuleFunction(); + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); + } + } + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + }); + }); + + /** + * @typedef {"LEFT_SIDE"|"RIGHT_SIDE"} Side + */ + + var LEFT_SIDE = 'LEFT_SIDE'; + var RIGHT_SIDE = 'RIGHT_SIDE'; + + /** + * @external AST + * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html + */ + + /** + * One of the rules of `grammar.pegjs` + * @typedef {PlainObject} SelectorAST + * @see grammar.pegjs + */ + + /** + * The `sequence` production of `grammar.pegjs` + * @typedef {PlainObject} SelectorSequenceAST + */ + + /** + * Get the value of a property which may be multiple levels down + * in the object. + * @param {?PlainObject} obj + * @param {string[]} keys + * @returns {undefined|boolean|string|number|external:AST} + */ + function getPath(obj, keys) { + for (var i = 0; i < keys.length; ++i) { + if (obj == null) { + return obj; + } + obj = obj[keys[i]]; + } + return obj; + } + + /** + * Determine whether `node` can be reached by following `path`, + * starting at `ancestor`. + * @param {?external:AST} node + * @param {?external:AST} ancestor + * @param {string[]} path + * @param {Integer} fromPathIndex + * @returns {boolean} + */ + function inPath(node, ancestor, path, fromPathIndex) { + var current = ancestor; + for (var i = fromPathIndex; i < path.length; ++i) { + if (current == null) { + return false; + } + var field = current[path[i]]; + if (Array.isArray(field)) { + for (var k = 0; k < field.length; ++k) { + if (inPath(node, field[k], path, i + 1)) { + return true; + } + } + return false; + } + current = field; + } + return node === current; + } + + /** + * A generated matcher function for a selector. + * @callback SelectorMatcher + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @returns {void} + */ + + /** + * A WeakMap for holding cached matcher functions for selectors. + * @type {WeakMap} + */ + var MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap() : null; + + /** + * Look up a matcher function for `selector` in the cache. + * If it does not exist, generate it with `generateMatcher` and add it to the cache. + * In engines without WeakMap, the caching is skipped and matchers are generated with every call. + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ + function getMatcher(selector) { + if (selector == null) { + return function () { + return true; + }; + } + if (MATCHER_CACHE != null) { + var matcher = MATCHER_CACHE.get(selector); + if (matcher != null) { + return matcher; + } + matcher = generateMatcher(selector); + MATCHER_CACHE.set(selector, matcher); + return matcher; + } + return generateMatcher(selector); + } + + /** + * Create a matcher function for `selector`, + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ + function generateMatcher(selector) { + switch (selector.type) { + case 'wildcard': + return function () { + return true; + }; + case 'identifier': + { + var value = selector.value.toLowerCase(); + return function (node, ancestry, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return value === node[nodeTypeKey].toLowerCase(); + }; + } + case 'exactNode': + return function (node, ancestry) { + return ancestry.length === 0; + }; + case 'field': + { + var path = selector.name.split('.'); + return function (node, ancestry) { + var ancestor = ancestry[path.length - 1]; + return inPath(node, ancestor, path, 0); + }; + } + case 'matches': + { + var matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < matchers.length; ++i) { + if (matchers[i](node, ancestry, options)) { + return true; + } + } + return false; + }; + } + case 'compound': + { + var _matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers.length; ++i) { + if (!_matchers[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'not': + { + var _matchers2 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers2.length; ++i) { + if (_matchers2[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'has': + { + var _matchers3 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + var result = false; + var a = []; + estraverse.traverse(node, { + enter: function enter(node, parent) { + if (parent != null) { + a.unshift(parent); + } + for (var i = 0; i < _matchers3.length; ++i) { + if (_matchers3[i](node, a, options)) { + result = true; + this["break"](); + return; + } + } + }, + leave: function leave() { + a.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + return result; + }; + } + case 'child': + { + var left = getMatcher(selector.left); + var right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (ancestry.length > 0 && right(node, ancestry, options)) { + return left(ancestry[0], ancestry.slice(1), options); + } + return false; + }; + } + case 'descendant': + { + var _left = getMatcher(selector.left); + var _right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (_right(node, ancestry, options)) { + for (var i = 0, l = ancestry.length; i < l; ++i) { + if (_left(ancestry[i], ancestry.slice(i + 1), options)) { + return true; + } + } + } + return false; + }; + } + case 'attribute': + { + var _path = selector.name.split('.'); + switch (selector.operator) { + case void 0: + return function (node) { + return getPath(node, _path) != null; + }; + case '=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + var p = getPath(node, _path); + return typeof p === 'string' && selector.value.value.test(p); + }; + case 'literal': + { + var literal = "".concat(selector.value.value); + return function (node) { + return literal === "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value === _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '!=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + return !selector.value.value.test(getPath(node, _path)); + }; + case 'literal': + { + var _literal = "".concat(selector.value.value); + return function (node) { + return _literal !== "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value !== _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '<=': + return function (node) { + return getPath(node, _path) <= selector.value.value; + }; + case '<': + return function (node) { + return getPath(node, _path) < selector.value.value; + }; + case '>': + return function (node) { + return getPath(node, _path) > selector.value.value; + }; + case '>=': + return function (node) { + return getPath(node, _path) >= selector.value.value; + }; + } + throw new Error("Unknown operator: ".concat(selector.operator)); + } + case 'sibling': + { + var _left2 = getMatcher(selector.left); + var _right2 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right2(node, ancestry, options) && sibling(node, _left2, ancestry, LEFT_SIDE, options) || selector.left.subject && _left2(node, ancestry, options) && sibling(node, _right2, ancestry, RIGHT_SIDE, options); + }; + } + case 'adjacent': + { + var _left3 = getMatcher(selector.left); + var _right3 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right3(node, ancestry, options) && adjacent(node, _left3, ancestry, LEFT_SIDE, options) || selector.right.subject && _left3(node, ancestry, options) && adjacent(node, _right3, ancestry, RIGHT_SIDE, options); + }; + } + case 'nth-child': + { + var nth = selector.index.value; + var _right4 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right4(node, ancestry, options) && nthChild(node, ancestry, nth, options); + }; + } + case 'nth-last-child': + { + var _nth = -selector.index.value; + var _right5 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right5(node, ancestry, options) && nthChild(node, ancestry, _nth, options); + }; + } + case 'class': + { + var name = selector.name.toLowerCase(); + return function (node, ancestry, options) { + if (options && options.matchClass) { + return options.matchClass(selector.name, node, ancestry); + } + if (options && options.nodeTypeKey) return false; + switch (name) { + case 'statement': + if (node.type.slice(-9) === 'Statement') return true; + // fallthrough: interface Declaration <: Statement { } + case 'declaration': + return node.type.slice(-11) === 'Declaration'; + case 'pattern': + if (node.type.slice(-7) === 'Pattern') return true; + // fallthrough: interface Expression <: Node, Pattern { } + case 'expression': + return node.type.slice(-10) === 'Expression' || node.type.slice(-7) === 'Literal' || node.type === 'Identifier' && (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty') || node.type === 'MetaProperty'; + case 'function': + return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; + } + throw new Error("Unknown class name: ".concat(selector.name)); + }; + } + } + throw new Error("Unknown selector type: ".concat(selector.type)); + } + + /** + * @callback TraverseOptionFallback + * @param {external:AST} node The given node. + * @returns {string[]} An array of visitor keys for the given node. + */ + + /** + * @callback ClassMatcher + * @param {string} className The name of the class to match. + * @param {external:AST} node The node to match against. + * @param {Array} ancestry The ancestry of the node. + * @returns {boolean} True if the node matches the class, false if not. + */ + + /** + * @typedef {object} ESQueryOptions + * @property {string} [nodeTypeKey="type"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery. + * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node. + * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes. + * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes. + */ + + /** + * Given a `node` and its ancestors, determine if `node` is matched + * by `selector`. + * @param {?external:AST} node + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @throws {Error} Unknowns (operator, class name, selector type, or + * selector value type) + * @returns {boolean} + */ + function matches(node, selector, ancestry, options) { + if (!selector) { + return true; + } + if (!node) { + return false; + } + if (!ancestry) { + ancestry = []; + } + return getMatcher(selector)(node, ancestry, options); + } + + /** + * Get visitor keys of a given node. + * @param {external:AST} node The AST node to get keys. + * @param {ESQueryOptions|undefined} options + * @returns {string[]} Visitor keys of the node. + */ + function getVisitorKeys(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + var nodeType = node[nodeTypeKey]; + if (options && options.visitorKeys && options.visitorKeys[nodeType]) { + return options.visitorKeys[nodeType]; + } + if (estraverse.VisitorKeys[nodeType]) { + return estraverse.VisitorKeys[nodeType]; + } + if (options && typeof options.fallback === 'function') { + return options.fallback(node); + } + // 'iteration' fallback + return Object.keys(node).filter(function (key) { + return key !== nodeTypeKey; + }); + } + + /** + * Check whether the given value is an ASTNode or not. + * @param {any} node The value to check. + * @param {ESQueryOptions|undefined} options The options to use. + * @returns {boolean} `true` if the value is an ASTNode. + */ + function isNode(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return node !== null && _typeof(node) === 'object' && typeof node[nodeTypeKey] === 'string'; + } + + /** + * Determines if the given node has a sibling that matches the + * given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function sibling(node, matcher, ancestry, side, options) { + var _ancestry = _slicedToArray(ancestry, 1), + parent = _ancestry[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var startIndex = listProp.indexOf(node); + if (startIndex < 0) { + continue; + } + var lowerBound = void 0, + upperBound = void 0; + if (side === LEFT_SIDE) { + lowerBound = 0; + upperBound = startIndex; + } else { + lowerBound = startIndex + 1; + upperBound = listProp.length; + } + for (var k = lowerBound; k < upperBound; ++k) { + if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) { + return true; + } + } + } + } + return false; + } + + /** + * Determines if the given node has an adjacent sibling that matches + * the given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function adjacent(node, matcher, ancestry, side, options) { + var _ancestry2 = _slicedToArray(ancestry, 1), + parent = _ancestry2[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = listProp.indexOf(node); + if (idx < 0) { + continue; + } + if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) { + return true; + } + if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) { + return true; + } + } + } + return false; + } + + /** + * Determines if the given node is the `nth` child. + * If `nth` is negative then the position is counted + * from the end of the list of children. + * @param {external:AST} node + * @param {external:AST[]} ancestry + * @param {Integer} nth + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function nthChild(node, ancestry, nth, options) { + if (nth === 0) { + return false; + } + var _ancestry3 = _slicedToArray(ancestry, 1), + parent = _ancestry3[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = nth < 0 ? listProp.length + nth : nth - 1; + if (idx >= 0 && idx < listProp.length && listProp[idx] === node) { + return true; + } + } + } + return false; + } + + /** + * For each selector node marked as a subject, find the portion of the + * selector that the subject must match. + * @param {SelectorAST} selector + * @param {SelectorAST} [ancestor] Defaults to `selector` + * @returns {SelectorAST[]} + */ + function subjects(selector, ancestor) { + if (selector == null || _typeof(selector) != 'object') { + return []; + } + if (ancestor == null) { + ancestor = selector; + } + var results = selector.subject ? [ancestor] : []; + var keys = Object.keys(selector); + for (var i = 0; i < keys.length; ++i) { + var p = keys[i]; + var sel = selector[p]; + results.push.apply(results, _toConsumableArray(subjects(sel, p === 'left' ? sel : ancestor))); + } + return results; + } + + /** + * @callback TraverseVisitor + * @param {?external:AST} node + * @param {?external:AST} parent + * @param {external:AST[]} ancestry + */ + + /** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {TraverseVisitor} visitor + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function traverse(ast, selector, visitor, options) { + if (!selector) { + return; + } + var ancestry = []; + var matcher = getMatcher(selector); + var altSubjects = subjects(selector).map(getMatcher); + estraverse.traverse(ast, { + enter: function enter(node, parent) { + if (parent != null) { + ancestry.unshift(parent); + } + if (matcher(node, ancestry, options)) { + if (altSubjects.length) { + for (var i = 0, l = altSubjects.length; i < l; ++i) { + if (altSubjects[i](node, ancestry, options)) { + visitor(node, parent, ancestry); + } + for (var k = 0, m = ancestry.length; k < m; ++k) { + var succeedingAncestry = ancestry.slice(k + 1); + if (altSubjects[i](ancestry[k], succeedingAncestry, options)) { + visitor(ancestry[k], parent, succeedingAncestry); + } + } + } + } else { + visitor(node, parent, ancestry); + } + } + }, + leave: function leave() { + ancestry.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + } + + /** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function match(ast, selector, options) { + var results = []; + traverse(ast, selector, function (node) { + results.push(node); + }, options); + return results; + } + + /** + * Parse a selector string and return its AST. + * @param {string} selector + * @returns {SelectorAST} + */ + function parse(selector) { + return parser.parse(selector); + } + + /** + * Query the code AST using the selector string. + * @param {external:AST} ast + * @param {string} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function query(ast, selector, options) { + return match(ast, parse(selector), options); + } + query.parse = parse; + query.match = match; + query.traverse = traverse; + query.matches = matches; + query.query = query; + + return query; + +}))); diff --git a/node_modules/esquery/dist/esquery.lite.js b/node_modules/esquery/dist/esquery.lite.js new file mode 100644 index 00000000..170c9336 --- /dev/null +++ b/node_modules/esquery/dist/esquery.lite.js @@ -0,0 +1,3470 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('estraverse')) : + typeof define === 'function' && define.amd ? define(['estraverse'], factory) : + (global = global || self, global.esquery = factory(global.estraverse)); +}(this, (function (estraverse) { 'use strict'; + + estraverse = estraverse && Object.prototype.hasOwnProperty.call(estraverse, 'default') ? estraverse['default'] : estraverse; + + function _iterableToArrayLimit(arr, i) { + var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; + if (null != _i) { + var _s, + _e, + _x, + _r, + _arr = [], + _n = !0, + _d = !1; + try { + if (_x = (_i = _i.call(arr)).next, 0 === i) { + if (Object(_i) !== _i) return; + _n = !1; + } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); + } catch (err) { + _d = !0, _e = err; + } finally { + try { + if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; + } finally { + if (_d) throw _e; + } + } + return _arr; + } + } + function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); + } + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); + } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); + } + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + } + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; + } + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var parser = createCommonjsModule(function (module) { + /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function (root, factory) { + if ( module.exports) { + module.exports = factory(); + } + })(commonjsGlobal, function () { + + function peg$subclass(child, parent) { + function ctor() { + this.constructor = child; + } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + peg$subclass(peg$SyntaxError, Error); + peg$SyntaxError.buildMessage = function (expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function literal(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + "class": function _class(expectation) { + var escapedParts = "", + i; + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); + } + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + any: function any(expectation) { + return "any character"; + }, + end: function end(expectation) { + return "end of input"; + }, + other: function other(expectation) { + return expectation.description; + } + }; + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + function literalEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function classEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/\]/g, '\\]').replace(/\^/g, '\\^').replace(/-/g, '\\-').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, + j; + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + descriptions.sort(); + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + switch (descriptions.length) { + case 1: + return descriptions[0]; + case 2: + return descriptions[0] + " or " + descriptions[1]; + default: + return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; + } + } + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + var peg$FAILED = {}, + peg$startRuleFunctions = { + start: peg$parsestart + }, + peg$startRuleFunction = peg$parsestart, + peg$c0 = function peg$c0(ss) { + return ss.length === 1 ? ss[0] : { + type: 'matches', + selectors: ss + }; + }, + peg$c1 = function peg$c1() { + return void 0; + }, + peg$c2 = " ", + peg$c3 = peg$literalExpectation(" ", false), + peg$c4 = /^[^ [\],():#!=><~+.]/, + peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), + peg$c6 = function peg$c6(i) { + return i.join(''); + }, + peg$c7 = ">", + peg$c8 = peg$literalExpectation(">", false), + peg$c9 = function peg$c9() { + return 'child'; + }, + peg$c10 = "~", + peg$c11 = peg$literalExpectation("~", false), + peg$c12 = function peg$c12() { + return 'sibling'; + }, + peg$c13 = "+", + peg$c14 = peg$literalExpectation("+", false), + peg$c15 = function peg$c15() { + return 'adjacent'; + }, + peg$c16 = function peg$c16() { + return 'descendant'; + }, + peg$c17 = ",", + peg$c18 = peg$literalExpectation(",", false), + peg$c19 = function peg$c19(s, ss) { + return [s].concat(ss.map(function (s) { + return s[3]; + })); + }, + peg$c20 = function peg$c20(op, s) { + if (!op) return s; + return { + type: op, + left: { + type: 'exactNode' + }, + right: s + }; + }, + peg$c21 = function peg$c21(a, ops) { + return ops.reduce(function (memo, rhs) { + return { + type: rhs[0], + left: memo, + right: rhs[1] + }; + }, a); + }, + peg$c22 = "!", + peg$c23 = peg$literalExpectation("!", false), + peg$c24 = function peg$c24(subject, as) { + var b = as.length === 1 ? as[0] : { + type: 'compound', + selectors: as + }; + if (subject) b.subject = true; + return b; + }, + peg$c25 = "*", + peg$c26 = peg$literalExpectation("*", false), + peg$c27 = function peg$c27(a) { + return { + type: 'wildcard', + value: a + }; + }, + peg$c28 = "#", + peg$c29 = peg$literalExpectation("#", false), + peg$c30 = function peg$c30(i) { + return { + type: 'identifier', + value: i + }; + }, + peg$c31 = "[", + peg$c32 = peg$literalExpectation("[", false), + peg$c33 = "]", + peg$c34 = peg$literalExpectation("]", false), + peg$c35 = function peg$c35(v) { + return v; + }, + peg$c36 = /^[>", "<", "!"], false, false), + peg$c38 = "=", + peg$c39 = peg$literalExpectation("=", false), + peg$c40 = function peg$c40(a) { + return (a || '') + '='; + }, + peg$c41 = /^[><]/, + peg$c42 = peg$classExpectation([">", "<"], false, false), + peg$c43 = ".", + peg$c44 = peg$literalExpectation(".", false), + peg$c45 = function peg$c45(a, as) { + return [].concat.apply([a], as).join(''); + }, + peg$c46 = function peg$c46(name, op, value) { + return { + type: 'attribute', + name: name, + operator: op, + value: value + }; + }, + peg$c47 = function peg$c47(name) { + return { + type: 'attribute', + name: name + }; + }, + peg$c48 = "\"", + peg$c49 = peg$literalExpectation("\"", false), + peg$c50 = /^[^\\"]/, + peg$c51 = peg$classExpectation(["\\", "\""], true, false), + peg$c52 = "\\", + peg$c53 = peg$literalExpectation("\\", false), + peg$c54 = peg$anyExpectation(), + peg$c55 = function peg$c55(a, b) { + return a + b; + }, + peg$c56 = function peg$c56(d) { + return { + type: 'literal', + value: strUnescape(d.join('')) + }; + }, + peg$c57 = "'", + peg$c58 = peg$literalExpectation("'", false), + peg$c59 = /^[^\\']/, + peg$c60 = peg$classExpectation(["\\", "'"], true, false), + peg$c61 = /^[0-9]/, + peg$c62 = peg$classExpectation([["0", "9"]], false, false), + peg$c63 = function peg$c63(a, b) { + // Can use `a.flat().join('')` once supported + var leadingDecimals = a ? [].concat.apply([], a).join('') : ''; + return { + type: 'literal', + value: parseFloat(leadingDecimals + b.join('')) + }; + }, + peg$c64 = function peg$c64(i) { + return { + type: 'literal', + value: i + }; + }, + peg$c65 = "type(", + peg$c66 = peg$literalExpectation("type(", false), + peg$c67 = /^[^ )]/, + peg$c68 = peg$classExpectation([" ", ")"], true, false), + peg$c69 = ")", + peg$c70 = peg$literalExpectation(")", false), + peg$c71 = function peg$c71(t) { + return { + type: 'type', + value: t.join('') + }; + }, + peg$c72 = /^[imsu]/, + peg$c73 = peg$classExpectation(["i", "m", "s", "u"], false, false), + peg$c74 = "/", + peg$c75 = peg$literalExpectation("/", false), + peg$c76 = /^[^\/]/, + peg$c77 = peg$classExpectation(["/"], true, false), + peg$c78 = function peg$c78(d, flgs) { + return { + type: 'regexp', + value: new RegExp(d.join(''), flgs ? flgs.join('') : '') + }; + }, + peg$c79 = function peg$c79(i, is) { + return { + type: 'field', + name: is.reduce(function (memo, p) { + return memo + p[0] + p[1]; + }, i) + }; + }, + peg$c80 = ":not(", + peg$c81 = peg$literalExpectation(":not(", false), + peg$c82 = function peg$c82(ss) { + return { + type: 'not', + selectors: ss + }; + }, + peg$c83 = ":matches(", + peg$c84 = peg$literalExpectation(":matches(", false), + peg$c85 = function peg$c85(ss) { + return { + type: 'matches', + selectors: ss + }; + }, + peg$c86 = ":has(", + peg$c87 = peg$literalExpectation(":has(", false), + peg$c88 = function peg$c88(ss) { + return { + type: 'has', + selectors: ss + }; + }, + peg$c89 = ":first-child", + peg$c90 = peg$literalExpectation(":first-child", false), + peg$c91 = function peg$c91() { + return nth(1); + }, + peg$c92 = ":last-child", + peg$c93 = peg$literalExpectation(":last-child", false), + peg$c94 = function peg$c94() { + return nthLast(1); + }, + peg$c95 = ":nth-child(", + peg$c96 = peg$literalExpectation(":nth-child(", false), + peg$c97 = function peg$c97(n) { + return nth(parseInt(n.join(''), 10)); + }, + peg$c98 = ":nth-last-child(", + peg$c99 = peg$literalExpectation(":nth-last-child(", false), + peg$c100 = function peg$c100(n) { + return nthLast(parseInt(n.join(''), 10)); + }, + peg$c101 = ":", + peg$c102 = peg$literalExpectation(":", false), + peg$c103 = function peg$c103(c) { + return { + type: 'class', + name: c + }; + }, + peg$currPos = 0, + peg$posDetailsCache = [{ + line: 1, + column: 1 + }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$resultsCache = {}, + peg$result; + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + function peg$literalExpectation(text, ignoreCase) { + return { + type: "literal", + text: text, + ignoreCase: ignoreCase + }; + } + function peg$classExpectation(parts, inverted, ignoreCase) { + return { + type: "class", + parts: parts, + inverted: inverted, + ignoreCase: ignoreCase + }; + } + function peg$anyExpectation() { + return { + type: "any" + }; + } + function peg$endExpectation() { + return { + type: "end" + }; + } + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], + p; + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + p++; + } + peg$posDetailsCache[pos] = details; + return details; + } + } + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { + return; + } + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + peg$maxFailExpected.push(expected); + } + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location); + } + function peg$parsestart() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 0, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$parseselectors(); + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c0(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s1 = peg$c1(); + } + s0 = s1; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parse_() { + var s0, s1; + var key = peg$currPos * 32 + 1, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifierName() { + var s0, s1, s2; + var key = peg$currPos * 32 + 2, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = []; + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s1 = peg$c6(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsebinaryOp() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 3, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c8); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c9(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c10; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c11); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c12(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c13; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c14); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c15(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s1 = peg$c16(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 32 + 4, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsehasSelector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 32 + 5, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseselector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelector() { + var s0, s1, s2; + var key = peg$currPos * 32 + 6, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsebinaryOp(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseselector(); + if (s2 !== peg$FAILED) { + s1 = peg$c20(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselector() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 7, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsesequence(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c21(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsesequence() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 8, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseatom(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseatom(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c24(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseatom() { + var s0; + var key = peg$currPos * 32 + 9, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$parsewildcard(); + if (s0 === peg$FAILED) { + s0 = peg$parseidentifier(); + if (s0 === peg$FAILED) { + s0 = peg$parseattr(); + if (s0 === peg$FAILED) { + s0 = peg$parsefield(); + if (s0 === peg$FAILED) { + s0 = peg$parsenegation(); + if (s0 === peg$FAILED) { + s0 = peg$parsematches(); + if (s0 === peg$FAILED) { + s0 = peg$parsehas(); + if (s0 === peg$FAILED) { + s0 = peg$parsefirstChild(); + if (s0 === peg$FAILED) { + s0 = peg$parselastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthLastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parseclass(); + } + } + } + } + } + } + } + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsewildcard() { + var s0, s1; + var key = peg$currPos * 32 + 10, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c25; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c26); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c27(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifier() { + var s0, s1, s2; + var key = peg$currPos * 32 + 11, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c28; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c30(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattr() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 12, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c32); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrValue(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c33; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c34); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c35(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrOps() { + var s0, s1, s2; + var key = peg$currPos * 32 + 13, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (peg$c36.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (peg$c41.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + { + peg$fail(peg$c42); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrEqOps() { + var s0, s1, s2; + var key = peg$currPos * 32 + 14, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrName() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 15, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c45(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrValue() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 16, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrEqOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetype(); + if (s5 === peg$FAILED) { + s5 = peg$parseregex(); + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsestring(); + if (s5 === peg$FAILED) { + s5 = peg$parsenumber(); + if (s5 === peg$FAILED) { + s5 = peg$parsepath(); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s1 = peg$c47(s1); + } + s0 = s1; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsestring() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 17, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c48; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c48; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c57; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c57; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenumber() { + var s0, s1, s2, s3; + var key = peg$currPos * 32 + 18, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c43; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c63(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsepath() { + var s0, s1; + var key = peg$currPos * 32 + 19, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s1 = peg$c64(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsetype() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 20, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c65) { + s1 = peg$c65; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c66); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c71(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseflags() { + var s0, s1; + var key = peg$currPos * 32 + 21, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + } + } else { + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseregex() { + var s0, s1, s2, s3, s4; + var key = peg$currPos * 32 + 22, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c74; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c76.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c77); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c76.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c77); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s3 = peg$c74; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseflags(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = peg$c78(s2, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefield() { + var s0, s1, s2, s3, s4, s5, s6; + var key = peg$currPos * 32 + 23, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c43; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c79(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenegation() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 24, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c80) { + s1 = peg$c80; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c81); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c82(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsematches() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 25, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c83) { + s1 = peg$c83; + peg$currPos += 9; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c84); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c85(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehas() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 26, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c86) { + s1 = peg$c86; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c87); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehasSelectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c88(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefirstChild() { + var s0, s1; + var key = peg$currPos * 32 + 27, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 12) === peg$c89) { + s1 = peg$c89; + peg$currPos += 12; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c90); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c91(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parselastChild() { + var s0, s1; + var key = peg$currPos * 32 + 28, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c92) { + s1 = peg$c92; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c93); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c94(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 29, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c95) { + s1 = peg$c95; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c96); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c97(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthLastChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 32 + 30, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 16) === peg$c98) { + s1 = peg$c98; + peg$currPos += 16; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c99); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c100(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseclass() { + var s0, s1, s2; + var key = peg$currPos * 32 + 31, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c101; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c102); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c103(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function nth(n) { + return { + type: 'nth-child', + index: { + type: 'literal', + value: n + } + }; + } + function nthLast(n) { + return { + type: 'nth-last-child', + index: { + type: 'literal', + value: n + } + }; + } + function strUnescape(s) { + return s.replace(/\\(.)/g, function (match, ch) { + switch (ch) { + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + default: + return ch; + } + }); + } + peg$result = peg$startRuleFunction(); + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); + } + } + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + }); + }); + + /** + * @typedef {"LEFT_SIDE"|"RIGHT_SIDE"} Side + */ + + var LEFT_SIDE = 'LEFT_SIDE'; + var RIGHT_SIDE = 'RIGHT_SIDE'; + + /** + * @external AST + * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html + */ + + /** + * One of the rules of `grammar.pegjs` + * @typedef {PlainObject} SelectorAST + * @see grammar.pegjs + */ + + /** + * The `sequence` production of `grammar.pegjs` + * @typedef {PlainObject} SelectorSequenceAST + */ + + /** + * Get the value of a property which may be multiple levels down + * in the object. + * @param {?PlainObject} obj + * @param {string[]} keys + * @returns {undefined|boolean|string|number|external:AST} + */ + function getPath(obj, keys) { + for (var i = 0; i < keys.length; ++i) { + if (obj == null) { + return obj; + } + obj = obj[keys[i]]; + } + return obj; + } + + /** + * Determine whether `node` can be reached by following `path`, + * starting at `ancestor`. + * @param {?external:AST} node + * @param {?external:AST} ancestor + * @param {string[]} path + * @param {Integer} fromPathIndex + * @returns {boolean} + */ + function inPath(node, ancestor, path, fromPathIndex) { + var current = ancestor; + for (var i = fromPathIndex; i < path.length; ++i) { + if (current == null) { + return false; + } + var field = current[path[i]]; + if (Array.isArray(field)) { + for (var k = 0; k < field.length; ++k) { + if (inPath(node, field[k], path, i + 1)) { + return true; + } + } + return false; + } + current = field; + } + return node === current; + } + + /** + * A generated matcher function for a selector. + * @callback SelectorMatcher + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @returns {void} + */ + + /** + * A WeakMap for holding cached matcher functions for selectors. + * @type {WeakMap} + */ + var MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap() : null; + + /** + * Look up a matcher function for `selector` in the cache. + * If it does not exist, generate it with `generateMatcher` and add it to the cache. + * In engines without WeakMap, the caching is skipped and matchers are generated with every call. + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ + function getMatcher(selector) { + if (selector == null) { + return function () { + return true; + }; + } + if (MATCHER_CACHE != null) { + var matcher = MATCHER_CACHE.get(selector); + if (matcher != null) { + return matcher; + } + matcher = generateMatcher(selector); + MATCHER_CACHE.set(selector, matcher); + return matcher; + } + return generateMatcher(selector); + } + + /** + * Create a matcher function for `selector`, + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ + function generateMatcher(selector) { + switch (selector.type) { + case 'wildcard': + return function () { + return true; + }; + case 'identifier': + { + var value = selector.value.toLowerCase(); + return function (node, ancestry, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return value === node[nodeTypeKey].toLowerCase(); + }; + } + case 'exactNode': + return function (node, ancestry) { + return ancestry.length === 0; + }; + case 'field': + { + var path = selector.name.split('.'); + return function (node, ancestry) { + var ancestor = ancestry[path.length - 1]; + return inPath(node, ancestor, path, 0); + }; + } + case 'matches': + { + var matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < matchers.length; ++i) { + if (matchers[i](node, ancestry, options)) { + return true; + } + } + return false; + }; + } + case 'compound': + { + var _matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers.length; ++i) { + if (!_matchers[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'not': + { + var _matchers2 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers2.length; ++i) { + if (_matchers2[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'has': + { + var _matchers3 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + var result = false; + var a = []; + estraverse.traverse(node, { + enter: function enter(node, parent) { + if (parent != null) { + a.unshift(parent); + } + for (var i = 0; i < _matchers3.length; ++i) { + if (_matchers3[i](node, a, options)) { + result = true; + this["break"](); + return; + } + } + }, + leave: function leave() { + a.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + return result; + }; + } + case 'child': + { + var left = getMatcher(selector.left); + var right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (ancestry.length > 0 && right(node, ancestry, options)) { + return left(ancestry[0], ancestry.slice(1), options); + } + return false; + }; + } + case 'descendant': + { + var _left = getMatcher(selector.left); + var _right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (_right(node, ancestry, options)) { + for (var i = 0, l = ancestry.length; i < l; ++i) { + if (_left(ancestry[i], ancestry.slice(i + 1), options)) { + return true; + } + } + } + return false; + }; + } + case 'attribute': + { + var _path = selector.name.split('.'); + switch (selector.operator) { + case void 0: + return function (node) { + return getPath(node, _path) != null; + }; + case '=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + var p = getPath(node, _path); + return typeof p === 'string' && selector.value.value.test(p); + }; + case 'literal': + { + var literal = "".concat(selector.value.value); + return function (node) { + return literal === "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value === _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '!=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + return !selector.value.value.test(getPath(node, _path)); + }; + case 'literal': + { + var _literal = "".concat(selector.value.value); + return function (node) { + return _literal !== "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value !== _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '<=': + return function (node) { + return getPath(node, _path) <= selector.value.value; + }; + case '<': + return function (node) { + return getPath(node, _path) < selector.value.value; + }; + case '>': + return function (node) { + return getPath(node, _path) > selector.value.value; + }; + case '>=': + return function (node) { + return getPath(node, _path) >= selector.value.value; + }; + } + throw new Error("Unknown operator: ".concat(selector.operator)); + } + case 'sibling': + { + var _left2 = getMatcher(selector.left); + var _right2 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right2(node, ancestry, options) && sibling(node, _left2, ancestry, LEFT_SIDE, options) || selector.left.subject && _left2(node, ancestry, options) && sibling(node, _right2, ancestry, RIGHT_SIDE, options); + }; + } + case 'adjacent': + { + var _left3 = getMatcher(selector.left); + var _right3 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right3(node, ancestry, options) && adjacent(node, _left3, ancestry, LEFT_SIDE, options) || selector.right.subject && _left3(node, ancestry, options) && adjacent(node, _right3, ancestry, RIGHT_SIDE, options); + }; + } + case 'nth-child': + { + var nth = selector.index.value; + var _right4 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right4(node, ancestry, options) && nthChild(node, ancestry, nth, options); + }; + } + case 'nth-last-child': + { + var _nth = -selector.index.value; + var _right5 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right5(node, ancestry, options) && nthChild(node, ancestry, _nth, options); + }; + } + case 'class': + { + var name = selector.name.toLowerCase(); + return function (node, ancestry, options) { + if (options && options.matchClass) { + return options.matchClass(selector.name, node, ancestry); + } + if (options && options.nodeTypeKey) return false; + switch (name) { + case 'statement': + if (node.type.slice(-9) === 'Statement') return true; + // fallthrough: interface Declaration <: Statement { } + case 'declaration': + return node.type.slice(-11) === 'Declaration'; + case 'pattern': + if (node.type.slice(-7) === 'Pattern') return true; + // fallthrough: interface Expression <: Node, Pattern { } + case 'expression': + return node.type.slice(-10) === 'Expression' || node.type.slice(-7) === 'Literal' || node.type === 'Identifier' && (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty') || node.type === 'MetaProperty'; + case 'function': + return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; + } + throw new Error("Unknown class name: ".concat(selector.name)); + }; + } + } + throw new Error("Unknown selector type: ".concat(selector.type)); + } + + /** + * @callback TraverseOptionFallback + * @param {external:AST} node The given node. + * @returns {string[]} An array of visitor keys for the given node. + */ + + /** + * @callback ClassMatcher + * @param {string} className The name of the class to match. + * @param {external:AST} node The node to match against. + * @param {Array} ancestry The ancestry of the node. + * @returns {boolean} True if the node matches the class, false if not. + */ + + /** + * @typedef {object} ESQueryOptions + * @property {string} [nodeTypeKey="type"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery. + * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node. + * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes. + * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes. + */ + + /** + * Given a `node` and its ancestors, determine if `node` is matched + * by `selector`. + * @param {?external:AST} node + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @throws {Error} Unknowns (operator, class name, selector type, or + * selector value type) + * @returns {boolean} + */ + function matches(node, selector, ancestry, options) { + if (!selector) { + return true; + } + if (!node) { + return false; + } + if (!ancestry) { + ancestry = []; + } + return getMatcher(selector)(node, ancestry, options); + } + + /** + * Get visitor keys of a given node. + * @param {external:AST} node The AST node to get keys. + * @param {ESQueryOptions|undefined} options + * @returns {string[]} Visitor keys of the node. + */ + function getVisitorKeys(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + var nodeType = node[nodeTypeKey]; + if (options && options.visitorKeys && options.visitorKeys[nodeType]) { + return options.visitorKeys[nodeType]; + } + if (estraverse.VisitorKeys[nodeType]) { + return estraverse.VisitorKeys[nodeType]; + } + if (options && typeof options.fallback === 'function') { + return options.fallback(node); + } + // 'iteration' fallback + return Object.keys(node).filter(function (key) { + return key !== nodeTypeKey; + }); + } + + /** + * Check whether the given value is an ASTNode or not. + * @param {any} node The value to check. + * @param {ESQueryOptions|undefined} options The options to use. + * @returns {boolean} `true` if the value is an ASTNode. + */ + function isNode(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return node !== null && _typeof(node) === 'object' && typeof node[nodeTypeKey] === 'string'; + } + + /** + * Determines if the given node has a sibling that matches the + * given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function sibling(node, matcher, ancestry, side, options) { + var _ancestry = _slicedToArray(ancestry, 1), + parent = _ancestry[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var startIndex = listProp.indexOf(node); + if (startIndex < 0) { + continue; + } + var lowerBound = void 0, + upperBound = void 0; + if (side === LEFT_SIDE) { + lowerBound = 0; + upperBound = startIndex; + } else { + lowerBound = startIndex + 1; + upperBound = listProp.length; + } + for (var k = lowerBound; k < upperBound; ++k) { + if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) { + return true; + } + } + } + } + return false; + } + + /** + * Determines if the given node has an adjacent sibling that matches + * the given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function adjacent(node, matcher, ancestry, side, options) { + var _ancestry2 = _slicedToArray(ancestry, 1), + parent = _ancestry2[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = listProp.indexOf(node); + if (idx < 0) { + continue; + } + if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) { + return true; + } + if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) { + return true; + } + } + } + return false; + } + + /** + * Determines if the given node is the `nth` child. + * If `nth` is negative then the position is counted + * from the end of the list of children. + * @param {external:AST} node + * @param {external:AST[]} ancestry + * @param {Integer} nth + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function nthChild(node, ancestry, nth, options) { + if (nth === 0) { + return false; + } + var _ancestry3 = _slicedToArray(ancestry, 1), + parent = _ancestry3[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = nth < 0 ? listProp.length + nth : nth - 1; + if (idx >= 0 && idx < listProp.length && listProp[idx] === node) { + return true; + } + } + } + return false; + } + + /** + * For each selector node marked as a subject, find the portion of the + * selector that the subject must match. + * @param {SelectorAST} selector + * @param {SelectorAST} [ancestor] Defaults to `selector` + * @returns {SelectorAST[]} + */ + function subjects(selector, ancestor) { + if (selector == null || _typeof(selector) != 'object') { + return []; + } + if (ancestor == null) { + ancestor = selector; + } + var results = selector.subject ? [ancestor] : []; + var keys = Object.keys(selector); + for (var i = 0; i < keys.length; ++i) { + var p = keys[i]; + var sel = selector[p]; + results.push.apply(results, _toConsumableArray(subjects(sel, p === 'left' ? sel : ancestor))); + } + return results; + } + + /** + * @callback TraverseVisitor + * @param {?external:AST} node + * @param {?external:AST} parent + * @param {external:AST[]} ancestry + */ + + /** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {TraverseVisitor} visitor + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function traverse(ast, selector, visitor, options) { + if (!selector) { + return; + } + var ancestry = []; + var matcher = getMatcher(selector); + var altSubjects = subjects(selector).map(getMatcher); + estraverse.traverse(ast, { + enter: function enter(node, parent) { + if (parent != null) { + ancestry.unshift(parent); + } + if (matcher(node, ancestry, options)) { + if (altSubjects.length) { + for (var i = 0, l = altSubjects.length; i < l; ++i) { + if (altSubjects[i](node, ancestry, options)) { + visitor(node, parent, ancestry); + } + for (var k = 0, m = ancestry.length; k < m; ++k) { + var succeedingAncestry = ancestry.slice(k + 1); + if (altSubjects[i](ancestry[k], succeedingAncestry, options)) { + visitor(ancestry[k], parent, succeedingAncestry); + } + } + } + } else { + visitor(node, parent, ancestry); + } + } + }, + leave: function leave() { + ancestry.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + } + + /** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function match(ast, selector, options) { + var results = []; + traverse(ast, selector, function (node) { + results.push(node); + }, options); + return results; + } + + /** + * Parse a selector string and return its AST. + * @param {string} selector + * @returns {SelectorAST} + */ + function parse(selector) { + return parser.parse(selector); + } + + /** + * Query the code AST using the selector string. + * @param {external:AST} ast + * @param {string} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function query(ast, selector, options) { + return match(ast, parse(selector), options); + } + query.parse = parse; + query.match = match; + query.traverse = traverse; + query.matches = matches; + query.query = query; + + return query; + +}))); diff --git a/node_modules/esquery/dist/esquery.lite.min.js b/node_modules/esquery/dist/esquery.lite.min.js new file mode 100644 index 00000000..80dd64ee --- /dev/null +++ b/node_modules/esquery/dist/esquery.lite.min.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("estraverse")):"function"==typeof define&&define.amd?define(["estraverse"],e):(t=t||self).esquery=e(t.estraverse)}(this,(function(t){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function r(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,u,o,a,s=[],c=!0,i=!1;try{if(o=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==e);c=!0);}catch(t){i=!0,u=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(i)throw u}}return s}}(t,e)||u(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(t){return function(t){if(Array.isArray(t))return o(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||u(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(t,e){if(t){if("string"==typeof t)return o(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(t,e):void 0}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0){for(e=1,n=1;e<~+.]/,h=ht([" ","[","]",",","(",")",":","#","!","=",">","<","~","+","."],!0,!1),p=ft(">",!1),v=ft("~",!1),y=ft("+",!1),d=ft(",",!1),A=function(t,e){return[t].concat(e.map((function(t){return t[3]})))},x=ft("!",!1),g=ft("*",!1),m=ft("#",!1),P=ft("[",!1),b=ft("]",!1),C=/^[>","<","!"],!1,!1),j=ft("=",!1),E=function(t){return(t||"")+"="},S=/^[><]/,k=ht([">","<"],!1,!1),I=ft(".",!1),T=function(t,e,r){return{type:"attribute",name:t,operator:e,value:r}},F=ft('"',!1),K=/^[^\\"]/,O=ht(["\\",'"'],!0,!1),D=ft("\\",!1),L={type:"any"},R=function(t,e){return t+e},M=function(t){return{type:"literal",value:(e=t.join(""),e.replace(/\\(.)/g,(function(t,e){switch(e){case"b":return"\b";case"f":return"\f";case"n":return"\n";case"r":return"\r";case"t":return"\t";case"v":return"\v";default:return e}})))};var e},U=ft("'",!1),_=/^[^\\']/,q=ht(["\\","'"],!0,!1),G=/^[0-9]/,H=ht([["0","9"]],!1,!1),N=ft("type(",!1),V=/^[^ )]/,W=ht([" ",")"],!0,!1),$=ft(")",!1),z=/^[imsu]/,B=ht(["i","m","s","u"],!1,!1),J=ft("/",!1),Q=/^[^\/]/,X=ht(["/"],!0,!1),Y=ft(":not(",!1),Z=ft(":matches(",!1),tt=ft(":has(",!1),et=ft(":first-child",!1),rt=ft(":last-child",!1),nt=ft(":nth-child(",!1),ut=ft(":nth-last-child(",!1),ot=ft(":",!1),at=0,st=[{line:1,column:1}],ct=0,it=[],lt={};if("startRule"in r){if(!(r.startRule in c))throw new Error("Can't start parsing from rule \""+r.startRule+'".');i=c[r.startRule]}function ft(t,e){return{type:"literal",text:t,ignoreCase:e}}function ht(t,e,r){return{type:"class",parts:t,inverted:e,ignoreCase:r}}function pt(t){var r,n=st[t];if(n)return n;for(r=t-1;!st[r];)r--;for(n={line:(n=st[r]).line,column:n.column};rct&&(ct=at,it=[]),it.push(t))}function dt(){var t,e,r,n,u=32*at+0,o=lt[u];return o?(at=o.nextPos,o.result):(t=at,(e=At())!==s&&(r=mt())!==s&&At()!==s?t=e=1===(n=r).length?n[0]:{type:"matches",selectors:n}:(at=t,t=s),t===s&&(t=at,(e=At())!==s&&(e=void 0),t=e),lt[u]={nextPos:at,result:t},t)}function At(){var t,r,n=32*at+1,u=lt[n];if(u)return at=u.nextPos,u.result;for(t=[],32===e.charCodeAt(at)?(r=" ",at++):(r=s,yt(l));r!==s;)t.push(r),32===e.charCodeAt(at)?(r=" ",at++):(r=s,yt(l));return lt[n]={nextPos:at,result:t},t}function xt(){var t,r,n,u=32*at+2,o=lt[u];if(o)return at=o.nextPos,o.result;if(r=[],f.test(e.charAt(at))?(n=e.charAt(at),at++):(n=s,yt(h)),n!==s)for(;n!==s;)r.push(n),f.test(e.charAt(at))?(n=e.charAt(at),at++):(n=s,yt(h));else r=s;return r!==s&&(r=r.join("")),t=r,lt[u]={nextPos:at,result:t},t}function gt(){var t,r,n,u=32*at+3,o=lt[u];return o?(at=o.nextPos,o.result):(t=at,(r=At())!==s?(62===e.charCodeAt(at)?(n=">",at++):(n=s,yt(p)),n!==s&&At()!==s?t=r="child":(at=t,t=s)):(at=t,t=s),t===s&&(t=at,(r=At())!==s?(126===e.charCodeAt(at)?(n="~",at++):(n=s,yt(v)),n!==s&&At()!==s?t=r="sibling":(at=t,t=s)):(at=t,t=s),t===s&&(t=at,(r=At())!==s?(43===e.charCodeAt(at)?(n="+",at++):(n=s,yt(y)),n!==s&&At()!==s?t=r="adjacent":(at=t,t=s)):(at=t,t=s),t===s&&(t=at,32===e.charCodeAt(at)?(r=" ",at++):(r=s,yt(l)),r!==s&&(n=At())!==s?t=r="descendant":(at=t,t=s)))),lt[u]={nextPos:at,result:t},t)}function mt(){var t,r,n,u,o,a,c,i,l=32*at+5,f=lt[l];if(f)return at=f.nextPos,f.result;if(t=at,(r=bt())!==s){for(n=[],u=at,(o=At())!==s?(44===e.charCodeAt(at)?(a=",",at++):(a=s,yt(d)),a!==s&&(c=At())!==s&&(i=bt())!==s?u=o=[o,a,c,i]:(at=u,u=s)):(at=u,u=s);u!==s;)n.push(u),u=at,(o=At())!==s?(44===e.charCodeAt(at)?(a=",",at++):(a=s,yt(d)),a!==s&&(c=At())!==s&&(i=bt())!==s?u=o=[o,a,c,i]:(at=u,u=s)):(at=u,u=s);n!==s?t=r=A(r,n):(at=t,t=s)}else at=t,t=s;return lt[l]={nextPos:at,result:t},t}function Pt(){var t,e,r,n,u,o=32*at+6,a=lt[o];return a?(at=a.nextPos,a.result):(t=at,(e=gt())===s&&(e=null),e!==s&&(r=bt())!==s?(u=r,t=e=(n=e)?{type:n,left:{type:"exactNode"},right:u}:u):(at=t,t=s),lt[o]={nextPos:at,result:t},t)}function bt(){var t,e,r,n,u,o,a,c=32*at+7,i=lt[c];if(i)return at=i.nextPos,i.result;if(t=at,(e=Ct())!==s){for(r=[],n=at,(u=gt())!==s&&(o=Ct())!==s?n=u=[u,o]:(at=n,n=s);n!==s;)r.push(n),n=at,(u=gt())!==s&&(o=Ct())!==s?n=u=[u,o]:(at=n,n=s);r!==s?(a=e,t=e=r.reduce((function(t,e){return{type:e[0],left:t,right:e[1]}}),a)):(at=t,t=s)}else at=t,t=s;return lt[c]={nextPos:at,result:t},t}function Ct(){var t,r,n,u,o,a,c,i=32*at+8,l=lt[i];if(l)return at=l.nextPos,l.result;if(t=at,33===e.charCodeAt(at)?(r="!",at++):(r=s,yt(x)),r===s&&(r=null),r!==s){if(n=[],(u=wt())!==s)for(;u!==s;)n.push(u),u=wt();else n=s;n!==s?(o=r,c=1===(a=n).length?a[0]:{type:"compound",selectors:a},o&&(c.subject=!0),t=r=c):(at=t,t=s)}else at=t,t=s;return lt[i]={nextPos:at,result:t},t}function wt(){var t,r=32*at+9,n=lt[r];return n?(at=n.nextPos,n.result):((t=function(){var t,r,n=32*at+10,u=lt[n];return u?(at=u.nextPos,u.result):(42===e.charCodeAt(at)?(r="*",at++):(r=s,yt(g)),r!==s&&(r={type:"wildcard",value:r}),t=r,lt[n]={nextPos:at,result:t},t)}())===s&&(t=function(){var t,r,n,u=32*at+11,o=lt[u];return o?(at=o.nextPos,o.result):(t=at,35===e.charCodeAt(at)?(r="#",at++):(r=s,yt(m)),r===s&&(r=null),r!==s&&(n=xt())!==s?t=r={type:"identifier",value:n}:(at=t,t=s),lt[u]={nextPos:at,result:t},t)}())===s&&(t=function(){var t,r,n,u,o=32*at+12,a=lt[o];return a?(at=a.nextPos,a.result):(t=at,91===e.charCodeAt(at)?(r="[",at++):(r=s,yt(P)),r!==s&&At()!==s&&(n=function(){var t,r,n,u,o=32*at+16,a=lt[o];return a?(at=a.nextPos,a.result):(t=at,(r=jt())!==s&&At()!==s&&(n=function(){var t,r,n,u=32*at+14,o=lt[u];return o?(at=o.nextPos,o.result):(t=at,33===e.charCodeAt(at)?(r="!",at++):(r=s,yt(x)),r===s&&(r=null),r!==s?(61===e.charCodeAt(at)?(n="=",at++):(n=s,yt(j)),n!==s?(r=E(r),t=r):(at=t,t=s)):(at=t,t=s),lt[u]={nextPos:at,result:t},t)}())!==s&&At()!==s?((u=function(){var t,r,n,u,o,a=32*at+20,c=lt[a];if(c)return at=c.nextPos,c.result;if(t=at,"type("===e.substr(at,5)?(r="type(",at+=5):(r=s,yt(N)),r!==s)if(At()!==s){if(n=[],V.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(W)),u!==s)for(;u!==s;)n.push(u),V.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(W));else n=s;n!==s&&(u=At())!==s?(41===e.charCodeAt(at)?(o=")",at++):(o=s,yt($)),o!==s?(r={type:"type",value:n.join("")},t=r):(at=t,t=s)):(at=t,t=s)}else at=t,t=s;else at=t,t=s;return lt[a]={nextPos:at,result:t},t}())===s&&(u=function(){var t,r,n,u,o,a,c=32*at+22,i=lt[c];if(i)return at=i.nextPos,i.result;if(t=at,47===e.charCodeAt(at)?(r="/",at++):(r=s,yt(J)),r!==s){if(n=[],Q.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(X)),u!==s)for(;u!==s;)n.push(u),Q.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(X));else n=s;n!==s?(47===e.charCodeAt(at)?(u="/",at++):(u=s,yt(J)),u!==s?((o=function(){var t,r,n=32*at+21,u=lt[n];if(u)return at=u.nextPos,u.result;if(t=[],z.test(e.charAt(at))?(r=e.charAt(at),at++):(r=s,yt(B)),r!==s)for(;r!==s;)t.push(r),z.test(e.charAt(at))?(r=e.charAt(at),at++):(r=s,yt(B));else t=s;return lt[n]={nextPos:at,result:t},t}())===s&&(o=null),o!==s?(a=o,r={type:"regexp",value:new RegExp(n.join(""),a?a.join(""):"")},t=r):(at=t,t=s)):(at=t,t=s)):(at=t,t=s)}else at=t,t=s;return lt[c]={nextPos:at,result:t},t}()),u!==s?(r=T(r,n,u),t=r):(at=t,t=s)):(at=t,t=s),t===s&&(t=at,(r=jt())!==s&&At()!==s&&(n=function(){var t,r,n,u=32*at+13,o=lt[u];return o?(at=o.nextPos,o.result):(t=at,C.test(e.charAt(at))?(r=e.charAt(at),at++):(r=s,yt(w)),r===s&&(r=null),r!==s?(61===e.charCodeAt(at)?(n="=",at++):(n=s,yt(j)),n!==s?(r=E(r),t=r):(at=t,t=s)):(at=t,t=s),t===s&&(S.test(e.charAt(at))?(t=e.charAt(at),at++):(t=s,yt(k))),lt[u]={nextPos:at,result:t},t)}())!==s&&At()!==s?((u=function(){var t,r,n,u,o,a,c=32*at+17,i=lt[c];if(i)return at=i.nextPos,i.result;if(t=at,34===e.charCodeAt(at)?(r='"',at++):(r=s,yt(F)),r!==s){for(n=[],K.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(O)),u===s&&(u=at,92===e.charCodeAt(at)?(o="\\",at++):(o=s,yt(D)),o!==s?(e.length>at?(a=e.charAt(at),at++):(a=s,yt(L)),a!==s?(o=R(o,a),u=o):(at=u,u=s)):(at=u,u=s));u!==s;)n.push(u),K.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(O)),u===s&&(u=at,92===e.charCodeAt(at)?(o="\\",at++):(o=s,yt(D)),o!==s?(e.length>at?(a=e.charAt(at),at++):(a=s,yt(L)),a!==s?(o=R(o,a),u=o):(at=u,u=s)):(at=u,u=s));n!==s?(34===e.charCodeAt(at)?(u='"',at++):(u=s,yt(F)),u!==s?(r=M(n),t=r):(at=t,t=s)):(at=t,t=s)}else at=t,t=s;if(t===s)if(t=at,39===e.charCodeAt(at)?(r="'",at++):(r=s,yt(U)),r!==s){for(n=[],_.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(q)),u===s&&(u=at,92===e.charCodeAt(at)?(o="\\",at++):(o=s,yt(D)),o!==s?(e.length>at?(a=e.charAt(at),at++):(a=s,yt(L)),a!==s?(o=R(o,a),u=o):(at=u,u=s)):(at=u,u=s));u!==s;)n.push(u),_.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(q)),u===s&&(u=at,92===e.charCodeAt(at)?(o="\\",at++):(o=s,yt(D)),o!==s?(e.length>at?(a=e.charAt(at),at++):(a=s,yt(L)),a!==s?(o=R(o,a),u=o):(at=u,u=s)):(at=u,u=s));n!==s?(39===e.charCodeAt(at)?(u="'",at++):(u=s,yt(U)),u!==s?(r=M(n),t=r):(at=t,t=s)):(at=t,t=s)}else at=t,t=s;return lt[c]={nextPos:at,result:t},t}())===s&&(u=function(){var t,r,n,u,o,a,c,i=32*at+18,l=lt[i];if(l)return at=l.nextPos,l.result;for(t=at,r=at,n=[],G.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(H));u!==s;)n.push(u),G.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(H));if(n!==s?(46===e.charCodeAt(at)?(u=".",at++):(u=s,yt(I)),u!==s?r=n=[n,u]:(at=r,r=s)):(at=r,r=s),r===s&&(r=null),r!==s){if(n=[],G.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(H)),u!==s)for(;u!==s;)n.push(u),G.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(H));else n=s;n!==s?(a=n,c=(o=r)?[].concat.apply([],o).join(""):"",r={type:"literal",value:parseFloat(c+a.join(""))},t=r):(at=t,t=s)}else at=t,t=s;return lt[i]={nextPos:at,result:t},t}())===s&&(u=function(){var t,e,r=32*at+19,n=lt[r];return n?(at=n.nextPos,n.result):((e=xt())!==s&&(e={type:"literal",value:e}),t=e,lt[r]={nextPos:at,result:t},t)}()),u!==s?(r=T(r,n,u),t=r):(at=t,t=s)):(at=t,t=s),t===s&&(t=at,(r=jt())!==s&&(r={type:"attribute",name:r}),t=r)),lt[o]={nextPos:at,result:t},t)}())!==s&&At()!==s?(93===e.charCodeAt(at)?(u="]",at++):(u=s,yt(b)),u!==s?t=r=n:(at=t,t=s)):(at=t,t=s),lt[o]={nextPos:at,result:t},t)}())===s&&(t=function(){var t,r,n,u,o,a,c,i,l=32*at+23,f=lt[l];if(f)return at=f.nextPos,f.result;if(t=at,46===e.charCodeAt(at)?(r=".",at++):(r=s,yt(I)),r!==s)if((n=xt())!==s){for(u=[],o=at,46===e.charCodeAt(at)?(a=".",at++):(a=s,yt(I)),a!==s&&(c=xt())!==s?o=a=[a,c]:(at=o,o=s);o!==s;)u.push(o),o=at,46===e.charCodeAt(at)?(a=".",at++):(a=s,yt(I)),a!==s&&(c=xt())!==s?o=a=[a,c]:(at=o,o=s);u!==s?(i=n,r={type:"field",name:u.reduce((function(t,e){return t+e[0]+e[1]}),i)},t=r):(at=t,t=s)}else at=t,t=s;else at=t,t=s;return lt[l]={nextPos:at,result:t},t}())===s&&(t=function(){var t,r,n,u,o=32*at+24,a=lt[o];return a?(at=a.nextPos,a.result):(t=at,":not("===e.substr(at,5)?(r=":not(",at+=5):(r=s,yt(Y)),r!==s&&At()!==s&&(n=mt())!==s&&At()!==s?(41===e.charCodeAt(at)?(u=")",at++):(u=s,yt($)),u!==s?t=r={type:"not",selectors:n}:(at=t,t=s)):(at=t,t=s),lt[o]={nextPos:at,result:t},t)}())===s&&(t=function(){var t,r,n,u,o=32*at+25,a=lt[o];return a?(at=a.nextPos,a.result):(t=at,":matches("===e.substr(at,9)?(r=":matches(",at+=9):(r=s,yt(Z)),r!==s&&At()!==s&&(n=mt())!==s&&At()!==s?(41===e.charCodeAt(at)?(u=")",at++):(u=s,yt($)),u!==s?t=r={type:"matches",selectors:n}:(at=t,t=s)):(at=t,t=s),lt[o]={nextPos:at,result:t},t)}())===s&&(t=function(){var t,r,n,u,o=32*at+26,a=lt[o];return a?(at=a.nextPos,a.result):(t=at,":has("===e.substr(at,5)?(r=":has(",at+=5):(r=s,yt(tt)),r!==s&&At()!==s&&(n=function(){var t,r,n,u,o,a,c,i,l=32*at+4,f=lt[l];if(f)return at=f.nextPos,f.result;if(t=at,(r=Pt())!==s){for(n=[],u=at,(o=At())!==s?(44===e.charCodeAt(at)?(a=",",at++):(a=s,yt(d)),a!==s&&(c=At())!==s&&(i=Pt())!==s?u=o=[o,a,c,i]:(at=u,u=s)):(at=u,u=s);u!==s;)n.push(u),u=at,(o=At())!==s?(44===e.charCodeAt(at)?(a=",",at++):(a=s,yt(d)),a!==s&&(c=At())!==s&&(i=Pt())!==s?u=o=[o,a,c,i]:(at=u,u=s)):(at=u,u=s);n!==s?t=r=A(r,n):(at=t,t=s)}else at=t,t=s;return lt[l]={nextPos:at,result:t},t}())!==s&&At()!==s?(41===e.charCodeAt(at)?(u=")",at++):(u=s,yt($)),u!==s?t=r={type:"has",selectors:n}:(at=t,t=s)):(at=t,t=s),lt[o]={nextPos:at,result:t},t)}())===s&&(t=function(){var t,r,n=32*at+27,u=lt[n];return u?(at=u.nextPos,u.result):(":first-child"===e.substr(at,12)?(r=":first-child",at+=12):(r=s,yt(et)),r!==s&&(r=Et(1)),t=r,lt[n]={nextPos:at,result:t},t)}())===s&&(t=function(){var t,r,n=32*at+28,u=lt[n];return u?(at=u.nextPos,u.result):(":last-child"===e.substr(at,11)?(r=":last-child",at+=11):(r=s,yt(rt)),r!==s&&(r=St(1)),t=r,lt[n]={nextPos:at,result:t},t)}())===s&&(t=function(){var t,r,n,u,o,a=32*at+29,c=lt[a];if(c)return at=c.nextPos,c.result;if(t=at,":nth-child("===e.substr(at,11)?(r=":nth-child(",at+=11):(r=s,yt(nt)),r!==s)if(At()!==s){if(n=[],G.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(H)),u!==s)for(;u!==s;)n.push(u),G.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(H));else n=s;n!==s&&(u=At())!==s?(41===e.charCodeAt(at)?(o=")",at++):(o=s,yt($)),o!==s?(r=Et(parseInt(n.join(""),10)),t=r):(at=t,t=s)):(at=t,t=s)}else at=t,t=s;else at=t,t=s;return lt[a]={nextPos:at,result:t},t}())===s&&(t=function(){var t,r,n,u,o,a=32*at+30,c=lt[a];if(c)return at=c.nextPos,c.result;if(t=at,":nth-last-child("===e.substr(at,16)?(r=":nth-last-child(",at+=16):(r=s,yt(ut)),r!==s)if(At()!==s){if(n=[],G.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(H)),u!==s)for(;u!==s;)n.push(u),G.test(e.charAt(at))?(u=e.charAt(at),at++):(u=s,yt(H));else n=s;n!==s&&(u=At())!==s?(41===e.charCodeAt(at)?(o=")",at++):(o=s,yt($)),o!==s?(r=St(parseInt(n.join(""),10)),t=r):(at=t,t=s)):(at=t,t=s)}else at=t,t=s;else at=t,t=s;return lt[a]={nextPos:at,result:t},t}())===s&&(t=function(){var t,r,n,u=32*at+31,o=lt[u];return o?(at=o.nextPos,o.result):(t=at,58===e.charCodeAt(at)?(r=":",at++):(r=s,yt(ot)),r!==s&&(n=xt())!==s?t=r={type:"class",name:n}:(at=t,t=s),lt[u]={nextPos:at,result:t},t)}()),lt[r]={nextPos:at,result:t},t)}function jt(){var t,r,n,u,o,a,c,i,l=32*at+15,f=lt[l];if(f)return at=f.nextPos,f.result;if(t=at,(r=xt())!==s){for(n=[],u=at,46===e.charCodeAt(at)?(o=".",at++):(o=s,yt(I)),o!==s&&(a=xt())!==s?u=o=[o,a]:(at=u,u=s);u!==s;)n.push(u),u=at,46===e.charCodeAt(at)?(o=".",at++):(o=s,yt(I)),o!==s&&(a=xt())!==s?u=o=[o,a]:(at=u,u=s);n!==s?(c=r,i=n,t=r=[].concat.apply([c],i).join("")):(at=t,t=s)}else at=t,t=s;return lt[l]={nextPos:at,result:t},t}function Et(t){return{type:"nth-child",index:{type:"literal",value:t}}}function St(t){return{type:"nth-last-child",index:{type:"literal",value:t}}}if((n=i())!==s&&at===e.length)return n;throw n!==s&&at0&&h(t,e,r))&&f(e[0],e.slice(1),r)};case"descendant":var d=i(r.left),A=i(r.right);return function(t,e,r){if(A(t,e,r))for(var n=0,u=e.length;n":return function(t){return s(t,x)>r.value.value};case">=":return function(t){return s(t,x)>=r.value.value}}throw new Error("Unknown operator: ".concat(r.operator));case"sibling":var P=i(r.left),b=i(r.right);return function(t,e,n){return b(t,e,n)&&p(t,P,e,"LEFT_SIDE",n)||r.left.subject&&P(t,e,n)&&p(t,b,e,"RIGHT_SIDE",n)};case"adjacent":var C=i(r.left),w=i(r.right);return function(t,e,n){return w(t,e,n)&&v(t,C,e,"LEFT_SIDE",n)||r.right.subject&&C(t,e,n)&&v(t,w,e,"RIGHT_SIDE",n)};case"nth-child":var j=r.index.value,E=i(r.right);return function(t,e,r){return E(t,e,r)&&y(t,e,j,r)};case"nth-last-child":var S=-r.index.value,k=i(r.right);return function(t,e,r){return k(t,e,r)&&y(t,e,S,r)};case"class":var I=r.name.toLowerCase();return function(t,e,n){if(n&&n.matchClass)return n.matchClass(r.name,t,e);if(n&&n.nodeTypeKey)return!1;switch(I){case"statement":if("Statement"===t.type.slice(-9))return!0;case"declaration":return"Declaration"===t.type.slice(-11);case"pattern":if("Pattern"===t.type.slice(-7))return!0;case"expression":return"Expression"===t.type.slice(-10)||"Literal"===t.type.slice(-7)||"Identifier"===t.type&&(0===e.length||"MetaProperty"!==e[0].type)||"MetaProperty"===t.type;case"function":return"FunctionDeclaration"===t.type||"FunctionExpression"===t.type||"ArrowFunctionExpression"===t.type}throw new Error("Unknown class name: ".concat(r.name))}}throw new Error("Unknown selector type: ".concat(r.type))}function f(e,r){var n=r&&r.nodeTypeKey||"type",u=e[n];return r&&r.visitorKeys&&r.visitorKeys[u]?r.visitorKeys[u]:t.VisitorKeys[u]?t.VisitorKeys[u]:r&&"function"==typeof r.fallback?r.fallback(e):Object.keys(e).filter((function(t){return t!==n}))}function h(t,r){var n=r&&r.nodeTypeKey||"type";return null!==t&&"object"===e(t)&&"string"==typeof t[n]}function p(t,e,n,u,o){var a=r(n,1)[0];if(!a)return!1;for(var s=f(a,o),c=0;c0&&h(i[l-1],o)&&e(i[l-1],n,o))return!0;if("RIGHT_SIDE"===u&&l=0&&i 0) {\n for (i = 1, j = 1; i < descriptions.length; i++) {\n if (descriptions[i - 1] !== descriptions[i]) {\n descriptions[j] = descriptions[i];\n j++;\n }\n }\n descriptions.length = j;\n }\n\n switch (descriptions.length) {\n case 1:\n return descriptions[0];\n\n case 2:\n return descriptions[0] + \" or \" + descriptions[1];\n\n default:\n return descriptions.slice(0, -1).join(\", \")\n + \", or \"\n + descriptions[descriptions.length - 1];\n }\n }\n\n function describeFound(found) {\n return found ? \"\\\"\" + literalEscape(found) + \"\\\"\" : \"end of input\";\n }\n\n return \"Expected \" + describeExpected(expected) + \" but \" + describeFound(found) + \" found.\";\n };\n\n function peg$parse(input, options) {\n options = options !== void 0 ? options : {};\n\n var peg$FAILED = {},\n\n peg$startRuleFunctions = { start: peg$parsestart },\n peg$startRuleFunction = peg$parsestart,\n\n peg$c0 = function(ss) {\n return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss };\n },\n peg$c1 = function() { return void 0; },\n peg$c2 = \" \",\n peg$c3 = peg$literalExpectation(\" \", false),\n peg$c4 = /^[^ [\\],():#!=><~+.]/,\n peg$c5 = peg$classExpectation([\" \", \"[\", \"]\", \",\", \"(\", \")\", \":\", \"#\", \"!\", \"=\", \">\", \"<\", \"~\", \"+\", \".\"], true, false),\n peg$c6 = function(i) { return i.join(''); },\n peg$c7 = \">\",\n peg$c8 = peg$literalExpectation(\">\", false),\n peg$c9 = function() { return 'child'; },\n peg$c10 = \"~\",\n peg$c11 = peg$literalExpectation(\"~\", false),\n peg$c12 = function() { return 'sibling'; },\n peg$c13 = \"+\",\n peg$c14 = peg$literalExpectation(\"+\", false),\n peg$c15 = function() { return 'adjacent'; },\n peg$c16 = function() { return 'descendant'; },\n peg$c17 = \",\",\n peg$c18 = peg$literalExpectation(\",\", false),\n peg$c19 = function(s, ss) {\n return [s].concat(ss.map(function (s) { return s[3]; }));\n },\n peg$c20 = function(op, s) {\n if (!op) return s;\n return { type: op, left: { type: 'exactNode' }, right: s };\n },\n peg$c21 = function(a, ops) {\n return ops.reduce(function (memo, rhs) {\n return { type: rhs[0], left: memo, right: rhs[1] };\n }, a);\n },\n peg$c22 = \"!\",\n peg$c23 = peg$literalExpectation(\"!\", false),\n peg$c24 = function(subject, as) {\n const b = as.length === 1 ? as[0] : { type: 'compound', selectors: as };\n if(subject) b.subject = true;\n return b;\n },\n peg$c25 = \"*\",\n peg$c26 = peg$literalExpectation(\"*\", false),\n peg$c27 = function(a) { return { type: 'wildcard', value: a }; },\n peg$c28 = \"#\",\n peg$c29 = peg$literalExpectation(\"#\", false),\n peg$c30 = function(i) { return { type: 'identifier', value: i }; },\n peg$c31 = \"[\",\n peg$c32 = peg$literalExpectation(\"[\", false),\n peg$c33 = \"]\",\n peg$c34 = peg$literalExpectation(\"]\", false),\n peg$c35 = function(v) { return v; },\n peg$c36 = /^[>\", \"<\", \"!\"], false, false),\n peg$c38 = \"=\",\n peg$c39 = peg$literalExpectation(\"=\", false),\n peg$c40 = function(a) { return (a || '') + '='; },\n peg$c41 = /^[><]/,\n peg$c42 = peg$classExpectation([\">\", \"<\"], false, false),\n peg$c43 = \".\",\n peg$c44 = peg$literalExpectation(\".\", false),\n peg$c45 = function(a, as) {\n return [].concat.apply([a], as).join('');\n },\n peg$c46 = function(name, op, value) {\n return { type: 'attribute', name: name, operator: op, value: value };\n },\n peg$c47 = function(name) { return { type: 'attribute', name: name }; },\n peg$c48 = \"\\\"\",\n peg$c49 = peg$literalExpectation(\"\\\"\", false),\n peg$c50 = /^[^\\\\\"]/,\n peg$c51 = peg$classExpectation([\"\\\\\", \"\\\"\"], true, false),\n peg$c52 = \"\\\\\",\n peg$c53 = peg$literalExpectation(\"\\\\\", false),\n peg$c54 = peg$anyExpectation(),\n peg$c55 = function(a, b) { return a + b; },\n peg$c56 = function(d) {\n return { type: 'literal', value: strUnescape(d.join('')) };\n },\n peg$c57 = \"'\",\n peg$c58 = peg$literalExpectation(\"'\", false),\n peg$c59 = /^[^\\\\']/,\n peg$c60 = peg$classExpectation([\"\\\\\", \"'\"], true, false),\n peg$c61 = /^[0-9]/,\n peg$c62 = peg$classExpectation([[\"0\", \"9\"]], false, false),\n peg$c63 = function(a, b) {\n // Can use `a.flat().join('')` once supported\n const leadingDecimals = a ? [].concat.apply([], a).join('') : '';\n return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) };\n },\n peg$c64 = function(i) { return { type: 'literal', value: i }; },\n peg$c65 = \"type(\",\n peg$c66 = peg$literalExpectation(\"type(\", false),\n peg$c67 = /^[^ )]/,\n peg$c68 = peg$classExpectation([\" \", \")\"], true, false),\n peg$c69 = \")\",\n peg$c70 = peg$literalExpectation(\")\", false),\n peg$c71 = function(t) { return { type: 'type', value: t.join('') }; },\n peg$c72 = /^[imsu]/,\n peg$c73 = peg$classExpectation([\"i\", \"m\", \"s\", \"u\"], false, false),\n peg$c74 = \"/\",\n peg$c75 = peg$literalExpectation(\"/\", false),\n peg$c76 = /^[^\\/]/,\n peg$c77 = peg$classExpectation([\"/\"], true, false),\n peg$c78 = function(d, flgs) { return {\n type: 'regexp', value: new RegExp(d.join(''), flgs ? flgs.join('') : '') };\n },\n peg$c79 = function(i, is) {\n return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)};\n },\n peg$c80 = \":not(\",\n peg$c81 = peg$literalExpectation(\":not(\", false),\n peg$c82 = function(ss) { return { type: 'not', selectors: ss }; },\n peg$c83 = \":matches(\",\n peg$c84 = peg$literalExpectation(\":matches(\", false),\n peg$c85 = function(ss) { return { type: 'matches', selectors: ss }; },\n peg$c86 = \":has(\",\n peg$c87 = peg$literalExpectation(\":has(\", false),\n peg$c88 = function(ss) { return { type: 'has', selectors: ss }; },\n peg$c89 = \":first-child\",\n peg$c90 = peg$literalExpectation(\":first-child\", false),\n peg$c91 = function() { return nth(1); },\n peg$c92 = \":last-child\",\n peg$c93 = peg$literalExpectation(\":last-child\", false),\n peg$c94 = function() { return nthLast(1); },\n peg$c95 = \":nth-child(\",\n peg$c96 = peg$literalExpectation(\":nth-child(\", false),\n peg$c97 = function(n) { return nth(parseInt(n.join(''), 10)); },\n peg$c98 = \":nth-last-child(\",\n peg$c99 = peg$literalExpectation(\":nth-last-child(\", false),\n peg$c100 = function(n) { return nthLast(parseInt(n.join(''), 10)); },\n peg$c101 = \":\",\n peg$c102 = peg$literalExpectation(\":\", false),\n peg$c103 = function(c) {\n return { type: 'class', name: c };\n },\n\n peg$currPos = 0,\n peg$savedPos = 0,\n peg$posDetailsCache = [{ line: 1, column: 1 }],\n peg$maxFailPos = 0,\n peg$maxFailExpected = [],\n peg$silentFails = 0,\n\n peg$resultsCache = {},\n\n peg$result;\n\n if (\"startRule\" in options) {\n if (!(options.startRule in peg$startRuleFunctions)) {\n throw new Error(\"Can't start parsing from rule \\\"\" + options.startRule + \"\\\".\");\n }\n\n peg$startRuleFunction = peg$startRuleFunctions[options.startRule];\n }\n\n function text() {\n return input.substring(peg$savedPos, peg$currPos);\n }\n\n function location() {\n return peg$computeLocation(peg$savedPos, peg$currPos);\n }\n\n function expected(description, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildStructuredError(\n [peg$otherExpectation(description)],\n input.substring(peg$savedPos, peg$currPos),\n location\n );\n }\n\n function error(message, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildSimpleError(message, location);\n }\n\n function peg$literalExpectation(text, ignoreCase) {\n return { type: \"literal\", text: text, ignoreCase: ignoreCase };\n }\n\n function peg$classExpectation(parts, inverted, ignoreCase) {\n return { type: \"class\", parts: parts, inverted: inverted, ignoreCase: ignoreCase };\n }\n\n function peg$anyExpectation() {\n return { type: \"any\" };\n }\n\n function peg$endExpectation() {\n return { type: \"end\" };\n }\n\n function peg$otherExpectation(description) {\n return { type: \"other\", description: description };\n }\n\n function peg$computePosDetails(pos) {\n var details = peg$posDetailsCache[pos], p;\n\n if (details) {\n return details;\n } else {\n p = pos - 1;\n while (!peg$posDetailsCache[p]) {\n p--;\n }\n\n details = peg$posDetailsCache[p];\n details = {\n line: details.line,\n column: details.column\n };\n\n while (p < pos) {\n if (input.charCodeAt(p) === 10) {\n details.line++;\n details.column = 1;\n } else {\n details.column++;\n }\n\n p++;\n }\n\n peg$posDetailsCache[pos] = details;\n return details;\n }\n }\n\n function peg$computeLocation(startPos, endPos) {\n var startPosDetails = peg$computePosDetails(startPos),\n endPosDetails = peg$computePosDetails(endPos);\n\n return {\n start: {\n offset: startPos,\n line: startPosDetails.line,\n column: startPosDetails.column\n },\n end: {\n offset: endPos,\n line: endPosDetails.line,\n column: endPosDetails.column\n }\n };\n }\n\n function peg$fail(expected) {\n if (peg$currPos < peg$maxFailPos) { return; }\n\n if (peg$currPos > peg$maxFailPos) {\n peg$maxFailPos = peg$currPos;\n peg$maxFailExpected = [];\n }\n\n peg$maxFailExpected.push(expected);\n }\n\n function peg$buildSimpleError(message, location) {\n return new peg$SyntaxError(message, null, null, location);\n }\n\n function peg$buildStructuredError(expected, found, location) {\n return new peg$SyntaxError(\n peg$SyntaxError.buildMessage(expected, found),\n expected,\n found,\n location\n );\n }\n\n function peg$parsestart() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 0,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselectors();\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c0(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c1();\n }\n s0 = s1;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parse_() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 1,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifierName() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 2,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = [];\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n if (s2 !== peg$FAILED) {\n while (s2 !== peg$FAILED) {\n s1.push(s2);\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n }\n } else {\n s1 = peg$FAILED;\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c6(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsebinaryOp() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 3,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 62) {\n s2 = peg$c7;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c8); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c9();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 126) {\n s2 = peg$c10;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c11); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c12();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 43) {\n s2 = peg$c13;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c14); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c15();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c16();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 32 + 4,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsehasSelector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 32 + 5,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseselector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelector() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 6,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsebinaryOp();\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselector();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c20(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselector() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 7,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsesequence();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c21(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsesequence() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 8,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$parseatom();\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$parseatom();\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c24(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseatom() {\n var s0;\n\n var key = peg$currPos * 32 + 9,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$parsewildcard();\n if (s0 === peg$FAILED) {\n s0 = peg$parseidentifier();\n if (s0 === peg$FAILED) {\n s0 = peg$parseattr();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefield();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenegation();\n if (s0 === peg$FAILED) {\n s0 = peg$parsematches();\n if (s0 === peg$FAILED) {\n s0 = peg$parsehas();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefirstChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parselastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthLastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parseclass();\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsewildcard() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 10,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 42) {\n s1 = peg$c25;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c26); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c27(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifier() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 11,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 35) {\n s1 = peg$c28;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c29); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c30(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattr() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 12,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 91) {\n s1 = peg$c31;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c32); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrValue();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 93) {\n s5 = peg$c33;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c34); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c35(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 13,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (peg$c36.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c37); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n if (peg$c41.test(input.charAt(peg$currPos))) {\n s0 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s0 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c42); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrEqOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 14,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrName() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 15,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c45(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrValue() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 16,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrEqOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsetype();\n if (s5 === peg$FAILED) {\n s5 = peg$parseregex();\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsestring();\n if (s5 === peg$FAILED) {\n s5 = peg$parsenumber();\n if (s5 === peg$FAILED) {\n s5 = peg$parsepath();\n }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c47(s1);\n }\n s0 = s1;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsestring() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 17,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 34) {\n s1 = peg$c48;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 34) {\n s3 = peg$c48;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 39) {\n s1 = peg$c57;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 39) {\n s3 = peg$c57;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenumber() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 18,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$currPos;\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 46) {\n s3 = peg$c43;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s3 !== peg$FAILED) {\n s2 = [s2, s3];\n s1 = s2;\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c63(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsepath() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 19,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c64(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsetype() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 20,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c65) {\n s1 = peg$c65;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c66); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c71(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseflags() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 21,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n if (s1 !== peg$FAILED) {\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n }\n } else {\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseregex() {\n var s0, s1, s2, s3, s4;\n\n var key = peg$currPos * 32 + 22,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 47) {\n s1 = peg$c74;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c76.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c77); }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c76.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c77); }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 47) {\n s3 = peg$c74;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parseflags();\n if (s4 === peg$FAILED) {\n s4 = null;\n }\n if (s4 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c78(s2, s4);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefield() {\n var s0, s1, s2, s3, s4, s5, s6;\n\n var key = peg$currPos * 32 + 23,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s1 = peg$c43;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n s3 = [];\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c79(s2, s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenegation() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 24,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c80) {\n s1 = peg$c80;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c81); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c82(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsematches() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 25,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 9) === peg$c83) {\n s1 = peg$c83;\n peg$currPos += 9;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c84); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c85(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehas() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 26,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c86) {\n s1 = peg$c86;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c87); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parsehasSelectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c88(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefirstChild() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 27,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 12) === peg$c89) {\n s1 = peg$c89;\n peg$currPos += 12;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c90); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c91();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parselastChild() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 28,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c92) {\n s1 = peg$c92;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c93); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c94();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 29,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c95) {\n s1 = peg$c95;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c96); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c97(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthLastChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 30,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 16) === peg$c98) {\n s1 = peg$c98;\n peg$currPos += 16;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c99); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c100(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseclass() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 31,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 58) {\n s1 = peg$c101;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c102); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c103(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n\n function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; }\n function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; }\n function strUnescape(s) {\n return s.replace(/\\\\(.)/g, function(match, ch) {\n switch(ch) {\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n case 'v': return '\\v';\n default: return ch;\n }\n });\n }\n\n\n peg$result = peg$startRuleFunction();\n\n if (peg$result !== peg$FAILED && peg$currPos === input.length) {\n return peg$result;\n } else {\n if (peg$result !== peg$FAILED && peg$currPos < input.length) {\n peg$fail(peg$endExpectation());\n }\n\n throw peg$buildStructuredError(\n peg$maxFailExpected,\n peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,\n peg$maxFailPos < input.length\n ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)\n : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)\n );\n }\n }\n\n return {\n SyntaxError: peg$SyntaxError,\n parse: peg$parse\n };\n});\n","/* vim: set sw=4 sts=4 : */\nimport estraverse from 'estraverse';\nimport parser from './parser.js';\n\n/**\n* @typedef {\"LEFT_SIDE\"|\"RIGHT_SIDE\"} Side\n*/\n\nconst LEFT_SIDE = 'LEFT_SIDE';\nconst RIGHT_SIDE = 'RIGHT_SIDE';\n\n/**\n * @external AST\n * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html\n */\n\n/**\n * One of the rules of `grammar.pegjs`\n * @typedef {PlainObject} SelectorAST\n * @see grammar.pegjs\n*/\n\n/**\n * The `sequence` production of `grammar.pegjs`\n * @typedef {PlainObject} SelectorSequenceAST\n*/\n\n/**\n * Get the value of a property which may be multiple levels down\n * in the object.\n * @param {?PlainObject} obj\n * @param {string[]} keys\n * @returns {undefined|boolean|string|number|external:AST}\n */\nfunction getPath(obj, keys) {\n for (let i = 0; i < keys.length; ++i) {\n if (obj == null) { return obj; }\n obj = obj[keys[i]];\n }\n return obj;\n}\n\n/**\n * Determine whether `node` can be reached by following `path`,\n * starting at `ancestor`.\n * @param {?external:AST} node\n * @param {?external:AST} ancestor\n * @param {string[]} path\n * @param {Integer} fromPathIndex\n * @returns {boolean}\n */\nfunction inPath(node, ancestor, path, fromPathIndex) {\n let current = ancestor;\n for (let i = fromPathIndex; i < path.length; ++i) {\n if (current == null) {\n return false;\n }\n const field = current[path[i]];\n if (Array.isArray(field)) {\n for (let k = 0; k < field.length; ++k) {\n if (inPath(node, field[k], path, i + 1)) {\n return true;\n }\n }\n return false;\n }\n current = field;\n }\n return node === current;\n}\n\n/**\n * A generated matcher function for a selector.\n * @callback SelectorMatcher\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @returns {void}\n*/\n\n/**\n * A WeakMap for holding cached matcher functions for selectors.\n * @type {WeakMap}\n*/\nconst MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap : null;\n\n/**\n * Look up a matcher function for `selector` in the cache.\n * If it does not exist, generate it with `generateMatcher` and add it to the cache.\n * In engines without WeakMap, the caching is skipped and matchers are generated with every call.\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction getMatcher(selector) {\n if (selector == null) {\n return () => true;\n }\n\n if (MATCHER_CACHE != null) {\n let matcher = MATCHER_CACHE.get(selector);\n if (matcher != null) {\n return matcher;\n }\n matcher = generateMatcher(selector);\n MATCHER_CACHE.set(selector, matcher);\n return matcher;\n }\n\n return generateMatcher(selector);\n}\n\n/**\n * Create a matcher function for `selector`,\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction generateMatcher(selector) {\n switch(selector.type) {\n case 'wildcard':\n return () => true;\n\n case 'identifier': {\n const value = selector.value.toLowerCase();\n return (node, ancestry, options) => {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return value === node[nodeTypeKey].toLowerCase();\n };\n }\n\n case 'exactNode':\n return (node, ancestry) => {\n return ancestry.length === 0;\n };\n\n case 'field': {\n const path = selector.name.split('.');\n return (node, ancestry) => {\n const ancestor = ancestry[path.length - 1];\n return inPath(node, ancestor, path, 0);\n };\n }\n\n case 'matches': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return true; }\n }\n return false;\n };\n }\n\n case 'compound': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (!matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'not': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'has': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n let result = false;\n\n const a = [];\n estraverse.traverse(node, {\n enter (node, parent) {\n if (parent != null) { a.unshift(parent); }\n\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, a, options)) {\n result = true;\n this.break();\n return;\n }\n }\n },\n leave () { a.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n\n return result;\n };\n }\n\n case 'child': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (ancestry.length > 0 && right(node, ancestry, options)) {\n return left(ancestry[0], ancestry.slice(1), options);\n }\n return false;\n };\n }\n\n case 'descendant': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (right(node, ancestry, options)) {\n for (let i = 0, l = ancestry.length; i < l; ++i) {\n if (left(ancestry[i], ancestry.slice(i + 1), options)) {\n return true;\n }\n }\n }\n return false;\n };\n }\n\n case 'attribute': {\n const path = selector.name.split('.');\n switch (selector.operator) {\n case void 0:\n return (node) => getPath(node, path) != null;\n case '=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => {\n const p = getPath(node, path);\n return typeof p === 'string' && selector.value.value.test(p);\n };\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal === `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value === typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '!=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => !selector.value.value.test(getPath(node, path));\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal !== `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value !== typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '<=':\n return (node) => getPath(node, path) <= selector.value.value;\n case '<':\n return (node) => getPath(node, path) < selector.value.value;\n case '>':\n return (node) => getPath(node, path) > selector.value.value;\n case '>=':\n return (node) => getPath(node, path) >= selector.value.value;\n }\n throw new Error(`Unknown operator: ${selector.operator}`);\n }\n\n case 'sibling': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n sibling(node, left, ancestry, LEFT_SIDE, options) ||\n selector.left.subject &&\n left(node, ancestry, options) &&\n sibling(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'adjacent': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n adjacent(node, left, ancestry, LEFT_SIDE, options) ||\n selector.right.subject &&\n left(node, ancestry, options) &&\n adjacent(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'nth-child': {\n const nth = selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'nth-last-child': {\n const nth = -selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'class': {\n \n const name = selector.name.toLowerCase();\n\n return (node, ancestry, options) => {\n \n if (options && options.matchClass) {\n return options.matchClass(selector.name, node, ancestry);\n }\n \n if (options && options.nodeTypeKey) return false; \n\n switch(name){\n case 'statement':\n if(node.type.slice(-9) === 'Statement') return true;\n // fallthrough: interface Declaration <: Statement { }\n case 'declaration':\n return node.type.slice(-11) === 'Declaration';\n case 'pattern':\n if(node.type.slice(-7) === 'Pattern') return true;\n // fallthrough: interface Expression <: Node, Pattern { }\n case 'expression':\n return node.type.slice(-10) === 'Expression' ||\n node.type.slice(-7) === 'Literal' ||\n (\n node.type === 'Identifier' &&\n (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty')\n ) ||\n node.type === 'MetaProperty';\n case 'function':\n return node.type === 'FunctionDeclaration' ||\n node.type === 'FunctionExpression' ||\n node.type === 'ArrowFunctionExpression';\n }\n throw new Error(`Unknown class name: ${selector.name}`);\n };\n }\n }\n\n throw new Error(`Unknown selector type: ${selector.type}`);\n}\n\n/**\n * @callback TraverseOptionFallback\n * @param {external:AST} node The given node.\n * @returns {string[]} An array of visitor keys for the given node.\n */\n\n/**\n * @callback ClassMatcher\n * @param {string} className The name of the class to match.\n * @param {external:AST} node The node to match against.\n * @param {Array} ancestry The ancestry of the node.\n * @returns {boolean} True if the node matches the class, false if not.\n */\n\n/**\n * @typedef {object} ESQueryOptions\n * @property {string} [nodeTypeKey=\"type\"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery.\n * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node.\n * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes.\n * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes.\n */\n\n/**\n * Given a `node` and its ancestors, determine if `node` is matched\n * by `selector`.\n * @param {?external:AST} node\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @throws {Error} Unknowns (operator, class name, selector type, or\n * selector value type)\n * @returns {boolean}\n */\nfunction matches(node, selector, ancestry, options) {\n if (!selector) { return true; }\n if (!node) { return false; }\n if (!ancestry) { ancestry = []; }\n\n return getMatcher(selector)(node, ancestry, options);\n}\n\n/**\n * Get visitor keys of a given node.\n * @param {external:AST} node The AST node to get keys.\n * @param {ESQueryOptions|undefined} options\n * @returns {string[]} Visitor keys of the node.\n */\nfunction getVisitorKeys(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n\n const nodeType = node[nodeTypeKey];\n if (options && options.visitorKeys && options.visitorKeys[nodeType]) {\n return options.visitorKeys[nodeType];\n }\n if (estraverse.VisitorKeys[nodeType]) {\n return estraverse.VisitorKeys[nodeType];\n }\n if (options && typeof options.fallback === 'function') {\n return options.fallback(node);\n }\n // 'iteration' fallback\n return Object.keys(node).filter(function (key) {\n return key !== nodeTypeKey;\n });\n}\n\n\n/**\n * Check whether the given value is an ASTNode or not.\n * @param {any} node The value to check.\n * @param {ESQueryOptions|undefined} options The options to use.\n * @returns {boolean} `true` if the value is an ASTNode.\n */\nfunction isNode(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return node !== null && typeof node === 'object' && typeof node[nodeTypeKey] === 'string';\n}\n\n/**\n * Determines if the given node has a sibling that matches the\n * given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction sibling(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const startIndex = listProp.indexOf(node);\n if (startIndex < 0) { continue; }\n let lowerBound, upperBound;\n if (side === LEFT_SIDE) {\n lowerBound = 0;\n upperBound = startIndex;\n } else {\n lowerBound = startIndex + 1;\n upperBound = listProp.length;\n }\n for (let k = lowerBound; k < upperBound; ++k) {\n if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node has an adjacent sibling that matches\n * the given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction adjacent(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const idx = listProp.indexOf(node);\n if (idx < 0) { continue; }\n if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) {\n return true;\n }\n if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node is the `nth` child.\n * If `nth` is negative then the position is counted\n * from the end of the list of children.\n * @param {external:AST} node\n * @param {external:AST[]} ancestry\n * @param {Integer} nth\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction nthChild(node, ancestry, nth, options) {\n if (nth === 0) { return false; }\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)){\n const idx = nth < 0 ? listProp.length + nth : nth - 1;\n if (idx >= 0 && idx < listProp.length && listProp[idx] === node) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * For each selector node marked as a subject, find the portion of the\n * selector that the subject must match.\n * @param {SelectorAST} selector\n * @param {SelectorAST} [ancestor] Defaults to `selector`\n * @returns {SelectorAST[]}\n */\nfunction subjects(selector, ancestor) {\n if (selector == null || typeof selector != 'object') { return []; }\n if (ancestor == null) { ancestor = selector; }\n const results = selector.subject ? [ancestor] : [];\n const keys = Object.keys(selector);\n for (let i = 0; i < keys.length; ++i) {\n const p = keys[i];\n const sel = selector[p];\n results.push(...subjects(sel, p === 'left' ? sel : ancestor));\n }\n return results;\n}\n\n/**\n* @callback TraverseVisitor\n* @param {?external:AST} node\n* @param {?external:AST} parent\n* @param {external:AST[]} ancestry\n*/\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {TraverseVisitor} visitor\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction traverse(ast, selector, visitor, options) {\n if (!selector) { return; }\n const ancestry = [];\n const matcher = getMatcher(selector);\n const altSubjects = subjects(selector).map(getMatcher);\n estraverse.traverse(ast, {\n enter (node, parent) {\n if (parent != null) { ancestry.unshift(parent); }\n if (matcher(node, ancestry, options)) {\n if (altSubjects.length) {\n for (let i = 0, l = altSubjects.length; i < l; ++i) {\n if (altSubjects[i](node, ancestry, options)) {\n visitor(node, parent, ancestry);\n }\n for (let k = 0, m = ancestry.length; k < m; ++k) {\n const succeedingAncestry = ancestry.slice(k + 1);\n if (altSubjects[i](ancestry[k], succeedingAncestry, options)) {\n visitor(ancestry[k], parent, succeedingAncestry);\n }\n }\n }\n } else {\n visitor(node, parent, ancestry);\n }\n }\n },\n leave () { ancestry.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n}\n\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction match(ast, selector, options) {\n const results = [];\n traverse(ast, selector, function (node) {\n results.push(node);\n }, options);\n return results;\n}\n\n/**\n * Parse a selector string and return its AST.\n * @param {string} selector\n * @returns {SelectorAST}\n */\nfunction parse(selector) {\n return parser.parse(selector);\n}\n\n/**\n * Query the code AST using the selector string.\n * @param {external:AST} ast\n * @param {string} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction query(ast, selector, options) {\n return match(ast, parse(selector), options);\n}\n\nquery.parse = parse;\nquery.match = match;\nquery.traverse = traverse;\nquery.matches = matches;\nquery.query = query;\n\nexport default query;\n"],"names":["module","exports","peg$SyntaxError","message","expected","found","location","this","name","Error","captureStackTrace","child","parent","ctor","constructor","prototype","peg$subclass","buildMessage","DESCRIBE_EXPECTATION_FNS","literal","expectation","literalEscape","text","class","i","escapedParts","parts","length","Array","classEscape","inverted","any","end","other","description","hex","ch","charCodeAt","toString","toUpperCase","s","replace","j","descriptions","type","sort","slice","join","describeExpected","describeFound","SyntaxError","parse","input","options","peg$result","peg$FAILED","peg$startRuleFunctions","start","peg$parsestart","peg$startRuleFunction","peg$c3","peg$literalExpectation","peg$c4","peg$c5","peg$classExpectation","peg$c8","peg$c11","peg$c14","peg$c18","peg$c19","ss","concat","map","peg$c23","peg$c26","peg$c29","peg$c32","peg$c34","peg$c36","peg$c37","peg$c39","peg$c40","a","peg$c41","peg$c42","peg$c44","peg$c46","op","value","operator","peg$c49","peg$c50","peg$c51","peg$c53","peg$c54","peg$c55","b","peg$c56","d","match","peg$c58","peg$c59","peg$c60","peg$c61","peg$c62","peg$c66","peg$c67","peg$c68","peg$c70","peg$c72","peg$c73","peg$c75","peg$c76","peg$c77","peg$c81","peg$c84","peg$c87","peg$c90","peg$c93","peg$c96","peg$c99","peg$c102","peg$currPos","peg$posDetailsCache","line","column","peg$maxFailPos","peg$maxFailExpected","peg$resultsCache","startRule","ignoreCase","peg$computePosDetails","pos","p","details","peg$computeLocation","startPos","endPos","startPosDetails","endPosDetails","offset","peg$fail","push","s0","s1","s2","key","cached","nextPos","result","peg$parse_","peg$parseselectors","selectors","peg$c1","peg$parseidentifierName","test","charAt","peg$parsebinaryOp","s3","s4","s5","s6","s7","peg$parseselector","peg$parsehasSelector","left","right","peg$parsesequence","reduce","memo","rhs","subject","as","peg$parseatom","peg$parsewildcard","peg$parseidentifier","peg$parseattrName","peg$parseattrEqOps","substr","peg$parsetype","flgs","peg$parseflags","RegExp","peg$parseregex","peg$parseattrOps","peg$parsestring","leadingDecimals","apply","parseFloat","peg$parsenumber","peg$parsepath","peg$parseattrValue","peg$parseattr","peg$parsefield","peg$parsenegation","peg$parsematches","peg$parsehasSelectors","peg$parsehas","nth","peg$parsefirstChild","nthLast","peg$parselastChild","parseInt","peg$parsenthChild","peg$parsenthLastChild","peg$parseclass","n","index","factory","getPath","obj","keys","MATCHER_CACHE","WeakMap","getMatcher","selector","matcher","get","generateMatcher","set","toLowerCase","node","ancestry","nodeTypeKey","path","split","inPath","ancestor","fromPathIndex","current","field","isArray","k","matchers","estraverse","traverse","enter","unshift","leave","shift","visitorKeys","fallback","l","sibling","adjacent","nthChild","matchClass","getVisitorKeys","nodeType","VisitorKeys","Object","filter","isNode","_typeof","side","listProp","startIndex","indexOf","lowerBound","upperBound","idx","ast","visitor","altSubjects","subjects","results","sel","m","succeedingAncestry","parser","query","matches"],"mappings":"mnEAQ2CA,EAAOC,UAC9CD,UAEK,WASP,SAASE,EAAgBC,EAASC,EAAUC,EAAOC,GACjDC,KAAKJ,QAAWA,EAChBI,KAAKH,SAAWA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AAQ6M,EAAImC,IAAKnC,EAAG,CAC7C,IAAMoC,EAAqB9C,EAAShL,MAAM0L,EAAI,GAC1C+B,EAAY/O,GAAGsM,EAASU,GAAIoC,EAAoBvN,IAChDiN,EAAQxC,EAASU,GAAI5N,EAAQgQ,SAKzCN,EAAQzC,EAAMjN,EAAQkN,IAIlCgB,iBAAWhB,EAASiB,SACpB5B,KAAM9J,GAAWA,EAAQ2L,YACzBC,SAAU5L,GAAWA,EAAQ4L,UAAY,eAajD,SAAS9I,EAAMkK,EAAK9C,EAAUlK,GAC1B,IAAMoN,EAAU,GAIhB,OAHA9B,EAAS0B,EAAK9C,GAAU,SAAUM,GAC9B4C,EAAQ3H,KAAK+E,KACdxK,GACIoN,EAQX,SAAStN,EAAMoK,GACX,OAAOsD,EAAO1N,MAAMoK,GAUxB,SAASuD,EAAMT,EAAK9C,EAAUlK,GAC1B,OAAO8C,EAAMkK,EAAKlN,EAAMoK,GAAWlK,UAGvCyN,EAAM3N,MAAQA,EACd2N,EAAM3K,MAAQA,EACd2K,EAAMnC,SAAWA,EACjBmC,EAAMC,QAvPN,SAAiBlD,EAAMN,EAAUO,EAAUzK,GACvC,OAAKkK,KACAM,IACAC,IAAYA,EAAW,IAErBR,EAAWC,EAAXD,CAAqBO,EAAMC,EAAUzK,KAmPhDyN,EAAMA,MAAQA"} \ No newline at end of file diff --git a/node_modules/esquery/dist/esquery.min.js b/node_modules/esquery/dist/esquery.min.js new file mode 100644 index 00000000..6ec6c9b9 --- /dev/null +++ b/node_modules/esquery/dist/esquery.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).esquery=t()}(this,(function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,s=[],u=!0,l=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){l=!0,o=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(l)throw o}}return s}}(e,t)||n(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||n(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(e,t){if(e){if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0;--r)if(e[r].node===t)return!0;return!1}function d(e,t){return(new f).traverse(e,t)}function m(e,t){var r;return r=function(e,t){var r,n,o,a;for(n=e.length,o=0;n;)t(e[a=o+(r=n>>>1)])?n=r:(o=a+1,n-=r+1);return o}(t,(function(t){return t.range[0]>e.range[0]})),e.extendedRange=[e.range[0],e.range[1]],r!==t.length&&(e.extendedRange[1]=t[r].range[0]),(r-=1)>=0&&(e.extendedRange[0]=t[r].range[1]),e}return r={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ChainExpression:"ChainExpression",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",PrivateIdentifier:"PrivateIdentifier",Program:"Program",Property:"Property",PropertyDefinition:"PropertyDefinition",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},o={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ChainExpression:["expression"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateIdentifier:[],Program:["body"],Property:["key","value"],PropertyDefinition:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],Super:[],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]},n={Break:a={},Skip:i={},Remove:s={}},l.prototype.replace=function(e){this.parent[this.key]=e},l.prototype.remove=function(){return Array.isArray(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},f.prototype.path=function(){var e,t,r,n,o;function a(e,t){if(Array.isArray(t))for(r=0,n=t.length;r=0;)if(v=s[f=x[d]])if(Array.isArray(v)){for(m=v.length;(m-=1)>=0;)if(v[m]&&!y(n,v[m])){if(h(u,x[d]))o=new c(v[m],[f,m],"Property",null);else{if(!p(v[m]))continue;o=new c(v[m],[f,m],null,null)}r.push(o)}}else if(p(v)){if(y(n,v))continue;r.push(new c(v,f,null,null))}}}else if(o=n.pop(),l=this.__execute(t.leave,o),this.__state===a||l===a)return},f.prototype.replace=function(e,t){var r,n,o,u,f,y,d,m,x,v,g,A,E;function b(e){var t,n,o,a;if(e.ref.remove())for(n=e.ref.key,a=e.ref.parent,t=r.length;t--;)if((o=r[t]).ref&&o.ref.parent===a){if(o.ref.key=0;)if(v=o[E=x[d]])if(Array.isArray(v)){for(m=v.length;(m-=1)>=0;)if(v[m]){if(h(u,x[d]))y=new c(v[m],[E,m],"Property",new l(v,m));else{if(!p(v[m]))continue;y=new c(v[m],[E,m],null,new l(v,m))}r.push(y)}}else p(v)&&r.push(new c(v,E,null,new l(o,E)))}}else if(y=n.pop(),void 0!==(f=this.__execute(t.leave,y))&&f!==a&&f!==i&&f!==s&&y.ref.replace(f),this.__state!==s&&f!==s||b(y),this.__state===a||f===a)return A.root;return A.root},t.Syntax=r,t.traverse=d,t.replace=function(e,t){return(new f).replace(e,t)},t.attachComments=function(e,t,r){var o,a,i,s,l=[];if(!e.range)throw new Error("attachComments needs range information");if(!r.length){if(t.length){for(i=0,a=t.length;ie.range[0]);)t.extendedRange[1]===e.range[0]?(e.leadingComments||(e.leadingComments=[]),e.leadingComments.push(t),l.splice(s,1)):s+=1;return s===l.length?n.Break:l[s].extendedRange[0]>e.range[1]?n.Skip:void 0}}),s=0,d(e,{leave:function(e){for(var t;se.range[1]?n.Skip:void 0}}),e},t.VisitorKeys=o,t.VisitorOption=n,t.Controller=f,t.cloneEnvironment=function(){return e({})},t}(t)})),s=a((function(e){e.exports&&(e.exports=function(){function e(t,r,n,o){this.message=t,this.expected=r,this.found=n,this.location=o,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}return function(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}(e,Error),e.buildMessage=function(e,t){var r={literal:function(e){return'"'+o(e.text)+'"'},class:function(e){var t,r="";for(t=0;t0){for(t=1,n=1;t<~+.]/,p=pe([" ","[","]",",","(",")",":","#","!","=",">","<","~","+","."],!0,!1),h=fe(">",!1),y=fe("~",!1),d=fe("+",!1),m=fe(",",!1),x=function(e,t){return[e].concat(t.map((function(e){return e[3]})))},v=fe("!",!1),g=fe("*",!1),A=fe("#",!1),E=fe("[",!1),b=fe("]",!1),S=/^[>","<","!"],!1,!1),C=fe("=",!1),w=function(e){return(e||"")+"="},P=/^[><]/,k=pe([">","<"],!1,!1),D=fe(".",!1),I=function(e,t,r){return{type:"attribute",name:e,operator:t,value:r}},j=fe('"',!1),T=/^[^\\"]/,F=pe(["\\",'"'],!0,!1),R=fe("\\",!1),O={type:"any"},L=function(e,t){return e+t},M=function(e){return{type:"literal",value:(t=e.join(""),t.replace(/\\(.)/g,(function(e,t){switch(t){case"b":return"\b";case"f":return"\f";case"n":return"\n";case"r":return"\r";case"t":return"\t";case"v":return"\v";default:return t}})))};var t},B=fe("'",!1),U=/^[^\\']/,K=pe(["\\","'"],!0,!1),N=/^[0-9]/,W=pe([["0","9"]],!1,!1),q=fe("type(",!1),V=/^[^ )]/,G=pe([" ",")"],!0,!1),z=fe(")",!1),H=/^[imsu]/,Y=pe(["i","m","s","u"],!1,!1),$=fe("/",!1),J=/^[^\/]/,Q=pe(["/"],!0,!1),X=fe(":not(",!1),Z=fe(":matches(",!1),ee=fe(":has(",!1),te=fe(":first-child",!1),re=fe(":last-child",!1),ne=fe(":nth-child(",!1),oe=fe(":nth-last-child(",!1),ae=fe(":",!1),ie=0,se=[{line:1,column:1}],ue=0,le=[],ce={};if("startRule"in r){if(!(r.startRule in u))throw new Error("Can't start parsing from rule \""+r.startRule+'".');l=u[r.startRule]}function fe(e,t){return{type:"literal",text:e,ignoreCase:t}}function pe(e,t,r){return{type:"class",parts:e,inverted:t,ignoreCase:r}}function he(e){var r,n=se[e];if(n)return n;for(r=e-1;!se[r];)r--;for(n={line:(n=se[r]).line,column:n.column};rue&&(ue=ie,le=[]),le.push(e))}function me(){var e,t,r,n,o=32*ie+0,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,(t=xe())!==s&&(r=Ae())!==s&&xe()!==s?e=t=1===(n=r).length?n[0]:{type:"matches",selectors:n}:(ie=e,e=s),e===s&&(e=ie,(t=xe())!==s&&(t=void 0),e=t),ce[o]={nextPos:ie,result:e},e)}function xe(){var e,r,n=32*ie+1,o=ce[n];if(o)return ie=o.nextPos,o.result;for(e=[],32===t.charCodeAt(ie)?(r=" ",ie++):(r=s,de(c));r!==s;)e.push(r),32===t.charCodeAt(ie)?(r=" ",ie++):(r=s,de(c));return ce[n]={nextPos:ie,result:e},e}function ve(){var e,r,n,o=32*ie+2,a=ce[o];if(a)return ie=a.nextPos,a.result;if(r=[],f.test(t.charAt(ie))?(n=t.charAt(ie),ie++):(n=s,de(p)),n!==s)for(;n!==s;)r.push(n),f.test(t.charAt(ie))?(n=t.charAt(ie),ie++):(n=s,de(p));else r=s;return r!==s&&(r=r.join("")),e=r,ce[o]={nextPos:ie,result:e},e}function ge(){var e,r,n,o=32*ie+3,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,(r=xe())!==s?(62===t.charCodeAt(ie)?(n=">",ie++):(n=s,de(h)),n!==s&&xe()!==s?e=r="child":(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,(r=xe())!==s?(126===t.charCodeAt(ie)?(n="~",ie++):(n=s,de(y)),n!==s&&xe()!==s?e=r="sibling":(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,(r=xe())!==s?(43===t.charCodeAt(ie)?(n="+",ie++):(n=s,de(d)),n!==s&&xe()!==s?e=r="adjacent":(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,32===t.charCodeAt(ie)?(r=" ",ie++):(r=s,de(c)),r!==s&&(n=xe())!==s?e=r="descendant":(ie=e,e=s)))),ce[o]={nextPos:ie,result:e},e)}function Ae(){var e,r,n,o,a,i,u,l,c=32*ie+5,f=ce[c];if(f)return ie=f.nextPos,f.result;if(e=ie,(r=be())!==s){for(n=[],o=ie,(a=xe())!==s?(44===t.charCodeAt(ie)?(i=",",ie++):(i=s,de(m)),i!==s&&(u=xe())!==s&&(l=be())!==s?o=a=[a,i,u,l]:(ie=o,o=s)):(ie=o,o=s);o!==s;)n.push(o),o=ie,(a=xe())!==s?(44===t.charCodeAt(ie)?(i=",",ie++):(i=s,de(m)),i!==s&&(u=xe())!==s&&(l=be())!==s?o=a=[a,i,u,l]:(ie=o,o=s)):(ie=o,o=s);n!==s?e=r=x(r,n):(ie=e,e=s)}else ie=e,e=s;return ce[c]={nextPos:ie,result:e},e}function Ee(){var e,t,r,n,o,a=32*ie+6,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,(t=ge())===s&&(t=null),t!==s&&(r=be())!==s?(o=r,e=t=(n=t)?{type:n,left:{type:"exactNode"},right:o}:o):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}function be(){var e,t,r,n,o,a,i,u=32*ie+7,l=ce[u];if(l)return ie=l.nextPos,l.result;if(e=ie,(t=Se())!==s){for(r=[],n=ie,(o=ge())!==s&&(a=Se())!==s?n=o=[o,a]:(ie=n,n=s);n!==s;)r.push(n),n=ie,(o=ge())!==s&&(a=Se())!==s?n=o=[o,a]:(ie=n,n=s);r!==s?(i=t,e=t=r.reduce((function(e,t){return{type:t[0],left:e,right:t[1]}}),i)):(ie=e,e=s)}else ie=e,e=s;return ce[u]={nextPos:ie,result:e},e}function Se(){var e,r,n,o,a,i,u,l=32*ie+8,c=ce[l];if(c)return ie=c.nextPos,c.result;if(e=ie,33===t.charCodeAt(ie)?(r="!",ie++):(r=s,de(v)),r===s&&(r=null),r!==s){if(n=[],(o=_e())!==s)for(;o!==s;)n.push(o),o=_e();else n=s;n!==s?(a=r,u=1===(i=n).length?i[0]:{type:"compound",selectors:i},a&&(u.subject=!0),e=r=u):(ie=e,e=s)}else ie=e,e=s;return ce[l]={nextPos:ie,result:e},e}function _e(){var e,r=32*ie+9,n=ce[r];return n?(ie=n.nextPos,n.result):((e=function(){var e,r,n=32*ie+10,o=ce[n];return o?(ie=o.nextPos,o.result):(42===t.charCodeAt(ie)?(r="*",ie++):(r=s,de(g)),r!==s&&(r={type:"wildcard",value:r}),e=r,ce[n]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o=32*ie+11,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,35===t.charCodeAt(ie)?(r="#",ie++):(r=s,de(A)),r===s&&(r=null),r!==s&&(n=ve())!==s?e=r={type:"identifier",value:n}:(ie=e,e=s),ce[o]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=32*ie+12,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,91===t.charCodeAt(ie)?(r="[",ie++):(r=s,de(E)),r!==s&&xe()!==s&&(n=function(){var e,r,n,o,a=32*ie+16,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,(r=Ce())!==s&&xe()!==s&&(n=function(){var e,r,n,o=32*ie+14,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,33===t.charCodeAt(ie)?(r="!",ie++):(r=s,de(v)),r===s&&(r=null),r!==s?(61===t.charCodeAt(ie)?(n="=",ie++):(n=s,de(C)),n!==s?(r=w(r),e=r):(ie=e,e=s)):(ie=e,e=s),ce[o]={nextPos:ie,result:e},e)}())!==s&&xe()!==s?((o=function(){var e,r,n,o,a,i=32*ie+20,u=ce[i];if(u)return ie=u.nextPos,u.result;if(e=ie,"type("===t.substr(ie,5)?(r="type(",ie+=5):(r=s,de(q)),r!==s)if(xe()!==s){if(n=[],V.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(G)),o!==s)for(;o!==s;)n.push(o),V.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(G));else n=s;n!==s&&(o=xe())!==s?(41===t.charCodeAt(ie)?(a=")",ie++):(a=s,de(z)),a!==s?(r={type:"type",value:n.join("")},e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;else ie=e,e=s;return ce[i]={nextPos:ie,result:e},e}())===s&&(o=function(){var e,r,n,o,a,i,u=32*ie+22,l=ce[u];if(l)return ie=l.nextPos,l.result;if(e=ie,47===t.charCodeAt(ie)?(r="/",ie++):(r=s,de($)),r!==s){if(n=[],J.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(Q)),o!==s)for(;o!==s;)n.push(o),J.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(Q));else n=s;n!==s?(47===t.charCodeAt(ie)?(o="/",ie++):(o=s,de($)),o!==s?((a=function(){var e,r,n=32*ie+21,o=ce[n];if(o)return ie=o.nextPos,o.result;if(e=[],H.test(t.charAt(ie))?(r=t.charAt(ie),ie++):(r=s,de(Y)),r!==s)for(;r!==s;)e.push(r),H.test(t.charAt(ie))?(r=t.charAt(ie),ie++):(r=s,de(Y));else e=s;return ce[n]={nextPos:ie,result:e},e}())===s&&(a=null),a!==s?(i=a,r={type:"regexp",value:new RegExp(n.join(""),i?i.join(""):"")},e=r):(ie=e,e=s)):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;return ce[u]={nextPos:ie,result:e},e}()),o!==s?(r=I(r,n,o),e=r):(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,(r=Ce())!==s&&xe()!==s&&(n=function(){var e,r,n,o=32*ie+13,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,S.test(t.charAt(ie))?(r=t.charAt(ie),ie++):(r=s,de(_)),r===s&&(r=null),r!==s?(61===t.charCodeAt(ie)?(n="=",ie++):(n=s,de(C)),n!==s?(r=w(r),e=r):(ie=e,e=s)):(ie=e,e=s),e===s&&(P.test(t.charAt(ie))?(e=t.charAt(ie),ie++):(e=s,de(k))),ce[o]={nextPos:ie,result:e},e)}())!==s&&xe()!==s?((o=function(){var e,r,n,o,a,i,u=32*ie+17,l=ce[u];if(l)return ie=l.nextPos,l.result;if(e=ie,34===t.charCodeAt(ie)?(r='"',ie++):(r=s,de(j)),r!==s){for(n=[],T.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(F)),o===s&&(o=ie,92===t.charCodeAt(ie)?(a="\\",ie++):(a=s,de(R)),a!==s?(t.length>ie?(i=t.charAt(ie),ie++):(i=s,de(O)),i!==s?(a=L(a,i),o=a):(ie=o,o=s)):(ie=o,o=s));o!==s;)n.push(o),T.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(F)),o===s&&(o=ie,92===t.charCodeAt(ie)?(a="\\",ie++):(a=s,de(R)),a!==s?(t.length>ie?(i=t.charAt(ie),ie++):(i=s,de(O)),i!==s?(a=L(a,i),o=a):(ie=o,o=s)):(ie=o,o=s));n!==s?(34===t.charCodeAt(ie)?(o='"',ie++):(o=s,de(j)),o!==s?(r=M(n),e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;if(e===s)if(e=ie,39===t.charCodeAt(ie)?(r="'",ie++):(r=s,de(B)),r!==s){for(n=[],U.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(K)),o===s&&(o=ie,92===t.charCodeAt(ie)?(a="\\",ie++):(a=s,de(R)),a!==s?(t.length>ie?(i=t.charAt(ie),ie++):(i=s,de(O)),i!==s?(a=L(a,i),o=a):(ie=o,o=s)):(ie=o,o=s));o!==s;)n.push(o),U.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(K)),o===s&&(o=ie,92===t.charCodeAt(ie)?(a="\\",ie++):(a=s,de(R)),a!==s?(t.length>ie?(i=t.charAt(ie),ie++):(i=s,de(O)),i!==s?(a=L(a,i),o=a):(ie=o,o=s)):(ie=o,o=s));n!==s?(39===t.charCodeAt(ie)?(o="'",ie++):(o=s,de(B)),o!==s?(r=M(n),e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;return ce[u]={nextPos:ie,result:e},e}())===s&&(o=function(){var e,r,n,o,a,i,u,l=32*ie+18,c=ce[l];if(c)return ie=c.nextPos,c.result;for(e=ie,r=ie,n=[],N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));o!==s;)n.push(o),N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));if(n!==s?(46===t.charCodeAt(ie)?(o=".",ie++):(o=s,de(D)),o!==s?r=n=[n,o]:(ie=r,r=s)):(ie=r,r=s),r===s&&(r=null),r!==s){if(n=[],N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));else n=s;n!==s?(i=n,u=(a=r)?[].concat.apply([],a).join(""):"",r={type:"literal",value:parseFloat(u+i.join(""))},e=r):(ie=e,e=s)}else ie=e,e=s;return ce[l]={nextPos:ie,result:e},e}())===s&&(o=function(){var e,t,r=32*ie+19,n=ce[r];return n?(ie=n.nextPos,n.result):((t=ve())!==s&&(t={type:"literal",value:t}),e=t,ce[r]={nextPos:ie,result:e},e)}()),o!==s?(r=I(r,n,o),e=r):(ie=e,e=s)):(ie=e,e=s),e===s&&(e=ie,(r=Ce())!==s&&(r={type:"attribute",name:r}),e=r)),ce[a]={nextPos:ie,result:e},e)}())!==s&&xe()!==s?(93===t.charCodeAt(ie)?(o="]",ie++):(o=s,de(b)),o!==s?e=r=n:(ie=e,e=s)):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a,i,u,l,c=32*ie+23,f=ce[c];if(f)return ie=f.nextPos,f.result;if(e=ie,46===t.charCodeAt(ie)?(r=".",ie++):(r=s,de(D)),r!==s)if((n=ve())!==s){for(o=[],a=ie,46===t.charCodeAt(ie)?(i=".",ie++):(i=s,de(D)),i!==s&&(u=ve())!==s?a=i=[i,u]:(ie=a,a=s);a!==s;)o.push(a),a=ie,46===t.charCodeAt(ie)?(i=".",ie++):(i=s,de(D)),i!==s&&(u=ve())!==s?a=i=[i,u]:(ie=a,a=s);o!==s?(l=n,r={type:"field",name:o.reduce((function(e,t){return e+t[0]+t[1]}),l)},e=r):(ie=e,e=s)}else ie=e,e=s;else ie=e,e=s;return ce[c]={nextPos:ie,result:e},e}())===s&&(e=function(){var e,r,n,o,a=32*ie+24,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,":not("===t.substr(ie,5)?(r=":not(",ie+=5):(r=s,de(X)),r!==s&&xe()!==s&&(n=Ae())!==s&&xe()!==s?(41===t.charCodeAt(ie)?(o=")",ie++):(o=s,de(z)),o!==s?e=r={type:"not",selectors:n}:(ie=e,e=s)):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=32*ie+25,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,":matches("===t.substr(ie,9)?(r=":matches(",ie+=9):(r=s,de(Z)),r!==s&&xe()!==s&&(n=Ae())!==s&&xe()!==s?(41===t.charCodeAt(ie)?(o=")",ie++):(o=s,de(z)),o!==s?e=r={type:"matches",selectors:n}:(ie=e,e=s)):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=32*ie+26,i=ce[a];return i?(ie=i.nextPos,i.result):(e=ie,":has("===t.substr(ie,5)?(r=":has(",ie+=5):(r=s,de(ee)),r!==s&&xe()!==s&&(n=function(){var e,r,n,o,a,i,u,l,c=32*ie+4,f=ce[c];if(f)return ie=f.nextPos,f.result;if(e=ie,(r=Ee())!==s){for(n=[],o=ie,(a=xe())!==s?(44===t.charCodeAt(ie)?(i=",",ie++):(i=s,de(m)),i!==s&&(u=xe())!==s&&(l=Ee())!==s?o=a=[a,i,u,l]:(ie=o,o=s)):(ie=o,o=s);o!==s;)n.push(o),o=ie,(a=xe())!==s?(44===t.charCodeAt(ie)?(i=",",ie++):(i=s,de(m)),i!==s&&(u=xe())!==s&&(l=Ee())!==s?o=a=[a,i,u,l]:(ie=o,o=s)):(ie=o,o=s);n!==s?e=r=x(r,n):(ie=e,e=s)}else ie=e,e=s;return ce[c]={nextPos:ie,result:e},e}())!==s&&xe()!==s?(41===t.charCodeAt(ie)?(o=")",ie++):(o=s,de(z)),o!==s?e=r={type:"has",selectors:n}:(ie=e,e=s)):(ie=e,e=s),ce[a]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n=32*ie+27,o=ce[n];return o?(ie=o.nextPos,o.result):(":first-child"===t.substr(ie,12)?(r=":first-child",ie+=12):(r=s,de(te)),r!==s&&(r=we(1)),e=r,ce[n]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n=32*ie+28,o=ce[n];return o?(ie=o.nextPos,o.result):(":last-child"===t.substr(ie,11)?(r=":last-child",ie+=11):(r=s,de(re)),r!==s&&(r=Pe(1)),e=r,ce[n]={nextPos:ie,result:e},e)}())===s&&(e=function(){var e,r,n,o,a,i=32*ie+29,u=ce[i];if(u)return ie=u.nextPos,u.result;if(e=ie,":nth-child("===t.substr(ie,11)?(r=":nth-child(",ie+=11):(r=s,de(ne)),r!==s)if(xe()!==s){if(n=[],N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));else n=s;n!==s&&(o=xe())!==s?(41===t.charCodeAt(ie)?(a=")",ie++):(a=s,de(z)),a!==s?(r=we(parseInt(n.join(""),10)),e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;else ie=e,e=s;return ce[i]={nextPos:ie,result:e},e}())===s&&(e=function(){var e,r,n,o,a,i=32*ie+30,u=ce[i];if(u)return ie=u.nextPos,u.result;if(e=ie,":nth-last-child("===t.substr(ie,16)?(r=":nth-last-child(",ie+=16):(r=s,de(oe)),r!==s)if(xe()!==s){if(n=[],N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ie))?(o=t.charAt(ie),ie++):(o=s,de(W));else n=s;n!==s&&(o=xe())!==s?(41===t.charCodeAt(ie)?(a=")",ie++):(a=s,de(z)),a!==s?(r=Pe(parseInt(n.join(""),10)),e=r):(ie=e,e=s)):(ie=e,e=s)}else ie=e,e=s;else ie=e,e=s;return ce[i]={nextPos:ie,result:e},e}())===s&&(e=function(){var e,r,n,o=32*ie+31,a=ce[o];return a?(ie=a.nextPos,a.result):(e=ie,58===t.charCodeAt(ie)?(r=":",ie++):(r=s,de(ae)),r!==s&&(n=ve())!==s?e=r={type:"class",name:n}:(ie=e,e=s),ce[o]={nextPos:ie,result:e},e)}()),ce[r]={nextPos:ie,result:e},e)}function Ce(){var e,r,n,o,a,i,u,l,c=32*ie+15,f=ce[c];if(f)return ie=f.nextPos,f.result;if(e=ie,(r=ve())!==s){for(n=[],o=ie,46===t.charCodeAt(ie)?(a=".",ie++):(a=s,de(D)),a!==s&&(i=ve())!==s?o=a=[a,i]:(ie=o,o=s);o!==s;)n.push(o),o=ie,46===t.charCodeAt(ie)?(a=".",ie++):(a=s,de(D)),a!==s&&(i=ve())!==s?o=a=[a,i]:(ie=o,o=s);n!==s?(u=r,l=n,e=r=[].concat.apply([u],l).join("")):(ie=e,e=s)}else ie=e,e=s;return ce[c]={nextPos:ie,result:e},e}function we(e){return{type:"nth-child",index:{type:"literal",value:e}}}function Pe(e){return{type:"nth-last-child",index:{type:"literal",value:e}}}if((n=l())!==s&&ie===t.length)return n;throw n!==s&&ie0&&p(e,t,r))&&f(t[0],t.slice(1),r)};case"descendant":var h=c(t.left),x=c(t.right);return function(e,t,r){if(x(e,t,r))for(var n=0,o=t.length;n":return function(e){return u(e,v)>t.value.value};case">=":return function(e){return u(e,v)>=t.value.value}}throw new Error("Unknown operator: ".concat(t.operator));case"sibling":var E=c(t.left),b=c(t.right);return function(e,r,n){return b(e,r,n)&&y(e,E,r,"LEFT_SIDE",n)||t.left.subject&&E(e,r,n)&&y(e,b,r,"RIGHT_SIDE",n)};case"adjacent":var S=c(t.left),_=c(t.right);return function(e,r,n){return _(e,r,n)&&d(e,S,r,"LEFT_SIDE",n)||t.right.subject&&S(e,r,n)&&d(e,_,r,"RIGHT_SIDE",n)};case"nth-child":var C=t.index.value,w=c(t.right);return function(e,t,r){return w(e,t,r)&&m(e,t,C,r)};case"nth-last-child":var P=-t.index.value,k=c(t.right);return function(e,t,r){return k(e,t,r)&&m(e,t,P,r)};case"class":var D=t.name.toLowerCase();return function(e,r,n){if(n&&n.matchClass)return n.matchClass(t.name,e,r);if(n&&n.nodeTypeKey)return!1;switch(D){case"statement":if("Statement"===e.type.slice(-9))return!0;case"declaration":return"Declaration"===e.type.slice(-11);case"pattern":if("Pattern"===e.type.slice(-7))return!0;case"expression":return"Expression"===e.type.slice(-10)||"Literal"===e.type.slice(-7)||"Identifier"===e.type&&(0===r.length||"MetaProperty"!==r[0].type)||"MetaProperty"===e.type;case"function":return"FunctionDeclaration"===e.type||"FunctionExpression"===e.type||"ArrowFunctionExpression"===e.type}throw new Error("Unknown class name: ".concat(t.name))}}throw new Error("Unknown selector type: ".concat(t.type))}function p(e,t){var r=t&&t.nodeTypeKey||"type",n=e[r];return t&&t.visitorKeys&&t.visitorKeys[n]?t.visitorKeys[n]:i.VisitorKeys[n]?i.VisitorKeys[n]:t&&"function"==typeof t.fallback?t.fallback(e):Object.keys(e).filter((function(e){return e!==r}))}function h(t,r){var n=r&&r.nodeTypeKey||"type";return null!==t&&"object"===e(t)&&"string"==typeof t[n]}function y(e,r,n,o,a){var i=t(n,1)[0];if(!i)return!1;for(var s=p(i,a),u=0;u0&&h(l[c-1],a)&&r(l[c-1],n,a))return!0;if("RIGHT_SIDE"===o&&c=0&&l\n Copyright (C) 2012 Ariya Hidayat \n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*jslint vars:false, bitwise:true*/\n/*jshint indent:4*/\n/*global exports:true*/\n(function clone(exports) {\n 'use strict';\n\n var Syntax,\n VisitorOption,\n VisitorKeys,\n BREAK,\n SKIP,\n REMOVE;\n\n function deepCopy(obj) {\n var ret = {}, key, val;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) {\n val = obj[key];\n if (typeof val === 'object' && val !== null) {\n ret[key] = deepCopy(val);\n } else {\n ret[key] = val;\n }\n }\n }\n return ret;\n }\n\n // based on LLVM libc++ upper_bound / lower_bound\n // MIT License\n\n function upperBound(array, func) {\n var diff, len, i, current;\n\n len = array.length;\n i = 0;\n\n while (len) {\n diff = len >>> 1;\n current = i + diff;\n if (func(array[current])) {\n len = diff;\n } else {\n i = current + 1;\n len -= diff + 1;\n }\n }\n return i;\n }\n\n Syntax = {\n AssignmentExpression: 'AssignmentExpression',\n AssignmentPattern: 'AssignmentPattern',\n ArrayExpression: 'ArrayExpression',\n ArrayPattern: 'ArrayPattern',\n ArrowFunctionExpression: 'ArrowFunctionExpression',\n AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.\n BlockStatement: 'BlockStatement',\n BinaryExpression: 'BinaryExpression',\n BreakStatement: 'BreakStatement',\n CallExpression: 'CallExpression',\n CatchClause: 'CatchClause',\n ChainExpression: 'ChainExpression',\n ClassBody: 'ClassBody',\n ClassDeclaration: 'ClassDeclaration',\n ClassExpression: 'ClassExpression',\n ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.\n ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.\n ConditionalExpression: 'ConditionalExpression',\n ContinueStatement: 'ContinueStatement',\n DebuggerStatement: 'DebuggerStatement',\n DirectiveStatement: 'DirectiveStatement',\n DoWhileStatement: 'DoWhileStatement',\n EmptyStatement: 'EmptyStatement',\n ExportAllDeclaration: 'ExportAllDeclaration',\n ExportDefaultDeclaration: 'ExportDefaultDeclaration',\n ExportNamedDeclaration: 'ExportNamedDeclaration',\n ExportSpecifier: 'ExportSpecifier',\n ExpressionStatement: 'ExpressionStatement',\n ForStatement: 'ForStatement',\n ForInStatement: 'ForInStatement',\n ForOfStatement: 'ForOfStatement',\n FunctionDeclaration: 'FunctionDeclaration',\n FunctionExpression: 'FunctionExpression',\n GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.\n Identifier: 'Identifier',\n IfStatement: 'IfStatement',\n ImportExpression: 'ImportExpression',\n ImportDeclaration: 'ImportDeclaration',\n ImportDefaultSpecifier: 'ImportDefaultSpecifier',\n ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',\n ImportSpecifier: 'ImportSpecifier',\n Literal: 'Literal',\n LabeledStatement: 'LabeledStatement',\n LogicalExpression: 'LogicalExpression',\n MemberExpression: 'MemberExpression',\n MetaProperty: 'MetaProperty',\n MethodDefinition: 'MethodDefinition',\n ModuleSpecifier: 'ModuleSpecifier',\n NewExpression: 'NewExpression',\n ObjectExpression: 'ObjectExpression',\n ObjectPattern: 'ObjectPattern',\n PrivateIdentifier: 'PrivateIdentifier',\n Program: 'Program',\n Property: 'Property',\n PropertyDefinition: 'PropertyDefinition',\n RestElement: 'RestElement',\n ReturnStatement: 'ReturnStatement',\n SequenceExpression: 'SequenceExpression',\n SpreadElement: 'SpreadElement',\n Super: 'Super',\n SwitchStatement: 'SwitchStatement',\n SwitchCase: 'SwitchCase',\n TaggedTemplateExpression: 'TaggedTemplateExpression',\n TemplateElement: 'TemplateElement',\n TemplateLiteral: 'TemplateLiteral',\n ThisExpression: 'ThisExpression',\n ThrowStatement: 'ThrowStatement',\n TryStatement: 'TryStatement',\n UnaryExpression: 'UnaryExpression',\n UpdateExpression: 'UpdateExpression',\n VariableDeclaration: 'VariableDeclaration',\n VariableDeclarator: 'VariableDeclarator',\n WhileStatement: 'WhileStatement',\n WithStatement: 'WithStatement',\n YieldExpression: 'YieldExpression'\n };\n\n VisitorKeys = {\n AssignmentExpression: ['left', 'right'],\n AssignmentPattern: ['left', 'right'],\n ArrayExpression: ['elements'],\n ArrayPattern: ['elements'],\n ArrowFunctionExpression: ['params', 'body'],\n AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.\n BlockStatement: ['body'],\n BinaryExpression: ['left', 'right'],\n BreakStatement: ['label'],\n CallExpression: ['callee', 'arguments'],\n CatchClause: ['param', 'body'],\n ChainExpression: ['expression'],\n ClassBody: ['body'],\n ClassDeclaration: ['id', 'superClass', 'body'],\n ClassExpression: ['id', 'superClass', 'body'],\n ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.\n ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n ConditionalExpression: ['test', 'consequent', 'alternate'],\n ContinueStatement: ['label'],\n DebuggerStatement: [],\n DirectiveStatement: [],\n DoWhileStatement: ['body', 'test'],\n EmptyStatement: [],\n ExportAllDeclaration: ['source'],\n ExportDefaultDeclaration: ['declaration'],\n ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],\n ExportSpecifier: ['exported', 'local'],\n ExpressionStatement: ['expression'],\n ForStatement: ['init', 'test', 'update', 'body'],\n ForInStatement: ['left', 'right', 'body'],\n ForOfStatement: ['left', 'right', 'body'],\n FunctionDeclaration: ['id', 'params', 'body'],\n FunctionExpression: ['id', 'params', 'body'],\n GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n Identifier: [],\n IfStatement: ['test', 'consequent', 'alternate'],\n ImportExpression: ['source'],\n ImportDeclaration: ['specifiers', 'source'],\n ImportDefaultSpecifier: ['local'],\n ImportNamespaceSpecifier: ['local'],\n ImportSpecifier: ['imported', 'local'],\n Literal: [],\n LabeledStatement: ['label', 'body'],\n LogicalExpression: ['left', 'right'],\n MemberExpression: ['object', 'property'],\n MetaProperty: ['meta', 'property'],\n MethodDefinition: ['key', 'value'],\n ModuleSpecifier: [],\n NewExpression: ['callee', 'arguments'],\n ObjectExpression: ['properties'],\n ObjectPattern: ['properties'],\n PrivateIdentifier: [],\n Program: ['body'],\n Property: ['key', 'value'],\n PropertyDefinition: ['key', 'value'],\n RestElement: [ 'argument' ],\n ReturnStatement: ['argument'],\n SequenceExpression: ['expressions'],\n SpreadElement: ['argument'],\n Super: [],\n SwitchStatement: ['discriminant', 'cases'],\n SwitchCase: ['test', 'consequent'],\n TaggedTemplateExpression: ['tag', 'quasi'],\n TemplateElement: [],\n TemplateLiteral: ['quasis', 'expressions'],\n ThisExpression: [],\n ThrowStatement: ['argument'],\n TryStatement: ['block', 'handler', 'finalizer'],\n UnaryExpression: ['argument'],\n UpdateExpression: ['argument'],\n VariableDeclaration: ['declarations'],\n VariableDeclarator: ['id', 'init'],\n WhileStatement: ['test', 'body'],\n WithStatement: ['object', 'body'],\n YieldExpression: ['argument']\n };\n\n // unique id\n BREAK = {};\n SKIP = {};\n REMOVE = {};\n\n VisitorOption = {\n Break: BREAK,\n Skip: SKIP,\n Remove: REMOVE\n };\n\n function Reference(parent, key) {\n this.parent = parent;\n this.key = key;\n }\n\n Reference.prototype.replace = function replace(node) {\n this.parent[this.key] = node;\n };\n\n Reference.prototype.remove = function remove() {\n if (Array.isArray(this.parent)) {\n this.parent.splice(this.key, 1);\n return true;\n } else {\n this.replace(null);\n return false;\n }\n };\n\n function Element(node, path, wrap, ref) {\n this.node = node;\n this.path = path;\n this.wrap = wrap;\n this.ref = ref;\n }\n\n function Controller() { }\n\n // API:\n // return property path array from root to current node\n Controller.prototype.path = function path() {\n var i, iz, j, jz, result, element;\n\n function addToPath(result, path) {\n if (Array.isArray(path)) {\n for (j = 0, jz = path.length; j < jz; ++j) {\n result.push(path[j]);\n }\n } else {\n result.push(path);\n }\n }\n\n // root node\n if (!this.__current.path) {\n return null;\n }\n\n // first node is sentinel, second node is root element\n result = [];\n for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {\n element = this.__leavelist[i];\n addToPath(result, element.path);\n }\n addToPath(result, this.__current.path);\n return result;\n };\n\n // API:\n // return type of current node\n Controller.prototype.type = function () {\n var node = this.current();\n return node.type || this.__current.wrap;\n };\n\n // API:\n // return array of parent elements\n Controller.prototype.parents = function parents() {\n var i, iz, result;\n\n // first node is sentinel\n result = [];\n for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {\n result.push(this.__leavelist[i].node);\n }\n\n return result;\n };\n\n // API:\n // return current node\n Controller.prototype.current = function current() {\n return this.__current.node;\n };\n\n Controller.prototype.__execute = function __execute(callback, element) {\n var previous, result;\n\n result = undefined;\n\n previous = this.__current;\n this.__current = element;\n this.__state = null;\n if (callback) {\n result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);\n }\n this.__current = previous;\n\n return result;\n };\n\n // API:\n // notify control skip / break\n Controller.prototype.notify = function notify(flag) {\n this.__state = flag;\n };\n\n // API:\n // skip child nodes of current node\n Controller.prototype.skip = function () {\n this.notify(SKIP);\n };\n\n // API:\n // break traversals\n Controller.prototype['break'] = function () {\n this.notify(BREAK);\n };\n\n // API:\n // remove node\n Controller.prototype.remove = function () {\n this.notify(REMOVE);\n };\n\n Controller.prototype.__initialize = function(root, visitor) {\n this.visitor = visitor;\n this.root = root;\n this.__worklist = [];\n this.__leavelist = [];\n this.__current = null;\n this.__state = null;\n this.__fallback = null;\n if (visitor.fallback === 'iteration') {\n this.__fallback = Object.keys;\n } else if (typeof visitor.fallback === 'function') {\n this.__fallback = visitor.fallback;\n }\n\n this.__keys = VisitorKeys;\n if (visitor.keys) {\n this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);\n }\n };\n\n function isNode(node) {\n if (node == null) {\n return false;\n }\n return typeof node === 'object' && typeof node.type === 'string';\n }\n\n function isProperty(nodeType, key) {\n return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;\n }\n \n function candidateExistsInLeaveList(leavelist, candidate) {\n for (var i = leavelist.length - 1; i >= 0; --i) {\n if (leavelist[i].node === candidate) {\n return true;\n }\n }\n return false;\n }\n\n Controller.prototype.traverse = function traverse(root, visitor) {\n var worklist,\n leavelist,\n element,\n node,\n nodeType,\n ret,\n key,\n current,\n current2,\n candidates,\n candidate,\n sentinel;\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n worklist.push(new Element(root, null, null, null));\n leavelist.push(new Element(null, null, null, null));\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n ret = this.__execute(visitor.leave, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n continue;\n }\n\n if (element.node) {\n\n ret = this.__execute(visitor.enter, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || ret === SKIP) {\n continue;\n }\n\n node = element.node;\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n\n if (candidateExistsInLeaveList(leavelist, candidate[current2])) {\n continue;\n }\n\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', null);\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, null);\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n if (candidateExistsInLeaveList(leavelist, candidate)) {\n continue;\n }\n\n worklist.push(new Element(candidate, key, null, null));\n }\n }\n }\n }\n };\n\n Controller.prototype.replace = function replace(root, visitor) {\n var worklist,\n leavelist,\n node,\n nodeType,\n target,\n element,\n current,\n current2,\n candidates,\n candidate,\n sentinel,\n outer,\n key;\n\n function removeElem(element) {\n var i,\n key,\n nextElem,\n parent;\n\n if (element.ref.remove()) {\n // When the reference is an element of an array.\n key = element.ref.key;\n parent = element.ref.parent;\n\n // If removed from array, then decrease following items' keys.\n i = worklist.length;\n while (i--) {\n nextElem = worklist[i];\n if (nextElem.ref && nextElem.ref.parent === parent) {\n if (nextElem.ref.key < key) {\n break;\n }\n --nextElem.ref.key;\n }\n }\n }\n }\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n outer = {\n root: root\n };\n element = new Element(root, null, null, new Reference(outer, 'root'));\n worklist.push(element);\n leavelist.push(element);\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n target = this.__execute(visitor.leave, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n continue;\n }\n\n target = this.__execute(visitor.enter, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n element.node = target;\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n element.node = null;\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n\n // node may be null\n node = element.node;\n if (!node) {\n continue;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || target === SKIP) {\n continue;\n }\n\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n worklist.push(new Element(candidate, key, null, new Reference(node, key)));\n }\n }\n }\n\n return outer.root;\n };\n\n function traverse(root, visitor) {\n var controller = new Controller();\n return controller.traverse(root, visitor);\n }\n\n function replace(root, visitor) {\n var controller = new Controller();\n return controller.replace(root, visitor);\n }\n\n function extendCommentRange(comment, tokens) {\n var target;\n\n target = upperBound(tokens, function search(token) {\n return token.range[0] > comment.range[0];\n });\n\n comment.extendedRange = [comment.range[0], comment.range[1]];\n\n if (target !== tokens.length) {\n comment.extendedRange[1] = tokens[target].range[0];\n }\n\n target -= 1;\n if (target >= 0) {\n comment.extendedRange[0] = tokens[target].range[1];\n }\n\n return comment;\n }\n\n function attachComments(tree, providedComments, tokens) {\n // At first, we should calculate extended comment ranges.\n var comments = [], comment, len, i, cursor;\n\n if (!tree.range) {\n throw new Error('attachComments needs range information');\n }\n\n // tokens array is empty, we attach comments to tree as 'leadingComments'\n if (!tokens.length) {\n if (providedComments.length) {\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comment = deepCopy(providedComments[i]);\n comment.extendedRange = [0, tree.range[0]];\n comments.push(comment);\n }\n tree.leadingComments = comments;\n }\n return tree;\n }\n\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));\n }\n\n // This is based on John Freeman's implementation.\n cursor = 0;\n traverse(tree, {\n enter: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (comment.extendedRange[1] > node.range[0]) {\n break;\n }\n\n if (comment.extendedRange[1] === node.range[0]) {\n if (!node.leadingComments) {\n node.leadingComments = [];\n }\n node.leadingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n cursor = 0;\n traverse(tree, {\n leave: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (node.range[1] < comment.extendedRange[0]) {\n break;\n }\n\n if (node.range[1] === comment.extendedRange[0]) {\n if (!node.trailingComments) {\n node.trailingComments = [];\n }\n node.trailingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n return tree;\n }\n\n exports.Syntax = Syntax;\n exports.traverse = traverse;\n exports.replace = replace;\n exports.attachComments = attachComments;\n exports.VisitorKeys = VisitorKeys;\n exports.VisitorOption = VisitorOption;\n exports.Controller = Controller;\n exports.cloneEnvironment = function () { return clone({}); };\n\n return exports;\n}(exports));\n/* vim: set sw=4 ts=4 et tw=80 : */\n","/*\n * Generated by PEG.js 0.10.0.\n *\n * http://pegjs.org/\n */\n(function(root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define([], factory);\n } else if (typeof module === \"object\" && module.exports) {\n module.exports = factory();\n }\n})(this, function() {\n \"use strict\";\n\n function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }\n\n function peg$SyntaxError(message, expected, found, location) {\n this.message = message;\n this.expected = expected;\n this.found = found;\n this.location = location;\n this.name = \"SyntaxError\";\n\n if (typeof Error.captureStackTrace === \"function\") {\n Error.captureStackTrace(this, peg$SyntaxError);\n }\n }\n\n peg$subclass(peg$SyntaxError, Error);\n\n peg$SyntaxError.buildMessage = function(expected, found) {\n var DESCRIBE_EXPECTATION_FNS = {\n literal: function(expectation) {\n return \"\\\"\" + literalEscape(expectation.text) + \"\\\"\";\n },\n\n \"class\": function(expectation) {\n var escapedParts = \"\",\n i;\n\n for (i = 0; i < expectation.parts.length; i++) {\n escapedParts += expectation.parts[i] instanceof Array\n ? classEscape(expectation.parts[i][0]) + \"-\" + classEscape(expectation.parts[i][1])\n : classEscape(expectation.parts[i]);\n }\n\n return \"[\" + (expectation.inverted ? \"^\" : \"\") + escapedParts + \"]\";\n },\n\n any: function(expectation) {\n return \"any character\";\n },\n\n end: function(expectation) {\n return \"end of input\";\n },\n\n other: function(expectation) {\n return expectation.description;\n }\n };\n\n function hex(ch) {\n return ch.charCodeAt(0).toString(16).toUpperCase();\n }\n\n function literalEscape(s) {\n return s\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\0/g, '\\\\0')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/[\\x00-\\x0F]/g, function(ch) { return '\\\\x0' + hex(ch); })\n .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return '\\\\x' + hex(ch); });\n }\n\n function classEscape(s) {\n return s\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\]/g, '\\\\]')\n .replace(/\\^/g, '\\\\^')\n .replace(/-/g, '\\\\-')\n .replace(/\\0/g, '\\\\0')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/[\\x00-\\x0F]/g, function(ch) { return '\\\\x0' + hex(ch); })\n .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return '\\\\x' + hex(ch); });\n }\n\n function describeExpectation(expectation) {\n return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);\n }\n\n function describeExpected(expected) {\n var descriptions = new Array(expected.length),\n i, j;\n\n for (i = 0; i < expected.length; i++) {\n descriptions[i] = describeExpectation(expected[i]);\n }\n\n descriptions.sort();\n\n if (descriptions.length > 0) {\n for (i = 1, j = 1; i < descriptions.length; i++) {\n if (descriptions[i - 1] !== descriptions[i]) {\n descriptions[j] = descriptions[i];\n j++;\n }\n }\n descriptions.length = j;\n }\n\n switch (descriptions.length) {\n case 1:\n return descriptions[0];\n\n case 2:\n return descriptions[0] + \" or \" + descriptions[1];\n\n default:\n return descriptions.slice(0, -1).join(\", \")\n + \", or \"\n + descriptions[descriptions.length - 1];\n }\n }\n\n function describeFound(found) {\n return found ? \"\\\"\" + literalEscape(found) + \"\\\"\" : \"end of input\";\n }\n\n return \"Expected \" + describeExpected(expected) + \" but \" + describeFound(found) + \" found.\";\n };\n\n function peg$parse(input, options) {\n options = options !== void 0 ? options : {};\n\n var peg$FAILED = {},\n\n peg$startRuleFunctions = { start: peg$parsestart },\n peg$startRuleFunction = peg$parsestart,\n\n peg$c0 = function(ss) {\n return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss };\n },\n peg$c1 = function() { return void 0; },\n peg$c2 = \" \",\n peg$c3 = peg$literalExpectation(\" \", false),\n peg$c4 = /^[^ [\\],():#!=><~+.]/,\n peg$c5 = peg$classExpectation([\" \", \"[\", \"]\", \",\", \"(\", \")\", \":\", \"#\", \"!\", \"=\", \">\", \"<\", \"~\", \"+\", \".\"], true, false),\n peg$c6 = function(i) { return i.join(''); },\n peg$c7 = \">\",\n peg$c8 = peg$literalExpectation(\">\", false),\n peg$c9 = function() { return 'child'; },\n peg$c10 = \"~\",\n peg$c11 = peg$literalExpectation(\"~\", false),\n peg$c12 = function() { return 'sibling'; },\n peg$c13 = \"+\",\n peg$c14 = peg$literalExpectation(\"+\", false),\n peg$c15 = function() { return 'adjacent'; },\n peg$c16 = function() { return 'descendant'; },\n peg$c17 = \",\",\n peg$c18 = peg$literalExpectation(\",\", false),\n peg$c19 = function(s, ss) {\n return [s].concat(ss.map(function (s) { return s[3]; }));\n },\n peg$c20 = function(op, s) {\n if (!op) return s;\n return { type: op, left: { type: 'exactNode' }, right: s };\n },\n peg$c21 = function(a, ops) {\n return ops.reduce(function (memo, rhs) {\n return { type: rhs[0], left: memo, right: rhs[1] };\n }, a);\n },\n peg$c22 = \"!\",\n peg$c23 = peg$literalExpectation(\"!\", false),\n peg$c24 = function(subject, as) {\n const b = as.length === 1 ? as[0] : { type: 'compound', selectors: as };\n if(subject) b.subject = true;\n return b;\n },\n peg$c25 = \"*\",\n peg$c26 = peg$literalExpectation(\"*\", false),\n peg$c27 = function(a) { return { type: 'wildcard', value: a }; },\n peg$c28 = \"#\",\n peg$c29 = peg$literalExpectation(\"#\", false),\n peg$c30 = function(i) { return { type: 'identifier', value: i }; },\n peg$c31 = \"[\",\n peg$c32 = peg$literalExpectation(\"[\", false),\n peg$c33 = \"]\",\n peg$c34 = peg$literalExpectation(\"]\", false),\n peg$c35 = function(v) { return v; },\n peg$c36 = /^[>\", \"<\", \"!\"], false, false),\n peg$c38 = \"=\",\n peg$c39 = peg$literalExpectation(\"=\", false),\n peg$c40 = function(a) { return (a || '') + '='; },\n peg$c41 = /^[><]/,\n peg$c42 = peg$classExpectation([\">\", \"<\"], false, false),\n peg$c43 = \".\",\n peg$c44 = peg$literalExpectation(\".\", false),\n peg$c45 = function(a, as) {\n return [].concat.apply([a], as).join('');\n },\n peg$c46 = function(name, op, value) {\n return { type: 'attribute', name: name, operator: op, value: value };\n },\n peg$c47 = function(name) { return { type: 'attribute', name: name }; },\n peg$c48 = \"\\\"\",\n peg$c49 = peg$literalExpectation(\"\\\"\", false),\n peg$c50 = /^[^\\\\\"]/,\n peg$c51 = peg$classExpectation([\"\\\\\", \"\\\"\"], true, false),\n peg$c52 = \"\\\\\",\n peg$c53 = peg$literalExpectation(\"\\\\\", false),\n peg$c54 = peg$anyExpectation(),\n peg$c55 = function(a, b) { return a + b; },\n peg$c56 = function(d) {\n return { type: 'literal', value: strUnescape(d.join('')) };\n },\n peg$c57 = \"'\",\n peg$c58 = peg$literalExpectation(\"'\", false),\n peg$c59 = /^[^\\\\']/,\n peg$c60 = peg$classExpectation([\"\\\\\", \"'\"], true, false),\n peg$c61 = /^[0-9]/,\n peg$c62 = peg$classExpectation([[\"0\", \"9\"]], false, false),\n peg$c63 = function(a, b) {\n // Can use `a.flat().join('')` once supported\n const leadingDecimals = a ? [].concat.apply([], a).join('') : '';\n return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) };\n },\n peg$c64 = function(i) { return { type: 'literal', value: i }; },\n peg$c65 = \"type(\",\n peg$c66 = peg$literalExpectation(\"type(\", false),\n peg$c67 = /^[^ )]/,\n peg$c68 = peg$classExpectation([\" \", \")\"], true, false),\n peg$c69 = \")\",\n peg$c70 = peg$literalExpectation(\")\", false),\n peg$c71 = function(t) { return { type: 'type', value: t.join('') }; },\n peg$c72 = /^[imsu]/,\n peg$c73 = peg$classExpectation([\"i\", \"m\", \"s\", \"u\"], false, false),\n peg$c74 = \"/\",\n peg$c75 = peg$literalExpectation(\"/\", false),\n peg$c76 = /^[^\\/]/,\n peg$c77 = peg$classExpectation([\"/\"], true, false),\n peg$c78 = function(d, flgs) { return {\n type: 'regexp', value: new RegExp(d.join(''), flgs ? flgs.join('') : '') };\n },\n peg$c79 = function(i, is) {\n return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)};\n },\n peg$c80 = \":not(\",\n peg$c81 = peg$literalExpectation(\":not(\", false),\n peg$c82 = function(ss) { return { type: 'not', selectors: ss }; },\n peg$c83 = \":matches(\",\n peg$c84 = peg$literalExpectation(\":matches(\", false),\n peg$c85 = function(ss) { return { type: 'matches', selectors: ss }; },\n peg$c86 = \":has(\",\n peg$c87 = peg$literalExpectation(\":has(\", false),\n peg$c88 = function(ss) { return { type: 'has', selectors: ss }; },\n peg$c89 = \":first-child\",\n peg$c90 = peg$literalExpectation(\":first-child\", false),\n peg$c91 = function() { return nth(1); },\n peg$c92 = \":last-child\",\n peg$c93 = peg$literalExpectation(\":last-child\", false),\n peg$c94 = function() { return nthLast(1); },\n peg$c95 = \":nth-child(\",\n peg$c96 = peg$literalExpectation(\":nth-child(\", false),\n peg$c97 = function(n) { return nth(parseInt(n.join(''), 10)); },\n peg$c98 = \":nth-last-child(\",\n peg$c99 = peg$literalExpectation(\":nth-last-child(\", false),\n peg$c100 = function(n) { return nthLast(parseInt(n.join(''), 10)); },\n peg$c101 = \":\",\n peg$c102 = peg$literalExpectation(\":\", false),\n peg$c103 = function(c) {\n return { type: 'class', name: c };\n },\n\n peg$currPos = 0,\n peg$savedPos = 0,\n peg$posDetailsCache = [{ line: 1, column: 1 }],\n peg$maxFailPos = 0,\n peg$maxFailExpected = [],\n peg$silentFails = 0,\n\n peg$resultsCache = {},\n\n peg$result;\n\n if (\"startRule\" in options) {\n if (!(options.startRule in peg$startRuleFunctions)) {\n throw new Error(\"Can't start parsing from rule \\\"\" + options.startRule + \"\\\".\");\n }\n\n peg$startRuleFunction = peg$startRuleFunctions[options.startRule];\n }\n\n function text() {\n return input.substring(peg$savedPos, peg$currPos);\n }\n\n function location() {\n return peg$computeLocation(peg$savedPos, peg$currPos);\n }\n\n function expected(description, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildStructuredError(\n [peg$otherExpectation(description)],\n input.substring(peg$savedPos, peg$currPos),\n location\n );\n }\n\n function error(message, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildSimpleError(message, location);\n }\n\n function peg$literalExpectation(text, ignoreCase) {\n return { type: \"literal\", text: text, ignoreCase: ignoreCase };\n }\n\n function peg$classExpectation(parts, inverted, ignoreCase) {\n return { type: \"class\", parts: parts, inverted: inverted, ignoreCase: ignoreCase };\n }\n\n function peg$anyExpectation() {\n return { type: \"any\" };\n }\n\n function peg$endExpectation() {\n return { type: \"end\" };\n }\n\n function peg$otherExpectation(description) {\n return { type: \"other\", description: description };\n }\n\n function peg$computePosDetails(pos) {\n var details = peg$posDetailsCache[pos], p;\n\n if (details) {\n return details;\n } else {\n p = pos - 1;\n while (!peg$posDetailsCache[p]) {\n p--;\n }\n\n details = peg$posDetailsCache[p];\n details = {\n line: details.line,\n column: details.column\n };\n\n while (p < pos) {\n if (input.charCodeAt(p) === 10) {\n details.line++;\n details.column = 1;\n } else {\n details.column++;\n }\n\n p++;\n }\n\n peg$posDetailsCache[pos] = details;\n return details;\n }\n }\n\n function peg$computeLocation(startPos, endPos) {\n var startPosDetails = peg$computePosDetails(startPos),\n endPosDetails = peg$computePosDetails(endPos);\n\n return {\n start: {\n offset: startPos,\n line: startPosDetails.line,\n column: startPosDetails.column\n },\n end: {\n offset: endPos,\n line: endPosDetails.line,\n column: endPosDetails.column\n }\n };\n }\n\n function peg$fail(expected) {\n if (peg$currPos < peg$maxFailPos) { return; }\n\n if (peg$currPos > peg$maxFailPos) {\n peg$maxFailPos = peg$currPos;\n peg$maxFailExpected = [];\n }\n\n peg$maxFailExpected.push(expected);\n }\n\n function peg$buildSimpleError(message, location) {\n return new peg$SyntaxError(message, null, null, location);\n }\n\n function peg$buildStructuredError(expected, found, location) {\n return new peg$SyntaxError(\n peg$SyntaxError.buildMessage(expected, found),\n expected,\n found,\n location\n );\n }\n\n function peg$parsestart() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 0,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselectors();\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c0(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c1();\n }\n s0 = s1;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parse_() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 1,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifierName() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 2,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = [];\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n if (s2 !== peg$FAILED) {\n while (s2 !== peg$FAILED) {\n s1.push(s2);\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n }\n } else {\n s1 = peg$FAILED;\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c6(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsebinaryOp() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 3,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 62) {\n s2 = peg$c7;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c8); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c9();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 126) {\n s2 = peg$c10;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c11); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c12();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 43) {\n s2 = peg$c13;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c14); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c15();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c16();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 32 + 4,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsehasSelector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 32 + 5,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseselector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelector() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 6,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsebinaryOp();\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselector();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c20(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselector() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 7,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsesequence();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c21(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsesequence() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 8,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$parseatom();\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$parseatom();\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c24(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseatom() {\n var s0;\n\n var key = peg$currPos * 32 + 9,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$parsewildcard();\n if (s0 === peg$FAILED) {\n s0 = peg$parseidentifier();\n if (s0 === peg$FAILED) {\n s0 = peg$parseattr();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefield();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenegation();\n if (s0 === peg$FAILED) {\n s0 = peg$parsematches();\n if (s0 === peg$FAILED) {\n s0 = peg$parsehas();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefirstChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parselastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthLastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parseclass();\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsewildcard() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 10,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 42) {\n s1 = peg$c25;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c26); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c27(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifier() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 11,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 35) {\n s1 = peg$c28;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c29); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c30(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattr() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 12,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 91) {\n s1 = peg$c31;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c32); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrValue();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 93) {\n s5 = peg$c33;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c34); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c35(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 13,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (peg$c36.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c37); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n if (peg$c41.test(input.charAt(peg$currPos))) {\n s0 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s0 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c42); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrEqOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 14,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrName() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 15,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c45(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrValue() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 16,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrEqOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsetype();\n if (s5 === peg$FAILED) {\n s5 = peg$parseregex();\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsestring();\n if (s5 === peg$FAILED) {\n s5 = peg$parsenumber();\n if (s5 === peg$FAILED) {\n s5 = peg$parsepath();\n }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c47(s1);\n }\n s0 = s1;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsestring() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 17,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 34) {\n s1 = peg$c48;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 34) {\n s3 = peg$c48;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 39) {\n s1 = peg$c57;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 39) {\n s3 = peg$c57;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenumber() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 32 + 18,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$currPos;\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 46) {\n s3 = peg$c43;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s3 !== peg$FAILED) {\n s2 = [s2, s3];\n s1 = s2;\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c63(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsepath() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 19,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c64(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsetype() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 20,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c65) {\n s1 = peg$c65;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c66); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c71(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseflags() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 21,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n if (s1 !== peg$FAILED) {\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n }\n } else {\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseregex() {\n var s0, s1, s2, s3, s4;\n\n var key = peg$currPos * 32 + 22,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 47) {\n s1 = peg$c74;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c76.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c77); }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c76.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c77); }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 47) {\n s3 = peg$c74;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parseflags();\n if (s4 === peg$FAILED) {\n s4 = null;\n }\n if (s4 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c78(s2, s4);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefield() {\n var s0, s1, s2, s3, s4, s5, s6;\n\n var key = peg$currPos * 32 + 23,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s1 = peg$c43;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n s3 = [];\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c79(s2, s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenegation() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 24,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c80) {\n s1 = peg$c80;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c81); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c82(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsematches() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 25,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 9) === peg$c83) {\n s1 = peg$c83;\n peg$currPos += 9;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c84); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c85(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehas() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 26,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c86) {\n s1 = peg$c86;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c87); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parsehasSelectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c88(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefirstChild() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 27,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 12) === peg$c89) {\n s1 = peg$c89;\n peg$currPos += 12;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c90); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c91();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parselastChild() {\n var s0, s1;\n\n var key = peg$currPos * 32 + 28,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c92) {\n s1 = peg$c92;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c93); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c94();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 29,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c95) {\n s1 = peg$c95;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c96); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c97(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthLastChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 32 + 30,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 16) === peg$c98) {\n s1 = peg$c98;\n peg$currPos += 16;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c99); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c100(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseclass() {\n var s0, s1, s2;\n\n var key = peg$currPos * 32 + 31,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 58) {\n s1 = peg$c101;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c102); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c103(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n\n function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; }\n function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; }\n function strUnescape(s) {\n return s.replace(/\\\\(.)/g, function(match, ch) {\n switch(ch) {\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n case 'v': return '\\v';\n default: return ch;\n }\n });\n }\n\n\n peg$result = peg$startRuleFunction();\n\n if (peg$result !== peg$FAILED && peg$currPos === input.length) {\n return peg$result;\n } else {\n if (peg$result !== peg$FAILED && peg$currPos < input.length) {\n peg$fail(peg$endExpectation());\n }\n\n throw peg$buildStructuredError(\n peg$maxFailExpected,\n peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,\n peg$maxFailPos < input.length\n ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)\n : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)\n );\n }\n }\n\n return {\n SyntaxError: peg$SyntaxError,\n parse: peg$parse\n };\n});\n","/* vim: set sw=4 sts=4 : */\nimport estraverse from 'estraverse';\nimport parser from './parser.js';\n\n/**\n* @typedef {\"LEFT_SIDE\"|\"RIGHT_SIDE\"} Side\n*/\n\nconst LEFT_SIDE = 'LEFT_SIDE';\nconst RIGHT_SIDE = 'RIGHT_SIDE';\n\n/**\n * @external AST\n * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html\n */\n\n/**\n * One of the rules of `grammar.pegjs`\n * @typedef {PlainObject} SelectorAST\n * @see grammar.pegjs\n*/\n\n/**\n * The `sequence` production of `grammar.pegjs`\n * @typedef {PlainObject} SelectorSequenceAST\n*/\n\n/**\n * Get the value of a property which may be multiple levels down\n * in the object.\n * @param {?PlainObject} obj\n * @param {string[]} keys\n * @returns {undefined|boolean|string|number|external:AST}\n */\nfunction getPath(obj, keys) {\n for (let i = 0; i < keys.length; ++i) {\n if (obj == null) { return obj; }\n obj = obj[keys[i]];\n }\n return obj;\n}\n\n/**\n * Determine whether `node` can be reached by following `path`,\n * starting at `ancestor`.\n * @param {?external:AST} node\n * @param {?external:AST} ancestor\n * @param {string[]} path\n * @param {Integer} fromPathIndex\n * @returns {boolean}\n */\nfunction inPath(node, ancestor, path, fromPathIndex) {\n let current = ancestor;\n for (let i = fromPathIndex; i < path.length; ++i) {\n if (current == null) {\n return false;\n }\n const field = current[path[i]];\n if (Array.isArray(field)) {\n for (let k = 0; k < field.length; ++k) {\n if (inPath(node, field[k], path, i + 1)) {\n return true;\n }\n }\n return false;\n }\n current = field;\n }\n return node === current;\n}\n\n/**\n * A generated matcher function for a selector.\n * @callback SelectorMatcher\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @returns {void}\n*/\n\n/**\n * A WeakMap for holding cached matcher functions for selectors.\n * @type {WeakMap}\n*/\nconst MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap : null;\n\n/**\n * Look up a matcher function for `selector` in the cache.\n * If it does not exist, generate it with `generateMatcher` and add it to the cache.\n * In engines without WeakMap, the caching is skipped and matchers are generated with every call.\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction getMatcher(selector) {\n if (selector == null) {\n return () => true;\n }\n\n if (MATCHER_CACHE != null) {\n let matcher = MATCHER_CACHE.get(selector);\n if (matcher != null) {\n return matcher;\n }\n matcher = generateMatcher(selector);\n MATCHER_CACHE.set(selector, matcher);\n return matcher;\n }\n\n return generateMatcher(selector);\n}\n\n/**\n * Create a matcher function for `selector`,\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction generateMatcher(selector) {\n switch(selector.type) {\n case 'wildcard':\n return () => true;\n\n case 'identifier': {\n const value = selector.value.toLowerCase();\n return (node, ancestry, options) => {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return value === node[nodeTypeKey].toLowerCase();\n };\n }\n\n case 'exactNode':\n return (node, ancestry) => {\n return ancestry.length === 0;\n };\n\n case 'field': {\n const path = selector.name.split('.');\n return (node, ancestry) => {\n const ancestor = ancestry[path.length - 1];\n return inPath(node, ancestor, path, 0);\n };\n }\n\n case 'matches': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return true; }\n }\n return false;\n };\n }\n\n case 'compound': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (!matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'not': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'has': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n let result = false;\n\n const a = [];\n estraverse.traverse(node, {\n enter (node, parent) {\n if (parent != null) { a.unshift(parent); }\n\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, a, options)) {\n result = true;\n this.break();\n return;\n }\n }\n },\n leave () { a.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n\n return result;\n };\n }\n\n case 'child': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (ancestry.length > 0 && right(node, ancestry, options)) {\n return left(ancestry[0], ancestry.slice(1), options);\n }\n return false;\n };\n }\n\n case 'descendant': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (right(node, ancestry, options)) {\n for (let i = 0, l = ancestry.length; i < l; ++i) {\n if (left(ancestry[i], ancestry.slice(i + 1), options)) {\n return true;\n }\n }\n }\n return false;\n };\n }\n\n case 'attribute': {\n const path = selector.name.split('.');\n switch (selector.operator) {\n case void 0:\n return (node) => getPath(node, path) != null;\n case '=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => {\n const p = getPath(node, path);\n return typeof p === 'string' && selector.value.value.test(p);\n };\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal === `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value === typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '!=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => !selector.value.value.test(getPath(node, path));\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal !== `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value !== typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '<=':\n return (node) => getPath(node, path) <= selector.value.value;\n case '<':\n return (node) => getPath(node, path) < selector.value.value;\n case '>':\n return (node) => getPath(node, path) > selector.value.value;\n case '>=':\n return (node) => getPath(node, path) >= selector.value.value;\n }\n throw new Error(`Unknown operator: ${selector.operator}`);\n }\n\n case 'sibling': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n sibling(node, left, ancestry, LEFT_SIDE, options) ||\n selector.left.subject &&\n left(node, ancestry, options) &&\n sibling(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'adjacent': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n adjacent(node, left, ancestry, LEFT_SIDE, options) ||\n selector.right.subject &&\n left(node, ancestry, options) &&\n adjacent(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'nth-child': {\n const nth = selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'nth-last-child': {\n const nth = -selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'class': {\n \n const name = selector.name.toLowerCase();\n\n return (node, ancestry, options) => {\n \n if (options && options.matchClass) {\n return options.matchClass(selector.name, node, ancestry);\n }\n \n if (options && options.nodeTypeKey) return false; \n\n switch(name){\n case 'statement':\n if(node.type.slice(-9) === 'Statement') return true;\n // fallthrough: interface Declaration <: Statement { }\n case 'declaration':\n return node.type.slice(-11) === 'Declaration';\n case 'pattern':\n if(node.type.slice(-7) === 'Pattern') return true;\n // fallthrough: interface Expression <: Node, Pattern { }\n case 'expression':\n return node.type.slice(-10) === 'Expression' ||\n node.type.slice(-7) === 'Literal' ||\n (\n node.type === 'Identifier' &&\n (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty')\n ) ||\n node.type === 'MetaProperty';\n case 'function':\n return node.type === 'FunctionDeclaration' ||\n node.type === 'FunctionExpression' ||\n node.type === 'ArrowFunctionExpression';\n }\n throw new Error(`Unknown class name: ${selector.name}`);\n };\n }\n }\n\n throw new Error(`Unknown selector type: ${selector.type}`);\n}\n\n/**\n * @callback TraverseOptionFallback\n * @param {external:AST} node The given node.\n * @returns {string[]} An array of visitor keys for the given node.\n */\n\n/**\n * @callback ClassMatcher\n * @param {string} className The name of the class to match.\n * @param {external:AST} node The node to match against.\n * @param {Array} ancestry The ancestry of the node.\n * @returns {boolean} True if the node matches the class, false if not.\n */\n\n/**\n * @typedef {object} ESQueryOptions\n * @property {string} [nodeTypeKey=\"type\"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery.\n * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node.\n * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes.\n * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes.\n */\n\n/**\n * Given a `node` and its ancestors, determine if `node` is matched\n * by `selector`.\n * @param {?external:AST} node\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @throws {Error} Unknowns (operator, class name, selector type, or\n * selector value type)\n * @returns {boolean}\n */\nfunction matches(node, selector, ancestry, options) {\n if (!selector) { return true; }\n if (!node) { return false; }\n if (!ancestry) { ancestry = []; }\n\n return getMatcher(selector)(node, ancestry, options);\n}\n\n/**\n * Get visitor keys of a given node.\n * @param {external:AST} node The AST node to get keys.\n * @param {ESQueryOptions|undefined} options\n * @returns {string[]} Visitor keys of the node.\n */\nfunction getVisitorKeys(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n\n const nodeType = node[nodeTypeKey];\n if (options && options.visitorKeys && options.visitorKeys[nodeType]) {\n return options.visitorKeys[nodeType];\n }\n if (estraverse.VisitorKeys[nodeType]) {\n return estraverse.VisitorKeys[nodeType];\n }\n if (options && typeof options.fallback === 'function') {\n return options.fallback(node);\n }\n // 'iteration' fallback\n return Object.keys(node).filter(function (key) {\n return key !== nodeTypeKey;\n });\n}\n\n\n/**\n * Check whether the given value is an ASTNode or not.\n * @param {any} node The value to check.\n * @param {ESQueryOptions|undefined} options The options to use.\n * @returns {boolean} `true` if the value is an ASTNode.\n */\nfunction isNode(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return node !== null && typeof node === 'object' && typeof node[nodeTypeKey] === 'string';\n}\n\n/**\n * Determines if the given node has a sibling that matches the\n * given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction sibling(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const startIndex = listProp.indexOf(node);\n if (startIndex < 0) { continue; }\n let lowerBound, upperBound;\n if (side === LEFT_SIDE) {\n lowerBound = 0;\n upperBound = startIndex;\n } else {\n lowerBound = startIndex + 1;\n upperBound = listProp.length;\n }\n for (let k = lowerBound; k < upperBound; ++k) {\n if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node has an adjacent sibling that matches\n * the given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction adjacent(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const idx = listProp.indexOf(node);\n if (idx < 0) { continue; }\n if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) {\n return true;\n }\n if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node is the `nth` child.\n * If `nth` is negative then the position is counted\n * from the end of the list of children.\n * @param {external:AST} node\n * @param {external:AST[]} ancestry\n * @param {Integer} nth\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction nthChild(node, ancestry, nth, options) {\n if (nth === 0) { return false; }\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)){\n const idx = nth < 0 ? listProp.length + nth : nth - 1;\n if (idx >= 0 && idx < listProp.length && listProp[idx] === node) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * For each selector node marked as a subject, find the portion of the\n * selector that the subject must match.\n * @param {SelectorAST} selector\n * @param {SelectorAST} [ancestor] Defaults to `selector`\n * @returns {SelectorAST[]}\n */\nfunction subjects(selector, ancestor) {\n if (selector == null || typeof selector != 'object') { return []; }\n if (ancestor == null) { ancestor = selector; }\n const results = selector.subject ? [ancestor] : [];\n const keys = Object.keys(selector);\n for (let i = 0; i < keys.length; ++i) {\n const p = keys[i];\n const sel = selector[p];\n results.push(...subjects(sel, p === 'left' ? sel : ancestor));\n }\n return results;\n}\n\n/**\n* @callback TraverseVisitor\n* @param {?external:AST} node\n* @param {?external:AST} parent\n* @param {external:AST[]} ancestry\n*/\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {TraverseVisitor} visitor\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction traverse(ast, selector, visitor, options) {\n if (!selector) { return; }\n const ancestry = [];\n const matcher = getMatcher(selector);\n const altSubjects = subjects(selector).map(getMatcher);\n estraverse.traverse(ast, {\n enter (node, parent) {\n if (parent != null) { ancestry.unshift(parent); }\n if (matcher(node, ancestry, options)) {\n if (altSubjects.length) {\n for (let i = 0, l = altSubjects.length; i < l; ++i) {\n if (altSubjects[i](node, ancestry, options)) {\n visitor(node, parent, ancestry);\n }\n for (let k = 0, m = ancestry.length; k < m; ++k) {\n const succeedingAncestry = ancestry.slice(k + 1);\n if (altSubjects[i](ancestry[k], succeedingAncestry, options)) {\n visitor(ancestry[k], parent, succeedingAncestry);\n }\n }\n }\n } else {\n visitor(node, parent, ancestry);\n }\n }\n },\n leave () { ancestry.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n}\n\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction match(ast, selector, options) {\n const results = [];\n traverse(ast, selector, function (node) {\n results.push(node);\n }, options);\n return results;\n}\n\n/**\n * Parse a selector string and return its AST.\n * @param {string} selector\n * @returns {SelectorAST}\n */\nfunction parse(selector) {\n return parser.parse(selector);\n}\n\n/**\n * Query the code AST using the selector string.\n * @param {external:AST} ast\n * @param {string} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction query(ast, selector, options) {\n return match(ast, parse(selector), options);\n}\n\nquery.parse = parse;\nquery.match = match;\nquery.traverse = traverse;\nquery.matches = matches;\nquery.query = query;\n\nexport default query;\n"],"names":["clone","exports","Syntax","VisitorOption","VisitorKeys","BREAK","SKIP","REMOVE","deepCopy","obj","key","val","ret","hasOwnProperty","Reference","parent","this","Element","node","path","wrap","ref","Controller","isNode","type","isProperty","nodeType","ObjectExpression","ObjectPattern","candidateExistsInLeaveList","leavelist","candidate","i","length","traverse","root","visitor","extendCommentRange","comment","tokens","target","array","func","diff","len","current","upperBound","token","range","extendedRange","AssignmentExpression","AssignmentPattern","ArrayExpression","ArrayPattern","ArrowFunctionExpression","AwaitExpression","BlockStatement","BinaryExpression","BreakStatement","CallExpression","CatchClause","ChainExpression","ClassBody","ClassDeclaration","ClassExpression","ComprehensionBlock","ComprehensionExpression","ConditionalExpression","ContinueStatement","DebuggerStatement","DirectiveStatement","DoWhileStatement","EmptyStatement","ExportAllDeclaration","ExportDefaultDeclaration","ExportNamedDeclaration","ExportSpecifier","ExpressionStatement","ForStatement","ForInStatement","ForOfStatement","FunctionDeclaration","FunctionExpression","GeneratorExpression","Identifier","IfStatement","ImportExpression","ImportDeclaration","ImportDefaultSpecifier","ImportNamespaceSpecifier","ImportSpecifier","Literal","LabeledStatement","LogicalExpression","MemberExpression","MetaProperty","MethodDefinition","ModuleSpecifier","NewExpression","PrivateIdentifier","Program","Property","PropertyDefinition","RestElement","ReturnStatement","SequenceExpression","SpreadElement","Super","SwitchStatement","SwitchCase","TaggedTemplateExpression","TemplateElement","TemplateLiteral","ThisExpression","ThrowStatement","TryStatement","UnaryExpression","UpdateExpression","VariableDeclaration","VariableDeclarator","WhileStatement","WithStatement","YieldExpression","Break","Skip","Remove","prototype","replace","remove","Array","isArray","splice","iz","j","jz","result","addToPath","push","__current","__leavelist","parents","__execute","callback","element","previous","undefined","__state","call","notify","flag","skip","__initialize","__worklist","__fallback","fallback","Object","keys","__keys","assign","create","worklist","current2","candidates","sentinel","pop","enter","Error","leave","outer","removeElem","nextElem","attachComments","tree","providedComments","cursor","comments","leadingComments","trailingComments","cloneEnvironment","module","peg$SyntaxError","message","expected","found","location","name","captureStackTrace","child","ctor","constructor","peg$subclass","buildMessage","DESCRIBE_EXPECTATION_FNS","literal","expectation","literalEscape","text","class","escapedParts","parts","classEscape","inverted","any","end","other","description","hex","ch","charCodeAt","toString","toUpperCase","s","descriptions","sort","slice","join","describeExpected","describeFound","SyntaxError","parse","input","options","peg$result","peg$FAILED","peg$startRuleFunctions","start","peg$parsestart","peg$startRuleFunction","peg$c3","peg$literalExpectation","peg$c4","peg$c5","peg$classExpectation","peg$c8","peg$c11","peg$c14","peg$c18","peg$c19","ss","concat","map","peg$c23","peg$c26","peg$c29","peg$c32","peg$c34","peg$c36","peg$c37","peg$c39","peg$c40","a","peg$c41","peg$c42","peg$c44","peg$c46","op","value","operator","peg$c49","peg$c50","peg$c51","peg$c53","peg$c54","peg$c55","b","peg$c56","d","match","peg$c58","peg$c59","peg$c60","peg$c61","peg$c62","peg$c66","peg$c67","peg$c68","peg$c70","peg$c72","peg$c73","peg$c75","peg$c76","peg$c77","peg$c81","peg$c84","peg$c87","peg$c90","peg$c93","peg$c96","peg$c99","peg$c102","peg$currPos","peg$posDetailsCache","line","column","peg$maxFailPos","peg$maxFailExpected","peg$silentFails","startRule","ignoreCase","peg$computePosDetails","pos","p","details","peg$computeLocation","startPos","endPos","startPosDetails","endPosDetails","offset","peg$fail","s0","s1","s2","cached","peg$resultsCache","nextPos","peg$parse_","peg$parseselectors","selectors","peg$c1","peg$parseidentifierName","test","charAt","peg$parsebinaryOp","s3","s4","s5","s6","s7","peg$parseselector","peg$parsehasSelector","left","right","peg$parsesequence","reduce","memo","rhs","subject","as","peg$parseatom","peg$parsewildcard","peg$parseidentifier","peg$parseattrName","peg$parseattrEqOps","substr","peg$parsetype","flgs","peg$parseflags","RegExp","peg$parseregex","peg$parseattrOps","peg$parsestring","leadingDecimals","apply","parseFloat","peg$parsenumber","peg$parsepath","peg$parseattrValue","peg$parseattr","peg$parsefield","peg$parsenegation","peg$parsematches","peg$parsehasSelectors","peg$parsehas","nth","peg$parsefirstChild","nthLast","peg$parselastChild","parseInt","peg$parsenthChild","peg$parsenthLastChild","peg$parseclass","n","index","factory","getPath","MATCHER_CACHE","WeakMap","getMatcher","selector","matcher","get","generateMatcher","set","toLowerCase","ancestry","nodeTypeKey","split","inPath","ancestor","fromPathIndex","field","k","matchers","estraverse","unshift","shift","visitorKeys","l","sibling","adjacent","nthChild","matchClass","getVisitorKeys","filter","_typeof","side","listProp","startIndex","indexOf","lowerBound","idx","ast","altSubjects","subjects","results","sel","m","succeedingAncestry","parser","query","matches"],"mappings":"qgEA2BC,SAASA,EAAMC,GAGZ,IAAIC,EACAC,EACAC,EACAC,EACAC,EACAC,EAEJ,SAASC,EAASC,GACd,IAAcC,EAAKC,EAAfC,EAAM,GACV,IAAKF,KAAOD,EACJA,EAAII,eAAeH,KACnBC,EAAMF,EAAIC,GAENE,EAAIF,GADW,iBAARC,GAA4B,OAARA,EAChBH,EAASG,GAETA,GAIvB,OAAOC,EAgMX,SAASE,EAAUC,EAAQL,GACvBM,KAAKD,OAASA,EACdC,KAAKN,IAAMA,EAiBf,SAASO,EAAQC,EAAMC,EAAMC,EAAMC,GAC/BL,KAAKE,KAAOA,EACZF,KAAKG,KAAOA,EACZH,KAAKI,KAAOA,EACZJ,KAAKK,IAAMA,EAGf,SAASC,KAuHT,SAASC,EAAOL,GACZ,OAAY,MAARA,IAGmB,iBAATA,GAA0C,iBAAdA,EAAKM,MAGnD,SAASC,EAAWC,EAAUhB,GAC1B,OAAQgB,IAAaxB,EAAOyB,kBAAoBD,IAAaxB,EAAO0B,gBAAkB,eAAiBlB,EAG3G,SAASmB,EAA2BC,EAAWC,GAC3C,IAAK,IAA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O,GAAIzX,EAAQmZ,SAKzC9X,EAAQlB,EAAMH,EAAQkX,IAIlC1N,iBAAW0N,EAASW,SACpBhP,KAAMiE,GAAWA,EAAQgL,YACzBnP,SAAUmE,GAAWA,EAAQnE,UAAY,eAajD,SAASiH,EAAMiJ,EAAKjC,EAAU9J,GAC1B,IAAMkM,EAAU,GAIhB,OAHA7X,EAAS0X,EAAKjC,GAAU,SAAUzW,GAC9B6Y,EAAQtR,KAAKvH,KACd2M,GACIkM,EAQX,SAASpM,EAAMgK,GACX,OAAOwC,EAAOxM,MAAMgK,GAUxB,SAASyC,EAAMR,EAAKjC,EAAU9J,GAC1B,OAAO8C,EAAMiJ,EAAKjM,EAAMgK,GAAW9J,UAGvCuM,EAAMzM,MAAQA,EACdyM,EAAMzJ,MAAQA,EACdyJ,EAAMlY,SAAWA,EACjBkY,EAAMC,QAvPN,SAAiBnZ,EAAMyW,EAAUM,EAAUpK,GACvC,OAAK8J,KACAzW,IACA+W,IAAYA,EAAW,IAErBP,EAAWC,EAAXD,CAAqBxW,EAAM+W,EAAUpK,KAmPhDuM,EAAMA,MAAQA"} \ No newline at end of file diff --git a/node_modules/esquery/license.txt b/node_modules/esquery/license.txt new file mode 100644 index 00000000..52f915e2 --- /dev/null +++ b/node_modules/esquery/license.txt @@ -0,0 +1,24 @@ +Copyright (c) 2013, Joel Feenstra +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the ESQuery nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL JOEL FEENSTRA BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/esquery/package.json b/node_modules/esquery/package.json new file mode 100644 index 00000000..5e314b3a --- /dev/null +++ b/node_modules/esquery/package.json @@ -0,0 +1,78 @@ +{ + "name": "esquery", + "version": "1.6.0", + "author": "Joel Feenstra ", + "contributors": [], + "description": "A query library for ECMAScript AST using a CSS selector like query language.", + "main": "dist/esquery.min.js", + "module": "dist/esquery.esm.min.js", + "files": [ + "dist/*.js", + "dist/*.map", + "parser.js", + "license.txt", + "README.md" + ], + "nyc": { + "branches": 100, + "lines": 100, + "functions": 100, + "statements": 100, + "reporter": [ + "html", + "text" + ], + "exclude": [ + "parser.js", + "dist", + "tests" + ] + }, + "scripts": { + "prepublishOnly": "npm run build && npm test", + "build:parser": "rm parser.js && pegjs --cache --format umd -o \"parser.js\" \"grammar.pegjs\"", + "build:browser": "rollup -c", + "build": "npm run build:parser && npm run build:browser", + "mocha": "mocha --require chai/register-assert --require @babel/register tests", + "test": "nyc npm run mocha && npm run lint", + "test:ci": "npm run mocha", + "lint": "eslint ." + }, + "repository": { + "type": "git", + "url": "https://github.com/estools/esquery.git" + }, + "bugs": "https://github.com/estools/esquery/issues", + "homepage": "https://github.com/estools/esquery/", + "keywords": [ + "ast", + "ecmascript", + "javascript", + "query" + ], + "devDependencies": { + "@babel/core": "^7.9.0", + "@babel/preset-env": "^7.9.5", + "@babel/register": "^7.9.0", + "@rollup/plugin-commonjs": "^11.1.0", + "@rollup/plugin-json": "^4.0.2", + "@rollup/plugin-node-resolve": "^7.1.3", + "babel-plugin-transform-es2017-object-entries": "0.0.5", + "chai": "4.2.0", + "eslint": "^6.8.0", + "esprima": "~4.0.1", + "mocha": "7.1.1", + "nyc": "^15.0.1", + "pegjs": "~0.10.0", + "rollup": "^1.32.1", + "rollup-plugin-babel": "^4.4.0", + "rollup-plugin-terser": "^5.3.0" + }, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10" + }, + "dependencies": { + "estraverse": "^5.1.0" + } +} diff --git a/node_modules/esquery/parser.js b/node_modules/esquery/parser.js new file mode 100644 index 00000000..eac0a009 --- /dev/null +++ b/node_modules/esquery/parser.js @@ -0,0 +1,2694 @@ +/* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ +(function(root, factory) { + if (typeof define === "function" && define.amd) { + define([], factory); + } else if (typeof module === "object" && module.exports) { + module.exports = factory(); + } +})(this, function() { + "use strict"; + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + + peg$subclass(peg$SyntaxError, Error); + + peg$SyntaxError.buildMessage = function(expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + + "class": function(expectation) { + var escapedParts = "", + i; + + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array + ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) + : classEscape(expectation.parts[i]); + } + + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + + any: function(expectation) { + return "any character"; + }, + + end: function(expectation) { + return "end of input"; + }, + + other: function(expectation) { + return expectation.description; + } + }; + + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + + function literalEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function classEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/\]/g, '\\]') + .replace(/\^/g, '\\^') + .replace(/-/g, '\\-') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, j; + + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + + descriptions.sort(); + + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + + switch (descriptions.length) { + case 1: + return descriptions[0]; + + case 2: + return descriptions[0] + " or " + descriptions[1]; + + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; + } + } + + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + + var peg$FAILED = {}, + + peg$startRuleFunctions = { start: peg$parsestart }, + peg$startRuleFunction = peg$parsestart, + + peg$c0 = function(ss) { + return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss }; + }, + peg$c1 = function() { return void 0; }, + peg$c2 = " ", + peg$c3 = peg$literalExpectation(" ", false), + peg$c4 = /^[^ [\],():#!=><~+.]/, + peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), + peg$c6 = function(i) { return i.join(''); }, + peg$c7 = ">", + peg$c8 = peg$literalExpectation(">", false), + peg$c9 = function() { return 'child'; }, + peg$c10 = "~", + peg$c11 = peg$literalExpectation("~", false), + peg$c12 = function() { return 'sibling'; }, + peg$c13 = "+", + peg$c14 = peg$literalExpectation("+", false), + peg$c15 = function() { return 'adjacent'; }, + peg$c16 = function() { return 'descendant'; }, + peg$c17 = ",", + peg$c18 = peg$literalExpectation(",", false), + peg$c19 = function(s, ss) { + return [s].concat(ss.map(function (s) { return s[3]; })); + }, + peg$c20 = function(op, s) { + if (!op) return s; + return { type: op, left: { type: 'exactNode' }, right: s }; + }, + peg$c21 = function(a, ops) { + return ops.reduce(function (memo, rhs) { + return { type: rhs[0], left: memo, right: rhs[1] }; + }, a); + }, + peg$c22 = "!", + peg$c23 = peg$literalExpectation("!", false), + peg$c24 = function(subject, as) { + const b = as.length === 1 ? as[0] : { type: 'compound', selectors: as }; + if(subject) b.subject = true; + return b; + }, + peg$c25 = "*", + peg$c26 = peg$literalExpectation("*", false), + peg$c27 = function(a) { return { type: 'wildcard', value: a }; }, + peg$c28 = "#", + peg$c29 = peg$literalExpectation("#", false), + peg$c30 = function(i) { return { type: 'identifier', value: i }; }, + peg$c31 = "[", + peg$c32 = peg$literalExpectation("[", false), + peg$c33 = "]", + peg$c34 = peg$literalExpectation("]", false), + peg$c35 = function(v) { return v; }, + peg$c36 = /^[>", "<", "!"], false, false), + peg$c38 = "=", + peg$c39 = peg$literalExpectation("=", false), + peg$c40 = function(a) { return (a || '') + '='; }, + peg$c41 = /^[><]/, + peg$c42 = peg$classExpectation([">", "<"], false, false), + peg$c43 = ".", + peg$c44 = peg$literalExpectation(".", false), + peg$c45 = function(a, as) { + return [].concat.apply([a], as).join(''); + }, + peg$c46 = function(name, op, value) { + return { type: 'attribute', name: name, operator: op, value: value }; + }, + peg$c47 = function(name) { return { type: 'attribute', name: name }; }, + peg$c48 = "\"", + peg$c49 = peg$literalExpectation("\"", false), + peg$c50 = /^[^\\"]/, + peg$c51 = peg$classExpectation(["\\", "\""], true, false), + peg$c52 = "\\", + peg$c53 = peg$literalExpectation("\\", false), + peg$c54 = peg$anyExpectation(), + peg$c55 = function(a, b) { return a + b; }, + peg$c56 = function(d) { + return { type: 'literal', value: strUnescape(d.join('')) }; + }, + peg$c57 = "'", + peg$c58 = peg$literalExpectation("'", false), + peg$c59 = /^[^\\']/, + peg$c60 = peg$classExpectation(["\\", "'"], true, false), + peg$c61 = /^[0-9]/, + peg$c62 = peg$classExpectation([["0", "9"]], false, false), + peg$c63 = function(a, b) { + // Can use `a.flat().join('')` once supported + const leadingDecimals = a ? [].concat.apply([], a).join('') : ''; + return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) }; + }, + peg$c64 = function(i) { return { type: 'literal', value: i }; }, + peg$c65 = "type(", + peg$c66 = peg$literalExpectation("type(", false), + peg$c67 = /^[^ )]/, + peg$c68 = peg$classExpectation([" ", ")"], true, false), + peg$c69 = ")", + peg$c70 = peg$literalExpectation(")", false), + peg$c71 = function(t) { return { type: 'type', value: t.join('') }; }, + peg$c72 = /^[imsu]/, + peg$c73 = peg$classExpectation(["i", "m", "s", "u"], false, false), + peg$c74 = "/", + peg$c75 = peg$literalExpectation("/", false), + peg$c76 = /^[^\/]/, + peg$c77 = peg$classExpectation(["/"], true, false), + peg$c78 = function(d, flgs) { return { + type: 'regexp', value: new RegExp(d.join(''), flgs ? flgs.join('') : '') }; + }, + peg$c79 = function(i, is) { + return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)}; + }, + peg$c80 = ":not(", + peg$c81 = peg$literalExpectation(":not(", false), + peg$c82 = function(ss) { return { type: 'not', selectors: ss }; }, + peg$c83 = ":matches(", + peg$c84 = peg$literalExpectation(":matches(", false), + peg$c85 = function(ss) { return { type: 'matches', selectors: ss }; }, + peg$c86 = ":has(", + peg$c87 = peg$literalExpectation(":has(", false), + peg$c88 = function(ss) { return { type: 'has', selectors: ss }; }, + peg$c89 = ":first-child", + peg$c90 = peg$literalExpectation(":first-child", false), + peg$c91 = function() { return nth(1); }, + peg$c92 = ":last-child", + peg$c93 = peg$literalExpectation(":last-child", false), + peg$c94 = function() { return nthLast(1); }, + peg$c95 = ":nth-child(", + peg$c96 = peg$literalExpectation(":nth-child(", false), + peg$c97 = function(n) { return nth(parseInt(n.join(''), 10)); }, + peg$c98 = ":nth-last-child(", + peg$c99 = peg$literalExpectation(":nth-last-child(", false), + peg$c100 = function(n) { return nthLast(parseInt(n.join(''), 10)); }, + peg$c101 = ":", + peg$c102 = peg$literalExpectation(":", false), + peg$c103 = function(c) { + return { type: 'class', name: c }; + }, + + peg$currPos = 0, + peg$savedPos = 0, + peg$posDetailsCache = [{ line: 1, column: 1 }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$resultsCache = {}, + + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + + function location() { + return peg$computeLocation(peg$savedPos, peg$currPos); + } + + function expected(description, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) + + throw peg$buildStructuredError( + [peg$otherExpectation(description)], + input.substring(peg$savedPos, peg$currPos), + location + ); + } + + function error(message, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) + + throw peg$buildSimpleError(message, location); + } + + function peg$literalExpectation(text, ignoreCase) { + return { type: "literal", text: text, ignoreCase: ignoreCase }; + } + + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + + function peg$anyExpectation() { + return { type: "any" }; + } + + function peg$endExpectation() { + return { type: "end" }; + } + + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], p; + + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + + p++; + } + + peg$posDetailsCache[pos] = details; + return details; + } + } + + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildSimpleError(message, location) { + return new peg$SyntaxError(message, null, null, location); + } + + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError( + peg$SyntaxError.buildMessage(expected, found), + expected, + found, + location + ); + } + + function peg$parsestart() { + var s0, s1, s2, s3; + + var key = peg$currPos * 32 + 0, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$parseselectors(); + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c0(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c1(); + } + s0 = s1; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parse_() { + var s0, s1; + + var key = peg$currPos * 32 + 1, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = []; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c3); } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c3); } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseidentifierName() { + var s0, s1, s2; + + var key = peg$currPos * 32 + 2, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c5); } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c5); } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c6(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsebinaryOp() { + var s0, s1, s2, s3; + + var key = peg$currPos * 32 + 3, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c9(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c10; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c11); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c12(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c13; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c14); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c15(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c3); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c16(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsehasSelectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 32 + 4, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsehasSelector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseselectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 32 + 5, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseselector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsehasSelector() { + var s0, s1, s2; + + var key = peg$currPos * 32 + 6, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsebinaryOp(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseselector(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c20(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseselector() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 7, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsesequence(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c21(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesequence() { + var s0, s1, s2, s3; + + var key = peg$currPos * 32 + 8, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c23); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseatom(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseatom(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c24(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseatom() { + var s0; + + var key = peg$currPos * 32 + 9, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$parsewildcard(); + if (s0 === peg$FAILED) { + s0 = peg$parseidentifier(); + if (s0 === peg$FAILED) { + s0 = peg$parseattr(); + if (s0 === peg$FAILED) { + s0 = peg$parsefield(); + if (s0 === peg$FAILED) { + s0 = peg$parsenegation(); + if (s0 === peg$FAILED) { + s0 = peg$parsematches(); + if (s0 === peg$FAILED) { + s0 = peg$parsehas(); + if (s0 === peg$FAILED) { + s0 = peg$parsefirstChild(); + if (s0 === peg$FAILED) { + s0 = peg$parselastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthLastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parseclass(); + } + } + } + } + } + } + } + } + } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsewildcard() { + var s0, s1; + + var key = peg$currPos * 32 + 10, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c25; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c26); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c27(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseidentifier() { + var s0, s1, s2; + + var key = peg$currPos * 32 + 11, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c28; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c29); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c30(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattr() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 12, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrValue(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c33; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c34); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c35(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrOps() { + var s0, s1, s2; + + var key = peg$currPos * 32 + 13, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (peg$c36.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (peg$c41.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c42); } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrEqOps() { + var s0, s1, s2; + + var key = peg$currPos * 32 + 14, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c23); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrName() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 15, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c45(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrValue() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 16, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrEqOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetype(); + if (s5 === peg$FAILED) { + s5 = peg$parseregex(); + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsestring(); + if (s5 === peg$FAILED) { + s5 = peg$parsenumber(); + if (s5 === peg$FAILED) { + s5 = peg$parsepath(); + } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c47(s1); + } + s0 = s1; + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 17, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c48; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c49); } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c48; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c49); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c57; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c58); } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c57; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c58); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenumber() { + var s0, s1, s2, s3; + + var key = peg$currPos * 32 + 18, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c43; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c63(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsepath() { + var s0, s1; + + var key = peg$currPos * 32 + 19, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c64(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetype() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 20, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c65) { + s1 = peg$c65; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c66); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c71(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseflags() { + var s0, s1; + + var key = peg$currPos * 32 + 21, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = []; + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + } + } else { + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseregex() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 32 + 22, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c74; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c75); } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c76.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c77); } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c76.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c77); } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s3 = peg$c74; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c75); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseflags(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c78(s2, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefield() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 32 + 23, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c43; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c79(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenegation() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 24, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c80) { + s1 = peg$c80; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c81); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c82(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsematches() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 25, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c83) { + s1 = peg$c83; + peg$currPos += 9; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c85(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsehas() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 26, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c86) { + s1 = peg$c86; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c87); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehasSelectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c88(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefirstChild() { + var s0, s1; + + var key = peg$currPos * 32 + 27, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 12) === peg$c89) { + s1 = peg$c89; + peg$currPos += 12; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c90); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c91(); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parselastChild() { + var s0, s1; + + var key = peg$currPos * 32 + 28, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c92) { + s1 = peg$c92; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c94(); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenthChild() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 29, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c95) { + s1 = peg$c95; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c96); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c97(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenthLastChild() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 32 + 30, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 16) === peg$c98) { + s1 = peg$c98; + peg$currPos += 16; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c99); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c100(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseclass() { + var s0, s1, s2; + + var key = peg$currPos * 32 + 31, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c101; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c102); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c103(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + + function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; } + function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; } + function strUnescape(s) { + return s.replace(/\\(.)/g, function(match, ch) { + switch(ch) { + case 'b': return '\b'; + case 'f': return '\f'; + case 'n': return '\n'; + case 'r': return '\r'; + case 't': return '\t'; + case 'v': return '\v'; + default: return ch; + } + }); + } + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + + throw peg$buildStructuredError( + peg$maxFailExpected, + peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, + peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) + ); + } + } + + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; +}); diff --git a/node_modules/esrecurse/.babelrc b/node_modules/esrecurse/.babelrc new file mode 100644 index 00000000..a0765e18 --- /dev/null +++ b/node_modules/esrecurse/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["es2015"] +} diff --git a/node_modules/esrecurse/README.md b/node_modules/esrecurse/README.md new file mode 100644 index 00000000..ffea6b43 --- /dev/null +++ b/node_modules/esrecurse/README.md @@ -0,0 +1,171 @@ +### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse) + +Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is +[ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm) +recursive traversing functionality. + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +esrecurse.visit(ast, { + XXXStatement: function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); + } +}); +``` + +We can use `Visitor` instance. + +```javascript +var visitor = new esrecurse.Visitor({ + XXXStatement: function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); + } +}); + +visitor.visit(ast); +``` + +We can inherit `Visitor` instance easily. + +```javascript +class Derived extends esrecurse.Visitor { + constructor() + { + super(null); + } + + XXXStatement(node) { + } +} +``` + +```javascript +function DerivedVisitor() { + esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); +} +util.inherits(DerivedVisitor, esrecurse.Visitor); +DerivedVisitor.prototype.XXXStatement = function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); +}; +``` + +And you can invoke default visiting operation inside custom visit operation. + +```javascript +function DerivedVisitor() { + esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); +} +util.inherits(DerivedVisitor, esrecurse.Visitor); +DerivedVisitor.prototype.XXXStatement = function (node) { + // do something... + this.visitChildren(node); +}; +``` + +The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`. +We can use user-defined node types. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +esrecurse.visit( + ast, + { + Literal: function (node) { + // do something... + } + }, + { + // Extending the existing traversing rules. + childVisitorKeys: { + // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] + TestExpression: ['argument'] + } + } +); +``` + +We can use the `fallback` option as well. +If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes. +Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). + +```javascript +esrecurse.visit( + ast, + { + Literal: function (node) { + // do something... + } + }, + { + fallback: 'iteration' + } +); +``` + +If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes. +Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). + +```javascript +esrecurse.visit( + ast, + { + Literal: function (node) { + // do something... + } + }, + { + fallback: function (node) { + return Object.keys(node).filter(function(key) { + return key !== 'argument' + }); + } + } +); +``` + +### License + +Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation) + (twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/esrecurse/esrecurse.js b/node_modules/esrecurse/esrecurse.js new file mode 100644 index 00000000..15d57dfd --- /dev/null +++ b/node_modules/esrecurse/esrecurse.js @@ -0,0 +1,117 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +(function () { + 'use strict'; + + var estraverse = require('estraverse'); + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties'; + } + + function Visitor(visitor, options) { + options = options || {}; + + this.__visitor = visitor || this; + this.__childVisitorKeys = options.childVisitorKeys + ? Object.assign({}, estraverse.VisitorKeys, options.childVisitorKeys) + : estraverse.VisitorKeys; + if (options.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof options.fallback === 'function') { + this.__fallback = options.fallback; + } + } + + /* Default method for visiting children. + * When you need to call default visiting operation inside custom visiting + * operation, you can use it with `this.visitChildren(node)`. + */ + Visitor.prototype.visitChildren = function (node) { + var type, children, i, iz, j, jz, child; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + + children = this.__childVisitorKeys[type]; + if (!children) { + if (this.__fallback) { + children = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + type + '.'); + } + } + + for (i = 0, iz = children.length; i < iz; ++i) { + child = node[children[i]]; + if (child) { + if (Array.isArray(child)) { + for (j = 0, jz = child.length; j < jz; ++j) { + if (child[j]) { + if (isNode(child[j]) || isProperty(type, children[i])) { + this.visit(child[j]); + } + } + } + } else if (isNode(child)) { + this.visit(child); + } + } + } + }; + + /* Dispatching node. */ + Visitor.prototype.visit = function (node) { + var type; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + if (this.__visitor[type]) { + this.__visitor[type].call(this, node); + return; + } + this.visitChildren(node); + }; + + exports.version = require('./package.json').version; + exports.Visitor = Visitor; + exports.visit = function (node, visitor, options) { + var v = new Visitor(visitor, options); + v.visit(node); + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esrecurse/gulpfile.babel.js b/node_modules/esrecurse/gulpfile.babel.js new file mode 100644 index 00000000..aa881c9c --- /dev/null +++ b/node_modules/esrecurse/gulpfile.babel.js @@ -0,0 +1,92 @@ +// Copyright (C) 2014 Yusuke Suzuki +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import gulp from 'gulp'; +import mocha from 'gulp-mocha'; +import eslint from 'gulp-eslint'; +import minimist from 'minimist'; +import git from 'gulp-git'; +import bump from 'gulp-bump'; +import filter from 'gulp-filter'; +import tagVersion from 'gulp-tag-version'; +import 'babel-register'; + +const SOURCE = [ + '*.js' +]; + +let ESLINT_OPTION = { + parser: 'babel-eslint', + parserOptions: { + 'sourceType': 'module' + }, + rules: { + 'quotes': 0, + 'eqeqeq': 0, + 'no-use-before-define': 0, + 'no-shadow': 0, + 'no-new': 0, + 'no-underscore-dangle': 0, + 'no-multi-spaces': 0, + 'no-native-reassign': 0, + 'no-loop-func': 0 + }, + env: { + 'node': true + } +}; + +gulp.task('test', function() { + let options = minimist(process.argv.slice(2), { + string: 'test', + default: { + test: 'test/*.js' + } + } + ); + return gulp.src(options.test).pipe(mocha({reporter: 'spec'})); +}); + +gulp.task('lint', () => + gulp.src(SOURCE) + .pipe(eslint(ESLINT_OPTION)) + .pipe(eslint.formatEach('stylish', process.stderr)) + .pipe(eslint.failOnError()) +); + +let inc = importance => + gulp.src(['./package.json']) + .pipe(bump({type: importance})) + .pipe(gulp.dest('./')) + .pipe(git.commit('Bumps package version')) + .pipe(filter('package.json')) + .pipe(tagVersion({ + prefix: '' + })) +; + +gulp.task('travis', [ 'lint', 'test' ]); +gulp.task('default', [ 'travis' ]); + +gulp.task('patch', [ ], () => inc('patch')); +gulp.task('minor', [ ], () => inc('minor')); +gulp.task('major', [ ], () => inc('major')); diff --git a/node_modules/esrecurse/package.json b/node_modules/esrecurse/package.json new file mode 100755 index 00000000..dec5b1bc --- /dev/null +++ b/node_modules/esrecurse/package.json @@ -0,0 +1,52 @@ +{ + "name": "esrecurse", + "description": "ECMAScript AST recursive visitor", + "homepage": "https://github.com/estools/esrecurse", + "main": "esrecurse.js", + "version": "4.3.0", + "engines": { + "node": ">=4.0" + }, + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "https://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/estools/esrecurse.git" + }, + "dependencies": { + "estraverse": "^5.2.0" + }, + "devDependencies": { + "babel-cli": "^6.24.1", + "babel-eslint": "^7.2.3", + "babel-preset-es2015": "^6.24.1", + "babel-register": "^6.24.1", + "chai": "^4.0.2", + "esprima": "^4.0.0", + "gulp": "^3.9.0", + "gulp-bump": "^2.7.0", + "gulp-eslint": "^4.0.0", + "gulp-filter": "^5.0.0", + "gulp-git": "^2.4.1", + "gulp-mocha": "^4.3.1", + "gulp-tag-version": "^1.2.1", + "jsdoc": "^3.3.0-alpha10", + "minimist": "^1.1.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "gulp travis", + "unit-test": "gulp test", + "lint": "gulp lint" + }, + "babel": { + "presets": [ + "es2015" + ] + } +} diff --git a/node_modules/estraverse/.jshintrc b/node_modules/estraverse/.jshintrc new file mode 100644 index 00000000..f642dae7 --- /dev/null +++ b/node_modules/estraverse/.jshintrc @@ -0,0 +1,16 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "eqnull": true, + "latedef": true, + "noarg": true, + "noempty": true, + "quotmark": "single", + "undef": true, + "unused": true, + "strict": true, + "trailing": true, + + "node": true +} diff --git a/node_modules/estraverse/LICENSE.BSD b/node_modules/estraverse/LICENSE.BSD new file mode 100644 index 00000000..3e580c35 --- /dev/null +++ b/node_modules/estraverse/LICENSE.BSD @@ -0,0 +1,19 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/estraverse/README.md b/node_modules/estraverse/README.md new file mode 100644 index 00000000..ccd3377f --- /dev/null +++ b/node_modules/estraverse/README.md @@ -0,0 +1,153 @@ +### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) + +Estraverse ([estraverse](http://github.com/estools/estraverse)) is +[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +traversal functions from [esmangle project](http://github.com/estools/esmangle). + +### Documentation + +You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +estraverse.traverse(ast, { + enter: function (node, parent) { + if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') + return estraverse.VisitorOption.Skip; + }, + leave: function (node, parent) { + if (node.type == 'VariableDeclarator') + console.log(node.id.name); + } +}); +``` + +We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. + +```javascript +estraverse.traverse(ast, { + enter: function (node) { + this.break(); + } +}); +``` + +And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. + +```javascript +result = estraverse.replace(tree, { + enter: function (node) { + // Replace it with replaced. + if (node.type === 'Literal') + return replaced; + } +}); +``` + +By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Extending the existing traversing rules. + keys: { + // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] + TestExpression: ['argument'] + } +}); +``` + +By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Iterating the child **nodes** of unknown nodes. + fallback: 'iteration' +}); +``` + +When `visitor.fallback` is a function, we can determine which keys to visit on each node. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Skip the `argument` property of each node + fallback: function(node) { + return Object.keys(node).filter(function(key) { + return key !== 'argument'; + }); + } +}); +``` + +### License + +Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/estraverse/estraverse.js b/node_modules/estraverse/estraverse.js new file mode 100644 index 00000000..f0d9af9b --- /dev/null +++ b/node_modules/estraverse/estraverse.js @@ -0,0 +1,805 @@ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; + + var Syntax, + VisitorOption, + VisitorKeys, + BREAK, + SKIP, + REMOVE; + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ChainExpression: 'ChainExpression', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + PrivateIdentifier: 'PrivateIdentifier', + Program: 'Program', + Property: 'Property', + PropertyDefinition: 'PropertyDefinition', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ChainExpression: ['expression'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + PrivateIdentifier: [], + Program: ['body'], + Property: ['key', 'value'], + PropertyDefinition: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } + + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + + function candidateExistsInLeaveList(leavelist, candidate) { + for (var i = leavelist.length - 1; i >= 0; --i) { + if (leavelist[i].node === candidate) { + return true; + } + } + return false; + } + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + + if (candidateExistsInLeaveList(leavelist, candidate[current2])) { + continue; + } + + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + if (candidateExistsInLeaveList(leavelist, candidate)) { + continue; + } + + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + function removeElem(element) { + var i, + key, + nextElem, + parent; + + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; + + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/estraverse/gulpfile.js b/node_modules/estraverse/gulpfile.js new file mode 100644 index 00000000..8772bbcc --- /dev/null +++ b/node_modules/estraverse/gulpfile.js @@ -0,0 +1,70 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +'use strict'; + +var gulp = require('gulp'), + git = require('gulp-git'), + bump = require('gulp-bump'), + filter = require('gulp-filter'), + tagVersion = require('gulp-tag-version'); + +var TEST = [ 'test/*.js' ]; +var POWERED = [ 'powered-test/*.js' ]; +var SOURCE = [ 'src/**/*.js' ]; + +/** + * Bumping version number and tagging the repository with it. + * Please read http://semver.org/ + * + * You can use the commands + * + * gulp patch # makes v0.1.0 -> v0.1.1 + * gulp feature # makes v0.1.1 -> v0.2.0 + * gulp release # makes v0.2.1 -> v1.0.0 + * + * To bump the version numbers accordingly after you did a patch, + * introduced a feature or made a backwards-incompatible release. + */ + +function inc(importance) { + // get all the files to bump version in + return gulp.src(['./package.json']) + // bump the version number in those files + .pipe(bump({type: importance})) + // save it back to filesystem + .pipe(gulp.dest('./')) + // commit the changed version number + .pipe(git.commit('Bumps package version')) + // read only one file to get the version number + .pipe(filter('package.json')) + // **tag it in the repository** + .pipe(tagVersion({ + prefix: '' + })); +} + +gulp.task('patch', [ ], function () { return inc('patch'); }) +gulp.task('minor', [ ], function () { return inc('minor'); }) +gulp.task('major', [ ], function () { return inc('major'); }) diff --git a/node_modules/estraverse/package.json b/node_modules/estraverse/package.json new file mode 100644 index 00000000..a8632185 --- /dev/null +++ b/node_modules/estraverse/package.json @@ -0,0 +1,40 @@ +{ + "name": "estraverse", + "description": "ECMAScript JS AST traversal functions", + "homepage": "https://github.com/estools/estraverse", + "main": "estraverse.js", + "version": "5.3.0", + "engines": { + "node": ">=4.0" + }, + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "http://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/estools/estraverse.git" + }, + "devDependencies": { + "babel-preset-env": "^1.6.1", + "babel-register": "^6.3.13", + "chai": "^2.1.1", + "espree": "^1.11.0", + "gulp": "^3.8.10", + "gulp-bump": "^0.2.2", + "gulp-filter": "^2.0.0", + "gulp-git": "^1.0.1", + "gulp-tag-version": "^1.3.0", + "jshint": "^2.5.6", + "mocha": "^2.1.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint estraverse.js", + "unit-test": "mocha --compilers js:babel-register" + } +} diff --git a/node_modules/esutils/LICENSE.BSD b/node_modules/esutils/LICENSE.BSD new file mode 100644 index 00000000..3e580c35 --- /dev/null +++ b/node_modules/esutils/LICENSE.BSD @@ -0,0 +1,19 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/esutils/README.md b/node_modules/esutils/README.md new file mode 100644 index 00000000..517526cf --- /dev/null +++ b/node_modules/esutils/README.md @@ -0,0 +1,174 @@ +### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) +esutils ([esutils](http://github.com/estools/esutils)) is +utility box for ECMAScript language tools. + +### API + +### ast + +#### ast.isExpression(node) + +Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section +[11](https://es5.github.io/#x11). + +#### ast.isStatement(node) + +Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section +[12](https://es5.github.io/#x12). + +#### ast.isIterationStatement(node) + +Returns true if `node` is an IterationStatement as defined in ECMA262 edition +5.1 section [12.6](https://es5.github.io/#x12.6). + +#### ast.isSourceElement(node) + +Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 +section [14](https://es5.github.io/#x14). + +#### ast.trailingStatement(node) + +Returns `Statement?` if `node` has trailing `Statement`. +```js +if (cond) + consequent; +``` +When taking this `IfStatement`, returns `consequent;` statement. + +#### ast.isProblematicIfStatement(node) + +Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. +```js +{ + type: 'IfStatement', + consequent: { + type: 'WithStatement', + body: { + type: 'IfStatement', + consequent: {type: 'EmptyStatement'} + } + }, + alternate: {type: 'EmptyStatement'} +} +``` +The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. + + +### code + +#### code.isDecimalDigit(code) + +Return true if provided code is decimal digit. + +#### code.isHexDigit(code) + +Return true if provided code is hexadecimal digit. + +#### code.isOctalDigit(code) + +Return true if provided code is octal digit. + +#### code.isWhiteSpace(code) + +Return true if provided code is white space. White space characters are formally defined in ECMA262. + +#### code.isLineTerminator(code) + +Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. + +#### code.isIdentifierStart(code) + +Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. + +#### code.isIdentifierPart(code) + +Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. + +### keyword + +#### keyword.isKeywordES5(id, strict) + +Returns `true` if provided identifier string is a Keyword or Future Reserved Word +in ECMA262 edition 5.1. They are formally defined in ECMA262 sections +[7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), +respectively. If the `strict` flag is truthy, this function additionally checks whether +`id` is a Keyword or Future Reserved Word under strict mode. + +#### keyword.isKeywordES6(id, strict) + +Returns `true` if provided identifier string is a Keyword or Future Reserved Word +in ECMA262 edition 6. They are formally defined in ECMA262 sections +[11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and +[11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), +respectively. If the `strict` flag is truthy, this function additionally checks whether +`id` is a Keyword or Future Reserved Word under strict mode. + +#### keyword.isReservedWordES5(id, strict) + +Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. +They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). +If the `strict` flag is truthy, this function additionally checks whether `id` +is a Reserved Word under strict mode. + +#### keyword.isReservedWordES6(id, strict) + +Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. +They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). +If the `strict` flag is truthy, this function additionally checks whether `id` +is a Reserved Word under strict mode. + +#### keyword.isRestrictedWord(id) + +Returns `true` if provided identifier string is one of `eval` or `arguments`. +They are restricted in strict mode code throughout ECMA262 edition 5.1 and +in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). + +#### keyword.isIdentifierNameES5(id) + +Return true if provided identifier string is an IdentifierName as specified in +ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). + +#### keyword.isIdentifierNameES6(id) + +Return true if provided identifier string is an IdentifierName as specified in +ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). + +#### keyword.isIdentifierES5(id, strict) + +Return true if provided identifier string is an Identifier as specified in +ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` +flag is truthy, this function additionally checks whether `id` is an Identifier +under strict mode. + +#### keyword.isIdentifierES6(id, strict) + +Return true if provided identifier string is an Identifier as specified in +ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). +If the `strict` flag is truthy, this function additionally checks whether `id` +is an Identifier under strict mode. + +### License + +Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/esutils/lib/ast.js b/node_modules/esutils/lib/ast.js new file mode 100644 index 00000000..8faadae1 --- /dev/null +++ b/node_modules/esutils/lib/ast.js @@ -0,0 +1,144 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + function isExpression(node) { + if (node == null) { return false; } + switch (node.type) { + case 'ArrayExpression': + case 'AssignmentExpression': + case 'BinaryExpression': + case 'CallExpression': + case 'ConditionalExpression': + case 'FunctionExpression': + case 'Identifier': + case 'Literal': + case 'LogicalExpression': + case 'MemberExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'SequenceExpression': + case 'ThisExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return true; + } + return false; + } + + function isIterationStatement(node) { + if (node == null) { return false; } + switch (node.type) { + case 'DoWhileStatement': + case 'ForInStatement': + case 'ForStatement': + case 'WhileStatement': + return true; + } + return false; + } + + function isStatement(node) { + if (node == null) { return false; } + switch (node.type) { + case 'BlockStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'DebuggerStatement': + case 'DoWhileStatement': + case 'EmptyStatement': + case 'ExpressionStatement': + case 'ForInStatement': + case 'ForStatement': + case 'IfStatement': + case 'LabeledStatement': + case 'ReturnStatement': + case 'SwitchStatement': + case 'ThrowStatement': + case 'TryStatement': + case 'VariableDeclaration': + case 'WhileStatement': + case 'WithStatement': + return true; + } + return false; + } + + function isSourceElement(node) { + return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; + } + + function trailingStatement(node) { + switch (node.type) { + case 'IfStatement': + if (node.alternate != null) { + return node.alternate; + } + return node.consequent; + + case 'LabeledStatement': + case 'ForStatement': + case 'ForInStatement': + case 'WhileStatement': + case 'WithStatement': + return node.body; + } + return null; + } + + function isProblematicIfStatement(node) { + var current; + + if (node.type !== 'IfStatement') { + return false; + } + if (node.alternate == null) { + return false; + } + current = node.consequent; + do { + if (current.type === 'IfStatement') { + if (current.alternate == null) { + return true; + } + } + current = trailingStatement(current); + } while (current); + + return false; + } + + module.exports = { + isExpression: isExpression, + isStatement: isStatement, + isIterationStatement: isIterationStatement, + isSourceElement: isSourceElement, + isProblematicIfStatement: isProblematicIfStatement, + + trailingStatement: trailingStatement + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/lib/code.js b/node_modules/esutils/lib/code.js new file mode 100644 index 00000000..23136af9 --- /dev/null +++ b/node_modules/esutils/lib/code.js @@ -0,0 +1,135 @@ +/* + Copyright (C) 2013-2014 Yusuke Suzuki + Copyright (C) 2014 Ivan Nikulin + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; + + // See `tools/generate-identifier-regex.js`. + ES5Regex = { + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0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0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ + }; + + ES6Regex = { + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\u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uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFC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uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + + function isDecimalDigit(ch) { + return 0x30 <= ch && ch <= 0x39; // 0..9 + } + + function isHexDigit(ch) { + return 0x30 <= ch && ch <= 0x39 || // 0..9 + 0x61 <= ch && ch <= 0x66 || // a..f + 0x41 <= ch && ch <= 0x46; // A..F + } + + function isOctalDigit(ch) { + return ch >= 0x30 && ch <= 0x37; // 0..7 + } + + // 7.2 White Space + + NON_ASCII_WHITESPACES = [ + 0x1680, + 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, + 0x202F, 0x205F, + 0x3000, + 0xFEFF + ]; + + function isWhiteSpace(ch) { + return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || + ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; + } + + // 7.6 Identifier Names and Identifiers + + function fromCodePoint(cp) { + if (cp <= 0xFFFF) { return String.fromCharCode(cp); } + var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); + var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00); + return cu1 + cu2; + } + + IDENTIFIER_START = new Array(0x80); + for(ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_START[ch] = + ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + IDENTIFIER_PART = new Array(0x80); + for(ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_PART[ch] = + ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch >= 0x30 && ch <= 0x39 || // 0..9 + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + function isIdentifierStartES5(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES5(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + function isIdentifierStartES6(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES6(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStartES5: isIdentifierStartES5, + isIdentifierPartES5: isIdentifierPartES5, + isIdentifierStartES6: isIdentifierStartES6, + isIdentifierPartES6: isIdentifierPartES6 + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/lib/keyword.js b/node_modules/esutils/lib/keyword.js new file mode 100644 index 00000000..13c8c6a9 --- /dev/null +++ b/node_modules/esutils/lib/keyword.js @@ -0,0 +1,165 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + var code = require('./code'); + + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + default: + return false; + } + } + + function isKeywordES5(id, strict) { + // yield should not be treated as keyword under non-strict mode. + if (!strict && id === 'yield') { + return false; + } + return isKeywordES6(id, strict); + } + + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + } + + function isReservedWordES5(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + } + + function isReservedWordES6(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + function isIdentifierNameES5(id) { + var i, iz, ch; + + if (id.length === 0) { return false; } + + ch = id.charCodeAt(0); + if (!code.isIdentifierStartES5(ch)) { + return false; + } + + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (!code.isIdentifierPartES5(ch)) { + return false; + } + } + return true; + } + + function decodeUtf16(lead, trail) { + return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + } + + function isIdentifierNameES6(id) { + var i, iz, ch, lowCh, check; + + if (id.length === 0) { return false; } + + check = code.isIdentifierStartES6; + for (i = 0, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (0xD800 <= ch && ch <= 0xDBFF) { + ++i; + if (i >= iz) { return false; } + lowCh = id.charCodeAt(i); + if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { + return false; + } + ch = decodeUtf16(ch, lowCh); + } + if (!check(ch)) { + return false; + } + check = code.isIdentifierPartES6; + } + return true; + } + + function isIdentifierES5(id, strict) { + return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); + } + + function isIdentifierES6(id, strict) { + return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); + } + + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierNameES5: isIdentifierNameES5, + isIdentifierNameES6: isIdentifierNameES6, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/lib/utils.js b/node_modules/esutils/lib/utils.js new file mode 100644 index 00000000..ce18faa6 --- /dev/null +++ b/node_modules/esutils/lib/utils.js @@ -0,0 +1,33 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +(function () { + 'use strict'; + + exports.ast = require('./ast'); + exports.code = require('./code'); + exports.keyword = require('./keyword'); +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/package.json b/node_modules/esutils/package.json new file mode 100644 index 00000000..8396f4ce --- /dev/null +++ b/node_modules/esutils/package.json @@ -0,0 +1,44 @@ +{ + "name": "esutils", + "description": "utility box for ECMAScript language tools", + "homepage": "https://github.com/estools/esutils", + "main": "lib/utils.js", + "version": "2.0.3", + "engines": { + "node": ">=0.10.0" + }, + "directories": { + "lib": "./lib" + }, + "files": [ + "LICENSE.BSD", + "README.md", + "lib" + ], + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "http://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/estools/esutils.git" + }, + "devDependencies": { + "chai": "~1.7.2", + "coffee-script": "~1.6.3", + "jshint": "2.6.3", + "mocha": "~2.2.1", + "regenerate": "~1.3.1", + "unicode-9.0.0": "~0.7.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint lib/*.js", + "unit-test": "mocha --compilers coffee:coffee-script -R spec", + "generate-regex": "node tools/generate-identifier-regex.js" + } +} diff --git a/node_modules/fast-deep-equal/LICENSE b/node_modules/fast-deep-equal/LICENSE new file mode 100644 index 00000000..7f154356 --- /dev/null +++ b/node_modules/fast-deep-equal/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/fast-deep-equal/README.md b/node_modules/fast-deep-equal/README.md new file mode 100644 index 00000000..326bb2a5 --- /dev/null +++ b/node_modules/fast-deep-equal/README.md @@ -0,0 +1,58 @@ +# fast-deep-equal +The fastest deep equal + +[![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) +[![npm version](https://badge.fury.io/js/fast-deep-equal.svg)](http://badge.fury.io/js/fast-deep-equal) +[![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) + + +## Install + +```bash +npm install fast-deep-equal +``` + + +## Features + +- ES5 compatible +- works in node.js (0.10+) and browsers (IE9+) +- checks equality of Date and RegExp objects by value. + + +## Usage + +```javascript +var equal = require('fast-deep-equal'); +console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true +``` + + +## Performance benchmark + +Node.js v9.11.1: + +``` +fast-deep-equal x 226,960 ops/sec ±1.55% (86 runs sampled) +nano-equal x 218,210 ops/sec ±0.79% (89 runs sampled) +shallow-equal-fuzzy x 206,762 ops/sec ±0.84% (88 runs sampled) +underscore.isEqual x 128,668 ops/sec ±0.75% (91 runs sampled) +lodash.isEqual x 44,895 ops/sec ±0.67% (85 runs sampled) +deep-equal x 51,616 ops/sec ±0.96% (90 runs sampled) +deep-eql x 28,218 ops/sec ±0.42% (85 runs sampled) +assert.deepStrictEqual x 1,777 ops/sec ±1.05% (86 runs sampled) +ramda.equals x 13,466 ops/sec ±0.82% (86 runs sampled) +The fastest is fast-deep-equal +``` + +To run benchmark (requires node.js 6+): + +```bash +npm install +node benchmark +``` + + +## License + +[MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE) diff --git a/node_modules/fast-deep-equal/index.d.ts b/node_modules/fast-deep-equal/index.d.ts new file mode 100644 index 00000000..3c042caa --- /dev/null +++ b/node_modules/fast-deep-equal/index.d.ts @@ -0,0 +1,4 @@ +declare module 'fast-deep-equal' { + const equal: (a: any, b: any) => boolean; + export = equal; +} diff --git a/node_modules/fast-deep-equal/index.js b/node_modules/fast-deep-equal/index.js new file mode 100644 index 00000000..27264f5b --- /dev/null +++ b/node_modules/fast-deep-equal/index.js @@ -0,0 +1,55 @@ +'use strict'; + +var isArray = Array.isArray; +var keyList = Object.keys; +var hasProp = Object.prototype.hasOwnProperty; + +module.exports = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + var arrA = isArray(a) + , arrB = isArray(b) + , i + , length + , key; + + if (arrA && arrB) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + if (arrA != arrB) return false; + + var dateA = a instanceof Date + , dateB = b instanceof Date; + if (dateA != dateB) return false; + if (dateA && dateB) return a.getTime() == b.getTime(); + + var regexpA = a instanceof RegExp + , regexpB = b instanceof RegExp; + if (regexpA != regexpB) return false; + if (regexpA && regexpB) return a.toString() == b.toString(); + + var keys = keyList(a); + length = keys.length; + + if (length !== keyList(b).length) + return false; + + for (i = length; i-- !== 0;) + if (!hasProp.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + return a!==a && b!==b; +}; diff --git a/node_modules/fast-deep-equal/package.json b/node_modules/fast-deep-equal/package.json new file mode 100644 index 00000000..716114ec --- /dev/null +++ b/node_modules/fast-deep-equal/package.json @@ -0,0 +1,59 @@ +{ + "name": "fast-deep-equal", + "version": "2.0.1", + "description": "Fast deep equal", + "main": "index.js", + "scripts": { + "eslint": "eslint *.js benchmark spec", + "test-spec": "mocha spec/*.spec.js -R spec", + "test-cov": "nyc npm run test-spec", + "test-ts": "tsc --target ES5 --noImplicitAny index.d.ts", + "test": "npm run eslint && npm run test-ts && npm run test-cov" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/epoberezkin/fast-deep-equal.git" + }, + "keywords": [ + "fast", + "equal", + "deep-equal" + ], + "author": "Evgeny Poberezkin", + "license": "MIT", + "bugs": { + "url": "https://github.com/epoberezkin/fast-deep-equal/issues" + }, + "homepage": "https://github.com/epoberezkin/fast-deep-equal#readme", + "devDependencies": { + "benchmark": "^2.1.4", + "coveralls": "^2.13.1", + "deep-eql": "latest", + "deep-equal": "latest", + "eslint": "^4.0.0", + "lodash": "latest", + "mocha": "^3.4.2", + "nano-equal": "latest", + "nyc": "^11.0.2", + "pre-commit": "^1.2.2", + "ramda": "latest", + "shallow-equal-fuzzy": "latest", + "typescript": "^2.6.1", + "underscore": "latest" + }, + "nyc": { + "exclude": [ + "**/spec/**", + "node_modules" + ], + "reporter": [ + "lcov", + "text-summary" + ] + }, + "files": [ + "index.js", + "index.d.ts" + ], + "types": "index.d.ts" +} diff --git a/node_modules/fast-glob/LICENSE b/node_modules/fast-glob/LICENSE new file mode 100644 index 00000000..65a99946 --- /dev/null +++ b/node_modules/fast-glob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/fast-glob/README.md b/node_modules/fast-glob/README.md new file mode 100644 index 00000000..1d7843a4 --- /dev/null +++ b/node_modules/fast-glob/README.md @@ -0,0 +1,830 @@ +# fast-glob + +> It's a very fast and efficient [glob][glob_definition] library for [Node.js][node_js]. + +This package provides methods for traversing the file system and returning pathnames that matched a defined set of a specified pattern according to the rules used by the Unix Bash shell with some simplifications, meanwhile results are returned in **arbitrary order**. Quick, simple, effective. + +## Table of Contents + +
+Details + +* [Highlights](#highlights) +* [Old and modern mode](#old-and-modern-mode) +* [Pattern syntax](#pattern-syntax) + * [Basic syntax](#basic-syntax) + * [Advanced syntax](#advanced-syntax) +* [Installation](#installation) +* [API](#api) + * [Asynchronous](#asynchronous) + * [Synchronous](#synchronous) + * [Stream](#stream) + * [patterns](#patterns) + * [[options]](#options) + * [Helpers](#helpers) + * [generateTasks](#generatetaskspatterns-options) + * [isDynamicPattern](#isdynamicpatternpattern-options) + * [escapePath](#escapepathpath) + * [convertPathToPattern](#convertpathtopatternpath) +* [Options](#options-3) + * [Common](#common) + * [concurrency](#concurrency) + * [cwd](#cwd) + * [deep](#deep) + * [followSymbolicLinks](#followsymboliclinks) + * [fs](#fs) + * [ignore](#ignore) + * [suppressErrors](#suppresserrors) + * [throwErrorOnBrokenSymbolicLink](#throwerroronbrokensymboliclink) + * [Output control](#output-control) + * [absolute](#absolute) + * [markDirectories](#markdirectories) + * [objectMode](#objectmode) + * [onlyDirectories](#onlydirectories) + * [onlyFiles](#onlyfiles) + * [stats](#stats) + * [unique](#unique) + * [Matching control](#matching-control) + * [braceExpansion](#braceexpansion) + * [caseSensitiveMatch](#casesensitivematch) + * [dot](#dot) + * [extglob](#extglob) + * [globstar](#globstar) + * [baseNameMatch](#basenamematch) +* [FAQ](#faq) + * [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) + * [How to write patterns on Windows?](#how-to-write-patterns-on-windows) + * [Why are parentheses match wrong?](#why-are-parentheses-match-wrong) + * [How to exclude directory from reading?](#how-to-exclude-directory-from-reading) + * [How to use UNC path?](#how-to-use-unc-path) + * [Compatible with `node-glob`?](#compatible-with-node-glob) +* [Benchmarks](#benchmarks) + * [Server](#server) + * [Nettop](#nettop) +* [Changelog](#changelog) +* [License](#license) + +
+ +## Highlights + +* Fast. Probably the fastest. +* Supports multiple and negative patterns. +* Synchronous, Promise and Stream API. +* Object mode. Can return more than just strings. +* Error-tolerant. + +## Old and modern mode + +This package works in two modes, depending on the environment in which it is used. + +* **Old mode**. Node.js below 10.10 or when the [`stats`](#stats) option is *enabled*. +* **Modern mode**. Node.js 10.10+ and the [`stats`](#stats) option is *disabled*. + +The modern mode is faster. Learn more about the [internal mechanism][nodelib_fs_scandir_old_and_modern_modern]. + +## Pattern syntax + +> :warning: Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. + +There is more than one form of syntax: basic and advanced. Below is a brief overview of the supported features. Also pay attention to our [FAQ](#faq). + +> :book: This package uses [`micromatch`][micromatch] as a library for pattern matching. + +### Basic syntax + +* An asterisk (`*`) — matches everything except slashes (path separators), hidden files (names starting with `.`). +* A double star or globstar (`**`) — matches zero or more directories. +* Question mark (`?`) – matches any single character except slashes (path separators). +* Sequence (`[seq]`) — matches any character in sequence. + +> :book: A few additional words about the [basic matching behavior][picomatch_matching_behavior]. + +Some examples: + +* `src/**/*.js` — matches all files in the `src` directory (any level of nesting) that have the `.js` extension. +* `src/*.??` — matches all files in the `src` directory (only first level of nesting) that have a two-character extension. +* `file-[01].js` — matches files: `file-0.js`, `file-1.js`. + +### Advanced syntax + +* [Escapes characters][micromatch_backslashes] (`\\`) — matching special characters (`$^*+?()[]`) as literals. +* [POSIX character classes][picomatch_posix_brackets] (`[[:digit:]]`). +* [Extended globs][micromatch_extglobs] (`?(pattern-list)`). +* [Bash style brace expansions][micromatch_braces] (`{}`). +* [Regexp character classes][micromatch_regex_character_classes] (`[1-5]`). +* [Regex groups][regular_expressions_brackets] (`(a|b)`). + +> :book: A few additional words about the [advanced matching behavior][micromatch_extended_globbing]. + +Some examples: + +* `src/**/*.{css,scss}` — matches all files in the `src` directory (any level of nesting) that have the `.css` or `.scss` extension. +* `file-[[:digit:]].js` — matches files: `file-0.js`, `file-1.js`, …, `file-9.js`. +* `file-{1..3}.js` — matches files: `file-1.js`, `file-2.js`, `file-3.js`. +* `file-(1|2)` — matches files: `file-1.js`, `file-2.js`. + +## Installation + +```console +npm install fast-glob +``` + +## API + +### Asynchronous + +```js +fg(patterns, [options]) +fg.async(patterns, [options]) +fg.glob(patterns, [options]) +``` + +Returns a `Promise` with an array of matching entries. + +```js +const fg = require('fast-glob'); + +const entries = await fg(['.editorconfig', '**/index.js'], { dot: true }); + +// ['.editorconfig', 'services/index.js'] +``` + +### Synchronous + +```js +fg.sync(patterns, [options]) +fg.globSync(patterns, [options]) +``` + +Returns an array of matching entries. + +```js +const fg = require('fast-glob'); + +const entries = fg.sync(['.editorconfig', '**/index.js'], { dot: true }); + +// ['.editorconfig', 'services/index.js'] +``` + +### Stream + +```js +fg.stream(patterns, [options]) +fg.globStream(patterns, [options]) +``` + +Returns a [`ReadableStream`][node_js_stream_readable_streams] when the `data` event will be emitted with matching entry. + +```js +const fg = require('fast-glob'); + +const stream = fg.stream(['.editorconfig', '**/index.js'], { dot: true }); + +for await (const entry of stream) { + // .editorconfig + // services/index.js +} +``` + +#### patterns + +* Required: `true` +* Type: `string | string[]` + +Any correct pattern(s). + +> :1234: [Pattern syntax](#pattern-syntax) +> +> :warning: This package does not respect the order of patterns. First, all the negative patterns are applied, and only then the positive patterns. If you want to get a certain order of records, use sorting or split calls. + +#### [options] + +* Required: `false` +* Type: [`Options`](#options-3) + +See [Options](#options-3) section. + +### Helpers + +#### `generateTasks(patterns, [options])` + +Returns the internal representation of patterns ([`Task`](./src/managers/tasks.ts) is a combining patterns by base directory). + +```js +fg.generateTasks('*'); + +[{ + base: '.', // Parent directory for all patterns inside this task + dynamic: true, // Dynamic or static patterns are in this task + patterns: ['*'], + positive: ['*'], + negative: [] +}] +``` + +##### patterns + +* Required: `true` +* Type: `string | string[]` + +Any correct pattern(s). + +##### [options] + +* Required: `false` +* Type: [`Options`](#options-3) + +See [Options](#options-3) section. + +#### `isDynamicPattern(pattern, [options])` + +Returns `true` if the passed pattern is a dynamic pattern. + +> :1234: [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) + +```js +fg.isDynamicPattern('*'); // true +fg.isDynamicPattern('abc'); // false +``` + +##### pattern + +* Required: `true` +* Type: `string` + +Any correct pattern. + +##### [options] + +* Required: `false` +* Type: [`Options`](#options-3) + +See [Options](#options-3) section. + +#### `escapePath(path)` + +Returns the path with escaped special characters depending on the platform. + +* Posix: + * `*?|(){}[]`; + * `!` at the beginning of line; + * `@+!` before the opening parenthesis; + * `\\` before non-special characters; +* Windows: + * `(){}[]` + * `!` at the beginning of line; + * `@+!` before the opening parenthesis; + * Characters like `*?|` cannot be used in the path ([windows_naming_conventions][windows_naming_conventions]), so they will not be escaped; + +```js +fg.escapePath('!abc'); +// \\!abc +fg.escapePath('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac' +// \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac + +fg.posix.escapePath('C:\\Program Files (x86)\\**\\*'); +// C:\\\\Program Files \\(x86\\)\\*\\*\\* +fg.win32.escapePath('C:\\Program Files (x86)\\**\\*'); +// Windows: C:\\Program Files \\(x86\\)\\**\\* +``` + +#### `convertPathToPattern(path)` + +Converts a path to a pattern depending on the platform, including special character escaping. + +* Posix. Works similarly to the `fg.posix.escapePath` method. +* Windows. Works similarly to the `fg.win32.escapePath` method, additionally converting backslashes to forward slashes in cases where they are not escape characters (`!()+@{}[]`). + +```js +fg.convertPathToPattern('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac'; +// \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac + +fg.convertPathToPattern('C:/Program Files (x86)/**/*'); +// Posix: C:/Program Files \\(x86\\)/\\*\\*/\\* +// Windows: C:/Program Files \\(x86\\)/**/* + +fg.convertPathToPattern('C:\\Program Files (x86)\\**\\*'); +// Posix: C:\\\\Program Files \\(x86\\)\\*\\*\\* +// Windows: C:/Program Files \\(x86\\)/**/* + +fg.posix.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*'; +// Posix: \\\\\\?\\\\c:\\\\Program Files \\(x86\\)/**/* (broken pattern) +fg.win32.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*'; +// Windows: //?/c:/Program Files \\(x86\\)/**/* +``` + +## Options + +### Common options + +#### concurrency + +* Type: `number` +* Default: `os.cpus().length` + +Specifies the maximum number of concurrent requests from a reader to read directories. + +> :book: The higher the number, the higher the performance and load on the file system. If you want to read in quiet mode, set the value to a comfortable number or `1`. + +
+ +More details + +In Node, there are [two types of threads][nodejs_thread_pool]: Event Loop (code) and a Thread Pool (fs, dns, …). The thread pool size controlled by the `UV_THREADPOOL_SIZE` environment variable. Its default size is 4 ([documentation][libuv_thread_pool]). The pool is one for all tasks within a single Node process. + +Any code can make 4 real concurrent accesses to the file system. The rest of the FS requests will wait in the queue. + +> :book: Each new instance of FG in the same Node process will use the same Thread pool. + +But this package also has the `concurrency` option. This option allows you to control the number of concurrent accesses to the FS at the package level. By default, this package has a value equal to the number of cores available for the current Node process. This allows you to set a value smaller than the pool size (`concurrency: 1`) or, conversely, to prepare tasks for the pool queue more quickly (`concurrency: Number.POSITIVE_INFINITY`). + +So, in fact, this package can **only make 4 concurrent requests to the FS**. You can increase this value by using an environment variable (`UV_THREADPOOL_SIZE`), but in practice this does not give a multiple advantage. + +
+ +#### cwd + +* Type: `string` +* Default: `process.cwd()` + +The current working directory in which to search. + +#### deep + +* Type: `number` +* Default: `Infinity` + +Specifies the maximum depth of a read directory relative to the start directory. + +For example, you have the following tree: + +```js +dir/ +└── one/ // 1 + └── two/ // 2 + └── file.js // 3 +``` + +```js +// With base directory +fg.sync('dir/**', { onlyFiles: false, deep: 1 }); // ['dir/one'] +fg.sync('dir/**', { onlyFiles: false, deep: 2 }); // ['dir/one', 'dir/one/two'] + +// With cwd option +fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 1 }); // ['one'] +fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 2 }); // ['one', 'one/two'] +``` + +> :book: If you specify a pattern with some base directory, this directory will not participate in the calculation of the depth of the found directories. Think of it as a [`cwd`](#cwd) option. + +#### followSymbolicLinks + +* Type: `boolean` +* Default: `true` + +Indicates whether to traverse descendants of symbolic link directories when expanding `**` patterns. + +> :book: Note that this option does not affect the base directory of the pattern. For example, if `./a` is a symlink to directory `./b` and you specified `['./a**', './b/**']` patterns, then directory `./a` will still be read. + +> :book: If the [`stats`](#stats) option is specified, the information about the symbolic link (`fs.lstat`) will be replaced with information about the entry (`fs.stat`) behind it. + +#### fs + +* Type: `FileSystemAdapter` +* Default: `fs.*` + +Custom implementation of methods for working with the file system. Supports objects with enumerable properties only. + +```ts +export interface FileSystemAdapter { + lstat?: typeof fs.lstat; + stat?: typeof fs.stat; + lstatSync?: typeof fs.lstatSync; + statSync?: typeof fs.statSync; + readdir?: typeof fs.readdir; + readdirSync?: typeof fs.readdirSync; +} +``` + +#### ignore + +* Type: `string[]` +* Default: `[]` + +An array of glob patterns to exclude matches. This is an alternative way to use negative patterns. + +```js +dir/ +├── package-lock.json +└── package.json +``` + +```js +fg.sync(['*.json', '!package-lock.json']); // ['package.json'] +fg.sync('*.json', { ignore: ['package-lock.json'] }); // ['package.json'] +``` + +#### suppressErrors + +* Type: `boolean` +* Default: `false` + +By default this package suppress only `ENOENT` errors. Set to `true` to suppress any error. + +> :book: Can be useful when the directory has entries with a special level of access. + +#### throwErrorOnBrokenSymbolicLink + +* Type: `boolean` +* Default: `false` + +Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. + +> :book: This option has no effect on errors when reading the symbolic link directory. + +### Output control + +#### absolute + +* Type: `boolean` +* Default: `false` + +Return the absolute path for entries. + +```js +fg.sync('*.js', { absolute: false }); // ['index.js'] +fg.sync('*.js', { absolute: true }); // ['/home/user/index.js'] +``` + +> :book: This option is required if you want to use negative patterns with absolute path, for example, `!${__dirname}/*.js`. + +#### markDirectories + +* Type: `boolean` +* Default: `false` + +Mark the directory path with the final slash. + +```js +fg.sync('*', { onlyFiles: false, markDirectories: false }); // ['index.js', 'controllers'] +fg.sync('*', { onlyFiles: false, markDirectories: true }); // ['index.js', 'controllers/'] +``` + +#### objectMode + +* Type: `boolean` +* Default: `false` + +Returns objects (instead of strings) describing entries. + +```js +fg.sync('*', { objectMode: false }); // ['src/index.js'] +fg.sync('*', { objectMode: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: }] +``` + +The object has the following fields: + +* name (`string`) — the last part of the path (basename) +* path (`string`) — full path relative to the pattern base directory +* dirent ([`fs.Dirent`][node_js_fs_class_fs_dirent]) — instance of `fs.Dirent` + +> :book: An object is an internal representation of entry, so getting it does not affect performance. + +#### onlyDirectories + +* Type: `boolean` +* Default: `false` + +Return only directories. + +```js +fg.sync('*', { onlyDirectories: false }); // ['index.js', 'src'] +fg.sync('*', { onlyDirectories: true }); // ['src'] +``` + +> :book: If `true`, the [`onlyFiles`](#onlyfiles) option is automatically `false`. + +#### onlyFiles + +* Type: `boolean` +* Default: `true` + +Return only files. + +```js +fg.sync('*', { onlyFiles: false }); // ['index.js', 'src'] +fg.sync('*', { onlyFiles: true }); // ['index.js'] +``` + +#### stats + +* Type: `boolean` +* Default: `false` + +Enables an [object mode](#objectmode) with an additional field: + +* stats ([`fs.Stats`][node_js_fs_class_fs_stats]) — instance of `fs.Stats` + +```js +fg.sync('*', { stats: false }); // ['src/index.js'] +fg.sync('*', { stats: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: , stats: }] +``` + +> :book: Returns `fs.stat` instead of `fs.lstat` for symbolic links when the [`followSymbolicLinks`](#followsymboliclinks) option is specified. +> +> :warning: Unlike [object mode](#objectmode) this mode requires additional calls to the file system. On average, this mode is slower at least twice. See [old and modern mode](#old-and-modern-mode) for more details. + +#### unique + +* Type: `boolean` +* Default: `true` + +Ensures that the returned entries are unique. + +```js +fg.sync(['*.json', 'package.json'], { unique: false }); // ['package.json', 'package.json'] +fg.sync(['*.json', 'package.json'], { unique: true }); // ['package.json'] +``` + +If `true` and similar entries are found, the result is the first found. + +### Matching control + +#### braceExpansion + +* Type: `boolean` +* Default: `true` + +Enables Bash-like brace expansion. + +> :1234: [Syntax description][bash_hackers_syntax_expansion_brace] or more [detailed description][micromatch_braces]. + +```js +dir/ +├── abd +├── acd +└── a{b,c}d +``` + +```js +fg.sync('a{b,c}d', { braceExpansion: false }); // ['a{b,c}d'] +fg.sync('a{b,c}d', { braceExpansion: true }); // ['abd', 'acd'] +``` + +#### caseSensitiveMatch + +* Type: `boolean` +* Default: `true` + +Enables a [case-sensitive][wikipedia_case_sensitivity] mode for matching files. + +```js +dir/ +├── file.txt +└── File.txt +``` + +```js +fg.sync('file.txt', { caseSensitiveMatch: false }); // ['file.txt', 'File.txt'] +fg.sync('file.txt', { caseSensitiveMatch: true }); // ['file.txt'] +``` + +#### dot + +* Type: `boolean` +* Default: `false` + +Allow patterns to match entries that begin with a period (`.`). + +> :book: Note that an explicit dot in a portion of the pattern will always match dot files. + +```js +dir/ +├── .editorconfig +└── package.json +``` + +```js +fg.sync('*', { dot: false }); // ['package.json'] +fg.sync('*', { dot: true }); // ['.editorconfig', 'package.json'] +``` + +#### extglob + +* Type: `boolean` +* Default: `true` + +Enables Bash-like `extglob` functionality. + +> :1234: [Syntax description][micromatch_extglobs]. + +```js +dir/ +├── README.md +└── package.json +``` + +```js +fg.sync('*.+(json|md)', { extglob: false }); // [] +fg.sync('*.+(json|md)', { extglob: true }); // ['README.md', 'package.json'] +``` + +#### globstar + +* Type: `boolean` +* Default: `true` + +Enables recursively repeats a pattern containing `**`. If `false`, `**` behaves exactly like `*`. + +```js +dir/ +└── a + └── b +``` + +```js +fg.sync('**', { onlyFiles: false, globstar: false }); // ['a'] +fg.sync('**', { onlyFiles: false, globstar: true }); // ['a', 'a/b'] +``` + +#### baseNameMatch + +* Type: `boolean` +* Default: `false` + +If set to `true`, then patterns without slashes will be matched against the basename of the path if it contains slashes. + +```js +dir/ +└── one/ + └── file.md +``` + +```js +fg.sync('*.md', { baseNameMatch: false }); // [] +fg.sync('*.md', { baseNameMatch: true }); // ['one/file.md'] +``` + +## FAQ + +## What is a static or dynamic pattern? + +All patterns can be divided into two types: + +* **static**. A pattern is considered static if it can be used to get an entry on the file system without using matching mechanisms. For example, the `file.js` pattern is a static pattern because we can just verify that it exists on the file system. +* **dynamic**. A pattern is considered dynamic if it cannot be used directly to find occurrences without using a matching mechanisms. For example, the `*` pattern is a dynamic pattern because we cannot use this pattern directly. + +A pattern is considered dynamic if it contains the following characters (`…` — any characters or their absence) or options: + +* The [`caseSensitiveMatch`](#casesensitivematch) option is disabled +* `\\` (the escape character) +* `*`, `?`, `!` (at the beginning of line) +* `[…]` +* `(…|…)` +* `@(…)`, `!(…)`, `*(…)`, `?(…)`, `+(…)` (respects the [`extglob`](#extglob) option) +* `{…,…}`, `{…..…}` (respects the [`braceExpansion`](#braceexpansion) option) + +## How to write patterns on Windows? + +Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. With the [`cwd`](#cwd) option use a convenient format. + +**Bad** + +```ts +[ + 'directory\\*', + path.join(process.cwd(), '**') +] +``` + +**Good** + +```ts +[ + 'directory/*', + fg.convertPathToPattern(process.cwd()) + '/**' +] +``` + +> :book: Use the [`.convertPathToPattern`](#convertpathtopatternpath) package to convert Windows-style path to a Unix-style path. + +Read more about [matching with backslashes][micromatch_backslashes]. + +## Why are parentheses match wrong? + +```js +dir/ +└── (special-*file).txt +``` + +```js +fg.sync(['(special-*file).txt']) // [] +``` + +Refers to Bash. You need to escape special characters: + +```js +fg.sync(['\\(special-*file\\).txt']) // ['(special-*file).txt'] +``` + +Read more about [matching special characters as literals][picomatch_matching_special_characters_as_literals]. Or use the [`.escapePath`](#escapepathpath). + +## How to exclude directory from reading? + +You can use a negative pattern like this: `!**/node_modules` or `!**/node_modules/**`. Also you can use [`ignore`](#ignore) option. Just look at the example below. + +```js +first/ +├── file.md +└── second/ + └── file.txt +``` + +If you don't want to read the `second` directory, you must write the following pattern: `!**/second` or `!**/second/**`. + +```js +fg.sync(['**/*.md', '!**/second']); // ['first/file.md'] +fg.sync(['**/*.md'], { ignore: ['**/second/**'] }); // ['first/file.md'] +``` + +> :warning: When you write `!**/second/**/*` it means that the directory will be **read**, but all the entries will not be included in the results. + +You have to understand that if you write the pattern to exclude directories, then the directory will not be read under any circumstances. + +## How to use UNC path? + +You cannot use [Uniform Naming Convention (UNC)][unc_path] paths as patterns (due to syntax) directly, but you can use them as [`cwd`](#cwd) directory or use the `fg.convertPathToPattern` method. + +```ts +// cwd +fg.sync('*', { cwd: '\\\\?\\C:\\Python27' /* or //?/C:/Python27 */ }); +fg.sync('Python27/*', { cwd: '\\\\?\\C:\\' /* or //?/C:/ */ }); + +// .convertPathToPattern +fg.sync(fg.convertPathToPattern('\\\\?\\c:\\Python27') + '/*'); +``` + +## Compatible with `node-glob`? + +| node-glob | fast-glob | +| :----------: | :-------: | +| `cwd` | [`cwd`](#cwd) | +| `root` | – | +| `dot` | [`dot`](#dot) | +| `nomount` | – | +| `mark` | [`markDirectories`](#markdirectories) | +| `nosort` | – | +| `nounique` | [`unique`](#unique) | +| `nobrace` | [`braceExpansion`](#braceexpansion) | +| `noglobstar` | [`globstar`](#globstar) | +| `noext` | [`extglob`](#extglob) | +| `nocase` | [`caseSensitiveMatch`](#casesensitivematch) | +| `matchBase` | [`baseNameMatch`](#basenamematch) | +| `nodir` | [`onlyFiles`](#onlyfiles) | +| `ignore` | [`ignore`](#ignore) | +| `follow` | [`followSymbolicLinks`](#followsymboliclinks) | +| `realpath` | – | +| `absolute` | [`absolute`](#absolute) | + +## Benchmarks + +You can see results [here](https://github.com/mrmlnc/fast-glob/actions/workflows/benchmark.yml?query=branch%3Amaster) for every commit into the `main` branch. + +* **Product benchmark** – comparison with the main competitors. +* **Regress benchmark** – regression between the current version and the version from the npm registry. + +## Changelog + +See the [Releases section of our GitHub project][github_releases] for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. + +[bash_hackers_syntax_expansion_brace]: https://wiki.bash-hackers.org/syntax/expansion/brace +[github_releases]: https://github.com/mrmlnc/fast-glob/releases +[glob_definition]: https://en.wikipedia.org/wiki/Glob_(programming) +[glob_linux_man]: http://man7.org/linux/man-pages/man3/glob.3.html +[micromatch_backslashes]: https://github.com/micromatch/micromatch#backslashes +[micromatch_braces]: https://github.com/micromatch/braces +[micromatch_extended_globbing]: https://github.com/micromatch/micromatch#extended-globbing +[micromatch_extglobs]: https://github.com/micromatch/micromatch#extglobs +[micromatch_regex_character_classes]: https://github.com/micromatch/micromatch#regex-character-classes +[micromatch]: https://github.com/micromatch/micromatch +[node_js_fs_class_fs_dirent]: https://nodejs.org/api/fs.html#fs_class_fs_dirent +[node_js_fs_class_fs_stats]: https://nodejs.org/api/fs.html#fs_class_fs_stats +[node_js_stream_readable_streams]: https://nodejs.org/api/stream.html#stream_readable_streams +[node_js]: https://nodejs.org/en +[nodelib_fs_scandir_old_and_modern_modern]: https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode +[npm_normalize_path]: https://www.npmjs.com/package/normalize-path +[npm_unixify]: https://www.npmjs.com/package/unixify +[picomatch_matching_behavior]: https://github.com/micromatch/picomatch#matching-behavior-vs-bash +[picomatch_matching_special_characters_as_literals]: https://github.com/micromatch/picomatch#matching-special-characters-as-literals +[picomatch_posix_brackets]: https://github.com/micromatch/picomatch#posix-brackets +[regular_expressions_brackets]: https://www.regular-expressions.info/brackets.html +[unc_path]: https://learn.microsoft.com/openspecs/windows_protocols/ms-dtyp/62e862f4-2a51-452e-8eeb-dc4ff5ee33cc +[wikipedia_case_sensitivity]: https://en.wikipedia.org/wiki/Case_sensitivity +[nodejs_thread_pool]: https://nodejs.org/en/docs/guides/dont-block-the-event-loop +[libuv_thread_pool]: http://docs.libuv.org/en/v1.x/threadpool.html +[windows_naming_conventions]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions diff --git a/node_modules/fast-glob/node_modules/glob-parent/CHANGELOG.md b/node_modules/fast-glob/node_modules/glob-parent/CHANGELOG.md new file mode 100644 index 00000000..fb9de961 --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/CHANGELOG.md @@ -0,0 +1,110 @@ +### [5.1.2](https://github.com/gulpjs/glob-parent/compare/v5.1.1...v5.1.2) (2021-03-06) + + +### Bug Fixes + +* eliminate ReDoS ([#36](https://github.com/gulpjs/glob-parent/issues/36)) ([f923116](https://github.com/gulpjs/glob-parent/commit/f9231168b0041fea3f8f954b3cceb56269fc6366)) + +### [5.1.1](https://github.com/gulpjs/glob-parent/compare/v5.1.0...v5.1.1) (2021-01-27) + + +### Bug Fixes + +* unescape exclamation mark ([#26](https://github.com/gulpjs/glob-parent/issues/26)) ([a98874f](https://github.com/gulpjs/glob-parent/commit/a98874f1a59e407f4fb1beb0db4efa8392da60bb)) + +## [5.1.0](https://github.com/gulpjs/glob-parent/compare/v5.0.0...v5.1.0) (2021-01-27) + + +### Features + +* add `flipBackslashes` option to disable auto conversion of slashes (closes [#24](https://github.com/gulpjs/glob-parent/issues/24)) ([#25](https://github.com/gulpjs/glob-parent/issues/25)) ([eecf91d](https://github.com/gulpjs/glob-parent/commit/eecf91d5e3834ed78aee39c4eaaae654d76b87b3)) + +## [5.0.0](https://github.com/gulpjs/glob-parent/compare/v4.0.0...v5.0.0) (2021-01-27) + + +### ⚠ BREAKING CHANGES + +* Drop support for node <6 & bump dependencies + +### Miscellaneous Chores + +* Drop support for node <6 & bump dependencies ([896c0c0](https://github.com/gulpjs/glob-parent/commit/896c0c00b4e7362f60b96e7fc295ae929245255a)) + +## [4.0.0](https://github.com/gulpjs/glob-parent/compare/v3.1.0...v4.0.0) (2021-01-27) + + +### ⚠ BREAKING CHANGES + +* question marks are valid path characters on Windows so avoid flagging as a glob when alone +* Update is-glob dependency + +### Features + +* hoist regexps and strings for performance gains ([4a80667](https://github.com/gulpjs/glob-parent/commit/4a80667c69355c76a572a5892b0f133c8e1f457e)) +* question marks are valid path characters on Windows so avoid flagging as a glob when alone ([2a551dd](https://github.com/gulpjs/glob-parent/commit/2a551dd0dc3235e78bf3c94843d4107072d17841)) +* Update is-glob dependency ([e41fcd8](https://github.com/gulpjs/glob-parent/commit/e41fcd895d1f7bc617dba45c9d935a7949b9c281)) + +## [3.1.0](https://github.com/gulpjs/glob-parent/compare/v3.0.1...v3.1.0) (2021-01-27) + + +### Features + +* allow basic win32 backslash use ([272afa5](https://github.com/gulpjs/glob-parent/commit/272afa5fd070fc0f796386a5993d4ee4a846988b)) +* handle extglobs (parentheses) containing separators ([7db1bdb](https://github.com/gulpjs/glob-parent/commit/7db1bdb0756e55fd14619e8ce31aa31b17b117fd)) +* new approach to braces/brackets handling ([8269bd8](https://github.com/gulpjs/glob-parent/commit/8269bd89290d99fac9395a354fb56fdcdb80f0be)) +* pre-process braces/brackets sections ([9ef8a87](https://github.com/gulpjs/glob-parent/commit/9ef8a87f66b1a43d0591e7a8e4fc5a18415ee388)) +* preserve escaped brace/bracket at end of string ([8cfb0ba](https://github.com/gulpjs/glob-parent/commit/8cfb0ba84202d51571340dcbaf61b79d16a26c76)) + + +### Bug Fixes + +* trailing escaped square brackets ([99ec9fe](https://github.com/gulpjs/glob-parent/commit/99ec9fecc60ee488ded20a94dd4f18b4f55c4ccf)) + +### [3.0.1](https://github.com/gulpjs/glob-parent/compare/v3.0.0...v3.0.1) (2021-01-27) + + +### Features + +* use path-dirname ponyfill ([cdbea5f](https://github.com/gulpjs/glob-parent/commit/cdbea5f32a58a54e001a75ddd7c0fccd4776aacc)) + + +### Bug Fixes + +* unescape glob-escaped dirnames on output ([598c533](https://github.com/gulpjs/glob-parent/commit/598c533bdf49c1428bc063aa9b8db40c5a86b030)) + +## [3.0.0](https://github.com/gulpjs/glob-parent/compare/v2.0.0...v3.0.0) (2021-01-27) + + +### ⚠ BREAKING CHANGES + +* update is-glob dependency + +### Features + +* update is-glob dependency ([5c5f8ef](https://github.com/gulpjs/glob-parent/commit/5c5f8efcee362a8e7638cf8220666acd8784f6bd)) + +## [2.0.0](https://github.com/gulpjs/glob-parent/compare/v1.3.0...v2.0.0) (2021-01-27) + + +### Features + +* move up to dirname regardless of glob characters ([f97fb83](https://github.com/gulpjs/glob-parent/commit/f97fb83be2e0a9fc8d3b760e789d2ecadd6aa0c2)) + +## [1.3.0](https://github.com/gulpjs/glob-parent/compare/v1.2.0...v1.3.0) (2021-01-27) + +## [1.2.0](https://github.com/gulpjs/glob-parent/compare/v1.1.0...v1.2.0) (2021-01-27) + + +### Reverts + +* feat: make regex test strings smaller ([dc80fa9](https://github.com/gulpjs/glob-parent/commit/dc80fa9658dca20549cfeba44bbd37d5246fcce0)) + +## [1.1.0](https://github.com/gulpjs/glob-parent/compare/v1.0.0...v1.1.0) (2021-01-27) + + +### Features + +* make regex test strings smaller ([cd83220](https://github.com/gulpjs/glob-parent/commit/cd832208638f45169f986d80fcf66e401f35d233)) + +## 1.0.0 (2021-01-27) + diff --git a/node_modules/fast-glob/node_modules/glob-parent/LICENSE b/node_modules/fast-glob/node_modules/glob-parent/LICENSE new file mode 100644 index 00000000..63222d7a --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015, 2019 Elan Shanker + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/fast-glob/node_modules/glob-parent/README.md b/node_modules/fast-glob/node_modules/glob-parent/README.md new file mode 100644 index 00000000..36a27938 --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/README.md @@ -0,0 +1,137 @@ +

+ + + +

+ +# glob-parent + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] + +Extract the non-magic parent path from a glob string. + +## Usage + +```js +var globParent = require('glob-parent'); + +globParent('path/to/*.js'); // 'path/to' +globParent('/root/path/to/*.js'); // '/root/path/to' +globParent('/*.js'); // '/' +globParent('*.js'); // '.' +globParent('**/*.js'); // '.' +globParent('path/{to,from}'); // 'path' +globParent('path/!(to|from)'); // 'path' +globParent('path/?(to|from)'); // 'path' +globParent('path/+(to|from)'); // 'path' +globParent('path/*(to|from)'); // 'path' +globParent('path/@(to|from)'); // 'path' +globParent('path/**/*'); // 'path' + +// if provided a non-glob path, returns the nearest dir +globParent('path/foo/bar.js'); // 'path/foo' +globParent('path/foo/'); // 'path/foo' +globParent('path/foo'); // 'path' (see issue #3 for details) +``` + +## API + +### `globParent(maybeGlobString, [options])` + +Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. + +#### options + +```js +{ + // Disables the automatic conversion of slashes for Windows + flipBackslashes: true +} +``` + +## Escaping + +The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: + +- `?` (question mark) unless used as a path segment alone +- `*` (asterisk) +- `|` (pipe) +- `(` (opening parenthesis) +- `)` (closing parenthesis) +- `{` (opening curly brace) +- `}` (closing curly brace) +- `[` (opening bracket) +- `]` (closing bracket) + +**Example** + +```js +globParent('foo/[bar]/') // 'foo' +globParent('foo/\\[bar]/') // 'foo/[bar]' +``` + +## Limitations + +### Braces & Brackets +This library attempts a quick and imperfect method of determining which path +parts have glob magic without fully parsing/lexing the pattern. There are some +advanced use cases that can trip it up, such as nested braces where the outer +pair is escaped and the inner one contains a path separator. If you find +yourself in the unlikely circumstance of being affected by this or need to +ensure higher-fidelity glob handling in your library, it is recommended that you +pre-process your input with [expand-braces] and/or [expand-brackets]. + +### Windows +Backslashes are not valid path separators for globs. If a path with backslashes +is provided anyway, for simple cases, glob-parent will replace the path +separator for you and return the non-glob parent path (now with +forward-slashes, which are still valid as Windows path separators). + +This cannot be used in conjunction with escape characters. + +```js +// BAD +globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' + +// GOOD +globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' +``` + +If you are using escape characters for a pattern without path parts (i.e. +relative to `cwd`), prefix with `./` to avoid confusing glob-parent. + +```js +// BAD +globParent('foo \\[bar]') // 'foo ' +globParent('foo \\[bar]*') // 'foo ' + +// GOOD +globParent('./foo \\[bar]') // 'foo [bar]' +globParent('./foo \\[bar]*') // '.' +``` + +## License + +ISC + +[expand-braces]: https://github.com/jonschlinkert/expand-braces +[expand-brackets]: https://github.com/jonschlinkert/expand-brackets + +[downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg +[npm-url]: https://www.npmjs.com/package/glob-parent +[npm-image]: https://img.shields.io/npm/v/glob-parent.svg + +[azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master +[azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master + +[travis-url]: https://travis-ci.org/gulpjs/glob-parent +[travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci + +[appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent +[appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor + +[coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent +[coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg + +[gitter-url]: https://gitter.im/gulpjs/gulp +[gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg diff --git a/node_modules/fast-glob/node_modules/glob-parent/index.js b/node_modules/fast-glob/node_modules/glob-parent/index.js new file mode 100644 index 00000000..09e257ea --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var isGlob = require('is-glob'); +var pathPosixDirname = require('path').posix.dirname; +var isWin32 = require('os').platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + * @returns {string} + */ +module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (enclosure.test(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; diff --git a/node_modules/fast-glob/node_modules/glob-parent/package.json b/node_modules/fast-glob/node_modules/glob-parent/package.json new file mode 100644 index 00000000..125c971c --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/package.json @@ -0,0 +1,48 @@ +{ + "name": "glob-parent", + "version": "5.1.2", + "description": "Extract the non-magic parent path from a glob string.", + "author": "Gulp Team (https://gulpjs.com/)", + "contributors": [ + "Elan Shanker (https://github.com/es128)", + "Blaine Bublitz " + ], + "repository": "gulpjs/glob-parent", + "license": "ISC", + "engines": { + "node": ">= 6" + }, + "main": "index.js", + "files": [ + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "pretest": "npm run lint", + "test": "nyc mocha --async-only", + "azure-pipelines": "nyc mocha --async-only --reporter xunit -O output=test.xunit", + "coveralls": "nyc report --reporter=text-lcov | coveralls" + }, + "dependencies": { + "is-glob": "^4.0.1" + }, + "devDependencies": { + "coveralls": "^3.0.11", + "eslint": "^2.13.1", + "eslint-config-gulp": "^3.0.1", + "expect": "^1.20.2", + "mocha": "^6.0.2", + "nyc": "^13.3.0" + }, + "keywords": [ + "glob", + "parent", + "strip", + "path", + "dirname", + "directory", + "base", + "wildcard" + ] +} diff --git a/node_modules/fast-glob/out/index.d.ts b/node_modules/fast-glob/out/index.d.ts new file mode 100644 index 00000000..46823bb5 --- /dev/null +++ b/node_modules/fast-glob/out/index.d.ts @@ -0,0 +1,40 @@ +/// +import * as taskManager from './managers/tasks'; +import { Options as OptionsInternal } from './settings'; +import { Entry as EntryInternal, FileSystemAdapter as FileSystemAdapterInternal, Pattern as PatternInternal } from './types'; +type EntryObjectModePredicate = { + [TKey in keyof Pick]-?: true; +}; +type EntryStatsPredicate = { + [TKey in keyof Pick]-?: true; +}; +type EntryObjectPredicate = EntryObjectModePredicate | EntryStatsPredicate; +declare function FastGlob(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): Promise; +declare function FastGlob(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Promise; +declare namespace FastGlob { + type Options = OptionsInternal; + type Entry = EntryInternal; + type Task = taskManager.Task; + type Pattern = PatternInternal; + type FileSystemAdapter = FileSystemAdapterInternal; + const glob: typeof FastGlob; + const globSync: typeof sync; + const globStream: typeof stream; + const async: typeof FastGlob; + function sync(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): EntryInternal[]; + function sync(source: PatternInternal | PatternInternal[], options?: OptionsInternal): string[]; + function stream(source: PatternInternal | PatternInternal[], options?: OptionsInternal): NodeJS.ReadableStream; + function generateTasks(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Task[]; + function isDynamicPattern(source: PatternInternal, options?: OptionsInternal): boolean; + function escapePath(source: string): PatternInternal; + function convertPathToPattern(source: string): PatternInternal; + namespace posix { + function escapePath(source: string): PatternInternal; + function convertPathToPattern(source: string): PatternInternal; + } + namespace win32 { + function escapePath(source: string): PatternInternal; + function convertPathToPattern(source: string): PatternInternal; + } +} +export = FastGlob; diff --git a/node_modules/fast-glob/out/index.js b/node_modules/fast-glob/out/index.js new file mode 100644 index 00000000..90365d48 --- /dev/null +++ b/node_modules/fast-glob/out/index.js @@ -0,0 +1,102 @@ +"use strict"; +const taskManager = require("./managers/tasks"); +const async_1 = require("./providers/async"); +const stream_1 = require("./providers/stream"); +const sync_1 = require("./providers/sync"); +const settings_1 = require("./settings"); +const utils = require("./utils"); +async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async_1.default, options); + const result = await Promise.all(works); + return utils.array.flatten(result); +} +// https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare +(function (FastGlob) { + FastGlob.glob = FastGlob; + FastGlob.globSync = sync; + FastGlob.globStream = stream; + FastGlob.async = FastGlob; + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync_1.default, options); + return utils.array.flatten(works); + } + FastGlob.sync = sync; + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream_1.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + return utils.stream.merge(works); + } + FastGlob.stream = stream; + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings_1.default(options); + return taskManager.generate(patterns, settings); + } + FastGlob.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings_1.default(options); + return utils.pattern.isDynamicPattern(source, settings); + } + FastGlob.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escape(source); + } + FastGlob.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPathToPattern(source); + } + FastGlob.convertPathToPattern = convertPathToPattern; + let posix; + (function (posix) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapePosixPath(source); + } + posix.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPosixPathToPattern(source); + } + posix.convertPathToPattern = convertPathToPattern; + })(posix = FastGlob.posix || (FastGlob.posix = {})); + let win32; + (function (win32) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapeWindowsPath(source); + } + win32.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertWindowsPathToPattern(source); + } + win32.convertPathToPattern = convertPathToPattern; + })(win32 = FastGlob.win32 || (FastGlob.win32 = {})); +})(FastGlob || (FastGlob = {})); +function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings_1.default(options); + const tasks = taskManager.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks.map(provider.read, provider); +} +function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } +} +module.exports = FastGlob; diff --git a/node_modules/fast-glob/out/managers/tasks.d.ts b/node_modules/fast-glob/out/managers/tasks.d.ts new file mode 100644 index 00000000..59d2c427 --- /dev/null +++ b/node_modules/fast-glob/out/managers/tasks.d.ts @@ -0,0 +1,22 @@ +import Settings from '../settings'; +import { Pattern, PatternsGroup } from '../types'; +export type Task = { + base: string; + dynamic: boolean; + patterns: Pattern[]; + positive: Pattern[]; + negative: Pattern[]; +}; +export declare function generate(input: Pattern[], settings: Settings): Task[]; +/** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ +export declare function convertPatternsToTasks(positive: Pattern[], negative: Pattern[], dynamic: boolean): Task[]; +export declare function getPositivePatterns(patterns: Pattern[]): Pattern[]; +export declare function getNegativePatternsAsPositive(patterns: Pattern[], ignore: Pattern[]): Pattern[]; +export declare function groupPatternsByBaseDirectory(patterns: Pattern[]): PatternsGroup; +export declare function convertPatternGroupsToTasks(positive: PatternsGroup, negative: Pattern[], dynamic: boolean): Task[]; +export declare function convertPatternGroupToTask(base: string, positive: Pattern[], negative: Pattern[], dynamic: boolean): Task; diff --git a/node_modules/fast-glob/out/managers/tasks.js b/node_modules/fast-glob/out/managers/tasks.js new file mode 100644 index 00000000..335a7651 --- /dev/null +++ b/node_modules/fast-glob/out/managers/tasks.js @@ -0,0 +1,110 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; +const utils = require("../utils"); +function generate(input, settings) { + const patterns = processPatterns(input, settings); + const ignore = processPatterns(settings.ignore, settings); + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); +} +exports.generate = generate; +function processPatterns(input, settings) { + let patterns = input; + /** + * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry + * and some problems with the micromatch package (see fast-glob issues: #365, #394). + * + * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown + * in matching in the case of a large set of patterns after expansion. + */ + if (settings.braceExpansion) { + patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns); + } + /** + * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used + * at any nesting level. + * + * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change + * the pattern in the filter before creating a regular expression. There is no need to change the patterns + * in the application. Only on the input. + */ + if (settings.baseNameMatch) { + patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); + } + /** + * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. + */ + return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern)); +} +/** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ +function convertPatternsToTasks(positive, negative, dynamic) { + const tasks = []; + const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); + const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); + const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); + tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); + /* + * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory + * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. + */ + if ('.' in insideCurrentDirectoryGroup) { + tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); + } + else { + tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + } + return tasks; +} +exports.convertPatternsToTasks = convertPatternsToTasks; +function getPositivePatterns(patterns) { + return utils.pattern.getPositivePatterns(patterns); +} +exports.getPositivePatterns = getPositivePatterns; +function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils.pattern.convertToPositivePattern); + return positive; +} +exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, group); +} +exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) + }; +} +exports.convertPatternGroupToTask = convertPatternGroupToTask; diff --git a/node_modules/fast-glob/out/providers/async.d.ts b/node_modules/fast-glob/out/providers/async.d.ts new file mode 100644 index 00000000..27426164 --- /dev/null +++ b/node_modules/fast-glob/out/providers/async.d.ts @@ -0,0 +1,9 @@ +import { Task } from '../managers/tasks'; +import { Entry, EntryItem, ReaderOptions } from '../types'; +import ReaderAsync from '../readers/async'; +import Provider from './provider'; +export default class ProviderAsync extends Provider> { + protected _reader: ReaderAsync; + read(task: Task): Promise; + api(root: string, task: Task, options: ReaderOptions): Promise; +} diff --git a/node_modules/fast-glob/out/providers/async.js b/node_modules/fast-glob/out/providers/async.js new file mode 100644 index 00000000..0c5286e7 --- /dev/null +++ b/node_modules/fast-glob/out/providers/async.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const async_1 = require("../readers/async"); +const provider_1 = require("./provider"); +class ProviderAsync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new async_1.default(this._settings); + } + async read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = await this.api(root, task, options); + return entries.map((entry) => options.transform(entry)); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderAsync; diff --git a/node_modules/fast-glob/out/providers/filters/deep.d.ts b/node_modules/fast-glob/out/providers/filters/deep.d.ts new file mode 100644 index 00000000..377fab88 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/deep.d.ts @@ -0,0 +1,16 @@ +import { MicromatchOptions, EntryFilterFunction, Pattern } from '../../types'; +import Settings from '../../settings'; +export default class DeepFilter { + private readonly _settings; + private readonly _micromatchOptions; + constructor(_settings: Settings, _micromatchOptions: MicromatchOptions); + getFilter(basePath: string, positive: Pattern[], negative: Pattern[]): EntryFilterFunction; + private _getMatcher; + private _getNegativePatternsRe; + private _filter; + private _isSkippedByDeep; + private _getEntryLevel; + private _isSkippedSymbolicLink; + private _isSkippedByPositivePatterns; + private _isSkippedByNegativePatterns; +} diff --git a/node_modules/fast-glob/out/providers/filters/deep.js b/node_modules/fast-glob/out/providers/filters/deep.js new file mode 100644 index 00000000..644bf41b --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/deep.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +const partial_1 = require("../matchers/partial"); +class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); + } + _getMatcher(patterns) { + return new partial_1.default(patterns, this._settings, this._micromatchOptions); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); + return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; + } + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; + } + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; + } + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + if (basePath === '') { + return entryPathDepth; + } + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; + } + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils.pattern.matchAny(entryPath, patternsRe); + } +} +exports.default = DeepFilter; diff --git a/node_modules/fast-glob/out/providers/filters/entry.d.ts b/node_modules/fast-glob/out/providers/filters/entry.d.ts new file mode 100644 index 00000000..23db3539 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/entry.d.ts @@ -0,0 +1,17 @@ +import Settings from '../../settings'; +import { EntryFilterFunction, MicromatchOptions, Pattern } from '../../types'; +export default class EntryFilter { + private readonly _settings; + private readonly _micromatchOptions; + readonly index: Map; + constructor(_settings: Settings, _micromatchOptions: MicromatchOptions); + getFilter(positive: Pattern[], negative: Pattern[]): EntryFilterFunction; + private _filter; + private _isDuplicateEntry; + private _createIndexRecord; + private _onlyFileFilter; + private _onlyDirectoryFilter; + private _isMatchToPatternsSet; + private _isMatchToAbsoluteNegative; + private _isMatchToPatterns; +} diff --git a/node_modules/fast-glob/out/providers/filters/entry.js b/node_modules/fast-glob/out/providers/filters/entry.js new file mode 100644 index 00000000..0c9210c5 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/entry.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + getFilter(positive, negative) { + const [absoluteNegative, relativeNegative] = utils.pattern.partitionAbsoluteAndRelative(negative); + const patterns = { + positive: { + all: utils.pattern.convertPatternsToRe(positive, this._micromatchOptions) + }, + negative: { + absolute: utils.pattern.convertPatternsToRe(absoluteNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })), + relative: utils.pattern.convertPatternsToRe(relativeNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })) + } + }; + return (entry) => this._filter(entry, patterns); + } + _filter(entry, patterns) { + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._settings.unique && this._isDuplicateEntry(filepath)) { + return false; + } + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + const isMatched = this._isMatchToPatternsSet(filepath, patterns, entry.dirent.isDirectory()); + if (this._settings.unique && isMatched) { + this._createIndexRecord(filepath); + } + return isMatched; + } + _isDuplicateEntry(filepath) { + return this.index.has(filepath); + } + _createIndexRecord(filepath) { + this.index.set(filepath, undefined); + } + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isMatchToPatternsSet(filepath, patterns, isDirectory) { + const isMatched = this._isMatchToPatterns(filepath, patterns.positive.all, isDirectory); + if (!isMatched) { + return false; + } + const isMatchedByRelativeNegative = this._isMatchToPatterns(filepath, patterns.negative.relative, isDirectory); + if (isMatchedByRelativeNegative) { + return false; + } + const isMatchedByAbsoluteNegative = this._isMatchToAbsoluteNegative(filepath, patterns.negative.absolute, isDirectory); + if (isMatchedByAbsoluteNegative) { + return false; + } + return true; + } + _isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } + const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath); + return this._isMatchToPatterns(fullpath, patternsRe, isDirectory); + } + _isMatchToPatterns(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } + // Trying to match files and directories by patterns. + const isMatched = utils.pattern.matchAny(filepath, patternsRe); + // A pattern with a trailling slash can be used for directory matching. + // To apply such pattern, we need to add a tralling slash to the path. + if (!isMatched && isDirectory) { + return utils.pattern.matchAny(filepath + '/', patternsRe); + } + return isMatched; + } +} +exports.default = EntryFilter; diff --git a/node_modules/fast-glob/out/providers/filters/error.d.ts b/node_modules/fast-glob/out/providers/filters/error.d.ts new file mode 100644 index 00000000..170eb251 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/error.d.ts @@ -0,0 +1,8 @@ +import Settings from '../../settings'; +import { ErrorFilterFunction } from '../../types'; +export default class ErrorFilter { + private readonly _settings; + constructor(_settings: Settings); + getFilter(): ErrorFilterFunction; + private _isNonFatalError; +} diff --git a/node_modules/fast-glob/out/providers/filters/error.js b/node_modules/fast-glob/out/providers/filters/error.js new file mode 100644 index 00000000..1c6f2416 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/error.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } +} +exports.default = ErrorFilter; diff --git a/node_modules/fast-glob/out/providers/matchers/matcher.d.ts b/node_modules/fast-glob/out/providers/matchers/matcher.d.ts new file mode 100644 index 00000000..d04c2322 --- /dev/null +++ b/node_modules/fast-glob/out/providers/matchers/matcher.d.ts @@ -0,0 +1,33 @@ +import { Pattern, MicromatchOptions, PatternRe } from '../../types'; +import Settings from '../../settings'; +export type PatternSegment = StaticPatternSegment | DynamicPatternSegment; +type StaticPatternSegment = { + dynamic: false; + pattern: Pattern; +}; +type DynamicPatternSegment = { + dynamic: true; + pattern: Pattern; + patternRe: PatternRe; +}; +export type PatternSection = PatternSegment[]; +export type PatternInfo = { + /** + * Indicates that the pattern has a globstar (more than a single section). + */ + complete: boolean; + pattern: Pattern; + segments: PatternSegment[]; + sections: PatternSection[]; +}; +export default abstract class Matcher { + private readonly _patterns; + private readonly _settings; + private readonly _micromatchOptions; + protected readonly _storage: PatternInfo[]; + constructor(_patterns: Pattern[], _settings: Settings, _micromatchOptions: MicromatchOptions); + private _fillStorage; + private _getPatternSegments; + private _splitSegmentsIntoSections; +} +export {}; diff --git a/node_modules/fast-glob/out/providers/matchers/matcher.js b/node_modules/fast-glob/out/providers/matchers/matcher.js new file mode 100644 index 00000000..eae67c98 --- /dev/null +++ b/node_modules/fast-glob/out/providers/matchers/matcher.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + for (const pattern of this._patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + _getPatternSegments(pattern) { + const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + return { + dynamic: true, + pattern: part, + patternRe: utils.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); + } +} +exports.default = Matcher; diff --git a/node_modules/fast-glob/out/providers/matchers/partial.d.ts b/node_modules/fast-glob/out/providers/matchers/partial.d.ts new file mode 100644 index 00000000..91520f64 --- /dev/null +++ b/node_modules/fast-glob/out/providers/matchers/partial.d.ts @@ -0,0 +1,4 @@ +import Matcher from './matcher'; +export default class PartialMatcher extends Matcher { + match(filepath: string): boolean; +} diff --git a/node_modules/fast-glob/out/providers/matchers/partial.js b/node_modules/fast-glob/out/providers/matchers/partial.js new file mode 100644 index 00000000..1dfffeb5 --- /dev/null +++ b/node_modules/fast-glob/out/providers/matchers/partial.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const matcher_1 = require("./matcher"); +class PartialMatcher extends matcher_1.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + if (!pattern.complete && levels > section.length) { + return true; + } + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + if (!segment.dynamic && segment.pattern === part) { + return true; + } + return false; + }); + if (match) { + return true; + } + } + return false; + } +} +exports.default = PartialMatcher; diff --git a/node_modules/fast-glob/out/providers/provider.d.ts b/node_modules/fast-glob/out/providers/provider.d.ts new file mode 100644 index 00000000..1053460a --- /dev/null +++ b/node_modules/fast-glob/out/providers/provider.d.ts @@ -0,0 +1,19 @@ +import { Task } from '../managers/tasks'; +import Settings from '../settings'; +import { MicromatchOptions, ReaderOptions } from '../types'; +import DeepFilter from './filters/deep'; +import EntryFilter from './filters/entry'; +import ErrorFilter from './filters/error'; +import EntryTransformer from './transformers/entry'; +export default abstract class Provider { + protected readonly _settings: Settings; + readonly errorFilter: ErrorFilter; + readonly entryFilter: EntryFilter; + readonly deepFilter: DeepFilter; + readonly entryTransformer: EntryTransformer; + constructor(_settings: Settings); + abstract read(_task: Task): T; + protected _getRootDirectory(task: Task): string; + protected _getReaderOptions(task: Task): ReaderOptions; + protected _getMicromatchOptions(): MicromatchOptions; +} diff --git a/node_modules/fast-glob/out/providers/provider.js b/node_modules/fast-glob/out/providers/provider.js new file mode 100644 index 00000000..da88ee02 --- /dev/null +++ b/node_modules/fast-glob/out/providers/provider.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const deep_1 = require("./filters/deep"); +const entry_1 = require("./filters/entry"); +const error_1 = require("./filters/error"); +const entry_2 = require("./transformers/entry"); +class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error_1.default(this._settings); + this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry_2.default(this._settings); + } + _getRootDirectory(task) { + return path.resolve(this._settings.cwd, task.base); + } + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } +} +exports.default = Provider; diff --git a/node_modules/fast-glob/out/providers/stream.d.ts b/node_modules/fast-glob/out/providers/stream.d.ts new file mode 100644 index 00000000..3d02a1f4 --- /dev/null +++ b/node_modules/fast-glob/out/providers/stream.d.ts @@ -0,0 +1,11 @@ +/// +import { Readable } from 'stream'; +import { Task } from '../managers/tasks'; +import ReaderStream from '../readers/stream'; +import { ReaderOptions } from '../types'; +import Provider from './provider'; +export default class ProviderStream extends Provider { + protected _reader: ReaderStream; + read(task: Task): Readable; + api(root: string, task: Task, options: ReaderOptions): Readable; +} diff --git a/node_modules/fast-glob/out/providers/stream.js b/node_modules/fast-glob/out/providers/stream.js new file mode 100644 index 00000000..85da62eb --- /dev/null +++ b/node_modules/fast-glob/out/providers/stream.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = require("stream"); +const stream_2 = require("../readers/stream"); +const provider_1 = require("./provider"); +class ProviderStream extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const destination = new stream_1.Readable({ objectMode: true, read: () => { } }); + source + .once('error', (error) => destination.emit('error', error)) + .on('data', (entry) => destination.emit('data', options.transform(entry))) + .once('end', () => destination.emit('end')); + destination + .once('close', () => source.destroy()); + return destination; + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderStream; diff --git a/node_modules/fast-glob/out/providers/sync.d.ts b/node_modules/fast-glob/out/providers/sync.d.ts new file mode 100644 index 00000000..9c0fe1e1 --- /dev/null +++ b/node_modules/fast-glob/out/providers/sync.d.ts @@ -0,0 +1,9 @@ +import { Task } from '../managers/tasks'; +import ReaderSync from '../readers/sync'; +import { Entry, EntryItem, ReaderOptions } from '../types'; +import Provider from './provider'; +export default class ProviderSync extends Provider { + protected _reader: ReaderSync; + read(task: Task): EntryItem[]; + api(root: string, task: Task, options: ReaderOptions): Entry[]; +} diff --git a/node_modules/fast-glob/out/providers/sync.js b/node_modules/fast-glob/out/providers/sync.js new file mode 100644 index 00000000..d70aa1b1 --- /dev/null +++ b/node_modules/fast-glob/out/providers/sync.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const sync_1 = require("../readers/sync"); +const provider_1 = require("./provider"); +class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = this.api(root, task, options); + return entries.map(options.transform); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderSync; diff --git a/node_modules/fast-glob/out/providers/transformers/entry.d.ts b/node_modules/fast-glob/out/providers/transformers/entry.d.ts new file mode 100644 index 00000000..e9b85fa7 --- /dev/null +++ b/node_modules/fast-glob/out/providers/transformers/entry.d.ts @@ -0,0 +1,8 @@ +import Settings from '../../settings'; +import { EntryTransformerFunction } from '../../types'; +export default class EntryTransformer { + private readonly _settings; + constructor(_settings: Settings); + getTransformer(): EntryTransformerFunction; + private _transform; +} diff --git a/node_modules/fast-glob/out/providers/transformers/entry.js b/node_modules/fast-glob/out/providers/transformers/entry.js new file mode 100644 index 00000000..d11903c8 --- /dev/null +++ b/node_modules/fast-glob/out/providers/transformers/entry.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +class EntryTransformer { + constructor(_settings) { + this._settings = _settings; + } + getTransformer() { + return (entry) => this._transform(entry); + } + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils.path.unixify(filepath); + } + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + if (!this._settings.objectMode) { + return filepath; + } + return Object.assign(Object.assign({}, entry), { path: filepath }); + } +} +exports.default = EntryTransformer; diff --git a/node_modules/fast-glob/out/readers/async.d.ts b/node_modules/fast-glob/out/readers/async.d.ts new file mode 100644 index 00000000..fbca4286 --- /dev/null +++ b/node_modules/fast-glob/out/readers/async.d.ts @@ -0,0 +1,10 @@ +import * as fsWalk from '@nodelib/fs.walk'; +import { Entry, ReaderOptions, Pattern } from '../types'; +import Reader from './reader'; +import ReaderStream from './stream'; +export default class ReaderAsync extends Reader> { + protected _walkAsync: typeof fsWalk.walk; + protected _readerStream: ReaderStream; + dynamic(root: string, options: ReaderOptions): Promise; + static(patterns: Pattern[], options: ReaderOptions): Promise; +} diff --git a/node_modules/fast-glob/out/readers/async.js b/node_modules/fast-glob/out/readers/async.js new file mode 100644 index 00000000..d024145b --- /dev/null +++ b/node_modules/fast-glob/out/readers/async.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fsWalk = require("@nodelib/fs.walk"); +const reader_1 = require("./reader"); +const stream_1 = require("./stream"); +class ReaderAsync extends reader_1.default { + constructor() { + super(...arguments); + this._walkAsync = fsWalk.walk; + this._readerStream = new stream_1.default(this._settings); + } + dynamic(root, options) { + return new Promise((resolve, reject) => { + this._walkAsync(root, options, (error, entries) => { + if (error === null) { + resolve(entries); + } + else { + reject(error); + } + }); + }); + } + async static(patterns, options) { + const entries = []; + const stream = this._readerStream.static(patterns, options); + // After #235, replace it with an asynchronous iterator. + return new Promise((resolve, reject) => { + stream.once('error', reject); + stream.on('data', (entry) => entries.push(entry)); + stream.once('end', () => resolve(entries)); + }); + } +} +exports.default = ReaderAsync; diff --git a/node_modules/fast-glob/out/readers/reader.d.ts b/node_modules/fast-glob/out/readers/reader.d.ts new file mode 100644 index 00000000..2af16b67 --- /dev/null +++ b/node_modules/fast-glob/out/readers/reader.d.ts @@ -0,0 +1,15 @@ +/// +import * as fs from 'fs'; +import * as fsStat from '@nodelib/fs.stat'; +import Settings from '../settings'; +import { Entry, ErrnoException, Pattern, ReaderOptions } from '../types'; +export default abstract class Reader { + protected readonly _settings: Settings; + protected readonly _fsStatSettings: fsStat.Settings; + constructor(_settings: Settings); + abstract dynamic(root: string, options: ReaderOptions): T; + abstract static(patterns: Pattern[], options: ReaderOptions): T; + protected _getFullEntryPath(filepath: string): string; + protected _makeEntry(stats: fs.Stats, pattern: Pattern): Entry; + protected _isFatalError(error: ErrnoException): boolean; +} diff --git a/node_modules/fast-glob/out/readers/reader.js b/node_modules/fast-glob/out/readers/reader.js new file mode 100644 index 00000000..7b40255a --- /dev/null +++ b/node_modules/fast-glob/out/readers/reader.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fsStat = require("@nodelib/fs.stat"); +const utils = require("../utils"); +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; + } + return entry; + } + _isFatalError(error) { + return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } +} +exports.default = Reader; diff --git a/node_modules/fast-glob/out/readers/stream.d.ts b/node_modules/fast-glob/out/readers/stream.d.ts new file mode 100644 index 00000000..1c74cac6 --- /dev/null +++ b/node_modules/fast-glob/out/readers/stream.d.ts @@ -0,0 +1,14 @@ +/// +import { Readable } from 'stream'; +import * as fsStat from '@nodelib/fs.stat'; +import * as fsWalk from '@nodelib/fs.walk'; +import { Pattern, ReaderOptions } from '../types'; +import Reader from './reader'; +export default class ReaderStream extends Reader { + protected _walkStream: typeof fsWalk.walkStream; + protected _stat: typeof fsStat.stat; + dynamic(root: string, options: ReaderOptions): Readable; + static(patterns: Pattern[], options: ReaderOptions): Readable; + private _getEntry; + private _getStat; +} diff --git a/node_modules/fast-glob/out/readers/stream.js b/node_modules/fast-glob/out/readers/stream.js new file mode 100644 index 00000000..317c6d5d --- /dev/null +++ b/node_modules/fast-glob/out/readers/stream.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = require("stream"); +const fsStat = require("@nodelib/fs.stat"); +const fsWalk = require("@nodelib/fs.walk"); +const reader_1 = require("./reader"); +class ReaderStream extends reader_1.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk.walkStream; + this._stat = fsStat.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream_1.PassThrough({ objectMode: true }); + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options) + .then((entry) => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + if (index === filepaths.length - 1) { + stream.end(); + } + done(); + }) + .catch(done); + }; + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); + } + return stream; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath) + .then((stats) => this._makeEntry(stats, pattern)) + .catch((error) => { + if (options.errorFilter(error)) { + return null; + } + throw error; + }); + } + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } +} +exports.default = ReaderStream; diff --git a/node_modules/fast-glob/out/readers/sync.d.ts b/node_modules/fast-glob/out/readers/sync.d.ts new file mode 100644 index 00000000..c96ffeed --- /dev/null +++ b/node_modules/fast-glob/out/readers/sync.d.ts @@ -0,0 +1,12 @@ +import * as fsStat from '@nodelib/fs.stat'; +import * as fsWalk from '@nodelib/fs.walk'; +import { Entry, Pattern, ReaderOptions } from '../types'; +import Reader from './reader'; +export default class ReaderSync extends Reader { + protected _walkSync: typeof fsWalk.walkSync; + protected _statSync: typeof fsStat.statSync; + dynamic(root: string, options: ReaderOptions): Entry[]; + static(patterns: Pattern[], options: ReaderOptions): Entry[]; + private _getEntry; + private _getStat; +} diff --git a/node_modules/fast-glob/out/readers/sync.js b/node_modules/fast-glob/out/readers/sync.js new file mode 100644 index 00000000..4704d65d --- /dev/null +++ b/node_modules/fast-glob/out/readers/sync.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fsStat = require("@nodelib/fs.stat"); +const fsWalk = require("@nodelib/fs.walk"); +const reader_1 = require("./reader"); +class ReaderSync extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) { + continue; + } + entries.push(entry); + } + return entries; + } + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } + catch (error) { + if (options.errorFilter(error)) { + return null; + } + throw error; + } + } + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } +} +exports.default = ReaderSync; diff --git a/node_modules/fast-glob/out/settings.d.ts b/node_modules/fast-glob/out/settings.d.ts new file mode 100644 index 00000000..76a74f8a --- /dev/null +++ b/node_modules/fast-glob/out/settings.d.ts @@ -0,0 +1,164 @@ +import { FileSystemAdapter, Pattern } from './types'; +export declare const DEFAULT_FILE_SYSTEM_ADAPTER: FileSystemAdapter; +export type Options = { + /** + * Return the absolute path for entries. + * + * @default false + */ + absolute?: boolean; + /** + * If set to `true`, then patterns without slashes will be matched against + * the basename of the path if it contains slashes. + * + * @default false + */ + baseNameMatch?: boolean; + /** + * Enables Bash-like brace expansion. + * + * @default true + */ + braceExpansion?: boolean; + /** + * Enables a case-sensitive mode for matching files. + * + * @default true + */ + caseSensitiveMatch?: boolean; + /** + * Specifies the maximum number of concurrent requests from a reader to read + * directories. + * + * @default os.cpus().length + */ + concurrency?: number; + /** + * The current working directory in which to search. + * + * @default process.cwd() + */ + cwd?: string; + /** + * Specifies the maximum depth of a read directory relative to the start + * directory. + * + * @default Infinity + */ + deep?: number; + /** + * Allow patterns to match entries that begin with a period (`.`). + * + * @default false + */ + dot?: boolean; + /** + * Enables Bash-like `extglob` functionality. + * + * @default true + */ + extglob?: boolean; + /** + * Indicates whether to traverse descendants of symbolic link directories. + * + * @default true + */ + followSymbolicLinks?: boolean; + /** + * Custom implementation of methods for working with the file system. + * + * @default fs.* + */ + fs?: Partial; + /** + * Enables recursively repeats a pattern containing `**`. + * If `false`, `**` behaves exactly like `*`. + * + * @default true + */ + globstar?: boolean; + /** + * An array of glob patterns to exclude matches. + * This is an alternative way to use negative patterns. + * + * @default [] + */ + ignore?: Pattern[]; + /** + * Mark the directory path with the final slash. + * + * @default false + */ + markDirectories?: boolean; + /** + * Returns objects (instead of strings) describing entries. + * + * @default false + */ + objectMode?: boolean; + /** + * Return only directories. + * + * @default false + */ + onlyDirectories?: boolean; + /** + * Return only files. + * + * @default true + */ + onlyFiles?: boolean; + /** + * Enables an object mode (`objectMode`) with an additional `stats` field. + * + * @default false + */ + stats?: boolean; + /** + * By default this package suppress only `ENOENT` errors. + * Set to `true` to suppress any error. + * + * @default false + */ + suppressErrors?: boolean; + /** + * Throw an error when symbolic link is broken if `true` or safely + * return `lstat` call if `false`. + * + * @default false + */ + throwErrorOnBrokenSymbolicLink?: boolean; + /** + * Ensures that the returned entries are unique. + * + * @default true + */ + unique?: boolean; +}; +export default class Settings { + private readonly _options; + readonly absolute: boolean; + readonly baseNameMatch: boolean; + readonly braceExpansion: boolean; + readonly caseSensitiveMatch: boolean; + readonly concurrency: number; + readonly cwd: string; + readonly deep: number; + readonly dot: boolean; + readonly extglob: boolean; + readonly followSymbolicLinks: boolean; + readonly fs: FileSystemAdapter; + readonly globstar: boolean; + readonly ignore: Pattern[]; + readonly markDirectories: boolean; + readonly objectMode: boolean; + readonly onlyDirectories: boolean; + readonly onlyFiles: boolean; + readonly stats: boolean; + readonly suppressErrors: boolean; + readonly throwErrorOnBrokenSymbolicLink: boolean; + readonly unique: boolean; + constructor(_options?: Options); + private _getValue; + private _getFileSystemMethods; +} diff --git a/node_modules/fast-glob/out/settings.js b/node_modules/fast-glob/out/settings.js new file mode 100644 index 00000000..23f916c8 --- /dev/null +++ b/node_modules/fast-glob/out/settings.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; +const fs = require("fs"); +const os = require("os"); +/** + * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. + * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 + */ +const CPU_COUNT = Math.max(os.cpus().length, 1); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + lstatSync: fs.lstatSync, + stat: fs.stat, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) { + this.onlyFiles = false; + } + if (this.stats) { + this.objectMode = true; + } + // Remove the cast to the array in the next major (#404). + this.ignore = [].concat(this.ignore); + } + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } +} +exports.default = Settings; diff --git a/node_modules/fast-glob/out/types/index.d.ts b/node_modules/fast-glob/out/types/index.d.ts new file mode 100644 index 00000000..6506cafd --- /dev/null +++ b/node_modules/fast-glob/out/types/index.d.ts @@ -0,0 +1,31 @@ +/// +import * as fsWalk from '@nodelib/fs.walk'; +export type ErrnoException = NodeJS.ErrnoException; +export type Entry = fsWalk.Entry; +export type EntryItem = string | Entry; +export type Pattern = string; +export type PatternRe = RegExp; +export type PatternsGroup = Record; +export type ReaderOptions = fsWalk.Options & { + transform(entry: Entry): EntryItem; + deepFilter: DeepFilterFunction; + entryFilter: EntryFilterFunction; + errorFilter: ErrorFilterFunction; + fs: FileSystemAdapter; + stats: boolean; +}; +export type ErrorFilterFunction = fsWalk.ErrorFilterFunction; +export type EntryFilterFunction = fsWalk.EntryFilterFunction; +export type DeepFilterFunction = fsWalk.DeepFilterFunction; +export type EntryTransformerFunction = (entry: Entry) => EntryItem; +export type MicromatchOptions = { + dot?: boolean; + matchBase?: boolean; + nobrace?: boolean; + nocase?: boolean; + noext?: boolean; + noglobstar?: boolean; + posix?: boolean; + strictSlashes?: boolean; +}; +export type FileSystemAdapter = fsWalk.FileSystemAdapter; diff --git a/node_modules/fast-glob/out/types/index.js b/node_modules/fast-glob/out/types/index.js new file mode 100644 index 00000000..c8ad2e54 --- /dev/null +++ b/node_modules/fast-glob/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/fast-glob/out/utils/array.d.ts b/node_modules/fast-glob/out/utils/array.d.ts new file mode 100644 index 00000000..98e73250 --- /dev/null +++ b/node_modules/fast-glob/out/utils/array.d.ts @@ -0,0 +1,2 @@ +export declare function flatten(items: T[][]): T[]; +export declare function splitWhen(items: T[], predicate: (item: T) => boolean): T[][]; diff --git a/node_modules/fast-glob/out/utils/array.js b/node_modules/fast-glob/out/utils/array.js new file mode 100644 index 00000000..50c406e8 --- /dev/null +++ b/node_modules/fast-glob/out/utils/array.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.splitWhen = exports.flatten = void 0; +function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); +} +exports.flatten = flatten; +function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } + else { + result[groupIndex].push(item); + } + } + return result; +} +exports.splitWhen = splitWhen; diff --git a/node_modules/fast-glob/out/utils/errno.d.ts b/node_modules/fast-glob/out/utils/errno.d.ts new file mode 100644 index 00000000..1c08d3ba --- /dev/null +++ b/node_modules/fast-glob/out/utils/errno.d.ts @@ -0,0 +1,2 @@ +import { ErrnoException } from '../types'; +export declare function isEnoentCodeError(error: ErrnoException): boolean; diff --git a/node_modules/fast-glob/out/utils/errno.js b/node_modules/fast-glob/out/utils/errno.js new file mode 100644 index 00000000..f0bd8015 --- /dev/null +++ b/node_modules/fast-glob/out/utils/errno.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEnoentCodeError = void 0; +function isEnoentCodeError(error) { + return error.code === 'ENOENT'; +} +exports.isEnoentCodeError = isEnoentCodeError; diff --git a/node_modules/fast-glob/out/utils/fs.d.ts b/node_modules/fast-glob/out/utils/fs.d.ts new file mode 100644 index 00000000..64c61ce6 --- /dev/null +++ b/node_modules/fast-glob/out/utils/fs.d.ts @@ -0,0 +1,4 @@ +/// +import * as fs from 'fs'; +import { Dirent } from '@nodelib/fs.walk'; +export declare function createDirentFromStats(name: string, stats: fs.Stats): Dirent; diff --git a/node_modules/fast-glob/out/utils/fs.js b/node_modules/fast-glob/out/utils/fs.js new file mode 100644 index 00000000..ace7c74d --- /dev/null +++ b/node_modules/fast-glob/out/utils/fs.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats; diff --git a/node_modules/fast-glob/out/utils/index.d.ts b/node_modules/fast-glob/out/utils/index.d.ts new file mode 100644 index 00000000..f634cad0 --- /dev/null +++ b/node_modules/fast-glob/out/utils/index.d.ts @@ -0,0 +1,8 @@ +import * as array from './array'; +import * as errno from './errno'; +import * as fs from './fs'; +import * as path from './path'; +import * as pattern from './pattern'; +import * as stream from './stream'; +import * as string from './string'; +export { array, errno, fs, path, pattern, stream, string }; diff --git a/node_modules/fast-glob/out/utils/index.js b/node_modules/fast-glob/out/utils/index.js new file mode 100644 index 00000000..0f92c166 --- /dev/null +++ b/node_modules/fast-glob/out/utils/index.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; +const array = require("./array"); +exports.array = array; +const errno = require("./errno"); +exports.errno = errno; +const fs = require("./fs"); +exports.fs = fs; +const path = require("./path"); +exports.path = path; +const pattern = require("./pattern"); +exports.pattern = pattern; +const stream = require("./stream"); +exports.stream = stream; +const string = require("./string"); +exports.string = string; diff --git a/node_modules/fast-glob/out/utils/path.d.ts b/node_modules/fast-glob/out/utils/path.d.ts new file mode 100644 index 00000000..0b13f4b4 --- /dev/null +++ b/node_modules/fast-glob/out/utils/path.d.ts @@ -0,0 +1,13 @@ +import { Pattern } from '../types'; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +export declare function unixify(filepath: string): string; +export declare function makeAbsolute(cwd: string, filepath: string): string; +export declare function removeLeadingDotSegment(entry: string): string; +export declare const escape: typeof escapeWindowsPath; +export declare function escapeWindowsPath(pattern: Pattern): Pattern; +export declare function escapePosixPath(pattern: Pattern): Pattern; +export declare const convertPathToPattern: typeof convertWindowsPathToPattern; +export declare function convertWindowsPathToPattern(filepath: string): Pattern; +export declare function convertPosixPathToPattern(filepath: string): Pattern; diff --git a/node_modules/fast-glob/out/utils/path.js b/node_modules/fast-glob/out/utils/path.js new file mode 100644 index 00000000..7b53b397 --- /dev/null +++ b/node_modules/fast-glob/out/utils/path.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0; +const os = require("os"); +const path = require("path"); +const IS_WINDOWS_PLATFORM = os.platform() === 'win32'; +const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ +/** + * All non-escaped special characters. + * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. + * Windows: (){}[], !+@ before (, ! at the beginning. + */ +const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; +const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; +/** + * The device path (\\.\ or \\?\). + * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths + */ +const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; +/** + * All backslashes except those escaping special characters. + * Windows: !()+@{} + * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions + */ +const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +function unixify(filepath) { + return filepath.replace(/\\/g, '/'); +} +exports.unixify = unixify; +function makeAbsolute(cwd, filepath) { + return path.resolve(cwd, filepath); +} +exports.makeAbsolute = makeAbsolute; +function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + return entry; +} +exports.removeLeadingDotSegment = removeLeadingDotSegment; +exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; +function escapeWindowsPath(pattern) { + return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escapeWindowsPath = escapeWindowsPath; +function escapePosixPath(pattern) { + return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escapePosixPath = escapePosixPath; +exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; +function convertWindowsPathToPattern(filepath) { + return escapeWindowsPath(filepath) + .replace(DOS_DEVICE_PATH_RE, '//$1') + .replace(WINDOWS_BACKSLASHES_RE, '/'); +} +exports.convertWindowsPathToPattern = convertWindowsPathToPattern; +function convertPosixPathToPattern(filepath) { + return escapePosixPath(filepath); +} +exports.convertPosixPathToPattern = convertPosixPathToPattern; diff --git a/node_modules/fast-glob/out/utils/pattern.d.ts b/node_modules/fast-glob/out/utils/pattern.d.ts new file mode 100644 index 00000000..e3598a96 --- /dev/null +++ b/node_modules/fast-glob/out/utils/pattern.d.ts @@ -0,0 +1,49 @@ +import { MicromatchOptions, Pattern, PatternRe } from '../types'; +type PatternTypeOptions = { + braceExpansion?: boolean; + caseSensitiveMatch?: boolean; + extglob?: boolean; +}; +export declare function isStaticPattern(pattern: Pattern, options?: PatternTypeOptions): boolean; +export declare function isDynamicPattern(pattern: Pattern, options?: PatternTypeOptions): boolean; +export declare function convertToPositivePattern(pattern: Pattern): Pattern; +export declare function convertToNegativePattern(pattern: Pattern): Pattern; +export declare function isNegativePattern(pattern: Pattern): boolean; +export declare function isPositivePattern(pattern: Pattern): boolean; +export declare function getNegativePatterns(patterns: Pattern[]): Pattern[]; +export declare function getPositivePatterns(patterns: Pattern[]): Pattern[]; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +export declare function getPatternsInsideCurrentDirectory(patterns: Pattern[]): Pattern[]; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +export declare function getPatternsOutsideCurrentDirectory(patterns: Pattern[]): Pattern[]; +export declare function isPatternRelatedToParentDirectory(pattern: Pattern): boolean; +export declare function getBaseDirectory(pattern: Pattern): string; +export declare function hasGlobStar(pattern: Pattern): boolean; +export declare function endsWithSlashGlobStar(pattern: Pattern): boolean; +export declare function isAffectDepthOfReadingPattern(pattern: Pattern): boolean; +export declare function expandPatternsWithBraceExpansion(patterns: Pattern[]): Pattern[]; +export declare function expandBraceExpansion(pattern: Pattern): Pattern[]; +export declare function getPatternParts(pattern: Pattern, options: MicromatchOptions): Pattern[]; +export declare function makeRe(pattern: Pattern, options: MicromatchOptions): PatternRe; +export declare function convertPatternsToRe(patterns: Pattern[], options: MicromatchOptions): PatternRe[]; +export declare function matchAny(entry: string, patternsRe: PatternRe[]): boolean; +/** + * This package only works with forward slashes as a path separator. + * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + */ +export declare function removeDuplicateSlashes(pattern: string): string; +export declare function partitionAbsoluteAndRelative(patterns: Pattern[]): Pattern[][]; +export declare function isAbsolute(pattern: string): boolean; +export {}; diff --git a/node_modules/fast-glob/out/utils/pattern.js b/node_modules/fast-glob/out/utils/pattern.js new file mode 100644 index 00000000..b2924e78 --- /dev/null +++ b/node_modules/fast-glob/out/utils/pattern.js @@ -0,0 +1,206 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; +const path = require("path"); +const globParent = require("glob-parent"); +const micromatch = require("micromatch"); +const GLOBSTAR = '**'; +const ESCAPE_SYMBOL = '\\'; +const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; +const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; +const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; +const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; +const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; +/** + * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. + * The latter is due to the presence of the device path at the beginning of the UNC path. + */ +const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; +function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); +} +exports.isStaticPattern = isStaticPattern; +function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { + return true; + } + return false; +} +exports.isDynamicPattern = isDynamicPattern; +function hasBraceExpansion(pattern) { + const openingBraceIndex = pattern.indexOf('{'); + if (openingBraceIndex === -1) { + return false; + } + const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); + if (closingBraceIndex === -1) { + return false; + } + const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); + return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); +} +function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; +} +exports.convertToPositivePattern = convertToPositivePattern; +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +exports.convertToNegativePattern = convertToNegativePattern; +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +exports.isNegativePattern = isNegativePattern; +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +exports.isPositivePattern = isPositivePattern; +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +exports.getNegativePatterns = getNegativePatterns; +function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); +} +exports.getPositivePatterns = getPositivePatterns; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); +} +exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); +} +exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; +function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith('..') || pattern.startsWith('./..'); +} +exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; +function getBaseDirectory(pattern) { + return globParent(pattern, { flipBackslashes: false }); +} +exports.getBaseDirectory = getBaseDirectory; +function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); +} +exports.hasGlobStar = hasGlobStar; +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); +} +exports.endsWithSlashGlobStar = endsWithSlashGlobStar; +function isAffectDepthOfReadingPattern(pattern) { + const basename = path.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); +} +exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; +function expandBraceExpansion(pattern) { + const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true }); + /** + * Sort the patterns by length so that the same depth patterns are processed side by side. + * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` + */ + patterns.sort((a, b) => a.length - b.length); + /** + * Micromatch can return an empty string in the case of patterns like `{a,}`. + */ + return patterns.filter((pattern) => pattern !== ''); +} +exports.expandBraceExpansion = expandBraceExpansion; +function getPatternParts(pattern, options) { + let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + if (parts.length === 0) { + parts = [pattern]; + } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + return parts; +} +exports.getPatternParts = getPatternParts; +function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); +} +exports.makeRe = makeRe; +function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); +} +exports.convertPatternsToRe = convertPatternsToRe; +function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); +} +exports.matchAny = matchAny; +/** + * This package only works with forward slashes as a path separator. + * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + */ +function removeDuplicateSlashes(pattern) { + return pattern.replace(DOUBLE_SLASH_RE, '/'); +} +exports.removeDuplicateSlashes = removeDuplicateSlashes; +function partitionAbsoluteAndRelative(patterns) { + const absolute = []; + const relative = []; + for (const pattern of patterns) { + if (isAbsolute(pattern)) { + absolute.push(pattern); + } + else { + relative.push(pattern); + } + } + return [absolute, relative]; +} +exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative; +function isAbsolute(pattern) { + return path.isAbsolute(pattern); +} +exports.isAbsolute = isAbsolute; diff --git a/node_modules/fast-glob/out/utils/stream.d.ts b/node_modules/fast-glob/out/utils/stream.d.ts new file mode 100644 index 00000000..4daf9137 --- /dev/null +++ b/node_modules/fast-glob/out/utils/stream.d.ts @@ -0,0 +1,4 @@ +/// +/// +import { Readable } from 'stream'; +export declare function merge(streams: Readable[]): NodeJS.ReadableStream; diff --git a/node_modules/fast-glob/out/utils/stream.js b/node_modules/fast-glob/out/utils/stream.js new file mode 100644 index 00000000..b32028ce --- /dev/null +++ b/node_modules/fast-glob/out/utils/stream.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.merge = void 0; +const merge2 = require("merge2"); +function merge(streams) { + const mergedStream = merge2(streams); + streams.forEach((stream) => { + stream.once('error', (error) => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; +} +exports.merge = merge; +function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit('close')); +} diff --git a/node_modules/fast-glob/out/utils/string.d.ts b/node_modules/fast-glob/out/utils/string.d.ts new file mode 100644 index 00000000..c8847356 --- /dev/null +++ b/node_modules/fast-glob/out/utils/string.d.ts @@ -0,0 +1,2 @@ +export declare function isString(input: unknown): input is string; +export declare function isEmpty(input: string): boolean; diff --git a/node_modules/fast-glob/out/utils/string.js b/node_modules/fast-glob/out/utils/string.js new file mode 100644 index 00000000..76e7ea54 --- /dev/null +++ b/node_modules/fast-glob/out/utils/string.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEmpty = exports.isString = void 0; +function isString(input) { + return typeof input === 'string'; +} +exports.isString = isString; +function isEmpty(input) { + return input === ''; +} +exports.isEmpty = isEmpty; diff --git a/node_modules/fast-glob/package.json b/node_modules/fast-glob/package.json new file mode 100644 index 00000000..e910de93 --- /dev/null +++ b/node_modules/fast-glob/package.json @@ -0,0 +1,81 @@ +{ + "name": "fast-glob", + "version": "3.3.3", + "description": "It's a very fast and efficient glob library for Node.js", + "license": "MIT", + "repository": "mrmlnc/fast-glob", + "author": { + "name": "Denis Malinochkin", + "url": "https://mrmlnc.com" + }, + "engines": { + "node": ">=8.6.0" + }, + "main": "out/index.js", + "typings": "out/index.d.ts", + "files": [ + "out", + "!out/{benchmark,tests}", + "!out/**/*.map", + "!out/**/*.spec.*" + ], + "keywords": [ + "glob", + "patterns", + "fast", + "implementation" + ], + "devDependencies": { + "@nodelib/fs.macchiato": "^1.0.1", + "@types/glob-parent": "^5.1.0", + "@types/merge2": "^1.1.4", + "@types/micromatch": "^4.0.0", + "@types/mocha": "^5.2.7", + "@types/node": "^14.18.53", + "@types/picomatch": "^2.3.0", + "@types/sinon": "^7.5.0", + "bencho": "^0.1.1", + "eslint": "^6.5.1", + "eslint-config-mrmlnc": "^1.1.0", + "execa": "^7.1.1", + "fast-glob": "^3.0.4", + "fdir": "6.0.1", + "glob": "^10.0.0", + "hereby": "^1.8.1", + "mocha": "^6.2.1", + "rimraf": "^5.0.0", + "sinon": "^7.5.0", + "snap-shot-it": "^7.9.10", + "typescript": "^4.9.5" + }, + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "scripts": { + "clean": "rimraf out", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "test:e2e": "mocha \"out/**/*.e2e.js\" -s 0", + "test:e2e:sync": "mocha \"out/**/*.e2e.js\" -s 0 --grep \"\\(sync\\)\"", + "test:e2e:async": "mocha \"out/**/*.e2e.js\" -s 0 --grep \"\\(async\\)\"", + "test:e2e:stream": "mocha \"out/**/*.e2e.js\" -s 0 --grep \"\\(stream\\)\"", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile -- -- --sourceMap --watch", + "bench:async": "npm run bench:product:async && npm run bench:regression:async", + "bench:stream": "npm run bench:product:stream && npm run bench:regression:stream", + "bench:sync": "npm run bench:product:sync && npm run bench:regression:sync", + "bench:product": "npm run bench:product:async && npm run bench:product:sync && npm run bench:product:stream", + "bench:product:async": "hereby bench:product:async", + "bench:product:sync": "hereby bench:product:sync", + "bench:product:stream": "hereby bench:product:stream", + "bench:regression": "npm run bench:regression:async && npm run bench:regression:sync && npm run bench:regression:stream", + "bench:regression:async": "hereby bench:regression:async", + "bench:regression:sync": "hereby bench:regression:sync", + "bench:regression:stream": "hereby bench:regression:stream" + } +} diff --git a/node_modules/fast-json-stable-stringify/.eslintrc.yml b/node_modules/fast-json-stable-stringify/.eslintrc.yml new file mode 100644 index 00000000..1c77b0d4 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/.eslintrc.yml @@ -0,0 +1,26 @@ +extends: eslint:recommended +env: + node: true + browser: true +rules: + block-scoped-var: 2 + callback-return: 2 + dot-notation: 2 + indent: 2 + linebreak-style: [2, unix] + new-cap: 2 + no-console: [2, allow: [warn, error]] + no-else-return: 2 + no-eq-null: 2 + no-fallthrough: 2 + no-invalid-this: 2 + no-return-assign: 2 + no-shadow: 1 + no-trailing-spaces: 2 + no-use-before-define: [2, nofunc] + quotes: [2, single, avoid-escape] + semi: [2, always] + strict: [2, global] + valid-jsdoc: [2, requireReturn: false] + no-control-regex: 0 + no-useless-escape: 2 diff --git a/node_modules/fast-json-stable-stringify/.github/FUNDING.yml b/node_modules/fast-json-stable-stringify/.github/FUNDING.yml new file mode 100644 index 00000000..61f9daa9 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/.github/FUNDING.yml @@ -0,0 +1 @@ +tidelift: "npm/fast-json-stable-stringify" diff --git a/node_modules/fast-json-stable-stringify/.travis.yml b/node_modules/fast-json-stable-stringify/.travis.yml new file mode 100644 index 00000000..b61e8f0d --- /dev/null +++ b/node_modules/fast-json-stable-stringify/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "8" + - "10" + - "12" + - "13" +after_script: + - coveralls < coverage/lcov.info diff --git a/node_modules/fast-json-stable-stringify/LICENSE b/node_modules/fast-json-stable-stringify/LICENSE new file mode 100644 index 00000000..c932223b --- /dev/null +++ b/node_modules/fast-json-stable-stringify/LICENSE @@ -0,0 +1,21 @@ +This software is released under the MIT license: + +Copyright (c) 2017 Evgeny Poberezkin +Copyright (c) 2013 James Halliday + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/fast-json-stable-stringify/README.md b/node_modules/fast-json-stable-stringify/README.md new file mode 100644 index 00000000..02cf49ff --- /dev/null +++ b/node_modules/fast-json-stable-stringify/README.md @@ -0,0 +1,131 @@ +# fast-json-stable-stringify + +Deterministic `JSON.stringify()` - a faster version of [@substack](https://github.com/substack)'s json-stable-strigify without [jsonify](https://github.com/substack/jsonify). + +You can also pass in a custom comparison function. + +[![Build Status](https://travis-ci.org/epoberezkin/fast-json-stable-stringify.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-json-stable-stringify) +[![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-json-stable-stringify/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-json-stable-stringify?branch=master) + +# example + +``` js +var stringify = require('fast-json-stable-stringify'); +var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; +console.log(stringify(obj)); +``` + +output: + +``` +{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8} +``` + + +# methods + +``` js +var stringify = require('fast-json-stable-stringify') +``` + +## var str = stringify(obj, opts) + +Return a deterministic stringified string `str` from the object `obj`. + + +## options + +### cmp + +If `opts` is given, you can supply an `opts.cmp` to have a custom comparison +function for object keys. Your function `opts.cmp` is called with these +parameters: + +``` js +opts.cmp({ key: akey, value: avalue }, { key: bkey, value: bvalue }) +``` + +For example, to sort on the object key names in reverse order you could write: + +``` js +var stringify = require('fast-json-stable-stringify'); + +var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; +var s = stringify(obj, function (a, b) { + return a.key < b.key ? 1 : -1; +}); +console.log(s); +``` + +which results in the output string: + +``` +{"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3} +``` + +Or if you wanted to sort on the object values in reverse order, you could write: + +``` +var stringify = require('fast-json-stable-stringify'); + +var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 }; +var s = stringify(obj, function (a, b) { + return a.value < b.value ? 1 : -1; +}); +console.log(s); +``` + +which outputs: + +``` +{"d":6,"c":5,"b":[{"z":3,"y":2,"x":1},9],"a":10} +``` + +### cycles + +Pass `true` in `opts.cycles` to stringify circular property as `__cycle__` - the result will not be a valid JSON string in this case. + +TypeError will be thrown in case of circular object without this option. + + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install fast-json-stable-stringify +``` + + +# benchmark + +To run benchmark (requires Node.js 6+): +``` +node benchmark +``` + +Results: +``` +fast-json-stable-stringify x 17,189 ops/sec ±1.43% (83 runs sampled) +json-stable-stringify x 13,634 ops/sec ±1.39% (85 runs sampled) +fast-stable-stringify x 20,212 ops/sec ±1.20% (84 runs sampled) +faster-stable-stringify x 15,549 ops/sec ±1.12% (84 runs sampled) +The fastest is fast-stable-stringify +``` + + +## Enterprise support + +fast-json-stable-stringify package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-json-stable-stringify?utm_source=npm-fast-json-stable-stringify&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. + + +## Security contact + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. + + +# license + +[MIT](https://github.com/epoberezkin/fast-json-stable-stringify/blob/master/LICENSE) diff --git a/node_modules/fast-json-stable-stringify/benchmark/index.js b/node_modules/fast-json-stable-stringify/benchmark/index.js new file mode 100644 index 00000000..e725f9fc --- /dev/null +++ b/node_modules/fast-json-stable-stringify/benchmark/index.js @@ -0,0 +1,31 @@ +'use strict'; + +const Benchmark = require('benchmark'); +const suite = new Benchmark.Suite; +const testData = require('./test.json'); + + +const stringifyPackages = { + // 'JSON.stringify': JSON.stringify, + 'fast-json-stable-stringify': require('../index'), + 'json-stable-stringify': true, + 'fast-stable-stringify': true, + 'faster-stable-stringify': true +}; + + +for (const name in stringifyPackages) { + let func = stringifyPackages[name]; + if (func === true) func = require(name); + + suite.add(name, function() { + func(testData); + }); +} + +suite + .on('cycle', (event) => console.log(String(event.target))) + .on('complete', function () { + console.log('The fastest is ' + this.filter('fastest').map('name')); + }) + .run({async: true}); diff --git a/node_modules/fast-json-stable-stringify/benchmark/test.json b/node_modules/fast-json-stable-stringify/benchmark/test.json new file mode 100644 index 00000000..c9118c11 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/benchmark/test.json @@ -0,0 +1,137 @@ +[ + { + "_id": "59ef4a83ee8364808d761beb", + "index": 0, + "guid": "e50ffae9-7128-4148-9ee5-40c3fc523c5d", + "isActive": false, + "balance": "$2,341.81", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "brown", + "name": "Carey Savage", + "gender": "female", + "company": "VERAQ", + "email": "careysavage@veraq.com", + "phone": "+1 (897) 574-3014", + "address": "458 Willow Street, Henrietta, California, 7234", + "about": "Nisi reprehenderit nulla ad officia pariatur non dolore laboris irure cupidatat laborum. Minim eu ex Lorem adipisicing exercitation irure minim sunt est enim mollit incididunt voluptate nulla. Ut mollit anim reprehenderit et aliqua ex esse aliquip. Aute sit duis deserunt do incididunt consequat minim qui dolor commodo deserunt et voluptate.\r\n", + "registered": "2014-05-21T01:56:51 -01:00", + "latitude": 63.89502, + "longitude": 62.369807, + "tags": [ + "nostrud", + "nisi", + "consectetur", + "ullamco", + "cupidatat", + "culpa", + "commodo" + ], + "friends": [ + { + "id": 0, + "name": "Henry Walls" + }, + { + "id": 1, + "name": "Janice Baker" + }, + { + "id": 2, + "name": "Russell Bush" + } + ], + "greeting": "Hello, Carey Savage! You have 4 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "59ef4a83ff5774a691454e89", + "index": 1, + "guid": "2bee9efc-4095-4c2e-87ef-d08c8054c89d", + "isActive": true, + "balance": "$1,618.15", + "picture": "http://placehold.it/32x32", + "age": 35, + "eyeColor": "blue", + "name": "Elinor Pearson", + "gender": "female", + "company": "FLEXIGEN", + "email": "elinorpearson@flexigen.com", + "phone": "+1 (923) 548-3751", + "address": "600 Bayview Avenue, Draper, Montana, 3088", + "about": "Mollit commodo ea sit Lorem velit. Irure anim esse Lorem sint quis officia ut. Aliqua nisi dolore in aute deserunt mollit ex ea in mollit.\r\n", + "registered": "2017-04-22T07:58:41 -01:00", + "latitude": -87.824919, + "longitude": 69.538927, + "tags": [ + "fugiat", + "labore", + "proident", + "quis", + "eiusmod", + "qui", + "est" + ], + "friends": [ + { + "id": 0, + "name": "Massey Wagner" + }, + { + "id": 1, + "name": "Marcella Ferrell" + }, + { + "id": 2, + "name": "Evans Mckee" + } + ], + "greeting": "Hello, Elinor Pearson! You have 3 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "59ef4a839ec8a4be4430b36b", + "index": 2, + "guid": "ddd6e8c0-95bd-416d-8b46-a768d6363809", + "isActive": false, + "balance": "$2,046.95", + "picture": "http://placehold.it/32x32", + "age": 40, + "eyeColor": "green", + "name": "Irwin Davidson", + "gender": "male", + "company": "DANJA", + "email": "irwindavidson@danja.com", + "phone": "+1 (883) 537-2041", + "address": "439 Cook Street, Chapin, Kentucky, 7398", + "about": "Irure velit non commodo aliqua exercitation ut nostrud minim magna. Dolor ad ad ut irure eu. Non pariatur dolor eiusmod ipsum do et exercitation cillum. Et amet laboris minim eiusmod ullamco magna ea reprehenderit proident sunt.\r\n", + "registered": "2016-09-01T07:49:08 -01:00", + "latitude": -49.803812, + "longitude": 104.93279, + "tags": [ + "consequat", + "enim", + "quis", + "magna", + "est", + "culpa", + "tempor" + ], + "friends": [ + { + "id": 0, + "name": "Ruth Hansen" + }, + { + "id": 1, + "name": "Kathrine Austin" + }, + { + "id": 2, + "name": "Rivera Munoz" + } + ], + "greeting": "Hello, Irwin Davidson! You have 2 unread messages.", + "favoriteFruit": "banana" + } +] diff --git a/node_modules/fast-json-stable-stringify/example/key_cmp.js b/node_modules/fast-json-stable-stringify/example/key_cmp.js new file mode 100644 index 00000000..d5f66752 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/example/key_cmp.js @@ -0,0 +1,7 @@ +var stringify = require('../'); + +var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; +var s = stringify(obj, function (a, b) { + return a.key < b.key ? 1 : -1; +}); +console.log(s); diff --git a/node_modules/fast-json-stable-stringify/example/nested.js b/node_modules/fast-json-stable-stringify/example/nested.js new file mode 100644 index 00000000..9a672fc6 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/example/nested.js @@ -0,0 +1,3 @@ +var stringify = require('../'); +var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; +console.log(stringify(obj)); diff --git a/node_modules/fast-json-stable-stringify/example/str.js b/node_modules/fast-json-stable-stringify/example/str.js new file mode 100644 index 00000000..9b4b3cd2 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/example/str.js @@ -0,0 +1,3 @@ +var stringify = require('../'); +var obj = { c: 6, b: [4,5], a: 3 }; +console.log(stringify(obj)); diff --git a/node_modules/fast-json-stable-stringify/example/value_cmp.js b/node_modules/fast-json-stable-stringify/example/value_cmp.js new file mode 100644 index 00000000..09f1c5f7 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/example/value_cmp.js @@ -0,0 +1,7 @@ +var stringify = require('../'); + +var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 }; +var s = stringify(obj, function (a, b) { + return a.value < b.value ? 1 : -1; +}); +console.log(s); diff --git a/node_modules/fast-json-stable-stringify/index.d.ts b/node_modules/fast-json-stable-stringify/index.d.ts new file mode 100644 index 00000000..23e46caf --- /dev/null +++ b/node_modules/fast-json-stable-stringify/index.d.ts @@ -0,0 +1,4 @@ +declare module 'fast-json-stable-stringify' { + function stringify(obj: any): string; + export = stringify; +} diff --git a/node_modules/fast-json-stable-stringify/index.js b/node_modules/fast-json-stable-stringify/index.js new file mode 100644 index 00000000..c44e6a41 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/index.js @@ -0,0 +1,59 @@ +'use strict'; + +module.exports = function (data, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { cmp: opts }; + var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; + + var cmp = opts.cmp && (function (f) { + return function (node) { + return function (a, b) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); + + var seen = []; + return (function stringify (node) { + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } + + if (node === undefined) return; + if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; + if (typeof node !== 'object') return JSON.stringify(node); + + var i, out; + if (Array.isArray(node)) { + out = '['; + for (i = 0; i < node.length; i++) { + if (i) out += ','; + out += stringify(node[i]) || 'null'; + } + return out + ']'; + } + + if (node === null) return 'null'; + + if (seen.indexOf(node) !== -1) { + if (cycles) return JSON.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } + + var seenIndex = seen.push(node) - 1; + var keys = Object.keys(node).sort(cmp && cmp(node)); + out = ''; + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node[key]); + + if (!value) continue; + if (out) out += ','; + out += JSON.stringify(key) + ':' + value; + } + seen.splice(seenIndex, 1); + return '{' + out + '}'; + })(data); +}; diff --git a/node_modules/fast-json-stable-stringify/package.json b/node_modules/fast-json-stable-stringify/package.json new file mode 100644 index 00000000..ad2c8bff --- /dev/null +++ b/node_modules/fast-json-stable-stringify/package.json @@ -0,0 +1,52 @@ +{ + "name": "fast-json-stable-stringify", + "version": "2.1.0", + "description": "deterministic `JSON.stringify()` - a faster version of substack's json-stable-strigify without jsonify", + "main": "index.js", + "types": "index.d.ts", + "dependencies": {}, + "devDependencies": { + "benchmark": "^2.1.4", + "coveralls": "^3.0.0", + "eslint": "^6.7.0", + "fast-stable-stringify": "latest", + "faster-stable-stringify": "latest", + "json-stable-stringify": "latest", + "nyc": "^14.1.0", + "pre-commit": "^1.2.2", + "tape": "^4.11.0" + }, + "scripts": { + "eslint": "eslint index.js test", + "test-spec": "tape test/*.js", + "test": "npm run eslint && nyc npm run test-spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/epoberezkin/fast-json-stable-stringify.git" + }, + "homepage": "https://github.com/epoberezkin/fast-json-stable-stringify", + "keywords": [ + "json", + "stringify", + "deterministic", + "hash", + "stable" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "nyc": { + "exclude": [ + "test", + "node_modules" + ], + "reporter": [ + "lcov", + "text-summary" + ] + } +} diff --git a/node_modules/fast-json-stable-stringify/test/cmp.js b/node_modules/fast-json-stable-stringify/test/cmp.js new file mode 100644 index 00000000..4efd6b59 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/test/cmp.js @@ -0,0 +1,13 @@ +'use strict'; + +var test = require('tape'); +var stringify = require('../'); + +test('custom comparison function', function (t) { + t.plan(1); + var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; + var s = stringify(obj, function (a, b) { + return a.key < b.key ? 1 : -1; + }); + t.equal(s, '{"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3}'); +}); diff --git a/node_modules/fast-json-stable-stringify/test/nested.js b/node_modules/fast-json-stable-stringify/test/nested.js new file mode 100644 index 00000000..167a358e --- /dev/null +++ b/node_modules/fast-json-stable-stringify/test/nested.js @@ -0,0 +1,44 @@ +'use strict'; + +var test = require('tape'); +var stringify = require('../'); + +test('nested', function (t) { + t.plan(1); + var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; + t.equal(stringify(obj), '{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}'); +}); + +test('cyclic (default)', function (t) { + t.plan(1); + var one = { a: 1 }; + var two = { a: 2, one: one }; + one.two = two; + try { + stringify(one); + } catch (ex) { + t.equal(ex.toString(), 'TypeError: Converting circular structure to JSON'); + } +}); + +test('cyclic (specifically allowed)', function (t) { + t.plan(1); + var one = { a: 1 }; + var two = { a: 2, one: one }; + one.two = two; + t.equal(stringify(one, {cycles:true}), '{"a":1,"two":{"a":2,"one":"__cycle__"}}'); +}); + +test('repeated non-cyclic value', function(t) { + t.plan(1); + var one = { x: 1 }; + var two = { a: one, b: one }; + t.equal(stringify(two), '{"a":{"x":1},"b":{"x":1}}'); +}); + +test('acyclic but with reused obj-property pointers', function (t) { + t.plan(1); + var x = { a: 1 }; + var y = { b: x, c: x }; + t.equal(stringify(y), '{"b":{"a":1},"c":{"a":1}}'); +}); diff --git a/node_modules/fast-json-stable-stringify/test/str.js b/node_modules/fast-json-stable-stringify/test/str.js new file mode 100644 index 00000000..99a9ade1 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/test/str.js @@ -0,0 +1,46 @@ +'use strict'; + +var test = require('tape'); +var stringify = require('../'); + +test('simple object', function (t) { + t.plan(1); + var obj = { c: 6, b: [4,5], a: 3, z: null }; + t.equal(stringify(obj), '{"a":3,"b":[4,5],"c":6,"z":null}'); +}); + +test('object with undefined', function (t) { + t.plan(1); + var obj = { a: 3, z: undefined }; + t.equal(stringify(obj), '{"a":3}'); +}); + +test('object with null', function (t) { + t.plan(1); + var obj = { a: 3, z: null }; + t.equal(stringify(obj), '{"a":3,"z":null}'); +}); + +test('object with NaN and Infinity', function (t) { + t.plan(1); + var obj = { a: 3, b: NaN, c: Infinity }; + t.equal(stringify(obj), '{"a":3,"b":null,"c":null}'); +}); + +test('array with undefined', function (t) { + t.plan(1); + var obj = [4, undefined, 6]; + t.equal(stringify(obj), '[4,null,6]'); +}); + +test('object with empty string', function (t) { + t.plan(1); + var obj = { a: 3, z: '' }; + t.equal(stringify(obj), '{"a":3,"z":""}'); +}); + +test('array with empty string', function (t) { + t.plan(1); + var obj = [4, '', 6]; + t.equal(stringify(obj), '[4,"",6]'); +}); diff --git a/node_modules/fast-json-stable-stringify/test/to-json.js b/node_modules/fast-json-stable-stringify/test/to-json.js new file mode 100644 index 00000000..2fb2cfa3 --- /dev/null +++ b/node_modules/fast-json-stable-stringify/test/to-json.js @@ -0,0 +1,22 @@ +'use strict'; + +var test = require('tape'); +var stringify = require('../'); + +test('toJSON function', function (t) { + t.plan(1); + var obj = { one: 1, two: 2, toJSON: function() { return { one: 1 }; } }; + t.equal(stringify(obj), '{"one":1}' ); +}); + +test('toJSON returns string', function (t) { + t.plan(1); + var obj = { one: 1, two: 2, toJSON: function() { return 'one'; } }; + t.equal(stringify(obj), '"one"'); +}); + +test('toJSON returns array', function (t) { + t.plan(1); + var obj = { one: 1, two: 2, toJSON: function() { return ['one']; } }; + t.equal(stringify(obj), '["one"]'); +}); diff --git a/node_modules/fast-levenshtein/LICENSE.md b/node_modules/fast-levenshtein/LICENSE.md new file mode 100644 index 00000000..6212406b --- /dev/null +++ b/node_modules/fast-levenshtein/LICENSE.md @@ -0,0 +1,25 @@ +(MIT License) + +Copyright (c) 2013 [Ramesh Nair](http://www.hiddentao.com/) + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/fast-levenshtein/README.md b/node_modules/fast-levenshtein/README.md new file mode 100644 index 00000000..a7789953 --- /dev/null +++ b/node_modules/fast-levenshtein/README.md @@ -0,0 +1,104 @@ +# fast-levenshtein - Levenshtein algorithm in Javascript + +[![Build Status](https://secure.travis-ci.org/hiddentao/fast-levenshtein.png)](http://travis-ci.org/hiddentao/fast-levenshtein) +[![NPM module](https://badge.fury.io/js/fast-levenshtein.png)](https://badge.fury.io/js/fast-levenshtein) +[![NPM downloads](https://img.shields.io/npm/dm/fast-levenshtein.svg?maxAge=2592000)](https://www.npmjs.com/package/fast-levenshtein) +[![Follow on Twitter](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/hiddentao) + +An efficient Javascript implementation of the [Levenshtein algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) with locale-specific collator support. + +## Features + +* Works in node.js and in the browser. +* Better performance than other implementations by not needing to store the whole matrix ([more info](http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm)). +* Locale-sensitive string comparisions if needed. +* Comprehensive test suite and performance benchmark. +* Small: <1 KB minified and gzipped + +## Installation + +### node.js + +Install using [npm](http://npmjs.org/): + +```bash +$ npm install fast-levenshtein +``` + +### Browser + +Using bower: + +```bash +$ bower install fast-levenshtein +``` + +If you are not using any module loader system then the API will then be accessible via the `window.Levenshtein` object. + +## Examples + +**Default usage** + +```javascript +var levenshtein = require('fast-levenshtein'); + +var distance = levenshtein.get('back', 'book'); // 2 +var distance = levenshtein.get('我愛你', '我叫你'); // 1 +``` + +**Locale-sensitive string comparisons** + +It supports using [Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) for locale-sensitive string comparisons: + +```javascript +var levenshtein = require('fast-levenshtein'); + +levenshtein.get('mikailovitch', 'Mikhaïlovitch', { useCollator: true}); +// 1 +``` + +## Building and Testing + +To build the code and run the tests: + +```bash +$ npm install -g grunt-cli +$ npm install +$ npm run build +``` + +## Performance + +_Thanks to [Titus Wormer](https://github.com/wooorm) for [encouraging me](https://github.com/hiddentao/fast-levenshtein/issues/1) to do this._ + +Benchmarked against other node.js levenshtein distance modules (on Macbook Air 2012, Core i7, 8GB RAM): + +```bash +Running suite Implementation comparison [benchmark/speed.js]... +>> levenshtein-edit-distance x 234 ops/sec ±3.02% (73 runs sampled) +>> levenshtein-component x 422 ops/sec ±4.38% (83 runs sampled) +>> levenshtein-deltas x 283 ops/sec ±3.83% (78 runs sampled) +>> natural x 255 ops/sec ±0.76% (88 runs sampled) +>> levenshtein x 180 ops/sec ±3.55% (86 runs sampled) +>> fast-levenshtein x 1,792 ops/sec ±2.72% (95 runs sampled) +Benchmark done. +Fastest test is fast-levenshtein at 4.2x faster than levenshtein-component +``` + +You can run this benchmark yourself by doing: + +```bash +$ npm install +$ npm run build +$ npm run benchmark +``` + +## Contributing + +If you wish to submit a pull request please update and/or create new tests for any changes you make and ensure the grunt build passes. + +See [CONTRIBUTING.md](https://github.com/hiddentao/fast-levenshtein/blob/master/CONTRIBUTING.md) for details. + +## License + +MIT - see [LICENSE.md](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md) diff --git a/node_modules/fast-levenshtein/levenshtein.js b/node_modules/fast-levenshtein/levenshtein.js new file mode 100644 index 00000000..dbe36280 --- /dev/null +++ b/node_modules/fast-levenshtein/levenshtein.js @@ -0,0 +1,136 @@ +(function() { + 'use strict'; + + var collator; + try { + collator = (typeof Intl !== "undefined" && typeof Intl.Collator !== "undefined") ? Intl.Collator("generic", { sensitivity: "base" }) : null; + } catch (err){ + console.log("Collator could not be initialized and wouldn't be used"); + } + // arrays to re-use + var prevRow = [], + str2Char = []; + + /** + * Based on the algorithm at http://en.wikipedia.org/wiki/Levenshtein_distance. + */ + var Levenshtein = { + /** + * Calculate levenshtein distance of the two strings. + * + * @param str1 String the first string. + * @param str2 String the second string. + * @param [options] Additional options. + * @param [options.useCollator] Use `Intl.Collator` for locale-sensitive string comparison. + * @return Integer the levenshtein distance (0 and above). + */ + get: function(str1, str2, options) { + var useCollator = (options && collator && options.useCollator); + + var str1Len = str1.length, + str2Len = str2.length; + + // base cases + if (str1Len === 0) return str2Len; + if (str2Len === 0) return str1Len; + + // two rows + var curCol, nextCol, i, j, tmp; + + // initialise previous row + for (i=0; i tmp) { + nextCol = tmp; + } + // deletion + tmp = prevRow[j + 1] + 1; + if (nextCol > tmp) { + nextCol = tmp; + } + + // copy current col value into previous (in preparation for next iteration) + prevRow[j] = curCol; + } + + // copy last col value into previous (in preparation for next iteration) + prevRow[j] = nextCol; + } + } + else { + // calculate current row distance from previous row without collator + for (i = 0; i < str1Len; ++i) { + nextCol = i + 1; + + for (j = 0; j < str2Len; ++j) { + curCol = nextCol; + + // substution + strCmp = str1.charCodeAt(i) === str2Char[j]; + + nextCol = prevRow[j] + (strCmp ? 0 : 1); + + // insertion + tmp = curCol + 1; + if (nextCol > tmp) { + nextCol = tmp; + } + // deletion + tmp = prevRow[j + 1] + 1; + if (nextCol > tmp) { + nextCol = tmp; + } + + // copy current col value into previous (in preparation for next iteration) + prevRow[j] = curCol; + } + + // copy last col value into previous (in preparation for next iteration) + prevRow[j] = nextCol; + } + } + return nextCol; + } + + }; + + // amd + if (typeof define !== "undefined" && define !== null && define.amd) { + define(function() { + return Levenshtein; + }); + } + // commonjs + else if (typeof module !== "undefined" && module !== null && typeof exports !== "undefined" && module.exports === exports) { + module.exports = Levenshtein; + } + // web worker + else if (typeof self !== "undefined" && typeof self.postMessage === 'function' && typeof self.importScripts === 'function') { + self.Levenshtein = Levenshtein; + } + // browser main thread + else if (typeof window !== "undefined" && window !== null) { + window.Levenshtein = Levenshtein; + } +}()); + diff --git a/node_modules/fast-levenshtein/package.json b/node_modules/fast-levenshtein/package.json new file mode 100644 index 00000000..5b4736d4 --- /dev/null +++ b/node_modules/fast-levenshtein/package.json @@ -0,0 +1,39 @@ +{ + "name": "fast-levenshtein", + "version": "2.0.6", + "description": "Efficient implementation of Levenshtein algorithm with locale-specific collator support.", + "main": "levenshtein.js", + "files": [ + "levenshtein.js" + ], + "scripts": { + "build": "grunt build", + "prepublish": "npm run build", + "benchmark": "grunt benchmark", + "test": "mocha" + }, + "devDependencies": { + "chai": "~1.5.0", + "grunt": "~0.4.1", + "grunt-benchmark": "~0.2.0", + "grunt-cli": "^1.2.0", + "grunt-contrib-jshint": "~0.4.3", + "grunt-contrib-uglify": "~0.2.0", + "grunt-mocha-test": "~0.2.2", + "grunt-npm-install": "~0.1.0", + "load-grunt-tasks": "~0.6.0", + "lodash": "^4.0.1", + "mocha": "~1.9.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/hiddentao/fast-levenshtein.git" + }, + "keywords": [ + "levenshtein", + "distance", + "string" + ], + "author": "Ramesh Nair (http://www.hiddentao.com/)", + "license": "MIT" +} diff --git a/node_modules/fastq/.github/dependabot.yml b/node_modules/fastq/.github/dependabot.yml new file mode 100644 index 00000000..7e7cbe1b --- /dev/null +++ b/node_modules/fastq/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 +updates: +- package-ecosystem: npm + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 + ignore: + - dependency-name: standard + versions: + - 16.0.3 diff --git a/node_modules/fastq/.github/workflows/ci.yml b/node_modules/fastq/.github/workflows/ci.yml new file mode 100644 index 00000000..09dc7a3d --- /dev/null +++ b/node_modules/fastq/.github/workflows/ci.yml @@ -0,0 +1,75 @@ +name: ci + +on: [push, pull_request] + +jobs: + legacy: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: ['0.10', '0.12', 4.x, 6.x, 8.x, 10.x, 12.x, 13.x, 14.x, 15.x, 16.x] + + steps: + - uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + + - name: Install + run: | + npm install --production && npm install tape + + - name: Run tests + run: | + npm run legacy + + test: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [18.x, 20.x, 22.x] + + steps: + - uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node-version }} + + - name: Install + run: | + npm install + + - name: Run tests + run: | + npm run test + + types: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: Install + run: | + npm install + + - name: Run types tests + run: | + npm run typescript diff --git a/node_modules/fastq/LICENSE b/node_modules/fastq/LICENSE new file mode 100644 index 00000000..27c7bb46 --- /dev/null +++ b/node_modules/fastq/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015-2020, Matteo Collina + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/fastq/README.md b/node_modules/fastq/README.md new file mode 100644 index 00000000..16441111 --- /dev/null +++ b/node_modules/fastq/README.md @@ -0,0 +1,312 @@ +# fastq + +![ci][ci-url] +[![npm version][npm-badge]][npm-url] + +Fast, in memory work queue. + +Benchmarks (1 million tasks): + +* setImmediate: 812ms +* fastq: 854ms +* async.queue: 1298ms +* neoAsync.queue: 1249ms + +Obtained on node 12.16.1, on a dedicated server. + +If you need zero-overhead series function call, check out +[fastseries](http://npm.im/fastseries). For zero-overhead parallel +function call, check out [fastparallel](http://npm.im/fastparallel). + +[![js-standard-style](https://raw.githubusercontent.com/feross/standard/master/badge.png)](https://github.com/feross/standard) + + * Installation + * Usage + * API + * Licence & copyright + +## Install + +`npm i fastq --save` + +## Usage (callback API) + +```js +'use strict' + +const queue = require('fastq')(worker, 1) + +queue.push(42, function (err, result) { + if (err) { throw err } + console.log('the result is', result) +}) + +function worker (arg, cb) { + cb(null, arg * 2) +} +``` + +## Usage (promise API) + +```js +const queue = require('fastq').promise(worker, 1) + +async function worker (arg) { + return arg * 2 +} + +async function run () { + const result = await queue.push(42) + console.log('the result is', result) +} + +run() +``` + +### Setting "this" + +```js +'use strict' + +const that = { hello: 'world' } +const queue = require('fastq')(that, worker, 1) + +queue.push(42, function (err, result) { + if (err) { throw err } + console.log(this) + console.log('the result is', result) +}) + +function worker (arg, cb) { + console.log(this) + cb(null, arg * 2) +} +``` + +### Using with TypeScript (callback API) + +```ts +'use strict' + +import * as fastq from "fastq"; +import type { queue, done } from "fastq"; + +type Task = { + id: number +} + +const q: queue = fastq(worker, 1) + +q.push({ id: 42}) + +function worker (arg: Task, cb: done) { + console.log(arg.id) + cb(null) +} +``` + +### Using with TypeScript (promise API) + +```ts +'use strict' + +import * as fastq from "fastq"; +import type { queueAsPromised } from "fastq"; + +type Task = { + id: number +} + +const q: queueAsPromised = fastq.promise(asyncWorker, 1) + +q.push({ id: 42}).catch((err) => console.error(err)) + +async function asyncWorker (arg: Task): Promise { + // No need for a try-catch block, fastq handles errors automatically + console.log(arg.id) +} +``` + +## API + +* fastqueue() +* queue#push() +* queue#unshift() +* queue#pause() +* queue#resume() +* queue#idle() +* queue#length() +* queue#getQueue() +* queue#kill() +* queue#killAndDrain() +* queue#error() +* queue#concurrency +* queue#drain +* queue#empty +* queue#saturated +* fastqueue.promise() + +------------------------------------------------------- + +### fastqueue([that], worker, concurrency) + +Creates a new queue. + +Arguments: + +* `that`, optional context of the `worker` function. +* `worker`, worker function, it would be called with `that` as `this`, + if that is specified. +* `concurrency`, number of concurrent tasks that could be executed in + parallel. + +------------------------------------------------------- + +### queue.push(task, done) + +Add a task at the end of the queue. `done(err, result)` will be called +when the task was processed. + +------------------------------------------------------- + +### queue.unshift(task, done) + +Add a task at the beginning of the queue. `done(err, result)` will be called +when the task was processed. + +------------------------------------------------------- + +### queue.pause() + +Pause the processing of tasks. Currently worked tasks are not +stopped. + +------------------------------------------------------- + +### queue.resume() + +Resume the processing of tasks. + +------------------------------------------------------- + +### queue.idle() + +Returns `false` if there are tasks being processed or waiting to be processed. +`true` otherwise. + +------------------------------------------------------- + +### queue.length() + +Returns the number of tasks waiting to be processed (in the queue). + +------------------------------------------------------- + +### queue.getQueue() + +Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks + +------------------------------------------------------- + +### queue.kill() + +Removes all tasks waiting to be processed, and reset `drain` to an empty +function. + +------------------------------------------------------- + +### queue.killAndDrain() + +Same than `kill` but the `drain` function will be called before reset to empty. + +------------------------------------------------------- + +### queue.error(handler) + +Set a global error handler. `handler(err, task)` will be called +each time a task is completed, `err` will be not null if the task has thrown an error. + +------------------------------------------------------- + +### queue.concurrency + +Property that returns the number of concurrent tasks that could be executed in +parallel. It can be altered at runtime. + +------------------------------------------------------- + +### queue.paused + +Property (Read-Only) that returns `true` when the queue is in a paused state. + +------------------------------------------------------- + +### queue.drain + +Function that will be called when the last +item from the queue has been processed by a worker. +It can be altered at runtime. + +------------------------------------------------------- + +### queue.empty + +Function that will be called when the last +item from the queue has been assigned to a worker. +It can be altered at runtime. + +------------------------------------------------------- + +### queue.saturated + +Function that will be called when the queue hits the concurrency +limit. +It can be altered at runtime. + +------------------------------------------------------- + +### fastqueue.promise([that], worker(arg), concurrency) + +Creates a new queue with `Promise` apis. It also offers all the methods +and properties of the object returned by [`fastqueue`](#fastqueue) with the modified +[`push`](#pushPromise) and [`unshift`](#unshiftPromise) methods. + +Node v10+ is required to use the promisified version. + +Arguments: +* `that`, optional context of the `worker` function. +* `worker`, worker function, it would be called with `that` as `this`, + if that is specified. It MUST return a `Promise`. +* `concurrency`, number of concurrent tasks that could be executed in + parallel. + + +#### queue.push(task) => Promise + +Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) +when the task is completed successfully (unsuccessfully). + +This promise could be ignored as it will not lead to a `'unhandledRejection'`. + + +#### queue.unshift(task) => Promise + +Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) +when the task is completed successfully (unsuccessfully). + +This promise could be ignored as it will not lead to a `'unhandledRejection'`. + + +#### queue.drained() => Promise + +Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. + +This promise could be ignored as it will not lead to a `'unhandledRejection'`. + +## License + +ISC + +[ci-url]: https://github.com/mcollina/fastq/workflows/ci/badge.svg +[npm-badge]: https://badge.fury.io/js/fastq.svg +[npm-url]: https://badge.fury.io/js/fastq diff --git a/node_modules/fastq/SECURITY.md b/node_modules/fastq/SECURITY.md new file mode 100644 index 00000000..dd9f1d51 --- /dev/null +++ b/node_modules/fastq/SECURITY.md @@ -0,0 +1,15 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 1.x | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +Please report all vulnerabilities at [https://github.com/mcollina/fastq/security](https://github.com/mcollina/fastq/security). diff --git a/node_modules/fastq/bench.js b/node_modules/fastq/bench.js new file mode 100644 index 00000000..4eaa829f --- /dev/null +++ b/node_modules/fastq/bench.js @@ -0,0 +1,66 @@ +'use strict' + +const max = 1000000 +const fastqueue = require('./')(worker, 1) +const { promisify } = require('util') +const immediate = promisify(setImmediate) +const qPromise = require('./').promise(immediate, 1) +const async = require('async') +const neo = require('neo-async') +const asyncqueue = async.queue(worker, 1) +const neoqueue = neo.queue(worker, 1) + +function bench (func, done) { + const key = max + '*' + func.name + let count = -1 + + console.time(key) + end() + + function end () { + if (++count < max) { + func(end) + } else { + console.timeEnd(key) + if (done) { + done() + } + } + } +} + +function benchFastQ (done) { + fastqueue.push(42, done) +} + +function benchAsyncQueue (done) { + asyncqueue.push(42, done) +} + +function benchNeoQueue (done) { + neoqueue.push(42, done) +} + +function worker (arg, cb) { + setImmediate(cb) +} + +function benchSetImmediate (cb) { + worker(42, cb) +} + +function benchFastQPromise (done) { + qPromise.push(42).then(function () { done() }, done) +} + +function runBench (done) { + async.eachSeries([ + benchSetImmediate, + benchFastQ, + benchNeoQueue, + benchAsyncQueue, + benchFastQPromise + ], bench, done) +} + +runBench(runBench) diff --git a/node_modules/fastq/example.js b/node_modules/fastq/example.js new file mode 100644 index 00000000..665fdc84 --- /dev/null +++ b/node_modules/fastq/example.js @@ -0,0 +1,14 @@ +'use strict' + +/* eslint-disable no-var */ + +var queue = require('./')(worker, 1) + +queue.push(42, function (err, result) { + if (err) { throw err } + console.log('the result is', result) +}) + +function worker (arg, cb) { + cb(null, 42 * 2) +} diff --git a/node_modules/fastq/example.mjs b/node_modules/fastq/example.mjs new file mode 100644 index 00000000..81be789a --- /dev/null +++ b/node_modules/fastq/example.mjs @@ -0,0 +1,11 @@ +import { promise as queueAsPromised } from './queue.js' + +/* eslint-disable */ + +const queue = queueAsPromised(worker, 1) + +console.log('the result is', await queue.push(42)) + +async function worker (arg) { + return 42 * 2 +} diff --git a/node_modules/fastq/index.d.ts b/node_modules/fastq/index.d.ts new file mode 100644 index 00000000..817cdb58 --- /dev/null +++ b/node_modules/fastq/index.d.ts @@ -0,0 +1,57 @@ +declare function fastq(context: C, worker: fastq.worker, concurrency: number): fastq.queue +declare function fastq(worker: fastq.worker, concurrency: number): fastq.queue + +declare namespace fastq { + type worker = (this: C, task: T, cb: fastq.done) => void + type asyncWorker = (this: C, task: T) => Promise + type done = (err: Error | null, result?: R) => void + type errorHandler = (err: Error, task: T) => void + + interface queue { + /** Add a task at the end of the queue. `done(err, result)` will be called when the task was processed. */ + push(task: T, done?: done): void + /** Add a task at the beginning of the queue. `done(err, result)` will be called when the task was processed. */ + unshift(task: T, done?: done): void + /** Pause the processing of tasks. Currently worked tasks are not stopped. */ + pause(): any + /** Resume the processing of tasks. */ + resume(): any + running(): number + /** Returns `false` if there are tasks being processed or waiting to be processed. `true` otherwise. */ + idle(): boolean + /** Returns the number of tasks waiting to be processed (in the queue). */ + length(): number + /** Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks */ + getQueue(): T[] + /** Removes all tasks waiting to be processed, and reset `drain` to an empty function. */ + kill(): any + /** Same than `kill` but the `drain` function will be called before reset to empty. */ + killAndDrain(): any + /** Set a global error handler. `handler(err, task)` will be called each time a task is completed, `err` will be not null if the task has thrown an error. */ + error(handler: errorHandler): void + /** Property that returns the number of concurrent tasks that could be executed in parallel. It can be altered at runtime. */ + concurrency: number + /** Property (Read-Only) that returns `true` when the queue is in a paused state. */ + readonly paused: boolean + /** Function that will be called when the last item from the queue has been processed by a worker. It can be altered at runtime. */ + drain(): any + /** Function that will be called when the last item from the queue has been assigned to a worker. It can be altered at runtime. */ + empty: () => void + /** Function that will be called when the queue hits the concurrency limit. It can be altered at runtime. */ + saturated: () => void + } + + interface queueAsPromised extends queue { + /** Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). */ + push(task: T): Promise + /** Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). */ + unshift(task: T): Promise + /** Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. */ + drained(): Promise + } + + function promise(context: C, worker: fastq.asyncWorker, concurrency: number): fastq.queueAsPromised + function promise(worker: fastq.asyncWorker, concurrency: number): fastq.queueAsPromised +} + +export = fastq diff --git a/node_modules/fastq/package.json b/node_modules/fastq/package.json new file mode 100644 index 00000000..989151ff --- /dev/null +++ b/node_modules/fastq/package.json @@ -0,0 +1,53 @@ +{ + "name": "fastq", + "version": "1.19.1", + "description": "Fast, in memory work queue", + "main": "queue.js", + "scripts": { + "lint": "standard --verbose | snazzy", + "unit": "nyc --lines 100 --branches 100 --functions 100 --check-coverage --reporter=text tape test/test.js test/promise.js", + "coverage": "nyc --reporter=html --reporter=cobertura --reporter=text tape test/test.js test/promise.js", + "test:report": "npm run lint && npm run unit:report", + "test": "npm run lint && npm run unit", + "typescript": "tsc --project ./test/tsconfig.json", + "legacy": "tape test/test.js" + }, + "pre-commit": [ + "test", + "typescript" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/mcollina/fastq.git" + }, + "keywords": [ + "fast", + "queue", + "async", + "worker" + ], + "author": "Matteo Collina ", + "license": "ISC", + "bugs": { + "url": "https://github.com/mcollina/fastq/issues" + }, + "homepage": "https://github.com/mcollina/fastq#readme", + "devDependencies": { + "async": "^3.1.0", + "neo-async": "^2.6.1", + "nyc": "^17.0.0", + "pre-commit": "^1.2.2", + "snazzy": "^9.0.0", + "standard": "^16.0.0", + "tape": "^5.0.0", + "typescript": "^5.0.4" + }, + "dependencies": { + "reusify": "^1.0.4" + }, + "standard": { + "ignore": [ + "example.mjs" + ] + } +} diff --git a/node_modules/fastq/queue.js b/node_modules/fastq/queue.js new file mode 100644 index 00000000..7ea8a312 --- /dev/null +++ b/node_modules/fastq/queue.js @@ -0,0 +1,311 @@ +'use strict' + +/* eslint-disable no-var */ + +var reusify = require('reusify') + +function fastqueue (context, worker, _concurrency) { + if (typeof context === 'function') { + _concurrency = worker + worker = context + context = null + } + + if (!(_concurrency >= 1)) { + throw new Error('fastqueue concurrency must be equal to or greater than 1') + } + + var cache = reusify(Task) + var queueHead = null + var queueTail = null + var _running = 0 + var errorHandler = null + + var self = { + push: push, + drain: noop, + saturated: noop, + pause: pause, + paused: false, + + get concurrency () { + return _concurrency + }, + set concurrency (value) { + if (!(value >= 1)) { + throw new Error('fastqueue concurrency must be equal to or greater than 1') + } + _concurrency = value + + if (self.paused) return + for (; queueHead && _running < _concurrency;) { + _running++ + release() + } + }, + + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop, + kill: kill, + killAndDrain: killAndDrain, + error: error + } + + return self + + function running () { + return _running + } + + function pause () { + self.paused = true + } + + function length () { + var current = queueHead + var counter = 0 + + while (current) { + current = current.next + counter++ + } + + return counter + } + + function getQueue () { + var current = queueHead + var tasks = [] + + while (current) { + tasks.push(current.value) + current = current.next + } + + return tasks + } + + function resume () { + if (!self.paused) return + self.paused = false + if (queueHead === null) { + _running++ + release() + return + } + for (; queueHead && _running < _concurrency;) { + _running++ + release() + } + } + + function idle () { + return _running === 0 && self.length() === 0 + } + + function push (value, done) { + var current = cache.get() + + current.context = context + current.release = release + current.value = value + current.callback = done || noop + current.errorHandler = errorHandler + + if (_running >= _concurrency || self.paused) { + if (queueTail) { + queueTail.next = current + queueTail = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } + + function unshift (value, done) { + var current = cache.get() + + current.context = context + current.release = release + current.value = value + current.callback = done || noop + current.errorHandler = errorHandler + + if (_running >= _concurrency || self.paused) { + if (queueHead) { + current.next = queueHead + queueHead = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } + + function release (holder) { + if (holder) { + cache.release(holder) + } + var next = queueHead + if (next && _running <= _concurrency) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null + } + queueHead = next.next + next.next = null + worker.call(context, next.value, next.worked) + if (queueTail === null) { + self.empty() + } + } else { + _running-- + } + } else if (--_running === 0) { + self.drain() + } + } + + function kill () { + queueHead = null + queueTail = null + self.drain = noop + } + + function killAndDrain () { + queueHead = null + queueTail = null + self.drain() + self.drain = noop + } + + function error (handler) { + errorHandler = handler + } +} + +function noop () {} + +function Task () { + this.value = null + this.callback = noop + this.next = null + this.release = noop + this.context = null + this.errorHandler = null + + var self = this + + this.worked = function worked (err, result) { + var callback = self.callback + var errorHandler = self.errorHandler + var val = self.value + self.value = null + self.callback = noop + if (self.errorHandler) { + errorHandler(err, val) + } + callback.call(self.context, err, result) + self.release(self) + } +} + +function queueAsPromised (context, worker, _concurrency) { + if (typeof context === 'function') { + _concurrency = worker + worker = context + context = null + } + + function asyncWrapper (arg, cb) { + worker.call(this, arg) + .then(function (res) { + cb(null, res) + }, cb) + } + + var queue = fastqueue(context, asyncWrapper, _concurrency) + + var pushCb = queue.push + var unshiftCb = queue.unshift + + queue.push = push + queue.unshift = unshift + queue.drained = drained + + return queue + + function push (value) { + var p = new Promise(function (resolve, reject) { + pushCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) + + return p + } + + function unshift (value) { + var p = new Promise(function (resolve, reject) { + unshiftCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) + + return p + } + + function drained () { + var p = new Promise(function (resolve) { + process.nextTick(function () { + if (queue.idle()) { + resolve() + } else { + var previousDrain = queue.drain + queue.drain = function () { + if (typeof previousDrain === 'function') previousDrain() + resolve() + queue.drain = previousDrain + } + } + }) + }) + + return p + } +} + +module.exports = fastqueue +module.exports.promise = queueAsPromised diff --git a/node_modules/fastq/test/example.ts b/node_modules/fastq/test/example.ts new file mode 100644 index 00000000..a47d4419 --- /dev/null +++ b/node_modules/fastq/test/example.ts @@ -0,0 +1,83 @@ +import * as fastq from '../' +import { promise as queueAsPromised } from '../' + +// Basic example + +const queue = fastq(worker, 1) + +queue.push('world', (err, result) => { + if (err) throw err + console.log('the result is', result) +}) + +queue.push('push without cb') + +queue.concurrency + +queue.drain() + +queue.empty = () => undefined + +console.log('the queue tasks are', queue.getQueue()) + +queue.idle() + +queue.kill() + +queue.killAndDrain() + +queue.length + +queue.pause() + +queue.resume() + +queue.running() + +queue.saturated = () => undefined + +queue.unshift('world', (err, result) => { + if (err) throw err + console.log('the result is', result) +}) + +queue.unshift('unshift without cb') + +function worker(task: any, cb: fastq.done) { + cb(null, 'hello ' + task) +} + +// Generics example + +interface GenericsContext { + base: number; +} + +const genericsQueue = fastq({ base: 6 }, genericsWorker, 1) + +genericsQueue.push(7, (err, done) => { + if (err) throw err + console.log('the result is', done) +}) + +genericsQueue.unshift(7, (err, done) => { + if (err) throw err + console.log('the result is', done) +}) + +function genericsWorker(this: GenericsContext, task: number, cb: fastq.done) { + cb(null, 'the meaning of life is ' + (this.base * task)) +} + +const queue2 = queueAsPromised(asyncWorker, 1) + +async function asyncWorker(task: any) { + return 'hello ' + task +} + +async function run () { + await queue.push(42) + await queue.unshift(42) +} + +run() diff --git a/node_modules/fastq/test/promise.js b/node_modules/fastq/test/promise.js new file mode 100644 index 00000000..45349a4f --- /dev/null +++ b/node_modules/fastq/test/promise.js @@ -0,0 +1,291 @@ +'use strict' + +const test = require('tape') +const buildQueue = require('../').promise +const { promisify } = require('util') +const sleep = promisify(setTimeout) +const immediate = promisify(setImmediate) + +test('concurrency', function (t) { + t.plan(2) + t.throws(buildQueue.bind(null, worker, 0)) + t.doesNotThrow(buildQueue.bind(null, worker, 1)) + + async function worker (arg) { + return true + } +}) + +test('worker execution', async function (t) { + const queue = buildQueue(worker, 1) + + const result = await queue.push(42) + + t.equal(result, true, 'result matches') + + async function worker (arg) { + t.equal(arg, 42) + return true + } +}) + +test('limit', async function (t) { + const queue = buildQueue(worker, 1) + + const [res1, res2] = await Promise.all([queue.push(10), queue.push(0)]) + t.equal(res1, 10, 'the result matches') + t.equal(res2, 0, 'the result matches') + + async function worker (arg) { + await sleep(arg) + return arg + } +}) + +test('multiple executions', async function (t) { + const queue = buildQueue(worker, 1) + const toExec = [1, 2, 3, 4, 5] + const expected = ['a', 'b', 'c', 'd', 'e'] + let count = 0 + + await Promise.all(toExec.map(async function (task, i) { + const result = await queue.push(task) + t.equal(result, expected[i], 'the result matches') + })) + + async function worker (arg) { + t.equal(arg, toExec[count], 'arg matches') + return expected[count++] + } +}) + +test('drained', async function (t) { + const queue = buildQueue(worker, 2) + + const toExec = new Array(10).fill(10) + let count = 0 + + async function worker (arg) { + await sleep(arg) + count++ + } + + toExec.forEach(function (i) { + queue.push(i) + }) + + await queue.drained() + + t.equal(count, toExec.length) + + toExec.forEach(function (i) { + queue.push(i) + }) + + await queue.drained() + + t.equal(count, toExec.length * 2) +}) + +test('drained with exception should not throw', async function (t) { + const queue = buildQueue(worker, 2) + + const toExec = new Array(10).fill(10) + + async function worker () { + throw new Error('foo') + } + + toExec.forEach(function (i) { + queue.push(i) + }) + + await queue.drained() +}) + +test('drained with drain function', async function (t) { + let drainCalled = false + const queue = buildQueue(worker, 2) + + queue.drain = function () { + drainCalled = true + } + + const toExec = new Array(10).fill(10) + let count = 0 + + async function worker (arg) { + await sleep(arg) + count++ + } + + toExec.forEach(function () { + queue.push() + }) + + await queue.drained() + + t.equal(count, toExec.length) + t.equal(drainCalled, true) +}) + +test('drained while idle should resolve', async function (t) { + const queue = buildQueue(worker, 2) + + async function worker (arg) { + await sleep(arg) + } + + await queue.drained() +}) + +test('drained while idle should not call the drain function', async function (t) { + let drainCalled = false + const queue = buildQueue(worker, 2) + + queue.drain = function () { + drainCalled = true + } + + async function worker (arg) { + await sleep(arg) + } + + await queue.drained() + + t.equal(drainCalled, false) +}) + +test('set this', async function (t) { + t.plan(1) + const that = {} + const queue = buildQueue(that, worker, 1) + + await queue.push(42) + + async function worker (arg) { + t.equal(this, that, 'this matches') + } +}) + +test('unshift', async function (t) { + const queue = buildQueue(worker, 1) + const expected = [1, 2, 3, 4] + + await Promise.all([ + queue.push(1), + queue.push(4), + queue.unshift(3), + queue.unshift(2) + ]) + + t.is(expected.length, 0) + + async function worker (arg) { + t.equal(expected.shift(), arg, 'tasks come in order') + } +}) + +test('push with worker throwing error', async function (t) { + t.plan(5) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + q.error(function (err, task) { + t.ok(err instanceof Error, 'global error handler should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + t.equal(task, 42, 'The task executed should be passed') + }) + try { + await q.push(42) + } catch (err) { + t.ok(err instanceof Error, 'push callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + } +}) + +test('unshift with worker throwing error', async function (t) { + t.plan(2) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + try { + await q.unshift(42) + } catch (err) { + t.ok(err instanceof Error, 'push callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + } +}) + +test('no unhandledRejection (push)', async function (t) { + function handleRejection () { + t.fail('unhandledRejection') + } + process.once('unhandledRejection', handleRejection) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + + q.push(42) + + await immediate() + process.removeListener('unhandledRejection', handleRejection) +}) + +test('no unhandledRejection (unshift)', async function (t) { + function handleRejection () { + t.fail('unhandledRejection') + } + process.once('unhandledRejection', handleRejection) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + + q.unshift(42) + + await immediate() + process.removeListener('unhandledRejection', handleRejection) +}) + +test('drained should resolve after async tasks complete', async function (t) { + const logs = [] + + async function processTask () { + await new Promise(resolve => setTimeout(resolve, 0)) + logs.push('processed') + } + + const queue = buildQueue(processTask, 1) + queue.drain = () => logs.push('called drain') + + queue.drained().then(() => logs.push('drained promise resolved')) + + await Promise.all([ + queue.push(), + queue.push(), + queue.push() + ]) + + t.deepEqual(logs, [ + 'processed', + 'processed', + 'processed', + 'called drain', + 'drained promise resolved' + ], 'events happened in correct order') +}) + +test('drained should handle undefined drain function', async function (t) { + const queue = buildQueue(worker, 1) + + async function worker (arg) { + await sleep(10) + return arg + } + + queue.drain = undefined + queue.push(1) + await queue.drained() + + t.pass('drained resolved successfully with undefined drain') +}) diff --git a/node_modules/fastq/test/test.js b/node_modules/fastq/test/test.js new file mode 100644 index 00000000..79f0f6c8 --- /dev/null +++ b/node_modules/fastq/test/test.js @@ -0,0 +1,653 @@ +'use strict' + +/* eslint-disable no-var */ + +var test = require('tape') +var buildQueue = require('../') + +test('concurrency', function (t) { + t.plan(6) + t.throws(buildQueue.bind(null, worker, 0)) + t.throws(buildQueue.bind(null, worker, NaN)) + t.doesNotThrow(buildQueue.bind(null, worker, 1)) + + var queue = buildQueue(worker, 1) + t.throws(function () { + queue.concurrency = 0 + }) + t.throws(function () { + queue.concurrency = NaN + }) + t.doesNotThrow(function () { + queue.concurrency = 2 + }) + + function worker (arg, cb) { + cb(null, true) + } +}) + +test('worker execution', function (t) { + t.plan(3) + + var queue = buildQueue(worker, 1) + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + function worker (arg, cb) { + t.equal(arg, 42) + cb(null, true) + } +}) + +test('limit', function (t) { + t.plan(4) + + var expected = [10, 0] + var queue = buildQueue(worker, 1) + + queue.push(10, result) + queue.push(0, result) + + function result (err, arg) { + t.error(err, 'no error') + t.equal(arg, expected.shift(), 'the result matches') + } + + function worker (arg, cb) { + setTimeout(cb, arg, null, arg) + } +}) + +test('multiple executions', function (t) { + t.plan(15) + + var queue = buildQueue(worker, 1) + var toExec = [1, 2, 3, 4, 5] + var count = 0 + + toExec.forEach(function (task) { + queue.push(task, done) + }) + + function done (err, result) { + t.error(err, 'no error') + t.equal(result, toExec[count - 1], 'the result matches') + } + + function worker (arg, cb) { + t.equal(arg, toExec[count], 'arg matches') + count++ + setImmediate(cb, null, arg) + } +}) + +test('multiple executions, one after another', function (t) { + t.plan(15) + + var queue = buildQueue(worker, 1) + var toExec = [1, 2, 3, 4, 5] + var count = 0 + + queue.push(toExec[0], done) + + function done (err, result) { + t.error(err, 'no error') + t.equal(result, toExec[count - 1], 'the result matches') + if (count < toExec.length) { + queue.push(toExec[count], done) + } + } + + function worker (arg, cb) { + t.equal(arg, toExec[count], 'arg matches') + count++ + setImmediate(cb, null, arg) + } +}) + +test('set this', function (t) { + t.plan(3) + + var that = {} + var queue = buildQueue(that, worker, 1) + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(this, that, 'this matches') + }) + + function worker (arg, cb) { + t.equal(this, that, 'this matches') + cb(null, true) + } +}) + +test('drain', function (t) { + t.plan(4) + + var queue = buildQueue(worker, 1) + var worked = false + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + queue.drain = function () { + t.equal(true, worked, 'drained') + } + + function worker (arg, cb) { + t.equal(arg, 42) + worked = true + setImmediate(cb, null, true) + } +}) + +test('pause && resume', function (t) { + t.plan(13) + + var queue = buildQueue(worker, 1) + var worked = false + var expected = [42, 24] + + t.notOk(queue.paused, 'it should not be paused') + + queue.pause() + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + queue.push(24, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + t.notOk(worked, 'it should be paused') + t.ok(queue.paused, 'it should be paused') + + queue.resume() + queue.pause() + queue.resume() + queue.resume() // second resume is a no-op + + function worker (arg, cb) { + t.notOk(queue.paused, 'it should not be paused') + t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') + t.equal(arg, expected.shift()) + worked = true + process.nextTick(function () { cb(null, true) }) + } +}) + +test('pause in flight && resume', function (t) { + t.plan(16) + + var queue = buildQueue(worker, 1) + var expected = [42, 24, 12] + + t.notOk(queue.paused, 'it should not be paused') + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.ok(queue.paused, 'it should be paused') + process.nextTick(function () { + queue.resume() + queue.pause() + queue.resume() + }) + }) + + queue.push(24, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.notOk(queue.paused, 'it should not be paused') + }) + + queue.push(12, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.notOk(queue.paused, 'it should not be paused') + }) + + queue.pause() + + function worker (arg, cb) { + t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') + t.equal(arg, expected.shift()) + process.nextTick(function () { cb(null, true) }) + } +}) + +test('altering concurrency', function (t) { + t.plan(24) + + var queue = buildQueue(worker, 1) + + queue.push(24, workDone) + queue.push(24, workDone) + queue.push(24, workDone) + + queue.pause() + + queue.concurrency = 3 // concurrency changes are ignored while paused + queue.concurrency = 2 + + queue.resume() + + t.equal(queue.running(), 2, '2 jobs running') + + queue.concurrency = 3 + + t.equal(queue.running(), 3, '3 jobs running') + + queue.concurrency = 1 + + t.equal(queue.running(), 3, '3 jobs running') // running jobs can't be killed + + queue.push(24, workDone) + queue.push(24, workDone) + queue.push(24, workDone) + queue.push(24, workDone) + + function workDone (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + } + + function worker (arg, cb) { + t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('idle()', function (t) { + t.plan(12) + + var queue = buildQueue(worker, 1) + + t.ok(queue.idle(), 'queue is idle') + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.notOk(queue.idle(), 'queue is not idle') + }) + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + // it will go idle after executing this function + setImmediate(function () { + t.ok(queue.idle(), 'queue is now idle') + }) + }) + + t.notOk(queue.idle(), 'queue is not idle') + + function worker (arg, cb) { + t.notOk(queue.idle(), 'queue is not idle') + t.equal(arg, 42) + setImmediate(cb, null, true) + } +}) + +test('saturated', function (t) { + t.plan(9) + + var queue = buildQueue(worker, 1) + var preworked = 0 + var worked = 0 + + queue.saturated = function () { + t.pass('saturated') + t.equal(preworked, 1, 'started 1 task') + t.equal(worked, 0, 'worked zero task') + } + + queue.push(42, done) + queue.push(42, done) + + function done (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + } + + function worker (arg, cb) { + t.equal(arg, 42) + preworked++ + setImmediate(function () { + worked++ + cb(null, true) + }) + } +}) + +test('length', function (t) { + t.plan(7) + + var queue = buildQueue(worker, 1) + + t.equal(queue.length(), 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.length(), 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.length(), 1, 'one task waiting') + queue.push(42, done) + t.equal(queue.length(), 2, 'two tasks waiting') + + function done (err, result) { + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('getQueue', function (t) { + t.plan(10) + + var queue = buildQueue(worker, 1) + + t.equal(queue.getQueue().length, 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.getQueue().length, 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.getQueue().length, 1, 'one task waiting') + t.equal(queue.getQueue()[0], 42, 'should be equal') + queue.push(43, done) + t.equal(queue.getQueue().length, 2, 'two tasks waiting') + t.equal(queue.getQueue()[0], 42, 'should be equal') + t.equal(queue.getQueue()[1], 43, 'should be equal') + + function done (err, result) { + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('unshift', function (t) { + t.plan(8) + + var queue = buildQueue(worker, 1) + var expected = [1, 2, 3, 4] + + queue.push(1, done) + queue.push(4, done) + queue.unshift(3, done) + queue.unshift(2, done) + + function done (err, result) { + t.error(err, 'no error') + } + + function worker (arg, cb) { + t.equal(expected.shift(), arg, 'tasks come in order') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('unshift && empty', function (t) { + t.plan(2) + + var queue = buildQueue(worker, 1) + var completed = false + + queue.pause() + + queue.empty = function () { + t.notOk(completed, 'the task has not completed yet') + } + + queue.unshift(1, done) + + queue.resume() + + function done (err, result) { + completed = true + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('push && empty', function (t) { + t.plan(2) + + var queue = buildQueue(worker, 1) + var completed = false + + queue.pause() + + queue.empty = function () { + t.notOk(completed, 'the task has not completed yet') + } + + queue.push(1, done) + + queue.resume() + + function done (err, result) { + completed = true + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('kill', function (t) { + t.plan(5) + + var queue = buildQueue(worker, 1) + var expected = [1] + + var predrain = queue.drain + + queue.drain = function drain () { + t.fail('drain should never be called') + } + + queue.push(1, done) + queue.push(4, done) + queue.unshift(3, done) + queue.unshift(2, done) + queue.kill() + + function done (err, result) { + t.error(err, 'no error') + setImmediate(function () { + t.equal(queue.length(), 0, 'no queued tasks') + t.equal(queue.running(), 0, 'no running tasks') + t.equal(queue.drain, predrain, 'drain is back to default') + }) + } + + function worker (arg, cb) { + t.equal(expected.shift(), arg, 'tasks come in order') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('killAndDrain', function (t) { + t.plan(6) + + var queue = buildQueue(worker, 1) + var expected = [1] + + var predrain = queue.drain + + queue.drain = function drain () { + t.pass('drain has been called') + } + + queue.push(1, done) + queue.push(4, done) + queue.unshift(3, done) + queue.unshift(2, done) + queue.killAndDrain() + + function done (err, result) { + t.error(err, 'no error') + setImmediate(function () { + t.equal(queue.length(), 0, 'no queued tasks') + t.equal(queue.running(), 0, 'no running tasks') + t.equal(queue.drain, predrain, 'drain is back to default') + }) + } + + function worker (arg, cb) { + t.equal(expected.shift(), arg, 'tasks come in order') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('pause && idle', function (t) { + t.plan(11) + + var queue = buildQueue(worker, 1) + var worked = false + + t.notOk(queue.paused, 'it should not be paused') + t.ok(queue.idle(), 'should be idle') + + queue.pause() + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + t.notOk(worked, 'it should be paused') + t.ok(queue.paused, 'it should be paused') + t.notOk(queue.idle(), 'should not be idle') + + queue.resume() + + t.notOk(queue.paused, 'it should not be paused') + t.notOk(queue.idle(), 'it should not be idle') + + function worker (arg, cb) { + t.equal(arg, 42) + worked = true + process.nextTick(cb.bind(null, null, true)) + process.nextTick(function () { + t.ok(queue.idle(), 'is should be idle') + }) + } +}) + +test('push without cb', function (t) { + t.plan(1) + + var queue = buildQueue(worker, 1) + + queue.push(42) + + function worker (arg, cb) { + t.equal(arg, 42) + cb() + } +}) + +test('unshift without cb', function (t) { + t.plan(1) + + var queue = buildQueue(worker, 1) + + queue.unshift(42) + + function worker (arg, cb) { + t.equal(arg, 42) + cb() + } +}) + +test('push with worker throwing error', function (t) { + t.plan(5) + var q = buildQueue(function (task, cb) { + cb(new Error('test error'), null) + }, 1) + q.error(function (err, task) { + t.ok(err instanceof Error, 'global error handler should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + t.equal(task, 42, 'The task executed should be passed') + }) + q.push(42, function (err) { + t.ok(err instanceof Error, 'push callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + }) +}) + +test('unshift with worker throwing error', function (t) { + t.plan(5) + var q = buildQueue(function (task, cb) { + cb(new Error('test error'), null) + }, 1) + q.error(function (err, task) { + t.ok(err instanceof Error, 'global error handler should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + t.equal(task, 42, 'The task executed should be passed') + }) + q.unshift(42, function (err) { + t.ok(err instanceof Error, 'unshift callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + }) +}) + +test('pause/resume should trigger drain event', function (t) { + t.plan(1) + + var queue = buildQueue(worker, 1) + queue.pause() + queue.drain = function () { + t.pass('drain should be called') + } + + function worker (arg, cb) { + cb(null, true) + } + + queue.resume() +}) + +test('paused flag', function (t) { + t.plan(2) + + var queue = buildQueue(function (arg, cb) { + cb(null) + }, 1) + t.equal(queue.paused, false) + queue.pause() + t.equal(queue.paused, true) +}) diff --git a/node_modules/fastq/test/tsconfig.json b/node_modules/fastq/test/tsconfig.json new file mode 100644 index 00000000..66e16e93 --- /dev/null +++ b/node_modules/fastq/test/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "noEmit": true, + "strict": true + }, + "files": [ + "./example.ts" + ] +} diff --git a/node_modules/file-entry-cache/LICENSE b/node_modules/file-entry-cache/LICENSE new file mode 100644 index 00000000..39a8bc45 --- /dev/null +++ b/node_modules/file-entry-cache/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) Roy Riojas & Jared Wray + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/file-entry-cache/README.md b/node_modules/file-entry-cache/README.md new file mode 100644 index 00000000..4f068fe4 --- /dev/null +++ b/node_modules/file-entry-cache/README.md @@ -0,0 +1,115 @@ +# file-entry-cache +> Super simple cache for file metadata, useful for process that work on a given series of files +> and that only need to repeat the job on the changed ones since the previous run of the process — Edit + +[![NPM Version](https://img.shields.io/npm/v/file-entry-cache.svg?style=flat)](https://npmjs.org/package/file-entry-cache) +[![tests](https://github.com/jaredwray/file-entry-cache/actions/workflows/tests.yaml/badge.svg?branch=master)](https://github.com/jaredwray/file-entry-cache/actions/workflows/tests.yaml) +[![codecov](https://codecov.io/github/jaredwray/file-entry-cache/graph/badge.svg?token=37tZMQE0Sy)](https://codecov.io/github/jaredwray/file-entry-cache) +[![npm](https://img.shields.io/npm/dm/file-entry-cache)](https://npmjs.com/package/file-entry-cache) + + +## install + +```bash +npm i --save file-entry-cache +``` + +## Usage + +The module exposes two functions `create` and `createFromFile`. + +## `create(cacheName, [directory, useCheckSum])` +- **cacheName**: the name of the cache to be created +- **directory**: Optional the directory to load the cache from +- **usecheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. + +## `createFromFile(pathToCache, [useCheckSum])` +- **pathToCache**: the path to the cache file (this combines the cache name and directory) +- **useCheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. + +```js +// loads the cache, if one does not exists for the given +// Id a new one will be prepared to be created +var fileEntryCache = require('file-entry-cache'); + +var cache = fileEntryCache.create('testCache'); + +var files = expand('../fixtures/*.txt'); + +// the first time this method is called, will return all the files +var oFiles = cache.getUpdatedFiles(files); + +// this will persist this to disk checking each file stats and +// updating the meta attributes `size` and `mtime`. +// custom fields could also be added to the meta object and will be persisted +// in order to retrieve them later +cache.reconcile(); + +// use this if you want the non visited file entries to be kept in the cache +// for more than one execution +// +// cache.reconcile( true /* noPrune */) + +// on a second run +var cache2 = fileEntryCache.create('testCache'); + +// will return now only the files that were modified or none +// if no files were modified previous to the execution of this function +var oFiles = cache.getUpdatedFiles(files); + +// if you want to prevent a file from being considered non modified +// something useful if a file failed some sort of validation +// you can then remove the entry from the cache doing +cache.removeEntry('path/to/file'); // path to file should be the same path of the file received on `getUpdatedFiles` +// that will effectively make the file to appear again as modified until the validation is passed. In that +// case you should not remove it from the cache + +// if you need all the files, so you can determine what to do with the changed ones +// you can call +var oFiles = cache.normalizeEntries(files); + +// oFiles will be an array of objects like the following +entry = { + key: 'some/name/file', the path to the file + changed: true, // if the file was changed since previous run + meta: { + size: 3242, // the size of the file + mtime: 231231231, // the modification time of the file + data: {} // some extra field stored for this file (useful to save the result of a transformation on the file + } +} + +``` + +## Motivation for this module + +I needed a super simple and dumb **in-memory cache** with optional disk persistence (write-back cache) in order to make +a script that will beautify files with `esformatter` to execute only on the files that were changed since the last run. + +In doing so the process of beautifying files was reduced from several seconds to a small fraction of a second. + +This module uses [flat-cache](https://www.npmjs.com/package/flat-cache) a super simple `key/value` cache storage with +optional file persistance. + +The main idea is to read the files when the task begins, apply the transforms required, and if the process succeed, +then store the new state of the files. The next time this module request for `getChangedFiles` will return only +the files that were modified. Making the process to end faster. + +This module could also be used by processes that modify the files applying a transform, in that case the result of the +transform could be stored in the `meta` field, of the entries. Anything added to the meta field will be persisted. +Those processes won't need to call `getChangedFiles` they will instead call `normalizeEntries` that will return the +entries with a `changed` field that can be used to determine if the file was changed or not. If it was not changed +the transformed stored data could be used instead of actually applying the transformation, saving time in case of only +a few files changed. + +In the worst case scenario all the files will be processed. In the best case scenario only a few of them will be processed. + +## Important notes +- The values set on the meta attribute of the entries should be `stringify-able` ones if possible, flat-cache uses `circular-json` to try to persist circular structures, but this should be considered experimental. The best results are always obtained with non circular values +- All the changes to the cache state are done to memory first and only persisted after reconcile. + +## License + +MIT + + diff --git a/node_modules/file-entry-cache/cache.js b/node_modules/file-entry-cache/cache.js new file mode 100644 index 00000000..6b15767e --- /dev/null +++ b/node_modules/file-entry-cache/cache.js @@ -0,0 +1,291 @@ +var path = require('path'); +var crypto = require('crypto'); + +module.exports = { + createFromFile: function (filePath, useChecksum) { + var fname = path.basename(filePath); + var dir = path.dirname(filePath); + return this.create(fname, dir, useChecksum); + }, + + create: function (cacheId, _path, useChecksum) { + var fs = require('fs'); + var flatCache = require('flat-cache'); + var cache = flatCache.load(cacheId, _path); + var normalizedEntries = {}; + + var removeNotFoundFiles = function removeNotFoundFiles() { + const cachedEntries = cache.keys(); + // remove not found entries + cachedEntries.forEach(function remover(fPath) { + try { + fs.statSync(fPath); + } catch (err) { + if (err.code === 'ENOENT') { + cache.removeKey(fPath); + } + } + }); + }; + + removeNotFoundFiles(); + + return { + /** + * the flat cache storage used to persist the metadata of the `files + * @type {Object} + */ + cache: cache, + + /** + * Given a buffer, calculate md5 hash of its content. + * @method getHash + * @param {Buffer} buffer buffer to calculate hash on + * @return {String} content hash digest + */ + getHash: function (buffer) { + return crypto.createHash('md5').update(buffer).digest('hex'); + }, + + /** + * Return whether or not a file has changed since last time reconcile was called. + * @method hasFileChanged + * @param {String} file the filepath to check + * @return {Boolean} wheter or not the file has changed + */ + hasFileChanged: function (file) { + return this.getFileDescriptor(file).changed; + }, + + /** + * given an array of file paths it return and object with three arrays: + * - changedFiles: Files that changed since previous run + * - notChangedFiles: Files that haven't change + * - notFoundFiles: Files that were not found, probably deleted + * + * @param {Array} files the files to analyze and compare to the previous seen files + * @return {[type]} [description] + */ + analyzeFiles: function (files) { + var me = this; + files = files || []; + + var res = { + changedFiles: [], + notFoundFiles: [], + notChangedFiles: [], + }; + + me.normalizeEntries(files).forEach(function (entry) { + if (entry.changed) { + res.changedFiles.push(entry.key); + return; + } + if (entry.notFound) { + res.notFoundFiles.push(entry.key); + return; + } + res.notChangedFiles.push(entry.key); + }); + return res; + }, + + getFileDescriptor: function (file) { + var fstat; + + try { + fstat = fs.statSync(file); + } catch (ex) { + this.removeEntry(file); + return { key: file, notFound: true, err: ex }; + } + + if (useChecksum) { + return this._getFileDescriptorUsingChecksum(file); + } + + return this._getFileDescriptorUsingMtimeAndSize(file, fstat); + }, + + _getFileDescriptorUsingMtimeAndSize: function (file, fstat) { + var meta = cache.getKey(file); + var cacheExists = !!meta; + + var cSize = fstat.size; + var cTime = fstat.mtime.getTime(); + + var isDifferentDate; + var isDifferentSize; + + if (!meta) { + meta = { size: cSize, mtime: cTime }; + } else { + isDifferentDate = cTime !== meta.mtime; + isDifferentSize = cSize !== meta.size; + } + + var nEntry = (normalizedEntries[file] = { + key: file, + changed: !cacheExists || isDifferentDate || isDifferentSize, + meta: meta, + }); + + return nEntry; + }, + + _getFileDescriptorUsingChecksum: function (file) { + var meta = cache.getKey(file); + var cacheExists = !!meta; + + var contentBuffer; + try { + contentBuffer = fs.readFileSync(file); + } catch (ex) { + contentBuffer = ''; + } + + var isDifferent = true; + var hash = this.getHash(contentBuffer); + + if (!meta) { + meta = { hash: hash }; + } else { + isDifferent = hash !== meta.hash; + } + + var nEntry = (normalizedEntries[file] = { + key: file, + changed: !cacheExists || isDifferent, + meta: meta, + }); + + return nEntry; + }, + + /** + * Return the list o the files that changed compared + * against the ones stored in the cache + * + * @method getUpdated + * @param files {Array} the array of files to compare against the ones in the cache + * @returns {Array} + */ + getUpdatedFiles: function (files) { + var me = this; + files = files || []; + + return me + .normalizeEntries(files) + .filter(function (entry) { + return entry.changed; + }) + .map(function (entry) { + return entry.key; + }); + }, + + /** + * return the list of files + * @method normalizeEntries + * @param files + * @returns {*} + */ + normalizeEntries: function (files) { + files = files || []; + + var me = this; + var nEntries = files.map(function (file) { + return me.getFileDescriptor(file); + }); + + //normalizeEntries = nEntries; + return nEntries; + }, + + /** + * Remove an entry from the file-entry-cache. Useful to force the file to still be considered + * modified the next time the process is run + * + * @method removeEntry + * @param entryName + */ + removeEntry: function (entryName) { + delete normalizedEntries[entryName]; + cache.removeKey(entryName); + }, + + /** + * Delete the cache file from the disk + * @method deleteCacheFile + */ + deleteCacheFile: function () { + cache.removeCacheFile(); + }, + + /** + * remove the cache from the file and clear the memory cache + */ + destroy: function () { + normalizedEntries = {}; + cache.destroy(); + }, + + _getMetaForFileUsingCheckSum: function (cacheEntry) { + var contentBuffer = fs.readFileSync(cacheEntry.key); + var hash = this.getHash(contentBuffer); + var meta = Object.assign(cacheEntry.meta, { hash: hash }); + delete meta.size; + delete meta.mtime; + return meta; + }, + + _getMetaForFileUsingMtimeAndSize: function (cacheEntry) { + var stat = fs.statSync(cacheEntry.key); + var meta = Object.assign(cacheEntry.meta, { + size: stat.size, + mtime: stat.mtime.getTime(), + }); + delete meta.hash; + return meta; + }, + + /** + * Sync the files and persist them to the cache + * @method reconcile + */ + reconcile: function (noPrune) { + removeNotFoundFiles(); + + noPrune = typeof noPrune === 'undefined' ? true : noPrune; + + var entries = normalizedEntries; + var keys = Object.keys(entries); + + if (keys.length === 0) { + return; + } + + var me = this; + + keys.forEach(function (entryName) { + var cacheEntry = entries[entryName]; + + try { + var meta = useChecksum + ? me._getMetaForFileUsingCheckSum(cacheEntry) + : me._getMetaForFileUsingMtimeAndSize(cacheEntry); + cache.setKey(entryName, meta); + } catch (err) { + // if the file does not exists we don't save it + // other errors are just thrown + if (err.code !== 'ENOENT') { + throw err; + } + } + }); + + cache.save(noPrune); + }, + }; + }, +}; diff --git a/node_modules/file-entry-cache/package.json b/node_modules/file-entry-cache/package.json new file mode 100644 index 00000000..ef63b6ff --- /dev/null +++ b/node_modules/file-entry-cache/package.json @@ -0,0 +1,56 @@ +{ + "name": "file-entry-cache", + "version": "8.0.0", + "description": "Super simple cache for file metadata, useful for process that work o a given series of files and that only need to repeat the job on the changed ones since the previous run of the process", + "repository": "jaredwray/file-entry-cache", + "license": "MIT", + "author": { + "name": "Jared Wray", + "url": "https://jaredwray.com" + }, + "main": "cache.js", + "files": [ + "cache.js" + ], + "engines": { + "node": ">=16.0.0" + }, + "scripts": { + "eslint": "eslint --cache --cache-location=node_modules/.cache/ 'cache.js' 'test/**/*.js' 'perf.js'", + "autofix": "npm run eslint -- --fix", + "clean": "rimraf ./node_modules ./package-lock.json ./yarn.lock", + "test": "npm run eslint --silent && c8 mocha -R spec test/specs", + "test:ci": "npm run eslint --silent && c8 --reporter=lcov mocha -R spec test/specs", + "perf": "node perf.js" + }, + "prepush": [ + "npm run eslint --silent" + ], + "precommit": [ + "npm run eslint --silent" + ], + "keywords": [ + "file cache", + "task cache files", + "file cache", + "key par", + "key value", + "cache" + ], + "devDependencies": { + "c8": "^8.0.1", + "chai": "^4.3.10", + "eslint": "^8.56.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-mocha": "^10.2.0", + "eslint-plugin-prettier": "^5.0.1", + "glob-expand": "^0.2.1", + "mocha": "^10.2.0", + "prettier": "^3.1.1", + "rimraf": "^5.0.5", + "write": "^2.0.0" + }, + "dependencies": { + "flat-cache": "^4.0.0" + } +} diff --git a/node_modules/fill-range/LICENSE b/node_modules/fill-range/LICENSE new file mode 100644 index 00000000..9af4a67d --- /dev/null +++ b/node_modules/fill-range/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/fill-range/README.md b/node_modules/fill-range/README.md new file mode 100644 index 00000000..8d756fe9 --- /dev/null +++ b/node_modules/fill-range/README.md @@ -0,0 +1,237 @@ +# fill-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/fill-range.svg?style=flat)](https://www.npmjs.com/package/fill-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![NPM total downloads](https://img.shields.io/npm/dt/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fill-range.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fill-range) + +> Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex` + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save fill-range +``` + +## Usage + +Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_. + +```js +const fill = require('fill-range'); +// fill(from, to[, step, options]); + +console.log(fill('1', '10')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] +console.log(fill('1', '10', { toRegex: true })); //=> [1-9]|10 +``` + +**Params** + +* `from`: **{String|Number}** the number or letter to start with +* `to`: **{String|Number}** the number or letter to end with +* `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use. +* `options`: **{Object|Function}**: See all available [options](#options) + +## Examples + +By default, an array of values is returned. + +**Alphabetical ranges** + +```js +console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e'] +console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ] +``` + +**Numerical ranges** + +Numbers can be defined as actual numbers or strings. + +```js +console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] +console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ] +``` + +**Negative ranges** + +Numbers can be defined as actual numbers or strings. + +```js +console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ] +console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ] +``` + +**Steps (increments)** + +```js +// numerical ranges with increments +console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ] +console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ] +console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ] + +// alphabetical ranges with increments +console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ] +console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] +console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ] +``` + +## Options + +### options.step + +**Type**: `number` (formatted as a string or number) + +**Default**: `undefined` + +**Description**: The increment to use for the range. Can be used with letters or numbers. + +**Example(s)** + +```js +// numbers +console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ] +console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ] +console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ] + +// letters +console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] +console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ] +console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ] +``` + +### options.strictRanges + +**Type**: `boolean` + +**Default**: `false` + +**Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges. + +**Example(s)** + +The following are all invalid: + +```js +fill('1.1', '2'); // decimals not supported in ranges +fill('a', '2'); // incompatible range values +fill(1, 10, 'foo'); // invalid "step" argument +``` + +### options.stringify + +**Type**: `boolean` + +**Default**: `undefined` + +**Description**: Cast all returned values to strings. By default, integers are returned as numbers. + +**Example(s)** + +```js +console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] +console.log(fill(1, 5, { stringify: true })); //=> [ '1', '2', '3', '4', '5' ] +``` + +### options.toRegex + +**Type**: `boolean` + +**Default**: `undefined` + +**Description**: Create a regex-compatible source string, instead of expanding values to an array. + +**Example(s)** + +```js +// alphabetical range +console.log(fill('a', 'e', { toRegex: true })); //=> '[a-e]' +// alphabetical with step +console.log(fill('a', 'z', 3, { toRegex: true })); //=> 'a|d|g|j|m|p|s|v|y' +// numerical range +console.log(fill('1', '100', { toRegex: true })); //=> '[1-9]|[1-9][0-9]|100' +// numerical range with zero padding +console.log(fill('000001', '100000', { toRegex: true })); +//=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000' +``` + +### options.transform + +**Type**: `function` + +**Default**: `undefined` + +**Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_. + +**Example(s)** + +```js +// add zero padding +console.log(fill(1, 5, value => String(value).padStart(4, '0'))); +//=> ['0001', '0002', '0003', '0004', '0005'] +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 116 | [jonschlinkert](https://github.com/jonschlinkert) | +| 4 | [paulmillr](https://github.com/paulmillr) | +| 2 | [realityking](https://github.com/realityking) | +| 2 | [bluelovers](https://github.com/bluelovers) | +| 1 | [edorivai](https://github.com/edorivai) | +| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! + + + + + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ \ No newline at end of file diff --git a/node_modules/fill-range/index.js b/node_modules/fill-range/index.js new file mode 100644 index 00000000..ddb212ee --- /dev/null +++ b/node_modules/fill-range/index.js @@ -0,0 +1,248 @@ +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ + +'use strict'; + +const util = require('util'); +const toRegexRange = require('to-regex-range'); + +const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; + +const isNumber = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; + +const stringify = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; + +const toSequence = (parts, options, maxLen) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util.inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; + + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify(start, end, options) === false; + let format = options.transform || transform(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options, maxLen) + : toRegex(range, null, { wrap: false, ...options }); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { + return invalidRange(start, end, options); + } + + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } + + return range; +}; + +const fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill(start, end, 1, { transform: step }); + } + + if (isObject(step)) { + return fill(start, end, 0, step); + } + + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber(step)) { + if (step != null && !isObject(step)) return invalidStep(step, opts); + return fill(start, end, 1, step); + } + + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +module.exports = fill; diff --git a/node_modules/fill-range/package.json b/node_modules/fill-range/package.json new file mode 100644 index 00000000..582357fb --- /dev/null +++ b/node_modules/fill-range/package.json @@ -0,0 +1,74 @@ +{ + "name": "fill-range", + "description": "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`", + "version": "7.1.1", + "homepage": "https://github.com/jonschlinkert/fill-range", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Edo Rivai (edo.rivai.nl)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Paul Miller (paulmillr.com)", + "Rouven Weßling (www.rouvenwessling.de)", + "(https://github.com/wtgtybhertgeghgtwtg)" + ], + "repository": "jonschlinkert/fill-range", + "bugs": { + "url": "https://github.com/jonschlinkert/fill-range/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=8" + }, + "scripts": { + "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .", + "mocha": "mocha --reporter dot", + "test": "npm run lint && npm run mocha", + "test:ci": "npm run test:cover", + "test:cover": "nyc npm run mocha" + }, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "devDependencies": { + "gulp-format-md": "^2.0.0", + "mocha": "^6.1.1", + "nyc": "^15.1.0" + }, + "keywords": [ + "alpha", + "alphabetical", + "array", + "bash", + "brace", + "expand", + "expansion", + "fill", + "glob", + "match", + "matches", + "matching", + "number", + "numerical", + "range", + "ranges", + "regex", + "sh" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/find-up/index.d.ts b/node_modules/find-up/index.d.ts new file mode 100644 index 00000000..6746bb72 --- /dev/null +++ b/node_modules/find-up/index.d.ts @@ -0,0 +1,138 @@ +/* eslint-disable @typescript-eslint/unified-signatures */ +import {Options as LocatePathOptions} from 'locate-path'; + +declare const stop: unique symbol; + +declare namespace findUp { + interface Options extends LocatePathOptions {} + + type StopSymbol = typeof stop; + + type Match = string | StopSymbol | undefined; +} + +declare const findUp: { + sync: { + /** + Synchronously check if a path exists. + + @param path - Path to the file or directory. + @returns Whether the path exists. + + @example + ``` + import findUp = require('find-up'); + + console.log(findUp.sync.exists('/Users/sindresorhus/unicorn.png')); + //=> true + ``` + */ + exists: (path: string) => boolean; + + /** + Synchronously find a file or directory by walking up parent directories. + + @param name - Name of the file or directory to find. Can be multiple. + @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. + */ + (name: string | readonly string[], options?: findUp.Options): string | undefined; + + /** + Synchronously find a file or directory by walking up parent directories. + + @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. + @returns The first path found or `undefined` if none could be found. + + @example + ``` + import path = require('path'); + import findUp = require('find-up'); + + console.log(findUp.sync(directory => { + const hasUnicorns = findUp.sync.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' + ``` + */ + (matcher: (directory: string) => findUp.Match, options?: findUp.Options): string | undefined; + }; + + /** + Check if a path exists. + + @param path - Path to a file or directory. + @returns Whether the path exists. + + @example + ``` + import findUp = require('find-up'); + + (async () => { + console.log(await findUp.exists('/Users/sindresorhus/unicorn.png')); + //=> true + })(); + ``` + */ + exists: (path: string) => Promise; + + /** + Return this in a `matcher` function to stop the search and force `findUp` to immediately return `undefined`. + */ + readonly stop: findUp.StopSymbol; + + /** + Find a file or directory by walking up parent directories. + + @param name - Name of the file or directory to find. Can be multiple. + @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. + + @example + ``` + // / + // └── Users + // └── sindresorhus + // ├── unicorn.png + // └── foo + // └── bar + // ├── baz + // └── example.js + + // example.js + import findUp = require('find-up'); + + (async () => { + console.log(await findUp('unicorn.png')); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(['rainbow.png', 'unicorn.png'])); + //=> '/Users/sindresorhus/unicorn.png' + })(); + ``` + */ + (name: string | readonly string[], options?: findUp.Options): Promise; + + /** + Find a file or directory by walking up parent directories. + + @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. + @returns The first path found or `undefined` if none could be found. + + @example + ``` + import path = require('path'); + import findUp = require('find-up'); + + (async () => { + console.log(await findUp(async directory => { + const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' + })(); + ``` + */ + (matcher: (directory: string) => (findUp.Match | Promise), options?: findUp.Options): Promise; +}; + +export = findUp; diff --git a/node_modules/find-up/index.js b/node_modules/find-up/index.js new file mode 100644 index 00000000..ce564e5d --- /dev/null +++ b/node_modules/find-up/index.js @@ -0,0 +1,89 @@ +'use strict'; +const path = require('path'); +const locatePath = require('locate-path'); +const pathExists = require('path-exists'); + +const stop = Symbol('findUp.stop'); + +module.exports = async (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = async locateOptions => { + if (typeof name !== 'function') { + return locatePath(paths, locateOptions); + } + + const foundPath = await name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + // eslint-disable-next-line no-await-in-loop + const foundPath = await runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } +}; + +module.exports.sync = (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = locateOptions => { + if (typeof name !== 'function') { + return locatePath.sync(paths, locateOptions); + } + + const foundPath = name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath.sync([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + const foundPath = runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } +}; + +module.exports.exists = pathExists; + +module.exports.sync.exists = pathExists.sync; + +module.exports.stop = stop; diff --git a/node_modules/find-up/license b/node_modules/find-up/license new file mode 100644 index 00000000..fa7ceba3 --- /dev/null +++ b/node_modules/find-up/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/find-up/package.json b/node_modules/find-up/package.json new file mode 100644 index 00000000..56db6dd8 --- /dev/null +++ b/node_modules/find-up/package.json @@ -0,0 +1,54 @@ +{ + "name": "find-up", + "version": "5.0.0", + "description": "Find a file or directory by walking up parent directories", + "license": "MIT", + "repository": "sindresorhus/find-up", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "find", + "up", + "find-up", + "findup", + "look-up", + "look", + "file", + "search", + "match", + "package", + "resolve", + "parent", + "parents", + "folder", + "directory", + "walk", + "walking", + "path" + ], + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "devDependencies": { + "ava": "^2.1.0", + "is-path-inside": "^2.1.0", + "tempy": "^0.6.0", + "tsd": "^0.13.1", + "xo": "^0.33.0" + } +} diff --git a/node_modules/find-up/readme.md b/node_modules/find-up/readme.md new file mode 100644 index 00000000..7ad908a7 --- /dev/null +++ b/node_modules/find-up/readme.md @@ -0,0 +1,151 @@ +# find-up [![Build Status](https://travis-ci.com/sindresorhus/find-up.svg?branch=master)](https://travis-ci.com/github/sindresorhus/find-up) + +> Find a file or directory by walking up parent directories + +## Install + +``` +$ npm install find-up +``` + +## Usage + +``` +/ +└── Users + └── sindresorhus + ├── unicorn.png + └── foo + └── bar + ├── baz + └── example.js +``` + +`example.js` + +```js +const path = require('path'); +const findUp = require('find-up'); + +(async () => { + console.log(await findUp('unicorn.png')); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(['rainbow.png', 'unicorn.png'])); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(async directory => { + const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' +})(); +``` + +## API + +### findUp(name, options?) +### findUp(matcher, options?) + +Returns a `Promise` for either the path or `undefined` if it couldn't be found. + +### findUp([...name], options?) + +Returns a `Promise` for either the first path found (by respecting the order of the array) or `undefined` if none could be found. + +### findUp.sync(name, options?) +### findUp.sync(matcher, options?) + +Returns a path or `undefined` if it couldn't be found. + +### findUp.sync([...name], options?) + +Returns the first path found (by respecting the order of the array) or `undefined` if none could be found. + +#### name + +Type: `string` + +Name of the file or directory to find. + +#### matcher + +Type: `Function` + +A function that will be called with each directory until it returns a `string` with the path, which stops the search, or the root directory has been reached and nothing was found. Useful if you want to match files with certain patterns, set of permissions, or other advanced use-cases. + +When using async mode, the `matcher` may optionally be an async or promise-returning function that returns the path. + +#### options + +Type: `object` + +##### cwd + +Type: `string`\ +Default: `process.cwd()` + +Directory to start from. + +##### type + +Type: `string`\ +Default: `'file'`\ +Values: `'file'` `'directory'` + +The type of paths that can match. + +##### allowSymlinks + +Type: `boolean`\ +Default: `true` + +Allow symbolic links to match if they point to the chosen path type. + +### findUp.exists(path) + +Returns a `Promise` of whether the path exists. + +### findUp.sync.exists(path) + +Returns a `boolean` of whether the path exists. + +#### path + +Type: `string` + +Path to a file or directory. + +### findUp.stop + +A [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that can be returned by a `matcher` function to stop the search and cause `findUp` to immediately return `undefined`. Useful as a performance optimization in case the current working directory is deeply nested in the filesystem. + +```js +const path = require('path'); +const findUp = require('find-up'); + +(async () => { + await findUp(directory => { + return path.basename(directory) === 'work' ? findUp.stop : 'logo.png'; + }); +})(); +``` + +## Related + +- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module +- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file +- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package +- [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module like `require.resolve()` but from a given path + +--- + +
+ + Get professional support for 'find-up' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/flat-cache/LICENSE b/node_modules/flat-cache/LICENSE new file mode 100644 index 00000000..7383a47e --- /dev/null +++ b/node_modules/flat-cache/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) Roy Riojas and Jared Wray + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/flat-cache/README.md b/node_modules/flat-cache/README.md new file mode 100644 index 00000000..3d7793aa --- /dev/null +++ b/node_modules/flat-cache/README.md @@ -0,0 +1,77 @@ +# flat-cache + +> A stupidly simple key/value storage using files to persist the data + +[![NPM Version](https://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache) +[![tests](https://github.com/jaredwray/flat-cache/actions/workflows/tests.yaml/badge.svg?branch=master)](https://github.com/jaredwray/flat-cache/actions/workflows/tests.yaml) +[![codecov](https://codecov.io/github/jaredwray/flat-cache/branch/master/graph/badge.svg?token=KxR95XT3NF)](https://codecov.io/github/jaredwray/flat-cache) +[![npm](https://img.shields.io/npm/dm/flat-cache)](https://npmjs.com/package/flat-cache) + +## install + +```bash +npm i --save flat-cache +``` + +## Usage + +```js +const flatCache = require('flat-cache'); +// loads the cache, if one does not exists for the given +// Id a new one will be prepared to be created +const cache = flatCache.load('cacheId'); + +// sets a key on the cache +cache.setKey('key', { foo: 'var' }); + +// get a key from the cache +cache.getKey('key'); // { foo: 'var' } + +// fetch the entire persisted object +cache.all(); // { 'key': { foo: 'var' } } + +// remove a key +cache.removeKey('key'); // removes a key from the cache + +// save it to disk +cache.save(); // very important, if you don't save no changes will be persisted. +// cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys + +// loads the cache from a given directory, if one does +// not exists for the given Id a new one will be prepared to be created +const cache = flatCache.load('cacheId', path.resolve('./path/to/folder')); + +// The following methods are useful to clear the cache +// delete a given cache +flatCache.clearCacheById('cacheId'); // removes the cacheId document if one exists. + +// delete all cache +flatCache.clearAll(); // remove the cache directory +``` + +## Motivation for this module + +I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make +a script that will beutify files with `esformatter` only execute on the files that were changed since the last run. +To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value` +storage was needed and Bam! this module was born. + +## Important notes + +- If no directory is especified when the `load` method is called, a folder named `.cache` will be created + inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you + might want to ignore the default `.cache` folder, or specify a custom directory. +- The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references +- All the changes to the cache state are done to memory +- I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module + intentionally dumb and simple +- Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call + like: `cache.save( true /* noPrune */ )`. + +## License + +MIT + +## Changelog + +[changelog](./changelog.md) diff --git a/node_modules/flat-cache/changelog.md b/node_modules/flat-cache/changelog.md new file mode 100644 index 00000000..866f9501 --- /dev/null +++ b/node_modules/flat-cache/changelog.md @@ -0,0 +1,278 @@ +# flat-cache - Changelog + +## v3.0.4 + +- **Refactoring** + - add files by name to the list of exported files - [89a2698](https://github.com/royriojas/flat-cache/commit/89a2698), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 02:35:39 + +## v3.0.3 + +- **Bug Fixes** + - Fix wrong eslint command - [f268e42](https://github.com/royriojas/flat-cache/commit/f268e42), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 02:15:04 + +## v3.0.2 + +- **Refactoring** + + - Update the files paths - [6983a80](https://github.com/royriojas/flat-cache/commit/6983a80), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:58:39 + - Move code to src/ - [18ed6e8](https://github.com/royriojas/flat-cache/commit/18ed6e8), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:57:17 + - Change eslint-cache location - [beed74c](https://github.com/royriojas/flat-cache/commit/beed74c), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:48:32 + +## v3.0.1 + +- **Refactoring** + - Remove unused deps - [8c6d9dc](https://github.com/royriojas/flat-cache/commit/8c6d9dc), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:43:29 + +## v3.0.0 + +- **Refactoring** + - Fix engines - [52b824c](https://github.com/royriojas/flat-cache/commit/52b824c), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:01:52 +- **Other changes** + + - Replace write with combination of mkdir and writeFile ([#49](https://github.com/royriojas/flat-cache/issues/49)) - [ef48276](https://github.com/royriojas/flat-cache/commit/ef48276), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 08/11/2020 00:17:15 + + Node v10 introduced a great "recursive" option for mkdir which allows to + get rid from mkdirp package and easily rewrite "write" package usage + with two function calls. + + https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback + + - Added a testcase for clearAll ([#48](https://github.com/royriojas/flat-cache/issues/48)) - [45b51ca](https://github.com/royriojas/flat-cache/commit/45b51ca), [Aaron Chen](https://github.com/Aaron Chen), 21/05/2020 08:40:03 + - requet node>=10 - [a5c482c](https://github.com/royriojas/flat-cache/commit/a5c482c), [yumetodo](https://github.com/yumetodo), 10/04/2020 23:14:53 + + thanks @SuperITMan + + - Update README.md - [29fe40b](https://github.com/royriojas/flat-cache/commit/29fe40b), [Roy Riojas](https://github.com/Roy Riojas), 10/04/2020 20:08:05 + - reduce vulnerability to 1 - [e9db1b2](https://github.com/royriojas/flat-cache/commit/e9db1b2), [yumetodo](https://github.com/yumetodo), 30/03/2020 11:10:43 + - reduce vulnerabilities dependencies to 8 - [b58d196](https://github.com/royriojas/flat-cache/commit/b58d196), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:54:56 + - use prettier instead of esbeautifier - [03b1db7](https://github.com/royriojas/flat-cache/commit/03b1db7), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:27:14 + - update proxyquire - [c2f048d](https://github.com/royriojas/flat-cache/commit/c2f048d), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:16:16 + - update flatted and mocha - [a0e56da](https://github.com/royriojas/flat-cache/commit/a0e56da), [yumetodo](https://github.com/yumetodo), 30/03/2020 09:46:45 + + mocha > mkdirp is updated + istanble >>> optimist > minimist is not updated + + - drop support node.js < 10 in develop - [beba691](https://github.com/royriojas/flat-cache/commit/beba691), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:31:09 + + see mkdirp + + - npm aufit fix(still remains) - [ce166cb](https://github.com/royriojas/flat-cache/commit/ce166cb), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:18:08 + + 37 vulnerabilities required manual review and could not be updated + + - updtate sinon - [9f2d1b6](https://github.com/royriojas/flat-cache/commit/9f2d1b6), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:17:51 + - apply eslint-plugin-mocha - [07343b5](https://github.com/royriojas/flat-cache/commit/07343b5), [yumetodo](https://github.com/yumetodo), 13/03/2020 22:17:21 + - Less strint version check ([#44](https://github.com/royriojas/flat-cache/issues/44)) - [92aca1c](https://github.com/royriojas/flat-cache/commit/92aca1c), [Wojciech Maj](https://github.com/Wojciech Maj), 13/11/2019 16:18:25 + + - Use ^ version matching for production dependencies + - Run npm audit fix + +- **Bug Fixes** + - update dependencies and use eslint directly - [73fbed2](https://github.com/royriojas/flat-cache/commit/73fbed2), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:17:27 + +## v2.0.1 + +- **Refactoring** + - upgrade node modules to latest versions - [6402ed3](https://github.com/royriojas/flat-cache/commit/6402ed3), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 18:47:05 + +## v2.0.0 + +- **Bug Fixes** + + - upgrade package.json lock file - [8d21c7b](https://github.com/royriojas/flat-cache/commit/8d21c7b), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 17:03:13 + - Use the same versions of node_js that eslint use - [8d23379](https://github.com/royriojas/flat-cache/commit/8d23379), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 16:25:11 + +- **Other changes** + + - Replace circular-json with flatted ([#36](https://github.com/royriojas/flat-cache/issues/36)) - [b93aced](https://github.com/royriojas/flat-cache/commit/b93aced), [C. K. Tang](https://github.com/C. K. Tang), 08/01/2019 17:03:01 + - Change JSON parser from circular-json to flatted & 1 more changes ([#37](https://github.com/royriojas/flat-cache/issues/37)) - [745e65a](https://github.com/royriojas/flat-cache/commit/745e65a), [Andy Chen](https://github.com/Andy Chen), 08/01/2019 16:17:20 + + - Change JSON parser from circular-json to flatted & 1 more changes + - Change JSON parser from circular-json + - Audited 2 vulnerabilities + - Update package.json + - Update Engine require + - There's a bunch of dependencies in this pkg requires node >=4, so I changed it to 4 + - Remove and add node versions + - I have seen this pkg is not available with node 0.12 so I removed it + - I have added a popular used LTS version of node - 10 + +## v1.3.4 + +- **Refactoring** + - Add del.js and utils.js to the list of files to be beautified - [9d0ca9b](https://github.com/royriojas/flat-cache/commit/9d0ca9b), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 12:19:02 + +## v1.3.3 + +- **Refactoring** + - Make sure package-lock.json is up to date - [a7d2598](https://github.com/royriojas/flat-cache/commit/a7d2598), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 11:36:08 +- **Other changes** + + - Removed the need for del ([#33](https://github.com/royriojas/flat-cache/issues/33)) - [c429012](https://github.com/royriojas/flat-cache/commit/c429012), [S. Gilroy](https://github.com/S. Gilroy), 13/11/2018 13:56:37 + + - Removed the need for del + + Removed the need for del as newer versions have broken backwards + compatibility. del mainly uses rimraf for deleting folders + and files, replaceing it with rimraf only is a minimal change. + + - Disable glob on rimraf calls + - Added glob disable to wrong call + - Wrapped rimraf to simplify solution + +## v1.3.2 + +- **Refactoring** + - remove yarn.lock file - [704c6c4](https://github.com/royriojas/flat-cache/commit/704c6c4), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:41:08 +- **Other changes** + + - replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23))" - [db12d74](https://github.com/royriojas/flat-cache/commit/db12d74), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:40:39 + + This reverts commit 00f689277a75e85fef28e6a048fad227afc525e6. + +## v1.3.1 + +- **Refactoring** + - upgrade deps to remove some security warnings - [f405719](https://github.com/royriojas/flat-cache/commit/f405719), [Roy Riojas](https://github.com/Roy Riojas), 06/11/2018 12:07:31 +- **Bug Fixes** + - replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23)) - [00f6892](https://github.com/royriojas/flat-cache/commit/00f6892), [Terry](https://github.com/Terry), 05/11/2018 18:44:16 +- **Other changes** + + - update del to v3.0.0 ([#26](https://github.com/royriojas/flat-cache/issues/26)) - [d42883f](https://github.com/royriojas/flat-cache/commit/d42883f), [Patrick Silva](https://github.com/Patrick Silva), 03/11/2018 01:00:44 + + Closes #25 + +## v1.3.0 + +- **Other changes** + + - Added #all method ([#16](https://github.com/royriojas/flat-cache/issues/16)) - [12293be](https://github.com/royriojas/flat-cache/commit/12293be), [Ozair Patel](https://github.com/Ozair Patel), 25/09/2017 14:46:38 + + - Added #all method + - Added #all method test + - Updated readme + - Added yarn.lock + - Added more keys for #all test + - Beautified file + + - fix changelog title style ([#14](https://github.com/royriojas/flat-cache/issues/14)) - [af8338a](https://github.com/royriojas/flat-cache/commit/af8338a), [前端小武](https://github.com/前端小武), 19/12/2016 20:34:48 + +## v1.2.2 + +- **Bug Fixes** + + - Do not crash if cache file is invalid JSON. ([#13](https://github.com/royriojas/flat-cache/issues/13)) - [87beaa6](https://github.com/royriojas/flat-cache/commit/87beaa6), [Roy Riojas](https://github.com/Roy Riojas), 19/12/2016 18:03:35 + + Fixes #12 + + Not sure under which situations a cache file might exist that does + not contain a valid JSON structure, but just in case to cover + the possibility of this happening a try catch block has been added + + If the cache is somehow not valid the cache will be discarded an a + a new cache will be stored instead + +- **Other changes** + + - Added travis ci support for modern node versions ([#11](https://github.com/royriojas/flat-cache/issues/11)) - [1c2b1f7](https://github.com/royriojas/flat-cache/commit/1c2b1f7), [Amila Welihinda](https://github.com/Amila Welihinda), 10/11/2016 23:47:52 + - Bumping `circular-son` version ([#10](https://github.com/royriojas/flat-cache/issues/10)) - [4d5e861](https://github.com/royriojas/flat-cache/commit/4d5e861), [Andrea Giammarchi](https://github.com/Andrea Giammarchi), 02/08/2016 07:13:52 + + As mentioned in https://github.com/WebReflection/circular-json/issues/25 `circular-json` wan't rightly implementing the license field. + + Latest version bump changed only that bit so that ESLint should now be happy. + +## v1.2.1 + +- **Bug Fixes** + - Add missing utils.js file to the package. closes [#8](https://github.com/royriojas/flat-cache/issues/8) - [ec10cf2](https://github.com/royriojas/flat-cache/commit/ec10cf2), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:18:57 + +## v1.2.0 + +- **Documentation** + - Add documentation about noPrune option - [23e11f9](https://github.com/royriojas/flat-cache/commit/23e11f9), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:06:49 + +## v1.0.11 + +- **Features** + + - Add noPrune option to cache.save() method. closes [#7](https://github.com/royriojas/flat-cache/issues/7) - [2c8016a](https://github.com/royriojas/flat-cache/commit/2c8016a), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:00:29 + - Add json read and write utility based on circular-json - [c31081e](https://github.com/royriojas/flat-cache/commit/c31081e), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:58:17 + +- **Bug Fixes** + + - Remove UTF16 BOM stripping - [4a41e22](https://github.com/royriojas/flat-cache/commit/4a41e22), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:18:06 + + Since we control both writing and reading of JSON stream, there no needs + to handle unicode BOM. + + - Use circular-json to handle circular references (fix [#5](https://github.com/royriojas/flat-cache/issues/5)) - [cd7aeed](https://github.com/royriojas/flat-cache/commit/cd7aeed), [Jean Ponchon](https://github.com/Jean Ponchon), 25/07/2016 11:11:59 + +- **Tests Related fixes** + + - Add missing file from eslint test - [d6fa3c3](https://github.com/royriojas/flat-cache/commit/d6fa3c3), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:15:51 + - Add test for circular json serialization / deserialization - [07d2ddd](https://github.com/royriojas/flat-cache/commit/07d2ddd), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:36 + +- **Refactoring** + - Remove unused read-json-sync - [2be1c24](https://github.com/royriojas/flat-cache/commit/2be1c24), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:18 +- **Build Scripts Changes** + - travis tests on 0.12 and 4x - [3a613fd](https://github.com/royriojas/flat-cache/commit/3a613fd), [royriojas](https://github.com/royriojas), 15/11/2015 14:34:40 + +## v1.0.10 + +- **Build Scripts Changes** + + - add eslint-fix task - [fd29e52](https://github.com/royriojas/flat-cache/commit/fd29e52), [royriojas](https://github.com/royriojas), 01/11/2015 15:04:08 + - make sure the test script also verify beautification and linting of files before running tests - [e94e176](https://github.com/royriojas/flat-cache/commit/e94e176), [royriojas](https://github.com/royriojas), 01/11/2015 11:54:48 + +- **Other changes** + - add clearAll for cacheDir - [97383d9](https://github.com/royriojas/flat-cache/commit/97383d9), [xieyaowu](https://github.com/xieyaowu), 31/10/2015 21:02:18 + +## v1.0.9 + +- **Bug Fixes** + - wrong default values for changelogx user repo name - [7bb52d1](https://github.com/royriojas/flat-cache/commit/7bb52d1), [royriojas](https://github.com/royriojas), 11/09/2015 15:59:30 + +## v1.0.8 + +- **Build Scripts Changes** + - test against node 4 - [c395b66](https://github.com/royriojas/flat-cache/commit/c395b66), [royriojas](https://github.com/royriojas), 11/09/2015 15:51:39 + +## v1.0.7 + +- **Other changes** + - Move dependencies into devDep - [7e47099](https://github.com/royriojas/flat-cache/commit/7e47099), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 15:10:57 +- **Documentation** + - Add missing changelog link - [f51197a](https://github.com/royriojas/flat-cache/commit/f51197a), [royriojas](https://github.com/royriojas), 11/09/2015 14:48:05 + +## v1.0.6 + +- **Build Scripts Changes** + - Add helpers/code check scripts - [bdb82f3](https://github.com/royriojas/flat-cache/commit/bdb82f3), [royriojas](https://github.com/royriojas), 11/09/2015 14:44:31 + +## v1.0.5 + +- **Documentation** + - better description for the module - [436817f](https://github.com/royriojas/flat-cache/commit/436817f), [royriojas](https://github.com/royriojas), 11/09/2015 14:35:33 +- **Other changes** + - Update dependencies - [be88aa3](https://github.com/royriojas/flat-cache/commit/be88aa3), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 13:47:41 + +## v1.0.4 + +- **Refactoring** + - load a cache file using the full filepath - [b8f68c2](https://github.com/royriojas/flat-cache/commit/b8f68c2), [Roy Riojas](https://github.com/Roy Riojas), 30/08/2015 04:19:14 +- **Documentation** + - Add documentation about `clearAll` and `clearCacheById` - [13947c1](https://github.com/royriojas/flat-cache/commit/13947c1), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:44:05 +- **Features** + - Add methods to remove the cache documents created - [af40443](https://github.com/royriojas/flat-cache/commit/af40443), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:39:27 + +## v1.0.1 + +- **Other changes** + - Update README.md - [c2b6805](https://github.com/royriojas/flat-cache/commit/c2b6805), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:28:07 + +## v1.0.0 + +- **Refactoring** + - flat-cache v.1.0.0 - [c984274](https://github.com/royriojas/flat-cache/commit/c984274), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:11:50 +- **Other changes** + - Initial commit - [d43cccf](https://github.com/royriojas/flat-cache/commit/d43cccf), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 01:12:16 diff --git a/node_modules/flat-cache/package.json b/node_modules/flat-cache/package.json new file mode 100644 index 00000000..b1248837 --- /dev/null +++ b/node_modules/flat-cache/package.json @@ -0,0 +1,63 @@ +{ + "name": "flat-cache", + "version": "4.0.1", + "description": "A stupidly simple key/value storage using files to persist some data", + "repository": "jaredwray/flat-cache", + "license": "MIT", + "author": { + "name": "Jared Wray", + "url": "https://jaredwray.com" + }, + "main": "src/cache.js", + "files": [ + "src/cache.js", + "src/del.js", + "src/utils.js" + ], + "engines": { + "node": ">=16" + }, + "precommit": [ + "npm run verify --silent" + ], + "prepush": [ + "npm run verify --silent" + ], + "scripts": { + "eslint": "eslint --cache --cache-location=node_modules/.cache/ ./src/**/*.js ./test/**/*.js", + "clean": "rimraf ./node_modules ./package-lock.json ./yarn.lock ./coverage", + "eslint-fix": "npm run eslint -- --fix", + "autofix": "npm run eslint-fix", + "check": "npm run eslint", + "verify": "npm run eslint && npm run test:cache", + "test:cache": "c8 mocha -R spec test/specs", + "test:ci:cache": "c8 --reporter=lcov mocha -R spec test/specs", + "test": "npm run verify --silent", + "format": "prettier --write ." + }, + "keywords": [ + "json cache", + "simple cache", + "file cache", + "key par", + "key value", + "cache" + ], + "devDependencies": { + "c8": "^9.1.0", + "chai": "^4.3.10", + "eslint": "^8.56.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-mocha": "^10.2.0", + "glob-expand": "^0.2.1", + "mocha": "^10.3.0", + "prettier": "^3.2.4", + "rimraf": "^5.0.5", + "sinon": "^17.0.1", + "write": "^2.0.0" + }, + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + } +} diff --git a/node_modules/flat-cache/src/cache.js b/node_modules/flat-cache/src/cache.js new file mode 100644 index 00000000..b1fdf6d8 --- /dev/null +++ b/node_modules/flat-cache/src/cache.js @@ -0,0 +1,214 @@ +const path = require('path'); +const fs = require('fs'); +const Keyv = require('keyv'); +const { writeJSON, tryParse } = require('./utils'); +const { del } = require('./del'); + +const cache = { + /** + * Load a cache identified by the given Id. If the element does not exists, then initialize an empty + * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted + * then the cache module directory `./cache` will be used instead + * + * @method load + * @param docId {String} the id of the cache, would also be used as the name of the file cache + * @param [cacheDir] {String} directory for the cache entry + */ + load: function (docId, cacheDir) { + const me = this; + me.keyv = new Keyv(); + + me.__visited = {}; + me.__persisted = {}; + + me._pathToFile = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, '../.cache/', docId); + + if (fs.existsSync(me._pathToFile)) { + me._persisted = tryParse(me._pathToFile, {}); + } + }, + + get _persisted() { + return this.__persisted; + }, + + set _persisted(value) { + this.__persisted = value; + }, + + get _visited() { + return this.__visited; + }, + + set _visited(value) { + this.__visited = value; + }, + + /** + * Load the cache from the provided file + * @method loadFile + * @param {String} pathToFile the path to the file containing the info for the cache + */ + loadFile: function (pathToFile) { + const me = this; + const dir = path.dirname(pathToFile); + const fName = path.basename(pathToFile); + + me.load(fName, dir); + }, + + /** + * Returns the entire persisted object + * @method all + * @returns {*} + */ + all: function () { + return this._persisted; + }, + + keys: function () { + return Object.keys(this._persisted); + }, + /** + * sets a key to a given value + * @method setKey + * @param key {string} the key to set + * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify + */ + setKey: function (key, value) { + this._visited[key] = true; + this._persisted[key] = value; + }, + /** + * remove a given key from the cache + * @method removeKey + * @param key {String} the key to remove from the object + */ + removeKey: function (key) { + delete this._visited[key]; // esfmt-ignore-line + delete this._persisted[key]; // esfmt-ignore-line + }, + /** + * Return the value of the provided key + * @method getKey + * @param key {String} the name of the key to retrieve + * @returns {*} the value from the key + */ + getKey: function (key) { + this._visited[key] = true; + return this._persisted[key]; + }, + + /** + * Remove keys that were not accessed/set since the + * last time the `prune` method was called. + * @method _prune + * @private + */ + _prune: function () { + const me = this; + const obj = {}; + + const keys = Object.keys(me._visited); + + // no keys visited for either get or set value + if (keys.length === 0) { + return; + } + + keys.forEach(function (key) { + obj[key] = me._persisted[key]; + }); + + me._visited = {}; + me._persisted = obj; + }, + + /** + * Save the state of the cache identified by the docId to disk + * as a JSON structure + * @param [noPrune=false] {Boolean} whether to remove from cache the non visited files + * @method save + */ + save: function (noPrune) { + const me = this; + !noPrune && me._prune(); + writeJSON(me._pathToFile, me._persisted); + }, + + /** + * remove the file where the cache is persisted + * @method removeCacheFile + * @return {Boolean} true or false if the file was successfully deleted + */ + removeCacheFile: function () { + return del(this._pathToFile); + }, + /** + * Destroy the file cache and cache content. + * @method destroy + */ + destroy: function () { + const me = this; + me._visited = {}; + me._persisted = {}; + + me.removeCacheFile(); + }, +}; + +module.exports = { + /** + * Alias for create. Should be considered depreacted. Will be removed in next releases + * + * @method load + * @param docId {String} the id of the cache, would also be used as the name of the file cache + * @param [cacheDir] {String} directory for the cache entry + * @returns {cache} cache instance + */ + load: function (docId, cacheDir) { + return this.create(docId, cacheDir); + }, + + /** + * Load a cache identified by the given Id. If the element does not exists, then initialize an empty + * cache storage. + * + * @method create + * @param docId {String} the id of the cache, would also be used as the name of the file cache + * @param [cacheDir] {String} directory for the cache entry + * @returns {cache} cache instance + */ + create: function (docId, cacheDir) { + const obj = Object.create(cache); + obj.load(docId, cacheDir); + return obj; + }, + + createFromFile: function (filePath) { + const obj = Object.create(cache); + obj.loadFile(filePath); + return obj; + }, + /** + * Clear the cache identified by the given id. Caches stored in a different cache directory can be deleted directly + * + * @method clearCache + * @param docId {String} the id of the cache, would also be used as the name of the file cache + * @param cacheDir {String} the directory where the cache file was written + * @returns {Boolean} true if the cache folder was deleted. False otherwise + */ + clearCacheById: function (docId, cacheDir) { + const filePath = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, '../.cache/', docId); + return del(filePath); + }, + /** + * Remove all cache stored in the cache directory + * @method clearAll + * @returns {Boolean} true if the cache folder was deleted. False otherwise + */ + clearAll: function (cacheDir) { + const filePath = cacheDir ? path.resolve(cacheDir) : path.resolve(__dirname, '../.cache/'); + return del(filePath); + }, +}; diff --git a/node_modules/flat-cache/src/del.js b/node_modules/flat-cache/src/del.js new file mode 100644 index 00000000..9cd55c36 --- /dev/null +++ b/node_modules/flat-cache/src/del.js @@ -0,0 +1,30 @@ +const fs = require('fs'); +const path = require('path'); + +function del(targetPath) { + if (!fs.existsSync(targetPath)) { + return false; + } + + try { + if (fs.statSync(targetPath).isDirectory()) { + // If it's a directory, delete its contents first + fs.readdirSync(targetPath).forEach(file => { + const curPath = path.join(targetPath, file); + + if (fs.statSync(curPath).isFile()) { + fs.unlinkSync(curPath); // Delete file + } + }); + fs.rmdirSync(targetPath); // Delete the now-empty directory + } else { + fs.unlinkSync(targetPath); // If it's a file, delete it directly + } + + return true; + } catch (error) { + console.error(`Error while deleting ${targetPath}: ${error.message}`); + } +} + +module.exports = { del }; diff --git a/node_modules/flat-cache/src/utils.js b/node_modules/flat-cache/src/utils.js new file mode 100644 index 00000000..c4f75fbc --- /dev/null +++ b/node_modules/flat-cache/src/utils.js @@ -0,0 +1,42 @@ +const fs = require('fs'); +const path = require('path'); +const flatted = require('flatted'); + +function tryParse(filePath, defaultValue) { + let result; + try { + result = readJSON(filePath); + } catch (ex) { + result = defaultValue; + } + return result; +} + +/** + * Read json file synchronously using flatted + * + * @param {String} filePath Json filepath + * @returns {*} parse result + */ +function readJSON(filePath) { + return flatted.parse( + fs.readFileSync(filePath, { + encoding: 'utf8', + }) + ); +} + +/** + * Write json file synchronously using circular-json + * + * @param {String} filePath Json filepath + * @param {*} data Object to serialize + */ +function writeJSON(filePath, data) { + fs.mkdirSync(path.dirname(filePath), { + recursive: true, + }); + fs.writeFileSync(filePath, flatted.stringify(data)); +} + +module.exports = { tryParse, readJSON, writeJSON }; diff --git a/node_modules/flatted/LICENSE b/node_modules/flatted/LICENSE new file mode 100644 index 00000000..506dc479 --- /dev/null +++ b/node_modules/flatted/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2018-2020, Andrea Giammarchi, @WebReflection + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/flatted/README.md b/node_modules/flatted/README.md new file mode 100644 index 00000000..f01c4c4c --- /dev/null +++ b/node_modules/flatted/README.md @@ -0,0 +1,115 @@ +# flatted + +[![Downloads](https://img.shields.io/npm/dm/flatted.svg)](https://www.npmjs.com/package/flatted) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/flatted/badge.svg?branch=main)](https://coveralls.io/github/WebReflection/flatted?branch=main) [![Build Status](https://travis-ci.com/WebReflection/flatted.svg?branch=main)](https://travis-ci.com/WebReflection/flatted) [![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC) ![WebReflection status](https://offline.report/status/webreflection.svg) + +![snow flake](./flatted.jpg) + +**Social Media Photo by [Matt Seymour](https://unsplash.com/@mattseymour) on [Unsplash](https://unsplash.com/)** + +A super light (0.5K) and fast circular JSON parser, directly from the creator of [CircularJSON](https://github.com/WebReflection/circular-json/#circularjson). + +Available also for **[PHP](./php/flatted.php)**. + +Available also for **[Python](./python/flatted.py)**. + +- - - + +## Announcement 📣 + +There is a standard approach to recursion and more data-types than what JSON allows, and it's part of the [Structured Clone polyfill](https://github.com/ungap/structured-clone/#readme). + +Beside acting as a polyfill, its `@ungap/structured-clone/json` export provides both `stringify` and `parse`, and it's been tested for being faster than *flatted*, but its produced output is also smaller than *flatted* in general. + +The *@ungap/structured-clone* module is, in short, a drop in replacement for *flatted*, but it's not compatible with *flatted* specialized syntax. + +However, if recursion, as well as more data-types, are what you are after, or interesting for your projects/use cases, consider switching to this new module whenever you can 👍 + +- - - + +```js +npm i flatted +``` + +Usable via [CDN](https://unpkg.com/flatted) or as regular module. + +```js +// ESM +import {parse, stringify, toJSON, fromJSON} from 'flatted'; + +// CJS +const {parse, stringify, toJSON, fromJSON} = require('flatted'); + +const a = [{}]; +a[0].a = a; +a.push(a); + +stringify(a); // [["1","0"],{"a":"0"}] +``` + +## toJSON and fromJSON + +If you'd like to implicitly survive JSON serialization, these two helpers helps: + +```js +import {toJSON, fromJSON} from 'flatted'; + +class RecursiveMap extends Map { + static fromJSON(any) { + return new this(fromJSON(any)); + } + toJSON() { + return toJSON([...this.entries()]); + } +} + +const recursive = new RecursiveMap; +const same = {}; +same.same = same; +recursive.set('same', same); + +const asString = JSON.stringify(recursive); +const asMap = RecursiveMap.fromJSON(JSON.parse(asString)); +asMap.get('same') === asMap.get('same').same; +// true +``` + + +## Flatted VS JSON + +As it is for every other specialized format capable of serializing and deserializing circular data, you should never `JSON.parse(Flatted.stringify(data))`, and you should never `Flatted.parse(JSON.stringify(data))`. + +The only way this could work is to `Flatted.parse(Flatted.stringify(data))`, as it is also for _CircularJSON_ or any other, otherwise there's no granted data integrity. + +Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected. + + +### New in V1: Exact same JSON API + + * Added a [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Syntax) parameter to `.parse(string, reviver)` and revive your own objects. + * Added a [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax) and a `space` parameter to `.stringify(object, replacer, space)` for feature parity with JSON signature. + + +### Compatibility +All ECMAScript engines compatible with `Map`, `Set`, `Object.keys`, and `Array.prototype.reduce` will work, even if polyfilled. + + +### How does it work ? +While stringifying, all Objects, including Arrays, and strings, are flattened out and replaced as unique index. `*` + +Once parsed, all indexes will be replaced through the flattened collection. + +`*` represented as string to avoid conflicts with numbers + +```js +// logic example +var a = [{one: 1}, {two: '2'}]; +a[0].a = a; +// a is the main object, will be at index '0' +// {one: 1} is the second object, index '1' +// {two: '2'} the third, in '2', and it has a string +// which will be found at index '3' + +Flatted.stringify(a); +// [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"] +// a[one,two] {one: 1, a} {two: '2'} '2' +``` diff --git a/node_modules/flatted/cjs/index.js b/node_modules/flatted/cjs/index.js new file mode 100644 index 00000000..7591f259 --- /dev/null +++ b/node_modules/flatted/cjs/index.js @@ -0,0 +1,125 @@ +'use strict'; +/// + +// (c) 2020-present Andrea Giammarchi + +const {parse: $parse, stringify: $stringify} = JSON; +const {keys} = Object; + +const Primitive = String; // it could be Number +const primitive = 'string'; // it could be 'number' + +const ignore = {}; +const object = 'object'; + +const noop = (_, value) => value; + +const primitives = value => ( + value instanceof Primitive ? Primitive(value) : value +); + +const Primitives = (_, value) => ( + typeof value === primitive ? new Primitive(value) : value +); + +const revive = (input, parsed, output, $) => { + const lazy = []; + for (let ke = keys(output), {length} = ke, y = 0; y < length; y++) { + const k = ke[y]; + const value = output[k]; + if (value instanceof Primitive) { + const tmp = input[value]; + if (typeof tmp === object && !parsed.has(tmp)) { + parsed.add(tmp); + output[k] = ignore; + lazy.push({k, a: [input, parsed, tmp, $]}); + } + else + output[k] = $.call(output, k, tmp); + } + else if (output[k] !== ignore) + output[k] = $.call(output, k, value); + } + for (let {length} = lazy, i = 0; i < length; i++) { + const {k, a} = lazy[i]; + output[k] = $.call(output, k, revive.apply(null, a)); + } + return output; +}; + +const set = (known, input, value) => { + const index = Primitive(input.push(value) - 1); + known.set(value, index); + return index; +}; + +/** + * Converts a specialized flatted string into a JS value. + * @param {string} text + * @param {(this: any, key: string, value: any) => any} [reviver] + * @returns {any} + */ +const parse = (text, reviver) => { + const input = $parse(text, Primitives).map(primitives); + const value = input[0]; + const $ = reviver || noop; + const tmp = typeof value === object && value ? + revive(input, new Set, value, $) : + value; + return $.call({'': tmp}, '', tmp); +}; +exports.parse = parse; + +/** + * Converts a JS value into a specialized flatted string. + * @param {any} value + * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer] + * @param {string | number | undefined} [space] + * @returns {string} + */ +const stringify = (value, replacer, space) => { + const $ = replacer && typeof replacer === object ? + (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) : + (replacer || noop); + const known = new Map; + const input = []; + const output = []; + let i = +set(known, input, $.call({'': value}, '', value)); + let firstRun = !i; + while (i < input.length) { + firstRun = true; + output[i] = $stringify(input[i++], replace, space); + } + return '[' + output.join(',') + ']'; + function replace(key, value) { + if (firstRun) { + firstRun = !firstRun; + return value; + } + const after = $.call(this, key, value); + switch (typeof after) { + case object: + if (after === null) return after; + case primitive: + return known.get(after) || set(known, input, after); + } + return after; + } +}; +exports.stringify = stringify; + +/** + * Converts a generic value into a JSON serializable object without losing recursion. + * @param {any} value + * @returns {any} + */ +const toJSON = value => $parse(stringify(value)); +exports.toJSON = toJSON; + +/** + * Converts a previously serialized object with recursion into a recursive one. + * @param {any} value + * @returns {any} + */ +const fromJSON = value => parse($stringify(value)); +exports.fromJSON = fromJSON; diff --git a/node_modules/flatted/cjs/package.json b/node_modules/flatted/cjs/package.json new file mode 100644 index 00000000..0292b995 --- /dev/null +++ b/node_modules/flatted/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} \ No newline at end of file diff --git a/node_modules/flatted/es.js b/node_modules/flatted/es.js new file mode 100644 index 00000000..42c98aef --- /dev/null +++ b/node_modules/flatted/es.js @@ -0,0 +1 @@ +self.Flatted=function(t){"use strict";const{parse:e,stringify:n}=JSON,{keys:r}=Object,s=String,o="string",c={},l="object",a=(t,e)=>e,f=t=>t instanceof s?s(t):t,i=(t,e)=>typeof e===o?new s(e):e,u=(t,e,n,o)=>{const a=[];for(let f=r(n),{length:i}=f,u=0;u{const r=s(e.push(n)-1);return t.set(n,r),r},y=(t,n)=>{const r=e(t,i).map(f),s=r[0],o=n||a,c=typeof s===l&&s?u(r,new Set,s,o):s;return o.call({"":c},"",c)},g=(t,e,r)=>{const s=e&&typeof e===l?(t,n)=>""===t||-1y(n(t)),t.parse=y,t.stringify=g,t.toJSON=t=>e(g(t)),t}({}); diff --git a/node_modules/flatted/esm.js b/node_modules/flatted/esm.js new file mode 100644 index 00000000..a5d5351e --- /dev/null +++ b/node_modules/flatted/esm.js @@ -0,0 +1 @@ +const{parse:t,stringify:e}=JSON,{keys:n}=Object,l=String,o="string",r={},s="object",c=(t,e)=>e,a=t=>t instanceof l?l(t):t,f=(t,e)=>typeof e===o?new l(e):e,i=(t,e,o,c)=>{const a=[];for(let f=n(o),{length:i}=f,p=0;p{const o=l(e.push(n)-1);return t.set(n,o),o},u=(e,n)=>{const l=t(e,f).map(a),o=l[0],r=n||c,p=typeof o===s&&o?i(l,new Set,o,r):o;return r.call({"":p},"",p)},h=(t,n,l)=>{const r=n&&typeof n===s?(t,e)=>""===t||-1t(h(e)),g=t=>u(e(t));export{g as fromJSON,u as parse,h as stringify,y as toJSON}; diff --git a/node_modules/flatted/esm/index.js b/node_modules/flatted/esm/index.js new file mode 100644 index 00000000..d203851a --- /dev/null +++ b/node_modules/flatted/esm/index.js @@ -0,0 +1,120 @@ +/// + +// (c) 2020-present Andrea Giammarchi + +const {parse: $parse, stringify: $stringify} = JSON; +const {keys} = Object; + +const Primitive = String; // it could be Number +const primitive = 'string'; // it could be 'number' + +const ignore = {}; +const object = 'object'; + +const noop = (_, value) => value; + +const primitives = value => ( + value instanceof Primitive ? Primitive(value) : value +); + +const Primitives = (_, value) => ( + typeof value === primitive ? new Primitive(value) : value +); + +const revive = (input, parsed, output, $) => { + const lazy = []; + for (let ke = keys(output), {length} = ke, y = 0; y < length; y++) { + const k = ke[y]; + const value = output[k]; + if (value instanceof Primitive) { + const tmp = input[value]; + if (typeof tmp === object && !parsed.has(tmp)) { + parsed.add(tmp); + output[k] = ignore; + lazy.push({k, a: [input, parsed, tmp, $]}); + } + else + output[k] = $.call(output, k, tmp); + } + else if (output[k] !== ignore) + output[k] = $.call(output, k, value); + } + for (let {length} = lazy, i = 0; i < length; i++) { + const {k, a} = lazy[i]; + output[k] = $.call(output, k, revive.apply(null, a)); + } + return output; +}; + +const set = (known, input, value) => { + const index = Primitive(input.push(value) - 1); + known.set(value, index); + return index; +}; + +/** + * Converts a specialized flatted string into a JS value. + * @param {string} text + * @param {(this: any, key: string, value: any) => any} [reviver] + * @returns {any} + */ +export const parse = (text, reviver) => { + const input = $parse(text, Primitives).map(primitives); + const value = input[0]; + const $ = reviver || noop; + const tmp = typeof value === object && value ? + revive(input, new Set, value, $) : + value; + return $.call({'': tmp}, '', tmp); +}; + +/** + * Converts a JS value into a specialized flatted string. + * @param {any} value + * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer] + * @param {string | number | undefined} [space] + * @returns {string} + */ +export const stringify = (value, replacer, space) => { + const $ = replacer && typeof replacer === object ? + (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) : + (replacer || noop); + const known = new Map; + const input = []; + const output = []; + let i = +set(known, input, $.call({'': value}, '', value)); + let firstRun = !i; + while (i < input.length) { + firstRun = true; + output[i] = $stringify(input[i++], replace, space); + } + return '[' + output.join(',') + ']'; + function replace(key, value) { + if (firstRun) { + firstRun = !firstRun; + return value; + } + const after = $.call(this, key, value); + switch (typeof after) { + case object: + if (after === null) return after; + case primitive: + return known.get(after) || set(known, input, after); + } + return after; + } +}; + +/** + * Converts a generic value into a JSON serializable object without losing recursion. + * @param {any} value + * @returns {any} + */ +export const toJSON = value => $parse(stringify(value)); + +/** + * Converts a previously serialized object with recursion into a recursive one. + * @param {any} value + * @returns {any} + */ +export const fromJSON = value => parse($stringify(value)); diff --git a/node_modules/flatted/index.js b/node_modules/flatted/index.js new file mode 100644 index 00000000..f40414ab --- /dev/null +++ b/node_modules/flatted/index.js @@ -0,0 +1,146 @@ +self.Flatted = (function (exports) { + 'use strict'; + + function _typeof(o) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof(o); + } + + /// + + // (c) 2020-present Andrea Giammarchi + + var $parse = JSON.parse, + $stringify = JSON.stringify; + var keys = Object.keys; + var Primitive = String; // it could be Number + var primitive = 'string'; // it could be 'number' + + var ignore = {}; + var object = 'object'; + var noop = function noop(_, value) { + return value; + }; + var primitives = function primitives(value) { + return value instanceof Primitive ? Primitive(value) : value; + }; + var Primitives = function Primitives(_, value) { + return _typeof(value) === primitive ? new Primitive(value) : value; + }; + var _revive = function revive(input, parsed, output, $) { + var lazy = []; + for (var ke = keys(output), length = ke.length, y = 0; y < length; y++) { + var k = ke[y]; + var value = output[k]; + if (value instanceof Primitive) { + var tmp = input[value]; + if (_typeof(tmp) === object && !parsed.has(tmp)) { + parsed.add(tmp); + output[k] = ignore; + lazy.push({ + k: k, + a: [input, parsed, tmp, $] + }); + } else output[k] = $.call(output, k, tmp); + } else if (output[k] !== ignore) output[k] = $.call(output, k, value); + } + for (var _length = lazy.length, i = 0; i < _length; i++) { + var _lazy$i = lazy[i], + _k = _lazy$i.k, + a = _lazy$i.a; + output[_k] = $.call(output, _k, _revive.apply(null, a)); + } + return output; + }; + var set = function set(known, input, value) { + var index = Primitive(input.push(value) - 1); + known.set(value, index); + return index; + }; + + /** + * Converts a specialized flatted string into a JS value. + * @param {string} text + * @param {(this: any, key: string, value: any) => any} [reviver] + * @returns {any} + */ + var parse = function parse(text, reviver) { + var input = $parse(text, Primitives).map(primitives); + var value = input[0]; + var $ = reviver || noop; + var tmp = _typeof(value) === object && value ? _revive(input, new Set(), value, $) : value; + return $.call({ + '': tmp + }, '', tmp); + }; + + /** + * Converts a JS value into a specialized flatted string. + * @param {any} value + * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer] + * @param {string | number | undefined} [space] + * @returns {string} + */ + var stringify = function stringify(value, replacer, space) { + var $ = replacer && _typeof(replacer) === object ? function (k, v) { + return k === '' || -1 < replacer.indexOf(k) ? v : void 0; + } : replacer || noop; + var known = new Map(); + var input = []; + var output = []; + var i = +set(known, input, $.call({ + '': value + }, '', value)); + var firstRun = !i; + while (i < input.length) { + firstRun = true; + output[i] = $stringify(input[i++], replace, space); + } + return '[' + output.join(',') + ']'; + function replace(key, value) { + if (firstRun) { + firstRun = !firstRun; + return value; + } + var after = $.call(this, key, value); + switch (_typeof(after)) { + case object: + if (after === null) return after; + case primitive: + return known.get(after) || set(known, input, after); + } + return after; + } + }; + + /** + * Converts a generic value into a JSON serializable object without losing recursion. + * @param {any} value + * @returns {any} + */ + var toJSON = function toJSON(value) { + return $parse(stringify(value)); + }; + + /** + * Converts a previously serialized object with recursion into a recursive one. + * @param {any} value + * @returns {any} + */ + var fromJSON = function fromJSON(value) { + return parse($stringify(value)); + }; + + exports.fromJSON = fromJSON; + exports.parse = parse; + exports.stringify = stringify; + exports.toJSON = toJSON; + + return exports; + +})({}); diff --git a/node_modules/flatted/min.js b/node_modules/flatted/min.js new file mode 100644 index 00000000..ad049a4a --- /dev/null +++ b/node_modules/flatted/min.js @@ -0,0 +1 @@ +self.Flatted=function(n){"use strict";function t(n){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(n){return typeof n}:function(n){return n&&"function"==typeof Symbol&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},t(n)}var r=JSON.parse,e=JSON.stringify,o=Object.keys,u=String,f="string",i={},c="object",a=function(n,t){return t},l=function(n){return n instanceof u?u(n):n},s=function(n,r){return t(r)===f?new u(r):r},y=function(n,r,e,f){for(var a=[],l=o(e),s=l.length,p=0;p ./coverage/lcov.info" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/WebReflection/flatted.git" + }, + "files": [ + "LICENSE", + "README.md", + "cjs/", + "es.js", + "esm.js", + "esm/", + "index.js", + "min.js", + "php/flatted.php", + "python/flatted.py", + "types/" + ], + "keywords": [ + "circular", + "JSON", + "fast", + "parser", + "minimal" + ], + "author": "Andrea Giammarchi", + "license": "ISC", + "bugs": { + "url": "https://github.com/WebReflection/flatted/issues" + }, + "homepage": "https://github.com/WebReflection/flatted#readme", + "devDependencies": { + "@babel/core": "^7.26.9", + "@babel/preset-env": "^7.26.9", + "@rollup/plugin-babel": "^6.0.4", + "@rollup/plugin-terser": "^0.4.4", + "@ungap/structured-clone": "^1.3.0", + "ascjs": "^6.0.3", + "c8": "^10.1.3", + "circular-json": "^0.5.9", + "circular-json-es6": "^2.0.2", + "jsan": "^3.1.14", + "rollup": "^4.34.8", + "terser": "^5.39.0", + "typescript": "^5.7.3" + }, + "module": "./esm/index.js", + "type": "module", + "exports": { + ".": { + "types": "./types/index.d.ts", + "import": "./esm/index.js", + "default": "./cjs/index.js" + }, + "./esm": "./esm.js", + "./package.json": "./package.json" + }, + "types": "./types/index.d.ts" +} diff --git a/node_modules/flatted/php/flatted.php b/node_modules/flatted/php/flatted.php new file mode 100644 index 00000000..22659f6a --- /dev/null +++ b/node_modules/flatted/php/flatted.php @@ -0,0 +1,156 @@ +value = $value; + } +} + +class Flatted { + + // public utilities + public static function parse($json, $assoc = false, $depth = 512, $options = 0) { + $input = array_map( + 'Flatted::asString', + array_map( + 'Flatted::wrap', + json_decode($json, $assoc, $depth, $options) + ) + ); + $value = &$input[0]; + $set = array(); + $set[] = &$value; + if (is_array($value)) + return Flatted::loop(false, array_keys($value), $input, $set, $value); + if (is_object($value)) + return Flatted::loop(true, Flatted::keys($value), $input, $set, $value); + return $value; + } + + public static function stringify($value, $options = 0, $depth = 512) { + $known = new stdClass; + $known->key = array(); + $known->value = array(); + $input = array(); + $output = array(); + $i = intval(Flatted::index($known, $input, $value)); + while ($i < count($input)) { + $output[$i] = Flatted::transform($known, $input, $input[$i]); + $i++; + } + return json_encode($output, $options, $depth); + } + + // private helpers + private static function asString($value) { + return $value instanceof FlattedString ? $value->value : $value; + } + + private static function index(&$known, &$input, &$value) { + $input[] = &$value; + $index = strval(count($input) - 1); + $known->key[] = &$value; + $known->value[] = &$index; + return $index; + } + + private static function keys(&$value) { + $obj = new ReflectionObject($value); + $props = $obj->getProperties(); + $keys = array(); + foreach ($props as $prop) + $keys[] = $prop->getName(); + return $keys; + } + + private static function loop($obj, $keys, &$input, &$set, &$output) { + foreach ($keys as $key) { + $value = $obj ? $output->$key : $output[$key]; + if ($value instanceof FlattedString) + Flatted::ref($obj, $key, $input[$value->value], $input, $set, $output); + } + return $output; + } + + private static function relate(&$known, &$input, &$value) { + if (is_string($value) || is_array($value) || is_object($value)) { + $key = array_search($value, $known->key, true); + if ($key !== false) + return $known->value[$key]; + return Flatted::index($known, $input, $value); + } + return $value; + } + + private static function ref($obj, &$key, &$value, &$input, &$set, &$output) { + if (is_array($value) && !in_array($value, $set, true)) { + $set[] = $value; + $value = Flatted::loop(false, array_keys($value), $input, $set, $value); + } + elseif (is_object($value) && !in_array($value, $set, true)) { + $set[] = $value; + $value = Flatted::loop(true, Flatted::keys($value), $input, $set, $value); + } + if ($obj) { + $output->$key = &$value; + } + else { + $output[$key] = &$value; + } + } + + private static function transform(&$known, &$input, &$value) { + if (is_array($value)) { + return array_map( + function ($value) use(&$known, &$input) { + return Flatted::relate($known, $input, $value); + }, + $value + ); + } + if (is_object($value)) { + $object = new stdClass; + $keys = Flatted::keys($value); + foreach ($keys as $key) + $object->$key = Flatted::relate($known, $input, $value->$key); + return $object; + } + return $value; + } + + private static function wrap($value) { + if (is_string($value)) { + return new FlattedString($value); + } + if (is_array($value)) { + return array_map('Flatted::wrap', $value); + } + if (is_object($value)) { + $keys = Flatted::keys($value); + foreach ($keys as $key) { + $value->$key = self::wrap($value->$key); + } + } + return $value; + } +} +?> \ No newline at end of file diff --git a/node_modules/flatted/python/flatted.py b/node_modules/flatted/python/flatted.py new file mode 100644 index 00000000..a7e57fc9 --- /dev/null +++ b/node_modules/flatted/python/flatted.py @@ -0,0 +1,149 @@ +# ISC License +# +# Copyright (c) 2018-2025, Andrea Giammarchi, @WebReflection +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +# PERFORMANCE OF THIS SOFTWARE. + +import json as _json + +class _Known: + def __init__(self): + self.key = [] + self.value = [] + +class _String: + def __init__(self, value): + self.value = value + + +def _array_keys(value): + keys = [] + i = 0 + for _ in value: + keys.append(i) + i += 1 + return keys + +def _object_keys(value): + keys = [] + for key in value: + keys.append(key) + return keys + +def _is_array(value): + return isinstance(value, (list, tuple)) + +def _is_object(value): + return isinstance(value, dict) + +def _is_string(value): + return isinstance(value, str) + +def _index(known, input, value): + input.append(value) + index = str(len(input) - 1) + known.key.append(value) + known.value.append(index) + return index + +def _loop(keys, input, known, output): + for key in keys: + value = output[key] + if isinstance(value, _String): + _ref(key, input[int(value.value)], input, known, output) + + return output + +def _ref(key, value, input, known, output): + if _is_array(value) and value not in known: + known.append(value) + value = _loop(_array_keys(value), input, known, value) + elif _is_object(value) and value not in known: + known.append(value) + value = _loop(_object_keys(value), input, known, value) + + output[key] = value + +def _relate(known, input, value): + if _is_string(value) or _is_array(value) or _is_object(value): + try: + return known.value[known.key.index(value)] + except: + return _index(known, input, value) + + return value + +def _transform(known, input, value): + if _is_array(value): + output = [] + for val in value: + output.append(_relate(known, input, val)) + return output + + if _is_object(value): + obj = {} + for key in value: + obj[key] = _relate(known, input, value[key]) + return obj + + return value + +def _wrap(value): + if _is_string(value): + return _String(value) + + if _is_array(value): + i = 0 + for val in value: + value[i] = _wrap(val) + i += 1 + + elif _is_object(value): + for key in value: + value[key] = _wrap(value[key]) + + return value + +def parse(value, *args, **kwargs): + json = _json.loads(value, *args, **kwargs) + wrapped = [] + for value in json: + wrapped.append(_wrap(value)) + + input = [] + for value in wrapped: + if isinstance(value, _String): + input.append(value.value) + else: + input.append(value) + + value = input[0] + + if _is_array(value): + return _loop(_array_keys(value), input, [value], value) + + if _is_object(value): + return _loop(_object_keys(value), input, [value], value) + + return value + + +def stringify(value, *args, **kwargs): + known = _Known() + input = [] + output = [] + i = int(_index(known, input, value)) + while i < len(input): + output.append(_transform(known, input, input[i])) + i += 1 + return _json.dumps(output, *args, **kwargs) diff --git a/node_modules/flatted/types/index.d.ts b/node_modules/flatted/types/index.d.ts new file mode 100644 index 00000000..75dac338 --- /dev/null +++ b/node_modules/flatted/types/index.d.ts @@ -0,0 +1,4 @@ +export function parse(text: string, reviver?: (this: any, key: string, value: any) => any): any; +export function stringify(value: any, replacer?: (string | number)[] | ((this: any, key: string, value: any) => any), space?: string | number | undefined): string; +export function toJSON(value: any): any; +export function fromJSON(value: any): any; diff --git a/node_modules/glob-parent/LICENSE b/node_modules/glob-parent/LICENSE new file mode 100644 index 00000000..d701b083 --- /dev/null +++ b/node_modules/glob-parent/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015, 2019 Elan Shanker, 2021 Blaine Bublitz , Eric Schoffstall and other contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/glob-parent/README.md b/node_modules/glob-parent/README.md new file mode 100644 index 00000000..6ae18a1a --- /dev/null +++ b/node_modules/glob-parent/README.md @@ -0,0 +1,134 @@ +

+ + + +

+ +# glob-parent + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Coveralls Status][coveralls-image]][coveralls-url] + +Extract the non-magic parent path from a glob string. + +## Usage + +```js +var globParent = require('glob-parent'); + +globParent('path/to/*.js'); // 'path/to' +globParent('/root/path/to/*.js'); // '/root/path/to' +globParent('/*.js'); // '/' +globParent('*.js'); // '.' +globParent('**/*.js'); // '.' +globParent('path/{to,from}'); // 'path' +globParent('path/!(to|from)'); // 'path' +globParent('path/?(to|from)'); // 'path' +globParent('path/+(to|from)'); // 'path' +globParent('path/*(to|from)'); // 'path' +globParent('path/@(to|from)'); // 'path' +globParent('path/**/*'); // 'path' + +// if provided a non-glob path, returns the nearest dir +globParent('path/foo/bar.js'); // 'path/foo' +globParent('path/foo/'); // 'path/foo' +globParent('path/foo'); // 'path' (see issue #3 for details) +``` + +## API + +### `globParent(maybeGlobString, [options])` + +Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. + +#### options + +```js +{ + // Disables the automatic conversion of slashes for Windows + flipBackslashes: true; +} +``` + +## Escaping + +The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: + +- `?` (question mark) unless used as a path segment alone +- `*` (asterisk) +- `|` (pipe) +- `(` (opening parenthesis) +- `)` (closing parenthesis) +- `{` (opening curly brace) +- `}` (closing curly brace) +- `[` (opening bracket) +- `]` (closing bracket) + +**Example** + +```js +globParent('foo/[bar]/'); // 'foo' +globParent('foo/\\[bar]/'); // 'foo/[bar]' +``` + +## Limitations + +### Braces & Brackets + +This library attempts a quick and imperfect method of determining which path +parts have glob magic without fully parsing/lexing the pattern. There are some +advanced use cases that can trip it up, such as nested braces where the outer +pair is escaped and the inner one contains a path separator. If you find +yourself in the unlikely circumstance of being affected by this or need to +ensure higher-fidelity glob handling in your library, it is recommended that you +pre-process your input with [expand-braces] and/or [expand-brackets]. + +### Windows + +Backslashes are not valid path separators for globs. If a path with backslashes +is provided anyway, for simple cases, glob-parent will replace the path +separator for you and return the non-glob parent path (now with +forward-slashes, which are still valid as Windows path separators). + +This cannot be used in conjunction with escape characters. + +```js +// BAD +globParent('C:\\Program Files \\(x86\\)\\*.ext'); // 'C:/Program Files /(x86/)' + +// GOOD +globParent('C:/Program Files\\(x86\\)/*.ext'); // 'C:/Program Files (x86)' +``` + +If you are using escape characters for a pattern without path parts (i.e. +relative to `cwd`), prefix with `./` to avoid confusing glob-parent. + +```js +// BAD +globParent('foo \\[bar]'); // 'foo ' +globParent('foo \\[bar]*'); // 'foo ' + +// GOOD +globParent('./foo \\[bar]'); // 'foo [bar]' +globParent('./foo \\[bar]*'); // '.' +``` + +## License + +ISC + + +[downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg?style=flat-square +[npm-url]: https://www.npmjs.com/package/glob-parent +[npm-image]: https://img.shields.io/npm/v/glob-parent.svg?style=flat-square + +[ci-url]: https://github.com/gulpjs/glob-parent/actions?query=workflow:dev +[ci-image]: https://img.shields.io/github/workflow/status/gulpjs/glob-parent/dev?style=flat-square + +[coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent +[coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg?style=flat-square + + + +[expand-braces]: https://github.com/jonschlinkert/expand-braces +[expand-brackets]: https://github.com/jonschlinkert/expand-brackets + diff --git a/node_modules/glob-parent/index.js b/node_modules/glob-parent/index.js new file mode 100644 index 00000000..09dde64b --- /dev/null +++ b/node_modules/glob-parent/index.js @@ -0,0 +1,75 @@ +'use strict'; + +var isGlob = require('is-glob'); +var pathPosixDirname = require('path').posix.dirname; +var isWin32 = require('os').platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var escaped = /\\([!*?|[\](){}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + */ +module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (isEnclosure(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlobby(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +function isEnclosure(str) { + var lastChar = str.slice(-1); + + var enclosureStart; + switch (lastChar) { + case '}': + enclosureStart = '{'; + break; + case ']': + enclosureStart = '['; + break; + default: + return false; + } + + var foundIndex = str.indexOf(enclosureStart); + if (foundIndex < 0) { + return false; + } + + return str.slice(foundIndex + 1, -1).includes(slash); +} + +function isGlobby(str) { + if (/\([^()]+$/.test(str)) { + return true; + } + if (str[0] === '{' || str[0] === '[') { + return true; + } + if (/[^\\][{[]/.test(str)) { + return true; + } + return isGlob(str); +} diff --git a/node_modules/glob-parent/package.json b/node_modules/glob-parent/package.json new file mode 100644 index 00000000..baeab421 --- /dev/null +++ b/node_modules/glob-parent/package.json @@ -0,0 +1,54 @@ +{ + "name": "glob-parent", + "version": "6.0.2", + "description": "Extract the non-magic parent path from a glob string.", + "author": "Gulp Team (https://gulpjs.com/)", + "contributors": [ + "Elan Shanker (https://github.com/es128)", + "Blaine Bublitz " + ], + "repository": "gulpjs/glob-parent", + "license": "ISC", + "engines": { + "node": ">=10.13.0" + }, + "main": "index.js", + "files": [ + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "pretest": "npm run lint", + "test": "nyc mocha --async-only" + }, + "dependencies": { + "is-glob": "^4.0.3" + }, + "devDependencies": { + "eslint": "^7.0.0", + "eslint-config-gulp": "^5.0.0", + "expect": "^26.0.1", + "mocha": "^7.1.2", + "nyc": "^15.0.1" + }, + "nyc": { + "reporter": [ + "lcov", + "text-summary" + ] + }, + "prettier": { + "singleQuote": true + }, + "keywords": [ + "glob", + "parent", + "strip", + "path", + "dirname", + "directory", + "base", + "wildcard" + ] +} diff --git a/node_modules/globals/globals.json b/node_modules/globals/globals.json new file mode 100644 index 00000000..4e75173f --- /dev/null +++ b/node_modules/globals/globals.json @@ -0,0 +1,1998 @@ +{ + "builtin": { + "AggregateError": false, + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "FinalizationRegistry": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakRef": false, + "WeakSet": false + }, + "es5": { + "Array": false, + "Boolean": false, + "constructor": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "propertyIsEnumerable": false, + "RangeError": false, + "ReferenceError": false, + "RegExp": false, + "String": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false + }, + "es2015": { + "Array": false, + "ArrayBuffer": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2017": { + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2020": { + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2021": { + "AggregateError": false, + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "FinalizationRegistry": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakRef": false, + "WeakSet": false + }, + "browser": { + "AbortController": false, + "AbortSignal": false, + "addEventListener": false, + "alert": false, + "AnalyserNode": false, + "Animation": false, + "AnimationEffectReadOnly": false, + "AnimationEffectTiming": false, + "AnimationEffectTimingReadOnly": false, + "AnimationEvent": false, + "AnimationPlaybackEvent": false, + "AnimationTimeline": false, + "applicationCache": false, + "ApplicationCache": false, + "ApplicationCacheErrorEvent": false, + "atob": false, + "Attr": false, + "Audio": false, + "AudioBuffer": false, + "AudioBufferSourceNode": false, + "AudioContext": false, + "AudioDestinationNode": false, + "AudioListener": false, + "AudioNode": false, + "AudioParam": false, + "AudioProcessingEvent": false, + "AudioScheduledSourceNode": false, + "AudioWorkletGlobalScope": false, + "AudioWorkletNode": false, + "AudioWorkletProcessor": false, + "BarProp": false, + "BaseAudioContext": false, + "BatteryManager": false, + "BeforeUnloadEvent": false, + "BiquadFilterNode": false, + "Blob": false, + "BlobEvent": false, + "blur": false, + "BroadcastChannel": false, + "btoa": false, + "BudgetService": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "CacheStorage": false, + "cancelAnimationFrame": false, + "cancelIdleCallback": false, + "CanvasCaptureMediaStreamTrack": false, + "CanvasGradient": false, + "CanvasPattern": false, + "CanvasRenderingContext2D": false, + "ChannelMergerNode": false, + "ChannelSplitterNode": false, + "CharacterData": false, + "clearInterval": false, + "clearTimeout": false, + "clientInformation": false, + "ClipboardEvent": false, + "ClipboardItem": false, + "close": false, + "closed": false, + "CloseEvent": false, + "Comment": false, + "CompositionEvent": false, + "CompressionStream": false, + "confirm": false, + "console": false, + "ConstantSourceNode": false, + "ConvolverNode": false, + "CountQueuingStrategy": false, + "createImageBitmap": false, + "Credential": false, + "CredentialsContainer": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CSS": false, + "CSSConditionRule": false, + "CSSFontFaceRule": false, + "CSSGroupingRule": false, + "CSSImportRule": false, + "CSSKeyframeRule": false, + "CSSKeyframesRule": false, + "CSSMatrixComponent": false, + "CSSMediaRule": false, + "CSSNamespaceRule": false, + "CSSPageRule": false, + "CSSPerspective": false, + "CSSRotate": false, + "CSSRule": false, + "CSSRuleList": false, + "CSSScale": false, + "CSSSkew": false, + "CSSSkewX": false, + "CSSSkewY": false, + "CSSStyleDeclaration": false, + "CSSStyleRule": false, + "CSSStyleSheet": false, + "CSSSupportsRule": false, + "CSSTransformValue": false, + "CSSTranslate": false, + "CustomElementRegistry": false, + "customElements": false, + "CustomEvent": false, + "DataTransfer": false, + "DataTransferItem": false, + "DataTransferItemList": false, + "DecompressionStream": false, + "defaultstatus": false, + "defaultStatus": false, + "DelayNode": false, + "DeviceMotionEvent": false, + "DeviceOrientationEvent": false, + "devicePixelRatio": false, + "dispatchEvent": false, + "document": false, + "Document": false, + "DocumentFragment": false, + "DocumentType": false, + "DOMError": false, + "DOMException": false, + "DOMImplementation": false, + "DOMMatrix": false, + "DOMMatrixReadOnly": false, + "DOMParser": false, + "DOMPoint": false, + "DOMPointReadOnly": false, + "DOMQuad": false, + "DOMRect": false, + "DOMRectList": false, + "DOMRectReadOnly": false, + "DOMStringList": false, + "DOMStringMap": false, + "DOMTokenList": false, + "DragEvent": false, + "DynamicsCompressorNode": false, + "Element": false, + "ErrorEvent": false, + "event": false, + "Event": false, + "EventSource": false, + "EventTarget": false, + "external": false, + "fetch": false, + "File": false, + "FileList": false, + "FileReader": false, + "find": false, + "focus": false, + "FocusEvent": false, + "FontFace": false, + "FontFaceSetLoadEvent": false, + "FormData": false, + "FormDataEvent": false, + "frameElement": false, + "frames": false, + "GainNode": false, + "Gamepad": false, + "GamepadButton": false, + "GamepadEvent": false, + "getComputedStyle": false, + "getSelection": false, + "HashChangeEvent": false, + "Headers": false, + "history": false, + "History": false, + "HTMLAllCollection": false, + "HTMLAnchorElement": false, + "HTMLAreaElement": false, + "HTMLAudioElement": false, + "HTMLBaseElement": false, + "HTMLBodyElement": false, + "HTMLBRElement": false, + "HTMLButtonElement": false, + "HTMLCanvasElement": false, + "HTMLCollection": false, + "HTMLContentElement": false, + "HTMLDataElement": false, + "HTMLDataListElement": false, + "HTMLDetailsElement": false, + "HTMLDialogElement": false, + "HTMLDirectoryElement": false, + "HTMLDivElement": false, + "HTMLDListElement": false, + "HTMLDocument": false, + "HTMLElement": false, + "HTMLEmbedElement": false, + "HTMLFieldSetElement": false, + "HTMLFontElement": false, + "HTMLFormControlsCollection": false, + "HTMLFormElement": false, + "HTMLFrameElement": false, + "HTMLFrameSetElement": false, + "HTMLHeadElement": false, + "HTMLHeadingElement": false, + "HTMLHRElement": false, + "HTMLHtmlElement": false, + "HTMLIFrameElement": false, + "HTMLImageElement": false, + "HTMLInputElement": false, + "HTMLLabelElement": false, + "HTMLLegendElement": false, + "HTMLLIElement": false, + "HTMLLinkElement": false, + "HTMLMapElement": false, + "HTMLMarqueeElement": false, + "HTMLMediaElement": false, + "HTMLMenuElement": false, + "HTMLMetaElement": false, + "HTMLMeterElement": false, + "HTMLModElement": false, + "HTMLObjectElement": false, + "HTMLOListElement": false, + "HTMLOptGroupElement": false, + "HTMLOptionElement": false, + "HTMLOptionsCollection": false, + "HTMLOutputElement": false, + "HTMLParagraphElement": false, + "HTMLParamElement": false, + "HTMLPictureElement": false, + "HTMLPreElement": false, + "HTMLProgressElement": false, + "HTMLQuoteElement": false, + "HTMLScriptElement": false, + "HTMLSelectElement": false, + "HTMLShadowElement": false, + "HTMLSlotElement": false, + "HTMLSourceElement": false, + "HTMLSpanElement": false, + "HTMLStyleElement": false, + "HTMLTableCaptionElement": false, + "HTMLTableCellElement": false, + "HTMLTableColElement": false, + "HTMLTableElement": false, + "HTMLTableRowElement": false, + "HTMLTableSectionElement": false, + "HTMLTemplateElement": false, + "HTMLTextAreaElement": false, + "HTMLTimeElement": false, + "HTMLTitleElement": false, + "HTMLTrackElement": false, + "HTMLUListElement": false, + "HTMLUnknownElement": false, + "HTMLVideoElement": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "IdleDeadline": false, + "IIRFilterNode": false, + "Image": false, + "ImageBitmap": false, + "ImageBitmapRenderingContext": false, + "ImageCapture": false, + "ImageData": false, + "indexedDB": false, + "innerHeight": false, + "innerWidth": false, + "InputEvent": false, + "IntersectionObserver": false, + "IntersectionObserverEntry": false, + "Intl": false, + "isSecureContext": false, + "KeyboardEvent": false, + "KeyframeEffect": false, + "KeyframeEffectReadOnly": false, + "length": false, + "localStorage": false, + "location": true, + "Location": false, + "locationbar": false, + "matchMedia": false, + "MediaDeviceInfo": false, + "MediaDevices": false, + "MediaElementAudioSourceNode": false, + "MediaEncryptedEvent": false, + "MediaError": false, + "MediaKeyMessageEvent": false, + "MediaKeySession": false, + "MediaKeyStatusMap": false, + "MediaKeySystemAccess": false, + "MediaList": false, + "MediaMetadata": false, + "MediaQueryList": false, + "MediaQueryListEvent": false, + "MediaRecorder": false, + "MediaSettingsRange": false, + "MediaSource": false, + "MediaStream": false, + "MediaStreamAudioDestinationNode": false, + "MediaStreamAudioSourceNode": false, + "MediaStreamConstraints": false, + "MediaStreamEvent": false, + "MediaStreamTrack": false, + "MediaStreamTrackEvent": false, + "menubar": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "MIDIAccess": false, + "MIDIConnectionEvent": false, + "MIDIInput": false, + "MIDIInputMap": false, + "MIDIMessageEvent": false, + "MIDIOutput": false, + "MIDIOutputMap": false, + "MIDIPort": false, + "MimeType": false, + "MimeTypeArray": false, + "MouseEvent": false, + "moveBy": false, + "moveTo": false, + "MutationEvent": false, + "MutationObserver": false, + "MutationRecord": false, + "name": false, + "NamedNodeMap": false, + "NavigationPreloadManager": false, + "navigator": false, + "Navigator": false, + "NavigatorUAData": false, + "NetworkInformation": false, + "Node": false, + "NodeFilter": false, + "NodeIterator": false, + "NodeList": false, + "Notification": false, + "OfflineAudioCompletionEvent": false, + "OfflineAudioContext": false, + "offscreenBuffering": false, + "OffscreenCanvas": true, + "OffscreenCanvasRenderingContext2D": false, + "onabort": true, + "onafterprint": true, + "onanimationend": true, + "onanimationiteration": true, + "onanimationstart": true, + "onappinstalled": true, + "onauxclick": true, + "onbeforeinstallprompt": true, + "onbeforeprint": true, + "onbeforeunload": true, + "onblur": true, + "oncancel": true, + "oncanplay": true, + "oncanplaythrough": true, + "onchange": true, + "onclick": true, + "onclose": true, + "oncontextmenu": true, + "oncuechange": true, + "ondblclick": true, + "ondevicemotion": true, + "ondeviceorientation": true, + "ondeviceorientationabsolute": true, + "ondrag": true, + "ondragend": true, + "ondragenter": true, + "ondragleave": true, + "ondragover": true, + "ondragstart": true, + "ondrop": true, + "ondurationchange": true, + "onemptied": true, + "onended": true, + "onerror": true, + "onfocus": true, + "ongotpointercapture": true, + "onhashchange": true, + "oninput": true, + "oninvalid": true, + "onkeydown": true, + "onkeypress": true, + "onkeyup": true, + "onlanguagechange": true, + "onload": true, + "onloadeddata": true, + "onloadedmetadata": true, + "onloadstart": true, + "onlostpointercapture": true, + "onmessage": true, + "onmessageerror": true, + "onmousedown": true, + "onmouseenter": true, + "onmouseleave": true, + "onmousemove": true, + "onmouseout": true, + "onmouseover": true, + "onmouseup": true, + "onmousewheel": true, + "onoffline": true, + "ononline": true, + "onpagehide": true, + "onpageshow": true, + "onpause": true, + "onplay": true, + "onplaying": true, + "onpointercancel": true, + "onpointerdown": true, + "onpointerenter": true, + "onpointerleave": true, + "onpointermove": true, + "onpointerout": true, + "onpointerover": true, + "onpointerup": true, + "onpopstate": true, + "onprogress": true, + "onratechange": true, + "onrejectionhandled": true, + "onreset": true, + "onresize": true, + "onscroll": true, + "onsearch": true, + "onseeked": true, + "onseeking": true, + "onselect": true, + "onstalled": true, + "onstorage": true, + "onsubmit": true, + "onsuspend": true, + "ontimeupdate": true, + "ontoggle": true, + "ontransitionend": true, + "onunhandledrejection": true, + "onunload": true, + "onvolumechange": true, + "onwaiting": true, + "onwheel": true, + "open": false, + "openDatabase": false, + "opener": false, + "Option": false, + "origin": false, + "OscillatorNode": false, + "outerHeight": false, + "outerWidth": false, + "OverconstrainedError": false, + "PageTransitionEvent": false, + "pageXOffset": false, + "pageYOffset": false, + "PannerNode": false, + "parent": false, + "Path2D": false, + "PaymentAddress": false, + "PaymentRequest": false, + "PaymentRequestUpdateEvent": false, + "PaymentResponse": false, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceLongTaskTiming": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceNavigationTiming": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformancePaintTiming": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "PeriodicWave": false, + "Permissions": false, + "PermissionStatus": false, + "personalbar": false, + "PhotoCapabilities": false, + "Plugin": false, + "PluginArray": false, + "PointerEvent": false, + "PopStateEvent": false, + "postMessage": false, + "Presentation": false, + "PresentationAvailability": false, + "PresentationConnection": false, + "PresentationConnectionAvailableEvent": false, + "PresentationConnectionCloseEvent": false, + "PresentationConnectionList": false, + "PresentationReceiver": false, + "PresentationRequest": false, + "print": false, + "ProcessingInstruction": false, + "ProgressEvent": false, + "PromiseRejectionEvent": false, + "prompt": false, + "PushManager": false, + "PushSubscription": false, + "PushSubscriptionOptions": false, + "queueMicrotask": false, + "RadioNodeList": false, + "Range": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "registerProcessor": false, + "RemotePlayback": false, + "removeEventListener": false, + "reportError": false, + "Request": false, + "requestAnimationFrame": false, + "requestIdleCallback": false, + "resizeBy": false, + "ResizeObserver": false, + "ResizeObserverEntry": false, + "resizeTo": false, + "Response": false, + "RTCCertificate": false, + "RTCDataChannel": false, + "RTCDataChannelEvent": false, + "RTCDtlsTransport": false, + "RTCIceCandidate": false, + "RTCIceGatherer": false, + "RTCIceTransport": false, + "RTCPeerConnection": false, + "RTCPeerConnectionIceEvent": false, + "RTCRtpContributingSource": false, + "RTCRtpReceiver": false, + "RTCRtpSender": false, + "RTCSctpTransport": false, + "RTCSessionDescription": false, + "RTCStatsReport": false, + "RTCTrackEvent": false, + "screen": false, + "Screen": false, + "screenLeft": false, + "ScreenOrientation": false, + "screenTop": false, + "screenX": false, + "screenY": false, + "ScriptProcessorNode": false, + "scroll": false, + "scrollbars": false, + "scrollBy": false, + "scrollTo": false, + "scrollX": false, + "scrollY": false, + "SecurityPolicyViolationEvent": false, + "Selection": false, + "self": false, + "ServiceWorker": false, + "ServiceWorkerContainer": false, + "ServiceWorkerRegistration": false, + "sessionStorage": false, + "setInterval": false, + "setTimeout": false, + "ShadowRoot": false, + "SharedWorker": false, + "SourceBuffer": false, + "SourceBufferList": false, + "speechSynthesis": false, + "SpeechSynthesisEvent": false, + "SpeechSynthesisUtterance": false, + "StaticRange": false, + "status": false, + "statusbar": false, + "StereoPannerNode": false, + "stop": false, + "Storage": false, + "StorageEvent": false, + "StorageManager": false, + "structuredClone": false, + "styleMedia": false, + "StyleSheet": false, + "StyleSheetList": false, + "SubmitEvent": false, + "SubtleCrypto": false, + "SVGAElement": false, + "SVGAngle": false, + "SVGAnimatedAngle": false, + "SVGAnimatedBoolean": false, + "SVGAnimatedEnumeration": false, + "SVGAnimatedInteger": false, + "SVGAnimatedLength": false, + "SVGAnimatedLengthList": false, + "SVGAnimatedNumber": false, + "SVGAnimatedNumberList": false, + "SVGAnimatedPreserveAspectRatio": false, + "SVGAnimatedRect": false, + "SVGAnimatedString": false, + "SVGAnimatedTransformList": false, + "SVGAnimateElement": false, + "SVGAnimateMotionElement": false, + "SVGAnimateTransformElement": false, + "SVGAnimationElement": false, + "SVGCircleElement": false, + "SVGClipPathElement": false, + "SVGComponentTransferFunctionElement": false, + "SVGDefsElement": false, + "SVGDescElement": false, + "SVGDiscardElement": false, + "SVGElement": false, + "SVGEllipseElement": false, + "SVGFEBlendElement": false, + "SVGFEColorMatrixElement": false, + "SVGFEComponentTransferElement": false, + "SVGFECompositeElement": false, + "SVGFEConvolveMatrixElement": false, + "SVGFEDiffuseLightingElement": false, + "SVGFEDisplacementMapElement": false, + "SVGFEDistantLightElement": false, + "SVGFEDropShadowElement": false, + "SVGFEFloodElement": false, + "SVGFEFuncAElement": false, + "SVGFEFuncBElement": false, + "SVGFEFuncGElement": false, + "SVGFEFuncRElement": false, + "SVGFEGaussianBlurElement": false, + "SVGFEImageElement": false, + "SVGFEMergeElement": false, + "SVGFEMergeNodeElement": false, + "SVGFEMorphologyElement": false, + "SVGFEOffsetElement": false, + "SVGFEPointLightElement": false, + "SVGFESpecularLightingElement": false, + "SVGFESpotLightElement": false, + "SVGFETileElement": false, + "SVGFETurbulenceElement": false, + "SVGFilterElement": false, + "SVGForeignObjectElement": false, + "SVGGElement": false, + "SVGGeometryElement": false, + "SVGGradientElement": false, + "SVGGraphicsElement": false, + "SVGImageElement": false, + "SVGLength": false, + "SVGLengthList": false, + "SVGLinearGradientElement": false, + "SVGLineElement": false, + "SVGMarkerElement": false, + "SVGMaskElement": false, + "SVGMatrix": false, + "SVGMetadataElement": false, + "SVGMPathElement": false, + "SVGNumber": false, + "SVGNumberList": false, + "SVGPathElement": false, + "SVGPatternElement": false, + "SVGPoint": false, + "SVGPointList": false, + "SVGPolygonElement": false, + "SVGPolylineElement": false, + "SVGPreserveAspectRatio": false, + "SVGRadialGradientElement": false, + "SVGRect": false, + "SVGRectElement": false, + "SVGScriptElement": false, + "SVGSetElement": false, + "SVGStopElement": false, + "SVGStringList": false, + "SVGStyleElement": false, + "SVGSVGElement": false, + "SVGSwitchElement": false, + "SVGSymbolElement": false, + "SVGTextContentElement": false, + "SVGTextElement": false, + "SVGTextPathElement": false, + "SVGTextPositioningElement": false, + "SVGTitleElement": false, + "SVGTransform": false, + "SVGTransformList": false, + "SVGTSpanElement": false, + "SVGUnitTypes": false, + "SVGUseElement": false, + "SVGViewElement": false, + "TaskAttributionTiming": false, + "Text": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TextEvent": false, + "TextMetrics": false, + "TextTrack": false, + "TextTrackCue": false, + "TextTrackCueList": false, + "TextTrackList": false, + "TimeRanges": false, + "ToggleEvent": false, + "toolbar": false, + "top": false, + "Touch": false, + "TouchEvent": false, + "TouchList": false, + "TrackEvent": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "TransitionEvent": false, + "TreeWalker": false, + "UIEvent": false, + "URL": false, + "URLSearchParams": false, + "ValidityState": false, + "visualViewport": false, + "VisualViewport": false, + "VTTCue": false, + "WaveShaperNode": false, + "WebAssembly": false, + "WebGL2RenderingContext": false, + "WebGLActiveInfo": false, + "WebGLBuffer": false, + "WebGLContextEvent": false, + "WebGLFramebuffer": false, + "WebGLProgram": false, + "WebGLQuery": false, + "WebGLRenderbuffer": false, + "WebGLRenderingContext": false, + "WebGLSampler": false, + "WebGLShader": false, + "WebGLShaderPrecisionFormat": false, + "WebGLSync": false, + "WebGLTexture": false, + "WebGLTransformFeedback": false, + "WebGLUniformLocation": false, + "WebGLVertexArrayObject": false, + "WebSocket": false, + "WheelEvent": false, + "window": false, + "Window": false, + "Worker": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false, + "XMLDocument": false, + "XMLHttpRequest": false, + "XMLHttpRequestEventTarget": false, + "XMLHttpRequestUpload": false, + "XMLSerializer": false, + "XPathEvaluator": false, + "XPathExpression": false, + "XPathResult": false, + "XRAnchor": false, + "XRBoundedReferenceSpace": false, + "XRCPUDepthInformation": false, + "XRDepthInformation": false, + "XRFrame": false, + "XRInputSource": false, + "XRInputSourceArray": false, + "XRInputSourceEvent": false, + "XRInputSourcesChangeEvent": false, + "XRPose": false, + "XRReferenceSpace": false, + "XRReferenceSpaceEvent": false, + "XRRenderState": false, + "XRRigidTransform": false, + "XRSession": false, + "XRSessionEvent": false, + "XRSpace": false, + "XRSystem": false, + "XRView": false, + "XRViewerPose": false, + "XRViewport": false, + "XRWebGLBinding": false, + "XRWebGLDepthInformation": false, + "XRWebGLLayer": false, + "XSLTProcessor": false + }, + "worker": { + "addEventListener": false, + "applicationCache": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "clearInterval": false, + "clearTimeout": false, + "close": true, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "ErrorEvent": false, + "Event": false, + "fetch": false, + "File": false, + "FileReaderSync": false, + "FormData": false, + "Headers": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "ImageData": false, + "importScripts": true, + "indexedDB": false, + "location": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "name": false, + "navigator": false, + "Notification": false, + "onclose": true, + "onconnect": true, + "onerror": true, + "onlanguagechange": true, + "onmessage": true, + "onoffline": true, + "ononline": true, + "onrejectionhandled": true, + "onunhandledrejection": true, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "postMessage": true, + "Promise": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "removeEventListener": false, + "reportError": false, + "Request": false, + "Response": false, + "self": true, + "ServiceWorkerRegistration": false, + "setInterval": false, + "setTimeout": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WebSocket": false, + "Worker": false, + "WorkerGlobalScope": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false, + "XMLHttpRequest": false + }, + "node": { + "__dirname": false, + "__filename": false, + "AbortController": false, + "AbortSignal": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "Buffer": false, + "ByteLengthQueuingStrategy": false, + "clearImmediate": false, + "clearInterval": false, + "clearTimeout": false, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "DOMException": false, + "Event": false, + "EventTarget": false, + "exports": true, + "fetch": false, + "File": false, + "FormData": false, + "global": false, + "Headers": false, + "Intl": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "module": false, + "performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "process": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "Request": false, + "require": false, + "Response": false, + "setImmediate": false, + "setInterval": false, + "setTimeout": false, + "structuredClone": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false + }, + "nodeBuiltin": { + "AbortController": false, + "AbortSignal": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "Buffer": false, + "ByteLengthQueuingStrategy": false, + "clearImmediate": false, + "clearInterval": false, + "clearTimeout": false, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "DOMException": false, + "Event": false, + "EventTarget": false, + "fetch": false, + "File": false, + "FormData": false, + "global": false, + "Headers": false, + "Intl": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "process": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "Request": false, + "Response": false, + "setImmediate": false, + "setInterval": false, + "setTimeout": false, + "structuredClone": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false + }, + "commonjs": { + "exports": true, + "global": false, + "module": false, + "require": false + }, + "amd": { + "define": false, + "require": false + }, + "mocha": { + "after": false, + "afterEach": false, + "before": false, + "beforeEach": false, + "context": false, + "describe": false, + "it": false, + "mocha": false, + "run": false, + "setup": false, + "specify": false, + "suite": false, + "suiteSetup": false, + "suiteTeardown": false, + "teardown": false, + "test": false, + "xcontext": false, + "xdescribe": false, + "xit": false, + "xspecify": false + }, + "jasmine": { + "afterAll": false, + "afterEach": false, + "beforeAll": false, + "beforeEach": false, + "describe": false, + "expect": false, + "expectAsync": false, + "fail": false, + "fdescribe": false, + "fit": false, + "it": false, + "jasmine": false, + "pending": false, + "runs": false, + "spyOn": false, + "spyOnAllFunctions": false, + "spyOnProperty": false, + "waits": false, + "waitsFor": false, + "xdescribe": false, + "xit": false + }, + "jest": { + "afterAll": false, + "afterEach": false, + "beforeAll": false, + "beforeEach": false, + "describe": false, + "expect": false, + "fdescribe": false, + "fit": false, + "it": false, + "jest": false, + "pit": false, + "require": false, + "test": false, + "xdescribe": false, + "xit": false, + "xtest": false + }, + "qunit": { + "asyncTest": false, + "deepEqual": false, + "equal": false, + "expect": false, + "module": false, + "notDeepEqual": false, + "notEqual": false, + "notOk": false, + "notPropEqual": false, + "notStrictEqual": false, + "ok": false, + "propEqual": false, + "QUnit": false, + "raises": false, + "start": false, + "stop": false, + "strictEqual": false, + "test": false, + "throws": false + }, + "phantomjs": { + "console": true, + "exports": true, + "phantom": true, + "require": true, + "WebPage": true + }, + "couch": { + "emit": false, + "exports": false, + "getRow": false, + "log": false, + "module": false, + "provides": false, + "require": false, + "respond": false, + "send": false, + "start": false, + "sum": false + }, + "rhino": { + "defineClass": false, + "deserialize": false, + "gc": false, + "help": false, + "importClass": false, + "importPackage": false, + "java": false, + "load": false, + "loadClass": false, + "Packages": false, + "print": false, + "quit": false, + "readFile": false, + "readUrl": false, + "runCommand": false, + "seal": false, + "serialize": false, + "spawn": false, + "sync": false, + "toint32": false, + "version": false + }, + "nashorn": { + "__DIR__": false, + "__FILE__": false, + "__LINE__": false, + "com": false, + "edu": false, + "exit": false, + "java": false, + "Java": false, + "javafx": false, + "JavaImporter": false, + "javax": false, + "JSAdapter": false, + "load": false, + "loadWithNewGlobal": false, + "org": false, + "Packages": false, + "print": false, + "quit": false + }, + "wsh": { + "ActiveXObject": false, + "CollectGarbage": false, + "Debug": false, + "Enumerator": false, + "GetObject": false, + "RuntimeObject": false, + "ScriptEngine": false, + "ScriptEngineBuildVersion": false, + "ScriptEngineMajorVersion": false, + "ScriptEngineMinorVersion": false, + "VBArray": false, + "WScript": false, + "WSH": false + }, + "jquery": { + "$": false, + "jQuery": false + }, + "yui": { + "YAHOO": false, + "YAHOO_config": false, + "YUI": false, + "YUI_config": false + }, + "shelljs": { + "cat": false, + "cd": false, + "chmod": false, + "config": false, + "cp": false, + "dirs": false, + "echo": false, + "env": false, + "error": false, + "exec": false, + "exit": false, + "find": false, + "grep": false, + "ln": false, + "ls": false, + "mkdir": false, + "mv": false, + "popd": false, + "pushd": false, + "pwd": false, + "rm": false, + "sed": false, + "set": false, + "target": false, + "tempdir": false, + "test": false, + "touch": false, + "which": false + }, + "prototypejs": { + "$": false, + "$$": false, + "$A": false, + "$break": false, + "$continue": false, + "$F": false, + "$H": false, + "$R": false, + "$w": false, + "Abstract": false, + "Ajax": false, + "Autocompleter": false, + "Builder": false, + "Class": false, + "Control": false, + "Draggable": false, + "Draggables": false, + "Droppables": false, + "Effect": false, + "Element": false, + "Enumerable": false, + "Event": false, + "Field": false, + "Form": false, + "Hash": false, + "Insertion": false, + "ObjectRange": false, + "PeriodicalExecuter": false, + "Position": false, + "Prototype": false, + "Scriptaculous": false, + "Selector": false, + "Sortable": false, + "SortableObserver": false, + "Sound": false, + "Template": false, + "Toggle": false, + "Try": false + }, + "meteor": { + "$": false, + "Accounts": false, + "AccountsClient": false, + "AccountsCommon": false, + "AccountsServer": false, + "App": false, + "Assets": false, + "Blaze": false, + "check": false, + "Cordova": false, + "DDP": false, + "DDPRateLimiter": false, + "DDPServer": false, + "Deps": false, + "EJSON": false, + "Email": false, + "HTTP": false, + "Log": false, + "Match": false, + "Meteor": false, + "Mongo": false, + "MongoInternals": false, + "Npm": false, + "Package": false, + "Plugin": false, + "process": false, + "Random": false, + "ReactiveDict": false, + "ReactiveVar": false, + "Router": false, + "ServiceConfiguration": false, + "Session": false, + "share": false, + "Spacebars": false, + "Template": false, + "Tinytest": false, + "Tracker": false, + "UI": false, + "Utils": false, + "WebApp": false, + "WebAppInternals": false + }, + "mongo": { + "_isWindows": false, + "_rand": false, + "BulkWriteResult": false, + "cat": false, + "cd": false, + "connect": false, + "db": false, + "getHostName": false, + "getMemInfo": false, + "hostname": false, + "ISODate": false, + "listFiles": false, + "load": false, + "ls": false, + "md5sumFile": false, + "mkdir": false, + "Mongo": false, + "NumberInt": false, + "NumberLong": false, + "ObjectId": false, + "PlanCache": false, + "print": false, + "printjson": false, + "pwd": false, + "quit": false, + "removeFile": false, + "rs": false, + "sh": false, + "UUID": false, + "version": false, + "WriteResult": false + }, + "applescript": { + "$": false, + "Application": false, + "Automation": false, + "console": false, + "delay": false, + "Library": false, + "ObjC": false, + "ObjectSpecifier": false, + "Path": false, + "Progress": false, + "Ref": false + }, + "serviceworker": { + "addEventListener": false, + "applicationCache": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "CacheStorage": false, + "clearInterval": false, + "clearTimeout": false, + "Client": false, + "clients": false, + "Clients": false, + "close": true, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "ErrorEvent": false, + "Event": false, + "ExtendableEvent": false, + "ExtendableMessageEvent": false, + "fetch": false, + "FetchEvent": false, + "File": false, + "FileReaderSync": false, + "FormData": false, + "Headers": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "ImageData": false, + "importScripts": false, + "indexedDB": false, + "location": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "name": false, + "navigator": false, + "Notification": false, + "onclose": true, + "onconnect": true, + "onerror": true, + "onfetch": true, + "oninstall": true, + "onlanguagechange": true, + "onmessage": true, + "onmessageerror": true, + "onnotificationclick": true, + "onnotificationclose": true, + "onoffline": true, + "ononline": true, + "onpush": true, + "onpushsubscriptionchange": true, + "onrejectionhandled": true, + "onsync": true, + "onunhandledrejection": true, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "postMessage": true, + "Promise": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "registration": false, + "removeEventListener": false, + "Request": false, + "Response": false, + "self": false, + "ServiceWorker": false, + "ServiceWorkerContainer": false, + "ServiceWorkerGlobalScope": false, + "ServiceWorkerMessageEvent": false, + "ServiceWorkerRegistration": false, + "setInterval": false, + "setTimeout": false, + "skipWaiting": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WebSocket": false, + "WindowClient": false, + "Worker": false, + "WorkerGlobalScope": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false, + "XMLHttpRequest": false + }, + "atomtest": { + "advanceClock": false, + "atom": false, + "fakeClearInterval": false, + "fakeClearTimeout": false, + "fakeSetInterval": false, + "fakeSetTimeout": false, + "resetTimeouts": false, + "waitsForPromise": false + }, + "embertest": { + "andThen": false, + "click": false, + "currentPath": false, + "currentRouteName": false, + "currentURL": false, + "fillIn": false, + "find": false, + "findAll": false, + "findWithAssert": false, + "keyEvent": false, + "pauseTest": false, + "resumeTest": false, + "triggerEvent": false, + "visit": false, + "wait": false + }, + "protractor": { + "$": false, + "$$": false, + "browser": false, + "by": false, + "By": false, + "DartObject": false, + "element": false, + "protractor": false + }, + "shared-node-browser": { + "AbortController": false, + "AbortSignal": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "ByteLengthQueuingStrategy": false, + "clearInterval": false, + "clearTimeout": false, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "DOMException": false, + "Event": false, + "EventTarget": false, + "fetch": false, + "File": false, + "FormData": false, + "Headers": false, + "Intl": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "Request": false, + "Response": false, + "setInterval": false, + "setTimeout": false, + "structuredClone": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false + }, + "webextensions": { + "browser": false, + "chrome": false, + "opr": false + }, + "greasemonkey": { + "cloneInto": false, + "createObjectIn": false, + "exportFunction": false, + "GM": false, + "GM_addElement": false, + "GM_addStyle": false, + "GM_addValueChangeListener": false, + "GM_deleteValue": false, + "GM_download": false, + "GM_getResourceText": false, + "GM_getResourceURL": false, + "GM_getTab": false, + "GM_getTabs": false, + "GM_getValue": false, + "GM_info": false, + "GM_listValues": false, + "GM_log": false, + "GM_notification": false, + "GM_openInTab": false, + "GM_registerMenuCommand": false, + "GM_removeValueChangeListener": false, + "GM_saveTab": false, + "GM_setClipboard": false, + "GM_setValue": false, + "GM_unregisterMenuCommand": false, + "GM_xmlhttpRequest": false, + "unsafeWindow": false + }, + "devtools": { + "$": false, + "$_": false, + "$$": false, + "$0": false, + "$1": false, + "$2": false, + "$3": false, + "$4": false, + "$x": false, + "chrome": false, + "clear": false, + "copy": false, + "debug": false, + "dir": false, + "dirxml": false, + "getEventListeners": false, + "inspect": false, + "keys": false, + "monitor": false, + "monitorEvents": false, + "profile": false, + "profileEnd": false, + "queryObjects": false, + "table": false, + "undebug": false, + "unmonitor": false, + "unmonitorEvents": false, + "values": false + } +} diff --git a/node_modules/globals/index.d.ts b/node_modules/globals/index.d.ts new file mode 100644 index 00000000..edd861f9 --- /dev/null +++ b/node_modules/globals/index.d.ts @@ -0,0 +1,2077 @@ +// This file is autogenerated by scripts/generate-types.mjs +// Do NOT modify this file manually + +type GlobalsBuiltin = { + readonly 'AggregateError': false; + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Atomics': false; + readonly 'BigInt': false; + readonly 'BigInt64Array': false; + readonly 'BigUint64Array': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'FinalizationRegistry': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'globalThis': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'SharedArrayBuffer': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakRef': false; + readonly 'WeakSet': false; +} + +type GlobalsEs5 = { + readonly 'Array': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'Function': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'propertyIsEnumerable': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'RegExp': false; + readonly 'String': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; +} + +type GlobalsEs2015 = { + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakSet': false; +} + +type GlobalsEs2017 = { + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Atomics': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'SharedArrayBuffer': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakSet': false; +} + +type GlobalsEs2020 = { + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Atomics': false; + readonly 'BigInt': false; + readonly 'BigInt64Array': false; + readonly 'BigUint64Array': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'globalThis': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'SharedArrayBuffer': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakSet': false; +} + +type GlobalsEs2021 = { + readonly 'AggregateError': false; + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Atomics': false; + readonly 'BigInt': false; + readonly 'BigInt64Array': false; + readonly 'BigUint64Array': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'FinalizationRegistry': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'globalThis': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'SharedArrayBuffer': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakRef': false; + readonly 'WeakSet': false; +} + +type GlobalsBrowser = { + readonly 'AbortController': false; + readonly 'AbortSignal': false; + readonly 'addEventListener': false; + readonly 'alert': false; + readonly 'AnalyserNode': false; + readonly 'Animation': false; + readonly 'AnimationEffectReadOnly': false; + readonly 'AnimationEffectTiming': false; + readonly 'AnimationEffectTimingReadOnly': false; + readonly 'AnimationEvent': false; + readonly 'AnimationPlaybackEvent': false; + readonly 'AnimationTimeline': false; + readonly 'applicationCache': false; + readonly 'ApplicationCache': false; + readonly 'ApplicationCacheErrorEvent': false; + readonly 'atob': false; + readonly 'Attr': false; + readonly 'Audio': false; + readonly 'AudioBuffer': false; + readonly 'AudioBufferSourceNode': false; + readonly 'AudioContext': false; + readonly 'AudioDestinationNode': false; + readonly 'AudioListener': false; + readonly 'AudioNode': false; + readonly 'AudioParam': false; + readonly 'AudioProcessingEvent': false; + readonly 'AudioScheduledSourceNode': false; + readonly 'AudioWorkletGlobalScope': false; + readonly 'AudioWorkletNode': false; + readonly 'AudioWorkletProcessor': false; + readonly 'BarProp': false; + readonly 'BaseAudioContext': false; + readonly 'BatteryManager': false; + readonly 'BeforeUnloadEvent': false; + readonly 'BiquadFilterNode': false; + readonly 'Blob': false; + readonly 'BlobEvent': false; + readonly 'blur': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'BudgetService': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'Cache': false; + readonly 'caches': false; + readonly 'CacheStorage': false; + readonly 'cancelAnimationFrame': false; + readonly 'cancelIdleCallback': false; + readonly 'CanvasCaptureMediaStreamTrack': false; + readonly 'CanvasGradient': false; + readonly 'CanvasPattern': false; + readonly 'CanvasRenderingContext2D': false; + readonly 'ChannelMergerNode': false; + readonly 'ChannelSplitterNode': false; + readonly 'CharacterData': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'clientInformation': false; + readonly 'ClipboardEvent': false; + readonly 'ClipboardItem': false; + readonly 'close': false; + readonly 'closed': false; + readonly 'CloseEvent': false; + readonly 'Comment': false; + readonly 'CompositionEvent': false; + readonly 'CompressionStream': false; + readonly 'confirm': false; + readonly 'console': false; + readonly 'ConstantSourceNode': false; + readonly 'ConvolverNode': false; + readonly 'CountQueuingStrategy': false; + readonly 'createImageBitmap': false; + readonly 'Credential': false; + readonly 'CredentialsContainer': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CSS': false; + readonly 'CSSConditionRule': false; + readonly 'CSSFontFaceRule': false; + readonly 'CSSGroupingRule': false; + readonly 'CSSImportRule': false; + readonly 'CSSKeyframeRule': false; + readonly 'CSSKeyframesRule': false; + readonly 'CSSMatrixComponent': false; + readonly 'CSSMediaRule': false; + readonly 'CSSNamespaceRule': false; + readonly 'CSSPageRule': false; + readonly 'CSSPerspective': false; + readonly 'CSSRotate': false; + readonly 'CSSRule': false; + readonly 'CSSRuleList': false; + readonly 'CSSScale': false; + readonly 'CSSSkew': false; + readonly 'CSSSkewX': false; + readonly 'CSSSkewY': false; + readonly 'CSSStyleDeclaration': false; + readonly 'CSSStyleRule': false; + readonly 'CSSStyleSheet': false; + readonly 'CSSSupportsRule': false; + readonly 'CSSTransformValue': false; + readonly 'CSSTranslate': false; + readonly 'CustomElementRegistry': false; + readonly 'customElements': false; + readonly 'CustomEvent': false; + readonly 'DataTransfer': false; + readonly 'DataTransferItem': false; + readonly 'DataTransferItemList': false; + readonly 'DecompressionStream': false; + readonly 'defaultstatus': false; + readonly 'defaultStatus': false; + readonly 'DelayNode': false; + readonly 'DeviceMotionEvent': false; + readonly 'DeviceOrientationEvent': false; + readonly 'devicePixelRatio': false; + readonly 'dispatchEvent': false; + readonly 'document': false; + readonly 'Document': false; + readonly 'DocumentFragment': false; + readonly 'DocumentType': false; + readonly 'DOMError': false; + readonly 'DOMException': false; + readonly 'DOMImplementation': false; + readonly 'DOMMatrix': false; + readonly 'DOMMatrixReadOnly': false; + readonly 'DOMParser': false; + readonly 'DOMPoint': false; + readonly 'DOMPointReadOnly': false; + readonly 'DOMQuad': false; + readonly 'DOMRect': false; + readonly 'DOMRectList': false; + readonly 'DOMRectReadOnly': false; + readonly 'DOMStringList': false; + readonly 'DOMStringMap': false; + readonly 'DOMTokenList': false; + readonly 'DragEvent': false; + readonly 'DynamicsCompressorNode': false; + readonly 'Element': false; + readonly 'ErrorEvent': false; + readonly 'event': false; + readonly 'Event': false; + readonly 'EventSource': false; + readonly 'EventTarget': false; + readonly 'external': false; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FileList': false; + readonly 'FileReader': false; + readonly 'find': false; + readonly 'focus': false; + readonly 'FocusEvent': false; + readonly 'FontFace': false; + readonly 'FontFaceSetLoadEvent': false; + readonly 'FormData': false; + readonly 'FormDataEvent': false; + readonly 'frameElement': false; + readonly 'frames': false; + readonly 'GainNode': false; + readonly 'Gamepad': false; + readonly 'GamepadButton': false; + readonly 'GamepadEvent': false; + readonly 'getComputedStyle': false; + readonly 'getSelection': false; + readonly 'HashChangeEvent': false; + readonly 'Headers': false; + readonly 'history': false; + readonly 'History': false; + readonly 'HTMLAllCollection': false; + readonly 'HTMLAnchorElement': false; + readonly 'HTMLAreaElement': false; + readonly 'HTMLAudioElement': false; + readonly 'HTMLBaseElement': false; + readonly 'HTMLBodyElement': false; + readonly 'HTMLBRElement': false; + readonly 'HTMLButtonElement': false; + readonly 'HTMLCanvasElement': false; + readonly 'HTMLCollection': false; + readonly 'HTMLContentElement': false; + readonly 'HTMLDataElement': false; + readonly 'HTMLDataListElement': false; + readonly 'HTMLDetailsElement': false; + readonly 'HTMLDialogElement': false; + readonly 'HTMLDirectoryElement': false; + readonly 'HTMLDivElement': false; + readonly 'HTMLDListElement': false; + readonly 'HTMLDocument': false; + readonly 'HTMLElement': false; + readonly 'HTMLEmbedElement': false; + readonly 'HTMLFieldSetElement': false; + readonly 'HTMLFontElement': false; + readonly 'HTMLFormControlsCollection': false; + readonly 'HTMLFormElement': false; + readonly 'HTMLFrameElement': false; + readonly 'HTMLFrameSetElement': false; + readonly 'HTMLHeadElement': false; + readonly 'HTMLHeadingElement': false; + readonly 'HTMLHRElement': false; + readonly 'HTMLHtmlElement': false; + readonly 'HTMLIFrameElement': false; + readonly 'HTMLImageElement': false; + readonly 'HTMLInputElement': false; + readonly 'HTMLLabelElement': false; + readonly 'HTMLLegendElement': false; + readonly 'HTMLLIElement': false; + readonly 'HTMLLinkElement': false; + readonly 'HTMLMapElement': false; + readonly 'HTMLMarqueeElement': false; + readonly 'HTMLMediaElement': false; + readonly 'HTMLMenuElement': false; + readonly 'HTMLMetaElement': false; + readonly 'HTMLMeterElement': false; + readonly 'HTMLModElement': false; + readonly 'HTMLObjectElement': false; + readonly 'HTMLOListElement': false; + readonly 'HTMLOptGroupElement': false; + readonly 'HTMLOptionElement': false; + readonly 'HTMLOptionsCollection': false; + readonly 'HTMLOutputElement': false; + readonly 'HTMLParagraphElement': false; + readonly 'HTMLParamElement': false; + readonly 'HTMLPictureElement': false; + readonly 'HTMLPreElement': false; + readonly 'HTMLProgressElement': false; + readonly 'HTMLQuoteElement': false; + readonly 'HTMLScriptElement': false; + readonly 'HTMLSelectElement': false; + readonly 'HTMLShadowElement': false; + readonly 'HTMLSlotElement': false; + readonly 'HTMLSourceElement': false; + readonly 'HTMLSpanElement': false; + readonly 'HTMLStyleElement': false; + readonly 'HTMLTableCaptionElement': false; + readonly 'HTMLTableCellElement': false; + readonly 'HTMLTableColElement': false; + readonly 'HTMLTableElement': false; + readonly 'HTMLTableRowElement': false; + readonly 'HTMLTableSectionElement': false; + readonly 'HTMLTemplateElement': false; + readonly 'HTMLTextAreaElement': false; + readonly 'HTMLTimeElement': false; + readonly 'HTMLTitleElement': false; + readonly 'HTMLTrackElement': false; + readonly 'HTMLUListElement': false; + readonly 'HTMLUnknownElement': false; + readonly 'HTMLVideoElement': false; + readonly 'IDBCursor': false; + readonly 'IDBCursorWithValue': false; + readonly 'IDBDatabase': false; + readonly 'IDBFactory': false; + readonly 'IDBIndex': false; + readonly 'IDBKeyRange': false; + readonly 'IDBObjectStore': false; + readonly 'IDBOpenDBRequest': false; + readonly 'IDBRequest': false; + readonly 'IDBTransaction': false; + readonly 'IDBVersionChangeEvent': false; + readonly 'IdleDeadline': false; + readonly 'IIRFilterNode': false; + readonly 'Image': false; + readonly 'ImageBitmap': false; + readonly 'ImageBitmapRenderingContext': false; + readonly 'ImageCapture': false; + readonly 'ImageData': false; + readonly 'indexedDB': false; + readonly 'innerHeight': false; + readonly 'innerWidth': false; + readonly 'InputEvent': false; + readonly 'IntersectionObserver': false; + readonly 'IntersectionObserverEntry': false; + readonly 'Intl': false; + readonly 'isSecureContext': false; + readonly 'KeyboardEvent': false; + readonly 'KeyframeEffect': false; + readonly 'KeyframeEffectReadOnly': false; + readonly 'length': false; + readonly 'localStorage': false; + readonly 'location': true; + readonly 'Location': false; + readonly 'locationbar': false; + readonly 'matchMedia': false; + readonly 'MediaDeviceInfo': false; + readonly 'MediaDevices': false; + readonly 'MediaElementAudioSourceNode': false; + readonly 'MediaEncryptedEvent': false; + readonly 'MediaError': false; + readonly 'MediaKeyMessageEvent': false; + readonly 'MediaKeySession': false; + readonly 'MediaKeyStatusMap': false; + readonly 'MediaKeySystemAccess': false; + readonly 'MediaList': false; + readonly 'MediaMetadata': false; + readonly 'MediaQueryList': false; + readonly 'MediaQueryListEvent': false; + readonly 'MediaRecorder': false; + readonly 'MediaSettingsRange': false; + readonly 'MediaSource': false; + readonly 'MediaStream': false; + readonly 'MediaStreamAudioDestinationNode': false; + readonly 'MediaStreamAudioSourceNode': false; + readonly 'MediaStreamConstraints': false; + readonly 'MediaStreamEvent': false; + readonly 'MediaStreamTrack': false; + readonly 'MediaStreamTrackEvent': false; + readonly 'menubar': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'MIDIAccess': false; + readonly 'MIDIConnectionEvent': false; + readonly 'MIDIInput': false; + readonly 'MIDIInputMap': false; + readonly 'MIDIMessageEvent': false; + readonly 'MIDIOutput': false; + readonly 'MIDIOutputMap': false; + readonly 'MIDIPort': false; + readonly 'MimeType': false; + readonly 'MimeTypeArray': false; + readonly 'MouseEvent': false; + readonly 'moveBy': false; + readonly 'moveTo': false; + readonly 'MutationEvent': false; + readonly 'MutationObserver': false; + readonly 'MutationRecord': false; + readonly 'name': false; + readonly 'NamedNodeMap': false; + readonly 'NavigationPreloadManager': false; + readonly 'navigator': false; + readonly 'Navigator': false; + readonly 'NavigatorUAData': false; + readonly 'NetworkInformation': false; + readonly 'Node': false; + readonly 'NodeFilter': false; + readonly 'NodeIterator': false; + readonly 'NodeList': false; + readonly 'Notification': false; + readonly 'OfflineAudioCompletionEvent': false; + readonly 'OfflineAudioContext': false; + readonly 'offscreenBuffering': false; + readonly 'OffscreenCanvas': true; + readonly 'OffscreenCanvasRenderingContext2D': false; + readonly 'onabort': true; + readonly 'onafterprint': true; + readonly 'onanimationend': true; + readonly 'onanimationiteration': true; + readonly 'onanimationstart': true; + readonly 'onappinstalled': true; + readonly 'onauxclick': true; + readonly 'onbeforeinstallprompt': true; + readonly 'onbeforeprint': true; + readonly 'onbeforeunload': true; + readonly 'onblur': true; + readonly 'oncancel': true; + readonly 'oncanplay': true; + readonly 'oncanplaythrough': true; + readonly 'onchange': true; + readonly 'onclick': true; + readonly 'onclose': true; + readonly 'oncontextmenu': true; + readonly 'oncuechange': true; + readonly 'ondblclick': true; + readonly 'ondevicemotion': true; + readonly 'ondeviceorientation': true; + readonly 'ondeviceorientationabsolute': true; + readonly 'ondrag': true; + readonly 'ondragend': true; + readonly 'ondragenter': true; + readonly 'ondragleave': true; + readonly 'ondragover': true; + readonly 'ondragstart': true; + readonly 'ondrop': true; + readonly 'ondurationchange': true; + readonly 'onemptied': true; + readonly 'onended': true; + readonly 'onerror': true; + readonly 'onfocus': true; + readonly 'ongotpointercapture': true; + readonly 'onhashchange': true; + readonly 'oninput': true; + readonly 'oninvalid': true; + readonly 'onkeydown': true; + readonly 'onkeypress': true; + readonly 'onkeyup': true; + readonly 'onlanguagechange': true; + readonly 'onload': true; + readonly 'onloadeddata': true; + readonly 'onloadedmetadata': true; + readonly 'onloadstart': true; + readonly 'onlostpointercapture': true; + readonly 'onmessage': true; + readonly 'onmessageerror': true; + readonly 'onmousedown': true; + readonly 'onmouseenter': true; + readonly 'onmouseleave': true; + readonly 'onmousemove': true; + readonly 'onmouseout': true; + readonly 'onmouseover': true; + readonly 'onmouseup': true; + readonly 'onmousewheel': true; + readonly 'onoffline': true; + readonly 'ononline': true; + readonly 'onpagehide': true; + readonly 'onpageshow': true; + readonly 'onpause': true; + readonly 'onplay': true; + readonly 'onplaying': true; + readonly 'onpointercancel': true; + readonly 'onpointerdown': true; + readonly 'onpointerenter': true; + readonly 'onpointerleave': true; + readonly 'onpointermove': true; + readonly 'onpointerout': true; + readonly 'onpointerover': true; + readonly 'onpointerup': true; + readonly 'onpopstate': true; + readonly 'onprogress': true; + readonly 'onratechange': true; + readonly 'onrejectionhandled': true; + readonly 'onreset': true; + readonly 'onresize': true; + readonly 'onscroll': true; + readonly 'onsearch': true; + readonly 'onseeked': true; + readonly 'onseeking': true; + readonly 'onselect': true; + readonly 'onstalled': true; + readonly 'onstorage': true; + readonly 'onsubmit': true; + readonly 'onsuspend': true; + readonly 'ontimeupdate': true; + readonly 'ontoggle': true; + readonly 'ontransitionend': true; + readonly 'onunhandledrejection': true; + readonly 'onunload': true; + readonly 'onvolumechange': true; + readonly 'onwaiting': true; + readonly 'onwheel': true; + readonly 'open': false; + readonly 'openDatabase': false; + readonly 'opener': false; + readonly 'Option': false; + readonly 'origin': false; + readonly 'OscillatorNode': false; + readonly 'outerHeight': false; + readonly 'outerWidth': false; + readonly 'OverconstrainedError': false; + readonly 'PageTransitionEvent': false; + readonly 'pageXOffset': false; + readonly 'pageYOffset': false; + readonly 'PannerNode': false; + readonly 'parent': false; + readonly 'Path2D': false; + readonly 'PaymentAddress': false; + readonly 'PaymentRequest': false; + readonly 'PaymentRequestUpdateEvent': false; + readonly 'PaymentResponse': false; + readonly 'performance': false; + readonly 'Performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceLongTaskTiming': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceNavigation': false; + readonly 'PerformanceNavigationTiming': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformancePaintTiming': false; + readonly 'PerformanceResourceTiming': false; + readonly 'PerformanceTiming': false; + readonly 'PeriodicWave': false; + readonly 'Permissions': false; + readonly 'PermissionStatus': false; + readonly 'personalbar': false; + readonly 'PhotoCapabilities': false; + readonly 'Plugin': false; + readonly 'PluginArray': false; + readonly 'PointerEvent': false; + readonly 'PopStateEvent': false; + readonly 'postMessage': false; + readonly 'Presentation': false; + readonly 'PresentationAvailability': false; + readonly 'PresentationConnection': false; + readonly 'PresentationConnectionAvailableEvent': false; + readonly 'PresentationConnectionCloseEvent': false; + readonly 'PresentationConnectionList': false; + readonly 'PresentationReceiver': false; + readonly 'PresentationRequest': false; + readonly 'print': false; + readonly 'ProcessingInstruction': false; + readonly 'ProgressEvent': false; + readonly 'PromiseRejectionEvent': false; + readonly 'prompt': false; + readonly 'PushManager': false; + readonly 'PushSubscription': false; + readonly 'PushSubscriptionOptions': false; + readonly 'queueMicrotask': false; + readonly 'RadioNodeList': false; + readonly 'Range': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'registerProcessor': false; + readonly 'RemotePlayback': false; + readonly 'removeEventListener': false; + readonly 'reportError': false; + readonly 'Request': false; + readonly 'requestAnimationFrame': false; + readonly 'requestIdleCallback': false; + readonly 'resizeBy': false; + readonly 'ResizeObserver': false; + readonly 'ResizeObserverEntry': false; + readonly 'resizeTo': false; + readonly 'Response': false; + readonly 'RTCCertificate': false; + readonly 'RTCDataChannel': false; + readonly 'RTCDataChannelEvent': false; + readonly 'RTCDtlsTransport': false; + readonly 'RTCIceCandidate': false; + readonly 'RTCIceGatherer': false; + readonly 'RTCIceTransport': false; + readonly 'RTCPeerConnection': false; + readonly 'RTCPeerConnectionIceEvent': false; + readonly 'RTCRtpContributingSource': false; + readonly 'RTCRtpReceiver': false; + readonly 'RTCRtpSender': false; + readonly 'RTCSctpTransport': false; + readonly 'RTCSessionDescription': false; + readonly 'RTCStatsReport': false; + readonly 'RTCTrackEvent': false; + readonly 'screen': false; + readonly 'Screen': false; + readonly 'screenLeft': false; + readonly 'ScreenOrientation': false; + readonly 'screenTop': false; + readonly 'screenX': false; + readonly 'screenY': false; + readonly 'ScriptProcessorNode': false; + readonly 'scroll': false; + readonly 'scrollbars': false; + readonly 'scrollBy': false; + readonly 'scrollTo': false; + readonly 'scrollX': false; + readonly 'scrollY': false; + readonly 'SecurityPolicyViolationEvent': false; + readonly 'Selection': false; + readonly 'self': false; + readonly 'ServiceWorker': false; + readonly 'ServiceWorkerContainer': false; + readonly 'ServiceWorkerRegistration': false; + readonly 'sessionStorage': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'ShadowRoot': false; + readonly 'SharedWorker': false; + readonly 'SourceBuffer': false; + readonly 'SourceBufferList': false; + readonly 'speechSynthesis': false; + readonly 'SpeechSynthesisEvent': false; + readonly 'SpeechSynthesisUtterance': false; + readonly 'StaticRange': false; + readonly 'status': false; + readonly 'statusbar': false; + readonly 'StereoPannerNode': false; + readonly 'stop': false; + readonly 'Storage': false; + readonly 'StorageEvent': false; + readonly 'StorageManager': false; + readonly 'structuredClone': false; + readonly 'styleMedia': false; + readonly 'StyleSheet': false; + readonly 'StyleSheetList': false; + readonly 'SubmitEvent': false; + readonly 'SubtleCrypto': false; + readonly 'SVGAElement': false; + readonly 'SVGAngle': false; + readonly 'SVGAnimatedAngle': false; + readonly 'SVGAnimatedBoolean': false; + readonly 'SVGAnimatedEnumeration': false; + readonly 'SVGAnimatedInteger': false; + readonly 'SVGAnimatedLength': false; + readonly 'SVGAnimatedLengthList': false; + readonly 'SVGAnimatedNumber': false; + readonly 'SVGAnimatedNumberList': false; + readonly 'SVGAnimatedPreserveAspectRatio': false; + readonly 'SVGAnimatedRect': false; + readonly 'SVGAnimatedString': false; + readonly 'SVGAnimatedTransformList': false; + readonly 'SVGAnimateElement': false; + readonly 'SVGAnimateMotionElement': false; + readonly 'SVGAnimateTransformElement': false; + readonly 'SVGAnimationElement': false; + readonly 'SVGCircleElement': false; + readonly 'SVGClipPathElement': false; + readonly 'SVGComponentTransferFunctionElement': false; + readonly 'SVGDefsElement': false; + readonly 'SVGDescElement': false; + readonly 'SVGDiscardElement': false; + readonly 'SVGElement': false; + readonly 'SVGEllipseElement': false; + readonly 'SVGFEBlendElement': false; + readonly 'SVGFEColorMatrixElement': false; + readonly 'SVGFEComponentTransferElement': false; + readonly 'SVGFECompositeElement': false; + readonly 'SVGFEConvolveMatrixElement': false; + readonly 'SVGFEDiffuseLightingElement': false; + readonly 'SVGFEDisplacementMapElement': false; + readonly 'SVGFEDistantLightElement': false; + readonly 'SVGFEDropShadowElement': false; + readonly 'SVGFEFloodElement': false; + readonly 'SVGFEFuncAElement': false; + readonly 'SVGFEFuncBElement': false; + readonly 'SVGFEFuncGElement': false; + readonly 'SVGFEFuncRElement': false; + readonly 'SVGFEGaussianBlurElement': false; + readonly 'SVGFEImageElement': false; + readonly 'SVGFEMergeElement': false; + readonly 'SVGFEMergeNodeElement': false; + readonly 'SVGFEMorphologyElement': false; + readonly 'SVGFEOffsetElement': false; + readonly 'SVGFEPointLightElement': false; + readonly 'SVGFESpecularLightingElement': false; + readonly 'SVGFESpotLightElement': false; + readonly 'SVGFETileElement': false; + readonly 'SVGFETurbulenceElement': false; + readonly 'SVGFilterElement': false; + readonly 'SVGForeignObjectElement': false; + readonly 'SVGGElement': false; + readonly 'SVGGeometryElement': false; + readonly 'SVGGradientElement': false; + readonly 'SVGGraphicsElement': false; + readonly 'SVGImageElement': false; + readonly 'SVGLength': false; + readonly 'SVGLengthList': false; + readonly 'SVGLinearGradientElement': false; + readonly 'SVGLineElement': false; + readonly 'SVGMarkerElement': false; + readonly 'SVGMaskElement': false; + readonly 'SVGMatrix': false; + readonly 'SVGMetadataElement': false; + readonly 'SVGMPathElement': false; + readonly 'SVGNumber': false; + readonly 'SVGNumberList': false; + readonly 'SVGPathElement': false; + readonly 'SVGPatternElement': false; + readonly 'SVGPoint': false; + readonly 'SVGPointList': false; + readonly 'SVGPolygonElement': false; + readonly 'SVGPolylineElement': false; + readonly 'SVGPreserveAspectRatio': false; + readonly 'SVGRadialGradientElement': false; + readonly 'SVGRect': false; + readonly 'SVGRectElement': false; + readonly 'SVGScriptElement': false; + readonly 'SVGSetElement': false; + readonly 'SVGStopElement': false; + readonly 'SVGStringList': false; + readonly 'SVGStyleElement': false; + readonly 'SVGSVGElement': false; + readonly 'SVGSwitchElement': false; + readonly 'SVGSymbolElement': false; + readonly 'SVGTextContentElement': false; + readonly 'SVGTextElement': false; + readonly 'SVGTextPathElement': false; + readonly 'SVGTextPositioningElement': false; + readonly 'SVGTitleElement': false; + readonly 'SVGTransform': false; + readonly 'SVGTransformList': false; + readonly 'SVGTSpanElement': false; + readonly 'SVGUnitTypes': false; + readonly 'SVGUseElement': false; + readonly 'SVGViewElement': false; + readonly 'TaskAttributionTiming': false; + readonly 'Text': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TextEvent': false; + readonly 'TextMetrics': false; + readonly 'TextTrack': false; + readonly 'TextTrackCue': false; + readonly 'TextTrackCueList': false; + readonly 'TextTrackList': false; + readonly 'TimeRanges': false; + readonly 'ToggleEvent': false; + readonly 'toolbar': false; + readonly 'top': false; + readonly 'Touch': false; + readonly 'TouchEvent': false; + readonly 'TouchList': false; + readonly 'TrackEvent': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'TransitionEvent': false; + readonly 'TreeWalker': false; + readonly 'UIEvent': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'ValidityState': false; + readonly 'visualViewport': false; + readonly 'VisualViewport': false; + readonly 'VTTCue': false; + readonly 'WaveShaperNode': false; + readonly 'WebAssembly': false; + readonly 'WebGL2RenderingContext': false; + readonly 'WebGLActiveInfo': false; + readonly 'WebGLBuffer': false; + readonly 'WebGLContextEvent': false; + readonly 'WebGLFramebuffer': false; + readonly 'WebGLProgram': false; + readonly 'WebGLQuery': false; + readonly 'WebGLRenderbuffer': false; + readonly 'WebGLRenderingContext': false; + readonly 'WebGLSampler': false; + readonly 'WebGLShader': false; + readonly 'WebGLShaderPrecisionFormat': false; + readonly 'WebGLSync': false; + readonly 'WebGLTexture': false; + readonly 'WebGLTransformFeedback': false; + readonly 'WebGLUniformLocation': false; + readonly 'WebGLVertexArrayObject': false; + readonly 'WebSocket': false; + readonly 'WheelEvent': false; + readonly 'window': false; + readonly 'Window': false; + readonly 'Worker': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; + readonly 'XMLDocument': false; + readonly 'XMLHttpRequest': false; + readonly 'XMLHttpRequestEventTarget': false; + readonly 'XMLHttpRequestUpload': false; + readonly 'XMLSerializer': false; + readonly 'XPathEvaluator': false; + readonly 'XPathExpression': false; + readonly 'XPathResult': false; + readonly 'XRAnchor': false; + readonly 'XRBoundedReferenceSpace': false; + readonly 'XRCPUDepthInformation': false; + readonly 'XRDepthInformation': false; + readonly 'XRFrame': false; + readonly 'XRInputSource': false; + readonly 'XRInputSourceArray': false; + readonly 'XRInputSourceEvent': false; + readonly 'XRInputSourcesChangeEvent': false; + readonly 'XRPose': false; + readonly 'XRReferenceSpace': false; + readonly 'XRReferenceSpaceEvent': false; + readonly 'XRRenderState': false; + readonly 'XRRigidTransform': false; + readonly 'XRSession': false; + readonly 'XRSessionEvent': false; + readonly 'XRSpace': false; + readonly 'XRSystem': false; + readonly 'XRView': false; + readonly 'XRViewerPose': false; + readonly 'XRViewport': false; + readonly 'XRWebGLBinding': false; + readonly 'XRWebGLDepthInformation': false; + readonly 'XRWebGLLayer': false; + readonly 'XSLTProcessor': false; +} + +type GlobalsWorker = { + readonly 'addEventListener': false; + readonly 'applicationCache': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'Cache': false; + readonly 'caches': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'close': true; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'ErrorEvent': false; + readonly 'Event': false; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FileReaderSync': false; + readonly 'FormData': false; + readonly 'Headers': false; + readonly 'IDBCursor': false; + readonly 'IDBCursorWithValue': false; + readonly 'IDBDatabase': false; + readonly 'IDBFactory': false; + readonly 'IDBIndex': false; + readonly 'IDBKeyRange': false; + readonly 'IDBObjectStore': false; + readonly 'IDBOpenDBRequest': false; + readonly 'IDBRequest': false; + readonly 'IDBTransaction': false; + readonly 'IDBVersionChangeEvent': false; + readonly 'ImageData': false; + readonly 'importScripts': true; + readonly 'indexedDB': false; + readonly 'location': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'name': false; + readonly 'navigator': false; + readonly 'Notification': false; + readonly 'onclose': true; + readonly 'onconnect': true; + readonly 'onerror': true; + readonly 'onlanguagechange': true; + readonly 'onmessage': true; + readonly 'onoffline': true; + readonly 'ononline': true; + readonly 'onrejectionhandled': true; + readonly 'onunhandledrejection': true; + readonly 'performance': false; + readonly 'Performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceNavigation': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'PerformanceTiming': false; + readonly 'postMessage': true; + readonly 'Promise': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'removeEventListener': false; + readonly 'reportError': false; + readonly 'Request': false; + readonly 'Response': false; + readonly 'self': true; + readonly 'ServiceWorkerRegistration': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WebSocket': false; + readonly 'Worker': false; + readonly 'WorkerGlobalScope': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; + readonly 'XMLHttpRequest': false; +} + +type GlobalsNode = { + readonly '__dirname': false; + readonly '__filename': false; + readonly 'AbortController': false; + readonly 'AbortSignal': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'Buffer': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'clearImmediate': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'DOMException': false; + readonly 'Event': false; + readonly 'EventTarget': false; + readonly 'exports': true; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FormData': false; + readonly 'global': false; + readonly 'Headers': false; + readonly 'Intl': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'module': false; + readonly 'performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'process': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'Request': false; + readonly 'require': false; + readonly 'Response': false; + readonly 'setImmediate': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'structuredClone': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; +} + +type GlobalsNodeBuiltin = { + readonly 'AbortController': false; + readonly 'AbortSignal': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'Buffer': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'clearImmediate': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'DOMException': false; + readonly 'Event': false; + readonly 'EventTarget': false; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FormData': false; + readonly 'global': false; + readonly 'Headers': false; + readonly 'Intl': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'process': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'Request': false; + readonly 'Response': false; + readonly 'setImmediate': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'structuredClone': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; +} + +type GlobalsCommonjs = { + readonly 'exports': true; + readonly 'global': false; + readonly 'module': false; + readonly 'require': false; +} + +type GlobalsAmd = { + readonly 'define': false; + readonly 'require': false; +} + +type GlobalsMocha = { + readonly 'after': false; + readonly 'afterEach': false; + readonly 'before': false; + readonly 'beforeEach': false; + readonly 'context': false; + readonly 'describe': false; + readonly 'it': false; + readonly 'mocha': false; + readonly 'run': false; + readonly 'setup': false; + readonly 'specify': false; + readonly 'suite': false; + readonly 'suiteSetup': false; + readonly 'suiteTeardown': false; + readonly 'teardown': false; + readonly 'test': false; + readonly 'xcontext': false; + readonly 'xdescribe': false; + readonly 'xit': false; + readonly 'xspecify': false; +} + +type GlobalsJasmine = { + readonly 'afterAll': false; + readonly 'afterEach': false; + readonly 'beforeAll': false; + readonly 'beforeEach': false; + readonly 'describe': false; + readonly 'expect': false; + readonly 'expectAsync': false; + readonly 'fail': false; + readonly 'fdescribe': false; + readonly 'fit': false; + readonly 'it': false; + readonly 'jasmine': false; + readonly 'pending': false; + readonly 'runs': false; + readonly 'spyOn': false; + readonly 'spyOnAllFunctions': false; + readonly 'spyOnProperty': false; + readonly 'waits': false; + readonly 'waitsFor': false; + readonly 'xdescribe': false; + readonly 'xit': false; +} + +type GlobalsJest = { + readonly 'afterAll': false; + readonly 'afterEach': false; + readonly 'beforeAll': false; + readonly 'beforeEach': false; + readonly 'describe': false; + readonly 'expect': false; + readonly 'fdescribe': false; + readonly 'fit': false; + readonly 'it': false; + readonly 'jest': false; + readonly 'pit': false; + readonly 'require': false; + readonly 'test': false; + readonly 'xdescribe': false; + readonly 'xit': false; + readonly 'xtest': false; +} + +type GlobalsQunit = { + readonly 'asyncTest': false; + readonly 'deepEqual': false; + readonly 'equal': false; + readonly 'expect': false; + readonly 'module': false; + readonly 'notDeepEqual': false; + readonly 'notEqual': false; + readonly 'notOk': false; + readonly 'notPropEqual': false; + readonly 'notStrictEqual': false; + readonly 'ok': false; + readonly 'propEqual': false; + readonly 'QUnit': false; + readonly 'raises': false; + readonly 'start': false; + readonly 'stop': false; + readonly 'strictEqual': false; + readonly 'test': false; + readonly 'throws': false; +} + +type GlobalsPhantomjs = { + readonly 'console': true; + readonly 'exports': true; + readonly 'phantom': true; + readonly 'require': true; + readonly 'WebPage': true; +} + +type GlobalsCouch = { + readonly 'emit': false; + readonly 'exports': false; + readonly 'getRow': false; + readonly 'log': false; + readonly 'module': false; + readonly 'provides': false; + readonly 'require': false; + readonly 'respond': false; + readonly 'send': false; + readonly 'start': false; + readonly 'sum': false; +} + +type GlobalsRhino = { + readonly 'defineClass': false; + readonly 'deserialize': false; + readonly 'gc': false; + readonly 'help': false; + readonly 'importClass': false; + readonly 'importPackage': false; + readonly 'java': false; + readonly 'load': false; + readonly 'loadClass': false; + readonly 'Packages': false; + readonly 'print': false; + readonly 'quit': false; + readonly 'readFile': false; + readonly 'readUrl': false; + readonly 'runCommand': false; + readonly 'seal': false; + readonly 'serialize': false; + readonly 'spawn': false; + readonly 'sync': false; + readonly 'toint32': false; + readonly 'version': false; +} + +type GlobalsNashorn = { + readonly '__DIR__': false; + readonly '__FILE__': false; + readonly '__LINE__': false; + readonly 'com': false; + readonly 'edu': false; + readonly 'exit': false; + readonly 'java': false; + readonly 'Java': false; + readonly 'javafx': false; + readonly 'JavaImporter': false; + readonly 'javax': false; + readonly 'JSAdapter': false; + readonly 'load': false; + readonly 'loadWithNewGlobal': false; + readonly 'org': false; + readonly 'Packages': false; + readonly 'print': false; + readonly 'quit': false; +} + +type GlobalsWsh = { + readonly 'ActiveXObject': false; + readonly 'CollectGarbage': false; + readonly 'Debug': false; + readonly 'Enumerator': false; + readonly 'GetObject': false; + readonly 'RuntimeObject': false; + readonly 'ScriptEngine': false; + readonly 'ScriptEngineBuildVersion': false; + readonly 'ScriptEngineMajorVersion': false; + readonly 'ScriptEngineMinorVersion': false; + readonly 'VBArray': false; + readonly 'WScript': false; + readonly 'WSH': false; +} + +type GlobalsJquery = { + readonly '$': false; + readonly 'jQuery': false; +} + +type GlobalsYui = { + readonly 'YAHOO': false; + readonly 'YAHOO_config': false; + readonly 'YUI': false; + readonly 'YUI_config': false; +} + +type GlobalsShelljs = { + readonly 'cat': false; + readonly 'cd': false; + readonly 'chmod': false; + readonly 'config': false; + readonly 'cp': false; + readonly 'dirs': false; + readonly 'echo': false; + readonly 'env': false; + readonly 'error': false; + readonly 'exec': false; + readonly 'exit': false; + readonly 'find': false; + readonly 'grep': false; + readonly 'ln': false; + readonly 'ls': false; + readonly 'mkdir': false; + readonly 'mv': false; + readonly 'popd': false; + readonly 'pushd': false; + readonly 'pwd': false; + readonly 'rm': false; + readonly 'sed': false; + readonly 'set': false; + readonly 'target': false; + readonly 'tempdir': false; + readonly 'test': false; + readonly 'touch': false; + readonly 'which': false; +} + +type GlobalsPrototypejs = { + readonly '$': false; + readonly '$$': false; + readonly '$A': false; + readonly '$break': false; + readonly '$continue': false; + readonly '$F': false; + readonly '$H': false; + readonly '$R': false; + readonly '$w': false; + readonly 'Abstract': false; + readonly 'Ajax': false; + readonly 'Autocompleter': false; + readonly 'Builder': false; + readonly 'Class': false; + readonly 'Control': false; + readonly 'Draggable': false; + readonly 'Draggables': false; + readonly 'Droppables': false; + readonly 'Effect': false; + readonly 'Element': false; + readonly 'Enumerable': false; + readonly 'Event': false; + readonly 'Field': false; + readonly 'Form': false; + readonly 'Hash': false; + readonly 'Insertion': false; + readonly 'ObjectRange': false; + readonly 'PeriodicalExecuter': false; + readonly 'Position': false; + readonly 'Prototype': false; + readonly 'Scriptaculous': false; + readonly 'Selector': false; + readonly 'Sortable': false; + readonly 'SortableObserver': false; + readonly 'Sound': false; + readonly 'Template': false; + readonly 'Toggle': false; + readonly 'Try': false; +} + +type GlobalsMeteor = { + readonly '$': false; + readonly 'Accounts': false; + readonly 'AccountsClient': false; + readonly 'AccountsCommon': false; + readonly 'AccountsServer': false; + readonly 'App': false; + readonly 'Assets': false; + readonly 'Blaze': false; + readonly 'check': false; + readonly 'Cordova': false; + readonly 'DDP': false; + readonly 'DDPRateLimiter': false; + readonly 'DDPServer': false; + readonly 'Deps': false; + readonly 'EJSON': false; + readonly 'Email': false; + readonly 'HTTP': false; + readonly 'Log': false; + readonly 'Match': false; + readonly 'Meteor': false; + readonly 'Mongo': false; + readonly 'MongoInternals': false; + readonly 'Npm': false; + readonly 'Package': false; + readonly 'Plugin': false; + readonly 'process': false; + readonly 'Random': false; + readonly 'ReactiveDict': false; + readonly 'ReactiveVar': false; + readonly 'Router': false; + readonly 'ServiceConfiguration': false; + readonly 'Session': false; + readonly 'share': false; + readonly 'Spacebars': false; + readonly 'Template': false; + readonly 'Tinytest': false; + readonly 'Tracker': false; + readonly 'UI': false; + readonly 'Utils': false; + readonly 'WebApp': false; + readonly 'WebAppInternals': false; +} + +type GlobalsMongo = { + readonly '_isWindows': false; + readonly '_rand': false; + readonly 'BulkWriteResult': false; + readonly 'cat': false; + readonly 'cd': false; + readonly 'connect': false; + readonly 'db': false; + readonly 'getHostName': false; + readonly 'getMemInfo': false; + readonly 'hostname': false; + readonly 'ISODate': false; + readonly 'listFiles': false; + readonly 'load': false; + readonly 'ls': false; + readonly 'md5sumFile': false; + readonly 'mkdir': false; + readonly 'Mongo': false; + readonly 'NumberInt': false; + readonly 'NumberLong': false; + readonly 'ObjectId': false; + readonly 'PlanCache': false; + readonly 'print': false; + readonly 'printjson': false; + readonly 'pwd': false; + readonly 'quit': false; + readonly 'removeFile': false; + readonly 'rs': false; + readonly 'sh': false; + readonly 'UUID': false; + readonly 'version': false; + readonly 'WriteResult': false; +} + +type GlobalsApplescript = { + readonly '$': false; + readonly 'Application': false; + readonly 'Automation': false; + readonly 'console': false; + readonly 'delay': false; + readonly 'Library': false; + readonly 'ObjC': false; + readonly 'ObjectSpecifier': false; + readonly 'Path': false; + readonly 'Progress': false; + readonly 'Ref': false; +} + +type GlobalsServiceworker = { + readonly 'addEventListener': false; + readonly 'applicationCache': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'Cache': false; + readonly 'caches': false; + readonly 'CacheStorage': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'Client': false; + readonly 'clients': false; + readonly 'Clients': false; + readonly 'close': true; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'ErrorEvent': false; + readonly 'Event': false; + readonly 'ExtendableEvent': false; + readonly 'ExtendableMessageEvent': false; + readonly 'fetch': false; + readonly 'FetchEvent': false; + readonly 'File': false; + readonly 'FileReaderSync': false; + readonly 'FormData': false; + readonly 'Headers': false; + readonly 'IDBCursor': false; + readonly 'IDBCursorWithValue': false; + readonly 'IDBDatabase': false; + readonly 'IDBFactory': false; + readonly 'IDBIndex': false; + readonly 'IDBKeyRange': false; + readonly 'IDBObjectStore': false; + readonly 'IDBOpenDBRequest': false; + readonly 'IDBRequest': false; + readonly 'IDBTransaction': false; + readonly 'IDBVersionChangeEvent': false; + readonly 'ImageData': false; + readonly 'importScripts': false; + readonly 'indexedDB': false; + readonly 'location': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'name': false; + readonly 'navigator': false; + readonly 'Notification': false; + readonly 'onclose': true; + readonly 'onconnect': true; + readonly 'onerror': true; + readonly 'onfetch': true; + readonly 'oninstall': true; + readonly 'onlanguagechange': true; + readonly 'onmessage': true; + readonly 'onmessageerror': true; + readonly 'onnotificationclick': true; + readonly 'onnotificationclose': true; + readonly 'onoffline': true; + readonly 'ononline': true; + readonly 'onpush': true; + readonly 'onpushsubscriptionchange': true; + readonly 'onrejectionhandled': true; + readonly 'onsync': true; + readonly 'onunhandledrejection': true; + readonly 'performance': false; + readonly 'Performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceNavigation': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'PerformanceTiming': false; + readonly 'postMessage': true; + readonly 'Promise': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'registration': false; + readonly 'removeEventListener': false; + readonly 'Request': false; + readonly 'Response': false; + readonly 'self': false; + readonly 'ServiceWorker': false; + readonly 'ServiceWorkerContainer': false; + readonly 'ServiceWorkerGlobalScope': false; + readonly 'ServiceWorkerMessageEvent': false; + readonly 'ServiceWorkerRegistration': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'skipWaiting': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WebSocket': false; + readonly 'WindowClient': false; + readonly 'Worker': false; + readonly 'WorkerGlobalScope': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; + readonly 'XMLHttpRequest': false; +} + +type GlobalsAtomtest = { + readonly 'advanceClock': false; + readonly 'atom': false; + readonly 'fakeClearInterval': false; + readonly 'fakeClearTimeout': false; + readonly 'fakeSetInterval': false; + readonly 'fakeSetTimeout': false; + readonly 'resetTimeouts': false; + readonly 'waitsForPromise': false; +} + +type GlobalsEmbertest = { + readonly 'andThen': false; + readonly 'click': false; + readonly 'currentPath': false; + readonly 'currentRouteName': false; + readonly 'currentURL': false; + readonly 'fillIn': false; + readonly 'find': false; + readonly 'findAll': false; + readonly 'findWithAssert': false; + readonly 'keyEvent': false; + readonly 'pauseTest': false; + readonly 'resumeTest': false; + readonly 'triggerEvent': false; + readonly 'visit': false; + readonly 'wait': false; +} + +type GlobalsProtractor = { + readonly '$': false; + readonly '$$': false; + readonly 'browser': false; + readonly 'by': false; + readonly 'By': false; + readonly 'DartObject': false; + readonly 'element': false; + readonly 'protractor': false; +} + +type GlobalsSharednodebrowser = { + readonly 'AbortController': false; + readonly 'AbortSignal': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'DOMException': false; + readonly 'Event': false; + readonly 'EventTarget': false; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FormData': false; + readonly 'Headers': false; + readonly 'Intl': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'Request': false; + readonly 'Response': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'structuredClone': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; +} + +type GlobalsWebextensions = { + readonly 'browser': false; + readonly 'chrome': false; + readonly 'opr': false; +} + +type GlobalsGreasemonkey = { + readonly 'cloneInto': false; + readonly 'createObjectIn': false; + readonly 'exportFunction': false; + readonly 'GM': false; + readonly 'GM_addElement': false; + readonly 'GM_addStyle': false; + readonly 'GM_addValueChangeListener': false; + readonly 'GM_deleteValue': false; + readonly 'GM_download': false; + readonly 'GM_getResourceText': false; + readonly 'GM_getResourceURL': false; + readonly 'GM_getTab': false; + readonly 'GM_getTabs': false; + readonly 'GM_getValue': false; + readonly 'GM_info': false; + readonly 'GM_listValues': false; + readonly 'GM_log': false; + readonly 'GM_notification': false; + readonly 'GM_openInTab': false; + readonly 'GM_registerMenuCommand': false; + readonly 'GM_removeValueChangeListener': false; + readonly 'GM_saveTab': false; + readonly 'GM_setClipboard': false; + readonly 'GM_setValue': false; + readonly 'GM_unregisterMenuCommand': false; + readonly 'GM_xmlhttpRequest': false; + readonly 'unsafeWindow': false; +} + +type GlobalsDevtools = { + readonly '$': false; + readonly '$_': false; + readonly '$$': false; + readonly '$0': false; + readonly '$1': false; + readonly '$2': false; + readonly '$3': false; + readonly '$4': false; + readonly '$x': false; + readonly 'chrome': false; + readonly 'clear': false; + readonly 'copy': false; + readonly 'debug': false; + readonly 'dir': false; + readonly 'dirxml': false; + readonly 'getEventListeners': false; + readonly 'inspect': false; + readonly 'keys': false; + readonly 'monitor': false; + readonly 'monitorEvents': false; + readonly 'profile': false; + readonly 'profileEnd': false; + readonly 'queryObjects': false; + readonly 'table': false; + readonly 'undebug': false; + readonly 'unmonitor': false; + readonly 'unmonitorEvents': false; + readonly 'values': false; +} + +type Globals = { + readonly 'builtin': GlobalsBuiltin; + readonly 'es5': GlobalsEs5; + readonly 'es2015': GlobalsEs2015; + readonly 'es2017': GlobalsEs2017; + readonly 'es2020': GlobalsEs2020; + readonly 'es2021': GlobalsEs2021; + readonly 'browser': GlobalsBrowser; + readonly 'worker': GlobalsWorker; + readonly 'node': GlobalsNode; + readonly 'nodeBuiltin': GlobalsNodeBuiltin; + readonly 'commonjs': GlobalsCommonjs; + readonly 'amd': GlobalsAmd; + readonly 'mocha': GlobalsMocha; + readonly 'jasmine': GlobalsJasmine; + readonly 'jest': GlobalsJest; + readonly 'qunit': GlobalsQunit; + readonly 'phantomjs': GlobalsPhantomjs; + readonly 'couch': GlobalsCouch; + readonly 'rhino': GlobalsRhino; + readonly 'nashorn': GlobalsNashorn; + readonly 'wsh': GlobalsWsh; + readonly 'jquery': GlobalsJquery; + readonly 'yui': GlobalsYui; + readonly 'shelljs': GlobalsShelljs; + readonly 'prototypejs': GlobalsPrototypejs; + readonly 'meteor': GlobalsMeteor; + readonly 'mongo': GlobalsMongo; + readonly 'applescript': GlobalsApplescript; + readonly 'serviceworker': GlobalsServiceworker; + readonly 'atomtest': GlobalsAtomtest; + readonly 'embertest': GlobalsEmbertest; + readonly 'protractor': GlobalsProtractor; + readonly 'shared-node-browser': GlobalsSharednodebrowser; + readonly 'webextensions': GlobalsWebextensions; + readonly 'greasemonkey': GlobalsGreasemonkey; + readonly 'devtools': GlobalsDevtools; +} + +declare const globals: Globals; + +export = globals; diff --git a/node_modules/globals/index.js b/node_modules/globals/index.js new file mode 100644 index 00000000..a951582e --- /dev/null +++ b/node_modules/globals/index.js @@ -0,0 +1,2 @@ +'use strict'; +module.exports = require('./globals.json'); diff --git a/node_modules/globals/license b/node_modules/globals/license new file mode 100644 index 00000000..fa7ceba3 --- /dev/null +++ b/node_modules/globals/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/globals/package.json b/node_modules/globals/package.json new file mode 100644 index 00000000..fca10a52 --- /dev/null +++ b/node_modules/globals/package.json @@ -0,0 +1,58 @@ +{ + "name": "globals", + "version": "14.0.0", + "description": "Global identifiers from different JavaScript environments", + "license": "MIT", + "repository": "sindresorhus/globals", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "sideEffects": false, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && ava && tsd", + "prepare": "npm run --silent update-types", + "update-builtin-globals": "node scripts/get-builtin-globals.mjs", + "update-types": "node scripts/generate-types.mjs > index.d.ts" + }, + "files": [ + "index.js", + "index.d.ts", + "globals.json" + ], + "keywords": [ + "globals", + "global", + "identifiers", + "variables", + "vars", + "jshint", + "eslint", + "environments" + ], + "devDependencies": { + "ava": "^2.4.0", + "cheerio": "^1.0.0-rc.12", + "tsd": "^0.30.4", + "type-fest": "^4.10.2", + "xo": "^0.36.1" + }, + "xo": { + "ignores": [ + "get-browser-globals.js" + ], + "rules": { + "node/no-unsupported-features/es-syntax": "off" + } + }, + "tsd": { + "compilerOptions": { + "resolveJsonModule": true + } + } +} diff --git a/node_modules/globals/readme.md b/node_modules/globals/readme.md new file mode 100644 index 00000000..29442a85 --- /dev/null +++ b/node_modules/globals/readme.md @@ -0,0 +1,44 @@ +# globals + +> Global identifiers from different JavaScript environments + +It's just a [JSON file](globals.json), so use it in any environment. + +This package is used by ESLint. + +**This package [no longer accepts](https://github.com/sindresorhus/globals/issues/82) new environments. If you need it for ESLint, just [create a plugin](http://eslint.org/docs/developer-guide/working-with-plugins#environments-in-plugins).** + +## Install + +```sh +npm install globals +``` + +## Usage + +```js +const globals = require('globals'); + +console.log(globals.browser); +/* +{ + addEventListener: false, + applicationCache: false, + ArrayBuffer: false, + atob: false, + … +} +*/ +``` + +Each global is given a value of `true` or `false`. A value of `true` indicates that the variable may be overwritten. A value of `false` indicates that the variable should be considered read-only. This information is used by static analysis tools to flag incorrect behavior. We assume all variables should be `false` unless we hear otherwise. + +For Node.js this package provides two sets of globals: + +- `globals.nodeBuiltin`: Globals available to all code running in Node.js. + These will usually be available as properties on the `global` object and include `process`, `Buffer`, but not CommonJS arguments like `require`. + See: https://nodejs.org/api/globals.html +- `globals.node`: A combination of the globals from `nodeBuiltin` plus all CommonJS arguments ("CommonJS module scope"). + See: https://nodejs.org/api/modules.html#modules_the_module_scope + +When analyzing code that is known to run outside of a CommonJS wrapper, for example, JavaScript modules, `nodeBuiltin` can find accidental CommonJS references. diff --git a/node_modules/graphemer/CHANGELOG.md b/node_modules/graphemer/CHANGELOG.md new file mode 100644 index 00000000..dc1dd423 --- /dev/null +++ b/node_modules/graphemer/CHANGELOG.md @@ -0,0 +1,30 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [1.3.0] - 2021-12-13 + +### Added + +- Updated to include support for Unicode 14 + +## [1.2.0] - 2021-01-29 + +### Updated + +- Refactored to increase speed + +## [1.1.0] - 2020-09-14 + +### Added + +- Updated to include support for Unicode 13 + +## [1.0.0] - 2020-09-13 + +- Forked from work by @JLHwung on original `Grapheme-Splitter` library: https://github.com/JLHwung/grapheme-splitter/tree/next +- Converted to Typescript +- Added development and build tooling diff --git a/node_modules/graphemer/LICENSE b/node_modules/graphemer/LICENSE new file mode 100644 index 00000000..51f38310 --- /dev/null +++ b/node_modules/graphemer/LICENSE @@ -0,0 +1,18 @@ +Copyright 2020 Filament (Anomalous Technologies Limited) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/graphemer/README.md b/node_modules/graphemer/README.md new file mode 100644 index 00000000..0ac98ad3 --- /dev/null +++ b/node_modules/graphemer/README.md @@ -0,0 +1,132 @@ +# Graphemer: Unicode Character Splitter 🪓 + +## Introduction + +This library continues the work of [Grapheme Splitter](https://github.com/orling/grapheme-splitter) and supports the following unicode versions: + +- Unicode 15 and below `[v1.4.0]` +- Unicode 14 and below `[v1.3.0]` +- Unicode 13 and below `[v1.1.0]` +- Unicode 11 and below `[v1.0.0]` (Unicode 10 supported by `grapheme-splitter`) + +In JavaScript there is not always a one-to-one relationship between string characters and what a user would call a separate visual "letter". Some symbols are represented by several characters. This can cause issues when splitting strings and inadvertently cutting a multi-char letter in half, or when you need the actual number of letters in a string. + +For example, emoji characters like "🌷","🎁","💩","😜" and "👍" are represented by two JavaScript characters each (high surrogate and low surrogate). That is, + +```javascript +'🌷'.length == 2; +``` + +The combined emoji are even longer: + +```javascript +'🏳️‍🌈'.length == 6; +``` + +What's more, some languages often include combining marks - characters that are used to modify the letters before them. Common examples are the German letter ü and the Spanish letter ñ. Sometimes they can be represented alternatively both as a single character and as a letter + combining mark, with both forms equally valid: + +```javascript +var two = 'ñ'; // unnormalized two-char n+◌̃, i.e. "\u006E\u0303"; +var one = 'ñ'; // normalized single-char, i.e. "\u00F1" + +console.log(one != two); // prints 'true' +``` + +Unicode normalization, as performed by the popular punycode.js library or ECMAScript 6's String.normalize, can **sometimes** fix those differences and turn two-char sequences into single characters. But it is **not** enough in all cases. Some languages like Hindi make extensive use of combining marks on their letters, that have no dedicated single-codepoint Unicode sequences, due to the sheer number of possible combinations. +For example, the Hindi word "अनुच्छेद" is comprised of 5 letters and 3 combining marks: + +अ + न + ु + च + ् + छ + े + द + +which is in fact just 5 user-perceived letters: + +अ + नु + च् + छे + द + +and which Unicode normalization would not combine properly. +There are also the unusual letter+combining mark combinations which have no dedicated Unicode codepoint. The string Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘ obviously has 5 separate letters, but is in fact comprised of 58 JavaScript characters, most of which are combining marks. + +Enter the `graphemer` library. It can be used to properly split JavaScript strings into what a human user would call separate letters (or "extended grapheme clusters" in Unicode terminology), no matter what their internal representation is. It is an implementation on the [Default Grapheme Cluster Boundary](http://unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table) of [UAX #29](http://www.unicode.org/reports/tr29/). + +## Installation + +Install `graphemer` using the NPM command below: + +``` +$ npm i graphemer +``` + +## Usage + +If you're using [Typescript](https://www.typescriptlang.org/) or a compiler like [Babel](https://babeljs.io/) (or something like Create React App) things are pretty simple; just import, initialize and use! + +```javascript +import Graphemer from 'graphemer'; + +const splitter = new Graphemer(); + +// split the string to an array of grapheme clusters (one string each) +const graphemes = splitter.splitGraphemes(string); + +// iterate the string to an iterable iterator of grapheme clusters (one string each) +const graphemeIterator = splitter.iterateGraphemes(string); + +// or do this if you just need their number +const graphemeCount = splitter.countGraphemes(string); +``` + +If you're using vanilla Node you can use the `require()` method. + +```javascript +const Graphemer = require('graphemer').default; + +const splitter = new Graphemer(); + +const graphemes = splitter.splitGraphemes(string); +``` + +## Examples + +```javascript +import Graphemer from 'graphemer'; + +const splitter = new Graphemer(); + +// plain latin alphabet - nothing spectacular +splitter.splitGraphemes('abcd'); // returns ["a", "b", "c", "d"] + +// two-char emojis and six-char combined emoji +splitter.splitGraphemes('🌷🎁💩😜👍🏳️‍🌈'); // returns ["🌷","🎁","💩","😜","👍","🏳️‍🌈"] + +// diacritics as combining marks, 10 JavaScript chars +splitter.splitGraphemes('Ĺo͂řȩm̅'); // returns ["Ĺ","o͂","ř","ȩ","m̅"] + +// individual Korean characters (Jamo), 4 JavaScript chars +splitter.splitGraphemes('뎌쉐'); // returns ["뎌","쉐"] + +// Hindi text with combining marks, 8 JavaScript chars +splitter.splitGraphemes('अनुच्छेद'); // returns ["अ","नु","च्","छे","द"] + +// demonic multiple combining marks, 75 JavaScript chars +splitter.splitGraphemes('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞'); // returns ["Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍","A̴̵̜̰͔ͫ͗͢","L̠ͨͧͩ͘","G̴̻͈͍͔̹̑͗̎̅͛́","Ǫ̵̹̻̝̳͂̌̌͘","!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞"] +``` + +## TypeScript + +Graphemer is built with TypeScript and, of course, includes type declarations. + +```javascript +import Graphemer from 'graphemer'; + +const splitter = new Graphemer(); + +const split: string[] = splitter.splitGraphemes('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞'); +``` + +## Contributing + +See [Contribution Guide](./CONTRIBUTING.md). + +## Acknowledgements + +This library is a fork of the incredible work done by Orlin Georgiev and Huáng Jùnliàng at https://github.com/orling/grapheme-splitter. + +The original library was heavily influenced by Devon Govett's excellent [grapheme-breaker](https://github.com/devongovett/grapheme-breaker) CoffeeScript library. diff --git a/node_modules/graphemer/lib/Graphemer.d.ts b/node_modules/graphemer/lib/Graphemer.d.ts new file mode 100644 index 00000000..a89b8cbc --- /dev/null +++ b/node_modules/graphemer/lib/Graphemer.d.ts @@ -0,0 +1,41 @@ +import GraphemerIterator from './GraphemerIterator'; +export default class Graphemer { + /** + * Returns the next grapheme break in the string after the given index + * @param string {string} + * @param index {number} + * @returns {number} + */ + static nextBreak(string: string, index: number): number; + /** + * Breaks the given string into an array of grapheme clusters + * @param str {string} + * @returns {string[]} + */ + splitGraphemes(str: string): string[]; + /** + * Returns an iterator of grapheme clusters in the given string + * @param str {string} + * @returns {GraphemerIterator} + */ + iterateGraphemes(str: string): GraphemerIterator; + /** + * Returns the number of grapheme clusters in the given string + * @param str {string} + * @returns {number} + */ + countGraphemes(str: string): number; + /** + * Given a Unicode code point, determines this symbol's grapheme break property + * @param code {number} Unicode code point + * @returns {number} + */ + static getGraphemeBreakProperty(code: number): number; + /** + * Given a Unicode code point, returns if symbol is an extended pictographic or some other break + * @param code {number} Unicode code point + * @returns {number} + */ + static getEmojiProperty(code: number): number; +} +//# sourceMappingURL=Graphemer.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/Graphemer.d.ts.map b/node_modules/graphemer/lib/Graphemer.d.ts.map new file mode 100644 index 00000000..692b7623 --- /dev/null +++ b/node_modules/graphemer/lib/Graphemer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Graphemer.d.ts","sourceRoot":"","sources":["../src/Graphemer.ts"],"names":[],"mappings":"AAEA,OAAO,iBAAiB,MAAM,qBAAqB,CAAC;AAEpD,MAAM,CAAC,OAAO,OAAO,SAAS;IAC5B;;;;;OAKG;IACH,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM;IA2CvD;;;;OAIG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE;IAcrC;;;;OAIG;IACH,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB;IAIhD;;;;OAIG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAcnC;;;;OAIG;IACH,MAAM,CAAC,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAoySrD;;;;OAIG;IACH,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CA47B9C"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/Graphemer.js b/node_modules/graphemer/lib/Graphemer.js new file mode 100644 index 00000000..8ed00ca5 --- /dev/null +++ b/node_modules/graphemer/lib/Graphemer.js @@ -0,0 +1,11959 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const boundaries_1 = require("./boundaries"); +const GraphemerHelper_1 = __importDefault(require("./GraphemerHelper")); +const GraphemerIterator_1 = __importDefault(require("./GraphemerIterator")); +class Graphemer { + /** + * Returns the next grapheme break in the string after the given index + * @param string {string} + * @param index {number} + * @returns {number} + */ + static nextBreak(string, index) { + if (index === undefined) { + index = 0; + } + if (index < 0) { + return 0; + } + if (index >= string.length - 1) { + return string.length; + } + const prevCP = GraphemerHelper_1.default.codePointAt(string, index); + const prev = Graphemer.getGraphemeBreakProperty(prevCP); + const prevEmoji = Graphemer.getEmojiProperty(prevCP); + const mid = []; + const midEmoji = []; + for (let i = index + 1; i < string.length; i++) { + // check for already processed low surrogates + if (GraphemerHelper_1.default.isSurrogate(string, i - 1)) { + continue; + } + const nextCP = GraphemerHelper_1.default.codePointAt(string, i); + const next = Graphemer.getGraphemeBreakProperty(nextCP); + const nextEmoji = Graphemer.getEmojiProperty(nextCP); + if (GraphemerHelper_1.default.shouldBreak(prev, mid, next, prevEmoji, midEmoji, nextEmoji)) { + return i; + } + mid.push(next); + midEmoji.push(nextEmoji); + } + return string.length; + } + /** + * Breaks the given string into an array of grapheme clusters + * @param str {string} + * @returns {string[]} + */ + splitGraphemes(str) { + const res = []; + let index = 0; + let brk; + while ((brk = Graphemer.nextBreak(str, index)) < str.length) { + res.push(str.slice(index, brk)); + index = brk; + } + if (index < str.length) { + res.push(str.slice(index)); + } + return res; + } + /** + * Returns an iterator of grapheme clusters in the given string + * @param str {string} + * @returns {GraphemerIterator} + */ + iterateGraphemes(str) { + return new GraphemerIterator_1.default(str, Graphemer.nextBreak); + } + /** + * Returns the number of grapheme clusters in the given string + * @param str {string} + * @returns {number} + */ + countGraphemes(str) { + let count = 0; + let index = 0; + let brk; + while ((brk = Graphemer.nextBreak(str, index)) < str.length) { + index = brk; + count++; + } + if (index < str.length) { + count++; + } + return count; + } + /** + * Given a Unicode code point, determines this symbol's grapheme break property + * @param code {number} Unicode code point + * @returns {number} + */ + static getGraphemeBreakProperty(code) { + // Grapheme break property taken from: + // https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakProperty.txt + // and generated by + // node ./scripts/generate-grapheme-break.js + if (code < 0xbf09) { + if (code < 0xac54) { + if (code < 0x102d) { + if (code < 0xb02) { + if (code < 0x93b) { + if (code < 0x6df) { + if (code < 0x5bf) { + if (code < 0x7f) { + if (code < 0xb) { + if (code < 0xa) { + // Cc [10] .. + if (0x0 <= code && code <= 0x9) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Cc + if (0xa === code) { + return boundaries_1.CLUSTER_BREAK.LF; + } + } + } + else { + if (code < 0xd) { + // Cc [2] .. + if (0xb <= code && code <= 0xc) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0xe) { + // Cc + if (0xd === code) { + return boundaries_1.CLUSTER_BREAK.CR; + } + } + else { + // Cc [18] .. + if (0xe <= code && code <= 0x1f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + } + } + else { + if (code < 0x300) { + if (code < 0xad) { + // Cc [33] .. + if (0x7f <= code && code <= 0x9f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Cf SOFT HYPHEN + if (0xad === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + else { + if (code < 0x483) { + // Mn [112] COMBINING GRAVE ACCENT..COMBINING LATIN SMALL LETTER X + if (0x300 <= code && code <= 0x36f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x591) { + // Mn [5] COMBINING CYRILLIC TITLO..COMBINING CYRILLIC POKRYTIE + // Me [2] COMBINING CYRILLIC HUNDRED THOUSANDS SIGN..COMBINING CYRILLIC MILLIONS SIGN + if (0x483 <= code && code <= 0x489) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [45] HEBREW ACCENT ETNAHTA..HEBREW POINT METEG + if (0x591 <= code && code <= 0x5bd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x610) { + if (code < 0x5c4) { + if (code < 0x5c1) { + // Mn HEBREW POINT RAFE + if (0x5bf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] HEBREW POINT SHIN DOT..HEBREW POINT SIN DOT + if (0x5c1 <= code && code <= 0x5c2) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x5c7) { + // Mn [2] HEBREW MARK UPPER DOT..HEBREW MARK LOWER DOT + if (0x5c4 <= code && code <= 0x5c5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x600) { + // Mn HEBREW POINT QAMATS QATAN + if (0x5c7 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf [6] ARABIC NUMBER SIGN..ARABIC NUMBER MARK ABOVE + if (0x600 <= code && code <= 0x605) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + } + else { + if (code < 0x670) { + if (code < 0x61c) { + // Mn [11] ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM..ARABIC SMALL KASRA + if (0x610 <= code && code <= 0x61a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x64b) { + // Cf ARABIC LETTER MARK + if (0x61c === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Mn [21] ARABIC FATHATAN..ARABIC WAVY HAMZA BELOW + if (0x64b <= code && code <= 0x65f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x6d6) { + // Mn ARABIC LETTER SUPERSCRIPT ALEF + if (0x670 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x6dd) { + // Mn [7] ARABIC SMALL HIGH LIGATURE SAD WITH LAM WITH ALEF MAKSURA..ARABIC SMALL HIGH SEEN + if (0x6d6 <= code && code <= 0x6dc) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf ARABIC END OF AYAH + if (0x6dd === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + } + } + } + else { + if (code < 0x81b) { + if (code < 0x730) { + if (code < 0x6ea) { + if (code < 0x6e7) { + // Mn [6] ARABIC SMALL HIGH ROUNDED ZERO..ARABIC SMALL HIGH MADDA + if (0x6df <= code && code <= 0x6e4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] ARABIC SMALL HIGH YEH..ARABIC SMALL HIGH NOON + if (0x6e7 <= code && code <= 0x6e8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x70f) { + // Mn [4] ARABIC EMPTY CENTRE LOW STOP..ARABIC SMALL LOW MEEM + if (0x6ea <= code && code <= 0x6ed) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf SYRIAC ABBREVIATION MARK + if (0x70f === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + // Mn SYRIAC LETTER SUPERSCRIPT ALAPH + if (0x711 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x7eb) { + if (code < 0x7a6) { + // Mn [27] SYRIAC PTHAHA ABOVE..SYRIAC BARREKH + if (0x730 <= code && code <= 0x74a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [11] THAANA ABAFILI..THAANA SUKUN + if (0x7a6 <= code && code <= 0x7b0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x7fd) { + // Mn [9] NKO COMBINING SHORT HIGH TONE..NKO COMBINING DOUBLE DOT ABOVE + if (0x7eb <= code && code <= 0x7f3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x816) { + // Mn NKO DANTAYALAN + if (0x7fd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [4] SAMARITAN MARK IN..SAMARITAN MARK DAGESH + if (0x816 <= code && code <= 0x819) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x898) { + if (code < 0x829) { + if (code < 0x825) { + // Mn [9] SAMARITAN MARK EPENTHETIC YUT..SAMARITAN VOWEL SIGN A + if (0x81b <= code && code <= 0x823) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] SAMARITAN VOWEL SIGN SHORT A..SAMARITAN VOWEL SIGN U + if (0x825 <= code && code <= 0x827) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x859) { + // Mn [5] SAMARITAN VOWEL SIGN LONG I..SAMARITAN MARK NEQUDAA + if (0x829 <= code && code <= 0x82d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x890) { + // Mn [3] MANDAIC AFFRICATION MARK..MANDAIC GEMINATION MARK + if (0x859 <= code && code <= 0x85b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf [2] ARABIC POUND MARK ABOVE..ARABIC PIASTRE MARK ABOVE + if (0x890 <= code && code <= 0x891) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + } + else { + if (code < 0x8e3) { + if (code < 0x8ca) { + // Mn [8] ARABIC SMALL HIGH WORD AL-JUZ..ARABIC HALF MADDA OVER MADDA + if (0x898 <= code && code <= 0x89f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x8e2) { + // Mn [24] ARABIC SMALL HIGH FARSI YEH..ARABIC SMALL HIGH SIGN SAFHA + if (0x8ca <= code && code <= 0x8e1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf ARABIC DISPUTED END OF AYAH + if (0x8e2 === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + else { + if (code < 0x903) { + // Mn [32] ARABIC TURNED DAMMA BELOW..DEVANAGARI SIGN ANUSVARA + if (0x8e3 <= code && code <= 0x902) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc DEVANAGARI SIGN VISARGA + if (0x903 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn DEVANAGARI VOWEL SIGN OE + if (0x93a === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0xa01) { + if (code < 0x982) { + if (code < 0x94d) { + if (code < 0x93e) { + // Mc DEVANAGARI VOWEL SIGN OOE + if (0x93b === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn DEVANAGARI SIGN NUKTA + if (0x93c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x941) { + // Mc [3] DEVANAGARI VOWEL SIGN AA..DEVANAGARI VOWEL SIGN II + if (0x93e <= code && code <= 0x940) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x949) { + // Mn [8] DEVANAGARI VOWEL SIGN U..DEVANAGARI VOWEL SIGN AI + if (0x941 <= code && code <= 0x948) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [4] DEVANAGARI VOWEL SIGN CANDRA O..DEVANAGARI VOWEL SIGN AU + if (0x949 <= code && code <= 0x94c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x951) { + if (code < 0x94e) { + // Mn DEVANAGARI SIGN VIRAMA + if (0x94d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] DEVANAGARI VOWEL SIGN PRISHTHAMATRA E..DEVANAGARI VOWEL SIGN AW + if (0x94e <= code && code <= 0x94f) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x962) { + // Mn [7] DEVANAGARI STRESS SIGN UDATTA..DEVANAGARI VOWEL SIGN UUE + if (0x951 <= code && code <= 0x957) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x981) { + // Mn [2] DEVANAGARI VOWEL SIGN VOCALIC L..DEVANAGARI VOWEL SIGN VOCALIC LL + if (0x962 <= code && code <= 0x963) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn BENGALI SIGN CANDRABINDU + if (0x981 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x9c7) { + if (code < 0x9be) { + if (code < 0x9bc) { + // Mc [2] BENGALI SIGN ANUSVARA..BENGALI SIGN VISARGA + if (0x982 <= code && code <= 0x983) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BENGALI SIGN NUKTA + if (0x9bc === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x9bf) { + // Mc BENGALI VOWEL SIGN AA + if (0x9be === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x9c1) { + // Mc [2] BENGALI VOWEL SIGN I..BENGALI VOWEL SIGN II + if (0x9bf <= code && code <= 0x9c0) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] BENGALI VOWEL SIGN U..BENGALI VOWEL SIGN VOCALIC RR + if (0x9c1 <= code && code <= 0x9c4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x9d7) { + if (code < 0x9cb) { + // Mc [2] BENGALI VOWEL SIGN E..BENGALI VOWEL SIGN AI + if (0x9c7 <= code && code <= 0x9c8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x9cd) { + // Mc [2] BENGALI VOWEL SIGN O..BENGALI VOWEL SIGN AU + if (0x9cb <= code && code <= 0x9cc) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BENGALI SIGN VIRAMA + if (0x9cd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x9e2) { + // Mc BENGALI AU LENGTH MARK + if (0x9d7 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x9fe) { + // Mn [2] BENGALI VOWEL SIGN VOCALIC L..BENGALI VOWEL SIGN VOCALIC LL + if (0x9e2 <= code && code <= 0x9e3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn BENGALI SANDHI MARK + if (0x9fe === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0xa83) { + if (code < 0xa47) { + if (code < 0xa3c) { + if (code < 0xa03) { + // Mn [2] GURMUKHI SIGN ADAK BINDI..GURMUKHI SIGN BINDI + if (0xa01 <= code && code <= 0xa02) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc GURMUKHI SIGN VISARGA + if (0xa03 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0xa3e) { + // Mn GURMUKHI SIGN NUKTA + if (0xa3c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa41) { + // Mc [3] GURMUKHI VOWEL SIGN AA..GURMUKHI VOWEL SIGN II + if (0xa3e <= code && code <= 0xa40) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] GURMUKHI VOWEL SIGN U..GURMUKHI VOWEL SIGN UU + if (0xa41 <= code && code <= 0xa42) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xa70) { + if (code < 0xa4b) { + // Mn [2] GURMUKHI VOWEL SIGN EE..GURMUKHI VOWEL SIGN AI + if (0xa47 <= code && code <= 0xa48) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa51) { + // Mn [3] GURMUKHI VOWEL SIGN OO..GURMUKHI SIGN VIRAMA + if (0xa4b <= code && code <= 0xa4d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn GURMUKHI SIGN UDAAT + if (0xa51 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xa75) { + // Mn [2] GURMUKHI TIPPI..GURMUKHI ADDAK + if (0xa70 <= code && code <= 0xa71) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa81) { + // Mn GURMUKHI SIGN YAKASH + if (0xa75 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] GUJARATI SIGN CANDRABINDU..GUJARATI SIGN ANUSVARA + if (0xa81 <= code && code <= 0xa82) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xac9) { + if (code < 0xabe) { + // Mc GUJARATI SIGN VISARGA + if (0xa83 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn GUJARATI SIGN NUKTA + if (0xabc === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xac1) { + // Mc [3] GUJARATI VOWEL SIGN AA..GUJARATI VOWEL SIGN II + if (0xabe <= code && code <= 0xac0) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xac7) { + // Mn [5] GUJARATI VOWEL SIGN U..GUJARATI VOWEL SIGN CANDRA E + if (0xac1 <= code && code <= 0xac5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] GUJARATI VOWEL SIGN E..GUJARATI VOWEL SIGN AI + if (0xac7 <= code && code <= 0xac8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xae2) { + if (code < 0xacb) { + // Mc GUJARATI VOWEL SIGN CANDRA O + if (0xac9 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xacd) { + // Mc [2] GUJARATI VOWEL SIGN O..GUJARATI VOWEL SIGN AU + if (0xacb <= code && code <= 0xacc) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn GUJARATI SIGN VIRAMA + if (0xacd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xafa) { + // Mn [2] GUJARATI VOWEL SIGN VOCALIC L..GUJARATI VOWEL SIGN VOCALIC LL + if (0xae2 <= code && code <= 0xae3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xb01) { + // Mn [6] GUJARATI SIGN SUKUN..GUJARATI SIGN TWO-CIRCLE NUKTA ABOVE + if (0xafa <= code && code <= 0xaff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn ORIYA SIGN CANDRABINDU + if (0xb01 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xcf3) { + if (code < 0xc04) { + if (code < 0xb82) { + if (code < 0xb47) { + if (code < 0xb3e) { + if (code < 0xb3c) { + // Mc [2] ORIYA SIGN ANUSVARA..ORIYA SIGN VISARGA + if (0xb02 <= code && code <= 0xb03) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn ORIYA SIGN NUKTA + if (0xb3c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xb40) { + // Mc ORIYA VOWEL SIGN AA + // Mn ORIYA VOWEL SIGN I + if (0xb3e <= code && code <= 0xb3f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xb41) { + // Mc ORIYA VOWEL SIGN II + if (0xb40 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] ORIYA VOWEL SIGN U..ORIYA VOWEL SIGN VOCALIC RR + if (0xb41 <= code && code <= 0xb44) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xb4d) { + if (code < 0xb4b) { + // Mc [2] ORIYA VOWEL SIGN E..ORIYA VOWEL SIGN AI + if (0xb47 <= code && code <= 0xb48) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [2] ORIYA VOWEL SIGN O..ORIYA VOWEL SIGN AU + if (0xb4b <= code && code <= 0xb4c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0xb55) { + // Mn ORIYA SIGN VIRAMA + if (0xb4d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xb62) { + // Mn [2] ORIYA SIGN OVERLINE..ORIYA AI LENGTH MARK + // Mc ORIYA AU LENGTH MARK + if (0xb55 <= code && code <= 0xb57) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] ORIYA VOWEL SIGN VOCALIC L..ORIYA VOWEL SIGN VOCALIC LL + if (0xb62 <= code && code <= 0xb63) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xbc6) { + if (code < 0xbbf) { + // Mn TAMIL SIGN ANUSVARA + if (0xb82 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc TAMIL VOWEL SIGN AA + if (0xbbe === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xbc0) { + // Mc TAMIL VOWEL SIGN I + if (0xbbf === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xbc1) { + // Mn TAMIL VOWEL SIGN II + if (0xbc0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] TAMIL VOWEL SIGN U..TAMIL VOWEL SIGN UU + if (0xbc1 <= code && code <= 0xbc2) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xbd7) { + if (code < 0xbca) { + // Mc [3] TAMIL VOWEL SIGN E..TAMIL VOWEL SIGN AI + if (0xbc6 <= code && code <= 0xbc8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xbcd) { + // Mc [3] TAMIL VOWEL SIGN O..TAMIL VOWEL SIGN AU + if (0xbca <= code && code <= 0xbcc) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn TAMIL SIGN VIRAMA + if (0xbcd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xc00) { + // Mc TAMIL AU LENGTH MARK + if (0xbd7 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xc01) { + // Mn TELUGU SIGN COMBINING CANDRABINDU ABOVE + if (0xc00 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] TELUGU SIGN CANDRABINDU..TELUGU SIGN VISARGA + if (0xc01 <= code && code <= 0xc03) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + else { + if (code < 0xcbe) { + if (code < 0xc4a) { + if (code < 0xc3e) { + // Mn TELUGU SIGN COMBINING ANUSVARA ABOVE + if (0xc04 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn TELUGU SIGN NUKTA + if (0xc3c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xc41) { + // Mn [3] TELUGU VOWEL SIGN AA..TELUGU VOWEL SIGN II + if (0xc3e <= code && code <= 0xc40) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xc46) { + // Mc [4] TELUGU VOWEL SIGN U..TELUGU VOWEL SIGN VOCALIC RR + if (0xc41 <= code && code <= 0xc44) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [3] TELUGU VOWEL SIGN E..TELUGU VOWEL SIGN AI + if (0xc46 <= code && code <= 0xc48) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xc81) { + if (code < 0xc55) { + // Mn [4] TELUGU VOWEL SIGN O..TELUGU SIGN VIRAMA + if (0xc4a <= code && code <= 0xc4d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xc62) { + // Mn [2] TELUGU LENGTH MARK..TELUGU AI LENGTH MARK + if (0xc55 <= code && code <= 0xc56) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] TELUGU VOWEL SIGN VOCALIC L..TELUGU VOWEL SIGN VOCALIC LL + if (0xc62 <= code && code <= 0xc63) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xc82) { + // Mn KANNADA SIGN CANDRABINDU + if (0xc81 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xcbc) { + // Mc [2] KANNADA SIGN ANUSVARA..KANNADA SIGN VISARGA + if (0xc82 <= code && code <= 0xc83) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn KANNADA SIGN NUKTA + if (0xcbc === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xcc6) { + if (code < 0xcc0) { + // Mc KANNADA VOWEL SIGN AA + if (0xcbe === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn KANNADA VOWEL SIGN I + if (0xcbf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xcc2) { + // Mc [2] KANNADA VOWEL SIGN II..KANNADA VOWEL SIGN U + if (0xcc0 <= code && code <= 0xcc1) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xcc3) { + // Mc KANNADA VOWEL SIGN UU + if (0xcc2 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] KANNADA VOWEL SIGN VOCALIC R..KANNADA VOWEL SIGN VOCALIC RR + if (0xcc3 <= code && code <= 0xcc4) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xccc) { + if (code < 0xcc7) { + // Mn KANNADA VOWEL SIGN E + if (0xcc6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xcca) { + // Mc [2] KANNADA VOWEL SIGN EE..KANNADA VOWEL SIGN AI + if (0xcc7 <= code && code <= 0xcc8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [2] KANNADA VOWEL SIGN O..KANNADA VOWEL SIGN OO + if (0xcca <= code && code <= 0xccb) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0xcd5) { + // Mn [2] KANNADA VOWEL SIGN AU..KANNADA SIGN VIRAMA + if (0xccc <= code && code <= 0xccd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xce2) { + // Mc [2] KANNADA LENGTH MARK..KANNADA AI LENGTH MARK + if (0xcd5 <= code && code <= 0xcd6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] KANNADA VOWEL SIGN VOCALIC L..KANNADA VOWEL SIGN VOCALIC LL + if (0xce2 <= code && code <= 0xce3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0xddf) { + if (code < 0xd4e) { + if (code < 0xd3f) { + if (code < 0xd02) { + if (code < 0xd00) { + // Mc KANNADA SIGN COMBINING ANUSVARA ABOVE RIGHT + if (0xcf3 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] MALAYALAM SIGN COMBINING ANUSVARA ABOVE..MALAYALAM SIGN CANDRABINDU + if (0xd00 <= code && code <= 0xd01) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xd3b) { + // Mc [2] MALAYALAM SIGN ANUSVARA..MALAYALAM SIGN VISARGA + if (0xd02 <= code && code <= 0xd03) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xd3e) { + // Mn [2] MALAYALAM SIGN VERTICAL BAR VIRAMA..MALAYALAM SIGN CIRCULAR VIRAMA + if (0xd3b <= code && code <= 0xd3c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc MALAYALAM VOWEL SIGN AA + if (0xd3e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xd46) { + if (code < 0xd41) { + // Mc [2] MALAYALAM VOWEL SIGN I..MALAYALAM VOWEL SIGN II + if (0xd3f <= code && code <= 0xd40) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] MALAYALAM VOWEL SIGN U..MALAYALAM VOWEL SIGN VOCALIC RR + if (0xd41 <= code && code <= 0xd44) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xd4a) { + // Mc [3] MALAYALAM VOWEL SIGN E..MALAYALAM VOWEL SIGN AI + if (0xd46 <= code && code <= 0xd48) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xd4d) { + // Mc [3] MALAYALAM VOWEL SIGN O..MALAYALAM VOWEL SIGN AU + if (0xd4a <= code && code <= 0xd4c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MALAYALAM SIGN VIRAMA + if (0xd4d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xdca) { + if (code < 0xd62) { + // Lo MALAYALAM LETTER DOT REPH + if (0xd4e === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + // Mc MALAYALAM AU LENGTH MARK + if (0xd57 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xd81) { + // Mn [2] MALAYALAM VOWEL SIGN VOCALIC L..MALAYALAM VOWEL SIGN VOCALIC LL + if (0xd62 <= code && code <= 0xd63) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xd82) { + // Mn SINHALA SIGN CANDRABINDU + if (0xd81 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SINHALA SIGN ANUSVARAYA..SINHALA SIGN VISARGAYA + if (0xd82 <= code && code <= 0xd83) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xdd2) { + if (code < 0xdcf) { + // Mn SINHALA SIGN AL-LAKUNA + if (0xdca === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xdd0) { + // Mc SINHALA VOWEL SIGN AELA-PILLA + if (0xdcf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SINHALA VOWEL SIGN KETTI AEDA-PILLA..SINHALA VOWEL SIGN DIGA AEDA-PILLA + if (0xdd0 <= code && code <= 0xdd1) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0xdd6) { + // Mn [3] SINHALA VOWEL SIGN KETTI IS-PILLA..SINHALA VOWEL SIGN KETTI PAA-PILLA + if (0xdd2 <= code && code <= 0xdd4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xdd8) { + // Mn SINHALA VOWEL SIGN DIGA PAA-PILLA + if (0xdd6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [7] SINHALA VOWEL SIGN GAETTA-PILLA..SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA + if (0xdd8 <= code && code <= 0xdde) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + else { + if (code < 0xf35) { + if (code < 0xe47) { + if (code < 0xe31) { + if (code < 0xdf2) { + // Mc SINHALA VOWEL SIGN GAYANUKITTA + if (0xddf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SINHALA VOWEL SIGN DIGA GAETTA-PILLA..SINHALA VOWEL SIGN DIGA GAYANUKITTA + if (0xdf2 <= code && code <= 0xdf3) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0xe33) { + // Mn THAI CHARACTER MAI HAN-AKAT + if (0xe31 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xe34) { + // Lo THAI CHARACTER SARA AM + if (0xe33 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [7] THAI CHARACTER SARA I..THAI CHARACTER PHINTHU + if (0xe34 <= code && code <= 0xe3a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xeb4) { + if (code < 0xeb1) { + // Mn [8] THAI CHARACTER MAITAIKHU..THAI CHARACTER YAMAKKAN + if (0xe47 <= code && code <= 0xe4e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn LAO VOWEL SIGN MAI KAN + if (0xeb1 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Lo LAO VOWEL SIGN AM + if (0xeb3 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0xec8) { + // Mn [9] LAO VOWEL SIGN I..LAO SEMIVOWEL SIGN LO + if (0xeb4 <= code && code <= 0xebc) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xf18) { + // Mn [7] LAO TONE MAI EK..LAO YAMAKKAN + if (0xec8 <= code && code <= 0xece) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] TIBETAN ASTROLOGICAL SIGN -KHYUD PA..TIBETAN ASTROLOGICAL SIGN SDONG TSHUGS + if (0xf18 <= code && code <= 0xf19) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xf7f) { + if (code < 0xf39) { + // Mn TIBETAN MARK NGAS BZUNG NYI ZLA + if (0xf35 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn TIBETAN MARK NGAS BZUNG SGOR RTAGS + if (0xf37 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xf3e) { + // Mn TIBETAN MARK TSA -PHRU + if (0xf39 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xf71) { + // Mc [2] TIBETAN SIGN YAR TSHES..TIBETAN SIGN MAR TSHES + if (0xf3e <= code && code <= 0xf3f) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [14] TIBETAN VOWEL SIGN AA..TIBETAN SIGN RJES SU NGA RO + if (0xf71 <= code && code <= 0xf7e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xf8d) { + if (code < 0xf80) { + // Mc TIBETAN SIGN RNAM BCAD + if (0xf7f === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xf86) { + // Mn [5] TIBETAN VOWEL SIGN REVERSED I..TIBETAN MARK HALANTA + if (0xf80 <= code && code <= 0xf84) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] TIBETAN SIGN LCI RTAGS..TIBETAN SIGN YANG RTAGS + if (0xf86 <= code && code <= 0xf87) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xf99) { + // Mn [11] TIBETAN SUBJOINED SIGN LCE TSA CAN..TIBETAN SUBJOINED LETTER JA + if (0xf8d <= code && code <= 0xf97) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xfc6) { + // Mn [36] TIBETAN SUBJOINED LETTER NYA..TIBETAN SUBJOINED LETTER FIXED-FORM RA + if (0xf99 <= code && code <= 0xfbc) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn TIBETAN SYMBOL PADMA GDAN + if (0xfc6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0x1c24) { + if (code < 0x1930) { + if (code < 0x1732) { + if (code < 0x1082) { + if (code < 0x103d) { + if (code < 0x1032) { + if (code < 0x1031) { + // Mn [4] MYANMAR VOWEL SIGN I..MYANMAR VOWEL SIGN UU + if (0x102d <= code && code <= 0x1030) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc MYANMAR VOWEL SIGN E + if (0x1031 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1039) { + // Mn [6] MYANMAR VOWEL SIGN AI..MYANMAR SIGN DOT BELOW + if (0x1032 <= code && code <= 0x1037) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x103b) { + // Mn [2] MYANMAR SIGN VIRAMA..MYANMAR SIGN ASAT + if (0x1039 <= code && code <= 0x103a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] MYANMAR CONSONANT SIGN MEDIAL YA..MYANMAR CONSONANT SIGN MEDIAL RA + if (0x103b <= code && code <= 0x103c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1058) { + if (code < 0x1056) { + // Mn [2] MYANMAR CONSONANT SIGN MEDIAL WA..MYANMAR CONSONANT SIGN MEDIAL HA + if (0x103d <= code && code <= 0x103e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] MYANMAR VOWEL SIGN VOCALIC R..MYANMAR VOWEL SIGN VOCALIC RR + if (0x1056 <= code && code <= 0x1057) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x105e) { + // Mn [2] MYANMAR VOWEL SIGN VOCALIC L..MYANMAR VOWEL SIGN VOCALIC LL + if (0x1058 <= code && code <= 0x1059) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1071) { + // Mn [3] MYANMAR CONSONANT SIGN MON MEDIAL NA..MYANMAR CONSONANT SIGN MON MEDIAL LA + if (0x105e <= code && code <= 0x1060) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [4] MYANMAR VOWEL SIGN GEBA KAREN I..MYANMAR VOWEL SIGN KAYAH EE + if (0x1071 <= code && code <= 0x1074) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x1100) { + if (code < 0x1085) { + // Mn MYANMAR CONSONANT SIGN SHAN MEDIAL WA + if (0x1082 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc MYANMAR VOWEL SIGN SHAN E + if (0x1084 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x108d) { + // Mn [2] MYANMAR VOWEL SIGN SHAN E ABOVE..MYANMAR VOWEL SIGN SHAN FINAL Y + if (0x1085 <= code && code <= 0x1086) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn MYANMAR SIGN SHAN COUNCIL EMPHATIC TONE + if (0x108d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn MYANMAR VOWEL SIGN AITON AI + if (0x109d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x135d) { + if (code < 0x1160) { + // Lo [96] HANGUL CHOSEONG KIYEOK..HANGUL CHOSEONG FILLER + if (0x1100 <= code && code <= 0x115f) { + return boundaries_1.CLUSTER_BREAK.L; + } + } + else { + if (code < 0x11a8) { + // Lo [72] HANGUL JUNGSEONG FILLER..HANGUL JUNGSEONG O-YAE + if (0x1160 <= code && code <= 0x11a7) { + return boundaries_1.CLUSTER_BREAK.V; + } + } + else { + // Lo [88] HANGUL JONGSEONG KIYEOK..HANGUL JONGSEONG SSANGNIEUN + if (0x11a8 <= code && code <= 0x11ff) { + return boundaries_1.CLUSTER_BREAK.T; + } + } + } + } + else { + if (code < 0x1712) { + // Mn [3] ETHIOPIC COMBINING GEMINATION AND VOWEL LENGTH MARK..ETHIOPIC COMBINING GEMINATION MARK + if (0x135d <= code && code <= 0x135f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1715) { + // Mn [3] TAGALOG VOWEL SIGN I..TAGALOG SIGN VIRAMA + if (0x1712 <= code && code <= 0x1714) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc TAGALOG SIGN PAMUDPOD + if (0x1715 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + else { + if (code < 0x17c9) { + if (code < 0x17b6) { + if (code < 0x1752) { + if (code < 0x1734) { + // Mn [2] HANUNOO VOWEL SIGN I..HANUNOO VOWEL SIGN U + if (0x1732 <= code && code <= 0x1733) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc HANUNOO SIGN PAMUDPOD + if (0x1734 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1772) { + // Mn [2] BUHID VOWEL SIGN I..BUHID VOWEL SIGN U + if (0x1752 <= code && code <= 0x1753) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x17b4) { + // Mn [2] TAGBANWA VOWEL SIGN I..TAGBANWA VOWEL SIGN U + if (0x1772 <= code && code <= 0x1773) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA + if (0x17b4 <= code && code <= 0x17b5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x17be) { + if (code < 0x17b7) { + // Mc KHMER VOWEL SIGN AA + if (0x17b6 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [7] KHMER VOWEL SIGN I..KHMER VOWEL SIGN UA + if (0x17b7 <= code && code <= 0x17bd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x17c6) { + // Mc [8] KHMER VOWEL SIGN OE..KHMER VOWEL SIGN AU + if (0x17be <= code && code <= 0x17c5) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x17c7) { + // Mn KHMER SIGN NIKAHIT + if (0x17c6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] KHMER SIGN REAHMUK..KHMER SIGN YUUKALEAPINTU + if (0x17c7 <= code && code <= 0x17c8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0x1885) { + if (code < 0x180b) { + if (code < 0x17dd) { + // Mn [11] KHMER SIGN MUUSIKATOAN..KHMER SIGN BATHAMASAT + if (0x17c9 <= code && code <= 0x17d3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn KHMER SIGN ATTHACAN + if (0x17dd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x180e) { + // Mn [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE + if (0x180b <= code && code <= 0x180d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf MONGOLIAN VOWEL SEPARATOR + if (0x180e === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + // Mn MONGOLIAN FREE VARIATION SELECTOR FOUR + if (0x180f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1923) { + if (code < 0x18a9) { + // Mn [2] MONGOLIAN LETTER ALI GALI BALUDA..MONGOLIAN LETTER ALI GALI THREE BALUDA + if (0x1885 <= code && code <= 0x1886) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1920) { + // Mn MONGOLIAN LETTER ALI GALI DAGALGA + if (0x18a9 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] LIMBU VOWEL SIGN A..LIMBU VOWEL SIGN U + if (0x1920 <= code && code <= 0x1922) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1927) { + // Mc [4] LIMBU VOWEL SIGN EE..LIMBU VOWEL SIGN AU + if (0x1923 <= code && code <= 0x1926) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1929) { + // Mn [2] LIMBU VOWEL SIGN E..LIMBU VOWEL SIGN O + if (0x1927 <= code && code <= 0x1928) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] LIMBU SUBJOINED LETTER YA..LIMBU SUBJOINED LETTER WA + if (0x1929 <= code && code <= 0x192b) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + } + else { + if (code < 0x1b3b) { + if (code < 0x1a58) { + if (code < 0x1a19) { + if (code < 0x1933) { + if (code < 0x1932) { + // Mc [2] LIMBU SMALL LETTER KA..LIMBU SMALL LETTER NGA + if (0x1930 <= code && code <= 0x1931) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn LIMBU SMALL LETTER ANUSVARA + if (0x1932 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1939) { + // Mc [6] LIMBU SMALL LETTER TA..LIMBU SMALL LETTER LA + if (0x1933 <= code && code <= 0x1938) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1a17) { + // Mn [3] LIMBU SIGN MUKPHRENG..LIMBU SIGN SA-I + if (0x1939 <= code && code <= 0x193b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] BUGINESE VOWEL SIGN I..BUGINESE VOWEL SIGN U + if (0x1a17 <= code && code <= 0x1a18) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1a55) { + if (code < 0x1a1b) { + // Mc [2] BUGINESE VOWEL SIGN E..BUGINESE VOWEL SIGN O + if (0x1a19 <= code && code <= 0x1a1a) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BUGINESE VOWEL SIGN AE + if (0x1a1b === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1a56) { + // Mc TAI THAM CONSONANT SIGN MEDIAL RA + if (0x1a55 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn TAI THAM CONSONANT SIGN MEDIAL LA + if (0x1a56 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc TAI THAM CONSONANT SIGN LA TANG LAI + if (0x1a57 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1a73) { + if (code < 0x1a62) { + if (code < 0x1a60) { + // Mn [7] TAI THAM SIGN MAI KANG LAI..TAI THAM CONSONANT SIGN SA + if (0x1a58 <= code && code <= 0x1a5e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn TAI THAM SIGN SAKOT + if (0x1a60 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1a65) { + // Mn TAI THAM VOWEL SIGN MAI SAT + if (0x1a62 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1a6d) { + // Mn [8] TAI THAM VOWEL SIGN I..TAI THAM VOWEL SIGN OA BELOW + if (0x1a65 <= code && code <= 0x1a6c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [6] TAI THAM VOWEL SIGN OY..TAI THAM VOWEL SIGN THAM AI + if (0x1a6d <= code && code <= 0x1a72) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1b00) { + if (code < 0x1a7f) { + // Mn [10] TAI THAM VOWEL SIGN OA ABOVE..TAI THAM SIGN KHUEN-LUE KARAN + if (0x1a73 <= code && code <= 0x1a7c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1ab0) { + // Mn TAI THAM COMBINING CRYPTOGRAMMIC DOT + if (0x1a7f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [14] COMBINING DOUBLED CIRCUMFLEX ACCENT..COMBINING PARENTHESES BELOW + // Me COMBINING PARENTHESES OVERLAY + // Mn [16] COMBINING LATIN SMALL LETTER W BELOW..COMBINING LATIN SMALL LETTER INSULAR T + if (0x1ab0 <= code && code <= 0x1ace) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1b04) { + // Mn [4] BALINESE SIGN ULU RICEM..BALINESE SIGN SURANG + if (0x1b00 <= code && code <= 0x1b03) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1b34) { + // Mc BALINESE SIGN BISAH + if (0x1b04 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BALINESE SIGN REREKAN + // Mc BALINESE VOWEL SIGN TEDUNG + // Mn [5] BALINESE VOWEL SIGN ULU..BALINESE VOWEL SIGN RA REPA + if (0x1b34 <= code && code <= 0x1b3a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0x1ba8) { + if (code < 0x1b6b) { + if (code < 0x1b3d) { + // Mc BALINESE VOWEL SIGN RA REPA TEDUNG + if (0x1b3b === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn BALINESE VOWEL SIGN LA LENGA + if (0x1b3c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1b42) { + // Mc [5] BALINESE VOWEL SIGN LA LENGA TEDUNG..BALINESE VOWEL SIGN TALING REPA TEDUNG + if (0x1b3d <= code && code <= 0x1b41) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1b43) { + // Mn BALINESE VOWEL SIGN PEPET + if (0x1b42 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] BALINESE VOWEL SIGN PEPET TEDUNG..BALINESE ADEG ADEG + if (0x1b43 <= code && code <= 0x1b44) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1ba1) { + if (code < 0x1b80) { + // Mn [9] BALINESE MUSICAL SYMBOL COMBINING TEGEH..BALINESE MUSICAL SYMBOL COMBINING GONG + if (0x1b6b <= code && code <= 0x1b73) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1b82) { + // Mn [2] SUNDANESE SIGN PANYECEK..SUNDANESE SIGN PANGLAYAR + if (0x1b80 <= code && code <= 0x1b81) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc SUNDANESE SIGN PANGWISAD + if (0x1b82 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1ba2) { + // Mc SUNDANESE CONSONANT SIGN PAMINGKAL + if (0x1ba1 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1ba6) { + // Mn [4] SUNDANESE CONSONANT SIGN PANYAKRA..SUNDANESE VOWEL SIGN PANYUKU + if (0x1ba2 <= code && code <= 0x1ba5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SUNDANESE VOWEL SIGN PANAELAENG..SUNDANESE VOWEL SIGN PANOLONG + if (0x1ba6 <= code && code <= 0x1ba7) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0x1be8) { + if (code < 0x1bab) { + if (code < 0x1baa) { + // Mn [2] SUNDANESE VOWEL SIGN PAMEPET..SUNDANESE VOWEL SIGN PANEULEUNG + if (0x1ba8 <= code && code <= 0x1ba9) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc SUNDANESE SIGN PAMAAEH + if (0x1baa === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1be6) { + // Mn [3] SUNDANESE SIGN VIRAMA..SUNDANESE CONSONANT SIGN PASANGAN WA + if (0x1bab <= code && code <= 0x1bad) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn BATAK SIGN TOMPI + if (0x1be6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc BATAK VOWEL SIGN E + if (0x1be7 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1bee) { + if (code < 0x1bea) { + // Mn [2] BATAK VOWEL SIGN PAKPAK E..BATAK VOWEL SIGN EE + if (0x1be8 <= code && code <= 0x1be9) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1bed) { + // Mc [3] BATAK VOWEL SIGN I..BATAK VOWEL SIGN O + if (0x1bea <= code && code <= 0x1bec) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn BATAK VOWEL SIGN KARO O + if (0x1bed === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1bef) { + // Mc BATAK VOWEL SIGN U + if (0x1bee === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1bf2) { + // Mn [3] BATAK VOWEL SIGN U FOR SIMALUNGUN SA..BATAK CONSONANT SIGN H + if (0x1bef <= code && code <= 0x1bf1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] BATAK PANGOLAT..BATAK PANONGONAN + if (0x1bf2 <= code && code <= 0x1bf3) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xa952) { + if (code < 0x2d7f) { + if (code < 0x1cf7) { + if (code < 0x1cd4) { + if (code < 0x1c34) { + if (code < 0x1c2c) { + // Mc [8] LEPCHA SUBJOINED LETTER YA..LEPCHA VOWEL SIGN UU + if (0x1c24 <= code && code <= 0x1c2b) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [8] LEPCHA VOWEL SIGN E..LEPCHA CONSONANT SIGN T + if (0x1c2c <= code && code <= 0x1c33) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1c36) { + // Mc [2] LEPCHA CONSONANT SIGN NYIN-DO..LEPCHA CONSONANT SIGN KANG + if (0x1c34 <= code && code <= 0x1c35) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1cd0) { + // Mn [2] LEPCHA SIGN RAN..LEPCHA SIGN NUKTA + if (0x1c36 <= code && code <= 0x1c37) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] VEDIC TONE KARSHANA..VEDIC TONE PRENKHA + if (0x1cd0 <= code && code <= 0x1cd2) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1ce2) { + if (code < 0x1ce1) { + // Mn [13] VEDIC SIGN YAJURVEDIC MIDLINE SVARITA..VEDIC TONE RIGVEDIC KASHMIRI INDEPENDENT SVARITA + if (0x1cd4 <= code && code <= 0x1ce0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc VEDIC TONE ATHARVAVEDIC INDEPENDENT SVARITA + if (0x1ce1 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1ced) { + // Mn [7] VEDIC SIGN VISARGA SVARITA..VEDIC SIGN VISARGA ANUDATTA WITH TAIL + if (0x1ce2 <= code && code <= 0x1ce8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn VEDIC SIGN TIRYAK + if (0x1ced === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn VEDIC TONE CANDRA ABOVE + if (0x1cf4 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x200d) { + if (code < 0x1dc0) { + if (code < 0x1cf8) { + // Mc VEDIC SIGN ATIKRAMA + if (0x1cf7 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] VEDIC TONE RING ABOVE..VEDIC TONE DOUBLE RING ABOVE + if (0x1cf8 <= code && code <= 0x1cf9) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x200b) { + // Mn [64] COMBINING DOTTED GRAVE ACCENT..COMBINING RIGHT ARROWHEAD AND DOWN ARROWHEAD BELOW + if (0x1dc0 <= code && code <= 0x1dff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cf ZERO WIDTH SPACE + if (0x200b === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + // Cf ZERO WIDTH NON-JOINER + if (0x200c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x2060) { + if (code < 0x200e) { + // Cf ZERO WIDTH JOINER + if (0x200d === code) { + return boundaries_1.CLUSTER_BREAK.ZWJ; + } + } + else { + if (code < 0x2028) { + // Cf [2] LEFT-TO-RIGHT MARK..RIGHT-TO-LEFT MARK + if (0x200e <= code && code <= 0x200f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Zl LINE SEPARATOR + // Zp PARAGRAPH SEPARATOR + // Cf [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE + if (0x2028 <= code && code <= 0x202e) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + } + else { + if (code < 0x20d0) { + // Cf [5] WORD JOINER..INVISIBLE PLUS + // Cn + // Cf [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES + if (0x2060 <= code && code <= 0x206f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0x2cef) { + // Mn [13] COMBINING LEFT HARPOON ABOVE..COMBINING FOUR DOTS ABOVE + // Me [4] COMBINING ENCLOSING CIRCLE..COMBINING ENCLOSING CIRCLE BACKSLASH + // Mn COMBINING LEFT RIGHT ARROW ABOVE + // Me [3] COMBINING ENCLOSING SCREEN..COMBINING ENCLOSING UPWARD POINTING TRIANGLE + // Mn [12] COMBINING REVERSE SOLIDUS OVERLAY..COMBINING ASTERISK ABOVE + if (0x20d0 <= code && code <= 0x20f0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] COPTIC COMBINING NI ABOVE..COPTIC COMBINING SPIRITUS LENIS + if (0x2cef <= code && code <= 0x2cf1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0xa823) { + if (code < 0xa674) { + if (code < 0x302a) { + if (code < 0x2de0) { + // Mn TIFINAGH CONSONANT JOINER + if (0x2d7f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [32] COMBINING CYRILLIC LETTER BE..COMBINING CYRILLIC LETTER IOTIFIED BIG YUS + if (0x2de0 <= code && code <= 0x2dff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x3099) { + // Mn [4] IDEOGRAPHIC LEVEL TONE MARK..IDEOGRAPHIC ENTERING TONE MARK + // Mc [2] HANGUL SINGLE DOT TONE MARK..HANGUL DOUBLE DOT TONE MARK + if (0x302a <= code && code <= 0x302f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa66f) { + // Mn [2] COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK..COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK + if (0x3099 <= code && code <= 0x309a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn COMBINING CYRILLIC VZMET + // Me [3] COMBINING CYRILLIC TEN MILLIONS SIGN..COMBINING CYRILLIC THOUSAND MILLIONS SIGN + if (0xa66f <= code && code <= 0xa672) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xa802) { + if (code < 0xa69e) { + // Mn [10] COMBINING CYRILLIC LETTER UKRAINIAN IE..COMBINING CYRILLIC PAYEROK + if (0xa674 <= code && code <= 0xa67d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa6f0) { + // Mn [2] COMBINING CYRILLIC LETTER EF..COMBINING CYRILLIC LETTER IOTIFIED E + if (0xa69e <= code && code <= 0xa69f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] BAMUM COMBINING MARK KOQNDON..BAMUM COMBINING MARK TUKWENTIS + if (0xa6f0 <= code && code <= 0xa6f1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xa806) { + // Mn SYLOTI NAGRI SIGN DVISVARA + if (0xa802 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn SYLOTI NAGRI SIGN HASANTA + if (0xa806 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn SYLOTI NAGRI SIGN ANUSVARA + if (0xa80b === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0xa8b4) { + if (code < 0xa827) { + if (code < 0xa825) { + // Mc [2] SYLOTI NAGRI VOWEL SIGN A..SYLOTI NAGRI VOWEL SIGN I + if (0xa823 <= code && code <= 0xa824) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] SYLOTI NAGRI VOWEL SIGN U..SYLOTI NAGRI VOWEL SIGN E + if (0xa825 <= code && code <= 0xa826) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xa82c) { + // Mc SYLOTI NAGRI VOWEL SIGN OO + if (0xa827 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xa880) { + // Mn SYLOTI NAGRI SIGN ALTERNATE HASANTA + if (0xa82c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SAURASHTRA SIGN ANUSVARA..SAURASHTRA SIGN VISARGA + if (0xa880 <= code && code <= 0xa881) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xa8ff) { + if (code < 0xa8c4) { + // Mc [16] SAURASHTRA CONSONANT SIGN HAARU..SAURASHTRA VOWEL SIGN AU + if (0xa8b4 <= code && code <= 0xa8c3) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xa8e0) { + // Mn [2] SAURASHTRA SIGN VIRAMA..SAURASHTRA SIGN CANDRABINDU + if (0xa8c4 <= code && code <= 0xa8c5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [18] COMBINING DEVANAGARI DIGIT ZERO..COMBINING DEVANAGARI SIGN AVAGRAHA + if (0xa8e0 <= code && code <= 0xa8f1) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xa926) { + // Mn DEVANAGARI VOWEL SIGN AY + if (0xa8ff === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xa947) { + // Mn [8] KAYAH LI VOWEL UE..KAYAH LI TONE CALYA PLOPHU + if (0xa926 <= code && code <= 0xa92d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [11] REJANG VOWEL SIGN I..REJANG CONSONANT SIGN R + if (0xa947 <= code && code <= 0xa951) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0xaab2) { + if (code < 0xa9e5) { + if (code < 0xa9b4) { + if (code < 0xa980) { + if (code < 0xa960) { + // Mc [2] REJANG CONSONANT SIGN H..REJANG VIRAMA + if (0xa952 <= code && code <= 0xa953) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Lo [29] HANGUL CHOSEONG TIKEUT-MIEUM..HANGUL CHOSEONG SSANGYEORINHIEUH + if (0xa960 <= code && code <= 0xa97c) { + return boundaries_1.CLUSTER_BREAK.L; + } + } + } + else { + if (code < 0xa983) { + // Mn [3] JAVANESE SIGN PANYANGGA..JAVANESE SIGN LAYAR + if (0xa980 <= code && code <= 0xa982) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc JAVANESE SIGN WIGNYAN + if (0xa983 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn JAVANESE SIGN CECAK TELU + if (0xa9b3 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xa9ba) { + if (code < 0xa9b6) { + // Mc [2] JAVANESE VOWEL SIGN TARUNG..JAVANESE VOWEL SIGN TOLONG + if (0xa9b4 <= code && code <= 0xa9b5) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] JAVANESE VOWEL SIGN WULU..JAVANESE VOWEL SIGN SUKU MENDUT + if (0xa9b6 <= code && code <= 0xa9b9) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xa9bc) { + // Mc [2] JAVANESE VOWEL SIGN TALING..JAVANESE VOWEL SIGN DIRGA MURE + if (0xa9ba <= code && code <= 0xa9bb) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xa9be) { + // Mn [2] JAVANESE VOWEL SIGN PEPET..JAVANESE CONSONANT SIGN KERET + if (0xa9bc <= code && code <= 0xa9bd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] JAVANESE CONSONANT SIGN PENGKAL..JAVANESE PANGKON + if (0xa9be <= code && code <= 0xa9c0) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0xaa35) { + if (code < 0xaa2f) { + if (code < 0xaa29) { + // Mn MYANMAR SIGN SHAN SAW + if (0xa9e5 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [6] CHAM VOWEL SIGN AA..CHAM VOWEL SIGN OE + if (0xaa29 <= code && code <= 0xaa2e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xaa31) { + // Mc [2] CHAM VOWEL SIGN O..CHAM VOWEL SIGN AI + if (0xaa2f <= code && code <= 0xaa30) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0xaa33) { + // Mn [2] CHAM VOWEL SIGN AU..CHAM VOWEL SIGN UE + if (0xaa31 <= code && code <= 0xaa32) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] CHAM CONSONANT SIGN YA..CHAM CONSONANT SIGN RA + if (0xaa33 <= code && code <= 0xaa34) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0xaa4d) { + if (code < 0xaa43) { + // Mn [2] CHAM CONSONANT SIGN LA..CHAM CONSONANT SIGN WA + if (0xaa35 <= code && code <= 0xaa36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn CHAM CONSONANT SIGN FINAL NG + if (0xaa43 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn CHAM CONSONANT SIGN FINAL M + if (0xaa4c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xaa7c) { + // Mc CHAM CONSONANT SIGN FINAL H + if (0xaa4d === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MYANMAR SIGN TAI LAING TONE-2 + if (0xaa7c === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn TAI VIET MAI KANG + if (0xaab0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xabe6) { + if (code < 0xaaec) { + if (code < 0xaabe) { + if (code < 0xaab7) { + // Mn [3] TAI VIET VOWEL I..TAI VIET VOWEL U + if (0xaab2 <= code && code <= 0xaab4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] TAI VIET MAI KHIT..TAI VIET VOWEL IA + if (0xaab7 <= code && code <= 0xaab8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xaac1) { + // Mn [2] TAI VIET VOWEL AM..TAI VIET TONE MAI EK + if (0xaabe <= code && code <= 0xaabf) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn TAI VIET TONE MAI THO + if (0xaac1 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc MEETEI MAYEK VOWEL SIGN II + if (0xaaeb === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0xaaf6) { + if (code < 0xaaee) { + // Mn [2] MEETEI MAYEK VOWEL SIGN UU..MEETEI MAYEK VOWEL SIGN AAI + if (0xaaec <= code && code <= 0xaaed) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xaaf5) { + // Mc [2] MEETEI MAYEK VOWEL SIGN AU..MEETEI MAYEK VOWEL SIGN AAU + if (0xaaee <= code && code <= 0xaaef) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc MEETEI MAYEK VOWEL SIGN VISARGA + if (0xaaf5 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0xabe3) { + // Mn MEETEI MAYEK VIRAMA + if (0xaaf6 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xabe5) { + // Mc [2] MEETEI MAYEK VOWEL SIGN ONAP..MEETEI MAYEK VOWEL SIGN INAP + if (0xabe3 <= code && code <= 0xabe4) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MEETEI MAYEK VOWEL SIGN ANAP + if (0xabe5 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0xac00) { + if (code < 0xabe9) { + if (code < 0xabe8) { + // Mc [2] MEETEI MAYEK VOWEL SIGN YENAP..MEETEI MAYEK VOWEL SIGN SOUNAP + if (0xabe6 <= code && code <= 0xabe7) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MEETEI MAYEK VOWEL SIGN UNAP + if (0xabe8 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0xabec) { + // Mc [2] MEETEI MAYEK VOWEL SIGN CHEINAP..MEETEI MAYEK VOWEL SIGN NUNG + if (0xabe9 <= code && code <= 0xabea) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc MEETEI MAYEK LUM IYEK + if (0xabec === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn MEETEI MAYEK APUN IYEK + if (0xabed === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xac1d) { + if (code < 0xac01) { + // Lo HANGUL SYLLABLE GA + if (0xac00 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xac1c) { + // Lo [27] HANGUL SYLLABLE GAG..HANGUL SYLLABLE GAH + if (0xac01 <= code && code <= 0xac1b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GAE + if (0xac1c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xac38) { + // Lo [27] HANGUL SYLLABLE GAEG..HANGUL SYLLABLE GAEH + if (0xac1d <= code && code <= 0xac37) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xac39) { + // Lo HANGUL SYLLABLE GYA + if (0xac38 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GYAG..HANGUL SYLLABLE GYAH + if (0xac39 <= code && code <= 0xac53) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0xb5a1) { + if (code < 0xb0ed) { + if (code < 0xaea0) { + if (code < 0xad6d) { + if (code < 0xace0) { + if (code < 0xac8d) { + if (code < 0xac70) { + if (code < 0xac55) { + // Lo HANGUL SYLLABLE GYAE + if (0xac54 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GYAEG..HANGUL SYLLABLE GYAEH + if (0xac55 <= code && code <= 0xac6f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xac71) { + // Lo HANGUL SYLLABLE GEO + if (0xac70 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xac8c) { + // Lo [27] HANGUL SYLLABLE GEOG..HANGUL SYLLABLE GEOH + if (0xac71 <= code && code <= 0xac8b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GE + if (0xac8c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xaca9) { + if (code < 0xaca8) { + // Lo [27] HANGUL SYLLABLE GEG..HANGUL SYLLABLE GEH + if (0xac8d <= code && code <= 0xaca7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GYEO + if (0xaca8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xacc4) { + // Lo [27] HANGUL SYLLABLE GYEOG..HANGUL SYLLABLE GYEOH + if (0xaca9 <= code && code <= 0xacc3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xacc5) { + // Lo HANGUL SYLLABLE GYE + if (0xacc4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GYEG..HANGUL SYLLABLE GYEH + if (0xacc5 <= code && code <= 0xacdf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xad19) { + if (code < 0xacfc) { + if (code < 0xace1) { + // Lo HANGUL SYLLABLE GO + if (0xace0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GOG..HANGUL SYLLABLE GOH + if (0xace1 <= code && code <= 0xacfb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xacfd) { + // Lo HANGUL SYLLABLE GWA + if (0xacfc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xad18) { + // Lo [27] HANGUL SYLLABLE GWAG..HANGUL SYLLABLE GWAH + if (0xacfd <= code && code <= 0xad17) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GWAE + if (0xad18 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xad50) { + if (code < 0xad34) { + // Lo [27] HANGUL SYLLABLE GWAEG..HANGUL SYLLABLE GWAEH + if (0xad19 <= code && code <= 0xad33) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xad35) { + // Lo HANGUL SYLLABLE GOE + if (0xad34 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GOEG..HANGUL SYLLABLE GOEH + if (0xad35 <= code && code <= 0xad4f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xad51) { + // Lo HANGUL SYLLABLE GYO + if (0xad50 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xad6c) { + // Lo [27] HANGUL SYLLABLE GYOG..HANGUL SYLLABLE GYOH + if (0xad51 <= code && code <= 0xad6b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GU + if (0xad6c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xadf9) { + if (code < 0xadc0) { + if (code < 0xad89) { + if (code < 0xad88) { + // Lo [27] HANGUL SYLLABLE GUG..HANGUL SYLLABLE GUH + if (0xad6d <= code && code <= 0xad87) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GWEO + if (0xad88 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xada4) { + // Lo [27] HANGUL SYLLABLE GWEOG..HANGUL SYLLABLE GWEOH + if (0xad89 <= code && code <= 0xada3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xada5) { + // Lo HANGUL SYLLABLE GWE + if (0xada4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GWEG..HANGUL SYLLABLE GWEH + if (0xada5 <= code && code <= 0xadbf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xaddc) { + if (code < 0xadc1) { + // Lo HANGUL SYLLABLE GWI + if (0xadc0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GWIG..HANGUL SYLLABLE GWIH + if (0xadc1 <= code && code <= 0xaddb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xaddd) { + // Lo HANGUL SYLLABLE GYU + if (0xaddc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xadf8) { + // Lo [27] HANGUL SYLLABLE GYUG..HANGUL SYLLABLE GYUH + if (0xaddd <= code && code <= 0xadf7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GEU + if (0xadf8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xae4c) { + if (code < 0xae15) { + if (code < 0xae14) { + // Lo [27] HANGUL SYLLABLE GEUG..HANGUL SYLLABLE GEUH + if (0xadf9 <= code && code <= 0xae13) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GYI + if (0xae14 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xae30) { + // Lo [27] HANGUL SYLLABLE GYIG..HANGUL SYLLABLE GYIH + if (0xae15 <= code && code <= 0xae2f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xae31) { + // Lo HANGUL SYLLABLE GI + if (0xae30 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GIG..HANGUL SYLLABLE GIH + if (0xae31 <= code && code <= 0xae4b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xae69) { + if (code < 0xae4d) { + // Lo HANGUL SYLLABLE GGA + if (0xae4c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xae68) { + // Lo [27] HANGUL SYLLABLE GGAG..HANGUL SYLLABLE GGAH + if (0xae4d <= code && code <= 0xae67) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGAE + if (0xae68 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xae84) { + // Lo [27] HANGUL SYLLABLE GGAEG..HANGUL SYLLABLE GGAEH + if (0xae69 <= code && code <= 0xae83) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xae85) { + // Lo HANGUL SYLLABLE GGYA + if (0xae84 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGYAG..HANGUL SYLLABLE GGYAH + if (0xae85 <= code && code <= 0xae9f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xafb9) { + if (code < 0xaf2c) { + if (code < 0xaed9) { + if (code < 0xaebc) { + if (code < 0xaea1) { + // Lo HANGUL SYLLABLE GGYAE + if (0xaea0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGYAEG..HANGUL SYLLABLE GGYAEH + if (0xaea1 <= code && code <= 0xaebb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xaebd) { + // Lo HANGUL SYLLABLE GGEO + if (0xaebc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xaed8) { + // Lo [27] HANGUL SYLLABLE GGEOG..HANGUL SYLLABLE GGEOH + if (0xaebd <= code && code <= 0xaed7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGE + if (0xaed8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xaef5) { + if (code < 0xaef4) { + // Lo [27] HANGUL SYLLABLE GGEG..HANGUL SYLLABLE GGEH + if (0xaed9 <= code && code <= 0xaef3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGYEO + if (0xaef4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xaf10) { + // Lo [27] HANGUL SYLLABLE GGYEOG..HANGUL SYLLABLE GGYEOH + if (0xaef5 <= code && code <= 0xaf0f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xaf11) { + // Lo HANGUL SYLLABLE GGYE + if (0xaf10 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGYEG..HANGUL SYLLABLE GGYEH + if (0xaf11 <= code && code <= 0xaf2b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xaf65) { + if (code < 0xaf48) { + if (code < 0xaf2d) { + // Lo HANGUL SYLLABLE GGO + if (0xaf2c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGOG..HANGUL SYLLABLE GGOH + if (0xaf2d <= code && code <= 0xaf47) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xaf49) { + // Lo HANGUL SYLLABLE GGWA + if (0xaf48 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xaf64) { + // Lo [27] HANGUL SYLLABLE GGWAG..HANGUL SYLLABLE GGWAH + if (0xaf49 <= code && code <= 0xaf63) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGWAE + if (0xaf64 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xaf9c) { + if (code < 0xaf80) { + // Lo [27] HANGUL SYLLABLE GGWAEG..HANGUL SYLLABLE GGWAEH + if (0xaf65 <= code && code <= 0xaf7f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xaf81) { + // Lo HANGUL SYLLABLE GGOE + if (0xaf80 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGOEG..HANGUL SYLLABLE GGOEH + if (0xaf81 <= code && code <= 0xaf9b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xaf9d) { + // Lo HANGUL SYLLABLE GGYO + if (0xaf9c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xafb8) { + // Lo [27] HANGUL SYLLABLE GGYOG..HANGUL SYLLABLE GGYOH + if (0xaf9d <= code && code <= 0xafb7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGU + if (0xafb8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xb060) { + if (code < 0xb00c) { + if (code < 0xafd5) { + if (code < 0xafd4) { + // Lo [27] HANGUL SYLLABLE GGUG..HANGUL SYLLABLE GGUH + if (0xafb9 <= code && code <= 0xafd3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGWEO + if (0xafd4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xaff0) { + // Lo [27] HANGUL SYLLABLE GGWEOG..HANGUL SYLLABLE GGWEOH + if (0xafd5 <= code && code <= 0xafef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xaff1) { + // Lo HANGUL SYLLABLE GGWE + if (0xaff0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGWEG..HANGUL SYLLABLE GGWEH + if (0xaff1 <= code && code <= 0xb00b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb029) { + if (code < 0xb00d) { + // Lo HANGUL SYLLABLE GGWI + if (0xb00c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb028) { + // Lo [27] HANGUL SYLLABLE GGWIG..HANGUL SYLLABLE GGWIH + if (0xb00d <= code && code <= 0xb027) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE GGYU + if (0xb028 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb044) { + // Lo [27] HANGUL SYLLABLE GGYUG..HANGUL SYLLABLE GGYUH + if (0xb029 <= code && code <= 0xb043) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb045) { + // Lo HANGUL SYLLABLE GGEU + if (0xb044 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGEUG..HANGUL SYLLABLE GGEUH + if (0xb045 <= code && code <= 0xb05f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xb099) { + if (code < 0xb07c) { + if (code < 0xb061) { + // Lo HANGUL SYLLABLE GGYI + if (0xb060 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE GGYIG..HANGUL SYLLABLE GGYIH + if (0xb061 <= code && code <= 0xb07b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb07d) { + // Lo HANGUL SYLLABLE GGI + if (0xb07c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb098) { + // Lo [27] HANGUL SYLLABLE GGIG..HANGUL SYLLABLE GGIH + if (0xb07d <= code && code <= 0xb097) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NA + if (0xb098 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb0d0) { + if (code < 0xb0b4) { + // Lo [27] HANGUL SYLLABLE NAG..HANGUL SYLLABLE NAH + if (0xb099 <= code && code <= 0xb0b3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb0b5) { + // Lo HANGUL SYLLABLE NAE + if (0xb0b4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NAEG..HANGUL SYLLABLE NAEH + if (0xb0b5 <= code && code <= 0xb0cf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb0d1) { + // Lo HANGUL SYLLABLE NYA + if (0xb0d0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb0ec) { + // Lo [27] HANGUL SYLLABLE NYAG..HANGUL SYLLABLE NYAH + if (0xb0d1 <= code && code <= 0xb0eb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NYAE + if (0xb0ec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xb354) { + if (code < 0xb220) { + if (code < 0xb179) { + if (code < 0xb140) { + if (code < 0xb109) { + if (code < 0xb108) { + // Lo [27] HANGUL SYLLABLE NYAEG..HANGUL SYLLABLE NYAEH + if (0xb0ed <= code && code <= 0xb107) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NEO + if (0xb108 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb124) { + // Lo [27] HANGUL SYLLABLE NEOG..HANGUL SYLLABLE NEOH + if (0xb109 <= code && code <= 0xb123) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb125) { + // Lo HANGUL SYLLABLE NE + if (0xb124 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NEG..HANGUL SYLLABLE NEH + if (0xb125 <= code && code <= 0xb13f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb15c) { + if (code < 0xb141) { + // Lo HANGUL SYLLABLE NYEO + if (0xb140 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NYEOG..HANGUL SYLLABLE NYEOH + if (0xb141 <= code && code <= 0xb15b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb15d) { + // Lo HANGUL SYLLABLE NYE + if (0xb15c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb178) { + // Lo [27] HANGUL SYLLABLE NYEG..HANGUL SYLLABLE NYEH + if (0xb15d <= code && code <= 0xb177) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NO + if (0xb178 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xb1cc) { + if (code < 0xb195) { + if (code < 0xb194) { + // Lo [27] HANGUL SYLLABLE NOG..HANGUL SYLLABLE NOH + if (0xb179 <= code && code <= 0xb193) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NWA + if (0xb194 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb1b0) { + // Lo [27] HANGUL SYLLABLE NWAG..HANGUL SYLLABLE NWAH + if (0xb195 <= code && code <= 0xb1af) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb1b1) { + // Lo HANGUL SYLLABLE NWAE + if (0xb1b0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NWAEG..HANGUL SYLLABLE NWAEH + if (0xb1b1 <= code && code <= 0xb1cb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb1e9) { + if (code < 0xb1cd) { + // Lo HANGUL SYLLABLE NOE + if (0xb1cc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb1e8) { + // Lo [27] HANGUL SYLLABLE NOEG..HANGUL SYLLABLE NOEH + if (0xb1cd <= code && code <= 0xb1e7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NYO + if (0xb1e8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb204) { + // Lo [27] HANGUL SYLLABLE NYOG..HANGUL SYLLABLE NYOH + if (0xb1e9 <= code && code <= 0xb203) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb205) { + // Lo HANGUL SYLLABLE NU + if (0xb204 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NUG..HANGUL SYLLABLE NUH + if (0xb205 <= code && code <= 0xb21f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xb2ad) { + if (code < 0xb259) { + if (code < 0xb23c) { + if (code < 0xb221) { + // Lo HANGUL SYLLABLE NWEO + if (0xb220 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NWEOG..HANGUL SYLLABLE NWEOH + if (0xb221 <= code && code <= 0xb23b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb23d) { + // Lo HANGUL SYLLABLE NWE + if (0xb23c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb258) { + // Lo [27] HANGUL SYLLABLE NWEG..HANGUL SYLLABLE NWEH + if (0xb23d <= code && code <= 0xb257) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NWI + if (0xb258 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb290) { + if (code < 0xb274) { + // Lo [27] HANGUL SYLLABLE NWIG..HANGUL SYLLABLE NWIH + if (0xb259 <= code && code <= 0xb273) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb275) { + // Lo HANGUL SYLLABLE NYU + if (0xb274 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE NYUG..HANGUL SYLLABLE NYUH + if (0xb275 <= code && code <= 0xb28f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb291) { + // Lo HANGUL SYLLABLE NEU + if (0xb290 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb2ac) { + // Lo [27] HANGUL SYLLABLE NEUG..HANGUL SYLLABLE NEUH + if (0xb291 <= code && code <= 0xb2ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NYI + if (0xb2ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xb300) { + if (code < 0xb2c9) { + if (code < 0xb2c8) { + // Lo [27] HANGUL SYLLABLE NYIG..HANGUL SYLLABLE NYIH + if (0xb2ad <= code && code <= 0xb2c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE NI + if (0xb2c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb2e4) { + // Lo [27] HANGUL SYLLABLE NIG..HANGUL SYLLABLE NIH + if (0xb2c9 <= code && code <= 0xb2e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb2e5) { + // Lo HANGUL SYLLABLE DA + if (0xb2e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DAG..HANGUL SYLLABLE DAH + if (0xb2e5 <= code && code <= 0xb2ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb31d) { + if (code < 0xb301) { + // Lo HANGUL SYLLABLE DAE + if (0xb300 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb31c) { + // Lo [27] HANGUL SYLLABLE DAEG..HANGUL SYLLABLE DAEH + if (0xb301 <= code && code <= 0xb31b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DYA + if (0xb31c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb338) { + // Lo [27] HANGUL SYLLABLE DYAG..HANGUL SYLLABLE DYAH + if (0xb31d <= code && code <= 0xb337) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb339) { + // Lo HANGUL SYLLABLE DYAE + if (0xb338 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DYAEG..HANGUL SYLLABLE DYAEH + if (0xb339 <= code && code <= 0xb353) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xb46d) { + if (code < 0xb3e0) { + if (code < 0xb38d) { + if (code < 0xb370) { + if (code < 0xb355) { + // Lo HANGUL SYLLABLE DEO + if (0xb354 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DEOG..HANGUL SYLLABLE DEOH + if (0xb355 <= code && code <= 0xb36f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb371) { + // Lo HANGUL SYLLABLE DE + if (0xb370 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb38c) { + // Lo [27] HANGUL SYLLABLE DEG..HANGUL SYLLABLE DEH + if (0xb371 <= code && code <= 0xb38b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DYEO + if (0xb38c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb3a9) { + if (code < 0xb3a8) { + // Lo [27] HANGUL SYLLABLE DYEOG..HANGUL SYLLABLE DYEOH + if (0xb38d <= code && code <= 0xb3a7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DYE + if (0xb3a8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb3c4) { + // Lo [27] HANGUL SYLLABLE DYEG..HANGUL SYLLABLE DYEH + if (0xb3a9 <= code && code <= 0xb3c3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb3c5) { + // Lo HANGUL SYLLABLE DO + if (0xb3c4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DOG..HANGUL SYLLABLE DOH + if (0xb3c5 <= code && code <= 0xb3df) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xb419) { + if (code < 0xb3fc) { + if (code < 0xb3e1) { + // Lo HANGUL SYLLABLE DWA + if (0xb3e0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DWAG..HANGUL SYLLABLE DWAH + if (0xb3e1 <= code && code <= 0xb3fb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb3fd) { + // Lo HANGUL SYLLABLE DWAE + if (0xb3fc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb418) { + // Lo [27] HANGUL SYLLABLE DWAEG..HANGUL SYLLABLE DWAEH + if (0xb3fd <= code && code <= 0xb417) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DOE + if (0xb418 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb450) { + if (code < 0xb434) { + // Lo [27] HANGUL SYLLABLE DOEG..HANGUL SYLLABLE DOEH + if (0xb419 <= code && code <= 0xb433) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb435) { + // Lo HANGUL SYLLABLE DYO + if (0xb434 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DYOG..HANGUL SYLLABLE DYOH + if (0xb435 <= code && code <= 0xb44f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb451) { + // Lo HANGUL SYLLABLE DU + if (0xb450 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb46c) { + // Lo [27] HANGUL SYLLABLE DUG..HANGUL SYLLABLE DUH + if (0xb451 <= code && code <= 0xb46b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DWEO + if (0xb46c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xb514) { + if (code < 0xb4c0) { + if (code < 0xb489) { + if (code < 0xb488) { + // Lo [27] HANGUL SYLLABLE DWEOG..HANGUL SYLLABLE DWEOH + if (0xb46d <= code && code <= 0xb487) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DWE + if (0xb488 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb4a4) { + // Lo [27] HANGUL SYLLABLE DWEG..HANGUL SYLLABLE DWEH + if (0xb489 <= code && code <= 0xb4a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb4a5) { + // Lo HANGUL SYLLABLE DWI + if (0xb4a4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DWIG..HANGUL SYLLABLE DWIH + if (0xb4a5 <= code && code <= 0xb4bf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb4dd) { + if (code < 0xb4c1) { + // Lo HANGUL SYLLABLE DYU + if (0xb4c0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb4dc) { + // Lo [27] HANGUL SYLLABLE DYUG..HANGUL SYLLABLE DYUH + if (0xb4c1 <= code && code <= 0xb4db) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DEU + if (0xb4dc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb4f8) { + // Lo [27] HANGUL SYLLABLE DEUG..HANGUL SYLLABLE DEUH + if (0xb4dd <= code && code <= 0xb4f7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb4f9) { + // Lo HANGUL SYLLABLE DYI + if (0xb4f8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DYIG..HANGUL SYLLABLE DYIH + if (0xb4f9 <= code && code <= 0xb513) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xb54d) { + if (code < 0xb530) { + if (code < 0xb515) { + // Lo HANGUL SYLLABLE DI + if (0xb514 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DIG..HANGUL SYLLABLE DIH + if (0xb515 <= code && code <= 0xb52f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb531) { + // Lo HANGUL SYLLABLE DDA + if (0xb530 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb54c) { + // Lo [27] HANGUL SYLLABLE DDAG..HANGUL SYLLABLE DDAH + if (0xb531 <= code && code <= 0xb54b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDAE + if (0xb54c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb584) { + if (code < 0xb568) { + // Lo [27] HANGUL SYLLABLE DDAEG..HANGUL SYLLABLE DDAEH + if (0xb54d <= code && code <= 0xb567) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb569) { + // Lo HANGUL SYLLABLE DDYA + if (0xb568 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDYAG..HANGUL SYLLABLE DDYAH + if (0xb569 <= code && code <= 0xb583) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb585) { + // Lo HANGUL SYLLABLE DDYAE + if (0xb584 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb5a0) { + // Lo [27] HANGUL SYLLABLE DDYAEG..HANGUL SYLLABLE DDYAEH + if (0xb585 <= code && code <= 0xb59f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDEO + if (0xb5a0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0xba55) { + if (code < 0xb808) { + if (code < 0xb6d4) { + if (code < 0xb62d) { + if (code < 0xb5f4) { + if (code < 0xb5bd) { + if (code < 0xb5bc) { + // Lo [27] HANGUL SYLLABLE DDEOG..HANGUL SYLLABLE DDEOH + if (0xb5a1 <= code && code <= 0xb5bb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDE + if (0xb5bc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb5d8) { + // Lo [27] HANGUL SYLLABLE DDEG..HANGUL SYLLABLE DDEH + if (0xb5bd <= code && code <= 0xb5d7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb5d9) { + // Lo HANGUL SYLLABLE DDYEO + if (0xb5d8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDYEOG..HANGUL SYLLABLE DDYEOH + if (0xb5d9 <= code && code <= 0xb5f3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb610) { + if (code < 0xb5f5) { + // Lo HANGUL SYLLABLE DDYE + if (0xb5f4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDYEG..HANGUL SYLLABLE DDYEH + if (0xb5f5 <= code && code <= 0xb60f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb611) { + // Lo HANGUL SYLLABLE DDO + if (0xb610 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb62c) { + // Lo [27] HANGUL SYLLABLE DDOG..HANGUL SYLLABLE DDOH + if (0xb611 <= code && code <= 0xb62b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDWA + if (0xb62c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xb680) { + if (code < 0xb649) { + if (code < 0xb648) { + // Lo [27] HANGUL SYLLABLE DDWAG..HANGUL SYLLABLE DDWAH + if (0xb62d <= code && code <= 0xb647) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDWAE + if (0xb648 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb664) { + // Lo [27] HANGUL SYLLABLE DDWAEG..HANGUL SYLLABLE DDWAEH + if (0xb649 <= code && code <= 0xb663) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb665) { + // Lo HANGUL SYLLABLE DDOE + if (0xb664 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDOEG..HANGUL SYLLABLE DDOEH + if (0xb665 <= code && code <= 0xb67f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb69d) { + if (code < 0xb681) { + // Lo HANGUL SYLLABLE DDYO + if (0xb680 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb69c) { + // Lo [27] HANGUL SYLLABLE DDYOG..HANGUL SYLLABLE DDYOH + if (0xb681 <= code && code <= 0xb69b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDU + if (0xb69c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb6b8) { + // Lo [27] HANGUL SYLLABLE DDUG..HANGUL SYLLABLE DDUH + if (0xb69d <= code && code <= 0xb6b7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb6b9) { + // Lo HANGUL SYLLABLE DDWEO + if (0xb6b8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDWEOG..HANGUL SYLLABLE DDWEOH + if (0xb6b9 <= code && code <= 0xb6d3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xb761) { + if (code < 0xb70d) { + if (code < 0xb6f0) { + if (code < 0xb6d5) { + // Lo HANGUL SYLLABLE DDWE + if (0xb6d4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDWEG..HANGUL SYLLABLE DDWEH + if (0xb6d5 <= code && code <= 0xb6ef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb6f1) { + // Lo HANGUL SYLLABLE DDWI + if (0xb6f0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb70c) { + // Lo [27] HANGUL SYLLABLE DDWIG..HANGUL SYLLABLE DDWIH + if (0xb6f1 <= code && code <= 0xb70b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDYU + if (0xb70c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb744) { + if (code < 0xb728) { + // Lo [27] HANGUL SYLLABLE DDYUG..HANGUL SYLLABLE DDYUH + if (0xb70d <= code && code <= 0xb727) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb729) { + // Lo HANGUL SYLLABLE DDEU + if (0xb728 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE DDEUG..HANGUL SYLLABLE DDEUH + if (0xb729 <= code && code <= 0xb743) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb745) { + // Lo HANGUL SYLLABLE DDYI + if (0xb744 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb760) { + // Lo [27] HANGUL SYLLABLE DDYIG..HANGUL SYLLABLE DDYIH + if (0xb745 <= code && code <= 0xb75f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE DDI + if (0xb760 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xb7b4) { + if (code < 0xb77d) { + if (code < 0xb77c) { + // Lo [27] HANGUL SYLLABLE DDIG..HANGUL SYLLABLE DDIH + if (0xb761 <= code && code <= 0xb77b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RA + if (0xb77c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb798) { + // Lo [27] HANGUL SYLLABLE RAG..HANGUL SYLLABLE RAH + if (0xb77d <= code && code <= 0xb797) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb799) { + // Lo HANGUL SYLLABLE RAE + if (0xb798 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RAEG..HANGUL SYLLABLE RAEH + if (0xb799 <= code && code <= 0xb7b3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb7d1) { + if (code < 0xb7b5) { + // Lo HANGUL SYLLABLE RYA + if (0xb7b4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb7d0) { + // Lo [27] HANGUL SYLLABLE RYAG..HANGUL SYLLABLE RYAH + if (0xb7b5 <= code && code <= 0xb7cf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RYAE + if (0xb7d0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb7ec) { + // Lo [27] HANGUL SYLLABLE RYAEG..HANGUL SYLLABLE RYAEH + if (0xb7d1 <= code && code <= 0xb7eb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb7ed) { + // Lo HANGUL SYLLABLE REO + if (0xb7ec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE REOG..HANGUL SYLLABLE REOH + if (0xb7ed <= code && code <= 0xb807) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xb921) { + if (code < 0xb894) { + if (code < 0xb841) { + if (code < 0xb824) { + if (code < 0xb809) { + // Lo HANGUL SYLLABLE RE + if (0xb808 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE REG..HANGUL SYLLABLE REH + if (0xb809 <= code && code <= 0xb823) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb825) { + // Lo HANGUL SYLLABLE RYEO + if (0xb824 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb840) { + // Lo [27] HANGUL SYLLABLE RYEOG..HANGUL SYLLABLE RYEOH + if (0xb825 <= code && code <= 0xb83f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RYE + if (0xb840 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb85d) { + if (code < 0xb85c) { + // Lo [27] HANGUL SYLLABLE RYEG..HANGUL SYLLABLE RYEH + if (0xb841 <= code && code <= 0xb85b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RO + if (0xb85c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb878) { + // Lo [27] HANGUL SYLLABLE ROG..HANGUL SYLLABLE ROH + if (0xb85d <= code && code <= 0xb877) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb879) { + // Lo HANGUL SYLLABLE RWA + if (0xb878 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RWAG..HANGUL SYLLABLE RWAH + if (0xb879 <= code && code <= 0xb893) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xb8cd) { + if (code < 0xb8b0) { + if (code < 0xb895) { + // Lo HANGUL SYLLABLE RWAE + if (0xb894 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RWAEG..HANGUL SYLLABLE RWAEH + if (0xb895 <= code && code <= 0xb8af) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb8b1) { + // Lo HANGUL SYLLABLE ROE + if (0xb8b0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb8cc) { + // Lo [27] HANGUL SYLLABLE ROEG..HANGUL SYLLABLE ROEH + if (0xb8b1 <= code && code <= 0xb8cb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RYO + if (0xb8cc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xb904) { + if (code < 0xb8e8) { + // Lo [27] HANGUL SYLLABLE RYOG..HANGUL SYLLABLE RYOH + if (0xb8cd <= code && code <= 0xb8e7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb8e9) { + // Lo HANGUL SYLLABLE RU + if (0xb8e8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RUG..HANGUL SYLLABLE RUH + if (0xb8e9 <= code && code <= 0xb903) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xb905) { + // Lo HANGUL SYLLABLE RWEO + if (0xb904 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb920) { + // Lo [27] HANGUL SYLLABLE RWEOG..HANGUL SYLLABLE RWEOH + if (0xb905 <= code && code <= 0xb91f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RWE + if (0xb920 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xb9c8) { + if (code < 0xb974) { + if (code < 0xb93d) { + if (code < 0xb93c) { + // Lo [27] HANGUL SYLLABLE RWEG..HANGUL SYLLABLE RWEH + if (0xb921 <= code && code <= 0xb93b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RWI + if (0xb93c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xb958) { + // Lo [27] HANGUL SYLLABLE RWIG..HANGUL SYLLABLE RWIH + if (0xb93d <= code && code <= 0xb957) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb959) { + // Lo HANGUL SYLLABLE RYU + if (0xb958 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RYUG..HANGUL SYLLABLE RYUH + if (0xb959 <= code && code <= 0xb973) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xb991) { + if (code < 0xb975) { + // Lo HANGUL SYLLABLE REU + if (0xb974 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xb990) { + // Lo [27] HANGUL SYLLABLE REUG..HANGUL SYLLABLE REUH + if (0xb975 <= code && code <= 0xb98f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE RYI + if (0xb990 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xb9ac) { + // Lo [27] HANGUL SYLLABLE RYIG..HANGUL SYLLABLE RYIH + if (0xb991 <= code && code <= 0xb9ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xb9ad) { + // Lo HANGUL SYLLABLE RI + if (0xb9ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE RIG..HANGUL SYLLABLE RIH + if (0xb9ad <= code && code <= 0xb9c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xba01) { + if (code < 0xb9e4) { + if (code < 0xb9c9) { + // Lo HANGUL SYLLABLE MA + if (0xb9c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MAG..HANGUL SYLLABLE MAH + if (0xb9c9 <= code && code <= 0xb9e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xb9e5) { + // Lo HANGUL SYLLABLE MAE + if (0xb9e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xba00) { + // Lo [27] HANGUL SYLLABLE MAEG..HANGUL SYLLABLE MAEH + if (0xb9e5 <= code && code <= 0xb9ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MYA + if (0xba00 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xba38) { + if (code < 0xba1c) { + // Lo [27] HANGUL SYLLABLE MYAG..HANGUL SYLLABLE MYAH + if (0xba01 <= code && code <= 0xba1b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xba1d) { + // Lo HANGUL SYLLABLE MYAE + if (0xba1c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MYAEG..HANGUL SYLLABLE MYAEH + if (0xba1d <= code && code <= 0xba37) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xba39) { + // Lo HANGUL SYLLABLE MEO + if (0xba38 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xba54) { + // Lo [27] HANGUL SYLLABLE MEOG..HANGUL SYLLABLE MEOH + if (0xba39 <= code && code <= 0xba53) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE ME + if (0xba54 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xbcbc) { + if (code < 0xbb88) { + if (code < 0xbae1) { + if (code < 0xbaa8) { + if (code < 0xba71) { + if (code < 0xba70) { + // Lo [27] HANGUL SYLLABLE MEG..HANGUL SYLLABLE MEH + if (0xba55 <= code && code <= 0xba6f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MYEO + if (0xba70 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xba8c) { + // Lo [27] HANGUL SYLLABLE MYEOG..HANGUL SYLLABLE MYEOH + if (0xba71 <= code && code <= 0xba8b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xba8d) { + // Lo HANGUL SYLLABLE MYE + if (0xba8c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MYEG..HANGUL SYLLABLE MYEH + if (0xba8d <= code && code <= 0xbaa7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbac4) { + if (code < 0xbaa9) { + // Lo HANGUL SYLLABLE MO + if (0xbaa8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MOG..HANGUL SYLLABLE MOH + if (0xbaa9 <= code && code <= 0xbac3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbac5) { + // Lo HANGUL SYLLABLE MWA + if (0xbac4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbae0) { + // Lo [27] HANGUL SYLLABLE MWAG..HANGUL SYLLABLE MWAH + if (0xbac5 <= code && code <= 0xbadf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MWAE + if (0xbae0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xbb34) { + if (code < 0xbafd) { + if (code < 0xbafc) { + // Lo [27] HANGUL SYLLABLE MWAEG..HANGUL SYLLABLE MWAEH + if (0xbae1 <= code && code <= 0xbafb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MOE + if (0xbafc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbb18) { + // Lo [27] HANGUL SYLLABLE MOEG..HANGUL SYLLABLE MOEH + if (0xbafd <= code && code <= 0xbb17) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbb19) { + // Lo HANGUL SYLLABLE MYO + if (0xbb18 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MYOG..HANGUL SYLLABLE MYOH + if (0xbb19 <= code && code <= 0xbb33) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbb51) { + if (code < 0xbb35) { + // Lo HANGUL SYLLABLE MU + if (0xbb34 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbb50) { + // Lo [27] HANGUL SYLLABLE MUG..HANGUL SYLLABLE MUH + if (0xbb35 <= code && code <= 0xbb4f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MWEO + if (0xbb50 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xbb6c) { + // Lo [27] HANGUL SYLLABLE MWEOG..HANGUL SYLLABLE MWEOH + if (0xbb51 <= code && code <= 0xbb6b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbb6d) { + // Lo HANGUL SYLLABLE MWE + if (0xbb6c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MWEG..HANGUL SYLLABLE MWEH + if (0xbb6d <= code && code <= 0xbb87) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xbc15) { + if (code < 0xbbc1) { + if (code < 0xbba4) { + if (code < 0xbb89) { + // Lo HANGUL SYLLABLE MWI + if (0xbb88 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MWIG..HANGUL SYLLABLE MWIH + if (0xbb89 <= code && code <= 0xbba3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbba5) { + // Lo HANGUL SYLLABLE MYU + if (0xbba4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbbc0) { + // Lo [27] HANGUL SYLLABLE MYUG..HANGUL SYLLABLE MYUH + if (0xbba5 <= code && code <= 0xbbbf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE MEU + if (0xbbc0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xbbf8) { + if (code < 0xbbdc) { + // Lo [27] HANGUL SYLLABLE MEUG..HANGUL SYLLABLE MEUH + if (0xbbc1 <= code && code <= 0xbbdb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbbdd) { + // Lo HANGUL SYLLABLE MYI + if (0xbbdc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE MYIG..HANGUL SYLLABLE MYIH + if (0xbbdd <= code && code <= 0xbbf7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xbbf9) { + // Lo HANGUL SYLLABLE MI + if (0xbbf8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbc14) { + // Lo [27] HANGUL SYLLABLE MIG..HANGUL SYLLABLE MIH + if (0xbbf9 <= code && code <= 0xbc13) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BA + if (0xbc14 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xbc68) { + if (code < 0xbc31) { + if (code < 0xbc30) { + // Lo [27] HANGUL SYLLABLE BAG..HANGUL SYLLABLE BAH + if (0xbc15 <= code && code <= 0xbc2f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BAE + if (0xbc30 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbc4c) { + // Lo [27] HANGUL SYLLABLE BAEG..HANGUL SYLLABLE BAEH + if (0xbc31 <= code && code <= 0xbc4b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbc4d) { + // Lo HANGUL SYLLABLE BYA + if (0xbc4c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BYAG..HANGUL SYLLABLE BYAH + if (0xbc4d <= code && code <= 0xbc67) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbc85) { + if (code < 0xbc69) { + // Lo HANGUL SYLLABLE BYAE + if (0xbc68 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbc84) { + // Lo [27] HANGUL SYLLABLE BYAEG..HANGUL SYLLABLE BYAEH + if (0xbc69 <= code && code <= 0xbc83) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BEO + if (0xbc84 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xbca0) { + // Lo [27] HANGUL SYLLABLE BEOG..HANGUL SYLLABLE BEOH + if (0xbc85 <= code && code <= 0xbc9f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbca1) { + // Lo HANGUL SYLLABLE BE + if (0xbca0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BEG..HANGUL SYLLABLE BEH + if (0xbca1 <= code && code <= 0xbcbb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xbdd5) { + if (code < 0xbd48) { + if (code < 0xbcf5) { + if (code < 0xbcd8) { + if (code < 0xbcbd) { + // Lo HANGUL SYLLABLE BYEO + if (0xbcbc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BYEOG..HANGUL SYLLABLE BYEOH + if (0xbcbd <= code && code <= 0xbcd7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbcd9) { + // Lo HANGUL SYLLABLE BYE + if (0xbcd8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbcf4) { + // Lo [27] HANGUL SYLLABLE BYEG..HANGUL SYLLABLE BYEH + if (0xbcd9 <= code && code <= 0xbcf3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BO + if (0xbcf4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xbd11) { + if (code < 0xbd10) { + // Lo [27] HANGUL SYLLABLE BOG..HANGUL SYLLABLE BOH + if (0xbcf5 <= code && code <= 0xbd0f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BWA + if (0xbd10 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbd2c) { + // Lo [27] HANGUL SYLLABLE BWAG..HANGUL SYLLABLE BWAH + if (0xbd11 <= code && code <= 0xbd2b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbd2d) { + // Lo HANGUL SYLLABLE BWAE + if (0xbd2c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BWAEG..HANGUL SYLLABLE BWAEH + if (0xbd2d <= code && code <= 0xbd47) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xbd81) { + if (code < 0xbd64) { + if (code < 0xbd49) { + // Lo HANGUL SYLLABLE BOE + if (0xbd48 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BOEG..HANGUL SYLLABLE BOEH + if (0xbd49 <= code && code <= 0xbd63) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbd65) { + // Lo HANGUL SYLLABLE BYO + if (0xbd64 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbd80) { + // Lo [27] HANGUL SYLLABLE BYOG..HANGUL SYLLABLE BYOH + if (0xbd65 <= code && code <= 0xbd7f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BU + if (0xbd80 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xbdb8) { + if (code < 0xbd9c) { + // Lo [27] HANGUL SYLLABLE BUG..HANGUL SYLLABLE BUH + if (0xbd81 <= code && code <= 0xbd9b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbd9d) { + // Lo HANGUL SYLLABLE BWEO + if (0xbd9c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BWEOG..HANGUL SYLLABLE BWEOH + if (0xbd9d <= code && code <= 0xbdb7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xbdb9) { + // Lo HANGUL SYLLABLE BWE + if (0xbdb8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbdd4) { + // Lo [27] HANGUL SYLLABLE BWEG..HANGUL SYLLABLE BWEH + if (0xbdb9 <= code && code <= 0xbdd3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BWI + if (0xbdd4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xbe7c) { + if (code < 0xbe28) { + if (code < 0xbdf1) { + if (code < 0xbdf0) { + // Lo [27] HANGUL SYLLABLE BWIG..HANGUL SYLLABLE BWIH + if (0xbdd5 <= code && code <= 0xbdef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BYU + if (0xbdf0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbe0c) { + // Lo [27] HANGUL SYLLABLE BYUG..HANGUL SYLLABLE BYUH + if (0xbdf1 <= code && code <= 0xbe0b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbe0d) { + // Lo HANGUL SYLLABLE BEU + if (0xbe0c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BEUG..HANGUL SYLLABLE BEUH + if (0xbe0d <= code && code <= 0xbe27) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbe45) { + if (code < 0xbe29) { + // Lo HANGUL SYLLABLE BYI + if (0xbe28 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbe44) { + // Lo [27] HANGUL SYLLABLE BYIG..HANGUL SYLLABLE BYIH + if (0xbe29 <= code && code <= 0xbe43) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BI + if (0xbe44 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xbe60) { + // Lo [27] HANGUL SYLLABLE BIG..HANGUL SYLLABLE BIH + if (0xbe45 <= code && code <= 0xbe5f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbe61) { + // Lo HANGUL SYLLABLE BBA + if (0xbe60 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBAG..HANGUL SYLLABLE BBAH + if (0xbe61 <= code && code <= 0xbe7b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xbeb5) { + if (code < 0xbe98) { + if (code < 0xbe7d) { + // Lo HANGUL SYLLABLE BBAE + if (0xbe7c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBAEG..HANGUL SYLLABLE BBAEH + if (0xbe7d <= code && code <= 0xbe97) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbe99) { + // Lo HANGUL SYLLABLE BBYA + if (0xbe98 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbeb4) { + // Lo [27] HANGUL SYLLABLE BBYAG..HANGUL SYLLABLE BBYAH + if (0xbe99 <= code && code <= 0xbeb3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYAE + if (0xbeb4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xbeec) { + if (code < 0xbed0) { + // Lo [27] HANGUL SYLLABLE BBYAEG..HANGUL SYLLABLE BBYAEH + if (0xbeb5 <= code && code <= 0xbecf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbed1) { + // Lo HANGUL SYLLABLE BBEO + if (0xbed0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBEOG..HANGUL SYLLABLE BBEOH + if (0xbed1 <= code && code <= 0xbeeb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xbeed) { + // Lo HANGUL SYLLABLE BBE + if (0xbeec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbf08) { + // Lo [27] HANGUL SYLLABLE BBEG..HANGUL SYLLABLE BBEH + if (0xbeed <= code && code <= 0xbf07) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYEO + if (0xbf08 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0xd1d8) { + if (code < 0xc870) { + if (code < 0xc3bc) { + if (code < 0xc155) { + if (code < 0xc03c) { + if (code < 0xbf95) { + if (code < 0xbf5c) { + if (code < 0xbf25) { + if (code < 0xbf24) { + // Lo [27] HANGUL SYLLABLE BBYEOG..HANGUL SYLLABLE BBYEOH + if (0xbf09 <= code && code <= 0xbf23) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYE + if (0xbf24 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbf40) { + // Lo [27] HANGUL SYLLABLE BBYEG..HANGUL SYLLABLE BBYEH + if (0xbf25 <= code && code <= 0xbf3f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbf41) { + // Lo HANGUL SYLLABLE BBO + if (0xbf40 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBOG..HANGUL SYLLABLE BBOH + if (0xbf41 <= code && code <= 0xbf5b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xbf78) { + if (code < 0xbf5d) { + // Lo HANGUL SYLLABLE BBWA + if (0xbf5c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBWAG..HANGUL SYLLABLE BBWAH + if (0xbf5d <= code && code <= 0xbf77) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xbf79) { + // Lo HANGUL SYLLABLE BBWAE + if (0xbf78 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xbf94) { + // Lo [27] HANGUL SYLLABLE BBWAEG..HANGUL SYLLABLE BBWAEH + if (0xbf79 <= code && code <= 0xbf93) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBOE + if (0xbf94 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xbfe8) { + if (code < 0xbfb1) { + if (code < 0xbfb0) { + // Lo [27] HANGUL SYLLABLE BBOEG..HANGUL SYLLABLE BBOEH + if (0xbf95 <= code && code <= 0xbfaf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYO + if (0xbfb0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xbfcc) { + // Lo [27] HANGUL SYLLABLE BBYOG..HANGUL SYLLABLE BBYOH + if (0xbfb1 <= code && code <= 0xbfcb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xbfcd) { + // Lo HANGUL SYLLABLE BBU + if (0xbfcc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBUG..HANGUL SYLLABLE BBUH + if (0xbfcd <= code && code <= 0xbfe7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc005) { + if (code < 0xbfe9) { + // Lo HANGUL SYLLABLE BBWEO + if (0xbfe8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc004) { + // Lo [27] HANGUL SYLLABLE BBWEOG..HANGUL SYLLABLE BBWEOH + if (0xbfe9 <= code && code <= 0xc003) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBWE + if (0xc004 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc020) { + // Lo [27] HANGUL SYLLABLE BBWEG..HANGUL SYLLABLE BBWEH + if (0xc005 <= code && code <= 0xc01f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc021) { + // Lo HANGUL SYLLABLE BBWI + if (0xc020 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBWIG..HANGUL SYLLABLE BBWIH + if (0xc021 <= code && code <= 0xc03b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xc0c8) { + if (code < 0xc075) { + if (code < 0xc058) { + if (code < 0xc03d) { + // Lo HANGUL SYLLABLE BBYU + if (0xc03c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE BBYUG..HANGUL SYLLABLE BBYUH + if (0xc03d <= code && code <= 0xc057) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc059) { + // Lo HANGUL SYLLABLE BBEU + if (0xc058 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc074) { + // Lo [27] HANGUL SYLLABLE BBEUG..HANGUL SYLLABLE BBEUH + if (0xc059 <= code && code <= 0xc073) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBYI + if (0xc074 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc091) { + if (code < 0xc090) { + // Lo [27] HANGUL SYLLABLE BBYIG..HANGUL SYLLABLE BBYIH + if (0xc075 <= code && code <= 0xc08f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE BBI + if (0xc090 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc0ac) { + // Lo [27] HANGUL SYLLABLE BBIG..HANGUL SYLLABLE BBIH + if (0xc091 <= code && code <= 0xc0ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc0ad) { + // Lo HANGUL SYLLABLE SA + if (0xc0ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SAG..HANGUL SYLLABLE SAH + if (0xc0ad <= code && code <= 0xc0c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xc101) { + if (code < 0xc0e4) { + if (code < 0xc0c9) { + // Lo HANGUL SYLLABLE SAE + if (0xc0c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SAEG..HANGUL SYLLABLE SAEH + if (0xc0c9 <= code && code <= 0xc0e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc0e5) { + // Lo HANGUL SYLLABLE SYA + if (0xc0e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc100) { + // Lo [27] HANGUL SYLLABLE SYAG..HANGUL SYLLABLE SYAH + if (0xc0e5 <= code && code <= 0xc0ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYAE + if (0xc100 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc138) { + if (code < 0xc11c) { + // Lo [27] HANGUL SYLLABLE SYAEG..HANGUL SYLLABLE SYAEH + if (0xc101 <= code && code <= 0xc11b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc11d) { + // Lo HANGUL SYLLABLE SEO + if (0xc11c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SEOG..HANGUL SYLLABLE SEOH + if (0xc11d <= code && code <= 0xc137) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc139) { + // Lo HANGUL SYLLABLE SE + if (0xc138 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc154) { + // Lo [27] HANGUL SYLLABLE SEG..HANGUL SYLLABLE SEH + if (0xc139 <= code && code <= 0xc153) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYEO + if (0xc154 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + else { + if (code < 0xc288) { + if (code < 0xc1e1) { + if (code < 0xc1a8) { + if (code < 0xc171) { + if (code < 0xc170) { + // Lo [27] HANGUL SYLLABLE SYEOG..HANGUL SYLLABLE SYEOH + if (0xc155 <= code && code <= 0xc16f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYE + if (0xc170 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc18c) { + // Lo [27] HANGUL SYLLABLE SYEG..HANGUL SYLLABLE SYEH + if (0xc171 <= code && code <= 0xc18b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc18d) { + // Lo HANGUL SYLLABLE SO + if (0xc18c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SOG..HANGUL SYLLABLE SOH + if (0xc18d <= code && code <= 0xc1a7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc1c4) { + if (code < 0xc1a9) { + // Lo HANGUL SYLLABLE SWA + if (0xc1a8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SWAG..HANGUL SYLLABLE SWAH + if (0xc1a9 <= code && code <= 0xc1c3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc1c5) { + // Lo HANGUL SYLLABLE SWAE + if (0xc1c4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc1e0) { + // Lo [27] HANGUL SYLLABLE SWAEG..HANGUL SYLLABLE SWAEH + if (0xc1c5 <= code && code <= 0xc1df) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SOE + if (0xc1e0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xc234) { + if (code < 0xc1fd) { + if (code < 0xc1fc) { + // Lo [27] HANGUL SYLLABLE SOEG..HANGUL SYLLABLE SOEH + if (0xc1e1 <= code && code <= 0xc1fb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYO + if (0xc1fc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc218) { + // Lo [27] HANGUL SYLLABLE SYOG..HANGUL SYLLABLE SYOH + if (0xc1fd <= code && code <= 0xc217) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc219) { + // Lo HANGUL SYLLABLE SU + if (0xc218 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SUG..HANGUL SYLLABLE SUH + if (0xc219 <= code && code <= 0xc233) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc251) { + if (code < 0xc235) { + // Lo HANGUL SYLLABLE SWEO + if (0xc234 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc250) { + // Lo [27] HANGUL SYLLABLE SWEOG..HANGUL SYLLABLE SWEOH + if (0xc235 <= code && code <= 0xc24f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SWE + if (0xc250 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc26c) { + // Lo [27] HANGUL SYLLABLE SWEG..HANGUL SYLLABLE SWEH + if (0xc251 <= code && code <= 0xc26b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc26d) { + // Lo HANGUL SYLLABLE SWI + if (0xc26c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SWIG..HANGUL SYLLABLE SWIH + if (0xc26d <= code && code <= 0xc287) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xc315) { + if (code < 0xc2c1) { + if (code < 0xc2a4) { + if (code < 0xc289) { + // Lo HANGUL SYLLABLE SYU + if (0xc288 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SYUG..HANGUL SYLLABLE SYUH + if (0xc289 <= code && code <= 0xc2a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc2a5) { + // Lo HANGUL SYLLABLE SEU + if (0xc2a4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc2c0) { + // Lo [27] HANGUL SYLLABLE SEUG..HANGUL SYLLABLE SEUH + if (0xc2a5 <= code && code <= 0xc2bf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SYI + if (0xc2c0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc2f8) { + if (code < 0xc2dc) { + // Lo [27] HANGUL SYLLABLE SYIG..HANGUL SYLLABLE SYIH + if (0xc2c1 <= code && code <= 0xc2db) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc2dd) { + // Lo HANGUL SYLLABLE SI + if (0xc2dc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SIG..HANGUL SYLLABLE SIH + if (0xc2dd <= code && code <= 0xc2f7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc2f9) { + // Lo HANGUL SYLLABLE SSA + if (0xc2f8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc314) { + // Lo [27] HANGUL SYLLABLE SSAG..HANGUL SYLLABLE SSAH + if (0xc2f9 <= code && code <= 0xc313) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSAE + if (0xc314 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xc368) { + if (code < 0xc331) { + if (code < 0xc330) { + // Lo [27] HANGUL SYLLABLE SSAEG..HANGUL SYLLABLE SSAEH + if (0xc315 <= code && code <= 0xc32f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSYA + if (0xc330 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc34c) { + // Lo [27] HANGUL SYLLABLE SSYAG..HANGUL SYLLABLE SSYAH + if (0xc331 <= code && code <= 0xc34b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc34d) { + // Lo HANGUL SYLLABLE SSYAE + if (0xc34c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYAEG..HANGUL SYLLABLE SSYAEH + if (0xc34d <= code && code <= 0xc367) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc385) { + if (code < 0xc369) { + // Lo HANGUL SYLLABLE SSEO + if (0xc368 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc384) { + // Lo [27] HANGUL SYLLABLE SSEOG..HANGUL SYLLABLE SSEOH + if (0xc369 <= code && code <= 0xc383) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSE + if (0xc384 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc3a0) { + // Lo [27] HANGUL SYLLABLE SSEG..HANGUL SYLLABLE SSEH + if (0xc385 <= code && code <= 0xc39f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc3a1) { + // Lo HANGUL SYLLABLE SSYEO + if (0xc3a0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYEOG..HANGUL SYLLABLE SSYEOH + if (0xc3a1 <= code && code <= 0xc3bb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xc609) { + if (code < 0xc4d5) { + if (code < 0xc448) { + if (code < 0xc3f5) { + if (code < 0xc3d8) { + if (code < 0xc3bd) { + // Lo HANGUL SYLLABLE SSYE + if (0xc3bc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYEG..HANGUL SYLLABLE SSYEH + if (0xc3bd <= code && code <= 0xc3d7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc3d9) { + // Lo HANGUL SYLLABLE SSO + if (0xc3d8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc3f4) { + // Lo [27] HANGUL SYLLABLE SSOG..HANGUL SYLLABLE SSOH + if (0xc3d9 <= code && code <= 0xc3f3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSWA + if (0xc3f4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc411) { + if (code < 0xc410) { + // Lo [27] HANGUL SYLLABLE SSWAG..HANGUL SYLLABLE SSWAH + if (0xc3f5 <= code && code <= 0xc40f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSWAE + if (0xc410 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc42c) { + // Lo [27] HANGUL SYLLABLE SSWAEG..HANGUL SYLLABLE SSWAEH + if (0xc411 <= code && code <= 0xc42b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc42d) { + // Lo HANGUL SYLLABLE SSOE + if (0xc42c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSOEG..HANGUL SYLLABLE SSOEH + if (0xc42d <= code && code <= 0xc447) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xc481) { + if (code < 0xc464) { + if (code < 0xc449) { + // Lo HANGUL SYLLABLE SSYO + if (0xc448 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYOG..HANGUL SYLLABLE SSYOH + if (0xc449 <= code && code <= 0xc463) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc465) { + // Lo HANGUL SYLLABLE SSU + if (0xc464 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc480) { + // Lo [27] HANGUL SYLLABLE SSUG..HANGUL SYLLABLE SSUH + if (0xc465 <= code && code <= 0xc47f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSWEO + if (0xc480 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc4b8) { + if (code < 0xc49c) { + // Lo [27] HANGUL SYLLABLE SSWEOG..HANGUL SYLLABLE SSWEOH + if (0xc481 <= code && code <= 0xc49b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc49d) { + // Lo HANGUL SYLLABLE SSWE + if (0xc49c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSWEG..HANGUL SYLLABLE SSWEH + if (0xc49d <= code && code <= 0xc4b7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc4b9) { + // Lo HANGUL SYLLABLE SSWI + if (0xc4b8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc4d4) { + // Lo [27] HANGUL SYLLABLE SSWIG..HANGUL SYLLABLE SSWIH + if (0xc4b9 <= code && code <= 0xc4d3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSYU + if (0xc4d4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xc57c) { + if (code < 0xc528) { + if (code < 0xc4f1) { + if (code < 0xc4f0) { + // Lo [27] HANGUL SYLLABLE SSYUG..HANGUL SYLLABLE SSYUH + if (0xc4d5 <= code && code <= 0xc4ef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE SSEU + if (0xc4f0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc50c) { + // Lo [27] HANGUL SYLLABLE SSEUG..HANGUL SYLLABLE SSEUH + if (0xc4f1 <= code && code <= 0xc50b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc50d) { + // Lo HANGUL SYLLABLE SSYI + if (0xc50c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE SSYIG..HANGUL SYLLABLE SSYIH + if (0xc50d <= code && code <= 0xc527) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc545) { + if (code < 0xc529) { + // Lo HANGUL SYLLABLE SSI + if (0xc528 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc544) { + // Lo [27] HANGUL SYLLABLE SSIG..HANGUL SYLLABLE SSIH + if (0xc529 <= code && code <= 0xc543) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE A + if (0xc544 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc560) { + // Lo [27] HANGUL SYLLABLE AG..HANGUL SYLLABLE AH + if (0xc545 <= code && code <= 0xc55f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc561) { + // Lo HANGUL SYLLABLE AE + if (0xc560 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE AEG..HANGUL SYLLABLE AEH + if (0xc561 <= code && code <= 0xc57b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xc5b5) { + if (code < 0xc598) { + if (code < 0xc57d) { + // Lo HANGUL SYLLABLE YA + if (0xc57c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE YAG..HANGUL SYLLABLE YAH + if (0xc57d <= code && code <= 0xc597) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc599) { + // Lo HANGUL SYLLABLE YAE + if (0xc598 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc5b4) { + // Lo [27] HANGUL SYLLABLE YAEG..HANGUL SYLLABLE YAEH + if (0xc599 <= code && code <= 0xc5b3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE EO + if (0xc5b4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc5ec) { + if (code < 0xc5d0) { + // Lo [27] HANGUL SYLLABLE EOG..HANGUL SYLLABLE EOH + if (0xc5b5 <= code && code <= 0xc5cf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc5d1) { + // Lo HANGUL SYLLABLE E + if (0xc5d0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE EG..HANGUL SYLLABLE EH + if (0xc5d1 <= code && code <= 0xc5eb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc5ed) { + // Lo HANGUL SYLLABLE YEO + if (0xc5ec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc608) { + // Lo [27] HANGUL SYLLABLE YEOG..HANGUL SYLLABLE YEOH + if (0xc5ed <= code && code <= 0xc607) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE YE + if (0xc608 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + else { + if (code < 0xc73c) { + if (code < 0xc695) { + if (code < 0xc65c) { + if (code < 0xc625) { + if (code < 0xc624) { + // Lo [27] HANGUL SYLLABLE YEG..HANGUL SYLLABLE YEH + if (0xc609 <= code && code <= 0xc623) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE O + if (0xc624 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc640) { + // Lo [27] HANGUL SYLLABLE OG..HANGUL SYLLABLE OH + if (0xc625 <= code && code <= 0xc63f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc641) { + // Lo HANGUL SYLLABLE WA + if (0xc640 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE WAG..HANGUL SYLLABLE WAH + if (0xc641 <= code && code <= 0xc65b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc678) { + if (code < 0xc65d) { + // Lo HANGUL SYLLABLE WAE + if (0xc65c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE WAEG..HANGUL SYLLABLE WAEH + if (0xc65d <= code && code <= 0xc677) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc679) { + // Lo HANGUL SYLLABLE OE + if (0xc678 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc694) { + // Lo [27] HANGUL SYLLABLE OEG..HANGUL SYLLABLE OEH + if (0xc679 <= code && code <= 0xc693) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE YO + if (0xc694 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xc6e8) { + if (code < 0xc6b1) { + if (code < 0xc6b0) { + // Lo [27] HANGUL SYLLABLE YOG..HANGUL SYLLABLE YOH + if (0xc695 <= code && code <= 0xc6af) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE U + if (0xc6b0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc6cc) { + // Lo [27] HANGUL SYLLABLE UG..HANGUL SYLLABLE UH + if (0xc6b1 <= code && code <= 0xc6cb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc6cd) { + // Lo HANGUL SYLLABLE WEO + if (0xc6cc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE WEOG..HANGUL SYLLABLE WEOH + if (0xc6cd <= code && code <= 0xc6e7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc705) { + if (code < 0xc6e9) { + // Lo HANGUL SYLLABLE WE + if (0xc6e8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc704) { + // Lo [27] HANGUL SYLLABLE WEG..HANGUL SYLLABLE WEH + if (0xc6e9 <= code && code <= 0xc703) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE WI + if (0xc704 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc720) { + // Lo [27] HANGUL SYLLABLE WIG..HANGUL SYLLABLE WIH + if (0xc705 <= code && code <= 0xc71f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc721) { + // Lo HANGUL SYLLABLE YU + if (0xc720 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE YUG..HANGUL SYLLABLE YUH + if (0xc721 <= code && code <= 0xc73b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xc7c9) { + if (code < 0xc775) { + if (code < 0xc758) { + if (code < 0xc73d) { + // Lo HANGUL SYLLABLE EU + if (0xc73c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE EUG..HANGUL SYLLABLE EUH + if (0xc73d <= code && code <= 0xc757) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc759) { + // Lo HANGUL SYLLABLE YI + if (0xc758 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc774) { + // Lo [27] HANGUL SYLLABLE YIG..HANGUL SYLLABLE YIH + if (0xc759 <= code && code <= 0xc773) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE I + if (0xc774 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc7ac) { + if (code < 0xc790) { + // Lo [27] HANGUL SYLLABLE IG..HANGUL SYLLABLE IH + if (0xc775 <= code && code <= 0xc78f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc791) { + // Lo HANGUL SYLLABLE JA + if (0xc790 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JAG..HANGUL SYLLABLE JAH + if (0xc791 <= code && code <= 0xc7ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc7ad) { + // Lo HANGUL SYLLABLE JAE + if (0xc7ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc7c8) { + // Lo [27] HANGUL SYLLABLE JAEG..HANGUL SYLLABLE JAEH + if (0xc7ad <= code && code <= 0xc7c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JYA + if (0xc7c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xc81c) { + if (code < 0xc7e5) { + if (code < 0xc7e4) { + // Lo [27] HANGUL SYLLABLE JYAG..HANGUL SYLLABLE JYAH + if (0xc7c9 <= code && code <= 0xc7e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JYAE + if (0xc7e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc800) { + // Lo [27] HANGUL SYLLABLE JYAEG..HANGUL SYLLABLE JYAEH + if (0xc7e5 <= code && code <= 0xc7ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc801) { + // Lo HANGUL SYLLABLE JEO + if (0xc800 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JEOG..HANGUL SYLLABLE JEOH + if (0xc801 <= code && code <= 0xc81b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc839) { + if (code < 0xc81d) { + // Lo HANGUL SYLLABLE JE + if (0xc81c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc838) { + // Lo [27] HANGUL SYLLABLE JEG..HANGUL SYLLABLE JEH + if (0xc81d <= code && code <= 0xc837) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JYEO + if (0xc838 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xc854) { + // Lo [27] HANGUL SYLLABLE JYEOG..HANGUL SYLLABLE JYEOH + if (0xc839 <= code && code <= 0xc853) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc855) { + // Lo HANGUL SYLLABLE JYE + if (0xc854 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JYEG..HANGUL SYLLABLE JYEH + if (0xc855 <= code && code <= 0xc86f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0xcd24) { + if (code < 0xcabd) { + if (code < 0xc989) { + if (code < 0xc8fc) { + if (code < 0xc8a9) { + if (code < 0xc88c) { + if (code < 0xc871) { + // Lo HANGUL SYLLABLE JO + if (0xc870 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JOG..HANGUL SYLLABLE JOH + if (0xc871 <= code && code <= 0xc88b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc88d) { + // Lo HANGUL SYLLABLE JWA + if (0xc88c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc8a8) { + // Lo [27] HANGUL SYLLABLE JWAG..HANGUL SYLLABLE JWAH + if (0xc88d <= code && code <= 0xc8a7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JWAE + if (0xc8a8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc8c5) { + if (code < 0xc8c4) { + // Lo [27] HANGUL SYLLABLE JWAEG..HANGUL SYLLABLE JWAEH + if (0xc8a9 <= code && code <= 0xc8c3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JOE + if (0xc8c4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc8e0) { + // Lo [27] HANGUL SYLLABLE JOEG..HANGUL SYLLABLE JOEH + if (0xc8c5 <= code && code <= 0xc8df) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc8e1) { + // Lo HANGUL SYLLABLE JYO + if (0xc8e0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JYOG..HANGUL SYLLABLE JYOH + if (0xc8e1 <= code && code <= 0xc8fb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xc935) { + if (code < 0xc918) { + if (code < 0xc8fd) { + // Lo HANGUL SYLLABLE JU + if (0xc8fc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JUG..HANGUL SYLLABLE JUH + if (0xc8fd <= code && code <= 0xc917) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xc919) { + // Lo HANGUL SYLLABLE JWEO + if (0xc918 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc934) { + // Lo [27] HANGUL SYLLABLE JWEOG..HANGUL SYLLABLE JWEOH + if (0xc919 <= code && code <= 0xc933) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JWE + if (0xc934 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xc96c) { + if (code < 0xc950) { + // Lo [27] HANGUL SYLLABLE JWEG..HANGUL SYLLABLE JWEH + if (0xc935 <= code && code <= 0xc94f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc951) { + // Lo HANGUL SYLLABLE JWI + if (0xc950 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JWIG..HANGUL SYLLABLE JWIH + if (0xc951 <= code && code <= 0xc96b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xc96d) { + // Lo HANGUL SYLLABLE JYU + if (0xc96c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc988) { + // Lo [27] HANGUL SYLLABLE JYUG..HANGUL SYLLABLE JYUH + if (0xc96d <= code && code <= 0xc987) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JEU + if (0xc988 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xca30) { + if (code < 0xc9dc) { + if (code < 0xc9a5) { + if (code < 0xc9a4) { + // Lo [27] HANGUL SYLLABLE JEUG..HANGUL SYLLABLE JEUH + if (0xc989 <= code && code <= 0xc9a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JYI + if (0xc9a4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xc9c0) { + // Lo [27] HANGUL SYLLABLE JYIG..HANGUL SYLLABLE JYIH + if (0xc9a5 <= code && code <= 0xc9bf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xc9c1) { + // Lo HANGUL SYLLABLE JI + if (0xc9c0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JIG..HANGUL SYLLABLE JIH + if (0xc9c1 <= code && code <= 0xc9db) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xc9f9) { + if (code < 0xc9dd) { + // Lo HANGUL SYLLABLE JJA + if (0xc9dc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xc9f8) { + // Lo [27] HANGUL SYLLABLE JJAG..HANGUL SYLLABLE JJAH + if (0xc9dd <= code && code <= 0xc9f7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJAE + if (0xc9f8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xca14) { + // Lo [27] HANGUL SYLLABLE JJAEG..HANGUL SYLLABLE JJAEH + if (0xc9f9 <= code && code <= 0xca13) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xca15) { + // Lo HANGUL SYLLABLE JJYA + if (0xca14 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJYAG..HANGUL SYLLABLE JJYAH + if (0xca15 <= code && code <= 0xca2f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xca69) { + if (code < 0xca4c) { + if (code < 0xca31) { + // Lo HANGUL SYLLABLE JJYAE + if (0xca30 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJYAEG..HANGUL SYLLABLE JJYAEH + if (0xca31 <= code && code <= 0xca4b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xca4d) { + // Lo HANGUL SYLLABLE JJEO + if (0xca4c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xca68) { + // Lo [27] HANGUL SYLLABLE JJEOG..HANGUL SYLLABLE JJEOH + if (0xca4d <= code && code <= 0xca67) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJE + if (0xca68 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xcaa0) { + if (code < 0xca84) { + // Lo [27] HANGUL SYLLABLE JJEG..HANGUL SYLLABLE JJEH + if (0xca69 <= code && code <= 0xca83) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xca85) { + // Lo HANGUL SYLLABLE JJYEO + if (0xca84 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJYEOG..HANGUL SYLLABLE JJYEOH + if (0xca85 <= code && code <= 0xca9f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xcaa1) { + // Lo HANGUL SYLLABLE JJYE + if (0xcaa0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcabc) { + // Lo [27] HANGUL SYLLABLE JJYEG..HANGUL SYLLABLE JJYEH + if (0xcaa1 <= code && code <= 0xcabb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJO + if (0xcabc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + else { + if (code < 0xcbf0) { + if (code < 0xcb49) { + if (code < 0xcb10) { + if (code < 0xcad9) { + if (code < 0xcad8) { + // Lo [27] HANGUL SYLLABLE JJOG..HANGUL SYLLABLE JJOH + if (0xcabd <= code && code <= 0xcad7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJWA + if (0xcad8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xcaf4) { + // Lo [27] HANGUL SYLLABLE JJWAG..HANGUL SYLLABLE JJWAH + if (0xcad9 <= code && code <= 0xcaf3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcaf5) { + // Lo HANGUL SYLLABLE JJWAE + if (0xcaf4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJWAEG..HANGUL SYLLABLE JJWAEH + if (0xcaf5 <= code && code <= 0xcb0f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcb2c) { + if (code < 0xcb11) { + // Lo HANGUL SYLLABLE JJOE + if (0xcb10 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJOEG..HANGUL SYLLABLE JJOEH + if (0xcb11 <= code && code <= 0xcb2b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcb2d) { + // Lo HANGUL SYLLABLE JJYO + if (0xcb2c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcb48) { + // Lo [27] HANGUL SYLLABLE JJYOG..HANGUL SYLLABLE JJYOH + if (0xcb2d <= code && code <= 0xcb47) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJU + if (0xcb48 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xcb9c) { + if (code < 0xcb65) { + if (code < 0xcb64) { + // Lo [27] HANGUL SYLLABLE JJUG..HANGUL SYLLABLE JJUH + if (0xcb49 <= code && code <= 0xcb63) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJWEO + if (0xcb64 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xcb80) { + // Lo [27] HANGUL SYLLABLE JJWEOG..HANGUL SYLLABLE JJWEOH + if (0xcb65 <= code && code <= 0xcb7f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcb81) { + // Lo HANGUL SYLLABLE JJWE + if (0xcb80 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJWEG..HANGUL SYLLABLE JJWEH + if (0xcb81 <= code && code <= 0xcb9b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcbb9) { + if (code < 0xcb9d) { + // Lo HANGUL SYLLABLE JJWI + if (0xcb9c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcbb8) { + // Lo [27] HANGUL SYLLABLE JJWIG..HANGUL SYLLABLE JJWIH + if (0xcb9d <= code && code <= 0xcbb7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE JJYU + if (0xcbb8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xcbd4) { + // Lo [27] HANGUL SYLLABLE JJYUG..HANGUL SYLLABLE JJYUH + if (0xcbb9 <= code && code <= 0xcbd3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcbd5) { + // Lo HANGUL SYLLABLE JJEU + if (0xcbd4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJEUG..HANGUL SYLLABLE JJEUH + if (0xcbd5 <= code && code <= 0xcbef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xcc7d) { + if (code < 0xcc29) { + if (code < 0xcc0c) { + if (code < 0xcbf1) { + // Lo HANGUL SYLLABLE JJYI + if (0xcbf0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE JJYIG..HANGUL SYLLABLE JJYIH + if (0xcbf1 <= code && code <= 0xcc0b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcc0d) { + // Lo HANGUL SYLLABLE JJI + if (0xcc0c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcc28) { + // Lo [27] HANGUL SYLLABLE JJIG..HANGUL SYLLABLE JJIH + if (0xcc0d <= code && code <= 0xcc27) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CA + if (0xcc28 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xcc60) { + if (code < 0xcc44) { + // Lo [27] HANGUL SYLLABLE CAG..HANGUL SYLLABLE CAH + if (0xcc29 <= code && code <= 0xcc43) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcc45) { + // Lo HANGUL SYLLABLE CAE + if (0xcc44 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CAEG..HANGUL SYLLABLE CAEH + if (0xcc45 <= code && code <= 0xcc5f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xcc61) { + // Lo HANGUL SYLLABLE CYA + if (0xcc60 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcc7c) { + // Lo [27] HANGUL SYLLABLE CYAG..HANGUL SYLLABLE CYAH + if (0xcc61 <= code && code <= 0xcc7b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CYAE + if (0xcc7c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xccd0) { + if (code < 0xcc99) { + if (code < 0xcc98) { + // Lo [27] HANGUL SYLLABLE CYAEG..HANGUL SYLLABLE CYAEH + if (0xcc7d <= code && code <= 0xcc97) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CEO + if (0xcc98 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xccb4) { + // Lo [27] HANGUL SYLLABLE CEOG..HANGUL SYLLABLE CEOH + if (0xcc99 <= code && code <= 0xccb3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xccb5) { + // Lo HANGUL SYLLABLE CE + if (0xccb4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CEG..HANGUL SYLLABLE CEH + if (0xccb5 <= code && code <= 0xcccf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcced) { + if (code < 0xccd1) { + // Lo HANGUL SYLLABLE CYEO + if (0xccd0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xccec) { + // Lo [27] HANGUL SYLLABLE CYEOG..HANGUL SYLLABLE CYEOH + if (0xccd1 <= code && code <= 0xcceb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CYE + if (0xccec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xcd08) { + // Lo [27] HANGUL SYLLABLE CYEG..HANGUL SYLLABLE CYEH + if (0xcced <= code && code <= 0xcd07) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcd09) { + // Lo HANGUL SYLLABLE CO + if (0xcd08 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE COG..HANGUL SYLLABLE COH + if (0xcd09 <= code && code <= 0xcd23) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + else { + if (code < 0xcf71) { + if (code < 0xce3d) { + if (code < 0xcdb0) { + if (code < 0xcd5d) { + if (code < 0xcd40) { + if (code < 0xcd25) { + // Lo HANGUL SYLLABLE CWA + if (0xcd24 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CWAG..HANGUL SYLLABLE CWAH + if (0xcd25 <= code && code <= 0xcd3f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcd41) { + // Lo HANGUL SYLLABLE CWAE + if (0xcd40 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcd5c) { + // Lo [27] HANGUL SYLLABLE CWAEG..HANGUL SYLLABLE CWAEH + if (0xcd41 <= code && code <= 0xcd5b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE COE + if (0xcd5c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xcd79) { + if (code < 0xcd78) { + // Lo [27] HANGUL SYLLABLE COEG..HANGUL SYLLABLE COEH + if (0xcd5d <= code && code <= 0xcd77) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CYO + if (0xcd78 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xcd94) { + // Lo [27] HANGUL SYLLABLE CYOG..HANGUL SYLLABLE CYOH + if (0xcd79 <= code && code <= 0xcd93) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcd95) { + // Lo HANGUL SYLLABLE CU + if (0xcd94 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CUG..HANGUL SYLLABLE CUH + if (0xcd95 <= code && code <= 0xcdaf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xcde9) { + if (code < 0xcdcc) { + if (code < 0xcdb1) { + // Lo HANGUL SYLLABLE CWEO + if (0xcdb0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CWEOG..HANGUL SYLLABLE CWEOH + if (0xcdb1 <= code && code <= 0xcdcb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcdcd) { + // Lo HANGUL SYLLABLE CWE + if (0xcdcc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcde8) { + // Lo [27] HANGUL SYLLABLE CWEG..HANGUL SYLLABLE CWEH + if (0xcdcd <= code && code <= 0xcde7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CWI + if (0xcde8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xce20) { + if (code < 0xce04) { + // Lo [27] HANGUL SYLLABLE CWIG..HANGUL SYLLABLE CWIH + if (0xcde9 <= code && code <= 0xce03) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xce05) { + // Lo HANGUL SYLLABLE CYU + if (0xce04 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE CYUG..HANGUL SYLLABLE CYUH + if (0xce05 <= code && code <= 0xce1f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xce21) { + // Lo HANGUL SYLLABLE CEU + if (0xce20 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xce3c) { + // Lo [27] HANGUL SYLLABLE CEUG..HANGUL SYLLABLE CEUH + if (0xce21 <= code && code <= 0xce3b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CYI + if (0xce3c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xcee4) { + if (code < 0xce90) { + if (code < 0xce59) { + if (code < 0xce58) { + // Lo [27] HANGUL SYLLABLE CYIG..HANGUL SYLLABLE CYIH + if (0xce3d <= code && code <= 0xce57) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE CI + if (0xce58 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xce74) { + // Lo [27] HANGUL SYLLABLE CIG..HANGUL SYLLABLE CIH + if (0xce59 <= code && code <= 0xce73) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xce75) { + // Lo HANGUL SYLLABLE KA + if (0xce74 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KAG..HANGUL SYLLABLE KAH + if (0xce75 <= code && code <= 0xce8f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcead) { + if (code < 0xce91) { + // Lo HANGUL SYLLABLE KAE + if (0xce90 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xceac) { + // Lo [27] HANGUL SYLLABLE KAEG..HANGUL SYLLABLE KAEH + if (0xce91 <= code && code <= 0xceab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KYA + if (0xceac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xcec8) { + // Lo [27] HANGUL SYLLABLE KYAG..HANGUL SYLLABLE KYAH + if (0xcead <= code && code <= 0xcec7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcec9) { + // Lo HANGUL SYLLABLE KYAE + if (0xcec8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KYAEG..HANGUL SYLLABLE KYAEH + if (0xcec9 <= code && code <= 0xcee3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xcf1d) { + if (code < 0xcf00) { + if (code < 0xcee5) { + // Lo HANGUL SYLLABLE KEO + if (0xcee4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KEOG..HANGUL SYLLABLE KEOH + if (0xcee5 <= code && code <= 0xceff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcf01) { + // Lo HANGUL SYLLABLE KE + if (0xcf00 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcf1c) { + // Lo [27] HANGUL SYLLABLE KEG..HANGUL SYLLABLE KEH + if (0xcf01 <= code && code <= 0xcf1b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KYEO + if (0xcf1c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xcf54) { + if (code < 0xcf38) { + // Lo [27] HANGUL SYLLABLE KYEOG..HANGUL SYLLABLE KYEOH + if (0xcf1d <= code && code <= 0xcf37) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcf39) { + // Lo HANGUL SYLLABLE KYE + if (0xcf38 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KYEG..HANGUL SYLLABLE KYEH + if (0xcf39 <= code && code <= 0xcf53) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xcf55) { + // Lo HANGUL SYLLABLE KO + if (0xcf54 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcf70) { + // Lo [27] HANGUL SYLLABLE KOG..HANGUL SYLLABLE KOH + if (0xcf55 <= code && code <= 0xcf6f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KWA + if (0xcf70 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + else { + if (code < 0xd0a4) { + if (code < 0xcffd) { + if (code < 0xcfc4) { + if (code < 0xcf8d) { + if (code < 0xcf8c) { + // Lo [27] HANGUL SYLLABLE KWAG..HANGUL SYLLABLE KWAH + if (0xcf71 <= code && code <= 0xcf8b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KWAE + if (0xcf8c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xcfa8) { + // Lo [27] HANGUL SYLLABLE KWAEG..HANGUL SYLLABLE KWAEH + if (0xcf8d <= code && code <= 0xcfa7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xcfa9) { + // Lo HANGUL SYLLABLE KOE + if (0xcfa8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KOEG..HANGUL SYLLABLE KOEH + if (0xcfa9 <= code && code <= 0xcfc3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xcfe0) { + if (code < 0xcfc5) { + // Lo HANGUL SYLLABLE KYO + if (0xcfc4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KYOG..HANGUL SYLLABLE KYOH + if (0xcfc5 <= code && code <= 0xcfdf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xcfe1) { + // Lo HANGUL SYLLABLE KU + if (0xcfe0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xcffc) { + // Lo [27] HANGUL SYLLABLE KUG..HANGUL SYLLABLE KUH + if (0xcfe1 <= code && code <= 0xcffb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KWEO + if (0xcffc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xd050) { + if (code < 0xd019) { + if (code < 0xd018) { + // Lo [27] HANGUL SYLLABLE KWEOG..HANGUL SYLLABLE KWEOH + if (0xcffd <= code && code <= 0xd017) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KWE + if (0xd018 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd034) { + // Lo [27] HANGUL SYLLABLE KWEG..HANGUL SYLLABLE KWEH + if (0xd019 <= code && code <= 0xd033) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd035) { + // Lo HANGUL SYLLABLE KWI + if (0xd034 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KWIG..HANGUL SYLLABLE KWIH + if (0xd035 <= code && code <= 0xd04f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd06d) { + if (code < 0xd051) { + // Lo HANGUL SYLLABLE KYU + if (0xd050 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd06c) { + // Lo [27] HANGUL SYLLABLE KYUG..HANGUL SYLLABLE KYUH + if (0xd051 <= code && code <= 0xd06b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE KEU + if (0xd06c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd088) { + // Lo [27] HANGUL SYLLABLE KEUG..HANGUL SYLLABLE KEUH + if (0xd06d <= code && code <= 0xd087) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd089) { + // Lo HANGUL SYLLABLE KYI + if (0xd088 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KYIG..HANGUL SYLLABLE KYIH + if (0xd089 <= code && code <= 0xd0a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0xd131) { + if (code < 0xd0dd) { + if (code < 0xd0c0) { + if (code < 0xd0a5) { + // Lo HANGUL SYLLABLE KI + if (0xd0a4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE KIG..HANGUL SYLLABLE KIH + if (0xd0a5 <= code && code <= 0xd0bf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd0c1) { + // Lo HANGUL SYLLABLE TA + if (0xd0c0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd0dc) { + // Lo [27] HANGUL SYLLABLE TAG..HANGUL SYLLABLE TAH + if (0xd0c1 <= code && code <= 0xd0db) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TAE + if (0xd0dc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd114) { + if (code < 0xd0f8) { + // Lo [27] HANGUL SYLLABLE TAEG..HANGUL SYLLABLE TAEH + if (0xd0dd <= code && code <= 0xd0f7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd0f9) { + // Lo HANGUL SYLLABLE TYA + if (0xd0f8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TYAG..HANGUL SYLLABLE TYAH + if (0xd0f9 <= code && code <= 0xd113) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xd115) { + // Lo HANGUL SYLLABLE TYAE + if (0xd114 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd130) { + // Lo [27] HANGUL SYLLABLE TYAEG..HANGUL SYLLABLE TYAEH + if (0xd115 <= code && code <= 0xd12f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TEO + if (0xd130 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xd184) { + if (code < 0xd14d) { + if (code < 0xd14c) { + // Lo [27] HANGUL SYLLABLE TEOG..HANGUL SYLLABLE TEOH + if (0xd131 <= code && code <= 0xd14b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TE + if (0xd14c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd168) { + // Lo [27] HANGUL SYLLABLE TEG..HANGUL SYLLABLE TEH + if (0xd14d <= code && code <= 0xd167) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd169) { + // Lo HANGUL SYLLABLE TYEO + if (0xd168 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TYEOG..HANGUL SYLLABLE TYEOH + if (0xd169 <= code && code <= 0xd183) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd1a1) { + if (code < 0xd185) { + // Lo HANGUL SYLLABLE TYE + if (0xd184 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd1a0) { + // Lo [27] HANGUL SYLLABLE TYEG..HANGUL SYLLABLE TYEH + if (0xd185 <= code && code <= 0xd19f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TO + if (0xd1a0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd1bc) { + // Lo [27] HANGUL SYLLABLE TOG..HANGUL SYLLABLE TOH + if (0xd1a1 <= code && code <= 0xd1bb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd1bd) { + // Lo HANGUL SYLLABLE TWA + if (0xd1bc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TWAG..HANGUL SYLLABLE TWAH + if (0xd1bd <= code && code <= 0xd1d7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0x1133b) { + if (code < 0xd671) { + if (code < 0xd424) { + if (code < 0xd2f1) { + if (code < 0xd264) { + if (code < 0xd211) { + if (code < 0xd1f4) { + if (code < 0xd1d9) { + // Lo HANGUL SYLLABLE TWAE + if (0xd1d8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TWAEG..HANGUL SYLLABLE TWAEH + if (0xd1d9 <= code && code <= 0xd1f3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd1f5) { + // Lo HANGUL SYLLABLE TOE + if (0xd1f4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd210) { + // Lo [27] HANGUL SYLLABLE TOEG..HANGUL SYLLABLE TOEH + if (0xd1f5 <= code && code <= 0xd20f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TYO + if (0xd210 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd22d) { + if (code < 0xd22c) { + // Lo [27] HANGUL SYLLABLE TYOG..HANGUL SYLLABLE TYOH + if (0xd211 <= code && code <= 0xd22b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TU + if (0xd22c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd248) { + // Lo [27] HANGUL SYLLABLE TUG..HANGUL SYLLABLE TUH + if (0xd22d <= code && code <= 0xd247) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd249) { + // Lo HANGUL SYLLABLE TWEO + if (0xd248 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TWEOG..HANGUL SYLLABLE TWEOH + if (0xd249 <= code && code <= 0xd263) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xd29d) { + if (code < 0xd280) { + if (code < 0xd265) { + // Lo HANGUL SYLLABLE TWE + if (0xd264 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TWEG..HANGUL SYLLABLE TWEH + if (0xd265 <= code && code <= 0xd27f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd281) { + // Lo HANGUL SYLLABLE TWI + if (0xd280 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd29c) { + // Lo [27] HANGUL SYLLABLE TWIG..HANGUL SYLLABLE TWIH + if (0xd281 <= code && code <= 0xd29b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TYU + if (0xd29c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd2d4) { + if (code < 0xd2b8) { + // Lo [27] HANGUL SYLLABLE TYUG..HANGUL SYLLABLE TYUH + if (0xd29d <= code && code <= 0xd2b7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd2b9) { + // Lo HANGUL SYLLABLE TEU + if (0xd2b8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE TEUG..HANGUL SYLLABLE TEUH + if (0xd2b9 <= code && code <= 0xd2d3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xd2d5) { + // Lo HANGUL SYLLABLE TYI + if (0xd2d4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd2f0) { + // Lo [27] HANGUL SYLLABLE TYIG..HANGUL SYLLABLE TYIH + if (0xd2d5 <= code && code <= 0xd2ef) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE TI + if (0xd2f0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xd37d) { + if (code < 0xd344) { + if (code < 0xd30d) { + if (code < 0xd30c) { + // Lo [27] HANGUL SYLLABLE TIG..HANGUL SYLLABLE TIH + if (0xd2f1 <= code && code <= 0xd30b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PA + if (0xd30c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd328) { + // Lo [27] HANGUL SYLLABLE PAG..HANGUL SYLLABLE PAH + if (0xd30d <= code && code <= 0xd327) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd329) { + // Lo HANGUL SYLLABLE PAE + if (0xd328 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PAEG..HANGUL SYLLABLE PAEH + if (0xd329 <= code && code <= 0xd343) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd360) { + if (code < 0xd345) { + // Lo HANGUL SYLLABLE PYA + if (0xd344 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PYAG..HANGUL SYLLABLE PYAH + if (0xd345 <= code && code <= 0xd35f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd361) { + // Lo HANGUL SYLLABLE PYAE + if (0xd360 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd37c) { + // Lo [27] HANGUL SYLLABLE PYAEG..HANGUL SYLLABLE PYAEH + if (0xd361 <= code && code <= 0xd37b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PEO + if (0xd37c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xd3d0) { + if (code < 0xd399) { + if (code < 0xd398) { + // Lo [27] HANGUL SYLLABLE PEOG..HANGUL SYLLABLE PEOH + if (0xd37d <= code && code <= 0xd397) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PE + if (0xd398 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd3b4) { + // Lo [27] HANGUL SYLLABLE PEG..HANGUL SYLLABLE PEH + if (0xd399 <= code && code <= 0xd3b3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd3b5) { + // Lo HANGUL SYLLABLE PYEO + if (0xd3b4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PYEOG..HANGUL SYLLABLE PYEOH + if (0xd3b5 <= code && code <= 0xd3cf) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd3ed) { + if (code < 0xd3d1) { + // Lo HANGUL SYLLABLE PYE + if (0xd3d0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd3ec) { + // Lo [27] HANGUL SYLLABLE PYEG..HANGUL SYLLABLE PYEH + if (0xd3d1 <= code && code <= 0xd3eb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PO + if (0xd3ec === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd408) { + // Lo [27] HANGUL SYLLABLE POG..HANGUL SYLLABLE POH + if (0xd3ed <= code && code <= 0xd407) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd409) { + // Lo HANGUL SYLLABLE PWA + if (0xd408 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PWAG..HANGUL SYLLABLE PWAH + if (0xd409 <= code && code <= 0xd423) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + } + else { + if (code < 0xd53d) { + if (code < 0xd4b0) { + if (code < 0xd45d) { + if (code < 0xd440) { + if (code < 0xd425) { + // Lo HANGUL SYLLABLE PWAE + if (0xd424 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PWAEG..HANGUL SYLLABLE PWAEH + if (0xd425 <= code && code <= 0xd43f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd441) { + // Lo HANGUL SYLLABLE POE + if (0xd440 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd45c) { + // Lo [27] HANGUL SYLLABLE POEG..HANGUL SYLLABLE POEH + if (0xd441 <= code && code <= 0xd45b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PYO + if (0xd45c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd479) { + if (code < 0xd478) { + // Lo [27] HANGUL SYLLABLE PYOG..HANGUL SYLLABLE PYOH + if (0xd45d <= code && code <= 0xd477) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PU + if (0xd478 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd494) { + // Lo [27] HANGUL SYLLABLE PUG..HANGUL SYLLABLE PUH + if (0xd479 <= code && code <= 0xd493) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd495) { + // Lo HANGUL SYLLABLE PWEO + if (0xd494 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PWEOG..HANGUL SYLLABLE PWEOH + if (0xd495 <= code && code <= 0xd4af) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xd4e9) { + if (code < 0xd4cc) { + if (code < 0xd4b1) { + // Lo HANGUL SYLLABLE PWE + if (0xd4b0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PWEG..HANGUL SYLLABLE PWEH + if (0xd4b1 <= code && code <= 0xd4cb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd4cd) { + // Lo HANGUL SYLLABLE PWI + if (0xd4cc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd4e8) { + // Lo [27] HANGUL SYLLABLE PWIG..HANGUL SYLLABLE PWIH + if (0xd4cd <= code && code <= 0xd4e7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PYU + if (0xd4e8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd520) { + if (code < 0xd504) { + // Lo [27] HANGUL SYLLABLE PYUG..HANGUL SYLLABLE PYUH + if (0xd4e9 <= code && code <= 0xd503) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd505) { + // Lo HANGUL SYLLABLE PEU + if (0xd504 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE PEUG..HANGUL SYLLABLE PEUH + if (0xd505 <= code && code <= 0xd51f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xd521) { + // Lo HANGUL SYLLABLE PYI + if (0xd520 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd53c) { + // Lo [27] HANGUL SYLLABLE PYIG..HANGUL SYLLABLE PYIH + if (0xd521 <= code && code <= 0xd53b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE PI + if (0xd53c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + else { + if (code < 0xd5e4) { + if (code < 0xd590) { + if (code < 0xd559) { + if (code < 0xd558) { + // Lo [27] HANGUL SYLLABLE PIG..HANGUL SYLLABLE PIH + if (0xd53d <= code && code <= 0xd557) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HA + if (0xd558 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd574) { + // Lo [27] HANGUL SYLLABLE HAG..HANGUL SYLLABLE HAH + if (0xd559 <= code && code <= 0xd573) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd575) { + // Lo HANGUL SYLLABLE HAE + if (0xd574 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HAEG..HANGUL SYLLABLE HAEH + if (0xd575 <= code && code <= 0xd58f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd5ad) { + if (code < 0xd591) { + // Lo HANGUL SYLLABLE HYA + if (0xd590 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd5ac) { + // Lo [27] HANGUL SYLLABLE HYAG..HANGUL SYLLABLE HYAH + if (0xd591 <= code && code <= 0xd5ab) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HYAE + if (0xd5ac === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd5c8) { + // Lo [27] HANGUL SYLLABLE HYAEG..HANGUL SYLLABLE HYAEH + if (0xd5ad <= code && code <= 0xd5c7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd5c9) { + // Lo HANGUL SYLLABLE HEO + if (0xd5c8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HEOG..HANGUL SYLLABLE HEOH + if (0xd5c9 <= code && code <= 0xd5e3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + else { + if (code < 0xd61d) { + if (code < 0xd600) { + if (code < 0xd5e5) { + // Lo HANGUL SYLLABLE HE + if (0xd5e4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HEG..HANGUL SYLLABLE HEH + if (0xd5e5 <= code && code <= 0xd5ff) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd601) { + // Lo HANGUL SYLLABLE HYEO + if (0xd600 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd61c) { + // Lo [27] HANGUL SYLLABLE HYEOG..HANGUL SYLLABLE HYEOH + if (0xd601 <= code && code <= 0xd61b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HYE + if (0xd61c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + else { + if (code < 0xd654) { + if (code < 0xd638) { + // Lo [27] HANGUL SYLLABLE HYEG..HANGUL SYLLABLE HYEH + if (0xd61d <= code && code <= 0xd637) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd639) { + // Lo HANGUL SYLLABLE HO + if (0xd638 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HOG..HANGUL SYLLABLE HOH + if (0xd639 <= code && code <= 0xd653) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + else { + if (code < 0xd655) { + // Lo HANGUL SYLLABLE HWA + if (0xd654 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd670) { + // Lo [27] HANGUL SYLLABLE HWAG..HANGUL SYLLABLE HWAH + if (0xd655 <= code && code <= 0xd66f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HWAE + if (0xd670 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + } + } + } + else { + if (code < 0x11000) { + if (code < 0xd7b0) { + if (code < 0xd6fd) { + if (code < 0xd6c4) { + if (code < 0xd68d) { + if (code < 0xd68c) { + // Lo [27] HANGUL SYLLABLE HWAEG..HANGUL SYLLABLE HWAEH + if (0xd671 <= code && code <= 0xd68b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HOE + if (0xd68c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd6a8) { + // Lo [27] HANGUL SYLLABLE HOEG..HANGUL SYLLABLE HOEH + if (0xd68d <= code && code <= 0xd6a7) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd6a9) { + // Lo HANGUL SYLLABLE HYO + if (0xd6a8 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HYOG..HANGUL SYLLABLE HYOH + if (0xd6a9 <= code && code <= 0xd6c3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd6e0) { + if (code < 0xd6c5) { + // Lo HANGUL SYLLABLE HU + if (0xd6c4 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HUG..HANGUL SYLLABLE HUH + if (0xd6c5 <= code && code <= 0xd6df) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + else { + if (code < 0xd6e1) { + // Lo HANGUL SYLLABLE HWEO + if (0xd6e0 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd6fc) { + // Lo [27] HANGUL SYLLABLE HWEOG..HANGUL SYLLABLE HWEOH + if (0xd6e1 <= code && code <= 0xd6fb) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HWE + if (0xd6fc === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + } + } + else { + if (code < 0xd750) { + if (code < 0xd719) { + if (code < 0xd718) { + // Lo [27] HANGUL SYLLABLE HWEG..HANGUL SYLLABLE HWEH + if (0xd6fd <= code && code <= 0xd717) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HWI + if (0xd718 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + else { + if (code < 0xd734) { + // Lo [27] HANGUL SYLLABLE HWIG..HANGUL SYLLABLE HWIH + if (0xd719 <= code && code <= 0xd733) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd735) { + // Lo HANGUL SYLLABLE HYU + if (0xd734 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HYUG..HANGUL SYLLABLE HYUH + if (0xd735 <= code && code <= 0xd74f) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + else { + if (code < 0xd76d) { + if (code < 0xd751) { + // Lo HANGUL SYLLABLE HEU + if (0xd750 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + if (code < 0xd76c) { + // Lo [27] HANGUL SYLLABLE HEUG..HANGUL SYLLABLE HEUH + if (0xd751 <= code && code <= 0xd76b) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + // Lo HANGUL SYLLABLE HYI + if (0xd76c === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + } + } + else { + if (code < 0xd788) { + // Lo [27] HANGUL SYLLABLE HYIG..HANGUL SYLLABLE HYIH + if (0xd76d <= code && code <= 0xd787) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + else { + if (code < 0xd789) { + // Lo HANGUL SYLLABLE HI + if (0xd788 === code) { + return boundaries_1.CLUSTER_BREAK.LV; + } + } + else { + // Lo [27] HANGUL SYLLABLE HIG..HANGUL SYLLABLE HIH + if (0xd789 <= code && code <= 0xd7a3) { + return boundaries_1.CLUSTER_BREAK.LVT; + } + } + } + } + } + } + } + else { + if (code < 0x10a01) { + if (code < 0xfeff) { + if (code < 0xfb1e) { + if (code < 0xd7cb) { + // Lo [23] HANGUL JUNGSEONG O-YEO..HANGUL JUNGSEONG ARAEA-E + if (0xd7b0 <= code && code <= 0xd7c6) { + return boundaries_1.CLUSTER_BREAK.V; + } + } + else { + // Lo [49] HANGUL JONGSEONG NIEUN-RIEUL..HANGUL JONGSEONG PHIEUPH-THIEUTH + if (0xd7cb <= code && code <= 0xd7fb) { + return boundaries_1.CLUSTER_BREAK.T; + } + } + } + else { + if (code < 0xfe00) { + // Mn HEBREW POINT JUDEO-SPANISH VARIKA + if (0xfb1e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xfe20) { + // Mn [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16 + if (0xfe00 <= code && code <= 0xfe0f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [16] COMBINING LIGATURE LEFT HALF..COMBINING CYRILLIC TITLO RIGHT HALF + if (0xfe20 <= code && code <= 0xfe2f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x101fd) { + if (code < 0xff9e) { + // Cf ZERO WIDTH NO-BREAK SPACE + if (0xfeff === code) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0xfff0) { + // Lm [2] HALFWIDTH KATAKANA VOICED SOUND MARK..HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK + if (0xff9e <= code && code <= 0xff9f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cn [9] .. + // Cf [3] INTERLINEAR ANNOTATION ANCHOR..INTERLINEAR ANNOTATION TERMINATOR + if (0xfff0 <= code && code <= 0xfffb) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + } + else { + if (code < 0x102e0) { + // Mn PHAISTOS DISC SIGN COMBINING OBLIQUE STROKE + if (0x101fd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x10376) { + // Mn COPTIC EPACT THOUSANDS MARK + if (0x102e0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [5] COMBINING OLD PERMIC LETTER AN..COMBINING OLD PERMIC LETTER SII + if (0x10376 <= code && code <= 0x1037a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x10ae5) { + if (code < 0x10a0c) { + if (code < 0x10a05) { + // Mn [3] KHAROSHTHI VOWEL SIGN I..KHAROSHTHI VOWEL SIGN VOCALIC R + if (0x10a01 <= code && code <= 0x10a03) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] KHAROSHTHI VOWEL SIGN E..KHAROSHTHI VOWEL SIGN O + if (0x10a05 <= code && code <= 0x10a06) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x10a38) { + // Mn [4] KHAROSHTHI VOWEL LENGTH MARK..KHAROSHTHI SIGN VISARGA + if (0x10a0c <= code && code <= 0x10a0f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x10a3f) { + // Mn [3] KHAROSHTHI SIGN BAR ABOVE..KHAROSHTHI SIGN DOT BELOW + if (0x10a38 <= code && code <= 0x10a3a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn KHAROSHTHI VIRAMA + if (0x10a3f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x10efd) { + if (code < 0x10d24) { + // Mn [2] MANICHAEAN ABBREVIATION MARK ABOVE..MANICHAEAN ABBREVIATION MARK BELOW + if (0x10ae5 <= code && code <= 0x10ae6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x10eab) { + // Mn [4] HANIFI ROHINGYA SIGN HARBAHAY..HANIFI ROHINGYA SIGN TASSI + if (0x10d24 <= code && code <= 0x10d27) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] YEZIDI COMBINING HAMZA MARK..YEZIDI COMBINING MADDA MARK + if (0x10eab <= code && code <= 0x10eac) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x10f46) { + // Mn [3] ARABIC SMALL LOW WORD SAKTA..ARABIC SMALL LOW WORD MADDA + if (0x10efd <= code && code <= 0x10eff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x10f82) { + // Mn [11] SOGDIAN COMBINING DOT BELOW..SOGDIAN COMBINING STROKE BELOW + if (0x10f46 <= code && code <= 0x10f50) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [4] OLD UYGHUR COMBINING DOT ABOVE..OLD UYGHUR COMBINING TWO DOTS BELOW + if (0x10f82 <= code && code <= 0x10f85) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0x11180) { + if (code < 0x110b7) { + if (code < 0x11073) { + if (code < 0x11002) { + // Mc BRAHMI SIGN CANDRABINDU + if (0x11000 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn BRAHMI SIGN ANUSVARA + if (0x11001 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11038) { + // Mc BRAHMI SIGN VISARGA + if (0x11002 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11070) { + // Mn [15] BRAHMI VOWEL SIGN AA..BRAHMI VIRAMA + if (0x11038 <= code && code <= 0x11046) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn BRAHMI SIGN OLD TAMIL VIRAMA + if (0x11070 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x11082) { + if (code < 0x1107f) { + // Mn [2] BRAHMI VOWEL SIGN OLD TAMIL SHORT E..BRAHMI VOWEL SIGN OLD TAMIL SHORT O + if (0x11073 <= code && code <= 0x11074) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] BRAHMI NUMBER JOINER..KAITHI SIGN ANUSVARA + if (0x1107f <= code && code <= 0x11081) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x110b0) { + // Mc KAITHI SIGN VISARGA + if (0x11082 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x110b3) { + // Mc [3] KAITHI VOWEL SIGN AA..KAITHI VOWEL SIGN II + if (0x110b0 <= code && code <= 0x110b2) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] KAITHI VOWEL SIGN U..KAITHI VOWEL SIGN AI + if (0x110b3 <= code && code <= 0x110b6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11100) { + if (code < 0x110bd) { + if (code < 0x110b9) { + // Mc [2] KAITHI VOWEL SIGN O..KAITHI VOWEL SIGN AU + if (0x110b7 <= code && code <= 0x110b8) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] KAITHI SIGN VIRAMA..KAITHI SIGN NUKTA + if (0x110b9 <= code && code <= 0x110ba) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x110c2) { + // Cf KAITHI NUMBER SIGN + if (0x110bd === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + // Mn KAITHI VOWEL SIGN VOCALIC R + if (0x110c2 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Cf KAITHI NUMBER SIGN ABOVE + if (0x110cd === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + } + } + else { + if (code < 0x1112d) { + if (code < 0x11127) { + // Mn [3] CHAKMA SIGN CANDRABINDU..CHAKMA SIGN VISARGA + if (0x11100 <= code && code <= 0x11102) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1112c) { + // Mn [5] CHAKMA VOWEL SIGN A..CHAKMA VOWEL SIGN UU + if (0x11127 <= code && code <= 0x1112b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc CHAKMA VOWEL SIGN E + if (0x1112c === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x11145) { + // Mn [8] CHAKMA VOWEL SIGN AI..CHAKMA MAAYYAA + if (0x1112d <= code && code <= 0x11134) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11173) { + // Mc [2] CHAKMA VOWEL SIGN AA..CHAKMA VOWEL SIGN EI + if (0x11145 <= code && code <= 0x11146) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn MAHAJANI SIGN NUKTA + if (0x11173 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0x11232) { + if (code < 0x111c2) { + if (code < 0x111b3) { + if (code < 0x11182) { + // Mn [2] SHARADA SIGN CANDRABINDU..SHARADA SIGN ANUSVARA + if (0x11180 <= code && code <= 0x11181) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc SHARADA SIGN VISARGA + if (0x11182 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x111b6) { + // Mc [3] SHARADA VOWEL SIGN AA..SHARADA VOWEL SIGN II + if (0x111b3 <= code && code <= 0x111b5) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x111bf) { + // Mn [9] SHARADA VOWEL SIGN U..SHARADA VOWEL SIGN O + if (0x111b6 <= code && code <= 0x111be) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SHARADA VOWEL SIGN AU..SHARADA SIGN VIRAMA + if (0x111bf <= code && code <= 0x111c0) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x111cf) { + if (code < 0x111c9) { + // Lo [2] SHARADA SIGN JIHVAMULIYA..SHARADA SIGN UPADHMANIYA + if (0x111c2 <= code && code <= 0x111c3) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + if (code < 0x111ce) { + // Mn [4] SHARADA SANDHI MARK..SHARADA EXTRA SHORT VOWEL MARK + if (0x111c9 <= code && code <= 0x111cc) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc SHARADA VOWEL SIGN PRISHTHAMATRA E + if (0x111ce === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1122c) { + // Mn SHARADA SIGN INVERTED CANDRABINDU + if (0x111cf === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1122f) { + // Mc [3] KHOJKI VOWEL SIGN AA..KHOJKI VOWEL SIGN II + if (0x1122c <= code && code <= 0x1122e) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [3] KHOJKI VOWEL SIGN U..KHOJKI VOWEL SIGN AI + if (0x1122f <= code && code <= 0x11231) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11241) { + if (code < 0x11235) { + if (code < 0x11234) { + // Mc [2] KHOJKI VOWEL SIGN O..KHOJKI VOWEL SIGN AU + if (0x11232 <= code && code <= 0x11233) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn KHOJKI SIGN ANUSVARA + if (0x11234 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11236) { + // Mc KHOJKI SIGN VIRAMA + if (0x11235 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1123e) { + // Mn [2] KHOJKI SIGN NUKTA..KHOJKI SIGN SHADDA + if (0x11236 <= code && code <= 0x11237) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn KHOJKI SIGN SUKUN + if (0x1123e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x112e3) { + if (code < 0x112df) { + // Mn KHOJKI VOWEL SIGN VOCALIC R + if (0x11241 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x112e0) { + // Mn KHUDAWADI SIGN ANUSVARA + if (0x112df === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] KHUDAWADI VOWEL SIGN AA..KHUDAWADI VOWEL SIGN II + if (0x112e0 <= code && code <= 0x112e2) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x11300) { + // Mn [8] KHUDAWADI VOWEL SIGN U..KHUDAWADI SIGN VIRAMA + if (0x112e3 <= code && code <= 0x112ea) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11302) { + // Mn [2] GRANTHA SIGN COMBINING ANUSVARA ABOVE..GRANTHA SIGN CANDRABINDU + if (0x11300 <= code && code <= 0x11301) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] GRANTHA SIGN ANUSVARA..GRANTHA SIGN VISARGA + if (0x11302 <= code && code <= 0x11303) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + } + } + } + else { + if (code < 0x11a97) { + if (code < 0x116ab) { + if (code < 0x114b9) { + if (code < 0x11370) { + if (code < 0x11347) { + if (code < 0x1133f) { + if (code < 0x1133e) { + // Mn [2] COMBINING BINDU BELOW..GRANTHA SIGN NUKTA + if (0x1133b <= code && code <= 0x1133c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc GRANTHA VOWEL SIGN AA + if (0x1133e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11340) { + // Mc GRANTHA VOWEL SIGN I + if (0x1133f === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11341) { + // Mn GRANTHA VOWEL SIGN II + if (0x11340 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [4] GRANTHA VOWEL SIGN U..GRANTHA VOWEL SIGN VOCALIC RR + if (0x11341 <= code && code <= 0x11344) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x11357) { + if (code < 0x1134b) { + // Mc [2] GRANTHA VOWEL SIGN EE..GRANTHA VOWEL SIGN AI + if (0x11347 <= code && code <= 0x11348) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [3] GRANTHA VOWEL SIGN OO..GRANTHA SIGN VIRAMA + if (0x1134b <= code && code <= 0x1134d) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11362) { + // Mc GRANTHA AU LENGTH MARK + if (0x11357 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11366) { + // Mc [2] GRANTHA VOWEL SIGN VOCALIC L..GRANTHA VOWEL SIGN VOCALIC LL + if (0x11362 <= code && code <= 0x11363) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [7] COMBINING GRANTHA DIGIT ZERO..COMBINING GRANTHA DIGIT SIX + if (0x11366 <= code && code <= 0x1136c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11445) { + if (code < 0x11438) { + if (code < 0x11435) { + // Mn [5] COMBINING GRANTHA LETTER A..COMBINING GRANTHA LETTER PA + if (0x11370 <= code && code <= 0x11374) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] NEWA VOWEL SIGN AA..NEWA VOWEL SIGN II + if (0x11435 <= code && code <= 0x11437) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11440) { + // Mn [8] NEWA VOWEL SIGN U..NEWA VOWEL SIGN AI + if (0x11438 <= code && code <= 0x1143f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11442) { + // Mc [2] NEWA VOWEL SIGN O..NEWA VOWEL SIGN AU + if (0x11440 <= code && code <= 0x11441) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [3] NEWA SIGN VIRAMA..NEWA SIGN ANUSVARA + if (0x11442 <= code && code <= 0x11444) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x114b0) { + if (code < 0x11446) { + // Mc NEWA SIGN VISARGA + if (0x11445 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn NEWA SIGN NUKTA + if (0x11446 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mn NEWA SANDHI MARK + if (0x1145e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x114b1) { + // Mc TIRHUTA VOWEL SIGN AA + if (0x114b0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x114b3) { + // Mc [2] TIRHUTA VOWEL SIGN I..TIRHUTA VOWEL SIGN II + if (0x114b1 <= code && code <= 0x114b2) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [6] TIRHUTA VOWEL SIGN U..TIRHUTA VOWEL SIGN VOCALIC LL + if (0x114b3 <= code && code <= 0x114b8) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0x115b8) { + if (code < 0x114bf) { + if (code < 0x114bb) { + // Mc TIRHUTA VOWEL SIGN E + if (0x114b9 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn TIRHUTA VOWEL SIGN SHORT E + if (0x114ba === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x114bd) { + // Mc [2] TIRHUTA VOWEL SIGN AI..TIRHUTA VOWEL SIGN O + if (0x114bb <= code && code <= 0x114bc) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc TIRHUTA VOWEL SIGN SHORT O + if (0x114bd === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc TIRHUTA VOWEL SIGN AU + if (0x114be === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x115af) { + if (code < 0x114c1) { + // Mn [2] TIRHUTA SIGN CANDRABINDU..TIRHUTA SIGN ANUSVARA + if (0x114bf <= code && code <= 0x114c0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x114c2) { + // Mc TIRHUTA SIGN VISARGA + if (0x114c1 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] TIRHUTA SIGN VIRAMA..TIRHUTA SIGN NUKTA + if (0x114c2 <= code && code <= 0x114c3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x115b0) { + // Mc SIDDHAM VOWEL SIGN AA + if (0x115af === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x115b2) { + // Mc [2] SIDDHAM VOWEL SIGN I..SIDDHAM VOWEL SIGN II + if (0x115b0 <= code && code <= 0x115b1) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] SIDDHAM VOWEL SIGN U..SIDDHAM VOWEL SIGN VOCALIC RR + if (0x115b2 <= code && code <= 0x115b5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11630) { + if (code < 0x115be) { + if (code < 0x115bc) { + // Mc [4] SIDDHAM VOWEL SIGN E..SIDDHAM VOWEL SIGN AU + if (0x115b8 <= code && code <= 0x115bb) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] SIDDHAM SIGN CANDRABINDU..SIDDHAM SIGN ANUSVARA + if (0x115bc <= code && code <= 0x115bd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x115bf) { + // Mc SIDDHAM SIGN VISARGA + if (0x115be === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x115dc) { + // Mn [2] SIDDHAM SIGN VIRAMA..SIDDHAM SIGN NUKTA + if (0x115bf <= code && code <= 0x115c0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] SIDDHAM VOWEL SIGN ALTERNATE U..SIDDHAM VOWEL SIGN ALTERNATE UU + if (0x115dc <= code && code <= 0x115dd) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1163d) { + if (code < 0x11633) { + // Mc [3] MODI VOWEL SIGN AA..MODI VOWEL SIGN II + if (0x11630 <= code && code <= 0x11632) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x1163b) { + // Mn [8] MODI VOWEL SIGN U..MODI VOWEL SIGN AI + if (0x11633 <= code && code <= 0x1163a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] MODI VOWEL SIGN O..MODI VOWEL SIGN AU + if (0x1163b <= code && code <= 0x1163c) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1163e) { + // Mn MODI SIGN ANUSVARA + if (0x1163d === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1163f) { + // Mc MODI SIGN VISARGA + if (0x1163e === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] MODI SIGN VIRAMA..MODI SIGN ARDHACANDRA + if (0x1163f <= code && code <= 0x11640) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0x1193f) { + if (code < 0x11727) { + if (code < 0x116b6) { + if (code < 0x116ad) { + // Mn TAKRI SIGN ANUSVARA + if (0x116ab === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc TAKRI SIGN VISARGA + if (0x116ac === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x116ae) { + // Mn TAKRI VOWEL SIGN AA + if (0x116ad === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x116b0) { + // Mc [2] TAKRI VOWEL SIGN I..TAKRI VOWEL SIGN II + if (0x116ae <= code && code <= 0x116af) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [6] TAKRI VOWEL SIGN U..TAKRI VOWEL SIGN AU + if (0x116b0 <= code && code <= 0x116b5) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1171d) { + // Mc TAKRI SIGN VIRAMA + if (0x116b6 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn TAKRI SIGN NUKTA + if (0x116b7 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11722) { + // Mn [3] AHOM CONSONANT SIGN MEDIAL LA..AHOM CONSONANT SIGN MEDIAL LIGATING RA + if (0x1171d <= code && code <= 0x1171f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11726) { + // Mn [4] AHOM VOWEL SIGN I..AHOM VOWEL SIGN UU + if (0x11722 <= code && code <= 0x11725) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc AHOM VOWEL SIGN E + if (0x11726 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0x11930) { + if (code < 0x1182f) { + if (code < 0x1182c) { + // Mn [5] AHOM VOWEL SIGN AW..AHOM SIGN KILLER + if (0x11727 <= code && code <= 0x1172b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [3] DOGRA VOWEL SIGN AA..DOGRA VOWEL SIGN II + if (0x1182c <= code && code <= 0x1182e) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11838) { + // Mn [9] DOGRA VOWEL SIGN U..DOGRA SIGN ANUSVARA + if (0x1182f <= code && code <= 0x11837) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11839) { + // Mc DOGRA SIGN VISARGA + if (0x11838 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] DOGRA SIGN VIRAMA..DOGRA SIGN NUKTA + if (0x11839 <= code && code <= 0x1183a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1193b) { + if (code < 0x11931) { + // Mc DIVES AKURU VOWEL SIGN AA + if (0x11930 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11937) { + // Mc [5] DIVES AKURU VOWEL SIGN I..DIVES AKURU VOWEL SIGN E + if (0x11931 <= code && code <= 0x11935) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [2] DIVES AKURU VOWEL SIGN AI..DIVES AKURU VOWEL SIGN O + if (0x11937 <= code && code <= 0x11938) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x1193d) { + // Mn [2] DIVES AKURU SIGN ANUSVARA..DIVES AKURU SIGN CANDRABINDU + if (0x1193b <= code && code <= 0x1193c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc DIVES AKURU SIGN HALANTA + if (0x1193d === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn DIVES AKURU VIRAMA + if (0x1193e === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11a01) { + if (code < 0x119d1) { + if (code < 0x11941) { + // Lo DIVES AKURU PREFIXED NASAL SIGN + if (0x1193f === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + // Mc DIVES AKURU MEDIAL YA + if (0x11940 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11942) { + // Lo DIVES AKURU INITIAL RA + if (0x11941 === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + // Mc DIVES AKURU MEDIAL RA + if (0x11942 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn DIVES AKURU SIGN NUKTA + if (0x11943 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x119dc) { + if (code < 0x119d4) { + // Mc [3] NANDINAGARI VOWEL SIGN AA..NANDINAGARI VOWEL SIGN II + if (0x119d1 <= code && code <= 0x119d3) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x119da) { + // Mn [4] NANDINAGARI VOWEL SIGN U..NANDINAGARI VOWEL SIGN VOCALIC RR + if (0x119d4 <= code && code <= 0x119d7) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [2] NANDINAGARI VOWEL SIGN E..NANDINAGARI VOWEL SIGN AI + if (0x119da <= code && code <= 0x119db) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x119e0) { + // Mc [4] NANDINAGARI VOWEL SIGN O..NANDINAGARI SIGN VISARGA + if (0x119dc <= code && code <= 0x119df) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn NANDINAGARI SIGN VIRAMA + if (0x119e0 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc NANDINAGARI VOWEL SIGN PRISHTHAMATRA E + if (0x119e4 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x11a47) { + if (code < 0x11a39) { + if (code < 0x11a33) { + // Mn [10] ZANABAZAR SQUARE VOWEL SIGN I..ZANABAZAR SQUARE VOWEL LENGTH MARK + if (0x11a01 <= code && code <= 0x11a0a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [6] ZANABAZAR SQUARE FINAL CONSONANT MARK..ZANABAZAR SQUARE SIGN ANUSVARA + if (0x11a33 <= code && code <= 0x11a38) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11a3a) { + // Mc ZANABAZAR SQUARE SIGN VISARGA + if (0x11a39 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11a3b) { + // Lo ZANABAZAR SQUARE CLUSTER-INITIAL LETTER RA + if (0x11a3a === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + // Mn [4] ZANABAZAR SQUARE CLUSTER-FINAL LETTER YA..ZANABAZAR SQUARE CLUSTER-FINAL LETTER VA + if (0x11a3b <= code && code <= 0x11a3e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x11a59) { + if (code < 0x11a51) { + // Mn ZANABAZAR SQUARE SUBJOINER + if (0x11a47 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11a57) { + // Mn [6] SOYOMBO VOWEL SIGN I..SOYOMBO VOWEL SIGN OE + if (0x11a51 <= code && code <= 0x11a56) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] SOYOMBO VOWEL SIGN AI..SOYOMBO VOWEL SIGN AU + if (0x11a57 <= code && code <= 0x11a58) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + else { + if (code < 0x11a84) { + // Mn [3] SOYOMBO VOWEL SIGN VOCALIC R..SOYOMBO VOWEL LENGTH MARK + if (0x11a59 <= code && code <= 0x11a5b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11a8a) { + // Lo [6] SOYOMBO SIGN JIHVAMULIYA..SOYOMBO CLUSTER-INITIAL LETTER SA + if (0x11a84 <= code && code <= 0x11a89) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + // Mn [13] SOYOMBO FINAL CONSONANT SIGN G..SOYOMBO SIGN ANUSVARA + if (0x11a8a <= code && code <= 0x11a96) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + } + else { + if (code < 0x16f51) { + if (code < 0x11d90) { + if (code < 0x11cb1) { + if (code < 0x11c3e) { + if (code < 0x11c2f) { + if (code < 0x11a98) { + // Mc SOYOMBO SIGN VISARGA + if (0x11a97 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] SOYOMBO GEMINATION MARK..SOYOMBO SUBJOINER + if (0x11a98 <= code && code <= 0x11a99) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11c30) { + // Mc BHAIKSUKI VOWEL SIGN AA + if (0x11c2f === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11c38) { + // Mn [7] BHAIKSUKI VOWEL SIGN I..BHAIKSUKI VOWEL SIGN VOCALIC L + if (0x11c30 <= code && code <= 0x11c36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [6] BHAIKSUKI VOWEL SIGN E..BHAIKSUKI SIGN ANUSVARA + if (0x11c38 <= code && code <= 0x11c3d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x11c92) { + // Mc BHAIKSUKI SIGN VISARGA + if (0x11c3e === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn BHAIKSUKI SIGN VIRAMA + if (0x11c3f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11ca9) { + // Mn [22] MARCHEN SUBJOINED LETTER KA..MARCHEN SUBJOINED LETTER ZA + if (0x11c92 <= code && code <= 0x11ca7) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11caa) { + // Mc MARCHEN SUBJOINED LETTER YA + if (0x11ca9 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [7] MARCHEN SUBJOINED LETTER RA..MARCHEN VOWEL SIGN AA + if (0x11caa <= code && code <= 0x11cb0) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x11d3a) { + if (code < 0x11cb4) { + if (code < 0x11cb2) { + // Mc MARCHEN VOWEL SIGN I + if (0x11cb1 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] MARCHEN VOWEL SIGN U..MARCHEN VOWEL SIGN E + if (0x11cb2 <= code && code <= 0x11cb3) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x11cb5) { + // Mc MARCHEN VOWEL SIGN O + if (0x11cb4 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + if (code < 0x11d31) { + // Mn [2] MARCHEN SIGN ANUSVARA..MARCHEN SIGN CANDRABINDU + if (0x11cb5 <= code && code <= 0x11cb6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [6] MASARAM GONDI VOWEL SIGN AA..MASARAM GONDI VOWEL SIGN VOCALIC R + if (0x11d31 <= code && code <= 0x11d36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x11d46) { + if (code < 0x11d3c) { + // Mn MASARAM GONDI VOWEL SIGN E + if (0x11d3a === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11d3f) { + // Mn [2] MASARAM GONDI VOWEL SIGN AI..MASARAM GONDI VOWEL SIGN O + if (0x11d3c <= code && code <= 0x11d3d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [7] MASARAM GONDI VOWEL SIGN AU..MASARAM GONDI VIRAMA + if (0x11d3f <= code && code <= 0x11d45) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x11d47) { + // Lo MASARAM GONDI REPHA + if (0x11d46 === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + if (code < 0x11d8a) { + // Mn MASARAM GONDI RA-KARA + if (0x11d47 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [5] GUNJALA GONDI VOWEL SIGN AA..GUNJALA GONDI VOWEL SIGN UU + if (0x11d8a <= code && code <= 0x11d8e) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + } + else { + if (code < 0x11f36) { + if (code < 0x11ef3) { + if (code < 0x11d95) { + if (code < 0x11d93) { + // Mn [2] GUNJALA GONDI VOWEL SIGN EE..GUNJALA GONDI VOWEL SIGN AI + if (0x11d90 <= code && code <= 0x11d91) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] GUNJALA GONDI VOWEL SIGN OO..GUNJALA GONDI VOWEL SIGN AU + if (0x11d93 <= code && code <= 0x11d94) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11d96) { + // Mn GUNJALA GONDI SIGN ANUSVARA + if (0x11d95 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc GUNJALA GONDI SIGN VISARGA + if (0x11d96 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn GUNJALA GONDI VIRAMA + if (0x11d97 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x11f02) { + if (code < 0x11ef5) { + // Mn [2] MAKASAR VOWEL SIGN I..MAKASAR VOWEL SIGN U + if (0x11ef3 <= code && code <= 0x11ef4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x11f00) { + // Mc [2] MAKASAR VOWEL SIGN E..MAKASAR VOWEL SIGN O + if (0x11ef5 <= code && code <= 0x11ef6) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] KAWI SIGN CANDRABINDU..KAWI SIGN ANUSVARA + if (0x11f00 <= code && code <= 0x11f01) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x11f03) { + // Lo KAWI SIGN REPHA + if (0x11f02 === code) { + return boundaries_1.CLUSTER_BREAK.PREPEND; + } + } + else { + if (code < 0x11f34) { + // Mc KAWI SIGN VISARGA + if (0x11f03 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mc [2] KAWI VOWEL SIGN AA..KAWI VOWEL SIGN ALTERNATE AA + if (0x11f34 <= code && code <= 0x11f35) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + } + else { + if (code < 0x13430) { + if (code < 0x11f40) { + if (code < 0x11f3e) { + // Mn [5] KAWI VOWEL SIGN I..KAWI VOWEL SIGN VOCALIC R + if (0x11f36 <= code && code <= 0x11f3a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc [2] KAWI VOWEL SIGN E..KAWI VOWEL SIGN AI + if (0x11f3e <= code && code <= 0x11f3f) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x11f41) { + // Mn KAWI VOWEL SIGN EU + if (0x11f40 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc KAWI SIGN KILLER + if (0x11f41 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + // Mn KAWI CONJOINER + if (0x11f42 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x16af0) { + if (code < 0x13440) { + // Cf [16] EGYPTIAN HIEROGLYPH VERTICAL JOINER..EGYPTIAN HIEROGLYPH END WALLED ENCLOSURE + if (0x13430 <= code && code <= 0x1343f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0x13447) { + // Mn EGYPTIAN HIEROGLYPH MIRROR HORIZONTALLY + if (0x13440 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [15] EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT TOP START..EGYPTIAN HIEROGLYPH MODIFIER DAMAGED + if (0x13447 <= code && code <= 0x13455) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x16b30) { + // Mn [5] BASSA VAH COMBINING HIGH TONE..BASSA VAH COMBINING HIGH-LOW TONE + if (0x16af0 <= code && code <= 0x16af4) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x16f4f) { + // Mn [7] PAHAWH HMONG MARK CIM TUB..PAHAWH HMONG MARK CIM TAUM + if (0x16b30 <= code && code <= 0x16b36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn MIAO SIGN CONSONANT MODIFIER BAR + if (0x16f4f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + } + else { + if (code < 0x1da84) { + if (code < 0x1d167) { + if (code < 0x1bca0) { + if (code < 0x16fe4) { + if (code < 0x16f8f) { + // Mc [55] MIAO SIGN ASPIRATION..MIAO VOWEL SIGN UI + if (0x16f51 <= code && code <= 0x16f87) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [4] MIAO TONE RIGHT..MIAO TONE BELOW + if (0x16f8f <= code && code <= 0x16f92) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x16ff0) { + // Mn KHITAN SMALL SCRIPT FILLER + if (0x16fe4 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1bc9d) { + // Mc [2] VIETNAMESE ALTERNATE READING MARK CA..VIETNAMESE ALTERNATE READING MARK NHAY + if (0x16ff0 <= code && code <= 0x16ff1) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + else { + // Mn [2] DUPLOYAN THICK LETTER SELECTOR..DUPLOYAN DOUBLE MARK + if (0x1bc9d <= code && code <= 0x1bc9e) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1cf30) { + if (code < 0x1cf00) { + // Cf [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP + if (0x1bca0 <= code && code <= 0x1bca3) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Mn [46] ZNAMENNY COMBINING MARK GORAZDO NIZKO S KRYZHEM ON LEFT..ZNAMENNY COMBINING MARK KRYZH ON LEFT + if (0x1cf00 <= code && code <= 0x1cf2d) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1d165) { + // Mn [23] ZNAMENNY COMBINING TONAL RANGE MARK MRACHNO..ZNAMENNY PRIZNAK MODIFIER ROG + if (0x1cf30 <= code && code <= 0x1cf46) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc MUSICAL SYMBOL COMBINING STEM + if (0x1d165 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + // Mc MUSICAL SYMBOL COMBINING SPRECHGESANG STEM + if (0x1d166 === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + } + } + else { + if (code < 0x1d185) { + if (code < 0x1d16e) { + if (code < 0x1d16d) { + // Mn [3] MUSICAL SYMBOL COMBINING TREMOLO-1..MUSICAL SYMBOL COMBINING TREMOLO-3 + if (0x1d167 <= code && code <= 0x1d169) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mc MUSICAL SYMBOL COMBINING AUGMENTATION DOT + if (0x1d16d === code) { + return boundaries_1.CLUSTER_BREAK.SPACINGMARK; + } + } + } + else { + if (code < 0x1d173) { + // Mc [5] MUSICAL SYMBOL COMBINING FLAG-1..MUSICAL SYMBOL COMBINING FLAG-5 + if (0x1d16e <= code && code <= 0x1d172) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1d17b) { + // Cf [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE + if (0x1d173 <= code && code <= 0x1d17a) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Mn [8] MUSICAL SYMBOL COMBINING ACCENT..MUSICAL SYMBOL COMBINING LOURE + if (0x1d17b <= code && code <= 0x1d182) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1da00) { + if (code < 0x1d1aa) { + // Mn [7] MUSICAL SYMBOL COMBINING DOIT..MUSICAL SYMBOL COMBINING TRIPLE TONGUE + if (0x1d185 <= code && code <= 0x1d18b) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1d242) { + // Mn [4] MUSICAL SYMBOL COMBINING DOWN BOW..MUSICAL SYMBOL COMBINING SNAP PIZZICATO + if (0x1d1aa <= code && code <= 0x1d1ad) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [3] COMBINING GREEK MUSICAL TRISEME..COMBINING GREEK MUSICAL PENTASEME + if (0x1d242 <= code && code <= 0x1d244) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1da3b) { + // Mn [55] SIGNWRITING HEAD RIM..SIGNWRITING AIR SUCKING IN + if (0x1da00 <= code && code <= 0x1da36) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1da75) { + // Mn [50] SIGNWRITING MOUTH CLOSED NEUTRAL..SIGNWRITING EXCITEMENT + if (0x1da3b <= code && code <= 0x1da6c) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn SIGNWRITING UPPER BODY TILTING FROM HIP JOINTS + if (0x1da75 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + } + else { + if (code < 0x1e2ec) { + if (code < 0x1e01b) { + if (code < 0x1daa1) { + if (code < 0x1da9b) { + // Mn SIGNWRITING LOCATION HEAD NECK + if (0x1da84 === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [5] SIGNWRITING FILL MODIFIER-2..SIGNWRITING FILL MODIFIER-6 + if (0x1da9b <= code && code <= 0x1da9f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1e000) { + // Mn [15] SIGNWRITING ROTATION MODIFIER-2..SIGNWRITING ROTATION MODIFIER-16 + if (0x1daa1 <= code && code <= 0x1daaf) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1e008) { + // Mn [7] COMBINING GLAGOLITIC LETTER AZU..COMBINING GLAGOLITIC LETTER ZHIVETE + if (0x1e000 <= code && code <= 0x1e006) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [17] COMBINING GLAGOLITIC LETTER ZEMLJA..COMBINING GLAGOLITIC LETTER HERU + if (0x1e008 <= code && code <= 0x1e018) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + else { + if (code < 0x1e08f) { + if (code < 0x1e023) { + // Mn [7] COMBINING GLAGOLITIC LETTER SHTA..COMBINING GLAGOLITIC LETTER YATI + if (0x1e01b <= code && code <= 0x1e021) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1e026) { + // Mn [2] COMBINING GLAGOLITIC LETTER YU..COMBINING GLAGOLITIC LETTER SMALL YUS + if (0x1e023 <= code && code <= 0x1e024) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [5] COMBINING GLAGOLITIC LETTER YO..COMBINING GLAGOLITIC LETTER FITA + if (0x1e026 <= code && code <= 0x1e02a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0x1e130) { + // Mn COMBINING CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I + if (0x1e08f === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1e2ae) { + // Mn [7] NYIAKENG PUACHUE HMONG TONE-B..NYIAKENG PUACHUE HMONG TONE-D + if (0x1e130 <= code && code <= 0x1e136) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn TOTO SIGN RISING TONE + if (0x1e2ae === code) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + } + } + else { + if (code < 0x1f3fb) { + if (code < 0x1e8d0) { + if (code < 0x1e4ec) { + // Mn [4] WANCHO TONE TUP..WANCHO TONE KOINI + if (0x1e2ec <= code && code <= 0x1e2ef) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Mn [4] NAG MUNDARI SIGN MUHOR..NAG MUNDARI SIGN SUTUH + if (0x1e4ec <= code && code <= 0x1e4ef) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + else { + if (code < 0x1e944) { + // Mn [7] MENDE KIKAKUI COMBINING NUMBER TEENS..MENDE KIKAKUI COMBINING NUMBER MILLIONS + if (0x1e8d0 <= code && code <= 0x1e8d6) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0x1f1e6) { + // Mn [7] ADLAM ALIF LENGTHENER..ADLAM NUKTA + if (0x1e944 <= code && code <= 0x1e94a) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // So [26] REGIONAL INDICATOR SYMBOL LETTER A..REGIONAL INDICATOR SYMBOL LETTER Z + if (0x1f1e6 <= code && code <= 0x1f1ff) { + return boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR; + } + } + } + } + } + else { + if (code < 0xe0080) { + if (code < 0xe0000) { + // Sk [5] EMOJI MODIFIER FITZPATRICK TYPE-1-2..EMOJI MODIFIER FITZPATRICK TYPE-6 + if (0x1f3fb <= code && code <= 0x1f3ff) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + if (code < 0xe0020) { + // Cn + // Cf LANGUAGE TAG + // Cn [30] .. + if (0xe0000 <= code && code <= 0xe001f) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + // Cf [96] TAG SPACE..CANCEL TAG + if (0xe0020 <= code && code <= 0xe007f) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + } + } + else { + if (code < 0xe0100) { + // Cn [128] .. + if (0xe0080 <= code && code <= 0xe00ff) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + else { + if (code < 0xe01f0) { + // Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256 + if (0xe0100 <= code && code <= 0xe01ef) { + return boundaries_1.CLUSTER_BREAK.EXTEND; + } + } + else { + // Cn [3600] .. + if (0xe01f0 <= code && code <= 0xe0fff) { + return boundaries_1.CLUSTER_BREAK.CONTROL; + } + } + } + } + } + } + } + } + } + } + } + } + // unlisted code points are treated as a break property of "Other" + return boundaries_1.CLUSTER_BREAK.OTHER; + } + /** + * Given a Unicode code point, returns if symbol is an extended pictographic or some other break + * @param code {number} Unicode code point + * @returns {number} + */ + static getEmojiProperty(code) { + // emoji property taken from: + // https://www.unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt + // and generated by + // node ./scripts/generate-emoji-extended-pictographic.js + if (code < 0x27b0) { + if (code < 0x2600) { + if (code < 0x2328) { + if (code < 0x2122) { + if (code < 0x203c) { + // E0.6 [1] (©️) copyright + if (0xa9 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (®️) registered + if (0xae === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (‼️) double exclamation mark + if (0x203c === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (⁉️) exclamation question mark + if (0x2049 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x2194) { + // E0.6 [1] (™️) trade mark + if (0x2122 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (ℹ️) information + if (0x2139 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x21a9) { + // E0.6 [6] (↔️..↙️) left-right arrow..down-left arrow + if (0x2194 <= code && code <= 0x2199) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x231a) { + // E0.6 [2] (↩️..↪️) right arrow curving left..left arrow curving right + if (0x21a9 <= code && code <= 0x21aa) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [2] (⌚..⌛) watch..hourglass done + if (0x231a <= code && code <= 0x231b) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + else { + if (code < 0x24c2) { + if (code < 0x23cf) { + // E1.0 [1] (⌨️) keyboard + if (0x2328 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.0 [1] (⎈) HELM SYMBOL + if (0x2388 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x23e9) { + // E1.0 [1] (⏏️) eject button + if (0x23cf === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x23f8) { + // E0.6 [4] (⏩..⏬) fast-forward button..fast down button + // E0.7 [2] (⏭️..⏮️) next track button..last track button + // E1.0 [1] (⏯️) play or pause button + // E0.6 [1] (⏰) alarm clock + // E1.0 [2] (⏱️..⏲️) stopwatch..timer clock + // E0.6 [1] (⏳) hourglass not done + if (0x23e9 <= code && code <= 0x23f3) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.7 [3] (⏸️..⏺️) pause button..record button + if (0x23f8 <= code && code <= 0x23fa) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x25b6) { + if (code < 0x25aa) { + // E0.6 [1] (Ⓜ️) circled M + if (0x24c2 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [2] (▪️..▫️) black small square..white small square + if (0x25aa <= code && code <= 0x25ab) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x25c0) { + // E0.6 [1] (▶️) play button + if (0x25b6 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x25fb) { + // E0.6 [1] (◀️) reverse button + if (0x25c0 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [4] (◻️..◾) white medium square..black medium-small square + if (0x25fb <= code && code <= 0x25fe) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + } + else { + if (code < 0x2733) { + if (code < 0x2714) { + if (code < 0x2614) { + if (code < 0x2607) { + // E0.6 [2] (☀️..☁️) sun..cloud + // E0.7 [2] (☂️..☃️) umbrella..snowman + // E1.0 [1] (☄️) comet + // E0.0 [1] (★) BLACK STAR + if (0x2600 <= code && code <= 0x2605) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [7] (☇..☍) LIGHTNING..OPPOSITION + // E0.6 [1] (☎️) telephone + // E0.0 [2] (☏..☐) WHITE TELEPHONE..BALLOT BOX + // E0.6 [1] (☑️) check box with check + // E0.0 [1] (☒) BALLOT BOX WITH X + if (0x2607 <= code && code <= 0x2612) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x2690) { + // E0.6 [2] (☔..☕) umbrella with rain drops..hot beverage + // E0.0 [2] (☖..☗) WHITE SHOGI PIECE..BLACK SHOGI PIECE + // E1.0 [1] (☘️) shamrock + // E0.0 [4] (☙..☜) REVERSED ROTATED FLORAL HEART BULLET..WHITE LEFT POINTING INDEX + // E0.6 [1] (☝️) index pointing up + // E0.0 [2] (☞..☟) WHITE RIGHT POINTING INDEX..WHITE DOWN POINTING INDEX + // E1.0 [1] (☠️) skull and crossbones + // E0.0 [1] (☡) CAUTION SIGN + // E1.0 [2] (☢️..☣️) radioactive..biohazard + // E0.0 [2] (☤..☥) CADUCEUS..ANKH + // E1.0 [1] (☦️) orthodox cross + // E0.0 [3] (☧..☩) CHI RHO..CROSS OF JERUSALEM + // E0.7 [1] (☪️) star and crescent + // E0.0 [3] (☫..☭) FARSI SYMBOL..HAMMER AND SICKLE + // E1.0 [1] (☮️) peace symbol + // E0.7 [1] (☯️) yin yang + // E0.0 [8] (☰..☷) TRIGRAM FOR HEAVEN..TRIGRAM FOR EARTH + // E0.7 [2] (☸️..☹️) wheel of dharma..frowning face + // E0.6 [1] (☺️) smiling face + // E0.0 [5] (☻..☿) BLACK SMILING FACE..MERCURY + // E4.0 [1] (♀️) female sign + // E0.0 [1] (♁) EARTH + // E4.0 [1] (♂️) male sign + // E0.0 [5] (♃..♇) JUPITER..PLUTO + // E0.6 [12] (♈..♓) Aries..Pisces + // E0.0 [11] (♔..♞) WHITE CHESS KING..BLACK CHESS KNIGHT + // E11.0 [1] (♟️) chess pawn + // E0.6 [1] (♠️) spade suit + // E0.0 [2] (♡..♢) WHITE HEART SUIT..WHITE DIAMOND SUIT + // E0.6 [1] (♣️) club suit + // E0.0 [1] (♤) WHITE SPADE SUIT + // E0.6 [2] (♥️..♦️) heart suit..diamond suit + // E0.0 [1] (♧) WHITE CLUB SUIT + // E0.6 [1] (♨️) hot springs + // E0.0 [18] (♩..♺) QUARTER NOTE..RECYCLING SYMBOL FOR GENERIC MATERIALS + // E0.6 [1] (♻️) recycling symbol + // E0.0 [2] (♼..♽) RECYCLED PAPER SYMBOL..PARTIALLY-RECYCLED PAPER SYMBOL + // E11.0 [1] (♾️) infinity + // E0.6 [1] (♿) wheelchair symbol + // E0.0 [6] (⚀..⚅) DIE FACE-1..DIE FACE-6 + if (0x2614 <= code && code <= 0x2685) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x2708) { + // E0.0 [2] (⚐..⚑) WHITE FLAG..BLACK FLAG + // E1.0 [1] (⚒️) hammer and pick + // E0.6 [1] (⚓) anchor + // E1.0 [1] (⚔️) crossed swords + // E4.0 [1] (⚕️) medical symbol + // E1.0 [2] (⚖️..⚗️) balance scale..alembic + // E0.0 [1] (⚘) FLOWER + // E1.0 [1] (⚙️) gear + // E0.0 [1] (⚚) STAFF OF HERMES + // E1.0 [2] (⚛️..⚜️) atom symbol..fleur-de-lis + // E0.0 [3] (⚝..⚟) OUTLINED WHITE STAR..THREE LINES CONVERGING LEFT + // E0.6 [2] (⚠️..⚡) warning..high voltage + // E0.0 [5] (⚢..⚦) DOUBLED FEMALE SIGN..MALE WITH STROKE SIGN + // E13.0 [1] (⚧️) transgender symbol + // E0.0 [2] (⚨..⚩) VERTICAL MALE WITH STROKE SIGN..HORIZONTAL MALE WITH STROKE SIGN + // E0.6 [2] (⚪..⚫) white circle..black circle + // E0.0 [4] (⚬..⚯) MEDIUM SMALL WHITE CIRCLE..UNMARRIED PARTNERSHIP SYMBOL + // E1.0 [2] (⚰️..⚱️) coffin..funeral urn + // E0.0 [11] (⚲..⚼) NEUTER..SESQUIQUADRATE + // E0.6 [2] (⚽..⚾) soccer ball..baseball + // E0.0 [5] (⚿..⛃) SQUARED KEY..BLACK DRAUGHTS KING + // E0.6 [2] (⛄..⛅) snowman without snow..sun behind cloud + // E0.0 [2] (⛆..⛇) RAIN..BLACK SNOWMAN + // E0.7 [1] (⛈️) cloud with lightning and rain + // E0.0 [5] (⛉..⛍) TURNED WHITE SHOGI PIECE..DISABLED CAR + // E0.6 [1] (⛎) Ophiuchus + // E0.7 [1] (⛏️) pick + // E0.0 [1] (⛐) CAR SLIDING + // E0.7 [1] (⛑️) rescue worker’s helmet + // E0.0 [1] (⛒) CIRCLED CROSSING LANES + // E0.7 [1] (⛓️) chains + // E0.6 [1] (⛔) no entry + // E0.0 [20] (⛕..⛨) ALTERNATE ONE-WAY LEFT WAY TRAFFIC..BLACK CROSS ON SHIELD + // E0.7 [1] (⛩️) shinto shrine + // E0.6 [1] (⛪) church + // E0.0 [5] (⛫..⛯) CASTLE..MAP SYMBOL FOR LIGHTHOUSE + // E0.7 [2] (⛰️..⛱️) mountain..umbrella on ground + // E0.6 [2] (⛲..⛳) fountain..flag in hole + // E0.7 [1] (⛴️) ferry + // E0.6 [1] (⛵) sailboat + // E0.0 [1] (⛶) SQUARE FOUR CORNERS + // E0.7 [3] (⛷️..⛹️) skier..person bouncing ball + // E0.6 [1] (⛺) tent + // E0.0 [2] (⛻..⛼) JAPANESE BANK SYMBOL..HEADSTONE GRAVEYARD SYMBOL + // E0.6 [1] (⛽) fuel pump + // E0.0 [4] (⛾..✁) CUP ON BLACK SQUARE..UPPER BLADE SCISSORS + // E0.6 [1] (✂️) scissors + // E0.0 [2] (✃..✄) LOWER BLADE SCISSORS..WHITE SCISSORS + // E0.6 [1] (✅) check mark button + if (0x2690 <= code && code <= 0x2705) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [5] (✈️..✌️) airplane..victory hand + // E0.7 [1] (✍️) writing hand + // E0.0 [1] (✎) LOWER RIGHT PENCIL + // E0.6 [1] (✏️) pencil + // E0.0 [2] (✐..✑) UPPER RIGHT PENCIL..WHITE NIB + // E0.6 [1] (✒️) black nib + if (0x2708 <= code && code <= 0x2712) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x271d) { + // E0.6 [1] (✔️) check mark + if (0x2714 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (✖️) multiply + if (0x2716 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x2721) { + // E0.7 [1] (✝️) latin cross + if (0x271d === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.7 [1] (✡️) star of David + if (0x2721 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (✨) sparkles + if (0x2728 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x2753) { + if (code < 0x2747) { + if (code < 0x2744) { + // E0.6 [2] (✳️..✴️) eight-spoked asterisk..eight-pointed star + if (0x2733 <= code && code <= 0x2734) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (❄️) snowflake + if (0x2744 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x274c) { + // E0.6 [1] (❇️) sparkle + if (0x2747 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (❌) cross mark + if (0x274c === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (❎) cross mark button + if (0x274e === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + else { + if (code < 0x2763) { + if (code < 0x2757) { + // E0.6 [3] (❓..❕) red question mark..white exclamation mark + if (0x2753 <= code && code <= 0x2755) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (❗) red exclamation mark + if (0x2757 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x2795) { + // E1.0 [1] (❣️) heart exclamation + // E0.6 [1] (❤️) red heart + // E0.0 [3] (❥..❧) ROTATED HEAVY BLACK HEART BULLET..ROTATED FLORAL HEART BULLET + if (0x2763 <= code && code <= 0x2767) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x27a1) { + // E0.6 [3] (➕..➗) plus..divide + if (0x2795 <= code && code <= 0x2797) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (➡️) right arrow + if (0x27a1 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + } + } + else { + if (code < 0x1f201) { + if (code < 0x3297) { + if (code < 0x2b1b) { + if (code < 0x2934) { + // E0.6 [1] (➰) curly loop + if (0x27b0 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E1.0 [1] (➿) double curly loop + if (0x27bf === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x2b05) { + // E0.6 [2] (⤴️..⤵️) right arrow curving up..right arrow curving down + if (0x2934 <= code && code <= 0x2935) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [3] (⬅️..⬇️) left arrow..down arrow + if (0x2b05 <= code && code <= 0x2b07) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + else { + if (code < 0x2b55) { + if (code < 0x2b50) { + // E0.6 [2] (⬛..⬜) black large square..white large square + if (0x2b1b <= code && code <= 0x2b1c) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (⭐) star + if (0x2b50 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x3030) { + // E0.6 [1] (⭕) hollow red circle + if (0x2b55 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (〰️) wavy dash + if (0x3030 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (〽️) part alternation mark + if (0x303d === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x1f16c) { + if (code < 0x1f000) { + // E0.6 [1] (㊗️) Japanese “congratulations” button + if (0x3297 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + // E0.6 [1] (㊙️) Japanese “secret” button + if (0x3299 === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f10d) { + // E0.0 [4] (🀀..🀃) MAHJONG TILE EAST WIND..MAHJONG TILE NORTH WIND + // E0.6 [1] (🀄) mahjong red dragon + // E0.0 [202] (🀅..🃎) MAHJONG TILE GREEN DRAGON..PLAYING CARD KING OF DIAMONDS + // E0.6 [1] (🃏) joker + // E0.0 [48] (🃐..🃿) .. + if (0x1f000 <= code && code <= 0x1f0ff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f12f) { + // E0.0 [3] (🄍..🄏) CIRCLED ZERO WITH SLASH..CIRCLED DOLLAR SIGN WITH OVERLAID BACKSLASH + if (0x1f10d <= code && code <= 0x1f10f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [1] (🄯) COPYLEFT SYMBOL + if (0x1f12f === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x1f18e) { + if (code < 0x1f17e) { + // E0.0 [4] (🅬..🅯) RAISED MR SIGN..CIRCLED HUMAN FIGURE + // E0.6 [2] (🅰️..🅱️) A button (blood type)..B button (blood type) + if (0x1f16c <= code && code <= 0x1f171) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [2] (🅾️..🅿️) O button (blood type)..P button + if (0x1f17e <= code && code <= 0x1f17f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f191) { + // E0.6 [1] (🆎) AB button (blood type) + if (0x1f18e === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f1ad) { + // E0.6 [10] (🆑..🆚) CL button..VS button + if (0x1f191 <= code && code <= 0x1f19a) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [57] (🆭..🇥) MASK WORK SYMBOL.. + if (0x1f1ad <= code && code <= 0x1f1e5) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + } + else { + if (code < 0x1f7d5) { + if (code < 0x1f249) { + if (code < 0x1f22f) { + if (code < 0x1f21a) { + // E0.6 [2] (🈁..🈂️) Japanese “here” button..Japanese “service charge” button + // E0.0 [13] (🈃..🈏) .. + if (0x1f201 <= code && code <= 0x1f20f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.6 [1] (🈚) Japanese “free of charge” button + if (0x1f21a === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f232) { + // E0.6 [1] (🈯) Japanese “reserved” button + if (0x1f22f === code) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f23c) { + // E0.6 [9] (🈲..🈺) Japanese “prohibited” button..Japanese “open for business” button + if (0x1f232 <= code && code <= 0x1f23a) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [4] (🈼..🈿) .. + if (0x1f23c <= code && code <= 0x1f23f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x1f546) { + if (code < 0x1f400) { + // E0.0 [7] (🉉..🉏) .. + // E0.6 [2] (🉐..🉑) Japanese “bargain” button..Japanese “acceptable” button + // E0.0 [174] (🉒..🋿) .. + // E0.6 [13] (🌀..🌌) cyclone..milky way + // E0.7 [2] (🌍..🌎) globe showing Europe-Africa..globe showing Americas + // E0.6 [1] (🌏) globe showing Asia-Australia + // E1.0 [1] (🌐) globe with meridians + // E0.6 [1] (🌑) new moon + // E1.0 [1] (🌒) waxing crescent moon + // E0.6 [3] (🌓..🌕) first quarter moon..full moon + // E1.0 [3] (🌖..🌘) waning gibbous moon..waning crescent moon + // E0.6 [1] (🌙) crescent moon + // E1.0 [1] (🌚) new moon face + // E0.6 [1] (🌛) first quarter moon face + // E0.7 [1] (🌜) last quarter moon face + // E1.0 [2] (🌝..🌞) full moon face..sun with face + // E0.6 [2] (🌟..🌠) glowing star..shooting star + // E0.7 [1] (🌡️) thermometer + // E0.0 [2] (🌢..🌣) BLACK DROPLET..WHITE SUN + // E0.7 [9] (🌤️..🌬️) sun behind small cloud..wind face + // E1.0 [3] (🌭..🌯) hot dog..burrito + // E0.6 [2] (🌰..🌱) chestnut..seedling + // E1.0 [2] (🌲..🌳) evergreen tree..deciduous tree + // E0.6 [2] (🌴..🌵) palm tree..cactus + // E0.7 [1] (🌶️) hot pepper + // E0.6 [20] (🌷..🍊) tulip..tangerine + // E1.0 [1] (🍋) lemon + // E0.6 [4] (🍌..🍏) banana..green apple + // E1.0 [1] (🍐) pear + // E0.6 [43] (🍑..🍻) peach..clinking beer mugs + // E1.0 [1] (🍼) baby bottle + // E0.7 [1] (🍽️) fork and knife with plate + // E1.0 [2] (🍾..🍿) bottle with popping cork..popcorn + // E0.6 [20] (🎀..🎓) ribbon..graduation cap + // E0.0 [2] (🎔..🎕) HEART WITH TIP ON THE LEFT..BOUQUET OF FLOWERS + // E0.7 [2] (🎖️..🎗️) military medal..reminder ribbon + // E0.0 [1] (🎘) MUSICAL KEYBOARD WITH JACKS + // E0.7 [3] (🎙️..🎛️) studio microphone..control knobs + // E0.0 [2] (🎜..🎝) BEAMED ASCENDING MUSICAL NOTES..BEAMED DESCENDING MUSICAL NOTES + // E0.7 [2] (🎞️..🎟️) film frames..admission tickets + // E0.6 [37] (🎠..🏄) carousel horse..person surfing + // E1.0 [1] (🏅) sports medal + // E0.6 [1] (🏆) trophy + // E1.0 [1] (🏇) horse racing + // E0.6 [1] (🏈) american football + // E1.0 [1] (🏉) rugby football + // E0.6 [1] (🏊) person swimming + // E0.7 [4] (🏋️..🏎️) person lifting weights..racing car + // E1.0 [5] (🏏..🏓) cricket game..ping pong + // E0.7 [12] (🏔️..🏟️) snow-capped mountain..stadium + // E0.6 [4] (🏠..🏣) house..Japanese post office + // E1.0 [1] (🏤) post office + // E0.6 [12] (🏥..🏰) hospital..castle + // E0.0 [2] (🏱..🏲) WHITE PENNANT..BLACK PENNANT + // E0.7 [1] (🏳️) white flag + // E1.0 [1] (🏴) black flag + // E0.7 [1] (🏵️) rosette + // E0.0 [1] (🏶) BLACK ROSETTE + // E0.7 [1] (🏷️) label + // E1.0 [3] (🏸..🏺) badminton..amphora + if (0x1f249 <= code && code <= 0x1f3fa) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E1.0 [8] (🐀..🐇) rat..rabbit + // E0.7 [1] (🐈) cat + // E1.0 [3] (🐉..🐋) dragon..whale + // E0.6 [3] (🐌..🐎) snail..horse + // E1.0 [2] (🐏..🐐) ram..goat + // E0.6 [2] (🐑..🐒) ewe..monkey + // E1.0 [1] (🐓) rooster + // E0.6 [1] (🐔) chicken + // E0.7 [1] (🐕) dog + // E1.0 [1] (🐖) pig + // E0.6 [19] (🐗..🐩) boar..poodle + // E1.0 [1] (🐪) camel + // E0.6 [20] (🐫..🐾) two-hump camel..paw prints + // E0.7 [1] (🐿️) chipmunk + // E0.6 [1] (👀) eyes + // E0.7 [1] (👁️) eye + // E0.6 [35] (👂..👤) ear..bust in silhouette + // E1.0 [1] (👥) busts in silhouette + // E0.6 [6] (👦..👫) boy..woman and man holding hands + // E1.0 [2] (👬..👭) men holding hands..women holding hands + // E0.6 [63] (👮..💬) police officer..speech balloon + // E1.0 [1] (💭) thought balloon + // E0.6 [8] (💮..💵) white flower..dollar banknote + // E1.0 [2] (💶..💷) euro banknote..pound banknote + // E0.6 [52] (💸..📫) money with wings..closed mailbox with raised flag + // E0.7 [2] (📬..📭) open mailbox with raised flag..open mailbox with lowered flag + // E0.6 [1] (📮) postbox + // E1.0 [1] (📯) postal horn + // E0.6 [5] (📰..📴) newspaper..mobile phone off + // E1.0 [1] (📵) no mobile phones + // E0.6 [2] (📶..📷) antenna bars..camera + // E1.0 [1] (📸) camera with flash + // E0.6 [4] (📹..📼) video camera..videocassette + // E0.7 [1] (📽️) film projector + // E0.0 [1] (📾) PORTABLE STEREO + // E1.0 [4] (📿..🔂) prayer beads..repeat single button + // E0.6 [1] (🔃) clockwise vertical arrows + // E1.0 [4] (🔄..🔇) counterclockwise arrows button..muted speaker + // E0.7 [1] (🔈) speaker low volume + // E1.0 [1] (🔉) speaker medium volume + // E0.6 [11] (🔊..🔔) speaker high volume..bell + // E1.0 [1] (🔕) bell with slash + // E0.6 [22] (🔖..🔫) bookmark..water pistol + // E1.0 [2] (🔬..🔭) microscope..telescope + // E0.6 [16] (🔮..🔽) crystal ball..downwards button + if (0x1f400 <= code && code <= 0x1f53d) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f680) { + // E0.0 [3] (🕆..🕈) WHITE LATIN CROSS..CELTIC CROSS + // E0.7 [2] (🕉️..🕊️) om..dove + // E1.0 [4] (🕋..🕎) kaaba..menorah + // E0.0 [1] (🕏) BOWL OF HYGIEIA + // E0.6 [12] (🕐..🕛) one o’clock..twelve o’clock + // E0.7 [12] (🕜..🕧) one-thirty..twelve-thirty + // E0.0 [7] (🕨..🕮) RIGHT SPEAKER..BOOK + // E0.7 [2] (🕯️..🕰️) candle..mantelpiece clock + // E0.0 [2] (🕱..🕲) BLACK SKULL AND CROSSBONES..NO PIRACY + // E0.7 [7] (🕳️..🕹️) hole..joystick + // E3.0 [1] (🕺) man dancing + // E0.0 [12] (🕻..🖆) LEFT HAND TELEPHONE RECEIVER..PEN OVER STAMPED ENVELOPE + // E0.7 [1] (🖇️) linked paperclips + // E0.0 [2] (🖈..🖉) BLACK PUSHPIN..LOWER LEFT PENCIL + // E0.7 [4] (🖊️..🖍️) pen..crayon + // E0.0 [2] (🖎..🖏) LEFT WRITING HAND..TURNED OK HAND SIGN + // E0.7 [1] (🖐️) hand with fingers splayed + // E0.0 [4] (🖑..🖔) REVERSED RAISED HAND WITH FINGERS SPLAYED..REVERSED VICTORY HAND + // E1.0 [2] (🖕..🖖) middle finger..vulcan salute + // E0.0 [13] (🖗..🖣) WHITE DOWN POINTING LEFT HAND INDEX..BLACK DOWN POINTING BACKHAND INDEX + // E3.0 [1] (🖤) black heart + // E0.7 [1] (🖥️) desktop computer + // E0.0 [2] (🖦..🖧) KEYBOARD AND MOUSE..THREE NETWORKED COMPUTERS + // E0.7 [1] (🖨️) printer + // E0.0 [8] (🖩..🖰) POCKET CALCULATOR..TWO BUTTON MOUSE + // E0.7 [2] (🖱️..🖲️) computer mouse..trackball + // E0.0 [9] (🖳..🖻) OLD PERSONAL COMPUTER..DOCUMENT WITH PICTURE + // E0.7 [1] (🖼️) framed picture + // E0.0 [5] (🖽..🗁) FRAME WITH TILES..OPEN FOLDER + // E0.7 [3] (🗂️..🗄️) card index dividers..file cabinet + // E0.0 [12] (🗅..🗐) EMPTY NOTE..PAGES + // E0.7 [3] (🗑️..🗓️) wastebasket..spiral calendar + // E0.0 [8] (🗔..🗛) DESKTOP WINDOW..DECREASE FONT SIZE SYMBOL + // E0.7 [3] (🗜️..🗞️) clamp..rolled-up newspaper + // E0.0 [2] (🗟..🗠) PAGE WITH CIRCLED TEXT..STOCK CHART + // E0.7 [1] (🗡️) dagger + // E0.0 [1] (🗢) LIPS + // E0.7 [1] (🗣️) speaking head + // E0.0 [4] (🗤..🗧) THREE RAYS ABOVE..THREE RAYS RIGHT + // E2.0 [1] (🗨️) left speech bubble + // E0.0 [6] (🗩..🗮) RIGHT SPEECH BUBBLE..LEFT ANGER BUBBLE + // E0.7 [1] (🗯️) right anger bubble + // E0.0 [3] (🗰..🗲) MOOD BUBBLE..LIGHTNING MOOD + // E0.7 [1] (🗳️) ballot box with ballot + // E0.0 [6] (🗴..🗹) BALLOT SCRIPT X..BALLOT BOX WITH BOLD CHECK + // E0.7 [1] (🗺️) world map + // E0.6 [5] (🗻..🗿) mount fuji..moai + // E1.0 [1] (😀) grinning face + // E0.6 [6] (😁..😆) beaming face with smiling eyes..grinning squinting face + // E1.0 [2] (😇..😈) smiling face with halo..smiling face with horns + // E0.6 [5] (😉..😍) winking face..smiling face with heart-eyes + // E1.0 [1] (😎) smiling face with sunglasses + // E0.6 [1] (😏) smirking face + // E0.7 [1] (😐) neutral face + // E1.0 [1] (😑) expressionless face + // E0.6 [3] (😒..😔) unamused face..pensive face + // E1.0 [1] (😕) confused face + // E0.6 [1] (😖) confounded face + // E1.0 [1] (😗) kissing face + // E0.6 [1] (😘) face blowing a kiss + // E1.0 [1] (😙) kissing face with smiling eyes + // E0.6 [1] (😚) kissing face with closed eyes + // E1.0 [1] (😛) face with tongue + // E0.6 [3] (😜..😞) winking face with tongue..disappointed face + // E1.0 [1] (😟) worried face + // E0.6 [6] (😠..😥) angry face..sad but relieved face + // E1.0 [2] (😦..😧) frowning face with open mouth..anguished face + // E0.6 [4] (😨..😫) fearful face..tired face + // E1.0 [1] (😬) grimacing face + // E0.6 [1] (😭) loudly crying face + // E1.0 [2] (😮..😯) face with open mouth..hushed face + // E0.6 [4] (😰..😳) anxious face with sweat..flushed face + // E1.0 [1] (😴) sleeping face + // E0.6 [1] (😵) face with crossed-out eyes + // E1.0 [1] (😶) face without mouth + // E0.6 [10] (😷..🙀) face with medical mask..weary cat + // E1.0 [4] (🙁..🙄) slightly frowning face..face with rolling eyes + // E0.6 [11] (🙅..🙏) person gesturing NO..folded hands + if (0x1f546 <= code && code <= 0x1f64f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f774) { + // E0.6 [1] (🚀) rocket + // E1.0 [2] (🚁..🚂) helicopter..locomotive + // E0.6 [3] (🚃..🚅) railway car..bullet train + // E1.0 [1] (🚆) train + // E0.6 [1] (🚇) metro + // E1.0 [1] (🚈) light rail + // E0.6 [1] (🚉) station + // E1.0 [2] (🚊..🚋) tram..tram car + // E0.6 [1] (🚌) bus + // E0.7 [1] (🚍) oncoming bus + // E1.0 [1] (🚎) trolleybus + // E0.6 [1] (🚏) bus stop + // E1.0 [1] (🚐) minibus + // E0.6 [3] (🚑..🚓) ambulance..police car + // E0.7 [1] (🚔) oncoming police car + // E0.6 [1] (🚕) taxi + // E1.0 [1] (🚖) oncoming taxi + // E0.6 [1] (🚗) automobile + // E0.7 [1] (🚘) oncoming automobile + // E0.6 [2] (🚙..🚚) sport utility vehicle..delivery truck + // E1.0 [7] (🚛..🚡) articulated lorry..aerial tramway + // E0.6 [1] (🚢) ship + // E1.0 [1] (🚣) person rowing boat + // E0.6 [2] (🚤..🚥) speedboat..horizontal traffic light + // E1.0 [1] (🚦) vertical traffic light + // E0.6 [7] (🚧..🚭) construction..no smoking + // E1.0 [4] (🚮..🚱) litter in bin sign..non-potable water + // E0.6 [1] (🚲) bicycle + // E1.0 [3] (🚳..🚵) no bicycles..person mountain biking + // E0.6 [1] (🚶) person walking + // E1.0 [2] (🚷..🚸) no pedestrians..children crossing + // E0.6 [6] (🚹..🚾) men’s room..water closet + // E1.0 [1] (🚿) shower + // E0.6 [1] (🛀) person taking bath + // E1.0 [5] (🛁..🛅) bathtub..left luggage + // E0.0 [5] (🛆..🛊) TRIANGLE WITH ROUNDED CORNERS..GIRLS SYMBOL + // E0.7 [1] (🛋️) couch and lamp + // E1.0 [1] (🛌) person in bed + // E0.7 [3] (🛍️..🛏️) shopping bags..bed + // E1.0 [1] (🛐) place of worship + // E3.0 [2] (🛑..🛒) stop sign..shopping cart + // E0.0 [2] (🛓..🛔) STUPA..PAGODA + // E12.0 [1] (🛕) hindu temple + // E13.0 [2] (🛖..🛗) hut..elevator + // E0.0 [4] (🛘..🛛) .. + // E15.0 [1] (🛜) wireless + // E14.0 [3] (🛝..🛟) playground slide..ring buoy + // E0.7 [6] (🛠️..🛥️) hammer and wrench..motor boat + // E0.0 [3] (🛦..🛨) UP-POINTING MILITARY AIRPLANE..UP-POINTING SMALL AIRPLANE + // E0.7 [1] (🛩️) small airplane + // E0.0 [1] (🛪) NORTHEAST-POINTING AIRPLANE + // E1.0 [2] (🛫..🛬) airplane departure..airplane arrival + // E0.0 [3] (🛭..🛯) .. + // E0.7 [1] (🛰️) satellite + // E0.0 [2] (🛱..🛲) ONCOMING FIRE ENGINE..DIESEL LOCOMOTIVE + // E0.7 [1] (🛳️) passenger ship + // E3.0 [3] (🛴..🛶) kick scooter..canoe + // E5.0 [2] (🛷..🛸) sled..flying saucer + // E11.0 [1] (🛹) skateboard + // E12.0 [1] (🛺) auto rickshaw + // E13.0 [2] (🛻..🛼) pickup truck..roller skate + // E0.0 [3] (🛽..🛿) .. + if (0x1f680 <= code && code <= 0x1f6ff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [12] (🝴..🝿) LOT OF FORTUNE..ORCUS + if (0x1f774 <= code && code <= 0x1f77f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + else { + if (code < 0x1f8ae) { + if (code < 0x1f848) { + if (code < 0x1f80c) { + // E0.0 [11] (🟕..🟟) CIRCLED TRIANGLE.. + // E12.0 [12] (🟠..🟫) orange circle..brown square + // E0.0 [4] (🟬..🟯) .. + // E14.0 [1] (🟰) heavy equals sign + // E0.0 [15] (🟱..🟿) .. + if (0x1f7d5 <= code && code <= 0x1f7ff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [4] (🠌..🠏) .. + if (0x1f80c <= code && code <= 0x1f80f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f85a) { + // E0.0 [8] (🡈..🡏) .. + if (0x1f848 <= code && code <= 0x1f84f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1f888) { + // E0.0 [6] (🡚..🡟) .. + if (0x1f85a <= code && code <= 0x1f85f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0 [8] (🢈..🢏) .. + if (0x1f888 <= code && code <= 0x1f88f) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + else { + if (code < 0x1f93c) { + if (code < 0x1f90c) { + // E0.0 [82] (🢮..🣿) .. + if (0x1f8ae <= code && code <= 0x1f8ff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E13.0 [1] (🤌) pinched fingers + // E12.0 [3] (🤍..🤏) white heart..pinching hand + // E1.0 [9] (🤐..🤘) zipper-mouth face..sign of the horns + // E3.0 [6] (🤙..🤞) call me hand..crossed fingers + // E5.0 [1] (🤟) love-you gesture + // E3.0 [8] (🤠..🤧) cowboy hat face..sneezing face + // E5.0 [8] (🤨..🤯) face with raised eyebrow..exploding head + // E3.0 [1] (🤰) pregnant woman + // E5.0 [2] (🤱..🤲) breast-feeding..palms up together + // E3.0 [8] (🤳..🤺) selfie..person fencing + if (0x1f90c <= code && code <= 0x1f93a) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + else { + if (code < 0x1f947) { + // E3.0 [3] (🤼..🤾) people wrestling..person playing handball + // E12.0 [1] (🤿) diving mask + // E3.0 [6] (🥀..🥅) wilted flower..goal net + if (0x1f93c <= code && code <= 0x1f945) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + if (code < 0x1fc00) { + // E3.0 [5] (🥇..🥋) 1st place medal..martial arts uniform + // E5.0 [1] (🥌) curling stone + // E11.0 [3] (🥍..🥏) lacrosse..flying disc + // E3.0 [15] (🥐..🥞) croissant..pancakes + // E5.0 [13] (🥟..🥫) dumpling..canned food + // E11.0 [5] (🥬..🥰) leafy green..smiling face with hearts + // E12.0 [1] (🥱) yawning face + // E13.0 [1] (🥲) smiling face with tear + // E11.0 [4] (🥳..🥶) partying face..cold face + // E13.0 [2] (🥷..🥸) ninja..disguised face + // E14.0 [1] (🥹) face holding back tears + // E11.0 [1] (🥺) pleading face + // E12.0 [1] (🥻) sari + // E11.0 [4] (🥼..🥿) lab coat..flat shoe + // E1.0 [5] (🦀..🦄) crab..unicorn + // E3.0 [13] (🦅..🦑) eagle..squid + // E5.0 [6] (🦒..🦗) giraffe..cricket + // E11.0 [11] (🦘..🦢) kangaroo..swan + // E13.0 [2] (🦣..🦤) mammoth..dodo + // E12.0 [6] (🦥..🦪) sloth..oyster + // E13.0 [3] (🦫..🦭) beaver..seal + // E12.0 [2] (🦮..🦯) guide dog..white cane + // E11.0 [10] (🦰..🦹) red hair..supervillain + // E12.0 [6] (🦺..🦿) safety vest..mechanical leg + // E1.0 [1] (🧀) cheese wedge + // E11.0 [2] (🧁..🧂) cupcake..salt + // E12.0 [8] (🧃..🧊) beverage box..ice + // E13.0 [1] (🧋) bubble tea + // E14.0 [1] (🧌) troll + // E12.0 [3] (🧍..🧏) person standing..deaf person + // E5.0 [23] (🧐..🧦) face with monocle..socks + // E11.0 [25] (🧧..🧿) red envelope..nazar amulet + // E0.0 [112] (🨀..🩯) NEUTRAL CHESS KING.. + // E12.0 [4] (🩰..🩳) ballet shoes..shorts + // E13.0 [1] (🩴) thong sandal + // E15.0 [3] (🩵..🩷) light blue heart..pink heart + // E12.0 [3] (🩸..🩺) drop of blood..stethoscope + // E14.0 [2] (🩻..🩼) x-ray..crutch + // E0.0 [3] (🩽..🩿) .. + // E12.0 [3] (🪀..🪂) yo-yo..parachute + // E13.0 [4] (🪃..🪆) boomerang..nesting dolls + // E15.0 [2] (🪇..🪈) maracas..flute + // E0.0 [7] (🪉..🪏) .. + // E12.0 [6] (🪐..🪕) ringed planet..banjo + // E13.0 [19] (🪖..🪨) military helmet..rock + // E14.0 [4] (🪩..🪬) mirror ball..hamsa + // E15.0 [3] (🪭..🪯) folding hand fan..khanda + // E13.0 [7] (🪰..🪶) fly..feather + // E14.0 [4] (🪷..🪺) lotus..nest with eggs + // E15.0 [3] (🪻..🪽) hyacinth..wing + // E0.0 [1] (🪾) + // E15.0 [1] (🪿) goose + // E13.0 [3] (🫀..🫂) anatomical heart..people hugging + // E14.0 [3] (🫃..🫅) pregnant man..person with crown + // E0.0 [8] (🫆..🫍) .. + // E15.0 [2] (🫎..🫏) moose..donkey + // E13.0 [7] (🫐..🫖) blueberries..teapot + // E14.0 [3] (🫗..🫙) pouring liquid..jar + // E15.0 [2] (🫚..🫛) ginger root..pea pod + // E0.0 [4] (🫜..🫟) .. + // E14.0 [8] (🫠..🫧) melting face..bubbles + // E15.0 [1] (🫨) shaking face + // E0.0 [7] (🫩..🫯) .. + // E14.0 [7] (🫰..🫶) hand with index finger and thumb crossed..heart hands + // E15.0 [2] (🫷..🫸) leftwards pushing hand..rightwards pushing hand + // E0.0 [7] (🫹..🫿) .. + if (0x1f947 <= code && code <= 0x1faff) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + else { + // E0.0[1022] (🰀..🿽) .. + if (0x1fc00 <= code && code <= 0x1fffd) { + return boundaries_1.EXTENDED_PICTOGRAPHIC; + } + } + } + } + } + } + } + } + // unlisted code points are treated as a break property of "Other" + return boundaries_1.CLUSTER_BREAK.OTHER; + } +} +exports.default = Graphemer; diff --git a/node_modules/graphemer/lib/GraphemerHelper.d.ts b/node_modules/graphemer/lib/GraphemerHelper.d.ts new file mode 100644 index 00000000..64f6c35c --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerHelper.d.ts @@ -0,0 +1,32 @@ +declare class GraphemerHelper { + /** + * Check if the the character at the position {pos} of the string is surrogate + * @param str {string} + * @param pos {number} + * @returns {boolean} + */ + static isSurrogate(str: string, pos: number): boolean; + /** + * The String.prototype.codePointAt polyfill + * Private function, gets a Unicode code point from a JavaScript UTF-16 string + * handling surrogate pairs appropriately + * @param str {string} + * @param idx {number} + * @returns {number} + */ + static codePointAt(str: string, idx: number): number; + /** + * Private function, returns whether a break is allowed between the two given grapheme breaking classes + * Implemented the UAX #29 3.1.1 Grapheme Cluster Boundary Rules on extended grapheme clusters + * @param start {number} + * @param mid {Array} + * @param end {number} + * @param startEmoji {number} + * @param midEmoji {Array} + * @param endEmoji {number} + * @returns {number} + */ + static shouldBreak(start: number, mid: number[], end: number, startEmoji: number, midEmoji: number[], endEmoji: number): number; +} +export default GraphemerHelper; +//# sourceMappingURL=GraphemerHelper.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/GraphemerHelper.d.ts.map b/node_modules/graphemer/lib/GraphemerHelper.d.ts.map new file mode 100644 index 00000000..369421a1 --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerHelper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GraphemerHelper.d.ts","sourceRoot":"","sources":["../src/GraphemerHelper.ts"],"names":[],"mappings":"AAUA,cAAM,eAAe;IACnB;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO;IASrD;;;;;;;OAOG;IACH,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM;IAgCpD;;;;;;;;;;OAUG;IACH,MAAM,CAAC,WAAW,CAChB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,MAAM,EAAE,EACb,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAAE,EAClB,QAAQ,EAAE,MAAM,GACf,MAAM;CAyHV;AAED,eAAe,eAAe,CAAC"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/GraphemerHelper.js b/node_modules/graphemer/lib/GraphemerHelper.js new file mode 100644 index 00000000..9bc71ebd --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerHelper.js @@ -0,0 +1,169 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const boundaries_1 = require("./boundaries"); +// BreakTypes +// @type {BreakType} +const NotBreak = 0; +const BreakStart = 1; +const Break = 2; +const BreakLastRegional = 3; +const BreakPenultimateRegional = 4; +class GraphemerHelper { + /** + * Check if the the character at the position {pos} of the string is surrogate + * @param str {string} + * @param pos {number} + * @returns {boolean} + */ + static isSurrogate(str, pos) { + return (0xd800 <= str.charCodeAt(pos) && + str.charCodeAt(pos) <= 0xdbff && + 0xdc00 <= str.charCodeAt(pos + 1) && + str.charCodeAt(pos + 1) <= 0xdfff); + } + /** + * The String.prototype.codePointAt polyfill + * Private function, gets a Unicode code point from a JavaScript UTF-16 string + * handling surrogate pairs appropriately + * @param str {string} + * @param idx {number} + * @returns {number} + */ + static codePointAt(str, idx) { + if (idx === undefined) { + idx = 0; + } + const code = str.charCodeAt(idx); + // if a high surrogate + if (0xd800 <= code && code <= 0xdbff && idx < str.length - 1) { + const hi = code; + const low = str.charCodeAt(idx + 1); + if (0xdc00 <= low && low <= 0xdfff) { + return (hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000; + } + return hi; + } + // if a low surrogate + if (0xdc00 <= code && code <= 0xdfff && idx >= 1) { + const hi = str.charCodeAt(idx - 1); + const low = code; + if (0xd800 <= hi && hi <= 0xdbff) { + return (hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000; + } + return low; + } + // just return the char if an unmatched surrogate half or a + // single-char codepoint + return code; + } + // + /** + * Private function, returns whether a break is allowed between the two given grapheme breaking classes + * Implemented the UAX #29 3.1.1 Grapheme Cluster Boundary Rules on extended grapheme clusters + * @param start {number} + * @param mid {Array} + * @param end {number} + * @param startEmoji {number} + * @param midEmoji {Array} + * @param endEmoji {number} + * @returns {number} + */ + static shouldBreak(start, mid, end, startEmoji, midEmoji, endEmoji) { + const all = [start].concat(mid).concat([end]); + const allEmoji = [startEmoji].concat(midEmoji).concat([endEmoji]); + const previous = all[all.length - 2]; + const next = end; + const nextEmoji = endEmoji; + // Lookahead terminator for: + // GB12. ^ (RI RI)* RI ? RI + // GB13. [^RI] (RI RI)* RI ? RI + const rIIndex = all.lastIndexOf(boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR); + if (rIIndex > 0 && + all.slice(1, rIIndex).every(function (c) { + return c === boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR; + }) && + [boundaries_1.CLUSTER_BREAK.PREPEND, boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR].indexOf(previous) === -1) { + if (all.filter(function (c) { + return c === boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR; + }).length % + 2 === + 1) { + return BreakLastRegional; + } + else { + return BreakPenultimateRegional; + } + } + // GB3. CR × LF + if (previous === boundaries_1.CLUSTER_BREAK.CR && next === boundaries_1.CLUSTER_BREAK.LF) { + return NotBreak; + } + // GB4. (Control|CR|LF) ÷ + else if (previous === boundaries_1.CLUSTER_BREAK.CONTROL || + previous === boundaries_1.CLUSTER_BREAK.CR || + previous === boundaries_1.CLUSTER_BREAK.LF) { + return BreakStart; + } + // GB5. ÷ (Control|CR|LF) + else if (next === boundaries_1.CLUSTER_BREAK.CONTROL || + next === boundaries_1.CLUSTER_BREAK.CR || + next === boundaries_1.CLUSTER_BREAK.LF) { + return BreakStart; + } + // GB6. L × (L|V|LV|LVT) + else if (previous === boundaries_1.CLUSTER_BREAK.L && + (next === boundaries_1.CLUSTER_BREAK.L || + next === boundaries_1.CLUSTER_BREAK.V || + next === boundaries_1.CLUSTER_BREAK.LV || + next === boundaries_1.CLUSTER_BREAK.LVT)) { + return NotBreak; + } + // GB7. (LV|V) × (V|T) + else if ((previous === boundaries_1.CLUSTER_BREAK.LV || previous === boundaries_1.CLUSTER_BREAK.V) && + (next === boundaries_1.CLUSTER_BREAK.V || next === boundaries_1.CLUSTER_BREAK.T)) { + return NotBreak; + } + // GB8. (LVT|T) × (T) + else if ((previous === boundaries_1.CLUSTER_BREAK.LVT || previous === boundaries_1.CLUSTER_BREAK.T) && + next === boundaries_1.CLUSTER_BREAK.T) { + return NotBreak; + } + // GB9. × (Extend|ZWJ) + else if (next === boundaries_1.CLUSTER_BREAK.EXTEND || next === boundaries_1.CLUSTER_BREAK.ZWJ) { + return NotBreak; + } + // GB9a. × SpacingMark + else if (next === boundaries_1.CLUSTER_BREAK.SPACINGMARK) { + return NotBreak; + } + // GB9b. Prepend × + else if (previous === boundaries_1.CLUSTER_BREAK.PREPEND) { + return NotBreak; + } + // GB11. \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic} + const previousNonExtendIndex = allEmoji + .slice(0, -1) + .lastIndexOf(boundaries_1.EXTENDED_PICTOGRAPHIC); + if (previousNonExtendIndex !== -1 && + allEmoji[previousNonExtendIndex] === boundaries_1.EXTENDED_PICTOGRAPHIC && + all.slice(previousNonExtendIndex + 1, -2).every(function (c) { + return c === boundaries_1.CLUSTER_BREAK.EXTEND; + }) && + previous === boundaries_1.CLUSTER_BREAK.ZWJ && + nextEmoji === boundaries_1.EXTENDED_PICTOGRAPHIC) { + return NotBreak; + } + // GB12. ^ (RI RI)* RI × RI + // GB13. [^RI] (RI RI)* RI × RI + if (mid.indexOf(boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR) !== -1) { + return Break; + } + if (previous === boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR && + next === boundaries_1.CLUSTER_BREAK.REGIONAL_INDICATOR) { + return NotBreak; + } + // GB999. Any ? Any + return BreakStart; + } +} +exports.default = GraphemerHelper; diff --git a/node_modules/graphemer/lib/GraphemerIterator.d.ts b/node_modules/graphemer/lib/GraphemerIterator.d.ts new file mode 100644 index 00000000..4c52d91f --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerIterator.d.ts @@ -0,0 +1,22 @@ +/** + * GraphemerIterator + * + * Takes a string and a "BreakHandler" method during initialisation + * and creates an iterable object that returns individual graphemes. + * + * @param str {string} + * @return GraphemerIterator + */ +declare class GraphemerIterator implements Iterator { + private _index; + private _str; + private _nextBreak; + constructor(str: string, nextBreak: (str: string, index: number) => number); + [Symbol.iterator](): this; + next(): { + value: string; + done: boolean; + }; +} +export default GraphemerIterator; +//# sourceMappingURL=GraphemerIterator.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/GraphemerIterator.d.ts.map b/node_modules/graphemer/lib/GraphemerIterator.d.ts.map new file mode 100644 index 00000000..c65f0eec --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerIterator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GraphemerIterator.d.ts","sourceRoot":"","sources":["../src/GraphemerIterator.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,cAAM,iBAAkB,YAAW,QAAQ,CAAC,MAAM,CAAC;IACjD,OAAO,CAAC,MAAM,CAAa;IAC3B,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,UAAU,CAAyC;gBAE/C,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM;IAK1E,CAAC,MAAM,CAAC,QAAQ,CAAC;IAIjB,IAAI;;;;CAcL;AAED,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/GraphemerIterator.js b/node_modules/graphemer/lib/GraphemerIterator.js new file mode 100644 index 00000000..dd21ce54 --- /dev/null +++ b/node_modules/graphemer/lib/GraphemerIterator.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * GraphemerIterator + * + * Takes a string and a "BreakHandler" method during initialisation + * and creates an iterable object that returns individual graphemes. + * + * @param str {string} + * @return GraphemerIterator + */ +class GraphemerIterator { + constructor(str, nextBreak) { + this._index = 0; + this._str = str; + this._nextBreak = nextBreak; + } + [Symbol.iterator]() { + return this; + } + next() { + let brk; + if ((brk = this._nextBreak(this._str, this._index)) < this._str.length) { + const value = this._str.slice(this._index, brk); + this._index = brk; + return { value: value, done: false }; + } + if (this._index < this._str.length) { + const value = this._str.slice(this._index); + this._index = this._str.length; + return { value: value, done: false }; + } + return { value: undefined, done: true }; + } +} +exports.default = GraphemerIterator; diff --git a/node_modules/graphemer/lib/boundaries.d.ts b/node_modules/graphemer/lib/boundaries.d.ts new file mode 100644 index 00000000..330aed10 --- /dev/null +++ b/node_modules/graphemer/lib/boundaries.d.ts @@ -0,0 +1,35 @@ +/** + * The Grapheme_Cluster_Break property value + * @see https://www.unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table + */ +export declare enum CLUSTER_BREAK { + CR = 0, + LF = 1, + CONTROL = 2, + EXTEND = 3, + REGIONAL_INDICATOR = 4, + SPACINGMARK = 5, + L = 6, + V = 7, + T = 8, + LV = 9, + LVT = 10, + OTHER = 11, + PREPEND = 12, + E_BASE = 13, + E_MODIFIER = 14, + ZWJ = 15, + GLUE_AFTER_ZWJ = 16, + E_BASE_GAZ = 17 +} +/** + * The Emoji character property is an extension of UCD but shares the same namespace and structure + * @see http://www.unicode.org/reports/tr51/tr51-14.html#Emoji_Properties_and_Data_Files + * + * Here we model Extended_Pictograhpic only to implement UAX #29 GB11 + * \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic} + * + * The Emoji character property should not be mixed with Grapheme_Cluster_Break since they are not exclusive + */ +export declare const EXTENDED_PICTOGRAPHIC = 101; +//# sourceMappingURL=boundaries.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/boundaries.d.ts.map b/node_modules/graphemer/lib/boundaries.d.ts.map new file mode 100644 index 00000000..5bc59bae --- /dev/null +++ b/node_modules/graphemer/lib/boundaries.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"boundaries.d.ts","sourceRoot":"","sources":["../src/boundaries.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,oBAAY,aAAa;IACvB,EAAE,IAAI;IACN,EAAE,IAAI;IACN,OAAO,IAAI;IACX,MAAM,IAAI;IACV,kBAAkB,IAAI;IACtB,WAAW,IAAI;IACf,CAAC,IAAI;IACL,CAAC,IAAI;IACL,CAAC,IAAI;IACL,EAAE,IAAI;IACN,GAAG,KAAK;IACR,KAAK,KAAK;IACV,OAAO,KAAK;IACZ,MAAM,KAAK;IACX,UAAU,KAAK;IACf,GAAG,KAAK;IACR,cAAc,KAAK;IACnB,UAAU,KAAK;CAChB;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/boundaries.js b/node_modules/graphemer/lib/boundaries.js new file mode 100644 index 00000000..2c98c145 --- /dev/null +++ b/node_modules/graphemer/lib/boundaries.js @@ -0,0 +1,38 @@ +"use strict"; +/** + * The Grapheme_Cluster_Break property value + * @see https://www.unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EXTENDED_PICTOGRAPHIC = exports.CLUSTER_BREAK = void 0; +var CLUSTER_BREAK; +(function (CLUSTER_BREAK) { + CLUSTER_BREAK[CLUSTER_BREAK["CR"] = 0] = "CR"; + CLUSTER_BREAK[CLUSTER_BREAK["LF"] = 1] = "LF"; + CLUSTER_BREAK[CLUSTER_BREAK["CONTROL"] = 2] = "CONTROL"; + CLUSTER_BREAK[CLUSTER_BREAK["EXTEND"] = 3] = "EXTEND"; + CLUSTER_BREAK[CLUSTER_BREAK["REGIONAL_INDICATOR"] = 4] = "REGIONAL_INDICATOR"; + CLUSTER_BREAK[CLUSTER_BREAK["SPACINGMARK"] = 5] = "SPACINGMARK"; + CLUSTER_BREAK[CLUSTER_BREAK["L"] = 6] = "L"; + CLUSTER_BREAK[CLUSTER_BREAK["V"] = 7] = "V"; + CLUSTER_BREAK[CLUSTER_BREAK["T"] = 8] = "T"; + CLUSTER_BREAK[CLUSTER_BREAK["LV"] = 9] = "LV"; + CLUSTER_BREAK[CLUSTER_BREAK["LVT"] = 10] = "LVT"; + CLUSTER_BREAK[CLUSTER_BREAK["OTHER"] = 11] = "OTHER"; + CLUSTER_BREAK[CLUSTER_BREAK["PREPEND"] = 12] = "PREPEND"; + CLUSTER_BREAK[CLUSTER_BREAK["E_BASE"] = 13] = "E_BASE"; + CLUSTER_BREAK[CLUSTER_BREAK["E_MODIFIER"] = 14] = "E_MODIFIER"; + CLUSTER_BREAK[CLUSTER_BREAK["ZWJ"] = 15] = "ZWJ"; + CLUSTER_BREAK[CLUSTER_BREAK["GLUE_AFTER_ZWJ"] = 16] = "GLUE_AFTER_ZWJ"; + CLUSTER_BREAK[CLUSTER_BREAK["E_BASE_GAZ"] = 17] = "E_BASE_GAZ"; +})(CLUSTER_BREAK = exports.CLUSTER_BREAK || (exports.CLUSTER_BREAK = {})); +/** + * The Emoji character property is an extension of UCD but shares the same namespace and structure + * @see http://www.unicode.org/reports/tr51/tr51-14.html#Emoji_Properties_and_Data_Files + * + * Here we model Extended_Pictograhpic only to implement UAX #29 GB11 + * \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic} + * + * The Emoji character property should not be mixed with Grapheme_Cluster_Break since they are not exclusive + */ +exports.EXTENDED_PICTOGRAPHIC = 101; diff --git a/node_modules/graphemer/lib/index.d.ts b/node_modules/graphemer/lib/index.d.ts new file mode 100644 index 00000000..c7c39af1 --- /dev/null +++ b/node_modules/graphemer/lib/index.d.ts @@ -0,0 +1,3 @@ +import Graphemer from './Graphemer'; +export default Graphemer; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/graphemer/lib/index.d.ts.map b/node_modules/graphemer/lib/index.d.ts.map new file mode 100644 index 00000000..a6bacf99 --- /dev/null +++ b/node_modules/graphemer/lib/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,aAAa,CAAC;AAEpC,eAAe,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/graphemer/lib/index.js b/node_modules/graphemer/lib/index.js new file mode 100644 index 00000000..548bdd01 --- /dev/null +++ b/node_modules/graphemer/lib/index.js @@ -0,0 +1,7 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const Graphemer_1 = __importDefault(require("./Graphemer")); +exports.default = Graphemer_1.default; diff --git a/node_modules/graphemer/package.json b/node_modules/graphemer/package.json new file mode 100644 index 00000000..cf0315dd --- /dev/null +++ b/node_modules/graphemer/package.json @@ -0,0 +1,54 @@ +{ + "name": "graphemer", + "version": "1.4.0", + "description": "A JavaScript library that breaks strings into their individual user-perceived characters (including emojis!)", + "homepage": "https://github.com/flmnt/graphemer", + "author": "Matt Davies (https://github.com/mattpauldavies)", + "contributors": [ + "Orlin Georgiev (https://github.com/orling)", + "Huáng Jùnliàng (https://github.com/JLHwung)" + ], + "main": "./lib/index.js", + "types": "./lib/index.d.ts", + "files": [ + "lib" + ], + "license": "MIT", + "keywords": [ + "utf-8", + "strings", + "emoji", + "split" + ], + "scripts": { + "prepublishOnly": "npm run build", + "build": "tsc --project tsconfig.json", + "pretest": "npm run build", + "test": "ts-node node_modules/tape/bin/tape tests/**.ts", + "prettier:check": "prettier --check .", + "prettier:fix": "prettier --write ." + }, + "repository": { + "type": "git", + "url": "https://github.com/flmnt/graphemer.git" + }, + "bugs": "https://github.com/flmnt/graphemer/issues", + "devDependencies": { + "@types/tape": "^4.13.0", + "husky": "^4.3.0", + "lint-staged": "^10.3.0", + "prettier": "^2.1.1", + "tape": "^4.6.3", + "ts-node": "^9.0.0", + "typescript": "^4.0.2" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged", + "pre-push": "npm test" + } + }, + "lint-staged": { + "*.{js,ts,md,json}": "prettier --write" + } +} diff --git a/node_modules/has-flag/index.d.ts b/node_modules/has-flag/index.d.ts new file mode 100644 index 00000000..a0a48c89 --- /dev/null +++ b/node_modules/has-flag/index.d.ts @@ -0,0 +1,39 @@ +/** +Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag. + +@param flag - CLI flag to look for. The `--` prefix is optional. +@param argv - CLI arguments. Default: `process.argv`. +@returns Whether the flag exists. + +@example +``` +// $ ts-node foo.ts -f --unicorn --foo=bar -- --rainbow + +// foo.ts +import hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` +*/ +declare function hasFlag(flag: string, argv?: string[]): boolean; + +export = hasFlag; diff --git a/node_modules/has-flag/index.js b/node_modules/has-flag/index.js new file mode 100644 index 00000000..b6f80b1f --- /dev/null +++ b/node_modules/has-flag/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; diff --git a/node_modules/has-flag/license b/node_modules/has-flag/license new file mode 100644 index 00000000..e7af2f77 --- /dev/null +++ b/node_modules/has-flag/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/has-flag/package.json b/node_modules/has-flag/package.json new file mode 100644 index 00000000..a9cba4b8 --- /dev/null +++ b/node_modules/has-flag/package.json @@ -0,0 +1,46 @@ +{ + "name": "has-flag", + "version": "4.0.0", + "description": "Check if argv has a specific flag", + "license": "MIT", + "repository": "sindresorhus/has-flag", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "has", + "check", + "detect", + "contains", + "find", + "flag", + "cli", + "command-line", + "argv", + "process", + "arg", + "args", + "argument", + "arguments", + "getopt", + "minimist", + "optimist" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/has-flag/readme.md b/node_modules/has-flag/readme.md new file mode 100644 index 00000000..3f72dff2 --- /dev/null +++ b/node_modules/has-flag/readme.md @@ -0,0 +1,89 @@ +# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag) + +> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag + +Correctly stops looking after an `--` argument terminator. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + + +## Install + +``` +$ npm install has-flag +``` + + +## Usage + +```js +// foo.js +const hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` + +``` +$ node foo.js -f --unicorn --foo=bar -- --rainbow +``` + + +## API + +### hasFlag(flag, [argv]) + +Returns a boolean for whether the flag exists. + +#### flag + +Type: `string` + +CLI flag to look for. The `--` prefix is optional. + +#### argv + +Type: `string[]`
+Default: `process.argv` + +CLI arguments. + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/ignore/LICENSE-MIT b/node_modules/ignore/LICENSE-MIT new file mode 100644 index 00000000..825533e3 --- /dev/null +++ b/node_modules/ignore/LICENSE-MIT @@ -0,0 +1,21 @@ +Copyright (c) 2013 Kael Zhang , contributors +http://kael.me/ + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/ignore/README.md b/node_modules/ignore/README.md new file mode 100644 index 00000000..073660e6 --- /dev/null +++ b/node_modules/ignore/README.md @@ -0,0 +1,452 @@ +| Linux / MacOS / Windows | Coverage | Downloads | +| ----------------------- | -------- | --------- | +| [![build][bb]][bl] | [![coverage][cb]][cl] | [![downloads][db]][dl] | + +[bb]: https://github.com/kaelzhang/node-ignore/actions/workflows/nodejs.yml/badge.svg +[bl]: https://github.com/kaelzhang/node-ignore/actions/workflows/nodejs.yml + +[cb]: https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg +[cl]: https://codecov.io/gh/kaelzhang/node-ignore + +[db]: http://img.shields.io/npm/dm/ignore.svg +[dl]: https://www.npmjs.org/package/ignore + +# ignore + +`ignore` is a manager, filter and parser which implemented in pure JavaScript according to the [.gitignore spec 2.22.1](http://git-scm.com/docs/gitignore). + +`ignore` is used by eslint, gitbook and [many others](https://www.npmjs.com/browse/depended/ignore). + +Pay **ATTENTION** that [`minimatch`](https://www.npmjs.org/package/minimatch) (which used by `fstream-ignore`) does not follow the gitignore spec. + +To filter filenames according to a .gitignore file, I recommend this npm package, `ignore`. + +To parse an `.npmignore` file, you should use `minimatch`, because an `.npmignore` file is parsed by npm using `minimatch` and it does not work in the .gitignore way. + +### Tested on + +`ignore` is fully tested, and has more than **five hundreds** of unit tests. + +- Linux + Node: `0.8` - `7.x` +- Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. + +Actually, `ignore` does not rely on any versions of node specially. + +Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). + +## Table Of Main Contents + +- [Usage](#usage) +- [`Pathname` Conventions](#pathname-conventions) +- See Also: + - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. +- [Upgrade Guide](#upgrade-guide) + +## Install + +```sh +npm i ignore +``` + +## Usage + +```js +import ignore from 'ignore' +const ig = ignore().add(['.abc/*', '!.abc/d/']) +``` + +### Filter the given paths + +```js +const paths = [ + '.abc/a.js', // filtered out + '.abc/d/e.js' // included +] + +ig.filter(paths) // ['.abc/d/e.js'] +ig.ignores('.abc/a.js') // true +``` + +### As the filter function + +```js +paths.filter(ig.createFilter()); // ['.abc/d/e.js'] +``` + +### Win32 paths will be handled + +```js +ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) +// if the code above runs on windows, the result will be +// ['.abc\\d\\e.js'] +``` + +## Why another ignore? + +- `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. + +- `ignore` only contains utility methods to filter paths according to the specified ignore rules, so + - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. + - `ignore` don't cares about sub-modules of git projects. + +- Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: + - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. + - '`**/foo`' should match '`foo`' anywhere. + - Prevent re-including a file if a parent directory of that file is excluded. + - Handle trailing whitespaces: + - `'a '`(one space) should not match `'a '`(two spaces). + - `'a \ '` matches `'a '` + - All test cases are verified with the result of `git check-ignore`. + +# Methods + +## .add(pattern: string | Ignore): this +## .add(patterns: Array): this +## .add({pattern: string, mark?: string}): this since 7.0.0 + +- **pattern** `string | Ignore` An ignore pattern string, or the `Ignore` instance +- **patterns** `Array` Array of ignore patterns. +- **mark?** `string` Pattern mark, which is used to associate the pattern with a certain marker, such as the line no of the `.gitignore` file. Actually it could be an arbitrary string and is optional. + +Adds a rule or several rules to the current manager. + +Returns `this` + +Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. + +```js +ignore().add('#abc').ignores('#abc') // false +ignore().add('\\#abc').ignores('#abc') // true +``` + +`pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: + +```js +ignore() +.add(fs.readFileSync(filenameOfGitignore).toString()) +.filter(filenames) +``` + +`pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. + +## .ignores(pathname: [Pathname](#pathname-conventions)): boolean + +> new in 3.2.0 + +Returns `Boolean` whether `pathname` should be ignored. + +```js +ig.ignores('.abc/a.js') // true +``` + +Please **PAY ATTENTION** that `.ignores()` is **NOT** equivalent to `git check-ignore` although in most cases they return equivalent results. + +However, for the purposes of imitating the behavior of `git check-ignore`, please use `.checkIgnore()` instead. + +### `Pathname` Conventions: + +#### 1. `Pathname` should be a `path.relative()`d pathname + +`Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory, + +```js +// WRONG, an error will be thrown +ig.ignores('./abc') + +// WRONG, for it will never happen, and an error will be thrown +// If the gitignore rule locates at the root directory, +// `'/abc'` should be changed to `'abc'`. +// ``` +// path.relative('/', '/abc') -> 'abc' +// ``` +ig.ignores('/abc') + +// WRONG, that it is an absolute path on Windows, an error will be thrown +ig.ignores('C:\\abc') + +// Right +ig.ignores('abc') + +// Right +ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' +``` + +In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. + +Suppose the dir structure is: + +``` +/path/to/your/repo + |-- a + | |-- a.js + | + |-- .b + | + |-- .c + |-- .DS_store +``` + +Then the `paths` might be like this: + +```js +[ + 'a/a.js' + '.b', + '.c/.DS_store' +] +``` + +#### 2. filenames and dirnames + +`node-ignore` does NO `fs.stat` during path matching, so `node-ignore` treats +- `foo` as a file +- **`foo/` as a directory** + +For the example below: + +```js +// First, we add a ignore pattern to ignore a directory +ig.add('config/') + +// `ig` does NOT know if 'config', in the real world, +// is a normal file, directory or something. + +ig.ignores('config') +// `ig` treats `config` as a file, so it returns `false` + +ig.ignores('config/') +// returns `true` +``` + +Specially for people who develop some library based on `node-ignore`, it is important to understand that. + +Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: + +```js +import glob from 'glob' + +glob('**', { + // Adds a / character to directory matches. + mark: true +}, (err, files) => { + if (err) { + return console.error(err) + } + + let filtered = ignore().add(patterns).filter(files) + console.log(filtered) +}) +``` + + +## .filter(paths: Array<Pathname>): Array<Pathname> + +```ts +type Pathname = string +``` + +Filters the given array of pathnames, and returns the filtered array. + +- **paths** `Array.` The array of `pathname`s to be filtered. + +## .createFilter() + +Creates a filter function which could filter an array of paths with `Array.prototype.filter`. + +Returns `function(path)` the filter function. + +## .test(pathname: Pathname): TestResult + +> New in 5.0.0 + +Returns `TestResult` + +```ts +// Since 5.0.0 +interface TestResult { + ignored: boolean + // true if the `pathname` is finally unignored by some negative pattern + unignored: boolean + // The `IgnoreRule` which ignores the pathname + rule?: IgnoreRule +} + +// Since 7.0.0 +interface IgnoreRule { + // The original pattern + pattern: string + // Whether the pattern is a negative pattern + negative: boolean + // Which is used for other packages to build things upon `node-ignore` + mark?: string +} +``` + +- `{ignored: true, unignored: false}`: the `pathname` is ignored +- `{ignored: false, unignored: true}`: the `pathname` is unignored +- `{ignored: false, unignored: false}`: the `pathname` is never matched by any ignore rules. + +## .checkIgnore(target: string): TestResult + +> new in 7.0.0 + +Debugs gitignore / exclude files, which is equivalent to `git check-ignore -v`. Usually this method is used for other packages to implement the function of `git check-ignore -v` upon `node-ignore` + +- **target** `string` the target to test. + +Returns `TestResult` + +```js +ig.add({ + pattern: 'foo/*', + mark: '60' +}) + +const { + ignored, + rule +} = checkIgnore('foo/') + +if (ignored) { + console.log(`.gitignore:${result}:${rule.mark}:${rule.pattern} foo/`) +} + +// .gitignore:60:foo/* foo/ +``` + +Please pay attention that this method does not have a strong built-in cache mechanism. + +The purpose of introducing this method is to make it possible to implement the `git check-ignore` command in JavaScript based on `node-ignore`. + +So do not use this method in those situations where performance is extremely important. + +## static `isPathValid(pathname): boolean` since 5.0.0 + +Check whether the `pathname` is an valid `path.relative()`d path according to the [convention](#1-pathname-should-be-a-pathrelatived-pathname). + +This method is **NOT** used to check if an ignore pattern is valid. + +```js +import {isPathValid} from 'ignore' + +isPathValid('./foo') // false +``` + +## .addIgnoreFile(path) + +REMOVED in `3.x` for now. + +To upgrade `ignore@2.x` up to `3.x`, use + +```js +import fs from 'fs' + +if (fs.existsSync(filename)) { + ignore().add(fs.readFileSync(filename).toString()) +} +``` + +instead. + +## ignore(options) + +### `options.ignorecase` since 4.0.0 + +Similar to the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (the default value), otherwise case sensitive. + +```js +const ig = ignore({ + ignorecase: false +}) + +ig.add('*.png') + +ig.ignores('*.PNG') // false +``` + +### `options.ignoreCase?: boolean` since 5.2.0 + +Which is an alternative to `options.ignoreCase` + +### `options.allowRelativePaths?: boolean` since 5.2.0 + +This option brings backward compatibility with projects which based on `ignore@4.x`. If `options.allowRelativePaths` is `true`, `ignore` will not check whether the given path to be tested is [`path.relative()`d](#pathname-conventions). + +However, passing a relative path, such as `'./foo'` or `'../foo'`, to test if it is ignored or not is not a good practise, which might lead to unexpected behavior + +```js +ignore({ + allowRelativePaths: true +}).ignores('../foo/bar.js') // And it will not throw +``` + +**** + +# Upgrade Guide + +## Upgrade 4.x -> 5.x + +Since `5.0.0`, if an invalid `Pathname` passed into `ig.ignores()`, an error will be thrown, unless `options.allowRelative = true` is passed to the `Ignore` factory. + +While `ignore < 5.0.0` did not make sure what the return value was, as well as + +```ts +.ignores(pathname: Pathname): boolean + +.filter(pathnames: Array): Array + +.createFilter(): (pathname: Pathname) => boolean + +.test(pathname: Pathname): {ignored: boolean, unignored: boolean} +``` + +See the convention [here](#1-pathname-should-be-a-pathrelatived-pathname) for details. + +If there are invalid pathnames, the conversion and filtration should be done by users. + +```js +import {isPathValid} from 'ignore' // introduced in 5.0.0 + +const paths = [ + // invalid + ////////////////// + '', + false, + '../foo', + '.', + ////////////////// + + // valid + 'foo' +] +.filter(isPathValid) + +ig.filter(paths) +``` + +## Upgrade 3.x -> 4.x + +Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: + +```js +var ignore = require('ignore/legacy') +``` + +## Upgrade 2.x -> 3.x + +- All `options` of 2.x are unnecessary and removed, so just remove them. +- `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. +- `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. + +**** + +# Collaborators + +- [@whitecolor](https://github.com/whitecolor) *Alex* +- [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* +- [@azproduction](https://github.com/azproduction) *Mikhail Davydov* +- [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* +- [@JanMattner](https://github.com/JanMattner) *Jan Mattner* +- [@ntwb](https://github.com/ntwb) *Stephen Edgar* +- [@kasperisager](https://github.com/kasperisager) *Kasper Isager* +- [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* diff --git a/node_modules/ignore/index.d.ts b/node_modules/ignore/index.d.ts new file mode 100644 index 00000000..f6912595 --- /dev/null +++ b/node_modules/ignore/index.d.ts @@ -0,0 +1,81 @@ +type Pathname = string + +interface IgnoreRule { + pattern: string + mark?: string + negative: boolean +} + +interface TestResult { + ignored: boolean + unignored: boolean + rule?: IgnoreRule +} + +interface PatternParams { + pattern: string + mark?: string +} + +/** + * Creates new ignore manager. + */ +declare function ignore(options?: ignore.Options): ignore.Ignore +declare namespace ignore { + interface Ignore { + /** + * Adds one or several rules to the current manager. + * @param {string[]} patterns + * @returns IgnoreBase + */ + add( + patterns: string | Ignore | readonly (string | Ignore)[] | PatternParams + ): this + + /** + * Filters the given array of pathnames, and returns the filtered array. + * NOTICE that each path here should be a relative path to the root of your repository. + * @param paths the array of paths to be filtered. + * @returns The filtered array of paths + */ + filter(pathnames: readonly Pathname[]): Pathname[] + + /** + * Creates a filter function which could filter + * an array of paths with Array.prototype.filter. + */ + createFilter(): (pathname: Pathname) => boolean + + /** + * Returns Boolean whether pathname should be ignored. + * @param {string} pathname a path to check + * @returns boolean + */ + ignores(pathname: Pathname): boolean + + /** + * Returns whether pathname should be ignored or unignored + * @param {string} pathname a path to check + * @returns TestResult + */ + test(pathname: Pathname): TestResult + + /** + * Debugs ignore rules and returns the checking result, which is + * equivalent to `git check-ignore -v`. + * @returns TestResult + */ + checkIgnore(pathname: Pathname): TestResult + } + + interface Options { + ignorecase?: boolean + // For compatibility + ignoreCase?: boolean + allowRelativePaths?: boolean + } + + function isPathValid(pathname: string): boolean +} + +export = ignore diff --git a/node_modules/ignore/index.js b/node_modules/ignore/index.js new file mode 100644 index 00000000..6dee02f8 --- /dev/null +++ b/node_modules/ignore/index.js @@ -0,0 +1,784 @@ +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} + +const UNDEFINED = undefined +const EMPTY = '' +const SPACE = ' ' +const ESCAPE = '\\' +const REGEX_TEST_BLANK_LINE = /^\s+$/ +const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/ +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ +const REGEX_SPLITALL_CRLF = /\r?\n/g + +// Invalid: +// - /foo, +// - ./foo, +// - ../foo, +// - . +// - .. +// Valid: +// - .foo +const REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/ + +const REGEX_TEST_TRAILING_SLASH = /\/$/ + +const SLASH = '/' + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +let TMP_KEY_IGNORE = 'node-ignore' +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol.for('node-ignore') +} +const KEY_IGNORE = TMP_KEY_IGNORE + +const define = (object, key, value) => { + Object.defineProperty(object, key, {value}) + return value +} + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g + +const RETURN_FALSE = () => false + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY +) + +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes + return slashes.slice(0, length - length % 2) +} + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ + + [ + // Remove BOM + // TODO: + // Other similar zero-width characters? + /^\uFEFF/, + () => EMPTY + ], + + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a ) -> (a) + // (a \ ) -> (a ) + /((?:\\\\)*?)(\\?\s+)$/, + (_, m1, m2) => m1 + ( + m2.indexOf('\\') === 0 + ? SPACE + : EMPTY + ) + ], + + // Replace (\ ) with ' ' + // (\ ) -> ' ' + // (\\ ) -> '\\ ' + // (\\\ ) -> '\\ ' + [ + /(\\+?)\s/g, + (_, m1) => { + const {length} = m1 + return m1.slice(0, length - length % 2) + SPACE + } + ], + + // Escape metacharacters + // which is written down by users but means special for regular expressions. + + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + match => `\\${match}` + ], + + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], + + // leading slash + [ + + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], + + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], + + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], + + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], + + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, + + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer + + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], + + // normal intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' + + // 'abc.*/' -> go + // 'abc.*' -> skip this rule, + // coz trailing single wildcard will be handed by [trailing wildcard] + /(^|[^\\]+)(\\\*)+(?=.+)/g, + + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1, p2) => { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + const unescaped = p2.replace(/\\\*/g, '[^\\/]*') + return p1 + unescaped + } + ], + + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], + + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], + + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. + + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` + : close === ']' + ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? `[${sanitizeRange(range)}${endEscape}]` + // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' + : '[]' + ], + + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, + + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ] +] + +const REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/ +const MODE_IGNORE = 'regex' +const MODE_CHECK_IGNORE = 'checkRegex' +const UNDERSCORE = '_' + +const TRAILING_WILD_CARD_REPLACERS = { + [MODE_IGNORE] (_, p1) { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' + + return `${prefix}(?=$|\\/$)` + }, + + [MODE_CHECK_IGNORE] (_, p1) { + // When doing `git check-ignore` + const prefix = p1 + // '\\\/': + // 'abc/*' DOES match 'abc/' ! + ? `${p1}[^/]*` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' + + return `${prefix}(?=$|\\/$)` + } +} + +// @param {pattern} +const makeRegexPrefix = pattern => REPLACERS.reduce( + (prev, [matcher, replacer]) => + prev.replace(matcher, replacer.bind(pattern)), + pattern +) + +const isString = subject => typeof subject === 'string' + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0 + +const splitPattern = pattern => pattern +.split(REGEX_SPLITALL_CRLF) +.filter(Boolean) + +class IgnoreRule { + constructor ( + pattern, + mark, + body, + ignoreCase, + negative, + prefix + ) { + this.pattern = pattern + this.mark = mark + this.negative = negative + + define(this, 'body', body) + define(this, 'ignoreCase', ignoreCase) + define(this, 'regexPrefix', prefix) + } + + get regex () { + const key = UNDERSCORE + MODE_IGNORE + + if (this[key]) { + return this[key] + } + + return this._make(MODE_IGNORE, key) + } + + get checkRegex () { + const key = UNDERSCORE + MODE_CHECK_IGNORE + + if (this[key]) { + return this[key] + } + + return this._make(MODE_CHECK_IGNORE, key) + } + + _make (mode, key) { + const str = this.regexPrefix.replace( + REGEX_REPLACE_TRAILING_WILDCARD, + + // It does not need to bind pattern + TRAILING_WILD_CARD_REPLACERS[mode] + ) + + const regex = this.ignoreCase + ? new RegExp(str, 'i') + : new RegExp(str) + + return define(this, key, regex) + } +} + +const createRule = ({ + pattern, + mark +}, ignoreCase) => { + let negative = false + let body = pattern + + // > An optional prefix "!" which negates the pattern; + if (body.indexOf('!') === 0) { + negative = true + body = body.substr(1) + } + + body = body + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') + + const regexPrefix = makeRegexPrefix(body) + + return new IgnoreRule( + pattern, + mark, + body, + ignoreCase, + negative, + regexPrefix + ) +} + +class RuleManager { + constructor (ignoreCase) { + this._ignoreCase = ignoreCase + this._rules = [] + } + + _add (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules._rules) + this._added = true + return + } + + if (isString(pattern)) { + pattern = { + pattern + } + } + + if (checkPattern(pattern.pattern)) { + const rule = createRule(pattern, this._ignoreCase) + this._added = true + this._rules.push(rule) + } + } + + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false + + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._add, this) + + return this._added + } + + // Test one single path without recursively checking parent directories + // + // - checkUnignored `boolean` whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE` + + // @returns {TestResult} true if a file is ignored + test (path, checkUnignored, mode) { + let ignored = false + let unignored = false + let matchedRule + + this._rules.forEach(rule => { + const {negative} = rule + + // | ignored : unignored + // -------- | --------------------------------------- + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } + + const matched = rule[mode].test(path) + + if (!matched) { + return + } + + ignored = !negative + unignored = negative + + matchedRule = negative + ? UNDEFINED + : rule + }) + + const ret = { + ignored, + unignored + } + + if (matchedRule) { + ret.rule = matchedRule + } + + return ret + } +} + +const throwError = (message, Ctor) => { + throw new Ctor(message) +} + +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d' + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + + return true +} + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + +checkPath.isNotRelative = isNotRelative + +// On windows, the following function will be replaced +/* istanbul ignore next */ +checkPath.convert = p => p + + +class Ignore { + constructor ({ + ignorecase = true, + ignoreCase = ignorecase, + allowRelativePaths = false + } = {}) { + define(this, KEY_IGNORE, true) + + this._rules = new RuleManager(ignoreCase) + this._strictPathCheck = !allowRelativePaths + this._initCache() + } + + _initCache () { + // A cache for the result of `.ignores()` + this._ignoreCache = Object.create(null) + + // A cache for the result of `.test()` + this._testCache = Object.create(null) + } + + add (pattern) { + if (this._rules.add(pattern)) { + // Some rules have just added to the ignore, + // making the behavior changed, + // so we need to re-initialize the result cache + this._initCache() + } + + return this + } + + // legacy + addPattern (pattern) { + return this.add(pattern) + } + + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath) + + checkPath( + path, + originalPath, + this._strictPathCheck + ? throwError + : RETURN_FALSE + ) + + return this._t(path, cache, checkUnignored, slices) + } + + checkIgnore (path) { + // If the path doest not end with a slash, `.ignores()` is much equivalent + // to `git check-ignore` + if (!REGEX_TEST_TRAILING_SLASH.test(path)) { + return this.test(path) + } + + const slices = path.split(SLASH).filter(Boolean) + slices.pop() + + if (slices.length) { + const parent = this._t( + slices.join(SLASH) + SLASH, + this._testCache, + true, + slices + ) + + if (parent.ignored) { + return parent + } + } + + return this._rules.test(path, false, MODE_CHECK_IGNORE) + } + + _t ( + // The path to be tested + path, + + // The cache for the result of a certain checking + cache, + + // Whether should check if the path is unignored + checkUnignored, + + // The path slices + slices + ) { + if (path in cache) { + return cache[path] + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH).filter(Boolean) + } + + slices.pop() + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE) + } + + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ) + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._rules.test(path, checkUnignored, MODE_IGNORE) + } + + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + + createFilter () { + return path => !this.ignores(path) + } + + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } + + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} + +const factory = options => new Ignore(options) + +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, RETURN_FALSE) + +/* istanbul ignore next */ +const setupWindows = () => { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/') + + checkPath.convert = makePosix + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i + checkPath.isNotRelative = path => + REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path) +} + + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore next */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && process.platform === 'win32' +) { + setupWindows() +} + +// COMMONJS_EXPORTS //////////////////////////////////////////////////////////// + +module.exports = factory + +// Although it is an anti-pattern, +// it is still widely misused by a lot of libraries in github +// Ref: https://github.com/search?q=ignore.default%28%29&type=code +factory.default = factory + +module.exports.isPathValid = isPathValid + +// For testing purposes +define(module.exports, Symbol.for('setupWindows'), setupWindows) diff --git a/node_modules/ignore/legacy.js b/node_modules/ignore/legacy.js new file mode 100644 index 00000000..13c03d7c --- /dev/null +++ b/node_modules/ignore/legacy.js @@ -0,0 +1,681 @@ +"use strict"; + +var _TRAILING_WILD_CARD_R; +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +// A simple implementation of make-array +function makeArray(subject) { + return Array.isArray(subject) ? subject : [subject]; +} +var UNDEFINED = undefined; +var EMPTY = ''; +var SPACE = ' '; +var ESCAPE = '\\'; +var REGEX_TEST_BLANK_LINE = /^\s+$/; +var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/; +var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; +var REGEX_SPLITALL_CRLF = /\r?\n/g; + +// Invalid: +// - /foo, +// - ./foo, +// - ../foo, +// - . +// - .. +// Valid: +// - .foo +var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/; +var REGEX_TEST_TRAILING_SLASH = /\/$/; +var SLASH = '/'; + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +var TMP_KEY_IGNORE = 'node-ignore'; +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol["for"]('node-ignore'); +} +var KEY_IGNORE = TMP_KEY_IGNORE; +var define = function define(object, key, value) { + Object.defineProperty(object, key, { + value: value + }); + return value; +}; +var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; +var RETURN_FALSE = function RETURN_FALSE() { + return false; +}; + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +var sanitizeRange = function sanitizeRange(range) { + return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) { + return from.charCodeAt(0) <= to.charCodeAt(0) ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY; + }); +}; + +// See fixtures #59 +var cleanRangeBackSlash = function cleanRangeBackSlash(slashes) { + var length = slashes.length; + return slashes.slice(0, length - length % 2); +}; + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +var REPLACERS = [[ +// Remove BOM +// TODO: +// Other similar zero-width characters? +/^\uFEFF/, function () { + return EMPTY; +}], +// > Trailing spaces are ignored unless they are quoted with backslash ("\") +[ +// (a\ ) -> (a ) +// (a ) -> (a) +// (a ) -> (a) +// (a \ ) -> (a ) +/((?:\\\\)*?)(\\?\s+)$/, function (_, m1, m2) { + return m1 + (m2.indexOf('\\') === 0 ? SPACE : EMPTY); +}], +// Replace (\ ) with ' ' +// (\ ) -> ' ' +// (\\ ) -> '\\ ' +// (\\\ ) -> '\\ ' +[/(\\+?)\s/g, function (_, m1) { + var length = m1.length; + return m1.slice(0, length - length % 2) + SPACE; +}], +// Escape metacharacters +// which is written down by users but means special for regular expressions. + +// > There are 12 characters with special meanings: +// > - the backslash \, +// > - the caret ^, +// > - the dollar sign $, +// > - the period or dot ., +// > - the vertical bar or pipe symbol |, +// > - the question mark ?, +// > - the asterisk or star *, +// > - the plus sign +, +// > - the opening parenthesis (, +// > - the closing parenthesis ), +// > - and the opening square bracket [, +// > - the opening curly brace {, +// > These special characters are often called "metacharacters". +[/[\\$.|*+(){^]/g, function (match) { + return "\\".concat(match); +}], [ +// > a question mark (?) matches a single character +/(?!\\)\?/g, function () { + return '[^/]'; +}], +// leading slash +[ +// > A leading slash matches the beginning of the pathname. +// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". +// A leading slash matches the beginning of the pathname +/^\//, function () { + return '^'; +}], +// replace special metacharacter slash after the leading slash +[/\//g, function () { + return '\\/'; +}], [ +// > A leading "**" followed by a slash means match in all directories. +// > For example, "**/foo" matches file or directory "foo" anywhere, +// > the same as pattern "foo". +// > "**/foo/bar" matches file or directory "bar" anywhere that is directly +// > under directory "foo". +// Notice that the '*'s have been replaced as '\\*' +/^\^*\\\*\\\*\\\//, +// '**/foo' <-> 'foo' +function () { + return '^(?:.*\\/)?'; +}], +// starting +[ +// there will be no leading '/' +// (which has been replaced by section "leading slash") +// If starts with '**', adding a '^' to the regular expression also works +/^(?=[^^])/, function startingReplacer() { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^'; +}], +// two globstars +[ +// Use lookahead assertions so that we could match more than one `'/**'` +/\\\/\\\*\\\*(?=\\\/|$)/g, +// Zero, one or several directories +// should not use '*', or it will be replaced by the next replacer + +// Check if it is not the last `'/**'` +function (_, index, str) { + return index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+'; +}], +// normal intermediate wildcards +[ +// Never replace escaped '*' +// ignore rule '\*' will match the path '*' + +// 'abc.*/' -> go +// 'abc.*' -> skip this rule, +// coz trailing single wildcard will be handed by [trailing wildcard] +/(^|[^\\]+)(\\\*)+(?=.+)/g, +// '*.js' matches '.js' +// '*.js' doesn't match 'abc' +function (_, p1, p2) { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + var unescaped = p2.replace(/\\\*/g, '[^\\/]*'); + return p1 + unescaped; +}], [ +// unescape, revert step 3 except for back slash +// For example, if a user escape a '\\*', +// after step 3, the result will be '\\\\\\*' +/\\\\\\(?=[$.|*+(){^])/g, function () { + return ESCAPE; +}], [ +// '\\\\' -> '\\' +/\\\\/g, function () { + return ESCAPE; +}], [ +// > The range notation, e.g. [a-zA-Z], +// > can be used to match one of the characters in a range. + +// `\` is escaped by step 3 +/(\\)?\[([^\]/]*?)(\\*)($|\])/g, function (match, leadEscape, range, endEscape, close) { + return leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? "\\[".concat(range).concat(cleanRangeBackSlash(endEscape)).concat(close) : close === ']' ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? "[".concat(sanitizeRange(range)).concat(endEscape, "]") // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' : '[]'; +}], +// ending +[ +// 'js' will not match 'js.' +// 'ab' will not match 'abc' +/(?:[^*])$/, +// WTF! +// https://git-scm.com/docs/gitignore +// changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) +// which re-fixes #24, #38 + +// > If there is a separator at the end of the pattern then the pattern +// > will only match directories, otherwise the pattern can match both +// > files and directories. + +// 'js*' will not match 'a.js' +// 'js/' will not match 'a.js' +// 'js' will match 'a.js' and 'a.js/' +function (match) { + return /\/$/.test(match) + // foo/ will not match 'foo' + ? "".concat(match, "$") // foo matches 'foo' and 'foo/' + : "".concat(match, "(?=$|\\/$)"); +}]]; +var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/; +var MODE_IGNORE = 'regex'; +var MODE_CHECK_IGNORE = 'checkRegex'; +var UNDERSCORE = '_'; +var TRAILING_WILD_CARD_REPLACERS = (_TRAILING_WILD_CARD_R = {}, _defineProperty(_TRAILING_WILD_CARD_R, MODE_IGNORE, function (_, p1) { + var prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? "".concat(p1, "[^/]+") // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + return "".concat(prefix, "(?=$|\\/$)"); +}), _defineProperty(_TRAILING_WILD_CARD_R, MODE_CHECK_IGNORE, function (_, p1) { + // When doing `git check-ignore` + var prefix = p1 + // '\\\/': + // 'abc/*' DOES match 'abc/' ! + ? "".concat(p1, "[^/]*") // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + return "".concat(prefix, "(?=$|\\/$)"); +}), _TRAILING_WILD_CARD_R); + +// @param {pattern} +var makeRegexPrefix = function makeRegexPrefix(pattern) { + return REPLACERS.reduce(function (prev, _ref) { + var _ref2 = _slicedToArray(_ref, 2), + matcher = _ref2[0], + replacer = _ref2[1]; + return prev.replace(matcher, replacer.bind(pattern)); + }, pattern); +}; +var isString = function isString(subject) { + return typeof subject === 'string'; +}; + +// > A blank line matches no files, so it can serve as a separator for readability. +var checkPattern = function checkPattern(pattern) { + return pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0; +}; +var splitPattern = function splitPattern(pattern) { + return pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean); +}; +var IgnoreRule = /*#__PURE__*/function () { + function IgnoreRule(pattern, mark, body, ignoreCase, negative, prefix) { + _classCallCheck(this, IgnoreRule); + this.pattern = pattern; + this.mark = mark; + this.negative = negative; + define(this, 'body', body); + define(this, 'ignoreCase', ignoreCase); + define(this, 'regexPrefix', prefix); + } + _createClass(IgnoreRule, [{ + key: "regex", + get: function get() { + var key = UNDERSCORE + MODE_IGNORE; + if (this[key]) { + return this[key]; + } + return this._make(MODE_IGNORE, key); + } + }, { + key: "checkRegex", + get: function get() { + var key = UNDERSCORE + MODE_CHECK_IGNORE; + if (this[key]) { + return this[key]; + } + return this._make(MODE_CHECK_IGNORE, key); + } + }, { + key: "_make", + value: function _make(mode, key) { + var str = this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, + // It does not need to bind pattern + TRAILING_WILD_CARD_REPLACERS[mode]); + var regex = this.ignoreCase ? new RegExp(str, 'i') : new RegExp(str); + return define(this, key, regex); + } + }]); + return IgnoreRule; +}(); +var createRule = function createRule(_ref3, ignoreCase) { + var pattern = _ref3.pattern, + mark = _ref3.mark; + var negative = false; + var body = pattern; + + // > An optional prefix "!" which negates the pattern; + if (body.indexOf('!') === 0) { + negative = true; + body = body.substr(1); + } + body = body + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); + var regexPrefix = makeRegexPrefix(body); + return new IgnoreRule(pattern, mark, body, ignoreCase, negative, regexPrefix); +}; +var RuleManager = /*#__PURE__*/function () { + function RuleManager(ignoreCase) { + _classCallCheck(this, RuleManager); + this._ignoreCase = ignoreCase; + this._rules = []; + } + _createClass(RuleManager, [{ + key: "_add", + value: function _add(pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules._rules); + this._added = true; + return; + } + if (isString(pattern)) { + pattern = { + pattern: pattern + }; + } + if (checkPattern(pattern.pattern)) { + var rule = createRule(pattern, this._ignoreCase); + this._added = true; + this._rules.push(rule); + } + } + + // @param {Array | string | Ignore} pattern + }, { + key: "add", + value: function add(pattern) { + this._added = false; + makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._add, this); + return this._added; + } + + // Test one single path without recursively checking parent directories + // + // - checkUnignored `boolean` whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE` + + // @returns {TestResult} true if a file is ignored + }, { + key: "test", + value: function test(path, checkUnignored, mode) { + var ignored = false; + var unignored = false; + var matchedRule; + this._rules.forEach(function (rule) { + var negative = rule.negative; + + // | ignored : unignored + // -------- | --------------------------------------- + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) { + return; + } + var matched = rule[mode].test(path); + if (!matched) { + return; + } + ignored = !negative; + unignored = negative; + matchedRule = negative ? UNDEFINED : rule; + }); + var ret = { + ignored: ignored, + unignored: unignored + }; + if (matchedRule) { + ret.rule = matchedRule; + } + return ret; + } + }]); + return RuleManager; +}(); +var throwError = function throwError(message, Ctor) { + throw new Ctor(message); +}; +var checkPath = function checkPath(path, originalPath, doThrow) { + if (!isString(path)) { + return doThrow("path must be a string, but got `".concat(originalPath, "`"), TypeError); + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow("path must not be empty", TypeError); + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + var r = '`path.relative()`d'; + return doThrow("path should be a ".concat(r, " string, but got \"").concat(originalPath, "\""), RangeError); + } + return true; +}; +var isNotRelative = function isNotRelative(path) { + return REGEX_TEST_INVALID_PATH.test(path); +}; +checkPath.isNotRelative = isNotRelative; + +// On windows, the following function will be replaced +/* istanbul ignore next */ +checkPath.convert = function (p) { + return p; +}; +var Ignore = /*#__PURE__*/function () { + function Ignore() { + var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref4$ignorecase = _ref4.ignorecase, + ignorecase = _ref4$ignorecase === void 0 ? true : _ref4$ignorecase, + _ref4$ignoreCase = _ref4.ignoreCase, + ignoreCase = _ref4$ignoreCase === void 0 ? ignorecase : _ref4$ignoreCase, + _ref4$allowRelativePa = _ref4.allowRelativePaths, + allowRelativePaths = _ref4$allowRelativePa === void 0 ? false : _ref4$allowRelativePa; + _classCallCheck(this, Ignore); + define(this, KEY_IGNORE, true); + this._rules = new RuleManager(ignoreCase); + this._strictPathCheck = !allowRelativePaths; + this._initCache(); + } + _createClass(Ignore, [{ + key: "_initCache", + value: function _initCache() { + // A cache for the result of `.ignores()` + this._ignoreCache = Object.create(null); + + // A cache for the result of `.test()` + this._testCache = Object.create(null); + } + }, { + key: "add", + value: function add(pattern) { + if (this._rules.add(pattern)) { + // Some rules have just added to the ignore, + // making the behavior changed, + // so we need to re-initialize the result cache + this._initCache(); + } + return this; + } + + // legacy + }, { + key: "addPattern", + value: function addPattern(pattern) { + return this.add(pattern); + } + + // @returns {TestResult} + }, { + key: "_test", + value: function _test(originalPath, cache, checkUnignored, slices) { + var path = originalPath + // Supports nullable path + && checkPath.convert(originalPath); + checkPath(path, originalPath, this._strictPathCheck ? throwError : RETURN_FALSE); + return this._t(path, cache, checkUnignored, slices); + } + }, { + key: "checkIgnore", + value: function checkIgnore(path) { + // If the path doest not end with a slash, `.ignores()` is much equivalent + // to `git check-ignore` + if (!REGEX_TEST_TRAILING_SLASH.test(path)) { + return this.test(path); + } + var slices = path.split(SLASH).filter(Boolean); + slices.pop(); + if (slices.length) { + var parent = this._t(slices.join(SLASH) + SLASH, this._testCache, true, slices); + if (parent.ignored) { + return parent; + } + } + return this._rules.test(path, false, MODE_CHECK_IGNORE); + } + }, { + key: "_t", + value: function _t( + // The path to be tested + path, + // The cache for the result of a certain checking + cache, + // Whether should check if the path is unignored + checkUnignored, + // The path slices + slices) { + if (path in cache) { + return cache[path]; + } + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH).filter(Boolean); + } + slices.pop(); + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE); + } + var parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices); + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent : this._rules.test(path, checkUnignored, MODE_IGNORE); + } + }, { + key: "ignores", + value: function ignores(path) { + return this._test(path, this._ignoreCache, false).ignored; + } + }, { + key: "createFilter", + value: function createFilter() { + var _this = this; + return function (path) { + return !_this.ignores(path); + }; + } + }, { + key: "filter", + value: function filter(paths) { + return makeArray(paths).filter(this.createFilter()); + } + + // @returns {TestResult} + }, { + key: "test", + value: function test(path) { + return this._test(path, this._testCache, true); + } + }]); + return Ignore; +}(); +var factory = function factory(options) { + return new Ignore(options); +}; +var isPathValid = function isPathValid(path) { + return checkPath(path && checkPath.convert(path), path, RETURN_FALSE); +}; + +/* istanbul ignore next */ +var setupWindows = function setupWindows() { + /* eslint no-control-regex: "off" */ + var makePosix = function makePosix(str) { + return /^\\\\\?\\/.test(str) || /[\0-\x1F"<>\|]+/.test(str) ? str : str.replace(/\\/g, '/'); + }; + checkPath.convert = makePosix; + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + var REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + checkPath.isNotRelative = function (path) { + return REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path); + }; +}; + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore next */ +if ( +// Detect `process` so that it can run in browsers. +typeof process !== 'undefined' && process.platform === 'win32') { + setupWindows(); +} + +// COMMONJS_EXPORTS //////////////////////////////////////////////////////////// + +module.exports = factory; + +// Although it is an anti-pattern, +// it is still widely misused by a lot of libraries in github +// Ref: https://github.com/search?q=ignore.default%28%29&type=code +factory["default"] = factory; +module.exports.isPathValid = isPathValid; + +// For testing purposes +define(module.exports, Symbol["for"]('setupWindows'), setupWindows); diff --git a/node_modules/ignore/package.json b/node_modules/ignore/package.json new file mode 100644 index 00000000..d787bc4d --- /dev/null +++ b/node_modules/ignore/package.json @@ -0,0 +1,87 @@ +{ + "name": "ignore", + "version": "7.0.5", + "description": "Ignore is a manager and filter for .gitignore rules, the one used by eslint, gitbook and many others.", + "types": "index.d.ts", + "files": [ + "legacy.js", + "index.js", + "index.d.ts", + "LICENSE-MIT" + ], + "scripts": { + "prepublishOnly": "npm run build", + "build": "babel -o legacy.js index.js", + + "==================== linting ======================": "", + "lint": "eslint .", + + "===================== import ======================": "", + "ts": "npm run test:ts && npm run test:16", + "test:ts": "ts-node ./test/import/simple.ts", + "test:16": "npm run test:ts:16 && npm run test:cjs:16 && npm run test:mjs:16", + "test:ts:16": "ts-node --compilerOptions '{\"moduleResolution\": \"Node16\", \"module\": \"Node16\"}' ./test/import/simple.ts && tsc ./test/import/simple.ts --lib ES6 --moduleResolution Node16 --module Node16 && node ./test/import/simple.js", + "test:cjs:16": "ts-node --compilerOptions '{\"moduleResolution\": \"Node16\", \"module\": \"Node16\"}' ./test/import/simple.cjs", + "test:mjs:16": "ts-node --compilerOptions '{\"moduleResolution\": \"Node16\", \"module\": \"Node16\"}' ./test/import/simple.mjs && babel -o ./test/import/simple-mjs.js ./test/import/simple.mjs && node ./test/import/simple-mjs.js", + + "===================== cases =======================": "", + "test:cases": "npm run tap test/*.test.js -- --coverage", + "tap": "tap --reporter classic", + + "===================== debug =======================": "", + "test:git": "npm run tap test/git-check-ignore.test.js", + "test:ignore": "npm run tap test/ignore.test.js", + "test:ignore:only": "IGNORE_ONLY_IGNORES=1 npm run tap test/ignore.test.js", + "test:others": "npm run tap test/others.test.js", + "test:no-coverage": "npm run tap test/*.test.js -- --no-check-coverage", + + "test": "npm run lint && npm run ts && npm run build && npm run test:cases", + "test:win32": "IGNORE_TEST_WIN32=1 npm run test", + "report": "tap --coverage-report=html" + }, + "repository": { + "type": "git", + "url": "git@github.com:kaelzhang/node-ignore.git" + }, + "keywords": [ + "ignore", + ".gitignore", + "gitignore", + "npmignore", + "rules", + "manager", + "filter", + "regexp", + "regex", + "fnmatch", + "glob", + "asterisks", + "regular-expression" + ], + "author": "kael", + "license": "MIT", + "bugs": { + "url": "https://github.com/kaelzhang/node-ignore/issues" + }, + "devDependencies": { + "@babel/cli": "^7.22.9", + "@babel/core": "^7.22.9", + "@babel/preset-env": "^7.22.9", + "@typescript-eslint/eslint-plugin": "^8.19.1", + "debug": "^4.3.4", + "eslint": "^8.46.0", + "eslint-config-ostai": "^3.0.0", + "eslint-plugin-import": "^2.28.0", + "mkdirp": "^3.0.1", + "pre-suf": "^1.1.1", + "rimraf": "^6.0.1", + "spawn-sync": "^2.0.0", + "tap": "^16.3.9", + "tmp": "0.2.3", + "ts-node": "^10.9.2", + "typescript": "^5.6.2" + }, + "engines": { + "node": ">= 4" + } +} diff --git a/node_modules/import-fresh/index.d.ts b/node_modules/import-fresh/index.d.ts new file mode 100644 index 00000000..36d7e208 --- /dev/null +++ b/node_modules/import-fresh/index.d.ts @@ -0,0 +1,30 @@ +/** +Import a module while bypassing the cache. + +@example +``` +// foo.js +let i = 0; +module.exports = () => ++i; + +// index.js +import importFresh = require('import-fresh'); + +require('./foo')(); +//=> 1 + +require('./foo')(); +//=> 2 + +importFresh('./foo')(); +//=> 1 + +importFresh('./foo')(); +//=> 1 + +const foo = importFresh('./foo'); +``` +*/ +declare function importFresh(moduleId: string): T; + +export = importFresh; diff --git a/node_modules/import-fresh/index.js b/node_modules/import-fresh/index.js new file mode 100644 index 00000000..1bed8765 --- /dev/null +++ b/node_modules/import-fresh/index.js @@ -0,0 +1,34 @@ +'use strict'; +const path = require('path'); +const resolveFrom = require('resolve-from'); +const parentModule = require('parent-module'); + +module.exports = moduleId => { + if (typeof moduleId !== 'string') { + throw new TypeError('Expected a string'); + } + + const parentPath = parentModule(__filename); + + const cwd = parentPath ? path.dirname(parentPath) : __dirname; + const filePath = resolveFrom(cwd, moduleId); + + const oldModule = require.cache[filePath]; + // Delete itself from module parent + if (oldModule && oldModule.parent) { + let i = oldModule.parent.children.length; + + while (i--) { + if (oldModule.parent.children[i].id === filePath) { + oldModule.parent.children.splice(i, 1); + } + } + } + + delete require.cache[filePath]; // Delete module from cache + + const parent = require.cache[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step + + // In case cache doesn't have parent, fall back to normal require + return parent === undefined || parent.require === undefined ? require(filePath) : parent.require(filePath); +}; diff --git a/node_modules/import-fresh/license b/node_modules/import-fresh/license new file mode 100644 index 00000000..fa7ceba3 --- /dev/null +++ b/node_modules/import-fresh/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/import-fresh/package.json b/node_modules/import-fresh/package.json new file mode 100644 index 00000000..4e8b8416 --- /dev/null +++ b/node_modules/import-fresh/package.json @@ -0,0 +1,48 @@ +{ + "name": "import-fresh", + "version": "3.3.1", + "description": "Import a module while bypassing the cache", + "license": "MIT", + "repository": "sindresorhus/import-fresh", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "sideEffects": false, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd", + "heapdump": "node heapdump.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "require", + "cache", + "uncache", + "uncached", + "module", + "fresh", + "bypass" + ], + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "devDependencies": { + "ava": "^1.0.1", + "heapdump": "^0.3.12", + "tsd": "^0.7.3", + "xo": "^0.23.0" + } +} diff --git a/node_modules/import-fresh/readme.md b/node_modules/import-fresh/readme.md new file mode 100644 index 00000000..a868bc62 --- /dev/null +++ b/node_modules/import-fresh/readme.md @@ -0,0 +1,54 @@ +# import-fresh + +> Import a module while bypassing the [cache](https://nodejs.org/api/modules.html#modules_caching) + +Useful for testing purposes when you need to freshly import a module. + +## ESM + +For ESM, you can use this snippet: + +```js +const importFresh = moduleName => import(`${moduleName}?${Date.now()}`); + +const {default: foo} = await importFresh('foo'); +``` + +**This snippet causes a memory leak, so only use it for short-lived tests.** + +## Install + +```sh +npm install import-fresh +``` + +## Usage + +```js +// foo.js +let i = 0; +module.exports = () => ++i; +``` + +```js +const importFresh = require('import-fresh'); + +require('./foo')(); +//=> 1 + +require('./foo')(); +//=> 2 + +importFresh('./foo')(); +//=> 1 + +importFresh('./foo')(); +//=> 1 +``` + +## Related + +- [clear-module](https://github.com/sindresorhus/clear-module) - Clear a module from the import cache +- [import-from](https://github.com/sindresorhus/import-from) - Import a module from a given path +- [import-cwd](https://github.com/sindresorhus/import-cwd) - Import a module from the current working directory +- [import-lazy](https://github.com/sindresorhus/import-lazy) - Import modules lazily diff --git a/node_modules/imurmurhash/README.md b/node_modules/imurmurhash/README.md new file mode 100644 index 00000000..f35b20a0 --- /dev/null +++ b/node_modules/imurmurhash/README.md @@ -0,0 +1,122 @@ +iMurmurHash.js +============== + +An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). + +This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. + +Installation +------------ + +To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. + +```html + + +``` + +--- + +To use iMurmurHash in Node.js, install the module using NPM: + +```bash +npm install imurmurhash +``` + +Then simply include it in your scripts: + +```javascript +MurmurHash3 = require('imurmurhash'); +``` + +Quick Example +------------- + +```javascript +// Create the initial hash +var hashState = MurmurHash3('string'); + +// Incrementally add text +hashState.hash('more strings'); +hashState.hash('even more strings'); + +// All calls can be chained if desired +hashState.hash('and').hash('some').hash('more'); + +// Get a result +hashState.result(); +// returns 0xe4ccfe6b +``` + +Functions +--------- + +### MurmurHash3 ([string], [seed]) +Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: + +```javascript +// Use the cached object, calling the function again will return the same +// object (but reset, so the current state would be lost) +hashState = MurmurHash3(); +... + +// Create a new object that can be safely used however you wish. Calling the +// function again will simply return a new state object, and no state loss +// will occur, at the cost of creating more objects. +hashState = new MurmurHash3(); +``` + +Both methods can be mixed however you like if you have different use cases. + +--- + +### MurmurHash3.prototype.hash (string) +Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. + +--- + +### MurmurHash3.prototype.result () +Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. + +```javascript +// Do the whole string at once +MurmurHash3('this is a test string').result(); +// 0x70529328 + +// Do part of the string, get a result, then the other part +var m = MurmurHash3('this is a'); +m.result(); +// 0xbfc4f834 +m.hash(' test string').result(); +// 0x70529328 (same as above) +``` + +--- + +### MurmurHash3.prototype.reset ([seed]) +Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. + +--- + +License (MIT) +------------- +Copyright (c) 2013 Gary Court, Jens Taylor + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/imurmurhash/imurmurhash.js b/node_modules/imurmurhash/imurmurhash.js new file mode 100644 index 00000000..e63146a2 --- /dev/null +++ b/node_modules/imurmurhash/imurmurhash.js @@ -0,0 +1,138 @@ +/** + * @preserve + * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * + * @author Jens Taylor + * @see http://github.com/homebrewing/brauhaus-diff + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + */ +(function(){ + var cache; + + // Call this function without `new` to use the cached object (good for + // single-threaded environments), or with `new` to create a new object. + // + // @param {string} key A UTF-16 or ASCII string + // @param {number} seed An optional positive integer + // @return {object} A MurmurHash3 object for incremental hashing + function MurmurHash3(key, seed) { + var m = this instanceof MurmurHash3 ? this : cache; + m.reset(seed) + if (typeof key === 'string' && key.length > 0) { + m.hash(key); + } + + if (m !== this) { + return m; + } + }; + + // Incrementally add a string to this hash + // + // @param {string} key A UTF-16 or ASCII string + // @return {object} this + MurmurHash3.prototype.hash = function(key) { + var h1, k1, i, top, len; + + len = key.length; + this.len += len; + + k1 = this.k1; + i = 0; + switch (this.rem) { + case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; + case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; + case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; + case 3: + k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; + k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; + } + + this.rem = (len + this.rem) & 3; // & 3 is same as % 4 + len -= this.rem; + if (len > 0) { + h1 = this.h1; + while (1) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; + + if (i >= len) { + break; + } + + k1 = ((key.charCodeAt(i++) & 0xffff)) ^ + ((key.charCodeAt(i++) & 0xffff) << 8) ^ + ((key.charCodeAt(i++) & 0xffff) << 16); + top = key.charCodeAt(i++); + k1 ^= ((top & 0xff) << 24) ^ + ((top & 0xff00) >> 8); + } + + k1 = 0; + switch (this.rem) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xffff); + } + + this.h1 = h1; + } + + this.k1 = k1; + return this; + }; + + // Get the result of this hash + // + // @return {number} The 32-bit hash + MurmurHash3.prototype.result = function() { + var k1, h1; + + k1 = this.k1; + h1 = this.h1; + + if (k1 > 0) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= this.len; + + h1 ^= h1 >>> 16; + h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; + }; + + // Reset the hash object for reuse + // + // @param {number} seed An optional positive integer + MurmurHash3.prototype.reset = function(seed) { + this.h1 = typeof seed === 'number' ? seed : 0; + this.rem = this.k1 = this.len = 0; + return this; + }; + + // A cached object to use. This can be safely used if you're in a single- + // threaded environment, otherwise you need to create new hashes to use. + cache = new MurmurHash3(); + + if (typeof(module) != 'undefined') { + module.exports = MurmurHash3; + } else { + this.MurmurHash3 = MurmurHash3; + } +}()); diff --git a/node_modules/imurmurhash/imurmurhash.min.js b/node_modules/imurmurhash/imurmurhash.min.js new file mode 100644 index 00000000..dc0ee88d --- /dev/null +++ b/node_modules/imurmurhash/imurmurhash.min.js @@ -0,0 +1,12 @@ +/** + * @preserve + * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * + * @author Jens Taylor + * @see http://github.com/homebrewing/brauhaus-diff + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + */ +!function(){function t(h,r){var s=this instanceof t?this:e;return s.reset(r),"string"==typeof h&&h.length>0&&s.hash(h),s!==this?s:void 0}var e;t.prototype.hash=function(t){var e,h,r,s,i;switch(i=t.length,this.len+=i,h=this.k1,r=0,this.rem){case 0:h^=i>r?65535&t.charCodeAt(r++):0;case 1:h^=i>r?(65535&t.charCodeAt(r++))<<8:0;case 2:h^=i>r?(65535&t.charCodeAt(r++))<<16:0;case 3:h^=i>r?(255&t.charCodeAt(r))<<24:0,h^=i>r?(65280&t.charCodeAt(r++))>>8:0}if(this.rem=3&i+this.rem,i-=this.rem,i>0){for(e=this.h1;;){if(h=4294967295&11601*h+3432906752*(65535&h),h=h<<15|h>>>17,h=4294967295&13715*h+461832192*(65535&h),e^=h,e=e<<13|e>>>19,e=4294967295&5*e+3864292196,r>=i)break;h=65535&t.charCodeAt(r++)^(65535&t.charCodeAt(r++))<<8^(65535&t.charCodeAt(r++))<<16,s=t.charCodeAt(r++),h^=(255&s)<<24^(65280&s)>>8}switch(h=0,this.rem){case 3:h^=(65535&t.charCodeAt(r+2))<<16;case 2:h^=(65535&t.charCodeAt(r+1))<<8;case 1:h^=65535&t.charCodeAt(r)}this.h1=e}return this.k1=h,this},t.prototype.result=function(){var t,e;return t=this.k1,e=this.h1,t>0&&(t=4294967295&11601*t+3432906752*(65535&t),t=t<<15|t>>>17,t=4294967295&13715*t+461832192*(65535&t),e^=t),e^=this.len,e^=e>>>16,e=4294967295&51819*e+2246770688*(65535&e),e^=e>>>13,e=4294967295&44597*e+3266445312*(65535&e),e^=e>>>16,e>>>0},t.prototype.reset=function(t){return this.h1="number"==typeof t?t:0,this.rem=this.k1=this.len=0,this},e=new t,"undefined"!=typeof module?module.exports=t:this.MurmurHash3=t}(); \ No newline at end of file diff --git a/node_modules/imurmurhash/package.json b/node_modules/imurmurhash/package.json new file mode 100644 index 00000000..8a93edb5 --- /dev/null +++ b/node_modules/imurmurhash/package.json @@ -0,0 +1,40 @@ +{ + "name": "imurmurhash", + "version": "0.1.4", + "description": "An incremental implementation of MurmurHash3", + "homepage": "https://github.com/jensyt/imurmurhash-js", + "main": "imurmurhash.js", + "files": [ + "imurmurhash.js", + "imurmurhash.min.js", + "package.json", + "README.md" + ], + "repository": { + "type": "git", + "url": "https://github.com/jensyt/imurmurhash-js" + }, + "bugs": { + "url": "https://github.com/jensyt/imurmurhash-js/issues" + }, + "keywords": [ + "murmur", + "murmurhash", + "murmurhash3", + "hash", + "incremental" + ], + "author": { + "name": "Jens Taylor", + "email": "jensyt@gmail.com", + "url": "https://github.com/homebrewing" + }, + "license": "MIT", + "dependencies": { + }, + "devDependencies": { + }, + "engines": { + "node": ">=0.8.19" + } +} diff --git a/node_modules/is-extglob/LICENSE b/node_modules/is-extglob/LICENSE new file mode 100644 index 00000000..842218cf --- /dev/null +++ b/node_modules/is-extglob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2016, Jon Schlinkert + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-extglob/README.md b/node_modules/is-extglob/README.md new file mode 100644 index 00000000..0416af5c --- /dev/null +++ b/node_modules/is-extglob/README.md @@ -0,0 +1,107 @@ +# is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) + +> Returns true if a string has an extglob. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-extglob +``` + +## Usage + +```js +var isExtglob = require('is-extglob'); +``` + +**True** + +```js +isExtglob('?(abc)'); +isExtglob('@(abc)'); +isExtglob('!(abc)'); +isExtglob('*(abc)'); +isExtglob('+(abc)'); +``` + +**False** + +Escaped extglobs: + +```js +isExtglob('\\?(abc)'); +isExtglob('\\@(abc)'); +isExtglob('\\!(abc)'); +isExtglob('\\*(abc)'); +isExtglob('\\+(abc)'); +``` + +Everything else... + +```js +isExtglob('foo.js'); +isExtglob('!foo.js'); +isExtglob('*.js'); +isExtglob('**/abc.js'); +isExtglob('abc/*.js'); +isExtglob('abc/(aaa|bbb).js'); +isExtglob('abc/[a-z].js'); +isExtglob('abc/{a,b}.js'); +isExtglob('abc/?.js'); +isExtglob('abc.js'); +isExtglob('abc/def/ghi.js'); +``` + +## History + +**v2.0** + +Adds support for escaping. Escaped exglobs no longer return true. + +## About + +### Related projects + +* [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") +* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") +* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") + +### Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +### Building docs + +_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ + +To generate the readme and API documentation with [verb](https://github.com/verbose/verb): + +```sh +$ npm install -g verb verb-generate-readme && verb +``` + +### Running tests + +Install dev dependencies: + +```sh +$ npm install -d && npm test +``` + +### Author + +**Jon Schlinkert** + +* [github/jonschlinkert](https://github.com/jonschlinkert) +* [twitter/jonschlinkert](http://twitter.com/jonschlinkert) + +### License + +Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ \ No newline at end of file diff --git a/node_modules/is-extglob/index.js b/node_modules/is-extglob/index.js new file mode 100644 index 00000000..c1d986fc --- /dev/null +++ b/node_modules/is-extglob/index.js @@ -0,0 +1,20 @@ +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +module.exports = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; diff --git a/node_modules/is-extglob/package.json b/node_modules/is-extglob/package.json new file mode 100644 index 00000000..7a908369 --- /dev/null +++ b/node_modules/is-extglob/package.json @@ -0,0 +1,69 @@ +{ + "name": "is-extglob", + "description": "Returns true if a string has an extglob.", + "version": "2.1.1", + "homepage": "https://github.com/jonschlinkert/is-extglob", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "repository": "jonschlinkert/is-extglob", + "bugs": { + "url": "https://github.com/jonschlinkert/is-extglob/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "has-glob", + "is-glob", + "micromatch" + ] + }, + "reflinks": [ + "verb", + "verb-generate-readme" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/is-glob/LICENSE b/node_modules/is-glob/LICENSE new file mode 100644 index 00000000..3f2eca18 --- /dev/null +++ b/node_modules/is-glob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2017, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-glob/README.md b/node_modules/is-glob/README.md new file mode 100644 index 00000000..740724b2 --- /dev/null +++ b/node_modules/is-glob/README.md @@ -0,0 +1,206 @@ +# is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) + +> Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-glob +``` + +You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). + +## Usage + +```js +var isGlob = require('is-glob'); +``` + +### Default behavior + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js'); +isGlob('*.js'); +isGlob('**/abc.js'); +isGlob('abc/*.js'); +isGlob('abc/(aaa|bbb).js'); +isGlob('abc/[a-z].js'); +isGlob('abc/{a,b}.js'); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js'); +isGlob('abc/!(a).js'); +isGlob('abc/+(a).js'); +isGlob('abc/*(a).js'); +isGlob('abc/?(a).js'); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('abc/\\@(a).js'); +isGlob('abc/\\!(a).js'); +isGlob('abc/\\+(a).js'); +isGlob('abc/\\*(a).js'); +isGlob('abc/\\?(a).js'); +isGlob('\\!foo.js'); +isGlob('\\*.js'); +isGlob('\\*\\*/abc.js'); +isGlob('abc/\\*.js'); +isGlob('abc/\\(aaa|bbb).js'); +isGlob('abc/\\[a-z].js'); +isGlob('abc/\\{a,b}.js'); +//=> false +``` + +Patterns that do not have glob patterns return `false`: + +```js +isGlob('abc.js'); +isGlob('abc/def/ghi.js'); +isGlob('foo.js'); +isGlob('abc/@.js'); +isGlob('abc/+.js'); +isGlob('abc/?.js'); +isGlob(); +isGlob(null); +//=> false +``` + +Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): + +```js +isGlob(['**/*.js']); +isGlob(['foo.js']); +//=> false +``` + +### Option strict + +When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that +some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js', {strict: false}); +isGlob('*.js', {strict: false}); +isGlob('**/abc.js', {strict: false}); +isGlob('abc/*.js', {strict: false}); +isGlob('abc/(aaa|bbb).js', {strict: false}); +isGlob('abc/[a-z].js', {strict: false}); +isGlob('abc/{a,b}.js', {strict: false}); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js', {strict: false}); +isGlob('abc/!(a).js', {strict: false}); +isGlob('abc/+(a).js', {strict: false}); +isGlob('abc/*(a).js', {strict: false}); +isGlob('abc/?(a).js', {strict: false}); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('\\!foo.js', {strict: false}); +isGlob('\\*.js', {strict: false}); +isGlob('\\*\\*/abc.js', {strict: false}); +isGlob('abc/\\*.js', {strict: false}); +isGlob('abc/\\(aaa|bbb).js', {strict: false}); +isGlob('abc/\\[a-z].js', {strict: false}); +isGlob('abc/\\{a,b}.js', {strict: false}); +//=> false +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") +* [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") +* [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") +* [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 47 | [jonschlinkert](https://github.com/jonschlinkert) | +| 5 | [doowb](https://github.com/doowb) | +| 1 | [phated](https://github.com/phated) | +| 1 | [danhper](https://github.com/danhper) | +| 1 | [paulmillr](https://github.com/paulmillr) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ \ No newline at end of file diff --git a/node_modules/is-glob/index.js b/node_modules/is-glob/index.js new file mode 100644 index 00000000..620f563e --- /dev/null +++ b/node_modules/is-glob/index.js @@ -0,0 +1,150 @@ +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var isExtglob = require('is-extglob'); +var chars = { '{': '}', '(': ')', '[': ']'}; +var strictCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + var pipeIndex = -2; + var closeSquareIndex = -2; + var closeCurlyIndex = -2; + var closeParenIndex = -2; + var backSlashIndex = -2; + while (index < str.length) { + if (str[index] === '*') { + return true; + } + + if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { + return true; + } + + if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { + if (closeSquareIndex < index) { + closeSquareIndex = str.indexOf(']', index); + } + if (closeSquareIndex > index) { + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + } + } + + if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { + closeCurlyIndex = str.indexOf('}', index); + if (closeCurlyIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { + return true; + } + } + } + + if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { + closeParenIndex = str.indexOf(')', index); + if (closeParenIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + + if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { + if (pipeIndex < index) { + pipeIndex = str.indexOf('|', index); + } + if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { + closeParenIndex = str.indexOf(')', pipeIndex); + if (closeParenIndex > pipeIndex) { + backSlashIndex = str.indexOf('\\', pipeIndex); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +var relaxedCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + while (index < str.length) { + if (/[*?{}()[\]]/.test(str[index])) { + return true; + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +module.exports = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var check = strictCheck; + + // optionally relax check + if (options && options.strict === false) { + check = relaxedCheck; + } + + return check(str); +}; diff --git a/node_modules/is-glob/package.json b/node_modules/is-glob/package.json new file mode 100644 index 00000000..858af037 --- /dev/null +++ b/node_modules/is-glob/package.json @@ -0,0 +1,81 @@ +{ + "name": "is-glob", + "description": "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience.", + "version": "4.0.3", + "homepage": "https://github.com/micromatch/is-glob", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Brian Woodward (https://twitter.com/doowb)", + "Daniel Perez (https://tuvistavie.com)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)" + ], + "repository": "micromatch/is-glob", + "bugs": { + "url": "https://github.com/micromatch/is-glob/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha && node benchmark.js" + }, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "verb": { + "layout": "default", + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "assemble", + "base", + "update", + "verb" + ] + }, + "reflinks": [ + "assemble", + "bach", + "base", + "composer", + "gulp", + "has-glob", + "is-valid-glob", + "micromatch", + "npm", + "scaffold", + "verb", + "vinyl" + ] + } +} diff --git a/node_modules/is-number/LICENSE b/node_modules/is-number/LICENSE new file mode 100644 index 00000000..9af4a67d --- /dev/null +++ b/node_modules/is-number/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-number/README.md b/node_modules/is-number/README.md new file mode 100644 index 00000000..eb8149e8 --- /dev/null +++ b/node_modules/is-number/README.md @@ -0,0 +1,187 @@ +# is-number [![NPM version](https://img.shields.io/npm/v/is-number.svg?style=flat)](https://www.npmjs.com/package/is-number) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![NPM total downloads](https://img.shields.io/npm/dt/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-number.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-number) + +> Returns true if the value is a finite number. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-number +``` + +## Why is this needed? + +In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use `+`, `-`, or `Number()` to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results: + +```js +console.log(+[]); //=> 0 +console.log(+''); //=> 0 +console.log(+' '); //=> 0 +console.log(typeof NaN); //=> 'number' +``` + +This library offers a performant way to smooth out edge cases like these. + +## Usage + +```js +const isNumber = require('is-number'); +``` + +See the [tests](./test.js) for more examples. + +### true + +```js +isNumber(5e3); // true +isNumber(0xff); // true +isNumber(-1.1); // true +isNumber(0); // true +isNumber(1); // true +isNumber(1.1); // true +isNumber(10); // true +isNumber(10.10); // true +isNumber(100); // true +isNumber('-1.1'); // true +isNumber('0'); // true +isNumber('012'); // true +isNumber('0xff'); // true +isNumber('1'); // true +isNumber('1.1'); // true +isNumber('10'); // true +isNumber('10.10'); // true +isNumber('100'); // true +isNumber('5e3'); // true +isNumber(parseInt('012')); // true +isNumber(parseFloat('012')); // true +``` + +### False + +Everything else is false, as you would expect: + +```js +isNumber(Infinity); // false +isNumber(NaN); // false +isNumber(null); // false +isNumber(undefined); // false +isNumber(''); // false +isNumber(' '); // false +isNumber('foo'); // false +isNumber([1]); // false +isNumber([]); // false +isNumber(function () {}); // false +isNumber({}); // false +``` + +## Release history + +### 7.0.0 + +* Refactor. Now uses `.isFinite` if it exists. +* Performance is about the same as v6.0 when the value is a string or number. But it's now 3x-4x faster when the value is not a string or number. + +### 6.0.0 + +* Optimizations, thanks to @benaadams. + +### 5.0.0 + +**Breaking changes** + +* removed support for `instanceof Number` and `instanceof String` + +## Benchmarks + +As with all benchmarks, take these with a grain of salt. See the [benchmarks](./benchmark/index.js) for more detail. + +``` +# all +v7.0 x 413,222 ops/sec ±2.02% (86 runs sampled) +v6.0 x 111,061 ops/sec ±1.29% (85 runs sampled) +parseFloat x 317,596 ops/sec ±1.36% (86 runs sampled) +fastest is 'v7.0' + +# string +v7.0 x 3,054,496 ops/sec ±1.05% (89 runs sampled) +v6.0 x 2,957,781 ops/sec ±0.98% (88 runs sampled) +parseFloat x 3,071,060 ops/sec ±1.13% (88 runs sampled) +fastest is 'parseFloat,v7.0' + +# number +v7.0 x 3,146,895 ops/sec ±0.89% (89 runs sampled) +v6.0 x 3,214,038 ops/sec ±1.07% (89 runs sampled) +parseFloat x 3,077,588 ops/sec ±1.07% (87 runs sampled) +fastest is 'v6.0' +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") +* [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") +* [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") +* [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 49 | [jonschlinkert](https://github.com/jonschlinkert) | +| 5 | [charlike-old](https://github.com/charlike-old) | +| 1 | [benaadams](https://github.com/benaadams) | +| 1 | [realityking](https://github.com/realityking) | + +### Author + +**Jon Schlinkert** + +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) + +### License + +Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 15, 2018._ \ No newline at end of file diff --git a/node_modules/is-number/index.js b/node_modules/is-number/index.js new file mode 100644 index 00000000..27f19b75 --- /dev/null +++ b/node_modules/is-number/index.js @@ -0,0 +1,18 @@ +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +module.exports = function(num) { + if (typeof num === 'number') { + return num - num === 0; + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; +}; diff --git a/node_modules/is-number/package.json b/node_modules/is-number/package.json new file mode 100644 index 00000000..37150726 --- /dev/null +++ b/node_modules/is-number/package.json @@ -0,0 +1,82 @@ +{ + "name": "is-number", + "description": "Returns true if a number or string value is a finite number. Useful for regex matches, parsing, user input, etc.", + "version": "7.0.0", + "homepage": "https://github.com/jonschlinkert/is-number", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Olsten Larck (https://i.am.charlike.online)", + "Rouven Weßling (www.rouvenwessling.de)" + ], + "repository": "jonschlinkert/is-number", + "bugs": { + "url": "https://github.com/jonschlinkert/is-number/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.12.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "gulp-format-md": "^1.0.0", + "mocha": "^3.5.3" + }, + "keywords": [ + "cast", + "check", + "coerce", + "coercion", + "finite", + "integer", + "is", + "isnan", + "is-nan", + "is-num", + "is-number", + "isnumber", + "isfinite", + "istype", + "kind", + "math", + "nan", + "num", + "number", + "numeric", + "parseFloat", + "parseInt", + "test", + "type", + "typeof", + "value" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "related": { + "list": [ + "is-plain-object", + "is-primitive", + "isobject", + "kind-of" + ] + }, + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/isexe/.npmignore b/node_modules/isexe/.npmignore new file mode 100644 index 00000000..c1cb757a --- /dev/null +++ b/node_modules/isexe/.npmignore @@ -0,0 +1,2 @@ +.nyc_output/ +coverage/ diff --git a/node_modules/isexe/LICENSE b/node_modules/isexe/LICENSE new file mode 100644 index 00000000..19129e31 --- /dev/null +++ b/node_modules/isexe/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/isexe/README.md b/node_modules/isexe/README.md new file mode 100644 index 00000000..35769e84 --- /dev/null +++ b/node_modules/isexe/README.md @@ -0,0 +1,51 @@ +# isexe + +Minimal module to check if a file is executable, and a normal file. + +Uses `fs.stat` and tests against the `PATHEXT` environment variable on +Windows. + +## USAGE + +```javascript +var isexe = require('isexe') +isexe('some-file-name', function (err, isExe) { + if (err) { + console.error('probably file does not exist or something', err) + } else if (isExe) { + console.error('this thing can be run') + } else { + console.error('cannot be run') + } +}) + +// same thing but synchronous, throws errors +var isExe = isexe.sync('some-file-name') + +// treat errors as just "not executable" +isexe('maybe-missing-file', { ignoreErrors: true }, callback) +var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) +``` + +## API + +### `isexe(path, [options], [callback])` + +Check if the path is executable. If no callback provided, and a +global `Promise` object is available, then a Promise will be returned. + +Will raise whatever errors may be raised by `fs.stat`, unless +`options.ignoreErrors` is set to true. + +### `isexe.sync(path, [options])` + +Same as `isexe` but returns the value and throws any errors raised. + +### Options + +* `ignoreErrors` Treat all errors as "no, this is not executable", but + don't raise them. +* `uid` Number to use as the user id +* `gid` Number to use as the group id +* `pathExt` List of path extensions to use instead of `PATHEXT` + environment variable on Windows. diff --git a/node_modules/isexe/index.js b/node_modules/isexe/index.js new file mode 100644 index 00000000..553fb32b --- /dev/null +++ b/node_modules/isexe/index.js @@ -0,0 +1,57 @@ +var fs = require('fs') +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = require('./windows.js') +} else { + core = require('./mode.js') +} + +module.exports = isexe +isexe.sync = sync + +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) + } + }) + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false + } + } + cb(er, is) + }) +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} diff --git a/node_modules/isexe/mode.js b/node_modules/isexe/mode.js new file mode 100644 index 00000000..1995ea4a --- /dev/null +++ b/node_modules/isexe/mode.js @@ -0,0 +1,41 @@ +module.exports = isexe +isexe.sync = sync + +var fs = require('fs') + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} + +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} + +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() + + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 + + return ret +} diff --git a/node_modules/isexe/package.json b/node_modules/isexe/package.json new file mode 100644 index 00000000..e4526894 --- /dev/null +++ b/node_modules/isexe/package.json @@ -0,0 +1,31 @@ +{ + "name": "isexe", + "version": "2.0.0", + "description": "Minimal module to check if a file is executable.", + "main": "index.js", + "directories": { + "test": "test" + }, + "devDependencies": { + "mkdirp": "^0.5.1", + "rimraf": "^2.5.0", + "tap": "^10.3.0" + }, + "scripts": { + "test": "tap test/*.js --100", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/isexe.git" + }, + "keywords": [], + "bugs": { + "url": "https://github.com/isaacs/isexe/issues" + }, + "homepage": "https://github.com/isaacs/isexe#readme" +} diff --git a/node_modules/isexe/test/basic.js b/node_modules/isexe/test/basic.js new file mode 100644 index 00000000..d926df64 --- /dev/null +++ b/node_modules/isexe/test/basic.js @@ -0,0 +1,221 @@ +var t = require('tap') +var fs = require('fs') +var path = require('path') +var fixture = path.resolve(__dirname, 'fixtures') +var meow = fixture + '/meow.cat' +var mine = fixture + '/mine.cat' +var ours = fixture + '/ours.cat' +var fail = fixture + '/fail.false' +var noent = fixture + '/enoent.exe' +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') + +var isWindows = process.platform === 'win32' +var hasAccess = typeof fs.access === 'function' +var winSkip = isWindows && 'windows' +var accessSkip = !hasAccess && 'no fs.access function' +var hasPromise = typeof Promise === 'function' +var promiseSkip = !hasPromise && 'no global Promise' + +function reset () { + delete require.cache[require.resolve('../')] + return require('../') +} + +t.test('setup fixtures', function (t) { + rimraf.sync(fixture) + mkdirp.sync(fixture) + fs.writeFileSync(meow, '#!/usr/bin/env cat\nmeow\n') + fs.chmodSync(meow, parseInt('0755', 8)) + fs.writeFileSync(fail, '#!/usr/bin/env false\n') + fs.chmodSync(fail, parseInt('0644', 8)) + fs.writeFileSync(mine, '#!/usr/bin/env cat\nmine\n') + fs.chmodSync(mine, parseInt('0744', 8)) + fs.writeFileSync(ours, '#!/usr/bin/env cat\nours\n') + fs.chmodSync(ours, parseInt('0754', 8)) + t.end() +}) + +t.test('promise', { skip: promiseSkip }, function (t) { + var isexe = reset() + t.test('meow async', function (t) { + isexe(meow).then(function (is) { + t.ok(is) + t.end() + }) + }) + t.test('fail async', function (t) { + isexe(fail).then(function (is) { + t.notOk(is) + t.end() + }) + }) + t.test('noent async', function (t) { + isexe(noent).catch(function (er) { + t.ok(er) + t.end() + }) + }) + t.test('noent ignore async', function (t) { + isexe(noent, { ignoreErrors: true }).then(function (is) { + t.notOk(is) + t.end() + }) + }) + t.end() +}) + +t.test('no promise', function (t) { + global.Promise = null + var isexe = reset() + t.throws('try to meow a promise', function () { + isexe(meow) + }) + t.end() +}) + +t.test('access', { skip: accessSkip || winSkip }, function (t) { + runTest(t) +}) + +t.test('mode', { skip: winSkip }, function (t) { + delete fs.access + delete fs.accessSync + var isexe = reset() + t.ok(isexe.sync(ours, { uid: 0, gid: 0 })) + t.ok(isexe.sync(mine, { uid: 0, gid: 0 })) + runTest(t) +}) + +t.test('windows', function (t) { + global.TESTING_WINDOWS = true + var pathExt = '.EXE;.CAT;.CMD;.COM' + t.test('pathExt option', function (t) { + runTest(t, { pathExt: '.EXE;.CAT;.CMD;.COM' }) + }) + t.test('pathExt env', function (t) { + process.env.PATHEXT = pathExt + runTest(t) + }) + t.test('no pathExt', function (t) { + // with a pathExt of '', any filename is fine. + // so the "fail" one would still pass. + runTest(t, { pathExt: '', skipFail: true }) + }) + t.test('pathext with empty entry', function (t) { + // with a pathExt of '', any filename is fine. + // so the "fail" one would still pass. + runTest(t, { pathExt: ';' + pathExt, skipFail: true }) + }) + t.end() +}) + +t.test('cleanup', function (t) { + rimraf.sync(fixture) + t.end() +}) + +function runTest (t, options) { + var isexe = reset() + + var optionsIgnore = Object.create(options || {}) + optionsIgnore.ignoreErrors = true + + if (!options || !options.skipFail) { + t.notOk(isexe.sync(fail, options)) + } + t.notOk(isexe.sync(noent, optionsIgnore)) + if (!options) { + t.ok(isexe.sync(meow)) + } else { + t.ok(isexe.sync(meow, options)) + } + + t.ok(isexe.sync(mine, options)) + t.ok(isexe.sync(ours, options)) + t.throws(function () { + isexe.sync(noent, options) + }) + + t.test('meow async', function (t) { + if (!options) { + isexe(meow, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + } else { + isexe(meow, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + } + }) + + t.test('mine async', function (t) { + isexe(mine, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + }) + + t.test('ours async', function (t) { + isexe(ours, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + }) + + if (!options || !options.skipFail) { + t.test('fail async', function (t) { + isexe(fail, options, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + } + + t.test('noent async', function (t) { + isexe(noent, options, function (er, is) { + t.ok(er) + t.notOk(is) + t.end() + }) + }) + + t.test('noent ignore async', function (t) { + isexe(noent, optionsIgnore, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + + t.test('directory is not executable', function (t) { + isexe(__dirname, options, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + + t.end() +} diff --git a/node_modules/isexe/windows.js b/node_modules/isexe/windows.js new file mode 100644 index 00000000..34996734 --- /dev/null +++ b/node_modules/isexe/windows.js @@ -0,0 +1,42 @@ +module.exports = isexe +isexe.sync = sync + +var fs = require('fs') + +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) +} diff --git a/node_modules/js-yaml/CHANGELOG.md b/node_modules/js-yaml/CHANGELOG.md new file mode 100644 index 00000000..ff2375e0 --- /dev/null +++ b/node_modules/js-yaml/CHANGELOG.md @@ -0,0 +1,616 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [4.1.0] - 2021-04-15 +### Added +- Types are now exported as `yaml.types.XXX`. +- Every type now has `options` property with original arguments kept as they were + (see `yaml.types.int.options` as an example). + +### Changed +- `Schema.extend()` now keeps old type order in case of conflicts + (e.g. Schema.extend([ a, b, c ]).extend([ b, a, d ]) is now ordered as `abcd` instead of `cbad`). + + +## [4.0.0] - 2021-01-03 +### Changed +- Check [migration guide](migrate_v3_to_v4.md) to see details for all breaking changes. +- Breaking: "unsafe" tags `!!js/function`, `!!js/regexp`, `!!js/undefined` are + moved to [js-yaml-js-types](https://github.com/nodeca/js-yaml-js-types) package. +- Breaking: removed `safe*` functions. Use `load`, `loadAll`, `dump` + instead which are all now safe by default. +- `yaml.DEFAULT_SAFE_SCHEMA` and `yaml.DEFAULT_FULL_SCHEMA` are removed, use + `yaml.DEFAULT_SCHEMA` instead. +- `yaml.Schema.create(schema, tags)` is removed, use `schema.extend(tags)` instead. +- `!!binary` now always mapped to `Uint8Array` on load. +- Reduced nesting of `/lib` folder. +- Parse numbers according to YAML 1.2 instead of YAML 1.1 (`01234` is now decimal, + `0o1234` is octal, `1:23` is parsed as string instead of base60). +- `dump()` no longer quotes `:`, `[`, `]`, `(`, `)` except when necessary, #470, #557. +- Line and column in exceptions are now formatted as `(X:Y)` instead of + `at line X, column Y` (also present in compact format), #332. +- Code snippet created in exceptions now contains multiple lines with line numbers. +- `dump()` now serializes `undefined` as `null` in collections and removes keys with + `undefined` in mappings, #571. +- `dump()` with `skipInvalid=true` now serializes invalid items in collections as null. +- Custom tags starting with `!` are now dumped as `!tag` instead of `!`, #576. +- Custom tags starting with `tag:yaml.org,2002:` are now shorthanded using `!!`, #258. + +### Added +- Added `.mjs` (es modules) support. +- Added `quotingType` and `forceQuotes` options for dumper to configure + string literal style, #290, #529. +- Added `styles: { '!!null': 'empty' }` option for dumper + (serializes `{ foo: null }` as "`foo: `"), #570. +- Added `replacer` option (similar to option in JSON.stringify), #339. +- Custom `Tag` can now handle all tags or multiple tags with the same prefix, #385. + +### Fixed +- Astral characters are no longer encoded by `dump()`, #587. +- "duplicate mapping key" exception now points at the correct column, #452. +- Extra commas in flow collections (e.g. `[foo,,bar]`) now throw an exception + instead of producing null, #321. +- `__proto__` key no longer overrides object prototype, #164. +- Removed `bower.json`. +- Tags are now url-decoded in `load()` and url-encoded in `dump()` + (previously usage of custom non-ascii tags may have led to invalid YAML that can't be parsed). +- Anchors now work correctly with empty nodes, #301. +- Fix incorrect parsing of invalid block mapping syntax, #418. +- Throw an error if block sequence/mapping indent contains a tab, #80. + + +## [3.14.1] - 2020-12-07 +### Security +- Fix possible code execution in (already unsafe) `.load()` (in &anchor). + + +## [3.14.0] - 2020-05-22 +### Changed +- Support `safe/loadAll(input, options)` variant of call. +- CI: drop outdated nodejs versions. +- Dev deps bump. + +### Fixed +- Quote `=` in plain scalars #519. +- Check the node type for `!` tag in case user manually specifies it. +- Verify that there are no null-bytes in input. +- Fix wrong quote position when writing condensed flow, #526. + + +## [3.13.1] - 2019-04-05 +### Security +- Fix possible code execution in (already unsafe) `.load()`, #480. + + +## [3.13.0] - 2019-03-20 +### Security +- Security fix: `safeLoad()` can hang when arrays with nested refs + used as key. Now throws exception for nested arrays. #475. + + +## [3.12.2] - 2019-02-26 +### Fixed +- Fix `noArrayIndent` option for root level, #468. + + +## [3.12.1] - 2019-01-05 +### Added +- Added `noArrayIndent` option, #432. + + +## [3.12.0] - 2018-06-02 +### Changed +- Support arrow functions without a block statement, #421. + + +## [3.11.0] - 2018-03-05 +### Added +- Add arrow functions suport for `!!js/function`. + +### Fixed +- Fix dump in bin/octal/hex formats for negative integers, #399. + + +## [3.10.0] - 2017-09-10 +### Fixed +- Fix `condenseFlow` output (quote keys for sure, instead of spaces), #371, #370. +- Dump astrals as codepoints instead of surrogate pair, #368. + + +## [3.9.1] - 2017-07-08 +### Fixed +- Ensure stack is present for custom errors in node 7.+, #351. + + +## [3.9.0] - 2017-07-08 +### Added +- Add `condenseFlow` option (to create pretty URL query params), #346. + +### Fixed +- Support array return from safeLoadAll/loadAll, #350. + + +## [3.8.4] - 2017-05-08 +### Fixed +- Dumper: prevent space after dash for arrays that wrap, #343. + + +## [3.8.3] - 2017-04-05 +### Fixed +- Should not allow numbers to begin and end with underscore, #335. + + +## [3.8.2] - 2017-03-02 +### Fixed +- Fix `!!float 123` (integers) parse, #333. +- Don't allow leading zeros in floats (except 0, 0.xxx). +- Allow positive exponent without sign in floats. + + +## [3.8.1] - 2017-02-07 +### Changed +- Maintenance: update browserified build. + + +## [3.8.0] - 2017-02-07 +### Fixed +- Fix reported position for `duplicated mapping key` errors. + Now points to block start instead of block end. + (#243, thanks to @shockey). + + +## [3.7.0] - 2016-11-12 +### Added +- Support polymorphism for tags (#300, thanks to @monken). + +### Fixed +- Fix parsing of quotes followed by newlines (#304, thanks to @dplepage). + + +## [3.6.1] - 2016-05-11 +### Fixed +- Fix output cut on a pipe, #286. + + +## [3.6.0] - 2016-04-16 +### Fixed +- Dumper rewrite, fix multiple bugs with trailing `\n`. + Big thanks to @aepsilon! +- Loader: fix leading/trailing newlines in block scalars, @aepsilon. + + +## [3.5.5] - 2016-03-17 +### Fixed +- Date parse fix: don't allow dates with on digit in month and day, #268. + + +## [3.5.4] - 2016-03-09 +### Added +- `noCompatMode` for dumper, to disable quoting YAML 1.1 values. + + +## [3.5.3] - 2016-02-11 +### Changed +- Maintenance release. + + +## [3.5.2] - 2016-01-11 +### Changed +- Maintenance: missed comma in bower config. + + +## [3.5.1] - 2016-01-11 +### Changed +- Removed `inherit` dependency, #239. +- Better browserify workaround for esprima load. +- Demo rewrite. + + +## [3.5.0] - 2016-01-10 +### Fixed +- Dumper. Fold strings only, #217. +- Dumper. `norefs` option, to clone linked objects, #229. +- Loader. Throw a warning for duplicate keys, #166. +- Improved browserify support (mark `esprima` & `Buffer` excluded). + + +## [3.4.6] - 2015-11-26 +### Changed +- Use standalone `inherit` to keep browserified files clear. + + +## [3.4.5] - 2015-11-23 +### Added +- Added `lineWidth` option to dumper. + + +## [3.4.4] - 2015-11-21 +### Fixed +- Fixed floats dump (missed dot for scientific format), #220. +- Allow non-printable characters inside quoted scalars, #192. + + +## [3.4.3] - 2015-10-10 +### Changed +- Maintenance release - deps bump (esprima, argparse). + + +## [3.4.2] - 2015-09-09 +### Fixed +- Fixed serialization of duplicated entries in sequences, #205. + Thanks to @vogelsgesang. + + +## [3.4.1] - 2015-09-05 +### Fixed +- Fixed stacktrace handling in generated errors, for browsers (FF/IE). + + +## [3.4.0] - 2015-08-23 +### Changed +- Don't throw on warnings anymore. Use `onWarning` option to catch. +- Throw error on unknown tags (was warning before). +- Reworked internals of error class. + +### Fixed +- Fixed multiline keys dump, #197. Thanks to @tcr. +- Fixed heading line breaks in some scalars (regression). + + +## [3.3.1] - 2015-05-13 +### Added +- Added `.sortKeys` dumper option, thanks to @rjmunro. + +### Fixed +- Fixed astral characters support, #191. + + +## [3.3.0] - 2015-04-26 +### Changed +- Significantly improved long strings formatting in dumper, thanks to @isaacs. +- Strip BOM if exists. + + +## [3.2.7] - 2015-02-19 +### Changed +- Maintenance release. +- Updated dependencies. +- HISTORY.md -> CHANGELOG.md + + +## [3.2.6] - 2015-02-07 +### Fixed +- Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE). +- Fixed demo dates dump (#113, thanks to @Hypercubed). + + +## [3.2.5] - 2014-12-28 +### Fixed +- Fixed resolving of all built-in types on empty nodes. +- Fixed invalid warning on empty lines within quoted scalars and flow collections. +- Fixed bug: Tag on an empty node didn't resolve in some cases. + + +## [3.2.4] - 2014-12-19 +### Fixed +- Fixed resolving of !!null tag on an empty node. + + +## [3.2.3] - 2014-11-08 +### Fixed +- Implemented dumping of objects with circular and cross references. +- Partially fixed aliasing of constructed objects. (see issue #141 for details) + + +## [3.2.2] - 2014-09-07 +### Fixed +- Fixed infinite loop on unindented block scalars. +- Rewritten base64 encode/decode in binary type, to keep code licence clear. + + +## [3.2.1] - 2014-08-24 +### Fixed +- Nothig new. Just fix npm publish error. + + +## [3.2.0] - 2014-08-24 +### Added +- Added input piping support to CLI. + +### Fixed +- Fixed typo, that could cause hand on initial indent (#139). + + +## [3.1.0] - 2014-07-07 +### Changed +- 1.5x-2x speed boost. +- Removed deprecated `require('xxx.yml')` support. +- Significant code cleanup and refactoring. +- Internal API changed. If you used custom types - see updated examples. + Others are not affected. +- Even if the input string has no trailing line break character, + it will be parsed as if it has one. +- Added benchmark scripts. +- Moved bower files to /dist folder +- Bugfixes. + + +## [3.0.2] - 2014-02-27 +### Fixed +- Fixed bug: "constructor" string parsed as `null`. + + +## [3.0.1] - 2013-12-22 +### Fixed +- Fixed parsing of literal scalars. (issue #108) +- Prevented adding unnecessary spaces in object dumps. (issue #68) +- Fixed dumping of objects with very long (> 1024 in length) keys. + + +## [3.0.0] - 2013-12-16 +### Changed +- Refactored code. Changed API for custom types. +- Removed output colors in CLI, dump json by default. +- Removed big dependencies from browser version (esprima, buffer). Load `esprima` manually, if `!!js/function` needed. `!!bin` now returns Array in browser +- AMD support. +- Don't quote dumped strings because of `-` & `?` (if not first char). +- __Deprecated__ loading yaml files via `require()`, as not recommended + behaviour for node. + + +## [2.1.3] - 2013-10-16 +### Fixed +- Fix wrong loading of empty block scalars. + + +## [2.1.2] - 2013-10-07 +### Fixed +- Fix unwanted line breaks in folded scalars. + + +## [2.1.1] - 2013-10-02 +### Fixed +- Dumper now respects deprecated booleans syntax from YAML 1.0/1.1 +- Fixed reader bug in JSON-like sequences/mappings. + + +## [2.1.0] - 2013-06-05 +### Added +- Add standard YAML schemas: Failsafe (`FAILSAFE_SCHEMA`), + JSON (`JSON_SCHEMA`) and Core (`CORE_SCHEMA`). +- Add `skipInvalid` dumper option. + +### Changed +- Rename `DEFAULT_SCHEMA` to `DEFAULT_FULL_SCHEMA` + and `SAFE_SCHEMA` to `DEFAULT_SAFE_SCHEMA`. +- Use `safeLoad` for `require` extension. + +### Fixed +- Bug fix: export `NIL` constant from the public interface. + + +## [2.0.5] - 2013-04-26 +### Security +- Close security issue in !!js/function constructor. + Big thanks to @nealpoole for security audit. + + +## [2.0.4] - 2013-04-08 +### Changed +- Updated .npmignore to reduce package size + + +## [2.0.3] - 2013-02-26 +### Fixed +- Fixed dumping of empty arrays ans objects. ([] and {} instead of null) + + +## [2.0.2] - 2013-02-15 +### Fixed +- Fixed input validation: tabs are printable characters. + + +## [2.0.1] - 2013-02-09 +### Fixed +- Fixed error, when options not passed to function cass + + +## [2.0.0] - 2013-02-09 +### Changed +- Full rewrite. New architecture. Fast one-stage parsing. +- Changed custom types API. +- Added YAML dumper. + + +## [1.0.3] - 2012-11-05 +### Fixed +- Fixed utf-8 files loading. + + +## [1.0.2] - 2012-08-02 +### Fixed +- Pull out hand-written shims. Use ES5-Shims for old browsers support. See #44. +- Fix timstamps incorectly parsed in local time when no time part specified. + + +## [1.0.1] - 2012-07-07 +### Fixed +- Fixes `TypeError: 'undefined' is not an object` under Safari. Thanks Phuong. +- Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46. + + +## [1.0.0] - 2012-07-01 +### Changed +- `y`, `yes`, `n`, `no`, `on`, `off` are not converted to Booleans anymore. + Fixes #42. +- `require(filename)` now returns a single document and throws an Error if + file contains more than one document. +- CLI was merged back from js-yaml.bin + + +## [0.3.7] - 2012-02-28 +### Fixed +- Fix export of `addConstructor()`. Closes #39. + + +## [0.3.6] - 2012-02-22 +### Changed +- Removed AMD parts - too buggy to use. Need help to rewrite from scratch + +### Fixed +- Removed YUI compressor warning (renamed `double` variable). Closes #40. + + +## [0.3.5] - 2012-01-10 +### Fixed +- Workagound for .npmignore fuckup under windows. Thanks to airportyh. + + +## [0.3.4] - 2011-12-24 +### Fixed +- Fixes str[] for oldIEs support. +- Adds better has change support for browserified demo. +- improves compact output of Error. Closes #33. + + +## [0.3.3] - 2011-12-20 +### Added +- adds `compact` stringification of Errors. + +### Changed +- jsyaml executable moved to separate module. + + +## [0.3.2] - 2011-12-16 +### Added +- Added jsyaml executable. +- Added !!js/function support. Closes #12. + +### Fixed +- Fixes ug with block style scalars. Closes #26. +- All sources are passing JSLint now. +- Fixes bug in Safari. Closes #28. +- Fixes bug in Opers. Closes #29. +- Improves browser support. Closes #20. + + +## [0.3.1] - 2011-11-18 +### Added +- Added AMD support for browserified version. +- Added permalinks for online demo YAML snippets. Now we have YPaste service, lol. +- Added !!js/regexp and !!js/undefined types. Partially solves #12. + +### Changed +- Wrapped browserified js-yaml into closure. + +### Fixed +- Fixed the resolvement of non-specific tags. Closes #17. +- Fixed !!set mapping. +- Fixed month parse in dates. Closes #19. + + +## [0.3.0] - 2011-11-09 +### Added +- Added browserified version. Closes #13. +- Added live demo of browserified version. +- Ported some of the PyYAML tests. See #14. + +### Fixed +- Removed JS.Class dependency. Closes #3. +- Fixed timestamp bug when fraction was given. + + +## [0.2.2] - 2011-11-06 +### Fixed +- Fixed crash on docs without ---. Closes #8. +- Fixed multiline string parse +- Fixed tests/comments for using array as key + + +## [0.2.1] - 2011-11-02 +### Fixed +- Fixed short file read (<4k). Closes #9. + + +## [0.2.0] - 2011-11-02 +### Changed +- First public release + + +[4.1.0]: https://github.com/nodeca/js-yaml/compare/4.0.0...4.1.0 +[4.0.0]: https://github.com/nodeca/js-yaml/compare/3.14.0...4.0.0 +[3.14.0]: https://github.com/nodeca/js-yaml/compare/3.13.1...3.14.0 +[3.13.1]: https://github.com/nodeca/js-yaml/compare/3.13.0...3.13.1 +[3.13.0]: https://github.com/nodeca/js-yaml/compare/3.12.2...3.13.0 +[3.12.2]: https://github.com/nodeca/js-yaml/compare/3.12.1...3.12.2 +[3.12.1]: https://github.com/nodeca/js-yaml/compare/3.12.0...3.12.1 +[3.12.0]: https://github.com/nodeca/js-yaml/compare/3.11.0...3.12.0 +[3.11.0]: https://github.com/nodeca/js-yaml/compare/3.10.0...3.11.0 +[3.10.0]: https://github.com/nodeca/js-yaml/compare/3.9.1...3.10.0 +[3.9.1]: https://github.com/nodeca/js-yaml/compare/3.9.0...3.9.1 +[3.9.0]: https://github.com/nodeca/js-yaml/compare/3.8.4...3.9.0 +[3.8.4]: https://github.com/nodeca/js-yaml/compare/3.8.3...3.8.4 +[3.8.3]: https://github.com/nodeca/js-yaml/compare/3.8.2...3.8.3 +[3.8.2]: https://github.com/nodeca/js-yaml/compare/3.8.1...3.8.2 +[3.8.1]: https://github.com/nodeca/js-yaml/compare/3.8.0...3.8.1 +[3.8.0]: https://github.com/nodeca/js-yaml/compare/3.7.0...3.8.0 +[3.7.0]: https://github.com/nodeca/js-yaml/compare/3.6.1...3.7.0 +[3.6.1]: https://github.com/nodeca/js-yaml/compare/3.6.0...3.6.1 +[3.6.0]: https://github.com/nodeca/js-yaml/compare/3.5.5...3.6.0 +[3.5.5]: https://github.com/nodeca/js-yaml/compare/3.5.4...3.5.5 +[3.5.4]: https://github.com/nodeca/js-yaml/compare/3.5.3...3.5.4 +[3.5.3]: https://github.com/nodeca/js-yaml/compare/3.5.2...3.5.3 +[3.5.2]: https://github.com/nodeca/js-yaml/compare/3.5.1...3.5.2 +[3.5.1]: https://github.com/nodeca/js-yaml/compare/3.5.0...3.5.1 +[3.5.0]: https://github.com/nodeca/js-yaml/compare/3.4.6...3.5.0 +[3.4.6]: https://github.com/nodeca/js-yaml/compare/3.4.5...3.4.6 +[3.4.5]: https://github.com/nodeca/js-yaml/compare/3.4.4...3.4.5 +[3.4.4]: https://github.com/nodeca/js-yaml/compare/3.4.3...3.4.4 +[3.4.3]: https://github.com/nodeca/js-yaml/compare/3.4.2...3.4.3 +[3.4.2]: https://github.com/nodeca/js-yaml/compare/3.4.1...3.4.2 +[3.4.1]: https://github.com/nodeca/js-yaml/compare/3.4.0...3.4.1 +[3.4.0]: https://github.com/nodeca/js-yaml/compare/3.3.1...3.4.0 +[3.3.1]: https://github.com/nodeca/js-yaml/compare/3.3.0...3.3.1 +[3.3.0]: https://github.com/nodeca/js-yaml/compare/3.2.7...3.3.0 +[3.2.7]: https://github.com/nodeca/js-yaml/compare/3.2.6...3.2.7 +[3.2.6]: https://github.com/nodeca/js-yaml/compare/3.2.5...3.2.6 +[3.2.5]: https://github.com/nodeca/js-yaml/compare/3.2.4...3.2.5 +[3.2.4]: https://github.com/nodeca/js-yaml/compare/3.2.3...3.2.4 +[3.2.3]: https://github.com/nodeca/js-yaml/compare/3.2.2...3.2.3 +[3.2.2]: https://github.com/nodeca/js-yaml/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/nodeca/js-yaml/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/nodeca/js-yaml/compare/3.1.0...3.2.0 +[3.1.0]: https://github.com/nodeca/js-yaml/compare/3.0.2...3.1.0 +[3.0.2]: https://github.com/nodeca/js-yaml/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/nodeca/js-yaml/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/nodeca/js-yaml/compare/2.1.3...3.0.0 +[2.1.3]: https://github.com/nodeca/js-yaml/compare/2.1.2...2.1.3 +[2.1.2]: https://github.com/nodeca/js-yaml/compare/2.1.1...2.1.2 +[2.1.1]: https://github.com/nodeca/js-yaml/compare/2.1.0...2.1.1 +[2.1.0]: https://github.com/nodeca/js-yaml/compare/2.0.5...2.1.0 +[2.0.5]: https://github.com/nodeca/js-yaml/compare/2.0.4...2.0.5 +[2.0.4]: https://github.com/nodeca/js-yaml/compare/2.0.3...2.0.4 +[2.0.3]: https://github.com/nodeca/js-yaml/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/nodeca/js-yaml/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/nodeca/js-yaml/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/nodeca/js-yaml/compare/1.0.3...2.0.0 +[1.0.3]: https://github.com/nodeca/js-yaml/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/js-yaml/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/js-yaml/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/js-yaml/compare/0.3.7...1.0.0 +[0.3.7]: https://github.com/nodeca/js-yaml/compare/0.3.6...0.3.7 +[0.3.6]: https://github.com/nodeca/js-yaml/compare/0.3.5...0.3.6 +[0.3.5]: https://github.com/nodeca/js-yaml/compare/0.3.4...0.3.5 +[0.3.4]: https://github.com/nodeca/js-yaml/compare/0.3.3...0.3.4 +[0.3.3]: https://github.com/nodeca/js-yaml/compare/0.3.2...0.3.3 +[0.3.2]: https://github.com/nodeca/js-yaml/compare/0.3.1...0.3.2 +[0.3.1]: https://github.com/nodeca/js-yaml/compare/0.3.0...0.3.1 +[0.3.0]: https://github.com/nodeca/js-yaml/compare/0.2.2...0.3.0 +[0.2.2]: https://github.com/nodeca/js-yaml/compare/0.2.1...0.2.2 +[0.2.1]: https://github.com/nodeca/js-yaml/compare/0.2.0...0.2.1 +[0.2.0]: https://github.com/nodeca/js-yaml/releases/tag/0.2.0 diff --git a/node_modules/js-yaml/LICENSE b/node_modules/js-yaml/LICENSE new file mode 100644 index 00000000..09d3a29e --- /dev/null +++ b/node_modules/js-yaml/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2011-2015 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/js-yaml/README.md b/node_modules/js-yaml/README.md new file mode 100644 index 00000000..3cbc4bd2 --- /dev/null +++ b/node_modules/js-yaml/README.md @@ -0,0 +1,246 @@ +JS-YAML - YAML 1.2 parser / writer for JavaScript +================================================= + +[![CI](https://github.com/nodeca/js-yaml/workflows/CI/badge.svg?branch=master)](https://github.com/nodeca/js-yaml/actions) +[![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) + +__[Online Demo](http://nodeca.github.com/js-yaml/)__ + + +This is an implementation of [YAML](http://yaml.org/), a human-friendly data +serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was +completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. + + +Installation +------------ + +### YAML module for node.js + +``` +npm install js-yaml +``` + + +### CLI executable + +If you want to inspect your YAML files from CLI, install js-yaml globally: + +``` +npm install -g js-yaml +``` + +#### Usage + +``` +usage: js-yaml [-h] [-v] [-c] [-t] file + +Positional arguments: + file File with YAML document(s) + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -c, --compact Display errors in compact mode + -t, --trace Show stack trace on error +``` + + +API +--- + +Here we cover the most 'useful' methods. If you need advanced details (creating +your own tags), see [examples](https://github.com/nodeca/js-yaml/tree/master/examples) +for more info. + +``` javascript +const yaml = require('js-yaml'); +const fs = require('fs'); + +// Get document, or throw exception on error +try { + const doc = yaml.load(fs.readFileSync('/home/ixti/example.yml', 'utf8')); + console.log(doc); +} catch (e) { + console.log(e); +} +``` + + +### load (string [ , options ]) + +Parses `string` as single YAML document. Returns either a +plain object, a string, a number, `null` or `undefined`, or throws `YAMLException` on error. By default, does +not support regexps, functions and undefined. + +options: + +- `filename` _(default: null)_ - string to be used as a file path in + error/warning messages. +- `onWarning` _(default: null)_ - function to call on warning messages. + Loader will call this function with an instance of `YAMLException` for each warning. +- `schema` _(default: `DEFAULT_SCHEMA`)_ - specifies a schema to use. + - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: + http://www.yaml.org/spec/1.2/spec.html#id2802346 + - `JSON_SCHEMA` - all JSON-supported types: + http://www.yaml.org/spec/1.2/spec.html#id2803231 + - `CORE_SCHEMA` - same as `JSON_SCHEMA`: + http://www.yaml.org/spec/1.2/spec.html#id2804923 + - `DEFAULT_SCHEMA` - all supported YAML types. +- `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. + +NOTE: This function **does not** understand multi-document sources, it throws +exception on those. + +NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. +So, the JSON schema is not as strictly defined in the YAML specification. +It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. +The core schema also has no such restrictions. It allows binary notation for integers. + + +### loadAll (string [, iterator] [, options ]) + +Same as `load()`, but understands multi-document sources. Applies +`iterator` to each document if specified, or returns array of documents. + +``` javascript +const yaml = require('js-yaml'); + +yaml.loadAll(data, function (doc) { + console.log(doc); +}); +``` + + +### dump (object [ , options ]) + +Serializes `object` as a YAML document. Uses `DEFAULT_SCHEMA`, so it will +throw an exception if you try to dump regexps or functions. However, you can +disable exceptions by setting the `skipInvalid` option to `true`. + +options: + +- `indent` _(default: 2)_ - indentation width to use (in spaces). +- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements +- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function + in the safe schema) and skip pairs and single values with such types. +- `flowLevel` _(default: -1)_ - specifies level of nesting, when to switch from + block to flow style for collections. -1 means block style everwhere +- `styles` - "tag" => "style" map. Each tag may have own set of styles. +- `schema` _(default: `DEFAULT_SCHEMA`)_ specifies a schema to use. +- `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a + function, use the function to sort the keys. +- `lineWidth` _(default: `80`)_ - set max line width. Set `-1` for unlimited width. +- `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references +- `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older + yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 +- `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. +- `quotingType` _(`'` or `"`, default: `'`)_ - strings will be quoted using this quoting style. If you specify single quotes, double quotes will still be used for non-printable characters. +- `forceQuotes` _(default: `false`)_ - if `true`, all non-key strings will be quoted even if they normally don't need to. +- `replacer` - callback `function (key, value)` called recursively on each key/value in source object (see `replacer` docs for `JSON.stringify`). + +The following table show availlable styles (e.g. "canonical", +"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml +output is shown on the right side after `=>` (default setting) or `->`: + +``` none +!!null + "canonical" -> "~" + "lowercase" => "null" + "uppercase" -> "NULL" + "camelcase" -> "Null" + +!!int + "binary" -> "0b1", "0b101010", "0b1110001111010" + "octal" -> "0o1", "0o52", "0o16172" + "decimal" => "1", "42", "7290" + "hexadecimal" -> "0x1", "0x2A", "0x1C7A" + +!!bool + "lowercase" => "true", "false" + "uppercase" -> "TRUE", "FALSE" + "camelcase" -> "True", "False" + +!!float + "lowercase" => ".nan", '.inf' + "uppercase" -> ".NAN", '.INF' + "camelcase" -> ".NaN", '.Inf' +``` + +Example: + +``` javascript +dump(object, { + 'styles': { + '!!null': 'canonical' // dump null as ~ + }, + 'sortKeys': true // sort object keys +}); +``` + +Supported YAML types +-------------------- + +The list of standard YAML tags and corresponding JavaScript types. See also +[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and +[YAML types repository](http://yaml.org/type/). + +``` +!!null '' # null +!!bool 'yes' # bool +!!int '3...' # number +!!float '3.14...' # number +!!binary '...base64...' # buffer +!!timestamp 'YYYY-...' # date +!!omap [ ... ] # array of key-value pairs +!!pairs [ ... ] # array or array pairs +!!set { ... } # array of objects with given keys and null values +!!str '...' # string +!!seq [ ... ] # array +!!map { ... } # object +``` + +**JavaScript-specific tags** + +See [js-yaml-js-types](https://github.com/nodeca/js-yaml-js-types) for +extra types. + + +Caveats +------- + +Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects +or arrays as keys, and stringifies (by calling `toString()` method) them at the +moment of adding them. + +``` yaml +--- +? [ foo, bar ] +: - baz +? { foo: bar } +: - baz + - baz +``` + +``` javascript +{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } +``` + +Also, reading of properties on implicit block mapping keys is not supported yet. +So, the following YAML document cannot be loaded. + +``` yaml +&anchor foo: + foo: bar + *anchor: duplicate key + baz: bat + *anchor: duplicate key +``` + + +js-yaml for enterprise +---------------------- + +Available as part of the Tidelift Subscription + +The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/js-yaml/bin/js-yaml.js b/node_modules/js-yaml/bin/js-yaml.js new file mode 100755 index 00000000..a182f1af --- /dev/null +++ b/node_modules/js-yaml/bin/js-yaml.js @@ -0,0 +1,126 @@ +#!/usr/bin/env node + + +'use strict'; + +/*eslint-disable no-console*/ + + +var fs = require('fs'); +var argparse = require('argparse'); +var yaml = require('..'); + + +//////////////////////////////////////////////////////////////////////////////// + + +var cli = new argparse.ArgumentParser({ + prog: 'js-yaml', + add_help: true +}); + +cli.add_argument('-v', '--version', { + action: 'version', + version: require('../package.json').version +}); + +cli.add_argument('-c', '--compact', { + help: 'Display errors in compact mode', + action: 'store_true' +}); + +// deprecated (not needed after we removed output colors) +// option suppressed, but not completely removed for compatibility +cli.add_argument('-j', '--to-json', { + help: argparse.SUPPRESS, + dest: 'json', + action: 'store_true' +}); + +cli.add_argument('-t', '--trace', { + help: 'Show stack trace on error', + action: 'store_true' +}); + +cli.add_argument('file', { + help: 'File to read, utf-8 encoded without BOM', + nargs: '?', + default: '-' +}); + + +//////////////////////////////////////////////////////////////////////////////// + + +var options = cli.parse_args(); + + +//////////////////////////////////////////////////////////////////////////////// + +function readFile(filename, encoding, callback) { + if (options.file === '-') { + // read from stdin + + var chunks = []; + + process.stdin.on('data', function (chunk) { + chunks.push(chunk); + }); + + process.stdin.on('end', function () { + return callback(null, Buffer.concat(chunks).toString(encoding)); + }); + } else { + fs.readFile(filename, encoding, callback); + } +} + +readFile(options.file, 'utf8', function (error, input) { + var output, isYaml; + + if (error) { + if (error.code === 'ENOENT') { + console.error('File not found: ' + options.file); + process.exit(2); + } + + console.error( + options.trace && error.stack || + error.message || + String(error)); + + process.exit(1); + } + + try { + output = JSON.parse(input); + isYaml = false; + } catch (err) { + if (err instanceof SyntaxError) { + try { + output = []; + yaml.loadAll(input, function (doc) { output.push(doc); }, {}); + isYaml = true; + + if (output.length === 0) output = null; + else if (output.length === 1) output = output[0]; + + } catch (e) { + if (options.trace && err.stack) console.error(e.stack); + else console.error(e.toString(options.compact)); + + process.exit(1); + } + } else { + console.error( + options.trace && err.stack || + err.message || + String(err)); + + process.exit(1); + } + } + + if (isYaml) console.log(JSON.stringify(output, null, ' ')); + else console.log(yaml.dump(output)); +}); diff --git a/node_modules/js-yaml/dist/js-yaml.js b/node_modules/js-yaml/dist/js-yaml.js new file mode 100644 index 00000000..4cc0ddf6 --- /dev/null +++ b/node_modules/js-yaml/dist/js-yaml.js @@ -0,0 +1,3874 @@ + +/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jsyaml = {})); +}(this, (function (exports) { 'use strict'; + + function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); + } + + + function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); + } + + + function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; + } + + + function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; + } + + + function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; + } + + + function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); + } + + + var isNothing_1 = isNothing; + var isObject_1 = isObject; + var toArray_1 = toArray; + var repeat_1 = repeat; + var isNegativeZero_1 = isNegativeZero; + var extend_1 = extend; + + var common = { + isNothing: isNothing_1, + isObject: isObject_1, + toArray: toArray_1, + repeat: repeat_1, + isNegativeZero: isNegativeZero_1, + extend: extend_1 + }; + + // YAML error class. http://stackoverflow.com/questions/8458984 + + + function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; + + if (!exception.mark) return message; + + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } + + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; + + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; + } + + return message + ' ' + where; + } + + + function YAMLException$1(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } + } + + + // Inherit from Error + YAMLException$1.prototype = Object.create(Error.prototype); + YAMLException$1.prototype.constructor = YAMLException$1; + + + YAMLException$1.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); + }; + + + var exception = YAMLException$1; + + // get snippet for a single line, respecting maxLength + function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; + } + + + function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; + } + + + function makeSnippet(mark, options) { + options = Object.create(options || null); + + if (!mark.buffer) return null; + + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); + } + + + var snippet = makeSnippet; + + var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' + ]; + + var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' + ]; + + function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; + } + + function Type$1(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } + } + + var type = Type$1; + + /*eslint-disable max-len*/ + + + + + + function compileList(schema, name) { + var result = []; + + schema[name].forEach(function (currentType) { + var newIndex = result.length; + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; + } + + + function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; + } + + + function Schema$1(definition) { + return this.extend(definition); + } + + + Schema$1.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + + } else { + throw new exception('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + if (type$1.loadKind && type$1.loadKind !== 'scalar') { + throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + + if (type$1.multi) { + throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); + + explicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema$1.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + + return result; + }; + + + var schema = Schema$1; + + var str = new type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } + }); + + var seq = new type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } + }); + + var map = new type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } + }); + + var failsafe = new schema({ + explicit: [ + str, + seq, + map + ] + }); + + function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); + } + + function constructYamlNull() { + return null; + } + + function isNull(object) { + return object === null; + } + + var _null = new type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' + }); + + function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); + } + + function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; + } + + function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; + } + + var bool = new type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' + }); + + function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); + } + + function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); + } + + function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); + } + + function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + } + + // base 10 (except 0) + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; + } + + function constructYamlInteger(data) { + var value = data, sign = 1, ch; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + } + + return sign * parseInt(value, 10); + } + + function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); + } + + var int = new type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } + }); + + var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + + function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; + } + + function constructYamlFloat(data) { + var value, sign; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); + } + + + var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + + function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; + } + + function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); + } + + var float = new type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' + }); + + var json = failsafe.extend({ + implicit: [ + _null, + bool, + int, + float + ] + }); + + var core = json; + + var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + + var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + + function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; + } + + function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; + } + + function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); + } + + var timestamp = new type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp + }); + + function resolveYamlMerge(data) { + return data === '<<' || data === null; + } + + var merge = new type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge + }); + + /*eslint-disable no-bitwise*/ + + + + + + // [ 64, 65, 66 ] -> [ padding, CR, LF ] + var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + + function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; + } + + function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + return new Uint8Array(result); + } + + function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; + } + + function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; + } + + var binary = new type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary + }); + + var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; + var _toString$2 = Object.prototype.toString; + + function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString$2.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty$3.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; + } + + function constructYamlOmap(data) { + return data !== null ? data : []; + } + + var omap = new type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap + }); + + var _toString$1 = Object.prototype.toString; + + function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString$1.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; + } + + function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; + } + + var pairs = new type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs + }); + + var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; + + function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$2.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; + } + + function constructYamlSet(data) { + return data !== null ? data : {}; + } + + var set = new type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet + }); + + var _default = core.extend({ + implicit: [ + timestamp, + merge + ], + explicit: [ + binary, + omap, + pairs, + set + ] + }); + + /*eslint-disable max-len,no-use-before-define*/ + + + + + + + + var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; + + + var CONTEXT_FLOW_IN = 1; + var CONTEXT_FLOW_OUT = 2; + var CONTEXT_BLOCK_IN = 3; + var CONTEXT_BLOCK_OUT = 4; + + + var CHOMPING_CLIP = 1; + var CHOMPING_STRIP = 2; + var CHOMPING_KEEP = 3; + + + var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; + var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; + var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; + var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + + function _class(obj) { return Object.prototype.toString.call(obj); } + + function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); + } + + function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); + } + + function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); + } + + function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; + } + + function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; + } + + function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; + } + + function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; + } + + function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; + } + + function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); + } + + var simpleEscapeCheck = new Array(256); // integer, for fast access + var simpleEscapeMap = new Array(256); + for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); + } + + + function State$1(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || _default; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; + + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + + } + + + function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; + + mark.snippet = snippet(mark); + + return new exception(message, mark); + } + + function throwError(state, message) { + throw generateError(state, message); + } + + function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } + } + + + var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$1.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } + }; + + + function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } + } + + function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty$1.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } + } + + function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$1.call(overridableKeys, keyNode) && + _hasOwnProperty$1.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; + } + + return _result; + } + + function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; + } + + function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; + } + + function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; + } + + function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } + } + + + function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; + } + + function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); + } + + function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); + } + + function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); + } + + function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; + } + + function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; + } + + function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; + } + + function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; + } + + function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; + } + + function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; + } + + function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; + } + + function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } + } + + + function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State$1(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; + } + + + function loadAll$1(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } + } + + + function load$1(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception('expected a single document in the stream, but found more'); + } + + + var loadAll_1 = loadAll$1; + var load_1 = load$1; + + var loader = { + loadAll: loadAll_1, + load: load_1 + }; + + /*eslint-disable no-use-before-define*/ + + + + + + var _toString = Object.prototype.toString; + var _hasOwnProperty = Object.prototype.hasOwnProperty; + + var CHAR_BOM = 0xFEFF; + var CHAR_TAB = 0x09; /* Tab */ + var CHAR_LINE_FEED = 0x0A; /* LF */ + var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ + var CHAR_SPACE = 0x20; /* Space */ + var CHAR_EXCLAMATION = 0x21; /* ! */ + var CHAR_DOUBLE_QUOTE = 0x22; /* " */ + var CHAR_SHARP = 0x23; /* # */ + var CHAR_PERCENT = 0x25; /* % */ + var CHAR_AMPERSAND = 0x26; /* & */ + var CHAR_SINGLE_QUOTE = 0x27; /* ' */ + var CHAR_ASTERISK = 0x2A; /* * */ + var CHAR_COMMA = 0x2C; /* , */ + var CHAR_MINUS = 0x2D; /* - */ + var CHAR_COLON = 0x3A; /* : */ + var CHAR_EQUALS = 0x3D; /* = */ + var CHAR_GREATER_THAN = 0x3E; /* > */ + var CHAR_QUESTION = 0x3F; /* ? */ + var CHAR_COMMERCIAL_AT = 0x40; /* @ */ + var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ + var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ + var CHAR_GRAVE_ACCENT = 0x60; /* ` */ + var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ + var CHAR_VERTICAL_LINE = 0x7C; /* | */ + var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + + var ESCAPE_SEQUENCES = {}; + + ESCAPE_SEQUENCES[0x00] = '\\0'; + ESCAPE_SEQUENCES[0x07] = '\\a'; + ESCAPE_SEQUENCES[0x08] = '\\b'; + ESCAPE_SEQUENCES[0x09] = '\\t'; + ESCAPE_SEQUENCES[0x0A] = '\\n'; + ESCAPE_SEQUENCES[0x0B] = '\\v'; + ESCAPE_SEQUENCES[0x0C] = '\\f'; + ESCAPE_SEQUENCES[0x0D] = '\\r'; + ESCAPE_SEQUENCES[0x1B] = '\\e'; + ESCAPE_SEQUENCES[0x22] = '\\"'; + ESCAPE_SEQUENCES[0x5C] = '\\\\'; + ESCAPE_SEQUENCES[0x85] = '\\N'; + ESCAPE_SEQUENCES[0xA0] = '\\_'; + ESCAPE_SEQUENCES[0x2028] = '\\L'; + ESCAPE_SEQUENCES[0x2029] = '\\P'; + + var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' + ]; + + var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + + function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; + } + + function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; + } + + + var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; + + function State(options) { + this.schema = options['schema'] || _default; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; + } + + // Indents every line in a string. Empty lines (\n only) are not indented. + function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; + } + + function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); + } + + function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; + } + + // [33] s-white ::= s-space | s-tab + function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; + } + + // Returns true if the character can be printed without escaping. + // From YAML 1.2: "any allowed characters known to be non-printable + // should also be escaped. [However,] This isn’t mandatory" + // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. + function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); + } + + // [34] ns-char ::= nb-char - s-white + // [27] nb-char ::= c-printable - b-char - c-byte-order-mark + // [26] b-char ::= b-line-feed | b-carriage-return + // Including s-white (for some reason, examples doesn't match specs in this aspect) + // ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark + function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; + } + + // [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out + // c = flow-in ⇒ ns-plain-safe-in + // c = block-key ⇒ ns-plain-safe-out + // c = flow-key ⇒ ns-plain-safe-in + // [128] ns-plain-safe-out ::= ns-char + // [129] ns-plain-safe-in ::= ns-char - c-flow-indicator + // [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) + // | ( /* An ns-char preceding */ “#” ) + // | ( “:” /* Followed by an ns-plain-safe(c) */ ) + function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' + } + + // Simplified test for values allowed as the first character in plain style. + function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; + } + + // Simplified test for values allowed as the last character in plain style. + function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; + } + + // Same as 'string'.codePointAt(pos), but works in older browsers. + function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; + } + + // Determines whether block indentation indicator is required. + function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); + } + + var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + + // Determines which scalar styles are possible and returns the preferred style. + // lineWidth = -1 => no limit. + // Pre-conditions: str.length > 0. + // Post-conditions: + // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. + // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). + // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). + function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + + // Note: line breaking/folding is implemented for only the folded style. + // NB. We drop the last trailing newline (if any) of a returned block scalar + // since the dumper adds its own newline. This always works: + // • No ending newline => unaffected; already using strip "-" chomping. + // • Ending newline => removed then restored. + // Importantly, this keeps the "+" chomp indicator from gaining an extra line. + function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string) + '"'; + default: + throw new exception('impossible error: invalid scalar style'); + } + }()); + } + + // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. + function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; + } + + // (See the note for writeScalar.) + function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; + } + + // Note: a long line without a suitable break point will exceed the width limit. + // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. + function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; + } + + // Greedy line breaking. + // Picks the longest line under the limit each time, + // otherwise settles for the shortest line over the limit. + // NB. More-indented lines *cannot* be folded, as that would add an extra \n. + function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner + } + + // Escapes a double-quoted string. + function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; + + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } + + return result; + } + + function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; + } + + function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. + } + + function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; + } + + function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new exception('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. + } + + function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; + } + + // Serializes `object` and writes it to global `result`. + // Returns true on success, or false on invalid object. + // + function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new exception('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + + state.dump = tagStr + ' ' + state.dump; + } + } + + return true; + } + + function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); + } + + function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } + } + + function dump$1(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; + } + + var dump_1 = dump$1; + + var dumper = { + dump: dump_1 + }; + + function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; + } + + + var Type = type; + var Schema = schema; + var FAILSAFE_SCHEMA = failsafe; + var JSON_SCHEMA = json; + var CORE_SCHEMA = core; + var DEFAULT_SCHEMA = _default; + var load = loader.load; + var loadAll = loader.loadAll; + var dump = dumper.dump; + var YAMLException = exception; + + // Re-export all types in case user wants to create custom schema + var types = { + binary: binary, + float: float, + map: map, + null: _null, + pairs: pairs, + set: set, + timestamp: timestamp, + bool: bool, + int: int, + merge: merge, + omap: omap, + seq: seq, + str: str + }; + + // Removed functions from JS-YAML 3.0.x + var safeLoad = renamed('safeLoad', 'load'); + var safeLoadAll = renamed('safeLoadAll', 'loadAll'); + var safeDump = renamed('safeDump', 'dump'); + + var jsYaml = { + Type: Type, + Schema: Schema, + FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, + JSON_SCHEMA: JSON_SCHEMA, + CORE_SCHEMA: CORE_SCHEMA, + DEFAULT_SCHEMA: DEFAULT_SCHEMA, + load: load, + loadAll: loadAll, + dump: dump, + YAMLException: YAMLException, + types: types, + safeLoad: safeLoad, + safeLoadAll: safeLoadAll, + safeDump: safeDump + }; + + exports.CORE_SCHEMA = CORE_SCHEMA; + exports.DEFAULT_SCHEMA = DEFAULT_SCHEMA; + exports.FAILSAFE_SCHEMA = FAILSAFE_SCHEMA; + exports.JSON_SCHEMA = JSON_SCHEMA; + exports.Schema = Schema; + exports.Type = Type; + exports.YAMLException = YAMLException; + exports.default = jsYaml; + exports.dump = dump; + exports.load = load; + exports.loadAll = loadAll; + exports.safeDump = safeDump; + exports.safeLoad = safeLoad; + exports.safeLoadAll = safeLoadAll; + exports.types = types; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/node_modules/js-yaml/dist/js-yaml.min.js b/node_modules/js-yaml/dist/js-yaml.min.js new file mode 100644 index 00000000..bdd8eef5 --- /dev/null +++ b/node_modules/js-yaml/dist/js-yaml.min.js @@ -0,0 +1,2 @@ +/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).jsyaml={})}(this,(function(e){"use strict";function t(e){return null==e}var n={isNothing:t,isObject:function(e){return"object"==typeof e&&null!==e},toArray:function(e){return Array.isArray(e)?e:t(e)?[]:[e]},repeat:function(e,t){var n,i="";for(n=0;nl&&(t=i-l+(o=" ... ").length),n-i>l&&(n=i+l-(a=" ...").length),{str:o+e.slice(t,n).replace(/\t/g,"→")+a,pos:i-t+o.length}}function l(e,t){return n.repeat(" ",t-e.length)+e}var c=function(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),"number"!=typeof t.indent&&(t.indent=1),"number"!=typeof t.linesBefore&&(t.linesBefore=3),"number"!=typeof t.linesAfter&&(t.linesAfter=2);for(var i,r=/\r?\n|\r|\0/g,o=[0],c=[],s=-1;i=r.exec(e.buffer);)c.push(i.index),o.push(i.index+i[0].length),e.position<=i.index&&s<0&&(s=o.length-2);s<0&&(s=o.length-1);var u,p,f="",d=Math.min(e.line+t.linesAfter,c.length).toString().length,h=t.maxLength-(t.indent+d+3);for(u=1;u<=t.linesBefore&&!(s-u<0);u++)p=a(e.buffer,o[s-u],c[s-u],e.position-(o[s]-o[s-u]),h),f=n.repeat(" ",t.indent)+l((e.line-u+1).toString(),d)+" | "+p.str+"\n"+f;for(p=a(e.buffer,o[s],c[s],e.position,h),f+=n.repeat(" ",t.indent)+l((e.line+1).toString(),d)+" | "+p.str+"\n",f+=n.repeat("-",t.indent+d+3+p.pos)+"^\n",u=1;u<=t.linesAfter&&!(s+u>=c.length);u++)p=a(e.buffer,o[s+u],c[s+u],e.position-(o[s]-o[s+u]),h),f+=n.repeat(" ",t.indent)+l((e.line+u+1).toString(),d)+" | "+p.str+"\n";return f.replace(/\n$/,"")},s=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],u=["scalar","sequence","mapping"];var p=function(e,t){if(t=t||{},Object.keys(t).forEach((function(t){if(-1===s.indexOf(t))throw new o('Unknown option "'+t+'" is met in definition of "'+e+'" YAML type.')})),this.options=t,this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=function(e){var t={};return null!==e&&Object.keys(e).forEach((function(n){e[n].forEach((function(e){t[String(e)]=n}))})),t}(t.styleAliases||null),-1===u.indexOf(this.kind))throw new o('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')};function f(e,t){var n=[];return e[t].forEach((function(e){var t=n.length;n.forEach((function(n,i){n.tag===e.tag&&n.kind===e.kind&&n.multi===e.multi&&(t=i)})),n[t]=e})),n}function d(e){return this.extend(e)}d.prototype.extend=function(e){var t=[],n=[];if(e instanceof p)n.push(e);else if(Array.isArray(e))n=n.concat(e);else{if(!e||!Array.isArray(e.implicit)&&!Array.isArray(e.explicit))throw new o("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");e.implicit&&(t=t.concat(e.implicit)),e.explicit&&(n=n.concat(e.explicit))}t.forEach((function(e){if(!(e instanceof p))throw new o("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(e.loadKind&&"scalar"!==e.loadKind)throw new o("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(e.multi)throw new o("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")})),n.forEach((function(e){if(!(e instanceof p))throw new o("Specified list of YAML types (or a single Type object) contains a non-Type object.")}));var i=Object.create(d.prototype);return i.implicit=(this.implicit||[]).concat(t),i.explicit=(this.explicit||[]).concat(n),i.compiledImplicit=f(i,"implicit"),i.compiledExplicit=f(i,"explicit"),i.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function i(e){e.multi?(n.multi[e.kind].push(e),n.multi.fallback.push(e)):n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0o"+e.toString(8):"-0o"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),x=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var I=/^[-+]?[0-9]+e/;var S=new p("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!x.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,"+-".indexOf(t[0])>=0&&(t=t.slice(1)),".inf"===t?1===n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||n.isNegativeZero(e))},represent:function(e,t){var i;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(n.isNegativeZero(e))return"-0.0";return i=e.toString(10),I.test(i)?i.replace("e",".e"):i},defaultStyle:"lowercase"}),O=b.extend({implicit:[A,v,C,S]}),j=O,T=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),N=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");var F=new p("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:function(e){return null!==e&&(null!==T.exec(e)||null!==N.exec(e))},construct:function(e){var t,n,i,r,o,a,l,c,s=0,u=null;if(null===(t=T.exec(e))&&(t=N.exec(e)),null===t)throw new Error("Date resolve error");if(n=+t[1],i=+t[2]-1,r=+t[3],!t[4])return new Date(Date.UTC(n,i,r));if(o=+t[4],a=+t[5],l=+t[6],t[7]){for(s=t[7].slice(0,3);s.length<3;)s+="0";s=+s}return t[9]&&(u=6e4*(60*+t[10]+ +(t[11]||0)),"-"===t[9]&&(u=-u)),c=new Date(Date.UTC(n,i,r,o,a,l,s)),u&&c.setTime(c.getTime()-u),c},instanceOf:Date,represent:function(e){return e.toISOString()}});var E=new p("tag:yaml.org,2002:merge",{kind:"scalar",resolve:function(e){return"<<"===e||null===e}}),M="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";var L=new p("tag:yaml.org,2002:binary",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i=0,r=e.length,o=M;for(n=0;n64)){if(t<0)return!1;i+=6}return i%8==0},construct:function(e){var t,n,i=e.replace(/[\r\n=]/g,""),r=i.length,o=M,a=0,l=[];for(t=0;t>16&255),l.push(a>>8&255),l.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0===(n=r%4*6)?(l.push(a>>16&255),l.push(a>>8&255),l.push(255&a)):18===n?(l.push(a>>10&255),l.push(a>>2&255)):12===n&&l.push(a>>4&255),new Uint8Array(l)},predicate:function(e){return"[object Uint8Array]"===Object.prototype.toString.call(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=M;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0===(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2===n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1===n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}}),_=Object.prototype.hasOwnProperty,D=Object.prototype.toString;var U=new p("tag:yaml.org,2002:omap",{kind:"sequence",resolve:function(e){if(null===e)return!0;var t,n,i,r,o,a=[],l=e;for(t=0,n=l.length;t>10),56320+(e-65536&1023))}for(var ie=new Array(256),re=new Array(256),oe=0;oe<256;oe++)ie[oe]=te(oe)?1:0,re[oe]=te(oe);function ae(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||K,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function le(e,t){var n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=c(n),new o(t,n)}function ce(e,t){throw le(e,t)}function se(e,t){e.onWarning&&e.onWarning.call(null,le(e,t))}var ue={YAML:function(e,t,n){var i,r,o;null!==e.version&&ce(e,"duplication of %YAML directive"),1!==n.length&&ce(e,"YAML directive accepts exactly one argument"),null===(i=/^([0-9]+)\.([0-9]+)$/.exec(n[0]))&&ce(e,"ill-formed argument of the YAML directive"),r=parseInt(i[1],10),o=parseInt(i[2],10),1!==r&&ce(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=o<2,1!==o&&2!==o&&se(e,"unsupported YAML version of the document")},TAG:function(e,t,n){var i,r;2!==n.length&&ce(e,"TAG directive accepts exactly two arguments"),i=n[0],r=n[1],G.test(i)||ce(e,"ill-formed tag handle (first argument) of the TAG directive"),P.call(e.tagMap,i)&&ce(e,'there is a previously declared suffix for "'+i+'" tag handle'),V.test(r)||ce(e,"ill-formed tag prefix (second argument) of the TAG directive");try{r=decodeURIComponent(r)}catch(t){ce(e,"tag prefix is malformed: "+r)}e.tagMap[i]=r}};function pe(e,t,n,i){var r,o,a,l;if(t1&&(e.result+=n.repeat("\n",t-1))}function be(e,t){var n,i,r=e.tag,o=e.anchor,a=[],l=!1;if(-1!==e.firstTabInLine)return!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=a),i=e.input.charCodeAt(e.position);0!==i&&(-1!==e.firstTabInLine&&(e.position=e.firstTabInLine,ce(e,"tab characters must not be used in indentation")),45===i)&&z(e.input.charCodeAt(e.position+1));)if(l=!0,e.position++,ge(e,!0,-1)&&e.lineIndent<=t)a.push(null),i=e.input.charCodeAt(e.position);else if(n=e.line,we(e,t,3,!1,!0),a.push(e.result),ge(e,!0,-1),i=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&0!==i)ce(e,"bad indentation of a sequence entry");else if(e.lineIndentt?g=1:e.lineIndent===t?g=0:e.lineIndentt?g=1:e.lineIndent===t?g=0:e.lineIndentt)&&(y&&(a=e.line,l=e.lineStart,c=e.position),we(e,t,4,!0,r)&&(y?g=e.result:m=e.result),y||(de(e,f,d,h,g,m,a,l,c),h=g=m=null),ge(e,!0,-1),s=e.input.charCodeAt(e.position)),(e.line===o||e.lineIndent>t)&&0!==s)ce(e,"bad indentation of a mapping entry");else if(e.lineIndent=0))break;0===o?ce(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):u?ce(e,"repeat of an indentation width identifier"):(p=t+o-1,u=!0)}if(Q(a)){do{a=e.input.charCodeAt(++e.position)}while(Q(a));if(35===a)do{a=e.input.charCodeAt(++e.position)}while(!J(a)&&0!==a)}for(;0!==a;){for(he(e),e.lineIndent=0,a=e.input.charCodeAt(e.position);(!u||e.lineIndentp&&(p=e.lineIndent),J(a))f++;else{if(e.lineIndent0){for(r=a,o=0;r>0;r--)(a=ee(l=e.input.charCodeAt(++e.position)))>=0?o=(o<<4)+a:ce(e,"expected hexadecimal character");e.result+=ne(o),e.position++}else ce(e,"unknown escape sequence");n=i=e.position}else J(l)?(pe(e,n,i,!0),ye(e,ge(e,!1,t)),n=i=e.position):e.position===e.lineStart&&me(e)?ce(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}ce(e,"unexpected end of the stream within a double quoted scalar")}(e,d)?y=!0:!function(e){var t,n,i;if(42!==(i=e.input.charCodeAt(e.position)))return!1;for(i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!z(i)&&!X(i);)i=e.input.charCodeAt(++e.position);return e.position===t&&ce(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),P.call(e.anchorMap,n)||ce(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],ge(e,!0,-1),!0}(e)?function(e,t,n){var i,r,o,a,l,c,s,u,p=e.kind,f=e.result;if(z(u=e.input.charCodeAt(e.position))||X(u)||35===u||38===u||42===u||33===u||124===u||62===u||39===u||34===u||37===u||64===u||96===u)return!1;if((63===u||45===u)&&(z(i=e.input.charCodeAt(e.position+1))||n&&X(i)))return!1;for(e.kind="scalar",e.result="",r=o=e.position,a=!1;0!==u;){if(58===u){if(z(i=e.input.charCodeAt(e.position+1))||n&&X(i))break}else if(35===u){if(z(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&me(e)||n&&X(u))break;if(J(u)){if(l=e.line,c=e.lineStart,s=e.lineIndent,ge(e,!1,-1),e.lineIndent>=t){a=!0,u=e.input.charCodeAt(e.position);continue}e.position=o,e.line=l,e.lineStart=c,e.lineIndent=s;break}}a&&(pe(e,r,o,!1),ye(e,e.line-l),r=o=e.position,a=!1),Q(u)||(o=e.position+1),u=e.input.charCodeAt(++e.position)}return pe(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,d,1===i)&&(y=!0,null===e.tag&&(e.tag="?")):(y=!0,null===e.tag&&null===e.anchor||ce(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===g&&(y=c&&be(e,h))),null===e.tag)null!==e.anchor&&(e.anchorMap[e.anchor]=e.result);else if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&ce(e,'unacceptable node kind for ! tag; it should be "scalar", not "'+e.kind+'"'),s=0,u=e.implicitTypes.length;s"),null!==e.result&&f.kind!==e.kind&&ce(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+f.kind+'", not "'+e.kind+'"'),f.resolve(e.result,e.tag)?(e.result=f.construct(e.result,e.tag),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):ce(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")}return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||y}function ke(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);0!==(r=e.input.charCodeAt(e.position))&&(ge(e,!0,-1),r=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==r));){for(a=!0,r=e.input.charCodeAt(++e.position),t=e.position;0!==r&&!z(r);)r=e.input.charCodeAt(++e.position);for(i=[],(n=e.input.slice(t,e.position)).length<1&&ce(e,"directive name must not be less than one character in length");0!==r;){for(;Q(r);)r=e.input.charCodeAt(++e.position);if(35===r){do{r=e.input.charCodeAt(++e.position)}while(0!==r&&!J(r));break}if(J(r))break;for(t=e.position;0!==r&&!z(r);)r=e.input.charCodeAt(++e.position);i.push(e.input.slice(t,e.position))}0!==r&&he(e),P.call(ue,n)?ue[n](e,n,i):se(e,'unknown document directive "'+n+'"')}ge(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,ge(e,!0,-1)):a&&ce(e,"directives end mark is expected"),we(e,e.lineIndent-1,4,!1,!0),ge(e,!0,-1),e.checkLineBreaks&&H.test(e.input.slice(o,e.position))&&se(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&me(e)?46===e.input.charCodeAt(e.position)&&(e.position+=3,ge(e,!0,-1)):e.position=55296&&i<=56319&&t+1=56320&&n<=57343?1024*(i-55296)+n-56320+65536:i}function Re(e){return/^\n* /.test(e)}function Be(e,t,n,i,r,o,a,l){var c,s,u=0,p=null,f=!1,d=!1,h=-1!==i,g=-1,m=De(s=Ye(e,0))&&s!==Oe&&!_e(s)&&45!==s&&63!==s&&58!==s&&44!==s&&91!==s&&93!==s&&123!==s&&125!==s&&35!==s&&38!==s&&42!==s&&33!==s&&124!==s&&61!==s&&62!==s&&39!==s&&34!==s&&37!==s&&64!==s&&96!==s&&function(e){return!_e(e)&&58!==e}(Ye(e,e.length-1));if(t||a)for(c=0;c=65536?c+=2:c++){if(!De(u=Ye(e,c)))return 5;m=m&&qe(u,p,l),p=u}else{for(c=0;c=65536?c+=2:c++){if(10===(u=Ye(e,c)))f=!0,h&&(d=d||c-g-1>i&&" "!==e[g+1],g=c);else if(!De(u))return 5;m=m&&qe(u,p,l),p=u}d=d||h&&c-g-1>i&&" "!==e[g+1]}return f||d?n>9&&Re(e)?5:a?2===o?5:2:d?4:3:!m||a||r(e)?2===o?5:2:1}function Ke(e,t,n,i,r){e.dump=function(){if(0===t.length)return 2===e.quotingType?'""':"''";if(!e.noCompatMode&&(-1!==Te.indexOf(t)||Ne.test(t)))return 2===e.quotingType?'"'+t+'"':"'"+t+"'";var a=e.indent*Math.max(1,n),l=-1===e.lineWidth?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-a),c=i||e.flowLevel>-1&&n>=e.flowLevel;switch(Be(t,c,e.indent,l,(function(t){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+Pe(t,e.indent)+We(Me(function(e,t){var n,i,r=/(\n+)([^\n]*)/g,o=(l=e.indexOf("\n"),l=-1!==l?l:e.length,r.lastIndex=l,He(e.slice(0,l),t)),a="\n"===e[0]||" "===e[0];var l;for(;i=r.exec(e);){var c=i[1],s=i[2];n=" "===s[0],o+=c+(a||n||""===s?"":"\n")+He(s,t),a=n}return o}(t,l),a));case 5:return'"'+function(e){for(var t,n="",i=0,r=0;r=65536?r+=2:r++)i=Ye(e,r),!(t=je[i])&&De(i)?(n+=e[r],i>=65536&&(n+=e[r+1])):n+=t||Fe(i);return n}(t)+'"';default:throw new o("impossible error: invalid scalar style")}}()}function Pe(e,t){var n=Re(e)?String(t):"",i="\n"===e[e.length-1];return n+(i&&("\n"===e[e.length-2]||"\n"===e)?"+":i?"":"-")+"\n"}function We(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function He(e,t){if(""===e||" "===e[0])return e;for(var n,i,r=/ [^ ]/g,o=0,a=0,l=0,c="";n=r.exec(e);)(l=n.index)-o>t&&(i=a>o?a:l,c+="\n"+e.slice(o,i),o=i+1),a=l;return c+="\n",e.length-o>t&&a>o?c+=e.slice(o,a)+"\n"+e.slice(a+1):c+=e.slice(o),c.slice(1)}function $e(e,t,n,i){var r,o,a,l="",c=e.tag;for(r=0,o=n.length;r tag resolver accepts not "'+s+'" style');i=c.represent[s](t,s)}e.dump=i}return!0}return!1}function Ve(e,t,n,i,r,a,l){e.tag=null,e.dump=n,Ge(e,n,!1)||Ge(e,n,!0);var c,s=Ie.call(e.dump),u=i;i&&(i=e.flowLevel<0||e.flowLevel>t);var p,f,d="[object Object]"===s||"[object Array]"===s;if(d&&(f=-1!==(p=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||f||2!==e.indent&&t>0)&&(r=!1),f&&e.usedDuplicates[p])e.dump="*ref_"+p;else{if(d&&f&&!e.usedDuplicates[p]&&(e.usedDuplicates[p]=!0),"[object Object]"===s)i&&0!==Object.keys(e.dump).length?(!function(e,t,n,i){var r,a,l,c,s,u,p="",f=e.tag,d=Object.keys(n);if(!0===e.sortKeys)d.sort();else if("function"==typeof e.sortKeys)d.sort(e.sortKeys);else if(e.sortKeys)throw new o("sortKeys must be a boolean or a function");for(r=0,a=d.length;r1024)&&(e.dump&&10===e.dump.charCodeAt(0)?u+="?":u+="? "),u+=e.dump,s&&(u+=Le(e,t)),Ve(e,t+1,c,!0,s)&&(e.dump&&10===e.dump.charCodeAt(0)?u+=":":u+=": ",p+=u+=e.dump));e.tag=f,e.dump=p||"{}"}(e,t,e.dump,r),f&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,n){var i,r,o,a,l,c="",s=e.tag,u=Object.keys(n);for(i=0,r=u.length;i1024&&(l+="? "),l+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),Ve(e,t,a,!1,!1)&&(c+=l+=e.dump));e.tag=s,e.dump="{"+c+"}"}(e,t,e.dump),f&&(e.dump="&ref_"+p+" "+e.dump));else if("[object Array]"===s)i&&0!==e.dump.length?(e.noArrayIndent&&!l&&t>0?$e(e,t-1,e.dump,r):$e(e,t,e.dump,r),f&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,n){var i,r,o,a="",l=e.tag;for(i=0,r=n.length;i",e.dump=c+" "+e.dump)}return!0}function Ze(e,t){var n,i,r=[],o=[];for(Je(e,r,o),n=0,i=o.length;n maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; +} + + +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; +} + + +function makeSnippet(mark, options) { + options = Object.create(options || null); + + if (!mark.buffer) return null; + + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); +} + + +var snippet = makeSnippet; + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type$1(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +var type = Type$1; + +/*eslint-disable max-len*/ + + + + + +function compileList(schema, name) { + var result = []; + + schema[name].forEach(function (currentType) { + var newIndex = result.length; + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema$1(definition) { + return this.extend(definition); +} + + +Schema$1.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + + } else { + throw new exception('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + if (type$1.loadKind && type$1.loadKind !== 'scalar') { + throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + + if (type$1.multi) { + throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); + + explicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema$1.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + + return result; +}; + + +var schema = Schema$1; + +var str = new type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +var seq = new type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +var map = new type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +var failsafe = new schema({ + explicit: [ + str, + seq, + map + ] +}); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +var _null = new type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +var bool = new type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + } + + // base 10 (except 0) + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +var int = new type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +var float = new type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +var json = failsafe.extend({ + implicit: [ + _null, + bool, + int, + float + ] +}); + +var core = json; + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +var timestamp = new type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +var merge = new type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +/*eslint-disable no-bitwise*/ + + + + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + return new Uint8Array(result); +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} + +var binary = new type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; +var _toString$2 = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString$2.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty$3.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +var omap = new type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +var _toString$1 = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString$1.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +var pairs = new type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$2.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +var set = new type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +var _default = core.extend({ + implicit: [ + timestamp, + merge + ], + explicit: [ + binary, + omap, + pairs, + set + ] +}); + +/*eslint-disable max-len,no-use-before-define*/ + + + + + + + +var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State$1(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || _default; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; + + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; + + mark.snippet = snippet(mark); + + return new exception(message, mark); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$1.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty$1.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$1.call(overridableKeys, keyNode) && + _hasOwnProperty$1.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State$1(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll$1(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load$1(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception('expected a single document in the stream, but found more'); +} + + +var loadAll_1 = loadAll$1; +var load_1 = load$1; + +var loader = { + loadAll: loadAll_1, + load: load_1 +}; + +/*eslint-disable no-use-before-define*/ + + + + + +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + + +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; + +function State(options) { + this.schema = options['schema'] || _default; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string) + '"'; + default: + throw new exception('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; + + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new exception('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new exception('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + + state.dump = tagStr + ' ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump$1(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; +} + +var dump_1 = dump$1; + +var dumper = { + dump: dump_1 +}; + +function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; +} + + +var Type = type; +var Schema = schema; +var FAILSAFE_SCHEMA = failsafe; +var JSON_SCHEMA = json; +var CORE_SCHEMA = core; +var DEFAULT_SCHEMA = _default; +var load = loader.load; +var loadAll = loader.loadAll; +var dump = dumper.dump; +var YAMLException = exception; + +// Re-export all types in case user wants to create custom schema +var types = { + binary: binary, + float: float, + map: map, + null: _null, + pairs: pairs, + set: set, + timestamp: timestamp, + bool: bool, + int: int, + merge: merge, + omap: omap, + seq: seq, + str: str +}; + +// Removed functions from JS-YAML 3.0.x +var safeLoad = renamed('safeLoad', 'load'); +var safeLoadAll = renamed('safeLoadAll', 'loadAll'); +var safeDump = renamed('safeDump', 'dump'); + +var jsYaml = { + Type: Type, + Schema: Schema, + FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, + JSON_SCHEMA: JSON_SCHEMA, + CORE_SCHEMA: CORE_SCHEMA, + DEFAULT_SCHEMA: DEFAULT_SCHEMA, + load: load, + loadAll: loadAll, + dump: dump, + YAMLException: YAMLException, + types: types, + safeLoad: safeLoad, + safeLoadAll: safeLoadAll, + safeDump: safeDump +}; + +export default jsYaml; +export { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema, Type, YAMLException, dump, load, loadAll, safeDump, safeLoad, safeLoadAll, types }; diff --git a/node_modules/js-yaml/index.js b/node_modules/js-yaml/index.js new file mode 100644 index 00000000..bcb7eba7 --- /dev/null +++ b/node_modules/js-yaml/index.js @@ -0,0 +1,47 @@ +'use strict'; + + +var loader = require('./lib/loader'); +var dumper = require('./lib/dumper'); + + +function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; +} + + +module.exports.Type = require('./lib/type'); +module.exports.Schema = require('./lib/schema'); +module.exports.FAILSAFE_SCHEMA = require('./lib/schema/failsafe'); +module.exports.JSON_SCHEMA = require('./lib/schema/json'); +module.exports.CORE_SCHEMA = require('./lib/schema/core'); +module.exports.DEFAULT_SCHEMA = require('./lib/schema/default'); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.dump = dumper.dump; +module.exports.YAMLException = require('./lib/exception'); + +// Re-export all types in case user wants to create custom schema +module.exports.types = { + binary: require('./lib/type/binary'), + float: require('./lib/type/float'), + map: require('./lib/type/map'), + null: require('./lib/type/null'), + pairs: require('./lib/type/pairs'), + set: require('./lib/type/set'), + timestamp: require('./lib/type/timestamp'), + bool: require('./lib/type/bool'), + int: require('./lib/type/int'), + merge: require('./lib/type/merge'), + omap: require('./lib/type/omap'), + seq: require('./lib/type/seq'), + str: require('./lib/type/str') +}; + +// Removed functions from JS-YAML 3.0.x +module.exports.safeLoad = renamed('safeLoad', 'load'); +module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); +module.exports.safeDump = renamed('safeDump', 'dump'); diff --git a/node_modules/js-yaml/lib/common.js b/node_modules/js-yaml/lib/common.js new file mode 100644 index 00000000..25ef7d8e --- /dev/null +++ b/node_modules/js-yaml/lib/common.js @@ -0,0 +1,59 @@ +'use strict'; + + +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; +} + + +function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; diff --git a/node_modules/js-yaml/lib/dumper.js b/node_modules/js-yaml/lib/dumper.js new file mode 100644 index 00000000..f357a6ae --- /dev/null +++ b/node_modules/js-yaml/lib/dumper.js @@ -0,0 +1,965 @@ +'use strict'; + +/*eslint-disable no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var DEFAULT_SCHEMA = require('./schema/default'); + +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + + +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; + +function State(options) { + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; + + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + + state.dump = tagStr + ' ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; +} + +module.exports.dump = dump; diff --git a/node_modules/js-yaml/lib/exception.js b/node_modules/js-yaml/lib/exception.js new file mode 100644 index 00000000..7f62daae --- /dev/null +++ b/node_modules/js-yaml/lib/exception.js @@ -0,0 +1,55 @@ +// YAML error class. http://stackoverflow.com/questions/8458984 +// +'use strict'; + + +function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; + + if (!exception.mark) return message; + + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } + + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; + + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; + } + + return message + ' ' + where; +} + + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; + + +module.exports = YAMLException; diff --git a/node_modules/js-yaml/lib/loader.js b/node_modules/js-yaml/lib/loader.js new file mode 100644 index 00000000..39f13f56 --- /dev/null +++ b/node_modules/js-yaml/lib/loader.js @@ -0,0 +1,1727 @@ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var makeSnippet = require('./snippet'); +var DEFAULT_SCHEMA = require('./schema/default'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; + + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; + + mark.snippet = makeSnippet(mark); + + return new YAMLException(message, mark); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; diff --git a/node_modules/js-yaml/lib/schema.js b/node_modules/js-yaml/lib/schema.js new file mode 100644 index 00000000..65b41f40 --- /dev/null +++ b/node_modules/js-yaml/lib/schema.js @@ -0,0 +1,121 @@ +'use strict'; + +/*eslint-disable max-len*/ + +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name) { + var result = []; + + schema[name].forEach(function (currentType) { + var newIndex = result.length; + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + return this.extend(definition); +} + + +Schema.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof Type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + + } else { + throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + + if (type.multi) { + throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); + + explicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + + return result; +}; + + +module.exports = Schema; diff --git a/node_modules/js-yaml/lib/schema/core.js b/node_modules/js-yaml/lib/schema/core.js new file mode 100644 index 00000000..608b26de --- /dev/null +++ b/node_modules/js-yaml/lib/schema/core.js @@ -0,0 +1,11 @@ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +module.exports = require('./json'); diff --git a/node_modules/js-yaml/lib/schema/default.js b/node_modules/js-yaml/lib/schema/default.js new file mode 100644 index 00000000..3af0520d --- /dev/null +++ b/node_modules/js-yaml/lib/schema/default.js @@ -0,0 +1,22 @@ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +module.exports = require('./core').extend({ + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); diff --git a/node_modules/js-yaml/lib/schema/failsafe.js b/node_modules/js-yaml/lib/schema/failsafe.js new file mode 100644 index 00000000..b7a33eb7 --- /dev/null +++ b/node_modules/js-yaml/lib/schema/failsafe.js @@ -0,0 +1,17 @@ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); diff --git a/node_modules/js-yaml/lib/schema/json.js b/node_modules/js-yaml/lib/schema/json.js new file mode 100644 index 00000000..b73df78e --- /dev/null +++ b/node_modules/js-yaml/lib/schema/json.js @@ -0,0 +1,19 @@ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +module.exports = require('./failsafe').extend({ + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); diff --git a/node_modules/js-yaml/lib/snippet.js b/node_modules/js-yaml/lib/snippet.js new file mode 100644 index 00000000..00e2133c --- /dev/null +++ b/node_modules/js-yaml/lib/snippet.js @@ -0,0 +1,101 @@ +'use strict'; + + +var common = require('./common'); + + +// get snippet for a single line, respecting maxLength +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; +} + + +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; +} + + +function makeSnippet(mark, options) { + options = Object.create(options || null); + + if (!mark.buffer) return null; + + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); +} + + +module.exports = makeSnippet; diff --git a/node_modules/js-yaml/lib/type.js b/node_modules/js-yaml/lib/type.js new file mode 100644 index 00000000..5e57877f --- /dev/null +++ b/node_modules/js-yaml/lib/type.js @@ -0,0 +1,66 @@ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; diff --git a/node_modules/js-yaml/lib/type/binary.js b/node_modules/js-yaml/lib/type/binary.js new file mode 100644 index 00000000..e1523513 --- /dev/null +++ b/node_modules/js-yaml/lib/type/binary.js @@ -0,0 +1,125 @@ +'use strict'; + +/*eslint-disable no-bitwise*/ + + +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + return new Uint8Array(result); +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); diff --git a/node_modules/js-yaml/lib/type/bool.js b/node_modules/js-yaml/lib/type/bool.js new file mode 100644 index 00000000..cb774593 --- /dev/null +++ b/node_modules/js-yaml/lib/type/bool.js @@ -0,0 +1,35 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/js-yaml/lib/type/float.js b/node_modules/js-yaml/lib/type/float.js new file mode 100644 index 00000000..74d77ec2 --- /dev/null +++ b/node_modules/js-yaml/lib/type/float.js @@ -0,0 +1,97 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/js-yaml/lib/type/int.js b/node_modules/js-yaml/lib/type/int.js new file mode 100644 index 00000000..3fe3a443 --- /dev/null +++ b/node_modules/js-yaml/lib/type/int.js @@ -0,0 +1,156 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + } + + // base 10 (except 0) + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); diff --git a/node_modules/js-yaml/lib/type/map.js b/node_modules/js-yaml/lib/type/map.js new file mode 100644 index 00000000..f327beeb --- /dev/null +++ b/node_modules/js-yaml/lib/type/map.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); diff --git a/node_modules/js-yaml/lib/type/merge.js b/node_modules/js-yaml/lib/type/merge.js new file mode 100644 index 00000000..ae08a864 --- /dev/null +++ b/node_modules/js-yaml/lib/type/merge.js @@ -0,0 +1,12 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); diff --git a/node_modules/js-yaml/lib/type/null.js b/node_modules/js-yaml/lib/type/null.js new file mode 100644 index 00000000..315ca4e2 --- /dev/null +++ b/node_modules/js-yaml/lib/type/null.js @@ -0,0 +1,35 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/js-yaml/lib/type/omap.js b/node_modules/js-yaml/lib/type/omap.js new file mode 100644 index 00000000..b2b5323b --- /dev/null +++ b/node_modules/js-yaml/lib/type/omap.js @@ -0,0 +1,44 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); diff --git a/node_modules/js-yaml/lib/type/pairs.js b/node_modules/js-yaml/lib/type/pairs.js new file mode 100644 index 00000000..74b52403 --- /dev/null +++ b/node_modules/js-yaml/lib/type/pairs.js @@ -0,0 +1,53 @@ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); diff --git a/node_modules/js-yaml/lib/type/seq.js b/node_modules/js-yaml/lib/type/seq.js new file mode 100644 index 00000000..be8f77f2 --- /dev/null +++ b/node_modules/js-yaml/lib/type/seq.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); diff --git a/node_modules/js-yaml/lib/type/set.js b/node_modules/js-yaml/lib/type/set.js new file mode 100644 index 00000000..f885a329 --- /dev/null +++ b/node_modules/js-yaml/lib/type/set.js @@ -0,0 +1,29 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); diff --git a/node_modules/js-yaml/lib/type/str.js b/node_modules/js-yaml/lib/type/str.js new file mode 100644 index 00000000..27acc106 --- /dev/null +++ b/node_modules/js-yaml/lib/type/str.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); diff --git a/node_modules/js-yaml/lib/type/timestamp.js b/node_modules/js-yaml/lib/type/timestamp.js new file mode 100644 index 00000000..8fa9c586 --- /dev/null +++ b/node_modules/js-yaml/lib/type/timestamp.js @@ -0,0 +1,88 @@ +'use strict'; + +var Type = require('../type'); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); diff --git a/node_modules/js-yaml/package.json b/node_modules/js-yaml/package.json new file mode 100644 index 00000000..17574da8 --- /dev/null +++ b/node_modules/js-yaml/package.json @@ -0,0 +1,66 @@ +{ + "name": "js-yaml", + "version": "4.1.0", + "description": "YAML 1.2 parser and serializer", + "keywords": [ + "yaml", + "parser", + "serializer", + "pyyaml" + ], + "author": "Vladimir Zapparov ", + "contributors": [ + "Aleksey V Zapparov (http://www.ixti.net/)", + "Vitaly Puzrin (https://github.com/puzrin)", + "Martin Grenfell (http://got-ravings.blogspot.com)" + ], + "license": "MIT", + "repository": "nodeca/js-yaml", + "files": [ + "index.js", + "lib/", + "bin/", + "dist/" + ], + "bin": { + "js-yaml": "bin/js-yaml.js" + }, + "module": "./dist/js-yaml.mjs", + "exports": { + ".": { + "import": "./dist/js-yaml.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "lint": "eslint .", + "test": "npm run lint && mocha", + "coverage": "npm run lint && nyc mocha && nyc report --reporter html", + "demo": "npm run lint && node support/build_demo.js", + "gh-demo": "npm run demo && gh-pages -d demo -f", + "browserify": "rollup -c support/rollup.config.js", + "prepublishOnly": "npm run gh-demo" + }, + "unpkg": "dist/js-yaml.min.js", + "jsdelivr": "dist/js-yaml.min.js", + "dependencies": { + "argparse": "^2.0.1" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^17.0.0", + "@rollup/plugin-node-resolve": "^11.0.0", + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "codemirror": "^5.13.4", + "eslint": "^7.0.0", + "fast-check": "^2.8.0", + "gh-pages": "^3.1.0", + "mocha": "^8.2.1", + "nyc": "^15.1.0", + "rollup": "^2.34.1", + "rollup-plugin-node-polyfills": "^0.2.1", + "rollup-plugin-terser": "^7.0.2", + "shelljs": "^0.8.4" + } +} diff --git a/node_modules/json-buffer/.travis.yml b/node_modules/json-buffer/.travis.yml new file mode 100644 index 00000000..244b7e88 --- /dev/null +++ b/node_modules/json-buffer/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - '0.10' diff --git a/node_modules/json-buffer/LICENSE b/node_modules/json-buffer/LICENSE new file mode 100644 index 00000000..b799ec00 --- /dev/null +++ b/node_modules/json-buffer/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2013 Dominic Tarr + +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software and +associated documentation files (the "Software"), to +deal in the Software without restriction, including +without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom +the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/json-buffer/README.md b/node_modules/json-buffer/README.md new file mode 100644 index 00000000..4773d631 --- /dev/null +++ b/node_modules/json-buffer/README.md @@ -0,0 +1,24 @@ +# json-buffer + +JSON functions that can convert buffers! + +[![build status](https://secure.travis-ci.org/dominictarr/json-buffer.png)](http://travis-ci.org/dominictarr/json-buffer) + +[![testling badge](https://ci.testling.com/dominictarr/json-buffer.png)](https://ci.testling.com/dominictarr/json-buffer) + +JSON mangles buffers by converting to an array... +which isn't helpful. json-buffers converts to base64 instead, +and deconverts base64 to a buffer. + +``` js +var JSONB = require('json-buffer') +var Buffer = require('buffer').Buffer + +var str = JSONB.stringify(Buffer.from('hello there!')) + +console.log(JSONB.parse(str)) //GET a BUFFER back +``` + +## License + +MIT diff --git a/node_modules/json-buffer/index.js b/node_modules/json-buffer/index.js new file mode 100644 index 00000000..16f012e4 --- /dev/null +++ b/node_modules/json-buffer/index.js @@ -0,0 +1,58 @@ +//TODO: handle reviver/dehydrate function like normal +//and handle indentation, like normal. +//if anyone needs this... please send pull request. + +exports.stringify = function stringify (o) { + if('undefined' == typeof o) return o + + if(o && Buffer.isBuffer(o)) + return JSON.stringify(':base64:' + o.toString('base64')) + + if(o && o.toJSON) + o = o.toJSON() + + if(o && 'object' === typeof o) { + var s = '' + var array = Array.isArray(o) + s = array ? '[' : '{' + var first = true + + for(var k in o) { + var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]) + if(Object.hasOwnProperty.call(o, k) && !ignore) { + if(!first) + s += ',' + first = false + if (array) { + if(o[k] == undefined) + s += 'null' + else + s += stringify(o[k]) + } else if (o[k] !== void(0)) { + s += stringify(k) + ':' + stringify(o[k]) + } + } + } + + s += array ? ']' : '}' + + return s + } else if ('string' === typeof o) { + return JSON.stringify(/^:/.test(o) ? ':' + o : o) + } else if ('undefined' === typeof o) { + return 'null'; + } else + return JSON.stringify(o) +} + +exports.parse = function (s) { + return JSON.parse(s, function (key, value) { + if('string' === typeof value) { + if(/^:base64:/.test(value)) + return Buffer.from(value.substring(8), 'base64') + else + return /^:/.test(value) ? value.substring(1) : value + } + return value + }) +} diff --git a/node_modules/json-buffer/package.json b/node_modules/json-buffer/package.json new file mode 100644 index 00000000..346747fd --- /dev/null +++ b/node_modules/json-buffer/package.json @@ -0,0 +1,34 @@ +{ + "name": "json-buffer", + "description": "JSON parse & stringify that supports binary via bops & base64", + "version": "3.0.1", + "homepage": "https://github.com/dominictarr/json-buffer", + "repository": { + "type": "git", + "url": "git://github.com/dominictarr/json-buffer.git" + }, + "devDependencies": { + "tape": "^4.6.3" + }, + "scripts": { + "test": "set -e; for t in test/*.js; do node $t; done" + }, + "author": "Dominic Tarr (http://dominictarr.com)", + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/17..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/json-buffer/test/index.js b/node_modules/json-buffer/test/index.js new file mode 100644 index 00000000..94e83720 --- /dev/null +++ b/node_modules/json-buffer/test/index.js @@ -0,0 +1,63 @@ + +var test = require('tape') +var _JSON = require('../') + +function clone (o) { + return JSON.parse(JSON.stringify(o)) +} + +var examples = { + simple: { foo: [], bar: {}, baz: Buffer.from('some binary data') }, + just_buffer: Buffer.from('JUST A BUFFER'), + all_types: { + string:'hello', + number: 3145, + null: null, + object: {}, + array: [], + boolean: true, + boolean2: false + }, + foo: Buffer.from('foo'), + foo2: Buffer.from('foo2'), + escape: { + buffer: Buffer.from('x'), + string: _JSON.stringify(Buffer.from('x')) + }, + escape2: { + buffer: Buffer.from('x'), + string: ':base64:'+ Buffer.from('x').toString('base64') + }, + undefined: { + empty: undefined, test: true + }, + undefined2: { + first: 1, empty: undefined, test: true + }, + undefinedArray: { + array: [undefined, 1, 'two'] + }, + fn: { + fn: function () {} + }, + undefined: undefined +} + +for(k in examples) +(function (value, k) { + test(k, function (t) { + var s = _JSON.stringify(value) + console.log('parse', s) + if(JSON.stringify(value) !== undefined) { + console.log(s) + var _value = _JSON.parse(s) + t.deepEqual(clone(_value), clone(value)) + } + else + t.equal(s, undefined) + t.end() + }) +})(examples[k], k) + + + diff --git a/node_modules/json-schema-traverse/.eslintrc.yml b/node_modules/json-schema-traverse/.eslintrc.yml new file mode 100644 index 00000000..ab1762da --- /dev/null +++ b/node_modules/json-schema-traverse/.eslintrc.yml @@ -0,0 +1,27 @@ +extends: eslint:recommended +env: + node: true + browser: true +rules: + block-scoped-var: 2 + complexity: [2, 13] + curly: [2, multi-or-nest, consistent] + dot-location: [2, property] + dot-notation: 2 + indent: [2, 2, SwitchCase: 1] + linebreak-style: [2, unix] + new-cap: 2 + no-console: [2, allow: [warn, error]] + no-else-return: 2 + no-eq-null: 2 + no-fallthrough: 2 + no-invalid-this: 2 + no-return-assign: 2 + no-shadow: 1 + no-trailing-spaces: 2 + no-use-before-define: [2, nofunc] + quotes: [2, single, avoid-escape] + semi: [2, always] + strict: [2, global] + valid-jsdoc: [2, requireReturn: false] + no-control-regex: 0 diff --git a/node_modules/json-schema-traverse/.travis.yml b/node_modules/json-schema-traverse/.travis.yml new file mode 100644 index 00000000..7ddce74b --- /dev/null +++ b/node_modules/json-schema-traverse/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "4" + - "6" + - "7" + - "8" +after_script: + - coveralls < coverage/lcov.info diff --git a/node_modules/json-schema-traverse/LICENSE b/node_modules/json-schema-traverse/LICENSE new file mode 100644 index 00000000..7f154356 --- /dev/null +++ b/node_modules/json-schema-traverse/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/json-schema-traverse/README.md b/node_modules/json-schema-traverse/README.md new file mode 100644 index 00000000..d5ccaf45 --- /dev/null +++ b/node_modules/json-schema-traverse/README.md @@ -0,0 +1,83 @@ +# json-schema-traverse +Traverse JSON Schema passing each schema object to callback + +[![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse) +[![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse) +[![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) + + +## Install + +``` +npm install json-schema-traverse +``` + + +## Usage + +```javascript +const traverse = require('json-schema-traverse'); +const schema = { + properties: { + foo: {type: 'string'}, + bar: {type: 'integer'} + } +}; + +traverse(schema, {cb}); +// cb is called 3 times with: +// 1. root schema +// 2. {type: 'string'} +// 3. {type: 'integer'} + +// Or: + +traverse(schema, {cb: {pre, post}}); +// pre is called 3 times with: +// 1. root schema +// 2. {type: 'string'} +// 3. {type: 'integer'} +// +// post is called 3 times with: +// 1. {type: 'string'} +// 2. {type: 'integer'} +// 3. root schema + +``` + +Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. + +Callback is passed these parameters: + +- _schema_: the current schema object +- _JSON pointer_: from the root schema to the current schema object +- _root schema_: the schema passed to `traverse` object +- _parent JSON pointer_: from the root schema to the parent schema object (see below) +- _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) +- _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema +- _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` + + +## Traverse objects in all unknown keywords + +```javascript +const traverse = require('json-schema-traverse'); +const schema = { + mySchema: { + minimum: 1, + maximum: 2 + } +}; + +traverse(schema, {allKeys: true, cb}); +// cb is called 2 times with: +// 1. root schema +// 2. mySchema +``` + +Without option `allKeys: true` callback will be called only with root schema. + + +## License + +[MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) diff --git a/node_modules/json-schema-traverse/index.js b/node_modules/json-schema-traverse/index.js new file mode 100644 index 00000000..d4a18dfc --- /dev/null +++ b/node_modules/json-schema-traverse/index.js @@ -0,0 +1,89 @@ +'use strict'; + +var traverse = module.exports = function (schema, opts, cb) { + // Legacy support for v0.3.1 and earlier. + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } + + cb = opts.cb || cb; + var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + + _traverse(opts, pre, post, schema, '', schema); +}; + + +traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true +}; + +traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; + +traverse.propsKeywords = { + definitions: true, + properties: true, + patternProperties: true, + dependencies: true +}; + +traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; + + +function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == 'object' && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i=0; i + keyv +
+
+ + +> Simple key-value storage with support for multiple backends + +[![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) +[![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) +[![npm](https://img.shields.io/npm/dm/keyv.svg)](https://www.npmjs.com/package/keyv) +[![npm](https://img.shields.io/npm/v/keyv.svg)](https://www.npmjs.com/package/keyv) + +Keyv provides a consistent interface for key-value storage across multiple backends via storage adapters. It supports TTL based expiry, making it suitable as a cache or a persistent key-value store. + +## Features + +There are a few existing modules similar to Keyv, however Keyv is different because it: + +- Isn't bloated +- Has a simple Promise based API +- Suitable as a TTL based cache or persistent key-value store +- [Easily embeddable](#add-cache-support-to-your-module) inside another module +- Works with any storage that implements the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) API +- Handles all JSON types plus `Buffer` +- Supports namespaces +- Wide range of [**efficient, well tested**](#official-storage-adapters) storage adapters +- Connection errors are passed through (db failures won't kill your app) +- Supports the current active LTS version of Node.js or higher + +## Usage + +Install Keyv. + +``` +npm install --save keyv +``` + +By default everything is stored in memory, you can optionally also install a storage adapter. + +``` +npm install --save @keyv/redis +npm install --save @keyv/mongo +npm install --save @keyv/sqlite +npm install --save @keyv/postgres +npm install --save @keyv/mysql +npm install --save @keyv/etcd +``` + +Create a new Keyv instance, passing your connection string if applicable. Keyv will automatically load the correct storage adapter. + +```js +const Keyv = require('keyv'); + +// One of the following +const keyv = new Keyv(); +const keyv = new Keyv('redis://user:pass@localhost:6379'); +const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname'); +const keyv = new Keyv('sqlite://path/to/database.sqlite'); +const keyv = new Keyv('postgresql://user:pass@localhost:5432/dbname'); +const keyv = new Keyv('mysql://user:pass@localhost:3306/dbname'); +const keyv = new Keyv('etcd://localhost:2379'); + +// Handle DB connection errors +keyv.on('error', err => console.log('Connection Error', err)); + +await keyv.set('foo', 'expires in 1 second', 1000); // true +await keyv.set('foo', 'never expires'); // true +await keyv.get('foo'); // 'never expires' +await keyv.delete('foo'); // true +await keyv.clear(); // undefined +``` + +### Namespaces + +You can namespace your Keyv instance to avoid key collisions and allow you to clear only a certain namespace while using the same database. + +```js +const users = new Keyv('redis://user:pass@localhost:6379', { namespace: 'users' }); +const cache = new Keyv('redis://user:pass@localhost:6379', { namespace: 'cache' }); + +await users.set('foo', 'users'); // true +await cache.set('foo', 'cache'); // true +await users.get('foo'); // 'users' +await cache.get('foo'); // 'cache' +await users.clear(); // undefined +await users.get('foo'); // undefined +await cache.get('foo'); // 'cache' +``` + +### Custom Serializers + +Keyv uses [`json-buffer`](https://github.com/dominictarr/json-buffer) for data serialization to ensure consistency across different backends. + +You can optionally provide your own serialization functions to support extra data types or to serialize to something other than JSON. + +```js +const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse }); +``` + +**Warning:** Using custom serializers means you lose any guarantee of data consistency. You should do extensive testing with your serialisation functions and chosen storage engine. + +## Official Storage Adapters + +The official storage adapters are covered by [over 150 integration tests](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) to guarantee consistent behaviour. They are lightweight, efficient wrappers over the DB clients making use of indexes and native TTLs where available. + +Database | Adapter | Native TTL +---|---|--- +Redis | [@keyv/redis](https://github.com/jaredwray/keyv/tree/master/packages/redis) | Yes +MongoDB | [@keyv/mongo](https://github.com/jaredwray/keyv/tree/master/packages/mongo) | Yes +SQLite | [@keyv/sqlite](https://github.com/jaredwray/keyv/tree/master/packages/sqlite) | No +PostgreSQL | [@keyv/postgres](https://github.com/jaredwray/keyv/tree/master/packages/postgres) | No +MySQL | [@keyv/mysql](https://github.com/jaredwray/keyv/tree/master/packages/mysql) | No +Etcd | [@keyv/etcd](https://github.com/jaredwray/keyv/tree/master/packages/etcd) | Yes +Memcache | [@keyv/memcache](https://github.com/jaredwray/keyv/tree/master/packages/memcache) | Yes + +## Third-party Storage Adapters + +You can also use third-party storage adapters or build your own. Keyv will wrap these storage adapters in TTL functionality and handle complex types internally. + +```js +const Keyv = require('keyv'); +const myAdapter = require('./my-storage-adapter'); + +const keyv = new Keyv({ store: myAdapter }); +``` + +Any store that follows the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) api will work. + +```js +new Keyv({ store: new Map() }); +``` + +For example, [`quick-lru`](https://github.com/sindresorhus/quick-lru) is a completely unrelated module that implements the Map API. + +```js +const Keyv = require('keyv'); +const QuickLRU = require('quick-lru'); + +const lru = new QuickLRU({ maxSize: 1000 }); +const keyv = new Keyv({ store: lru }); +``` + +The following are third-party storage adapters compatible with Keyv: + +- [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple "Least Recently Used" (LRU) cache +- [keyv-file](https://github.com/zaaack/keyv-file) - File system storage adapter for Keyv +- [keyv-dynamodb](https://www.npmjs.com/package/keyv-dynamodb) - DynamoDB storage adapter for Keyv +- [keyv-lru](https://www.npmjs.com/package/keyv-lru) - LRU storage adapter for Keyv +- [keyv-null](https://www.npmjs.com/package/keyv-null) - Null storage adapter for Keyv +- [keyv-firestore ](https://github.com/goto-bus-stop/keyv-firestore) – Firebase Cloud Firestore adapter for Keyv +- [keyv-mssql](https://github.com/pmorgan3/keyv-mssql) - Microsoft Sql Server adapter for Keyv +- [keyv-azuretable](https://github.com/howlowck/keyv-azuretable) - Azure Table Storage/API adapter for Keyv +- [keyv-arango](https://github.com/TimMikeladze/keyv-arango) - ArangoDB storage adapter for Keyv +- [keyv-momento](https://github.com/momentohq/node-keyv-adaptor/) - Momento storage adapter for Keyv + +## Add Cache Support to your Module + +Keyv is designed to be easily embedded into other modules to add cache support. The recommended pattern is to expose a `cache` option in your modules options which is passed through to Keyv. Caching will work in memory by default and users have the option to also install a Keyv storage adapter and pass in a connection string, or any other storage that implements the `Map` API. + +You should also set a namespace for your module so you can safely call `.clear()` without clearing unrelated app data. + +Inside your module: + +```js +class AwesomeModule { + constructor(opts) { + this.cache = new Keyv({ + uri: typeof opts.cache === 'string' && opts.cache, + store: typeof opts.cache !== 'string' && opts.cache, + namespace: 'awesome-module' + }); + } +} +``` + +Now it can be consumed like this: + +```js +const AwesomeModule = require('awesome-module'); + +// Caches stuff in memory by default +const awesomeModule = new AwesomeModule(); + +// After npm install --save keyv-redis +const awesomeModule = new AwesomeModule({ cache: 'redis://localhost' }); + +// Some third-party module that implements the Map API +const awesomeModule = new AwesomeModule({ cache: some3rdPartyStore }); +``` + +## Compression + +Keyv supports `gzip` and `brotli` compression. To enable compression, pass the `compress` option to the constructor. + +```js +const KeyvGzip = require('@keyv/compress-gzip'); +const Keyv = require('keyv'); + +const keyvGzip = new KeyvGzip(); +const keyv = new Keyv({ compression: KeyvGzip }); +``` + +You can also pass a custom compression function to the `compression` option. Following the pattern of the official compression adapters. + +### Want to build your own? + +Great! Keyv is designed to be easily extended. You can build your own compression adapter by following the pattern of the official compression adapters based on this interface: + +```typescript +interface CompressionAdapter { + async compress(value: any, options?: any); + async decompress(value: any, options?: any); + async serialize(value: any); + async deserialize(value: any); +} +``` + +In addition to the interface, you can test it with our compression test suite using @keyv/test-suite: + +```js +const {keyvCompresstionTests} = require('@keyv/test-suite'); +const KeyvGzip = require('@keyv/compress-gzip'); + +keyvCompresstionTests(test, new KeyvGzip()); +``` + +## API + +### new Keyv([uri], [options]) + +Returns a new Keyv instance. + +The Keyv instance is also an `EventEmitter` that will emit an `'error'` event if the storage adapter connection fails. + +### uri + +Type: `String`
+Default: `undefined` + +The connection string URI. + +Merged into the options object as options.uri. + +### options + +Type: `Object` + +The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. + +#### options.namespace + +Type: `String`
+Default: `'keyv'` + +Namespace for the current instance. + +#### options.ttl + +Type: `Number`
+Default: `undefined` + +Default TTL. Can be overridden by specififying a TTL on `.set()`. + +#### options.compression + +Type: `@keyv/compress-`
+Default: `undefined` + +Compression package to use. See [Compression](#compression) for more details. + +#### options.serialize + +Type: `Function`
+Default: `JSONB.stringify` + +A custom serialization function. + +#### options.deserialize + +Type: `Function`
+Default: `JSONB.parse` + +A custom deserialization function. + +#### options.store + +Type: `Storage adapter instance`
+Default: `new Map()` + +The storage adapter instance to be used by Keyv. + +#### options.adapter + +Type: `String`
+Default: `undefined` + +Specify an adapter to use. e.g `'redis'` or `'mongodb'`. + +### Instance + +Keys must always be strings. Values can be of any type. + +#### .set(key, value, [ttl]) + +Set a value. + +By default keys are persistent. You can set an expiry TTL in milliseconds. + +Returns a promise which resolves to `true`. + +#### .get(key, [options]) + +Returns a promise which resolves to the retrieved value. + +##### options.raw + +Type: `Boolean`
+Default: `false` + +If set to true the raw DB object Keyv stores internally will be returned instead of just the value. + +This contains the TTL timestamp. + +#### .delete(key) + +Deletes an entry. + +Returns a promise which resolves to `true` if the key existed, `false` if not. + +#### .clear() + +Delete all entries in the current namespace. + +Returns a promise which is resolved when the entries have been cleared. + +#### .iterator() + +Iterate over all entries of the current namespace. + +Returns a iterable that can be iterated by for-of loops. For example: + +```js +// please note that the "await" keyword should be used here +for await (const [key, value] of this.keyv.iterator()) { + console.log(key, value); +}; +``` + +# How to Contribute + +In this section of the documentation we will cover: + +1) How to set up this repository locally +2) How to get started with running commands +3) How to contribute changes using Pull Requests + +## Dependencies + +This package requires the following dependencies to run: + +1) [Yarn V1](https://yarnpkg.com/getting-started/install) +3) [Docker](https://docs.docker.com/get-docker/) + +## Setting up your workspace + +To contribute to this repository, start by setting up this project locally: + +1) Fork this repository into your Git account +2) Clone the forked repository to your local directory using `git clone` +3) Install any of the above missing dependencies + +## Launching the project + +Once the project is installed locally, you are ready to start up its services: + +1) Ensure that your Docker service is running. +2) From the root directory of your project, run the `yarn` command in the command prompt to install yarn. +3) Run the `yarn bootstrap` command to install any necessary dependencies. +4) Run `yarn test:services:start` to start up this project's Docker container. The container will launch all services within your workspace. + +## Available Commands + +Once the project is running, you can execute a variety of commands. The root workspace and each subpackage contain a `package.json` file with a `scripts` field listing all the commands that can be executed from that directory. This project also supports native `yarn`, and `docker` commands. + +Here, we'll cover the primary commands that can be executed from the root directory. Unless otherwise noted, these commands can also be executed from a subpackage. If executed from a subpackage, they will only affect that subpackage, rather than the entire workspace. + +### `yarn` + +The `yarn` command installs yarn in the workspace. + +### `yarn bootstrap` + +The `yarn bootstrap` command installs all dependencies in the workspace. + +### `yarn test:services:start` + +The `yarn test:services:start` command starts up the project's Docker container, launching all services in the workspace. This command must be executed from the root directory. + +### `yarn test:services:stop` + +The `yarn test:services:stop` command brings down the project's Docker container, halting all services. This command must be executed from the root directory. + +### `yarn test` + +The `yarn test` command runs all tests in the workspace. + +### `yarn clean` + +The `yarn clean` command removes yarn and all dependencies installed by yarn. After executing this command, you must repeat the steps in *Setting up your workspace* to rebuild your workspace. + +## Contributing Changes + +Now that you've set up your workspace, you're ready to contribute changes to the `keyv` repository. + +1) Make any changes that you would like to contribute in your local workspace. +2) After making these changes, ensure that the project's tests still pass by executing the `yarn test` command in the root directory. +3) Commit your changes and push them to your forked repository. +4) Navigate to the original `keyv` repository and go the *Pull Requests* tab. +5) Click the *New pull request* button, and open a pull request for the branch in your repository that contains your changes. +6) Once your pull request is created, ensure that all checks have passed and that your branch has no conflicts with the base branch. If there are any issues, resolve these changes in your local repository, and then commit and push them to git. +7) Similarly, respond to any reviewer comments or requests for changes by making edits to your local repository and pushing them to Git. +8) Once the pull request has been reviewed, those with write access to the branch will be able to merge your changes into the `keyv` repository. + +If you need more information on the steps to create a pull request, you can find a detailed walkthrough in the [Github documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork) + +## License + +MIT © Jared Wray diff --git a/node_modules/keyv/package.json b/node_modules/keyv/package.json new file mode 100644 index 00000000..a8304611 --- /dev/null +++ b/node_modules/keyv/package.json @@ -0,0 +1,57 @@ +{ + "name": "keyv", + "version": "4.5.4", + "description": "Simple key-value storage with support for multiple backends", + "main": "src/index.js", + "scripts": { + "build": "echo 'No build step required.'", + "prepare": "yarn build", + "test": "xo && c8 ava --serial", + "test:ci": "xo && ava --serial", + "clean": "rm -rf node_modules && rm -rf ./coverage && rm -rf ./test/testdb.sqlite" + }, + "xo": { + "rules": { + "unicorn/prefer-module": 0, + "unicorn/prefer-node-protocol": 0, + "@typescript-eslint/consistent-type-definitions": 0, + "unicorn/no-typeof-undefined": 0, + "unicorn/prefer-event-target": 0 + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jaredwray/keyv.git" + }, + "keywords": [ + "key", + "value", + "store", + "cache", + "ttl" + ], + "author": "Jared Wray (http://jaredwray.com)", + "license": "MIT", + "bugs": { + "url": "https://github.com/jaredwray/keyv/issues" + }, + "homepage": "https://github.com/jaredwray/keyv", + "dependencies": { + "json-buffer": "3.0.1" + }, + "devDependencies": { + "@keyv/test-suite": "*", + "eslint": "^8.51.0", + "eslint-plugin-promise": "^6.1.1", + "pify": "^5.0.0", + "timekeeper": "^2.3.1", + "tsd": "^0.29.0" + }, + "tsd": { + "directory": "test" + }, + "types": "./src/index.d.ts", + "files": [ + "src" + ] +} diff --git a/node_modules/keyv/src/index.d.ts b/node_modules/keyv/src/index.d.ts new file mode 100644 index 00000000..77d81ca5 --- /dev/null +++ b/node_modules/keyv/src/index.d.ts @@ -0,0 +1,112 @@ +import {EventEmitter} from 'events'; + +type WithRequiredProperties = T & Required>; + +declare class Keyv = Record> extends EventEmitter { + /** + * `this.opts` is an object containing at least the properties listed + * below. However, `Keyv.Options` allows arbitrary properties as well. + * These properties can be specified as the second type parameter to `Keyv`. + */ + opts: WithRequiredProperties< + Keyv.Options, + 'deserialize' | 'namespace' | 'serialize' | 'store' | 'uri' + > & + Options; + + /** + * @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. + */ + constructor(options?: Keyv.Options & Options); + /** + * @param uri The connection string URI. + * + * Merged into the options object as options.uri. + * @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. + */ + constructor(uri?: string, options?: Keyv.Options & Options); + + /** Returns the value. */ + get(key: string, options?: {raw?: false}): Promise; + /** Returns the raw value. */ + get(key: string, options: {raw: true}): Promise | undefined>; + + /** Returns an array of values. Uses `store.getMany` if it exists, otherwise uses parallel calls to `store.get`. */ + get(key: string[], options?: {raw?: false}): Promise>; + /** Returns an array of raw values. Uses `store.getMany` if it exists, otherwise uses parallel calls to `store.get`. */ + get(key: string[], options: {raw: true}): Promise | undefined>>; + + /** + * Set a value. + * + * By default keys are persistent. You can set an expiry TTL in milliseconds. + */ + set(key: string, value: Value, ttl?: number): Promise; + /** + * Deletes an entry. + * + * Returns `true` if the key existed, `false` if not. + */ + delete(key: string | string[]): Promise; + /** Delete all entries in the current namespace. */ + clear(): Promise; + /** Check if key exists in current namespace. */ + has(key: string): Promise; + /** Iterator */ + iterator(namespace?: string): AsyncGenerator; + /** + * Closes the connection. + * + * Returns `undefined` when the connection closes. + */ + disconnect(): Promise; +} + +declare namespace Keyv { + interface Options { + [key: string]: any; + + /** Namespace for the current instance. */ + namespace?: string | undefined; + /** A custom serialization function. */ + serialize?: ((data: DeserializedData) => string) | undefined; + /** A custom deserialization function. */ + deserialize?: ((data: string) => DeserializedData | undefined) | undefined; + /** The connection string URI. */ + uri?: string | undefined; + /** The storage adapter instance to be used by Keyv. */ + store?: Store | undefined; + /** Default TTL. Can be overridden by specififying a TTL on `.set()`. */ + ttl?: number | undefined; + /** Specify an adapter to use. e.g `'redis'` or `'mongodb'`. */ + adapter?: 'redis' | 'mongodb' | 'mongo' | 'sqlite' | 'postgresql' | 'postgres' | 'mysql' | undefined; + /** Enable compression option **/ + compression?: CompressionAdapter | undefined; + } + + interface CompressionAdapter { + compress(value: any, options?: any): Promise; + decompress(value: any, options?: any): Promise; + serialize(value: any): Promise; + deserialize(value: any): Promise; + } + + interface DeserializedData { + value: Value; expires: number | undefined; + } + + type StoredData = DeserializedData | string | undefined; + + interface Store { + get(key: string): Value | Promise | undefined; + set(key: string, value: Value, ttl?: number): any; + delete(key: string): boolean | Promise; + clear(): void | Promise; + has?(key: string): boolean | Promise; + getMany?( + keys: string[] + ): Array> | Promise>> | undefined; + } +} + +export = Keyv; diff --git a/node_modules/keyv/src/index.js b/node_modules/keyv/src/index.js new file mode 100644 index 00000000..ac539bd9 --- /dev/null +++ b/node_modules/keyv/src/index.js @@ -0,0 +1,259 @@ +'use strict'; + +const EventEmitter = require('events'); +const JSONB = require('json-buffer'); + +const loadStore = options => { + const adapters = { + redis: '@keyv/redis', + rediss: '@keyv/redis', + mongodb: '@keyv/mongo', + mongo: '@keyv/mongo', + sqlite: '@keyv/sqlite', + postgresql: '@keyv/postgres', + postgres: '@keyv/postgres', + mysql: '@keyv/mysql', + etcd: '@keyv/etcd', + offline: '@keyv/offline', + tiered: '@keyv/tiered', + }; + if (options.adapter || options.uri) { + const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0]; + return new (require(adapters[adapter]))(options); + } + + return new Map(); +}; + +const iterableAdapters = [ + 'sqlite', + 'postgres', + 'mysql', + 'mongo', + 'redis', + 'tiered', +]; + +class Keyv extends EventEmitter { + constructor(uri, {emitErrors = true, ...options} = {}) { + super(); + this.opts = { + namespace: 'keyv', + serialize: JSONB.stringify, + deserialize: JSONB.parse, + ...((typeof uri === 'string') ? {uri} : uri), + ...options, + }; + + if (!this.opts.store) { + const adapterOptions = {...this.opts}; + this.opts.store = loadStore(adapterOptions); + } + + if (this.opts.compression) { + const compression = this.opts.compression; + this.opts.serialize = compression.serialize.bind(compression); + this.opts.deserialize = compression.deserialize.bind(compression); + } + + if (typeof this.opts.store.on === 'function' && emitErrors) { + this.opts.store.on('error', error => this.emit('error', error)); + } + + this.opts.store.namespace = this.opts.namespace; + + const generateIterator = iterator => async function * () { + for await (const [key, raw] of typeof iterator === 'function' + ? iterator(this.opts.store.namespace) + : iterator) { + const data = await this.opts.deserialize(raw); + if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) { + continue; + } + + if (typeof data.expires === 'number' && Date.now() > data.expires) { + this.delete(key); + continue; + } + + yield [this._getKeyUnprefix(key), data.value]; + } + }; + + // Attach iterators + if (typeof this.opts.store[Symbol.iterator] === 'function' && this.opts.store instanceof Map) { + this.iterator = generateIterator(this.opts.store); + } else if (typeof this.opts.store.iterator === 'function' && this.opts.store.opts + && this._checkIterableAdaptar()) { + this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store)); + } + } + + _checkIterableAdaptar() { + return iterableAdapters.includes(this.opts.store.opts.dialect) + || iterableAdapters.findIndex(element => this.opts.store.opts.url.includes(element)) >= 0; + } + + _getKeyPrefix(key) { + return `${this.opts.namespace}:${key}`; + } + + _getKeyPrefixArray(keys) { + return keys.map(key => `${this.opts.namespace}:${key}`); + } + + _getKeyUnprefix(key) { + return key + .split(':') + .splice(1) + .join(':'); + } + + get(key, options) { + const {store} = this.opts; + const isArray = Array.isArray(key); + const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key); + if (isArray && store.getMany === undefined) { + const promises = []; + for (const key of keyPrefixed) { + promises.push(Promise.resolve() + .then(() => store.get(key)) + .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) + .then(data => { + if (data === undefined || data === null) { + return undefined; + } + + if (typeof data.expires === 'number' && Date.now() > data.expires) { + return this.delete(key).then(() => undefined); + } + + return (options && options.raw) ? data : data.value; + }), + ); + } + + return Promise.allSettled(promises) + .then(values => { + const data = []; + for (const value of values) { + data.push(value.value); + } + + return data; + }); + } + + return Promise.resolve() + .then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)) + .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) + .then(data => { + if (data === undefined || data === null) { + return undefined; + } + + if (isArray) { + return data.map((row, index) => { + if ((typeof row === 'string')) { + row = this.opts.deserialize(row); + } + + if (row === undefined || row === null) { + return undefined; + } + + if (typeof row.expires === 'number' && Date.now() > row.expires) { + this.delete(key[index]).then(() => undefined); + return undefined; + } + + return (options && options.raw) ? row : row.value; + }); + } + + if (typeof data.expires === 'number' && Date.now() > data.expires) { + return this.delete(key).then(() => undefined); + } + + return (options && options.raw) ? data : data.value; + }); + } + + set(key, value, ttl) { + const keyPrefixed = this._getKeyPrefix(key); + if (typeof ttl === 'undefined') { + ttl = this.opts.ttl; + } + + if (ttl === 0) { + ttl = undefined; + } + + const {store} = this.opts; + + return Promise.resolve() + .then(() => { + const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null; + if (typeof value === 'symbol') { + this.emit('error', 'symbol cannot be serialized'); + } + + value = {value, expires}; + return this.opts.serialize(value); + }) + .then(value => store.set(keyPrefixed, value, ttl)) + .then(() => true); + } + + delete(key) { + const {store} = this.opts; + if (Array.isArray(key)) { + const keyPrefixed = this._getKeyPrefixArray(key); + if (store.deleteMany === undefined) { + const promises = []; + for (const key of keyPrefixed) { + promises.push(store.delete(key)); + } + + return Promise.allSettled(promises) + .then(values => values.every(x => x.value === true)); + } + + return Promise.resolve() + .then(() => store.deleteMany(keyPrefixed)); + } + + const keyPrefixed = this._getKeyPrefix(key); + return Promise.resolve() + .then(() => store.delete(keyPrefixed)); + } + + clear() { + const {store} = this.opts; + return Promise.resolve() + .then(() => store.clear()); + } + + has(key) { + const keyPrefixed = this._getKeyPrefix(key); + const {store} = this.opts; + return Promise.resolve() + .then(async () => { + if (typeof store.has === 'function') { + return store.has(keyPrefixed); + } + + const value = await store.get(keyPrefixed); + return value !== undefined; + }); + } + + disconnect() { + const {store} = this.opts; + if (typeof store.disconnect === 'function') { + return store.disconnect(); + } + } +} + +module.exports = Keyv; diff --git a/node_modules/launchdarkly-js-client-sdk/LICENSE.txt b/node_modules/launchdarkly-js-client-sdk/LICENSE.txt new file mode 100644 index 00000000..e82de54e --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/LICENSE.txt @@ -0,0 +1,13 @@ +Copyright 2016 Catamorphic, Co. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/node_modules/launchdarkly-js-client-sdk/README.md b/node_modules/launchdarkly-js-client-sdk/README.md new file mode 100644 index 00000000..8baaea27 --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/README.md @@ -0,0 +1,57 @@ +# LaunchDarkly SDK for Browser JavaScript + +[![Build and Test](https://github.com/launchdarkly/js-client-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/launchdarkly/js-client-sdk/actions/workflows/ci.yml) + +## LaunchDarkly overview + +[LaunchDarkly](https://www.launchdarkly.com) is a feature management platform that serves trillions of feature flags daily to help teams build better software, faster. [Get started](https://docs.launchdarkly.com/home/getting-started) using LaunchDarkly today! + +[![Twitter Follow](https://img.shields.io/twitter/follow/launchdarkly.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/intent/follow?screen_name=launchdarkly) + +## Getting started + +Refer to the [SDK documentation](https://docs.launchdarkly.com/sdk/client-side/javascript#getting-started) for instructions on getting started with using the SDK. + +Note: _If you are using JavaScript in a non-browser environment,_ please see our [server-side Node.js SDK](https://github.com/launchdarkly/node-server-sdk), [client-side Node.js SDK](https://github.com/launchdarkly/node-client-sdk), and [Electron SDK](https://github.com/launchdarkly/electron-client-sdk). + +Please note that the JavaScript SDK has two special requirements in terms of your LaunchDarkly environment. First, in terms of the credentials for your environment that appear on your [Account Settings](https://app.launchdarkly.com/settings/projects) dashboard, the JavaScript SDK uses the "Client-side ID"-- not the "SDK key" or the "Mobile key". Second, for any feature flag that you will be using in JavaScript code, you must check the "Make this flag available to client-side SDKs" box on that flag's Settings page. + +## ReactJS + +The SDK does not require any particular JavaScript framework. However, if you are using [React](https://reactjs.org/), there is an add-on to simplify use of the SDK. See [`react-client-sdk`](https://github.com/launchdarkly/react-client-sdk). + +## Browser compatibility + +The LaunchDarkly SDK can be used in all major browsers. However, web browsers vary widely in their support of specific features and standards. Three features that are used by the LaunchDarkly SDK that may not be available on every browser are `Promise`, `EventSource`, and `document.querySelectorAll()`. For more information on whether you may need to use a polyfill to ensure compatibility, and how to do so, see ["JS SDK requirements and polyfills"](https://docs.launchdarkly.com/sdk/client-side/javascript/requirements-polyfills). + +## Logging + +By default, the SDK sends log output to the browser console. There are four logging levels: `debug`, `info`, `warn`, and `error`; by default, `debug` and `info` messages are hidden. See [`LDOptions.logger`](https://launchdarkly.github.io/js-client-sdk/interfaces/LDOptions.html#logger) and [`basicLogger`](https://launchdarkly.github.io/js-client-sdk/functions/basicLogger.html) for more details. + +## Learn more + +Read our [documentation](https://docs.launchdarkly.com) for in-depth instructions on configuring and using LaunchDarkly. You can also head straight to the [complete reference guide for this SDK](https://docs.launchdarkly.com/sdk/client-side/javascript). Additionally, the authoritative full description of all properties, types, and methods is the [online TypeScript documentation](https://launchdarkly.github.io/js-client-sdk/). If you are not using TypeScript, then the types are only for your information and are not enforced, although the properties and methods are still the same as described in the documentation. + +For examples of using the SDK in a simple JavaScript application, see [`hello-js`](https://github.com/launchdarkly/hello-js) and [`hello-bootstrap`](https://github.com/launchdarkly/hello-bootstrap). + +## Testing + +We run integration tests for all our SDKs using a centralized test harness. This approach gives us the ability to test for consistency across SDKs, as well as test networking behavior in a long-running application. These tests cover each method in the SDK, and verify that event sending, flag evaluation, stream reconnection, and other aspects of the SDK all behave correctly. + +## Contributing + +We encourage pull requests and other contributions from the community. Check out our [contributing guidelines](CONTRIBUTING.md) for instructions on how to contribute to this SDK. + +## About LaunchDarkly + +* LaunchDarkly is a continuous delivery platform that provides feature flags as a service and allows developers to iterate quickly and safely. We allow you to easily flag your features and manage them from the LaunchDarkly dashboard. With LaunchDarkly, you can: + * Roll out a new feature to a subset of your users (like a group of users who opt-in to a beta tester group), gathering feedback and bug reports from real-world use cases. + * Gradually roll out a feature to an increasing percentage of users, and track the effect that the feature has on key metrics (for instance, how likely is a user to complete a purchase if they have feature A versus feature B?). + * Turn off a feature that you realize is causing performance problems in production, without needing to re-deploy, or even restart the application with a changed configuration file. + * Grant access to certain features based on user attributes, like payment plan (eg: users on the ‘gold’ plan get access to more features than users in the ‘silver’ plan). Disable parts of your application to facilitate maintenance, without taking everything offline. +* LaunchDarkly provides feature flag SDKs for a wide variety of languages and technologies. Check out [our documentation](https://docs.launchdarkly.com/sdk) for a complete list. +* Explore LaunchDarkly + * [launchdarkly.com](https://www.launchdarkly.com/ "LaunchDarkly Main Website") for more information + * [docs.launchdarkly.com](https://docs.launchdarkly.com/ "LaunchDarkly Documentation") for our documentation and SDK reference guides + * [apidocs.launchdarkly.com](https://apidocs.launchdarkly.com/ "LaunchDarkly API Documentation") for our API documentation + * [blog.launchdarkly.com](https://blog.launchdarkly.com/ "LaunchDarkly Blog Documentation") for the latest product updates diff --git a/node_modules/launchdarkly-js-client-sdk/dist/ldclient.cjs.js b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.cjs.js new file mode 100644 index 00000000..c8c7de9d --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.cjs.js @@ -0,0 +1,2 @@ +"use strict";function e(e){function t(e,t){Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.message=e,this.code=t}return t.prototype=new Error,t.prototype.name=e,t.prototype.constructor=t,t}Object.defineProperty(exports,"__esModule",{value:!0});const t=e("LaunchDarklyUnexpectedResponseError"),n=e("LaunchDarklyInvalidEnvironmentIdError"),r=e("LaunchDarklyInvalidUserError"),o=e("LaunchDarklyInvalidEventKeyError"),i=e("LaunchDarklyInvalidArgumentError"),a=e("LaunchDarklyFlagFetchError");for(var s={LDUnexpectedResponseError:t,LDInvalidEnvironmentIdError:n,LDInvalidUserError:r,LDInvalidEventKeyError:o,LDInvalidArgumentError:i,LDInvalidDataError:e("LaunchDarklyInvalidDataError"),LDFlagFetchError:a,LDTimeoutError:e("LaunchDarklyTimeoutError"),isHttpErrorRecoverable:function(e){return!(e>=400&&e<500)||(400===e||408===e||429===e)}},c=function(e){var t=m(e),n=t[0],r=t[1];return 3*(n+r)/4-r},u=function(e){var t,n,r=m(e),o=r[0],i=r[1],a=new g(function(e,t,n){return 3*(t+n)/4-n}(0,o,i)),s=0,c=i>0?o-4:o;for(n=0;n>16&255,a[s++]=t>>8&255,a[s++]=255&t;2===i&&(t=f[e.charCodeAt(n)]<<2|f[e.charCodeAt(n+1)]>>4,a[s++]=255&t);1===i&&(t=f[e.charCodeAt(n)]<<10|f[e.charCodeAt(n+1)]<<4|f[e.charCodeAt(n+2)]>>2,a[s++]=t>>8&255,a[s++]=255&t);return a},l=function(e){for(var t,n=e.length,r=n%3,o=[],i=16383,a=0,s=n-r;as?s:a+i));1===r?(t=e[n-1],o.push(d[t>>2]+d[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],o.push(d[t>>10]+d[t>>4&63]+d[t<<2&63]+"="));return o.join("")},d=[],f=[],g="undefined"!=typeof Uint8Array?Uint8Array:Array,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0;p<64;++p)d[p]=v[p],f[v.charCodeAt(p)]=p;function m(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function h(e,t,n){for(var r,o,i=[],a=t;a>18&63]+d[o>>12&63]+d[o>>6&63]+d[63&o]);return i.join("")}f["-".charCodeAt(0)]=62,f["_".charCodeAt(0)]=63;var y={byteLength:c,toByteArray:u,fromByteArray:l},w=Array.isArray,b=Object.keys,k=Object.prototype.hasOwnProperty,E=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){var r,o,i,a=w(t),s=w(n);if(a&&s){if((o=t.length)!=n.length)return!1;for(r=o;0!==r--;)if(!e(t[r],n[r]))return!1;return!0}if(a!=s)return!1;var c=t instanceof Date,u=n instanceof Date;if(c!=u)return!1;if(c&&u)return t.getTime()==n.getTime();var l=t instanceof RegExp,d=n instanceof RegExp;if(l!=d)return!1;if(l&&d)return t.toString()==n.toString();var f=b(t);if((o=f.length)!==b(n).length)return!1;for(r=o;0!==r--;)if(!k.call(n,f[r]))return!1;for(r=o;0!==r--;)if(!e(t[i=f[r]],n[i]))return!1;return!0}return t!=t&&n!=n};const D=["key","ip","country","email","firstName","lastName","avatar","name"];function x(e){const t=unescape(encodeURIComponent(e));return y.fromByteArray(function(e){const t=[];for(let n=0;n({...e,...t})),{})},getLDUserAgentString:function(e){const t=e.version||"?";return e.userAgent+"/"+t},objectHasOwnProperty:C,onNextTick:function(e){setTimeout(e,0)},sanitizeContext:function(e){if(!e)return e;let t;return null!==e.kind&&void 0!==e.kind||D.forEach((n=>{const r=e[n];void 0!==r&&"string"!=typeof r&&(t=t||{...e},t[n]=String(r))})),t||e},transformValuesToVersionedValues:function(e){const t={};for(const n in e)C(e,n)&&(t[n]={value:e[n],version:0});return t},transformVersionedValuesToValues:function(e){const t={};for(const n in e)C(e,n)&&(t[n]=e[n].value);return t},wrapPromiseCallback:function(e,t){const n=e.then((e=>(t&&setTimeout((()=>{t(null,e)}),0),e)),(e=>{if(!t)return Promise.reject(e);setTimeout((()=>{t(e,null)}),0)}));return t?void 0:n},once:function(e){let t,n=!1;return function(...r){return n||(n=!0,t=e.apply(this,r)),t}}},I=new Uint8Array(16);function O(){if(!P&&!(P="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return P(I)}var T=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function L(e){return"string"==typeof e&&T.test(e)}for(var U,A,j=[],R=0;R<256;++R)j.push((R+256).toString(16).substr(1));function F(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(j[e[t+0]]+j[e[t+1]]+j[e[t+2]]+j[e[t+3]]+"-"+j[e[t+4]]+j[e[t+5]]+"-"+j[e[t+6]]+j[e[t+7]]+"-"+j[e[t+8]]+j[e[t+9]]+"-"+j[e[t+10]]+j[e[t+11]]+j[e[t+12]]+j[e[t+13]]+j[e[t+14]]+j[e[t+15]]).toLowerCase();if(!L(n))throw TypeError("Stringified UUID is invalid");return n}var N=0,$=0;function V(e){if(!L(e))throw TypeError("Invalid UUID");var t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=255&t,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=255&t,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=255&t,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=255&t,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=255&t,n}function H(e,t,n){function r(e,r,o,i){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n>>9<<4)+1}function q(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function z(e,t,n,r,o,i){return q((a=q(q(t,e),q(r,i)))<<(s=o)|a>>>32-s,n);var a,s}function K(e,t,n,r,o,i,a){return z(t&n|~t&r,e,t,o,i,a)}function _(e,t,n,r,o,i,a){return z(t&r|n&~r,e,t,o,i,a)}function J(e,t,n,r,o,i,a){return z(t^n^r,e,t,o,i,a)}function B(e,t,n,r,o,i,a){return z(n^(t|~r),e,t,o,i,a)}var G=H("v3",48,(function(e){if("string"==typeof e){var t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(var n=0;n>5]>>>o%32&255,a=parseInt(r.charAt(i>>>4&15)+r.charAt(15&i),16);t.push(a)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[r/8])<>>32-t}var Y=H("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var r=unescape(encodeURIComponent(e));e=[];for(var o=0;o>>0;w=y,y=h,h=Q(m,30)>>>0,m=p,p=E}n[0]=n[0]+p>>>0,n[1]=n[1]+m>>>0,n[2]=n[2]+h>>>0,n[3]=n[3]+y>>>0,n[4]=n[4]+w>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]})),Z=Y;var ee=Object.freeze({__proto__:null,v1:function(e,t,n){var r=t&&n||0,o=t||new Array(16),i=(e=e||{}).node||U,a=void 0!==e.clockseq?e.clockseq:A;if(null==i||null==a){var s=e.random||(e.rng||O)();null==i&&(i=U=[1|s[0],s[1],s[2],s[3],s[4],s[5]]),null==a&&(a=A=16383&(s[6]<<8|s[7]))}var c=void 0!==e.msecs?e.msecs:Date.now(),u=void 0!==e.nsecs?e.nsecs:$+1,l=c-N+(u-$)/1e4;if(l<0&&void 0===e.clockseq&&(a=a+1&16383),(l<0||c>N)&&void 0===e.nsecs&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");N=c,$=u,A=a;var d=(1e4*(268435455&(c+=122192928e5))+u)%4294967296;o[r++]=d>>>24&255,o[r++]=d>>>16&255,o[r++]=d>>>8&255,o[r++]=255&d;var f=c/4294967296*1e4&268435455;o[r++]=f>>>8&255,o[r++]=255&f,o[r++]=f>>>24&15|16,o[r++]=f>>>16&255,o[r++]=a>>>8|128,o[r++]=255&a;for(var g=0;g<6;++g)o[r+g]=i[g];return t||F(o)},v3:W,v4:function(e,t,n){var r=(e=e||{}).random||(e.rng||O)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(var o=0;o<16;++o)t[n+o]=r[o];return t}return F(r)},v5:Z,NIL:"00000000-0000-0000-0000-000000000000",version:function(e){if(!L(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)},validate:L,stringify:F,parse:V});const te=["debug","info","warn","error","none"];var ne={commonBasicLogger:function(e,t){if(e&&e.destination&&"function"!=typeof e.destination)throw new Error("destination for basicLogger was set to a non-function");function n(e){return function(t){console&&console[e]&&console[e].call(console,t)}}const r=e&&e.destination?[e.destination,e.destination,e.destination,e.destination]:[n("log"),n("info"),n("warn"),n("error")],o=!(!e||!e.destination),i=e&&void 0!==e.prefix&&null!==e.prefix?e.prefix:"[LaunchDarkly] ";let a=1;if(e&&e.level)for(let t=0;t{};else{const n=e;c[t]=function(){s(n,t,arguments)}}}return c},validateLogger:function(e){te.forEach((t=>{if("none"!==t&&(!e[t]||"function"!=typeof e[t]))throw new Error("Provided logger instance must support logger."+t+"(...) method")}))}};function re(e){return e&&e.message?e.message:"string"==typeof e||e instanceof String?e:JSON.stringify(e)}const oe=" Please see https://docs.launchdarkly.com/sdk/client-side/javascript#initialize-the-client for instructions on SDK initialization.";var ie={bootstrapInvalid:function(){return"LaunchDarkly bootstrap data is not available because the back end could not read the flags."},bootstrapOldFormat:function(){return"LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."+oe},clientInitialized:function(){return"LaunchDarkly client initialized"},clientNotReady:function(){return"LaunchDarkly client is not ready"},debugEnqueueingEvent:function(e){return'enqueueing "'+e+'" event'},debugPostingDiagnosticEvent:function(e){return"sending diagnostic event ("+e.kind+")"},debugPostingEvents:function(e){return"sending "+e+" events"},debugStreamDelete:function(e){return'received streaming deletion for flag "'+e+'"'},debugStreamDeleteIgnored:function(e){return'received streaming deletion for flag "'+e+'" but ignored due to version check'},debugStreamPatch:function(e){return'received streaming update for flag "'+e+'"'},debugStreamPatchIgnored:function(e){return'received streaming update for flag "'+e+'" but ignored due to version check'},debugStreamPing:function(){return"received ping message from stream"},debugPolling:function(e){return"polling for feature flags at "+e},debugStreamPut:function(){return"received streaming update for all flags"},deprecated:function(e,t){return t?'"'+e+'" is deprecated, please use "'+t+'"':'"'+e+'" is deprecated'},environmentNotFound:function(){return"Environment not found. Double check that you specified a valid environment/client-side ID."+oe},environmentNotSpecified:function(){return"No environment/client-side ID was specified."+oe},errorFetchingFlags:function(e){return"Error fetching flag settings: "+re(e)},eventCapacityExceeded:function(){return"Exceeded event queue capacity. Increase capacity to avoid dropping events."},eventWithoutContext:function(){return"Be sure to call `identify` in the LaunchDarkly client: https://docs.launchdarkly.com/sdk/features/identify#javascript"},httpErrorMessage:function(e,t,n){return"Received error "+e+(401===e?" (invalid SDK key)":"")+" for "+t+" - "+(s.isHttpErrorRecoverable(e)?n:"giving up permanently")},httpUnavailable:function(){return"Cannot make HTTP requests in this environment."+oe},identifyDisabled:function(){return"identify() has no effect here; it must be called on the main client instance"},inspectorMethodError:(e,t)=>`an inspector: "${t}" of type: "${e}" generated an exception`,invalidContentType:function(e){return'Expected application/json content type but got "'+e+'"'},invalidData:function(){return"Invalid data received from LaunchDarkly; connection may have been interrupted"},invalidInspector:(e,t)=>`an inspector: "${t}" of an invalid type (${e}) was configured`,invalidKey:function(){return"Event key must be a string"},invalidMetricValue:e=>`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`,invalidContext:function(){return"Invalid context specified."+oe},invalidTagValue:e=>`Config option "${e}" must only contain letters, numbers, ., _ or -.`,localStorageUnavailable:function(e){return"local storage is unavailable: "+re(e)},networkError:e=>"network error"+(e?" ("+e+")":""),optionBelowMinimum:(e,t,n)=>'Config option "'+e+'" was set to '+t+", changing to minimum value of "+n,streamClosing:function(){return"Closing stream connection"},streamConnecting:function(e){return"Opening stream connection to "+e},streamError:function(e,t){return"Error on stream connection: "+re(e)+", will continue retrying after "+t+" milliseconds."},tagValueTooLong:e=>`Value of "${e}" was longer than 64 characters and was discarded.`,unknownCustomEventKey:function(e){return'Custom event "'+e+'" does not exist'},unknownOption:e=>'Ignoring unknown config option "'+e+'"',contextNotSpecified:function(){return"No context specified."+oe},unrecoverableStreamError:e=>`Error on stream connection ${re(e)}, giving up permanently`,wrongOptionType:(e,t,n)=>'Config option "'+e+'" should be of type '+t+", got "+n+", using default value",wrongOptionTypeBoolean:(e,t)=>'Config option "'+e+'" should be a boolean, got '+t+", converting to boolean"};const{validateLogger:ae}=ne,se={baseUrl:{default:"https://app.launchdarkly.com"},streamUrl:{default:"https://clientstream.launchdarkly.com"},eventsUrl:{default:"https://events.launchdarkly.com"},sendEvents:{default:!0},streaming:{type:"boolean"},sendLDHeaders:{default:!0},requestHeaderTransform:{type:"function"},sendEventsOnlyForVariation:{default:!1},useReport:{default:!1},evaluationReasons:{default:!1},eventCapacity:{default:100,minimum:1},flushInterval:{default:2e3,minimum:2e3},samplingInterval:{default:0,minimum:0},streamReconnectDelay:{default:1e3,minimum:0},allAttributesPrivate:{default:!1},privateAttributes:{default:[]},bootstrap:{type:"string|object"},diagnosticRecordingInterval:{default:9e5,minimum:2e3},diagnosticOptOut:{default:!1},wrapperName:{type:"string"},wrapperVersion:{type:"string"},stateProvider:{type:"object"},application:{validator:function(e,t,n){const r={};t.id&&(r.id=le(`${e}.id`,t.id,n));t.version&&(r.version=le(`${e}.version`,t.version,n));return r}},inspectors:{default:[]},hooks:{default:[]},plugins:{default:[]}},ce=/^(\w|\.|-)+$/;function ue(e){return e&&e.replace(/\/+$/,"")}function le(e,t,n){if("string"==typeof t&&t.match(ce)){if(!(t.length>64))return t;n.warn(ie.tagValueTooLong(e))}else n.warn(ie.invalidTagValue(e))}var de={baseOptionDefs:se,validate:function(e,t,n,r){const o=S.extend({logger:{default:r}},se,n),i={};function a(e){S.onNextTick((()=>{t&&t.maybeReportError(new s.LDInvalidArgumentError(e))}))}let c=S.extend({},e||{});return function(e){const t=e;Object.keys(i).forEach((e=>{if(void 0!==t[e]){const n=i[e];r&&r.warn(ie.deprecated(e,n)),n&&(void 0===t[n]&&(t[n]=t[e]),delete t[e])}}))}(c),c=function(e){const t=S.extend({},e);return Object.keys(o).forEach((e=>{void 0!==t[e]&&null!==t[e]||(t[e]=o[e]&&o[e].default)})),t}(c),c=function(e){const t=S.extend({},e),n=e=>{if(null===e)return"any";if(void 0===e)return;if(Array.isArray(e))return"array";const t=typeof e;return"boolean"===t||"string"===t||"number"===t||"function"===t?t:"object"};return Object.keys(e).forEach((i=>{const s=e[i];if(null!=s){const c=o[i];if(void 0===c)a(ie.unknownOption(i));else{const o=c.type||n(c.default),u=c.validator;if(u){const n=u(i,e[i],r);void 0!==n?t[i]=n:delete t[i]}else if("any"!==o){const e=o.split("|"),r=n(s);e.indexOf(r)<0?"boolean"===o?(t[i]=!!s,a(ie.wrongOptionTypeBoolean(i,r))):(a(ie.wrongOptionType(i,o,r)),t[i]=c.default):"number"===r&&void 0!==c.minimum&&sArray.isArray(r[e])?r[e].sort().map((t=>`${e}/${t}`)):[`${e}/${r[e]}`])).reduce(((e,t)=>e.concat(t)),[]).join(" ")),n},transformHeaders:function(e,t){return t&&t.requestHeaderTransform?t.requestHeaderTransform({...e}):e}};const{v1:ve}=ee,{getLDHeaders:pe,transformHeaders:me}=ge;var he=function(e,t,n){const r=S.extend({"Content-Type":"application/json"},pe(e,n)),o={};return o.sendEvents=(t,o,i)=>{if(!e.httpRequest)return Promise.resolve();const a=JSON.stringify(t),c=i?null:ve();return function t(u){const l=i?r:S.extend({},r,{"X-LaunchDarkly-Event-Schema":"4","X-LaunchDarkly-Payload-ID":c});return e.httpRequest("POST",o,me(l,n),a).promise.then((e=>{if(e)return e.status>=400&&s.isHttpErrorRecoverable(e.status)&&u?t(!1):function(e){const t={status:e.status},n=e.header("date");if(n){const e=Date.parse(n);e&&(t.serverTime=e)}return t}(e)})).catch((()=>u?t(!1):Promise.reject()))}(!0).catch((()=>{}))},o};var ye=function e(t,n=[]){if(null===t||"object"!=typeof t)return JSON.stringify(t);if(n.includes(t))throw new Error("Cycle detected");if(Array.isArray(t)){return`[${t.map((r=>e(r,[...n,t]))).map((e=>void 0===e?"null":e)).join(",")}]`}return`{${Object.keys(t).sort().map((r=>{const o=e(t[r],[...n,t]);if(void 0!==o)return`${JSON.stringify(r)}:${o}`})).filter((e=>void 0!==e)).join(",")}}`};const{commonBasicLogger:we}=ne;function be(e){return"string"==typeof e&&"kind"!==e&&e.match(/^(\w|\.|-)+$/)}function ke(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}var Ee={checkContext:function(e,t){if(e){if(t&&(void 0===e.kind||null===e.kind))return void 0!==e.key&&null!==e.key;const n=e.key,r=void 0===e.kind?"user":e.kind,o=be(r),i="multi"===r||null!=n&&""!==n;if("multi"===r){const t=Object.keys(e).filter((e=>"kind"!==e));return i&&t.every((e=>be(e)))&&t.every((t=>{const n=e[t].key;return null!=n&&""!==n}))}return i&&o}return!1},getContextKeys:function(e,t=we()){if(!e)return;const n={},{kind:r,key:o}=e;switch(r){case void 0:n.user=`${o}`;break;case"multi":Object.entries(e).filter((([e])=>"kind"!==e)).forEach((([e,t])=>{t&&t.key&&(n[e]=t.key)}));break;case null:t.warn(`null is not a valid context kind: ${e}`);break;case"":t.warn(`'' is not a valid context kind: ${e}`);break;default:n[r]=`${o}`}return n},getContextKinds:function(e){return e?null===e.kind||void 0===e.kind?["user"]:"multi"!==e.kind?[e.kind]:Object.keys(e).filter((e=>"kind"!==e)):[]},getCanonicalKey:function(e){if(e){if((void 0===e.kind||null===e.kind||"user"===e.kind)&&e.key)return e.key;if("multi"!==e.kind&&e.key)return`${e.kind}:${ke(e.key)}`;if("multi"===e.kind)return Object.keys(e).sort().filter((e=>"kind"!==e)).map((t=>`${t}:${ke(e[t].key)}`)).join(":")}}};const{getContextKinds:De}=Ee;var xe=function(){const e={};let t=0,n=0,r={},o={};return e.summarizeEvent=e=>{if("feature"===e.kind){const i=e.key+":"+(null!==e.variation&&void 0!==e.variation?e.variation:"")+":"+(null!==e.version&&void 0!==e.version?e.version:""),a=r[i];let s=o[e.key];s||(s=new Set,o[e.key]=s),function(e){return e.context?De(e.context):e.contextKeys?Object.keys(e.contextKeys):[]}(e).forEach((e=>s.add(e))),a?a.count=a.count+1:r[i]={count:1,key:e.key,version:e.version,variation:e.variation,value:e.value,default:e.default},(0===t||e.creationDaten&&(n=e.creationDate)}},e.getSummary=()=>{const e={};let i=!0;for(const t of Object.values(r)){let n=e[t.key];n||(n={default:t.default,counters:[],contextKinds:[...o[t.key]]},e[t.key]=n);const r={value:t.value,count:t.count};void 0!==t.variation&&null!==t.variation&&(r.variation=t.variation),void 0!==t.version&&null!==t.version?r.version=t.version:r.unknown=!0,n.counters.push(r),i=!1}return i?null:{startDate:t,endDate:n,features:e,kind:"summary"}},e.clearSummary=()=>{t=0,n=0,r={},o={}},e};var Ce=function(e){let t={},n={};return{summarizeEvent:function(e){if("feature"===e.kind){const r=ye(e.context);if(!r)return;let o=t[r];o||(t[r]=xe(),o=t[r],n[r]=e.context),o.summarizeEvent(e)}},getSummaries:function(){const r=t,o=n;return t={},n={},Object.entries(r).map((([t,n])=>{const r=n.getSummary();return r.context=e.filter(o[t]),r}))}}};function Pe(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Se(e){return(e.startsWith("/")?e.substring(1):e).split("/").map((e=>e.indexOf("~")>=0?e.replace(/~1/g,"/").replace(/~0/g,"~"):e))}function Ie(e){return!e.startsWith("/")}function Oe(e,t){const n=Ie(e),r=Ie(t);if(n&&r)return e===t;if(n){const n=Se(t);return 1===n.length&&e===n[0]}if(r){const n=Se(e);return 1===n.length&&t===n[0]}return e===t}function Te(e){return`/${Pe(e)}`}var Le={cloneExcluding:function(e,t){const n=[],r={},o=[];for(n.push(...Object.keys(e).map((t=>({key:t,ptr:Te(t),source:e,parent:r,visited:[e]}))));n.length;){const e=n.pop();if(t.some((t=>Oe(t,e.ptr))))o.push(e.ptr);else{const t=e.source[e.key];if(null===t)e.parent[e.key]=t;else if(Array.isArray(t))e.parent[e.key]=[...t];else if("object"==typeof t){if(e.visited.includes(t))continue;e.parent[e.key]={},n.push(...Object.keys(t).map((n=>{return{key:n,ptr:(r=e.ptr,o=Pe(n),`${r}/${o}`),source:t,parent:e.parent[e.key],visited:[...e.visited,t]};var r,o})))}else e.parent[e.key]=t}}return{cloned:r,excluded:o.sort()}},compare:Oe,literalToReference:Te};var Ue=function(e){const t={},n=e.allAttributesPrivate,r=e.privateAttributes||[],o=["key","kind","_meta","anonymous"],i=["name","ip","firstName","lastName","email","avatar","country"],a=(e,t)=>{if("object"!=typeof e||null===e||Array.isArray(e))return;const{cloned:i,excluded:a}=Le.cloneExcluding(e,((e,t)=>(n||t&&e.anonymous?Object.keys(e):[...r,...e._meta&&e._meta.privateAttributes||[]]).filter((e=>!o.some((t=>Le.compare(e,t))))))(e,t));return i.key=String(i.key),a.length&&(i._meta||(i._meta={}),i._meta.redactedAttributes=a),i._meta&&(delete i._meta.privateAttributes,0===Object.keys(i._meta).length&&delete i._meta),void 0!==i.anonymous&&(i.anonymous=!!i.anonymous),i};return t.filter=(e,t=!1)=>void 0===e.kind||null===e.kind?a((e=>{const t={...e.custom||{},kind:"user",key:e.key};void 0!==e.anonymous&&(t.anonymous=!!e.anonymous);for(const n of i)delete t[n],void 0!==e[n]&&null!==e[n]&&(t[n]=String(e[n]));return void 0!==e.privateAttributeNames&&null!==e.privateAttributeNames&&(t._meta=t._meta||{},t._meta.privateAttributes=e.privateAttributeNames.map((e=>e.startsWith("/")?Le.literalToReference(e):e))),t})(e),t):"multi"===e.kind?((e,t)=>{const n={kind:e.kind},r=Object.keys(e);for(const o of r)if("kind"!==o){const r=a(e[o],t);r&&(n[o]=r)}return n})(e,t):a(e,t),t};const{getContextKeys:Ae}=Ee;var je=function(e,t,n,r=null,o=null,i=null){const a={},c=i||he(e,n,t),u=S.appendUrlPath(t.eventsUrl,"/events/bulk/"+n),l=Ue(t),d=Ce(l),f=t.samplingInterval,g=t.eventCapacity,v=t.flushInterval,p=t.logger;let m,h=[],y=0,w=!1,b=!1;function k(){return 0===f||0===Math.floor(Math.random()*f)}function E(e){const t=S.extend({},e);return"identify"===e.kind||"feature"===e.kind||"custom"===e.kind?t.context=l.filter(e.context):(t.contextKeys=Ae(e.context,p),delete t.context),"feature"===e.kind&&(delete t.trackEvents,delete t.debugEventsUntilDate),t}function D(e){h.lengthy&&r.debugEventsUntilDate>(new Date).getTime()):t=k(),t&&D(E(e)),n){const t=S.extend({},e,{kind:"debug"});t.context=l.filter(t.context),delete t.trackEvents,delete t.debugEventsUntilDate,D(t)}},a.flush=async function(){if(w)return Promise.resolve();const e=h;return d.getSummaries().forEach((t=>{Object.keys(t.features).length&&e.push(t)})),r&&r.setEventsInLastBatch(e.length),0===e.length?Promise.resolve():(h=[],p.debug(ie.debugPostingEvents(e.length)),c.sendEvents(e,u).then((e=>{e&&(e.serverTime&&(y=e.serverTime),s.isHttpErrorRecoverable(e.status)||(w=!0),e.status>=400&&S.onNextTick((()=>{o.maybeReportError(new s.LDUnexpectedResponseError(ie.httpErrorMessage(e.status,"event posting","some events were dropped")))})))})))},a.start=function(){const e=()=>{a.flush(),m=setTimeout(e,v)};m=setTimeout(e,v)},a.stop=function(){clearTimeout(m)},a};var Re=function(e){const t={},n={};return t.on=function(e,t,r){n[e]=n[e]||[],n[e]=n[e].concat({handler:t,context:r})},t.off=function(e,t,r){if(n[e])for(let o=0;o{const n=()=>{e.off(Fe,n),t()};e.on(Fe,n)})).catch((()=>{}));return{getInitializationPromise:()=>o||(t?Promise.resolve():n?Promise.reject(r):(o=new Promise(((t,n)=>{const r=()=>{e.off(Ne,r),t()},o=t=>{e.off($e,o),n(t)};e.on(Ne,r),e.on($e,o)})),o)),getReadyPromise:()=>i,signalSuccess:()=>{t||n||(t=!0,e.emit(Ne),e.emit(Fe))},signalFailure:o=>{t||n||(n=!0,r=o,e.emit($e,o),e.emit(Fe)),e.maybeReportError(o)}}};var He=function(e,t,n,r){const o={};function i(){let e="";const o=r.getContext();return o&&(e=n||S.btoa(JSON.stringify(o))),"ld:"+t+":"+e}return o.loadFlags=()=>e.get(i()).then((e=>{if(null==e)return null;try{let t=JSON.parse(e);if(t){const e=t.$schema;void 0===e||e<1?t=S.transformValuesToVersionedValues(t):delete t.$schema}return t}catch(e){return o.clearFlags().then((()=>null))}})),o.saveFlags=t=>{const n=S.extend({},t,{$schema:1});return e.set(i(),JSON.stringify(n))},o.clearFlags=()=>e.clear(i()),o};var Me=function(e,t){const n={};let r=!1;const o=e=>{r||(r=!0,t.warn(ie.localStorageUnavailable(e)))};return n.isEnabled=()=>!!e,n.get=t=>new Promise((n=>{e?e.get(t).then(n).catch((e=>{o(e),n(void 0)})):n(void 0)})),n.set=(t,n)=>new Promise((r=>{e?e.set(t,n).then((()=>r(!0))).catch((e=>{o(e),r(!1)})):r(!1)})),n.clear=t=>new Promise((n=>{e?e.clear(t).then((()=>n(!0))).catch((e=>{o(e),n(!1)})):n(!1)})),n};const{appendUrlPath:qe,base64URLEncode:ze,objectHasOwnProperty:Ke}=S,{getLDHeaders:_e,transformHeaders:Je}=ge,{isHttpErrorRecoverable:Be}=s;var Ge=function(e,t,n,r){const o=t.streamUrl,i=t.logger,a={},s=qe(o,"/eval/"+n),c=t.useReport,u=t.evaluationReasons,l=t.streamReconnectDelay,d=_e(e,t);let f,g=!1,v=null,p=null,m=null,h=null,y=null,w=0;function b(){const e=(t=function(){const e=l*Math.pow(2,w);return e>3e4?3e4:e}(),t-Math.trunc(.5*Math.random()*t));var t;return w+=1,e}function k(e){if(e.status&&"number"==typeof e.status&&!Be(e.status))return x(),i.error(ie.unrecoverableStreamError(e)),void(p&&(clearTimeout(p),p=null));const t=b();g||(i.warn(ie.streamError(e,t)),g=!0),C(!1),x(),E(t)}function E(e){p||(e?p=setTimeout(D,e):D())}function D(){let r;p=null;let a="";const l={headers:d,readTimeoutMillis:3e5};if(e.eventSourceFactory){null!=h&&(a="h="+h),c?e.eventSourceAllowsReport?(r=s,l.method="REPORT",l.headers["Content-Type"]="application/json",l.body=JSON.stringify(m)):(r=qe(o,"/ping/"+n),a=""):r=s+"/"+ze(JSON.stringify(m)),l.headers=Je(l.headers,t),u&&(a=a+(a?"&":"")+"withReasons=true"),r=r+(a?"?":"")+a,x(),i.info(ie.streamConnecting(r)),f=(new Date).getTime(),v=e.eventSourceFactory(r,l);for(const e in y)Ke(y,e)&&v.addEventListener(e,y[e]);v.onerror=k,v.onopen=()=>{w=0}}}function x(){v&&(i.info(ie.streamClosing()),v.close(),v=null)}function C(e){f&&r&&r.recordStreamInit(f,!e,(new Date).getTime()-f),f=null}return a.connect=function(e,t,n){m=e,h=t,y={};for(const e in n||{})y[e]=function(t){g=!1,C(!0),n[e]&&n[e](t)};E()},a.disconnect=function(){clearTimeout(p),p=null,x()},a.isConnected=function(){return!!(v&&e.eventSourceIsActive&&e.eventSourceIsActive(v))},a};var We=function(e){let t,n,r,o;const i={addPromise:(i,a)=>{t=i,n&&n(),n=a,i.then((n=>{t===i&&(r(n),e&&e())}),(n=>{t===i&&(o(n),e&&e())}))}};return i.resultPromise=new Promise(((e,t)=>{r=e,o=t})),i};const{transformHeaders:Xe,getLDHeaders:Qe}=ge,Ye="application/json";var Ze=function(e,t,n){const r=t.baseUrl,o=t.useReport,i=t.evaluationReasons,a=t.logger,c={},u={};function l(n,r){if(!e.httpRequest)return new Promise(((e,t)=>{t(new s.LDFlagFetchError(ie.httpUnavailable()))}));const o=r?"REPORT":"GET",i=Qe(e,t);r&&(i["Content-Type"]=Ye);let a=u[n];a||(a=We((()=>{delete u[n]})),u[n]=a);const c=e.httpRequest(o,n,Xe(i,t),r),l=c.promise.then((e=>{if(200===e.status){if(e.header("content-type")&&e.header("content-type").substring(0,16)===Ye)return JSON.parse(e.body);{const t=ie.invalidContentType(e.header("content-type")||"");return Promise.reject(new s.LDFlagFetchError(t))}}return Promise.reject(function(e){return 404===e.status?new s.LDInvalidEnvironmentIdError(ie.environmentNotFound()):new s.LDFlagFetchError(ie.errorFetchingFlags(e.statusText||String(e.status)))}(e))}),(e=>Promise.reject(new s.LDFlagFetchError(ie.networkError(e)))));return a.addPromise(l,(()=>{c.cancel&&c.cancel()})),a.resultPromise}return c.fetchJSON=function(e){return l(S.appendUrlPath(r,e),null)},c.fetchFlagSettings=function(e,t){let s,c,u,d="";return o?(c=[r,"/sdk/evalx/",n,"/context"].join(""),u=JSON.stringify(e)):(s=S.base64URLEncode(JSON.stringify(e)),c=[r,"/sdk/evalx/",n,"/contexts/",s].join("")),t&&(d="h="+t),i&&(d=d+(d?"&":"")+"withReasons=true"),c=c+(d?"?":"")+d,a.debug(ie.debugPolling(c)),l(c,u)},c};var et=function(e,t){const n={};let r;return n.setContext=function(e){r=S.sanitizeContext(e),r&&t&&t(S.clone(r))},n.getContext=function(){return r?S.clone(r):null},e&&n.setContext(e),n};const{v1:tt}=ee,{getContextKinds:nt}=Ee;var rt=function(e){function t(e){return null==e||"user"===e?"ld:$anonUserId":`ld:$contextKey:${e}`}function n(n,r){return null!==r.key&&void 0!==r.key?(r.key=r.key.toString(),Promise.resolve(r)):r.anonymous?function(n){return e.get(t(n))}(n).then((o=>{if(o)return r.key=o,r;{const o=tt();return r.key=o,function(n,r){return e.set(t(r),n)}(o,n).then((()=>r))}})):Promise.reject(new s.LDInvalidUserError(ie.invalidContext()))}this.processContext=e=>{if(!e)return Promise.reject(new s.LDInvalidUserError(ie.contextNotSpecified()));const t=S.clone(e);if("multi"===e.kind){const e=nt(t);return Promise.all(e.map((e=>n(e,t[e])))).then((()=>t))}return n(e.kind,t)}};const{v1:ot}=ee,{baseOptionDefs:it}=de,{appendUrlPath:at}=S;var st={DiagnosticId:function(e){const t={diagnosticId:ot()};return e&&(t.sdkKeySuffix=e.length>6?e.substring(e.length-6):e),t},DiagnosticsAccumulator:function(e){let t,n,r,o;function i(e){t=e,n=0,r=0,o=[]}return i(e),{getProps:()=>({dataSinceDate:t,droppedEvents:n,eventsInLastBatch:r,streamInits:o}),setProps:e=>{t=e.dataSinceDate,n=e.droppedEvents||0,r=e.eventsInLastBatch||0,o=e.streamInits||[]},incrementDroppedEvents:()=>{n++},setEventsInLastBatch:e=>{r=e},recordStreamInit:(e,t,n)=>{const r={timestamp:e,failed:t,durationMillis:n};o.push(r)},reset:i}},DiagnosticsManager:function(e,t,n,r,o,i,a){const s=!!e.diagnosticUseCombinedEvent,c="ld:"+o+":$diagnostics",u=at(i.eventsUrl,"/events/diagnostic/"+o),l=i.diagnosticRecordingInterval,d=n;let f,g,v=!!i.streaming;const p={};function m(){return{sdk:w(),configuration:b(),platform:e.diagnosticPlatformData}}function h(e){i.logger&&i.logger.debug(ie.debugPostingDiagnosticEvent(e)),r.sendEvents(e,u,!0).then((()=>{})).catch((()=>{}))}function y(){h(function(){const e=(new Date).getTime();let t={kind:s?"diagnostic-combined":"diagnostic",id:a,creationDate:e,...d.getProps()};return s&&(t={...t,...m()}),d.reset(e),t}()),g=setTimeout(y,l),f=(new Date).getTime(),s&&function(){if(t.isEnabled()){const e={...d.getProps()};t.set(c,JSON.stringify(e))}}()}function w(){const t={...e.diagnosticSdkData};return i.wrapperName&&(t.wrapperName=i.wrapperName),i.wrapperVersion&&(t.wrapperVersion=i.wrapperVersion),t}function b(){return{customBaseURI:i.baseUrl!==it.baseUrl.default,customStreamURI:i.streamUrl!==it.streamUrl.default,customEventsURI:i.eventsUrl!==it.eventsUrl.default,eventsCapacity:i.eventCapacity,eventsFlushIntervalMillis:i.flushInterval,reconnectTimeMillis:i.streamReconnectDelay,streamingDisabled:!v,allAttributesPrivate:!!i.allAttributesPrivate,diagnosticRecordingIntervalMillis:i.diagnosticRecordingInterval,usingSecureMode:!!i.hash,bootstrapMode:!!i.bootstrap,fetchGoalsDisabled:!i.fetchGoals,sendEventsOnlyForVariation:!!i.sendEventsOnlyForVariation}}return p.start=()=>{s?function(e){if(!t.isEnabled())return e(!1);t.get(c).then((t=>{if(t)try{const e=JSON.parse(t);d.setProps(e),f=e.dataSinceDate}catch(e){}e(!0)})).catch((()=>{e(!1)}))}((e=>{if(e){const e=(f||0)+l,t=(new Date).getTime();t>=e?y():g=setTimeout(y,e-t)}else 0===Math.floor(4*Math.random())?y():g=setTimeout(y,l)})):(h({kind:"diagnostic-init",id:a,creationDate:d.getProps().dataSinceDate,...m()}),g=setTimeout(y,l))},p.stop=()=>{g&&clearTimeout(g)},p.setStreaming=e=>{v=e},p}};var ct=function(e,t){let n=!1;const r={type:e.type,name:e.name,synchronous:e.synchronous,method:(...o)=>{try{e.method(...o)}catch{n||(n=!0,t.warn(ie.inspectorMethodError(r.type,r.name)))}}};return r};const{onNextTick:ut}=S,lt={flagUsed:"flag-used",flagDetailsChanged:"flag-details-changed",flagDetailChanged:"flag-detail-changed",clientIdentityChanged:"client-identity-changed"};Object.freeze(lt);var dt={InspectorTypes:lt,InspectorManager:function(e,t){const n={},r={[lt.flagUsed]:[],[lt.flagDetailsChanged]:[],[lt.flagDetailChanged]:[],[lt.clientIdentityChanged]:[]},o={[lt.flagUsed]:[],[lt.flagDetailsChanged]:[],[lt.flagDetailChanged]:[],[lt.clientIdentityChanged]:[]},i=e&&e.map((e=>ct(e,t)));return i&&i.forEach((e=>{Object.prototype.hasOwnProperty.call(r,e.type)&&!e.synchronous?r[e.type].push(e):Object.prototype.hasOwnProperty.call(o,e.type)&&e.synchronous?o[e.type].push(e):t.warn(ie.invalidInspector(e.type,e.name))})),n.hasListeners=e=>r[e]&&r[e].length||o[e]&&o[e].length,n.onFlagUsed=(e,t,n)=>{const i=lt.flagUsed;o[i].length&&o[i].forEach((r=>r.method(e,t,n))),r[i].length&&ut((()=>{r[i].forEach((r=>r.method(e,t,n)))}))},n.onFlags=e=>{const t=lt.flagDetailsChanged;o[t].length&&o[t].forEach((t=>t.method(e))),r[t].length&&ut((()=>{r[t].forEach((t=>t.method(e)))}))},n.onFlagChanged=(e,t)=>{const n=lt.flagDetailChanged;o[n].length&&o[n].forEach((n=>n.method(e,t))),r[n].length&&ut((()=>{r[n].forEach((n=>n.method(e,t)))}))},n.onIdentityChanged=e=>{const t=lt.clientIdentityChanged;o[t].length&&o[t].forEach((t=>t.method(e))),r[t].length&&ut((()=>{r[t].forEach((t=>t.method(e)))}))},n}};const{LDTimeoutError:ft}=s;var gt=function(e,t){return new Promise(((n,r)=>{setTimeout((()=>{r(new ft(`${t} timed out after ${e} seconds.`))}),1e3*e)}))};const vt="unknown hook";function pt(e,t,n,r,o){try{return r()}catch(r){return e?.error(`An error was encountered in "${t}" of the "${n}" hook: ${r}`),o}}function mt(e,t){try{return t.getMetadata().name||vt}catch{return e.error("Exception thrown getting metadata for hook. Unable to get hook name."),vt}}var ht=function(e,t){const n=t?[...t]:[];return{withEvaluation:function(t,r,o,i){if(0===n.length)return i();const a=[...n],s={flagKey:t,context:r,defaultValue:o},c=function(e,t,n){return t.map((t=>pt(e,"beforeEvaluation",mt(e,t),(()=>t?.beforeEvaluation?.(n,{})??{}),{})))}(e,a,s),u=i();return function(e,t,n,r,o){for(let i=t.length-1;i>=0;i-=1){const a=t[i],s=r[i];pt(e,"afterEvaluation",mt(e,a),(()=>a?.afterEvaluation?.(n,s,o)??{}),{})}}(e,a,s,c,u),u},identify:function(t,r){const o=[...n],i={context:t,timeout:r},a=function(e,t,n){return t.map((t=>pt(e,"beforeIdentify",mt(e,t),(()=>t?.beforeIdentify?.(n,{})??{}),{})))}(e,o,i);return t=>{!function(e,t,n,r,o){for(let i=t.length-1;i>=0;i-=1){const a=t[i],s=r[i];pt(e,"afterIdentify",mt(e,a),(()=>a?.afterIdentify?.(n,s,o)??{}),{})}}(e,o,i,a,t)}},addHook:function(e){n.push(e)},afterTrack:function(t){if(0===n.length)return;const r=[...n];!function(e,t,n){for(let r=t.length-1;r>=0;r-=1){const o=t[r];pt(e,"afterTrack",mt(e,o),(()=>o?.afterTrack?.(n)),void 0)}}(e,r,t)}}};const yt="unknown plugin";function wt(e,t){try{return t.getMetadata().name||yt}catch(t){return e.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),yt}}var bt={getPluginHooks:function(e,t,n){const r=[];return n.forEach((n=>{try{const o=n.getHooks?.(t);void 0===o?e.error(`Plugin ${wt(e,n)} returned undefined from getHooks.`):o&&o.length>0&&r.push(...o)}catch(t){e.error(`Exception thrown getting hooks for plugin ${wt(e,n)}. Unable to get hooks.`)}})),r},registerPlugins:function(e,t,n,r){r.forEach((r=>{try{r.register(n,t)}catch(t){e.error(`Exception thrown registering plugin ${wt(e,r)}.`)}}))},createPluginEnvironment:function(e,t,n){const r={};e.userAgent&&(r.name=e.userAgent),e.version&&(r.version=e.version),n.wrapperName&&(r.wrapperName=n.wrapperName),n.wrapperVersion&&(r.wrapperVersion=n.wrapperVersion);const o={};n.application&&(n.application.name&&(o.name=n.application.name),n.application.version&&(o.version=n.application.version));const i={sdk:r,clientSideId:t};return Object.keys(o).length>0&&(i.application=o),i}};const{commonBasicLogger:kt}=ne,{checkContext:Et,getContextKeys:Dt}=Ee,{InspectorTypes:xt,InspectorManager:Ct}=dt,{getPluginHooks:Pt,registerPlugins:St,createPluginEnvironment:It}=bt,Ot="change",Tt="internal-change";var Lt={initialize:function(e,t,n,r,o){const i=function(){if(n&&n.logger)return n.logger;return o&&o.logger&&o.logger.default||kt("warn")}(),a=Re(i),c=Ve(a),u=de.validate(n,a,o,i),l=Ct(u.inspectors,i),d=u.sendEvents;let f=e,g=u.hash;const v=[...u.plugins],p=It(r,e,u),m=Pt(i,p,v),h=ht(i,[...u.hooks,...m]),y=Me(r.localStorage,i),w=he(r,f,u),b=u.sendEvents&&!u.diagnosticOptOut,k=b?st.DiagnosticId(f):null,E=b?st.DiagnosticsAccumulator((new Date).getTime()):null,D=b?st.DiagnosticsManager(r,y,E,w,f,u,k):null,x=Ge(r,u,f,E),C=u.eventProcessor||je(r,u,f,E,a,w),P=Ze(r,u,f);let I,O,T,L={},U=u.streaming,A=!1,j=!1,R=!0;const F=u.stateProvider,N=et(null,(function(e){(function(e){if(F)return;e&&H({kind:"identify",context:e,creationDate:(new Date).getTime()})})(e),l.hasListeners(xt.clientIdentityChanged)&&l.onIdentityChanged(N.getContext())})),$=new rt(y),V=y.isEnabled()?He(y,f,g,N):null;function H(e){f&&(F&&F.enqueueEvent&&F.enqueueEvent(e)||(e.context?(R=!1,!d||j||r.isDoNotTrack()||(i.debug(ie.debugEnqueueingEvent(e.kind)),C.enqueue(e))):R&&(i.warn(ie.eventWithoutContext()),R=!1)))}function M(e,t){l.hasListeners(xt.flagDetailChanged)&&l.onFlagChanged(e.key,J(t))}function q(){l.hasListeners(xt.flagDetailsChanged)&&l.onFlags(Object.entries(L).map((([e,t])=>({key:e,detail:J(t)}))).reduce(((e,t)=>(e[t.key]=t.detail,e)),{}))}function z(e,t,n,r){const o=N.getContext(),i=new Date,a={kind:"feature",key:e,context:o,value:t?t.value:null,variation:t?t.variationIndex:null,default:n,creationDate:i.getTime()},s=L[e];s&&(a.version=s.flagVersion?s.flagVersion:s.version,a.trackEvents=s.trackEvents,a.debugEventsUntilDate=s.debugEventsUntilDate),(r||s&&s.trackReason)&&t&&(a.reason=t.reason),H(a)}function K(e){return Et(e,!1)?Promise.resolve(e):Promise.reject(new s.LDInvalidUserError(ie.invalidContext()))}function _(e,t,n,r,o,i){let a,s;return L&&S.objectHasOwnProperty(L,e)&&L[e]&&!L[e].deleted?(s=L[e],a=J(s),null!==s.value&&void 0!==s.value||(a.value=t)):a={value:t,variationIndex:null,reason:{kind:"ERROR",errorKind:"FLAG_NOT_FOUND"}},n&&(o||s?.prerequisites?.forEach((e=>{_(e,void 0,n,!1,!1,!1)})),z(e,a,t,r)),!o&&i&&function(e,t){l.hasListeners(xt.flagUsed)&&l.onFlagUsed(e,t,N.getContext())}(e,a),a}function J(e){return{value:e.value,variationIndex:void 0===e.variation?null:e.variation,reason:e.reason||null}}function B(){if(O=!0,!N.getContext())return;const e=e=>{try{return JSON.parse(e)}catch(e){return void a.maybeReportError(new s.LDInvalidDataError(ie.invalidData()))}};x.connect(N.getContext(),g,{ping:function(){i.debug(ie.debugStreamPing());const e=N.getContext();P.fetchFlagSettings(e,g).then((t=>{S.deepEquals(e,N.getContext())&&W(t||{})})).catch((e=>{a.maybeReportError(new s.LDFlagFetchError(ie.errorFetchingFlags(e)))}))},put:function(t){const n=e(t.data);n&&(i.debug(ie.debugStreamPut()),W(n))},patch:function(t){const n=e(t.data);if(!n)return;const r=L[n.key];if(!r||!r.version||!n.version||r.version{}))}function X(e){const t=Object.keys(e);if(t.length>0){const n={};t.forEach((t=>{const r=e[t].current,o=r?r.value:void 0,i=e[t].previous;a.emit(Ot+":"+t,o,i),n[t]=r?{current:o,previous:i}:{previous:i}})),a.emit(Ot,n),a.emit(Tt,L),u.sendEventsOnlyForVariation||F||t.forEach((t=>{z(t,e[t].current)}))}return I&&V?V.saveFlags(L):Promise.resolve()}function Q(){const e=U||T&&void 0===U;e&&!O?B():!e&&O&&G(),D&&D.setStreaming(e)}function Y(e){return e===Ot||e.substr(0,7)===Ot+":"}if("string"==typeof u.bootstrap&&"LOCALSTORAGE"===u.bootstrap.toUpperCase()&&(V?I=!0:i.warn(ie.localStorageUnavailable())),"object"==typeof u.bootstrap&&(L=function(e){const t=Object.keys(e),n="$flagsState",r="$valid",o=e[n];!o&&t.length&&i.warn(ie.bootstrapOldFormat()),!1===e[r]&&i.warn(ie.bootstrapInvalid());const a={};return t.forEach((t=>{if(t!==n&&t!==r){let n={value:e[t]};o&&o[t]?n=S.extend(n,o[t]):n.version=0,a[t]=n}})),a}(u.bootstrap)),F){const e=F.getInitialState();e?Z(e):F.on("init",Z),F.on("update",(function(e){e.context&&N.setContext(e.context);e.flags&&W(e.flags)}))}else(function(){if(!e)return Promise.reject(new s.LDInvalidEnvironmentIdError(ie.environmentNotSpecified()));let n;return $.processContext(t).then(K).then((e=>(n=S.once(h.identify(e,void 0)),e))).then((e=>(n?.({status:"completed"}),N.setContext(e),"object"==typeof u.bootstrap?ee():I?V.loadFlags().then((e=>null==e?(L={},P.fetchFlagSettings(N.getContext(),g).then((e=>W(e||{}))).then(ee).catch((e=>{te(new s.LDFlagFetchError(ie.errorFetchingFlags(e)))}))):(L=e,S.onNextTick(ee),P.fetchFlagSettings(N.getContext(),g).then((e=>W(e))).catch((e=>a.maybeReportError(e)))))):P.fetchFlagSettings(N.getContext(),g).then((e=>{L=e||{},q(),ee()})).catch((e=>{L={},te(e)}))))).catch((e=>{throw n?.({status:"error"}),e}))})().catch(te);function Z(e){f=e.environment,N.setContext(e.context),L={...e.flags},S.onNextTick(ee)}function ee(){i.info(ie.clientInitialized()),A=!0,Q(),c.signalSuccess()}function te(e){c.signalFailure(e)}const ne={waitForInitialization:function(e=void 0){if(null!=e){if("number"==typeof e)return function(e){e>5&&i.warn("The waitForInitialization function was called with a timeout greater than 5 seconds. We recommend a timeout of 5 seconds or less.");const t=c.getInitializationPromise(),n=gt(e,"waitForInitialization");return Promise.race([n,t]).catch((e=>{throw e instanceof s.LDTimeoutError&&i.error(`waitForInitialization error: ${e}`),e}))}(e);i.warn("The waitForInitialization method was provided with a non-numeric timeout.")}return i.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied."),c.getInitializationPromise()},waitUntilReady:()=>c.getReadyPromise(),identify:function(e,t,n){if(j)return S.wrapPromiseCallback(Promise.resolve({}),n);if(F)return i.warn(ie.identifyDisabled()),S.wrapPromiseCallback(Promise.resolve(S.transformVersionedValuesToValues(L)),n);let r;const o=I&&V?V.clearFlags():Promise.resolve();return S.wrapPromiseCallback(o.then((()=>$.processContext(e))).then(K).then((e=>(r=S.once(h.identify(e,void 0)),e))).then((e=>P.fetchFlagSettings(e,t).then((n=>{const r=S.transformVersionedValuesToValues(n);return N.setContext(e),g=t,n?W(n).then((()=>r)):r})))).then((e=>(r?.({status:"completed"}),O&&B(),e))).catch((e=>(r?.({status:"error"}),a.maybeReportError(e),Promise.reject(e)))),n)},getContext:function(){return N.getContext()},variation:function(e,t){const{value:n}=h.withEvaluation(e,N.getContext(),t,(()=>_(e,t,!0,!1,!1,!0)));return n},variationDetail:function(e,t){return h.withEvaluation(e,N.getContext(),t,(()=>_(e,t,!0,!0,!1,!0)))},track:function(e,t,n){if("string"!=typeof e)return void a.maybeReportError(new s.LDInvalidEventKeyError(ie.unknownCustomEventKey(e)));void 0!==n&&"number"!=typeof n&&i.warn(ie.invalidMetricValue(typeof n)),r.customEventFilter&&!r.customEventFilter(e)&&i.warn(ie.unknownCustomEventKey(e));const o=N.getContext(),c={kind:"custom",key:e,context:o,url:r.getCurrentUrl(),creationDate:(new Date).getTime()};o&&o.anonymous&&(c.contextKind=o.anonymous?"anonymousUser":"user"),null!=t&&(c.data=t),null!=n&&(c.metricValue=n),H(c),h.afterTrack({context:o,key:e,data:t,metricValue:n})},on:function(e,t,n){Y(e)?(T=!0,A&&Q(),a.on(e,t,n)):a.on(...arguments)},off:function(e){if(a.off(...arguments),Y(e)){let e=!1;a.getEvents().forEach((t=>{Y(t)&&a.getEventListenerCount(t)>0&&(e=!0)})),e||(T=!1,O&&void 0===U&&G())}},setStreaming:function(e){const t=null===e?void 0:e;t!==U&&(U=t,Q())},flush:function(e){return S.wrapPromiseCallback(d?C.flush():Promise.resolve(),e)},allFlags:function(){const e={};if(!L)return e;for(const t in L)S.objectHasOwnProperty(L,t)&&!L[t].deleted&&(e[t]=_(t,null,!u.sendEventsOnlyForVariation,!1,!0,!1).value);return e},close:function(e){if(j)return S.wrapPromiseCallback(Promise.resolve(),e);const t=()=>{j=!0,L={}},n=Promise.resolve().then((()=>{if(G(),D&&D.stop(),d)return C.stop(),C.flush()})).then(t).catch(t);return S.wrapPromiseCallback(n,e)},addHook:function(e){h.addHook(e)}};return St(i,p,ne,v),{client:ne,options:u,emitter:a,ident:N,logger:i,requestor:P,start:function(){d&&(D&&D.start(),C.start())},enqueueEvent:H,getFlagsInternal:function(){return L},getEnvironmentId:()=>f,internalChangeEventName:Tt}},commonBasicLogger:kt,errors:s,messages:ie,utils:S,getContextKeys:Dt},Ut=Lt.initialize,At=Lt.errors,jt=Lt.messages;function Rt(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ft(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Nt(e){for(var t=1;t{if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")};function zt(e,t,n,r){var o,i,a=(("substring"===e.kind||"regex"===e.kind)&&r.includes("/")?t:t.replace(r,"")).replace(n,"");switch(e.kind){case"exact":i=t,o=new RegExp("^"+qt(e.url)+"/?$");break;case"canonical":i=a,o=new RegExp("^"+qt(e.url)+"/?$");break;case"substring":i=a,o=new RegExp(".*"+qt(e.substring)+".*$");break;case"regex":i=a,o=new RegExp(e.pattern);break;default:return!1}return o.test(i)}function Kt(e,t){for(var n={},r=null,o=[],i=0;i0&&(r=function(e){for(var n=function(e,t){for(var n=[],r=0;r0;){for(var c=0;c0&&(r=Kt(n=e,i),function(e,t){var n,r=window.location.href;function o(){(n=window.location.href)!==r&&(r=n,t())}!function e(t,n){t(),setTimeout((function(){e(t,n)}),n)}(o,e),window.history&&window.history.pushState?window.addEventListener("popstate",o):window.addEventListener("hashchange",o)}(300,o)),t()})).catch((function(n){e.emitter.maybeReportError(new At.LDUnexpectedResponseError((n&&n.message,n.message))),t()})),{}}var Jt="goalsReady",Bt={fetchGoals:{default:!0},hash:{type:"string"},eventProcessor:{type:"object"},eventUrlTransformer:{type:"function"},disableSyncEventPost:{default:!1}};function Gt(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=function(e){var t,n={userAgentHeaderName:"X-LaunchDarkly-User-Agent",synchronousFlush:!1};if(window.XMLHttpRequest){var r=e&&e.disableSyncEventPost;n.httpRequest=function(e,t,o,i){var a=n.synchronousFlush&!r;return n.synchronousFlush=!1,Mt(e,t,o,i,a)}}n.httpAllowsPost=function(){return void 0===t&&(t=!!window.XMLHttpRequest&&"withCredentials"in new window.XMLHttpRequest),t},n.httpFallbackPing=function(e){(new window.Image).src=e};var o,i=e&&e.eventUrlTransformer;n.getCurrentUrl=function(){return i?i(window.location.href):window.location.href},n.isDoNotTrack=function(){var e;return 1===(e=window.navigator&&void 0!==window.navigator.doNotTrack?window.navigator.doNotTrack:window.navigator&&void 0!==window.navigator.msDoNotTrack?window.navigator.msDoNotTrack:window.doNotTrack)||!0===e||"1"===e||"yes"===e};try{window.localStorage&&(n.localStorage={get:function(e){return new Promise((function(t){t(window.localStorage.getItem(e))}))},set:function(e,t){return new Promise((function(n){window.localStorage.setItem(e,t),n()}))},clear:function(e){return new Promise((function(t){window.localStorage.removeItem(e),t()}))}})}catch(e){n.localStorage=null}if(e&&e.useReport&&"function"==typeof window.EventSourcePolyfill&&window.EventSourcePolyfill.supportedOptions&&window.EventSourcePolyfill.supportedOptions.method?(n.eventSourceAllowsReport=!0,o=window.EventSourcePolyfill):(n.eventSourceAllowsReport=!1,o=window.EventSource),window.EventSource){var a=3e5;n.eventSourceFactory=function(e,t){var n=Nt(Nt({},{heartbeatTimeout:a,silentTimeout:a,skipDefaultHeaders:!0}),t);return new o(e,n)},n.eventSourceIsActive=function(e){return e.readyState===window.EventSource.OPEN||e.readyState===window.EventSource.CONNECTING}}return n.userAgent="JSClient",n.version="3.8.1",n.diagnosticSdkData={name:"js-client-sdk",version:"3.8.1"},n.diagnosticPlatformData={name:"JS"},n.diagnosticUseCombinedEvent=!0,n}(n),o=Ut(e,t,n,r,Bt),i=o.client,a=o.options,s=o.emitter,c=new Promise((function(e){var t=s.on(Jt,(function(){s.off(Jt,t),e()}))}));i.waitUntilGoalsReady=function(){return c},a.fetchGoals?_t(o,(function(){return s.emit(Jt)})):s.emit(Jt),"complete"!==document.readyState?window.addEventListener("load",o.start):o.start();var u=function(){r.synchronousFlush=!0,i.flush().catch((function(){})),r.synchronousFlush=!1};return document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&u()})),window.addEventListener("pagehide",u),i}var Wt=Vt,Xt="3.8.1";var Qt={initialize:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return console&&console.warn&&console.warn(jt.deprecated("default export","named LDClient export")),Gt(e,t,n)},version:Xt};exports.basicLogger=Wt,exports.createConsoleLogger=undefined,exports.default=Qt,exports.initialize=Gt,exports.version=Xt; +//# sourceMappingURL=ldclient.cjs.js.map diff --git a/node_modules/launchdarkly-js-client-sdk/dist/ldclient.cjs.js.map b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.cjs.js.map new file mode 100644 index 00000000..9377ba05 --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ldclient.cjs.js","sources":["../node_modules/launchdarkly-js-sdk-common/src/errors.js","../node_modules/base64-js/index.js","../node_modules/launchdarkly-js-sdk-common/node_modules/fast-deep-equal/index.js","../node_modules/launchdarkly-js-sdk-common/src/utils.js","../node_modules/uuid/dist/esm-browser/rng.js","../node_modules/uuid/dist/esm-browser/regex.js","../node_modules/uuid/dist/esm-browser/validate.js","../node_modules/uuid/dist/esm-browser/stringify.js","../node_modules/uuid/dist/esm-browser/v1.js","../node_modules/uuid/dist/esm-browser/parse.js","../node_modules/uuid/dist/esm-browser/v35.js","../node_modules/uuid/dist/esm-browser/md5.js","../node_modules/uuid/dist/esm-browser/v3.js","../node_modules/uuid/dist/esm-browser/sha1.js","../node_modules/uuid/dist/esm-browser/v5.js","../node_modules/uuid/dist/esm-browser/v4.js","../node_modules/uuid/dist/esm-browser/nil.js","../node_modules/uuid/dist/esm-browser/version.js","../node_modules/launchdarkly-js-sdk-common/src/loggers.js","../node_modules/launchdarkly-js-sdk-common/src/messages.js","../node_modules/launchdarkly-js-sdk-common/src/configuration.js","../node_modules/launchdarkly-js-sdk-common/src/headers.js","../node_modules/launchdarkly-js-sdk-common/src/EventSender.js","../node_modules/launchdarkly-js-sdk-common/src/canonicalize.js","../node_modules/launchdarkly-js-sdk-common/src/context.js","../node_modules/launchdarkly-js-sdk-common/src/EventSummarizer.js","../node_modules/launchdarkly-js-sdk-common/src/MultiEventSummarizer.js","../node_modules/launchdarkly-js-sdk-common/src/attributeReference.js","../node_modules/launchdarkly-js-sdk-common/src/ContextFilter.js","../node_modules/launchdarkly-js-sdk-common/src/EventProcessor.js","../node_modules/launchdarkly-js-sdk-common/src/EventEmitter.js","../node_modules/launchdarkly-js-sdk-common/src/InitializationState.js","../node_modules/launchdarkly-js-sdk-common/src/PersistentFlagStore.js","../node_modules/launchdarkly-js-sdk-common/src/PersistentStorage.js","../node_modules/launchdarkly-js-sdk-common/src/Stream.js","../node_modules/launchdarkly-js-sdk-common/src/promiseCoalescer.js","../node_modules/launchdarkly-js-sdk-common/src/Requestor.js","../node_modules/launchdarkly-js-sdk-common/src/Identity.js","../node_modules/launchdarkly-js-sdk-common/src/AnonymousContextProcessor.js","../node_modules/launchdarkly-js-sdk-common/src/diagnosticEvents.js","../node_modules/launchdarkly-js-sdk-common/src/SafeInspector.js","../node_modules/launchdarkly-js-sdk-common/src/InspectorManager.js","../node_modules/launchdarkly-js-sdk-common/src/timedPromise.js","../node_modules/launchdarkly-js-sdk-common/src/HookRunner.js","../node_modules/launchdarkly-js-sdk-common/src/plugins.js","../node_modules/launchdarkly-js-sdk-common/src/index.js","../src/basicLogger.js","../src/httpRequest.js","../node_modules/escape-string-regexp/index.js","../src/GoalTracker.js","../src/GoalManager.js","../src/index.js","../src/browserPlatform.js"],"sourcesContent":["function createCustomError(name) {\n function CustomError(message, code) {\n Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);\n this.message = message;\n this.code = code;\n }\n\n CustomError.prototype = new Error();\n CustomError.prototype.name = name;\n CustomError.prototype.constructor = CustomError;\n\n return CustomError;\n}\n\nconst LDUnexpectedResponseError = createCustomError('LaunchDarklyUnexpectedResponseError');\nconst LDInvalidEnvironmentIdError = createCustomError('LaunchDarklyInvalidEnvironmentIdError');\nconst LDInvalidUserError = createCustomError('LaunchDarklyInvalidUserError');\nconst LDInvalidEventKeyError = createCustomError('LaunchDarklyInvalidEventKeyError');\nconst LDInvalidArgumentError = createCustomError('LaunchDarklyInvalidArgumentError');\nconst LDFlagFetchError = createCustomError('LaunchDarklyFlagFetchError');\nconst LDInvalidDataError = createCustomError('LaunchDarklyInvalidDataError');\nconst LDTimeoutError = createCustomError('LaunchDarklyTimeoutError');\n\nfunction isHttpErrorRecoverable(status) {\n if (status >= 400 && status < 500) {\n return status === 400 || status === 408 || status === 429;\n }\n return true;\n}\n\nmodule.exports = {\n LDUnexpectedResponseError,\n LDInvalidEnvironmentIdError,\n LDInvalidUserError,\n LDInvalidEventKeyError,\n LDInvalidArgumentError,\n LDInvalidDataError,\n LDFlagFetchError,\n LDTimeoutError,\n isHttpErrorRecoverable,\n};\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","'use strict';\n\nvar isArray = Array.isArray;\nvar keyList = Object.keys;\nvar hasProp = Object.prototype.hasOwnProperty;\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n var arrA = isArray(a)\n , arrB = isArray(b)\n , i\n , length\n , key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var dateA = a instanceof Date\n , dateB = b instanceof Date;\n if (dateA != dateB) return false;\n if (dateA && dateB) return a.getTime() == b.getTime();\n\n var regexpA = a instanceof RegExp\n , regexpB = b instanceof RegExp;\n if (regexpA != regexpB) return false;\n if (regexpA && regexpB) return a.toString() == b.toString();\n\n var keys = keyList(a);\n length = keys.length;\n\n if (length !== keyList(b).length)\n return false;\n\n for (i = length; i-- !== 0;)\n if (!hasProp.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n key = keys[i];\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n return a!==a && b!==b;\n};\n","const base64 = require('base64-js');\nconst fastDeepEqual = require('fast-deep-equal');\n\nconst userAttrsToStringify = ['key', 'ip', 'country', 'email', 'firstName', 'lastName', 'avatar', 'name'];\n\nfunction appendUrlPath(baseUrl, path) {\n // Ensure that URL concatenation is done correctly regardless of whether the\n // base URL has a trailing slash or not.\n const trimBaseUrl = baseUrl.endsWith('/') ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl;\n return trimBaseUrl + (path.startsWith('/') ? '' : '/') + path;\n}\n\n// See http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html\nfunction btoa(s) {\n const escaped = unescape(encodeURIComponent(s));\n return base64.fromByteArray(stringToBytes(escaped));\n}\n\nfunction stringToBytes(s) {\n const b = [];\n for (let i = 0; i < s.length; i++) {\n b.push(s.charCodeAt(i));\n }\n return b;\n}\n\nfunction base64URLEncode(s) {\n return (\n btoa(s)\n // eslint-disable-next-line\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n );\n}\n\nfunction clone(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n\nfunction deepEquals(a, b) {\n return fastDeepEqual(a, b);\n}\n\n// Events emitted in LDClient's initialize method will happen before the consumer\n// can register a listener, so defer them to next tick.\nfunction onNextTick(cb) {\n setTimeout(cb, 0);\n}\n\n/**\n * Wrap a promise to invoke an optional callback upon resolution or rejection.\n *\n * This function assumes the callback follows the Node.js callback type: (err, value) => void\n *\n * If a callback is provided:\n * - if the promise is resolved, invoke the callback with (null, value)\n * - if the promise is rejected, invoke the callback with (error, null)\n *\n * @param {Promise} promise\n * @param {Function} callback\n * @returns Promise | undefined\n */\nfunction wrapPromiseCallback(promise, callback) {\n const ret = promise.then(\n value => {\n if (callback) {\n setTimeout(() => {\n callback(null, value);\n }, 0);\n }\n return value;\n },\n error => {\n if (callback) {\n setTimeout(() => {\n callback(error, null);\n }, 0);\n } else {\n return Promise.reject(error);\n }\n }\n );\n\n return !callback ? ret : undefined;\n}\n\n/**\n * Takes a map of flag keys to values, and returns the more verbose structure used by the\n * client stream.\n */\nfunction transformValuesToVersionedValues(flags) {\n const ret = {};\n for (const key in flags) {\n if (objectHasOwnProperty(flags, key)) {\n ret[key] = { value: flags[key], version: 0 };\n }\n }\n return ret;\n}\n\n/**\n * Converts the internal flag state map to a simple map of flag keys to values.\n */\nfunction transformVersionedValuesToValues(flagsState) {\n const ret = {};\n for (const key in flagsState) {\n if (objectHasOwnProperty(flagsState, key)) {\n ret[key] = flagsState[key].value;\n }\n }\n return ret;\n}\n\nfunction getLDUserAgentString(platform) {\n const version = platform.version || '?';\n return platform.userAgent + '/' + version;\n}\n\nfunction extend(...objects) {\n return objects.reduce((acc, obj) => ({ ...acc, ...obj }), {});\n}\n\nfunction objectHasOwnProperty(object, name) {\n return Object.prototype.hasOwnProperty.call(object, name);\n}\n\nfunction sanitizeContext(context) {\n if (!context) {\n return context;\n }\n let newContext;\n // Only stringify user attributes for legacy users.\n if (context.kind === null || context.kind === undefined) {\n userAttrsToStringify.forEach(attr => {\n const value = context[attr];\n if (value !== undefined && typeof value !== 'string') {\n newContext = newContext || { ...context };\n newContext[attr] = String(value);\n }\n });\n }\n\n return newContext || context;\n}\n\n/**\n * Creates a function that will invoke the provided function only once.\n *\n * If the function returns a value, then that returned value will be re-used for subsequent invocations.\n *\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n */\nfunction once(func) {\n let called = false;\n let result;\n return function(...args) {\n if (!called) {\n called = true;\n result = func.apply(this, args);\n }\n return result;\n };\n}\n\nmodule.exports = {\n appendUrlPath,\n base64URLEncode,\n btoa,\n clone,\n deepEquals,\n extend,\n getLDUserAgentString,\n objectHasOwnProperty,\n onNextTick,\n sanitizeContext,\n transformValuesToVersionedValues,\n transformVersionedValuesToValues,\n wrapPromiseCallback,\n once,\n};\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js'; // **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\n\nvar _clockseq; // Previous uuid creation time\n\n\nvar _lastMSecs = 0;\nvar _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || new Array(16);\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n var seedBytes = options.random || (options.rng || rng)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || stringify(b);\n}\n\nexport default v1;","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n var v;\n var arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","import stringify from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n var bytes = [];\n\n for (var i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function (name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (namespace.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n var bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return stringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","/*\n * Browser-compatible JavaScript MD5\n *\n * Modification of JavaScript MD5\n * https://github.com/blueimp/JavaScript-MD5\n *\n * Copyright 2011, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on\n * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message\n * Digest Algorithm, as defined in RFC 1321.\n * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for more info.\n */\nfunction md5(bytes) {\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = new Uint8Array(msg.length);\n\n for (var i = 0; i < msg.length; ++i) {\n bytes[i] = msg.charCodeAt(i);\n }\n }\n\n return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));\n}\n/*\n * Convert an array of little-endian words to an array of bytes\n */\n\n\nfunction md5ToHexEncodedArray(input) {\n var output = [];\n var length32 = input.length * 32;\n var hexTab = '0123456789abcdef';\n\n for (var i = 0; i < length32; i += 8) {\n var x = input[i >> 5] >>> i % 32 & 0xff;\n var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);\n output.push(hex);\n }\n\n return output;\n}\n/**\n * Calculate output length with padding and bit length\n */\n\n\nfunction getOutputLength(inputLength8) {\n return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;\n}\n/*\n * Calculate the MD5 of an array of little-endian words, and a bit length.\n */\n\n\nfunction wordsToMd5(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << len % 32;\n x[getOutputLength(len) - 1] = len;\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n a = md5ff(a, b, c, d, x[i], 7, -680876936);\n d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);\n c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);\n a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);\n d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);\n b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);\n a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);\n c = md5ff(c, d, a, b, x[i + 10], 17, -42063);\n b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);\n d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);\n c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);\n a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);\n d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);\n b = md5gg(b, c, d, a, x[i], 20, -373897302);\n a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);\n c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);\n b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);\n d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);\n c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);\n a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);\n d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);\n b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);\n a = md5hh(a, b, c, d, x[i + 5], 4, -378558);\n d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);\n c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);\n b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);\n d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);\n c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);\n a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);\n d = md5hh(d, a, b, c, x[i], 11, -358537222);\n c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);\n b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);\n a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);\n c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);\n b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = md5ii(a, b, c, d, x[i], 6, -198630844);\n d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);\n c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);\n a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);\n d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);\n b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);\n a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);\n c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);\n b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);\n d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);\n c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);\n a = safeAdd(a, olda);\n b = safeAdd(b, oldb);\n c = safeAdd(c, oldc);\n d = safeAdd(d, oldd);\n }\n\n return [a, b, c, d];\n}\n/*\n * Convert an array bytes to an array of little-endian words\n * Characters >255 have their high-byte silently ignored.\n */\n\n\nfunction bytesToWords(input) {\n if (input.length === 0) {\n return [];\n }\n\n var length8 = input.length * 8;\n var output = new Uint32Array(getOutputLength(length8));\n\n for (var i = 0; i < length8; i += 8) {\n output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;\n }\n\n return output;\n}\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n\n\nfunction safeAdd(x, y) {\n var lsw = (x & 0xffff) + (y & 0xffff);\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return msw << 16 | lsw & 0xffff;\n}\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\n\n\nfunction bitRotateLeft(num, cnt) {\n return num << cnt | num >>> 32 - cnt;\n}\n/*\n * These functions implement the four basic operations the algorithm uses.\n */\n\n\nfunction md5cmn(q, a, b, x, s, t) {\n return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);\n}\n\nfunction md5ff(a, b, c, d, x, s, t) {\n return md5cmn(b & c | ~b & d, a, b, x, s, t);\n}\n\nfunction md5gg(a, b, c, d, x, s, t) {\n return md5cmn(b & d | c & ~d, a, b, x, s, t);\n}\n\nfunction md5hh(a, b, c, d, x, s, t) {\n return md5cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction md5ii(a, b, c, d, x, s, t) {\n return md5cmn(c ^ (b | ~d), a, b, x, s, t);\n}\n\nexport default md5;","import v35 from './v35.js';\nimport md5 from './md5.js';\nvar v3 = v35('v3', 0x30, md5);\nexport default v3;","// Adapted from Chris Veness' SHA1 code at\n// http://www.movable-type.co.uk/scripts/sha1.html\nfunction f(s, x, y, z) {\n switch (s) {\n case 0:\n return x & y ^ ~x & z;\n\n case 1:\n return x ^ y ^ z;\n\n case 2:\n return x & y ^ x & z ^ y & z;\n\n case 3:\n return x ^ y ^ z;\n }\n}\n\nfunction ROTL(x, n) {\n return x << n | x >>> 32 - n;\n}\n\nfunction sha1(bytes) {\n var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = [];\n\n for (var i = 0; i < msg.length; ++i) {\n bytes.push(msg.charCodeAt(i));\n }\n } else if (!Array.isArray(bytes)) {\n // Convert Array-like to Array\n bytes = Array.prototype.slice.call(bytes);\n }\n\n bytes.push(0x80);\n var l = bytes.length / 4 + 2;\n var N = Math.ceil(l / 16);\n var M = new Array(N);\n\n for (var _i = 0; _i < N; ++_i) {\n var arr = new Uint32Array(16);\n\n for (var j = 0; j < 16; ++j) {\n arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];\n }\n\n M[_i] = arr;\n }\n\n M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);\n M[N - 1][14] = Math.floor(M[N - 1][14]);\n M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;\n\n for (var _i2 = 0; _i2 < N; ++_i2) {\n var W = new Uint32Array(80);\n\n for (var t = 0; t < 16; ++t) {\n W[t] = M[_i2][t];\n }\n\n for (var _t = 16; _t < 80; ++_t) {\n W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);\n }\n\n var a = H[0];\n var b = H[1];\n var c = H[2];\n var d = H[3];\n var e = H[4];\n\n for (var _t2 = 0; _t2 < 80; ++_t2) {\n var s = Math.floor(_t2 / 20);\n var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;\n e = d;\n d = c;\n c = ROTL(b, 30) >>> 0;\n b = a;\n a = T;\n }\n\n H[0] = H[0] + a >>> 0;\n H[1] = H[1] + b >>> 0;\n H[2] = H[2] + c >>> 0;\n H[3] = H[3] + d >>> 0;\n H[4] = H[4] + e >>> 0;\n }\n\n return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nvar v5 = v35('v5', 0x50, sha1);\nexport default v5;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","export default '00000000-0000-0000-0000-000000000000';","import validate from './validate.js';\n\nfunction version(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.substr(14, 1), 16);\n}\n\nexport default version;","const logLevels = ['debug', 'info', 'warn', 'error', 'none'];\n\n/**\n * A simple logger that writes to stderr.\n */\nfunction commonBasicLogger(options, formatFn) {\n if (options && options.destination && typeof options.destination !== 'function') {\n throw new Error('destination for basicLogger was set to a non-function');\n }\n\n function toConsole(methodName) {\n // The global console variable is not guaranteed to be defined at all times in all browsers:\n // https://www.beyondjava.net/console-log-surprises-with-internet-explorer-11-and-edge\n return function(line) {\n if (console && console[methodName]) {\n console[methodName].call(console, line);\n }\n };\n }\n const destinations =\n options && options.destination\n ? [options.destination, options.destination, options.destination, options.destination]\n : [toConsole('log'), toConsole('info'), toConsole('warn'), toConsole('error')];\n const prependLevelToMessage = !!(options && options.destination); // if we're writing to console.warn, etc. we don't need the prefix\n const prefix =\n !options || options.prefix === undefined || options.prefix === null ? '[LaunchDarkly] ' : options.prefix;\n\n let minLevel = 1; // default is 'info'\n if (options && options.level) {\n for (let i = 0; i < logLevels.length; i++) {\n if (logLevels[i] === options.level) {\n minLevel = i;\n }\n }\n }\n\n function write(levelIndex, levelName, args) {\n if (args.length < 1) {\n return;\n }\n let line;\n const fullPrefix = prependLevelToMessage ? levelName + ': ' + prefix : prefix;\n if (args.length === 1 || !formatFn) {\n line = fullPrefix + args[0];\n } else {\n const tempArgs = [...args];\n tempArgs[0] = fullPrefix + tempArgs[0];\n line = formatFn(...tempArgs);\n }\n try {\n destinations[levelIndex](line);\n } catch (err) {\n console &&\n console.log &&\n console.log(\"[LaunchDarkly] Configured logger's \" + levelName + ' method threw an exception: ' + err);\n }\n }\n\n const logger = {};\n for (let i = 0; i < logLevels.length; i++) {\n const levelName = logLevels[i];\n if (levelName !== 'none') {\n if (i < minLevel) {\n logger[levelName] = () => {};\n } else {\n const levelIndex = i;\n logger[levelName] = function() {\n // can't use arrow function with \"arguments\"\n write(levelIndex, levelName, arguments);\n };\n }\n }\n }\n\n return logger;\n}\n\nfunction validateLogger(logger) {\n logLevels.forEach(level => {\n if (level !== 'none' && (!logger[level] || typeof logger[level] !== 'function')) {\n throw new Error('Provided logger instance must support logger.' + level + '(...) method');\n // Note that the SDK normally does not throw exceptions to the application, but that rule\n // does not apply to LDClient.init() which will throw an exception if the parameters are so\n // invalid that we cannot proceed with creating the client. An invalid logger meets those\n // criteria since the SDK calls the logger during nearly all of its operations.\n }\n });\n}\n\nmodule.exports = {\n commonBasicLogger,\n validateLogger,\n};\n","const errors = require('./errors');\n\nfunction errorString(err) {\n if (err && err.message) {\n return err.message;\n }\n if (typeof err === 'string' || err instanceof String) {\n return err;\n }\n return JSON.stringify(err);\n}\n\nconst clientInitialized = function() {\n return 'LaunchDarkly client initialized';\n};\n\nconst docLink =\n ' Please see https://docs.launchdarkly.com/sdk/client-side/javascript#initialize-the-client for instructions on SDK initialization.';\n\nconst clientNotReady = function() {\n return 'LaunchDarkly client is not ready';\n};\n\nconst eventCapacityExceeded = function() {\n return 'Exceeded event queue capacity. Increase capacity to avoid dropping events.';\n};\n\nconst eventWithoutContext = function() {\n return 'Be sure to call `identify` in the LaunchDarkly client: https://docs.launchdarkly.com/sdk/features/identify#javascript';\n};\n\nconst invalidContentType = function(contentType) {\n return 'Expected application/json content type but got \"' + contentType + '\"';\n};\n\nconst invalidKey = function() {\n return 'Event key must be a string';\n};\n\nconst localStorageUnavailable = function(err) {\n return 'local storage is unavailable: ' + errorString(err);\n};\n\nconst networkError = e => 'network error' + (e ? ' (' + e + ')' : '');\n\n// We should remove unknownCustomEventKey in the future - see comments in track() in index.js\nconst unknownCustomEventKey = function(key) {\n return 'Custom event \"' + key + '\" does not exist';\n};\n\nconst environmentNotFound = function() {\n return 'Environment not found. Double check that you specified a valid environment/client-side ID.' + docLink;\n};\n\nconst environmentNotSpecified = function() {\n return 'No environment/client-side ID was specified.' + docLink;\n};\n\nconst errorFetchingFlags = function(err) {\n return 'Error fetching flag settings: ' + errorString(err);\n};\n\nconst contextNotSpecified = function() {\n return 'No context specified.' + docLink;\n};\n\nconst invalidContext = function() {\n return 'Invalid context specified.' + docLink;\n};\n\nconst invalidData = function() {\n return 'Invalid data received from LaunchDarkly; connection may have been interrupted';\n};\n\nconst bootstrapOldFormat = function() {\n return (\n 'LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. ' +\n 'Events may not be sent correctly.' +\n docLink\n );\n};\n\nconst bootstrapInvalid = function() {\n return 'LaunchDarkly bootstrap data is not available because the back end could not read the flags.';\n};\n\nconst deprecated = function(oldName, newName) {\n if (newName) {\n return '\"' + oldName + '\" is deprecated, please use \"' + newName + '\"';\n }\n return '\"' + oldName + '\" is deprecated';\n};\n\nconst httpErrorMessage = function(status, context, retryMessage) {\n return (\n 'Received error ' +\n status +\n (status === 401 ? ' (invalid SDK key)' : '') +\n ' for ' +\n context +\n ' - ' +\n (errors.isHttpErrorRecoverable(status) ? retryMessage : 'giving up permanently')\n );\n};\n\nconst httpUnavailable = function() {\n return 'Cannot make HTTP requests in this environment.' + docLink;\n};\n\nconst identifyDisabled = function() {\n return 'identify() has no effect here; it must be called on the main client instance';\n};\n\nconst streamClosing = function() {\n return 'Closing stream connection';\n};\n\nconst streamConnecting = function(url) {\n return 'Opening stream connection to ' + url;\n};\n\nconst streamError = function(err, streamReconnectDelay) {\n return (\n 'Error on stream connection: ' +\n errorString(err) +\n ', will continue retrying after ' +\n streamReconnectDelay +\n ' milliseconds.'\n );\n};\n\nconst unknownOption = name => 'Ignoring unknown config option \"' + name + '\"';\n\nconst unrecoverableStreamError = err => `Error on stream connection ${errorString(err)}, giving up permanently`;\n\nconst wrongOptionType = (name, expectedType, actualType) =>\n 'Config option \"' + name + '\" should be of type ' + expectedType + ', got ' + actualType + ', using default value';\n\nconst wrongOptionTypeBoolean = (name, actualType) =>\n 'Config option \"' + name + '\" should be a boolean, got ' + actualType + ', converting to boolean';\n\nconst optionBelowMinimum = (name, value, minimum) =>\n 'Config option \"' + name + '\" was set to ' + value + ', changing to minimum value of ' + minimum;\n\nconst debugPolling = function(url) {\n return 'polling for feature flags at ' + url;\n};\n\nconst debugStreamPing = function() {\n return 'received ping message from stream';\n};\n\nconst debugStreamPut = function() {\n return 'received streaming update for all flags';\n};\n\nconst debugStreamPatch = function(key) {\n return 'received streaming update for flag \"' + key + '\"';\n};\n\nconst debugStreamPatchIgnored = function(key) {\n return 'received streaming update for flag \"' + key + '\" but ignored due to version check';\n};\n\nconst debugStreamDelete = function(key) {\n return 'received streaming deletion for flag \"' + key + '\"';\n};\n\nconst debugStreamDeleteIgnored = function(key) {\n return 'received streaming deletion for flag \"' + key + '\" but ignored due to version check';\n};\n\nconst debugEnqueueingEvent = function(kind) {\n return 'enqueueing \"' + kind + '\" event';\n};\n\nconst debugPostingEvents = function(count) {\n return 'sending ' + count + ' events';\n};\n\nconst debugPostingDiagnosticEvent = function(event) {\n return 'sending diagnostic event (' + event.kind + ')';\n};\n\nconst invalidInspector = (type, name) => `an inspector: \"${name}\" of an invalid type (${type}) was configured`;\n\nconst inspectorMethodError = (type, name) => `an inspector: \"${name}\" of type: \"${type}\" generated an exception`;\n\nconst invalidTagValue = name => `Config option \"${name}\" must only contain letters, numbers, ., _ or -.`;\n\nconst tagValueTooLong = name => `Value of \"${name}\" was longer than 64 characters and was discarded.`;\n\nconst invalidMetricValue = badType =>\n `The track function was called with a non-numeric \"metricValue\" (${badType}), only numeric metric values are supported.`;\n\nmodule.exports = {\n bootstrapInvalid,\n bootstrapOldFormat,\n clientInitialized,\n clientNotReady,\n debugEnqueueingEvent,\n debugPostingDiagnosticEvent,\n debugPostingEvents,\n debugStreamDelete,\n debugStreamDeleteIgnored,\n debugStreamPatch,\n debugStreamPatchIgnored,\n debugStreamPing,\n debugPolling,\n debugStreamPut,\n deprecated,\n environmentNotFound,\n environmentNotSpecified,\n errorFetchingFlags,\n eventCapacityExceeded,\n eventWithoutContext,\n httpErrorMessage,\n httpUnavailable,\n identifyDisabled,\n inspectorMethodError,\n invalidContentType,\n invalidData,\n invalidInspector,\n invalidKey,\n invalidMetricValue,\n invalidContext,\n invalidTagValue,\n localStorageUnavailable,\n networkError,\n optionBelowMinimum,\n streamClosing,\n streamConnecting,\n streamError,\n tagValueTooLong,\n unknownCustomEventKey,\n unknownOption,\n contextNotSpecified,\n unrecoverableStreamError,\n wrongOptionType,\n wrongOptionTypeBoolean,\n};\n","const errors = require('./errors');\nconst { validateLogger } = require('./loggers');\nconst messages = require('./messages');\nconst utils = require('./utils');\n\n// baseOptionDefs should contain an entry for each supported configuration option in the common package.\n// Each entry can have three properties:\n// - \"default\": the default value if any\n// - \"type\": a type constraint used if the type can't be inferred from the default value). The allowable\n// values are \"boolean\", \"string\", \"number\", \"array\", \"object\", \"function\", or several of these OR'd\n// together with \"|\" (\"function|object\").\n// - \"minimum\": minimum value if any for numeric properties\n//\n// The extraOptionDefs parameter to validate() uses the same format.\nconst baseOptionDefs = {\n baseUrl: { default: 'https://app.launchdarkly.com' },\n streamUrl: { default: 'https://clientstream.launchdarkly.com' },\n eventsUrl: { default: 'https://events.launchdarkly.com' },\n sendEvents: { default: true },\n streaming: { type: 'boolean' }, // default for this is undefined, which is different from false\n sendLDHeaders: { default: true },\n requestHeaderTransform: { type: 'function' },\n sendEventsOnlyForVariation: { default: false },\n useReport: { default: false },\n evaluationReasons: { default: false },\n eventCapacity: { default: 100, minimum: 1 },\n flushInterval: { default: 2000, minimum: 2000 },\n samplingInterval: { default: 0, minimum: 0 },\n streamReconnectDelay: { default: 1000, minimum: 0 },\n allAttributesPrivate: { default: false },\n privateAttributes: { default: [] },\n bootstrap: { type: 'string|object' },\n diagnosticRecordingInterval: { default: 900000, minimum: 2000 },\n diagnosticOptOut: { default: false },\n wrapperName: { type: 'string' },\n wrapperVersion: { type: 'string' },\n stateProvider: { type: 'object' }, // not a public option, used internally\n application: { validator: applicationConfigValidator },\n inspectors: { default: [] },\n hooks: { default: [] },\n plugins: { default: [] },\n};\n\n/**\n * Expression to validate characters that are allowed in tag keys and values.\n */\nconst allowedTagCharacters = /^(\\w|\\.|-)+$/;\n\nfunction canonicalizeUrl(url) {\n return url && url.replace(/\\/+$/, '');\n}\n\n/**\n * Verify that a value meets the requirements for a tag value.\n * @param {string} tagValue\n * @param {Object} logger\n */\nfunction validateTagValue(name, tagValue, logger) {\n if (typeof tagValue !== 'string' || !tagValue.match(allowedTagCharacters)) {\n logger.warn(messages.invalidTagValue(name));\n return undefined;\n }\n if (tagValue.length > 64) {\n logger.warn(messages.tagValueTooLong(name));\n return undefined;\n }\n return tagValue;\n}\n\nfunction applicationConfigValidator(name, value, logger) {\n const validated = {};\n if (value.id) {\n validated.id = validateTagValue(`${name}.id`, value.id, logger);\n }\n if (value.version) {\n validated.version = validateTagValue(`${name}.version`, value.version, logger);\n }\n return validated;\n}\n\nfunction validate(options, emitter, extraOptionDefs, logger) {\n const optionDefs = utils.extend({ logger: { default: logger } }, baseOptionDefs, extraOptionDefs);\n\n const deprecatedOptions = {\n // As of the latest major version, there are no deprecated options. Next time we deprecate\n // something, add an item here where the property name is the deprecated name, and the\n // property value is the preferred name if any, or null/undefined if there is no replacement.\n };\n\n function checkDeprecatedOptions(config) {\n const opts = config;\n Object.keys(deprecatedOptions).forEach(oldName => {\n if (opts[oldName] !== undefined) {\n const newName = deprecatedOptions[oldName];\n logger && logger.warn(messages.deprecated(oldName, newName));\n if (newName) {\n if (opts[newName] === undefined) {\n opts[newName] = opts[oldName];\n }\n delete opts[oldName];\n }\n }\n });\n }\n\n function applyDefaults(config) {\n // This works differently from utils.extend() in that it *will not* override a default value\n // if the provided value is explicitly set to null. This provides backward compatibility\n // since in the past we only used the provided values if they were truthy.\n const ret = utils.extend({}, config);\n Object.keys(optionDefs).forEach(name => {\n if (ret[name] === undefined || ret[name] === null) {\n ret[name] = optionDefs[name] && optionDefs[name].default;\n }\n });\n return ret;\n }\n\n function validateTypesAndNames(config) {\n const ret = utils.extend({}, config);\n const typeDescForValue = value => {\n if (value === null) {\n return 'any';\n }\n if (value === undefined) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n const t = typeof value;\n if (t === 'boolean' || t === 'string' || t === 'number' || t === 'function') {\n return t;\n }\n return 'object';\n };\n Object.keys(config).forEach(name => {\n const value = config[name];\n if (value !== null && value !== undefined) {\n const optionDef = optionDefs[name];\n if (optionDef === undefined) {\n reportArgumentError(messages.unknownOption(name));\n } else {\n const expectedType = optionDef.type || typeDescForValue(optionDef.default);\n const validator = optionDef.validator;\n if (validator) {\n const validated = validator(name, config[name], logger);\n if (validated !== undefined) {\n ret[name] = validated;\n } else {\n delete ret[name];\n }\n } else if (expectedType !== 'any') {\n const allowedTypes = expectedType.split('|');\n const actualType = typeDescForValue(value);\n if (allowedTypes.indexOf(actualType) < 0) {\n if (expectedType === 'boolean') {\n ret[name] = !!value;\n reportArgumentError(messages.wrongOptionTypeBoolean(name, actualType));\n } else {\n reportArgumentError(messages.wrongOptionType(name, expectedType, actualType));\n ret[name] = optionDef.default;\n }\n } else {\n if (actualType === 'number' && optionDef.minimum !== undefined && value < optionDef.minimum) {\n reportArgumentError(messages.optionBelowMinimum(name, value, optionDef.minimum));\n ret[name] = optionDef.minimum;\n }\n }\n }\n }\n }\n });\n\n ret.baseUrl = canonicalizeUrl(ret.baseUrl);\n ret.streamUrl = canonicalizeUrl(ret.streamUrl);\n ret.eventsUrl = canonicalizeUrl(ret.eventsUrl);\n\n return ret;\n }\n\n function reportArgumentError(message) {\n utils.onNextTick(() => {\n emitter && emitter.maybeReportError(new errors.LDInvalidArgumentError(message));\n });\n }\n\n let config = utils.extend({}, options || {});\n\n checkDeprecatedOptions(config);\n\n config = applyDefaults(config);\n config = validateTypesAndNames(config);\n validateLogger(config.logger);\n\n return config;\n}\n\n/**\n * Get tags for the specified configuration.\n *\n * If any additional tags are added to the configuration, then the tags from\n * this method should be extended with those.\n * @param {Object} config The already valiated configuration.\n * @returns {Object} The tag configuration.\n */\nfunction getTags(config) {\n const tags = {};\n if (config) {\n if (config.application && config.application.id !== undefined && config.application.id !== null) {\n tags['application-id'] = [config.application.id];\n }\n if (config.application && config.application.version !== undefined && config.application.id !== null) {\n tags['application-version'] = [config.application.version];\n }\n }\n\n return tags;\n}\n\nmodule.exports = {\n baseOptionDefs,\n validate,\n getTags,\n};\n","const { getLDUserAgentString } = require('./utils');\nconst configuration = require('./configuration');\n\nfunction getLDHeaders(platform, options) {\n if (options && !options.sendLDHeaders) {\n return {};\n }\n const h = {};\n h[platform.userAgentHeaderName || 'User-Agent'] = getLDUserAgentString(platform);\n if (options && options.wrapperName) {\n h['X-LaunchDarkly-Wrapper'] = options.wrapperVersion\n ? options.wrapperName + '/' + options.wrapperVersion\n : options.wrapperName;\n }\n const tags = configuration.getTags(options);\n const tagKeys = Object.keys(tags);\n if (tagKeys.length) {\n h['x-launchdarkly-tags'] = tagKeys\n .sort()\n .map(key =>\n Array.isArray(tags[key]) ? tags[key].sort().map(value => `${key}/${value}`) : [`${key}/${tags[key]}`]\n )\n .reduce((flattened, item) => flattened.concat(item), [])\n .join(' ');\n }\n return h;\n}\n\nfunction transformHeaders(headers, options) {\n if (!options || !options.requestHeaderTransform) {\n return headers;\n }\n return options.requestHeaderTransform({ ...headers });\n}\n\nmodule.exports = {\n getLDHeaders,\n transformHeaders,\n};\n","const errors = require('./errors');\nconst utils = require('./utils');\nconst { v1: uuidv1 } = require('uuid');\nconst { getLDHeaders, transformHeaders } = require('./headers');\n\nfunction EventSender(platform, environmentId, options) {\n const baseHeaders = utils.extend({ 'Content-Type': 'application/json' }, getLDHeaders(platform, options));\n const sender = {};\n\n function getResponseInfo(result) {\n const ret = { status: result.status };\n const dateStr = result.header('date');\n if (dateStr) {\n const time = Date.parse(dateStr);\n if (time) {\n ret.serverTime = time;\n }\n }\n return ret;\n }\n\n sender.sendEvents = (events, url, isDiagnostic) => {\n if (!platform.httpRequest) {\n return Promise.resolve();\n }\n\n const jsonBody = JSON.stringify(events);\n const payloadId = isDiagnostic ? null : uuidv1();\n\n function doPostRequest(canRetry) {\n const headers = isDiagnostic\n ? baseHeaders\n : utils.extend({}, baseHeaders, {\n 'X-LaunchDarkly-Event-Schema': '4',\n 'X-LaunchDarkly-Payload-ID': payloadId,\n });\n return platform\n .httpRequest('POST', url, transformHeaders(headers, options), jsonBody)\n .promise.then(result => {\n if (!result) {\n // This was a response from a fire-and-forget request, so we won't have a status.\n return;\n }\n if (result.status >= 400 && errors.isHttpErrorRecoverable(result.status) && canRetry) {\n return doPostRequest(false);\n } else {\n return getResponseInfo(result);\n }\n })\n .catch(() => {\n if (canRetry) {\n return doPostRequest(false);\n }\n return Promise.reject();\n });\n }\n\n return doPostRequest(true).catch(() => {});\n };\n\n return sender;\n}\n\nmodule.exports = EventSender;\n","/**\n * Given some object to serialize product a canonicalized JSON string.\n * https://www.rfc-editor.org/rfc/rfc8785.html\n *\n * We do not support custom toJSON methods on objects. Objects should be limited to basic types.\n *\n * @param {any} object The object to serialize.\n * @param {any[]?} visited The list of objects that have already been visited to avoid cycles.\n * @returns {string} The canonicalized JSON string.\n */\nfunction canonicalize(object, visited = []) {\n // For JavaScript the default JSON serialization will produce canonicalized output for basic types.\n if (object === null || typeof object !== 'object') {\n return JSON.stringify(object);\n }\n\n if (visited.includes(object)) {\n throw new Error('Cycle detected');\n }\n\n if (Array.isArray(object)) {\n const values = object\n .map(item => canonicalize(item, [...visited, object]))\n .map(item => (item === undefined ? 'null' : item));\n return `[${values.join(',')}]`;\n }\n\n const values = Object.keys(object)\n .sort()\n .map(key => {\n const value = canonicalize(object[key], [...visited, object]);\n if (value !== undefined) {\n return `${JSON.stringify(key)}:${value}`;\n }\n return undefined;\n })\n .filter(item => item !== undefined);\n return `{${values.join(',')}}`;\n}\n\nmodule.exports = canonicalize;\n","const { commonBasicLogger } = require('./loggers');\n\n/**\n * Validate a context kind.\n * @param {string} kind\n * @returns true if the kind is valid.\n */\nfunction validKind(kind) {\n return typeof kind === 'string' && kind !== 'kind' && kind.match(/^(\\w|\\.|-)+$/);\n}\n\n/**\n * Perform a check of basic context requirements.\n * @param {Object} context\n * @param {boolean} allowLegacyKey If true, then a legacy user can have an\n * empty or non-string key. A legacy user is a context without a kind.\n * @returns true if the context meets basic requirements.\n */\nfunction checkContext(context, allowLegacyKey) {\n if (context) {\n if (allowLegacyKey && (context.kind === undefined || context.kind === null)) {\n return context.key !== undefined && context.key !== null;\n }\n const key = context.key;\n const kind = context.kind === undefined ? 'user' : context.kind;\n const kindValid = validKind(kind);\n const keyValid = kind === 'multi' || (key !== undefined && key !== null && key !== '');\n if (kind === 'multi') {\n const kinds = Object.keys(context).filter(key => key !== 'kind');\n return (\n keyValid &&\n kinds.every(key => validKind(key)) &&\n kinds.every(key => {\n const contextKey = context[key].key;\n return contextKey !== undefined && contextKey !== null && contextKey !== '';\n })\n );\n }\n return keyValid && kindValid;\n }\n return false;\n}\n\n/**\n * For a given context get a list of context kinds.\n * @param {Object} context\n * @returns {string[]} A list of kinds in the context.\n */\nfunction getContextKinds(context) {\n if (context) {\n if (context.kind === null || context.kind === undefined) {\n return ['user'];\n }\n if (context.kind !== 'multi') {\n return [context.kind];\n }\n return Object.keys(context).filter(kind => kind !== 'kind');\n }\n return [];\n}\n\n/**\n * The partial URL encoding is needed because : is a valid character in context keys.\n *\n * Partial encoding is the replacement of all colon (:) characters with the URL\n * encoded equivalent (%3A) and all percent (%) characters with the URL encoded\n * equivalent (%25).\n * @param {string} key The key to encode.\n * @returns {string} Partially URL encoded key.\n */\nfunction encodeKey(key) {\n if (key.includes('%') || key.includes(':')) {\n return key.replace(/%/g, '%25').replace(/:/g, '%3A');\n }\n return key;\n}\n\nfunction getCanonicalKey(context) {\n if (context) {\n if ((context.kind === undefined || context.kind === null || context.kind === 'user') && context.key) {\n return context.key;\n } else if (context.kind !== 'multi' && context.key) {\n return `${context.kind}:${encodeKey(context.key)}`;\n } else if (context.kind === 'multi') {\n return Object.keys(context)\n .sort()\n .filter(key => key !== 'kind')\n .map(key => `${key}:${encodeKey(context[key].key)}`)\n .join(':');\n }\n }\n}\n\nfunction getContextKeys(context, logger = commonBasicLogger()) {\n if (!context) {\n return undefined;\n }\n\n const keys = {};\n const { kind, key } = context;\n\n switch (kind) {\n case undefined:\n keys.user = `${key}`;\n break;\n case 'multi':\n Object.entries(context)\n .filter(([key]) => key !== 'kind')\n .forEach(([key, value]) => {\n if (value && value.key) {\n keys[key] = value.key;\n }\n });\n break;\n case null:\n logger.warn(`null is not a valid context kind: ${context}`);\n break;\n case '':\n logger.warn(`'' is not a valid context kind: ${context}`);\n break;\n default:\n keys[kind] = `${key}`;\n break;\n }\n\n return keys;\n}\n\nmodule.exports = {\n checkContext,\n getContextKeys,\n getContextKinds,\n getCanonicalKey,\n};\n","const { getContextKinds } = require('./context');\n\nfunction getKinds(event) {\n if (event.context) {\n return getContextKinds(event.context);\n }\n if (event.contextKeys) {\n return Object.keys(event.contextKeys);\n }\n return [];\n}\n\nfunction EventSummarizer() {\n const es = {};\n\n let startDate = 0,\n endDate = 0,\n counters = {},\n contextKinds = {};\n\n es.summarizeEvent = event => {\n if (event.kind === 'feature') {\n const counterKey =\n event.key +\n ':' +\n (event.variation !== null && event.variation !== undefined ? event.variation : '') +\n ':' +\n (event.version !== null && event.version !== undefined ? event.version : '');\n const counterVal = counters[counterKey];\n let kinds = contextKinds[event.key];\n if (!kinds) {\n kinds = new Set();\n contextKinds[event.key] = kinds;\n }\n getKinds(event).forEach(kind => kinds.add(kind));\n\n if (counterVal) {\n counterVal.count = counterVal.count + 1;\n } else {\n counters[counterKey] = {\n count: 1,\n key: event.key,\n version: event.version,\n variation: event.variation,\n value: event.value,\n default: event.default,\n };\n }\n if (startDate === 0 || event.creationDate < startDate) {\n startDate = event.creationDate;\n }\n if (event.creationDate > endDate) {\n endDate = event.creationDate;\n }\n }\n };\n\n es.getSummary = () => {\n const flagsOut = {};\n let empty = true;\n for (const c of Object.values(counters)) {\n let flag = flagsOut[c.key];\n if (!flag) {\n flag = {\n default: c.default,\n counters: [],\n contextKinds: [...contextKinds[c.key]],\n };\n flagsOut[c.key] = flag;\n }\n const counterOut = {\n value: c.value,\n count: c.count,\n };\n if (c.variation !== undefined && c.variation !== null) {\n counterOut.variation = c.variation;\n }\n if (c.version !== undefined && c.version !== null) {\n counterOut.version = c.version;\n } else {\n counterOut.unknown = true;\n }\n flag.counters.push(counterOut);\n empty = false;\n }\n return empty\n ? null\n : {\n startDate,\n endDate,\n features: flagsOut,\n kind: 'summary',\n };\n };\n\n es.clearSummary = () => {\n startDate = 0;\n endDate = 0;\n counters = {};\n contextKinds = {};\n };\n\n return es;\n}\n\nmodule.exports = EventSummarizer;\n","const canonicalize = require('./canonicalize');\nconst EventSummarizer = require('./EventSummarizer');\n\n/**\n * Construct a multi-event summarizer. This summarizer produces a summary event for each unique context.\n * @param {{filter: (context: any) => any}} contextFilter\n */\nfunction MultiEventSummarizer(contextFilter) {\n let summarizers = {};\n let contexts = {};\n\n /**\n * Summarize the given event.\n * @param {{\n * kind: string,\n * context?: any,\n * }} event\n */\n function summarizeEvent(event) {\n if (event.kind === 'feature') {\n const key = canonicalize(event.context);\n if (!key) {\n return;\n }\n\n let summarizer = summarizers[key];\n if (!summarizer) {\n summarizers[key] = EventSummarizer();\n summarizer = summarizers[key];\n contexts[key] = event.context;\n }\n\n summarizer.summarizeEvent(event);\n }\n }\n\n /**\n * Get the summaries of the events that have been summarized.\n * @returns {any[]}\n */\n function getSummaries() {\n const summarizersToFlush = summarizers;\n const contextsForSummaries = contexts;\n\n summarizers = {};\n contexts = {};\n return Object.entries(summarizersToFlush).map(([key, summarizer]) => {\n const summary = summarizer.getSummary();\n summary.context = contextFilter.filter(contextsForSummaries[key]);\n return summary;\n });\n }\n\n return {\n summarizeEvent,\n getSummaries,\n };\n}\n\nmodule.exports = MultiEventSummarizer;\n","/**\n * Take a key string and escape the characters to allow it to be used as a reference.\n * @param {string} key\n * @returns {string} The processed key.\n */\nfunction processEscapeCharacters(key) {\n return key.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * @param {string} reference The reference to get the components of.\n * @returns {string[]} The components of the reference. Escape characters will be converted to their representative values.\n */\nfunction getComponents(reference) {\n const referenceWithoutPrefix = reference.startsWith('/') ? reference.substring(1) : reference;\n return referenceWithoutPrefix\n .split('/')\n .map(component => (component.indexOf('~') >= 0 ? component.replace(/~1/g, '/').replace(/~0/g, '~') : component));\n}\n\n/**\n * @param {string} reference The reference to check if it is a literal.\n * @returns true if the reference is a literal.\n */\nfunction isLiteral(reference) {\n return !reference.startsWith('/');\n}\n\n/**\n * Compare two references and determine if they are equivalent.\n * @param {string} a\n * @param {string} b\n */\nfunction compare(a, b) {\n const aIsLiteral = isLiteral(a);\n const bIsLiteral = isLiteral(b);\n if (aIsLiteral && bIsLiteral) {\n return a === b;\n }\n if (aIsLiteral) {\n const bComponents = getComponents(b);\n if (bComponents.length !== 1) {\n return false;\n }\n return a === bComponents[0];\n }\n if (bIsLiteral) {\n const aComponents = getComponents(a);\n if (aComponents.length !== 1) {\n return false;\n }\n return b === aComponents[0];\n }\n return a === b;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns The two strings joined by '/'.\n */\nfunction join(a, b) {\n return `${a}/${b}`;\n}\n\n/**\n * There are cases where a field could have been named with a preceeding '/'.\n * If that attribute was private, then the literal would appear to be a reference.\n * This method can be used to convert a literal to a reference in such situations.\n * @param {string} literal The literal to convert to a reference.\n * @returns A literal which has been converted to a reference.\n */\nfunction literalToReference(literal) {\n return `/${processEscapeCharacters(literal)}`;\n}\n\n/**\n * Clone an object excluding the values referenced by a list of references.\n * @param {Object} target The object to clone.\n * @param {string[]} references A list of references from the cloned object.\n * @returns {{cloned: Object, excluded: string[]}} The cloned object and a list of excluded values.\n */\nfunction cloneExcluding(target, references) {\n const stack = [];\n const cloned = {};\n const excluded = [];\n\n stack.push(\n ...Object.keys(target).map(key => ({\n key,\n ptr: literalToReference(key),\n source: target,\n parent: cloned,\n visited: [target],\n }))\n );\n\n while (stack.length) {\n const item = stack.pop();\n if (!references.some(ptr => compare(ptr, item.ptr))) {\n const value = item.source[item.key];\n\n // Handle null because it overlaps with object, which we will want to handle later.\n if (value === null) {\n item.parent[item.key] = value;\n } else if (Array.isArray(value)) {\n item.parent[item.key] = [...value];\n } else if (typeof value === 'object') {\n //Arrays and null must already be handled.\n\n //Prevent cycles by not visiting the same object\n //with in the same branch. Parallel branches\n //may contain the same object.\n if (item.visited.includes(value)) {\n continue;\n }\n\n item.parent[item.key] = {};\n\n stack.push(\n ...Object.keys(value).map(key => ({\n key,\n ptr: join(item.ptr, processEscapeCharacters(key)),\n source: value,\n parent: item.parent[item.key],\n visited: [...item.visited, value],\n }))\n );\n } else {\n item.parent[item.key] = value;\n }\n } else {\n excluded.push(item.ptr);\n }\n }\n return { cloned, excluded: excluded.sort() };\n}\n\nmodule.exports = {\n cloneExcluding,\n compare,\n literalToReference,\n};\n","const AttributeReference = require('./attributeReference');\n\nfunction ContextFilter(config) {\n const filter = {};\n\n const allAttributesPrivate = config.allAttributesPrivate;\n const privateAttributes = config.privateAttributes || [];\n\n // These attributes cannot be removed via a private attribute.\n const protectedAttributes = ['key', 'kind', '_meta', 'anonymous'];\n\n const legacyTopLevelCopyAttributes = ['name', 'ip', 'firstName', 'lastName', 'email', 'avatar', 'country'];\n\n /**\n * For the given context and configuration get a list of attributes to filter.\n * @param {Object} context\n * @returns {string[]} A list of the attributes to filter.\n */\n const getAttributesToFilter = (context, redactAnonymous) =>\n (allAttributesPrivate || (redactAnonymous && context.anonymous)\n ? Object.keys(context)\n : [...privateAttributes, ...((context._meta && context._meta.privateAttributes) || [])]\n ).filter(attr => !protectedAttributes.some(protectedAttr => AttributeReference.compare(attr, protectedAttr)));\n\n /**\n * @param {Object} context\n * @param {boolean} redactAnonymous\n * @returns {Object} A copy of the context with private attributes removed,\n * and the redactedAttributes meta populated.\n */\n const filterSingleKind = (context, redactAnonymous) => {\n if (typeof context !== 'object' || context === null || Array.isArray(context)) {\n return undefined;\n }\n\n const { cloned, excluded } = AttributeReference.cloneExcluding(\n context,\n getAttributesToFilter(context, redactAnonymous)\n );\n cloned.key = String(cloned.key);\n if (excluded.length) {\n if (!cloned._meta) {\n cloned._meta = {};\n }\n cloned._meta.redactedAttributes = excluded;\n }\n if (cloned._meta) {\n delete cloned._meta['privateAttributes'];\n if (Object.keys(cloned._meta).length === 0) {\n delete cloned._meta;\n }\n }\n // Make sure anonymous is boolean if present.\n // Null counts as present, and would be falsy, which is the default.\n if (cloned.anonymous !== undefined) {\n cloned.anonymous = !!cloned.anonymous;\n }\n\n return cloned;\n };\n\n /**\n * @param {Object} context\n * @param {boolean} redactAnonymous\n * @returns {Object} A copy of the context with the private attributes removed,\n * and the redactedAttributes meta populated for each sub-context.\n */\n const filterMultiKind = (context, redactAnonymous) => {\n const filtered = {\n kind: context.kind,\n };\n const contextKeys = Object.keys(context);\n\n for (const contextKey of contextKeys) {\n if (contextKey !== 'kind') {\n const filteredContext = filterSingleKind(context[contextKey], redactAnonymous);\n if (filteredContext) {\n filtered[contextKey] = filteredContext;\n }\n }\n }\n return filtered;\n };\n\n /**\n * Convert the LDUser object into an LDContext object.\n * @param {Object} user The LDUser to produce an LDContext for.\n * @returns {Object} A single kind context based on the provided user.\n */\n const legacyToSingleKind = user => {\n const filtered = {\n /* Destructure custom items into the top level.\n Duplicate keys will be overridden by previously\n top level items.\n */\n ...(user.custom || {}),\n\n // Implicity a user kind.\n kind: 'user',\n\n key: user.key,\n };\n\n if (user.anonymous !== undefined) {\n filtered.anonymous = !!user.anonymous;\n }\n\n // Copy top level keys and convert them to strings.\n // Remove keys that may have been destructured from `custom`.\n for (const key of legacyTopLevelCopyAttributes) {\n delete filtered[key];\n if (user[key] !== undefined && user[key] !== null) {\n filtered[key] = String(user[key]);\n }\n }\n\n if (user.privateAttributeNames !== undefined && user.privateAttributeNames !== null) {\n filtered._meta = filtered._meta || {};\n // If any private attributes started with '/' we need to convert them to references, otherwise the '/' will\n // cause the literal to incorrectly be treated as a reference.\n filtered._meta.privateAttributes = user.privateAttributeNames.map(literal =>\n literal.startsWith('/') ? AttributeReference.literalToReference(literal) : literal\n );\n }\n\n return filtered;\n };\n\n filter.filter = (context, redactAnonymous = false) => {\n if (context.kind === undefined || context.kind === null) {\n return filterSingleKind(legacyToSingleKind(context), redactAnonymous);\n } else if (context.kind === 'multi') {\n return filterMultiKind(context, redactAnonymous);\n } else {\n return filterSingleKind(context, redactAnonymous);\n }\n };\n\n return filter;\n}\n\nmodule.exports = ContextFilter;\n","const EventSender = require('./EventSender');\nconst MultiEventSummarizer = require('./MultiEventSummarizer');\nconst ContextFilter = require('./ContextFilter');\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst utils = require('./utils');\nconst { getContextKeys } = require('./context');\n\nfunction EventProcessor(\n platform,\n options,\n environmentId,\n diagnosticsAccumulator = null,\n emitter = null,\n sender = null\n) {\n const processor = {};\n const eventSender = sender || EventSender(platform, environmentId, options);\n const mainEventsUrl = utils.appendUrlPath(options.eventsUrl, '/events/bulk/' + environmentId);\n const contextFilter = ContextFilter(options);\n const summarizer = MultiEventSummarizer(contextFilter);\n const samplingInterval = options.samplingInterval;\n const eventCapacity = options.eventCapacity;\n const flushInterval = options.flushInterval;\n const logger = options.logger;\n let queue = [];\n let lastKnownPastTime = 0;\n let disabled = false;\n let exceededCapacity = false;\n let flushTimer;\n\n function shouldSampleEvent() {\n return samplingInterval === 0 || Math.floor(Math.random() * samplingInterval) === 0;\n }\n\n function shouldDebugEvent(e) {\n if (e.debugEventsUntilDate) {\n // The \"last known past time\" comes from the last HTTP response we got from the server.\n // In case the client's time is set wrong, at least we know that any expiration date\n // earlier than that point is definitely in the past. If there's any discrepancy, we\n // want to err on the side of cutting off event debugging sooner.\n return e.debugEventsUntilDate > lastKnownPastTime && e.debugEventsUntilDate > new Date().getTime();\n }\n return false;\n }\n\n // Transform an event from its internal format to the format we use when sending a payload.\n function makeOutputEvent(e) {\n const ret = utils.extend({}, e);\n\n // Identify, feature, and custom events should all include the full context.\n // Debug events do as well, but are not handled by this code path.\n if (e.kind === 'identify' || e.kind === 'feature' || e.kind === 'custom') {\n ret.context = contextFilter.filter(e.context);\n } else {\n ret.contextKeys = getContextKeysFromEvent(e);\n delete ret['context'];\n }\n\n if (e.kind === 'feature') {\n delete ret['trackEvents'];\n delete ret['debugEventsUntilDate'];\n }\n return ret;\n }\n\n function getContextKeysFromEvent(event) {\n return getContextKeys(event.context, logger);\n }\n\n function addToOutbox(event) {\n if (queue.length < eventCapacity) {\n queue.push(event);\n exceededCapacity = false;\n } else {\n if (!exceededCapacity) {\n exceededCapacity = true;\n logger.warn(messages.eventCapacityExceeded());\n }\n if (diagnosticsAccumulator) {\n // For diagnostic events, we track how many times we had to drop an event due to exceeding the capacity.\n diagnosticsAccumulator.incrementDroppedEvents();\n }\n }\n }\n\n processor.enqueue = function(event) {\n if (disabled) {\n return;\n }\n let addFullEvent = false;\n let addDebugEvent = false;\n\n // Add event to the summary counters if appropriate\n summarizer.summarizeEvent(event);\n\n // Decide whether to add the event to the payload. Feature events may be added twice, once for\n // the event (if tracked) and once for debugging.\n if (event.kind === 'feature') {\n if (shouldSampleEvent()) {\n addFullEvent = !!event.trackEvents;\n addDebugEvent = shouldDebugEvent(event);\n }\n } else {\n addFullEvent = shouldSampleEvent();\n }\n\n if (addFullEvent) {\n addToOutbox(makeOutputEvent(event));\n }\n if (addDebugEvent) {\n const debugEvent = utils.extend({}, event, { kind: 'debug' });\n debugEvent.context = contextFilter.filter(debugEvent.context);\n delete debugEvent['trackEvents'];\n delete debugEvent['debugEventsUntilDate'];\n addToOutbox(debugEvent);\n }\n };\n\n processor.flush = async function() {\n if (disabled) {\n return Promise.resolve();\n }\n const eventsToSend = queue;\n const summaries = summarizer.getSummaries();\n\n summaries.forEach(summary => {\n if (Object.keys(summary.features).length) {\n eventsToSend.push(summary);\n }\n });\n\n if (diagnosticsAccumulator) {\n // For diagnostic events, we record how many events were in the queue at the last flush (since \"how\n // many events happened to be in the queue at the moment we decided to send a diagnostic event\" would\n // not be a very useful statistic).\n diagnosticsAccumulator.setEventsInLastBatch(eventsToSend.length);\n }\n if (eventsToSend.length === 0) {\n return Promise.resolve();\n }\n queue = [];\n logger.debug(messages.debugPostingEvents(eventsToSend.length));\n return eventSender.sendEvents(eventsToSend, mainEventsUrl).then(responseInfo => {\n if (responseInfo) {\n if (responseInfo.serverTime) {\n lastKnownPastTime = responseInfo.serverTime;\n }\n if (!errors.isHttpErrorRecoverable(responseInfo.status)) {\n disabled = true;\n }\n if (responseInfo.status >= 400) {\n utils.onNextTick(() => {\n emitter.maybeReportError(\n new errors.LDUnexpectedResponseError(\n messages.httpErrorMessage(responseInfo.status, 'event posting', 'some events were dropped')\n )\n );\n });\n }\n }\n });\n };\n\n processor.start = function() {\n const flushTick = () => {\n processor.flush();\n flushTimer = setTimeout(flushTick, flushInterval);\n };\n flushTimer = setTimeout(flushTick, flushInterval);\n };\n\n processor.stop = function() {\n clearTimeout(flushTimer);\n };\n\n return processor;\n}\n\nmodule.exports = EventProcessor;\n","function EventEmitter(logger) {\n const emitter = {};\n const events = {};\n\n const listeningTo = event => !!events[event];\n\n emitter.on = function(event, handler, context) {\n events[event] = events[event] || [];\n events[event] = events[event].concat({\n handler: handler,\n context: context,\n });\n };\n\n emitter.off = function(event, handler, context) {\n if (!events[event]) {\n return;\n }\n for (let i = 0; i < events[event].length; i++) {\n if (events[event][i].handler === handler && events[event][i].context === context) {\n events[event] = events[event].slice(0, i).concat(events[event].slice(i + 1));\n }\n }\n };\n\n emitter.emit = function(event) {\n if (!events[event]) {\n return;\n }\n // Copy the list of handlers before iterating, in case any handler adds or removes another handler.\n // Any such changes should not affect what we do here-- we want to notify every handler that existed\n // at the moment that the event was fired.\n const copiedHandlers = events[event].slice(0);\n for (let i = 0; i < copiedHandlers.length; i++) {\n copiedHandlers[i].handler.apply(copiedHandlers[i].context, Array.prototype.slice.call(arguments, 1));\n }\n };\n\n emitter.getEvents = function() {\n return Object.keys(events);\n };\n\n emitter.getEventListenerCount = function(event) {\n return events[event] ? events[event].length : 0;\n };\n\n emitter.maybeReportError = function(error) {\n if (!error) {\n return;\n }\n if (listeningTo('error')) {\n this.emit('error', error);\n } else {\n (logger || console).error(error.message);\n }\n };\n return emitter;\n}\n\nmodule.exports = EventEmitter;\n","// This file provides an abstraction of the client's startup state.\n//\n// Startup can either succeed or fail exactly once; calling signalSuccess() or signalFailure()\n// after that point has no effect.\n//\n// On success, we fire both an \"initialized\" event and a \"ready\" event. Both the waitForInitialization()\n// promise and the waitUntilReady() promise are resolved in this case.\n//\n// On failure, we fire both a \"failed\" event (with the error as a parameter) and a \"ready\" event.\n// The waitForInitialization() promise is rejected, but the waitUntilReady() promise is resolved.\n//\n// To complicate things, we must *not* create the waitForInitialization() promise unless it is\n// requested, because otherwise failures would cause an *unhandled* rejection which can be a\n// serious problem in some environments. So we use a somewhat roundabout system for tracking the\n// initialization state and lazily creating this promise.\n\nconst readyEvent = 'ready',\n successEvent = 'initialized',\n failureEvent = 'failed';\n\nfunction InitializationStateTracker(eventEmitter) {\n let succeeded = false,\n failed = false,\n failureValue = null,\n initializationPromise = null;\n\n const readyPromise = new Promise(resolve => {\n const onReady = () => {\n eventEmitter.off(readyEvent, onReady); // we can't use \"once\" because it's not available on some JS platforms\n resolve();\n };\n eventEmitter.on(readyEvent, onReady);\n }).catch(() => {}); // this Promise should never be rejected, but the catch handler is a safety measure\n\n return {\n getInitializationPromise: () => {\n if (initializationPromise) {\n return initializationPromise;\n }\n if (succeeded) {\n return Promise.resolve();\n }\n if (failed) {\n return Promise.reject(failureValue);\n }\n initializationPromise = new Promise((resolve, reject) => {\n const onSuccess = () => {\n eventEmitter.off(successEvent, onSuccess);\n resolve();\n };\n const onFailure = err => {\n eventEmitter.off(failureEvent, onFailure);\n reject(err);\n };\n eventEmitter.on(successEvent, onSuccess);\n eventEmitter.on(failureEvent, onFailure);\n });\n return initializationPromise;\n },\n\n getReadyPromise: () => readyPromise,\n\n signalSuccess: () => {\n if (!succeeded && !failed) {\n succeeded = true;\n eventEmitter.emit(successEvent);\n eventEmitter.emit(readyEvent);\n }\n },\n\n signalFailure: err => {\n if (!succeeded && !failed) {\n failed = true;\n failureValue = err;\n eventEmitter.emit(failureEvent, err);\n eventEmitter.emit(readyEvent);\n }\n eventEmitter.maybeReportError(err); // the \"error\" event can be emitted more than once, unlike the others\n },\n };\n}\n\nmodule.exports = InitializationStateTracker;\n","const utils = require('./utils');\n\nfunction PersistentFlagStore(storage, environment, hash, ident) {\n const store = {};\n\n function getFlagsKey() {\n let key = '';\n const context = ident.getContext();\n if (context) {\n key = hash || utils.btoa(JSON.stringify(context));\n }\n return 'ld:' + environment + ':' + key;\n }\n\n // Returns a Promise which will be resolved with a parsed JSON value if a stored value was available,\n // or resolved with null if there was no value or if storage was not available.\n store.loadFlags = () =>\n storage.get(getFlagsKey()).then(dataStr => {\n if (dataStr === null || dataStr === undefined) {\n return null;\n }\n try {\n let data = JSON.parse(dataStr);\n if (data) {\n const schema = data.$schema;\n if (schema === undefined || schema < 1) {\n data = utils.transformValuesToVersionedValues(data);\n } else {\n delete data['$schema'];\n }\n }\n return data;\n } catch (ex) {\n return store.clearFlags().then(() => null);\n }\n });\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n store.saveFlags = flags => {\n const data = utils.extend({}, flags, { $schema: 1 });\n return storage.set(getFlagsKey(), JSON.stringify(data));\n };\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n store.clearFlags = () => storage.clear(getFlagsKey());\n\n return store;\n}\n\nmodule.exports = PersistentFlagStore;\n","const messages = require('./messages');\n\n// The localStorageProvider is provided by the platform object. It should have the following\n// methods, each of which should return a Promise:\n// - get(key): Gets the string value, if any, for the given key\n// - set(key, value): Stores a string value for the given key\n// - remove(key): Removes the given key\n//\n// Storage is just a light wrapper of the localStorageProvider, adding error handling and\n// ensuring that we don't call it if it's unavailable. The get method will simply resolve\n// with an undefined value if there is an error or if there is no localStorageProvider.\n// None of the promises returned by Storage will ever be rejected.\n//\n// It is always possible that the underlying platform storage mechanism might fail or be\n// disabled. If so, it's likely that it will keep failing, so we will only log one warning\n// instead of repetitive warnings.\nfunction PersistentStorage(localStorageProvider, logger) {\n const storage = {};\n let loggedError = false;\n\n const logError = err => {\n if (!loggedError) {\n loggedError = true;\n logger.warn(messages.localStorageUnavailable(err));\n }\n };\n\n storage.isEnabled = () => !!localStorageProvider;\n\n // Resolves with a value, or undefined if storage is unavailable. Never rejects.\n storage.get = key =>\n new Promise(resolve => {\n if (!localStorageProvider) {\n resolve(undefined);\n return;\n }\n localStorageProvider\n .get(key)\n .then(resolve)\n .catch(err => {\n logError(err);\n resolve(undefined);\n });\n });\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n storage.set = (key, value) =>\n new Promise(resolve => {\n if (!localStorageProvider) {\n resolve(false);\n return;\n }\n localStorageProvider\n .set(key, value)\n .then(() => resolve(true))\n .catch(err => {\n logError(err);\n resolve(false);\n });\n });\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n storage.clear = key =>\n new Promise(resolve => {\n if (!localStorageProvider) {\n resolve(false);\n return;\n }\n localStorageProvider\n .clear(key)\n .then(() => resolve(true))\n .catch(err => {\n logError(err);\n resolve(false);\n });\n });\n\n return storage;\n}\n\nmodule.exports = PersistentStorage;\n","const messages = require('./messages');\nconst { appendUrlPath, base64URLEncode, objectHasOwnProperty } = require('./utils');\nconst { getLDHeaders, transformHeaders } = require('./headers');\nconst { isHttpErrorRecoverable } = require('./errors');\n\n// The underlying event source implementation is abstracted via the platform object, which should\n// have these three properties:\n// eventSourceFactory(): a function that takes a URL and optional config object and returns an object\n// with the same methods as the regular HTML5 EventSource object. The properties in the config\n// object are those supported by the launchdarkly-eventsource package; browser EventSource\n// implementations don't have any config options.\n// eventSourceIsActive(): a function that takes an EventSource-compatible object and returns true if\n// it is in an active state (connected or connecting).\n// eventSourceAllowsReport: true if REPORT is supported.\n\n// The read timeout for the stream is a fixed value that is set to be slightly longer than the expected\n// interval between heartbeats from the LaunchDarkly streaming server. If this amount of time elapses\n// with no new data, the connection will be cycled.\nconst streamReadTimeoutMillis = 5 * 60 * 1000; // 5 minutes\nconst maxRetryDelay = 30 * 1000; // Maximum retry delay 30 seconds.\nconst jitterRatio = 0.5; // Delay should be 50%-100% of calculated time.\n\nfunction Stream(platform, config, environment, diagnosticsAccumulator) {\n const baseUrl = config.streamUrl;\n const logger = config.logger;\n const stream = {};\n const evalUrlPrefix = appendUrlPath(baseUrl, '/eval/' + environment);\n const useReport = config.useReport;\n const withReasons = config.evaluationReasons;\n const baseReconnectDelay = config.streamReconnectDelay;\n const headers = getLDHeaders(platform, config);\n let firstConnectionErrorLogged = false;\n let es = null;\n let reconnectTimeoutReference = null;\n let connectionAttemptStartTime;\n let context = null;\n let hash = null;\n let handlers = null;\n let retryCount = 0;\n\n function backoff() {\n const delay = baseReconnectDelay * Math.pow(2, retryCount);\n return delay > maxRetryDelay ? maxRetryDelay : delay;\n }\n\n function jitter(computedDelayMillis) {\n return computedDelayMillis - Math.trunc(Math.random() * jitterRatio * computedDelayMillis);\n }\n\n function getNextRetryDelay() {\n const delay = jitter(backoff());\n retryCount += 1;\n return delay;\n }\n\n stream.connect = function(newContext, newHash, newHandlers) {\n context = newContext;\n hash = newHash;\n handlers = {};\n for (const key in newHandlers || {}) {\n handlers[key] = function(e) {\n // Reset the state for logging the first connection error so that the first\n // connection error following a successful connection will once again be logged.\n // We will decorate *all* handlers to do this to keep this abstraction agnostic\n // for different stream implementations.\n firstConnectionErrorLogged = false;\n logConnectionResult(true);\n newHandlers[key] && newHandlers[key](e);\n };\n }\n tryConnect();\n };\n\n stream.disconnect = function() {\n clearTimeout(reconnectTimeoutReference);\n reconnectTimeoutReference = null;\n closeConnection();\n };\n\n stream.isConnected = function() {\n return !!(es && platform.eventSourceIsActive && platform.eventSourceIsActive(es));\n };\n\n function handleError(err) {\n // The event source may not produce a status. But the LaunchDarkly\n // polyfill can. If we can get the status, then we should stop retrying\n // on certain error codes.\n if (err.status && typeof err.status === 'number' && !isHttpErrorRecoverable(err.status)) {\n // If we encounter an unrecoverable condition, then we do not want to\n // retry anymore.\n closeConnection();\n logger.error(messages.unrecoverableStreamError(err));\n // Ensure any pending retry attempts are not done.\n if (reconnectTimeoutReference) {\n clearTimeout(reconnectTimeoutReference);\n reconnectTimeoutReference = null;\n }\n return;\n }\n\n const delay = getNextRetryDelay();\n\n if (!firstConnectionErrorLogged) {\n logger.warn(messages.streamError(err, delay));\n firstConnectionErrorLogged = true;\n }\n logConnectionResult(false);\n closeConnection();\n tryConnect(delay);\n }\n\n function tryConnect(delay) {\n if (!reconnectTimeoutReference) {\n if (delay) {\n reconnectTimeoutReference = setTimeout(openConnection, delay);\n } else {\n openConnection();\n }\n }\n }\n\n function openConnection() {\n reconnectTimeoutReference = null;\n let url;\n let query = '';\n const options = { headers, readTimeoutMillis: streamReadTimeoutMillis };\n if (platform.eventSourceFactory) {\n if (hash !== null && hash !== undefined) {\n query = 'h=' + hash;\n }\n if (useReport) {\n if (platform.eventSourceAllowsReport) {\n url = evalUrlPrefix;\n options.method = 'REPORT';\n options.headers['Content-Type'] = 'application/json';\n options.body = JSON.stringify(context);\n } else {\n // if we can't do REPORT, fall back to the old ping-based stream\n url = appendUrlPath(baseUrl, '/ping/' + environment);\n query = '';\n }\n } else {\n url = evalUrlPrefix + '/' + base64URLEncode(JSON.stringify(context));\n }\n options.headers = transformHeaders(options.headers, config);\n if (withReasons) {\n query = query + (query ? '&' : '') + 'withReasons=true';\n }\n url = url + (query ? '?' : '') + query;\n\n closeConnection();\n logger.info(messages.streamConnecting(url));\n logConnectionStarted();\n\n es = platform.eventSourceFactory(url, options);\n for (const key in handlers) {\n if (objectHasOwnProperty(handlers, key)) {\n es.addEventListener(key, handlers[key]);\n }\n }\n\n es.onerror = handleError;\n\n es.onopen = () => {\n // If the connection is a success, then reset the retryCount.\n retryCount = 0;\n };\n }\n }\n\n function closeConnection() {\n if (es) {\n logger.info(messages.streamClosing());\n es.close();\n es = null;\n }\n }\n\n function logConnectionStarted() {\n connectionAttemptStartTime = new Date().getTime();\n }\n\n function logConnectionResult(success) {\n if (connectionAttemptStartTime && diagnosticsAccumulator) {\n diagnosticsAccumulator.recordStreamInit(\n connectionAttemptStartTime,\n !success,\n new Date().getTime() - connectionAttemptStartTime\n );\n }\n connectionAttemptStartTime = null;\n }\n\n return stream;\n}\n\nmodule.exports = Stream;\n","// This function allows a series of Promises to be coalesced such that only the most recently\n// added one actually matters. For instance, if several HTTP requests are made to the same\n// endpoint and we want to ensure that whoever made each one always gets the latest data, each\n// can be passed to addPromise (on the same coalescer) and each caller can wait on the\n// coalescer.resultPromise; all three will then receive the result (or error) from the *last*\n// request, and the results of the first two will be discarded.\n//\n// The cancelFn callback, if present, will be called whenever an existing promise is being\n// discarded. This can be used for instance to abort an HTTP request that's now obsolete.\n//\n// The finallyFn callback, if present, is called on completion of the whole thing. This is\n// different from calling coalescer.resultPromise.finally() because it is executed before any\n// other handlers. Its purpose is to tell the caller that this coalescer should no longer be used.\n\nfunction promiseCoalescer(finallyFn) {\n let currentPromise;\n let currentCancelFn;\n let finalResolve;\n let finalReject;\n\n const coalescer = {};\n\n coalescer.addPromise = (p, cancelFn) => {\n currentPromise = p;\n currentCancelFn && currentCancelFn();\n currentCancelFn = cancelFn;\n\n p.then(\n result => {\n if (currentPromise === p) {\n finalResolve(result);\n finallyFn && finallyFn();\n }\n },\n error => {\n if (currentPromise === p) {\n finalReject(error);\n finallyFn && finallyFn();\n }\n }\n );\n };\n\n coalescer.resultPromise = new Promise((resolve, reject) => {\n finalResolve = resolve;\n finalReject = reject;\n });\n\n return coalescer;\n}\n\nmodule.exports = promiseCoalescer;\n","const utils = require('./utils');\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst promiseCoalescer = require('./promiseCoalescer');\nconst { transformHeaders, getLDHeaders } = require('./headers');\n\nconst jsonContentType = 'application/json';\n\nfunction getResponseError(result) {\n if (result.status === 404) {\n return new errors.LDInvalidEnvironmentIdError(messages.environmentNotFound());\n } else {\n return new errors.LDFlagFetchError(messages.errorFetchingFlags(result.statusText || String(result.status)));\n }\n}\n\nfunction Requestor(platform, options, environment) {\n const baseUrl = options.baseUrl;\n const useReport = options.useReport;\n const withReasons = options.evaluationReasons;\n const logger = options.logger;\n\n const requestor = {};\n\n const activeRequests = {}; // map of URLs to promiseCoalescers\n\n function fetchJSON(endpoint, body) {\n if (!platform.httpRequest) {\n return new Promise((resolve, reject) => {\n reject(new errors.LDFlagFetchError(messages.httpUnavailable()));\n });\n }\n\n const method = body ? 'REPORT' : 'GET';\n const headers = getLDHeaders(platform, options);\n if (body) {\n headers['Content-Type'] = jsonContentType;\n }\n\n let coalescer = activeRequests[endpoint];\n if (!coalescer) {\n coalescer = promiseCoalescer(() => {\n // this will be called once there are no more active requests for the same endpoint\n delete activeRequests[endpoint];\n });\n activeRequests[endpoint] = coalescer;\n }\n\n const req = platform.httpRequest(method, endpoint, transformHeaders(headers, options), body);\n const p = req.promise.then(\n result => {\n if (result.status === 200) {\n // We're using substring here because using startsWith would require a polyfill in IE.\n if (\n result.header('content-type') &&\n result.header('content-type').substring(0, jsonContentType.length) === jsonContentType\n ) {\n return JSON.parse(result.body);\n } else {\n const message = messages.invalidContentType(result.header('content-type') || '');\n return Promise.reject(new errors.LDFlagFetchError(message));\n }\n } else {\n return Promise.reject(getResponseError(result));\n }\n },\n e => Promise.reject(new errors.LDFlagFetchError(messages.networkError(e)))\n );\n coalescer.addPromise(p, () => {\n // this will be called if another request for the same endpoint supersedes this one\n req.cancel && req.cancel();\n });\n return coalescer.resultPromise;\n }\n\n // Performs a GET request to an arbitrary path under baseUrl. Returns a Promise which will resolve\n // with the parsed JSON response, or will be rejected if the request failed.\n requestor.fetchJSON = function(path) {\n return fetchJSON(utils.appendUrlPath(baseUrl, path), null);\n };\n\n // Requests the current state of all flags for the given context from LaunchDarkly. Returns a Promise\n // which will resolve with the parsed JSON response, or will be rejected if the request failed.\n requestor.fetchFlagSettings = function(context, hash) {\n let data;\n let endpoint;\n let query = '';\n let body;\n\n if (useReport) {\n endpoint = [baseUrl, '/sdk/evalx/', environment, '/context'].join('');\n body = JSON.stringify(context);\n } else {\n data = utils.base64URLEncode(JSON.stringify(context));\n endpoint = [baseUrl, '/sdk/evalx/', environment, '/contexts/', data].join('');\n }\n if (hash) {\n query = 'h=' + hash;\n }\n if (withReasons) {\n query = query + (query ? '&' : '') + 'withReasons=true';\n }\n endpoint = endpoint + (query ? '?' : '') + query;\n logger.debug(messages.debugPolling(endpoint));\n\n return fetchJSON(endpoint, body);\n };\n\n return requestor;\n}\n\nmodule.exports = Requestor;\n","const utils = require('./utils');\n\nfunction Identity(initialContext, onChange) {\n const ident = {};\n let context;\n\n ident.setContext = function(c) {\n context = utils.sanitizeContext(c);\n if (context && onChange) {\n onChange(utils.clone(context));\n }\n };\n\n ident.getContext = function() {\n return context ? utils.clone(context) : null;\n };\n\n if (initialContext) {\n ident.setContext(initialContext);\n }\n\n return ident;\n}\n\nmodule.exports = Identity;\n","const { v1: uuidv1 } = require('uuid');\nconst { getContextKinds } = require('./context');\n\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst utils = require('./utils');\n\nconst ldUserIdKey = 'ld:$anonUserId';\n\n/**\n * Create an object which can process a context and populate any required keys\n * for anonymous objects.\n *\n * @param {Object} persistentStorage The persistent storage from which to store\n * and access persisted anonymous context keys.\n * @returns An AnonymousContextProcessor.\n */\nfunction AnonymousContextProcessor(persistentStorage) {\n function getContextKeyIdString(kind) {\n if (kind === undefined || kind === null || kind === 'user') {\n return ldUserIdKey;\n }\n return `ld:$contextKey:${kind}`;\n }\n\n function getCachedContextKey(kind) {\n return persistentStorage.get(getContextKeyIdString(kind));\n }\n\n function setCachedContextKey(id, kind) {\n return persistentStorage.set(getContextKeyIdString(kind), id);\n }\n\n /**\n * Process a single kind context, or a single context within a multi-kind context.\n * @param {string} kind The kind of the context. Independent because the kind is not prevent\n * within a context in a multi-kind context.\n * @param {Object} context\n * @returns {Promise} a promise that resolves to a processed contexts, or rejects\n * a context which cannot be processed.\n */\n function processSingleKindContext(kind, context) {\n // We are working on a copy of an original context, so we want to re-assign\n // versus duplicating it again.\n\n /* eslint-disable no-param-reassign */\n if (context.key !== null && context.key !== undefined) {\n context.key = context.key.toString();\n return Promise.resolve(context);\n }\n\n if (context.anonymous) {\n // If the key doesn't exist, then the persistent storage will resolve\n // with undefined.\n return getCachedContextKey(kind).then(cachedId => {\n if (cachedId) {\n context.key = cachedId;\n return context;\n } else {\n const id = uuidv1();\n context.key = id;\n return setCachedContextKey(id, kind).then(() => context);\n }\n });\n } else {\n return Promise.reject(new errors.LDInvalidUserError(messages.invalidContext()));\n }\n /* eslint-enable no-param-reassign */\n }\n\n /**\n * Process the context, returning a Promise that resolves to the processed context, or rejects if there is an error.\n * @param {Object} context\n * @returns {Promise} A promise which resolves to a processed context, or a rejection if the context cannot be\n * processed. The context should still be checked for overall validity after being processed.\n */\n this.processContext = context => {\n if (!context) {\n return Promise.reject(new errors.LDInvalidUserError(messages.contextNotSpecified()));\n }\n\n const processedContext = utils.clone(context);\n\n if (context.kind === 'multi') {\n const kinds = getContextKinds(processedContext);\n\n return Promise.all(kinds.map(kind => processSingleKindContext(kind, processedContext[kind]))).then(\n () => processedContext\n );\n }\n return processSingleKindContext(context.kind, processedContext);\n };\n}\n\nmodule.exports = AnonymousContextProcessor;\n","const { v1: uuidv1 } = require('uuid');\n// Note that in the diagnostic events spec, these IDs are to be generated with UUID v4. However,\n// in JS we were already using v1 for unique context keys, so to avoid bringing in two packages we\n// will use v1 here as well.\n\nconst { baseOptionDefs } = require('./configuration');\nconst messages = require('./messages');\nconst { appendUrlPath } = require('./utils');\n\nfunction DiagnosticId(sdkKey) {\n const ret = {\n diagnosticId: uuidv1(),\n };\n if (sdkKey) {\n ret.sdkKeySuffix = sdkKey.length > 6 ? sdkKey.substring(sdkKey.length - 6) : sdkKey;\n }\n return ret;\n}\n\n// A stateful object holding statistics that will go into diagnostic events.\n\nfunction DiagnosticsAccumulator(startTime) {\n let dataSinceDate, droppedEvents, eventsInLastBatch, streamInits;\n\n function reset(time) {\n dataSinceDate = time;\n droppedEvents = 0;\n eventsInLastBatch = 0;\n streamInits = [];\n }\n\n reset(startTime);\n\n return {\n getProps: () => ({\n dataSinceDate,\n droppedEvents,\n eventsInLastBatch,\n streamInits,\n // omit deduplicatedUsers for the JS SDKs because they don't deduplicate users\n }),\n setProps: props => {\n dataSinceDate = props.dataSinceDate;\n droppedEvents = props.droppedEvents || 0;\n eventsInLastBatch = props.eventsInLastBatch || 0;\n streamInits = props.streamInits || [];\n },\n incrementDroppedEvents: () => {\n droppedEvents++;\n },\n setEventsInLastBatch: n => {\n eventsInLastBatch = n;\n },\n recordStreamInit: (timestamp, failed, durationMillis) => {\n const info = { timestamp, failed, durationMillis };\n streamInits.push(info);\n },\n reset,\n };\n}\n\n// An object that maintains information that will go into diagnostic events, and knows how to format\n// those events. It is instantiated by the SDK client, and shared with the event processor.\n//\n// The JS-based SDKs have two modes for diagnostic events. By default, the behavior is basically the\n// same as the server-side SDKs: a \"diagnostic-init\" event is sent on startup, and then \"diagnostic\"\n// events with operating statistics are sent periodically. However, in a browser environment this is\n// undesirable because the page may be reloaded frequently. In that case, setting the property\n// \"platform.diagnosticUseCombinedEvent\" to true enables an alternate mode in which a combination of\n// both kinds of event is sent at intervals, relative to the last time this was done (if any) which\n// is cached in local storage.\n\nfunction DiagnosticsManager(\n platform,\n persistentStorage,\n accumulator,\n eventSender,\n environmentId,\n config,\n diagnosticId\n) {\n const combinedMode = !!platform.diagnosticUseCombinedEvent;\n const localStorageKey = 'ld:' + environmentId + ':$diagnostics';\n const diagnosticEventsUrl = appendUrlPath(config.eventsUrl, '/events/diagnostic/' + environmentId);\n const periodicInterval = config.diagnosticRecordingInterval;\n const acc = accumulator;\n const initialEventSamplingInterval = 4; // used only in combined mode - see start()\n let streamingEnabled = !!config.streaming;\n let eventSentTime;\n let periodicTimer;\n const manager = {};\n\n function makeInitProperties() {\n return {\n sdk: makeSdkData(),\n configuration: makeConfigData(),\n platform: platform.diagnosticPlatformData,\n };\n }\n\n // Send a diagnostic event and do not wait for completion.\n function sendDiagnosticEvent(event) {\n config.logger && config.logger.debug(messages.debugPostingDiagnosticEvent(event));\n eventSender\n .sendEvents(event, diagnosticEventsUrl, true)\n .then(() => undefined)\n .catch(() => undefined);\n }\n\n function loadProperties(callback) {\n if (!persistentStorage.isEnabled()) {\n return callback(false); // false indicates that local storage is not available\n }\n persistentStorage\n .get(localStorageKey)\n .then(data => {\n if (data) {\n try {\n const props = JSON.parse(data);\n acc.setProps(props);\n eventSentTime = props.dataSinceDate;\n } catch (e) {\n // disregard malformed cached data\n }\n }\n callback(true);\n })\n .catch(() => {\n callback(false);\n });\n }\n\n function saveProperties() {\n if (persistentStorage.isEnabled()) {\n const props = { ...acc.getProps() };\n persistentStorage.set(localStorageKey, JSON.stringify(props));\n }\n }\n\n // Creates the initial event that is sent by the event processor when the SDK starts up. This will not\n // be repeated during the lifetime of the SDK client. In combined mode, we don't send this.\n function createInitEvent() {\n return {\n kind: 'diagnostic-init',\n id: diagnosticId,\n creationDate: acc.getProps().dataSinceDate,\n ...makeInitProperties(),\n };\n }\n\n // Creates a periodic event containing time-dependent stats, and resets the state of the manager with\n // regard to those stats. In combined mode (browser SDK) this also contains the configuration data.\n function createPeriodicEventAndReset() {\n const currentTime = new Date().getTime();\n let ret = {\n kind: combinedMode ? 'diagnostic-combined' : 'diagnostic',\n id: diagnosticId,\n creationDate: currentTime,\n ...acc.getProps(),\n };\n if (combinedMode) {\n ret = { ...ret, ...makeInitProperties() };\n }\n acc.reset(currentTime);\n return ret;\n }\n\n function sendPeriodicEvent() {\n sendDiagnosticEvent(createPeriodicEventAndReset());\n periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval);\n eventSentTime = new Date().getTime();\n if (combinedMode) {\n saveProperties();\n }\n }\n\n function makeSdkData() {\n const sdkData = { ...platform.diagnosticSdkData };\n if (config.wrapperName) {\n sdkData.wrapperName = config.wrapperName;\n }\n if (config.wrapperVersion) {\n sdkData.wrapperVersion = config.wrapperVersion;\n }\n return sdkData;\n }\n\n function makeConfigData() {\n const configData = {\n customBaseURI: config.baseUrl !== baseOptionDefs.baseUrl.default,\n customStreamURI: config.streamUrl !== baseOptionDefs.streamUrl.default,\n customEventsURI: config.eventsUrl !== baseOptionDefs.eventsUrl.default,\n eventsCapacity: config.eventCapacity,\n eventsFlushIntervalMillis: config.flushInterval,\n reconnectTimeMillis: config.streamReconnectDelay,\n streamingDisabled: !streamingEnabled,\n allAttributesPrivate: !!config.allAttributesPrivate,\n diagnosticRecordingIntervalMillis: config.diagnosticRecordingInterval,\n // The following extra properties are only provided by client-side JS SDKs:\n usingSecureMode: !!config.hash,\n bootstrapMode: !!config.bootstrap,\n fetchGoalsDisabled: !config.fetchGoals,\n sendEventsOnlyForVariation: !!config.sendEventsOnlyForVariation,\n };\n // Client-side JS SDKs do not have the following properties which other SDKs have:\n // connectTimeoutMillis\n // pollingIntervalMillis\n // samplingInterval\n // socketTimeoutMillis\n // startWaitMillis\n // userKeysCapacity\n // userKeysFlushIntervalMillis\n // usingProxy\n // usingProxyAuthenticator\n // usingRelayDaemon\n\n return configData;\n }\n\n // Called when the SDK is starting up. Either send an init event immediately, or, in the alternate\n // mode, check for cached local storage properties and send an event only if we haven't done so\n // recently.\n manager.start = () => {\n if (combinedMode) {\n loadProperties(localStorageAvailable => {\n if (localStorageAvailable) {\n const nextEventTime = (eventSentTime || 0) + periodicInterval;\n const timeNow = new Date().getTime();\n if (timeNow >= nextEventTime) {\n sendPeriodicEvent();\n } else {\n periodicTimer = setTimeout(sendPeriodicEvent, nextEventTime - timeNow);\n }\n } else {\n // We don't have the ability to cache anything in local storage, so we don't know if we\n // recently sent an event before this page load, but we would still prefer not to send one\n // on *every* page load. So, as a rough heuristic, we'll decide semi-randomly.\n if (Math.floor(Math.random() * initialEventSamplingInterval) === 0) {\n sendPeriodicEvent();\n } else {\n periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval);\n }\n }\n });\n } else {\n sendDiagnosticEvent(createInitEvent());\n periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval);\n }\n };\n\n manager.stop = () => {\n periodicTimer && clearTimeout(periodicTimer);\n };\n\n // Called when streaming mode is turned on or off dynamically.\n manager.setStreaming = enabled => {\n streamingEnabled = enabled;\n };\n\n return manager;\n}\n\nmodule.exports = {\n DiagnosticId,\n DiagnosticsAccumulator,\n DiagnosticsManager,\n};\n","const messages = require('./messages');\n\n/**\n * Wrap an inspector ensuring that calling its methods are safe.\n * @param {object} inspector Inspector to wrap.\n */\nfunction SafeInspector(inspector, logger) {\n let errorLogged = false;\n const wrapper = {\n type: inspector.type,\n name: inspector.name,\n synchronous: inspector.synchronous,\n };\n\n wrapper.method = (...args) => {\n try {\n inspector.method(...args);\n } catch {\n // If something goes wrong in an inspector we want to log that something\n // went wrong. We don't want to flood the logs, so we only log something\n // the first time that something goes wrong.\n // We do not include the exception in the log, because we do not know what\n // kind of data it may contain.\n if (!errorLogged) {\n errorLogged = true;\n logger.warn(messages.inspectorMethodError(wrapper.type, wrapper.name));\n }\n // Prevent errors.\n }\n };\n\n return wrapper;\n}\n\nmodule.exports = SafeInspector;\n","const messages = require('./messages');\nconst SafeInspector = require('./SafeInspector');\nconst { onNextTick } = require('./utils');\n\n/**\n * The types of supported inspectors.\n */\nconst InspectorTypes = {\n flagUsed: 'flag-used',\n flagDetailsChanged: 'flag-details-changed',\n flagDetailChanged: 'flag-detail-changed',\n clientIdentityChanged: 'client-identity-changed',\n};\n\nObject.freeze(InspectorTypes);\n\n/**\n * Manages dispatching of inspection data to registered inspectors.\n */\nfunction InspectorManager(inspectors, logger) {\n const manager = {};\n\n /**\n * Collection of inspectors keyed by type.\n *\n * Inspectors are async by default.\n *\n * @type {{[type: string]: object[]}}\n */\n const inspectorsByType = {\n [InspectorTypes.flagUsed]: [],\n [InspectorTypes.flagDetailsChanged]: [],\n [InspectorTypes.flagDetailChanged]: [],\n [InspectorTypes.clientIdentityChanged]: [],\n };\n /**\n * Collection synchronous of inspectors keyed by type.\n *\n * @type {{[type: string]: object[]}}\n */\n const synchronousInspectorsByType = {\n [InspectorTypes.flagUsed]: [],\n [InspectorTypes.flagDetailsChanged]: [],\n [InspectorTypes.flagDetailChanged]: [],\n [InspectorTypes.clientIdentityChanged]: [],\n };\n\n const safeInspectors = inspectors && inspectors.map(inspector => SafeInspector(inspector, logger));\n\n safeInspectors &&\n safeInspectors.forEach(safeInspector => {\n // Only add inspectors of supported types.\n if (Object.prototype.hasOwnProperty.call(inspectorsByType, safeInspector.type) && !safeInspector.synchronous) {\n inspectorsByType[safeInspector.type].push(safeInspector);\n } else if (\n Object.prototype.hasOwnProperty.call(synchronousInspectorsByType, safeInspector.type) &&\n safeInspector.synchronous\n ) {\n synchronousInspectorsByType[safeInspector.type].push(safeInspector);\n } else {\n logger.warn(messages.invalidInspector(safeInspector.type, safeInspector.name));\n }\n });\n\n /**\n * Check if there is an inspector of a specific type registered.\n *\n * @param {string} type The type of the inspector to check.\n * @returns True if there are any inspectors of that type registered.\n */\n manager.hasListeners = type =>\n (inspectorsByType[type] && inspectorsByType[type].length) ||\n (synchronousInspectorsByType[type] && synchronousInspectorsByType[type].length);\n\n /**\n * Notify registered inspectors of a flag being used.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {string} flagKey The key for the flag.\n * @param {Object} detail The LDEvaluationDetail for the flag.\n * @param {Object} context The LDContext for the flag.\n */\n manager.onFlagUsed = (flagKey, detail, context) => {\n const type = InspectorTypes.flagUsed;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(flagKey, detail, context));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(flagKey, detail, context));\n });\n }\n };\n\n /**\n * Notify registered inspectors that the flags have been replaced.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {Record} flags The current flags as a Record.\n */\n manager.onFlags = flags => {\n const type = InspectorTypes.flagDetailsChanged;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(flags));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(flags));\n });\n }\n };\n\n /**\n * Notify registered inspectors that a flag value has changed.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {string} flagKey The key for the flag that changed.\n * @param {Object} flag An `LDEvaluationDetail` for the flag.\n */\n manager.onFlagChanged = (flagKey, flag) => {\n const type = InspectorTypes.flagDetailChanged;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(flagKey, flag));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(flagKey, flag));\n });\n }\n };\n\n /**\n * Notify the registered inspectors that the context identity has changed.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {Object} context The `LDContext` which is now identified.\n */\n manager.onIdentityChanged = context => {\n const type = InspectorTypes.clientIdentityChanged;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(context));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(context));\n });\n }\n };\n\n return manager;\n}\n\nmodule.exports = { InspectorTypes, InspectorManager };\n","const { LDTimeoutError } = require('./errors');\n\n/**\n * Returns a promise which errors after t seconds.\n *\n * @param t Timeout in seconds.\n * @param taskName Name of task being timed for logging and error reporting.\n */\nfunction timedPromise(t, taskName) {\n return new Promise((_res, reject) => {\n setTimeout(() => {\n const e = `${taskName} timed out after ${t} seconds.`;\n reject(new LDTimeoutError(e));\n }, t * 1000);\n });\n}\nmodule.exports = timedPromise;\n","const UNKNOWN_HOOK_NAME = 'unknown hook';\nconst BEFORE_EVALUATION_STAGE_NAME = 'beforeEvaluation';\nconst AFTER_EVALUATION_STAGE_NAME = 'afterEvaluation';\nconst BEFORE_IDENTIFY_STAGE_NAME = 'beforeIdentify';\nconst AFTER_IDENTIFY_STAGE_NAME = 'afterIdentify';\nconst AFTER_TRACK_STAGE_NAME = 'afterTrack';\n\n/**\n * Safely executes a hook stage function, logging any errors.\n * @param {{ error: (message: string) => void } | undefined} logger The logger instance.\n * @param {string} method The name of the hook stage being executed (e.g., 'beforeEvaluation').\n * @param {string} hookName The name of the hook.\n * @param {() => any} stage The function representing the hook stage to execute.\n * @param {any} def The default value to return if the stage function throws an error.\n * @returns {any} The result of the stage function, or the default value if an error occurred.\n */\nfunction tryExecuteStage(logger, method, hookName, stage, def) {\n try {\n return stage();\n } catch (err) {\n logger?.error(`An error was encountered in \"${method}\" of the \"${hookName}\" hook: ${err}`);\n return def;\n }\n}\n\n/**\n * Safely gets the name of a hook from its metadata.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {{ getMetadata: () => { name?: string } }} hook The hook instance.\n * @returns {string} The name of the hook, or 'unknown hook' if unable to retrieve it.\n */\nfunction getHookName(logger, hook) {\n try {\n return hook.getMetadata().name || UNKNOWN_HOOK_NAME;\n } catch {\n logger.error(`Exception thrown getting metadata for hook. Unable to get hook name.`);\n return UNKNOWN_HOOK_NAME;\n }\n}\n\n/**\n * Executes the 'beforeEvaluation' stage for all registered hooks.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ beforeEvaluation?: (hookContext: object, data: object) => object }>} hooks The array of hook instances.\n * @param {{ flagKey: string, context: object, defaultValue: any }} hookContext The context for the evaluation series.\n * @returns {Array} An array containing the data returned by each hook's 'beforeEvaluation' stage.\n */\nfunction executeBeforeEvaluation(logger, hooks, hookContext) {\n return hooks.map(hook =>\n tryExecuteStage(\n logger,\n BEFORE_EVALUATION_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.beforeEvaluation?.(hookContext, {}) ?? {},\n {}\n )\n );\n}\n\n/**\n * Executes the 'afterEvaluation' stage for all registered hooks in reverse order.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ afterEvaluation?: (hookContext: object, data: object, result: object) => object }>} hooks The array of hook instances.\n * @param {{ flagKey: string, context: object, defaultValue: any }} hookContext The context for the evaluation series.\n * @param {Array} updatedData The data collected from the 'beforeEvaluation' stages.\n * @param {{ value: any, variationIndex?: number, reason?: object }} result The result of the flag evaluation.\n * @returns {void}\n */\nfunction executeAfterEvaluation(logger, hooks, hookContext, updatedData, result) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = updatedData[hookIndex];\n tryExecuteStage(\n logger,\n AFTER_EVALUATION_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.afterEvaluation?.(hookContext, data, result) ?? {},\n {}\n );\n }\n}\n\n/**\n * Executes the 'beforeIdentify' stage for all registered hooks.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ beforeIdentify?: (hookContext: object, data: object) => object }>} hooks The array of hook instances.\n * @param {{ context: object, timeout?: number }} hookContext The context for the identify series.\n * @returns {Array} An array containing the data returned by each hook's 'beforeIdentify' stage.\n */\nfunction executeBeforeIdentify(logger, hooks, hookContext) {\n return hooks.map(hook =>\n tryExecuteStage(\n logger,\n BEFORE_IDENTIFY_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.beforeIdentify?.(hookContext, {}) ?? {},\n {}\n )\n );\n}\n\n/**\n * Executes the 'afterIdentify' stage for all registered hooks in reverse order.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ afterIdentify?: (hookContext: object, data: object, result: object) => object }>} hooks The array of hook instances.\n * @param {{ context: object, timeout?: number }} hookContext The context for the identify series.\n * @param {Array} updatedData The data collected from the 'beforeIdentify' stages.\n * @param {{ status: string }} result The result of the identify operation.\n * @returns {void}\n */\nfunction executeAfterIdentify(logger, hooks, hookContext, updatedData, result) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = updatedData[hookIndex];\n tryExecuteStage(\n logger,\n AFTER_IDENTIFY_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.afterIdentify?.(hookContext, data, result) ?? {},\n {}\n );\n }\n}\n\n/**\n * Executes the 'afterTrack' stage for all registered hooks in reverse order.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ afterTrack?: (hookContext: { context: object, data: object, metricValue: number }) => void }>} hooks The array of hook instances.\n * @param {{ context: object, data: object, metricValue: number }} hookContext The context for the track operation.\n * @returns {void}\n */\nfunction executeAfterTrack(logger, hooks, hookContext) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n tryExecuteStage(\n logger,\n AFTER_TRACK_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.afterTrack?.(hookContext),\n undefined\n );\n }\n}\n\n/**\n * Factory function to create a HookRunner instance.\n * Manages the execution of hooks for flag evaluations and identify operations.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array | undefined} initialHooks An optional array of hooks to initialize with.\n * @returns {{\n * withEvaluation: (key: string, context: object, defaultValue: any, method: () => { value: any, variationIndex?: number, reason?: object }) => { value: any, variationIndex?: number, reason?: object },\n * identify: (context: object, timeout?: number) => (result: { status: string }) => void,\n * addHook: (hook: object) => void\n * }} The hook runner object with methods to manage and execute hooks.\n */\nfunction createHookRunner(logger, initialHooks) {\n // Use local variable instead of instance property\n const hooksInternal = initialHooks ? [...initialHooks] : [];\n\n /**\n * Wraps a flag evaluation method with before/after hook stages.\n * @param {string} key The flag key.\n * @param {object} context The evaluation context.\n * @param {any} defaultValue The default value for the flag.\n * @param {() => { value: any, variationIndex?: number, reason?: object }} method The function that performs the actual flag evaluation.\n * @returns {{ value: any, variationIndex?: number, reason?: object }} The result of the flag evaluation.\n */\n function withEvaluation(key, context, defaultValue, method) {\n if (hooksInternal.length === 0) {\n return method();\n }\n const hooks = [...hooksInternal];\n /** @type {{ flagKey: string, context: object, defaultValue: any }} */\n const hookContext = {\n flagKey: key,\n context,\n defaultValue,\n };\n\n // Use the logger passed into the factory\n const hookData = executeBeforeEvaluation(logger, hooks, hookContext);\n const result = method();\n executeAfterEvaluation(logger, hooks, hookContext, hookData, result);\n return result;\n }\n\n /**\n * Wraps the identify operation with before/after hook stages.\n * Executes the 'beforeIdentify' stage immediately and returns a function\n * to execute the 'afterIdentify' stage later.\n * @param {object} context The context being identified.\n * @param {number | undefined} timeout Optional timeout for the identify operation.\n * @returns {(result: { status: string }) => void} A function to call after the identify operation completes.\n */\n function identify(context, timeout) {\n const hooks = [...hooksInternal];\n /** @type {{ context: object, timeout?: number }} */\n const hookContext = {\n context,\n timeout,\n };\n // Use the logger passed into the factory\n const hookData = executeBeforeIdentify(logger, hooks, hookContext);\n /**\n * Executes the 'afterIdentify' hook stage.\n * @param {{ status: string }} result The result of the identify operation.\n */\n return result => {\n executeAfterIdentify(logger, hooks, hookContext, hookData, result);\n };\n }\n\n /**\n * Adds a new hook to the runner.\n * @param {object} hook The hook instance to add.\n * @returns {void}\n */\n function addHook(hook) {\n // Mutate the internal hooks array\n hooksInternal.push(hook);\n }\n\n /**\n * Executes the 'afterTrack' stage for all registered hooks in reverse order.\n * @param {{ context: object, data: object, metricValue: number }} hookContext The context for the track operation.\n * @returns {void}\n */\n function afterTrack(hookContext) {\n if (hooksInternal.length === 0) {\n return;\n }\n const hooks = [...hooksInternal];\n executeAfterTrack(logger, hooks, hookContext);\n }\n\n return {\n withEvaluation,\n identify,\n addHook,\n afterTrack,\n };\n}\n\nmodule.exports = createHookRunner;\n","const UNKNOWN_PLUGIN_NAME = 'unknown plugin';\n\n/**\n * Safely gets the name of a plugin with error handling\n * @param {{ error: (message: string) => void }} logger - The logger instance\n * @param {{getMetadata: () => {name: string}}} plugin - Plugin object that may have a name property\n * @returns {string} The plugin name or 'unknown' if not available\n */\nfunction getPluginName(logger, plugin) {\n try {\n return plugin.getMetadata().name || UNKNOWN_PLUGIN_NAME;\n } catch (error) {\n logger.error(`Exception thrown getting metadata for plugin. Unable to get plugin name.`);\n return UNKNOWN_PLUGIN_NAME;\n }\n}\n\n/**\n * Safely retrieves hooks from plugins with error handling\n * @param {Object} logger - The logger instance\n * @param {Object} environmentMetadata - Metadata about the environment for plugin initialization\n * @param {Array<{getHooks: (environmentMetadata: object) => Hook[]}>} plugins - Array of plugin objects that may implement getHooks\n * @returns {Array} Array of hook objects collected from all plugins\n */\nfunction getPluginHooks(logger, environmentMetadata, plugins) {\n const hooks = [];\n plugins.forEach(plugin => {\n try {\n const pluginHooks = plugin.getHooks?.(environmentMetadata);\n if (pluginHooks === undefined) {\n logger.error(`Plugin ${getPluginName(logger, plugin)} returned undefined from getHooks.`);\n } else if (pluginHooks && pluginHooks.length > 0) {\n hooks.push(...pluginHooks);\n }\n } catch (error) {\n logger.error(`Exception thrown getting hooks for plugin ${getPluginName(logger, plugin)}. Unable to get hooks.`);\n }\n });\n return hooks;\n}\n\n/**\n * Registers plugins with the SDK\n * @param {{ error: (message: string) => void }} logger - The logger instance\n * @param {Object} environmentMetadata - Metadata about the environment for plugin initialization\n * @param {Object} client - The SDK client instance\n * @param {Array<{register: (client: object, environmentMetadata: object) => void}>} plugins - Array of plugin objects that implement register\n */\nfunction registerPlugins(logger, environmentMetadata, client, plugins) {\n plugins.forEach(plugin => {\n try {\n plugin.register(client, environmentMetadata);\n } catch (error) {\n logger.error(`Exception thrown registering plugin ${getPluginName(logger, plugin)}.`);\n }\n });\n}\n\n/**\n * Creates a plugin environment object\n * @param {{userAgent: string, version: string}} platform - The platform object\n * @param {string} env - The environment\n * @param {{application: {name: string, version: string}, wrapperName: string, wrapperVersion: string}} options - The options\n * @returns {{sdk: {name: string, version: string, wrapperName: string, wrapperVersion: string}, application: {name: string, version: string}, clientSideId: string}} The plugin environment\n */\nfunction createPluginEnvironment(platform, env, options) {\n const pluginSdkMetadata = {};\n\n if (platform.userAgent) {\n pluginSdkMetadata.name = platform.userAgent;\n }\n if (platform.version) {\n pluginSdkMetadata.version = platform.version;\n }\n if (options.wrapperName) {\n pluginSdkMetadata.wrapperName = options.wrapperName;\n }\n if (options.wrapperVersion) {\n pluginSdkMetadata.wrapperVersion = options.wrapperVersion;\n }\n\n const pluginApplicationMetadata = {};\n\n if (options.application) {\n if (options.application.name) {\n pluginApplicationMetadata.name = options.application.name;\n }\n if (options.application.version) {\n pluginApplicationMetadata.version = options.application.version;\n }\n }\n\n const pluginEnvironment = {\n sdk: pluginSdkMetadata,\n clientSideId: env,\n };\n\n if (Object.keys(pluginApplicationMetadata).length > 0) {\n pluginEnvironment.application = pluginApplicationMetadata;\n }\n\n return pluginEnvironment;\n}\n\nmodule.exports = {\n getPluginHooks,\n registerPlugins,\n createPluginEnvironment,\n};\n","const EventProcessor = require('./EventProcessor');\nconst EventEmitter = require('./EventEmitter');\nconst EventSender = require('./EventSender');\nconst InitializationStateTracker = require('./InitializationState');\nconst PersistentFlagStore = require('./PersistentFlagStore');\nconst PersistentStorage = require('./PersistentStorage');\nconst Stream = require('./Stream');\nconst Requestor = require('./Requestor');\nconst Identity = require('./Identity');\nconst AnonymousContextProcessor = require('./AnonymousContextProcessor');\nconst configuration = require('./configuration');\nconst diagnostics = require('./diagnosticEvents');\nconst { commonBasicLogger } = require('./loggers');\nconst utils = require('./utils');\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst { checkContext, getContextKeys } = require('./context');\nconst { InspectorTypes, InspectorManager } = require('./InspectorManager');\nconst timedPromise = require('./timedPromise');\nconst createHookRunner = require('./HookRunner');\nconst { getPluginHooks, registerPlugins, createPluginEnvironment } = require('./plugins');\nconst changeEvent = 'change';\nconst internalChangeEvent = 'internal-change';\nconst highTimeoutThreshold = 5;\n\n// This is called by the per-platform initialize functions to create the base client object that we\n// may also extend with additional behavior. It returns an object with these properties:\n// client: the actual client object\n// options: the configuration (after any appropriate defaults have been applied)\n// If we need to give the platform-specific clients access to any internals here, we should add those\n// as properties of the return object, not public properties of the client.\n//\n// For definitions of the API in the platform object, see stubPlatform.js in the test code.\n\nfunction initialize(env, context, specifiedOptions, platform, extraOptionDefs) {\n const logger = createLogger();\n const emitter = EventEmitter(logger);\n const initializationStateTracker = InitializationStateTracker(emitter);\n const options = configuration.validate(specifiedOptions, emitter, extraOptionDefs, logger);\n const inspectorManager = InspectorManager(options.inspectors, logger);\n const sendEvents = options.sendEvents;\n let environment = env;\n let hash = options.hash;\n const plugins = [...options.plugins];\n\n const pluginEnvironment = createPluginEnvironment(platform, env, options);\n\n const pluginHooks = getPluginHooks(logger, pluginEnvironment, plugins);\n\n const hookRunner = createHookRunner(logger, [...options.hooks, ...pluginHooks]);\n\n const persistentStorage = PersistentStorage(platform.localStorage, logger);\n\n const eventSender = EventSender(platform, environment, options);\n\n const diagnosticsEnabled = options.sendEvents && !options.diagnosticOptOut;\n const diagnosticId = diagnosticsEnabled ? diagnostics.DiagnosticId(environment) : null;\n const diagnosticsAccumulator = diagnosticsEnabled ? diagnostics.DiagnosticsAccumulator(new Date().getTime()) : null;\n const diagnosticsManager = diagnosticsEnabled\n ? diagnostics.DiagnosticsManager(\n platform,\n persistentStorage,\n diagnosticsAccumulator,\n eventSender,\n environment,\n options,\n diagnosticId\n )\n : null;\n\n const stream = Stream(platform, options, environment, diagnosticsAccumulator);\n\n const events =\n options.eventProcessor ||\n EventProcessor(platform, options, environment, diagnosticsAccumulator, emitter, eventSender);\n\n const requestor = Requestor(platform, options, environment);\n\n let flags = {};\n let useLocalStorage;\n let streamActive;\n let streamForcedState = options.streaming;\n let subscribedToChangeEvents;\n let inited = false;\n let closed = false;\n let firstEvent = true;\n\n // The \"stateProvider\" object is used in the Electron SDK, to allow one client instance to take partial\n // control of another. If present, it has the following contract:\n // - getInitialState() returns the initial client state if it is already available. The state is an\n // object whose properties are \"environment\", \"context\", and \"flags\".\n // - on(\"init\", listener) triggers an event when the initial client state becomes available, passing\n // the state object to the listener.\n // - on(\"update\", listener) triggers an event when flag values change and/or the current context changes.\n // The parameter is an object that *may* contain \"context\" and/or \"flags\".\n // - enqueueEvent(event) accepts an analytics event object and returns true if the stateProvider will\n // be responsible for delivering it, or false if we still should deliver it ourselves.\n const stateProvider = options.stateProvider;\n\n const ident = Identity(null, onIdentifyChange);\n const anonymousContextProcessor = new AnonymousContextProcessor(persistentStorage);\n const persistentFlagStore = persistentStorage.isEnabled()\n ? PersistentFlagStore(persistentStorage, environment, hash, ident, logger)\n : null;\n\n function createLogger() {\n if (specifiedOptions && specifiedOptions.logger) {\n return specifiedOptions.logger;\n }\n return (extraOptionDefs && extraOptionDefs.logger && extraOptionDefs.logger.default) || commonBasicLogger('warn');\n }\n\n function readFlagsFromBootstrap(data) {\n // If the bootstrap data came from an older server-side SDK, we'll have just a map of keys to values.\n // Newer SDKs that have an allFlagsState method will provide an extra \"$flagsState\" key that contains\n // the rest of the metadata we want. We do it this way for backward compatibility with older JS SDKs.\n const keys = Object.keys(data);\n const metadataKey = '$flagsState';\n const validKey = '$valid';\n const metadata = data[metadataKey];\n if (!metadata && keys.length) {\n logger.warn(messages.bootstrapOldFormat());\n }\n if (data[validKey] === false) {\n logger.warn(messages.bootstrapInvalid());\n }\n const ret = {};\n keys.forEach(key => {\n if (key !== metadataKey && key !== validKey) {\n let flag = { value: data[key] };\n if (metadata && metadata[key]) {\n flag = utils.extend(flag, metadata[key]);\n } else {\n flag.version = 0;\n }\n ret[key] = flag;\n }\n });\n return ret;\n }\n\n function shouldEnqueueEvent() {\n return sendEvents && !closed && !platform.isDoNotTrack();\n }\n\n function enqueueEvent(event) {\n if (!environment) {\n // We're in paired mode and haven't been initialized with an environment or context yet\n return;\n }\n if (stateProvider && stateProvider.enqueueEvent && stateProvider.enqueueEvent(event)) {\n return; // it'll be handled elsewhere\n }\n\n if (!event.context) {\n if (firstEvent) {\n logger.warn(messages.eventWithoutContext());\n firstEvent = false;\n }\n return;\n }\n firstEvent = false;\n\n if (shouldEnqueueEvent()) {\n logger.debug(messages.debugEnqueueingEvent(event.kind));\n events.enqueue(event);\n }\n }\n\n function notifyInspectionFlagUsed(key, detail) {\n if (inspectorManager.hasListeners(InspectorTypes.flagUsed)) {\n inspectorManager.onFlagUsed(key, detail, ident.getContext());\n }\n }\n\n function notifyInspectionIdentityChanged() {\n if (inspectorManager.hasListeners(InspectorTypes.clientIdentityChanged)) {\n inspectorManager.onIdentityChanged(ident.getContext());\n }\n }\n\n function notifyInspectionFlagChanged(data, newFlag) {\n if (inspectorManager.hasListeners(InspectorTypes.flagDetailChanged)) {\n inspectorManager.onFlagChanged(data.key, getFlagDetail(newFlag));\n }\n }\n\n function notifyInspectionFlagsChanged() {\n if (inspectorManager.hasListeners(InspectorTypes.flagDetailsChanged)) {\n inspectorManager.onFlags(\n Object.entries(flags)\n .map(([key, value]) => ({ key, detail: getFlagDetail(value) }))\n .reduce((acc, cur) => {\n // eslint-disable-next-line no-param-reassign\n acc[cur.key] = cur.detail;\n return acc;\n }, {})\n );\n }\n }\n\n function onIdentifyChange(context) {\n sendIdentifyEvent(context);\n notifyInspectionIdentityChanged();\n }\n\n function sendIdentifyEvent(context) {\n if (stateProvider) {\n // In paired mode, the other client is responsible for sending identify events\n return;\n }\n if (context) {\n enqueueEvent({\n kind: 'identify',\n context,\n creationDate: new Date().getTime(),\n });\n }\n }\n\n function sendFlagEvent(key, detail, defaultValue, includeReason) {\n const context = ident.getContext();\n const now = new Date();\n const value = detail ? detail.value : null;\n\n const event = {\n kind: 'feature',\n key: key,\n context,\n value: value,\n variation: detail ? detail.variationIndex : null,\n default: defaultValue,\n creationDate: now.getTime(),\n };\n const flag = flags[key];\n if (flag) {\n event.version = flag.flagVersion ? flag.flagVersion : flag.version;\n event.trackEvents = flag.trackEvents;\n event.debugEventsUntilDate = flag.debugEventsUntilDate;\n }\n if ((includeReason || (flag && flag.trackReason)) && detail) {\n event.reason = detail.reason;\n }\n\n enqueueEvent(event);\n }\n\n function verifyContext(context) {\n // The context will already have been processed to have a string key, so we\n // do not need to allow for legacy keys in the check.\n if (checkContext(context, false)) {\n return Promise.resolve(context);\n } else {\n return Promise.reject(new errors.LDInvalidUserError(messages.invalidContext()));\n }\n }\n\n function identify(context, newHash, onDone) {\n if (closed) {\n return utils.wrapPromiseCallback(Promise.resolve({}), onDone);\n }\n if (stateProvider) {\n // We're being controlled by another client instance, so only that instance is allowed to change the context\n logger.warn(messages.identifyDisabled());\n return utils.wrapPromiseCallback(Promise.resolve(utils.transformVersionedValuesToValues(flags)), onDone);\n }\n let afterIdentify;\n const clearFirst = useLocalStorage && persistentFlagStore ? persistentFlagStore.clearFlags() : Promise.resolve();\n return utils.wrapPromiseCallback(\n clearFirst\n .then(() => anonymousContextProcessor.processContext(context))\n .then(verifyContext)\n .then(context => {\n afterIdentify = utils.once(hookRunner.identify(context, undefined));\n return context;\n })\n .then(validatedContext =>\n requestor\n .fetchFlagSettings(validatedContext, newHash)\n // the following then() is nested within this one so we can use realUser from the previous closure\n .then(requestedFlags => {\n const flagValueMap = utils.transformVersionedValuesToValues(requestedFlags);\n ident.setContext(validatedContext);\n hash = newHash;\n if (requestedFlags) {\n return replaceAllFlags(requestedFlags).then(() => flagValueMap);\n } else {\n return flagValueMap;\n }\n })\n )\n .then(flagValueMap => {\n afterIdentify?.({ status: 'completed' });\n if (streamActive) {\n connectStream();\n }\n return flagValueMap;\n })\n .catch(err => {\n afterIdentify?.({ status: 'error' });\n emitter.maybeReportError(err);\n return Promise.reject(err);\n }),\n onDone\n );\n }\n\n function getContext() {\n return ident.getContext();\n }\n\n function flush(onDone) {\n return utils.wrapPromiseCallback(sendEvents ? events.flush() : Promise.resolve(), onDone);\n }\n\n function variation(key, defaultValue) {\n const { value } = hookRunner.withEvaluation(key, ident.getContext(), defaultValue, () =>\n variationDetailInternal(key, defaultValue, true, false, false, true)\n );\n return value;\n }\n\n function variationDetail(key, defaultValue) {\n return hookRunner.withEvaluation(key, ident.getContext(), defaultValue, () =>\n variationDetailInternal(key, defaultValue, true, true, false, true)\n );\n }\n\n function variationDetailInternal(key, defaultValue, sendEvent, includeReasonInEvent, isAllFlags, notifyInspection) {\n let detail;\n let flag;\n\n if (flags && utils.objectHasOwnProperty(flags, key) && flags[key] && !flags[key].deleted) {\n flag = flags[key];\n detail = getFlagDetail(flag);\n if (flag.value === null || flag.value === undefined) {\n detail.value = defaultValue;\n }\n } else {\n detail = { value: defaultValue, variationIndex: null, reason: { kind: 'ERROR', errorKind: 'FLAG_NOT_FOUND' } };\n }\n\n if (sendEvent) {\n // For an all-flags evaluation, with events enabled, each flag will get an event, so we do not\n // need to duplicate the prerequisites.\n if (!isAllFlags) {\n flag?.prerequisites?.forEach(key => {\n variationDetailInternal(key, undefined, sendEvent, false, false, false);\n });\n }\n sendFlagEvent(key, detail, defaultValue, includeReasonInEvent);\n }\n\n // For the all flags case `onFlags` will be called instead.\n if (!isAllFlags && notifyInspection) {\n notifyInspectionFlagUsed(key, detail);\n }\n\n return detail;\n }\n\n function getFlagDetail(flag) {\n return {\n value: flag.value,\n variationIndex: flag.variation === undefined ? null : flag.variation,\n reason: flag.reason || null,\n };\n // Note, the logic above ensures that variationIndex and reason will always be null rather than\n // undefined if we don't have values for them. That's just to avoid subtle errors that depend on\n // whether an object was JSON-encoded with null properties omitted or not.\n }\n\n function allFlags() {\n const results = {};\n\n if (!flags) {\n return results;\n }\n\n for (const key in flags) {\n if (utils.objectHasOwnProperty(flags, key) && !flags[key].deleted) {\n results[key] = variationDetailInternal(\n key,\n null,\n !options.sendEventsOnlyForVariation,\n false,\n true,\n false\n ).value;\n }\n }\n\n return results;\n }\n\n function userContextKind(user) {\n return user.anonymous ? 'anonymousUser' : 'user';\n }\n\n function track(key, data, metricValue) {\n if (typeof key !== 'string') {\n emitter.maybeReportError(new errors.LDInvalidEventKeyError(messages.unknownCustomEventKey(key)));\n return;\n }\n if (metricValue !== undefined && typeof metricValue !== 'number') {\n logger.warn(messages.invalidMetricValue(typeof metricValue));\n }\n\n // The following logic was used only for the JS browser SDK (js-client-sdk) and\n // is no longer needed as of version 2.9.13 of that SDK. The other client-side\n // JS-based SDKs did not define customEventFilter, and now none of them do. We\n // can remove this in the next major version of the common code, when it's OK to\n // make breaking changes to our internal API contracts.\n if (platform.customEventFilter && !platform.customEventFilter(key)) {\n logger.warn(messages.unknownCustomEventKey(key));\n }\n\n const context = ident.getContext();\n const e = {\n kind: 'custom',\n key: key,\n context,\n url: platform.getCurrentUrl(),\n creationDate: new Date().getTime(),\n };\n if (context && context.anonymous) {\n e.contextKind = userContextKind(context);\n }\n // Note, check specifically for null/undefined because it is legal to set these fields to a falsey value.\n if (data !== null && data !== undefined) {\n e.data = data;\n }\n if (metricValue !== null && metricValue !== undefined) {\n e.metricValue = metricValue;\n }\n enqueueEvent(e);\n hookRunner.afterTrack({ context, key, data, metricValue });\n }\n\n function connectStream() {\n streamActive = true;\n if (!ident.getContext()) {\n return;\n }\n const tryParseData = jsonData => {\n try {\n return JSON.parse(jsonData);\n } catch (err) {\n emitter.maybeReportError(new errors.LDInvalidDataError(messages.invalidData()));\n return undefined;\n }\n };\n stream.connect(ident.getContext(), hash, {\n ping: function() {\n logger.debug(messages.debugStreamPing());\n const contextAtTimeOfPingEvent = ident.getContext();\n requestor\n .fetchFlagSettings(contextAtTimeOfPingEvent, hash)\n .then(requestedFlags => {\n // Check whether the current context is still the same - we don't want to overwrite the flags if\n // the application has called identify() while this request was in progress\n if (utils.deepEquals(contextAtTimeOfPingEvent, ident.getContext())) {\n replaceAllFlags(requestedFlags || {});\n }\n })\n .catch(err => {\n emitter.maybeReportError(new errors.LDFlagFetchError(messages.errorFetchingFlags(err)));\n });\n },\n put: function(e) {\n const data = tryParseData(e.data);\n if (!data) {\n return;\n }\n logger.debug(messages.debugStreamPut());\n replaceAllFlags(data);\n // Don't wait for this Promise to be resolved; note that replaceAllFlags is guaranteed\n // never to have an unhandled rejection\n },\n patch: function(e) {\n const data = tryParseData(e.data);\n if (!data) {\n return;\n }\n // If both the flag and the patch have a version property, then the patch version must be\n // greater than the flag version for us to accept the patch. If either one has no version\n // then the patch always succeeds.\n const oldFlag = flags[data.key];\n if (!oldFlag || !oldFlag.version || !data.version || oldFlag.version < data.version) {\n logger.debug(messages.debugStreamPatch(data.key));\n const mods = {};\n const newFlag = utils.extend({}, data);\n delete newFlag['key'];\n flags[data.key] = newFlag;\n const newDetail = getFlagDetail(newFlag);\n if (oldFlag) {\n mods[data.key] = { previous: oldFlag.value, current: newDetail };\n } else {\n mods[data.key] = { current: newDetail };\n }\n notifyInspectionFlagChanged(data, newFlag);\n handleFlagChanges(mods); // don't wait for this Promise to be resolved\n } else {\n logger.debug(messages.debugStreamPatchIgnored(data.key));\n }\n },\n delete: function(e) {\n const data = tryParseData(e.data);\n if (!data) {\n return;\n }\n if (!flags[data.key] || flags[data.key].version < data.version) {\n logger.debug(messages.debugStreamDelete(data.key));\n const mods = {};\n if (flags[data.key] && !flags[data.key].deleted) {\n mods[data.key] = { previous: flags[data.key].value };\n }\n flags[data.key] = { version: data.version, deleted: true };\n notifyInspectionFlagChanged(data, flags[data.key]);\n handleFlagChanges(mods); // don't wait for this Promise to be resolved\n } else {\n logger.debug(messages.debugStreamDeleteIgnored(data.key));\n }\n },\n });\n }\n\n function disconnectStream() {\n if (streamActive) {\n stream.disconnect();\n streamActive = false;\n }\n }\n\n // Returns a Promise which will be resolved when we have completely updated the internal flags state,\n // dispatched all change events, and updated local storage if appropriate. This Promise is guaranteed\n // never to have an unhandled rejection.\n function replaceAllFlags(newFlags) {\n const changes = {};\n\n if (!newFlags) {\n return Promise.resolve();\n }\n\n for (const key in flags) {\n if (utils.objectHasOwnProperty(flags, key) && flags[key]) {\n if (newFlags[key] && !utils.deepEquals(newFlags[key].value, flags[key].value)) {\n changes[key] = { previous: flags[key].value, current: getFlagDetail(newFlags[key]) };\n } else if (!newFlags[key] || newFlags[key].deleted) {\n changes[key] = { previous: flags[key].value };\n }\n }\n }\n for (const key in newFlags) {\n if (utils.objectHasOwnProperty(newFlags, key) && newFlags[key] && (!flags[key] || flags[key].deleted)) {\n changes[key] = { current: getFlagDetail(newFlags[key]) };\n }\n }\n\n flags = { ...newFlags };\n\n notifyInspectionFlagsChanged();\n\n return handleFlagChanges(changes).catch(() => {}); // swallow any exceptions from this Promise\n }\n\n // Returns a Promise which will be resolved when we have dispatched all change events and updated\n // local storage if appropriate.\n function handleFlagChanges(changes) {\n const keys = Object.keys(changes);\n\n if (keys.length > 0) {\n const changeEventParams = {};\n keys.forEach(key => {\n const current = changes[key].current;\n const value = current ? current.value : undefined;\n const previous = changes[key].previous;\n emitter.emit(changeEvent + ':' + key, value, previous);\n changeEventParams[key] = current ? { current: value, previous: previous } : { previous: previous };\n });\n\n emitter.emit(changeEvent, changeEventParams);\n emitter.emit(internalChangeEvent, flags);\n\n // By default, we send feature evaluation events whenever we have received new flag values -\n // the client has in effect evaluated these flags just by receiving them. This can be suppressed\n // by setting \"sendEventsOnlyForVariation\". Also, if we have a stateProvider, we don't send these\n // events because we assume they have already been sent by the other client that gave us the flags\n // (when it received them in the first place).\n if (!options.sendEventsOnlyForVariation && !stateProvider) {\n keys.forEach(key => {\n sendFlagEvent(key, changes[key].current);\n });\n }\n }\n\n if (useLocalStorage && persistentFlagStore) {\n return persistentFlagStore.saveFlags(flags);\n } else {\n return Promise.resolve();\n }\n }\n\n function on(event, handler, context) {\n if (isChangeEventKey(event)) {\n subscribedToChangeEvents = true;\n if (inited) {\n updateStreamingState();\n }\n emitter.on(event, handler, context);\n } else {\n emitter.on(...arguments);\n }\n }\n\n function off(event) {\n emitter.off(...arguments);\n if (isChangeEventKey(event)) {\n let haveListeners = false;\n emitter.getEvents().forEach(key => {\n if (isChangeEventKey(key) && emitter.getEventListenerCount(key) > 0) {\n haveListeners = true;\n }\n });\n if (!haveListeners) {\n subscribedToChangeEvents = false;\n if (streamActive && streamForcedState === undefined) {\n disconnectStream();\n }\n }\n }\n }\n\n function setStreaming(state) {\n const newState = state === null ? undefined : state;\n if (newState !== streamForcedState) {\n streamForcedState = newState;\n updateStreamingState();\n }\n }\n\n function updateStreamingState() {\n const shouldBeStreaming = streamForcedState || (subscribedToChangeEvents && streamForcedState === undefined);\n if (shouldBeStreaming && !streamActive) {\n connectStream();\n } else if (!shouldBeStreaming && streamActive) {\n disconnectStream();\n }\n if (diagnosticsManager) {\n diagnosticsManager.setStreaming(shouldBeStreaming);\n }\n }\n\n function isChangeEventKey(event) {\n return event === changeEvent || event.substr(0, changeEvent.length + 1) === changeEvent + ':';\n }\n\n if (typeof options.bootstrap === 'string' && options.bootstrap.toUpperCase() === 'LOCALSTORAGE') {\n if (persistentFlagStore) {\n useLocalStorage = true;\n } else {\n logger.warn(messages.localStorageUnavailable());\n }\n }\n\n if (typeof options.bootstrap === 'object') {\n // Set the flags as soon as possible before we get into any async code, so application code can read\n // them even if the ready event has not yet fired.\n flags = readFlagsFromBootstrap(options.bootstrap);\n }\n\n if (stateProvider) {\n // The stateProvider option is used in the Electron SDK, to allow a client instance in the main process\n // to control another client instance (i.e. this one) in the renderer process. We can't predict which\n // one will start up first, so the initial state may already be available for us or we may have to wait\n // to receive it.\n const state = stateProvider.getInitialState();\n if (state) {\n initFromStateProvider(state);\n } else {\n stateProvider.on('init', initFromStateProvider);\n }\n stateProvider.on('update', updateFromStateProvider);\n } else {\n finishInit().catch(signalFailedInit);\n }\n\n function finishInit() {\n if (!env) {\n return Promise.reject(new errors.LDInvalidEnvironmentIdError(messages.environmentNotSpecified()));\n }\n let afterIdentify;\n return anonymousContextProcessor\n .processContext(context)\n .then(verifyContext)\n .then(context => {\n afterIdentify = utils.once(hookRunner.identify(context, undefined));\n return context;\n })\n .then(validatedContext => {\n afterIdentify?.({ status: 'completed' });\n ident.setContext(validatedContext);\n if (typeof options.bootstrap === 'object') {\n // flags have already been set earlier\n return signalSuccessfulInit();\n } else if (useLocalStorage) {\n return finishInitWithLocalStorage();\n } else {\n return finishInitWithPolling();\n }\n })\n .catch(err => {\n afterIdentify?.({ status: 'error' });\n throw err;\n });\n }\n\n function finishInitWithLocalStorage() {\n return persistentFlagStore.loadFlags().then(storedFlags => {\n if (storedFlags === null || storedFlags === undefined) {\n flags = {};\n return requestor\n .fetchFlagSettings(ident.getContext(), hash)\n .then(requestedFlags => replaceAllFlags(requestedFlags || {}))\n .then(signalSuccessfulInit)\n .catch(err => {\n const initErr = new errors.LDFlagFetchError(messages.errorFetchingFlags(err));\n signalFailedInit(initErr);\n });\n } else {\n // We're reading the flags from local storage. Signal that we're ready,\n // then update localStorage for the next page load. We won't signal changes or update\n // the in-memory flags unless you subscribe for changes\n flags = storedFlags;\n utils.onNextTick(signalSuccessfulInit);\n\n return requestor\n .fetchFlagSettings(ident.getContext(), hash)\n .then(requestedFlags => replaceAllFlags(requestedFlags))\n .catch(err => emitter.maybeReportError(err));\n }\n });\n }\n\n function finishInitWithPolling() {\n return requestor\n .fetchFlagSettings(ident.getContext(), hash)\n .then(requestedFlags => {\n flags = requestedFlags || {};\n\n notifyInspectionFlagsChanged();\n // Note, we don't need to call updateSettings here because local storage and change events are not relevant\n signalSuccessfulInit();\n })\n .catch(err => {\n flags = {};\n signalFailedInit(err);\n });\n }\n\n function initFromStateProvider(state) {\n environment = state.environment;\n ident.setContext(state.context);\n flags = { ...state.flags };\n utils.onNextTick(signalSuccessfulInit);\n }\n\n function updateFromStateProvider(state) {\n if (state.context) {\n ident.setContext(state.context);\n }\n if (state.flags) {\n replaceAllFlags(state.flags); // don't wait for this Promise to be resolved\n }\n }\n\n function signalSuccessfulInit() {\n logger.info(messages.clientInitialized());\n inited = true;\n updateStreamingState();\n initializationStateTracker.signalSuccess();\n }\n\n function signalFailedInit(err) {\n initializationStateTracker.signalFailure(err);\n }\n\n function start() {\n if (sendEvents) {\n if (diagnosticsManager) {\n diagnosticsManager.start();\n }\n events.start();\n }\n }\n\n function close(onDone) {\n if (closed) {\n return utils.wrapPromiseCallback(Promise.resolve(), onDone);\n }\n const finishClose = () => {\n closed = true;\n flags = {};\n };\n const p = Promise.resolve()\n .then(() => {\n disconnectStream();\n if (diagnosticsManager) {\n diagnosticsManager.stop();\n }\n if (sendEvents) {\n events.stop();\n return events.flush();\n }\n })\n .then(finishClose)\n .catch(finishClose);\n return utils.wrapPromiseCallback(p, onDone);\n }\n\n function getFlagsInternal() {\n // used by Electron integration\n return flags;\n }\n\n function waitForInitializationWithTimeout(timeout) {\n if (timeout > highTimeoutThreshold) {\n logger.warn(\n 'The waitForInitialization function was called with a timeout greater than ' +\n `${highTimeoutThreshold} seconds. We recommend a timeout of ` +\n `${highTimeoutThreshold} seconds or less.`\n );\n }\n\n const initPromise = initializationStateTracker.getInitializationPromise();\n const timeoutPromise = timedPromise(timeout, 'waitForInitialization');\n\n return Promise.race([timeoutPromise, initPromise]).catch(e => {\n if (e instanceof errors.LDTimeoutError) {\n logger.error(`waitForInitialization error: ${e}`);\n }\n throw e;\n });\n }\n\n function waitForInitialization(timeout = undefined) {\n if (timeout !== undefined && timeout !== null) {\n if (typeof timeout === 'number') {\n return waitForInitializationWithTimeout(timeout);\n }\n logger.warn('The waitForInitialization method was provided with a non-numeric timeout.');\n }\n logger.warn(\n 'The waitForInitialization function was called without a timeout specified.' +\n ' In a future version a default timeout will be applied.'\n );\n return initializationStateTracker.getInitializationPromise();\n }\n\n function addHook(hook) {\n hookRunner.addHook(hook);\n }\n\n const client = {\n waitForInitialization,\n waitUntilReady: () => initializationStateTracker.getReadyPromise(),\n identify: identify,\n getContext: getContext,\n variation: variation,\n variationDetail: variationDetail,\n track: track,\n on: on,\n off: off,\n setStreaming: setStreaming,\n flush: flush,\n allFlags: allFlags,\n close: close,\n addHook: addHook,\n };\n\n registerPlugins(logger, pluginEnvironment, client, plugins);\n\n return {\n client: client, // The client object containing all public methods.\n options: options, // The validated configuration object, including all defaults.\n emitter: emitter, // The event emitter which can be used to log errors or trigger events.\n ident: ident, // The Identity object that manages the current context.\n logger: logger, // The logging abstraction.\n requestor: requestor, // The Requestor object.\n start: start, // Starts the client once the environment is ready.\n enqueueEvent: enqueueEvent, // Puts an analytics event in the queue, if event sending is enabled.\n getFlagsInternal: getFlagsInternal, // Returns flag data structure with all details.\n getEnvironmentId: () => environment, // Gets the environment ID (this may have changed since initialization, if we have a state provider)\n internalChangeEventName: internalChangeEvent, // This event is triggered whenever we have new flag state.\n };\n}\n\nmodule.exports = {\n initialize,\n commonBasicLogger,\n errors,\n messages,\n utils,\n getContextKeys,\n};\n","const { commonBasicLogger } = require('launchdarkly-js-sdk-common');\n\nfunction basicLogger(options) {\n return commonBasicLogger({ destination: console.log, ...options });\n}\n\nmodule.exports = {\n basicLogger,\n};\n","function isSyncXhrSupported() {\n // This is temporary logic to disable synchronous XHR in Chrome 73 and above. In all other browsers,\n // we will assume it is supported. See https://github.com/launchdarkly/js-client-sdk/issues/147\n const userAgent = window.navigator && window.navigator.userAgent;\n if (userAgent) {\n const chromeMatch = userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./);\n if (chromeMatch) {\n const version = parseInt(chromeMatch[2], 10);\n return version < 73;\n }\n }\n return true;\n}\n\nconst emptyResult = { promise: Promise.resolve({ status: 200, header: () => null, body: null }) };\n\nexport default function newHttpRequest(method, url, headers, body, pageIsClosing) {\n if (pageIsClosing) {\n // When the page is about to close, we have to use synchronous XHR (until we migrate to sendBeacon).\n // But not all browsers support this.\n if (!isSyncXhrSupported()) {\n return emptyResult;\n // Note that we return a fake success response, because we don't want the request to be retried in this case.\n }\n }\n\n const xhr = new window.XMLHttpRequest();\n xhr.open(method, url, !pageIsClosing);\n for (const key in headers || {}) {\n if (Object.prototype.hasOwnProperty.call(headers, key)) {\n xhr.setRequestHeader(key, headers[key]);\n }\n }\n if (pageIsClosing) {\n try {\n xhr.send(body); // We specified synchronous mode when we called xhr.open\n } catch (e) {\n // do nothing intentionally to suppress noise for now\n }\n return emptyResult; // Again, we never want a request to be retried in this case, so we must say it succeeded.\n } else {\n let cancelled;\n const p = new Promise((resolve, reject) => {\n xhr.addEventListener('load', () => {\n if (cancelled) {\n return;\n }\n resolve({\n status: xhr.status,\n header: (key) => xhr.getResponseHeader(key),\n body: xhr.responseText,\n });\n });\n xhr.addEventListener('error', () => {\n if (cancelled) {\n return;\n }\n reject(new Error());\n });\n xhr.send(body);\n });\n const cancel = () => {\n cancelled = true;\n xhr.abort();\n };\n return { promise: p, cancel: cancel };\n }\n}\n","'use strict';\n\nmodule.exports = string => {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a \\unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n};\n","import escapeStringRegexp from 'escape-string-regexp';\n\nexport function doesUrlMatch(matcher, href, search, hash) {\n const keepHash = (matcher.kind === 'substring' || matcher.kind === 'regex') && hash.includes('/');\n const canonicalUrl = (keepHash ? href : href.replace(hash, '')).replace(search, '');\n\n let regex;\n let testUrl;\n\n switch (matcher.kind) {\n case 'exact':\n testUrl = href;\n regex = new RegExp('^' + escapeStringRegexp(matcher.url) + '/?$');\n break;\n case 'canonical':\n testUrl = canonicalUrl;\n regex = new RegExp('^' + escapeStringRegexp(matcher.url) + '/?$');\n break;\n case 'substring':\n testUrl = canonicalUrl;\n regex = new RegExp('.*' + escapeStringRegexp(matcher.substring) + '.*$');\n break;\n case 'regex':\n testUrl = canonicalUrl;\n regex = new RegExp(matcher.pattern);\n break;\n default:\n return false;\n }\n return regex.test(testUrl);\n}\n\nfunction findGoalsForClick(event, clickGoals) {\n const matches = [];\n\n for (let i = 0; i < clickGoals.length; i++) {\n let target = event.target;\n const goal = clickGoals[i];\n const selector = goal.selector;\n const elements = document.querySelectorAll(selector);\n while (target && elements.length > 0) {\n for (let j = 0; j < elements.length; j++) {\n if (target === elements[j]) {\n matches.push(goal);\n }\n }\n target = target.parentNode;\n }\n }\n\n return matches;\n}\n\nexport default function GoalTracker(goals, onEvent) {\n const tracker = {};\n let listenerFn = null;\n\n const clickGoals = [];\n\n for (let i = 0; i < goals.length; i++) {\n const goal = goals[i];\n const urls = goal.urls || [];\n\n for (let j = 0; j < urls.length; j++) {\n if (doesUrlMatch(urls[j], window.location.href, window.location.search, window.location.hash)) {\n if (goal.kind === 'pageview') {\n onEvent('pageview', goal);\n } else {\n clickGoals.push(goal);\n onEvent('click_pageview', goal);\n }\n break;\n }\n }\n }\n\n if (clickGoals.length > 0) {\n listenerFn = function (event) {\n const goals = findGoalsForClick(event, clickGoals);\n for (let i = 0; i < goals.length; i++) {\n onEvent('click', goals[i]);\n }\n };\n\n document.addEventListener('click', listenerFn);\n }\n\n tracker.dispose = function () {\n document.removeEventListener('click', listenerFn);\n };\n\n return tracker;\n}\n","import * as common from 'launchdarkly-js-sdk-common';\nimport GoalTracker from './GoalTracker';\n\nconst locationWatcherInterval = 300;\n\nexport default function GoalManager(clientVars, readyCallback) {\n let goals;\n let goalTracker;\n\n const ret = {};\n\n function getGoalsPath() {\n return '/sdk/goals/' + clientVars.getEnvironmentId();\n }\n\n function refreshGoalTracker() {\n if (goalTracker) {\n goalTracker.dispose();\n }\n if (goals && goals.length) {\n goalTracker = GoalTracker(goals, sendGoalEvent);\n }\n }\n\n function sendGoalEvent(kind, goal) {\n const context = clientVars.ident.getContext();\n const event = {\n kind: kind,\n key: goal.key,\n data: null,\n url: window.location.href,\n creationDate: new Date().getTime(),\n context: context,\n };\n\n if (kind === 'click') {\n event.selector = goal.selector;\n }\n\n return clientVars.enqueueEvent(event);\n }\n\n function watchLocation(interval, callback) {\n let previousUrl = window.location.href;\n let currentUrl;\n\n function checkUrl() {\n currentUrl = window.location.href;\n\n if (currentUrl !== previousUrl) {\n previousUrl = currentUrl;\n callback();\n }\n }\n\n function poll(fn, interval) {\n fn();\n setTimeout(() => {\n poll(fn, interval);\n }, interval);\n }\n\n poll(checkUrl, interval);\n\n if (window.history && window.history.pushState) {\n window.addEventListener('popstate', checkUrl);\n } else {\n window.addEventListener('hashchange', checkUrl);\n }\n }\n\n clientVars.requestor\n .fetchJSON(getGoalsPath())\n .then((g) => {\n if (g && g.length > 0) {\n goals = g;\n goalTracker = GoalTracker(goals, sendGoalEvent);\n watchLocation(locationWatcherInterval, refreshGoalTracker);\n }\n readyCallback();\n })\n .catch((err) => {\n clientVars.emitter.maybeReportError(\n new common.errors.LDUnexpectedResponseError('Error fetching goals: ' + (err && err.message) ? err.message : err)\n );\n readyCallback();\n });\n\n return ret;\n}\n","import * as common from 'launchdarkly-js-sdk-common';\nimport * as importBasicLogger from './basicLogger';\nimport browserPlatform from './browserPlatform';\nimport GoalManager from './GoalManager';\n\nconst goalsEvent = 'goalsReady';\nconst extraOptionDefs = {\n fetchGoals: { default: true },\n hash: { type: 'string' },\n eventProcessor: { type: 'object' }, // used only in tests\n eventUrlTransformer: { type: 'function' },\n disableSyncEventPost: { default: false },\n};\n\n// Pass our platform object to the common code to create the browser version of the client\nexport function initialize(env, user, options = {}) {\n const platform = browserPlatform(options);\n const clientVars = common.initialize(env, user, options, platform, extraOptionDefs);\n\n const client = clientVars.client;\n const validatedOptions = clientVars.options;\n const emitter = clientVars.emitter;\n\n const goalsPromise = new Promise((resolve) => {\n const onGoals = emitter.on(goalsEvent, () => {\n emitter.off(goalsEvent, onGoals);\n resolve();\n });\n });\n client.waitUntilGoalsReady = () => goalsPromise;\n\n if (validatedOptions.fetchGoals) {\n GoalManager(clientVars, () => emitter.emit(goalsEvent));\n // Don't need to save a reference to the GoalManager - its constructor takes care of setting\n // up the necessary event wiring\n } else {\n emitter.emit(goalsEvent);\n }\n\n if (document.readyState !== 'complete') {\n window.addEventListener('load', clientVars.start);\n } else {\n clientVars.start();\n }\n\n const syncFlush = () => {\n // Synchronous events are not available in all browsers, but where they\n // are we should attempt to use them. This increases the chance of the events\n // being delivered.\n platform.synchronousFlush = true;\n client.flush().catch(() => {});\n platform.synchronousFlush = false;\n };\n\n // When the visibility of the page changes to hidden we want to flush any pending events.\n //\n // This is handled with visibility, instead of beforeunload/unload\n // because those events are not compatible with the bfcache and are unlikely\n // to be called in many situations. For more information see: https://developer.chrome.com/blog/page-lifecycle-api/\n //\n // Redundancy is included by using both the visibilitychange handler as well as\n // pagehide, because different browsers, and versions have different bugs with each.\n // This also may provide more opportunity for the events to get flushed.\n //\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'hidden') {\n syncFlush();\n }\n };\n\n document.addEventListener('visibilitychange', handleVisibilityChange);\n window.addEventListener('pagehide', syncFlush);\n\n return client;\n}\n\nexport const basicLogger = importBasicLogger.basicLogger;\n\nexport const createConsoleLogger = common.createConsoleLogger;\n\nexport const version = VERSION;\n\nfunction deprecatedInitialize(env, user, options = {}) {\n console && console.warn && console.warn(common.messages.deprecated('default export', 'named LDClient export')); // eslint-disable-line no-console\n return initialize(env, user, options);\n}\n\nexport default { initialize: deprecatedInitialize, version };\n","import newHttpRequest from './httpRequest';\n\nexport default function makeBrowserPlatform(options) {\n const ret = {\n userAgentHeaderName: 'X-LaunchDarkly-User-Agent',\n };\n\n ret.synchronousFlush = false; // this will be set to true by index.js if the page is hidden\n\n // XMLHttpRequest may not exist if we're running in a server-side rendering context\n if (window.XMLHttpRequest) {\n const disableSyncFlush = options && options.disableSyncEventPost;\n ret.httpRequest = (method, url, headers, body) => {\n const syncFlush = ret.synchronousFlush & !disableSyncFlush;\n ret.synchronousFlush = false;\n return newHttpRequest(method, url, headers, body, syncFlush);\n };\n }\n\n let hasCors;\n ret.httpAllowsPost = () => {\n // We compute this lazily because calling XMLHttpRequest() at initialization time can disrupt tests\n if (hasCors === undefined) {\n hasCors = window.XMLHttpRequest ? 'withCredentials' in new window.XMLHttpRequest() : false;\n }\n return hasCors;\n };\n\n // Image-based mechanism for sending events if POST isn't available\n ret.httpFallbackPing = (url) => {\n const img = new window.Image();\n img.src = url;\n };\n\n const eventUrlTransformer = options && options.eventUrlTransformer;\n ret.getCurrentUrl = () => (eventUrlTransformer ? eventUrlTransformer(window.location.href) : window.location.href);\n\n ret.isDoNotTrack = () => {\n let flag;\n if (window.navigator && window.navigator.doNotTrack !== undefined) {\n flag = window.navigator.doNotTrack; // FF, Chrome\n } else if (window.navigator && window.navigator.msDoNotTrack !== undefined) {\n flag = window.navigator.msDoNotTrack; // IE 9/10\n } else {\n flag = window.doNotTrack; // IE 11+, Safari\n }\n return flag === 1 || flag === true || flag === '1' || flag === 'yes';\n };\n\n try {\n if (window.localStorage) {\n ret.localStorage = {\n get: (key) =>\n new Promise((resolve) => {\n resolve(window.localStorage.getItem(key));\n }),\n set: (key, value) =>\n new Promise((resolve) => {\n window.localStorage.setItem(key, value);\n resolve();\n }),\n clear: (key) =>\n new Promise((resolve) => {\n window.localStorage.removeItem(key);\n resolve();\n }),\n };\n }\n } catch (e) {\n // In some browsers (such as Chrome), even looking at window.localStorage at all will cause a\n // security error if the feature is disabled.\n ret.localStorage = null;\n }\n\n // The browser built-in EventSource implementations do not support setting the method used for\n // the request. When useReport is true, we ensure sending the user in the body of a REPORT request\n // rather than in the URL path. If a polyfill for EventSource that supports setting the request\n // method is provided (currently, launchdarkly-eventsource is the only polyfill that both supports\n // it and gives us a way to *know* that it supports it), we use the polyfill to connect to a flag\n // stream that will provide evaluated flags for the specific user. Otherwise, when useReport is\n // true, we fall back to a generic 'ping' stream that informs the SDK to make a separate REPORT\n // request for the user's flag evaluations whenever the flag definitions have been updated.\n let eventSourceConstructor;\n const useReport = options && options.useReport;\n if (\n useReport &&\n typeof window.EventSourcePolyfill === 'function' &&\n window.EventSourcePolyfill.supportedOptions &&\n window.EventSourcePolyfill.supportedOptions.method\n ) {\n ret.eventSourceAllowsReport = true;\n eventSourceConstructor = window.EventSourcePolyfill;\n } else {\n ret.eventSourceAllowsReport = false;\n eventSourceConstructor = window.EventSource;\n }\n\n // If EventSource does not exist, the absence of eventSourceFactory will make us not try to open streams\n if (window.EventSource) {\n const timeoutMillis = 300000; // this is only used by polyfills - see below\n\n ret.eventSourceFactory = (url, options) => {\n // The standard EventSource constructor doesn't take any options, just a URL. However, some\n // EventSource polyfills allow us to specify a timeout interval, and in some cases they will\n // default to a too-short timeout if we don't specify one. So, here, we are setting the\n // timeout properties that are used by several popular polyfills.\n // Also, the skipDefaultHeaders property (if supported) tells the polyfill not to add the\n // Cache-Control header that can cause CORS problems in browsers.\n // See: https://github.com/launchdarkly/js-eventsource\n const defaultOptions = {\n heartbeatTimeout: timeoutMillis,\n silentTimeout: timeoutMillis,\n skipDefaultHeaders: true,\n };\n\n const esOptions = { ...defaultOptions, ...options };\n\n return new eventSourceConstructor(url, esOptions);\n };\n\n ret.eventSourceIsActive = (es) =>\n es.readyState === window.EventSource.OPEN || es.readyState === window.EventSource.CONNECTING;\n }\n\n ret.userAgent = 'JSClient';\n ret.version = VERSION;\n\n ret.diagnosticSdkData = {\n name: 'js-client-sdk',\n version: VERSION,\n };\n\n ret.diagnosticPlatformData = {\n name: 'JS',\n };\n\n ret.diagnosticUseCombinedEvent = true; // the browser SDK uses the \"diagnostic-combined\" event format\n\n return ret;\n}\n"],"names":["createCustomError","name","CustomError","message","code","Error","captureStackTrace","this","constructor","prototype","LDUnexpectedResponseError","LDInvalidEnvironmentIdError","LDInvalidUserError","LDInvalidEventKeyError","LDInvalidArgumentError","LDFlagFetchError","errors","LDInvalidDataError","LDTimeoutError","isHttpErrorRecoverable","status","byteLength_1","b64","lens","getLens","validLen","placeHoldersLen","toByteArray_1","tmp","i","arr","Arr","_byteLength","curByte","len","revLookup","charCodeAt","fromByteArray_1","uint8","length","extraBytes","parts","maxChunkLength","len2","push","encodeChunk","lookup","join","Uint8Array","Array","indexOf","start","end","num","output","isArray","keyList","Object","keys","hasProp","hasOwnProperty","fastDeepEqual","equal","a","b","key","arrA","arrB","dateA","Date","dateB","getTime","regexpA","RegExp","regexpB","toString","call","userAttrsToStringify","btoa","s","escaped","unescape","encodeURIComponent","base64","fromByteArray","stringToBytes","objectHasOwnProperty","object","getRandomValues","utils","appendUrlPath","baseUrl","path","endsWith","substring","startsWith","base64URLEncode","replace","clone","obj","JSON","parse","stringify","deepEquals","extend","objects","reduce","acc","getLDUserAgentString","platform","version","userAgent","onNextTick","cb","setTimeout","sanitizeContext","context","newContext","kind","undefined","forEach","attr","value","String","transformValuesToVersionedValues","flags","ret","transformVersionedValuesToValues","flagsState","wrapPromiseCallback","promise","callback","then","error","Promise","reject","once","func","result","called","args","apply","rnds8","rng","crypto","bind","msCrypto","REGEX","validate","uuid","test","_nodeId","_clockseq","byteToHex","substr","offset","arguments","toLowerCase","TypeError","_lastMSecs","_lastNSecs","v","parseInt","slice","v35","hashfunc","generateUUID","namespace","buf","str","bytes","set","err","DNS","URL","getOutputLength","inputLength8","safeAdd","x","y","lsw","md5cmn","q","t","cnt","md5ff","c","d","md5gg","md5hh","md5ii","v3","msg","input","length32","hexTab","hex","charAt","md5ToHexEncodedArray","olda","oldb","oldc","oldd","wordsToMd5","length8","Uint32Array","bytesToWords","v3$1","f","z","ROTL","n","v5","K","H","l","N","Math","ceil","M","_i","j","pow","floor","_i2","W","_t","e","_t2","T","v5$1","options","node","clockseq","seedBytes","random","msecs","now","nsecs","dt","tl","tmh","rnds","logLevels","loggers","commonBasicLogger","formatFn","destination","toConsole","methodName","line","console","destinations","prependLevelToMessage","prefix","minLevel","level","write","levelIndex","levelName","fullPrefix","tempArgs","log","logger","validateLogger","errorString","docLink","messages","bootstrapInvalid","bootstrapOldFormat","clientInitialized","clientNotReady","debugEnqueueingEvent","debugPostingDiagnosticEvent","event","debugPostingEvents","count","debugStreamDelete","debugStreamDeleteIgnored","debugStreamPatch","debugStreamPatchIgnored","debugStreamPing","debugPolling","url","debugStreamPut","deprecated","oldName","newName","environmentNotFound","environmentNotSpecified","errorFetchingFlags","eventCapacityExceeded","eventWithoutContext","httpErrorMessage","retryMessage","httpUnavailable","identifyDisabled","inspectorMethodError","type","invalidContentType","contentType","invalidData","invalidInspector","invalidKey","invalidMetricValue","badType","invalidContext","invalidTagValue","localStorageUnavailable","networkError","optionBelowMinimum","minimum","streamClosing","streamConnecting","streamError","streamReconnectDelay","tagValueTooLong","unknownCustomEventKey","unknownOption","contextNotSpecified","unrecoverableStreamError","wrongOptionType","expectedType","actualType","wrongOptionTypeBoolean","require$$0","baseOptionDefs","default","streamUrl","eventsUrl","sendEvents","streaming","sendLDHeaders","requestHeaderTransform","sendEventsOnlyForVariation","useReport","evaluationReasons","eventCapacity","flushInterval","samplingInterval","allAttributesPrivate","privateAttributes","bootstrap","diagnosticRecordingInterval","diagnosticOptOut","wrapperName","wrapperVersion","stateProvider","application","validator","validated","id","validateTagValue","inspectors","hooks","plugins","allowedTagCharacters","canonicalizeUrl","tagValue","match","warn","configuration","emitter","extraOptionDefs","optionDefs","deprecatedOptions","reportArgumentError","maybeReportError","config","opts","checkDeprecatedOptions","applyDefaults","typeDescForValue","optionDef","allowedTypes","split","validateTypesAndNames","getTags","tags","headers","getLDHeaders","h","userAgentHeaderName","tagKeys","sort","map","flattened","item","concat","transformHeaders","v1","uuidv1","require$$1","EventSender_1","environmentId","baseHeaders","sender","events","isDiagnostic","httpRequest","resolve","jsonBody","payloadId","doPostRequest","canRetry","dateStr","header","time","serverTime","getResponseInfo","catch","canonicalize_1","canonicalize","visited","includes","filter","validKind","encodeKey","checkContext","allowLegacyKey","kindValid","keyValid","kinds","every","contextKey","getContextKeys","user","entries","getContextKinds","getCanonicalKey","EventSummarizer_1","es","startDate","endDate","counters","contextKinds","summarizeEvent","counterKey","variation","counterVal","Set","contextKeys","getKinds","add","creationDate","getSummary","flagsOut","empty","values","flag","counterOut","unknown","features","clearSummary","MultiEventSummarizer_1","contextFilter","summarizers","contexts","summarizer","EventSummarizer","getSummaries","summarizersToFlush","contextsForSummaries","summary","processEscapeCharacters","getComponents","reference","component","isLiteral","compare","aIsLiteral","bIsLiteral","bComponents","aComponents","literalToReference","literal","attributeReference","cloneExcluding","target","references","stack","cloned","excluded","ptr","source","parent","pop","some","ContextFilter_1","protectedAttributes","legacyTopLevelCopyAttributes","filterSingleKind","redactAnonymous","AttributeReference","anonymous","_meta","protectedAttr","getAttributesToFilter","redactedAttributes","filtered","custom","privateAttributeNames","legacyToSingleKind","filteredContext","filterMultiKind","EventProcessor_1","diagnosticsAccumulator","processor","eventSender","EventSender","mainEventsUrl","ContextFilter","MultiEventSummarizer","flushTimer","queue","lastKnownPastTime","disabled","exceededCapacity","shouldSampleEvent","makeOutputEvent","addToOutbox","incrementDroppedEvents","enqueue","addFullEvent","addDebugEvent","trackEvents","debugEventsUntilDate","debugEvent","flush","async","eventsToSend","setEventsInLastBatch","debug","responseInfo","flushTick","stop","clearTimeout","EventEmitter_1","on","handler","off","emit","copiedHandlers","getEvents","getEventListenerCount","readyEvent","successEvent","failureEvent","InitializationState","eventEmitter","succeeded","failed","failureValue","initializationPromise","readyPromise","onReady","getInitializationPromise","onSuccess","onFailure","getReadyPromise","signalSuccess","signalFailure","PersistentFlagStore_1","storage","environment","hash","ident","store","getFlagsKey","getContext","loadFlags","get","dataStr","data","schema","$schema","ex","clearFlags","saveFlags","clear","PersistentStorage_1","localStorageProvider","loggedError","logError","isEnabled","require$$2","Stream_1","stream","evalUrlPrefix","withReasons","baseReconnectDelay","connectionAttemptStartTime","firstConnectionErrorLogged","reconnectTimeoutReference","handlers","retryCount","getNextRetryDelay","delay","computedDelayMillis","backoff","trunc","handleError","closeConnection","logConnectionResult","tryConnect","openConnection","query","readTimeoutMillis","eventSourceFactory","eventSourceAllowsReport","method","body","info","addEventListener","onerror","onopen","close","success","recordStreamInit","connect","newHash","newHandlers","disconnect","isConnected","eventSourceIsActive","promiseCoalescer_1","finallyFn","currentPromise","currentCancelFn","finalResolve","finalReject","coalescer","p","cancelFn","resultPromise","jsonContentType","Requestor_1","requestor","activeRequests","fetchJSON","endpoint","promiseCoalescer","req","statusText","getResponseError","addPromise","cancel","fetchFlagSettings","Identity_1","initialContext","onChange","setContext","AnonymousContextProcessor_1","persistentStorage","getContextKeyIdString","processSingleKindContext","getCachedContextKey","cachedId","setCachedContextKey","processContext","processedContext","all","diagnosticEvents","DiagnosticId","sdkKey","diagnosticId","sdkKeySuffix","DiagnosticsAccumulator","startTime","dataSinceDate","droppedEvents","eventsInLastBatch","streamInits","reset","getProps","setProps","props","timestamp","durationMillis","DiagnosticsManager","accumulator","combinedMode","diagnosticUseCombinedEvent","localStorageKey","diagnosticEventsUrl","periodicInterval","eventSentTime","periodicTimer","streamingEnabled","manager","makeInitProperties","sdk","makeSdkData","makeConfigData","diagnosticPlatformData","sendDiagnosticEvent","sendPeriodicEvent","currentTime","createPeriodicEventAndReset","saveProperties","sdkData","diagnosticSdkData","customBaseURI","customStreamURI","customEventsURI","eventsCapacity","eventsFlushIntervalMillis","reconnectTimeMillis","streamingDisabled","diagnosticRecordingIntervalMillis","usingSecureMode","bootstrapMode","fetchGoalsDisabled","fetchGoals","loadProperties","localStorageAvailable","nextEventTime","timeNow","setStreaming","enabled","SafeInspector_1","inspector","errorLogged","wrapper","synchronous","InspectorTypes","flagUsed","flagDetailsChanged","flagDetailChanged","clientIdentityChanged","freeze","InspectorManager_1","InspectorManager","inspectorsByType","synchronousInspectorsByType","safeInspectors","SafeInspector","safeInspector","hasListeners","onFlagUsed","flagKey","detail","onFlags","onFlagChanged","onIdentityChanged","timedPromise_1","taskName","_res","UNKNOWN_HOOK_NAME","tryExecuteStage","hookName","stage","def","getHookName","hook","getMetadata","HookRunner","initialHooks","hooksInternal","withEvaluation","defaultValue","hookContext","hookData","beforeEvaluation","executeBeforeEvaluation","updatedData","hookIndex","afterEvaluation","executeAfterEvaluation","identify","timeout","beforeIdentify","executeBeforeIdentify","afterIdentify","executeAfterIdentify","addHook","afterTrack","executeAfterTrack","UNKNOWN_PLUGIN_NAME","getPluginName","plugin","getPluginHooks","environmentMetadata","pluginHooks","getHooks","registerPlugins","client","register","createPluginEnvironment","env","pluginSdkMetadata","pluginApplicationMetadata","pluginEnvironment","clientSideId","require$$3","changeEvent","internalChangeEvent","src","initialize","specifiedOptions","createLogger","EventEmitter","initializationStateTracker","InitializationStateTracker","inspectorManager","hookRunner","createHookRunner","PersistentStorage","localStorage","diagnosticsEnabled","diagnostics","diagnosticsManager","Stream","eventProcessor","EventProcessor","Requestor","useLocalStorage","streamActive","subscribedToChangeEvents","streamForcedState","inited","closed","firstEvent","Identity","enqueueEvent","sendIdentifyEvent","anonymousContextProcessor","AnonymousContextProcessor","persistentFlagStore","PersistentFlagStore","isDoNotTrack","notifyInspectionFlagChanged","newFlag","getFlagDetail","notifyInspectionFlagsChanged","cur","sendFlagEvent","includeReason","variationIndex","flagVersion","trackReason","reason","verifyContext","variationDetailInternal","sendEvent","includeReasonInEvent","isAllFlags","notifyInspection","deleted","errorKind","prerequisites","notifyInspectionFlagUsed","connectStream","tryParseData","jsonData","ping","contextAtTimeOfPingEvent","requestedFlags","replaceAllFlags","put","patch","oldFlag","mods","newDetail","previous","current","handleFlagChanges","delete","disconnectStream","newFlags","changes","changeEventParams","updateStreamingState","shouldBeStreaming","isChangeEventKey","toUpperCase","metadataKey","validKey","metadata","readFlagsFromBootstrap","state","getInitialState","initFromStateProvider","validatedContext","signalSuccessfulInit","storedFlags","signalFailedInit","finishInit","waitForInitialization","initPromise","timeoutPromise","timedPromise","race","waitForInitializationWithTimeout","waitUntilReady","onDone","clearFirst","flagValueMap","variationDetail","track","metricValue","customEventFilter","getCurrentUrl","contextKind","haveListeners","newState","allFlags","results","finishClose","getFlagsInternal","getEnvironmentId","internalChangeEventName","_objectSpread","emptyResult","newHttpRequest","pageIsClosing","window","navigator","chromeMatch","isSyncXhrSupported","xhr","XMLHttpRequest","open","setRequestHeader","send","cancelled","getResponseHeader","responseText","abort","escapeStringRegexp","string","doesUrlMatch","matcher","href","search","regex","testUrl","canonicalUrl","pattern","GoalTracker","goals","onEvent","tracker","listenerFn","clickGoals","goal","urls","location","matches","selector","elements","document","querySelectorAll","parentNode","findGoalsForClick","dispose","removeEventListener","GoalManager","clientVars","readyCallback","goalTracker","refreshGoalTracker","sendGoalEvent","g","interval","currentUrl","previousUrl","checkUrl","poll","fn","history","pushState","watchLocation","common","goalsEvent","eventUrlTransformer","disableSyncEventPost","hasCors","disableSyncFlush","syncFlush","synchronousFlush","httpAllowsPost","httpFallbackPing","Image","eventSourceConstructor","doNotTrack","msDoNotTrack","getItem","setItem","removeItem","EventSourcePolyfill","supportedOptions","EventSource","timeoutMillis","esOptions","defaultOptions","heartbeatTimeout","silentTimeout","skipDefaultHeaders","readyState","OPEN","CONNECTING","browserPlatform","validatedOptions","goalsPromise","onGoals","waitUntilGoalsReady","visibilityState","basicLogger","importBasicLogger","index"],"mappings":"aAAA,SAASA,EAAkBC,GACzB,SAASC,EAAYC,EAASC,GAC5BC,MAAMC,mBAAqBD,MAAMC,kBAAkBC,KAAMA,KAAKC,aAC9DD,KAAKJ,QAAUA,EACfI,KAAKH,KAAOA,CACb,CAMD,OAJAF,EAAYO,UAAY,IAAIJ,MAC5BH,EAAYO,UAAUR,KAAOA,EAC7BC,EAAYO,UAAUD,YAAcN,EAE7BA,CACT,wDAEA,MAAMQ,EAA4BV,EAAkB,uCAC9CW,EAA8BX,EAAkB,yCAChDY,EAAqBZ,EAAkB,gCACvCa,EAAyBb,EAAkB,oCAC3Cc,EAAyBd,EAAkB,oCAC3Ce,EAAmBf,EAAkB,8BCR3C,IDmBA,IAAAgB,EAAiB,CACfN,4BACAC,8BACAC,qBACAC,yBACAC,yBACAG,mBAhByBjB,EAAkB,gCAiB3Ce,mBACFG,eAjBuBlB,EAAkB,4BAkBzCmB,uBAhBA,SAAgCC,GAC9B,QAAIA,GAAU,KAAOA,EAAS,OACV,MAAXA,GAA6B,MAAXA,GAA6B,MAAXA,EAG/C,GC1BAC,EAuCA,SAAqBC,GACnB,IAAIC,EAAOC,E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,OADA+F,SAAWA,QAAQ6G,MAAQ7G,QAAQ6G,KAAKqmB,GAAgBhrB,WAAW,iBAAkB,0BAC9EigB,GAAWT,EAAK3W,EAAMnM,EAC/B,EAEmDzH,QAAAA,uDAThB+1B"} \ No newline at end of file diff --git a/node_modules/launchdarkly-js-client-sdk/dist/ldclient.es.js b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.es.js new file mode 100644 index 00000000..eb66c2c8 --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.es.js @@ -0,0 +1,2 @@ +function e(e){function t(e,t){Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.message=e,this.code=t}return t.prototype=new Error,t.prototype.name=e,t.prototype.constructor=t,t}const t=e("LaunchDarklyUnexpectedResponseError"),n=e("LaunchDarklyInvalidEnvironmentIdError"),r=e("LaunchDarklyInvalidUserError"),o=e("LaunchDarklyInvalidEventKeyError"),i=e("LaunchDarklyInvalidArgumentError"),a=e("LaunchDarklyFlagFetchError");for(var s={LDUnexpectedResponseError:t,LDInvalidEnvironmentIdError:n,LDInvalidUserError:r,LDInvalidEventKeyError:o,LDInvalidArgumentError:i,LDInvalidDataError:e("LaunchDarklyInvalidDataError"),LDFlagFetchError:a,LDTimeoutError:e("LaunchDarklyTimeoutError"),isHttpErrorRecoverable:function(e){return!(e>=400&&e<500)||(400===e||408===e||429===e)}},c=function(e){var t=m(e),n=t[0],r=t[1];return 3*(n+r)/4-r},u=function(e){var t,n,r=m(e),o=r[0],i=r[1],a=new g(function(e,t,n){return 3*(t+n)/4-n}(0,o,i)),s=0,c=i>0?o-4:o;for(n=0;n>16&255,a[s++]=t>>8&255,a[s++]=255&t;2===i&&(t=f[e.charCodeAt(n)]<<2|f[e.charCodeAt(n+1)]>>4,a[s++]=255&t);1===i&&(t=f[e.charCodeAt(n)]<<10|f[e.charCodeAt(n+1)]<<4|f[e.charCodeAt(n+2)]>>2,a[s++]=t>>8&255,a[s++]=255&t);return a},l=function(e){for(var t,n=e.length,r=n%3,o=[],i=16383,a=0,s=n-r;as?s:a+i));1===r?(t=e[n-1],o.push(d[t>>2]+d[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],o.push(d[t>>10]+d[t>>4&63]+d[t<<2&63]+"="));return o.join("")},d=[],f=[],g="undefined"!=typeof Uint8Array?Uint8Array:Array,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0;p<64;++p)d[p]=v[p],f[v.charCodeAt(p)]=p;function m(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function h(e,t,n){for(var r,o,i=[],a=t;a>18&63]+d[o>>12&63]+d[o>>6&63]+d[63&o]);return i.join("")}f["-".charCodeAt(0)]=62,f["_".charCodeAt(0)]=63;var y={byteLength:c,toByteArray:u,fromByteArray:l},w=Array.isArray,b=Object.keys,k=Object.prototype.hasOwnProperty,E=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){var r,o,i,a=w(t),s=w(n);if(a&&s){if((o=t.length)!=n.length)return!1;for(r=o;0!==r--;)if(!e(t[r],n[r]))return!1;return!0}if(a!=s)return!1;var c=t instanceof Date,u=n instanceof Date;if(c!=u)return!1;if(c&&u)return t.getTime()==n.getTime();var l=t instanceof RegExp,d=n instanceof RegExp;if(l!=d)return!1;if(l&&d)return t.toString()==n.toString();var f=b(t);if((o=f.length)!==b(n).length)return!1;for(r=o;0!==r--;)if(!k.call(n,f[r]))return!1;for(r=o;0!==r--;)if(!e(t[i=f[r]],n[i]))return!1;return!0}return t!=t&&n!=n};const D=["key","ip","country","email","firstName","lastName","avatar","name"];function x(e){const t=unescape(encodeURIComponent(e));return y.fromByteArray(function(e){const t=[];for(let n=0;n({...e,...t})),{})},getLDUserAgentString:function(e){const t=e.version||"?";return e.userAgent+"/"+t},objectHasOwnProperty:C,onNextTick:function(e){setTimeout(e,0)},sanitizeContext:function(e){if(!e)return e;let t;return null!==e.kind&&void 0!==e.kind||D.forEach((n=>{const r=e[n];void 0!==r&&"string"!=typeof r&&(t=t||{...e},t[n]=String(r))})),t||e},transformValuesToVersionedValues:function(e){const t={};for(const n in e)C(e,n)&&(t[n]={value:e[n],version:0});return t},transformVersionedValuesToValues:function(e){const t={};for(const n in e)C(e,n)&&(t[n]=e[n].value);return t},wrapPromiseCallback:function(e,t){const n=e.then((e=>(t&&setTimeout((()=>{t(null,e)}),0),e)),(e=>{if(!t)return Promise.reject(e);setTimeout((()=>{t(e,null)}),0)}));return t?void 0:n},once:function(e){let t,n=!1;return function(...r){return n||(n=!0,t=e.apply(this,r)),t}}},I=new Uint8Array(16);function O(){if(!P&&!(P="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return P(I)}var T=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function L(e){return"string"==typeof e&&T.test(e)}for(var U,A,j=[],R=0;R<256;++R)j.push((R+256).toString(16).substr(1));function F(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(j[e[t+0]]+j[e[t+1]]+j[e[t+2]]+j[e[t+3]]+"-"+j[e[t+4]]+j[e[t+5]]+"-"+j[e[t+6]]+j[e[t+7]]+"-"+j[e[t+8]]+j[e[t+9]]+"-"+j[e[t+10]]+j[e[t+11]]+j[e[t+12]]+j[e[t+13]]+j[e[t+14]]+j[e[t+15]]).toLowerCase();if(!L(n))throw TypeError("Stringified UUID is invalid");return n}var N=0,$=0;function V(e){if(!L(e))throw TypeError("Invalid UUID");var t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=255&t,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=255&t,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=255&t,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=255&t,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=255&t,n}function H(e,t,n){function r(e,r,o,i){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n>>9<<4)+1}function q(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function z(e,t,n,r,o,i){return q((a=q(q(t,e),q(r,i)))<<(s=o)|a>>>32-s,n);var a,s}function K(e,t,n,r,o,i,a){return z(t&n|~t&r,e,t,o,i,a)}function _(e,t,n,r,o,i,a){return z(t&r|n&~r,e,t,o,i,a)}function J(e,t,n,r,o,i,a){return z(t^n^r,e,t,o,i,a)}function B(e,t,n,r,o,i,a){return z(n^(t|~r),e,t,o,i,a)}var G=H("v3",48,(function(e){if("string"==typeof e){var t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(var n=0;n>5]>>>o%32&255,a=parseInt(r.charAt(i>>>4&15)+r.charAt(15&i),16);t.push(a)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[r/8])<>>32-t}var Y=H("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var r=unescape(encodeURIComponent(e));e=[];for(var o=0;o>>0;w=y,y=h,h=Q(m,30)>>>0,m=p,p=E}n[0]=n[0]+p>>>0,n[1]=n[1]+m>>>0,n[2]=n[2]+h>>>0,n[3]=n[3]+y>>>0,n[4]=n[4]+w>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]})),Z=Y;var ee=Object.freeze({__proto__:null,v1:function(e,t,n){var r=t&&n||0,o=t||new Array(16),i=(e=e||{}).node||U,a=void 0!==e.clockseq?e.clockseq:A;if(null==i||null==a){var s=e.random||(e.rng||O)();null==i&&(i=U=[1|s[0],s[1],s[2],s[3],s[4],s[5]]),null==a&&(a=A=16383&(s[6]<<8|s[7]))}var c=void 0!==e.msecs?e.msecs:Date.now(),u=void 0!==e.nsecs?e.nsecs:$+1,l=c-N+(u-$)/1e4;if(l<0&&void 0===e.clockseq&&(a=a+1&16383),(l<0||c>N)&&void 0===e.nsecs&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");N=c,$=u,A=a;var d=(1e4*(268435455&(c+=122192928e5))+u)%4294967296;o[r++]=d>>>24&255,o[r++]=d>>>16&255,o[r++]=d>>>8&255,o[r++]=255&d;var f=c/4294967296*1e4&268435455;o[r++]=f>>>8&255,o[r++]=255&f,o[r++]=f>>>24&15|16,o[r++]=f>>>16&255,o[r++]=a>>>8|128,o[r++]=255&a;for(var g=0;g<6;++g)o[r+g]=i[g];return t||F(o)},v3:W,v4:function(e,t,n){var r=(e=e||{}).random||(e.rng||O)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(var o=0;o<16;++o)t[n+o]=r[o];return t}return F(r)},v5:Z,NIL:"00000000-0000-0000-0000-000000000000",version:function(e){if(!L(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)},validate:L,stringify:F,parse:V});const te=["debug","info","warn","error","none"];var ne={commonBasicLogger:function(e,t){if(e&&e.destination&&"function"!=typeof e.destination)throw new Error("destination for basicLogger was set to a non-function");function n(e){return function(t){console&&console[e]&&console[e].call(console,t)}}const r=e&&e.destination?[e.destination,e.destination,e.destination,e.destination]:[n("log"),n("info"),n("warn"),n("error")],o=!(!e||!e.destination),i=e&&void 0!==e.prefix&&null!==e.prefix?e.prefix:"[LaunchDarkly] ";let a=1;if(e&&e.level)for(let t=0;t{};else{const n=e;c[t]=function(){s(n,t,arguments)}}}return c},validateLogger:function(e){te.forEach((t=>{if("none"!==t&&(!e[t]||"function"!=typeof e[t]))throw new Error("Provided logger instance must support logger."+t+"(...) method")}))}};function re(e){return e&&e.message?e.message:"string"==typeof e||e instanceof String?e:JSON.stringify(e)}const oe=" Please see https://docs.launchdarkly.com/sdk/client-side/javascript#initialize-the-client for instructions on SDK initialization.";var ie={bootstrapInvalid:function(){return"LaunchDarkly bootstrap data is not available because the back end could not read the flags."},bootstrapOldFormat:function(){return"LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."+oe},clientInitialized:function(){return"LaunchDarkly client initialized"},clientNotReady:function(){return"LaunchDarkly client is not ready"},debugEnqueueingEvent:function(e){return'enqueueing "'+e+'" event'},debugPostingDiagnosticEvent:function(e){return"sending diagnostic event ("+e.kind+")"},debugPostingEvents:function(e){return"sending "+e+" events"},debugStreamDelete:function(e){return'received streaming deletion for flag "'+e+'"'},debugStreamDeleteIgnored:function(e){return'received streaming deletion for flag "'+e+'" but ignored due to version check'},debugStreamPatch:function(e){return'received streaming update for flag "'+e+'"'},debugStreamPatchIgnored:function(e){return'received streaming update for flag "'+e+'" but ignored due to version check'},debugStreamPing:function(){return"received ping message from stream"},debugPolling:function(e){return"polling for feature flags at "+e},debugStreamPut:function(){return"received streaming update for all flags"},deprecated:function(e,t){return t?'"'+e+'" is deprecated, please use "'+t+'"':'"'+e+'" is deprecated'},environmentNotFound:function(){return"Environment not found. Double check that you specified a valid environment/client-side ID."+oe},environmentNotSpecified:function(){return"No environment/client-side ID was specified."+oe},errorFetchingFlags:function(e){return"Error fetching flag settings: "+re(e)},eventCapacityExceeded:function(){return"Exceeded event queue capacity. Increase capacity to avoid dropping events."},eventWithoutContext:function(){return"Be sure to call `identify` in the LaunchDarkly client: https://docs.launchdarkly.com/sdk/features/identify#javascript"},httpErrorMessage:function(e,t,n){return"Received error "+e+(401===e?" (invalid SDK key)":"")+" for "+t+" - "+(s.isHttpErrorRecoverable(e)?n:"giving up permanently")},httpUnavailable:function(){return"Cannot make HTTP requests in this environment."+oe},identifyDisabled:function(){return"identify() has no effect here; it must be called on the main client instance"},inspectorMethodError:(e,t)=>`an inspector: "${t}" of type: "${e}" generated an exception`,invalidContentType:function(e){return'Expected application/json content type but got "'+e+'"'},invalidData:function(){return"Invalid data received from LaunchDarkly; connection may have been interrupted"},invalidInspector:(e,t)=>`an inspector: "${t}" of an invalid type (${e}) was configured`,invalidKey:function(){return"Event key must be a string"},invalidMetricValue:e=>`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`,invalidContext:function(){return"Invalid context specified."+oe},invalidTagValue:e=>`Config option "${e}" must only contain letters, numbers, ., _ or -.`,localStorageUnavailable:function(e){return"local storage is unavailable: "+re(e)},networkError:e=>"network error"+(e?" ("+e+")":""),optionBelowMinimum:(e,t,n)=>'Config option "'+e+'" was set to '+t+", changing to minimum value of "+n,streamClosing:function(){return"Closing stream connection"},streamConnecting:function(e){return"Opening stream connection to "+e},streamError:function(e,t){return"Error on stream connection: "+re(e)+", will continue retrying after "+t+" milliseconds."},tagValueTooLong:e=>`Value of "${e}" was longer than 64 characters and was discarded.`,unknownCustomEventKey:function(e){return'Custom event "'+e+'" does not exist'},unknownOption:e=>'Ignoring unknown config option "'+e+'"',contextNotSpecified:function(){return"No context specified."+oe},unrecoverableStreamError:e=>`Error on stream connection ${re(e)}, giving up permanently`,wrongOptionType:(e,t,n)=>'Config option "'+e+'" should be of type '+t+", got "+n+", using default value",wrongOptionTypeBoolean:(e,t)=>'Config option "'+e+'" should be a boolean, got '+t+", converting to boolean"};const{validateLogger:ae}=ne,se={baseUrl:{default:"https://app.launchdarkly.com"},streamUrl:{default:"https://clientstream.launchdarkly.com"},eventsUrl:{default:"https://events.launchdarkly.com"},sendEvents:{default:!0},streaming:{type:"boolean"},sendLDHeaders:{default:!0},requestHeaderTransform:{type:"function"},sendEventsOnlyForVariation:{default:!1},useReport:{default:!1},evaluationReasons:{default:!1},eventCapacity:{default:100,minimum:1},flushInterval:{default:2e3,minimum:2e3},samplingInterval:{default:0,minimum:0},streamReconnectDelay:{default:1e3,minimum:0},allAttributesPrivate:{default:!1},privateAttributes:{default:[]},bootstrap:{type:"string|object"},diagnosticRecordingInterval:{default:9e5,minimum:2e3},diagnosticOptOut:{default:!1},wrapperName:{type:"string"},wrapperVersion:{type:"string"},stateProvider:{type:"object"},application:{validator:function(e,t,n){const r={};t.id&&(r.id=le(`${e}.id`,t.id,n));t.version&&(r.version=le(`${e}.version`,t.version,n));return r}},inspectors:{default:[]},hooks:{default:[]},plugins:{default:[]}},ce=/^(\w|\.|-)+$/;function ue(e){return e&&e.replace(/\/+$/,"")}function le(e,t,n){if("string"==typeof t&&t.match(ce)){if(!(t.length>64))return t;n.warn(ie.tagValueTooLong(e))}else n.warn(ie.invalidTagValue(e))}var de={baseOptionDefs:se,validate:function(e,t,n,r){const o=S.extend({logger:{default:r}},se,n),i={};function a(e){S.onNextTick((()=>{t&&t.maybeReportError(new s.LDInvalidArgumentError(e))}))}let c=S.extend({},e||{});return function(e){const t=e;Object.keys(i).forEach((e=>{if(void 0!==t[e]){const n=i[e];r&&r.warn(ie.deprecated(e,n)),n&&(void 0===t[n]&&(t[n]=t[e]),delete t[e])}}))}(c),c=function(e){const t=S.extend({},e);return Object.keys(o).forEach((e=>{void 0!==t[e]&&null!==t[e]||(t[e]=o[e]&&o[e].default)})),t}(c),c=function(e){const t=S.extend({},e),n=e=>{if(null===e)return"any";if(void 0===e)return;if(Array.isArray(e))return"array";const t=typeof e;return"boolean"===t||"string"===t||"number"===t||"function"===t?t:"object"};return Object.keys(e).forEach((i=>{const s=e[i];if(null!=s){const c=o[i];if(void 0===c)a(ie.unknownOption(i));else{const o=c.type||n(c.default),u=c.validator;if(u){const n=u(i,e[i],r);void 0!==n?t[i]=n:delete t[i]}else if("any"!==o){const e=o.split("|"),r=n(s);e.indexOf(r)<0?"boolean"===o?(t[i]=!!s,a(ie.wrongOptionTypeBoolean(i,r))):(a(ie.wrongOptionType(i,o,r)),t[i]=c.default):"number"===r&&void 0!==c.minimum&&sArray.isArray(r[e])?r[e].sort().map((t=>`${e}/${t}`)):[`${e}/${r[e]}`])).reduce(((e,t)=>e.concat(t)),[]).join(" ")),n},transformHeaders:function(e,t){return t&&t.requestHeaderTransform?t.requestHeaderTransform({...e}):e}};const{v1:ve}=ee,{getLDHeaders:pe,transformHeaders:me}=ge;var he=function(e,t,n){const r=S.extend({"Content-Type":"application/json"},pe(e,n)),o={};return o.sendEvents=(t,o,i)=>{if(!e.httpRequest)return Promise.resolve();const a=JSON.stringify(t),c=i?null:ve();return function t(u){const l=i?r:S.extend({},r,{"X-LaunchDarkly-Event-Schema":"4","X-LaunchDarkly-Payload-ID":c});return e.httpRequest("POST",o,me(l,n),a).promise.then((e=>{if(e)return e.status>=400&&s.isHttpErrorRecoverable(e.status)&&u?t(!1):function(e){const t={status:e.status},n=e.header("date");if(n){const e=Date.parse(n);e&&(t.serverTime=e)}return t}(e)})).catch((()=>u?t(!1):Promise.reject()))}(!0).catch((()=>{}))},o};var ye=function e(t,n=[]){if(null===t||"object"!=typeof t)return JSON.stringify(t);if(n.includes(t))throw new Error("Cycle detected");if(Array.isArray(t)){return`[${t.map((r=>e(r,[...n,t]))).map((e=>void 0===e?"null":e)).join(",")}]`}return`{${Object.keys(t).sort().map((r=>{const o=e(t[r],[...n,t]);if(void 0!==o)return`${JSON.stringify(r)}:${o}`})).filter((e=>void 0!==e)).join(",")}}`};const{commonBasicLogger:we}=ne;function be(e){return"string"==typeof e&&"kind"!==e&&e.match(/^(\w|\.|-)+$/)}function ke(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}var Ee={checkContext:function(e,t){if(e){if(t&&(void 0===e.kind||null===e.kind))return void 0!==e.key&&null!==e.key;const n=e.key,r=void 0===e.kind?"user":e.kind,o=be(r),i="multi"===r||null!=n&&""!==n;if("multi"===r){const t=Object.keys(e).filter((e=>"kind"!==e));return i&&t.every((e=>be(e)))&&t.every((t=>{const n=e[t].key;return null!=n&&""!==n}))}return i&&o}return!1},getContextKeys:function(e,t=we()){if(!e)return;const n={},{kind:r,key:o}=e;switch(r){case void 0:n.user=`${o}`;break;case"multi":Object.entries(e).filter((([e])=>"kind"!==e)).forEach((([e,t])=>{t&&t.key&&(n[e]=t.key)}));break;case null:t.warn(`null is not a valid context kind: ${e}`);break;case"":t.warn(`'' is not a valid context kind: ${e}`);break;default:n[r]=`${o}`}return n},getContextKinds:function(e){return e?null===e.kind||void 0===e.kind?["user"]:"multi"!==e.kind?[e.kind]:Object.keys(e).filter((e=>"kind"!==e)):[]},getCanonicalKey:function(e){if(e){if((void 0===e.kind||null===e.kind||"user"===e.kind)&&e.key)return e.key;if("multi"!==e.kind&&e.key)return`${e.kind}:${ke(e.key)}`;if("multi"===e.kind)return Object.keys(e).sort().filter((e=>"kind"!==e)).map((t=>`${t}:${ke(e[t].key)}`)).join(":")}}};const{getContextKinds:De}=Ee;var xe=function(){const e={};let t=0,n=0,r={},o={};return e.summarizeEvent=e=>{if("feature"===e.kind){const i=e.key+":"+(null!==e.variation&&void 0!==e.variation?e.variation:"")+":"+(null!==e.version&&void 0!==e.version?e.version:""),a=r[i];let s=o[e.key];s||(s=new Set,o[e.key]=s),function(e){return e.context?De(e.context):e.contextKeys?Object.keys(e.contextKeys):[]}(e).forEach((e=>s.add(e))),a?a.count=a.count+1:r[i]={count:1,key:e.key,version:e.version,variation:e.variation,value:e.value,default:e.default},(0===t||e.creationDaten&&(n=e.creationDate)}},e.getSummary=()=>{const e={};let i=!0;for(const t of Object.values(r)){let n=e[t.key];n||(n={default:t.default,counters:[],contextKinds:[...o[t.key]]},e[t.key]=n);const r={value:t.value,count:t.count};void 0!==t.variation&&null!==t.variation&&(r.variation=t.variation),void 0!==t.version&&null!==t.version?r.version=t.version:r.unknown=!0,n.counters.push(r),i=!1}return i?null:{startDate:t,endDate:n,features:e,kind:"summary"}},e.clearSummary=()=>{t=0,n=0,r={},o={}},e};var Ce=function(e){let t={},n={};return{summarizeEvent:function(e){if("feature"===e.kind){const r=ye(e.context);if(!r)return;let o=t[r];o||(t[r]=xe(),o=t[r],n[r]=e.context),o.summarizeEvent(e)}},getSummaries:function(){const r=t,o=n;return t={},n={},Object.entries(r).map((([t,n])=>{const r=n.getSummary();return r.context=e.filter(o[t]),r}))}}};function Pe(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Se(e){return(e.startsWith("/")?e.substring(1):e).split("/").map((e=>e.indexOf("~")>=0?e.replace(/~1/g,"/").replace(/~0/g,"~"):e))}function Ie(e){return!e.startsWith("/")}function Oe(e,t){const n=Ie(e),r=Ie(t);if(n&&r)return e===t;if(n){const n=Se(t);return 1===n.length&&e===n[0]}if(r){const n=Se(e);return 1===n.length&&t===n[0]}return e===t}function Te(e){return`/${Pe(e)}`}var Le={cloneExcluding:function(e,t){const n=[],r={},o=[];for(n.push(...Object.keys(e).map((t=>({key:t,ptr:Te(t),source:e,parent:r,visited:[e]}))));n.length;){const e=n.pop();if(t.some((t=>Oe(t,e.ptr))))o.push(e.ptr);else{const t=e.source[e.key];if(null===t)e.parent[e.key]=t;else if(Array.isArray(t))e.parent[e.key]=[...t];else if("object"==typeof t){if(e.visited.includes(t))continue;e.parent[e.key]={},n.push(...Object.keys(t).map((n=>{return{key:n,ptr:(r=e.ptr,o=Pe(n),`${r}/${o}`),source:t,parent:e.parent[e.key],visited:[...e.visited,t]};var r,o})))}else e.parent[e.key]=t}}return{cloned:r,excluded:o.sort()}},compare:Oe,literalToReference:Te};var Ue=function(e){const t={},n=e.allAttributesPrivate,r=e.privateAttributes||[],o=["key","kind","_meta","anonymous"],i=["name","ip","firstName","lastName","email","avatar","country"],a=(e,t)=>{if("object"!=typeof e||null===e||Array.isArray(e))return;const{cloned:i,excluded:a}=Le.cloneExcluding(e,((e,t)=>(n||t&&e.anonymous?Object.keys(e):[...r,...e._meta&&e._meta.privateAttributes||[]]).filter((e=>!o.some((t=>Le.compare(e,t))))))(e,t));return i.key=String(i.key),a.length&&(i._meta||(i._meta={}),i._meta.redactedAttributes=a),i._meta&&(delete i._meta.privateAttributes,0===Object.keys(i._meta).length&&delete i._meta),void 0!==i.anonymous&&(i.anonymous=!!i.anonymous),i};return t.filter=(e,t=!1)=>void 0===e.kind||null===e.kind?a((e=>{const t={...e.custom||{},kind:"user",key:e.key};void 0!==e.anonymous&&(t.anonymous=!!e.anonymous);for(const n of i)delete t[n],void 0!==e[n]&&null!==e[n]&&(t[n]=String(e[n]));return void 0!==e.privateAttributeNames&&null!==e.privateAttributeNames&&(t._meta=t._meta||{},t._meta.privateAttributes=e.privateAttributeNames.map((e=>e.startsWith("/")?Le.literalToReference(e):e))),t})(e),t):"multi"===e.kind?((e,t)=>{const n={kind:e.kind},r=Object.keys(e);for(const o of r)if("kind"!==o){const r=a(e[o],t);r&&(n[o]=r)}return n})(e,t):a(e,t),t};const{getContextKeys:Ae}=Ee;var je=function(e,t,n,r=null,o=null,i=null){const a={},c=i||he(e,n,t),u=S.appendUrlPath(t.eventsUrl,"/events/bulk/"+n),l=Ue(t),d=Ce(l),f=t.samplingInterval,g=t.eventCapacity,v=t.flushInterval,p=t.logger;let m,h=[],y=0,w=!1,b=!1;function k(){return 0===f||0===Math.floor(Math.random()*f)}function E(e){const t=S.extend({},e);return"identify"===e.kind||"feature"===e.kind||"custom"===e.kind?t.context=l.filter(e.context):(t.contextKeys=Ae(e.context,p),delete t.context),"feature"===e.kind&&(delete t.trackEvents,delete t.debugEventsUntilDate),t}function D(e){h.lengthy&&r.debugEventsUntilDate>(new Date).getTime()):t=k(),t&&D(E(e)),n){const t=S.extend({},e,{kind:"debug"});t.context=l.filter(t.context),delete t.trackEvents,delete t.debugEventsUntilDate,D(t)}},a.flush=async function(){if(w)return Promise.resolve();const e=h;return d.getSummaries().forEach((t=>{Object.keys(t.features).length&&e.push(t)})),r&&r.setEventsInLastBatch(e.length),0===e.length?Promise.resolve():(h=[],p.debug(ie.debugPostingEvents(e.length)),c.sendEvents(e,u).then((e=>{e&&(e.serverTime&&(y=e.serverTime),s.isHttpErrorRecoverable(e.status)||(w=!0),e.status>=400&&S.onNextTick((()=>{o.maybeReportError(new s.LDUnexpectedResponseError(ie.httpErrorMessage(e.status,"event posting","some events were dropped")))})))})))},a.start=function(){const e=()=>{a.flush(),m=setTimeout(e,v)};m=setTimeout(e,v)},a.stop=function(){clearTimeout(m)},a};var Re=function(e){const t={},n={};return t.on=function(e,t,r){n[e]=n[e]||[],n[e]=n[e].concat({handler:t,context:r})},t.off=function(e,t,r){if(n[e])for(let o=0;o{const n=()=>{e.off(Fe,n),t()};e.on(Fe,n)})).catch((()=>{}));return{getInitializationPromise:()=>o||(t?Promise.resolve():n?Promise.reject(r):(o=new Promise(((t,n)=>{const r=()=>{e.off(Ne,r),t()},o=t=>{e.off($e,o),n(t)};e.on(Ne,r),e.on($e,o)})),o)),getReadyPromise:()=>i,signalSuccess:()=>{t||n||(t=!0,e.emit(Ne),e.emit(Fe))},signalFailure:o=>{t||n||(n=!0,r=o,e.emit($e,o),e.emit(Fe)),e.maybeReportError(o)}}};var He=function(e,t,n,r){const o={};function i(){let e="";const o=r.getContext();return o&&(e=n||S.btoa(JSON.stringify(o))),"ld:"+t+":"+e}return o.loadFlags=()=>e.get(i()).then((e=>{if(null==e)return null;try{let t=JSON.parse(e);if(t){const e=t.$schema;void 0===e||e<1?t=S.transformValuesToVersionedValues(t):delete t.$schema}return t}catch(e){return o.clearFlags().then((()=>null))}})),o.saveFlags=t=>{const n=S.extend({},t,{$schema:1});return e.set(i(),JSON.stringify(n))},o.clearFlags=()=>e.clear(i()),o};var Me=function(e,t){const n={};let r=!1;const o=e=>{r||(r=!0,t.warn(ie.localStorageUnavailable(e)))};return n.isEnabled=()=>!!e,n.get=t=>new Promise((n=>{e?e.get(t).then(n).catch((e=>{o(e),n(void 0)})):n(void 0)})),n.set=(t,n)=>new Promise((r=>{e?e.set(t,n).then((()=>r(!0))).catch((e=>{o(e),r(!1)})):r(!1)})),n.clear=t=>new Promise((n=>{e?e.clear(t).then((()=>n(!0))).catch((e=>{o(e),n(!1)})):n(!1)})),n};const{appendUrlPath:qe,base64URLEncode:ze,objectHasOwnProperty:Ke}=S,{getLDHeaders:_e,transformHeaders:Je}=ge,{isHttpErrorRecoverable:Be}=s;var Ge=function(e,t,n,r){const o=t.streamUrl,i=t.logger,a={},s=qe(o,"/eval/"+n),c=t.useReport,u=t.evaluationReasons,l=t.streamReconnectDelay,d=_e(e,t);let f,g=!1,v=null,p=null,m=null,h=null,y=null,w=0;function b(){const e=(t=function(){const e=l*Math.pow(2,w);return e>3e4?3e4:e}(),t-Math.trunc(.5*Math.random()*t));var t;return w+=1,e}function k(e){if(e.status&&"number"==typeof e.status&&!Be(e.status))return x(),i.error(ie.unrecoverableStreamError(e)),void(p&&(clearTimeout(p),p=null));const t=b();g||(i.warn(ie.streamError(e,t)),g=!0),C(!1),x(),E(t)}function E(e){p||(e?p=setTimeout(D,e):D())}function D(){let r;p=null;let a="";const l={headers:d,readTimeoutMillis:3e5};if(e.eventSourceFactory){null!=h&&(a="h="+h),c?e.eventSourceAllowsReport?(r=s,l.method="REPORT",l.headers["Content-Type"]="application/json",l.body=JSON.stringify(m)):(r=qe(o,"/ping/"+n),a=""):r=s+"/"+ze(JSON.stringify(m)),l.headers=Je(l.headers,t),u&&(a=a+(a?"&":"")+"withReasons=true"),r=r+(a?"?":"")+a,x(),i.info(ie.streamConnecting(r)),f=(new Date).getTime(),v=e.eventSourceFactory(r,l);for(const e in y)Ke(y,e)&&v.addEventListener(e,y[e]);v.onerror=k,v.onopen=()=>{w=0}}}function x(){v&&(i.info(ie.streamClosing()),v.close(),v=null)}function C(e){f&&r&&r.recordStreamInit(f,!e,(new Date).getTime()-f),f=null}return a.connect=function(e,t,n){m=e,h=t,y={};for(const e in n||{})y[e]=function(t){g=!1,C(!0),n[e]&&n[e](t)};E()},a.disconnect=function(){clearTimeout(p),p=null,x()},a.isConnected=function(){return!!(v&&e.eventSourceIsActive&&e.eventSourceIsActive(v))},a};var We=function(e){let t,n,r,o;const i={addPromise:(i,a)=>{t=i,n&&n(),n=a,i.then((n=>{t===i&&(r(n),e&&e())}),(n=>{t===i&&(o(n),e&&e())}))}};return i.resultPromise=new Promise(((e,t)=>{r=e,o=t})),i};const{transformHeaders:Xe,getLDHeaders:Qe}=ge,Ye="application/json";var Ze=function(e,t,n){const r=t.baseUrl,o=t.useReport,i=t.evaluationReasons,a=t.logger,c={},u={};function l(n,r){if(!e.httpRequest)return new Promise(((e,t)=>{t(new s.LDFlagFetchError(ie.httpUnavailable()))}));const o=r?"REPORT":"GET",i=Qe(e,t);r&&(i["Content-Type"]=Ye);let a=u[n];a||(a=We((()=>{delete u[n]})),u[n]=a);const c=e.httpRequest(o,n,Xe(i,t),r),l=c.promise.then((e=>{if(200===e.status){if(e.header("content-type")&&e.header("content-type").substring(0,16)===Ye)return JSON.parse(e.body);{const t=ie.invalidContentType(e.header("content-type")||"");return Promise.reject(new s.LDFlagFetchError(t))}}return Promise.reject(function(e){return 404===e.status?new s.LDInvalidEnvironmentIdError(ie.environmentNotFound()):new s.LDFlagFetchError(ie.errorFetchingFlags(e.statusText||String(e.status)))}(e))}),(e=>Promise.reject(new s.LDFlagFetchError(ie.networkError(e)))));return a.addPromise(l,(()=>{c.cancel&&c.cancel()})),a.resultPromise}return c.fetchJSON=function(e){return l(S.appendUrlPath(r,e),null)},c.fetchFlagSettings=function(e,t){let s,c,u,d="";return o?(c=[r,"/sdk/evalx/",n,"/context"].join(""),u=JSON.stringify(e)):(s=S.base64URLEncode(JSON.stringify(e)),c=[r,"/sdk/evalx/",n,"/contexts/",s].join("")),t&&(d="h="+t),i&&(d=d+(d?"&":"")+"withReasons=true"),c=c+(d?"?":"")+d,a.debug(ie.debugPolling(c)),l(c,u)},c};var et=function(e,t){const n={};let r;return n.setContext=function(e){r=S.sanitizeContext(e),r&&t&&t(S.clone(r))},n.getContext=function(){return r?S.clone(r):null},e&&n.setContext(e),n};const{v1:tt}=ee,{getContextKinds:nt}=Ee;var rt=function(e){function t(e){return null==e||"user"===e?"ld:$anonUserId":`ld:$contextKey:${e}`}function n(n,r){return null!==r.key&&void 0!==r.key?(r.key=r.key.toString(),Promise.resolve(r)):r.anonymous?function(n){return e.get(t(n))}(n).then((o=>{if(o)return r.key=o,r;{const o=tt();return r.key=o,function(n,r){return e.set(t(r),n)}(o,n).then((()=>r))}})):Promise.reject(new s.LDInvalidUserError(ie.invalidContext()))}this.processContext=e=>{if(!e)return Promise.reject(new s.LDInvalidUserError(ie.contextNotSpecified()));const t=S.clone(e);if("multi"===e.kind){const e=nt(t);return Promise.all(e.map((e=>n(e,t[e])))).then((()=>t))}return n(e.kind,t)}};const{v1:ot}=ee,{baseOptionDefs:it}=de,{appendUrlPath:at}=S;var st={DiagnosticId:function(e){const t={diagnosticId:ot()};return e&&(t.sdkKeySuffix=e.length>6?e.substring(e.length-6):e),t},DiagnosticsAccumulator:function(e){let t,n,r,o;function i(e){t=e,n=0,r=0,o=[]}return i(e),{getProps:()=>({dataSinceDate:t,droppedEvents:n,eventsInLastBatch:r,streamInits:o}),setProps:e=>{t=e.dataSinceDate,n=e.droppedEvents||0,r=e.eventsInLastBatch||0,o=e.streamInits||[]},incrementDroppedEvents:()=>{n++},setEventsInLastBatch:e=>{r=e},recordStreamInit:(e,t,n)=>{const r={timestamp:e,failed:t,durationMillis:n};o.push(r)},reset:i}},DiagnosticsManager:function(e,t,n,r,o,i,a){const s=!!e.diagnosticUseCombinedEvent,c="ld:"+o+":$diagnostics",u=at(i.eventsUrl,"/events/diagnostic/"+o),l=i.diagnosticRecordingInterval,d=n;let f,g,v=!!i.streaming;const p={};function m(){return{sdk:w(),configuration:b(),platform:e.diagnosticPlatformData}}function h(e){i.logger&&i.logger.debug(ie.debugPostingDiagnosticEvent(e)),r.sendEvents(e,u,!0).then((()=>{})).catch((()=>{}))}function y(){h(function(){const e=(new Date).getTime();let t={kind:s?"diagnostic-combined":"diagnostic",id:a,creationDate:e,...d.getProps()};return s&&(t={...t,...m()}),d.reset(e),t}()),g=setTimeout(y,l),f=(new Date).getTime(),s&&function(){if(t.isEnabled()){const e={...d.getProps()};t.set(c,JSON.stringify(e))}}()}function w(){const t={...e.diagnosticSdkData};return i.wrapperName&&(t.wrapperName=i.wrapperName),i.wrapperVersion&&(t.wrapperVersion=i.wrapperVersion),t}function b(){return{customBaseURI:i.baseUrl!==it.baseUrl.default,customStreamURI:i.streamUrl!==it.streamUrl.default,customEventsURI:i.eventsUrl!==it.eventsUrl.default,eventsCapacity:i.eventCapacity,eventsFlushIntervalMillis:i.flushInterval,reconnectTimeMillis:i.streamReconnectDelay,streamingDisabled:!v,allAttributesPrivate:!!i.allAttributesPrivate,diagnosticRecordingIntervalMillis:i.diagnosticRecordingInterval,usingSecureMode:!!i.hash,bootstrapMode:!!i.bootstrap,fetchGoalsDisabled:!i.fetchGoals,sendEventsOnlyForVariation:!!i.sendEventsOnlyForVariation}}return p.start=()=>{s?function(e){if(!t.isEnabled())return e(!1);t.get(c).then((t=>{if(t)try{const e=JSON.parse(t);d.setProps(e),f=e.dataSinceDate}catch(e){}e(!0)})).catch((()=>{e(!1)}))}((e=>{if(e){const e=(f||0)+l,t=(new Date).getTime();t>=e?y():g=setTimeout(y,e-t)}else 0===Math.floor(4*Math.random())?y():g=setTimeout(y,l)})):(h({kind:"diagnostic-init",id:a,creationDate:d.getProps().dataSinceDate,...m()}),g=setTimeout(y,l))},p.stop=()=>{g&&clearTimeout(g)},p.setStreaming=e=>{v=e},p}};var ct=function(e,t){let n=!1;const r={type:e.type,name:e.name,synchronous:e.synchronous,method:(...o)=>{try{e.method(...o)}catch{n||(n=!0,t.warn(ie.inspectorMethodError(r.type,r.name)))}}};return r};const{onNextTick:ut}=S,lt={flagUsed:"flag-used",flagDetailsChanged:"flag-details-changed",flagDetailChanged:"flag-detail-changed",clientIdentityChanged:"client-identity-changed"};Object.freeze(lt);var dt={InspectorTypes:lt,InspectorManager:function(e,t){const n={},r={[lt.flagUsed]:[],[lt.flagDetailsChanged]:[],[lt.flagDetailChanged]:[],[lt.clientIdentityChanged]:[]},o={[lt.flagUsed]:[],[lt.flagDetailsChanged]:[],[lt.flagDetailChanged]:[],[lt.clientIdentityChanged]:[]},i=e&&e.map((e=>ct(e,t)));return i&&i.forEach((e=>{Object.prototype.hasOwnProperty.call(r,e.type)&&!e.synchronous?r[e.type].push(e):Object.prototype.hasOwnProperty.call(o,e.type)&&e.synchronous?o[e.type].push(e):t.warn(ie.invalidInspector(e.type,e.name))})),n.hasListeners=e=>r[e]&&r[e].length||o[e]&&o[e].length,n.onFlagUsed=(e,t,n)=>{const i=lt.flagUsed;o[i].length&&o[i].forEach((r=>r.method(e,t,n))),r[i].length&&ut((()=>{r[i].forEach((r=>r.method(e,t,n)))}))},n.onFlags=e=>{const t=lt.flagDetailsChanged;o[t].length&&o[t].forEach((t=>t.method(e))),r[t].length&&ut((()=>{r[t].forEach((t=>t.method(e)))}))},n.onFlagChanged=(e,t)=>{const n=lt.flagDetailChanged;o[n].length&&o[n].forEach((n=>n.method(e,t))),r[n].length&&ut((()=>{r[n].forEach((n=>n.method(e,t)))}))},n.onIdentityChanged=e=>{const t=lt.clientIdentityChanged;o[t].length&&o[t].forEach((t=>t.method(e))),r[t].length&&ut((()=>{r[t].forEach((t=>t.method(e)))}))},n}};const{LDTimeoutError:ft}=s;var gt=function(e,t){return new Promise(((n,r)=>{setTimeout((()=>{r(new ft(`${t} timed out after ${e} seconds.`))}),1e3*e)}))};const vt="unknown hook";function pt(e,t,n,r,o){try{return r()}catch(r){return e?.error(`An error was encountered in "${t}" of the "${n}" hook: ${r}`),o}}function mt(e,t){try{return t.getMetadata().name||vt}catch{return e.error("Exception thrown getting metadata for hook. Unable to get hook name."),vt}}var ht=function(e,t){const n=t?[...t]:[];return{withEvaluation:function(t,r,o,i){if(0===n.length)return i();const a=[...n],s={flagKey:t,context:r,defaultValue:o},c=function(e,t,n){return t.map((t=>pt(e,"beforeEvaluation",mt(e,t),(()=>t?.beforeEvaluation?.(n,{})??{}),{})))}(e,a,s),u=i();return function(e,t,n,r,o){for(let i=t.length-1;i>=0;i-=1){const a=t[i],s=r[i];pt(e,"afterEvaluation",mt(e,a),(()=>a?.afterEvaluation?.(n,s,o)??{}),{})}}(e,a,s,c,u),u},identify:function(t,r){const o=[...n],i={context:t,timeout:r},a=function(e,t,n){return t.map((t=>pt(e,"beforeIdentify",mt(e,t),(()=>t?.beforeIdentify?.(n,{})??{}),{})))}(e,o,i);return t=>{!function(e,t,n,r,o){for(let i=t.length-1;i>=0;i-=1){const a=t[i],s=r[i];pt(e,"afterIdentify",mt(e,a),(()=>a?.afterIdentify?.(n,s,o)??{}),{})}}(e,o,i,a,t)}},addHook:function(e){n.push(e)},afterTrack:function(t){if(0===n.length)return;const r=[...n];!function(e,t,n){for(let r=t.length-1;r>=0;r-=1){const o=t[r];pt(e,"afterTrack",mt(e,o),(()=>o?.afterTrack?.(n)),void 0)}}(e,r,t)}}};const yt="unknown plugin";function wt(e,t){try{return t.getMetadata().name||yt}catch(t){return e.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),yt}}var bt={getPluginHooks:function(e,t,n){const r=[];return n.forEach((n=>{try{const o=n.getHooks?.(t);void 0===o?e.error(`Plugin ${wt(e,n)} returned undefined from getHooks.`):o&&o.length>0&&r.push(...o)}catch(t){e.error(`Exception thrown getting hooks for plugin ${wt(e,n)}. Unable to get hooks.`)}})),r},registerPlugins:function(e,t,n,r){r.forEach((r=>{try{r.register(n,t)}catch(t){e.error(`Exception thrown registering plugin ${wt(e,r)}.`)}}))},createPluginEnvironment:function(e,t,n){const r={};e.userAgent&&(r.name=e.userAgent),e.version&&(r.version=e.version),n.wrapperName&&(r.wrapperName=n.wrapperName),n.wrapperVersion&&(r.wrapperVersion=n.wrapperVersion);const o={};n.application&&(n.application.name&&(o.name=n.application.name),n.application.version&&(o.version=n.application.version));const i={sdk:r,clientSideId:t};return Object.keys(o).length>0&&(i.application=o),i}};const{commonBasicLogger:kt}=ne,{checkContext:Et,getContextKeys:Dt}=Ee,{InspectorTypes:xt,InspectorManager:Ct}=dt,{getPluginHooks:Pt,registerPlugins:St,createPluginEnvironment:It}=bt,Ot="change",Tt="internal-change";var Lt={initialize:function(e,t,n,r,o){const i=function(){if(n&&n.logger)return n.logger;return o&&o.logger&&o.logger.default||kt("warn")}(),a=Re(i),c=Ve(a),u=de.validate(n,a,o,i),l=Ct(u.inspectors,i),d=u.sendEvents;let f=e,g=u.hash;const v=[...u.plugins],p=It(r,e,u),m=Pt(i,p,v),h=ht(i,[...u.hooks,...m]),y=Me(r.localStorage,i),w=he(r,f,u),b=u.sendEvents&&!u.diagnosticOptOut,k=b?st.DiagnosticId(f):null,E=b?st.DiagnosticsAccumulator((new Date).getTime()):null,D=b?st.DiagnosticsManager(r,y,E,w,f,u,k):null,x=Ge(r,u,f,E),C=u.eventProcessor||je(r,u,f,E,a,w),P=Ze(r,u,f);let I,O,T,L={},U=u.streaming,A=!1,j=!1,R=!0;const F=u.stateProvider,N=et(null,(function(e){(function(e){if(F)return;e&&H({kind:"identify",context:e,creationDate:(new Date).getTime()})})(e),l.hasListeners(xt.clientIdentityChanged)&&l.onIdentityChanged(N.getContext())})),$=new rt(y),V=y.isEnabled()?He(y,f,g,N):null;function H(e){f&&(F&&F.enqueueEvent&&F.enqueueEvent(e)||(e.context?(R=!1,!d||j||r.isDoNotTrack()||(i.debug(ie.debugEnqueueingEvent(e.kind)),C.enqueue(e))):R&&(i.warn(ie.eventWithoutContext()),R=!1)))}function M(e,t){l.hasListeners(xt.flagDetailChanged)&&l.onFlagChanged(e.key,J(t))}function q(){l.hasListeners(xt.flagDetailsChanged)&&l.onFlags(Object.entries(L).map((([e,t])=>({key:e,detail:J(t)}))).reduce(((e,t)=>(e[t.key]=t.detail,e)),{}))}function z(e,t,n,r){const o=N.getContext(),i=new Date,a={kind:"feature",key:e,context:o,value:t?t.value:null,variation:t?t.variationIndex:null,default:n,creationDate:i.getTime()},s=L[e];s&&(a.version=s.flagVersion?s.flagVersion:s.version,a.trackEvents=s.trackEvents,a.debugEventsUntilDate=s.debugEventsUntilDate),(r||s&&s.trackReason)&&t&&(a.reason=t.reason),H(a)}function K(e){return Et(e,!1)?Promise.resolve(e):Promise.reject(new s.LDInvalidUserError(ie.invalidContext()))}function _(e,t,n,r,o,i){let a,s;return L&&S.objectHasOwnProperty(L,e)&&L[e]&&!L[e].deleted?(s=L[e],a=J(s),null!==s.value&&void 0!==s.value||(a.value=t)):a={value:t,variationIndex:null,reason:{kind:"ERROR",errorKind:"FLAG_NOT_FOUND"}},n&&(o||s?.prerequisites?.forEach((e=>{_(e,void 0,n,!1,!1,!1)})),z(e,a,t,r)),!o&&i&&function(e,t){l.hasListeners(xt.flagUsed)&&l.onFlagUsed(e,t,N.getContext())}(e,a),a}function J(e){return{value:e.value,variationIndex:void 0===e.variation?null:e.variation,reason:e.reason||null}}function B(){if(O=!0,!N.getContext())return;const e=e=>{try{return JSON.parse(e)}catch(e){return void a.maybeReportError(new s.LDInvalidDataError(ie.invalidData()))}};x.connect(N.getContext(),g,{ping:function(){i.debug(ie.debugStreamPing());const e=N.getContext();P.fetchFlagSettings(e,g).then((t=>{S.deepEquals(e,N.getContext())&&W(t||{})})).catch((e=>{a.maybeReportError(new s.LDFlagFetchError(ie.errorFetchingFlags(e)))}))},put:function(t){const n=e(t.data);n&&(i.debug(ie.debugStreamPut()),W(n))},patch:function(t){const n=e(t.data);if(!n)return;const r=L[n.key];if(!r||!r.version||!n.version||r.version{}))}function X(e){const t=Object.keys(e);if(t.length>0){const n={};t.forEach((t=>{const r=e[t].current,o=r?r.value:void 0,i=e[t].previous;a.emit(Ot+":"+t,o,i),n[t]=r?{current:o,previous:i}:{previous:i}})),a.emit(Ot,n),a.emit(Tt,L),u.sendEventsOnlyForVariation||F||t.forEach((t=>{z(t,e[t].current)}))}return I&&V?V.saveFlags(L):Promise.resolve()}function Q(){const e=U||T&&void 0===U;e&&!O?B():!e&&O&&G(),D&&D.setStreaming(e)}function Y(e){return e===Ot||e.substr(0,7)===Ot+":"}if("string"==typeof u.bootstrap&&"LOCALSTORAGE"===u.bootstrap.toUpperCase()&&(V?I=!0:i.warn(ie.localStorageUnavailable())),"object"==typeof u.bootstrap&&(L=function(e){const t=Object.keys(e),n="$flagsState",r="$valid",o=e[n];!o&&t.length&&i.warn(ie.bootstrapOldFormat()),!1===e[r]&&i.warn(ie.bootstrapInvalid());const a={};return t.forEach((t=>{if(t!==n&&t!==r){let n={value:e[t]};o&&o[t]?n=S.extend(n,o[t]):n.version=0,a[t]=n}})),a}(u.bootstrap)),F){const e=F.getInitialState();e?Z(e):F.on("init",Z),F.on("update",(function(e){e.context&&N.setContext(e.context);e.flags&&W(e.flags)}))}else(function(){if(!e)return Promise.reject(new s.LDInvalidEnvironmentIdError(ie.environmentNotSpecified()));let n;return $.processContext(t).then(K).then((e=>(n=S.once(h.identify(e,void 0)),e))).then((e=>(n?.({status:"completed"}),N.setContext(e),"object"==typeof u.bootstrap?ee():I?V.loadFlags().then((e=>null==e?(L={},P.fetchFlagSettings(N.getContext(),g).then((e=>W(e||{}))).then(ee).catch((e=>{te(new s.LDFlagFetchError(ie.errorFetchingFlags(e)))}))):(L=e,S.onNextTick(ee),P.fetchFlagSettings(N.getContext(),g).then((e=>W(e))).catch((e=>a.maybeReportError(e)))))):P.fetchFlagSettings(N.getContext(),g).then((e=>{L=e||{},q(),ee()})).catch((e=>{L={},te(e)}))))).catch((e=>{throw n?.({status:"error"}),e}))})().catch(te);function Z(e){f=e.environment,N.setContext(e.context),L={...e.flags},S.onNextTick(ee)}function ee(){i.info(ie.clientInitialized()),A=!0,Q(),c.signalSuccess()}function te(e){c.signalFailure(e)}const ne={waitForInitialization:function(e=void 0){if(null!=e){if("number"==typeof e)return function(e){e>5&&i.warn("The waitForInitialization function was called with a timeout greater than 5 seconds. We recommend a timeout of 5 seconds or less.");const t=c.getInitializationPromise(),n=gt(e,"waitForInitialization");return Promise.race([n,t]).catch((e=>{throw e instanceof s.LDTimeoutError&&i.error(`waitForInitialization error: ${e}`),e}))}(e);i.warn("The waitForInitialization method was provided with a non-numeric timeout.")}return i.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied."),c.getInitializationPromise()},waitUntilReady:()=>c.getReadyPromise(),identify:function(e,t,n){if(j)return S.wrapPromiseCallback(Promise.resolve({}),n);if(F)return i.warn(ie.identifyDisabled()),S.wrapPromiseCallback(Promise.resolve(S.transformVersionedValuesToValues(L)),n);let r;const o=I&&V?V.clearFlags():Promise.resolve();return S.wrapPromiseCallback(o.then((()=>$.processContext(e))).then(K).then((e=>(r=S.once(h.identify(e,void 0)),e))).then((e=>P.fetchFlagSettings(e,t).then((n=>{const r=S.transformVersionedValuesToValues(n);return N.setContext(e),g=t,n?W(n).then((()=>r)):r})))).then((e=>(r?.({status:"completed"}),O&&B(),e))).catch((e=>(r?.({status:"error"}),a.maybeReportError(e),Promise.reject(e)))),n)},getContext:function(){return N.getContext()},variation:function(e,t){const{value:n}=h.withEvaluation(e,N.getContext(),t,(()=>_(e,t,!0,!1,!1,!0)));return n},variationDetail:function(e,t){return h.withEvaluation(e,N.getContext(),t,(()=>_(e,t,!0,!0,!1,!0)))},track:function(e,t,n){if("string"!=typeof e)return void a.maybeReportError(new s.LDInvalidEventKeyError(ie.unknownCustomEventKey(e)));void 0!==n&&"number"!=typeof n&&i.warn(ie.invalidMetricValue(typeof n)),r.customEventFilter&&!r.customEventFilter(e)&&i.warn(ie.unknownCustomEventKey(e));const o=N.getContext(),c={kind:"custom",key:e,context:o,url:r.getCurrentUrl(),creationDate:(new Date).getTime()};o&&o.anonymous&&(c.contextKind=o.anonymous?"anonymousUser":"user"),null!=t&&(c.data=t),null!=n&&(c.metricValue=n),H(c),h.afterTrack({context:o,key:e,data:t,metricValue:n})},on:function(e,t,n){Y(e)?(T=!0,A&&Q(),a.on(e,t,n)):a.on(...arguments)},off:function(e){if(a.off(...arguments),Y(e)){let e=!1;a.getEvents().forEach((t=>{Y(t)&&a.getEventListenerCount(t)>0&&(e=!0)})),e||(T=!1,O&&void 0===U&&G())}},setStreaming:function(e){const t=null===e?void 0:e;t!==U&&(U=t,Q())},flush:function(e){return S.wrapPromiseCallback(d?C.flush():Promise.resolve(),e)},allFlags:function(){const e={};if(!L)return e;for(const t in L)S.objectHasOwnProperty(L,t)&&!L[t].deleted&&(e[t]=_(t,null,!u.sendEventsOnlyForVariation,!1,!0,!1).value);return e},close:function(e){if(j)return S.wrapPromiseCallback(Promise.resolve(),e);const t=()=>{j=!0,L={}},n=Promise.resolve().then((()=>{if(G(),D&&D.stop(),d)return C.stop(),C.flush()})).then(t).catch(t);return S.wrapPromiseCallback(n,e)},addHook:function(e){h.addHook(e)}};return St(i,p,ne,v),{client:ne,options:u,emitter:a,ident:N,logger:i,requestor:P,start:function(){d&&(D&&D.start(),C.start())},enqueueEvent:H,getFlagsInternal:function(){return L},getEnvironmentId:()=>f,internalChangeEventName:Tt}},commonBasicLogger:kt,errors:s,messages:ie,utils:S,getContextKeys:Dt},Ut=Lt.initialize,At=Lt.errors,jt=Lt.messages;function Rt(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ft(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Nt(e){for(var t=1;t{if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")};function zt(e,t,n,r){var o,i,a=(("substring"===e.kind||"regex"===e.kind)&&r.includes("/")?t:t.replace(r,"")).replace(n,"");switch(e.kind){case"exact":i=t,o=new RegExp("^"+qt(e.url)+"/?$");break;case"canonical":i=a,o=new RegExp("^"+qt(e.url)+"/?$");break;case"substring":i=a,o=new RegExp(".*"+qt(e.substring)+".*$");break;case"regex":i=a,o=new RegExp(e.pattern);break;default:return!1}return o.test(i)}function Kt(e,t){for(var n={},r=null,o=[],i=0;i0&&(r=function(e){for(var n=function(e,t){for(var n=[],r=0;r0;){for(var c=0;c0&&(r=Kt(n=e,i),function(e,t){var n,r=window.location.href;function o(){(n=window.location.href)!==r&&(r=n,t())}!function e(t,n){t(),setTimeout((function(){e(t,n)}),n)}(o,e),window.history&&window.history.pushState?window.addEventListener("popstate",o):window.addEventListener("hashchange",o)}(300,o)),t()})).catch((function(n){e.emitter.maybeReportError(new At.LDUnexpectedResponseError((n&&n.message,n.message))),t()})),{}}var Jt="goalsReady",Bt={fetchGoals:{default:!0},hash:{type:"string"},eventProcessor:{type:"object"},eventUrlTransformer:{type:"function"},disableSyncEventPost:{default:!1}};function Gt(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=function(e){var t,n={userAgentHeaderName:"X-LaunchDarkly-User-Agent",synchronousFlush:!1};if(window.XMLHttpRequest){var r=e&&e.disableSyncEventPost;n.httpRequest=function(e,t,o,i){var a=n.synchronousFlush&!r;return n.synchronousFlush=!1,Mt(e,t,o,i,a)}}n.httpAllowsPost=function(){return void 0===t&&(t=!!window.XMLHttpRequest&&"withCredentials"in new window.XMLHttpRequest),t},n.httpFallbackPing=function(e){(new window.Image).src=e};var o,i=e&&e.eventUrlTransformer;n.getCurrentUrl=function(){return i?i(window.location.href):window.location.href},n.isDoNotTrack=function(){var e;return 1===(e=window.navigator&&void 0!==window.navigator.doNotTrack?window.navigator.doNotTrack:window.navigator&&void 0!==window.navigator.msDoNotTrack?window.navigator.msDoNotTrack:window.doNotTrack)||!0===e||"1"===e||"yes"===e};try{window.localStorage&&(n.localStorage={get:function(e){return new Promise((function(t){t(window.localStorage.getItem(e))}))},set:function(e,t){return new Promise((function(n){window.localStorage.setItem(e,t),n()}))},clear:function(e){return new Promise((function(t){window.localStorage.removeItem(e),t()}))}})}catch(e){n.localStorage=null}if(e&&e.useReport&&"function"==typeof window.EventSourcePolyfill&&window.EventSourcePolyfill.supportedOptions&&window.EventSourcePolyfill.supportedOptions.method?(n.eventSourceAllowsReport=!0,o=window.EventSourcePolyfill):(n.eventSourceAllowsReport=!1,o=window.EventSource),window.EventSource){var a=3e5;n.eventSourceFactory=function(e,t){var n=Nt(Nt({},{heartbeatTimeout:a,silentTimeout:a,skipDefaultHeaders:!0}),t);return new o(e,n)},n.eventSourceIsActive=function(e){return e.readyState===window.EventSource.OPEN||e.readyState===window.EventSource.CONNECTING}}return n.userAgent="JSClient",n.version="3.8.1",n.diagnosticSdkData={name:"js-client-sdk",version:"3.8.1"},n.diagnosticPlatformData={name:"JS"},n.diagnosticUseCombinedEvent=!0,n}(n),o=Ut(e,t,n,r,Bt),i=o.client,a=o.options,s=o.emitter,c=new Promise((function(e){var t=s.on(Jt,(function(){s.off(Jt,t),e()}))}));i.waitUntilGoalsReady=function(){return c},a.fetchGoals?_t(o,(function(){return s.emit(Jt)})):s.emit(Jt),"complete"!==document.readyState?window.addEventListener("load",o.start):o.start();var u=function(){r.synchronousFlush=!0,i.flush().catch((function(){})),r.synchronousFlush=!1};return document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&u()})),window.addEventListener("pagehide",u),i}var Wt=Vt,Xt=void 0,Qt="3.8.1";var Yt={initialize:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return console&&console.warn&&console.warn(jt.deprecated("default export","named LDClient export")),Gt(e,t,n)},version:Qt};export{Wt as basicLogger,Xt as createConsoleLogger,Yt as default,Gt as initialize,Qt as version}; +//# sourceMappingURL=ldclient.es.js.map diff --git a/node_modules/launchdarkly-js-client-sdk/dist/ldclient.es.js.map b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.es.js.map new file mode 100644 index 00000000..fb77ae75 --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ldclient.es.js","sources":["../node_modules/launchdarkly-js-sdk-common/src/errors.js","../node_modules/base64-js/index.js","../node_modules/launchdarkly-js-sdk-common/node_modules/fast-deep-equal/index.js","../node_modules/launchdarkly-js-sdk-common/src/utils.js","../node_modules/uuid/dist/esm-browser/rng.js","../node_modules/uuid/dist/esm-browser/regex.js","../node_modules/uuid/dist/esm-browser/validate.js","../node_modules/uuid/dist/esm-browser/stringify.js","../node_modules/uuid/dist/esm-browser/v1.js","../node_modules/uuid/dist/esm-browser/parse.js","../node_modules/uuid/dist/esm-browser/v35.js","../node_modules/uuid/dist/esm-browser/md5.js","../node_modules/uuid/dist/esm-browser/v3.js","../node_modules/uuid/dist/esm-browser/sha1.js","../node_modules/uuid/dist/esm-browser/v5.js","../node_modules/uuid/dist/esm-browser/v4.js","../node_modules/uuid/dist/esm-browser/nil.js","../node_modules/uuid/dist/esm-browser/version.js","../node_modules/launchdarkly-js-sdk-common/src/loggers.js","../node_modules/launchdarkly-js-sdk-common/src/messages.js","../node_modules/launchdarkly-js-sdk-common/src/configuration.js","../node_modules/launchdarkly-js-sdk-common/src/headers.js","../node_modules/launchdarkly-js-sdk-common/src/EventSender.js","../node_modules/launchdarkly-js-sdk-common/src/canonicalize.js","../node_modules/launchdarkly-js-sdk-common/src/context.js","../node_modules/launchdarkly-js-sdk-common/src/EventSummarizer.js","../node_modules/launchdarkly-js-sdk-common/src/MultiEventSummarizer.js","../node_modules/launchdarkly-js-sdk-common/src/attributeReference.js","../node_modules/launchdarkly-js-sdk-common/src/ContextFilter.js","../node_modules/launchdarkly-js-sdk-common/src/EventProcessor.js","../node_modules/launchdarkly-js-sdk-common/src/EventEmitter.js","../node_modules/launchdarkly-js-sdk-common/src/InitializationState.js","../node_modules/launchdarkly-js-sdk-common/src/PersistentFlagStore.js","../node_modules/launchdarkly-js-sdk-common/src/PersistentStorage.js","../node_modules/launchdarkly-js-sdk-common/src/Stream.js","../node_modules/launchdarkly-js-sdk-common/src/promiseCoalescer.js","../node_modules/launchdarkly-js-sdk-common/src/Requestor.js","../node_modules/launchdarkly-js-sdk-common/src/Identity.js","../node_modules/launchdarkly-js-sdk-common/src/AnonymousContextProcessor.js","../node_modules/launchdarkly-js-sdk-common/src/diagnosticEvents.js","../node_modules/launchdarkly-js-sdk-common/src/SafeInspector.js","../node_modules/launchdarkly-js-sdk-common/src/InspectorManager.js","../node_modules/launchdarkly-js-sdk-common/src/timedPromise.js","../node_modules/launchdarkly-js-sdk-common/src/HookRunner.js","../node_modules/launchdarkly-js-sdk-common/src/plugins.js","../node_modules/launchdarkly-js-sdk-common/src/index.js","../src/basicLogger.js","../src/httpRequest.js","../node_modules/escape-string-regexp/index.js","../src/GoalTracker.js","../src/GoalManager.js","../src/index.js","../src/browserPlatform.js"],"sourcesContent":["function createCustomError(name) {\n function CustomError(message, code) {\n Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);\n this.message = message;\n this.code = code;\n }\n\n CustomError.prototype = new Error();\n CustomError.prototype.name = name;\n CustomError.prototype.constructor = CustomError;\n\n return CustomError;\n}\n\nconst LDUnexpectedResponseError = createCustomError('LaunchDarklyUnexpectedResponseError');\nconst LDInvalidEnvironmentIdError = createCustomError('LaunchDarklyInvalidEnvironmentIdError');\nconst LDInvalidUserError = createCustomError('LaunchDarklyInvalidUserError');\nconst LDInvalidEventKeyError = createCustomError('LaunchDarklyInvalidEventKeyError');\nconst LDInvalidArgumentError = createCustomError('LaunchDarklyInvalidArgumentError');\nconst LDFlagFetchError = createCustomError('LaunchDarklyFlagFetchError');\nconst LDInvalidDataError = createCustomError('LaunchDarklyInvalidDataError');\nconst LDTimeoutError = createCustomError('LaunchDarklyTimeoutError');\n\nfunction isHttpErrorRecoverable(status) {\n if (status >= 400 && status < 500) {\n return status === 400 || status === 408 || status === 429;\n }\n return true;\n}\n\nmodule.exports = {\n LDUnexpectedResponseError,\n LDInvalidEnvironmentIdError,\n LDInvalidUserError,\n LDInvalidEventKeyError,\n LDInvalidArgumentError,\n LDInvalidDataError,\n LDFlagFetchError,\n LDTimeoutError,\n isHttpErrorRecoverable,\n};\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","'use strict';\n\nvar isArray = Array.isArray;\nvar keyList = Object.keys;\nvar hasProp = Object.prototype.hasOwnProperty;\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n var arrA = isArray(a)\n , arrB = isArray(b)\n , i\n , length\n , key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var dateA = a instanceof Date\n , dateB = b instanceof Date;\n if (dateA != dateB) return false;\n if (dateA && dateB) return a.getTime() == b.getTime();\n\n var regexpA = a instanceof RegExp\n , regexpB = b instanceof RegExp;\n if (regexpA != regexpB) return false;\n if (regexpA && regexpB) return a.toString() == b.toString();\n\n var keys = keyList(a);\n length = keys.length;\n\n if (length !== keyList(b).length)\n return false;\n\n for (i = length; i-- !== 0;)\n if (!hasProp.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n key = keys[i];\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n return a!==a && b!==b;\n};\n","const base64 = require('base64-js');\nconst fastDeepEqual = require('fast-deep-equal');\n\nconst userAttrsToStringify = ['key', 'ip', 'country', 'email', 'firstName', 'lastName', 'avatar', 'name'];\n\nfunction appendUrlPath(baseUrl, path) {\n // Ensure that URL concatenation is done correctly regardless of whether the\n // base URL has a trailing slash or not.\n const trimBaseUrl = baseUrl.endsWith('/') ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl;\n return trimBaseUrl + (path.startsWith('/') ? '' : '/') + path;\n}\n\n// See http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html\nfunction btoa(s) {\n const escaped = unescape(encodeURIComponent(s));\n return base64.fromByteArray(stringToBytes(escaped));\n}\n\nfunction stringToBytes(s) {\n const b = [];\n for (let i = 0; i < s.length; i++) {\n b.push(s.charCodeAt(i));\n }\n return b;\n}\n\nfunction base64URLEncode(s) {\n return (\n btoa(s)\n // eslint-disable-next-line\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n );\n}\n\nfunction clone(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n\nfunction deepEquals(a, b) {\n return fastDeepEqual(a, b);\n}\n\n// Events emitted in LDClient's initialize method will happen before the consumer\n// can register a listener, so defer them to next tick.\nfunction onNextTick(cb) {\n setTimeout(cb, 0);\n}\n\n/**\n * Wrap a promise to invoke an optional callback upon resolution or rejection.\n *\n * This function assumes the callback follows the Node.js callback type: (err, value) => void\n *\n * If a callback is provided:\n * - if the promise is resolved, invoke the callback with (null, value)\n * - if the promise is rejected, invoke the callback with (error, null)\n *\n * @param {Promise} promise\n * @param {Function} callback\n * @returns Promise | undefined\n */\nfunction wrapPromiseCallback(promise, callback) {\n const ret = promise.then(\n value => {\n if (callback) {\n setTimeout(() => {\n callback(null, value);\n }, 0);\n }\n return value;\n },\n error => {\n if (callback) {\n setTimeout(() => {\n callback(error, null);\n }, 0);\n } else {\n return Promise.reject(error);\n }\n }\n );\n\n return !callback ? ret : undefined;\n}\n\n/**\n * Takes a map of flag keys to values, and returns the more verbose structure used by the\n * client stream.\n */\nfunction transformValuesToVersionedValues(flags) {\n const ret = {};\n for (const key in flags) {\n if (objectHasOwnProperty(flags, key)) {\n ret[key] = { value: flags[key], version: 0 };\n }\n }\n return ret;\n}\n\n/**\n * Converts the internal flag state map to a simple map of flag keys to values.\n */\nfunction transformVersionedValuesToValues(flagsState) {\n const ret = {};\n for (const key in flagsState) {\n if (objectHasOwnProperty(flagsState, key)) {\n ret[key] = flagsState[key].value;\n }\n }\n return ret;\n}\n\nfunction getLDUserAgentString(platform) {\n const version = platform.version || '?';\n return platform.userAgent + '/' + version;\n}\n\nfunction extend(...objects) {\n return objects.reduce((acc, obj) => ({ ...acc, ...obj }), {});\n}\n\nfunction objectHasOwnProperty(object, name) {\n return Object.prototype.hasOwnProperty.call(object, name);\n}\n\nfunction sanitizeContext(context) {\n if (!context) {\n return context;\n }\n let newContext;\n // Only stringify user attributes for legacy users.\n if (context.kind === null || context.kind === undefined) {\n userAttrsToStringify.forEach(attr => {\n const value = context[attr];\n if (value !== undefined && typeof value !== 'string') {\n newContext = newContext || { ...context };\n newContext[attr] = String(value);\n }\n });\n }\n\n return newContext || context;\n}\n\n/**\n * Creates a function that will invoke the provided function only once.\n *\n * If the function returns a value, then that returned value will be re-used for subsequent invocations.\n *\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n */\nfunction once(func) {\n let called = false;\n let result;\n return function(...args) {\n if (!called) {\n called = true;\n result = func.apply(this, args);\n }\n return result;\n };\n}\n\nmodule.exports = {\n appendUrlPath,\n base64URLEncode,\n btoa,\n clone,\n deepEquals,\n extend,\n getLDUserAgentString,\n objectHasOwnProperty,\n onNextTick,\n sanitizeContext,\n transformValuesToVersionedValues,\n transformVersionedValuesToValues,\n wrapPromiseCallback,\n once,\n};\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js'; // **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\n\nvar _clockseq; // Previous uuid creation time\n\n\nvar _lastMSecs = 0;\nvar _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || new Array(16);\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n var seedBytes = options.random || (options.rng || rng)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || stringify(b);\n}\n\nexport default v1;","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n var v;\n var arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","import stringify from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n var bytes = [];\n\n for (var i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function (name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (namespace.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n var bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return stringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","/*\n * Browser-compatible JavaScript MD5\n *\n * Modification of JavaScript MD5\n * https://github.com/blueimp/JavaScript-MD5\n *\n * Copyright 2011, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on\n * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message\n * Digest Algorithm, as defined in RFC 1321.\n * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for more info.\n */\nfunction md5(bytes) {\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = new Uint8Array(msg.length);\n\n for (var i = 0; i < msg.length; ++i) {\n bytes[i] = msg.charCodeAt(i);\n }\n }\n\n return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));\n}\n/*\n * Convert an array of little-endian words to an array of bytes\n */\n\n\nfunction md5ToHexEncodedArray(input) {\n var output = [];\n var length32 = input.length * 32;\n var hexTab = '0123456789abcdef';\n\n for (var i = 0; i < length32; i += 8) {\n var x = input[i >> 5] >>> i % 32 & 0xff;\n var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);\n output.push(hex);\n }\n\n return output;\n}\n/**\n * Calculate output length with padding and bit length\n */\n\n\nfunction getOutputLength(inputLength8) {\n return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;\n}\n/*\n * Calculate the MD5 of an array of little-endian words, and a bit length.\n */\n\n\nfunction wordsToMd5(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << len % 32;\n x[getOutputLength(len) - 1] = len;\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n a = md5ff(a, b, c, d, x[i], 7, -680876936);\n d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);\n c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);\n a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);\n d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);\n b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);\n a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);\n c = md5ff(c, d, a, b, x[i + 10], 17, -42063);\n b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);\n d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);\n c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);\n a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);\n d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);\n b = md5gg(b, c, d, a, x[i], 20, -373897302);\n a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);\n c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);\n b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);\n d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);\n c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);\n a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);\n d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);\n b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);\n a = md5hh(a, b, c, d, x[i + 5], 4, -378558);\n d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);\n c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);\n b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);\n d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);\n c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);\n a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);\n d = md5hh(d, a, b, c, x[i], 11, -358537222);\n c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);\n b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);\n a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);\n c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);\n b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = md5ii(a, b, c, d, x[i], 6, -198630844);\n d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);\n c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);\n a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);\n d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);\n b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);\n a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);\n c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);\n b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);\n d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);\n c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);\n a = safeAdd(a, olda);\n b = safeAdd(b, oldb);\n c = safeAdd(c, oldc);\n d = safeAdd(d, oldd);\n }\n\n return [a, b, c, d];\n}\n/*\n * Convert an array bytes to an array of little-endian words\n * Characters >255 have their high-byte silently ignored.\n */\n\n\nfunction bytesToWords(input) {\n if (input.length === 0) {\n return [];\n }\n\n var length8 = input.length * 8;\n var output = new Uint32Array(getOutputLength(length8));\n\n for (var i = 0; i < length8; i += 8) {\n output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;\n }\n\n return output;\n}\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n\n\nfunction safeAdd(x, y) {\n var lsw = (x & 0xffff) + (y & 0xffff);\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return msw << 16 | lsw & 0xffff;\n}\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\n\n\nfunction bitRotateLeft(num, cnt) {\n return num << cnt | num >>> 32 - cnt;\n}\n/*\n * These functions implement the four basic operations the algorithm uses.\n */\n\n\nfunction md5cmn(q, a, b, x, s, t) {\n return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);\n}\n\nfunction md5ff(a, b, c, d, x, s, t) {\n return md5cmn(b & c | ~b & d, a, b, x, s, t);\n}\n\nfunction md5gg(a, b, c, d, x, s, t) {\n return md5cmn(b & d | c & ~d, a, b, x, s, t);\n}\n\nfunction md5hh(a, b, c, d, x, s, t) {\n return md5cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction md5ii(a, b, c, d, x, s, t) {\n return md5cmn(c ^ (b | ~d), a, b, x, s, t);\n}\n\nexport default md5;","import v35 from './v35.js';\nimport md5 from './md5.js';\nvar v3 = v35('v3', 0x30, md5);\nexport default v3;","// Adapted from Chris Veness' SHA1 code at\n// http://www.movable-type.co.uk/scripts/sha1.html\nfunction f(s, x, y, z) {\n switch (s) {\n case 0:\n return x & y ^ ~x & z;\n\n case 1:\n return x ^ y ^ z;\n\n case 2:\n return x & y ^ x & z ^ y & z;\n\n case 3:\n return x ^ y ^ z;\n }\n}\n\nfunction ROTL(x, n) {\n return x << n | x >>> 32 - n;\n}\n\nfunction sha1(bytes) {\n var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = [];\n\n for (var i = 0; i < msg.length; ++i) {\n bytes.push(msg.charCodeAt(i));\n }\n } else if (!Array.isArray(bytes)) {\n // Convert Array-like to Array\n bytes = Array.prototype.slice.call(bytes);\n }\n\n bytes.push(0x80);\n var l = bytes.length / 4 + 2;\n var N = Math.ceil(l / 16);\n var M = new Array(N);\n\n for (var _i = 0; _i < N; ++_i) {\n var arr = new Uint32Array(16);\n\n for (var j = 0; j < 16; ++j) {\n arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];\n }\n\n M[_i] = arr;\n }\n\n M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);\n M[N - 1][14] = Math.floor(M[N - 1][14]);\n M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;\n\n for (var _i2 = 0; _i2 < N; ++_i2) {\n var W = new Uint32Array(80);\n\n for (var t = 0; t < 16; ++t) {\n W[t] = M[_i2][t];\n }\n\n for (var _t = 16; _t < 80; ++_t) {\n W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);\n }\n\n var a = H[0];\n var b = H[1];\n var c = H[2];\n var d = H[3];\n var e = H[4];\n\n for (var _t2 = 0; _t2 < 80; ++_t2) {\n var s = Math.floor(_t2 / 20);\n var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;\n e = d;\n d = c;\n c = ROTL(b, 30) >>> 0;\n b = a;\n a = T;\n }\n\n H[0] = H[0] + a >>> 0;\n H[1] = H[1] + b >>> 0;\n H[2] = H[2] + c >>> 0;\n H[3] = H[3] + d >>> 0;\n H[4] = H[4] + e >>> 0;\n }\n\n return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nvar v5 = v35('v5', 0x50, sha1);\nexport default v5;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","export default '00000000-0000-0000-0000-000000000000';","import validate from './validate.js';\n\nfunction version(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.substr(14, 1), 16);\n}\n\nexport default version;","const logLevels = ['debug', 'info', 'warn', 'error', 'none'];\n\n/**\n * A simple logger that writes to stderr.\n */\nfunction commonBasicLogger(options, formatFn) {\n if (options && options.destination && typeof options.destination !== 'function') {\n throw new Error('destination for basicLogger was set to a non-function');\n }\n\n function toConsole(methodName) {\n // The global console variable is not guaranteed to be defined at all times in all browsers:\n // https://www.beyondjava.net/console-log-surprises-with-internet-explorer-11-and-edge\n return function(line) {\n if (console && console[methodName]) {\n console[methodName].call(console, line);\n }\n };\n }\n const destinations =\n options && options.destination\n ? [options.destination, options.destination, options.destination, options.destination]\n : [toConsole('log'), toConsole('info'), toConsole('warn'), toConsole('error')];\n const prependLevelToMessage = !!(options && options.destination); // if we're writing to console.warn, etc. we don't need the prefix\n const prefix =\n !options || options.prefix === undefined || options.prefix === null ? '[LaunchDarkly] ' : options.prefix;\n\n let minLevel = 1; // default is 'info'\n if (options && options.level) {\n for (let i = 0; i < logLevels.length; i++) {\n if (logLevels[i] === options.level) {\n minLevel = i;\n }\n }\n }\n\n function write(levelIndex, levelName, args) {\n if (args.length < 1) {\n return;\n }\n let line;\n const fullPrefix = prependLevelToMessage ? levelName + ': ' + prefix : prefix;\n if (args.length === 1 || !formatFn) {\n line = fullPrefix + args[0];\n } else {\n const tempArgs = [...args];\n tempArgs[0] = fullPrefix + tempArgs[0];\n line = formatFn(...tempArgs);\n }\n try {\n destinations[levelIndex](line);\n } catch (err) {\n console &&\n console.log &&\n console.log(\"[LaunchDarkly] Configured logger's \" + levelName + ' method threw an exception: ' + err);\n }\n }\n\n const logger = {};\n for (let i = 0; i < logLevels.length; i++) {\n const levelName = logLevels[i];\n if (levelName !== 'none') {\n if (i < minLevel) {\n logger[levelName] = () => {};\n } else {\n const levelIndex = i;\n logger[levelName] = function() {\n // can't use arrow function with \"arguments\"\n write(levelIndex, levelName, arguments);\n };\n }\n }\n }\n\n return logger;\n}\n\nfunction validateLogger(logger) {\n logLevels.forEach(level => {\n if (level !== 'none' && (!logger[level] || typeof logger[level] !== 'function')) {\n throw new Error('Provided logger instance must support logger.' + level + '(...) method');\n // Note that the SDK normally does not throw exceptions to the application, but that rule\n // does not apply to LDClient.init() which will throw an exception if the parameters are so\n // invalid that we cannot proceed with creating the client. An invalid logger meets those\n // criteria since the SDK calls the logger during nearly all of its operations.\n }\n });\n}\n\nmodule.exports = {\n commonBasicLogger,\n validateLogger,\n};\n","const errors = require('./errors');\n\nfunction errorString(err) {\n if (err && err.message) {\n return err.message;\n }\n if (typeof err === 'string' || err instanceof String) {\n return err;\n }\n return JSON.stringify(err);\n}\n\nconst clientInitialized = function() {\n return 'LaunchDarkly client initialized';\n};\n\nconst docLink =\n ' Please see https://docs.launchdarkly.com/sdk/client-side/javascript#initialize-the-client for instructions on SDK initialization.';\n\nconst clientNotReady = function() {\n return 'LaunchDarkly client is not ready';\n};\n\nconst eventCapacityExceeded = function() {\n return 'Exceeded event queue capacity. Increase capacity to avoid dropping events.';\n};\n\nconst eventWithoutContext = function() {\n return 'Be sure to call `identify` in the LaunchDarkly client: https://docs.launchdarkly.com/sdk/features/identify#javascript';\n};\n\nconst invalidContentType = function(contentType) {\n return 'Expected application/json content type but got \"' + contentType + '\"';\n};\n\nconst invalidKey = function() {\n return 'Event key must be a string';\n};\n\nconst localStorageUnavailable = function(err) {\n return 'local storage is unavailable: ' + errorString(err);\n};\n\nconst networkError = e => 'network error' + (e ? ' (' + e + ')' : '');\n\n// We should remove unknownCustomEventKey in the future - see comments in track() in index.js\nconst unknownCustomEventKey = function(key) {\n return 'Custom event \"' + key + '\" does not exist';\n};\n\nconst environmentNotFound = function() {\n return 'Environment not found. Double check that you specified a valid environment/client-side ID.' + docLink;\n};\n\nconst environmentNotSpecified = function() {\n return 'No environment/client-side ID was specified.' + docLink;\n};\n\nconst errorFetchingFlags = function(err) {\n return 'Error fetching flag settings: ' + errorString(err);\n};\n\nconst contextNotSpecified = function() {\n return 'No context specified.' + docLink;\n};\n\nconst invalidContext = function() {\n return 'Invalid context specified.' + docLink;\n};\n\nconst invalidData = function() {\n return 'Invalid data received from LaunchDarkly; connection may have been interrupted';\n};\n\nconst bootstrapOldFormat = function() {\n return (\n 'LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. ' +\n 'Events may not be sent correctly.' +\n docLink\n );\n};\n\nconst bootstrapInvalid = function() {\n return 'LaunchDarkly bootstrap data is not available because the back end could not read the flags.';\n};\n\nconst deprecated = function(oldName, newName) {\n if (newName) {\n return '\"' + oldName + '\" is deprecated, please use \"' + newName + '\"';\n }\n return '\"' + oldName + '\" is deprecated';\n};\n\nconst httpErrorMessage = function(status, context, retryMessage) {\n return (\n 'Received error ' +\n status +\n (status === 401 ? ' (invalid SDK key)' : '') +\n ' for ' +\n context +\n ' - ' +\n (errors.isHttpErrorRecoverable(status) ? retryMessage : 'giving up permanently')\n );\n};\n\nconst httpUnavailable = function() {\n return 'Cannot make HTTP requests in this environment.' + docLink;\n};\n\nconst identifyDisabled = function() {\n return 'identify() has no effect here; it must be called on the main client instance';\n};\n\nconst streamClosing = function() {\n return 'Closing stream connection';\n};\n\nconst streamConnecting = function(url) {\n return 'Opening stream connection to ' + url;\n};\n\nconst streamError = function(err, streamReconnectDelay) {\n return (\n 'Error on stream connection: ' +\n errorString(err) +\n ', will continue retrying after ' +\n streamReconnectDelay +\n ' milliseconds.'\n );\n};\n\nconst unknownOption = name => 'Ignoring unknown config option \"' + name + '\"';\n\nconst unrecoverableStreamError = err => `Error on stream connection ${errorString(err)}, giving up permanently`;\n\nconst wrongOptionType = (name, expectedType, actualType) =>\n 'Config option \"' + name + '\" should be of type ' + expectedType + ', got ' + actualType + ', using default value';\n\nconst wrongOptionTypeBoolean = (name, actualType) =>\n 'Config option \"' + name + '\" should be a boolean, got ' + actualType + ', converting to boolean';\n\nconst optionBelowMinimum = (name, value, minimum) =>\n 'Config option \"' + name + '\" was set to ' + value + ', changing to minimum value of ' + minimum;\n\nconst debugPolling = function(url) {\n return 'polling for feature flags at ' + url;\n};\n\nconst debugStreamPing = function() {\n return 'received ping message from stream';\n};\n\nconst debugStreamPut = function() {\n return 'received streaming update for all flags';\n};\n\nconst debugStreamPatch = function(key) {\n return 'received streaming update for flag \"' + key + '\"';\n};\n\nconst debugStreamPatchIgnored = function(key) {\n return 'received streaming update for flag \"' + key + '\" but ignored due to version check';\n};\n\nconst debugStreamDelete = function(key) {\n return 'received streaming deletion for flag \"' + key + '\"';\n};\n\nconst debugStreamDeleteIgnored = function(key) {\n return 'received streaming deletion for flag \"' + key + '\" but ignored due to version check';\n};\n\nconst debugEnqueueingEvent = function(kind) {\n return 'enqueueing \"' + kind + '\" event';\n};\n\nconst debugPostingEvents = function(count) {\n return 'sending ' + count + ' events';\n};\n\nconst debugPostingDiagnosticEvent = function(event) {\n return 'sending diagnostic event (' + event.kind + ')';\n};\n\nconst invalidInspector = (type, name) => `an inspector: \"${name}\" of an invalid type (${type}) was configured`;\n\nconst inspectorMethodError = (type, name) => `an inspector: \"${name}\" of type: \"${type}\" generated an exception`;\n\nconst invalidTagValue = name => `Config option \"${name}\" must only contain letters, numbers, ., _ or -.`;\n\nconst tagValueTooLong = name => `Value of \"${name}\" was longer than 64 characters and was discarded.`;\n\nconst invalidMetricValue = badType =>\n `The track function was called with a non-numeric \"metricValue\" (${badType}), only numeric metric values are supported.`;\n\nmodule.exports = {\n bootstrapInvalid,\n bootstrapOldFormat,\n clientInitialized,\n clientNotReady,\n debugEnqueueingEvent,\n debugPostingDiagnosticEvent,\n debugPostingEvents,\n debugStreamDelete,\n debugStreamDeleteIgnored,\n debugStreamPatch,\n debugStreamPatchIgnored,\n debugStreamPing,\n debugPolling,\n debugStreamPut,\n deprecated,\n environmentNotFound,\n environmentNotSpecified,\n errorFetchingFlags,\n eventCapacityExceeded,\n eventWithoutContext,\n httpErrorMessage,\n httpUnavailable,\n identifyDisabled,\n inspectorMethodError,\n invalidContentType,\n invalidData,\n invalidInspector,\n invalidKey,\n invalidMetricValue,\n invalidContext,\n invalidTagValue,\n localStorageUnavailable,\n networkError,\n optionBelowMinimum,\n streamClosing,\n streamConnecting,\n streamError,\n tagValueTooLong,\n unknownCustomEventKey,\n unknownOption,\n contextNotSpecified,\n unrecoverableStreamError,\n wrongOptionType,\n wrongOptionTypeBoolean,\n};\n","const errors = require('./errors');\nconst { validateLogger } = require('./loggers');\nconst messages = require('./messages');\nconst utils = require('./utils');\n\n// baseOptionDefs should contain an entry for each supported configuration option in the common package.\n// Each entry can have three properties:\n// - \"default\": the default value if any\n// - \"type\": a type constraint used if the type can't be inferred from the default value). The allowable\n// values are \"boolean\", \"string\", \"number\", \"array\", \"object\", \"function\", or several of these OR'd\n// together with \"|\" (\"function|object\").\n// - \"minimum\": minimum value if any for numeric properties\n//\n// The extraOptionDefs parameter to validate() uses the same format.\nconst baseOptionDefs = {\n baseUrl: { default: 'https://app.launchdarkly.com' },\n streamUrl: { default: 'https://clientstream.launchdarkly.com' },\n eventsUrl: { default: 'https://events.launchdarkly.com' },\n sendEvents: { default: true },\n streaming: { type: 'boolean' }, // default for this is undefined, which is different from false\n sendLDHeaders: { default: true },\n requestHeaderTransform: { type: 'function' },\n sendEventsOnlyForVariation: { default: false },\n useReport: { default: false },\n evaluationReasons: { default: false },\n eventCapacity: { default: 100, minimum: 1 },\n flushInterval: { default: 2000, minimum: 2000 },\n samplingInterval: { default: 0, minimum: 0 },\n streamReconnectDelay: { default: 1000, minimum: 0 },\n allAttributesPrivate: { default: false },\n privateAttributes: { default: [] },\n bootstrap: { type: 'string|object' },\n diagnosticRecordingInterval: { default: 900000, minimum: 2000 },\n diagnosticOptOut: { default: false },\n wrapperName: { type: 'string' },\n wrapperVersion: { type: 'string' },\n stateProvider: { type: 'object' }, // not a public option, used internally\n application: { validator: applicationConfigValidator },\n inspectors: { default: [] },\n hooks: { default: [] },\n plugins: { default: [] },\n};\n\n/**\n * Expression to validate characters that are allowed in tag keys and values.\n */\nconst allowedTagCharacters = /^(\\w|\\.|-)+$/;\n\nfunction canonicalizeUrl(url) {\n return url && url.replace(/\\/+$/, '');\n}\n\n/**\n * Verify that a value meets the requirements for a tag value.\n * @param {string} tagValue\n * @param {Object} logger\n */\nfunction validateTagValue(name, tagValue, logger) {\n if (typeof tagValue !== 'string' || !tagValue.match(allowedTagCharacters)) {\n logger.warn(messages.invalidTagValue(name));\n return undefined;\n }\n if (tagValue.length > 64) {\n logger.warn(messages.tagValueTooLong(name));\n return undefined;\n }\n return tagValue;\n}\n\nfunction applicationConfigValidator(name, value, logger) {\n const validated = {};\n if (value.id) {\n validated.id = validateTagValue(`${name}.id`, value.id, logger);\n }\n if (value.version) {\n validated.version = validateTagValue(`${name}.version`, value.version, logger);\n }\n return validated;\n}\n\nfunction validate(options, emitter, extraOptionDefs, logger) {\n const optionDefs = utils.extend({ logger: { default: logger } }, baseOptionDefs, extraOptionDefs);\n\n const deprecatedOptions = {\n // As of the latest major version, there are no deprecated options. Next time we deprecate\n // something, add an item here where the property name is the deprecated name, and the\n // property value is the preferred name if any, or null/undefined if there is no replacement.\n };\n\n function checkDeprecatedOptions(config) {\n const opts = config;\n Object.keys(deprecatedOptions).forEach(oldName => {\n if (opts[oldName] !== undefined) {\n const newName = deprecatedOptions[oldName];\n logger && logger.warn(messages.deprecated(oldName, newName));\n if (newName) {\n if (opts[newName] === undefined) {\n opts[newName] = opts[oldName];\n }\n delete opts[oldName];\n }\n }\n });\n }\n\n function applyDefaults(config) {\n // This works differently from utils.extend() in that it *will not* override a default value\n // if the provided value is explicitly set to null. This provides backward compatibility\n // since in the past we only used the provided values if they were truthy.\n const ret = utils.extend({}, config);\n Object.keys(optionDefs).forEach(name => {\n if (ret[name] === undefined || ret[name] === null) {\n ret[name] = optionDefs[name] && optionDefs[name].default;\n }\n });\n return ret;\n }\n\n function validateTypesAndNames(config) {\n const ret = utils.extend({}, config);\n const typeDescForValue = value => {\n if (value === null) {\n return 'any';\n }\n if (value === undefined) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n const t = typeof value;\n if (t === 'boolean' || t === 'string' || t === 'number' || t === 'function') {\n return t;\n }\n return 'object';\n };\n Object.keys(config).forEach(name => {\n const value = config[name];\n if (value !== null && value !== undefined) {\n const optionDef = optionDefs[name];\n if (optionDef === undefined) {\n reportArgumentError(messages.unknownOption(name));\n } else {\n const expectedType = optionDef.type || typeDescForValue(optionDef.default);\n const validator = optionDef.validator;\n if (validator) {\n const validated = validator(name, config[name], logger);\n if (validated !== undefined) {\n ret[name] = validated;\n } else {\n delete ret[name];\n }\n } else if (expectedType !== 'any') {\n const allowedTypes = expectedType.split('|');\n const actualType = typeDescForValue(value);\n if (allowedTypes.indexOf(actualType) < 0) {\n if (expectedType === 'boolean') {\n ret[name] = !!value;\n reportArgumentError(messages.wrongOptionTypeBoolean(name, actualType));\n } else {\n reportArgumentError(messages.wrongOptionType(name, expectedType, actualType));\n ret[name] = optionDef.default;\n }\n } else {\n if (actualType === 'number' && optionDef.minimum !== undefined && value < optionDef.minimum) {\n reportArgumentError(messages.optionBelowMinimum(name, value, optionDef.minimum));\n ret[name] = optionDef.minimum;\n }\n }\n }\n }\n }\n });\n\n ret.baseUrl = canonicalizeUrl(ret.baseUrl);\n ret.streamUrl = canonicalizeUrl(ret.streamUrl);\n ret.eventsUrl = canonicalizeUrl(ret.eventsUrl);\n\n return ret;\n }\n\n function reportArgumentError(message) {\n utils.onNextTick(() => {\n emitter && emitter.maybeReportError(new errors.LDInvalidArgumentError(message));\n });\n }\n\n let config = utils.extend({}, options || {});\n\n checkDeprecatedOptions(config);\n\n config = applyDefaults(config);\n config = validateTypesAndNames(config);\n validateLogger(config.logger);\n\n return config;\n}\n\n/**\n * Get tags for the specified configuration.\n *\n * If any additional tags are added to the configuration, then the tags from\n * this method should be extended with those.\n * @param {Object} config The already valiated configuration.\n * @returns {Object} The tag configuration.\n */\nfunction getTags(config) {\n const tags = {};\n if (config) {\n if (config.application && config.application.id !== undefined && config.application.id !== null) {\n tags['application-id'] = [config.application.id];\n }\n if (config.application && config.application.version !== undefined && config.application.id !== null) {\n tags['application-version'] = [config.application.version];\n }\n }\n\n return tags;\n}\n\nmodule.exports = {\n baseOptionDefs,\n validate,\n getTags,\n};\n","const { getLDUserAgentString } = require('./utils');\nconst configuration = require('./configuration');\n\nfunction getLDHeaders(platform, options) {\n if (options && !options.sendLDHeaders) {\n return {};\n }\n const h = {};\n h[platform.userAgentHeaderName || 'User-Agent'] = getLDUserAgentString(platform);\n if (options && options.wrapperName) {\n h['X-LaunchDarkly-Wrapper'] = options.wrapperVersion\n ? options.wrapperName + '/' + options.wrapperVersion\n : options.wrapperName;\n }\n const tags = configuration.getTags(options);\n const tagKeys = Object.keys(tags);\n if (tagKeys.length) {\n h['x-launchdarkly-tags'] = tagKeys\n .sort()\n .map(key =>\n Array.isArray(tags[key]) ? tags[key].sort().map(value => `${key}/${value}`) : [`${key}/${tags[key]}`]\n )\n .reduce((flattened, item) => flattened.concat(item), [])\n .join(' ');\n }\n return h;\n}\n\nfunction transformHeaders(headers, options) {\n if (!options || !options.requestHeaderTransform) {\n return headers;\n }\n return options.requestHeaderTransform({ ...headers });\n}\n\nmodule.exports = {\n getLDHeaders,\n transformHeaders,\n};\n","const errors = require('./errors');\nconst utils = require('./utils');\nconst { v1: uuidv1 } = require('uuid');\nconst { getLDHeaders, transformHeaders } = require('./headers');\n\nfunction EventSender(platform, environmentId, options) {\n const baseHeaders = utils.extend({ 'Content-Type': 'application/json' }, getLDHeaders(platform, options));\n const sender = {};\n\n function getResponseInfo(result) {\n const ret = { status: result.status };\n const dateStr = result.header('date');\n if (dateStr) {\n const time = Date.parse(dateStr);\n if (time) {\n ret.serverTime = time;\n }\n }\n return ret;\n }\n\n sender.sendEvents = (events, url, isDiagnostic) => {\n if (!platform.httpRequest) {\n return Promise.resolve();\n }\n\n const jsonBody = JSON.stringify(events);\n const payloadId = isDiagnostic ? null : uuidv1();\n\n function doPostRequest(canRetry) {\n const headers = isDiagnostic\n ? baseHeaders\n : utils.extend({}, baseHeaders, {\n 'X-LaunchDarkly-Event-Schema': '4',\n 'X-LaunchDarkly-Payload-ID': payloadId,\n });\n return platform\n .httpRequest('POST', url, transformHeaders(headers, options), jsonBody)\n .promise.then(result => {\n if (!result) {\n // This was a response from a fire-and-forget request, so we won't have a status.\n return;\n }\n if (result.status >= 400 && errors.isHttpErrorRecoverable(result.status) && canRetry) {\n return doPostRequest(false);\n } else {\n return getResponseInfo(result);\n }\n })\n .catch(() => {\n if (canRetry) {\n return doPostRequest(false);\n }\n return Promise.reject();\n });\n }\n\n return doPostRequest(true).catch(() => {});\n };\n\n return sender;\n}\n\nmodule.exports = EventSender;\n","/**\n * Given some object to serialize product a canonicalized JSON string.\n * https://www.rfc-editor.org/rfc/rfc8785.html\n *\n * We do not support custom toJSON methods on objects. Objects should be limited to basic types.\n *\n * @param {any} object The object to serialize.\n * @param {any[]?} visited The list of objects that have already been visited to avoid cycles.\n * @returns {string} The canonicalized JSON string.\n */\nfunction canonicalize(object, visited = []) {\n // For JavaScript the default JSON serialization will produce canonicalized output for basic types.\n if (object === null || typeof object !== 'object') {\n return JSON.stringify(object);\n }\n\n if (visited.includes(object)) {\n throw new Error('Cycle detected');\n }\n\n if (Array.isArray(object)) {\n const values = object\n .map(item => canonicalize(item, [...visited, object]))\n .map(item => (item === undefined ? 'null' : item));\n return `[${values.join(',')}]`;\n }\n\n const values = Object.keys(object)\n .sort()\n .map(key => {\n const value = canonicalize(object[key], [...visited, object]);\n if (value !== undefined) {\n return `${JSON.stringify(key)}:${value}`;\n }\n return undefined;\n })\n .filter(item => item !== undefined);\n return `{${values.join(',')}}`;\n}\n\nmodule.exports = canonicalize;\n","const { commonBasicLogger } = require('./loggers');\n\n/**\n * Validate a context kind.\n * @param {string} kind\n * @returns true if the kind is valid.\n */\nfunction validKind(kind) {\n return typeof kind === 'string' && kind !== 'kind' && kind.match(/^(\\w|\\.|-)+$/);\n}\n\n/**\n * Perform a check of basic context requirements.\n * @param {Object} context\n * @param {boolean} allowLegacyKey If true, then a legacy user can have an\n * empty or non-string key. A legacy user is a context without a kind.\n * @returns true if the context meets basic requirements.\n */\nfunction checkContext(context, allowLegacyKey) {\n if (context) {\n if (allowLegacyKey && (context.kind === undefined || context.kind === null)) {\n return context.key !== undefined && context.key !== null;\n }\n const key = context.key;\n const kind = context.kind === undefined ? 'user' : context.kind;\n const kindValid = validKind(kind);\n const keyValid = kind === 'multi' || (key !== undefined && key !== null && key !== '');\n if (kind === 'multi') {\n const kinds = Object.keys(context).filter(key => key !== 'kind');\n return (\n keyValid &&\n kinds.every(key => validKind(key)) &&\n kinds.every(key => {\n const contextKey = context[key].key;\n return contextKey !== undefined && contextKey !== null && contextKey !== '';\n })\n );\n }\n return keyValid && kindValid;\n }\n return false;\n}\n\n/**\n * For a given context get a list of context kinds.\n * @param {Object} context\n * @returns {string[]} A list of kinds in the context.\n */\nfunction getContextKinds(context) {\n if (context) {\n if (context.kind === null || context.kind === undefined) {\n return ['user'];\n }\n if (context.kind !== 'multi') {\n return [context.kind];\n }\n return Object.keys(context).filter(kind => kind !== 'kind');\n }\n return [];\n}\n\n/**\n * The partial URL encoding is needed because : is a valid character in context keys.\n *\n * Partial encoding is the replacement of all colon (:) characters with the URL\n * encoded equivalent (%3A) and all percent (%) characters with the URL encoded\n * equivalent (%25).\n * @param {string} key The key to encode.\n * @returns {string} Partially URL encoded key.\n */\nfunction encodeKey(key) {\n if (key.includes('%') || key.includes(':')) {\n return key.replace(/%/g, '%25').replace(/:/g, '%3A');\n }\n return key;\n}\n\nfunction getCanonicalKey(context) {\n if (context) {\n if ((context.kind === undefined || context.kind === null || context.kind === 'user') && context.key) {\n return context.key;\n } else if (context.kind !== 'multi' && context.key) {\n return `${context.kind}:${encodeKey(context.key)}`;\n } else if (context.kind === 'multi') {\n return Object.keys(context)\n .sort()\n .filter(key => key !== 'kind')\n .map(key => `${key}:${encodeKey(context[key].key)}`)\n .join(':');\n }\n }\n}\n\nfunction getContextKeys(context, logger = commonBasicLogger()) {\n if (!context) {\n return undefined;\n }\n\n const keys = {};\n const { kind, key } = context;\n\n switch (kind) {\n case undefined:\n keys.user = `${key}`;\n break;\n case 'multi':\n Object.entries(context)\n .filter(([key]) => key !== 'kind')\n .forEach(([key, value]) => {\n if (value && value.key) {\n keys[key] = value.key;\n }\n });\n break;\n case null:\n logger.warn(`null is not a valid context kind: ${context}`);\n break;\n case '':\n logger.warn(`'' is not a valid context kind: ${context}`);\n break;\n default:\n keys[kind] = `${key}`;\n break;\n }\n\n return keys;\n}\n\nmodule.exports = {\n checkContext,\n getContextKeys,\n getContextKinds,\n getCanonicalKey,\n};\n","const { getContextKinds } = require('./context');\n\nfunction getKinds(event) {\n if (event.context) {\n return getContextKinds(event.context);\n }\n if (event.contextKeys) {\n return Object.keys(event.contextKeys);\n }\n return [];\n}\n\nfunction EventSummarizer() {\n const es = {};\n\n let startDate = 0,\n endDate = 0,\n counters = {},\n contextKinds = {};\n\n es.summarizeEvent = event => {\n if (event.kind === 'feature') {\n const counterKey =\n event.key +\n ':' +\n (event.variation !== null && event.variation !== undefined ? event.variation : '') +\n ':' +\n (event.version !== null && event.version !== undefined ? event.version : '');\n const counterVal = counters[counterKey];\n let kinds = contextKinds[event.key];\n if (!kinds) {\n kinds = new Set();\n contextKinds[event.key] = kinds;\n }\n getKinds(event).forEach(kind => kinds.add(kind));\n\n if (counterVal) {\n counterVal.count = counterVal.count + 1;\n } else {\n counters[counterKey] = {\n count: 1,\n key: event.key,\n version: event.version,\n variation: event.variation,\n value: event.value,\n default: event.default,\n };\n }\n if (startDate === 0 || event.creationDate < startDate) {\n startDate = event.creationDate;\n }\n if (event.creationDate > endDate) {\n endDate = event.creationDate;\n }\n }\n };\n\n es.getSummary = () => {\n const flagsOut = {};\n let empty = true;\n for (const c of Object.values(counters)) {\n let flag = flagsOut[c.key];\n if (!flag) {\n flag = {\n default: c.default,\n counters: [],\n contextKinds: [...contextKinds[c.key]],\n };\n flagsOut[c.key] = flag;\n }\n const counterOut = {\n value: c.value,\n count: c.count,\n };\n if (c.variation !== undefined && c.variation !== null) {\n counterOut.variation = c.variation;\n }\n if (c.version !== undefined && c.version !== null) {\n counterOut.version = c.version;\n } else {\n counterOut.unknown = true;\n }\n flag.counters.push(counterOut);\n empty = false;\n }\n return empty\n ? null\n : {\n startDate,\n endDate,\n features: flagsOut,\n kind: 'summary',\n };\n };\n\n es.clearSummary = () => {\n startDate = 0;\n endDate = 0;\n counters = {};\n contextKinds = {};\n };\n\n return es;\n}\n\nmodule.exports = EventSummarizer;\n","const canonicalize = require('./canonicalize');\nconst EventSummarizer = require('./EventSummarizer');\n\n/**\n * Construct a multi-event summarizer. This summarizer produces a summary event for each unique context.\n * @param {{filter: (context: any) => any}} contextFilter\n */\nfunction MultiEventSummarizer(contextFilter) {\n let summarizers = {};\n let contexts = {};\n\n /**\n * Summarize the given event.\n * @param {{\n * kind: string,\n * context?: any,\n * }} event\n */\n function summarizeEvent(event) {\n if (event.kind === 'feature') {\n const key = canonicalize(event.context);\n if (!key) {\n return;\n }\n\n let summarizer = summarizers[key];\n if (!summarizer) {\n summarizers[key] = EventSummarizer();\n summarizer = summarizers[key];\n contexts[key] = event.context;\n }\n\n summarizer.summarizeEvent(event);\n }\n }\n\n /**\n * Get the summaries of the events that have been summarized.\n * @returns {any[]}\n */\n function getSummaries() {\n const summarizersToFlush = summarizers;\n const contextsForSummaries = contexts;\n\n summarizers = {};\n contexts = {};\n return Object.entries(summarizersToFlush).map(([key, summarizer]) => {\n const summary = summarizer.getSummary();\n summary.context = contextFilter.filter(contextsForSummaries[key]);\n return summary;\n });\n }\n\n return {\n summarizeEvent,\n getSummaries,\n };\n}\n\nmodule.exports = MultiEventSummarizer;\n","/**\n * Take a key string and escape the characters to allow it to be used as a reference.\n * @param {string} key\n * @returns {string} The processed key.\n */\nfunction processEscapeCharacters(key) {\n return key.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * @param {string} reference The reference to get the components of.\n * @returns {string[]} The components of the reference. Escape characters will be converted to their representative values.\n */\nfunction getComponents(reference) {\n const referenceWithoutPrefix = reference.startsWith('/') ? reference.substring(1) : reference;\n return referenceWithoutPrefix\n .split('/')\n .map(component => (component.indexOf('~') >= 0 ? component.replace(/~1/g, '/').replace(/~0/g, '~') : component));\n}\n\n/**\n * @param {string} reference The reference to check if it is a literal.\n * @returns true if the reference is a literal.\n */\nfunction isLiteral(reference) {\n return !reference.startsWith('/');\n}\n\n/**\n * Compare two references and determine if they are equivalent.\n * @param {string} a\n * @param {string} b\n */\nfunction compare(a, b) {\n const aIsLiteral = isLiteral(a);\n const bIsLiteral = isLiteral(b);\n if (aIsLiteral && bIsLiteral) {\n return a === b;\n }\n if (aIsLiteral) {\n const bComponents = getComponents(b);\n if (bComponents.length !== 1) {\n return false;\n }\n return a === bComponents[0];\n }\n if (bIsLiteral) {\n const aComponents = getComponents(a);\n if (aComponents.length !== 1) {\n return false;\n }\n return b === aComponents[0];\n }\n return a === b;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns The two strings joined by '/'.\n */\nfunction join(a, b) {\n return `${a}/${b}`;\n}\n\n/**\n * There are cases where a field could have been named with a preceeding '/'.\n * If that attribute was private, then the literal would appear to be a reference.\n * This method can be used to convert a literal to a reference in such situations.\n * @param {string} literal The literal to convert to a reference.\n * @returns A literal which has been converted to a reference.\n */\nfunction literalToReference(literal) {\n return `/${processEscapeCharacters(literal)}`;\n}\n\n/**\n * Clone an object excluding the values referenced by a list of references.\n * @param {Object} target The object to clone.\n * @param {string[]} references A list of references from the cloned object.\n * @returns {{cloned: Object, excluded: string[]}} The cloned object and a list of excluded values.\n */\nfunction cloneExcluding(target, references) {\n const stack = [];\n const cloned = {};\n const excluded = [];\n\n stack.push(\n ...Object.keys(target).map(key => ({\n key,\n ptr: literalToReference(key),\n source: target,\n parent: cloned,\n visited: [target],\n }))\n );\n\n while (stack.length) {\n const item = stack.pop();\n if (!references.some(ptr => compare(ptr, item.ptr))) {\n const value = item.source[item.key];\n\n // Handle null because it overlaps with object, which we will want to handle later.\n if (value === null) {\n item.parent[item.key] = value;\n } else if (Array.isArray(value)) {\n item.parent[item.key] = [...value];\n } else if (typeof value === 'object') {\n //Arrays and null must already be handled.\n\n //Prevent cycles by not visiting the same object\n //with in the same branch. Parallel branches\n //may contain the same object.\n if (item.visited.includes(value)) {\n continue;\n }\n\n item.parent[item.key] = {};\n\n stack.push(\n ...Object.keys(value).map(key => ({\n key,\n ptr: join(item.ptr, processEscapeCharacters(key)),\n source: value,\n parent: item.parent[item.key],\n visited: [...item.visited, value],\n }))\n );\n } else {\n item.parent[item.key] = value;\n }\n } else {\n excluded.push(item.ptr);\n }\n }\n return { cloned, excluded: excluded.sort() };\n}\n\nmodule.exports = {\n cloneExcluding,\n compare,\n literalToReference,\n};\n","const AttributeReference = require('./attributeReference');\n\nfunction ContextFilter(config) {\n const filter = {};\n\n const allAttributesPrivate = config.allAttributesPrivate;\n const privateAttributes = config.privateAttributes || [];\n\n // These attributes cannot be removed via a private attribute.\n const protectedAttributes = ['key', 'kind', '_meta', 'anonymous'];\n\n const legacyTopLevelCopyAttributes = ['name', 'ip', 'firstName', 'lastName', 'email', 'avatar', 'country'];\n\n /**\n * For the given context and configuration get a list of attributes to filter.\n * @param {Object} context\n * @returns {string[]} A list of the attributes to filter.\n */\n const getAttributesToFilter = (context, redactAnonymous) =>\n (allAttributesPrivate || (redactAnonymous && context.anonymous)\n ? Object.keys(context)\n : [...privateAttributes, ...((context._meta && context._meta.privateAttributes) || [])]\n ).filter(attr => !protectedAttributes.some(protectedAttr => AttributeReference.compare(attr, protectedAttr)));\n\n /**\n * @param {Object} context\n * @param {boolean} redactAnonymous\n * @returns {Object} A copy of the context with private attributes removed,\n * and the redactedAttributes meta populated.\n */\n const filterSingleKind = (context, redactAnonymous) => {\n if (typeof context !== 'object' || context === null || Array.isArray(context)) {\n return undefined;\n }\n\n const { cloned, excluded } = AttributeReference.cloneExcluding(\n context,\n getAttributesToFilter(context, redactAnonymous)\n );\n cloned.key = String(cloned.key);\n if (excluded.length) {\n if (!cloned._meta) {\n cloned._meta = {};\n }\n cloned._meta.redactedAttributes = excluded;\n }\n if (cloned._meta) {\n delete cloned._meta['privateAttributes'];\n if (Object.keys(cloned._meta).length === 0) {\n delete cloned._meta;\n }\n }\n // Make sure anonymous is boolean if present.\n // Null counts as present, and would be falsy, which is the default.\n if (cloned.anonymous !== undefined) {\n cloned.anonymous = !!cloned.anonymous;\n }\n\n return cloned;\n };\n\n /**\n * @param {Object} context\n * @param {boolean} redactAnonymous\n * @returns {Object} A copy of the context with the private attributes removed,\n * and the redactedAttributes meta populated for each sub-context.\n */\n const filterMultiKind = (context, redactAnonymous) => {\n const filtered = {\n kind: context.kind,\n };\n const contextKeys = Object.keys(context);\n\n for (const contextKey of contextKeys) {\n if (contextKey !== 'kind') {\n const filteredContext = filterSingleKind(context[contextKey], redactAnonymous);\n if (filteredContext) {\n filtered[contextKey] = filteredContext;\n }\n }\n }\n return filtered;\n };\n\n /**\n * Convert the LDUser object into an LDContext object.\n * @param {Object} user The LDUser to produce an LDContext for.\n * @returns {Object} A single kind context based on the provided user.\n */\n const legacyToSingleKind = user => {\n const filtered = {\n /* Destructure custom items into the top level.\n Duplicate keys will be overridden by previously\n top level items.\n */\n ...(user.custom || {}),\n\n // Implicity a user kind.\n kind: 'user',\n\n key: user.key,\n };\n\n if (user.anonymous !== undefined) {\n filtered.anonymous = !!user.anonymous;\n }\n\n // Copy top level keys and convert them to strings.\n // Remove keys that may have been destructured from `custom`.\n for (const key of legacyTopLevelCopyAttributes) {\n delete filtered[key];\n if (user[key] !== undefined && user[key] !== null) {\n filtered[key] = String(user[key]);\n }\n }\n\n if (user.privateAttributeNames !== undefined && user.privateAttributeNames !== null) {\n filtered._meta = filtered._meta || {};\n // If any private attributes started with '/' we need to convert them to references, otherwise the '/' will\n // cause the literal to incorrectly be treated as a reference.\n filtered._meta.privateAttributes = user.privateAttributeNames.map(literal =>\n literal.startsWith('/') ? AttributeReference.literalToReference(literal) : literal\n );\n }\n\n return filtered;\n };\n\n filter.filter = (context, redactAnonymous = false) => {\n if (context.kind === undefined || context.kind === null) {\n return filterSingleKind(legacyToSingleKind(context), redactAnonymous);\n } else if (context.kind === 'multi') {\n return filterMultiKind(context, redactAnonymous);\n } else {\n return filterSingleKind(context, redactAnonymous);\n }\n };\n\n return filter;\n}\n\nmodule.exports = ContextFilter;\n","const EventSender = require('./EventSender');\nconst MultiEventSummarizer = require('./MultiEventSummarizer');\nconst ContextFilter = require('./ContextFilter');\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst utils = require('./utils');\nconst { getContextKeys } = require('./context');\n\nfunction EventProcessor(\n platform,\n options,\n environmentId,\n diagnosticsAccumulator = null,\n emitter = null,\n sender = null\n) {\n const processor = {};\n const eventSender = sender || EventSender(platform, environmentId, options);\n const mainEventsUrl = utils.appendUrlPath(options.eventsUrl, '/events/bulk/' + environmentId);\n const contextFilter = ContextFilter(options);\n const summarizer = MultiEventSummarizer(contextFilter);\n const samplingInterval = options.samplingInterval;\n const eventCapacity = options.eventCapacity;\n const flushInterval = options.flushInterval;\n const logger = options.logger;\n let queue = [];\n let lastKnownPastTime = 0;\n let disabled = false;\n let exceededCapacity = false;\n let flushTimer;\n\n function shouldSampleEvent() {\n return samplingInterval === 0 || Math.floor(Math.random() * samplingInterval) === 0;\n }\n\n function shouldDebugEvent(e) {\n if (e.debugEventsUntilDate) {\n // The \"last known past time\" comes from the last HTTP response we got from the server.\n // In case the client's time is set wrong, at least we know that any expiration date\n // earlier than that point is definitely in the past. If there's any discrepancy, we\n // want to err on the side of cutting off event debugging sooner.\n return e.debugEventsUntilDate > lastKnownPastTime && e.debugEventsUntilDate > new Date().getTime();\n }\n return false;\n }\n\n // Transform an event from its internal format to the format we use when sending a payload.\n function makeOutputEvent(e) {\n const ret = utils.extend({}, e);\n\n // Identify, feature, and custom events should all include the full context.\n // Debug events do as well, but are not handled by this code path.\n if (e.kind === 'identify' || e.kind === 'feature' || e.kind === 'custom') {\n ret.context = contextFilter.filter(e.context);\n } else {\n ret.contextKeys = getContextKeysFromEvent(e);\n delete ret['context'];\n }\n\n if (e.kind === 'feature') {\n delete ret['trackEvents'];\n delete ret['debugEventsUntilDate'];\n }\n return ret;\n }\n\n function getContextKeysFromEvent(event) {\n return getContextKeys(event.context, logger);\n }\n\n function addToOutbox(event) {\n if (queue.length < eventCapacity) {\n queue.push(event);\n exceededCapacity = false;\n } else {\n if (!exceededCapacity) {\n exceededCapacity = true;\n logger.warn(messages.eventCapacityExceeded());\n }\n if (diagnosticsAccumulator) {\n // For diagnostic events, we track how many times we had to drop an event due to exceeding the capacity.\n diagnosticsAccumulator.incrementDroppedEvents();\n }\n }\n }\n\n processor.enqueue = function(event) {\n if (disabled) {\n return;\n }\n let addFullEvent = false;\n let addDebugEvent = false;\n\n // Add event to the summary counters if appropriate\n summarizer.summarizeEvent(event);\n\n // Decide whether to add the event to the payload. Feature events may be added twice, once for\n // the event (if tracked) and once for debugging.\n if (event.kind === 'feature') {\n if (shouldSampleEvent()) {\n addFullEvent = !!event.trackEvents;\n addDebugEvent = shouldDebugEvent(event);\n }\n } else {\n addFullEvent = shouldSampleEvent();\n }\n\n if (addFullEvent) {\n addToOutbox(makeOutputEvent(event));\n }\n if (addDebugEvent) {\n const debugEvent = utils.extend({}, event, { kind: 'debug' });\n debugEvent.context = contextFilter.filter(debugEvent.context);\n delete debugEvent['trackEvents'];\n delete debugEvent['debugEventsUntilDate'];\n addToOutbox(debugEvent);\n }\n };\n\n processor.flush = async function() {\n if (disabled) {\n return Promise.resolve();\n }\n const eventsToSend = queue;\n const summaries = summarizer.getSummaries();\n\n summaries.forEach(summary => {\n if (Object.keys(summary.features).length) {\n eventsToSend.push(summary);\n }\n });\n\n if (diagnosticsAccumulator) {\n // For diagnostic events, we record how many events were in the queue at the last flush (since \"how\n // many events happened to be in the queue at the moment we decided to send a diagnostic event\" would\n // not be a very useful statistic).\n diagnosticsAccumulator.setEventsInLastBatch(eventsToSend.length);\n }\n if (eventsToSend.length === 0) {\n return Promise.resolve();\n }\n queue = [];\n logger.debug(messages.debugPostingEvents(eventsToSend.length));\n return eventSender.sendEvents(eventsToSend, mainEventsUrl).then(responseInfo => {\n if (responseInfo) {\n if (responseInfo.serverTime) {\n lastKnownPastTime = responseInfo.serverTime;\n }\n if (!errors.isHttpErrorRecoverable(responseInfo.status)) {\n disabled = true;\n }\n if (responseInfo.status >= 400) {\n utils.onNextTick(() => {\n emitter.maybeReportError(\n new errors.LDUnexpectedResponseError(\n messages.httpErrorMessage(responseInfo.status, 'event posting', 'some events were dropped')\n )\n );\n });\n }\n }\n });\n };\n\n processor.start = function() {\n const flushTick = () => {\n processor.flush();\n flushTimer = setTimeout(flushTick, flushInterval);\n };\n flushTimer = setTimeout(flushTick, flushInterval);\n };\n\n processor.stop = function() {\n clearTimeout(flushTimer);\n };\n\n return processor;\n}\n\nmodule.exports = EventProcessor;\n","function EventEmitter(logger) {\n const emitter = {};\n const events = {};\n\n const listeningTo = event => !!events[event];\n\n emitter.on = function(event, handler, context) {\n events[event] = events[event] || [];\n events[event] = events[event].concat({\n handler: handler,\n context: context,\n });\n };\n\n emitter.off = function(event, handler, context) {\n if (!events[event]) {\n return;\n }\n for (let i = 0; i < events[event].length; i++) {\n if (events[event][i].handler === handler && events[event][i].context === context) {\n events[event] = events[event].slice(0, i).concat(events[event].slice(i + 1));\n }\n }\n };\n\n emitter.emit = function(event) {\n if (!events[event]) {\n return;\n }\n // Copy the list of handlers before iterating, in case any handler adds or removes another handler.\n // Any such changes should not affect what we do here-- we want to notify every handler that existed\n // at the moment that the event was fired.\n const copiedHandlers = events[event].slice(0);\n for (let i = 0; i < copiedHandlers.length; i++) {\n copiedHandlers[i].handler.apply(copiedHandlers[i].context, Array.prototype.slice.call(arguments, 1));\n }\n };\n\n emitter.getEvents = function() {\n return Object.keys(events);\n };\n\n emitter.getEventListenerCount = function(event) {\n return events[event] ? events[event].length : 0;\n };\n\n emitter.maybeReportError = function(error) {\n if (!error) {\n return;\n }\n if (listeningTo('error')) {\n this.emit('error', error);\n } else {\n (logger || console).error(error.message);\n }\n };\n return emitter;\n}\n\nmodule.exports = EventEmitter;\n","// This file provides an abstraction of the client's startup state.\n//\n// Startup can either succeed or fail exactly once; calling signalSuccess() or signalFailure()\n// after that point has no effect.\n//\n// On success, we fire both an \"initialized\" event and a \"ready\" event. Both the waitForInitialization()\n// promise and the waitUntilReady() promise are resolved in this case.\n//\n// On failure, we fire both a \"failed\" event (with the error as a parameter) and a \"ready\" event.\n// The waitForInitialization() promise is rejected, but the waitUntilReady() promise is resolved.\n//\n// To complicate things, we must *not* create the waitForInitialization() promise unless it is\n// requested, because otherwise failures would cause an *unhandled* rejection which can be a\n// serious problem in some environments. So we use a somewhat roundabout system for tracking the\n// initialization state and lazily creating this promise.\n\nconst readyEvent = 'ready',\n successEvent = 'initialized',\n failureEvent = 'failed';\n\nfunction InitializationStateTracker(eventEmitter) {\n let succeeded = false,\n failed = false,\n failureValue = null,\n initializationPromise = null;\n\n const readyPromise = new Promise(resolve => {\n const onReady = () => {\n eventEmitter.off(readyEvent, onReady); // we can't use \"once\" because it's not available on some JS platforms\n resolve();\n };\n eventEmitter.on(readyEvent, onReady);\n }).catch(() => {}); // this Promise should never be rejected, but the catch handler is a safety measure\n\n return {\n getInitializationPromise: () => {\n if (initializationPromise) {\n return initializationPromise;\n }\n if (succeeded) {\n return Promise.resolve();\n }\n if (failed) {\n return Promise.reject(failureValue);\n }\n initializationPromise = new Promise((resolve, reject) => {\n const onSuccess = () => {\n eventEmitter.off(successEvent, onSuccess);\n resolve();\n };\n const onFailure = err => {\n eventEmitter.off(failureEvent, onFailure);\n reject(err);\n };\n eventEmitter.on(successEvent, onSuccess);\n eventEmitter.on(failureEvent, onFailure);\n });\n return initializationPromise;\n },\n\n getReadyPromise: () => readyPromise,\n\n signalSuccess: () => {\n if (!succeeded && !failed) {\n succeeded = true;\n eventEmitter.emit(successEvent);\n eventEmitter.emit(readyEvent);\n }\n },\n\n signalFailure: err => {\n if (!succeeded && !failed) {\n failed = true;\n failureValue = err;\n eventEmitter.emit(failureEvent, err);\n eventEmitter.emit(readyEvent);\n }\n eventEmitter.maybeReportError(err); // the \"error\" event can be emitted more than once, unlike the others\n },\n };\n}\n\nmodule.exports = InitializationStateTracker;\n","const utils = require('./utils');\n\nfunction PersistentFlagStore(storage, environment, hash, ident) {\n const store = {};\n\n function getFlagsKey() {\n let key = '';\n const context = ident.getContext();\n if (context) {\n key = hash || utils.btoa(JSON.stringify(context));\n }\n return 'ld:' + environment + ':' + key;\n }\n\n // Returns a Promise which will be resolved with a parsed JSON value if a stored value was available,\n // or resolved with null if there was no value or if storage was not available.\n store.loadFlags = () =>\n storage.get(getFlagsKey()).then(dataStr => {\n if (dataStr === null || dataStr === undefined) {\n return null;\n }\n try {\n let data = JSON.parse(dataStr);\n if (data) {\n const schema = data.$schema;\n if (schema === undefined || schema < 1) {\n data = utils.transformValuesToVersionedValues(data);\n } else {\n delete data['$schema'];\n }\n }\n return data;\n } catch (ex) {\n return store.clearFlags().then(() => null);\n }\n });\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n store.saveFlags = flags => {\n const data = utils.extend({}, flags, { $schema: 1 });\n return storage.set(getFlagsKey(), JSON.stringify(data));\n };\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n store.clearFlags = () => storage.clear(getFlagsKey());\n\n return store;\n}\n\nmodule.exports = PersistentFlagStore;\n","const messages = require('./messages');\n\n// The localStorageProvider is provided by the platform object. It should have the following\n// methods, each of which should return a Promise:\n// - get(key): Gets the string value, if any, for the given key\n// - set(key, value): Stores a string value for the given key\n// - remove(key): Removes the given key\n//\n// Storage is just a light wrapper of the localStorageProvider, adding error handling and\n// ensuring that we don't call it if it's unavailable. The get method will simply resolve\n// with an undefined value if there is an error or if there is no localStorageProvider.\n// None of the promises returned by Storage will ever be rejected.\n//\n// It is always possible that the underlying platform storage mechanism might fail or be\n// disabled. If so, it's likely that it will keep failing, so we will only log one warning\n// instead of repetitive warnings.\nfunction PersistentStorage(localStorageProvider, logger) {\n const storage = {};\n let loggedError = false;\n\n const logError = err => {\n if (!loggedError) {\n loggedError = true;\n logger.warn(messages.localStorageUnavailable(err));\n }\n };\n\n storage.isEnabled = () => !!localStorageProvider;\n\n // Resolves with a value, or undefined if storage is unavailable. Never rejects.\n storage.get = key =>\n new Promise(resolve => {\n if (!localStorageProvider) {\n resolve(undefined);\n return;\n }\n localStorageProvider\n .get(key)\n .then(resolve)\n .catch(err => {\n logError(err);\n resolve(undefined);\n });\n });\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n storage.set = (key, value) =>\n new Promise(resolve => {\n if (!localStorageProvider) {\n resolve(false);\n return;\n }\n localStorageProvider\n .set(key, value)\n .then(() => resolve(true))\n .catch(err => {\n logError(err);\n resolve(false);\n });\n });\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n storage.clear = key =>\n new Promise(resolve => {\n if (!localStorageProvider) {\n resolve(false);\n return;\n }\n localStorageProvider\n .clear(key)\n .then(() => resolve(true))\n .catch(err => {\n logError(err);\n resolve(false);\n });\n });\n\n return storage;\n}\n\nmodule.exports = PersistentStorage;\n","const messages = require('./messages');\nconst { appendUrlPath, base64URLEncode, objectHasOwnProperty } = require('./utils');\nconst { getLDHeaders, transformHeaders } = require('./headers');\nconst { isHttpErrorRecoverable } = require('./errors');\n\n// The underlying event source implementation is abstracted via the platform object, which should\n// have these three properties:\n// eventSourceFactory(): a function that takes a URL and optional config object and returns an object\n// with the same methods as the regular HTML5 EventSource object. The properties in the config\n// object are those supported by the launchdarkly-eventsource package; browser EventSource\n// implementations don't have any config options.\n// eventSourceIsActive(): a function that takes an EventSource-compatible object and returns true if\n// it is in an active state (connected or connecting).\n// eventSourceAllowsReport: true if REPORT is supported.\n\n// The read timeout for the stream is a fixed value that is set to be slightly longer than the expected\n// interval between heartbeats from the LaunchDarkly streaming server. If this amount of time elapses\n// with no new data, the connection will be cycled.\nconst streamReadTimeoutMillis = 5 * 60 * 1000; // 5 minutes\nconst maxRetryDelay = 30 * 1000; // Maximum retry delay 30 seconds.\nconst jitterRatio = 0.5; // Delay should be 50%-100% of calculated time.\n\nfunction Stream(platform, config, environment, diagnosticsAccumulator) {\n const baseUrl = config.streamUrl;\n const logger = config.logger;\n const stream = {};\n const evalUrlPrefix = appendUrlPath(baseUrl, '/eval/' + environment);\n const useReport = config.useReport;\n const withReasons = config.evaluationReasons;\n const baseReconnectDelay = config.streamReconnectDelay;\n const headers = getLDHeaders(platform, config);\n let firstConnectionErrorLogged = false;\n let es = null;\n let reconnectTimeoutReference = null;\n let connectionAttemptStartTime;\n let context = null;\n let hash = null;\n let handlers = null;\n let retryCount = 0;\n\n function backoff() {\n const delay = baseReconnectDelay * Math.pow(2, retryCount);\n return delay > maxRetryDelay ? maxRetryDelay : delay;\n }\n\n function jitter(computedDelayMillis) {\n return computedDelayMillis - Math.trunc(Math.random() * jitterRatio * computedDelayMillis);\n }\n\n function getNextRetryDelay() {\n const delay = jitter(backoff());\n retryCount += 1;\n return delay;\n }\n\n stream.connect = function(newContext, newHash, newHandlers) {\n context = newContext;\n hash = newHash;\n handlers = {};\n for (const key in newHandlers || {}) {\n handlers[key] = function(e) {\n // Reset the state for logging the first connection error so that the first\n // connection error following a successful connection will once again be logged.\n // We will decorate *all* handlers to do this to keep this abstraction agnostic\n // for different stream implementations.\n firstConnectionErrorLogged = false;\n logConnectionResult(true);\n newHandlers[key] && newHandlers[key](e);\n };\n }\n tryConnect();\n };\n\n stream.disconnect = function() {\n clearTimeout(reconnectTimeoutReference);\n reconnectTimeoutReference = null;\n closeConnection();\n };\n\n stream.isConnected = function() {\n return !!(es && platform.eventSourceIsActive && platform.eventSourceIsActive(es));\n };\n\n function handleError(err) {\n // The event source may not produce a status. But the LaunchDarkly\n // polyfill can. If we can get the status, then we should stop retrying\n // on certain error codes.\n if (err.status && typeof err.status === 'number' && !isHttpErrorRecoverable(err.status)) {\n // If we encounter an unrecoverable condition, then we do not want to\n // retry anymore.\n closeConnection();\n logger.error(messages.unrecoverableStreamError(err));\n // Ensure any pending retry attempts are not done.\n if (reconnectTimeoutReference) {\n clearTimeout(reconnectTimeoutReference);\n reconnectTimeoutReference = null;\n }\n return;\n }\n\n const delay = getNextRetryDelay();\n\n if (!firstConnectionErrorLogged) {\n logger.warn(messages.streamError(err, delay));\n firstConnectionErrorLogged = true;\n }\n logConnectionResult(false);\n closeConnection();\n tryConnect(delay);\n }\n\n function tryConnect(delay) {\n if (!reconnectTimeoutReference) {\n if (delay) {\n reconnectTimeoutReference = setTimeout(openConnection, delay);\n } else {\n openConnection();\n }\n }\n }\n\n function openConnection() {\n reconnectTimeoutReference = null;\n let url;\n let query = '';\n const options = { headers, readTimeoutMillis: streamReadTimeoutMillis };\n if (platform.eventSourceFactory) {\n if (hash !== null && hash !== undefined) {\n query = 'h=' + hash;\n }\n if (useReport) {\n if (platform.eventSourceAllowsReport) {\n url = evalUrlPrefix;\n options.method = 'REPORT';\n options.headers['Content-Type'] = 'application/json';\n options.body = JSON.stringify(context);\n } else {\n // if we can't do REPORT, fall back to the old ping-based stream\n url = appendUrlPath(baseUrl, '/ping/' + environment);\n query = '';\n }\n } else {\n url = evalUrlPrefix + '/' + base64URLEncode(JSON.stringify(context));\n }\n options.headers = transformHeaders(options.headers, config);\n if (withReasons) {\n query = query + (query ? '&' : '') + 'withReasons=true';\n }\n url = url + (query ? '?' : '') + query;\n\n closeConnection();\n logger.info(messages.streamConnecting(url));\n logConnectionStarted();\n\n es = platform.eventSourceFactory(url, options);\n for (const key in handlers) {\n if (objectHasOwnProperty(handlers, key)) {\n es.addEventListener(key, handlers[key]);\n }\n }\n\n es.onerror = handleError;\n\n es.onopen = () => {\n // If the connection is a success, then reset the retryCount.\n retryCount = 0;\n };\n }\n }\n\n function closeConnection() {\n if (es) {\n logger.info(messages.streamClosing());\n es.close();\n es = null;\n }\n }\n\n function logConnectionStarted() {\n connectionAttemptStartTime = new Date().getTime();\n }\n\n function logConnectionResult(success) {\n if (connectionAttemptStartTime && diagnosticsAccumulator) {\n diagnosticsAccumulator.recordStreamInit(\n connectionAttemptStartTime,\n !success,\n new Date().getTime() - connectionAttemptStartTime\n );\n }\n connectionAttemptStartTime = null;\n }\n\n return stream;\n}\n\nmodule.exports = Stream;\n","// This function allows a series of Promises to be coalesced such that only the most recently\n// added one actually matters. For instance, if several HTTP requests are made to the same\n// endpoint and we want to ensure that whoever made each one always gets the latest data, each\n// can be passed to addPromise (on the same coalescer) and each caller can wait on the\n// coalescer.resultPromise; all three will then receive the result (or error) from the *last*\n// request, and the results of the first two will be discarded.\n//\n// The cancelFn callback, if present, will be called whenever an existing promise is being\n// discarded. This can be used for instance to abort an HTTP request that's now obsolete.\n//\n// The finallyFn callback, if present, is called on completion of the whole thing. This is\n// different from calling coalescer.resultPromise.finally() because it is executed before any\n// other handlers. Its purpose is to tell the caller that this coalescer should no longer be used.\n\nfunction promiseCoalescer(finallyFn) {\n let currentPromise;\n let currentCancelFn;\n let finalResolve;\n let finalReject;\n\n const coalescer = {};\n\n coalescer.addPromise = (p, cancelFn) => {\n currentPromise = p;\n currentCancelFn && currentCancelFn();\n currentCancelFn = cancelFn;\n\n p.then(\n result => {\n if (currentPromise === p) {\n finalResolve(result);\n finallyFn && finallyFn();\n }\n },\n error => {\n if (currentPromise === p) {\n finalReject(error);\n finallyFn && finallyFn();\n }\n }\n );\n };\n\n coalescer.resultPromise = new Promise((resolve, reject) => {\n finalResolve = resolve;\n finalReject = reject;\n });\n\n return coalescer;\n}\n\nmodule.exports = promiseCoalescer;\n","const utils = require('./utils');\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst promiseCoalescer = require('./promiseCoalescer');\nconst { transformHeaders, getLDHeaders } = require('./headers');\n\nconst jsonContentType = 'application/json';\n\nfunction getResponseError(result) {\n if (result.status === 404) {\n return new errors.LDInvalidEnvironmentIdError(messages.environmentNotFound());\n } else {\n return new errors.LDFlagFetchError(messages.errorFetchingFlags(result.statusText || String(result.status)));\n }\n}\n\nfunction Requestor(platform, options, environment) {\n const baseUrl = options.baseUrl;\n const useReport = options.useReport;\n const withReasons = options.evaluationReasons;\n const logger = options.logger;\n\n const requestor = {};\n\n const activeRequests = {}; // map of URLs to promiseCoalescers\n\n function fetchJSON(endpoint, body) {\n if (!platform.httpRequest) {\n return new Promise((resolve, reject) => {\n reject(new errors.LDFlagFetchError(messages.httpUnavailable()));\n });\n }\n\n const method = body ? 'REPORT' : 'GET';\n const headers = getLDHeaders(platform, options);\n if (body) {\n headers['Content-Type'] = jsonContentType;\n }\n\n let coalescer = activeRequests[endpoint];\n if (!coalescer) {\n coalescer = promiseCoalescer(() => {\n // this will be called once there are no more active requests for the same endpoint\n delete activeRequests[endpoint];\n });\n activeRequests[endpoint] = coalescer;\n }\n\n const req = platform.httpRequest(method, endpoint, transformHeaders(headers, options), body);\n const p = req.promise.then(\n result => {\n if (result.status === 200) {\n // We're using substring here because using startsWith would require a polyfill in IE.\n if (\n result.header('content-type') &&\n result.header('content-type').substring(0, jsonContentType.length) === jsonContentType\n ) {\n return JSON.parse(result.body);\n } else {\n const message = messages.invalidContentType(result.header('content-type') || '');\n return Promise.reject(new errors.LDFlagFetchError(message));\n }\n } else {\n return Promise.reject(getResponseError(result));\n }\n },\n e => Promise.reject(new errors.LDFlagFetchError(messages.networkError(e)))\n );\n coalescer.addPromise(p, () => {\n // this will be called if another request for the same endpoint supersedes this one\n req.cancel && req.cancel();\n });\n return coalescer.resultPromise;\n }\n\n // Performs a GET request to an arbitrary path under baseUrl. Returns a Promise which will resolve\n // with the parsed JSON response, or will be rejected if the request failed.\n requestor.fetchJSON = function(path) {\n return fetchJSON(utils.appendUrlPath(baseUrl, path), null);\n };\n\n // Requests the current state of all flags for the given context from LaunchDarkly. Returns a Promise\n // which will resolve with the parsed JSON response, or will be rejected if the request failed.\n requestor.fetchFlagSettings = function(context, hash) {\n let data;\n let endpoint;\n let query = '';\n let body;\n\n if (useReport) {\n endpoint = [baseUrl, '/sdk/evalx/', environment, '/context'].join('');\n body = JSON.stringify(context);\n } else {\n data = utils.base64URLEncode(JSON.stringify(context));\n endpoint = [baseUrl, '/sdk/evalx/', environment, '/contexts/', data].join('');\n }\n if (hash) {\n query = 'h=' + hash;\n }\n if (withReasons) {\n query = query + (query ? '&' : '') + 'withReasons=true';\n }\n endpoint = endpoint + (query ? '?' : '') + query;\n logger.debug(messages.debugPolling(endpoint));\n\n return fetchJSON(endpoint, body);\n };\n\n return requestor;\n}\n\nmodule.exports = Requestor;\n","const utils = require('./utils');\n\nfunction Identity(initialContext, onChange) {\n const ident = {};\n let context;\n\n ident.setContext = function(c) {\n context = utils.sanitizeContext(c);\n if (context && onChange) {\n onChange(utils.clone(context));\n }\n };\n\n ident.getContext = function() {\n return context ? utils.clone(context) : null;\n };\n\n if (initialContext) {\n ident.setContext(initialContext);\n }\n\n return ident;\n}\n\nmodule.exports = Identity;\n","const { v1: uuidv1 } = require('uuid');\nconst { getContextKinds } = require('./context');\n\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst utils = require('./utils');\n\nconst ldUserIdKey = 'ld:$anonUserId';\n\n/**\n * Create an object which can process a context and populate any required keys\n * for anonymous objects.\n *\n * @param {Object} persistentStorage The persistent storage from which to store\n * and access persisted anonymous context keys.\n * @returns An AnonymousContextProcessor.\n */\nfunction AnonymousContextProcessor(persistentStorage) {\n function getContextKeyIdString(kind) {\n if (kind === undefined || kind === null || kind === 'user') {\n return ldUserIdKey;\n }\n return `ld:$contextKey:${kind}`;\n }\n\n function getCachedContextKey(kind) {\n return persistentStorage.get(getContextKeyIdString(kind));\n }\n\n function setCachedContextKey(id, kind) {\n return persistentStorage.set(getContextKeyIdString(kind), id);\n }\n\n /**\n * Process a single kind context, or a single context within a multi-kind context.\n * @param {string} kind The kind of the context. Independent because the kind is not prevent\n * within a context in a multi-kind context.\n * @param {Object} context\n * @returns {Promise} a promise that resolves to a processed contexts, or rejects\n * a context which cannot be processed.\n */\n function processSingleKindContext(kind, context) {\n // We are working on a copy of an original context, so we want to re-assign\n // versus duplicating it again.\n\n /* eslint-disable no-param-reassign */\n if (context.key !== null && context.key !== undefined) {\n context.key = context.key.toString();\n return Promise.resolve(context);\n }\n\n if (context.anonymous) {\n // If the key doesn't exist, then the persistent storage will resolve\n // with undefined.\n return getCachedContextKey(kind).then(cachedId => {\n if (cachedId) {\n context.key = cachedId;\n return context;\n } else {\n const id = uuidv1();\n context.key = id;\n return setCachedContextKey(id, kind).then(() => context);\n }\n });\n } else {\n return Promise.reject(new errors.LDInvalidUserError(messages.invalidContext()));\n }\n /* eslint-enable no-param-reassign */\n }\n\n /**\n * Process the context, returning a Promise that resolves to the processed context, or rejects if there is an error.\n * @param {Object} context\n * @returns {Promise} A promise which resolves to a processed context, or a rejection if the context cannot be\n * processed. The context should still be checked for overall validity after being processed.\n */\n this.processContext = context => {\n if (!context) {\n return Promise.reject(new errors.LDInvalidUserError(messages.contextNotSpecified()));\n }\n\n const processedContext = utils.clone(context);\n\n if (context.kind === 'multi') {\n const kinds = getContextKinds(processedContext);\n\n return Promise.all(kinds.map(kind => processSingleKindContext(kind, processedContext[kind]))).then(\n () => processedContext\n );\n }\n return processSingleKindContext(context.kind, processedContext);\n };\n}\n\nmodule.exports = AnonymousContextProcessor;\n","const { v1: uuidv1 } = require('uuid');\n// Note that in the diagnostic events spec, these IDs are to be generated with UUID v4. However,\n// in JS we were already using v1 for unique context keys, so to avoid bringing in two packages we\n// will use v1 here as well.\n\nconst { baseOptionDefs } = require('./configuration');\nconst messages = require('./messages');\nconst { appendUrlPath } = require('./utils');\n\nfunction DiagnosticId(sdkKey) {\n const ret = {\n diagnosticId: uuidv1(),\n };\n if (sdkKey) {\n ret.sdkKeySuffix = sdkKey.length > 6 ? sdkKey.substring(sdkKey.length - 6) : sdkKey;\n }\n return ret;\n}\n\n// A stateful object holding statistics that will go into diagnostic events.\n\nfunction DiagnosticsAccumulator(startTime) {\n let dataSinceDate, droppedEvents, eventsInLastBatch, streamInits;\n\n function reset(time) {\n dataSinceDate = time;\n droppedEvents = 0;\n eventsInLastBatch = 0;\n streamInits = [];\n }\n\n reset(startTime);\n\n return {\n getProps: () => ({\n dataSinceDate,\n droppedEvents,\n eventsInLastBatch,\n streamInits,\n // omit deduplicatedUsers for the JS SDKs because they don't deduplicate users\n }),\n setProps: props => {\n dataSinceDate = props.dataSinceDate;\n droppedEvents = props.droppedEvents || 0;\n eventsInLastBatch = props.eventsInLastBatch || 0;\n streamInits = props.streamInits || [];\n },\n incrementDroppedEvents: () => {\n droppedEvents++;\n },\n setEventsInLastBatch: n => {\n eventsInLastBatch = n;\n },\n recordStreamInit: (timestamp, failed, durationMillis) => {\n const info = { timestamp, failed, durationMillis };\n streamInits.push(info);\n },\n reset,\n };\n}\n\n// An object that maintains information that will go into diagnostic events, and knows how to format\n// those events. It is instantiated by the SDK client, and shared with the event processor.\n//\n// The JS-based SDKs have two modes for diagnostic events. By default, the behavior is basically the\n// same as the server-side SDKs: a \"diagnostic-init\" event is sent on startup, and then \"diagnostic\"\n// events with operating statistics are sent periodically. However, in a browser environment this is\n// undesirable because the page may be reloaded frequently. In that case, setting the property\n// \"platform.diagnosticUseCombinedEvent\" to true enables an alternate mode in which a combination of\n// both kinds of event is sent at intervals, relative to the last time this was done (if any) which\n// is cached in local storage.\n\nfunction DiagnosticsManager(\n platform,\n persistentStorage,\n accumulator,\n eventSender,\n environmentId,\n config,\n diagnosticId\n) {\n const combinedMode = !!platform.diagnosticUseCombinedEvent;\n const localStorageKey = 'ld:' + environmentId + ':$diagnostics';\n const diagnosticEventsUrl = appendUrlPath(config.eventsUrl, '/events/diagnostic/' + environmentId);\n const periodicInterval = config.diagnosticRecordingInterval;\n const acc = accumulator;\n const initialEventSamplingInterval = 4; // used only in combined mode - see start()\n let streamingEnabled = !!config.streaming;\n let eventSentTime;\n let periodicTimer;\n const manager = {};\n\n function makeInitProperties() {\n return {\n sdk: makeSdkData(),\n configuration: makeConfigData(),\n platform: platform.diagnosticPlatformData,\n };\n }\n\n // Send a diagnostic event and do not wait for completion.\n function sendDiagnosticEvent(event) {\n config.logger && config.logger.debug(messages.debugPostingDiagnosticEvent(event));\n eventSender\n .sendEvents(event, diagnosticEventsUrl, true)\n .then(() => undefined)\n .catch(() => undefined);\n }\n\n function loadProperties(callback) {\n if (!persistentStorage.isEnabled()) {\n return callback(false); // false indicates that local storage is not available\n }\n persistentStorage\n .get(localStorageKey)\n .then(data => {\n if (data) {\n try {\n const props = JSON.parse(data);\n acc.setProps(props);\n eventSentTime = props.dataSinceDate;\n } catch (e) {\n // disregard malformed cached data\n }\n }\n callback(true);\n })\n .catch(() => {\n callback(false);\n });\n }\n\n function saveProperties() {\n if (persistentStorage.isEnabled()) {\n const props = { ...acc.getProps() };\n persistentStorage.set(localStorageKey, JSON.stringify(props));\n }\n }\n\n // Creates the initial event that is sent by the event processor when the SDK starts up. This will not\n // be repeated during the lifetime of the SDK client. In combined mode, we don't send this.\n function createInitEvent() {\n return {\n kind: 'diagnostic-init',\n id: diagnosticId,\n creationDate: acc.getProps().dataSinceDate,\n ...makeInitProperties(),\n };\n }\n\n // Creates a periodic event containing time-dependent stats, and resets the state of the manager with\n // regard to those stats. In combined mode (browser SDK) this also contains the configuration data.\n function createPeriodicEventAndReset() {\n const currentTime = new Date().getTime();\n let ret = {\n kind: combinedMode ? 'diagnostic-combined' : 'diagnostic',\n id: diagnosticId,\n creationDate: currentTime,\n ...acc.getProps(),\n };\n if (combinedMode) {\n ret = { ...ret, ...makeInitProperties() };\n }\n acc.reset(currentTime);\n return ret;\n }\n\n function sendPeriodicEvent() {\n sendDiagnosticEvent(createPeriodicEventAndReset());\n periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval);\n eventSentTime = new Date().getTime();\n if (combinedMode) {\n saveProperties();\n }\n }\n\n function makeSdkData() {\n const sdkData = { ...platform.diagnosticSdkData };\n if (config.wrapperName) {\n sdkData.wrapperName = config.wrapperName;\n }\n if (config.wrapperVersion) {\n sdkData.wrapperVersion = config.wrapperVersion;\n }\n return sdkData;\n }\n\n function makeConfigData() {\n const configData = {\n customBaseURI: config.baseUrl !== baseOptionDefs.baseUrl.default,\n customStreamURI: config.streamUrl !== baseOptionDefs.streamUrl.default,\n customEventsURI: config.eventsUrl !== baseOptionDefs.eventsUrl.default,\n eventsCapacity: config.eventCapacity,\n eventsFlushIntervalMillis: config.flushInterval,\n reconnectTimeMillis: config.streamReconnectDelay,\n streamingDisabled: !streamingEnabled,\n allAttributesPrivate: !!config.allAttributesPrivate,\n diagnosticRecordingIntervalMillis: config.diagnosticRecordingInterval,\n // The following extra properties are only provided by client-side JS SDKs:\n usingSecureMode: !!config.hash,\n bootstrapMode: !!config.bootstrap,\n fetchGoalsDisabled: !config.fetchGoals,\n sendEventsOnlyForVariation: !!config.sendEventsOnlyForVariation,\n };\n // Client-side JS SDKs do not have the following properties which other SDKs have:\n // connectTimeoutMillis\n // pollingIntervalMillis\n // samplingInterval\n // socketTimeoutMillis\n // startWaitMillis\n // userKeysCapacity\n // userKeysFlushIntervalMillis\n // usingProxy\n // usingProxyAuthenticator\n // usingRelayDaemon\n\n return configData;\n }\n\n // Called when the SDK is starting up. Either send an init event immediately, or, in the alternate\n // mode, check for cached local storage properties and send an event only if we haven't done so\n // recently.\n manager.start = () => {\n if (combinedMode) {\n loadProperties(localStorageAvailable => {\n if (localStorageAvailable) {\n const nextEventTime = (eventSentTime || 0) + periodicInterval;\n const timeNow = new Date().getTime();\n if (timeNow >= nextEventTime) {\n sendPeriodicEvent();\n } else {\n periodicTimer = setTimeout(sendPeriodicEvent, nextEventTime - timeNow);\n }\n } else {\n // We don't have the ability to cache anything in local storage, so we don't know if we\n // recently sent an event before this page load, but we would still prefer not to send one\n // on *every* page load. So, as a rough heuristic, we'll decide semi-randomly.\n if (Math.floor(Math.random() * initialEventSamplingInterval) === 0) {\n sendPeriodicEvent();\n } else {\n periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval);\n }\n }\n });\n } else {\n sendDiagnosticEvent(createInitEvent());\n periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval);\n }\n };\n\n manager.stop = () => {\n periodicTimer && clearTimeout(periodicTimer);\n };\n\n // Called when streaming mode is turned on or off dynamically.\n manager.setStreaming = enabled => {\n streamingEnabled = enabled;\n };\n\n return manager;\n}\n\nmodule.exports = {\n DiagnosticId,\n DiagnosticsAccumulator,\n DiagnosticsManager,\n};\n","const messages = require('./messages');\n\n/**\n * Wrap an inspector ensuring that calling its methods are safe.\n * @param {object} inspector Inspector to wrap.\n */\nfunction SafeInspector(inspector, logger) {\n let errorLogged = false;\n const wrapper = {\n type: inspector.type,\n name: inspector.name,\n synchronous: inspector.synchronous,\n };\n\n wrapper.method = (...args) => {\n try {\n inspector.method(...args);\n } catch {\n // If something goes wrong in an inspector we want to log that something\n // went wrong. We don't want to flood the logs, so we only log something\n // the first time that something goes wrong.\n // We do not include the exception in the log, because we do not know what\n // kind of data it may contain.\n if (!errorLogged) {\n errorLogged = true;\n logger.warn(messages.inspectorMethodError(wrapper.type, wrapper.name));\n }\n // Prevent errors.\n }\n };\n\n return wrapper;\n}\n\nmodule.exports = SafeInspector;\n","const messages = require('./messages');\nconst SafeInspector = require('./SafeInspector');\nconst { onNextTick } = require('./utils');\n\n/**\n * The types of supported inspectors.\n */\nconst InspectorTypes = {\n flagUsed: 'flag-used',\n flagDetailsChanged: 'flag-details-changed',\n flagDetailChanged: 'flag-detail-changed',\n clientIdentityChanged: 'client-identity-changed',\n};\n\nObject.freeze(InspectorTypes);\n\n/**\n * Manages dispatching of inspection data to registered inspectors.\n */\nfunction InspectorManager(inspectors, logger) {\n const manager = {};\n\n /**\n * Collection of inspectors keyed by type.\n *\n * Inspectors are async by default.\n *\n * @type {{[type: string]: object[]}}\n */\n const inspectorsByType = {\n [InspectorTypes.flagUsed]: [],\n [InspectorTypes.flagDetailsChanged]: [],\n [InspectorTypes.flagDetailChanged]: [],\n [InspectorTypes.clientIdentityChanged]: [],\n };\n /**\n * Collection synchronous of inspectors keyed by type.\n *\n * @type {{[type: string]: object[]}}\n */\n const synchronousInspectorsByType = {\n [InspectorTypes.flagUsed]: [],\n [InspectorTypes.flagDetailsChanged]: [],\n [InspectorTypes.flagDetailChanged]: [],\n [InspectorTypes.clientIdentityChanged]: [],\n };\n\n const safeInspectors = inspectors && inspectors.map(inspector => SafeInspector(inspector, logger));\n\n safeInspectors &&\n safeInspectors.forEach(safeInspector => {\n // Only add inspectors of supported types.\n if (Object.prototype.hasOwnProperty.call(inspectorsByType, safeInspector.type) && !safeInspector.synchronous) {\n inspectorsByType[safeInspector.type].push(safeInspector);\n } else if (\n Object.prototype.hasOwnProperty.call(synchronousInspectorsByType, safeInspector.type) &&\n safeInspector.synchronous\n ) {\n synchronousInspectorsByType[safeInspector.type].push(safeInspector);\n } else {\n logger.warn(messages.invalidInspector(safeInspector.type, safeInspector.name));\n }\n });\n\n /**\n * Check if there is an inspector of a specific type registered.\n *\n * @param {string} type The type of the inspector to check.\n * @returns True if there are any inspectors of that type registered.\n */\n manager.hasListeners = type =>\n (inspectorsByType[type] && inspectorsByType[type].length) ||\n (synchronousInspectorsByType[type] && synchronousInspectorsByType[type].length);\n\n /**\n * Notify registered inspectors of a flag being used.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {string} flagKey The key for the flag.\n * @param {Object} detail The LDEvaluationDetail for the flag.\n * @param {Object} context The LDContext for the flag.\n */\n manager.onFlagUsed = (flagKey, detail, context) => {\n const type = InspectorTypes.flagUsed;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(flagKey, detail, context));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(flagKey, detail, context));\n });\n }\n };\n\n /**\n * Notify registered inspectors that the flags have been replaced.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {Record} flags The current flags as a Record.\n */\n manager.onFlags = flags => {\n const type = InspectorTypes.flagDetailsChanged;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(flags));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(flags));\n });\n }\n };\n\n /**\n * Notify registered inspectors that a flag value has changed.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {string} flagKey The key for the flag that changed.\n * @param {Object} flag An `LDEvaluationDetail` for the flag.\n */\n manager.onFlagChanged = (flagKey, flag) => {\n const type = InspectorTypes.flagDetailChanged;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(flagKey, flag));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(flagKey, flag));\n });\n }\n };\n\n /**\n * Notify the registered inspectors that the context identity has changed.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {Object} context The `LDContext` which is now identified.\n */\n manager.onIdentityChanged = context => {\n const type = InspectorTypes.clientIdentityChanged;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(context));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(context));\n });\n }\n };\n\n return manager;\n}\n\nmodule.exports = { InspectorTypes, InspectorManager };\n","const { LDTimeoutError } = require('./errors');\n\n/**\n * Returns a promise which errors after t seconds.\n *\n * @param t Timeout in seconds.\n * @param taskName Name of task being timed for logging and error reporting.\n */\nfunction timedPromise(t, taskName) {\n return new Promise((_res, reject) => {\n setTimeout(() => {\n const e = `${taskName} timed out after ${t} seconds.`;\n reject(new LDTimeoutError(e));\n }, t * 1000);\n });\n}\nmodule.exports = timedPromise;\n","const UNKNOWN_HOOK_NAME = 'unknown hook';\nconst BEFORE_EVALUATION_STAGE_NAME = 'beforeEvaluation';\nconst AFTER_EVALUATION_STAGE_NAME = 'afterEvaluation';\nconst BEFORE_IDENTIFY_STAGE_NAME = 'beforeIdentify';\nconst AFTER_IDENTIFY_STAGE_NAME = 'afterIdentify';\nconst AFTER_TRACK_STAGE_NAME = 'afterTrack';\n\n/**\n * Safely executes a hook stage function, logging any errors.\n * @param {{ error: (message: string) => void } | undefined} logger The logger instance.\n * @param {string} method The name of the hook stage being executed (e.g., 'beforeEvaluation').\n * @param {string} hookName The name of the hook.\n * @param {() => any} stage The function representing the hook stage to execute.\n * @param {any} def The default value to return if the stage function throws an error.\n * @returns {any} The result of the stage function, or the default value if an error occurred.\n */\nfunction tryExecuteStage(logger, method, hookName, stage, def) {\n try {\n return stage();\n } catch (err) {\n logger?.error(`An error was encountered in \"${method}\" of the \"${hookName}\" hook: ${err}`);\n return def;\n }\n}\n\n/**\n * Safely gets the name of a hook from its metadata.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {{ getMetadata: () => { name?: string } }} hook The hook instance.\n * @returns {string} The name of the hook, or 'unknown hook' if unable to retrieve it.\n */\nfunction getHookName(logger, hook) {\n try {\n return hook.getMetadata().name || UNKNOWN_HOOK_NAME;\n } catch {\n logger.error(`Exception thrown getting metadata for hook. Unable to get hook name.`);\n return UNKNOWN_HOOK_NAME;\n }\n}\n\n/**\n * Executes the 'beforeEvaluation' stage for all registered hooks.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ beforeEvaluation?: (hookContext: object, data: object) => object }>} hooks The array of hook instances.\n * @param {{ flagKey: string, context: object, defaultValue: any }} hookContext The context for the evaluation series.\n * @returns {Array} An array containing the data returned by each hook's 'beforeEvaluation' stage.\n */\nfunction executeBeforeEvaluation(logger, hooks, hookContext) {\n return hooks.map(hook =>\n tryExecuteStage(\n logger,\n BEFORE_EVALUATION_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.beforeEvaluation?.(hookContext, {}) ?? {},\n {}\n )\n );\n}\n\n/**\n * Executes the 'afterEvaluation' stage for all registered hooks in reverse order.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ afterEvaluation?: (hookContext: object, data: object, result: object) => object }>} hooks The array of hook instances.\n * @param {{ flagKey: string, context: object, defaultValue: any }} hookContext The context for the evaluation series.\n * @param {Array} updatedData The data collected from the 'beforeEvaluation' stages.\n * @param {{ value: any, variationIndex?: number, reason?: object }} result The result of the flag evaluation.\n * @returns {void}\n */\nfunction executeAfterEvaluation(logger, hooks, hookContext, updatedData, result) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = updatedData[hookIndex];\n tryExecuteStage(\n logger,\n AFTER_EVALUATION_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.afterEvaluation?.(hookContext, data, result) ?? {},\n {}\n );\n }\n}\n\n/**\n * Executes the 'beforeIdentify' stage for all registered hooks.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ beforeIdentify?: (hookContext: object, data: object) => object }>} hooks The array of hook instances.\n * @param {{ context: object, timeout?: number }} hookContext The context for the identify series.\n * @returns {Array} An array containing the data returned by each hook's 'beforeIdentify' stage.\n */\nfunction executeBeforeIdentify(logger, hooks, hookContext) {\n return hooks.map(hook =>\n tryExecuteStage(\n logger,\n BEFORE_IDENTIFY_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.beforeIdentify?.(hookContext, {}) ?? {},\n {}\n )\n );\n}\n\n/**\n * Executes the 'afterIdentify' stage for all registered hooks in reverse order.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ afterIdentify?: (hookContext: object, data: object, result: object) => object }>} hooks The array of hook instances.\n * @param {{ context: object, timeout?: number }} hookContext The context for the identify series.\n * @param {Array} updatedData The data collected from the 'beforeIdentify' stages.\n * @param {{ status: string }} result The result of the identify operation.\n * @returns {void}\n */\nfunction executeAfterIdentify(logger, hooks, hookContext, updatedData, result) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = updatedData[hookIndex];\n tryExecuteStage(\n logger,\n AFTER_IDENTIFY_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.afterIdentify?.(hookContext, data, result) ?? {},\n {}\n );\n }\n}\n\n/**\n * Executes the 'afterTrack' stage for all registered hooks in reverse order.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ afterTrack?: (hookContext: { context: object, data: object, metricValue: number }) => void }>} hooks The array of hook instances.\n * @param {{ context: object, data: object, metricValue: number }} hookContext The context for the track operation.\n * @returns {void}\n */\nfunction executeAfterTrack(logger, hooks, hookContext) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n tryExecuteStage(\n logger,\n AFTER_TRACK_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.afterTrack?.(hookContext),\n undefined\n );\n }\n}\n\n/**\n * Factory function to create a HookRunner instance.\n * Manages the execution of hooks for flag evaluations and identify operations.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array | undefined} initialHooks An optional array of hooks to initialize with.\n * @returns {{\n * withEvaluation: (key: string, context: object, defaultValue: any, method: () => { value: any, variationIndex?: number, reason?: object }) => { value: any, variationIndex?: number, reason?: object },\n * identify: (context: object, timeout?: number) => (result: { status: string }) => void,\n * addHook: (hook: object) => void\n * }} The hook runner object with methods to manage and execute hooks.\n */\nfunction createHookRunner(logger, initialHooks) {\n // Use local variable instead of instance property\n const hooksInternal = initialHooks ? [...initialHooks] : [];\n\n /**\n * Wraps a flag evaluation method with before/after hook stages.\n * @param {string} key The flag key.\n * @param {object} context The evaluation context.\n * @param {any} defaultValue The default value for the flag.\n * @param {() => { value: any, variationIndex?: number, reason?: object }} method The function that performs the actual flag evaluation.\n * @returns {{ value: any, variationIndex?: number, reason?: object }} The result of the flag evaluation.\n */\n function withEvaluation(key, context, defaultValue, method) {\n if (hooksInternal.length === 0) {\n return method();\n }\n const hooks = [...hooksInternal];\n /** @type {{ flagKey: string, context: object, defaultValue: any }} */\n const hookContext = {\n flagKey: key,\n context,\n defaultValue,\n };\n\n // Use the logger passed into the factory\n const hookData = executeBeforeEvaluation(logger, hooks, hookContext);\n const result = method();\n executeAfterEvaluation(logger, hooks, hookContext, hookData, result);\n return result;\n }\n\n /**\n * Wraps the identify operation with before/after hook stages.\n * Executes the 'beforeIdentify' stage immediately and returns a function\n * to execute the 'afterIdentify' stage later.\n * @param {object} context The context being identified.\n * @param {number | undefined} timeout Optional timeout for the identify operation.\n * @returns {(result: { status: string }) => void} A function to call after the identify operation completes.\n */\n function identify(context, timeout) {\n const hooks = [...hooksInternal];\n /** @type {{ context: object, timeout?: number }} */\n const hookContext = {\n context,\n timeout,\n };\n // Use the logger passed into the factory\n const hookData = executeBeforeIdentify(logger, hooks, hookContext);\n /**\n * Executes the 'afterIdentify' hook stage.\n * @param {{ status: string }} result The result of the identify operation.\n */\n return result => {\n executeAfterIdentify(logger, hooks, hookContext, hookData, result);\n };\n }\n\n /**\n * Adds a new hook to the runner.\n * @param {object} hook The hook instance to add.\n * @returns {void}\n */\n function addHook(hook) {\n // Mutate the internal hooks array\n hooksInternal.push(hook);\n }\n\n /**\n * Executes the 'afterTrack' stage for all registered hooks in reverse order.\n * @param {{ context: object, data: object, metricValue: number }} hookContext The context for the track operation.\n * @returns {void}\n */\n function afterTrack(hookContext) {\n if (hooksInternal.length === 0) {\n return;\n }\n const hooks = [...hooksInternal];\n executeAfterTrack(logger, hooks, hookContext);\n }\n\n return {\n withEvaluation,\n identify,\n addHook,\n afterTrack,\n };\n}\n\nmodule.exports = createHookRunner;\n","const UNKNOWN_PLUGIN_NAME = 'unknown plugin';\n\n/**\n * Safely gets the name of a plugin with error handling\n * @param {{ error: (message: string) => void }} logger - The logger instance\n * @param {{getMetadata: () => {name: string}}} plugin - Plugin object that may have a name property\n * @returns {string} The plugin name or 'unknown' if not available\n */\nfunction getPluginName(logger, plugin) {\n try {\n return plugin.getMetadata().name || UNKNOWN_PLUGIN_NAME;\n } catch (error) {\n logger.error(`Exception thrown getting metadata for plugin. Unable to get plugin name.`);\n return UNKNOWN_PLUGIN_NAME;\n }\n}\n\n/**\n * Safely retrieves hooks from plugins with error handling\n * @param {Object} logger - The logger instance\n * @param {Object} environmentMetadata - Metadata about the environment for plugin initialization\n * @param {Array<{getHooks: (environmentMetadata: object) => Hook[]}>} plugins - Array of plugin objects that may implement getHooks\n * @returns {Array} Array of hook objects collected from all plugins\n */\nfunction getPluginHooks(logger, environmentMetadata, plugins) {\n const hooks = [];\n plugins.forEach(plugin => {\n try {\n const pluginHooks = plugin.getHooks?.(environmentMetadata);\n if (pluginHooks === undefined) {\n logger.error(`Plugin ${getPluginName(logger, plugin)} returned undefined from getHooks.`);\n } else if (pluginHooks && pluginHooks.length > 0) {\n hooks.push(...pluginHooks);\n }\n } catch (error) {\n logger.error(`Exception thrown getting hooks for plugin ${getPluginName(logger, plugin)}. Unable to get hooks.`);\n }\n });\n return hooks;\n}\n\n/**\n * Registers plugins with the SDK\n * @param {{ error: (message: string) => void }} logger - The logger instance\n * @param {Object} environmentMetadata - Metadata about the environment for plugin initialization\n * @param {Object} client - The SDK client instance\n * @param {Array<{register: (client: object, environmentMetadata: object) => void}>} plugins - Array of plugin objects that implement register\n */\nfunction registerPlugins(logger, environmentMetadata, client, plugins) {\n plugins.forEach(plugin => {\n try {\n plugin.register(client, environmentMetadata);\n } catch (error) {\n logger.error(`Exception thrown registering plugin ${getPluginName(logger, plugin)}.`);\n }\n });\n}\n\n/**\n * Creates a plugin environment object\n * @param {{userAgent: string, version: string}} platform - The platform object\n * @param {string} env - The environment\n * @param {{application: {name: string, version: string}, wrapperName: string, wrapperVersion: string}} options - The options\n * @returns {{sdk: {name: string, version: string, wrapperName: string, wrapperVersion: string}, application: {name: string, version: string}, clientSideId: string}} The plugin environment\n */\nfunction createPluginEnvironment(platform, env, options) {\n const pluginSdkMetadata = {};\n\n if (platform.userAgent) {\n pluginSdkMetadata.name = platform.userAgent;\n }\n if (platform.version) {\n pluginSdkMetadata.version = platform.version;\n }\n if (options.wrapperName) {\n pluginSdkMetadata.wrapperName = options.wrapperName;\n }\n if (options.wrapperVersion) {\n pluginSdkMetadata.wrapperVersion = options.wrapperVersion;\n }\n\n const pluginApplicationMetadata = {};\n\n if (options.application) {\n if (options.application.name) {\n pluginApplicationMetadata.name = options.application.name;\n }\n if (options.application.version) {\n pluginApplicationMetadata.version = options.application.version;\n }\n }\n\n const pluginEnvironment = {\n sdk: pluginSdkMetadata,\n clientSideId: env,\n };\n\n if (Object.keys(pluginApplicationMetadata).length > 0) {\n pluginEnvironment.application = pluginApplicationMetadata;\n }\n\n return pluginEnvironment;\n}\n\nmodule.exports = {\n getPluginHooks,\n registerPlugins,\n createPluginEnvironment,\n};\n","const EventProcessor = require('./EventProcessor');\nconst EventEmitter = require('./EventEmitter');\nconst EventSender = require('./EventSender');\nconst InitializationStateTracker = require('./InitializationState');\nconst PersistentFlagStore = require('./PersistentFlagStore');\nconst PersistentStorage = require('./PersistentStorage');\nconst Stream = require('./Stream');\nconst Requestor = require('./Requestor');\nconst Identity = require('./Identity');\nconst AnonymousContextProcessor = require('./AnonymousContextProcessor');\nconst configuration = require('./configuration');\nconst diagnostics = require('./diagnosticEvents');\nconst { commonBasicLogger } = require('./loggers');\nconst utils = require('./utils');\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst { checkContext, getContextKeys } = require('./context');\nconst { InspectorTypes, InspectorManager } = require('./InspectorManager');\nconst timedPromise = require('./timedPromise');\nconst createHookRunner = require('./HookRunner');\nconst { getPluginHooks, registerPlugins, createPluginEnvironment } = require('./plugins');\nconst changeEvent = 'change';\nconst internalChangeEvent = 'internal-change';\nconst highTimeoutThreshold = 5;\n\n// This is called by the per-platform initialize functions to create the base client object that we\n// may also extend with additional behavior. It returns an object with these properties:\n// client: the actual client object\n// options: the configuration (after any appropriate defaults have been applied)\n// If we need to give the platform-specific clients access to any internals here, we should add those\n// as properties of the return object, not public properties of the client.\n//\n// For definitions of the API in the platform object, see stubPlatform.js in the test code.\n\nfunction initialize(env, context, specifiedOptions, platform, extraOptionDefs) {\n const logger = createLogger();\n const emitter = EventEmitter(logger);\n const initializationStateTracker = InitializationStateTracker(emitter);\n const options = configuration.validate(specifiedOptions, emitter, extraOptionDefs, logger);\n const inspectorManager = InspectorManager(options.inspectors, logger);\n const sendEvents = options.sendEvents;\n let environment = env;\n let hash = options.hash;\n const plugins = [...options.plugins];\n\n const pluginEnvironment = createPluginEnvironment(platform, env, options);\n\n const pluginHooks = getPluginHooks(logger, pluginEnvironment, plugins);\n\n const hookRunner = createHookRunner(logger, [...options.hooks, ...pluginHooks]);\n\n const persistentStorage = PersistentStorage(platform.localStorage, logger);\n\n const eventSender = EventSender(platform, environment, options);\n\n const diagnosticsEnabled = options.sendEvents && !options.diagnosticOptOut;\n const diagnosticId = diagnosticsEnabled ? diagnostics.DiagnosticId(environment) : null;\n const diagnosticsAccumulator = diagnosticsEnabled ? diagnostics.DiagnosticsAccumulator(new Date().getTime()) : null;\n const diagnosticsManager = diagnosticsEnabled\n ? diagnostics.DiagnosticsManager(\n platform,\n persistentStorage,\n diagnosticsAccumulator,\n eventSender,\n environment,\n options,\n diagnosticId\n )\n : null;\n\n const stream = Stream(platform, options, environment, diagnosticsAccumulator);\n\n const events =\n options.eventProcessor ||\n EventProcessor(platform, options, environment, diagnosticsAccumulator, emitter, eventSender);\n\n const requestor = Requestor(platform, options, environment);\n\n let flags = {};\n let useLocalStorage;\n let streamActive;\n let streamForcedState = options.streaming;\n let subscribedToChangeEvents;\n let inited = false;\n let closed = false;\n let firstEvent = true;\n\n // The \"stateProvider\" object is used in the Electron SDK, to allow one client instance to take partial\n // control of another. If present, it has the following contract:\n // - getInitialState() returns the initial client state if it is already available. The state is an\n // object whose properties are \"environment\", \"context\", and \"flags\".\n // - on(\"init\", listener) triggers an event when the initial client state becomes available, passing\n // the state object to the listener.\n // - on(\"update\", listener) triggers an event when flag values change and/or the current context changes.\n // The parameter is an object that *may* contain \"context\" and/or \"flags\".\n // - enqueueEvent(event) accepts an analytics event object and returns true if the stateProvider will\n // be responsible for delivering it, or false if we still should deliver it ourselves.\n const stateProvider = options.stateProvider;\n\n const ident = Identity(null, onIdentifyChange);\n const anonymousContextProcessor = new AnonymousContextProcessor(persistentStorage);\n const persistentFlagStore = persistentStorage.isEnabled()\n ? PersistentFlagStore(persistentStorage, environment, hash, ident, logger)\n : null;\n\n function createLogger() {\n if (specifiedOptions && specifiedOptions.logger) {\n return specifiedOptions.logger;\n }\n return (extraOptionDefs && extraOptionDefs.logger && extraOptionDefs.logger.default) || commonBasicLogger('warn');\n }\n\n function readFlagsFromBootstrap(data) {\n // If the bootstrap data came from an older server-side SDK, we'll have just a map of keys to values.\n // Newer SDKs that have an allFlagsState method will provide an extra \"$flagsState\" key that contains\n // the rest of the metadata we want. We do it this way for backward compatibility with older JS SDKs.\n const keys = Object.keys(data);\n const metadataKey = '$flagsState';\n const validKey = '$valid';\n const metadata = data[metadataKey];\n if (!metadata && keys.length) {\n logger.warn(messages.bootstrapOldFormat());\n }\n if (data[validKey] === false) {\n logger.warn(messages.bootstrapInvalid());\n }\n const ret = {};\n keys.forEach(key => {\n if (key !== metadataKey && key !== validKey) {\n let flag = { value: data[key] };\n if (metadata && metadata[key]) {\n flag = utils.extend(flag, metadata[key]);\n } else {\n flag.version = 0;\n }\n ret[key] = flag;\n }\n });\n return ret;\n }\n\n function shouldEnqueueEvent() {\n return sendEvents && !closed && !platform.isDoNotTrack();\n }\n\n function enqueueEvent(event) {\n if (!environment) {\n // We're in paired mode and haven't been initialized with an environment or context yet\n return;\n }\n if (stateProvider && stateProvider.enqueueEvent && stateProvider.enqueueEvent(event)) {\n return; // it'll be handled elsewhere\n }\n\n if (!event.context) {\n if (firstEvent) {\n logger.warn(messages.eventWithoutContext());\n firstEvent = false;\n }\n return;\n }\n firstEvent = false;\n\n if (shouldEnqueueEvent()) {\n logger.debug(messages.debugEnqueueingEvent(event.kind));\n events.enqueue(event);\n }\n }\n\n function notifyInspectionFlagUsed(key, detail) {\n if (inspectorManager.hasListeners(InspectorTypes.flagUsed)) {\n inspectorManager.onFlagUsed(key, detail, ident.getContext());\n }\n }\n\n function notifyInspectionIdentityChanged() {\n if (inspectorManager.hasListeners(InspectorTypes.clientIdentityChanged)) {\n inspectorManager.onIdentityChanged(ident.getContext());\n }\n }\n\n function notifyInspectionFlagChanged(data, newFlag) {\n if (inspectorManager.hasListeners(InspectorTypes.flagDetailChanged)) {\n inspectorManager.onFlagChanged(data.key, getFlagDetail(newFlag));\n }\n }\n\n function notifyInspectionFlagsChanged() {\n if (inspectorManager.hasListeners(InspectorTypes.flagDetailsChanged)) {\n inspectorManager.onFlags(\n Object.entries(flags)\n .map(([key, value]) => ({ key, detail: getFlagDetail(value) }))\n .reduce((acc, cur) => {\n // eslint-disable-next-line no-param-reassign\n acc[cur.key] = cur.detail;\n return acc;\n }, {})\n );\n }\n }\n\n function onIdentifyChange(context) {\n sendIdentifyEvent(context);\n notifyInspectionIdentityChanged();\n }\n\n function sendIdentifyEvent(context) {\n if (stateProvider) {\n // In paired mode, the other client is responsible for sending identify events\n return;\n }\n if (context) {\n enqueueEvent({\n kind: 'identify',\n context,\n creationDate: new Date().getTime(),\n });\n }\n }\n\n function sendFlagEvent(key, detail, defaultValue, includeReason) {\n const context = ident.getContext();\n const now = new Date();\n const value = detail ? detail.value : null;\n\n const event = {\n kind: 'feature',\n key: key,\n context,\n value: value,\n variation: detail ? detail.variationIndex : null,\n default: defaultValue,\n creationDate: now.getTime(),\n };\n const flag = flags[key];\n if (flag) {\n event.version = flag.flagVersion ? flag.flagVersion : flag.version;\n event.trackEvents = flag.trackEvents;\n event.debugEventsUntilDate = flag.debugEventsUntilDate;\n }\n if ((includeReason || (flag && flag.trackReason)) && detail) {\n event.reason = detail.reason;\n }\n\n enqueueEvent(event);\n }\n\n function verifyContext(context) {\n // The context will already have been processed to have a string key, so we\n // do not need to allow for legacy keys in the check.\n if (checkContext(context, false)) {\n return Promise.resolve(context);\n } else {\n return Promise.reject(new errors.LDInvalidUserError(messages.invalidContext()));\n }\n }\n\n function identify(context, newHash, onDone) {\n if (closed) {\n return utils.wrapPromiseCallback(Promise.resolve({}), onDone);\n }\n if (stateProvider) {\n // We're being controlled by another client instance, so only that instance is allowed to change the context\n logger.warn(messages.identifyDisabled());\n return utils.wrapPromiseCallback(Promise.resolve(utils.transformVersionedValuesToValues(flags)), onDone);\n }\n let afterIdentify;\n const clearFirst = useLocalStorage && persistentFlagStore ? persistentFlagStore.clearFlags() : Promise.resolve();\n return utils.wrapPromiseCallback(\n clearFirst\n .then(() => anonymousContextProcessor.processContext(context))\n .then(verifyContext)\n .then(context => {\n afterIdentify = utils.once(hookRunner.identify(context, undefined));\n return context;\n })\n .then(validatedContext =>\n requestor\n .fetchFlagSettings(validatedContext, newHash)\n // the following then() is nested within this one so we can use realUser from the previous closure\n .then(requestedFlags => {\n const flagValueMap = utils.transformVersionedValuesToValues(requestedFlags);\n ident.setContext(validatedContext);\n hash = newHash;\n if (requestedFlags) {\n return replaceAllFlags(requestedFlags).then(() => flagValueMap);\n } else {\n return flagValueMap;\n }\n })\n )\n .then(flagValueMap => {\n afterIdentify?.({ status: 'completed' });\n if (streamActive) {\n connectStream();\n }\n return flagValueMap;\n })\n .catch(err => {\n afterIdentify?.({ status: 'error' });\n emitter.maybeReportError(err);\n return Promise.reject(err);\n }),\n onDone\n );\n }\n\n function getContext() {\n return ident.getContext();\n }\n\n function flush(onDone) {\n return utils.wrapPromiseCallback(sendEvents ? events.flush() : Promise.resolve(), onDone);\n }\n\n function variation(key, defaultValue) {\n const { value } = hookRunner.withEvaluation(key, ident.getContext(), defaultValue, () =>\n variationDetailInternal(key, defaultValue, true, false, false, true)\n );\n return value;\n }\n\n function variationDetail(key, defaultValue) {\n return hookRunner.withEvaluation(key, ident.getContext(), defaultValue, () =>\n variationDetailInternal(key, defaultValue, true, true, false, true)\n );\n }\n\n function variationDetailInternal(key, defaultValue, sendEvent, includeReasonInEvent, isAllFlags, notifyInspection) {\n let detail;\n let flag;\n\n if (flags && utils.objectHasOwnProperty(flags, key) && flags[key] && !flags[key].deleted) {\n flag = flags[key];\n detail = getFlagDetail(flag);\n if (flag.value === null || flag.value === undefined) {\n detail.value = defaultValue;\n }\n } else {\n detail = { value: defaultValue, variationIndex: null, reason: { kind: 'ERROR', errorKind: 'FLAG_NOT_FOUND' } };\n }\n\n if (sendEvent) {\n // For an all-flags evaluation, with events enabled, each flag will get an event, so we do not\n // need to duplicate the prerequisites.\n if (!isAllFlags) {\n flag?.prerequisites?.forEach(key => {\n variationDetailInternal(key, undefined, sendEvent, false, false, false);\n });\n }\n sendFlagEvent(key, detail, defaultValue, includeReasonInEvent);\n }\n\n // For the all flags case `onFlags` will be called instead.\n if (!isAllFlags && notifyInspection) {\n notifyInspectionFlagUsed(key, detail);\n }\n\n return detail;\n }\n\n function getFlagDetail(flag) {\n return {\n value: flag.value,\n variationIndex: flag.variation === undefined ? null : flag.variation,\n reason: flag.reason || null,\n };\n // Note, the logic above ensures that variationIndex and reason will always be null rather than\n // undefined if we don't have values for them. That's just to avoid subtle errors that depend on\n // whether an object was JSON-encoded with null properties omitted or not.\n }\n\n function allFlags() {\n const results = {};\n\n if (!flags) {\n return results;\n }\n\n for (const key in flags) {\n if (utils.objectHasOwnProperty(flags, key) && !flags[key].deleted) {\n results[key] = variationDetailInternal(\n key,\n null,\n !options.sendEventsOnlyForVariation,\n false,\n true,\n false\n ).value;\n }\n }\n\n return results;\n }\n\n function userContextKind(user) {\n return user.anonymous ? 'anonymousUser' : 'user';\n }\n\n function track(key, data, metricValue) {\n if (typeof key !== 'string') {\n emitter.maybeReportError(new errors.LDInvalidEventKeyError(messages.unknownCustomEventKey(key)));\n return;\n }\n if (metricValue !== undefined && typeof metricValue !== 'number') {\n logger.warn(messages.invalidMetricValue(typeof metricValue));\n }\n\n // The following logic was used only for the JS browser SDK (js-client-sdk) and\n // is no longer needed as of version 2.9.13 of that SDK. The other client-side\n // JS-based SDKs did not define customEventFilter, and now none of them do. We\n // can remove this in the next major version of the common code, when it's OK to\n // make breaking changes to our internal API contracts.\n if (platform.customEventFilter && !platform.customEventFilter(key)) {\n logger.warn(messages.unknownCustomEventKey(key));\n }\n\n const context = ident.getContext();\n const e = {\n kind: 'custom',\n key: key,\n context,\n url: platform.getCurrentUrl(),\n creationDate: new Date().getTime(),\n };\n if (context && context.anonymous) {\n e.contextKind = userContextKind(context);\n }\n // Note, check specifically for null/undefined because it is legal to set these fields to a falsey value.\n if (data !== null && data !== undefined) {\n e.data = data;\n }\n if (metricValue !== null && metricValue !== undefined) {\n e.metricValue = metricValue;\n }\n enqueueEvent(e);\n hookRunner.afterTrack({ context, key, data, metricValue });\n }\n\n function connectStream() {\n streamActive = true;\n if (!ident.getContext()) {\n return;\n }\n const tryParseData = jsonData => {\n try {\n return JSON.parse(jsonData);\n } catch (err) {\n emitter.maybeReportError(new errors.LDInvalidDataError(messages.invalidData()));\n return undefined;\n }\n };\n stream.connect(ident.getContext(), hash, {\n ping: function() {\n logger.debug(messages.debugStreamPing());\n const contextAtTimeOfPingEvent = ident.getContext();\n requestor\n .fetchFlagSettings(contextAtTimeOfPingEvent, hash)\n .then(requestedFlags => {\n // Check whether the current context is still the same - we don't want to overwrite the flags if\n // the application has called identify() while this request was in progress\n if (utils.deepEquals(contextAtTimeOfPingEvent, ident.getContext())) {\n replaceAllFlags(requestedFlags || {});\n }\n })\n .catch(err => {\n emitter.maybeReportError(new errors.LDFlagFetchError(messages.errorFetchingFlags(err)));\n });\n },\n put: function(e) {\n const data = tryParseData(e.data);\n if (!data) {\n return;\n }\n logger.debug(messages.debugStreamPut());\n replaceAllFlags(data);\n // Don't wait for this Promise to be resolved; note that replaceAllFlags is guaranteed\n // never to have an unhandled rejection\n },\n patch: function(e) {\n const data = tryParseData(e.data);\n if (!data) {\n return;\n }\n // If both the flag and the patch have a version property, then the patch version must be\n // greater than the flag version for us to accept the patch. If either one has no version\n // then the patch always succeeds.\n const oldFlag = flags[data.key];\n if (!oldFlag || !oldFlag.version || !data.version || oldFlag.version < data.version) {\n logger.debug(messages.debugStreamPatch(data.key));\n const mods = {};\n const newFlag = utils.extend({}, data);\n delete newFlag['key'];\n flags[data.key] = newFlag;\n const newDetail = getFlagDetail(newFlag);\n if (oldFlag) {\n mods[data.key] = { previous: oldFlag.value, current: newDetail };\n } else {\n mods[data.key] = { current: newDetail };\n }\n notifyInspectionFlagChanged(data, newFlag);\n handleFlagChanges(mods); // don't wait for this Promise to be resolved\n } else {\n logger.debug(messages.debugStreamPatchIgnored(data.key));\n }\n },\n delete: function(e) {\n const data = tryParseData(e.data);\n if (!data) {\n return;\n }\n if (!flags[data.key] || flags[data.key].version < data.version) {\n logger.debug(messages.debugStreamDelete(data.key));\n const mods = {};\n if (flags[data.key] && !flags[data.key].deleted) {\n mods[data.key] = { previous: flags[data.key].value };\n }\n flags[data.key] = { version: data.version, deleted: true };\n notifyInspectionFlagChanged(data, flags[data.key]);\n handleFlagChanges(mods); // don't wait for this Promise to be resolved\n } else {\n logger.debug(messages.debugStreamDeleteIgnored(data.key));\n }\n },\n });\n }\n\n function disconnectStream() {\n if (streamActive) {\n stream.disconnect();\n streamActive = false;\n }\n }\n\n // Returns a Promise which will be resolved when we have completely updated the internal flags state,\n // dispatched all change events, and updated local storage if appropriate. This Promise is guaranteed\n // never to have an unhandled rejection.\n function replaceAllFlags(newFlags) {\n const changes = {};\n\n if (!newFlags) {\n return Promise.resolve();\n }\n\n for (const key in flags) {\n if (utils.objectHasOwnProperty(flags, key) && flags[key]) {\n if (newFlags[key] && !utils.deepEquals(newFlags[key].value, flags[key].value)) {\n changes[key] = { previous: flags[key].value, current: getFlagDetail(newFlags[key]) };\n } else if (!newFlags[key] || newFlags[key].deleted) {\n changes[key] = { previous: flags[key].value };\n }\n }\n }\n for (const key in newFlags) {\n if (utils.objectHasOwnProperty(newFlags, key) && newFlags[key] && (!flags[key] || flags[key].deleted)) {\n changes[key] = { current: getFlagDetail(newFlags[key]) };\n }\n }\n\n flags = { ...newFlags };\n\n notifyInspectionFlagsChanged();\n\n return handleFlagChanges(changes).catch(() => {}); // swallow any exceptions from this Promise\n }\n\n // Returns a Promise which will be resolved when we have dispatched all change events and updated\n // local storage if appropriate.\n function handleFlagChanges(changes) {\n const keys = Object.keys(changes);\n\n if (keys.length > 0) {\n const changeEventParams = {};\n keys.forEach(key => {\n const current = changes[key].current;\n const value = current ? current.value : undefined;\n const previous = changes[key].previous;\n emitter.emit(changeEvent + ':' + key, value, previous);\n changeEventParams[key] = current ? { current: value, previous: previous } : { previous: previous };\n });\n\n emitter.emit(changeEvent, changeEventParams);\n emitter.emit(internalChangeEvent, flags);\n\n // By default, we send feature evaluation events whenever we have received new flag values -\n // the client has in effect evaluated these flags just by receiving them. This can be suppressed\n // by setting \"sendEventsOnlyForVariation\". Also, if we have a stateProvider, we don't send these\n // events because we assume they have already been sent by the other client that gave us the flags\n // (when it received them in the first place).\n if (!options.sendEventsOnlyForVariation && !stateProvider) {\n keys.forEach(key => {\n sendFlagEvent(key, changes[key].current);\n });\n }\n }\n\n if (useLocalStorage && persistentFlagStore) {\n return persistentFlagStore.saveFlags(flags);\n } else {\n return Promise.resolve();\n }\n }\n\n function on(event, handler, context) {\n if (isChangeEventKey(event)) {\n subscribedToChangeEvents = true;\n if (inited) {\n updateStreamingState();\n }\n emitter.on(event, handler, context);\n } else {\n emitter.on(...arguments);\n }\n }\n\n function off(event) {\n emitter.off(...arguments);\n if (isChangeEventKey(event)) {\n let haveListeners = false;\n emitter.getEvents().forEach(key => {\n if (isChangeEventKey(key) && emitter.getEventListenerCount(key) > 0) {\n haveListeners = true;\n }\n });\n if (!haveListeners) {\n subscribedToChangeEvents = false;\n if (streamActive && streamForcedState === undefined) {\n disconnectStream();\n }\n }\n }\n }\n\n function setStreaming(state) {\n const newState = state === null ? undefined : state;\n if (newState !== streamForcedState) {\n streamForcedState = newState;\n updateStreamingState();\n }\n }\n\n function updateStreamingState() {\n const shouldBeStreaming = streamForcedState || (subscribedToChangeEvents && streamForcedState === undefined);\n if (shouldBeStreaming && !streamActive) {\n connectStream();\n } else if (!shouldBeStreaming && streamActive) {\n disconnectStream();\n }\n if (diagnosticsManager) {\n diagnosticsManager.setStreaming(shouldBeStreaming);\n }\n }\n\n function isChangeEventKey(event) {\n return event === changeEvent || event.substr(0, changeEvent.length + 1) === changeEvent + ':';\n }\n\n if (typeof options.bootstrap === 'string' && options.bootstrap.toUpperCase() === 'LOCALSTORAGE') {\n if (persistentFlagStore) {\n useLocalStorage = true;\n } else {\n logger.warn(messages.localStorageUnavailable());\n }\n }\n\n if (typeof options.bootstrap === 'object') {\n // Set the flags as soon as possible before we get into any async code, so application code can read\n // them even if the ready event has not yet fired.\n flags = readFlagsFromBootstrap(options.bootstrap);\n }\n\n if (stateProvider) {\n // The stateProvider option is used in the Electron SDK, to allow a client instance in the main process\n // to control another client instance (i.e. this one) in the renderer process. We can't predict which\n // one will start up first, so the initial state may already be available for us or we may have to wait\n // to receive it.\n const state = stateProvider.getInitialState();\n if (state) {\n initFromStateProvider(state);\n } else {\n stateProvider.on('init', initFromStateProvider);\n }\n stateProvider.on('update', updateFromStateProvider);\n } else {\n finishInit().catch(signalFailedInit);\n }\n\n function finishInit() {\n if (!env) {\n return Promise.reject(new errors.LDInvalidEnvironmentIdError(messages.environmentNotSpecified()));\n }\n let afterIdentify;\n return anonymousContextProcessor\n .processContext(context)\n .then(verifyContext)\n .then(context => {\n afterIdentify = utils.once(hookRunner.identify(context, undefined));\n return context;\n })\n .then(validatedContext => {\n afterIdentify?.({ status: 'completed' });\n ident.setContext(validatedContext);\n if (typeof options.bootstrap === 'object') {\n // flags have already been set earlier\n return signalSuccessfulInit();\n } else if (useLocalStorage) {\n return finishInitWithLocalStorage();\n } else {\n return finishInitWithPolling();\n }\n })\n .catch(err => {\n afterIdentify?.({ status: 'error' });\n throw err;\n });\n }\n\n function finishInitWithLocalStorage() {\n return persistentFlagStore.loadFlags().then(storedFlags => {\n if (storedFlags === null || storedFlags === undefined) {\n flags = {};\n return requestor\n .fetchFlagSettings(ident.getContext(), hash)\n .then(requestedFlags => replaceAllFlags(requestedFlags || {}))\n .then(signalSuccessfulInit)\n .catch(err => {\n const initErr = new errors.LDFlagFetchError(messages.errorFetchingFlags(err));\n signalFailedInit(initErr);\n });\n } else {\n // We're reading the flags from local storage. Signal that we're ready,\n // then update localStorage for the next page load. We won't signal changes or update\n // the in-memory flags unless you subscribe for changes\n flags = storedFlags;\n utils.onNextTick(signalSuccessfulInit);\n\n return requestor\n .fetchFlagSettings(ident.getContext(), hash)\n .then(requestedFlags => replaceAllFlags(requestedFlags))\n .catch(err => emitter.maybeReportError(err));\n }\n });\n }\n\n function finishInitWithPolling() {\n return requestor\n .fetchFlagSettings(ident.getContext(), hash)\n .then(requestedFlags => {\n flags = requestedFlags || {};\n\n notifyInspectionFlagsChanged();\n // Note, we don't need to call updateSettings here because local storage and change events are not relevant\n signalSuccessfulInit();\n })\n .catch(err => {\n flags = {};\n signalFailedInit(err);\n });\n }\n\n function initFromStateProvider(state) {\n environment = state.environment;\n ident.setContext(state.context);\n flags = { ...state.flags };\n utils.onNextTick(signalSuccessfulInit);\n }\n\n function updateFromStateProvider(state) {\n if (state.context) {\n ident.setContext(state.context);\n }\n if (state.flags) {\n replaceAllFlags(state.flags); // don't wait for this Promise to be resolved\n }\n }\n\n function signalSuccessfulInit() {\n logger.info(messages.clientInitialized());\n inited = true;\n updateStreamingState();\n initializationStateTracker.signalSuccess();\n }\n\n function signalFailedInit(err) {\n initializationStateTracker.signalFailure(err);\n }\n\n function start() {\n if (sendEvents) {\n if (diagnosticsManager) {\n diagnosticsManager.start();\n }\n events.start();\n }\n }\n\n function close(onDone) {\n if (closed) {\n return utils.wrapPromiseCallback(Promise.resolve(), onDone);\n }\n const finishClose = () => {\n closed = true;\n flags = {};\n };\n const p = Promise.resolve()\n .then(() => {\n disconnectStream();\n if (diagnosticsManager) {\n diagnosticsManager.stop();\n }\n if (sendEvents) {\n events.stop();\n return events.flush();\n }\n })\n .then(finishClose)\n .catch(finishClose);\n return utils.wrapPromiseCallback(p, onDone);\n }\n\n function getFlagsInternal() {\n // used by Electron integration\n return flags;\n }\n\n function waitForInitializationWithTimeout(timeout) {\n if (timeout > highTimeoutThreshold) {\n logger.warn(\n 'The waitForInitialization function was called with a timeout greater than ' +\n `${highTimeoutThreshold} seconds. We recommend a timeout of ` +\n `${highTimeoutThreshold} seconds or less.`\n );\n }\n\n const initPromise = initializationStateTracker.getInitializationPromise();\n const timeoutPromise = timedPromise(timeout, 'waitForInitialization');\n\n return Promise.race([timeoutPromise, initPromise]).catch(e => {\n if (e instanceof errors.LDTimeoutError) {\n logger.error(`waitForInitialization error: ${e}`);\n }\n throw e;\n });\n }\n\n function waitForInitialization(timeout = undefined) {\n if (timeout !== undefined && timeout !== null) {\n if (typeof timeout === 'number') {\n return waitForInitializationWithTimeout(timeout);\n }\n logger.warn('The waitForInitialization method was provided with a non-numeric timeout.');\n }\n logger.warn(\n 'The waitForInitialization function was called without a timeout specified.' +\n ' In a future version a default timeout will be applied.'\n );\n return initializationStateTracker.getInitializationPromise();\n }\n\n function addHook(hook) {\n hookRunner.addHook(hook);\n }\n\n const client = {\n waitForInitialization,\n waitUntilReady: () => initializationStateTracker.getReadyPromise(),\n identify: identify,\n getContext: getContext,\n variation: variation,\n variationDetail: variationDetail,\n track: track,\n on: on,\n off: off,\n setStreaming: setStreaming,\n flush: flush,\n allFlags: allFlags,\n close: close,\n addHook: addHook,\n };\n\n registerPlugins(logger, pluginEnvironment, client, plugins);\n\n return {\n client: client, // The client object containing all public methods.\n options: options, // The validated configuration object, including all defaults.\n emitter: emitter, // The event emitter which can be used to log errors or trigger events.\n ident: ident, // The Identity object that manages the current context.\n logger: logger, // The logging abstraction.\n requestor: requestor, // The Requestor object.\n start: start, // Starts the client once the environment is ready.\n enqueueEvent: enqueueEvent, // Puts an analytics event in the queue, if event sending is enabled.\n getFlagsInternal: getFlagsInternal, // Returns flag data structure with all details.\n getEnvironmentId: () => environment, // Gets the environment ID (this may have changed since initialization, if we have a state provider)\n internalChangeEventName: internalChangeEvent, // This event is triggered whenever we have new flag state.\n };\n}\n\nmodule.exports = {\n initialize,\n commonBasicLogger,\n errors,\n messages,\n utils,\n getContextKeys,\n};\n","const { commonBasicLogger } = require('launchdarkly-js-sdk-common');\n\nfunction basicLogger(options) {\n return commonBasicLogger({ destination: console.log, ...options });\n}\n\nmodule.exports = {\n basicLogger,\n};\n","function isSyncXhrSupported() {\n // This is temporary logic to disable synchronous XHR in Chrome 73 and above. In all other browsers,\n // we will assume it is supported. See https://github.com/launchdarkly/js-client-sdk/issues/147\n const userAgent = window.navigator && window.navigator.userAgent;\n if (userAgent) {\n const chromeMatch = userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./);\n if (chromeMatch) {\n const version = parseInt(chromeMatch[2], 10);\n return version < 73;\n }\n }\n return true;\n}\n\nconst emptyResult = { promise: Promise.resolve({ status: 200, header: () => null, body: null }) };\n\nexport default function newHttpRequest(method, url, headers, body, pageIsClosing) {\n if (pageIsClosing) {\n // When the page is about to close, we have to use synchronous XHR (until we migrate to sendBeacon).\n // But not all browsers support this.\n if (!isSyncXhrSupported()) {\n return emptyResult;\n // Note that we return a fake success response, because we don't want the request to be retried in this case.\n }\n }\n\n const xhr = new window.XMLHttpRequest();\n xhr.open(method, url, !pageIsClosing);\n for (const key in headers || {}) {\n if (Object.prototype.hasOwnProperty.call(headers, key)) {\n xhr.setRequestHeader(key, headers[key]);\n }\n }\n if (pageIsClosing) {\n try {\n xhr.send(body); // We specified synchronous mode when we called xhr.open\n } catch (e) {\n // do nothing intentionally to suppress noise for now\n }\n return emptyResult; // Again, we never want a request to be retried in this case, so we must say it succeeded.\n } else {\n let cancelled;\n const p = new Promise((resolve, reject) => {\n xhr.addEventListener('load', () => {\n if (cancelled) {\n return;\n }\n resolve({\n status: xhr.status,\n header: (key) => xhr.getResponseHeader(key),\n body: xhr.responseText,\n });\n });\n xhr.addEventListener('error', () => {\n if (cancelled) {\n return;\n }\n reject(new Error());\n });\n xhr.send(body);\n });\n const cancel = () => {\n cancelled = true;\n xhr.abort();\n };\n return { promise: p, cancel: cancel };\n }\n}\n","'use strict';\n\nmodule.exports = string => {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a \\unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n};\n","import escapeStringRegexp from 'escape-string-regexp';\n\nexport function doesUrlMatch(matcher, href, search, hash) {\n const keepHash = (matcher.kind === 'substring' || matcher.kind === 'regex') && hash.includes('/');\n const canonicalUrl = (keepHash ? href : href.replace(hash, '')).replace(search, '');\n\n let regex;\n let testUrl;\n\n switch (matcher.kind) {\n case 'exact':\n testUrl = href;\n regex = new RegExp('^' + escapeStringRegexp(matcher.url) + '/?$');\n break;\n case 'canonical':\n testUrl = canonicalUrl;\n regex = new RegExp('^' + escapeStringRegexp(matcher.url) + '/?$');\n break;\n case 'substring':\n testUrl = canonicalUrl;\n regex = new RegExp('.*' + escapeStringRegexp(matcher.substring) + '.*$');\n break;\n case 'regex':\n testUrl = canonicalUrl;\n regex = new RegExp(matcher.pattern);\n break;\n default:\n return false;\n }\n return regex.test(testUrl);\n}\n\nfunction findGoalsForClick(event, clickGoals) {\n const matches = [];\n\n for (let i = 0; i < clickGoals.length; i++) {\n let target = event.target;\n const goal = clickGoals[i];\n const selector = goal.selector;\n const elements = document.querySelectorAll(selector);\n while (target && elements.length > 0) {\n for (let j = 0; j < elements.length; j++) {\n if (target === elements[j]) {\n matches.push(goal);\n }\n }\n target = target.parentNode;\n }\n }\n\n return matches;\n}\n\nexport default function GoalTracker(goals, onEvent) {\n const tracker = {};\n let listenerFn = null;\n\n const clickGoals = [];\n\n for (let i = 0; i < goals.length; i++) {\n const goal = goals[i];\n const urls = goal.urls || [];\n\n for (let j = 0; j < urls.length; j++) {\n if (doesUrlMatch(urls[j], window.location.href, window.location.search, window.location.hash)) {\n if (goal.kind === 'pageview') {\n onEvent('pageview', goal);\n } else {\n clickGoals.push(goal);\n onEvent('click_pageview', goal);\n }\n break;\n }\n }\n }\n\n if (clickGoals.length > 0) {\n listenerFn = function (event) {\n const goals = findGoalsForClick(event, clickGoals);\n for (let i = 0; i < goals.length; i++) {\n onEvent('click', goals[i]);\n }\n };\n\n document.addEventListener('click', listenerFn);\n }\n\n tracker.dispose = function () {\n document.removeEventListener('click', listenerFn);\n };\n\n return tracker;\n}\n","import * as common from 'launchdarkly-js-sdk-common';\nimport GoalTracker from './GoalTracker';\n\nconst locationWatcherInterval = 300;\n\nexport default function GoalManager(clientVars, readyCallback) {\n let goals;\n let goalTracker;\n\n const ret = {};\n\n function getGoalsPath() {\n return '/sdk/goals/' + clientVars.getEnvironmentId();\n }\n\n function refreshGoalTracker() {\n if (goalTracker) {\n goalTracker.dispose();\n }\n if (goals && goals.length) {\n goalTracker = GoalTracker(goals, sendGoalEvent);\n }\n }\n\n function sendGoalEvent(kind, goal) {\n const context = clientVars.ident.getContext();\n const event = {\n kind: kind,\n key: goal.key,\n data: null,\n url: window.location.href,\n creationDate: new Date().getTime(),\n context: context,\n };\n\n if (kind === 'click') {\n event.selector = goal.selector;\n }\n\n return clientVars.enqueueEvent(event);\n }\n\n function watchLocation(interval, callback) {\n let previousUrl = window.location.href;\n let currentUrl;\n\n function checkUrl() {\n currentUrl = window.location.href;\n\n if (currentUrl !== previousUrl) {\n previousUrl = currentUrl;\n callback();\n }\n }\n\n function poll(fn, interval) {\n fn();\n setTimeout(() => {\n poll(fn, interval);\n }, interval);\n }\n\n poll(checkUrl, interval);\n\n if (window.history && window.history.pushState) {\n window.addEventListener('popstate', checkUrl);\n } else {\n window.addEventListener('hashchange', checkUrl);\n }\n }\n\n clientVars.requestor\n .fetchJSON(getGoalsPath())\n .then((g) => {\n if (g && g.length > 0) {\n goals = g;\n goalTracker = GoalTracker(goals, sendGoalEvent);\n watchLocation(locationWatcherInterval, refreshGoalTracker);\n }\n readyCallback();\n })\n .catch((err) => {\n clientVars.emitter.maybeReportError(\n new common.errors.LDUnexpectedResponseError('Error fetching goals: ' + (err && err.message) ? err.message : err)\n );\n readyCallback();\n });\n\n return ret;\n}\n","import * as common from 'launchdarkly-js-sdk-common';\nimport * as importBasicLogger from './basicLogger';\nimport browserPlatform from './browserPlatform';\nimport GoalManager from './GoalManager';\n\nconst goalsEvent = 'goalsReady';\nconst extraOptionDefs = {\n fetchGoals: { default: true },\n hash: { type: 'string' },\n eventProcessor: { type: 'object' }, // used only in tests\n eventUrlTransformer: { type: 'function' },\n disableSyncEventPost: { default: false },\n};\n\n// Pass our platform object to the common code to create the browser version of the client\nexport function initialize(env, user, options = {}) {\n const platform = browserPlatform(options);\n const clientVars = common.initialize(env, user, options, platform, extraOptionDefs);\n\n const client = clientVars.client;\n const validatedOptions = clientVars.options;\n const emitter = clientVars.emitter;\n\n const goalsPromise = new Promise((resolve) => {\n const onGoals = emitter.on(goalsEvent, () => {\n emitter.off(goalsEvent, onGoals);\n resolve();\n });\n });\n client.waitUntilGoalsReady = () => goalsPromise;\n\n if (validatedOptions.fetchGoals) {\n GoalManager(clientVars, () => emitter.emit(goalsEvent));\n // Don't need to save a reference to the GoalManager - its constructor takes care of setting\n // up the necessary event wiring\n } else {\n emitter.emit(goalsEvent);\n }\n\n if (document.readyState !== 'complete') {\n window.addEventListener('load', clientVars.start);\n } else {\n clientVars.start();\n }\n\n const syncFlush = () => {\n // Synchronous events are not available in all browsers, but where they\n // are we should attempt to use them. This increases the chance of the events\n // being delivered.\n platform.synchronousFlush = true;\n client.flush().catch(() => {});\n platform.synchronousFlush = false;\n };\n\n // When the visibility of the page changes to hidden we want to flush any pending events.\n //\n // This is handled with visibility, instead of beforeunload/unload\n // because those events are not compatible with the bfcache and are unlikely\n // to be called in many situations. For more information see: https://developer.chrome.com/blog/page-lifecycle-api/\n //\n // Redundancy is included by using both the visibilitychange handler as well as\n // pagehide, because different browsers, and versions have different bugs with each.\n // This also may provide more opportunity for the events to get flushed.\n //\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'hidden') {\n syncFlush();\n }\n };\n\n document.addEventListener('visibilitychange', handleVisibilityChange);\n window.addEventListener('pagehide', syncFlush);\n\n return client;\n}\n\nexport const basicLogger = importBasicLogger.basicLogger;\n\nexport const createConsoleLogger = common.createConsoleLogger;\n\nexport const version = VERSION;\n\nfunction deprecatedInitialize(env, user, options = {}) {\n console && console.warn && console.warn(common.messages.deprecated('default export', 'named LDClient export')); // eslint-disable-line no-console\n return initialize(env, user, options);\n}\n\nexport default { initialize: deprecatedInitialize, version };\n","import newHttpRequest from './httpRequest';\n\nexport default function makeBrowserPlatform(options) {\n const ret = {\n userAgentHeaderName: 'X-LaunchDarkly-User-Agent',\n };\n\n ret.synchronousFlush = false; // this will be set to true by index.js if the page is hidden\n\n // XMLHttpRequest may not exist if we're running in a server-side rendering context\n if (window.XMLHttpRequest) {\n const disableSyncFlush = options && options.disableSyncEventPost;\n ret.httpRequest = (method, url, headers, body) => {\n const syncFlush = ret.synchronousFlush & !disableSyncFlush;\n ret.synchronousFlush = false;\n return newHttpRequest(method, url, headers, body, syncFlush);\n };\n }\n\n let hasCors;\n ret.httpAllowsPost = () => {\n // We compute this lazily because calling XMLHttpRequest() at initialization time can disrupt tests\n if (hasCors === undefined) {\n hasCors = window.XMLHttpRequest ? 'withCredentials' in new window.XMLHttpRequest() : false;\n }\n return hasCors;\n };\n\n // Image-based mechanism for sending events if POST isn't available\n ret.httpFallbackPing = (url) => {\n const img = new window.Image();\n img.src = url;\n };\n\n const eventUrlTransformer = options && options.eventUrlTransformer;\n ret.getCurrentUrl = () => (eventUrlTransformer ? eventUrlTransformer(window.location.href) : window.location.href);\n\n ret.isDoNotTrack = () => {\n let flag;\n if (window.navigator && window.navigator.doNotTrack !== undefined) {\n flag = window.navigator.doNotTrack; // FF, Chrome\n } else if (window.navigator && window.navigator.msDoNotTrack !== undefined) {\n flag = window.navigator.msDoNotTrack; // IE 9/10\n } else {\n flag = window.doNotTrack; // IE 11+, Safari\n }\n return flag === 1 || flag === true || flag === '1' || flag === 'yes';\n };\n\n try {\n if (window.localStorage) {\n ret.localStorage = {\n get: (key) =>\n new Promise((resolve) => {\n resolve(window.localStorage.getItem(key));\n }),\n set: (key, value) =>\n new Promise((resolve) => {\n window.localStorage.setItem(key, value);\n resolve();\n }),\n clear: (key) =>\n new Promise((resolve) => {\n window.localStorage.removeItem(key);\n resolve();\n }),\n };\n }\n } catch (e) {\n // In some browsers (such as Chrome), even looking at window.localStorage at all will cause a\n // security error if the feature is disabled.\n ret.localStorage = null;\n }\n\n // The browser built-in EventSource implementations do not support setting the method used for\n // the request. When useReport is true, we ensure sending the user in the body of a REPORT request\n // rather than in the URL path. If a polyfill for EventSource that supports setting the request\n // method is provided (currently, launchdarkly-eventsource is the only polyfill that both supports\n // it and gives us a way to *know* that it supports it), we use the polyfill to connect to a flag\n // stream that will provide evaluated flags for the specific user. Otherwise, when useReport is\n // true, we fall back to a generic 'ping' stream that informs the SDK to make a separate REPORT\n // request for the user's flag evaluations whenever the flag definitions have been updated.\n let eventSourceConstructor;\n const useReport = options && options.useReport;\n if (\n useReport &&\n typeof window.EventSourcePolyfill === 'function' &&\n window.EventSourcePolyfill.supportedOptions &&\n window.EventSourcePolyfill.supportedOptions.method\n ) {\n ret.eventSourceAllowsReport = true;\n eventSourceConstructor = window.EventSourcePolyfill;\n } else {\n ret.eventSourceAllowsReport = false;\n eventSourceConstructor = window.EventSource;\n }\n\n // If EventSource does not exist, the absence of eventSourceFactory will make us not try to open streams\n if (window.EventSource) {\n const timeoutMillis = 300000; // this is only used by polyfills - see below\n\n ret.eventSourceFactory = (url, options) => {\n // The standard EventSource constructor doesn't take any options, just a URL. However, some\n // EventSource polyfills allow us to specify a timeout interval, and in some cases they will\n // default to a too-short timeout if we don't specify one. So, here, we are setting the\n // timeout properties that are used by several popular polyfills.\n // Also, the skipDefaultHeaders property (if supported) tells the polyfill not to add the\n // Cache-Control header that can cause CORS problems in browsers.\n // See: https://github.com/launchdarkly/js-eventsource\n const defaultOptions = {\n heartbeatTimeout: timeoutMillis,\n silentTimeout: timeoutMillis,\n skipDefaultHeaders: true,\n };\n\n const esOptions = { ...defaultOptions, ...options };\n\n return new eventSourceConstructor(url, esOptions);\n };\n\n ret.eventSourceIsActive = (es) =>\n es.readyState === window.EventSource.OPEN || es.readyState === window.EventSource.CONNECTING;\n }\n\n ret.userAgent = 'JSClient';\n ret.version = VERSION;\n\n ret.diagnosticSdkData = {\n name: 'js-client-sdk',\n version: VERSION,\n };\n\n ret.diagnosticPlatformData = {\n name: 'JS',\n };\n\n ret.diagnosticUseCombinedEvent = true; // the browser SDK uses the \"diagnostic-combined\" event format\n\n return ret;\n}\n"],"names":["createCustomError","name","CustomError","message","code","Error","captureStackTrace","this","constructor","prototype","LDUnexpectedResponseError","LDInvalidEnvironmentIdError","LDInvalidUserError","LDInvalidEventKeyError","LDInvalidArgumentError","LDFlagFetchError","errors","LDInvalidDataError","LDTimeoutError","isHttpErrorRecoverable","status","byteLength_1","b64","lens","getLens","validLen","placeHoldersLen","toByteArray_1","tmp","i","arr","Arr","_byteLength","curByte","len","revLookup","charCodeAt","fromByteArray_1","uint8","length","extraBytes","parts","maxChunkLength","len2","push","encodeChunk","lookup","join","Uint8Array","Array","indexOf","start","end","num","output","isArray","keyList","Object","keys","hasProp","hasOwnProperty","fastDeepEqual","equal","a","b","key","arrA","arrB","dateA","Date","dateB","getTime","regexpA","RegExp","regexpB","toString","call","userAttrsToStringify","btoa","s","escaped","unescape","encodeURIComponent","base64","fromByteArray","stringToBytes","objectHasOwnProperty","object","getRandomValues","utils","appendUrlPath","baseUrl","path","endsWith","substring","startsWith","base64URLEncode","replace","clone","obj","JSON","parse","stringify","deepEquals","extend","objects","reduce","acc","getLDUserAgentString","platform","version","userAgent","onNextTick","cb","setTimeout","sanitizeContext","context","newContext","kind","undefined","forEach","attr","value","String","transformValuesToVersionedValues","flags","ret","transformVersionedValuesToValues","flagsState","wrapPromiseCallback","promise","callback","then","error","Promise","reject","once","func","result","called","args","apply","rnds8","rng","crypto","bind","msCrypto","REGEX","validate","uuid","test","_nodeId","_clockseq","byteToHex","substr","offset","arguments","toLowerCase","TypeError","_lastMSecs","_lastNSecs","v","parseInt","slice","v35","hashfunc","generateUUID","namespace","buf","str","bytes","set","err","DNS","URL","getOutputLength","inputLength8","safeAdd","x","y","lsw","md5cmn","q","t","cnt","md5ff","c","d","md5gg","md5hh","md5ii","v3","msg","input","length32","hexTab","hex","charAt","md5ToHexEncodedArray","olda","oldb","oldc","oldd","wordsToMd5","length8","Uint32Array","bytesToWords","v3$1","f","z","ROTL","n","v5","K","H","l","N","Math","ceil","M","_i","j","pow","floor","_i2","W","_t","e","_t2","T","v5$1","options","node","clockseq","seedBytes","random","msecs","now","nsecs","dt","tl","tmh","rnds","logLevels","loggers","commonBasicLogger","formatFn","destination","toConsole","methodName","line","console","destinations","prependLevelToMessage","prefix","minLevel","level","write","levelIndex","levelName","fullPrefix","tempArgs","log","logger","validateLogger","errorString","docLink","messages","bootstrapInvalid","bootstrapOldFormat","clientInitialized","clientNotReady","debugEnqueueingEvent","debugPostingDiagnosticEvent","event","debugPostingEvents","count","debugStreamDelete","debugStreamDeleteIgnored","debugStreamPatch","debugStreamPatchIgnored","debugStreamPing","debugPolling","url","debugStreamPut","deprecated","oldName","newName","environmentNotFound","environmentNotSpecified","errorFetchingFlags","eventCapacityExceeded","eventWithoutContext","httpErrorMessage","retryMessage","httpUnavailable","identifyDisabled","inspectorMethodError","type","invalidContentType","contentType","invalidData","invalidInspector","invalidKey","invalidMetricValue","badType","invalidContext","invalidTagValue","localStorageUnavailable","networkError","optionBelowMinimum","minimum","streamClosing","streamConnecting","streamError","streamReconnectDelay","tagValueTooLong","unknownCustomEventKey","unknownOption","contextNotSpecified","unrecoverableStreamError","wrongOptionType","expectedType","actualType","wrongOptionTypeBoolean","require$$0","baseOptionDefs","default","streamUrl","eventsUrl","sendEvents","streaming","sendLDHeaders","requestHeaderTransform","sendEventsOnlyForVariation","useReport","evaluationReasons","eventCapacity","flushInterval","samplingInterval","allAttributesPrivate","privateAttributes","bootstrap","diagnosticRecordingInterval","diagnosticOptOut","wrapperName","wrapperVersion","stateProvider","application","validator","validated","id","validateTagValue","inspectors","hooks","plugins","allowedTagCharacters","canonicalizeUrl","tagValue","match","warn","configuration","emitter","extraOptionDefs","optionDefs","deprecatedOptions","reportArgumentError","maybeReportError","config","opts","checkDeprecatedOptions","applyDefaults","typeDescForValue","optionDef","allowedTypes","split","validateTypesAndNames","getTags","tags","headers","getLDHeaders","h","userAgentHeaderName","tagKeys","sort","map","flattened","item","concat","transformHeaders","v1","uuidv1","require$$1","EventSender_1","environmentId","baseHeaders","sender","events","isDiagnostic","httpRequest","resolve","jsonBody","payloadId","doPostRequest","canRetry","dateStr","header","time","serverTime","getResponseInfo","catch","canonicalize_1","canonicalize","visited","includes","filter","validKind","encodeKey","checkContext","allowLegacyKey","kindValid","keyValid","kinds","every","contextKey","getContextKeys","user","entries","getContextKinds","getCanonicalKey","EventSummarizer_1","es","startDate","endDate","counters","contextKinds","summarizeEvent","counterKey","variation","counterVal","Set","contextKeys","getKinds","add","creationDate","getSummary","flagsOut","empty","values","flag","counterOut","unknown","features","clearSummary","MultiEventSummarizer_1","contextFilter","summarizers","contexts","summarizer","EventSummarizer","getSummaries","summarizersToFlush","contextsForSummaries","summary","processEscapeCharacters","getComponents","reference","component","isLiteral","compare","aIsLiteral","bIsLiteral","bComponents","aComponents","literalToReference","literal","attributeReference","cloneExcluding","target","references","stack","cloned","excluded","ptr","source","parent","pop","some","ContextFilter_1","protectedAttributes","legacyTopLevelCopyAttributes","filterSingleKind","redactAnonymous","AttributeReference","anonymous","_meta","protectedAttr","getAttributesToFilter","redactedAttributes","filtered","custom","privateAttributeNames","legacyToSingleKind","filteredContext","filterMultiKind","EventProcessor_1","diagnosticsAccumulator","processor","eventSender","EventSender","mainEventsUrl","ContextFilter","MultiEventSummarizer","flushTimer","queue","lastKnownPastTime","disabled","exceededCapacity","shouldSampleEvent","makeOutputEvent","addToOutbox","incrementDroppedEvents","enqueue","addFullEvent","addDebugEvent","trackEvents","debugEventsUntilDate","debugEvent","flush","async","eventsToSend","setEventsInLastBatch","debug","responseInfo","flushTick","stop","clearTimeout","EventEmitter_1","on","handler","off","emit","copiedHandlers","getEvents","getEventListenerCount","readyEvent","successEvent","failureEvent","InitializationState","eventEmitter","succeeded","failed","failureValue","initializationPromise","readyPromise","onReady","getInitializationPromise","onSuccess","onFailure","getReadyPromise","signalSuccess","signalFailure","PersistentFlagStore_1","storage","environment","hash","ident","store","getFlagsKey","getContext","loadFlags","get","dataStr","data","schema","$schema","ex","clearFlags","saveFlags","clear","PersistentStorage_1","localStorageProvider","loggedError","logError","isEnabled","require$$2","Stream_1","stream","evalUrlPrefix","withReasons","baseReconnectDelay","connectionAttemptStartTime","firstConnectionErrorLogged","reconnectTimeoutReference","handlers","retryCount","getNextRetryDelay","delay","computedDelayMillis","backoff","trunc","handleError","closeConnection","logConnectionResult","tryConnect","openConnection","query","readTimeoutMillis","eventSourceFactory","eventSourceAllowsReport","method","body","info","addEventListener","onerror","onopen","close","success","recordStreamInit","connect","newHash","newHandlers","disconnect","isConnected","eventSourceIsActive","promiseCoalescer_1","finallyFn","currentPromise","currentCancelFn","finalResolve","finalReject","coalescer","p","cancelFn","resultPromise","jsonContentType","Requestor_1","requestor","activeRequests","fetchJSON","endpoint","promiseCoalescer","req","statusText","getResponseError","addPromise","cancel","fetchFlagSettings","Identity_1","initialContext","onChange","setContext","AnonymousContextProcessor_1","persistentStorage","getContextKeyIdString","processSingleKindContext","getCachedContextKey","cachedId","setCachedContextKey","processContext","processedContext","all","diagnosticEvents","DiagnosticId","sdkKey","diagnosticId","sdkKeySuffix","DiagnosticsAccumulator","startTime","dataSinceDate","droppedEvents","eventsInLastBatch","streamInits","reset","getProps","setProps","props","timestamp","durationMillis","DiagnosticsManager","accumulator","combinedMode","diagnosticUseCombinedEvent","localStorageKey","diagnosticEventsUrl","periodicInterval","eventSentTime","periodicTimer","streamingEnabled","manager","makeInitProperties","sdk","makeSdkData","makeConfigData","diagnosticPlatformData","sendDiagnosticEvent","sendPeriodicEvent","currentTime","createPeriodicEventAndReset","saveProperties","sdkData","diagnosticSdkData","customBaseURI","customStreamURI","customEventsURI","eventsCapacity","eventsFlushIntervalMillis","reconnectTimeMillis","streamingDisabled","diagnosticRecordingIntervalMillis","usingSecureMode","bootstrapMode","fetchGoalsDisabled","fetchGoals","loadProperties","localStorageAvailable","nextEventTime","timeNow","setStreaming","enabled","SafeInspector_1","inspector","errorLogged","wrapper","synchronous","InspectorTypes","flagUsed","flagDetailsChanged","flagDetailChanged","clientIdentityChanged","freeze","InspectorManager_1","InspectorManager","inspectorsByType","synchronousInspectorsByType","safeInspectors","SafeInspector","safeInspector","hasListeners","onFlagUsed","flagKey","detail","onFlags","onFlagChanged","onIdentityChanged","timedPromise_1","taskName","_res","UNKNOWN_HOOK_NAME","tryExecuteStage","hookName","stage","def","getHookName","hook","getMetadata","HookRunner","initialHooks","hooksInternal","withEvaluation","defaultValue","hookContext","hookData","beforeEvaluation","executeBeforeEvaluation","updatedData","hookIndex","afterEvaluation","executeAfterEvaluation","identify","timeout","beforeIdentify","executeBeforeIdentify","afterIdentify","executeAfterIdentify","addHook","afterTrack","executeAfterTrack","UNKNOWN_PLUGIN_NAME","getPluginName","plugin","getPluginHooks","environmentMetadata","pluginHooks","getHooks","registerPlugins","client","register","createPluginEnvironment","env","pluginSdkMetadata","pluginApplicationMetadata","pluginEnvironment","clientSideId","require$$3","changeEvent","internalChangeEvent","src","initialize","specifiedOptions","createLogger","EventEmitter","initializationStateTracker","InitializationStateTracker","inspectorManager","hookRunner","createHookRunner","PersistentStorage","localStorage","diagnosticsEnabled","diagnostics","diagnosticsManager","Stream","eventProcessor","EventProcessor","Requestor","useLocalStorage","streamActive","subscribedToChangeEvents","streamForcedState","inited","closed","firstEvent","Identity","enqueueEvent","sendIdentifyEvent","anonymousContextProcessor","AnonymousContextProcessor","persistentFlagStore","PersistentFlagStore","isDoNotTrack","notifyInspectionFlagChanged","newFlag","getFlagDetail","notifyInspectionFlagsChanged","cur","sendFlagEvent","includeReason","variationIndex","flagVersion","trackReason","reason","verifyContext","variationDetailInternal","sendEvent","includeReasonInEvent","isAllFlags","notifyInspection","deleted","errorKind","prerequisites","notifyInspectionFlagUsed","connectStream","tryParseData","jsonData","ping","contextAtTimeOfPingEvent","requestedFlags","replaceAllFlags","put","patch","oldFlag","mods","newDetail","previous","current","handleFlagChanges","delete","disconnectStream","newFlags","changes","changeEventParams","updateStreamingState","shouldBeStreaming","isChangeEventKey","toUpperCase","metadataKey","validKey","metadata","readFlagsFromBootstrap","state","getInitialState","initFromStateProvider","validatedContext","signalSuccessfulInit","storedFlags","signalFailedInit","finishInit","waitForInitialization","initPromise","timeoutPromise","timedPromise","race","waitForInitializationWithTimeout","waitUntilReady","onDone","clearFirst","flagValueMap","variationDetail","track","metricValue","customEventFilter","getCurrentUrl","contextKind","haveListeners","newState","allFlags","results","finishClose","getFlagsInternal","getEnvironmentId","internalChangeEventName","_objectSpread","emptyResult","newHttpRequest","pageIsClosing","window","navigator","chromeMatch","isSyncXhrSupported","xhr","XMLHttpRequest","open","setRequestHeader","send","cancelled","getResponseHeader","responseText","abort","escapeStringRegexp","string","doesUrlMatch","matcher","href","search","regex","testUrl","canonicalUrl","pattern","GoalTracker","goals","onEvent","tracker","listenerFn","clickGoals","goal","urls","location","matches","selector","elements","document","querySelectorAll","parentNode","findGoalsForClick","dispose","removeEventListener","GoalManager","clientVars","readyCallback","goalTracker","refreshGoalTracker","sendGoalEvent","g","interval","currentUrl","previousUrl","checkUrl","poll","fn","history","pushState","watchLocation","common","goalsEvent","eventUrlTransformer","disableSyncEventPost","hasCors","disableSyncFlush","syncFlush","synchronousFlush","httpAllowsPost","httpFallbackPing","Image","eventSourceConstructor","doNotTrack","msDoNotTrack","getItem","setItem","removeItem","EventSourcePolyfill","supportedOptions","EventSource","timeoutMillis","esOptions","defaultOptions","heartbeatTimeout","silentTimeout","skipDefaultHeaders","readyState","OPEN","CONNECTING","browserPlatform","validatedOptions","goalsPromise","onGoals","waitUntilGoalsReady","visibilityState","basicLogger","importBasicLogger","createConsoleLogger","index"],"mappings":"AAAA,SAASA,EAAkBC,GACzB,SAASC,EAAYC,EAASC,GAC5BC,MAAMC,mBAAqBD,MAAMC,kBAAkBC,KAAMA,KAAKC,aAC9DD,KAAKJ,QAAUA,EACfI,KAAKH,KAAOA,CACb,CAMD,OAJAF,EAAYO,UAAY,IAAIJ,MAC5BH,EAAYO,UAAUR,KAAOA,EAC7BC,EAAYO,UAAUD,YAAcN,EAE7BA,CACT,CAEA,MAAMQ,EAA4BV,EAAkB,uCAC9CW,EAA8BX,EAAkB,yCAChDY,EAAqBZ,EAAkB,gCACvCa,EAAyBb,EAAkB,oCAC3Cc,EAAyBd,EAAkB,oCAC3Ce,EAAmBf,EAAkB,8BCR3C,IDmBA,IAAAgB,EAAiB,CACfN,4BACAC,8BACAC,qBACAC,yBACAC,yBACAG,mBAhByBjB,EAAkB,gCAiB3Ce,mBACFG,eAjBuBlB,EAAkB,4BAkBzCmB,uBAhBA,SAAgCC,GAC9B,QAAIA,GAAU,KAAOA,EAAS,OACV,MAAXA,GAA6B,MAAXA,GAA6B,MAAXA,EAG/C,GC1BAC,EAuCA,SAAqBC,GACnB,IAAIC,EAAOC,EAAQF,GACfG,EAAWF,EAAK,GAChBG,EAAkBH,EAAK,GAC3B,OAAuC,GAA9BE,EAAWC,GAAuB,EAAKA,CAClD,EA3CAC,EAiDA,SAAsBL,GACpB,IAAIM,EAcAC,EAbAN,EAAOC,EAAQF,GACfG,EAAWF,EA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/launchdarkly-js-client-sdk/dist/ldclient.min.js b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.min.js new file mode 100644 index 00000000..4e7fc5f2 --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LDClient={})}(this,(function(e){"use strict";function t(e){function t(e,t){Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.message=e,this.code=t}return t.prototype=new Error,t.prototype.name=e,t.prototype.constructor=t,t}const n=t("LaunchDarklyUnexpectedResponseError"),r=t("LaunchDarklyInvalidEnvironmentIdError"),o=t("LaunchDarklyInvalidUserError"),i=t("LaunchDarklyInvalidEventKeyError"),a=t("LaunchDarklyInvalidArgumentError"),s=t("LaunchDarklyFlagFetchError");for(var c={LDUnexpectedResponseError:n,LDInvalidEnvironmentIdError:r,LDInvalidUserError:o,LDInvalidEventKeyError:i,LDInvalidArgumentError:a,LDInvalidDataError:t("LaunchDarklyInvalidDataError"),LDFlagFetchError:s,LDTimeoutError:t("LaunchDarklyTimeoutError"),isHttpErrorRecoverable:function(e){return!(e>=400&&e<500)||(400===e||408===e||429===e)}},u=function(e){var t=h(e),n=t[0],r=t[1];return 3*(n+r)/4-r},l=function(e){var t,n,r=h(e),o=r[0],i=r[1],a=new v(function(e,t,n){return 3*(t+n)/4-n}(0,o,i)),s=0,c=i>0?o-4:o;for(n=0;n>16&255,a[s++]=t>>8&255,a[s++]=255&t;2===i&&(t=g[e.charCodeAt(n)]<<2|g[e.charCodeAt(n+1)]>>4,a[s++]=255&t);1===i&&(t=g[e.charCodeAt(n)]<<10|g[e.charCodeAt(n+1)]<<4|g[e.charCodeAt(n+2)]>>2,a[s++]=t>>8&255,a[s++]=255&t);return a},d=function(e){for(var t,n=e.length,r=n%3,o=[],i=16383,a=0,s=n-r;as?s:a+i));1===r?(t=e[n-1],o.push(f[t>>2]+f[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],o.push(f[t>>10]+f[t>>4&63]+f[t<<2&63]+"="));return o.join("")},f=[],g=[],v="undefined"!=typeof Uint8Array?Uint8Array:Array,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",m=0;m<64;++m)f[m]=p[m],g[p.charCodeAt(m)]=m;function h(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function y(e,t,n){for(var r,o,i=[],a=t;a>18&63]+f[o>>12&63]+f[o>>6&63]+f[63&o]);return i.join("")}g["-".charCodeAt(0)]=62,g["_".charCodeAt(0)]=63;var w={byteLength:u,toByteArray:l,fromByteArray:d},b=Array.isArray,k=Object.keys,E=Object.prototype.hasOwnProperty,D=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){var r,o,i,a=b(t),s=b(n);if(a&&s){if((o=t.length)!=n.length)return!1;for(r=o;0!==r--;)if(!e(t[r],n[r]))return!1;return!0}if(a!=s)return!1;var c=t instanceof Date,u=n instanceof Date;if(c!=u)return!1;if(c&&u)return t.getTime()==n.getTime();var l=t instanceof RegExp,d=n instanceof RegExp;if(l!=d)return!1;if(l&&d)return t.toString()==n.toString();var f=k(t);if((o=f.length)!==k(n).length)return!1;for(r=o;0!==r--;)if(!E.call(n,f[r]))return!1;for(r=o;0!==r--;)if(!e(t[i=f[r]],n[i]))return!1;return!0}return t!=t&&n!=n};const x=["key","ip","country","email","firstName","lastName","avatar","name"];function C(e){const t=unescape(encodeURIComponent(e));return w.fromByteArray(function(e){const t=[];for(let n=0;n({...e,...t})),{})},getLDUserAgentString:function(e){const t=e.version||"?";return e.userAgent+"/"+t},objectHasOwnProperty:P,onNextTick:function(e){setTimeout(e,0)},sanitizeContext:function(e){if(!e)return e;let t;return null!==e.kind&&void 0!==e.kind||x.forEach((n=>{const r=e[n];void 0!==r&&"string"!=typeof r&&(t=t||{...e},t[n]=String(r))})),t||e},transformValuesToVersionedValues:function(e){const t={};for(const n in e)P(e,n)&&(t[n]={value:e[n],version:0});return t},transformVersionedValuesToValues:function(e){const t={};for(const n in e)P(e,n)&&(t[n]=e[n].value);return t},wrapPromiseCallback:function(e,t){const n=e.then((e=>(t&&setTimeout((()=>{t(null,e)}),0),e)),(e=>{if(!t)return Promise.reject(e);setTimeout((()=>{t(e,null)}),0)}));return t?void 0:n},once:function(e){let t,n=!1;return function(...r){return n||(n=!0,t=e.apply(this,r)),t}}},O=new Uint8Array(16);function T(){if(!S&&!(S="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return S(O)}var L=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function U(e){return"string"==typeof e&&L.test(e)}for(var j,A,R=[],F=0;F<256;++F)R.push((F+256).toString(16).substr(1));function N(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]).toLowerCase();if(!U(n))throw TypeError("Stringified UUID is invalid");return n}var $=0,V=0;function H(e){if(!U(e))throw TypeError("Invalid UUID");var t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=255&t,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=255&t,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=255&t,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=255&t,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=255&t,n}function M(e,t,n){function r(e,r,o,i){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n>>9<<4)+1}function z(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function K(e,t,n,r,o,i){return z((a=z(z(t,e),z(r,i)))<<(s=o)|a>>>32-s,n);var a,s}function _(e,t,n,r,o,i,a){return K(t&n|~t&r,e,t,o,i,a)}function J(e,t,n,r,o,i,a){return K(t&r|n&~r,e,t,o,i,a)}function B(e,t,n,r,o,i,a){return K(t^n^r,e,t,o,i,a)}function G(e,t,n,r,o,i,a){return K(n^(t|~r),e,t,o,i,a)}var W=M("v3",48,(function(e){if("string"==typeof e){var t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(var n=0;n>5]>>>o%32&255,a=parseInt(r.charAt(i>>>4&15)+r.charAt(15&i),16);t.push(a)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[r/8])<>>32-t}var Z=M("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var r=unescape(encodeURIComponent(e));e=[];for(var o=0;o>>0;w=y,y=h,h=Y(m,30)>>>0,m=p,p=E}n[0]=n[0]+p>>>0,n[1]=n[1]+m>>>0,n[2]=n[2]+h>>>0,n[3]=n[3]+y>>>0,n[4]=n[4]+w>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]})),ee=Z;var te=Object.freeze({__proto__:null,v1:function(e,t,n){var r=t&&n||0,o=t||new Array(16),i=(e=e||{}).node||j,a=void 0!==e.clockseq?e.clockseq:A;if(null==i||null==a){var s=e.random||(e.rng||T)();null==i&&(i=j=[1|s[0],s[1],s[2],s[3],s[4],s[5]]),null==a&&(a=A=16383&(s[6]<<8|s[7]))}var c=void 0!==e.msecs?e.msecs:Date.now(),u=void 0!==e.nsecs?e.nsecs:V+1,l=c-$+(u-V)/1e4;if(l<0&&void 0===e.clockseq&&(a=a+1&16383),(l<0||c>$)&&void 0===e.nsecs&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");$=c,V=u,A=a;var d=(1e4*(268435455&(c+=122192928e5))+u)%4294967296;o[r++]=d>>>24&255,o[r++]=d>>>16&255,o[r++]=d>>>8&255,o[r++]=255&d;var f=c/4294967296*1e4&268435455;o[r++]=f>>>8&255,o[r++]=255&f,o[r++]=f>>>24&15|16,o[r++]=f>>>16&255,o[r++]=a>>>8|128,o[r++]=255&a;for(var g=0;g<6;++g)o[r+g]=i[g];return t||N(o)},v3:X,v4:function(e,t,n){var r=(e=e||{}).random||(e.rng||T)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(var o=0;o<16;++o)t[n+o]=r[o];return t}return N(r)},v5:ee,NIL:"00000000-0000-0000-0000-000000000000",version:function(e){if(!U(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)},validate:U,stringify:N,parse:H});const ne=["debug","info","warn","error","none"];var re={commonBasicLogger:function(e,t){if(e&&e.destination&&"function"!=typeof e.destination)throw new Error("destination for basicLogger was set to a non-function");function n(e){return function(t){console&&console[e]&&console[e].call(console,t)}}const r=e&&e.destination?[e.destination,e.destination,e.destination,e.destination]:[n("log"),n("info"),n("warn"),n("error")],o=!(!e||!e.destination),i=e&&void 0!==e.prefix&&null!==e.prefix?e.prefix:"[LaunchDarkly] ";let a=1;if(e&&e.level)for(let t=0;t{};else{const n=e;c[t]=function(){s(n,t,arguments)}}}return c},validateLogger:function(e){ne.forEach((t=>{if("none"!==t&&(!e[t]||"function"!=typeof e[t]))throw new Error("Provided logger instance must support logger."+t+"(...) method")}))}};function oe(e){return e&&e.message?e.message:"string"==typeof e||e instanceof String?e:JSON.stringify(e)}const ie=" Please see https://docs.launchdarkly.com/sdk/client-side/javascript#initialize-the-client for instructions on SDK initialization.";var ae={bootstrapInvalid:function(){return"LaunchDarkly bootstrap data is not available because the back end could not read the flags."},bootstrapOldFormat:function(){return"LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."+ie},clientInitialized:function(){return"LaunchDarkly client initialized"},clientNotReady:function(){return"LaunchDarkly client is not ready"},debugEnqueueingEvent:function(e){return'enqueueing "'+e+'" event'},debugPostingDiagnosticEvent:function(e){return"sending diagnostic event ("+e.kind+")"},debugPostingEvents:function(e){return"sending "+e+" events"},debugStreamDelete:function(e){return'received streaming deletion for flag "'+e+'"'},debugStreamDeleteIgnored:function(e){return'received streaming deletion for flag "'+e+'" but ignored due to version check'},debugStreamPatch:function(e){return'received streaming update for flag "'+e+'"'},debugStreamPatchIgnored:function(e){return'received streaming update for flag "'+e+'" but ignored due to version check'},debugStreamPing:function(){return"received ping message from stream"},debugPolling:function(e){return"polling for feature flags at "+e},debugStreamPut:function(){return"received streaming update for all flags"},deprecated:function(e,t){return t?'"'+e+'" is deprecated, please use "'+t+'"':'"'+e+'" is deprecated'},environmentNotFound:function(){return"Environment not found. Double check that you specified a valid environment/client-side ID."+ie},environmentNotSpecified:function(){return"No environment/client-side ID was specified."+ie},errorFetchingFlags:function(e){return"Error fetching flag settings: "+oe(e)},eventCapacityExceeded:function(){return"Exceeded event queue capacity. Increase capacity to avoid dropping events."},eventWithoutContext:function(){return"Be sure to call `identify` in the LaunchDarkly client: https://docs.launchdarkly.com/sdk/features/identify#javascript"},httpErrorMessage:function(e,t,n){return"Received error "+e+(401===e?" (invalid SDK key)":"")+" for "+t+" - "+(c.isHttpErrorRecoverable(e)?n:"giving up permanently")},httpUnavailable:function(){return"Cannot make HTTP requests in this environment."+ie},identifyDisabled:function(){return"identify() has no effect here; it must be called on the main client instance"},inspectorMethodError:(e,t)=>`an inspector: "${t}" of type: "${e}" generated an exception`,invalidContentType:function(e){return'Expected application/json content type but got "'+e+'"'},invalidData:function(){return"Invalid data received from LaunchDarkly; connection may have been interrupted"},invalidInspector:(e,t)=>`an inspector: "${t}" of an invalid type (${e}) was configured`,invalidKey:function(){return"Event key must be a string"},invalidMetricValue:e=>`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`,invalidContext:function(){return"Invalid context specified."+ie},invalidTagValue:e=>`Config option "${e}" must only contain letters, numbers, ., _ or -.`,localStorageUnavailable:function(e){return"local storage is unavailable: "+oe(e)},networkError:e=>"network error"+(e?" ("+e+")":""),optionBelowMinimum:(e,t,n)=>'Config option "'+e+'" was set to '+t+", changing to minimum value of "+n,streamClosing:function(){return"Closing stream connection"},streamConnecting:function(e){return"Opening stream connection to "+e},streamError:function(e,t){return"Error on stream connection: "+oe(e)+", will continue retrying after "+t+" milliseconds."},tagValueTooLong:e=>`Value of "${e}" was longer than 64 characters and was discarded.`,unknownCustomEventKey:function(e){return'Custom event "'+e+'" does not exist'},unknownOption:e=>'Ignoring unknown config option "'+e+'"',contextNotSpecified:function(){return"No context specified."+ie},unrecoverableStreamError:e=>`Error on stream connection ${oe(e)}, giving up permanently`,wrongOptionType:(e,t,n)=>'Config option "'+e+'" should be of type '+t+", got "+n+", using default value",wrongOptionTypeBoolean:(e,t)=>'Config option "'+e+'" should be a boolean, got '+t+", converting to boolean"};const{validateLogger:se}=re,ce={baseUrl:{default:"https://app.launchdarkly.com"},streamUrl:{default:"https://clientstream.launchdarkly.com"},eventsUrl:{default:"https://events.launchdarkly.com"},sendEvents:{default:!0},streaming:{type:"boolean"},sendLDHeaders:{default:!0},requestHeaderTransform:{type:"function"},sendEventsOnlyForVariation:{default:!1},useReport:{default:!1},evaluationReasons:{default:!1},eventCapacity:{default:100,minimum:1},flushInterval:{default:2e3,minimum:2e3},samplingInterval:{default:0,minimum:0},streamReconnectDelay:{default:1e3,minimum:0},allAttributesPrivate:{default:!1},privateAttributes:{default:[]},bootstrap:{type:"string|object"},diagnosticRecordingInterval:{default:9e5,minimum:2e3},diagnosticOptOut:{default:!1},wrapperName:{type:"string"},wrapperVersion:{type:"string"},stateProvider:{type:"object"},application:{validator:function(e,t,n){const r={};t.id&&(r.id=de(`${e}.id`,t.id,n));t.version&&(r.version=de(`${e}.version`,t.version,n));return r}},inspectors:{default:[]},hooks:{default:[]},plugins:{default:[]}},ue=/^(\w|\.|-)+$/;function le(e){return e&&e.replace(/\/+$/,"")}function de(e,t,n){if("string"==typeof t&&t.match(ue)){if(!(t.length>64))return t;n.warn(ae.tagValueTooLong(e))}else n.warn(ae.invalidTagValue(e))}var fe={baseOptionDefs:ce,validate:function(e,t,n,r){const o=I.extend({logger:{default:r}},ce,n),i={};function a(e){I.onNextTick((()=>{t&&t.maybeReportError(new c.LDInvalidArgumentError(e))}))}let s=I.extend({},e||{});return function(e){const t=e;Object.keys(i).forEach((e=>{if(void 0!==t[e]){const n=i[e];r&&r.warn(ae.deprecated(e,n)),n&&(void 0===t[n]&&(t[n]=t[e]),delete t[e])}}))}(s),s=function(e){const t=I.extend({},e);return Object.keys(o).forEach((e=>{void 0!==t[e]&&null!==t[e]||(t[e]=o[e]&&o[e].default)})),t}(s),s=function(e){const t=I.extend({},e),n=e=>{if(null===e)return"any";if(void 0===e)return;if(Array.isArray(e))return"array";const t=typeof e;return"boolean"===t||"string"===t||"number"===t||"function"===t?t:"object"};return Object.keys(e).forEach((i=>{const s=e[i];if(null!=s){const c=o[i];if(void 0===c)a(ae.unknownOption(i));else{const o=c.type||n(c.default),u=c.validator;if(u){const n=u(i,e[i],r);void 0!==n?t[i]=n:delete t[i]}else if("any"!==o){const e=o.split("|"),r=n(s);e.indexOf(r)<0?"boolean"===o?(t[i]=!!s,a(ae.wrongOptionTypeBoolean(i,r))):(a(ae.wrongOptionType(i,o,r)),t[i]=c.default):"number"===r&&void 0!==c.minimum&&sArray.isArray(r[e])?r[e].sort().map((t=>`${e}/${t}`)):[`${e}/${r[e]}`])).reduce(((e,t)=>e.concat(t)),[]).join(" ")),n},transformHeaders:function(e,t){return t&&t.requestHeaderTransform?t.requestHeaderTransform({...e}):e}};const{v1:pe}=te,{getLDHeaders:me,transformHeaders:he}=ve;var ye=function(e,t,n){const r=I.extend({"Content-Type":"application/json"},me(e,n)),o={};return o.sendEvents=(t,o,i)=>{if(!e.httpRequest)return Promise.resolve();const a=JSON.stringify(t),s=i?null:pe();return function t(u){const l=i?r:I.extend({},r,{"X-LaunchDarkly-Event-Schema":"4","X-LaunchDarkly-Payload-ID":s});return e.httpRequest("POST",o,he(l,n),a).promise.then((e=>{if(e)return e.status>=400&&c.isHttpErrorRecoverable(e.status)&&u?t(!1):function(e){const t={status:e.status},n=e.header("date");if(n){const e=Date.parse(n);e&&(t.serverTime=e)}return t}(e)})).catch((()=>u?t(!1):Promise.reject()))}(!0).catch((()=>{}))},o};var we=function e(t,n=[]){if(null===t||"object"!=typeof t)return JSON.stringify(t);if(n.includes(t))throw new Error("Cycle detected");if(Array.isArray(t)){return`[${t.map((r=>e(r,[...n,t]))).map((e=>void 0===e?"null":e)).join(",")}]`}return`{${Object.keys(t).sort().map((r=>{const o=e(t[r],[...n,t]);if(void 0!==o)return`${JSON.stringify(r)}:${o}`})).filter((e=>void 0!==e)).join(",")}}`};const{commonBasicLogger:be}=re;function ke(e){return"string"==typeof e&&"kind"!==e&&e.match(/^(\w|\.|-)+$/)}function Ee(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}var De={checkContext:function(e,t){if(e){if(t&&(void 0===e.kind||null===e.kind))return void 0!==e.key&&null!==e.key;const n=e.key,r=void 0===e.kind?"user":e.kind,o=ke(r),i="multi"===r||null!=n&&""!==n;if("multi"===r){const t=Object.keys(e).filter((e=>"kind"!==e));return i&&t.every((e=>ke(e)))&&t.every((t=>{const n=e[t].key;return null!=n&&""!==n}))}return i&&o}return!1},getContextKeys:function(e,t=be()){if(!e)return;const n={},{kind:r,key:o}=e;switch(r){case void 0:n.user=`${o}`;break;case"multi":Object.entries(e).filter((([e])=>"kind"!==e)).forEach((([e,t])=>{t&&t.key&&(n[e]=t.key)}));break;case null:t.warn(`null is not a valid context kind: ${e}`);break;case"":t.warn(`'' is not a valid context kind: ${e}`);break;default:n[r]=`${o}`}return n},getContextKinds:function(e){return e?null===e.kind||void 0===e.kind?["user"]:"multi"!==e.kind?[e.kind]:Object.keys(e).filter((e=>"kind"!==e)):[]},getCanonicalKey:function(e){if(e){if((void 0===e.kind||null===e.kind||"user"===e.kind)&&e.key)return e.key;if("multi"!==e.kind&&e.key)return`${e.kind}:${Ee(e.key)}`;if("multi"===e.kind)return Object.keys(e).sort().filter((e=>"kind"!==e)).map((t=>`${t}:${Ee(e[t].key)}`)).join(":")}}};const{getContextKinds:xe}=De;var Ce=function(){const e={};let t=0,n=0,r={},o={};return e.summarizeEvent=e=>{if("feature"===e.kind){const i=e.key+":"+(null!==e.variation&&void 0!==e.variation?e.variation:"")+":"+(null!==e.version&&void 0!==e.version?e.version:""),a=r[i];let s=o[e.key];s||(s=new Set,o[e.key]=s),function(e){return e.context?xe(e.context):e.contextKeys?Object.keys(e.contextKeys):[]}(e).forEach((e=>s.add(e))),a?a.count=a.count+1:r[i]={count:1,key:e.key,version:e.version,variation:e.variation,value:e.value,default:e.default},(0===t||e.creationDaten&&(n=e.creationDate)}},e.getSummary=()=>{const e={};let i=!0;for(const t of Object.values(r)){let n=e[t.key];n||(n={default:t.default,counters:[],contextKinds:[...o[t.key]]},e[t.key]=n);const r={value:t.value,count:t.count};void 0!==t.variation&&null!==t.variation&&(r.variation=t.variation),void 0!==t.version&&null!==t.version?r.version=t.version:r.unknown=!0,n.counters.push(r),i=!1}return i?null:{startDate:t,endDate:n,features:e,kind:"summary"}},e.clearSummary=()=>{t=0,n=0,r={},o={}},e};var Pe=function(e){let t={},n={};return{summarizeEvent:function(e){if("feature"===e.kind){const r=we(e.context);if(!r)return;let o=t[r];o||(t[r]=Ce(),o=t[r],n[r]=e.context),o.summarizeEvent(e)}},getSummaries:function(){const r=t,o=n;return t={},n={},Object.entries(r).map((([t,n])=>{const r=n.getSummary();return r.context=e.filter(o[t]),r}))}}};function Se(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Ie(e){return(e.startsWith("/")?e.substring(1):e).split("/").map((e=>e.indexOf("~")>=0?e.replace(/~1/g,"/").replace(/~0/g,"~"):e))}function Oe(e){return!e.startsWith("/")}function Te(e,t){const n=Oe(e),r=Oe(t);if(n&&r)return e===t;if(n){const n=Ie(t);return 1===n.length&&e===n[0]}if(r){const n=Ie(e);return 1===n.length&&t===n[0]}return e===t}function Le(e){return`/${Se(e)}`}var Ue={cloneExcluding:function(e,t){const n=[],r={},o=[];for(n.push(...Object.keys(e).map((t=>({key:t,ptr:Le(t),source:e,parent:r,visited:[e]}))));n.length;){const e=n.pop();if(t.some((t=>Te(t,e.ptr))))o.push(e.ptr);else{const t=e.source[e.key];if(null===t)e.parent[e.key]=t;else if(Array.isArray(t))e.parent[e.key]=[...t];else if("object"==typeof t){if(e.visited.includes(t))continue;e.parent[e.key]={},n.push(...Object.keys(t).map((n=>{return{key:n,ptr:(r=e.ptr,o=Se(n),`${r}/${o}`),source:t,parent:e.parent[e.key],visited:[...e.visited,t]};var r,o})))}else e.parent[e.key]=t}}return{cloned:r,excluded:o.sort()}},compare:Te,literalToReference:Le};var je=function(e){const t={},n=e.allAttributesPrivate,r=e.privateAttributes||[],o=["key","kind","_meta","anonymous"],i=["name","ip","firstName","lastName","email","avatar","country"],a=(e,t)=>{if("object"!=typeof e||null===e||Array.isArray(e))return;const{cloned:i,excluded:a}=Ue.cloneExcluding(e,((e,t)=>(n||t&&e.anonymous?Object.keys(e):[...r,...e._meta&&e._meta.privateAttributes||[]]).filter((e=>!o.some((t=>Ue.compare(e,t))))))(e,t));return i.key=String(i.key),a.length&&(i._meta||(i._meta={}),i._meta.redactedAttributes=a),i._meta&&(delete i._meta.privateAttributes,0===Object.keys(i._meta).length&&delete i._meta),void 0!==i.anonymous&&(i.anonymous=!!i.anonymous),i};return t.filter=(e,t=!1)=>void 0===e.kind||null===e.kind?a((e=>{const t={...e.custom||{},kind:"user",key:e.key};void 0!==e.anonymous&&(t.anonymous=!!e.anonymous);for(const n of i)delete t[n],void 0!==e[n]&&null!==e[n]&&(t[n]=String(e[n]));return void 0!==e.privateAttributeNames&&null!==e.privateAttributeNames&&(t._meta=t._meta||{},t._meta.privateAttributes=e.privateAttributeNames.map((e=>e.startsWith("/")?Ue.literalToReference(e):e))),t})(e),t):"multi"===e.kind?((e,t)=>{const n={kind:e.kind},r=Object.keys(e);for(const o of r)if("kind"!==o){const r=a(e[o],t);r&&(n[o]=r)}return n})(e,t):a(e,t),t};const{getContextKeys:Ae}=De;var Re=function(e,t,n,r=null,o=null,i=null){const a={},s=i||ye(e,n,t),u=I.appendUrlPath(t.eventsUrl,"/events/bulk/"+n),l=je(t),d=Pe(l),f=t.samplingInterval,g=t.eventCapacity,v=t.flushInterval,p=t.logger;let m,h=[],y=0,w=!1,b=!1;function k(){return 0===f||0===Math.floor(Math.random()*f)}function E(e){const t=I.extend({},e);return"identify"===e.kind||"feature"===e.kind||"custom"===e.kind?t.context=l.filter(e.context):(t.contextKeys=Ae(e.context,p),delete t.context),"feature"===e.kind&&(delete t.trackEvents,delete t.debugEventsUntilDate),t}function D(e){h.lengthy&&r.debugEventsUntilDate>(new Date).getTime()):t=k(),t&&D(E(e)),n){const t=I.extend({},e,{kind:"debug"});t.context=l.filter(t.context),delete t.trackEvents,delete t.debugEventsUntilDate,D(t)}},a.flush=async function(){if(w)return Promise.resolve();const e=h;return d.getSummaries().forEach((t=>{Object.keys(t.features).length&&e.push(t)})),r&&r.setEventsInLastBatch(e.length),0===e.length?Promise.resolve():(h=[],p.debug(ae.debugPostingEvents(e.length)),s.sendEvents(e,u).then((e=>{e&&(e.serverTime&&(y=e.serverTime),c.isHttpErrorRecoverable(e.status)||(w=!0),e.status>=400&&I.onNextTick((()=>{o.maybeReportError(new c.LDUnexpectedResponseError(ae.httpErrorMessage(e.status,"event posting","some events were dropped")))})))})))},a.start=function(){const e=()=>{a.flush(),m=setTimeout(e,v)};m=setTimeout(e,v)},a.stop=function(){clearTimeout(m)},a};var Fe=function(e){const t={},n={};return t.on=function(e,t,r){n[e]=n[e]||[],n[e]=n[e].concat({handler:t,context:r})},t.off=function(e,t,r){if(n[e])for(let o=0;o{const n=()=>{e.off(Ne,n),t()};e.on(Ne,n)})).catch((()=>{}));return{getInitializationPromise:()=>o||(t?Promise.resolve():n?Promise.reject(r):(o=new Promise(((t,n)=>{const r=()=>{e.off($e,r),t()},o=t=>{e.off(Ve,o),n(t)};e.on($e,r),e.on(Ve,o)})),o)),getReadyPromise:()=>i,signalSuccess:()=>{t||n||(t=!0,e.emit($e),e.emit(Ne))},signalFailure:o=>{t||n||(n=!0,r=o,e.emit(Ve,o),e.emit(Ne)),e.maybeReportError(o)}}};var Me=function(e,t,n,r){const o={};function i(){let e="";const o=r.getContext();return o&&(e=n||I.btoa(JSON.stringify(o))),"ld:"+t+":"+e}return o.loadFlags=()=>e.get(i()).then((e=>{if(null==e)return null;try{let t=JSON.parse(e);if(t){const e=t.$schema;void 0===e||e<1?t=I.transformValuesToVersionedValues(t):delete t.$schema}return t}catch(e){return o.clearFlags().then((()=>null))}})),o.saveFlags=t=>{const n=I.extend({},t,{$schema:1});return e.set(i(),JSON.stringify(n))},o.clearFlags=()=>e.clear(i()),o};var qe=function(e,t){const n={};let r=!1;const o=e=>{r||(r=!0,t.warn(ae.localStorageUnavailable(e)))};return n.isEnabled=()=>!!e,n.get=t=>new Promise((n=>{e?e.get(t).then(n).catch((e=>{o(e),n(void 0)})):n(void 0)})),n.set=(t,n)=>new Promise((r=>{e?e.set(t,n).then((()=>r(!0))).catch((e=>{o(e),r(!1)})):r(!1)})),n.clear=t=>new Promise((n=>{e?e.clear(t).then((()=>n(!0))).catch((e=>{o(e),n(!1)})):n(!1)})),n};const{appendUrlPath:ze,base64URLEncode:Ke,objectHasOwnProperty:_e}=I,{getLDHeaders:Je,transformHeaders:Be}=ve,{isHttpErrorRecoverable:Ge}=c;var We=function(e,t,n,r){const o=t.streamUrl,i=t.logger,a={},s=ze(o,"/eval/"+n),c=t.useReport,u=t.evaluationReasons,l=t.streamReconnectDelay,d=Je(e,t);let f,g=!1,v=null,p=null,m=null,h=null,y=null,w=0;function b(){const e=(t=function(){const e=l*Math.pow(2,w);return e>3e4?3e4:e}(),t-Math.trunc(.5*Math.random()*t));var t;return w+=1,e}function k(e){if(e.status&&"number"==typeof e.status&&!Ge(e.status))return x(),i.error(ae.unrecoverableStreamError(e)),void(p&&(clearTimeout(p),p=null));const t=b();g||(i.warn(ae.streamError(e,t)),g=!0),C(!1),x(),E(t)}function E(e){p||(e?p=setTimeout(D,e):D())}function D(){let r;p=null;let a="";const l={headers:d,readTimeoutMillis:3e5};if(e.eventSourceFactory){null!=h&&(a="h="+h),c?e.eventSourceAllowsReport?(r=s,l.method="REPORT",l.headers["Content-Type"]="application/json",l.body=JSON.stringify(m)):(r=ze(o,"/ping/"+n),a=""):r=s+"/"+Ke(JSON.stringify(m)),l.headers=Be(l.headers,t),u&&(a=a+(a?"&":"")+"withReasons=true"),r=r+(a?"?":"")+a,x(),i.info(ae.streamConnecting(r)),f=(new Date).getTime(),v=e.eventSourceFactory(r,l);for(const e in y)_e(y,e)&&v.addEventListener(e,y[e]);v.onerror=k,v.onopen=()=>{w=0}}}function x(){v&&(i.info(ae.streamClosing()),v.close(),v=null)}function C(e){f&&r&&r.recordStreamInit(f,!e,(new Date).getTime()-f),f=null}return a.connect=function(e,t,n){m=e,h=t,y={};for(const e in n||{})y[e]=function(t){g=!1,C(!0),n[e]&&n[e](t)};E()},a.disconnect=function(){clearTimeout(p),p=null,x()},a.isConnected=function(){return!!(v&&e.eventSourceIsActive&&e.eventSourceIsActive(v))},a};var Xe=function(e){let t,n,r,o;const i={addPromise:(i,a)=>{t=i,n&&n(),n=a,i.then((n=>{t===i&&(r(n),e&&e())}),(n=>{t===i&&(o(n),e&&e())}))}};return i.resultPromise=new Promise(((e,t)=>{r=e,o=t})),i};const{transformHeaders:Qe,getLDHeaders:Ye}=ve,Ze="application/json";var et=function(e,t,n){const r=t.baseUrl,o=t.useReport,i=t.evaluationReasons,a=t.logger,s={},u={};function l(n,r){if(!e.httpRequest)return new Promise(((e,t)=>{t(new c.LDFlagFetchError(ae.httpUnavailable()))}));const o=r?"REPORT":"GET",i=Ye(e,t);r&&(i["Content-Type"]=Ze);let a=u[n];a||(a=Xe((()=>{delete u[n]})),u[n]=a);const s=e.httpRequest(o,n,Qe(i,t),r),l=s.promise.then((e=>{if(200===e.status){if(e.header("content-type")&&e.header("content-type").substring(0,16)===Ze)return JSON.parse(e.body);{const t=ae.invalidContentType(e.header("content-type")||"");return Promise.reject(new c.LDFlagFetchError(t))}}return Promise.reject(function(e){return 404===e.status?new c.LDInvalidEnvironmentIdError(ae.environmentNotFound()):new c.LDFlagFetchError(ae.errorFetchingFlags(e.statusText||String(e.status)))}(e))}),(e=>Promise.reject(new c.LDFlagFetchError(ae.networkError(e)))));return a.addPromise(l,(()=>{s.cancel&&s.cancel()})),a.resultPromise}return s.fetchJSON=function(e){return l(I.appendUrlPath(r,e),null)},s.fetchFlagSettings=function(e,t){let s,c,u,d="";return o?(c=[r,"/sdk/evalx/",n,"/context"].join(""),u=JSON.stringify(e)):(s=I.base64URLEncode(JSON.stringify(e)),c=[r,"/sdk/evalx/",n,"/contexts/",s].join("")),t&&(d="h="+t),i&&(d=d+(d?"&":"")+"withReasons=true"),c=c+(d?"?":"")+d,a.debug(ae.debugPolling(c)),l(c,u)},s};var tt=function(e,t){const n={};let r;return n.setContext=function(e){r=I.sanitizeContext(e),r&&t&&t(I.clone(r))},n.getContext=function(){return r?I.clone(r):null},e&&n.setContext(e),n};const{v1:nt}=te,{getContextKinds:rt}=De;var ot=function(e){function t(e){return null==e||"user"===e?"ld:$anonUserId":`ld:$contextKey:${e}`}function n(n,r){return null!==r.key&&void 0!==r.key?(r.key=r.key.toString(),Promise.resolve(r)):r.anonymous?function(n){return e.get(t(n))}(n).then((o=>{if(o)return r.key=o,r;{const o=nt();return r.key=o,function(n,r){return e.set(t(r),n)}(o,n).then((()=>r))}})):Promise.reject(new c.LDInvalidUserError(ae.invalidContext()))}this.processContext=e=>{if(!e)return Promise.reject(new c.LDInvalidUserError(ae.contextNotSpecified()));const t=I.clone(e);if("multi"===e.kind){const e=rt(t);return Promise.all(e.map((e=>n(e,t[e])))).then((()=>t))}return n(e.kind,t)}};const{v1:it}=te,{baseOptionDefs:at}=fe,{appendUrlPath:st}=I;var ct={DiagnosticId:function(e){const t={diagnosticId:it()};return e&&(t.sdkKeySuffix=e.length>6?e.substring(e.length-6):e),t},DiagnosticsAccumulator:function(e){let t,n,r,o;function i(e){t=e,n=0,r=0,o=[]}return i(e),{getProps:()=>({dataSinceDate:t,droppedEvents:n,eventsInLastBatch:r,streamInits:o}),setProps:e=>{t=e.dataSinceDate,n=e.droppedEvents||0,r=e.eventsInLastBatch||0,o=e.streamInits||[]},incrementDroppedEvents:()=>{n++},setEventsInLastBatch:e=>{r=e},recordStreamInit:(e,t,n)=>{const r={timestamp:e,failed:t,durationMillis:n};o.push(r)},reset:i}},DiagnosticsManager:function(e,t,n,r,o,i,a){const s=!!e.diagnosticUseCombinedEvent,c="ld:"+o+":$diagnostics",u=st(i.eventsUrl,"/events/diagnostic/"+o),l=i.diagnosticRecordingInterval,d=n;let f,g,v=!!i.streaming;const p={};function m(){return{sdk:w(),configuration:b(),platform:e.diagnosticPlatformData}}function h(e){i.logger&&i.logger.debug(ae.debugPostingDiagnosticEvent(e)),r.sendEvents(e,u,!0).then((()=>{})).catch((()=>{}))}function y(){h(function(){const e=(new Date).getTime();let t={kind:s?"diagnostic-combined":"diagnostic",id:a,creationDate:e,...d.getProps()};return s&&(t={...t,...m()}),d.reset(e),t}()),g=setTimeout(y,l),f=(new Date).getTime(),s&&function(){if(t.isEnabled()){const e={...d.getProps()};t.set(c,JSON.stringify(e))}}()}function w(){const t={...e.diagnosticSdkData};return i.wrapperName&&(t.wrapperName=i.wrapperName),i.wrapperVersion&&(t.wrapperVersion=i.wrapperVersion),t}function b(){return{customBaseURI:i.baseUrl!==at.baseUrl.default,customStreamURI:i.streamUrl!==at.streamUrl.default,customEventsURI:i.eventsUrl!==at.eventsUrl.default,eventsCapacity:i.eventCapacity,eventsFlushIntervalMillis:i.flushInterval,reconnectTimeMillis:i.streamReconnectDelay,streamingDisabled:!v,allAttributesPrivate:!!i.allAttributesPrivate,diagnosticRecordingIntervalMillis:i.diagnosticRecordingInterval,usingSecureMode:!!i.hash,bootstrapMode:!!i.bootstrap,fetchGoalsDisabled:!i.fetchGoals,sendEventsOnlyForVariation:!!i.sendEventsOnlyForVariation}}return p.start=()=>{s?function(e){if(!t.isEnabled())return e(!1);t.get(c).then((t=>{if(t)try{const e=JSON.parse(t);d.setProps(e),f=e.dataSinceDate}catch(e){}e(!0)})).catch((()=>{e(!1)}))}((e=>{if(e){const e=(f||0)+l,t=(new Date).getTime();t>=e?y():g=setTimeout(y,e-t)}else 0===Math.floor(4*Math.random())?y():g=setTimeout(y,l)})):(h({kind:"diagnostic-init",id:a,creationDate:d.getProps().dataSinceDate,...m()}),g=setTimeout(y,l))},p.stop=()=>{g&&clearTimeout(g)},p.setStreaming=e=>{v=e},p}};var ut=function(e,t){let n=!1;const r={type:e.type,name:e.name,synchronous:e.synchronous,method:(...o)=>{try{e.method(...o)}catch{n||(n=!0,t.warn(ae.inspectorMethodError(r.type,r.name)))}}};return r};const{onNextTick:lt}=I,dt={flagUsed:"flag-used",flagDetailsChanged:"flag-details-changed",flagDetailChanged:"flag-detail-changed",clientIdentityChanged:"client-identity-changed"};Object.freeze(dt);var ft={InspectorTypes:dt,InspectorManager:function(e,t){const n={},r={[dt.flagUsed]:[],[dt.flagDetailsChanged]:[],[dt.flagDetailChanged]:[],[dt.clientIdentityChanged]:[]},o={[dt.flagUsed]:[],[dt.flagDetailsChanged]:[],[dt.flagDetailChanged]:[],[dt.clientIdentityChanged]:[]},i=e&&e.map((e=>ut(e,t)));return i&&i.forEach((e=>{Object.prototype.hasOwnProperty.call(r,e.type)&&!e.synchronous?r[e.type].push(e):Object.prototype.hasOwnProperty.call(o,e.type)&&e.synchronous?o[e.type].push(e):t.warn(ae.invalidInspector(e.type,e.name))})),n.hasListeners=e=>r[e]&&r[e].length||o[e]&&o[e].length,n.onFlagUsed=(e,t,n)=>{const i=dt.flagUsed;o[i].length&&o[i].forEach((r=>r.method(e,t,n))),r[i].length&<((()=>{r[i].forEach((r=>r.method(e,t,n)))}))},n.onFlags=e=>{const t=dt.flagDetailsChanged;o[t].length&&o[t].forEach((t=>t.method(e))),r[t].length&<((()=>{r[t].forEach((t=>t.method(e)))}))},n.onFlagChanged=(e,t)=>{const n=dt.flagDetailChanged;o[n].length&&o[n].forEach((n=>n.method(e,t))),r[n].length&<((()=>{r[n].forEach((n=>n.method(e,t)))}))},n.onIdentityChanged=e=>{const t=dt.clientIdentityChanged;o[t].length&&o[t].forEach((t=>t.method(e))),r[t].length&<((()=>{r[t].forEach((t=>t.method(e)))}))},n}};const{LDTimeoutError:gt}=c;var vt=function(e,t){return new Promise(((n,r)=>{setTimeout((()=>{r(new gt(`${t} timed out after ${e} seconds.`))}),1e3*e)}))};const pt="unknown hook";function mt(e,t,n,r,o){try{return r()}catch(r){return e?.error(`An error was encountered in "${t}" of the "${n}" hook: ${r}`),o}}function ht(e,t){try{return t.getMetadata().name||pt}catch{return e.error("Exception thrown getting metadata for hook. Unable to get hook name."),pt}}var yt=function(e,t){const n=t?[...t]:[];return{withEvaluation:function(t,r,o,i){if(0===n.length)return i();const a=[...n],s={flagKey:t,context:r,defaultValue:o},c=function(e,t,n){return t.map((t=>mt(e,"beforeEvaluation",ht(e,t),(()=>t?.beforeEvaluation?.(n,{})??{}),{})))}(e,a,s),u=i();return function(e,t,n,r,o){for(let i=t.length-1;i>=0;i-=1){const a=t[i],s=r[i];mt(e,"afterEvaluation",ht(e,a),(()=>a?.afterEvaluation?.(n,s,o)??{}),{})}}(e,a,s,c,u),u},identify:function(t,r){const o=[...n],i={context:t,timeout:r},a=function(e,t,n){return t.map((t=>mt(e,"beforeIdentify",ht(e,t),(()=>t?.beforeIdentify?.(n,{})??{}),{})))}(e,o,i);return t=>{!function(e,t,n,r,o){for(let i=t.length-1;i>=0;i-=1){const a=t[i],s=r[i];mt(e,"afterIdentify",ht(e,a),(()=>a?.afterIdentify?.(n,s,o)??{}),{})}}(e,o,i,a,t)}},addHook:function(e){n.push(e)},afterTrack:function(t){if(0===n.length)return;const r=[...n];!function(e,t,n){for(let r=t.length-1;r>=0;r-=1){const o=t[r];mt(e,"afterTrack",ht(e,o),(()=>o?.afterTrack?.(n)),void 0)}}(e,r,t)}}};const wt="unknown plugin";function bt(e,t){try{return t.getMetadata().name||wt}catch(t){return e.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),wt}}var kt={getPluginHooks:function(e,t,n){const r=[];return n.forEach((n=>{try{const o=n.getHooks?.(t);void 0===o?e.error(`Plugin ${bt(e,n)} returned undefined from getHooks.`):o&&o.length>0&&r.push(...o)}catch(t){e.error(`Exception thrown getting hooks for plugin ${bt(e,n)}. Unable to get hooks.`)}})),r},registerPlugins:function(e,t,n,r){r.forEach((r=>{try{r.register(n,t)}catch(t){e.error(`Exception thrown registering plugin ${bt(e,r)}.`)}}))},createPluginEnvironment:function(e,t,n){const r={};e.userAgent&&(r.name=e.userAgent),e.version&&(r.version=e.version),n.wrapperName&&(r.wrapperName=n.wrapperName),n.wrapperVersion&&(r.wrapperVersion=n.wrapperVersion);const o={};n.application&&(n.application.name&&(o.name=n.application.name),n.application.version&&(o.version=n.application.version));const i={sdk:r,clientSideId:t};return Object.keys(o).length>0&&(i.application=o),i}};const{commonBasicLogger:Et}=re,{checkContext:Dt,getContextKeys:xt}=De,{InspectorTypes:Ct,InspectorManager:Pt}=ft,{getPluginHooks:St,registerPlugins:It,createPluginEnvironment:Ot}=kt,Tt="change",Lt="internal-change";var Ut={initialize:function(e,t,n,r,o){const i=function(){if(n&&n.logger)return n.logger;return o&&o.logger&&o.logger.default||Et("warn")}(),a=Fe(i),s=He(a),u=fe.validate(n,a,o,i),l=Pt(u.inspectors,i),d=u.sendEvents;let f=e,g=u.hash;const v=[...u.plugins],p=Ot(r,e,u),m=St(i,p,v),h=yt(i,[...u.hooks,...m]),y=qe(r.localStorage,i),w=ye(r,f,u),b=u.sendEvents&&!u.diagnosticOptOut,k=b?ct.DiagnosticId(f):null,E=b?ct.DiagnosticsAccumulator((new Date).getTime()):null,D=b?ct.DiagnosticsManager(r,y,E,w,f,u,k):null,x=We(r,u,f,E),C=u.eventProcessor||Re(r,u,f,E,a,w),P=et(r,u,f);let S,O,T,L={},U=u.streaming,j=!1,A=!1,R=!0;const F=u.stateProvider,N=tt(null,(function(e){(function(e){if(F)return;e&&H({kind:"identify",context:e,creationDate:(new Date).getTime()})})(e),l.hasListeners(Ct.clientIdentityChanged)&&l.onIdentityChanged(N.getContext())})),$=new ot(y),V=y.isEnabled()?Me(y,f,g,N):null;function H(e){f&&(F&&F.enqueueEvent&&F.enqueueEvent(e)||(e.context?(R=!1,!d||A||r.isDoNotTrack()||(i.debug(ae.debugEnqueueingEvent(e.kind)),C.enqueue(e))):R&&(i.warn(ae.eventWithoutContext()),R=!1)))}function M(e,t){l.hasListeners(Ct.flagDetailChanged)&&l.onFlagChanged(e.key,J(t))}function q(){l.hasListeners(Ct.flagDetailsChanged)&&l.onFlags(Object.entries(L).map((([e,t])=>({key:e,detail:J(t)}))).reduce(((e,t)=>(e[t.key]=t.detail,e)),{}))}function z(e,t,n,r){const o=N.getContext(),i=new Date,a={kind:"feature",key:e,context:o,value:t?t.value:null,variation:t?t.variationIndex:null,default:n,creationDate:i.getTime()},s=L[e];s&&(a.version=s.flagVersion?s.flagVersion:s.version,a.trackEvents=s.trackEvents,a.debugEventsUntilDate=s.debugEventsUntilDate),(r||s&&s.trackReason)&&t&&(a.reason=t.reason),H(a)}function K(e){return Dt(e,!1)?Promise.resolve(e):Promise.reject(new c.LDInvalidUserError(ae.invalidContext()))}function _(e,t,n,r,o,i){let a,s;return L&&I.objectHasOwnProperty(L,e)&&L[e]&&!L[e].deleted?(s=L[e],a=J(s),null!==s.value&&void 0!==s.value||(a.value=t)):a={value:t,variationIndex:null,reason:{kind:"ERROR",errorKind:"FLAG_NOT_FOUND"}},n&&(o||s?.prerequisites?.forEach((e=>{_(e,void 0,n,!1,!1,!1)})),z(e,a,t,r)),!o&&i&&function(e,t){l.hasListeners(Ct.flagUsed)&&l.onFlagUsed(e,t,N.getContext())}(e,a),a}function J(e){return{value:e.value,variationIndex:void 0===e.variation?null:e.variation,reason:e.reason||null}}function B(){if(O=!0,!N.getContext())return;const e=e=>{try{return JSON.parse(e)}catch(e){return void a.maybeReportError(new c.LDInvalidDataError(ae.invalidData()))}};x.connect(N.getContext(),g,{ping:function(){i.debug(ae.debugStreamPing());const e=N.getContext();P.fetchFlagSettings(e,g).then((t=>{I.deepEquals(e,N.getContext())&&W(t||{})})).catch((e=>{a.maybeReportError(new c.LDFlagFetchError(ae.errorFetchingFlags(e)))}))},put:function(t){const n=e(t.data);n&&(i.debug(ae.debugStreamPut()),W(n))},patch:function(t){const n=e(t.data);if(!n)return;const r=L[n.key];if(!r||!r.version||!n.version||r.version{}))}function X(e){const t=Object.keys(e);if(t.length>0){const n={};t.forEach((t=>{const r=e[t].current,o=r?r.value:void 0,i=e[t].previous;a.emit(Tt+":"+t,o,i),n[t]=r?{current:o,previous:i}:{previous:i}})),a.emit(Tt,n),a.emit(Lt,L),u.sendEventsOnlyForVariation||F||t.forEach((t=>{z(t,e[t].current)}))}return S&&V?V.saveFlags(L):Promise.resolve()}function Q(){const e=U||T&&void 0===U;e&&!O?B():!e&&O&&G(),D&&D.setStreaming(e)}function Y(e){return e===Tt||e.substr(0,7)===Tt+":"}if("string"==typeof u.bootstrap&&"LOCALSTORAGE"===u.bootstrap.toUpperCase()&&(V?S=!0:i.warn(ae.localStorageUnavailable())),"object"==typeof u.bootstrap&&(L=function(e){const t=Object.keys(e),n="$flagsState",r="$valid",o=e[n];!o&&t.length&&i.warn(ae.bootstrapOldFormat()),!1===e[r]&&i.warn(ae.bootstrapInvalid());const a={};return t.forEach((t=>{if(t!==n&&t!==r){let n={value:e[t]};o&&o[t]?n=I.extend(n,o[t]):n.version=0,a[t]=n}})),a}(u.bootstrap)),F){const e=F.getInitialState();e?Z(e):F.on("init",Z),F.on("update",(function(e){e.context&&N.setContext(e.context);e.flags&&W(e.flags)}))}else(function(){if(!e)return Promise.reject(new c.LDInvalidEnvironmentIdError(ae.environmentNotSpecified()));let n;return $.processContext(t).then(K).then((e=>(n=I.once(h.identify(e,void 0)),e))).then((e=>(n?.({status:"completed"}),N.setContext(e),"object"==typeof u.bootstrap?ee():S?V.loadFlags().then((e=>null==e?(L={},P.fetchFlagSettings(N.getContext(),g).then((e=>W(e||{}))).then(ee).catch((e=>{te(new c.LDFlagFetchError(ae.errorFetchingFlags(e)))}))):(L=e,I.onNextTick(ee),P.fetchFlagSettings(N.getContext(),g).then((e=>W(e))).catch((e=>a.maybeReportError(e)))))):P.fetchFlagSettings(N.getContext(),g).then((e=>{L=e||{},q(),ee()})).catch((e=>{L={},te(e)}))))).catch((e=>{throw n?.({status:"error"}),e}))})().catch(te);function Z(e){f=e.environment,N.setContext(e.context),L={...e.flags},I.onNextTick(ee)}function ee(){i.info(ae.clientInitialized()),j=!0,Q(),s.signalSuccess()}function te(e){s.signalFailure(e)}const ne={waitForInitialization:function(e=void 0){if(null!=e){if("number"==typeof e)return function(e){e>5&&i.warn("The waitForInitialization function was called with a timeout greater than 5 seconds. We recommend a timeout of 5 seconds or less.");const t=s.getInitializationPromise(),n=vt(e,"waitForInitialization");return Promise.race([n,t]).catch((e=>{throw e instanceof c.LDTimeoutError&&i.error(`waitForInitialization error: ${e}`),e}))}(e);i.warn("The waitForInitialization method was provided with a non-numeric timeout.")}return i.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied."),s.getInitializationPromise()},waitUntilReady:()=>s.getReadyPromise(),identify:function(e,t,n){if(A)return I.wrapPromiseCallback(Promise.resolve({}),n);if(F)return i.warn(ae.identifyDisabled()),I.wrapPromiseCallback(Promise.resolve(I.transformVersionedValuesToValues(L)),n);let r;const o=S&&V?V.clearFlags():Promise.resolve();return I.wrapPromiseCallback(o.then((()=>$.processContext(e))).then(K).then((e=>(r=I.once(h.identify(e,void 0)),e))).then((e=>P.fetchFlagSettings(e,t).then((n=>{const r=I.transformVersionedValuesToValues(n);return N.setContext(e),g=t,n?W(n).then((()=>r)):r})))).then((e=>(r?.({status:"completed"}),O&&B(),e))).catch((e=>(r?.({status:"error"}),a.maybeReportError(e),Promise.reject(e)))),n)},getContext:function(){return N.getContext()},variation:function(e,t){const{value:n}=h.withEvaluation(e,N.getContext(),t,(()=>_(e,t,!0,!1,!1,!0)));return n},variationDetail:function(e,t){return h.withEvaluation(e,N.getContext(),t,(()=>_(e,t,!0,!0,!1,!0)))},track:function(e,t,n){if("string"!=typeof e)return void a.maybeReportError(new c.LDInvalidEventKeyError(ae.unknownCustomEventKey(e)));void 0!==n&&"number"!=typeof n&&i.warn(ae.invalidMetricValue(typeof n)),r.customEventFilter&&!r.customEventFilter(e)&&i.warn(ae.unknownCustomEventKey(e));const o=N.getContext(),s={kind:"custom",key:e,context:o,url:r.getCurrentUrl(),creationDate:(new Date).getTime()};o&&o.anonymous&&(s.contextKind=o.anonymous?"anonymousUser":"user"),null!=t&&(s.data=t),null!=n&&(s.metricValue=n),H(s),h.afterTrack({context:o,key:e,data:t,metricValue:n})},on:function(e,t,n){Y(e)?(T=!0,j&&Q(),a.on(e,t,n)):a.on(...arguments)},off:function(e){if(a.off(...arguments),Y(e)){let e=!1;a.getEvents().forEach((t=>{Y(t)&&a.getEventListenerCount(t)>0&&(e=!0)})),e||(T=!1,O&&void 0===U&&G())}},setStreaming:function(e){const t=null===e?void 0:e;t!==U&&(U=t,Q())},flush:function(e){return I.wrapPromiseCallback(d?C.flush():Promise.resolve(),e)},allFlags:function(){const e={};if(!L)return e;for(const t in L)I.objectHasOwnProperty(L,t)&&!L[t].deleted&&(e[t]=_(t,null,!u.sendEventsOnlyForVariation,!1,!0,!1).value);return e},close:function(e){if(A)return I.wrapPromiseCallback(Promise.resolve(),e);const t=()=>{A=!0,L={}},n=Promise.resolve().then((()=>{if(G(),D&&D.stop(),d)return C.stop(),C.flush()})).then(t).catch(t);return I.wrapPromiseCallback(n,e)},addHook:function(e){h.addHook(e)}};return It(i,p,ne,v),{client:ne,options:u,emitter:a,ident:N,logger:i,requestor:P,start:function(){d&&(D&&D.start(),C.start())},enqueueEvent:H,getFlagsInternal:function(){return L},getEnvironmentId:()=>f,internalChangeEventName:Lt}},commonBasicLogger:Et,errors:c,messages:ae,utils:I,getContextKeys:xt},jt=Ut.initialize,At=Ut.errors,Rt=Ut.messages;function Ft(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Nt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function $t(e){for(var t=1;t{if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")};function Kt(e,t,n,r){var o,i,a=(("substring"===e.kind||"regex"===e.kind)&&r.includes("/")?t:t.replace(r,"")).replace(n,"");switch(e.kind){case"exact":i=t,o=new RegExp("^"+zt(e.url)+"/?$");break;case"canonical":i=a,o=new RegExp("^"+zt(e.url)+"/?$");break;case"substring":i=a,o=new RegExp(".*"+zt(e.substring)+".*$");break;case"regex":i=a,o=new RegExp(e.pattern);break;default:return!1}return o.test(i)}function _t(e,t){for(var n={},r=null,o=[],i=0;i0&&(r=function(e){for(var n=function(e,t){for(var n=[],r=0;r0;){for(var c=0;c0&&(r=_t(n=e,i),function(e,t){var n,r=window.location.href;function o(){(n=window.location.href)!==r&&(r=n,t())}!function e(t,n){t(),setTimeout((function(){e(t,n)}),n)}(o,e),window.history&&window.history.pushState?window.addEventListener("popstate",o):window.addEventListener("hashchange",o)}(300,o)),t()})).catch((function(n){e.emitter.maybeReportError(new At.LDUnexpectedResponseError((n&&n.message,n.message))),t()})),{}}var Bt="goalsReady",Gt={fetchGoals:{default:!0},hash:{type:"string"},eventProcessor:{type:"object"},eventUrlTransformer:{type:"function"},disableSyncEventPost:{default:!1}};function Wt(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=function(e){var t,n={userAgentHeaderName:"X-LaunchDarkly-User-Agent",synchronousFlush:!1};if(window.XMLHttpRequest){var r=e&&e.disableSyncEventPost;n.httpRequest=function(e,t,o,i){var a=n.synchronousFlush&!r;return n.synchronousFlush=!1,qt(e,t,o,i,a)}}n.httpAllowsPost=function(){return void 0===t&&(t=!!window.XMLHttpRequest&&"withCredentials"in new window.XMLHttpRequest),t},n.httpFallbackPing=function(e){(new window.Image).src=e};var o,i=e&&e.eventUrlTransformer;n.getCurrentUrl=function(){return i?i(window.location.href):window.location.href},n.isDoNotTrack=function(){var e;return 1===(e=window.navigator&&void 0!==window.navigator.doNotTrack?window.navigator.doNotTrack:window.navigator&&void 0!==window.navigator.msDoNotTrack?window.navigator.msDoNotTrack:window.doNotTrack)||!0===e||"1"===e||"yes"===e};try{window.localStorage&&(n.localStorage={get:function(e){return new Promise((function(t){t(window.localStorage.getItem(e))}))},set:function(e,t){return new Promise((function(n){window.localStorage.setItem(e,t),n()}))},clear:function(e){return new Promise((function(t){window.localStorage.removeItem(e),t()}))}})}catch(e){n.localStorage=null}if(e&&e.useReport&&"function"==typeof window.EventSourcePolyfill&&window.EventSourcePolyfill.supportedOptions&&window.EventSourcePolyfill.supportedOptions.method?(n.eventSourceAllowsReport=!0,o=window.EventSourcePolyfill):(n.eventSourceAllowsReport=!1,o=window.EventSource),window.EventSource){var a=3e5;n.eventSourceFactory=function(e,t){var n=$t($t({},{heartbeatTimeout:a,silentTimeout:a,skipDefaultHeaders:!0}),t);return new o(e,n)},n.eventSourceIsActive=function(e){return e.readyState===window.EventSource.OPEN||e.readyState===window.EventSource.CONNECTING}}return n.userAgent="JSClient",n.version="3.8.1",n.diagnosticSdkData={name:"js-client-sdk",version:"3.8.1"},n.diagnosticPlatformData={name:"JS"},n.diagnosticUseCombinedEvent=!0,n}(n),o=jt(e,t,n,r,Gt),i=o.client,a=o.options,s=o.emitter,c=new Promise((function(e){var t=s.on(Bt,(function(){s.off(Bt,t),e()}))}));i.waitUntilGoalsReady=function(){return c},a.fetchGoals?Jt(o,(function(){return s.emit(Bt)})):s.emit(Bt),"complete"!==document.readyState?window.addEventListener("load",o.start):o.start();var u=function(){r.synchronousFlush=!0,i.flush().catch((function(){})),r.synchronousFlush=!1};return document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&u()})),window.addEventListener("pagehide",u),i}var Xt=Ht,Qt="3.8.1";var Yt={initialize:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return console&&console.warn&&console.warn(Rt.deprecated("default export","named LDClient export")),Wt(e,t,n)},version:Qt};e.basicLogger=Xt,e.createConsoleLogger=undefined,e.default=Yt,e.initialize=Wt,e.version=Qt,Object.defineProperty(e,"__esModule",{value:!0})})); +//# sourceMappingURL=ldclient.min.js.map diff --git a/node_modules/launchdarkly-js-client-sdk/dist/ldclient.min.js.map b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.min.js.map new file mode 100644 index 00000000..3da5b37c --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/dist/ldclient.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ldclient.min.js","sources":["../node_modules/launchdarkly-js-sdk-common/src/errors.js","../node_modules/base64-js/index.js","../node_modules/launchdarkly-js-sdk-common/node_modules/fast-deep-equal/index.js","../node_modules/launchdarkly-js-sdk-common/src/utils.js","../node_modules/uuid/dist/esm-browser/rng.js","../node_modules/uuid/dist/esm-browser/regex.js","../node_modules/uuid/dist/esm-browser/validate.js","../node_modules/uuid/dist/esm-browser/stringify.js","../node_modules/uuid/dist/esm-browser/v1.js","../node_modules/uuid/dist/esm-browser/parse.js","../node_modules/uuid/dist/esm-browser/v35.js","../node_modules/uuid/dist/esm-browser/md5.js","../node_modules/uuid/dist/esm-browser/v3.js","../node_modules/uuid/dist/esm-browser/sha1.js","../node_modules/uuid/dist/esm-browser/v5.js","../node_modules/uuid/dist/esm-browser/v4.js","../node_modules/uuid/dist/esm-browser/nil.js","../node_modules/uuid/dist/esm-browser/version.js","../node_modules/launchdarkly-js-sdk-common/src/loggers.js","../node_modules/launchdarkly-js-sdk-common/src/messages.js","../node_modules/launchdarkly-js-sdk-common/src/configuration.js","../node_modules/launchdarkly-js-sdk-common/src/headers.js","../node_modules/launchdarkly-js-sdk-common/src/EventSender.js","../node_modules/launchdarkly-js-sdk-common/src/canonicalize.js","../node_modules/launchdarkly-js-sdk-common/src/context.js","../node_modules/launchdarkly-js-sdk-common/src/EventSummarizer.js","../node_modules/launchdarkly-js-sdk-common/src/MultiEventSummarizer.js","../node_modules/launchdarkly-js-sdk-common/src/attributeReference.js","../node_modules/launchdarkly-js-sdk-common/src/ContextFilter.js","../node_modules/launchdarkly-js-sdk-common/src/EventProcessor.js","../node_modules/launchdarkly-js-sdk-common/src/EventEmitter.js","../node_modules/launchdarkly-js-sdk-common/src/InitializationState.js","../node_modules/launchdarkly-js-sdk-common/src/PersistentFlagStore.js","../node_modules/launchdarkly-js-sdk-common/src/PersistentStorage.js","../node_modules/launchdarkly-js-sdk-common/src/Stream.js","../node_modules/launchdarkly-js-sdk-common/src/promiseCoalescer.js","../node_modules/launchdarkly-js-sdk-common/src/Requestor.js","../node_modules/launchdarkly-js-sdk-common/src/Identity.js","../node_modules/launchdarkly-js-sdk-common/src/AnonymousContextProcessor.js","../node_modules/launchdarkly-js-sdk-common/src/diagnosticEvents.js","../node_modules/launchdarkly-js-sdk-common/src/SafeInspector.js","../node_modules/launchdarkly-js-sdk-common/src/InspectorManager.js","../node_modules/launchdarkly-js-sdk-common/src/timedPromise.js","../node_modules/launchdarkly-js-sdk-common/src/HookRunner.js","../node_modules/launchdarkly-js-sdk-common/src/plugins.js","../node_modules/launchdarkly-js-sdk-common/src/index.js","../src/basicLogger.js","../src/httpRequest.js","../node_modules/escape-string-regexp/index.js","../src/GoalTracker.js","../src/GoalManager.js","../src/index.js","../src/browserPlatform.js"],"sourcesContent":["function createCustomError(name) {\n function CustomError(message, code) {\n Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);\n this.message = message;\n this.code = code;\n }\n\n CustomError.prototype = new Error();\n CustomError.prototype.name = name;\n CustomError.prototype.constructor = CustomError;\n\n return CustomError;\n}\n\nconst LDUnexpectedResponseError = createCustomError('LaunchDarklyUnexpectedResponseError');\nconst LDInvalidEnvironmentIdError = createCustomError('LaunchDarklyInvalidEnvironmentIdError');\nconst LDInvalidUserError = createCustomError('LaunchDarklyInvalidUserError');\nconst LDInvalidEventKeyError = createCustomError('LaunchDarklyInvalidEventKeyError');\nconst LDInvalidArgumentError = createCustomError('LaunchDarklyInvalidArgumentError');\nconst LDFlagFetchError = createCustomError('LaunchDarklyFlagFetchError');\nconst LDInvalidDataError = createCustomError('LaunchDarklyInvalidDataError');\nconst LDTimeoutError = createCustomError('LaunchDarklyTimeoutError');\n\nfunction isHttpErrorRecoverable(status) {\n if (status >= 400 && status < 500) {\n return status === 400 || status === 408 || status === 429;\n }\n return true;\n}\n\nmodule.exports = {\n LDUnexpectedResponseError,\n LDInvalidEnvironmentIdError,\n LDInvalidUserError,\n LDInvalidEventKeyError,\n LDInvalidArgumentError,\n LDInvalidDataError,\n LDFlagFetchError,\n LDTimeoutError,\n isHttpErrorRecoverable,\n};\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","'use strict';\n\nvar isArray = Array.isArray;\nvar keyList = Object.keys;\nvar hasProp = Object.prototype.hasOwnProperty;\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n var arrA = isArray(a)\n , arrB = isArray(b)\n , i\n , length\n , key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var dateA = a instanceof Date\n , dateB = b instanceof Date;\n if (dateA != dateB) return false;\n if (dateA && dateB) return a.getTime() == b.getTime();\n\n var regexpA = a instanceof RegExp\n , regexpB = b instanceof RegExp;\n if (regexpA != regexpB) return false;\n if (regexpA && regexpB) return a.toString() == b.toString();\n\n var keys = keyList(a);\n length = keys.length;\n\n if (length !== keyList(b).length)\n return false;\n\n for (i = length; i-- !== 0;)\n if (!hasProp.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n key = keys[i];\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n return a!==a && b!==b;\n};\n","const base64 = require('base64-js');\nconst fastDeepEqual = require('fast-deep-equal');\n\nconst userAttrsToStringify = ['key', 'ip', 'country', 'email', 'firstName', 'lastName', 'avatar', 'name'];\n\nfunction appendUrlPath(baseUrl, path) {\n // Ensure that URL concatenation is done correctly regardless of whether the\n // base URL has a trailing slash or not.\n const trimBaseUrl = baseUrl.endsWith('/') ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl;\n return trimBaseUrl + (path.startsWith('/') ? '' : '/') + path;\n}\n\n// See http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html\nfunction btoa(s) {\n const escaped = unescape(encodeURIComponent(s));\n return base64.fromByteArray(stringToBytes(escaped));\n}\n\nfunction stringToBytes(s) {\n const b = [];\n for (let i = 0; i < s.length; i++) {\n b.push(s.charCodeAt(i));\n }\n return b;\n}\n\nfunction base64URLEncode(s) {\n return (\n btoa(s)\n // eslint-disable-next-line\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n );\n}\n\nfunction clone(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n\nfunction deepEquals(a, b) {\n return fastDeepEqual(a, b);\n}\n\n// Events emitted in LDClient's initialize method will happen before the consumer\n// can register a listener, so defer them to next tick.\nfunction onNextTick(cb) {\n setTimeout(cb, 0);\n}\n\n/**\n * Wrap a promise to invoke an optional callback upon resolution or rejection.\n *\n * This function assumes the callback follows the Node.js callback type: (err, value) => void\n *\n * If a callback is provided:\n * - if the promise is resolved, invoke the callback with (null, value)\n * - if the promise is rejected, invoke the callback with (error, null)\n *\n * @param {Promise} promise\n * @param {Function} callback\n * @returns Promise | undefined\n */\nfunction wrapPromiseCallback(promise, callback) {\n const ret = promise.then(\n value => {\n if (callback) {\n setTimeout(() => {\n callback(null, value);\n }, 0);\n }\n return value;\n },\n error => {\n if (callback) {\n setTimeout(() => {\n callback(error, null);\n }, 0);\n } else {\n return Promise.reject(error);\n }\n }\n );\n\n return !callback ? ret : undefined;\n}\n\n/**\n * Takes a map of flag keys to values, and returns the more verbose structure used by the\n * client stream.\n */\nfunction transformValuesToVersionedValues(flags) {\n const ret = {};\n for (const key in flags) {\n if (objectHasOwnProperty(flags, key)) {\n ret[key] = { value: flags[key], version: 0 };\n }\n }\n return ret;\n}\n\n/**\n * Converts the internal flag state map to a simple map of flag keys to values.\n */\nfunction transformVersionedValuesToValues(flagsState) {\n const ret = {};\n for (const key in flagsState) {\n if (objectHasOwnProperty(flagsState, key)) {\n ret[key] = flagsState[key].value;\n }\n }\n return ret;\n}\n\nfunction getLDUserAgentString(platform) {\n const version = platform.version || '?';\n return platform.userAgent + '/' + version;\n}\n\nfunction extend(...objects) {\n return objects.reduce((acc, obj) => ({ ...acc, ...obj }), {});\n}\n\nfunction objectHasOwnProperty(object, name) {\n return Object.prototype.hasOwnProperty.call(object, name);\n}\n\nfunction sanitizeContext(context) {\n if (!context) {\n return context;\n }\n let newContext;\n // Only stringify user attributes for legacy users.\n if (context.kind === null || context.kind === undefined) {\n userAttrsToStringify.forEach(attr => {\n const value = context[attr];\n if (value !== undefined && typeof value !== 'string') {\n newContext = newContext || { ...context };\n newContext[attr] = String(value);\n }\n });\n }\n\n return newContext || context;\n}\n\n/**\n * Creates a function that will invoke the provided function only once.\n *\n * If the function returns a value, then that returned value will be re-used for subsequent invocations.\n *\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n */\nfunction once(func) {\n let called = false;\n let result;\n return function(...args) {\n if (!called) {\n called = true;\n result = func.apply(this, args);\n }\n return result;\n };\n}\n\nmodule.exports = {\n appendUrlPath,\n base64URLEncode,\n btoa,\n clone,\n deepEquals,\n extend,\n getLDUserAgentString,\n objectHasOwnProperty,\n onNextTick,\n sanitizeContext,\n transformValuesToVersionedValues,\n transformVersionedValuesToValues,\n wrapPromiseCallback,\n once,\n};\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js'; // **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\n\nvar _clockseq; // Previous uuid creation time\n\n\nvar _lastMSecs = 0;\nvar _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || new Array(16);\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n var seedBytes = options.random || (options.rng || rng)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || stringify(b);\n}\n\nexport default v1;","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n var v;\n var arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","import stringify from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n var bytes = [];\n\n for (var i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function (name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (namespace.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n var bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return stringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","/*\n * Browser-compatible JavaScript MD5\n *\n * Modification of JavaScript MD5\n * https://github.com/blueimp/JavaScript-MD5\n *\n * Copyright 2011, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on\n * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message\n * Digest Algorithm, as defined in RFC 1321.\n * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for more info.\n */\nfunction md5(bytes) {\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = new Uint8Array(msg.length);\n\n for (var i = 0; i < msg.length; ++i) {\n bytes[i] = msg.charCodeAt(i);\n }\n }\n\n return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));\n}\n/*\n * Convert an array of little-endian words to an array of bytes\n */\n\n\nfunction md5ToHexEncodedArray(input) {\n var output = [];\n var length32 = input.length * 32;\n var hexTab = '0123456789abcdef';\n\n for (var i = 0; i < length32; i += 8) {\n var x = input[i >> 5] >>> i % 32 & 0xff;\n var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);\n output.push(hex);\n }\n\n return output;\n}\n/**\n * Calculate output length with padding and bit length\n */\n\n\nfunction getOutputLength(inputLength8) {\n return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;\n}\n/*\n * Calculate the MD5 of an array of little-endian words, and a bit length.\n */\n\n\nfunction wordsToMd5(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << len % 32;\n x[getOutputLength(len) - 1] = len;\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n a = md5ff(a, b, c, d, x[i], 7, -680876936);\n d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);\n c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);\n a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);\n d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);\n b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);\n a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);\n c = md5ff(c, d, a, b, x[i + 10], 17, -42063);\n b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);\n d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);\n c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);\n a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);\n d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);\n b = md5gg(b, c, d, a, x[i], 20, -373897302);\n a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);\n c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);\n b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);\n d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);\n c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);\n a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);\n d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);\n b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);\n a = md5hh(a, b, c, d, x[i + 5], 4, -378558);\n d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);\n c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);\n b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);\n d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);\n c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);\n a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);\n d = md5hh(d, a, b, c, x[i], 11, -358537222);\n c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);\n b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);\n a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);\n c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);\n b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = md5ii(a, b, c, d, x[i], 6, -198630844);\n d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);\n c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);\n a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);\n d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);\n b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);\n a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);\n c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);\n b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);\n d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);\n c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);\n a = safeAdd(a, olda);\n b = safeAdd(b, oldb);\n c = safeAdd(c, oldc);\n d = safeAdd(d, oldd);\n }\n\n return [a, b, c, d];\n}\n/*\n * Convert an array bytes to an array of little-endian words\n * Characters >255 have their high-byte silently ignored.\n */\n\n\nfunction bytesToWords(input) {\n if (input.length === 0) {\n return [];\n }\n\n var length8 = input.length * 8;\n var output = new Uint32Array(getOutputLength(length8));\n\n for (var i = 0; i < length8; i += 8) {\n output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;\n }\n\n return output;\n}\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n\n\nfunction safeAdd(x, y) {\n var lsw = (x & 0xffff) + (y & 0xffff);\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return msw << 16 | lsw & 0xffff;\n}\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\n\n\nfunction bitRotateLeft(num, cnt) {\n return num << cnt | num >>> 32 - cnt;\n}\n/*\n * These functions implement the four basic operations the algorithm uses.\n */\n\n\nfunction md5cmn(q, a, b, x, s, t) {\n return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);\n}\n\nfunction md5ff(a, b, c, d, x, s, t) {\n return md5cmn(b & c | ~b & d, a, b, x, s, t);\n}\n\nfunction md5gg(a, b, c, d, x, s, t) {\n return md5cmn(b & d | c & ~d, a, b, x, s, t);\n}\n\nfunction md5hh(a, b, c, d, x, s, t) {\n return md5cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction md5ii(a, b, c, d, x, s, t) {\n return md5cmn(c ^ (b | ~d), a, b, x, s, t);\n}\n\nexport default md5;","import v35 from './v35.js';\nimport md5 from './md5.js';\nvar v3 = v35('v3', 0x30, md5);\nexport default v3;","// Adapted from Chris Veness' SHA1 code at\n// http://www.movable-type.co.uk/scripts/sha1.html\nfunction f(s, x, y, z) {\n switch (s) {\n case 0:\n return x & y ^ ~x & z;\n\n case 1:\n return x ^ y ^ z;\n\n case 2:\n return x & y ^ x & z ^ y & z;\n\n case 3:\n return x ^ y ^ z;\n }\n}\n\nfunction ROTL(x, n) {\n return x << n | x >>> 32 - n;\n}\n\nfunction sha1(bytes) {\n var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = [];\n\n for (var i = 0; i < msg.length; ++i) {\n bytes.push(msg.charCodeAt(i));\n }\n } else if (!Array.isArray(bytes)) {\n // Convert Array-like to Array\n bytes = Array.prototype.slice.call(bytes);\n }\n\n bytes.push(0x80);\n var l = bytes.length / 4 + 2;\n var N = Math.ceil(l / 16);\n var M = new Array(N);\n\n for (var _i = 0; _i < N; ++_i) {\n var arr = new Uint32Array(16);\n\n for (var j = 0; j < 16; ++j) {\n arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];\n }\n\n M[_i] = arr;\n }\n\n M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);\n M[N - 1][14] = Math.floor(M[N - 1][14]);\n M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;\n\n for (var _i2 = 0; _i2 < N; ++_i2) {\n var W = new Uint32Array(80);\n\n for (var t = 0; t < 16; ++t) {\n W[t] = M[_i2][t];\n }\n\n for (var _t = 16; _t < 80; ++_t) {\n W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);\n }\n\n var a = H[0];\n var b = H[1];\n var c = H[2];\n var d = H[3];\n var e = H[4];\n\n for (var _t2 = 0; _t2 < 80; ++_t2) {\n var s = Math.floor(_t2 / 20);\n var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;\n e = d;\n d = c;\n c = ROTL(b, 30) >>> 0;\n b = a;\n a = T;\n }\n\n H[0] = H[0] + a >>> 0;\n H[1] = H[1] + b >>> 0;\n H[2] = H[2] + c >>> 0;\n H[3] = H[3] + d >>> 0;\n H[4] = H[4] + e >>> 0;\n }\n\n return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nvar v5 = v35('v5', 0x50, sha1);\nexport default v5;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","export default '00000000-0000-0000-0000-000000000000';","import validate from './validate.js';\n\nfunction version(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.substr(14, 1), 16);\n}\n\nexport default version;","const logLevels = ['debug', 'info', 'warn', 'error', 'none'];\n\n/**\n * A simple logger that writes to stderr.\n */\nfunction commonBasicLogger(options, formatFn) {\n if (options && options.destination && typeof options.destination !== 'function') {\n throw new Error('destination for basicLogger was set to a non-function');\n }\n\n function toConsole(methodName) {\n // The global console variable is not guaranteed to be defined at all times in all browsers:\n // https://www.beyondjava.net/console-log-surprises-with-internet-explorer-11-and-edge\n return function(line) {\n if (console && console[methodName]) {\n console[methodName].call(console, line);\n }\n };\n }\n const destinations =\n options && options.destination\n ? [options.destination, options.destination, options.destination, options.destination]\n : [toConsole('log'), toConsole('info'), toConsole('warn'), toConsole('error')];\n const prependLevelToMessage = !!(options && options.destination); // if we're writing to console.warn, etc. we don't need the prefix\n const prefix =\n !options || options.prefix === undefined || options.prefix === null ? '[LaunchDarkly] ' : options.prefix;\n\n let minLevel = 1; // default is 'info'\n if (options && options.level) {\n for (let i = 0; i < logLevels.length; i++) {\n if (logLevels[i] === options.level) {\n minLevel = i;\n }\n }\n }\n\n function write(levelIndex, levelName, args) {\n if (args.length < 1) {\n return;\n }\n let line;\n const fullPrefix = prependLevelToMessage ? levelName + ': ' + prefix : prefix;\n if (args.length === 1 || !formatFn) {\n line = fullPrefix + args[0];\n } else {\n const tempArgs = [...args];\n tempArgs[0] = fullPrefix + tempArgs[0];\n line = formatFn(...tempArgs);\n }\n try {\n destinations[levelIndex](line);\n } catch (err) {\n console &&\n console.log &&\n console.log(\"[LaunchDarkly] Configured logger's \" + levelName + ' method threw an exception: ' + err);\n }\n }\n\n const logger = {};\n for (let i = 0; i < logLevels.length; i++) {\n const levelName = logLevels[i];\n if (levelName !== 'none') {\n if (i < minLevel) {\n logger[levelName] = () => {};\n } else {\n const levelIndex = i;\n logger[levelName] = function() {\n // can't use arrow function with \"arguments\"\n write(levelIndex, levelName, arguments);\n };\n }\n }\n }\n\n return logger;\n}\n\nfunction validateLogger(logger) {\n logLevels.forEach(level => {\n if (level !== 'none' && (!logger[level] || typeof logger[level] !== 'function')) {\n throw new Error('Provided logger instance must support logger.' + level + '(...) method');\n // Note that the SDK normally does not throw exceptions to the application, but that rule\n // does not apply to LDClient.init() which will throw an exception if the parameters are so\n // invalid that we cannot proceed with creating the client. An invalid logger meets those\n // criteria since the SDK calls the logger during nearly all of its operations.\n }\n });\n}\n\nmodule.exports = {\n commonBasicLogger,\n validateLogger,\n};\n","const errors = require('./errors');\n\nfunction errorString(err) {\n if (err && err.message) {\n return err.message;\n }\n if (typeof err === 'string' || err instanceof String) {\n return err;\n }\n return JSON.stringify(err);\n}\n\nconst clientInitialized = function() {\n return 'LaunchDarkly client initialized';\n};\n\nconst docLink =\n ' Please see https://docs.launchdarkly.com/sdk/client-side/javascript#initialize-the-client for instructions on SDK initialization.';\n\nconst clientNotReady = function() {\n return 'LaunchDarkly client is not ready';\n};\n\nconst eventCapacityExceeded = function() {\n return 'Exceeded event queue capacity. Increase capacity to avoid dropping events.';\n};\n\nconst eventWithoutContext = function() {\n return 'Be sure to call `identify` in the LaunchDarkly client: https://docs.launchdarkly.com/sdk/features/identify#javascript';\n};\n\nconst invalidContentType = function(contentType) {\n return 'Expected application/json content type but got \"' + contentType + '\"';\n};\n\nconst invalidKey = function() {\n return 'Event key must be a string';\n};\n\nconst localStorageUnavailable = function(err) {\n return 'local storage is unavailable: ' + errorString(err);\n};\n\nconst networkError = e => 'network error' + (e ? ' (' + e + ')' : '');\n\n// We should remove unknownCustomEventKey in the future - see comments in track() in index.js\nconst unknownCustomEventKey = function(key) {\n return 'Custom event \"' + key + '\" does not exist';\n};\n\nconst environmentNotFound = function() {\n return 'Environment not found. Double check that you specified a valid environment/client-side ID.' + docLink;\n};\n\nconst environmentNotSpecified = function() {\n return 'No environment/client-side ID was specified.' + docLink;\n};\n\nconst errorFetchingFlags = function(err) {\n return 'Error fetching flag settings: ' + errorString(err);\n};\n\nconst contextNotSpecified = function() {\n return 'No context specified.' + docLink;\n};\n\nconst invalidContext = function() {\n return 'Invalid context specified.' + docLink;\n};\n\nconst invalidData = function() {\n return 'Invalid data received from LaunchDarkly; connection may have been interrupted';\n};\n\nconst bootstrapOldFormat = function() {\n return (\n 'LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. ' +\n 'Events may not be sent correctly.' +\n docLink\n );\n};\n\nconst bootstrapInvalid = function() {\n return 'LaunchDarkly bootstrap data is not available because the back end could not read the flags.';\n};\n\nconst deprecated = function(oldName, newName) {\n if (newName) {\n return '\"' + oldName + '\" is deprecated, please use \"' + newName + '\"';\n }\n return '\"' + oldName + '\" is deprecated';\n};\n\nconst httpErrorMessage = function(status, context, retryMessage) {\n return (\n 'Received error ' +\n status +\n (status === 401 ? ' (invalid SDK key)' : '') +\n ' for ' +\n context +\n ' - ' +\n (errors.isHttpErrorRecoverable(status) ? retryMessage : 'giving up permanently')\n );\n};\n\nconst httpUnavailable = function() {\n return 'Cannot make HTTP requests in this environment.' + docLink;\n};\n\nconst identifyDisabled = function() {\n return 'identify() has no effect here; it must be called on the main client instance';\n};\n\nconst streamClosing = function() {\n return 'Closing stream connection';\n};\n\nconst streamConnecting = function(url) {\n return 'Opening stream connection to ' + url;\n};\n\nconst streamError = function(err, streamReconnectDelay) {\n return (\n 'Error on stream connection: ' +\n errorString(err) +\n ', will continue retrying after ' +\n streamReconnectDelay +\n ' milliseconds.'\n );\n};\n\nconst unknownOption = name => 'Ignoring unknown config option \"' + name + '\"';\n\nconst unrecoverableStreamError = err => `Error on stream connection ${errorString(err)}, giving up permanently`;\n\nconst wrongOptionType = (name, expectedType, actualType) =>\n 'Config option \"' + name + '\" should be of type ' + expectedType + ', got ' + actualType + ', using default value';\n\nconst wrongOptionTypeBoolean = (name, actualType) =>\n 'Config option \"' + name + '\" should be a boolean, got ' + actualType + ', converting to boolean';\n\nconst optionBelowMinimum = (name, value, minimum) =>\n 'Config option \"' + name + '\" was set to ' + value + ', changing to minimum value of ' + minimum;\n\nconst debugPolling = function(url) {\n return 'polling for feature flags at ' + url;\n};\n\nconst debugStreamPing = function() {\n return 'received ping message from stream';\n};\n\nconst debugStreamPut = function() {\n return 'received streaming update for all flags';\n};\n\nconst debugStreamPatch = function(key) {\n return 'received streaming update for flag \"' + key + '\"';\n};\n\nconst debugStreamPatchIgnored = function(key) {\n return 'received streaming update for flag \"' + key + '\" but ignored due to version check';\n};\n\nconst debugStreamDelete = function(key) {\n return 'received streaming deletion for flag \"' + key + '\"';\n};\n\nconst debugStreamDeleteIgnored = function(key) {\n return 'received streaming deletion for flag \"' + key + '\" but ignored due to version check';\n};\n\nconst debugEnqueueingEvent = function(kind) {\n return 'enqueueing \"' + kind + '\" event';\n};\n\nconst debugPostingEvents = function(count) {\n return 'sending ' + count + ' events';\n};\n\nconst debugPostingDiagnosticEvent = function(event) {\n return 'sending diagnostic event (' + event.kind + ')';\n};\n\nconst invalidInspector = (type, name) => `an inspector: \"${name}\" of an invalid type (${type}) was configured`;\n\nconst inspectorMethodError = (type, name) => `an inspector: \"${name}\" of type: \"${type}\" generated an exception`;\n\nconst invalidTagValue = name => `Config option \"${name}\" must only contain letters, numbers, ., _ or -.`;\n\nconst tagValueTooLong = name => `Value of \"${name}\" was longer than 64 characters and was discarded.`;\n\nconst invalidMetricValue = badType =>\n `The track function was called with a non-numeric \"metricValue\" (${badType}), only numeric metric values are supported.`;\n\nmodule.exports = {\n bootstrapInvalid,\n bootstrapOldFormat,\n clientInitialized,\n clientNotReady,\n debugEnqueueingEvent,\n debugPostingDiagnosticEvent,\n debugPostingEvents,\n debugStreamDelete,\n debugStreamDeleteIgnored,\n debugStreamPatch,\n debugStreamPatchIgnored,\n debugStreamPing,\n debugPolling,\n debugStreamPut,\n deprecated,\n environmentNotFound,\n environmentNotSpecified,\n errorFetchingFlags,\n eventCapacityExceeded,\n eventWithoutContext,\n httpErrorMessage,\n httpUnavailable,\n identifyDisabled,\n inspectorMethodError,\n invalidContentType,\n invalidData,\n invalidInspector,\n invalidKey,\n invalidMetricValue,\n invalidContext,\n invalidTagValue,\n localStorageUnavailable,\n networkError,\n optionBelowMinimum,\n streamClosing,\n streamConnecting,\n streamError,\n tagValueTooLong,\n unknownCustomEventKey,\n unknownOption,\n contextNotSpecified,\n unrecoverableStreamError,\n wrongOptionType,\n wrongOptionTypeBoolean,\n};\n","const errors = require('./errors');\nconst { validateLogger } = require('./loggers');\nconst messages = require('./messages');\nconst utils = require('./utils');\n\n// baseOptionDefs should contain an entry for each supported configuration option in the common package.\n// Each entry can have three properties:\n// - \"default\": the default value if any\n// - \"type\": a type constraint used if the type can't be inferred from the default value). The allowable\n// values are \"boolean\", \"string\", \"number\", \"array\", \"object\", \"function\", or several of these OR'd\n// together with \"|\" (\"function|object\").\n// - \"minimum\": minimum value if any for numeric properties\n//\n// The extraOptionDefs parameter to validate() uses the same format.\nconst baseOptionDefs = {\n baseUrl: { default: 'https://app.launchdarkly.com' },\n streamUrl: { default: 'https://clientstream.launchdarkly.com' },\n eventsUrl: { default: 'https://events.launchdarkly.com' },\n sendEvents: { default: true },\n streaming: { type: 'boolean' }, // default for this is undefined, which is different from false\n sendLDHeaders: { default: true },\n requestHeaderTransform: { type: 'function' },\n sendEventsOnlyForVariation: { default: false },\n useReport: { default: false },\n evaluationReasons: { default: false },\n eventCapacity: { default: 100, minimum: 1 },\n flushInterval: { default: 2000, minimum: 2000 },\n samplingInterval: { default: 0, minimum: 0 },\n streamReconnectDelay: { default: 1000, minimum: 0 },\n allAttributesPrivate: { default: false },\n privateAttributes: { default: [] },\n bootstrap: { type: 'string|object' },\n diagnosticRecordingInterval: { default: 900000, minimum: 2000 },\n diagnosticOptOut: { default: false },\n wrapperName: { type: 'string' },\n wrapperVersion: { type: 'string' },\n stateProvider: { type: 'object' }, // not a public option, used internally\n application: { validator: applicationConfigValidator },\n inspectors: { default: [] },\n hooks: { default: [] },\n plugins: { default: [] },\n};\n\n/**\n * Expression to validate characters that are allowed in tag keys and values.\n */\nconst allowedTagCharacters = /^(\\w|\\.|-)+$/;\n\nfunction canonicalizeUrl(url) {\n return url && url.replace(/\\/+$/, '');\n}\n\n/**\n * Verify that a value meets the requirements for a tag value.\n * @param {string} tagValue\n * @param {Object} logger\n */\nfunction validateTagValue(name, tagValue, logger) {\n if (typeof tagValue !== 'string' || !tagValue.match(allowedTagCharacters)) {\n logger.warn(messages.invalidTagValue(name));\n return undefined;\n }\n if (tagValue.length > 64) {\n logger.warn(messages.tagValueTooLong(name));\n return undefined;\n }\n return tagValue;\n}\n\nfunction applicationConfigValidator(name, value, logger) {\n const validated = {};\n if (value.id) {\n validated.id = validateTagValue(`${name}.id`, value.id, logger);\n }\n if (value.version) {\n validated.version = validateTagValue(`${name}.version`, value.version, logger);\n }\n return validated;\n}\n\nfunction validate(options, emitter, extraOptionDefs, logger) {\n const optionDefs = utils.extend({ logger: { default: logger } }, baseOptionDefs, extraOptionDefs);\n\n const deprecatedOptions = {\n // As of the latest major version, there are no deprecated options. Next time we deprecate\n // something, add an item here where the property name is the deprecated name, and the\n // property value is the preferred name if any, or null/undefined if there is no replacement.\n };\n\n function checkDeprecatedOptions(config) {\n const opts = config;\n Object.keys(deprecatedOptions).forEach(oldName => {\n if (opts[oldName] !== undefined) {\n const newName = deprecatedOptions[oldName];\n logger && logger.warn(messages.deprecated(oldName, newName));\n if (newName) {\n if (opts[newName] === undefined) {\n opts[newName] = opts[oldName];\n }\n delete opts[oldName];\n }\n }\n });\n }\n\n function applyDefaults(config) {\n // This works differently from utils.extend() in that it *will not* override a default value\n // if the provided value is explicitly set to null. This provides backward compatibility\n // since in the past we only used the provided values if they were truthy.\n const ret = utils.extend({}, config);\n Object.keys(optionDefs).forEach(name => {\n if (ret[name] === undefined || ret[name] === null) {\n ret[name] = optionDefs[name] && optionDefs[name].default;\n }\n });\n return ret;\n }\n\n function validateTypesAndNames(config) {\n const ret = utils.extend({}, config);\n const typeDescForValue = value => {\n if (value === null) {\n return 'any';\n }\n if (value === undefined) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n const t = typeof value;\n if (t === 'boolean' || t === 'string' || t === 'number' || t === 'function') {\n return t;\n }\n return 'object';\n };\n Object.keys(config).forEach(name => {\n const value = config[name];\n if (value !== null && value !== undefined) {\n const optionDef = optionDefs[name];\n if (optionDef === undefined) {\n reportArgumentError(messages.unknownOption(name));\n } else {\n const expectedType = optionDef.type || typeDescForValue(optionDef.default);\n const validator = optionDef.validator;\n if (validator) {\n const validated = validator(name, config[name], logger);\n if (validated !== undefined) {\n ret[name] = validated;\n } else {\n delete ret[name];\n }\n } else if (expectedType !== 'any') {\n const allowedTypes = expectedType.split('|');\n const actualType = typeDescForValue(value);\n if (allowedTypes.indexOf(actualType) < 0) {\n if (expectedType === 'boolean') {\n ret[name] = !!value;\n reportArgumentError(messages.wrongOptionTypeBoolean(name, actualType));\n } else {\n reportArgumentError(messages.wrongOptionType(name, expectedType, actualType));\n ret[name] = optionDef.default;\n }\n } else {\n if (actualType === 'number' && optionDef.minimum !== undefined && value < optionDef.minimum) {\n reportArgumentError(messages.optionBelowMinimum(name, value, optionDef.minimum));\n ret[name] = optionDef.minimum;\n }\n }\n }\n }\n }\n });\n\n ret.baseUrl = canonicalizeUrl(ret.baseUrl);\n ret.streamUrl = canonicalizeUrl(ret.streamUrl);\n ret.eventsUrl = canonicalizeUrl(ret.eventsUrl);\n\n return ret;\n }\n\n function reportArgumentError(message) {\n utils.onNextTick(() => {\n emitter && emitter.maybeReportError(new errors.LDInvalidArgumentError(message));\n });\n }\n\n let config = utils.extend({}, options || {});\n\n checkDeprecatedOptions(config);\n\n config = applyDefaults(config);\n config = validateTypesAndNames(config);\n validateLogger(config.logger);\n\n return config;\n}\n\n/**\n * Get tags for the specified configuration.\n *\n * If any additional tags are added to the configuration, then the tags from\n * this method should be extended with those.\n * @param {Object} config The already valiated configuration.\n * @returns {Object} The tag configuration.\n */\nfunction getTags(config) {\n const tags = {};\n if (config) {\n if (config.application && config.application.id !== undefined && config.application.id !== null) {\n tags['application-id'] = [config.application.id];\n }\n if (config.application && config.application.version !== undefined && config.application.id !== null) {\n tags['application-version'] = [config.application.version];\n }\n }\n\n return tags;\n}\n\nmodule.exports = {\n baseOptionDefs,\n validate,\n getTags,\n};\n","const { getLDUserAgentString } = require('./utils');\nconst configuration = require('./configuration');\n\nfunction getLDHeaders(platform, options) {\n if (options && !options.sendLDHeaders) {\n return {};\n }\n const h = {};\n h[platform.userAgentHeaderName || 'User-Agent'] = getLDUserAgentString(platform);\n if (options && options.wrapperName) {\n h['X-LaunchDarkly-Wrapper'] = options.wrapperVersion\n ? options.wrapperName + '/' + options.wrapperVersion\n : options.wrapperName;\n }\n const tags = configuration.getTags(options);\n const tagKeys = Object.keys(tags);\n if (tagKeys.length) {\n h['x-launchdarkly-tags'] = tagKeys\n .sort()\n .map(key =>\n Array.isArray(tags[key]) ? tags[key].sort().map(value => `${key}/${value}`) : [`${key}/${tags[key]}`]\n )\n .reduce((flattened, item) => flattened.concat(item), [])\n .join(' ');\n }\n return h;\n}\n\nfunction transformHeaders(headers, options) {\n if (!options || !options.requestHeaderTransform) {\n return headers;\n }\n return options.requestHeaderTransform({ ...headers });\n}\n\nmodule.exports = {\n getLDHeaders,\n transformHeaders,\n};\n","const errors = require('./errors');\nconst utils = require('./utils');\nconst { v1: uuidv1 } = require('uuid');\nconst { getLDHeaders, transformHeaders } = require('./headers');\n\nfunction EventSender(platform, environmentId, options) {\n const baseHeaders = utils.extend({ 'Content-Type': 'application/json' }, getLDHeaders(platform, options));\n const sender = {};\n\n function getResponseInfo(result) {\n const ret = { status: result.status };\n const dateStr = result.header('date');\n if (dateStr) {\n const time = Date.parse(dateStr);\n if (time) {\n ret.serverTime = time;\n }\n }\n return ret;\n }\n\n sender.sendEvents = (events, url, isDiagnostic) => {\n if (!platform.httpRequest) {\n return Promise.resolve();\n }\n\n const jsonBody = JSON.stringify(events);\n const payloadId = isDiagnostic ? null : uuidv1();\n\n function doPostRequest(canRetry) {\n const headers = isDiagnostic\n ? baseHeaders\n : utils.extend({}, baseHeaders, {\n 'X-LaunchDarkly-Event-Schema': '4',\n 'X-LaunchDarkly-Payload-ID': payloadId,\n });\n return platform\n .httpRequest('POST', url, transformHeaders(headers, options), jsonBody)\n .promise.then(result => {\n if (!result) {\n // This was a response from a fire-and-forget request, so we won't have a status.\n return;\n }\n if (result.status >= 400 && errors.isHttpErrorRecoverable(result.status) && canRetry) {\n return doPostRequest(false);\n } else {\n return getResponseInfo(result);\n }\n })\n .catch(() => {\n if (canRetry) {\n return doPostRequest(false);\n }\n return Promise.reject();\n });\n }\n\n return doPostRequest(true).catch(() => {});\n };\n\n return sender;\n}\n\nmodule.exports = EventSender;\n","/**\n * Given some object to serialize product a canonicalized JSON string.\n * https://www.rfc-editor.org/rfc/rfc8785.html\n *\n * We do not support custom toJSON methods on objects. Objects should be limited to basic types.\n *\n * @param {any} object The object to serialize.\n * @param {any[]?} visited The list of objects that have already been visited to avoid cycles.\n * @returns {string} The canonicalized JSON string.\n */\nfunction canonicalize(object, visited = []) {\n // For JavaScript the default JSON serialization will produce canonicalized output for basic types.\n if (object === null || typeof object !== 'object') {\n return JSON.stringify(object);\n }\n\n if (visited.includes(object)) {\n throw new Error('Cycle detected');\n }\n\n if (Array.isArray(object)) {\n const values = object\n .map(item => canonicalize(item, [...visited, object]))\n .map(item => (item === undefined ? 'null' : item));\n return `[${values.join(',')}]`;\n }\n\n const values = Object.keys(object)\n .sort()\n .map(key => {\n const value = canonicalize(object[key], [...visited, object]);\n if (value !== undefined) {\n return `${JSON.stringify(key)}:${value}`;\n }\n return undefined;\n })\n .filter(item => item !== undefined);\n return `{${values.join(',')}}`;\n}\n\nmodule.exports = canonicalize;\n","const { commonBasicLogger } = require('./loggers');\n\n/**\n * Validate a context kind.\n * @param {string} kind\n * @returns true if the kind is valid.\n */\nfunction validKind(kind) {\n return typeof kind === 'string' && kind !== 'kind' && kind.match(/^(\\w|\\.|-)+$/);\n}\n\n/**\n * Perform a check of basic context requirements.\n * @param {Object} context\n * @param {boolean} allowLegacyKey If true, then a legacy user can have an\n * empty or non-string key. A legacy user is a context without a kind.\n * @returns true if the context meets basic requirements.\n */\nfunction checkContext(context, allowLegacyKey) {\n if (context) {\n if (allowLegacyKey && (context.kind === undefined || context.kind === null)) {\n return context.key !== undefined && context.key !== null;\n }\n const key = context.key;\n const kind = context.kind === undefined ? 'user' : context.kind;\n const kindValid = validKind(kind);\n const keyValid = kind === 'multi' || (key !== undefined && key !== null && key !== '');\n if (kind === 'multi') {\n const kinds = Object.keys(context).filter(key => key !== 'kind');\n return (\n keyValid &&\n kinds.every(key => validKind(key)) &&\n kinds.every(key => {\n const contextKey = context[key].key;\n return contextKey !== undefined && contextKey !== null && contextKey !== '';\n })\n );\n }\n return keyValid && kindValid;\n }\n return false;\n}\n\n/**\n * For a given context get a list of context kinds.\n * @param {Object} context\n * @returns {string[]} A list of kinds in the context.\n */\nfunction getContextKinds(context) {\n if (context) {\n if (context.kind === null || context.kind === undefined) {\n return ['user'];\n }\n if (context.kind !== 'multi') {\n return [context.kind];\n }\n return Object.keys(context).filter(kind => kind !== 'kind');\n }\n return [];\n}\n\n/**\n * The partial URL encoding is needed because : is a valid character in context keys.\n *\n * Partial encoding is the replacement of all colon (:) characters with the URL\n * encoded equivalent (%3A) and all percent (%) characters with the URL encoded\n * equivalent (%25).\n * @param {string} key The key to encode.\n * @returns {string} Partially URL encoded key.\n */\nfunction encodeKey(key) {\n if (key.includes('%') || key.includes(':')) {\n return key.replace(/%/g, '%25').replace(/:/g, '%3A');\n }\n return key;\n}\n\nfunction getCanonicalKey(context) {\n if (context) {\n if ((context.kind === undefined || context.kind === null || context.kind === 'user') && context.key) {\n return context.key;\n } else if (context.kind !== 'multi' && context.key) {\n return `${context.kind}:${encodeKey(context.key)}`;\n } else if (context.kind === 'multi') {\n return Object.keys(context)\n .sort()\n .filter(key => key !== 'kind')\n .map(key => `${key}:${encodeKey(context[key].key)}`)\n .join(':');\n }\n }\n}\n\nfunction getContextKeys(context, logger = commonBasicLogger()) {\n if (!context) {\n return undefined;\n }\n\n const keys = {};\n const { kind, key } = context;\n\n switch (kind) {\n case undefined:\n keys.user = `${key}`;\n break;\n case 'multi':\n Object.entries(context)\n .filter(([key]) => key !== 'kind')\n .forEach(([key, value]) => {\n if (value && value.key) {\n keys[key] = value.key;\n }\n });\n break;\n case null:\n logger.warn(`null is not a valid context kind: ${context}`);\n break;\n case '':\n logger.warn(`'' is not a valid context kind: ${context}`);\n break;\n default:\n keys[kind] = `${key}`;\n break;\n }\n\n return keys;\n}\n\nmodule.exports = {\n checkContext,\n getContextKeys,\n getContextKinds,\n getCanonicalKey,\n};\n","const { getContextKinds } = require('./context');\n\nfunction getKinds(event) {\n if (event.context) {\n return getContextKinds(event.context);\n }\n if (event.contextKeys) {\n return Object.keys(event.contextKeys);\n }\n return [];\n}\n\nfunction EventSummarizer() {\n const es = {};\n\n let startDate = 0,\n endDate = 0,\n counters = {},\n contextKinds = {};\n\n es.summarizeEvent = event => {\n if (event.kind === 'feature') {\n const counterKey =\n event.key +\n ':' +\n (event.variation !== null && event.variation !== undefined ? event.variation : '') +\n ':' +\n (event.version !== null && event.version !== undefined ? event.version : '');\n const counterVal = counters[counterKey];\n let kinds = contextKinds[event.key];\n if (!kinds) {\n kinds = new Set();\n contextKinds[event.key] = kinds;\n }\n getKinds(event).forEach(kind => kinds.add(kind));\n\n if (counterVal) {\n counterVal.count = counterVal.count + 1;\n } else {\n counters[counterKey] = {\n count: 1,\n key: event.key,\n version: event.version,\n variation: event.variation,\n value: event.value,\n default: event.default,\n };\n }\n if (startDate === 0 || event.creationDate < startDate) {\n startDate = event.creationDate;\n }\n if (event.creationDate > endDate) {\n endDate = event.creationDate;\n }\n }\n };\n\n es.getSummary = () => {\n const flagsOut = {};\n let empty = true;\n for (const c of Object.values(counters)) {\n let flag = flagsOut[c.key];\n if (!flag) {\n flag = {\n default: c.default,\n counters: [],\n contextKinds: [...contextKinds[c.key]],\n };\n flagsOut[c.key] = flag;\n }\n const counterOut = {\n value: c.value,\n count: c.count,\n };\n if (c.variation !== undefined && c.variation !== null) {\n counterOut.variation = c.variation;\n }\n if (c.version !== undefined && c.version !== null) {\n counterOut.version = c.version;\n } else {\n counterOut.unknown = true;\n }\n flag.counters.push(counterOut);\n empty = false;\n }\n return empty\n ? null\n : {\n startDate,\n endDate,\n features: flagsOut,\n kind: 'summary',\n };\n };\n\n es.clearSummary = () => {\n startDate = 0;\n endDate = 0;\n counters = {};\n contextKinds = {};\n };\n\n return es;\n}\n\nmodule.exports = EventSummarizer;\n","const canonicalize = require('./canonicalize');\nconst EventSummarizer = require('./EventSummarizer');\n\n/**\n * Construct a multi-event summarizer. This summarizer produces a summary event for each unique context.\n * @param {{filter: (context: any) => any}} contextFilter\n */\nfunction MultiEventSummarizer(contextFilter) {\n let summarizers = {};\n let contexts = {};\n\n /**\n * Summarize the given event.\n * @param {{\n * kind: string,\n * context?: any,\n * }} event\n */\n function summarizeEvent(event) {\n if (event.kind === 'feature') {\n const key = canonicalize(event.context);\n if (!key) {\n return;\n }\n\n let summarizer = summarizers[key];\n if (!summarizer) {\n summarizers[key] = EventSummarizer();\n summarizer = summarizers[key];\n contexts[key] = event.context;\n }\n\n summarizer.summarizeEvent(event);\n }\n }\n\n /**\n * Get the summaries of the events that have been summarized.\n * @returns {any[]}\n */\n function getSummaries() {\n const summarizersToFlush = summarizers;\n const contextsForSummaries = contexts;\n\n summarizers = {};\n contexts = {};\n return Object.entries(summarizersToFlush).map(([key, summarizer]) => {\n const summary = summarizer.getSummary();\n summary.context = contextFilter.filter(contextsForSummaries[key]);\n return summary;\n });\n }\n\n return {\n summarizeEvent,\n getSummaries,\n };\n}\n\nmodule.exports = MultiEventSummarizer;\n","/**\n * Take a key string and escape the characters to allow it to be used as a reference.\n * @param {string} key\n * @returns {string} The processed key.\n */\nfunction processEscapeCharacters(key) {\n return key.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * @param {string} reference The reference to get the components of.\n * @returns {string[]} The components of the reference. Escape characters will be converted to their representative values.\n */\nfunction getComponents(reference) {\n const referenceWithoutPrefix = reference.startsWith('/') ? reference.substring(1) : reference;\n return referenceWithoutPrefix\n .split('/')\n .map(component => (component.indexOf('~') >= 0 ? component.replace(/~1/g, '/').replace(/~0/g, '~') : component));\n}\n\n/**\n * @param {string} reference The reference to check if it is a literal.\n * @returns true if the reference is a literal.\n */\nfunction isLiteral(reference) {\n return !reference.startsWith('/');\n}\n\n/**\n * Compare two references and determine if they are equivalent.\n * @param {string} a\n * @param {string} b\n */\nfunction compare(a, b) {\n const aIsLiteral = isLiteral(a);\n const bIsLiteral = isLiteral(b);\n if (aIsLiteral && bIsLiteral) {\n return a === b;\n }\n if (aIsLiteral) {\n const bComponents = getComponents(b);\n if (bComponents.length !== 1) {\n return false;\n }\n return a === bComponents[0];\n }\n if (bIsLiteral) {\n const aComponents = getComponents(a);\n if (aComponents.length !== 1) {\n return false;\n }\n return b === aComponents[0];\n }\n return a === b;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns The two strings joined by '/'.\n */\nfunction join(a, b) {\n return `${a}/${b}`;\n}\n\n/**\n * There are cases where a field could have been named with a preceeding '/'.\n * If that attribute was private, then the literal would appear to be a reference.\n * This method can be used to convert a literal to a reference in such situations.\n * @param {string} literal The literal to convert to a reference.\n * @returns A literal which has been converted to a reference.\n */\nfunction literalToReference(literal) {\n return `/${processEscapeCharacters(literal)}`;\n}\n\n/**\n * Clone an object excluding the values referenced by a list of references.\n * @param {Object} target The object to clone.\n * @param {string[]} references A list of references from the cloned object.\n * @returns {{cloned: Object, excluded: string[]}} The cloned object and a list of excluded values.\n */\nfunction cloneExcluding(target, references) {\n const stack = [];\n const cloned = {};\n const excluded = [];\n\n stack.push(\n ...Object.keys(target).map(key => ({\n key,\n ptr: literalToReference(key),\n source: target,\n parent: cloned,\n visited: [target],\n }))\n );\n\n while (stack.length) {\n const item = stack.pop();\n if (!references.some(ptr => compare(ptr, item.ptr))) {\n const value = item.source[item.key];\n\n // Handle null because it overlaps with object, which we will want to handle later.\n if (value === null) {\n item.parent[item.key] = value;\n } else if (Array.isArray(value)) {\n item.parent[item.key] = [...value];\n } else if (typeof value === 'object') {\n //Arrays and null must already be handled.\n\n //Prevent cycles by not visiting the same object\n //with in the same branch. Parallel branches\n //may contain the same object.\n if (item.visited.includes(value)) {\n continue;\n }\n\n item.parent[item.key] = {};\n\n stack.push(\n ...Object.keys(value).map(key => ({\n key,\n ptr: join(item.ptr, processEscapeCharacters(key)),\n source: value,\n parent: item.parent[item.key],\n visited: [...item.visited, value],\n }))\n );\n } else {\n item.parent[item.key] = value;\n }\n } else {\n excluded.push(item.ptr);\n }\n }\n return { cloned, excluded: excluded.sort() };\n}\n\nmodule.exports = {\n cloneExcluding,\n compare,\n literalToReference,\n};\n","const AttributeReference = require('./attributeReference');\n\nfunction ContextFilter(config) {\n const filter = {};\n\n const allAttributesPrivate = config.allAttributesPrivate;\n const privateAttributes = config.privateAttributes || [];\n\n // These attributes cannot be removed via a private attribute.\n const protectedAttributes = ['key', 'kind', '_meta', 'anonymous'];\n\n const legacyTopLevelCopyAttributes = ['name', 'ip', 'firstName', 'lastName', 'email', 'avatar', 'country'];\n\n /**\n * For the given context and configuration get a list of attributes to filter.\n * @param {Object} context\n * @returns {string[]} A list of the attributes to filter.\n */\n const getAttributesToFilter = (context, redactAnonymous) =>\n (allAttributesPrivate || (redactAnonymous && context.anonymous)\n ? Object.keys(context)\n : [...privateAttributes, ...((context._meta && context._meta.privateAttributes) || [])]\n ).filter(attr => !protectedAttributes.some(protectedAttr => AttributeReference.compare(attr, protectedAttr)));\n\n /**\n * @param {Object} context\n * @param {boolean} redactAnonymous\n * @returns {Object} A copy of the context with private attributes removed,\n * and the redactedAttributes meta populated.\n */\n const filterSingleKind = (context, redactAnonymous) => {\n if (typeof context !== 'object' || context === null || Array.isArray(context)) {\n return undefined;\n }\n\n const { cloned, excluded } = AttributeReference.cloneExcluding(\n context,\n getAttributesToFilter(context, redactAnonymous)\n );\n cloned.key = String(cloned.key);\n if (excluded.length) {\n if (!cloned._meta) {\n cloned._meta = {};\n }\n cloned._meta.redactedAttributes = excluded;\n }\n if (cloned._meta) {\n delete cloned._meta['privateAttributes'];\n if (Object.keys(cloned._meta).length === 0) {\n delete cloned._meta;\n }\n }\n // Make sure anonymous is boolean if present.\n // Null counts as present, and would be falsy, which is the default.\n if (cloned.anonymous !== undefined) {\n cloned.anonymous = !!cloned.anonymous;\n }\n\n return cloned;\n };\n\n /**\n * @param {Object} context\n * @param {boolean} redactAnonymous\n * @returns {Object} A copy of the context with the private attributes removed,\n * and the redactedAttributes meta populated for each sub-context.\n */\n const filterMultiKind = (context, redactAnonymous) => {\n const filtered = {\n kind: context.kind,\n };\n const contextKeys = Object.keys(context);\n\n for (const contextKey of contextKeys) {\n if (contextKey !== 'kind') {\n const filteredContext = filterSingleKind(context[contextKey], redactAnonymous);\n if (filteredContext) {\n filtered[contextKey] = filteredContext;\n }\n }\n }\n return filtered;\n };\n\n /**\n * Convert the LDUser object into an LDContext object.\n * @param {Object} user The LDUser to produce an LDContext for.\n * @returns {Object} A single kind context based on the provided user.\n */\n const legacyToSingleKind = user => {\n const filtered = {\n /* Destructure custom items into the top level.\n Duplicate keys will be overridden by previously\n top level items.\n */\n ...(user.custom || {}),\n\n // Implicity a user kind.\n kind: 'user',\n\n key: user.key,\n };\n\n if (user.anonymous !== undefined) {\n filtered.anonymous = !!user.anonymous;\n }\n\n // Copy top level keys and convert them to strings.\n // Remove keys that may have been destructured from `custom`.\n for (const key of legacyTopLevelCopyAttributes) {\n delete filtered[key];\n if (user[key] !== undefined && user[key] !== null) {\n filtered[key] = String(user[key]);\n }\n }\n\n if (user.privateAttributeNames !== undefined && user.privateAttributeNames !== null) {\n filtered._meta = filtered._meta || {};\n // If any private attributes started with '/' we need to convert them to references, otherwise the '/' will\n // cause the literal to incorrectly be treated as a reference.\n filtered._meta.privateAttributes = user.privateAttributeNames.map(literal =>\n literal.startsWith('/') ? AttributeReference.literalToReference(literal) : literal\n );\n }\n\n return filtered;\n };\n\n filter.filter = (context, redactAnonymous = false) => {\n if (context.kind === undefined || context.kind === null) {\n return filterSingleKind(legacyToSingleKind(context), redactAnonymous);\n } else if (context.kind === 'multi') {\n return filterMultiKind(context, redactAnonymous);\n } else {\n return filterSingleKind(context, redactAnonymous);\n }\n };\n\n return filter;\n}\n\nmodule.exports = ContextFilter;\n","const EventSender = require('./EventSender');\nconst MultiEventSummarizer = require('./MultiEventSummarizer');\nconst ContextFilter = require('./ContextFilter');\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst utils = require('./utils');\nconst { getContextKeys } = require('./context');\n\nfunction EventProcessor(\n platform,\n options,\n environmentId,\n diagnosticsAccumulator = null,\n emitter = null,\n sender = null\n) {\n const processor = {};\n const eventSender = sender || EventSender(platform, environmentId, options);\n const mainEventsUrl = utils.appendUrlPath(options.eventsUrl, '/events/bulk/' + environmentId);\n const contextFilter = ContextFilter(options);\n const summarizer = MultiEventSummarizer(contextFilter);\n const samplingInterval = options.samplingInterval;\n const eventCapacity = options.eventCapacity;\n const flushInterval = options.flushInterval;\n const logger = options.logger;\n let queue = [];\n let lastKnownPastTime = 0;\n let disabled = false;\n let exceededCapacity = false;\n let flushTimer;\n\n function shouldSampleEvent() {\n return samplingInterval === 0 || Math.floor(Math.random() * samplingInterval) === 0;\n }\n\n function shouldDebugEvent(e) {\n if (e.debugEventsUntilDate) {\n // The \"last known past time\" comes from the last HTTP response we got from the server.\n // In case the client's time is set wrong, at least we know that any expiration date\n // earlier than that point is definitely in the past. If there's any discrepancy, we\n // want to err on the side of cutting off event debugging sooner.\n return e.debugEventsUntilDate > lastKnownPastTime && e.debugEventsUntilDate > new Date().getTime();\n }\n return false;\n }\n\n // Transform an event from its internal format to the format we use when sending a payload.\n function makeOutputEvent(e) {\n const ret = utils.extend({}, e);\n\n // Identify, feature, and custom events should all include the full context.\n // Debug events do as well, but are not handled by this code path.\n if (e.kind === 'identify' || e.kind === 'feature' || e.kind === 'custom') {\n ret.context = contextFilter.filter(e.context);\n } else {\n ret.contextKeys = getContextKeysFromEvent(e);\n delete ret['context'];\n }\n\n if (e.kind === 'feature') {\n delete ret['trackEvents'];\n delete ret['debugEventsUntilDate'];\n }\n return ret;\n }\n\n function getContextKeysFromEvent(event) {\n return getContextKeys(event.context, logger);\n }\n\n function addToOutbox(event) {\n if (queue.length < eventCapacity) {\n queue.push(event);\n exceededCapacity = false;\n } else {\n if (!exceededCapacity) {\n exceededCapacity = true;\n logger.warn(messages.eventCapacityExceeded());\n }\n if (diagnosticsAccumulator) {\n // For diagnostic events, we track how many times we had to drop an event due to exceeding the capacity.\n diagnosticsAccumulator.incrementDroppedEvents();\n }\n }\n }\n\n processor.enqueue = function(event) {\n if (disabled) {\n return;\n }\n let addFullEvent = false;\n let addDebugEvent = false;\n\n // Add event to the summary counters if appropriate\n summarizer.summarizeEvent(event);\n\n // Decide whether to add the event to the payload. Feature events may be added twice, once for\n // the event (if tracked) and once for debugging.\n if (event.kind === 'feature') {\n if (shouldSampleEvent()) {\n addFullEvent = !!event.trackEvents;\n addDebugEvent = shouldDebugEvent(event);\n }\n } else {\n addFullEvent = shouldSampleEvent();\n }\n\n if (addFullEvent) {\n addToOutbox(makeOutputEvent(event));\n }\n if (addDebugEvent) {\n const debugEvent = utils.extend({}, event, { kind: 'debug' });\n debugEvent.context = contextFilter.filter(debugEvent.context);\n delete debugEvent['trackEvents'];\n delete debugEvent['debugEventsUntilDate'];\n addToOutbox(debugEvent);\n }\n };\n\n processor.flush = async function() {\n if (disabled) {\n return Promise.resolve();\n }\n const eventsToSend = queue;\n const summaries = summarizer.getSummaries();\n\n summaries.forEach(summary => {\n if (Object.keys(summary.features).length) {\n eventsToSend.push(summary);\n }\n });\n\n if (diagnosticsAccumulator) {\n // For diagnostic events, we record how many events were in the queue at the last flush (since \"how\n // many events happened to be in the queue at the moment we decided to send a diagnostic event\" would\n // not be a very useful statistic).\n diagnosticsAccumulator.setEventsInLastBatch(eventsToSend.length);\n }\n if (eventsToSend.length === 0) {\n return Promise.resolve();\n }\n queue = [];\n logger.debug(messages.debugPostingEvents(eventsToSend.length));\n return eventSender.sendEvents(eventsToSend, mainEventsUrl).then(responseInfo => {\n if (responseInfo) {\n if (responseInfo.serverTime) {\n lastKnownPastTime = responseInfo.serverTime;\n }\n if (!errors.isHttpErrorRecoverable(responseInfo.status)) {\n disabled = true;\n }\n if (responseInfo.status >= 400) {\n utils.onNextTick(() => {\n emitter.maybeReportError(\n new errors.LDUnexpectedResponseError(\n messages.httpErrorMessage(responseInfo.status, 'event posting', 'some events were dropped')\n )\n );\n });\n }\n }\n });\n };\n\n processor.start = function() {\n const flushTick = () => {\n processor.flush();\n flushTimer = setTimeout(flushTick, flushInterval);\n };\n flushTimer = setTimeout(flushTick, flushInterval);\n };\n\n processor.stop = function() {\n clearTimeout(flushTimer);\n };\n\n return processor;\n}\n\nmodule.exports = EventProcessor;\n","function EventEmitter(logger) {\n const emitter = {};\n const events = {};\n\n const listeningTo = event => !!events[event];\n\n emitter.on = function(event, handler, context) {\n events[event] = events[event] || [];\n events[event] = events[event].concat({\n handler: handler,\n context: context,\n });\n };\n\n emitter.off = function(event, handler, context) {\n if (!events[event]) {\n return;\n }\n for (let i = 0; i < events[event].length; i++) {\n if (events[event][i].handler === handler && events[event][i].context === context) {\n events[event] = events[event].slice(0, i).concat(events[event].slice(i + 1));\n }\n }\n };\n\n emitter.emit = function(event) {\n if (!events[event]) {\n return;\n }\n // Copy the list of handlers before iterating, in case any handler adds or removes another handler.\n // Any such changes should not affect what we do here-- we want to notify every handler that existed\n // at the moment that the event was fired.\n const copiedHandlers = events[event].slice(0);\n for (let i = 0; i < copiedHandlers.length; i++) {\n copiedHandlers[i].handler.apply(copiedHandlers[i].context, Array.prototype.slice.call(arguments, 1));\n }\n };\n\n emitter.getEvents = function() {\n return Object.keys(events);\n };\n\n emitter.getEventListenerCount = function(event) {\n return events[event] ? events[event].length : 0;\n };\n\n emitter.maybeReportError = function(error) {\n if (!error) {\n return;\n }\n if (listeningTo('error')) {\n this.emit('error', error);\n } else {\n (logger || console).error(error.message);\n }\n };\n return emitter;\n}\n\nmodule.exports = EventEmitter;\n","// This file provides an abstraction of the client's startup state.\n//\n// Startup can either succeed or fail exactly once; calling signalSuccess() or signalFailure()\n// after that point has no effect.\n//\n// On success, we fire both an \"initialized\" event and a \"ready\" event. Both the waitForInitialization()\n// promise and the waitUntilReady() promise are resolved in this case.\n//\n// On failure, we fire both a \"failed\" event (with the error as a parameter) and a \"ready\" event.\n// The waitForInitialization() promise is rejected, but the waitUntilReady() promise is resolved.\n//\n// To complicate things, we must *not* create the waitForInitialization() promise unless it is\n// requested, because otherwise failures would cause an *unhandled* rejection which can be a\n// serious problem in some environments. So we use a somewhat roundabout system for tracking the\n// initialization state and lazily creating this promise.\n\nconst readyEvent = 'ready',\n successEvent = 'initialized',\n failureEvent = 'failed';\n\nfunction InitializationStateTracker(eventEmitter) {\n let succeeded = false,\n failed = false,\n failureValue = null,\n initializationPromise = null;\n\n const readyPromise = new Promise(resolve => {\n const onReady = () => {\n eventEmitter.off(readyEvent, onReady); // we can't use \"once\" because it's not available on some JS platforms\n resolve();\n };\n eventEmitter.on(readyEvent, onReady);\n }).catch(() => {}); // this Promise should never be rejected, but the catch handler is a safety measure\n\n return {\n getInitializationPromise: () => {\n if (initializationPromise) {\n return initializationPromise;\n }\n if (succeeded) {\n return Promise.resolve();\n }\n if (failed) {\n return Promise.reject(failureValue);\n }\n initializationPromise = new Promise((resolve, reject) => {\n const onSuccess = () => {\n eventEmitter.off(successEvent, onSuccess);\n resolve();\n };\n const onFailure = err => {\n eventEmitter.off(failureEvent, onFailure);\n reject(err);\n };\n eventEmitter.on(successEvent, onSuccess);\n eventEmitter.on(failureEvent, onFailure);\n });\n return initializationPromise;\n },\n\n getReadyPromise: () => readyPromise,\n\n signalSuccess: () => {\n if (!succeeded && !failed) {\n succeeded = true;\n eventEmitter.emit(successEvent);\n eventEmitter.emit(readyEvent);\n }\n },\n\n signalFailure: err => {\n if (!succeeded && !failed) {\n failed = true;\n failureValue = err;\n eventEmitter.emit(failureEvent, err);\n eventEmitter.emit(readyEvent);\n }\n eventEmitter.maybeReportError(err); // the \"error\" event can be emitted more than once, unlike the others\n },\n };\n}\n\nmodule.exports = InitializationStateTracker;\n","const utils = require('./utils');\n\nfunction PersistentFlagStore(storage, environment, hash, ident) {\n const store = {};\n\n function getFlagsKey() {\n let key = '';\n const context = ident.getContext();\n if (context) {\n key = hash || utils.btoa(JSON.stringify(context));\n }\n return 'ld:' + environment + ':' + key;\n }\n\n // Returns a Promise which will be resolved with a parsed JSON value if a stored value was available,\n // or resolved with null if there was no value or if storage was not available.\n store.loadFlags = () =>\n storage.get(getFlagsKey()).then(dataStr => {\n if (dataStr === null || dataStr === undefined) {\n return null;\n }\n try {\n let data = JSON.parse(dataStr);\n if (data) {\n const schema = data.$schema;\n if (schema === undefined || schema < 1) {\n data = utils.transformValuesToVersionedValues(data);\n } else {\n delete data['$schema'];\n }\n }\n return data;\n } catch (ex) {\n return store.clearFlags().then(() => null);\n }\n });\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n store.saveFlags = flags => {\n const data = utils.extend({}, flags, { $schema: 1 });\n return storage.set(getFlagsKey(), JSON.stringify(data));\n };\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n store.clearFlags = () => storage.clear(getFlagsKey());\n\n return store;\n}\n\nmodule.exports = PersistentFlagStore;\n","const messages = require('./messages');\n\n// The localStorageProvider is provided by the platform object. It should have the following\n// methods, each of which should return a Promise:\n// - get(key): Gets the string value, if any, for the given key\n// - set(key, value): Stores a string value for the given key\n// - remove(key): Removes the given key\n//\n// Storage is just a light wrapper of the localStorageProvider, adding error handling and\n// ensuring that we don't call it if it's unavailable. The get method will simply resolve\n// with an undefined value if there is an error or if there is no localStorageProvider.\n// None of the promises returned by Storage will ever be rejected.\n//\n// It is always possible that the underlying platform storage mechanism might fail or be\n// disabled. If so, it's likely that it will keep failing, so we will only log one warning\n// instead of repetitive warnings.\nfunction PersistentStorage(localStorageProvider, logger) {\n const storage = {};\n let loggedError = false;\n\n const logError = err => {\n if (!loggedError) {\n loggedError = true;\n logger.warn(messages.localStorageUnavailable(err));\n }\n };\n\n storage.isEnabled = () => !!localStorageProvider;\n\n // Resolves with a value, or undefined if storage is unavailable. Never rejects.\n storage.get = key =>\n new Promise(resolve => {\n if (!localStorageProvider) {\n resolve(undefined);\n return;\n }\n localStorageProvider\n .get(key)\n .then(resolve)\n .catch(err => {\n logError(err);\n resolve(undefined);\n });\n });\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n storage.set = (key, value) =>\n new Promise(resolve => {\n if (!localStorageProvider) {\n resolve(false);\n return;\n }\n localStorageProvider\n .set(key, value)\n .then(() => resolve(true))\n .catch(err => {\n logError(err);\n resolve(false);\n });\n });\n\n // Resolves with true if successful, or false if storage is unavailable. Never rejects.\n storage.clear = key =>\n new Promise(resolve => {\n if (!localStorageProvider) {\n resolve(false);\n return;\n }\n localStorageProvider\n .clear(key)\n .then(() => resolve(true))\n .catch(err => {\n logError(err);\n resolve(false);\n });\n });\n\n return storage;\n}\n\nmodule.exports = PersistentStorage;\n","const messages = require('./messages');\nconst { appendUrlPath, base64URLEncode, objectHasOwnProperty } = require('./utils');\nconst { getLDHeaders, transformHeaders } = require('./headers');\nconst { isHttpErrorRecoverable } = require('./errors');\n\n// The underlying event source implementation is abstracted via the platform object, which should\n// have these three properties:\n// eventSourceFactory(): a function that takes a URL and optional config object and returns an object\n// with the same methods as the regular HTML5 EventSource object. The properties in the config\n// object are those supported by the launchdarkly-eventsource package; browser EventSource\n// implementations don't have any config options.\n// eventSourceIsActive(): a function that takes an EventSource-compatible object and returns true if\n// it is in an active state (connected or connecting).\n// eventSourceAllowsReport: true if REPORT is supported.\n\n// The read timeout for the stream is a fixed value that is set to be slightly longer than the expected\n// interval between heartbeats from the LaunchDarkly streaming server. If this amount of time elapses\n// with no new data, the connection will be cycled.\nconst streamReadTimeoutMillis = 5 * 60 * 1000; // 5 minutes\nconst maxRetryDelay = 30 * 1000; // Maximum retry delay 30 seconds.\nconst jitterRatio = 0.5; // Delay should be 50%-100% of calculated time.\n\nfunction Stream(platform, config, environment, diagnosticsAccumulator) {\n const baseUrl = config.streamUrl;\n const logger = config.logger;\n const stream = {};\n const evalUrlPrefix = appendUrlPath(baseUrl, '/eval/' + environment);\n const useReport = config.useReport;\n const withReasons = config.evaluationReasons;\n const baseReconnectDelay = config.streamReconnectDelay;\n const headers = getLDHeaders(platform, config);\n let firstConnectionErrorLogged = false;\n let es = null;\n let reconnectTimeoutReference = null;\n let connectionAttemptStartTime;\n let context = null;\n let hash = null;\n let handlers = null;\n let retryCount = 0;\n\n function backoff() {\n const delay = baseReconnectDelay * Math.pow(2, retryCount);\n return delay > maxRetryDelay ? maxRetryDelay : delay;\n }\n\n function jitter(computedDelayMillis) {\n return computedDelayMillis - Math.trunc(Math.random() * jitterRatio * computedDelayMillis);\n }\n\n function getNextRetryDelay() {\n const delay = jitter(backoff());\n retryCount += 1;\n return delay;\n }\n\n stream.connect = function(newContext, newHash, newHandlers) {\n context = newContext;\n hash = newHash;\n handlers = {};\n for (const key in newHandlers || {}) {\n handlers[key] = function(e) {\n // Reset the state for logging the first connection error so that the first\n // connection error following a successful connection will once again be logged.\n // We will decorate *all* handlers to do this to keep this abstraction agnostic\n // for different stream implementations.\n firstConnectionErrorLogged = false;\n logConnectionResult(true);\n newHandlers[key] && newHandlers[key](e);\n };\n }\n tryConnect();\n };\n\n stream.disconnect = function() {\n clearTimeout(reconnectTimeoutReference);\n reconnectTimeoutReference = null;\n closeConnection();\n };\n\n stream.isConnected = function() {\n return !!(es && platform.eventSourceIsActive && platform.eventSourceIsActive(es));\n };\n\n function handleError(err) {\n // The event source may not produce a status. But the LaunchDarkly\n // polyfill can. If we can get the status, then we should stop retrying\n // on certain error codes.\n if (err.status && typeof err.status === 'number' && !isHttpErrorRecoverable(err.status)) {\n // If we encounter an unrecoverable condition, then we do not want to\n // retry anymore.\n closeConnection();\n logger.error(messages.unrecoverableStreamError(err));\n // Ensure any pending retry attempts are not done.\n if (reconnectTimeoutReference) {\n clearTimeout(reconnectTimeoutReference);\n reconnectTimeoutReference = null;\n }\n return;\n }\n\n const delay = getNextRetryDelay();\n\n if (!firstConnectionErrorLogged) {\n logger.warn(messages.streamError(err, delay));\n firstConnectionErrorLogged = true;\n }\n logConnectionResult(false);\n closeConnection();\n tryConnect(delay);\n }\n\n function tryConnect(delay) {\n if (!reconnectTimeoutReference) {\n if (delay) {\n reconnectTimeoutReference = setTimeout(openConnection, delay);\n } else {\n openConnection();\n }\n }\n }\n\n function openConnection() {\n reconnectTimeoutReference = null;\n let url;\n let query = '';\n const options = { headers, readTimeoutMillis: streamReadTimeoutMillis };\n if (platform.eventSourceFactory) {\n if (hash !== null && hash !== undefined) {\n query = 'h=' + hash;\n }\n if (useReport) {\n if (platform.eventSourceAllowsReport) {\n url = evalUrlPrefix;\n options.method = 'REPORT';\n options.headers['Content-Type'] = 'application/json';\n options.body = JSON.stringify(context);\n } else {\n // if we can't do REPORT, fall back to the old ping-based stream\n url = appendUrlPath(baseUrl, '/ping/' + environment);\n query = '';\n }\n } else {\n url = evalUrlPrefix + '/' + base64URLEncode(JSON.stringify(context));\n }\n options.headers = transformHeaders(options.headers, config);\n if (withReasons) {\n query = query + (query ? '&' : '') + 'withReasons=true';\n }\n url = url + (query ? '?' : '') + query;\n\n closeConnection();\n logger.info(messages.streamConnecting(url));\n logConnectionStarted();\n\n es = platform.eventSourceFactory(url, options);\n for (const key in handlers) {\n if (objectHasOwnProperty(handlers, key)) {\n es.addEventListener(key, handlers[key]);\n }\n }\n\n es.onerror = handleError;\n\n es.onopen = () => {\n // If the connection is a success, then reset the retryCount.\n retryCount = 0;\n };\n }\n }\n\n function closeConnection() {\n if (es) {\n logger.info(messages.streamClosing());\n es.close();\n es = null;\n }\n }\n\n function logConnectionStarted() {\n connectionAttemptStartTime = new Date().getTime();\n }\n\n function logConnectionResult(success) {\n if (connectionAttemptStartTime && diagnosticsAccumulator) {\n diagnosticsAccumulator.recordStreamInit(\n connectionAttemptStartTime,\n !success,\n new Date().getTime() - connectionAttemptStartTime\n );\n }\n connectionAttemptStartTime = null;\n }\n\n return stream;\n}\n\nmodule.exports = Stream;\n","// This function allows a series of Promises to be coalesced such that only the most recently\n// added one actually matters. For instance, if several HTTP requests are made to the same\n// endpoint and we want to ensure that whoever made each one always gets the latest data, each\n// can be passed to addPromise (on the same coalescer) and each caller can wait on the\n// coalescer.resultPromise; all three will then receive the result (or error) from the *last*\n// request, and the results of the first two will be discarded.\n//\n// The cancelFn callback, if present, will be called whenever an existing promise is being\n// discarded. This can be used for instance to abort an HTTP request that's now obsolete.\n//\n// The finallyFn callback, if present, is called on completion of the whole thing. This is\n// different from calling coalescer.resultPromise.finally() because it is executed before any\n// other handlers. Its purpose is to tell the caller that this coalescer should no longer be used.\n\nfunction promiseCoalescer(finallyFn) {\n let currentPromise;\n let currentCancelFn;\n let finalResolve;\n let finalReject;\n\n const coalescer = {};\n\n coalescer.addPromise = (p, cancelFn) => {\n currentPromise = p;\n currentCancelFn && currentCancelFn();\n currentCancelFn = cancelFn;\n\n p.then(\n result => {\n if (currentPromise === p) {\n finalResolve(result);\n finallyFn && finallyFn();\n }\n },\n error => {\n if (currentPromise === p) {\n finalReject(error);\n finallyFn && finallyFn();\n }\n }\n );\n };\n\n coalescer.resultPromise = new Promise((resolve, reject) => {\n finalResolve = resolve;\n finalReject = reject;\n });\n\n return coalescer;\n}\n\nmodule.exports = promiseCoalescer;\n","const utils = require('./utils');\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst promiseCoalescer = require('./promiseCoalescer');\nconst { transformHeaders, getLDHeaders } = require('./headers');\n\nconst jsonContentType = 'application/json';\n\nfunction getResponseError(result) {\n if (result.status === 404) {\n return new errors.LDInvalidEnvironmentIdError(messages.environmentNotFound());\n } else {\n return new errors.LDFlagFetchError(messages.errorFetchingFlags(result.statusText || String(result.status)));\n }\n}\n\nfunction Requestor(platform, options, environment) {\n const baseUrl = options.baseUrl;\n const useReport = options.useReport;\n const withReasons = options.evaluationReasons;\n const logger = options.logger;\n\n const requestor = {};\n\n const activeRequests = {}; // map of URLs to promiseCoalescers\n\n function fetchJSON(endpoint, body) {\n if (!platform.httpRequest) {\n return new Promise((resolve, reject) => {\n reject(new errors.LDFlagFetchError(messages.httpUnavailable()));\n });\n }\n\n const method = body ? 'REPORT' : 'GET';\n const headers = getLDHeaders(platform, options);\n if (body) {\n headers['Content-Type'] = jsonContentType;\n }\n\n let coalescer = activeRequests[endpoint];\n if (!coalescer) {\n coalescer = promiseCoalescer(() => {\n // this will be called once there are no more active requests for the same endpoint\n delete activeRequests[endpoint];\n });\n activeRequests[endpoint] = coalescer;\n }\n\n const req = platform.httpRequest(method, endpoint, transformHeaders(headers, options), body);\n const p = req.promise.then(\n result => {\n if (result.status === 200) {\n // We're using substring here because using startsWith would require a polyfill in IE.\n if (\n result.header('content-type') &&\n result.header('content-type').substring(0, jsonContentType.length) === jsonContentType\n ) {\n return JSON.parse(result.body);\n } else {\n const message = messages.invalidContentType(result.header('content-type') || '');\n return Promise.reject(new errors.LDFlagFetchError(message));\n }\n } else {\n return Promise.reject(getResponseError(result));\n }\n },\n e => Promise.reject(new errors.LDFlagFetchError(messages.networkError(e)))\n );\n coalescer.addPromise(p, () => {\n // this will be called if another request for the same endpoint supersedes this one\n req.cancel && req.cancel();\n });\n return coalescer.resultPromise;\n }\n\n // Performs a GET request to an arbitrary path under baseUrl. Returns a Promise which will resolve\n // with the parsed JSON response, or will be rejected if the request failed.\n requestor.fetchJSON = function(path) {\n return fetchJSON(utils.appendUrlPath(baseUrl, path), null);\n };\n\n // Requests the current state of all flags for the given context from LaunchDarkly. Returns a Promise\n // which will resolve with the parsed JSON response, or will be rejected if the request failed.\n requestor.fetchFlagSettings = function(context, hash) {\n let data;\n let endpoint;\n let query = '';\n let body;\n\n if (useReport) {\n endpoint = [baseUrl, '/sdk/evalx/', environment, '/context'].join('');\n body = JSON.stringify(context);\n } else {\n data = utils.base64URLEncode(JSON.stringify(context));\n endpoint = [baseUrl, '/sdk/evalx/', environment, '/contexts/', data].join('');\n }\n if (hash) {\n query = 'h=' + hash;\n }\n if (withReasons) {\n query = query + (query ? '&' : '') + 'withReasons=true';\n }\n endpoint = endpoint + (query ? '?' : '') + query;\n logger.debug(messages.debugPolling(endpoint));\n\n return fetchJSON(endpoint, body);\n };\n\n return requestor;\n}\n\nmodule.exports = Requestor;\n","const utils = require('./utils');\n\nfunction Identity(initialContext, onChange) {\n const ident = {};\n let context;\n\n ident.setContext = function(c) {\n context = utils.sanitizeContext(c);\n if (context && onChange) {\n onChange(utils.clone(context));\n }\n };\n\n ident.getContext = function() {\n return context ? utils.clone(context) : null;\n };\n\n if (initialContext) {\n ident.setContext(initialContext);\n }\n\n return ident;\n}\n\nmodule.exports = Identity;\n","const { v1: uuidv1 } = require('uuid');\nconst { getContextKinds } = require('./context');\n\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst utils = require('./utils');\n\nconst ldUserIdKey = 'ld:$anonUserId';\n\n/**\n * Create an object which can process a context and populate any required keys\n * for anonymous objects.\n *\n * @param {Object} persistentStorage The persistent storage from which to store\n * and access persisted anonymous context keys.\n * @returns An AnonymousContextProcessor.\n */\nfunction AnonymousContextProcessor(persistentStorage) {\n function getContextKeyIdString(kind) {\n if (kind === undefined || kind === null || kind === 'user') {\n return ldUserIdKey;\n }\n return `ld:$contextKey:${kind}`;\n }\n\n function getCachedContextKey(kind) {\n return persistentStorage.get(getContextKeyIdString(kind));\n }\n\n function setCachedContextKey(id, kind) {\n return persistentStorage.set(getContextKeyIdString(kind), id);\n }\n\n /**\n * Process a single kind context, or a single context within a multi-kind context.\n * @param {string} kind The kind of the context. Independent because the kind is not prevent\n * within a context in a multi-kind context.\n * @param {Object} context\n * @returns {Promise} a promise that resolves to a processed contexts, or rejects\n * a context which cannot be processed.\n */\n function processSingleKindContext(kind, context) {\n // We are working on a copy of an original context, so we want to re-assign\n // versus duplicating it again.\n\n /* eslint-disable no-param-reassign */\n if (context.key !== null && context.key !== undefined) {\n context.key = context.key.toString();\n return Promise.resolve(context);\n }\n\n if (context.anonymous) {\n // If the key doesn't exist, then the persistent storage will resolve\n // with undefined.\n return getCachedContextKey(kind).then(cachedId => {\n if (cachedId) {\n context.key = cachedId;\n return context;\n } else {\n const id = uuidv1();\n context.key = id;\n return setCachedContextKey(id, kind).then(() => context);\n }\n });\n } else {\n return Promise.reject(new errors.LDInvalidUserError(messages.invalidContext()));\n }\n /* eslint-enable no-param-reassign */\n }\n\n /**\n * Process the context, returning a Promise that resolves to the processed context, or rejects if there is an error.\n * @param {Object} context\n * @returns {Promise} A promise which resolves to a processed context, or a rejection if the context cannot be\n * processed. The context should still be checked for overall validity after being processed.\n */\n this.processContext = context => {\n if (!context) {\n return Promise.reject(new errors.LDInvalidUserError(messages.contextNotSpecified()));\n }\n\n const processedContext = utils.clone(context);\n\n if (context.kind === 'multi') {\n const kinds = getContextKinds(processedContext);\n\n return Promise.all(kinds.map(kind => processSingleKindContext(kind, processedContext[kind]))).then(\n () => processedContext\n );\n }\n return processSingleKindContext(context.kind, processedContext);\n };\n}\n\nmodule.exports = AnonymousContextProcessor;\n","const { v1: uuidv1 } = require('uuid');\n// Note that in the diagnostic events spec, these IDs are to be generated with UUID v4. However,\n// in JS we were already using v1 for unique context keys, so to avoid bringing in two packages we\n// will use v1 here as well.\n\nconst { baseOptionDefs } = require('./configuration');\nconst messages = require('./messages');\nconst { appendUrlPath } = require('./utils');\n\nfunction DiagnosticId(sdkKey) {\n const ret = {\n diagnosticId: uuidv1(),\n };\n if (sdkKey) {\n ret.sdkKeySuffix = sdkKey.length > 6 ? sdkKey.substring(sdkKey.length - 6) : sdkKey;\n }\n return ret;\n}\n\n// A stateful object holding statistics that will go into diagnostic events.\n\nfunction DiagnosticsAccumulator(startTime) {\n let dataSinceDate, droppedEvents, eventsInLastBatch, streamInits;\n\n function reset(time) {\n dataSinceDate = time;\n droppedEvents = 0;\n eventsInLastBatch = 0;\n streamInits = [];\n }\n\n reset(startTime);\n\n return {\n getProps: () => ({\n dataSinceDate,\n droppedEvents,\n eventsInLastBatch,\n streamInits,\n // omit deduplicatedUsers for the JS SDKs because they don't deduplicate users\n }),\n setProps: props => {\n dataSinceDate = props.dataSinceDate;\n droppedEvents = props.droppedEvents || 0;\n eventsInLastBatch = props.eventsInLastBatch || 0;\n streamInits = props.streamInits || [];\n },\n incrementDroppedEvents: () => {\n droppedEvents++;\n },\n setEventsInLastBatch: n => {\n eventsInLastBatch = n;\n },\n recordStreamInit: (timestamp, failed, durationMillis) => {\n const info = { timestamp, failed, durationMillis };\n streamInits.push(info);\n },\n reset,\n };\n}\n\n// An object that maintains information that will go into diagnostic events, and knows how to format\n// those events. It is instantiated by the SDK client, and shared with the event processor.\n//\n// The JS-based SDKs have two modes for diagnostic events. By default, the behavior is basically the\n// same as the server-side SDKs: a \"diagnostic-init\" event is sent on startup, and then \"diagnostic\"\n// events with operating statistics are sent periodically. However, in a browser environment this is\n// undesirable because the page may be reloaded frequently. In that case, setting the property\n// \"platform.diagnosticUseCombinedEvent\" to true enables an alternate mode in which a combination of\n// both kinds of event is sent at intervals, relative to the last time this was done (if any) which\n// is cached in local storage.\n\nfunction DiagnosticsManager(\n platform,\n persistentStorage,\n accumulator,\n eventSender,\n environmentId,\n config,\n diagnosticId\n) {\n const combinedMode = !!platform.diagnosticUseCombinedEvent;\n const localStorageKey = 'ld:' + environmentId + ':$diagnostics';\n const diagnosticEventsUrl = appendUrlPath(config.eventsUrl, '/events/diagnostic/' + environmentId);\n const periodicInterval = config.diagnosticRecordingInterval;\n const acc = accumulator;\n const initialEventSamplingInterval = 4; // used only in combined mode - see start()\n let streamingEnabled = !!config.streaming;\n let eventSentTime;\n let periodicTimer;\n const manager = {};\n\n function makeInitProperties() {\n return {\n sdk: makeSdkData(),\n configuration: makeConfigData(),\n platform: platform.diagnosticPlatformData,\n };\n }\n\n // Send a diagnostic event and do not wait for completion.\n function sendDiagnosticEvent(event) {\n config.logger && config.logger.debug(messages.debugPostingDiagnosticEvent(event));\n eventSender\n .sendEvents(event, diagnosticEventsUrl, true)\n .then(() => undefined)\n .catch(() => undefined);\n }\n\n function loadProperties(callback) {\n if (!persistentStorage.isEnabled()) {\n return callback(false); // false indicates that local storage is not available\n }\n persistentStorage\n .get(localStorageKey)\n .then(data => {\n if (data) {\n try {\n const props = JSON.parse(data);\n acc.setProps(props);\n eventSentTime = props.dataSinceDate;\n } catch (e) {\n // disregard malformed cached data\n }\n }\n callback(true);\n })\n .catch(() => {\n callback(false);\n });\n }\n\n function saveProperties() {\n if (persistentStorage.isEnabled()) {\n const props = { ...acc.getProps() };\n persistentStorage.set(localStorageKey, JSON.stringify(props));\n }\n }\n\n // Creates the initial event that is sent by the event processor when the SDK starts up. This will not\n // be repeated during the lifetime of the SDK client. In combined mode, we don't send this.\n function createInitEvent() {\n return {\n kind: 'diagnostic-init',\n id: diagnosticId,\n creationDate: acc.getProps().dataSinceDate,\n ...makeInitProperties(),\n };\n }\n\n // Creates a periodic event containing time-dependent stats, and resets the state of the manager with\n // regard to those stats. In combined mode (browser SDK) this also contains the configuration data.\n function createPeriodicEventAndReset() {\n const currentTime = new Date().getTime();\n let ret = {\n kind: combinedMode ? 'diagnostic-combined' : 'diagnostic',\n id: diagnosticId,\n creationDate: currentTime,\n ...acc.getProps(),\n };\n if (combinedMode) {\n ret = { ...ret, ...makeInitProperties() };\n }\n acc.reset(currentTime);\n return ret;\n }\n\n function sendPeriodicEvent() {\n sendDiagnosticEvent(createPeriodicEventAndReset());\n periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval);\n eventSentTime = new Date().getTime();\n if (combinedMode) {\n saveProperties();\n }\n }\n\n function makeSdkData() {\n const sdkData = { ...platform.diagnosticSdkData };\n if (config.wrapperName) {\n sdkData.wrapperName = config.wrapperName;\n }\n if (config.wrapperVersion) {\n sdkData.wrapperVersion = config.wrapperVersion;\n }\n return sdkData;\n }\n\n function makeConfigData() {\n const configData = {\n customBaseURI: config.baseUrl !== baseOptionDefs.baseUrl.default,\n customStreamURI: config.streamUrl !== baseOptionDefs.streamUrl.default,\n customEventsURI: config.eventsUrl !== baseOptionDefs.eventsUrl.default,\n eventsCapacity: config.eventCapacity,\n eventsFlushIntervalMillis: config.flushInterval,\n reconnectTimeMillis: config.streamReconnectDelay,\n streamingDisabled: !streamingEnabled,\n allAttributesPrivate: !!config.allAttributesPrivate,\n diagnosticRecordingIntervalMillis: config.diagnosticRecordingInterval,\n // The following extra properties are only provided by client-side JS SDKs:\n usingSecureMode: !!config.hash,\n bootstrapMode: !!config.bootstrap,\n fetchGoalsDisabled: !config.fetchGoals,\n sendEventsOnlyForVariation: !!config.sendEventsOnlyForVariation,\n };\n // Client-side JS SDKs do not have the following properties which other SDKs have:\n // connectTimeoutMillis\n // pollingIntervalMillis\n // samplingInterval\n // socketTimeoutMillis\n // startWaitMillis\n // userKeysCapacity\n // userKeysFlushIntervalMillis\n // usingProxy\n // usingProxyAuthenticator\n // usingRelayDaemon\n\n return configData;\n }\n\n // Called when the SDK is starting up. Either send an init event immediately, or, in the alternate\n // mode, check for cached local storage properties and send an event only if we haven't done so\n // recently.\n manager.start = () => {\n if (combinedMode) {\n loadProperties(localStorageAvailable => {\n if (localStorageAvailable) {\n const nextEventTime = (eventSentTime || 0) + periodicInterval;\n const timeNow = new Date().getTime();\n if (timeNow >= nextEventTime) {\n sendPeriodicEvent();\n } else {\n periodicTimer = setTimeout(sendPeriodicEvent, nextEventTime - timeNow);\n }\n } else {\n // We don't have the ability to cache anything in local storage, so we don't know if we\n // recently sent an event before this page load, but we would still prefer not to send one\n // on *every* page load. So, as a rough heuristic, we'll decide semi-randomly.\n if (Math.floor(Math.random() * initialEventSamplingInterval) === 0) {\n sendPeriodicEvent();\n } else {\n periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval);\n }\n }\n });\n } else {\n sendDiagnosticEvent(createInitEvent());\n periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval);\n }\n };\n\n manager.stop = () => {\n periodicTimer && clearTimeout(periodicTimer);\n };\n\n // Called when streaming mode is turned on or off dynamically.\n manager.setStreaming = enabled => {\n streamingEnabled = enabled;\n };\n\n return manager;\n}\n\nmodule.exports = {\n DiagnosticId,\n DiagnosticsAccumulator,\n DiagnosticsManager,\n};\n","const messages = require('./messages');\n\n/**\n * Wrap an inspector ensuring that calling its methods are safe.\n * @param {object} inspector Inspector to wrap.\n */\nfunction SafeInspector(inspector, logger) {\n let errorLogged = false;\n const wrapper = {\n type: inspector.type,\n name: inspector.name,\n synchronous: inspector.synchronous,\n };\n\n wrapper.method = (...args) => {\n try {\n inspector.method(...args);\n } catch {\n // If something goes wrong in an inspector we want to log that something\n // went wrong. We don't want to flood the logs, so we only log something\n // the first time that something goes wrong.\n // We do not include the exception in the log, because we do not know what\n // kind of data it may contain.\n if (!errorLogged) {\n errorLogged = true;\n logger.warn(messages.inspectorMethodError(wrapper.type, wrapper.name));\n }\n // Prevent errors.\n }\n };\n\n return wrapper;\n}\n\nmodule.exports = SafeInspector;\n","const messages = require('./messages');\nconst SafeInspector = require('./SafeInspector');\nconst { onNextTick } = require('./utils');\n\n/**\n * The types of supported inspectors.\n */\nconst InspectorTypes = {\n flagUsed: 'flag-used',\n flagDetailsChanged: 'flag-details-changed',\n flagDetailChanged: 'flag-detail-changed',\n clientIdentityChanged: 'client-identity-changed',\n};\n\nObject.freeze(InspectorTypes);\n\n/**\n * Manages dispatching of inspection data to registered inspectors.\n */\nfunction InspectorManager(inspectors, logger) {\n const manager = {};\n\n /**\n * Collection of inspectors keyed by type.\n *\n * Inspectors are async by default.\n *\n * @type {{[type: string]: object[]}}\n */\n const inspectorsByType = {\n [InspectorTypes.flagUsed]: [],\n [InspectorTypes.flagDetailsChanged]: [],\n [InspectorTypes.flagDetailChanged]: [],\n [InspectorTypes.clientIdentityChanged]: [],\n };\n /**\n * Collection synchronous of inspectors keyed by type.\n *\n * @type {{[type: string]: object[]}}\n */\n const synchronousInspectorsByType = {\n [InspectorTypes.flagUsed]: [],\n [InspectorTypes.flagDetailsChanged]: [],\n [InspectorTypes.flagDetailChanged]: [],\n [InspectorTypes.clientIdentityChanged]: [],\n };\n\n const safeInspectors = inspectors && inspectors.map(inspector => SafeInspector(inspector, logger));\n\n safeInspectors &&\n safeInspectors.forEach(safeInspector => {\n // Only add inspectors of supported types.\n if (Object.prototype.hasOwnProperty.call(inspectorsByType, safeInspector.type) && !safeInspector.synchronous) {\n inspectorsByType[safeInspector.type].push(safeInspector);\n } else if (\n Object.prototype.hasOwnProperty.call(synchronousInspectorsByType, safeInspector.type) &&\n safeInspector.synchronous\n ) {\n synchronousInspectorsByType[safeInspector.type].push(safeInspector);\n } else {\n logger.warn(messages.invalidInspector(safeInspector.type, safeInspector.name));\n }\n });\n\n /**\n * Check if there is an inspector of a specific type registered.\n *\n * @param {string} type The type of the inspector to check.\n * @returns True if there are any inspectors of that type registered.\n */\n manager.hasListeners = type =>\n (inspectorsByType[type] && inspectorsByType[type].length) ||\n (synchronousInspectorsByType[type] && synchronousInspectorsByType[type].length);\n\n /**\n * Notify registered inspectors of a flag being used.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {string} flagKey The key for the flag.\n * @param {Object} detail The LDEvaluationDetail for the flag.\n * @param {Object} context The LDContext for the flag.\n */\n manager.onFlagUsed = (flagKey, detail, context) => {\n const type = InspectorTypes.flagUsed;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(flagKey, detail, context));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(flagKey, detail, context));\n });\n }\n };\n\n /**\n * Notify registered inspectors that the flags have been replaced.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {Record} flags The current flags as a Record.\n */\n manager.onFlags = flags => {\n const type = InspectorTypes.flagDetailsChanged;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(flags));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(flags));\n });\n }\n };\n\n /**\n * Notify registered inspectors that a flag value has changed.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {string} flagKey The key for the flag that changed.\n * @param {Object} flag An `LDEvaluationDetail` for the flag.\n */\n manager.onFlagChanged = (flagKey, flag) => {\n const type = InspectorTypes.flagDetailChanged;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(flagKey, flag));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(flagKey, flag));\n });\n }\n };\n\n /**\n * Notify the registered inspectors that the context identity has changed.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param {Object} context The `LDContext` which is now identified.\n */\n manager.onIdentityChanged = context => {\n const type = InspectorTypes.clientIdentityChanged;\n if (synchronousInspectorsByType[type].length) {\n synchronousInspectorsByType[type].forEach(inspector => inspector.method(context));\n }\n if (inspectorsByType[type].length) {\n onNextTick(() => {\n inspectorsByType[type].forEach(inspector => inspector.method(context));\n });\n }\n };\n\n return manager;\n}\n\nmodule.exports = { InspectorTypes, InspectorManager };\n","const { LDTimeoutError } = require('./errors');\n\n/**\n * Returns a promise which errors after t seconds.\n *\n * @param t Timeout in seconds.\n * @param taskName Name of task being timed for logging and error reporting.\n */\nfunction timedPromise(t, taskName) {\n return new Promise((_res, reject) => {\n setTimeout(() => {\n const e = `${taskName} timed out after ${t} seconds.`;\n reject(new LDTimeoutError(e));\n }, t * 1000);\n });\n}\nmodule.exports = timedPromise;\n","const UNKNOWN_HOOK_NAME = 'unknown hook';\nconst BEFORE_EVALUATION_STAGE_NAME = 'beforeEvaluation';\nconst AFTER_EVALUATION_STAGE_NAME = 'afterEvaluation';\nconst BEFORE_IDENTIFY_STAGE_NAME = 'beforeIdentify';\nconst AFTER_IDENTIFY_STAGE_NAME = 'afterIdentify';\nconst AFTER_TRACK_STAGE_NAME = 'afterTrack';\n\n/**\n * Safely executes a hook stage function, logging any errors.\n * @param {{ error: (message: string) => void } | undefined} logger The logger instance.\n * @param {string} method The name of the hook stage being executed (e.g., 'beforeEvaluation').\n * @param {string} hookName The name of the hook.\n * @param {() => any} stage The function representing the hook stage to execute.\n * @param {any} def The default value to return if the stage function throws an error.\n * @returns {any} The result of the stage function, or the default value if an error occurred.\n */\nfunction tryExecuteStage(logger, method, hookName, stage, def) {\n try {\n return stage();\n } catch (err) {\n logger?.error(`An error was encountered in \"${method}\" of the \"${hookName}\" hook: ${err}`);\n return def;\n }\n}\n\n/**\n * Safely gets the name of a hook from its metadata.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {{ getMetadata: () => { name?: string } }} hook The hook instance.\n * @returns {string} The name of the hook, or 'unknown hook' if unable to retrieve it.\n */\nfunction getHookName(logger, hook) {\n try {\n return hook.getMetadata().name || UNKNOWN_HOOK_NAME;\n } catch {\n logger.error(`Exception thrown getting metadata for hook. Unable to get hook name.`);\n return UNKNOWN_HOOK_NAME;\n }\n}\n\n/**\n * Executes the 'beforeEvaluation' stage for all registered hooks.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ beforeEvaluation?: (hookContext: object, data: object) => object }>} hooks The array of hook instances.\n * @param {{ flagKey: string, context: object, defaultValue: any }} hookContext The context for the evaluation series.\n * @returns {Array} An array containing the data returned by each hook's 'beforeEvaluation' stage.\n */\nfunction executeBeforeEvaluation(logger, hooks, hookContext) {\n return hooks.map(hook =>\n tryExecuteStage(\n logger,\n BEFORE_EVALUATION_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.beforeEvaluation?.(hookContext, {}) ?? {},\n {}\n )\n );\n}\n\n/**\n * Executes the 'afterEvaluation' stage for all registered hooks in reverse order.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ afterEvaluation?: (hookContext: object, data: object, result: object) => object }>} hooks The array of hook instances.\n * @param {{ flagKey: string, context: object, defaultValue: any }} hookContext The context for the evaluation series.\n * @param {Array} updatedData The data collected from the 'beforeEvaluation' stages.\n * @param {{ value: any, variationIndex?: number, reason?: object }} result The result of the flag evaluation.\n * @returns {void}\n */\nfunction executeAfterEvaluation(logger, hooks, hookContext, updatedData, result) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = updatedData[hookIndex];\n tryExecuteStage(\n logger,\n AFTER_EVALUATION_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.afterEvaluation?.(hookContext, data, result) ?? {},\n {}\n );\n }\n}\n\n/**\n * Executes the 'beforeIdentify' stage for all registered hooks.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ beforeIdentify?: (hookContext: object, data: object) => object }>} hooks The array of hook instances.\n * @param {{ context: object, timeout?: number }} hookContext The context for the identify series.\n * @returns {Array} An array containing the data returned by each hook's 'beforeIdentify' stage.\n */\nfunction executeBeforeIdentify(logger, hooks, hookContext) {\n return hooks.map(hook =>\n tryExecuteStage(\n logger,\n BEFORE_IDENTIFY_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.beforeIdentify?.(hookContext, {}) ?? {},\n {}\n )\n );\n}\n\n/**\n * Executes the 'afterIdentify' stage for all registered hooks in reverse order.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ afterIdentify?: (hookContext: object, data: object, result: object) => object }>} hooks The array of hook instances.\n * @param {{ context: object, timeout?: number }} hookContext The context for the identify series.\n * @param {Array} updatedData The data collected from the 'beforeIdentify' stages.\n * @param {{ status: string }} result The result of the identify operation.\n * @returns {void}\n */\nfunction executeAfterIdentify(logger, hooks, hookContext, updatedData, result) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = updatedData[hookIndex];\n tryExecuteStage(\n logger,\n AFTER_IDENTIFY_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.afterIdentify?.(hookContext, data, result) ?? {},\n {}\n );\n }\n}\n\n/**\n * Executes the 'afterTrack' stage for all registered hooks in reverse order.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array<{ afterTrack?: (hookContext: { context: object, data: object, metricValue: number }) => void }>} hooks The array of hook instances.\n * @param {{ context: object, data: object, metricValue: number }} hookContext The context for the track operation.\n * @returns {void}\n */\nfunction executeAfterTrack(logger, hooks, hookContext) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n tryExecuteStage(\n logger,\n AFTER_TRACK_STAGE_NAME,\n getHookName(logger, hook),\n () => hook?.afterTrack?.(hookContext),\n undefined\n );\n }\n}\n\n/**\n * Factory function to create a HookRunner instance.\n * Manages the execution of hooks for flag evaluations and identify operations.\n * @param {{ error: (message: string) => void }} logger The logger instance.\n * @param {Array | undefined} initialHooks An optional array of hooks to initialize with.\n * @returns {{\n * withEvaluation: (key: string, context: object, defaultValue: any, method: () => { value: any, variationIndex?: number, reason?: object }) => { value: any, variationIndex?: number, reason?: object },\n * identify: (context: object, timeout?: number) => (result: { status: string }) => void,\n * addHook: (hook: object) => void\n * }} The hook runner object with methods to manage and execute hooks.\n */\nfunction createHookRunner(logger, initialHooks) {\n // Use local variable instead of instance property\n const hooksInternal = initialHooks ? [...initialHooks] : [];\n\n /**\n * Wraps a flag evaluation method with before/after hook stages.\n * @param {string} key The flag key.\n * @param {object} context The evaluation context.\n * @param {any} defaultValue The default value for the flag.\n * @param {() => { value: any, variationIndex?: number, reason?: object }} method The function that performs the actual flag evaluation.\n * @returns {{ value: any, variationIndex?: number, reason?: object }} The result of the flag evaluation.\n */\n function withEvaluation(key, context, defaultValue, method) {\n if (hooksInternal.length === 0) {\n return method();\n }\n const hooks = [...hooksInternal];\n /** @type {{ flagKey: string, context: object, defaultValue: any }} */\n const hookContext = {\n flagKey: key,\n context,\n defaultValue,\n };\n\n // Use the logger passed into the factory\n const hookData = executeBeforeEvaluation(logger, hooks, hookContext);\n const result = method();\n executeAfterEvaluation(logger, hooks, hookContext, hookData, result);\n return result;\n }\n\n /**\n * Wraps the identify operation with before/after hook stages.\n * Executes the 'beforeIdentify' stage immediately and returns a function\n * to execute the 'afterIdentify' stage later.\n * @param {object} context The context being identified.\n * @param {number | undefined} timeout Optional timeout for the identify operation.\n * @returns {(result: { status: string }) => void} A function to call after the identify operation completes.\n */\n function identify(context, timeout) {\n const hooks = [...hooksInternal];\n /** @type {{ context: object, timeout?: number }} */\n const hookContext = {\n context,\n timeout,\n };\n // Use the logger passed into the factory\n const hookData = executeBeforeIdentify(logger, hooks, hookContext);\n /**\n * Executes the 'afterIdentify' hook stage.\n * @param {{ status: string }} result The result of the identify operation.\n */\n return result => {\n executeAfterIdentify(logger, hooks, hookContext, hookData, result);\n };\n }\n\n /**\n * Adds a new hook to the runner.\n * @param {object} hook The hook instance to add.\n * @returns {void}\n */\n function addHook(hook) {\n // Mutate the internal hooks array\n hooksInternal.push(hook);\n }\n\n /**\n * Executes the 'afterTrack' stage for all registered hooks in reverse order.\n * @param {{ context: object, data: object, metricValue: number }} hookContext The context for the track operation.\n * @returns {void}\n */\n function afterTrack(hookContext) {\n if (hooksInternal.length === 0) {\n return;\n }\n const hooks = [...hooksInternal];\n executeAfterTrack(logger, hooks, hookContext);\n }\n\n return {\n withEvaluation,\n identify,\n addHook,\n afterTrack,\n };\n}\n\nmodule.exports = createHookRunner;\n","const UNKNOWN_PLUGIN_NAME = 'unknown plugin';\n\n/**\n * Safely gets the name of a plugin with error handling\n * @param {{ error: (message: string) => void }} logger - The logger instance\n * @param {{getMetadata: () => {name: string}}} plugin - Plugin object that may have a name property\n * @returns {string} The plugin name or 'unknown' if not available\n */\nfunction getPluginName(logger, plugin) {\n try {\n return plugin.getMetadata().name || UNKNOWN_PLUGIN_NAME;\n } catch (error) {\n logger.error(`Exception thrown getting metadata for plugin. Unable to get plugin name.`);\n return UNKNOWN_PLUGIN_NAME;\n }\n}\n\n/**\n * Safely retrieves hooks from plugins with error handling\n * @param {Object} logger - The logger instance\n * @param {Object} environmentMetadata - Metadata about the environment for plugin initialization\n * @param {Array<{getHooks: (environmentMetadata: object) => Hook[]}>} plugins - Array of plugin objects that may implement getHooks\n * @returns {Array} Array of hook objects collected from all plugins\n */\nfunction getPluginHooks(logger, environmentMetadata, plugins) {\n const hooks = [];\n plugins.forEach(plugin => {\n try {\n const pluginHooks = plugin.getHooks?.(environmentMetadata);\n if (pluginHooks === undefined) {\n logger.error(`Plugin ${getPluginName(logger, plugin)} returned undefined from getHooks.`);\n } else if (pluginHooks && pluginHooks.length > 0) {\n hooks.push(...pluginHooks);\n }\n } catch (error) {\n logger.error(`Exception thrown getting hooks for plugin ${getPluginName(logger, plugin)}. Unable to get hooks.`);\n }\n });\n return hooks;\n}\n\n/**\n * Registers plugins with the SDK\n * @param {{ error: (message: string) => void }} logger - The logger instance\n * @param {Object} environmentMetadata - Metadata about the environment for plugin initialization\n * @param {Object} client - The SDK client instance\n * @param {Array<{register: (client: object, environmentMetadata: object) => void}>} plugins - Array of plugin objects that implement register\n */\nfunction registerPlugins(logger, environmentMetadata, client, plugins) {\n plugins.forEach(plugin => {\n try {\n plugin.register(client, environmentMetadata);\n } catch (error) {\n logger.error(`Exception thrown registering plugin ${getPluginName(logger, plugin)}.`);\n }\n });\n}\n\n/**\n * Creates a plugin environment object\n * @param {{userAgent: string, version: string}} platform - The platform object\n * @param {string} env - The environment\n * @param {{application: {name: string, version: string}, wrapperName: string, wrapperVersion: string}} options - The options\n * @returns {{sdk: {name: string, version: string, wrapperName: string, wrapperVersion: string}, application: {name: string, version: string}, clientSideId: string}} The plugin environment\n */\nfunction createPluginEnvironment(platform, env, options) {\n const pluginSdkMetadata = {};\n\n if (platform.userAgent) {\n pluginSdkMetadata.name = platform.userAgent;\n }\n if (platform.version) {\n pluginSdkMetadata.version = platform.version;\n }\n if (options.wrapperName) {\n pluginSdkMetadata.wrapperName = options.wrapperName;\n }\n if (options.wrapperVersion) {\n pluginSdkMetadata.wrapperVersion = options.wrapperVersion;\n }\n\n const pluginApplicationMetadata = {};\n\n if (options.application) {\n if (options.application.name) {\n pluginApplicationMetadata.name = options.application.name;\n }\n if (options.application.version) {\n pluginApplicationMetadata.version = options.application.version;\n }\n }\n\n const pluginEnvironment = {\n sdk: pluginSdkMetadata,\n clientSideId: env,\n };\n\n if (Object.keys(pluginApplicationMetadata).length > 0) {\n pluginEnvironment.application = pluginApplicationMetadata;\n }\n\n return pluginEnvironment;\n}\n\nmodule.exports = {\n getPluginHooks,\n registerPlugins,\n createPluginEnvironment,\n};\n","const EventProcessor = require('./EventProcessor');\nconst EventEmitter = require('./EventEmitter');\nconst EventSender = require('./EventSender');\nconst InitializationStateTracker = require('./InitializationState');\nconst PersistentFlagStore = require('./PersistentFlagStore');\nconst PersistentStorage = require('./PersistentStorage');\nconst Stream = require('./Stream');\nconst Requestor = require('./Requestor');\nconst Identity = require('./Identity');\nconst AnonymousContextProcessor = require('./AnonymousContextProcessor');\nconst configuration = require('./configuration');\nconst diagnostics = require('./diagnosticEvents');\nconst { commonBasicLogger } = require('./loggers');\nconst utils = require('./utils');\nconst errors = require('./errors');\nconst messages = require('./messages');\nconst { checkContext, getContextKeys } = require('./context');\nconst { InspectorTypes, InspectorManager } = require('./InspectorManager');\nconst timedPromise = require('./timedPromise');\nconst createHookRunner = require('./HookRunner');\nconst { getPluginHooks, registerPlugins, createPluginEnvironment } = require('./plugins');\nconst changeEvent = 'change';\nconst internalChangeEvent = 'internal-change';\nconst highTimeoutThreshold = 5;\n\n// This is called by the per-platform initialize functions to create the base client object that we\n// may also extend with additional behavior. It returns an object with these properties:\n// client: the actual client object\n// options: the configuration (after any appropriate defaults have been applied)\n// If we need to give the platform-specific clients access to any internals here, we should add those\n// as properties of the return object, not public properties of the client.\n//\n// For definitions of the API in the platform object, see stubPlatform.js in the test code.\n\nfunction initialize(env, context, specifiedOptions, platform, extraOptionDefs) {\n const logger = createLogger();\n const emitter = EventEmitter(logger);\n const initializationStateTracker = InitializationStateTracker(emitter);\n const options = configuration.validate(specifiedOptions, emitter, extraOptionDefs, logger);\n const inspectorManager = InspectorManager(options.inspectors, logger);\n const sendEvents = options.sendEvents;\n let environment = env;\n let hash = options.hash;\n const plugins = [...options.plugins];\n\n const pluginEnvironment = createPluginEnvironment(platform, env, options);\n\n const pluginHooks = getPluginHooks(logger, pluginEnvironment, plugins);\n\n const hookRunner = createHookRunner(logger, [...options.hooks, ...pluginHooks]);\n\n const persistentStorage = PersistentStorage(platform.localStorage, logger);\n\n const eventSender = EventSender(platform, environment, options);\n\n const diagnosticsEnabled = options.sendEvents && !options.diagnosticOptOut;\n const diagnosticId = diagnosticsEnabled ? diagnostics.DiagnosticId(environment) : null;\n const diagnosticsAccumulator = diagnosticsEnabled ? diagnostics.DiagnosticsAccumulator(new Date().getTime()) : null;\n const diagnosticsManager = diagnosticsEnabled\n ? diagnostics.DiagnosticsManager(\n platform,\n persistentStorage,\n diagnosticsAccumulator,\n eventSender,\n environment,\n options,\n diagnosticId\n )\n : null;\n\n const stream = Stream(platform, options, environment, diagnosticsAccumulator);\n\n const events =\n options.eventProcessor ||\n EventProcessor(platform, options, environment, diagnosticsAccumulator, emitter, eventSender);\n\n const requestor = Requestor(platform, options, environment);\n\n let flags = {};\n let useLocalStorage;\n let streamActive;\n let streamForcedState = options.streaming;\n let subscribedToChangeEvents;\n let inited = false;\n let closed = false;\n let firstEvent = true;\n\n // The \"stateProvider\" object is used in the Electron SDK, to allow one client instance to take partial\n // control of another. If present, it has the following contract:\n // - getInitialState() returns the initial client state if it is already available. The state is an\n // object whose properties are \"environment\", \"context\", and \"flags\".\n // - on(\"init\", listener) triggers an event when the initial client state becomes available, passing\n // the state object to the listener.\n // - on(\"update\", listener) triggers an event when flag values change and/or the current context changes.\n // The parameter is an object that *may* contain \"context\" and/or \"flags\".\n // - enqueueEvent(event) accepts an analytics event object and returns true if the stateProvider will\n // be responsible for delivering it, or false if we still should deliver it ourselves.\n const stateProvider = options.stateProvider;\n\n const ident = Identity(null, onIdentifyChange);\n const anonymousContextProcessor = new AnonymousContextProcessor(persistentStorage);\n const persistentFlagStore = persistentStorage.isEnabled()\n ? PersistentFlagStore(persistentStorage, environment, hash, ident, logger)\n : null;\n\n function createLogger() {\n if (specifiedOptions && specifiedOptions.logger) {\n return specifiedOptions.logger;\n }\n return (extraOptionDefs && extraOptionDefs.logger && extraOptionDefs.logger.default) || commonBasicLogger('warn');\n }\n\n function readFlagsFromBootstrap(data) {\n // If the bootstrap data came from an older server-side SDK, we'll have just a map of keys to values.\n // Newer SDKs that have an allFlagsState method will provide an extra \"$flagsState\" key that contains\n // the rest of the metadata we want. We do it this way for backward compatibility with older JS SDKs.\n const keys = Object.keys(data);\n const metadataKey = '$flagsState';\n const validKey = '$valid';\n const metadata = data[metadataKey];\n if (!metadata && keys.length) {\n logger.warn(messages.bootstrapOldFormat());\n }\n if (data[validKey] === false) {\n logger.warn(messages.bootstrapInvalid());\n }\n const ret = {};\n keys.forEach(key => {\n if (key !== metadataKey && key !== validKey) {\n let flag = { value: data[key] };\n if (metadata && metadata[key]) {\n flag = utils.extend(flag, metadata[key]);\n } else {\n flag.version = 0;\n }\n ret[key] = flag;\n }\n });\n return ret;\n }\n\n function shouldEnqueueEvent() {\n return sendEvents && !closed && !platform.isDoNotTrack();\n }\n\n function enqueueEvent(event) {\n if (!environment) {\n // We're in paired mode and haven't been initialized with an environment or context yet\n return;\n }\n if (stateProvider && stateProvider.enqueueEvent && stateProvider.enqueueEvent(event)) {\n return; // it'll be handled elsewhere\n }\n\n if (!event.context) {\n if (firstEvent) {\n logger.warn(messages.eventWithoutContext());\n firstEvent = false;\n }\n return;\n }\n firstEvent = false;\n\n if (shouldEnqueueEvent()) {\n logger.debug(messages.debugEnqueueingEvent(event.kind));\n events.enqueue(event);\n }\n }\n\n function notifyInspectionFlagUsed(key, detail) {\n if (inspectorManager.hasListeners(InspectorTypes.flagUsed)) {\n inspectorManager.onFlagUsed(key, detail, ident.getContext());\n }\n }\n\n function notifyInspectionIdentityChanged() {\n if (inspectorManager.hasListeners(InspectorTypes.clientIdentityChanged)) {\n inspectorManager.onIdentityChanged(ident.getContext());\n }\n }\n\n function notifyInspectionFlagChanged(data, newFlag) {\n if (inspectorManager.hasListeners(InspectorTypes.flagDetailChanged)) {\n inspectorManager.onFlagChanged(data.key, getFlagDetail(newFlag));\n }\n }\n\n function notifyInspectionFlagsChanged() {\n if (inspectorManager.hasListeners(InspectorTypes.flagDetailsChanged)) {\n inspectorManager.onFlags(\n Object.entries(flags)\n .map(([key, value]) => ({ key, detail: getFlagDetail(value) }))\n .reduce((acc, cur) => {\n // eslint-disable-next-line no-param-reassign\n acc[cur.key] = cur.detail;\n return acc;\n }, {})\n );\n }\n }\n\n function onIdentifyChange(context) {\n sendIdentifyEvent(context);\n notifyInspectionIdentityChanged();\n }\n\n function sendIdentifyEvent(context) {\n if (stateProvider) {\n // In paired mode, the other client is responsible for sending identify events\n return;\n }\n if (context) {\n enqueueEvent({\n kind: 'identify',\n context,\n creationDate: new Date().getTime(),\n });\n }\n }\n\n function sendFlagEvent(key, detail, defaultValue, includeReason) {\n const context = ident.getContext();\n const now = new Date();\n const value = detail ? detail.value : null;\n\n const event = {\n kind: 'feature',\n key: key,\n context,\n value: value,\n variation: detail ? detail.variationIndex : null,\n default: defaultValue,\n creationDate: now.getTime(),\n };\n const flag = flags[key];\n if (flag) {\n event.version = flag.flagVersion ? flag.flagVersion : flag.version;\n event.trackEvents = flag.trackEvents;\n event.debugEventsUntilDate = flag.debugEventsUntilDate;\n }\n if ((includeReason || (flag && flag.trackReason)) && detail) {\n event.reason = detail.reason;\n }\n\n enqueueEvent(event);\n }\n\n function verifyContext(context) {\n // The context will already have been processed to have a string key, so we\n // do not need to allow for legacy keys in the check.\n if (checkContext(context, false)) {\n return Promise.resolve(context);\n } else {\n return Promise.reject(new errors.LDInvalidUserError(messages.invalidContext()));\n }\n }\n\n function identify(context, newHash, onDone) {\n if (closed) {\n return utils.wrapPromiseCallback(Promise.resolve({}), onDone);\n }\n if (stateProvider) {\n // We're being controlled by another client instance, so only that instance is allowed to change the context\n logger.warn(messages.identifyDisabled());\n return utils.wrapPromiseCallback(Promise.resolve(utils.transformVersionedValuesToValues(flags)), onDone);\n }\n let afterIdentify;\n const clearFirst = useLocalStorage && persistentFlagStore ? persistentFlagStore.clearFlags() : Promise.resolve();\n return utils.wrapPromiseCallback(\n clearFirst\n .then(() => anonymousContextProcessor.processContext(context))\n .then(verifyContext)\n .then(context => {\n afterIdentify = utils.once(hookRunner.identify(context, undefined));\n return context;\n })\n .then(validatedContext =>\n requestor\n .fetchFlagSettings(validatedContext, newHash)\n // the following then() is nested within this one so we can use realUser from the previous closure\n .then(requestedFlags => {\n const flagValueMap = utils.transformVersionedValuesToValues(requestedFlags);\n ident.setContext(validatedContext);\n hash = newHash;\n if (requestedFlags) {\n return replaceAllFlags(requestedFlags).then(() => flagValueMap);\n } else {\n return flagValueMap;\n }\n })\n )\n .then(flagValueMap => {\n afterIdentify?.({ status: 'completed' });\n if (streamActive) {\n connectStream();\n }\n return flagValueMap;\n })\n .catch(err => {\n afterIdentify?.({ status: 'error' });\n emitter.maybeReportError(err);\n return Promise.reject(err);\n }),\n onDone\n );\n }\n\n function getContext() {\n return ident.getContext();\n }\n\n function flush(onDone) {\n return utils.wrapPromiseCallback(sendEvents ? events.flush() : Promise.resolve(), onDone);\n }\n\n function variation(key, defaultValue) {\n const { value } = hookRunner.withEvaluation(key, ident.getContext(), defaultValue, () =>\n variationDetailInternal(key, defaultValue, true, false, false, true)\n );\n return value;\n }\n\n function variationDetail(key, defaultValue) {\n return hookRunner.withEvaluation(key, ident.getContext(), defaultValue, () =>\n variationDetailInternal(key, defaultValue, true, true, false, true)\n );\n }\n\n function variationDetailInternal(key, defaultValue, sendEvent, includeReasonInEvent, isAllFlags, notifyInspection) {\n let detail;\n let flag;\n\n if (flags && utils.objectHasOwnProperty(flags, key) && flags[key] && !flags[key].deleted) {\n flag = flags[key];\n detail = getFlagDetail(flag);\n if (flag.value === null || flag.value === undefined) {\n detail.value = defaultValue;\n }\n } else {\n detail = { value: defaultValue, variationIndex: null, reason: { kind: 'ERROR', errorKind: 'FLAG_NOT_FOUND' } };\n }\n\n if (sendEvent) {\n // For an all-flags evaluation, with events enabled, each flag will get an event, so we do not\n // need to duplicate the prerequisites.\n if (!isAllFlags) {\n flag?.prerequisites?.forEach(key => {\n variationDetailInternal(key, undefined, sendEvent, false, false, false);\n });\n }\n sendFlagEvent(key, detail, defaultValue, includeReasonInEvent);\n }\n\n // For the all flags case `onFlags` will be called instead.\n if (!isAllFlags && notifyInspection) {\n notifyInspectionFlagUsed(key, detail);\n }\n\n return detail;\n }\n\n function getFlagDetail(flag) {\n return {\n value: flag.value,\n variationIndex: flag.variation === undefined ? null : flag.variation,\n reason: flag.reason || null,\n };\n // Note, the logic above ensures that variationIndex and reason will always be null rather than\n // undefined if we don't have values for them. That's just to avoid subtle errors that depend on\n // whether an object was JSON-encoded with null properties omitted or not.\n }\n\n function allFlags() {\n const results = {};\n\n if (!flags) {\n return results;\n }\n\n for (const key in flags) {\n if (utils.objectHasOwnProperty(flags, key) && !flags[key].deleted) {\n results[key] = variationDetailInternal(\n key,\n null,\n !options.sendEventsOnlyForVariation,\n false,\n true,\n false\n ).value;\n }\n }\n\n return results;\n }\n\n function userContextKind(user) {\n return user.anonymous ? 'anonymousUser' : 'user';\n }\n\n function track(key, data, metricValue) {\n if (typeof key !== 'string') {\n emitter.maybeReportError(new errors.LDInvalidEventKeyError(messages.unknownCustomEventKey(key)));\n return;\n }\n if (metricValue !== undefined && typeof metricValue !== 'number') {\n logger.warn(messages.invalidMetricValue(typeof metricValue));\n }\n\n // The following logic was used only for the JS browser SDK (js-client-sdk) and\n // is no longer needed as of version 2.9.13 of that SDK. The other client-side\n // JS-based SDKs did not define customEventFilter, and now none of them do. We\n // can remove this in the next major version of the common code, when it's OK to\n // make breaking changes to our internal API contracts.\n if (platform.customEventFilter && !platform.customEventFilter(key)) {\n logger.warn(messages.unknownCustomEventKey(key));\n }\n\n const context = ident.getContext();\n const e = {\n kind: 'custom',\n key: key,\n context,\n url: platform.getCurrentUrl(),\n creationDate: new Date().getTime(),\n };\n if (context && context.anonymous) {\n e.contextKind = userContextKind(context);\n }\n // Note, check specifically for null/undefined because it is legal to set these fields to a falsey value.\n if (data !== null && data !== undefined) {\n e.data = data;\n }\n if (metricValue !== null && metricValue !== undefined) {\n e.metricValue = metricValue;\n }\n enqueueEvent(e);\n hookRunner.afterTrack({ context, key, data, metricValue });\n }\n\n function connectStream() {\n streamActive = true;\n if (!ident.getContext()) {\n return;\n }\n const tryParseData = jsonData => {\n try {\n return JSON.parse(jsonData);\n } catch (err) {\n emitter.maybeReportError(new errors.LDInvalidDataError(messages.invalidData()));\n return undefined;\n }\n };\n stream.connect(ident.getContext(), hash, {\n ping: function() {\n logger.debug(messages.debugStreamPing());\n const contextAtTimeOfPingEvent = ident.getContext();\n requestor\n .fetchFlagSettings(contextAtTimeOfPingEvent, hash)\n .then(requestedFlags => {\n // Check whether the current context is still the same - we don't want to overwrite the flags if\n // the application has called identify() while this request was in progress\n if (utils.deepEquals(contextAtTimeOfPingEvent, ident.getContext())) {\n replaceAllFlags(requestedFlags || {});\n }\n })\n .catch(err => {\n emitter.maybeReportError(new errors.LDFlagFetchError(messages.errorFetchingFlags(err)));\n });\n },\n put: function(e) {\n const data = tryParseData(e.data);\n if (!data) {\n return;\n }\n logger.debug(messages.debugStreamPut());\n replaceAllFlags(data);\n // Don't wait for this Promise to be resolved; note that replaceAllFlags is guaranteed\n // never to have an unhandled rejection\n },\n patch: function(e) {\n const data = tryParseData(e.data);\n if (!data) {\n return;\n }\n // If both the flag and the patch have a version property, then the patch version must be\n // greater than the flag version for us to accept the patch. If either one has no version\n // then the patch always succeeds.\n const oldFlag = flags[data.key];\n if (!oldFlag || !oldFlag.version || !data.version || oldFlag.version < data.version) {\n logger.debug(messages.debugStreamPatch(data.key));\n const mods = {};\n const newFlag = utils.extend({}, data);\n delete newFlag['key'];\n flags[data.key] = newFlag;\n const newDetail = getFlagDetail(newFlag);\n if (oldFlag) {\n mods[data.key] = { previous: oldFlag.value, current: newDetail };\n } else {\n mods[data.key] = { current: newDetail };\n }\n notifyInspectionFlagChanged(data, newFlag);\n handleFlagChanges(mods); // don't wait for this Promise to be resolved\n } else {\n logger.debug(messages.debugStreamPatchIgnored(data.key));\n }\n },\n delete: function(e) {\n const data = tryParseData(e.data);\n if (!data) {\n return;\n }\n if (!flags[data.key] || flags[data.key].version < data.version) {\n logger.debug(messages.debugStreamDelete(data.key));\n const mods = {};\n if (flags[data.key] && !flags[data.key].deleted) {\n mods[data.key] = { previous: flags[data.key].value };\n }\n flags[data.key] = { version: data.version, deleted: true };\n notifyInspectionFlagChanged(data, flags[data.key]);\n handleFlagChanges(mods); // don't wait for this Promise to be resolved\n } else {\n logger.debug(messages.debugStreamDeleteIgnored(data.key));\n }\n },\n });\n }\n\n function disconnectStream() {\n if (streamActive) {\n stream.disconnect();\n streamActive = false;\n }\n }\n\n // Returns a Promise which will be resolved when we have completely updated the internal flags state,\n // dispatched all change events, and updated local storage if appropriate. This Promise is guaranteed\n // never to have an unhandled rejection.\n function replaceAllFlags(newFlags) {\n const changes = {};\n\n if (!newFlags) {\n return Promise.resolve();\n }\n\n for (const key in flags) {\n if (utils.objectHasOwnProperty(flags, key) && flags[key]) {\n if (newFlags[key] && !utils.deepEquals(newFlags[key].value, flags[key].value)) {\n changes[key] = { previous: flags[key].value, current: getFlagDetail(newFlags[key]) };\n } else if (!newFlags[key] || newFlags[key].deleted) {\n changes[key] = { previous: flags[key].value };\n }\n }\n }\n for (const key in newFlags) {\n if (utils.objectHasOwnProperty(newFlags, key) && newFlags[key] && (!flags[key] || flags[key].deleted)) {\n changes[key] = { current: getFlagDetail(newFlags[key]) };\n }\n }\n\n flags = { ...newFlags };\n\n notifyInspectionFlagsChanged();\n\n return handleFlagChanges(changes).catch(() => {}); // swallow any exceptions from this Promise\n }\n\n // Returns a Promise which will be resolved when we have dispatched all change events and updated\n // local storage if appropriate.\n function handleFlagChanges(changes) {\n const keys = Object.keys(changes);\n\n if (keys.length > 0) {\n const changeEventParams = {};\n keys.forEach(key => {\n const current = changes[key].current;\n const value = current ? current.value : undefined;\n const previous = changes[key].previous;\n emitter.emit(changeEvent + ':' + key, value, previous);\n changeEventParams[key] = current ? { current: value, previous: previous } : { previous: previous };\n });\n\n emitter.emit(changeEvent, changeEventParams);\n emitter.emit(internalChangeEvent, flags);\n\n // By default, we send feature evaluation events whenever we have received new flag values -\n // the client has in effect evaluated these flags just by receiving them. This can be suppressed\n // by setting \"sendEventsOnlyForVariation\". Also, if we have a stateProvider, we don't send these\n // events because we assume they have already been sent by the other client that gave us the flags\n // (when it received them in the first place).\n if (!options.sendEventsOnlyForVariation && !stateProvider) {\n keys.forEach(key => {\n sendFlagEvent(key, changes[key].current);\n });\n }\n }\n\n if (useLocalStorage && persistentFlagStore) {\n return persistentFlagStore.saveFlags(flags);\n } else {\n return Promise.resolve();\n }\n }\n\n function on(event, handler, context) {\n if (isChangeEventKey(event)) {\n subscribedToChangeEvents = true;\n if (inited) {\n updateStreamingState();\n }\n emitter.on(event, handler, context);\n } else {\n emitter.on(...arguments);\n }\n }\n\n function off(event) {\n emitter.off(...arguments);\n if (isChangeEventKey(event)) {\n let haveListeners = false;\n emitter.getEvents().forEach(key => {\n if (isChangeEventKey(key) && emitter.getEventListenerCount(key) > 0) {\n haveListeners = true;\n }\n });\n if (!haveListeners) {\n subscribedToChangeEvents = false;\n if (streamActive && streamForcedState === undefined) {\n disconnectStream();\n }\n }\n }\n }\n\n function setStreaming(state) {\n const newState = state === null ? undefined : state;\n if (newState !== streamForcedState) {\n streamForcedState = newState;\n updateStreamingState();\n }\n }\n\n function updateStreamingState() {\n const shouldBeStreaming = streamForcedState || (subscribedToChangeEvents && streamForcedState === undefined);\n if (shouldBeStreaming && !streamActive) {\n connectStream();\n } else if (!shouldBeStreaming && streamActive) {\n disconnectStream();\n }\n if (diagnosticsManager) {\n diagnosticsManager.setStreaming(shouldBeStreaming);\n }\n }\n\n function isChangeEventKey(event) {\n return event === changeEvent || event.substr(0, changeEvent.length + 1) === changeEvent + ':';\n }\n\n if (typeof options.bootstrap === 'string' && options.bootstrap.toUpperCase() === 'LOCALSTORAGE') {\n if (persistentFlagStore) {\n useLocalStorage = true;\n } else {\n logger.warn(messages.localStorageUnavailable());\n }\n }\n\n if (typeof options.bootstrap === 'object') {\n // Set the flags as soon as possible before we get into any async code, so application code can read\n // them even if the ready event has not yet fired.\n flags = readFlagsFromBootstrap(options.bootstrap);\n }\n\n if (stateProvider) {\n // The stateProvider option is used in the Electron SDK, to allow a client instance in the main process\n // to control another client instance (i.e. this one) in the renderer process. We can't predict which\n // one will start up first, so the initial state may already be available for us or we may have to wait\n // to receive it.\n const state = stateProvider.getInitialState();\n if (state) {\n initFromStateProvider(state);\n } else {\n stateProvider.on('init', initFromStateProvider);\n }\n stateProvider.on('update', updateFromStateProvider);\n } else {\n finishInit().catch(signalFailedInit);\n }\n\n function finishInit() {\n if (!env) {\n return Promise.reject(new errors.LDInvalidEnvironmentIdError(messages.environmentNotSpecified()));\n }\n let afterIdentify;\n return anonymousContextProcessor\n .processContext(context)\n .then(verifyContext)\n .then(context => {\n afterIdentify = utils.once(hookRunner.identify(context, undefined));\n return context;\n })\n .then(validatedContext => {\n afterIdentify?.({ status: 'completed' });\n ident.setContext(validatedContext);\n if (typeof options.bootstrap === 'object') {\n // flags have already been set earlier\n return signalSuccessfulInit();\n } else if (useLocalStorage) {\n return finishInitWithLocalStorage();\n } else {\n return finishInitWithPolling();\n }\n })\n .catch(err => {\n afterIdentify?.({ status: 'error' });\n throw err;\n });\n }\n\n function finishInitWithLocalStorage() {\n return persistentFlagStore.loadFlags().then(storedFlags => {\n if (storedFlags === null || storedFlags === undefined) {\n flags = {};\n return requestor\n .fetchFlagSettings(ident.getContext(), hash)\n .then(requestedFlags => replaceAllFlags(requestedFlags || {}))\n .then(signalSuccessfulInit)\n .catch(err => {\n const initErr = new errors.LDFlagFetchError(messages.errorFetchingFlags(err));\n signalFailedInit(initErr);\n });\n } else {\n // We're reading the flags from local storage. Signal that we're ready,\n // then update localStorage for the next page load. We won't signal changes or update\n // the in-memory flags unless you subscribe for changes\n flags = storedFlags;\n utils.onNextTick(signalSuccessfulInit);\n\n return requestor\n .fetchFlagSettings(ident.getContext(), hash)\n .then(requestedFlags => replaceAllFlags(requestedFlags))\n .catch(err => emitter.maybeReportError(err));\n }\n });\n }\n\n function finishInitWithPolling() {\n return requestor\n .fetchFlagSettings(ident.getContext(), hash)\n .then(requestedFlags => {\n flags = requestedFlags || {};\n\n notifyInspectionFlagsChanged();\n // Note, we don't need to call updateSettings here because local storage and change events are not relevant\n signalSuccessfulInit();\n })\n .catch(err => {\n flags = {};\n signalFailedInit(err);\n });\n }\n\n function initFromStateProvider(state) {\n environment = state.environment;\n ident.setContext(state.context);\n flags = { ...state.flags };\n utils.onNextTick(signalSuccessfulInit);\n }\n\n function updateFromStateProvider(state) {\n if (state.context) {\n ident.setContext(state.context);\n }\n if (state.flags) {\n replaceAllFlags(state.flags); // don't wait for this Promise to be resolved\n }\n }\n\n function signalSuccessfulInit() {\n logger.info(messages.clientInitialized());\n inited = true;\n updateStreamingState();\n initializationStateTracker.signalSuccess();\n }\n\n function signalFailedInit(err) {\n initializationStateTracker.signalFailure(err);\n }\n\n function start() {\n if (sendEvents) {\n if (diagnosticsManager) {\n diagnosticsManager.start();\n }\n events.start();\n }\n }\n\n function close(onDone) {\n if (closed) {\n return utils.wrapPromiseCallback(Promise.resolve(), onDone);\n }\n const finishClose = () => {\n closed = true;\n flags = {};\n };\n const p = Promise.resolve()\n .then(() => {\n disconnectStream();\n if (diagnosticsManager) {\n diagnosticsManager.stop();\n }\n if (sendEvents) {\n events.stop();\n return events.flush();\n }\n })\n .then(finishClose)\n .catch(finishClose);\n return utils.wrapPromiseCallback(p, onDone);\n }\n\n function getFlagsInternal() {\n // used by Electron integration\n return flags;\n }\n\n function waitForInitializationWithTimeout(timeout) {\n if (timeout > highTimeoutThreshold) {\n logger.warn(\n 'The waitForInitialization function was called with a timeout greater than ' +\n `${highTimeoutThreshold} seconds. We recommend a timeout of ` +\n `${highTimeoutThreshold} seconds or less.`\n );\n }\n\n const initPromise = initializationStateTracker.getInitializationPromise();\n const timeoutPromise = timedPromise(timeout, 'waitForInitialization');\n\n return Promise.race([timeoutPromise, initPromise]).catch(e => {\n if (e instanceof errors.LDTimeoutError) {\n logger.error(`waitForInitialization error: ${e}`);\n }\n throw e;\n });\n }\n\n function waitForInitialization(timeout = undefined) {\n if (timeout !== undefined && timeout !== null) {\n if (typeof timeout === 'number') {\n return waitForInitializationWithTimeout(timeout);\n }\n logger.warn('The waitForInitialization method was provided with a non-numeric timeout.');\n }\n logger.warn(\n 'The waitForInitialization function was called without a timeout specified.' +\n ' In a future version a default timeout will be applied.'\n );\n return initializationStateTracker.getInitializationPromise();\n }\n\n function addHook(hook) {\n hookRunner.addHook(hook);\n }\n\n const client = {\n waitForInitialization,\n waitUntilReady: () => initializationStateTracker.getReadyPromise(),\n identify: identify,\n getContext: getContext,\n variation: variation,\n variationDetail: variationDetail,\n track: track,\n on: on,\n off: off,\n setStreaming: setStreaming,\n flush: flush,\n allFlags: allFlags,\n close: close,\n addHook: addHook,\n };\n\n registerPlugins(logger, pluginEnvironment, client, plugins);\n\n return {\n client: client, // The client object containing all public methods.\n options: options, // The validated configuration object, including all defaults.\n emitter: emitter, // The event emitter which can be used to log errors or trigger events.\n ident: ident, // The Identity object that manages the current context.\n logger: logger, // The logging abstraction.\n requestor: requestor, // The Requestor object.\n start: start, // Starts the client once the environment is ready.\n enqueueEvent: enqueueEvent, // Puts an analytics event in the queue, if event sending is enabled.\n getFlagsInternal: getFlagsInternal, // Returns flag data structure with all details.\n getEnvironmentId: () => environment, // Gets the environment ID (this may have changed since initialization, if we have a state provider)\n internalChangeEventName: internalChangeEvent, // This event is triggered whenever we have new flag state.\n };\n}\n\nmodule.exports = {\n initialize,\n commonBasicLogger,\n errors,\n messages,\n utils,\n getContextKeys,\n};\n","const { commonBasicLogger } = require('launchdarkly-js-sdk-common');\n\nfunction basicLogger(options) {\n return commonBasicLogger({ destination: console.log, ...options });\n}\n\nmodule.exports = {\n basicLogger,\n};\n","function isSyncXhrSupported() {\n // This is temporary logic to disable synchronous XHR in Chrome 73 and above. In all other browsers,\n // we will assume it is supported. See https://github.com/launchdarkly/js-client-sdk/issues/147\n const userAgent = window.navigator && window.navigator.userAgent;\n if (userAgent) {\n const chromeMatch = userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./);\n if (chromeMatch) {\n const version = parseInt(chromeMatch[2], 10);\n return version < 73;\n }\n }\n return true;\n}\n\nconst emptyResult = { promise: Promise.resolve({ status: 200, header: () => null, body: null }) };\n\nexport default function newHttpRequest(method, url, headers, body, pageIsClosing) {\n if (pageIsClosing) {\n // When the page is about to close, we have to use synchronous XHR (until we migrate to sendBeacon).\n // But not all browsers support this.\n if (!isSyncXhrSupported()) {\n return emptyResult;\n // Note that we return a fake success response, because we don't want the request to be retried in this case.\n }\n }\n\n const xhr = new window.XMLHttpRequest();\n xhr.open(method, url, !pageIsClosing);\n for (const key in headers || {}) {\n if (Object.prototype.hasOwnProperty.call(headers, key)) {\n xhr.setRequestHeader(key, headers[key]);\n }\n }\n if (pageIsClosing) {\n try {\n xhr.send(body); // We specified synchronous mode when we called xhr.open\n } catch (e) {\n // do nothing intentionally to suppress noise for now\n }\n return emptyResult; // Again, we never want a request to be retried in this case, so we must say it succeeded.\n } else {\n let cancelled;\n const p = new Promise((resolve, reject) => {\n xhr.addEventListener('load', () => {\n if (cancelled) {\n return;\n }\n resolve({\n status: xhr.status,\n header: (key) => xhr.getResponseHeader(key),\n body: xhr.responseText,\n });\n });\n xhr.addEventListener('error', () => {\n if (cancelled) {\n return;\n }\n reject(new Error());\n });\n xhr.send(body);\n });\n const cancel = () => {\n cancelled = true;\n xhr.abort();\n };\n return { promise: p, cancel: cancel };\n }\n}\n","'use strict';\n\nmodule.exports = string => {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a \\unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n};\n","import escapeStringRegexp from 'escape-string-regexp';\n\nexport function doesUrlMatch(matcher, href, search, hash) {\n const keepHash = (matcher.kind === 'substring' || matcher.kind === 'regex') && hash.includes('/');\n const canonicalUrl = (keepHash ? href : href.replace(hash, '')).replace(search, '');\n\n let regex;\n let testUrl;\n\n switch (matcher.kind) {\n case 'exact':\n testUrl = href;\n regex = new RegExp('^' + escapeStringRegexp(matcher.url) + '/?$');\n break;\n case 'canonical':\n testUrl = canonicalUrl;\n regex = new RegExp('^' + escapeStringRegexp(matcher.url) + '/?$');\n break;\n case 'substring':\n testUrl = canonicalUrl;\n regex = new RegExp('.*' + escapeStringRegexp(matcher.substring) + '.*$');\n break;\n case 'regex':\n testUrl = canonicalUrl;\n regex = new RegExp(matcher.pattern);\n break;\n default:\n return false;\n }\n return regex.test(testUrl);\n}\n\nfunction findGoalsForClick(event, clickGoals) {\n const matches = [];\n\n for (let i = 0; i < clickGoals.length; i++) {\n let target = event.target;\n const goal = clickGoals[i];\n const selector = goal.selector;\n const elements = document.querySelectorAll(selector);\n while (target && elements.length > 0) {\n for (let j = 0; j < elements.length; j++) {\n if (target === elements[j]) {\n matches.push(goal);\n }\n }\n target = target.parentNode;\n }\n }\n\n return matches;\n}\n\nexport default function GoalTracker(goals, onEvent) {\n const tracker = {};\n let listenerFn = null;\n\n const clickGoals = [];\n\n for (let i = 0; i < goals.length; i++) {\n const goal = goals[i];\n const urls = goal.urls || [];\n\n for (let j = 0; j < urls.length; j++) {\n if (doesUrlMatch(urls[j], window.location.href, window.location.search, window.location.hash)) {\n if (goal.kind === 'pageview') {\n onEvent('pageview', goal);\n } else {\n clickGoals.push(goal);\n onEvent('click_pageview', goal);\n }\n break;\n }\n }\n }\n\n if (clickGoals.length > 0) {\n listenerFn = function (event) {\n const goals = findGoalsForClick(event, clickGoals);\n for (let i = 0; i < goals.length; i++) {\n onEvent('click', goals[i]);\n }\n };\n\n document.addEventListener('click', listenerFn);\n }\n\n tracker.dispose = function () {\n document.removeEventListener('click', listenerFn);\n };\n\n return tracker;\n}\n","import * as common from 'launchdarkly-js-sdk-common';\nimport GoalTracker from './GoalTracker';\n\nconst locationWatcherInterval = 300;\n\nexport default function GoalManager(clientVars, readyCallback) {\n let goals;\n let goalTracker;\n\n const ret = {};\n\n function getGoalsPath() {\n return '/sdk/goals/' + clientVars.getEnvironmentId();\n }\n\n function refreshGoalTracker() {\n if (goalTracker) {\n goalTracker.dispose();\n }\n if (goals && goals.length) {\n goalTracker = GoalTracker(goals, sendGoalEvent);\n }\n }\n\n function sendGoalEvent(kind, goal) {\n const context = clientVars.ident.getContext();\n const event = {\n kind: kind,\n key: goal.key,\n data: null,\n url: window.location.href,\n creationDate: new Date().getTime(),\n context: context,\n };\n\n if (kind === 'click') {\n event.selector = goal.selector;\n }\n\n return clientVars.enqueueEvent(event);\n }\n\n function watchLocation(interval, callback) {\n let previousUrl = window.location.href;\n let currentUrl;\n\n function checkUrl() {\n currentUrl = window.location.href;\n\n if (currentUrl !== previousUrl) {\n previousUrl = currentUrl;\n callback();\n }\n }\n\n function poll(fn, interval) {\n fn();\n setTimeout(() => {\n poll(fn, interval);\n }, interval);\n }\n\n poll(checkUrl, interval);\n\n if (window.history && window.history.pushState) {\n window.addEventListener('popstate', checkUrl);\n } else {\n window.addEventListener('hashchange', checkUrl);\n }\n }\n\n clientVars.requestor\n .fetchJSON(getGoalsPath())\n .then((g) => {\n if (g && g.length > 0) {\n goals = g;\n goalTracker = GoalTracker(goals, sendGoalEvent);\n watchLocation(locationWatcherInterval, refreshGoalTracker);\n }\n readyCallback();\n })\n .catch((err) => {\n clientVars.emitter.maybeReportError(\n new common.errors.LDUnexpectedResponseError('Error fetching goals: ' + (err && err.message) ? err.message : err)\n );\n readyCallback();\n });\n\n return ret;\n}\n","import * as common from 'launchdarkly-js-sdk-common';\nimport * as importBasicLogger from './basicLogger';\nimport browserPlatform from './browserPlatform';\nimport GoalManager from './GoalManager';\n\nconst goalsEvent = 'goalsReady';\nconst extraOptionDefs = {\n fetchGoals: { default: true },\n hash: { type: 'string' },\n eventProcessor: { type: 'object' }, // used only in tests\n eventUrlTransformer: { type: 'function' },\n disableSyncEventPost: { default: false },\n};\n\n// Pass our platform object to the common code to create the browser version of the client\nexport function initialize(env, user, options = {}) {\n const platform = browserPlatform(options);\n const clientVars = common.initialize(env, user, options, platform, extraOptionDefs);\n\n const client = clientVars.client;\n const validatedOptions = clientVars.options;\n const emitter = clientVars.emitter;\n\n const goalsPromise = new Promise((resolve) => {\n const onGoals = emitter.on(goalsEvent, () => {\n emitter.off(goalsEvent, onGoals);\n resolve();\n });\n });\n client.waitUntilGoalsReady = () => goalsPromise;\n\n if (validatedOptions.fetchGoals) {\n GoalManager(clientVars, () => emitter.emit(goalsEvent));\n // Don't need to save a reference to the GoalManager - its constructor takes care of setting\n // up the necessary event wiring\n } else {\n emitter.emit(goalsEvent);\n }\n\n if (document.readyState !== 'complete') {\n window.addEventListener('load', clientVars.start);\n } else {\n clientVars.start();\n }\n\n const syncFlush = () => {\n // Synchronous events are not available in all browsers, but where they\n // are we should attempt to use them. This increases the chance of the events\n // being delivered.\n platform.synchronousFlush = true;\n client.flush().catch(() => {});\n platform.synchronousFlush = false;\n };\n\n // When the visibility of the page changes to hidden we want to flush any pending events.\n //\n // This is handled with visibility, instead of beforeunload/unload\n // because those events are not compatible with the bfcache and are unlikely\n // to be called in many situations. For more information see: https://developer.chrome.com/blog/page-lifecycle-api/\n //\n // Redundancy is included by using both the visibilitychange handler as well as\n // pagehide, because different browsers, and versions have different bugs with each.\n // This also may provide more opportunity for the events to get flushed.\n //\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'hidden') {\n syncFlush();\n }\n };\n\n document.addEventListener('visibilitychange', handleVisibilityChange);\n window.addEventListener('pagehide', syncFlush);\n\n return client;\n}\n\nexport const basicLogger = importBasicLogger.basicLogger;\n\nexport const createConsoleLogger = common.createConsoleLogger;\n\nexport const version = VERSION;\n\nfunction deprecatedInitialize(env, user, options = {}) {\n console && console.warn && console.warn(common.messages.deprecated('default export', 'named LDClient export')); // eslint-disable-line no-console\n return initialize(env, user, options);\n}\n\nexport default { initialize: deprecatedInitialize, version };\n","import newHttpRequest from './httpRequest';\n\nexport default function makeBrowserPlatform(options) {\n const ret = {\n userAgentHeaderName: 'X-LaunchDarkly-User-Agent',\n };\n\n ret.synchronousFlush = false; // this will be set to true by index.js if the page is hidden\n\n // XMLHttpRequest may not exist if we're running in a server-side rendering context\n if (window.XMLHttpRequest) {\n const disableSyncFlush = options && options.disableSyncEventPost;\n ret.httpRequest = (method, url, headers, body) => {\n const syncFlush = ret.synchronousFlush & !disableSyncFlush;\n ret.synchronousFlush = false;\n return newHttpRequest(method, url, headers, body, syncFlush);\n };\n }\n\n let hasCors;\n ret.httpAllowsPost = () => {\n // We compute this lazily because calling XMLHttpRequest() at initialization time can disrupt tests\n if (hasCors === undefined) {\n hasCors = window.XMLHttpRequest ? 'withCredentials' in new window.XMLHttpRequest() : false;\n }\n return hasCors;\n };\n\n // Image-based mechanism for sending events if POST isn't available\n ret.httpFallbackPing = (url) => {\n const img = new window.Image();\n img.src = url;\n };\n\n const eventUrlTransformer = options && options.eventUrlTransformer;\n ret.getCurrentUrl = () => (eventUrlTransformer ? eventUrlTransformer(window.location.href) : window.location.href);\n\n ret.isDoNotTrack = () => {\n let flag;\n if (window.navigator && window.navigator.doNotTrack !== undefined) {\n flag = window.navigator.doNotTrack; // FF, Chrome\n } else if (window.navigator && window.navigator.msDoNotTrack !== undefined) {\n flag = window.navigator.msDoNotTrack; // IE 9/10\n } else {\n flag = window.doNotTrack; // IE 11+, Safari\n }\n return flag === 1 || flag === true || flag === '1' || flag === 'yes';\n };\n\n try {\n if (window.localStorage) {\n ret.localStorage = {\n get: (key) =>\n new Promise((resolve) => {\n resolve(window.localStorage.getItem(key));\n }),\n set: (key, value) =>\n new Promise((resolve) => {\n window.localStorage.setItem(key, value);\n resolve();\n }),\n clear: (key) =>\n new Promise((resolve) => {\n window.localStorage.removeItem(key);\n resolve();\n }),\n };\n }\n } catch (e) {\n // In some browsers (such as Chrome), even looking at window.localStorage at all will cause a\n // security error if the feature is disabled.\n ret.localStorage = null;\n }\n\n // The browser built-in EventSource implementations do not support setting the method used for\n // the request. When useReport is true, we ensure sending the user in the body of a REPORT request\n // rather than in the URL path. If a polyfill for EventSource that supports setting the request\n // method is provided (currently, launchdarkly-eventsource is the only polyfill that both supports\n // it and gives us a way to *know* that it supports it), we use the polyfill to connect to a flag\n // stream that will provide evaluated flags for the specific user. Otherwise, when useReport is\n // true, we fall back to a generic 'ping' stream that informs the SDK to make a separate REPORT\n // request for the user's flag evaluations whenever the flag definitions have been updated.\n let eventSourceConstructor;\n const useReport = options && options.useReport;\n if (\n useReport &&\n typeof window.EventSourcePolyfill === 'function' &&\n window.EventSourcePolyfill.supportedOptions &&\n window.EventSourcePolyfill.supportedOptions.method\n ) {\n ret.eventSourceAllowsReport = true;\n eventSourceConstructor = window.EventSourcePolyfill;\n } else {\n ret.eventSourceAllowsReport = false;\n eventSourceConstructor = window.EventSource;\n }\n\n // If EventSource does not exist, the absence of eventSourceFactory will make us not try to open streams\n if (window.EventSource) {\n const timeoutMillis = 300000; // this is only used by polyfills - see below\n\n ret.eventSourceFactory = (url, options) => {\n // The standard EventSource constructor doesn't take any options, just a URL. However, some\n // EventSource polyfills allow us to specify a timeout interval, and in some cases they will\n // default to a too-short timeout if we don't specify one. So, here, we are setting the\n // timeout properties that are used by several popular polyfills.\n // Also, the skipDefaultHeaders property (if supported) tells the polyfill not to add the\n // Cache-Control header that can cause CORS problems in browsers.\n // See: https://github.com/launchdarkly/js-eventsource\n const defaultOptions = {\n heartbeatTimeout: timeoutMillis,\n silentTimeout: timeoutMillis,\n skipDefaultHeaders: true,\n };\n\n const esOptions = { ...defaultOptions, ...options };\n\n return new eventSourceConstructor(url, esOptions);\n };\n\n ret.eventSourceIsActive = (es) =>\n es.readyState === window.EventSource.OPEN || es.readyState === window.EventSource.CONNECTING;\n }\n\n ret.userAgent = 'JSClient';\n ret.version = VERSION;\n\n ret.diagnosticSdkData = {\n name: 'js-client-sdk',\n version: VERSION,\n };\n\n ret.diagnosticPlatformData = {\n name: 'JS',\n };\n\n ret.diagnosticUseCombinedEvent = true; // the browser SDK uses the \"diagnostic-combined\" event format\n\n return ret;\n}\n"],"names":["createCustomError","name","CustomError","message","code","Error","captureStackTrace","this","constructor","prototype","LDUnexpectedResponseError","LDInvalidEnvironmentIdError","LDInvalidUserError","LDInvalidEventKeyError","LDInvalidArgumentError","LDFlagFetchError","errors","LDInvalidDataError","LDTimeoutError","isHttpErrorRecoverable","status","byteLength_1","b64","lens","getLens","validLen","placeHoldersLen","toByteArray_1","tmp","i","arr","Arr","_byteLength","curByte","len","revLookup","charCodeAt","fromByteArray_1","uint8","length","extraBytes","parts","maxChunkLength","len2","push","encodeChunk","lookup","join","Uint8Array","Array","indexOf","start","end","num","output","isArray","keyList","Object","keys","hasProp","hasOwnProperty","fastDeepEqual","equal","a","b","key","arrA","arrB","dateA","Date","dateB","getTime","regexpA","RegExp","regexpB","toString","call","userAttrsToStringify","btoa","s","escaped","unescape","encodeURIComponent","base64","fromByteArray","stringToBytes","objectHasOwnProperty","object","getRandomValues","utils","appendUrlPath","baseUrl","path","endsWith","substring","startsWith","base64URLEncode","replace","clone","obj","JSON","parse","stringify","deepEquals","extend","objects","reduce","acc","getLDUserAgentString","platform","version","userAgent","onNextTick","cb","setTimeout","sanitizeContext","context","newContext","kind","undefined","forEach","attr","value","String","transformValuesToVersionedValues","flags","ret","transformVersionedValuesToValues","flagsState","wrapPromiseCallback","promise","callback","then","error","Promise","reject","once","func","result","called","args","apply","rnds8","rng","crypto","bind","msCrypto","REGEX","validate","uuid","test","_nodeId","_clockseq","byteToHex","substr","offset","arguments","toLowerCase","TypeError","_lastMSecs","_lastNSecs","v","parseInt","slice","v35","hashfunc","generateUUID","namespace","buf","str","bytes","set","err","DNS","URL","getOutputLength","inputLength8","safeAdd","x","y","lsw","md5cmn","q","t","cnt","md5ff","c","d","md5gg","md5hh","md5ii","v3","msg","input","length32","hexTab","hex","charAt","md5ToHexEncodedArray","olda","oldb","oldc","oldd","wordsToMd5","length8","Uint32Array","bytesToWords","v3$1","f","z","ROTL","n","v5","K","H","l","N","Math","ceil","M","_i","j","pow","floor","_i2","W","_t","e","_t2","T","v5$1","options","node","clockseq","seedBytes","random","msecs","now","nsecs","dt","tl","tmh","rnds","logLevels","loggers","commonBasicLogger","formatFn","destination","toConsole","methodName","line","console","destinations","prependLevelToMessage","prefix","minLevel","level","write","levelIndex","levelName","fullPrefix","tempArgs","log","logger","validateLogger","errorString","docLink","messages","bootstrapInvalid","bootstrapOldFormat","clientInitialized","clientNotReady","debugEnqueueingEvent","debugPostingDiagnosticEvent","event","debugPostingEvents","count","debugStreamDelete","debugStreamDeleteIgnored","debugStreamPatch","debugStreamPatchIgnored","debugStreamPing","debugPolling","url","debugStreamPut","deprecated","oldName","newName","environmentNotFound","environmentNotSpecified","errorFetchingFlags","eventCapacityExceeded","eventWithoutContext","httpErrorMessage","retryMessage","httpUnavailable","identifyDisabled","inspectorMethodError","type","invalidContentType","contentType","invalidData","invalidInspector","invalidKey","invalidMetricValue","badType","invalidContext","invalidTagValue","localStorageUnavailable","networkError","optionBelowMinimum","minimum","streamClosing","streamConnecting","streamError","streamReconnectDelay","tagValueTooLong","unknownCustomEventKey","unknownOption","contextNotSpecified","unrecoverableStreamError","wrongOptionType","expectedType","actualType","wrongOptionTypeBoolean","require$$0","baseOptionDefs","default","streamUrl","eventsUrl","sendEvents","streaming","sendLDHeaders","requestHeaderTransform","sendEventsOnlyForVariation","useReport","evaluationReasons","eventCapacity","flushInterval","samplingInterval","allAttributesPrivate","privateAttributes","bootstrap","diagnosticRecordingInterval","diagnosticOptOut","wrapperName","wrapperVersion","stateProvider","application","validator","validated","id","validateTagValue","inspectors","hooks","plugins","allowedTagCharacters","canonicalizeUrl","tagValue","match","warn","configuration","emitter","extraOptionDefs","optionDefs","deprecatedOptions","reportArgumentError","maybeReportError","config","opts","checkDeprecatedOptions","applyDefaults","typeDescForValue","optionDef","allowedTypes","split","validateTypesAndNames","getTags","tags","headers","getLDHeaders","h","userAgentHeaderName","tagKeys","sort","map","flattened","item","concat","transformHeaders","v1","uuidv1","require$$1","EventSender_1","environmentId","baseHeaders","sender","events","isDiagnostic","httpRequest","resolve","jsonBody","payloadId","doPostRequest","canRetry","dateStr","header","time","serverTime","getResponseInfo","catch","canonicalize_1","canonicalize","visited","includes","filter","validKind","encodeKey","checkContext","allowLegacyKey","kindValid","keyValid","kinds","every","contextKey","getContextKeys","user","entries","getContextKinds","getCanonicalKey","EventSummarizer_1","es","startDate","endDate","counters","contextKinds","summarizeEvent","counterKey","variation","counterVal","Set","contextKeys","getKinds","add","creationDate","getSummary","flagsOut","empty","values","flag","counterOut","unknown","features","clearSummary","MultiEventSummarizer_1","contextFilter","summarizers","contexts","summarizer","EventSummarizer","getSummaries","summarizersToFlush","contextsForSummaries","summary","processEscapeCharacters","getComponents","reference","component","isLiteral","compare","aIsLiteral","bIsLiteral","bComponents","aComponents","literalToReference","literal","attributeReference","cloneExcluding","target","references","stack","cloned","excluded","ptr","source","parent","pop","some","ContextFilter_1","protectedAttributes","legacyTopLevelCopyAttributes","filterSingleKind","redactAnonymous","AttributeReference","anonymous","_meta","protectedAttr","getAttributesToFilter","redactedAttributes","filtered","custom","privateAttributeNames","legacyToSingleKind","filteredContext","filterMultiKind","EventProcessor_1","diagnosticsAccumulator","processor","eventSender","EventSender","mainEventsUrl","ContextFilter","MultiEventSummarizer","flushTimer","queue","lastKnownPastTime","disabled","exceededCapacity","shouldSampleEvent","makeOutputEvent","addToOutbox","incrementDroppedEvents","enqueue","addFullEvent","addDebugEvent","trackEvents","debugEventsUntilDate","debugEvent","flush","async","eventsToSend","setEventsInLastBatch","debug","responseInfo","flushTick","stop","clearTimeout","EventEmitter_1","on","handler","off","emit","copiedHandlers","getEvents","getEventListenerCount","readyEvent","successEvent","failureEvent","InitializationState","eventEmitter","succeeded","failed","failureValue","initializationPromise","readyPromise","onReady","getInitializationPromise","onSuccess","onFailure","getReadyPromise","signalSuccess","signalFailure","PersistentFlagStore_1","storage","environment","hash","ident","store","getFlagsKey","getContext","loadFlags","get","dataStr","data","schema","$schema","ex","clearFlags","saveFlags","clear","PersistentStorage_1","localStorageProvider","loggedError","logError","isEnabled","require$$2","Stream_1","stream","evalUrlPrefix","withReasons","baseReconnectDelay","connectionAttemptStartTime","firstConnectionErrorLogged","reconnectTimeoutReference","handlers","retryCount","getNextRetryDelay","delay","computedDelayMillis","backoff","trunc","handleError","closeConnection","logConnectionResult","tryConnect","openConnection","query","readTimeoutMillis","eventSourceFactory","eventSourceAllowsReport","method","body","info","addEventListener","onerror","onopen","close","success","recordStreamInit","connect","newHash","newHandlers","disconnect","isConnected","eventSourceIsActive","promiseCoalescer_1","finallyFn","currentPromise","currentCancelFn","finalResolve","finalReject","coalescer","p","cancelFn","resultPromise","jsonContentType","Requestor_1","requestor","activeRequests","fetchJSON","endpoint","promiseCoalescer","req","statusText","getResponseError","addPromise","cancel","fetchFlagSettings","Identity_1","initialContext","onChange","setContext","AnonymousContextProcessor_1","persistentStorage","getContextKeyIdString","processSingleKindContext","getCachedContextKey","cachedId","setCachedContextKey","processContext","processedContext","all","diagnosticEvents","DiagnosticId","sdkKey","diagnosticId","sdkKeySuffix","DiagnosticsAccumulator","startTime","dataSinceDate","droppedEvents","eventsInLastBatch","streamInits","reset","getProps","setProps","props","timestamp","durationMillis","DiagnosticsManager","accumulator","combinedMode","diagnosticUseCombinedEvent","localStorageKey","diagnosticEventsUrl","periodicInterval","eventSentTime","periodicTimer","streamingEnabled","manager","makeInitProperties","sdk","makeSdkData","makeConfigData","diagnosticPlatformData","sendDiagnosticEvent","sendPeriodicEvent","currentTime","createPeriodicEventAndReset","saveProperties","sdkData","diagnosticSdkData","customBaseURI","customStreamURI","customEventsURI","eventsCapacity","eventsFlushIntervalMillis","reconnectTimeMillis","streamingDisabled","diagnosticRecordingIntervalMillis","usingSecureMode","bootstrapMode","fetchGoalsDisabled","fetchGoals","loadProperties","localStorageAvailable","nextEventTime","timeNow","setStreaming","enabled","SafeInspector_1","inspector","errorLogged","wrapper","synchronous","InspectorTypes","flagUsed","flagDetailsChanged","flagDetailChanged","clientIdentityChanged","freeze","InspectorManager_1","InspectorManager","inspectorsByType","synchronousInspectorsByType","safeInspectors","SafeInspector","safeInspector","hasListeners","onFlagUsed","flagKey","detail","onFlags","onFlagChanged","onIdentityChanged","timedPromise_1","taskName","_res","UNKNOWN_HOOK_NAME","tryExecuteStage","hookName","stage","def","getHookName","hook","getMetadata","HookRunner","initialHooks","hooksInternal","withEvaluation","defaultValue","hookContext","hookData","beforeEvaluation","executeBeforeEvaluation","updatedData","hookIndex","afterEvaluation","executeAfterEvaluation","identify","timeout","beforeIdentify","executeBeforeIdentify","afterIdentify","executeAfterIdentify","addHook","afterTrack","executeAfterTrack","UNKNOWN_PLUGIN_NAME","getPluginName","plugin","getPluginHooks","environmentMetadata","pluginHooks","getHooks","registerPlugins","client","register","createPluginEnvironment","env","pluginSdkMetadata","pluginApplicationMetadata","pluginEnvironment","clientSideId","require$$3","changeEvent","internalChangeEvent","src","initialize","specifiedOptions","createLogger","EventEmitter","initializationStateTracker","InitializationStateTracker","inspectorManager","hookRunner","createHookRunner","PersistentStorage","localStorage","diagnosticsEnabled","diagnostics","diagnosticsManager","Stream","eventProcessor","EventProcessor","Requestor","useLocalStorage","streamActive","subscribedToChangeEvents","streamForcedState","inited","closed","firstEvent","Identity","enqueueEvent","sendIdentifyEvent","anonymousContextProcessor","AnonymousContextProcessor","persistentFlagStore","PersistentFlagStore","isDoNotTrack","notifyInspectionFlagChanged","newFlag","getFlagDetail","notifyInspectionFlagsChanged","cur","sendFlagEvent","includeReason","variationIndex","flagVersion","trackReason","reason","verifyContext","variationDetailInternal","sendEvent","includeReasonInEvent","isAllFlags","notifyInspection","deleted","errorKind","prerequisites","notifyInspectionFlagUsed","connectStream","tryParseData","jsonData","ping","contextAtTimeOfPingEvent","requestedFlags","replaceAllFlags","put","patch","oldFlag","mods","newDetail","previous","current","handleFlagChanges","delete","disconnectStream","newFlags","changes","changeEventParams","updateStreamingState","shouldBeStreaming","isChangeEventKey","toUpperCase","metadataKey","validKey","metadata","readFlagsFromBootstrap","state","getInitialState","initFromStateProvider","validatedContext","signalSuccessfulInit","storedFlags","signalFailedInit","finishInit","waitForInitialization","initPromise","timeoutPromise","timedPromise","race","waitForInitializationWithTimeout","waitUntilReady","onDone","clearFirst","flagValueMap","variationDetail","track","metricValue","customEventFilter","getCurrentUrl","contextKind","haveListeners","newState","allFlags","results","finishClose","getFlagsInternal","getEnvironmentId","internalChangeEventName","_objectSpread","emptyResult","newHttpRequest","pageIsClosing","window","navigator","chromeMatch","isSyncXhrSupported","xhr","XMLHttpRequest","open","setRequestHeader","send","cancelled","getResponseHeader","responseText","abort","escapeStringRegexp","string","doesUrlMatch","matcher","href","search","regex","testUrl","canonicalUrl","pattern","GoalTracker","goals","onEvent","tracker","listenerFn","clickGoals","goal","urls","location","matches","selector","elements","document","querySelectorAll","parentNode","findGoalsForClick","dispose","removeEventListener","GoalManager","clientVars","readyCallback","goalTracker","refreshGoalTracker","sendGoalEvent","g","interval","currentUrl","previousUrl","checkUrl","poll","fn","history","pushState","watchLocation","common","goalsEvent","eventUrlTransformer","disableSyncEventPost","hasCors","disableSyncFlush","syncFlush","synchronousFlush","httpAllowsPost","httpFallbackPing","Image","eventSourceConstructor","doNotTrack","msDoNotTrack","getItem","setItem","removeItem","EventSourcePolyfill","supportedOptions","EventSource","timeoutMillis","esOptions","defaultOptions","heartbeatTimeout","silentTimeout","skipDefaultHeaders","readyState","OPEN","CONNECTING","browserPlatform","validatedOptions","goalsPromise","onGoals","waitUntilGoalsReady","visibilityState","basicLogger","importBasicLogger","index"],"mappings":"gPAAA,SAASA,EAAkBC,GACzB,SAASC,EAAYC,EAASC,GAC5BC,MAAMC,mBAAqBD,MAAMC,kBAAkBC,KAAMA,KAAKC,aAC9DD,KAAKJ,QAAUA,EACfI,KAAKH,KAAOA,CACb,CAMD,OAJAF,EAAYO,UAAY,IAAIJ,MAC5BH,EAAYO,UAAUR,KAAOA,EAC7BC,EAAYO,UAAUD,YAAcN,EAE7BA,CACT,CAEA,MAAMQ,EAA4BV,EAAkB,uCAC9CW,EAA8BX,EAAkB,yCAChDY,EAAqBZ,EAAkB,gCACvCa,EAAyBb,EAAkB,oCAC3Cc,EAAyBd,EAAkB,oCAC3Ce,EAAmBf,EAAkB,8BCR3C,IDmBA,IAAAgB,EAAiB,CACfN,4BACAC,8BACAC,qBACAC,yBACAC,yBACAG,mBAhByBjB,EAAkB,gCAiB3Ce,mBACFG,eAjBuBlB,EAAkB,4BAkBzCmB,uBAhBA,SAAgCC,GAC9B,QAAIA,GAAU,KAAOA,EAAS,OACV,MAAXA,GAA6B,MAAXA,GAA6B,MAAXA,EAG/C,GC1BAC,EAuCA,SAAqBC,GACnB,IAAIC,EAAOC,EAAQF,GACfG,EAAWF,EAAK,GAChBG,EAAkBH,EAAK,GAC3B,OAAuC,GAA9BE,EAAWC,GAAuB,EAAKA,CAClD,EA3CAC,EAiDA,SAAsBL,GACpB,IAAIM,EAcAC,EAbAN,EAAOC,EAAQF,GACfG,EAAWF,EAAK,GAChBG,EAAkBH,EAAK,GAEv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ly-js-client-sdk/package.json new file mode 100644 index 00000000..527f5ee2 --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/package.json @@ -0,0 +1,91 @@ +{ + "name": "launchdarkly-js-client-sdk", + "version": "3.8.1", + "description": "LaunchDarkly SDK for JavaScript", + "author": "LaunchDarkly ", + "license": "Apache-2.0", + "keywords": [ + "launchdarkly", + "analytics", + "client" + ], + "files": [ + "ldclient.cjs.js", + "ldclient.cjs.js.map", + "ldclient.es.js", + "ldclient.es.js.map", + "ldclient.min.js", + "ldclient.min.js.map", + "typings.d.ts" + ], + "types": "./typings.d.ts", + "main": "dist/ldclient.cjs.js", + "module": "dist/ldclient.es.js", + "unpkg": "dist/ldclient.min.js", + "jsdelivr": "dist/ldclient.min.js", + "scripts": { + "lint": "eslint --format 'node_modules/eslint-formatter-pretty' --ignore-path ./.eslintignore", + "lint:all": "eslint --format 'node_modules/eslint-formatter-pretty' --ignore-path ./.eslintignore src", + "format": "npm run format:md && npm run format:js", + "format:md": "prettier --parser markdown --ignore-path ../../.prettierignore --write '*.md'", + "format:js": "prettier --ignore-path ../../.prettierignore --write 'src/**/*.js'", + "format:test": "npm run format:test:md && npm run format:test:js", + "format:test:md": "prettier --parser markdown --ignore-path ../../.prettierignore --list-different '*.md'", + "format:test:js": "prettier --ignore-path ../../.prettierignore --list-different 'src/**/*.js'", + "build": "cross-env NODE_ENV=development rollup -c rollup.config.js", + "build:min": "cross-env NODE_ENV=production rollup -c rollup.config.js", + "test": "cross-env NODE_ENV=test jest", + "test:junit": "cross-env NODE_ENV=test jest --testResultsProcessor jest-junit", + "check-typescript": "node_modules/typescript/bin/tsc", + "clean": "rimraf dist/**", + "prepublishOnly": "npm run build:min", + "doc": "typedoc" + }, + "devDependencies": { + "@babel/cli": "^7.19.3", + "@babel/core": "^7.19.3", + "@babel/eslint-parser": "7.19.1", + "@babel/plugin-transform-regenerator": "7.18.6", + "@babel/plugin-transform-runtime": "7.19.1", + "@babel/preset-env": "^7.19.3", + "@babel/runtime": "^7.19.0", + "@rollup/plugin-node-resolve": "^14.1.0", + "@rollup/plugin-replace": "^4.0.0", + "babel-jest": "^29.1.0", + "cross-env": "^7.0.3", + "eslint": "^8.24.0", + "eslint-config-prettier": "^8.5.0", + "eslint-config-xo": "^0.42.0", + "eslint-formatter-pretty": "^4.1.0", + "eslint-plugin-babel": "^5.3.1", + "eslint-plugin-prettier": "^4.2.1", + "jest": "^29.1.1", + "jest-environment-jsdom": "^29.1.1", + "jest-junit": "^14.0.1", + "jest-localstorage-mock": "^2.4.22", + "jsdom": "^20.0.0", + "prettier": "2.7.1", + "rimraf": "^3.0.2", + "rollup": "^2.79.1", + "rollup-plugin-babel": "^4.4.0", + "rollup-plugin-commonjs": "^10.1.0", + "rollup-plugin-filesize": "^9.1.2", + "rollup-plugin-node-globals": "^1.4.0", + "rollup-plugin-terser": "^7.0.2", + "sinon": "^14.0.0", + "typescript": "~5.4.5", + "typedoc": "^0.25.13", + "@types/estree": "^1.0.0" + }, + "dependencies": { + "escape-string-regexp": "^4.0.0", + "launchdarkly-js-sdk-common": "5.7.1" + }, + "repository": { + "type": "git", + "url": "git://github.com/launchdarkly/js-client-sdk.git" + }, + "overrides": { + "parse5": "7.2.1" + } +} diff --git a/node_modules/launchdarkly-js-client-sdk/typings.d.ts b/node_modules/launchdarkly-js-client-sdk/typings.d.ts new file mode 100644 index 00000000..61983382 --- /dev/null +++ b/node_modules/launchdarkly-js-client-sdk/typings.d.ts @@ -0,0 +1,157 @@ +/** + * This is the API reference for the LaunchDarkly SDK for browser JavaScript. + * + * In typical usage, you will call {@link initialize} once at startup time to obtain an instance of + * {@link LDClient}, which provides access to all of the SDK's functionality. + * + * For more information, see the [SDK reference guide](https://docs.launchdarkly.com/sdk/client-side/javascript). + * + * @packageDocumentation + */ + +declare module 'launchdarkly-js-client-sdk' { + + export * from 'launchdarkly-js-sdk-common'; + import { + BasicLoggerOptions, + LDClientBase, + LDContext, + LDLogger, + LDOptionsBase, + } from 'launchdarkly-js-sdk-common'; + + /** + * Creates an instance of the LaunchDarkly client. + * + * The client will begin attempting to connect to LaunchDarkly as soon as it is created. To + * determine when it is ready to use, call [[LDClient.waitForInitialization]], or register an + * event listener for the `"ready"` event using [[LDClient.on]]. + * + * Note that you can either import this as a named export or as part of the default exports, + * although the latter is deprecated: + * + * // Preferred usage: + * import { initialize } from 'launchdarkly-js-client-sdk'; + * const client = initialize(envKey, context, options); + * + * // Deprecated usage: + * import LaunchDarkly from 'launchdarkly-js-client-sdk'; + * const client = LaunchDarkly.initialize(envKey, user, options); + * + * @param envKey + * The environment ID. + * @param context + * The initial context properties. These can be changed later with [[LDClient.identify]]. + * @param options + * Optional configuration settings. + * @return + * The new client instance. + */ + export function initialize(envKey: string, context: LDContext, options?: LDOptions): LDClient; + + // This is @ignored because TypeDoc does not show default exports correctly. We'll just explain + // the export situation in the comment for initialize(). + /** @ignore */ + const LaunchDarkly: { + initialize: (envKey: string, context: LDContext, options?: LDOptions) => LDClient; + version: string; + }; + + /** @ignore */ // see above + export default LaunchDarkly; + + /** + * Initialization options for the LaunchDarkly browser SDK. + */ + export interface LDOptions extends LDOptionsBase { + /** + * The signed context key for Secure Mode. + * + * For more information, see the JavaScript SDK Reference Guide on + * [Secure mode](https://docs.launchdarkly.com/sdk/features/secure-mode#configuring-secure-mode-in-the-javascript-client-side-sdk). + */ + hash?: string; + + /** + * Whether the client should make a request to LaunchDarkly for Experimentation metrics (goals). + * + * This is true by default, meaning that this request will be made on every page load. + * Set it to false if you are not using Experimentation and want to skip the request. + */ + fetchGoals?: boolean; + + /** + * A function which, if present, can change the URL in analytics events to something other + * than the actual browser URL. It will be called with the current browser URL as a parameter, + * and returns the value that should be stored in the event's `url` property. + */ + eventUrlTransformer?: (url: string) => string; + + /** + * If set to true, this prevents the SDK from trying to use a synchronous HTTP request to deliver + * analytics events if the page is being closed. Not all browsers allow such requests; the SDK + * normally tries to avoid making them if not allowed, by using browser detection, but sometimes + * browser detection may not work so if you are seeing errors like "synchronous XHR request + * during page dismissal", you may want to set this option. Since currently the SDK does not have + * a better way to deliver events in this scenario, some events may be lost. + */ + disableSyncEventPost?: boolean; + } + + /** + * The LaunchDarkly SDK client object. + * + * Applications should configure the client at page load time and reuse the same instance. + * + * For more information, see the [SDK Reference Guide](https://docs.launchdarkly.com/sdk/client-side/javascript). + */ + export interface LDClient extends LDClientBase { + /** + * Allows you to wait until the client has received metrics (goals) data from LaunchDarkly. + * + * This is only relevant if you are using Experimentation features like click events and + * pageview events. Until the client has received the configuration for these, which + * happens immediately after the initial request for feature flags, click events and + * pageview events will not work, so you may wish to wait using this method before + * doing anything that you expect to generate those events. + * + * The returned Promise will be resolved once the client has received metrics data. If + * you prefer to use event handlers rather than Promises, you can listen on the client + * for a `"goalsReady"` event instead. + * + * @returns + * A Promise containing the initialization state of the client. + */ + waitUntilGoalsReady(): Promise; + } + + /** + * Provides a simple [[LDLogger]] implementation. + * + * This logging implementation uses a simple format that includes only the log level + * and the message text. By default, output is written to `console` methods (`console.info` + * for normal informational messages, `console.warn` for warnings, `console.error` for + * errors, and `console.log` for debug output) and the default minimum level is `info` + * (that is, debug output is suppressed). You can filter by log level or change the output + * destination with [[BasicLoggerOptions]]. + * + * To use the logger created by this function, put it into [[LDOptions.logger]]. If + * you do not set [[LDOptions.logger]] to anything, the SDK uses a default logger + * that is equivalent to `ld.basicLogger({ level: 'info' })`. + * + * @param options Configuration for the logger. If no options are specified, the + * logger uses `{ level: 'info' }`. + * + * @example + * This example shows how to use `basicLogger` in your SDK options to enable console + * logging only at `warn` and `error` levels. + * ```javascript + * const ldOptions = { + * logger: ld.basicLogger({ level: 'warn' }), + * }; + * ``` + */ + export function basicLogger( + options?: BasicLoggerOptions + ): LDLogger; +} diff --git a/node_modules/launchdarkly-js-sdk-common/.eslintignore b/node_modules/launchdarkly-js-sdk-common/.eslintignore new file mode 100644 index 00000000..13dfc571 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.eslintignore @@ -0,0 +1,4 @@ +node_modules/ +coverage/ +dist/ +eventsource.js diff --git a/node_modules/launchdarkly-js-sdk-common/.eslintrc.yaml b/node_modules/launchdarkly-js-sdk-common/.eslintrc.yaml new file mode 100644 index 00000000..30f6ad47 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.eslintrc.yaml @@ -0,0 +1,103 @@ +--- +parser: babel-eslint +root: true +extends: + - prettier + - eslint:recommended # https://eslint.org/docs/rules/ +env: + es6: true + node: true +plugins: + - babel + - prettier +globals: + describe: true + it: true + expect: true + jest: true + beforeAll: true + afterAll: true + beforeEach: true + afterEach: true + window: false # platform-agnostic code should *not* reference "window" or "document" + document: false +rules: + # https://eslint.org/docs/rules/array-callback-return + array-callback-return: error + + # https://eslint.org/docs/rules/arrow-body-style + arrow-body-style: + - error + - as-needed + + # https://github.com/babel/eslint-plugin-babel + babel/semi: error + + # Deprecations are required to turn enforce this + camelcase: warn + + # https://eslint.org/docs/rules/curly + curly: + - error + - all + + # https://eslint.org/docs/rules/eqeqeq + eqeqeq: error + + # https://eslint.org/docs/rules/no-array-constructor + no-array-constructor: error + + # https://eslint.org/docs/rules/no-eval + no-eval: error + + # https://eslint.org/docs/rules/no-implicit-coercion + no-implicit-coercion: + - 'off' + - boolean: false + number: true + string: true + allow: [] + + # https://eslint.org/docs/rules/no-implied-eval + no-implied-eval: error + + # https://eslint.org/docs/rules/no-nested-ternary + no-nested-ternary: error + + # https://eslint.org/docs/rules/no-new-object + no-new-object: error + + # https://eslint.org/docs/rules/no-new-wrappers + no-new-wrappers: error + + # https://eslint.org/docs/rules/no-param-reassign + no-param-reassign: + - error + - props: true + + # https://eslint.org/docs/rules/no-return-assign + no-return-assign: error + + # https://eslint.org/docs/rules/no-self-compare + no-self-compare: error + + # https://eslint.org/docs/rules/no-use-before-define + no-use-before-define: + - error + - functions: false + + # https://eslint.org/docs/rules/no-var + no-var: error + + # https://eslint.org/docs/rules/prefer-arrow-callback + prefer-arrow-callback: error + + # https://eslint.org/docs/rules/prefer-const + prefer-const: error + + # https://github.com/prettier/eslint-plugin-prettier + prettier/prettier: + - error + + # https://eslint.org/docs/rules/radix + radix: error diff --git a/node_modules/launchdarkly-js-sdk-common/.github/ISSUE_TEMPLATE/bug_report.md b/node_modules/launchdarkly-js-sdk-common/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..6b1d30d5 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,37 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Is this a support request?** +This issue tracker is maintained by LaunchDarkly SDK developers and is intended for feedback on the SDK code. If you're not sure whether the problem you are having is specifically related to the SDK, or to the LaunchDarkly service overall, it may be more appropriate to contact the LaunchDarkly support team; they can help to investigate the problem and will consult the SDK team if necessary. You can submit a support request by going [here](https://support.launchdarkly.com/) and clicking "submit a request", or by emailing support@launchdarkly.com. + +Note that issues filed on this issue tracker are publicly accessible. Do not provide any private account information on your issues. If your problem is specific to your account, you should submit a support request as described above. + +**Describe the bug** +A clear and concise description of what the bug is. + +**To reproduce** +Steps to reproduce the behavior. + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Logs** +If applicable, add any log output related to your problem. + +**SDK version** +The version of this SDK that you are using. + +**Language version, developer tools** +For instance, Go 1.11 or Ruby 2.5.3. If you are using a language that requires a separate compiler, such as C, please include the name and version of the compiler too. + +**OS/platform** +For instance, Ubuntu 16.04, Windows 10, or Android 4.0.3. If your code is running in a browser, please also include the browser type and version. + +**Additional context** +Add any other context about the problem here. diff --git a/node_modules/launchdarkly-js-sdk-common/.github/ISSUE_TEMPLATE/feature_request.md b/node_modules/launchdarkly-js-sdk-common/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..3f7d5bf3 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I would love to see the SDK [...does something new...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context about the feature request here. diff --git a/node_modules/launchdarkly-js-sdk-common/.github/actions/publish-docs/action.yml b/node_modules/launchdarkly-js-sdk-common/.github/actions/publish-docs/action.yml new file mode 100644 index 00000000..6b5e4187 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.github/actions/publish-docs/action.yml @@ -0,0 +1,16 @@ +name: Publish Documentation +description: 'Publish documentation to github pages.' + +inputs: + github_token: + description: 'The github token to use for committing' + required: true + +runs: + using: composite + steps: + - uses: launchdarkly/gh-actions/actions/publish-pages@publish-pages-v1.0.2 + name: 'Publish to Github pages' + with: + docs_path: docs + github_token: ${{ inputs.github_token }} diff --git a/node_modules/launchdarkly-js-sdk-common/.github/actions/publish-npm/action.yml b/node_modules/launchdarkly-js-sdk-common/.github/actions/publish-npm/action.yml new file mode 100644 index 00000000..92fed566 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.github/actions/publish-npm/action.yml @@ -0,0 +1,20 @@ +name: Publish to NPM +description: Publish an npm package. +inputs: + prerelease: + description: 'Is this a prerelease. If so, then the latest tag will not be updated in npm.' + required: false + dry-run: + description: 'Is this a dry run. If so no package will be published.' + required: false + +runs: + using: composite + steps: + - name: Publish + shell: bash + run: | + ./scripts/publish-npm.sh + env: + LD_RELEASE_IS_PRERELEASE: ${{ inputs.prerelease }} + LD_RELEASE_IS_DRYRUN: ${{ inputs.dry-run }} diff --git a/node_modules/launchdarkly-js-sdk-common/.github/pull_request_template.md b/node_modules/launchdarkly-js-sdk-common/.github/pull_request_template.md new file mode 100644 index 00000000..19806760 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.github/pull_request_template.md @@ -0,0 +1,21 @@ +**Requirements** + +- [ ] I have added test coverage for new or changed functionality +- [ ] I have followed the repository's [pull request submission guidelines](../blob/master/CONTRIBUTING.md#submitting-pull-requests) +- [ ] I have validated my changes against all supported platform versions + +**Related issues** + +Provide links to any issues in this repository or elsewhere relating to this pull request. + +**Describe the solution you've provided** + +Provide a clear and concise description of what you expect to happen. + +**Describe alternatives you've considered** + +Provide a clear and concise description of any alternative solutions or features you've considered. + +**Additional context** + +Add any other context about the pull request here. diff --git a/node_modules/launchdarkly-js-sdk-common/.github/workflows/ci.yml b/node_modules/launchdarkly-js-sdk-common/.github/workflows/ci.yml new file mode 100644 index 00000000..7f6bcb46 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: Build and Test + +on: + push: + branches: [main] + paths-ignore: + - '**.md' #Do not need to run CI for markdown changes. + pull_request: + branches: [main] + paths-ignore: + - '**.md' + +jobs: + build-test: + strategy: + matrix: + variations: [ + {os: ubuntu-latest, node: latest}, + {os: ubuntu-latest, node: 18} + ] + + runs-on: ${{ matrix.variations.os }} + + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.variations.node }} + registry-url: 'https://registry.npmjs.org' + - name: Install + run: npm install + - name: Test + run: npm test + env: + JEST_JUNIT_OUTPUT_FILE: "reports/junit/js-test-results.xml" + - name: Lint + run: npm run lint:all + - name: Check typescript + run: npm run check-typescript + - name: Build Docs + run: npm run doc diff --git a/node_modules/launchdarkly-js-sdk-common/.github/workflows/lint-pr-title.yml b/node_modules/launchdarkly-js-sdk-common/.github/workflows/lint-pr-title.yml new file mode 100644 index 00000000..4ba79c13 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.github/workflows/lint-pr-title.yml @@ -0,0 +1,12 @@ +name: Lint PR title + +on: + pull_request_target: + types: + - opened + - edited + - synchronize + +jobs: + lint-pr-title: + uses: launchdarkly/gh-actions/.github/workflows/lint-pr-title.yml@main diff --git a/node_modules/launchdarkly-js-sdk-common/.github/workflows/manual-publish.yml b/node_modules/launchdarkly-js-sdk-common/.github/workflows/manual-publish.yml new file mode 100644 index 00000000..f8edc186 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.github/workflows/manual-publish.yml @@ -0,0 +1,42 @@ +name: Manual Publish Package +on: + workflow_dispatch: + inputs: + dry-run: + description: 'Is this a dry run. If so no package will be published.' + type: boolean + required: true + prerelease: + description: 'Is this a prerelease. If so, then the latest tag will not be updated in npm.' + type: boolean + required: true + +jobs: + publish-package: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20.x + registry-url: 'https://registry.npmjs.org' + + - uses: launchdarkly/gh-actions/actions/release-secrets@release-secrets-v1.2.0 + name: 'Get NPM token' + with: + aws_assume_role: ${{ vars.AWS_ROLE_ARN }} + ssm_parameter_pairs: '/production/common/releasing/npm/token = NODE_AUTH_TOKEN' + + - name: Install Dependencies + run: npm install + + - id: publish-npm + name: Publish NPM Package + uses: ./.github/actions/publish-npm + with: + dry-run: ${{ inputs.dry-run }} + prerelease: ${{ inputs.prerelease }} diff --git a/node_modules/launchdarkly-js-sdk-common/.github/workflows/release-please.yml b/node_modules/launchdarkly-js-sdk-common/.github/workflows/release-please.yml new file mode 100644 index 00000000..214f6578 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.github/workflows/release-please.yml @@ -0,0 +1,57 @@ +name: Release Please + +on: + push: + branches: + - main + +jobs: + release-please: + runs-on: ubuntu-latest + outputs: + release_created: ${{ steps.release.outputs.release_created }} + steps: + - uses: googleapis/release-please-action@v4 + id: release + with: + token: ${{secrets.GITHUB_TOKEN}} + + publish-package: + runs-on: ubuntu-latest + needs: ['release-please'] + permissions: + id-token: write + contents: write + if: ${{ needs.release-please.outputs.release_created == 'true' }} + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20.x + registry-url: 'https://registry.npmjs.org' + + - uses: launchdarkly/gh-actions/actions/release-secrets@release-secrets-v1.2.0 + name: 'Get NPM token' + with: + aws_assume_role: ${{ vars.AWS_ROLE_ARN }} + ssm_parameter_pairs: '/production/common/releasing/npm/token = NODE_AUTH_TOKEN' + + - name: Install Dependencies + run: npm install + + - id: publish-npm + name: Publish NPM Package + uses: ./.github/actions/publish-npm + with: + dry-run: 'false' + prerelease: 'false' + + - name: Build Documentation + run: npm run doc + + - id: publish-docs + name: Publish Documentation + uses: ./.github/actions/publish-docs + with: + github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/launchdarkly-js-sdk-common/.prettierignore b/node_modules/launchdarkly-js-sdk-common/.prettierignore new file mode 100644 index 00000000..ec6d3cdd --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.prettierignore @@ -0,0 +1 @@ +package.json diff --git a/node_modules/launchdarkly-js-sdk-common/.prettierrc b/node_modules/launchdarkly-js-sdk-common/.prettierrc new file mode 100644 index 00000000..e2f78207 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.prettierrc @@ -0,0 +1,5 @@ +{ + "trailingComma": "es5", + "singleQuote": true, + "printWidth": 120 +} diff --git a/node_modules/launchdarkly-js-sdk-common/.release-please-manifest.json b/node_modules/launchdarkly-js-sdk-common/.release-please-manifest.json new file mode 100644 index 00000000..cabdafcb --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "5.7.1" +} diff --git a/node_modules/launchdarkly-js-sdk-common/CHANGELOG.md b/node_modules/launchdarkly-js-sdk-common/CHANGELOG.md new file mode 100644 index 00000000..e061af1e --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/CHANGELOG.md @@ -0,0 +1,302 @@ +# Change log + +All notable changes to the `launchdarkly-js-sdk-common` package will be documented in this file. Changes that affect the dependent SDKs such as `launchdarkly-js-client-sdk` should also be logged in those projects, in the next release that uses the updated version of this package. This project adheres to [Semantic Versioning](http://semver.org). + +## [5.7.1](https://github.com/launchdarkly/js-sdk-common/compare/5.7.0...5.7.1) (2025-05-30) + + +### Bug Fixes + +* updating identify code documentation ([82c6071](https://github.com/launchdarkly/js-sdk-common/commit/82c6071760cccbe3000a30f46fb19e169ed8573e)) + +## [5.7.0](https://github.com/launchdarkly/js-sdk-common/compare/5.6.0...5.7.0) (2025-05-22) + + +### Features + +* Add support for per-context summary events. ([#126](https://github.com/launchdarkly/js-sdk-common/issues/126)) ([05f7d4e](https://github.com/launchdarkly/js-sdk-common/commit/05f7d4ec0ac7b072e12a3260f55861c7db039e03)) + +## [5.6.0](https://github.com/launchdarkly/js-sdk-common/compare/5.5.1...5.6.0) (2025-04-29) + + +### Features + +* Add support for plugins. ([#124](https://github.com/launchdarkly/js-sdk-common/issues/124)) ([e0544c1](https://github.com/launchdarkly/js-sdk-common/commit/e0544c13d94b1088aebc4f6852743e408f5f77af)) +* Add support for the afterTrack stage for hooks. ([#123](https://github.com/launchdarkly/js-sdk-common/issues/123)) ([f7bebeb](https://github.com/launchdarkly/js-sdk-common/commit/f7bebebc15fc0ac718ebe167291215992b8ee6f5)) + +## [5.5.1](https://github.com/launchdarkly/js-sdk-common/compare/5.5.0...5.5.1) (2025-04-25) + + +### Bug Fixes + +* Add hooks to default options to prevent warning. ([#121](https://github.com/launchdarkly/js-sdk-common/issues/121)) ([9c04081](https://github.com/launchdarkly/js-sdk-common/commit/9c04081e828d2dde84f800c139480e960b537cfe)) + +## [5.5.0](https://github.com/launchdarkly/js-sdk-common/compare/5.4.0...5.5.0) (2025-04-21) + + +### Features + +* Add hook support. ([#116](https://github.com/launchdarkly/js-sdk-common/issues/116)) ([85c227c](https://github.com/launchdarkly/js-sdk-common/commit/85c227ca9b82a3c783b0dd449f7557a3806268bb)) +* Inline context in custom events. ([#118](https://github.com/launchdarkly/js-sdk-common/issues/118)) ([450f8f7](https://github.com/launchdarkly/js-sdk-common/commit/450f8f75f450de1382b35fe7b77d3b97060a19f8)) + +## [5.4.0](https://github.com/launchdarkly/js-sdk-common/compare/5.3.0...5.4.0) (2024-10-18) + + +### Features + +* Add support for client-side prerequisite events. ([#112](https://github.com/launchdarkly/js-sdk-common/issues/112)) ([9d1708b](https://github.com/launchdarkly/js-sdk-common/commit/9d1708b212246c5650794af99f79cd6a95cfbcd1)) + +## [5.3.0](https://github.com/launchdarkly/js-sdk-common/compare/launchdarkly-js-sdk-common-v5.2.0...launchdarkly-js-sdk-common-v5.3.0) (2024-06-18) + + +### Features + +* Add inExperiment to evaluation reason. ([#105](https://github.com/launchdarkly/js-sdk-common/issues/105)) ([cf69770](https://github.com/launchdarkly/js-sdk-common/commit/cf6977080e67e4e54f773df410a671764dbcb304)) +* Allow for synchronous inspectors. ([#103](https://github.com/launchdarkly/js-sdk-common/issues/103)) ([7e490f4](https://github.com/launchdarkly/js-sdk-common/commit/7e490f479299f772a9db78efd1c2235645785250)) + +## [5.2.0] - 2024-05-01 +### Added: +- Added an optional timeout to the `waitForInitialization` method. When a timeout is specified the returned promise will be rejected after the timeout elapses if the client has not finished initializing within that time. When no timeout is specified the returned promise will not be resolved or rejected until the initialization either completes or fails. + +### Changed: +- The track method now validates that the provided metricValue is a number. If a metric value is provided, and it is not a number, then a warning will be logged. + +### Fixed: +- Fixed the documentation for `evaluationReasons` for the `identify` method. + +## [5.1.0] - 2024-03-19 +### Changed: +- Redact anonymous attributes within feature events +- Always inline contexts for feature events + +### Fixed: +- Pin dev version of node to compatible types. + +### Removed: +- HTTP fallback ping + +## [5.0.3] - 2023-03-21 +### Changed: +- Update `LDContext` to allow for key to be optional. This is used when making an anonymous context with a generated key. + +## [5.0.2] - 2023-02-15 +### Changed: +- Removed usage of optional chaining (`?.`) to improve compatibility with projects which are using older transpilation tooling. + +## [5.0.1] - 2023-01-10 +### Changed: +- Updated all types in `typings.d.ts` to be exported. This is to ensure that those types are included in generated documentation of dependent SDKs. + +## [5.0.0] - 2022-11-30 +This major version release of `js-sdk-common` corresponds to the upcoming releases of the `js-client-sdk` v3 and `react-client-sdk` v3, and cannot be used with earlier SDK versions. + +### Added: +- Replaced users with contexts. A context is a generalized way of referring to the people, services, machines, or other resources that encounter feature flags in your product. All methods which previously operated on `LDUser` now operate on `LDContext`. + +### Changed: +- `LDClient.getUser` has been replaced with `LDClient.getContext`. +- `privateAttributeNames` has been replaced with `privateAttributes`. Private attributes now allow using attribute references, which allow for marking nodes in nested JSON private. + +### Removed: +- Alias events are no longer supported and the `alias` method has been removed from `LDClient`. +- Support for the `secondary` attribute has been removed from `LDUser`. If a secondary attribute is included in a context, then it is a normal attribute that can be used in rule evaluation, but it will not affect bucketing. +- `allowFrequentDuplicateEvents` has been removed from `LDOptions`. This had been deprecated in a previous version. The default behavior is as if this option had been set to true. +- `autoAliasingOptOut` has been removed from `LDOptions`. This functionality has been superseded by multi-context support. +- `inlineUsersInEvents` has been removed from `LDOptions`. Changes associated with contexts has removed the needed for this option. + +### Deprecated: +- The `LDUser` object has been deprecated. Support for `LDUser` is maintained to simplify the upgrade process, but it is recommended to use `LDContext` in the shape of either `LDSingleKindContext` or `LDMultiKindContext`. + +## [4.3.2] - 2022-10-20 +### Added: +- Implemented `jitter` and `backoff` for streaming connections. When a connection fails the retry will start at the `streamReconnectDelay` and will double on each unsuccessful consecutive connection attempt (`backoff`) to a max of 30 seconds. The delay will be adjusted from 50%-100% of the calculated delay to prevent many clients from attempting to reconnect at the same time (`jitter`). + +### Changed: +- Removed usage of `flatMap`. (Thanks [@mateuszsikora](https://github.com/launchdarkly/js-sdk-common/pull/77)) + +## [4.3.1] - 2022-10-17 +### Fixed: +- Fixed an issue that prevented the `flag-used` inspector from being called. + +## [4.3.0] - 2022-10-17 +### Added: +- Added support for `Inspectors` that can be used for collecting information for monitoring, analytics, and debugging. + +## [4.2.0] - 2022-10-03 +### Removed: +- Removed `seenRequests` cache. This cache was used to de-duplicate events, but it has been supplanted with summary events. + +### Deprecated: +- The `allowFrequentDuplicateEvents` configuration has been deprecated because it controlled the behavior of the `seenRequests` cache. + +## [4.1.1] - 2022-06-07 +### Changed: +- Enforce a 64 character limit for `application.id` and `application.version` configuration options. + +### Fixed: +- Do not include deleted flags in `allFlags`. + +## [4.1.0] - 2022-04-21 +### Added: +- `LDOptionsBase.application`, for configuration of application metadata that may be used in LaunchDarkly analytics or other product features. This does not affect feature flag evaluations. + +### Fixed: +- The `baseUrl`, `streamUrl`, and `eventsUrl` properties now work properly regardless of whether the URL string has a trailing slash. Previously, a trailing slash would cause request URL paths to have double slashes. + +## [4.0.3] - 2022-02-16 +### Fixed: +- If the SDK receives invalid JSON data from a streaming connection (possibly as a result of the connection being cut off), it now uses its regular error-handling logic: the error is emitted as an `error` event or, if there are no `error` event listeners, it is logged. Previously, it would be thrown as an unhandled exception. + +## [4.0.2] - 2022-01-25 +### Removed: +- Removed the `version` export which was originally a constant inserted by the Rollup build, but was no longer usable since Rollup is no longer being used. The SDKs never used this export, since they have `version` properties of their own; the version string of `launchdarkly-js-sdk-common` was never meant to be exposed to applications. + +## [4.0.1] - 2022-01-21 +### Changed: +- This package is now published as a regular Node module. Previously, it was published as minified bundles created by Rollup. There was no need for this since Rollup is only needed for web code, and the `js-client-sdk` build already runs Rollup to embed the `js-sdk-common` code. Using Rollup caused the platform-dependent behavior of `uuid` to fail because the code for only one platform (browser or Node) was embedded. + +## [4.0.0] - 2022-01-14 +### Changed: +- Updated `uuid` package to 8.x. +- In TypeScript, the property `LDEvaluationDetail.reason` is now nullable, which correctly reflects the fact that evaluation reasons may not always be available. + +### Removed: +- Removed the type `NonNullableLDEvaluationReason`, which was a side effect of the `LDEvaluationDetail.reason` being incorrectly defined before. +- Removed all types, properties, and functions that were deprecated as of the last 3.x release. + +## [3.5.1] - 2022-02-17 +### Fixed: +- If the SDK receives invalid JSON data from a streaming connection (possibly as a result of the connection being cut off), it now uses its regular error-handling logic: the error is emitted as an `error` event or, if there are no `error` event listeners, it is logged. Previously, it would be thrown as an unhandled exception. + +## [3.5.0] - 2022-01-14 +### Added: +- New configurable logger factory `commonBasicLogger` and `BasicLoggerOptions`. The `commonBasicLogger` method is not intended to be exported directly in the SDKs, but wrapped to provide platform-specific behavior. + +### Fixed: +- Any exceptions thrown by the platform-specific local storage implementation (for instance, if we are in a browser and `window.localstorage` is available but disabled) are now consistently caught, and will only be logged the first time to avoid repetitive logging. + +## [3.4.0] - 2021-10-15 +### Added: +- Added LDOptionsBase.requestHeaderTransform allowing custom headers to be added to all requests. + +## [3.3.4] - 2021-10-15 +### Fixed: +- Reverted change to `uuid` dependency while working on some compatibility issues. + +## [3.3.3] - 2021-08-23 +### Fixed: +- Updated `uuid` dependency to 8.x to remove deprecated usage. ([#46](https://github.com/launchdarkly/js-sdk-common/issues/46)) + +## [3.3.2] - 2021-06-07 +### Fixed: +- Events for the [LaunchDarkly debugger](https://docs.launchdarkly.com/home/flags/debugger) are now properly pre-processed to omit private user attributes, as well as enforce only expected top level attributes are sent. +- Events for the [LaunchDarkly debugger](https://docs.launchdarkly.com/home/flags/debugger) now include the index of the variation responsible for the evaluation result. + +## [3.3.1] - 2021-04-01 +### Fixed: +- The property `LDOptionsBase.inlineUsersInEvents` was not included in the TypeScript definitions. +- Fixed an outdated documentation link (thanks, [sinchang](https://github.com/launchdarkly/js-sdk-common/pull/36)!) +- Fixed a documentation typo (thanks, [Doesntmeananything](https://github.com/launchdarkly/js-sdk-common/pull/37)!) + +## [3.3.0] - 2021-01-26 +### Added: +- Added the `alias` method. This method can be used to associate two user objects for analytics purposes. When invoked, this method will queue a new alias event to be sent to LaunchDarkly. +- Added the `autoAliasingOptOut` configuration option. This can be used to control the new automatic aliasing behavior of the `identify` method; by passing `autoAliasingOptOut: true`, `identify` will not automatically generate alias events. + +### Changed: +- The `identify` method will now automatically generate an alias event when switching from an anonymous to a known user. This event associates the two users for analytics purposes as they most likely represent a single person. + +## [3.2.12] - 2021-01-25 +### Changed: +- When creating a stream connection, we now set a `streamReadTimeoutMillis` option which is hard-coded to the standard LaunchDarkly stream timeout of 5 minutes. This option is implemented by [`launchdarkly-eventsource`](https://github.com/launchdarkly/js-eventsource) 1.4.0 and higher, and should be ignored by SDKs that are not using that EventSource implementation. + +## [3.2.11] - 2020-11-17 +### Fixed: +- Updated the `LDEvaluationDetail.reason` type definition to be nullable. This value will be `null` when `LDOptions.evaluationReasons` is `false`. + +## [3.2.10] - 2020-09-14 +### Fixed: +- In streaming mode, when connecting to the Relay Proxy rather than directly to the LaunchDarkly streaming service, if the current user was changed twice within a short time it was possible for the SDK to revert to flag values from the previous user. + +## [3.2.9] - 2020-07-10 +### Fixed: +- Removed uses of `String.startsWith` that caused errors in Internet Explorer unless a polyfill for that function was present. + +## [3.2.8] - 2020-05-13 +### Fixed: +- The TypeScript declaration for `track()` was missing the optional `metricValue` parameter. ([#23](https://github.com/launchdarkly/js-sdk-common/issues/23)) + +## [3.2.7] - 2020-04-30 +### Fixed: +- Some diagnostic event data was being sent twice, resulting in extra HTTP requests. This did not affect analytics events, so customer data on the dashboard and in data export would still be correct. + +## [3.2.6] - 2020-03-31 +### Fixed: +- The default logging implementation (`createConsoleLogger`) could throw errors in Internet Explorer 11 if log output (of an enabled level) happened while the developer tools were _not_ open. This is because in IE 11, the `console` object [does not exist](https://www.beyondjava.net/console-log-surprises-with-internet-explorer-11-and-edge) unless the tools are open. This has been fixed so the logger does not try to use `console` unless it currently has a value. + +## [3.2.5] - 2020-03-18 +### Fixed: +- Fixed incorrect usage of `Object.hasOwnProperty` which could have caused an error if a feature flag had `hasOwnProperty` as its flag key. + +## [3.2.4] - 2020-03-18 +### Fixed: +- Some users reported an error where the SDK said that the content type of a response was `"application/json, application/json; charset=utf8"`. It is invalid to have multiple Content-Type values in a response and the LaunchDarkly service does not do this, but an improperly configured proxy/gateway might add such a header. Now the SDK will tolerate a value like this as long as it starts with `"application/json"`. + +## [3.2.3] - 2020-03-06 +### Fixed: +- At client initialization time, if the initial flag polling request failed, it would cause an unhandled promise rejection unless the application had called `waitForInitialization()` and provided an error handler for the promise that was returned by that method. While that is correct behavior if the application did call `waitForInitialization()` (any promise that might be rejected should have an error handler attached), it is highly undesirable if the application did not call `waitForInitialization()` at all-- which is not mandatory, since the application could use events instead, or `waitUntilReady()`, or might simply not care about waiting for initialization. This has been fixed so that no such promise is created until the first time the application calls `waitForInitialization()`; subsequent calls to the same method will return the same promise (since initialization can only happen once). +- A bug in the event emitter made its behavior unpredictable if an event handler called `on` or `off` while handling an event. This has been fixed so that all event handlers that were defined _at the time the event was fired_ will be called; any changes made will not take effect until the next event. + +## [3.2.2] - 2020-02-13 +### Fixed: +- When sending stream connection statistics in diagnostic event data, always specify the `failed` property even if it is false. This only affects LaunchDarkly's internal analytics. + +## [3.2.1] - 2020-02-13 +### Fixed: +- When using secure mode in conjunction with streaming mode, if an application specified a new `hash` parameter while changing the current user with `identify()`, the SDK was not using the new `hash` value when recomputing the stream URL, causing the stream to fail. ([#13](https://github.com/launchdarkly/js-sdk-common/issues/13)) + +## [3.2.0] - 2020-02-12 +### Added: +- The SDKs now periodically send diagnostic data to LaunchDarkly, describing the version and configuration of the SDK, the architecture and version of the runtime platform (provided by the platform-specific SDK packages), and performance statistics. No credentials, hostnames, or other identifiable values are included. This behavior can be disabled with the `diagnosticOptOut` option or configured with `diagnosticRecordingInterval`. + +## [3.1.2] - 2020-01-31 +### Removed: +- Removed an unused dependency on `@babel/polyfill`. (Thanks, [bdwain](https://github.com/launchdarkly/js-sdk-common/pull/7)!) +- Changed exact version dependencies to "highest compatible" dependencies, to avoid having modules that are also used by the host application loaded twice by NPM. ([#8](https://github.com/launchdarkly/js-sdk-common/issues/8)) + +## [3.1.1] - 2020-01-15 +### Fixed: +- The SDK now specifies a uniquely identifiable request header when sending events to LaunchDarkly to ensure that events are only processed once, even if the SDK sends them two times due to a failed initial attempt. + +## [3.1.0] - 2019-12-13 +### Added: +- Configuration options `wrapperName` and `wrapperVersion`. +- Platform option `httpFallbackPing` (to be used for the browser image mechanism - see below). + +### Fixed: +- When calling `identify`, the current user (as reported by `getUser()`) was being updated before the SDK had received the new flag values for that user, causing the client to be temporarily in an inconsistent state where flag evaluations would be associated with the wrong user in analytics events. Now, the current-user state will stay in sync with the flags and change only when they have finished changing. (Thanks, [edvinerikson](https://github.com/launchdarkly/js-sdk-common/pull/3)!) + +### Removed: +- Logic for sending a one-way HTTP request in a browser by creating an image has been moved to the browser-specific code (`js-client-sdk`). + + +## [3.0.0] - 2019-12-13 +### Added: +- Configuration property `eventCapacity`: the maximum number of analytics events (not counting evaluation counters) that can be held at once, to prevent the SDK from consuming unexpected amounts of memory in case an application generates events unusually rapidly. In JavaScript code this would not normally be an issue, since the SDK flushes events every two seconds by default, but you may wish to increase this value if you will intentionally be generating a high volume of custom or identify events. The default value is 100. + +### Changed: +- (Breaking change) The `extraDefaults` parameter to the internal common `initialize` method is now `extraOptionDefs` and has a different format, allowing for more flexible validation. +- The SDK now logs a warning if any configuration property has an inappropriate type, such as `baseUri:3` or `sendEvents:"no"`. For boolean properties, the SDK will still interpret the value in terms of truthiness, which was the previous behavior. For all other types, since there's no such commonly accepted way to coerce the type, it will fall back to the default setting for that property; previously, the behavior was undefined but most such mistakes would have caused the SDK to throw an exception at some later point. +- Removed or updated some development dependencies that were causing vulnerability warnings. + +### Deprecated: +- The `samplingInterval` configuration property was deprecated in the code in the previous minor version release, and in the changelog, but the deprecation notice was accidentally omitted from the documentation comments. It is hereby deprecated again. + + +## [2.14.1] - 2019-11-04 +### Fixed: +- Removed uses of `Object.assign` that caused errors in Internet Explorer unless a polyfill for that function was present. + + + +Prior to the 2.15.0 release, this code was a monorepo subpackage in the [`js-client-sdk`](https://github.com/launchdarkly/js-client-sdk) repo. See the [changelog](https://github.com/launchdarkly/js-client-sdk/blob/2.14.0/CHANGELOG.md) in that repo for changes prior to that version. It is now maintained in this repo and has its own versioning and changelog. diff --git a/node_modules/launchdarkly-js-sdk-common/CODEOWNERS b/node_modules/launchdarkly-js-sdk-common/CODEOWNERS new file mode 100644 index 00000000..31dc3d13 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/CODEOWNERS @@ -0,0 +1,2 @@ +# Repository Maintainers +* @launchdarkly/team-sdk-js diff --git a/node_modules/launchdarkly-js-sdk-common/CONTRIBUTING.md b/node_modules/launchdarkly-js-sdk-common/CONTRIBUTING.md new file mode 100644 index 00000000..3179bc32 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/CONTRIBUTING.md @@ -0,0 +1,45 @@ +# Contributing to This Project + +The `launchdarkly-js-sdk-common` package provides core implementation components for several LaunchDarkly SDKs. + +## Submitting bug reports and feature requests + +Bug reports and feature requests, unless they are very specifically related to a piece of code in this project, should be filed in the individual SDK repositories instead. If you do have an issue specifically for this repository, the LaunchDarkly SDK team monitors the [issue tracker](https://github.com/launchdarkly/js-sdk-common/issues) and will respond to all newly filed issues within two business days. + +## Submitting pull requests + +We encourage pull requests and other contributions from the community. Before submitting pull requests, ensure that all temporary or unintended code is removed. Don't worry about adding reviewers to the pull request; the LaunchDarkly SDK team will add themselves. The SDK team will acknowledge all pull requests within two business days. + +## Build instructions + +### Prerequisites + +The project uses `npm`, which is bundled in all supported versions of Node. + +### Setup + +To install project dependencies, from the project root directory: + +``` +npm install +``` + +### Testing + +To run all unit tests: + +``` +npm test +``` + +To verify that the TypeScript declarations compile correctly (this involves compiling the file `test-types.ts`, so if you have changed any types or interfaces, you will want to update that code): + +``` +npm run check-typescript +``` + +### Coding guidelines + +This code is shared between several SDK projects: `js-client-sdk` which runs in browsers, `node-client-sdk` which runs in Node.js, and `electron-client-sdk` which uses it both in a Node environment and in a browser environment. + +Therefore, it should not have any JavaScript usages that work _only_ in a browser or _only_ in Node.js. All such things, if they depend on the runtime environment, must be accessed indirectly via the "platform" abstraction, where each SDK provides its own platform-specific callbacks for the `js-sdk-common` code to use. Or, if it's just a question of JavaScript syntax usages, use whatever will work in both browsers and Node (for instance, use only `require` and `module.exports`, not ES6 imports). diff --git a/node_modules/launchdarkly-js-sdk-common/LICENSE.txt b/node_modules/launchdarkly-js-sdk-common/LICENSE.txt new file mode 100644 index 00000000..7510071d --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/LICENSE.txt @@ -0,0 +1,13 @@ +Copyright 2019 Catamorphic, Co. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/launchdarkly-js-sdk-common/README.md b/node_modules/launchdarkly-js-sdk-common/README.md new file mode 100644 index 00000000..ed00d7a4 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/README.md @@ -0,0 +1,38 @@ +# LaunchDarkly Javascript SDK Core Components + +[![Actions Status][ci-badge]][ci] + +## LaunchDarkly overview + +[LaunchDarkly](https://www.launchdarkly.com) is a feature management platform that serves trillions of feature flags daily to help teams build better software, faster. [Get started](https://docs.launchdarkly.com/home/getting-started) using LaunchDarkly today! + +[![Twitter Follow](https://img.shields.io/twitter/follow/launchdarkly.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/intent/follow?screen_name=launchdarkly) + +## Overview + +This project provides core implementation components for all of the LaunchDarkly client-side SDKs that use JavaScript: the JS (browser) SDK, the React SDK, the client-side Node SDK, and the Electron SDK. Application code should never refer to the `launchdarkly-js-sdk-common` package directly. + +The `initialize` function in `index.js` creates the basic client object that all of those SDKs are built upon. The SDK's own `initialize` function calls this function, providing a "platform" object that defines additional capabilities specific to that SDK, and then optionally decorates the client object with any other public methods or properties it should have. Inasmuch as possible, the SDK code contains only what is necessary to distinguish it from the other JavaScript-based SDKs. For instance, this project contains no browser-specific code; that is all in [`js-client-sdk`](https://github.com/launchdarkly/js-client-sdk). + +It also provides TypeScript definitions in `index.d.ts` which are re-exported or extended by the SDKs, so the Typedoc documentation for the SDKs includes them. + +## Contributing + +We encourage pull requests and other contributions from the community. Check out our [contributing guidelines](CONTRIBUTING.md) for instructions on how to contribute to this project. + +## About LaunchDarkly + +* LaunchDarkly is a continuous delivery platform that provides feature flags as a service and allows developers to iterate quickly and safely. We allow you to easily flag your features and manage them from the LaunchDarkly dashboard. With LaunchDarkly, you can: + * Roll out a new feature to a subset of your users (like a group of users who opt-in to a beta tester group), gathering feedback and bug reports from real-world use cases. + * Gradually roll out a feature to an increasing percentage of users, and track the effect that the feature has on key metrics (for instance, how likely is a user to complete a purchase if they have feature A versus feature B?). + * Turn off a feature that you realize is causing performance problems in production, without needing to re-deploy, or even restart the application with a changed configuration file. + * Grant access to certain features based on user attributes, like payment plan (eg: users on the ‘gold’ plan get access to more features than users in the ‘silver’ plan). Disable parts of your application to facilitate maintenance, without taking everything offline. +* LaunchDarkly provides feature flag SDKs for a wide variety of languages and technologies. Read [our documentation](https://docs.launchdarkly.com/sdk) for a complete list. +* Explore LaunchDarkly + * [launchdarkly.com](https://www.launchdarkly.com/ "LaunchDarkly Main Website") for more information + * [docs.launchdarkly.com](https://docs.launchdarkly.com/ "LaunchDarkly Documentation") for our documentation and SDK reference guides + * [apidocs.launchdarkly.com](https://apidocs.launchdarkly.com/ "LaunchDarkly API Documentation") for our API documentation + * [blog.launchdarkly.com](https://blog.launchdarkly.com/ "LaunchDarkly Blog Documentation") for the latest product updates + +[ci-badge]: https://github.com/launchdarkly/js-sdk-common/actions/workflows/ci.yml/badge.svg +[ci]: https://github.com/launchdarkly/js-sdk-common/actions/workflows/ci.yml diff --git a/node_modules/launchdarkly-js-sdk-common/SECURITY.md b/node_modules/launchdarkly-js-sdk-common/SECURITY.md new file mode 100644 index 00000000..10f1d1ac --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/SECURITY.md @@ -0,0 +1,5 @@ +# Reporting and Fixing Security Issues + +Please report all security issues to the LaunchDarkly security team by submitting a bug bounty report to our [HackerOne program](https://hackerone.com/launchdarkly?type=team). LaunchDarkly will triage and address all valid security issues following the response targets defined in our program policy. Valid security issues may be eligible for a bounty. + +Please do not open issues or pull requests for security issues. This makes the problem immediately visible to everyone, including potentially malicious actors. diff --git a/node_modules/launchdarkly-js-sdk-common/babel.config.js b/node_modules/launchdarkly-js-sdk-common/babel.config.js new file mode 100644 index 00000000..56704e87 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/babel.config.js @@ -0,0 +1,18 @@ +module.exports = { + presets: [ + [ + '@babel/env', + { + targets: ["last 2 versions", "ie >= 10"], + }, + ], + ], + env: { + test: { + plugins: [ + '@babel/plugin-transform-regenerator', + '@babel/plugin-transform-runtime', + ], + }, + }, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/jest.config.js b/node_modules/launchdarkly-js-sdk-common/jest.config.js new file mode 100644 index 00000000..2308ec84 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/jest.config.js @@ -0,0 +1,12 @@ +const version = process.env.npm_package_version; + +module.exports = { + automock: false, + resetModules: true, + rootDir: 'src', + setupFiles: ['./jest.setup.js'], + testMatch: ['**/__tests__/**/*-test.js'], + transform: { + '^.+\\.js$': 'babel-jest', + }, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/package.json b/node_modules/launchdarkly-js-sdk-common/package.json new file mode 100644 index 00000000..19133031 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/package.json @@ -0,0 +1,59 @@ +{ + "name": "launchdarkly-js-sdk-common", + "version": "5.7.1", + "description": "LaunchDarkly SDK for JavaScript - common code", + "author": "LaunchDarkly ", + "license": "Apache-2.0", + "types": "./typings.d.ts", + "main": "src/index.js", + "scripts": { + "lint": "eslint --format 'node_modules/eslint-formatter-pretty' --ignore-path .eslintignore", + "lint:all": "eslint --format 'node_modules/eslint-formatter-pretty' --ignore-path .eslintignore src", + "lint-fix:all": "eslint --fix --format 'node_modules/eslint-formatter-pretty' --ignore-path .eslintignore src", + "format": "npm run format:md && npm run format:js", + "format:md": "prettier --parser markdown --ignore-path .prettierignore --write '*.md'", + "format:js": "prettier --ignore-path .prettierignore --write 'src/**/*.js'", + "format:test": "npm run format:test:md && npm run format:test:js", + "format:test:md": "prettier --parser markdown --ignore-path .prettierignore --list-different '*.md'", + "format:test:js": "prettier --ignore-path .prettierignore --list-different 'src/**/*.js'", + "test": "cross-env NODE_ENV=test jest", + "check-typescript": "tsc", + "doc": "typedoc" + }, + "devDependencies": { + "@babel/cli": "^7.8.4", + "@babel/core": "^7.6.4", + "@babel/plugin-transform-regenerator": "^7.4.5", + "@babel/plugin-transform-runtime": "^7.6.2", + "@babel/preset-env": "^7.6.3", + "@babel/runtime": "7.6.3", + "@rollup/plugin-replace": "^2.2.0", + "@types/jest": "^27.4.1", + "@types/node": "12.12.6", + "babel-eslint": "^10.1.0", + "babel-jest": "^25.1.0", + "cross-env": "^5.1.4", + "eslint": "^6.8.0", + "eslint-config-prettier": "^2.9.0", + "eslint-config-xo": "^0.20.1", + "eslint-formatter-pretty": "^1.3.0", + "eslint-plugin-babel": "^5.0.0", + "eslint-plugin-prettier": "^2.6.0", + "jest": "^26.6.3", + "jsdom": "^11.11.0", + "launchdarkly-js-test-helpers": "1.1.0", + "prettier": "1.19.1", + "readline-sync": "^1.4.9", + "typescript": "~5.4.5", + "typedoc": "^0.25.13" + }, + "dependencies": { + "base64-js": "^1.3.0", + "fast-deep-equal": "^2.0.1", + "uuid": "^8.0.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/launchdarkly/js-sdk-common.git" + } +} diff --git a/node_modules/launchdarkly-js-sdk-common/release-please-config.json b/node_modules/launchdarkly-js-sdk-common/release-please-config.json new file mode 100644 index 00000000..df4a6c22 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/release-please-config.json @@ -0,0 +1,10 @@ +{ + "bootstrap-sha": "d49ca41718a593c071874950d301f2f00c71a371", + "packages": { + ".": { + "release-type": "node", + "include-v-in-tag": false, + "include-component-in-tag": false + } + } +} diff --git a/node_modules/launchdarkly-js-sdk-common/scripts/better-audit.sh b/node_modules/launchdarkly-js-sdk-common/scripts/better-audit.sh new file mode 100755 index 00000000..b835456d --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/scripts/better-audit.sh @@ -0,0 +1,76 @@ +#!/bin/bash + +# This script processes the output of "npm audit" to make it more useful, as follows: +# - For each flagged vulnerability, it looks at the "path" field and extracts both the flagged +# package (the last element in the path) and the topmost dependency that led to it (the first +# element in the path). +# - It sorts these and eliminates duplicates. +# - It then compares each of the topmost dependencies to package.json to see if it is from +# "dependencies", "peerDependencies", or "devDependencies". If it is either of the first two +# then this is a real runtime vulnerability, and must be fixed by updating the topmost +# dependency. If it is from devDependencies, then it can be safely fixed with "npm audit fix". + +set -e + +function readPackages() { + inCategory=$1 + jq -r ".${inCategory} | keys | .[]" package.json 2>/dev/null || true +} + +function isInList() { + item=$1 + shift + for x in $@; do + if [ "$item" == "$x" ]; then + true + return + fi + done + false +} + +dependencies=$(readPackages dependencies) +devDependencies=$(readPackages devDependencies) +peerDependencies=$(readPackages peerDependencies) + +function processItems() { + flaggedRuntime=0 + flaggedDev=0 + while read -r badPackage topLevelDep; do + echo -n "flagged package \"$badPackage\", referenced via \"$topLevelDep\" " + for category in dependencies peerDependencies devDependencies; do + if isInList $topLevelDep ${!category}; then + if [ "$category" == "devDependencies" ]; then + echo "-- from \"$category\"" + flaggedDev=1 + else + echo "-- from \"$category\" (RUNTIME) ***" + flaggedRuntime=1 + fi + break + fi + done + done + echo + if [ "$flaggedRuntime" == "1" ]; then + echo "*** At least one runtime dependency was flagged. These must be fixed by updating package.json." + echo "Do not use 'npm audit fix'." + exit 1 # return an error, causing the build to fail + elif [ "$flaggedDev" == "1" ]; then + echo "Only development dependencies were flagged. You may safely run 'npm audit fix', which will" + echo "fix these by adding overrides to package-lock.json." + else + echo "Congratulations! No dependencies were flagged by 'npm audit'." + fi +} + +echo "Running npm audit..." +echo + +npm audit --json \ + | grep '"path":' \ + | sort | uniq \ + | sed -n -e 's#.*"path": "\([^"]*\)".*#\1#p' \ + | awk -F '>' '{ print $NF,$1 }' \ + | sort | uniq \ + | processItems diff --git a/node_modules/launchdarkly-js-sdk-common/scripts/publish-npm.sh b/node_modules/launchdarkly-js-sdk-common/scripts/publish-npm.sh new file mode 100755 index 00000000..69196bdf --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/scripts/publish-npm.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +if $LD_RELEASE_IS_DRYRUN ; then + echo "Doing a dry run of publishing." +else + if $LD_RELEASE_IS_PRERELEASE ; then + echo "Publishing with prerelease tag." + npm publish --tag prerelease --provenance --access public || { echo "npm publish failed" >&2; exit 1; } + else + npm publish --provenance --access public || { echo "npm publish failed" >&2; exit 1; } + fi +fi diff --git a/node_modules/launchdarkly-js-sdk-common/src/AnonymousContextProcessor.js b/node_modules/launchdarkly-js-sdk-common/src/AnonymousContextProcessor.js new file mode 100644 index 00000000..8223b5ce --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/AnonymousContextProcessor.js @@ -0,0 +1,95 @@ +const { v1: uuidv1 } = require('uuid'); +const { getContextKinds } = require('./context'); + +const errors = require('./errors'); +const messages = require('./messages'); +const utils = require('./utils'); + +const ldUserIdKey = 'ld:$anonUserId'; + +/** + * Create an object which can process a context and populate any required keys + * for anonymous objects. + * + * @param {Object} persistentStorage The persistent storage from which to store + * and access persisted anonymous context keys. + * @returns An AnonymousContextProcessor. + */ +function AnonymousContextProcessor(persistentStorage) { + function getContextKeyIdString(kind) { + if (kind === undefined || kind === null || kind === 'user') { + return ldUserIdKey; + } + return `ld:$contextKey:${kind}`; + } + + function getCachedContextKey(kind) { + return persistentStorage.get(getContextKeyIdString(kind)); + } + + function setCachedContextKey(id, kind) { + return persistentStorage.set(getContextKeyIdString(kind), id); + } + + /** + * Process a single kind context, or a single context within a multi-kind context. + * @param {string} kind The kind of the context. Independent because the kind is not prevent + * within a context in a multi-kind context. + * @param {Object} context + * @returns {Promise} a promise that resolves to a processed contexts, or rejects + * a context which cannot be processed. + */ + function processSingleKindContext(kind, context) { + // We are working on a copy of an original context, so we want to re-assign + // versus duplicating it again. + + /* eslint-disable no-param-reassign */ + if (context.key !== null && context.key !== undefined) { + context.key = context.key.toString(); + return Promise.resolve(context); + } + + if (context.anonymous) { + // If the key doesn't exist, then the persistent storage will resolve + // with undefined. + return getCachedContextKey(kind).then(cachedId => { + if (cachedId) { + context.key = cachedId; + return context; + } else { + const id = uuidv1(); + context.key = id; + return setCachedContextKey(id, kind).then(() => context); + } + }); + } else { + return Promise.reject(new errors.LDInvalidUserError(messages.invalidContext())); + } + /* eslint-enable no-param-reassign */ + } + + /** + * Process the context, returning a Promise that resolves to the processed context, or rejects if there is an error. + * @param {Object} context + * @returns {Promise} A promise which resolves to a processed context, or a rejection if the context cannot be + * processed. The context should still be checked for overall validity after being processed. + */ + this.processContext = context => { + if (!context) { + return Promise.reject(new errors.LDInvalidUserError(messages.contextNotSpecified())); + } + + const processedContext = utils.clone(context); + + if (context.kind === 'multi') { + const kinds = getContextKinds(processedContext); + + return Promise.all(kinds.map(kind => processSingleKindContext(kind, processedContext[kind]))).then( + () => processedContext + ); + } + return processSingleKindContext(context.kind, processedContext); + }; +} + +module.exports = AnonymousContextProcessor; diff --git a/node_modules/launchdarkly-js-sdk-common/src/ContextFilter.js b/node_modules/launchdarkly-js-sdk-common/src/ContextFilter.js new file mode 100644 index 00000000..f3eb8b82 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/ContextFilter.js @@ -0,0 +1,142 @@ +const AttributeReference = require('./attributeReference'); + +function ContextFilter(config) { + const filter = {}; + + const allAttributesPrivate = config.allAttributesPrivate; + const privateAttributes = config.privateAttributes || []; + + // These attributes cannot be removed via a private attribute. + const protectedAttributes = ['key', 'kind', '_meta', 'anonymous']; + + const legacyTopLevelCopyAttributes = ['name', 'ip', 'firstName', 'lastName', 'email', 'avatar', 'country']; + + /** + * For the given context and configuration get a list of attributes to filter. + * @param {Object} context + * @returns {string[]} A list of the attributes to filter. + */ + const getAttributesToFilter = (context, redactAnonymous) => + (allAttributesPrivate || (redactAnonymous && context.anonymous) + ? Object.keys(context) + : [...privateAttributes, ...((context._meta && context._meta.privateAttributes) || [])] + ).filter(attr => !protectedAttributes.some(protectedAttr => AttributeReference.compare(attr, protectedAttr))); + + /** + * @param {Object} context + * @param {boolean} redactAnonymous + * @returns {Object} A copy of the context with private attributes removed, + * and the redactedAttributes meta populated. + */ + const filterSingleKind = (context, redactAnonymous) => { + if (typeof context !== 'object' || context === null || Array.isArray(context)) { + return undefined; + } + + const { cloned, excluded } = AttributeReference.cloneExcluding( + context, + getAttributesToFilter(context, redactAnonymous) + ); + cloned.key = String(cloned.key); + if (excluded.length) { + if (!cloned._meta) { + cloned._meta = {}; + } + cloned._meta.redactedAttributes = excluded; + } + if (cloned._meta) { + delete cloned._meta['privateAttributes']; + if (Object.keys(cloned._meta).length === 0) { + delete cloned._meta; + } + } + // Make sure anonymous is boolean if present. + // Null counts as present, and would be falsy, which is the default. + if (cloned.anonymous !== undefined) { + cloned.anonymous = !!cloned.anonymous; + } + + return cloned; + }; + + /** + * @param {Object} context + * @param {boolean} redactAnonymous + * @returns {Object} A copy of the context with the private attributes removed, + * and the redactedAttributes meta populated for each sub-context. + */ + const filterMultiKind = (context, redactAnonymous) => { + const filtered = { + kind: context.kind, + }; + const contextKeys = Object.keys(context); + + for (const contextKey of contextKeys) { + if (contextKey !== 'kind') { + const filteredContext = filterSingleKind(context[contextKey], redactAnonymous); + if (filteredContext) { + filtered[contextKey] = filteredContext; + } + } + } + return filtered; + }; + + /** + * Convert the LDUser object into an LDContext object. + * @param {Object} user The LDUser to produce an LDContext for. + * @returns {Object} A single kind context based on the provided user. + */ + const legacyToSingleKind = user => { + const filtered = { + /* Destructure custom items into the top level. + Duplicate keys will be overridden by previously + top level items. + */ + ...(user.custom || {}), + + // Implicity a user kind. + kind: 'user', + + key: user.key, + }; + + if (user.anonymous !== undefined) { + filtered.anonymous = !!user.anonymous; + } + + // Copy top level keys and convert them to strings. + // Remove keys that may have been destructured from `custom`. + for (const key of legacyTopLevelCopyAttributes) { + delete filtered[key]; + if (user[key] !== undefined && user[key] !== null) { + filtered[key] = String(user[key]); + } + } + + if (user.privateAttributeNames !== undefined && user.privateAttributeNames !== null) { + filtered._meta = filtered._meta || {}; + // If any private attributes started with '/' we need to convert them to references, otherwise the '/' will + // cause the literal to incorrectly be treated as a reference. + filtered._meta.privateAttributes = user.privateAttributeNames.map(literal => + literal.startsWith('/') ? AttributeReference.literalToReference(literal) : literal + ); + } + + return filtered; + }; + + filter.filter = (context, redactAnonymous = false) => { + if (context.kind === undefined || context.kind === null) { + return filterSingleKind(legacyToSingleKind(context), redactAnonymous); + } else if (context.kind === 'multi') { + return filterMultiKind(context, redactAnonymous); + } else { + return filterSingleKind(context, redactAnonymous); + } + }; + + return filter; +} + +module.exports = ContextFilter; diff --git a/node_modules/launchdarkly-js-sdk-common/src/EventEmitter.js b/node_modules/launchdarkly-js-sdk-common/src/EventEmitter.js new file mode 100644 index 00000000..346a664f --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/EventEmitter.js @@ -0,0 +1,60 @@ +function EventEmitter(logger) { + const emitter = {}; + const events = {}; + + const listeningTo = event => !!events[event]; + + emitter.on = function(event, handler, context) { + events[event] = events[event] || []; + events[event] = events[event].concat({ + handler: handler, + context: context, + }); + }; + + emitter.off = function(event, handler, context) { + if (!events[event]) { + return; + } + for (let i = 0; i < events[event].length; i++) { + if (events[event][i].handler === handler && events[event][i].context === context) { + events[event] = events[event].slice(0, i).concat(events[event].slice(i + 1)); + } + } + }; + + emitter.emit = function(event) { + if (!events[event]) { + return; + } + // Copy the list of handlers before iterating, in case any handler adds or removes another handler. + // Any such changes should not affect what we do here-- we want to notify every handler that existed + // at the moment that the event was fired. + const copiedHandlers = events[event].slice(0); + for (let i = 0; i < copiedHandlers.length; i++) { + copiedHandlers[i].handler.apply(copiedHandlers[i].context, Array.prototype.slice.call(arguments, 1)); + } + }; + + emitter.getEvents = function() { + return Object.keys(events); + }; + + emitter.getEventListenerCount = function(event) { + return events[event] ? events[event].length : 0; + }; + + emitter.maybeReportError = function(error) { + if (!error) { + return; + } + if (listeningTo('error')) { + this.emit('error', error); + } else { + (logger || console).error(error.message); + } + }; + return emitter; +} + +module.exports = EventEmitter; diff --git a/node_modules/launchdarkly-js-sdk-common/src/EventProcessor.js b/node_modules/launchdarkly-js-sdk-common/src/EventProcessor.js new file mode 100644 index 00000000..e6a0facb --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/EventProcessor.js @@ -0,0 +1,180 @@ +const EventSender = require('./EventSender'); +const MultiEventSummarizer = require('./MultiEventSummarizer'); +const ContextFilter = require('./ContextFilter'); +const errors = require('./errors'); +const messages = require('./messages'); +const utils = require('./utils'); +const { getContextKeys } = require('./context'); + +function EventProcessor( + platform, + options, + environmentId, + diagnosticsAccumulator = null, + emitter = null, + sender = null +) { + const processor = {}; + const eventSender = sender || EventSender(platform, environmentId, options); + const mainEventsUrl = utils.appendUrlPath(options.eventsUrl, '/events/bulk/' + environmentId); + const contextFilter = ContextFilter(options); + const summarizer = MultiEventSummarizer(contextFilter); + const samplingInterval = options.samplingInterval; + const eventCapacity = options.eventCapacity; + const flushInterval = options.flushInterval; + const logger = options.logger; + let queue = []; + let lastKnownPastTime = 0; + let disabled = false; + let exceededCapacity = false; + let flushTimer; + + function shouldSampleEvent() { + return samplingInterval === 0 || Math.floor(Math.random() * samplingInterval) === 0; + } + + function shouldDebugEvent(e) { + if (e.debugEventsUntilDate) { + // The "last known past time" comes from the last HTTP response we got from the server. + // In case the client's time is set wrong, at least we know that any expiration date + // earlier than that point is definitely in the past. If there's any discrepancy, we + // want to err on the side of cutting off event debugging sooner. + return e.debugEventsUntilDate > lastKnownPastTime && e.debugEventsUntilDate > new Date().getTime(); + } + return false; + } + + // Transform an event from its internal format to the format we use when sending a payload. + function makeOutputEvent(e) { + const ret = utils.extend({}, e); + + // Identify, feature, and custom events should all include the full context. + // Debug events do as well, but are not handled by this code path. + if (e.kind === 'identify' || e.kind === 'feature' || e.kind === 'custom') { + ret.context = contextFilter.filter(e.context); + } else { + ret.contextKeys = getContextKeysFromEvent(e); + delete ret['context']; + } + + if (e.kind === 'feature') { + delete ret['trackEvents']; + delete ret['debugEventsUntilDate']; + } + return ret; + } + + function getContextKeysFromEvent(event) { + return getContextKeys(event.context, logger); + } + + function addToOutbox(event) { + if (queue.length < eventCapacity) { + queue.push(event); + exceededCapacity = false; + } else { + if (!exceededCapacity) { + exceededCapacity = true; + logger.warn(messages.eventCapacityExceeded()); + } + if (diagnosticsAccumulator) { + // For diagnostic events, we track how many times we had to drop an event due to exceeding the capacity. + diagnosticsAccumulator.incrementDroppedEvents(); + } + } + } + + processor.enqueue = function(event) { + if (disabled) { + return; + } + let addFullEvent = false; + let addDebugEvent = false; + + // Add event to the summary counters if appropriate + summarizer.summarizeEvent(event); + + // Decide whether to add the event to the payload. Feature events may be added twice, once for + // the event (if tracked) and once for debugging. + if (event.kind === 'feature') { + if (shouldSampleEvent()) { + addFullEvent = !!event.trackEvents; + addDebugEvent = shouldDebugEvent(event); + } + } else { + addFullEvent = shouldSampleEvent(); + } + + if (addFullEvent) { + addToOutbox(makeOutputEvent(event)); + } + if (addDebugEvent) { + const debugEvent = utils.extend({}, event, { kind: 'debug' }); + debugEvent.context = contextFilter.filter(debugEvent.context); + delete debugEvent['trackEvents']; + delete debugEvent['debugEventsUntilDate']; + addToOutbox(debugEvent); + } + }; + + processor.flush = async function() { + if (disabled) { + return Promise.resolve(); + } + const eventsToSend = queue; + const summaries = summarizer.getSummaries(); + + summaries.forEach(summary => { + if (Object.keys(summary.features).length) { + eventsToSend.push(summary); + } + }); + + if (diagnosticsAccumulator) { + // For diagnostic events, we record how many events were in the queue at the last flush (since "how + // many events happened to be in the queue at the moment we decided to send a diagnostic event" would + // not be a very useful statistic). + diagnosticsAccumulator.setEventsInLastBatch(eventsToSend.length); + } + if (eventsToSend.length === 0) { + return Promise.resolve(); + } + queue = []; + logger.debug(messages.debugPostingEvents(eventsToSend.length)); + return eventSender.sendEvents(eventsToSend, mainEventsUrl).then(responseInfo => { + if (responseInfo) { + if (responseInfo.serverTime) { + lastKnownPastTime = responseInfo.serverTime; + } + if (!errors.isHttpErrorRecoverable(responseInfo.status)) { + disabled = true; + } + if (responseInfo.status >= 400) { + utils.onNextTick(() => { + emitter.maybeReportError( + new errors.LDUnexpectedResponseError( + messages.httpErrorMessage(responseInfo.status, 'event posting', 'some events were dropped') + ) + ); + }); + } + } + }); + }; + + processor.start = function() { + const flushTick = () => { + processor.flush(); + flushTimer = setTimeout(flushTick, flushInterval); + }; + flushTimer = setTimeout(flushTick, flushInterval); + }; + + processor.stop = function() { + clearTimeout(flushTimer); + }; + + return processor; +} + +module.exports = EventProcessor; diff --git a/node_modules/launchdarkly-js-sdk-common/src/EventSender.js b/node_modules/launchdarkly-js-sdk-common/src/EventSender.js new file mode 100644 index 00000000..5a9a6204 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/EventSender.js @@ -0,0 +1,64 @@ +const errors = require('./errors'); +const utils = require('./utils'); +const { v1: uuidv1 } = require('uuid'); +const { getLDHeaders, transformHeaders } = require('./headers'); + +function EventSender(platform, environmentId, options) { + const baseHeaders = utils.extend({ 'Content-Type': 'application/json' }, getLDHeaders(platform, options)); + const sender = {}; + + function getResponseInfo(result) { + const ret = { status: result.status }; + const dateStr = result.header('date'); + if (dateStr) { + const time = Date.parse(dateStr); + if (time) { + ret.serverTime = time; + } + } + return ret; + } + + sender.sendEvents = (events, url, isDiagnostic) => { + if (!platform.httpRequest) { + return Promise.resolve(); + } + + const jsonBody = JSON.stringify(events); + const payloadId = isDiagnostic ? null : uuidv1(); + + function doPostRequest(canRetry) { + const headers = isDiagnostic + ? baseHeaders + : utils.extend({}, baseHeaders, { + 'X-LaunchDarkly-Event-Schema': '4', + 'X-LaunchDarkly-Payload-ID': payloadId, + }); + return platform + .httpRequest('POST', url, transformHeaders(headers, options), jsonBody) + .promise.then(result => { + if (!result) { + // This was a response from a fire-and-forget request, so we won't have a status. + return; + } + if (result.status >= 400 && errors.isHttpErrorRecoverable(result.status) && canRetry) { + return doPostRequest(false); + } else { + return getResponseInfo(result); + } + }) + .catch(() => { + if (canRetry) { + return doPostRequest(false); + } + return Promise.reject(); + }); + } + + return doPostRequest(true).catch(() => {}); + }; + + return sender; +} + +module.exports = EventSender; diff --git a/node_modules/launchdarkly-js-sdk-common/src/EventSummarizer.js b/node_modules/launchdarkly-js-sdk-common/src/EventSummarizer.js new file mode 100644 index 00000000..7d15e146 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/EventSummarizer.js @@ -0,0 +1,106 @@ +const { getContextKinds } = require('./context'); + +function getKinds(event) { + if (event.context) { + return getContextKinds(event.context); + } + if (event.contextKeys) { + return Object.keys(event.contextKeys); + } + return []; +} + +function EventSummarizer() { + const es = {}; + + let startDate = 0, + endDate = 0, + counters = {}, + contextKinds = {}; + + es.summarizeEvent = event => { + if (event.kind === 'feature') { + const counterKey = + event.key + + ':' + + (event.variation !== null && event.variation !== undefined ? event.variation : '') + + ':' + + (event.version !== null && event.version !== undefined ? event.version : ''); + const counterVal = counters[counterKey]; + let kinds = contextKinds[event.key]; + if (!kinds) { + kinds = new Set(); + contextKinds[event.key] = kinds; + } + getKinds(event).forEach(kind => kinds.add(kind)); + + if (counterVal) { + counterVal.count = counterVal.count + 1; + } else { + counters[counterKey] = { + count: 1, + key: event.key, + version: event.version, + variation: event.variation, + value: event.value, + default: event.default, + }; + } + if (startDate === 0 || event.creationDate < startDate) { + startDate = event.creationDate; + } + if (event.creationDate > endDate) { + endDate = event.creationDate; + } + } + }; + + es.getSummary = () => { + const flagsOut = {}; + let empty = true; + for (const c of Object.values(counters)) { + let flag = flagsOut[c.key]; + if (!flag) { + flag = { + default: c.default, + counters: [], + contextKinds: [...contextKinds[c.key]], + }; + flagsOut[c.key] = flag; + } + const counterOut = { + value: c.value, + count: c.count, + }; + if (c.variation !== undefined && c.variation !== null) { + counterOut.variation = c.variation; + } + if (c.version !== undefined && c.version !== null) { + counterOut.version = c.version; + } else { + counterOut.unknown = true; + } + flag.counters.push(counterOut); + empty = false; + } + return empty + ? null + : { + startDate, + endDate, + features: flagsOut, + kind: 'summary', + }; + }; + + es.clearSummary = () => { + startDate = 0; + endDate = 0; + counters = {}; + contextKinds = {}; + }; + + return es; +} + +module.exports = EventSummarizer; diff --git a/node_modules/launchdarkly-js-sdk-common/src/HookRunner.js b/node_modules/launchdarkly-js-sdk-common/src/HookRunner.js new file mode 100644 index 00000000..571cf6ec --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/HookRunner.js @@ -0,0 +1,250 @@ +const UNKNOWN_HOOK_NAME = 'unknown hook'; +const BEFORE_EVALUATION_STAGE_NAME = 'beforeEvaluation'; +const AFTER_EVALUATION_STAGE_NAME = 'afterEvaluation'; +const BEFORE_IDENTIFY_STAGE_NAME = 'beforeIdentify'; +const AFTER_IDENTIFY_STAGE_NAME = 'afterIdentify'; +const AFTER_TRACK_STAGE_NAME = 'afterTrack'; + +/** + * Safely executes a hook stage function, logging any errors. + * @param {{ error: (message: string) => void } | undefined} logger The logger instance. + * @param {string} method The name of the hook stage being executed (e.g., 'beforeEvaluation'). + * @param {string} hookName The name of the hook. + * @param {() => any} stage The function representing the hook stage to execute. + * @param {any} def The default value to return if the stage function throws an error. + * @returns {any} The result of the stage function, or the default value if an error occurred. + */ +function tryExecuteStage(logger, method, hookName, stage, def) { + try { + return stage(); + } catch (err) { + logger?.error(`An error was encountered in "${method}" of the "${hookName}" hook: ${err}`); + return def; + } +} + +/** + * Safely gets the name of a hook from its metadata. + * @param {{ error: (message: string) => void }} logger The logger instance. + * @param {{ getMetadata: () => { name?: string } }} hook The hook instance. + * @returns {string} The name of the hook, or 'unknown hook' if unable to retrieve it. + */ +function getHookName(logger, hook) { + try { + return hook.getMetadata().name || UNKNOWN_HOOK_NAME; + } catch { + logger.error(`Exception thrown getting metadata for hook. Unable to get hook name.`); + return UNKNOWN_HOOK_NAME; + } +} + +/** + * Executes the 'beforeEvaluation' stage for all registered hooks. + * @param {{ error: (message: string) => void }} logger The logger instance. + * @param {Array<{ beforeEvaluation?: (hookContext: object, data: object) => object }>} hooks The array of hook instances. + * @param {{ flagKey: string, context: object, defaultValue: any }} hookContext The context for the evaluation series. + * @returns {Array} An array containing the data returned by each hook's 'beforeEvaluation' stage. + */ +function executeBeforeEvaluation(logger, hooks, hookContext) { + return hooks.map(hook => + tryExecuteStage( + logger, + BEFORE_EVALUATION_STAGE_NAME, + getHookName(logger, hook), + () => hook?.beforeEvaluation?.(hookContext, {}) ?? {}, + {} + ) + ); +} + +/** + * Executes the 'afterEvaluation' stage for all registered hooks in reverse order. + * @param {{ error: (message: string) => void }} logger The logger instance. + * @param {Array<{ afterEvaluation?: (hookContext: object, data: object, result: object) => object }>} hooks The array of hook instances. + * @param {{ flagKey: string, context: object, defaultValue: any }} hookContext The context for the evaluation series. + * @param {Array} updatedData The data collected from the 'beforeEvaluation' stages. + * @param {{ value: any, variationIndex?: number, reason?: object }} result The result of the flag evaluation. + * @returns {void} + */ +function executeAfterEvaluation(logger, hooks, hookContext, updatedData, result) { + // This iterates in reverse, versus reversing a shallow copy of the hooks, + // for efficiency. + for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) { + const hook = hooks[hookIndex]; + const data = updatedData[hookIndex]; + tryExecuteStage( + logger, + AFTER_EVALUATION_STAGE_NAME, + getHookName(logger, hook), + () => hook?.afterEvaluation?.(hookContext, data, result) ?? {}, + {} + ); + } +} + +/** + * Executes the 'beforeIdentify' stage for all registered hooks. + * @param {{ error: (message: string) => void }} logger The logger instance. + * @param {Array<{ beforeIdentify?: (hookContext: object, data: object) => object }>} hooks The array of hook instances. + * @param {{ context: object, timeout?: number }} hookContext The context for the identify series. + * @returns {Array} An array containing the data returned by each hook's 'beforeIdentify' stage. + */ +function executeBeforeIdentify(logger, hooks, hookContext) { + return hooks.map(hook => + tryExecuteStage( + logger, + BEFORE_IDENTIFY_STAGE_NAME, + getHookName(logger, hook), + () => hook?.beforeIdentify?.(hookContext, {}) ?? {}, + {} + ) + ); +} + +/** + * Executes the 'afterIdentify' stage for all registered hooks in reverse order. + * @param {{ error: (message: string) => void }} logger The logger instance. + * @param {Array<{ afterIdentify?: (hookContext: object, data: object, result: object) => object }>} hooks The array of hook instances. + * @param {{ context: object, timeout?: number }} hookContext The context for the identify series. + * @param {Array} updatedData The data collected from the 'beforeIdentify' stages. + * @param {{ status: string }} result The result of the identify operation. + * @returns {void} + */ +function executeAfterIdentify(logger, hooks, hookContext, updatedData, result) { + // This iterates in reverse, versus reversing a shallow copy of the hooks, + // for efficiency. + for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) { + const hook = hooks[hookIndex]; + const data = updatedData[hookIndex]; + tryExecuteStage( + logger, + AFTER_IDENTIFY_STAGE_NAME, + getHookName(logger, hook), + () => hook?.afterIdentify?.(hookContext, data, result) ?? {}, + {} + ); + } +} + +/** + * Executes the 'afterTrack' stage for all registered hooks in reverse order. + * @param {{ error: (message: string) => void }} logger The logger instance. + * @param {Array<{ afterTrack?: (hookContext: { context: object, data: object, metricValue: number }) => void }>} hooks The array of hook instances. + * @param {{ context: object, data: object, metricValue: number }} hookContext The context for the track operation. + * @returns {void} + */ +function executeAfterTrack(logger, hooks, hookContext) { + // This iterates in reverse, versus reversing a shallow copy of the hooks, + // for efficiency. + for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) { + const hook = hooks[hookIndex]; + tryExecuteStage( + logger, + AFTER_TRACK_STAGE_NAME, + getHookName(logger, hook), + () => hook?.afterTrack?.(hookContext), + undefined + ); + } +} + +/** + * Factory function to create a HookRunner instance. + * Manages the execution of hooks for flag evaluations and identify operations. + * @param {{ error: (message: string) => void }} logger The logger instance. + * @param {Array | undefined} initialHooks An optional array of hooks to initialize with. + * @returns {{ + * withEvaluation: (key: string, context: object, defaultValue: any, method: () => { value: any, variationIndex?: number, reason?: object }) => { value: any, variationIndex?: number, reason?: object }, + * identify: (context: object, timeout?: number) => (result: { status: string }) => void, + * addHook: (hook: object) => void + * }} The hook runner object with methods to manage and execute hooks. + */ +function createHookRunner(logger, initialHooks) { + // Use local variable instead of instance property + const hooksInternal = initialHooks ? [...initialHooks] : []; + + /** + * Wraps a flag evaluation method with before/after hook stages. + * @param {string} key The flag key. + * @param {object} context The evaluation context. + * @param {any} defaultValue The default value for the flag. + * @param {() => { value: any, variationIndex?: number, reason?: object }} method The function that performs the actual flag evaluation. + * @returns {{ value: any, variationIndex?: number, reason?: object }} The result of the flag evaluation. + */ + function withEvaluation(key, context, defaultValue, method) { + if (hooksInternal.length === 0) { + return method(); + } + const hooks = [...hooksInternal]; + /** @type {{ flagKey: string, context: object, defaultValue: any }} */ + const hookContext = { + flagKey: key, + context, + defaultValue, + }; + + // Use the logger passed into the factory + const hookData = executeBeforeEvaluation(logger, hooks, hookContext); + const result = method(); + executeAfterEvaluation(logger, hooks, hookContext, hookData, result); + return result; + } + + /** + * Wraps the identify operation with before/after hook stages. + * Executes the 'beforeIdentify' stage immediately and returns a function + * to execute the 'afterIdentify' stage later. + * @param {object} context The context being identified. + * @param {number | undefined} timeout Optional timeout for the identify operation. + * @returns {(result: { status: string }) => void} A function to call after the identify operation completes. + */ + function identify(context, timeout) { + const hooks = [...hooksInternal]; + /** @type {{ context: object, timeout?: number }} */ + const hookContext = { + context, + timeout, + }; + // Use the logger passed into the factory + const hookData = executeBeforeIdentify(logger, hooks, hookContext); + /** + * Executes the 'afterIdentify' hook stage. + * @param {{ status: string }} result The result of the identify operation. + */ + return result => { + executeAfterIdentify(logger, hooks, hookContext, hookData, result); + }; + } + + /** + * Adds a new hook to the runner. + * @param {object} hook The hook instance to add. + * @returns {void} + */ + function addHook(hook) { + // Mutate the internal hooks array + hooksInternal.push(hook); + } + + /** + * Executes the 'afterTrack' stage for all registered hooks in reverse order. + * @param {{ context: object, data: object, metricValue: number }} hookContext The context for the track operation. + * @returns {void} + */ + function afterTrack(hookContext) { + if (hooksInternal.length === 0) { + return; + } + const hooks = [...hooksInternal]; + executeAfterTrack(logger, hooks, hookContext); + } + + return { + withEvaluation, + identify, + addHook, + afterTrack, + }; +} + +module.exports = createHookRunner; diff --git a/node_modules/launchdarkly-js-sdk-common/src/Identity.js b/node_modules/launchdarkly-js-sdk-common/src/Identity.js new file mode 100644 index 00000000..9a7eef92 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/Identity.js @@ -0,0 +1,25 @@ +const utils = require('./utils'); + +function Identity(initialContext, onChange) { + const ident = {}; + let context; + + ident.setContext = function(c) { + context = utils.sanitizeContext(c); + if (context && onChange) { + onChange(utils.clone(context)); + } + }; + + ident.getContext = function() { + return context ? utils.clone(context) : null; + }; + + if (initialContext) { + ident.setContext(initialContext); + } + + return ident; +} + +module.exports = Identity; diff --git a/node_modules/launchdarkly-js-sdk-common/src/InitializationState.js b/node_modules/launchdarkly-js-sdk-common/src/InitializationState.js new file mode 100644 index 00000000..11d811fc --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/InitializationState.js @@ -0,0 +1,83 @@ +// This file provides an abstraction of the client's startup state. +// +// Startup can either succeed or fail exactly once; calling signalSuccess() or signalFailure() +// after that point has no effect. +// +// On success, we fire both an "initialized" event and a "ready" event. Both the waitForInitialization() +// promise and the waitUntilReady() promise are resolved in this case. +// +// On failure, we fire both a "failed" event (with the error as a parameter) and a "ready" event. +// The waitForInitialization() promise is rejected, but the waitUntilReady() promise is resolved. +// +// To complicate things, we must *not* create the waitForInitialization() promise unless it is +// requested, because otherwise failures would cause an *unhandled* rejection which can be a +// serious problem in some environments. So we use a somewhat roundabout system for tracking the +// initialization state and lazily creating this promise. + +const readyEvent = 'ready', + successEvent = 'initialized', + failureEvent = 'failed'; + +function InitializationStateTracker(eventEmitter) { + let succeeded = false, + failed = false, + failureValue = null, + initializationPromise = null; + + const readyPromise = new Promise(resolve => { + const onReady = () => { + eventEmitter.off(readyEvent, onReady); // we can't use "once" because it's not available on some JS platforms + resolve(); + }; + eventEmitter.on(readyEvent, onReady); + }).catch(() => {}); // this Promise should never be rejected, but the catch handler is a safety measure + + return { + getInitializationPromise: () => { + if (initializationPromise) { + return initializationPromise; + } + if (succeeded) { + return Promise.resolve(); + } + if (failed) { + return Promise.reject(failureValue); + } + initializationPromise = new Promise((resolve, reject) => { + const onSuccess = () => { + eventEmitter.off(successEvent, onSuccess); + resolve(); + }; + const onFailure = err => { + eventEmitter.off(failureEvent, onFailure); + reject(err); + }; + eventEmitter.on(successEvent, onSuccess); + eventEmitter.on(failureEvent, onFailure); + }); + return initializationPromise; + }, + + getReadyPromise: () => readyPromise, + + signalSuccess: () => { + if (!succeeded && !failed) { + succeeded = true; + eventEmitter.emit(successEvent); + eventEmitter.emit(readyEvent); + } + }, + + signalFailure: err => { + if (!succeeded && !failed) { + failed = true; + failureValue = err; + eventEmitter.emit(failureEvent, err); + eventEmitter.emit(readyEvent); + } + eventEmitter.maybeReportError(err); // the "error" event can be emitted more than once, unlike the others + }, + }; +} + +module.exports = InitializationStateTracker; diff --git a/node_modules/launchdarkly-js-sdk-common/src/InspectorManager.js b/node_modules/launchdarkly-js-sdk-common/src/InspectorManager.js new file mode 100644 index 00000000..ce8e7028 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/InspectorManager.js @@ -0,0 +1,157 @@ +const messages = require('./messages'); +const SafeInspector = require('./SafeInspector'); +const { onNextTick } = require('./utils'); + +/** + * The types of supported inspectors. + */ +const InspectorTypes = { + flagUsed: 'flag-used', + flagDetailsChanged: 'flag-details-changed', + flagDetailChanged: 'flag-detail-changed', + clientIdentityChanged: 'client-identity-changed', +}; + +Object.freeze(InspectorTypes); + +/** + * Manages dispatching of inspection data to registered inspectors. + */ +function InspectorManager(inspectors, logger) { + const manager = {}; + + /** + * Collection of inspectors keyed by type. + * + * Inspectors are async by default. + * + * @type {{[type: string]: object[]}} + */ + const inspectorsByType = { + [InspectorTypes.flagUsed]: [], + [InspectorTypes.flagDetailsChanged]: [], + [InspectorTypes.flagDetailChanged]: [], + [InspectorTypes.clientIdentityChanged]: [], + }; + /** + * Collection synchronous of inspectors keyed by type. + * + * @type {{[type: string]: object[]}} + */ + const synchronousInspectorsByType = { + [InspectorTypes.flagUsed]: [], + [InspectorTypes.flagDetailsChanged]: [], + [InspectorTypes.flagDetailChanged]: [], + [InspectorTypes.clientIdentityChanged]: [], + }; + + const safeInspectors = inspectors && inspectors.map(inspector => SafeInspector(inspector, logger)); + + safeInspectors && + safeInspectors.forEach(safeInspector => { + // Only add inspectors of supported types. + if (Object.prototype.hasOwnProperty.call(inspectorsByType, safeInspector.type) && !safeInspector.synchronous) { + inspectorsByType[safeInspector.type].push(safeInspector); + } else if ( + Object.prototype.hasOwnProperty.call(synchronousInspectorsByType, safeInspector.type) && + safeInspector.synchronous + ) { + synchronousInspectorsByType[safeInspector.type].push(safeInspector); + } else { + logger.warn(messages.invalidInspector(safeInspector.type, safeInspector.name)); + } + }); + + /** + * Check if there is an inspector of a specific type registered. + * + * @param {string} type The type of the inspector to check. + * @returns True if there are any inspectors of that type registered. + */ + manager.hasListeners = type => + (inspectorsByType[type] && inspectorsByType[type].length) || + (synchronousInspectorsByType[type] && synchronousInspectorsByType[type].length); + + /** + * Notify registered inspectors of a flag being used. + * + * The notification itself will be dispatched asynchronously. + * + * @param {string} flagKey The key for the flag. + * @param {Object} detail The LDEvaluationDetail for the flag. + * @param {Object} context The LDContext for the flag. + */ + manager.onFlagUsed = (flagKey, detail, context) => { + const type = InspectorTypes.flagUsed; + if (synchronousInspectorsByType[type].length) { + synchronousInspectorsByType[type].forEach(inspector => inspector.method(flagKey, detail, context)); + } + if (inspectorsByType[type].length) { + onNextTick(() => { + inspectorsByType[type].forEach(inspector => inspector.method(flagKey, detail, context)); + }); + } + }; + + /** + * Notify registered inspectors that the flags have been replaced. + * + * The notification itself will be dispatched asynchronously. + * + * @param {Record} flags The current flags as a Record. + */ + manager.onFlags = flags => { + const type = InspectorTypes.flagDetailsChanged; + if (synchronousInspectorsByType[type].length) { + synchronousInspectorsByType[type].forEach(inspector => inspector.method(flags)); + } + if (inspectorsByType[type].length) { + onNextTick(() => { + inspectorsByType[type].forEach(inspector => inspector.method(flags)); + }); + } + }; + + /** + * Notify registered inspectors that a flag value has changed. + * + * The notification itself will be dispatched asynchronously. + * + * @param {string} flagKey The key for the flag that changed. + * @param {Object} flag An `LDEvaluationDetail` for the flag. + */ + manager.onFlagChanged = (flagKey, flag) => { + const type = InspectorTypes.flagDetailChanged; + if (synchronousInspectorsByType[type].length) { + synchronousInspectorsByType[type].forEach(inspector => inspector.method(flagKey, flag)); + } + if (inspectorsByType[type].length) { + onNextTick(() => { + inspectorsByType[type].forEach(inspector => inspector.method(flagKey, flag)); + }); + } + }; + + /** + * Notify the registered inspectors that the context identity has changed. + * + * The notification itself will be dispatched asynchronously. + * + * @param {Object} context The `LDContext` which is now identified. + */ + manager.onIdentityChanged = context => { + const type = InspectorTypes.clientIdentityChanged; + if (synchronousInspectorsByType[type].length) { + synchronousInspectorsByType[type].forEach(inspector => inspector.method(context)); + } + if (inspectorsByType[type].length) { + onNextTick(() => { + inspectorsByType[type].forEach(inspector => inspector.method(context)); + }); + } + }; + + return manager; +} + +module.exports = { InspectorTypes, InspectorManager }; diff --git a/node_modules/launchdarkly-js-sdk-common/src/MultiEventSummarizer.js b/node_modules/launchdarkly-js-sdk-common/src/MultiEventSummarizer.js new file mode 100644 index 00000000..f2818a9a --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/MultiEventSummarizer.js @@ -0,0 +1,60 @@ +const canonicalize = require('./canonicalize'); +const EventSummarizer = require('./EventSummarizer'); + +/** + * Construct a multi-event summarizer. This summarizer produces a summary event for each unique context. + * @param {{filter: (context: any) => any}} contextFilter + */ +function MultiEventSummarizer(contextFilter) { + let summarizers = {}; + let contexts = {}; + + /** + * Summarize the given event. + * @param {{ + * kind: string, + * context?: any, + * }} event + */ + function summarizeEvent(event) { + if (event.kind === 'feature') { + const key = canonicalize(event.context); + if (!key) { + return; + } + + let summarizer = summarizers[key]; + if (!summarizer) { + summarizers[key] = EventSummarizer(); + summarizer = summarizers[key]; + contexts[key] = event.context; + } + + summarizer.summarizeEvent(event); + } + } + + /** + * Get the summaries of the events that have been summarized. + * @returns {any[]} + */ + function getSummaries() { + const summarizersToFlush = summarizers; + const contextsForSummaries = contexts; + + summarizers = {}; + contexts = {}; + return Object.entries(summarizersToFlush).map(([key, summarizer]) => { + const summary = summarizer.getSummary(); + summary.context = contextFilter.filter(contextsForSummaries[key]); + return summary; + }); + } + + return { + summarizeEvent, + getSummaries, + }; +} + +module.exports = MultiEventSummarizer; diff --git a/node_modules/launchdarkly-js-sdk-common/src/PersistentFlagStore.js b/node_modules/launchdarkly-js-sdk-common/src/PersistentFlagStore.js new file mode 100644 index 00000000..05d31b62 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/PersistentFlagStore.js @@ -0,0 +1,50 @@ +const utils = require('./utils'); + +function PersistentFlagStore(storage, environment, hash, ident) { + const store = {}; + + function getFlagsKey() { + let key = ''; + const context = ident.getContext(); + if (context) { + key = hash || utils.btoa(JSON.stringify(context)); + } + return 'ld:' + environment + ':' + key; + } + + // Returns a Promise which will be resolved with a parsed JSON value if a stored value was available, + // or resolved with null if there was no value or if storage was not available. + store.loadFlags = () => + storage.get(getFlagsKey()).then(dataStr => { + if (dataStr === null || dataStr === undefined) { + return null; + } + try { + let data = JSON.parse(dataStr); + if (data) { + const schema = data.$schema; + if (schema === undefined || schema < 1) { + data = utils.transformValuesToVersionedValues(data); + } else { + delete data['$schema']; + } + } + return data; + } catch (ex) { + return store.clearFlags().then(() => null); + } + }); + + // Resolves with true if successful, or false if storage is unavailable. Never rejects. + store.saveFlags = flags => { + const data = utils.extend({}, flags, { $schema: 1 }); + return storage.set(getFlagsKey(), JSON.stringify(data)); + }; + + // Resolves with true if successful, or false if storage is unavailable. Never rejects. + store.clearFlags = () => storage.clear(getFlagsKey()); + + return store; +} + +module.exports = PersistentFlagStore; diff --git a/node_modules/launchdarkly-js-sdk-common/src/PersistentStorage.js b/node_modules/launchdarkly-js-sdk-common/src/PersistentStorage.js new file mode 100644 index 00000000..0d811db7 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/PersistentStorage.js @@ -0,0 +1,81 @@ +const messages = require('./messages'); + +// The localStorageProvider is provided by the platform object. It should have the following +// methods, each of which should return a Promise: +// - get(key): Gets the string value, if any, for the given key +// - set(key, value): Stores a string value for the given key +// - remove(key): Removes the given key +// +// Storage is just a light wrapper of the localStorageProvider, adding error handling and +// ensuring that we don't call it if it's unavailable. The get method will simply resolve +// with an undefined value if there is an error or if there is no localStorageProvider. +// None of the promises returned by Storage will ever be rejected. +// +// It is always possible that the underlying platform storage mechanism might fail or be +// disabled. If so, it's likely that it will keep failing, so we will only log one warning +// instead of repetitive warnings. +function PersistentStorage(localStorageProvider, logger) { + const storage = {}; + let loggedError = false; + + const logError = err => { + if (!loggedError) { + loggedError = true; + logger.warn(messages.localStorageUnavailable(err)); + } + }; + + storage.isEnabled = () => !!localStorageProvider; + + // Resolves with a value, or undefined if storage is unavailable. Never rejects. + storage.get = key => + new Promise(resolve => { + if (!localStorageProvider) { + resolve(undefined); + return; + } + localStorageProvider + .get(key) + .then(resolve) + .catch(err => { + logError(err); + resolve(undefined); + }); + }); + + // Resolves with true if successful, or false if storage is unavailable. Never rejects. + storage.set = (key, value) => + new Promise(resolve => { + if (!localStorageProvider) { + resolve(false); + return; + } + localStorageProvider + .set(key, value) + .then(() => resolve(true)) + .catch(err => { + logError(err); + resolve(false); + }); + }); + + // Resolves with true if successful, or false if storage is unavailable. Never rejects. + storage.clear = key => + new Promise(resolve => { + if (!localStorageProvider) { + resolve(false); + return; + } + localStorageProvider + .clear(key) + .then(() => resolve(true)) + .catch(err => { + logError(err); + resolve(false); + }); + }); + + return storage; +} + +module.exports = PersistentStorage; diff --git a/node_modules/launchdarkly-js-sdk-common/src/Requestor.js b/node_modules/launchdarkly-js-sdk-common/src/Requestor.js new file mode 100644 index 00000000..0507a4d5 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/Requestor.js @@ -0,0 +1,112 @@ +const utils = require('./utils'); +const errors = require('./errors'); +const messages = require('./messages'); +const promiseCoalescer = require('./promiseCoalescer'); +const { transformHeaders, getLDHeaders } = require('./headers'); + +const jsonContentType = 'application/json'; + +function getResponseError(result) { + if (result.status === 404) { + return new errors.LDInvalidEnvironmentIdError(messages.environmentNotFound()); + } else { + return new errors.LDFlagFetchError(messages.errorFetchingFlags(result.statusText || String(result.status))); + } +} + +function Requestor(platform, options, environment) { + const baseUrl = options.baseUrl; + const useReport = options.useReport; + const withReasons = options.evaluationReasons; + const logger = options.logger; + + const requestor = {}; + + const activeRequests = {}; // map of URLs to promiseCoalescers + + function fetchJSON(endpoint, body) { + if (!platform.httpRequest) { + return new Promise((resolve, reject) => { + reject(new errors.LDFlagFetchError(messages.httpUnavailable())); + }); + } + + const method = body ? 'REPORT' : 'GET'; + const headers = getLDHeaders(platform, options); + if (body) { + headers['Content-Type'] = jsonContentType; + } + + let coalescer = activeRequests[endpoint]; + if (!coalescer) { + coalescer = promiseCoalescer(() => { + // this will be called once there are no more active requests for the same endpoint + delete activeRequests[endpoint]; + }); + activeRequests[endpoint] = coalescer; + } + + const req = platform.httpRequest(method, endpoint, transformHeaders(headers, options), body); + const p = req.promise.then( + result => { + if (result.status === 200) { + // We're using substring here because using startsWith would require a polyfill in IE. + if ( + result.header('content-type') && + result.header('content-type').substring(0, jsonContentType.length) === jsonContentType + ) { + return JSON.parse(result.body); + } else { + const message = messages.invalidContentType(result.header('content-type') || ''); + return Promise.reject(new errors.LDFlagFetchError(message)); + } + } else { + return Promise.reject(getResponseError(result)); + } + }, + e => Promise.reject(new errors.LDFlagFetchError(messages.networkError(e))) + ); + coalescer.addPromise(p, () => { + // this will be called if another request for the same endpoint supersedes this one + req.cancel && req.cancel(); + }); + return coalescer.resultPromise; + } + + // Performs a GET request to an arbitrary path under baseUrl. Returns a Promise which will resolve + // with the parsed JSON response, or will be rejected if the request failed. + requestor.fetchJSON = function(path) { + return fetchJSON(utils.appendUrlPath(baseUrl, path), null); + }; + + // Requests the current state of all flags for the given context from LaunchDarkly. Returns a Promise + // which will resolve with the parsed JSON response, or will be rejected if the request failed. + requestor.fetchFlagSettings = function(context, hash) { + let data; + let endpoint; + let query = ''; + let body; + + if (useReport) { + endpoint = [baseUrl, '/sdk/evalx/', environment, '/context'].join(''); + body = JSON.stringify(context); + } else { + data = utils.base64URLEncode(JSON.stringify(context)); + endpoint = [baseUrl, '/sdk/evalx/', environment, '/contexts/', data].join(''); + } + if (hash) { + query = 'h=' + hash; + } + if (withReasons) { + query = query + (query ? '&' : '') + 'withReasons=true'; + } + endpoint = endpoint + (query ? '?' : '') + query; + logger.debug(messages.debugPolling(endpoint)); + + return fetchJSON(endpoint, body); + }; + + return requestor; +} + +module.exports = Requestor; diff --git a/node_modules/launchdarkly-js-sdk-common/src/SafeInspector.js b/node_modules/launchdarkly-js-sdk-common/src/SafeInspector.js new file mode 100644 index 00000000..e172e3d0 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/SafeInspector.js @@ -0,0 +1,35 @@ +const messages = require('./messages'); + +/** + * Wrap an inspector ensuring that calling its methods are safe. + * @param {object} inspector Inspector to wrap. + */ +function SafeInspector(inspector, logger) { + let errorLogged = false; + const wrapper = { + type: inspector.type, + name: inspector.name, + synchronous: inspector.synchronous, + }; + + wrapper.method = (...args) => { + try { + inspector.method(...args); + } catch { + // If something goes wrong in an inspector we want to log that something + // went wrong. We don't want to flood the logs, so we only log something + // the first time that something goes wrong. + // We do not include the exception in the log, because we do not know what + // kind of data it may contain. + if (!errorLogged) { + errorLogged = true; + logger.warn(messages.inspectorMethodError(wrapper.type, wrapper.name)); + } + // Prevent errors. + } + }; + + return wrapper; +} + +module.exports = SafeInspector; diff --git a/node_modules/launchdarkly-js-sdk-common/src/Stream.js b/node_modules/launchdarkly-js-sdk-common/src/Stream.js new file mode 100644 index 00000000..16df5fb4 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/Stream.js @@ -0,0 +1,197 @@ +const messages = require('./messages'); +const { appendUrlPath, base64URLEncode, objectHasOwnProperty } = require('./utils'); +const { getLDHeaders, transformHeaders } = require('./headers'); +const { isHttpErrorRecoverable } = require('./errors'); + +// The underlying event source implementation is abstracted via the platform object, which should +// have these three properties: +// eventSourceFactory(): a function that takes a URL and optional config object and returns an object +// with the same methods as the regular HTML5 EventSource object. The properties in the config +// object are those supported by the launchdarkly-eventsource package; browser EventSource +// implementations don't have any config options. +// eventSourceIsActive(): a function that takes an EventSource-compatible object and returns true if +// it is in an active state (connected or connecting). +// eventSourceAllowsReport: true if REPORT is supported. + +// The read timeout for the stream is a fixed value that is set to be slightly longer than the expected +// interval between heartbeats from the LaunchDarkly streaming server. If this amount of time elapses +// with no new data, the connection will be cycled. +const streamReadTimeoutMillis = 5 * 60 * 1000; // 5 minutes +const maxRetryDelay = 30 * 1000; // Maximum retry delay 30 seconds. +const jitterRatio = 0.5; // Delay should be 50%-100% of calculated time. + +function Stream(platform, config, environment, diagnosticsAccumulator) { + const baseUrl = config.streamUrl; + const logger = config.logger; + const stream = {}; + const evalUrlPrefix = appendUrlPath(baseUrl, '/eval/' + environment); + const useReport = config.useReport; + const withReasons = config.evaluationReasons; + const baseReconnectDelay = config.streamReconnectDelay; + const headers = getLDHeaders(platform, config); + let firstConnectionErrorLogged = false; + let es = null; + let reconnectTimeoutReference = null; + let connectionAttemptStartTime; + let context = null; + let hash = null; + let handlers = null; + let retryCount = 0; + + function backoff() { + const delay = baseReconnectDelay * Math.pow(2, retryCount); + return delay > maxRetryDelay ? maxRetryDelay : delay; + } + + function jitter(computedDelayMillis) { + return computedDelayMillis - Math.trunc(Math.random() * jitterRatio * computedDelayMillis); + } + + function getNextRetryDelay() { + const delay = jitter(backoff()); + retryCount += 1; + return delay; + } + + stream.connect = function(newContext, newHash, newHandlers) { + context = newContext; + hash = newHash; + handlers = {}; + for (const key in newHandlers || {}) { + handlers[key] = function(e) { + // Reset the state for logging the first connection error so that the first + // connection error following a successful connection will once again be logged. + // We will decorate *all* handlers to do this to keep this abstraction agnostic + // for different stream implementations. + firstConnectionErrorLogged = false; + logConnectionResult(true); + newHandlers[key] && newHandlers[key](e); + }; + } + tryConnect(); + }; + + stream.disconnect = function() { + clearTimeout(reconnectTimeoutReference); + reconnectTimeoutReference = null; + closeConnection(); + }; + + stream.isConnected = function() { + return !!(es && platform.eventSourceIsActive && platform.eventSourceIsActive(es)); + }; + + function handleError(err) { + // The event source may not produce a status. But the LaunchDarkly + // polyfill can. If we can get the status, then we should stop retrying + // on certain error codes. + if (err.status && typeof err.status === 'number' && !isHttpErrorRecoverable(err.status)) { + // If we encounter an unrecoverable condition, then we do not want to + // retry anymore. + closeConnection(); + logger.error(messages.unrecoverableStreamError(err)); + // Ensure any pending retry attempts are not done. + if (reconnectTimeoutReference) { + clearTimeout(reconnectTimeoutReference); + reconnectTimeoutReference = null; + } + return; + } + + const delay = getNextRetryDelay(); + + if (!firstConnectionErrorLogged) { + logger.warn(messages.streamError(err, delay)); + firstConnectionErrorLogged = true; + } + logConnectionResult(false); + closeConnection(); + tryConnect(delay); + } + + function tryConnect(delay) { + if (!reconnectTimeoutReference) { + if (delay) { + reconnectTimeoutReference = setTimeout(openConnection, delay); + } else { + openConnection(); + } + } + } + + function openConnection() { + reconnectTimeoutReference = null; + let url; + let query = ''; + const options = { headers, readTimeoutMillis: streamReadTimeoutMillis }; + if (platform.eventSourceFactory) { + if (hash !== null && hash !== undefined) { + query = 'h=' + hash; + } + if (useReport) { + if (platform.eventSourceAllowsReport) { + url = evalUrlPrefix; + options.method = 'REPORT'; + options.headers['Content-Type'] = 'application/json'; + options.body = JSON.stringify(context); + } else { + // if we can't do REPORT, fall back to the old ping-based stream + url = appendUrlPath(baseUrl, '/ping/' + environment); + query = ''; + } + } else { + url = evalUrlPrefix + '/' + base64URLEncode(JSON.stringify(context)); + } + options.headers = transformHeaders(options.headers, config); + if (withReasons) { + query = query + (query ? '&' : '') + 'withReasons=true'; + } + url = url + (query ? '?' : '') + query; + + closeConnection(); + logger.info(messages.streamConnecting(url)); + logConnectionStarted(); + + es = platform.eventSourceFactory(url, options); + for (const key in handlers) { + if (objectHasOwnProperty(handlers, key)) { + es.addEventListener(key, handlers[key]); + } + } + + es.onerror = handleError; + + es.onopen = () => { + // If the connection is a success, then reset the retryCount. + retryCount = 0; + }; + } + } + + function closeConnection() { + if (es) { + logger.info(messages.streamClosing()); + es.close(); + es = null; + } + } + + function logConnectionStarted() { + connectionAttemptStartTime = new Date().getTime(); + } + + function logConnectionResult(success) { + if (connectionAttemptStartTime && diagnosticsAccumulator) { + diagnosticsAccumulator.recordStreamInit( + connectionAttemptStartTime, + !success, + new Date().getTime() - connectionAttemptStartTime + ); + } + connectionAttemptStartTime = null; + } + + return stream; +} + +module.exports = Stream; diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/.eslintrc.yaml b/node_modules/launchdarkly-js-sdk-common/src/__tests__/.eslintrc.yaml new file mode 100644 index 00000000..cabd464c --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/.eslintrc.yaml @@ -0,0 +1,6 @@ +--- +globals: + sinon: true + expect: true + requestor: true + client: true \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/ContextFilter-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/ContextFilter-test.js new file mode 100644 index 00000000..5cb79607 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/ContextFilter-test.js @@ -0,0 +1,460 @@ +const ContextFilter = require('../ContextFilter'); + +describe('when handling legacy user contexts', () => { + // users to serialize + const user = { + key: 'abc', + firstName: 'Sue', + custom: { bizzle: 'def', dizzle: 'ghi' }, + }; + + const userSpecifyingOwnPrivateAttr = { + key: 'abc', + firstName: 'Sue', + custom: { bizzle: 'def', dizzle: 'ghi' }, + privateAttributeNames: ['dizzle', 'unused'], + }; + + const userWithUnknownTopLevelAttrs = { + key: 'abc', + firstName: 'Sue', + species: 'human', + hatSize: 6, + custom: { bizzle: 'def', dizzle: 'ghi' }, + }; + + const anonUser = { + key: 'abc', + anonymous: true, + custom: { bizzle: 'def', dizzle: 'ghi' }, + }; + + const userWithNonStringsInStringRequiredFields = { + key: -1, + name: 0, + ip: 1, + firstName: 2, + lastName: ['a', 99, null], + email: 4, + avatar: 5, + country: 6, + custom: { + validNumericField: 7, + }, + }; + + // expected results from serializing user + const userWithNothingHidden = { + bizzle: 'def', + dizzle: 'ghi', + firstName: 'Sue', + key: 'abc', + kind: 'user', + }; + + const userWithAllAttrsHidden = { + kind: 'user', + key: 'abc', + _meta: { + redactedAttributes: ['/bizzle', '/dizzle', '/firstName'], + }, + }; + + const userWithSomeAttrsHidden = { + kind: 'user', + key: 'abc', + dizzle: 'ghi', + _meta: { + redactedAttributes: ['/bizzle', '/firstName'], + }, + }; + + const userWithOwnSpecifiedAttrHidden = { + kind: 'user', + key: 'abc', + firstName: 'Sue', + bizzle: 'def', + _meta: { + redactedAttributes: ['/dizzle'], + }, + }; + + const anonUserWithAllAttrsHidden = { + kind: 'user', + key: 'abc', + anonymous: true, + _meta: { + redactedAttributes: ['/bizzle', '/dizzle'], + }, + }; + + const userWithStringFieldsConverted = { + key: '-1', + kind: 'user', + name: '0', + ip: '1', + firstName: '2', + lastName: 'a,99,', + email: '4', + avatar: '5', + country: '6', + validNumericField: 7, + }; + + const userWithPrivateFieldsWithAPrecedingSlash = { + key: 'annoying', + custom: { + '/why': 'not', + why: 'because', + }, + privateAttributeNames: ['/why'], + }; + + const userWithPrivateFieldsWithAPrecedingSlashFiltered = { + kind: 'user', + key: 'annoying', + why: 'because', + _meta: { + redactedAttributes: ['/~1why'], + }, + }; + + it('includes all user attributes by default', () => { + const uf = ContextFilter({}); + expect(uf.filter(user)).toEqual(userWithNothingHidden); + }); + + it('hides all except key if allAttributesPrivate is true', () => { + const uf = ContextFilter({ allAttributesPrivate: true }); + expect(uf.filter(user)).toEqual(userWithAllAttrsHidden); + }); + + it('hides some attributes if privateAttributes is set', () => { + const uf = ContextFilter({ privateAttributes: ['firstName', 'bizzle'] }); + expect(uf.filter(user)).toEqual(userWithSomeAttrsHidden); + }); + + it('hides attributes specified in per-user redactedAttributes', () => { + const uf = ContextFilter({}); + expect(uf.filter(userSpecifyingOwnPrivateAttr)).toEqual(userWithOwnSpecifiedAttrHidden); + }); + + it('looks at both per-user redactedAttributes and global config', () => { + const uf = ContextFilter({ privateAttributes: ['firstName', 'bizzle'] }); + expect(uf.filter(userSpecifyingOwnPrivateAttr)).toEqual(userWithAllAttrsHidden); + }); + + it('strips unknown top-level attributes', () => { + const uf = ContextFilter({}); + expect(uf.filter(userWithUnknownTopLevelAttrs)).toEqual(userWithNothingHidden); + }); + + it('maintains anonymous in conversion to a single kind context', () => { + const uf = ContextFilter({ allAttributesPrivate: true }); + expect(uf.filter(anonUser)).toEqual(anonUserWithAllAttrsHidden); + }); + + it('converts non-boolean "anonymous" to boolean "anonymous"', () => { + const uf = ContextFilter({ allAttributesPrivate: true }); + expect(uf.filter({ key: 'user', anonymous: 'yes' })).toEqual({ key: 'user', kind: 'user', anonymous: true }); + }); + + it('converts fields to string types when needed', () => { + const uf = ContextFilter({}); + expect(uf.filter(userWithNonStringsInStringRequiredFields)).toEqual(userWithStringFieldsConverted); + }); + + it('it handles legacy names which had a preceding slash', () => { + const uf = ContextFilter({}); + expect(uf.filter(userWithPrivateFieldsWithAPrecedingSlash)).toEqual( + userWithPrivateFieldsWithAPrecedingSlashFiltered + ); + }); + + it.each([null, undefined])('handles null and undefined the same for built-in attributes', value => { + const cf = ContextFilter({}); + const user = { + key: 'userKey', + name: value, + ip: value, + firstName: value, + lastName: value, + email: value, + avatar: value, + country: value, + }; + expect(cf.filter(user)).toEqual({ key: 'userKey', kind: 'user' }); + }); +}); + +describe('when handling single kind contexts', () => { + // users to serialize + const context = { + kind: 'organization', + key: 'abc', + firstName: 'Sue', + bizzle: 'def', + dizzle: 'ghi', + }; + + const contextSpecifyingOwnPrivateAttr = { + kind: 'organization', + key: 'abc', + firstName: 'Sue', + bizzle: 'def', + dizzle: 'ghi', + _meta: { + privateAttributes: ['dizzle', 'unused'], + }, + }; + + const anonymousContext = { + kind: 'organization', + key: 'abc', + anonymous: true, + bizzle: 'def', + dizzle: 'ghi', + }; + + // expected results from serializing context + const userWithAllAttrsHidden = { + kind: 'organization', + key: 'abc', + _meta: { + redactedAttributes: ['/bizzle', '/dizzle', '/firstName'], + }, + }; + + const contextWithSomeAttrsHidden = { + kind: 'organization', + key: 'abc', + dizzle: 'ghi', + _meta: { + redactedAttributes: ['/bizzle', '/firstName'], + }, + }; + + const contextWithOwnSpecifiedAttrHidden = { + kind: 'organization', + key: 'abc', + firstName: 'Sue', + bizzle: 'def', + _meta: { + redactedAttributes: ['/dizzle'], + }, + }; + + const contextWithAllAttrsHidden = { + kind: 'organization', + key: 'abc', + anonymous: true, + _meta: { + redactedAttributes: ['/bizzle', '/dizzle'], + }, + }; + + it('includes all attributes by default', () => { + const uf = ContextFilter({}); + expect(uf.filter(context)).toEqual(context); + }); + + it('hides all except key if allAttributesPrivate is true', () => { + const uf = ContextFilter({ allAttributesPrivate: true }); + expect(uf.filter(context)).toEqual(userWithAllAttrsHidden); + }); + + it('hides some attributes if privateAttributes is set', () => { + const uf = ContextFilter({ privateAttributes: ['firstName', 'bizzle'] }); + expect(uf.filter(context)).toEqual(contextWithSomeAttrsHidden); + }); + + it('hides attributes specified in per-context redactedAttributes', () => { + const uf = ContextFilter({}); + expect(uf.filter(contextSpecifyingOwnPrivateAttr)).toEqual(contextWithOwnSpecifiedAttrHidden); + }); + + it('looks at both per-context redactedAttributes and global config', () => { + const uf = ContextFilter({ privateAttributes: ['firstName', 'bizzle'] }); + expect(uf.filter(contextSpecifyingOwnPrivateAttr)).toEqual(userWithAllAttrsHidden); + }); + + it('context remains anonymous even when all attributes are hidden', () => { + const uf = ContextFilter({ allAttributesPrivate: true }); + expect(uf.filter(anonymousContext)).toEqual(contextWithAllAttrsHidden); + }); + + it('all attributes are redacted when anonymous', () => { + const uf = ContextFilter({}); + expect(uf.filter(anonymousContext, true)).toEqual(contextWithAllAttrsHidden); + }); + + it('converts non-boolean anonymous to boolean.', () => { + const uf = ContextFilter({}); + expect(uf.filter({ kind: 'user', key: 'user', anonymous: 'string' })).toEqual({ + kind: 'user', + key: 'user', + anonymous: true, + }); + + expect(uf.filter({ kind: 'user', key: 'user', anonymous: null })).toEqual({ + kind: 'user', + key: 'user', + anonymous: false, + }); + }); +}); + +describe('when handling mult-kind contexts', () => { + const contextWithBadContexts = { + kind: 'multi', + string: 'string', + null: null, + number: 0, + real: { + key: 'real', + }, + }; + + const contextWithBadContextsRemoved = { + kind: 'multi', + real: { + key: 'real', + }, + }; + + const orgAndUserContext = { + kind: 'multi', + organization: { + key: 'LD', + rocks: true, + name: 'name', + department: { + name: 'sdk', + }, + }, + user: { + key: 'abc', + name: 'alphabet', + anonymous: true, + letters: ['a', 'b', 'c'], + order: 3, + object: { + a: 'a', + b: 'b', + }, + _meta: { + privateAttributes: ['letters', '/object/b'], + }, + }, + }; + + const orgAndUserContextWithAnonymousRedaction = { + kind: 'multi', + organization: { + key: 'LD', + rocks: true, + name: 'name', + department: { + name: 'sdk', + }, + }, + user: { + key: 'abc', + anonymous: true, + _meta: { + redactedAttributes: ['/letters', '/name', '/object', '/order'], + }, + }, + }; + + const orgAndUserContextAllPrivate = { + kind: 'multi', + organization: { + key: 'LD', + _meta: { + redactedAttributes: ['/department', '/name', '/rocks'], + }, + }, + user: { + key: 'abc', + anonymous: true, + _meta: { + redactedAttributes: ['/letters', '/name', '/object', '/order'], + }, + }, + }; + + const orgAndUserGlobalNamePrivate = { + kind: 'multi', + organization: { + key: 'LD', + rocks: true, + department: { + name: 'sdk', + }, + _meta: { + redactedAttributes: ['/name'], + }, + }, + user: { + key: 'abc', + order: 3, + anonymous: true, + object: { + a: 'a', + }, + _meta: { + redactedAttributes: ['/letters', '/name', '/object/b'], + }, + }, + }; + + const orgAndUserContextIncludedPrivate = { + kind: 'multi', + organization: { + key: 'LD', + rocks: true, + name: 'name', + department: { + name: 'sdk', + }, + }, + user: { + key: 'abc', + name: 'alphabet', + anonymous: true, + order: 3, + object: { + a: 'a', + }, + _meta: { + redactedAttributes: ['/letters', '/object/b'], + }, + }, + }; + + it('it should not include invalid contexts', () => { + const uf = ContextFilter({}); + expect(uf.filter(contextWithBadContexts)).toEqual(contextWithBadContextsRemoved); + }); + + it('it should remove attributes from all contexts when all attributes are private.', () => { + const uf = ContextFilter({ allAttributesPrivate: true }); + expect(uf.filter(orgAndUserContext)).toEqual(orgAndUserContextAllPrivate); + }); + + it('it should remove attributes from all anonymous contexts', () => { + const uf = ContextFilter({}); + expect(uf.filter(orgAndUserContext, true)).toEqual(orgAndUserContextWithAnonymousRedaction); + }); + + it('it should apply private attributes from the context to the context.', () => { + const uf = ContextFilter({}); + expect(uf.filter(orgAndUserContext)).toEqual(orgAndUserContextIncludedPrivate); + }); + + it('it should apply global private attributes to all contexts.', () => { + const uf = ContextFilter({ privateAttributes: ['name'] }); + expect(uf.filter(orgAndUserContext)).toEqual(orgAndUserGlobalNamePrivate); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventProcessor-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventProcessor-test.js new file mode 100644 index 00000000..f1082e9b --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventProcessor-test.js @@ -0,0 +1,641 @@ +import EventProcessor from '../EventProcessor'; +import { DiagnosticsAccumulator } from '../diagnosticEvents'; +import * as messages from '../messages'; + +import * as stubPlatform from './stubPlatform'; +import { MockEventSender } from './testUtils'; + +// These tests verify that the event processor produces the expected event payload data for +// various inputs. The actual delivery of data is done by EventSender, which has its own +// tests; here, we use a mock EventSender. + +describe.each([ + [ + { key: 'userKey', name: 'Red' }, + { key: 'userKey', kind: 'user', _meta: { redactedAttributes: ['/name'] } }, + ], + [ + { kind: 'user', key: 'userKey', name: 'Red' }, + { key: 'userKey', kind: 'user', _meta: { redactedAttributes: ['/name'] } }, + ], + [ + { kind: 'multi', user: { key: 'userKey', name: 'Red' } }, + { kind: 'multi', user: { key: 'userKey', _meta: { redactedAttributes: ['/name'] } } }, + ], +])('EventProcessor', (context, filteredContext) => { + // const user = { key: 'userKey', name: 'Red' }; + const eventContext = { ...context, kind: context.kind || 'user' }; + // const filteredUser = { key: 'userKey', kind: 'user', _meta: { redactedAttributes: ['/name'] } }; + const eventsUrl = '/fake-url'; + const envId = 'env'; + const logger = stubPlatform.logger(); + const defaultConfig = { + eventsUrl: eventsUrl, + eventCapacity: 100, + flushInterval: 2000, + samplingInterval: 0, + logger: logger, + }; + const platform = stubPlatform.defaults(); + + async function withProcessorAndSender(config, asyncCallback) { + const sender = MockEventSender(); + const ep = EventProcessor(platform, config, envId, null, null, sender); + try { + return await asyncCallback(ep, sender); + } finally { + ep.stop(); + } + } + + async function withDiagnosticProcessorAndSender(config, asyncCallback) { + const sender = MockEventSender(); + const diagnosticAccumulator = DiagnosticsAccumulator(1000); + const ep = EventProcessor(platform, config, envId, diagnosticAccumulator, null, sender); + try { + return await asyncCallback(ep, sender, diagnosticAccumulator); + } finally { + ep.stop(); + } + } + + function checkFeatureEvent(e, source, debug, inlineUser) { + expect(e.kind).toEqual(debug ? 'debug' : 'feature'); + expect(e.creationDate).toEqual(source.creationDate); + expect(e.key).toEqual(source.key); + expect(e.version).toEqual(source.version); + expect(e.variation).toEqual(source.variation); + expect(e.value).toEqual(source.value); + expect(e.default).toEqual(source.default); + expect(e.reason).toEqual(source.reason); + expect(e.context).toEqual(inlineUser); + } + + function checkCustomEvent(e, source) { + expect(e.kind).toEqual('custom'); + expect(e.creationDate).toEqual(source.creationDate); + expect(e.key).toEqual(source.key); + expect(e.data).toEqual(source.data); + expect(e.metricValue).toEqual(source.metricValue); + expect(e.context).toEqual(source.context); + } + + function checkSummaryEvent(e) { + expect(e.kind).toEqual('summary'); + } + + it('should enqueue identify event', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + const event = { kind: 'identify', creationDate: 1000, context: eventContext }; + ep.enqueue(event); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + expect((await mockEventSender.calls.take()).events).toEqual([event]); + }); + }); + + it('filters user in identify event', async () => { + const config = { ...defaultConfig, allAttributesPrivate: true }; + await withProcessorAndSender(config, async (ep, mockEventSender) => { + const event = { kind: 'identify', creationDate: 1000, context: eventContext }; + ep.enqueue(event); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + expect((await mockEventSender.calls.take()).events).toEqual([ + { + kind: 'identify', + creationDate: event.creationDate, + + context: filteredContext, + }, + ]); + }); + }); + + it('queues individual feature event', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + const event = { + kind: 'feature', + creationDate: 1000, + key: 'flagkey', + context: eventContext, + trackEvents: true, + }; + ep.enqueue(event); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(2); + checkFeatureEvent(output[0], event, false, eventContext); + checkSummaryEvent(output[1]); + }); + }); + + it('can include reason in feature event', async () => { + const config = { ...defaultConfig }; + const reason = { kind: 'FALLTHROUGH' }; + await withProcessorAndSender(config, async (ep, mockEventSender) => { + const event = { + kind: 'feature', + creationDate: 1000, + key: 'flagkey', + context: eventContext, + trackEvents: true, + reason: reason, + }; + ep.enqueue(event); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(2); + checkFeatureEvent(output[0], event, false, eventContext); + checkSummaryEvent(output[1]); + }); + }); + + it('sets event kind to debug if event is temporarily in debug mode', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + const futureTime = new Date().getTime() + 1000000; + const e = { + kind: 'feature', + creationDate: 1000, + context: eventContext, + key: 'flagkey', + version: 11, + variation: 1, + value: 'value', + trackEvents: false, + debugEventsUntilDate: futureTime, + }; + ep.enqueue(e); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(2); + checkFeatureEvent(output[0], e, true, { ...context, kind: context.kind || 'user' }); + checkSummaryEvent(output[1]); + }); + }); + + it('filters user in debug event', async () => { + const config = { ...defaultConfig, allAttributesPrivate: true }; + await withProcessorAndSender(config, async (ep, mockEventSender) => { + const futureTime = new Date().getTime() + 1000000; + const e = { + kind: 'feature', + creationDate: 1000, + context: eventContext, + key: 'flagkey', + version: 11, + variation: 1, + value: 'value', + default: 'default', + trackEvents: false, + debugEventsUntilDate: futureTime, + }; + ep.enqueue(e); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(2); + checkFeatureEvent(output[0], e, true, filteredContext); + checkSummaryEvent(output[1]); + }); + }); + + it('filters context in feature event', async () => { + const config = { ...defaultConfig, allAttributesPrivate: true }; + await withProcessorAndSender(config, async (ep, mockEventSender) => { + const e = { + kind: 'feature', + creationDate: 1000, + context: eventContext, + key: 'flagkey', + version: 11, + variation: 1, + value: 'value', + default: 'default', + trackEvents: true, + }; + ep.enqueue(e); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(2); + checkFeatureEvent(output[0], e, false, filteredContext); + checkSummaryEvent(output[1]); + }); + }); + + it('can both track and debug an event', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + const futureTime = new Date().getTime() + 1000000; + const e = { + kind: 'feature', + creationDate: 1000, + context: eventContext, + key: 'flagkey', + version: 11, + variation: 1, + value: 'value', + trackEvents: true, + debugEventsUntilDate: futureTime, + }; + ep.enqueue(e); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(3); + checkFeatureEvent(output[0], e, false, { ...context, kind: context.kind || 'user' }); + checkFeatureEvent(output[1], e, true, { ...context, kind: context.kind || 'user' }); + checkSummaryEvent(output[2]); + }); + }); + + it('expires debug mode based on client time if client time is later than server time', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + // Pick a server time that is somewhat behind the client time + const serverTime = new Date().getTime() - 20000; + mockEventSender.setServerTime(serverTime); + + // Send and flush an event we don't care about, just to set the last server time + ep.enqueue({ kind: 'identify', context: { key: 'otherUser' } }); + await ep.flush(); + + // Now send an event with debug mode on, with a "debug until" time that is further in + // the future than the server time, but in the past compared to the client. + const debugUntil = serverTime + 1000; + const e = { + kind: 'feature', + creationDate: 1000, + context: eventContext, + key: 'flagkey', + version: 11, + variation: 1, + value: 'value', + trackEvents: false, + debugEventsUntilDate: debugUntil, + }; + ep.enqueue(e); + + // Should get a summary event only, not a full feature event + await ep.flush(); + expect(mockEventSender.calls.length()).toEqual(2); + await mockEventSender.calls.take(); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(1); + checkSummaryEvent(output[0]); + }); + }); + + it('expires debug mode based on server time if server time is later than client time', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + // Pick a server time that is somewhat ahead of the client time + const serverTime = new Date().getTime() + 20000; + mockEventSender.setServerTime(serverTime); + + // Send and flush an event we don't care about, just to set the last server time + ep.enqueue({ kind: 'identify', context: { key: 'otherUser' } }); + await ep.flush(); + + // Now send an event with debug mode on, with a "debug until" time that is further in + // the future than the client time, but in the past compared to the server. + const debugUntil = serverTime - 1000; + const e = { + kind: 'feature', + creationDate: 1000, + context: eventContext, + key: 'flagkey', + version: 11, + variation: 1, + value: 'value', + trackEvents: false, + debugEventsUntilDate: debugUntil, + }; + ep.enqueue(e); + + // Should get a summary event only, not a full feature event + await ep.flush(); + expect(mockEventSender.calls.length()).toEqual(2); + await mockEventSender.calls.take(); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(1); + checkSummaryEvent(output[0]); + }); + }); + + it('summarizes nontracked events', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + function makeEvent(key, date, version, variation, value, defaultVal) { + return { + kind: 'feature', + creationDate: date, + context: eventContext, + key: key, + version: version, + variation: variation, + value: value, + default: defaultVal, + trackEvents: false, + }; + } + const e1 = makeEvent('flagkey1', 1000, 11, 1, 'value1', 'default1'); + const e2 = makeEvent('flagkey2', 2000, 22, 1, 'value2', 'default2'); + ep.enqueue(e1); + ep.enqueue(e2); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(1); + const se = output[0]; + checkSummaryEvent(se); + expect(se.startDate).toEqual(1000); + expect(se.endDate).toEqual(2000); + expect(se.features).toEqual({ + flagkey1: { + contextKinds: ['user'], + default: 'default1', + counters: [{ version: 11, variation: 1, value: 'value1', count: 1 }], + }, + flagkey2: { + contextKinds: ['user'], + default: 'default2', + counters: [{ version: 22, variation: 1, value: 'value2', count: 1 }], + }, + }); + }); + }); + + it('queues custom event', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + const e = { + kind: 'custom', + creationDate: 1000, + context: eventContext, + key: 'eventkey', + data: { thing: 'stuff' }, + metricValue: 1.5, + }; + ep.enqueue(e); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(1); + checkCustomEvent(output[0], e); + }); + }); + + it('filters context in custom event', async () => { + const config = { ...defaultConfig, allAttributesPrivate: true }; + await withProcessorAndSender(config, async (ep, mockEventSender) => { + const e = { + kind: 'custom', + creationDate: 1000, + context: eventContext, + key: 'eventkey', + data: { thing: 'stuff' }, + metricValue: 1.5, + }; + ep.enqueue(e); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(1); + checkCustomEvent(output[0], { ...e, context: filteredContext }); + }); + }); + + it('enforces event capacity', async () => { + const config = { ...defaultConfig, eventCapacity: 1, logger: stubPlatform.logger() }; + const e0 = { kind: 'custom', creationDate: 1000, context: eventContext, key: 'key0' }; + const e1 = { kind: 'custom', creationDate: 1001, context: eventContext, key: 'key1' }; + const e2 = { kind: 'custom', creationDate: 1002, context: eventContext, key: 'key2' }; + await withProcessorAndSender(config, async (ep, mockEventSender) => { + ep.enqueue(e0); + ep.enqueue(e1); + ep.enqueue(e2); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(1); + checkCustomEvent(output[0], e0); + + expect(config.logger.output.warn).toEqual([messages.eventCapacityExceeded()]); // warning is not repeated for e2 + }); + }); + + it('sends nothing if there are no events to flush', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + await ep.flush(); + expect(mockEventSender.calls.length()).toEqual(0); + }); + }); + + async function verifyUnrecoverableHttpError(status) { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + const e = { kind: 'identify', creationDate: 1000, context: eventContext }; + ep.enqueue(e); + mockEventSender.setStatus(status); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + ep.enqueue(e); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); // still the one from our first flush + }); + } + + async function verifyRecoverableHttpError(status) { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + const e = { kind: 'identify', creationDate: 1000, context: eventContext }; + ep.enqueue(e); + mockEventSender.setStatus(status); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + ep.enqueue(e); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(2); + }); + } + + describe('stops sending events after unrecoverable HTTP error', () => { + [401, 403, 404].forEach(status => { + it('status ' + status, async () => await verifyUnrecoverableHttpError(status)); + }); + }); + + describe('continues sending events after recoverable HTTP error', () => { + [408, 429, 500].forEach(status => { + it('status ' + status, async () => await verifyRecoverableHttpError(status)); + }); + }); + + it('generates separate summary events for different contexts', async () => { + await withProcessorAndSender(defaultConfig, async (ep, mockEventSender) => { + const context1 = { key: 'user1', kind: 'user' }; + const context2 = { key: 'user2', kind: 'user' }; + + // Create feature events for two different contexts + const event1 = { + kind: 'feature', + creationDate: 1000, + context: context1, + key: 'flag1', + version: 11, + variation: 1, + value: 'value1', + default: 'default1', + trackEvents: false, + }; + + const event2 = { + kind: 'feature', + creationDate: 1000, + context: context2, + key: 'flag2', + version: 22, + variation: 2, + value: 'value2', + default: 'default2', + trackEvents: false, + }; + + ep.enqueue(event1); + ep.enqueue(event2); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + + // Should have two summary events, one for each context + expect(output.length).toEqual(2); + + // Find the summary event for each context + const summary1 = output.find(e => e.context.key === 'user1'); + const summary2 = output.find(e => e.context.key === 'user2'); + + // Verify each summary event has the correct context and flag data + expect(summary1).toBeDefined(); + expect(summary1.context).toEqual(context1); + expect(summary1.features).toEqual({ + flag1: { + contextKinds: ['user'], + default: 'default1', + counters: [{ version: 11, variation: 1, value: 'value1', count: 1 }], + }, + }); + + expect(summary2).toBeDefined(); + expect(summary2.context).toEqual(context2); + expect(summary2.features).toEqual({ + flag2: { + contextKinds: ['user'], + default: 'default2', + counters: [{ version: 22, variation: 2, value: 'value2', count: 1 }], + }, + }); + }); + }); + + describe('interaction with diagnostic events', () => { + it('sets eventsInLastBatch on flush', async () => { + const e0 = { kind: 'custom', creationDate: 1000, context: eventContext, key: 'key0' }; + const e1 = { kind: 'custom', creationDate: 1001, context: eventContext, key: 'key1' }; + await withDiagnosticProcessorAndSender(defaultConfig, async (ep, mockEventSender, diagnosticAccumulator) => { + expect(diagnosticAccumulator.getProps().eventsInLastBatch).toEqual(0); + + ep.enqueue(e0); + ep.enqueue(e1); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(2); + + expect(diagnosticAccumulator.getProps().eventsInLastBatch).toEqual(2); + }); + }); + + it('increments droppedEvents when capacity is exceeded', async () => { + const config = { ...defaultConfig, eventCapacity: 1, logger: stubPlatform.logger() }; + const e0 = { kind: 'custom', creationDate: 1000, context: eventContext, key: 'key0' }; + const e1 = { kind: 'custom', creationDate: 1001, context: eventContext, key: 'key1' }; + const e2 = { kind: 'custom', creationDate: 1002, context: eventContext, key: 'key2' }; + await withDiagnosticProcessorAndSender(config, async (ep, mockEventSender, diagnosticAccumulator) => { + ep.enqueue(e0); + ep.enqueue(e1); + ep.enqueue(e2); + await ep.flush(); + + expect(mockEventSender.calls.length()).toEqual(1); + const output = (await mockEventSender.calls.take()).events; + expect(output.length).toEqual(1); + checkCustomEvent(output[0], e0); + + expect(config.logger.output.warn).toEqual([messages.eventCapacityExceeded()]); // warning is not repeated for e2 + + expect(diagnosticAccumulator.getProps().droppedEvents).toEqual(2); + }); + }); + + it('filters context in summary events', async () => { + const event = { + kind: 'feature', + creationDate: 1000, + context: eventContext, + key: 'flagkey', + version: 11, + variation: 1, + value: 'value', + default: 'default', + trackEvents: true, + }; + + // Configure with allAttributesPrivate set to true + const config = { ...defaultConfig, allAttributesPrivate: true }; + + const sender = MockEventSender(); + const ep = EventProcessor(platform, config, envId, null, null, sender); + try { + ep.enqueue(event); + await ep.flush(); + + expect(sender.calls.length()).toEqual(1); + const output = (await sender.calls.take()).events; + expect(output.length).toEqual(2); + + // Verify the feature event has filtered context + checkFeatureEvent(output[0], event, false, filteredContext); + + // Verify the summary event has filtered context + const summaryEvent = output[1]; + checkSummaryEvent(summaryEvent); + expect(summaryEvent.context).toEqual(filteredContext); + expect(summaryEvent.features).toEqual({ + flagkey: { + contextKinds: ['user'], + default: 'default', + counters: [{ version: 11, variation: 1, value: 'value', count: 1 }], + }, + }); + } finally { + ep.stop(); + } + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventSender-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventSender-test.js new file mode 100644 index 00000000..cb3d43ea --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventSender-test.js @@ -0,0 +1,196 @@ +import EventSender from '../EventSender'; +import * as utils from '../utils'; + +import { respond, networkError } from './mockHttp'; +import * as stubPlatform from './stubPlatform'; + +// These tests verify that EventSender executes the expected HTTP requests to deliver events. Since +// the js-sdk-common package uses an abstraction of HTTP requests, these tests do not use HTTP but +// rather use a test implementation of our HTTP abstraction; the individual platform-specific SDKs +// are responsible for verifying that their own implementations of the same HTTP abstraction work +// correctly with real networking. + +describe('EventSender', () => { + let platform; + const envId = 'env'; + + beforeEach(() => { + platform = stubPlatform.defaults(); + }); + + describe('using POST when CORS is available', () => { + it('should send all events in request body', async () => { + const server = platform.testing.http.newServer(); + server.byDefault(respond(202)); + const sender = EventSender(platform, envId); + const events = []; + for (let i = 0; i < 80; i++) { + events.push({ kind: 'identify', key: 'thisIsALongUserKey' + i }); + } + await sender.sendEvents(events, server.url + '/endpoint'); + + const r = await server.nextRequest(); + expect(r.path).toEqual('/endpoint'); + expect(r.method).toEqual('post'); + expect(JSON.parse(r.body)).toEqual(events); + }); + + it('should send custom user-agent header', async () => { + const options = { sendLDHeaders: true }; + const server = platform.testing.http.newServer(); + server.byDefault(respond(202)); + const sender = EventSender(platform, envId, options); + const event = { kind: 'identify', key: 'userKey' }; + await sender.sendEvents([event], server.url); + + const r = await server.nextRequest(); + expect(r.headers['user-agent']).toEqual(utils.getLDUserAgentString(platform)); + expect(r.headers['x-launchdarkly-wrapper']).toBeUndefined(); + }); + + it('should send unique payload IDs', async () => { + const options = { sendLDHeaders: true }; + const server = platform.testing.http.newServer(); + server.byDefault(respond(202)); + const sender = EventSender(platform, envId, options); + const event = { kind: 'identify', key: 'userKey' }; + await sender.sendEvents([event], server.url, false); + await sender.sendEvents([event], server.url, false); // deliberately repeated + + const r0 = await server.nextRequest(); + const r1 = await server.nextRequest(); + const id0 = r0.headers['x-launchdarkly-payload-id']; + const id1 = r1.headers['x-launchdarkly-payload-id']; + expect(id0).toBeTruthy(); + expect(id1).toBeTruthy(); + expect(id0).not.toEqual(id1); + }); + + it('should send wrapper info if present', async () => { + const options = { sendLDHeaders: true, wrapperName: 'FakeSDK' }; + const server = platform.testing.http.newServer(); + server.byDefault(respond(202)); + const sender = EventSender(platform, envId, options); + const event = { kind: 'identify', key: 'userKey' }; + await sender.sendEvents([event], server.url); + + const r = await server.nextRequest(); + expect(r.headers['user-agent']).toEqual(utils.getLDUserAgentString(platform)); + expect(r.headers['x-launchdarkly-wrapper']).toEqual('FakeSDK'); + }); + + it('should send transformed headers if requestHeaderTransform function is provided', async () => { + const headerTransform = input => { + const output = { ...input }; + output['c'] = '30'; + return output; + }; + const options = { requestHeaderTransform: headerTransform }; + const server = platform.testing.http.newServer(); + server.byDefault(respond(202)); + const sender = EventSender(platform, envId, options); + const event = { kind: 'identify', key: 'userKey' }; + await sender.sendEvents([event], server.url); + + const r = await server.nextRequest(); + expect(r.headers['c']).toEqual('30'); + }); + + describe('retry on recoverable HTTP error', () => { + const retryableStatuses = [400, 408, 429, 500, 503]; + for (const i in retryableStatuses) { + const status = retryableStatuses[i]; + it('status ' + status, async () => { + const server = platform.testing.http.newServer(); + let n = 0; + server.byDefault((req, res) => { + n++; + respond(n >= 2 ? 200 : status)(req, res); + }); + const sender = EventSender(platform, envId); + const event = { kind: 'false', key: 'userKey' }; + await sender.sendEvents([event], server.url, false); + + expect(server.requests.length()).toEqual(2); + const r0 = await server.nextRequest(); + const r1 = await server.nextRequest(); + expect(JSON.parse(r0.body)).toEqual([event]); + expect(JSON.parse(r1.body)).toEqual([event]); + const id0 = r0.headers['x-launchdarkly-payload-id']; + expect(id0).toBeTruthy(); + expect(r1.headers['x-launchdarkly-payload-id']).toEqual(id0); + }); + } + }); + + it('should not retry more than once', async () => { + const server = platform.testing.http.newServer(); + let n = 0; + server.byDefault((req, res) => { + n++; + respond(n >= 3 ? 200 : 503)(req, res); + }); + const sender = EventSender(platform, envId); + const event = { kind: 'false', key: 'userKey' }; + await sender.sendEvents([event], server.url); + + expect(server.requests.length()).toEqual(2); + }); + + it('should not retry on error 401', async () => { + const server = platform.testing.http.newServer(); + server.byDefault(respond(401)); + const sender = EventSender(platform, envId); + const event = { kind: 'false', key: 'userKey' }; + await sender.sendEvents([event], server.url); + + expect(server.requests.length()).toEqual(1); + }); + + it('should retry on I/O error', async () => { + const server = platform.testing.http.newServer(); + let n = 0; + server.byDefault((req, res) => { + n++; + if (n >= 2) { + respond(200)(req, res); + } else { + networkError()(req, res); + } + }); + const sender = EventSender(platform, envId); + const event = { kind: 'false', key: 'userKey' }; + await sender.sendEvents([event], server.url); + + expect(server.requests.length()).toEqual(2); + await server.nextRequest(); + const r1 = await server.nextRequest(); + expect(JSON.parse(r1.body)).toEqual([event]); + }); + }); + + describe('verify sendEvents response format', () => { + it('includes date header', async () => { + const options = { sendLDHeaders: true }; + const server = platform.testing.http.newServer(); + server.byDefault(respond(202, { date: 'Wed, 21 Oct 2015 07:28:00 GMT' }, '{}')); + + const sender = EventSender(platform, envId, options); + const event = { kind: 'identify', key: 'userKey' }; + const responseInfo = await sender.sendEvents([event], server.url); + + expect(responseInfo.serverTime).toEqual(1445412480000); + }); + }); + + describe('When HTTP requests are not available at all', () => { + it('should silently discard events', async () => { + const server = platform.testing.http.newServer(); + const sender = EventSender(stubPlatform.withoutHttp(), server.url, envId); + const event = { kind: 'false', key: 'userKey' }; + await sender.sendEvents([event], server.url); + + expect(server.requests.length()).toEqual(0); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventSource-mock.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventSource-mock.js new file mode 100644 index 00000000..b50a4e50 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventSource-mock.js @@ -0,0 +1,61 @@ +import EventEmitter from 'events'; + +export default function EventSource(url) { + this.__emitter = new EventEmitter(); + + this.onerror = undefined; + this.onopen = undefined; + this.onmessage = undefined; + this.readyState = EventSource.CONNECTING; + + this.addEventListener = addEventListener; + this.removeEventListener = removeEventListener; + this.close = close; + + this.mockUrl = url; + this.mockEmit = mockEmit; + this.mockError = mockError; + this.mockOpen = mockOpen; + this.mockMessage = mockMessage; + + function addEventListener(eventName, callback) { + this.__emitter.on(eventName, callback); + } + + function removeEventListener(eventName, callback) { + this.__emitter.off(eventName, callback); + } + + function close() { + this.readyState = EventSource.CLOSED; + } + + function mockEmit(eventName, param) { + if (this.readyState !== EventSource.CLOSED) { + this.__emitter.emit(eventName, param); + } + } + + function mockError(error) { + if (this.readyState !== EventSource.CLOSED) { + this.onerror && this.onerror(error); + } + } + + function mockOpen(error) { + if (this.readyState === EventSource.CONNECTING) { + this.readyState = EventSource.OPEN; + this.onopen && this.onopen(error); + } + } + + function mockMessage(message) { + if (this.readyState === EventSource.OPEN) { + this.onmessage && this.onmessage(message); + } + } +} + +EventSource.CONNECTING = 0; +EventSource.OPEN = 1; +EventSource.CLOSED = 2; diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventSummarizer-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventSummarizer-test.js new file mode 100644 index 00000000..87099c6d --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/EventSummarizer-test.js @@ -0,0 +1,157 @@ +import EventSummarizer from '../EventSummarizer'; + +// These tests cover only the logic for counting feature requests in summary data. + +describe('EventSummarizer', () => { + const user = { key: 'key1' }; + + it('does nothing for identify event', () => { + const es = EventSummarizer(); + const snapshot = es.getSummary(); + es.summarizeEvent({ kind: 'identify', creationDate: 1000, user: user }); + expect(es.getSummary()).toEqual(snapshot); + }); + + it('does nothing for custom event', () => { + const es = EventSummarizer(); + const snapshot = es.getSummary(); + es.summarizeEvent({ kind: 'custom', creationDate: 1000, key: 'eventkey', user: user }); + expect(es.getSummary()).toEqual(snapshot); + }); + + it('sets start and end dates for feature events', () => { + const es = EventSummarizer(); + const event1 = { kind: 'feature', creationDate: 2000, key: 'key', user: user }; + const event2 = { kind: 'feature', creationDate: 1000, key: 'key', user: user }; + const event3 = { kind: 'feature', creationDate: 1500, key: 'key', user: user }; + es.summarizeEvent(event1); + es.summarizeEvent(event2); + es.summarizeEvent(event3); + const data = es.getSummary(); + + expect(data.startDate).toEqual(1000); + expect(data.endDate).toEqual(2000); + }); + + function makeEvent(key, version, variation, value, defaultVal) { + return { + kind: 'feature', + creationDate: 1000, + key: key, + version: version, + context: user, + variation: variation, + value: value, + default: defaultVal, + }; + } + + it('increments counters for feature events', () => { + const es = EventSummarizer(); + const event1 = makeEvent('key1', 11, 1, 100, 111); + const event2 = makeEvent('key1', 11, 2, 200, 111); + const event3 = makeEvent('key2', 22, 1, 999, 222); + const event4 = makeEvent('key1', 11, 1, 100, 111); + const event5 = makeEvent('badkey', null, null, 333, 333); + es.summarizeEvent(event1); + es.summarizeEvent(event2); + es.summarizeEvent(event3); + es.summarizeEvent(event4); + es.summarizeEvent(event5); + const data = es.getSummary(); + + data.features.key1.counters.sort((a, b) => a.value - b.value); + const expectedFeatures = { + key1: { + contextKinds: ['user'], + default: 111, + counters: [ + { value: 100, variation: 1, version: 11, count: 2 }, + { value: 200, variation: 2, version: 11, count: 1 }, + ], + }, + key2: { + contextKinds: ['user'], + default: 222, + counters: [{ value: 999, variation: 1, version: 22, count: 1 }], + }, + badkey: { + contextKinds: ['user'], + default: 333, + counters: [{ value: 333, unknown: true, count: 1 }], + }, + }; + expect(data.features).toEqual(expectedFeatures); + }); + + it('distinguishes between zero and null/undefined in feature variation', () => { + const es = EventSummarizer(); + const event1 = makeEvent('key1', 11, 0, 100, 111); + const event2 = makeEvent('key1', 11, null, 111, 111); + const event3 = makeEvent('key1', 11, undefined, 111, 111); + es.summarizeEvent(event1); + es.summarizeEvent(event2); + es.summarizeEvent(event3); + const data = es.getSummary(); + + data.features.key1.counters.sort((a, b) => a.value - b.value); + const expectedFeatures = { + key1: { + contextKinds: ['user'], + default: 111, + counters: [ + { variation: 0, value: 100, version: 11, count: 1 }, + { value: 111, version: 11, count: 2 }, + ], + }, + }; + expect(data.features).toEqual(expectedFeatures); + }); + + it('includes keys from all kinds', () => { + const es = EventSummarizer(); + const event1 = { + kind: 'feature', + creationDate: 1000, + key: 'key1', + version: 11, + context: { key: 'test' }, + variation: 1, + value: 100, + default: 111, + }; + const event2 = { + kind: 'feature', + creationDate: 1000, + key: 'key1', + version: 11, + context: { kind: 'org', key: 'test' }, + variation: 1, + value: 100, + default: 111, + }; + const event3 = { + kind: 'feature', + creationDate: 1000, + key: 'key1', + version: 11, + context: { kind: 'multi', bacon: { key: 'crispy' }, eggs: { key: 'scrambled' } }, + variation: 1, + value: 100, + default: 111, + }; + es.summarizeEvent(event1); + es.summarizeEvent(event2); + es.summarizeEvent(event3); + const data = es.getSummary(); + + const expectedFeatures = { + key1: { + default: 111, + counters: [{ variation: 1, value: 100, version: 11, count: 3 }], + contextKinds: ['user', 'org', 'bacon', 'eggs'], + }, + }; + expect(data.features).toEqual(expectedFeatures); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/HookRunner-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/HookRunner-test.js new file mode 100644 index 00000000..b68d06d2 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/HookRunner-test.js @@ -0,0 +1,449 @@ +// The HookRunner factory function under test +const createHookRunner = require('../HookRunner'); + +// Mock the logger functions we expect to be called +const mockLogger = () => ({ + error: jest.fn(), + warn: jest.fn(), + info: jest.fn(), + debug: jest.fn(), +}); + +// Define a basic Hook structure for tests +const createTestHook = (name = 'Test Hook') => ({ + getMetadata: jest.fn().mockReturnValue({ name }), + beforeEvaluation: jest.fn(), + afterEvaluation: jest.fn(), + beforeIdentify: jest.fn(), + afterIdentify: jest.fn(), + afterTrack: jest.fn(), +}); + +describe('Given a logger, runner, and hook', () => { + let logger; + let testHook; + let hookRunner; + + beforeEach(() => { + // Reset mocks and create fresh instances for each test + logger = mockLogger(); + testHook = createTestHook(); + // Initialize the runner with the test hook + hookRunner = createHookRunner(logger, [testHook]); + }); + + it('evaluation: should execute hooks and return the evaluation result', () => { + const key = 'test-flag'; + const context = { kind: 'user', key: 'user-123' }; + const defaultValue = false; + const evaluationResult = { + value: true, + variationIndex: 1, + reason: { kind: 'OFF' }, + }; + // Mock the core evaluation method + const method = jest.fn().mockReturnValue(evaluationResult); + + // The data expected to be passed between stages initially is empty + const initialData = {}; + + const result = hookRunner.withEvaluation(key, context, defaultValue, method); + + // Check if beforeEvaluation was called correctly + expect(testHook.beforeEvaluation).toHaveBeenCalledWith( + expect.objectContaining({ + flagKey: key, + context, + defaultValue, + }), + initialData // Initial data passed to beforeEvaluation + ); + + // Check if the original evaluation method was called + expect(method).toHaveBeenCalled(); + + // Check if afterEvaluation was called correctly + expect(testHook.afterEvaluation).toHaveBeenCalledWith( + expect.objectContaining({ + flagKey: key, + context, + defaultValue, + }), + initialData, // Data returned from (mocked) beforeEvaluation + evaluationResult + ); + + // Verify the final result matches the evaluation result + expect(result).toEqual(evaluationResult); + }); + + it('evaluation: should handle errors in beforeEvaluation hook', () => { + const errorHook = createTestHook('Error Hook'); + const testError = new Error('Hook error in before'); + errorHook.beforeEvaluation.mockImplementation(() => { + throw testError; + }); + + const errorHookRunner = createHookRunner(logger, [errorHook]); + const method = jest.fn().mockReturnValue({ value: 'default', reason: { kind: 'ERROR' } }); + const initialData = {}; // Data returned by the failing hook (default) + + errorHookRunner.withEvaluation('test-flag', { kind: 'user', key: 'user-123' }, false, method); + + // Error should be logged + expect(logger.error).toHaveBeenCalledWith( + 'An error was encountered in "beforeEvaluation" of the "Error Hook" hook: Error: Hook error in before' + ); + // Method should still be called + expect(method).toHaveBeenCalled(); + // After evaluation should still be called, passing the default data ({}) because before failed + expect(errorHook.afterEvaluation).toHaveBeenCalledWith(expect.anything(), initialData, expect.anything()); + }); + + it('evaluation: should handle errors in afterEvaluation hook', () => { + const errorHook = createTestHook('Error Hook'); + const testError = new Error('Hook error in after'); + errorHook.afterEvaluation.mockImplementation(() => { + throw testError; + }); + + const errorHookRunner = createHookRunner(logger, [errorHook]); + const method = jest.fn().mockReturnValue({ value: 'default', reason: { kind: 'FALLTHROUGH' } }); + + errorHookRunner.withEvaluation('test-flag', { kind: 'user', key: 'user-123' }, false, method); + + // Before evaluation should be called normally + expect(errorHook.beforeEvaluation).toHaveBeenCalled(); + // Method should be called normally + expect(method).toHaveBeenCalled(); + // Error should be logged for afterEvaluation + expect(logger.error).toHaveBeenCalledWith( + 'An error was encountered in "afterEvaluation" of the "Error Hook" hook: Error: Hook error in after' + ); + }); + + it('evaluation: should skip hook execution if no hooks are provided', () => { + const emptyHookRunner = createHookRunner(logger, []); // No initial hooks + const method = jest.fn().mockReturnValue({ value: true }); + + emptyHookRunner.withEvaluation('test-flag', { kind: 'user', key: 'user-123' }, false, method); + + // Only the method should be called + expect(method).toHaveBeenCalled(); + expect(logger.error).not.toHaveBeenCalled(); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it('evaluation: should pass data from beforeEvaluation to afterEvaluation', () => { + const key = 'test-flag'; + const context = { kind: 'user', key: 'user-123' }; + const defaultValue = false; + const evaluationResult = { value: true }; + const seriesData = { testData: 'before data' }; + + // Mock beforeEvaluation to return specific data + testHook.beforeEvaluation.mockReturnValue(seriesData); + const method = jest.fn().mockReturnValue(evaluationResult); + + hookRunner.withEvaluation(key, context, defaultValue, method); + + expect(testHook.beforeEvaluation).toHaveBeenCalled(); + // afterEvaluation should receive the data returned by beforeEvaluation + expect(testHook.afterEvaluation).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining(seriesData), // Check if the passed data includes seriesData + evaluationResult + ); + }); + + it('identify: should execute identify hooks', () => { + const context = { kind: 'user', key: 'user-123' }; + const timeout = 10; + const identifyResult = { status: 'completed' }; // Example result structure + const initialData = {}; + + // Call identify to get the callback + const identifyCallback = hookRunner.identify(context, timeout); + + // Check if beforeIdentify was called immediately + expect(testHook.beforeIdentify).toHaveBeenCalledWith( + expect.objectContaining({ + context, + timeout, + }), + initialData // Initial data passed to beforeIdentify + ); + + // Now invoke the callback returned by identify + identifyCallback(identifyResult); + + // Check if afterIdentify was called with the correct arguments + expect(testHook.afterIdentify).toHaveBeenCalledWith( + expect.objectContaining({ + context, + timeout, + }), + initialData, // Data returned from (mocked) beforeIdentify + identifyResult + ); + }); + + it('identify: should handle errors in beforeIdentify hook', () => { + const errorHook = createTestHook('Error Hook'); + const testError = new Error('Hook error in before identify'); + errorHook.beforeIdentify.mockImplementation(() => { + throw testError; + }); + + const errorHookRunner = createHookRunner(logger, [errorHook]); + const identifyCallback = errorHookRunner.identify({ kind: 'user', key: 'user-456' }, 1000); + + // Error should be logged immediately from beforeIdentify + expect(logger.error).toHaveBeenCalledWith( + 'An error was encountered in "beforeIdentify" of the "Error Hook" hook: Error: Hook error in before identify' + ); + + // Execute the callback - afterIdentify should still be called + identifyCallback({ status: 'error' }); // Example result + + // Check afterIdentify was called, receiving default data {} + expect(errorHook.afterIdentify).toHaveBeenCalledWith(expect.anything(), {}, expect.anything()); + }); + + it('identify: should handle errors in afterIdentify hook', () => { + const errorHook = createTestHook('Error Hook'); + const testError = new Error('Hook error in after identify'); + errorHook.afterIdentify.mockImplementation(() => { + throw testError; + }); + + const errorHookRunner = createHookRunner(logger, [errorHook]); + const identifyCallback = errorHookRunner.identify({ kind: 'user', key: 'user-456' }, 1000); + + // Before should run fine + expect(errorHook.beforeIdentify).toHaveBeenCalled(); + expect(logger.error).not.toHaveBeenCalled(); + + // Execute the callback - this should trigger the error in afterIdentify + identifyCallback({ status: 'completed' }); // Example result + + // Error should be logged from afterIdentify + expect(logger.error).toHaveBeenCalledWith( + 'An error was encountered in "afterIdentify" of the "Error Hook" hook: Error: Hook error in after identify' + ); + }); + + it('identify: should pass data from beforeIdentify to afterIdentify', () => { + const context = { kind: 'user', key: 'user-789' }; + const timeout = 50; + const identifyResult = { status: 'completed' }; + const seriesData = { testData: 'before identify data' }; + + // Mock beforeIdentify to return specific data + testHook.beforeIdentify.mockReturnValue(seriesData); + + const identifyCallback = hookRunner.identify(context, timeout); + identifyCallback(identifyResult); + + expect(testHook.beforeIdentify).toHaveBeenCalled(); + // afterIdentify should receive the data returned by beforeIdentify + expect(testHook.afterIdentify).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining(seriesData), // Check if the passed data includes seriesData + identifyResult + ); + }); + + it('addHook: should use the added hook in future invocations', () => { + const newHook = createTestHook('New Hook'); + hookRunner.addHook(newHook); + + const method = jest.fn().mockReturnValue({ value: true }); + hookRunner.withEvaluation('test-flag', { kind: 'user', key: 'user-123' }, false, method); + + // Both the original and the new hook should have been called + expect(testHook.beforeEvaluation).toHaveBeenCalled(); + expect(testHook.afterEvaluation).toHaveBeenCalled(); + expect(newHook.beforeEvaluation).toHaveBeenCalled(); + expect(newHook.afterEvaluation).toHaveBeenCalled(); + }); + + it('error handling: should log "unknown hook" when getMetadata throws', () => { + const errorMetadataHook = { + getMetadata: jest.fn().mockImplementation(() => { + throw new Error('Metadata error'); + }), + beforeEvaluation: jest.fn().mockImplementation(() => { + throw new Error('Eval error'); // Add an error here to trigger logging + }), + afterEvaluation: jest.fn(), + // Add other methods if needed for completeness, mocked simply + beforeIdentify: jest.fn(), + afterIdentify: jest.fn(), + }; + + const errorRunner = createHookRunner(logger, [errorMetadataHook]); + errorRunner.withEvaluation('flag', {}, false, () => ({ value: null })); + + // First error: getting metadata + expect(logger.error).toHaveBeenCalledWith('Exception thrown getting metadata for hook. Unable to get hook name.'); + // Second error: executing the stage with 'unknown hook' name + expect(logger.error).toHaveBeenCalledWith( + 'An error was encountered in "beforeEvaluation" of the "unknown hook" hook: Error: Eval error' + ); + }); + + it('error handling: should log "unknown hook" when getMetadata returns empty name', () => { + const emptyNameHook = createTestHook(''); // Create hook with empty name + emptyNameHook.beforeEvaluation.mockImplementation(() => { + throw new Error('Eval error'); // Add an error here to trigger logging + }); + + const errorRunner = createHookRunner(logger, [emptyNameHook]); + errorRunner.withEvaluation('flag', {}, false, () => ({ value: null })); + + // Verify getMetadata was called (even though name is empty) + expect(emptyNameHook.getMetadata).toHaveBeenCalled(); + + // Verify the error uses 'unknown hook' + expect(logger.error).toHaveBeenCalledWith( + 'An error was encountered in "beforeEvaluation" of the "unknown hook" hook: Error: Eval error' + ); + }); + + it('error handling: should log the correct hook name when an error occurs', () => { + const hookName = 'Specific Error Hook'; + const errorHook = createTestHook(hookName); + const testError = new Error('Specific test error'); + errorHook.beforeEvaluation.mockImplementation(() => { + throw testError; + }); + + const specificRunner = createHookRunner(logger, [errorHook]); + specificRunner.withEvaluation('flag', {}, false, () => ({ value: null })); + + // Verify getMetadata was called + expect(errorHook.getMetadata).toHaveBeenCalled(); + // Verify the error message includes the correct hook name + expect(logger.error).toHaveBeenCalledWith( + `An error was encountered in "beforeEvaluation" of the "${hookName}" hook: Error: Specific test error` + ); + }); + + it('should execute afterTrack hooks', () => { + const context = { kind: 'user', key: 'user-123' }; + const key = 'test'; + const data = { test: 'data' }; + const metricValue = 42; + + const trackContext = { + key, + context, + data, + metricValue, + }; + + hookRunner.afterTrack(trackContext); + + expect(testHook.afterTrack).toHaveBeenCalledWith(trackContext); + }); + + it('should handle errors in afterTrack hooks', () => { + const errorHook = { + getMetadata: jest.fn().mockReturnValue({ name: 'Error Hook' }), + afterTrack: jest.fn().mockImplementation(() => { + throw new Error('Hook error'); + }), + }; + + const errorHookRunner = createHookRunner(logger, [errorHook]); + + errorHookRunner.afterTrack({ + key: 'test', + context: { kind: 'user', key: 'user-123' }, + }); + + expect(logger.error).toHaveBeenCalledWith( + expect.stringContaining('An error was encountered in "afterTrack" of the "Error Hook" hook: Error: Hook error') + ); + }); + + it('should skip afterTrack execution if there are no hooks', () => { + const emptyHookRunner = createHookRunner(logger, []); + + emptyHookRunner.afterTrack({ + key: 'test', + context: { kind: 'user', key: 'user-123' }, + }); + + expect(logger.error).not.toHaveBeenCalled(); + }); + + it('executes hook stages in the specified order', () => { + const beforeEvalOrder = []; + const afterEvalOrder = []; + const beforeIdentifyOrder = []; + const afterIdentifyOrder = []; + const afterTrackOrder = []; + + const createMockHook = id => ({ + getMetadata: jest.fn().mockReturnValue({ name: `Hook ${id}` }), + beforeEvaluation: jest.fn().mockImplementation((_context, data) => { + beforeEvalOrder.push(id); + return data; + }), + afterEvaluation: jest.fn().mockImplementation((_context, data) => { + afterEvalOrder.push(id); + return data; + }), + beforeIdentify: jest.fn().mockImplementation((_context, data) => { + beforeIdentifyOrder.push(id); + return data; + }), + afterIdentify: jest.fn().mockImplementation((_context, data) => { + afterIdentifyOrder.push(id); + return data; + }), + afterTrack: jest.fn().mockImplementation(() => { + afterTrackOrder.push(id); + }), + }); + + const hookA = createMockHook('a'); + const hookB = createMockHook('b'); + const hookC = createMockHook('c'); + + const runner = createHookRunner(logger, [hookA, hookB]); + runner.addHook(hookC); + + // Test evaluation order + runner.withEvaluation('flagKey', { kind: 'user', key: 'bob' }, 'default', () => ({ + value: false, + reason: { kind: 'ERROR', errorKind: 'FLAG_NOT_FOUND' }, + variationIndex: null, + })); + + // Test identify order + const identifyCallback = runner.identify({ kind: 'user', key: 'bob' }, 1000); + identifyCallback({ status: 'completed' }); + + // Test track order + runner.afterTrack({ + key: 'test', + context: { kind: 'user', key: 'bob' }, + data: { test: 'data' }, + metricValue: 42, + }); + + // Verify evaluation hooks order + expect(beforeEvalOrder).toEqual(['a', 'b', 'c']); + expect(afterEvalOrder).toEqual(['c', 'b', 'a']); + + // Verify identify hooks order + expect(beforeIdentifyOrder).toEqual(['a', 'b', 'c']); + expect(afterIdentifyOrder).toEqual(['c', 'b', 'a']); + + // Verify track hooks order + expect(afterTrackOrder).toEqual(['c', 'b', 'a']); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/InspectorManager-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/InspectorManager-test.js new file mode 100644 index 00000000..d381f6f1 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/InspectorManager-test.js @@ -0,0 +1,192 @@ +const { AsyncQueue } = require('launchdarkly-js-test-helpers'); +const { InspectorTypes, InspectorManager } = require('../InspectorManager'); +const stubPlatform = require('./stubPlatform'); + +describe('given an inspector manager with no registered inspectors', () => { + const platform = stubPlatform.defaults(); + const manager = InspectorManager([], platform.testing.logger); + + it('does not cause errors', () => { + manager.onIdentityChanged({ key: 'key' }); + manager.onFlagUsed( + 'flag-key', + { + value: null, + }, + { key: 'key' } + ); + manager.onFlags({}); + manager.onFlagChanged('flag-key', { value: null }); + }); + + it('does not report any registered listeners', () => { + expect(manager.hasListeners(InspectorTypes.clientIdentityChanged)).toBeFalsy(); + expect(manager.hasListeners(InspectorTypes.flagDetailChanged)).toBeFalsy(); + expect(manager.hasListeners(InspectorTypes.flagDetailsChanged)).toBeFalsy(); + expect(manager.hasListeners(InspectorTypes.flagUsed)).toBeFalsy(); + expect(manager.hasListeners('potato')).toBeFalsy(); + }); +}); + +describe.each([true, false])('given an inspector with callbacks of every type: synchronous: %p', synchronous => { + /** + * @type {AsyncQueue} + */ + const eventQueue = new AsyncQueue(); + const platform = stubPlatform.defaults(); + const manager = InspectorManager( + [ + { + type: 'flag-used', + name: 'my-flag-used-inspector', + synchronous, + method: (flagKey, flagDetail, context) => { + eventQueue.add({ type: 'flag-used', flagKey, flagDetail, context }); + }, + }, + // 'flag-used registered twice. + { + type: 'flag-used', + name: 'my-other-flag-used-inspector', + synchronous, + method: (flagKey, flagDetail, context) => { + eventQueue.add({ type: 'flag-used', flagKey, flagDetail, context }); + }, + }, + { + type: 'flag-details-changed', + name: 'my-flag-details-inspector', + synchronous, + method: details => { + eventQueue.add({ + type: 'flag-details-changed', + details, + }); + }, + }, + { + type: 'flag-detail-changed', + name: 'my-flag-detail-inspector', + synchronous, + method: (flagKey, flagDetail) => { + eventQueue.add({ + type: 'flag-detail-changed', + flagKey, + flagDetail, + }); + }, + }, + { + type: 'client-identity-changed', + name: 'my-identity-inspector', + synchronous, + method: context => { + eventQueue.add({ + type: 'client-identity-changed', + context, + }); + }, + }, + // Invalid inspector shouldn't have an effect. + { + type: 'potato', + synchronous, + name: 'my-potato-inspector', + method: () => {}, + }, + ], + platform.testing.logger + ); + + afterEach(() => { + expect(eventQueue.length()).toEqual(0); + }); + + afterAll(() => { + eventQueue.close(); + }); + + it('logged that there was a bad inspector', () => { + expect(platform.testing.logger.output.warn).toEqual([ + 'an inspector: "my-potato-inspector" of an invalid type (potato) was configured', + ]); + }); + + it('reports any registered listeners', () => { + expect(manager.hasListeners(InspectorTypes.clientIdentityChanged)).toBeTruthy(); + expect(manager.hasListeners(InspectorTypes.flagDetailChanged)).toBeTruthy(); + expect(manager.hasListeners(InspectorTypes.flagDetailsChanged)).toBeTruthy(); + expect(manager.hasListeners(InspectorTypes.flagUsed)).toBeTruthy(); + expect(manager.hasListeners('potato')).toBeFalsy(); + }); + + it('executes `onFlagUsed` handlers', async () => { + manager.onFlagUsed( + 'flag-key', + { + value: 'test', + variationIndex: 1, + reason: { + kind: 'OFF', + }, + }, + { key: 'test-key' } + ); + + const expectedEvent = { + type: 'flag-used', + flagKey: 'flag-key', + flagDetail: { + value: 'test', + variationIndex: 1, + reason: { + kind: 'OFF', + }, + }, + context: { key: 'test-key' }, + }; + const event1 = await eventQueue.take(); + expect(event1).toMatchObject(expectedEvent); + + // There are two handlers, so there should be another event. + const event2 = await eventQueue.take(); + expect(event2).toMatchObject(expectedEvent); + }); + + it('executes `onFlags` handler', async () => { + manager.onFlags({ + example: { value: 'a-value' }, + }); + + const event = await eventQueue.take(); + expect(event).toMatchObject({ + type: 'flag-details-changed', + details: { + example: { value: 'a-value' }, + }, + }); + }); + + it('executes `onFlagChanged` handler', async () => { + manager.onFlagChanged('the-flag', { value: 'a-value' }); + + const event = await eventQueue.take(); + expect(event).toMatchObject({ + type: 'flag-detail-changed', + flagKey: 'the-flag', + flagDetail: { + value: 'a-value', + }, + }); + }); + + it('executes `onIdentityChanged` handler', async () => { + manager.onIdentityChanged({ key: 'the-key' }); + + const event = await eventQueue.take(); + expect(event).toMatchObject({ + type: 'client-identity-changed', + context: { key: 'the-key' }, + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-events-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-events-test.js new file mode 100644 index 00000000..e882baf1 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-events-test.js @@ -0,0 +1,718 @@ +// @ts-nocheck +import * as messages from '../messages'; + +import { withCloseable, sleepAsync } from 'launchdarkly-js-test-helpers'; + +import { respond, respondJson } from './mockHttp'; +import * as stubPlatform from './stubPlatform'; +import { makeBootstrap, numericUser, stringifiedNumericUser } from './testUtils'; + +// These tests verify that the client generates the appropriate analytics events for various scenarios. +// We use a mock event processor component so that the events are not sent anywhere. +// +// We also use a mock HTTP service in a few tests-- not to simulate an event-recorder instance, since +// we're not testing event delivery here, but to simulate the polling service in cases where the test +// logic involves a flag request. In all other cases we just start the client with bootstrap data. + +describe('LDClient events', () => { + const envName = 'UNKNOWN_ENVIRONMENT_ID'; + const user = { key: 'user' }; + const fakeUrl = 'http://fake'; + let platform; + + beforeEach(() => { + platform = stubPlatform.defaults(); + platform.testing.setCurrentUrl(fakeUrl); + }); + + function stubEventProcessor() { + const ep = { events: [] }; + ep.start = function() {}; + ep.flush = function() {}; + ep.stop = function() {}; + ep.enqueue = function(e) { + ep.events.push(e); + }; + return ep; + } + + async function withServer(asyncCallback) { + const server = platform.testing.http.newServer(); + server.byDefault(respondJson({})); + return await withCloseable(server, asyncCallback); + } + + async function withClientAndEventProcessor(user, extraConfig, asyncCallback) { + const ep = stubEventProcessor(); + const config = Object.assign({ baseUrl: 'shouldnt-use-this', bootstrap: {}, eventProcessor: ep }, extraConfig); + const client = platform.testing.makeClient(envName, user, config); + return await withCloseable(client, async () => await asyncCallback(client, ep)); + } + + function expectIdentifyEvent(e, user) { + expect(e.kind).toEqual('identify'); + expect(e.context).toEqual(user); + } + + function expectFeatureEvent({ + e, + key, + user, + value, + variation, + version, + defaultVal, + trackEvents, + debugEventsUntilDate, + }) { + expect(e.kind).toEqual('feature'); + expect(e.key).toEqual(key); + expect(e.value).toEqual(value); + expect(e.variation).toEqual(variation); + expect(e.version).toEqual(version); + expect(e.default).toEqual(defaultVal); + expect(e.trackEvents).toEqual(trackEvents); + expect(e.debugEventsUntilDate).toEqual(debugEventsUntilDate); + expect(e.context).toEqual(user); + } + + it('sends an identify event at startup', async () => { + await withClientAndEventProcessor(user, {}, async (client, ep) => { + await client.waitForInitialization(5); + + expect(ep.events.length).toEqual(1); + expectIdentifyEvent(ep.events[0], user); + }); + }); + + it('stringifies user attributes in the identify event at startup', async () => { + // This just verifies that the event is being sent with the sanitized user, not the user that was passed in + await withClientAndEventProcessor(numericUser, {}, async (client, ep) => { + await client.waitForInitialization(5); + + expect(ep.events.length).toEqual(1); + expectIdentifyEvent(ep.events[0], stringifiedNumericUser); + }); + }); + + it('sends an identify event when identify() is called', async () => { + // need a server because it'll do a polling request when we call identify + await withServer(async server => { + await withClientAndEventProcessor(user, { baseUrl: server.url }, async (client, ep) => { + const user1 = { key: 'user1' }; + await client.waitForInitialization(5); + + expect(ep.events.length).toEqual(1); + await client.identify(user1); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[1], user1); + }); + }); + }); + + it('stringifies user attributes in the identify event when identify() is called', async () => { + // This just verifies that the event is being sent with the sanitized user, not the user that was passed in + await withServer(async server => { + await withClientAndEventProcessor(user, { baseUrl: server.url }, async (client, ep) => { + await client.waitForInitialization(5); + + expect(ep.events.length).toEqual(1); + await client.identify(numericUser); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[1], stringifiedNumericUser); + }); + }); + }); + + it('does not send an identify event if doNotTrack is set', async () => { + platform.testing.setDoNotTrack(true); + await withServer(async server => { + await withClientAndEventProcessor(user, { baseUrl: server.url }, async (client, ep) => { + const user1 = { key: 'user1' }; + + await client.waitForInitialization(5); + await client.identify(user1); + + expect(ep.events.length).toEqual(0); + }); + }); + }); + + it('sends a feature event for variation()', async () => { + const initData = makeBootstrap({ foo: { value: 'a', variation: 1, version: 2, flagVersion: 2000 } }); + await withClientAndEventProcessor(user, { bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + + client.variation('foo', 'x'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + expectFeatureEvent({ + e: ep.events[1], + key: 'foo', + user, + value: 'a', + variation: 1, + version: 2000, + defaultVal: 'x', + }); + }); + }); + + it('sends a feature event for variation() when user is anonymous', async () => { + const initData = makeBootstrap({ foo: { value: 'a', variation: 1, version: 2, flagVersion: 2000 } }); + await withServer(async server => { + const anonUser = { key: 'anon-user', anonymous: true }; + await withClientAndEventProcessor(anonUser, { baseUrl: server.url, bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + + client.variation('foo', 'x'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], anonUser); + expectFeatureEvent({ + e: ep.events[1], + key: 'foo', + user: anonUser, + value: 'a', + variation: 1, + version: 2000, + defaultVal: 'x', + }); + }); + }); + }); + + it('sends a feature event with reason for variationDetail()', async () => { + const initData = makeBootstrap({ + foo: { value: 'a', variation: 1, version: 2, flagVersion: 2000, reason: { kind: 'OFF' } }, + }); + await withClientAndEventProcessor(user, { bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + client.variationDetail('foo', 'x'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + expectFeatureEvent({ + e: ep.events[1], + key: 'foo', + user, + value: 'a', + variation: 1, + version: 2000, + defaultVal: 'x', + }); + expect(ep.events[1].reason).toEqual({ kind: 'OFF' }); + }); + }); + + it('does not include reason in event for variation() even if reason is available', async () => { + const initData = makeBootstrap({ + foo: { value: 'a', variation: 1, version: 2, flagVersion: 2000, reason: { kind: 'OFF' } }, + }); + await withClientAndEventProcessor(user, { bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + client.variation('foo', 'x'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + expectFeatureEvent({ + e: ep.events[1], + key: 'foo', + user, + value: 'a', + variation: 1, + version: 2000, + defaultVal: 'x', + }); + expect(ep.events[1].reason).toBe(undefined); + }); + }); + + it('sends a feature event with reason for variation() if trackReason is set', async () => { + const initData = makeBootstrap({ + foo: { value: 'a', variation: 1, version: 2, flagVersion: 2000, reason: { kind: 'OFF' }, trackReason: true }, + }); + await withClientAndEventProcessor(user, { bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + client.variation('foo', 'x'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + expectFeatureEvent({ + e: ep.events[1], + key: 'foo', + user, + value: 'a', + variation: 1, + version: 2000, + defaultVal: 'x', + }); + expect(ep.events[1].reason).toEqual({ kind: 'OFF' }); + }); + }); + + it('sends events for prerequisites', async () => { + const initData = makeBootstrap({ + 'is-prereq': { + value: true, + variation: 1, + reason: { + kind: 'FALLTHROUGH', + }, + version: 1, + trackEvents: true, + trackReason: true, + }, + 'has-prereq-depth-1': { + value: true, + variation: 0, + prerequisites: ['is-prereq'], + reason: { + kind: 'FALLTHROUGH', + }, + version: 4, + trackEvents: true, + trackReason: true, + }, + 'has-prereq-depth-2': { + value: true, + variation: 0, + prerequisites: ['has-prereq-depth-1'], + reason: { + kind: 'FALLTHROUGH', + }, + version: 5, + trackEvents: true, + trackReason: true, + }, + }); + await withClientAndEventProcessor(user, { bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + client.variation('has-prereq-depth-2', false); + + // An identify event and 3 feature events. + expect(ep.events.length).toEqual(4); + expectIdentifyEvent(ep.events[0], user); + expect(ep.events[1]).toMatchObject({ + kind: 'feature', + key: 'is-prereq', + variation: 1, + value: true, + version: 1, + reason: { + kind: 'FALLTHROUGH', + }, + }); + expect(ep.events[2]).toMatchObject({ + kind: 'feature', + key: 'has-prereq-depth-1', + variation: 0, + value: true, + version: 4, + reason: { + kind: 'FALLTHROUGH', + }, + }); + expect(ep.events[3]).toMatchObject({ + kind: 'feature', + key: 'has-prereq-depth-2', + variation: 0, + value: true, + version: 5, + reason: { + kind: 'FALLTHROUGH', + }, + }); + }); + }); + + it('sends a feature event on receiving a new flag value', async () => { + const oldFlags = { foo: { value: 'a', variation: 1, version: 2, flagVersion: 2000 } }; + const newFlags = { foo: { value: 'b', variation: 2, version: 3, flagVersion: 2001 } }; + const initData = makeBootstrap(oldFlags); + await withServer(async server => { + server.byDefault(respondJson(newFlags)); + await withClientAndEventProcessor(user, { baseUrl: server.url, bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + + const user1 = { key: 'user1' }; + await client.identify(user1); + + expect(ep.events.length).toEqual(3); + expectIdentifyEvent(ep.events[0], user); + expectIdentifyEvent(ep.events[1], user1); + expectFeatureEvent({ e: ep.events[2], key: 'foo', user: user1, value: 'b', variation: 2, version: 2001 }); + }); + }); + }); + + it('does not send a feature event for a new flag value if sendEventsOnlyForVariation is set', async () => { + const oldFlags = { foo: { value: 'a', variation: 1, version: 2, flagVersion: 2000 } }; + const newFlags = { foo: { value: 'b', variation: 2, version: 3, flagVersion: 2001 } }; + const initData = makeBootstrap(oldFlags); + await withServer(async server => { + server.byDefault(respondJson(newFlags)); + const extraConfig = { sendEventsOnlyForVariation: true, baseUrl: server.url, bootstrap: initData }; + await withClientAndEventProcessor(user, extraConfig, async (client, ep) => { + await client.waitForInitialization(5); + + const user1 = { key: 'user1' }; + await client.identify(user1); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + expectIdentifyEvent(ep.events[1], user1); + }); + }); + }); + + it('does not send a feature event for a new flag value if there is a state provider', async () => { + const oldFlags = { foo: { value: 'a', variation: 1, version: 2, flagVersion: 2000 } }; + const newFlags = { foo: { value: 'b', variation: 2, version: 3, flagVersion: 2001 } }; + const sp = stubPlatform.mockStateProvider({ environment: envName, context: user, flags: oldFlags }); + await withServer(async server => { + server.byDefault(respondJson(newFlags)); + const extraConfig = { stateProvider: sp, baseUrl: server.url }; + await withClientAndEventProcessor(user, extraConfig, async (client, ep) => { + await client.waitForInitialization(5); + + sp.emit('update', { flags: newFlags }); + + expect(client.variation('foo')).toEqual('b'); + expect(ep.events.length).toEqual(1); + }); + }); + }); + + it('sends feature events for allFlags()', async () => { + const initData = makeBootstrap({ + foo: { value: 'a', variation: 1, version: 2 }, + bar: { value: 'b', variation: 1, version: 3 }, + }); + await withClientAndEventProcessor(user, { bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + client.allFlags(); + + expect(ep.events.length).toEqual(3); + expectIdentifyEvent(ep.events[0], user); + expectFeatureEvent({ e: ep.events[1], key: 'foo', user, value: 'a', variation: 1, version: 2, defaultVal: null }); + expectFeatureEvent({ e: ep.events[2], key: 'bar', user, value: 'b', variation: 1, version: 3, defaultVal: null }); + }); + }); + + it('does not send duplicate events for prerequisites with all flags.', async () => { + const initData = makeBootstrap({ + foo: { value: 'a', variation: 1, version: 2 }, + bar: { value: 'b', variation: 1, version: 3, prerequisites: ['foo'] }, + }); + await withClientAndEventProcessor(user, { bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + client.allFlags(); + + expect(ep.events.length).toEqual(3); + expectIdentifyEvent(ep.events[0], user); + expectFeatureEvent({ e: ep.events[1], key: 'foo', user, value: 'a', variation: 1, version: 2, defaultVal: null }); + expectFeatureEvent({ e: ep.events[2], key: 'bar', user, value: 'b', variation: 1, version: 3, defaultVal: null }); + }); + }); + + it('does not send feature events for allFlags() if sendEventsOnlyForVariation is set', async () => { + const initData = makeBootstrap({ + foo: { value: 'a', variation: 1, version: 2 }, + bar: { value: 'b', variation: 1, version: 3 }, + }); + const extraConfig = { sendEventsOnlyForVariation: true, bootstrap: initData }; + await withClientAndEventProcessor(user, extraConfig, async (client, ep) => { + await client.waitForInitialization(5); + client.allFlags(); + + expect(ep.events.length).toEqual(1); + expectIdentifyEvent(ep.events[0], user); + }); + }); + + it('uses "version" instead of "flagVersion" in event if "flagVersion" is absent', async () => { + const initData = makeBootstrap({ foo: { value: 'a', variation: 1, version: 2 } }); + await withClientAndEventProcessor(user, { bootstrap: initData }, async (client, ep) => { + await client.waitForInitialization(5); + client.variation('foo', 'x'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + expectFeatureEvent({ e: ep.events[1], key: 'foo', user, value: 'a', variation: 1, version: 2, defaultVal: 'x' }); + }); + }); + + it('omits event version if flag does not exist', async () => { + await withClientAndEventProcessor(user, {}, async (client, ep) => { + await client.waitForInitialization(5); + client.variation('foo', 'x'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + expectFeatureEvent({ e: ep.events[1], key: 'foo', user, value: 'x', variation: null, defaultVal: 'x' }); + }); + }); + + it('can get metadata for events from bootstrap object', async () => { + const initData = makeBootstrap({ + foo: { + value: 'bar', + variation: 1, + version: 2, + trackEvents: true, + debugEventsUntilDate: 1000, + }, + }); + await withClientAndEventProcessor(user, { bootstrap: initData }, async (client, ep) => { + await withCloseable(client, async () => { + await client.waitForInitialization(5); + client.variation('foo', 'x'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + expectFeatureEvent({ + e: ep.events[1], + key: 'foo', + value: 'bar', + variation: 1, + version: 2, + defaultVal: 'x', + trackEvents: true, + debugEventsUntilDate: 1000, + user, + }); + }); + }); + }); + + it('sends an event for track()', async () => { + await withClientAndEventProcessor(user, {}, async (client, ep) => { + await client.waitForInitialization(5); + client.track('eventkey'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + const trackEvent = ep.events[1]; + expect(trackEvent.kind).toEqual('custom'); + expect(trackEvent.key).toEqual('eventkey'); + expect(trackEvent.context).toEqual(user); + expect(trackEvent.data).toEqual(undefined); + expect(trackEvent.url).toEqual(fakeUrl); + }); + }); + + it('sends an event for track() when user is anonymous', async () => { + await withServer(async server => { + const anonUser = { key: 'anon-user', anonymous: true }; + await withClientAndEventProcessor(anonUser, { baseUrl: server.url }, async (client, ep) => { + await client.waitForInitialization(5); + client.track('eventkey'); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], anonUser); + const trackEvent = ep.events[1]; + expect(trackEvent.kind).toEqual('custom'); + expect(trackEvent.key).toEqual('eventkey'); + expect(trackEvent.context).toEqual(anonUser); + expect(trackEvent.data).toEqual(undefined); + expect(trackEvent.url).toEqual(fakeUrl); + }); + }); + }); + + it('sends an event for track() with data', async () => { + await withClientAndEventProcessor(user, {}, async (client, ep) => { + const eventData = { thing: 'stuff' }; + await client.waitForInitialization(5); + client.track('eventkey', eventData); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + const trackEvent = ep.events[1]; + expect(trackEvent.kind).toEqual('custom'); + expect(trackEvent.key).toEqual('eventkey'); + expect(trackEvent.context).toEqual(user); + expect(trackEvent.data).toEqual(eventData); + expect(trackEvent.url).toEqual(fakeUrl); + }); + }); + + it('sends an event for track() with metric value', async () => { + await withClientAndEventProcessor(user, {}, async (client, ep) => { + const eventData = { thing: 'stuff' }; + const metricValue = 1.5; + await client.waitForInitialization(5); + client.track('eventkey', eventData, metricValue); + + expect(ep.events.length).toEqual(2); + expectIdentifyEvent(ep.events[0], user); + const trackEvent = ep.events[1]; + expect(trackEvent.kind).toEqual('custom'); + expect(trackEvent.key).toEqual('eventkey'); + expect(trackEvent.context).toEqual(user); + expect(trackEvent.data).toEqual(eventData); + expect(trackEvent.metricValue).toEqual(metricValue); + expect(trackEvent.url).toEqual(fakeUrl); + }); + }); + + it('does not send an event for track() if doNotTrack is set', async () => { + platform.testing.setDoNotTrack(true); + await withClientAndEventProcessor(user, {}, async (client, ep) => { + const eventData = { thing: 'stuff' }; + await client.waitForInitialization(5); + client.track('eventkey', eventData); + expect(ep.events.length).toEqual(0); + }); + }); + + it('does not warn by default when tracking a custom event', async () => { + await withClientAndEventProcessor(user, {}, async client => { + await client.waitForInitialization(5); + + client.track('known'); + expect(platform.testing.logger.output.warn).toEqual([]); + }); + }); + + it('does warn when a metric value is non-numeric', async () => { + await withClientAndEventProcessor(user, {}, async client => { + await client.waitForInitialization(5); + + client.track('known', undefined, '12'); + expect(platform.testing.logger.output.warn).toEqual([ + 'The track function was called with a non-numeric "metricValue" (string), ' + + 'only numeric metric values are supported.', + ]); + }); + }); + + it('emits an error when tracking a non-string custom event', async () => { + await withClientAndEventProcessor(user, {}, async client => { + await client.waitForInitialization(5); + + const badCustomEventKeys = [123, [], {}, null, undefined]; + badCustomEventKeys.forEach(key => { + platform.testing.logger.reset(); + client.track(key); + expect(platform.testing.logger.output.error).toEqual([messages.unknownCustomEventKey(key)]); + }); + }); + }); + + it('should warn about missing user on first event', async () => { + await withClientAndEventProcessor(null, {}, async client => { + client.track('eventkey', null); + expect(platform.testing.logger.output.warn).toEqual([messages.eventWithoutContext()]); + }); + }); + + it('allows stateProvider to take over sending an event', async () => { + const sp = stubPlatform.mockStateProvider({ environment: envName, context: user, flags: {} }); + const divertedEvents = []; + sp.enqueueEvent = event => divertedEvents.push(event); + + await withClientAndEventProcessor(user, { stateProvider: sp }, async (client, ep) => { + await client.waitForInitialization(5); + + client.track('eventkey'); + expect(ep.events.length).toEqual(0); + expect(divertedEvents.length).toEqual(1); + expect(divertedEvents[0].kind).toEqual('custom'); + }); + }); + + async function expectDiagnosticEventAndDiscardRegularEvent(server) { + const req0 = await server.nextRequest(); + const req1 = await server.nextRequest(); + const expectedPath = '/events/diagnostic/' + envName; + const otherPath = '/events/bulk/' + envName; + let initEventReq; + if (req0.path === expectedPath) { + expect(req1.path).toEqual(otherPath); + initEventReq = req0; + } else { + expect(req0.path).toEqual(otherPath); + expect(req1.path).toEqual(expectedPath); + initEventReq = req1; + } + return JSON.parse(initEventReq.body); + } + + async function expectNoMoreRequests(server, timeout) { + await sleepAsync(timeout); + expect(server.requests.length()).toEqual(0); + } + + it('sends diagnostic init event on startup', async () => { + const server = platform.testing.http.newServer(); + server.byDefault(respond(202)); + await withCloseable(server, async () => { + const config = { + baseUrl: 'shouldnt-use-this', + bootstrap: {}, + eventsUrl: server.url, + }; + const client = platform.testing.makeClient(envName, user, config); + await withCloseable(client, async () => { + await client.waitForInitialization(5); + await client.flush(); + const data = await expectDiagnosticEventAndDiscardRegularEvent(server); + expect(data.kind).toEqual('diagnostic-init'); + expect(data.platform).toEqual(platform.diagnosticPlatformData); + expect(data.sdk).toEqual(platform.diagnosticSdkData); + await expectNoMoreRequests(server, 50); + }); + }); + }); + + it('sends diagnostic combined event on startup', async () => { + const platform1 = stubPlatform.defaults(); + platform1.diagnosticUseCombinedEvent = true; + const server = platform1.testing.http.newServer(); + server.byDefault(respond(202)); + await withCloseable(server, async () => { + const config = { + baseUrl: 'shouldnt-use-this', + bootstrap: {}, + eventsUrl: server.url, + }; + const client = platform1.testing.makeClient(envName, user, config); + await withCloseable(client, async () => { + await client.waitForInitialization(5); + await client.flush(); + const data = await expectDiagnosticEventAndDiscardRegularEvent(server); + expect(data.kind).toEqual('diagnostic-combined'); + expect(data.platform).toEqual(platform1.diagnosticPlatformData); + expect(data.sdk).toEqual(platform1.diagnosticSdkData); + await expectNoMoreRequests(server, 50); + }); + }); + }); + + it('does not send diagnostic init event when opted out', async () => { + const server = platform.testing.http.newServer(); + server.byDefault(respond(202)); + await withCloseable(server, async () => { + const config = { + baseUrl: 'shouldnt-use-this', + bootstrap: {}, + eventsUrl: server.url, + diagnosticOptOut: true, + }; + const client = platform.testing.makeClient(envName, user, config); + await withCloseable(client, async () => { + await client.waitForInitialization(5); + await client.flush(); + expect(server.requests.length()).toEqual(1); + const req = await server.nextRequest(); + expect(req.path).toEqual('/events/bulk/' + envName); + await expectNoMoreRequests(server, 50); + }); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-hooks-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-hooks-test.js new file mode 100644 index 00000000..c707e752 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-hooks-test.js @@ -0,0 +1,254 @@ +const { initialize } = require('../index'); +const stubPlatform = require('./stubPlatform'); +const { respondJson } = require('./mockHttp'); + +// Mock the logger functions +const mockLogger = () => ({ + error: jest.fn(), + warn: jest.fn(), + info: jest.fn(), + debug: jest.fn(), +}); + +// Define a basic Hook structure for tests +const createTestHook = (name = 'Test Hook') => ({ + getMetadata: jest.fn().mockReturnValue({ name }), + beforeEvaluation: jest.fn(), + afterEvaluation: jest.fn(), + beforeIdentify: jest.fn().mockImplementation((_ctx, data) => data), // Pass data through + afterIdentify: jest.fn(), +}); + +// Helper to initialize the client for tests +// Disables network requests and event sending by default +async function withClient(initialContext, configOverrides = {}, hooks = [], testFn) { + const platform = stubPlatform.defaults(); + const server = platform.testing.http.newServer(); + + const logger = mockLogger(); + + // Disable streaming and event sending unless overridden + // Configure client to use the mock server's URL + const defaults = { + baseUrl: server.url, // Use mock server URL + streaming: false, + sendEvents: false, + useLdd: false, + logger: logger, + hooks: hooks, // Pass initial hooks here + }; + const config = { ...defaults, ...configOverrides }; + const { client, start } = initialize('env', initialContext, config, platform); + + // Set the mock server to return an empty flag set by default + server.byDefault(respondJson({})); // Correct way to provide initial flags + + start(); // Start the client components + + try { + // Wait briefly for initialization (client will hit the mock server) + await client.waitForInitialization(10); // Use a short timeout + await testFn(client, logger, platform); // Pass client, logger, platform to the test + } finally { + await client.close(); + server.close(); // Close the mock server + } +} + +describe('LDClient Hooks Integration', () => { + const initialContext = { kind: 'user', key: 'user-key-initial' }; + const flagKey = 'test-flag'; + const flagDefaultValue = false; + // Expected result when flag is not found (as it will be with empty flags) + const flagNotFoundDetail = { + value: flagDefaultValue, + variationIndex: null, + reason: { kind: 'ERROR', errorKind: 'FLAG_NOT_FOUND' }, + }; + + it('should use hooks registered during configuration', async () => { + const testHook = createTestHook('Initial Hook'); + const initialData = {}; // Hooks start with empty data + + await withClient(initialContext, {}, [testHook], async client => { + // Call variation + await client.variation(flagKey, flagDefaultValue); + + // Check identify hooks + expect(testHook.beforeIdentify).toHaveBeenCalledTimes(1); + expect(testHook.beforeIdentify).toHaveBeenCalledWith( + expect.objectContaining({ + context: initialContext, + // timeout will be undefined unless explicitly passed to identify + }), + initialData + ); + expect(testHook.afterIdentify).toHaveBeenCalledTimes(1); + expect(testHook.afterIdentify).toHaveBeenCalledWith( + expect.objectContaining({ + context: initialContext, + }), + initialData, // Assumes beforeIdentify just returned the initial data + { status: 'completed' } + ); + + // Check evaluation hooks (context from identify is now current) + expect(testHook.beforeEvaluation).toHaveBeenCalledTimes(1); + expect(testHook.beforeEvaluation).toHaveBeenCalledWith( + expect.objectContaining({ + flagKey: flagKey, + context: initialContext, + defaultValue: flagDefaultValue, + }), + initialData + ); + expect(testHook.afterEvaluation).toHaveBeenCalledTimes(1); + expect(testHook.afterEvaluation).toHaveBeenCalledWith( + expect.objectContaining({ + flagKey: flagKey, + context: initialContext, + defaultValue: flagDefaultValue, + }), + initialData, // Assumes beforeEvaluation just returned the initial data + flagNotFoundDetail // Using the default flag not found result + ); + }); + }); + + it('should execute hooks that are added using addHook', async () => { + const addedHook = createTestHook('Added Hook'); + const identifyContext = { kind: 'user', key: 'user-key-added' }; + const initialData = {}; + + // Initialize client *without* the hook initially + await withClient(initialContext, {}, [], async client => { + // Add the hook dynamically + client.addHook(addedHook); + + // Call identify and variation + await client.identify(identifyContext); + await client.variation(flagKey, flagDefaultValue); + + // Check identify hooks + expect(addedHook.beforeIdentify).toHaveBeenCalledTimes(1); + expect(addedHook.beforeIdentify).toHaveBeenCalledWith( + expect.objectContaining({ context: identifyContext }), + initialData + ); + expect(addedHook.afterIdentify).toHaveBeenCalledTimes(1); + expect(addedHook.afterIdentify).toHaveBeenCalledWith( + expect.objectContaining({ context: identifyContext }), + initialData, + { status: 'completed' } + ); + + // Check evaluation hooks + expect(addedHook.beforeEvaluation).toHaveBeenCalledTimes(1); + expect(addedHook.beforeEvaluation).toHaveBeenCalledWith( + expect.objectContaining({ flagKey, context: identifyContext, defaultValue: flagDefaultValue }), + initialData + ); + expect(addedHook.afterEvaluation).toHaveBeenCalledTimes(1); + expect(addedHook.afterEvaluation).toHaveBeenCalledWith( + expect.objectContaining({ flagKey, context: identifyContext, defaultValue: flagDefaultValue }), + initialData, + flagNotFoundDetail + ); + }); + }); + + it('should execute both initial hooks and hooks added using addHook', async () => { + const initialHook = createTestHook('Initial Hook For Both'); + const addedHook = createTestHook('Added Hook For Both'); + const identifyContext = { kind: 'user', key: 'user-key-both' }; + const initialData = {}; + + // Initialize client *with* the initial hook + await withClient(initialContext, {}, [initialHook], async client => { + // Add the second hook dynamically + client.addHook(addedHook); + + await client.identify(identifyContext); + await client.variation(flagKey, flagDefaultValue); + + expect(initialHook.beforeIdentify).toHaveBeenCalledTimes(2); + expect(initialHook.beforeIdentify).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ context: initialContext }), + initialData + ); + expect(initialHook.beforeIdentify).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ context: identifyContext }), + initialData + ); + + expect(initialHook.afterIdentify).toHaveBeenCalledTimes(2); + expect(initialHook.afterIdentify).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ context: initialContext }), + initialData, // Assuming pass-through + { status: 'completed' } + ); + expect(initialHook.afterIdentify).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ context: identifyContext }), + initialData, // Assuming pass-through + { status: 'completed' } + ); + + expect(addedHook.beforeIdentify).toHaveBeenCalledTimes(1); + expect(addedHook.beforeIdentify).toHaveBeenCalledWith( + expect.objectContaining({ context: identifyContext }), + initialData + ); + expect(addedHook.afterIdentify).toHaveBeenCalledTimes(1); + expect(addedHook.afterIdentify).toHaveBeenCalledWith( + expect.objectContaining({ context: identifyContext }), + initialData, // Assuming pass-through + { status: 'completed' } + ); + + // Check evaluation hooks for BOTH hooks + [initialHook, addedHook].forEach(hook => { + expect(hook.beforeEvaluation).toHaveBeenCalledTimes(1); + expect(hook.beforeEvaluation).toHaveBeenCalledWith( + expect.objectContaining({ flagKey, context: identifyContext, defaultValue: flagDefaultValue }), + initialData + ); + expect(hook.afterEvaluation).toHaveBeenCalledTimes(1); + expect(hook.afterEvaluation).toHaveBeenCalledWith( + expect.objectContaining({ flagKey, context: identifyContext, defaultValue: flagDefaultValue }), + initialData, // Assuming pass-through + flagNotFoundDetail + ); + }); + }); + }); + + it('should execute afterTrack hooks when tracking events', async () => { + const testHook = { + beforeEvaluation: jest.fn(), + afterEvaluation: jest.fn(), + beforeIdentify: jest.fn(), + afterIdentify: jest.fn(), + afterTrack: jest.fn(), + getMetadata() { + return { + name: 'test hook', + }; + }, + }; + + await withClient(initialContext, {}, [testHook], async client => { + client.track('test', { test: 'data' }, 42); + + expect(testHook.afterTrack).toHaveBeenCalledWith({ + key: 'test', + context: { kind: 'user', key: 'user-key-initial' }, + data: { test: 'data' }, + metricValue: 42, + }); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-inspectors-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-inspectors-test.js new file mode 100644 index 00000000..4a31c334 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-inspectors-test.js @@ -0,0 +1,236 @@ +const { AsyncQueue } = require('launchdarkly-js-test-helpers'); +const { respondJson } = require('./mockHttp'); +const stubPlatform = require('./stubPlatform'); + +const envName = 'UNKNOWN_ENVIRONMENT_ID'; +const context = { key: 'context-key' }; + +const flagPayload = { + 'is-prereq': { + value: true, + variation: 1, + reason: { + kind: 'FALLTHROUGH', + }, + version: 1, + trackEvents: true, + trackReason: true, + }, + 'has-prereq-depth-1': { + value: true, + variation: 0, + prerequisites: ['is-prereq'], + reason: { + kind: 'FALLTHROUGH', + }, + version: 4, + trackEvents: true, + trackReason: true, + }, + 'has-prereq-depth-2': { + value: true, + variation: 0, + prerequisites: ['has-prereq-depth-1'], + reason: { + kind: 'FALLTHROUGH', + }, + version: 5, + trackEvents: true, + trackReason: true, + }, +}; + +describe.each([true, false])('given a streaming client with registered inspectors, synchronous: %p', synchronous => { + const eventQueue = new AsyncQueue(); + + const inspectors = [ + { + type: 'flag-used', + synchronous, + method: (flagKey, flagDetail, context) => { + eventQueue.add({ type: 'flag-used', flagKey, flagDetail, context }); + }, + }, + // 'flag-used registered twice. + { + type: 'flag-used', + synchronous, + method: (flagKey, flagDetail, context) => { + eventQueue.add({ type: 'flag-used', flagKey, flagDetail, context }); + }, + }, + { + type: 'flag-details-changed', + synchronous, + method: details => { + eventQueue.add({ + type: 'flag-details-changed', + details, + }); + }, + }, + { + type: 'flag-detail-changed', + synchronous, + method: (flagKey, flagDetail) => { + eventQueue.add({ + type: 'flag-detail-changed', + flagKey, + flagDetail, + }); + }, + }, + { + type: 'client-identity-changed', + synchronous, + method: context => { + eventQueue.add({ + type: 'client-identity-changed', + context, + }); + }, + }, + ]; + + let client; + let platform; + + beforeEach(async () => { + platform = stubPlatform.defaults(); + const server = platform.testing.http.newServer(); + server.byDefault(respondJson(flagPayload)); + const config = { streaming: true, baseUrl: server.url, inspectors, sendEvents: false }; + client = platform.testing.makeClient(envName, context, config); + await client.waitUntilReady(); + }); + + afterEach(() => { + expect(eventQueue.length()).toEqual(0); + }); + + afterAll(() => { + eventQueue.close(); + }); + + afterEach(async () => { + await client.close(); + }); + + it('has an initial identify event and flag payload', async () => { + // These events cover the initial identify and a polling response. + const ident = await eventQueue.take(); + expect(ident).toMatchObject({ + type: 'client-identity-changed', + context, + }); + const flagsEvent = await eventQueue.take(); + expect(flagsEvent).toMatchObject({ + type: 'flag-details-changed', + details: { + 'is-prereq': { + value: true, + variationIndex: 1, + reason: { + kind: 'FALLTHROUGH', + }, + }, + 'has-prereq-depth-1': { + value: true, + variationIndex: 0, + reason: { + kind: 'FALLTHROUGH', + }, + }, + 'has-prereq-depth-2': { + value: true, + variationIndex: 0, + reason: { + kind: 'FALLTHROUGH', + }, + }, + }, + }); + }); + + it('emits an event for the stream put replacing all flags', async () => { + // Take initial events. + eventQueue.take(); + eventQueue.take(); + + const stream = await platform.testing.eventSourcesCreated.take(); + stream.eventSource.mockEmit('put', { + data: '{"flagKey":{"value":true,"version":1}}', + }); + const updateEvent = await eventQueue.take(); + expect(updateEvent).toMatchObject({ + type: 'flag-details-changed', + details: { + flagKey: { value: true }, + }, + }); + }); + + it('emits an event for a stream patch changing a flag', async () => { + // Take initial events. + eventQueue.take(); + eventQueue.take(); + + const stream = await platform.testing.eventSourcesCreated.take(); + stream.eventSource.mockEmit('patch', { + data: '{"key": "flagKey", "value":false,"version":2}', + }); + const updateEvent = await eventQueue.take(); + expect(updateEvent).toMatchObject({ + type: 'flag-detail-changed', + flagKey: 'flagKey', + flagDetail: { value: false }, + }); + }); + + it('emits an event when a flag is used', async () => { + // Take initial events. + eventQueue.take(); + eventQueue.take(); + + await platform.testing.eventSourcesCreated.take(); + client.variation('is-prereq', false); + const updateEvent = await eventQueue.take(); + expect(updateEvent).toMatchObject({ + type: 'flag-used', + flagKey: 'is-prereq', + flagDetail: { value: true }, + }); + // Two inspectors are handling this + const updateEvent2 = await eventQueue.take(); + expect(updateEvent2).toMatchObject({ + type: 'flag-used', + flagKey: 'is-prereq', + flagDetail: { value: true }, + }); + }); + + it('does not execute flag-used for prerequisites', async () => { + // Take initial events. + eventQueue.take(); + eventQueue.take(); + + await platform.testing.eventSourcesCreated.take(); + client.variation('has-prereq-depth-2', false); + // There would be many more than 2 events if prerequisites were inspected. + const updateEvent = await eventQueue.take(); + expect(updateEvent).toMatchObject({ + type: 'flag-used', + flagKey: 'has-prereq-depth-2', + flagDetail: { value: true }, + }); + // Two inspectors are handling this + const updateEvent2 = await eventQueue.take(); + expect(updateEvent2).toMatchObject({ + type: 'flag-used', + flagKey: 'has-prereq-depth-2', + flagDetail: { value: true }, + }); + + expect(eventQueue.length()).toEqual(0); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-localstorage-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-localstorage-test.js new file mode 100644 index 00000000..6b092d8e --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-localstorage-test.js @@ -0,0 +1,179 @@ +import * as messages from '../messages'; +import * as utils from '../utils'; + +import { sleepAsync, withCloseable } from 'launchdarkly-js-test-helpers'; + +import { respond, respondJson } from './mockHttp'; +import * as stubPlatform from './stubPlatform'; + +// These tests cover the "bootstrap: 'localstorage'" mode. The actual implementation of local storage +// is provided by the platform-specific SDKs; we use a mock implementation here. + +describe('LDClient local storage', () => { + const envName = 'UNKNOWN_ENVIRONMENT_ID'; + const user = { key: 'user' }; + const lsKey = 'ld:' + envName + ':' + utils.btoa(JSON.stringify(user)); + let platform; + + beforeEach(() => { + platform = stubPlatform.defaults(); + }); + + async function withServer(asyncCallback) { + const server = platform.testing.http.newServer(); + server.byDefault(respondJson({})); + return await withCloseable(server, asyncCallback); + } + + async function withClient(user, extraConfig, asyncCallback) { + // We specify bootstrap: 'localstorage' for all tests in this file + const config = { baseUrl: 'shouldnt-use-this', bootstrap: 'localstorage', sendEvents: false, ...extraConfig }; + const client = platform.testing.makeClient(envName, user, config); + return await withCloseable(client, asyncCallback); + } + + describe('bootstrapping from local storage', () => { + it('does not try to use local storage if the platform says it is unavailable', async () => { + platform.localStorage = null; + + await withServer(async server => { + await withClient(user, { baseUrl: server.url }, async client => { + await client.waitForInitialization(5); + + // should see a flag request to the server right away, as if bootstrap was not specified + expect(server.requests.length()).toEqual(1); + + expect(platform.testing.logger.output.warn).toEqual([messages.localStorageUnavailable()]); + }); + }); + }); + + it('uses cached flags if available and requests flags from server after ready', async () => { + const json = '{"flag-key": 1}'; + platform.testing.setLocalStorageImmediately(lsKey, json); + + await withServer(async server => { + // This no-op request handler means that the flags request will simply hang with no + // response, so we can be sure that we're seeing only the initial flags from local storage. + server.byDefault(() => {}); + + await withClient(user, { baseUrl: server.url }, async client => { + await client.waitForInitialization(5); + + expect(client.variation('flag-key')).toEqual(1); + + await sleepAsync(0); // allow any pending async tasks to complete + + expect(server.requests.length()).toEqual(1); + }); + }); + }); + + it('starts with empty flags and requests them from server if there are no cached flags', async () => { + const flags = { 'flag-key': { value: 1 } }; + + await withServer(async server => { + server.byDefault(respondJson(flags)); + await withClient(user, { baseUrl: server.url }, async client => { + // don't wait for ready event - verifying that variation() doesn't throw an error if called before ready + expect(client.variation('flag-key', 0)).toEqual(0); + + // verify that the flags get requested from LD + await client.waitForInitialization(5); + expect(client.variation('flag-key')).toEqual(1); + }); + }); + }); + + it('should handle localStorage.get returning an error', async () => { + const myError = new Error('deliberate error'); + platform.localStorage.get = () => Promise.reject(myError); + const flags = { 'enable-foo': { value: true } }; + + await withServer(async server => { + server.byDefault(respondJson(flags)); + await withClient(user, { baseUrl: server.url }, async client => { + await client.waitForInitialization(5); + expect(platform.testing.logger.output.warn).toEqual([messages.localStorageUnavailable(myError)]); + }); + }); + }); + + it('should handle localStorage.set returning an error', async () => { + const myError = new Error('deliberate error'); + platform.localStorage.set = () => Promise.reject(myError); + const flags = { 'enable-foo': { value: true } }; + + await withServer(async server => { + server.byDefault(respondJson(flags)); + await withClient(user, { baseUrl: server.url }, async client => { + await client.waitForInitialization(5); + + await sleepAsync(0); // allow any pending async tasks to complete + + expect(platform.testing.logger.output.warn).toEqual([messages.localStorageUnavailable(myError)]); + }); + }); + }); + + it('should not update cached settings if there was an error fetching flags', async () => { + const json = '{"enable-foo": true}'; + platform.testing.setLocalStorageImmediately(lsKey, json); + + await withServer(async server => { + server.byDefault(respond(503)); + await withClient(user, { baseUrl: server.url }, async client => { + await client.waitForInitialization(5); + + await sleepAsync(0); // allow any pending async tasks to complete + + const value = platform.testing.getLocalStorageImmediately(lsKey); + expect(value).toEqual(json); + }); + }); + }); + + it('should use hash as localStorage key when secure mode is enabled', async () => { + const hash = 'totallyLegitHash'; + const lsKeyHash = 'ld:UNKNOWN_ENVIRONMENT_ID:' + hash; + const flags = { 'enable-foo': { value: true } }; + + await withServer(async server => { + server.byDefault(respondJson(flags)); + await withClient(user, { baseUrl: server.url, hash }, async client => { + await client.waitForInitialization(5); + const value = platform.testing.getLocalStorageImmediately(lsKeyHash); + expect(JSON.parse(value)).toEqual({ + $schema: 1, + 'enable-foo': { value: true }, + }); + }); + }); + }); + + it('should clear localStorage when user context is changed', async () => { + const lsKey2 = 'ld:UNKNOWN_ENVIRONMENT_ID:' + utils.btoa('{"key":"user2"}'); + const flags = { 'enable-foo': { value: true } }; + const user2 = { key: 'user2' }; + + await withServer(async server => { + server.byDefault(respondJson(flags)); + await withClient(user, { baseUrl: server.url }, async client => { + await client.waitForInitialization(5); + + await sleepAsync(0); // allow any pending async tasks to complete + + await client.identify(user2); + + const value1 = platform.testing.getLocalStorageImmediately(lsKey); + expect(value1).not.toEqual(expect.anything()); + const value2 = platform.testing.getLocalStorageImmediately(lsKey2); + expect(JSON.parse(value2)).toEqual({ + $schema: 1, + 'enable-foo': { value: true }, + }); + }); + }); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-plugins-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-plugins-test.js new file mode 100644 index 00000000..fcc690b8 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-plugins-test.js @@ -0,0 +1,214 @@ +const { initialize } = require('../index'); +const stubPlatform = require('./stubPlatform'); +const { respondJson } = require('./mockHttp'); + +// Mock the logger functions +const mockLogger = () => ({ + error: jest.fn(), + warn: jest.fn(), + info: jest.fn(), + debug: jest.fn(), +}); + +// Define a basic Hook structure for tests +const createTestHook = (name = 'Test Hook') => ({ + getMetadata: jest.fn().mockReturnValue({ name }), + beforeEvaluation: jest.fn().mockImplementation((_ctx, data) => data), + afterEvaluation: jest.fn().mockImplementation((_ctx, data) => data), + beforeIdentify: jest.fn().mockImplementation((_ctx, data) => data), + afterIdentify: jest.fn().mockImplementation((_ctx, data) => data), + afterTrack: jest.fn().mockImplementation((_ctx, data) => data), +}); + +// Define a basic Plugin structure for tests +const createTestPlugin = (name = 'Test Plugin', hooks = []) => ({ + getMetadata: jest.fn().mockReturnValue({ name }), + register: jest.fn(), + getHooks: jest.fn().mockReturnValue(hooks), +}); + +// Helper to initialize the client for tests +async function withClient(initialContext, configOverrides = {}, plugins = [], testFn) { + const platform = stubPlatform.defaults(); + const server = platform.testing.http.newServer(); + const logger = mockLogger(); + + // Disable streaming and event sending unless overridden + const defaults = { + baseUrl: server.url, + streaming: false, + sendEvents: false, + useLdd: false, + logger: logger, + plugins: plugins, + }; + const config = { ...defaults, ...configOverrides }; + const { client, start } = initialize('env', initialContext, config, platform); + + server.byDefault(respondJson({})); + start(); + + try { + await client.waitForInitialization(10); + await testFn(client, logger, platform); + } finally { + await client.close(); + server.close(); + } +} + +it('registers plugins and executes hooks during initialization', async () => { + const mockHook = createTestHook('test-hook'); + const mockPlugin = createTestPlugin('test-plugin', [mockHook]); + + await withClient({ key: 'user-key', kind: 'user' }, {}, [mockPlugin], async client => { + // Verify the plugin was registered + expect(mockPlugin.register).toHaveBeenCalled(); + + // Test identify hook + await client.identify({ key: 'user-key', kind: 'user' }); + expect(mockHook.beforeIdentify).toHaveBeenCalledWith( + { context: { key: 'user-key', kind: 'user' }, timeout: undefined }, + {} + ); + expect(mockHook.afterIdentify).toHaveBeenCalledWith( + { context: { key: 'user-key', kind: 'user' }, timeout: undefined }, + {}, + { status: 'completed' } + ); + + // Test variation hook + client.variation('flag-key', false); + expect(mockHook.beforeEvaluation).toHaveBeenCalledWith( + { + context: { key: 'user-key', kind: 'user' }, + defaultValue: false, + flagKey: 'flag-key', + }, + {} + ); + expect(mockHook.afterEvaluation).toHaveBeenCalled(); + + // Test track hook + client.track('event-key', { data: true }, 42); + expect(mockHook.afterTrack).toHaveBeenCalledWith({ + context: { key: 'user-key', kind: 'user' }, + key: 'event-key', + data: { data: true }, + metricValue: 42, + }); + }); +}); + +it('registers multiple plugins and executes all hooks', async () => { + const mockHook1 = createTestHook('test-hook-1'); + const mockHook2 = createTestHook('test-hook-2'); + const mockPlugin1 = createTestPlugin('test-plugin-1', [mockHook1]); + const mockPlugin2 = createTestPlugin('test-plugin-2', [mockHook2]); + + await withClient({ key: 'user-key', kind: 'user' }, {}, [mockPlugin1, mockPlugin2], async client => { + // Verify plugins were registered + expect(mockPlugin1.register).toHaveBeenCalled(); + expect(mockPlugin2.register).toHaveBeenCalled(); + + // Test that both hooks work + await client.identify({ key: 'user-key', kind: 'user' }); + client.variation('flag-key', false); + client.track('event-key', { data: true }, 42); + + expect(mockHook1.beforeEvaluation).toHaveBeenCalled(); + expect(mockHook1.afterEvaluation).toHaveBeenCalled(); + expect(mockHook2.beforeEvaluation).toHaveBeenCalled(); + expect(mockHook2.afterEvaluation).toHaveBeenCalled(); + expect(mockHook1.afterTrack).toHaveBeenCalled(); + expect(mockHook2.afterTrack).toHaveBeenCalled(); + }); +}); + +it('passes correct environmentMetadata to plugin getHooks and register functions', async () => { + const mockPlugin = createTestPlugin('test-plugin'); + const options = { + wrapperName: 'test-wrapper', + wrapperVersion: '2.0.0', + application: { + name: 'test-app', + version: '3.0.0', + }, + }; + + await withClient( + { key: 'user-key', kind: 'user' }, + { ...options, plugins: [mockPlugin] }, + [mockPlugin], + async (client, logger, testPlatform) => { + expect(testPlatform.userAgent).toBeDefined(); + expect(testPlatform.version).toBeDefined(); + // Verify getHooks was called with correct environmentMetadata + expect(mockPlugin.getHooks).toHaveBeenCalledWith({ + sdk: { + name: testPlatform.userAgent, + version: testPlatform.version, + wrapperName: options.wrapperName, + wrapperVersion: options.wrapperVersion, + }, + application: { + id: options.application.id, + version: options.application.version, + }, + clientSideId: 'env', + }); + + // Verify register was called with correct environmentMetadata + expect(mockPlugin.register).toHaveBeenCalledWith( + expect.any(Object), // client + { + sdk: { + name: testPlatform.userAgent, + version: testPlatform.version, + wrapperName: options.wrapperName, + wrapperVersion: options.wrapperVersion, + }, + application: { + id: options.application.id, + version: options.application.version, + }, + clientSideId: 'env', + } + ); + } + ); +}); + +it('passes correct environmentMetadata without optional fields', async () => { + const mockPlugin = createTestPlugin('test-plugin'); + + await withClient( + { key: 'user-key', kind: 'user' }, + { plugins: [mockPlugin] }, + [mockPlugin], + async (client, logger, testPlatform) => { + expect(testPlatform.userAgent).toBeDefined(); + expect(testPlatform.version).toBeDefined(); + // Verify getHooks was called with correct environmentMetadata + expect(mockPlugin.getHooks).toHaveBeenCalledWith({ + sdk: { + name: testPlatform.userAgent, + version: testPlatform.version, + }, + clientSideId: 'env', + }); + + // Verify register was called with correct environmentMetadata + expect(mockPlugin.register).toHaveBeenCalledWith( + expect.any(Object), // client + { + sdk: { + name: testPlatform.userAgent, + version: testPlatform.version, + }, + clientSideId: 'env', + } + ); + } + ); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-streaming-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-streaming-test.js new file mode 100644 index 00000000..b9151dee --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-streaming-test.js @@ -0,0 +1,716 @@ +import * as messages from '../messages'; +import * as utils from '../utils'; + +import { AsyncQueue, eventSink, sleepAsync, withCloseable } from 'launchdarkly-js-test-helpers'; + +import EventSource from './EventSource-mock'; +import { respondJson } from './mockHttp'; +import * as stubPlatform from './stubPlatform'; +import { makeBootstrap } from './testUtils'; + +// These tests verify the client's optional streaming behavior. The actual implementation of +// the SSE client is provided by the platform-specific SDKs (e.g. the browser SDK uses +// EventSource, other SDKs use the js-eventsource polyfill) so these tests use only a mock +// implementation, verifying that the SDK interacts properly with the stream abstraction. + +describe('LDClient streaming', () => { + const defaultStreamBaseUrl = 'https://clientstream.launchdarkly.com'; + const envName = 'UNKNOWN_ENVIRONMENT_ID'; + const lsKey = 'ld:UNKNOWN_ENVIRONMENT_ID:' + utils.btoa('{"key":"user"}'); + const user = { key: 'user' }; + const encodedUser = 'eyJrZXkiOiJ1c2VyIn0'; + const hash = '012345789abcde'; + let platform; + + beforeEach(() => { + platform = stubPlatform.defaults(); + }); + + async function withClientAndServer(extraConfig, asyncCallback) { + const server = platform.testing.http.newServer(); + server.byDefault(respondJson({})); + const config = { ...extraConfig, baseUrl: server.url }; + const client = platform.testing.makeClient(envName, user, config); + return await withCloseable(client, async () => await asyncCallback(client, server)); + } + + function makeExpectedStreamUrl(base64User, userHash, withReasons) { + const baseUrl = defaultStreamBaseUrl + '/eval/' + envName + '/' + base64User; + const queryParams = []; + if (userHash) { + queryParams.push('h=' + userHash); + } + if (withReasons) { + queryParams.push('?withReasons=true'); + } + return baseUrl + (queryParams.length ? '?' + queryParams.join('&') : ''); + } + + describe('streaming/event listening', () => { + const fullStreamUrlWithUser = makeExpectedStreamUrl(encodedUser); + + async function expectStreamConnecting(url) { + const stream = await platform.testing.expectStream(url); + expect(stream.eventSource.readyState === EventSource.CONNECTING); + return stream; + } + + function expectNoStreamIsOpen() { + expect(platform.testing.eventSourcesCreated.length()).toEqual(0); + } + + it('does not connect to the stream by default', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + + expectNoStreamIsOpen(); + }); + }); + + it('connects to the stream if options.streaming is true', async () => { + await withClientAndServer({ streaming: true }, async client => { + await client.waitForInitialization(5); + + await platform.testing.expectStream(fullStreamUrlWithUser); + }); + }); + + describe('setStreaming()', () => { + it('can connect to the stream', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + + client.setStreaming(true); + await expectStreamConnecting(fullStreamUrlWithUser); + }); + }); + + it('can disconnect from the stream', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + + client.setStreaming(true); + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + client.setStreaming(false); + expect(stream.eventSource.readyState === EventSource.CLOSED); + }); + }); + }); + + describe('on("change")', () => { + it('connects to the stream if not otherwise overridden', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + client.on('change', () => {}); + + await expectStreamConnecting(fullStreamUrlWithUser); + }); + }); + + it('also connects if listening for a specific flag', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + client.on('change:flagkey', () => {}); + + await expectStreamConnecting(fullStreamUrlWithUser); + }); + }); + + it('does not connect if some other kind of event was specified', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + client.on('error', () => {}); + + expectNoStreamIsOpen(); + }); + }); + + it('does not connect if options.streaming is explicitly set to false', async () => { + await withClientAndServer({ streaming: false }, async client => { + await client.waitForInitialization(5); + client.on('change', () => {}); + + expectNoStreamIsOpen(); + }); + }); + + it('does not connect if setStreaming(false) was called', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + client.setStreaming(false); + client.on('change', () => {}); + + expectNoStreamIsOpen(); + }); + }); + }); + + describe('off("change")', () => { + it('disconnects from the stream if all event listeners are removed', async () => { + await withClientAndServer({}, async client => { + const listener1 = () => {}; + const listener2 = () => {}; + await client.waitForInitialization(5); + + client.on('change', listener1); + client.on('change:flagKey', listener2); + client.on('error', () => {}); + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + + client.off('change', listener1); + expect(stream.eventSource.readyState).toEqual(EventSource.CONNECTING); + + client.off('change:flagKey', listener2); + expect(stream.eventSource.readyState).toEqual(EventSource.CLOSED); + }); + }); + + it('does not disconnect if setStreaming(true) was called, but still removes event listener', async () => { + const changes1 = []; + const changes2 = []; + + await withClientAndServer({}, async client => { + const listener1 = allValues => changes1.push(allValues); + const listener2 = newValue => changes2.push(newValue); + await client.waitForInitialization(5); + + client.setStreaming(true); + + client.on('change', listener1); + client.on('change:flagKey', listener2); + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + + stream.eventSource.mockEmit('put', { + data: '{"flagKey":{"value":"a","version":1}}', + }); + + expect(changes1).toEqual([{ flagKey: { current: 'a', previous: undefined } }]); + expect(changes2).toEqual(['a']); + + client.off('change', listener1); + expect(stream.eventSource.readyState).toEqual(EventSource.CONNECTING); + + stream.eventSource.mockEmit('put', { + data: '{"flagKey":{"value":"b","version":1}}', + }); + + expect(changes1).toEqual([{ flagKey: { current: 'a', previous: undefined } }]); + expect(changes2).toEqual(['a', 'b']); + + client.off('change:flagKey', listener2); + expect(stream.eventSource.readyState).toEqual(EventSource.CONNECTING); + + stream.eventSource.mockEmit('put', { + data: '{"flagKey":{"value":"c","version":1}}', + }); + + expect(changes1).toEqual([{ flagKey: { current: 'a', previous: undefined } }]); + expect(changes2).toEqual(['a', 'b']); + }); + }); + }); + + it('passes the secure mode hash in the stream URL if provided', async () => { + await withClientAndServer({ hash }, async client => { + await client.waitForInitialization(5); + client.on('change:flagKey', () => {}); + + await expectStreamConnecting(fullStreamUrlWithUser + '?h=' + hash); + }); + }); + + it('passes withReasons parameter if provided', async () => { + await withClientAndServer({ evaluationReasons: true }, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + await expectStreamConnecting(fullStreamUrlWithUser + '?withReasons=true'); + }); + }); + + it('passes secure mode hash and withReasons if provided', async () => { + await withClientAndServer({ hash, evaluationReasons: true }, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + await expectStreamConnecting(fullStreamUrlWithUser + '?h=' + hash + '&withReasons=true'); + }); + }); + + it('handles stream ping message by getting flags', async () => { + await withClientAndServer({}, async (client, server) => { + server.byDefault(respondJson({ flagKey: { value: true, version: 1 } })); + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('ping'); + await sleepAsync(20); // give response handler a chance to execute + + expect(client.variation('flagKey')).toEqual(true); + }); + }); + + it("poll request triggered by stream ping can't overwrite another user's flags", async () => { + const otherUser = { key: 'otherUser' }; + const initUserBase64 = utils.base64URLEncode(JSON.stringify(user)); + const otherUserBase64 = utils.base64URLEncode(JSON.stringify(otherUser)); + + await withClientAndServer({}, async (client, server) => { + const reqRespQueue = new AsyncQueue(); + server.byDefault((req, resp) => { + reqRespQueue.add({ req: req, resp: resp }); + }); + + const initPromise = client.waitForInitialization(5); + const poll1 = await reqRespQueue.take(); + expect(poll1.req.path).toContain(initUserBase64); + respondJson({ flagKey: { value: 1 } })(poll1.req, poll1.resp); + await initPromise; + + // The flag value is now 1, from the initial poll + expect(client.variation('flagKey')).toEqual(1); + + client.setStreaming(true); + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + + stream.eventSource.mockEmit('ping'); + const poll2 = await reqRespQueue.take(); + // poll2 is the poll request that was triggered by the ping; don't respond to it yet + expect(poll2.req.path).toContain(initUserBase64); + + const identifyPromise = client.identify(otherUser); + const poll3 = await reqRespQueue.take(); + // poll3 is the poll request for the identify + expect(poll3.req.path).toContain(otherUserBase64); + + // Now let's say poll3 completes first, setting the flag value to 3 for the new user + respondJson({ flagKey: { value: 3 } })(poll3.req, poll3.resp); + + // And then poll2, which was for the previous user, completes with a flag value of 2 + respondJson({ flagKey: { value: 2 } })(poll2.req, poll2.resp); + + await identifyPromise; + + // The flag value should now be 3, not 2 + expect(client.variation('flagKey')).toEqual(3); + }); + }); + + it('handles stream put message by updating flags', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('put', { + data: '{"flagKey":{"value":true,"version":1}}', + }); + + expect(client.variation('flagKey')).toEqual(true); + }); + }); + + it('updates local storage for put message if using local storage', async () => { + platform.testing.setLocalStorageImmediately(lsKey, '{"flagKey":false}'); + + await withClientAndServer({ bootstrap: 'localstorage' }, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('put', { + data: '{"flagKey":{"value":true,"version":1}}', + }); + + expect(client.variation('flagKey')).toEqual(true); + const storageData = JSON.parse(platform.testing.getLocalStorageImmediately(lsKey)); + expect(storageData).toMatchObject({ flagKey: { value: true, version: 1 } }); + }); + }); + + it('fires global change event when flags are updated from put event', async () => { + await withClientAndServer({ bootstrap: { flagKey: false } }, async client => { + await client.waitForInitialization(5); + + const receivedChange = eventSink(client, 'change'); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('put', { + data: '{"flagKey":{"value":true,"version":1}}', + }); + + const changes = await receivedChange.take(); + expect(changes).toEqual({ + flagKey: { current: true, previous: false }, + }); + }); + }); + + it('does not fire change event if new and old values are equivalent JSON objects', async () => { + const config = { + bootstrap: { + 'will-change': 3, + 'wont-change': { a: 1, b: 2 }, + }, + }; + await withClientAndServer(config, async client => { + await client.waitForInitialization(5); + + const receivedChange = eventSink(client, 'change'); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + const putData = { + 'will-change': { value: 4, version: 2 }, + 'wont-change': { value: { b: 2, a: 1 }, version: 2 }, + }; + stream.eventSource.mockEmit('put', { data: JSON.stringify(putData) }); + + const changes = await receivedChange.take(); + expect(changes).toEqual({ + 'will-change': { current: 4, previous: 3 }, + }); + }); + }); + + it('fires individual change event when flags are updated from put event', async () => { + await withClientAndServer({ bootstrap: { flagKey: false } }, async client => { + await client.waitForInitialization(5); + + const receivedChange = eventSink(client, 'change:flagKey'); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('put', { + data: '{"flagKey":{"value":true,"version":1}}', + }); + + const args = await receivedChange.take(); + expect(args).toEqual([true, false]); + }); + }); + + it('handles patch message by updating flag', async () => { + await withClientAndServer({ bootstrap: { flagKey: false } }, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('patch', { data: '{"key":"flagKey","value":true,"version":1}' }); + + expect(client.variation('flagKey')).toEqual(true); + }); + }); + + it('does not update flag if patch version < flag version', async () => { + const initData = makeBootstrap({ flagKey: { value: 'a', version: 2 } }); + await withClientAndServer({ bootstrap: initData }, async client => { + await client.waitForInitialization(5); + + expect(client.variation('flagKey')).toEqual('a'); + + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('patch', { data: '{"key":"flagKey","value":"b","version":1}' }); + + expect(client.variation('flagKey')).toEqual('a'); + }); + }); + + it('does not update flag if patch version == flag version', async () => { + const initData = makeBootstrap({ flagKey: { value: 'a', version: 2 } }); + await withClientAndServer({ bootstrap: initData }, async client => { + await client.waitForInitialization(5); + + expect(client.variation('flagKey')).toEqual('a'); + + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('patch', { data: '{"key":"flagKey","value":"b","version":2}' }); + + expect(client.variation('flagKey')).toEqual('a'); + }); + }); + + it('updates flag if patch has a version and flag has no version', async () => { + const initData = makeBootstrap({ flagKey: { value: 'a' } }); + await withClientAndServer({ bootstrap: initData }, async client => { + await client.waitForInitialization(5); + + expect(client.variation('flagKey')).toEqual('a'); + + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('patch', { data: '{"key":"flagKey","value":"b","version":1}' }); + + expect(client.variation('flagKey')).toEqual('b'); + }); + }); + + it('updates flag if flag has a version and patch has no version', async () => { + const initData = makeBootstrap({ flagKey: { value: 'a', version: 2 } }); + await withClientAndServer({ bootstrap: initData }, async client => { + await client.waitForInitialization(5); + + expect(client.variation('flagKey')).toEqual('a'); + + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('patch', { data: '{"key":"flagKey","value":"b"}' }); + + expect(client.variation('flagKey')).toEqual('b'); + }); + }); + + it('updates local storage for patch message if using local storage', async () => { + platform.testing.setLocalStorageImmediately(lsKey, '{"flagKey":false}'); + + await withClientAndServer({ bootstrap: 'localstorage' }, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('put', { + data: '{"flagKey":{"value":true,"version":1}}', + }); + + expect(client.variation('flagKey')).toEqual(true); + const storageData = JSON.parse(platform.testing.getLocalStorageImmediately(lsKey)); + expect(storageData).toMatchObject({ flagKey: { value: true, version: 1 } }); + }); + }); + + it('fires global change event when flag is updated from patch event', async () => { + await withClientAndServer({ bootstrap: { flagKey: false } }, async client => { + await client.waitForInitialization(5); + + const receivedChange = eventSink(client, 'change'); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('patch', { + data: '{"key":"flagKey","value":true,"version":1}', + }); + + const changes = await receivedChange.take(); + expect(changes).toEqual({ + flagKey: { current: true, previous: false }, + }); + }); + }); + + it('fires individual change event when flag is updated from patch event', async () => { + await withClientAndServer({ bootstrap: { flagKey: false } }, async client => { + await client.waitForInitialization(5); + + const receivedChange = eventSink(client, 'change:flagKey'); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('patch', { + data: '{"key":"flagKey","value":true,"version":1}', + }); + + const args = await receivedChange.take(); + expect(args).toEqual([true, false]); + }); + }); + + it('fires global change event when flag is newly created from patch event', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + + const receivedChange = eventSink(client, 'change'); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('patch', { + data: '{"key":"flagKey","value":true,"version":1}', + }); + + const changes = await receivedChange.take(); + expect(changes).toEqual({ + flagKey: { current: true }, + }); + }); + }); + + it('fires individual change event when flag is newly created from patch event', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + + const receivedChange = eventSink(client, 'change:flagKey'); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('patch', { + data: '{"key":"flagKey","value":true,"version":1}', + }); + + const args = await receivedChange.take(); + expect(args).toEqual([true, undefined]); + }); + }); + + it('handles delete message by deleting flag', async () => { + await withClientAndServer({ bootstrap: { flagKey: false } }, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('delete', { + data: '{"key":"flagKey","version":1}', + }); + + expect(client.variation('flagKey')).toBeUndefined(); + }); + }); + + it('handles delete message for unknown flag by storing placeholder', async () => { + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('delete', { + data: '{"key":"mystery","version":3}', + }); + + // The following patch message should be ignored because it has a lower version than the deleted placeholder + stream.eventSource.mockEmit('patch', { + data: '{"key":"mystery","value":"yes","version":2}', + }); + + expect(client.variation('mystery')).toBeUndefined(); + }); + }); + + it('ignores delete message with lower version', async () => { + const initData = makeBootstrap({ flagKey: { value: 'yes', version: 3 } }); + await withClientAndServer({ bootstrap: initData }, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('delete', { + data: '{"key":"flagKey","version":2}', + }); + + expect(client.variation('flagKey')).toEqual('yes'); + }); + }); + + it('fires global change event when flag is deleted', async () => { + await withClientAndServer({ bootstrap: { flagKey: true } }, async client => { + await client.waitForInitialization(5); + + const receivedChange = eventSink(client, 'change'); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('delete', { + data: '{"key":"flagKey","version":1}', + }); + + const changes = await receivedChange.take(); + expect(changes).toEqual({ + flagKey: { previous: true }, + }); + }); + }); + + it('fires individual change event when flag is deleted', async () => { + await withClientAndServer({ bootstrap: { flagKey: true } }, async client => { + await client.waitForInitialization(5); + + const receivedChange = eventSink(client, 'change:flagKey'); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('delete', { + data: '{"key":"flagKey","version":1}', + }); + + const args = await receivedChange.take(); + expect(args).toEqual([undefined, true]); + }); + }); + + it('updates local storage for delete message if using local storage', async () => { + platform.testing.setLocalStorageImmediately(lsKey, '{"flagKey":false}'); + + await withClientAndServer({ bootstrap: 'localstorage' }, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit('delete', { + data: '{"key":"flagKey","version":1}', + }); + + expect(client.variation('flagKey')).toEqual(undefined); + const storageData = JSON.parse(platform.testing.getLocalStorageImmediately(lsKey)); + expect(storageData).toMatchObject({ flagKey: { version: 1, deleted: true } }); + }); + }); + + describe('emits error if malformed JSON is received', () => { + const doMalformedJsonEventTest = async (eventName, eventData) => { + // First, verify that there isn't an unhandled rejection if we're not listening for an error + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit(eventName, { data: eventData }); + }); + + // Then, repeat the test using a listener to observe the error event + await withClientAndServer({}, async client => { + const errorEvents = new AsyncQueue(); + client.on('error', e => errorEvents.add(e)); + + await client.waitForInitialization(5); + client.setStreaming(true); + + const stream = await expectStreamConnecting(fullStreamUrlWithUser); + stream.eventSource.mockEmit(eventName, { data: eventData }); + + const e = await errorEvents.take(); + expect(e.message).toEqual(messages.invalidData()); + }); + }; + + it('in put event', async () => doMalformedJsonEventTest('put', '{no')); + it('in patch event', async () => doMalformedJsonEventTest('patch', '{no')); + it('in delete event', async () => doMalformedJsonEventTest('delete', '{no')); + }); + + it('reconnects to stream if the user changes', async () => { + const user2 = { key: 'user2' }; + const encodedUser2 = 'eyJrZXkiOiJ1c2VyMiJ9'; + await withClientAndServer({}, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + await expectStreamConnecting(makeExpectedStreamUrl(encodedUser)); + + await client.identify(user2); + await expectStreamConnecting(makeExpectedStreamUrl(encodedUser2)); + }); + }); + + it('reconnects to stream with new hash value in secure mode if the user changes', async () => { + const newUser = { key: 'user2' }; + const newEncodedUser = 'eyJrZXkiOiJ1c2VyMiJ9'; + const newHash = hash + 'xxx'; + + await withClientAndServer({ hash }, async client => { + await client.waitForInitialization(5); + client.setStreaming(true); + + await expectStreamConnecting(makeExpectedStreamUrl(encodedUser, hash)); + + await client.identify(newUser, newHash); + await expectStreamConnecting(makeExpectedStreamUrl(newEncodedUser, newHash)); + }); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-test.js new file mode 100644 index 00000000..e3f74fbc --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-test.js @@ -0,0 +1,758 @@ +import * as LDClient from '../index'; +import * as messages from '../messages'; +import * as utils from '../utils'; + +import { eventSink, promisifySingle, sleepAsync, withCloseable, AsyncQueue } from 'launchdarkly-js-test-helpers'; + +import { respond, respondJson } from './mockHttp'; +import * as stubPlatform from './stubPlatform'; +import { makeBootstrap, numericUser, stringifiedNumericUser } from './testUtils'; + +describe('LDClient', () => { + const envName = 'UNKNOWN_ENVIRONMENT_ID'; + const user = { key: 'user' }; + let platform; + + beforeEach(() => { + platform = stubPlatform.defaults(); + }); + + async function withServers(asyncCallback) { + const pollServer = platform.testing.http.newServer(); + const eventsServer = platform.testing.http.newServer(); + pollServer.byDefault(respondJson({})); + eventsServer.byDefault(respond(202)); + const baseConfig = { baseUrl: pollServer.url, eventsUrl: eventsServer.url }; + return await asyncCallback(baseConfig, pollServer, eventsServer); + } + + async function withClient(user, extraConfig, asyncCallback) { + const client = platform.testing.makeClient(envName, user, { diagnosticOptOut: true, ...extraConfig }); + return await withCloseable(client, asyncCallback); + } + + async function withDiagnosticsEnabledClient(user, extraConfig, asyncCallback) { + const client = platform.testing.makeClient(envName, user, { ...extraConfig }); + return await withCloseable(client, asyncCallback); + } + + it('should exist', () => { + expect(LDClient).toBeDefined(); + }); + + describe('initialization', () => { + it('triggers "ready" event', async () => { + await withServers(async baseConfig => { + await withClient(user, baseConfig, async client => { + const gotReady = eventSink(client, 'ready'); + await gotReady.take(); + + expect(platform.testing.logger.output.info).toEqual([messages.clientInitialized()]); + }); + }); + }); + + it('triggers "initialized" event', async () => { + await withServers(async baseConfig => { + await withClient(user, baseConfig, async client => { + const gotInited = eventSink(client, 'initialized'); + await gotInited.take(); + }); + }); + }); + + it('resolves waitForInitialization promise', async () => { + await withServers(async baseConfig => { + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + }); + }); + }); + + it('resolves waitUntilReady promise', async () => { + await withServers(async baseConfig => { + await withClient(user, baseConfig, async client => { + await client.waitUntilReady(); + }); + }); + }); + + it('fetches flag settings if bootstrap is not provided (without reasons)', async () => { + const flags = { flagKey: { value: true } }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags)); + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + const req = await pollServer.nextRequest(); + expect(req.path).toMatch(/sdk\/eval/); + expect(req.path).not.toMatch(/withReasons=true/); + }); + }); + }); + + it('fetches flag settings if bootstrap is not provided (with reasons)', async () => { + const flags = { flagKey: { value: true, variation: 1, reason: { kind: 'OFF' } } }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags)); + await withClient(user, { ...baseConfig, evaluationReasons: true }, async client => { + await client.waitForInitialization(5); + + const req = await pollServer.nextRequest(); + expect(req.path).toMatch(/sdk\/eval/); + expect(req.path).toMatch(/withReasons=true/); + }); + }); + }); + + async function verifyCustomHeader(sendLDHeaders, shouldGetHeaders) { + await withServers(async (baseConfig, pollServer) => { + await withClient(user, { ...baseConfig, sendLDHeaders }, async client => { + await client.waitForInitialization(5); + const request = await pollServer.nextRequest(); + expect(request.headers['user-agent']).toEqual( + shouldGetHeaders ? utils.getLDUserAgentString(platform) : undefined + ); + }); + }); + } + + it('sends custom header by default', () => verifyCustomHeader(undefined, true)); + + it('sends custom header if sendLDHeaders is true', () => verifyCustomHeader(true, true)); + + it('does not send custom header if sendLDHeaders is false', () => verifyCustomHeader(undefined, true)); + + it('sanitizes the user', async () => { + await withServers(async baseConfig => { + await withClient(numericUser, baseConfig, async client => { + await client.waitForInitialization(5); + expect(client.getContext()).toEqual(stringifiedNumericUser); + }); + }); + }); + + it('provides a persistent key for an anonymous user with no key', async () => { + const anonUser = { anonymous: true, country: 'US' }; + await withServers(async baseConfig => { + let generatedUser; + await withClient(anonUser, baseConfig, async client0 => { + await client0.waitForInitialization(5); + + generatedUser = client0.getContext(); + expect(generatedUser.key).toEqual(expect.anything()); + expect(generatedUser).toMatchObject(anonUser); + }); + await withClient(anonUser, baseConfig, async client1 => { + await client1.waitForInitialization(5); + + const newUser1 = client1.getContext(); + expect(newUser1).toEqual(generatedUser); + }); + }); + }); + + it('provides a key for an anonymous user with no key, even if local storage is unavailable', async () => { + platform.localStorage = null; + const anonUser = { anonymous: true, country: 'US' }; + + await withServers(async baseConfig => { + let generatedUser; + await withClient(anonUser, baseConfig, async client0 => { + await client0.waitForInitialization(5); + + generatedUser = client0.getContext(); + expect(generatedUser.key).toEqual(expect.anything()); + expect(generatedUser).toMatchObject(anonUser); + }); + await sleepAsync(100); // so that the time-based UUID algorithm will produce a different result below + await withClient(anonUser, baseConfig, async client1 => { + await client1.waitForInitialization(5); + + const newUser1 = client1.getContext(); + expect(newUser1.key).toEqual(expect.anything()); + expect(newUser1.key).not.toEqual(generatedUser.key); + expect(newUser1).toMatchObject(anonUser); + }); + }); + }); + }); + + describe('failed initialization', () => { + function doErrorTests(expectedMessage, doWithClientAsyncFn) { + async function runTest(asyncTest) { + try { + await doWithClientAsyncFn(asyncTest); + } finally { + // sleep briefly so any unhandled promise rejections will show up in this test, instead of + // in a later test + await sleepAsync(2); + } + } + + it('rejects waitForInitialization promise', async () => { + await runTest(async client => { + await expect(client.waitForInitialization(5)).rejects.toThrow(); + }); + }); + + it('resolves waitUntilReady promise', async () => { + await runTest(async client => { + await client.waitUntilReady(); + }); + }); + + it('emits "error" event', async () => { + await runTest(async client => { + const gotError = eventSink(client, 'error'); + const err = await gotError.take(); + expect(err.message).toEqual(expectedMessage); + }); + }); + + it('emits "failed" event', async () => { + await runTest(async client => { + const gotFailed = eventSink(client, 'failed'); + const err = await gotFailed.take(); + expect(err.message).toEqual(expectedMessage); + }); + }); + + it('emits "ready" event', async () => { + await runTest(async client => { + const gotReady = eventSink(client, 'ready'); + await gotReady.take(); + }); + }); + + it('returns default values', async () => { + await runTest(async client => { + await client.waitUntilReady(); + expect(client.variation('flag-key', 1)).toEqual(1); + }); + }); + } + + describe('environment key not specified', () => { + doErrorTests( + messages.environmentNotSpecified(), + async callback => await withCloseable(platform.testing.makeClient('', user), callback) + ); + }); + + describe('invalid environment key (404 error)', () => { + doErrorTests(messages.environmentNotFound(), async callback => { + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respond(404)); + await withClient(user, baseConfig, callback); + }); + }); + }); + + describe('HTTP error other than 404 on initial poll', () => { + doErrorTests(messages.errorFetchingFlags(503), async callback => { + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respond(503)); + await withClient(user, baseConfig, callback); + }); + }); + }); + }); + + describe('initialization with bootstrap object', () => { + it('should not fetch flag settings', async () => { + await withServers(async (baseConfig, pollServer) => { + await withClient(user, { ...baseConfig, bootstrap: {} }, async client => { + await client.waitForInitialization(5); + + expect(pollServer.requests.length()).toEqual(0); + }); + }); + }); + + it('makes flags available immediately before ready event', async () => { + await withServers(async baseConfig => { + const initData = makeBootstrap({ foo: { value: 'bar', version: 1 } }); + await withClient(user, { ...baseConfig, bootstrap: initData }, async client => { + expect(client.variation('foo')).toEqual('bar'); + }); + }); + }); + + it('logs warning when bootstrap object uses old format', async () => { + const initData = { foo: 'bar' }; + await withClient(user, { bootstrap: initData, sendEvents: false }, async client => { + await client.waitForInitialization(5); + + expect(platform.testing.logger.output.warn).toEqual([messages.bootstrapOldFormat()]); + }); + }); + + it('does not log warning when bootstrap object uses new format', async () => { + const initData = makeBootstrap({ foo: { value: 'bar', version: 1 } }); + await withClient(user, { bootstrap: initData, sendEvents: false }, async client => { + await client.waitForInitialization(5); + + expect(platform.testing.logger.output.warn).toEqual([]); + expect(client.variation('foo')).toEqual('bar'); + }); + }); + }); + + describe('variation', () => { + it('returns value for an existing flag - from bootstrap', async () => { + const config = { + bootstrap: makeBootstrap({ foo: { value: 'bar', version: 1 } }), + sendEvents: false, + }; + await withClient(user, config, async client => { + await client.waitForInitialization(5); + + expect(client.variation('foo')).toEqual('bar'); + }); + }); + + it('returns value for an existing flag - from bootstrap with old format', async () => { + const config = { + bootstrap: makeBootstrap({ foo: { value: 'bar', version: 1 } }), + sendEvents: false, + }; + await withClient(user, config, async client => { + await client.waitForInitialization(5); + + expect(client.variation('foo')).toEqual('bar'); + }); + }); + + it('returns value for an existing flag - from polling', async () => { + const flags = { 'enable-foo': { value: true, version: 1, variation: 2 } }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags)); + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + expect(client.variation('enable-foo', 1)).toEqual(true); + }); + }); + }); + + it('returns default value for flag that had null value', async () => { + const flags = { 'enable-foo': { value: null, version: 1, variation: 2 } }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags)); + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + expect(client.variation('foo', 'default')).toEqual('default'); + }); + }); + }); + + it('returns default value for unknown flag', async () => { + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson({})); + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + expect(client.variation('foo', 'default')).toEqual('default'); + }); + }); + }); + }); + + describe('variationDetail', () => { + const reason = { kind: 'FALLTHROUGH' }; + it('returns details for an existing flag - from bootstrap', async () => { + const config = { + bootstrap: makeBootstrap({ foo: { value: 'bar', version: 1, variation: 2, reason: reason } }), + }; + await withClient(user, config, async client => { + await client.waitForInitialization(5); + + expect(client.variationDetail('foo')).toEqual({ value: 'bar', variationIndex: 2, reason: reason }); + }); + }); + + it('returns details for an existing flag - from bootstrap with old format', async () => { + const config = { bootstrap: { foo: 'bar' } }; + await withClient(user, config, async client => { + await client.waitForInitialization(5); + + expect(client.variationDetail('foo')).toEqual({ value: 'bar', variationIndex: null, reason: null }); + }); + }); + + it('returns details for an existing flag - from polling', async () => { + const flags = { foo: { value: 'bar', version: 1, variation: 2, reason: reason } }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags)); + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + expect(client.variationDetail('foo', 'default')).toEqual({ value: 'bar', variationIndex: 2, reason: reason }); + }); + }); + }); + + it('returns default value for flag that had null value', async () => { + const flags = { foo: { value: null, version: 1 } }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags)); + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + expect(client.variationDetail('foo', 'default')).toEqual({ + value: 'default', + variationIndex: null, + reason: null, + }); + }); + }); + }); + + it('returns default value and error for unknown flag', async () => { + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson({})); + await withClient(user, baseConfig, async client => { + expect(client.variationDetail('foo', 'default')).toEqual({ + value: 'default', + variationIndex: null, + reason: { kind: 'ERROR', errorKind: 'FLAG_NOT_FOUND' }, + }); + }); + }); + }); + }); + + describe('allFlags', () => { + it('returns flag values', async () => { + const flags = { key1: { value: 'value1' }, key2: { value: 'value2' } }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags)); + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + expect(client.allFlags()).toEqual({ key1: 'value1', key2: 'value2' }); + }); + }); + }); + + it('returns empty map if client is not initialized', async () => { + const flags = { key1: { value: 'value1' }, key2: { value: 'value2' } }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags)); + await withClient(user, baseConfig, async client => { + expect(client.allFlags()).toEqual({}); + }); + }); + }); + }); + + describe('identify', () => { + it('does not set user until the flag config has been updated', async () => { + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson({})); + await withClient(user, baseConfig, async client => { + const signal = new AsyncQueue(); + const user2 = { key: 'user2' }; + await client.waitForInitialization(5); + + // Make the server wait until signaled to return the next response + pollServer.byDefault((req, res) => { + signal.take().then(() => { + respondJson({})(req, res); + }); + }); + + const identifyPromise = client.identify(user2); + await sleepAsync(100); // sleep to jump some async ticks + expect(client.getContext()).toEqual(user); + + signal.add(); + await identifyPromise; + + expect(client.getContext()).toEqual(user2); + }); + }); + }); + + it('updates flag values when the user changes', async () => { + const flags0 = { 'enable-foo': { value: false } }; + const flags1 = { 'enable-foo': { value: true } }; + const user1 = { key: 'user1' }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags0)); + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + expect(client.variation('enable-foo')).toBe(false); + + pollServer.byDefault(respondJson(flags1)); + + const newFlagsMap = await client.identify(user1); + + expect(client.variation('enable-foo')).toBe(true); + + expect(newFlagsMap).toEqual({ 'enable-foo': true }); + }); + }); + }); + + it.each([ + { country: 'US' }, // Legacy user with no key, and not anonymous. + { kind: 'user' }, // A single kind that is not anonymous and has no key. + { kind: 'multi', app: { anonymous: true }, org: {}, user: { key: 'yes' } }, // Multi kind with 1 non-anonymous context without a key. + ])('returns an error and does not update flags when identify is called with invalid contexts', async badContext => { + const flags0 = { 'enable-foo': { value: false } }; + const flags1 = { 'enable-foo': { value: true } }; + await withServers(async (baseConfig, pollServer) => { + pollServer.byDefault(respondJson(flags0)); + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + expect(client.variation('enable-foo')).toBe(false); + expect(pollServer.requests.length()).toEqual(1); + + pollServer.byDefault(respondJson(flags1)); + + await expect(client.identify(null)).rejects.toThrow(); + + expect(client.variation('enable-foo')).toBe(false); + expect(pollServer.requests.length()).toEqual(1); + + await expect(client.identify(badContext)).rejects.toThrow(); + + expect(client.variation('enable-foo')).toBe(false); + expect(pollServer.requests.length()).toEqual(1); + }); + }); + }); + + it('provides a persistent key for an anonymous user with no key', async () => { + await withServers(async baseConfig => { + await withClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + + const anonUser = { anonymous: true, country: 'US' }; + await client.identify(anonUser); + + const newUser = client.getContext(); + expect(newUser.key).toEqual(expect.anything()); + expect(newUser).toMatchObject(anonUser); + }); + }); + }); + }); + + describe('initializing with stateProvider', () => { + it('immediately uses initial state if available, and does not make an HTTP request', async () => { + const user = { key: 'user' }; + const state = { + environment: 'env', + context: user, + flags: { flagkey: { value: 'value' } }, + }; + const sp = stubPlatform.mockStateProvider(state); + + await withServers(async (baseConfig, pollServer) => { + await withClient(null, { ...baseConfig, stateProvider: sp }, async client => { + await client.waitForInitialization(5); + + expect(client.variation('flagkey')).toEqual('value'); + expect(pollServer.requests.length()).toEqual(0); + }); + }); + }); + + it('defers initialization if initial state not available, and does not make an HTTP request', async () => { + const sp = stubPlatform.mockStateProvider(null); + + await withServers(async (baseConfig, pollServer) => { + await withClient(null, { ...baseConfig, stateProvider: sp }, async () => { + expect(pollServer.requests.length()).toEqual(0); + }); + }); + }); + + it('finishes initialization on receiving init event', async () => { + const user = { key: 'user' }; + const state = { + environment: 'env', + context: user, + flags: { flagkey: { value: 'value' } }, + }; + const sp = stubPlatform.mockStateProvider(null); + + await withClient(null, { stateProvider: sp, sendEvents: false }, async client => { + sp.emit('init', state); + + await client.waitForInitialization(5); + expect(client.variation('flagkey')).toEqual('value'); + }); + }); + + it('updates flags on receiving update event', async () => { + const user = { key: 'user' }; + const state0 = { + environment: 'env', + context: user, + flags: { flagkey: { value: 'value0' } }, + }; + const sp = stubPlatform.mockStateProvider(state0); + + await withClient(null, { stateProvider: sp, sendEvents: false }, async client => { + await client.waitForInitialization(5); + + expect(client.variation('flagkey')).toEqual('value0'); + + const state1 = { + flags: { flagkey: { value: 'value1' } }, + }; + + const gotChange = eventSink(client, 'change:flagkey'); + + sp.emit('update', state1); + + const args = await gotChange.take(); + expect(args).toEqual(['value1', 'value0']); + }); + }); + + it('disables identify()', async () => { + const user = { key: 'user' }; + const user1 = { key: 'user1' }; + const state = { environment: 'env', context: user, flags: { flagkey: { value: 'value' } } }; + const sp = stubPlatform.mockStateProvider(state); + + await withServers(async (baseConfig, pollServer) => { + await withClient(null, { ...baseConfig, stateProvider: sp }, async client => { + sp.emit('init', state); + + await client.waitForInitialization(5); + const newFlags = await client.identify(user1); + + expect(newFlags).toEqual({ flagkey: 'value' }); + expect(pollServer.requests.length()).toEqual(0); + expect(platform.testing.logger.output.warn).toEqual([messages.identifyDisabled()]); + }); + }); + }); + + it('copies data from state provider to avoid unintentional object-sharing', async () => { + const user = { key: 'user' }; + const state = { + environment: 'env', + user: user, + flags: { flagkey: { value: 'value' } }, + }; + const sp = stubPlatform.mockStateProvider(null); + + await withClient(null, { stateProvider: sp, sendEvents: false }, async client => { + sp.emit('init', state); + + await client.waitForInitialization(5); + expect(client.variation('flagkey')).toEqual('value'); + + state.flags.flagkey = { value: 'secondValue' }; + expect(client.variation('flagkey')).toEqual('value'); + + sp.emit('update', state); + expect(client.variation('flagkey')).toEqual('secondValue'); + + state.flags.flagkey = { value: 'thirdValue' }; + expect(client.variation('flagkey')).toEqual('secondValue'); + }); + }); + }); + + describe('close()', () => { + it('flushes events', async () => { + await withServers(async (baseConfig, pollServer, eventsServer) => { + await withClient(user, { ...baseConfig, flushInterval: 100000 }, async client => { + await client.waitForInitialization(5); + }); + + // Flushing is an async operation, so we cannot ensure that the requests are made by + // the time we reach this point. If we await the nextRequest(), then it will catch + // whatever was flushed. + const req = await eventsServer.nextRequest(); + const data = JSON.parse(req.body); + expect(data.length).toEqual(1); + expect(data[0].kind).toEqual('identify'); + }); + }); + + it('does nothing if called twice', async () => { + await withServers(async (baseConfig, pollServer, eventsServer) => { + await withClient(user, { ...baseConfig, flushInterval: 100000 }, async client => { + await client.waitForInitialization(5); + + await client.close(); + + expect(eventsServer.requests.length()).toEqual(1); + + await client.close(); + + expect(eventsServer.requests.length()).toEqual(1); + }); + }); + }); + + it('is not rejected if flush fails', async () => { + await withServers(async (baseConfig, pollServer, eventsServer) => { + eventsServer.byDefault(respond(404)); + await withClient(user, { ...baseConfig, flushInterval: 100000 }, async client => { + await client.waitForInitialization(5); + + await client.close(); // shouldn't throw or have an unhandled rejection + }); + }); + }); + + it('can take a callback instead of returning a promise', async () => { + await withServers(async (baseConfig, pollServer, eventsServer) => { + await withClient(user, { ...baseConfig }, async client => { + await client.waitForInitialization(5); + + await promisifySingle(client.close)(); + + expect(eventsServer.requests.length()).toEqual(1); + }); + }); + }); + }); + + describe('diagnostic events', () => { + // Note, the default configuration provided by withClient() sets { diagnosticOptOut: true } so that the + // diagnostic events won't interfere with the rest of the tests in this file. In this test group, we will + // deliberately enable diagnostic events. The details of DiagnosticManager's behavior are covered by + // diagnosticEvents-test.js, so here we're just verifying that the client starts up the DiagnosticsManager + // and gives it the right eventsUrl. + + it('sends diagnostic init event if not opted out', async () => { + await withServers(async (baseConfig, pollServer, eventsServer) => { + await withDiagnosticsEnabledClient(user, baseConfig, async client => { + await client.waitForInitialization(5); + await client.flush(); + + // We can't be sure which will be posted first, the regular events or the diagnostic event + const requests = []; + const req1 = await eventsServer.requests.take(); + requests.push({ path: req1.path, data: JSON.parse(req1.body) }); + const req2 = await eventsServer.requests.take(); + requests.push({ path: req2.path, data: JSON.parse(req2.body) }); + + expect(requests).toContainEqual({ + path: '/events/bulk/' + envName, + data: expect.arrayContaining([expect.objectContaining({ kind: 'identify' })]), + }); + + expect(requests).toContainEqual({ + path: '/events/diagnostic/' + envName, + data: expect.objectContaining({ kind: 'diagnostic-init' }), + }); + }); + }); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-timeout-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-timeout-test.js new file mode 100644 index 00000000..0241ebb2 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/LDClient-timeout-test.js @@ -0,0 +1,90 @@ +jest.mock('../InitializationState', () => jest.fn()); + +import { initialize } from '../index'; +import InitializationState from '../InitializationState'; +import * as stubPlatform from './stubPlatform'; + +const createHangingPromise = () => + new Promise(() => { + // never resolves + }); + +describe('timeout', () => { + let ldc; + let mockGetInitializationPromise; + let mockGetReadyPromise; + let logger; + + beforeEach(() => { + mockGetInitializationPromise = jest.fn(); + mockGetReadyPromise = jest.fn(); + logger = stubPlatform.logger(); + InitializationState.mockImplementation(() => ({ + getInitializationPromise: mockGetInitializationPromise, + getReadyPromise: mockGetReadyPromise, + signalFailure: jest.fn(), + })); + mockGetInitializationPromise.mockImplementation(createHangingPromise); + mockGetReadyPromise.mockImplementation(createHangingPromise); + ({ client: ldc } = initialize( + 'abc', + { kind: 'user', key: 'test-user' }, + { + logger: logger, + }, + {} + )); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + it('waitForInitialization times out if initialization does not resolve', async () => { + const p = ldc.waitForInitialization(1); + await expect(p).rejects.toThrow(/timed out/); + + // No warnings in this configuration. + expect(logger.output.warn).toEqual([]); + expect(logger.output.error).toEqual([ + 'waitForInitialization error: LaunchDarklyTimeoutError: waitForInitialization timed out after 1 seconds.', + ]); + }); + + it('waitForInitialization warns if no timeout is provided', async () => { + ldc.waitForInitialization(); + + expect(logger.output.warn).toEqual([ + 'The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.', + ]); + }); + + it('waitForInitialization warns if timeout is not a number', async () => { + ldc.waitForInitialization('10'); + + // You get two warnings in this case. Which should be fine as you have to go our of your way to get into this situation. + expect(logger.output.warn).toEqual([ + 'The waitForInitialization method was provided with a non-numeric timeout.', + 'The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.', + ]); + }); + + it('waitForInitialization warns if timeout provided is too high', async () => { + ldc.waitForInitialization(10); + + expect(logger.output.warn).toEqual([ + 'The waitForInitialization function was called with a timeout greater than 5 seconds. We recommend a timeout of 5 seconds or less.', + ]); + }); + + it('waitForInitialization does not timeout if the initialization promise resolves in the timeout', async () => { + mockGetInitializationPromise.mockImplementation(() => Promise.resolve('success')); + + const p = ldc.waitForInitialization(5); + + await expect(p).resolves.toEqual('success'); + + // No warnings in this configuration. + expect(logger.output.warn).toEqual([]); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/MultiEventSummarizer-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/MultiEventSummarizer-test.js new file mode 100644 index 00000000..e52e8401 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/MultiEventSummarizer-test.js @@ -0,0 +1,148 @@ +const MultiEventSummarizer = require('../MultiEventSummarizer'); +const ContextFilter = require('../ContextFilter'); + +function makeEvent(key, version, variation, value, defaultVal, context) { + return { + kind: 'feature', + creationDate: 1000, + key: key, + version: version, + context: context, + variation: variation, + value: value, + default: defaultVal, + }; +} + +describe('given a multi-event summarizer and context filter', () => { + let summarizer; + let contextFilter; + + beforeEach(() => { + contextFilter = ContextFilter(false, []); + summarizer = MultiEventSummarizer(contextFilter); + }); + + it('creates new summarizer for new context hash', async () => { + const context = { kind: 'user', key: 'user1' }; + const event = { kind: 'feature', context }; + + summarizer.summarizeEvent(event); + + const summaries = await summarizer.getSummaries(); + expect(summaries).toHaveLength(1); + }); + + it('uses existing summarizer for same context hash', async () => { + const context = { kind: 'user', key: 'user1' }; + const event1 = { kind: 'feature', context, value: 'value1' }; + const event2 = { kind: 'feature', context, value: 'value2' }; + + summarizer.summarizeEvent(event1); + summarizer.summarizeEvent(event2); + + const summaries = await summarizer.getSummaries(); + expect(summaries).toHaveLength(1); + }); + + it('ignores non-feature events', async () => { + const context = { kind: 'user', key: 'user1' }; + const event = { kind: 'identify', context }; + + summarizer.summarizeEvent(event); + + const summaries = await summarizer.getSummaries(); + expect(summaries).toHaveLength(0); + }); + + it('handles multiple different contexts', async () => { + const context1 = { kind: 'user', key: 'user1' }; + const context2 = { kind: 'user', key: 'user2' }; + const event1 = { kind: 'feature', context: context1 }; + const event2 = { kind: 'feature', context: context2 }; + + summarizer.summarizeEvent(event1); + summarizer.summarizeEvent(event2); + + const summaries = await summarizer.getSummaries(); + expect(summaries).toHaveLength(2); + }); + + it('automatically clears summaries when summarized', async () => { + const context = { kind: 'user', key: 'user1' }; + const event = { kind: 'feature', context }; + + summarizer.summarizeEvent(event); + + const summariesA = await summarizer.getSummaries(); + const summariesB = await summarizer.getSummaries(); + expect(summariesA).toHaveLength(1); + expect(summariesB).toHaveLength(0); + }); + + it('increments counters for feature events across multiple contexts', async () => { + const context1 = { kind: 'user', key: 'user1' }; + const context2 = { kind: 'user', key: 'user2' }; + + // Events for context1 (using values 100-199) + const event1 = makeEvent('key1', 11, 1, 100, 111, context1); + const event2 = makeEvent('key1', 11, 2, 150, 111, context1); + const event3 = makeEvent('key2', 22, 1, 199, 222, context1); + + // Events for context2 (using values 200-299) + const event4 = makeEvent('key1', 11, 1, 200, 211, context2); + const event5 = makeEvent('key1', 11, 2, 250, 211, context2); + const event6 = makeEvent('key2', 22, 1, 299, 222, context2); + + summarizer.summarizeEvent(event1); + summarizer.summarizeEvent(event2); + summarizer.summarizeEvent(event3); + summarizer.summarizeEvent(event4); + summarizer.summarizeEvent(event5); + summarizer.summarizeEvent(event6); + + const summaries = await summarizer.getSummaries(); + expect(summaries).toHaveLength(2); + + // Sort summaries by context key to make assertions consistent + summaries.sort((a, b) => a.context.key.localeCompare(b.context.key)); + + // Verify first context's summary (user1, values 100-199) + const summary1 = summaries[0]; + summary1.features.key1.counters.sort((a, b) => a.value - b.value); + expect(summary1.features).toEqual({ + key1: { + contextKinds: ['user'], + default: 111, + counters: [ + { value: 100, variation: 1, version: 11, count: 1 }, + { value: 150, variation: 2, version: 11, count: 1 }, + ], + }, + key2: { + contextKinds: ['user'], + default: 222, + counters: [{ value: 199, variation: 1, version: 22, count: 1 }], + }, + }); + + // Verify second context's summary (user2, values 200-299) + const summary2 = summaries[1]; + summary2.features.key1.counters.sort((a, b) => a.value - b.value); + expect(summary2.features).toEqual({ + key1: { + contextKinds: ['user'], + default: 211, + counters: [ + { value: 200, variation: 1, version: 11, count: 1 }, + { value: 250, variation: 2, version: 11, count: 1 }, + ], + }, + key2: { + contextKinds: ['user'], + default: 222, + counters: [{ value: 299, variation: 1, version: 22, count: 1 }], + }, + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/PersistentFlagStore-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/PersistentFlagStore-test.js new file mode 100644 index 00000000..ecdcee3a --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/PersistentFlagStore-test.js @@ -0,0 +1,111 @@ +import * as stubPlatform from './stubPlatform'; + +import * as messages from '../messages'; +import Identity from '../Identity'; +import PersistentFlagStore from '../PersistentFlagStore'; +import PersistentStorage from '../PersistentStorage'; +import * as utils from '../utils'; + +describe('PersistentFlagStore', () => { + const context = { key: 'context-key', kind: 'user' }; + const ident = Identity(context); + const env = 'ENVIRONMENT'; + const lsKey = 'ld:' + env + ':' + utils.btoa(JSON.stringify(context)); + + it('stores flags', async () => { + const platform = stubPlatform.defaults(); + const storage = PersistentStorage(platform.localStorage, platform.testing.logger); + const store = PersistentFlagStore(storage, env, '', ident, platform.testing.logger); + + const flags = { flagKey: { value: 'x' } }; + + await store.saveFlags(flags); + + const value = platform.testing.getLocalStorageImmediately(lsKey); + const expected = { $schema: 1, ...flags }; + expect(JSON.parse(value)).toEqual(expected); + }); + + it('retrieves and parses flags', async () => { + const platform = stubPlatform.defaults(); + const storage = PersistentStorage(platform.localStorage, platform.testing.logger); + const store = PersistentFlagStore(storage, env, '', ident, platform.testing.logger); + + const expected = { flagKey: { value: 'x' } }; + const stored = { $schema: 1, ...expected }; + platform.testing.setLocalStorageImmediately(lsKey, JSON.stringify(stored)); + + const values = await store.loadFlags(); + expect(values).toEqual(expected); + }); + + it('converts flags from old format if schema property is missing', async () => { + const platform = stubPlatform.defaults(); + const storage = PersistentStorage(platform.localStorage, platform.testing.logger); + const store = PersistentFlagStore(storage, env, '', ident, platform.testing.logger); + + const oldFlags = { flagKey: 'x' }; + const newFlags = { flagKey: { value: 'x', version: 0 } }; + platform.testing.setLocalStorageImmediately(lsKey, JSON.stringify(oldFlags)); + + const values = await store.loadFlags(); + expect(values).toEqual(newFlags); + }); + + it('returns null if storage is empty', async () => { + const platform = stubPlatform.defaults(); + const storage = PersistentStorage(platform.localStorage, platform.testing.logger); + const store = PersistentFlagStore(storage, env, '', ident, platform.testing.logger); + + const values = await store.loadFlags(); + expect(values).toBe(null); + }); + + it('clears storage and returns null if value is not valid JSON', async () => { + const platform = stubPlatform.defaults(); + const storage = PersistentStorage(platform.localStorage, platform.testing.logger); + const store = PersistentFlagStore(storage, env, '', ident, platform.testing.logger); + + platform.testing.setLocalStorageImmediately(lsKey, '{bad'); + + expect(await store.loadFlags()).toBe(null); + + expect(platform.testing.getLocalStorageImmediately(lsKey)).toBe(undefined); + }); + + it('uses hash, if present, instead of context properties', async () => { + const platform = stubPlatform.defaults(); + const storage = PersistentStorage(platform.localStorage, platform.testing.logger); + const hash = '12345'; + const keyWithHash = 'ld:' + env + ':' + hash; + const store = PersistentFlagStore(storage, env, hash, ident, platform.testing.logger); + + const flags = { flagKey: { value: 'x' } }; + await store.saveFlags(flags); + + const value = platform.testing.getLocalStorageImmediately(keyWithHash); + expect(JSON.parse(value)).toEqual({ $schema: 1, ...flags }); + }); + + it('should handle localStorage.get returning an error', async () => { + const platform = stubPlatform.defaults(); + const storage = PersistentStorage(platform.localStorage, platform.testing.logger); + const store = PersistentFlagStore(storage, env, '', ident, platform.testing.logger); + const myError = new Error('localstorage getitem error'); + jest.spyOn(platform.localStorage, 'get').mockImplementation(() => Promise.reject(myError)); + + expect(await store.loadFlags()).toBe(null); + expect(platform.testing.logger.output.warn).toEqual([messages.localStorageUnavailable(myError)]); + }); + + it('should handle localStorage.set returning an error', async () => { + const platform = stubPlatform.defaults(); + const storage = PersistentStorage(platform.localStorage, platform.testing.logger); + const store = PersistentFlagStore(storage, env, '', ident, platform.testing.logger); + const myError = new Error('localstorage setitem error'); + jest.spyOn(platform.localStorage, 'set').mockImplementation(() => Promise.reject(myError)); + + await store.saveFlags({ foo: {} }); + expect(platform.testing.logger.output.warn).toEqual([messages.localStorageUnavailable(myError)]); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/Requestor-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/Requestor-test.js new file mode 100644 index 00000000..a7399fee --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/Requestor-test.js @@ -0,0 +1,362 @@ +import Requestor from '../Requestor'; +import * as errors from '../errors'; +import * as messages from '../messages'; +import * as utils from '../utils'; + +import { fakeNetworkErrorValue, networkError, respond, respondJson } from './mockHttp'; +import * as stubPlatform from './stubPlatform'; + +// These tests verify that Requestor executes the expected HTTP requests to retrieve flags. Since +// the js-sdk-common package uses an abstraction of HTTP requests, these tests do not use HTTP but +// rather use a test implementation of our HTTP abstraction; the individual platform-specific SDKs +// are responsible for verifying that their own implementations of the same HTTP abstraction work +// correctly with real networking. + +describe('Requestor', () => { + const user = { key: 'foo' }; + const encodedUser = 'eyJrZXkiOiJmb28ifQ'; + const env = 'FAKE_ENV'; + const platform = stubPlatform.defaults(); + + async function withServer(asyncCallback) { + const server = platform.testing.http.newServer(); + server.byDefault(respondJson({})); + const baseConfig = { baseUrl: server.url, logger: stubPlatform.logger() }; + return await asyncCallback(baseConfig, server); + } + + it('resolves on success', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, baseConfig, env); + + await requestor.fetchFlagSettings({ key: 'user1' }, 'hash1'); + await requestor.fetchFlagSettings({ key: 'user2' }, 'hash2'); + + expect(server.requests.length()).toEqual(2); + }); + }); + + it('makes requests with the GET verb if useReport is disabled', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, { ...baseConfig, useReport: false }, env); + + await requestor.fetchFlagSettings(user, 'hash1'); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.method).toEqual('get'); + }); + }); + + it('makes requests with the REPORT verb with a payload if useReport is enabled', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, { ...baseConfig, useReport: true }, env); + + await requestor.fetchFlagSettings(user, 'hash1'); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.method).toEqual('report'); + expect(JSON.parse(req.body)).toEqual(user); + }); + }); + + it('includes environment and user in GET URL', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, baseConfig, env); + + await requestor.fetchFlagSettings(user, null); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.path).toEqual(`/sdk/evalx/${env}/contexts/${encodedUser}`); + }); + }); + + it('includes environment, user, and hash in GET URL', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, baseConfig, env); + + await requestor.fetchFlagSettings(user, 'hash1'); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.path).toEqual(`/sdk/evalx/${env}/contexts/${encodedUser}?h=hash1`); + }); + }); + + it('includes environment, user, and withReasons in GET URL', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, { ...baseConfig, evaluationReasons: true }, env); + + await requestor.fetchFlagSettings(user, null); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.path).toEqual(`/sdk/evalx/${env}/contexts/${encodedUser}?withReasons=true`); + }); + }); + + it('includes environment, user, hash, and withReasons in GET URL', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, { ...baseConfig, evaluationReasons: true }, env); + + await requestor.fetchFlagSettings(user, 'hash1'); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.path).toEqual(`/sdk/evalx/${env}/contexts/${encodedUser}?h=hash1&withReasons=true`); + }); + }); + + it('includes environment in REPORT URL', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, { ...baseConfig, useReport: true }, env); + + await requestor.fetchFlagSettings(user, null); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.path).toEqual(`/sdk/evalx/${env}/context`); + }); + }); + + it('includes environment and hash in REPORT URL', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, { ...baseConfig, useReport: true }, env); + + await requestor.fetchFlagSettings(user, 'hash1'); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.path).toEqual(`/sdk/evalx/${env}/context?h=hash1`); + }); + }); + + it('includes environment and withReasons in REPORT URL', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, { ...baseConfig, useReport: true, evaluationReasons: true }, env); + + await requestor.fetchFlagSettings(user, null); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.path).toEqual(`/sdk/evalx/${env}/context?withReasons=true`); + }); + }); + + it('includes environment, hash, and withReasons in REPORT URL', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(platform, { ...baseConfig, useReport: true, evaluationReasons: true }, env); + + await requestor.fetchFlagSettings(user, 'hash1'); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.path).toEqual(`/sdk/evalx/${env}/context?h=hash1&withReasons=true`); + }); + }); + + it('sends custom user-agent header in GET mode when sendLDHeaders is true', async () => { + await withServer(async (baseConfig, server) => { + const config = { ...baseConfig, sendLDHeaders: true }; + const requestor = Requestor(platform, config, env); + + await requestor.fetchFlagSettings(user); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.headers['user-agent']).toEqual(utils.getLDUserAgentString(platform)); + expect(req.headers['x-launchdarkly-wrapper']).toBeUndefined(); + }); + }); + + it('sends wrapper info if specified in GET mode when sendLDHeaders is true', async () => { + await withServer(async (baseConfig, server) => { + const config = { ...baseConfig, sendLDHeaders: true, wrapperName: 'FakeSDK' }; + const requestor = Requestor(platform, config, env); + + await requestor.fetchFlagSettings(user); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.headers['user-agent']).toEqual(utils.getLDUserAgentString(platform)); + expect(req.headers['x-launchdarkly-wrapper']).toEqual('FakeSDK'); + }); + }); + + it('sends custom user-agent header in REPORT mode when sendLDHeaders is true', async () => { + await withServer(async (baseConfig, server) => { + const config = { ...baseConfig, useReport: true, sendLDHeaders: true }; + const requestor = Requestor(platform, config, env); + + await requestor.fetchFlagSettings(user, 'hash1'); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.headers['user-agent']).toEqual(utils.getLDUserAgentString(platform)); + expect(req.headers['x-launchdarkly-wrapper']).toBeUndefined(); + }); + }); + + it('sends wrapper info if specified in REPORT mode when sendLDHeaders is true', async () => { + await withServer(async (baseConfig, server) => { + const config = { ...baseConfig, useReport: true, sendLDHeaders: true, wrapperName: 'FakeSDK' }; + const requestor = Requestor(platform, config, env); + + await requestor.fetchFlagSettings(user, 'hash1'); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.headers['user-agent']).toEqual(utils.getLDUserAgentString(platform)); + expect(req.headers['x-launchdarkly-wrapper']).toEqual('FakeSDK'); + }); + }); + + it('does NOT send custom user-agent header when sendLDHeaders is false', async () => { + await withServer(async (baseConfig, server) => { + const config = { ...baseConfig, sendLDHeaders: false }; + const requestor = Requestor(platform, config, env); + + await requestor.fetchFlagSettings(user); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.headers['user-agent']).toBeUndefined(); + expect(req.headers['x-launchdarkly-wrapper']).toBeUndefined(); + }); + }); + + it('sends transformed headers if requestHeaderTransform function is provided', async () => { + await withServer(async (baseConfig, server) => { + const headerTransform = input => { + const output = { ...input }; + output['b'] = '20'; + return output; + }; + const config = { ...baseConfig, requestHeaderTransform: headerTransform }; + const requestor = Requestor(platform, config, env); + + await requestor.fetchFlagSettings(user); + + expect(server.requests.length()).toEqual(1); + const req = await server.requests.take(); + expect(req.headers['b']).toEqual('20'); + }); + }); + + it('returns parsed JSON response on success', async () => { + const data = { foo: 'bar' }; + await withServer(async (baseConfig, server) => { + server.byDefault(respondJson(data)); + const requestor = Requestor(platform, baseConfig, env); + + const result = await requestor.fetchFlagSettings(user); + expect(result).toEqual(data); + }); + }); + + it('allows JSON content type with charset', async () => { + await withServer(async (baseConfig, server) => { + server.byDefault(respond(200, { 'content-type': 'application/json; charset=utf-8' }, '{}')); + const requestor = Requestor(platform, baseConfig, env); + + const result = await requestor.fetchFlagSettings(user); + expect(result).toEqual({}); + }); + }); + + it('allows extra JSON content type header', async () => { + await withServer(async (baseConfig, server) => { + // this could happen if a proxy/gateway interpolated its own content-type header; https://github.com/launchdarkly/js-client-sdk/issues/205 + server.byDefault(respond(200, { 'content-type': 'application/json, application/json; charset=utf-8' }, '{}')); + const requestor = Requestor(platform, baseConfig, env); + + const result = await requestor.fetchFlagSettings(user); + expect(result).toEqual({}); + }); + }); + + it('returns error for non-JSON content type', async () => { + await withServer(async (baseConfig, server) => { + server.byDefault(respond(200, { 'content-type': 'text/plain' }, 'sorry')); + const requestor = Requestor(platform, baseConfig, env); + + const err = new errors.LDFlagFetchError(messages.invalidContentType('text/plain')); + await expect(requestor.fetchFlagSettings(user)).rejects.toThrow(err); + }); + }); + + it('returns error for unspecified content type', async () => { + await withServer(async (baseConfig, server) => { + server.byDefault(respond(200, {}, '')); + const requestor = Requestor(platform, baseConfig, env); + + const err = new errors.LDFlagFetchError(messages.invalidContentType('')); + await expect(requestor.fetchFlagSettings(user)).rejects.toThrow(err); + }); + }); + + it('signals specific error for 404 response', async () => { + await withServer(async (baseConfig, server) => { + server.byDefault(respond(404)); + const requestor = Requestor(platform, baseConfig, env); + + const err = new errors.LDInvalidEnvironmentIdError(messages.environmentNotFound()); + await expect(requestor.fetchFlagSettings(user)).rejects.toThrow(err); + }); + }); + + it('signals general error for non-404 error status', async () => { + await withServer(async (baseConfig, server) => { + server.byDefault(respond(500)); + const requestor = Requestor(platform, baseConfig, env); + + const err = new errors.LDFlagFetchError(messages.errorFetchingFlags('500')); + await expect(requestor.fetchFlagSettings(user)).rejects.toThrow(err); + }); + }); + + it('signals general error for network error', async () => { + await withServer(async (baseConfig, server) => { + server.byDefault(networkError()); + const requestor = Requestor(platform, baseConfig, env); + + const err = new errors.LDFlagFetchError(messages.networkError(fakeNetworkErrorValue)); + await expect(requestor.fetchFlagSettings(user)).rejects.toThrow(err); + }); + }); + + it('coalesces multiple requests so all callers get the latest result', async () => { + await withServer(async (baseConfig, server) => { + let n = 0; + server.byDefault((req, res) => { + n++; + respondJson({ value: n })(req, res); + }); + + const requestor = Requestor(platform, baseConfig, env); + + const r1 = requestor.fetchFlagSettings(user); + const r2 = requestor.fetchFlagSettings(user); + + const result1 = await r1; + const result2 = await r2; + + expect(result1).toEqual({ value: 2 }); + expect(result2).toEqual({ value: 2 }); + + expect(server.requests.length()).toEqual(2); + }); + }); + + describe('When HTTP requests are not available at all', () => { + it('fails on fetchFlagSettings', async () => { + await withServer(async (baseConfig, server) => { + const requestor = Requestor(stubPlatform.withoutHttp(), baseConfig, env); + await expect(requestor.fetchFlagSettings(user, null)).rejects.toThrow(messages.httpUnavailable()); + expect(server.requests.length()).toEqual(0); + }); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/SafeInspector-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/SafeInspector-test.js new file mode 100644 index 00000000..2f6f47cf --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/SafeInspector-test.js @@ -0,0 +1,61 @@ +const SafeInspector = require('../SafeInspector'); +const stubPlatform = require('./stubPlatform'); + +describe('given a safe inspector', () => { + const platform = stubPlatform.defaults(); + const mockInspector = { + type: 'the-inspector-type', + name: 'the-inspector-name', + method: () => { + throw new Error('evil inspector'); + }, + }; + const safeInspector = SafeInspector(mockInspector, platform.testing.logger); + + it('has the correct type', () => { + expect(safeInspector.type).toEqual('the-inspector-type'); + }); + + it('does not allow exceptions to propagate', () => { + safeInspector.method(); + }); + + it('only logs one error', () => { + safeInspector.method(); + safeInspector.method(); + expect(platform.testing.logger.output.warn).toEqual([ + 'an inspector: "the-inspector-name" of type: "the-inspector-type" generated an exception', + ]); + }); +}); + +// Type and name are required by the schema, but it should operate fine if they are not specified. +describe('given a safe inspector with no name or type', () => { + const platform = stubPlatform.defaults(); + const mockInspector = { + method: () => { + throw new Error('evil inspector'); + }, + }; + const safeInspector = SafeInspector(mockInspector, platform.testing.logger); + + it('has undefined type', () => { + expect(safeInspector.type).toBeUndefined(); + }); + + it('has undefined name', () => { + expect(safeInspector.name).toBeUndefined(); + }); + + it('does not allow exceptions to propagate', () => { + safeInspector.method(); + }); + + it('only logs one error', () => { + safeInspector.method(); + safeInspector.method(); + expect(platform.testing.logger.output.warn).toEqual([ + 'an inspector: "undefined" of type: "undefined" generated an exception', + ]); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/Stream-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/Stream-test.js new file mode 100644 index 00000000..733a2874 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/Stream-test.js @@ -0,0 +1,337 @@ +import { DiagnosticsAccumulator } from '../diagnosticEvents'; +import * as messages from '../messages'; +import Stream from '../Stream'; +import { getLDHeaders } from '../headers'; + +import { sleepAsync } from 'launchdarkly-js-test-helpers'; +import EventSource from './EventSource-mock'; +import * as stubPlatform from './stubPlatform'; + +const noop = () => {}; + +describe('Stream', () => { + const baseUrl = 'https://example.com'; + const envName = 'testenv'; + const user = { key: 'me' }; + const encodedUser = 'eyJrZXkiOiJtZSJ9'; + const hash = '012345789abcde'; + const defaultConfig = { streamUrl: baseUrl, sendLDHeaders: true }; + let logger; + let platform; + let baseHeaders; + + beforeEach(() => { + logger = stubPlatform.logger(); + defaultConfig.logger = logger; + platform = stubPlatform.defaults(); + baseHeaders = getLDHeaders(platform, defaultConfig); + }); + + function makeExpectedStreamUrl(base64User, userHash, withReasons) { + const url = baseUrl + '/eval/' + envName + '/' + base64User; + const queryParams = []; + if (userHash) { + queryParams.push('h=' + userHash); + } + if (withReasons) { + queryParams.push('?withReasons=true'); + } + return url + (queryParams.length ? '?' + queryParams.join('&') : ''); + } + + it('should not throw on EventSource when it does not exist', () => { + const platform1 = { ...platform }; + delete platform1['eventSourceFactory']; + + const stream = new Stream(platform1, defaultConfig, envName); + + const connect = () => { + stream.connect(noop); + }; + + expect(connect).not.toThrow(TypeError); + }); + + it('should not throw when calling disconnect without first calling connect', () => { + const stream = new Stream(platform, defaultConfig, envName); + const disconnect = () => { + stream.disconnect(noop); + }; + + expect(disconnect).not.toThrow(TypeError); + }); + + it('connects to EventSource with eval stream URL by default', async () => { + const stream = new Stream(platform, defaultConfig, envName); + stream.connect(user, null, {}); + + await platform.testing.expectStream(makeExpectedStreamUrl(encodedUser)); + }); + + it('adds secure mode hash to URL if provided', async () => { + const stream = new Stream(platform, defaultConfig, envName); + stream.connect(user, hash, {}); + + await platform.testing.expectStream(makeExpectedStreamUrl(encodedUser, hash)); + }); + + it('falls back to ping stream URL if useReport is true and REPORT is not supported', async () => { + const config = { ...defaultConfig, useReport: true }; + const stream = new Stream(platform, config, envName); + stream.connect(user, null, {}); + + await platform.testing.expectStream(baseUrl + '/ping/' + envName); + }); + + it('sends request body if useReport is true and REPORT is supported', async () => { + const platform1 = { ...platform, eventSourceAllowsReport: true }; + const config = { ...defaultConfig, useReport: true }; + const stream = new Stream(platform1, config, envName); + stream.connect(user, null, {}); + + const created = await platform.testing.expectStream(baseUrl + '/eval/' + envName); + expect(created.options.method).toEqual('REPORT'); + expect(JSON.parse(created.options.body)).toEqual(user); + }); + + it('sends default SDK headers', async () => { + const stream = new Stream(platform, defaultConfig, envName); + stream.connect(user, null, {}); + + const created = await platform.testing.expectStream(makeExpectedStreamUrl(encodedUser)); + expect(created.options.headers).toEqual(baseHeaders); + }); + + it('sends SDK headers with wrapper info', async () => { + const config = { ...defaultConfig, wrapperName: 'FakeSDK' }; + const stream = new Stream(platform, config, envName); + stream.connect(user, null, {}); + + const created = await platform.testing.expectStream(makeExpectedStreamUrl(encodedUser)); + expect(created.options.headers).toEqual({ ...baseHeaders, 'X-LaunchDarkly-Wrapper': 'FakeSDK' }); + }); + + it('does not send SDK headers when sendLDHeaders is false', async () => { + const config = { ...defaultConfig, sendLDHeaders: false }; + const stream = new Stream(platform, config, envName); + stream.connect(user, null, {}); + + const created = await platform.testing.expectStream(makeExpectedStreamUrl(encodedUser)); + expect(created.options.headers).toEqual({}); + }); + + it('sends transformed headers if requestHeaderTransform function is provided', async () => { + const headerTransform = input => { + const output = { ...input }; + output['a'] = '10'; + return output; + }; + const config = { ...defaultConfig, requestHeaderTransform: headerTransform }; + const stream = new Stream(platform, config, envName); + stream.connect(user, null, {}); + + const created = await platform.testing.expectStream(makeExpectedStreamUrl(encodedUser)); + expect(created.options.headers).toEqual({ ...baseHeaders, a: '10' }); + }); + + it('sets event listeners', async () => { + const stream = new Stream(platform, defaultConfig, envName); + const fn1 = jest.fn(); + const fn2 = jest.fn(); + + stream.connect(user, null, { + birthday: fn1, + anniversary: fn2, + }); + + const created = await platform.testing.expectStream(); + const es = created.eventSource; + + es.mockEmit('birthday'); + expect(fn1).toHaveBeenCalled(); + expect(fn2).not.toHaveBeenCalled(); + + es.mockEmit('anniversary'); + expect(fn2).toHaveBeenCalled(); + }); + + it('reconnects after encountering an error', async () => { + const config = { ...defaultConfig, streamReconnectDelay: 1, useReport: false }; + const stream = new Stream(platform, config, envName); + stream.connect(user); + + const created = await platform.testing.expectStream(); + let es = created.eventSource; + + expect(es.readyState).toBe(EventSource.CONNECTING); + es.mockOpen(); + expect(es.readyState).toBe(EventSource.OPEN); + + const nAttempts = 5; + for (let i = 0; i < nAttempts; i++) { + es.mockError('test error'); + await sleepAsync(10); + const created1 = await platform.testing.expectStream(); + const es1 = created1.eventSource; + + expect(es.readyState).toBe(EventSource.CLOSED); + expect(es1.readyState).toBe(EventSource.CONNECTING); + + es1.mockOpen(); + await sleepAsync(0); // make sure the stream logic has a chance to catch up with the new EventSource state + + expect(stream.isConnected()).toBe(true); + + es = es1; + } + }); + + it.each([401, 403])('does not reconnect after an unrecoverable error', async status => { + const config = { ...defaultConfig, streamReconnectDelay: 1, useReport: false }; + const stream = new Stream(platform, config, envName); + stream.connect(user); + + const created = await platform.testing.expectStream(); + const es = created.eventSource; + + expect(es.readyState).toBe(EventSource.CONNECTING); + es.mockOpen(); + expect(es.readyState).toBe(EventSource.OPEN); + + es.mockError({ status }); + await sleepAsync(10); + expect(platform.testing.eventSourcesCreated.length()).toEqual(0); + }); + + it.each([400, 408, 429])('does reconnect after a recoverable error', async status => { + const config = { ...defaultConfig, streamReconnectDelay: 1, useReport: false }; + const stream = new Stream(platform, config, envName); + stream.connect(user); + + const created = await platform.testing.expectStream(); + const es = created.eventSource; + + expect(es.readyState).toBe(EventSource.CONNECTING); + es.mockOpen(); + expect(es.readyState).toBe(EventSource.OPEN); + + es.mockError({ status }); + await sleepAsync(10); + expect(platform.testing.eventSourcesCreated.length()).toEqual(1); + }); + + it('logs a warning for only the first failed connection attempt', async () => { + const config = { ...defaultConfig, streamReconnectDelay: 1 }; + const stream = new Stream(platform, config, envName); + stream.connect(user); + + const created = await platform.testing.expectStream(); + let es = created.eventSource; + es.mockOpen(); + + const nAttempts = 5; + for (let i = 0; i < nAttempts; i++) { + es.mockError('test error'); + await sleepAsync(10); + const created1 = await platform.testing.expectStream(); + es = created1.eventSource; + es.mockOpen(); + } + + // make sure there is just a single logged message rather than five (one per attempt) + expect(logger.output.warn).toEqual([messages.streamError('test error', 1)]); + }); + + it('logs a warning again after a successful connection', async () => { + const config = { ...defaultConfig, streamReconnectDelay: 1 }; + const stream = new Stream(platform, config, envName); + const fakePut = jest.fn(); + stream.connect(user, null, { + put: fakePut, + }); + + const created = await platform.testing.expectStream(); + let es = created.eventSource; + es.mockOpen(); + + const nAttempts = 5; + for (let i = 0; i < nAttempts; i++) { + es.mockError('test error #1'); + await sleepAsync(10); + const created1 = await platform.testing.expectStream(); + es = created1.eventSource; + es.mockOpen(); + } + + // simulate the re-establishment of a successful connection + es.mockEmit('put', 'something'); + expect(fakePut).toHaveBeenCalled(); + + for (let i = 0; i < nAttempts; i++) { + es.mockError('test error #2'); + await sleepAsync(10); + const created1 = await platform.testing.expectStream(); + es = created1.eventSource; + es.mockOpen(); + } + + // make sure there is just a single logged message rather than five (one per attempt) + expect(logger.output.warn).toEqual([ + expect.stringContaining('test error #1'), + expect.stringContaining('test error #2'), + ]); + }); + + describe('interaction with diagnostic events', () => { + it('records successful stream initialization', async () => { + const startTime = new Date().getTime(); + const acc = DiagnosticsAccumulator(startTime); + const config = { ...defaultConfig, streamReconnectDelay: 1 }; + const stream = new Stream(platform, config, envName, acc); + + expect(acc.getProps().streamInits.length).toEqual(0); + + stream.connect(user, null, { + put: jest.fn(), + }); + + const created = await platform.testing.expectStream(); + const es = created.eventSource; + es.mockOpen(); + + // streamInits should not be updated until we actually receive something + expect(acc.getProps().streamInits.length).toEqual(0); + + es.mockEmit('put', 'something'); + + const streamInits = acc.getProps().streamInits; + expect(streamInits.length).toEqual(1); + expect(streamInits[0].timestamp).toBeGreaterThanOrEqual(startTime); + expect(streamInits[0].durationMillis).toBeGreaterThanOrEqual(0); + expect(streamInits[0].failed).toBeFalsy(); + }); + + it('records failed stream initialization', async () => { + const startTime = new Date().getTime(); + const acc = DiagnosticsAccumulator(startTime); + const config = { ...defaultConfig, streamReconnectDelay: 1 }; + const stream = new Stream(platform, config, envName, acc); + + expect(acc.getProps().streamInits.length).toEqual(0); + + stream.connect(user, null, { + put: jest.fn(), + }); + + const created = await platform.testing.expectStream(); + const es = created.eventSource; + es.mockError('test error'); + + const streamInits = acc.getProps().streamInits; + expect(streamInits.length).toEqual(1); + expect(streamInits[0].timestamp).toBeGreaterThanOrEqual(startTime); + expect(streamInits[0].durationMillis).toBeGreaterThanOrEqual(0); + expect(streamInits[0].failed).toBe(true); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/TransientContextProcessor-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/TransientContextProcessor-test.js new file mode 100644 index 00000000..f94fff18 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/TransientContextProcessor-test.js @@ -0,0 +1,115 @@ +import AnonymousContextProcessor from '../AnonymousContextProcessor'; + +describe('AnonymousContextProcessor', () => { + let localStorage; + let logger; + let uv; + + beforeEach(() => { + localStorage = {}; + logger = { + warn: jest.fn(), + }; + uv = new AnonymousContextProcessor(localStorage, logger); + }); + + it('rejects null user', async () => { + await expect(uv.processContext(null)).rejects.toThrow(); + }); + + it('leaves user with string key unchanged', async () => { + const u = { key: 'someone', name: 'me' }; + expect(await uv.processContext(u)).toEqual(u); + }); + + it('stringifies non-string key', async () => { + const u0 = { key: 123, name: 'me' }; + const u1 = { key: '123', name: 'me' }; + expect(await uv.processContext(u0)).toEqual(u1); + }); + + it('uses cached key for anonymous user', async () => { + const cachedKey = 'thing'; + let storageKey; + localStorage.get = async key => { + storageKey = key; + return cachedKey; + }; + const u = { anonymous: true }; + expect(await uv.processContext(u)).toEqual({ key: cachedKey, anonymous: true }); + expect(storageKey).toEqual('ld:$anonUserId'); + }); + + it('generates and stores key for anonymous user', async () => { + let storageKey; + let storedValue; + localStorage.get = async () => null; + localStorage.set = async (key, value) => { + storageKey = key; + storedValue = value; + }; + const u0 = { anonymous: true }; + const u1 = await uv.processContext(u0); + expect(storedValue).toEqual(expect.anything()); + expect(u1).toEqual({ key: storedValue, anonymous: true }); + expect(storageKey).toEqual('ld:$anonUserId'); + }); + + it('generates and stores a key for each anonymous context in a multi-kind context', async () => { + const context = { + kind: 'multi', + user: { anonymous: true }, + org: { anonymous: true }, + app: { key: 'app' }, + }; + + const storage = {}; + localStorage.get = async key => storage[key]; + localStorage.set = async (key, value) => { + storage[key] = value; + }; + + const processed = await uv.processContext(context); + expect(processed.user.key).toBeDefined(); + expect(processed.user.key).not.toEqual(processed.org.key); + expect(processed.org.key).toBeDefined(); + expect(processed.app.key).toEqual('app'); + }); + + it('uses cached keys for context kinds that have already been generated', async () => { + const context = { + kind: 'multi', + user: { anonymous: true }, + org: { anonymous: true }, + another: { anonymous: true }, + app: { key: 'app' }, + }; + + const storage = { + 'ld:$contextKey:org': 'cachedOrgKey', + 'ld:$anonUserId': 'cachedUserKey', + }; + localStorage.get = async key => storage[key]; + localStorage.set = async (key, value) => { + storage[key] = value; + }; + + const processed = await uv.processContext(context); + expect(processed.user.key).toEqual('cachedUserKey'); + expect(processed.org.key).toEqual('cachedOrgKey'); + expect(processed.another.key).toBeDefined(); + expect(processed.app.key).toEqual('app'); + }); + + it.each([{ anonymous: true }, { kind: 'user', anonymous: true }, { kind: 'multi', user: { anonymous: true } }])( + 'uses the same key to store any user context (legacy, single, multi)', + async context => { + const storage = {}; + localStorage.get = async key => expect(key).toEqual('ld:$anonUserId'); + localStorage.set = async (key, value) => { + storage[key] = value; + }; + await uv.processContext(context); + } + ); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/attributeReference-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/attributeReference-test.js new file mode 100644 index 00000000..3669c90d --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/attributeReference-test.js @@ -0,0 +1,400 @@ +const AttributeReference = require('../attributeReference'); + +describe('when filtering attributes by reference', () => { + it('should be able to remove a top level value', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['ld'] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }); + expect(excluded).toEqual(['/ld']); + }); + + it('should be able to exclude a nested value', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['/launchdarkly/u2c'] + ); + expect(cloned).toEqual({ + launchdarkly: {}, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }); + expect(excluded).toEqual(['/launchdarkly/u2c']); + }); + + it('sould be able to exclude an object', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['launchdarkly'] + ); + expect(cloned).toEqual({ + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }); + expect(excluded).toEqual(['/launchdarkly']); + }); + + it('sould be able to exclude an array', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['foo'] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + ld: false, + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }); + expect(excluded).toEqual(['/foo']); + }); + + it('should not allow exclude an array index', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['foo/0'] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }); + expect(excluded).toEqual([]); + }); + + it('should not allow exclude a property inside an index of an array.', () => { + const objWithArrayOfObjects = { + array: [ + { + toRemove: true, + toLeave: true, + }, + ], + }; + + const { cloned, excluded } = AttributeReference.cloneExcluding(objWithArrayOfObjects, ['array/0/toRemove']); + expect(cloned).toEqual(objWithArrayOfObjects); + expect(excluded).toEqual([]); + }); + + it('should not allow exclude the root object', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['/'] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }); + expect(excluded).toEqual([]); + }); + + it('should allow exclude a null value', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['null'] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + }); + expect(excluded).toEqual(['/null']); + }); + + it('should not allow exclude a value inside null', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['/null/null'] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }); + expect(excluded).toEqual([]); + }); + + it('should not allow exclude a value inside explicit undefined', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['undefined/null'] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }); + expect(excluded).toEqual([]); + }); + + it('should allow removing an explicit undefined value', () => { + const objToClone = { undefined: undefined }; + const { cloned, excluded } = AttributeReference.cloneExcluding(objToClone, ['undefined']); + expect(cloned).toEqual({}); + expect(excluded).toEqual(['/undefined']); + }); + + it('should allow removing references with escape characters', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['/a~1b', '/m~0n'] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + ' ': ' ', + null: null, + }); + expect(excluded).toEqual(['/a~1b', '/m~0n']); + }); + + it('should allow removing literals without escape characters', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + ['a/b', 'm~n'] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + ' ': ' ', + null: null, + }); + expect(excluded).toEqual(['/a~1b', '/m~0n']); + }); + + it('should handle cycles', () => { + const item = {}; + const objWithCycle = { + item, + name: 'test', + remove: 'remove', + }; + item.parent = objWithCycle; + const { cloned, excluded } = AttributeReference.cloneExcluding(objWithCycle, ['remove']); + expect(cloned).toEqual({ + item: {}, + name: 'test', + }); + expect(excluded).toEqual(['/remove']); + }); + + it('should allow non-circular reference and should treat them independently for filtering', () => { + const item = { value: 'value' }; + const objWithSharedPeer = { + item: item, + second: item, + third: item, + fourth: item, + }; + const { cloned, excluded } = AttributeReference.cloneExcluding(objWithSharedPeer, ['third', '/second/value']); + expect(cloned).toEqual({ + item: { value: 'value' }, + second: {}, + fourth: { value: 'value' }, + }); + expect(excluded).toEqual(['/second/value', '/third']); + }); + + it('should allow for an empty reference list', () => { + const { cloned, excluded } = AttributeReference.cloneExcluding( + { + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }, + [] + ); + expect(cloned).toEqual({ + launchdarkly: { + u2c: true, + }, + ld: false, + foo: ['bar', 'baz'], + 'a/b': 1, + 'm~n': 2, + ' ': ' ', + null: null, + }); + expect(excluded).toEqual([]); + }); +}); + +describe('when given a literal', () => { + it('can convert it to a reference', () => { + expect(AttributeReference.literalToReference('/~why')).toEqual('/~1~0why'); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/canonicalize-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/canonicalize-test.js new file mode 100644 index 00000000..1b340f76 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/canonicalize-test.js @@ -0,0 +1,86 @@ +const fs = require('fs'); +const path = require('path'); + +const canonicalize = require('../canonicalize'); + +// Get the test file pairs +const testInputDir = path.join(__dirname, 'testdata', 'input'); +const testOutputDir = path.join(__dirname, 'testdata', 'output'); +const testFiles = fs.readdirSync(testInputDir); + +it.each(testFiles)('should correctly canonicalize %s', filename => { + // Load the input and expected output files + const inputPath = path.join(testInputDir, filename); + const outputPath = path.join(testOutputDir, filename); + + const inputData = JSON.parse(fs.readFileSync(inputPath, 'utf8')); + const expectedOutput = fs.readFileSync(outputPath, 'utf8'); + + // Apply the canonicalize function + const result = canonicalize(inputData); + + // Compare results + expect(result).toEqual(expectedOutput); +}); + +it('handles basic arrays', () => { + const input = []; + const expected = '[]'; + const result = canonicalize(input); + expect(result).toEqual(expected); +}); + +it('handles arrays of null/undefined', () => { + const input = [null, undefined]; + const expected = '[null,null]'; + const result = canonicalize(input); + expect(result).toEqual(expected); +}); + +it('handles objects with numeric keys', () => { + const input = { + 1: 'one', + 2: 'two', + }; + const expected = '{"1":"one","2":"two"}'; + const result = canonicalize(input); + expect(result).toEqual(expected); +}); + +it('handles objects with undefined values', () => { + const input = { + a: 'b', + c: undefined, + }; + const expected = '{"a":"b"}'; + const result = canonicalize(input); + expect(result).toEqual(expected); +}); + +it('handles an object with a symbol value', () => { + const input = { + a: 'b', + c: Symbol('c'), + }; + const expected = '{"a":"b"}'; + const result = canonicalize(input); + expect(result).toEqual(expected); +}); + +it('handles an object with a symbol key', () => { + const input = { + a: 'b', + [Symbol('c')]: 'd', + }; + const expected = '{"a":"b"}'; + const result = canonicalize(input); + expect(result).toEqual(expected); +}); + +it('should throw an error for objects with cycles', () => { + const a = {}; + const b = { a }; + a.b = b; + + expect(() => canonicalize(a)).toThrow('Cycle detected'); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/configuration-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/configuration-test.js new file mode 100644 index 00000000..348ea7b1 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/configuration-test.js @@ -0,0 +1,261 @@ +import { sleepAsync, eventSink } from 'launchdarkly-js-test-helpers'; + +import * as configuration from '../configuration'; +import { LDInvalidArgumentError } from '../errors'; +import * as messages from '../messages'; +import EventEmitter from '../EventEmitter'; + +import * as stubPlatform from './stubPlatform'; + +describe('configuration', () => { + function errorListener() { + const logger = stubPlatform.logger(); + const emitter = EventEmitter(logger); + const errorQueue = eventSink(emitter, 'error'); + return { + emitter, + logger, + expectNoErrors: async () => { + await sleepAsync(0); // errors are dispatched on next tick + expect(errorQueue.length()).toEqual(0); + expect(logger.output.error).toEqual([]); + }, + expectError: async message => { + await sleepAsync(0); + expect(errorQueue.length()).toEqual(1); + if (message) { + expect(await errorQueue.take()).toEqual(new LDInvalidArgumentError(message)); + } else { + expect((await errorQueue.take()).constructor.prototype.name).toEqual('LaunchDarklyInvalidArgumentError'); + } + }, + expectWarningOnly: async message => { + await sleepAsync(0); + expect(errorQueue.length()).toEqual(0); + expect(logger.output.warn).toContain(message); + }, + }; + } + + async function expectDefault(name) { + const listener = errorListener(); + const config = configuration.validate({}, listener.emitter, null, listener.logger); + expect(config[name]).toBe(configuration.baseOptionDefs[name].default); + await listener.expectNoErrors(); + } + + // As of the latest major version, there are no deprecated options. This logic can be restored + // the next time we deprecate something. + // function checkDeprecated(oldName, newName, value) { + // const desc = newName + // ? 'allows "' + oldName + '" as a deprecated equivalent to "' + newName + '"' + // : 'warns that "' + oldName + '" is deprecated'; + // it(desc, async () => { + // const listener = errorListener(); + // const config0 = {}; + // config0[oldName] = value; + // const config1 = configuration.validate(config0, listener.emitter, null, listener.logger); + // if (newName) { + // expect(config1[newName]).toBe(value); + // expect(config1[oldName]).toBeUndefined(); + // } else { + // expect(config1[oldName]).toEqual(value); + // } + // await listener.expectWarningOnly(messages.deprecated(oldName, newName)); + // }); + // } + + function checkBooleanProperty(name) { + it('enforces boolean type and default for "' + name + '"', async () => { + await expectDefault(name); + + let listener = errorListener(); + const configIn1 = {}; + configIn1[name] = true; + const config1 = configuration.validate(configIn1, listener.emitter, null, listener.logger); + expect(config1[name]).toBe(true); + await listener.expectNoErrors(); + + listener = errorListener(); + const configIn2 = {}; + configIn2[name] = false; + const config2 = configuration.validate(configIn2, listener.emitter, null, listener.logger); + expect(config2[name]).toBe(false); + await listener.expectNoErrors(); + + listener = errorListener(); + const configIn3 = {}; + configIn3[name] = 'abc'; + const config3 = configuration.validate(configIn3, listener.emitter, null, listener.logger); + expect(config3[name]).toBe(true); + await listener.expectError(messages.wrongOptionTypeBoolean(name, 'string')); + + listener = errorListener(); + const configIn4 = {}; + configIn4[name] = 0; + const config4 = configuration.validate(configIn4, listener.emitter, null, listener.logger); + expect(config4[name]).toBe(false); + await listener.expectError(messages.wrongOptionTypeBoolean(name, 'number')); + }); + } + + checkBooleanProperty('sendEvents'); + checkBooleanProperty('allAttributesPrivate'); + checkBooleanProperty('sendLDHeaders'); + checkBooleanProperty('sendEventsOnlyForVariation'); + checkBooleanProperty('useReport'); + checkBooleanProperty('evaluationReasons'); + checkBooleanProperty('diagnosticOptOut'); + checkBooleanProperty('streaming'); + + function checkNumericProperty(name, validValue) { + it('enforces numeric type and default for "' + name + '"', async () => { + await expectDefault(name); + + let listener = errorListener(); + const configIn1 = {}; + configIn1[name] = validValue; + const config1 = configuration.validate(configIn1, listener.emitter, null, listener.logger); + expect(config1[name]).toBe(validValue); + await listener.expectNoErrors(); + + listener = errorListener(); + const configIn2 = {}; + configIn2[name] = 'no'; + const config2 = configuration.validate(configIn2, listener.emitter, null, listener.logger); + expect(config2[name]).toBe(configuration.baseOptionDefs[name].default); + await listener.expectError(messages.wrongOptionType(name, 'number', 'string')); + }); + } + + checkNumericProperty('eventCapacity', 200); + checkNumericProperty('flushInterval', 3000); + checkNumericProperty('samplingInterval', 1); + checkNumericProperty('streamReconnectDelay', 2000); + + function checkMinimumValue(name, minimum) { + it('disallows value below minimum of ' + minimum + ' for ' + name, async () => { + const listener = errorListener(); + const configIn = {}; + configIn[name] = minimum - 1; + const config = configuration.validate(configIn, listener.emitter, null, listener.logger); + await listener.expectError(messages.optionBelowMinimum(name, minimum - 1, minimum)); + expect(config[name]).toBe(minimum); + }); + } + + checkMinimumValue('eventCapacity', 1); + checkMinimumValue('flushInterval', 2000); + checkMinimumValue('samplingInterval', 0); + checkMinimumValue('diagnosticRecordingInterval', 2000); + + function checkValidValue(name, goodValue) { + it('allows value of ' + JSON.stringify(goodValue) + ' for ' + name, async () => { + const listener = errorListener(); + const configIn = {}; + configIn[name] = goodValue; + const config = configuration.validate(configIn, listener.emitter, null, listener.logger); + await listener.expectNoErrors(); + expect(config[name]).toBe(goodValue); + }); + } + + checkValidValue('bootstrap', 'localstorage'); + checkValidValue('bootstrap', { flag: 'value' }); + + it('validates custom logger methods', () => { + const badLogger = { debug: () => {}, info: () => {}, warn: () => {}, error: 'not a function' }; + const listener = errorListener(); + const configIn = { logger: badLogger }; + expect(() => configuration.validate(configIn, listener.emitter, null, listener.logger)).toThrow(); + }); + + it('allows custom logger with valid methods', async () => { + const goodLogger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + const listener = errorListener(); + const configIn = { logger: goodLogger }; + const config = configuration.validate(configIn, listener.emitter, null, listener.logger); + await listener.expectNoErrors(); + expect(config.logger).toBe(goodLogger); + }); + + it('complains if you set an unknown property', async () => { + const listener = errorListener(); + const configIn = { unsupportedThing: true }; + const config = configuration.validate(configIn, listener.emitter, null, listener.logger); + await listener.expectError(messages.unknownOption('unsupportedThing')); + expect(config.unsupportedThing).toBe(true); + }); + + it('allows platform-specific SDK options whose defaults are specified by the SDK', async () => { + const listener = errorListener(); + const fn = () => {}; + const platformSpecificOptions = { + extraBooleanOption: { default: true }, + extraNumericOption: { default: 2 }, + extraNumericOptionWithoutDefault: { type: 'number' }, + extraStringOption: { default: 'yes' }, + extraStringOptionWithoutDefault: { type: 'string' }, + extraFunctionOption: { type: 'function' }, + }; + const configIn = { + extraBooleanOption: false, + extraNumericOptionWithoutDefault: 'not a number', + extraStringOptionWithoutDefault: 'ok', + extraFunctionOption: fn, + }; + const config = configuration.validate(configIn, listener.emitter, platformSpecificOptions, listener.logger); + expect(config.extraBooleanOption).toBe(false); + expect(config.extraNumericOption).toBe(2); + expect(config.extraStringOption).toBe('yes'); + expect(config.extraStringOptionWithoutDefault).toBe('ok'); + expect(config.extraFunctionOption).toBe(fn); + await listener.expectError(messages.wrongOptionType('extraNumericOptionWithoutDefault', 'number', 'string')); + }); + + it('handles a valid application id', async () => { + const listener = errorListener(); + const configIn = { application: { id: 'test-application' } }; + expect(configuration.validate(configIn, listener.emitter, null, listener.logger).application.id).toEqual( + 'test-application' + ); + }); + + it('logs a warning with an invalid application id', async () => { + const listener = errorListener(); + const configIn = { application: { id: 'test #$#$#' } }; + expect(configuration.validate(configIn, listener.emitter, null, listener.logger).application.id).toBeUndefined(); + await listener.expectWarningOnly(messages.invalidTagValue('application.id')); + }); + + it('logs a warning when a tag value is too long', async () => { + const listener = errorListener(); + const configIn = { application: { id: 'a'.repeat(65), version: 'b'.repeat(64) } }; + expect(configuration.validate(configIn, listener.emitter, null, listener.logger).application.id).toBeUndefined(); + await listener.expectWarningOnly(messages.tagValueTooLong('application.id')); + }); + + it('handles a valid application version', async () => { + const listener = errorListener(); + const configIn = { application: { version: 'test-version' } }; + expect(configuration.validate(configIn, listener.emitter, null, listener.logger).application.version).toEqual( + 'test-version' + ); + }); + + it('logs a warning with an invalid application version', async () => { + const listener = errorListener(); + const configIn = { application: { version: 'test #$#$#' } }; + expect( + configuration.validate(configIn, listener.emitter, null, listener.logger).application.version + ).toBeUndefined(); + await listener.expectWarningOnly(messages.invalidTagValue('application.version')); + }); + + it('includes application id and version in tags when present', async () => { + expect(configuration.getTags({ application: { id: 'test-id', version: 'test-version' } })).toEqual({ + 'application-id': ['test-id'], + 'application-version': ['test-version'], + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/context-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/context-test.js new file mode 100644 index 00000000..6c7f726a --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/context-test.js @@ -0,0 +1,201 @@ +const { checkContext, getContextKeys, getContextKinds, getCanonicalKey } = require('../context'); + +describe.each([{ key: 'test' }, { kind: 'user', key: 'test' }, { kind: 'multi', user: { key: 'test' } }])( + 'given a context which contains a single kind', + context => { + it('should get the context kind', () => { + expect(getContextKinds(context)).toEqual(['user']); + }); + + it('should be valid', () => { + expect(checkContext(context, false)).toBeTruthy(); + }); + } +); + +describe('given a valid multi-kind context', () => { + const context = { + kind: 'multi', + user: { + key: 'user', + }, + org: { + key: 'org', + }, + }; + + it('should get a list of the kinds', () => { + expect(getContextKinds(context).sort()).toEqual(['org', 'user']); + }); + + it('should be valid', () => { + expect(checkContext(context, false)).toBeTruthy(); + }); +}); + +// A sample of invalid characters. +const invalidSampleChars = [ + ...`#$%&'()*+,/:;<=>?@[\\]^\`{|}~ ¡¢£¤¥¦§¨©ª«¬­®¯°±² +³´µ¶·¸¹º»¼½¾¿À汉字`, +]; +const badKinds = invalidSampleChars.map(char => ({ kind: char, key: 'test' })); + +describe.each([ + {}, // An empty object is not a valid context. + { key: '' }, // If allowLegacyKey is not true, then this should be invalid. + { kind: 'kind', key: 'kind' }, // The kind cannot be kind. + { kind: 'user' }, // The context needs to have a key. + { kind: 'org', key: '' }, // For a non-legacy context the key cannot be empty. + { kind: ' ', key: 'test' }, // Kind cannot be whitespace only. + { kind: 'cat dog', key: 'test' }, // Kind cannot contain whitespace + { kind: '~!@#$%^&*()_+', key: 'test' }, // Special characters are not valid. + ...badKinds, +])('given invalid contexts', context => { + it('should not be valid', () => { + expect(checkContext(context, false)).toBeFalsy(); + }); +}); + +const validChars = ['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.']; +const goodKinds = validChars.map(char => [{ kind: char, key: 'test' }, false]); + +describe.each([ + [{ key: '' }, true], // Allow a legacy context with an empty key. + ...goodKinds, +])('given valid contexts', (context, allowLegacyKey) => { + it('should be valid and can get context kinds', () => { + expect(checkContext(context, allowLegacyKey)).toBeTruthy(); + expect(getContextKinds(context)).toEqual([context.kind || 'user']); + }); +}); + +describe('when determining canonical keys', () => { + it.each([ + [{ key: 'test' }, 'test'], + [{ kind: 'user', key: 'test' }, 'test'], + [{ kind: 'org', key: 'orgtest' }, 'org:orgtest'], + [{ kind: 'multi', user: { key: 'usertest' } }, 'user:usertest'], + [{ kind: 'multi', user: { key: 'usertest' }, org: { key: 'orgtest' } }, 'org:orgtest:user:usertest'], + [{ kind: 'multi', user: { key: 'user:test' }, org: { key: 'org:test' } }, 'org:org%3Atest:user:user%3Atest'], + [{ kind: 'multi', user: { key: 'user%test' }, org: { key: 'org%test' } }, 'org:org%25test:user:user%25test'], + [ + { kind: 'multi', user: { key: 'user%:test' }, org: { key: 'org%:test' } }, + 'org:org%25%3Atest:user:user%25%3Atest', + ], + ])('produces a canonical key for valid contexts', (context, canonicalKey) => { + expect(getCanonicalKey(context)).toEqual(canonicalKey); + }); + + it('does not break with an null/undefined context', () => { + expect(getCanonicalKey(undefined)).toBeUndefined(); + expect(getCanonicalKey(null)).toBeUndefined(); + }); +}); + +describe('getContextKeys', () => { + it('returns undefined if argument is undefined', () => { + const context = undefined; + const keys = getContextKeys(context); + expect(keys).toBeUndefined(); + }); + + it('works with legacy user without kind attribute', () => { + const user = { + key: 'legacy-user-key', + name: 'Test User', + custom: { + customAttribute1: true, + }, + }; + const keys = getContextKeys(user); + expect(keys).toEqual({ user: 'legacy-user-key' }); + }); + + it('gets keys from multi context', () => { + const context = { + kind: 'multi', + user: { + key: 'test-user-key', + name: 'Test User', + isPremiumCustomer: true, + }, + organization: { + key: 'test-organization-key', + name: 'Test Company', + industry: 'technology', + }, + }; + const keys = getContextKeys(context); + expect(keys).toEqual({ user: 'test-user-key', organization: 'test-organization-key' }); + }); + + it('ignores undefined keys from multi context', () => { + const context = { + kind: 'multi', + user: { + key: 'test-user-key', + name: 'Test User', + isPremiumCustomer: true, + }, + organization: { + name: 'Test Company', + industry: 'technology', + }, + rogueAttribute: undefined, + }; + const keys = getContextKeys(context); + expect(keys).toEqual({ user: 'test-user-key' }); + }); + + it('ignores empty string and null keys from multi context', () => { + const context = { + kind: 'multi', + user: { + key: 'test-user-key', + name: 'Test User', + isPremiumCustomer: true, + }, + organization: { + key: '', + name: 'Test Company', + industry: 'technology', + }, + drone: { + key: null, + name: 'test-drone', + }, + }; + const keys = getContextKeys(context); + expect(keys).toEqual({ user: 'test-user-key' }); + }); + + it('gets keys from single context', () => { + const context = { + kind: 'drone', + key: 'test-drone-key', + name: 'test-drone', + }; + const keys = getContextKeys(context); + expect(keys).toEqual({ drone: 'test-drone-key' }); + }); + + it('ignores kind when it is an empty string', () => { + const context = { + kind: '', + key: 'test-drone-key', + name: 'test-drone', + }; + const keys = getContextKeys(context); + expect(keys).toEqual({}); + }); + + it('ignores kind when it is null', () => { + const context = { + kind: null, + key: 'test-drone-key', + name: 'test-drone', + }; + const keys = getContextKeys(context); + expect(keys).toEqual({}); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/diagnosticEvents-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/diagnosticEvents-test.js new file mode 100644 index 00000000..e38d32c6 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/diagnosticEvents-test.js @@ -0,0 +1,449 @@ +import { baseOptionDefs } from '../configuration'; +import { DiagnosticId, DiagnosticsAccumulator, DiagnosticsManager } from '../diagnosticEvents'; +import PersistentStorage from '../PersistentStorage'; +import { sleepAsync } from 'launchdarkly-js-test-helpers'; + +import * as stubPlatform from './stubPlatform'; +import { MockEventSender } from './testUtils'; + +// These tests cover the logic in diagnosticEvents.js. Some of the statistics in diagnostic events come from +// other SDK components; the tests for those components will verify that they generate the right values. + +describe('DiagnosticId', () => { + it('creates unique IDs', () => { + const id1 = DiagnosticId('key'); + const id2 = DiagnosticId('key'); + expect(id1.diagnosticId).not.toEqual(id2.diagnosticId); + }); + + it('uses only last 6 characters of key', () => { + const id = DiagnosticId('0123456789abcdef'); + expect(id.sdkKeySuffix).toEqual('abcdef'); + }); +}); + +describe('DiagnosticsAccumulator', () => { + it('sets initial properties', () => { + const acc = DiagnosticsAccumulator(1000); + expect(acc.getProps()).toEqual({ + dataSinceDate: 1000, + droppedEvents: 0, + eventsInLastBatch: 0, + streamInits: [], + }); + }); + + it('increments dropped events', () => { + const acc = DiagnosticsAccumulator(1000); + acc.incrementDroppedEvents(); + acc.incrementDroppedEvents(); + expect(acc.getProps().droppedEvents).toEqual(2); + }); + + it('sets event count', () => { + const acc = DiagnosticsAccumulator(1000); + acc.setEventsInLastBatch(99); + expect(acc.getProps().eventsInLastBatch).toEqual(99); + }); + + it('records successful stream init', () => { + const acc = DiagnosticsAccumulator(1000); + acc.recordStreamInit(1001, false, 500); + expect(acc.getProps().streamInits).toEqual([{ timestamp: 1001, failed: false, durationMillis: 500 }]); + }); + + it('records failed stream init', () => { + const acc = DiagnosticsAccumulator(1000); + acc.recordStreamInit(1001, true, 500); + expect(acc.getProps().streamInits).toEqual([{ timestamp: 1001, failed: true, durationMillis: 500 }]); + }); + + it('resets properties', () => { + const acc = DiagnosticsAccumulator(1000); + acc.incrementDroppedEvents(); + acc.setEventsInLastBatch(99); + acc.recordStreamInit(1001, false, 500); + acc.reset(1002); + expect(acc.getProps()).toEqual({ + dataSinceDate: 1002, + droppedEvents: 0, + eventsInLastBatch: 0, + streamInits: [], + }); + }); +}); + +describe('DiagnosticsManager', () => { + const diagnosticId = DiagnosticId('123456'); + const envId = 'my-environment-id'; + const defaultStartTime = 1000; + const defaultInterval = 100000; + const localStorageKey = 'ld:' + envId + ':$diagnostics'; + const sdkData = { + name: 'js-test', + version: '0.0.1', + }; + const platformData = { + name: 'Positron', + osArch: 'usrobots', + osName: 'Robbie', + osVersion: '1940', + }; + const defaultConfig = { + baseUrl: baseOptionDefs.baseUrl.default, + streamUrl: baseOptionDefs.streamUrl.default, + eventsUrl: baseOptionDefs.eventsUrl.default, + eventCapacity: 50, + fetchGoals: true, + flushInterval: 1000, + streamReconnectDelay: 900, + diagnosticRecordingInterval: defaultInterval, + }; + const defaultConfigInEvent = { + allAttributesPrivate: false, + bootstrapMode: false, + customBaseURI: false, + customEventsURI: false, + customStreamURI: false, + diagnosticRecordingIntervalMillis: defaultInterval, + eventsCapacity: defaultConfig.eventCapacity, + eventsFlushIntervalMillis: defaultConfig.flushInterval, + fetchGoalsDisabled: false, + reconnectTimeMillis: defaultConfig.streamReconnectDelay, + sendEventsOnlyForVariation: false, + streamingDisabled: true, + usingSecureMode: false, + }; + const expectedStatsForPeriodicEvent1 = { + droppedEvents: 1, + eventsInLastBatch: 2, + streamInits: [ + { timestamp: 1001, durationMillis: 100 }, + { timestamp: 1002, failed: true, durationMillis: 500 }, + ], + }; + const expectedStatsForPeriodicEvent2 = { + droppedEvents: 0, + eventsInLastBatch: 1, + streamInits: [{ timestamp: 1003, durationMillis: 99 }], + }; + + async function withManager(extraConfig, overridePlatform, asyncCallback) { + const platform = overridePlatform || stubPlatform.defaults(); + const storage = PersistentStorage(platform.localStorage, platform.testing.logger); + platform.diagnosticSdkData = sdkData; + platform.diagnosticPlatformData = platformData; + const config = { ...defaultConfig, ...extraConfig }; + const acc = DiagnosticsAccumulator(defaultStartTime); + const sender = MockEventSender(); + const m = DiagnosticsManager(platform, storage, acc, sender, envId, config, diagnosticId); + try { + return await asyncCallback(m, acc, sender); + } finally { + m.stop(); + } + } + + function setupStatsForPeriodicEvent1(acc) { + acc.incrementDroppedEvents(); + acc.setEventsInLastBatch(2); + acc.recordStreamInit(1001, false, 100); + acc.recordStreamInit(1002, true, 500); + } + + function setupStatsForPeriodicEvent2(acc) { + acc.setEventsInLastBatch(1); + acc.recordStreamInit(1003, false, 99); + } + + async function getPostedEvent(sender, config) { + const posted = await sender.calls.take(); + const baseUrl = { ...defaultConfig, ...config }.eventsUrl; + expect(posted.url).toEqual(baseUrl + '/events/diagnostic/' + envId); + return posted.events; + } + + describe('in default mode', () => { + it('does not send init event before start()', async () => { + await withManager({}, null, async (manager, acc, sender) => { + expect(sender.calls.length()).toEqual(0); + }); + }); + + it('sends init event on start() with default config', async () => { + await withManager({}, null, async (manager, acc, sender) => { + manager.start(); + expect(sender.calls.length()).toEqual(1); + const initEvent = await getPostedEvent(sender); + expect(initEvent).toEqual({ + kind: 'diagnostic-init', + creationDate: defaultStartTime, + id: diagnosticId, + sdk: sdkData, + platform: platformData, + configuration: defaultConfigInEvent, + }); + }); + }); + + it('sends init event on start() with custom config', async () => { + const configAndResultValues = [ + [{ allAttributesPrivate: true }, { allAttributesPrivate: true }], + [{ bootstrap: {} }, { bootstrapMode: true }], + [{ baseUrl: 'http://other' }, { customBaseURI: true }], + [{ eventsUrl: 'http://other' }, { customEventsURI: true }], + [{ streamUrl: 'http://other' }, { customStreamURI: true }], + [{ diagnosticRecordingInterval: 99999 }, { diagnosticRecordingIntervalMillis: 99999 }], + [{ eventCapacity: 222 }, { eventsCapacity: 222 }], + [{ flushInterval: 2222 }, { eventsFlushIntervalMillis: 2222 }], + [{ fetchGoals: false }, { fetchGoalsDisabled: true }], + [{ streamReconnectDelay: 2222 }, { reconnectTimeMillis: 2222 }], + [{ sendEventsOnlyForVariation: true }, { sendEventsOnlyForVariation: true }], + [{ streaming: true }, { streamingDisabled: false }], + [{ hash: 'x' }, { usingSecureMode: true }], + ]; + for (const i in configAndResultValues) { + const configOverrides = configAndResultValues[i][0]; + const expectedConfig = { ...defaultConfigInEvent, ...configAndResultValues[i][1] }; + await withManager(configOverrides, null, async (manager, acc, sender) => { + manager.start(); + expect(sender.calls.length()).toEqual(1); + const initEvent = await getPostedEvent(sender, configOverrides); + expect(initEvent).toEqual({ + kind: 'diagnostic-init', + creationDate: defaultStartTime, + id: diagnosticId, + sdk: sdkData, + platform: platformData, + configuration: expectedConfig, + }); + }); + } + }); + + it('allows client to indicate that streaming is now enabled', async () => { + await withManager({}, null, async (manager, acc, sender) => { + manager.setStreaming(true); + manager.start(); + expect(sender.calls.length()).toEqual(1); + const initEvent = await getPostedEvent(sender); + expect(initEvent).toEqual({ + kind: 'diagnostic-init', + creationDate: defaultStartTime, + id: diagnosticId, + sdk: sdkData, + platform: platformData, + configuration: { ...defaultConfigInEvent, streamingDisabled: false }, + }); + }); + }); + + it('sends periodic events', async () => { + const interval = 100; + // Note that since we haven't added any special instrumentation to DiagnosticsManager to let the test + // control the exact timing of the periodic events, this test is assuming that we can do a few simple + // steps before 100ms elapses. + await withManager({ diagnosticRecordingInterval: interval }, null, async (manager, acc, sender) => { + manager.start(); + const initEvent = await getPostedEvent(sender); + expect(initEvent.kind).toEqual('diagnostic-init'); + + setupStatsForPeriodicEvent1(acc); + + const periodic1 = await getPostedEvent(sender); + expect(periodic1).toMatchObject({ + kind: 'diagnostic', + dataSinceDate: defaultStartTime, + id: diagnosticId, + ...expectedStatsForPeriodicEvent1, + }); + expect(periodic1.creationDate).toBeGreaterThanOrEqual(defaultStartTime); + + setupStatsForPeriodicEvent2(acc); + + const periodic2 = await getPostedEvent(sender); + expect(periodic2).toMatchObject({ + kind: 'diagnostic', + dataSinceDate: periodic1.creationDate, + id: diagnosticId, + ...expectedStatsForPeriodicEvent2, + }); + }); + }); + }); + + describe('in combined (browser) mode', () => { + const interval = 100; + const expectedConfig = { ...defaultConfigInEvent, diagnosticRecordingIntervalMillis: interval }; + + it('does not send event before start()', async () => { + const overridePlatform = stubPlatform.defaults(); + overridePlatform.diagnosticUseCombinedEvent = true; + await withManager({}, overridePlatform, async (manager, acc, sender) => { + expect(sender.calls.length()).toEqual(0); + }); + }); + + it('if local storage has no data, sends event on start(), then sends periodic event', async () => { + const timeBeforeStart = new Date().getTime(); + const overridePlatform = stubPlatform.defaults(); + overridePlatform.diagnosticUseCombinedEvent = true; + await withManager({ diagnosticRecordingInterval: interval }, overridePlatform, async (manager, acc, sender) => { + manager.start(); + + const firstEvent = await getPostedEvent(sender); + expect(firstEvent).toMatchObject({ + kind: 'diagnostic-combined', + id: diagnosticId, + dataSinceDate: defaultStartTime, + sdk: sdkData, + platform: platformData, + configuration: expectedConfig, + droppedEvents: 0, + eventsInLastBatch: 0, + streamInits: [], + }); + expect(firstEvent.creationDate).toBeGreaterThanOrEqual(timeBeforeStart); + + setupStatsForPeriodicEvent1(acc); + + const periodic1 = await getPostedEvent(sender); + expect(periodic1).toMatchObject({ + kind: 'diagnostic-combined', + id: diagnosticId, + sdk: sdkData, + platform: platformData, + configuration: expectedConfig, + ...expectedStatsForPeriodicEvent1, + }); + expect(periodic1.dataSinceDate).toBeGreaterThan(firstEvent.dataSinceDate); + }); + }); + + it('if local storage has non-recent data, sends cached event on start(), then sends periodic event', async () => { + const timeBeforeStart = new Date().getTime(); + const storedStats = { + dataSinceDate: timeBeforeStart - interval - 1, + droppedEvents: 1, + eventsInLastBatch: 2, + streamInits: [{ timestamp: 1000, durationMillis: 500 }], + }; + const overridePlatform = stubPlatform.defaults(); + overridePlatform.diagnosticUseCombinedEvent = true; + overridePlatform.testing.setLocalStorageImmediately(localStorageKey, JSON.stringify(storedStats)); + await withManager({ diagnosticRecordingInterval: interval }, overridePlatform, async (manager, acc, sender) => { + const timeBeforeStart = new Date().getTime(); + manager.start(); + await sleepAsync(10); // manager's localstorage logic is async, so allow it to catch up with us + + expect(sender.calls.length()).toEqual(1); + const firstEvent = await getPostedEvent(sender); + expect(firstEvent).toMatchObject({ + kind: 'diagnostic-combined', + id: diagnosticId, + sdk: sdkData, + platform: platformData, + configuration: { ...defaultConfigInEvent, diagnosticRecordingIntervalMillis: interval }, + ...storedStats, + }); + expect(firstEvent.creationDate).toBeGreaterThanOrEqual(timeBeforeStart); + + setupStatsForPeriodicEvent1(acc); + + const periodic1 = await getPostedEvent(sender); + expect(periodic1).toMatchObject({ + kind: 'diagnostic-combined', + id: diagnosticId, + sdk: sdkData, + platform: platformData, + configuration: expectedConfig, + ...expectedStatsForPeriodicEvent1, + }); + expect(periodic1.dataSinceDate).toBeGreaterThan(firstEvent.dataSinceDate); + }); + }); + + it('defers event on start() if event was sent recently', async () => { + const timeBeforeStart = new Date().getTime(); + const interval = 200; + const storedStats = { + dataSinceDate: timeBeforeStart - interval + 100, + droppedEvents: 1, + eventsInLastBatch: 2, + streamInits: [{ timestamp: 1000, durationMillis: 500 }], + }; + const overridePlatform = stubPlatform.defaults(); + overridePlatform.diagnosticUseCombinedEvent = true; + overridePlatform.testing.setLocalStorageImmediately(localStorageKey, JSON.stringify(storedStats)); + await withManager({ diagnosticRecordingInterval: interval }, overridePlatform, async (manager, acc, sender) => { + const timeBeforeStart = new Date().getTime(); + manager.start(); + await sleepAsync(10); // manager's localstorage logic is async, so allow it to catch up with us + expect(sender.calls.length()).toEqual(0); + + acc.incrementDroppedEvents(); + acc.setEventsInLastBatch(3); + acc.recordStreamInit(1001, false, 501); + + const firstEvent = await getPostedEvent(sender); + expect(firstEvent).toMatchObject({ + kind: 'diagnostic-combined', + id: diagnosticId, + sdk: sdkData, + platform: platformData, + configuration: { ...defaultConfigInEvent, diagnosticRecordingIntervalMillis: interval }, + dataSinceDate: storedStats.dataSinceDate, + droppedEvents: 2, + eventsInLastBatch: 3, + streamInits: [ + { timestamp: 1000, durationMillis: 500 }, + { timestamp: 1001, durationMillis: 501 }, + ], + }); + expect(firstEvent.creationDate).toBeGreaterThanOrEqual(timeBeforeStart); + }); + }); + + it('continues sending periodic events', async () => { + // In the previous tests in this group, we always separately verified the first periodic event (after + // the initial event) because there could be a different code path for scheduling it depending on the + // initial conditions. But we can assume that the scheduling of the second event does not depend on the + // initial conditions - it will always be scheduled when the first one gets sent. + const interval = 100; + const expectedConfig = { ...defaultConfigInEvent, diagnosticRecordingIntervalMillis: interval }; + const overridePlatform = stubPlatform.defaults(); + overridePlatform.diagnosticUseCombinedEvent = true; + await withManager({ diagnosticRecordingInterval: interval }, overridePlatform, async (manager, acc, sender) => { + manager.start(); + + const firstEvent = await getPostedEvent(sender); + expect(firstEvent).toMatchObject({ + kind: 'diagnostic-combined', + dataSinceDate: defaultStartTime, + }); + + setupStatsForPeriodicEvent1(acc); + + const periodic1 = await getPostedEvent(sender); + expect(periodic1).toMatchObject({ + kind: 'diagnostic-combined', + ...expectedStatsForPeriodicEvent1, + }); + expect(periodic1.dataSinceDate).toBeGreaterThan(firstEvent.dataSinceDate); + + setupStatsForPeriodicEvent2(acc); + + const periodic2 = (await sender.calls.take()).events; + expect(periodic2).toMatchObject({ + kind: 'diagnostic-combined', + id: diagnosticId, + sdk: sdkData, + platform: platformData, + configuration: expectedConfig, + ...expectedStatsForPeriodicEvent2, + }); + expect(periodic2.dataSinceDate).toBeGreaterThan(periodic1.dataSinceDate); + }); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/headers-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/headers-test.js new file mode 100644 index 00000000..2c6bacd7 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/headers-test.js @@ -0,0 +1,117 @@ +import { getLDHeaders, transformHeaders } from '../headers'; +import { getLDUserAgentString } from '../utils'; +import * as stubPlatform from './stubPlatform'; + +describe('getLDHeaders', () => { + it('sends no headers unless sendLDHeaders is true', () => { + const platform = stubPlatform.defaults(); + const headers = getLDHeaders(platform, {}); + expect(headers).toEqual({}); + }); + + it('adds user-agent header', () => { + const platform = stubPlatform.defaults(); + const headers = getLDHeaders(platform, { sendLDHeaders: true }); + expect(headers).toMatchObject({ 'User-Agent': getLDUserAgentString(platform) }); + }); + + it('adds user-agent header with custom name', () => { + const platform = stubPlatform.defaults(); + platform.userAgentHeaderName = 'X-Fake-User-Agent'; + const headers = getLDHeaders(platform, { sendLDHeaders: true }); + expect(headers).toMatchObject({ 'X-Fake-User-Agent': getLDUserAgentString(platform) }); + }); + + it('adds wrapper info if specified, without version', () => { + const platform = stubPlatform.defaults(); + const headers = getLDHeaders(platform, { sendLDHeaders: true, wrapperName: 'FakeSDK' }); + expect(headers).toMatchObject({ + 'User-Agent': getLDUserAgentString(platform), + 'X-LaunchDarkly-Wrapper': 'FakeSDK', + }); + }); + + it('adds wrapper info if specified, with version', () => { + const platform = stubPlatform.defaults(); + const headers = getLDHeaders(platform, { sendLDHeaders: true, wrapperName: 'FakeSDK', wrapperVersion: '9.9' }); + expect(headers).toMatchObject({ + 'User-Agent': getLDUserAgentString(platform), + 'X-LaunchDarkly-Wrapper': 'FakeSDK/9.9', + }); + }); + + it('sets the X-LaunchDarkly-Tags header with valid id and version.', () => { + const platform = stubPlatform.defaults(); + const headers = getLDHeaders(platform, { + sendLDHeaders: true, + application: { + id: 'test-application', + version: 'test-version', + }, + }); + expect(headers).toMatchObject({ + 'User-Agent': getLDUserAgentString(platform), + 'x-launchdarkly-tags': 'application-id/test-application application-version/test-version', + }); + }); + + it('sets the X-LaunchDarkly-Tags header with just application id', () => { + const platform = stubPlatform.defaults(); + const headers = getLDHeaders(platform, { + sendLDHeaders: true, + application: { + id: 'test-application', + }, + }); + expect(headers).toMatchObject({ + 'User-Agent': getLDUserAgentString(platform), + 'x-launchdarkly-tags': 'application-id/test-application', + }); + }); + + it('sets the X-LaunchDarkly-Tags header with just application version.', () => { + const platform = stubPlatform.defaults(); + const headers = getLDHeaders(platform, { + sendLDHeaders: true, + application: { + version: 'test-version', + }, + }); + expect(headers).toMatchObject({ + 'User-Agent': getLDUserAgentString(platform), + 'x-launchdarkly-tags': 'application-version/test-version', + }); + }); +}); + +describe('transformHeaders', () => { + it('does not modify the headers if the option is not available', () => { + const inputHeaders = { a: '1', b: '2' }; + const headers = transformHeaders(inputHeaders, {}); + expect(headers).toEqual(inputHeaders); + }); + + it('modifies the headers if the option has a transform', () => { + const inputHeaders = { c: '3', d: '4' }; + const outputHeaders = { c: '9', d: '4', e: '5' }; + const headerTransform = input => { + const output = { ...input }; + output['c'] = '9'; + output['e'] = '5'; + return output; + }; + const headers = transformHeaders(inputHeaders, { requestHeaderTransform: headerTransform }); + expect(headers).toEqual(outputHeaders); + }); + + it('cannot mutate the input header object', () => { + const inputHeaders = { f: '6' }; + const expectedInputHeaders = { f: '6' }; + const headerMutate = input => { + input['f'] = '7'; // eslint-disable-line no-param-reassign + return input; + }; + transformHeaders(inputHeaders, { requestHeaderTransform: headerMutate }); + expect(inputHeaders).toEqual(expectedInputHeaders); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/loggers-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/loggers-test.js new file mode 100644 index 00000000..3b1dedf5 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/loggers-test.js @@ -0,0 +1,149 @@ +const { format } = require('util'); +const loggers = require('../loggers'); + +describe('commonBasicLogger', () => { + it('uses console methods by default', () => { + const realLog = console.log, + realInfo = console.info, + realWarn = console.warn, + realError = console.error; + const mockLog = jest.fn(), + mockInfo = jest.fn(), + mockWarn = jest.fn(), + mockError = jest.fn(); + try { + console.log = mockLog; + console.info = mockInfo; + console.warn = mockWarn; + console.error = mockError; + const logger = loggers.commonBasicLogger({ level: 'debug' }); + logger.debug('a'); + logger.info('b'); + logger.warn('c'); + logger.error('d'); + expect(mockLog).toHaveBeenCalledWith('[LaunchDarkly] a'); + expect(mockInfo).toHaveBeenCalledWith('[LaunchDarkly] b'); + expect(mockWarn).toHaveBeenCalledWith('[LaunchDarkly] c'); + expect(mockError).toHaveBeenCalledWith('[LaunchDarkly] d'); + } finally { + console.log = realLog; + console.info = realInfo; + console.warn = realWarn; + console.error = realError; + } + }); + + it('can write to an arbitrary function', () => { + const outputFn = jest.fn(); + const logger = loggers.commonBasicLogger({ destination: outputFn }); + logger.warn('hello'); + expect(outputFn).toHaveBeenCalledWith('warn: [LaunchDarkly] hello'); + }); + + it('throws an exception immediately if destination is not a function', () => { + expect(() => loggers.commonBasicLogger({ destination: 'Mars' })).toThrow(); + }); + + it('does not use formatter if there is only one argument', () => { + const outputFn = jest.fn(); + const logger = loggers.commonBasicLogger({ destination: outputFn }, format); + logger.warn('%d things'); + expect(outputFn).toHaveBeenCalledWith('warn: [LaunchDarkly] %d things'); + }); + + it('uses formatter if there are multiple arguments', () => { + const outputFn = jest.fn(); + const logger = loggers.commonBasicLogger({ destination: outputFn }, format); + logger.warn('%d things', 3); + expect(outputFn).toHaveBeenCalledWith('warn: [LaunchDarkly] 3 things'); + }); + + it('does not use formatter if there is none', () => { + const outputFn = jest.fn(); + const logger = loggers.commonBasicLogger({ destination: outputFn }, null); + logger.warn('%d things', 3); + expect(outputFn).toHaveBeenCalledWith('warn: [LaunchDarkly] %d things'); + }); + + describe('output filtering by level', () => { + const testLevel = (minLevel, enabledLevels) => { + it('level: ' + minLevel, () => { + const outputFn = jest.fn(); + const config = { destination: outputFn }; + if (minLevel) { + config.level = minLevel; + } + const logger = loggers.commonBasicLogger({ level: minLevel, destination: outputFn }); + logger.debug('some debug output'); + logger.info('some info output'); + logger.warn('some warn output'); + logger.error('some error output'); + for (const [level, shouldBeEnabled] of Object.entries(enabledLevels)) { + const line = level + ': [LaunchDarkly] some ' + level + ' output'; + if (shouldBeEnabled) { + expect(outputFn).toHaveBeenCalledWith(line); + } else { + expect(outputFn).not.toHaveBeenCalledWith(line); + } + } + }); + }; + + testLevel('debug', { debug: true, info: true, warn: true, error: true }); + testLevel('info', { debug: false, info: true, warn: true, error: true }); + testLevel('warn', { debug: false, info: false, warn: true, error: true }); + testLevel('error', { debug: false, info: false, warn: false, error: true }); + testLevel('none', { debug: false, info: false, warn: false, error: false }); + + // default is info + testLevel(undefined, { debug: false, info: true, warn: true, error: true }); + }); + + it('does not throw an error if console is undefined or null', () => { + const oldConsole = console; + try { + console = null; // eslint-disable-line no-global-assign + const logger = loggers.commonBasicLogger({ level: 'debug' }); + logger.debug('x'); + logger.info('x'); + logger.warn('x'); + logger.error('x'); + console = undefined; // eslint-disable-line no-global-assign + logger.debug('x'); + logger.info('x'); + logger.warn('x'); + logger.error('x'); + } finally { + console = oldConsole; // eslint-disable-line no-global-assign + } + }); +}); + +describe('validateLogger', () => { + function mockLogger() { + return { + error: jest.fn(), + warn: jest.fn(), + info: jest.fn(), + debug: jest.fn(), + }; + } + + const levels = ['error', 'warn', 'info', 'debug']; + + it('throws an error if the logger does not conform to the LDLogger schema', () => { + // If the method does not exist + levels.forEach(method => { + const logger = mockLogger(); + delete logger[method]; + expect(() => loggers.validateLogger(logger)).toThrow(/Provided logger instance must support .* method/); + }); + + // If the method is not a function + levels.forEach(method => { + const logger = mockLogger(); + logger[method] = 'invalid'; + expect(() => loggers.validateLogger(logger)).toThrow(/Provided logger instance must support .* method/); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/mockHttp.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/mockHttp.js new file mode 100644 index 00000000..c0d7dc3f --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/mockHttp.js @@ -0,0 +1,122 @@ +import * as url from 'url'; +import { AsyncQueue } from 'launchdarkly-js-test-helpers'; + +// The js-sdk-common package does not do any HTTP requests itself, because the implementation of +// HTTP is platform-dependent and must be provided by the individual SDKs (e.g. the browser SDK, +// which uses XMLHttpRequest, versus the Electron SDK, which uses Node HTTP). So, for testing +// this package, there is no point in using an HTTP capture tool like Sinon or a real embedded +// HTTP server. Instead we use this simple implementation of the abstraction, which lets us set +// up test handlers with a syntax that imitates our launchdarkly-js-test-helpers HTTP server. + +let lastServerId = 0; + +export function MockHttpState() { + const servers = {}; + + return { + newServer: () => { + lastServerId++; + const hostname = 'mock-server-' + lastServerId; + const server = newMockServer(hostname); + servers[hostname] = server; + return server; + }, + + doRequest: (method, requestUrl, headers, body, synchronous) => { + const urlParams = url.parse(requestUrl); + const server = servers[urlParams.host]; + if (!server) { + return { promise: Promise.reject('unknown host: ' + urlParams.host) }; + } + return server._doRequest(method, urlParams, headers, body, synchronous); + }, + }; +} + +function newMockServer(hostname) { + let defaultHandler = respond(404); + const matchers = []; + const requests = new AsyncQueue(); + + function dispatch(req, resp) { + for (const i in matchers) { + if (matchers[i](req, resp)) { + return; + } + } + defaultHandler(req, resp); + } + + const server = { + url: 'http://' + hostname, + + requests, + + nextRequest: async () => await requests.take(), + + byDefault: handler => { + defaultHandler = handler; + return server; + }, + + forMethodAndPath: (method, path, handler) => { + const matcher = (req, resp) => { + if (req.method === method.toLowerCase() && req.path === path) { + handler(req, resp); + return true; + } + return false; + }; + matchers.push(matcher); + return server; + }, + + close: () => {}, // currently we don't need to clean up the server state + + _doRequest: (method, urlParams, headers, body) => { + const transformedHeaders = {}; + Object.keys(headers || {}).forEach(key => { + transformedHeaders[key.toLowerCase()] = headers[key]; + }); + const req = { + method: method.toLowerCase(), + path: urlParams.path, + headers: transformedHeaders, + body, + }; + requests.add(req); + const ret = {}; + ret.promise = new Promise((resolve, reject) => { + const resp = { resolve, reject }; + dispatch(req, resp); + }); + return ret; + }, + }; + + return server; +} + +export function respond(status, headers, body) { + return (req, resp) => { + const respProps = { + // these are the properties our HTTP abstraction expects + status, + header: name => headers && headers[name.toLowerCase()], + body, + }; + resp.resolve(respProps); + }; +} + +export function respondJson(data) { + return respond(200, { 'content-type': 'application/json' }, JSON.stringify(data)); +} + +export const fakeNetworkErrorValue = new Error('fake network error'); + +export function networkError() { + return (req, resp) => { + resp.reject(fakeNetworkErrorValue); + }; +} diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/promiseCoalescer-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/promiseCoalescer-test.js new file mode 100644 index 00000000..0ce16f6e --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/promiseCoalescer-test.js @@ -0,0 +1,128 @@ +import promiseCoalescer from '../promiseCoalescer'; + +describe('promiseCoalescer', () => { + function instrumentedPromise() { + let resolveFn, rejectFn; + const p = new Promise((resolve, reject) => { + resolveFn = resolve; + rejectFn = reject; + }); + p.resolve = resolveFn; + p.reject = rejectFn; + return p; + } + + describe('with a single promise', () => { + it('resolves', async () => { + const c = promiseCoalescer(); + const p = instrumentedPromise(); + c.addPromise(p); + p.resolve(3); + const result = await c.resultPromise; + expect(result).toEqual(3); + }); + + it('rejects', async () => { + const c = promiseCoalescer(); + const p = instrumentedPromise(); + c.addPromise(p); + p.reject(new Error('no')); + await expect(c.resultPromise).rejects.toThrow('no'); + }); + + it('does not call cancelFn', async () => { + const fn = jest.fn(); + const c = promiseCoalescer(); + const p = instrumentedPromise(); + c.addPromise(p, fn); + p.resolve(3); + await c.resultPromise; + expect(fn).not.toHaveBeenCalled(); + }); + + it('calls finallyFn', async () => { + const fn = jest.fn(); + const c = promiseCoalescer(fn); + const p = instrumentedPromise(); + c.addPromise(p, fn); + expect(fn).not.toHaveBeenCalled(); + p.resolve(3); + await c.resultPromise; + expect(fn).toHaveBeenCalledTimes(1); + }); + }); + + describe('with multiple promises', () => { + it('resolves only from the last one', async () => { + const c = promiseCoalescer(); + const p1 = instrumentedPromise(); + const p2 = instrumentedPromise(); + const p3 = instrumentedPromise(); + c.addPromise(p1); + c.addPromise(p2); + c.addPromise(p3); + p2.resolve(2); + p3.resolve(3); + p1.resolve(1); + const result = await c.resultPromise; + expect(result).toEqual(3); + }); + + it('rejects only from the last one', async () => { + const c = promiseCoalescer(); + const p1 = instrumentedPromise(); + const p2 = instrumentedPromise(); + const p3 = instrumentedPromise(); + c.addPromise(p1); + c.addPromise(p2); + c.addPromise(p3); + p2.resolve(2); + p3.reject(new Error('no')); + p1.resolve(new Error('maybe')); + await expect(c.resultPromise).rejects.toThrow('no'); + }); + + it('calls cancelFn on all but the last', async () => { + const fn1 = jest.fn(); + const fn2 = jest.fn(); + const fn3 = jest.fn(); + const c = promiseCoalescer(); + const p1 = instrumentedPromise(); + const p2 = instrumentedPromise(); + const p3 = instrumentedPromise(); + c.addPromise(p1, fn1); + expect(fn1).not.toHaveBeenCalled(); + c.addPromise(p2, fn2); + expect(fn1).toHaveBeenCalledTimes(1); + expect(fn2).not.toHaveBeenCalled(); + c.addPromise(p3, fn3); + expect(fn1).toHaveBeenCalledTimes(1); + expect(fn2).toHaveBeenCalledTimes(1); + expect(fn3).not.toHaveBeenCalled(); + p2.resolve(2); + p3.resolve(3); + p1.resolve(1); + await c.resultPromise; + expect(fn3).not.toHaveBeenCalled(); + }); + + it('calls finallyFn', async () => { + const fn = jest.fn(); + const c = promiseCoalescer(fn); + const p1 = instrumentedPromise(); + const p2 = instrumentedPromise(); + const p3 = instrumentedPromise(); + c.addPromise(p1); + expect(fn).not.toHaveBeenCalled(); + c.addPromise(p2); + expect(fn).not.toHaveBeenCalled(); + c.addPromise(p3); + expect(fn).not.toHaveBeenCalled(); + p2.resolve(2); + p3.resolve(3); + p1.resolve(1); + await c.resultPromise; + expect(fn).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/stubPlatform.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/stubPlatform.js new file mode 100644 index 00000000..db31afc5 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/stubPlatform.js @@ -0,0 +1,144 @@ +import * as LDClient from '../index'; +import EventEmitter from '../EventEmitter'; + +import { AsyncQueue, sleepAsync } from 'launchdarkly-js-test-helpers'; + +import EventSource from './EventSource-mock'; +import { MockHttpState } from './mockHttp'; + +// This file provides a stub implementation of the internal platform API for use in tests. +// +// The SDK expects the platform object to have the following properties and methods: +// +// httpRequest?: (method, url, headers, body, sync) => requestProperties +// requestProperties.promise: Promise // resolves to { status, header: (name) => value, body } or rejects for a network error +// requestProperties.cancel?: () => void // provided if it's possible to cancel requests in this implementation +// getCurrentUrl: () => string // returns null if we're not in a browser +// isDoNotTrack: () => boolean +// localStorage: { +// get: (key: string, callback: (err: Error, data: string) => void) => void +// set: (key: string, data: string, callback: (err: Error) => void) => void +// clear: (key: string, callback: (err: Error) => void) => void +// } +// eventSourceFactory?: (url: string, options: object) => EventSource +// // note that the options are ignored by the browser's built-in EventSource; they only work with polyfills +// eventSourceIsActive?: (es: EventSource) => boolean // returns true if it's open or connecting +// eventSourceAllowsReport?: boolean // returns true if we can set { method: 'REPORT' } in the options +// diagnosticSdkData: object // provides the "sdk" property in diagnostic events +// diagnosticPlatformData: object // provides the "platform" property in diagnostic events +// diagnosticUseCombinedEvent: boolean // true if diagnostic events should use the combined model (browser SDK) +// uuid: () => string // function to generate a UUID (this is done differently in browsers vs. Node) +// userAgent: string +// userAgentHeaderName?: string // custom header name to use instead of User-Agent +// version?: string // the SDK version for the User-Agent header, if that is *not* the same as the version of launchdarkly-js-sdk-common + +export function defaults() { + const localStore = {}; + const mockHttpState = MockHttpState(); + const eventSourcesCreated = new AsyncQueue(); + let currentUrl = null; + let doNotTrack = false; + + const p = { + httpRequest: mockHttpState.doRequest, + diagnosticSdkData: { name: 'stub-sdk' }, + diagnosticPlatformData: { name: 'stub-platform' }, + getCurrentUrl: () => currentUrl, + isDoNotTrack: () => doNotTrack, + eventSourceFactory: (url, options) => { + const es = new EventSource(url); + es.options = options; + eventSourcesCreated.add({ eventSource: es, url, options }); + return es; + }, + eventSourceIsActive: es => es.readyState === EventSource.OPEN || es.readyState === EventSource.CONNECTING, + localStorage: { + get: key => + new Promise(resolve => { + resolve(localStore[key]); + }), + set: (key, value) => + new Promise(resolve => { + localStore[key] = value; + resolve(); + }), + clear: key => + new Promise(resolve => { + delete localStore[key]; + resolve(); + }), + }, + userAgent: 'stubClient', + version: '1.2.3', + + // extra methods used for testing + testing: { + logger: logger(), + + http: mockHttpState, + + eventSourcesCreated, + + makeClient: (env, context, options = {}) => { + const config = { logger: p.testing.logger, ...options }; + // We want to simulate what the platform-specific SDKs will do in their own initialization functions. + // They will call the common package's LDClient.initialize() and receive the clientVars object which + // contains both the underlying client (in its "client" property) and some internal methods that the + // platform-specific SDKs can use to do internal stuff. One of those is start(), which they will + // call after doing any other initialization things they may need to do. + const clientVars = LDClient.initialize(env, context, config, p); + clientVars.start(); + return clientVars.client; + }, + + setCurrentUrl: url => { + currentUrl = url; + }, + + setDoNotTrack: value => { + doNotTrack = value; + }, + + getLocalStorageImmediately: key => localStore[key], + + setLocalStorageImmediately: (key, value) => { + localStore[key] = value; + }, + + expectStream: async url => { + await sleepAsync(0); // in case the stream is created by a deferred task + expect(eventSourcesCreated.length()).toBeGreaterThanOrEqual(1); + const created = await eventSourcesCreated.take(); + if (url) { + expect(created.url).toEqual(url); + } + return created; + }, + }, + }; + return p; +} + +export function withoutHttp() { + const e = defaults(); + delete e.httpRequest; + return e; +} + +export function logger() { + const logger = {}; + ['debug', 'info', 'warn', 'error'].forEach(level => { + logger[level] = msg => logger.output[level].push(typeof msg === 'function' ? msg() : msg); + }); + logger.reset = () => { + logger.output = { debug: [], info: [], warn: [], error: [] }; + }; + logger.reset(); + return logger; +} + +export function mockStateProvider(initialState) { + const sp = EventEmitter(); + sp.getInitialState = () => initialState; + return sp; +} diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testUtils.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testUtils.js new file mode 100644 index 00000000..8b656beb --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testUtils.js @@ -0,0 +1,75 @@ +import { AsyncQueue } from 'launchdarkly-js-test-helpers'; + +export const numericUser = { + key: 1, + ip: 3, + country: 4, + email: 5, + firstName: 6, + lastName: 7, + avatar: 8, + name: 9, + anonymous: false, + custom: { age: 99 }, +}; + +// This returns a Promise with a .callback property that is a plain callback function; when +// called, it will resolve the promise with either a single value or an array of arguments. +export function promiseListener() { + let cb; + const p = new Promise(resolve => { + cb = function(value) { + if (arguments.length > 1) { + resolve(Array.prototype.slice.call(arguments)); + } else { + resolve(value); + } + }; + }); + p.callback = cb; + return p; +} + +export const stringifiedNumericUser = { + key: '1', + ip: '3', + country: '4', + email: '5', + firstName: '6', + lastName: '7', + avatar: '8', + name: '9', + anonymous: false, + custom: { age: 99 }, +}; + +export function makeBootstrap(flagsData) { + const ret = { $flagsState: {} }; + for (const key in flagsData) { + const state = { ...flagsData[key] }; + ret[key] = state.value; + delete state.value; + ret.$flagsState[key] = state; + } + return ret; +} + +export function MockEventSender() { + const calls = new AsyncQueue(); + let serverTime = null; + let status = 200; + const sender = { + calls, + sendEvents: (events, url) => { + calls.add({ events, url }); + return Promise.resolve({ serverTime, status }); + }, + setServerTime: time => { + serverTime = time; + }, + setStatus: respStatus => { + status = respStatus; + }, + }; + return sender; +} diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/LICENSE.txt b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/LICENSE.txt new file mode 100644 index 00000000..7c18a967 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/LICENSE.txt @@ -0,0 +1,13 @@ + Copyright 2018 Anders Rundgren + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/VENDOR.txt b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/VENDOR.txt new file mode 100644 index 00000000..c6f4119e --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/VENDOR.txt @@ -0,0 +1,2 @@ +Test data originally from: +https://github.com/cyberphone/json-canonicalization/tree/master/testdata \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/arrays.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/arrays.json new file mode 100644 index 00000000..20e62263 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/arrays.json @@ -0,0 +1,8 @@ +[ + 56, + { + "d": true, + "10": null, + "1": [ ] + } +] diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/french.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/french.json new file mode 100644 index 00000000..4ff6d3de --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/french.json @@ -0,0 +1,6 @@ +{ + "peach": "This sorting order", + "péché": "is wrong according to French", + "pêche": "but canonicalization MUST", + "sin": "ignore locale" +} diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/structures.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/structures.json new file mode 100644 index 00000000..eb71efb8 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/structures.json @@ -0,0 +1,8 @@ +{ + "1": {"f": {"f": "hi","F": 5} ,"\n": 56.0}, + "10": { }, + "": "empty", + "a": { }, + "111": [ {"e": "yes","E": "no" } ], + "A": { } +} \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/unicode.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/unicode.json new file mode 100644 index 00000000..4b5bc769 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/unicode.json @@ -0,0 +1,3 @@ +{ + "Unnormalized Unicode":"A\u030a" +} diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/values.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/values.json new file mode 100644 index 00000000..f7712c2f --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/values.json @@ -0,0 +1,5 @@ +{ + "numbers": [333333333.33333329, 1E30, 4.50, 2e-3, 0.000000000000000000000000001], + "string": "\u20ac$\u000F\u000aA'\u0042\u0022\u005c\\\"\/", + "literals": [null, true, false] +} \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/weird.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/weird.json new file mode 100644 index 00000000..53fabe67 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/input/weird.json @@ -0,0 +1,11 @@ +{ + "\u20ac": "Euro Sign", + "\r": "Carriage Return", + "\u000a": "Newline", + "1": "One", + "\u0080": "Control\u007f", + "\ud83d\ude02": "Smiley", + "\u00f6": "Latin Small Letter O With Diaeresis", + "\ufb33": "Hebrew Letter Dalet With Dagesh", + "": "Browser Challenge" +} diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/arrays.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/arrays.json new file mode 100644 index 00000000..5efb93db --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/arrays.json @@ -0,0 +1 @@ +[56,{"1":[],"10":null,"d":true}] \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/french.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/french.json new file mode 100644 index 00000000..2e15cd1b --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/french.json @@ -0,0 +1 @@ +{"peach":"This sorting order","péché":"is wrong according to French","pêche":"but canonicalization MUST","sin":"ignore locale"} \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/structures.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/structures.json new file mode 100644 index 00000000..dc21e242 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/structures.json @@ -0,0 +1 @@ +{"":"empty","1":{"\n":56,"f":{"F":5,"f":"hi"}},"10":{},"111":[{"E":"no","e":"yes"}],"A":{},"a":{}} \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/unicode.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/unicode.json new file mode 100644 index 00000000..ee60fd12 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/unicode.json @@ -0,0 +1 @@ +{"Unnormalized Unicode":"Å"} \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/values.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/values.json new file mode 100644 index 00000000..29b720b6 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/values.json @@ -0,0 +1 @@ +{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],"string":"€$\u000f\nA'B\"\\\\\"/"} \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/weird.json b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/weird.json new file mode 100644 index 00000000..62c83a33 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/testdata/output/weird.json @@ -0,0 +1 @@ +{"\n":"Newline","\r":"Carriage Return","1":"One","":"Browser Challenge","€":"Control","ö":"Latin Small Letter O With Diaeresis","€":"Euro Sign","😂":"Smiley","דּ":"Hebrew Letter Dalet With Dagesh"} \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/src/__tests__/utils-test.js b/node_modules/launchdarkly-js-sdk-common/src/__tests__/utils-test.js new file mode 100644 index 00000000..c427abb1 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/__tests__/utils-test.js @@ -0,0 +1,96 @@ +import { appendUrlPath, getLDUserAgentString, wrapPromiseCallback, once } from '../utils'; + +import * as stubPlatform from './stubPlatform'; + +describe('utils', () => { + it('appendUrlPath', () => { + expect(appendUrlPath('http://base', '/path')).toEqual('http://base/path'); + expect(appendUrlPath('http://base', 'path')).toEqual('http://base/path'); + expect(appendUrlPath('http://base/', '/path')).toEqual('http://base/path'); + expect(appendUrlPath('http://base/', '/path')).toEqual('http://base/path'); + }); + + describe('wrapPromiseCallback', () => { + it('should resolve to the value', done => { + const promise = wrapPromiseCallback(Promise.resolve('woohoo')); + promise.then(value => { + expect(value).toEqual('woohoo'); + done(); + }); + }); + + it('should reject with the error', done => { + const error = new Error('something went wrong'); + const promise = wrapPromiseCallback(Promise.reject(error)); + promise.catch(error => { + expect(error).toEqual(error); + done(); + }); + }); + + it('should call the callback with a value if the promise resolves', done => { + const promise = wrapPromiseCallback(Promise.resolve('woohoo'), (error, value) => { + expect(promise).toBeUndefined(); + expect(error).toBeNull(); + expect(value).toEqual('woohoo'); + done(); + }); + }); + + it('should call the callback with an error if the promise rejects', done => { + const actualError = new Error('something went wrong'); + const promise = wrapPromiseCallback(Promise.reject(actualError), (error, value) => { + expect(promise).toBeUndefined(); + expect(error).toEqual(actualError); + expect(value).toBeNull(); + done(); + }); + }); + }); + + describe('getLDUserAgentString', () => { + it('uses platform user-agent and unknown version by default', () => { + const platform = stubPlatform.defaults(); + platform.version = undefined; + const ua = getLDUserAgentString(platform); + expect(ua).toEqual('stubClient/?'); + }); + + it('uses platform user-agent and platform version if provided', () => { + const platform = stubPlatform.defaults(); + platform.version = '7.8.9'; + const ua = getLDUserAgentString(platform); + expect(ua).toEqual('stubClient/7.8.9'); + }); + }); + + it('when using once the original function is only called once', () => { + let count = 0; + const fn = once(() => { + count++; + return count; + }); + + expect(fn()).toBe(1); + expect(fn()).toBe(1); + expect(fn()).toBe(1); + expect(count).toBe(1); + }); + + it('once works with async functions', async () => { + let count = 0; + const fn = once(async () => { + count++; + return count; + }); + + const result1 = await fn(); + const result2 = await fn(); + const result3 = await fn(); + + expect(result1).toBe(1); + expect(result2).toBe(1); + expect(result3).toBe(1); + expect(count).toBe(1); + }); +}); diff --git a/node_modules/launchdarkly-js-sdk-common/src/attributeReference.js b/node_modules/launchdarkly-js-sdk-common/src/attributeReference.js new file mode 100644 index 00000000..e3921de8 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/attributeReference.js @@ -0,0 +1,143 @@ +/** + * Take a key string and escape the characters to allow it to be used as a reference. + * @param {string} key + * @returns {string} The processed key. + */ +function processEscapeCharacters(key) { + return key.replace(/~/g, '~0').replace(/\//g, '~1'); +} + +/** + * @param {string} reference The reference to get the components of. + * @returns {string[]} The components of the reference. Escape characters will be converted to their representative values. + */ +function getComponents(reference) { + const referenceWithoutPrefix = reference.startsWith('/') ? reference.substring(1) : reference; + return referenceWithoutPrefix + .split('/') + .map(component => (component.indexOf('~') >= 0 ? component.replace(/~1/g, '/').replace(/~0/g, '~') : component)); +} + +/** + * @param {string} reference The reference to check if it is a literal. + * @returns true if the reference is a literal. + */ +function isLiteral(reference) { + return !reference.startsWith('/'); +} + +/** + * Compare two references and determine if they are equivalent. + * @param {string} a + * @param {string} b + */ +function compare(a, b) { + const aIsLiteral = isLiteral(a); + const bIsLiteral = isLiteral(b); + if (aIsLiteral && bIsLiteral) { + return a === b; + } + if (aIsLiteral) { + const bComponents = getComponents(b); + if (bComponents.length !== 1) { + return false; + } + return a === bComponents[0]; + } + if (bIsLiteral) { + const aComponents = getComponents(a); + if (aComponents.length !== 1) { + return false; + } + return b === aComponents[0]; + } + return a === b; +} + +/** + * @param {string} a + * @param {string} b + * @returns The two strings joined by '/'. + */ +function join(a, b) { + return `${a}/${b}`; +} + +/** + * There are cases where a field could have been named with a preceeding '/'. + * If that attribute was private, then the literal would appear to be a reference. + * This method can be used to convert a literal to a reference in such situations. + * @param {string} literal The literal to convert to a reference. + * @returns A literal which has been converted to a reference. + */ +function literalToReference(literal) { + return `/${processEscapeCharacters(literal)}`; +} + +/** + * Clone an object excluding the values referenced by a list of references. + * @param {Object} target The object to clone. + * @param {string[]} references A list of references from the cloned object. + * @returns {{cloned: Object, excluded: string[]}} The cloned object and a list of excluded values. + */ +function cloneExcluding(target, references) { + const stack = []; + const cloned = {}; + const excluded = []; + + stack.push( + ...Object.keys(target).map(key => ({ + key, + ptr: literalToReference(key), + source: target, + parent: cloned, + visited: [target], + })) + ); + + while (stack.length) { + const item = stack.pop(); + if (!references.some(ptr => compare(ptr, item.ptr))) { + const value = item.source[item.key]; + + // Handle null because it overlaps with object, which we will want to handle later. + if (value === null) { + item.parent[item.key] = value; + } else if (Array.isArray(value)) { + item.parent[item.key] = [...value]; + } else if (typeof value === 'object') { + //Arrays and null must already be handled. + + //Prevent cycles by not visiting the same object + //with in the same branch. Parallel branches + //may contain the same object. + if (item.visited.includes(value)) { + continue; + } + + item.parent[item.key] = {}; + + stack.push( + ...Object.keys(value).map(key => ({ + key, + ptr: join(item.ptr, processEscapeCharacters(key)), + source: value, + parent: item.parent[item.key], + visited: [...item.visited, value], + })) + ); + } else { + item.parent[item.key] = value; + } + } else { + excluded.push(item.ptr); + } + } + return { cloned, excluded: excluded.sort() }; +} + +module.exports = { + cloneExcluding, + compare, + literalToReference, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/canonicalize.js b/node_modules/launchdarkly-js-sdk-common/src/canonicalize.js new file mode 100644 index 00000000..b9878373 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/canonicalize.js @@ -0,0 +1,41 @@ +/** + * Given some object to serialize product a canonicalized JSON string. + * https://www.rfc-editor.org/rfc/rfc8785.html + * + * We do not support custom toJSON methods on objects. Objects should be limited to basic types. + * + * @param {any} object The object to serialize. + * @param {any[]?} visited The list of objects that have already been visited to avoid cycles. + * @returns {string} The canonicalized JSON string. + */ +function canonicalize(object, visited = []) { + // For JavaScript the default JSON serialization will produce canonicalized output for basic types. + if (object === null || typeof object !== 'object') { + return JSON.stringify(object); + } + + if (visited.includes(object)) { + throw new Error('Cycle detected'); + } + + if (Array.isArray(object)) { + const values = object + .map(item => canonicalize(item, [...visited, object])) + .map(item => (item === undefined ? 'null' : item)); + return `[${values.join(',')}]`; + } + + const values = Object.keys(object) + .sort() + .map(key => { + const value = canonicalize(object[key], [...visited, object]); + if (value !== undefined) { + return `${JSON.stringify(key)}:${value}`; + } + return undefined; + }) + .filter(item => item !== undefined); + return `{${values.join(',')}}`; +} + +module.exports = canonicalize; diff --git a/node_modules/launchdarkly-js-sdk-common/src/configuration.js b/node_modules/launchdarkly-js-sdk-common/src/configuration.js new file mode 100644 index 00000000..617f5286 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/configuration.js @@ -0,0 +1,225 @@ +const errors = require('./errors'); +const { validateLogger } = require('./loggers'); +const messages = require('./messages'); +const utils = require('./utils'); + +// baseOptionDefs should contain an entry for each supported configuration option in the common package. +// Each entry can have three properties: +// - "default": the default value if any +// - "type": a type constraint used if the type can't be inferred from the default value). The allowable +// values are "boolean", "string", "number", "array", "object", "function", or several of these OR'd +// together with "|" ("function|object"). +// - "minimum": minimum value if any for numeric properties +// +// The extraOptionDefs parameter to validate() uses the same format. +const baseOptionDefs = { + baseUrl: { default: 'https://app.launchdarkly.com' }, + streamUrl: { default: 'https://clientstream.launchdarkly.com' }, + eventsUrl: { default: 'https://events.launchdarkly.com' }, + sendEvents: { default: true }, + streaming: { type: 'boolean' }, // default for this is undefined, which is different from false + sendLDHeaders: { default: true }, + requestHeaderTransform: { type: 'function' }, + sendEventsOnlyForVariation: { default: false }, + useReport: { default: false }, + evaluationReasons: { default: false }, + eventCapacity: { default: 100, minimum: 1 }, + flushInterval: { default: 2000, minimum: 2000 }, + samplingInterval: { default: 0, minimum: 0 }, + streamReconnectDelay: { default: 1000, minimum: 0 }, + allAttributesPrivate: { default: false }, + privateAttributes: { default: [] }, + bootstrap: { type: 'string|object' }, + diagnosticRecordingInterval: { default: 900000, minimum: 2000 }, + diagnosticOptOut: { default: false }, + wrapperName: { type: 'string' }, + wrapperVersion: { type: 'string' }, + stateProvider: { type: 'object' }, // not a public option, used internally + application: { validator: applicationConfigValidator }, + inspectors: { default: [] }, + hooks: { default: [] }, + plugins: { default: [] }, +}; + +/** + * Expression to validate characters that are allowed in tag keys and values. + */ +const allowedTagCharacters = /^(\w|\.|-)+$/; + +function canonicalizeUrl(url) { + return url && url.replace(/\/+$/, ''); +} + +/** + * Verify that a value meets the requirements for a tag value. + * @param {string} tagValue + * @param {Object} logger + */ +function validateTagValue(name, tagValue, logger) { + if (typeof tagValue !== 'string' || !tagValue.match(allowedTagCharacters)) { + logger.warn(messages.invalidTagValue(name)); + return undefined; + } + if (tagValue.length > 64) { + logger.warn(messages.tagValueTooLong(name)); + return undefined; + } + return tagValue; +} + +function applicationConfigValidator(name, value, logger) { + const validated = {}; + if (value.id) { + validated.id = validateTagValue(`${name}.id`, value.id, logger); + } + if (value.version) { + validated.version = validateTagValue(`${name}.version`, value.version, logger); + } + return validated; +} + +function validate(options, emitter, extraOptionDefs, logger) { + const optionDefs = utils.extend({ logger: { default: logger } }, baseOptionDefs, extraOptionDefs); + + const deprecatedOptions = { + // As of the latest major version, there are no deprecated options. Next time we deprecate + // something, add an item here where the property name is the deprecated name, and the + // property value is the preferred name if any, or null/undefined if there is no replacement. + }; + + function checkDeprecatedOptions(config) { + const opts = config; + Object.keys(deprecatedOptions).forEach(oldName => { + if (opts[oldName] !== undefined) { + const newName = deprecatedOptions[oldName]; + logger && logger.warn(messages.deprecated(oldName, newName)); + if (newName) { + if (opts[newName] === undefined) { + opts[newName] = opts[oldName]; + } + delete opts[oldName]; + } + } + }); + } + + function applyDefaults(config) { + // This works differently from utils.extend() in that it *will not* override a default value + // if the provided value is explicitly set to null. This provides backward compatibility + // since in the past we only used the provided values if they were truthy. + const ret = utils.extend({}, config); + Object.keys(optionDefs).forEach(name => { + if (ret[name] === undefined || ret[name] === null) { + ret[name] = optionDefs[name] && optionDefs[name].default; + } + }); + return ret; + } + + function validateTypesAndNames(config) { + const ret = utils.extend({}, config); + const typeDescForValue = value => { + if (value === null) { + return 'any'; + } + if (value === undefined) { + return undefined; + } + if (Array.isArray(value)) { + return 'array'; + } + const t = typeof value; + if (t === 'boolean' || t === 'string' || t === 'number' || t === 'function') { + return t; + } + return 'object'; + }; + Object.keys(config).forEach(name => { + const value = config[name]; + if (value !== null && value !== undefined) { + const optionDef = optionDefs[name]; + if (optionDef === undefined) { + reportArgumentError(messages.unknownOption(name)); + } else { + const expectedType = optionDef.type || typeDescForValue(optionDef.default); + const validator = optionDef.validator; + if (validator) { + const validated = validator(name, config[name], logger); + if (validated !== undefined) { + ret[name] = validated; + } else { + delete ret[name]; + } + } else if (expectedType !== 'any') { + const allowedTypes = expectedType.split('|'); + const actualType = typeDescForValue(value); + if (allowedTypes.indexOf(actualType) < 0) { + if (expectedType === 'boolean') { + ret[name] = !!value; + reportArgumentError(messages.wrongOptionTypeBoolean(name, actualType)); + } else { + reportArgumentError(messages.wrongOptionType(name, expectedType, actualType)); + ret[name] = optionDef.default; + } + } else { + if (actualType === 'number' && optionDef.minimum !== undefined && value < optionDef.minimum) { + reportArgumentError(messages.optionBelowMinimum(name, value, optionDef.minimum)); + ret[name] = optionDef.minimum; + } + } + } + } + } + }); + + ret.baseUrl = canonicalizeUrl(ret.baseUrl); + ret.streamUrl = canonicalizeUrl(ret.streamUrl); + ret.eventsUrl = canonicalizeUrl(ret.eventsUrl); + + return ret; + } + + function reportArgumentError(message) { + utils.onNextTick(() => { + emitter && emitter.maybeReportError(new errors.LDInvalidArgumentError(message)); + }); + } + + let config = utils.extend({}, options || {}); + + checkDeprecatedOptions(config); + + config = applyDefaults(config); + config = validateTypesAndNames(config); + validateLogger(config.logger); + + return config; +} + +/** + * Get tags for the specified configuration. + * + * If any additional tags are added to the configuration, then the tags from + * this method should be extended with those. + * @param {Object} config The already valiated configuration. + * @returns {Object} The tag configuration. + */ +function getTags(config) { + const tags = {}; + if (config) { + if (config.application && config.application.id !== undefined && config.application.id !== null) { + tags['application-id'] = [config.application.id]; + } + if (config.application && config.application.version !== undefined && config.application.id !== null) { + tags['application-version'] = [config.application.version]; + } + } + + return tags; +} + +module.exports = { + baseOptionDefs, + validate, + getTags, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/context.js b/node_modules/launchdarkly-js-sdk-common/src/context.js new file mode 100644 index 00000000..40ed20cf --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/context.js @@ -0,0 +1,134 @@ +const { commonBasicLogger } = require('./loggers'); + +/** + * Validate a context kind. + * @param {string} kind + * @returns true if the kind is valid. + */ +function validKind(kind) { + return typeof kind === 'string' && kind !== 'kind' && kind.match(/^(\w|\.|-)+$/); +} + +/** + * Perform a check of basic context requirements. + * @param {Object} context + * @param {boolean} allowLegacyKey If true, then a legacy user can have an + * empty or non-string key. A legacy user is a context without a kind. + * @returns true if the context meets basic requirements. + */ +function checkContext(context, allowLegacyKey) { + if (context) { + if (allowLegacyKey && (context.kind === undefined || context.kind === null)) { + return context.key !== undefined && context.key !== null; + } + const key = context.key; + const kind = context.kind === undefined ? 'user' : context.kind; + const kindValid = validKind(kind); + const keyValid = kind === 'multi' || (key !== undefined && key !== null && key !== ''); + if (kind === 'multi') { + const kinds = Object.keys(context).filter(key => key !== 'kind'); + return ( + keyValid && + kinds.every(key => validKind(key)) && + kinds.every(key => { + const contextKey = context[key].key; + return contextKey !== undefined && contextKey !== null && contextKey !== ''; + }) + ); + } + return keyValid && kindValid; + } + return false; +} + +/** + * For a given context get a list of context kinds. + * @param {Object} context + * @returns {string[]} A list of kinds in the context. + */ +function getContextKinds(context) { + if (context) { + if (context.kind === null || context.kind === undefined) { + return ['user']; + } + if (context.kind !== 'multi') { + return [context.kind]; + } + return Object.keys(context).filter(kind => kind !== 'kind'); + } + return []; +} + +/** + * The partial URL encoding is needed because : is a valid character in context keys. + * + * Partial encoding is the replacement of all colon (:) characters with the URL + * encoded equivalent (%3A) and all percent (%) characters with the URL encoded + * equivalent (%25). + * @param {string} key The key to encode. + * @returns {string} Partially URL encoded key. + */ +function encodeKey(key) { + if (key.includes('%') || key.includes(':')) { + return key.replace(/%/g, '%25').replace(/:/g, '%3A'); + } + return key; +} + +function getCanonicalKey(context) { + if (context) { + if ((context.kind === undefined || context.kind === null || context.kind === 'user') && context.key) { + return context.key; + } else if (context.kind !== 'multi' && context.key) { + return `${context.kind}:${encodeKey(context.key)}`; + } else if (context.kind === 'multi') { + return Object.keys(context) + .sort() + .filter(key => key !== 'kind') + .map(key => `${key}:${encodeKey(context[key].key)}`) + .join(':'); + } + } +} + +function getContextKeys(context, logger = commonBasicLogger()) { + if (!context) { + return undefined; + } + + const keys = {}; + const { kind, key } = context; + + switch (kind) { + case undefined: + keys.user = `${key}`; + break; + case 'multi': + Object.entries(context) + .filter(([key]) => key !== 'kind') + .forEach(([key, value]) => { + if (value && value.key) { + keys[key] = value.key; + } + }); + break; + case null: + logger.warn(`null is not a valid context kind: ${context}`); + break; + case '': + logger.warn(`'' is not a valid context kind: ${context}`); + break; + default: + keys[kind] = `${key}`; + break; + } + + return keys; +} + +module.exports = { + checkContext, + getContextKeys, + getContextKinds, + getCanonicalKey, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/diagnosticEvents.js b/node_modules/launchdarkly-js-sdk-common/src/diagnosticEvents.js new file mode 100644 index 00000000..4d7ad19b --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/diagnosticEvents.js @@ -0,0 +1,267 @@ +const { v1: uuidv1 } = require('uuid'); +// Note that in the diagnostic events spec, these IDs are to be generated with UUID v4. However, +// in JS we were already using v1 for unique context keys, so to avoid bringing in two packages we +// will use v1 here as well. + +const { baseOptionDefs } = require('./configuration'); +const messages = require('./messages'); +const { appendUrlPath } = require('./utils'); + +function DiagnosticId(sdkKey) { + const ret = { + diagnosticId: uuidv1(), + }; + if (sdkKey) { + ret.sdkKeySuffix = sdkKey.length > 6 ? sdkKey.substring(sdkKey.length - 6) : sdkKey; + } + return ret; +} + +// A stateful object holding statistics that will go into diagnostic events. + +function DiagnosticsAccumulator(startTime) { + let dataSinceDate, droppedEvents, eventsInLastBatch, streamInits; + + function reset(time) { + dataSinceDate = time; + droppedEvents = 0; + eventsInLastBatch = 0; + streamInits = []; + } + + reset(startTime); + + return { + getProps: () => ({ + dataSinceDate, + droppedEvents, + eventsInLastBatch, + streamInits, + // omit deduplicatedUsers for the JS SDKs because they don't deduplicate users + }), + setProps: props => { + dataSinceDate = props.dataSinceDate; + droppedEvents = props.droppedEvents || 0; + eventsInLastBatch = props.eventsInLastBatch || 0; + streamInits = props.streamInits || []; + }, + incrementDroppedEvents: () => { + droppedEvents++; + }, + setEventsInLastBatch: n => { + eventsInLastBatch = n; + }, + recordStreamInit: (timestamp, failed, durationMillis) => { + const info = { timestamp, failed, durationMillis }; + streamInits.push(info); + }, + reset, + }; +} + +// An object that maintains information that will go into diagnostic events, and knows how to format +// those events. It is instantiated by the SDK client, and shared with the event processor. +// +// The JS-based SDKs have two modes for diagnostic events. By default, the behavior is basically the +// same as the server-side SDKs: a "diagnostic-init" event is sent on startup, and then "diagnostic" +// events with operating statistics are sent periodically. However, in a browser environment this is +// undesirable because the page may be reloaded frequently. In that case, setting the property +// "platform.diagnosticUseCombinedEvent" to true enables an alternate mode in which a combination of +// both kinds of event is sent at intervals, relative to the last time this was done (if any) which +// is cached in local storage. + +function DiagnosticsManager( + platform, + persistentStorage, + accumulator, + eventSender, + environmentId, + config, + diagnosticId +) { + const combinedMode = !!platform.diagnosticUseCombinedEvent; + const localStorageKey = 'ld:' + environmentId + ':$diagnostics'; + const diagnosticEventsUrl = appendUrlPath(config.eventsUrl, '/events/diagnostic/' + environmentId); + const periodicInterval = config.diagnosticRecordingInterval; + const acc = accumulator; + const initialEventSamplingInterval = 4; // used only in combined mode - see start() + let streamingEnabled = !!config.streaming; + let eventSentTime; + let periodicTimer; + const manager = {}; + + function makeInitProperties() { + return { + sdk: makeSdkData(), + configuration: makeConfigData(), + platform: platform.diagnosticPlatformData, + }; + } + + // Send a diagnostic event and do not wait for completion. + function sendDiagnosticEvent(event) { + config.logger && config.logger.debug(messages.debugPostingDiagnosticEvent(event)); + eventSender + .sendEvents(event, diagnosticEventsUrl, true) + .then(() => undefined) + .catch(() => undefined); + } + + function loadProperties(callback) { + if (!persistentStorage.isEnabled()) { + return callback(false); // false indicates that local storage is not available + } + persistentStorage + .get(localStorageKey) + .then(data => { + if (data) { + try { + const props = JSON.parse(data); + acc.setProps(props); + eventSentTime = props.dataSinceDate; + } catch (e) { + // disregard malformed cached data + } + } + callback(true); + }) + .catch(() => { + callback(false); + }); + } + + function saveProperties() { + if (persistentStorage.isEnabled()) { + const props = { ...acc.getProps() }; + persistentStorage.set(localStorageKey, JSON.stringify(props)); + } + } + + // Creates the initial event that is sent by the event processor when the SDK starts up. This will not + // be repeated during the lifetime of the SDK client. In combined mode, we don't send this. + function createInitEvent() { + return { + kind: 'diagnostic-init', + id: diagnosticId, + creationDate: acc.getProps().dataSinceDate, + ...makeInitProperties(), + }; + } + + // Creates a periodic event containing time-dependent stats, and resets the state of the manager with + // regard to those stats. In combined mode (browser SDK) this also contains the configuration data. + function createPeriodicEventAndReset() { + const currentTime = new Date().getTime(); + let ret = { + kind: combinedMode ? 'diagnostic-combined' : 'diagnostic', + id: diagnosticId, + creationDate: currentTime, + ...acc.getProps(), + }; + if (combinedMode) { + ret = { ...ret, ...makeInitProperties() }; + } + acc.reset(currentTime); + return ret; + } + + function sendPeriodicEvent() { + sendDiagnosticEvent(createPeriodicEventAndReset()); + periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval); + eventSentTime = new Date().getTime(); + if (combinedMode) { + saveProperties(); + } + } + + function makeSdkData() { + const sdkData = { ...platform.diagnosticSdkData }; + if (config.wrapperName) { + sdkData.wrapperName = config.wrapperName; + } + if (config.wrapperVersion) { + sdkData.wrapperVersion = config.wrapperVersion; + } + return sdkData; + } + + function makeConfigData() { + const configData = { + customBaseURI: config.baseUrl !== baseOptionDefs.baseUrl.default, + customStreamURI: config.streamUrl !== baseOptionDefs.streamUrl.default, + customEventsURI: config.eventsUrl !== baseOptionDefs.eventsUrl.default, + eventsCapacity: config.eventCapacity, + eventsFlushIntervalMillis: config.flushInterval, + reconnectTimeMillis: config.streamReconnectDelay, + streamingDisabled: !streamingEnabled, + allAttributesPrivate: !!config.allAttributesPrivate, + diagnosticRecordingIntervalMillis: config.diagnosticRecordingInterval, + // The following extra properties are only provided by client-side JS SDKs: + usingSecureMode: !!config.hash, + bootstrapMode: !!config.bootstrap, + fetchGoalsDisabled: !config.fetchGoals, + sendEventsOnlyForVariation: !!config.sendEventsOnlyForVariation, + }; + // Client-side JS SDKs do not have the following properties which other SDKs have: + // connectTimeoutMillis + // pollingIntervalMillis + // samplingInterval + // socketTimeoutMillis + // startWaitMillis + // userKeysCapacity + // userKeysFlushIntervalMillis + // usingProxy + // usingProxyAuthenticator + // usingRelayDaemon + + return configData; + } + + // Called when the SDK is starting up. Either send an init event immediately, or, in the alternate + // mode, check for cached local storage properties and send an event only if we haven't done so + // recently. + manager.start = () => { + if (combinedMode) { + loadProperties(localStorageAvailable => { + if (localStorageAvailable) { + const nextEventTime = (eventSentTime || 0) + periodicInterval; + const timeNow = new Date().getTime(); + if (timeNow >= nextEventTime) { + sendPeriodicEvent(); + } else { + periodicTimer = setTimeout(sendPeriodicEvent, nextEventTime - timeNow); + } + } else { + // We don't have the ability to cache anything in local storage, so we don't know if we + // recently sent an event before this page load, but we would still prefer not to send one + // on *every* page load. So, as a rough heuristic, we'll decide semi-randomly. + if (Math.floor(Math.random() * initialEventSamplingInterval) === 0) { + sendPeriodicEvent(); + } else { + periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval); + } + } + }); + } else { + sendDiagnosticEvent(createInitEvent()); + periodicTimer = setTimeout(sendPeriodicEvent, periodicInterval); + } + }; + + manager.stop = () => { + periodicTimer && clearTimeout(periodicTimer); + }; + + // Called when streaming mode is turned on or off dynamically. + manager.setStreaming = enabled => { + streamingEnabled = enabled; + }; + + return manager; +} + +module.exports = { + DiagnosticId, + DiagnosticsAccumulator, + DiagnosticsManager, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/errors.js b/node_modules/launchdarkly-js-sdk-common/src/errors.js new file mode 100644 index 00000000..75b69277 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/errors.js @@ -0,0 +1,41 @@ +function createCustomError(name) { + function CustomError(message, code) { + Error.captureStackTrace && Error.captureStackTrace(this, this.constructor); + this.message = message; + this.code = code; + } + + CustomError.prototype = new Error(); + CustomError.prototype.name = name; + CustomError.prototype.constructor = CustomError; + + return CustomError; +} + +const LDUnexpectedResponseError = createCustomError('LaunchDarklyUnexpectedResponseError'); +const LDInvalidEnvironmentIdError = createCustomError('LaunchDarklyInvalidEnvironmentIdError'); +const LDInvalidUserError = createCustomError('LaunchDarklyInvalidUserError'); +const LDInvalidEventKeyError = createCustomError('LaunchDarklyInvalidEventKeyError'); +const LDInvalidArgumentError = createCustomError('LaunchDarklyInvalidArgumentError'); +const LDFlagFetchError = createCustomError('LaunchDarklyFlagFetchError'); +const LDInvalidDataError = createCustomError('LaunchDarklyInvalidDataError'); +const LDTimeoutError = createCustomError('LaunchDarklyTimeoutError'); + +function isHttpErrorRecoverable(status) { + if (status >= 400 && status < 500) { + return status === 400 || status === 408 || status === 429; + } + return true; +} + +module.exports = { + LDUnexpectedResponseError, + LDInvalidEnvironmentIdError, + LDInvalidUserError, + LDInvalidEventKeyError, + LDInvalidArgumentError, + LDInvalidDataError, + LDFlagFetchError, + LDTimeoutError, + isHttpErrorRecoverable, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/headers.js b/node_modules/launchdarkly-js-sdk-common/src/headers.js new file mode 100644 index 00000000..3c47999a --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/headers.js @@ -0,0 +1,39 @@ +const { getLDUserAgentString } = require('./utils'); +const configuration = require('./configuration'); + +function getLDHeaders(platform, options) { + if (options && !options.sendLDHeaders) { + return {}; + } + const h = {}; + h[platform.userAgentHeaderName || 'User-Agent'] = getLDUserAgentString(platform); + if (options && options.wrapperName) { + h['X-LaunchDarkly-Wrapper'] = options.wrapperVersion + ? options.wrapperName + '/' + options.wrapperVersion + : options.wrapperName; + } + const tags = configuration.getTags(options); + const tagKeys = Object.keys(tags); + if (tagKeys.length) { + h['x-launchdarkly-tags'] = tagKeys + .sort() + .map(key => + Array.isArray(tags[key]) ? tags[key].sort().map(value => `${key}/${value}`) : [`${key}/${tags[key]}`] + ) + .reduce((flattened, item) => flattened.concat(item), []) + .join(' '); + } + return h; +} + +function transformHeaders(headers, options) { + if (!options || !options.requestHeaderTransform) { + return headers; + } + return options.requestHeaderTransform({ ...headers }); +} + +module.exports = { + getLDHeaders, + transformHeaders, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/index.js b/node_modules/launchdarkly-js-sdk-common/src/index.js new file mode 100644 index 00000000..86d67526 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/index.js @@ -0,0 +1,905 @@ +const EventProcessor = require('./EventProcessor'); +const EventEmitter = require('./EventEmitter'); +const EventSender = require('./EventSender'); +const InitializationStateTracker = require('./InitializationState'); +const PersistentFlagStore = require('./PersistentFlagStore'); +const PersistentStorage = require('./PersistentStorage'); +const Stream = require('./Stream'); +const Requestor = require('./Requestor'); +const Identity = require('./Identity'); +const AnonymousContextProcessor = require('./AnonymousContextProcessor'); +const configuration = require('./configuration'); +const diagnostics = require('./diagnosticEvents'); +const { commonBasicLogger } = require('./loggers'); +const utils = require('./utils'); +const errors = require('./errors'); +const messages = require('./messages'); +const { checkContext, getContextKeys } = require('./context'); +const { InspectorTypes, InspectorManager } = require('./InspectorManager'); +const timedPromise = require('./timedPromise'); +const createHookRunner = require('./HookRunner'); +const { getPluginHooks, registerPlugins, createPluginEnvironment } = require('./plugins'); +const changeEvent = 'change'; +const internalChangeEvent = 'internal-change'; +const highTimeoutThreshold = 5; + +// This is called by the per-platform initialize functions to create the base client object that we +// may also extend with additional behavior. It returns an object with these properties: +// client: the actual client object +// options: the configuration (after any appropriate defaults have been applied) +// If we need to give the platform-specific clients access to any internals here, we should add those +// as properties of the return object, not public properties of the client. +// +// For definitions of the API in the platform object, see stubPlatform.js in the test code. + +function initialize(env, context, specifiedOptions, platform, extraOptionDefs) { + const logger = createLogger(); + const emitter = EventEmitter(logger); + const initializationStateTracker = InitializationStateTracker(emitter); + const options = configuration.validate(specifiedOptions, emitter, extraOptionDefs, logger); + const inspectorManager = InspectorManager(options.inspectors, logger); + const sendEvents = options.sendEvents; + let environment = env; + let hash = options.hash; + const plugins = [...options.plugins]; + + const pluginEnvironment = createPluginEnvironment(platform, env, options); + + const pluginHooks = getPluginHooks(logger, pluginEnvironment, plugins); + + const hookRunner = createHookRunner(logger, [...options.hooks, ...pluginHooks]); + + const persistentStorage = PersistentStorage(platform.localStorage, logger); + + const eventSender = EventSender(platform, environment, options); + + const diagnosticsEnabled = options.sendEvents && !options.diagnosticOptOut; + const diagnosticId = diagnosticsEnabled ? diagnostics.DiagnosticId(environment) : null; + const diagnosticsAccumulator = diagnosticsEnabled ? diagnostics.DiagnosticsAccumulator(new Date().getTime()) : null; + const diagnosticsManager = diagnosticsEnabled + ? diagnostics.DiagnosticsManager( + platform, + persistentStorage, + diagnosticsAccumulator, + eventSender, + environment, + options, + diagnosticId + ) + : null; + + const stream = Stream(platform, options, environment, diagnosticsAccumulator); + + const events = + options.eventProcessor || + EventProcessor(platform, options, environment, diagnosticsAccumulator, emitter, eventSender); + + const requestor = Requestor(platform, options, environment); + + let flags = {}; + let useLocalStorage; + let streamActive; + let streamForcedState = options.streaming; + let subscribedToChangeEvents; + let inited = false; + let closed = false; + let firstEvent = true; + + // The "stateProvider" object is used in the Electron SDK, to allow one client instance to take partial + // control of another. If present, it has the following contract: + // - getInitialState() returns the initial client state if it is already available. The state is an + // object whose properties are "environment", "context", and "flags". + // - on("init", listener) triggers an event when the initial client state becomes available, passing + // the state object to the listener. + // - on("update", listener) triggers an event when flag values change and/or the current context changes. + // The parameter is an object that *may* contain "context" and/or "flags". + // - enqueueEvent(event) accepts an analytics event object and returns true if the stateProvider will + // be responsible for delivering it, or false if we still should deliver it ourselves. + const stateProvider = options.stateProvider; + + const ident = Identity(null, onIdentifyChange); + const anonymousContextProcessor = new AnonymousContextProcessor(persistentStorage); + const persistentFlagStore = persistentStorage.isEnabled() + ? PersistentFlagStore(persistentStorage, environment, hash, ident, logger) + : null; + + function createLogger() { + if (specifiedOptions && specifiedOptions.logger) { + return specifiedOptions.logger; + } + return (extraOptionDefs && extraOptionDefs.logger && extraOptionDefs.logger.default) || commonBasicLogger('warn'); + } + + function readFlagsFromBootstrap(data) { + // If the bootstrap data came from an older server-side SDK, we'll have just a map of keys to values. + // Newer SDKs that have an allFlagsState method will provide an extra "$flagsState" key that contains + // the rest of the metadata we want. We do it this way for backward compatibility with older JS SDKs. + const keys = Object.keys(data); + const metadataKey = '$flagsState'; + const validKey = '$valid'; + const metadata = data[metadataKey]; + if (!metadata && keys.length) { + logger.warn(messages.bootstrapOldFormat()); + } + if (data[validKey] === false) { + logger.warn(messages.bootstrapInvalid()); + } + const ret = {}; + keys.forEach(key => { + if (key !== metadataKey && key !== validKey) { + let flag = { value: data[key] }; + if (metadata && metadata[key]) { + flag = utils.extend(flag, metadata[key]); + } else { + flag.version = 0; + } + ret[key] = flag; + } + }); + return ret; + } + + function shouldEnqueueEvent() { + return sendEvents && !closed && !platform.isDoNotTrack(); + } + + function enqueueEvent(event) { + if (!environment) { + // We're in paired mode and haven't been initialized with an environment or context yet + return; + } + if (stateProvider && stateProvider.enqueueEvent && stateProvider.enqueueEvent(event)) { + return; // it'll be handled elsewhere + } + + if (!event.context) { + if (firstEvent) { + logger.warn(messages.eventWithoutContext()); + firstEvent = false; + } + return; + } + firstEvent = false; + + if (shouldEnqueueEvent()) { + logger.debug(messages.debugEnqueueingEvent(event.kind)); + events.enqueue(event); + } + } + + function notifyInspectionFlagUsed(key, detail) { + if (inspectorManager.hasListeners(InspectorTypes.flagUsed)) { + inspectorManager.onFlagUsed(key, detail, ident.getContext()); + } + } + + function notifyInspectionIdentityChanged() { + if (inspectorManager.hasListeners(InspectorTypes.clientIdentityChanged)) { + inspectorManager.onIdentityChanged(ident.getContext()); + } + } + + function notifyInspectionFlagChanged(data, newFlag) { + if (inspectorManager.hasListeners(InspectorTypes.flagDetailChanged)) { + inspectorManager.onFlagChanged(data.key, getFlagDetail(newFlag)); + } + } + + function notifyInspectionFlagsChanged() { + if (inspectorManager.hasListeners(InspectorTypes.flagDetailsChanged)) { + inspectorManager.onFlags( + Object.entries(flags) + .map(([key, value]) => ({ key, detail: getFlagDetail(value) })) + .reduce((acc, cur) => { + // eslint-disable-next-line no-param-reassign + acc[cur.key] = cur.detail; + return acc; + }, {}) + ); + } + } + + function onIdentifyChange(context) { + sendIdentifyEvent(context); + notifyInspectionIdentityChanged(); + } + + function sendIdentifyEvent(context) { + if (stateProvider) { + // In paired mode, the other client is responsible for sending identify events + return; + } + if (context) { + enqueueEvent({ + kind: 'identify', + context, + creationDate: new Date().getTime(), + }); + } + } + + function sendFlagEvent(key, detail, defaultValue, includeReason) { + const context = ident.getContext(); + const now = new Date(); + const value = detail ? detail.value : null; + + const event = { + kind: 'feature', + key: key, + context, + value: value, + variation: detail ? detail.variationIndex : null, + default: defaultValue, + creationDate: now.getTime(), + }; + const flag = flags[key]; + if (flag) { + event.version = flag.flagVersion ? flag.flagVersion : flag.version; + event.trackEvents = flag.trackEvents; + event.debugEventsUntilDate = flag.debugEventsUntilDate; + } + if ((includeReason || (flag && flag.trackReason)) && detail) { + event.reason = detail.reason; + } + + enqueueEvent(event); + } + + function verifyContext(context) { + // The context will already have been processed to have a string key, so we + // do not need to allow for legacy keys in the check. + if (checkContext(context, false)) { + return Promise.resolve(context); + } else { + return Promise.reject(new errors.LDInvalidUserError(messages.invalidContext())); + } + } + + function identify(context, newHash, onDone) { + if (closed) { + return utils.wrapPromiseCallback(Promise.resolve({}), onDone); + } + if (stateProvider) { + // We're being controlled by another client instance, so only that instance is allowed to change the context + logger.warn(messages.identifyDisabled()); + return utils.wrapPromiseCallback(Promise.resolve(utils.transformVersionedValuesToValues(flags)), onDone); + } + let afterIdentify; + const clearFirst = useLocalStorage && persistentFlagStore ? persistentFlagStore.clearFlags() : Promise.resolve(); + return utils.wrapPromiseCallback( + clearFirst + .then(() => anonymousContextProcessor.processContext(context)) + .then(verifyContext) + .then(context => { + afterIdentify = utils.once(hookRunner.identify(context, undefined)); + return context; + }) + .then(validatedContext => + requestor + .fetchFlagSettings(validatedContext, newHash) + // the following then() is nested within this one so we can use realUser from the previous closure + .then(requestedFlags => { + const flagValueMap = utils.transformVersionedValuesToValues(requestedFlags); + ident.setContext(validatedContext); + hash = newHash; + if (requestedFlags) { + return replaceAllFlags(requestedFlags).then(() => flagValueMap); + } else { + return flagValueMap; + } + }) + ) + .then(flagValueMap => { + afterIdentify?.({ status: 'completed' }); + if (streamActive) { + connectStream(); + } + return flagValueMap; + }) + .catch(err => { + afterIdentify?.({ status: 'error' }); + emitter.maybeReportError(err); + return Promise.reject(err); + }), + onDone + ); + } + + function getContext() { + return ident.getContext(); + } + + function flush(onDone) { + return utils.wrapPromiseCallback(sendEvents ? events.flush() : Promise.resolve(), onDone); + } + + function variation(key, defaultValue) { + const { value } = hookRunner.withEvaluation(key, ident.getContext(), defaultValue, () => + variationDetailInternal(key, defaultValue, true, false, false, true) + ); + return value; + } + + function variationDetail(key, defaultValue) { + return hookRunner.withEvaluation(key, ident.getContext(), defaultValue, () => + variationDetailInternal(key, defaultValue, true, true, false, true) + ); + } + + function variationDetailInternal(key, defaultValue, sendEvent, includeReasonInEvent, isAllFlags, notifyInspection) { + let detail; + let flag; + + if (flags && utils.objectHasOwnProperty(flags, key) && flags[key] && !flags[key].deleted) { + flag = flags[key]; + detail = getFlagDetail(flag); + if (flag.value === null || flag.value === undefined) { + detail.value = defaultValue; + } + } else { + detail = { value: defaultValue, variationIndex: null, reason: { kind: 'ERROR', errorKind: 'FLAG_NOT_FOUND' } }; + } + + if (sendEvent) { + // For an all-flags evaluation, with events enabled, each flag will get an event, so we do not + // need to duplicate the prerequisites. + if (!isAllFlags) { + flag?.prerequisites?.forEach(key => { + variationDetailInternal(key, undefined, sendEvent, false, false, false); + }); + } + sendFlagEvent(key, detail, defaultValue, includeReasonInEvent); + } + + // For the all flags case `onFlags` will be called instead. + if (!isAllFlags && notifyInspection) { + notifyInspectionFlagUsed(key, detail); + } + + return detail; + } + + function getFlagDetail(flag) { + return { + value: flag.value, + variationIndex: flag.variation === undefined ? null : flag.variation, + reason: flag.reason || null, + }; + // Note, the logic above ensures that variationIndex and reason will always be null rather than + // undefined if we don't have values for them. That's just to avoid subtle errors that depend on + // whether an object was JSON-encoded with null properties omitted or not. + } + + function allFlags() { + const results = {}; + + if (!flags) { + return results; + } + + for (const key in flags) { + if (utils.objectHasOwnProperty(flags, key) && !flags[key].deleted) { + results[key] = variationDetailInternal( + key, + null, + !options.sendEventsOnlyForVariation, + false, + true, + false + ).value; + } + } + + return results; + } + + function userContextKind(user) { + return user.anonymous ? 'anonymousUser' : 'user'; + } + + function track(key, data, metricValue) { + if (typeof key !== 'string') { + emitter.maybeReportError(new errors.LDInvalidEventKeyError(messages.unknownCustomEventKey(key))); + return; + } + if (metricValue !== undefined && typeof metricValue !== 'number') { + logger.warn(messages.invalidMetricValue(typeof metricValue)); + } + + // The following logic was used only for the JS browser SDK (js-client-sdk) and + // is no longer needed as of version 2.9.13 of that SDK. The other client-side + // JS-based SDKs did not define customEventFilter, and now none of them do. We + // can remove this in the next major version of the common code, when it's OK to + // make breaking changes to our internal API contracts. + if (platform.customEventFilter && !platform.customEventFilter(key)) { + logger.warn(messages.unknownCustomEventKey(key)); + } + + const context = ident.getContext(); + const e = { + kind: 'custom', + key: key, + context, + url: platform.getCurrentUrl(), + creationDate: new Date().getTime(), + }; + if (context && context.anonymous) { + e.contextKind = userContextKind(context); + } + // Note, check specifically for null/undefined because it is legal to set these fields to a falsey value. + if (data !== null && data !== undefined) { + e.data = data; + } + if (metricValue !== null && metricValue !== undefined) { + e.metricValue = metricValue; + } + enqueueEvent(e); + hookRunner.afterTrack({ context, key, data, metricValue }); + } + + function connectStream() { + streamActive = true; + if (!ident.getContext()) { + return; + } + const tryParseData = jsonData => { + try { + return JSON.parse(jsonData); + } catch (err) { + emitter.maybeReportError(new errors.LDInvalidDataError(messages.invalidData())); + return undefined; + } + }; + stream.connect(ident.getContext(), hash, { + ping: function() { + logger.debug(messages.debugStreamPing()); + const contextAtTimeOfPingEvent = ident.getContext(); + requestor + .fetchFlagSettings(contextAtTimeOfPingEvent, hash) + .then(requestedFlags => { + // Check whether the current context is still the same - we don't want to overwrite the flags if + // the application has called identify() while this request was in progress + if (utils.deepEquals(contextAtTimeOfPingEvent, ident.getContext())) { + replaceAllFlags(requestedFlags || {}); + } + }) + .catch(err => { + emitter.maybeReportError(new errors.LDFlagFetchError(messages.errorFetchingFlags(err))); + }); + }, + put: function(e) { + const data = tryParseData(e.data); + if (!data) { + return; + } + logger.debug(messages.debugStreamPut()); + replaceAllFlags(data); + // Don't wait for this Promise to be resolved; note that replaceAllFlags is guaranteed + // never to have an unhandled rejection + }, + patch: function(e) { + const data = tryParseData(e.data); + if (!data) { + return; + } + // If both the flag and the patch have a version property, then the patch version must be + // greater than the flag version for us to accept the patch. If either one has no version + // then the patch always succeeds. + const oldFlag = flags[data.key]; + if (!oldFlag || !oldFlag.version || !data.version || oldFlag.version < data.version) { + logger.debug(messages.debugStreamPatch(data.key)); + const mods = {}; + const newFlag = utils.extend({}, data); + delete newFlag['key']; + flags[data.key] = newFlag; + const newDetail = getFlagDetail(newFlag); + if (oldFlag) { + mods[data.key] = { previous: oldFlag.value, current: newDetail }; + } else { + mods[data.key] = { current: newDetail }; + } + notifyInspectionFlagChanged(data, newFlag); + handleFlagChanges(mods); // don't wait for this Promise to be resolved + } else { + logger.debug(messages.debugStreamPatchIgnored(data.key)); + } + }, + delete: function(e) { + const data = tryParseData(e.data); + if (!data) { + return; + } + if (!flags[data.key] || flags[data.key].version < data.version) { + logger.debug(messages.debugStreamDelete(data.key)); + const mods = {}; + if (flags[data.key] && !flags[data.key].deleted) { + mods[data.key] = { previous: flags[data.key].value }; + } + flags[data.key] = { version: data.version, deleted: true }; + notifyInspectionFlagChanged(data, flags[data.key]); + handleFlagChanges(mods); // don't wait for this Promise to be resolved + } else { + logger.debug(messages.debugStreamDeleteIgnored(data.key)); + } + }, + }); + } + + function disconnectStream() { + if (streamActive) { + stream.disconnect(); + streamActive = false; + } + } + + // Returns a Promise which will be resolved when we have completely updated the internal flags state, + // dispatched all change events, and updated local storage if appropriate. This Promise is guaranteed + // never to have an unhandled rejection. + function replaceAllFlags(newFlags) { + const changes = {}; + + if (!newFlags) { + return Promise.resolve(); + } + + for (const key in flags) { + if (utils.objectHasOwnProperty(flags, key) && flags[key]) { + if (newFlags[key] && !utils.deepEquals(newFlags[key].value, flags[key].value)) { + changes[key] = { previous: flags[key].value, current: getFlagDetail(newFlags[key]) }; + } else if (!newFlags[key] || newFlags[key].deleted) { + changes[key] = { previous: flags[key].value }; + } + } + } + for (const key in newFlags) { + if (utils.objectHasOwnProperty(newFlags, key) && newFlags[key] && (!flags[key] || flags[key].deleted)) { + changes[key] = { current: getFlagDetail(newFlags[key]) }; + } + } + + flags = { ...newFlags }; + + notifyInspectionFlagsChanged(); + + return handleFlagChanges(changes).catch(() => {}); // swallow any exceptions from this Promise + } + + // Returns a Promise which will be resolved when we have dispatched all change events and updated + // local storage if appropriate. + function handleFlagChanges(changes) { + const keys = Object.keys(changes); + + if (keys.length > 0) { + const changeEventParams = {}; + keys.forEach(key => { + const current = changes[key].current; + const value = current ? current.value : undefined; + const previous = changes[key].previous; + emitter.emit(changeEvent + ':' + key, value, previous); + changeEventParams[key] = current ? { current: value, previous: previous } : { previous: previous }; + }); + + emitter.emit(changeEvent, changeEventParams); + emitter.emit(internalChangeEvent, flags); + + // By default, we send feature evaluation events whenever we have received new flag values - + // the client has in effect evaluated these flags just by receiving them. This can be suppressed + // by setting "sendEventsOnlyForVariation". Also, if we have a stateProvider, we don't send these + // events because we assume they have already been sent by the other client that gave us the flags + // (when it received them in the first place). + if (!options.sendEventsOnlyForVariation && !stateProvider) { + keys.forEach(key => { + sendFlagEvent(key, changes[key].current); + }); + } + } + + if (useLocalStorage && persistentFlagStore) { + return persistentFlagStore.saveFlags(flags); + } else { + return Promise.resolve(); + } + } + + function on(event, handler, context) { + if (isChangeEventKey(event)) { + subscribedToChangeEvents = true; + if (inited) { + updateStreamingState(); + } + emitter.on(event, handler, context); + } else { + emitter.on(...arguments); + } + } + + function off(event) { + emitter.off(...arguments); + if (isChangeEventKey(event)) { + let haveListeners = false; + emitter.getEvents().forEach(key => { + if (isChangeEventKey(key) && emitter.getEventListenerCount(key) > 0) { + haveListeners = true; + } + }); + if (!haveListeners) { + subscribedToChangeEvents = false; + if (streamActive && streamForcedState === undefined) { + disconnectStream(); + } + } + } + } + + function setStreaming(state) { + const newState = state === null ? undefined : state; + if (newState !== streamForcedState) { + streamForcedState = newState; + updateStreamingState(); + } + } + + function updateStreamingState() { + const shouldBeStreaming = streamForcedState || (subscribedToChangeEvents && streamForcedState === undefined); + if (shouldBeStreaming && !streamActive) { + connectStream(); + } else if (!shouldBeStreaming && streamActive) { + disconnectStream(); + } + if (diagnosticsManager) { + diagnosticsManager.setStreaming(shouldBeStreaming); + } + } + + function isChangeEventKey(event) { + return event === changeEvent || event.substr(0, changeEvent.length + 1) === changeEvent + ':'; + } + + if (typeof options.bootstrap === 'string' && options.bootstrap.toUpperCase() === 'LOCALSTORAGE') { + if (persistentFlagStore) { + useLocalStorage = true; + } else { + logger.warn(messages.localStorageUnavailable()); + } + } + + if (typeof options.bootstrap === 'object') { + // Set the flags as soon as possible before we get into any async code, so application code can read + // them even if the ready event has not yet fired. + flags = readFlagsFromBootstrap(options.bootstrap); + } + + if (stateProvider) { + // The stateProvider option is used in the Electron SDK, to allow a client instance in the main process + // to control another client instance (i.e. this one) in the renderer process. We can't predict which + // one will start up first, so the initial state may already be available for us or we may have to wait + // to receive it. + const state = stateProvider.getInitialState(); + if (state) { + initFromStateProvider(state); + } else { + stateProvider.on('init', initFromStateProvider); + } + stateProvider.on('update', updateFromStateProvider); + } else { + finishInit().catch(signalFailedInit); + } + + function finishInit() { + if (!env) { + return Promise.reject(new errors.LDInvalidEnvironmentIdError(messages.environmentNotSpecified())); + } + let afterIdentify; + return anonymousContextProcessor + .processContext(context) + .then(verifyContext) + .then(context => { + afterIdentify = utils.once(hookRunner.identify(context, undefined)); + return context; + }) + .then(validatedContext => { + afterIdentify?.({ status: 'completed' }); + ident.setContext(validatedContext); + if (typeof options.bootstrap === 'object') { + // flags have already been set earlier + return signalSuccessfulInit(); + } else if (useLocalStorage) { + return finishInitWithLocalStorage(); + } else { + return finishInitWithPolling(); + } + }) + .catch(err => { + afterIdentify?.({ status: 'error' }); + throw err; + }); + } + + function finishInitWithLocalStorage() { + return persistentFlagStore.loadFlags().then(storedFlags => { + if (storedFlags === null || storedFlags === undefined) { + flags = {}; + return requestor + .fetchFlagSettings(ident.getContext(), hash) + .then(requestedFlags => replaceAllFlags(requestedFlags || {})) + .then(signalSuccessfulInit) + .catch(err => { + const initErr = new errors.LDFlagFetchError(messages.errorFetchingFlags(err)); + signalFailedInit(initErr); + }); + } else { + // We're reading the flags from local storage. Signal that we're ready, + // then update localStorage for the next page load. We won't signal changes or update + // the in-memory flags unless you subscribe for changes + flags = storedFlags; + utils.onNextTick(signalSuccessfulInit); + + return requestor + .fetchFlagSettings(ident.getContext(), hash) + .then(requestedFlags => replaceAllFlags(requestedFlags)) + .catch(err => emitter.maybeReportError(err)); + } + }); + } + + function finishInitWithPolling() { + return requestor + .fetchFlagSettings(ident.getContext(), hash) + .then(requestedFlags => { + flags = requestedFlags || {}; + + notifyInspectionFlagsChanged(); + // Note, we don't need to call updateSettings here because local storage and change events are not relevant + signalSuccessfulInit(); + }) + .catch(err => { + flags = {}; + signalFailedInit(err); + }); + } + + function initFromStateProvider(state) { + environment = state.environment; + ident.setContext(state.context); + flags = { ...state.flags }; + utils.onNextTick(signalSuccessfulInit); + } + + function updateFromStateProvider(state) { + if (state.context) { + ident.setContext(state.context); + } + if (state.flags) { + replaceAllFlags(state.flags); // don't wait for this Promise to be resolved + } + } + + function signalSuccessfulInit() { + logger.info(messages.clientInitialized()); + inited = true; + updateStreamingState(); + initializationStateTracker.signalSuccess(); + } + + function signalFailedInit(err) { + initializationStateTracker.signalFailure(err); + } + + function start() { + if (sendEvents) { + if (diagnosticsManager) { + diagnosticsManager.start(); + } + events.start(); + } + } + + function close(onDone) { + if (closed) { + return utils.wrapPromiseCallback(Promise.resolve(), onDone); + } + const finishClose = () => { + closed = true; + flags = {}; + }; + const p = Promise.resolve() + .then(() => { + disconnectStream(); + if (diagnosticsManager) { + diagnosticsManager.stop(); + } + if (sendEvents) { + events.stop(); + return events.flush(); + } + }) + .then(finishClose) + .catch(finishClose); + return utils.wrapPromiseCallback(p, onDone); + } + + function getFlagsInternal() { + // used by Electron integration + return flags; + } + + function waitForInitializationWithTimeout(timeout) { + if (timeout > highTimeoutThreshold) { + logger.warn( + 'The waitForInitialization function was called with a timeout greater than ' + + `${highTimeoutThreshold} seconds. We recommend a timeout of ` + + `${highTimeoutThreshold} seconds or less.` + ); + } + + const initPromise = initializationStateTracker.getInitializationPromise(); + const timeoutPromise = timedPromise(timeout, 'waitForInitialization'); + + return Promise.race([timeoutPromise, initPromise]).catch(e => { + if (e instanceof errors.LDTimeoutError) { + logger.error(`waitForInitialization error: ${e}`); + } + throw e; + }); + } + + function waitForInitialization(timeout = undefined) { + if (timeout !== undefined && timeout !== null) { + if (typeof timeout === 'number') { + return waitForInitializationWithTimeout(timeout); + } + logger.warn('The waitForInitialization method was provided with a non-numeric timeout.'); + } + logger.warn( + 'The waitForInitialization function was called without a timeout specified.' + + ' In a future version a default timeout will be applied.' + ); + return initializationStateTracker.getInitializationPromise(); + } + + function addHook(hook) { + hookRunner.addHook(hook); + } + + const client = { + waitForInitialization, + waitUntilReady: () => initializationStateTracker.getReadyPromise(), + identify: identify, + getContext: getContext, + variation: variation, + variationDetail: variationDetail, + track: track, + on: on, + off: off, + setStreaming: setStreaming, + flush: flush, + allFlags: allFlags, + close: close, + addHook: addHook, + }; + + registerPlugins(logger, pluginEnvironment, client, plugins); + + return { + client: client, // The client object containing all public methods. + options: options, // The validated configuration object, including all defaults. + emitter: emitter, // The event emitter which can be used to log errors or trigger events. + ident: ident, // The Identity object that manages the current context. + logger: logger, // The logging abstraction. + requestor: requestor, // The Requestor object. + start: start, // Starts the client once the environment is ready. + enqueueEvent: enqueueEvent, // Puts an analytics event in the queue, if event sending is enabled. + getFlagsInternal: getFlagsInternal, // Returns flag data structure with all details. + getEnvironmentId: () => environment, // Gets the environment ID (this may have changed since initialization, if we have a state provider) + internalChangeEventName: internalChangeEvent, // This event is triggered whenever we have new flag state. + }; +} + +module.exports = { + initialize, + commonBasicLogger, + errors, + messages, + utils, + getContextKeys, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/jest.setup.js b/node_modules/launchdarkly-js-sdk-common/src/jest.setup.js new file mode 100644 index 00000000..f64a0e0f --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/jest.setup.js @@ -0,0 +1 @@ +// Test environment setup diff --git a/node_modules/launchdarkly-js-sdk-common/src/loggers.js b/node_modules/launchdarkly-js-sdk-common/src/loggers.js new file mode 100644 index 00000000..9c5000fa --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/loggers.js @@ -0,0 +1,93 @@ +const logLevels = ['debug', 'info', 'warn', 'error', 'none']; + +/** + * A simple logger that writes to stderr. + */ +function commonBasicLogger(options, formatFn) { + if (options && options.destination && typeof options.destination !== 'function') { + throw new Error('destination for basicLogger was set to a non-function'); + } + + function toConsole(methodName) { + // The global console variable is not guaranteed to be defined at all times in all browsers: + // https://www.beyondjava.net/console-log-surprises-with-internet-explorer-11-and-edge + return function(line) { + if (console && console[methodName]) { + console[methodName].call(console, line); + } + }; + } + const destinations = + options && options.destination + ? [options.destination, options.destination, options.destination, options.destination] + : [toConsole('log'), toConsole('info'), toConsole('warn'), toConsole('error')]; + const prependLevelToMessage = !!(options && options.destination); // if we're writing to console.warn, etc. we don't need the prefix + const prefix = + !options || options.prefix === undefined || options.prefix === null ? '[LaunchDarkly] ' : options.prefix; + + let minLevel = 1; // default is 'info' + if (options && options.level) { + for (let i = 0; i < logLevels.length; i++) { + if (logLevels[i] === options.level) { + minLevel = i; + } + } + } + + function write(levelIndex, levelName, args) { + if (args.length < 1) { + return; + } + let line; + const fullPrefix = prependLevelToMessage ? levelName + ': ' + prefix : prefix; + if (args.length === 1 || !formatFn) { + line = fullPrefix + args[0]; + } else { + const tempArgs = [...args]; + tempArgs[0] = fullPrefix + tempArgs[0]; + line = formatFn(...tempArgs); + } + try { + destinations[levelIndex](line); + } catch (err) { + console && + console.log && + console.log("[LaunchDarkly] Configured logger's " + levelName + ' method threw an exception: ' + err); + } + } + + const logger = {}; + for (let i = 0; i < logLevels.length; i++) { + const levelName = logLevels[i]; + if (levelName !== 'none') { + if (i < minLevel) { + logger[levelName] = () => {}; + } else { + const levelIndex = i; + logger[levelName] = function() { + // can't use arrow function with "arguments" + write(levelIndex, levelName, arguments); + }; + } + } + } + + return logger; +} + +function validateLogger(logger) { + logLevels.forEach(level => { + if (level !== 'none' && (!logger[level] || typeof logger[level] !== 'function')) { + throw new Error('Provided logger instance must support logger.' + level + '(...) method'); + // Note that the SDK normally does not throw exceptions to the application, but that rule + // does not apply to LDClient.init() which will throw an exception if the parameters are so + // invalid that we cannot proceed with creating the client. An invalid logger meets those + // criteria since the SDK calls the logger during nearly all of its operations. + } + }); +} + +module.exports = { + commonBasicLogger, + validateLogger, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/messages.js b/node_modules/launchdarkly-js-sdk-common/src/messages.js new file mode 100644 index 00000000..d2b6271f --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/messages.js @@ -0,0 +1,241 @@ +const errors = require('./errors'); + +function errorString(err) { + if (err && err.message) { + return err.message; + } + if (typeof err === 'string' || err instanceof String) { + return err; + } + return JSON.stringify(err); +} + +const clientInitialized = function() { + return 'LaunchDarkly client initialized'; +}; + +const docLink = + ' Please see https://docs.launchdarkly.com/sdk/client-side/javascript#initialize-the-client for instructions on SDK initialization.'; + +const clientNotReady = function() { + return 'LaunchDarkly client is not ready'; +}; + +const eventCapacityExceeded = function() { + return 'Exceeded event queue capacity. Increase capacity to avoid dropping events.'; +}; + +const eventWithoutContext = function() { + return 'Be sure to call `identify` in the LaunchDarkly client: https://docs.launchdarkly.com/sdk/features/identify#javascript'; +}; + +const invalidContentType = function(contentType) { + return 'Expected application/json content type but got "' + contentType + '"'; +}; + +const invalidKey = function() { + return 'Event key must be a string'; +}; + +const localStorageUnavailable = function(err) { + return 'local storage is unavailable: ' + errorString(err); +}; + +const networkError = e => 'network error' + (e ? ' (' + e + ')' : ''); + +// We should remove unknownCustomEventKey in the future - see comments in track() in index.js +const unknownCustomEventKey = function(key) { + return 'Custom event "' + key + '" does not exist'; +}; + +const environmentNotFound = function() { + return 'Environment not found. Double check that you specified a valid environment/client-side ID.' + docLink; +}; + +const environmentNotSpecified = function() { + return 'No environment/client-side ID was specified.' + docLink; +}; + +const errorFetchingFlags = function(err) { + return 'Error fetching flag settings: ' + errorString(err); +}; + +const contextNotSpecified = function() { + return 'No context specified.' + docLink; +}; + +const invalidContext = function() { + return 'Invalid context specified.' + docLink; +}; + +const invalidData = function() { + return 'Invalid data received from LaunchDarkly; connection may have been interrupted'; +}; + +const bootstrapOldFormat = function() { + return ( + 'LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. ' + + 'Events may not be sent correctly.' + + docLink + ); +}; + +const bootstrapInvalid = function() { + return 'LaunchDarkly bootstrap data is not available because the back end could not read the flags.'; +}; + +const deprecated = function(oldName, newName) { + if (newName) { + return '"' + oldName + '" is deprecated, please use "' + newName + '"'; + } + return '"' + oldName + '" is deprecated'; +}; + +const httpErrorMessage = function(status, context, retryMessage) { + return ( + 'Received error ' + + status + + (status === 401 ? ' (invalid SDK key)' : '') + + ' for ' + + context + + ' - ' + + (errors.isHttpErrorRecoverable(status) ? retryMessage : 'giving up permanently') + ); +}; + +const httpUnavailable = function() { + return 'Cannot make HTTP requests in this environment.' + docLink; +}; + +const identifyDisabled = function() { + return 'identify() has no effect here; it must be called on the main client instance'; +}; + +const streamClosing = function() { + return 'Closing stream connection'; +}; + +const streamConnecting = function(url) { + return 'Opening stream connection to ' + url; +}; + +const streamError = function(err, streamReconnectDelay) { + return ( + 'Error on stream connection: ' + + errorString(err) + + ', will continue retrying after ' + + streamReconnectDelay + + ' milliseconds.' + ); +}; + +const unknownOption = name => 'Ignoring unknown config option "' + name + '"'; + +const unrecoverableStreamError = err => `Error on stream connection ${errorString(err)}, giving up permanently`; + +const wrongOptionType = (name, expectedType, actualType) => + 'Config option "' + name + '" should be of type ' + expectedType + ', got ' + actualType + ', using default value'; + +const wrongOptionTypeBoolean = (name, actualType) => + 'Config option "' + name + '" should be a boolean, got ' + actualType + ', converting to boolean'; + +const optionBelowMinimum = (name, value, minimum) => + 'Config option "' + name + '" was set to ' + value + ', changing to minimum value of ' + minimum; + +const debugPolling = function(url) { + return 'polling for feature flags at ' + url; +}; + +const debugStreamPing = function() { + return 'received ping message from stream'; +}; + +const debugStreamPut = function() { + return 'received streaming update for all flags'; +}; + +const debugStreamPatch = function(key) { + return 'received streaming update for flag "' + key + '"'; +}; + +const debugStreamPatchIgnored = function(key) { + return 'received streaming update for flag "' + key + '" but ignored due to version check'; +}; + +const debugStreamDelete = function(key) { + return 'received streaming deletion for flag "' + key + '"'; +}; + +const debugStreamDeleteIgnored = function(key) { + return 'received streaming deletion for flag "' + key + '" but ignored due to version check'; +}; + +const debugEnqueueingEvent = function(kind) { + return 'enqueueing "' + kind + '" event'; +}; + +const debugPostingEvents = function(count) { + return 'sending ' + count + ' events'; +}; + +const debugPostingDiagnosticEvent = function(event) { + return 'sending diagnostic event (' + event.kind + ')'; +}; + +const invalidInspector = (type, name) => `an inspector: "${name}" of an invalid type (${type}) was configured`; + +const inspectorMethodError = (type, name) => `an inspector: "${name}" of type: "${type}" generated an exception`; + +const invalidTagValue = name => `Config option "${name}" must only contain letters, numbers, ., _ or -.`; + +const tagValueTooLong = name => `Value of "${name}" was longer than 64 characters and was discarded.`; + +const invalidMetricValue = badType => + `The track function was called with a non-numeric "metricValue" (${badType}), only numeric metric values are supported.`; + +module.exports = { + bootstrapInvalid, + bootstrapOldFormat, + clientInitialized, + clientNotReady, + debugEnqueueingEvent, + debugPostingDiagnosticEvent, + debugPostingEvents, + debugStreamDelete, + debugStreamDeleteIgnored, + debugStreamPatch, + debugStreamPatchIgnored, + debugStreamPing, + debugPolling, + debugStreamPut, + deprecated, + environmentNotFound, + environmentNotSpecified, + errorFetchingFlags, + eventCapacityExceeded, + eventWithoutContext, + httpErrorMessage, + httpUnavailable, + identifyDisabled, + inspectorMethodError, + invalidContentType, + invalidData, + invalidInspector, + invalidKey, + invalidMetricValue, + invalidContext, + invalidTagValue, + localStorageUnavailable, + networkError, + optionBelowMinimum, + streamClosing, + streamConnecting, + streamError, + tagValueTooLong, + unknownCustomEventKey, + unknownOption, + contextNotSpecified, + unrecoverableStreamError, + wrongOptionType, + wrongOptionTypeBoolean, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/plugins.js b/node_modules/launchdarkly-js-sdk-common/src/plugins.js new file mode 100644 index 00000000..561635b9 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/plugins.js @@ -0,0 +1,109 @@ +const UNKNOWN_PLUGIN_NAME = 'unknown plugin'; + +/** + * Safely gets the name of a plugin with error handling + * @param {{ error: (message: string) => void }} logger - The logger instance + * @param {{getMetadata: () => {name: string}}} plugin - Plugin object that may have a name property + * @returns {string} The plugin name or 'unknown' if not available + */ +function getPluginName(logger, plugin) { + try { + return plugin.getMetadata().name || UNKNOWN_PLUGIN_NAME; + } catch (error) { + logger.error(`Exception thrown getting metadata for plugin. Unable to get plugin name.`); + return UNKNOWN_PLUGIN_NAME; + } +} + +/** + * Safely retrieves hooks from plugins with error handling + * @param {Object} logger - The logger instance + * @param {Object} environmentMetadata - Metadata about the environment for plugin initialization + * @param {Array<{getHooks: (environmentMetadata: object) => Hook[]}>} plugins - Array of plugin objects that may implement getHooks + * @returns {Array} Array of hook objects collected from all plugins + */ +function getPluginHooks(logger, environmentMetadata, plugins) { + const hooks = []; + plugins.forEach(plugin => { + try { + const pluginHooks = plugin.getHooks?.(environmentMetadata); + if (pluginHooks === undefined) { + logger.error(`Plugin ${getPluginName(logger, plugin)} returned undefined from getHooks.`); + } else if (pluginHooks && pluginHooks.length > 0) { + hooks.push(...pluginHooks); + } + } catch (error) { + logger.error(`Exception thrown getting hooks for plugin ${getPluginName(logger, plugin)}. Unable to get hooks.`); + } + }); + return hooks; +} + +/** + * Registers plugins with the SDK + * @param {{ error: (message: string) => void }} logger - The logger instance + * @param {Object} environmentMetadata - Metadata about the environment for plugin initialization + * @param {Object} client - The SDK client instance + * @param {Array<{register: (client: object, environmentMetadata: object) => void}>} plugins - Array of plugin objects that implement register + */ +function registerPlugins(logger, environmentMetadata, client, plugins) { + plugins.forEach(plugin => { + try { + plugin.register(client, environmentMetadata); + } catch (error) { + logger.error(`Exception thrown registering plugin ${getPluginName(logger, plugin)}.`); + } + }); +} + +/** + * Creates a plugin environment object + * @param {{userAgent: string, version: string}} platform - The platform object + * @param {string} env - The environment + * @param {{application: {name: string, version: string}, wrapperName: string, wrapperVersion: string}} options - The options + * @returns {{sdk: {name: string, version: string, wrapperName: string, wrapperVersion: string}, application: {name: string, version: string}, clientSideId: string}} The plugin environment + */ +function createPluginEnvironment(platform, env, options) { + const pluginSdkMetadata = {}; + + if (platform.userAgent) { + pluginSdkMetadata.name = platform.userAgent; + } + if (platform.version) { + pluginSdkMetadata.version = platform.version; + } + if (options.wrapperName) { + pluginSdkMetadata.wrapperName = options.wrapperName; + } + if (options.wrapperVersion) { + pluginSdkMetadata.wrapperVersion = options.wrapperVersion; + } + + const pluginApplicationMetadata = {}; + + if (options.application) { + if (options.application.name) { + pluginApplicationMetadata.name = options.application.name; + } + if (options.application.version) { + pluginApplicationMetadata.version = options.application.version; + } + } + + const pluginEnvironment = { + sdk: pluginSdkMetadata, + clientSideId: env, + }; + + if (Object.keys(pluginApplicationMetadata).length > 0) { + pluginEnvironment.application = pluginApplicationMetadata; + } + + return pluginEnvironment; +} + +module.exports = { + getPluginHooks, + registerPlugins, + createPluginEnvironment, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/src/promiseCoalescer.js b/node_modules/launchdarkly-js-sdk-common/src/promiseCoalescer.js new file mode 100644 index 00000000..66152c9c --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/promiseCoalescer.js @@ -0,0 +1,52 @@ +// This function allows a series of Promises to be coalesced such that only the most recently +// added one actually matters. For instance, if several HTTP requests are made to the same +// endpoint and we want to ensure that whoever made each one always gets the latest data, each +// can be passed to addPromise (on the same coalescer) and each caller can wait on the +// coalescer.resultPromise; all three will then receive the result (or error) from the *last* +// request, and the results of the first two will be discarded. +// +// The cancelFn callback, if present, will be called whenever an existing promise is being +// discarded. This can be used for instance to abort an HTTP request that's now obsolete. +// +// The finallyFn callback, if present, is called on completion of the whole thing. This is +// different from calling coalescer.resultPromise.finally() because it is executed before any +// other handlers. Its purpose is to tell the caller that this coalescer should no longer be used. + +function promiseCoalescer(finallyFn) { + let currentPromise; + let currentCancelFn; + let finalResolve; + let finalReject; + + const coalescer = {}; + + coalescer.addPromise = (p, cancelFn) => { + currentPromise = p; + currentCancelFn && currentCancelFn(); + currentCancelFn = cancelFn; + + p.then( + result => { + if (currentPromise === p) { + finalResolve(result); + finallyFn && finallyFn(); + } + }, + error => { + if (currentPromise === p) { + finalReject(error); + finallyFn && finallyFn(); + } + } + ); + }; + + coalescer.resultPromise = new Promise((resolve, reject) => { + finalResolve = resolve; + finalReject = reject; + }); + + return coalescer; +} + +module.exports = promiseCoalescer; diff --git a/node_modules/launchdarkly-js-sdk-common/src/timedPromise.js b/node_modules/launchdarkly-js-sdk-common/src/timedPromise.js new file mode 100644 index 00000000..5155c329 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/timedPromise.js @@ -0,0 +1,17 @@ +const { LDTimeoutError } = require('./errors'); + +/** + * Returns a promise which errors after t seconds. + * + * @param t Timeout in seconds. + * @param taskName Name of task being timed for logging and error reporting. + */ +function timedPromise(t, taskName) { + return new Promise((_res, reject) => { + setTimeout(() => { + const e = `${taskName} timed out after ${t} seconds.`; + reject(new LDTimeoutError(e)); + }, t * 1000); + }); +} +module.exports = timedPromise; diff --git a/node_modules/launchdarkly-js-sdk-common/src/utils.js b/node_modules/launchdarkly-js-sdk-common/src/utils.js new file mode 100644 index 00000000..a26d7e22 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/src/utils.js @@ -0,0 +1,182 @@ +const base64 = require('base64-js'); +const fastDeepEqual = require('fast-deep-equal'); + +const userAttrsToStringify = ['key', 'ip', 'country', 'email', 'firstName', 'lastName', 'avatar', 'name']; + +function appendUrlPath(baseUrl, path) { + // Ensure that URL concatenation is done correctly regardless of whether the + // base URL has a trailing slash or not. + const trimBaseUrl = baseUrl.endsWith('/') ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl; + return trimBaseUrl + (path.startsWith('/') ? '' : '/') + path; +} + +// See http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html +function btoa(s) { + const escaped = unescape(encodeURIComponent(s)); + return base64.fromByteArray(stringToBytes(escaped)); +} + +function stringToBytes(s) { + const b = []; + for (let i = 0; i < s.length; i++) { + b.push(s.charCodeAt(i)); + } + return b; +} + +function base64URLEncode(s) { + return ( + btoa(s) + // eslint-disable-next-line + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_') + ); +} + +function clone(obj) { + return JSON.parse(JSON.stringify(obj)); +} + +function deepEquals(a, b) { + return fastDeepEqual(a, b); +} + +// Events emitted in LDClient's initialize method will happen before the consumer +// can register a listener, so defer them to next tick. +function onNextTick(cb) { + setTimeout(cb, 0); +} + +/** + * Wrap a promise to invoke an optional callback upon resolution or rejection. + * + * This function assumes the callback follows the Node.js callback type: (err, value) => void + * + * If a callback is provided: + * - if the promise is resolved, invoke the callback with (null, value) + * - if the promise is rejected, invoke the callback with (error, null) + * + * @param {Promise} promise + * @param {Function} callback + * @returns Promise | undefined + */ +function wrapPromiseCallback(promise, callback) { + const ret = promise.then( + value => { + if (callback) { + setTimeout(() => { + callback(null, value); + }, 0); + } + return value; + }, + error => { + if (callback) { + setTimeout(() => { + callback(error, null); + }, 0); + } else { + return Promise.reject(error); + } + } + ); + + return !callback ? ret : undefined; +} + +/** + * Takes a map of flag keys to values, and returns the more verbose structure used by the + * client stream. + */ +function transformValuesToVersionedValues(flags) { + const ret = {}; + for (const key in flags) { + if (objectHasOwnProperty(flags, key)) { + ret[key] = { value: flags[key], version: 0 }; + } + } + return ret; +} + +/** + * Converts the internal flag state map to a simple map of flag keys to values. + */ +function transformVersionedValuesToValues(flagsState) { + const ret = {}; + for (const key in flagsState) { + if (objectHasOwnProperty(flagsState, key)) { + ret[key] = flagsState[key].value; + } + } + return ret; +} + +function getLDUserAgentString(platform) { + const version = platform.version || '?'; + return platform.userAgent + '/' + version; +} + +function extend(...objects) { + return objects.reduce((acc, obj) => ({ ...acc, ...obj }), {}); +} + +function objectHasOwnProperty(object, name) { + return Object.prototype.hasOwnProperty.call(object, name); +} + +function sanitizeContext(context) { + if (!context) { + return context; + } + let newContext; + // Only stringify user attributes for legacy users. + if (context.kind === null || context.kind === undefined) { + userAttrsToStringify.forEach(attr => { + const value = context[attr]; + if (value !== undefined && typeof value !== 'string') { + newContext = newContext || { ...context }; + newContext[attr] = String(value); + } + }); + } + + return newContext || context; +} + +/** + * Creates a function that will invoke the provided function only once. + * + * If the function returns a value, then that returned value will be re-used for subsequent invocations. + * + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + */ +function once(func) { + let called = false; + let result; + return function(...args) { + if (!called) { + called = true; + result = func.apply(this, args); + } + return result; + }; +} + +module.exports = { + appendUrlPath, + base64URLEncode, + btoa, + clone, + deepEquals, + extend, + getLDUserAgentString, + objectHasOwnProperty, + onNextTick, + sanitizeContext, + transformValuesToVersionedValues, + transformVersionedValuesToValues, + wrapPromiseCallback, + once, +}; diff --git a/node_modules/launchdarkly-js-sdk-common/test-types.ts b/node_modules/launchdarkly-js-sdk-common/test-types.ts new file mode 100644 index 00000000..b27906f8 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/test-types.ts @@ -0,0 +1,131 @@ + +// This file exists only so that we can run the TypeScript compiler in the CI build +// to validate our typings.d.ts file. + +import * as ld from 'launchdarkly-js-sdk-common'; + +var userWithKeyOnly: ld.LDUser = { key: 'user' }; +var anonUserWithNoKey: ld.LDUser = { anonymous: true }; +var anonUserWithKey: ld.LDUser = { key: 'anon-user', anonymous: true }; +var user: ld.LDContext = { + key: 'user', + name: 'name', + firstName: 'first', + lastName: 'last', + email: 'test@example.com', + avatar: 'http://avatar.url', + ip: '1.1.1.1', + country: 'us', + anonymous: true, + custom: { + 'a': 's', + 'b': true, + 'c': 3, + 'd': [ 'x', 'y' ], + 'e': [ true, false ], + 'f': [ 1, 2 ] + }, + privateAttributeNames: [ 'name', 'email' ] +}; +const hook: ld.Hook = { + getMetadata: () => ({ + name: 'hook', + }), + + beforeEvaluation(hookContext: ld.EvaluationSeriesContext, data: ld.EvaluationSeriesData): ld.EvaluationSeriesData { + return data; + }, + afterEvaluation(hookContext: ld.EvaluationSeriesContext, data: ld.EvaluationSeriesData, detail: ld.LDEvaluationDetail): ld.EvaluationSeriesData { + return data; + }, + beforeIdentify(hookContext: ld.IdentifySeriesContext, data: ld.IdentifySeriesData): ld.IdentifySeriesData { + return data; + }, + afterIdentify(hookContext: ld.IdentifySeriesContext, data: ld.IdentifySeriesData, result: ld.IdentifySeriesResult): ld.IdentifySeriesData { + return data; + }, + + afterTrack(hookContext: ld.TrackSeriesContext): void { + } +}; + +const plugin: ld.LDPlugin = { + getMetadata: () => ({ + name: 'plugin', + }), + register(client: ld.LDClientBase, environmentMetadata: ld.LDPluginEnvironmentMetadata): void { + }, + + getHooks(metadata: ld.LDPluginEnvironmentMetadata): ld.Hook[] { + return []; + }, +}; + +var logger: ld.LDLogger = ld.commonBasicLogger({ level: 'info' }); +var allBaseOptions: ld.LDOptionsBase = { + bootstrap: { }, + baseUrl: '', + eventsUrl: '', + streamUrl: '', + streaming: true, + useReport: true, + sendLDHeaders: true, + requestHeaderTransform: (x) => x, + evaluationReasons: true, + sendEvents: true, + allAttributesPrivate: true, + privateAttributes: [ 'x' ], + sendEventsOnlyForVariation: true, + flushInterval: 1, + streamReconnectDelay: 1, + logger: logger, + application: { + version: 'version', + id: 'id' + }, + hooks: [ hook ], + plugins: [ plugin ] +}; + +var client: ld.LDClientBase = {} as ld.LDClientBase; // wouldn't do this in real life, it's just so the following statements will compile + +client.waitUntilReady().then(() => {}); +client.waitForInitialization(5).then(() => {}); + +client.identify(user).then(() => {}); +client.identify(user, undefined, () => {}); +client.identify(user, 'hash').then(() => {}); + +var user: ld.LDContext = client.getContext(); + +client.flush(() => {}); +client.flush().then(() => {}); + +var boolFlagValue: ld.LDFlagValue = client.variation('key', false); +var numberFlagValue: ld.LDFlagValue = client.variation('key', 2); +var stringFlagValue: ld.LDFlagValue = client.variation('key', 'default'); +var jsonFlagValue: ld.LDFlagValue = client.variation('key', [ 'a', 'b' ]); + +var detail: ld.LDEvaluationDetail = client.variationDetail('key', 'default'); +var detailValue: ld.LDFlagValue = detail.value; +var detailIndex: number | undefined = detail.variationIndex; +var detailReason: ld.LDEvaluationReason | undefined = detail.reason; + +client.setStreaming(true); +client.setStreaming(); + +function handleEvent() {} +client.on('event', handleEvent); +client.off('event', handleEvent); + +client.track('event'); +client.track('event', { someData: 'x' }); +client.track('event', null, 3.5); + +var flagSet: ld.LDFlagSet = client.allFlags(); +var flagSetValue: ld.LDFlagValue = flagSet['key']; + +client.close(() => {}); +client.close().then(() => {}); + +var contextKeys = ld.getContextKeys(user); diff --git a/node_modules/launchdarkly-js-sdk-common/tsconfig.json b/node_modules/launchdarkly-js-sdk-common/tsconfig.json new file mode 100644 index 00000000..3634ec41 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "module": "commonjs", + "strict": true, + "lib": [ + "es6" + ] + }, + "files": [ + "typings.d.ts", + "test-types.ts" + ] +} \ No newline at end of file diff --git a/node_modules/launchdarkly-js-sdk-common/typedoc.json b/node_modules/launchdarkly-js-sdk-common/typedoc.json new file mode 100644 index 00000000..976948eb --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/typedoc.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://typedoc.org/schema.json", + "name": "launchdarkly-js-sdk-common", + "includeVersion": true, + "entryPoints": [ + "typings.d.ts", + ] +} diff --git a/node_modules/launchdarkly-js-sdk-common/typings.d.ts b/node_modules/launchdarkly-js-sdk-common/typings.d.ts new file mode 100644 index 00000000..64844572 --- /dev/null +++ b/node_modules/launchdarkly-js-sdk-common/typings.d.ts @@ -0,0 +1,1500 @@ +/** + * Basic LaunchDarkly JavaScript client interfaces, shared between the browser SDK and the Electron SDK. + */ +declare module 'launchdarkly-js-sdk-common' { + /** + * The types of values a feature flag can have. + * + * Flags can have any JSON-serializable value. + */ + export type LDFlagValue = any; + + /** + * A map of feature flags from their keys to their values. + */ + export interface LDFlagSet { + [key: string]: LDFlagValue; + } + + /** + * A map of feature flag keys to objects holding changes in their values. + */ + export interface LDFlagChangeset { + [key: string]: { + current: LDFlagValue; + previous: LDFlagValue; + }; + } + + /** + * The minimal interface for any object that LDClient can use for logging. + * + * The client uses four log levels, with "error" being the most severe. Each corresponding + * logger method takes a single string parameter. The logger implementation is responsible + * for deciding whether to produce output or not based on the level. + */ + export interface LDLogger { + debug: (message: string) => void; + info: (message: string) => void; + warn: (message: string) => void; + error: (message: string) => void; + } + + /** + * Contextual information provided to evaluation stages. + */ + export interface EvaluationSeriesContext { + /** + * The flag key the evaluation is for. + */ + readonly flagKey: string; + /** + * Optional in case evaluations are performed before a context is set. + */ + readonly context?: LDContext; + /** + * The default value that was provided. + */ + readonly defaultValue: unknown; + + /** + * Implementation note: Omitting method name because of the associated size. + * If we need this functionality, then we may want to consider adding it and + * taking the associated size hit. + */ + } + + /** + * Implementation specific hook data for evaluation stages. + * + * Hook implementations can use this to store data needed between stages. + */ + export interface EvaluationSeriesData { + readonly [index: string]: unknown; + } + + /** + * Meta-data about a hook implementation. + */ + export interface HookMetadata { + /** + * Name of the hook. + */ + readonly name: string; + } + + /** + * Contextual information provided to identify stages. + */ + export interface IdentifySeriesContext { + /** + * The context associated with the identify operation. + */ + readonly context: LDContext; + /** + * The timeout, in seconds, associated with the identify operation. + */ + readonly timeout?: number; + } + + /** + * Implementation specific hook data for identify stages. + * + * Hook implementations can use this to store data needed between stages. + */ + export interface IdentifySeriesData { + readonly [index: string]: unknown; + } + + /** + * The status an identify operation completed with. + * + * An example in which an error may occur is lack of network connectivity + * preventing the SDK from functioning. + */ + export type IdentifySeriesStatus = 'completed' | 'error'; + + /** + * The result applies to a single identify operation. An operation may complete + * with an error and then later complete successfully. Only the first completion + * will be executed in the identify series. + * + * For example, a network issue may cause an identify to error since the SDK + * can't refresh its cached data from the cloud at that moment, but then later + * the when the network issue is resolved, the SDK will refresh cached data. + */ + export interface IdentifySeriesResult { + status: IdentifySeriesStatus; + } + + /** + * Contextual information provided to track stages. + */ + export interface TrackSeriesContext { + /** + * The key for the event being tracked. + */ + readonly key: string; + /** + * The context associated with the track operation. + */ + readonly context: LDContext; + /** + * The data associated with the track operation. + */ + readonly data?: unknown; + /** + * The metric value associated with the track operation. + */ + readonly metricValue?: number; + } + + + /** + * Interface for extending SDK functionality via hooks. + */ + export interface Hook { + /** + * Get metadata about the hook implementation. + */ + getMetadata(): HookMetadata; + + /** + * This method is called during the execution of a variation method + * before the flag value has been determined. The method is executed synchronously. + * + * @param hookContext Contains information about the evaluation being performed. This is not + * mutable. + * @param data A record associated with each stage of hook invocations. Each stage is called with + * the data of the previous stage for a series. The input record should not be modified. + * @returns Data to use when executing the next state of the hook in the evaluation series. It is + * recommended to expand the previous input into the return. This helps ensure your stage remains + * compatible moving forward as more stages are added. + * ```js + * return {...data, "my-new-field": /*my data/*} + * ``` + */ + beforeEvaluation?( + hookContext: EvaluationSeriesContext, + data: EvaluationSeriesData, + ): EvaluationSeriesData; + + /** + * This method is called during the execution of the variation method + * after the flag value has been determined. The method is executed synchronously. + * + * @param hookContext Contains read-only information about the evaluation + * being performed. + * @param data A record associated with each stage of hook invocations. Each + * stage is called with the data of the previous stage for a series. + * @param detail The result of the evaluation. This value should not be + * modified. + * @returns Data to use when executing the next state of the hook in the evaluation series. It is + * recommended to expand the previous input into the return. This helps ensure your stage remains + * compatible moving forward as more stages are added. + * ```js + * return {...data, "my-new-field": /*my data/*} + * ``` + */ + afterEvaluation?( + hookContext: EvaluationSeriesContext, + data: EvaluationSeriesData, + detail: LDEvaluationDetail, + ): EvaluationSeriesData; + + /** + * This method is called during the execution of the identify process before the operation + * completes, but after any context modifications are performed. + * + * @param hookContext Contains information about the identify operation being performed. This is not + * mutable. + * @param data A record associated with each stage of hook invocations. Each stage is called with + * the data of the previous stage for a series. The input record should not be modified. + * @returns Data to use when executing the next state of the hook in the evaluation series. It is + * recommended to expand the previous input into the return. This helps ensure your stage remains + * compatible moving forward as more stages are added. + * ```js + * return {...data, "my-new-field": /*my data/*} + * ``` + */ + beforeIdentify?(hookContext: IdentifySeriesContext, data: IdentifySeriesData): IdentifySeriesData; + + /** + * This method is called during the execution of the identify process before the operation + * completes, but after any context modifications are performed. + * + * @param hookContext Contains information about the identify operation being performed. This is not + * mutable. + * @param data A record associated with each stage of hook invocations. Each stage is called with + * the data of the previous stage for a series. The input record should not be modified. + * @returns Data to use when executing the next state of the hook in the evaluation series. It is + * recommended to expand the previous input into the return. This helps ensure your stage remains + * compatible moving forward as more stages are added. + * ```js + * return {...data, "my-new-field": /*my data/*} + * ``` + */ + afterIdentify?( + hookContext: IdentifySeriesContext, + data: IdentifySeriesData, + result: IdentifySeriesResult, + ): IdentifySeriesData; + + /** + * This method is called during the execution of the track process after the event + * has been enqueued. + * + * @param hookContext Contains information about the track operation being performed. This is not + * mutable. + */ + afterTrack?(hookContext: TrackSeriesContext): void; + } + + /** + * Meta-data about a plugin implementation. + * + * May be used in logs and analytics to identify the plugin. + */ + export interface LDPluginMetadata { + /** + * The name of the plugin. + */ + readonly name: string; + } + + /** + * Metadata about the SDK that is running the plugin. + */ + export interface LDPluginSdkMetadata { + /** + * The name of the SDK. + */ + readonly name: string; + + /** + * The version of the SDK. + */ + readonly version: string; + + /** + * If this is a wrapper SDK, then this is the name of the wrapper. + */ + readonly wrapperName?: string; + + /** + * If this is a wrapper SDK, then this is the version of the wrapper. + */ + readonly wrapperVersion?: string; + } + + /** + * Metadata about the application where the LaunchDarkly SDK is running. + */ + export interface LDPluginApplicationMetadata { + /** + * A unique identifier representing the application where the LaunchDarkly SDK is running. + * + * This can be specified as any string value as long as it only uses the following characters: ASCII letters, + * ASCII digits, period, hyphen, underscore. A string containing any other characters will be ignored. + * + * Example: `authentication-service` + */ + readonly id?: string; + + /** + * A unique identifier representing the version of the application where the LaunchDarkly SDK is running. + * + * This can be specified as any string value as long as it only uses the following characters: ASCII letters, + * ASCII digits, period, hyphen, underscore. A string containing any other characters will be ignored. + * + * Example: `1.0.0` (standard version string) or `abcdef` (sha prefix) + */ + readonly version?: string; + } + + /** + * Metadata about the environment where the plugin is running. + */ + export interface LDPluginEnvironmentMetadata { + /** + * Metadata about the SDK that is running the plugin. + */ + readonly sdk: LDPluginSdkMetadata; + + /** + * Metadata about the application where the LaunchDarkly SDK is running. + * + * Only present if any application information is available. + */ + readonly application?: LDPluginApplicationMetadata; + + /** + * The client-side ID used to initialize the SDK. + */ + readonly clientSideId: string; + } + +/** + * Interface for plugins to the LaunchDarkly SDK. + */ +export interface LDPlugin { + /** + * Get metadata about the plugin. + */ + getMetadata(): LDPluginMetadata; + + /** + * Registers the plugin with the SDK. Called once during SDK initialization. + * + * The SDK initialization will typically not have been completed at this point, so the plugin should take appropriate + * actions to ensure the SDK is ready before sending track events or evaluating flags. + * + * @param client The SDK client instance. + * @param environmentMetadata Information about the environment where the plugin is running. + */ + register(client: LDClientBase, environmentMetadata: LDPluginEnvironmentMetadata): void; + + /** + * Gets a list of hooks that the plugin wants to register. + * + * This method will be called once during SDK initialization before the register method is called. + * + * If the plugin does not need to register any hooks, this method doesn't need to be implemented. + * @param metadata + */ + getHooks?(metadata: LDPluginEnvironmentMetadata): Hook[]; +} + + /** + * LaunchDarkly initialization options that are supported by all variants of the JS client. + * The browser SDK and Electron SDK may support additional options. + * + * @ignore (don't need to show this separately in TypeDoc output; all properties will be shown in LDOptions) + */ + export interface LDOptionsBase { + /** + * An object that will perform logging for the client. + * + * If not specified, the default is to use `basicLogger`. + */ + logger?: LDLogger; + + /** + * The initial set of flags to use until the remote set is retrieved. + * + * If `"localStorage"` is specified, the flags will be saved and retrieved from browser local + * storage. Alternatively, an {@link LDFlagSet} can be specified which will be used as the initial + * source of flag values. In the latter case, the flag values will be available via {@link LDClient.variation} + * immediately after calling `initialize()` (normally they would not be available until the + * client signals that it is ready). + * + * For more information, see the [SDK Reference Guide](https://docs.launchdarkly.com/sdk/features/bootstrapping#javascript). + */ + bootstrap?: 'localStorage' | LDFlagSet; + + /** + * The base URL for the LaunchDarkly server. + * + * Most users should use the default value. + */ + baseUrl?: string; + + /** + * The base URL for the LaunchDarkly events server. + * + * Most users should use the default value. + */ + eventsUrl?: string; + + /** + * The base URL for the LaunchDarkly streaming server. + * + * Most users should use the default value. + */ + streamUrl?: string; + + /** + * Whether or not to open a streaming connection to LaunchDarkly for live flag updates. + * + * If this is true, the client will always attempt to maintain a streaming connection; if false, + * it never will. If you leave the value undefined (the default), the client will open a streaming + * connection if you subscribe to `"change"` or `"change:flag-key"` events (see {@link LDClient.on}). + * + * This is equivalent to calling `client.setStreaming()` with the same value. + */ + streaming?: boolean; + + /** + * Whether or not to use the REPORT verb to fetch flag settings. + * + * If this is true, flag settings will be fetched with a REPORT request + * including a JSON entity body with the context object. + * + * Otherwise (by default) a GET request will be issued with the context passed as + * a base64 URL-encoded path parameter. + * + * Do not use unless advised by LaunchDarkly. + */ + useReport?: boolean; + + /** + * Whether or not to include custom HTTP headers when requesting flags from LaunchDarkly. + * + * These are used to send metadata about the SDK (such as the version). They + * are also used to send the application.id and application.version set in + * the options. + * + * This defaults to true (custom headers will be sent). One reason you might + * want to set it to false is that the presence of custom headers causes + * browsers to make an extra OPTIONS request (a CORS preflight check) before + * each flag request, which could affect performance. + */ + sendLDHeaders?: boolean; + + /** + * A transform function for dynamic configuration of HTTP headers. + * + * This method will run last in the header generation sequence, so the function should have + * all system generated headers in case those also need to be modified. + */ + requestHeaderTransform?: (headers: Map) => Map; + + /** + * Whether LaunchDarkly should provide additional information about how flag values were + * calculated. + * + * The additional information will then be available through the client's + * {@link LDClient.variationDetail} method. Since this increases the size of network requests, + * such information is not sent unless you set this option to true. + */ + evaluationReasons?: boolean; + + /** + * Whether to send analytics events back to LaunchDarkly. By default, this is true. + */ + sendEvents?: boolean; + + /** + * Whether all context attributes (except the context key) should be marked as private, and + * not sent to LaunchDarkly in analytics events. + * + * By default, this is false. + */ + allAttributesPrivate?: boolean; + + /** + * Specifies a list of attribute names (either built-in or custom) which should be marked as + * private, and not sent to LaunchDarkly in analytics events. You can also specify this on a + * per-context basis with {@link LDContextMeta.privateAttributes}. + * + * Any contexts sent to LaunchDarkly with this configuration active will have attributes with + * these names removed in analytic events. This is in addition to any attributes that were + * marked as private for an individual context with {@link LDContextMeta.privateAttributes}. + * Setting {@link LDOptions.allAttributesPrivate} to true overrides this. + * + * If and only if a parameter starts with a slash, it is interpreted as a slash-delimited path + * that can denote a nested property within a JSON object. For instance, "/address/street" means + * that if there is an attribute called "address" that is a JSON object, and one of the object's + * properties is "street", the "street" property will be redacted from the analytics data but + * other properties within "address" will still be sent. This syntax also uses the JSON Pointer + * convention of escaping a literal slash character as "~1" and a tilde as "~0". + */ + privateAttributes?: Array; + + /** + * Whether analytics events should be sent only when you call variation (true), or also when you + * call allFlags (false). + * + * By default, this is false (events will be sent in both cases). + */ + sendEventsOnlyForVariation?: boolean; + + /** + * The capacity of the analytics events queue. + * + * The client buffers up to this many events in memory before flushing. If the capacity is exceeded + * before the queue is flushed, events will be discarded. Increasing the capacity means that events + * are less likely to be discarded, at the cost of consuming more memory. Note that in regular usage + * flag evaluations do not produce individual events, only summary counts, so you only need a large + * capacity if you are generating a large number of click, pageview, or identify events (or if you + * are using the event debugger). + * + * The default value is 100. + */ + eventCapacity?: number; + + /** + * The interval in between flushes of the analytics events queue, in milliseconds. + * + * The default value is 2000ms. + */ + flushInterval?: number; + + /** + * How long (in milliseconds) to wait after a failure of the stream connection before trying to + * reconnect. + * + * This only applies if streaming has been enabled by setting {@link streaming} to true or + * subscribing to `"change"` events. The default is 1000ms. + */ + streamReconnectDelay?: number; + + /** + * Set to true to opt out of sending diagnostics data. + * + * Unless `diagnosticOptOut` is set to true, the client will send some diagnostics data to the LaunchDarkly + * servers in order to assist in the development of future SDK improvements. These diagnostics consist of + * an initial payload containing some details of SDK in use, the SDK's configuration, and the platform the + * SDK is being run on, as well as payloads sent periodically with information on irregular occurrences such + * as dropped events. + */ + diagnosticOptOut?: boolean; + + /** + * The interval at which periodic diagnostic data is sent, in milliseconds. + * + * The default is 900000 (every 15 minutes) and the minimum value is 6000. See {@link diagnosticOptOut} + * for more information on the diagnostics data being sent. + */ + diagnosticRecordingInterval?: number; + + /** + * For use by wrapper libraries to set an identifying name for the wrapper being used. + * + * This will be sent as diagnostic information to the LaunchDarkly servers to allow recording + * metrics on the usage of these wrapper libraries. + */ + wrapperName?: string; + + /** + * For use by wrapper libraries to set version to be included alongside `wrapperName`. + * + * If `wrapperName` is unset, this field will be ignored. + */ + wrapperVersion?: string; + + /** + * Information about the application where the LaunchDarkly SDK is running. + */ + application?: { + /** + * A unique identifier representing the application where the LaunchDarkly SDK is running. + * + * This can be specified as any string value as long as it only uses the following characters: ASCII letters, + * ASCII digits, period, hyphen, underscore. A string containing any other characters will be ignored. + * + * Example: `authentication-service` + */ + id?: string; + + /** + * A unique identifier representing the version of the application where the LaunchDarkly SDK is running. + * + * This can be specified as any string value as long as it only uses the following characters: ASCII letters, + * ASCII digits, period, hyphen, underscore. A string containing any other characters will be ignored. + * + * Example: `1.0.0` (standard version string) or `abcdef` (sha prefix) + */ + version?: string; + }; + + /** + * Inspectors can be used for collecting information for monitoring, analytics, and debugging. + */ + inspectors?: LDInspection[]; + + /** + * Initial set of hooks for the client. + * + * Hooks provide entrypoints which allow for observation of SDK functions. + * + * LaunchDarkly provides integration packages, and most applications will not + * need to implement their own hooks. Refer to the `@launchdarkly/node-server-sdk-otel` + * for instrumentation for the `@launchdarkly/node-server-sdk`. + * + * Example: + * ```typescript + * import { initialize } from 'launchdarkly-js-client-sdk'; + * import { TheHook } from '@launchdarkly/some-hook'; + * + * const client = init('my-sdk-key', { hooks: [new TheHook()] }); + * ``` + */ + hooks?: Hook[]; + + /** + * A list of plugins to be used with the SDK. + * + * Plugin support is currently experimental and subject to change. + */ + plugins?: LDPlugin[]; + } + + /** + * Meta attributes are used to control behavioral aspects of the Context. + * They cannot be addressed in targeting rules. + */ + export interface LDContextMeta { + /** + * + * Designate any number of Context attributes, or properties within them, as private: that is, + * their values will not be sent to LaunchDarkly in analytics events. + * + * Each parameter can be a simple attribute name, such as "email". Or, if the first character is + * a slash, the parameter is interpreted as a slash-delimited path to a property within a JSON + * object, where the first path component is a Context attribute name and each following + * component is a nested property name: for example, suppose the attribute "address" had the + * following JSON object value: + * + * ``` + * {"street": {"line1": "abc", "line2": "def"}} + * ``` + * + * Using ["/address/street/line1"] in this case would cause the "line1" property to be marked as + * private. This syntax deliberately resembles JSON Pointer, but other JSON Pointer features + * such as array indexing are not supported for Private. + * + * This action only affects analytics events that involve this particular Context. To mark some + * (or all) Context attributes as private for all users, use the overall configuration for the + * SDK. + * See {@link LDOptions.allAttributesPrivate} and {@link LDOptions.privateAttributes}. + * + * The attributes "kind" and "key", and the "_meta" attributes cannot be made private. + * + * In this example, firstName is marked as private, but lastName is not: + * + * ``` + * const context = { + * kind: 'org', + * key: 'my-key', + * firstName: 'Pierre', + * lastName: 'Menard', + * _meta: { + * privateAttributes: ['firstName'], + * } + * }; + * ``` + * + * This is a metadata property, rather than an attribute that can be addressed in evaluations: + * that is, a rule clause that references the attribute name "privateAttributes", will not use + * this value, but would use a "privateAttributes" attribute set on the context. + */ + privateAttributes?: string[]; + } + + /** + * Interface containing elements which are common to both single kind contexts as well as the + * parts that compose a multi context. For more information see {@link LDSingleKindContext} and + * {@link LDMultiKindContext}. + */ + export interface LDContextCommon { + /** + * If true, the context will _not_ appear on the Contexts page in the LaunchDarkly dashboard. + */ + anonymous?: boolean; + + /** + * A unique string identifying a context. + * This value must be set unless the context is anonymous. + */ + key?: string; + + /** + * The context's name. + * + * You can search for contexts on the Contexts page by name. + */ + name?: string; + + /** + * Meta attributes are used to control behavioral aspects of the Context, such as private + * private attributes. See {@link LDContextMeta.privateAttributes} as an example. + * + * They cannot be addressed in targeting rules. + */ + _meta?: LDContextMeta; + + /** + * Any additional attributes associated with the context. + */ + [attribute: string]: any; + } + + /** + * A context which represents a single kind. + * + * For a single kind context the 'kind' may not be 'multi'. + * + * ``` + * const myOrgContext = { + * kind: 'org', + * key: 'my-org-key', + * someAttribute: 'my-attribute-value' + * }; + * ``` + * + * The above context would be a single kind context representing an organization. It has a key + * for that organization, and a single attribute 'someAttribute'. + */ + export interface LDSingleKindContext extends LDContextCommon { + /** + * The kind of the context. + */ + kind: string; + } + + /** + * A context which represents multiple kinds. Each kind having its own key and attributes. + * + * A multi-context must contain `kind: 'multi'` at the root. + * + * ``` + * const myMultiContext = { + * // Multi-contexts must be of kind 'multi'. + * kind: 'multi', + * // The context is namespaced by its kind. This is an 'org' kind context. + * org: { + * // Each component context has its own key and attributes. + * key: 'my-org-key', + * someAttribute: 'my-attribute-value', + * }, + * user: { + * key: 'my-user-key', + * firstName: 'Bob', + * lastName: 'Bobberson', + * _meta: { + * // Each component context has its own _meta attributes. This will only apply the this + * // 'user' context. + * privateAttributes: ['firstName'] + * } + * } + * }; + * ``` + * + * The above multi-context contains both an 'org' and a 'user'. Each with their own key, + * attributes, and _meta attributes. + */ + export interface LDMultiKindContext { + /** + * The kind of the context. + */ + kind: 'multi'; + + /** + * The contexts which compose this multi-kind context. + * + * These should be of type LDContextCommon. "multi" is to allow + * for the top level "kind" attribute. + */ + [kind: string]: 'multi' | LDContextCommon; + } + + /** + * A LaunchDarkly context object. + */ + export type LDContext = LDUser | LDSingleKindContext | LDMultiKindContext; + + /** + * A LaunchDarkly user object. + * + * @deprecated + * The LDUser object is currently supported for ease of upgrade. + * In order to convert an LDUser into a LDSingleKindContext the following changes should + * be made. + * + * 1.) Add a kind to the object. `kind: 'user'`. + * + * 2.) Move custom attributes to the top level of the object. + * + * 3.) Move `privateAttributeNames` to `_meta.privateAttributes`. + * + * ``` + * const LDUser: user = { + * key: '1234', + * privateAttributeNames: ['myAttr'] + * custom: { + * myAttr: 'value' + * } + * } + * + * const LDSingleKindContext: context = { + * kind: 'user', + * key: '1234', + * myAttr: 'value' + * _meta: { + * privateAttributes: ['myAttr'] + * } + * } + * ``` + */ + export interface LDUser { + /** + * A unique string identifying a user. + * + * If you omit this property, and also set `anonymous` to `true`, the SDK will generate a UUID string + * and use that as the key; it will attempt to persist that value in local storage if possible so the + * next anonymous user will get the same key, but if local storage is unavailable then it will + * generate a new key each time you specify the user. + * + * It is an error to omit the `key` property if `anonymous` is not set. + */ + key?: string; + + /** + * The user's name. + * + * You can search for users on the User page by name. + */ + name?: string; + + /** + * The user's first name. + */ + firstName?: string; + + /** + * The user's last name. + */ + lastName?: string; + + /** + * The user's email address. + * + * If an `avatar` URL is not provided, LaunchDarkly will use Gravatar + * to try to display an avatar for the user on the Users page. + */ + email?: string; + + /** + * An absolute URL to an avatar image for the user. + */ + avatar?: string; + + /** + * The user's IP address. + */ + ip?: string; + + /** + * The country associated with the user. + */ + country?: string; + + /** + * Whether to show the user on the Users page in LaunchDarkly. + */ + anonymous?: boolean; + + /** + * Any additional attributes associated with the user. + */ + custom?: { + [key: string]: string | boolean | number | Array; + }; + + /** + * Specifies a list of attribute names (either built-in or custom) which should be + * marked as private, and not sent to LaunchDarkly in analytics events. This is in + * addition to any private attributes designated in the global configuration + * with {@link LDOptions.privateAttributes} or {@link LDOptions.allAttributesPrivate}. + */ + privateAttributeNames?: Array; + } + + /** + * Describes the reason that a flag evaluation produced a particular value. This is + * part of the {@link LDEvaluationDetail} object returned by {@link LDClient.variationDetail}. + */ + export interface LDEvaluationReason { + /** + * The general category of the reason: + * + * - `'OFF'`: The flag was off and therefore returned its configured off value. + * - `'FALLTHROUGH'`: The flag was on but the context did not match any targets or rules. + * - `'TARGET_MATCH'`: The context key was specifically targeted for this flag. + * - `'RULE_MATCH'`: the context matched one of the flag's rules. + * - `'PREREQUISITE_FAILED'`: The flag was considered off because it had at least one + * prerequisite flag that either was off or did not return the desired variation. + * - `'ERROR'`: The flag could not be evaluated, e.g. because it does not exist or due + * to an unexpected error. + */ + kind: string; + + /** + * A further description of the error condition, if the kind was `'ERROR'`. + */ + errorKind?: string; + + /** + * The index of the matched rule (0 for the first), if the kind was `'RULE_MATCH'`. + */ + ruleIndex?: number; + + /** + * The unique identifier of the matched rule, if the kind was `'RULE_MATCH'`. + */ + ruleId?: string; + + /** + * The key of the failed prerequisite flag, if the kind was `'PREREQUISITE_FAILED'`. + */ + prerequisiteKey?: string; + + /** + * Whether the evaluation was part of an experiment. + * + * This is true if the evaluation resulted in an experiment rollout and served one of + * the variations in the experiment. Otherwise it is false or undefined. + */ + inExperiment?: boolean; + } + + /** + * An object that combines the result of a feature flag evaluation with information about + * how it was calculated. + * + * This is the result of calling {@link LDClient.variationDetail}. + * + * For more information, see the [SDK reference guide](https://docs.launchdarkly.com/sdk/features/evaluation-reasons#javascript). + */ + export interface LDEvaluationDetail { + /** + * The result of the flag evaluation. This will be either one of the flag's variations or + * the default value that was passed to {@link LDClient.variationDetail}. + */ + value: LDFlagValue; + + /** + * The index of the returned value within the flag's list of variations, e.g. 0 for the + * first variation-- or `null` if the default value was returned. + */ + variationIndex?: number; + + /** + * An object describing the main factor that influenced the flag evaluation value. + * This will be `null`/`undefined` if the SDK was not configured to get evaluation + * reasons. + */ + reason?: LDEvaluationReason; + } + + /** + * The basic interface for the LaunchDarkly client. Platform-specific SDKs may add some methods of their own. + * + * @see https://docs.launchdarkly.com/sdk/client-side/javascript + * + * @ignore (don't need to show this separately in TypeDoc output; all methods will be shown in LDClient) + */ + export interface LDClientBase { + /** + * Returns a Promise that tracks the client's initialization state. + * + * The returned Promise will be resolved once the client has either successfully initialized + * or failed to initialize (e.g. due to an invalid environment key or a server error). It will + * never be rejected. + * + * ``` + * // using a Promise then() handler + * client.waitUntilReady().then(() => { + * doSomethingWithClient(); + * }); + * + * // using async/await + * await client.waitUntilReady(); + * doSomethingWithClient(); + * ``` + * + * If you want to distinguish between these success and failure conditions, use + * {@link waitForInitialization} instead. + * + * If you prefer to use event listeners ({@link on}) rather than Promises, you can listen on the + * client for a `"ready"` event, which will be fired in either case. + * + * @returns + * A Promise that will be resolved once the client is no longer trying to initialize. + */ + waitUntilReady(): Promise; + + /** + * Returns a Promise that tracks the client's initialization state. + * + * The Promise will be resolved if the client successfully initializes, or rejected if client + * initialization has irrevocably failed (for instance, if it detects that the SDK key is invalid). + * + * ``` + * // using Promise then() and catch() handlers + * client.waitForInitialization(5).then(() => { + * doSomethingWithSuccessfullyInitializedClient(); + * }).catch(err => { + * doSomethingForFailedStartup(err); + * }); + * + * // using async/await + * try { + * await client.waitForInitialization(5); + * doSomethingWithSuccessfullyInitializedClient(); + * } catch (err) { + * doSomethingForFailedStartup(err); + * } + * ``` + * + * It is important that you handle the rejection case; otherwise it will become an unhandled Promise + * rejection, which is a serious error on some platforms. The Promise is not created unless you + * request it, so if you never call `waitForInitialization()` then you do not have to worry about + * unhandled rejections. + * + * Note that you can also use event listeners ({@link on}) for the same purpose: the event `"initialized"` + * indicates success, and `"failed"` indicates failure. + * + * @param timeout + * The amount of time, in seconds, to wait for initialization before rejecting the promise. + * Using a large timeout is not recommended. If you use a large timeout and await it, then + * any network delays will cause your application to wait a long time before + * continuing execution. + * + * If no timeout is specified, then the returned promise will only be resolved when the client + * successfully initializes or initialization fails. + * + * @returns + * A Promise that will be resolved if the client initializes successfully, or rejected if it + * fails or the specified timeout elapses. + */ + waitForInitialization(timeout?: number): Promise; + + /** + * Identifies a context to LaunchDarkly. + * + * Unlike the server-side SDKs, the client-side JavaScript SDKs maintain a current context state, + * which is set at initialization time. You only need to call `identify()` if the context has changed + * since then. + * + * Changing the current context also causes all feature flag values to be reloaded. Until that has + * finished, calls to {@link variation} will still return flag values for the previous context. You can + * use a callback or a Promise to determine when the new flag values are available. + * + * It is possible that the identify call will fail. In that case, when using a callback, the callback will receive + * an error value. While the SDK will continue to function, the developer will need to be aware that + * calls to {@link variation} will still return flag values for the previous context. + * + * When using a promise, it is important that you handle the rejection case; + * otherwise it will become an unhandled Promise rejection, which is a serious error on some platforms. + * + * @param context + * The context properties. Must contain at least the `key` property. + * @param hash + * The signed context key if you are using [Secure Mode](https://docs.launchdarkly.com/sdk/features/secure-mode#configuring-secure-mode-in-the-javascript-client-side-sdk). + * @param onDone + * A function which will be called as soon as the flag values for the new context are available, + * with two parameters: an error value (if any), and an {@link LDFlagSet} containing the new values + * (which can also be obtained by calling {@link variation}). If the callback is omitted, you will + * receive a Promise instead. + * @returns + * If you provided a callback, then nothing. Otherwise, a Promise which resolve once the flag + * values for the new context are available, providing an {@link LDFlagSet} containing the new values + * (which can also be obtained by calling {@link variation}). + */ + identify( + context: LDContext, + hash?: string, + onDone?: (err: Error | null, flags: LDFlagSet | null) => void + ): Promise; + + /** + * Returns the client's current context. + * + * This is the context that was most recently passed to {@link identify}, or, if {@link identify} has never + * been called, the initial context specified when the client was created. + */ + getContext(): LDContext; + + /** + * Flushes all pending analytics events. + * + * Normally, batches of events are delivered in the background at intervals determined by the + * `flushInterval` property of {@link LDOptions}. Calling `flush()` triggers an immediate delivery. + * + * @param onDone + * A function which will be called when the flush completes. If omitted, you + * will receive a Promise instead. + * + * @returns + * If you provided a callback, then nothing. Otherwise, a Promise which resolves once + * flushing is finished. Note that the Promise will be rejected if the HTTP request + * fails, so be sure to attach a rejection handler to it. + */ + flush(onDone?: () => void): Promise; + + /** + * Determines the variation of a feature flag for the current context. + * + * In the client-side JavaScript SDKs, this is always a fast synchronous operation because all of + * the feature flag values for the current context have already been loaded into memory. + * + * @param key + * The unique key of the feature flag. + * @param defaultValue + * The default value of the flag, to be used if the value is not available from LaunchDarkly. + * @returns + * The flag's value. + */ + variation(key: string, defaultValue?: LDFlagValue): LDFlagValue; + + /** + * Determines the variation of a feature flag for a context, along with information about how it was + * calculated. + * + * Note that this will only work if you have set `evaluationReasons` to true in {@link LDOptions}. + * Otherwise, the `reason` property of the result will be null. + * + * The `reason` property of the result will also be included in analytics events, if you are + * capturing detailed event data for this flag. + * + * For more information, see the [SDK reference guide](https://docs.launchdarkly.com/sdk/features/evaluation-reasons#javascript). + * + * @param key + * The unique key of the feature flag. + * @param defaultValue + * The default value of the flag, to be used if the value is not available from LaunchDarkly. + * + * @returns + * An {@link LDEvaluationDetail} object containing the value and explanation. + */ + variationDetail(key: string, defaultValue?: LDFlagValue): LDEvaluationDetail; + + /** + * Specifies whether or not to open a streaming connection to LaunchDarkly for live flag updates. + * + * If this is true, the client will always attempt to maintain a streaming connection; if false, + * it never will. If you leave the value undefined (the default), the client will open a streaming + * connection if you subscribe to `"change"` or `"change:flag-key"` events (see {@link LDClient.on}). + * + * This can also be set as the `streaming` property of {@link LDOptions}. + */ + setStreaming(value?: boolean): void; + + /** + * Registers an event listener. + * + * The following event names (keys) are used by the client: + * + * - `"ready"`: The client has finished starting up. This event will be sent regardless + * of whether it successfully connected to LaunchDarkly, or encountered an error + * and had to give up; to distinguish between these cases, see below. + * - `"initialized"`: The client successfully started up and has valid feature flag + * data. This will always be accompanied by `"ready"`. + * - `"failed"`: The client encountered an error that prevented it from connecting to + * LaunchDarkly, such as an invalid environment ID. All flag evaluations will + * therefore receive default values. This will always be accompanied by `"ready"`. + * - `"error"`: General event for any kind of error condition during client operation. + * The callback parameter is an Error object. If you do not listen for "error" + * events, then the errors will be logged with `console.log()`. + * - `"change"`: The client has received new feature flag data. This can happen either + * because you have switched contexts with {@link identify}, or because the client has a + * stream connection and has received a live change to a flag value (see below). + * The callback parameter is an {@link LDFlagChangeset}. + * - `"change:FLAG-KEY"`: The client has received a new value for a specific flag + * whose key is `FLAG-KEY`. The callback receives two parameters: the current (new) + * flag value, and the previous value. This is always accompanied by a general + * `"change"` event as described above; you can listen for either or both. + * + * The `"change"` and `"change:FLAG-KEY"` events have special behavior: by default, the + * client will open a streaming connection to receive live changes if and only if + * you are listening for one of these events. This behavior can be overridden by + * setting `streaming` in {@link LDOptions} or calling {@link LDClient.setStreaming}. + * + * @param key + * The name of the event for which to listen. + * @param callback + * The function to execute when the event fires. The callback may or may not + * receive parameters, depending on the type of event. + * @param context + * The `this` context to use for the callback. + */ + on(key: string, callback: (...args: any[]) => void, context?: any): void; + + /** + * Deregisters an event listener. See {@link on} for the available event types. + * + * @param key + * The name of the event for which to stop listening. + * @param callback + * The function to deregister. + * @param context + * The `this` context for the callback, if one was specified for {@link on}. + */ + off(key: string, callback: (...args: any[]) => void, context?: any): void; + + /** + * Track page events to use in metrics (goals) or Experimentation. + * + * LaunchDarkly automatically tracks pageviews and clicks that are specified in the + * Metrics section of their dashboard. This can be used to track custom metrics or other + * events that do not currently have metrics. + * + * @param key + * The name of the event, which may correspond to a metric in experiments. + * @param data + * Additional information to associate with the event. + * @param metricValue + * An optional numeric value that can be used by the LaunchDarkly experimentation + * feature in numeric custom metrics. Can be omitted if this event is used by only + * non-numeric metrics. This field will also be returned as part of the custom event + * for Data Export. + */ + track(key: string, data?: any, metricValue?: number): void; + + /** + * Returns a map of all available flags to the current context's values. + * + * @returns + * An object in which each key is a feature flag key and each value is the flag value. + * Note that there is no way to specify a default value for each flag as there is with + * {@link variation}, so any flag that cannot be evaluated will have a null value. + */ + allFlags(): LDFlagSet; + + /** + * Shuts down the client and releases its resources, after delivering any pending analytics + * events. After the client is closed, all calls to {@link variation} will return default values, + * and it will not make any requests to LaunchDarkly. + * + * @param onDone + * A function which will be called when the operation completes. If omitted, you + * will receive a Promise instead. + * + * @returns + * If you provided a callback, then nothing. Otherwise, a Promise which resolves once + * closing is finished. It will never be rejected. + */ + close(onDone?: () => void): Promise; + + /** + * Add a hook to the client. In order to register a hook before the client + * starts, please use the `hooks` property of {@link LDOptions}. + * + * Hooks provide entrypoints which allow for observation of SDK functions. + * + * @param Hook The hook to add. + */ + addHook(hook: Hook): void; + } + + /** + * Provides a simple {@link LDLogger} implementation. + * + * This logging implementation uses a simple format that includes only the log level + * and the message text. Output is written to the console unless otherwise specified. + * You can filter by log level as described in {@link BasicLoggerOptions.level}. + * + * To use the logger created by this function, put it into {@link LDOptions.logger}. If + * you do not set {@link LDOptions.logger} to anything, the SDK uses a default logger + * that is equivalent to `ld.basicLogger({ level: 'info' })`. + * + * @param options Configuration for the logger. If no options are specified, the + * logger uses `{ level: 'info' }`. + * + * @param formatter An optional function equivalent to Node's util.format, allowing + * for parameter substitution in log messages. If this is omitted, parameter + * substitution is not available. + * + * @example + * This example shows how to use `basicLogger` in your SDK options to enable console + * logging only at `warn` and `error` levels. + * ```javascript + * const ldOptions = { + * logger: ld.basicLogger({ level: 'warn' }), + * }; + * ``` + * + * @example + * This example shows how to use `basicLogger` in your SDK options to cause log + * output to always go to `console.error` instead of `console.log`. + * ```javascript + * const ldOptions = { + * logger: ld.basicLogger({ destination: console.error }), + * }; + * ``` + * + * @ignore (don't need to show this separately in TypeDoc output; each SDK should provide its own + * basicLogger function that delegates to this and sets the formatter parameter) + */ + export function commonBasicLogger( + options?: BasicLoggerOptions, + formatter?: (format: string, ...args: any[]) => void + ): LDLogger; + + /** + * Configuration for {@link basicLogger}. + */ + export interface BasicLoggerOptions { + /** + * The lowest level of log message to enable. + * + * See {@link LDLogLevel} for a list of possible levels. Setting a level here causes + * all lower-importance levels to be disabled: for instance, if you specify + * `'warn'`, then `'debug'` and `'info'` are disabled. + * + * If not specified, the default is `'info'` (meaning that `'debug'` is disabled). + */ + level?: LDLogLevel; + + /** + * A string to prepend to all log output. If not specified, the default is + * "[LaunchDarkly] ". + */ + prefix?: string; + + /** + * An optional function to use to print each log line. + * + * If this is specified, `basicLogger` calls it to write each line of output. The + * argument is a fully formatted log line, not including a linefeed. The function + * is only called for log levels that are enabled. + * + * If not specified, the default in browsers is to use `console.log`, `console.info`, + * `console.warn`, or `console.error` according to the level; the default in + * Node.js and Electron is to always use `console.log`. + * + * Setting this property to anything other than a function will cause SDK + * initialization to fail. + */ + destination?: (line: string) => void; + } + + /** + * Logging levels that can be used with {@link basicLogger}. + * + * Set {@link BasicLoggerOptions.level} to one of these values to control what levels + * of log messages are enabled. Going from lowest importance (and most verbose) + * to most importance, the levels are `'debug'`, `'info'`, `'warn'`, and `'error'`. + * You can also specify `'none'` instead to disable all logging. + */ + export type LDLogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none'; + + export function getContextKeys(context: LDContext, logger?: LDLogger): { [attribute: string]: string } | undefined; + + /** + * Callback interface for collecting information about the SDK at runtime. + * + * This interface is used to collect information about flag usage. + * + * This interface should not be used by the application to access flags for the purpose of controlling application + * flow. It is intended for monitoring, analytics, or debugging purposes. + */ + export interface LDInspectionFlagUsedHandler { + type: 'flag-used'; + + /** + * Name of the inspector. Will be used for logging issues with the inspector. + */ + name: string; + + /** + * If `true`, then the inspector will be ran synchronously with evaluation. + * Synchronous inspectors execute inline with evaluation and care should be taken to ensure + * they have minimal performance overhead. + */ + synchronous?: boolean, + + /** + * This method is called when a flag is accessed via a variation method, or it can be called based on actions in + * wrapper SDKs which have different methods of tracking when a flag was accessed. It is not called when a call is made + * to allFlags. + */ + method: (flagKey: string, flagDetail: LDEvaluationDetail, context: LDContext) => void; + } + + /** + * Callback interface for collecting information about the SDK at runtime. + * + * This interface is used to collect information about flag data. In order to understand the + * current flag state it should be combined with {@link LDInspectionFlagValueChangedHandler}. + * This interface will get the initial flag information, and + * {@link LDInspectionFlagValueChangedHandler} will provide changes to individual flags. + * + * This interface should not be used by the application to access flags for the purpose of controlling application + * flow. It is intended for monitoring, analytics, or debugging purposes. + */ + export interface LDInspectionFlagDetailsChangedHandler { + type: 'flag-details-changed'; + + /** + * Name of the inspector. Will be used for logging issues with the inspector. + */ + name: string; + + /** + * If `true`, then the inspector will be ran synchronously with flag updates. + */ + synchronous?: boolean, + + /** + * This method is called when the flags in the store are replaced with new flags. It will contain all flags + * regardless of if they have been evaluated. + */ + method: (details: Record) => void; + } + + /** + * Callback interface for collecting information about the SDK at runtime. + * + * This interface is used to collect changes to flag data, but does not provide the initial + * data. It can be combined with {@link LDInspectionFlagValuesChangedHandler} to track the + * entire flag state. + * + * This interface should not be used by the application to access flags for the purpose of controlling application + * flow. It is intended for monitoring, analytics, or debugging purposes. + */ + export interface LDInspectionFlagDetailChangedHandler { + type: 'flag-detail-changed'; + + /** + * Name of the inspector. Will be used for logging issues with the inspector. + */ + name: string; + + /** + * If `true`, then the inspector will be ran synchronously with flag updates. + */ + synchronous?: boolean, + + /** + * This method is called when a flag is updated. It will not be called + * when all flags are updated. + */ + method: (flagKey: string, detail: LDEvaluationDetail) => void; + } + + /** + * Callback interface for collecting information about the SDK at runtime. + * + * This interface is used to track current identity state of the SDK. + * + * This interface should not be used by the application to access flags for the purpose of controlling application + * flow. It is intended for monitoring, analytics, or debugging purposes. + */ + export interface LDInspectionIdentifyHandler { + type: 'client-identity-changed'; + + /** + * Name of the inspector. Will be used for logging issues with the inspector. + */ + name: string; + + /** + * If `true`, then the inspector will be ran synchronously with identification. + */ + synchronous?: boolean, + + /** + * This method will be called when an identify operation completes. + */ + method: (context: LDContext) => void; + } + + export type LDInspection = + | LDInspectionFlagUsedHandler + | LDInspectionFlagDetailsChangedHandler + | LDInspectionFlagDetailChangedHandler + | LDInspectionIdentifyHandler; +} diff --git a/node_modules/levn/LICENSE b/node_modules/levn/LICENSE new file mode 100644 index 00000000..525b1185 --- /dev/null +++ b/node_modules/levn/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) George Zahariev + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/levn/README.md b/node_modules/levn/README.md new file mode 100644 index 00000000..7ab008d6 --- /dev/null +++ b/node_modules/levn/README.md @@ -0,0 +1,196 @@ +# levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) +__Light ECMAScript (JavaScript) Value Notation__ +Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments). + +Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.4.1. + +__How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose. + + npm install levn + +For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev). + + +## Quick Examples + +```js +var parse = require('levn').parse; +parse('Number', '2'); // 2 +parse('String', '2'); // '2' +parse('String', 'levn'); // 'levn' +parse('String', 'a b'); // 'a b' +parse('Boolean', 'true'); // true + +parse('Date', '#2011-11-11#'); // (Date object) +parse('Date', '2011-11-11'); // (Date object) +parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi +parse('RegExp', 're'); // /re/ +parse('Int', '2'); // 2 + +parse('Number | String', 'str'); // 'str' +parse('Number | String', '2'); // 2 + +parse('[Number]', '[1,2,3]'); // [1,2,3] +parse('(String, Boolean)', '(hi, false)'); // ['hi', false] +parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2} + +// at the top level, you can ommit surrounding delimiters +parse('[Number]', '1,2,3'); // [1,2,3] +parse('(String, Boolean)', 'hi, false'); // ['hi', false] +parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2} + +// wildcard - auto choose type +parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}] +``` +## Usage + +`require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions. + +```js +// parse(type, input, options); +parse('[Number]', '1,2,3'); // [1, 2, 3] + +// parsedTypeParse(parsedType, input, options); +var parsedType = require('type-check').parseType('[Number]'); +parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] +``` + +### parse(type, input, options) + +`parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value. + +##### arguments +* type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against +* input - `String` - the value written in the [levn format](#levn-format) +* options - `Maybe Object` - an optional parameter specifying additional [options](#options) + +##### returns +`*` - the resulting JavaScript value + +##### example +```js +parse('[Number]', '1,2,3'); // [1, 2, 3] +``` + +### parsedTypeParse(parsedType, input, options) + +`parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function. + +##### arguments +* type - `Object` - the type in the parsed type format which to check against +* input - `String` - the value written in the [levn format](#levn-format) +* options - `Maybe Object` - an optional parameter specifying additional [options](#options) + +##### returns +`*` - the resulting JavaScript value + +##### example +```js +var parsedType = require('type-check').parseType('[Number]'); +parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] +``` + +## Levn Format + +Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`. + +If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options). + +* `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"` +* `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')` +* `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi` +* `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents +* `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`. +* `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`). +* `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`. +* Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`. + +If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information: + +* If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`. +* If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`. +* If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`. +* If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`. +* If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`). +* If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`. + +If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list. + +Whitespace between special characters and elements is inconsequential. + +## Options + +Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions. + +### Explicit + +A `Boolean`. By default it is `false`. + +__Example:__ + +```js +parse('RegExp', 're', {explicit: false}); // /re/ +parse('RegExp', 're', {explicit: true}); // Error: ... does not type check... +parse('RegExp | String', 're', {explicit: true}); // 're' +``` + +`explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section. + +### customTypes + +An `Object`. Empty `{}` by default. + +__Example:__ + +```js +var options = { + customTypes: { + Even: { + typeOf: 'Number', + validate: function (x) { + return x % 2 === 0; + }, + cast: function (x) { + return {type: 'Just', value: parseInt(x)}; + } + } + } +} +parse('Even', '2', options); // 2 +parse('Even', '3', options); // Error: Value: "3" does not type check... +``` + +__Another Example:__ +```js +function Person(name, age){ + this.name = name; + this.age = age; +} +var options = { + customTypes: { + Person: { + typeOf: 'Object', + validate: function (x) { + x instanceof Person; + }, + cast: function (value, options, typesCast) { + var name, age; + if ({}.toString.call(value).slice(8, -1) !== 'Object') { + return {type: 'Nothing'}; + } + name = typesCast(value.name, [{type: 'String'}], options); + age = typesCast(value.age, [{type: 'Numger'}], options); + return {type: 'Just', value: new Person(name, age)}; + } + } +} +parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25} +``` + +`customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check. + +`cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly. + +## Technical About + +`levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library. diff --git a/node_modules/levn/lib/cast.js b/node_modules/levn/lib/cast.js new file mode 100644 index 00000000..92cb9a6d --- /dev/null +++ b/node_modules/levn/lib/cast.js @@ -0,0 +1,327 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var parsedTypeCheck, types, toString$ = {}.toString; + parsedTypeCheck = require('type-check').parsedTypeCheck; + types = { + '*': function(value, options){ + switch (toString$.call(value).slice(8, -1)) { + case 'Array': + return typeCast(value, { + type: 'Array' + }, options); + case 'Object': + return typeCast(value, { + type: 'Object' + }, options); + default: + return { + type: 'Just', + value: typesCast(value, [ + { + type: 'Undefined' + }, { + type: 'Null' + }, { + type: 'NaN' + }, { + type: 'Boolean' + }, { + type: 'Number' + }, { + type: 'Date' + }, { + type: 'RegExp' + }, { + type: 'Array' + }, { + type: 'Object' + }, { + type: 'String' + } + ], (options.explicit = true, options)) + }; + } + }, + Undefined: function(it){ + if (it === 'undefined' || it === void 8) { + return { + type: 'Just', + value: void 8 + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Null: function(it){ + if (it === 'null') { + return { + type: 'Just', + value: null + }; + } else { + return { + type: 'Nothing' + }; + } + }, + NaN: function(it){ + if (it === 'NaN') { + return { + type: 'Just', + value: NaN + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Boolean: function(it){ + if (it === 'true') { + return { + type: 'Just', + value: true + }; + } else if (it === 'false') { + return { + type: 'Just', + value: false + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Number: function(it){ + return { + type: 'Just', + value: +it + }; + }, + Int: function(it){ + return { + type: 'Just', + value: +it + }; + }, + Float: function(it){ + return { + type: 'Just', + value: +it + }; + }, + Date: function(value, options){ + var that; + if (that = /^\#([\s\S]*)\#$/.exec(value)) { + return { + type: 'Just', + value: new Date(+that[1] || that[1]) + }; + } else if (options.explicit) { + return { + type: 'Nothing' + }; + } else { + return { + type: 'Just', + value: new Date(+value || value) + }; + } + }, + RegExp: function(value, options){ + var that; + if (that = /^\/([\s\S]*)\/([gimy]*)$/.exec(value)) { + return { + type: 'Just', + value: new RegExp(that[1], that[2]) + }; + } else if (options.explicit) { + return { + type: 'Nothing' + }; + } else { + return { + type: 'Just', + value: new RegExp(value) + }; + } + }, + Array: function(value, options){ + return castArray(value, { + of: [{ + type: '*' + }] + }, options); + }, + Object: function(value, options){ + return castFields(value, { + of: {} + }, options); + }, + String: function(it){ + var replace, that; + if (toString$.call(it).slice(8, -1) !== 'String') { + return { + type: 'Nothing' + }; + } + replace = function(value, quote){ + return value.replace(/\\([^u]|u[0-9a-fA-F]{4})/g, function(all, escaped){ + switch (escaped[0]) { + case quote: + return quote; + case '\\': + return '\\'; + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'u': + return JSON.parse("\"" + all + "\""); + default: + return escaped; + } + }); + }; + if (that = it.match(/^'([\s\S]*)'$/)) { + return { + type: 'Just', + value: replace(that[1], "'") + }; + } else if (that = it.match(/^"([\s\S]*)"$/)) { + return { + type: 'Just', + value: replace(that[1], '"') + }; + } else { + return { + type: 'Just', + value: it + }; + } + } + }; + function castArray(node, type, options){ + var typeOf, element; + if (toString$.call(node).slice(8, -1) !== 'Array') { + return { + type: 'Nothing' + }; + } + typeOf = type.of; + return { + type: 'Just', + value: (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) { + element = ref$[i$]; + results$.push(typesCast(element, typeOf, options)); + } + return results$; + }()) + }; + } + function castTuple(node, type, options){ + var result, i, i$, ref$, len$, types, cast; + if (toString$.call(node).slice(8, -1) !== 'Array') { + return { + type: 'Nothing' + }; + } + result = []; + i = 0; + for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) { + types = ref$[i$]; + cast = typesCast(node[i], types, options); + if (toString$.call(cast).slice(8, -1) !== 'Undefined') { + result.push(cast); + } + i++; + } + if (node.length <= i) { + return { + type: 'Just', + value: result + }; + } else { + return { + type: 'Nothing' + }; + } + } + function castFields(node, type, options){ + var typeOf, key, value; + if (toString$.call(node).slice(8, -1) !== 'Object') { + return { + type: 'Nothing' + }; + } + typeOf = type.of; + return { + type: 'Just', + value: (function(){ + var ref$, resultObj$ = {}; + for (key in ref$ = node) { + value = ref$[key]; + resultObj$[typesCast(key, [{ + type: 'String' + }], options)] = typesCast(value, typeOf[key] || [{ + type: '*' + }], options); + } + return resultObj$; + }()) + }; + } + function typeCast(node, typeObj, options){ + var type, structure, castFunc, ref$; + type = typeObj.type, structure = typeObj.structure; + if (type) { + castFunc = ((ref$ = options.customTypes[type]) != null ? ref$.cast : void 8) || types[type]; + if (!castFunc) { + throw new Error("Type not defined: " + type + "."); + } + return castFunc(node, options, typesCast); + } else { + switch (structure) { + case 'array': + return castArray(node, typeObj, options); + case 'tuple': + return castTuple(node, typeObj, options); + case 'fields': + return castFields(node, typeObj, options); + } + } + } + function typesCast(node, types, options){ + var i$, len$, type, ref$, valueType, value; + for (i$ = 0, len$ = types.length; i$ < len$; ++i$) { + type = types[i$]; + ref$ = typeCast(node, type, options), valueType = ref$.type, value = ref$.value; + if (valueType === 'Nothing') { + continue; + } + if (parsedTypeCheck([type], value, { + customTypes: options.customTypes + })) { + return value; + } + } + throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + "."); + } + module.exports = function(node, types, options){ + if (!options.explicit && types.length === 1 && types[0].type === 'String') { + return node; + } + return typesCast(node, types, options); + }; +}).call(this); diff --git a/node_modules/levn/lib/index.js b/node_modules/levn/lib/index.js new file mode 100644 index 00000000..b8b66840 --- /dev/null +++ b/node_modules/levn/lib/index.js @@ -0,0 +1,22 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var parseString, cast, parseType, VERSION, parsedTypeParse, parse; + parseString = require('./parse-string'); + cast = require('./cast'); + parseType = require('type-check').parseType; + VERSION = '0.4.1'; + parsedTypeParse = function(parsedType, string, options){ + options == null && (options = {}); + options.explicit == null && (options.explicit = false); + options.customTypes == null && (options.customTypes = {}); + return cast(parseString(parsedType, string, options), parsedType, options); + }; + parse = function(type, string, options){ + return parsedTypeParse(parseType(type), string, options); + }; + module.exports = { + VERSION: VERSION, + parse: parse, + parsedTypeParse: parsedTypeParse + }; +}).call(this); diff --git a/node_modules/levn/lib/parse-string.js b/node_modules/levn/lib/parse-string.js new file mode 100644 index 00000000..eaed2f06 --- /dev/null +++ b/node_modules/levn/lib/parse-string.js @@ -0,0 +1,113 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var reject, special, tokenRegex; + reject = require('prelude-ls').reject; + function consumeOp(tokens, op){ + if (tokens[0] === op) { + return tokens.shift(); + } else { + throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + "."); + } + } + function maybeConsumeOp(tokens, op){ + if (tokens[0] === op) { + return tokens.shift(); + } + } + function consumeList(tokens, arg$, hasDelimiters){ + var open, close, result, untilTest; + open = arg$[0], close = arg$[1]; + if (hasDelimiters) { + consumeOp(tokens, open); + } + result = []; + untilTest = "," + (hasDelimiters ? close : ''); + while (tokens.length && (hasDelimiters && tokens[0] !== close)) { + result.push(consumeElement(tokens, untilTest)); + maybeConsumeOp(tokens, ','); + } + if (hasDelimiters) { + consumeOp(tokens, close); + } + return result; + } + function consumeArray(tokens, hasDelimiters){ + return consumeList(tokens, ['[', ']'], hasDelimiters); + } + function consumeTuple(tokens, hasDelimiters){ + return consumeList(tokens, ['(', ')'], hasDelimiters); + } + function consumeFields(tokens, hasDelimiters){ + var result, untilTest, key; + if (hasDelimiters) { + consumeOp(tokens, '{'); + } + result = {}; + untilTest = "," + (hasDelimiters ? '}' : ''); + while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) { + key = consumeValue(tokens, ':'); + consumeOp(tokens, ':'); + result[key] = consumeElement(tokens, untilTest); + maybeConsumeOp(tokens, ','); + } + if (hasDelimiters) { + consumeOp(tokens, '}'); + } + return result; + } + function consumeValue(tokens, untilTest){ + var out; + untilTest == null && (untilTest = ''); + out = ''; + while (tokens.length && -1 === untilTest.indexOf(tokens[0])) { + out += tokens.shift(); + } + return out; + } + function consumeElement(tokens, untilTest){ + switch (tokens[0]) { + case '[': + return consumeArray(tokens, true); + case '(': + return consumeTuple(tokens, true); + case '{': + return consumeFields(tokens, true); + default: + return consumeValue(tokens, untilTest); + } + } + function consumeTopLevel(tokens, types, options){ + var ref$, type, structure, origTokens, result, finalResult, x$, y$; + ref$ = types[0], type = ref$.type, structure = ref$.structure; + origTokens = tokens.concat(); + if (!options.explicit && types.length === 1 && ((!type && structure) || (type === 'Array' || type === 'Object'))) { + result = structure === 'array' || type === 'Array' + ? consumeArray(tokens, tokens[0] === '[') + : structure === 'tuple' + ? consumeTuple(tokens, tokens[0] === '(') + : consumeFields(tokens, tokens[0] === '{'); + finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array' + ? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$) + : (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result; + } else { + finalResult = consumeElement(tokens); + } + return finalResult; + } + special = /\[\]\(\)}{:,/.source; + tokenRegex = RegExp('("(?:\\\\"|[^"])*")|(\'(?:\\\\\'|[^\'])*\')|(/(?:\\\\/|[^/])*/[a-zA-Z]*)|(#.*#)|([' + special + '])|([^\\s' + special + '](?:\\s*[^\\s' + special + ']+)*)|\\s*'); + module.exports = function(types, string, options){ + var tokens, node; + options == null && (options = {}); + if (!options.explicit && types.length === 1 && types[0].type === 'String') { + return string; + } + tokens = reject(not$, string.split(tokenRegex)); + node = consumeTopLevel(tokens, types, options); + if (!node) { + throw new Error("Error parsing '" + string + "'."); + } + return node; + }; + function not$(x){ return !x; } +}).call(this); diff --git a/node_modules/levn/package.json b/node_modules/levn/package.json new file mode 100644 index 00000000..0c356d69 --- /dev/null +++ b/node_modules/levn/package.json @@ -0,0 +1,46 @@ +{ + "name": "levn", + "version": "0.4.1", + "author": "George Zahariev ", + "description": "Light ECMAScript (JavaScript) Value Notation - human written, concise, typed, flexible", + "homepage": "https://github.com/gkz/levn", + "keywords": [ + "levn", + "light", + "ecmascript", + "value", + "notation", + "json", + "typed", + "human", + "concise", + "typed", + "flexible" + ], + "files": [ + "lib", + "README.md", + "LICENSE" + ], + "main": "./lib/", + "bugs": "https://github.com/gkz/levn/issues", + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/gkz/levn.git" + }, + "scripts": { + "test": "make test" + }, + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "devDependencies": { + "livescript": "^1.6.0", + "mocha": "^7.1.1" + } +} diff --git a/node_modules/locate-path/index.d.ts b/node_modules/locate-path/index.d.ts new file mode 100644 index 00000000..a714f1d3 --- /dev/null +++ b/node_modules/locate-path/index.d.ts @@ -0,0 +1,83 @@ +declare namespace locatePath { + interface Options { + /** + Current working directory. + + @default process.cwd() + */ + readonly cwd?: string; + + /** + Type of path to match. + + @default 'file' + */ + readonly type?: 'file' | 'directory'; + + /** + Allow symbolic links to match if they point to the requested path type. + + @default true + */ + readonly allowSymlinks?: boolean; + } + + interface AsyncOptions extends Options { + /** + Number of concurrently pending promises. Minimum: `1`. + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `paths` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; + } +} + +declare const locatePath: { + /** + Synchronously get the first path that exists on disk of multiple paths. + + @param paths - Paths to check. + @returns The first path that exists or `undefined` if none exists. + */ + sync: ( + paths: Iterable, + options?: locatePath.Options + ) => string | undefined; + + /** + Get the first path that exists on disk of multiple paths. + + @param paths - Paths to check. + @returns The first path that exists or `undefined` if none exists. + + @example + ``` + import locatePath = require('locate-path'); + + const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' + ]; + + (async () => { + console(await locatePath(files)); + //=> 'rainbow' + })(); + ``` + */ + (paths: Iterable, options?: locatePath.AsyncOptions): Promise< + string | undefined + >; +}; + +export = locatePath; diff --git a/node_modules/locate-path/index.js b/node_modules/locate-path/index.js new file mode 100644 index 00000000..a6358e54 --- /dev/null +++ b/node_modules/locate-path/index.js @@ -0,0 +1,68 @@ +'use strict'; +const path = require('path'); +const fs = require('fs'); +const {promisify} = require('util'); +const pLocate = require('p-locate'); + +const fsStat = promisify(fs.stat); +const fsLStat = promisify(fs.lstat); + +const typeMappings = { + directory: 'isDirectory', + file: 'isFile' +}; + +function checkType({type}) { + if (type in typeMappings) { + return; + } + + throw new Error(`Invalid type specified: ${type}`); +} + +const matchType = (type, stat) => type === undefined || stat[typeMappings[type]](); + +module.exports = async (paths, options) => { + options = { + cwd: process.cwd(), + type: 'file', + allowSymlinks: true, + ...options + }; + + checkType(options); + + const statFn = options.allowSymlinks ? fsStat : fsLStat; + + return pLocate(paths, async path_ => { + try { + const stat = await statFn(path.resolve(options.cwd, path_)); + return matchType(options.type, stat); + } catch { + return false; + } + }, options); +}; + +module.exports.sync = (paths, options) => { + options = { + cwd: process.cwd(), + allowSymlinks: true, + type: 'file', + ...options + }; + + checkType(options); + + const statFn = options.allowSymlinks ? fs.statSync : fs.lstatSync; + + for (const path_ of paths) { + try { + const stat = statFn(path.resolve(options.cwd, path_)); + + if (matchType(options.type, stat)) { + return path_; + } + } catch {} + } +}; diff --git a/node_modules/locate-path/license b/node_modules/locate-path/license new file mode 100644 index 00000000..fa7ceba3 --- /dev/null +++ b/node_modules/locate-path/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/locate-path/package.json b/node_modules/locate-path/package.json new file mode 100644 index 00000000..08bea50d --- /dev/null +++ b/node_modules/locate-path/package.json @@ -0,0 +1,46 @@ +{ + "name": "locate-path", + "version": "6.0.0", + "description": "Get the first path that exists on disk of multiple paths", + "license": "MIT", + "repository": "sindresorhus/locate-path", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "locate", + "path", + "paths", + "file", + "files", + "exists", + "find", + "finder", + "search", + "searcher", + "array", + "iterable", + "iterator" + ], + "dependencies": { + "p-locate": "^5.0.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.13.1", + "xo": "^0.32.1" + } +} diff --git a/node_modules/locate-path/readme.md b/node_modules/locate-path/readme.md new file mode 100644 index 00000000..1002bcd6 --- /dev/null +++ b/node_modules/locate-path/readme.md @@ -0,0 +1,125 @@ +# locate-path [![Build Status](https://travis-ci.com/sindresorhus/locate-path.svg?branch=master)](https://travis-ci.com/github/sindresorhus/locate-path) + +> Get the first path that exists on disk of multiple paths + +## Install + +``` +$ npm install locate-path +``` + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +const locatePath = require('locate-path'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + console(await locatePath(files)); + //=> 'rainbow' +})(); +``` + +## API + +### locatePath(paths, options?) + +Returns a `Promise` for the first path that exists or `undefined` if none exists. + +#### paths + +Type: `Iterable` + +Paths to check. + +#### options + +Type: `object` + +##### concurrency + +Type: `number`\ +Default: `Infinity`\ +Minimum: `1` + +Number of concurrently pending promises. + +##### preserveOrder + +Type: `boolean`\ +Default: `true` + +Preserve `paths` order when searching. + +Disable this to improve performance if you don't care about the order. + +##### cwd + +Type: `string`\ +Default: `process.cwd()` + +Current working directory. + +##### type + +Type: `string`\ +Default: `'file'`\ +Values: `'file' | 'directory'` + +The type of paths that can match. + +##### allowSymlinks + +Type: `boolean`\ +Default: `true` + +Allow symbolic links to match if they point to the chosen path type. + +### locatePath.sync(paths, options?) + +Returns the first path that exists or `undefined` if none exists. + +#### paths + +Type: `Iterable` + +Paths to check. + +#### options + +Type: `object` + +##### cwd + +Same as above. + +##### type + +Same as above. + +##### allowSymlinks + +Same as above. + +## Related + +- [path-exists](https://github.com/sindresorhus/path-exists) - Check if a path exists + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/lodash.merge/LICENSE b/node_modules/lodash.merge/LICENSE new file mode 100644 index 00000000..77c42f14 --- /dev/null +++ b/node_modules/lodash.merge/LICENSE @@ -0,0 +1,47 @@ +Copyright OpenJS Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/node_modules/lodash.merge/README.md b/node_modules/lodash.merge/README.md new file mode 100644 index 00000000..91b75386 --- /dev/null +++ b/node_modules/lodash.merge/README.md @@ -0,0 +1,18 @@ +# lodash.merge v4.6.2 + +The [Lodash](https://lodash.com/) method `_.merge` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.merge +``` + +In Node.js: +```js +var merge = require('lodash.merge'); +``` + +See the [documentation](https://lodash.com/docs#merge) or [package source](https://github.com/lodash/lodash/blob/4.6.2-npm-packages/lodash.merge) for more details. diff --git a/node_modules/lodash.merge/index.js b/node_modules/lodash.merge/index.js new file mode 100644 index 00000000..8e75d955 --- /dev/null +++ b/node_modules/lodash.merge/index.js @@ -0,0 +1,1977 @@ +/** + * Lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeMax = Math.max, + nativeNow = Date.now; + +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'), + nativeCreate = getNative(Object, 'create'); + +/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ +var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; +}()); + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); +} + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +/** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } +} + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} + +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; +} + +/** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); +} + +/** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); +} + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); +} + +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); +}; + +/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ +function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; +} + +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; +} + +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} + +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; +} + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} + +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; +} + +/** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; +} + +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString = shortOut(baseSetToString); + +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; +} + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +/** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ +function toPlainObject(value) { + return copyObject(value, keysIn(value)); +} + +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} + +/** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ +var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); +}); + +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function() { + return value; + }; +} + +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +module.exports = merge; diff --git a/node_modules/lodash.merge/package.json b/node_modules/lodash.merge/package.json new file mode 100644 index 00000000..3130fc8f --- /dev/null +++ b/node_modules/lodash.merge/package.json @@ -0,0 +1,16 @@ +{ + "name": "lodash.merge", + "version": "4.6.2", + "description": "The Lodash method `_.merge` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, merge", + "author": "John-David Dalton ", + "contributors": [ + "John-David Dalton ", + "Mathias Bynens " + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/node_modules/merge2/LICENSE b/node_modules/merge2/LICENSE new file mode 100644 index 00000000..31dd9c72 --- /dev/null +++ b/node_modules/merge2/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2020 Teambition + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/merge2/README.md b/node_modules/merge2/README.md new file mode 100644 index 00000000..27f8eb99 --- /dev/null +++ b/node_modules/merge2/README.md @@ -0,0 +1,144 @@ +# merge2 + +Merge multiple streams into one stream in sequence or parallel. + +[![NPM version][npm-image]][npm-url] +[![Build Status][travis-image]][travis-url] +[![Downloads][downloads-image]][downloads-url] + +## Install + +Install with [npm](https://npmjs.org/package/merge2) + +```sh +npm install merge2 +``` + +## Usage + +```js +const gulp = require('gulp') +const merge2 = require('merge2') +const concat = require('gulp-concat') +const minifyHtml = require('gulp-minify-html') +const ngtemplate = require('gulp-ngtemplate') + +gulp.task('app-js', function () { + return merge2( + gulp.src('static/src/tpl/*.html') + .pipe(minifyHtml({empty: true})) + .pipe(ngtemplate({ + module: 'genTemplates', + standalone: true + }) + ), gulp.src([ + 'static/src/js/app.js', + 'static/src/js/locale_zh-cn.js', + 'static/src/js/router.js', + 'static/src/js/tools.js', + 'static/src/js/services.js', + 'static/src/js/filters.js', + 'static/src/js/directives.js', + 'static/src/js/controllers.js' + ]) + ) + .pipe(concat('app.js')) + .pipe(gulp.dest('static/dist/js/')) +}) +``` + +```js +const stream = merge2([stream1, stream2], stream3, {end: false}) +//... +stream.add(stream4, stream5) +//.. +stream.end() +``` + +```js +// equal to merge2([stream1, stream2], stream3) +const stream = merge2() +stream.add([stream1, stream2]) +stream.add(stream3) +``` + +```js +// merge order: +// 1. merge `stream1`; +// 2. merge `stream2` and `stream3` in parallel after `stream1` merged; +// 3. merge 'stream4' after `stream2` and `stream3` merged; +const stream = merge2(stream1, [stream2, stream3], stream4) + +// merge order: +// 1. merge `stream5` and `stream6` in parallel after `stream4` merged; +// 2. merge 'stream7' after `stream5` and `stream6` merged; +stream.add([stream5, stream6], stream7) +``` + +```js +// nest merge +// equal to merge2(stream1, stream2, stream6, stream3, [stream4, stream5]); +const streamA = merge2(stream1, stream2) +const streamB = merge2(stream3, [stream4, stream5]) +const stream = merge2(streamA, streamB) +streamA.add(stream6) +``` + +## API + +```js +const merge2 = require('merge2') +``` + +### merge2() + +### merge2(options) + +### merge2(stream1, stream2, ..., streamN) + +### merge2(stream1, stream2, ..., streamN, options) + +### merge2(stream1, [stream2, stream3, ...], streamN, options) + +return a duplex stream (mergedStream). streams in array will be merged in parallel. + +### mergedStream.add(stream) + +### mergedStream.add(stream1, [stream2, stream3, ...], ...) + +return the mergedStream. + +### mergedStream.on('queueDrain', function() {}) + +It will emit 'queueDrain' when all streams merged. If you set `end === false` in options, this event give you a notice that should add more streams to merge or end the mergedStream. + +#### stream + +*option* +Type: `Readable` or `Duplex` or `Transform` stream. + +#### options + +*option* +Type: `Object`. + +* **end** - `Boolean` - if `end === false` then mergedStream will not be auto ended, you should end by yourself. **Default:** `undefined` + +* **pipeError** - `Boolean` - if `pipeError === true` then mergedStream will emit `error` event from source streams. **Default:** `undefined` + +* **objectMode** - `Boolean` . **Default:** `true` + +`objectMode` and other options(`highWaterMark`, `defaultEncoding` ...) is same as Node.js `Stream`. + +## License + +MIT © [Teambition](https://www.teambition.com) + +[npm-url]: https://npmjs.org/package/merge2 +[npm-image]: http://img.shields.io/npm/v/merge2.svg + +[travis-url]: https://travis-ci.org/teambition/merge2 +[travis-image]: http://img.shields.io/travis/teambition/merge2.svg + +[downloads-url]: https://npmjs.org/package/merge2 +[downloads-image]: http://img.shields.io/npm/dm/merge2.svg?style=flat-square diff --git a/node_modules/merge2/index.js b/node_modules/merge2/index.js new file mode 100644 index 00000000..78a61edf --- /dev/null +++ b/node_modules/merge2/index.js @@ -0,0 +1,144 @@ +'use strict' +/* + * merge2 + * https://github.com/teambition/merge2 + * + * Copyright (c) 2014-2020 Teambition + * Licensed under the MIT license. + */ +const Stream = require('stream') +const PassThrough = Stream.PassThrough +const slice = Array.prototype.slice + +module.exports = merge2 + +function merge2 () { + const streamsQueue = [] + const args = slice.call(arguments) + let merging = false + let options = args[args.length - 1] + + if (options && !Array.isArray(options) && options.pipe == null) { + args.pop() + } else { + options = {} + } + + const doEnd = options.end !== false + const doPipeError = options.pipeError === true + if (options.objectMode == null) { + options.objectMode = true + } + if (options.highWaterMark == null) { + options.highWaterMark = 64 * 1024 + } + const mergedStream = PassThrough(options) + + function addStream () { + for (let i = 0, len = arguments.length; i < len; i++) { + streamsQueue.push(pauseStreams(arguments[i], options)) + } + mergeStream() + return this + } + + function mergeStream () { + if (merging) { + return + } + merging = true + + let streams = streamsQueue.shift() + if (!streams) { + process.nextTick(endStream) + return + } + if (!Array.isArray(streams)) { + streams = [streams] + } + + let pipesCount = streams.length + 1 + + function next () { + if (--pipesCount > 0) { + return + } + merging = false + mergeStream() + } + + function pipe (stream) { + function onend () { + stream.removeListener('merge2UnpipeEnd', onend) + stream.removeListener('end', onend) + if (doPipeError) { + stream.removeListener('error', onerror) + } + next() + } + function onerror (err) { + mergedStream.emit('error', err) + } + // skip ended stream + if (stream._readableState.endEmitted) { + return next() + } + + stream.on('merge2UnpipeEnd', onend) + stream.on('end', onend) + + if (doPipeError) { + stream.on('error', onerror) + } + + stream.pipe(mergedStream, { end: false }) + // compatible for old stream + stream.resume() + } + + for (let i = 0; i < streams.length; i++) { + pipe(streams[i]) + } + + next() + } + + function endStream () { + merging = false + // emit 'queueDrain' when all streams merged. + mergedStream.emit('queueDrain') + if (doEnd) { + mergedStream.end() + } + } + + mergedStream.setMaxListeners(0) + mergedStream.add = addStream + mergedStream.on('unpipe', function (stream) { + stream.emit('merge2UnpipeEnd') + }) + + if (args.length) { + addStream.apply(null, args) + } + return mergedStream +} + +// check and pause streams for pipe. +function pauseStreams (streams, options) { + if (!Array.isArray(streams)) { + // Backwards-compat with old-style streams + if (!streams._readableState && streams.pipe) { + streams = streams.pipe(PassThrough(options)) + } + if (!streams._readableState || !streams.pause || !streams.pipe) { + throw new Error('Only readable stream can be merged.') + } + streams.pause() + } else { + for (let i = 0, len = streams.length; i < len; i++) { + streams[i] = pauseStreams(streams[i], options) + } + } + return streams +} diff --git a/node_modules/merge2/package.json b/node_modules/merge2/package.json new file mode 100644 index 00000000..7777307f --- /dev/null +++ b/node_modules/merge2/package.json @@ -0,0 +1,43 @@ +{ + "name": "merge2", + "description": "Merge multiple streams into one stream in sequence or parallel.", + "authors": [ + "Yan Qing " + ], + "license": "MIT", + "version": "1.4.1", + "main": "./index.js", + "repository": { + "type": "git", + "url": "git@github.com:teambition/merge2.git" + }, + "homepage": "https://github.com/teambition/merge2", + "keywords": [ + "merge2", + "multiple", + "sequence", + "parallel", + "merge", + "stream", + "merge stream", + "sync" + ], + "engines": { + "node": ">= 8" + }, + "dependencies": {}, + "devDependencies": { + "standard": "^14.3.4", + "through2": "^3.0.1", + "thunks": "^4.9.6", + "tman": "^1.10.0", + "to-through": "^2.0.0" + }, + "scripts": { + "test": "standard && tman" + }, + "files": [ + "README.md", + "index.js" + ] +} diff --git a/node_modules/micromatch/LICENSE b/node_modules/micromatch/LICENSE new file mode 100755 index 00000000..9af4a67d --- /dev/null +++ b/node_modules/micromatch/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/micromatch/README.md b/node_modules/micromatch/README.md new file mode 100644 index 00000000..d72a059a --- /dev/null +++ b/node_modules/micromatch/README.md @@ -0,0 +1,1024 @@ +# micromatch [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![NPM total downloads](https://img.shields.io/npm/dt/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Tests](https://github.com/micromatch/micromatch/actions/workflows/test.yml/badge.svg)](https://github.com/micromatch/micromatch/actions/workflows/test.yml) + +> Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Table of Contents + +
+Details + + * [Install](#install) +- [Sponsors](#sponsors) + * [Gold Sponsors](#gold-sponsors) + * [Quickstart](#quickstart) + * [Why use micromatch?](#why-use-micromatch) + + [Matching features](#matching-features) + * [Switching to micromatch](#switching-to-micromatch) + + [From minimatch](#from-minimatch) + + [From multimatch](#from-multimatch) + * [API](#api) + * [Options](#options) + * [Options Examples](#options-examples) + + [options.basename](#optionsbasename) + + [options.bash](#optionsbash) + + [options.expandRange](#optionsexpandrange) + + [options.format](#optionsformat) + + [options.ignore](#optionsignore) + + [options.matchBase](#optionsmatchbase) + + [options.noextglob](#optionsnoextglob) + + [options.nonegate](#optionsnonegate) + + [options.noglobstar](#optionsnoglobstar) + + [options.nonull](#optionsnonull) + + [options.nullglob](#optionsnullglob) + + [options.onIgnore](#optionsonignore) + + [options.onMatch](#optionsonmatch) + + [options.onResult](#optionsonresult) + + [options.posixSlashes](#optionsposixslashes) + + [options.unescape](#optionsunescape) + * [Extended globbing](#extended-globbing) + + [Extglobs](#extglobs) + + [Braces](#braces) + + [Regex character classes](#regex-character-classes) + + [Regex groups](#regex-groups) + + [POSIX bracket expressions](#posix-bracket-expressions) + * [Notes](#notes) + + [Bash 4.3 parity](#bash-43-parity) + + [Backslashes](#backslashes) + * [Benchmarks](#benchmarks) + + [Running benchmarks](#running-benchmarks) + + [Latest results](#latest-results) + * [Contributing](#contributing) + * [About](#about) + +
+ +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save micromatch +``` + +
+ +# Sponsors + +[Become a Sponsor](https://github.com/sponsors/jonschlinkert) to add your logo to this README, or any of [my other projects](https://github.com/jonschlinkert?tab=repositories&q=&type=&language=&sort=stargazers) + +
+ +## Quickstart + +```js +const micromatch = require('micromatch'); +// micromatch(list, patterns[, options]); +``` + +The [main export](#micromatch) takes a list of strings and one or more glob patterns: + +```js +console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz'] +console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux'] +``` + +Use [.isMatch()](#ismatch) to for boolean matching: + +```js +console.log(micromatch.isMatch('foo', 'f*')) //=> true +console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true +``` + +[Switching](#switching-to-micromatch) from minimatch and multimatch is easy! + +
+ +## Why use micromatch? + +> micromatch is a [replacement](#switching-to-micromatch) for minimatch and multimatch + +* Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) +* More complete support for the Bash 4.3 specification than minimatch and multimatch. Micromatch passes _all of the spec tests_ from bash, including some that bash still fails. +* **Fast & Performant** - Loads in about 5ms and performs [fast matches](#benchmarks). +* **Glob matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories +* **[Advanced globbing](#extended-globbing)** - Supports [extglobs](#extglobs), [braces](#braces-1), and [POSIX brackets](#posix-bracket-expressions), and support for escaping special characters with `\` or quotes. +* **Accurate** - Covers more scenarios [than minimatch](https://github.com/yarnpkg/yarn/pull/3339) +* **Well tested** - More than 5,000 [test assertions](./test) +* **Windows support** - More reliable windows support than minimatch and multimatch. +* **[Safe](https://github.com/micromatch/braces#braces-is-safe)** - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch. + +### Matching features + +* Support for multiple glob patterns (no need for wrappers like multimatch) +* Wildcards (`**`, `*.js`) +* Negation (`'!a/*.js'`, `'*!(b).js'`) +* [extglobs](#extglobs) (`+(x|y)`, `!(a|b)`) +* [POSIX character classes](#posix-bracket-expressions) (`[[:alpha:][:digit:]]`) +* [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`) +* regex character classes (`foo-[1-5].js`) +* regex logical "or" (`foo/(abc|xyz).js`) + +You can mix and match these features to create whatever patterns you need! + +## Switching to micromatch + +_(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information.)_ + +### From minimatch + +Use [micromatch.isMatch()](#ismatch) instead of `minimatch()`: + +```js +console.log(micromatch.isMatch('foo', 'b*')); //=> false +``` + +Use [micromatch.match()](#match) instead of `minimatch.match()`: + +```js +console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar' +``` + +### From multimatch + +Same signature: + +```js +console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz'] +``` + +## API + +**Params** + +* `list` **{String|Array}**: List of strings to match. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) +* `returns` **{Array}**: Returns an array of matches + +**Example** + +```js +const mm = require('micromatch'); +// mm(list, patterns[, options]); + +console.log(mm(['a.js', 'a.txt'], ['*.js'])); +//=> [ 'a.js' ] +``` + +### [.matcher](index.js#L109) + +Returns a matcher function from the given glob `pattern` and `options`. The returned function takes a string to match as its only argument and returns true if the string is a match. + +**Params** + +* `pattern` **{String}**: Glob pattern +* `options` **{Object}** +* `returns` **{Function}**: Returns a matcher function. + +**Example** + +```js +const mm = require('micromatch'); +// mm.matcher(pattern[, options]); + +const isMatch = mm.matcher('*.!(*a)'); +console.log(isMatch('a.a')); //=> false +console.log(isMatch('a.b')); //=> true +``` + +### [.isMatch](index.js#L128) + +Returns true if **any** of the given glob `patterns` match the specified `string`. + +**Params** + +* `str` **{String}**: The string to test. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `[options]` **{Object}**: See available [options](#options). +* `returns` **{Boolean}**: Returns true if any patterns match `str` + +**Example** + +```js +const mm = require('micromatch'); +// mm.isMatch(string, patterns[, options]); + +console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true +console.log(mm.isMatch('a.a', 'b.*')); //=> false +``` + +### [.not](index.js#L153) + +Returns a list of strings that _**do not match any**_ of the given `patterns`. + +**Params** + +* `list` **{Array}**: Array of strings to match. +* `patterns` **{String|Array}**: One or more glob pattern to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns. + +**Example** + +```js +const mm = require('micromatch'); +// mm.not(list, patterns[, options]); + +console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); +//=> ['b.b', 'c.c'] +``` + +### [.contains](index.js#L193) + +Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. + +**Params** + +* `str` **{String}**: The string to match. +* `patterns` **{String|Array}**: Glob pattern to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Boolean}**: Returns true if any of the patterns matches any part of `str`. + +**Example** + +```js +var mm = require('micromatch'); +// mm.contains(string, pattern[, options]); + +console.log(mm.contains('aa/bb/cc', '*b')); +//=> true +console.log(mm.contains('aa/bb/cc', '*d')); +//=> false +``` + +### [.matchKeys](index.js#L235) + +Filter the keys of the given object with the given `glob` pattern and `options`. Does not attempt to match nested keys. If you need this feature, use [glob-object](https://github.com/jonschlinkert/glob-object) instead. + +**Params** + +* `object` **{Object}**: The object with keys to filter. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Object}**: Returns an object with only keys that match the given patterns. + +**Example** + +```js +const mm = require('micromatch'); +// mm.matchKeys(object, patterns[, options]); + +const obj = { aa: 'a', ab: 'b', ac: 'c' }; +console.log(mm.matchKeys(obj, '*b')); +//=> { ab: 'b' } +``` + +### [.some](index.js#L264) + +Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + +**Params** + +* `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Boolean}**: Returns true if any `patterns` matches any of the strings in `list` + +**Example** + +```js +const mm = require('micromatch'); +// mm.some(list, patterns[, options]); + +console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); +// true +console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); +// false +``` + +### [.every](index.js#L300) + +Returns true if every string in the given `list` matches any of the given glob `patterns`. + +**Params** + +* `list` **{String|Array}**: The string or array of strings to test. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Boolean}**: Returns true if all `patterns` matches all of the strings in `list` + +**Example** + +```js +const mm = require('micromatch'); +// mm.every(list, patterns[, options]); + +console.log(mm.every('foo.js', ['foo.js'])); +// true +console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); +// true +console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); +// false +console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); +// false +``` + +### [.all](index.js#L339) + +Returns true if **all** of the given `patterns` match the specified string. + +**Params** + +* `str` **{String|Array}**: The string to test. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Boolean}**: Returns true if any patterns match `str` + +**Example** + +```js +const mm = require('micromatch'); +// mm.all(string, patterns[, options]); + +console.log(mm.all('foo.js', ['foo.js'])); +// true + +console.log(mm.all('foo.js', ['*.js', '!foo.js'])); +// false + +console.log(mm.all('foo.js', ['*.js', 'foo.js'])); +// true + +console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); +// true +``` + +### [.capture](index.js#L366) + +Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. + +**Params** + +* `glob` **{String}**: Glob pattern to use for matching. +* `input` **{String}**: String to match +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Array|null}**: Returns an array of captures if the input matches the glob pattern, otherwise `null`. + +**Example** + +```js +const mm = require('micromatch'); +// mm.capture(pattern, string[, options]); + +console.log(mm.capture('test/*.js', 'test/foo.js')); +//=> ['foo'] +console.log(mm.capture('test/*.js', 'foo/bar.css')); +//=> null +``` + +### [.makeRe](index.js#L392) + +Create a regular expression from the given glob `pattern`. + +**Params** + +* `pattern` **{String}**: A glob pattern to convert to regex. +* `options` **{Object}** +* `returns` **{RegExp}**: Returns a regex created from the given pattern. + +**Example** + +```js +const mm = require('micromatch'); +// mm.makeRe(pattern[, options]); + +console.log(mm.makeRe('*.js')); +//=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ +``` + +### [.scan](index.js#L408) + +Scan a glob pattern to separate the pattern into segments. Used by the [split](#split) method. + +**Params** + +* `pattern` **{String}** +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with + +**Example** + +```js +const mm = require('micromatch'); +const state = mm.scan(pattern[, options]); +``` + +### [.parse](index.js#L424) + +Parse a glob pattern to create the source string for a regular expression. + +**Params** + +* `glob` **{String}** +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with useful properties and output to be used as regex source string. + +**Example** + +```js +const mm = require('micromatch'); +const state = mm.parse(pattern[, options]); +``` + +### [.braces](index.js#L451) + +Process the given brace `pattern`. + +**Params** + +* `pattern` **{String}**: String with brace pattern to process. +* `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. +* `returns` **{Array}** + +**Example** + +```js +const { braces } = require('micromatch'); +console.log(braces('foo/{a,b,c}/bar')); +//=> [ 'foo/(a|b|c)/bar' ] + +console.log(braces('foo/{a,b,c}/bar', { expand: true })); +//=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] +``` + +## Options + +| **Option** | **Type** | **Default value** | **Description** | +| --- | --- | --- | --- | +| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | +| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | +| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | +| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | +| `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | +| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | +| `dot` | `boolean` | `false` | Match dotfiles. Otherwise dotfiles are ignored unless a `.` is explicitly defined in the pattern. | +| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. This option is overridden by the `expandBrace` option. | +| `failglob` | `boolean` | `false` | Similar to the `failglob` behavior in Bash, throws an error when no matches are found. Based on the bash option of the same name. | +| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | +| `flags` | `boolean` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | +| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | +| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | +| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | +| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | +| `lookbehinds` | `boolean` | `true` | Support regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds. | +| `matchBase` | `boolean` | `false` | Alias for `basename` | +| `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | +| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | +| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | +| `nocase` | `boolean` | `false` | Perform case-insensitive matching. Equivalent to the regex `i` flag. Note that this option is ignored when the `flags` option is defined. | +| `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | +| `noext` | `boolean` | `false` | Alias for `noextglob` | +| `noextglob` | `boolean` | `false` | Disable support for matching with [extglobs](#extglobs) (like `+(a\|b)`) | +| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | +| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | +| `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | +| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | +| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | +| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | +| `posix` | `boolean` | `false` | Support [POSIX character classes](#posix-bracket-expressions) ("posix brackets"). | +| `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | +| `prepend` | `string` | `undefined` | String to prepend to the generated regex used for matching. | +| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | +| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | +| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | +| `unescape` | `boolean` | `undefined` | Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches. | +| `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatitibility. | + +## Options Examples + +### options.basename + +Allow glob patterns without slashes to match a file path based on its basename. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `matchBase`. + +**Type**: `Boolean` + +**Default**: `false` + +**Example** + +```js +micromatch(['a/b.js', 'a/c.md'], '*.js'); +//=> [] + +micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true }); +//=> ['a/b.js'] +``` + +### options.bash + +Enabled by default, this option enforces bash-like behavior with stars immediately following a bracket expression. Bash bracket expressions are similar to regex character classes, but unlike regex, a star following a bracket expression **does not repeat the bracketed characters**. Instead, the star is treated the same as any other star. + +**Type**: `Boolean` + +**Default**: `true` + +**Example** + +```js +const files = ['abc', 'ajz']; +console.log(micromatch(files, '[a-c]*')); +//=> ['abc', 'ajz'] + +console.log(micromatch(files, '[a-c]*', { bash: false })); +``` + +### options.expandRange + +**Type**: `function` + +**Default**: `undefined` + +Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. + +**Example** + +The following example shows how to create a glob that matches a numeric folder name between `01` and `25`, with leading zeros. + +```js +const fill = require('fill-range'); +const regex = micromatch.makeRe('foo/{01..25}/bar', { + expandRange(a, b) { + return `(${fill(a, b, { toRegex: true })})`; + } +}); + +console.log(regex) +//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ + +console.log(regex.test('foo/00/bar')) // false +console.log(regex.test('foo/01/bar')) // true +console.log(regex.test('foo/10/bar')) // true +console.log(regex.test('foo/22/bar')) // true +console.log(regex.test('foo/25/bar')) // true +console.log(regex.test('foo/26/bar')) // false +``` + +### options.format + +**Type**: `function` + +**Default**: `undefined` + +Custom function for formatting strings before they're matched. + +**Example** + +```js +// strip leading './' from strings +const format = str => str.replace(/^\.\//, ''); +const isMatch = picomatch('foo/*.js', { format }); +console.log(isMatch('./foo/bar.js')) //=> true +``` + +### options.ignore + +String or array of glob patterns to match files to ignore. + +**Type**: `String|Array` + +**Default**: `undefined` + +```js +const isMatch = micromatch.matcher('*', { ignore: 'f*' }); +console.log(isMatch('foo')) //=> false +console.log(isMatch('bar')) //=> true +console.log(isMatch('baz')) //=> true +``` + +### options.matchBase + +Alias for [options.basename](#options-basename). + +### options.noextglob + +Disable extglob support, so that [extglobs](#extglobs) are regarded as literal characters. + +**Type**: `Boolean` + +**Default**: `undefined` + +**Examples** + +```js +console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)')); +//=> ['a/b', 'a/!(z)'] + +console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true })); +//=> ['a/!(z)'] (matches only as literal characters) +``` + +### options.nonegate + +Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. + +**Type**: `Boolean` + +**Default**: `undefined` + +### options.noglobstar + +Disable matching with globstars (`**`). + +**Type**: `Boolean` + +**Default**: `undefined` + +```js +micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**'); +//=> ['a/b', 'a/b/c', 'a/b/c/d'] + +micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true}); +//=> ['a/b'] +``` + +### options.nonull + +Alias for [options.nullglob](#options-nullglob). + +### options.nullglob + +If `true`, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nonull`. + +**Type**: `Boolean` + +**Default**: `undefined` + +### options.onIgnore + +```js +const onIgnore = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); + // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' } +}; + +const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +### options.onMatch + +```js +const onMatch = ({ glob, regex, input, output }) => { + console.log({ input, output }); + // { input: 'some\\path', output: 'some/path' } + // { input: 'some\\path', output: 'some/path' } + // { input: 'some\\path', output: 'some/path' } +}; + +const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true }); +isMatch('some\\path'); +isMatch('some\\path'); +isMatch('some\\path'); +``` + +### options.onResult + +```js +const onResult = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = micromatch('*', { onResult, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +### options.posixSlashes + +Convert path separators on returned files to posix/unix-style forward slashes. Aliased as `unixify` for backwards compatibility. + +**Type**: `Boolean` + +**Default**: `true` on windows, `false` everywhere else. + +**Example** + +```js +console.log(micromatch.match(['a\\b\\c'], 'a/**')); +//=> ['a/b/c'] + +console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false })); +//=> ['a\\b\\c'] +``` + +### options.unescape + +Remove backslashes from escaped glob characters before creating the regular expression to perform matches. + +**Type**: `Boolean` + +**Default**: `undefined` + +**Example** + +In this example we want to match a literal `*`: + +```js +console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c')); +//=> ['a\\*c'] + +console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true })); +//=> ['a*c'] +``` + +
+
+ +## Extended globbing + +Micromatch supports the following extended globbing features. + +### Extglobs + +Extended globbing, as described by the bash man page: + +| **pattern** | **regex equivalent** | **description** | +| --- | --- | --- | +| `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns | +| `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns | +| `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns | +| `@(pattern)` | `(pattern)` * | Matches one of the given patterns | +| `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns | + +* Note that `@` isn't a regex character. + +### Braces + +Brace patterns can be used to match specific ranges or sets of characters. + +**Example** + +The pattern `{f,b}*/{1..3}/{b,q}*` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +baz/1/qux +baz/2/qux +baz/3/qux +``` + +Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues. + +### Regex character classes + +Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: + +* `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']` +* `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']` +* `a/[A-Z].js`: matches and uppercase letter, returning `['a/E.md']` + +Learn about [regex character classes](http://www.regular-expressions.info/charclass.html). + +### Regex groups + +Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: + +* `(a|c).js`: would match either `a` or `c`, returning `['a.js', 'c.js']` +* `(b|d).js`: would match either `b` or `d`, returning `['b.js', 'd.js']` +* `(b|[A-Z]).js`: would match either `b` or an uppercase letter, returning `['b.js', 'E.js']` + +As with regex, parens can be nested, so patterns like `((a|b)|c)/b` will work. Although brace expansion might be friendlier to use, depending on preference. + +### POSIX bracket expressions + +POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder. + +**Example** + +```js +console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true +console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false +``` + +*** + +## Notes + +### Bash 4.3 parity + +Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch. + +However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback. + +### Backslashes + +There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns. + +* Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows, which is consistent with bash behavior. _More importantly, unescaping globs can result in unsafe regular expressions_. +* Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns. + +We made this decision for micromatch for a couple of reasons: + +* Consistency with bash conventions. +* Glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine. + +**A note about joining paths to globs** + +Note that when you pass something like `path.join('foo', '*')` to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the `path.sep` is `\\`. + +In other words, since `\\` is reserved as an escape character in globs, on windows `path.join('foo', '*')` would result in `foo\\*`, which tells micromatch to match `*` as a literal character. This is the same behavior as bash. + +To solve this, you might be inspired to do something like `'foo\\*'.replace(/\\/g, '/')`, but this causes another, potentially much more serious, problem. + +## Benchmarks + +### Running benchmarks + +Install dependencies for running benchmarks: + +```sh +$ cd bench && npm install +``` + +Run the benchmarks: + +```sh +$ npm run bench +``` + +### Latest results + +As of August 23, 2024 (longer bars are better): + +```sh +# .makeRe star + micromatch x 2,232,802 ops/sec ±2.34% (89 runs sampled)) + minimatch x 781,018 ops/sec ±6.74% (92 runs sampled)) + +# .makeRe star; dot=true + micromatch x 1,863,453 ops/sec ±0.74% (93 runs sampled) + minimatch x 723,105 ops/sec ±0.75% (93 runs sampled) + +# .makeRe globstar + micromatch x 1,624,179 ops/sec ±2.22% (91 runs sampled) + minimatch x 1,117,230 ops/sec ±2.78% (86 runs sampled)) + +# .makeRe globstars + micromatch x 1,658,642 ops/sec ±0.86% (92 runs sampled) + minimatch x 741,224 ops/sec ±1.24% (89 runs sampled)) + +# .makeRe with leading star + micromatch x 1,525,014 ops/sec ±1.63% (90 runs sampled) + minimatch x 561,074 ops/sec ±3.07% (89 runs sampled) + +# .makeRe - braces + micromatch x 172,478 ops/sec ±2.37% (78 runs sampled) + minimatch x 96,087 ops/sec ±2.34% (88 runs sampled))) + +# .makeRe braces - range (expanded) + micromatch x 26,973 ops/sec ±0.84% (89 runs sampled) + minimatch x 3,023 ops/sec ±0.99% (90 runs sampled)) + +# .makeRe braces - range (compiled) + micromatch x 152,892 ops/sec ±1.67% (83 runs sampled) + minimatch x 992 ops/sec ±3.50% (89 runs sampled)d)) + +# .makeRe braces - nested ranges (expanded) + micromatch x 15,816 ops/sec ±13.05% (80 runs sampled) + minimatch x 2,953 ops/sec ±1.64% (91 runs sampled) + +# .makeRe braces - nested ranges (compiled) + micromatch x 110,881 ops/sec ±1.85% (82 runs sampled) + minimatch x 1,008 ops/sec ±1.51% (91 runs sampled) + +# .makeRe braces - set (compiled) + micromatch x 134,930 ops/sec ±3.54% (63 runs sampled)) + minimatch x 43,242 ops/sec ±0.60% (93 runs sampled) + +# .makeRe braces - nested sets (compiled) + micromatch x 94,455 ops/sec ±1.74% (69 runs sampled)) + minimatch x 27,720 ops/sec ±1.84% (93 runs sampled)) +``` + +## Contributing + +All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started. + +**Bug reports** + +Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please: + +* [research existing issues first](../../issues) (open and closed) +* visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern +* visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js +* if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated. + +**Platform issues** + +It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated). + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.") +* [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/micromatch/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") +* [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") +* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") +* [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 523 | [jonschlinkert](https://github.com/jonschlinkert) | +| 12 | [es128](https://github.com/es128) | +| 9 | [danez](https://github.com/danez) | +| 8 | [doowb](https://github.com/doowb) | +| 6 | [paulmillr](https://github.com/paulmillr) | +| 5 | [mrmlnc](https://github.com/mrmlnc) | +| 3 | [DrPizza](https://github.com/DrPizza) | +| 2 | [Tvrqvoise](https://github.com/Tvrqvoise) | +| 2 | [antonyk](https://github.com/antonyk) | +| 2 | [MartinKolarik](https://github.com/MartinKolarik) | +| 2 | [Glazy](https://github.com/Glazy) | +| 2 | [mceIdo](https://github.com/mceIdo) | +| 2 | [TrySound](https://github.com/TrySound) | +| 1 | [yvele](https://github.com/yvele) | +| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | +| 1 | [simlu](https://github.com/simlu) | +| 1 | [curbengh](https://github.com/curbengh) | +| 1 | [fidian](https://github.com/fidian) | +| 1 | [tomByrer](https://github.com/tomByrer) | +| 1 | [ZoomerTedJackson](https://github.com/ZoomerTedJackson) | +| 1 | [styfle](https://github.com/styfle) | +| 1 | [sebdeckers](https://github.com/sebdeckers) | +| 1 | [muescha](https://github.com/muescha) | +| 1 | [juszczykjakub](https://github.com/juszczykjakub) | +| 1 | [joyceerhl](https://github.com/joyceerhl) | +| 1 | [donatj](https://github.com/donatj) | +| 1 | [frangio](https://github.com/frangio) | +| 1 | [UltCombo](https://github.com/UltCombo) | +| 1 | [DianeLooney](https://github.com/DianeLooney) | +| 1 | [devongovett](https://github.com/devongovett) | +| 1 | [Cslove](https://github.com/Cslove) | +| 1 | [amilajack](https://github.com/amilajack) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2024, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on August 23, 2024._ \ No newline at end of file diff --git a/node_modules/micromatch/index.js b/node_modules/micromatch/index.js new file mode 100644 index 00000000..cb9d9ef3 --- /dev/null +++ b/node_modules/micromatch/index.js @@ -0,0 +1,474 @@ +'use strict'; + +const util = require('util'); +const braces = require('braces'); +const picomatch = require('picomatch'); +const utils = require('picomatch/lib/utils'); + +const isEmptyString = v => v === '' || v === './'; +const hasBraces = v => { + const index = v.indexOf('{'); + return index > -1 && v.indexOf('}', index) > -1; +}; + +/** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} `list` List of strings to match. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + +const micromatch = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); + + let omit = new Set(); + let keep = new Set(); + let items = new Set(); + let negatives = 0; + + let onResult = state => { + items.add(state.output); + if (options && options.onResult) { + options.onResult(state); + } + }; + + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; + + for (let item of list) { + let matched = isMatch(item, true); + + let match = negated ? !matched.isMatch : matched.isMatch; + if (!match) continue; + + if (negated) { + omit.add(matched.output); + } else { + omit.delete(matched.output); + keep.add(matched.output); + } + } + } + + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter(item => !omit.has(item)); + + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(', ')}"`); + } + + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + } + } + + return matches; +}; + +/** + * Backwards compatibility + */ + +micromatch.match = micromatch; + +/** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ + +micromatch.matcher = (pattern, options) => picomatch(pattern, options); + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `[options]` See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + +/** + * Backwards compatibility + */ + +micromatch.any = micromatch.isMatch; + +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +micromatch.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set(); + let items = []; + + let onResult = state => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; + + let matches = new Set(micromatch(list, patterns, { ...options, onResult })); + + for (let item of items) { + if (!matches.has(item)) { + result.add(item); + } + } + return [...result]; +}; + +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any of the patterns matches any part of `str`. + * @api public + */ + +micromatch.contains = (str, pattern, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } + + if (Array.isArray(pattern)) { + return pattern.some(p => micromatch.contains(str, p, options)); + } + + if (typeof pattern === 'string') { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + + if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { + return true; + } + } + + return micromatch.isMatch(str, pattern, { ...options, contains: true }); +}; + +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + +micromatch.matchKeys = (obj, patterns, options) => { + if (!utils.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + let keys = micromatch(Object.keys(obj), patterns, options); + let res = {}; + for (let key of keys) res[key] = obj[key]; + return res; +}; + +/** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` + * @api public + */ + +micromatch.some = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (items.some(item => isMatch(item))) { + return true; + } + } + return false; +}; + +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` + * @api public + */ + +micromatch.every = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (!items.every(item => isMatch(item))) { + return false; + } + } + return true; +}; + +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } + + return [].concat(patterns).every(p => picomatch(p, options)(str)); +}; + +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ + +micromatch.capture = (glob, input, options) => { + let posix = utils.isWindows(options); + let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); + let match = regex.exec(posix ? utils.toPosixSlashes(input) : input); + + if (match) { + return match.slice(1).map(v => v === void 0 ? '' : v); + } +}; + +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +micromatch.makeRe = (...args) => picomatch.makeRe(...args); + +/** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +micromatch.scan = (...args) => picomatch.scan(...args); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.parse(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ + +micromatch.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) { + for (let str of braces(String(pattern), options)) { + res.push(picomatch.parse(str, options)); + } + } + return res; +}; + +/** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + +micromatch.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + if ((options && options.nobrace === true) || !hasBraces(pattern)) { + return [pattern]; + } + return braces(pattern, options); +}; + +/** + * Expand braces + */ + +micromatch.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch.braces(pattern, { ...options, expand: true }); +}; + +/** + * Expose micromatch + */ + +// exposed for tests +micromatch.hasBraces = hasBraces; +module.exports = micromatch; diff --git a/node_modules/micromatch/package.json b/node_modules/micromatch/package.json new file mode 100644 index 00000000..d5558bb9 --- /dev/null +++ b/node_modules/micromatch/package.json @@ -0,0 +1,119 @@ +{ + "name": "micromatch", + "description": "Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch.", + "version": "4.0.8", + "homepage": "https://github.com/micromatch/micromatch", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "(https://github.com/DianeLooney)", + "Amila Welihinda (amilajack.com)", + "Bogdan Chadkin (https://github.com/TrySound)", + "Brian Woodward (https://twitter.com/doowb)", + "Devon Govett (http://badassjs.com)", + "Elan Shanker (https://github.com/es128)", + "Fabrício Matté (https://ultcombo.js.org)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Martin Kolárik (https://kolarik.sk)", + "Olsten Larck (https://i.am.charlike.online)", + "Paul Miller (paulmillr.com)", + "Tom Byrer (https://github.com/tomByrer)", + "Tyler Akins (http://rumkin.com)", + "Peter Bright (https://github.com/drpizza)", + "Kuba Juszczyk (https://github.com/ku8ar)" + ], + "repository": "micromatch/micromatch", + "bugs": { + "url": "https://github.com/micromatch/micromatch/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=8.6" + }, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "devDependencies": { + "fill-range": "^7.0.1", + "gulp-format-md": "^2.0.0", + "minimatch": "^5.0.1", + "mocha": "^9.2.2", + "time-require": "github:jonschlinkert/time-require" + }, + "keywords": [ + "bash", + "bracket", + "character-class", + "expand", + "expansion", + "expression", + "extglob", + "extglobs", + "file", + "files", + "filter", + "find", + "glob", + "globbing", + "globs", + "globstar", + "lookahead", + "lookaround", + "lookbehind", + "match", + "matcher", + "matches", + "matching", + "micromatch", + "minimatch", + "multimatch", + "negate", + "negation", + "path", + "pattern", + "patterns", + "posix", + "regex", + "regexp", + "regular", + "shell", + "star", + "wildcard" + ], + "verb": { + "toc": "collapsible", + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "braces", + "expand-brackets", + "extglob", + "fill-range", + "nanomatch" + ] + }, + "reflinks": [ + "extglob", + "fill-range", + "glob-object", + "minimatch", + "multimatch" + ] + } +} diff --git a/node_modules/minimatch/LICENSE b/node_modules/minimatch/LICENSE new file mode 100644 index 00000000..1493534e --- /dev/null +++ b/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2011-2023 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/minimatch/README.md b/node_modules/minimatch/README.md new file mode 100644 index 00000000..3c97a02f --- /dev/null +++ b/node_modules/minimatch/README.md @@ -0,0 +1,454 @@ +# minimatch + +A minimal matching utility. + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```js +// hybrid module, load with require() or import +import { minimatch } from 'minimatch' +// or: +const { minimatch } = require('minimatch') + +minimatch('bar.foo', '*.foo') // true! +minimatch('bar.foo', '*.bar') // false! +minimatch('bar.foo', '*.+(bar|foo)', { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +- Brace Expansion +- Extended glob matching +- "Globstar" `**` matching +- [Posix character + classes](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html), + like `[[:alpha:]]`, supporting the full range of Unicode + characters. For example, `[[:alpha:]]` will match against + `'é'`, though `[a-zA-Z]` will not. Collating symbol and set + matching is not supported, so `[[=e=]]` will _not_ match `'é'` + and `[[.ch.]]` will not match `'ch'` in locales where `ch` is + considered a single character. + +See: + +- `man sh` +- `man bash` [Pattern + Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) +- `man 3 fnmatch` +- `man 5 gitignore` + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes in patterns +will always be interpreted as escape characters, not path separators. + +Note that `\` or `/` _will_ be interpreted as path separators in paths on +Windows, and will match against `/` in glob expressions. + +So just always use `/` in patterns. + +### UNC Paths + +On Windows, UNC paths like `//?/c:/...` or +`//ComputerName/Share/...` are handled specially. + +- Patterns starting with a double-slash followed by some + non-slash characters will preserve their double-slash. As a + result, a pattern like `//*` will match `//x`, but not `/x`. +- Patterns staring with `//?/:` will _not_ treat + the `?` as a wildcard character. Instead, it will be treated + as a normal string. +- Patterns starting with `//?/:/...` will match + file paths starting with `:/...`, and vice versa, + as if the `//?/` was not present. This behavior only is + present when the drive letters are a case-insensitive match to + one another. The remaining portions of the path/pattern are + compared case sensitively, unless `nocase:true` is set. + +Note that specifying a UNC path using `\` characters as path +separators is always allowed in the file path argument, but only +allowed in the pattern argument when `windowsPathsNoEscape: true` +is set in the options. + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require('minimatch').Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +- `pattern` The original pattern the minimatch object represents. +- `options` The options supplied to the constructor. +- `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +- `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +- `negate` True if the pattern is negated. +- `comment` True if the pattern is a comment. +- `empty` True if the pattern is `""`. + +### Methods + +- `makeRe()` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +- `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +- `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. +- `hasMagic()` Returns true if the parsed pattern contains any + magic characters. Returns false if all comparator parts are + string literals. If the `magicalBraces` option is set on the + constructor, then it will consider brace expansions which are + not otherwise magical to be magic. If not set, then a pattern + like `a{b,c}d` will return `false`, because neither `abd` nor + `acd` contain any special glob characters. + + This does **not** mean that the pattern string can be used as a + literal filename, as it may contain magic glob characters that + are escaped. For example, the pattern `\\*` or `[*]` would not + be considered to have magic, as the matching portion parses to + the literal string `'*'` and would match a path named `'*'`, + not `'\\*'` or `'[*]'`. The `minimatch.unescape()` method may + be used to remove escape characters. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, '*.js', { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter('*.js', { matchBase: true })) +``` + +### minimatch.escape(pattern, options = {}) + +Escape all magic characters in a glob pattern, so that it will +only ever match literal strings + +If the `windowsPathsNoEscape` option is used, then characters are +escaped by wrapping in `[]`, because a magic character wrapped in +a character class can only be satisfied by that exact character. + +Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot +be escaped or unescaped. + +### minimatch.unescape(pattern, options = {}) + +Un-escape a glob string that may contain some escaped characters. + +If the `windowsPathsNoEscape` option is used, then square-brace +escapes are removed, but not backslash escapes. For example, it +will turn the string `'[*]'` into `*`, but it will not turn +`'\\*'` into `'*'`, because `\` is a path separator in +`windowsPathsNoEscape` mode. + +When `windowsPathsNoEscape` is not set, then both brace escapes +and backslash escapes are removed. + +Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot +be escaped or unescaped. + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, '*.js', { matchBase: true }) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nocaseMagicOnly + +When used with `{nocase: true}`, create regular expressions that +are case-insensitive, but leave string match portions untouched. +Has no effect when used without `{nocase: true}` + +Useful when some other form of case-insensitive matching is used, +or if the original string representation is useful in some other +way. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### magicalBraces + +This only affects the results of the `Minimatch.hasMagic` method. + +If the pattern contains brace expansions, such as `a{b,c}d`, but +no other magic characters, then the `Minimatch.hasMagic()` method +will return `false` by default. When this option set, it will +return `true` for brace expansion as well as other magic glob +characters. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` + +### windowsPathsNoEscape + +Use `\\` as a path separator _only_, and _never_ as an escape +character. If set, all `\\` characters are replaced with `/` in +the pattern. Note that this makes it **impossible** to match +against paths containing literal glob pattern characters, but +allows matching with patterns constructed using `path.join()` and +`path.resolve()` on Windows platforms, mimicking the (buggy!) +behavior of earlier versions on Windows. Please use with +caution, and be mindful of [the caveat about Windows +paths](#windows). + +For legacy reasons, this is also set if +`options.allowWindowsEscape` is set to the exact value `false`. + +### windowsNoMagicRoot + +When a pattern starts with a UNC path or drive letter, and in +`nocase:true` mode, do not convert the root portions of the +pattern into a case-insensitive regular expression, and instead +leave them as strings. + +This is the default when the platform is `win32` and +`nocase:true` is set. + +### preserveMultipleSlashes + +By default, multiple `/` characters (other than the leading `//` +in a UNC path, see "UNC Paths" above) are treated as a single +`/`. + +That is, a pattern like `a///b` will match the file path `a/b`. + +Set `preserveMultipleSlashes: true` to suppress this behavior. + +### optimizationLevel + +A number indicating the level of optimization that should be done +to the pattern prior to parsing and using it for matches. + +Globstar parts `**` are always converted to `*` when `noglobstar` +is set, and multiple adjacent `**` parts are converted into a +single `**` (ie, `a/**/**/b` will be treated as `a/**/b`, as this +is equivalent in all cases). + +- `0` - Make no further changes. In this mode, `.` and `..` are + maintained in the pattern, meaning that they must also appear + in the same position in the test path string. Eg, a pattern + like `a/*/../c` will match the string `a/b/../c` but not the + string `a/c`. +- `1` - (default) Remove cases where a double-dot `..` follows a + pattern portion that is not `**`, `.`, `..`, or empty `''`. For + example, the pattern `./a/b/../*` is converted to `./a/*`, and + so it will match the path string `./a/c`, but not the path + string `./a/b/../c`. Dots and empty path portions in the + pattern are preserved. +- `2` (or higher) - Much more aggressive optimizations, suitable + for use with file-walking cases: + + - Remove cases where a double-dot `..` follows a pattern + portion that is not `**`, `.`, or empty `''`. Remove empty + and `.` portions of the pattern, where safe to do so (ie, + anywhere other than the last position, the first position, or + the second position in a pattern starting with `/`, as this + may indicate a UNC path on Windows). + - Convert patterns containing `
/**/../

/` into the + equivalent `

/{..,**}/

/`, where `

` is a + a pattern portion other than `.`, `..`, `**`, or empty + `''`. + - Dedupe patterns where a `**` portion is present in one and + omitted in another, and it is not the final path portion, and + they are otherwise equivalent. So `{a/**/b,a/b}` becomes + `a/**/b`, because `**` matches against an empty path portion. + - Dedupe patterns where a `*` portion is present in one, and a + non-dot pattern other than `**`, `.`, `..`, or `''` is in the + same position in the other. So `a/{*,x}/b` becomes `a/*/b`, + because `*` can match against `x`. + + While these optimizations improve the performance of + file-walking use cases such as [glob](http://npm.im/glob) (ie, + the reason this module exists), there are cases where it will + fail to match a literal string that would have been matched in + optimization level 1 or 0. + + Specifically, while the `Minimatch.match()` method will + optimize the file path string in the same ways, resulting in + the same matches, it will fail when tested with the regular + expression provided by `Minimatch.makeRe()`, unless the path + string is first processed with + `minimatch.levelTwoFileOptimize()` or similar. + +### platform + +When set to `win32`, this will trigger all windows-specific +behaviors (special handling for UNC paths, and treating `\` as +separators in file paths for comparison.) + +Defaults to the value of `process.platform`. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a +worthwhile goal, some discrepancies exist between minimatch and +other implementations. Some are intentional, and some are +unavoidable. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +Negated extglob patterns are handled as closely as possible to +Bash semantics, but there are some cases with negative extglobs +which are exceedingly difficult to express in a JavaScript +regular expression. In particular the negated pattern +`!(*|)*` will in bash match anything that does +not start with ``. However, +`!(*)*` _will_ match paths starting with +``, because the empty string can match against +the negated portion. In this library, `!(*|)*` +will _not_ match any pattern starting with ``, due to a +difference in precisely which patterns are considered "greedy" in +Regular Expressions vs bash path expansion. This may be fixable, +but not without incurring some complexity and performance costs, +and the trade-off seems to not be worth pursuing. + +Note that `fnmatch(3)` in libc is an extremely naive string comparison +matcher, which does not do anything special for slashes. This library is +designed to be used in glob searching and file walkers, and so it does do +special things with `/`. Thus, `foo*` will not match `foo/bar` in this +library, even though it would in `fnmatch(3)`. diff --git a/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts new file mode 100644 index 00000000..8e318b23 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts @@ -0,0 +1,2 @@ +export declare const assertValidPattern: (pattern: any) => void; +//# sourceMappingURL=assert-valid-pattern.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts.map b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts.map new file mode 100644 index 00000000..c61c0310 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"assert-valid-pattern.d.ts","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAUlD,CAAA"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js new file mode 100644 index 00000000..5fc86bbd --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assertValidPattern = void 0; +const MAX_PATTERN_LENGTH = 1024 * 64; +const assertValidPattern = (pattern) => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern'); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long'); + } +}; +exports.assertValidPattern = assertValidPattern; +//# sourceMappingURL=assert-valid-pattern.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js.map b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js.map new file mode 100644 index 00000000..d43215c6 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"assert-valid-pattern.js","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":";;;AAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAA;AAC7B,MAAM,kBAAkB,GAA2B,CACxD,OAAY,EACe,EAAE;IAC7B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;KACvC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,kBAAkB,EAAE;QACvC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAA;KAC3C;AACH,CAAC,CAAA;AAVY,QAAA,kBAAkB,sBAU9B","sourcesContent":["const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n pattern: any\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/ast.d.ts b/node_modules/minimatch/dist/commonjs/ast.d.ts new file mode 100644 index 00000000..b8c1e544 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/ast.d.ts @@ -0,0 +1,20 @@ +import { MinimatchOptions, MMRegExp } from './index.js'; +export type ExtglobType = '!' | '?' | '+' | '*' | '@'; +export declare class AST { + #private; + type: ExtglobType | null; + constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions); + get hasMagic(): boolean | undefined; + toString(): string; + push(...parts: (string | AST)[]): void; + toJSON(): any[]; + isStart(): boolean; + isEnd(): boolean; + copyIn(part: AST | string): void; + clone(parent: AST): AST; + static fromGlob(pattern: string, options?: MinimatchOptions): AST; + toMMPattern(): MMRegExp | string; + get options(): MinimatchOptions; + toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean]; +} +//# sourceMappingURL=ast.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/ast.d.ts.map b/node_modules/minimatch/dist/commonjs/ast.d.ts.map new file mode 100644 index 00000000..9e7bfb9a --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/ast.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwCvD,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAkCrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;gBAiBtB,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IA+ClB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAY/B,MAAM;IAgBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsIjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CAiMjE"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/ast.js b/node_modules/minimatch/dist/commonjs/ast.js new file mode 100644 index 00000000..7b210962 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/ast.js @@ -0,0 +1,592 @@ +"use strict"; +// parse a single path portion +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AST = void 0; +const brace_expressions_js_1 = require("./brace-expressions.js"); +const unescape_js_1 = require("./unescape.js"); +const types = new Set(['!', '?', '+', '*', '@']); +const isExtglobType = (c) => types.has(c); +// Patterns that get prepended to bind to the start of either the +// entire string, or just a single path portion, to prevent dots +// and/or traversal patterns, when needed. +// Exts don't need the ^ or / bit, because the root binds that already. +const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))'; +const startNoDot = '(?!\\.)'; +// characters that indicate a start of pattern needs the "no dots" bit, +// because a dot *might* be matched. ( is not in the list, because in +// the case of a child extglob, it will handle the prevention itself. +const addPatternStart = new Set(['[', '.']); +// cases where traversal is A-OK, no dot prevention needed +const justDots = new Set(['..', '.']); +const reSpecials = new Set('().*{}+?[]^$\\!'); +const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +// any single thing other than / +const qmark = '[^/]'; +// * => any number of characters +const star = qmark + '*?'; +// use + when we need to ensure that *something* matches, because the * is +// the only thing in the path portion. +const starNoEmpty = qmark + '+?'; +// remove the \ chars that we added if we end up doing a nonmagic compare +// const deslash = (s: string) => s.replace(/\\(.)/g, '$1') +class AST { + type; + #root; + #hasMagic; + #uflag = false; + #parts = []; + #parent; + #parentIndex; + #negs; + #filledNegs = false; + #options; + #toString; + // set to true if it's an extglob with no children + // (which really means one child of '') + #emptyExt = false; + constructor(type, parent, options = {}) { + this.type = type; + // extglobs are inherently magical + if (type) + this.#hasMagic = true; + this.#parent = parent; + this.#root = this.#parent ? this.#parent.#root : this; + this.#options = this.#root === this ? options : this.#root.#options; + this.#negs = this.#root === this ? [] : this.#root.#negs; + if (type === '!' && !this.#root.#filledNegs) + this.#negs.push(this); + this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0; + } + get hasMagic() { + /* c8 ignore start */ + if (this.#hasMagic !== undefined) + return this.#hasMagic; + /* c8 ignore stop */ + for (const p of this.#parts) { + if (typeof p === 'string') + continue; + if (p.type || p.hasMagic) + return (this.#hasMagic = true); + } + // note: will be undefined until we generate the regexp src and find out + return this.#hasMagic; + } + // reconstructs the pattern + toString() { + if (this.#toString !== undefined) + return this.#toString; + if (!this.type) { + return (this.#toString = this.#parts.map(p => String(p)).join('')); + } + else { + return (this.#toString = + this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')'); + } + } + #fillNegs() { + /* c8 ignore start */ + if (this !== this.#root) + throw new Error('should only call on root'); + if (this.#filledNegs) + return this; + /* c8 ignore stop */ + // call toString() once to fill this out + this.toString(); + this.#filledNegs = true; + let n; + while ((n = this.#negs.pop())) { + if (n.type !== '!') + continue; + // walk up the tree, appending everthing that comes AFTER parentIndex + let p = n; + let pp = p.#parent; + while (pp) { + for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) { + for (const part of n.#parts) { + /* c8 ignore start */ + if (typeof part === 'string') { + throw new Error('string part in extglob AST??'); + } + /* c8 ignore stop */ + part.copyIn(pp.#parts[i]); + } + } + p = pp; + pp = p.#parent; + } + } + return this; + } + push(...parts) { + for (const p of parts) { + if (p === '') + continue; + /* c8 ignore start */ + if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) { + throw new Error('invalid part: ' + p); + } + /* c8 ignore stop */ + this.#parts.push(p); + } + } + toJSON() { + const ret = this.type === null + ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON())) + : [this.type, ...this.#parts.map(p => p.toJSON())]; + if (this.isStart() && !this.type) + ret.unshift([]); + if (this.isEnd() && + (this === this.#root || + (this.#root.#filledNegs && this.#parent?.type === '!'))) { + ret.push({}); + } + return ret; + } + isStart() { + if (this.#root === this) + return true; + // if (this.type) return !!this.#parent?.isStart() + if (!this.#parent?.isStart()) + return false; + if (this.#parentIndex === 0) + return true; + // if everything AHEAD of this is a negation, then it's still the "start" + const p = this.#parent; + for (let i = 0; i < this.#parentIndex; i++) { + const pp = p.#parts[i]; + if (!(pp instanceof AST && pp.type === '!')) { + return false; + } + } + return true; + } + isEnd() { + if (this.#root === this) + return true; + if (this.#parent?.type === '!') + return true; + if (!this.#parent?.isEnd()) + return false; + if (!this.type) + return this.#parent?.isEnd(); + // if not root, it'll always have a parent + /* c8 ignore start */ + const pl = this.#parent ? this.#parent.#parts.length : 0; + /* c8 ignore stop */ + return this.#parentIndex === pl - 1; + } + copyIn(part) { + if (typeof part === 'string') + this.push(part); + else + this.push(part.clone(this)); + } + clone(parent) { + const c = new AST(this.type, parent); + for (const p of this.#parts) { + c.copyIn(p); + } + return c; + } + static #parseAST(str, ast, pos, opt) { + let escaping = false; + let inBrace = false; + let braceStart = -1; + let braceNeg = false; + if (ast.type === null) { + // outside of a extglob, append until we find a start + let i = pos; + let acc = ''; + while (i < str.length) { + const c = str.charAt(i++); + // still accumulate escapes at this point, but we do ignore + // starts that are escaped + if (escaping || c === '\\') { + escaping = !escaping; + acc += c; + continue; + } + if (inBrace) { + if (i === braceStart + 1) { + if (c === '^' || c === '!') { + braceNeg = true; + } + } + else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc += c; + continue; + } + else if (c === '[') { + inBrace = true; + braceStart = i; + braceNeg = false; + acc += c; + continue; + } + if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') { + ast.push(acc); + acc = ''; + const ext = new AST(c, ast); + i = AST.#parseAST(str, ext, i, opt); + ast.push(ext); + continue; + } + acc += c; + } + ast.push(acc); + return i; + } + // some kind of extglob, pos is at the ( + // find the next | or ) + let i = pos + 1; + let part = new AST(null, ast); + const parts = []; + let acc = ''; + while (i < str.length) { + const c = str.charAt(i++); + // still accumulate escapes at this point, but we do ignore + // starts that are escaped + if (escaping || c === '\\') { + escaping = !escaping; + acc += c; + continue; + } + if (inBrace) { + if (i === braceStart + 1) { + if (c === '^' || c === '!') { + braceNeg = true; + } + } + else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc += c; + continue; + } + else if (c === '[') { + inBrace = true; + braceStart = i; + braceNeg = false; + acc += c; + continue; + } + if (isExtglobType(c) && str.charAt(i) === '(') { + part.push(acc); + acc = ''; + const ext = new AST(c, part); + part.push(ext); + i = AST.#parseAST(str, ext, i, opt); + continue; + } + if (c === '|') { + part.push(acc); + acc = ''; + parts.push(part); + part = new AST(null, ast); + continue; + } + if (c === ')') { + if (acc === '' && ast.#parts.length === 0) { + ast.#emptyExt = true; + } + part.push(acc); + acc = ''; + ast.push(...parts, part); + return i; + } + acc += c; + } + // unfinished extglob + // if we got here, it was a malformed extglob! not an extglob, but + // maybe something else in there. + ast.type = null; + ast.#hasMagic = undefined; + ast.#parts = [str.substring(pos - 1)]; + return i; + } + static fromGlob(pattern, options = {}) { + const ast = new AST(null, undefined, options); + AST.#parseAST(pattern, ast, 0, options); + return ast; + } + // returns the regular expression if there's magic, or the unescaped + // string if not. + toMMPattern() { + // should only be called on root + /* c8 ignore start */ + if (this !== this.#root) + return this.#root.toMMPattern(); + /* c8 ignore stop */ + const glob = this.toString(); + const [re, body, hasMagic, uflag] = this.toRegExpSource(); + // if we're in nocase mode, and not nocaseMagicOnly, then we do + // still need a regular expression if we have to case-insensitively + // match capital/lowercase characters. + const anyMagic = hasMagic || + this.#hasMagic || + (this.#options.nocase && + !this.#options.nocaseMagicOnly && + glob.toUpperCase() !== glob.toLowerCase()); + if (!anyMagic) { + return body; + } + const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : ''); + return Object.assign(new RegExp(`^${re}$`, flags), { + _src: re, + _glob: glob, + }); + } + get options() { + return this.#options; + } + // returns the string match, the regexp source, whether there's magic + // in the regexp (so a regular expression is required) and whether or + // not the uflag is needed for the regular expression (for posix classes) + // TODO: instead of injecting the start/end at this point, just return + // the BODY of the regexp, along with the start/end portions suitable + // for binding the start/end in either a joined full-path makeRe context + // (where we bind to (^|/), or a standalone matchPart context (where + // we bind to ^, and not /). Otherwise slashes get duped! + // + // In part-matching mode, the start is: + // - if not isStart: nothing + // - if traversal possible, but not allowed: ^(?!\.\.?$) + // - if dots allowed or not possible: ^ + // - if dots possible and not allowed: ^(?!\.) + // end is: + // - if not isEnd(): nothing + // - else: $ + // + // In full-path matching mode, we put the slash at the START of the + // pattern, so start is: + // - if first pattern: same as part-matching mode + // - if not isStart(): nothing + // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) + // - if dots allowed or not possible: / + // - if dots possible and not allowed: /(?!\.) + // end is: + // - if last pattern, same as part-matching mode + // - else nothing + // + // Always put the (?:$|/) on negated tails, though, because that has to be + // there to bind the end of the negated pattern portion, and it's easier to + // just stick it in now rather than try to inject it later in the middle of + // the pattern. + // + // We can just always return the same end, and leave it up to the caller + // to know whether it's going to be used joined or in parts. + // And, if the start is adjusted slightly, can do the same there: + // - if not isStart: nothing + // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) + // - if dots allowed or not possible: (?:/|^) + // - if dots possible and not allowed: (?:/|^)(?!\.) + // + // But it's better to have a simpler binding without a conditional, for + // performance, so probably better to return both start options. + // + // Then the caller just ignores the end if it's not the first pattern, + // and the start always gets applied. + // + // But that's always going to be $ if it's the ending pattern, or nothing, + // so the caller can just attach $ at the end of the pattern when building. + // + // So the todo is: + // - better detect what kind of start is needed + // - return both flavors of starting pattern + // - attach $ at the end of the pattern when creating the actual RegExp + // + // Ah, but wait, no, that all only applies to the root when the first pattern + // is not an extglob. If the first pattern IS an extglob, then we need all + // that dot prevention biz to live in the extglob portions, because eg + // +(*|.x*) can match .xy but not .yx. + // + // So, return the two flavors if it's #root and the first child is not an + // AST, otherwise leave it to the child AST to handle it, and there, + // use the (?:^|/) style of start binding. + // + // Even simplified further: + // - Since the start for a join is eg /(?!\.) and the start for a part + // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root + // or start or whatever) and prepend ^ or / at the Regexp construction. + toRegExpSource(allowDot) { + const dot = allowDot ?? !!this.#options.dot; + if (this.#root === this) + this.#fillNegs(); + if (!this.type) { + const noEmpty = this.isStart() && this.isEnd(); + const src = this.#parts + .map(p => { + const [re, _, hasMagic, uflag] = typeof p === 'string' + ? AST.#parseGlob(p, this.#hasMagic, noEmpty) + : p.toRegExpSource(allowDot); + this.#hasMagic = this.#hasMagic || hasMagic; + this.#uflag = this.#uflag || uflag; + return re; + }) + .join(''); + let start = ''; + if (this.isStart()) { + if (typeof this.#parts[0] === 'string') { + // this is the string that will match the start of the pattern, + // so we need to protect against dots and such. + // '.' and '..' cannot match unless the pattern is that exactly, + // even if it starts with . or dot:true is set. + const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]); + if (!dotTravAllowed) { + const aps = addPatternStart; + // check if we have a possibility of matching . or .., + // and prevent that. + const needNoTrav = + // dots are allowed, and the pattern starts with [ or . + (dot && aps.has(src.charAt(0))) || + // the pattern starts with \., and then [ or . + (src.startsWith('\\.') && aps.has(src.charAt(2))) || + // the pattern starts with \.\., and then [ or . + (src.startsWith('\\.\\.') && aps.has(src.charAt(4))); + // no need to prevent dots if it can't match a dot, or if a + // sub-pattern will be preventing it anyway. + const needNoDot = !dot && !allowDot && aps.has(src.charAt(0)); + start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''; + } + } + } + // append the "end of path portion" pattern to negation tails + let end = ''; + if (this.isEnd() && + this.#root.#filledNegs && + this.#parent?.type === '!') { + end = '(?:$|\\/)'; + } + const final = start + src + end; + return [ + final, + (0, unescape_js_1.unescape)(src), + (this.#hasMagic = !!this.#hasMagic), + this.#uflag, + ]; + } + // We need to calculate the body *twice* if it's a repeat pattern + // at the start, once in nodot mode, then again in dot mode, so a + // pattern like *(?) can match 'x.y' + const repeated = this.type === '*' || this.type === '+'; + // some kind of extglob + const start = this.type === '!' ? '(?:(?!(?:' : '(?:'; + let body = this.#partsToRegExp(dot); + if (this.isStart() && this.isEnd() && !body && this.type !== '!') { + // invalid extglob, has to at least be *something* present, if it's + // the entire path portion. + const s = this.toString(); + this.#parts = [s]; + this.type = null; + this.#hasMagic = undefined; + return [s, (0, unescape_js_1.unescape)(this.toString()), false, false]; + } + // XXX abstract out this map method + let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot + ? '' + : this.#partsToRegExp(true); + if (bodyDotAllowed === body) { + bodyDotAllowed = ''; + } + if (bodyDotAllowed) { + body = `(?:${body})(?:${bodyDotAllowed})*?`; + } + // an empty !() is exactly equivalent to a starNoEmpty + let final = ''; + if (this.type === '!' && this.#emptyExt) { + final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty; + } + else { + const close = this.type === '!' + ? // !() must match something,but !(x) can match '' + '))' + + (this.isStart() && !dot && !allowDot ? startNoDot : '') + + star + + ')' + : this.type === '@' + ? ')' + : this.type === '?' + ? ')?' + : this.type === '+' && bodyDotAllowed + ? ')' + : this.type === '*' && bodyDotAllowed + ? `)?` + : `)${this.type}`; + final = start + body + close; + } + return [ + final, + (0, unescape_js_1.unescape)(body), + (this.#hasMagic = !!this.#hasMagic), + this.#uflag, + ]; + } + #partsToRegExp(dot) { + return this.#parts + .map(p => { + // extglob ASTs should only contain parent ASTs + /* c8 ignore start */ + if (typeof p === 'string') { + throw new Error('string type in extglob ast??'); + } + /* c8 ignore stop */ + // can ignore hasMagic, because extglobs are already always magic + const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot); + this.#uflag = this.#uflag || uflag; + return re; + }) + .filter(p => !(this.isStart() && this.isEnd()) || !!p) + .join('|'); + } + static #parseGlob(glob, hasMagic, noEmpty = false) { + let escaping = false; + let re = ''; + let uflag = false; + for (let i = 0; i < glob.length; i++) { + const c = glob.charAt(i); + if (escaping) { + escaping = false; + re += (reSpecials.has(c) ? '\\' : '') + c; + continue; + } + if (c === '\\') { + if (i === glob.length - 1) { + re += '\\\\'; + } + else { + escaping = true; + } + continue; + } + if (c === '[') { + const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i); + if (consumed) { + re += src; + uflag = uflag || needUflag; + i += consumed - 1; + hasMagic = hasMagic || magic; + continue; + } + } + if (c === '*') { + if (noEmpty && glob === '*') + re += starNoEmpty; + else + re += star; + hasMagic = true; + continue; + } + if (c === '?') { + re += qmark; + hasMagic = true; + continue; + } + re += regExpEscape(c); + } + return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag]; + } +} +exports.AST = AST; +//# sourceMappingURL=ast.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/ast.js.map b/node_modules/minimatch/dist/commonjs/ast.js.map new file mode 100644 index 00000000..8383e433 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/ast.js.map @@ -0,0 +1 @@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E,CAAC,GAAG,CAAC,CAAA;gBACzC,SAAQ;aACT;YACD,IAAI,CAAC,KAAK,IAAI,EAAE;gBACd,IAAI,CAAC,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;oBACzB,EAAE,IAAI,MAAM,CAAA;iBACb;qBAAM;oBACL,QAAQ,GAAG,IAAI,CAAA;iBAChB;gBACD,SAAQ;aACT;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE,QAAQ,EAAE,KAAK,CAAC,GAAG,IAAA,iCAAU,EAAC,IAAI,EAAE,CAAC,CAAC,CAAA;gBAC7D,IAAI,QAAQ,EAAE;oBACZ,EAAE,IAAI,GAAG,CAAA;oBACT,KAAK,GAAG,KAAK,IAAI,SAAS,CAAA;oBAC1B,CAAC,IAAI,QAAQ,GAAG,CAAC,CAAA;oBACjB,QAAQ,GAAG,QAAQ,IAAI,KAAK,CAAA;oBAC5B,SAAQ;iBACT;aACF;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,IAAI,OAAO,IAAI,IAAI,KAAK,GAAG;oBAAE,EAAE,IAAI,WAAW,CAAA;;oBACzC,EAAE,IAAI,IAAI,CAAA;gBACf,QAAQ,GAAG,IAAI,CAAA;gBACf,SAAQ;aACT;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,EAAE,IAAI,KAAK,CAAA;gBACX,QAAQ,GAAG,IAAI,CAAA;gBACf,SAAQ;aACT;YACD,EAAE,IAAI,YAAY,CAAC,CAAC,CAAC,CAAA;SACtB;QACD,OAAO,CAAC,EAAE,EAAE,IAAA,sBAAQ,EAAC,IAAI,CAAC,EAAE,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;IAChD,CAAC;CACF;AA/kBD,kBA+kBC","sourcesContent":["// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n// 1 2 3 4 5 6 1 2 3 46 5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n// v----- .* because there's more following,\n// v v otherwise, .+ because it must be\n// v v *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n// copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string): c is ExtglobType =>\n types.has(c as ExtglobType)\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n type: ExtglobType | null\n readonly #root: AST\n\n #hasMagic?: boolean\n #uflag: boolean = false\n #parts: (string | AST)[] = []\n readonly #parent?: AST\n readonly #parentIndex: number\n #negs: AST[]\n #filledNegs: boolean = false\n #options: MinimatchOptions\n #toString?: string\n // set to true if it's an extglob with no children\n // (which really means one child of '')\n #emptyExt: boolean = false\n\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n this.type = type\n // extglobs are inherently magical\n if (type) this.#hasMagic = true\n this.#parent = parent\n this.#root = this.#parent ? this.#parent.#root : this\n this.#options = this.#root === this ? options : this.#root.#options\n this.#negs = this.#root === this ? [] : this.#root.#negs\n if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n }\n\n get hasMagic(): boolean | undefined {\n /* c8 ignore start */\n if (this.#hasMagic !== undefined) return this.#hasMagic\n /* c8 ignore stop */\n for (const p of this.#parts) {\n if (typeof p === 'string') continue\n if (p.type || p.hasMagic) return (this.#hasMagic = true)\n }\n // note: will be undefined until we generate the regexp src and find out\n return this.#hasMagic\n }\n\n // reconstructs the pattern\n toString(): string {\n if (this.#toString !== undefined) return this.#toString\n if (!this.type) {\n return (this.#toString = this.#parts.map(p => String(p)).join(''))\n } else {\n return (this.#toString =\n this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n }\n }\n\n #fillNegs() {\n /* c8 ignore start */\n if (this !== this.#root) throw new Error('should only call on root')\n if (this.#filledNegs) return this\n /* c8 ignore stop */\n\n // call toString() once to fill this out\n this.toString()\n this.#filledNegs = true\n let n: AST | undefined\n while ((n = this.#negs.pop())) {\n if (n.type !== '!') continue\n // walk up the tree, appending everthing that comes AFTER parentIndex\n let p: AST | undefined = n\n let pp = p.#parent\n while (pp) {\n for (\n let i = p.#parentIndex + 1;\n !pp.type && i < pp.#parts.length;\n i++\n ) {\n for (const part of n.#parts) {\n /* c8 ignore start */\n if (typeof part === 'string') {\n throw new Error('string part in extglob AST??')\n }\n /* c8 ignore stop */\n part.copyIn(pp.#parts[i])\n }\n }\n p = pp\n pp = p.#parent\n }\n }\n return this\n }\n\n push(...parts: (string | AST)[]) {\n for (const p of parts) {\n if (p === '') continue\n /* c8 ignore start */\n if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {\n throw new Error('invalid part: ' + p)\n }\n /* c8 ignore stop */\n this.#parts.push(p)\n }\n }\n\n toJSON() {\n const ret: any[] =\n this.type === null\n ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))\n : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n if (this.isStart() && !this.type) ret.unshift([])\n if (\n this.isEnd() &&\n (this === this.#root ||\n (this.#root.#filledNegs && this.#parent?.type === '!'))\n ) {\n ret.push({})\n }\n return ret\n }\n\n isStart(): boolean {\n if (this.#root === this) return true\n // if (this.type) return !!this.#parent?.isStart()\n if (!this.#parent?.isStart()) return false\n if (this.#parentIndex === 0) return true\n // if everything AHEAD of this is a negation, then it's still the \"start\"\n const p = this.#parent\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i]\n if (!(pp instanceof AST && pp.type === '!')) {\n return false\n }\n }\n return true\n }\n\n isEnd(): boolean {\n if (this.#root === this) return true\n if (this.#parent?.type === '!') return true\n if (!this.#parent?.isEnd()) return false\n if (!this.type) return this.#parent?.isEnd()\n // if not root, it'll always have a parent\n /* c8 ignore start */\n const pl = this.#parent ? this.#parent.#parts.length : 0\n /* c8 ignore stop */\n return this.#parentIndex === pl - 1\n }\n\n copyIn(part: AST | string) {\n if (typeof part === 'string') this.push(part)\n else this.push(part.clone(this))\n }\n\n clone(parent: AST) {\n const c = new AST(this.type, parent)\n for (const p of this.#parts) {\n c.copyIn(p)\n }\n return c\n }\n\n static #parseAST(\n str: string,\n ast: AST,\n pos: number,\n opt: MinimatchOptions\n ): number {\n let escaping = false\n let inBrace = false\n let braceStart = -1\n let braceNeg = false\n if (ast.type === null) {\n // outside of a extglob, append until we find a start\n let i = pos\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n ast.push(acc)\n acc = ''\n const ext = new AST(c, ast)\n i = AST.#parseAST(str, ext, i, opt)\n ast.push(ext)\n continue\n }\n acc += c\n }\n ast.push(acc)\n return i\n }\n\n // some kind of extglob, pos is at the (\n // find the next | or )\n let i = pos + 1\n let part = new AST(null, ast)\n const parts: AST[] = []\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (isExtglobType(c) && str.charAt(i) === '(') {\n part.push(acc)\n acc = ''\n const ext = new AST(c, part)\n part.push(ext)\n i = AST.#parseAST(str, ext, i, opt)\n continue\n }\n if (c === '|') {\n part.push(acc)\n acc = ''\n parts.push(part)\n part = new AST(null, ast)\n continue\n }\n if (c === ')') {\n if (acc === '' && ast.#parts.length === 0) {\n ast.#emptyExt = true\n }\n part.push(acc)\n acc = ''\n ast.push(...parts, part)\n return i\n }\n acc += c\n }\n\n // unfinished extglob\n // if we got here, it was a malformed extglob! not an extglob, but\n // maybe something else in there.\n ast.type = null\n ast.#hasMagic = undefined\n ast.#parts = [str.substring(pos - 1)]\n return i\n }\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n const ast = new AST(null, undefined, options)\n AST.#parseAST(pattern, ast, 0, options)\n return ast\n }\n\n // returns the regular expression if there's magic, or the unescaped\n // string if not.\n toMMPattern(): MMRegExp | string {\n // should only be called on root\n /* c8 ignore start */\n if (this !== this.#root) return this.#root.toMMPattern()\n /* c8 ignore stop */\n const glob = this.toString()\n const [re, body, hasMagic, uflag] = this.toRegExpSource()\n // if we're in nocase mode, and not nocaseMagicOnly, then we do\n // still need a regular expression if we have to case-insensitively\n // match capital/lowercase characters.\n const anyMagic =\n hasMagic ||\n this.#hasMagic ||\n (this.#options.nocase &&\n !this.#options.nocaseMagicOnly &&\n glob.toUpperCase() !== glob.toLowerCase())\n if (!anyMagic) {\n return body\n }\n\n const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob,\n })\n }\n\n get options() {\n return this.#options\n }\n\n // returns the string match, the regexp source, whether there's magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it's easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it's going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it's better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it's not the first pattern,\n // and the start always gets applied.\n //\n // But that's always going to be $ if it's the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it's #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(\n allowDot?: boolean\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n const dot = allowDot ?? !!this.#options.dot\n if (this.#root === this) this.#fillNegs()\n if (!this.type) {\n const noEmpty = this.isStart() && this.isEnd()\n const src = this.#parts\n .map(p => {\n const [re, _, hasMagic, uflag] =\n typeof p === 'string'\n ? AST.#parseGlob(p, this.#hasMagic, noEmpty)\n : p.toRegExpSource(allowDot)\n this.#hasMagic = this.#hasMagic || hasMagic\n this.#uflag = this.#uflag || uflag\n return re\n })\n .join('')\n\n let start = ''\n if (this.isStart()) {\n if (typeof this.#parts[0] === 'string') {\n // this is the string that will match the start of the pattern,\n // so we need to protect against dots and such.\n\n // '.' and '..' cannot match unless the pattern is that exactly,\n // even if it starts with . or dot:true is set.\n const dotTravAllowed =\n this.#parts.length === 1 && justDots.has(this.#parts[0])\n if (!dotTravAllowed) {\n const aps = addPatternStart\n // check if we have a possibility of matching . or ..,\n // and prevent that.\n const needNoTrav =\n // dots are allowed, and the pattern starts with [ or .\n (dot && aps.has(src.charAt(0))) ||\n // the pattern starts with \\., and then [ or .\n (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n // the pattern starts with \\.\\., and then [ or .\n (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n // no need to prevent dots if it can't match a dot, or if a\n // sub-pattern will be preventing it anyway.\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''\n }\n }\n }\n\n // append the \"end of path portion\" pattern to negation tails\n let end = ''\n if (\n this.isEnd() &&\n this.#root.#filledNegs &&\n this.#parent?.type === '!'\n ) {\n end = '(?:$|\\\\/)'\n }\n const final = start + src + end\n return [\n final,\n unescape(src),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n // We need to calculate the body *twice* if it's a repeat pattern\n // at the start, once in nodot mode, then again in dot mode, so a\n // pattern like *(?) can match 'x.y'\n\n const repeated = this.type === '*' || this.type === '+'\n // some kind of extglob\n const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n let body = this.#partsToRegExp(dot)\n\n if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n // invalid extglob, has to at least be *something* present, if it's\n // the entire path portion.\n const s = this.toString()\n this.#parts = [s]\n this.type = null\n this.#hasMagic = undefined\n return [s, unescape(this.toString()), false, false]\n }\n\n // XXX abstract out this map method\n let bodyDotAllowed =\n !repeated || allowDot || dot || !startNoDot\n ? ''\n : this.#partsToRegExp(true)\n if (bodyDotAllowed === body) {\n bodyDotAllowed = ''\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`\n }\n\n // an empty !() is exactly equivalent to a starNoEmpty\n let final = ''\n if (this.type === '!' && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n } else {\n const close =\n this.type === '!'\n ? // !() must match something,but !(x) can match ''\n '))' +\n (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n star +\n ')'\n : this.type === '@'\n ? ')'\n : this.type === '?'\n ? ')?'\n : this.type === '+' && bodyDotAllowed\n ? ')'\n : this.type === '*' && bodyDotAllowed\n ? `)?`\n : `)${this.type}`\n final = start + body + close\n }\n return [\n final,\n unescape(body),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n #partsToRegExp(dot: boolean) {\n return this.#parts\n .map(p => {\n // extglob ASTs should only contain parent ASTs\n /* c8 ignore start */\n if (typeof p === 'string') {\n throw new Error('string type in extglob ast??')\n }\n /* c8 ignore stop */\n // can ignore hasMagic, because extglobs are already always magic\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n this.#uflag = this.#uflag || uflag\n return re\n })\n .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n .join('|')\n }\n\n static #parseGlob(\n glob: string,\n hasMagic: boolean | undefined,\n noEmpty: boolean = false\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n let escaping = false\n let re = ''\n let uflag = false\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i)\n if (escaping) {\n escaping = false\n re += (reSpecials.has(c) ? '\\\\' : '') + c\n continue\n }\n if (c === '\\\\') {\n if (i === glob.length - 1) {\n re += '\\\\\\\\'\n } else {\n escaping = true\n }\n continue\n }\n if (c === '[') {\n const [src, needUflag, consumed, magic] = parseClass(glob, i)\n if (consumed) {\n re += src\n uflag = uflag || needUflag\n i += consumed - 1\n hasMagic = hasMagic || magic\n continue\n }\n }\n if (c === '*') {\n if (noEmpty && glob === '*') re += starNoEmpty\n else re += star\n hasMagic = true\n continue\n }\n if (c === '?') {\n re += qmark\n hasMagic = true\n continue\n }\n re += regExpEscape(c)\n }\n return [re, unescape(glob), !!hasMagic, uflag]\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts b/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts new file mode 100644 index 00000000..b1572deb --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts @@ -0,0 +1,8 @@ +export type ParseClassResult = [ + src: string, + uFlag: boolean, + consumed: number, + hasMagic: boolean +]; +export declare const parseClass: (glob: string, position: number) => ParseClassResult; +//# sourceMappingURL=brace-expressions.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts.map b/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts.map new file mode 100644 index 00000000..d3949648 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AA+BA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,SACf,MAAM,YACF,MAAM,qBA8HjB,CAAA"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/brace-expressions.js b/node_modules/minimatch/dist/commonjs/brace-expressions.js new file mode 100644 index 00000000..0e13eefc --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/brace-expressions.js @@ -0,0 +1,152 @@ +"use strict"; +// translate the various posix character classes into unicode properties +// this works across all unicode locales +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseClass = void 0; +// { : [, /u flag required, negated] +const posixClasses = { + '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true], + '[:alpha:]': ['\\p{L}\\p{Nl}', true], + '[:ascii:]': ['\\x' + '00-\\x' + '7f', false], + '[:blank:]': ['\\p{Zs}\\t', true], + '[:cntrl:]': ['\\p{Cc}', true], + '[:digit:]': ['\\p{Nd}', true], + '[:graph:]': ['\\p{Z}\\p{C}', true, true], + '[:lower:]': ['\\p{Ll}', true], + '[:print:]': ['\\p{C}', true], + '[:punct:]': ['\\p{P}', true], + '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true], + '[:upper:]': ['\\p{Lu}', true], + '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true], + '[:xdigit:]': ['A-Fa-f0-9', false], +}; +// only need to escape a few things inside of brace expressions +// escapes: [ \ ] - +const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&'); +// escape all regexp magic characters +const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +// everything has already been escaped, we just have to join +const rangesToString = (ranges) => ranges.join(''); +// takes a glob string at a posix brace expression, and returns +// an equivalent regular expression source, and boolean indicating +// whether the /u flag needs to be applied, and the number of chars +// consumed to parse the character class. +// This also removes out of order ranges, and returns ($.) if the +// entire class just no good. +const parseClass = (glob, position) => { + const pos = position; + /* c8 ignore start */ + if (glob.charAt(pos) !== '[') { + throw new Error('not in a brace expression'); + } + /* c8 ignore stop */ + const ranges = []; + const negs = []; + let i = pos + 1; + let sawStart = false; + let uflag = false; + let escaping = false; + let negate = false; + let endPos = pos; + let rangeStart = ''; + WHILE: while (i < glob.length) { + const c = glob.charAt(i); + if ((c === '!' || c === '^') && i === pos + 1) { + negate = true; + i++; + continue; + } + if (c === ']' && sawStart && !escaping) { + endPos = i + 1; + break; + } + sawStart = true; + if (c === '\\') { + if (!escaping) { + escaping = true; + i++; + continue; + } + // escaped \ char, fall through and treat like normal char + } + if (c === '[' && !escaping) { + // either a posix class, a collation equivalent, or just a [ + for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { + if (glob.startsWith(cls, i)) { + // invalid, [a-[] is fine, but not [a-[:alpha]] + if (rangeStart) { + return ['$.', false, glob.length - pos, true]; + } + i += cls.length; + if (neg) + negs.push(unip); + else + ranges.push(unip); + uflag = uflag || u; + continue WHILE; + } + } + } + // now it's just a normal character, effectively + escaping = false; + if (rangeStart) { + // throw this range away if it's not valid, but others + // can still match. + if (c > rangeStart) { + ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c)); + } + else if (c === rangeStart) { + ranges.push(braceEscape(c)); + } + rangeStart = ''; + i++; + continue; + } + // now might be the start of a range. + // can be either c-d or c-] or c] or c] at this point + if (glob.startsWith('-]', i + 1)) { + ranges.push(braceEscape(c + '-')); + i += 2; + continue; + } + if (glob.startsWith('-', i + 1)) { + rangeStart = c; + i += 2; + continue; + } + // not the start of a range, just a single character + ranges.push(braceEscape(c)); + i++; + } + if (endPos < i) { + // didn't see the end of the class, not a valid class, + // but might still be valid as a literal match. + return ['', false, 0, false]; + } + // if we got no ranges and no negates, then we have a range that + // cannot possibly match anything, and that poisons the whole glob + if (!ranges.length && !negs.length) { + return ['$.', false, glob.length - pos, true]; + } + // if we got one positive range, and it's a single character, then that's + // not actually a magic pattern, it's just that one literal character. + // we should not treat that as "magic", we should just return the literal + // character. [_] is a perfectly valid way to escape glob magic chars. + if (negs.length === 0 && + ranges.length === 1 && + /^\\?.$/.test(ranges[0]) && + !negate) { + const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; + return [regexpEscape(r), false, endPos - pos, false]; + } + const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; + const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; + const comb = ranges.length && negs.length + ? '(' + sranges + '|' + snegs + ')' + : ranges.length + ? sranges + : snegs; + return [comb, uflag, endPos - pos, true]; +}; +exports.parseClass = parseClass; +//# sourceMappingURL=brace-expressions.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/brace-expressions.js.map b/node_modules/minimatch/dist/commonjs/brace-expressions.js.map new file mode 100644 index 00000000..86b04756 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/brace-expressions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"brace-expressions.js","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":";AAAA,wEAAwE;AACxE,wCAAwC;;;AAExC,8DAA8D;AAC9D,MAAM,YAAY,GAA0D;IAC1E,WAAW,EAAE,CAAC,sBAAsB,EAAE,IAAI,CAAC;IAC3C,WAAW,EAAE,CAAC,eAAe,EAAE,IAAI,CAAC;IACpC,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,EAAE,KAAK,CAAC;IAC7C,WAAW,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC;IACjC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,cAAc,EAAE,IAAI,EAAE,IAAI,CAAC;IACzC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAA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AAC,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,CAAA;AAC1C,CAAC,CAAA;AAhIY,QAAA,UAAU,cAgItB","sourcesContent":["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n '[:cntrl:]': ['\\\\p{Cc}', true],\n '[:digit:]': ['\\\\p{Nd}', true],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n '[:lower:]': ['\\\\p{Ll}', true],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}', true],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n '[:upper:]': ['\\\\p{Lu}', true],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n '[:xdigit:]': ['A-Fa-f0-9', false],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n src: string,\n uFlag: boolean,\n consumed: number,\n hasMagic: boolean\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n glob: string,\n position: number\n): ParseClassResult => {\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let uflag = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return ['$.', false, glob.length - pos, true]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n uflag = uflag || u\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c))\n }\n rangeStart = ''\n i++\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c] or c] at this point\n if (glob.startsWith('-]', i + 1)) {\n ranges.push(braceEscape(c + '-'))\n i += 2\n continue\n }\n if (glob.startsWith('-', i + 1)) {\n rangeStart = c\n i += 2\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(c))\n i++\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return ['', false, 0, false]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return ['$.', false, glob.length - pos, true]\n }\n\n // if we got one positive range, and it's a single character, then that's\n // not actually a magic pattern, it's just that one literal character.\n // we should not treat that as \"magic\", we should just return the literal\n // character. [_] is a perfectly valid way to escape glob magic chars.\n if (\n negs.length === 0 &&\n ranges.length === 1 &&\n /^\\\\?.$/.test(ranges[0]) &&\n !negate\n ) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n return [regexpEscape(r), false, endPos - pos, false]\n }\n\n const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n const comb =\n ranges.length && negs.length\n ? '(' + sranges + '|' + snegs + ')'\n : ranges.length\n ? sranges\n : snegs\n\n return [comb, uflag, endPos - pos, true]\n}\n"]} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/escape.d.ts b/node_modules/minimatch/dist/commonjs/escape.d.ts new file mode 100644 index 00000000..dc3e3163 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/escape.d.ts @@ -0,0 +1,12 @@ +import { MinimatchOptions } from './index.js'; +/** + * Escape all magic characters in a glob pattern. + * + * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} + * option is used, then characters are escaped by wrapping in `[]`, because + * a magic character wrapped in a character class can only be satisfied by + * that exact character. In this mode, `\` is _not_ escaped, because it is + * not interpreted as a magic character, but instead as a path separator. + */ +export declare const escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; +//# sourceMappingURL=escape.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/escape.d.ts.map b/node_modules/minimatch/dist/commonjs/escape.d.ts.map new file mode 100644 index 00000000..0779dae7 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/escape.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;GAQG;AACH,eAAO,MAAM,MAAM,MACd,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAQlD,CAAA"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/escape.js b/node_modules/minimatch/dist/commonjs/escape.js new file mode 100644 index 00000000..02a4f8a8 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/escape.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.escape = void 0; +/** + * Escape all magic characters in a glob pattern. + * + * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} + * option is used, then characters are escaped by wrapping in `[]`, because + * a magic character wrapped in a character class can only be satisfied by + * that exact character. In this mode, `\` is _not_ escaped, because it is + * not interpreted as a magic character, but instead as a path separator. + */ +const escape = (s, { windowsPathsNoEscape = false, } = {}) => { + // don't need to escape +@! because we escape the parens + // that make those magic, and escaping ! as [!] isn't valid, + // because [!]] is a valid glob class meaning not ']'. + return windowsPathsNoEscape + ? s.replace(/[?*()[\]]/g, '[$&]') + : s.replace(/[?*()[\]\\]/g, '\\$&'); +}; +exports.escape = escape; +//# sourceMappingURL=escape.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/escape.js.map b/node_modules/minimatch/dist/commonjs/escape.js.map new file mode 100644 index 00000000..264b2ea5 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/escape.js.map @@ -0,0 +1 @@ +{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":";;;AACA;;;;;;;;GAQG;AACI,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA;AAZY,QAAA,MAAM,UAYlB","sourcesContent":["import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick = {}\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n return windowsPathsNoEscape\n ? s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n"]} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/index.d.ts b/node_modules/minimatch/dist/commonjs/index.d.ts new file mode 100644 index 00000000..41d16a98 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/index.d.ts @@ -0,0 +1,94 @@ +import { AST } from './ast.js'; +type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; +export interface MinimatchOptions { + nobrace?: boolean; + nocomment?: boolean; + nonegate?: boolean; + debug?: boolean; + noglobstar?: boolean; + noext?: boolean; + nonull?: boolean; + windowsPathsNoEscape?: boolean; + allowWindowsEscape?: boolean; + partial?: boolean; + dot?: boolean; + nocase?: boolean; + nocaseMagicOnly?: boolean; + magicalBraces?: boolean; + matchBase?: boolean; + flipNegate?: boolean; + preserveMultipleSlashes?: boolean; + optimizationLevel?: number; + platform?: Platform; + windowsNoMagicRoot?: boolean; +} +export declare const minimatch: { + (p: string, pattern: string, options?: MinimatchOptions): boolean; + sep: Sep; + GLOBSTAR: typeof GLOBSTAR; + filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; + defaults: (def: MinimatchOptions) => typeof minimatch; + braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; + makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; + match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; + AST: typeof AST; + Minimatch: typeof Minimatch; + escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; + unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; +}; +type Sep = '\\' | '/'; +export declare const sep: Sep; +export declare const GLOBSTAR: unique symbol; +export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; +export declare const defaults: (def: MinimatchOptions) => typeof minimatch; +export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; +export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; +export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; +export type MMRegExp = RegExp & { + _src?: string; + _glob?: string; +}; +export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR; +export type ParseReturn = ParseReturnFiltered | false; +export declare class Minimatch { + options: MinimatchOptions; + set: ParseReturnFiltered[][]; + pattern: string; + windowsPathsNoEscape: boolean; + nonegate: boolean; + negate: boolean; + comment: boolean; + empty: boolean; + preserveMultipleSlashes: boolean; + partial: boolean; + globSet: string[]; + globParts: string[][]; + nocase: boolean; + isWindows: boolean; + platform: Platform; + windowsNoMagicRoot: boolean; + regexp: false | null | MMRegExp; + constructor(pattern: string, options?: MinimatchOptions); + hasMagic(): boolean; + debug(..._: any[]): void; + make(): void; + preprocess(globParts: string[][]): string[][]; + adjascentGlobstarOptimize(globParts: string[][]): string[][]; + levelOneOptimize(globParts: string[][]): string[][]; + levelTwoFileOptimize(parts: string | string[]): string[]; + firstPhasePreProcess(globParts: string[][]): string[][]; + secondPhasePreProcess(globParts: string[][]): string[][]; + partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[]; + parseNegate(): void; + matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean; + braceExpand(): string[]; + parse(pattern: string): ParseReturn; + makeRe(): false | MMRegExp; + slashSplit(p: string): string[]; + match(f: string, partial?: boolean): boolean; + static defaults(def: MinimatchOptions): typeof Minimatch; +} +export { AST } from './ast.js'; +export { escape } from './escape.js'; +export { unescape } from './unescape.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/index.d.ts.map b/node_modules/minimatch/dist/commonjs/index.d.ts.map new file mode 100644 index 00000000..195491d8 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAe,MAAM,UAAU,CAAA;AAI3C,KAAK,QAAQ,GACT,KAAK,GACL,SAAS,GACT,QAAQ,GACR,SAAS,GACT,OAAO,GACP,OAAO,GACP,SAAS,GACT,OAAO,GACP,OAAO,GACP,QAAQ,GACR,QAAQ,CAAA;AAEZ,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,a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IA+CnB,WAAW;IAqBX,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,OAAO,GAAE,OAAe;IAiNzE,WAAW;IAIX,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW;IAiDnC,MAAM;IAsFN,UAAU,CAAC,CAAC,EAAE,MAAM;IAepB,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,UAAe;IAiEvC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,gBAAgB;CAGtC;AAED,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/index.js b/node_modules/minimatch/dist/commonjs/index.js new file mode 100644 index 00000000..64a0f1f8 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/index.js @@ -0,0 +1,1017 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; +const brace_expansion_1 = __importDefault(require("brace-expansion")); +const assert_valid_pattern_js_1 = require("./assert-valid-pattern.js"); +const ast_js_1 = require("./ast.js"); +const escape_js_1 = require("./escape.js"); +const unescape_js_1 = require("./unescape.js"); +const minimatch = (p, pattern, options = {}) => { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false; + } + return new Minimatch(pattern, options).match(p); +}; +exports.minimatch = minimatch; +// Optimized checking for the most common glob patterns. +const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; +const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); +const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); +const starDotExtTestNocase = (ext) => { + ext = ext.toLowerCase(); + return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); +}; +const starDotExtTestNocaseDot = (ext) => { + ext = ext.toLowerCase(); + return (f) => f.toLowerCase().endsWith(ext); +}; +const starDotStarRE = /^\*+\.\*+$/; +const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); +const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); +const dotStarRE = /^\.\*+$/; +const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); +const starRE = /^\*+$/; +const starTest = (f) => f.length !== 0 && !f.startsWith('.'); +const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; +const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; +const qmarksTestNocase = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestNocaseDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTest = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTestNoExt = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && !f.startsWith('.'); +}; +const qmarksTestNoExtDot = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && f !== '.' && f !== '..'; +}; +/* c8 ignore start */ +const defaultPlatform = (typeof process === 'object' && process + ? (typeof process.env === 'object' && + process.env && + process.env.__MINIMATCH_TESTING_PLATFORM__) || + process.platform + : 'posix'); +const path = { + win32: { sep: '\\' }, + posix: { sep: '/' }, +}; +/* c8 ignore stop */ +exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep; +exports.minimatch.sep = exports.sep; +exports.GLOBSTAR = Symbol('globstar **'); +exports.minimatch.GLOBSTAR = exports.GLOBSTAR; +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]'; +// * => any number of characters +const star = qmark + '*?'; +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; +const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options); +exports.filter = filter; +exports.minimatch.filter = exports.filter; +const ext = (a, b = {}) => Object.assign({}, a, b); +const defaults = (def) => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return exports.minimatch; + } + const orig = exports.minimatch; + const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); + return Object.assign(m, { + Minimatch: class Minimatch extends orig.Minimatch { + constructor(pattern, options = {}) { + super(pattern, ext(def, options)); + } + static defaults(options) { + return orig.defaults(ext(def, options)).Minimatch; + } + }, + AST: class AST extends orig.AST { + /* c8 ignore start */ + constructor(type, parent, options = {}) { + super(type, parent, ext(def, options)); + } + /* c8 ignore stop */ + static fromGlob(pattern, options = {}) { + return orig.AST.fromGlob(pattern, ext(def, options)); + } + }, + unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), + escape: (s, options = {}) => orig.escape(s, ext(def, options)), + filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), + defaults: (options) => orig.defaults(ext(def, options)), + makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), + braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), + match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), + sep: orig.sep, + GLOBSTAR: exports.GLOBSTAR, + }); +}; +exports.defaults = defaults; +exports.minimatch.defaults = exports.defaults; +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +const braceExpand = (pattern, options = {}) => { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern]; + } + return (0, brace_expansion_1.default)(pattern); +}; +exports.braceExpand = braceExpand; +exports.minimatch.braceExpand = exports.braceExpand; +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); +exports.makeRe = makeRe; +exports.minimatch.makeRe = exports.makeRe; +const match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options); + list = list.filter(f => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list; +}; +exports.match = match; +exports.minimatch.match = exports.match; +// replace stuff like \* with * +const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; +const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +class Minimatch { + options; + set; + pattern; + windowsPathsNoEscape; + nonegate; + negate; + comment; + empty; + preserveMultipleSlashes; + partial; + globSet; + globParts; + nocase; + isWindows; + platform; + windowsNoMagicRoot; + regexp; + constructor(pattern, options = {}) { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + options = options || {}; + this.options = options; + this.pattern = pattern; + this.platform = options.platform || defaultPlatform; + this.isWindows = this.platform === 'win32'; + this.windowsPathsNoEscape = + !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/'); + } + this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; + this.regexp = null; + this.negate = false; + this.nonegate = !!options.nonegate; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + this.nocase = !!this.options.nocase; + this.windowsNoMagicRoot = + options.windowsNoMagicRoot !== undefined + ? options.windowsNoMagicRoot + : !!(this.isWindows && this.nocase); + this.globSet = []; + this.globParts = []; + this.set = []; + // make the set of regexps etc. + this.make(); + } + hasMagic() { + if (this.options.magicalBraces && this.set.length > 1) { + return true; + } + for (const pattern of this.set) { + for (const part of pattern) { + if (typeof part !== 'string') + return true; + } + } + return false; + } + debug(..._) { } + make() { + const pattern = this.pattern; + const options = this.options; + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true; + return; + } + if (!pattern) { + this.empty = true; + return; + } + // step 1: figure out negation, etc. + this.parseNegate(); + // step 2: expand braces + this.globSet = [...new Set(this.braceExpand())]; + if (options.debug) { + this.debug = (...args) => console.error(...args); + } + this.debug(this.pattern, this.globSet); + // step 3: now we have a set, so turn each one into a series of + // path-portion matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + // + // First, we preprocess to make the glob pattern sets a bit simpler + // and deduped. There are some perf-killing patterns that can cause + // problems with a glob walk, but we can simplify them down a bit. + const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); + this.globParts = this.preprocess(rawGlobParts); + this.debug(this.pattern, this.globParts); + // glob --> regexps + let set = this.globParts.map((s, _, __) => { + if (this.isWindows && this.windowsNoMagicRoot) { + // check if it's a drive or unc path. + const isUNC = s[0] === '' && + s[1] === '' && + (s[2] === '?' || !globMagic.test(s[2])) && + !globMagic.test(s[3]); + const isDrive = /^[a-z]:/i.test(s[0]); + if (isUNC) { + return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]; + } + else if (isDrive) { + return [s[0], ...s.slice(1).map(ss => this.parse(ss))]; + } + } + return s.map(ss => this.parse(ss)); + }); + this.debug(this.pattern, set); + // filter out everything that didn't compile properly. + this.set = set.filter(s => s.indexOf(false) === -1); + // do not treat the ? in UNC paths as magic + if (this.isWindows) { + for (let i = 0; i < this.set.length; i++) { + const p = this.set[i]; + if (p[0] === '' && + p[1] === '' && + this.globParts[i][2] === '?' && + typeof p[3] === 'string' && + /^[a-z]:$/i.test(p[3])) { + p[2] = '?'; + } + } + } + this.debug(this.pattern, this.set); + } + // various transforms to equivalent pattern sets that are + // faster to process in a filesystem walk. The goal is to + // eliminate what we can, and push all ** patterns as far + // to the right as possible, even if it increases the number + // of patterns that we have to process. + preprocess(globParts) { + // if we're not in globstar mode, then turn all ** into * + if (this.options.noglobstar) { + for (let i = 0; i < globParts.length; i++) { + for (let j = 0; j < globParts[i].length; j++) { + if (globParts[i][j] === '**') { + globParts[i][j] = '*'; + } + } + } + } + const { optimizationLevel = 1 } = this.options; + if (optimizationLevel >= 2) { + // aggressive optimization for the purpose of fs walking + globParts = this.firstPhasePreProcess(globParts); + globParts = this.secondPhasePreProcess(globParts); + } + else if (optimizationLevel >= 1) { + // just basic optimizations to remove some .. parts + globParts = this.levelOneOptimize(globParts); + } + else { + // just collapse multiple ** portions into one + globParts = this.adjascentGlobstarOptimize(globParts); + } + return globParts; + } + // just get rid of adjascent ** portions + adjascentGlobstarOptimize(globParts) { + return globParts.map(parts => { + let gs = -1; + while (-1 !== (gs = parts.indexOf('**', gs + 1))) { + let i = gs; + while (parts[i + 1] === '**') { + i++; + } + if (i !== gs) { + parts.splice(gs, i - gs); + } + } + return parts; + }); + } + // get rid of adjascent ** and resolve .. portions + levelOneOptimize(globParts) { + return globParts.map(parts => { + parts = parts.reduce((set, part) => { + const prev = set[set.length - 1]; + if (part === '**' && prev === '**') { + return set; + } + if (part === '..') { + if (prev && prev !== '..' && prev !== '.' && prev !== '**') { + set.pop(); + return set; + } + } + set.push(part); + return set; + }, []); + return parts.length === 0 ? [''] : parts; + }); + } + levelTwoFileOptimize(parts) { + if (!Array.isArray(parts)) { + parts = this.slashSplit(parts); + } + let didSomething = false; + do { + didSomething = false; + //

// -> 
/
+            if (!this.preserveMultipleSlashes) {
+                for (let i = 1; i < parts.length - 1; i++) {
+                    const p = parts[i];
+                    // don't squeeze out UNC patterns
+                    if (i === 1 && p === '' && parts[0] === '')
+                        continue;
+                    if (p === '.' || p === '') {
+                        didSomething = true;
+                        parts.splice(i, 1);
+                        i--;
+                    }
+                }
+                if (parts[0] === '.' &&
+                    parts.length === 2 &&
+                    (parts[1] === '.' || parts[1] === '')) {
+                    didSomething = true;
+                    parts.pop();
+                }
+            }
+            // 
/

/../ ->

/
+            let dd = 0;
+            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
+                const p = parts[dd - 1];
+                if (p && p !== '.' && p !== '..' && p !== '**') {
+                    didSomething = true;
+                    parts.splice(dd - 1, 2);
+                    dd -= 2;
+                }
+            }
+        } while (didSomething);
+        return parts.length === 0 ? [''] : parts;
+    }
+    // First phase: single-pattern processing
+    // 
 is 1 or more portions
+    //  is 1 or more portions
+    // 

is any portion other than ., .., '', or ** + // is . or '' + // + // **/.. is *brutal* for filesystem walking performance, because + // it effectively resets the recursive walk each time it occurs, + // and ** cannot be reduced out by a .. pattern part like a regexp + // or most strings (other than .., ., and '') can be. + // + //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + //

// -> 
/
+    // 
/

/../ ->

/
+    // **/**/ -> **/
+    //
+    // **/*/ -> */**/ <== not valid because ** doesn't follow
+    // this WOULD be allowed if ** did follow symlinks, or * didn't
+    firstPhasePreProcess(globParts) {
+        let didSomething = false;
+        do {
+            didSomething = false;
+            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + for (let parts of globParts) { + let gs = -1; + while (-1 !== (gs = parts.indexOf('**', gs + 1))) { + let gss = gs; + while (parts[gss + 1] === '**') { + //

/**/**/ -> 
/**/
+                        gss++;
+                    }
+                    // eg, if gs is 2 and gss is 4, that means we have 3 **
+                    // parts, and can remove 2 of them.
+                    if (gss > gs) {
+                        parts.splice(gs + 1, gss - gs);
+                    }
+                    let next = parts[gs + 1];
+                    const p = parts[gs + 2];
+                    const p2 = parts[gs + 3];
+                    if (next !== '..')
+                        continue;
+                    if (!p ||
+                        p === '.' ||
+                        p === '..' ||
+                        !p2 ||
+                        p2 === '.' ||
+                        p2 === '..') {
+                        continue;
+                    }
+                    didSomething = true;
+                    // edit parts in place, and push the new one
+                    parts.splice(gs, 1);
+                    const other = parts.slice(0);
+                    other[gs] = '**';
+                    globParts.push(other);
+                    gs--;
+                }
+                // 
// -> 
/
+                if (!this.preserveMultipleSlashes) {
+                    for (let i = 1; i < parts.length - 1; i++) {
+                        const p = parts[i];
+                        // don't squeeze out UNC patterns
+                        if (i === 1 && p === '' && parts[0] === '')
+                            continue;
+                        if (p === '.' || p === '') {
+                            didSomething = true;
+                            parts.splice(i, 1);
+                            i--;
+                        }
+                    }
+                    if (parts[0] === '.' &&
+                        parts.length === 2 &&
+                        (parts[1] === '.' || parts[1] === '')) {
+                        didSomething = true;
+                        parts.pop();
+                    }
+                }
+                // 
/

/../ ->

/
+                let dd = 0;
+                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
+                    const p = parts[dd - 1];
+                    if (p && p !== '.' && p !== '..' && p !== '**') {
+                        didSomething = true;
+                        const needDot = dd === 1 && parts[dd + 1] === '**';
+                        const splin = needDot ? ['.'] : [];
+                        parts.splice(dd - 1, 2, ...splin);
+                        if (parts.length === 0)
+                            parts.push('');
+                        dd -= 2;
+                    }
+                }
+            }
+        } while (didSomething);
+        return globParts;
+    }
+    // second phase: multi-pattern dedupes
+    // {
/*/,
/

/} ->

/*/
+    // {
/,
/} -> 
/
+    // {
/**/,
/} -> 
/**/
+    //
+    // {
/**/,
/**/

/} ->

/**/
+    // ^-- not valid because ** doens't follow symlinks
+    secondPhasePreProcess(globParts) {
+        for (let i = 0; i < globParts.length - 1; i++) {
+            for (let j = i + 1; j < globParts.length; j++) {
+                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
+                if (matched) {
+                    globParts[i] = [];
+                    globParts[j] = matched;
+                    break;
+                }
+            }
+        }
+        return globParts.filter(gs => gs.length);
+    }
+    partsMatch(a, b, emptyGSMatch = false) {
+        let ai = 0;
+        let bi = 0;
+        let result = [];
+        let which = '';
+        while (ai < a.length && bi < b.length) {
+            if (a[ai] === b[bi]) {
+                result.push(which === 'b' ? b[bi] : a[ai]);
+                ai++;
+                bi++;
+            }
+            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
+                result.push(a[ai]);
+                ai++;
+            }
+            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
+                result.push(b[bi]);
+                bi++;
+            }
+            else if (a[ai] === '*' &&
+                b[bi] &&
+                (this.options.dot || !b[bi].startsWith('.')) &&
+                b[bi] !== '**') {
+                if (which === 'b')
+                    return false;
+                which = 'a';
+                result.push(a[ai]);
+                ai++;
+                bi++;
+            }
+            else if (b[bi] === '*' &&
+                a[ai] &&
+                (this.options.dot || !a[ai].startsWith('.')) &&
+                a[ai] !== '**') {
+                if (which === 'a')
+                    return false;
+                which = 'b';
+                result.push(b[bi]);
+                ai++;
+                bi++;
+            }
+            else {
+                return false;
+            }
+        }
+        // if we fall out of the loop, it means they two are identical
+        // as long as their lengths match
+        return a.length === b.length && result;
+    }
+    parseNegate() {
+        if (this.nonegate)
+            return;
+        const pattern = this.pattern;
+        let negate = false;
+        let negateOffset = 0;
+        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
+            negate = !negate;
+            negateOffset++;
+        }
+        if (negateOffset)
+            this.pattern = pattern.slice(negateOffset);
+        this.negate = negate;
+    }
+    // set partial to true to test if, for example,
+    // "/a/b" matches the start of "/*/b/*/d"
+    // Partial means, if you run out of file before you run
+    // out of pattern, then that's fine, as long as all
+    // the parts match.
+    matchOne(file, pattern, partial = false) {
+        const options = this.options;
+        // UNC paths like //?/X:/... can match X:/... and vice versa
+        // Drive letters in absolute drive or unc paths are always compared
+        // case-insensitively.
+        if (this.isWindows) {
+            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
+            const fileUNC = !fileDrive &&
+                file[0] === '' &&
+                file[1] === '' &&
+                file[2] === '?' &&
+                /^[a-z]:$/i.test(file[3]);
+            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
+            const patternUNC = !patternDrive &&
+                pattern[0] === '' &&
+                pattern[1] === '' &&
+                pattern[2] === '?' &&
+                typeof pattern[3] === 'string' &&
+                /^[a-z]:$/i.test(pattern[3]);
+            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
+            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
+            if (typeof fdi === 'number' && typeof pdi === 'number') {
+                const [fd, pd] = [file[fdi], pattern[pdi]];
+                if (fd.toLowerCase() === pd.toLowerCase()) {
+                    pattern[pdi] = fd;
+                    if (pdi > fdi) {
+                        pattern = pattern.slice(pdi);
+                    }
+                    else if (fdi > pdi) {
+                        file = file.slice(fdi);
+                    }
+                }
+            }
+        }
+        // resolve and reduce . and .. portions in the file as well.
+        // dont' need to do the second phase, because it's only one string[]
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+            file = this.levelTwoFileOptimize(file);
+        }
+        this.debug('matchOne', this, { file, pattern });
+        this.debug('matchOne', file.length, pattern.length);
+        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
+            this.debug('matchOne loop');
+            var p = pattern[pi];
+            var f = file[fi];
+            this.debug(pattern, p, f);
+            // should be impossible.
+            // some invalid regexp stuff in the set.
+            /* c8 ignore start */
+            if (p === false) {
+                return false;
+            }
+            /* c8 ignore stop */
+            if (p === exports.GLOBSTAR) {
+                this.debug('GLOBSTAR', [pattern, p, f]);
+                // "**"
+                // a/**/b/**/c would match the following:
+                // a/b/x/y/z/c
+                // a/x/y/z/b/c
+                // a/b/x/b/x/c
+                // a/b/c
+                // To do this, take the rest of the pattern after
+                // the **, and see if it would match the file remainder.
+                // If so, return success.
+                // If not, the ** "swallows" a segment, and try again.
+                // This is recursively awful.
+                //
+                // a/**/b/**/c matching a/b/x/y/z/c
+                // - a matches a
+                // - doublestar
+                //   - matchOne(b/x/y/z/c, b/**/c)
+                //     - b matches b
+                //     - doublestar
+                //       - matchOne(x/y/z/c, c) -> no
+                //       - matchOne(y/z/c, c) -> no
+                //       - matchOne(z/c, c) -> no
+                //       - matchOne(c, c) yes, hit
+                var fr = fi;
+                var pr = pi + 1;
+                if (pr === pl) {
+                    this.debug('** at the end');
+                    // a ** at the end will just swallow the rest.
+                    // We have found a match.
+                    // however, it will not swallow /.x, unless
+                    // options.dot is set.
+                    // . and .. are *never* matched by **, for explosively
+                    // exponential reasons.
+                    for (; fi < fl; fi++) {
+                        if (file[fi] === '.' ||
+                            file[fi] === '..' ||
+                            (!options.dot && file[fi].charAt(0) === '.'))
+                            return false;
+                    }
+                    return true;
+                }
+                // ok, let's see if we can swallow whatever we can.
+                while (fr < fl) {
+                    var swallowee = file[fr];
+                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
+                    // XXX remove this slice.  Just pass the start index.
+                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+                        this.debug('globstar found match!', fr, fl, swallowee);
+                        // found a match.
+                        return true;
+                    }
+                    else {
+                        // can't swallow "." or ".." ever.
+                        // can only swallow ".foo" when explicitly asked.
+                        if (swallowee === '.' ||
+                            swallowee === '..' ||
+                            (!options.dot && swallowee.charAt(0) === '.')) {
+                            this.debug('dot detected!', file, fr, pattern, pr);
+                            break;
+                        }
+                        // ** swallows a segment, and continue.
+                        this.debug('globstar swallow a segment, and continue');
+                        fr++;
+                    }
+                }
+                // no match was found.
+                // However, in partial mode, we can't say this is necessarily over.
+                /* c8 ignore start */
+                if (partial) {
+                    // ran out of file
+                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
+                    if (fr === fl) {
+                        return true;
+                    }
+                }
+                /* c8 ignore stop */
+                return false;
+            }
+            // something other than **
+            // non-magic patterns just have to match exactly
+            // patterns with magic have been turned into regexps.
+            let hit;
+            if (typeof p === 'string') {
+                hit = f === p;
+                this.debug('string match', p, f, hit);
+            }
+            else {
+                hit = p.test(f);
+                this.debug('pattern match', p, f, hit);
+            }
+            if (!hit)
+                return false;
+        }
+        // Note: ending in / means that we'll get a final ""
+        // at the end of the pattern.  This can only match a
+        // corresponding "" at the end of the file.
+        // If the file ends in /, then it can only match a
+        // a pattern that ends in /, unless the pattern just
+        // doesn't have any more for it. But, a/b/ should *not*
+        // match "a/b/*", even though "" matches against the
+        // [^/]*? pattern, except in partial mode, where it might
+        // simply not be reached yet.
+        // However, a/b/ should still satisfy a/*
+        // now either we fell off the end of the pattern, or we're done.
+        if (fi === fl && pi === pl) {
+            // ran out of pattern and filename at the same time.
+            // an exact hit!
+            return true;
+        }
+        else if (fi === fl) {
+            // ran out of file, but still had pattern left.
+            // this is ok if we're doing the match as part of
+            // a glob fs traversal.
+            return partial;
+        }
+        else if (pi === pl) {
+            // ran out of pattern, still have file left.
+            // this is only acceptable if we're on the very last
+            // empty segment of a file with a trailing slash.
+            // a/* should match a/b/
+            return fi === fl - 1 && file[fi] === '';
+            /* c8 ignore start */
+        }
+        else {
+            // should be unreachable.
+            throw new Error('wtf?');
+        }
+        /* c8 ignore stop */
+    }
+    braceExpand() {
+        return (0, exports.braceExpand)(this.pattern, this.options);
+    }
+    parse(pattern) {
+        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
+        const options = this.options;
+        // shortcuts
+        if (pattern === '**')
+            return exports.GLOBSTAR;
+        if (pattern === '')
+            return '';
+        // far and away, the most common glob pattern parts are
+        // *, *.*, and *.  Add a fast check method for those.
+        let m;
+        let fastTest = null;
+        if ((m = pattern.match(starRE))) {
+            fastTest = options.dot ? starTestDot : starTest;
+        }
+        else if ((m = pattern.match(starDotExtRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? starDotExtTestNocaseDot
+                    : starDotExtTestNocase
+                : options.dot
+                    ? starDotExtTestDot
+                    : starDotExtTest)(m[1]);
+        }
+        else if ((m = pattern.match(qmarksRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? qmarksTestNocaseDot
+                    : qmarksTestNocase
+                : options.dot
+                    ? qmarksTestDot
+                    : qmarksTest)(m);
+        }
+        else if ((m = pattern.match(starDotStarRE))) {
+            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
+        }
+        else if ((m = pattern.match(dotStarRE))) {
+            fastTest = dotStarTest;
+        }
+        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
+        if (fastTest && typeof re === 'object') {
+            // Avoids overriding in frozen environments
+            Reflect.defineProperty(re, 'test', { value: fastTest });
+        }
+        return re;
+    }
+    makeRe() {
+        if (this.regexp || this.regexp === false)
+            return this.regexp;
+        // at this point, this.set is a 2d array of partial
+        // pattern strings, or "**".
+        //
+        // It's better to use .match().  This function shouldn't
+        // be used, really, but it's pretty convenient sometimes,
+        // when you just want to work with a regex.
+        const set = this.set;
+        if (!set.length) {
+            this.regexp = false;
+            return this.regexp;
+        }
+        const options = this.options;
+        const twoStar = options.noglobstar
+            ? star
+            : options.dot
+                ? twoStarDot
+                : twoStarNoDot;
+        const flags = new Set(options.nocase ? ['i'] : []);
+        // regexpify non-globstar patterns
+        // if ** is only item, then we just do one twoStar
+        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
+        // if ** is last, append (\/twoStar|) to previous
+        // if ** is in the middle, append (\/|\/twoStar\/) to previous
+        // then filter out GLOBSTAR symbols
+        let re = set
+            .map(pattern => {
+            const pp = pattern.map(p => {
+                if (p instanceof RegExp) {
+                    for (const f of p.flags.split(''))
+                        flags.add(f);
+                }
+                return typeof p === 'string'
+                    ? regExpEscape(p)
+                    : p === exports.GLOBSTAR
+                        ? exports.GLOBSTAR
+                        : p._src;
+            });
+            pp.forEach((p, i) => {
+                const next = pp[i + 1];
+                const prev = pp[i - 1];
+                if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) {
+                    return;
+                }
+                if (prev === undefined) {
+                    if (next !== undefined && next !== exports.GLOBSTAR) {
+                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
+                    }
+                    else {
+                        pp[i] = twoStar;
+                    }
+                }
+                else if (next === undefined) {
+                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
+                }
+                else if (next !== exports.GLOBSTAR) {
+                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
+                    pp[i + 1] = exports.GLOBSTAR;
+                }
+            });
+            return pp.filter(p => p !== exports.GLOBSTAR).join('/');
+        })
+            .join('|');
+        // need to wrap in parens if we had more than one thing with |,
+        // otherwise only the first will be anchored to ^ and the last to $
+        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
+        // must match entire pattern
+        // ending in a * or ** will make it less strict.
+        re = '^' + open + re + close + '$';
+        // can match anything, as long as it's not this.
+        if (this.negate)
+            re = '^(?!' + re + ').+$';
+        try {
+            this.regexp = new RegExp(re, [...flags].join(''));
+            /* c8 ignore start */
+        }
+        catch (ex) {
+            // should be impossible
+            this.regexp = false;
+        }
+        /* c8 ignore stop */
+        return this.regexp;
+    }
+    slashSplit(p) {
+        // if p starts with // on windows, we preserve that
+        // so that UNC paths aren't broken.  Otherwise, any number of
+        // / characters are coalesced into one, unless
+        // preserveMultipleSlashes is set to true.
+        if (this.preserveMultipleSlashes) {
+            return p.split('/');
+        }
+        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
+            // add an extra '' for the one we lose
+            return ['', ...p.split(/\/+/)];
+        }
+        else {
+            return p.split(/\/+/);
+        }
+    }
+    match(f, partial = this.partial) {
+        this.debug('match', f, this.pattern);
+        // short-circuit in the case of busted things.
+        // comments, etc.
+        if (this.comment) {
+            return false;
+        }
+        if (this.empty) {
+            return f === '';
+        }
+        if (f === '/' && partial) {
+            return true;
+        }
+        const options = this.options;
+        // windows: need to use /, not \
+        if (this.isWindows) {
+            f = f.split('\\').join('/');
+        }
+        // treat the test path as a set of pathparts.
+        const ff = this.slashSplit(f);
+        this.debug(this.pattern, 'split', ff);
+        // just ONE of the pattern sets in this.set needs to match
+        // in order for it to be valid.  If negating, then just one
+        // match means that we have failed.
+        // Either way, return on the first hit.
+        const set = this.set;
+        this.debug(this.pattern, 'set', set);
+        // Find the basename of the path by looking for the last non-empty segment
+        let filename = ff[ff.length - 1];
+        if (!filename) {
+            for (let i = ff.length - 2; !filename && i >= 0; i--) {
+                filename = ff[i];
+            }
+        }
+        for (let i = 0; i < set.length; i++) {
+            const pattern = set[i];
+            let file = ff;
+            if (options.matchBase && pattern.length === 1) {
+                file = [filename];
+            }
+            const hit = this.matchOne(file, pattern, partial);
+            if (hit) {
+                if (options.flipNegate) {
+                    return true;
+                }
+                return !this.negate;
+            }
+        }
+        // didn't get any hits.  this is success if it's a negative
+        // pattern, failure otherwise.
+        if (options.flipNegate) {
+            return false;
+        }
+        return this.negate;
+    }
+    static defaults(def) {
+        return exports.minimatch.defaults(def).Minimatch;
+    }
+}
+exports.Minimatch = Minimatch;
+/* c8 ignore start */
+var ast_js_2 = require("./ast.js");
+Object.defineProperty(exports, "AST", { enumerable: true, get: function () { return ast_js_2.AST; } });
+var escape_js_2 = require("./escape.js");
+Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return escape_js_2.escape; } });
+var unescape_js_2 = require("./unescape.js");
+Object.defineProperty(exports, "unescape", { enumerable: true, get: function () { return unescape_js_2.unescape; } });
+/* c8 ignore stop */
+exports.minimatch.AST = ast_js_1.AST;
+exports.minimatch.Minimatch = Minimatch;
+exports.minimatch.escape = escape_js_1.escape;
+exports.minimatch.unescape = unescape_js_1.unescape;
+//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/index.js.map b/node_modules/minimatch/dist/commonjs/index.js.map
new file mode 100644
index 00000000..d4f6a870
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/index.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,sEAAoC;AACpC,uEAA8D;AAC9D,qCAA2C;AAC3C,2CAAoC;AACpC,+CAAwC;AAsCjC,MAAM,SAAS,GAAG,CACvB,CAAS,EACT,OAAe,EACf,UAA4B,EAAE,EAC9B,EAAE;IACF,IAAA,4CAAkB,EAAC,OAAO,CAAC,CAAA;IAE3B,oCAAoC;IACpC,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;QACnD,OAAO,KAAK,CAAA;KACb;IAED,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC,CAAA;AAbY,QAAA,SAAS,aAarB;AAED,wDAAwD;AACxD,MAAM,YAAY,GAAG,uBAAuB,CAAA;AAC5C,MAAM,cAAc,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,CAAS,EAAE,EAAE,CACpD,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;AACvC,MAAM,iBAAiB,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,C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;YACtB,IAAI,IAAI,GAAG,EAAE,CAAA;YACb,IAAI,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC7C,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAA;aAClB;YACD,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;YACjD,IAAI,GAAG,EAAE;gBACP,IAAI,OAAO,CAAC,UAAU,EAAE;oBACtB,OAAO,IAAI,CAAA;iBACZ;gBACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAA;aACpB;SACF;QAED,2DAA2D;QAC3D,8BAA8B;QAC9B,IAAI,OAAO,CAAC,UAAU,EAAE;YACtB,OAAO,KAAK,CAAA;SACb;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,GAAqB;QACnC,OAAO,iBAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;CACF;AAl4BD,8BAk4BC;AACD,qBAAqB;AACrB,mCAA8B;AAArB,6FAAA,GAAG,OAAA;AACZ,yCAAoC;AAA3B,mGAAA,MAAM,OAAA;AACf,6CAAwC;AAA/B,uGAAA,QAAQ,OAAA;AACjB,oBAAoB;AACpB,iBAAS,CAAC,GAAG,GAAG,YAAG,CAAA;AACnB,iBAAS,CAAC,SAAS,GAAG,SAAS,CAAA;AAC/B,iBAAS,CAAC,MAAM,GAAG,kBAAM,CAAA;AACzB,iBAAS,CAAC,QAAQ,GAAG,sBAAQ,CAAA","sourcesContent":["import expand from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\ntype Platform =\n  | 'aix'\n  | 'android'\n  | 'darwin'\n  | 'freebsd'\n  | 'haiku'\n  | 'linux'\n  | 'openbsd'\n  | 'sunos'\n  | 'win32'\n  | 'cygwin'\n  | 'netbsd'\n\nexport interface MinimatchOptions {\n  nobrace?: boolean\n  nocomment?: boolean\n  nonegate?: boolean\n  debug?: boolean\n  noglobstar?: boolean\n  noext?: boolean\n  nonull?: boolean\n  windowsPathsNoEscape?: boolean\n  allowWindowsEscape?: boolean\n  partial?: boolean\n  dot?: boolean\n  nocase?: boolean\n  nocaseMagicOnly?: boolean\n  magicalBraces?: boolean\n  matchBase?: boolean\n  flipNegate?: boolean\n  preserveMultipleSlashes?: boolean\n  optimizationLevel?: number\n  platform?: Platform\n  windowsNoMagicRoot?: boolean\n}\n\nexport const minimatch = (\n  p: string,\n  pattern: string,\n  options: MinimatchOptions = {}\n) => {\n  assertValidPattern(pattern)\n\n  // shortcut: comments match nothing.\n  if (!options.nocomment && pattern.charAt(0) === '#') {\n    return false\n  }\n\n  return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n  !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) => !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n  f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) => f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) => f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n  typeof process === 'object' && process\n    ? (typeof process.env === 'object' &&\n        process.env &&\n        process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n      process.platform\n    : 'posix'\n) as Platform\ntype Sep = '\\\\' | '/'\nconst path: { [k: string]: { sep: Sep } } = {\n  win32: { sep: '\\\\' },\n  posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed.  Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n  (pattern: string, options: MinimatchOptions = {}) =>\n  (p: string) =>\n    minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n  Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n  if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n    return minimatch\n  }\n\n  const orig = minimatch\n\n  const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n    orig(p, pattern, ext(def, options))\n\n  return Object.assign(m, {\n    Minimatch: class Minimatch extends orig.Minimatch {\n      constructor(pattern: string, options: MinimatchOptions = {}) {\n        super(pattern, ext(def, options))\n      }\n      static defaults(options: MinimatchOptions) {\n        return orig.defaults(ext(def, options)).Minimatch\n      }\n    },\n\n    AST: class AST extends orig.AST {\n      /* c8 ignore start */\n      constructor(\n        type: ExtglobType | null,\n        parent?: AST,\n        options: MinimatchOptions = {}\n      ) {\n        super(type, parent, ext(def, options))\n      }\n      /* c8 ignore stop */\n\n      static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n        return orig.AST.fromGlob(pattern, ext(def, options))\n      }\n    },\n\n    unescape: (\n      s: string,\n      options: Pick = {}\n    ) => orig.unescape(s, ext(def, options)),\n\n    escape: (\n      s: string,\n      options: Pick = {}\n    ) => orig.escape(s, ext(def, options)),\n\n    filter: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.filter(pattern, ext(def, options)),\n\n    defaults: (options: MinimatchOptions) => orig.defaults(ext(def, options)),\n\n    makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.makeRe(pattern, ext(def, options)),\n\n    braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.braceExpand(pattern, ext(def, options)),\n\n    match: (list: string[], pattern: string, options: MinimatchOptions = {}) =>\n      orig.match(list, pattern, ext(def, options)),\n\n    sep: orig.sep,\n    GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n  })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n  pattern: string,\n  options: MinimatchOptions = {}\n) => {\n  assertValidPattern(pattern)\n\n  // Thanks to Yeting Li  for\n  // improving this regexp to avoid a ReDOS vulnerability.\n  if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n    // shortcut. no need to expand.\n    return [pattern]\n  }\n\n  return expand(pattern)\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion.  Otherwise, any series\n// of * is equivalent to a single *.  Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n  new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n  list: string[],\n  pattern: string,\n  options: MinimatchOptions = {}\n) => {\n  const mm = new Minimatch(pattern, options)\n  list = list.filter(f => mm.match(f))\n  if (mm.options.nonull && !list.length) {\n    list.push(pattern)\n  }\n  return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n  _src?: string\n  _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n  options: MinimatchOptions\n  set: ParseReturnFiltered[][]\n  pattern: string\n\n  windowsPathsNoEscape: boolean\n  nonegate: boolean\n  negate: boolean\n  comment: boolean\n  empty: boolean\n  preserveMultipleSlashes: boolean\n  partial: boolean\n  globSet: string[]\n  globParts: string[][]\n  nocase: boolean\n\n  isWindows: boolean\n  platform: Platform\n  windowsNoMagicRoot: boolean\n\n  regexp: false | null | MMRegExp\n  constructor(pattern: string, options: MinimatchOptions = {}) {\n    assertValidPattern(pattern)\n\n    options = options || {}\n    this.options = options\n    this.pattern = pattern\n    this.platform = options.platform || defaultPlatform\n    this.isWindows = this.platform === 'win32'\n    this.windowsPathsNoEscape =\n      !!options.windowsPathsNoEscape || options.allowWindowsEscape === false\n    if (this.windowsPathsNoEscape) {\n      this.pattern = this.pattern.replace(/\\\\/g, '/')\n    }\n    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n    this.regexp = null\n    this.negate = false\n    this.nonegate = !!options.nonegate\n    this.comment = false\n    this.empty = false\n    this.partial = !!options.partial\n    this.nocase = !!this.options.nocase\n    this.windowsNoMagicRoot =\n      options.windowsNoMagicRoot !== undefined\n        ? options.windowsNoMagicRoot\n        : !!(this.isWindows && this.nocase)\n\n    this.globSet = []\n    this.globParts = []\n    this.set = []\n\n    // make the set of regexps etc.\n    this.make()\n  }\n\n  hasMagic(): boolean {\n    if (this.options.magicalBraces && this.set.length > 1) {\n      return true\n    }\n    for (const pattern of this.set) {\n      for (const part of pattern) {\n        if (typeof part !== 'string') return true\n      }\n    }\n    return false\n  }\n\n  debug(..._: any[]) {}\n\n  make() {\n    const pattern = this.pattern\n    const options = this.options\n\n    // empty patterns and comments match nothing.\n    if (!options.nocomment && pattern.charAt(0) === '#') {\n      this.comment = true\n      return\n    }\n\n    if (!pattern) {\n      this.empty = true\n      return\n    }\n\n    // step 1: figure out negation, etc.\n    this.parseNegate()\n\n    // step 2: expand braces\n    this.globSet = [...new Set(this.braceExpand())]\n\n    if (options.debug) {\n      this.debug = (...args: any[]) => console.error(...args)\n    }\n\n    this.debug(this.pattern, this.globSet)\n\n    // step 3: now we have a set, so turn each one into a series of\n    // path-portion matching patterns.\n    // These will be regexps, except in the case of \"**\", which is\n    // set to the GLOBSTAR object for globstar behavior,\n    // and will not contain any / characters\n    //\n    // First, we preprocess to make the glob pattern sets a bit simpler\n    // and deduped.  There are some perf-killing patterns that can cause\n    // problems with a glob walk, but we can simplify them down a bit.\n    const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n    this.globParts = this.preprocess(rawGlobParts)\n    this.debug(this.pattern, this.globParts)\n\n    // glob --> regexps\n    let set = this.globParts.map((s, _, __) => {\n      if (this.isWindows && this.windowsNoMagicRoot) {\n        // check if it's a drive or unc path.\n        const isUNC =\n          s[0] === '' &&\n          s[1] === '' &&\n          (s[2] === '?' || !globMagic.test(s[2])) &&\n          !globMagic.test(s[3])\n        const isDrive = /^[a-z]:/i.test(s[0])\n        if (isUNC) {\n          return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]\n        } else if (isDrive) {\n          return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n        }\n      }\n      return s.map(ss => this.parse(ss))\n    })\n\n    this.debug(this.pattern, set)\n\n    // filter out everything that didn't compile properly.\n    this.set = set.filter(\n      s => s.indexOf(false) === -1\n    ) as ParseReturnFiltered[][]\n\n    // do not treat the ? in UNC paths as magic\n    if (this.isWindows) {\n      for (let i = 0; i < this.set.length; i++) {\n        const p = this.set[i]\n        if (\n          p[0] === '' &&\n          p[1] === '' &&\n          this.globParts[i][2] === '?' &&\n          typeof p[3] === 'string' &&\n          /^[a-z]:$/i.test(p[3])\n        ) {\n          p[2] = '?'\n        }\n      }\n    }\n\n    this.debug(this.pattern, this.set)\n  }\n\n  // various transforms to equivalent pattern sets that are\n  // faster to process in a filesystem walk.  The goal is to\n  // eliminate what we can, and push all ** patterns as far\n  // to the right as possible, even if it increases the number\n  // of patterns that we have to process.\n  preprocess(globParts: string[][]) {\n    // if we're not in globstar mode, then turn all ** into *\n    if (this.options.noglobstar) {\n      for (let i = 0; i < globParts.length; i++) {\n        for (let j = 0; j < globParts[i].length; j++) {\n          if (globParts[i][j] === '**') {\n            globParts[i][j] = '*'\n          }\n        }\n      }\n    }\n\n    const { optimizationLevel = 1 } = this.options\n\n    if (optimizationLevel >= 2) {\n      // aggressive optimization for the purpose of fs walking\n      globParts = this.firstPhasePreProcess(globParts)\n      globParts = this.secondPhasePreProcess(globParts)\n    } else if (optimizationLevel >= 1) {\n      // just basic optimizations to remove some .. parts\n      globParts = this.levelOneOptimize(globParts)\n    } else {\n      // just collapse multiple ** portions into one\n      globParts = this.adjascentGlobstarOptimize(globParts)\n    }\n\n    return globParts\n  }\n\n  // just get rid of adjascent ** portions\n  adjascentGlobstarOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      let gs: number = -1\n      while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n        let i = gs\n        while (parts[i + 1] === '**') {\n          i++\n        }\n        if (i !== gs) {\n          parts.splice(gs, i - gs)\n        }\n      }\n      return parts\n    })\n  }\n\n  // get rid of adjascent ** and resolve .. portions\n  levelOneOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      parts = parts.reduce((set: string[], part) => {\n        const prev = set[set.length - 1]\n        if (part === '**' && prev === '**') {\n          return set\n        }\n        if (part === '..') {\n          if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n            set.pop()\n            return set\n          }\n        }\n        set.push(part)\n        return set\n      }, [])\n      return parts.length === 0 ? [''] : parts\n    })\n  }\n\n  levelTwoFileOptimize(parts: string | string[]) {\n    if (!Array.isArray(parts)) {\n      parts = this.slashSplit(parts)\n    }\n    let didSomething: boolean = false\n    do {\n      didSomething = false\n      // 
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      let dd: number = 0\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd -= 2\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        let dd: number = 0\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd -= 2\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/*/,
/

/} ->

/*/\n  // {
/,
/} -> 
/\n  // {
/**/,
/} -> 
/**/\n  //\n  // {
/**/,
/**/

/} ->

/**/\n  // ^-- not valid because ** doens't follow symlinks\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    for (let i = 0; i < globParts.length - 1; i++) {\n      for (let j = i + 1; j < globParts.length; j++) {\n        const matched = this.partsMatch(\n          globParts[i],\n          globParts[j],\n          !this.preserveMultipleSlashes\n        )\n        if (matched) {\n          globParts[i] = []\n          globParts[j] = matched\n          break\n        }\n      }\n    }\n    return globParts.filter(gs => gs.length)\n  }\n\n  partsMatch(\n    a: string[],\n    b: string[],\n    emptyGSMatch: boolean = false\n  ): false | string[] {\n    let ai = 0\n    let bi = 0\n    let result: string[] = []\n    let which: string = ''\n    while (ai < a.length && bi < b.length) {\n      if (a[ai] === b[bi]) {\n        result.push(which === 'b' ? b[bi] : a[ai])\n        ai++\n        bi++\n      } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n        result.push(a[ai])\n        ai++\n      } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n        result.push(b[bi])\n        bi++\n      } else if (\n        a[ai] === '*' &&\n        b[bi] &&\n        (this.options.dot || !b[bi].startsWith('.')) &&\n        b[bi] !== '**'\n      ) {\n        if (which === 'b') return false\n        which = 'a'\n        result.push(a[ai])\n        ai++\n        bi++\n      } else if (\n        b[bi] === '*' &&\n        a[ai] &&\n        (this.options.dot || !a[ai].startsWith('.')) &&\n        a[ai] !== '**'\n      ) {\n        if (which === 'a') return false\n        which = 'b'\n        result.push(b[bi])\n        ai++\n        bi++\n      } else {\n        return false\n      }\n    }\n    // if we fall out of the loop, it means they two are identical\n    // as long as their lengths match\n    return a.length === b.length && result\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // set partial to true to test if, for example,\n  // \"/a/b\" matches the start of \"/*/b/*/d\"\n  // Partial means, if you run out of file before you run\n  // out of pattern, then that's fine, as long as all\n  // the parts match.\n  matchOne(file: string[], pattern: ParseReturn[], partial: boolean = false) {\n    const options = this.options\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa\n    // Drive letters in absolute drive or unc paths are always compared\n    // case-insensitively.\n    if (this.isWindows) {\n      const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined\n      const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [file[fdi], pattern[pdi] as string]\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          pattern[pdi] = fd\n          if (pdi > fdi) {\n            pattern = pattern.slice(pdi)\n          } else if (fdi > pdi) {\n            file = file.slice(fdi)\n          }\n        }\n      }\n    }\n\n    // resolve and reduce . and .. portions in the file as well.\n    // dont' need to do the second phase, because it's only one string[]\n    const { optimizationLevel = 1 } = this.options\n    if (optimizationLevel >= 2) {\n      file = this.levelTwoFileOptimize(file)\n    }\n\n    this.debug('matchOne', this, { file, pattern })\n    this.debug('matchOne', file.length, pattern.length)\n\n    for (\n      var fi = 0, pi = 0, fl = file.length, pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      this.debug('matchOne loop')\n      var p = pattern[pi]\n      var f = file[fi]\n\n      this.debug(pattern, p, f)\n\n      // should be impossible.\n      // some invalid regexp stuff in the set.\n      /* c8 ignore start */\n      if (p === false) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      if (p === GLOBSTAR) {\n        this.debug('GLOBSTAR', [pattern, p, f])\n\n        // \"**\"\n        // a/**/b/**/c would match the following:\n        // a/b/x/y/z/c\n        // a/x/y/z/b/c\n        // a/b/x/b/x/c\n        // a/b/c\n        // To do this, take the rest of the pattern after\n        // the **, and see if it would match the file remainder.\n        // If so, return success.\n        // If not, the ** \"swallows\" a segment, and try again.\n        // This is recursively awful.\n        //\n        // a/**/b/**/c matching a/b/x/y/z/c\n        // - a matches a\n        // - doublestar\n        //   - matchOne(b/x/y/z/c, b/**/c)\n        //     - b matches b\n        //     - doublestar\n        //       - matchOne(x/y/z/c, c) -> no\n        //       - matchOne(y/z/c, c) -> no\n        //       - matchOne(z/c, c) -> no\n        //       - matchOne(c, c) yes, hit\n        var fr = fi\n        var pr = pi + 1\n        if (pr === pl) {\n          this.debug('** at the end')\n          // a ** at the end will just swallow the rest.\n          // We have found a match.\n          // however, it will not swallow /.x, unless\n          // options.dot is set.\n          // . and .. are *never* matched by **, for explosively\n          // exponential reasons.\n          for (; fi < fl; fi++) {\n            if (\n              file[fi] === '.' ||\n              file[fi] === '..' ||\n              (!options.dot && file[fi].charAt(0) === '.')\n            )\n              return false\n          }\n          return true\n        }\n\n        // ok, let's see if we can swallow whatever we can.\n        while (fr < fl) {\n          var swallowee = file[fr]\n\n          this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n          // XXX remove this slice.  Just pass the start index.\n          if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n            this.debug('globstar found match!', fr, fl, swallowee)\n            // found a match.\n            return true\n          } else {\n            // can't swallow \".\" or \"..\" ever.\n            // can only swallow \".foo\" when explicitly asked.\n            if (\n              swallowee === '.' ||\n              swallowee === '..' ||\n              (!options.dot && swallowee.charAt(0) === '.')\n            ) {\n              this.debug('dot detected!', file, fr, pattern, pr)\n              break\n            }\n\n            // ** swallows a segment, and continue.\n            this.debug('globstar swallow a segment, and continue')\n            fr++\n          }\n        }\n\n        // no match was found.\n        // However, in partial mode, we can't say this is necessarily over.\n        /* c8 ignore start */\n        if (partial) {\n          // ran out of file\n          this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n          if (fr === fl) {\n            return true\n          }\n        }\n        /* c8 ignore stop */\n        return false\n      }\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into regexps.\n      let hit: boolean\n      if (typeof p === 'string') {\n        hit = f === p\n        this.debug('string match', p, f, hit)\n      } else {\n        hit = p.test(f)\n        this.debug('pattern match', p, f, hit)\n      }\n\n      if (!hit) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though \"\" matches against the\n    // [^/]*? pattern, except in partial mode, where it might\n    // simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    // far and away, the most common glob pattern parts are\n    // *, *.*, and *.  Add a fast check method for those.\n    let m: RegExpMatchArray | null\n    let fastTest: null | ((f: string) => boolean) = null\n    if ((m = pattern.match(starRE))) {\n      fastTest = options.dot ? starTestDot : starTest\n    } else if ((m = pattern.match(starDotExtRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? starDotExtTestNocaseDot\n            : starDotExtTestNocase\n          : options.dot\n          ? starDotExtTestDot\n          : starDotExtTest\n      )(m[1])\n    } else if ((m = pattern.match(qmarksRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? qmarksTestNocaseDot\n            : qmarksTestNocase\n          : options.dot\n          ? qmarksTestDot\n          : qmarksTest\n      )(m)\n    } else if ((m = pattern.match(starDotStarRE))) {\n      fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n    } else if ((m = pattern.match(dotStarRE))) {\n      fastTest = dotStarTest\n    }\n\n    const re = AST.fromGlob(pattern, this.options).toMMPattern()\n    if (fastTest && typeof re === 'object') {\n      // Avoids overriding in frozen environments\n      Reflect.defineProperty(re, 'test', { value: fastTest })\n    }\n    return re\n  }\n\n  makeRe() {\n    if (this.regexp || this.regexp === false) return this.regexp\n\n    // at this point, this.set is a 2d array of partial\n    // pattern strings, or \"**\".\n    //\n    // It's better to use .match().  This function shouldn't\n    // be used, really, but it's pretty convenient sometimes,\n    // when you just want to work with a regex.\n    const set = this.set\n\n    if (!set.length) {\n      this.regexp = false\n      return this.regexp\n    }\n    const options = this.options\n\n    const twoStar = options.noglobstar\n      ? star\n      : options.dot\n      ? twoStarDot\n      : twoStarNoDot\n    const flags = new Set(options.nocase ? ['i'] : [])\n\n    // regexpify non-globstar patterns\n    // if ** is only item, then we just do one twoStar\n    // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n    // if ** is last, append (\\/twoStar|) to previous\n    // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n    // then filter out GLOBSTAR symbols\n    let re = set\n      .map(pattern => {\n        const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n          if (p instanceof RegExp) {\n            for (const f of p.flags.split('')) flags.add(f)\n          }\n          return typeof p === 'string'\n            ? regExpEscape(p)\n            : p === GLOBSTAR\n            ? GLOBSTAR\n            : p._src\n        }) as (string | typeof GLOBSTAR)[]\n        pp.forEach((p, i) => {\n          const next = pp[i + 1]\n          const prev = pp[i - 1]\n          if (p !== GLOBSTAR || prev === GLOBSTAR) {\n            return\n          }\n          if (prev === undefined) {\n            if (next !== undefined && next !== GLOBSTAR) {\n              pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n            } else {\n              pp[i] = twoStar\n            }\n          } else if (next === undefined) {\n            pp[i - 1] = prev + '(?:\\\\/|' + twoStar + ')?'\n          } else if (next !== GLOBSTAR) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n            pp[i + 1] = GLOBSTAR\n          }\n        })\n        return pp.filter(p => p !== GLOBSTAR).join('/')\n      })\n      .join('|')\n\n    // need to wrap in parens if we had more than one thing with |,\n    // otherwise only the first will be anchored to ^ and the last to $\n    const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n    // must match entire pattern\n    // ending in a * or ** will make it less strict.\n    re = '^' + open + re + close + '$'\n\n    // can match anything, as long as it's not this.\n    if (this.negate) re = '^(?!' + re + ').+$'\n\n    try {\n      this.regexp = new RegExp(re, [...flags].join(''))\n      /* c8 ignore start */\n    } catch (ex) {\n      // should be impossible\n      this.regexp = false\n    }\n    /* c8 ignore stop */\n    return this.regexp\n  }\n\n  slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    this.debug('match', f, this.pattern)\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // windows: need to use /, not \\\n    if (this.isWindows) {\n      f = f.split('\\\\').join('/')\n    }\n\n    // treat the test path as a set of pathparts.\n    const ff = this.slashSplit(f)\n    this.debug(this.pattern, 'split', ff)\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n    this.debug(this.pattern, 'set', set)\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let i = 0; i < set.length; i++) {\n      const pattern = set[i]\n      let file = ff\n      if (options.matchBase && pattern.length === 1) {\n        file = [filename]\n      }\n      const hit = this.matchOne(file, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/package.json b/node_modules/minimatch/dist/commonjs/package.json
new file mode 100644
index 00000000..5bbefffb
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/package.json
@@ -0,0 +1,3 @@
+{
+  "type": "commonjs"
+}
diff --git a/node_modules/minimatch/dist/commonjs/unescape.d.ts b/node_modules/minimatch/dist/commonjs/unescape.d.ts
new file mode 100644
index 00000000..23a7b387
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/unescape.d.ts
@@ -0,0 +1,17 @@
+import { MinimatchOptions } from './index.js';
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+export declare const unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+//# sourceMappingURL=unescape.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/unescape.d.ts.map b/node_modules/minimatch/dist/commonjs/unescape.d.ts.map
new file mode 100644
index 00000000..7ace0701
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/unescape.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,QAAQ,MAChB,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAKlD,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/unescape.js b/node_modules/minimatch/dist/commonjs/unescape.js
new file mode 100644
index 00000000..47c36bce
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/unescape.js
@@ -0,0 +1,24 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.unescape = void 0;
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
+    return windowsPathsNoEscape
+        ? s.replace(/\[([^\/\\])\]/g, '$1')
+        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
+};
+exports.unescape = unescape;
+//# sourceMappingURL=unescape.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/unescape.js.map b/node_modules/minimatch/dist/commonjs/unescape.js.map
new file mode 100644
index 00000000..353d3aa0
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/unescape.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":";;;AACA;;;;;;;;;;;;;GAaG;AACI,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC;QACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,2BAA2B,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC,CAAA;AAChF,CAAC,CAAA;AATY,QAAA,QAAQ,YASpB","sourcesContent":["import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes.  For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n  }: Pick = {}\n) => {\n  return windowsPathsNoEscape\n    ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n    : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts b/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts
new file mode 100644
index 00000000..8e318b23
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts
@@ -0,0 +1,2 @@
+export declare const assertValidPattern: (pattern: any) => void;
+//# sourceMappingURL=assert-valid-pattern.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts.map b/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts.map
new file mode 100644
index 00000000..c61c0310
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"assert-valid-pattern.d.ts","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAUlD,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/assert-valid-pattern.js b/node_modules/minimatch/dist/esm/assert-valid-pattern.js
new file mode 100644
index 00000000..7b534fc3
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/assert-valid-pattern.js
@@ -0,0 +1,10 @@
+const MAX_PATTERN_LENGTH = 1024 * 64;
+export const assertValidPattern = (pattern) => {
+    if (typeof pattern !== 'string') {
+        throw new TypeError('invalid pattern');
+    }
+    if (pattern.length > MAX_PATTERN_LENGTH) {
+        throw new TypeError('pattern is too long');
+    }
+};
+//# sourceMappingURL=assert-valid-pattern.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map b/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map
new file mode 100644
index 00000000..b1a5a0b9
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"assert-valid-pattern.js","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAA;AACpC,MAAM,CAAC,MAAM,kBAAkB,GAA2B,CACxD,OAAY,EACe,EAAE;IAC7B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;KACvC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,kBAAkB,EAAE;QACvC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAA;KAC3C;AACH,CAAC,CAAA","sourcesContent":["const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n  pattern: any\n): asserts pattern is string => {\n  if (typeof pattern !== 'string') {\n    throw new TypeError('invalid pattern')\n  }\n\n  if (pattern.length > MAX_PATTERN_LENGTH) {\n    throw new TypeError('pattern is too long')\n  }\n}\n"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/ast.d.ts b/node_modules/minimatch/dist/esm/ast.d.ts
new file mode 100644
index 00000000..b8c1e544
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/ast.d.ts
@@ -0,0 +1,20 @@
+import { MinimatchOptions, MMRegExp } from './index.js';
+export type ExtglobType = '!' | '?' | '+' | '*' | '@';
+export declare class AST {
+    #private;
+    type: ExtglobType | null;
+    constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions);
+    get hasMagic(): boolean | undefined;
+    toString(): string;
+    push(...parts: (string | AST)[]): void;
+    toJSON(): any[];
+    isStart(): boolean;
+    isEnd(): boolean;
+    copyIn(part: AST | string): void;
+    clone(parent: AST): AST;
+    static fromGlob(pattern: string, options?: MinimatchOptions): AST;
+    toMMPattern(): MMRegExp | string;
+    get options(): MinimatchOptions;
+    toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean];
+}
+//# sourceMappingURL=ast.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/ast.d.ts.map b/node_modules/minimatch/dist/esm/ast.d.ts.map
new file mode 100644
index 00000000..9e7bfb9a
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/ast.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwCvD,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAkCrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;gBAiBtB,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IA+ClB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAY/B,MAAM;IAgBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsIjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CAiMjE"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/ast.js b/node_modules/minimatch/dist/esm/ast.js
new file mode 100644
index 00000000..2d2bced6
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/ast.js
@@ -0,0 +1,588 @@
+// parse a single path portion
+import { parseClass } from './brace-expressions.js';
+import { unescape } from './unescape.js';
+const types = new Set(['!', '?', '+', '*', '@']);
+const isExtglobType = (c) => types.has(c);
+// Patterns that get prepended to bind to the start of either the
+// entire string, or just a single path portion, to prevent dots
+// and/or traversal patterns, when needed.
+// Exts don't need the ^ or / bit, because the root binds that already.
+const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
+const startNoDot = '(?!\\.)';
+// characters that indicate a start of pattern needs the "no dots" bit,
+// because a dot *might* be matched. ( is not in the list, because in
+// the case of a child extglob, it will handle the prevention itself.
+const addPatternStart = new Set(['[', '.']);
+// cases where traversal is A-OK, no dot prevention needed
+const justDots = new Set(['..', '.']);
+const reSpecials = new Set('().*{}+?[]^$\\!');
+const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+// any single thing other than /
+const qmark = '[^/]';
+// * => any number of characters
+const star = qmark + '*?';
+// use + when we need to ensure that *something* matches, because the * is
+// the only thing in the path portion.
+const starNoEmpty = qmark + '+?';
+// remove the \ chars that we added if we end up doing a nonmagic compare
+// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
+export class AST {
+    type;
+    #root;
+    #hasMagic;
+    #uflag = false;
+    #parts = [];
+    #parent;
+    #parentIndex;
+    #negs;
+    #filledNegs = false;
+    #options;
+    #toString;
+    // set to true if it's an extglob with no children
+    // (which really means one child of '')
+    #emptyExt = false;
+    constructor(type, parent, options = {}) {
+        this.type = type;
+        // extglobs are inherently magical
+        if (type)
+            this.#hasMagic = true;
+        this.#parent = parent;
+        this.#root = this.#parent ? this.#parent.#root : this;
+        this.#options = this.#root === this ? options : this.#root.#options;
+        this.#negs = this.#root === this ? [] : this.#root.#negs;
+        if (type === '!' && !this.#root.#filledNegs)
+            this.#negs.push(this);
+        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
+    }
+    get hasMagic() {
+        /* c8 ignore start */
+        if (this.#hasMagic !== undefined)
+            return this.#hasMagic;
+        /* c8 ignore stop */
+        for (const p of this.#parts) {
+            if (typeof p === 'string')
+                continue;
+            if (p.type || p.hasMagic)
+                return (this.#hasMagic = true);
+        }
+        // note: will be undefined until we generate the regexp src and find out
+        return this.#hasMagic;
+    }
+    // reconstructs the pattern
+    toString() {
+        if (this.#toString !== undefined)
+            return this.#toString;
+        if (!this.type) {
+            return (this.#toString = this.#parts.map(p => String(p)).join(''));
+        }
+        else {
+            return (this.#toString =
+                this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
+        }
+    }
+    #fillNegs() {
+        /* c8 ignore start */
+        if (this !== this.#root)
+            throw new Error('should only call on root');
+        if (this.#filledNegs)
+            return this;
+        /* c8 ignore stop */
+        // call toString() once to fill this out
+        this.toString();
+        this.#filledNegs = true;
+        let n;
+        while ((n = this.#negs.pop())) {
+            if (n.type !== '!')
+                continue;
+            // walk up the tree, appending everthing that comes AFTER parentIndex
+            let p = n;
+            let pp = p.#parent;
+            while (pp) {
+                for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
+                    for (const part of n.#parts) {
+                        /* c8 ignore start */
+                        if (typeof part === 'string') {
+                            throw new Error('string part in extglob AST??');
+                        }
+                        /* c8 ignore stop */
+                        part.copyIn(pp.#parts[i]);
+                    }
+                }
+                p = pp;
+                pp = p.#parent;
+            }
+        }
+        return this;
+    }
+    push(...parts) {
+        for (const p of parts) {
+            if (p === '')
+                continue;
+            /* c8 ignore start */
+            if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
+                throw new Error('invalid part: ' + p);
+            }
+            /* c8 ignore stop */
+            this.#parts.push(p);
+        }
+    }
+    toJSON() {
+        const ret = this.type === null
+            ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
+            : [this.type, ...this.#parts.map(p => p.toJSON())];
+        if (this.isStart() && !this.type)
+            ret.unshift([]);
+        if (this.isEnd() &&
+            (this === this.#root ||
+                (this.#root.#filledNegs && this.#parent?.type === '!'))) {
+            ret.push({});
+        }
+        return ret;
+    }
+    isStart() {
+        if (this.#root === this)
+            return true;
+        // if (this.type) return !!this.#parent?.isStart()
+        if (!this.#parent?.isStart())
+            return false;
+        if (this.#parentIndex === 0)
+            return true;
+        // if everything AHEAD of this is a negation, then it's still the "start"
+        const p = this.#parent;
+        for (let i = 0; i < this.#parentIndex; i++) {
+            const pp = p.#parts[i];
+            if (!(pp instanceof AST && pp.type === '!')) {
+                return false;
+            }
+        }
+        return true;
+    }
+    isEnd() {
+        if (this.#root === this)
+            return true;
+        if (this.#parent?.type === '!')
+            return true;
+        if (!this.#parent?.isEnd())
+            return false;
+        if (!this.type)
+            return this.#parent?.isEnd();
+        // if not root, it'll always have a parent
+        /* c8 ignore start */
+        const pl = this.#parent ? this.#parent.#parts.length : 0;
+        /* c8 ignore stop */
+        return this.#parentIndex === pl - 1;
+    }
+    copyIn(part) {
+        if (typeof part === 'string')
+            this.push(part);
+        else
+            this.push(part.clone(this));
+    }
+    clone(parent) {
+        const c = new AST(this.type, parent);
+        for (const p of this.#parts) {
+            c.copyIn(p);
+        }
+        return c;
+    }
+    static #parseAST(str, ast, pos, opt) {
+        let escaping = false;
+        let inBrace = false;
+        let braceStart = -1;
+        let braceNeg = false;
+        if (ast.type === null) {
+            // outside of a extglob, append until we find a start
+            let i = pos;
+            let acc = '';
+            while (i < str.length) {
+                const c = str.charAt(i++);
+                // still accumulate escapes at this point, but we do ignore
+                // starts that are escaped
+                if (escaping || c === '\\') {
+                    escaping = !escaping;
+                    acc += c;
+                    continue;
+                }
+                if (inBrace) {
+                    if (i === braceStart + 1) {
+                        if (c === '^' || c === '!') {
+                            braceNeg = true;
+                        }
+                    }
+                    else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
+                        inBrace = false;
+                    }
+                    acc += c;
+                    continue;
+                }
+                else if (c === '[') {
+                    inBrace = true;
+                    braceStart = i;
+                    braceNeg = false;
+                    acc += c;
+                    continue;
+                }
+                if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
+                    ast.push(acc);
+                    acc = '';
+                    const ext = new AST(c, ast);
+                    i = AST.#parseAST(str, ext, i, opt);
+                    ast.push(ext);
+                    continue;
+                }
+                acc += c;
+            }
+            ast.push(acc);
+            return i;
+        }
+        // some kind of extglob, pos is at the (
+        // find the next | or )
+        let i = pos + 1;
+        let part = new AST(null, ast);
+        const parts = [];
+        let acc = '';
+        while (i < str.length) {
+            const c = str.charAt(i++);
+            // still accumulate escapes at this point, but we do ignore
+            // starts that are escaped
+            if (escaping || c === '\\') {
+                escaping = !escaping;
+                acc += c;
+                continue;
+            }
+            if (inBrace) {
+                if (i === braceStart + 1) {
+                    if (c === '^' || c === '!') {
+                        braceNeg = true;
+                    }
+                }
+                else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
+                    inBrace = false;
+                }
+                acc += c;
+                continue;
+            }
+            else if (c === '[') {
+                inBrace = true;
+                braceStart = i;
+                braceNeg = false;
+                acc += c;
+                continue;
+            }
+            if (isExtglobType(c) && str.charAt(i) === '(') {
+                part.push(acc);
+                acc = '';
+                const ext = new AST(c, part);
+                part.push(ext);
+                i = AST.#parseAST(str, ext, i, opt);
+                continue;
+            }
+            if (c === '|') {
+                part.push(acc);
+                acc = '';
+                parts.push(part);
+                part = new AST(null, ast);
+                continue;
+            }
+            if (c === ')') {
+                if (acc === '' && ast.#parts.length === 0) {
+                    ast.#emptyExt = true;
+                }
+                part.push(acc);
+                acc = '';
+                ast.push(...parts, part);
+                return i;
+            }
+            acc += c;
+        }
+        // unfinished extglob
+        // if we got here, it was a malformed extglob! not an extglob, but
+        // maybe something else in there.
+        ast.type = null;
+        ast.#hasMagic = undefined;
+        ast.#parts = [str.substring(pos - 1)];
+        return i;
+    }
+    static fromGlob(pattern, options = {}) {
+        const ast = new AST(null, undefined, options);
+        AST.#parseAST(pattern, ast, 0, options);
+        return ast;
+    }
+    // returns the regular expression if there's magic, or the unescaped
+    // string if not.
+    toMMPattern() {
+        // should only be called on root
+        /* c8 ignore start */
+        if (this !== this.#root)
+            return this.#root.toMMPattern();
+        /* c8 ignore stop */
+        const glob = this.toString();
+        const [re, body, hasMagic, uflag] = this.toRegExpSource();
+        // if we're in nocase mode, and not nocaseMagicOnly, then we do
+        // still need a regular expression if we have to case-insensitively
+        // match capital/lowercase characters.
+        const anyMagic = hasMagic ||
+            this.#hasMagic ||
+            (this.#options.nocase &&
+                !this.#options.nocaseMagicOnly &&
+                glob.toUpperCase() !== glob.toLowerCase());
+        if (!anyMagic) {
+            return body;
+        }
+        const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
+        return Object.assign(new RegExp(`^${re}$`, flags), {
+            _src: re,
+            _glob: glob,
+        });
+    }
+    get options() {
+        return this.#options;
+    }
+    // returns the string match, the regexp source, whether there's magic
+    // in the regexp (so a regular expression is required) and whether or
+    // not the uflag is needed for the regular expression (for posix classes)
+    // TODO: instead of injecting the start/end at this point, just return
+    // the BODY of the regexp, along with the start/end portions suitable
+    // for binding the start/end in either a joined full-path makeRe context
+    // (where we bind to (^|/), or a standalone matchPart context (where
+    // we bind to ^, and not /).  Otherwise slashes get duped!
+    //
+    // In part-matching mode, the start is:
+    // - if not isStart: nothing
+    // - if traversal possible, but not allowed: ^(?!\.\.?$)
+    // - if dots allowed or not possible: ^
+    // - if dots possible and not allowed: ^(?!\.)
+    // end is:
+    // - if not isEnd(): nothing
+    // - else: $
+    //
+    // In full-path matching mode, we put the slash at the START of the
+    // pattern, so start is:
+    // - if first pattern: same as part-matching mode
+    // - if not isStart(): nothing
+    // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
+    // - if dots allowed or not possible: /
+    // - if dots possible and not allowed: /(?!\.)
+    // end is:
+    // - if last pattern, same as part-matching mode
+    // - else nothing
+    //
+    // Always put the (?:$|/) on negated tails, though, because that has to be
+    // there to bind the end of the negated pattern portion, and it's easier to
+    // just stick it in now rather than try to inject it later in the middle of
+    // the pattern.
+    //
+    // We can just always return the same end, and leave it up to the caller
+    // to know whether it's going to be used joined or in parts.
+    // And, if the start is adjusted slightly, can do the same there:
+    // - if not isStart: nothing
+    // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
+    // - if dots allowed or not possible: (?:/|^)
+    // - if dots possible and not allowed: (?:/|^)(?!\.)
+    //
+    // But it's better to have a simpler binding without a conditional, for
+    // performance, so probably better to return both start options.
+    //
+    // Then the caller just ignores the end if it's not the first pattern,
+    // and the start always gets applied.
+    //
+    // But that's always going to be $ if it's the ending pattern, or nothing,
+    // so the caller can just attach $ at the end of the pattern when building.
+    //
+    // So the todo is:
+    // - better detect what kind of start is needed
+    // - return both flavors of starting pattern
+    // - attach $ at the end of the pattern when creating the actual RegExp
+    //
+    // Ah, but wait, no, that all only applies to the root when the first pattern
+    // is not an extglob. If the first pattern IS an extglob, then we need all
+    // that dot prevention biz to live in the extglob portions, because eg
+    // +(*|.x*) can match .xy but not .yx.
+    //
+    // So, return the two flavors if it's #root and the first child is not an
+    // AST, otherwise leave it to the child AST to handle it, and there,
+    // use the (?:^|/) style of start binding.
+    //
+    // Even simplified further:
+    // - Since the start for a join is eg /(?!\.) and the start for a part
+    // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
+    // or start or whatever) and prepend ^ or / at the Regexp construction.
+    toRegExpSource(allowDot) {
+        const dot = allowDot ?? !!this.#options.dot;
+        if (this.#root === this)
+            this.#fillNegs();
+        if (!this.type) {
+            const noEmpty = this.isStart() && this.isEnd();
+            const src = this.#parts
+                .map(p => {
+                const [re, _, hasMagic, uflag] = typeof p === 'string'
+                    ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
+                    : p.toRegExpSource(allowDot);
+                this.#hasMagic = this.#hasMagic || hasMagic;
+                this.#uflag = this.#uflag || uflag;
+                return re;
+            })
+                .join('');
+            let start = '';
+            if (this.isStart()) {
+                if (typeof this.#parts[0] === 'string') {
+                    // this is the string that will match the start of the pattern,
+                    // so we need to protect against dots and such.
+                    // '.' and '..' cannot match unless the pattern is that exactly,
+                    // even if it starts with . or dot:true is set.
+                    const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
+                    if (!dotTravAllowed) {
+                        const aps = addPatternStart;
+                        // check if we have a possibility of matching . or ..,
+                        // and prevent that.
+                        const needNoTrav = 
+                        // dots are allowed, and the pattern starts with [ or .
+                        (dot && aps.has(src.charAt(0))) ||
+                            // the pattern starts with \., and then [ or .
+                            (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
+                            // the pattern starts with \.\., and then [ or .
+                            (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
+                        // no need to prevent dots if it can't match a dot, or if a
+                        // sub-pattern will be preventing it anyway.
+                        const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
+                        start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
+                    }
+                }
+            }
+            // append the "end of path portion" pattern to negation tails
+            let end = '';
+            if (this.isEnd() &&
+                this.#root.#filledNegs &&
+                this.#parent?.type === '!') {
+                end = '(?:$|\\/)';
+            }
+            const final = start + src + end;
+            return [
+                final,
+                unescape(src),
+                (this.#hasMagic = !!this.#hasMagic),
+                this.#uflag,
+            ];
+        }
+        // We need to calculate the body *twice* if it's a repeat pattern
+        // at the start, once in nodot mode, then again in dot mode, so a
+        // pattern like *(?) can match 'x.y'
+        const repeated = this.type === '*' || this.type === '+';
+        // some kind of extglob
+        const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
+        let body = this.#partsToRegExp(dot);
+        if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
+            // invalid extglob, has to at least be *something* present, if it's
+            // the entire path portion.
+            const s = this.toString();
+            this.#parts = [s];
+            this.type = null;
+            this.#hasMagic = undefined;
+            return [s, unescape(this.toString()), false, false];
+        }
+        // XXX abstract out this map method
+        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
+            ? ''
+            : this.#partsToRegExp(true);
+        if (bodyDotAllowed === body) {
+            bodyDotAllowed = '';
+        }
+        if (bodyDotAllowed) {
+            body = `(?:${body})(?:${bodyDotAllowed})*?`;
+        }
+        // an empty !() is exactly equivalent to a starNoEmpty
+        let final = '';
+        if (this.type === '!' && this.#emptyExt) {
+            final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
+        }
+        else {
+            const close = this.type === '!'
+                ? // !() must match something,but !(x) can match ''
+                    '))' +
+                        (this.isStart() && !dot && !allowDot ? startNoDot : '') +
+                        star +
+                        ')'
+                : this.type === '@'
+                    ? ')'
+                    : this.type === '?'
+                        ? ')?'
+                        : this.type === '+' && bodyDotAllowed
+                            ? ')'
+                            : this.type === '*' && bodyDotAllowed
+                                ? `)?`
+                                : `)${this.type}`;
+            final = start + body + close;
+        }
+        return [
+            final,
+            unescape(body),
+            (this.#hasMagic = !!this.#hasMagic),
+            this.#uflag,
+        ];
+    }
+    #partsToRegExp(dot) {
+        return this.#parts
+            .map(p => {
+            // extglob ASTs should only contain parent ASTs
+            /* c8 ignore start */
+            if (typeof p === 'string') {
+                throw new Error('string type in extglob ast??');
+            }
+            /* c8 ignore stop */
+            // can ignore hasMagic, because extglobs are already always magic
+            const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
+            this.#uflag = this.#uflag || uflag;
+            return re;
+        })
+            .filter(p => !(this.isStart() && this.isEnd()) || !!p)
+            .join('|');
+    }
+    static #parseGlob(glob, hasMagic, noEmpty = false) {
+        let escaping = false;
+        let re = '';
+        let uflag = false;
+        for (let i = 0; i < glob.length; i++) {
+            const c = glob.charAt(i);
+            if (escaping) {
+                escaping = false;
+                re += (reSpecials.has(c) ? '\\' : '') + c;
+                continue;
+            }
+            if (c === '\\') {
+                if (i === glob.length - 1) {
+                    re += '\\\\';
+                }
+                else {
+                    escaping = true;
+                }
+                continue;
+            }
+            if (c === '[') {
+                const [src, needUflag, consumed, magic] = parseClass(glob, i);
+                if (consumed) {
+                    re += src;
+                    uflag = uflag || needUflag;
+                    i += consumed - 1;
+                    hasMagic = hasMagic || magic;
+                    continue;
+                }
+            }
+            if (c === '*') {
+                if (noEmpty && glob === '*')
+                    re += starNoEmpty;
+                else
+                    re += star;
+                hasMagic = true;
+                continue;
+            }
+            if (c === '?') {
+                re += qmark;
+                hasMagic = true;
+                continue;
+            }
+            re += regExpEscape(c);
+        }
+        return [re, unescape(glob), !!hasMagic, uflag];
+    }
+}
+//# sourceMappingURL=ast.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/ast.js.map b/node_modules/minimatch/dist/esm/ast.js.map
new file mode 100644
index 00000000..f1f8b34c
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/ast.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"ast.js","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAE9B,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAEnD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAwCxC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAc,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;AAC7D,MAAM,aAAa,GAAG,CAAC,CAAS,EAAoB,EAAE,CACpD,KAAK,CAAC,GAAG,CAAC,CAAgB,CAAC,CAAA;AAE7B,iEAAiE;AACjE,gEAAgE;AAChE,0CAA0C;AAC1C,uEAAuE;AACvE,MAAM,gBAAgB,GAAG,2BAA2B,CAAA;AACpD,MAAM,UAAU,GAAG,SAAS,CAAA;A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CAAA;oBAC1B,CAAC,IAAI,QAAQ,GAAG,CAAC,CAAA;oBACjB,QAAQ,GAAG,QAAQ,IAAI,KAAK,CAAA;oBAC5B,SAAQ;iBACT;aACF;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,IAAI,OAAO,IAAI,IAAI,KAAK,GAAG;oBAAE,EAAE,IAAI,WAAW,CAAA;;oBACzC,EAAE,IAAI,IAAI,CAAA;gBACf,QAAQ,GAAG,IAAI,CAAA;gBACf,SAAQ;aACT;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,EAAE,IAAI,KAAK,CAAA;gBACX,QAAQ,GAAG,IAAI,CAAA;gBACf,SAAQ;aACT;YACD,EAAE,IAAI,YAAY,CAAC,CAAC,CAAC,CAAA;SACtB;QACD,OAAO,CAAC,EAAE,EAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;IAChD,CAAC;CACF","sourcesContent":["// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n//   1   2 3   4 5 6      1   2    3   46      5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n//                                 v----- .* because there's more following,\n//                                 v    v  otherwise, .+ because it must be\n//                                 v    v  *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n//   copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string): c is ExtglobType =>\n  types.has(c as ExtglobType)\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n  type: ExtglobType | null\n  readonly #root: AST\n\n  #hasMagic?: boolean\n  #uflag: boolean = false\n  #parts: (string | AST)[] = []\n  readonly #parent?: AST\n  readonly #parentIndex: number\n  #negs: AST[]\n  #filledNegs: boolean = false\n  #options: MinimatchOptions\n  #toString?: string\n  // set to true if it's an extglob with no children\n  // (which really means one child of '')\n  #emptyExt: boolean = false\n\n  constructor(\n    type: ExtglobType | null,\n    parent?: AST,\n    options: MinimatchOptions = {}\n  ) {\n    this.type = type\n    // extglobs are inherently magical\n    if (type) this.#hasMagic = true\n    this.#parent = parent\n    this.#root = this.#parent ? this.#parent.#root : this\n    this.#options = this.#root === this ? options : this.#root.#options\n    this.#negs = this.#root === this ? [] : this.#root.#negs\n    if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n    this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n  }\n\n  get hasMagic(): boolean | undefined {\n    /* c8 ignore start */\n    if (this.#hasMagic !== undefined) return this.#hasMagic\n    /* c8 ignore stop */\n    for (const p of this.#parts) {\n      if (typeof p === 'string') continue\n      if (p.type || p.hasMagic) return (this.#hasMagic = true)\n    }\n    // note: will be undefined until we generate the regexp src and find out\n    return this.#hasMagic\n  }\n\n  // reconstructs the pattern\n  toString(): string {\n    if (this.#toString !== undefined) return this.#toString\n    if (!this.type) {\n      return (this.#toString = this.#parts.map(p => String(p)).join(''))\n    } else {\n      return (this.#toString =\n        this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n    }\n  }\n\n  #fillNegs() {\n    /* c8 ignore start */\n    if (this !== this.#root) throw new Error('should only call on root')\n    if (this.#filledNegs) return this\n    /* c8 ignore stop */\n\n    // call toString() once to fill this out\n    this.toString()\n    this.#filledNegs = true\n    let n: AST | undefined\n    while ((n = this.#negs.pop())) {\n      if (n.type !== '!') continue\n      // walk up the tree, appending everthing that comes AFTER parentIndex\n      let p: AST | undefined = n\n      let pp = p.#parent\n      while (pp) {\n        for (\n          let i = p.#parentIndex + 1;\n          !pp.type && i < pp.#parts.length;\n          i++\n        ) {\n          for (const part of n.#parts) {\n            /* c8 ignore start */\n            if (typeof part === 'string') {\n              throw new Error('string part in extglob AST??')\n            }\n            /* c8 ignore stop */\n            part.copyIn(pp.#parts[i])\n          }\n        }\n        p = pp\n        pp = p.#parent\n      }\n    }\n    return this\n  }\n\n  push(...parts: (string | AST)[]) {\n    for (const p of parts) {\n      if (p === '') continue\n      /* c8 ignore start */\n      if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {\n        throw new Error('invalid part: ' + p)\n      }\n      /* c8 ignore stop */\n      this.#parts.push(p)\n    }\n  }\n\n  toJSON() {\n    const ret: any[] =\n      this.type === null\n        ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))\n        : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n    if (this.isStart() && !this.type) ret.unshift([])\n    if (\n      this.isEnd() &&\n      (this === this.#root ||\n        (this.#root.#filledNegs && this.#parent?.type === '!'))\n    ) {\n      ret.push({})\n    }\n    return ret\n  }\n\n  isStart(): boolean {\n    if (this.#root === this) return true\n    // if (this.type) return !!this.#parent?.isStart()\n    if (!this.#parent?.isStart()) return false\n    if (this.#parentIndex === 0) return true\n    // if everything AHEAD of this is a negation, then it's still the \"start\"\n    const p = this.#parent\n    for (let i = 0; i < this.#parentIndex; i++) {\n      const pp = p.#parts[i]\n      if (!(pp instanceof AST && pp.type === '!')) {\n        return false\n      }\n    }\n    return true\n  }\n\n  isEnd(): boolean {\n    if (this.#root === this) return true\n    if (this.#parent?.type === '!') return true\n    if (!this.#parent?.isEnd()) return false\n    if (!this.type) return this.#parent?.isEnd()\n    // if not root, it'll always have a parent\n    /* c8 ignore start */\n    const pl = this.#parent ? this.#parent.#parts.length : 0\n    /* c8 ignore stop */\n    return this.#parentIndex === pl - 1\n  }\n\n  copyIn(part: AST | string) {\n    if (typeof part === 'string') this.push(part)\n    else this.push(part.clone(this))\n  }\n\n  clone(parent: AST) {\n    const c = new AST(this.type, parent)\n    for (const p of this.#parts) {\n      c.copyIn(p)\n    }\n    return c\n  }\n\n  static #parseAST(\n    str: string,\n    ast: AST,\n    pos: number,\n    opt: MinimatchOptions\n  ): number {\n    let escaping = false\n    let inBrace = false\n    let braceStart = -1\n    let braceNeg = false\n    if (ast.type === null) {\n      // outside of a extglob, append until we find a start\n      let i = pos\n      let acc = ''\n      while (i < str.length) {\n        const c = str.charAt(i++)\n        // still accumulate escapes at this point, but we do ignore\n        // starts that are escaped\n        if (escaping || c === '\\\\') {\n          escaping = !escaping\n          acc += c\n          continue\n        }\n\n        if (inBrace) {\n          if (i === braceStart + 1) {\n            if (c === '^' || c === '!') {\n              braceNeg = true\n            }\n          } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n            inBrace = false\n          }\n          acc += c\n          continue\n        } else if (c === '[') {\n          inBrace = true\n          braceStart = i\n          braceNeg = false\n          acc += c\n          continue\n        }\n\n        if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n          ast.push(acc)\n          acc = ''\n          const ext = new AST(c, ast)\n          i = AST.#parseAST(str, ext, i, opt)\n          ast.push(ext)\n          continue\n        }\n        acc += c\n      }\n      ast.push(acc)\n      return i\n    }\n\n    // some kind of extglob, pos is at the (\n    // find the next | or )\n    let i = pos + 1\n    let part = new AST(null, ast)\n    const parts: AST[] = []\n    let acc = ''\n    while (i < str.length) {\n      const c = str.charAt(i++)\n      // still accumulate escapes at this point, but we do ignore\n      // starts that are escaped\n      if (escaping || c === '\\\\') {\n        escaping = !escaping\n        acc += c\n        continue\n      }\n\n      if (inBrace) {\n        if (i === braceStart + 1) {\n          if (c === '^' || c === '!') {\n            braceNeg = true\n          }\n        } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n          inBrace = false\n        }\n        acc += c\n        continue\n      } else if (c === '[') {\n        inBrace = true\n        braceStart = i\n        braceNeg = false\n        acc += c\n        continue\n      }\n\n      if (isExtglobType(c) && str.charAt(i) === '(') {\n        part.push(acc)\n        acc = ''\n        const ext = new AST(c, part)\n        part.push(ext)\n        i = AST.#parseAST(str, ext, i, opt)\n        continue\n      }\n      if (c === '|') {\n        part.push(acc)\n        acc = ''\n        parts.push(part)\n        part = new AST(null, ast)\n        continue\n      }\n      if (c === ')') {\n        if (acc === '' && ast.#parts.length === 0) {\n          ast.#emptyExt = true\n        }\n        part.push(acc)\n        acc = ''\n        ast.push(...parts, part)\n        return i\n      }\n      acc += c\n    }\n\n    // unfinished extglob\n    // if we got here, it was a malformed extglob! not an extglob, but\n    // maybe something else in there.\n    ast.type = null\n    ast.#hasMagic = undefined\n    ast.#parts = [str.substring(pos - 1)]\n    return i\n  }\n\n  static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n    const ast = new AST(null, undefined, options)\n    AST.#parseAST(pattern, ast, 0, options)\n    return ast\n  }\n\n  // returns the regular expression if there's magic, or the unescaped\n  // string if not.\n  toMMPattern(): MMRegExp | string {\n    // should only be called on root\n    /* c8 ignore start */\n    if (this !== this.#root) return this.#root.toMMPattern()\n    /* c8 ignore stop */\n    const glob = this.toString()\n    const [re, body, hasMagic, uflag] = this.toRegExpSource()\n    // if we're in nocase mode, and not nocaseMagicOnly, then we do\n    // still need a regular expression if we have to case-insensitively\n    // match capital/lowercase characters.\n    const anyMagic =\n      hasMagic ||\n      this.#hasMagic ||\n      (this.#options.nocase &&\n        !this.#options.nocaseMagicOnly &&\n        glob.toUpperCase() !== glob.toLowerCase())\n    if (!anyMagic) {\n      return body\n    }\n\n    const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n    return Object.assign(new RegExp(`^${re}$`, flags), {\n      _src: re,\n      _glob: glob,\n    })\n  }\n\n  get options() {\n    return this.#options\n  }\n\n  // returns the string match, the regexp source, whether there's magic\n  // in the regexp (so a regular expression is required) and whether or\n  // not the uflag is needed for the regular expression (for posix classes)\n  // TODO: instead of injecting the start/end at this point, just return\n  // the BODY of the regexp, along with the start/end portions suitable\n  // for binding the start/end in either a joined full-path makeRe context\n  // (where we bind to (^|/), or a standalone matchPart context (where\n  // we bind to ^, and not /).  Otherwise slashes get duped!\n  //\n  // In part-matching mode, the start is:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n  // - if dots allowed or not possible: ^\n  // - if dots possible and not allowed: ^(?!\\.)\n  // end is:\n  // - if not isEnd(): nothing\n  // - else: $\n  //\n  // In full-path matching mode, we put the slash at the START of the\n  // pattern, so start is:\n  // - if first pattern: same as part-matching mode\n  // - if not isStart(): nothing\n  // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n  // - if dots allowed or not possible: /\n  // - if dots possible and not allowed: /(?!\\.)\n  // end is:\n  // - if last pattern, same as part-matching mode\n  // - else nothing\n  //\n  // Always put the (?:$|/) on negated tails, though, because that has to be\n  // there to bind the end of the negated pattern portion, and it's easier to\n  // just stick it in now rather than try to inject it later in the middle of\n  // the pattern.\n  //\n  // We can just always return the same end, and leave it up to the caller\n  // to know whether it's going to be used joined or in parts.\n  // And, if the start is adjusted slightly, can do the same there:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n  // - if dots allowed or not possible: (?:/|^)\n  // - if dots possible and not allowed: (?:/|^)(?!\\.)\n  //\n  // But it's better to have a simpler binding without a conditional, for\n  // performance, so probably better to return both start options.\n  //\n  // Then the caller just ignores the end if it's not the first pattern,\n  // and the start always gets applied.\n  //\n  // But that's always going to be $ if it's the ending pattern, or nothing,\n  // so the caller can just attach $ at the end of the pattern when building.\n  //\n  // So the todo is:\n  // - better detect what kind of start is needed\n  // - return both flavors of starting pattern\n  // - attach $ at the end of the pattern when creating the actual RegExp\n  //\n  // Ah, but wait, no, that all only applies to the root when the first pattern\n  // is not an extglob. If the first pattern IS an extglob, then we need all\n  // that dot prevention biz to live in the extglob portions, because eg\n  // +(*|.x*) can match .xy but not .yx.\n  //\n  // So, return the two flavors if it's #root and the first child is not an\n  // AST, otherwise leave it to the child AST to handle it, and there,\n  // use the (?:^|/) style of start binding.\n  //\n  // Even simplified further:\n  // - Since the start for a join is eg /(?!\\.) and the start for a part\n  // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n  // or start or whatever) and prepend ^ or / at the Regexp construction.\n  toRegExpSource(\n    allowDot?: boolean\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    const dot = allowDot ?? !!this.#options.dot\n    if (this.#root === this) this.#fillNegs()\n    if (!this.type) {\n      const noEmpty = this.isStart() && this.isEnd()\n      const src = this.#parts\n        .map(p => {\n          const [re, _, hasMagic, uflag] =\n            typeof p === 'string'\n              ? AST.#parseGlob(p, this.#hasMagic, noEmpty)\n              : p.toRegExpSource(allowDot)\n          this.#hasMagic = this.#hasMagic || hasMagic\n          this.#uflag = this.#uflag || uflag\n          return re\n        })\n        .join('')\n\n      let start = ''\n      if (this.isStart()) {\n        if (typeof this.#parts[0] === 'string') {\n          // this is the string that will match the start of the pattern,\n          // so we need to protect against dots and such.\n\n          // '.' and '..' cannot match unless the pattern is that exactly,\n          // even if it starts with . or dot:true is set.\n          const dotTravAllowed =\n            this.#parts.length === 1 && justDots.has(this.#parts[0])\n          if (!dotTravAllowed) {\n            const aps = addPatternStart\n            // check if we have a possibility of matching . or ..,\n            // and prevent that.\n            const needNoTrav =\n              // dots are allowed, and the pattern starts with [ or .\n              (dot && aps.has(src.charAt(0))) ||\n              // the pattern starts with \\., and then [ or .\n              (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n              // the pattern starts with \\.\\., and then [ or .\n              (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n            // no need to prevent dots if it can't match a dot, or if a\n            // sub-pattern will be preventing it anyway.\n            const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n            start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''\n          }\n        }\n      }\n\n      // append the \"end of path portion\" pattern to negation tails\n      let end = ''\n      if (\n        this.isEnd() &&\n        this.#root.#filledNegs &&\n        this.#parent?.type === '!'\n      ) {\n        end = '(?:$|\\\\/)'\n      }\n      const final = start + src + end\n      return [\n        final,\n        unescape(src),\n        (this.#hasMagic = !!this.#hasMagic),\n        this.#uflag,\n      ]\n    }\n\n    // We need to calculate the body *twice* if it's a repeat pattern\n    // at the start, once in nodot mode, then again in dot mode, so a\n    // pattern like *(?) can match 'x.y'\n\n    const repeated = this.type === '*' || this.type === '+'\n    // some kind of extglob\n    const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n    let body = this.#partsToRegExp(dot)\n\n    if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n      // invalid extglob, has to at least be *something* present, if it's\n      // the entire path portion.\n      const s = this.toString()\n      this.#parts = [s]\n      this.type = null\n      this.#hasMagic = undefined\n      return [s, unescape(this.toString()), false, false]\n    }\n\n    // XXX abstract out this map method\n    let bodyDotAllowed =\n      !repeated || allowDot || dot || !startNoDot\n        ? ''\n        : this.#partsToRegExp(true)\n    if (bodyDotAllowed === body) {\n      bodyDotAllowed = ''\n    }\n    if (bodyDotAllowed) {\n      body = `(?:${body})(?:${bodyDotAllowed})*?`\n    }\n\n    // an empty !() is exactly equivalent to a starNoEmpty\n    let final = ''\n    if (this.type === '!' && this.#emptyExt) {\n      final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n    } else {\n      const close =\n        this.type === '!'\n          ? // !() must match something,but !(x) can match ''\n            '))' +\n            (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n            star +\n            ')'\n          : this.type === '@'\n          ? ')'\n          : this.type === '?'\n          ? ')?'\n          : this.type === '+' && bodyDotAllowed\n          ? ')'\n          : this.type === '*' && bodyDotAllowed\n          ? `)?`\n          : `)${this.type}`\n      final = start + body + close\n    }\n    return [\n      final,\n      unescape(body),\n      (this.#hasMagic = !!this.#hasMagic),\n      this.#uflag,\n    ]\n  }\n\n  #partsToRegExp(dot: boolean) {\n    return this.#parts\n      .map(p => {\n        // extglob ASTs should only contain parent ASTs\n        /* c8 ignore start */\n        if (typeof p === 'string') {\n          throw new Error('string type in extglob ast??')\n        }\n        /* c8 ignore stop */\n        // can ignore hasMagic, because extglobs are already always magic\n        const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n        this.#uflag = this.#uflag || uflag\n        return re\n      })\n      .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n      .join('|')\n  }\n\n  static #parseGlob(\n    glob: string,\n    hasMagic: boolean | undefined,\n    noEmpty: boolean = false\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    let escaping = false\n    let re = ''\n    let uflag = false\n    for (let i = 0; i < glob.length; i++) {\n      const c = glob.charAt(i)\n      if (escaping) {\n        escaping = false\n        re += (reSpecials.has(c) ? '\\\\' : '') + c\n        continue\n      }\n      if (c === '\\\\') {\n        if (i === glob.length - 1) {\n          re += '\\\\\\\\'\n        } else {\n          escaping = true\n        }\n        continue\n      }\n      if (c === '[') {\n        const [src, needUflag, consumed, magic] = parseClass(glob, i)\n        if (consumed) {\n          re += src\n          uflag = uflag || needUflag\n          i += consumed - 1\n          hasMagic = hasMagic || magic\n          continue\n        }\n      }\n      if (c === '*') {\n        if (noEmpty && glob === '*') re += starNoEmpty\n        else re += star\n        hasMagic = true\n        continue\n      }\n      if (c === '?') {\n        re += qmark\n        hasMagic = true\n        continue\n      }\n      re += regExpEscape(c)\n    }\n    return [re, unescape(glob), !!hasMagic, uflag]\n  }\n}\n"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/brace-expressions.d.ts b/node_modules/minimatch/dist/esm/brace-expressions.d.ts
new file mode 100644
index 00000000..b1572deb
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/brace-expressions.d.ts
@@ -0,0 +1,8 @@
+export type ParseClassResult = [
+    src: string,
+    uFlag: boolean,
+    consumed: number,
+    hasMagic: boolean
+];
+export declare const parseClass: (glob: string, position: number) => ParseClassResult;
+//# sourceMappingURL=brace-expressions.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/brace-expressions.d.ts.map b/node_modules/minimatch/dist/esm/brace-expressions.d.ts.map
new file mode 100644
index 00000000..d3949648
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/brace-expressions.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AA+BA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,SACf,MAAM,YACF,MAAM,qBA8HjB,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/brace-expressions.js b/node_modules/minimatch/dist/esm/brace-expressions.js
new file mode 100644
index 00000000..c629d6ae
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/brace-expressions.js
@@ -0,0 +1,148 @@
+// translate the various posix character classes into unicode properties
+// this works across all unicode locales
+// { : [, /u flag required, negated]
+const posixClasses = {
+    '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
+    '[:alpha:]': ['\\p{L}\\p{Nl}', true],
+    '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
+    '[:blank:]': ['\\p{Zs}\\t', true],
+    '[:cntrl:]': ['\\p{Cc}', true],
+    '[:digit:]': ['\\p{Nd}', true],
+    '[:graph:]': ['\\p{Z}\\p{C}', true, true],
+    '[:lower:]': ['\\p{Ll}', true],
+    '[:print:]': ['\\p{C}', true],
+    '[:punct:]': ['\\p{P}', true],
+    '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
+    '[:upper:]': ['\\p{Lu}', true],
+    '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
+    '[:xdigit:]': ['A-Fa-f0-9', false],
+};
+// only need to escape a few things inside of brace expressions
+// escapes: [ \ ] -
+const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
+// escape all regexp magic characters
+const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+// everything has already been escaped, we just have to join
+const rangesToString = (ranges) => ranges.join('');
+// takes a glob string at a posix brace expression, and returns
+// an equivalent regular expression source, and boolean indicating
+// whether the /u flag needs to be applied, and the number of chars
+// consumed to parse the character class.
+// This also removes out of order ranges, and returns ($.) if the
+// entire class just no good.
+export const parseClass = (glob, position) => {
+    const pos = position;
+    /* c8 ignore start */
+    if (glob.charAt(pos) !== '[') {
+        throw new Error('not in a brace expression');
+    }
+    /* c8 ignore stop */
+    const ranges = [];
+    const negs = [];
+    let i = pos + 1;
+    let sawStart = false;
+    let uflag = false;
+    let escaping = false;
+    let negate = false;
+    let endPos = pos;
+    let rangeStart = '';
+    WHILE: while (i < glob.length) {
+        const c = glob.charAt(i);
+        if ((c === '!' || c === '^') && i === pos + 1) {
+            negate = true;
+            i++;
+            continue;
+        }
+        if (c === ']' && sawStart && !escaping) {
+            endPos = i + 1;
+            break;
+        }
+        sawStart = true;
+        if (c === '\\') {
+            if (!escaping) {
+                escaping = true;
+                i++;
+                continue;
+            }
+            // escaped \ char, fall through and treat like normal char
+        }
+        if (c === '[' && !escaping) {
+            // either a posix class, a collation equivalent, or just a [
+            for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
+                if (glob.startsWith(cls, i)) {
+                    // invalid, [a-[] is fine, but not [a-[:alpha]]
+                    if (rangeStart) {
+                        return ['$.', false, glob.length - pos, true];
+                    }
+                    i += cls.length;
+                    if (neg)
+                        negs.push(unip);
+                    else
+                        ranges.push(unip);
+                    uflag = uflag || u;
+                    continue WHILE;
+                }
+            }
+        }
+        // now it's just a normal character, effectively
+        escaping = false;
+        if (rangeStart) {
+            // throw this range away if it's not valid, but others
+            // can still match.
+            if (c > rangeStart) {
+                ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
+            }
+            else if (c === rangeStart) {
+                ranges.push(braceEscape(c));
+            }
+            rangeStart = '';
+            i++;
+            continue;
+        }
+        // now might be the start of a range.
+        // can be either c-d or c-] or c] or c] at this point
+        if (glob.startsWith('-]', i + 1)) {
+            ranges.push(braceEscape(c + '-'));
+            i += 2;
+            continue;
+        }
+        if (glob.startsWith('-', i + 1)) {
+            rangeStart = c;
+            i += 2;
+            continue;
+        }
+        // not the start of a range, just a single character
+        ranges.push(braceEscape(c));
+        i++;
+    }
+    if (endPos < i) {
+        // didn't see the end of the class, not a valid class,
+        // but might still be valid as a literal match.
+        return ['', false, 0, false];
+    }
+    // if we got no ranges and no negates, then we have a range that
+    // cannot possibly match anything, and that poisons the whole glob
+    if (!ranges.length && !negs.length) {
+        return ['$.', false, glob.length - pos, true];
+    }
+    // if we got one positive range, and it's a single character, then that's
+    // not actually a magic pattern, it's just that one literal character.
+    // we should not treat that as "magic", we should just return the literal
+    // character. [_] is a perfectly valid way to escape glob magic chars.
+    if (negs.length === 0 &&
+        ranges.length === 1 &&
+        /^\\?.$/.test(ranges[0]) &&
+        !negate) {
+        const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
+        return [regexpEscape(r), false, endPos - pos, false];
+    }
+    const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
+    const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
+    const comb = ranges.length && negs.length
+        ? '(' + sranges + '|' + snegs + ')'
+        : ranges.length
+            ? sranges
+            : snegs;
+    return [comb, uflag, endPos - pos, true];
+};
+//# sourceMappingURL=brace-expressions.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/brace-expressions.js.map b/node_modules/minimatch/dist/esm/brace-expressions.js.map
new file mode 100644
index 00000000..cdba30da
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/brace-expressions.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"brace-expressions.js","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,wCAAwC;AAExC,8DAA8D;AAC9D,MAAM,YAAY,GAA0D;IAC1E,WAAW,EAAE,CAAC,sBAAsB,EAAE,IAAI,CAAC;IAC3C,WAAW,E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,GAAG,cAAc,CAAC,MAAM,CAAC,GAAG,GAAG,CAAA;IACxE,MAAM,KAAK,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,cAAc,CAAC,IAAI,CAAC,GAAG,GAAG,CAAA;IACpE,MAAM,IAAI,GACR,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM;QAC1B,CAAC,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG;QACnC,CAAC,CAAC,MAAM,CAAC,MAAM;YACf,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,KAAK,CAAA;IAEX,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,CAAA;AAC1C,CAAC,CAAA","sourcesContent":["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } = {\n  '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n  '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n  '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n  '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n  '[:cntrl:]': ['\\\\p{Cc}', true],\n  '[:digit:]': ['\\\\p{Nd}', true],\n  '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n  '[:lower:]': ['\\\\p{Ll}', true],\n  '[:print:]': ['\\\\p{C}', true],\n  '[:punct:]': ['\\\\p{P}', true],\n  '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n  '[:upper:]': ['\\\\p{Lu}', true],\n  '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n  '[:xdigit:]': ['A-Fa-f0-9', false],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n  src: string,\n  uFlag: boolean,\n  consumed: number,\n  hasMagic: boolean\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n  glob: string,\n  position: number\n): ParseClassResult => {\n  const pos = position\n  /* c8 ignore start */\n  if (glob.charAt(pos) !== '[') {\n    throw new Error('not in a brace expression')\n  }\n  /* c8 ignore stop */\n  const ranges: string[] = []\n  const negs: string[] = []\n\n  let i = pos + 1\n  let sawStart = false\n  let uflag = false\n  let escaping = false\n  let negate = false\n  let endPos = pos\n  let rangeStart = ''\n  WHILE: while (i < glob.length) {\n    const c = glob.charAt(i)\n    if ((c === '!' || c === '^') && i === pos + 1) {\n      negate = true\n      i++\n      continue\n    }\n\n    if (c === ']' && sawStart && !escaping) {\n      endPos = i + 1\n      break\n    }\n\n    sawStart = true\n    if (c === '\\\\') {\n      if (!escaping) {\n        escaping = true\n        i++\n        continue\n      }\n      // escaped \\ char, fall through and treat like normal char\n    }\n    if (c === '[' && !escaping) {\n      // either a posix class, a collation equivalent, or just a [\n      for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n        if (glob.startsWith(cls, i)) {\n          // invalid, [a-[] is fine, but not [a-[:alpha]]\n          if (rangeStart) {\n            return ['$.', false, glob.length - pos, true]\n          }\n          i += cls.length\n          if (neg) negs.push(unip)\n          else ranges.push(unip)\n          uflag = uflag || u\n          continue WHILE\n        }\n      }\n    }\n\n    // now it's just a normal character, effectively\n    escaping = false\n    if (rangeStart) {\n      // throw this range away if it's not valid, but others\n      // can still match.\n      if (c > rangeStart) {\n        ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n      } else if (c === rangeStart) {\n        ranges.push(braceEscape(c))\n      }\n      rangeStart = ''\n      i++\n      continue\n    }\n\n    // now might be the start of a range.\n    // can be either c-d or c-] or c] or c] at this point\n    if (glob.startsWith('-]', i + 1)) {\n      ranges.push(braceEscape(c + '-'))\n      i += 2\n      continue\n    }\n    if (glob.startsWith('-', i + 1)) {\n      rangeStart = c\n      i += 2\n      continue\n    }\n\n    // not the start of a range, just a single character\n    ranges.push(braceEscape(c))\n    i++\n  }\n\n  if (endPos < i) {\n    // didn't see the end of the class, not a valid class,\n    // but might still be valid as a literal match.\n    return ['', false, 0, false]\n  }\n\n  // if we got no ranges and no negates, then we have a range that\n  // cannot possibly match anything, and that poisons the whole glob\n  if (!ranges.length && !negs.length) {\n    return ['$.', false, glob.length - pos, true]\n  }\n\n  // if we got one positive range, and it's a single character, then that's\n  // not actually a magic pattern, it's just that one literal character.\n  // we should not treat that as \"magic\", we should just return the literal\n  // character. [_] is a perfectly valid way to escape glob magic chars.\n  if (\n    negs.length === 0 &&\n    ranges.length === 1 &&\n    /^\\\\?.$/.test(ranges[0]) &&\n    !negate\n  ) {\n    const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n    return [regexpEscape(r), false, endPos - pos, false]\n  }\n\n  const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n  const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n  const comb =\n    ranges.length && negs.length\n      ? '(' + sranges + '|' + snegs + ')'\n      : ranges.length\n      ? sranges\n      : snegs\n\n  return [comb, uflag, endPos - pos, true]\n}\n"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/escape.d.ts b/node_modules/minimatch/dist/esm/escape.d.ts
new file mode 100644
index 00000000..dc3e3163
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/escape.d.ts
@@ -0,0 +1,12 @@
+import { MinimatchOptions } from './index.js';
+/**
+ * Escape all magic characters in a glob pattern.
+ *
+ * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
+ * option is used, then characters are escaped by wrapping in `[]`, because
+ * a magic character wrapped in a character class can only be satisfied by
+ * that exact character.  In this mode, `\` is _not_ escaped, because it is
+ * not interpreted as a magic character, but instead as a path separator.
+ */
+export declare const escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+//# sourceMappingURL=escape.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/escape.d.ts.map b/node_modules/minimatch/dist/esm/escape.d.ts.map
new file mode 100644
index 00000000..0779dae7
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/escape.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;GAQG;AACH,eAAO,MAAM,MAAM,MACd,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAQlD,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/escape.js b/node_modules/minimatch/dist/esm/escape.js
new file mode 100644
index 00000000..16f7c8c7
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/escape.js
@@ -0,0 +1,18 @@
+/**
+ * Escape all magic characters in a glob pattern.
+ *
+ * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
+ * option is used, then characters are escaped by wrapping in `[]`, because
+ * a magic character wrapped in a character class can only be satisfied by
+ * that exact character.  In this mode, `\` is _not_ escaped, because it is
+ * not interpreted as a magic character, but instead as a path separator.
+ */
+export const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
+    // don't need to escape +@! because we escape the parens
+    // that make those magic, and escaping ! as [!] isn't valid,
+    // because [!]] is a valid glob class meaning not ']'.
+    return windowsPathsNoEscape
+        ? s.replace(/[?*()[\]]/g, '[$&]')
+        : s.replace(/[?*()[\]\\]/g, '\\$&');
+};
+//# sourceMappingURL=escape.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/escape.js.map b/node_modules/minimatch/dist/esm/escape.js.map
new file mode 100644
index 00000000..170fd1ad
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/escape.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AACA;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA","sourcesContent":["import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character.  In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n  }: Pick = {}\n) => {\n  // don't need to escape +@! because we escape the parens\n  // that make those magic, and escaping ! as [!] isn't valid,\n  // because [!]] is a valid glob class meaning not ']'.\n  return windowsPathsNoEscape\n    ? s.replace(/[?*()[\\]]/g, '[$&]')\n    : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/index.d.ts b/node_modules/minimatch/dist/esm/index.d.ts
new file mode 100644
index 00000000..41d16a98
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/index.d.ts
@@ -0,0 +1,94 @@
+import { AST } from './ast.js';
+type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd';
+export interface MinimatchOptions {
+    nobrace?: boolean;
+    nocomment?: boolean;
+    nonegate?: boolean;
+    debug?: boolean;
+    noglobstar?: boolean;
+    noext?: boolean;
+    nonull?: boolean;
+    windowsPathsNoEscape?: boolean;
+    allowWindowsEscape?: boolean;
+    partial?: boolean;
+    dot?: boolean;
+    nocase?: boolean;
+    nocaseMagicOnly?: boolean;
+    magicalBraces?: boolean;
+    matchBase?: boolean;
+    flipNegate?: boolean;
+    preserveMultipleSlashes?: boolean;
+    optimizationLevel?: number;
+    platform?: Platform;
+    windowsNoMagicRoot?: boolean;
+}
+export declare const minimatch: {
+    (p: string, pattern: string, options?: MinimatchOptions): boolean;
+    sep: Sep;
+    GLOBSTAR: typeof GLOBSTAR;
+    filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
+    defaults: (def: MinimatchOptions) => typeof minimatch;
+    braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
+    makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
+    match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
+    AST: typeof AST;
+    Minimatch: typeof Minimatch;
+    escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+    unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+};
+type Sep = '\\' | '/';
+export declare const sep: Sep;
+export declare const GLOBSTAR: unique symbol;
+export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
+export declare const defaults: (def: MinimatchOptions) => typeof minimatch;
+export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
+export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
+export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
+export type MMRegExp = RegExp & {
+    _src?: string;
+    _glob?: string;
+};
+export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR;
+export type ParseReturn = ParseReturnFiltered | false;
+export declare class Minimatch {
+    options: MinimatchOptions;
+    set: ParseReturnFiltered[][];
+    pattern: string;
+    windowsPathsNoEscape: boolean;
+    nonegate: boolean;
+    negate: boolean;
+    comment: boolean;
+    empty: boolean;
+    preserveMultipleSlashes: boolean;
+    partial: boolean;
+    globSet: string[];
+    globParts: string[][];
+    nocase: boolean;
+    isWindows: boolean;
+    platform: Platform;
+    windowsNoMagicRoot: boolean;
+    regexp: false | null | MMRegExp;
+    constructor(pattern: string, options?: MinimatchOptions);
+    hasMagic(): boolean;
+    debug(..._: any[]): void;
+    make(): void;
+    preprocess(globParts: string[][]): string[][];
+    adjascentGlobstarOptimize(globParts: string[][]): string[][];
+    levelOneOptimize(globParts: string[][]): string[][];
+    levelTwoFileOptimize(parts: string | string[]): string[];
+    firstPhasePreProcess(globParts: string[][]): string[][];
+    secondPhasePreProcess(globParts: string[][]): string[][];
+    partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[];
+    parseNegate(): void;
+    matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean;
+    braceExpand(): string[];
+    parse(pattern: string): ParseReturn;
+    makeRe(): false | MMRegExp;
+    slashSplit(p: string): string[];
+    match(f: string, partial?: boolean): boolean;
+    static defaults(def: MinimatchOptions): typeof Minimatch;
+}
+export { AST } from './ast.js';
+export { escape } from './escape.js';
+export { unescape } from './unescape.js';
+//# sourceMappingURL=index.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/index.d.ts.map b/node_modules/minimatch/dist/esm/index.d.ts.map
new file mode 100644
index 00000000..195491d8
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/index.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.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git a/node_modules/minimatch/dist/esm/index.js b/node_modules/minimatch/dist/esm/index.js
new file mode 100644
index 00000000..84b577b0
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/index.js
@@ -0,0 +1,1001 @@
+import expand from 'brace-expansion';
+import { assertValidPattern } from './assert-valid-pattern.js';
+import { AST } from './ast.js';
+import { escape } from './escape.js';
+import { unescape } from './unescape.js';
+export const minimatch = (p, pattern, options = {}) => {
+    assertValidPattern(pattern);
+    // shortcut: comments match nothing.
+    if (!options.nocomment && pattern.charAt(0) === '#') {
+        return false;
+    }
+    return new Minimatch(pattern, options).match(p);
+};
+// Optimized checking for the most common glob patterns.
+const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
+const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
+const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
+const starDotExtTestNocase = (ext) => {
+    ext = ext.toLowerCase();
+    return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
+};
+const starDotExtTestNocaseDot = (ext) => {
+    ext = ext.toLowerCase();
+    return (f) => f.toLowerCase().endsWith(ext);
+};
+const starDotStarRE = /^\*+\.\*+$/;
+const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
+const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
+const dotStarRE = /^\.\*+$/;
+const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
+const starRE = /^\*+$/;
+const starTest = (f) => f.length !== 0 && !f.startsWith('.');
+const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
+const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
+const qmarksTestNocase = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExt([$0]);
+    if (!ext)
+        return noext;
+    ext = ext.toLowerCase();
+    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
+};
+const qmarksTestNocaseDot = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExtDot([$0]);
+    if (!ext)
+        return noext;
+    ext = ext.toLowerCase();
+    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
+};
+const qmarksTestDot = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExtDot([$0]);
+    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+};
+const qmarksTest = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExt([$0]);
+    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+};
+const qmarksTestNoExt = ([$0]) => {
+    const len = $0.length;
+    return (f) => f.length === len && !f.startsWith('.');
+};
+const qmarksTestNoExtDot = ([$0]) => {
+    const len = $0.length;
+    return (f) => f.length === len && f !== '.' && f !== '..';
+};
+/* c8 ignore start */
+const defaultPlatform = (typeof process === 'object' && process
+    ? (typeof process.env === 'object' &&
+        process.env &&
+        process.env.__MINIMATCH_TESTING_PLATFORM__) ||
+        process.platform
+    : 'posix');
+const path = {
+    win32: { sep: '\\' },
+    posix: { sep: '/' },
+};
+/* c8 ignore stop */
+export const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
+minimatch.sep = sep;
+export const GLOBSTAR = Symbol('globstar **');
+minimatch.GLOBSTAR = GLOBSTAR;
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+const qmark = '[^/]';
+// * => any number of characters
+const star = qmark + '*?';
+// ** when dots are allowed.  Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
+export const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
+minimatch.filter = filter;
+const ext = (a, b = {}) => Object.assign({}, a, b);
+export const defaults = (def) => {
+    if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+        return minimatch;
+    }
+    const orig = minimatch;
+    const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
+    return Object.assign(m, {
+        Minimatch: class Minimatch extends orig.Minimatch {
+            constructor(pattern, options = {}) {
+                super(pattern, ext(def, options));
+            }
+            static defaults(options) {
+                return orig.defaults(ext(def, options)).Minimatch;
+            }
+        },
+        AST: class AST extends orig.AST {
+            /* c8 ignore start */
+            constructor(type, parent, options = {}) {
+                super(type, parent, ext(def, options));
+            }
+            /* c8 ignore stop */
+            static fromGlob(pattern, options = {}) {
+                return orig.AST.fromGlob(pattern, ext(def, options));
+            }
+        },
+        unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
+        escape: (s, options = {}) => orig.escape(s, ext(def, options)),
+        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
+        defaults: (options) => orig.defaults(ext(def, options)),
+        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
+        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
+        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
+        sep: orig.sep,
+        GLOBSTAR: GLOBSTAR,
+    });
+};
+minimatch.defaults = defaults;
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+export const braceExpand = (pattern, options = {}) => {
+    assertValidPattern(pattern);
+    // Thanks to Yeting Li  for
+    // improving this regexp to avoid a ReDOS vulnerability.
+    if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+        // shortcut. no need to expand.
+        return [pattern];
+    }
+    return expand(pattern);
+};
+minimatch.braceExpand = braceExpand;
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion.  Otherwise, any series
+// of * is equivalent to a single *.  Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+export const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
+minimatch.makeRe = makeRe;
+export const match = (list, pattern, options = {}) => {
+    const mm = new Minimatch(pattern, options);
+    list = list.filter(f => mm.match(f));
+    if (mm.options.nonull && !list.length) {
+        list.push(pattern);
+    }
+    return list;
+};
+minimatch.match = match;
+// replace stuff like \* with *
+const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
+const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+export class Minimatch {
+    options;
+    set;
+    pattern;
+    windowsPathsNoEscape;
+    nonegate;
+    negate;
+    comment;
+    empty;
+    preserveMultipleSlashes;
+    partial;
+    globSet;
+    globParts;
+    nocase;
+    isWindows;
+    platform;
+    windowsNoMagicRoot;
+    regexp;
+    constructor(pattern, options = {}) {
+        assertValidPattern(pattern);
+        options = options || {};
+        this.options = options;
+        this.pattern = pattern;
+        this.platform = options.platform || defaultPlatform;
+        this.isWindows = this.platform === 'win32';
+        this.windowsPathsNoEscape =
+            !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
+        if (this.windowsPathsNoEscape) {
+            this.pattern = this.pattern.replace(/\\/g, '/');
+        }
+        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
+        this.regexp = null;
+        this.negate = false;
+        this.nonegate = !!options.nonegate;
+        this.comment = false;
+        this.empty = false;
+        this.partial = !!options.partial;
+        this.nocase = !!this.options.nocase;
+        this.windowsNoMagicRoot =
+            options.windowsNoMagicRoot !== undefined
+                ? options.windowsNoMagicRoot
+                : !!(this.isWindows && this.nocase);
+        this.globSet = [];
+        this.globParts = [];
+        this.set = [];
+        // make the set of regexps etc.
+        this.make();
+    }
+    hasMagic() {
+        if (this.options.magicalBraces && this.set.length > 1) {
+            return true;
+        }
+        for (const pattern of this.set) {
+            for (const part of pattern) {
+                if (typeof part !== 'string')
+                    return true;
+            }
+        }
+        return false;
+    }
+    debug(..._) { }
+    make() {
+        const pattern = this.pattern;
+        const options = this.options;
+        // empty patterns and comments match nothing.
+        if (!options.nocomment && pattern.charAt(0) === '#') {
+            this.comment = true;
+            return;
+        }
+        if (!pattern) {
+            this.empty = true;
+            return;
+        }
+        // step 1: figure out negation, etc.
+        this.parseNegate();
+        // step 2: expand braces
+        this.globSet = [...new Set(this.braceExpand())];
+        if (options.debug) {
+            this.debug = (...args) => console.error(...args);
+        }
+        this.debug(this.pattern, this.globSet);
+        // step 3: now we have a set, so turn each one into a series of
+        // path-portion matching patterns.
+        // These will be regexps, except in the case of "**", which is
+        // set to the GLOBSTAR object for globstar behavior,
+        // and will not contain any / characters
+        //
+        // First, we preprocess to make the glob pattern sets a bit simpler
+        // and deduped.  There are some perf-killing patterns that can cause
+        // problems with a glob walk, but we can simplify them down a bit.
+        const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
+        this.globParts = this.preprocess(rawGlobParts);
+        this.debug(this.pattern, this.globParts);
+        // glob --> regexps
+        let set = this.globParts.map((s, _, __) => {
+            if (this.isWindows && this.windowsNoMagicRoot) {
+                // check if it's a drive or unc path.
+                const isUNC = s[0] === '' &&
+                    s[1] === '' &&
+                    (s[2] === '?' || !globMagic.test(s[2])) &&
+                    !globMagic.test(s[3]);
+                const isDrive = /^[a-z]:/i.test(s[0]);
+                if (isUNC) {
+                    return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
+                }
+                else if (isDrive) {
+                    return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
+                }
+            }
+            return s.map(ss => this.parse(ss));
+        });
+        this.debug(this.pattern, set);
+        // filter out everything that didn't compile properly.
+        this.set = set.filter(s => s.indexOf(false) === -1);
+        // do not treat the ? in UNC paths as magic
+        if (this.isWindows) {
+            for (let i = 0; i < this.set.length; i++) {
+                const p = this.set[i];
+                if (p[0] === '' &&
+                    p[1] === '' &&
+                    this.globParts[i][2] === '?' &&
+                    typeof p[3] === 'string' &&
+                    /^[a-z]:$/i.test(p[3])) {
+                    p[2] = '?';
+                }
+            }
+        }
+        this.debug(this.pattern, this.set);
+    }
+    // various transforms to equivalent pattern sets that are
+    // faster to process in a filesystem walk.  The goal is to
+    // eliminate what we can, and push all ** patterns as far
+    // to the right as possible, even if it increases the number
+    // of patterns that we have to process.
+    preprocess(globParts) {
+        // if we're not in globstar mode, then turn all ** into *
+        if (this.options.noglobstar) {
+            for (let i = 0; i < globParts.length; i++) {
+                for (let j = 0; j < globParts[i].length; j++) {
+                    if (globParts[i][j] === '**') {
+                        globParts[i][j] = '*';
+                    }
+                }
+            }
+        }
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+            // aggressive optimization for the purpose of fs walking
+            globParts = this.firstPhasePreProcess(globParts);
+            globParts = this.secondPhasePreProcess(globParts);
+        }
+        else if (optimizationLevel >= 1) {
+            // just basic optimizations to remove some .. parts
+            globParts = this.levelOneOptimize(globParts);
+        }
+        else {
+            // just collapse multiple ** portions into one
+            globParts = this.adjascentGlobstarOptimize(globParts);
+        }
+        return globParts;
+    }
+    // just get rid of adjascent ** portions
+    adjascentGlobstarOptimize(globParts) {
+        return globParts.map(parts => {
+            let gs = -1;
+            while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
+                let i = gs;
+                while (parts[i + 1] === '**') {
+                    i++;
+                }
+                if (i !== gs) {
+                    parts.splice(gs, i - gs);
+                }
+            }
+            return parts;
+        });
+    }
+    // get rid of adjascent ** and resolve .. portions
+    levelOneOptimize(globParts) {
+        return globParts.map(parts => {
+            parts = parts.reduce((set, part) => {
+                const prev = set[set.length - 1];
+                if (part === '**' && prev === '**') {
+                    return set;
+                }
+                if (part === '..') {
+                    if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
+                        set.pop();
+                        return set;
+                    }
+                }
+                set.push(part);
+                return set;
+            }, []);
+            return parts.length === 0 ? [''] : parts;
+        });
+    }
+    levelTwoFileOptimize(parts) {
+        if (!Array.isArray(parts)) {
+            parts = this.slashSplit(parts);
+        }
+        let didSomething = false;
+        do {
+            didSomething = false;
+            // 
// -> 
/
+            if (!this.preserveMultipleSlashes) {
+                for (let i = 1; i < parts.length - 1; i++) {
+                    const p = parts[i];
+                    // don't squeeze out UNC patterns
+                    if (i === 1 && p === '' && parts[0] === '')
+                        continue;
+                    if (p === '.' || p === '') {
+                        didSomething = true;
+                        parts.splice(i, 1);
+                        i--;
+                    }
+                }
+                if (parts[0] === '.' &&
+                    parts.length === 2 &&
+                    (parts[1] === '.' || parts[1] === '')) {
+                    didSomething = true;
+                    parts.pop();
+                }
+            }
+            // 
/

/../ ->

/
+            let dd = 0;
+            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
+                const p = parts[dd - 1];
+                if (p && p !== '.' && p !== '..' && p !== '**') {
+                    didSomething = true;
+                    parts.splice(dd - 1, 2);
+                    dd -= 2;
+                }
+            }
+        } while (didSomething);
+        return parts.length === 0 ? [''] : parts;
+    }
+    // First phase: single-pattern processing
+    // 
 is 1 or more portions
+    //  is 1 or more portions
+    // 

is any portion other than ., .., '', or ** + // is . or '' + // + // **/.. is *brutal* for filesystem walking performance, because + // it effectively resets the recursive walk each time it occurs, + // and ** cannot be reduced out by a .. pattern part like a regexp + // or most strings (other than .., ., and '') can be. + // + //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + //

// -> 
/
+    // 
/

/../ ->

/
+    // **/**/ -> **/
+    //
+    // **/*/ -> */**/ <== not valid because ** doesn't follow
+    // this WOULD be allowed if ** did follow symlinks, or * didn't
+    firstPhasePreProcess(globParts) {
+        let didSomething = false;
+        do {
+            didSomething = false;
+            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + for (let parts of globParts) { + let gs = -1; + while (-1 !== (gs = parts.indexOf('**', gs + 1))) { + let gss = gs; + while (parts[gss + 1] === '**') { + //

/**/**/ -> 
/**/
+                        gss++;
+                    }
+                    // eg, if gs is 2 and gss is 4, that means we have 3 **
+                    // parts, and can remove 2 of them.
+                    if (gss > gs) {
+                        parts.splice(gs + 1, gss - gs);
+                    }
+                    let next = parts[gs + 1];
+                    const p = parts[gs + 2];
+                    const p2 = parts[gs + 3];
+                    if (next !== '..')
+                        continue;
+                    if (!p ||
+                        p === '.' ||
+                        p === '..' ||
+                        !p2 ||
+                        p2 === '.' ||
+                        p2 === '..') {
+                        continue;
+                    }
+                    didSomething = true;
+                    // edit parts in place, and push the new one
+                    parts.splice(gs, 1);
+                    const other = parts.slice(0);
+                    other[gs] = '**';
+                    globParts.push(other);
+                    gs--;
+                }
+                // 
// -> 
/
+                if (!this.preserveMultipleSlashes) {
+                    for (let i = 1; i < parts.length - 1; i++) {
+                        const p = parts[i];
+                        // don't squeeze out UNC patterns
+                        if (i === 1 && p === '' && parts[0] === '')
+                            continue;
+                        if (p === '.' || p === '') {
+                            didSomething = true;
+                            parts.splice(i, 1);
+                            i--;
+                        }
+                    }
+                    if (parts[0] === '.' &&
+                        parts.length === 2 &&
+                        (parts[1] === '.' || parts[1] === '')) {
+                        didSomething = true;
+                        parts.pop();
+                    }
+                }
+                // 
/

/../ ->

/
+                let dd = 0;
+                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
+                    const p = parts[dd - 1];
+                    if (p && p !== '.' && p !== '..' && p !== '**') {
+                        didSomething = true;
+                        const needDot = dd === 1 && parts[dd + 1] === '**';
+                        const splin = needDot ? ['.'] : [];
+                        parts.splice(dd - 1, 2, ...splin);
+                        if (parts.length === 0)
+                            parts.push('');
+                        dd -= 2;
+                    }
+                }
+            }
+        } while (didSomething);
+        return globParts;
+    }
+    // second phase: multi-pattern dedupes
+    // {
/*/,
/

/} ->

/*/
+    // {
/,
/} -> 
/
+    // {
/**/,
/} -> 
/**/
+    //
+    // {
/**/,
/**/

/} ->

/**/
+    // ^-- not valid because ** doens't follow symlinks
+    secondPhasePreProcess(globParts) {
+        for (let i = 0; i < globParts.length - 1; i++) {
+            for (let j = i + 1; j < globParts.length; j++) {
+                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
+                if (matched) {
+                    globParts[i] = [];
+                    globParts[j] = matched;
+                    break;
+                }
+            }
+        }
+        return globParts.filter(gs => gs.length);
+    }
+    partsMatch(a, b, emptyGSMatch = false) {
+        let ai = 0;
+        let bi = 0;
+        let result = [];
+        let which = '';
+        while (ai < a.length && bi < b.length) {
+            if (a[ai] === b[bi]) {
+                result.push(which === 'b' ? b[bi] : a[ai]);
+                ai++;
+                bi++;
+            }
+            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
+                result.push(a[ai]);
+                ai++;
+            }
+            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
+                result.push(b[bi]);
+                bi++;
+            }
+            else if (a[ai] === '*' &&
+                b[bi] &&
+                (this.options.dot || !b[bi].startsWith('.')) &&
+                b[bi] !== '**') {
+                if (which === 'b')
+                    return false;
+                which = 'a';
+                result.push(a[ai]);
+                ai++;
+                bi++;
+            }
+            else if (b[bi] === '*' &&
+                a[ai] &&
+                (this.options.dot || !a[ai].startsWith('.')) &&
+                a[ai] !== '**') {
+                if (which === 'a')
+                    return false;
+                which = 'b';
+                result.push(b[bi]);
+                ai++;
+                bi++;
+            }
+            else {
+                return false;
+            }
+        }
+        // if we fall out of the loop, it means they two are identical
+        // as long as their lengths match
+        return a.length === b.length && result;
+    }
+    parseNegate() {
+        if (this.nonegate)
+            return;
+        const pattern = this.pattern;
+        let negate = false;
+        let negateOffset = 0;
+        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
+            negate = !negate;
+            negateOffset++;
+        }
+        if (negateOffset)
+            this.pattern = pattern.slice(negateOffset);
+        this.negate = negate;
+    }
+    // set partial to true to test if, for example,
+    // "/a/b" matches the start of "/*/b/*/d"
+    // Partial means, if you run out of file before you run
+    // out of pattern, then that's fine, as long as all
+    // the parts match.
+    matchOne(file, pattern, partial = false) {
+        const options = this.options;
+        // UNC paths like //?/X:/... can match X:/... and vice versa
+        // Drive letters in absolute drive or unc paths are always compared
+        // case-insensitively.
+        if (this.isWindows) {
+            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
+            const fileUNC = !fileDrive &&
+                file[0] === '' &&
+                file[1] === '' &&
+                file[2] === '?' &&
+                /^[a-z]:$/i.test(file[3]);
+            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
+            const patternUNC = !patternDrive &&
+                pattern[0] === '' &&
+                pattern[1] === '' &&
+                pattern[2] === '?' &&
+                typeof pattern[3] === 'string' &&
+                /^[a-z]:$/i.test(pattern[3]);
+            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
+            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
+            if (typeof fdi === 'number' && typeof pdi === 'number') {
+                const [fd, pd] = [file[fdi], pattern[pdi]];
+                if (fd.toLowerCase() === pd.toLowerCase()) {
+                    pattern[pdi] = fd;
+                    if (pdi > fdi) {
+                        pattern = pattern.slice(pdi);
+                    }
+                    else if (fdi > pdi) {
+                        file = file.slice(fdi);
+                    }
+                }
+            }
+        }
+        // resolve and reduce . and .. portions in the file as well.
+        // dont' need to do the second phase, because it's only one string[]
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+            file = this.levelTwoFileOptimize(file);
+        }
+        this.debug('matchOne', this, { file, pattern });
+        this.debug('matchOne', file.length, pattern.length);
+        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
+            this.debug('matchOne loop');
+            var p = pattern[pi];
+            var f = file[fi];
+            this.debug(pattern, p, f);
+            // should be impossible.
+            // some invalid regexp stuff in the set.
+            /* c8 ignore start */
+            if (p === false) {
+                return false;
+            }
+            /* c8 ignore stop */
+            if (p === GLOBSTAR) {
+                this.debug('GLOBSTAR', [pattern, p, f]);
+                // "**"
+                // a/**/b/**/c would match the following:
+                // a/b/x/y/z/c
+                // a/x/y/z/b/c
+                // a/b/x/b/x/c
+                // a/b/c
+                // To do this, take the rest of the pattern after
+                // the **, and see if it would match the file remainder.
+                // If so, return success.
+                // If not, the ** "swallows" a segment, and try again.
+                // This is recursively awful.
+                //
+                // a/**/b/**/c matching a/b/x/y/z/c
+                // - a matches a
+                // - doublestar
+                //   - matchOne(b/x/y/z/c, b/**/c)
+                //     - b matches b
+                //     - doublestar
+                //       - matchOne(x/y/z/c, c) -> no
+                //       - matchOne(y/z/c, c) -> no
+                //       - matchOne(z/c, c) -> no
+                //       - matchOne(c, c) yes, hit
+                var fr = fi;
+                var pr = pi + 1;
+                if (pr === pl) {
+                    this.debug('** at the end');
+                    // a ** at the end will just swallow the rest.
+                    // We have found a match.
+                    // however, it will not swallow /.x, unless
+                    // options.dot is set.
+                    // . and .. are *never* matched by **, for explosively
+                    // exponential reasons.
+                    for (; fi < fl; fi++) {
+                        if (file[fi] === '.' ||
+                            file[fi] === '..' ||
+                            (!options.dot && file[fi].charAt(0) === '.'))
+                            return false;
+                    }
+                    return true;
+                }
+                // ok, let's see if we can swallow whatever we can.
+                while (fr < fl) {
+                    var swallowee = file[fr];
+                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
+                    // XXX remove this slice.  Just pass the start index.
+                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+                        this.debug('globstar found match!', fr, fl, swallowee);
+                        // found a match.
+                        return true;
+                    }
+                    else {
+                        // can't swallow "." or ".." ever.
+                        // can only swallow ".foo" when explicitly asked.
+                        if (swallowee === '.' ||
+                            swallowee === '..' ||
+                            (!options.dot && swallowee.charAt(0) === '.')) {
+                            this.debug('dot detected!', file, fr, pattern, pr);
+                            break;
+                        }
+                        // ** swallows a segment, and continue.
+                        this.debug('globstar swallow a segment, and continue');
+                        fr++;
+                    }
+                }
+                // no match was found.
+                // However, in partial mode, we can't say this is necessarily over.
+                /* c8 ignore start */
+                if (partial) {
+                    // ran out of file
+                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
+                    if (fr === fl) {
+                        return true;
+                    }
+                }
+                /* c8 ignore stop */
+                return false;
+            }
+            // something other than **
+            // non-magic patterns just have to match exactly
+            // patterns with magic have been turned into regexps.
+            let hit;
+            if (typeof p === 'string') {
+                hit = f === p;
+                this.debug('string match', p, f, hit);
+            }
+            else {
+                hit = p.test(f);
+                this.debug('pattern match', p, f, hit);
+            }
+            if (!hit)
+                return false;
+        }
+        // Note: ending in / means that we'll get a final ""
+        // at the end of the pattern.  This can only match a
+        // corresponding "" at the end of the file.
+        // If the file ends in /, then it can only match a
+        // a pattern that ends in /, unless the pattern just
+        // doesn't have any more for it. But, a/b/ should *not*
+        // match "a/b/*", even though "" matches against the
+        // [^/]*? pattern, except in partial mode, where it might
+        // simply not be reached yet.
+        // However, a/b/ should still satisfy a/*
+        // now either we fell off the end of the pattern, or we're done.
+        if (fi === fl && pi === pl) {
+            // ran out of pattern and filename at the same time.
+            // an exact hit!
+            return true;
+        }
+        else if (fi === fl) {
+            // ran out of file, but still had pattern left.
+            // this is ok if we're doing the match as part of
+            // a glob fs traversal.
+            return partial;
+        }
+        else if (pi === pl) {
+            // ran out of pattern, still have file left.
+            // this is only acceptable if we're on the very last
+            // empty segment of a file with a trailing slash.
+            // a/* should match a/b/
+            return fi === fl - 1 && file[fi] === '';
+            /* c8 ignore start */
+        }
+        else {
+            // should be unreachable.
+            throw new Error('wtf?');
+        }
+        /* c8 ignore stop */
+    }
+    braceExpand() {
+        return braceExpand(this.pattern, this.options);
+    }
+    parse(pattern) {
+        assertValidPattern(pattern);
+        const options = this.options;
+        // shortcuts
+        if (pattern === '**')
+            return GLOBSTAR;
+        if (pattern === '')
+            return '';
+        // far and away, the most common glob pattern parts are
+        // *, *.*, and *.  Add a fast check method for those.
+        let m;
+        let fastTest = null;
+        if ((m = pattern.match(starRE))) {
+            fastTest = options.dot ? starTestDot : starTest;
+        }
+        else if ((m = pattern.match(starDotExtRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? starDotExtTestNocaseDot
+                    : starDotExtTestNocase
+                : options.dot
+                    ? starDotExtTestDot
+                    : starDotExtTest)(m[1]);
+        }
+        else if ((m = pattern.match(qmarksRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? qmarksTestNocaseDot
+                    : qmarksTestNocase
+                : options.dot
+                    ? qmarksTestDot
+                    : qmarksTest)(m);
+        }
+        else if ((m = pattern.match(starDotStarRE))) {
+            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
+        }
+        else if ((m = pattern.match(dotStarRE))) {
+            fastTest = dotStarTest;
+        }
+        const re = AST.fromGlob(pattern, this.options).toMMPattern();
+        if (fastTest && typeof re === 'object') {
+            // Avoids overriding in frozen environments
+            Reflect.defineProperty(re, 'test', { value: fastTest });
+        }
+        return re;
+    }
+    makeRe() {
+        if (this.regexp || this.regexp === false)
+            return this.regexp;
+        // at this point, this.set is a 2d array of partial
+        // pattern strings, or "**".
+        //
+        // It's better to use .match().  This function shouldn't
+        // be used, really, but it's pretty convenient sometimes,
+        // when you just want to work with a regex.
+        const set = this.set;
+        if (!set.length) {
+            this.regexp = false;
+            return this.regexp;
+        }
+        const options = this.options;
+        const twoStar = options.noglobstar
+            ? star
+            : options.dot
+                ? twoStarDot
+                : twoStarNoDot;
+        const flags = new Set(options.nocase ? ['i'] : []);
+        // regexpify non-globstar patterns
+        // if ** is only item, then we just do one twoStar
+        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
+        // if ** is last, append (\/twoStar|) to previous
+        // if ** is in the middle, append (\/|\/twoStar\/) to previous
+        // then filter out GLOBSTAR symbols
+        let re = set
+            .map(pattern => {
+            const pp = pattern.map(p => {
+                if (p instanceof RegExp) {
+                    for (const f of p.flags.split(''))
+                        flags.add(f);
+                }
+                return typeof p === 'string'
+                    ? regExpEscape(p)
+                    : p === GLOBSTAR
+                        ? GLOBSTAR
+                        : p._src;
+            });
+            pp.forEach((p, i) => {
+                const next = pp[i + 1];
+                const prev = pp[i - 1];
+                if (p !== GLOBSTAR || prev === GLOBSTAR) {
+                    return;
+                }
+                if (prev === undefined) {
+                    if (next !== undefined && next !== GLOBSTAR) {
+                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
+                    }
+                    else {
+                        pp[i] = twoStar;
+                    }
+                }
+                else if (next === undefined) {
+                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
+                }
+                else if (next !== GLOBSTAR) {
+                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
+                    pp[i + 1] = GLOBSTAR;
+                }
+            });
+            return pp.filter(p => p !== GLOBSTAR).join('/');
+        })
+            .join('|');
+        // need to wrap in parens if we had more than one thing with |,
+        // otherwise only the first will be anchored to ^ and the last to $
+        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
+        // must match entire pattern
+        // ending in a * or ** will make it less strict.
+        re = '^' + open + re + close + '$';
+        // can match anything, as long as it's not this.
+        if (this.negate)
+            re = '^(?!' + re + ').+$';
+        try {
+            this.regexp = new RegExp(re, [...flags].join(''));
+            /* c8 ignore start */
+        }
+        catch (ex) {
+            // should be impossible
+            this.regexp = false;
+        }
+        /* c8 ignore stop */
+        return this.regexp;
+    }
+    slashSplit(p) {
+        // if p starts with // on windows, we preserve that
+        // so that UNC paths aren't broken.  Otherwise, any number of
+        // / characters are coalesced into one, unless
+        // preserveMultipleSlashes is set to true.
+        if (this.preserveMultipleSlashes) {
+            return p.split('/');
+        }
+        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
+            // add an extra '' for the one we lose
+            return ['', ...p.split(/\/+/)];
+        }
+        else {
+            return p.split(/\/+/);
+        }
+    }
+    match(f, partial = this.partial) {
+        this.debug('match', f, this.pattern);
+        // short-circuit in the case of busted things.
+        // comments, etc.
+        if (this.comment) {
+            return false;
+        }
+        if (this.empty) {
+            return f === '';
+        }
+        if (f === '/' && partial) {
+            return true;
+        }
+        const options = this.options;
+        // windows: need to use /, not \
+        if (this.isWindows) {
+            f = f.split('\\').join('/');
+        }
+        // treat the test path as a set of pathparts.
+        const ff = this.slashSplit(f);
+        this.debug(this.pattern, 'split', ff);
+        // just ONE of the pattern sets in this.set needs to match
+        // in order for it to be valid.  If negating, then just one
+        // match means that we have failed.
+        // Either way, return on the first hit.
+        const set = this.set;
+        this.debug(this.pattern, 'set', set);
+        // Find the basename of the path by looking for the last non-empty segment
+        let filename = ff[ff.length - 1];
+        if (!filename) {
+            for (let i = ff.length - 2; !filename && i >= 0; i--) {
+                filename = ff[i];
+            }
+        }
+        for (let i = 0; i < set.length; i++) {
+            const pattern = set[i];
+            let file = ff;
+            if (options.matchBase && pattern.length === 1) {
+                file = [filename];
+            }
+            const hit = this.matchOne(file, pattern, partial);
+            if (hit) {
+                if (options.flipNegate) {
+                    return true;
+                }
+                return !this.negate;
+            }
+        }
+        // didn't get any hits.  this is success if it's a negative
+        // pattern, failure otherwise.
+        if (options.flipNegate) {
+            return false;
+        }
+        return this.negate;
+    }
+    static defaults(def) {
+        return minimatch.defaults(def).Minimatch;
+    }
+}
+/* c8 ignore start */
+export { AST } from './ast.js';
+export { escape } from './escape.js';
+export { unescape } from './unescape.js';
+/* c8 ignore stop */
+minimatch.AST = AST;
+minimatch.Minimatch = Minimatch;
+minimatch.escape = escape;
+minimatch.unescape = unescape;
+//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/index.js.map b/node_modules/minimatch/dist/esm/index.js.map
new file mode 100644
index 00000000..ff82a0d3
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/index.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,iBAAiB,CAAA;AACpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAC9D,OAAO,EAAE,GAAG,EAAe,MAAM,UAAU,CAAA;AAC3C,OAAO,E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A;IACpB,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,GAAqB;QACnC,OAAO,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;CACF;AACD,qBAAqB;AACrB,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AACxC,oBAAoB;AACpB,SAAS,CAAC,GAAG,GAAG,GAAG,CAAA;AACnB,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;AAC/B,SAAS,CAAC,MAAM,GAAG,MAAM,CAAA;AACzB,SAAS,CAAC,QAAQ,GAAG,QAAQ,CAAA","sourcesContent":["import expand from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\ntype Platform =\n  | 'aix'\n  | 'android'\n  | 'darwin'\n  | 'freebsd'\n  | 'haiku'\n  | 'linux'\n  | 'openbsd'\n  | 'sunos'\n  | 'win32'\n  | 'cygwin'\n  | 'netbsd'\n\nexport interface MinimatchOptions {\n  nobrace?: boolean\n  nocomment?: boolean\n  nonegate?: boolean\n  debug?: boolean\n  noglobstar?: boolean\n  noext?: boolean\n  nonull?: boolean\n  windowsPathsNoEscape?: boolean\n  allowWindowsEscape?: boolean\n  partial?: boolean\n  dot?: boolean\n  nocase?: boolean\n  nocaseMagicOnly?: boolean\n  magicalBraces?: boolean\n  matchBase?: boolean\n  flipNegate?: boolean\n  preserveMultipleSlashes?: boolean\n  optimizationLevel?: number\n  platform?: Platform\n  windowsNoMagicRoot?: boolean\n}\n\nexport const minimatch = (\n  p: string,\n  pattern: string,\n  options: MinimatchOptions = {}\n) => {\n  assertValidPattern(pattern)\n\n  // shortcut: comments match nothing.\n  if (!options.nocomment && pattern.charAt(0) === '#') {\n    return false\n  }\n\n  return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n  !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) => !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n  f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) => f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) => f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n  typeof process === 'object' && process\n    ? (typeof process.env === 'object' &&\n        process.env &&\n        process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n      process.platform\n    : 'posix'\n) as Platform\ntype Sep = '\\\\' | '/'\nconst path: { [k: string]: { sep: Sep } } = {\n  win32: { sep: '\\\\' },\n  posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed.  Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n  (pattern: string, options: MinimatchOptions = {}) =>\n  (p: string) =>\n    minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n  Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n  if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n    return minimatch\n  }\n\n  const orig = minimatch\n\n  const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n    orig(p, pattern, ext(def, options))\n\n  return Object.assign(m, {\n    Minimatch: class Minimatch extends orig.Minimatch {\n      constructor(pattern: string, options: MinimatchOptions = {}) {\n        super(pattern, ext(def, options))\n      }\n      static defaults(options: MinimatchOptions) {\n        return orig.defaults(ext(def, options)).Minimatch\n      }\n    },\n\n    AST: class AST extends orig.AST {\n      /* c8 ignore start */\n      constructor(\n        type: ExtglobType | null,\n        parent?: AST,\n        options: MinimatchOptions = {}\n      ) {\n        super(type, parent, ext(def, options))\n      }\n      /* c8 ignore stop */\n\n      static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n        return orig.AST.fromGlob(pattern, ext(def, options))\n      }\n    },\n\n    unescape: (\n      s: string,\n      options: Pick = {}\n    ) => orig.unescape(s, ext(def, options)),\n\n    escape: (\n      s: string,\n      options: Pick = {}\n    ) => orig.escape(s, ext(def, options)),\n\n    filter: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.filter(pattern, ext(def, options)),\n\n    defaults: (options: MinimatchOptions) => orig.defaults(ext(def, options)),\n\n    makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.makeRe(pattern, ext(def, options)),\n\n    braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.braceExpand(pattern, ext(def, options)),\n\n    match: (list: string[], pattern: string, options: MinimatchOptions = {}) =>\n      orig.match(list, pattern, ext(def, options)),\n\n    sep: orig.sep,\n    GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n  })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n  pattern: string,\n  options: MinimatchOptions = {}\n) => {\n  assertValidPattern(pattern)\n\n  // Thanks to Yeting Li  for\n  // improving this regexp to avoid a ReDOS vulnerability.\n  if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n    // shortcut. no need to expand.\n    return [pattern]\n  }\n\n  return expand(pattern)\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion.  Otherwise, any series\n// of * is equivalent to a single *.  Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n  new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n  list: string[],\n  pattern: string,\n  options: MinimatchOptions = {}\n) => {\n  const mm = new Minimatch(pattern, options)\n  list = list.filter(f => mm.match(f))\n  if (mm.options.nonull && !list.length) {\n    list.push(pattern)\n  }\n  return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n  _src?: string\n  _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n  options: MinimatchOptions\n  set: ParseReturnFiltered[][]\n  pattern: string\n\n  windowsPathsNoEscape: boolean\n  nonegate: boolean\n  negate: boolean\n  comment: boolean\n  empty: boolean\n  preserveMultipleSlashes: boolean\n  partial: boolean\n  globSet: string[]\n  globParts: string[][]\n  nocase: boolean\n\n  isWindows: boolean\n  platform: Platform\n  windowsNoMagicRoot: boolean\n\n  regexp: false | null | MMRegExp\n  constructor(pattern: string, options: MinimatchOptions = {}) {\n    assertValidPattern(pattern)\n\n    options = options || {}\n    this.options = options\n    this.pattern = pattern\n    this.platform = options.platform || defaultPlatform\n    this.isWindows = this.platform === 'win32'\n    this.windowsPathsNoEscape =\n      !!options.windowsPathsNoEscape || options.allowWindowsEscape === false\n    if (this.windowsPathsNoEscape) {\n      this.pattern = this.pattern.replace(/\\\\/g, '/')\n    }\n    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n    this.regexp = null\n    this.negate = false\n    this.nonegate = !!options.nonegate\n    this.comment = false\n    this.empty = false\n    this.partial = !!options.partial\n    this.nocase = !!this.options.nocase\n    this.windowsNoMagicRoot =\n      options.windowsNoMagicRoot !== undefined\n        ? options.windowsNoMagicRoot\n        : !!(this.isWindows && this.nocase)\n\n    this.globSet = []\n    this.globParts = []\n    this.set = []\n\n    // make the set of regexps etc.\n    this.make()\n  }\n\n  hasMagic(): boolean {\n    if (this.options.magicalBraces && this.set.length > 1) {\n      return true\n    }\n    for (const pattern of this.set) {\n      for (const part of pattern) {\n        if (typeof part !== 'string') return true\n      }\n    }\n    return false\n  }\n\n  debug(..._: any[]) {}\n\n  make() {\n    const pattern = this.pattern\n    const options = this.options\n\n    // empty patterns and comments match nothing.\n    if (!options.nocomment && pattern.charAt(0) === '#') {\n      this.comment = true\n      return\n    }\n\n    if (!pattern) {\n      this.empty = true\n      return\n    }\n\n    // step 1: figure out negation, etc.\n    this.parseNegate()\n\n    // step 2: expand braces\n    this.globSet = [...new Set(this.braceExpand())]\n\n    if (options.debug) {\n      this.debug = (...args: any[]) => console.error(...args)\n    }\n\n    this.debug(this.pattern, this.globSet)\n\n    // step 3: now we have a set, so turn each one into a series of\n    // path-portion matching patterns.\n    // These will be regexps, except in the case of \"**\", which is\n    // set to the GLOBSTAR object for globstar behavior,\n    // and will not contain any / characters\n    //\n    // First, we preprocess to make the glob pattern sets a bit simpler\n    // and deduped.  There are some perf-killing patterns that can cause\n    // problems with a glob walk, but we can simplify them down a bit.\n    const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n    this.globParts = this.preprocess(rawGlobParts)\n    this.debug(this.pattern, this.globParts)\n\n    // glob --> regexps\n    let set = this.globParts.map((s, _, __) => {\n      if (this.isWindows && this.windowsNoMagicRoot) {\n        // check if it's a drive or unc path.\n        const isUNC =\n          s[0] === '' &&\n          s[1] === '' &&\n          (s[2] === '?' || !globMagic.test(s[2])) &&\n          !globMagic.test(s[3])\n        const isDrive = /^[a-z]:/i.test(s[0])\n        if (isUNC) {\n          return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]\n        } else if (isDrive) {\n          return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n        }\n      }\n      return s.map(ss => this.parse(ss))\n    })\n\n    this.debug(this.pattern, set)\n\n    // filter out everything that didn't compile properly.\n    this.set = set.filter(\n      s => s.indexOf(false) === -1\n    ) as ParseReturnFiltered[][]\n\n    // do not treat the ? in UNC paths as magic\n    if (this.isWindows) {\n      for (let i = 0; i < this.set.length; i++) {\n        const p = this.set[i]\n        if (\n          p[0] === '' &&\n          p[1] === '' &&\n          this.globParts[i][2] === '?' &&\n          typeof p[3] === 'string' &&\n          /^[a-z]:$/i.test(p[3])\n        ) {\n          p[2] = '?'\n        }\n      }\n    }\n\n    this.debug(this.pattern, this.set)\n  }\n\n  // various transforms to equivalent pattern sets that are\n  // faster to process in a filesystem walk.  The goal is to\n  // eliminate what we can, and push all ** patterns as far\n  // to the right as possible, even if it increases the number\n  // of patterns that we have to process.\n  preprocess(globParts: string[][]) {\n    // if we're not in globstar mode, then turn all ** into *\n    if (this.options.noglobstar) {\n      for (let i = 0; i < globParts.length; i++) {\n        for (let j = 0; j < globParts[i].length; j++) {\n          if (globParts[i][j] === '**') {\n            globParts[i][j] = '*'\n          }\n        }\n      }\n    }\n\n    const { optimizationLevel = 1 } = this.options\n\n    if (optimizationLevel >= 2) {\n      // aggressive optimization for the purpose of fs walking\n      globParts = this.firstPhasePreProcess(globParts)\n      globParts = this.secondPhasePreProcess(globParts)\n    } else if (optimizationLevel >= 1) {\n      // just basic optimizations to remove some .. parts\n      globParts = this.levelOneOptimize(globParts)\n    } else {\n      // just collapse multiple ** portions into one\n      globParts = this.adjascentGlobstarOptimize(globParts)\n    }\n\n    return globParts\n  }\n\n  // just get rid of adjascent ** portions\n  adjascentGlobstarOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      let gs: number = -1\n      while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n        let i = gs\n        while (parts[i + 1] === '**') {\n          i++\n        }\n        if (i !== gs) {\n          parts.splice(gs, i - gs)\n        }\n      }\n      return parts\n    })\n  }\n\n  // get rid of adjascent ** and resolve .. portions\n  levelOneOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      parts = parts.reduce((set: string[], part) => {\n        const prev = set[set.length - 1]\n        if (part === '**' && prev === '**') {\n          return set\n        }\n        if (part === '..') {\n          if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n            set.pop()\n            return set\n          }\n        }\n        set.push(part)\n        return set\n      }, [])\n      return parts.length === 0 ? [''] : parts\n    })\n  }\n\n  levelTwoFileOptimize(parts: string | string[]) {\n    if (!Array.isArray(parts)) {\n      parts = this.slashSplit(parts)\n    }\n    let didSomething: boolean = false\n    do {\n      didSomething = false\n      // 
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      let dd: number = 0\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd -= 2\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        let dd: number = 0\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd -= 2\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/*/,
/

/} ->

/*/\n  // {
/,
/} -> 
/\n  // {
/**/,
/} -> 
/**/\n  //\n  // {
/**/,
/**/

/} ->

/**/\n  // ^-- not valid because ** doens't follow symlinks\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    for (let i = 0; i < globParts.length - 1; i++) {\n      for (let j = i + 1; j < globParts.length; j++) {\n        const matched = this.partsMatch(\n          globParts[i],\n          globParts[j],\n          !this.preserveMultipleSlashes\n        )\n        if (matched) {\n          globParts[i] = []\n          globParts[j] = matched\n          break\n        }\n      }\n    }\n    return globParts.filter(gs => gs.length)\n  }\n\n  partsMatch(\n    a: string[],\n    b: string[],\n    emptyGSMatch: boolean = false\n  ): false | string[] {\n    let ai = 0\n    let bi = 0\n    let result: string[] = []\n    let which: string = ''\n    while (ai < a.length && bi < b.length) {\n      if (a[ai] === b[bi]) {\n        result.push(which === 'b' ? b[bi] : a[ai])\n        ai++\n        bi++\n      } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n        result.push(a[ai])\n        ai++\n      } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n        result.push(b[bi])\n        bi++\n      } else if (\n        a[ai] === '*' &&\n        b[bi] &&\n        (this.options.dot || !b[bi].startsWith('.')) &&\n        b[bi] !== '**'\n      ) {\n        if (which === 'b') return false\n        which = 'a'\n        result.push(a[ai])\n        ai++\n        bi++\n      } else if (\n        b[bi] === '*' &&\n        a[ai] &&\n        (this.options.dot || !a[ai].startsWith('.')) &&\n        a[ai] !== '**'\n      ) {\n        if (which === 'a') return false\n        which = 'b'\n        result.push(b[bi])\n        ai++\n        bi++\n      } else {\n        return false\n      }\n    }\n    // if we fall out of the loop, it means they two are identical\n    // as long as their lengths match\n    return a.length === b.length && result\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // set partial to true to test if, for example,\n  // \"/a/b\" matches the start of \"/*/b/*/d\"\n  // Partial means, if you run out of file before you run\n  // out of pattern, then that's fine, as long as all\n  // the parts match.\n  matchOne(file: string[], pattern: ParseReturn[], partial: boolean = false) {\n    const options = this.options\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa\n    // Drive letters in absolute drive or unc paths are always compared\n    // case-insensitively.\n    if (this.isWindows) {\n      const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined\n      const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [file[fdi], pattern[pdi] as string]\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          pattern[pdi] = fd\n          if (pdi > fdi) {\n            pattern = pattern.slice(pdi)\n          } else if (fdi > pdi) {\n            file = file.slice(fdi)\n          }\n        }\n      }\n    }\n\n    // resolve and reduce . and .. portions in the file as well.\n    // dont' need to do the second phase, because it's only one string[]\n    const { optimizationLevel = 1 } = this.options\n    if (optimizationLevel >= 2) {\n      file = this.levelTwoFileOptimize(file)\n    }\n\n    this.debug('matchOne', this, { file, pattern })\n    this.debug('matchOne', file.length, pattern.length)\n\n    for (\n      var fi = 0, pi = 0, fl = file.length, pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      this.debug('matchOne loop')\n      var p = pattern[pi]\n      var f = file[fi]\n\n      this.debug(pattern, p, f)\n\n      // should be impossible.\n      // some invalid regexp stuff in the set.\n      /* c8 ignore start */\n      if (p === false) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      if (p === GLOBSTAR) {\n        this.debug('GLOBSTAR', [pattern, p, f])\n\n        // \"**\"\n        // a/**/b/**/c would match the following:\n        // a/b/x/y/z/c\n        // a/x/y/z/b/c\n        // a/b/x/b/x/c\n        // a/b/c\n        // To do this, take the rest of the pattern after\n        // the **, and see if it would match the file remainder.\n        // If so, return success.\n        // If not, the ** \"swallows\" a segment, and try again.\n        // This is recursively awful.\n        //\n        // a/**/b/**/c matching a/b/x/y/z/c\n        // - a matches a\n        // - doublestar\n        //   - matchOne(b/x/y/z/c, b/**/c)\n        //     - b matches b\n        //     - doublestar\n        //       - matchOne(x/y/z/c, c) -> no\n        //       - matchOne(y/z/c, c) -> no\n        //       - matchOne(z/c, c) -> no\n        //       - matchOne(c, c) yes, hit\n        var fr = fi\n        var pr = pi + 1\n        if (pr === pl) {\n          this.debug('** at the end')\n          // a ** at the end will just swallow the rest.\n          // We have found a match.\n          // however, it will not swallow /.x, unless\n          // options.dot is set.\n          // . and .. are *never* matched by **, for explosively\n          // exponential reasons.\n          for (; fi < fl; fi++) {\n            if (\n              file[fi] === '.' ||\n              file[fi] === '..' ||\n              (!options.dot && file[fi].charAt(0) === '.')\n            )\n              return false\n          }\n          return true\n        }\n\n        // ok, let's see if we can swallow whatever we can.\n        while (fr < fl) {\n          var swallowee = file[fr]\n\n          this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n          // XXX remove this slice.  Just pass the start index.\n          if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n            this.debug('globstar found match!', fr, fl, swallowee)\n            // found a match.\n            return true\n          } else {\n            // can't swallow \".\" or \"..\" ever.\n            // can only swallow \".foo\" when explicitly asked.\n            if (\n              swallowee === '.' ||\n              swallowee === '..' ||\n              (!options.dot && swallowee.charAt(0) === '.')\n            ) {\n              this.debug('dot detected!', file, fr, pattern, pr)\n              break\n            }\n\n            // ** swallows a segment, and continue.\n            this.debug('globstar swallow a segment, and continue')\n            fr++\n          }\n        }\n\n        // no match was found.\n        // However, in partial mode, we can't say this is necessarily over.\n        /* c8 ignore start */\n        if (partial) {\n          // ran out of file\n          this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n          if (fr === fl) {\n            return true\n          }\n        }\n        /* c8 ignore stop */\n        return false\n      }\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into regexps.\n      let hit: boolean\n      if (typeof p === 'string') {\n        hit = f === p\n        this.debug('string match', p, f, hit)\n      } else {\n        hit = p.test(f)\n        this.debug('pattern match', p, f, hit)\n      }\n\n      if (!hit) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though \"\" matches against the\n    // [^/]*? pattern, except in partial mode, where it might\n    // simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    // far and away, the most common glob pattern parts are\n    // *, *.*, and *.  Add a fast check method for those.\n    let m: RegExpMatchArray | null\n    let fastTest: null | ((f: string) => boolean) = null\n    if ((m = pattern.match(starRE))) {\n      fastTest = options.dot ? starTestDot : starTest\n    } else if ((m = pattern.match(starDotExtRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? starDotExtTestNocaseDot\n            : starDotExtTestNocase\n          : options.dot\n          ? starDotExtTestDot\n          : starDotExtTest\n      )(m[1])\n    } else if ((m = pattern.match(qmarksRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? qmarksTestNocaseDot\n            : qmarksTestNocase\n          : options.dot\n          ? qmarksTestDot\n          : qmarksTest\n      )(m)\n    } else if ((m = pattern.match(starDotStarRE))) {\n      fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n    } else if ((m = pattern.match(dotStarRE))) {\n      fastTest = dotStarTest\n    }\n\n    const re = AST.fromGlob(pattern, this.options).toMMPattern()\n    if (fastTest && typeof re === 'object') {\n      // Avoids overriding in frozen environments\n      Reflect.defineProperty(re, 'test', { value: fastTest })\n    }\n    return re\n  }\n\n  makeRe() {\n    if (this.regexp || this.regexp === false) return this.regexp\n\n    // at this point, this.set is a 2d array of partial\n    // pattern strings, or \"**\".\n    //\n    // It's better to use .match().  This function shouldn't\n    // be used, really, but it's pretty convenient sometimes,\n    // when you just want to work with a regex.\n    const set = this.set\n\n    if (!set.length) {\n      this.regexp = false\n      return this.regexp\n    }\n    const options = this.options\n\n    const twoStar = options.noglobstar\n      ? star\n      : options.dot\n      ? twoStarDot\n      : twoStarNoDot\n    const flags = new Set(options.nocase ? ['i'] : [])\n\n    // regexpify non-globstar patterns\n    // if ** is only item, then we just do one twoStar\n    // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n    // if ** is last, append (\\/twoStar|) to previous\n    // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n    // then filter out GLOBSTAR symbols\n    let re = set\n      .map(pattern => {\n        const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n          if (p instanceof RegExp) {\n            for (const f of p.flags.split('')) flags.add(f)\n          }\n          return typeof p === 'string'\n            ? regExpEscape(p)\n            : p === GLOBSTAR\n            ? GLOBSTAR\n            : p._src\n        }) as (string | typeof GLOBSTAR)[]\n        pp.forEach((p, i) => {\n          const next = pp[i + 1]\n          const prev = pp[i - 1]\n          if (p !== GLOBSTAR || prev === GLOBSTAR) {\n            return\n          }\n          if (prev === undefined) {\n            if (next !== undefined && next !== GLOBSTAR) {\n              pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n            } else {\n              pp[i] = twoStar\n            }\n          } else if (next === undefined) {\n            pp[i - 1] = prev + '(?:\\\\/|' + twoStar + ')?'\n          } else if (next !== GLOBSTAR) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n            pp[i + 1] = GLOBSTAR\n          }\n        })\n        return pp.filter(p => p !== GLOBSTAR).join('/')\n      })\n      .join('|')\n\n    // need to wrap in parens if we had more than one thing with |,\n    // otherwise only the first will be anchored to ^ and the last to $\n    const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n    // must match entire pattern\n    // ending in a * or ** will make it less strict.\n    re = '^' + open + re + close + '$'\n\n    // can match anything, as long as it's not this.\n    if (this.negate) re = '^(?!' + re + ').+$'\n\n    try {\n      this.regexp = new RegExp(re, [...flags].join(''))\n      /* c8 ignore start */\n    } catch (ex) {\n      // should be impossible\n      this.regexp = false\n    }\n    /* c8 ignore stop */\n    return this.regexp\n  }\n\n  slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    this.debug('match', f, this.pattern)\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // windows: need to use /, not \\\n    if (this.isWindows) {\n      f = f.split('\\\\').join('/')\n    }\n\n    // treat the test path as a set of pathparts.\n    const ff = this.slashSplit(f)\n    this.debug(this.pattern, 'split', ff)\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n    this.debug(this.pattern, 'set', set)\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let i = 0; i < set.length; i++) {\n      const pattern = set[i]\n      let file = ff\n      if (options.matchBase && pattern.length === 1) {\n        file = [filename]\n      }\n      const hit = this.matchOne(file, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/package.json b/node_modules/minimatch/dist/esm/package.json
new file mode 100644
index 00000000..3dbc1ca5
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/package.json
@@ -0,0 +1,3 @@
+{
+  "type": "module"
+}
diff --git a/node_modules/minimatch/dist/esm/unescape.d.ts b/node_modules/minimatch/dist/esm/unescape.d.ts
new file mode 100644
index 00000000..23a7b387
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/unescape.d.ts
@@ -0,0 +1,17 @@
+import { MinimatchOptions } from './index.js';
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+export declare const unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+//# sourceMappingURL=unescape.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/unescape.d.ts.map b/node_modules/minimatch/dist/esm/unescape.d.ts.map
new file mode 100644
index 00000000..7ace0701
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/unescape.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,QAAQ,MAChB,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAKlD,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/unescape.js b/node_modules/minimatch/dist/esm/unescape.js
new file mode 100644
index 00000000..0faf9a2b
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/unescape.js
@@ -0,0 +1,20 @@
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+export const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
+    return windowsPathsNoEscape
+        ? s.replace(/\[([^\/\\])\]/g, '$1')
+        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
+};
+//# sourceMappingURL=unescape.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/unescape.js.map b/node_modules/minimatch/dist/esm/unescape.js.map
new file mode 100644
index 00000000..eb146c20
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/unescape.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC;QACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,2BAA2B,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC,CAAA;AAChF,CAAC,CAAA","sourcesContent":["import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes.  For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n  }: Pick = {}\n) => {\n  return windowsPathsNoEscape\n    ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n    : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json
new file mode 100644
index 00000000..01fc48ec
--- /dev/null
+++ b/node_modules/minimatch/package.json
@@ -0,0 +1,82 @@
+{
+  "author": "Isaac Z. Schlueter  (http://blog.izs.me)",
+  "name": "minimatch",
+  "description": "a glob matcher in javascript",
+  "version": "9.0.5",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/isaacs/minimatch.git"
+  },
+  "main": "./dist/commonjs/index.js",
+  "types": "./dist/commonjs/index.d.ts",
+  "exports": {
+    "./package.json": "./package.json",
+    ".": {
+      "import": {
+        "types": "./dist/esm/index.d.ts",
+        "default": "./dist/esm/index.js"
+      },
+      "require": {
+        "types": "./dist/commonjs/index.d.ts",
+        "default": "./dist/commonjs/index.js"
+      }
+    }
+  },
+  "files": [
+    "dist"
+  ],
+  "scripts": {
+    "preversion": "npm test",
+    "postversion": "npm publish",
+    "prepublishOnly": "git push origin --follow-tags",
+    "prepare": "tshy",
+    "pretest": "npm run prepare",
+    "presnap": "npm run prepare",
+    "test": "tap",
+    "snap": "tap",
+    "format": "prettier --write . --loglevel warn",
+    "benchmark": "node benchmark/index.js",
+    "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts"
+  },
+  "prettier": {
+    "semi": false,
+    "printWidth": 80,
+    "tabWidth": 2,
+    "useTabs": false,
+    "singleQuote": true,
+    "jsxSingleQuote": false,
+    "bracketSameLine": true,
+    "arrowParens": "avoid",
+    "endOfLine": "lf"
+  },
+  "engines": {
+    "node": ">=16 || 14 >=14.17"
+  },
+  "dependencies": {
+    "brace-expansion": "^2.0.1"
+  },
+  "devDependencies": {
+    "@types/brace-expansion": "^1.1.0",
+    "@types/node": "^18.15.11",
+    "@types/tap": "^15.0.8",
+    "eslint-config-prettier": "^8.6.0",
+    "mkdirp": "1",
+    "prettier": "^2.8.2",
+    "tap": "^18.7.2",
+    "ts-node": "^10.9.1",
+    "tshy": "^1.12.0",
+    "typedoc": "^0.23.21",
+    "typescript": "^4.9.3"
+  },
+  "funding": {
+    "url": "https://github.com/sponsors/isaacs"
+  },
+  "license": "ISC",
+  "tshy": {
+    "exports": {
+      "./package.json": "./package.json",
+      ".": "./src/index.ts"
+    }
+  },
+  "type": "module"
+}
diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js
new file mode 100644
index 00000000..ea734fb7
--- /dev/null
+++ b/node_modules/ms/index.js
@@ -0,0 +1,162 @@
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var w = d * 7;
+var y = d * 365.25;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ *  - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
+
+module.exports = function (val, options) {
+  options = options || {};
+  var type = typeof val;
+  if (type === 'string' && val.length > 0) {
+    return parse(val);
+  } else if (type === 'number' && isFinite(val)) {
+    return options.long ? fmtLong(val) : fmtShort(val);
+  }
+  throw new Error(
+    'val is not a non-empty string or a valid number. val=' +
+      JSON.stringify(val)
+  );
+};
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse(str) {
+  str = String(str);
+  if (str.length > 100) {
+    return;
+  }
+  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
+    str
+  );
+  if (!match) {
+    return;
+  }
+  var n = parseFloat(match[1]);
+  var type = (match[2] || 'ms').toLowerCase();
+  switch (type) {
+    case 'years':
+    case 'year':
+    case 'yrs':
+    case 'yr':
+    case 'y':
+      return n * y;
+    case 'weeks':
+    case 'week':
+    case 'w':
+      return n * w;
+    case 'days':
+    case 'day':
+    case 'd':
+      return n * d;
+    case 'hours':
+    case 'hour':
+    case 'hrs':
+    case 'hr':
+    case 'h':
+      return n * h;
+    case 'minutes':
+    case 'minute':
+    case 'mins':
+    case 'min':
+    case 'm':
+      return n * m;
+    case 'seconds':
+    case 'second':
+    case 'secs':
+    case 'sec':
+    case 's':
+      return n * s;
+    case 'milliseconds':
+    case 'millisecond':
+    case 'msecs':
+    case 'msec':
+    case 'ms':
+      return n;
+    default:
+      return undefined;
+  }
+}
+
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtShort(ms) {
+  var msAbs = Math.abs(ms);
+  if (msAbs >= d) {
+    return Math.round(ms / d) + 'd';
+  }
+  if (msAbs >= h) {
+    return Math.round(ms / h) + 'h';
+  }
+  if (msAbs >= m) {
+    return Math.round(ms / m) + 'm';
+  }
+  if (msAbs >= s) {
+    return Math.round(ms / s) + 's';
+  }
+  return ms + 'ms';
+}
+
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtLong(ms) {
+  var msAbs = Math.abs(ms);
+  if (msAbs >= d) {
+    return plural(ms, msAbs, d, 'day');
+  }
+  if (msAbs >= h) {
+    return plural(ms, msAbs, h, 'hour');
+  }
+  if (msAbs >= m) {
+    return plural(ms, msAbs, m, 'minute');
+  }
+  if (msAbs >= s) {
+    return plural(ms, msAbs, s, 'second');
+  }
+  return ms + ' ms';
+}
+
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, msAbs, n, name) {
+  var isPlural = msAbs >= n * 1.5;
+  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
+}
diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md
new file mode 100644
index 00000000..fa5d39b6
--- /dev/null
+++ b/node_modules/ms/license.md
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2020 Vercel, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json
new file mode 100644
index 00000000..49971890
--- /dev/null
+++ b/node_modules/ms/package.json
@@ -0,0 +1,38 @@
+{
+  "name": "ms",
+  "version": "2.1.3",
+  "description": "Tiny millisecond conversion utility",
+  "repository": "vercel/ms",
+  "main": "./index",
+  "files": [
+    "index.js"
+  ],
+  "scripts": {
+    "precommit": "lint-staged",
+    "lint": "eslint lib/* bin/*",
+    "test": "mocha tests.js"
+  },
+  "eslintConfig": {
+    "extends": "eslint:recommended",
+    "env": {
+      "node": true,
+      "es6": true
+    }
+  },
+  "lint-staged": {
+    "*.js": [
+      "npm run lint",
+      "prettier --single-quote --write",
+      "git add"
+    ]
+  },
+  "license": "MIT",
+  "devDependencies": {
+    "eslint": "4.18.2",
+    "expect.js": "0.3.1",
+    "husky": "0.14.3",
+    "lint-staged": "5.0.0",
+    "mocha": "4.0.1",
+    "prettier": "2.0.5"
+  }
+}
diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md
new file mode 100644
index 00000000..0fc1abb3
--- /dev/null
+++ b/node_modules/ms/readme.md
@@ -0,0 +1,59 @@
+# ms
+
+![CI](https://github.com/vercel/ms/workflows/CI/badge.svg)
+
+Use this package to easily convert various time formats to milliseconds.
+
+## Examples
+
+```js
+ms('2 days')  // 172800000
+ms('1d')      // 86400000
+ms('10h')     // 36000000
+ms('2.5 hrs') // 9000000
+ms('2h')      // 7200000
+ms('1m')      // 60000
+ms('5s')      // 5000
+ms('1y')      // 31557600000
+ms('100')     // 100
+ms('-3 days') // -259200000
+ms('-1h')     // -3600000
+ms('-200')    // -200
+```
+
+### Convert from Milliseconds
+
+```js
+ms(60000)             // "1m"
+ms(2 * 60000)         // "2m"
+ms(-3 * 60000)        // "-3m"
+ms(ms('10 hours'))    // "10h"
+```
+
+### Time Format Written-Out
+
+```js
+ms(60000, { long: true })             // "1 minute"
+ms(2 * 60000, { long: true })         // "2 minutes"
+ms(-3 * 60000, { long: true })        // "-3 minutes"
+ms(ms('10 hours'), { long: true })    // "10 hours"
+```
+
+## Features
+
+- Works both in [Node.js](https://nodejs.org) and in the browser
+- If a number is supplied to `ms`, a string with a unit is returned
+- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
+- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
+
+## Related Packages
+
+- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
+
+## Caught a Bug?
+
+1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
+2. Link the package to the global module directory: `npm link`
+3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
+
+As always, you can run the tests using: `npm test`
diff --git a/node_modules/natural-compare/README.md b/node_modules/natural-compare/README.md
new file mode 100644
index 00000000..c85dfdf9
--- /dev/null
+++ b/node_modules/natural-compare/README.md
@@ -0,0 +1,125 @@
+
+[Build]:    http://img.shields.io/travis/litejs/natural-compare-lite.png
+[Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png
+[1]: https://travis-ci.org/litejs/natural-compare-lite
+[2]: https://coveralls.io/r/litejs/natural-compare-lite
+[npm package]: https://npmjs.org/package/natural-compare-lite
+[GitHub repo]: https://github.com/litejs/natural-compare-lite
+
+
+
+    @version    1.4.0
+    @date       2015-10-26
+    @stability  3 - Stable
+
+
+Natural Compare – [![Build][]][1] [![Coverage][]][2]
+===============
+
+Compare strings containing a mix of letters and numbers
+in the way a human being would in sort order.
+This is described as a "natural ordering".
+
+```text
+Standard sorting:   Natural order sorting:
+    img1.png            img1.png
+    img10.png           img2.png
+    img12.png           img10.png
+    img2.png            img12.png
+```
+
+String.naturalCompare returns a number indicating
+whether a reference string comes before or after or is the same
+as the given string in sort order.
+Use it with builtin sort() function.
+
+
+
+### Installation
+
+- In browser
+
+```html
+
+```
+
+- In node.js: `npm install natural-compare-lite`
+
+```javascript
+require("natural-compare-lite")
+```
+
+### Usage
+
+```javascript
+// Simple case sensitive example
+var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"];
+a.sort(String.naturalCompare);
+// ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"]
+
+// Use wrapper function for case insensitivity
+a.sort(function(a, b){
+  return String.naturalCompare(a.toLowerCase(), b.toLowerCase());
+})
+
+// In most cases we want to sort an array of objects
+var a = [ {"street":"350 5th Ave", "room":"A-1021"}
+        , {"street":"350 5th Ave", "room":"A-21046-b"} ];
+
+// sort by street, then by room
+a.sort(function(a, b){
+  return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room);
+})
+
+// When text transformation is needed (eg toLowerCase()),
+// it is best for performance to keep
+// transformed key in that object.
+// There are no need to do text transformation
+// on each comparision when sorting.
+var a = [ {"make":"Audi", "model":"A6"}
+        , {"make":"Kia",  "model":"Rio"} ];
+
+// sort by make, then by model
+a.map(function(car){
+  car.sort_key = (car.make + " " + car.model).toLowerCase();
+})
+a.sort(function(a, b){
+  return String.naturalCompare(a.sort_key, b.sort_key);
+})
+```
+
+- Works well with dates in ISO format eg "Rev 2012-07-26.doc".
+
+
+### Custom alphabet
+
+It is possible to configure a custom alphabet
+to achieve a desired order.
+
+```javascript
+// Estonian alphabet
+String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy"
+["t", "z", "x", "õ"].sort(String.naturalCompare)
+// ["z", "t", "õ", "x"]
+
+// Russian alphabet
+String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"
+["Ё", "А", "Б"].sort(String.naturalCompare)
+// ["А", "Б", "Ё"]
+```
+
+
+External links
+--------------
+
+-   [GitHub repo][https://github.com/litejs/natural-compare-lite]
+-   [jsperf test](http://jsperf.com/natural-sort-2/12)
+
+
+Licence
+-------
+
+Copyright (c) 2012-2015 Lauri Rooden <lauri@rooden.ee>  
+[The MIT License](http://lauri.rooden.ee/mit-license.txt)
+
+
diff --git a/node_modules/natural-compare/index.js b/node_modules/natural-compare/index.js
new file mode 100644
index 00000000..e705d49f
--- /dev/null
+++ b/node_modules/natural-compare/index.js
@@ -0,0 +1,57 @@
+
+
+
+/*
+ * @version    1.4.0
+ * @date       2015-10-26
+ * @stability  3 - Stable
+ * @author     Lauri Rooden (https://github.com/litejs/natural-compare-lite)
+ * @license    MIT License
+ */
+
+
+var naturalCompare = function(a, b) {
+	var i, codeA
+	, codeB = 1
+	, posA = 0
+	, posB = 0
+	, alphabet = String.alphabet
+
+	function getCode(str, pos, code) {
+		if (code) {
+			for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
+			return +str.slice(pos - 1, i)
+		}
+		code = alphabet && alphabet.indexOf(str.charAt(pos))
+		return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code
+			: code < 46 ? 65               // -
+			: code < 48 ? code - 1
+			: code < 58 ? code + 18        // 0-9
+			: code < 65 ? code - 11
+			: code < 91 ? code + 11        // A-Z
+			: code < 97 ? code - 37
+			: code < 123 ? code + 5        // a-z
+			: code - 63
+	}
+
+
+	if ((a+="") != (b+="")) for (;codeB;) {
+		codeA = getCode(a, posA++)
+		codeB = getCode(b, posB++)
+
+		if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
+			codeA = getCode(a, posA, posA)
+			codeB = getCode(b, posB, posA = i)
+			posB = i
+		}
+
+		if (codeA != codeB) return (codeA < codeB) ? -1 : 1
+	}
+	return 0
+}
+
+try {
+	module.exports = naturalCompare;
+} catch (e) {
+	String.naturalCompare = naturalCompare;
+}
diff --git a/node_modules/natural-compare/package.json b/node_modules/natural-compare/package.json
new file mode 100644
index 00000000..1a71362e
--- /dev/null
+++ b/node_modules/natural-compare/package.json
@@ -0,0 +1,42 @@
+{
+  "name": "natural-compare",
+  "version": "1.4.0",
+  "stability": 3,
+  "author": "Lauri Rooden (https://github.com/litejs/natural-compare-lite)",
+  "license": "MIT",
+  "description": "Compare strings containing a mix of letters and numbers in the way a human being would in sort order.",
+  "keywords": [
+    "string",
+    "natural",
+    "order",
+    "sort",
+    "natsort",
+    "natcmp",
+    "compare",
+    "alphanum",
+    "litejs"
+  ],
+  "main": "index.js",
+  "readmeFilename": "README.md",
+  "files": [
+    "index.js"
+  ],
+  "scripts": {
+    "build": "node node_modules/buildman/index.js --all",
+    "test": "node tests/index.js"
+  },
+  "repository": "git://github.com/litejs/natural-compare-lite.git",
+  "bugs": {
+    "url": "https://github.com/litejs/natural-compare-lite/issues"
+  },
+  "devDependencies": {
+    "buildman": "*",
+    "testman": "*"
+  },
+  "buildman": {
+    "dist/index-min.js": {
+      "banner": "/*! litejs.com/MIT-LICENSE.txt */",
+      "input": "index.js"
+    }
+  }
+}
diff --git a/node_modules/optionator/CHANGELOG.md b/node_modules/optionator/CHANGELOG.md
new file mode 100644
index 00000000..2928cc2c
--- /dev/null
+++ b/node_modules/optionator/CHANGELOG.md
@@ -0,0 +1,59 @@
+# 0.9.0
+- update dependencies, in particular `levn` and `type-check` - this could affect behaviour of argument parsing
+
+# 0.8.3
+- changes dependency from `wordwrap` to `word-wrap` due to license issue
+- update dependencies
+
+# 0.8.2
+- fix bug #18 - detect missing value when flag is last item
+- update dependencies
+
+# 0.8.1
+- update `fast-levenshtein` dependency
+
+# 0.8.0
+- update `levn` dependency - supplying a float value to an option with type `Int` now throws an error, instead of silently converting to an `Int`
+
+# 0.7.1
+- fix bug with use of `defaults` and `concatRepeatedArrays` or `mergeRepeatedObjects`
+
+# 0.7.0
+- added `concatrepeatedarrays` option: `oneValuePerFlag`, only allows one array value per flag
+- added `typeAliases` option
+- added `parseArgv` which takes an array and parses with the first two items sliced off
+- changed enum help style
+- bug fixes (#12)
+- use of `concatRepeatedArrays` and `mergeRepeatedObjects` at the top level is deprecated, use it as either a per-option option, or set them in the `defaults` object to set them for all objects
+
+# 0.6.0
+- added `defaults` lib-option flag, allowing one to set default properties for all options
+- added `concatRepeatedArrays` and `mergeRepeatedObjects` as option level properties, allowing you to turn this feature on for specific options only
+
+# 0.5.0
+- `Boolean` flags with `default: 'true'`, and no short aliases, will by default show the `--no` version in help
+
+# 0.4.0
+- add `mergeRepeatedObjects` setting
+
+# 0.3.0
+- add `concatRepeatedArrays` setting
+- add `overrideRequired` option setting
+- use just Levenshtein string compare algo rather than Levenshtein Damerau to due dependency license issue
+
+# 0.2.2
+- bug fixes
+
+# 0.2.1
+- improved interpolation
+- added changelog
+
+# 0.2.0
+- add dependency checks to options - added `dependsOn` as an option property
+- add interpolation for `prepend` and `append` text with new `generateHelp` option, `interpolate`
+
+# 0.1.1
+- update dependencies
+
+# 0.1.0
+- initial release
diff --git a/node_modules/optionator/LICENSE b/node_modules/optionator/LICENSE
new file mode 100644
index 00000000..525b1185
--- /dev/null
+++ b/node_modules/optionator/LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) George Zahariev
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
diff --git a/node_modules/optionator/README.md b/node_modules/optionator/README.md
new file mode 100644
index 00000000..9cd0bb43
--- /dev/null
+++ b/node_modules/optionator/README.md
@@ -0,0 +1,238 @@
+# Optionator
+
+
+Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator).
+
+For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo).
+
+[About](#about) · [Usage](#usage) · [Settings Format](#settings-format) · [Argument Format](#argument-format)
+
+## Why?
+The  problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not.
+With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant).
+If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application.
+
+    $ cmd --halp
+    Invalid option '--halp' - perhaps you meant '--help'?
+
+    $ cmd --count str
+    Invalid value for option 'count' - expected type Int, received value: str.
+
+Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier.
+
+## About
+Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types.
+
+MIT license. Version 0.9.4
+
+    npm install optionator
+
+For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev).
+
+Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify.
+
+## Usage
+`require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions.
+
+```js
+var optionator = require('optionator')({
+    prepend: 'Usage: cmd [options]',
+    append: 'Version 1.0.0',
+    options: [{
+        option: 'help',
+        alias: 'h',
+        type: 'Boolean',
+        description: 'displays help'
+    }, {
+        option: 'count',
+        alias: 'c',
+        type: 'Int',
+        description: 'number of things',
+        example: 'cmd --count 2'
+    }]
+});
+
+var options = optionator.parseArgv(process.argv);
+if (options.help) {
+    console.log(optionator.generateHelp());
+}
+...
+```
+
+### parse(input, parseOptions)
+`parse` processes the `input` according to your settings, and returns an object with the results.
+
+##### arguments
+* input - `[String] | Object | String` - the input you wish to parse
+* parseOptions - `{slice: Int}` - all options optional
+    - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`)
+
+##### returns
+`Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key.
+
+##### example
+```js
+parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']}
+parse('--count 2 positional');                         // {count: 2, _: ['positional']}
+parse({count: 2, _:['positional']});                   // {count: 2, _: ['positional']}
+```
+
+### parseArgv(input)
+`parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements.
+
+##### arguments
+* input - `[String]` - the input you wish to parse
+
+##### returns
+See "returns" section in "parse"
+
+##### example
+```js
+parseArgv(process.argv);
+```
+
+### generateHelp(helpOptions)
+`generateHelp` produces help text based on your settings.
+
+##### arguments
+* helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional
+    - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false`
+    - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2`
+
+##### returns
+`String` - the generated help text
+
+##### example
+```js
+generateHelp(); /*
+"Usage: cmd [options] positional
+
+  -h, --help       displays help
+  -c, --count Int  number of things
+
+Version  1.0.0
+"*/
+```
+
+### generateHelpForOption(optionName)
+`generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed,  and if a `longDescription` was specified, it will display that instead of the `description`.
+
+##### arguments
+* optionName - `String` - the name of the option to display
+
+##### returns
+`String` - the generated help text for the option
+
+##### example
+```js
+generateHelpForOption('count'); /*
+"-c, --count Int
+description: number of things
+example: cmd --count 2
+"*/
+```
+
+## Settings Format
+When your `require('optionator')`, you get a function that takes in a settings object. This object has the type:
+
+    {
+      prepend: String,
+      append: String,
+      options: [{heading: String} | {
+        option: String,
+        alias: [String] | String,
+        type: String,
+        enum: [String],
+        default: String,
+        restPositional: Boolean,
+        required: Boolean,
+        overrideRequired: Boolean,
+        dependsOn: [String] | String,
+        concatRepeatedArrays: Boolean | (Boolean, Object),
+        mergeRepeatedObjects: Boolean,
+        description: String,
+        longDescription: String,
+        example: [String] | String
+      }],
+      helpStyle: {
+        aliasSeparator: String,
+        typeSeparator: String,
+        descriptionSeparator: String,
+        initialIndent: Int,
+        secondaryIndent: Int,
+        maxPadFactor: Number
+      },
+      mutuallyExclusive: [[String | [String]]],
+      concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object
+      mergeRepeatedObjects: Boolean, // deprecated, set in defaults object
+      positionalAnywhere: Boolean,
+      typeAliases: Object,
+      defaults: Object
+    }
+
+All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array.
+
+### Top Level Properties
+* `prepend` is an optional string to be placed before the options in the help text
+* `append` is an optional string to be placed after the options in the help text
+* `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified
+* `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text
+* `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present
+* `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property
+* `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property
+* `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack`
+* `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String`
+* `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property
+
+#### Heading Properties
+* `heading` a required string, the name of the heading
+
+#### Option Properties
+* `option` the required name of the option - use dash-case, without the leading dashes
+* `alias` is an optional string or array of strings which specify any aliases for the option
+* `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it
+* `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type`
+* `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type`
+* `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument
+* `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined
+* `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags
+* `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']`
+
+ You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma.
+* `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}`
+* `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set
+* `description` is an optional string, which will be displayed next to the option in the help text
+* `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used
+* `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used
+
+#### Help Style Properties
+* `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,'
+* `typeSeparator` is an optional string, separates the type from the names - default: ' '
+* `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: '  '
+* `initialIndent` is an optional int - the amount of indent for options - default: 2
+* `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4
+* `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5
+
+## Argument Format
+At the highest level there are two types of arguments: named, and positional.
+
+Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`).
+
+There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value.
+
+For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages.
+
+You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`.
+
+Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`.
+
+Everything after an `--` is positional, even if it looks like a named argument.
+
+You may optionally use `=` to separate option names from values, for example: `--count=2`.
+
+If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`.
+
+If duplicate named arguments are present, the last one will be taken.
+
+## Technical About
+`optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library.
diff --git a/node_modules/optionator/lib/help.js b/node_modules/optionator/lib/help.js
new file mode 100644
index 00000000..59e6f969
--- /dev/null
+++ b/node_modules/optionator/lib/help.js
@@ -0,0 +1,260 @@
+// Generated by LiveScript 1.6.0
+(function(){
+  var ref$, id, find, sort, min, max, map, unlines, nameToRaw, dasherize, naturalJoin, wordWrap, wordwrap, getPreText, setHelpStyleDefaults, generateHelpForOption, generateHelp;
+  ref$ = require('prelude-ls'), id = ref$.id, find = ref$.find, sort = ref$.sort, min = ref$.min, max = ref$.max, map = ref$.map, unlines = ref$.unlines;
+  ref$ = require('./util'), nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin;
+  wordWrap = require('word-wrap');
+  wordwrap = function(a, b){
+    var ref$, indent, width;
+    ref$ = b === undefined
+      ? ['', a - 1]
+      : [repeatString$(' ', a), b - a - 1], indent = ref$[0], width = ref$[1];
+    return function(text){
+      return wordWrap(text, {
+        indent: indent,
+        width: width,
+        trim: true
+      });
+    };
+  };
+  getPreText = function(option, arg$, maxWidth){
+    var mainName, shortNames, ref$, longNames, type, description, aliasSeparator, typeSeparator, initialIndent, names, namesString, namesStringLen, typeSeparatorString, typeSeparatorStringLen, wrap;
+    mainName = option.option, shortNames = (ref$ = option.shortNames) != null
+      ? ref$
+      : [], longNames = (ref$ = option.longNames) != null
+      ? ref$
+      : [], type = option.type, description = option.description;
+    aliasSeparator = arg$.aliasSeparator, typeSeparator = arg$.typeSeparator, initialIndent = arg$.initialIndent;
+    if (option.negateName) {
+      mainName = "no-" + mainName;
+      if (longNames) {
+        longNames = map(function(it){
+          return "no-" + it;
+        }, longNames);
+      }
+    }
+    names = mainName.length === 1
+      ? [mainName].concat(shortNames, longNames)
+      : shortNames.concat([mainName], longNames);
+    namesString = map(nameToRaw, names).join(aliasSeparator);
+    namesStringLen = namesString.length;
+    typeSeparatorString = mainName === 'NUM' ? '::' : typeSeparator;
+    typeSeparatorStringLen = typeSeparatorString.length;
+    if (maxWidth != null && !option.boolean && initialIndent + namesStringLen + typeSeparatorStringLen + type.length > maxWidth) {
+      wrap = wordwrap(initialIndent + namesStringLen + typeSeparatorStringLen, maxWidth);
+      return namesString + "" + typeSeparatorString + wrap(type).replace(/^\s+/, '');
+    } else {
+      return namesString + "" + (option.boolean
+        ? ''
+        : typeSeparatorString + "" + type);
+    }
+  };
+  setHelpStyleDefaults = function(helpStyle){
+    helpStyle.aliasSeparator == null && (helpStyle.aliasSeparator = ', ');
+    helpStyle.typeSeparator == null && (helpStyle.typeSeparator = ' ');
+    helpStyle.descriptionSeparator == null && (helpStyle.descriptionSeparator = '  ');
+    helpStyle.initialIndent == null && (helpStyle.initialIndent = 2);
+    helpStyle.secondaryIndent == null && (helpStyle.secondaryIndent = 4);
+    helpStyle.maxPadFactor == null && (helpStyle.maxPadFactor = 1.5);
+  };
+  generateHelpForOption = function(getOption, arg$){
+    var stdout, helpStyle, ref$;
+    stdout = arg$.stdout, helpStyle = (ref$ = arg$.helpStyle) != null
+      ? ref$
+      : {};
+    setHelpStyleDefaults(helpStyle);
+    return function(optionName){
+      var maxWidth, wrap, option, e, pre, defaultString, restPositionalString, description, fullDescription, that, preDescription, descriptionString, exampleString, examples, seperator;
+      maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null;
+      wrap = maxWidth ? wordwrap(maxWidth) : id;
+      try {
+        option = getOption(dasherize(optionName));
+      } catch (e$) {
+        e = e$;
+        return e.message;
+      }
+      pre = getPreText(option, helpStyle);
+      defaultString = option['default'] && !option.negateName ? "\ndefault: " + option['default'] : '';
+      restPositionalString = option.restPositional ? 'Everything after this option is considered a positional argument, even if it looks like an option.' : '';
+      description = option.longDescription || option.description && sentencize(option.description);
+      fullDescription = description && restPositionalString
+        ? description + " " + restPositionalString
+        : (that = description || restPositionalString) ? that : '';
+      preDescription = 'description:';
+      descriptionString = !fullDescription
+        ? ''
+        : maxWidth && fullDescription.length - 1 - preDescription.length > maxWidth
+          ? "\n" + preDescription + "\n" + wrap(fullDescription)
+          : "\n" + preDescription + " " + fullDescription;
+      exampleString = (that = option.example) ? (examples = [].concat(that), examples.length > 1
+        ? "\nexamples:\n" + unlines(examples)
+        : "\nexample: " + examples[0]) : '';
+      seperator = defaultString || descriptionString || exampleString ? "\n" + repeatString$('=', pre.length) : '';
+      return pre + "" + seperator + defaultString + descriptionString + exampleString;
+    };
+  };
+  generateHelp = function(arg$){
+    var options, prepend, append, helpStyle, ref$, stdout, aliasSeparator, typeSeparator, descriptionSeparator, maxPadFactor, initialIndent, secondaryIndent;
+    options = arg$.options, prepend = arg$.prepend, append = arg$.append, helpStyle = (ref$ = arg$.helpStyle) != null
+      ? ref$
+      : {}, stdout = arg$.stdout;
+    setHelpStyleDefaults(helpStyle);
+    aliasSeparator = helpStyle.aliasSeparator, typeSeparator = helpStyle.typeSeparator, descriptionSeparator = helpStyle.descriptionSeparator, maxPadFactor = helpStyle.maxPadFactor, initialIndent = helpStyle.initialIndent, secondaryIndent = helpStyle.secondaryIndent;
+    return function(arg$){
+      var ref$, showHidden, interpolate, maxWidth, output, out, data, optionCount, totalPreLen, preLens, i$, len$, item, that, pre, descParts, desc, preLen, sortedPreLens, maxPreLen, preLenMean, x, padAmount, descSepLen, fullWrapCount, partialWrapCount, descLen, totalLen, initialSpace, wrapAllFull, i, wrap;
+      ref$ = arg$ != null
+        ? arg$
+        : {}, showHidden = ref$.showHidden, interpolate = ref$.interpolate;
+      maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null;
+      output = [];
+      out = function(it){
+        return output.push(it != null ? it : '');
+      };
+      if (prepend) {
+        out(interpolate ? interp(prepend, interpolate) : prepend);
+        out();
+      }
+      data = [];
+      optionCount = 0;
+      totalPreLen = 0;
+      preLens = [];
+      for (i$ = 0, len$ = (ref$ = options).length; i$ < len$; ++i$) {
+        item = ref$[i$];
+        if (showHidden || !item.hidden) {
+          if (that = item.heading) {
+            data.push({
+              type: 'heading',
+              value: that
+            });
+          } else {
+            pre = getPreText(item, helpStyle, maxWidth);
+            descParts = [];
+            if ((that = item.description) != null) {
+              descParts.push(that);
+            }
+            if (that = item['enum']) {
+              descParts.push("either: " + naturalJoin(that));
+            }
+            if (item['default'] && !item.negateName) {
+              descParts.push("default: " + item['default']);
+            }
+            desc = descParts.join(' - ');
+            data.push({
+              type: 'option',
+              pre: pre,
+              desc: desc,
+              descLen: desc.length
+            });
+            preLen = pre.length;
+            optionCount++;
+            totalPreLen += preLen;
+            preLens.push(preLen);
+          }
+        }
+      }
+      sortedPreLens = sort(preLens);
+      maxPreLen = sortedPreLens[sortedPreLens.length - 1];
+      preLenMean = initialIndent + totalPreLen / optionCount;
+      x = optionCount > 2 ? min(preLenMean * maxPadFactor, maxPreLen) : maxPreLen;
+      for (i$ = sortedPreLens.length - 1; i$ >= 0; --i$) {
+        preLen = sortedPreLens[i$];
+        if (preLen <= x) {
+          padAmount = preLen;
+          break;
+        }
+      }
+      descSepLen = descriptionSeparator.length;
+      if (maxWidth != null) {
+        fullWrapCount = 0;
+        partialWrapCount = 0;
+        for (i$ = 0, len$ = data.length; i$ < len$; ++i$) {
+          item = data[i$];
+          if (item.type === 'option') {
+            pre = item.pre, desc = item.desc, descLen = item.descLen;
+            if (descLen === 0) {
+              item.wrap = 'none';
+            } else {
+              preLen = max(padAmount, pre.length) + initialIndent + descSepLen;
+              totalLen = preLen + descLen;
+              if (totalLen > maxWidth) {
+                if (descLen / 2.5 > maxWidth - preLen) {
+                  fullWrapCount++;
+                  item.wrap = 'full';
+                } else {
+                  partialWrapCount++;
+                  item.wrap = 'partial';
+                }
+              } else {
+                item.wrap = 'none';
+              }
+            }
+          }
+        }
+      }
+      initialSpace = repeatString$(' ', initialIndent);
+      wrapAllFull = optionCount > 1 && fullWrapCount + partialWrapCount * 0.5 > optionCount * 0.5;
+      for (i$ = 0, len$ = data.length; i$ < len$; ++i$) {
+        i = i$;
+        item = data[i$];
+        if (item.type === 'heading') {
+          if (i !== 0) {
+            out();
+          }
+          out(item.value + ":");
+        } else {
+          pre = item.pre, desc = item.desc, descLen = item.descLen, wrap = item.wrap;
+          if (maxWidth != null) {
+            if (wrapAllFull || wrap === 'full') {
+              wrap = wordwrap(initialIndent + secondaryIndent, maxWidth);
+              out(initialSpace + "" + pre + "\n" + wrap(desc));
+              continue;
+            } else if (wrap === 'partial') {
+              wrap = wordwrap(initialIndent + descSepLen + max(padAmount, pre.length), maxWidth);
+              out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + wrap(desc).replace(/^\s+/, ''));
+              continue;
+            }
+          }
+          if (descLen === 0) {
+            out(initialSpace + "" + pre);
+          } else {
+            out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + desc);
+          }
+        }
+      }
+      if (append) {
+        out();
+        out(interpolate ? interp(append, interpolate) : append);
+      }
+      return unlines(output);
+    };
+  };
+  function pad(str, num){
+    var len, padAmount;
+    len = str.length;
+    padAmount = num - len;
+    return str + "" + repeatString$(' ', padAmount > 0 ? padAmount : 0);
+  }
+  function sentencize(str){
+    var first, rest, period;
+    first = str.charAt(0).toUpperCase();
+    rest = str.slice(1);
+    period = /[\.!\?]$/.test(str) ? '' : '.';
+    return first + "" + rest + period;
+  }
+  function interp(string, object){
+    return string.replace(/{{([a-zA-Z$_][a-zA-Z$_0-9]*)}}/g, function(arg$, key){
+      var ref$;
+      return (ref$ = object[key]) != null
+        ? ref$
+        : "{{" + key + "}}";
+    });
+  }
+  module.exports = {
+    generateHelp: generateHelp,
+    generateHelpForOption: generateHelpForOption
+  };
+  function repeatString$(str, n){
+    for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str;
+    return r;
+  }
+}).call(this);
diff --git a/node_modules/optionator/lib/index.js b/node_modules/optionator/lib/index.js
new file mode 100644
index 00000000..436b7cc9
--- /dev/null
+++ b/node_modules/optionator/lib/index.js
@@ -0,0 +1,465 @@
+// Generated by LiveScript 1.6.0
+(function(){
+  var VERSION, ref$, id, map, compact, any, groupBy, partition, chars, isItNaN, keys, Obj, camelize, deepIs, closestString, nameToRaw, dasherize, naturalJoin, generateHelp, generateHelpForOption, parsedTypeCheck, parseType, parseLevn, camelizeKeys, parseString, main, toString$ = {}.toString, slice$ = [].slice, arrayFrom$ = Array.from || function(x){return slice$.call(x);};
+  VERSION = '0.9.4';
+  ref$ = require('prelude-ls'), id = ref$.id, map = ref$.map, compact = ref$.compact, any = ref$.any, groupBy = ref$.groupBy, partition = ref$.partition, chars = ref$.chars, isItNaN = ref$.isItNaN, keys = ref$.keys, Obj = ref$.Obj, camelize = ref$.camelize;
+  deepIs = require('deep-is');
+  ref$ = require('./util'), closestString = ref$.closestString, nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin;
+  ref$ = require('./help'), generateHelp = ref$.generateHelp, generateHelpForOption = ref$.generateHelpForOption;
+  ref$ = require('type-check'), parsedTypeCheck = ref$.parsedTypeCheck, parseType = ref$.parseType;
+  parseLevn = require('levn').parsedTypeParse;
+  camelizeKeys = function(obj){
+    var key, value, resultObj$ = {};
+    for (key in obj) {
+      value = obj[key];
+      resultObj$[camelize(key)] = value;
+    }
+    return resultObj$;
+  };
+  parseString = function(string){
+    var assignOpt, regex, replaceRegex, result;
+    assignOpt = '--?[a-zA-Z][-a-z-A-Z0-9]*=';
+    regex = RegExp('(?:' + assignOpt + ')?(?:\'(?:\\\\\'|[^\'])+\'|"(?:\\\\"|[^"])+")|[^\'"\\s]+', 'g');
+    replaceRegex = RegExp('^(' + assignOpt + ')?[\'"]([\\s\\S]*)[\'"]$');
+    result = map(function(it){
+      return it.replace(replaceRegex, '$1$2');
+    }, string.match(regex) || []);
+    return result;
+  };
+  main = function(libOptions){
+    var opts, defaults, required, traverse, getOption, parse;
+    opts = {};
+    defaults = {};
+    required = [];
+    if (toString$.call(libOptions.stdout).slice(8, -1) === 'Undefined') {
+      libOptions.stdout = process.stdout;
+    }
+    libOptions.positionalAnywhere == null && (libOptions.positionalAnywhere = true);
+    libOptions.typeAliases == null && (libOptions.typeAliases = {});
+    libOptions.defaults == null && (libOptions.defaults = {});
+    if (libOptions.concatRepeatedArrays != null) {
+      libOptions.defaults.concatRepeatedArrays = libOptions.concatRepeatedArrays;
+    }
+    if (libOptions.mergeRepeatedObjects != null) {
+      libOptions.defaults.mergeRepeatedObjects = libOptions.mergeRepeatedObjects;
+    }
+    traverse = function(options){
+      var i$, len$, option, name, k, ref$, v, type, that, e, parsedPossibilities, parsedType, j$, len1$, possibility, rawDependsType, dependsOpts, dependsType, cra, alias, shortNames, longNames;
+      if (toString$.call(options).slice(8, -1) !== 'Array') {
+        throw new Error('No options defined.');
+      }
+      for (i$ = 0, len$ = options.length; i$ < len$; ++i$) {
+        option = options[i$];
+        if (option.heading == null) {
+          name = option.option;
+          if (opts[name] != null) {
+            throw new Error("Option '" + name + "' already defined.");
+          }
+          for (k in ref$ = libOptions.defaults) {
+            v = ref$[k];
+            option[k] == null && (option[k] = v);
+          }
+          if (option.type === 'Boolean') {
+            option.boolean == null && (option.boolean = true);
+          }
+          if (option.parsedType == null) {
+            if (!option.type) {
+              throw new Error("No type defined for option '" + name + "'.");
+            }
+            try {
+              type = (that = libOptions.typeAliases[option.type]) != null
+                ? that
+                : option.type;
+              option.parsedType = parseType(type);
+            } catch (e$) {
+              e = e$;
+              throw new Error("Option '" + name + "': Error parsing type '" + option.type + "': " + e.message);
+            }
+          }
+          if (option['default']) {
+            try {
+              defaults[name] = parseLevn(option.parsedType, option['default']);
+            } catch (e$) {
+              e = e$;
+              throw new Error("Option '" + name + "': Error parsing default value '" + option['default'] + "' for type '" + option.type + "': " + e.message);
+            }
+          }
+          if (option['enum'] && !option.parsedPossiblities) {
+            parsedPossibilities = [];
+            parsedType = option.parsedType;
+            for (j$ = 0, len1$ = (ref$ = option['enum']).length; j$ < len1$; ++j$) {
+              possibility = ref$[j$];
+              try {
+                parsedPossibilities.push(parseLevn(parsedType, possibility));
+              } catch (e$) {
+                e = e$;
+                throw new Error("Option '" + name + "': Error parsing enum value '" + possibility + "' for type '" + option.type + "': " + e.message);
+              }
+            }
+            option.parsedPossibilities = parsedPossibilities;
+          }
+          if (that = option.dependsOn) {
+            if (that.length) {
+              ref$ = [].concat(option.dependsOn), rawDependsType = ref$[0], dependsOpts = slice$.call(ref$, 1);
+              dependsType = rawDependsType.toLowerCase();
+              if (dependsOpts.length) {
+                if (dependsType === 'and' || dependsType === 'or') {
+                  option.dependsOn = [dependsType].concat(arrayFrom$(dependsOpts));
+                } else {
+                  throw new Error("Option '" + name + "': If you have more than one dependency, you must specify either 'and' or 'or'");
+                }
+              } else {
+                if ((ref$ = dependsType.toLowerCase()) === 'and' || ref$ === 'or') {
+                  option.dependsOn = null;
+                } else {
+                  option.dependsOn = ['and', rawDependsType];
+                }
+              }
+            } else {
+              option.dependsOn = null;
+            }
+          }
+          if (option.required) {
+            required.push(name);
+          }
+          opts[name] = option;
+          if (option.concatRepeatedArrays != null) {
+            cra = option.concatRepeatedArrays;
+            if ('Boolean' === toString$.call(cra).slice(8, -1)) {
+              option.concatRepeatedArrays = [cra, {}];
+            } else if (cra.length === 1) {
+              option.concatRepeatedArrays = [cra[0], {}];
+            } else if (cra.length !== 2) {
+              throw new Error("Invalid setting for concatRepeatedArrays");
+            }
+          }
+          if (option.alias || option.aliases) {
+            if (name === 'NUM') {
+              throw new Error("-NUM option can't have aliases.");
+            }
+            if (option.alias) {
+              option.aliases == null && (option.aliases = [].concat(option.alias));
+            }
+            for (j$ = 0, len1$ = (ref$ = option.aliases).length; j$ < len1$; ++j$) {
+              alias = ref$[j$];
+              if (opts[alias] != null) {
+                throw new Error("Option '" + alias + "' already defined.");
+              }
+              opts[alias] = option;
+            }
+            ref$ = partition(fn$, option.aliases), shortNames = ref$[0], longNames = ref$[1];
+            option.shortNames == null && (option.shortNames = shortNames);
+            option.longNames == null && (option.longNames = longNames);
+          }
+          if ((!option.aliases || option.shortNames.length === 0) && option.type === 'Boolean' && option['default'] === 'true') {
+            option.negateName = true;
+          }
+        }
+      }
+      function fn$(it){
+        return it.length === 1;
+      }
+    };
+    traverse(libOptions.options);
+    getOption = function(name){
+      var opt, possiblyMeant;
+      opt = opts[name];
+      if (opt == null) {
+        possiblyMeant = closestString(keys(opts), name);
+        throw new Error("Invalid option '" + nameToRaw(name) + "'" + (possiblyMeant ? " - perhaps you meant '" + nameToRaw(possiblyMeant) + "'?" : '.'));
+      }
+      return opt;
+    };
+    parse = function(input, arg$){
+      var slice, obj, positional, restPositional, overrideRequired, prop, setValue, setDefaults, checkRequired, mutuallyExclusiveError, checkMutuallyExclusive, checkDependency, checkDependencies, checkProp, args, key, value, option, ref$, i$, len$, arg, that, result, short, argName, usingAssign, val, flags, len, j$, len1$, i, flag, opt, name, valPrime, negated, noedName;
+      slice = (arg$ != null
+        ? arg$
+        : {}).slice;
+      obj = {};
+      positional = [];
+      restPositional = false;
+      overrideRequired = false;
+      prop = null;
+      setValue = function(name, value){
+        var opt, val, cra, e, currentType;
+        opt = getOption(name);
+        if (opt.boolean) {
+          val = value;
+        } else {
+          try {
+            cra = opt.concatRepeatedArrays;
+            if (cra != null && cra[0] && cra[1].oneValuePerFlag && opt.parsedType.length === 1 && opt.parsedType[0].structure === 'array') {
+              val = [parseLevn(opt.parsedType[0].of, value)];
+            } else {
+              val = parseLevn(opt.parsedType, value);
+            }
+          } catch (e$) {
+            e = e$;
+            throw new Error("Invalid value for option '" + name + "' - expected type " + opt.type + ", received value: " + value + ".");
+          }
+          if (opt['enum'] && !any(function(it){
+            return deepIs(it, val);
+          }, opt.parsedPossibilities)) {
+            throw new Error("Option " + name + ": '" + val + "' not one of " + naturalJoin(opt['enum']) + ".");
+          }
+        }
+        currentType = toString$.call(obj[name]).slice(8, -1);
+        if (obj[name] != null) {
+          if (opt.concatRepeatedArrays != null && opt.concatRepeatedArrays[0] && currentType === 'Array') {
+            obj[name] = obj[name].concat(val);
+          } else if (opt.mergeRepeatedObjects && currentType === 'Object') {
+            import$(obj[name], val);
+          } else {
+            obj[name] = val;
+          }
+        } else {
+          obj[name] = val;
+        }
+        if (opt.restPositional) {
+          restPositional = true;
+        }
+        if (opt.overrideRequired) {
+          overrideRequired = true;
+        }
+      };
+      setDefaults = function(){
+        var name, ref$, value;
+        for (name in ref$ = defaults) {
+          value = ref$[name];
+          if (obj[name] == null) {
+            obj[name] = value;
+          }
+        }
+      };
+      checkRequired = function(){
+        var i$, ref$, len$, name;
+        if (overrideRequired) {
+          return;
+        }
+        for (i$ = 0, len$ = (ref$ = required).length; i$ < len$; ++i$) {
+          name = ref$[i$];
+          if (!obj[name]) {
+            throw new Error("Option " + nameToRaw(name) + " is required.");
+          }
+        }
+      };
+      mutuallyExclusiveError = function(first, second){
+        throw new Error("The options " + nameToRaw(first) + " and " + nameToRaw(second) + " are mutually exclusive - you cannot use them at the same time.");
+      };
+      checkMutuallyExclusive = function(){
+        var rules, i$, len$, rule, present, j$, len1$, element, k$, len2$, opt;
+        rules = libOptions.mutuallyExclusive;
+        if (!rules) {
+          return;
+        }
+        for (i$ = 0, len$ = rules.length; i$ < len$; ++i$) {
+          rule = rules[i$];
+          present = null;
+          for (j$ = 0, len1$ = rule.length; j$ < len1$; ++j$) {
+            element = rule[j$];
+            if (toString$.call(element).slice(8, -1) === 'Array') {
+              for (k$ = 0, len2$ = element.length; k$ < len2$; ++k$) {
+                opt = element[k$];
+                if (opt in obj) {
+                  if (present != null) {
+                    mutuallyExclusiveError(present, opt);
+                  } else {
+                    present = opt;
+                    break;
+                  }
+                }
+              }
+            } else {
+              if (element in obj) {
+                if (present != null) {
+                  mutuallyExclusiveError(present, element);
+                } else {
+                  present = element;
+                }
+              }
+            }
+          }
+        }
+      };
+      checkDependency = function(option){
+        var dependsOn, type, targetOptionNames, i$, len$, targetOptionName, targetOption;
+        dependsOn = option.dependsOn;
+        if (!dependsOn || option.dependenciesMet) {
+          return true;
+        }
+        type = dependsOn[0], targetOptionNames = slice$.call(dependsOn, 1);
+        for (i$ = 0, len$ = targetOptionNames.length; i$ < len$; ++i$) {
+          targetOptionName = targetOptionNames[i$];
+          targetOption = obj[targetOptionName];
+          if (targetOption && checkDependency(targetOption)) {
+            if (type === 'or') {
+              return true;
+            }
+          } else if (type === 'and') {
+            throw new Error("The option '" + option.option + "' did not have its dependencies met.");
+          }
+        }
+        if (type === 'and') {
+          return true;
+        } else {
+          throw new Error("The option '" + option.option + "' did not meet any of its dependencies.");
+        }
+      };
+      checkDependencies = function(){
+        var name;
+        for (name in obj) {
+          checkDependency(opts[name]);
+        }
+      };
+      checkProp = function(){
+        if (prop) {
+          throw new Error("Value for '" + prop + "' of type '" + getOption(prop).type + "' required.");
+        }
+      };
+      switch (toString$.call(input).slice(8, -1)) {
+      case 'String':
+        args = parseString(input.slice(slice != null ? slice : 0));
+        break;
+      case 'Array':
+        args = input.slice(slice != null ? slice : 2);
+        break;
+      case 'Object':
+        obj = {};
+        for (key in input) {
+          value = input[key];
+          if (key !== '_') {
+            option = getOption(dasherize(key));
+            if (parsedTypeCheck(option.parsedType, value)) {
+              obj[option.option] = value;
+            } else {
+              throw new Error("Option '" + option.option + "': Invalid type for '" + value + "' - expected type '" + option.type + "'.");
+            }
+          }
+        }
+        checkMutuallyExclusive();
+        checkDependencies();
+        setDefaults();
+        checkRequired();
+        return ref$ = camelizeKeys(obj), ref$._ = input._ || [], ref$;
+      default:
+        throw new Error("Invalid argument to 'parse': " + input + ".");
+      }
+      for (i$ = 0, len$ = args.length; i$ < len$; ++i$) {
+        arg = args[i$];
+        if (arg === '--') {
+          restPositional = true;
+        } else if (restPositional) {
+          positional.push(arg);
+        } else {
+          if (that = arg.match(/^(--?)([a-zA-Z][-a-zA-Z0-9]*)(=)?(.*)?$/)) {
+            result = that;
+            checkProp();
+            short = result[1].length === 1;
+            argName = result[2];
+            usingAssign = result[3] != null;
+            val = result[4];
+            if (usingAssign && val == null) {
+              throw new Error("No value for '" + argName + "' specified.");
+            }
+            if (short) {
+              flags = chars(argName);
+              len = flags.length;
+              for (j$ = 0, len1$ = flags.length; j$ < len1$; ++j$) {
+                i = j$;
+                flag = flags[j$];
+                opt = getOption(flag);
+                name = opt.option;
+                if (restPositional) {
+                  positional.push(flag);
+                } else if (i === len - 1) {
+                  if (usingAssign) {
+                    valPrime = opt.boolean ? parseLevn([{
+                      type: 'Boolean'
+                    }], val) : val;
+                    setValue(name, valPrime);
+                  } else if (opt.boolean) {
+                    setValue(name, true);
+                  } else {
+                    prop = name;
+                  }
+                } else if (opt.boolean) {
+                  setValue(name, true);
+                } else {
+                  throw new Error("Can't set argument '" + flag + "' when not last flag in a group of short flags.");
+                }
+              }
+            } else {
+              negated = false;
+              if (that = argName.match(/^no-(.+)$/)) {
+                negated = true;
+                noedName = that[1];
+                opt = getOption(noedName);
+              } else {
+                opt = getOption(argName);
+              }
+              name = opt.option;
+              if (opt.boolean) {
+                valPrime = usingAssign ? parseLevn([{
+                  type: 'Boolean'
+                }], val) : true;
+                if (negated) {
+                  setValue(name, !valPrime);
+                } else {
+                  setValue(name, valPrime);
+                }
+              } else {
+                if (negated) {
+                  throw new Error("Only use 'no-' prefix for Boolean options, not with '" + noedName + "'.");
+                }
+                if (usingAssign) {
+                  setValue(name, val);
+                } else {
+                  prop = name;
+                }
+              }
+            }
+          } else if (that = arg.match(/^-([0-9]+(?:\.[0-9]+)?)$/)) {
+            opt = opts.NUM;
+            if (!opt) {
+              throw new Error('No -NUM option defined.');
+            }
+            setValue(opt.option, that[1]);
+          } else {
+            if (prop) {
+              setValue(prop, arg);
+              prop = null;
+            } else {
+              positional.push(arg);
+              if (!libOptions.positionalAnywhere) {
+                restPositional = true;
+              }
+            }
+          }
+        }
+      }
+      checkProp();
+      checkMutuallyExclusive();
+      checkDependencies();
+      setDefaults();
+      checkRequired();
+      return ref$ = camelizeKeys(obj), ref$._ = positional, ref$;
+    };
+    return {
+      parse: parse,
+      parseArgv: function(it){
+        return parse(it, {
+          slice: 2
+        });
+      },
+      generateHelp: generateHelp(libOptions),
+      generateHelpForOption: generateHelpForOption(getOption, libOptions)
+    };
+  };
+  main.VERSION = VERSION;
+  module.exports = main;
+  function import$(obj, src){
+    var own = {}.hasOwnProperty;
+    for (var key in src) if (own.call(src, key)) obj[key] = src[key];
+    return obj;
+  }
+}).call(this);
diff --git a/node_modules/optionator/lib/util.js b/node_modules/optionator/lib/util.js
new file mode 100644
index 00000000..5bc0cbb6
--- /dev/null
+++ b/node_modules/optionator/lib/util.js
@@ -0,0 +1,54 @@
+// Generated by LiveScript 1.6.0
+(function(){
+  var prelude, map, sortBy, fl, closestString, nameToRaw, dasherize, naturalJoin;
+  prelude = require('prelude-ls'), map = prelude.map, sortBy = prelude.sortBy;
+  fl = require('fast-levenshtein');
+  closestString = function(possibilities, input){
+    var distances, ref$, string, distance;
+    if (!possibilities.length) {
+      return;
+    }
+    distances = map(function(it){
+      var ref$, longer, shorter;
+      ref$ = input.length > it.length
+        ? [input, it]
+        : [it, input], longer = ref$[0], shorter = ref$[1];
+      return {
+        string: it,
+        distance: fl.get(longer, shorter)
+      };
+    })(
+    possibilities);
+    ref$ = sortBy(function(it){
+      return it.distance;
+    }, distances)[0], string = ref$.string, distance = ref$.distance;
+    return string;
+  };
+  nameToRaw = function(name){
+    if (name.length === 1 || name === 'NUM') {
+      return "-" + name;
+    } else {
+      return "--" + name;
+    }
+  };
+  dasherize = function(string){
+    if (/^[A-Z]/.test(string)) {
+      return string;
+    } else {
+      return prelude.dasherize(string);
+    }
+  };
+  naturalJoin = function(array){
+    if (array.length < 3) {
+      return array.join(' or ');
+    } else {
+      return array.slice(0, -1).join(', ') + ", or " + array[array.length - 1];
+    }
+  };
+  module.exports = {
+    closestString: closestString,
+    nameToRaw: nameToRaw,
+    dasherize: dasherize,
+    naturalJoin: naturalJoin
+  };
+}).call(this);
diff --git a/node_modules/optionator/package.json b/node_modules/optionator/package.json
new file mode 100644
index 00000000..72b21bab
--- /dev/null
+++ b/node_modules/optionator/package.json
@@ -0,0 +1,43 @@
+{
+  "name": "optionator",
+  "version": "0.9.4",
+  "author": "George Zahariev ",
+  "description": "option parsing and help generation",
+  "homepage": "https://github.com/gkz/optionator",
+  "keywords": [
+    "options",
+    "flags",
+    "option parsing",
+    "cli"
+  ],
+  "files": [
+    "lib",
+    "README.md",
+    "LICENSE"
+  ],
+  "main": "./lib/",
+  "bugs": "https://github.com/gkz/optionator/issues",
+  "license": "MIT",
+  "engines": {
+    "node": ">= 0.8.0"
+  },
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/gkz/optionator.git"
+  },
+  "scripts": {
+    "test": "make test"
+  },
+  "dependencies": {
+    "prelude-ls": "^1.2.1",
+    "deep-is": "^0.1.3",
+    "word-wrap": "^1.2.5",
+    "type-check": "^0.4.0",
+    "levn": "^0.4.1",
+    "fast-levenshtein": "^2.0.6"
+  },
+  "devDependencies": {
+    "livescript": "^1.6.0",
+    "mocha": "^10.4.0"
+  }
+}
diff --git a/node_modules/p-limit/index.d.ts b/node_modules/p-limit/index.d.ts
new file mode 100644
index 00000000..f348d7f1
--- /dev/null
+++ b/node_modules/p-limit/index.d.ts
@@ -0,0 +1,42 @@
+declare namespace pLimit {
+	interface Limit {
+		/**
+		The number of promises that are currently running.
+		*/
+		readonly activeCount: number;
+
+		/**
+		The number of promises that are waiting to run (i.e. their internal `fn` was not called yet).
+		*/
+		readonly pendingCount: number;
+
+		/**
+		Discard pending promises that are waiting to run.
+
+		This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app.
+
+		Note: This does not cancel promises that are already running.
+		*/
+		clearQueue: () => void;
+
+		/**
+		@param fn - Promise-returning/async function.
+		@param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions.
+		@returns The promise returned by calling `fn(...arguments)`.
+		*/
+		(
+			fn: (...arguments: Arguments) => PromiseLike | ReturnType,
+			...arguments: Arguments
+		): Promise;
+	}
+}
+
+/**
+Run multiple promise-returning & async functions with limited concurrency.
+
+@param concurrency - Concurrency limit. Minimum: `1`.
+@returns A `limit` function.
+*/
+declare function pLimit(concurrency: number): pLimit.Limit;
+
+export = pLimit;
diff --git a/node_modules/p-limit/index.js b/node_modules/p-limit/index.js
new file mode 100644
index 00000000..c2ae52d9
--- /dev/null
+++ b/node_modules/p-limit/index.js
@@ -0,0 +1,71 @@
+'use strict';
+const Queue = require('yocto-queue');
+
+const pLimit = concurrency => {
+	if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
+		throw new TypeError('Expected `concurrency` to be a number from 1 and up');
+	}
+
+	const queue = new Queue();
+	let activeCount = 0;
+
+	const next = () => {
+		activeCount--;
+
+		if (queue.size > 0) {
+			queue.dequeue()();
+		}
+	};
+
+	const run = async (fn, resolve, ...args) => {
+		activeCount++;
+
+		const result = (async () => fn(...args))();
+
+		resolve(result);
+
+		try {
+			await result;
+		} catch {}
+
+		next();
+	};
+
+	const enqueue = (fn, resolve, ...args) => {
+		queue.enqueue(run.bind(null, fn, resolve, ...args));
+
+		(async () => {
+			// This function needs to wait until the next microtask before comparing
+			// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
+			// when the run function is dequeued and called. The comparison in the if-statement
+			// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
+			await Promise.resolve();
+
+			if (activeCount < concurrency && queue.size > 0) {
+				queue.dequeue()();
+			}
+		})();
+	};
+
+	const generator = (fn, ...args) => new Promise(resolve => {
+		enqueue(fn, resolve, ...args);
+	});
+
+	Object.defineProperties(generator, {
+		activeCount: {
+			get: () => activeCount
+		},
+		pendingCount: {
+			get: () => queue.size
+		},
+		clearQueue: {
+			value: () => {
+				queue.clear();
+			}
+		}
+	});
+
+	return generator;
+};
+
+module.exports = pLimit;
diff --git a/node_modules/p-limit/license b/node_modules/p-limit/license
new file mode 100644
index 00000000..fa7ceba3
--- /dev/null
+++ b/node_modules/p-limit/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Sindre Sorhus  (https://sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/node_modules/p-limit/package.json b/node_modules/p-limit/package.json
new file mode 100644
index 00000000..76514736
--- /dev/null
+++ b/node_modules/p-limit/package.json
@@ -0,0 +1,52 @@
+{
+	"name": "p-limit",
+	"version": "3.1.0",
+	"description": "Run multiple promise-returning & async functions with limited concurrency",
+	"license": "MIT",
+	"repository": "sindresorhus/p-limit",
+	"funding": "https://github.com/sponsors/sindresorhus",
+	"author": {
+		"name": "Sindre Sorhus",
+		"email": "sindresorhus@gmail.com",
+		"url": "https://sindresorhus.com"
+	},
+	"engines": {
+		"node": ">=10"
+	},
+	"scripts": {
+		"test": "xo && ava && tsd"
+	},
+	"files": [
+		"index.js",
+		"index.d.ts"
+	],
+	"keywords": [
+		"promise",
+		"limit",
+		"limited",
+		"concurrency",
+		"throttle",
+		"throat",
+		"rate",
+		"batch",
+		"ratelimit",
+		"task",
+		"queue",
+		"async",
+		"await",
+		"promises",
+		"bluebird"
+	],
+	"dependencies": {
+		"yocto-queue": "^0.1.0"
+	},
+	"devDependencies": {
+		"ava": "^2.4.0",
+		"delay": "^4.4.0",
+		"in-range": "^2.0.0",
+		"random-int": "^2.0.1",
+		"time-span": "^4.0.0",
+		"tsd": "^0.13.1",
+		"xo": "^0.35.0"
+	}
+}
diff --git a/node_modules/p-limit/readme.md b/node_modules/p-limit/readme.md
new file mode 100644
index 00000000..b283c1e6
--- /dev/null
+++ b/node_modules/p-limit/readme.md
@@ -0,0 +1,101 @@
+# p-limit
+
+> Run multiple promise-returning & async functions with limited concurrency
+
+## Install
+
+```
+$ npm install p-limit
+```
+
+## Usage
+
+```js
+const pLimit = require('p-limit');
+
+const limit = pLimit(1);
+
+const input = [
+	limit(() => fetchSomething('foo')),
+	limit(() => fetchSomething('bar')),
+	limit(() => doSomething())
+];
+
+(async () => {
+	// Only one promise is run at once
+	const result = await Promise.all(input);
+	console.log(result);
+})();
+```
+
+## API
+
+### pLimit(concurrency)
+
+Returns a `limit` function.
+
+#### concurrency
+
+Type: `number`\
+Minimum: `1`\
+Default: `Infinity`
+
+Concurrency limit.
+
+### limit(fn, ...args)
+
+Returns the promise returned by calling `fn(...args)`.
+
+#### fn
+
+Type: `Function`
+
+Promise-returning/async function.
+
+#### args
+
+Any arguments to pass through to `fn`.
+
+Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions.
+
+### limit.activeCount
+
+The number of promises that are currently running.
+
+### limit.pendingCount
+
+The number of promises that are waiting to run (i.e. their internal `fn` was not called yet).
+
+### limit.clearQueue()
+
+Discard pending promises that are waiting to run.
+
+This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app.
+
+Note: This does not cancel promises that are already running.
+
+## FAQ
+
+### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package?
+
+This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue.
+
+## Related
+
+- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control
+- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions
+- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions
+- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency
+- [More…](https://github.com/sindresorhus/promise-fun)
+
+---
+
+
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/p-locate/index.d.ts b/node_modules/p-locate/index.d.ts new file mode 100644 index 00000000..38c7e578 --- /dev/null +++ b/node_modules/p-locate/index.d.ts @@ -0,0 +1,53 @@ +declare namespace pLocate { + interface Options { + /** + Number of concurrently pending promises returned by `tester`. Minimum: `1`. + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `input` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; + } +} + +/** +Get the first fulfilled promise that satisfies the provided testing function. + +@param input - An iterable of promises/values to test. +@param tester - This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. +@returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +@example +``` +import pathExists = require('path-exists'); +import pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` +*/ +declare function pLocate( + input: Iterable | ValueType>, + tester: (element: ValueType) => PromiseLike | boolean, + options?: pLocate.Options +): Promise; + +export = pLocate; diff --git a/node_modules/p-locate/index.js b/node_modules/p-locate/index.js new file mode 100644 index 00000000..641c3dd1 --- /dev/null +++ b/node_modules/p-locate/index.js @@ -0,0 +1,50 @@ +'use strict'; +const pLimit = require('p-limit'); + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +const pLocate = async (iterable, tester, options) => { + options = { + concurrency: Infinity, + preserveOrder: true, + ...options + }; + + const limit = pLimit(options.concurrency); + + // Start all the promises concurrently with optional limit + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently + const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +}; + +module.exports = pLocate; diff --git a/node_modules/p-locate/license b/node_modules/p-locate/license new file mode 100644 index 00000000..fa7ceba3 --- /dev/null +++ b/node_modules/p-locate/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/p-locate/package.json b/node_modules/p-locate/package.json new file mode 100644 index 00000000..2d5e447f --- /dev/null +++ b/node_modules/p-locate/package.json @@ -0,0 +1,54 @@ +{ + "name": "p-locate", + "version": "5.0.0", + "description": "Get the first fulfilled promise that satisfies the provided testing function", + "license": "MIT", + "repository": "sindresorhus/p-locate", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "locate", + "find", + "finder", + "search", + "searcher", + "test", + "array", + "collection", + "iterable", + "iterator", + "race", + "fulfilled", + "fastest", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-limit": "^3.0.2" + }, + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.1.0", + "in-range": "^2.0.0", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.32.1" + } +} diff --git a/node_modules/p-locate/readme.md b/node_modules/p-locate/readme.md new file mode 100644 index 00000000..be85ec1d --- /dev/null +++ b/node_modules/p-locate/readme.md @@ -0,0 +1,93 @@ +# p-locate [![Build Status](https://travis-ci.com/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.com/github/sindresorhus/p-locate) + +> Get the first fulfilled promise that satisfies the provided testing function + +Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find). + +## Install + +``` +$ npm install p-locate +``` + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +const pathExists = require('path-exists'); +const pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` + +*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.* + +## API + +### pLocate(input, tester, options?) + +Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +#### input + +Type: `Iterable` + +An iterable of promises/values to test. + +#### tester(element) + +Type: `Function` + +This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. + +#### options + +Type: `object` + +##### concurrency + +Type: `number`\ +Default: `Infinity`\ +Minimum: `1` + +Number of concurrently pending promises returned by `tester`. + +##### preserveOrder + +Type: `boolean`\ +Default: `true` + +Preserve `input` order when searching. + +Disable this to improve performance if you don't care about the order. + +## Related + +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently +- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/parent-module/index.js b/node_modules/parent-module/index.js new file mode 100644 index 00000000..a26f953a --- /dev/null +++ b/node_modules/parent-module/index.js @@ -0,0 +1,37 @@ +'use strict'; +const callsites = require('callsites'); + +module.exports = filepath => { + const stacks = callsites(); + + if (!filepath) { + return stacks[2].getFileName(); + } + + let seenVal = false; + + // Skip the first stack as it's this function + stacks.shift(); + + for (const stack of stacks) { + const parentFilepath = stack.getFileName(); + + if (typeof parentFilepath !== 'string') { + continue; + } + + if (parentFilepath === filepath) { + seenVal = true; + continue; + } + + // Skip native modules + if (parentFilepath === 'module.js') { + continue; + } + + if (seenVal && parentFilepath !== filepath) { + return parentFilepath; + } + } +}; diff --git a/node_modules/parent-module/license b/node_modules/parent-module/license new file mode 100644 index 00000000..e7af2f77 --- /dev/null +++ b/node_modules/parent-module/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/parent-module/package.json b/node_modules/parent-module/package.json new file mode 100644 index 00000000..790333d0 --- /dev/null +++ b/node_modules/parent-module/package.json @@ -0,0 +1,46 @@ +{ + "name": "parent-module", + "version": "1.0.1", + "description": "Get the path of the parent module", + "license": "MIT", + "repository": "sindresorhus/parent-module", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "parent", + "module", + "package", + "pkg", + "caller", + "calling", + "module", + "path", + "callsites", + "callsite", + "stacktrace", + "stack", + "trace", + "function", + "file" + ], + "dependencies": { + "callsites": "^3.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "execa": "^1.0.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/parent-module/readme.md b/node_modules/parent-module/readme.md new file mode 100644 index 00000000..dffb4ce8 --- /dev/null +++ b/node_modules/parent-module/readme.md @@ -0,0 +1,67 @@ +# parent-module [![Build Status](https://travis-ci.org/sindresorhus/parent-module.svg?branch=master)](https://travis-ci.org/sindresorhus/parent-module) + +> Get the path of the parent module + +Node.js exposes `module.parent`, but it only gives you the first cached parent, which is not necessarily the actual parent. + + +## Install + +``` +$ npm install parent-module +``` + + +## Usage + +```js +// bar.js +const parentModule = require('parent-module'); + +module.exports = () => { + console.log(parentModule()); + //=> '/Users/sindresorhus/dev/unicorn/foo.js' +}; +``` + +```js +// foo.js +const bar = require('./bar'); + +bar(); +``` + + +## API + +### parentModule([filepath]) + +By default, it will return the path of the immediate parent. + +#### filepath + +Type: `string`
+Default: [`__filename`](https://nodejs.org/api/globals.html#globals_filename) + +Filepath of the module of which to get the parent path. + +Useful if you want it to work [multiple module levels down](https://github.com/sindresorhus/parent-module/tree/master/fixtures/filepath). + + +## Tip + +Combine it with [`read-pkg-up`](https://github.com/sindresorhus/read-pkg-up) to read the package.json of the parent module. + +```js +const path = require('path'); +const readPkgUp = require('read-pkg-up'); +const parentModule = require('parent-module'); + +console.log(readPkgUp.sync({cwd: path.dirname(parentModule())}).pkg); +//=> {name: 'chalk', version: '1.0.0', …} +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/path-exists/index.d.ts b/node_modules/path-exists/index.d.ts new file mode 100644 index 00000000..54b7ab8f --- /dev/null +++ b/node_modules/path-exists/index.d.ts @@ -0,0 +1,28 @@ +declare const pathExists: { + /** + Check if a path exists. + + @returns Whether the path exists. + + @example + ``` + // foo.ts + import pathExists = require('path-exists'); + + (async () => { + console.log(await pathExists('foo.ts')); + //=> true + })(); + ``` + */ + (path: string): Promise; + + /** + Synchronously check if a path exists. + + @returns Whether the path exists. + */ + sync(path: string): boolean; +}; + +export = pathExists; diff --git a/node_modules/path-exists/index.js b/node_modules/path-exists/index.js new file mode 100644 index 00000000..1943921b --- /dev/null +++ b/node_modules/path-exists/index.js @@ -0,0 +1,23 @@ +'use strict'; +const fs = require('fs'); +const {promisify} = require('util'); + +const pAccess = promisify(fs.access); + +module.exports = async path => { + try { + await pAccess(path); + return true; + } catch (_) { + return false; + } +}; + +module.exports.sync = path => { + try { + fs.accessSync(path); + return true; + } catch (_) { + return false; + } +}; diff --git a/node_modules/path-exists/license b/node_modules/path-exists/license new file mode 100644 index 00000000..e7af2f77 --- /dev/null +++ b/node_modules/path-exists/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/path-exists/package.json b/node_modules/path-exists/package.json new file mode 100644 index 00000000..0755256a --- /dev/null +++ b/node_modules/path-exists/package.json @@ -0,0 +1,39 @@ +{ + "name": "path-exists", + "version": "4.0.0", + "description": "Check if a path exists", + "license": "MIT", + "repository": "sindresorhus/path-exists", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "exists", + "exist", + "file", + "filepath", + "fs", + "filesystem", + "file-system", + "access", + "stat" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/path-exists/readme.md b/node_modules/path-exists/readme.md new file mode 100644 index 00000000..81f98454 --- /dev/null +++ b/node_modules/path-exists/readme.md @@ -0,0 +1,52 @@ +# path-exists [![Build Status](https://travis-ci.org/sindresorhus/path-exists.svg?branch=master)](https://travis-ci.org/sindresorhus/path-exists) + +> Check if a path exists + +NOTE: `fs.existsSync` has been un-deprecated in Node.js since 6.8.0. If you only need to check synchronously, this module is not needed. + +While [`fs.exists()`](https://nodejs.org/api/fs.html#fs_fs_exists_path_callback) is being [deprecated](https://github.com/iojs/io.js/issues/103), there's still a genuine use-case of being able to check if a path exists for other purposes than doing IO with it. + +Never use this before handling a file though: + +> In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to `fs.exists()` and `fs.open()`. Just open the file and handle the error when it's not there. + + +## Install + +``` +$ npm install path-exists +``` + + +## Usage + +```js +// foo.js +const pathExists = require('path-exists'); + +(async () => { + console.log(await pathExists('foo.js')); + //=> true +})(); +``` + + +## API + +### pathExists(path) + +Returns a `Promise` of whether the path exists. + +### pathExists.sync(path) + +Returns a `boolean` of whether the path exists. + + +## Related + +- [path-exists-cli](https://github.com/sindresorhus/path-exists-cli) - CLI for this module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/path-key/index.d.ts b/node_modules/path-key/index.d.ts new file mode 100644 index 00000000..7c575d19 --- /dev/null +++ b/node_modules/path-key/index.d.ts @@ -0,0 +1,40 @@ +/// + +declare namespace pathKey { + interface Options { + /** + Use a custom environment variables object. Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env). + */ + readonly env?: {[key: string]: string | undefined}; + + /** + Get the PATH key for a specific platform. Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform). + */ + readonly platform?: NodeJS.Platform; + } +} + +declare const pathKey: { + /** + Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform. + + @example + ``` + import pathKey = require('path-key'); + + const key = pathKey(); + //=> 'PATH' + + const PATH = process.env[key]; + //=> '/usr/local/bin:/usr/bin:/bin' + ``` + */ + (options?: pathKey.Options): string; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function pathKey(options?: pathKey.Options): string; + // export = pathKey; + default: typeof pathKey; +}; + +export = pathKey; diff --git a/node_modules/path-key/index.js b/node_modules/path-key/index.js new file mode 100644 index 00000000..0cf6415d --- /dev/null +++ b/node_modules/path-key/index.js @@ -0,0 +1,16 @@ +'use strict'; + +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +module.exports = pathKey; +// TODO: Remove this for the next major release +module.exports.default = pathKey; diff --git a/node_modules/path-key/license b/node_modules/path-key/license new file mode 100644 index 00000000..e7af2f77 --- /dev/null +++ b/node_modules/path-key/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/path-key/package.json b/node_modules/path-key/package.json new file mode 100644 index 00000000..c8cbd383 --- /dev/null +++ b/node_modules/path-key/package.json @@ -0,0 +1,39 @@ +{ + "name": "path-key", + "version": "3.1.1", + "description": "Get the PATH environment variable key cross-platform", + "license": "MIT", + "repository": "sindresorhus/path-key", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "key", + "environment", + "env", + "variable", + "var", + "get", + "cross-platform", + "windows" + ], + "devDependencies": { + "@types/node": "^11.13.0", + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/path-key/readme.md b/node_modules/path-key/readme.md new file mode 100644 index 00000000..a9052d7a --- /dev/null +++ b/node_modules/path-key/readme.md @@ -0,0 +1,61 @@ +# path-key [![Build Status](https://travis-ci.org/sindresorhus/path-key.svg?branch=master)](https://travis-ci.org/sindresorhus/path-key) + +> Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform + +It's usually `PATH`, but on Windows it can be any casing like `Path`... + + +## Install + +``` +$ npm install path-key +``` + + +## Usage + +```js +const pathKey = require('path-key'); + +const key = pathKey(); +//=> 'PATH' + +const PATH = process.env[key]; +//=> '/usr/local/bin:/usr/bin:/bin' +``` + + +## API + +### pathKey(options?) + +#### options + +Type: `object` + +##### env + +Type: `object`
+Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env) + +Use a custom environment variables object. + +#### platform + +Type: `string`
+Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform) + +Get the PATH key for a specific platform. + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/picomatch/CHANGELOG.md b/node_modules/picomatch/CHANGELOG.md new file mode 100644 index 00000000..8ccc6c1b --- /dev/null +++ b/node_modules/picomatch/CHANGELOG.md @@ -0,0 +1,136 @@ +# Release history + +**All notable changes to this project will be documented in this file.** + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +
+ Guiding Principles + +- Changelogs are for humans, not machines. +- There should be an entry for every single version. +- The same types of changes should be grouped. +- Versions and sections should be linkable. +- The latest version comes first. +- The release date of each versions is displayed. +- Mention whether you follow Semantic Versioning. + +
+ +
+ Types of changes + +Changelog entries are classified using the following labels _(from [keep-a-changelog](http://keepachangelog.com/)_): + +- `Added` for new features. +- `Changed` for changes in existing functionality. +- `Deprecated` for soon-to-be removed features. +- `Removed` for now removed features. +- `Fixed` for any bug fixes. +- `Security` in case of vulnerabilities. + +
+ +## 2.3.1 (2022-01-02) + +### Fixed + +* Fixes bug when a pattern containing an expression after the closing parenthesis (`/!(*.d).{ts,tsx}`) was incorrectly converted to regexp ([9f241ef](https://github.com/micromatch/picomatch/commit/9f241ef)). + +### Changed + +* Some documentation improvements ([f81d236](https://github.com/micromatch/picomatch/commit/f81d236), [421e0e7](https://github.com/micromatch/picomatch/commit/421e0e7)). + +## 2.3.0 (2021-05-21) + +### Fixed + +* Fixes bug where file names with two dots were not being matched consistently with negation extglobs containing a star ([56083ef](https://github.com/micromatch/picomatch/commit/56083ef)) + +## 2.2.3 (2021-04-10) + +### Fixed + +* Do not skip pattern seperator for square brackets ([fb08a30](https://github.com/micromatch/picomatch/commit/fb08a30)). +* Set negatedExtGlob also if it does not span the whole pattern ([032e3f5](https://github.com/micromatch/picomatch/commit/032e3f5)). + +## 2.2.2 (2020-03-21) + +### Fixed + +* Correctly handle parts of the pattern after parentheses in the `scan` method ([e15b920](https://github.com/micromatch/picomatch/commit/e15b920)). + +## 2.2.1 (2020-01-04) + +* Fixes [#49](https://github.com/micromatch/picomatch/issues/49), so that braces with no sets or ranges are now propertly treated as literals. + +## 2.2.0 (2020-01-04) + +* Disable fastpaths mode for the parse method ([5b8d33f](https://github.com/micromatch/picomatch/commit/5b8d33f)) +* Add `tokens`, `slashes`, and `parts` to the object returned by `picomatch.scan()`. + +## 2.1.0 (2019-10-31) + +* add benchmarks for scan ([4793b92](https://github.com/micromatch/picomatch/commit/4793b92)) +* Add eslint object-curly-spacing rule ([707c650](https://github.com/micromatch/picomatch/commit/707c650)) +* Add prefer-const eslint rule ([5c7501c](https://github.com/micromatch/picomatch/commit/5c7501c)) +* Add support for nonegate in scan API ([275c9b9](https://github.com/micromatch/picomatch/commit/275c9b9)) +* Change lets to consts. Move root import up. ([4840625](https://github.com/micromatch/picomatch/commit/4840625)) +* closes https://github.com/micromatch/picomatch/issues/21 ([766bcb0](https://github.com/micromatch/picomatch/commit/766bcb0)) +* Fix "Extglobs" table in readme ([eb19da8](https://github.com/micromatch/picomatch/commit/eb19da8)) +* fixes https://github.com/micromatch/picomatch/issues/20 ([9caca07](https://github.com/micromatch/picomatch/commit/9caca07)) +* fixes https://github.com/micromatch/picomatch/issues/26 ([fa58f45](https://github.com/micromatch/picomatch/commit/fa58f45)) +* Lint test ([d433a34](https://github.com/micromatch/picomatch/commit/d433a34)) +* lint unit tests ([0159b55](https://github.com/micromatch/picomatch/commit/0159b55)) +* Make scan work with noext ([6c02e03](https://github.com/micromatch/picomatch/commit/6c02e03)) +* minor linting ([c2a2b87](https://github.com/micromatch/picomatch/commit/c2a2b87)) +* minor parser improvements ([197671d](https://github.com/micromatch/picomatch/commit/197671d)) +* remove eslint since it... ([07876fa](https://github.com/micromatch/picomatch/commit/07876fa)) +* remove funding file ([8ebe96d](https://github.com/micromatch/picomatch/commit/8ebe96d)) +* Remove unused funks ([cbc6d54](https://github.com/micromatch/picomatch/commit/cbc6d54)) +* Run eslint during pretest, fix existing eslint findings ([0682367](https://github.com/micromatch/picomatch/commit/0682367)) +* support `noparen` in scan ([3d37569](https://github.com/micromatch/picomatch/commit/3d37569)) +* update changelog ([7b34e77](https://github.com/micromatch/picomatch/commit/7b34e77)) +* update travis ([777f038](https://github.com/micromatch/picomatch/commit/777f038)) +* Use eslint-disable-next-line instead of eslint-disable ([4e7c1fd](https://github.com/micromatch/picomatch/commit/4e7c1fd)) + +## 2.0.7 (2019-05-14) + +* 2.0.7 ([9eb9a71](https://github.com/micromatch/picomatch/commit/9eb9a71)) +* supports lookbehinds ([1f63f7e](https://github.com/micromatch/picomatch/commit/1f63f7e)) +* update .verb.md file with typo change ([2741279](https://github.com/micromatch/picomatch/commit/2741279)) +* fix: typo in README ([0753e44](https://github.com/micromatch/picomatch/commit/0753e44)) + +## 2.0.4 (2019-04-10) + +### Fixed + +- Readme link [fixed](https://github.com/micromatch/picomatch/pull/13/commits/a96ab3aa2b11b6861c23289964613d85563b05df) by @danez. +- `options.capture` now works as expected when fastpaths are enabled. See https://github.com/micromatch/picomatch/pull/12/commits/26aefd71f1cfaf95c37f1c1fcab68a693b037304. Thanks to @DrPizza. + +## 2.0.0 (2019-04-10) + +### Added + +- Adds support for `options.onIgnore`. See the readme for details +- Adds support for `options.onResult`. See the readme for details + +### Breaking changes + +- The unixify option was renamed to `windows` +- caching and all related options and methods have been removed + +## 1.0.0 (2018-11-05) + +- adds `.onMatch` option +- improvements to `.scan` method +- numerous improvements and optimizations for matching and parsing +- better windows path handling + +## 0.1.0 - 2017-04-13 + +First release. + + +[keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog diff --git a/node_modules/picomatch/LICENSE b/node_modules/picomatch/LICENSE new file mode 100644 index 00000000..3608dca2 --- /dev/null +++ b/node_modules/picomatch/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/picomatch/README.md b/node_modules/picomatch/README.md new file mode 100644 index 00000000..b0526e28 --- /dev/null +++ b/node_modules/picomatch/README.md @@ -0,0 +1,708 @@ +

Picomatch

+ +

+ +version + + +test status + + +coverage status + + +downloads + +

+ +
+
+ +

+Blazing fast and accurate glob matcher written in JavaScript.
+No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions. +

+ +
+
+ +## Why picomatch? + +* **Lightweight** - No dependencies +* **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function. +* **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps) +* **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files) +* **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes. +* **Well tested** - Thousands of unit tests + +See the [library comparison](#library-comparisons) to other libraries. + +
+
+ +## Table of Contents + +
Click to expand + +- [Install](#install) +- [Usage](#usage) +- [API](#api) + * [picomatch](#picomatch) + * [.test](#test) + * [.matchBase](#matchbase) + * [.isMatch](#ismatch) + * [.parse](#parse) + * [.scan](#scan) + * [.compileRe](#compilere) + * [.makeRe](#makere) + * [.toRegex](#toregex) +- [Options](#options) + * [Picomatch options](#picomatch-options) + * [Scan Options](#scan-options) + * [Options Examples](#options-examples) +- [Globbing features](#globbing-features) + * [Basic globbing](#basic-globbing) + * [Advanced globbing](#advanced-globbing) + * [Braces](#braces) + * [Matching special characters as literals](#matching-special-characters-as-literals) +- [Library Comparisons](#library-comparisons) +- [Benchmarks](#benchmarks) +- [Philosophies](#philosophies) +- [About](#about) + * [Author](#author) + * [License](#license) + +_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ + +
+ +
+
+ +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +npm install --save picomatch +``` + +
+ +## Usage + +The main export is a function that takes a glob pattern and an options object and returns a function for matching strings. + +```js +const pm = require('picomatch'); +const isMatch = pm('*.js'); + +console.log(isMatch('abcd')); //=> false +console.log(isMatch('a.js')); //=> true +console.log(isMatch('a.md')); //=> false +console.log(isMatch('a/b.js')); //=> false +``` + +
+ +## API + +### [picomatch](lib/picomatch.js#L32) + +Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information. + +**Params** + +* `globs` **{String|Array}**: One or more glob patterns. +* `options` **{Object=}** +* `returns` **{Function=}**: Returns a matcher function. + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch(glob[, options]); + +const isMatch = picomatch('*.!(*a)'); +console.log(isMatch('a.a')); //=> false +console.log(isMatch('a.b')); //=> true +``` + +### [.test](lib/picomatch.js#L117) + +Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string. + +**Params** + +* `input` **{String}**: String to test. +* `regex` **{RegExp}** +* `returns` **{Object}**: Returns an object with matching info. + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.test(input, regex[, options]); + +console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); +// { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } +``` + +### [.matchBase](lib/picomatch.js#L161) + +Match the basename of a filepath. + +**Params** + +* `input` **{String}**: String to test. +* `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe). +* `returns` **{Boolean}** + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.matchBase(input, glob[, options]); +console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true +``` + +### [.isMatch](lib/picomatch.js#L183) + +Returns true if **any** of the given glob `patterns` match the specified `string`. + +**Params** + +* **{String|Array}**: str The string to test. +* **{String|Array}**: patterns One or more glob patterns to use for matching. +* **{Object}**: See available [options](#options). +* `returns` **{Boolean}**: Returns true if any patterns match `str` + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.isMatch(string, patterns[, options]); + +console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true +console.log(picomatch.isMatch('a.a', 'b.*')); //=> false +``` + +### [.parse](lib/picomatch.js#L199) + +Parse a glob pattern to create the source string for a regular expression. + +**Params** + +* `pattern` **{String}** +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string. + +**Example** + +```js +const picomatch = require('picomatch'); +const result = picomatch.parse(pattern[, options]); +``` + +### [.scan](lib/picomatch.js#L231) + +Scan a glob pattern to separate the pattern into segments. + +**Params** + +* `input` **{String}**: Glob pattern to scan. +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.scan(input[, options]); + +const result = picomatch.scan('!./foo/*.js'); +console.log(result); +{ prefix: '!./', + input: '!./foo/*.js', + start: 3, + base: 'foo', + glob: '*.js', + isBrace: false, + isBracket: false, + isGlob: true, + isExtglob: false, + isGlobstar: false, + negated: true } +``` + +### [.compileRe](lib/picomatch.js#L245) + +Compile a regular expression from the `state` object returned by the +[parse()](#parse) method. + +**Params** + +* `state` **{Object}** +* `options` **{Object}** +* `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser. +* `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. +* `returns` **{RegExp}** + +### [.makeRe](lib/picomatch.js#L286) + +Create a regular expression from a parsed glob pattern. + +**Params** + +* `state` **{String}**: The object returned from the `.parse` method. +* `options` **{Object}** +* `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. +* `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression. +* `returns` **{RegExp}**: Returns a regex created from the given pattern. + +**Example** + +```js +const picomatch = require('picomatch'); +const state = picomatch.parse('*.js'); +// picomatch.compileRe(state[, options]); + +console.log(picomatch.compileRe(state)); +//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ +``` + +### [.toRegex](lib/picomatch.js#L321) + +Create a regular expression from the given regex source string. + +**Params** + +* `source` **{String}**: Regular expression source string. +* `options` **{Object}** +* `returns` **{RegExp}** + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.toRegex(source[, options]); + +const { output } = picomatch.parse('*.js'); +console.log(picomatch.toRegex(output)); +//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ +``` + +
+ +## Options + +### Picomatch options + +The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API. + +| **Option** | **Type** | **Default value** | **Description** | +| --- | --- | --- | --- | +| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | +| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | +| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | +| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | +| `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | +| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | +| `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true | +| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. | +| `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. | +| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | +| `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | +| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | +| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | +| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | +| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | +| `matchBase` | `boolean` | `false` | Alias for `basename` | +| `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | +| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | +| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | +| `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. | +| `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | +| `noext` | `boolean` | `false` | Alias for `noextglob` | +| `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) | +| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | +| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | +| `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | +| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | +| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | +| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | +| `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). | +| `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | +| `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. | +| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | +| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | +| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | +| `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. | +| `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. | + +picomatch has automatic detection for regex positive and negative lookbehinds. If the pattern contains a negative lookbehind, you must be using Node.js >= 8.10 or else picomatch will throw an error. + +### Scan Options + +In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method. + +| **Option** | **Type** | **Default value** | **Description** | +| --- | --- | --- | --- | +| `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern | +| `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true | + +**Example** + +```js +const picomatch = require('picomatch'); +const result = picomatch.scan('!./foo/*.js', { tokens: true }); +console.log(result); +// { +// prefix: '!./', +// input: '!./foo/*.js', +// start: 3, +// base: 'foo', +// glob: '*.js', +// isBrace: false, +// isBracket: false, +// isGlob: true, +// isExtglob: false, +// isGlobstar: false, +// negated: true, +// maxDepth: 2, +// tokens: [ +// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true }, +// { value: 'foo', depth: 1, isGlob: false }, +// { value: '*.js', depth: 1, isGlob: true } +// ], +// slashes: [ 2, 6 ], +// parts: [ 'foo', '*.js' ] +// } +``` + +
+ +### Options Examples + +#### options.expandRange + +**Type**: `function` + +**Default**: `undefined` + +Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. + +**Example** + +The following example shows how to create a glob that matches a folder + +```js +const fill = require('fill-range'); +const regex = pm.makeRe('foo/{01..25}/bar', { + expandRange(a, b) { + return `(${fill(a, b, { toRegex: true })})`; + } +}); + +console.log(regex); +//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ + +console.log(regex.test('foo/00/bar')) // false +console.log(regex.test('foo/01/bar')) // true +console.log(regex.test('foo/10/bar')) // true +console.log(regex.test('foo/22/bar')) // true +console.log(regex.test('foo/25/bar')) // true +console.log(regex.test('foo/26/bar')) // false +``` + +#### options.format + +**Type**: `function` + +**Default**: `undefined` + +Custom function for formatting strings before they're matched. + +**Example** + +```js +// strip leading './' from strings +const format = str => str.replace(/^\.\//, ''); +const isMatch = picomatch('foo/*.js', { format }); +console.log(isMatch('./foo/bar.js')); //=> true +``` + +#### options.onMatch + +```js +const onMatch = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = picomatch('*', { onMatch }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +#### options.onIgnore + +```js +const onIgnore = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = picomatch('*', { onIgnore, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +#### options.onResult + +```js +const onResult = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = picomatch('*', { onResult, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +
+
+ +## Globbing features + +* [Basic globbing](#basic-globbing) (Wildcard matching) +* [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching) + +### Basic globbing + +| **Character** | **Description** | +| --- | --- | +| `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. | +| `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` on Windows) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. | +| `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. | +| `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. | + +#### Matching behavior vs. Bash + +Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions: + +* Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`. +* Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`. + +
+ +### Advanced globbing + +* [extglobs](#extglobs) +* [POSIX brackets](#posix-brackets) +* [Braces](#brace-expansion) + +#### Extglobs + +| **Pattern** | **Description** | +| --- | --- | +| `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` | +| `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` | +| `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` | +| `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` | +| `!(pattern)` | Match _anything but_ `pattern` | + +**Examples** + +```js +const pm = require('picomatch'); + +// *(pattern) matches ZERO or more of "pattern" +console.log(pm.isMatch('a', 'a*(z)')); // true +console.log(pm.isMatch('az', 'a*(z)')); // true +console.log(pm.isMatch('azzz', 'a*(z)')); // true + +// +(pattern) matches ONE or more of "pattern" +console.log(pm.isMatch('a', 'a*(z)')); // true +console.log(pm.isMatch('az', 'a*(z)')); // true +console.log(pm.isMatch('azzz', 'a*(z)')); // true + +// supports multiple extglobs +console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false + +// supports nested extglobs +console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true +``` + +#### POSIX brackets + +POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true. + +**Enable POSIX bracket support** + +```js +console.log(pm.makeRe('[[:word:]]+', { posix: true })); +//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/ +``` + +**Supported POSIX classes** + +The following named POSIX bracket expressions are supported: + +* `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]` +* `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`. +* `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`. +* `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`. +* `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`. +* `[:digit:]` - Numerical digits, equivalent to `[0-9]`. +* `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`. +* `[:lower:]` - Lowercase letters, equivalent to `[a-z]`. +* `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`. +* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`. +* `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`. +* `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`. +* `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`. +* `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`. + +See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information. + +### Braces + +Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces. + +### Matching special characters as literals + +If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes: + +**Special Characters** + +Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms. + +To match any of the following characters as literals: `$^*+?()[] + +Examples: + +```js +console.log(pm.makeRe('foo/bar \\(1\\)')); +console.log(pm.makeRe('foo/bar \\(1\\)')); +``` + +
+
+ +## Library Comparisons + +The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets). + +| **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - | +| Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - | +| Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - | +| Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - | +| Extglobs | partial | ✔ | ✔ | - | ✔ | - | - | +| Posix brackets | - | ✔ | ✔ | - | - | - | ✔ | +| Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ | +| File system operations | - | - | - | - | - | - | - | + +
+
+ +## Benchmarks + +Performance comparison of picomatch and minimatch. + +``` +# .makeRe star + picomatch x 1,993,050 ops/sec ±0.51% (91 runs sampled) + minimatch x 627,206 ops/sec ±1.96% (87 runs sampled)) + +# .makeRe star; dot=true + picomatch x 1,436,640 ops/sec ±0.62% (91 runs sampled) + minimatch x 525,876 ops/sec ±0.60% (88 runs sampled) + +# .makeRe globstar + picomatch x 1,592,742 ops/sec ±0.42% (90 runs sampled) + minimatch x 962,043 ops/sec ±1.76% (91 runs sampled)d) + +# .makeRe globstars + picomatch x 1,615,199 ops/sec ±0.35% (94 runs sampled) + minimatch x 477,179 ops/sec ±1.33% (91 runs sampled) + +# .makeRe with leading star + picomatch x 1,220,856 ops/sec ±0.40% (92 runs sampled) + minimatch x 453,564 ops/sec ±1.43% (94 runs sampled) + +# .makeRe - basic braces + picomatch x 392,067 ops/sec ±0.70% (90 runs sampled) + minimatch x 99,532 ops/sec ±2.03% (87 runs sampled)) +``` + +
+
+ +## Philosophies + +The goal of this library is to be blazing fast, without compromising on accuracy. + +**Accuracy** + +The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`. + +Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements. + +**Performance** + +Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer. + +
+
+ +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). diff --git a/node_modules/picomatch/index.js b/node_modules/picomatch/index.js new file mode 100644 index 00000000..d2f2bc59 --- /dev/null +++ b/node_modules/picomatch/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/picomatch'); diff --git a/node_modules/picomatch/lib/constants.js b/node_modules/picomatch/lib/constants.js new file mode 100644 index 00000000..a62ef387 --- /dev/null +++ b/node_modules/picomatch/lib/constants.js @@ -0,0 +1,179 @@ +'use strict'; + +const path = require('path'); +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +module.exports = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + SEP: path.sep, + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; diff --git a/node_modules/picomatch/lib/parse.js b/node_modules/picomatch/lib/parse.js new file mode 100644 index 00000000..58269d01 --- /dev/null +++ b/node_modules/picomatch/lib/parse.js @@ -0,0 +1,1091 @@ +'use strict'; + +const constants = require('./constants'); +const utils = require('./utils'); + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils.escapeRegex(v)).join('..'); + } + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + const win32 = utils.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils.isWindows(options); + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +module.exports = parse; diff --git a/node_modules/picomatch/lib/picomatch.js b/node_modules/picomatch/lib/picomatch.js new file mode 100644 index 00000000..782d8094 --- /dev/null +++ b/node_modules/picomatch/lib/picomatch.js @@ -0,0 +1,342 @@ +'use strict'; + +const path = require('path'); +const scan = require('./scan'); +const parse = require('./parse'); +const utils = require('./utils'); +const constants = require('./constants'); +const isObject = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils.isWindows(options); + const regex = isState + ? picomatch.compileRe(glob, options) + : picomatch.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch.scan = (input, options) => scan(input, options); + +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ + +picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + + return regex; +}; + +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + let parsed = { negated: false, fastpaths: true }; + + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse(input, options); + } + + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch.constants = constants; + +/** + * Expose "picomatch" + */ + +module.exports = picomatch; diff --git a/node_modules/picomatch/lib/scan.js b/node_modules/picomatch/lib/scan.js new file mode 100644 index 00000000..e59cd7a1 --- /dev/null +++ b/node_modules/picomatch/lib/scan.js @@ -0,0 +1,391 @@ +'use strict'; + +const utils = require('./utils'); +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = require('./constants'); + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +module.exports = scan; diff --git a/node_modules/picomatch/lib/utils.js b/node_modules/picomatch/lib/utils.js new file mode 100644 index 00000000..c3ca766a --- /dev/null +++ b/node_modules/picomatch/lib/utils.js @@ -0,0 +1,64 @@ +'use strict'; + +const path = require('path'); +const win32 = process.platform === 'win32'; +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = require('./constants'); + +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; + +exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; +}; + +exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path.sep === '\\'; +}; + +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; + +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; + +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; +}; diff --git a/node_modules/picomatch/package.json b/node_modules/picomatch/package.json new file mode 100644 index 00000000..3db22d40 --- /dev/null +++ b/node_modules/picomatch/package.json @@ -0,0 +1,81 @@ +{ + "name": "picomatch", + "description": "Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.", + "version": "2.3.1", + "homepage": "https://github.com/micromatch/picomatch", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "funding": "https://github.com/sponsors/jonschlinkert", + "repository": "micromatch/picomatch", + "bugs": { + "url": "https://github.com/micromatch/picomatch/issues" + }, + "license": "MIT", + "files": [ + "index.js", + "lib" + ], + "main": "index.js", + "engines": { + "node": ">=8.6" + }, + "scripts": { + "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .", + "mocha": "mocha --reporter dot", + "test": "npm run lint && npm run mocha", + "test:ci": "npm run test:cover", + "test:cover": "nyc npm run mocha" + }, + "devDependencies": { + "eslint": "^6.8.0", + "fill-range": "^7.0.1", + "gulp-format-md": "^2.0.0", + "mocha": "^6.2.2", + "nyc": "^15.0.0", + "time-require": "github:jonschlinkert/time-require" + }, + "keywords": [ + "glob", + "match", + "picomatch" + ], + "nyc": { + "reporter": [ + "html", + "lcov", + "text-summary" + ] + }, + "verb": { + "toc": { + "render": true, + "method": "preWrite", + "maxdepth": 3 + }, + "layout": "empty", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "braces", + "micromatch" + ] + }, + "reflinks": [ + "braces", + "expand-brackets", + "extglob", + "fill-range", + "micromatch", + "minimatch", + "nanomatch", + "picomatch" + ] + } +} diff --git a/node_modules/prelude-ls/CHANGELOG.md b/node_modules/prelude-ls/CHANGELOG.md new file mode 100644 index 00000000..71b8a0f2 --- /dev/null +++ b/node_modules/prelude-ls/CHANGELOG.md @@ -0,0 +1,108 @@ +# 1.2.1 +- fix version + +# 1.2.0 +- add `List.remove` +- build with LiveScript 1.6.0 +- update dependencies +- remove coverage calculation + +# 1.1.2 +- add `Func.memoize` +- fix `zip-all` and `zip-with-all` corner case (no input) +- build with LiveScript 1.4.0 + +# 1.1.1 +- curry `unique-by`, `minimum-by` + +# 1.1.0 +- added `List` functions: `maximum-by`, `minimum-by`, `unique-by` +- added `List` functions: `at`, `elem-index`, `elem-indices`, `find-index`, `find-indices` +- added `Str` functions: `capitalize`, `camelize`, `dasherize` +- added `Func` function: `over` - eg. ``same-length = (==) `over` (.length)`` +- exported `Str.repeat` through main `prelude` object +- fixed definition of `foldr` and `foldr1`, the new correct definition is backwards incompatible with the old, incorrect one +- fixed issue with `fix` +- improved code coverage + +# 1.0.3 +- build browser versions + +# 1.0.2 +- bug fix for `flatten` - slight change with bug fix, flattens arrays only, not array-like objects + +# 1.0.1 +- bug fixes for `drop-while` and `take-while` + +# 1.0.0 +* massive update - separated functions into separate modules +* functions do not accept multiple types anymore - use different versions in their respective modules in some cases (eg. `Obj.map`), or use `chars` or `values` in other cases to transform into a list +* objects are no longer transformed into functions, simply use `(obj.)` in LiveScript to do that +* browser version now using browserify - use `prelude = require('prelude-ls')` +* added `compact`, `split`, `flatten`, `difference`, `intersection`, `union`, `count-by`, `group-by`, `chars`, `unchars`, `apply` +* added `lists-to-obj` which takes a list of keys and list of values and zips them up into an object, and the converse `obj-to-lists` +* added `pairs-to-obj` which takes a list of pairs (2 element lists) and creates an object, and the converse `obj-to-pairs` +* removed `cons`, `append` - use the concat operator +* removed `compose` - use the compose operator +* removed `obj-to-func` - use partially applied access (eg. `(obj.)`) +* removed `length` - use `(.length)` +* `sort-by` renamed to `sort-with` +* added new `sort-by` +* removed `compare` - just use the new `sort-by` +* `break-it` renamed `break-list`, (`Str.break-str` for the string version) +* added `Str.repeat` which creates a new string by repeating the input n times +* `unfold` as alias to `unfoldr` is no longer used +* fixed up style and compiled with LiveScript 1.1.1 +* use Make instead of Slake +* greatly improved tests + +# 0.6.0 +* fixed various bugs +* added `fix`, a fixpoint (Y combinator) for anonymous recursive functions +* added `unfoldr` (alias `unfold`) +* calling `replicate` with a string now returns a list of strings +* removed `partial`, just use native partial application in LiveScript using the `_` placeholder, or currying +* added `sort`, `sortBy`, and `compare` + +# 0.5.0 +* removed `lookup` - use (.prop) +* removed `call` - use (.func arg1, arg2) +* removed `pluck` - use map (.prop), xs +* fixed buys wtih `head` and `last` +* added non-minifed browser version, as `prelude-browser.js` +* renamed `prelude-min.js` to `prelude-browser-min.js` +* renamed `zip` to `zipAll` +* renamed `zipWith` to `zipAllWith` +* added `zip`, a curried zip that takes only two arguments +* added `zipWith`, a curried zipWith that takes only two arguments + +# 0.4.0 +* added `parition` function +* added `curry` function +* removed `elem` function (use `in`) +* removed `notElem` function (use `not in`) + +# 0.3.0 +* added `listToObject` +* added `unique` +* added `objToFunc` +* added support for using strings in map and the like +* added support for using objects in map and the like +* added ability to use objects instead of functions in certain cases +* removed `error` (just use throw) +* added `tau` constant +* added `join` +* added `values` +* added `keys` +* added `partial` +* renamed `log` to `ln` +* added alias to `head`: `first` +* added `installPrelude` helper + +# 0.2.0 +* removed functions that simply warp operators as you can now use operators as functions in LiveScript +* `min/max` are now curried and take only 2 arguments +* added `call` + +# 0.1.0 +* initial public release diff --git a/node_modules/prelude-ls/LICENSE b/node_modules/prelude-ls/LICENSE new file mode 100644 index 00000000..525b1185 --- /dev/null +++ b/node_modules/prelude-ls/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) George Zahariev + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/prelude-ls/README.md b/node_modules/prelude-ls/README.md new file mode 100644 index 00000000..fabc212e --- /dev/null +++ b/node_modules/prelude-ls/README.md @@ -0,0 +1,15 @@ +# prelude.ls [![Build Status](https://travis-ci.org/gkz/prelude-ls.png?branch=master)](https://travis-ci.org/gkz/prelude-ls) + +is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, LiveScript. + +See **[the prelude.ls site](http://preludels.com)** for examples, a reference, and more. + +You can install via npm `npm install prelude-ls` + +### Development + +`make test` to test + +`make build` to build `lib` from `src` + +`make build-browser` to build browser versions diff --git a/node_modules/prelude-ls/lib/Func.js b/node_modules/prelude-ls/lib/Func.js new file mode 100644 index 00000000..09777a8c --- /dev/null +++ b/node_modules/prelude-ls/lib/Func.js @@ -0,0 +1,69 @@ +// Generated by LiveScript 1.6.0 +var apply, curry, flip, fix, over, memoize, toString$ = {}.toString; +apply = curry$(function(f, list){ + return f.apply(null, list); +}); +curry = function(f){ + return curry$(f); +}; +flip = curry$(function(f, x, y){ + return f(y, x); +}); +fix = function(f){ + return function(g){ + return function(){ + return f(g(g)).apply(null, arguments); + }; + }(function(g){ + return function(){ + return f(g(g)).apply(null, arguments); + }; + }); +}; +over = curry$(function(f, g, x, y){ + return f(g(x), g(y)); +}); +memoize = function(f){ + var memo; + memo = {}; + return function(){ + var args, res$, i$, to$, key, arg; + res$ = []; + for (i$ = 0, to$ = arguments.length; i$ < to$; ++i$) { + res$.push(arguments[i$]); + } + args = res$; + key = (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = args).length; i$ < len$; ++i$) { + arg = ref$[i$]; + results$.push(arg + toString$.call(arg).slice(8, -1)); + } + return results$; + }()).join(''); + return memo[key] = key in memo + ? memo[key] + : f.apply(null, args); + }; +}; +module.exports = { + curry: curry, + flip: flip, + fix: fix, + apply: apply, + over: over, + memoize: memoize +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/node_modules/prelude-ls/lib/List.js b/node_modules/prelude-ls/lib/List.js new file mode 100644 index 00000000..d2e41ab1 --- /dev/null +++ b/node_modules/prelude-ls/lib/List.js @@ -0,0 +1,716 @@ +// Generated by LiveScript 1.6.0 +var each, map, compact, filter, reject, remove, partition, find, head, first, tail, last, initial, empty, reverse, unique, uniqueBy, fold, foldl, fold1, foldl1, foldr, foldr1, unfoldr, concat, concatMap, flatten, difference, intersection, union, countBy, groupBy, andList, orList, any, all, sort, sortWith, sortBy, sum, product, mean, average, maximum, minimum, maximumBy, minimumBy, scan, scanl, scan1, scanl1, scanr, scanr1, slice, take, drop, splitAt, takeWhile, dropWhile, span, breakList, zip, zipWith, zipAll, zipAllWith, at, elemIndex, elemIndices, findIndex, findIndices, toString$ = {}.toString; +each = curry$(function(f, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + f(x); + } + return xs; +}); +map = curry$(function(f, xs){ + var i$, len$, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + results$.push(f(x)); + } + return results$; +}); +compact = function(xs){ + var i$, len$, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (x) { + results$.push(x); + } + } + return results$; +}; +filter = curry$(function(f, xs){ + var i$, len$, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (f(x)) { + results$.push(x); + } + } + return results$; +}); +reject = curry$(function(f, xs){ + var i$, len$, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (!f(x)) { + results$.push(x); + } + } + return results$; +}); +remove = curry$(function(el, xs){ + var i, x$; + i = elemIndex(el, xs); + x$ = xs.slice(); + if (i != null) { + x$.splice(i, 1); + } + return x$; +}); +partition = curry$(function(f, xs){ + var passed, failed, i$, len$, x; + passed = []; + failed = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + (f(x) ? passed : failed).push(x); + } + return [passed, failed]; +}); +find = curry$(function(f, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (f(x)) { + return x; + } + } +}); +head = first = function(xs){ + return xs[0]; +}; +tail = function(xs){ + if (!xs.length) { + return; + } + return xs.slice(1); +}; +last = function(xs){ + return xs[xs.length - 1]; +}; +initial = function(xs){ + if (!xs.length) { + return; + } + return xs.slice(0, -1); +}; +empty = function(xs){ + return !xs.length; +}; +reverse = function(xs){ + return xs.concat().reverse(); +}; +unique = function(xs){ + var result, i$, len$, x; + result = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (!in$(x, result)) { + result.push(x); + } + } + return result; +}; +uniqueBy = curry$(function(f, xs){ + var seen, i$, len$, x, val, results$ = []; + seen = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + val = f(x); + if (in$(val, seen)) { + continue; + } + seen.push(val); + results$.push(x); + } + return results$; +}); +fold = foldl = curry$(function(f, memo, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + memo = f(memo, x); + } + return memo; +}); +fold1 = foldl1 = curry$(function(f, xs){ + return fold(f, xs[0], xs.slice(1)); +}); +foldr = curry$(function(f, memo, xs){ + var i$, x; + for (i$ = xs.length - 1; i$ >= 0; --i$) { + x = xs[i$]; + memo = f(x, memo); + } + return memo; +}); +foldr1 = curry$(function(f, xs){ + return foldr(f, xs[xs.length - 1], xs.slice(0, -1)); +}); +unfoldr = curry$(function(f, b){ + var result, x, that; + result = []; + x = b; + while ((that = f(x)) != null) { + result.push(that[0]); + x = that[1]; + } + return result; +}); +concat = function(xss){ + return [].concat.apply([], xss); +}; +concatMap = curry$(function(f, xs){ + var x; + return [].concat.apply([], (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) { + x = ref$[i$]; + results$.push(f(x)); + } + return results$; + }())); +}); +flatten = function(xs){ + var x; + return [].concat.apply([], (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (toString$.call(x).slice(8, -1) === 'Array') { + results$.push(flatten(x)); + } else { + results$.push(x); + } + } + return results$; + }())); +}; +difference = function(xs){ + var yss, res$, i$, to$, results, len$, x, j$, len1$, ys; + res$ = []; + for (i$ = 1, to$ = arguments.length; i$ < to$; ++i$) { + res$.push(arguments[i$]); + } + yss = res$; + results = []; + outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + for (j$ = 0, len1$ = yss.length; j$ < len1$; ++j$) { + ys = yss[j$]; + if (in$(x, ys)) { + continue outer; + } + } + results.push(x); + } + return results; +}; +intersection = function(xs){ + var yss, res$, i$, to$, results, len$, x, j$, len1$, ys; + res$ = []; + for (i$ = 1, to$ = arguments.length; i$ < to$; ++i$) { + res$.push(arguments[i$]); + } + yss = res$; + results = []; + outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + for (j$ = 0, len1$ = yss.length; j$ < len1$; ++j$) { + ys = yss[j$]; + if (!in$(x, ys)) { + continue outer; + } + } + results.push(x); + } + return results; +}; +union = function(){ + var xss, res$, i$, to$, results, len$, xs, j$, len1$, x; + res$ = []; + for (i$ = 0, to$ = arguments.length; i$ < to$; ++i$) { + res$.push(arguments[i$]); + } + xss = res$; + results = []; + for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) { + xs = xss[i$]; + for (j$ = 0, len1$ = xs.length; j$ < len1$; ++j$) { + x = xs[j$]; + if (!in$(x, results)) { + results.push(x); + } + } + } + return results; +}; +countBy = curry$(function(f, xs){ + var results, i$, len$, x, key; + results = {}; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + key = f(x); + if (key in results) { + results[key] += 1; + } else { + results[key] = 1; + } + } + return results; +}); +groupBy = curry$(function(f, xs){ + var results, i$, len$, x, key; + results = {}; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + key = f(x); + if (key in results) { + results[key].push(x); + } else { + results[key] = [x]; + } + } + return results; +}); +andList = function(xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (!x) { + return false; + } + } + return true; +}; +orList = function(xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (x) { + return true; + } + } + return false; +}; +any = curry$(function(f, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (f(x)) { + return true; + } + } + return false; +}); +all = curry$(function(f, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (!f(x)) { + return false; + } + } + return true; +}); +sort = function(xs){ + return xs.concat().sort(function(x, y){ + if (x > y) { + return 1; + } else if (x < y) { + return -1; + } else { + return 0; + } + }); +}; +sortWith = curry$(function(f, xs){ + return xs.concat().sort(f); +}); +sortBy = curry$(function(f, xs){ + return xs.concat().sort(function(x, y){ + if (f(x) > f(y)) { + return 1; + } else if (f(x) < f(y)) { + return -1; + } else { + return 0; + } + }); +}); +sum = function(xs){ + var result, i$, len$, x; + result = 0; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + result += x; + } + return result; +}; +product = function(xs){ + var result, i$, len$, x; + result = 1; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + result *= x; + } + return result; +}; +mean = average = function(xs){ + var sum, i$, len$, x; + sum = 0; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + sum += x; + } + return sum / xs.length; +}; +maximum = function(xs){ + var max, i$, ref$, len$, x; + max = xs[0]; + for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (x > max) { + max = x; + } + } + return max; +}; +minimum = function(xs){ + var min, i$, ref$, len$, x; + min = xs[0]; + for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (x < min) { + min = x; + } + } + return min; +}; +maximumBy = curry$(function(f, xs){ + var max, i$, ref$, len$, x; + max = xs[0]; + for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (f(x) > f(max)) { + max = x; + } + } + return max; +}); +minimumBy = curry$(function(f, xs){ + var min, i$, ref$, len$, x; + min = xs[0]; + for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (f(x) < f(min)) { + min = x; + } + } + return min; +}); +scan = scanl = curry$(function(f, memo, xs){ + var last, x; + last = memo; + return [memo].concat((function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) { + x = ref$[i$]; + results$.push(last = f(last, x)); + } + return results$; + }())); +}); +scan1 = scanl1 = curry$(function(f, xs){ + if (!xs.length) { + return; + } + return scan(f, xs[0], xs.slice(1)); +}); +scanr = curry$(function(f, memo, xs){ + xs = xs.concat().reverse(); + return scan(f, memo, xs).reverse(); +}); +scanr1 = curry$(function(f, xs){ + if (!xs.length) { + return; + } + xs = xs.concat().reverse(); + return scan(f, xs[0], xs.slice(1)).reverse(); +}); +slice = curry$(function(x, y, xs){ + return xs.slice(x, y); +}); +take = curry$(function(n, xs){ + if (n <= 0) { + return xs.slice(0, 0); + } else { + return xs.slice(0, n); + } +}); +drop = curry$(function(n, xs){ + if (n <= 0) { + return xs; + } else { + return xs.slice(n); + } +}); +splitAt = curry$(function(n, xs){ + return [take(n, xs), drop(n, xs)]; +}); +takeWhile = curry$(function(p, xs){ + var len, i; + len = xs.length; + if (!len) { + return xs; + } + i = 0; + while (i < len && p(xs[i])) { + i += 1; + } + return xs.slice(0, i); +}); +dropWhile = curry$(function(p, xs){ + var len, i; + len = xs.length; + if (!len) { + return xs; + } + i = 0; + while (i < len && p(xs[i])) { + i += 1; + } + return xs.slice(i); +}); +span = curry$(function(p, xs){ + return [takeWhile(p, xs), dropWhile(p, xs)]; +}); +breakList = curry$(function(p, xs){ + return span(compose$(p, not$), xs); +}); +zip = curry$(function(xs, ys){ + var result, len, i$, len$, i, x; + result = []; + len = ys.length; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (i === len) { + break; + } + result.push([x, ys[i]]); + } + return result; +}); +zipWith = curry$(function(f, xs, ys){ + var result, len, i$, len$, i, x; + result = []; + len = ys.length; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (i === len) { + break; + } + result.push(f(x, ys[i])); + } + return result; +}); +zipAll = function(){ + var xss, res$, i$, to$, minLength, len$, xs, ref$, i, lresult$, j$, results$ = []; + res$ = []; + for (i$ = 0, to$ = arguments.length; i$ < to$; ++i$) { + res$.push(arguments[i$]); + } + xss = res$; + minLength = undefined; + for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) { + xs = xss[i$]; + minLength <= (ref$ = xs.length) || (minLength = ref$); + } + for (i$ = 0; i$ < minLength; ++i$) { + i = i$; + lresult$ = []; + for (j$ = 0, len$ = xss.length; j$ < len$; ++j$) { + xs = xss[j$]; + lresult$.push(xs[i]); + } + results$.push(lresult$); + } + return results$; +}; +zipAllWith = function(f){ + var xss, res$, i$, to$, minLength, len$, xs, ref$, i, results$ = []; + res$ = []; + for (i$ = 1, to$ = arguments.length; i$ < to$; ++i$) { + res$.push(arguments[i$]); + } + xss = res$; + minLength = undefined; + for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) { + xs = xss[i$]; + minLength <= (ref$ = xs.length) || (minLength = ref$); + } + for (i$ = 0; i$ < minLength; ++i$) { + i = i$; + results$.push(f.apply(null, (fn$()))); + } + return results$; + function fn$(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = xss).length; i$ < len$; ++i$) { + xs = ref$[i$]; + results$.push(xs[i]); + } + return results$; + } +}; +at = curry$(function(n, xs){ + if (n < 0) { + return xs[xs.length + n]; + } else { + return xs[n]; + } +}); +elemIndex = curry$(function(el, xs){ + var i$, len$, i, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (x === el) { + return i; + } + } +}); +elemIndices = curry$(function(el, xs){ + var i$, len$, i, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (x === el) { + results$.push(i); + } + } + return results$; +}); +findIndex = curry$(function(f, xs){ + var i$, len$, i, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (f(x)) { + return i; + } + } +}); +findIndices = curry$(function(f, xs){ + var i$, len$, i, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (f(x)) { + results$.push(i); + } + } + return results$; +}); +module.exports = { + each: each, + map: map, + filter: filter, + compact: compact, + reject: reject, + remove: remove, + partition: partition, + find: find, + head: head, + first: first, + tail: tail, + last: last, + initial: initial, + empty: empty, + reverse: reverse, + difference: difference, + intersection: intersection, + union: union, + countBy: countBy, + groupBy: groupBy, + fold: fold, + fold1: fold1, + foldl: foldl, + foldl1: foldl1, + foldr: foldr, + foldr1: foldr1, + unfoldr: unfoldr, + andList: andList, + orList: orList, + any: any, + all: all, + unique: unique, + uniqueBy: uniqueBy, + sort: sort, + sortWith: sortWith, + sortBy: sortBy, + sum: sum, + product: product, + mean: mean, + average: average, + concat: concat, + concatMap: concatMap, + flatten: flatten, + maximum: maximum, + minimum: minimum, + maximumBy: maximumBy, + minimumBy: minimumBy, + scan: scan, + scan1: scan1, + scanl: scanl, + scanl1: scanl1, + scanr: scanr, + scanr1: scanr1, + slice: slice, + take: take, + drop: drop, + splitAt: splitAt, + takeWhile: takeWhile, + dropWhile: dropWhile, + span: span, + breakList: breakList, + zip: zip, + zipWith: zipWith, + zipAll: zipAll, + zipAllWith: zipAllWith, + at: at, + elemIndex: elemIndex, + elemIndices: elemIndices, + findIndex: findIndex, + findIndices: findIndices +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} +function in$(x, xs){ + var i = -1, l = xs.length >>> 0; + while (++i < l) if (x === xs[i]) return true; + return false; +} +function compose$() { + var functions = arguments; + return function() { + var i, result; + result = functions[0].apply(this, arguments); + for (i = 1; i < functions.length; ++i) { + result = functions[i](result); + } + return result; + }; +} +function not$(x){ return !x; } \ No newline at end of file diff --git a/node_modules/prelude-ls/lib/Num.js b/node_modules/prelude-ls/lib/Num.js new file mode 100644 index 00000000..f6b53193 --- /dev/null +++ b/node_modules/prelude-ls/lib/Num.js @@ -0,0 +1,130 @@ +// Generated by LiveScript 1.6.0 +var max, min, negate, abs, signum, quot, rem, div, mod, recip, pi, tau, exp, sqrt, ln, pow, sin, tan, cos, asin, acos, atan, atan2, truncate, round, ceiling, floor, isItNaN, even, odd, gcd, lcm; +max = curry$(function(x$, y$){ + return x$ > y$ ? x$ : y$; +}); +min = curry$(function(x$, y$){ + return x$ < y$ ? x$ : y$; +}); +negate = function(x){ + return -x; +}; +abs = Math.abs; +signum = function(x){ + if (x < 0) { + return -1; + } else if (x > 0) { + return 1; + } else { + return 0; + } +}; +quot = curry$(function(x, y){ + return ~~(x / y); +}); +rem = curry$(function(x$, y$){ + return x$ % y$; +}); +div = curry$(function(x, y){ + return Math.floor(x / y); +}); +mod = curry$(function(x$, y$){ + var ref$; + return ((x$) % (ref$ = y$) + ref$) % ref$; +}); +recip = (function(it){ + return 1 / it; +}); +pi = Math.PI; +tau = pi * 2; +exp = Math.exp; +sqrt = Math.sqrt; +ln = Math.log; +pow = curry$(function(x$, y$){ + return Math.pow(x$, y$); +}); +sin = Math.sin; +tan = Math.tan; +cos = Math.cos; +asin = Math.asin; +acos = Math.acos; +atan = Math.atan; +atan2 = curry$(function(x, y){ + return Math.atan2(x, y); +}); +truncate = function(x){ + return ~~x; +}; +round = Math.round; +ceiling = Math.ceil; +floor = Math.floor; +isItNaN = function(x){ + return x !== x; +}; +even = function(x){ + return x % 2 === 0; +}; +odd = function(x){ + return x % 2 !== 0; +}; +gcd = curry$(function(x, y){ + var z; + x = Math.abs(x); + y = Math.abs(y); + while (y !== 0) { + z = x % y; + x = y; + y = z; + } + return x; +}); +lcm = curry$(function(x, y){ + return Math.abs(Math.floor(x / gcd(x, y) * y)); +}); +module.exports = { + max: max, + min: min, + negate: negate, + abs: abs, + signum: signum, + quot: quot, + rem: rem, + div: div, + mod: mod, + recip: recip, + pi: pi, + tau: tau, + exp: exp, + sqrt: sqrt, + ln: ln, + pow: pow, + sin: sin, + tan: tan, + cos: cos, + acos: acos, + asin: asin, + atan: atan, + atan2: atan2, + truncate: truncate, + round: round, + ceiling: ceiling, + floor: floor, + isItNaN: isItNaN, + even: even, + odd: odd, + gcd: gcd, + lcm: lcm +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/node_modules/prelude-ls/lib/Obj.js b/node_modules/prelude-ls/lib/Obj.js new file mode 100644 index 00000000..0b8d3216 --- /dev/null +++ b/node_modules/prelude-ls/lib/Obj.js @@ -0,0 +1,154 @@ +// Generated by LiveScript 1.6.0 +var values, keys, pairsToObj, objToPairs, listsToObj, objToLists, empty, each, map, compact, filter, reject, partition, find; +values = function(object){ + var i$, x, results$ = []; + for (i$ in object) { + x = object[i$]; + results$.push(x); + } + return results$; +}; +keys = function(object){ + var x, results$ = []; + for (x in object) { + results$.push(x); + } + return results$; +}; +pairsToObj = function(object){ + var i$, len$, x, resultObj$ = {}; + for (i$ = 0, len$ = object.length; i$ < len$; ++i$) { + x = object[i$]; + resultObj$[x[0]] = x[1]; + } + return resultObj$; +}; +objToPairs = function(object){ + var key, value, results$ = []; + for (key in object) { + value = object[key]; + results$.push([key, value]); + } + return results$; +}; +listsToObj = curry$(function(keys, values){ + var i$, len$, i, key, resultObj$ = {}; + for (i$ = 0, len$ = keys.length; i$ < len$; ++i$) { + i = i$; + key = keys[i$]; + resultObj$[key] = values[i]; + } + return resultObj$; +}); +objToLists = function(object){ + var keys, values, key, value; + keys = []; + values = []; + for (key in object) { + value = object[key]; + keys.push(key); + values.push(value); + } + return [keys, values]; +}; +empty = function(object){ + var x; + for (x in object) { + return false; + } + return true; +}; +each = curry$(function(f, object){ + var i$, x; + for (i$ in object) { + x = object[i$]; + f(x); + } + return object; +}); +map = curry$(function(f, object){ + var k, x, resultObj$ = {}; + for (k in object) { + x = object[k]; + resultObj$[k] = f(x); + } + return resultObj$; +}); +compact = function(object){ + var k, x, resultObj$ = {}; + for (k in object) { + x = object[k]; + if (x) { + resultObj$[k] = x; + } + } + return resultObj$; +}; +filter = curry$(function(f, object){ + var k, x, resultObj$ = {}; + for (k in object) { + x = object[k]; + if (f(x)) { + resultObj$[k] = x; + } + } + return resultObj$; +}); +reject = curry$(function(f, object){ + var k, x, resultObj$ = {}; + for (k in object) { + x = object[k]; + if (!f(x)) { + resultObj$[k] = x; + } + } + return resultObj$; +}); +partition = curry$(function(f, object){ + var passed, failed, k, x; + passed = {}; + failed = {}; + for (k in object) { + x = object[k]; + (f(x) ? passed : failed)[k] = x; + } + return [passed, failed]; +}); +find = curry$(function(f, object){ + var i$, x; + for (i$ in object) { + x = object[i$]; + if (f(x)) { + return x; + } + } +}); +module.exports = { + values: values, + keys: keys, + pairsToObj: pairsToObj, + objToPairs: objToPairs, + listsToObj: listsToObj, + objToLists: objToLists, + empty: empty, + each: each, + map: map, + filter: filter, + compact: compact, + reject: reject, + partition: partition, + find: find +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/node_modules/prelude-ls/lib/Str.js b/node_modules/prelude-ls/lib/Str.js new file mode 100644 index 00000000..59406d60 --- /dev/null +++ b/node_modules/prelude-ls/lib/Str.js @@ -0,0 +1,92 @@ +// Generated by LiveScript 1.6.0 +var split, join, lines, unlines, words, unwords, chars, unchars, reverse, repeat, capitalize, camelize, dasherize; +split = curry$(function(sep, str){ + return str.split(sep); +}); +join = curry$(function(sep, xs){ + return xs.join(sep); +}); +lines = function(str){ + if (!str.length) { + return []; + } + return str.split('\n'); +}; +unlines = function(it){ + return it.join('\n'); +}; +words = function(str){ + if (!str.length) { + return []; + } + return str.split(/[ ]+/); +}; +unwords = function(it){ + return it.join(' '); +}; +chars = function(it){ + return it.split(''); +}; +unchars = function(it){ + return it.join(''); +}; +reverse = function(str){ + return str.split('').reverse().join(''); +}; +repeat = curry$(function(n, str){ + var result, i$; + result = ''; + for (i$ = 0; i$ < n; ++i$) { + result += str; + } + return result; +}); +capitalize = function(str){ + return str.charAt(0).toUpperCase() + str.slice(1); +}; +camelize = function(it){ + return it.replace(/[-_]+(.)?/g, function(arg$, c){ + return (c != null ? c : '').toUpperCase(); + }); +}; +dasherize = function(str){ + return str.replace(/([^-A-Z])([A-Z]+)/g, function(arg$, lower, upper){ + return lower + "-" + (upper.length > 1 + ? upper + : upper.toLowerCase()); + }).replace(/^([A-Z]+)/, function(arg$, upper){ + if (upper.length > 1) { + return upper + "-"; + } else { + return upper.toLowerCase(); + } + }); +}; +module.exports = { + split: split, + join: join, + lines: lines, + unlines: unlines, + words: words, + unwords: unwords, + chars: chars, + unchars: unchars, + reverse: reverse, + repeat: repeat, + capitalize: capitalize, + camelize: camelize, + dasherize: dasherize +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/node_modules/prelude-ls/lib/index.js b/node_modules/prelude-ls/lib/index.js new file mode 100644 index 00000000..9dcbed46 --- /dev/null +++ b/node_modules/prelude-ls/lib/index.js @@ -0,0 +1,178 @@ +// Generated by LiveScript 1.6.0 +var Func, List, Obj, Str, Num, id, isType, replicate, prelude, toString$ = {}.toString; +Func = require('./Func.js'); +List = require('./List.js'); +Obj = require('./Obj.js'); +Str = require('./Str.js'); +Num = require('./Num.js'); +id = function(x){ + return x; +}; +isType = curry$(function(type, x){ + return toString$.call(x).slice(8, -1) === type; +}); +replicate = curry$(function(n, x){ + var i$, results$ = []; + for (i$ = 0; i$ < n; ++i$) { + results$.push(x); + } + return results$; +}); +Str.empty = List.empty; +Str.slice = List.slice; +Str.take = List.take; +Str.drop = List.drop; +Str.splitAt = List.splitAt; +Str.takeWhile = List.takeWhile; +Str.dropWhile = List.dropWhile; +Str.span = List.span; +Str.breakStr = List.breakList; +prelude = { + Func: Func, + List: List, + Obj: Obj, + Str: Str, + Num: Num, + id: id, + isType: isType, + replicate: replicate +}; +prelude.each = List.each; +prelude.map = List.map; +prelude.filter = List.filter; +prelude.compact = List.compact; +prelude.reject = List.reject; +prelude.partition = List.partition; +prelude.find = List.find; +prelude.head = List.head; +prelude.first = List.first; +prelude.tail = List.tail; +prelude.last = List.last; +prelude.initial = List.initial; +prelude.empty = List.empty; +prelude.reverse = List.reverse; +prelude.difference = List.difference; +prelude.intersection = List.intersection; +prelude.union = List.union; +prelude.countBy = List.countBy; +prelude.groupBy = List.groupBy; +prelude.fold = List.fold; +prelude.foldl = List.foldl; +prelude.fold1 = List.fold1; +prelude.foldl1 = List.foldl1; +prelude.foldr = List.foldr; +prelude.foldr1 = List.foldr1; +prelude.unfoldr = List.unfoldr; +prelude.andList = List.andList; +prelude.orList = List.orList; +prelude.any = List.any; +prelude.all = List.all; +prelude.unique = List.unique; +prelude.uniqueBy = List.uniqueBy; +prelude.sort = List.sort; +prelude.sortWith = List.sortWith; +prelude.sortBy = List.sortBy; +prelude.sum = List.sum; +prelude.product = List.product; +prelude.mean = List.mean; +prelude.average = List.average; +prelude.concat = List.concat; +prelude.concatMap = List.concatMap; +prelude.flatten = List.flatten; +prelude.maximum = List.maximum; +prelude.minimum = List.minimum; +prelude.maximumBy = List.maximumBy; +prelude.minimumBy = List.minimumBy; +prelude.scan = List.scan; +prelude.scanl = List.scanl; +prelude.scan1 = List.scan1; +prelude.scanl1 = List.scanl1; +prelude.scanr = List.scanr; +prelude.scanr1 = List.scanr1; +prelude.slice = List.slice; +prelude.take = List.take; +prelude.drop = List.drop; +prelude.splitAt = List.splitAt; +prelude.takeWhile = List.takeWhile; +prelude.dropWhile = List.dropWhile; +prelude.span = List.span; +prelude.breakList = List.breakList; +prelude.zip = List.zip; +prelude.zipWith = List.zipWith; +prelude.zipAll = List.zipAll; +prelude.zipAllWith = List.zipAllWith; +prelude.at = List.at; +prelude.elemIndex = List.elemIndex; +prelude.elemIndices = List.elemIndices; +prelude.findIndex = List.findIndex; +prelude.findIndices = List.findIndices; +prelude.apply = Func.apply; +prelude.curry = Func.curry; +prelude.flip = Func.flip; +prelude.fix = Func.fix; +prelude.over = Func.over; +prelude.split = Str.split; +prelude.join = Str.join; +prelude.lines = Str.lines; +prelude.unlines = Str.unlines; +prelude.words = Str.words; +prelude.unwords = Str.unwords; +prelude.chars = Str.chars; +prelude.unchars = Str.unchars; +prelude.repeat = Str.repeat; +prelude.capitalize = Str.capitalize; +prelude.camelize = Str.camelize; +prelude.dasherize = Str.dasherize; +prelude.values = Obj.values; +prelude.keys = Obj.keys; +prelude.pairsToObj = Obj.pairsToObj; +prelude.objToPairs = Obj.objToPairs; +prelude.listsToObj = Obj.listsToObj; +prelude.objToLists = Obj.objToLists; +prelude.max = Num.max; +prelude.min = Num.min; +prelude.negate = Num.negate; +prelude.abs = Num.abs; +prelude.signum = Num.signum; +prelude.quot = Num.quot; +prelude.rem = Num.rem; +prelude.div = Num.div; +prelude.mod = Num.mod; +prelude.recip = Num.recip; +prelude.pi = Num.pi; +prelude.tau = Num.tau; +prelude.exp = Num.exp; +prelude.sqrt = Num.sqrt; +prelude.ln = Num.ln; +prelude.pow = Num.pow; +prelude.sin = Num.sin; +prelude.tan = Num.tan; +prelude.cos = Num.cos; +prelude.acos = Num.acos; +prelude.asin = Num.asin; +prelude.atan = Num.atan; +prelude.atan2 = Num.atan2; +prelude.truncate = Num.truncate; +prelude.round = Num.round; +prelude.ceiling = Num.ceiling; +prelude.floor = Num.floor; +prelude.isItNaN = Num.isItNaN; +prelude.even = Num.even; +prelude.odd = Num.odd; +prelude.gcd = Num.gcd; +prelude.lcm = Num.lcm; +prelude.VERSION = '1.2.1'; +module.exports = prelude; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/node_modules/prelude-ls/package.json b/node_modules/prelude-ls/package.json new file mode 100644 index 00000000..c313c3da --- /dev/null +++ b/node_modules/prelude-ls/package.json @@ -0,0 +1,46 @@ +{ + "name": "prelude-ls", + "version": "1.2.1", + "author": "George Zahariev ", + "description": "prelude.ls is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, LiveScript.", + "keywords": [ + "prelude", + "livescript", + "utility", + "ls", + "coffeescript", + "javascript", + "library", + "functional", + "array", + "list", + "object", + "string" + ], + "main": "lib/", + "files": [ + "lib/", + "README.md", + "LICENSE" + ], + "homepage": "http://preludels.com", + "bugs": "https://github.com/gkz/prelude-ls/issues", + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/gkz/prelude-ls.git" + }, + "scripts": { + "test": "make test" + }, + "devDependencies": { + "livescript": "^1.6.0", + "uglify-js": "^3.8.1", + "mocha": "^7.1.1", + "browserify": "^16.5.1", + "sinon": "~8.0.1" + } +} diff --git a/node_modules/punycode/LICENSE-MIT.txt b/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 00000000..a41e0a7e --- /dev/null +++ b/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/punycode/README.md b/node_modules/punycode/README.md new file mode 100644 index 00000000..f611016b --- /dev/null +++ b/node_modules/punycode/README.md @@ -0,0 +1,148 @@ +# Punycode.js [![punycode on npm](https://img.shields.io/npm/v/punycode)](https://www.npmjs.com/package/punycode) [![](https://data.jsdelivr.com/v1/package/npm/punycode/badge)](https://www.jsdelivr.com/package/npm/punycode) + +Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). + +This project provides a CommonJS module that uses ES2015+ features and JavaScript module, which work in modern Node.js versions and browsers. For the old Punycode.js version that offers the same functionality in a UMD build with support for older pre-ES2015 runtimes, including Rhino, Ringo, and Narwhal, see [v1.4.1](https://github.com/mathiasbynens/punycode.js/releases/tag/v1.4.1). + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install punycode --save +``` + +In [Node.js](https://nodejs.org/): + +> ⚠️ Note that userland modules don't hide core modules. +> For example, `require('punycode')` still imports the deprecated core module even if you executed `npm install punycode`. +> Use `require('punycode/')` to import userland modules rather than core modules. + +```js +const punycode = require('punycode/'); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## For maintainers + +### How to publish a new release + +1. On the `main` branch, bump the version number in `package.json`: + + ```sh + npm version patch -m 'Release v%s' + ``` + + Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/). + + Note that this produces a Git commit + tag. + +1. Push the release commit and tag: + + ```sh + git push && git push --tags + ``` + + Our CI then automatically publishes the new release to npm, under both the [`punycode`](https://www.npmjs.com/package/punycode) and [`punycode.js`](https://www.npmjs.com/package/punycode.js) names. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +Punycode.js is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/punycode/package.json b/node_modules/punycode/package.json new file mode 100644 index 00000000..b8b76fc7 --- /dev/null +++ b/node_modules/punycode/package.json @@ -0,0 +1,58 @@ +{ + "name": "punycode", + "version": "2.3.1", + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "homepage": "https://mths.be/punycode", + "main": "punycode.js", + "jsnext:main": "punycode.es6.js", + "module": "punycode.es6.js", + "engines": { + "node": ">=6" + }, + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/punycode.js.git" + }, + "bugs": "https://github.com/mathiasbynens/punycode.js/issues", + "files": [ + "LICENSE-MIT.txt", + "punycode.js", + "punycode.es6.js" + ], + "scripts": { + "test": "mocha tests", + "build": "node scripts/prepublish.js" + }, + "devDependencies": { + "codecov": "^3.8.3", + "nyc": "^15.1.0", + "mocha": "^10.2.0" + }, + "jspm": { + "map": { + "./punycode.js": { + "node": "@node/punycode" + } + } + } +} diff --git a/node_modules/punycode/punycode.es6.js b/node_modules/punycode/punycode.es6.js new file mode 100644 index 00000000..dadece25 --- /dev/null +++ b/node_modules/punycode/punycode.es6.js @@ -0,0 +1,444 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base) { + error('invalid-input'); + } + if (digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.3.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +export { ucs2decode, ucs2encode, decode, encode, toASCII, toUnicode }; +export default punycode; diff --git a/node_modules/punycode/punycode.js b/node_modules/punycode/punycode.js new file mode 100644 index 00000000..a1ef2519 --- /dev/null +++ b/node_modules/punycode/punycode.js @@ -0,0 +1,443 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base) { + error('invalid-input'); + } + if (digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.3.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +module.exports = punycode; diff --git a/node_modules/queue-microtask/LICENSE b/node_modules/queue-microtask/LICENSE new file mode 100755 index 00000000..c7e68527 --- /dev/null +++ b/node_modules/queue-microtask/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/queue-microtask/README.md b/node_modules/queue-microtask/README.md new file mode 100644 index 00000000..0be05a64 --- /dev/null +++ b/node_modules/queue-microtask/README.md @@ -0,0 +1,90 @@ +# queue-microtask [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[ci-image]: https://img.shields.io/github/workflow/status/feross/queue-microtask/ci/master +[ci-url]: https://github.com/feross/queue-microtask/actions +[npm-image]: https://img.shields.io/npm/v/queue-microtask.svg +[npm-url]: https://npmjs.org/package/queue-microtask +[downloads-image]: https://img.shields.io/npm/dm/queue-microtask.svg +[downloads-url]: https://npmjs.org/package/queue-microtask +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +### fast, tiny [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) shim for modern engines + +- Use [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) in all modern JS engines. +- No dependencies. Less than 10 lines. No shims or complicated fallbacks. +- Optimal performance in all modern environments + - Uses `queueMicrotask` in modern environments + - Fallback to `Promise.resolve().then(fn)` in Node.js 10 and earlier, and old browsers (same performance as `queueMicrotask`) + +## install + +``` +npm install queue-microtask +``` + +## usage + +```js +const queueMicrotask = require('queue-microtask') + +queueMicrotask(() => { /* this will run soon */ }) +``` + +## What is `queueMicrotask` and why would one use it? + +The `queueMicrotask` function is a WHATWG standard. It queues a microtask to be executed prior to control returning to the event loop. + +A microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the event loop. + +The code `queueMicrotask(fn)` is equivalent to the code `Promise.resolve().then(fn)`. It is also very similar to [`process.nextTick(fn)`](https://nodejs.org/api/process.html#process_process_nexttick_callback_args) in Node. + +Using microtasks lets code run without interfering with any other, potentially higher priority, code that is pending, but before the JS engine regains control over the execution context. + +See the [spec](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#microtask-queuing) or [Node documentation](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback) for more information. + +## Who is this package for? + +This package allows you to use `queueMicrotask` safely in all modern JS engines. Use it if you prioritize small JS bundle size over support for old browsers. + +If you just need to support Node 12 and later, use `queueMicrotask` directly. If you need to support all versions of Node, use this package. + +## Why not use `process.nextTick`? + +In Node, `queueMicrotask` and `process.nextTick` are [essentially equivalent](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback), though there are [subtle differences](https://github.com/YuzuJS/setImmediate#macrotasks-and-microtasks) that don't matter in most situations. + +You can think of `queueMicrotask` as a standardized version of `process.nextTick` that works in the browser. No need to rely on your browser bundler to shim `process` for the browser environment. + +## Why not use `setTimeout(fn, 0)`? + +This approach is the most compatible, but it has problems. Modern browsers throttle timers severely, so `setTimeout(…, 0)` usually takes at least 4ms to run. Furthermore, the throttling gets even worse if the page is backgrounded. If you have many `setTimeout` calls, then this can severely limit the performance of your program. + +## Why not use a microtask library like [`immediate`](https://www.npmjs.com/package/immediate) or [`asap`](https://www.npmjs.com/package/asap)? + +These packages are great! However, if you prioritize small JS bundle size over optimal performance in old browsers then you may want to consider this package. + +This package (`queue-microtask`) is four times smaller than `immediate`, twice as small as `asap`, and twice as small as using `process.nextTick` and letting the browser bundler shim it automatically. + +Note: This package throws an exception in JS environments which lack `Promise` support -- which are usually very old browsers and Node.js versions. + +Since the `queueMicrotask` API is supported in Node.js, Chrome, Firefox, Safari, Opera, and Edge, **the vast majority of users will get optimal performance**. Any JS environment with `Promise`, which is almost all of them, also get optimal performance. If you need support for JS environments which lack `Promise` support, use one of the alternative packages. + +## What is a shim? + +> In computer programming, a shim is a library that transparently intercepts API calls and changes the arguments passed, handles the operation itself or redirects the operation elsewhere. – [Wikipedia](https://en.wikipedia.org/wiki/Shim_(computing)) + +This package could also be described as a "ponyfill". + +> A ponyfill is almost the same as a polyfill, but not quite. Instead of patching functionality for older browsers, a ponyfill provides that functionality as a standalone module you can use. – [PonyFoo](https://ponyfoo.com/articles/polyfills-or-ponyfills) + +## API + +### `queueMicrotask(fn)` + +The `queueMicrotask()` method queues a microtask. + +The `fn` argument is a function to be executed after all pending tasks have completed but before yielding control to the browser's event loop. + +## license + +MIT. Copyright (c) [Feross Aboukhadijeh](https://feross.org). diff --git a/node_modules/queue-microtask/index.d.ts b/node_modules/queue-microtask/index.d.ts new file mode 100644 index 00000000..b6a86463 --- /dev/null +++ b/node_modules/queue-microtask/index.d.ts @@ -0,0 +1,2 @@ +declare const queueMicrotask: (cb: () => void) => void +export = queueMicrotask diff --git a/node_modules/queue-microtask/index.js b/node_modules/queue-microtask/index.js new file mode 100644 index 00000000..55605343 --- /dev/null +++ b/node_modules/queue-microtask/index.js @@ -0,0 +1,9 @@ +/*! queue-microtask. MIT License. Feross Aboukhadijeh */ +let promise + +module.exports = typeof queueMicrotask === 'function' + ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global) + // reuse resolved promise, and allocate it lazily + : cb => (promise || (promise = Promise.resolve())) + .then(cb) + .catch(err => setTimeout(() => { throw err }, 0)) diff --git a/node_modules/queue-microtask/package.json b/node_modules/queue-microtask/package.json new file mode 100644 index 00000000..d29a401f --- /dev/null +++ b/node_modules/queue-microtask/package.json @@ -0,0 +1,55 @@ +{ + "name": "queue-microtask", + "description": "fast, tiny `queueMicrotask` shim for modern engines", + "version": "1.2.3", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/queue-microtask/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.2.2" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "homepage": "https://github.com/feross/queue-microtask", + "keywords": [ + "asap", + "immediate", + "micro task", + "microtask", + "nextTick", + "process.nextTick", + "queue micro task", + "queue microtask", + "queue-microtask", + "queueMicrotask", + "setImmediate", + "task" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/feross/queue-microtask.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + } +} diff --git a/node_modules/resolve-from/index.js b/node_modules/resolve-from/index.js new file mode 100644 index 00000000..d092447e --- /dev/null +++ b/node_modules/resolve-from/index.js @@ -0,0 +1,47 @@ +'use strict'; +const path = require('path'); +const Module = require('module'); +const fs = require('fs'); + +const resolveFrom = (fromDir, moduleId, silent) => { + if (typeof fromDir !== 'string') { + throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDir}\``); + } + + if (typeof moduleId !== 'string') { + throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``); + } + + try { + fromDir = fs.realpathSync(fromDir); + } catch (err) { + if (err.code === 'ENOENT') { + fromDir = path.resolve(fromDir); + } else if (silent) { + return null; + } else { + throw err; + } + } + + const fromFile = path.join(fromDir, 'noop.js'); + + const resolveFileName = () => Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDir) + }); + + if (silent) { + try { + return resolveFileName(); + } catch (err) { + return null; + } + } + + return resolveFileName(); +}; + +module.exports = (fromDir, moduleId) => resolveFrom(fromDir, moduleId); +module.exports.silent = (fromDir, moduleId) => resolveFrom(fromDir, moduleId, true); diff --git a/node_modules/resolve-from/license b/node_modules/resolve-from/license new file mode 100644 index 00000000..e7af2f77 --- /dev/null +++ b/node_modules/resolve-from/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/resolve-from/package.json b/node_modules/resolve-from/package.json new file mode 100644 index 00000000..96bade58 --- /dev/null +++ b/node_modules/resolve-from/package.json @@ -0,0 +1,34 @@ +{ + "name": "resolve-from", + "version": "4.0.0", + "description": "Resolve the path of a module like `require.resolve()` but from a given path", + "license": "MIT", + "repository": "sindresorhus/resolve-from", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "require", + "resolve", + "path", + "module", + "from", + "like", + "import" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/resolve-from/readme.md b/node_modules/resolve-from/readme.md new file mode 100644 index 00000000..e539f858 --- /dev/null +++ b/node_modules/resolve-from/readme.md @@ -0,0 +1,72 @@ +# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) + +> Resolve the path of a module like [`require.resolve()`](https://nodejs.org/api/globals.html#globals_require_resolve) but from a given path + + +## Install + +``` +$ npm install resolve-from +``` + + +## Usage + +```js +const resolveFrom = require('resolve-from'); + +// There is a file at `./foo/bar.js` + +resolveFrom('foo', './bar'); +//=> '/Users/sindresorhus/dev/test/foo/bar.js' +``` + + +## API + +### resolveFrom(fromDir, moduleId) + +Like `require()`, throws when the module can't be found. + +### resolveFrom.silent(fromDir, moduleId) + +Returns `null` instead of throwing when the module can't be found. + +#### fromDir + +Type: `string` + +Directory to resolve from. + +#### moduleId + +Type: `string` + +What you would use in `require()`. + + +## Tip + +Create a partial using a bound function if you want to resolve from the same `fromDir` multiple times: + +```js +const resolveFromFoo = resolveFrom.bind(null, 'foo'); + +resolveFromFoo('./bar'); +resolveFromFoo('./baz'); +``` + + +## Related + +- [resolve-cwd](https://github.com/sindresorhus/resolve-cwd) - Resolve the path of a module from the current working directory +- [import-from](https://github.com/sindresorhus/import-from) - Import a module from a given path +- [import-cwd](https://github.com/sindresorhus/import-cwd) - Import a module from the current working directory +- [resolve-pkg](https://github.com/sindresorhus/resolve-pkg) - Resolve the path of a package regardless of it having an entry point +- [import-lazy](https://github.com/sindresorhus/import-lazy) - Import a module lazily +- [resolve-global](https://github.com/sindresorhus/resolve-global) - Resolve the path of a globally installed module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/reusify/.github/dependabot.yml b/node_modules/reusify/.github/dependabot.yml new file mode 100644 index 00000000..4872c5af --- /dev/null +++ b/node_modules/reusify/.github/dependabot.yml @@ -0,0 +1,7 @@ +version: 2 +updates: +- package-ecosystem: npm + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 diff --git a/node_modules/reusify/.github/workflows/ci.yml b/node_modules/reusify/.github/workflows/ci.yml new file mode 100644 index 00000000..1e30ad80 --- /dev/null +++ b/node_modules/reusify/.github/workflows/ci.yml @@ -0,0 +1,96 @@ +name: ci + +on: [push, pull_request] + +jobs: + legacy: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: ['0.10', '0.12', 4.x, 6.x, 8.x, 10.x, 12.x, 13.x, 14.x, 15.x, 16.x] + + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Install + run: | + npm install --production && npm install tape + + - name: Run tests + run: | + npm run test + + test: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [18.x, 20.x, 22.x] + + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Install + run: | + npm install + + - name: Run tests + run: | + npm run test:coverage + + types: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Install + run: | + npm install + + - name: Run types tests + run: | + npm run test:typescript + + lint: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Install + run: | + npm install + + - name: Lint + run: | + npm run lint diff --git a/node_modules/reusify/LICENSE b/node_modules/reusify/LICENSE new file mode 100644 index 00000000..56d1590d --- /dev/null +++ b/node_modules/reusify/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015-2024 Matteo Collina + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/reusify/README.md b/node_modules/reusify/README.md new file mode 100644 index 00000000..1aaee5d9 --- /dev/null +++ b/node_modules/reusify/README.md @@ -0,0 +1,139 @@ +# reusify + +[![npm version][npm-badge]][npm-url] + +Reuse your objects and functions for maximum speed. This technique will +make any function run ~10% faster. You call your functions a +lot, and it adds up quickly in hot code paths. + +``` +$ node benchmarks/createNoCodeFunction.js +Total time 53133 +Total iterations 100000000 +Iteration/s 1882069.5236482036 + +$ node benchmarks/reuseNoCodeFunction.js +Total time 50617 +Total iterations 100000000 +Iteration/s 1975620.838848608 +``` + +The above benchmark uses fibonacci to simulate a real high-cpu load. +The actual numbers might differ for your use case, but the difference +should not. + +The benchmark was taken using Node v6.10.0. + +This library was extracted from +[fastparallel](http://npm.im/fastparallel). + +## Example + +```js +var reusify = require('reusify') +var fib = require('reusify/benchmarks/fib') +var instance = reusify(MyObject) + +// get an object from the cache, +// or creates a new one when cache is empty +var obj = instance.get() + +// set the state +obj.num = 100 +obj.func() + +// reset the state. +// if the state contains any external object +// do not use delete operator (it is slow) +// prefer set them to null +obj.num = 0 + +// store an object in the cache +instance.release(obj) + +function MyObject () { + // you need to define this property + // so V8 can compile MyObject into an + // hidden class + this.next = null + this.num = 0 + + var that = this + + // this function is never reallocated, + // so it can be optimized by V8 + this.func = function () { + if (null) { + // do nothing + } else { + // calculates fibonacci + fib(that.num) + } + } +} +``` + +The above example was intended for synchronous code, let's see async: +```js +var reusify = require('reusify') +var instance = reusify(MyObject) + +for (var i = 0; i < 100; i++) { + getData(i, console.log) +} + +function getData (value, cb) { + var obj = instance.get() + + obj.value = value + obj.cb = cb + obj.run() +} + +function MyObject () { + this.next = null + this.value = null + + var that = this + + this.run = function () { + asyncOperation(that.value, that.handle) + } + + this.handle = function (err, result) { + that.cb(err, result) + that.value = null + that.cb = null + instance.release(that) + } +} +``` + +Also note how in the above examples, the code, that consumes an instance of `MyObject`, +reset the state to initial condition, just before storing it in the cache. +That's needed so that every subsequent request for an instance from the cache, +could get a clean instance. + +## Why + +It is faster because V8 doesn't have to collect all the functions you +create. On a short-lived benchmark, it is as fast as creating the +nested function, but on a longer time frame it creates less +pressure on the garbage collector. + +## Other examples +If you want to see some complex example, checkout [middie](https://github.com/fastify/middie) and [steed](https://github.com/mcollina/steed). + +## Acknowledgements + +Thanks to [Trevor Norris](https://github.com/trevnorris) for +getting me down the rabbit hole of performance, and thanks to [Mathias +Buss](http://github.com/mafintosh) for suggesting me to share this +trick. + +## License + +MIT + +[npm-badge]: https://badge.fury.io/js/reusify.svg +[npm-url]: https://badge.fury.io/js/reusify diff --git a/node_modules/reusify/SECURITY.md b/node_modules/reusify/SECURITY.md new file mode 100644 index 00000000..dd9f1d51 --- /dev/null +++ b/node_modules/reusify/SECURITY.md @@ -0,0 +1,15 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 1.x | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +Please report all vulnerabilities at [https://github.com/mcollina/fastq/security](https://github.com/mcollina/fastq/security). diff --git a/node_modules/reusify/benchmarks/createNoCodeFunction.js b/node_modules/reusify/benchmarks/createNoCodeFunction.js new file mode 100644 index 00000000..ce1aac7b --- /dev/null +++ b/node_modules/reusify/benchmarks/createNoCodeFunction.js @@ -0,0 +1,30 @@ +'use strict' + +var fib = require('./fib') +var max = 100000000 +var start = Date.now() + +// create a funcion with the typical error +// pattern, that delegates the heavy load +// to something else +function createNoCodeFunction () { + /* eslint no-constant-condition: "off" */ + var num = 100 + + ;(function () { + if (null) { + // do nothing + } else { + fib(num) + } + })() +} + +for (var i = 0; i < max; i++) { + createNoCodeFunction() +} + +var time = Date.now() - start +console.log('Total time', time) +console.log('Total iterations', max) +console.log('Iteration/s', max / time * 1000) diff --git a/node_modules/reusify/benchmarks/fib.js b/node_modules/reusify/benchmarks/fib.js new file mode 100644 index 00000000..e22cc48d --- /dev/null +++ b/node_modules/reusify/benchmarks/fib.js @@ -0,0 +1,13 @@ +'use strict' + +function fib (num) { + var fib = [] + + fib[0] = 0 + fib[1] = 1 + for (var i = 2; i <= num; i++) { + fib[i] = fib[i - 2] + fib[i - 1] + } +} + +module.exports = fib diff --git a/node_modules/reusify/benchmarks/reuseNoCodeFunction.js b/node_modules/reusify/benchmarks/reuseNoCodeFunction.js new file mode 100644 index 00000000..3358d6e5 --- /dev/null +++ b/node_modules/reusify/benchmarks/reuseNoCodeFunction.js @@ -0,0 +1,38 @@ +'use strict' + +var reusify = require('../') +var fib = require('./fib') +var instance = reusify(MyObject) +var max = 100000000 +var start = Date.now() + +function reuseNoCodeFunction () { + var obj = instance.get() + obj.num = 100 + obj.func() + obj.num = 0 + instance.release(obj) +} + +function MyObject () { + this.next = null + var that = this + this.num = 0 + this.func = function () { + /* eslint no-constant-condition: "off" */ + if (null) { + // do nothing + } else { + fib(that.num) + } + } +} + +for (var i = 0; i < max; i++) { + reuseNoCodeFunction() +} + +var time = Date.now() - start +console.log('Total time', time) +console.log('Total iterations', max) +console.log('Iteration/s', max / time * 1000) diff --git a/node_modules/reusify/eslint.config.js b/node_modules/reusify/eslint.config.js new file mode 100644 index 00000000..d0a9af62 --- /dev/null +++ b/node_modules/reusify/eslint.config.js @@ -0,0 +1,14 @@ +'use strict' + +const base = require('neostandard')({}) + +module.exports = [ + ...base, + { + name: 'old-standard', + rules: { + 'no-var': 'off', + 'object-shorthand': 'off', + } + } +] diff --git a/node_modules/reusify/package.json b/node_modules/reusify/package.json new file mode 100644 index 00000000..e47ff11c --- /dev/null +++ b/node_modules/reusify/package.json @@ -0,0 +1,50 @@ +{ + "name": "reusify", + "version": "1.1.0", + "description": "Reuse objects and functions with style", + "main": "reusify.js", + "types": "reusify.d.ts", + "scripts": { + "lint": "eslint", + "test": "tape test.js", + "test:coverage": "c8 --100 tape test.js", + "test:typescript": "tsc" + }, + "pre-commit": [ + "lint", + "test", + "test:typescript" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/mcollina/reusify.git" + }, + "keywords": [ + "reuse", + "object", + "performance", + "function", + "fast" + ], + "author": "Matteo Collina ", + "license": "MIT", + "bugs": { + "url": "https://github.com/mcollina/reusify/issues" + }, + "homepage": "https://github.com/mcollina/reusify#readme", + "engines": { + "node": ">=0.10.0", + "iojs": ">=1.0.0" + }, + "devDependencies": { + "@types/node": "^22.9.0", + "eslint": "^9.13.0", + "neostandard": "^0.12.0", + "pre-commit": "^1.2.2", + "tape": "^5.0.0", + "c8": "^10.1.2", + "typescript": "^5.2.2" + }, + "dependencies": { + } +} diff --git a/node_modules/reusify/reusify.d.ts b/node_modules/reusify/reusify.d.ts new file mode 100644 index 00000000..9ba277dd --- /dev/null +++ b/node_modules/reusify/reusify.d.ts @@ -0,0 +1,14 @@ +interface Node { + next: Node | null; +} + +interface Constructor { + new(): T; +} + +declare function reusify(constructor: Constructor): { + get(): T; + release(node: T): void; +}; + +export = reusify; diff --git a/node_modules/reusify/reusify.js b/node_modules/reusify/reusify.js new file mode 100644 index 00000000..e6f36f3a --- /dev/null +++ b/node_modules/reusify/reusify.js @@ -0,0 +1,33 @@ +'use strict' + +function reusify (Constructor) { + var head = new Constructor() + var tail = head + + function get () { + var current = head + + if (current.next) { + head = current.next + } else { + head = new Constructor() + tail = head + } + + current.next = null + + return current + } + + function release (obj) { + tail.next = obj + tail = obj + } + + return { + get: get, + release: release + } +} + +module.exports = reusify diff --git a/node_modules/reusify/test.js b/node_modules/reusify/test.js new file mode 100644 index 00000000..929cfd71 --- /dev/null +++ b/node_modules/reusify/test.js @@ -0,0 +1,66 @@ +'use strict' + +var test = require('tape') +var reusify = require('./') + +test('reuse objects', function (t) { + t.plan(6) + + function MyObject () { + t.pass('constructor called') + this.next = null + } + + var instance = reusify(MyObject) + var obj = instance.get() + + t.notEqual(obj, instance.get(), 'two instance created') + t.notOk(obj.next, 'next must be null') + + instance.release(obj) + + // the internals keeps a hot copy ready for reuse + // putting this one back in the queue + instance.release(instance.get()) + + // comparing the old one with the one we got + // never do this in real code, after release you + // should never reuse that instance + t.equal(obj, instance.get(), 'instance must be reused') +}) + +test('reuse more than 2 objects', function (t) { + function MyObject () { + t.pass('constructor called') + this.next = null + } + + var instance = reusify(MyObject) + var obj = instance.get() + var obj2 = instance.get() + var obj3 = instance.get() + + t.notOk(obj.next, 'next must be null') + t.notOk(obj2.next, 'next must be null') + t.notOk(obj3.next, 'next must be null') + + t.notEqual(obj, obj2) + t.notEqual(obj, obj3) + t.notEqual(obj3, obj2) + + instance.release(obj) + instance.release(obj2) + instance.release(obj3) + + // skip one + instance.get() + + var obj4 = instance.get() + var obj5 = instance.get() + var obj6 = instance.get() + + t.equal(obj4, obj) + t.equal(obj5, obj2) + t.equal(obj6, obj3) + t.end() +}) diff --git a/node_modules/reusify/tsconfig.json b/node_modules/reusify/tsconfig.json new file mode 100644 index 00000000..dbe862bb --- /dev/null +++ b/node_modules/reusify/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "noEmit": true, + "strict": true + }, + "files": [ + "./reusify.d.ts" + ] +} diff --git a/node_modules/run-parallel/LICENSE b/node_modules/run-parallel/LICENSE new file mode 100644 index 00000000..c7e68527 --- /dev/null +++ b/node_modules/run-parallel/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/run-parallel/README.md b/node_modules/run-parallel/README.md new file mode 100644 index 00000000..edc3da45 --- /dev/null +++ b/node_modules/run-parallel/README.md @@ -0,0 +1,85 @@ +# run-parallel [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/run-parallel/master.svg +[travis-url]: https://travis-ci.org/feross/run-parallel +[npm-image]: https://img.shields.io/npm/v/run-parallel.svg +[npm-url]: https://npmjs.org/package/run-parallel +[downloads-image]: https://img.shields.io/npm/dm/run-parallel.svg +[downloads-url]: https://npmjs.org/package/run-parallel +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +### Run an array of functions in parallel + +![parallel](https://raw.githubusercontent.com/feross/run-parallel/master/img.png) [![Sauce Test Status](https://saucelabs.com/browser-matrix/run-parallel.svg)](https://saucelabs.com/u/run-parallel) + +### install + +``` +npm install run-parallel +``` + +### usage + +#### parallel(tasks, [callback]) + +Run the `tasks` array of functions in parallel, without waiting until the previous +function has completed. If any of the functions pass an error to its callback, the main +`callback` is immediately called with the value of the error. Once the `tasks` have +completed, the results are passed to the final `callback` as an array. + +It is also possible to use an object instead of an array. Each property will be run as a +function and the results will be passed to the final `callback` as an object instead of +an array. This can be a more readable way of handling the results. + +##### arguments + +- `tasks` - An array or object containing functions to run. Each function is passed a +`callback(err, result)` which it must call on completion with an error `err` (which can +be `null`) and an optional `result` value. +- `callback(err, results)` - An optional callback to run once all the functions have +completed. This function gets a results array (or object) containing all the result +arguments passed to the task callbacks. + +##### example + +```js +var parallel = require('run-parallel') + +parallel([ + function (callback) { + setTimeout(function () { + callback(null, 'one') + }, 200) + }, + function (callback) { + setTimeout(function () { + callback(null, 'two') + }, 100) + } +], +// optional callback +function (err, results) { + // the results array will equal ['one','two'] even though + // the second function had a shorter timeout. +}) +``` + +This module is basically equavalent to +[`async.parallel`](https://github.com/caolan/async#paralleltasks-callback), but it's +handy to just have the one function you need instead of the kitchen sink. Modularity! +Especially handy if you're serving to the browser and need to reduce your javascript +bundle size. + +Works great in the browser with [browserify](http://browserify.org/)! + +### see also + +- [run-auto](https://github.com/feross/run-auto) +- [run-parallel-limit](https://github.com/feross/run-parallel-limit) +- [run-series](https://github.com/feross/run-series) +- [run-waterfall](https://github.com/feross/run-waterfall) + +### license + +MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). diff --git a/node_modules/run-parallel/index.js b/node_modules/run-parallel/index.js new file mode 100644 index 00000000..6307141d --- /dev/null +++ b/node_modules/run-parallel/index.js @@ -0,0 +1,51 @@ +/*! run-parallel. MIT License. Feross Aboukhadijeh */ +module.exports = runParallel + +const queueMicrotask = require('queue-microtask') + +function runParallel (tasks, cb) { + let results, pending, keys + let isSync = true + + if (Array.isArray(tasks)) { + results = [] + pending = tasks.length + } else { + keys = Object.keys(tasks) + results = {} + pending = keys.length + } + + function done (err) { + function end () { + if (cb) cb(err, results) + cb = null + } + if (isSync) queueMicrotask(end) + else end() + } + + function each (i, err, result) { + results[i] = result + if (--pending === 0 || err) { + done(err) + } + } + + if (!pending) { + // empty + done(null) + } else if (keys) { + // object + keys.forEach(function (key) { + tasks[key](function (err, result) { each(key, err, result) }) + }) + } else { + // array + tasks.forEach(function (task, i) { + task(function (err, result) { each(i, err, result) }) + }) + } + + isSync = false +} diff --git a/node_modules/run-parallel/package.json b/node_modules/run-parallel/package.json new file mode 100644 index 00000000..1f147578 --- /dev/null +++ b/node_modules/run-parallel/package.json @@ -0,0 +1,58 @@ +{ + "name": "run-parallel", + "description": "Run an array of functions in parallel", + "version": "1.2.0", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/run-parallel/issues" + }, + "dependencies": { + "queue-microtask": "^1.2.2" + }, + "devDependencies": { + "airtap": "^3.0.0", + "standard": "*", + "tape": "^5.0.1" + }, + "homepage": "https://github.com/feross/run-parallel", + "keywords": [ + "parallel", + "async", + "function", + "callback", + "asynchronous", + "run", + "array", + "run parallel" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/feross/run-parallel.git" + }, + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "airtap -- test/*.js", + "test-browser-local": "airtap --local -- test/*.js", + "test-node": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/semver/LICENSE b/node_modules/semver/LICENSE new file mode 100644 index 00000000..19129e31 --- /dev/null +++ b/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/semver/README.md b/node_modules/semver/README.md new file mode 100644 index 00000000..e9522153 --- /dev/null +++ b/node_modules/semver/README.md @@ -0,0 +1,664 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +You can also just load the module for the function that you care about if +you'd like to minimize your footprint. + +```js +// load the whole API at once in a single object +const semver = require('semver') + +// or just load the bits you need +// all of them listed here, just pick and choose what you want + +// classes +const SemVer = require('semver/classes/semver') +const Comparator = require('semver/classes/comparator') +const Range = require('semver/classes/range') + +// functions for working with versions +const semverParse = require('semver/functions/parse') +const semverValid = require('semver/functions/valid') +const semverClean = require('semver/functions/clean') +const semverInc = require('semver/functions/inc') +const semverDiff = require('semver/functions/diff') +const semverMajor = require('semver/functions/major') +const semverMinor = require('semver/functions/minor') +const semverPatch = require('semver/functions/patch') +const semverPrerelease = require('semver/functions/prerelease') +const semverCompare = require('semver/functions/compare') +const semverRcompare = require('semver/functions/rcompare') +const semverCompareLoose = require('semver/functions/compare-loose') +const semverCompareBuild = require('semver/functions/compare-build') +const semverSort = require('semver/functions/sort') +const semverRsort = require('semver/functions/rsort') + +// low-level comparators between versions +const semverGt = require('semver/functions/gt') +const semverLt = require('semver/functions/lt') +const semverEq = require('semver/functions/eq') +const semverNeq = require('semver/functions/neq') +const semverGte = require('semver/functions/gte') +const semverLte = require('semver/functions/lte') +const semverCmp = require('semver/functions/cmp') +const semverCoerce = require('semver/functions/coerce') + +// working with ranges +const semverSatisfies = require('semver/functions/satisfies') +const semverMaxSatisfying = require('semver/ranges/max-satisfying') +const semverMinSatisfying = require('semver/ranges/min-satisfying') +const semverToComparators = require('semver/ranges/to-comparators') +const semverMinVersion = require('semver/ranges/min-version') +const semverValidRange = require('semver/ranges/valid') +const semverOutside = require('semver/ranges/outside') +const semverGtr = require('semver/ranges/gtr') +const semverLtr = require('semver/ranges/ltr') +const semverIntersects = require('semver/ranges/intersects') +const semverSimplifyRange = require('semver/ranges/simplify') +const semverRangeSubset = require('semver/ranges/subset') +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, prerelease, or release. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-n <0|1> + This is the base to be used for the prerelease identifier. + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. +Support for stripping a leading "v" is kept for compatibility with `v1.0.0` of the SemVer +specification but should not be used anymore. + +## Ranges + +A `version range` is a set of `comparators` that specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and +would match the versions `2.0.0` and `3.1.0`, but not the versions +`1.0.1` or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. +Version `3.4.5` *would* satisfy the range because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose of this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range-matching +semantics. + +Second, a user who has opted into using a prerelease version has +indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for range-matching) +by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +To get out of the prerelease phase, use the `release` option: + +```bash +$ semver 1.2.4-beta.1 -i release +1.2.4 +``` + +#### Prerelease Identifier Base + +The method `.inc` takes an optional parameter 'identifierBase' string +that will let you let your prerelease number as zero-based or one-based. +Set to `false` to omit the prerelease number altogether. +If you do not specify this parameter, it will default to zero-based. + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', '1') +// '1.2.4-beta.1' +``` + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', false) +// '1.2.4-beta' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n 1 +1.2.4-beta.1 +``` + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n false +1.2.4-beta +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless + `includePrerelease` is specified, in which case any version at all + satisfies) +* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0-0` +* `^0.2.3` := `>=0.2.3 <0.3.0-0` +* `^0.0.3` := `>=0.0.3 <0.0.4-0` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0-0` +* `^0.0.x` := `>=0.0.0 <0.1.0-0` +* `^0.0` := `>=0.0.0 <0.1.0-0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0-0` +* `^0.x` := `>=0.0.0 <1.0.0-0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose`: Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease`: Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, releaseType, options, identifier, identifierBase)`: + Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, `prerelease`, or `release`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, `prerelease` will work the + same as `prepatch`. It increments the patch version and then makes a + prerelease. If the input version is already a prerelease it simply + increments it. + * `release` will remove any prerelease part of the version. + * `identifier` can be used to prefix `premajor`, `preminor`, + `prepatch`, or `prerelease` version increments. `identifierBase` + is the base to be used for the `prerelease` identifier. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of `compare`. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. +* `compareLoose(v1, v2)`: Short for `compare(v1, v2, { loose: true })`. +* `diff(v1, v2)`: Returns the difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Sorting + +* `sort(versions)`: Returns a sorted array of versions based on the `compareBuild` + function. +* `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on + the `compareBuild` function in descending order. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid. +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can match + the given range. +* `gtr(version, range)`: Return `true` if the version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if the version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the range comparators intersect. +* `simplifyRange(versions, range)`: Return a "simplified" range that + matches the same items in the `versions` list as the range specified. Note + that it does *not* guarantee that it would match the same versions in all + cases, only for the set of versions provided. This is useful when + generating ranges by joining together multiple versions with `||` + programmatically, to provide the user with something a bit more + ergonomic. If the provided range is shorter in string-length than the + generated range, then that is returned. +* `subset(subRange, superRange)`: Return `true` if the `subRange` range is + entirely contained by the `superRange` range. + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +If the `options.includePrerelease` flag is set, then the `coerce` result will contain +prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2` +will preserve prerelease `rc.1` and build `rev.2` in the result. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `'2.1.5'` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Constants + +As a convenience, helper constants are exported to provide information about what `node-semver` supports: + +### `RELEASE_TYPES` + +- major +- premajor +- minor +- preminor +- patch +- prepatch +- prerelease + +``` +const semver = require('semver'); + +if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) { + console.log('This is a valid release type!'); +} else { + console.warn('This is NOT a valid release type!'); +} +``` + +### `SEMVER_SPEC_VERSION` + +2.0.0 + +``` +const semver = require('semver'); + +console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION); +``` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/simplify')` +* `require('semver/ranges/subset')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` + diff --git a/node_modules/semver/bin/semver.js b/node_modules/semver/bin/semver.js new file mode 100755 index 00000000..dbb1bf53 --- /dev/null +++ b/node_modules/semver/bin/semver.js @@ -0,0 +1,191 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +'use strict' + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +let identifierBase + +const semver = require('../') +const parseOptions = require('../internal/parse-options') + +let reverse = false + +let options = {} + +const main = () => { + if (!argv.length) { + return help() + } + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + const value = a.slice(indexOfEqualSign + 1) + a = a.slice(0, indexOfEqualSign) + argv.unshift(value) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + case 'release': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-n': + identifierBase = argv.shift() + if (identifierBase === 'false') { + identifierBase = false + } + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + options = parseOptions({ loose, includePrerelease, rtl }) + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) { + return fail() + } + if (inc && (versions.length !== 1 || range.length)) { + return failInc() + } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) { + return fail() + } + } + versions + .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options)) + .map(v => semver.clean(v, options)) + .map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v) + .forEach(v => console.log(v)) +} + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, prerelease, or release. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +-n + Base number to be used for the prerelease identifier. + Can be either 0 or 1, or false to omit the number altogether. + Defaults to 0. + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/semver/classes/comparator.js b/node_modules/semver/classes/comparator.js new file mode 100644 index 00000000..647c1f09 --- /dev/null +++ b/node_modules/semver/classes/comparator.js @@ -0,0 +1,143 @@ +'use strict' + +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + options = parseOptions(options) + + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} + +module.exports = Comparator + +const parseOptions = require('../internal/parse-options') +const { safeRe: re, t } = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/semver/classes/index.js b/node_modules/semver/classes/index.js new file mode 100644 index 00000000..91c24ec4 --- /dev/null +++ b/node_modules/semver/classes/index.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js'), +} diff --git a/node_modules/semver/classes/range.js b/node_modules/semver/classes/range.js new file mode 100644 index 00000000..f80c2359 --- /dev/null +++ b/node_modules/semver/classes/range.js @@ -0,0 +1,556 @@ +'use strict' + +const SPACE_CHARACTERS = /\s+/g + +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.formatted = undefined + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') + + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.formatted = undefined + } + + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted + } + + format () { + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} + +module.exports = Range + +const LRU = require('../internal/lrucache') +const cache = new LRU() + +const parseOptions = require('../internal/parse-options') +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = require('../internal/re') +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants') + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +// TODO build? +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return `${from} ${to}`.trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/semver/classes/semver.js b/node_modules/semver/classes/semver.js new file mode 100644 index 00000000..2efba0f4 --- /dev/null +++ b/node_modules/semver/classes/semver.js @@ -0,0 +1,319 @@ +'use strict' + +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { safeRe: re, t } = require('../internal/re') + +const parseOptions = require('../internal/parse-options') +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('build compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + if (release.startsWith('pre')) { + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + // Avoid an invalid semver results + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`) + } + } + } + + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + case 'release': + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`) + } + this.prerelease.length = 0 + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 + + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this + } +} + +module.exports = SemVer diff --git a/node_modules/semver/functions/clean.js b/node_modules/semver/functions/clean.js new file mode 100644 index 00000000..79703d63 --- /dev/null +++ b/node_modules/semver/functions/clean.js @@ -0,0 +1,8 @@ +'use strict' + +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/semver/functions/cmp.js b/node_modules/semver/functions/cmp.js new file mode 100644 index 00000000..77487dca --- /dev/null +++ b/node_modules/semver/functions/cmp.js @@ -0,0 +1,54 @@ +'use strict' + +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/semver/functions/coerce.js b/node_modules/semver/functions/coerce.js new file mode 100644 index 00000000..cfe02759 --- /dev/null +++ b/node_modules/semver/functions/coerce.js @@ -0,0 +1,62 @@ +'use strict' + +const SemVer = require('../classes/semver') +const parse = require('./parse') +const { safeRe: re, t } = require('../internal/re') + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 + } + + if (match === null) { + return null + } + + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' + + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +} +module.exports = coerce diff --git a/node_modules/semver/functions/compare-build.js b/node_modules/semver/functions/compare-build.js new file mode 100644 index 00000000..99157cf3 --- /dev/null +++ b/node_modules/semver/functions/compare-build.js @@ -0,0 +1,9 @@ +'use strict' + +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/semver/functions/compare-loose.js b/node_modules/semver/functions/compare-loose.js new file mode 100644 index 00000000..75316346 --- /dev/null +++ b/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/semver/functions/compare.js b/node_modules/semver/functions/compare.js new file mode 100644 index 00000000..63d8090c --- /dev/null +++ b/node_modules/semver/functions/compare.js @@ -0,0 +1,7 @@ +'use strict' + +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/semver/functions/diff.js b/node_modules/semver/functions/diff.js new file mode 100644 index 00000000..04e064e9 --- /dev/null +++ b/node_modules/semver/functions/diff.js @@ -0,0 +1,60 @@ +'use strict' + +const parse = require('./parse.js') + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' + } + + // If the main part has no difference + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return 'minor' + } + return 'patch' + } + } + + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' + + if (v1.major !== v2.major) { + return prefix + 'major' + } + + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } + + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + + // high and low are preleases + return 'prerelease' +} + +module.exports = diff diff --git a/node_modules/semver/functions/eq.js b/node_modules/semver/functions/eq.js new file mode 100644 index 00000000..5f0eead1 --- /dev/null +++ b/node_modules/semver/functions/eq.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/semver/functions/gt.js b/node_modules/semver/functions/gt.js new file mode 100644 index 00000000..84a57ddf --- /dev/null +++ b/node_modules/semver/functions/gt.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/semver/functions/gte.js b/node_modules/semver/functions/gte.js new file mode 100644 index 00000000..7c52bdf2 --- /dev/null +++ b/node_modules/semver/functions/gte.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/semver/functions/inc.js b/node_modules/semver/functions/inc.js new file mode 100644 index 00000000..ff999e9d --- /dev/null +++ b/node_modules/semver/functions/inc.js @@ -0,0 +1,21 @@ +'use strict' + +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/semver/functions/lt.js b/node_modules/semver/functions/lt.js new file mode 100644 index 00000000..2fb32a0e --- /dev/null +++ b/node_modules/semver/functions/lt.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/semver/functions/lte.js b/node_modules/semver/functions/lte.js new file mode 100644 index 00000000..da9ee8f4 --- /dev/null +++ b/node_modules/semver/functions/lte.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/semver/functions/major.js b/node_modules/semver/functions/major.js new file mode 100644 index 00000000..e6d08dc2 --- /dev/null +++ b/node_modules/semver/functions/major.js @@ -0,0 +1,5 @@ +'use strict' + +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/semver/functions/minor.js b/node_modules/semver/functions/minor.js new file mode 100644 index 00000000..9e70ffda --- /dev/null +++ b/node_modules/semver/functions/minor.js @@ -0,0 +1,5 @@ +'use strict' + +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/semver/functions/neq.js b/node_modules/semver/functions/neq.js new file mode 100644 index 00000000..84326b77 --- /dev/null +++ b/node_modules/semver/functions/neq.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/semver/functions/parse.js b/node_modules/semver/functions/parse.js new file mode 100644 index 00000000..d544d33a --- /dev/null +++ b/node_modules/semver/functions/parse.js @@ -0,0 +1,18 @@ +'use strict' + +const SemVer = require('../classes/semver') +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null + } + throw er + } +} + +module.exports = parse diff --git a/node_modules/semver/functions/patch.js b/node_modules/semver/functions/patch.js new file mode 100644 index 00000000..7675162f --- /dev/null +++ b/node_modules/semver/functions/patch.js @@ -0,0 +1,5 @@ +'use strict' + +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/semver/functions/prerelease.js b/node_modules/semver/functions/prerelease.js new file mode 100644 index 00000000..b8fe1db5 --- /dev/null +++ b/node_modules/semver/functions/prerelease.js @@ -0,0 +1,8 @@ +'use strict' + +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/semver/functions/rcompare.js b/node_modules/semver/functions/rcompare.js new file mode 100644 index 00000000..8e1c222b --- /dev/null +++ b/node_modules/semver/functions/rcompare.js @@ -0,0 +1,5 @@ +'use strict' + +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/semver/functions/rsort.js b/node_modules/semver/functions/rsort.js new file mode 100644 index 00000000..5d3d2009 --- /dev/null +++ b/node_modules/semver/functions/rsort.js @@ -0,0 +1,5 @@ +'use strict' + +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/semver/functions/satisfies.js b/node_modules/semver/functions/satisfies.js new file mode 100644 index 00000000..a0264a22 --- /dev/null +++ b/node_modules/semver/functions/satisfies.js @@ -0,0 +1,12 @@ +'use strict' + +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/semver/functions/sort.js b/node_modules/semver/functions/sort.js new file mode 100644 index 00000000..edb24b1d --- /dev/null +++ b/node_modules/semver/functions/sort.js @@ -0,0 +1,5 @@ +'use strict' + +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/semver/functions/valid.js b/node_modules/semver/functions/valid.js new file mode 100644 index 00000000..0db67edc --- /dev/null +++ b/node_modules/semver/functions/valid.js @@ -0,0 +1,8 @@ +'use strict' + +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/semver/index.js b/node_modules/semver/index.js new file mode 100644 index 00000000..285662ac --- /dev/null +++ b/node_modules/semver/index.js @@ -0,0 +1,91 @@ +'use strict' + +// just pre-load all the stuff that index.js lazily exports +const internalRe = require('./internal/re') +const constants = require('./internal/constants') +const SemVer = require('./classes/semver') +const identifiers = require('./internal/identifiers') +const parse = require('./functions/parse') +const valid = require('./functions/valid') +const clean = require('./functions/clean') +const inc = require('./functions/inc') +const diff = require('./functions/diff') +const major = require('./functions/major') +const minor = require('./functions/minor') +const patch = require('./functions/patch') +const prerelease = require('./functions/prerelease') +const compare = require('./functions/compare') +const rcompare = require('./functions/rcompare') +const compareLoose = require('./functions/compare-loose') +const compareBuild = require('./functions/compare-build') +const sort = require('./functions/sort') +const rsort = require('./functions/rsort') +const gt = require('./functions/gt') +const lt = require('./functions/lt') +const eq = require('./functions/eq') +const neq = require('./functions/neq') +const gte = require('./functions/gte') +const lte = require('./functions/lte') +const cmp = require('./functions/cmp') +const coerce = require('./functions/coerce') +const Comparator = require('./classes/comparator') +const Range = require('./classes/range') +const satisfies = require('./functions/satisfies') +const toComparators = require('./ranges/to-comparators') +const maxSatisfying = require('./ranges/max-satisfying') +const minSatisfying = require('./ranges/min-satisfying') +const minVersion = require('./ranges/min-version') +const validRange = require('./ranges/valid') +const outside = require('./ranges/outside') +const gtr = require('./ranges/gtr') +const ltr = require('./ranges/ltr') +const intersects = require('./ranges/intersects') +const simplifyRange = require('./ranges/simplify') +const subset = require('./ranges/subset') +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} diff --git a/node_modules/semver/internal/constants.js b/node_modules/semver/internal/constants.js new file mode 100644 index 00000000..6d1db915 --- /dev/null +++ b/node_modules/semver/internal/constants.js @@ -0,0 +1,37 @@ +'use strict' + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] + +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, +} diff --git a/node_modules/semver/internal/debug.js b/node_modules/semver/internal/debug.js new file mode 100644 index 00000000..20d1e9dc --- /dev/null +++ b/node_modules/semver/internal/debug.js @@ -0,0 +1,11 @@ +'use strict' + +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug diff --git a/node_modules/semver/internal/identifiers.js b/node_modules/semver/internal/identifiers.js new file mode 100644 index 00000000..a4613dee --- /dev/null +++ b/node_modules/semver/internal/identifiers.js @@ -0,0 +1,25 @@ +'use strict' + +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} diff --git a/node_modules/semver/internal/lrucache.js b/node_modules/semver/internal/lrucache.js new file mode 100644 index 00000000..b8bf5262 --- /dev/null +++ b/node_modules/semver/internal/lrucache.js @@ -0,0 +1,42 @@ +'use strict' + +class LRUCache { + constructor () { + this.max = 1000 + this.map = new Map() + } + + get (key) { + const value = this.map.get(key) + if (value === undefined) { + return undefined + } else { + // Remove the key from the map and add it to the end + this.map.delete(key) + this.map.set(key, value) + return value + } + } + + delete (key) { + return this.map.delete(key) + } + + set (key, value) { + const deleted = this.delete(key) + + if (!deleted && value !== undefined) { + // If cache is full, delete the least recently used item + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value + this.delete(firstKey) + } + + this.map.set(key, value) + } + + return this + } +} + +module.exports = LRUCache diff --git a/node_modules/semver/internal/parse-options.js b/node_modules/semver/internal/parse-options.js new file mode 100644 index 00000000..52954541 --- /dev/null +++ b/node_modules/semver/internal/parse-options.js @@ -0,0 +1,17 @@ +'use strict' + +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } + + if (typeof options !== 'object') { + return looseOption + } + + return options +} +module.exports = parseOptions diff --git a/node_modules/semver/internal/re.js b/node_modules/semver/internal/re.js new file mode 100644 index 00000000..4758c58d --- /dev/null +++ b/node_modules/semver/internal/re.js @@ -0,0 +1,223 @@ +'use strict' + +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const safeSrc = exports.safeSrc = [] +const t = exports.t = {} +let R = 0 + +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) + } + return value +} + +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + safeSrc[index] = safe + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. +// Non-numberic identifiers include numberic identifiers but can be longer. +// Therefore non-numberic identifiers must go first. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') diff --git a/node_modules/semver/package.json b/node_modules/semver/package.json new file mode 100644 index 00000000..1fbef5a9 --- /dev/null +++ b/node_modules/semver/package.json @@ -0,0 +1,78 @@ +{ + "name": "semver", + "version": "7.7.2", + "description": "The semantic version parser used by npm.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "lint": "npm run eslint", + "postlint": "template-oss-check", + "lintfix": "npm run eslint -- --fix", + "posttest": "npm run lint", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" + }, + "devDependencies": { + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "4.24.3", + "benchmark": "^2.1.4", + "tap": "^16.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "bin/semver.js" + }, + "files": [ + "bin/", + "lib/", + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "tap": { + "timeout": 30, + "coverage-map": "map.js", + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + }, + "engines": { + "node": ">=10" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "4.24.3", + "engines": ">=10", + "distPaths": [ + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "allowPaths": [ + "/classes/", + "/functions/", + "/internal/", + "/ranges/", + "/index.js", + "/preload.js", + "/range.bnf", + "/benchmarks" + ], + "publish": "true" + } +} diff --git a/node_modules/semver/preload.js b/node_modules/semver/preload.js new file mode 100644 index 00000000..e6c47b9b --- /dev/null +++ b/node_modules/semver/preload.js @@ -0,0 +1,4 @@ +'use strict' + +// XXX remove in v8 or beyond +module.exports = require('./index.js') diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf new file mode 100644 index 00000000..d4c6ae0d --- /dev/null +++ b/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver/ranges/gtr.js b/node_modules/semver/ranges/gtr.js new file mode 100644 index 00000000..0e7601f6 --- /dev/null +++ b/node_modules/semver/ranges/gtr.js @@ -0,0 +1,6 @@ +'use strict' + +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/semver/ranges/intersects.js b/node_modules/semver/ranges/intersects.js new file mode 100644 index 00000000..917be7e4 --- /dev/null +++ b/node_modules/semver/ranges/intersects.js @@ -0,0 +1,9 @@ +'use strict' + +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) +} +module.exports = intersects diff --git a/node_modules/semver/ranges/ltr.js b/node_modules/semver/ranges/ltr.js new file mode 100644 index 00000000..aa5e568e --- /dev/null +++ b/node_modules/semver/ranges/ltr.js @@ -0,0 +1,6 @@ +'use strict' + +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/semver/ranges/max-satisfying.js b/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 00000000..01fe5ae3 --- /dev/null +++ b/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,27 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/semver/ranges/min-satisfying.js b/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 00000000..af89c8ef --- /dev/null +++ b/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,26 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/semver/ranges/min-version.js b/node_modules/semver/ranges/min-version.js new file mode 100644 index 00000000..09a65aa3 --- /dev/null +++ b/node_modules/semver/ranges/min-version.js @@ -0,0 +1,63 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion diff --git a/node_modules/semver/ranges/outside.js b/node_modules/semver/ranges/outside.js new file mode 100644 index 00000000..ca744212 --- /dev/null +++ b/node_modules/semver/ranges/outside.js @@ -0,0 +1,82 @@ +'use strict' + +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const { ANY } = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside diff --git a/node_modules/semver/ranges/simplify.js b/node_modules/semver/ranges/simplify.js new file mode 100644 index 00000000..262732e6 --- /dev/null +++ b/node_modules/semver/ranges/simplify.js @@ -0,0 +1,49 @@ +'use strict' + +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} diff --git a/node_modules/semver/ranges/subset.js b/node_modules/semver/ranges/subset.js new file mode 100644 index 00000000..2c49aef1 --- /dev/null +++ b/node_modules/semver/ranges/subset.js @@ -0,0 +1,249 @@ +'use strict' + +const Range = require('../classes/range.js') +const Comparator = require('../classes/comparator.js') +const { ANY } = Comparator +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} + +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion + } + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + + if (eqSet.size > 1) { + return null + } + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset diff --git a/node_modules/semver/ranges/to-comparators.js b/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 00000000..5be25196 --- /dev/null +++ b/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,10 @@ +'use strict' + +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/semver/ranges/valid.js b/node_modules/semver/ranges/valid.js new file mode 100644 index 00000000..cc6b0e9f --- /dev/null +++ b/node_modules/semver/ranges/valid.js @@ -0,0 +1,13 @@ +'use strict' + +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/shebang-command/index.js b/node_modules/shebang-command/index.js new file mode 100644 index 00000000..f35db308 --- /dev/null +++ b/node_modules/shebang-command/index.js @@ -0,0 +1,19 @@ +'use strict'; +const shebangRegex = require('shebang-regex'); + +module.exports = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; diff --git a/node_modules/shebang-command/license b/node_modules/shebang-command/license new file mode 100644 index 00000000..db6bc32c --- /dev/null +++ b/node_modules/shebang-command/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Kevin Mårtensson (github.com/kevva) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/shebang-command/package.json b/node_modules/shebang-command/package.json new file mode 100644 index 00000000..18e3c046 --- /dev/null +++ b/node_modules/shebang-command/package.json @@ -0,0 +1,34 @@ +{ + "name": "shebang-command", + "version": "2.0.0", + "description": "Get the command from a shebang", + "license": "MIT", + "repository": "kevva/shebang-command", + "author": { + "name": "Kevin Mårtensson", + "email": "kevinmartensson@gmail.com", + "url": "github.com/kevva" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "cmd", + "command", + "parse", + "shebang" + ], + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "devDependencies": { + "ava": "^2.3.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/shebang-command/readme.md b/node_modules/shebang-command/readme.md new file mode 100644 index 00000000..84feb442 --- /dev/null +++ b/node_modules/shebang-command/readme.md @@ -0,0 +1,34 @@ +# shebang-command [![Build Status](https://travis-ci.org/kevva/shebang-command.svg?branch=master)](https://travis-ci.org/kevva/shebang-command) + +> Get the command from a shebang + + +## Install + +``` +$ npm install shebang-command +``` + + +## Usage + +```js +const shebangCommand = require('shebang-command'); + +shebangCommand('#!/usr/bin/env node'); +//=> 'node' + +shebangCommand('#!/bin/bash'); +//=> 'bash' +``` + + +## API + +### shebangCommand(string) + +#### string + +Type: `string` + +String containing a shebang. diff --git a/node_modules/shebang-regex/index.d.ts b/node_modules/shebang-regex/index.d.ts new file mode 100644 index 00000000..61d034b3 --- /dev/null +++ b/node_modules/shebang-regex/index.d.ts @@ -0,0 +1,22 @@ +/** +Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line. + +@example +``` +import shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` +*/ +declare const shebangRegex: RegExp; + +export = shebangRegex; diff --git a/node_modules/shebang-regex/index.js b/node_modules/shebang-regex/index.js new file mode 100644 index 00000000..63fc4a0b --- /dev/null +++ b/node_modules/shebang-regex/index.js @@ -0,0 +1,2 @@ +'use strict'; +module.exports = /^#!(.*)/; diff --git a/node_modules/shebang-regex/license b/node_modules/shebang-regex/license new file mode 100644 index 00000000..e7af2f77 --- /dev/null +++ b/node_modules/shebang-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/shebang-regex/package.json b/node_modules/shebang-regex/package.json new file mode 100644 index 00000000..00ab30fe --- /dev/null +++ b/node_modules/shebang-regex/package.json @@ -0,0 +1,35 @@ +{ + "name": "shebang-regex", + "version": "3.0.0", + "description": "Regular expression for matching a shebang line", + "license": "MIT", + "repository": "sindresorhus/shebang-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "regex", + "regexp", + "shebang", + "match", + "test", + "line" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/shebang-regex/readme.md b/node_modules/shebang-regex/readme.md new file mode 100644 index 00000000..5ecf863a --- /dev/null +++ b/node_modules/shebang-regex/readme.md @@ -0,0 +1,33 @@ +# shebang-regex [![Build Status](https://travis-ci.org/sindresorhus/shebang-regex.svg?branch=master)](https://travis-ci.org/sindresorhus/shebang-regex) + +> Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line + + +## Install + +``` +$ npm install shebang-regex +``` + + +## Usage + +```js +const shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/strip-json-comments/index.d.ts b/node_modules/strip-json-comments/index.d.ts new file mode 100644 index 00000000..28ba3c8a --- /dev/null +++ b/node_modules/strip-json-comments/index.d.ts @@ -0,0 +1,36 @@ +declare namespace stripJsonComments { + interface Options { + /** + Replace comments with whitespace instead of stripping them entirely. + + @default true + */ + readonly whitespace?: boolean; + } +} + +/** +Strip comments from JSON. Lets you use comments in your JSON files! + +It will replace single-line comments `//` and multi-line comments `/**\/` with whitespace. This allows JSON error positions to remain as close as possible to the original source. + +@param jsonString - Accepts a string with JSON. +@returns A JSON string without comments. + +@example +``` +const json = `{ + // Rainbows + "unicorn": "cake" +}`; + +JSON.parse(stripJsonComments(json)); +//=> {unicorn: 'cake'} +``` +*/ +declare function stripJsonComments( + jsonString: string, + options?: stripJsonComments.Options +): string; + +export = stripJsonComments; diff --git a/node_modules/strip-json-comments/index.js b/node_modules/strip-json-comments/index.js new file mode 100644 index 00000000..bb00b38b --- /dev/null +++ b/node_modules/strip-json-comments/index.js @@ -0,0 +1,77 @@ +'use strict'; +const singleComment = Symbol('singleComment'); +const multiComment = Symbol('multiComment'); +const stripWithoutWhitespace = () => ''; +const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, ' '); + +const isEscaped = (jsonString, quotePosition) => { + let index = quotePosition - 1; + let backslashCount = 0; + + while (jsonString[index] === '\\') { + index -= 1; + backslashCount += 1; + } + + return Boolean(backslashCount % 2); +}; + +module.exports = (jsonString, options = {}) => { + if (typeof jsonString !== 'string') { + throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``); + } + + const strip = options.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + let insideString = false; + let insideComment = false; + let offset = 0; + let result = ''; + + for (let i = 0; i < jsonString.length; i++) { + const currentCharacter = jsonString[i]; + const nextCharacter = jsonString[i + 1]; + + if (!insideComment && currentCharacter === '"') { + const escaped = isEscaped(jsonString, i); + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentCharacter + nextCharacter === '//') { + result += jsonString.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentCharacter + nextCharacter === '\r\n') { + i++; + insideComment = false; + result += strip(jsonString, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentCharacter === '\n') { + insideComment = false; + result += strip(jsonString, offset, i); + offset = i; + } else if (!insideComment && currentCharacter + nextCharacter === '/*') { + result += jsonString.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentCharacter + nextCharacter === '*/') { + i++; + insideComment = false; + result += strip(jsonString, offset, i + 1); + offset = i + 1; + continue; + } + } + + return result + (insideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset)); +}; diff --git a/node_modules/strip-json-comments/license b/node_modules/strip-json-comments/license new file mode 100644 index 00000000..fa7ceba3 --- /dev/null +++ b/node_modules/strip-json-comments/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/strip-json-comments/package.json b/node_modules/strip-json-comments/package.json new file mode 100644 index 00000000..ce7875aa --- /dev/null +++ b/node_modules/strip-json-comments/package.json @@ -0,0 +1,47 @@ +{ + "name": "strip-json-comments", + "version": "3.1.1", + "description": "Strip comments from JSON. Lets you use comments in your JSON files!", + "license": "MIT", + "repository": "sindresorhus/strip-json-comments", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd", + "bench": "matcha benchmark.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "json", + "strip", + "comments", + "remove", + "delete", + "trim", + "multiline", + "parse", + "config", + "configuration", + "settings", + "util", + "env", + "environment", + "jsonc" + ], + "devDependencies": { + "ava": "^1.4.1", + "matcha": "^0.7.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/strip-json-comments/readme.md b/node_modules/strip-json-comments/readme.md new file mode 100644 index 00000000..cc542e50 --- /dev/null +++ b/node_modules/strip-json-comments/readme.md @@ -0,0 +1,78 @@ +# strip-json-comments [![Build Status](https://travis-ci.com/sindresorhus/strip-json-comments.svg?branch=master)](https://travis-ci.com/github/sindresorhus/strip-json-comments) + +> Strip comments from JSON. Lets you use comments in your JSON files! + +This is now possible: + +```js +{ + // Rainbows + "unicorn": /* ❤ */ "cake" +} +``` + +It will replace single-line comments `//` and multi-line comments `/**/` with whitespace. This allows JSON error positions to remain as close as possible to the original source. + +Also available as a [Gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[Grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[Broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin. + +## Install + +``` +$ npm install strip-json-comments +``` + +## Usage + +```js +const json = `{ + // Rainbows + "unicorn": /* ❤ */ "cake" +}`; + +JSON.parse(stripJsonComments(json)); +//=> {unicorn: 'cake'} +``` + +## API + +### stripJsonComments(jsonString, options?) + +#### jsonString + +Type: `string` + +Accepts a string with JSON and returns a string without comments. + +#### options + +Type: `object` + +##### whitespace + +Type: `boolean`\ +Default: `true` + +Replace comments with whitespace instead of stripping them entirely. + +## Benchmark + +``` +$ npm run bench +``` + +## Related + +- [strip-json-comments-cli](https://github.com/sindresorhus/strip-json-comments-cli) - CLI for this module +- [strip-css-comments](https://github.com/sindresorhus/strip-css-comments) - Strip comments from CSS + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/supports-color/browser.js b/node_modules/supports-color/browser.js new file mode 100644 index 00000000..62afa3a7 --- /dev/null +++ b/node_modules/supports-color/browser.js @@ -0,0 +1,5 @@ +'use strict'; +module.exports = { + stdout: false, + stderr: false +}; diff --git a/node_modules/supports-color/index.js b/node_modules/supports-color/index.js new file mode 100644 index 00000000..6fada390 --- /dev/null +++ b/node_modules/supports-color/index.js @@ -0,0 +1,135 @@ +'use strict'; +const os = require('os'); +const tty = require('tty'); +const hasFlag = require('has-flag'); + +const {env} = process; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; +} + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; diff --git a/node_modules/supports-color/license b/node_modules/supports-color/license new file mode 100644 index 00000000..e7af2f77 --- /dev/null +++ b/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/supports-color/package.json b/node_modules/supports-color/package.json new file mode 100644 index 00000000..f7182edc --- /dev/null +++ b/node_modules/supports-color/package.json @@ -0,0 +1,53 @@ +{ + "name": "supports-color", + "version": "7.2.0", + "description": "Detect whether a terminal supports color", + "license": "MIT", + "repository": "chalk/supports-color", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "browser.js" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "dependencies": { + "has-flag": "^4.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "import-fresh": "^3.0.0", + "xo": "^0.24.0" + }, + "browser": "browser.js" +} diff --git a/node_modules/supports-color/readme.md b/node_modules/supports-color/readme.md new file mode 100644 index 00000000..36542285 --- /dev/null +++ b/node_modules/supports-color/readme.md @@ -0,0 +1,76 @@ +# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color) + +> Detect whether a terminal supports color + + +## Install + +``` +$ npm install supports-color +``` + + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- diff --git a/node_modules/to-regex-range/LICENSE b/node_modules/to-regex-range/LICENSE new file mode 100644 index 00000000..7cccaf9e --- /dev/null +++ b/node_modules/to-regex-range/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/to-regex-range/README.md b/node_modules/to-regex-range/README.md new file mode 100644 index 00000000..38887daf --- /dev/null +++ b/node_modules/to-regex-range/README.md @@ -0,0 +1,305 @@ +# to-regex-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/to-regex-range.svg?style=flat)](https://www.npmjs.com/package/to-regex-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![Linux Build Status](https://img.shields.io/travis/micromatch/to-regex-range.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/to-regex-range) + +> Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save to-regex-range +``` + +
+What does this do? + +
+ +This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. + +**Example** + +```js +const toRegexRange = require('to-regex-range'); +const regex = new RegExp(toRegexRange('15', '95')); +``` + +A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string). + +
+ +
+ +
+Why use this library? + +
+ +### Convenience + +Creating regular expressions for matching numbers gets deceptively complicated pretty fast. + +For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: + +* regex for matching `1` => `/1/` (easy enough) +* regex for matching `1` through `5` => `/[1-5]/` (not bad...) +* regex for matching `1` or `5` => `/(1|5)/` (still easy...) +* regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) +* regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) +* regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) +* regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) + +The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. + +**Learn more** + +If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. + +### Heavily tested + +As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. + +Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. + +### Optimized + +Generated regular expressions are optimized: + +* duplicate sequences and character classes are reduced using quantifiers +* smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative +* uses fragment caching to avoid processing the same exact string more than once + +
+ +
+ +## Usage + +Add this library to your javascript application with the following line of code + +```js +const toRegexRange = require('to-regex-range'); +``` + +The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). + +```js +const source = toRegexRange('15', '95'); +//=> 1[5-9]|[2-8][0-9]|9[0-5] + +const regex = new RegExp(`^${source}$`); +console.log(regex.test('14')); //=> false +console.log(regex.test('50')); //=> true +console.log(regex.test('94')); //=> true +console.log(regex.test('96')); //=> false +``` + +## Options + +### options.capture + +**Type**: `boolean` + +**Deafault**: `undefined` + +Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. + +```js +console.log(toRegexRange('-10', '10')); +//=> -[1-9]|-?10|[0-9] + +console.log(toRegexRange('-10', '10', { capture: true })); +//=> (-[1-9]|-?10|[0-9]) +``` + +### options.shorthand + +**Type**: `boolean` + +**Deafault**: `undefined` + +Use the regex shorthand for `[0-9]`: + +```js +console.log(toRegexRange('0', '999999')); +//=> [0-9]|[1-9][0-9]{1,5} + +console.log(toRegexRange('0', '999999', { shorthand: true })); +//=> \d|[1-9]\d{1,5} +``` + +### options.relaxZeros + +**Type**: `boolean` + +**Default**: `true` + +This option relaxes matching for leading zeros when when ranges are zero-padded. + +```js +const source = toRegexRange('-0010', '0010'); +const regex = new RegExp(`^${source}$`); +console.log(regex.test('-10')); //=> true +console.log(regex.test('-010')); //=> true +console.log(regex.test('-0010')); //=> true +console.log(regex.test('10')); //=> true +console.log(regex.test('010')); //=> true +console.log(regex.test('0010')); //=> true +``` + +When `relaxZeros` is false, matching is strict: + +```js +const source = toRegexRange('-0010', '0010', { relaxZeros: false }); +const regex = new RegExp(`^${source}$`); +console.log(regex.test('-10')); //=> false +console.log(regex.test('-010')); //=> false +console.log(regex.test('-0010')); //=> true +console.log(regex.test('10')); //=> false +console.log(regex.test('010')); //=> false +console.log(regex.test('0010')); //=> true +``` + +## Examples + +| **Range** | **Result** | **Compile time** | +| --- | --- | --- | +| `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132μs_ | +| `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50μs_ | +| `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42μs_ | +| `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109μs_ | +| `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51μs_ | +| `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31μs_ | +| `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24μs_ | +| `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23μs_ | +| `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30μs_ | +| `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43μs_ | +| `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38μs_ | +| `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24μs_ | +| `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32μs_ | +| `toRegexRange(5, 5)` | `5` | _8μs_ | +| `toRegexRange(5, 6)` | `5\|6` | _11μs_ | +| `toRegexRange(1, 2)` | `1\|2` | _6μs_ | +| `toRegexRange(1, 5)` | `[1-5]` | _15μs_ | +| `toRegexRange(1, 10)` | `[1-9]\|10` | _22μs_ | +| `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25μs_ | +| `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31μs_ | +| `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34μs_ | +| `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36μs_ | +| `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42μs_ | +| `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42μs_ | + +## Heads up! + +**Order of arguments** + +When the `min` is larger than the `max`, values will be flipped to create a valid range: + +```js +toRegexRange('51', '29'); +``` + +Is effectively flipped to: + +```js +toRegexRange('29', '51'); +//=> 29|[3-4][0-9]|5[0-1] +``` + +**Steps / increments** + +This library does not support steps (increments). A pr to add support would be welcome. + +## History + +### v2.0.0 - 2017-04-21 + +**New features** + +Adds support for zero-padding! + +### v1.0.0 + +**Optimizations** + +Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. + +## Attribution + +Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.") +* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") +* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") +* [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") +* [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 63 | [jonschlinkert](https://github.com/jonschlinkert) | +| 3 | [doowb](https://github.com/doowb) | +| 2 | [realityking](https://github.com/realityking) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! + + + + + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._ \ No newline at end of file diff --git a/node_modules/to-regex-range/index.js b/node_modules/to-regex-range/index.js new file mode 100644 index 00000000..77fbaced --- /dev/null +++ b/node_modules/to-regex-range/index.js @@ -0,0 +1,288 @@ +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +const isNumber = require('is-number'); + +const toRegexRange = (min, max, options) => { + if (isNumber(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives, opts); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; + let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; + let intersected = filterPatterns(neg, pos, '-?', true, options) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit, options); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange.cache = {}; +toRegexRange.clearCache = () => (toRegexRange.cache = {}); + +/** + * Expose `toRegexRange` + */ + +module.exports = toRegexRange; diff --git a/node_modules/to-regex-range/package.json b/node_modules/to-regex-range/package.json new file mode 100644 index 00000000..4ef194f3 --- /dev/null +++ b/node_modules/to-regex-range/package.json @@ -0,0 +1,88 @@ +{ + "name": "to-regex-range", + "description": "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.", + "version": "5.0.1", + "homepage": "https://github.com/micromatch/to-regex-range", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Rouven Weßling (www.rouvenwessling.de)" + ], + "repository": "micromatch/to-regex-range", + "bugs": { + "url": "https://github.com/micromatch/to-regex-range/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=8.0" + }, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "is-number": "^7.0.0" + }, + "devDependencies": { + "fill-range": "^6.0.0", + "gulp-format-md": "^2.0.0", + "mocha": "^6.0.2", + "text-table": "^0.2.0", + "time-diff": "^0.3.1" + }, + "keywords": [ + "bash", + "date", + "expand", + "expansion", + "expression", + "glob", + "match", + "match date", + "match number", + "match numbers", + "match year", + "matches", + "matching", + "number", + "numbers", + "numerical", + "range", + "ranges", + "regex", + "regexp", + "regular", + "regular expression", + "sequence" + ], + "verb": { + "layout": "default", + "toc": false, + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "helpers": { + "examples": { + "displayName": "examples" + } + }, + "related": { + "list": [ + "expand-range", + "fill-range", + "micromatch", + "repeat-element", + "repeat-string" + ] + } + } +} diff --git a/node_modules/ts-api-utils/LICENSE.md b/node_modules/ts-api-utils/LICENSE.md new file mode 100644 index 00000000..08520a1e --- /dev/null +++ b/node_modules/ts-api-utils/LICENSE.md @@ -0,0 +1,20 @@ +# MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ts-api-utils/README.md b/node_modules/ts-api-utils/README.md new file mode 100644 index 00000000..2586c999 --- /dev/null +++ b/node_modules/ts-api-utils/README.md @@ -0,0 +1,86 @@ +

TypeScript API Utils

+ +

+ Utility functions for working with TypeScript's API. + Successor to the wonderful tsutils. + 🛠️️ +

+ +

+ + +All Contributors: 10 👪 + + + 🤝 Code of Conduct: Kept + 🧪 Coverage + 📚 Documentation Coverage + 📝 License: MIT + 📦 npm version + 💪 TypeScript: Strict +

+ +## Usage + +```shell +npm i ts-api-utils +``` + +```ts +import * as tsutils from "ts-api-utils"; + +tsutils.forEachToken(/* ... */); +``` + +### API + +`ts-api-utils` provides many utility functions. +Check out our API docs for details: + +📝 [ts-api-utils API docs](https://joshuakgoldberg.github.io/ts-api-utils). + +## Development + +See [`.github/CONTRIBUTING.md`](./.github/CONTRIBUTING.md). +Thanks! 💖 + +## Contributors + +Many thanks to [@ajafff](https://github.com/ajafff) for creating the original [`tsutils`](https://github.com/ajafff/tsutils) ([original license: MIT](https://github.com/ajafff/tsutils/blob/26b195358ec36d59f00333115aa3ffd9611ca78b/LICENSE)) that this project was originally based on! 🙏 + + + + + + + + + + + + + + + + + + + + + + + + +
Dan Vanderkam
Dan Vanderkam

🐛
Johannes Chorzempa
Johannes Chorzempa

📖 💻
Josh Goldberg
Josh Goldberg

🐛 💻 📖 📆 ⚠️ 🔧 🚧 🚇 🤔
Kirill Cherkashin
Kirill Cherkashin

💻
Kirk Waiblinger
Kirk Waiblinger

🐛 💻
Klaus Meinhardt
Klaus Meinhardt

💻 ⚠️
Lars Kappert
Lars Kappert

💻
Rebecca Stevens
Rebecca Stevens

🐛 💻 📖 📆 ⚠️ 🔧 🚇 🚧 🤔
Ronen Amiel
Ronen Amiel

⚠️
fisker Cheung
fisker Cheung

💻
+ + + + + + + + + +> 💙 This package was templated with [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app). + +> _"My tools! I have to have my tools!" - Dennis Reynolds_ diff --git a/node_modules/ts-api-utils/lib/index.cjs b/node_modules/ts-api-utils/lib/index.cjs new file mode 100644 index 00000000..60ebd6ff --- /dev/null +++ b/node_modules/ts-api-utils/lib/index.cjs @@ -0,0 +1,2282 @@ +'use strict'; + +var ts9 = require('typescript'); + +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } + +var ts9__default = /*#__PURE__*/_interopDefault(ts9); + +// src/comments.ts +function forEachToken(node, callback, sourceFile = node.getSourceFile()) { + const queue = []; + while (true) { + if (ts9__default.default.isTokenKind(node.kind)) { + callback(node); + } else { + const children = node.getChildren(sourceFile); + if (children.length === 1) { + node = children[0]; + continue; + } + for (let i = children.length - 1; i >= 0; --i) { + queue.push(children[i]); + } + } + if (queue.length === 0) { + break; + } + node = queue.pop(); + } +} + +// src/comments.ts +function forEachComment(node, callback, sourceFile = node.getSourceFile()) { + const fullText = sourceFile.text; + const notJsx = sourceFile.languageVariant !== ts9__default.default.LanguageVariant.JSX; + return forEachToken( + node, + (token) => { + if (token.pos === token.end) { + return; + } + if (token.kind !== ts9__default.default.SyntaxKind.JsxText) { + ts9__default.default.forEachLeadingCommentRange( + fullText, + // skip shebang at position 0 + token.pos === 0 ? (ts9__default.default.getShebang(fullText) ?? "").length : token.pos, + commentCallback + ); + } + if (notJsx || canHaveTrailingTrivia(token)) { + return ts9__default.default.forEachTrailingCommentRange( + fullText, + token.end, + commentCallback + ); + } + }, + sourceFile + ); + function commentCallback(pos, end, kind) { + callback(fullText, { end, kind, pos }); + } +} +function canHaveTrailingTrivia(token) { + switch (token.kind) { + case ts9__default.default.SyntaxKind.CloseBraceToken: + return token.parent.kind !== ts9__default.default.SyntaxKind.JsxExpression || !isJsxElementOrFragment(token.parent.parent); + case ts9__default.default.SyntaxKind.GreaterThanToken: + switch (token.parent.kind) { + case ts9__default.default.SyntaxKind.JsxClosingElement: + case ts9__default.default.SyntaxKind.JsxClosingFragment: + return !isJsxElementOrFragment(token.parent.parent.parent); + case ts9__default.default.SyntaxKind.JsxOpeningElement: + return token.end !== token.parent.end; + case ts9__default.default.SyntaxKind.JsxOpeningFragment: + return false; + // would be inside the fragment + case ts9__default.default.SyntaxKind.JsxSelfClosingElement: + return token.end !== token.parent.end || // if end is not equal, this is part of the type arguments list + !isJsxElementOrFragment(token.parent.parent); + } + } + return true; +} +function isJsxElementOrFragment(node) { + return node.kind === ts9__default.default.SyntaxKind.JsxElement || node.kind === ts9__default.default.SyntaxKind.JsxFragment; +} +function isCompilerOptionEnabled(options, option) { + switch (option) { + case "allowJs": + return options.allowJs === undefined ? isCompilerOptionEnabled(options, "checkJs") : options.allowJs; + case "allowSyntheticDefaultImports": + return options.allowSyntheticDefaultImports !== undefined ? options.allowSyntheticDefaultImports : isCompilerOptionEnabled(options, "esModuleInterop") || options.module === ts9__default.default.ModuleKind.System; + case "alwaysStrict": + case "noImplicitAny": + case "noImplicitThis": + case "strictBindCallApply": + case "strictFunctionTypes": + case "strictNullChecks": + case "strictPropertyInitialization": + return isStrictCompilerOptionEnabled( + options, + option + ); + case "declaration": + return options.declaration || isCompilerOptionEnabled(options, "composite"); + case "declarationMap": + case "emitDeclarationOnly": + case "stripInternal": + return options[option] === true && isCompilerOptionEnabled(options, "declaration"); + case "incremental": + return options.incremental === undefined ? isCompilerOptionEnabled(options, "composite") : options.incremental; + case "noUncheckedIndexedAccess": + return options.noUncheckedIndexedAccess === true && isCompilerOptionEnabled(options, "strictNullChecks"); + case "skipDefaultLibCheck": + return options.skipDefaultLibCheck || isCompilerOptionEnabled(options, "skipLibCheck"); + case "suppressImplicitAnyIndexErrors": + return ( + // eslint-disable-next-line @typescript-eslint/no-deprecated + options.suppressImplicitAnyIndexErrors === true && isCompilerOptionEnabled(options, "noImplicitAny") + ); + } + return options[option] === true; +} +function isStrictCompilerOptionEnabled(options, option) { + return (options.strict ? options[option] !== false : options[option] === true) && (option !== "strictPropertyInitialization" || isStrictCompilerOptionEnabled(options, "strictNullChecks")); +} +function isModifierFlagSet(node, flag) { + return isFlagSet(ts9__default.default.getCombinedModifierFlags(node), flag); +} +function isFlagSet(allFlags, flag) { + return (allFlags & flag) !== 0; +} +function isFlagSetOnObject(obj, flag) { + return isFlagSet(obj.flags, flag); +} +var isNodeFlagSet = isFlagSetOnObject; +function isObjectFlagSet(objectType, flag) { + return isFlagSet(objectType.objectFlags, flag); +} +var isSymbolFlagSet = isFlagSetOnObject; +function isTransientSymbolLinksFlagSet(links, flag) { + return isFlagSet(links.checkFlags, flag); +} +var isTypeFlagSet = isFlagSetOnObject; + +// src/modifiers.ts +function includesModifier(modifiers, ...kinds) { + if (modifiers === undefined) { + return false; + } + for (const modifier of modifiers) { + if (kinds.includes(modifier.kind)) { + return true; + } + } + return false; +} +function isAssignmentKind(kind) { + return kind >= ts9__default.default.SyntaxKind.FirstAssignment && kind <= ts9__default.default.SyntaxKind.LastAssignment; +} +function isNumericPropertyName(name) { + return String(+name) === name; +} +function isValidPropertyAccess(text, languageVersion = ts9__default.default.ScriptTarget.Latest) { + if (text.length === 0) { + return false; + } + let ch = text.codePointAt(0); + if (!ts9__default.default.isIdentifierStart(ch, languageVersion)) { + return false; + } + for (let i = charSize(ch); i < text.length; i += charSize(ch)) { + ch = text.codePointAt(i); + if (!ts9__default.default.isIdentifierPart(ch, languageVersion)) { + return false; + } + } + return true; +} +function charSize(ch) { + return ch >= 65536 ? 2 : 1; +} + +// src/nodes/access.ts +var AccessKind = /* @__PURE__ */ ((AccessKind2) => { + AccessKind2[AccessKind2["None"] = 0] = "None"; + AccessKind2[AccessKind2["Read"] = 1] = "Read"; + AccessKind2[AccessKind2["Write"] = 2] = "Write"; + AccessKind2[AccessKind2["Delete"] = 4] = "Delete"; + AccessKind2[AccessKind2["ReadWrite"] = 3] = "ReadWrite"; + return AccessKind2; +})(AccessKind || {}); +function getAccessKind(node) { + const parent = node.parent; + switch (parent.kind) { + case ts9__default.default.SyntaxKind.ArrayLiteralExpression: + case ts9__default.default.SyntaxKind.SpreadAssignment: + case ts9__default.default.SyntaxKind.SpreadElement: + return isInDestructuringAssignment( + parent + ) ? 2 /* Write */ : 1 /* Read */; + case ts9__default.default.SyntaxKind.ArrowFunction: + return parent.body === node ? 1 /* Read */ : 2 /* Write */; + case ts9__default.default.SyntaxKind.AsExpression: + case ts9__default.default.SyntaxKind.NonNullExpression: + case ts9__default.default.SyntaxKind.ParenthesizedExpression: + case ts9__default.default.SyntaxKind.TypeAssertionExpression: + return getAccessKind(parent); + case ts9__default.default.SyntaxKind.AwaitExpression: + case ts9__default.default.SyntaxKind.CallExpression: + case ts9__default.default.SyntaxKind.CaseClause: + case ts9__default.default.SyntaxKind.ComputedPropertyName: + case ts9__default.default.SyntaxKind.ConditionalExpression: + case ts9__default.default.SyntaxKind.Decorator: + case ts9__default.default.SyntaxKind.DoStatement: + case ts9__default.default.SyntaxKind.ElementAccessExpression: + case ts9__default.default.SyntaxKind.ExpressionStatement: + case ts9__default.default.SyntaxKind.ForStatement: + case ts9__default.default.SyntaxKind.IfStatement: + case ts9__default.default.SyntaxKind.JsxElement: + case ts9__default.default.SyntaxKind.JsxExpression: + case ts9__default.default.SyntaxKind.JsxOpeningElement: + case ts9__default.default.SyntaxKind.JsxSelfClosingElement: + case ts9__default.default.SyntaxKind.JsxSpreadAttribute: + case ts9__default.default.SyntaxKind.NewExpression: + case ts9__default.default.SyntaxKind.ReturnStatement: + case ts9__default.default.SyntaxKind.SwitchStatement: + case ts9__default.default.SyntaxKind.TaggedTemplateExpression: + case ts9__default.default.SyntaxKind.TemplateSpan: + case ts9__default.default.SyntaxKind.ThrowStatement: + case ts9__default.default.SyntaxKind.TypeOfExpression: + case ts9__default.default.SyntaxKind.VoidExpression: + case ts9__default.default.SyntaxKind.WhileStatement: + case ts9__default.default.SyntaxKind.WithStatement: + case ts9__default.default.SyntaxKind.YieldExpression: + return 1 /* Read */; + case ts9__default.default.SyntaxKind.BinaryExpression: + return parent.right === node ? 1 /* Read */ : !isAssignmentKind(parent.operatorToken.kind) ? 1 /* Read */ : parent.operatorToken.kind === ts9__default.default.SyntaxKind.EqualsToken ? 2 /* Write */ : 3 /* ReadWrite */; + case ts9__default.default.SyntaxKind.BindingElement: + case ts9__default.default.SyntaxKind.EnumMember: + case ts9__default.default.SyntaxKind.JsxAttribute: + case ts9__default.default.SyntaxKind.Parameter: + case ts9__default.default.SyntaxKind.PropertyDeclaration: + case ts9__default.default.SyntaxKind.VariableDeclaration: + return parent.initializer === node ? 1 /* Read */ : 0 /* None */; + case ts9__default.default.SyntaxKind.DeleteExpression: + return 4 /* Delete */; + case ts9__default.default.SyntaxKind.ExportAssignment: + return parent.isExportEquals ? 1 /* Read */ : 0 /* None */; + case ts9__default.default.SyntaxKind.ExpressionWithTypeArguments: + return parent.parent.token === ts9__default.default.SyntaxKind.ExtendsKeyword && parent.parent.parent.kind !== ts9__default.default.SyntaxKind.InterfaceDeclaration ? 1 /* Read */ : 0 /* None */; + case ts9__default.default.SyntaxKind.ForInStatement: + case ts9__default.default.SyntaxKind.ForOfStatement: + return parent.initializer === node ? 2 /* Write */ : 1 /* Read */; + case ts9__default.default.SyntaxKind.PostfixUnaryExpression: + return 3 /* ReadWrite */; + case ts9__default.default.SyntaxKind.PrefixUnaryExpression: + return parent.operator === ts9__default.default.SyntaxKind.PlusPlusToken || parent.operator === ts9__default.default.SyntaxKind.MinusMinusToken ? 3 /* ReadWrite */ : 1 /* Read */; + case ts9__default.default.SyntaxKind.PropertyAccessExpression: + return parent.expression === node ? 1 /* Read */ : 0 /* None */; + case ts9__default.default.SyntaxKind.PropertyAssignment: + return parent.name === node ? 0 /* None */ : isInDestructuringAssignment(parent) ? 2 /* Write */ : 1 /* Read */; + case ts9__default.default.SyntaxKind.ShorthandPropertyAssignment: + return parent.objectAssignmentInitializer === node ? 1 /* Read */ : isInDestructuringAssignment(parent) ? 2 /* Write */ : 1 /* Read */; + } + return 0 /* None */; +} +function isInDestructuringAssignment(node) { + switch (node.kind) { + case ts9__default.default.SyntaxKind.ShorthandPropertyAssignment: + if (node.objectAssignmentInitializer !== undefined) { + return true; + } + // falls through + case ts9__default.default.SyntaxKind.PropertyAssignment: + case ts9__default.default.SyntaxKind.SpreadAssignment: + node = node.parent; + break; + case ts9__default.default.SyntaxKind.SpreadElement: + if (node.parent.kind !== ts9__default.default.SyntaxKind.ArrayLiteralExpression) { + return false; + } + node = node.parent; + } + while (true) { + switch (node.parent.kind) { + case ts9__default.default.SyntaxKind.ArrayLiteralExpression: + case ts9__default.default.SyntaxKind.ObjectLiteralExpression: + node = node.parent; + break; + case ts9__default.default.SyntaxKind.BinaryExpression: + return node.parent.left === node && node.parent.operatorToken.kind === ts9__default.default.SyntaxKind.EqualsToken; + case ts9__default.default.SyntaxKind.ForOfStatement: + return node.parent.initializer === node; + case ts9__default.default.SyntaxKind.PropertyAssignment: + case ts9__default.default.SyntaxKind.SpreadAssignment: + node = node.parent.parent; + break; + case ts9__default.default.SyntaxKind.SpreadElement: + if (node.parent.parent.kind !== ts9__default.default.SyntaxKind.ArrayLiteralExpression) { + return false; + } + node = node.parent.parent; + break; + default: + return false; + } + } +} +function isAbstractKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.AbstractKeyword; +} +function isAccessorKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.AccessorKeyword; +} +function isAnyKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.AnyKeyword; +} +function isAssertKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.AssertKeyword; +} +function isAssertsKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.AssertsKeyword; +} +function isAsyncKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.AsyncKeyword; +} +function isAwaitKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.AwaitKeyword; +} +function isBigIntKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.BigIntKeyword; +} +function isBooleanKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.BooleanKeyword; +} +function isColonToken(node) { + return node.kind === ts9__default.default.SyntaxKind.ColonToken; +} +function isConstKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.ConstKeyword; +} +function isDeclareKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.DeclareKeyword; +} +function isDefaultKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.DefaultKeyword; +} +function isDotToken(node) { + return node.kind === ts9__default.default.SyntaxKind.DotToken; +} +function isEndOfFileToken(node) { + return node.kind === ts9__default.default.SyntaxKind.EndOfFileToken; +} +function isEqualsGreaterThanToken(node) { + return node.kind === ts9__default.default.SyntaxKind.EqualsGreaterThanToken; +} +function isEqualsToken(node) { + return node.kind === ts9__default.default.SyntaxKind.EqualsToken; +} +function isExclamationToken(node) { + return node.kind === ts9__default.default.SyntaxKind.ExclamationToken; +} +function isExportKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.ExportKeyword; +} +function isFalseKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.FalseKeyword; +} +function isFalseLiteral(node) { + return node.kind === ts9__default.default.SyntaxKind.FalseKeyword; +} +function isImportExpression(node) { + return node.kind === ts9__default.default.SyntaxKind.ImportKeyword; +} +function isImportKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.ImportKeyword; +} +function isInKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.InKeyword; +} +function isJSDocText(node) { + return node.kind === ts9__default.default.SyntaxKind.JSDocText; +} +function isJsonMinusNumericLiteral(node) { + return node.kind === ts9__default.default.SyntaxKind.PrefixUnaryExpression; +} +function isNeverKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.NeverKeyword; +} +function isNullKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.NullKeyword; +} +function isNullLiteral(node) { + return node.kind === ts9__default.default.SyntaxKind.NullKeyword; +} +function isNumberKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.NumberKeyword; +} +function isObjectKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.ObjectKeyword; +} +function isOutKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.OutKeyword; +} +function isOverrideKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.OverrideKeyword; +} +function isPrivateKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.PrivateKeyword; +} +function isProtectedKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.ProtectedKeyword; +} +function isPublicKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.PublicKeyword; +} +function isQuestionDotToken(node) { + return node.kind === ts9__default.default.SyntaxKind.QuestionDotToken; +} +function isQuestionToken(node) { + return node.kind === ts9__default.default.SyntaxKind.QuestionToken; +} +function isReadonlyKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.ReadonlyKeyword; +} +function isStaticKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.StaticKeyword; +} +function isStringKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.StringKeyword; +} +function isSuperExpression(node) { + return node.kind === ts9__default.default.SyntaxKind.SuperKeyword; +} +function isSuperKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.SuperKeyword; +} +function isSymbolKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.SymbolKeyword; +} +function isSyntaxList(node) { + return node.kind === ts9__default.default.SyntaxKind.SyntaxList; +} +function isThisExpression(node) { + return node.kind === ts9__default.default.SyntaxKind.ThisKeyword; +} +function isThisKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.ThisKeyword; +} +function isTrueKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.TrueKeyword; +} +function isTrueLiteral(node) { + return node.kind === ts9__default.default.SyntaxKind.TrueKeyword; +} +function isUndefinedKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.UndefinedKeyword; +} +function isUnknownKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.UnknownKeyword; +} +function isVoidKeyword(node) { + return node.kind === ts9__default.default.SyntaxKind.VoidKeyword; +} +var [tsMajor, tsMinor] = ts9__default.default.versionMajorMinor.split(".").map((raw) => Number.parseInt(raw, 10)); +function isTsVersionAtLeast(major, minor = 0) { + return tsMajor > major || tsMajor === major && tsMinor >= minor; +} + +// src/nodes/typeGuards/union.ts +function hasDecorators(node) { + return ts9__default.default.isParameter(node) || ts9__default.default.isPropertyDeclaration(node) || ts9__default.default.isMethodDeclaration(node) || ts9__default.default.isGetAccessorDeclaration(node) || ts9__default.default.isSetAccessorDeclaration(node) || ts9__default.default.isClassExpression(node) || ts9__default.default.isClassDeclaration(node); +} +function hasExpressionInitializer(node) { + return ts9__default.default.isVariableDeclaration(node) || ts9__default.default.isParameter(node) || ts9__default.default.isBindingElement(node) || ts9__default.default.isPropertyDeclaration(node) || ts9__default.default.isPropertyAssignment(node) || ts9__default.default.isEnumMember(node); +} +function hasInitializer(node) { + return hasExpressionInitializer(node) || ts9__default.default.isForStatement(node) || ts9__default.default.isForInStatement(node) || ts9__default.default.isForOfStatement(node) || ts9__default.default.isJsxAttribute(node); +} +function hasJSDoc(node) { + if ( + // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isAccessorDeclaration(node) || ts9__default.default.isArrowFunction(node) || ts9__default.default.isBlock(node) || ts9__default.default.isBreakStatement(node) || ts9__default.default.isCallSignatureDeclaration(node) || ts9__default.default.isCaseClause(node) || // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isClassLikeDeclaration(node) || ts9__default.default.isConstructorDeclaration(node) || ts9__default.default.isConstructorTypeNode(node) || ts9__default.default.isConstructSignatureDeclaration(node) || ts9__default.default.isContinueStatement(node) || ts9__default.default.isDebuggerStatement(node) || ts9__default.default.isDoStatement(node) || ts9__default.default.isEmptyStatement(node) || isEndOfFileToken(node) || ts9__default.default.isEnumDeclaration(node) || ts9__default.default.isEnumMember(node) || ts9__default.default.isExportAssignment(node) || ts9__default.default.isExportDeclaration(node) || ts9__default.default.isExportSpecifier(node) || ts9__default.default.isExpressionStatement(node) || ts9__default.default.isForInStatement(node) || ts9__default.default.isForOfStatement(node) || ts9__default.default.isForStatement(node) || ts9__default.default.isFunctionDeclaration(node) || ts9__default.default.isFunctionExpression(node) || ts9__default.default.isFunctionTypeNode(node) || ts9__default.default.isIfStatement(node) || ts9__default.default.isImportDeclaration(node) || ts9__default.default.isImportEqualsDeclaration(node) || ts9__default.default.isIndexSignatureDeclaration(node) || ts9__default.default.isInterfaceDeclaration(node) || ts9__default.default.isJSDocFunctionType(node) || ts9__default.default.isLabeledStatement(node) || ts9__default.default.isMethodDeclaration(node) || ts9__default.default.isMethodSignature(node) || ts9__default.default.isModuleDeclaration(node) || ts9__default.default.isNamedTupleMember(node) || ts9__default.default.isNamespaceExportDeclaration(node) || ts9__default.default.isParameter(node) || ts9__default.default.isParenthesizedExpression(node) || ts9__default.default.isPropertyAssignment(node) || ts9__default.default.isPropertyDeclaration(node) || ts9__default.default.isPropertySignature(node) || ts9__default.default.isReturnStatement(node) || ts9__default.default.isShorthandPropertyAssignment(node) || ts9__default.default.isSpreadAssignment(node) || ts9__default.default.isSwitchStatement(node) || ts9__default.default.isThrowStatement(node) || ts9__default.default.isTryStatement(node) || ts9__default.default.isTypeAliasDeclaration(node) || ts9__default.default.isVariableDeclaration(node) || ts9__default.default.isVariableStatement(node) || ts9__default.default.isWhileStatement(node) || ts9__default.default.isWithStatement(node) + ) { + return true; + } + if (isTsVersionAtLeast(4, 4) && ts9__default.default.isClassStaticBlockDeclaration(node)) { + return true; + } + if (isTsVersionAtLeast(5, 0) && (ts9__default.default.isBinaryExpression(node) || ts9__default.default.isElementAccessExpression(node) || ts9__default.default.isIdentifier(node) || ts9__default.default.isJSDocSignature(node) || ts9__default.default.isObjectLiteralExpression(node) || ts9__default.default.isPropertyAccessExpression(node) || ts9__default.default.isTypeParameterDeclaration(node))) { + return true; + } + return false; +} +function hasModifiers(node) { + return ts9__default.default.isTypeParameterDeclaration(node) || ts9__default.default.isParameter(node) || ts9__default.default.isConstructorTypeNode(node) || ts9__default.default.isPropertySignature(node) || ts9__default.default.isPropertyDeclaration(node) || ts9__default.default.isMethodSignature(node) || ts9__default.default.isMethodDeclaration(node) || ts9__default.default.isConstructorDeclaration(node) || ts9__default.default.isGetAccessorDeclaration(node) || ts9__default.default.isSetAccessorDeclaration(node) || ts9__default.default.isIndexSignatureDeclaration(node) || ts9__default.default.isFunctionExpression(node) || ts9__default.default.isArrowFunction(node) || ts9__default.default.isClassExpression(node) || ts9__default.default.isVariableStatement(node) || ts9__default.default.isFunctionDeclaration(node) || ts9__default.default.isClassDeclaration(node) || ts9__default.default.isInterfaceDeclaration(node) || ts9__default.default.isTypeAliasDeclaration(node) || ts9__default.default.isEnumDeclaration(node) || ts9__default.default.isModuleDeclaration(node) || ts9__default.default.isImportEqualsDeclaration(node) || ts9__default.default.isImportDeclaration(node) || ts9__default.default.isExportAssignment(node) || ts9__default.default.isExportDeclaration(node); +} +function hasType(node) { + return isSignatureDeclaration(node) || ts9__default.default.isVariableDeclaration(node) || ts9__default.default.isParameter(node) || ts9__default.default.isPropertySignature(node) || ts9__default.default.isPropertyDeclaration(node) || ts9__default.default.isTypePredicateNode(node) || ts9__default.default.isParenthesizedTypeNode(node) || ts9__default.default.isTypeOperatorNode(node) || ts9__default.default.isMappedTypeNode(node) || ts9__default.default.isAssertionExpression(node) || ts9__default.default.isTypeAliasDeclaration(node) || ts9__default.default.isJSDocTypeExpression(node) || ts9__default.default.isJSDocNonNullableType(node) || ts9__default.default.isJSDocNullableType(node) || ts9__default.default.isJSDocOptionalType(node) || ts9__default.default.isJSDocVariadicType(node); +} +function hasTypeArguments(node) { + return ts9__default.default.isCallExpression(node) || ts9__default.default.isNewExpression(node) || ts9__default.default.isTaggedTemplateExpression(node) || ts9__default.default.isJsxOpeningElement(node) || ts9__default.default.isJsxSelfClosingElement(node); +} +function isAccessExpression(node) { + return ts9__default.default.isPropertyAccessExpression(node) || ts9__default.default.isElementAccessExpression(node); +} +function isAccessibilityModifier(node) { + return isPublicKeyword(node) || isPrivateKeyword(node) || isProtectedKeyword(node); +} +function isAccessorDeclaration(node) { + return ts9__default.default.isGetAccessorDeclaration(node) || ts9__default.default.isSetAccessorDeclaration(node); +} +function isArrayBindingElement(node) { + return ts9__default.default.isBindingElement(node) || ts9__default.default.isOmittedExpression(node); +} +function isArrayBindingOrAssignmentPattern(node) { + return ts9__default.default.isArrayBindingPattern(node) || ts9__default.default.isArrayLiteralExpression(node); +} +function isAssignmentPattern(node) { + return ts9__default.default.isObjectLiteralExpression(node) || ts9__default.default.isArrayLiteralExpression(node); +} +function isBindingOrAssignmentElementRestIndicator(node) { + if (ts9__default.default.isSpreadElement(node) || ts9__default.default.isSpreadAssignment(node)) { + return true; + } + if (isTsVersionAtLeast(4, 4)) { + return ts9__default.default.isDotDotDotToken(node); + } + return false; +} +function isBindingOrAssignmentElementTarget(node) { + return isBindingOrAssignmentPattern(node) || ts9__default.default.isIdentifier(node) || ts9__default.default.isPropertyAccessExpression(node) || ts9__default.default.isElementAccessExpression(node) || ts9__default.default.isOmittedExpression(node); +} +function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) || isArrayBindingOrAssignmentPattern(node); +} +function isBindingPattern(node) { + return ts9__default.default.isObjectBindingPattern(node) || ts9__default.default.isArrayBindingPattern(node); +} +function isBlockLike(node) { + return ts9__default.default.isSourceFile(node) || ts9__default.default.isBlock(node) || ts9__default.default.isModuleBlock(node) || ts9__default.default.isCaseOrDefaultClause(node); +} +function isBooleanLiteral(node) { + return isTrueLiteral(node) || isFalseLiteral(node); +} +function isClassLikeDeclaration(node) { + return ts9__default.default.isClassDeclaration(node) || ts9__default.default.isClassExpression(node); +} +function isClassMemberModifier(node) { + return isAccessibilityModifier(node) || isReadonlyKeyword(node) || isStaticKeyword(node) || isAccessorKeyword(node); +} +function isDeclarationName(node) { + return ts9__default.default.isIdentifier(node) || ts9__default.default.isPrivateIdentifier(node) || ts9__default.default.isStringLiteralLike(node) || ts9__default.default.isNumericLiteral(node) || ts9__default.default.isComputedPropertyName(node) || ts9__default.default.isElementAccessExpression(node) || isBindingPattern(node) || isEntityNameExpression(node); +} +function isDeclarationWithTypeParameterChildren(node) { + return isSignatureDeclaration(node) || // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isClassLikeDeclaration(node) || ts9__default.default.isInterfaceDeclaration(node) || ts9__default.default.isTypeAliasDeclaration(node) || ts9__default.default.isJSDocTemplateTag(node); +} +function isDeclarationWithTypeParameters(node) { + return isDeclarationWithTypeParameterChildren(node) || ts9__default.default.isJSDocTypedefTag(node) || ts9__default.default.isJSDocCallbackTag(node) || ts9__default.default.isJSDocSignature(node); +} +function isDestructuringPattern(node) { + return isBindingPattern(node) || ts9__default.default.isObjectLiteralExpression(node) || ts9__default.default.isArrayLiteralExpression(node); +} +function isEntityNameExpression(node) { + return ts9__default.default.isIdentifier(node) || isPropertyAccessEntityNameExpression(node); +} +function isEntityNameOrEntityNameExpression(node) { + return ts9__default.default.isEntityName(node) || isEntityNameExpression(node); +} +function isForInOrOfStatement(node) { + return ts9__default.default.isForInStatement(node) || ts9__default.default.isForOfStatement(node); +} +function isFunctionLikeDeclaration(node) { + return ts9__default.default.isFunctionDeclaration(node) || ts9__default.default.isMethodDeclaration(node) || ts9__default.default.isGetAccessorDeclaration(node) || ts9__default.default.isSetAccessorDeclaration(node) || ts9__default.default.isConstructorDeclaration(node) || ts9__default.default.isFunctionExpression(node) || ts9__default.default.isArrowFunction(node); +} +function isJSDocComment(node) { + if (isJSDocText(node)) { + return true; + } + if (isTsVersionAtLeast(4, 4)) { + return ts9__default.default.isJSDocLink(node) || ts9__default.default.isJSDocLinkCode(node) || ts9__default.default.isJSDocLinkPlain(node); + } + return false; +} +function isJSDocNamespaceBody(node) { + return ts9__default.default.isIdentifier(node) || isJSDocNamespaceDeclaration(node); +} +function isJSDocTypeReferencingNode(node) { + return ts9__default.default.isJSDocVariadicType(node) || ts9__default.default.isJSDocOptionalType(node) || ts9__default.default.isJSDocNullableType(node) || ts9__default.default.isJSDocNonNullableType(node); +} +function isJsonObjectExpression(node) { + return ts9__default.default.isObjectLiteralExpression(node) || ts9__default.default.isArrayLiteralExpression(node) || isJsonMinusNumericLiteral(node) || ts9__default.default.isNumericLiteral(node) || ts9__default.default.isStringLiteral(node) || isBooleanLiteral(node) || isNullLiteral(node); +} +function isJsxAttributeLike(node) { + return ts9__default.default.isJsxAttribute(node) || ts9__default.default.isJsxSpreadAttribute(node); +} +function isJsxAttributeValue(node) { + return ts9__default.default.isStringLiteral(node) || ts9__default.default.isJsxExpression(node) || ts9__default.default.isJsxElement(node) || ts9__default.default.isJsxSelfClosingElement(node) || ts9__default.default.isJsxFragment(node); +} +function isJsxChild(node) { + return ts9__default.default.isJsxText(node) || ts9__default.default.isJsxExpression(node) || ts9__default.default.isJsxElement(node) || ts9__default.default.isJsxSelfClosingElement(node) || ts9__default.default.isJsxFragment(node); +} +function isJsxTagNameExpression(node) { + return ts9__default.default.isIdentifier(node) || isThisExpression(node) || isJsxTagNamePropertyAccess(node); +} +function isLiteralToken(node) { + return ts9__default.default.isNumericLiteral(node) || ts9__default.default.isBigIntLiteral(node) || ts9__default.default.isStringLiteral(node) || ts9__default.default.isJsxText(node) || ts9__default.default.isRegularExpressionLiteral(node) || ts9__default.default.isNoSubstitutionTemplateLiteral(node); +} +function isModuleBody(node) { + return isNamespaceBody(node) || isJSDocNamespaceBody(node); +} +function isModuleName(node) { + return ts9__default.default.isIdentifier(node) || ts9__default.default.isStringLiteral(node); +} +function isModuleReference(node) { + return ts9__default.default.isEntityName(node) || ts9__default.default.isExternalModuleReference(node); +} +function isNamedImportBindings(node) { + return ts9__default.default.isNamespaceImport(node) || ts9__default.default.isNamedImports(node); +} +function isNamedImportsOrExports(node) { + return ts9__default.default.isNamedImports(node) || ts9__default.default.isNamedExports(node); +} +function isNamespaceBody(node) { + return ts9__default.default.isModuleBlock(node) || isNamespaceDeclaration(node); +} +function isObjectBindingOrAssignmentElement(node) { + return ts9__default.default.isBindingElement(node) || ts9__default.default.isPropertyAssignment(node) || ts9__default.default.isShorthandPropertyAssignment(node) || ts9__default.default.isSpreadAssignment(node); +} +function isObjectBindingOrAssignmentPattern(node) { + return ts9__default.default.isObjectBindingPattern(node) || ts9__default.default.isObjectLiteralExpression(node); +} +function isObjectTypeDeclaration(node) { + return ( + // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isClassLikeDeclaration(node) || ts9__default.default.isInterfaceDeclaration(node) || ts9__default.default.isTypeLiteralNode(node) + ); +} +function isParameterPropertyModifier(node) { + return isAccessibilityModifier(node) || isReadonlyKeyword(node); +} +function isPropertyNameLiteral(node) { + return ts9__default.default.isIdentifier(node) || ts9__default.default.isStringLiteralLike(node) || ts9__default.default.isNumericLiteral(node); +} +function isPseudoLiteralToken(node) { + return ts9__default.default.isTemplateHead(node) || ts9__default.default.isTemplateMiddle(node) || ts9__default.default.isTemplateTail(node); +} +function isSignatureDeclaration(node) { + return ts9__default.default.isCallSignatureDeclaration(node) || ts9__default.default.isConstructSignatureDeclaration(node) || ts9__default.default.isMethodSignature(node) || ts9__default.default.isIndexSignatureDeclaration(node) || ts9__default.default.isFunctionTypeNode(node) || ts9__default.default.isConstructorTypeNode(node) || ts9__default.default.isJSDocFunctionType(node) || ts9__default.default.isFunctionDeclaration(node) || ts9__default.default.isMethodDeclaration(node) || ts9__default.default.isConstructorDeclaration(node) || // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isAccessorDeclaration(node) || ts9__default.default.isFunctionExpression(node) || ts9__default.default.isArrowFunction(node); +} +function isSuperProperty(node) { + return isSuperPropertyAccessExpression(node) || isSuperElementAccessExpression(node); +} +function isTypeOnlyCompatibleAliasDeclaration(node) { + if (ts9__default.default.isImportClause(node) || ts9__default.default.isImportEqualsDeclaration(node) || ts9__default.default.isNamespaceImport(node) || ts9__default.default.isImportOrExportSpecifier(node)) { + return true; + } + if (isTsVersionAtLeast(5, 0) && (ts9__default.default.isExportDeclaration(node) || ts9__default.default.isNamespaceExport(node))) { + return true; + } + return false; +} +function isTypeReferenceType(node) { + return ts9__default.default.isTypeReferenceNode(node) || ts9__default.default.isExpressionWithTypeArguments(node); +} +function isUnionOrIntersectionTypeNode(node) { + return ts9__default.default.isUnionTypeNode(node) || ts9__default.default.isIntersectionTypeNode(node); +} +function isVariableLikeDeclaration(node) { + return ts9__default.default.isVariableDeclaration(node) || ts9__default.default.isParameter(node) || ts9__default.default.isBindingElement(node) || ts9__default.default.isPropertyDeclaration(node) || ts9__default.default.isPropertyAssignment(node) || ts9__default.default.isPropertySignature(node) || ts9__default.default.isJsxAttribute(node) || ts9__default.default.isShorthandPropertyAssignment(node) || ts9__default.default.isEnumMember(node) || ts9__default.default.isJSDocPropertyTag(node) || ts9__default.default.isJSDocParameterTag(node); +} + +// src/nodes/typeGuards/compound.ts +function isConstAssertionExpression(node) { + return ts9__default.default.isTypeReferenceNode(node.type) && ts9__default.default.isIdentifier(node.type.typeName) && node.type.typeName.escapedText === "const"; +} +function isIterationStatement(node) { + switch (node.kind) { + case ts9__default.default.SyntaxKind.DoStatement: + case ts9__default.default.SyntaxKind.ForInStatement: + case ts9__default.default.SyntaxKind.ForOfStatement: + case ts9__default.default.SyntaxKind.ForStatement: + case ts9__default.default.SyntaxKind.WhileStatement: + return true; + default: + return false; + } +} +function isJSDocNamespaceDeclaration(node) { + return ts9__default.default.isModuleDeclaration(node) && ts9__default.default.isIdentifier(node.name) && (node.body === undefined || isJSDocNamespaceBody(node.body)); +} +function isJsxTagNamePropertyAccess(node) { + return ts9__default.default.isPropertyAccessExpression(node) && // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts < 5 + isJsxTagNameExpression(node.expression); +} +function isNamedDeclarationWithName(node) { + return "name" in node && node.name !== undefined && node.name !== null && isDeclarationName(node.name); +} +function isNamespaceDeclaration(node) { + return ts9__default.default.isModuleDeclaration(node) && ts9__default.default.isIdentifier(node.name) && node.body !== undefined && isNamespaceBody(node.body); +} +function isNumericOrStringLikeLiteral(node) { + switch (node.kind) { + case ts9__default.default.SyntaxKind.NoSubstitutionTemplateLiteral: + case ts9__default.default.SyntaxKind.NumericLiteral: + case ts9__default.default.SyntaxKind.StringLiteral: + return true; + default: + return false; + } +} +function isPropertyAccessEntityNameExpression(node) { + return ts9__default.default.isPropertyAccessExpression(node) && ts9__default.default.isIdentifier(node.name) && isEntityNameExpression(node.expression); +} +function isSuperElementAccessExpression(node) { + return ts9__default.default.isElementAccessExpression(node) && isSuperExpression(node.expression); +} +function isSuperPropertyAccessExpression(node) { + return ts9__default.default.isPropertyAccessExpression(node) && isSuperExpression(node.expression); +} +function isFunctionScopeBoundary(node) { + switch (node.kind) { + case ts9__default.default.SyntaxKind.ArrowFunction: + case ts9__default.default.SyntaxKind.CallSignature: + case ts9__default.default.SyntaxKind.ClassDeclaration: + case ts9__default.default.SyntaxKind.ClassExpression: + case ts9__default.default.SyntaxKind.Constructor: + case ts9__default.default.SyntaxKind.ConstructorType: + case ts9__default.default.SyntaxKind.ConstructSignature: + case ts9__default.default.SyntaxKind.EnumDeclaration: + case ts9__default.default.SyntaxKind.FunctionDeclaration: + case ts9__default.default.SyntaxKind.FunctionExpression: + case ts9__default.default.SyntaxKind.FunctionType: + case ts9__default.default.SyntaxKind.GetAccessor: + case ts9__default.default.SyntaxKind.MethodDeclaration: + case ts9__default.default.SyntaxKind.MethodSignature: + case ts9__default.default.SyntaxKind.ModuleDeclaration: + case ts9__default.default.SyntaxKind.SetAccessor: + return true; + case ts9__default.default.SyntaxKind.SourceFile: + return ts9__default.default.isExternalModule(node); + default: + return false; + } +} +function isIntrinsicAnyType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Any); +} +function isIntrinsicBigIntType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.BigInt); +} +function isIntrinsicBooleanType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Boolean); +} +function isIntrinsicErrorType(type) { + return isIntrinsicType(type) && type.intrinsicName === "error"; +} +function isIntrinsicESSymbolType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.ESSymbol); +} +var IntrinsicTypeFlags = ts9__default.default.TypeFlags.Intrinsic ?? ts9__default.default.TypeFlags.Any | ts9__default.default.TypeFlags.Unknown | ts9__default.default.TypeFlags.String | ts9__default.default.TypeFlags.Number | ts9__default.default.TypeFlags.BigInt | ts9__default.default.TypeFlags.Boolean | ts9__default.default.TypeFlags.BooleanLiteral | ts9__default.default.TypeFlags.ESSymbol | ts9__default.default.TypeFlags.Void | ts9__default.default.TypeFlags.Undefined | ts9__default.default.TypeFlags.Null | ts9__default.default.TypeFlags.Never | ts9__default.default.TypeFlags.NonPrimitive; +function isIntrinsicNeverType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Never); +} +function isIntrinsicNonPrimitiveType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.NonPrimitive); +} +function isIntrinsicNullType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Null); +} +function isIntrinsicNumberType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Number); +} +function isIntrinsicStringType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.String); +} +function isIntrinsicType(type) { + return isTypeFlagSet(type, IntrinsicTypeFlags); +} +function isIntrinsicUndefinedType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Undefined); +} +function isIntrinsicUnknownType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Unknown); +} +function isIntrinsicVoidType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Void); +} +function isConditionalType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Conditional); +} +function isEnumType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Enum); +} +function isFreshableType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Freshable); +} +function isIndexedAccessType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.IndexedAccess); +} +function isIndexType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Index); +} +function isInstantiableType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Instantiable); +} +function isIntersectionType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Intersection); +} +function isObjectType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Object); +} +function isStringMappingType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.StringMapping); +} +function isSubstitutionType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Substitution); +} +function isTypeParameter(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.TypeParameter); +} +function isTypeVariable(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.TypeVariable); +} +function isUnionOrIntersectionType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.UnionOrIntersection); +} +function isUnionType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Union); +} +function isUniqueESSymbolType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.UniqueESSymbol); +} + +// src/types/typeGuards/objects.ts +function isEvolvingArrayType(type) { + return isObjectType(type) && isObjectFlagSet(type, ts9__default.default.ObjectFlags.EvolvingArray); +} +function isTupleType(type) { + return isObjectType(type) && isObjectFlagSet(type, ts9__default.default.ObjectFlags.Tuple); +} +function isTypeReference(type) { + return isObjectType(type) && isObjectFlagSet(type, ts9__default.default.ObjectFlags.Reference); +} + +// src/types/typeGuards/compound.ts +function isFreshableIntrinsicType(type) { + return isIntrinsicType(type) && isFreshableType(type); +} +function isTupleTypeReference(type) { + return isTypeReference(type) && isTupleType(type.target); +} +function isBigIntLiteralType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.BigIntLiteral); +} +function isBooleanLiteralType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.BooleanLiteral); +} +function isFalseLiteralType(type) { + return isBooleanLiteralType(type) && type.intrinsicName === "false"; +} +function isLiteralType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.Literal); +} +function isNumberLiteralType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.NumberLiteral); +} +function isStringLiteralType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.StringLiteral); +} +function isTemplateLiteralType(type) { + return isTypeFlagSet(type, ts9__default.default.TypeFlags.TemplateLiteral); +} +function isTrueLiteralType(type) { + return isBooleanLiteralType(type) && type.intrinsicName === "true"; +} + +// src/types/getters.ts +function getCallSignaturesOfType(type) { + if (isUnionType(type)) { + const signatures = []; + for (const subType of type.types) { + signatures.push(...getCallSignaturesOfType(subType)); + } + return signatures; + } + if (isIntersectionType(type)) { + let signatures; + for (const subType of type.types) { + const sig = getCallSignaturesOfType(subType); + if (sig.length !== 0) { + if (signatures !== undefined) { + return []; + } + signatures = sig; + } + } + return signatures === undefined ? [] : signatures; + } + return type.getCallSignatures(); +} +function getPropertyOfType(type, name) { + if (!name.startsWith("__")) { + return type.getProperty(name); + } + return type.getProperties().find((s) => s.escapedName === name); +} +function getWellKnownSymbolPropertyOfType(type, wellKnownSymbolName, typeChecker) { + const prefix = "__@" + wellKnownSymbolName; + for (const prop of type.getProperties()) { + if (!prop.name.startsWith(prefix)) { + continue; + } + const declaration = prop.valueDeclaration ?? prop.getDeclarations()?.[0]; + if (!declaration || !isNamedDeclarationWithName(declaration) || declaration.name === undefined || !ts9__default.default.isComputedPropertyName(declaration.name)) { + continue; + } + const globalSymbol = typeChecker.getApparentType( + typeChecker.getTypeAtLocation(declaration.name.expression) + ).symbol; + if (prop.escapedName === getPropertyNameOfWellKnownSymbol( + typeChecker, + globalSymbol, + wellKnownSymbolName + )) { + return prop; + } + } + return undefined; +} +function getPropertyNameOfWellKnownSymbol(typeChecker, symbolConstructor, symbolName) { + const knownSymbol = symbolConstructor && typeChecker.getTypeOfSymbolAtLocation( + symbolConstructor, + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access + symbolConstructor.valueDeclaration + ).getProperty(symbolName); + const knownSymbolType = knownSymbol && typeChecker.getTypeOfSymbolAtLocation( + knownSymbol, + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access + knownSymbol.valueDeclaration + ); + if (knownSymbolType && isUniqueESSymbolType(knownSymbolType)) { + return knownSymbolType.escapedName; + } + return "__@" + symbolName; +} +function isBindableObjectDefinePropertyCall(node) { + return node.arguments.length === 3 && isEntityNameExpression(node.arguments[0]) && isNumericOrStringLikeLiteral(node.arguments[1]) && ts9__default.default.isPropertyAccessExpression(node.expression) && node.expression.name.escapedText === "defineProperty" && ts9__default.default.isIdentifier(node.expression.expression) && node.expression.expression.escapedText === "Object"; +} +function isInConstContext(node, typeChecker) { + let current = node; + while (true) { + const parent = current.parent; + outer: switch (parent.kind) { + case ts9__default.default.SyntaxKind.ArrayLiteralExpression: + case ts9__default.default.SyntaxKind.ObjectLiteralExpression: + case ts9__default.default.SyntaxKind.ParenthesizedExpression: + case ts9__default.default.SyntaxKind.TemplateExpression: + current = parent; + break; + case ts9__default.default.SyntaxKind.AsExpression: + case ts9__default.default.SyntaxKind.TypeAssertionExpression: + return isConstAssertionExpression(parent); + case ts9__default.default.SyntaxKind.CallExpression: { + if (!ts9__default.default.isExpression(current)) { + return false; + } + const functionSignature = typeChecker.getResolvedSignature( + parent + ); + if (functionSignature === undefined) { + return false; + } + const argumentIndex = parent.arguments.indexOf( + current + ); + if (argumentIndex < 0) { + return false; + } + const parameterSymbol = functionSignature.getParameters()[argumentIndex]; + if (parameterSymbol === undefined || !("links" in parameterSymbol)) { + return false; + } + const parameterSymbolLinks = parameterSymbol.links; + const propertySymbol = parameterSymbolLinks.type?.getProperties()?.[argumentIndex]; + if (propertySymbol === undefined || !("links" in propertySymbol)) { + return false; + } + return isTransientSymbolLinksFlagSet( + propertySymbol.links, + ts9__default.default.CheckFlags.Readonly + ); + } + case ts9__default.default.SyntaxKind.PrefixUnaryExpression: + if (current.kind !== ts9__default.default.SyntaxKind.NumericLiteral) { + return false; + } + switch (parent.operator) { + case ts9__default.default.SyntaxKind.MinusToken: + case ts9__default.default.SyntaxKind.PlusToken: + current = parent; + break outer; + default: + return false; + } + case ts9__default.default.SyntaxKind.PropertyAssignment: + if (parent.initializer !== current) { + return false; + } + current = parent.parent; + break; + case ts9__default.default.SyntaxKind.ShorthandPropertyAssignment: + current = parent.parent; + break; + default: + return false; + } + } +} + +// src/types/utilities.ts +function intersectionConstituents(type) { + return isIntersectionType(type) ? type.types : [type]; +} +var intersectionTypeParts = intersectionConstituents; +function isFalsyType(type) { + if (isTypeFlagSet( + type, + ts9__default.default.TypeFlags.Undefined | ts9__default.default.TypeFlags.Null | ts9__default.default.TypeFlags.Void + )) { + return true; + } + if (typeIsLiteral(type)) { + if (typeof type.value === "object") { + return type.value.base10Value === "0"; + } else { + return !type.value; + } + } + return isFalseLiteralType(type); +} +function isPropertyReadonlyInType(type, name, typeChecker) { + let seenProperty = false; + let seenReadonlySignature = false; + for (const subType of unionConstituents(type)) { + if (getPropertyOfType(subType, name) === undefined) { + const index = (isNumericPropertyName(name) ? typeChecker.getIndexInfoOfType(subType, ts9__default.default.IndexKind.Number) : undefined) ?? typeChecker.getIndexInfoOfType(subType, ts9__default.default.IndexKind.String); + if (index?.isReadonly) { + if (seenProperty) { + return true; + } + seenReadonlySignature = true; + } + } else if (seenReadonlySignature || isReadonlyPropertyIntersection(subType, name, typeChecker)) { + return true; + } else { + seenProperty = true; + } + } + return false; +} +function isThenableType(typeChecker, node, type = typeChecker.getTypeAtLocation(node)) { + for (const constituent of unionConstituents( + typeChecker.getApparentType(type) + )) { + const then = constituent.getProperty("then"); + if (then === undefined) { + continue; + } + const thenType = typeChecker.getTypeOfSymbolAtLocation(then, node); + for (const subConstituent of unionConstituents(thenType)) { + for (const signature of subConstituent.getCallSignatures()) { + if (signature.parameters.length !== 0 && isCallback(typeChecker, signature.parameters[0], node)) { + return true; + } + } + } + } + return false; +} +function symbolHasReadonlyDeclaration(symbol, typeChecker) { + return !!((symbol.flags & ts9__default.default.SymbolFlags.Accessor) === ts9__default.default.SymbolFlags.GetAccessor || symbol.declarations?.some( + (node) => isModifierFlagSet(node, ts9__default.default.ModifierFlags.Readonly) || ts9__default.default.isVariableDeclaration(node) && isNodeFlagSet(node.parent, ts9__default.default.NodeFlags.Const) || ts9__default.default.isCallExpression(node) && isReadonlyAssignmentDeclaration(node, typeChecker) || ts9__default.default.isEnumMember(node) || (ts9__default.default.isPropertyAssignment(node) || ts9__default.default.isShorthandPropertyAssignment(node)) && isInConstContext(node, typeChecker) + )); +} +function typeConstituents(type) { + return isIntersectionType(type) || isUnionType(type) ? type.types : [type]; +} +function typeIsLiteral(type) { + if (isTsVersionAtLeast(5, 0)) { + return type.isLiteral(); + } else { + return isTypeFlagSet( + type, + ts9__default.default.TypeFlags.StringLiteral | ts9__default.default.TypeFlags.NumberLiteral | ts9__default.default.TypeFlags.BigIntLiteral + ); + } +} +var typeParts = typeConstituents; +function unionConstituents(type) { + return isUnionType(type) ? type.types : [type]; +} +var unionTypeParts = unionConstituents; +function isCallback(typeChecker, param, node) { + let type = typeChecker.getApparentType( + typeChecker.getTypeOfSymbolAtLocation(param, node) + ); + if (param.valueDeclaration.dotDotDotToken) { + type = type.getNumberIndexType(); + if (type === undefined) { + return false; + } + } + for (const subType of unionConstituents(type)) { + if (subType.getCallSignatures().length !== 0) { + return true; + } + } + return false; +} +function isReadonlyAssignmentDeclaration(node, typeChecker) { + if (!isBindableObjectDefinePropertyCall(node)) { + return false; + } + const descriptorType = typeChecker.getTypeAtLocation(node.arguments[2]); + if (descriptorType.getProperty("value") === undefined) { + return descriptorType.getProperty("set") === undefined; + } + const writableProp = descriptorType.getProperty("writable"); + if (writableProp === undefined) { + return false; + } + const writableType = writableProp.valueDeclaration !== undefined && ts9__default.default.isPropertyAssignment(writableProp.valueDeclaration) ? typeChecker.getTypeAtLocation(writableProp.valueDeclaration.initializer) : typeChecker.getTypeOfSymbolAtLocation(writableProp, node.arguments[2]); + return isFalseLiteralType(writableType); +} +function isReadonlyPropertyFromMappedType(type, name, typeChecker) { + if (!isObjectType(type) || !isObjectFlagSet(type, ts9__default.default.ObjectFlags.Mapped)) { + return; + } + const declaration = type.symbol.declarations[0]; + if (declaration.readonlyToken !== undefined && !/^__@[^@]+$/.test(name)) { + return declaration.readonlyToken.kind !== ts9__default.default.SyntaxKind.MinusToken; + } + const { modifiersType } = type; + return modifiersType && isPropertyReadonlyInType(modifiersType, name, typeChecker); +} +function isReadonlyPropertyIntersection(type, name, typeChecker) { + const constituents = intersectionConstituents(type); + return constituents.some((constituent) => { + const prop = getPropertyOfType(constituent, name); + if (prop === undefined) { + return false; + } + if (prop.flags & ts9__default.default.SymbolFlags.Transient) { + if (/^(?:[1-9]\d*|0)$/.test(name) && isTupleTypeReference(constituent)) { + return constituent.target.readonly; + } + switch (isReadonlyPropertyFromMappedType(constituent, name, typeChecker)) { + case false: + return false; + case true: + return true; + } + } + return !!// members of namespace import + (isSymbolFlagSet(prop, ts9__default.default.SymbolFlags.ValueModule) || // we unwrapped every mapped type, now we can check the actual declarations + symbolHasReadonlyDeclaration(prop, typeChecker)); + }); +} +function identifierToKeywordKind(node) { + return "originalKeywordKind" in node ? node.originalKeywordKind : ts9__default.default.identifierToKeywordKind(node); +} + +// src/usage/declarations.ts +var DeclarationDomain = /* @__PURE__ */ ((DeclarationDomain2) => { + DeclarationDomain2[DeclarationDomain2["Namespace"] = 1] = "Namespace"; + DeclarationDomain2[DeclarationDomain2["Type"] = 2] = "Type"; + DeclarationDomain2[DeclarationDomain2["Value"] = 4] = "Value"; + DeclarationDomain2[DeclarationDomain2["Any"] = 7] = "Any"; + DeclarationDomain2[DeclarationDomain2["Import"] = 8] = "Import"; + return DeclarationDomain2; +})(DeclarationDomain || {}); +function getDeclarationDomain(node) { + switch (node.parent.kind) { + case ts9__default.default.SyntaxKind.ClassDeclaration: + case ts9__default.default.SyntaxKind.ClassExpression: + return 2 /* Type */ | 4 /* Value */; + case ts9__default.default.SyntaxKind.EnumDeclaration: + return 7 /* Any */; + case ts9__default.default.SyntaxKind.FunctionDeclaration: + case ts9__default.default.SyntaxKind.FunctionExpression: + return 4 /* Value */; + case ts9__default.default.SyntaxKind.ImportClause: + case ts9__default.default.SyntaxKind.NamespaceImport: + return 7 /* Any */ | 8 /* Import */; + // TODO handle type-only imports + case ts9__default.default.SyntaxKind.ImportEqualsDeclaration: + case ts9__default.default.SyntaxKind.ImportSpecifier: + return node.parent.name === node ? 7 /* Any */ | 8 /* Import */ : undefined; + case ts9__default.default.SyntaxKind.InterfaceDeclaration: + case ts9__default.default.SyntaxKind.TypeAliasDeclaration: + case ts9__default.default.SyntaxKind.TypeParameter: + return 2 /* Type */; + case ts9__default.default.SyntaxKind.ModuleDeclaration: + return 1 /* Namespace */; + case ts9__default.default.SyntaxKind.Parameter: + if (node.parent.parent.kind === ts9__default.default.SyntaxKind.IndexSignature || identifierToKeywordKind(node) === ts9__default.default.SyntaxKind.ThisKeyword) { + return; + } + // falls through + case ts9__default.default.SyntaxKind.BindingElement: + case ts9__default.default.SyntaxKind.VariableDeclaration: + return node.parent.name === node ? 4 /* Value */ : undefined; + } +} +function getPropertyName(propertyName) { + if (propertyName.kind === ts9__default.default.SyntaxKind.ComputedPropertyName) { + const expression = unwrapParentheses(propertyName.expression); + if (ts9__default.default.isPrefixUnaryExpression(expression)) { + let negate = false; + switch (expression.operator) { + case ts9__default.default.SyntaxKind.MinusToken: + negate = true; + // falls through + case ts9__default.default.SyntaxKind.PlusToken: + return ts9__default.default.isNumericLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text}` : ts9__default.default.isBigIntLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text.slice(0, -1)}` : undefined; + default: + return; + } + } + if (ts9__default.default.isBigIntLiteral(expression)) { + return expression.text.slice(0, -1); + } + if (isNumericOrStringLikeLiteral(expression)) { + return expression.text; + } + return; + } + return propertyName.kind === ts9__default.default.SyntaxKind.PrivateIdentifier ? undefined : propertyName.text; +} +function unwrapParentheses(node) { + while (node.kind === ts9__default.default.SyntaxKind.ParenthesizedExpression) { + node = node.expression; + } + return node; +} +var UsageDomain = /* @__PURE__ */ ((UsageDomain2) => { + UsageDomain2[UsageDomain2["Namespace"] = 1] = "Namespace"; + UsageDomain2[UsageDomain2["Type"] = 2] = "Type"; + UsageDomain2[UsageDomain2["Value"] = 4] = "Value"; + UsageDomain2[UsageDomain2["Any"] = 7] = "Any"; + UsageDomain2[UsageDomain2["TypeQuery"] = 8] = "TypeQuery"; + UsageDomain2[UsageDomain2["ValueOrNamespace"] = 5] = "ValueOrNamespace"; + return UsageDomain2; +})(UsageDomain || {}); +function getUsageDomain(node) { + const parent = node.parent; + switch (parent.kind) { + // Value + case ts9__default.default.SyntaxKind.BindingElement: + if (parent.initializer === node) { + return 5 /* ValueOrNamespace */; + } + break; + case ts9__default.default.SyntaxKind.BreakStatement: + case ts9__default.default.SyntaxKind.ClassDeclaration: + case ts9__default.default.SyntaxKind.ClassExpression: + case ts9__default.default.SyntaxKind.ContinueStatement: + case ts9__default.default.SyntaxKind.EnumDeclaration: + case ts9__default.default.SyntaxKind.FunctionDeclaration: + case ts9__default.default.SyntaxKind.FunctionExpression: + case ts9__default.default.SyntaxKind.GetAccessor: + case ts9__default.default.SyntaxKind.ImportClause: + case ts9__default.default.SyntaxKind.ImportSpecifier: + case ts9__default.default.SyntaxKind.InterfaceDeclaration: + case ts9__default.default.SyntaxKind.JsxAttribute: + case ts9__default.default.SyntaxKind.LabeledStatement: + case ts9__default.default.SyntaxKind.MethodDeclaration: + case ts9__default.default.SyntaxKind.MethodSignature: + case ts9__default.default.SyntaxKind.ModuleDeclaration: + case ts9__default.default.SyntaxKind.NamedTupleMember: + case ts9__default.default.SyntaxKind.NamespaceExport: + case ts9__default.default.SyntaxKind.NamespaceExportDeclaration: + case ts9__default.default.SyntaxKind.NamespaceImport: + case ts9__default.default.SyntaxKind.PropertySignature: + case ts9__default.default.SyntaxKind.SetAccessor: + case ts9__default.default.SyntaxKind.TypeAliasDeclaration: + case ts9__default.default.SyntaxKind.TypeParameter: + case ts9__default.default.SyntaxKind.TypePredicate: + break; + case ts9__default.default.SyntaxKind.EnumMember: + case ts9__default.default.SyntaxKind.ImportEqualsDeclaration: + case ts9__default.default.SyntaxKind.Parameter: + case ts9__default.default.SyntaxKind.PropertyAccessExpression: + case ts9__default.default.SyntaxKind.PropertyAssignment: + case ts9__default.default.SyntaxKind.PropertyDeclaration: + case ts9__default.default.SyntaxKind.VariableDeclaration: + if (parent.name !== node) { + return 5 /* ValueOrNamespace */; + } + break; + case ts9__default.default.SyntaxKind.ExportAssignment: + return 7 /* Any */; + case ts9__default.default.SyntaxKind.ExportSpecifier: + if (parent.propertyName === undefined || parent.propertyName === node) { + return 7 /* Any */; + } + break; + case ts9__default.default.SyntaxKind.ExpressionWithTypeArguments: + return parent.parent.token === ts9__default.default.SyntaxKind.ImplementsKeyword || parent.parent.parent.kind === ts9__default.default.SyntaxKind.InterfaceDeclaration ? 2 /* Type */ : 4 /* Value */; + case ts9__default.default.SyntaxKind.QualifiedName: + if (parent.left === node) { + if (getEntityNameParent(parent).kind === ts9__default.default.SyntaxKind.TypeQuery) { + return 1 /* Namespace */ | 8 /* TypeQuery */; + } + return 1 /* Namespace */; + } + break; + case ts9__default.default.SyntaxKind.TypeQuery: + return 5 /* ValueOrNamespace */ | 8 /* TypeQuery */; + case ts9__default.default.SyntaxKind.TypeReference: + return identifierToKeywordKind(node) !== ts9__default.default.SyntaxKind.ConstKeyword ? 2 /* Type */ : undefined; + default: + return 5 /* ValueOrNamespace */; + } +} +function getEntityNameParent(name) { + let parent = name.parent; + while (parent.kind === ts9__default.default.SyntaxKind.QualifiedName) { + parent = parent.parent; + } + return parent; +} +function isBlockScopeBoundary(node) { + switch (node.kind) { + case ts9__default.default.SyntaxKind.Block: { + const parent = node.parent; + return parent.kind !== ts9__default.default.SyntaxKind.CatchClause && // blocks inside SourceFile are block scope boundaries + (parent.kind === ts9__default.default.SyntaxKind.SourceFile || // blocks that are direct children of a function scope boundary are no scope boundary + // for example the FunctionBlock is part of the function scope of the containing function + !isFunctionScopeBoundary(parent)) ? 2 /* Block */ : 0 /* None */; + } + case ts9__default.default.SyntaxKind.CaseBlock: + case ts9__default.default.SyntaxKind.CatchClause: + case ts9__default.default.SyntaxKind.ForInStatement: + case ts9__default.default.SyntaxKind.ForOfStatement: + case ts9__default.default.SyntaxKind.ForStatement: + case ts9__default.default.SyntaxKind.WithStatement: + return 2 /* Block */; + default: + return 0 /* None */; + } +} + +// src/usage/scopes.ts +var AbstractScope = class { + constructor(global) { + this.global = global; + } + namespaceScopes = undefined; + uses = []; + variables = /* @__PURE__ */ new Map(); + #enumScopes = undefined; + addUse(use) { + this.uses.push(use); + } + addVariable(identifier, name, selector, exported, domain) { + const variables = this.getDestinationScope(selector).getVariables(); + const declaration = { + declaration: name, + domain, + exported + }; + const variable = variables.get(identifier); + if (variable === undefined) { + variables.set(identifier, { + declarations: [declaration], + domain, + uses: [] + }); + } else { + variable.domain |= domain; + variable.declarations.push(declaration); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + createOrReuseEnumScope(name, _exported) { + let scope; + if (this.#enumScopes === undefined) { + this.#enumScopes = /* @__PURE__ */ new Map(); + } else { + scope = this.#enumScopes.get(name); + } + if (scope === undefined) { + scope = new EnumScope(this); + this.#enumScopes.set(name, scope); + } + return scope; + } + // only relevant for the root scope + createOrReuseNamespaceScope(name, _exported, ambient, hasExportStatement) { + let scope; + if (this.namespaceScopes === undefined) { + this.namespaceScopes = /* @__PURE__ */ new Map(); + } else { + scope = this.namespaceScopes.get(name); + } + if (scope === undefined) { + scope = new NamespaceScope(ambient, hasExportStatement, this); + this.namespaceScopes.set(name, scope); + } else { + scope.refresh(ambient, hasExportStatement); + } + return scope; + } + end(cb) { + if (this.namespaceScopes !== undefined) { + this.namespaceScopes.forEach((value) => value.finish(cb)); + } + this.namespaceScopes = this.#enumScopes = undefined; + this.applyUses(); + this.variables.forEach((variable) => { + for (const declaration of variable.declarations) { + const result = { + declarations: [], + domain: declaration.domain, + exported: declaration.exported, + inGlobalScope: this.global, + uses: [] + }; + for (const other of variable.declarations) { + if (other.domain & declaration.domain) { + result.declarations.push(other.declaration); + } + } + for (const use of variable.uses) { + if (use.domain & declaration.domain) { + result.uses.push(use); + } + } + cb(result, declaration.declaration, this); + } + }); + } + getFunctionScope() { + return this; + } + getVariables() { + return this.variables; + } + // eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars + markExported(_name) { + } + // eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars + addUseToParent(_use) { + } + applyUse(use, variables = this.variables) { + const variable = variables.get(use.location.text); + if (variable === undefined || (variable.domain & use.domain) === 0) { + return false; + } + variable.uses.push(use); + return true; + } + applyUses() { + for (const use of this.uses) { + if (!this.applyUse(use)) { + this.addUseToParent(use); + } + } + this.uses = []; + } +}; +var NonRootScope = class extends AbstractScope { + constructor(parent, boundary) { + super(false); + this.parent = parent; + this.boundary = boundary; + } + getDestinationScope(selector) { + return this.boundary & selector ? this : this.parent.getDestinationScope(selector); + } + addUseToParent(use) { + return this.parent.addUse(use, this); + } +}; +var AbstractNamedExpressionScope = class extends NonRootScope { + #domain; + #name; + constructor(name, domain, parent) { + super(parent, 1 /* Function */); + this.#name = name; + this.#domain = domain; + } + addUse(use, source) { + if (source !== this.innerScope) { + return this.innerScope.addUse(use); + } + if (use.domain & this.#domain && use.location.text === this.#name.text) { + this.uses.push(use); + } else { + return this.parent.addUse(use, this); + } + } + end(cb) { + this.innerScope.end(cb); + return cb( + { + declarations: [this.#name], + domain: this.#domain, + exported: false, + inGlobalScope: false, + uses: this.uses + }, + this.#name, + this + ); + } + getDestinationScope() { + return this.innerScope; + } + getFunctionScope() { + return this.innerScope; + } +}; +var BlockScope = class extends NonRootScope { + #functionScope; + constructor(functionScope, parent) { + super(parent, 2 /* Block */); + this.#functionScope = functionScope; + } + getFunctionScope() { + return this.#functionScope; + } +}; +var ClassExpressionScope = class extends AbstractNamedExpressionScope { + innerScope = new NonRootScope(this, 1 /* Function */); + constructor(name, parent) { + super(name, 4 /* Value */ | 2 /* Type */, parent); + } +}; +var ConditionalTypeScope = class extends NonRootScope { + #state = 0 /* Initial */; + constructor(parent) { + super(parent, 8 /* ConditionalType */); + } + addUse(use) { + if (this.#state === 2 /* TrueType */) { + return void this.uses.push(use); + } + return this.parent.addUse(use, this); + } + updateState(newState) { + this.#state = newState; + } +}; +var EnumScope = class extends NonRootScope { + constructor(parent) { + super(parent, 1 /* Function */); + } + end() { + this.applyUses(); + } +}; +var FunctionScope = class extends NonRootScope { + constructor(parent) { + super(parent, 1 /* Function */); + } + beginBody() { + this.applyUses(); + } +}; +var FunctionExpressionScope = class extends AbstractNamedExpressionScope { + innerScope = new FunctionScope(this); + constructor(name, parent) { + super(name, 4 /* Value */, parent); + } + beginBody() { + return this.innerScope.beginBody(); + } +}; +var NamespaceScope = class extends NonRootScope { + #ambient; + #exports = undefined; + #hasExport; + #innerScope = new NonRootScope(this, 1 /* Function */); + constructor(ambient, hasExport, parent) { + super(parent, 1 /* Function */); + this.#ambient = ambient; + this.#hasExport = hasExport; + } + addUse(use, source) { + if (source !== this.#innerScope) { + return this.#innerScope.addUse(use); + } + this.uses.push(use); + } + createOrReuseEnumScope(name, exported) { + if (!exported && (!this.#ambient || this.#hasExport)) { + return this.#innerScope.createOrReuseEnumScope(name, exported); + } + return super.createOrReuseEnumScope(name, exported); + } + createOrReuseNamespaceScope(name, exported, ambient, hasExportStatement) { + if (!exported && (!this.#ambient || this.#hasExport)) { + return this.#innerScope.createOrReuseNamespaceScope( + name, + exported, + ambient || this.#ambient, + hasExportStatement + ); + } + return super.createOrReuseNamespaceScope( + name, + exported, + ambient || this.#ambient, + hasExportStatement + ); + } + end(cb) { + this.#innerScope.end((variable, key, scope) => { + if (scope !== this.#innerScope || !variable.exported && (!this.#ambient || this.#exports !== undefined && !this.#exports.has(key.text))) { + return cb(variable, key, scope); + } + const namespaceVar = this.variables.get(key.text); + if (namespaceVar === undefined) { + this.variables.set(key.text, { + declarations: variable.declarations.map(mapDeclaration), + domain: variable.domain, + uses: [...variable.uses] + }); + } else { + outer: for (const declaration of variable.declarations) { + for (const existing of namespaceVar.declarations) { + if (existing.declaration === declaration) { + continue outer; + } + namespaceVar.declarations.push(mapDeclaration(declaration)); + } + } + namespaceVar.domain |= variable.domain; + for (const use of variable.uses) { + if (namespaceVar.uses.includes(use)) { + continue; + } + namespaceVar.uses.push(use); + } + } + }); + this.applyUses(); + this.#innerScope = new NonRootScope(this, 1 /* Function */); + } + finish(cb) { + return super.end(cb); + } + getDestinationScope() { + return this.#innerScope; + } + markExported(name) { + if (this.#exports === undefined) { + this.#exports = /* @__PURE__ */ new Set(); + } + this.#exports.add(name.text); + } + refresh(ambient, hasExport) { + this.#ambient = ambient; + this.#hasExport = hasExport; + } +}; +var RootScope = class extends AbstractScope { + #exportAll; + #exports = undefined; + #innerScope = new NonRootScope(this, 1 /* Function */); + constructor(exportAll, global) { + super(global); + this.#exportAll = exportAll; + } + addUse(use, origin) { + if (origin === this.#innerScope) { + return super.addUse(use); + } + return this.#innerScope.addUse(use); + } + addVariable(identifier, name, selector, exported, domain) { + if (domain & 8 /* Import */) { + return super.addVariable(identifier, name, selector, exported, domain); + } + return this.#innerScope.addVariable( + identifier, + name, + selector, + exported, + domain + ); + } + end(cb) { + this.#innerScope.end((value, key) => { + value.exported ||= this.#exportAll || this.#exports !== undefined && this.#exports.includes(key.text); + value.inGlobalScope = this.global; + return cb(value, key, this); + }); + return super.end((value, key, scope) => { + value.exported ||= scope === this && this.#exports !== undefined && this.#exports.includes(key.text); + return cb(value, key, scope); + }); + } + getDestinationScope() { + return this; + } + markExported(id) { + if (this.#exports === undefined) { + this.#exports = [id.text]; + } else { + this.#exports.push(id.text); + } + } +}; +function mapDeclaration(declaration) { + return { + declaration, + domain: getDeclarationDomain(declaration), + exported: true + }; +} + +// src/usage/UsageWalker.ts +var UsageWalker = class { + #result = /* @__PURE__ */ new Map(); + #scope; + getUsage(sourceFile) { + const variableCallback = (variable, key) => { + this.#result.set(key, variable); + }; + const isModule = ts9__default.default.isExternalModule(sourceFile); + this.#scope = new RootScope( + sourceFile.isDeclarationFile && isModule && !containsExportStatement(sourceFile), + !isModule + ); + const cb = (node) => { + if (isBlockScopeBoundary(node)) { + return continueWithScope( + node, + new BlockScope(this.#scope.getFunctionScope(), this.#scope), + handleBlockScope + ); + } + switch (node.kind) { + case ts9__default.default.SyntaxKind.ArrowFunction: + case ts9__default.default.SyntaxKind.CallSignature: + case ts9__default.default.SyntaxKind.Constructor: + case ts9__default.default.SyntaxKind.ConstructorType: + case ts9__default.default.SyntaxKind.ConstructSignature: + case ts9__default.default.SyntaxKind.FunctionDeclaration: + case ts9__default.default.SyntaxKind.FunctionExpression: + case ts9__default.default.SyntaxKind.FunctionType: + case ts9__default.default.SyntaxKind.GetAccessor: + case ts9__default.default.SyntaxKind.MethodDeclaration: + case ts9__default.default.SyntaxKind.MethodSignature: + case ts9__default.default.SyntaxKind.SetAccessor: + return this.#handleFunctionLikeDeclaration( + node, + cb, + variableCallback + ); + case ts9__default.default.SyntaxKind.ClassDeclaration: + this.#handleDeclaration( + node, + true, + 4 /* Value */ | 2 /* Type */ + ); + return continueWithScope( + node, + new NonRootScope(this.#scope, 1 /* Function */) + ); + case ts9__default.default.SyntaxKind.ClassExpression: + return continueWithScope( + node, + node.name !== undefined ? new ClassExpressionScope( + node.name, + this.#scope + ) : new NonRootScope(this.#scope, 1 /* Function */) + ); + case ts9__default.default.SyntaxKind.ConditionalType: + return this.#handleConditionalType( + node, + cb, + variableCallback + ); + case ts9__default.default.SyntaxKind.EnumDeclaration: + this.#handleDeclaration( + node, + true, + 7 /* Any */ + ); + return continueWithScope( + node, + this.#scope.createOrReuseEnumScope( + node.name.text, + includesModifier( + node.modifiers, + ts9__default.default.SyntaxKind.ExportKeyword + ) + ) + ); + case ts9__default.default.SyntaxKind.EnumMember: + this.#scope.addVariable( + getPropertyName(node.name), + node.name, + 1 /* Function */, + true, + 4 /* Value */ + ); + break; + case ts9__default.default.SyntaxKind.ExportAssignment: + if (node.expression.kind === ts9__default.default.SyntaxKind.Identifier) { + return this.#scope.markExported( + node.expression + ); + } + break; + case ts9__default.default.SyntaxKind.ExportSpecifier: + if (node.propertyName !== undefined) { + return this.#scope.markExported( + node.propertyName, + node.name + ); + } + return this.#scope.markExported(node.name); + case ts9__default.default.SyntaxKind.Identifier: { + const domain = getUsageDomain(node); + if (domain !== undefined) { + this.#scope.addUse({ domain, location: node }); + } + return; + } + case ts9__default.default.SyntaxKind.ImportClause: + case ts9__default.default.SyntaxKind.ImportEqualsDeclaration: + case ts9__default.default.SyntaxKind.ImportSpecifier: + case ts9__default.default.SyntaxKind.NamespaceImport: + this.#handleDeclaration( + node, + false, + 7 /* Any */ | 8 /* Import */ + ); + break; + case ts9__default.default.SyntaxKind.InterfaceDeclaration: + case ts9__default.default.SyntaxKind.TypeAliasDeclaration: + this.#handleDeclaration( + node, + true, + 2 /* Type */ + ); + return continueWithScope( + node, + new NonRootScope(this.#scope, 4 /* Type */) + ); + case ts9__default.default.SyntaxKind.MappedType: + return continueWithScope( + node, + new NonRootScope(this.#scope, 4 /* Type */) + ); + case ts9__default.default.SyntaxKind.ModuleDeclaration: + return this.#handleModule( + node, + continueWithScope + ); + case ts9__default.default.SyntaxKind.Parameter: + if (node.parent.kind !== ts9__default.default.SyntaxKind.IndexSignature && (node.name.kind !== ts9__default.default.SyntaxKind.Identifier || identifierToKeywordKind( + node.name + ) !== ts9__default.default.SyntaxKind.ThisKeyword)) { + this.#handleBindingName( + node.name, + false, + false + ); + } + break; + case ts9__default.default.SyntaxKind.TypeParameter: + this.#scope.addVariable( + node.name.text, + node.name, + node.parent.kind === ts9__default.default.SyntaxKind.InferType ? 8 /* InferType */ : 7 /* Type */, + false, + 2 /* Type */ + ); + break; + // End of Scope specific handling + case ts9__default.default.SyntaxKind.VariableDeclarationList: + this.#handleVariableDeclaration(node); + break; + } + return ts9__default.default.forEachChild(node, cb); + }; + const continueWithScope = (node, scope, next = forEachChild) => { + const savedScope = this.#scope; + this.#scope = scope; + next(node); + this.#scope.end(variableCallback); + this.#scope = savedScope; + }; + const handleBlockScope = (node) => { + if (node.kind === ts9__default.default.SyntaxKind.CatchClause && node.variableDeclaration !== undefined) { + this.#handleBindingName( + node.variableDeclaration.name, + true, + false + ); + } + return ts9__default.default.forEachChild(node, cb); + }; + ts9__default.default.forEachChild(sourceFile, cb); + this.#scope.end(variableCallback); + return this.#result; + function forEachChild(node) { + return ts9__default.default.forEachChild(node, cb); + } + } + #handleBindingName(name, blockScoped, exported) { + if (name.kind === ts9__default.default.SyntaxKind.Identifier) { + return this.#scope.addVariable( + name.text, + name, + blockScoped ? 3 /* Block */ : 1 /* Function */, + exported, + 4 /* Value */ + ); + } + forEachDestructuringIdentifier(name, (declaration) => { + this.#scope.addVariable( + declaration.name.text, + declaration.name, + blockScoped ? 3 /* Block */ : 1 /* Function */, + exported, + 4 /* Value */ + ); + }); + } + #handleConditionalType(node, cb, varCb) { + const savedScope = this.#scope; + const scope = this.#scope = new ConditionalTypeScope(savedScope); + cb(node.checkType); + scope.updateState(1 /* Extends */); + cb(node.extendsType); + scope.updateState(2 /* TrueType */); + cb(node.trueType); + scope.updateState(3 /* FalseType */); + cb(node.falseType); + scope.end(varCb); + this.#scope = savedScope; + } + #handleDeclaration(node, blockScoped, domain) { + if (node.name !== undefined) { + this.#scope.addVariable( + node.name.text, + node.name, + blockScoped ? 3 /* Block */ : 1 /* Function */, + includesModifier( + node.modifiers, + ts9__default.default.SyntaxKind.ExportKeyword + ), + domain + ); + } + } + #handleFunctionLikeDeclaration(node, cb, varCb) { + if (ts9__default.default.canHaveDecorators(node)) { + ts9__default.default.getDecorators(node)?.forEach(cb); + } + const savedScope = this.#scope; + if (node.kind === ts9__default.default.SyntaxKind.FunctionDeclaration) { + this.#handleDeclaration(node, false, 4 /* Value */); + } + const scope = this.#scope = node.kind === ts9__default.default.SyntaxKind.FunctionExpression && node.name !== undefined ? new FunctionExpressionScope(node.name, savedScope) : new FunctionScope(savedScope); + if (node.name !== undefined) { + cb(node.name); + } + if (node.typeParameters !== undefined) { + node.typeParameters.forEach(cb); + } + node.parameters.forEach(cb); + if (node.type !== undefined) { + cb(node.type); + } + if (node.body !== undefined) { + scope.beginBody(); + cb(node.body); + } + scope.end(varCb); + this.#scope = savedScope; + } + #handleModule(node, next) { + if (node.flags & ts9__default.default.NodeFlags.GlobalAugmentation) { + return next( + node, + this.#scope.createOrReuseNamespaceScope("-global", false, true, false) + ); + } + if (node.name.kind === ts9__default.default.SyntaxKind.Identifier) { + const exported = isNamespaceExported(node); + this.#scope.addVariable( + node.name.text, + node.name, + 1 /* Function */, + exported, + 1 /* Namespace */ | 4 /* Value */ + ); + const ambient = includesModifier( + node.modifiers, + ts9__default.default.SyntaxKind.DeclareKeyword + ); + return next( + node, + this.#scope.createOrReuseNamespaceScope( + node.name.text, + exported, + ambient, + ambient && namespaceHasExportStatement(node) + ) + ); + } + return next( + node, + this.#scope.createOrReuseNamespaceScope( + `"${node.name.text}"`, + false, + true, + namespaceHasExportStatement(node) + ) + ); + } + #handleVariableDeclaration(declarationList) { + const blockScoped = isBlockScopedVariableDeclarationList(declarationList); + const exported = declarationList.parent.kind === ts9__default.default.SyntaxKind.VariableStatement && includesModifier( + declarationList.parent.modifiers, + ts9__default.default.SyntaxKind.ExportKeyword + ); + for (const declaration of declarationList.declarations) { + this.#handleBindingName(declaration.name, blockScoped, exported); + } + } +}; +function containsExportStatement(block) { + for (const statement of block.statements) { + if (statement.kind === ts9__default.default.SyntaxKind.ExportDeclaration || statement.kind === ts9__default.default.SyntaxKind.ExportAssignment) { + return true; + } + } + return false; +} +function forEachDestructuringIdentifier(pattern, fn) { + for (const element of pattern.elements) { + if (element.kind !== ts9__default.default.SyntaxKind.BindingElement) { + continue; + } + let result; + if (element.name.kind === ts9__default.default.SyntaxKind.Identifier) { + result = fn(element); + } else { + result = forEachDestructuringIdentifier(element.name, fn); + } + if (result) { + return result; + } + } +} +function isBlockScopedVariableDeclarationList(declarationList) { + return (declarationList.flags & ts9__default.default.NodeFlags.BlockScoped) !== 0; +} +function isNamespaceExported(node) { + return node.parent.kind === ts9__default.default.SyntaxKind.ModuleDeclaration || includesModifier(node.modifiers, ts9__default.default.SyntaxKind.ExportKeyword); +} +function namespaceHasExportStatement(ns) { + if (ns.body === undefined || ns.body.kind !== ts9__default.default.SyntaxKind.ModuleBlock) { + return false; + } + return containsExportStatement(ns.body); +} + +// src/usage/collectVariableUsage.ts +function collectVariableUsage(sourceFile) { + return new UsageWalker().getUsage(sourceFile); +} + +exports.AccessKind = AccessKind; +exports.DeclarationDomain = DeclarationDomain; +exports.UsageDomain = UsageDomain; +exports.collectVariableUsage = collectVariableUsage; +exports.forEachComment = forEachComment; +exports.forEachToken = forEachToken; +exports.getAccessKind = getAccessKind; +exports.getCallSignaturesOfType = getCallSignaturesOfType; +exports.getPropertyOfType = getPropertyOfType; +exports.getWellKnownSymbolPropertyOfType = getWellKnownSymbolPropertyOfType; +exports.hasDecorators = hasDecorators; +exports.hasExpressionInitializer = hasExpressionInitializer; +exports.hasInitializer = hasInitializer; +exports.hasJSDoc = hasJSDoc; +exports.hasModifiers = hasModifiers; +exports.hasType = hasType; +exports.hasTypeArguments = hasTypeArguments; +exports.includesModifier = includesModifier; +exports.intersectionConstituents = intersectionConstituents; +exports.intersectionTypeParts = intersectionTypeParts; +exports.isAbstractKeyword = isAbstractKeyword; +exports.isAccessExpression = isAccessExpression; +exports.isAccessibilityModifier = isAccessibilityModifier; +exports.isAccessorDeclaration = isAccessorDeclaration; +exports.isAccessorKeyword = isAccessorKeyword; +exports.isAnyKeyword = isAnyKeyword; +exports.isArrayBindingElement = isArrayBindingElement; +exports.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; +exports.isAssertKeyword = isAssertKeyword; +exports.isAssertsKeyword = isAssertsKeyword; +exports.isAssignmentKind = isAssignmentKind; +exports.isAssignmentPattern = isAssignmentPattern; +exports.isAsyncKeyword = isAsyncKeyword; +exports.isAwaitKeyword = isAwaitKeyword; +exports.isBigIntKeyword = isBigIntKeyword; +exports.isBigIntLiteralType = isBigIntLiteralType; +exports.isBindingOrAssignmentElementRestIndicator = isBindingOrAssignmentElementRestIndicator; +exports.isBindingOrAssignmentElementTarget = isBindingOrAssignmentElementTarget; +exports.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; +exports.isBindingPattern = isBindingPattern; +exports.isBlockLike = isBlockLike; +exports.isBooleanKeyword = isBooleanKeyword; +exports.isBooleanLiteral = isBooleanLiteral; +exports.isBooleanLiteralType = isBooleanLiteralType; +exports.isClassLikeDeclaration = isClassLikeDeclaration; +exports.isClassMemberModifier = isClassMemberModifier; +exports.isColonToken = isColonToken; +exports.isCompilerOptionEnabled = isCompilerOptionEnabled; +exports.isConditionalType = isConditionalType; +exports.isConstAssertionExpression = isConstAssertionExpression; +exports.isConstKeyword = isConstKeyword; +exports.isDeclarationName = isDeclarationName; +exports.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; +exports.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; +exports.isDeclareKeyword = isDeclareKeyword; +exports.isDefaultKeyword = isDefaultKeyword; +exports.isDestructuringPattern = isDestructuringPattern; +exports.isDotToken = isDotToken; +exports.isEndOfFileToken = isEndOfFileToken; +exports.isEntityNameExpression = isEntityNameExpression; +exports.isEntityNameOrEntityNameExpression = isEntityNameOrEntityNameExpression; +exports.isEnumType = isEnumType; +exports.isEqualsGreaterThanToken = isEqualsGreaterThanToken; +exports.isEqualsToken = isEqualsToken; +exports.isEvolvingArrayType = isEvolvingArrayType; +exports.isExclamationToken = isExclamationToken; +exports.isExportKeyword = isExportKeyword; +exports.isFalseKeyword = isFalseKeyword; +exports.isFalseLiteral = isFalseLiteral; +exports.isFalseLiteralType = isFalseLiteralType; +exports.isFalsyType = isFalsyType; +exports.isForInOrOfStatement = isForInOrOfStatement; +exports.isFreshableIntrinsicType = isFreshableIntrinsicType; +exports.isFreshableType = isFreshableType; +exports.isFunctionLikeDeclaration = isFunctionLikeDeclaration; +exports.isFunctionScopeBoundary = isFunctionScopeBoundary; +exports.isImportExpression = isImportExpression; +exports.isImportKeyword = isImportKeyword; +exports.isInKeyword = isInKeyword; +exports.isIndexType = isIndexType; +exports.isIndexedAccessType = isIndexedAccessType; +exports.isInstantiableType = isInstantiableType; +exports.isIntersectionType = isIntersectionType; +exports.isIntrinsicAnyType = isIntrinsicAnyType; +exports.isIntrinsicBigIntType = isIntrinsicBigIntType; +exports.isIntrinsicBooleanType = isIntrinsicBooleanType; +exports.isIntrinsicESSymbolType = isIntrinsicESSymbolType; +exports.isIntrinsicErrorType = isIntrinsicErrorType; +exports.isIntrinsicNeverType = isIntrinsicNeverType; +exports.isIntrinsicNonPrimitiveType = isIntrinsicNonPrimitiveType; +exports.isIntrinsicNullType = isIntrinsicNullType; +exports.isIntrinsicNumberType = isIntrinsicNumberType; +exports.isIntrinsicStringType = isIntrinsicStringType; +exports.isIntrinsicType = isIntrinsicType; +exports.isIntrinsicUndefinedType = isIntrinsicUndefinedType; +exports.isIntrinsicUnknownType = isIntrinsicUnknownType; +exports.isIntrinsicVoidType = isIntrinsicVoidType; +exports.isIterationStatement = isIterationStatement; +exports.isJSDocComment = isJSDocComment; +exports.isJSDocNamespaceBody = isJSDocNamespaceBody; +exports.isJSDocNamespaceDeclaration = isJSDocNamespaceDeclaration; +exports.isJSDocText = isJSDocText; +exports.isJSDocTypeReferencingNode = isJSDocTypeReferencingNode; +exports.isJsonMinusNumericLiteral = isJsonMinusNumericLiteral; +exports.isJsonObjectExpression = isJsonObjectExpression; +exports.isJsxAttributeLike = isJsxAttributeLike; +exports.isJsxAttributeValue = isJsxAttributeValue; +exports.isJsxChild = isJsxChild; +exports.isJsxTagNameExpression = isJsxTagNameExpression; +exports.isJsxTagNamePropertyAccess = isJsxTagNamePropertyAccess; +exports.isLiteralToken = isLiteralToken; +exports.isLiteralType = isLiteralType; +exports.isModifierFlagSet = isModifierFlagSet; +exports.isModuleBody = isModuleBody; +exports.isModuleName = isModuleName; +exports.isModuleReference = isModuleReference; +exports.isNamedDeclarationWithName = isNamedDeclarationWithName; +exports.isNamedImportBindings = isNamedImportBindings; +exports.isNamedImportsOrExports = isNamedImportsOrExports; +exports.isNamespaceBody = isNamespaceBody; +exports.isNamespaceDeclaration = isNamespaceDeclaration; +exports.isNeverKeyword = isNeverKeyword; +exports.isNodeFlagSet = isNodeFlagSet; +exports.isNullKeyword = isNullKeyword; +exports.isNullLiteral = isNullLiteral; +exports.isNumberKeyword = isNumberKeyword; +exports.isNumberLiteralType = isNumberLiteralType; +exports.isNumericOrStringLikeLiteral = isNumericOrStringLikeLiteral; +exports.isNumericPropertyName = isNumericPropertyName; +exports.isObjectBindingOrAssignmentElement = isObjectBindingOrAssignmentElement; +exports.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; +exports.isObjectFlagSet = isObjectFlagSet; +exports.isObjectKeyword = isObjectKeyword; +exports.isObjectType = isObjectType; +exports.isObjectTypeDeclaration = isObjectTypeDeclaration; +exports.isOutKeyword = isOutKeyword; +exports.isOverrideKeyword = isOverrideKeyword; +exports.isParameterPropertyModifier = isParameterPropertyModifier; +exports.isPrivateKeyword = isPrivateKeyword; +exports.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; +exports.isPropertyNameLiteral = isPropertyNameLiteral; +exports.isPropertyReadonlyInType = isPropertyReadonlyInType; +exports.isProtectedKeyword = isProtectedKeyword; +exports.isPseudoLiteralToken = isPseudoLiteralToken; +exports.isPublicKeyword = isPublicKeyword; +exports.isQuestionDotToken = isQuestionDotToken; +exports.isQuestionToken = isQuestionToken; +exports.isReadonlyKeyword = isReadonlyKeyword; +exports.isSignatureDeclaration = isSignatureDeclaration; +exports.isStaticKeyword = isStaticKeyword; +exports.isStrictCompilerOptionEnabled = isStrictCompilerOptionEnabled; +exports.isStringKeyword = isStringKeyword; +exports.isStringLiteralType = isStringLiteralType; +exports.isStringMappingType = isStringMappingType; +exports.isSubstitutionType = isSubstitutionType; +exports.isSuperElementAccessExpression = isSuperElementAccessExpression; +exports.isSuperExpression = isSuperExpression; +exports.isSuperKeyword = isSuperKeyword; +exports.isSuperProperty = isSuperProperty; +exports.isSuperPropertyAccessExpression = isSuperPropertyAccessExpression; +exports.isSymbolFlagSet = isSymbolFlagSet; +exports.isSymbolKeyword = isSymbolKeyword; +exports.isSyntaxList = isSyntaxList; +exports.isTemplateLiteralType = isTemplateLiteralType; +exports.isThenableType = isThenableType; +exports.isThisExpression = isThisExpression; +exports.isThisKeyword = isThisKeyword; +exports.isTransientSymbolLinksFlagSet = isTransientSymbolLinksFlagSet; +exports.isTrueKeyword = isTrueKeyword; +exports.isTrueLiteral = isTrueLiteral; +exports.isTrueLiteralType = isTrueLiteralType; +exports.isTupleType = isTupleType; +exports.isTupleTypeReference = isTupleTypeReference; +exports.isTypeFlagSet = isTypeFlagSet; +exports.isTypeOnlyCompatibleAliasDeclaration = isTypeOnlyCompatibleAliasDeclaration; +exports.isTypeParameter = isTypeParameter; +exports.isTypeReference = isTypeReference; +exports.isTypeReferenceType = isTypeReferenceType; +exports.isTypeVariable = isTypeVariable; +exports.isUndefinedKeyword = isUndefinedKeyword; +exports.isUnionOrIntersectionType = isUnionOrIntersectionType; +exports.isUnionOrIntersectionTypeNode = isUnionOrIntersectionTypeNode; +exports.isUnionType = isUnionType; +exports.isUniqueESSymbolType = isUniqueESSymbolType; +exports.isUnknownKeyword = isUnknownKeyword; +exports.isValidPropertyAccess = isValidPropertyAccess; +exports.isVariableLikeDeclaration = isVariableLikeDeclaration; +exports.isVoidKeyword = isVoidKeyword; +exports.symbolHasReadonlyDeclaration = symbolHasReadonlyDeclaration; +exports.typeConstituents = typeConstituents; +exports.typeIsLiteral = typeIsLiteral; +exports.typeParts = typeParts; +exports.unionConstituents = unionConstituents; +exports.unionTypeParts = unionTypeParts; diff --git a/node_modules/ts-api-utils/lib/index.d.cts b/node_modules/ts-api-utils/lib/index.d.cts new file mode 100644 index 00000000..87946f8c --- /dev/null +++ b/node_modules/ts-api-utils/lib/index.d.cts @@ -0,0 +1,3019 @@ +import ts from 'typescript'; + +/** + * Callback type used for {@link forEachComment}. + * @category Callbacks + * @param fullText Full parsed text of the comment. + * @param comment Text range of the comment in its file. + * @example + * ```ts + * let onComment: ForEachCommentCallback = (fullText, comment) => { + * console.log(`Found comment at position ${comment.pos}: '${fullText}'.`); + * }; + * ``` + */ +type ForEachCommentCallback = (fullText: string, comment: ts.CommentRange) => void; +/** + * Iterates over all comments owned by `node` or its children. + * @category Nodes - Other Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * forEachComment(node, (fullText, comment) => { + * console.log(`Found comment at position ${comment.pos}: '${fullText}'.`); + * }); + * ``` + */ +declare function forEachComment(node: ts.Node, callback: ForEachCommentCallback, sourceFile?: ts.SourceFile): void; + +/** + * An option that can be tested with {@link isCompilerOptionEnabled}. + * @category Compiler Options + */ +type BooleanCompilerOptions = keyof { + [K in keyof ts.CompilerOptions as NonNullable extends boolean ? K : never]: unknown; +}; +/** + * An option that can be tested with {@link isStrictCompilerOptionEnabled}. + * @category Compiler Options + */ +type StrictCompilerOption = "alwaysStrict" | "noImplicitAny" | "noImplicitThis" | "strictBindCallApply" | "strictFunctionTypes" | "strictNullChecks" | "strictPropertyInitialization"; +/** + * Checks if a given compiler option is enabled. + * It handles dependencies of options, e.g. `declaration` is implicitly enabled by `composite` or `strictNullChecks` is enabled by `strict`. + * However, it does not check dependencies that are already checked and reported as errors, e.g. `checkJs` without `allowJs`. + * This function only handles boolean flags. + * @category Compiler Options + * @example + * ```ts + * const options = { + * allowJs: true, + * }; + * + * isCompilerOptionEnabled(options, "allowJs"); // true + * isCompilerOptionEnabled(options, "allowSyntheticDefaultImports"); // false + * ``` + */ +declare function isCompilerOptionEnabled(options: ts.CompilerOptions, option: BooleanCompilerOptions): boolean; +/** + * Checks if a given compiler option is enabled, accounting for whether all flags + * (except `strictPropertyInitialization`) have been enabled by `strict: true`. + * @category Compiler Options + * @example + * ```ts + * const optionsLenient = { + * noImplicitAny: true, + * }; + * + * isStrictCompilerOptionEnabled(optionsLenient, "noImplicitAny"); // true + * isStrictCompilerOptionEnabled(optionsLenient, "noImplicitThis"); // false + * ``` + * @example + * ```ts + * const optionsStrict = { + * noImplicitThis: false, + * strict: true, + * }; + * + * isStrictCompilerOptionEnabled(optionsStrict, "noImplicitAny"); // true + * isStrictCompilerOptionEnabled(optionsStrict, "noImplicitThis"); // false + * ``` + */ +declare function isStrictCompilerOptionEnabled(options: ts.CompilerOptions, option: StrictCompilerOption): boolean; + +/** + * Test if the given node has the given `ModifierFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isModifierFlagSet(node, ts.ModifierFlags.Abstract)) { + * // ... + * } + * ``` + */ +declare function isModifierFlagSet(node: ts.Declaration, flag: ts.ModifierFlags): boolean; +/** + * Test if the given node has the given `NodeFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNodeFlagSet(node, ts.NodeFlags.AwaitContext)) { + * // ... + * } + * ``` + */ +declare const isNodeFlagSet: (node: ts.Node, flag: ts.NodeFlags) => boolean; +/** + * Test if the given node has the given `ObjectFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectFlagSet(node, ts.ObjectFlags.Anonymous)) { + * // ... + * } + * ``` + */ +declare function isObjectFlagSet(objectType: ts.ObjectType, flag: ts.ObjectFlags): boolean; +/** + * Test if the given node has the given `SymbolFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const symbol: ts.Symbol; + * + * if (isSymbolFlagSet(symbol, ts.SymbolFlags.Accessor)) { + * // ... + * } + * ``` + */ +declare const isSymbolFlagSet: (symbol: ts.Symbol, flag: ts.SymbolFlags) => boolean; +/** + * Test if the given symbol's links has the given `CheckFlags` set. + * @internal + */ +declare function isTransientSymbolLinksFlagSet(links: ts.TransientSymbolLinks, flag: ts.CheckFlags): boolean; +/** + * Test if the given node has the given `TypeFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTypeFlagSet(type, ts.TypeFlags.Any)) { + * // ... + * } + * ``` + */ +declare const isTypeFlagSet: (type: ts.Type, flag: ts.TypeFlags) => boolean; + +/** + * Test if the given iterable includes a modifier of any of the given kinds. + * @category Modifier Utilities + * @example + * ```ts + * declare const modifiers: ts.Modifier[]; + * + * includesModifier(modifiers, ts.SyntaxKind.AbstractKeyword); + * ``` + */ +declare function includesModifier(modifiers: Iterable | undefined, ...kinds: ts.ModifierSyntaxKind[]): boolean; + +/** + * What operations(s), if any, an expression applies. + */ +declare enum AccessKind { + None = 0, + Read = 1, + Write = 2, + Delete = 4, + ReadWrite = 3 +} +/** + * Determines which operation(s), if any, an expression applies. + * @example + * ```ts + * declare const node: ts.Expression; + * + * if (getAccessKind(node).Write & AccessKind.Write) !== 0) { + * // this is a reassignment (write) + * } + * ``` + */ +declare function getAccessKind(node: ts.Expression): AccessKind; + +/** + * An `AssertionExpression` that is declared as const. + * @category Node Types + */ +type ConstAssertionExpression = ts.AssertionExpression & { + type: ts.TypeReferenceNode; + typeName: ConstAssertionIdentifier; +}; +/** + * An `Identifier` with an `escapedText` value of `"const"`. + * @category Node Types + */ +type ConstAssertionIdentifier = ts.Identifier & { + escapedText: "const" & ts.__String; +}; +/** + * a `NamedDeclaration` that definitely has a name. + * @category Node Types + */ +interface NamedDeclarationWithName extends ts.NamedDeclaration { + name: ts.DeclarationName; +} +/** + * A number or string-like literal. + * @category Node Types + */ +type NumericOrStringLikeLiteral = ts.NumericLiteral | ts.StringLiteralLike; +/** + * Test if a node is a {@link ConstAssertionExpression}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isConstAssertionExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link ConstAssertionExpression}. + */ +declare function isConstAssertionExpression(node: ts.AssertionExpression): node is ConstAssertionExpression; +/** + * Test if a node is an `IterationStatement`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isIterationStatement(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `IterationStatement`. + */ +declare function isIterationStatement(node: ts.Node): node is ts.IterationStatement; +/** + * Test if a node is a `JSDocNamespaceDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocNamespaceDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocNamespaceDeclaration`. + */ +declare function isJSDocNamespaceDeclaration(node: ts.Node): node is ts.JSDocNamespaceDeclaration; +/** + * Test if a node is a `JsxTagNamePropertyAccess`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxTagNamePropertyAccess(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxTagNamePropertyAccess`. + */ +declare function isJsxTagNamePropertyAccess(node: ts.Node): node is ts.JsxTagNamePropertyAccess; +/** + * Test if a node is a {@link NamedDeclarationWithName}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamedDeclarationWithName(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NamedDeclarationWithName}. + */ +declare function isNamedDeclarationWithName(node: ts.Declaration): node is NamedDeclarationWithName; +/** + * Test if a node is a `NamespaceDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamespaceDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NamespaceDeclaration`. + */ +declare function isNamespaceDeclaration(node: ts.Node): node is ts.NamespaceDeclaration; +/** + * Test if a node is a {@link NumericOrStringLikeLiteral}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNumericOrStringLikeLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NumericOrStringLikeLiteral}. + */ +declare function isNumericOrStringLikeLiteral(node: ts.Node): node is NumericOrStringLikeLiteral; +/** + * Test if a node is a `PropertyAccessEntityNameExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPropertyAccessEntityNameExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PropertyAccessEntityNameExpression`. + */ +declare function isPropertyAccessEntityNameExpression(node: ts.Node): node is ts.PropertyAccessEntityNameExpression; +/** + * Test if a node is a `SuperElementAccessExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperElementAccessExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SuperElementAccessExpression`. + */ +declare function isSuperElementAccessExpression(node: ts.Node): node is ts.SuperElementAccessExpression; +/** + * Test if a node is a `SuperPropertyAccessExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperPropertyAccessExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SuperPropertyAccessExpression`. + */ +declare function isSuperPropertyAccessExpression(node: ts.Node): node is ts.SuperPropertyAccessExpression; + +/** + * A node that represents the any keyword. + * @category Node Types + */ +type AnyKeyword = ts.KeywordToken; +/** + * A node that represents the bigint keyword. + * @category Node Types + */ +type BigIntKeyword = ts.KeywordToken; +/** + * A node that represents the boolean keyword. + * @category Node Types + */ +type BooleanKeyword = ts.KeywordToken; +/** + * A node that represents the false keyword. + * @category Node Types + */ +type FalseKeyword = ts.KeywordToken; +/** + * A node that represents the import keyword. + * @category Node Types + */ +type ImportKeyword = ts.KeywordToken; +/** + * A node that represents the never keyword. + * @category Node Types + */ +type NeverKeyword = ts.KeywordToken; +/** + * A node that represents the null keyword. + * @category Node Types + */ +type NullKeyword = ts.KeywordToken; +/** + * A node that represents the number keyword. + * @category Node Types + */ +type NumberKeyword = ts.KeywordToken; +/** + * A node that represents the object keyword. + * @category Node Types + */ +type ObjectKeyword = ts.KeywordToken; +/** + * A node that represents the string keyword. + * @category Node Types + */ +type StringKeyword = ts.KeywordToken; +/** + * A node that represents the super keyword. + * @category Node Types + */ +type SuperKeyword = ts.KeywordToken; +/** + * A node that represents the symbol keyword. + * @category Node Types + */ +type SymbolKeyword = ts.KeywordToken; +/** + * A node that represents the this keyword. + * @category Node Types + */ +type ThisKeyword = ts.KeywordToken; +/** + * A node that represents the true keyword. + * @category Node Types + */ +type TrueKeyword = ts.KeywordToken; +/** + * A node that represents the undefined keyword. + * @category Node Types + */ +type UndefinedKeyword = ts.KeywordToken; +/** + * A node that represents the unknown keyword. + * @category Node Types + */ +type UnknownKeyword = ts.KeywordToken; +/** + * A node that represents the void keyword. + * @category Node Types + */ +type VoidKeyword = ts.KeywordToken; +/** + * Test if a node is an `AbstractKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAbstractKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AbstractKeyword`. + */ +declare function isAbstractKeyword(node: ts.Node): node is ts.AbstractKeyword; +/** + * Test if a node is an `AccessorKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAccessorKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AccessorKeyword`. + */ +declare function isAccessorKeyword(node: ts.Node): node is ts.AccessorKeyword; +/** + * Test if a node is an {@link AnyKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAnyKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link AnyKeyword}. + */ +declare function isAnyKeyword(node: ts.Node): node is AnyKeyword; +/** + * Test if a node is an `AssertKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAssertKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AssertKeyword`. + */ +declare function isAssertKeyword(node: ts.Node): node is ts.AssertKeyword; +/** + * Test if a node is an `AssertsKeyword`. + * @deprecated With TypeScript v5, in favor of typescript's `isAssertsKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAssertsKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AssertsKeyword`. + */ +declare function isAssertsKeyword(node: ts.Node): node is ts.AssertsKeyword; +/** + * Test if a node is an `AsyncKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAsyncKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AsyncKeyword`. + */ +declare function isAsyncKeyword(node: ts.Node): node is ts.AsyncKeyword; +/** + * Test if a node is an `AwaitKeyword`. + * @deprecated With TypeScript v5, in favor of typescript's `isAwaitKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAwaitKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AwaitKeyword`. + */ +declare function isAwaitKeyword(node: ts.Node): node is ts.AwaitKeyword; +/** + * Test if a node is a {@link BigIntKeyword}. + * @deprecated With TypeScript v5, in favor of typescript's `isBigIntKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBigIntKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link BigIntKeyword}. + */ +declare function isBigIntKeyword(node: ts.Node): node is BigIntKeyword; +/** + * Test if a node is a {@link BooleanKeyword}. + * @deprecated With TypeScript v5, in favor of typescript's `isBooleanKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBooleanKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link BooleanKeyword}. + */ +declare function isBooleanKeyword(node: ts.Node): node is BooleanKeyword; +/** + * Test if a node is a `ColonToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isColonToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isColonToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ColonToken`. + */ +declare function isColonToken(node: ts.Node): node is ts.ColonToken; +/** + * Test if a node is a `ConstKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isConstKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ConstKeyword`. + */ +declare function isConstKeyword(node: ts.Node): node is ts.ConstKeyword; +/** + * Test if a node is a `DeclareKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDeclareKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DeclareKeyword`. + */ +declare function isDeclareKeyword(node: ts.Node): node is ts.DeclareKeyword; +/** + * Test if a node is a `DefaultKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDefaultKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DefaultKeyword`. + */ +declare function isDefaultKeyword(node: ts.Node): node is ts.DefaultKeyword; +/** + * Test if a node is a `DotToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDotToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DotToken`. + */ +declare function isDotToken(node: ts.Node): node is ts.DotToken; +/** + * Test if a node is an `EndOfFileToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEndOfFileToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EndOfFileToken`. + */ +declare function isEndOfFileToken(node: ts.Node): node is ts.EndOfFileToken; +/** + * Test if a node is an `EqualsGreaterThanToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isEqualsGreaterThanToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEqualsGreaterThanToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EqualsGreaterThanToken`. + */ +declare function isEqualsGreaterThanToken(node: ts.Node): node is ts.EqualsGreaterThanToken; +/** + * Test if a node is an `EqualsToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEqualsToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EqualsToken`. + */ +declare function isEqualsToken(node: ts.Node): node is ts.EqualsToken; +/** + * Test if a node is an `ExclamationToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isExclamationToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isExclamationToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ExclamationToken`. + */ +declare function isExclamationToken(node: ts.Node): node is ts.ExclamationToken; +/** + * Test if a node is an `ExportKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isExportKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ExportKeyword`. + */ +declare function isExportKeyword(node: ts.Node): node is ts.ExportKeyword; +/** + * Test if a node is a {@link FalseKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isFalseKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link FalseKeyword}. + */ +declare function isFalseKeyword(node: ts.Node): node is FalseKeyword; +/** + * Test if a node is a `FalseLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isFalseLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `FalseLiteral`. + */ +declare function isFalseLiteral(node: ts.Node): node is ts.FalseLiteral; +/** + * Test if a node is an `ImportExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isImportExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ImportExpression`. + */ +declare function isImportExpression(node: ts.Node): node is ts.ImportExpression; +/** + * Test if a node is an {@link ImportKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isImportKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link ImportKeyword}. + */ +declare function isImportKeyword(node: ts.Node): node is ImportKeyword; +/** + * Test if a node is an `InKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isInKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `InKeyword`. + */ +declare function isInKeyword(node: ts.Node): node is ts.InKeyword; +/** + * Test if a node is a `JSDocText`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocText(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocText`. + */ +declare function isJSDocText(node: ts.Node): node is ts.JSDocText; +/** + * Test if a node is a `JsonMinusNumericLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsonMinusNumericLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsonMinusNumericLiteral`. + */ +declare function isJsonMinusNumericLiteral(node: ts.Node): node is ts.JsonMinusNumericLiteral; +/** + * Test if a node is a {@link NeverKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNeverKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NeverKeyword}. + */ +declare function isNeverKeyword(node: ts.Node): node is NeverKeyword; +/** + * Test if a node is a {@link NullKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNullKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NullKeyword}. + */ +declare function isNullKeyword(node: ts.Node): node is NullKeyword; +/** + * Test if a node is a `NullLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNullLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NullLiteral`. + */ +declare function isNullLiteral(node: ts.Node): node is ts.NullLiteral; +/** + * Test if a node is a {@link NumberKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNumberKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NumberKeyword}. + */ +declare function isNumberKeyword(node: ts.Node): node is NumberKeyword; +/** + * Test if a node is an {@link ObjectKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link ObjectKeyword}. + */ +declare function isObjectKeyword(node: ts.Node): node is ObjectKeyword; +/** + * Test if a node is an `OutKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isOutKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `OutKeyword`. + */ +declare function isOutKeyword(node: ts.Node): node is ts.OutKeyword; +/** + * Test if a node is an `OverrideKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isOverrideKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `OverrideKeyword`. + */ +declare function isOverrideKeyword(node: ts.Node): node is ts.OverrideKeyword; +/** + * Test if a node is a `PrivateKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPrivateKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PrivateKeyword`. + */ +declare function isPrivateKeyword(node: ts.Node): node is ts.PrivateKeyword; +/** + * Test if a node is a `ProtectedKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isProtectedKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ProtectedKeyword`. + */ +declare function isProtectedKeyword(node: ts.Node): node is ts.ProtectedKeyword; +/** + * Test if a node is a `PublicKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPublicKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PublicKeyword`. + */ +declare function isPublicKeyword(node: ts.Node): node is ts.PublicKeyword; +/** + * Test if a node is a `QuestionDotToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isQuestionDotToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isQuestionDotToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `QuestionDotToken`. + */ +declare function isQuestionDotToken(node: ts.Node): node is ts.QuestionDotToken; +/** + * Test if a node is a `QuestionToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isQuestionToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isQuestionToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `QuestionToken`. + */ +declare function isQuestionToken(node: ts.Node): node is ts.QuestionToken; +/** + * Test if a node is a `ReadonlyKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isReadonlyKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ReadonlyKeyword`. + */ +declare function isReadonlyKeyword(node: ts.Node): node is ts.ReadonlyKeyword; +/** + * Test if a node is a `StaticKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isStaticKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `StaticKeyword`. + */ +declare function isStaticKeyword(node: ts.Node): node is ts.StaticKeyword; +/** + * Test if a node is a {@link StringKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isStringKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link StringKeyword}. + */ +declare function isStringKeyword(node: ts.Node): node is StringKeyword; +/** + * Test if a node is a `SuperExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SuperExpression`. + */ +declare function isSuperExpression(node: ts.Node): node is ts.SuperExpression; +/** + * Test if a node is a {@link SuperKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link SuperKeyword}. + */ +declare function isSuperKeyword(node: ts.Node): node is SuperKeyword; +/** + * Test if a node is a {@link SymbolKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSymbolKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link SymbolKeyword}. + */ +declare function isSymbolKeyword(node: ts.Node): node is SymbolKeyword; +/** + * Test if a node is a `SyntaxList`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSyntaxList(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SyntaxList`. + */ +declare function isSyntaxList(node: ts.Node): node is ts.SyntaxList; +/** + * Test if a node is a `ThisExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isThisExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ThisExpression`. + */ +declare function isThisExpression(node: ts.Node): node is ts.ThisExpression; +/** + * Test if a node is a {@link ThisKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isThisKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link ThisKeyword}. + */ +declare function isThisKeyword(node: ts.Node): node is ThisKeyword; +/** + * Test if a node is a {@link TrueKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isTrueKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link TrueKeyword}. + */ +declare function isTrueKeyword(node: ts.Node): node is TrueKeyword; +/** + * Test if a node is a `TrueLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isTrueLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `TrueLiteral`. + */ +declare function isTrueLiteral(node: ts.Node): node is ts.TrueLiteral; +/** + * Test if a node is an {@link UndefinedKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isUndefinedKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link UndefinedKeyword}. + */ +declare function isUndefinedKeyword(node: ts.Node): node is UndefinedKeyword; +/** + * Test if a node is an {@link UnknownKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isUnknownKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link UnknownKeyword}. + */ +declare function isUnknownKeyword(node: ts.Node): node is UnknownKeyword; +/** + * Test if a node is a {@link VoidKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isVoidKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link VoidKeyword}. + */ +declare function isVoidKeyword(node: ts.Node): node is VoidKeyword; + +/** + * Test if a node is a `HasDecorators`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasDecorators(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasDecorators`. + */ +declare function hasDecorators(node: ts.Node): node is ts.HasDecorators; +/** + * Test if a node is a `HasExpressionInitializer`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasExpressionInitializer(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasExpressionInitializer`. + */ +declare function hasExpressionInitializer(node: ts.Node): node is ts.HasExpressionInitializer; +/** + * Test if a node is a `HasInitializer`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasInitializer(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasInitializer`. + */ +declare function hasInitializer(node: ts.Node): node is ts.HasInitializer; +/** + * Test if a node is a `HasJSDoc`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasJSDoc(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasJSDoc`. + */ +declare function hasJSDoc(node: ts.Node): node is ts.HasJSDoc; +/** + * Test if a node is a `HasModifiers`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasModifiers(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasModifiers`. + */ +declare function hasModifiers(node: ts.Node): node is ts.HasModifiers; +/** + * Test if a node is a `HasType`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasType(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasType`. + */ +declare function hasType(node: ts.Node): node is ts.HasType; +/** + * Test if a node is a `HasTypeArguments`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasTypeArguments(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasTypeArguments`. + */ +declare function hasTypeArguments(node: ts.Node): node is ts.HasTypeArguments; +/** + * Test if a node is an `AccessExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAccessExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AccessExpression`. + */ +declare function isAccessExpression(node: ts.Node): node is ts.AccessExpression; +/** + * Test if a node is an `AccessibilityModifier`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAccessibilityModifier(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AccessibilityModifier`. + */ +declare function isAccessibilityModifier(node: ts.Node): node is ts.AccessibilityModifier; +/** + * Test if a node is an `AccessorDeclaration`. + * @deprecated With TypeScript v5, in favor of typescript's `isAccessor`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAccessorDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AccessorDeclaration`. + */ +declare function isAccessorDeclaration(node: ts.Node): node is ts.AccessorDeclaration; +/** + * Test if a node is an `ArrayBindingElement`. + * @deprecated With TypeScript v5, in favor of typescript's `isArrayBindingElement`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isArrayBindingElement(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ArrayBindingElement`. + */ +declare function isArrayBindingElement(node: ts.Node): node is ts.ArrayBindingElement; +/** + * Test if a node is an `ArrayBindingOrAssignmentPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isArrayBindingOrAssignmentPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ArrayBindingOrAssignmentPattern`. + */ +declare function isArrayBindingOrAssignmentPattern(node: ts.Node): node is ts.ArrayBindingOrAssignmentPattern; +/** + * Test if a node is an `AssignmentPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAssignmentPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AssignmentPattern`. + */ +declare function isAssignmentPattern(node: ts.Node): node is ts.AssignmentPattern; +/** + * Test if a node is a `BindingOrAssignmentElementRestIndicator`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBindingOrAssignmentElementRestIndicator(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BindingOrAssignmentElementRestIndicator`. + */ +declare function isBindingOrAssignmentElementRestIndicator(node: ts.Node): node is ts.BindingOrAssignmentElementRestIndicator; +/** + * Test if a node is a `BindingOrAssignmentElementTarget`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBindingOrAssignmentElementTarget(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BindingOrAssignmentElementTarget`. + */ +declare function isBindingOrAssignmentElementTarget(node: ts.Node): node is ts.BindingOrAssignmentElementTarget; +/** + * Test if a node is a `BindingOrAssignmentPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBindingOrAssignmentPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BindingOrAssignmentPattern`. + */ +declare function isBindingOrAssignmentPattern(node: ts.Node): node is ts.BindingOrAssignmentPattern; +/** + * Test if a node is a `BindingPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBindingPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BindingPattern`. + */ +declare function isBindingPattern(node: ts.Node): node is ts.BindingPattern; +/** + * Test if a node is a `BlockLike`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBlockLike(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BlockLike`. + */ +declare function isBlockLike(node: ts.Node): node is ts.BlockLike; +/** + * Test if a node is a `BooleanLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBooleanLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BooleanLiteral`. + */ +declare function isBooleanLiteral(node: ts.Node): node is ts.BooleanLiteral; +/** + * Test if a node is a `ClassLikeDeclaration`. + * @deprecated With TypeScript v5, in favor of typescript's `isClassLike`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isClassLikeDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ClassLikeDeclaration`. + */ +declare function isClassLikeDeclaration(node: ts.Node): node is ts.ClassLikeDeclaration; +/** + * Test if a node is a `ClassMemberModifier`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isClassMemberModifier(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ClassMemberModifier`. + */ +declare function isClassMemberModifier(node: ts.Node): node is ts.ClassMemberModifier; +/** + * Test if a node is a `DeclarationName`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDeclarationName(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DeclarationName`. + */ +declare function isDeclarationName(node: ts.Node): node is ts.DeclarationName; +/** + * Test if a node is a `DeclarationWithTypeParameterChildren`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDeclarationWithTypeParameterChildren(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DeclarationWithTypeParameterChildren`. + */ +declare function isDeclarationWithTypeParameterChildren(node: ts.Node): node is ts.DeclarationWithTypeParameterChildren; +/** + * Test if a node is a `DeclarationWithTypeParameters`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDeclarationWithTypeParameters(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DeclarationWithTypeParameters`. + */ +declare function isDeclarationWithTypeParameters(node: ts.Node): node is ts.DeclarationWithTypeParameters; +/** + * Test if a node is a `DestructuringPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDestructuringPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DestructuringPattern`. + */ +declare function isDestructuringPattern(node: ts.Node): node is ts.DestructuringPattern; +/** + * Test if a node is an `EntityNameExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEntityNameExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EntityNameExpression`. + */ +declare function isEntityNameExpression(node: ts.Node): node is ts.EntityNameExpression; +/** + * Test if a node is an `EntityNameOrEntityNameExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEntityNameOrEntityNameExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EntityNameOrEntityNameExpression`. + */ +declare function isEntityNameOrEntityNameExpression(node: ts.Node): node is ts.EntityNameOrEntityNameExpression; +/** + * Test if a node is a `ForInOrOfStatement`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isForInOrOfStatement(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ForInOrOfStatement`. + */ +declare function isForInOrOfStatement(node: ts.Node): node is ts.ForInOrOfStatement; +/** + * Test if a node is a `FunctionLikeDeclaration`. + * @deprecated With TypeScript v5, in favor of typescript's `isFunctionLike`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isFunctionLikeDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `FunctionLikeDeclaration`. + */ +declare function isFunctionLikeDeclaration(node: ts.Node): node is ts.FunctionLikeDeclaration; +/** + * Test if a node is a `JSDocComment`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocComment(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocComment`. + */ +declare function isJSDocComment(node: ts.Node): node is ts.JSDocComment; +/** + * Test if a node is a `JSDocNamespaceBody`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocNamespaceBody(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocNamespaceBody`. + */ +declare function isJSDocNamespaceBody(node: ts.Node): node is ts.JSDocNamespaceBody; +/** + * Test if a node is a `JSDocTypeReferencingNode`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocTypeReferencingNode(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocTypeReferencingNode`. + */ +declare function isJSDocTypeReferencingNode(node: ts.Node): node is ts.JSDocTypeReferencingNode; +/** + * Test if a node is a `JsonObjectExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsonObjectExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsonObjectExpression`. + */ +declare function isJsonObjectExpression(node: ts.Node): node is ts.JsonObjectExpression; +/** + * Test if a node is a `JsxAttributeLike`. + * @deprecated With TypeScript v5, in favor of typescript's `isJsxAttributeLike`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxAttributeLike(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxAttributeLike`. + */ +declare function isJsxAttributeLike(node: ts.Node): node is ts.JsxAttributeLike; +/** + * Test if a node is a `JsxAttributeValue`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxAttributeValue(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxAttributeValue`. + */ +declare function isJsxAttributeValue(node: ts.Node): node is ts.JsxAttributeValue; +/** + * Test if a node is a `JsxChild`. + * @deprecated With TypeScript v5, in favor of typescript's `isJsxChild`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxChild(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxChild`. + */ +declare function isJsxChild(node: ts.Node): node is ts.JsxChild; +/** + * Test if a node is a `JsxTagNameExpression`. + * @deprecated With TypeScript v5, in favor of typescript's `isJsxTagNameExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxTagNameExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxTagNameExpression`. + */ +declare function isJsxTagNameExpression(node: ts.Node): node is ts.JsxTagNameExpression; +/** + * Test if a node is a `LiteralToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isLiteralToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `LiteralToken`. + */ +declare function isLiteralToken(node: ts.Node): node is ts.LiteralToken; +/** + * Test if a node is a `ModuleBody`. + * @deprecated With TypeScript v5, in favor of typescript's `isModuleBody`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isModuleBody(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ModuleBody`. + */ +declare function isModuleBody(node: ts.Node): node is ts.ModuleBody; +/** + * Test if a node is a `ModuleName`. + * @deprecated With TypeScript v5, in favor of typescript's `isModuleName`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isModuleName(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ModuleName`. + */ +declare function isModuleName(node: ts.Node): node is ts.ModuleName; +/** + * Test if a node is a `ModuleReference`. + * @deprecated With TypeScript v5, in favor of typescript's `isModuleReference`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isModuleReference(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ModuleReference`. + */ +declare function isModuleReference(node: ts.Node): node is ts.ModuleReference; +/** + * Test if a node is a `NamedImportBindings`. + * @deprecated With TypeScript v5, in favor of typescript's `isNamedImportBindings`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamedImportBindings(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NamedImportBindings`. + */ +declare function isNamedImportBindings(node: ts.Node): node is ts.NamedImportBindings; +/** + * Test if a node is a `NamedImportsOrExports`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamedImportsOrExports(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NamedImportsOrExports`. + */ +declare function isNamedImportsOrExports(node: ts.Node): node is ts.NamedImportsOrExports; +/** + * Test if a node is a `NamespaceBody`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamespaceBody(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NamespaceBody`. + */ +declare function isNamespaceBody(node: ts.Node): node is ts.NamespaceBody; +/** + * Test if a node is an `ObjectBindingOrAssignmentElement`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectBindingOrAssignmentElement(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ObjectBindingOrAssignmentElement`. + */ +declare function isObjectBindingOrAssignmentElement(node: ts.Node): node is ts.ObjectBindingOrAssignmentElement; +/** + * Test if a node is an `ObjectBindingOrAssignmentPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectBindingOrAssignmentPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ObjectBindingOrAssignmentPattern`. + */ +declare function isObjectBindingOrAssignmentPattern(node: ts.Node): node is ts.ObjectBindingOrAssignmentPattern; +/** + * Test if a node is an `ObjectTypeDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectTypeDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ObjectTypeDeclaration`. + */ +declare function isObjectTypeDeclaration(node: ts.Node): node is ts.ObjectTypeDeclaration; +/** + * Test if a node is a `ParameterPropertyModifier`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isParameterPropertyModifier(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ParameterPropertyModifier`. + */ +declare function isParameterPropertyModifier(node: ts.Node): node is ts.ParameterPropertyModifier; +/** + * Test if a node is a `PropertyNameLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPropertyNameLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PropertyNameLiteral`. + */ +declare function isPropertyNameLiteral(node: ts.Node): node is ts.PropertyNameLiteral; +/** + * Test if a node is a `PseudoLiteralToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPseudoLiteralToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PseudoLiteralToken`. + */ +declare function isPseudoLiteralToken(node: ts.Node): node is ts.PseudoLiteralToken; +/** + * Test if a node is a `SignatureDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSignatureDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SignatureDeclaration`. + */ +declare function isSignatureDeclaration(node: ts.Node): node is ts.SignatureDeclaration; +/** + * Test if a node is a `SuperProperty`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperProperty(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SuperProperty`. + */ +declare function isSuperProperty(node: ts.Node): node is ts.SuperProperty; +/** + * Test if a node is a `TypeOnlyCompatibleAliasDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isTypeOnlyCompatibleAliasDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `TypeOnlyCompatibleAliasDeclaration`. + */ +declare function isTypeOnlyCompatibleAliasDeclaration(node: ts.Node): node is ts.TypeOnlyCompatibleAliasDeclaration; +/** + * Test if a node is a `TypeReferenceType`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isTypeReferenceType(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `TypeReferenceType`. + */ +declare function isTypeReferenceType(node: ts.Node): node is ts.TypeReferenceType; +/** + * Test if a node is an `UnionOrIntersectionTypeNode`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isUnionOrIntersectionTypeNode(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `UnionOrIntersectionTypeNode`. + */ +declare function isUnionOrIntersectionTypeNode(node: ts.Node): node is ts.UnionOrIntersectionTypeNode; +/** + * Test if a node is a `VariableLikeDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isVariableLikeDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `VariableLikeDeclaration`. + */ +declare function isVariableLikeDeclaration(node: ts.Node): node is ts.VariableLikeDeclaration; + +/** + * Is the node a scope boundary, specifically due to it being a function. + * @category Scope Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isFunctionScopeBoundary(node, ts.ObjectFlags.Anonymous)) { + * // ... + * } + * ``` + */ +declare function isFunctionScopeBoundary(node: ts.Node): boolean; + +/** + * Test of the kind given is for assignment. + * @category Syntax Utilities + * @example + * ```ts + * declare const kind: ts.SyntaxKind; + * + * isAssignmentKind(kind); + * ``` + */ +declare function isAssignmentKind(kind: ts.SyntaxKind): boolean; +/** + * Test if a string is numeric. + * @category Syntax Utilities + * @example + * ```ts + * isNumericPropertyName("abc"); // false + * isNumericPropertyName("123"); // true + * ``` + */ +declare function isNumericPropertyName(name: string | ts.__String): boolean; +/** + * Determines whether the given text can be used to access a property with a `PropertyAccessExpression` while preserving the property's name. + * @category Syntax Utilities + * @example + * ```ts + * isValidPropertyAccess("abc"); // true + * isValidPropertyAccess("123"); // false + * ``` + */ +declare function isValidPropertyAccess(text: string, languageVersion?: ts.ScriptTarget): boolean; + +/** + * Callback type used for {@link forEachToken}. + * @category Callbacks + * @example + * ```ts + * let onToken: ForEachTokenCallback = (token) => { + * console.log(`Found token at position: ${token.pos}.`); + * }; + * ``` + */ +type ForEachTokenCallback = (token: ts.Node) => void; +/** + * Iterates over all tokens of `node` + * @category Nodes - Other Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * forEachToken(node, (token) => { + * console.log("Found token:", token.getText()); + * }); + * ``` + * @param node The node whose tokens should be visited + * @param callback Is called for every token contained in `node` + */ +declare function forEachToken(node: ts.Node, callback: ForEachTokenCallback, sourceFile?: ts.SourceFile): void; + +/** + * Get the `CallSignatures` of the given type. + * @category Types - Getters + * @example + * ```ts + * declare const type: ts.Type; + * + * getCallSignaturesOfType(type); + * ``` + */ +declare function getCallSignaturesOfType(type: ts.Type): readonly ts.Signature[]; +/** + * Get the property with the given name on the given type (if it exists). + * @category Types - Getters + * @example + * ```ts + * declare const property: ts.Symbol; + * declare const type: ts.Type; + * + * getPropertyOfType(type, property.getEscapedName()); + * ``` + */ +declare function getPropertyOfType(type: ts.Type, name: ts.__String): ts.Symbol | undefined; +/** + * Retrieves a type symbol corresponding to a well-known string name. + * @category Types - Getters + * @example + * ```ts + * declare const type: ts.Type; + * declare const typeChecker: ts.TypeChecker; + * + * getWellKnownSymbolPropertyOfType(type, "asyncIterator", typeChecker); + * ``` + */ +declare function getWellKnownSymbolPropertyOfType(type: ts.Type, wellKnownSymbolName: string, typeChecker: ts.TypeChecker): ts.Symbol | undefined; + +/** + * A "any" intrinsic type. + * @category Type Types + */ +interface IntrinsicAnyType extends IntrinsicType { + intrinsicName: "any"; +} +/** + * A "bigint" intrinsic type. + * @category Type Types + */ +interface IntrinsicBigIntType extends IntrinsicType { + intrinsicName: "bigint"; +} +/** + * A "boolean" intrinsic type. + * @category Type Types + */ +interface IntrinsicBooleanType extends IntrinsicType { + intrinsicName: "boolean"; +} +/** + * An "error" intrinsic type. + * + * This refers to a type generated when TypeScript encounters an error while + * trying to resolve the type. + * @category Type Types + */ +interface IntrinsicErrorType extends IntrinsicType { + intrinsicName: "error"; +} +/** + * A "symbol" intrinsic type. + * @category Type Types + */ +interface IntrinsicESSymbolType extends IntrinsicType { + intrinsicName: "symbol"; +} +/** + * An "intrinsic" (built-in to TypeScript) type. + * @category Type Types + */ +interface IntrinsicType extends ts.Type { + intrinsicName: string; + objectFlags: ts.ObjectFlags; +} +/** + * Determines whether the given type is the "any" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicAnyType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicAnyType(type: ts.Type): type is IntrinsicAnyType; +/** + * Determines whether the given type is the "bigint" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicBigIntType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicBigIntType(type: ts.Type): type is IntrinsicBigIntType; +/** + * Determines whether the given type is the "boolean" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicBooleanType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicBooleanType(type: ts.Type): type is IntrinsicBooleanType; +/** + * Determines whether the given type is the "error" intrinsic type. + * + * The intrinsic error type occurs when TypeScript encounters an error while + * trying to resolve the type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicErrorType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicErrorType(type: ts.Type): type is IntrinsicErrorType; +/** + * Determines whether the given type is the "symbol" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicESSymbolType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicESSymbolType(type: ts.Type): type is IntrinsicESSymbolType; +/** + * A "never" intrinsic type. + * @category Type Types + */ +interface IntrinsicNeverType extends IntrinsicType { + intrinsicName: "never"; +} +/** + * A non-primitive intrinsic type. + * E.g. An "object" intrinsic type. + * @category Type Types + */ +interface IntrinsicNonPrimitiveType extends IntrinsicType { + intrinsicName: ""; +} +/** + * A "null" intrinsic type. + * @category Type Types + */ +interface IntrinsicNullType extends IntrinsicType { + intrinsicName: "null"; +} +/** + * A "number" intrinsic type. + * @category Type Types + */ +interface IntrinsicNumberType extends IntrinsicType { + intrinsicName: "number"; +} +/** + * A "string" intrinsic type. + * @category Type Types + */ +interface IntrinsicStringType extends IntrinsicType { + intrinsicName: "string"; +} +/** + * The built-in `undefined` type. + * @category Type Types + */ +interface IntrinsicUndefinedType extends IntrinsicType { + intrinsicName: "undefined"; +} +/** + * The built-in `unknown` type. + * @category Type Types + */ +interface IntrinsicUnknownType extends IntrinsicType { + intrinsicName: "unknown"; +} +/** + * A "void" intrinsic type. + * @category Type Types + */ +interface IntrinsicVoidType extends IntrinsicType { + intrinsicName: "void"; +} +/** + * Determines whether the given type is the "never" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicNeverType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicNeverType(type: ts.Type): type is IntrinsicNeverType; +/** + * Determines whether the given type is a non-primitive intrinsic type. + * E.g. An "object" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicNonPrimitiveType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicNonPrimitiveType(type: ts.Type): type is IntrinsicNonPrimitiveType; +/** + * Determines whether the given type is the "null" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicNullType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicNullType(type: ts.Type): type is IntrinsicNullType; +/** + * Determines whether the given type is the "number" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicNumberType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicNumberType(type: ts.Type): type is IntrinsicNumberType; +/** + * Determines whether the given type is the "string" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicStringType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicStringType(type: ts.Type): type is IntrinsicStringType; +/** + * Test if a type is an {@link IntrinsicType}. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicType(type: ts.Type): type is IntrinsicType; +/** + * Determines whether the given type is the "undefined" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicUndefinedType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicUndefinedType(type: ts.Type): type is IntrinsicUndefinedType; +/** + * Determines whether the given type is the "unknown" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicUnknownType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicUnknownType(type: ts.Type): type is IntrinsicUnknownType; +/** + * Determines whether the given type is the "void" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicVoidType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicVoidType(type: ts.Type): type is IntrinsicVoidType; + +/** + * A type that is both an {@link IntrinsicType} and a `FreshableType` + * @category Type Types + */ +interface FreshableIntrinsicType extends ts.FreshableType, IntrinsicType { +} +/** + * Test if a type is a `FreshableIntrinsicType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isFreshableIntrinsicType(type)) { + * // ... + * } + */ +declare function isFreshableIntrinsicType(type: ts.Type): type is FreshableIntrinsicType; +/** + * Test if a type is a `TupleTypeReference`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTupleTypeReference(type)) { + * // ... + * } + */ +declare function isTupleTypeReference(type: ts.Type): type is ts.TupleTypeReference; + +/** + * A boolean literal. + * i.e. Either a "true" or "false" literal. + * @category Type Types + */ +interface BooleanLiteralType extends FreshableIntrinsicType { + intrinsicName: "false" | "true"; +} +/** + * A "false" literal. + * @category Type Types + */ +interface FalseLiteralType extends BooleanLiteralType { + intrinsicName: "false"; +} +/** + * A "true" literal. + * @category Type Types + */ +interface TrueLiteralType extends BooleanLiteralType { + intrinsicName: "true"; +} +/** + * `LiteralType` from typescript except that it allows for it to work on arbitrary types. + * @deprecated Use {@link FreshableIntrinsicType} instead. + * @category Type Types + */ +interface UnknownLiteralType extends FreshableIntrinsicType { + value?: unknown; +} +/** + * Test if a type is a `BigIntLiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isBigIntLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isBigIntLiteralType(type: ts.Type): type is ts.BigIntLiteralType; +/** + * Determines whether the given type is a boolean literal type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isBooleanLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isBooleanLiteralType(type: ts.Type): type is BooleanLiteralType; +/** + * Determines whether the given type is a boolean literal type for "false". + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isFalseLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isFalseLiteralType(type: ts.Type): type is FalseLiteralType; +/** + * Test if a type is a `LiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isLiteralType(type: ts.Type): type is ts.LiteralType; +/** + * Test if a type is a `NumberLiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isNumberLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isNumberLiteralType(type: ts.Type): type is ts.NumberLiteralType; +/** + * Test if a type is a `StringLiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isStringLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isStringLiteralType(type: ts.Type): type is ts.StringLiteralType; +/** + * Test if a type is a `TemplateLiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTemplateLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isTemplateLiteralType(type: ts.Type): type is ts.TemplateLiteralType; +/** + * Determines whether the given type is a boolean literal type for "true". + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTrueLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isTrueLiteralType(type: ts.Type): type is TrueLiteralType; + +/** + * Test if a type is a `EvolvingArrayType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isEvolvingArrayType(type)) { + * // ... + * } + * ``` + */ +declare function isEvolvingArrayType(type: ts.Type): type is ts.EvolvingArrayType; +/** + * Test if a type is a `TupleType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTupleType(type)) { + * // ... + * } + * ``` + */ +declare function isTupleType(type: ts.Type): type is ts.TupleType; +/** + * Test if a type is a `TypeReference`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTypeReference(type)) { + * // ... + * } + * ``` + */ +declare function isTypeReference(type: ts.Type): type is ts.TypeReference; + +/** + * Test if a type is a `ConditionalType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isConditionalType(type)) { + * // ... + * } + * ``` + */ +declare function isConditionalType(type: ts.Type): type is ts.ConditionalType; +/** + * Test if a type is a `EnumType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isEnumType(type)) { + * // ... + * } + * ``` + */ +declare function isEnumType(type: ts.Type): type is ts.EnumType; +/** + * Test if a type is a `FreshableType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isFreshableType(type)) { + * // ... + * } + * ``` + */ +declare function isFreshableType(type: ts.Type): type is ts.FreshableType; +/** + * Test if a type is a `IndexedAccessType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIndexedAccessType(type)) { + * // ... + * } + * ``` + */ +declare function isIndexedAccessType(type: ts.Type): type is ts.IndexedAccessType; +/** + * Test if a type is a `IndexType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIndexType(type)) { + * // ... + * } + * ``` + */ +declare function isIndexType(type: ts.Type): type is ts.IndexType; +/** + * Test if a type is a `InstantiableType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isInstantiableType(type)) { + * // ... + * } + * ``` + */ +declare function isInstantiableType(type: ts.Type): type is ts.InstantiableType; +/** + * Test if a type is a `IntersectionType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntersectionType(type)) { + * // ... + * } + * ``` + */ +declare function isIntersectionType(type: ts.Type): type is ts.IntersectionType; +/** + * Test if a type is a `ObjectType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isObjectType(type)) { + * // ... + * } + * ``` + */ +declare function isObjectType(type: ts.Type): type is ts.ObjectType; +/** + * Test if a type is a `StringMappingType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isStringMappingType(type)) { + * // ... + * } + * ``` + */ +declare function isStringMappingType(type: ts.Type): type is ts.StringMappingType; +/** + * Test if a type is a `SubstitutionType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isSubstitutionType(type)) { + * // ... + * } + * ``` + */ +declare function isSubstitutionType(type: ts.Type): type is ts.SubstitutionType; +/** + * Test if a type is a `TypeParameter`. + * + * Note: It is intentional that this is not a type guard. + * @see https://github.com/JoshuaKGoldberg/ts-api-utils/issues/382 + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTypeParameter(type)) { + * // ... + * } + * ``` + */ +declare function isTypeParameter(type: ts.Type): boolean; +/** + * Test if a type is a `TypeVariable`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTypeVariable(type)) { + * // ... + * } + * ``` + */ +declare function isTypeVariable(type: ts.Type): type is ts.TypeVariable; +/** + * Test if a type is a `UnionOrIntersectionType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isUnionOrIntersectionType(type)) { + * // ... + * } + * ``` + */ +declare function isUnionOrIntersectionType(type: ts.Type): type is ts.UnionOrIntersectionType; +/** + * Test if a type is a `UnionType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isUnionType(type)) { + * // ... + * } + * ``` + */ +declare function isUnionType(type: ts.Type): type is ts.UnionType; +/** + * Test if a type is a `UniqueESSymbolType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isUniqueESSymbolType(type)) { + * // ... + * } + * ``` + */ +declare function isUniqueESSymbolType(type: ts.Type): type is ts.UniqueESSymbolType; + +/** + * Get the intersection type parts of the given type. + * + * If the given type is not a intersection type, an array contain only that type will be returned. + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * for (const constituent of intersectionConstituents(type)) { + * // ... + * } + * ``` + */ +declare function intersectionConstituents(type: ts.Type): ts.Type[]; +/** + * @deprecated Use {@link intersectionConstituents} instead. + * @category Types - Utilities + * ``` + */ +declare const intersectionTypeParts: typeof intersectionConstituents; +/** + * Determines whether a type is definitely falsy. This function doesn't unwrap union types. + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isFalsyType(type)) { + * // ... + * } + * ``` + */ +declare function isFalsyType(type: ts.Type): boolean; +/** + * Determines whether writing to a certain property of a given type is allowed. + * @category Types - Utilities + * @example + * ```ts + * declare const property: ts.Symbol; + * declare const type: ts.Type; + * declare const typeChecker: ts.TypeChecker; + * + * if (isPropertyReadonlyInType(type, property.getEscapedName(), typeChecker)) { + * // ... + * } + * ``` + */ +declare function isPropertyReadonlyInType(type: ts.Type, name: ts.__String, typeChecker: ts.TypeChecker): boolean; +/** + * Determines whether a type is thenable and thus can be used with `await`. + * @category Types - Utilities + * @example + * ```ts + * declare const node: ts.Node; + * declare const type: ts.Type; + * declare const typeChecker: ts.TypeChecker; + * + * if (isThenableType(typeChecker, node, type)) { + * // ... + * } + * ``` + */ +declare function isThenableType(typeChecker: ts.TypeChecker, node: ts.Node, type: ts.Type): boolean; +/** + * Determines whether a type is thenable and thus can be used with `await`. + * @category Types - Utilities + * @example + * ```ts + * declare const expression: ts.Expression; + * declare const typeChecker: ts.TypeChecker; + * + * if (isThenableType(typeChecker, expression)) { + * // ... + * } + * ``` + * @example + * ```ts + * declare const expression: ts.Expression; + * declare const typeChecker: ts.TypeChecker; + * declare const type: ts.Type; + * + * if (isThenableType(typeChecker, expression, type)) { + * // ... + * } + * ``` + */ +declare function isThenableType(typeChecker: ts.TypeChecker, node: ts.Expression, type?: ts.Type): boolean; +/** + * Test if the given symbol has a readonly declaration. + * @category Symbols - Utilities + * @example + * ```ts + * declare const symbol: ts.Symbol; + * declare const typeChecker: ts.TypeChecker; + * + * if (symbolHasReadonlyDeclaration(symbol, typeChecker)) { + * // ... + * } + * ``` + */ +declare function symbolHasReadonlyDeclaration(symbol: ts.Symbol, typeChecker: ts.TypeChecker): boolean; +/** + * Get the intersection or union type parts of the given type. + * + * Note that this is a shallow collection: it only returns `type.types` or `[type]`. + * + * If the given type is not an intersection or union type, an array contain only that type will be returned. + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * for (const constituent of typeConstituents(type)) { + * // ... + * } + * ``` + */ +declare function typeConstituents(type: ts.Type): ts.Type[]; +/** + * TS's `type.isLiteral()` is bugged before TS v5.0 and won't return `true` for + * bigint literals. Use this function instead if you need to check for bigint + * literals in TS versions before v5.0. Otherwise, you should just use + * `type.isLiteral()`. + * @see https://github.com/microsoft/TypeScript/pull/50929 + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * if (typeIsLiteral(type)) { + * // ... + * } + * ``` + */ +declare function typeIsLiteral(type: ts.Type): type is ts.LiteralType; +/** + * @deprecated Use {@link typeConstituents} instead. + * @category Types - Utilities + */ +declare const typeParts: typeof typeConstituents; +/** + * Get the union type parts of the given type. + * + * If the given type is not a union type, an array contain only that type will be returned. + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * for (const constituent of unionConstituents(type)) { + * // ... + * } + * ``` + */ +declare function unionConstituents(type: ts.Type): ts.Type[]; +/** + * @deprecated Use {@link unionConstituents} instead. + * @category Types - Utilities + */ +declare const unionTypeParts: typeof unionConstituents; + +/** + * Which "domain"(s) (most commonly, type or value space) a declaration is within. + */ +declare enum DeclarationDomain { + Namespace = 1, + Type = 2, + Value = 4, + Any = 7, + Import = 8 +} + +/** + * Which "domain"(s) (most commonly, type or value space) a usage is within. + */ +declare enum UsageDomain { + Namespace = 1, + Type = 2, + Value = 4, + Any = 7, + TypeQuery = 8, + ValueOrNamespace = 5 +} + +/** + * An instance of an item (type or value) being used. + */ +interface Usage { + /** + * Which space(s) the usage is within. + */ + domain: UsageDomain; + location: ts.Identifier; +} +/** + * How an item (type or value) was declared and/or referenced. + */ +interface UsageInfo { + /** + * Locations where the item was declared. + */ + declarations: ts.Identifier[]; + /** + * Which space(s) the item is within. + */ + domain: DeclarationDomain; + /** + * Whether the item was exported from its module or namespace scope. + */ + exported: boolean; + /** + * Whether the item's declaration was in the global scope. + */ + inGlobalScope: boolean; + /** + * Each reference to the item in the file. + */ + uses: Usage[]; +} + +/** + * Creates a mapping of each declared type and value to its type information. + * @category Nodes - Other Utilities + * @example + * ```ts + * declare const sourceFile: ts.SourceFile; + * + * const usage = collectVariableUsage(sourceFile); + * + * for (const [identifier, information] of usage) { + * console.log(`${identifier.getText()} is used ${information.uses.length} time(s).`); + * } + * ``` + */ +declare function collectVariableUsage(sourceFile: ts.SourceFile): Map; + +export { AccessKind, type AnyKeyword, type BigIntKeyword, type BooleanCompilerOptions, type BooleanKeyword, type BooleanLiteralType, type ConstAssertionExpression, type ConstAssertionIdentifier, DeclarationDomain, type FalseKeyword, type FalseLiteralType, type ForEachCommentCallback, type ForEachTokenCallback, type FreshableIntrinsicType, type ImportKeyword, type IntrinsicAnyType, type IntrinsicBigIntType, type IntrinsicBooleanType, type IntrinsicESSymbolType, type IntrinsicErrorType, type IntrinsicNeverType, type IntrinsicNonPrimitiveType, type IntrinsicNullType, type IntrinsicNumberType, type IntrinsicStringType, type IntrinsicType, type IntrinsicUndefinedType, type IntrinsicUnknownType, type IntrinsicVoidType, type NamedDeclarationWithName, type NeverKeyword, type NullKeyword, type NumberKeyword, type NumericOrStringLikeLiteral, type ObjectKeyword, type StrictCompilerOption, type StringKeyword, type SuperKeyword, type SymbolKeyword, type ThisKeyword, type TrueKeyword, type TrueLiteralType, type UndefinedKeyword, type UnknownKeyword, type UnknownLiteralType, UsageDomain, type UsageInfo as VariableInfo, type Usage as VariableUse, type VoidKeyword, collectVariableUsage, forEachComment, forEachToken, getAccessKind, getCallSignaturesOfType, getPropertyOfType, getWellKnownSymbolPropertyOfType, hasDecorators, hasExpressionInitializer, hasInitializer, hasJSDoc, hasModifiers, hasType, hasTypeArguments, includesModifier, intersectionConstituents, intersectionTypeParts, isAbstractKeyword, isAccessExpression, isAccessibilityModifier, isAccessorDeclaration, isAccessorKeyword, isAnyKeyword, isArrayBindingElement, isArrayBindingOrAssignmentPattern, isAssertKeyword, isAssertsKeyword, isAssignmentKind, isAssignmentPattern, isAsyncKeyword, isAwaitKeyword, isBigIntKeyword, isBigIntLiteralType, isBindingOrAssignmentElementRestIndicator, isBindingOrAssignmentElementTarget, isBindingOrAssignmentPattern, isBindingPattern, isBlockLike, isBooleanKeyword, isBooleanLiteral, isBooleanLiteralType, isClassLikeDeclaration, isClassMemberModifier, isColonToken, isCompilerOptionEnabled, isConditionalType, isConstAssertionExpression, isConstKeyword, isDeclarationName, isDeclarationWithTypeParameterChildren, isDeclarationWithTypeParameters, isDeclareKeyword, isDefaultKeyword, isDestructuringPattern, isDotToken, isEndOfFileToken, isEntityNameExpression, isEntityNameOrEntityNameExpression, isEnumType, isEqualsGreaterThanToken, isEqualsToken, isEvolvingArrayType, isExclamationToken, isExportKeyword, isFalseKeyword, isFalseLiteral, isFalseLiteralType, isFalsyType, isForInOrOfStatement, isFreshableIntrinsicType, isFreshableType, isFunctionLikeDeclaration, isFunctionScopeBoundary, isImportExpression, isImportKeyword, isInKeyword, isIndexType, isIndexedAccessType, isInstantiableType, isIntersectionType, isIntrinsicAnyType, isIntrinsicBigIntType, isIntrinsicBooleanType, isIntrinsicESSymbolType, isIntrinsicErrorType, isIntrinsicNeverType, isIntrinsicNonPrimitiveType, isIntrinsicNullType, isIntrinsicNumberType, isIntrinsicStringType, isIntrinsicType, isIntrinsicUndefinedType, isIntrinsicUnknownType, isIntrinsicVoidType, isIterationStatement, isJSDocComment, isJSDocNamespaceBody, isJSDocNamespaceDeclaration, isJSDocText, isJSDocTypeReferencingNode, isJsonMinusNumericLiteral, isJsonObjectExpression, isJsxAttributeLike, isJsxAttributeValue, isJsxChild, isJsxTagNameExpression, isJsxTagNamePropertyAccess, isLiteralToken, isLiteralType, isModifierFlagSet, isModuleBody, isModuleName, isModuleReference, isNamedDeclarationWithName, isNamedImportBindings, isNamedImportsOrExports, isNamespaceBody, isNamespaceDeclaration, isNeverKeyword, isNodeFlagSet, isNullKeyword, isNullLiteral, isNumberKeyword, isNumberLiteralType, isNumericOrStringLikeLiteral, isNumericPropertyName, isObjectBindingOrAssignmentElement, isObjectBindingOrAssignmentPattern, isObjectFlagSet, isObjectKeyword, isObjectType, isObjectTypeDeclaration, isOutKeyword, isOverrideKeyword, isParameterPropertyModifier, isPrivateKeyword, isPropertyAccessEntityNameExpression, isPropertyNameLiteral, isPropertyReadonlyInType, isProtectedKeyword, isPseudoLiteralToken, isPublicKeyword, isQuestionDotToken, isQuestionToken, isReadonlyKeyword, isSignatureDeclaration, isStaticKeyword, isStrictCompilerOptionEnabled, isStringKeyword, isStringLiteralType, isStringMappingType, isSubstitutionType, isSuperElementAccessExpression, isSuperExpression, isSuperKeyword, isSuperProperty, isSuperPropertyAccessExpression, isSymbolFlagSet, isSymbolKeyword, isSyntaxList, isTemplateLiteralType, isThenableType, isThisExpression, isThisKeyword, isTransientSymbolLinksFlagSet, isTrueKeyword, isTrueLiteral, isTrueLiteralType, isTupleType, isTupleTypeReference, isTypeFlagSet, isTypeOnlyCompatibleAliasDeclaration, isTypeParameter, isTypeReference, isTypeReferenceType, isTypeVariable, isUndefinedKeyword, isUnionOrIntersectionType, isUnionOrIntersectionTypeNode, isUnionType, isUniqueESSymbolType, isUnknownKeyword, isValidPropertyAccess, isVariableLikeDeclaration, isVoidKeyword, symbolHasReadonlyDeclaration, typeConstituents, typeIsLiteral, typeParts, unionConstituents, unionTypeParts }; diff --git a/node_modules/ts-api-utils/lib/index.d.ts b/node_modules/ts-api-utils/lib/index.d.ts new file mode 100644 index 00000000..87946f8c --- /dev/null +++ b/node_modules/ts-api-utils/lib/index.d.ts @@ -0,0 +1,3019 @@ +import ts from 'typescript'; + +/** + * Callback type used for {@link forEachComment}. + * @category Callbacks + * @param fullText Full parsed text of the comment. + * @param comment Text range of the comment in its file. + * @example + * ```ts + * let onComment: ForEachCommentCallback = (fullText, comment) => { + * console.log(`Found comment at position ${comment.pos}: '${fullText}'.`); + * }; + * ``` + */ +type ForEachCommentCallback = (fullText: string, comment: ts.CommentRange) => void; +/** + * Iterates over all comments owned by `node` or its children. + * @category Nodes - Other Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * forEachComment(node, (fullText, comment) => { + * console.log(`Found comment at position ${comment.pos}: '${fullText}'.`); + * }); + * ``` + */ +declare function forEachComment(node: ts.Node, callback: ForEachCommentCallback, sourceFile?: ts.SourceFile): void; + +/** + * An option that can be tested with {@link isCompilerOptionEnabled}. + * @category Compiler Options + */ +type BooleanCompilerOptions = keyof { + [K in keyof ts.CompilerOptions as NonNullable extends boolean ? K : never]: unknown; +}; +/** + * An option that can be tested with {@link isStrictCompilerOptionEnabled}. + * @category Compiler Options + */ +type StrictCompilerOption = "alwaysStrict" | "noImplicitAny" | "noImplicitThis" | "strictBindCallApply" | "strictFunctionTypes" | "strictNullChecks" | "strictPropertyInitialization"; +/** + * Checks if a given compiler option is enabled. + * It handles dependencies of options, e.g. `declaration` is implicitly enabled by `composite` or `strictNullChecks` is enabled by `strict`. + * However, it does not check dependencies that are already checked and reported as errors, e.g. `checkJs` without `allowJs`. + * This function only handles boolean flags. + * @category Compiler Options + * @example + * ```ts + * const options = { + * allowJs: true, + * }; + * + * isCompilerOptionEnabled(options, "allowJs"); // true + * isCompilerOptionEnabled(options, "allowSyntheticDefaultImports"); // false + * ``` + */ +declare function isCompilerOptionEnabled(options: ts.CompilerOptions, option: BooleanCompilerOptions): boolean; +/** + * Checks if a given compiler option is enabled, accounting for whether all flags + * (except `strictPropertyInitialization`) have been enabled by `strict: true`. + * @category Compiler Options + * @example + * ```ts + * const optionsLenient = { + * noImplicitAny: true, + * }; + * + * isStrictCompilerOptionEnabled(optionsLenient, "noImplicitAny"); // true + * isStrictCompilerOptionEnabled(optionsLenient, "noImplicitThis"); // false + * ``` + * @example + * ```ts + * const optionsStrict = { + * noImplicitThis: false, + * strict: true, + * }; + * + * isStrictCompilerOptionEnabled(optionsStrict, "noImplicitAny"); // true + * isStrictCompilerOptionEnabled(optionsStrict, "noImplicitThis"); // false + * ``` + */ +declare function isStrictCompilerOptionEnabled(options: ts.CompilerOptions, option: StrictCompilerOption): boolean; + +/** + * Test if the given node has the given `ModifierFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isModifierFlagSet(node, ts.ModifierFlags.Abstract)) { + * // ... + * } + * ``` + */ +declare function isModifierFlagSet(node: ts.Declaration, flag: ts.ModifierFlags): boolean; +/** + * Test if the given node has the given `NodeFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNodeFlagSet(node, ts.NodeFlags.AwaitContext)) { + * // ... + * } + * ``` + */ +declare const isNodeFlagSet: (node: ts.Node, flag: ts.NodeFlags) => boolean; +/** + * Test if the given node has the given `ObjectFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectFlagSet(node, ts.ObjectFlags.Anonymous)) { + * // ... + * } + * ``` + */ +declare function isObjectFlagSet(objectType: ts.ObjectType, flag: ts.ObjectFlags): boolean; +/** + * Test if the given node has the given `SymbolFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const symbol: ts.Symbol; + * + * if (isSymbolFlagSet(symbol, ts.SymbolFlags.Accessor)) { + * // ... + * } + * ``` + */ +declare const isSymbolFlagSet: (symbol: ts.Symbol, flag: ts.SymbolFlags) => boolean; +/** + * Test if the given symbol's links has the given `CheckFlags` set. + * @internal + */ +declare function isTransientSymbolLinksFlagSet(links: ts.TransientSymbolLinks, flag: ts.CheckFlags): boolean; +/** + * Test if the given node has the given `TypeFlags` set. + * @category Nodes - Flag Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTypeFlagSet(type, ts.TypeFlags.Any)) { + * // ... + * } + * ``` + */ +declare const isTypeFlagSet: (type: ts.Type, flag: ts.TypeFlags) => boolean; + +/** + * Test if the given iterable includes a modifier of any of the given kinds. + * @category Modifier Utilities + * @example + * ```ts + * declare const modifiers: ts.Modifier[]; + * + * includesModifier(modifiers, ts.SyntaxKind.AbstractKeyword); + * ``` + */ +declare function includesModifier(modifiers: Iterable | undefined, ...kinds: ts.ModifierSyntaxKind[]): boolean; + +/** + * What operations(s), if any, an expression applies. + */ +declare enum AccessKind { + None = 0, + Read = 1, + Write = 2, + Delete = 4, + ReadWrite = 3 +} +/** + * Determines which operation(s), if any, an expression applies. + * @example + * ```ts + * declare const node: ts.Expression; + * + * if (getAccessKind(node).Write & AccessKind.Write) !== 0) { + * // this is a reassignment (write) + * } + * ``` + */ +declare function getAccessKind(node: ts.Expression): AccessKind; + +/** + * An `AssertionExpression` that is declared as const. + * @category Node Types + */ +type ConstAssertionExpression = ts.AssertionExpression & { + type: ts.TypeReferenceNode; + typeName: ConstAssertionIdentifier; +}; +/** + * An `Identifier` with an `escapedText` value of `"const"`. + * @category Node Types + */ +type ConstAssertionIdentifier = ts.Identifier & { + escapedText: "const" & ts.__String; +}; +/** + * a `NamedDeclaration` that definitely has a name. + * @category Node Types + */ +interface NamedDeclarationWithName extends ts.NamedDeclaration { + name: ts.DeclarationName; +} +/** + * A number or string-like literal. + * @category Node Types + */ +type NumericOrStringLikeLiteral = ts.NumericLiteral | ts.StringLiteralLike; +/** + * Test if a node is a {@link ConstAssertionExpression}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isConstAssertionExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link ConstAssertionExpression}. + */ +declare function isConstAssertionExpression(node: ts.AssertionExpression): node is ConstAssertionExpression; +/** + * Test if a node is an `IterationStatement`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isIterationStatement(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `IterationStatement`. + */ +declare function isIterationStatement(node: ts.Node): node is ts.IterationStatement; +/** + * Test if a node is a `JSDocNamespaceDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocNamespaceDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocNamespaceDeclaration`. + */ +declare function isJSDocNamespaceDeclaration(node: ts.Node): node is ts.JSDocNamespaceDeclaration; +/** + * Test if a node is a `JsxTagNamePropertyAccess`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxTagNamePropertyAccess(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxTagNamePropertyAccess`. + */ +declare function isJsxTagNamePropertyAccess(node: ts.Node): node is ts.JsxTagNamePropertyAccess; +/** + * Test if a node is a {@link NamedDeclarationWithName}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamedDeclarationWithName(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NamedDeclarationWithName}. + */ +declare function isNamedDeclarationWithName(node: ts.Declaration): node is NamedDeclarationWithName; +/** + * Test if a node is a `NamespaceDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamespaceDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NamespaceDeclaration`. + */ +declare function isNamespaceDeclaration(node: ts.Node): node is ts.NamespaceDeclaration; +/** + * Test if a node is a {@link NumericOrStringLikeLiteral}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNumericOrStringLikeLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NumericOrStringLikeLiteral}. + */ +declare function isNumericOrStringLikeLiteral(node: ts.Node): node is NumericOrStringLikeLiteral; +/** + * Test if a node is a `PropertyAccessEntityNameExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPropertyAccessEntityNameExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PropertyAccessEntityNameExpression`. + */ +declare function isPropertyAccessEntityNameExpression(node: ts.Node): node is ts.PropertyAccessEntityNameExpression; +/** + * Test if a node is a `SuperElementAccessExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperElementAccessExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SuperElementAccessExpression`. + */ +declare function isSuperElementAccessExpression(node: ts.Node): node is ts.SuperElementAccessExpression; +/** + * Test if a node is a `SuperPropertyAccessExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperPropertyAccessExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SuperPropertyAccessExpression`. + */ +declare function isSuperPropertyAccessExpression(node: ts.Node): node is ts.SuperPropertyAccessExpression; + +/** + * A node that represents the any keyword. + * @category Node Types + */ +type AnyKeyword = ts.KeywordToken; +/** + * A node that represents the bigint keyword. + * @category Node Types + */ +type BigIntKeyword = ts.KeywordToken; +/** + * A node that represents the boolean keyword. + * @category Node Types + */ +type BooleanKeyword = ts.KeywordToken; +/** + * A node that represents the false keyword. + * @category Node Types + */ +type FalseKeyword = ts.KeywordToken; +/** + * A node that represents the import keyword. + * @category Node Types + */ +type ImportKeyword = ts.KeywordToken; +/** + * A node that represents the never keyword. + * @category Node Types + */ +type NeverKeyword = ts.KeywordToken; +/** + * A node that represents the null keyword. + * @category Node Types + */ +type NullKeyword = ts.KeywordToken; +/** + * A node that represents the number keyword. + * @category Node Types + */ +type NumberKeyword = ts.KeywordToken; +/** + * A node that represents the object keyword. + * @category Node Types + */ +type ObjectKeyword = ts.KeywordToken; +/** + * A node that represents the string keyword. + * @category Node Types + */ +type StringKeyword = ts.KeywordToken; +/** + * A node that represents the super keyword. + * @category Node Types + */ +type SuperKeyword = ts.KeywordToken; +/** + * A node that represents the symbol keyword. + * @category Node Types + */ +type SymbolKeyword = ts.KeywordToken; +/** + * A node that represents the this keyword. + * @category Node Types + */ +type ThisKeyword = ts.KeywordToken; +/** + * A node that represents the true keyword. + * @category Node Types + */ +type TrueKeyword = ts.KeywordToken; +/** + * A node that represents the undefined keyword. + * @category Node Types + */ +type UndefinedKeyword = ts.KeywordToken; +/** + * A node that represents the unknown keyword. + * @category Node Types + */ +type UnknownKeyword = ts.KeywordToken; +/** + * A node that represents the void keyword. + * @category Node Types + */ +type VoidKeyword = ts.KeywordToken; +/** + * Test if a node is an `AbstractKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAbstractKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AbstractKeyword`. + */ +declare function isAbstractKeyword(node: ts.Node): node is ts.AbstractKeyword; +/** + * Test if a node is an `AccessorKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAccessorKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AccessorKeyword`. + */ +declare function isAccessorKeyword(node: ts.Node): node is ts.AccessorKeyword; +/** + * Test if a node is an {@link AnyKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAnyKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link AnyKeyword}. + */ +declare function isAnyKeyword(node: ts.Node): node is AnyKeyword; +/** + * Test if a node is an `AssertKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAssertKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AssertKeyword`. + */ +declare function isAssertKeyword(node: ts.Node): node is ts.AssertKeyword; +/** + * Test if a node is an `AssertsKeyword`. + * @deprecated With TypeScript v5, in favor of typescript's `isAssertsKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAssertsKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AssertsKeyword`. + */ +declare function isAssertsKeyword(node: ts.Node): node is ts.AssertsKeyword; +/** + * Test if a node is an `AsyncKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAsyncKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AsyncKeyword`. + */ +declare function isAsyncKeyword(node: ts.Node): node is ts.AsyncKeyword; +/** + * Test if a node is an `AwaitKeyword`. + * @deprecated With TypeScript v5, in favor of typescript's `isAwaitKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAwaitKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AwaitKeyword`. + */ +declare function isAwaitKeyword(node: ts.Node): node is ts.AwaitKeyword; +/** + * Test if a node is a {@link BigIntKeyword}. + * @deprecated With TypeScript v5, in favor of typescript's `isBigIntKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBigIntKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link BigIntKeyword}. + */ +declare function isBigIntKeyword(node: ts.Node): node is BigIntKeyword; +/** + * Test if a node is a {@link BooleanKeyword}. + * @deprecated With TypeScript v5, in favor of typescript's `isBooleanKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBooleanKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link BooleanKeyword}. + */ +declare function isBooleanKeyword(node: ts.Node): node is BooleanKeyword; +/** + * Test if a node is a `ColonToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isColonToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isColonToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ColonToken`. + */ +declare function isColonToken(node: ts.Node): node is ts.ColonToken; +/** + * Test if a node is a `ConstKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isConstKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ConstKeyword`. + */ +declare function isConstKeyword(node: ts.Node): node is ts.ConstKeyword; +/** + * Test if a node is a `DeclareKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDeclareKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DeclareKeyword`. + */ +declare function isDeclareKeyword(node: ts.Node): node is ts.DeclareKeyword; +/** + * Test if a node is a `DefaultKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDefaultKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DefaultKeyword`. + */ +declare function isDefaultKeyword(node: ts.Node): node is ts.DefaultKeyword; +/** + * Test if a node is a `DotToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDotToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DotToken`. + */ +declare function isDotToken(node: ts.Node): node is ts.DotToken; +/** + * Test if a node is an `EndOfFileToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEndOfFileToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EndOfFileToken`. + */ +declare function isEndOfFileToken(node: ts.Node): node is ts.EndOfFileToken; +/** + * Test if a node is an `EqualsGreaterThanToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isEqualsGreaterThanToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEqualsGreaterThanToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EqualsGreaterThanToken`. + */ +declare function isEqualsGreaterThanToken(node: ts.Node): node is ts.EqualsGreaterThanToken; +/** + * Test if a node is an `EqualsToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEqualsToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EqualsToken`. + */ +declare function isEqualsToken(node: ts.Node): node is ts.EqualsToken; +/** + * Test if a node is an `ExclamationToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isExclamationToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isExclamationToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ExclamationToken`. + */ +declare function isExclamationToken(node: ts.Node): node is ts.ExclamationToken; +/** + * Test if a node is an `ExportKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isExportKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ExportKeyword`. + */ +declare function isExportKeyword(node: ts.Node): node is ts.ExportKeyword; +/** + * Test if a node is a {@link FalseKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isFalseKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link FalseKeyword}. + */ +declare function isFalseKeyword(node: ts.Node): node is FalseKeyword; +/** + * Test if a node is a `FalseLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isFalseLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `FalseLiteral`. + */ +declare function isFalseLiteral(node: ts.Node): node is ts.FalseLiteral; +/** + * Test if a node is an `ImportExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isImportExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ImportExpression`. + */ +declare function isImportExpression(node: ts.Node): node is ts.ImportExpression; +/** + * Test if a node is an {@link ImportKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isImportKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link ImportKeyword}. + */ +declare function isImportKeyword(node: ts.Node): node is ImportKeyword; +/** + * Test if a node is an `InKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isInKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `InKeyword`. + */ +declare function isInKeyword(node: ts.Node): node is ts.InKeyword; +/** + * Test if a node is a `JSDocText`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocText(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocText`. + */ +declare function isJSDocText(node: ts.Node): node is ts.JSDocText; +/** + * Test if a node is a `JsonMinusNumericLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsonMinusNumericLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsonMinusNumericLiteral`. + */ +declare function isJsonMinusNumericLiteral(node: ts.Node): node is ts.JsonMinusNumericLiteral; +/** + * Test if a node is a {@link NeverKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNeverKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NeverKeyword}. + */ +declare function isNeverKeyword(node: ts.Node): node is NeverKeyword; +/** + * Test if a node is a {@link NullKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNullKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NullKeyword}. + */ +declare function isNullKeyword(node: ts.Node): node is NullKeyword; +/** + * Test if a node is a `NullLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNullLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NullLiteral`. + */ +declare function isNullLiteral(node: ts.Node): node is ts.NullLiteral; +/** + * Test if a node is a {@link NumberKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNumberKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link NumberKeyword}. + */ +declare function isNumberKeyword(node: ts.Node): node is NumberKeyword; +/** + * Test if a node is an {@link ObjectKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link ObjectKeyword}. + */ +declare function isObjectKeyword(node: ts.Node): node is ObjectKeyword; +/** + * Test if a node is an `OutKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isOutKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `OutKeyword`. + */ +declare function isOutKeyword(node: ts.Node): node is ts.OutKeyword; +/** + * Test if a node is an `OverrideKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isOverrideKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `OverrideKeyword`. + */ +declare function isOverrideKeyword(node: ts.Node): node is ts.OverrideKeyword; +/** + * Test if a node is a `PrivateKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPrivateKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PrivateKeyword`. + */ +declare function isPrivateKeyword(node: ts.Node): node is ts.PrivateKeyword; +/** + * Test if a node is a `ProtectedKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isProtectedKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ProtectedKeyword`. + */ +declare function isProtectedKeyword(node: ts.Node): node is ts.ProtectedKeyword; +/** + * Test if a node is a `PublicKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPublicKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PublicKeyword`. + */ +declare function isPublicKeyword(node: ts.Node): node is ts.PublicKeyword; +/** + * Test if a node is a `QuestionDotToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isQuestionDotToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isQuestionDotToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `QuestionDotToken`. + */ +declare function isQuestionDotToken(node: ts.Node): node is ts.QuestionDotToken; +/** + * Test if a node is a `QuestionToken`. + * @deprecated With TypeScript v5, in favor of typescript's `isQuestionToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isQuestionToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `QuestionToken`. + */ +declare function isQuestionToken(node: ts.Node): node is ts.QuestionToken; +/** + * Test if a node is a `ReadonlyKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isReadonlyKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ReadonlyKeyword`. + */ +declare function isReadonlyKeyword(node: ts.Node): node is ts.ReadonlyKeyword; +/** + * Test if a node is a `StaticKeyword`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isStaticKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `StaticKeyword`. + */ +declare function isStaticKeyword(node: ts.Node): node is ts.StaticKeyword; +/** + * Test if a node is a {@link StringKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isStringKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link StringKeyword}. + */ +declare function isStringKeyword(node: ts.Node): node is StringKeyword; +/** + * Test if a node is a `SuperExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SuperExpression`. + */ +declare function isSuperExpression(node: ts.Node): node is ts.SuperExpression; +/** + * Test if a node is a {@link SuperKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link SuperKeyword}. + */ +declare function isSuperKeyword(node: ts.Node): node is SuperKeyword; +/** + * Test if a node is a {@link SymbolKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSymbolKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link SymbolKeyword}. + */ +declare function isSymbolKeyword(node: ts.Node): node is SymbolKeyword; +/** + * Test if a node is a `SyntaxList`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSyntaxList(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SyntaxList`. + */ +declare function isSyntaxList(node: ts.Node): node is ts.SyntaxList; +/** + * Test if a node is a `ThisExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isThisExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ThisExpression`. + */ +declare function isThisExpression(node: ts.Node): node is ts.ThisExpression; +/** + * Test if a node is a {@link ThisKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isThisKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link ThisKeyword}. + */ +declare function isThisKeyword(node: ts.Node): node is ThisKeyword; +/** + * Test if a node is a {@link TrueKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isTrueKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link TrueKeyword}. + */ +declare function isTrueKeyword(node: ts.Node): node is TrueKeyword; +/** + * Test if a node is a `TrueLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isTrueLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `TrueLiteral`. + */ +declare function isTrueLiteral(node: ts.Node): node is ts.TrueLiteral; +/** + * Test if a node is an {@link UndefinedKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isUndefinedKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link UndefinedKeyword}. + */ +declare function isUndefinedKeyword(node: ts.Node): node is UndefinedKeyword; +/** + * Test if a node is an {@link UnknownKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isUnknownKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an {@link UnknownKeyword}. + */ +declare function isUnknownKeyword(node: ts.Node): node is UnknownKeyword; +/** + * Test if a node is a {@link VoidKeyword}. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isVoidKeyword(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a {@link VoidKeyword}. + */ +declare function isVoidKeyword(node: ts.Node): node is VoidKeyword; + +/** + * Test if a node is a `HasDecorators`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasDecorators(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasDecorators`. + */ +declare function hasDecorators(node: ts.Node): node is ts.HasDecorators; +/** + * Test if a node is a `HasExpressionInitializer`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasExpressionInitializer(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasExpressionInitializer`. + */ +declare function hasExpressionInitializer(node: ts.Node): node is ts.HasExpressionInitializer; +/** + * Test if a node is a `HasInitializer`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasInitializer(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasInitializer`. + */ +declare function hasInitializer(node: ts.Node): node is ts.HasInitializer; +/** + * Test if a node is a `HasJSDoc`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasJSDoc(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasJSDoc`. + */ +declare function hasJSDoc(node: ts.Node): node is ts.HasJSDoc; +/** + * Test if a node is a `HasModifiers`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasModifiers(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasModifiers`. + */ +declare function hasModifiers(node: ts.Node): node is ts.HasModifiers; +/** + * Test if a node is a `HasType`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasType(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasType`. + */ +declare function hasType(node: ts.Node): node is ts.HasType; +/** + * Test if a node is a `HasTypeArguments`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (hasTypeArguments(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `HasTypeArguments`. + */ +declare function hasTypeArguments(node: ts.Node): node is ts.HasTypeArguments; +/** + * Test if a node is an `AccessExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAccessExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AccessExpression`. + */ +declare function isAccessExpression(node: ts.Node): node is ts.AccessExpression; +/** + * Test if a node is an `AccessibilityModifier`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAccessibilityModifier(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AccessibilityModifier`. + */ +declare function isAccessibilityModifier(node: ts.Node): node is ts.AccessibilityModifier; +/** + * Test if a node is an `AccessorDeclaration`. + * @deprecated With TypeScript v5, in favor of typescript's `isAccessor`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAccessorDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AccessorDeclaration`. + */ +declare function isAccessorDeclaration(node: ts.Node): node is ts.AccessorDeclaration; +/** + * Test if a node is an `ArrayBindingElement`. + * @deprecated With TypeScript v5, in favor of typescript's `isArrayBindingElement`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isArrayBindingElement(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ArrayBindingElement`. + */ +declare function isArrayBindingElement(node: ts.Node): node is ts.ArrayBindingElement; +/** + * Test if a node is an `ArrayBindingOrAssignmentPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isArrayBindingOrAssignmentPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ArrayBindingOrAssignmentPattern`. + */ +declare function isArrayBindingOrAssignmentPattern(node: ts.Node): node is ts.ArrayBindingOrAssignmentPattern; +/** + * Test if a node is an `AssignmentPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isAssignmentPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `AssignmentPattern`. + */ +declare function isAssignmentPattern(node: ts.Node): node is ts.AssignmentPattern; +/** + * Test if a node is a `BindingOrAssignmentElementRestIndicator`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBindingOrAssignmentElementRestIndicator(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BindingOrAssignmentElementRestIndicator`. + */ +declare function isBindingOrAssignmentElementRestIndicator(node: ts.Node): node is ts.BindingOrAssignmentElementRestIndicator; +/** + * Test if a node is a `BindingOrAssignmentElementTarget`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBindingOrAssignmentElementTarget(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BindingOrAssignmentElementTarget`. + */ +declare function isBindingOrAssignmentElementTarget(node: ts.Node): node is ts.BindingOrAssignmentElementTarget; +/** + * Test if a node is a `BindingOrAssignmentPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBindingOrAssignmentPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BindingOrAssignmentPattern`. + */ +declare function isBindingOrAssignmentPattern(node: ts.Node): node is ts.BindingOrAssignmentPattern; +/** + * Test if a node is a `BindingPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBindingPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BindingPattern`. + */ +declare function isBindingPattern(node: ts.Node): node is ts.BindingPattern; +/** + * Test if a node is a `BlockLike`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBlockLike(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BlockLike`. + */ +declare function isBlockLike(node: ts.Node): node is ts.BlockLike; +/** + * Test if a node is a `BooleanLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isBooleanLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `BooleanLiteral`. + */ +declare function isBooleanLiteral(node: ts.Node): node is ts.BooleanLiteral; +/** + * Test if a node is a `ClassLikeDeclaration`. + * @deprecated With TypeScript v5, in favor of typescript's `isClassLike`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isClassLikeDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ClassLikeDeclaration`. + */ +declare function isClassLikeDeclaration(node: ts.Node): node is ts.ClassLikeDeclaration; +/** + * Test if a node is a `ClassMemberModifier`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isClassMemberModifier(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ClassMemberModifier`. + */ +declare function isClassMemberModifier(node: ts.Node): node is ts.ClassMemberModifier; +/** + * Test if a node is a `DeclarationName`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDeclarationName(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DeclarationName`. + */ +declare function isDeclarationName(node: ts.Node): node is ts.DeclarationName; +/** + * Test if a node is a `DeclarationWithTypeParameterChildren`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDeclarationWithTypeParameterChildren(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DeclarationWithTypeParameterChildren`. + */ +declare function isDeclarationWithTypeParameterChildren(node: ts.Node): node is ts.DeclarationWithTypeParameterChildren; +/** + * Test if a node is a `DeclarationWithTypeParameters`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDeclarationWithTypeParameters(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DeclarationWithTypeParameters`. + */ +declare function isDeclarationWithTypeParameters(node: ts.Node): node is ts.DeclarationWithTypeParameters; +/** + * Test if a node is a `DestructuringPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isDestructuringPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `DestructuringPattern`. + */ +declare function isDestructuringPattern(node: ts.Node): node is ts.DestructuringPattern; +/** + * Test if a node is an `EntityNameExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEntityNameExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EntityNameExpression`. + */ +declare function isEntityNameExpression(node: ts.Node): node is ts.EntityNameExpression; +/** + * Test if a node is an `EntityNameOrEntityNameExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isEntityNameOrEntityNameExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `EntityNameOrEntityNameExpression`. + */ +declare function isEntityNameOrEntityNameExpression(node: ts.Node): node is ts.EntityNameOrEntityNameExpression; +/** + * Test if a node is a `ForInOrOfStatement`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isForInOrOfStatement(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ForInOrOfStatement`. + */ +declare function isForInOrOfStatement(node: ts.Node): node is ts.ForInOrOfStatement; +/** + * Test if a node is a `FunctionLikeDeclaration`. + * @deprecated With TypeScript v5, in favor of typescript's `isFunctionLike`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isFunctionLikeDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `FunctionLikeDeclaration`. + */ +declare function isFunctionLikeDeclaration(node: ts.Node): node is ts.FunctionLikeDeclaration; +/** + * Test if a node is a `JSDocComment`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocComment(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocComment`. + */ +declare function isJSDocComment(node: ts.Node): node is ts.JSDocComment; +/** + * Test if a node is a `JSDocNamespaceBody`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocNamespaceBody(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocNamespaceBody`. + */ +declare function isJSDocNamespaceBody(node: ts.Node): node is ts.JSDocNamespaceBody; +/** + * Test if a node is a `JSDocTypeReferencingNode`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJSDocTypeReferencingNode(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JSDocTypeReferencingNode`. + */ +declare function isJSDocTypeReferencingNode(node: ts.Node): node is ts.JSDocTypeReferencingNode; +/** + * Test if a node is a `JsonObjectExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsonObjectExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsonObjectExpression`. + */ +declare function isJsonObjectExpression(node: ts.Node): node is ts.JsonObjectExpression; +/** + * Test if a node is a `JsxAttributeLike`. + * @deprecated With TypeScript v5, in favor of typescript's `isJsxAttributeLike`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxAttributeLike(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxAttributeLike`. + */ +declare function isJsxAttributeLike(node: ts.Node): node is ts.JsxAttributeLike; +/** + * Test if a node is a `JsxAttributeValue`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxAttributeValue(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxAttributeValue`. + */ +declare function isJsxAttributeValue(node: ts.Node): node is ts.JsxAttributeValue; +/** + * Test if a node is a `JsxChild`. + * @deprecated With TypeScript v5, in favor of typescript's `isJsxChild`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxChild(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxChild`. + */ +declare function isJsxChild(node: ts.Node): node is ts.JsxChild; +/** + * Test if a node is a `JsxTagNameExpression`. + * @deprecated With TypeScript v5, in favor of typescript's `isJsxTagNameExpression`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isJsxTagNameExpression(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `JsxTagNameExpression`. + */ +declare function isJsxTagNameExpression(node: ts.Node): node is ts.JsxTagNameExpression; +/** + * Test if a node is a `LiteralToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isLiteralToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `LiteralToken`. + */ +declare function isLiteralToken(node: ts.Node): node is ts.LiteralToken; +/** + * Test if a node is a `ModuleBody`. + * @deprecated With TypeScript v5, in favor of typescript's `isModuleBody`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isModuleBody(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ModuleBody`. + */ +declare function isModuleBody(node: ts.Node): node is ts.ModuleBody; +/** + * Test if a node is a `ModuleName`. + * @deprecated With TypeScript v5, in favor of typescript's `isModuleName`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isModuleName(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ModuleName`. + */ +declare function isModuleName(node: ts.Node): node is ts.ModuleName; +/** + * Test if a node is a `ModuleReference`. + * @deprecated With TypeScript v5, in favor of typescript's `isModuleReference`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isModuleReference(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ModuleReference`. + */ +declare function isModuleReference(node: ts.Node): node is ts.ModuleReference; +/** + * Test if a node is a `NamedImportBindings`. + * @deprecated With TypeScript v5, in favor of typescript's `isNamedImportBindings`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamedImportBindings(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NamedImportBindings`. + */ +declare function isNamedImportBindings(node: ts.Node): node is ts.NamedImportBindings; +/** + * Test if a node is a `NamedImportsOrExports`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamedImportsOrExports(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NamedImportsOrExports`. + */ +declare function isNamedImportsOrExports(node: ts.Node): node is ts.NamedImportsOrExports; +/** + * Test if a node is a `NamespaceBody`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isNamespaceBody(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `NamespaceBody`. + */ +declare function isNamespaceBody(node: ts.Node): node is ts.NamespaceBody; +/** + * Test if a node is an `ObjectBindingOrAssignmentElement`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectBindingOrAssignmentElement(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ObjectBindingOrAssignmentElement`. + */ +declare function isObjectBindingOrAssignmentElement(node: ts.Node): node is ts.ObjectBindingOrAssignmentElement; +/** + * Test if a node is an `ObjectBindingOrAssignmentPattern`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectBindingOrAssignmentPattern(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ObjectBindingOrAssignmentPattern`. + */ +declare function isObjectBindingOrAssignmentPattern(node: ts.Node): node is ts.ObjectBindingOrAssignmentPattern; +/** + * Test if a node is an `ObjectTypeDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isObjectTypeDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `ObjectTypeDeclaration`. + */ +declare function isObjectTypeDeclaration(node: ts.Node): node is ts.ObjectTypeDeclaration; +/** + * Test if a node is a `ParameterPropertyModifier`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isParameterPropertyModifier(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `ParameterPropertyModifier`. + */ +declare function isParameterPropertyModifier(node: ts.Node): node is ts.ParameterPropertyModifier; +/** + * Test if a node is a `PropertyNameLiteral`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPropertyNameLiteral(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PropertyNameLiteral`. + */ +declare function isPropertyNameLiteral(node: ts.Node): node is ts.PropertyNameLiteral; +/** + * Test if a node is a `PseudoLiteralToken`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isPseudoLiteralToken(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `PseudoLiteralToken`. + */ +declare function isPseudoLiteralToken(node: ts.Node): node is ts.PseudoLiteralToken; +/** + * Test if a node is a `SignatureDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSignatureDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SignatureDeclaration`. + */ +declare function isSignatureDeclaration(node: ts.Node): node is ts.SignatureDeclaration; +/** + * Test if a node is a `SuperProperty`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isSuperProperty(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `SuperProperty`. + */ +declare function isSuperProperty(node: ts.Node): node is ts.SuperProperty; +/** + * Test if a node is a `TypeOnlyCompatibleAliasDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isTypeOnlyCompatibleAliasDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `TypeOnlyCompatibleAliasDeclaration`. + */ +declare function isTypeOnlyCompatibleAliasDeclaration(node: ts.Node): node is ts.TypeOnlyCompatibleAliasDeclaration; +/** + * Test if a node is a `TypeReferenceType`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isTypeReferenceType(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `TypeReferenceType`. + */ +declare function isTypeReferenceType(node: ts.Node): node is ts.TypeReferenceType; +/** + * Test if a node is an `UnionOrIntersectionTypeNode`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isUnionOrIntersectionTypeNode(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be an `UnionOrIntersectionTypeNode`. + */ +declare function isUnionOrIntersectionTypeNode(node: ts.Node): node is ts.UnionOrIntersectionTypeNode; +/** + * Test if a node is a `VariableLikeDeclaration`. + * @category Nodes - Type Guards + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isVariableLikeDeclaration(node)) { + * // ... + * } + * ``` + * @returns Whether the given node appears to be a `VariableLikeDeclaration`. + */ +declare function isVariableLikeDeclaration(node: ts.Node): node is ts.VariableLikeDeclaration; + +/** + * Is the node a scope boundary, specifically due to it being a function. + * @category Scope Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * if (isFunctionScopeBoundary(node, ts.ObjectFlags.Anonymous)) { + * // ... + * } + * ``` + */ +declare function isFunctionScopeBoundary(node: ts.Node): boolean; + +/** + * Test of the kind given is for assignment. + * @category Syntax Utilities + * @example + * ```ts + * declare const kind: ts.SyntaxKind; + * + * isAssignmentKind(kind); + * ``` + */ +declare function isAssignmentKind(kind: ts.SyntaxKind): boolean; +/** + * Test if a string is numeric. + * @category Syntax Utilities + * @example + * ```ts + * isNumericPropertyName("abc"); // false + * isNumericPropertyName("123"); // true + * ``` + */ +declare function isNumericPropertyName(name: string | ts.__String): boolean; +/** + * Determines whether the given text can be used to access a property with a `PropertyAccessExpression` while preserving the property's name. + * @category Syntax Utilities + * @example + * ```ts + * isValidPropertyAccess("abc"); // true + * isValidPropertyAccess("123"); // false + * ``` + */ +declare function isValidPropertyAccess(text: string, languageVersion?: ts.ScriptTarget): boolean; + +/** + * Callback type used for {@link forEachToken}. + * @category Callbacks + * @example + * ```ts + * let onToken: ForEachTokenCallback = (token) => { + * console.log(`Found token at position: ${token.pos}.`); + * }; + * ``` + */ +type ForEachTokenCallback = (token: ts.Node) => void; +/** + * Iterates over all tokens of `node` + * @category Nodes - Other Utilities + * @example + * ```ts + * declare const node: ts.Node; + * + * forEachToken(node, (token) => { + * console.log("Found token:", token.getText()); + * }); + * ``` + * @param node The node whose tokens should be visited + * @param callback Is called for every token contained in `node` + */ +declare function forEachToken(node: ts.Node, callback: ForEachTokenCallback, sourceFile?: ts.SourceFile): void; + +/** + * Get the `CallSignatures` of the given type. + * @category Types - Getters + * @example + * ```ts + * declare const type: ts.Type; + * + * getCallSignaturesOfType(type); + * ``` + */ +declare function getCallSignaturesOfType(type: ts.Type): readonly ts.Signature[]; +/** + * Get the property with the given name on the given type (if it exists). + * @category Types - Getters + * @example + * ```ts + * declare const property: ts.Symbol; + * declare const type: ts.Type; + * + * getPropertyOfType(type, property.getEscapedName()); + * ``` + */ +declare function getPropertyOfType(type: ts.Type, name: ts.__String): ts.Symbol | undefined; +/** + * Retrieves a type symbol corresponding to a well-known string name. + * @category Types - Getters + * @example + * ```ts + * declare const type: ts.Type; + * declare const typeChecker: ts.TypeChecker; + * + * getWellKnownSymbolPropertyOfType(type, "asyncIterator", typeChecker); + * ``` + */ +declare function getWellKnownSymbolPropertyOfType(type: ts.Type, wellKnownSymbolName: string, typeChecker: ts.TypeChecker): ts.Symbol | undefined; + +/** + * A "any" intrinsic type. + * @category Type Types + */ +interface IntrinsicAnyType extends IntrinsicType { + intrinsicName: "any"; +} +/** + * A "bigint" intrinsic type. + * @category Type Types + */ +interface IntrinsicBigIntType extends IntrinsicType { + intrinsicName: "bigint"; +} +/** + * A "boolean" intrinsic type. + * @category Type Types + */ +interface IntrinsicBooleanType extends IntrinsicType { + intrinsicName: "boolean"; +} +/** + * An "error" intrinsic type. + * + * This refers to a type generated when TypeScript encounters an error while + * trying to resolve the type. + * @category Type Types + */ +interface IntrinsicErrorType extends IntrinsicType { + intrinsicName: "error"; +} +/** + * A "symbol" intrinsic type. + * @category Type Types + */ +interface IntrinsicESSymbolType extends IntrinsicType { + intrinsicName: "symbol"; +} +/** + * An "intrinsic" (built-in to TypeScript) type. + * @category Type Types + */ +interface IntrinsicType extends ts.Type { + intrinsicName: string; + objectFlags: ts.ObjectFlags; +} +/** + * Determines whether the given type is the "any" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicAnyType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicAnyType(type: ts.Type): type is IntrinsicAnyType; +/** + * Determines whether the given type is the "bigint" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicBigIntType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicBigIntType(type: ts.Type): type is IntrinsicBigIntType; +/** + * Determines whether the given type is the "boolean" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicBooleanType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicBooleanType(type: ts.Type): type is IntrinsicBooleanType; +/** + * Determines whether the given type is the "error" intrinsic type. + * + * The intrinsic error type occurs when TypeScript encounters an error while + * trying to resolve the type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicErrorType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicErrorType(type: ts.Type): type is IntrinsicErrorType; +/** + * Determines whether the given type is the "symbol" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicESSymbolType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicESSymbolType(type: ts.Type): type is IntrinsicESSymbolType; +/** + * A "never" intrinsic type. + * @category Type Types + */ +interface IntrinsicNeverType extends IntrinsicType { + intrinsicName: "never"; +} +/** + * A non-primitive intrinsic type. + * E.g. An "object" intrinsic type. + * @category Type Types + */ +interface IntrinsicNonPrimitiveType extends IntrinsicType { + intrinsicName: ""; +} +/** + * A "null" intrinsic type. + * @category Type Types + */ +interface IntrinsicNullType extends IntrinsicType { + intrinsicName: "null"; +} +/** + * A "number" intrinsic type. + * @category Type Types + */ +interface IntrinsicNumberType extends IntrinsicType { + intrinsicName: "number"; +} +/** + * A "string" intrinsic type. + * @category Type Types + */ +interface IntrinsicStringType extends IntrinsicType { + intrinsicName: "string"; +} +/** + * The built-in `undefined` type. + * @category Type Types + */ +interface IntrinsicUndefinedType extends IntrinsicType { + intrinsicName: "undefined"; +} +/** + * The built-in `unknown` type. + * @category Type Types + */ +interface IntrinsicUnknownType extends IntrinsicType { + intrinsicName: "unknown"; +} +/** + * A "void" intrinsic type. + * @category Type Types + */ +interface IntrinsicVoidType extends IntrinsicType { + intrinsicName: "void"; +} +/** + * Determines whether the given type is the "never" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicNeverType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicNeverType(type: ts.Type): type is IntrinsicNeverType; +/** + * Determines whether the given type is a non-primitive intrinsic type. + * E.g. An "object" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicNonPrimitiveType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicNonPrimitiveType(type: ts.Type): type is IntrinsicNonPrimitiveType; +/** + * Determines whether the given type is the "null" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicNullType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicNullType(type: ts.Type): type is IntrinsicNullType; +/** + * Determines whether the given type is the "number" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicNumberType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicNumberType(type: ts.Type): type is IntrinsicNumberType; +/** + * Determines whether the given type is the "string" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicStringType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicStringType(type: ts.Type): type is IntrinsicStringType; +/** + * Test if a type is an {@link IntrinsicType}. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicType(type: ts.Type): type is IntrinsicType; +/** + * Determines whether the given type is the "undefined" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicUndefinedType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicUndefinedType(type: ts.Type): type is IntrinsicUndefinedType; +/** + * Determines whether the given type is the "unknown" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicUnknownType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicUnknownType(type: ts.Type): type is IntrinsicUnknownType; +/** + * Determines whether the given type is the "void" intrinsic type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntrinsicVoidType(type)) { + * // ... + * } + * ``` + */ +declare function isIntrinsicVoidType(type: ts.Type): type is IntrinsicVoidType; + +/** + * A type that is both an {@link IntrinsicType} and a `FreshableType` + * @category Type Types + */ +interface FreshableIntrinsicType extends ts.FreshableType, IntrinsicType { +} +/** + * Test if a type is a `FreshableIntrinsicType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isFreshableIntrinsicType(type)) { + * // ... + * } + */ +declare function isFreshableIntrinsicType(type: ts.Type): type is FreshableIntrinsicType; +/** + * Test if a type is a `TupleTypeReference`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTupleTypeReference(type)) { + * // ... + * } + */ +declare function isTupleTypeReference(type: ts.Type): type is ts.TupleTypeReference; + +/** + * A boolean literal. + * i.e. Either a "true" or "false" literal. + * @category Type Types + */ +interface BooleanLiteralType extends FreshableIntrinsicType { + intrinsicName: "false" | "true"; +} +/** + * A "false" literal. + * @category Type Types + */ +interface FalseLiteralType extends BooleanLiteralType { + intrinsicName: "false"; +} +/** + * A "true" literal. + * @category Type Types + */ +interface TrueLiteralType extends BooleanLiteralType { + intrinsicName: "true"; +} +/** + * `LiteralType` from typescript except that it allows for it to work on arbitrary types. + * @deprecated Use {@link FreshableIntrinsicType} instead. + * @category Type Types + */ +interface UnknownLiteralType extends FreshableIntrinsicType { + value?: unknown; +} +/** + * Test if a type is a `BigIntLiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isBigIntLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isBigIntLiteralType(type: ts.Type): type is ts.BigIntLiteralType; +/** + * Determines whether the given type is a boolean literal type. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isBooleanLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isBooleanLiteralType(type: ts.Type): type is BooleanLiteralType; +/** + * Determines whether the given type is a boolean literal type for "false". + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isFalseLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isFalseLiteralType(type: ts.Type): type is FalseLiteralType; +/** + * Test if a type is a `LiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isLiteralType(type: ts.Type): type is ts.LiteralType; +/** + * Test if a type is a `NumberLiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isNumberLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isNumberLiteralType(type: ts.Type): type is ts.NumberLiteralType; +/** + * Test if a type is a `StringLiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isStringLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isStringLiteralType(type: ts.Type): type is ts.StringLiteralType; +/** + * Test if a type is a `TemplateLiteralType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTemplateLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isTemplateLiteralType(type: ts.Type): type is ts.TemplateLiteralType; +/** + * Determines whether the given type is a boolean literal type for "true". + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTrueLiteralType(type)) { + * // ... + * } + * ``` + */ +declare function isTrueLiteralType(type: ts.Type): type is TrueLiteralType; + +/** + * Test if a type is a `EvolvingArrayType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isEvolvingArrayType(type)) { + * // ... + * } + * ``` + */ +declare function isEvolvingArrayType(type: ts.Type): type is ts.EvolvingArrayType; +/** + * Test if a type is a `TupleType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTupleType(type)) { + * // ... + * } + * ``` + */ +declare function isTupleType(type: ts.Type): type is ts.TupleType; +/** + * Test if a type is a `TypeReference`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTypeReference(type)) { + * // ... + * } + * ``` + */ +declare function isTypeReference(type: ts.Type): type is ts.TypeReference; + +/** + * Test if a type is a `ConditionalType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isConditionalType(type)) { + * // ... + * } + * ``` + */ +declare function isConditionalType(type: ts.Type): type is ts.ConditionalType; +/** + * Test if a type is a `EnumType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isEnumType(type)) { + * // ... + * } + * ``` + */ +declare function isEnumType(type: ts.Type): type is ts.EnumType; +/** + * Test if a type is a `FreshableType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isFreshableType(type)) { + * // ... + * } + * ``` + */ +declare function isFreshableType(type: ts.Type): type is ts.FreshableType; +/** + * Test if a type is a `IndexedAccessType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIndexedAccessType(type)) { + * // ... + * } + * ``` + */ +declare function isIndexedAccessType(type: ts.Type): type is ts.IndexedAccessType; +/** + * Test if a type is a `IndexType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIndexType(type)) { + * // ... + * } + * ``` + */ +declare function isIndexType(type: ts.Type): type is ts.IndexType; +/** + * Test if a type is a `InstantiableType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isInstantiableType(type)) { + * // ... + * } + * ``` + */ +declare function isInstantiableType(type: ts.Type): type is ts.InstantiableType; +/** + * Test if a type is a `IntersectionType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isIntersectionType(type)) { + * // ... + * } + * ``` + */ +declare function isIntersectionType(type: ts.Type): type is ts.IntersectionType; +/** + * Test if a type is a `ObjectType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isObjectType(type)) { + * // ... + * } + * ``` + */ +declare function isObjectType(type: ts.Type): type is ts.ObjectType; +/** + * Test if a type is a `StringMappingType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isStringMappingType(type)) { + * // ... + * } + * ``` + */ +declare function isStringMappingType(type: ts.Type): type is ts.StringMappingType; +/** + * Test if a type is a `SubstitutionType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isSubstitutionType(type)) { + * // ... + * } + * ``` + */ +declare function isSubstitutionType(type: ts.Type): type is ts.SubstitutionType; +/** + * Test if a type is a `TypeParameter`. + * + * Note: It is intentional that this is not a type guard. + * @see https://github.com/JoshuaKGoldberg/ts-api-utils/issues/382 + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTypeParameter(type)) { + * // ... + * } + * ``` + */ +declare function isTypeParameter(type: ts.Type): boolean; +/** + * Test if a type is a `TypeVariable`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isTypeVariable(type)) { + * // ... + * } + * ``` + */ +declare function isTypeVariable(type: ts.Type): type is ts.TypeVariable; +/** + * Test if a type is a `UnionOrIntersectionType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isUnionOrIntersectionType(type)) { + * // ... + * } + * ``` + */ +declare function isUnionOrIntersectionType(type: ts.Type): type is ts.UnionOrIntersectionType; +/** + * Test if a type is a `UnionType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isUnionType(type)) { + * // ... + * } + * ``` + */ +declare function isUnionType(type: ts.Type): type is ts.UnionType; +/** + * Test if a type is a `UniqueESSymbolType`. + * @category Types - Type Guards + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isUniqueESSymbolType(type)) { + * // ... + * } + * ``` + */ +declare function isUniqueESSymbolType(type: ts.Type): type is ts.UniqueESSymbolType; + +/** + * Get the intersection type parts of the given type. + * + * If the given type is not a intersection type, an array contain only that type will be returned. + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * for (const constituent of intersectionConstituents(type)) { + * // ... + * } + * ``` + */ +declare function intersectionConstituents(type: ts.Type): ts.Type[]; +/** + * @deprecated Use {@link intersectionConstituents} instead. + * @category Types - Utilities + * ``` + */ +declare const intersectionTypeParts: typeof intersectionConstituents; +/** + * Determines whether a type is definitely falsy. This function doesn't unwrap union types. + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * if (isFalsyType(type)) { + * // ... + * } + * ``` + */ +declare function isFalsyType(type: ts.Type): boolean; +/** + * Determines whether writing to a certain property of a given type is allowed. + * @category Types - Utilities + * @example + * ```ts + * declare const property: ts.Symbol; + * declare const type: ts.Type; + * declare const typeChecker: ts.TypeChecker; + * + * if (isPropertyReadonlyInType(type, property.getEscapedName(), typeChecker)) { + * // ... + * } + * ``` + */ +declare function isPropertyReadonlyInType(type: ts.Type, name: ts.__String, typeChecker: ts.TypeChecker): boolean; +/** + * Determines whether a type is thenable and thus can be used with `await`. + * @category Types - Utilities + * @example + * ```ts + * declare const node: ts.Node; + * declare const type: ts.Type; + * declare const typeChecker: ts.TypeChecker; + * + * if (isThenableType(typeChecker, node, type)) { + * // ... + * } + * ``` + */ +declare function isThenableType(typeChecker: ts.TypeChecker, node: ts.Node, type: ts.Type): boolean; +/** + * Determines whether a type is thenable and thus can be used with `await`. + * @category Types - Utilities + * @example + * ```ts + * declare const expression: ts.Expression; + * declare const typeChecker: ts.TypeChecker; + * + * if (isThenableType(typeChecker, expression)) { + * // ... + * } + * ``` + * @example + * ```ts + * declare const expression: ts.Expression; + * declare const typeChecker: ts.TypeChecker; + * declare const type: ts.Type; + * + * if (isThenableType(typeChecker, expression, type)) { + * // ... + * } + * ``` + */ +declare function isThenableType(typeChecker: ts.TypeChecker, node: ts.Expression, type?: ts.Type): boolean; +/** + * Test if the given symbol has a readonly declaration. + * @category Symbols - Utilities + * @example + * ```ts + * declare const symbol: ts.Symbol; + * declare const typeChecker: ts.TypeChecker; + * + * if (symbolHasReadonlyDeclaration(symbol, typeChecker)) { + * // ... + * } + * ``` + */ +declare function symbolHasReadonlyDeclaration(symbol: ts.Symbol, typeChecker: ts.TypeChecker): boolean; +/** + * Get the intersection or union type parts of the given type. + * + * Note that this is a shallow collection: it only returns `type.types` or `[type]`. + * + * If the given type is not an intersection or union type, an array contain only that type will be returned. + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * for (const constituent of typeConstituents(type)) { + * // ... + * } + * ``` + */ +declare function typeConstituents(type: ts.Type): ts.Type[]; +/** + * TS's `type.isLiteral()` is bugged before TS v5.0 and won't return `true` for + * bigint literals. Use this function instead if you need to check for bigint + * literals in TS versions before v5.0. Otherwise, you should just use + * `type.isLiteral()`. + * @see https://github.com/microsoft/TypeScript/pull/50929 + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * if (typeIsLiteral(type)) { + * // ... + * } + * ``` + */ +declare function typeIsLiteral(type: ts.Type): type is ts.LiteralType; +/** + * @deprecated Use {@link typeConstituents} instead. + * @category Types - Utilities + */ +declare const typeParts: typeof typeConstituents; +/** + * Get the union type parts of the given type. + * + * If the given type is not a union type, an array contain only that type will be returned. + * @category Types - Utilities + * @example + * ```ts + * declare const type: ts.Type; + * + * for (const constituent of unionConstituents(type)) { + * // ... + * } + * ``` + */ +declare function unionConstituents(type: ts.Type): ts.Type[]; +/** + * @deprecated Use {@link unionConstituents} instead. + * @category Types - Utilities + */ +declare const unionTypeParts: typeof unionConstituents; + +/** + * Which "domain"(s) (most commonly, type or value space) a declaration is within. + */ +declare enum DeclarationDomain { + Namespace = 1, + Type = 2, + Value = 4, + Any = 7, + Import = 8 +} + +/** + * Which "domain"(s) (most commonly, type or value space) a usage is within. + */ +declare enum UsageDomain { + Namespace = 1, + Type = 2, + Value = 4, + Any = 7, + TypeQuery = 8, + ValueOrNamespace = 5 +} + +/** + * An instance of an item (type or value) being used. + */ +interface Usage { + /** + * Which space(s) the usage is within. + */ + domain: UsageDomain; + location: ts.Identifier; +} +/** + * How an item (type or value) was declared and/or referenced. + */ +interface UsageInfo { + /** + * Locations where the item was declared. + */ + declarations: ts.Identifier[]; + /** + * Which space(s) the item is within. + */ + domain: DeclarationDomain; + /** + * Whether the item was exported from its module or namespace scope. + */ + exported: boolean; + /** + * Whether the item's declaration was in the global scope. + */ + inGlobalScope: boolean; + /** + * Each reference to the item in the file. + */ + uses: Usage[]; +} + +/** + * Creates a mapping of each declared type and value to its type information. + * @category Nodes - Other Utilities + * @example + * ```ts + * declare const sourceFile: ts.SourceFile; + * + * const usage = collectVariableUsage(sourceFile); + * + * for (const [identifier, information] of usage) { + * console.log(`${identifier.getText()} is used ${information.uses.length} time(s).`); + * } + * ``` + */ +declare function collectVariableUsage(sourceFile: ts.SourceFile): Map; + +export { AccessKind, type AnyKeyword, type BigIntKeyword, type BooleanCompilerOptions, type BooleanKeyword, type BooleanLiteralType, type ConstAssertionExpression, type ConstAssertionIdentifier, DeclarationDomain, type FalseKeyword, type FalseLiteralType, type ForEachCommentCallback, type ForEachTokenCallback, type FreshableIntrinsicType, type ImportKeyword, type IntrinsicAnyType, type IntrinsicBigIntType, type IntrinsicBooleanType, type IntrinsicESSymbolType, type IntrinsicErrorType, type IntrinsicNeverType, type IntrinsicNonPrimitiveType, type IntrinsicNullType, type IntrinsicNumberType, type IntrinsicStringType, type IntrinsicType, type IntrinsicUndefinedType, type IntrinsicUnknownType, type IntrinsicVoidType, type NamedDeclarationWithName, type NeverKeyword, type NullKeyword, type NumberKeyword, type NumericOrStringLikeLiteral, type ObjectKeyword, type StrictCompilerOption, type StringKeyword, type SuperKeyword, type SymbolKeyword, type ThisKeyword, type TrueKeyword, type TrueLiteralType, type UndefinedKeyword, type UnknownKeyword, type UnknownLiteralType, UsageDomain, type UsageInfo as VariableInfo, type Usage as VariableUse, type VoidKeyword, collectVariableUsage, forEachComment, forEachToken, getAccessKind, getCallSignaturesOfType, getPropertyOfType, getWellKnownSymbolPropertyOfType, hasDecorators, hasExpressionInitializer, hasInitializer, hasJSDoc, hasModifiers, hasType, hasTypeArguments, includesModifier, intersectionConstituents, intersectionTypeParts, isAbstractKeyword, isAccessExpression, isAccessibilityModifier, isAccessorDeclaration, isAccessorKeyword, isAnyKeyword, isArrayBindingElement, isArrayBindingOrAssignmentPattern, isAssertKeyword, isAssertsKeyword, isAssignmentKind, isAssignmentPattern, isAsyncKeyword, isAwaitKeyword, isBigIntKeyword, isBigIntLiteralType, isBindingOrAssignmentElementRestIndicator, isBindingOrAssignmentElementTarget, isBindingOrAssignmentPattern, isBindingPattern, isBlockLike, isBooleanKeyword, isBooleanLiteral, isBooleanLiteralType, isClassLikeDeclaration, isClassMemberModifier, isColonToken, isCompilerOptionEnabled, isConditionalType, isConstAssertionExpression, isConstKeyword, isDeclarationName, isDeclarationWithTypeParameterChildren, isDeclarationWithTypeParameters, isDeclareKeyword, isDefaultKeyword, isDestructuringPattern, isDotToken, isEndOfFileToken, isEntityNameExpression, isEntityNameOrEntityNameExpression, isEnumType, isEqualsGreaterThanToken, isEqualsToken, isEvolvingArrayType, isExclamationToken, isExportKeyword, isFalseKeyword, isFalseLiteral, isFalseLiteralType, isFalsyType, isForInOrOfStatement, isFreshableIntrinsicType, isFreshableType, isFunctionLikeDeclaration, isFunctionScopeBoundary, isImportExpression, isImportKeyword, isInKeyword, isIndexType, isIndexedAccessType, isInstantiableType, isIntersectionType, isIntrinsicAnyType, isIntrinsicBigIntType, isIntrinsicBooleanType, isIntrinsicESSymbolType, isIntrinsicErrorType, isIntrinsicNeverType, isIntrinsicNonPrimitiveType, isIntrinsicNullType, isIntrinsicNumberType, isIntrinsicStringType, isIntrinsicType, isIntrinsicUndefinedType, isIntrinsicUnknownType, isIntrinsicVoidType, isIterationStatement, isJSDocComment, isJSDocNamespaceBody, isJSDocNamespaceDeclaration, isJSDocText, isJSDocTypeReferencingNode, isJsonMinusNumericLiteral, isJsonObjectExpression, isJsxAttributeLike, isJsxAttributeValue, isJsxChild, isJsxTagNameExpression, isJsxTagNamePropertyAccess, isLiteralToken, isLiteralType, isModifierFlagSet, isModuleBody, isModuleName, isModuleReference, isNamedDeclarationWithName, isNamedImportBindings, isNamedImportsOrExports, isNamespaceBody, isNamespaceDeclaration, isNeverKeyword, isNodeFlagSet, isNullKeyword, isNullLiteral, isNumberKeyword, isNumberLiteralType, isNumericOrStringLikeLiteral, isNumericPropertyName, isObjectBindingOrAssignmentElement, isObjectBindingOrAssignmentPattern, isObjectFlagSet, isObjectKeyword, isObjectType, isObjectTypeDeclaration, isOutKeyword, isOverrideKeyword, isParameterPropertyModifier, isPrivateKeyword, isPropertyAccessEntityNameExpression, isPropertyNameLiteral, isPropertyReadonlyInType, isProtectedKeyword, isPseudoLiteralToken, isPublicKeyword, isQuestionDotToken, isQuestionToken, isReadonlyKeyword, isSignatureDeclaration, isStaticKeyword, isStrictCompilerOptionEnabled, isStringKeyword, isStringLiteralType, isStringMappingType, isSubstitutionType, isSuperElementAccessExpression, isSuperExpression, isSuperKeyword, isSuperProperty, isSuperPropertyAccessExpression, isSymbolFlagSet, isSymbolKeyword, isSyntaxList, isTemplateLiteralType, isThenableType, isThisExpression, isThisKeyword, isTransientSymbolLinksFlagSet, isTrueKeyword, isTrueLiteral, isTrueLiteralType, isTupleType, isTupleTypeReference, isTypeFlagSet, isTypeOnlyCompatibleAliasDeclaration, isTypeParameter, isTypeReference, isTypeReferenceType, isTypeVariable, isUndefinedKeyword, isUnionOrIntersectionType, isUnionOrIntersectionTypeNode, isUnionType, isUniqueESSymbolType, isUnknownKeyword, isValidPropertyAccess, isVariableLikeDeclaration, isVoidKeyword, symbolHasReadonlyDeclaration, typeConstituents, typeIsLiteral, typeParts, unionConstituents, unionTypeParts }; diff --git a/node_modules/ts-api-utils/lib/index.js b/node_modules/ts-api-utils/lib/index.js new file mode 100644 index 00000000..cd0dc8ed --- /dev/null +++ b/node_modules/ts-api-utils/lib/index.js @@ -0,0 +1,2083 @@ +import ts9 from 'typescript'; + +// src/comments.ts +function forEachToken(node, callback, sourceFile = node.getSourceFile()) { + const queue = []; + while (true) { + if (ts9.isTokenKind(node.kind)) { + callback(node); + } else { + const children = node.getChildren(sourceFile); + if (children.length === 1) { + node = children[0]; + continue; + } + for (let i = children.length - 1; i >= 0; --i) { + queue.push(children[i]); + } + } + if (queue.length === 0) { + break; + } + node = queue.pop(); + } +} + +// src/comments.ts +function forEachComment(node, callback, sourceFile = node.getSourceFile()) { + const fullText = sourceFile.text; + const notJsx = sourceFile.languageVariant !== ts9.LanguageVariant.JSX; + return forEachToken( + node, + (token) => { + if (token.pos === token.end) { + return; + } + if (token.kind !== ts9.SyntaxKind.JsxText) { + ts9.forEachLeadingCommentRange( + fullText, + // skip shebang at position 0 + token.pos === 0 ? (ts9.getShebang(fullText) ?? "").length : token.pos, + commentCallback + ); + } + if (notJsx || canHaveTrailingTrivia(token)) { + return ts9.forEachTrailingCommentRange( + fullText, + token.end, + commentCallback + ); + } + }, + sourceFile + ); + function commentCallback(pos, end, kind) { + callback(fullText, { end, kind, pos }); + } +} +function canHaveTrailingTrivia(token) { + switch (token.kind) { + case ts9.SyntaxKind.CloseBraceToken: + return token.parent.kind !== ts9.SyntaxKind.JsxExpression || !isJsxElementOrFragment(token.parent.parent); + case ts9.SyntaxKind.GreaterThanToken: + switch (token.parent.kind) { + case ts9.SyntaxKind.JsxClosingElement: + case ts9.SyntaxKind.JsxClosingFragment: + return !isJsxElementOrFragment(token.parent.parent.parent); + case ts9.SyntaxKind.JsxOpeningElement: + return token.end !== token.parent.end; + case ts9.SyntaxKind.JsxOpeningFragment: + return false; + // would be inside the fragment + case ts9.SyntaxKind.JsxSelfClosingElement: + return token.end !== token.parent.end || // if end is not equal, this is part of the type arguments list + !isJsxElementOrFragment(token.parent.parent); + } + } + return true; +} +function isJsxElementOrFragment(node) { + return node.kind === ts9.SyntaxKind.JsxElement || node.kind === ts9.SyntaxKind.JsxFragment; +} +function isCompilerOptionEnabled(options, option) { + switch (option) { + case "allowJs": + return options.allowJs === undefined ? isCompilerOptionEnabled(options, "checkJs") : options.allowJs; + case "allowSyntheticDefaultImports": + return options.allowSyntheticDefaultImports !== undefined ? options.allowSyntheticDefaultImports : isCompilerOptionEnabled(options, "esModuleInterop") || options.module === ts9.ModuleKind.System; + case "alwaysStrict": + case "noImplicitAny": + case "noImplicitThis": + case "strictBindCallApply": + case "strictFunctionTypes": + case "strictNullChecks": + case "strictPropertyInitialization": + return isStrictCompilerOptionEnabled( + options, + option + ); + case "declaration": + return options.declaration || isCompilerOptionEnabled(options, "composite"); + case "declarationMap": + case "emitDeclarationOnly": + case "stripInternal": + return options[option] === true && isCompilerOptionEnabled(options, "declaration"); + case "incremental": + return options.incremental === undefined ? isCompilerOptionEnabled(options, "composite") : options.incremental; + case "noUncheckedIndexedAccess": + return options.noUncheckedIndexedAccess === true && isCompilerOptionEnabled(options, "strictNullChecks"); + case "skipDefaultLibCheck": + return options.skipDefaultLibCheck || isCompilerOptionEnabled(options, "skipLibCheck"); + case "suppressImplicitAnyIndexErrors": + return ( + // eslint-disable-next-line @typescript-eslint/no-deprecated + options.suppressImplicitAnyIndexErrors === true && isCompilerOptionEnabled(options, "noImplicitAny") + ); + } + return options[option] === true; +} +function isStrictCompilerOptionEnabled(options, option) { + return (options.strict ? options[option] !== false : options[option] === true) && (option !== "strictPropertyInitialization" || isStrictCompilerOptionEnabled(options, "strictNullChecks")); +} +function isModifierFlagSet(node, flag) { + return isFlagSet(ts9.getCombinedModifierFlags(node), flag); +} +function isFlagSet(allFlags, flag) { + return (allFlags & flag) !== 0; +} +function isFlagSetOnObject(obj, flag) { + return isFlagSet(obj.flags, flag); +} +var isNodeFlagSet = isFlagSetOnObject; +function isObjectFlagSet(objectType, flag) { + return isFlagSet(objectType.objectFlags, flag); +} +var isSymbolFlagSet = isFlagSetOnObject; +function isTransientSymbolLinksFlagSet(links, flag) { + return isFlagSet(links.checkFlags, flag); +} +var isTypeFlagSet = isFlagSetOnObject; + +// src/modifiers.ts +function includesModifier(modifiers, ...kinds) { + if (modifiers === undefined) { + return false; + } + for (const modifier of modifiers) { + if (kinds.includes(modifier.kind)) { + return true; + } + } + return false; +} +function isAssignmentKind(kind) { + return kind >= ts9.SyntaxKind.FirstAssignment && kind <= ts9.SyntaxKind.LastAssignment; +} +function isNumericPropertyName(name) { + return String(+name) === name; +} +function isValidPropertyAccess(text, languageVersion = ts9.ScriptTarget.Latest) { + if (text.length === 0) { + return false; + } + let ch = text.codePointAt(0); + if (!ts9.isIdentifierStart(ch, languageVersion)) { + return false; + } + for (let i = charSize(ch); i < text.length; i += charSize(ch)) { + ch = text.codePointAt(i); + if (!ts9.isIdentifierPart(ch, languageVersion)) { + return false; + } + } + return true; +} +function charSize(ch) { + return ch >= 65536 ? 2 : 1; +} + +// src/nodes/access.ts +var AccessKind = /* @__PURE__ */ ((AccessKind2) => { + AccessKind2[AccessKind2["None"] = 0] = "None"; + AccessKind2[AccessKind2["Read"] = 1] = "Read"; + AccessKind2[AccessKind2["Write"] = 2] = "Write"; + AccessKind2[AccessKind2["Delete"] = 4] = "Delete"; + AccessKind2[AccessKind2["ReadWrite"] = 3] = "ReadWrite"; + return AccessKind2; +})(AccessKind || {}); +function getAccessKind(node) { + const parent = node.parent; + switch (parent.kind) { + case ts9.SyntaxKind.ArrayLiteralExpression: + case ts9.SyntaxKind.SpreadAssignment: + case ts9.SyntaxKind.SpreadElement: + return isInDestructuringAssignment( + parent + ) ? 2 /* Write */ : 1 /* Read */; + case ts9.SyntaxKind.ArrowFunction: + return parent.body === node ? 1 /* Read */ : 2 /* Write */; + case ts9.SyntaxKind.AsExpression: + case ts9.SyntaxKind.NonNullExpression: + case ts9.SyntaxKind.ParenthesizedExpression: + case ts9.SyntaxKind.TypeAssertionExpression: + return getAccessKind(parent); + case ts9.SyntaxKind.AwaitExpression: + case ts9.SyntaxKind.CallExpression: + case ts9.SyntaxKind.CaseClause: + case ts9.SyntaxKind.ComputedPropertyName: + case ts9.SyntaxKind.ConditionalExpression: + case ts9.SyntaxKind.Decorator: + case ts9.SyntaxKind.DoStatement: + case ts9.SyntaxKind.ElementAccessExpression: + case ts9.SyntaxKind.ExpressionStatement: + case ts9.SyntaxKind.ForStatement: + case ts9.SyntaxKind.IfStatement: + case ts9.SyntaxKind.JsxElement: + case ts9.SyntaxKind.JsxExpression: + case ts9.SyntaxKind.JsxOpeningElement: + case ts9.SyntaxKind.JsxSelfClosingElement: + case ts9.SyntaxKind.JsxSpreadAttribute: + case ts9.SyntaxKind.NewExpression: + case ts9.SyntaxKind.ReturnStatement: + case ts9.SyntaxKind.SwitchStatement: + case ts9.SyntaxKind.TaggedTemplateExpression: + case ts9.SyntaxKind.TemplateSpan: + case ts9.SyntaxKind.ThrowStatement: + case ts9.SyntaxKind.TypeOfExpression: + case ts9.SyntaxKind.VoidExpression: + case ts9.SyntaxKind.WhileStatement: + case ts9.SyntaxKind.WithStatement: + case ts9.SyntaxKind.YieldExpression: + return 1 /* Read */; + case ts9.SyntaxKind.BinaryExpression: + return parent.right === node ? 1 /* Read */ : !isAssignmentKind(parent.operatorToken.kind) ? 1 /* Read */ : parent.operatorToken.kind === ts9.SyntaxKind.EqualsToken ? 2 /* Write */ : 3 /* ReadWrite */; + case ts9.SyntaxKind.BindingElement: + case ts9.SyntaxKind.EnumMember: + case ts9.SyntaxKind.JsxAttribute: + case ts9.SyntaxKind.Parameter: + case ts9.SyntaxKind.PropertyDeclaration: + case ts9.SyntaxKind.VariableDeclaration: + return parent.initializer === node ? 1 /* Read */ : 0 /* None */; + case ts9.SyntaxKind.DeleteExpression: + return 4 /* Delete */; + case ts9.SyntaxKind.ExportAssignment: + return parent.isExportEquals ? 1 /* Read */ : 0 /* None */; + case ts9.SyntaxKind.ExpressionWithTypeArguments: + return parent.parent.token === ts9.SyntaxKind.ExtendsKeyword && parent.parent.parent.kind !== ts9.SyntaxKind.InterfaceDeclaration ? 1 /* Read */ : 0 /* None */; + case ts9.SyntaxKind.ForInStatement: + case ts9.SyntaxKind.ForOfStatement: + return parent.initializer === node ? 2 /* Write */ : 1 /* Read */; + case ts9.SyntaxKind.PostfixUnaryExpression: + return 3 /* ReadWrite */; + case ts9.SyntaxKind.PrefixUnaryExpression: + return parent.operator === ts9.SyntaxKind.PlusPlusToken || parent.operator === ts9.SyntaxKind.MinusMinusToken ? 3 /* ReadWrite */ : 1 /* Read */; + case ts9.SyntaxKind.PropertyAccessExpression: + return parent.expression === node ? 1 /* Read */ : 0 /* None */; + case ts9.SyntaxKind.PropertyAssignment: + return parent.name === node ? 0 /* None */ : isInDestructuringAssignment(parent) ? 2 /* Write */ : 1 /* Read */; + case ts9.SyntaxKind.ShorthandPropertyAssignment: + return parent.objectAssignmentInitializer === node ? 1 /* Read */ : isInDestructuringAssignment(parent) ? 2 /* Write */ : 1 /* Read */; + } + return 0 /* None */; +} +function isInDestructuringAssignment(node) { + switch (node.kind) { + case ts9.SyntaxKind.ShorthandPropertyAssignment: + if (node.objectAssignmentInitializer !== undefined) { + return true; + } + // falls through + case ts9.SyntaxKind.PropertyAssignment: + case ts9.SyntaxKind.SpreadAssignment: + node = node.parent; + break; + case ts9.SyntaxKind.SpreadElement: + if (node.parent.kind !== ts9.SyntaxKind.ArrayLiteralExpression) { + return false; + } + node = node.parent; + } + while (true) { + switch (node.parent.kind) { + case ts9.SyntaxKind.ArrayLiteralExpression: + case ts9.SyntaxKind.ObjectLiteralExpression: + node = node.parent; + break; + case ts9.SyntaxKind.BinaryExpression: + return node.parent.left === node && node.parent.operatorToken.kind === ts9.SyntaxKind.EqualsToken; + case ts9.SyntaxKind.ForOfStatement: + return node.parent.initializer === node; + case ts9.SyntaxKind.PropertyAssignment: + case ts9.SyntaxKind.SpreadAssignment: + node = node.parent.parent; + break; + case ts9.SyntaxKind.SpreadElement: + if (node.parent.parent.kind !== ts9.SyntaxKind.ArrayLiteralExpression) { + return false; + } + node = node.parent.parent; + break; + default: + return false; + } + } +} +function isAbstractKeyword(node) { + return node.kind === ts9.SyntaxKind.AbstractKeyword; +} +function isAccessorKeyword(node) { + return node.kind === ts9.SyntaxKind.AccessorKeyword; +} +function isAnyKeyword(node) { + return node.kind === ts9.SyntaxKind.AnyKeyword; +} +function isAssertKeyword(node) { + return node.kind === ts9.SyntaxKind.AssertKeyword; +} +function isAssertsKeyword(node) { + return node.kind === ts9.SyntaxKind.AssertsKeyword; +} +function isAsyncKeyword(node) { + return node.kind === ts9.SyntaxKind.AsyncKeyword; +} +function isAwaitKeyword(node) { + return node.kind === ts9.SyntaxKind.AwaitKeyword; +} +function isBigIntKeyword(node) { + return node.kind === ts9.SyntaxKind.BigIntKeyword; +} +function isBooleanKeyword(node) { + return node.kind === ts9.SyntaxKind.BooleanKeyword; +} +function isColonToken(node) { + return node.kind === ts9.SyntaxKind.ColonToken; +} +function isConstKeyword(node) { + return node.kind === ts9.SyntaxKind.ConstKeyword; +} +function isDeclareKeyword(node) { + return node.kind === ts9.SyntaxKind.DeclareKeyword; +} +function isDefaultKeyword(node) { + return node.kind === ts9.SyntaxKind.DefaultKeyword; +} +function isDotToken(node) { + return node.kind === ts9.SyntaxKind.DotToken; +} +function isEndOfFileToken(node) { + return node.kind === ts9.SyntaxKind.EndOfFileToken; +} +function isEqualsGreaterThanToken(node) { + return node.kind === ts9.SyntaxKind.EqualsGreaterThanToken; +} +function isEqualsToken(node) { + return node.kind === ts9.SyntaxKind.EqualsToken; +} +function isExclamationToken(node) { + return node.kind === ts9.SyntaxKind.ExclamationToken; +} +function isExportKeyword(node) { + return node.kind === ts9.SyntaxKind.ExportKeyword; +} +function isFalseKeyword(node) { + return node.kind === ts9.SyntaxKind.FalseKeyword; +} +function isFalseLiteral(node) { + return node.kind === ts9.SyntaxKind.FalseKeyword; +} +function isImportExpression(node) { + return node.kind === ts9.SyntaxKind.ImportKeyword; +} +function isImportKeyword(node) { + return node.kind === ts9.SyntaxKind.ImportKeyword; +} +function isInKeyword(node) { + return node.kind === ts9.SyntaxKind.InKeyword; +} +function isJSDocText(node) { + return node.kind === ts9.SyntaxKind.JSDocText; +} +function isJsonMinusNumericLiteral(node) { + return node.kind === ts9.SyntaxKind.PrefixUnaryExpression; +} +function isNeverKeyword(node) { + return node.kind === ts9.SyntaxKind.NeverKeyword; +} +function isNullKeyword(node) { + return node.kind === ts9.SyntaxKind.NullKeyword; +} +function isNullLiteral(node) { + return node.kind === ts9.SyntaxKind.NullKeyword; +} +function isNumberKeyword(node) { + return node.kind === ts9.SyntaxKind.NumberKeyword; +} +function isObjectKeyword(node) { + return node.kind === ts9.SyntaxKind.ObjectKeyword; +} +function isOutKeyword(node) { + return node.kind === ts9.SyntaxKind.OutKeyword; +} +function isOverrideKeyword(node) { + return node.kind === ts9.SyntaxKind.OverrideKeyword; +} +function isPrivateKeyword(node) { + return node.kind === ts9.SyntaxKind.PrivateKeyword; +} +function isProtectedKeyword(node) { + return node.kind === ts9.SyntaxKind.ProtectedKeyword; +} +function isPublicKeyword(node) { + return node.kind === ts9.SyntaxKind.PublicKeyword; +} +function isQuestionDotToken(node) { + return node.kind === ts9.SyntaxKind.QuestionDotToken; +} +function isQuestionToken(node) { + return node.kind === ts9.SyntaxKind.QuestionToken; +} +function isReadonlyKeyword(node) { + return node.kind === ts9.SyntaxKind.ReadonlyKeyword; +} +function isStaticKeyword(node) { + return node.kind === ts9.SyntaxKind.StaticKeyword; +} +function isStringKeyword(node) { + return node.kind === ts9.SyntaxKind.StringKeyword; +} +function isSuperExpression(node) { + return node.kind === ts9.SyntaxKind.SuperKeyword; +} +function isSuperKeyword(node) { + return node.kind === ts9.SyntaxKind.SuperKeyword; +} +function isSymbolKeyword(node) { + return node.kind === ts9.SyntaxKind.SymbolKeyword; +} +function isSyntaxList(node) { + return node.kind === ts9.SyntaxKind.SyntaxList; +} +function isThisExpression(node) { + return node.kind === ts9.SyntaxKind.ThisKeyword; +} +function isThisKeyword(node) { + return node.kind === ts9.SyntaxKind.ThisKeyword; +} +function isTrueKeyword(node) { + return node.kind === ts9.SyntaxKind.TrueKeyword; +} +function isTrueLiteral(node) { + return node.kind === ts9.SyntaxKind.TrueKeyword; +} +function isUndefinedKeyword(node) { + return node.kind === ts9.SyntaxKind.UndefinedKeyword; +} +function isUnknownKeyword(node) { + return node.kind === ts9.SyntaxKind.UnknownKeyword; +} +function isVoidKeyword(node) { + return node.kind === ts9.SyntaxKind.VoidKeyword; +} +var [tsMajor, tsMinor] = ts9.versionMajorMinor.split(".").map((raw) => Number.parseInt(raw, 10)); +function isTsVersionAtLeast(major, minor = 0) { + return tsMajor > major || tsMajor === major && tsMinor >= minor; +} + +// src/nodes/typeGuards/union.ts +function hasDecorators(node) { + return ts9.isParameter(node) || ts9.isPropertyDeclaration(node) || ts9.isMethodDeclaration(node) || ts9.isGetAccessorDeclaration(node) || ts9.isSetAccessorDeclaration(node) || ts9.isClassExpression(node) || ts9.isClassDeclaration(node); +} +function hasExpressionInitializer(node) { + return ts9.isVariableDeclaration(node) || ts9.isParameter(node) || ts9.isBindingElement(node) || ts9.isPropertyDeclaration(node) || ts9.isPropertyAssignment(node) || ts9.isEnumMember(node); +} +function hasInitializer(node) { + return hasExpressionInitializer(node) || ts9.isForStatement(node) || ts9.isForInStatement(node) || ts9.isForOfStatement(node) || ts9.isJsxAttribute(node); +} +function hasJSDoc(node) { + if ( + // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isAccessorDeclaration(node) || ts9.isArrowFunction(node) || ts9.isBlock(node) || ts9.isBreakStatement(node) || ts9.isCallSignatureDeclaration(node) || ts9.isCaseClause(node) || // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isClassLikeDeclaration(node) || ts9.isConstructorDeclaration(node) || ts9.isConstructorTypeNode(node) || ts9.isConstructSignatureDeclaration(node) || ts9.isContinueStatement(node) || ts9.isDebuggerStatement(node) || ts9.isDoStatement(node) || ts9.isEmptyStatement(node) || isEndOfFileToken(node) || ts9.isEnumDeclaration(node) || ts9.isEnumMember(node) || ts9.isExportAssignment(node) || ts9.isExportDeclaration(node) || ts9.isExportSpecifier(node) || ts9.isExpressionStatement(node) || ts9.isForInStatement(node) || ts9.isForOfStatement(node) || ts9.isForStatement(node) || ts9.isFunctionDeclaration(node) || ts9.isFunctionExpression(node) || ts9.isFunctionTypeNode(node) || ts9.isIfStatement(node) || ts9.isImportDeclaration(node) || ts9.isImportEqualsDeclaration(node) || ts9.isIndexSignatureDeclaration(node) || ts9.isInterfaceDeclaration(node) || ts9.isJSDocFunctionType(node) || ts9.isLabeledStatement(node) || ts9.isMethodDeclaration(node) || ts9.isMethodSignature(node) || ts9.isModuleDeclaration(node) || ts9.isNamedTupleMember(node) || ts9.isNamespaceExportDeclaration(node) || ts9.isParameter(node) || ts9.isParenthesizedExpression(node) || ts9.isPropertyAssignment(node) || ts9.isPropertyDeclaration(node) || ts9.isPropertySignature(node) || ts9.isReturnStatement(node) || ts9.isShorthandPropertyAssignment(node) || ts9.isSpreadAssignment(node) || ts9.isSwitchStatement(node) || ts9.isThrowStatement(node) || ts9.isTryStatement(node) || ts9.isTypeAliasDeclaration(node) || ts9.isVariableDeclaration(node) || ts9.isVariableStatement(node) || ts9.isWhileStatement(node) || ts9.isWithStatement(node) + ) { + return true; + } + if (isTsVersionAtLeast(4, 4) && ts9.isClassStaticBlockDeclaration(node)) { + return true; + } + if (isTsVersionAtLeast(5, 0) && (ts9.isBinaryExpression(node) || ts9.isElementAccessExpression(node) || ts9.isIdentifier(node) || ts9.isJSDocSignature(node) || ts9.isObjectLiteralExpression(node) || ts9.isPropertyAccessExpression(node) || ts9.isTypeParameterDeclaration(node))) { + return true; + } + return false; +} +function hasModifiers(node) { + return ts9.isTypeParameterDeclaration(node) || ts9.isParameter(node) || ts9.isConstructorTypeNode(node) || ts9.isPropertySignature(node) || ts9.isPropertyDeclaration(node) || ts9.isMethodSignature(node) || ts9.isMethodDeclaration(node) || ts9.isConstructorDeclaration(node) || ts9.isGetAccessorDeclaration(node) || ts9.isSetAccessorDeclaration(node) || ts9.isIndexSignatureDeclaration(node) || ts9.isFunctionExpression(node) || ts9.isArrowFunction(node) || ts9.isClassExpression(node) || ts9.isVariableStatement(node) || ts9.isFunctionDeclaration(node) || ts9.isClassDeclaration(node) || ts9.isInterfaceDeclaration(node) || ts9.isTypeAliasDeclaration(node) || ts9.isEnumDeclaration(node) || ts9.isModuleDeclaration(node) || ts9.isImportEqualsDeclaration(node) || ts9.isImportDeclaration(node) || ts9.isExportAssignment(node) || ts9.isExportDeclaration(node); +} +function hasType(node) { + return isSignatureDeclaration(node) || ts9.isVariableDeclaration(node) || ts9.isParameter(node) || ts9.isPropertySignature(node) || ts9.isPropertyDeclaration(node) || ts9.isTypePredicateNode(node) || ts9.isParenthesizedTypeNode(node) || ts9.isTypeOperatorNode(node) || ts9.isMappedTypeNode(node) || ts9.isAssertionExpression(node) || ts9.isTypeAliasDeclaration(node) || ts9.isJSDocTypeExpression(node) || ts9.isJSDocNonNullableType(node) || ts9.isJSDocNullableType(node) || ts9.isJSDocOptionalType(node) || ts9.isJSDocVariadicType(node); +} +function hasTypeArguments(node) { + return ts9.isCallExpression(node) || ts9.isNewExpression(node) || ts9.isTaggedTemplateExpression(node) || ts9.isJsxOpeningElement(node) || ts9.isJsxSelfClosingElement(node); +} +function isAccessExpression(node) { + return ts9.isPropertyAccessExpression(node) || ts9.isElementAccessExpression(node); +} +function isAccessibilityModifier(node) { + return isPublicKeyword(node) || isPrivateKeyword(node) || isProtectedKeyword(node); +} +function isAccessorDeclaration(node) { + return ts9.isGetAccessorDeclaration(node) || ts9.isSetAccessorDeclaration(node); +} +function isArrayBindingElement(node) { + return ts9.isBindingElement(node) || ts9.isOmittedExpression(node); +} +function isArrayBindingOrAssignmentPattern(node) { + return ts9.isArrayBindingPattern(node) || ts9.isArrayLiteralExpression(node); +} +function isAssignmentPattern(node) { + return ts9.isObjectLiteralExpression(node) || ts9.isArrayLiteralExpression(node); +} +function isBindingOrAssignmentElementRestIndicator(node) { + if (ts9.isSpreadElement(node) || ts9.isSpreadAssignment(node)) { + return true; + } + if (isTsVersionAtLeast(4, 4)) { + return ts9.isDotDotDotToken(node); + } + return false; +} +function isBindingOrAssignmentElementTarget(node) { + return isBindingOrAssignmentPattern(node) || ts9.isIdentifier(node) || ts9.isPropertyAccessExpression(node) || ts9.isElementAccessExpression(node) || ts9.isOmittedExpression(node); +} +function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) || isArrayBindingOrAssignmentPattern(node); +} +function isBindingPattern(node) { + return ts9.isObjectBindingPattern(node) || ts9.isArrayBindingPattern(node); +} +function isBlockLike(node) { + return ts9.isSourceFile(node) || ts9.isBlock(node) || ts9.isModuleBlock(node) || ts9.isCaseOrDefaultClause(node); +} +function isBooleanLiteral(node) { + return isTrueLiteral(node) || isFalseLiteral(node); +} +function isClassLikeDeclaration(node) { + return ts9.isClassDeclaration(node) || ts9.isClassExpression(node); +} +function isClassMemberModifier(node) { + return isAccessibilityModifier(node) || isReadonlyKeyword(node) || isStaticKeyword(node) || isAccessorKeyword(node); +} +function isDeclarationName(node) { + return ts9.isIdentifier(node) || ts9.isPrivateIdentifier(node) || ts9.isStringLiteralLike(node) || ts9.isNumericLiteral(node) || ts9.isComputedPropertyName(node) || ts9.isElementAccessExpression(node) || isBindingPattern(node) || isEntityNameExpression(node); +} +function isDeclarationWithTypeParameterChildren(node) { + return isSignatureDeclaration(node) || // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isClassLikeDeclaration(node) || ts9.isInterfaceDeclaration(node) || ts9.isTypeAliasDeclaration(node) || ts9.isJSDocTemplateTag(node); +} +function isDeclarationWithTypeParameters(node) { + return isDeclarationWithTypeParameterChildren(node) || ts9.isJSDocTypedefTag(node) || ts9.isJSDocCallbackTag(node) || ts9.isJSDocSignature(node); +} +function isDestructuringPattern(node) { + return isBindingPattern(node) || ts9.isObjectLiteralExpression(node) || ts9.isArrayLiteralExpression(node); +} +function isEntityNameExpression(node) { + return ts9.isIdentifier(node) || isPropertyAccessEntityNameExpression(node); +} +function isEntityNameOrEntityNameExpression(node) { + return ts9.isEntityName(node) || isEntityNameExpression(node); +} +function isForInOrOfStatement(node) { + return ts9.isForInStatement(node) || ts9.isForOfStatement(node); +} +function isFunctionLikeDeclaration(node) { + return ts9.isFunctionDeclaration(node) || ts9.isMethodDeclaration(node) || ts9.isGetAccessorDeclaration(node) || ts9.isSetAccessorDeclaration(node) || ts9.isConstructorDeclaration(node) || ts9.isFunctionExpression(node) || ts9.isArrowFunction(node); +} +function isJSDocComment(node) { + if (isJSDocText(node)) { + return true; + } + if (isTsVersionAtLeast(4, 4)) { + return ts9.isJSDocLink(node) || ts9.isJSDocLinkCode(node) || ts9.isJSDocLinkPlain(node); + } + return false; +} +function isJSDocNamespaceBody(node) { + return ts9.isIdentifier(node) || isJSDocNamespaceDeclaration(node); +} +function isJSDocTypeReferencingNode(node) { + return ts9.isJSDocVariadicType(node) || ts9.isJSDocOptionalType(node) || ts9.isJSDocNullableType(node) || ts9.isJSDocNonNullableType(node); +} +function isJsonObjectExpression(node) { + return ts9.isObjectLiteralExpression(node) || ts9.isArrayLiteralExpression(node) || isJsonMinusNumericLiteral(node) || ts9.isNumericLiteral(node) || ts9.isStringLiteral(node) || isBooleanLiteral(node) || isNullLiteral(node); +} +function isJsxAttributeLike(node) { + return ts9.isJsxAttribute(node) || ts9.isJsxSpreadAttribute(node); +} +function isJsxAttributeValue(node) { + return ts9.isStringLiteral(node) || ts9.isJsxExpression(node) || ts9.isJsxElement(node) || ts9.isJsxSelfClosingElement(node) || ts9.isJsxFragment(node); +} +function isJsxChild(node) { + return ts9.isJsxText(node) || ts9.isJsxExpression(node) || ts9.isJsxElement(node) || ts9.isJsxSelfClosingElement(node) || ts9.isJsxFragment(node); +} +function isJsxTagNameExpression(node) { + return ts9.isIdentifier(node) || isThisExpression(node) || isJsxTagNamePropertyAccess(node); +} +function isLiteralToken(node) { + return ts9.isNumericLiteral(node) || ts9.isBigIntLiteral(node) || ts9.isStringLiteral(node) || ts9.isJsxText(node) || ts9.isRegularExpressionLiteral(node) || ts9.isNoSubstitutionTemplateLiteral(node); +} +function isModuleBody(node) { + return isNamespaceBody(node) || isJSDocNamespaceBody(node); +} +function isModuleName(node) { + return ts9.isIdentifier(node) || ts9.isStringLiteral(node); +} +function isModuleReference(node) { + return ts9.isEntityName(node) || ts9.isExternalModuleReference(node); +} +function isNamedImportBindings(node) { + return ts9.isNamespaceImport(node) || ts9.isNamedImports(node); +} +function isNamedImportsOrExports(node) { + return ts9.isNamedImports(node) || ts9.isNamedExports(node); +} +function isNamespaceBody(node) { + return ts9.isModuleBlock(node) || isNamespaceDeclaration(node); +} +function isObjectBindingOrAssignmentElement(node) { + return ts9.isBindingElement(node) || ts9.isPropertyAssignment(node) || ts9.isShorthandPropertyAssignment(node) || ts9.isSpreadAssignment(node); +} +function isObjectBindingOrAssignmentPattern(node) { + return ts9.isObjectBindingPattern(node) || ts9.isObjectLiteralExpression(node); +} +function isObjectTypeDeclaration(node) { + return ( + // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isClassLikeDeclaration(node) || ts9.isInterfaceDeclaration(node) || ts9.isTypeLiteralNode(node) + ); +} +function isParameterPropertyModifier(node) { + return isAccessibilityModifier(node) || isReadonlyKeyword(node); +} +function isPropertyNameLiteral(node) { + return ts9.isIdentifier(node) || ts9.isStringLiteralLike(node) || ts9.isNumericLiteral(node); +} +function isPseudoLiteralToken(node) { + return ts9.isTemplateHead(node) || ts9.isTemplateMiddle(node) || ts9.isTemplateTail(node); +} +function isSignatureDeclaration(node) { + return ts9.isCallSignatureDeclaration(node) || ts9.isConstructSignatureDeclaration(node) || ts9.isMethodSignature(node) || ts9.isIndexSignatureDeclaration(node) || ts9.isFunctionTypeNode(node) || ts9.isConstructorTypeNode(node) || ts9.isJSDocFunctionType(node) || ts9.isFunctionDeclaration(node) || ts9.isMethodDeclaration(node) || ts9.isConstructorDeclaration(node) || // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts <5 + isAccessorDeclaration(node) || ts9.isFunctionExpression(node) || ts9.isArrowFunction(node); +} +function isSuperProperty(node) { + return isSuperPropertyAccessExpression(node) || isSuperElementAccessExpression(node); +} +function isTypeOnlyCompatibleAliasDeclaration(node) { + if (ts9.isImportClause(node) || ts9.isImportEqualsDeclaration(node) || ts9.isNamespaceImport(node) || ts9.isImportOrExportSpecifier(node)) { + return true; + } + if (isTsVersionAtLeast(5, 0) && (ts9.isExportDeclaration(node) || ts9.isNamespaceExport(node))) { + return true; + } + return false; +} +function isTypeReferenceType(node) { + return ts9.isTypeReferenceNode(node) || ts9.isExpressionWithTypeArguments(node); +} +function isUnionOrIntersectionTypeNode(node) { + return ts9.isUnionTypeNode(node) || ts9.isIntersectionTypeNode(node); +} +function isVariableLikeDeclaration(node) { + return ts9.isVariableDeclaration(node) || ts9.isParameter(node) || ts9.isBindingElement(node) || ts9.isPropertyDeclaration(node) || ts9.isPropertyAssignment(node) || ts9.isPropertySignature(node) || ts9.isJsxAttribute(node) || ts9.isShorthandPropertyAssignment(node) || ts9.isEnumMember(node) || ts9.isJSDocPropertyTag(node) || ts9.isJSDocParameterTag(node); +} + +// src/nodes/typeGuards/compound.ts +function isConstAssertionExpression(node) { + return ts9.isTypeReferenceNode(node.type) && ts9.isIdentifier(node.type.typeName) && node.type.typeName.escapedText === "const"; +} +function isIterationStatement(node) { + switch (node.kind) { + case ts9.SyntaxKind.DoStatement: + case ts9.SyntaxKind.ForInStatement: + case ts9.SyntaxKind.ForOfStatement: + case ts9.SyntaxKind.ForStatement: + case ts9.SyntaxKind.WhileStatement: + return true; + default: + return false; + } +} +function isJSDocNamespaceDeclaration(node) { + return ts9.isModuleDeclaration(node) && ts9.isIdentifier(node.name) && (node.body === undefined || isJSDocNamespaceBody(node.body)); +} +function isJsxTagNamePropertyAccess(node) { + return ts9.isPropertyAccessExpression(node) && // eslint-disable-next-line @typescript-eslint/no-deprecated -- Keep compatibility with ts < 5 + isJsxTagNameExpression(node.expression); +} +function isNamedDeclarationWithName(node) { + return "name" in node && node.name !== undefined && node.name !== null && isDeclarationName(node.name); +} +function isNamespaceDeclaration(node) { + return ts9.isModuleDeclaration(node) && ts9.isIdentifier(node.name) && node.body !== undefined && isNamespaceBody(node.body); +} +function isNumericOrStringLikeLiteral(node) { + switch (node.kind) { + case ts9.SyntaxKind.NoSubstitutionTemplateLiteral: + case ts9.SyntaxKind.NumericLiteral: + case ts9.SyntaxKind.StringLiteral: + return true; + default: + return false; + } +} +function isPropertyAccessEntityNameExpression(node) { + return ts9.isPropertyAccessExpression(node) && ts9.isIdentifier(node.name) && isEntityNameExpression(node.expression); +} +function isSuperElementAccessExpression(node) { + return ts9.isElementAccessExpression(node) && isSuperExpression(node.expression); +} +function isSuperPropertyAccessExpression(node) { + return ts9.isPropertyAccessExpression(node) && isSuperExpression(node.expression); +} +function isFunctionScopeBoundary(node) { + switch (node.kind) { + case ts9.SyntaxKind.ArrowFunction: + case ts9.SyntaxKind.CallSignature: + case ts9.SyntaxKind.ClassDeclaration: + case ts9.SyntaxKind.ClassExpression: + case ts9.SyntaxKind.Constructor: + case ts9.SyntaxKind.ConstructorType: + case ts9.SyntaxKind.ConstructSignature: + case ts9.SyntaxKind.EnumDeclaration: + case ts9.SyntaxKind.FunctionDeclaration: + case ts9.SyntaxKind.FunctionExpression: + case ts9.SyntaxKind.FunctionType: + case ts9.SyntaxKind.GetAccessor: + case ts9.SyntaxKind.MethodDeclaration: + case ts9.SyntaxKind.MethodSignature: + case ts9.SyntaxKind.ModuleDeclaration: + case ts9.SyntaxKind.SetAccessor: + return true; + case ts9.SyntaxKind.SourceFile: + return ts9.isExternalModule(node); + default: + return false; + } +} +function isIntrinsicAnyType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Any); +} +function isIntrinsicBigIntType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.BigInt); +} +function isIntrinsicBooleanType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Boolean); +} +function isIntrinsicErrorType(type) { + return isIntrinsicType(type) && type.intrinsicName === "error"; +} +function isIntrinsicESSymbolType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.ESSymbol); +} +var IntrinsicTypeFlags = ts9.TypeFlags.Intrinsic ?? ts9.TypeFlags.Any | ts9.TypeFlags.Unknown | ts9.TypeFlags.String | ts9.TypeFlags.Number | ts9.TypeFlags.BigInt | ts9.TypeFlags.Boolean | ts9.TypeFlags.BooleanLiteral | ts9.TypeFlags.ESSymbol | ts9.TypeFlags.Void | ts9.TypeFlags.Undefined | ts9.TypeFlags.Null | ts9.TypeFlags.Never | ts9.TypeFlags.NonPrimitive; +function isIntrinsicNeverType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Never); +} +function isIntrinsicNonPrimitiveType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.NonPrimitive); +} +function isIntrinsicNullType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Null); +} +function isIntrinsicNumberType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Number); +} +function isIntrinsicStringType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.String); +} +function isIntrinsicType(type) { + return isTypeFlagSet(type, IntrinsicTypeFlags); +} +function isIntrinsicUndefinedType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Undefined); +} +function isIntrinsicUnknownType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Unknown); +} +function isIntrinsicVoidType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Void); +} +function isConditionalType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Conditional); +} +function isEnumType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Enum); +} +function isFreshableType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Freshable); +} +function isIndexedAccessType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.IndexedAccess); +} +function isIndexType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Index); +} +function isInstantiableType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Instantiable); +} +function isIntersectionType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Intersection); +} +function isObjectType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Object); +} +function isStringMappingType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.StringMapping); +} +function isSubstitutionType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Substitution); +} +function isTypeParameter(type) { + return isTypeFlagSet(type, ts9.TypeFlags.TypeParameter); +} +function isTypeVariable(type) { + return isTypeFlagSet(type, ts9.TypeFlags.TypeVariable); +} +function isUnionOrIntersectionType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.UnionOrIntersection); +} +function isUnionType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Union); +} +function isUniqueESSymbolType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.UniqueESSymbol); +} + +// src/types/typeGuards/objects.ts +function isEvolvingArrayType(type) { + return isObjectType(type) && isObjectFlagSet(type, ts9.ObjectFlags.EvolvingArray); +} +function isTupleType(type) { + return isObjectType(type) && isObjectFlagSet(type, ts9.ObjectFlags.Tuple); +} +function isTypeReference(type) { + return isObjectType(type) && isObjectFlagSet(type, ts9.ObjectFlags.Reference); +} + +// src/types/typeGuards/compound.ts +function isFreshableIntrinsicType(type) { + return isIntrinsicType(type) && isFreshableType(type); +} +function isTupleTypeReference(type) { + return isTypeReference(type) && isTupleType(type.target); +} +function isBigIntLiteralType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.BigIntLiteral); +} +function isBooleanLiteralType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.BooleanLiteral); +} +function isFalseLiteralType(type) { + return isBooleanLiteralType(type) && type.intrinsicName === "false"; +} +function isLiteralType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.Literal); +} +function isNumberLiteralType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.NumberLiteral); +} +function isStringLiteralType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.StringLiteral); +} +function isTemplateLiteralType(type) { + return isTypeFlagSet(type, ts9.TypeFlags.TemplateLiteral); +} +function isTrueLiteralType(type) { + return isBooleanLiteralType(type) && type.intrinsicName === "true"; +} + +// src/types/getters.ts +function getCallSignaturesOfType(type) { + if (isUnionType(type)) { + const signatures = []; + for (const subType of type.types) { + signatures.push(...getCallSignaturesOfType(subType)); + } + return signatures; + } + if (isIntersectionType(type)) { + let signatures; + for (const subType of type.types) { + const sig = getCallSignaturesOfType(subType); + if (sig.length !== 0) { + if (signatures !== undefined) { + return []; + } + signatures = sig; + } + } + return signatures === undefined ? [] : signatures; + } + return type.getCallSignatures(); +} +function getPropertyOfType(type, name) { + if (!name.startsWith("__")) { + return type.getProperty(name); + } + return type.getProperties().find((s) => s.escapedName === name); +} +function getWellKnownSymbolPropertyOfType(type, wellKnownSymbolName, typeChecker) { + const prefix = "__@" + wellKnownSymbolName; + for (const prop of type.getProperties()) { + if (!prop.name.startsWith(prefix)) { + continue; + } + const declaration = prop.valueDeclaration ?? prop.getDeclarations()?.[0]; + if (!declaration || !isNamedDeclarationWithName(declaration) || declaration.name === undefined || !ts9.isComputedPropertyName(declaration.name)) { + continue; + } + const globalSymbol = typeChecker.getApparentType( + typeChecker.getTypeAtLocation(declaration.name.expression) + ).symbol; + if (prop.escapedName === getPropertyNameOfWellKnownSymbol( + typeChecker, + globalSymbol, + wellKnownSymbolName + )) { + return prop; + } + } + return undefined; +} +function getPropertyNameOfWellKnownSymbol(typeChecker, symbolConstructor, symbolName) { + const knownSymbol = symbolConstructor && typeChecker.getTypeOfSymbolAtLocation( + symbolConstructor, + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access + symbolConstructor.valueDeclaration + ).getProperty(symbolName); + const knownSymbolType = knownSymbol && typeChecker.getTypeOfSymbolAtLocation( + knownSymbol, + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access + knownSymbol.valueDeclaration + ); + if (knownSymbolType && isUniqueESSymbolType(knownSymbolType)) { + return knownSymbolType.escapedName; + } + return "__@" + symbolName; +} +function isBindableObjectDefinePropertyCall(node) { + return node.arguments.length === 3 && isEntityNameExpression(node.arguments[0]) && isNumericOrStringLikeLiteral(node.arguments[1]) && ts9.isPropertyAccessExpression(node.expression) && node.expression.name.escapedText === "defineProperty" && ts9.isIdentifier(node.expression.expression) && node.expression.expression.escapedText === "Object"; +} +function isInConstContext(node, typeChecker) { + let current = node; + while (true) { + const parent = current.parent; + outer: switch (parent.kind) { + case ts9.SyntaxKind.ArrayLiteralExpression: + case ts9.SyntaxKind.ObjectLiteralExpression: + case ts9.SyntaxKind.ParenthesizedExpression: + case ts9.SyntaxKind.TemplateExpression: + current = parent; + break; + case ts9.SyntaxKind.AsExpression: + case ts9.SyntaxKind.TypeAssertionExpression: + return isConstAssertionExpression(parent); + case ts9.SyntaxKind.CallExpression: { + if (!ts9.isExpression(current)) { + return false; + } + const functionSignature = typeChecker.getResolvedSignature( + parent + ); + if (functionSignature === undefined) { + return false; + } + const argumentIndex = parent.arguments.indexOf( + current + ); + if (argumentIndex < 0) { + return false; + } + const parameterSymbol = functionSignature.getParameters()[argumentIndex]; + if (parameterSymbol === undefined || !("links" in parameterSymbol)) { + return false; + } + const parameterSymbolLinks = parameterSymbol.links; + const propertySymbol = parameterSymbolLinks.type?.getProperties()?.[argumentIndex]; + if (propertySymbol === undefined || !("links" in propertySymbol)) { + return false; + } + return isTransientSymbolLinksFlagSet( + propertySymbol.links, + ts9.CheckFlags.Readonly + ); + } + case ts9.SyntaxKind.PrefixUnaryExpression: + if (current.kind !== ts9.SyntaxKind.NumericLiteral) { + return false; + } + switch (parent.operator) { + case ts9.SyntaxKind.MinusToken: + case ts9.SyntaxKind.PlusToken: + current = parent; + break outer; + default: + return false; + } + case ts9.SyntaxKind.PropertyAssignment: + if (parent.initializer !== current) { + return false; + } + current = parent.parent; + break; + case ts9.SyntaxKind.ShorthandPropertyAssignment: + current = parent.parent; + break; + default: + return false; + } + } +} + +// src/types/utilities.ts +function intersectionConstituents(type) { + return isIntersectionType(type) ? type.types : [type]; +} +var intersectionTypeParts = intersectionConstituents; +function isFalsyType(type) { + if (isTypeFlagSet( + type, + ts9.TypeFlags.Undefined | ts9.TypeFlags.Null | ts9.TypeFlags.Void + )) { + return true; + } + if (typeIsLiteral(type)) { + if (typeof type.value === "object") { + return type.value.base10Value === "0"; + } else { + return !type.value; + } + } + return isFalseLiteralType(type); +} +function isPropertyReadonlyInType(type, name, typeChecker) { + let seenProperty = false; + let seenReadonlySignature = false; + for (const subType of unionConstituents(type)) { + if (getPropertyOfType(subType, name) === undefined) { + const index = (isNumericPropertyName(name) ? typeChecker.getIndexInfoOfType(subType, ts9.IndexKind.Number) : undefined) ?? typeChecker.getIndexInfoOfType(subType, ts9.IndexKind.String); + if (index?.isReadonly) { + if (seenProperty) { + return true; + } + seenReadonlySignature = true; + } + } else if (seenReadonlySignature || isReadonlyPropertyIntersection(subType, name, typeChecker)) { + return true; + } else { + seenProperty = true; + } + } + return false; +} +function isThenableType(typeChecker, node, type = typeChecker.getTypeAtLocation(node)) { + for (const constituent of unionConstituents( + typeChecker.getApparentType(type) + )) { + const then = constituent.getProperty("then"); + if (then === undefined) { + continue; + } + const thenType = typeChecker.getTypeOfSymbolAtLocation(then, node); + for (const subConstituent of unionConstituents(thenType)) { + for (const signature of subConstituent.getCallSignatures()) { + if (signature.parameters.length !== 0 && isCallback(typeChecker, signature.parameters[0], node)) { + return true; + } + } + } + } + return false; +} +function symbolHasReadonlyDeclaration(symbol, typeChecker) { + return !!((symbol.flags & ts9.SymbolFlags.Accessor) === ts9.SymbolFlags.GetAccessor || symbol.declarations?.some( + (node) => isModifierFlagSet(node, ts9.ModifierFlags.Readonly) || ts9.isVariableDeclaration(node) && isNodeFlagSet(node.parent, ts9.NodeFlags.Const) || ts9.isCallExpression(node) && isReadonlyAssignmentDeclaration(node, typeChecker) || ts9.isEnumMember(node) || (ts9.isPropertyAssignment(node) || ts9.isShorthandPropertyAssignment(node)) && isInConstContext(node, typeChecker) + )); +} +function typeConstituents(type) { + return isIntersectionType(type) || isUnionType(type) ? type.types : [type]; +} +function typeIsLiteral(type) { + if (isTsVersionAtLeast(5, 0)) { + return type.isLiteral(); + } else { + return isTypeFlagSet( + type, + ts9.TypeFlags.StringLiteral | ts9.TypeFlags.NumberLiteral | ts9.TypeFlags.BigIntLiteral + ); + } +} +var typeParts = typeConstituents; +function unionConstituents(type) { + return isUnionType(type) ? type.types : [type]; +} +var unionTypeParts = unionConstituents; +function isCallback(typeChecker, param, node) { + let type = typeChecker.getApparentType( + typeChecker.getTypeOfSymbolAtLocation(param, node) + ); + if (param.valueDeclaration.dotDotDotToken) { + type = type.getNumberIndexType(); + if (type === undefined) { + return false; + } + } + for (const subType of unionConstituents(type)) { + if (subType.getCallSignatures().length !== 0) { + return true; + } + } + return false; +} +function isReadonlyAssignmentDeclaration(node, typeChecker) { + if (!isBindableObjectDefinePropertyCall(node)) { + return false; + } + const descriptorType = typeChecker.getTypeAtLocation(node.arguments[2]); + if (descriptorType.getProperty("value") === undefined) { + return descriptorType.getProperty("set") === undefined; + } + const writableProp = descriptorType.getProperty("writable"); + if (writableProp === undefined) { + return false; + } + const writableType = writableProp.valueDeclaration !== undefined && ts9.isPropertyAssignment(writableProp.valueDeclaration) ? typeChecker.getTypeAtLocation(writableProp.valueDeclaration.initializer) : typeChecker.getTypeOfSymbolAtLocation(writableProp, node.arguments[2]); + return isFalseLiteralType(writableType); +} +function isReadonlyPropertyFromMappedType(type, name, typeChecker) { + if (!isObjectType(type) || !isObjectFlagSet(type, ts9.ObjectFlags.Mapped)) { + return; + } + const declaration = type.symbol.declarations[0]; + if (declaration.readonlyToken !== undefined && !/^__@[^@]+$/.test(name)) { + return declaration.readonlyToken.kind !== ts9.SyntaxKind.MinusToken; + } + const { modifiersType } = type; + return modifiersType && isPropertyReadonlyInType(modifiersType, name, typeChecker); +} +function isReadonlyPropertyIntersection(type, name, typeChecker) { + const constituents = intersectionConstituents(type); + return constituents.some((constituent) => { + const prop = getPropertyOfType(constituent, name); + if (prop === undefined) { + return false; + } + if (prop.flags & ts9.SymbolFlags.Transient) { + if (/^(?:[1-9]\d*|0)$/.test(name) && isTupleTypeReference(constituent)) { + return constituent.target.readonly; + } + switch (isReadonlyPropertyFromMappedType(constituent, name, typeChecker)) { + case false: + return false; + case true: + return true; + } + } + return !!// members of namespace import + (isSymbolFlagSet(prop, ts9.SymbolFlags.ValueModule) || // we unwrapped every mapped type, now we can check the actual declarations + symbolHasReadonlyDeclaration(prop, typeChecker)); + }); +} +function identifierToKeywordKind(node) { + return "originalKeywordKind" in node ? node.originalKeywordKind : ts9.identifierToKeywordKind(node); +} + +// src/usage/declarations.ts +var DeclarationDomain = /* @__PURE__ */ ((DeclarationDomain2) => { + DeclarationDomain2[DeclarationDomain2["Namespace"] = 1] = "Namespace"; + DeclarationDomain2[DeclarationDomain2["Type"] = 2] = "Type"; + DeclarationDomain2[DeclarationDomain2["Value"] = 4] = "Value"; + DeclarationDomain2[DeclarationDomain2["Any"] = 7] = "Any"; + DeclarationDomain2[DeclarationDomain2["Import"] = 8] = "Import"; + return DeclarationDomain2; +})(DeclarationDomain || {}); +function getDeclarationDomain(node) { + switch (node.parent.kind) { + case ts9.SyntaxKind.ClassDeclaration: + case ts9.SyntaxKind.ClassExpression: + return 2 /* Type */ | 4 /* Value */; + case ts9.SyntaxKind.EnumDeclaration: + return 7 /* Any */; + case ts9.SyntaxKind.FunctionDeclaration: + case ts9.SyntaxKind.FunctionExpression: + return 4 /* Value */; + case ts9.SyntaxKind.ImportClause: + case ts9.SyntaxKind.NamespaceImport: + return 7 /* Any */ | 8 /* Import */; + // TODO handle type-only imports + case ts9.SyntaxKind.ImportEqualsDeclaration: + case ts9.SyntaxKind.ImportSpecifier: + return node.parent.name === node ? 7 /* Any */ | 8 /* Import */ : undefined; + case ts9.SyntaxKind.InterfaceDeclaration: + case ts9.SyntaxKind.TypeAliasDeclaration: + case ts9.SyntaxKind.TypeParameter: + return 2 /* Type */; + case ts9.SyntaxKind.ModuleDeclaration: + return 1 /* Namespace */; + case ts9.SyntaxKind.Parameter: + if (node.parent.parent.kind === ts9.SyntaxKind.IndexSignature || identifierToKeywordKind(node) === ts9.SyntaxKind.ThisKeyword) { + return; + } + // falls through + case ts9.SyntaxKind.BindingElement: + case ts9.SyntaxKind.VariableDeclaration: + return node.parent.name === node ? 4 /* Value */ : undefined; + } +} +function getPropertyName(propertyName) { + if (propertyName.kind === ts9.SyntaxKind.ComputedPropertyName) { + const expression = unwrapParentheses(propertyName.expression); + if (ts9.isPrefixUnaryExpression(expression)) { + let negate = false; + switch (expression.operator) { + case ts9.SyntaxKind.MinusToken: + negate = true; + // falls through + case ts9.SyntaxKind.PlusToken: + return ts9.isNumericLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text}` : ts9.isBigIntLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text.slice(0, -1)}` : undefined; + default: + return; + } + } + if (ts9.isBigIntLiteral(expression)) { + return expression.text.slice(0, -1); + } + if (isNumericOrStringLikeLiteral(expression)) { + return expression.text; + } + return; + } + return propertyName.kind === ts9.SyntaxKind.PrivateIdentifier ? undefined : propertyName.text; +} +function unwrapParentheses(node) { + while (node.kind === ts9.SyntaxKind.ParenthesizedExpression) { + node = node.expression; + } + return node; +} +var UsageDomain = /* @__PURE__ */ ((UsageDomain2) => { + UsageDomain2[UsageDomain2["Namespace"] = 1] = "Namespace"; + UsageDomain2[UsageDomain2["Type"] = 2] = "Type"; + UsageDomain2[UsageDomain2["Value"] = 4] = "Value"; + UsageDomain2[UsageDomain2["Any"] = 7] = "Any"; + UsageDomain2[UsageDomain2["TypeQuery"] = 8] = "TypeQuery"; + UsageDomain2[UsageDomain2["ValueOrNamespace"] = 5] = "ValueOrNamespace"; + return UsageDomain2; +})(UsageDomain || {}); +function getUsageDomain(node) { + const parent = node.parent; + switch (parent.kind) { + // Value + case ts9.SyntaxKind.BindingElement: + if (parent.initializer === node) { + return 5 /* ValueOrNamespace */; + } + break; + case ts9.SyntaxKind.BreakStatement: + case ts9.SyntaxKind.ClassDeclaration: + case ts9.SyntaxKind.ClassExpression: + case ts9.SyntaxKind.ContinueStatement: + case ts9.SyntaxKind.EnumDeclaration: + case ts9.SyntaxKind.FunctionDeclaration: + case ts9.SyntaxKind.FunctionExpression: + case ts9.SyntaxKind.GetAccessor: + case ts9.SyntaxKind.ImportClause: + case ts9.SyntaxKind.ImportSpecifier: + case ts9.SyntaxKind.InterfaceDeclaration: + case ts9.SyntaxKind.JsxAttribute: + case ts9.SyntaxKind.LabeledStatement: + case ts9.SyntaxKind.MethodDeclaration: + case ts9.SyntaxKind.MethodSignature: + case ts9.SyntaxKind.ModuleDeclaration: + case ts9.SyntaxKind.NamedTupleMember: + case ts9.SyntaxKind.NamespaceExport: + case ts9.SyntaxKind.NamespaceExportDeclaration: + case ts9.SyntaxKind.NamespaceImport: + case ts9.SyntaxKind.PropertySignature: + case ts9.SyntaxKind.SetAccessor: + case ts9.SyntaxKind.TypeAliasDeclaration: + case ts9.SyntaxKind.TypeParameter: + case ts9.SyntaxKind.TypePredicate: + break; + case ts9.SyntaxKind.EnumMember: + case ts9.SyntaxKind.ImportEqualsDeclaration: + case ts9.SyntaxKind.Parameter: + case ts9.SyntaxKind.PropertyAccessExpression: + case ts9.SyntaxKind.PropertyAssignment: + case ts9.SyntaxKind.PropertyDeclaration: + case ts9.SyntaxKind.VariableDeclaration: + if (parent.name !== node) { + return 5 /* ValueOrNamespace */; + } + break; + case ts9.SyntaxKind.ExportAssignment: + return 7 /* Any */; + case ts9.SyntaxKind.ExportSpecifier: + if (parent.propertyName === undefined || parent.propertyName === node) { + return 7 /* Any */; + } + break; + case ts9.SyntaxKind.ExpressionWithTypeArguments: + return parent.parent.token === ts9.SyntaxKind.ImplementsKeyword || parent.parent.parent.kind === ts9.SyntaxKind.InterfaceDeclaration ? 2 /* Type */ : 4 /* Value */; + case ts9.SyntaxKind.QualifiedName: + if (parent.left === node) { + if (getEntityNameParent(parent).kind === ts9.SyntaxKind.TypeQuery) { + return 1 /* Namespace */ | 8 /* TypeQuery */; + } + return 1 /* Namespace */; + } + break; + case ts9.SyntaxKind.TypeQuery: + return 5 /* ValueOrNamespace */ | 8 /* TypeQuery */; + case ts9.SyntaxKind.TypeReference: + return identifierToKeywordKind(node) !== ts9.SyntaxKind.ConstKeyword ? 2 /* Type */ : undefined; + default: + return 5 /* ValueOrNamespace */; + } +} +function getEntityNameParent(name) { + let parent = name.parent; + while (parent.kind === ts9.SyntaxKind.QualifiedName) { + parent = parent.parent; + } + return parent; +} +function isBlockScopeBoundary(node) { + switch (node.kind) { + case ts9.SyntaxKind.Block: { + const parent = node.parent; + return parent.kind !== ts9.SyntaxKind.CatchClause && // blocks inside SourceFile are block scope boundaries + (parent.kind === ts9.SyntaxKind.SourceFile || // blocks that are direct children of a function scope boundary are no scope boundary + // for example the FunctionBlock is part of the function scope of the containing function + !isFunctionScopeBoundary(parent)) ? 2 /* Block */ : 0 /* None */; + } + case ts9.SyntaxKind.CaseBlock: + case ts9.SyntaxKind.CatchClause: + case ts9.SyntaxKind.ForInStatement: + case ts9.SyntaxKind.ForOfStatement: + case ts9.SyntaxKind.ForStatement: + case ts9.SyntaxKind.WithStatement: + return 2 /* Block */; + default: + return 0 /* None */; + } +} + +// src/usage/scopes.ts +var AbstractScope = class { + constructor(global) { + this.global = global; + } + namespaceScopes = undefined; + uses = []; + variables = /* @__PURE__ */ new Map(); + #enumScopes = undefined; + addUse(use) { + this.uses.push(use); + } + addVariable(identifier, name, selector, exported, domain) { + const variables = this.getDestinationScope(selector).getVariables(); + const declaration = { + declaration: name, + domain, + exported + }; + const variable = variables.get(identifier); + if (variable === undefined) { + variables.set(identifier, { + declarations: [declaration], + domain, + uses: [] + }); + } else { + variable.domain |= domain; + variable.declarations.push(declaration); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + createOrReuseEnumScope(name, _exported) { + let scope; + if (this.#enumScopes === undefined) { + this.#enumScopes = /* @__PURE__ */ new Map(); + } else { + scope = this.#enumScopes.get(name); + } + if (scope === undefined) { + scope = new EnumScope(this); + this.#enumScopes.set(name, scope); + } + return scope; + } + // only relevant for the root scope + createOrReuseNamespaceScope(name, _exported, ambient, hasExportStatement) { + let scope; + if (this.namespaceScopes === undefined) { + this.namespaceScopes = /* @__PURE__ */ new Map(); + } else { + scope = this.namespaceScopes.get(name); + } + if (scope === undefined) { + scope = new NamespaceScope(ambient, hasExportStatement, this); + this.namespaceScopes.set(name, scope); + } else { + scope.refresh(ambient, hasExportStatement); + } + return scope; + } + end(cb) { + if (this.namespaceScopes !== undefined) { + this.namespaceScopes.forEach((value) => value.finish(cb)); + } + this.namespaceScopes = this.#enumScopes = undefined; + this.applyUses(); + this.variables.forEach((variable) => { + for (const declaration of variable.declarations) { + const result = { + declarations: [], + domain: declaration.domain, + exported: declaration.exported, + inGlobalScope: this.global, + uses: [] + }; + for (const other of variable.declarations) { + if (other.domain & declaration.domain) { + result.declarations.push(other.declaration); + } + } + for (const use of variable.uses) { + if (use.domain & declaration.domain) { + result.uses.push(use); + } + } + cb(result, declaration.declaration, this); + } + }); + } + getFunctionScope() { + return this; + } + getVariables() { + return this.variables; + } + // eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars + markExported(_name) { + } + // eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars + addUseToParent(_use) { + } + applyUse(use, variables = this.variables) { + const variable = variables.get(use.location.text); + if (variable === undefined || (variable.domain & use.domain) === 0) { + return false; + } + variable.uses.push(use); + return true; + } + applyUses() { + for (const use of this.uses) { + if (!this.applyUse(use)) { + this.addUseToParent(use); + } + } + this.uses = []; + } +}; +var NonRootScope = class extends AbstractScope { + constructor(parent, boundary) { + super(false); + this.parent = parent; + this.boundary = boundary; + } + getDestinationScope(selector) { + return this.boundary & selector ? this : this.parent.getDestinationScope(selector); + } + addUseToParent(use) { + return this.parent.addUse(use, this); + } +}; +var AbstractNamedExpressionScope = class extends NonRootScope { + #domain; + #name; + constructor(name, domain, parent) { + super(parent, 1 /* Function */); + this.#name = name; + this.#domain = domain; + } + addUse(use, source) { + if (source !== this.innerScope) { + return this.innerScope.addUse(use); + } + if (use.domain & this.#domain && use.location.text === this.#name.text) { + this.uses.push(use); + } else { + return this.parent.addUse(use, this); + } + } + end(cb) { + this.innerScope.end(cb); + return cb( + { + declarations: [this.#name], + domain: this.#domain, + exported: false, + inGlobalScope: false, + uses: this.uses + }, + this.#name, + this + ); + } + getDestinationScope() { + return this.innerScope; + } + getFunctionScope() { + return this.innerScope; + } +}; +var BlockScope = class extends NonRootScope { + #functionScope; + constructor(functionScope, parent) { + super(parent, 2 /* Block */); + this.#functionScope = functionScope; + } + getFunctionScope() { + return this.#functionScope; + } +}; +var ClassExpressionScope = class extends AbstractNamedExpressionScope { + innerScope = new NonRootScope(this, 1 /* Function */); + constructor(name, parent) { + super(name, 4 /* Value */ | 2 /* Type */, parent); + } +}; +var ConditionalTypeScope = class extends NonRootScope { + #state = 0 /* Initial */; + constructor(parent) { + super(parent, 8 /* ConditionalType */); + } + addUse(use) { + if (this.#state === 2 /* TrueType */) { + return void this.uses.push(use); + } + return this.parent.addUse(use, this); + } + updateState(newState) { + this.#state = newState; + } +}; +var EnumScope = class extends NonRootScope { + constructor(parent) { + super(parent, 1 /* Function */); + } + end() { + this.applyUses(); + } +}; +var FunctionScope = class extends NonRootScope { + constructor(parent) { + super(parent, 1 /* Function */); + } + beginBody() { + this.applyUses(); + } +}; +var FunctionExpressionScope = class extends AbstractNamedExpressionScope { + innerScope = new FunctionScope(this); + constructor(name, parent) { + super(name, 4 /* Value */, parent); + } + beginBody() { + return this.innerScope.beginBody(); + } +}; +var NamespaceScope = class extends NonRootScope { + #ambient; + #exports = undefined; + #hasExport; + #innerScope = new NonRootScope(this, 1 /* Function */); + constructor(ambient, hasExport, parent) { + super(parent, 1 /* Function */); + this.#ambient = ambient; + this.#hasExport = hasExport; + } + addUse(use, source) { + if (source !== this.#innerScope) { + return this.#innerScope.addUse(use); + } + this.uses.push(use); + } + createOrReuseEnumScope(name, exported) { + if (!exported && (!this.#ambient || this.#hasExport)) { + return this.#innerScope.createOrReuseEnumScope(name, exported); + } + return super.createOrReuseEnumScope(name, exported); + } + createOrReuseNamespaceScope(name, exported, ambient, hasExportStatement) { + if (!exported && (!this.#ambient || this.#hasExport)) { + return this.#innerScope.createOrReuseNamespaceScope( + name, + exported, + ambient || this.#ambient, + hasExportStatement + ); + } + return super.createOrReuseNamespaceScope( + name, + exported, + ambient || this.#ambient, + hasExportStatement + ); + } + end(cb) { + this.#innerScope.end((variable, key, scope) => { + if (scope !== this.#innerScope || !variable.exported && (!this.#ambient || this.#exports !== undefined && !this.#exports.has(key.text))) { + return cb(variable, key, scope); + } + const namespaceVar = this.variables.get(key.text); + if (namespaceVar === undefined) { + this.variables.set(key.text, { + declarations: variable.declarations.map(mapDeclaration), + domain: variable.domain, + uses: [...variable.uses] + }); + } else { + outer: for (const declaration of variable.declarations) { + for (const existing of namespaceVar.declarations) { + if (existing.declaration === declaration) { + continue outer; + } + namespaceVar.declarations.push(mapDeclaration(declaration)); + } + } + namespaceVar.domain |= variable.domain; + for (const use of variable.uses) { + if (namespaceVar.uses.includes(use)) { + continue; + } + namespaceVar.uses.push(use); + } + } + }); + this.applyUses(); + this.#innerScope = new NonRootScope(this, 1 /* Function */); + } + finish(cb) { + return super.end(cb); + } + getDestinationScope() { + return this.#innerScope; + } + markExported(name) { + if (this.#exports === undefined) { + this.#exports = /* @__PURE__ */ new Set(); + } + this.#exports.add(name.text); + } + refresh(ambient, hasExport) { + this.#ambient = ambient; + this.#hasExport = hasExport; + } +}; +var RootScope = class extends AbstractScope { + #exportAll; + #exports = undefined; + #innerScope = new NonRootScope(this, 1 /* Function */); + constructor(exportAll, global) { + super(global); + this.#exportAll = exportAll; + } + addUse(use, origin) { + if (origin === this.#innerScope) { + return super.addUse(use); + } + return this.#innerScope.addUse(use); + } + addVariable(identifier, name, selector, exported, domain) { + if (domain & 8 /* Import */) { + return super.addVariable(identifier, name, selector, exported, domain); + } + return this.#innerScope.addVariable( + identifier, + name, + selector, + exported, + domain + ); + } + end(cb) { + this.#innerScope.end((value, key) => { + value.exported ||= this.#exportAll || this.#exports !== undefined && this.#exports.includes(key.text); + value.inGlobalScope = this.global; + return cb(value, key, this); + }); + return super.end((value, key, scope) => { + value.exported ||= scope === this && this.#exports !== undefined && this.#exports.includes(key.text); + return cb(value, key, scope); + }); + } + getDestinationScope() { + return this; + } + markExported(id) { + if (this.#exports === undefined) { + this.#exports = [id.text]; + } else { + this.#exports.push(id.text); + } + } +}; +function mapDeclaration(declaration) { + return { + declaration, + domain: getDeclarationDomain(declaration), + exported: true + }; +} + +// src/usage/UsageWalker.ts +var UsageWalker = class { + #result = /* @__PURE__ */ new Map(); + #scope; + getUsage(sourceFile) { + const variableCallback = (variable, key) => { + this.#result.set(key, variable); + }; + const isModule = ts9.isExternalModule(sourceFile); + this.#scope = new RootScope( + sourceFile.isDeclarationFile && isModule && !containsExportStatement(sourceFile), + !isModule + ); + const cb = (node) => { + if (isBlockScopeBoundary(node)) { + return continueWithScope( + node, + new BlockScope(this.#scope.getFunctionScope(), this.#scope), + handleBlockScope + ); + } + switch (node.kind) { + case ts9.SyntaxKind.ArrowFunction: + case ts9.SyntaxKind.CallSignature: + case ts9.SyntaxKind.Constructor: + case ts9.SyntaxKind.ConstructorType: + case ts9.SyntaxKind.ConstructSignature: + case ts9.SyntaxKind.FunctionDeclaration: + case ts9.SyntaxKind.FunctionExpression: + case ts9.SyntaxKind.FunctionType: + case ts9.SyntaxKind.GetAccessor: + case ts9.SyntaxKind.MethodDeclaration: + case ts9.SyntaxKind.MethodSignature: + case ts9.SyntaxKind.SetAccessor: + return this.#handleFunctionLikeDeclaration( + node, + cb, + variableCallback + ); + case ts9.SyntaxKind.ClassDeclaration: + this.#handleDeclaration( + node, + true, + 4 /* Value */ | 2 /* Type */ + ); + return continueWithScope( + node, + new NonRootScope(this.#scope, 1 /* Function */) + ); + case ts9.SyntaxKind.ClassExpression: + return continueWithScope( + node, + node.name !== undefined ? new ClassExpressionScope( + node.name, + this.#scope + ) : new NonRootScope(this.#scope, 1 /* Function */) + ); + case ts9.SyntaxKind.ConditionalType: + return this.#handleConditionalType( + node, + cb, + variableCallback + ); + case ts9.SyntaxKind.EnumDeclaration: + this.#handleDeclaration( + node, + true, + 7 /* Any */ + ); + return continueWithScope( + node, + this.#scope.createOrReuseEnumScope( + node.name.text, + includesModifier( + node.modifiers, + ts9.SyntaxKind.ExportKeyword + ) + ) + ); + case ts9.SyntaxKind.EnumMember: + this.#scope.addVariable( + getPropertyName(node.name), + node.name, + 1 /* Function */, + true, + 4 /* Value */ + ); + break; + case ts9.SyntaxKind.ExportAssignment: + if (node.expression.kind === ts9.SyntaxKind.Identifier) { + return this.#scope.markExported( + node.expression + ); + } + break; + case ts9.SyntaxKind.ExportSpecifier: + if (node.propertyName !== undefined) { + return this.#scope.markExported( + node.propertyName, + node.name + ); + } + return this.#scope.markExported(node.name); + case ts9.SyntaxKind.Identifier: { + const domain = getUsageDomain(node); + if (domain !== undefined) { + this.#scope.addUse({ domain, location: node }); + } + return; + } + case ts9.SyntaxKind.ImportClause: + case ts9.SyntaxKind.ImportEqualsDeclaration: + case ts9.SyntaxKind.ImportSpecifier: + case ts9.SyntaxKind.NamespaceImport: + this.#handleDeclaration( + node, + false, + 7 /* Any */ | 8 /* Import */ + ); + break; + case ts9.SyntaxKind.InterfaceDeclaration: + case ts9.SyntaxKind.TypeAliasDeclaration: + this.#handleDeclaration( + node, + true, + 2 /* Type */ + ); + return continueWithScope( + node, + new NonRootScope(this.#scope, 4 /* Type */) + ); + case ts9.SyntaxKind.MappedType: + return continueWithScope( + node, + new NonRootScope(this.#scope, 4 /* Type */) + ); + case ts9.SyntaxKind.ModuleDeclaration: + return this.#handleModule( + node, + continueWithScope + ); + case ts9.SyntaxKind.Parameter: + if (node.parent.kind !== ts9.SyntaxKind.IndexSignature && (node.name.kind !== ts9.SyntaxKind.Identifier || identifierToKeywordKind( + node.name + ) !== ts9.SyntaxKind.ThisKeyword)) { + this.#handleBindingName( + node.name, + false, + false + ); + } + break; + case ts9.SyntaxKind.TypeParameter: + this.#scope.addVariable( + node.name.text, + node.name, + node.parent.kind === ts9.SyntaxKind.InferType ? 8 /* InferType */ : 7 /* Type */, + false, + 2 /* Type */ + ); + break; + // End of Scope specific handling + case ts9.SyntaxKind.VariableDeclarationList: + this.#handleVariableDeclaration(node); + break; + } + return ts9.forEachChild(node, cb); + }; + const continueWithScope = (node, scope, next = forEachChild) => { + const savedScope = this.#scope; + this.#scope = scope; + next(node); + this.#scope.end(variableCallback); + this.#scope = savedScope; + }; + const handleBlockScope = (node) => { + if (node.kind === ts9.SyntaxKind.CatchClause && node.variableDeclaration !== undefined) { + this.#handleBindingName( + node.variableDeclaration.name, + true, + false + ); + } + return ts9.forEachChild(node, cb); + }; + ts9.forEachChild(sourceFile, cb); + this.#scope.end(variableCallback); + return this.#result; + function forEachChild(node) { + return ts9.forEachChild(node, cb); + } + } + #handleBindingName(name, blockScoped, exported) { + if (name.kind === ts9.SyntaxKind.Identifier) { + return this.#scope.addVariable( + name.text, + name, + blockScoped ? 3 /* Block */ : 1 /* Function */, + exported, + 4 /* Value */ + ); + } + forEachDestructuringIdentifier(name, (declaration) => { + this.#scope.addVariable( + declaration.name.text, + declaration.name, + blockScoped ? 3 /* Block */ : 1 /* Function */, + exported, + 4 /* Value */ + ); + }); + } + #handleConditionalType(node, cb, varCb) { + const savedScope = this.#scope; + const scope = this.#scope = new ConditionalTypeScope(savedScope); + cb(node.checkType); + scope.updateState(1 /* Extends */); + cb(node.extendsType); + scope.updateState(2 /* TrueType */); + cb(node.trueType); + scope.updateState(3 /* FalseType */); + cb(node.falseType); + scope.end(varCb); + this.#scope = savedScope; + } + #handleDeclaration(node, blockScoped, domain) { + if (node.name !== undefined) { + this.#scope.addVariable( + node.name.text, + node.name, + blockScoped ? 3 /* Block */ : 1 /* Function */, + includesModifier( + node.modifiers, + ts9.SyntaxKind.ExportKeyword + ), + domain + ); + } + } + #handleFunctionLikeDeclaration(node, cb, varCb) { + if (ts9.canHaveDecorators(node)) { + ts9.getDecorators(node)?.forEach(cb); + } + const savedScope = this.#scope; + if (node.kind === ts9.SyntaxKind.FunctionDeclaration) { + this.#handleDeclaration(node, false, 4 /* Value */); + } + const scope = this.#scope = node.kind === ts9.SyntaxKind.FunctionExpression && node.name !== undefined ? new FunctionExpressionScope(node.name, savedScope) : new FunctionScope(savedScope); + if (node.name !== undefined) { + cb(node.name); + } + if (node.typeParameters !== undefined) { + node.typeParameters.forEach(cb); + } + node.parameters.forEach(cb); + if (node.type !== undefined) { + cb(node.type); + } + if (node.body !== undefined) { + scope.beginBody(); + cb(node.body); + } + scope.end(varCb); + this.#scope = savedScope; + } + #handleModule(node, next) { + if (node.flags & ts9.NodeFlags.GlobalAugmentation) { + return next( + node, + this.#scope.createOrReuseNamespaceScope("-global", false, true, false) + ); + } + if (node.name.kind === ts9.SyntaxKind.Identifier) { + const exported = isNamespaceExported(node); + this.#scope.addVariable( + node.name.text, + node.name, + 1 /* Function */, + exported, + 1 /* Namespace */ | 4 /* Value */ + ); + const ambient = includesModifier( + node.modifiers, + ts9.SyntaxKind.DeclareKeyword + ); + return next( + node, + this.#scope.createOrReuseNamespaceScope( + node.name.text, + exported, + ambient, + ambient && namespaceHasExportStatement(node) + ) + ); + } + return next( + node, + this.#scope.createOrReuseNamespaceScope( + `"${node.name.text}"`, + false, + true, + namespaceHasExportStatement(node) + ) + ); + } + #handleVariableDeclaration(declarationList) { + const blockScoped = isBlockScopedVariableDeclarationList(declarationList); + const exported = declarationList.parent.kind === ts9.SyntaxKind.VariableStatement && includesModifier( + declarationList.parent.modifiers, + ts9.SyntaxKind.ExportKeyword + ); + for (const declaration of declarationList.declarations) { + this.#handleBindingName(declaration.name, blockScoped, exported); + } + } +}; +function containsExportStatement(block) { + for (const statement of block.statements) { + if (statement.kind === ts9.SyntaxKind.ExportDeclaration || statement.kind === ts9.SyntaxKind.ExportAssignment) { + return true; + } + } + return false; +} +function forEachDestructuringIdentifier(pattern, fn) { + for (const element of pattern.elements) { + if (element.kind !== ts9.SyntaxKind.BindingElement) { + continue; + } + let result; + if (element.name.kind === ts9.SyntaxKind.Identifier) { + result = fn(element); + } else { + result = forEachDestructuringIdentifier(element.name, fn); + } + if (result) { + return result; + } + } +} +function isBlockScopedVariableDeclarationList(declarationList) { + return (declarationList.flags & ts9.NodeFlags.BlockScoped) !== 0; +} +function isNamespaceExported(node) { + return node.parent.kind === ts9.SyntaxKind.ModuleDeclaration || includesModifier(node.modifiers, ts9.SyntaxKind.ExportKeyword); +} +function namespaceHasExportStatement(ns) { + if (ns.body === undefined || ns.body.kind !== ts9.SyntaxKind.ModuleBlock) { + return false; + } + return containsExportStatement(ns.body); +} + +// src/usage/collectVariableUsage.ts +function collectVariableUsage(sourceFile) { + return new UsageWalker().getUsage(sourceFile); +} + +export { AccessKind, DeclarationDomain, UsageDomain, collectVariableUsage, forEachComment, forEachToken, getAccessKind, getCallSignaturesOfType, getPropertyOfType, getWellKnownSymbolPropertyOfType, hasDecorators, hasExpressionInitializer, hasInitializer, hasJSDoc, hasModifiers, hasType, hasTypeArguments, includesModifier, intersectionConstituents, intersectionTypeParts, isAbstractKeyword, isAccessExpression, isAccessibilityModifier, isAccessorDeclaration, isAccessorKeyword, isAnyKeyword, isArrayBindingElement, isArrayBindingOrAssignmentPattern, isAssertKeyword, isAssertsKeyword, isAssignmentKind, isAssignmentPattern, isAsyncKeyword, isAwaitKeyword, isBigIntKeyword, isBigIntLiteralType, isBindingOrAssignmentElementRestIndicator, isBindingOrAssignmentElementTarget, isBindingOrAssignmentPattern, isBindingPattern, isBlockLike, isBooleanKeyword, isBooleanLiteral, isBooleanLiteralType, isClassLikeDeclaration, isClassMemberModifier, isColonToken, isCompilerOptionEnabled, isConditionalType, isConstAssertionExpression, isConstKeyword, isDeclarationName, isDeclarationWithTypeParameterChildren, isDeclarationWithTypeParameters, isDeclareKeyword, isDefaultKeyword, isDestructuringPattern, isDotToken, isEndOfFileToken, isEntityNameExpression, isEntityNameOrEntityNameExpression, isEnumType, isEqualsGreaterThanToken, isEqualsToken, isEvolvingArrayType, isExclamationToken, isExportKeyword, isFalseKeyword, isFalseLiteral, isFalseLiteralType, isFalsyType, isForInOrOfStatement, isFreshableIntrinsicType, isFreshableType, isFunctionLikeDeclaration, isFunctionScopeBoundary, isImportExpression, isImportKeyword, isInKeyword, isIndexType, isIndexedAccessType, isInstantiableType, isIntersectionType, isIntrinsicAnyType, isIntrinsicBigIntType, isIntrinsicBooleanType, isIntrinsicESSymbolType, isIntrinsicErrorType, isIntrinsicNeverType, isIntrinsicNonPrimitiveType, isIntrinsicNullType, isIntrinsicNumberType, isIntrinsicStringType, isIntrinsicType, isIntrinsicUndefinedType, isIntrinsicUnknownType, isIntrinsicVoidType, isIterationStatement, isJSDocComment, isJSDocNamespaceBody, isJSDocNamespaceDeclaration, isJSDocText, isJSDocTypeReferencingNode, isJsonMinusNumericLiteral, isJsonObjectExpression, isJsxAttributeLike, isJsxAttributeValue, isJsxChild, isJsxTagNameExpression, isJsxTagNamePropertyAccess, isLiteralToken, isLiteralType, isModifierFlagSet, isModuleBody, isModuleName, isModuleReference, isNamedDeclarationWithName, isNamedImportBindings, isNamedImportsOrExports, isNamespaceBody, isNamespaceDeclaration, isNeverKeyword, isNodeFlagSet, isNullKeyword, isNullLiteral, isNumberKeyword, isNumberLiteralType, isNumericOrStringLikeLiteral, isNumericPropertyName, isObjectBindingOrAssignmentElement, isObjectBindingOrAssignmentPattern, isObjectFlagSet, isObjectKeyword, isObjectType, isObjectTypeDeclaration, isOutKeyword, isOverrideKeyword, isParameterPropertyModifier, isPrivateKeyword, isPropertyAccessEntityNameExpression, isPropertyNameLiteral, isPropertyReadonlyInType, isProtectedKeyword, isPseudoLiteralToken, isPublicKeyword, isQuestionDotToken, isQuestionToken, isReadonlyKeyword, isSignatureDeclaration, isStaticKeyword, isStrictCompilerOptionEnabled, isStringKeyword, isStringLiteralType, isStringMappingType, isSubstitutionType, isSuperElementAccessExpression, isSuperExpression, isSuperKeyword, isSuperProperty, isSuperPropertyAccessExpression, isSymbolFlagSet, isSymbolKeyword, isSyntaxList, isTemplateLiteralType, isThenableType, isThisExpression, isThisKeyword, isTransientSymbolLinksFlagSet, isTrueKeyword, isTrueLiteral, isTrueLiteralType, isTupleType, isTupleTypeReference, isTypeFlagSet, isTypeOnlyCompatibleAliasDeclaration, isTypeParameter, isTypeReference, isTypeReferenceType, isTypeVariable, isUndefinedKeyword, isUnionOrIntersectionType, isUnionOrIntersectionTypeNode, isUnionType, isUniqueESSymbolType, isUnknownKeyword, isValidPropertyAccess, isVariableLikeDeclaration, isVoidKeyword, symbolHasReadonlyDeclaration, typeConstituents, typeIsLiteral, typeParts, unionConstituents, unionTypeParts }; diff --git a/node_modules/ts-api-utils/package.json b/node_modules/ts-api-utils/package.json new file mode 100644 index 00000000..4e6cdaa5 --- /dev/null +++ b/node_modules/ts-api-utils/package.json @@ -0,0 +1,104 @@ +{ + "name": "ts-api-utils", + "version": "2.1.0", + "description": "Utility functions for working with TypeScript's API. Successor to the wonderful tsutils. 🛠️️", + "repository": { + "type": "git", + "url": "https://github.com/JoshuaKGoldberg/ts-api-utils" + }, + "license": "MIT", + "author": { + "name": "JoshuaKGoldberg", + "email": "npm@joshuakgoldberg.com" + }, + "type": "module", + "exports": { + ".": { + "types": { + "import": "./lib/index.d.ts", + "require": "./lib/index.d.cts" + }, + "import": "./lib/index.js", + "require": "./lib/index.cjs" + } + }, + "main": "./lib/index.js", + "files": [ + "lib/", + "package.json", + "LICENSE.md", + "README.md" + ], + "scripts": { + "build": "tsup src/index.ts && cp lib/index.d.ts lib/index.d.cts", + "docs": "typedoc", + "docs:serve": "npx --yes http-server docs/generated", + "format": "prettier \"**/*\" --ignore-unknown", + "lint": "eslint . --max-warnings 0", + "lint:docs": "typedoc --validation --treatValidationWarningsAsErrors", + "lint:knip": "knip", + "lint:md": "markdownlint \"**/*.md\" \".github/**/*.md\" --rules sentences-per-line", + "lint:packages": "pnpm dedupe --check", + "lint:spelling": "cspell \"**\" \".github/**/*\"", + "prepare": "husky", + "should-semantic-release": "should-semantic-release --verbose", + "test": "vitest", + "tsc": "tsc" + }, + "lint-staged": { + "*": "prettier --ignore-unknown --write" + }, + "devDependencies": { + "@eslint-community/eslint-plugin-eslint-comments": "^4.4.1", + "@eslint/js": "^9.19.0", + "@phenomnomnominal/tsquery": "^6.1.3", + "@release-it/conventional-changelog": "^10.0.0", + "@types/eslint-plugin-markdown": "^2.0.2", + "@types/node": "^18.19.74", + "@typescript/vfs": "^1.6.0", + "@vitest/coverage-v8": "^2.1.8", + "@vitest/eslint-plugin": "^1.1.25", + "console-fail-test": "^0.5.0", + "cspell": "^8.17.3", + "eslint": "^9.19.0", + "eslint-plugin-jsdoc": "^50.6.3", + "eslint-plugin-jsonc": "^2.19.1", + "eslint-plugin-markdown": "^5.1.0", + "eslint-plugin-n": "^17.15.1", + "eslint-plugin-package-json": "^0.19.0", + "eslint-plugin-perfectionist": "^4.7.0", + "eslint-plugin-regexp": "^2.7.0", + "eslint-plugin-yml": "^1.16.0", + "husky": "^9.1.7", + "jsonc-eslint-parser": "^2.4.0", + "knip": "^5.46.0", + "lint-staged": "^15.4.3", + "markdownlint": "^0.37.4", + "markdownlint-cli": "^0.44.0", + "prettier": "^3.4.2", + "prettier-plugin-curly": "^0.3.1", + "prettier-plugin-packagejson": "^2.5.8", + "release-it": "^18.1.2", + "sentences-per-line": "^0.3.0", + "should-semantic-release": "^0.3.0", + "tsup": "^8.3.6", + "typedoc": "^0.27.6", + "typedoc-plugin-coverage": "^3.4.1", + "typedoc-plugin-custom-validation": "^2.0.2", + "typedoc-plugin-konamimojisplosion": "^0.0.2", + "typedoc-plugin-mdn-links": "^4.0.10", + "typescript": "^5.7.3", + "typescript-eslint": "^8.22.0", + "vitest": "^3.0.0" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + }, + "packageManager": "pnpm@9.15.9", + "engines": { + "node": ">=18.12" + }, + "publishConfig": { + "provenance": true + } +} diff --git a/node_modules/type-check/LICENSE b/node_modules/type-check/LICENSE new file mode 100644 index 00000000..525b1185 --- /dev/null +++ b/node_modules/type-check/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) George Zahariev + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/type-check/README.md b/node_modules/type-check/README.md new file mode 100644 index 00000000..b170d67c --- /dev/null +++ b/node_modules/type-check/README.md @@ -0,0 +1,210 @@ +# type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check) + + + +`type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.4.0. Check out the [demo](http://gkz.github.io/type-check/). + +For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev). + + npm install type-check + +## Quick Examples + +```js +// Basic types: +var typeCheck = require('type-check').typeCheck; +typeCheck('Number', 1); // true +typeCheck('Number', 'str'); // false +typeCheck('Error', new Error); // true +typeCheck('Undefined', undefined); // true + +// Comment +typeCheck('count::Number', 1); // true + +// One type OR another type: +typeCheck('Number | String', 2); // true +typeCheck('Number | String', 'str'); // true + +// Wildcard, matches all types: +typeCheck('*', 2) // true + +// Array, all elements of a single type: +typeCheck('[Number]', [1, 2, 3]); // true +typeCheck('[Number]', [1, 'str', 3]); // false + +// Tuples, or fixed length arrays with elements of different types: +typeCheck('(String, Number)', ['str', 2]); // true +typeCheck('(String, Number)', ['str']); // false +typeCheck('(String, Number)', ['str', 2, 5]); // false + +// Object properties: +typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true +typeCheck('{x: Number, y: Boolean}', {x: 2}); // false +typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true +typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false +typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true + +// A particular type AND object properties: +typeCheck('RegExp{source: String, ...}', /re/i); // true +typeCheck('RegExp{source: String, ...}', {source: 're'}); // false + +// Custom types: +var opt = {customTypes: + {Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}}; +typeCheck('Even', 2, opt); // true + +// Nested: +var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}' +typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true +``` + +Check out the [type syntax format](#syntax) and [guide](#guide). + +## Usage + +`require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions. + +```js +// typeCheck(type, input, options); +typeCheck('Number', 2); // true + +// parseType(type); +var parsedType = parseType('Number'); // object + +// parsedTypeCheck(parsedType, input, options); +parsedTypeCheck(parsedType, 2); // true +``` + +### typeCheck(type, input, options) + +`typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`. + +##### arguments +* type - `String` - the type written in the [type format](#type-format) which to check against +* input - `*` - any JavaScript value, which is to be checked against the type +* options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) + +##### returns +`Boolean` - whether the input matches the type + +##### example +```js +typeCheck('Number', 2); // true +``` + +### parseType(type) + +`parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type. + +##### arguments +* type - `String` - the type written in the [type format](#type-format) which to parse + +##### returns +`Object` - an object in the parsed type format representing the parsed type + +##### example +```js +parseType('Number'); // [{type: 'Number'}] +``` +### parsedTypeCheck(parsedType, input, options) + +`parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once. + +##### arguments +* type - `Object` - the type in the parsed type format which to check against +* input - `*` - any JavaScript value, which is to be checked against the type +* options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) + +##### returns +`Boolean` - whether the input matches the type + +##### example +```js +parsedTypeCheck([{type: 'Number'}], 2); // true +var parsedType = parseType('String'); +parsedTypeCheck(parsedType, 'str'); // true +``` + + +## Type Format + +### Syntax + +White space is ignored. The root node is a __Types__. + +* __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String` +* __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*` +* __Types__ = optionally a comment (an `Identifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String` +* __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]` +* __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}` +* __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean` +* __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)` +* __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]` + +### Guide + +`type-check` uses `Object.toString` to find out the basic type of a value. Specifically, + +```js +{}.toString.call(VALUE).slice(8, -1) +{}.toString.call(true).slice(8, -1) // 'Boolean' +``` +A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`. + +You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false. + +Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`. + +You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out. + +The wildcard `*` matches all types. + +There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'. + +If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`. + +To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`. + +If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null). + +If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties. + +For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`. + +A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`. + +An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all. + +Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check. + +## Options + +Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`. + + +### Custom Types + +__Example:__ + +```js +var options = { + customTypes: { + Even: { + typeOf: 'Number', + validate: function(x) { + return x % 2 === 0; + } + } + } +}; +typeCheck('Even', 2, options); // true +typeCheck('Even', 3, options); // false +``` + +`customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function. + +The `typeOf` property is the type the value should be (optional - if not set only `validate` will be used), and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking. + +## Technical About + +`type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library. diff --git a/node_modules/type-check/lib/check.js b/node_modules/type-check/lib/check.js new file mode 100644 index 00000000..f78687ee --- /dev/null +++ b/node_modules/type-check/lib/check.js @@ -0,0 +1,128 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var ref$, any, all, isItNaN, types, defaultType, toString$ = {}.toString; + ref$ = require('prelude-ls'), any = ref$.any, all = ref$.all, isItNaN = ref$.isItNaN; + types = { + Number: { + typeOf: 'Number', + validate: function(it){ + return !isItNaN(it); + } + }, + NaN: { + typeOf: 'Number', + validate: isItNaN + }, + Int: { + typeOf: 'Number', + validate: function(it){ + return !isItNaN(it) && it % 1 === 0; + } + }, + Float: { + typeOf: 'Number', + validate: function(it){ + return !isItNaN(it); + } + }, + Date: { + typeOf: 'Date', + validate: function(it){ + return !isItNaN(it.getTime()); + } + } + }; + defaultType = { + array: 'Array', + tuple: 'Array' + }; + function checkArray(input, type, options){ + return all(function(it){ + return checkMultiple(it, type.of, options); + }, input); + } + function checkTuple(input, type, options){ + var i, i$, ref$, len$, types; + i = 0; + for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) { + types = ref$[i$]; + if (!checkMultiple(input[i], types, options)) { + return false; + } + i++; + } + return input.length <= i; + } + function checkFields(input, type, options){ + var inputKeys, numInputKeys, k, numOfKeys, key, ref$, types; + inputKeys = {}; + numInputKeys = 0; + for (k in input) { + inputKeys[k] = true; + numInputKeys++; + } + numOfKeys = 0; + for (key in ref$ = type.of) { + types = ref$[key]; + if (!checkMultiple(input[key], types, options)) { + return false; + } + if (inputKeys[key]) { + numOfKeys++; + } + } + return type.subset || numInputKeys === numOfKeys; + } + function checkStructure(input, type, options){ + if (!(input instanceof Object)) { + return false; + } + switch (type.structure) { + case 'fields': + return checkFields(input, type, options); + case 'array': + return checkArray(input, type, options); + case 'tuple': + return checkTuple(input, type, options); + } + } + function check(input, typeObj, options){ + var type, structure, setting, that; + type = typeObj.type, structure = typeObj.structure; + if (type) { + if (type === '*') { + return true; + } + setting = options.customTypes[type] || types[type]; + if (setting) { + return (setting.typeOf === void 8 || setting.typeOf === toString$.call(input).slice(8, -1)) && setting.validate(input); + } else { + return type === toString$.call(input).slice(8, -1) && (!structure || checkStructure(input, typeObj, options)); + } + } else if (structure) { + if (that = defaultType[structure]) { + if (that !== toString$.call(input).slice(8, -1)) { + return false; + } + } + return checkStructure(input, typeObj, options); + } else { + throw new Error("No type defined. Input: " + input + "."); + } + } + function checkMultiple(input, types, options){ + if (toString$.call(types).slice(8, -1) !== 'Array') { + throw new Error("Types must be in an array. Input: " + input + "."); + } + return any(function(it){ + return check(input, it, options); + }, types); + } + module.exports = function(parsedType, input, options){ + options == null && (options = {}); + if (options.customTypes == null) { + options.customTypes = {}; + } + return checkMultiple(input, parsedType, options); + }; +}).call(this); diff --git a/node_modules/type-check/lib/index.js b/node_modules/type-check/lib/index.js new file mode 100644 index 00000000..09db4cb6 --- /dev/null +++ b/node_modules/type-check/lib/index.js @@ -0,0 +1,16 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var VERSION, parseType, parsedTypeCheck, typeCheck; + VERSION = '0.4.0'; + parseType = require('./parse-type'); + parsedTypeCheck = require('./check'); + typeCheck = function(type, input, options){ + return parsedTypeCheck(parseType(type), input, options); + }; + module.exports = { + VERSION: VERSION, + typeCheck: typeCheck, + parsedTypeCheck: parsedTypeCheck, + parseType: parseType + }; +}).call(this); diff --git a/node_modules/type-check/lib/parse-type.js b/node_modules/type-check/lib/parse-type.js new file mode 100644 index 00000000..c360c973 --- /dev/null +++ b/node_modules/type-check/lib/parse-type.js @@ -0,0 +1,198 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var identifierRegex, tokenRegex; + identifierRegex = /[\$\w]+/; + function peek(tokens){ + var token; + token = tokens[0]; + if (token == null) { + throw new Error('Unexpected end of input.'); + } + return token; + } + function consumeIdent(tokens){ + var token; + token = peek(tokens); + if (!identifierRegex.test(token)) { + throw new Error("Expected text, got '" + token + "' instead."); + } + return tokens.shift(); + } + function consumeOp(tokens, op){ + var token; + token = peek(tokens); + if (token !== op) { + throw new Error("Expected '" + op + "', got '" + token + "' instead."); + } + return tokens.shift(); + } + function maybeConsumeOp(tokens, op){ + var token; + token = tokens[0]; + if (token === op) { + return tokens.shift(); + } else { + return null; + } + } + function consumeArray(tokens){ + var types; + consumeOp(tokens, '['); + if (peek(tokens) === ']') { + throw new Error("Must specify type of Array - eg. [Type], got [] instead."); + } + types = consumeTypes(tokens); + consumeOp(tokens, ']'); + return { + structure: 'array', + of: types + }; + } + function consumeTuple(tokens){ + var components; + components = []; + consumeOp(tokens, '('); + if (peek(tokens) === ')') { + throw new Error("Tuple must be of at least length 1 - eg. (Type), got () instead."); + } + for (;;) { + components.push(consumeTypes(tokens)); + maybeConsumeOp(tokens, ','); + if (')' === peek(tokens)) { + break; + } + } + consumeOp(tokens, ')'); + return { + structure: 'tuple', + of: components + }; + } + function consumeFields(tokens){ + var fields, subset, ref$, key, types; + fields = {}; + consumeOp(tokens, '{'); + subset = false; + for (;;) { + if (maybeConsumeOp(tokens, '...')) { + subset = true; + break; + } + ref$ = consumeField(tokens), key = ref$[0], types = ref$[1]; + fields[key] = types; + maybeConsumeOp(tokens, ','); + if ('}' === peek(tokens)) { + break; + } + } + consumeOp(tokens, '}'); + return { + structure: 'fields', + of: fields, + subset: subset + }; + } + function consumeField(tokens){ + var key, types; + key = consumeIdent(tokens); + consumeOp(tokens, ':'); + types = consumeTypes(tokens); + return [key, types]; + } + function maybeConsumeStructure(tokens){ + switch (tokens[0]) { + case '[': + return consumeArray(tokens); + case '(': + return consumeTuple(tokens); + case '{': + return consumeFields(tokens); + } + } + function consumeType(tokens){ + var token, wildcard, type, structure; + token = peek(tokens); + wildcard = token === '*'; + if (wildcard || identifierRegex.test(token)) { + type = wildcard + ? consumeOp(tokens, '*') + : consumeIdent(tokens); + structure = maybeConsumeStructure(tokens); + if (structure) { + return structure.type = type, structure; + } else { + return { + type: type + }; + } + } else { + structure = maybeConsumeStructure(tokens); + if (!structure) { + throw new Error("Unexpected character: " + token); + } + return structure; + } + } + function consumeTypes(tokens){ + var lookahead, types, typesSoFar, typeObj, type, structure; + if ('::' === peek(tokens)) { + throw new Error("No comment before comment separator '::' found."); + } + lookahead = tokens[1]; + if (lookahead != null && lookahead === '::') { + tokens.shift(); + tokens.shift(); + } + types = []; + typesSoFar = {}; + if ('Maybe' === peek(tokens)) { + tokens.shift(); + types = [ + { + type: 'Undefined' + }, { + type: 'Null' + } + ]; + typesSoFar = { + Undefined: true, + Null: true + }; + } + for (;;) { + typeObj = consumeType(tokens), type = typeObj.type, structure = typeObj.structure; + if (!typesSoFar[type]) { + types.push(typeObj); + } + if (structure == null) { + typesSoFar[type] = true; + } + if (!maybeConsumeOp(tokens, '|')) { + break; + } + } + return types; + } + tokenRegex = RegExp('\\.\\.\\.|::|->|' + identifierRegex.source + '|\\S', 'g'); + module.exports = function(input){ + var tokens, e; + if (!input.length) { + throw new Error('No type specified.'); + } + tokens = input.match(tokenRegex) || []; + if (in$('->', tokens)) { + throw new Error("Function types are not supported.\ To validate that something is a function, you may use 'Function'."); + } + try { + return consumeTypes(tokens); + } catch (e$) { + e = e$; + throw new Error(e.message + " - Remaining tokens: " + JSON.stringify(tokens) + " - Initial input: '" + input + "'"); + } + }; + function in$(x, xs){ + var i = -1, l = xs.length >>> 0; + while (++i < l) if (x === xs[i]) return true; + return false; + } +}).call(this); diff --git a/node_modules/type-check/package.json b/node_modules/type-check/package.json new file mode 100644 index 00000000..2a57ea06 --- /dev/null +++ b/node_modules/type-check/package.json @@ -0,0 +1,39 @@ +{ + "name": "type-check", + "version": "0.4.0", + "author": "George Zahariev ", + "description": "type-check allows you to check the types of JavaScript values at runtime with a Haskell like type syntax.", + "homepage": "https://github.com/gkz/type-check", + "keywords": [ + "type", + "check", + "checking", + "library" + ], + "files": [ + "lib", + "README.md", + "LICENSE" + ], + "main": "./lib/", + "bugs": "https://github.com/gkz/type-check/issues", + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/gkz/type-check.git" + }, + "scripts": { + "test": "make test" + }, + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "devDependencies": { + "livescript": "^1.6.0", + "mocha": "^7.1.1", + "browserify": "^16.5.1" + } +} diff --git a/node_modules/typescript-eslint/LICENSE b/node_modules/typescript-eslint/LICENSE new file mode 100644 index 00000000..a1164108 --- /dev/null +++ b/node_modules/typescript-eslint/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/typescript-eslint/README.md b/node_modules/typescript-eslint/README.md new file mode 100644 index 00000000..3c078eae --- /dev/null +++ b/node_modules/typescript-eslint/README.md @@ -0,0 +1,12 @@ +# `typescript-eslint` + +> Tooling which enables you to use TypeScript with ESLint + +[![NPM Version](https://img.shields.io/npm/v/typescript-eslint.svg?style=flat-square)](https://www.npmjs.com/package/typescript-eslint) +[![NPM Downloads](https://img.shields.io/npm/dm/typescript-eslint.svg?style=flat-square)](https://www.npmjs.com/package/typescript-eslint) + +👉 See **https://typescript-eslint.io/packages/typescript-eslint** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/typescript-eslint/dist/config-helper.d.ts b/node_modules/typescript-eslint/dist/config-helper.d.ts new file mode 100644 index 00000000..e6466add --- /dev/null +++ b/node_modules/typescript-eslint/dist/config-helper.d.ts @@ -0,0 +1,68 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +export type InfiniteDepthConfigWithExtends = ConfigWithExtends | InfiniteDepthConfigWithExtends[]; +export interface ConfigWithExtends extends TSESLint.FlatConfig.Config { + /** + * Allows you to "extend" a set of configs similar to `extends` from the + * classic configs. + * + * This is just a convenience short-hand to help reduce duplication. + * + * ```js + * export default tseslint.config({ + * files: ['** /*.ts'], + * extends: [ + * eslint.configs.recommended, + * tseslint.configs.recommended, + * ], + * rules: { + * '@typescript-eslint/array-type': 'error', + * '@typescript-eslint/consistent-type-imports': 'error', + * }, + * }) + * + * // expands to + * + * export default [ + * { + * ...eslint.configs.recommended, + * files: ['** /*.ts'], + * }, + * ...tseslint.configs.recommended.map(conf => ({ + * ...conf, + * files: ['** /*.ts'], + * })), + * { + * files: ['** /*.ts'], + * rules: { + * '@typescript-eslint/array-type': 'error', + * '@typescript-eslint/consistent-type-imports': 'error', + * }, + * }, + * ] + * ``` + */ + extends?: InfiniteDepthConfigWithExtends[]; +} +export type ConfigArray = TSESLint.FlatConfig.ConfigArray; +/** + * Utility function to make it easy to strictly type your "Flat" config file + * @example + * ```js + * // @ts-check + * + * import eslint from '@eslint/js'; + * import tseslint from 'typescript-eslint'; + * + * export default tseslint.config( + * eslint.configs.recommended, + * tseslint.configs.recommended, + * { + * rules: { + * '@typescript-eslint/array-type': 'error', + * }, + * }, + * ); + * ``` + */ +export declare function config(...configs: InfiniteDepthConfigWithExtends[]): ConfigArray; +//# sourceMappingURL=config-helper.d.ts.map \ No newline at end of file diff --git a/node_modules/typescript-eslint/dist/config-helper.d.ts.map b/node_modules/typescript-eslint/dist/config-helper.d.ts.map new file mode 100644 index 00000000..f6924ad9 --- /dev/null +++ b/node_modules/typescript-eslint/dist/config-helper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"config-helper.d.ts","sourceRoot":"","sources":["../src/config-helper.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAEzD,MAAM,MAAM,8BAA8B,GACtC,iBAAiB,GACjB,8BAA8B,EAAE,CAAC;AAErC,MAAM,WAAW,iBAAkB,SAAQ,QAAQ,CAAC,UAAU,CAAC,MAAM;IACnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAuCG;IACH,OAAO,CAAC,EAAE,8BAA8B,EAAE,CAAC;CAC5C;AAGD,MAAM,MAAM,WAAW,GAAG,QAAQ,CAAC,UAAU,CAAC,WAAW,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,MAAM,CACpB,GAAG,OAAO,EAAE,8BAA8B,EAAE,GAC3C,WAAW,CAEb"} \ No newline at end of file diff --git a/node_modules/typescript-eslint/dist/config-helper.js b/node_modules/typescript-eslint/dist/config-helper.js new file mode 100644 index 00000000..ce1180a3 --- /dev/null +++ b/node_modules/typescript-eslint/dist/config-helper.js @@ -0,0 +1,116 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.config = config; +/** + * Utility function to make it easy to strictly type your "Flat" config file + * @example + * ```js + * // @ts-check + * + * import eslint from '@eslint/js'; + * import tseslint from 'typescript-eslint'; + * + * export default tseslint.config( + * eslint.configs.recommended, + * tseslint.configs.recommended, + * { + * rules: { + * '@typescript-eslint/array-type': 'error', + * }, + * }, + * ); + * ``` + */ +function config(...configs) { + return configImpl(...configs); +} +// Implementation of the config function without assuming the runtime type of +// the input. +function configImpl(...configs) { + const flattened = configs.flat(Infinity); + return flattened.flatMap((configWithExtends, configIndex) => { + if (configWithExtends == null || + typeof configWithExtends !== 'object' || + !('extends' in configWithExtends)) { + // Unless the object is a config object with extends key, just forward it + // along to eslint. + return configWithExtends; + } + const { extends: extendsArr, ..._config } = configWithExtends; + const config = _config; + if (extendsArr == null) { + // If the extends value is nullish, just forward along the rest of the + // config object to eslint. + return config; + } + const name = (() => { + if ('name' in configWithExtends && configWithExtends.name != null) { + if (typeof configWithExtends.name !== 'string') { + throw new Error(`tseslint.config(): Config at index ${configIndex} has a 'name' property that is not a string.`); + } + return configWithExtends.name; + } + return undefined; + })(); + const nameErrorPhrase = name != null ? `, named "${name}",` : ' (anonymous)'; + if (!Array.isArray(extendsArr)) { + throw new TypeError(`tseslint.config(): Config at index ${configIndex}${nameErrorPhrase} has an 'extends' property that is not an array.`); + } + const extendsArrFlattened = extendsArr.flat(Infinity); + const nonObjectExtensions = []; + for (const [extensionIndex, extension] of extendsArrFlattened.entries()) { + // special error message to be clear we don't support eslint's stringly typed extends. + // https://eslint.org/docs/latest/use/configure/configuration-files#extending-configurations + if (typeof extension === 'string') { + throw new Error(`tseslint.config(): Config at index ${configIndex}${nameErrorPhrase} has an 'extends' array that contains a string (${JSON.stringify(extension)}) at index ${extensionIndex}.` + + " This is a feature of eslint's `defineConfig()` helper and is not supported by typescript-eslint." + + ' Please provide a config object instead.'); + } + if (extension == null || typeof extension !== 'object') { + nonObjectExtensions.push(extensionIndex); + } + } + if (nonObjectExtensions.length > 0) { + const extensionIndices = nonObjectExtensions.join(', '); + throw new Error(`tseslint.config(): Config at index ${configIndex}${nameErrorPhrase} contains non-object` + + ` extensions at the following indices: ${extensionIndices}.`); + } + const configArray = []; + for (const _extension of extendsArrFlattened) { + const extension = _extension; + const resolvedConfigName = [name, extension.name] + .filter(Boolean) + .join('__'); + if (isPossiblyGlobalIgnores(extension)) { + // If it's a global ignores, then just pass it along + configArray.push({ + ...extension, + ...(resolvedConfigName !== '' ? { name: resolvedConfigName } : {}), + }); + } + else { + configArray.push({ + ...extension, + ...(config.files ? { files: config.files } : {}), + ...(config.ignores ? { ignores: config.ignores } : {}), + ...(resolvedConfigName !== '' ? { name: resolvedConfigName } : {}), + }); + } + } + // If the base config could form a global ignores object, then we mustn't include + // it in the output. Otherwise, we must add it in order for it to have effect. + if (!isPossiblyGlobalIgnores(config)) { + configArray.push(config); + } + return configArray; + }); +} +/** + * This utility function returns false if the config objects contains any field + * that would prevent it from being considered a global ignores object and true + * otherwise. Note in particular that the `ignores` field may not be present and + * the return value can still be true. + */ +function isPossiblyGlobalIgnores(config) { + return Object.keys(config).every(key => ['name', 'ignores'].includes(key)); +} diff --git a/node_modules/typescript-eslint/dist/index.d.ts b/node_modules/typescript-eslint/dist/index.d.ts new file mode 100644 index 00000000..6fbd0a97 --- /dev/null +++ b/node_modules/typescript-eslint/dist/index.d.ts @@ -0,0 +1,153 @@ +import type { TSESLint } from '@typescript-eslint/utils'; +import { config } from './config-helper'; +export declare const parser: TSESLint.FlatConfig.Parser; +export declare const plugin: TSESLint.FlatConfig.Plugin; +export declare const configs: { + /** + * Enables each the rules provided as a part of typescript-eslint. Note that many rules are not applicable in all codebases, or are meant to be configured. + * @see {@link https://typescript-eslint.io/users/configs#all} + */ + all: TSESLint.FlatConfig.ConfigArray; + /** + * A minimal ruleset that sets only the required parser and plugin options needed to run typescript-eslint. + * We don't recommend using this directly; instead, extend from an earlier recommended rule. + * @see {@link https://typescript-eslint.io/users/configs#base} + */ + base: TSESLint.FlatConfig.Config; + /** + * A utility ruleset that will disable type-aware linting and all type-aware rules available in our project. + * @see {@link https://typescript-eslint.io/users/configs#disable-type-checked} + */ + disableTypeChecked: TSESLint.FlatConfig.Config; + /** + * This is a compatibility ruleset that: + * - disables rules from eslint:recommended which are already handled by TypeScript. + * - enables rules that make sense due to TS's typechecking / transpilation. + * @see {@link https://typescript-eslint.io/users/configs/#eslint-recommended} + */ + eslintRecommended: TSESLint.FlatConfig.Config; + /** + * Recommended rules for code correctness that you can drop in without additional configuration. + * @see {@link https://typescript-eslint.io/users/configs#recommended} + */ + recommended: TSESLint.FlatConfig.ConfigArray; + /** + * Contains all of `recommended` along with additional recommended rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked} + */ + recommendedTypeChecked: TSESLint.FlatConfig.ConfigArray; + /** + * A version of `recommended` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked-only} + */ + recommendedTypeCheckedOnly: TSESLint.FlatConfig.ConfigArray; + /** + * Contains all of `recommended`, as well as additional strict rules that can also catch bugs. + * @see {@link https://typescript-eslint.io/users/configs#strict} + */ + strict: TSESLint.FlatConfig.ConfigArray; + /** + * Contains all of `recommended`, `recommended-type-checked`, and `strict`, along with additional strict rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked} + */ + strictTypeChecked: TSESLint.FlatConfig.ConfigArray; + /** + * A version of `strict` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked-only} + */ + strictTypeCheckedOnly: TSESLint.FlatConfig.ConfigArray; + /** + * Rules considered to be best practice for modern TypeScript codebases, but that do not impact program logic. + * @see {@link https://typescript-eslint.io/users/configs#stylistic} + */ + stylistic: TSESLint.FlatConfig.ConfigArray; + /** + * Contains all of `stylistic`, along with additional stylistic rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked} + */ + stylisticTypeChecked: TSESLint.FlatConfig.ConfigArray; + /** + * A version of `stylistic` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked-only} + */ + stylisticTypeCheckedOnly: TSESLint.FlatConfig.ConfigArray; +}; +export type Config = TSESLint.FlatConfig.ConfigFile; +declare const _default: { + config: typeof config; + configs: { + /** + * Enables each the rules provided as a part of typescript-eslint. Note that many rules are not applicable in all codebases, or are meant to be configured. + * @see {@link https://typescript-eslint.io/users/configs#all} + */ + all: TSESLint.FlatConfig.ConfigArray; + /** + * A minimal ruleset that sets only the required parser and plugin options needed to run typescript-eslint. + * We don't recommend using this directly; instead, extend from an earlier recommended rule. + * @see {@link https://typescript-eslint.io/users/configs#base} + */ + base: TSESLint.FlatConfig.Config; + /** + * A utility ruleset that will disable type-aware linting and all type-aware rules available in our project. + * @see {@link https://typescript-eslint.io/users/configs#disable-type-checked} + */ + disableTypeChecked: TSESLint.FlatConfig.Config; + /** + * This is a compatibility ruleset that: + * - disables rules from eslint:recommended which are already handled by TypeScript. + * - enables rules that make sense due to TS's typechecking / transpilation. + * @see {@link https://typescript-eslint.io/users/configs/#eslint-recommended} + */ + eslintRecommended: TSESLint.FlatConfig.Config; + /** + * Recommended rules for code correctness that you can drop in without additional configuration. + * @see {@link https://typescript-eslint.io/users/configs#recommended} + */ + recommended: TSESLint.FlatConfig.ConfigArray; + /** + * Contains all of `recommended` along with additional recommended rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked} + */ + recommendedTypeChecked: TSESLint.FlatConfig.ConfigArray; + /** + * A version of `recommended` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked-only} + */ + recommendedTypeCheckedOnly: TSESLint.FlatConfig.ConfigArray; + /** + * Contains all of `recommended`, as well as additional strict rules that can also catch bugs. + * @see {@link https://typescript-eslint.io/users/configs#strict} + */ + strict: TSESLint.FlatConfig.ConfigArray; + /** + * Contains all of `recommended`, `recommended-type-checked`, and `strict`, along with additional strict rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked} + */ + strictTypeChecked: TSESLint.FlatConfig.ConfigArray; + /** + * A version of `strict` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked-only} + */ + strictTypeCheckedOnly: TSESLint.FlatConfig.ConfigArray; + /** + * Rules considered to be best practice for modern TypeScript codebases, but that do not impact program logic. + * @see {@link https://typescript-eslint.io/users/configs#stylistic} + */ + stylistic: TSESLint.FlatConfig.ConfigArray; + /** + * Contains all of `stylistic`, along with additional stylistic rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked} + */ + stylisticTypeChecked: TSESLint.FlatConfig.ConfigArray; + /** + * A version of `stylistic` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked-only} + */ + stylisticTypeCheckedOnly: TSESLint.FlatConfig.ConfigArray; + }; + parser: TSESLint.Parser.LooseParserModule; + plugin: TSESLint.FlatConfig.Plugin; +}; +export default _default; +export { config, type ConfigWithExtends, type InfiniteDepthConfigWithExtends, type ConfigArray, } from './config-helper'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/typescript-eslint/dist/index.d.ts.map b/node_modules/typescript-eslint/dist/index.d.ts.map new file mode 100644 index 00000000..104dd39f --- /dev/null +++ b/node_modules/typescript-eslint/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAKzD,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC,eAAO,MAAM,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC,MAAyB,CAAC;AAyBnE,eAAO,MAAM,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC,MAGxC,CAAC;AAEF,eAAO,MAAM,OAAO;IAClB;;;OAGG;;IAGH;;;;OAIG;;IAGH;;;OAGG;;IAGH;;;;;OAKG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAIH;;;OAGG;;IAIH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;IAGH;;;OAGG;;CAGJ,CAAC;AAEF,MAAM,MAAM,MAAM,GAAG,QAAQ,CAAC,UAAU,CAAC,UAAU,CAAC;;;;QArFlD;;;WAGG;;QAGH;;;;WAIG;;QAGH;;;WAGG;;QAGH;;;;;WAKG;;QAGH;;;WAGG;;QAGH;;;WAGG;;QAIH;;;WAGG;;QAIH;;;WAGG;;QAGH;;;WAGG;;QAGH;;;WAGG;;QAGH;;;WAGG;;QAGH;;;WAGG;;QAGH;;;WAGG;;;;;;AAgDL,wBAKE;AAEF,OAAO,EACL,MAAM,EACN,KAAK,iBAAiB,EACtB,KAAK,8BAA8B,EACnC,KAAK,WAAW,GACjB,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/node_modules/typescript-eslint/dist/index.js b/node_modules/typescript-eslint/dist/index.js new file mode 100644 index 00000000..9291b1b3 --- /dev/null +++ b/node_modules/typescript-eslint/dist/index.js @@ -0,0 +1,153 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.config = exports.configs = exports.plugin = exports.parser = void 0; +const eslint_plugin_1 = __importDefault(require("@typescript-eslint/eslint-plugin")); +const raw_plugin_1 = __importDefault(require("@typescript-eslint/eslint-plugin/use-at-your-own-risk/raw-plugin")); +const config_helper_1 = require("./config-helper"); +exports.parser = raw_plugin_1.default.parser; +/* +we could build a plugin object here without the `configs` key - but if we do +that then we create a situation in which +``` +require('typescript-eslint').plugin !== require('@typescript-eslint/eslint-plugin') +``` + +This is bad because it means that 3rd party configs would be required to use +`typescript-eslint` or else they would break a user's config if the user either +used `tseslint.configs.recomended` et al or +``` +{ + plugins: { + '@typescript-eslint': tseslint.plugin, + }, +} +``` + +This might be something we could consider okay (eg 3rd party flat configs must +use our new package); however legacy configs consumed via `@eslint/eslintrc` +would never be able to satisfy this constraint and thus users would be blocked +from using them. +*/ +exports.plugin = eslint_plugin_1.default; +exports.configs = { + /** + * Enables each the rules provided as a part of typescript-eslint. Note that many rules are not applicable in all codebases, or are meant to be configured. + * @see {@link https://typescript-eslint.io/users/configs#all} + */ + all: raw_plugin_1.default.flatConfigs['flat/all'], + /** + * A minimal ruleset that sets only the required parser and plugin options needed to run typescript-eslint. + * We don't recommend using this directly; instead, extend from an earlier recommended rule. + * @see {@link https://typescript-eslint.io/users/configs#base} + */ + base: raw_plugin_1.default.flatConfigs['flat/base'], + /** + * A utility ruleset that will disable type-aware linting and all type-aware rules available in our project. + * @see {@link https://typescript-eslint.io/users/configs#disable-type-checked} + */ + disableTypeChecked: raw_plugin_1.default.flatConfigs['flat/disable-type-checked'], + /** + * This is a compatibility ruleset that: + * - disables rules from eslint:recommended which are already handled by TypeScript. + * - enables rules that make sense due to TS's typechecking / transpilation. + * @see {@link https://typescript-eslint.io/users/configs/#eslint-recommended} + */ + eslintRecommended: raw_plugin_1.default.flatConfigs['flat/eslint-recommended'], + /** + * Recommended rules for code correctness that you can drop in without additional configuration. + * @see {@link https://typescript-eslint.io/users/configs#recommended} + */ + recommended: raw_plugin_1.default.flatConfigs['flat/recommended'], + /** + * Contains all of `recommended` along with additional recommended rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked} + */ + recommendedTypeChecked: raw_plugin_1.default.flatConfigs['flat/recommended-type-checked'], + /** + * A version of `recommended` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#recommended-type-checked-only} + */ + recommendedTypeCheckedOnly: raw_plugin_1.default.flatConfigs['flat/recommended-type-checked-only'], + /** + * Contains all of `recommended`, as well as additional strict rules that can also catch bugs. + * @see {@link https://typescript-eslint.io/users/configs#strict} + */ + strict: raw_plugin_1.default.flatConfigs['flat/strict'], + /** + * Contains all of `recommended`, `recommended-type-checked`, and `strict`, along with additional strict rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked} + */ + strictTypeChecked: raw_plugin_1.default.flatConfigs['flat/strict-type-checked'], + /** + * A version of `strict` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#strict-type-checked-only} + */ + strictTypeCheckedOnly: raw_plugin_1.default.flatConfigs['flat/strict-type-checked-only'], + /** + * Rules considered to be best practice for modern TypeScript codebases, but that do not impact program logic. + * @see {@link https://typescript-eslint.io/users/configs#stylistic} + */ + stylistic: raw_plugin_1.default.flatConfigs['flat/stylistic'], + /** + * Contains all of `stylistic`, along with additional stylistic rules that require type information. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked} + */ + stylisticTypeChecked: raw_plugin_1.default.flatConfigs['flat/stylistic-type-checked'], + /** + * A version of `stylistic` that only contains type-checked rules and disables of any corresponding core ESLint rules. + * @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked-only} + */ + stylisticTypeCheckedOnly: raw_plugin_1.default.flatConfigs['flat/stylistic-type-checked-only'], +}; +/* +we do both a default and named exports to allow people to use this package from +both CJS and ESM in very natural ways. + +EG it means that all of the following are valid: + +```ts +import tseslint from 'typescript-eslint'; + +export default tseslint.config( + ...tseslint.configs.recommended, +); +``` +```ts +import { config, parser, plugin } from 'typescript-eslint'; + +export default config( + { + languageOptions: { parser } + plugins: { ts: plugin }, + } +); +``` +```ts +const tseslint = require('typescript-eslint'); + +module.exports = tseslint.config( + ...tseslint.configs.recommended, +); +``` +```ts +const { config, parser, plugin } = require('typescript-eslint'); + +module.exports = config( + { + languageOptions: { parser } + plugins: { ts: plugin }, + } +); +``` +*/ +exports.default = { + config: config_helper_1.config, + configs: exports.configs, + parser: exports.parser, + plugin: exports.plugin, +}; +var config_helper_2 = require("./config-helper"); +Object.defineProperty(exports, "config", { enumerable: true, get: function () { return config_helper_2.config; } }); diff --git a/node_modules/typescript-eslint/package.json b/node_modules/typescript-eslint/package.json new file mode 100644 index 00000000..8eaff5aa --- /dev/null +++ b/node_modules/typescript-eslint/package.json @@ -0,0 +1,78 @@ +{ + "name": "typescript-eslint", + "version": "8.34.0", + "description": "Tooling which enables you to use TypeScript with ESLint", + "files": [ + "dist", + "!*.tsbuildinfo", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/typescript-eslint" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/typescript-eslint", + "license": "MIT", + "keywords": [ + "ast", + "ecmascript", + "javascript", + "typescript", + "parser", + "syntax", + "eslint", + "eslintplugin", + "eslint-plugin" + ], + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "yarn run -BT nx build", + "clean": "rimraf dist/ coverage/", + "format": "yarn run -T format", + "lint": "yarn run -BT nx lint", + "test": "yarn run -BT nx test", + "typecheck": "yarn run -BT nx typecheck" + }, + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.34.0", + "@typescript-eslint/parser": "8.34.0", + "@typescript-eslint/utils": "8.34.0" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + }, + "devDependencies": { + "@vitest/coverage-v8": "^3.1.3", + "rimraf": "*", + "typescript": "*", + "vitest": "^3.1.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "typescript-eslint", + "includedScripts": [ + "clean" + ] + } +} diff --git a/node_modules/typescript/LICENSE.txt b/node_modules/typescript/LICENSE.txt new file mode 100644 index 00000000..8746124b --- /dev/null +++ b/node_modules/typescript/LICENSE.txt @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/node_modules/typescript/README.md b/node_modules/typescript/README.md new file mode 100644 index 00000000..b6505f73 --- /dev/null +++ b/node_modules/typescript/README.md @@ -0,0 +1,50 @@ + +# TypeScript + +[![CI](https://github.com/microsoft/TypeScript/actions/workflows/ci.yml/badge.svg)](https://github.com/microsoft/TypeScript/actions/workflows/ci.yml) +[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript) +[![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript) +[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/microsoft/TypeScript/badge)](https://securityscorecards.dev/viewer/?uri=github.com/microsoft/TypeScript) + + +[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript). + +Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/). + +## Installing + +For the latest stable version: + +```bash +npm install -D typescript +``` + +For our nightly builds: + +```bash +npm install -D typescript@next +``` + +## Contribute + +There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript. +* [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in. +* Review the [source code changes](https://github.com/microsoft/TypeScript/pulls). +* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript). +* Help each other in the [TypeScript Community Discord](https://discord.gg/typescript). +* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter. +* [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md). + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see +the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) +with any additional questions or comments. + +## Documentation + +* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) +* [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html) +* [Homepage](https://www.typescriptlang.org/) + +## Roadmap + +For details on our planned features and future direction, please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap). diff --git a/node_modules/typescript/SECURITY.md b/node_modules/typescript/SECURITY.md new file mode 100644 index 00000000..b3c89efc --- /dev/null +++ b/node_modules/typescript/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd). + + diff --git a/node_modules/typescript/ThirdPartyNoticeText.txt b/node_modules/typescript/ThirdPartyNoticeText.txt new file mode 100644 index 00000000..a857fb3c --- /dev/null +++ b/node_modules/typescript/ThirdPartyNoticeText.txt @@ -0,0 +1,193 @@ +/*!----------------- TypeScript ThirdPartyNotices ------------------------------------------------------- + +The TypeScript software incorporates third party material from the projects listed below. The original copyright notice and the license under which Microsoft received such third party material are set forth below. Microsoft reserves all other rights not expressly granted, whether by implication, estoppel or otherwise. + +--------------------------------------------- +Third Party Code Components +-------------------------------------------- + +------------------- DefinitelyTyped -------------------- +This file is based on or incorporates material from the projects listed below (collectively "Third Party Code"). Microsoft is not the original author of the Third Party Code. The original copyright notice and the license, under which Microsoft received such Third Party Code, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft, not the third party, licenses the Third Party Code to you under the terms set forth in the EULA for the Microsoft Product. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise. +DefinitelyTyped +This project is licensed under the MIT license. Copyrights are respective of each contributor listed at the beginning of each definition file. Provided for Informational Purposes Only + +MIT License +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-------------------------------------------------------------------------------------- + +------------------- Unicode -------------------- +UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE + +Unicode Data Files include all data files under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and +http://www.unicode.org/utility/trac/browser/. + +Unicode Data Files do not include PDF online code charts under the +directory http://www.unicode.org/Public/. + +Software includes any source code published in the Unicode Standard +or under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and +http://www.unicode.org/utility/trac/browser/. + +NOTICE TO USER: Carefully read the following legal agreement. +BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S +DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), +YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. +IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE +THE DATA FILES OR SOFTWARE. + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1991-2017 Unicode, Inc. All rights reserved. +Distributed under the Terms of Use in http://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation +(the "Data Files") or Unicode software and any associated documentation +(the "Software") to deal in the Data Files or Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of +the Data Files or Software, and to permit persons to whom the Data Files +or Software are furnished to do so, provided that either +(a) this copyright and permission notice appear with all copies +of the Data Files or Software, or +(b) this copyright and permission notice appear in associated +Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT OF THIRD PARTY RIGHTS. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS +NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, +DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, +use or other dealings in these Data Files or Software without prior +written authorization of the copyright holder. +------------------------------------------------------------------------------------- + +-------------------Document Object Model----------------------------- +DOM + +W3C License +This work is being provided by the copyright holders under the following license. +By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. +Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following +on ALL copies of the work or portions thereof, including modifications: +* The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. +* Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included. +* Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived +from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." +Disclaimers +THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR +FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. +COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. +The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. +Title to copyright in this work will at all times remain with copyright holders. + +--------- + +DOM +Copyright © 2018 WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License: Attribution 4.0 International +======================================================================= +Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: + +wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= +Creative Commons Attribution 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the "Licensor." Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. + +-------------------------------------------------------------------------------- + +----------------------Web Background Synchronization------------------------------ + +Web Background Synchronization Specification +Portions of spec © by W3C + +W3C Community Final Specification Agreement +To secure commitments from participants for the full text of a Community or Business Group Report, the group may call for voluntary commitments to the following terms; a "summary" is +available. See also the related "W3C Community Contributor License Agreement". +1. The Purpose of this Agreement. +This Agreement sets forth the terms under which I make certain copyright and patent rights available to you for your implementation of the Specification. +Any other capitalized terms not specifically defined herein have the same meaning as those terms have in the "W3C Patent Policy", and if not defined there, in the "W3C Process Document". +2. Copyrights. +2.1. Copyright Grant. I grant to you a perpetual (for the duration of the applicable copyright), worldwide, non-exclusive, no-charge, royalty-free, copyright license, without any obligation for accounting to me, to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, distribute, and implement the Specification to the full extent of my copyright interest in the Specification. +2.2. Attribution. As a condition of the copyright grant, you must include an attribution to the Specification in any derivative work you make based on the Specification. That attribution must include, at minimum, the Specification name and version number. +3. Patents. +3.1. Patent Licensing Commitment. I agree to license my Essential Claims under the W3C Community RF Licensing Requirements. This requirement includes Essential Claims that I own and any that I have the right to license without obligation of payment or other consideration to an unrelated third party. W3C Community RF Licensing Requirements obligations made concerning the Specification and described in this policy are binding on me for the life of the patents in question and encumber the patents containing Essential Claims, regardless of changes in participation status or W3C Membership. I also agree to license my Essential Claims under the W3C Community RF Licensing Requirements in derivative works of the Specification so long as all normative portions of the Specification are maintained and that this licensing commitment does not extend to any portion of the derivative work that was not included in the Specification. +3.2. Optional, Additional Patent Grant. In addition to the provisions of Section 3.1, I may also, at my option, make certain intellectual property rights infringed by implementations of the Specification, including Essential Claims, available by providing those terms via the W3C Web site. +4. No Other Rights. Except as specifically set forth in this Agreement, no other express or implied patent, trademark, copyright, or other property rights are granted under this Agreement, including by implication, waiver, or estoppel. +5. Antitrust Compliance. I acknowledge that I may compete with other participants, that I am under no obligation to implement the Specification, that each participant is free to develop competing technologies and standards, and that each party is free to license its patent rights to third parties, including for the purpose of enabling competing technologies and standards. +6. Non-Circumvention. I agree that I will not intentionally take or willfully assist any third party to take any action for the purpose of circumventing my obligations under this Agreement. +7. Transition to W3C Recommendation Track. The Specification developed by the Project may transition to the W3C Recommendation Track. The W3C Team is responsible for notifying me that a Corresponding Working Group has been chartered. I have no obligation to join the Corresponding Working Group. If the Specification developed by the Project transitions to the W3C Recommendation Track, the following terms apply: +7.1. If I join the Corresponding Working Group. If I join the Corresponding Working Group, I will be subject to all W3C rules, obligations, licensing commitments, and policies that govern that Corresponding Working Group. +7.2. If I Do Not Join the Corresponding Working Group. +7.2.1. Licensing Obligations to Resulting Specification. If I do not join the Corresponding Working Group, I agree to offer patent licenses according to the W3C Royalty-Free licensing requirements described in Section 5 of the W3C Patent Policy for the portions of the Specification included in the resulting Recommendation. This licensing commitment does not extend to any portion of an implementation of the Recommendation that was not included in the Specification. This licensing commitment may not be revoked but may be modified through the exclusion process defined in Section 4 of the W3C Patent Policy. I am not required to join the Corresponding Working Group to exclude patents from the W3C Royalty-Free licensing commitment, but must otherwise follow the normal exclusion procedures defined by the W3C Patent Policy. The W3C Team will notify me of any Call for Exclusion in the Corresponding Working Group as set forth in Section 4.5 of the W3C Patent Policy. +7.2.2. No Disclosure Obligation. If I do not join the Corresponding Working Group, I have no patent disclosure obligations outside of those set forth in Section 6 of the W3C Patent Policy. +8. Conflict of Interest. I will disclose significant relationships when those relationships might reasonably be perceived as creating a conflict of interest with my role. I will notify W3C of any change in my affiliation using W3C-provided mechanisms. +9. Representations, Warranties and Disclaimers. I represent and warrant that I am legally entitled to grant the rights and promises set forth in this Agreement. IN ALL OTHER RESPECTS THE SPECIFICATION IS PROVIDED “AS IS.” The entire risk as to implementing or otherwise using the Specification is assumed by the implementer and user. Except as stated herein, I expressly disclaim any warranties (express, implied, or otherwise), including implied warranties of merchantability, non-infringement, fitness for a particular purpose, or title, related to the Specification. IN NO EVENT WILL ANY PARTY BE LIABLE TO ANY OTHER PARTY FOR LOST PROFITS OR ANY FORM OF INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER FROM ANY CAUSES OF ACTION OF ANY KIND WITH RESPECT TO THIS AGREEMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT THE OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. All of my obligations under Section 3 regarding the transfer, successors in interest, or assignment of Granted Claims will be satisfied if I notify the transferee or assignee of any patent that I know contains Granted Claims of the obligations under Section 3. Nothing in this Agreement requires me to undertake a patent search. +10. Definitions. +10.1. Agreement. “Agreement” means this W3C Community Final Specification Agreement. +10.2. Corresponding Working Group. “Corresponding Working Group” is a W3C Working Group that is chartered to develop a Recommendation, as defined in the W3C Process Document, that takes the Specification as an input. +10.3. Essential Claims. “Essential Claims” shall mean all claims in any patent or patent application in any jurisdiction in the world that would necessarily be infringed by implementation of the Specification. A claim is necessarily infringed hereunder only when it is not possible to avoid infringing it because there is no non-infringing alternative for implementing the normative portions of the Specification. Existence of a non-infringing alternative shall be judged based on the state of the art at the time of the publication of the Specification. The following are expressly excluded from and shall not be deemed to constitute Essential Claims: +10.3.1. any claims other than as set forth above even if contained in the same patent as Essential Claims; and +10.3.2. claims which would be infringed only by: +portions of an implementation that are not specified in the normative portions of the Specification, or +enabling technologies that may be necessary to make or use any product or portion thereof that complies with the Specification and are not themselves expressly set forth in the Specification (e.g., semiconductor manufacturing technology, compiler technology, object-oriented technology, basic operating system technology, and the like); or +the implementation of technology developed elsewhere and merely incorporated by reference in the body of the Specification. +10.3.3. design patents and design registrations. +For purposes of this definition, the normative portions of the Specification shall be deemed to include only architectural and interoperability requirements. Optional features in the RFC 2119 sense are considered normative unless they are specifically identified as informative. Implementation examples or any other material that merely illustrate the requirements of the Specification are informative, rather than normative. +10.4. I, Me, or My. “I,” “me,” or “my” refers to the signatory. +10.5 Project. “Project” means the W3C Community Group or Business Group for which I executed this Agreement. +10.6. Specification. “Specification” means the Specification identified by the Project as the target of this agreement in a call for Final Specification Commitments. W3C shall provide the authoritative mechanisms for the identification of this Specification. +10.7. W3C Community RF Licensing Requirements. “W3C Community RF Licensing Requirements” license shall mean a non-assignable, non-sublicensable license to make, have made, use, sell, have sold, offer to sell, import, and distribute and dispose of implementations of the Specification that: +10.7.1. shall be available to all, worldwide, whether or not they are W3C Members; +10.7.2. shall extend to all Essential Claims owned or controlled by me; +10.7.3. may be limited to implementations of the Specification, and to what is required by the Specification; +10.7.4. may be conditioned on a grant of a reciprocal RF license (as defined in this policy) to all Essential Claims owned or controlled by the licensee. A reciprocal license may be required to be available to all, and a reciprocal license may itself be conditioned on a further reciprocal license from all. +10.7.5. may not be conditioned on payment of royalties, fees or other consideration; +10.7.6. may be suspended with respect to any licensee when licensor issued by licensee for infringement of claims essential to implement the Specification or any W3C Recommendation; +10.7.7. may not impose any further conditions or restrictions on the use of any technology, intellectual property rights, or other restrictions on behavior of the licensee, but may include reasonable, customary terms relating to operation or maintenance of the license relationship such as the following: choice of law and dispute resolution; +10.7.8. shall not be considered accepted by an implementer who manifests an intent not to accept the terms of the W3C Community RF Licensing Requirements license as offered by the licensor. +10.7.9. The RF license conforming to the requirements in this policy shall be made available by the licensor as long as the Specification is in effect. The term of such license shall be for the life of the patents in question. +I am encouraged to provide a contact from which licensing information can be obtained and other relevant licensing information. Any such information will be made publicly available. +10.8. You or Your. “You,” “you,” or “your” means any person or entity who exercises copyright or patent rights granted under this Agreement, and any person that person or entity controls. + +------------------------------------------------------------------------------------- + +------------------- WebGL ----------------------------- +Copyright (c) 2018 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +------------------------------------------------------ + +------------- End of ThirdPartyNotices ------------------------------------------- */ + diff --git a/node_modules/typescript/bin/tsc b/node_modules/typescript/bin/tsc new file mode 100755 index 00000000..19c62bf7 --- /dev/null +++ b/node_modules/typescript/bin/tsc @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../lib/tsc.js') diff --git a/node_modules/typescript/bin/tsserver b/node_modules/typescript/bin/tsserver new file mode 100755 index 00000000..7143b6a7 --- /dev/null +++ b/node_modules/typescript/bin/tsserver @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../lib/tsserver.js') diff --git a/node_modules/typescript/lib/_tsc.js b/node_modules/typescript/lib/_tsc.js new file mode 100644 index 00000000..90c73288 --- /dev/null +++ b/node_modules/typescript/lib/_tsc.js @@ -0,0 +1,132810 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +"use strict"; + +// src/compiler/corePublic.ts +var versionMajorMinor = "5.8"; +var version = "5.8.3"; + +// src/compiler/core.ts +var emptyArray = []; +var emptyMap = /* @__PURE__ */ new Map(); +function length(array) { + return array !== void 0 ? array.length : 0; +} +function forEach(array, callback) { + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + const result = callback(array[i], i); + if (result) { + return result; + } + } + } + return void 0; +} +function firstDefined(array, callback) { + if (array === void 0) { + return void 0; + } + for (let i = 0; i < array.length; i++) { + const result = callback(array[i], i); + if (result !== void 0) { + return result; + } + } + return void 0; +} +function firstDefinedIterator(iter, callback) { + for (const value of iter) { + const result = callback(value); + if (result !== void 0) { + return result; + } + } + return void 0; +} +function reduceLeftIterator(iterator, f, initial) { + let result = initial; + if (iterator) { + let pos = 0; + for (const value of iterator) { + result = f(result, value, pos); + pos++; + } + } + return result; +} +function zipWith(arrayA, arrayB, callback) { + const result = []; + Debug.assertEqual(arrayA.length, arrayB.length); + for (let i = 0; i < arrayA.length; i++) { + result.push(callback(arrayA[i], arrayB[i], i)); + } + return result; +} +function every(array, callback) { + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; +} +function find(array, predicate, startIndex) { + if (array === void 0) return void 0; + for (let i = startIndex ?? 0; i < array.length; i++) { + const value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return void 0; +} +function findLast(array, predicate, startIndex) { + if (array === void 0) return void 0; + for (let i = startIndex ?? array.length - 1; i >= 0; i--) { + const value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return void 0; +} +function findIndex(array, predicate, startIndex) { + if (array === void 0) return -1; + for (let i = startIndex ?? 0; i < array.length; i++) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; +} +function findLastIndex(array, predicate, startIndex) { + if (array === void 0) return -1; + for (let i = startIndex ?? array.length - 1; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; +} +function contains(array, value, equalityComparer = equateValues) { + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + if (equalityComparer(array[i], value)) { + return true; + } + } + } + return false; +} +function indexOfAnyCharCode(text, charCodes, start) { + for (let i = start ?? 0; i < text.length; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; +} +function countWhere(array, predicate) { + let count = 0; + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + const v = array[i]; + if (predicate(v, i)) { + count++; + } + } + } + return count; +} +function filter(array, f) { + if (array !== void 0) { + const len = array.length; + let i = 0; + while (i < len && f(array[i])) i++; + if (i < len) { + const result = array.slice(0, i); + i++; + while (i < len) { + const item = array[i]; + if (f(item)) { + result.push(item); + } + i++; + } + return result; + } + } + return array; +} +function filterMutate(array, f) { + let outIndex = 0; + for (let i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; + outIndex++; + } + } + array.length = outIndex; +} +function clear(array) { + array.length = 0; +} +function map(array, f) { + let result; + if (array !== void 0) { + result = []; + for (let i = 0; i < array.length; i++) { + result.push(f(array[i], i)); + } + } + return result; +} +function* mapIterator(iter, mapFn) { + for (const x of iter) { + yield mapFn(x); + } +} +function sameMap(array, f) { + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + const item = array[i]; + const mapped = f(item, i); + if (item !== mapped) { + const result = array.slice(0, i); + result.push(mapped); + for (i++; i < array.length; i++) { + result.push(f(array[i], i)); + } + return result; + } + } + } + return array; +} +function flatten(array) { + const result = []; + for (let i = 0; i < array.length; i++) { + const v = array[i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } else { + result.push(v); + } + } + } + return result; +} +function flatMap(array, mapfn) { + let result; + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + const v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } else { + result = append(result, v); + } + } + } + } + return result ?? emptyArray; +} +function flatMapToMutable(array, mapfn) { + const result = []; + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + const v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } else { + result.push(v); + } + } + } + } + return result; +} +function sameFlatMap(array, mapfn) { + let result; + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + const item = array[i]; + const mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } else { + result.push(mapped); + } + } + } + } + return result ?? array; +} +function mapDefined(array, mapFn) { + const result = []; + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + const mapped = mapFn(array[i], i); + if (mapped !== void 0) { + result.push(mapped); + } + } + } + return result; +} +function* mapDefinedIterator(iter, mapFn) { + for (const x of iter) { + const value = mapFn(x); + if (value !== void 0) { + yield value; + } + } +} +function getOrUpdate(map2, key, callback) { + if (map2.has(key)) { + return map2.get(key); + } + const value = callback(); + map2.set(key, value); + return value; +} +function tryAddToSet(set, value) { + if (!set.has(value)) { + set.add(value); + return true; + } + return false; +} +function spanMap(array, keyfn, mapfn) { + let result; + if (array !== void 0) { + result = []; + const len = array.length; + let previousKey; + let key; + let start = 0; + let pos = 0; + while (start < len) { + while (pos < len) { + const value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + const v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; +} +function some(array, predicate) { + if (array !== void 0) { + if (predicate !== void 0) { + for (let i = 0; i < array.length; i++) { + if (predicate(array[i])) { + return true; + } + } + } else { + return array.length > 0; + } + } + return false; +} +function getRangesWhere(arr, pred, cb) { + let start; + for (let i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === void 0 ? i : start; + } else { + if (start !== void 0) { + cb(start, i); + start = void 0; + } + } + } + if (start !== void 0) cb(start, arr.length); +} +function concatenate(array1, array2) { + if (array2 === void 0 || array2.length === 0) return array1; + if (array1 === void 0 || array1.length === 0) return array2; + return [...array1, ...array2]; +} +function selectIndex(_, i) { + return i; +} +function indicesOf(array) { + return array.map(selectIndex); +} +function deduplicateRelational(array, equalityComparer, comparer) { + const indices = indicesOf(array); + stableSortIndices(array, indices, comparer); + let last2 = array[indices[0]]; + const deduplicated = [indices[0]]; + for (let i = 1; i < indices.length; i++) { + const index = indices[i]; + const item = array[index]; + if (!equalityComparer(last2, item)) { + deduplicated.push(index); + last2 = item; + } + } + deduplicated.sort(); + return deduplicated.map((i) => array[i]); +} +function deduplicateEquality(array, equalityComparer) { + const result = []; + for (let i = 0; i < array.length; i++) { + pushIfUnique(result, array[i], equalityComparer); + } + return result; +} +function deduplicate(array, equalityComparer, comparer) { + return array.length === 0 ? [] : array.length === 1 ? array.slice() : comparer ? deduplicateRelational(array, equalityComparer, comparer) : deduplicateEquality(array, equalityComparer); +} +function deduplicateSorted(array, comparer) { + if (array.length === 0) return emptyArray; + let last2 = array[0]; + const deduplicated = [last2]; + for (let i = 1; i < array.length; i++) { + const next = array[i]; + switch (comparer(next, last2)) { + // equality comparison + case true: + // relational comparison + // falls through + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last2 = next); + } + return deduplicated; +} +function insertSorted(array, insert, compare, equalityComparer, allowDuplicates) { + if (array.length === 0) { + array.push(insert); + return true; + } + const insertIndex = binarySearch(array, insert, identity, compare); + if (insertIndex < 0) { + if (equalityComparer && !allowDuplicates) { + const idx = ~insertIndex; + if (idx > 0 && equalityComparer(insert, array[idx - 1])) { + return false; + } + if (idx < array.length && equalityComparer(insert, array[idx])) { + array.splice(idx, 1, insert); + return true; + } + } + array.splice(~insertIndex, 0, insert); + return true; + } + if (allowDuplicates) { + array.splice(insertIndex, 0, insert); + return true; + } + return false; +} +function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(toSorted(array, comparer), equalityComparer ?? comparer ?? compareStringsCaseSensitive); +} +function arrayIsEqualTo(array1, array2, equalityComparer = equateValues) { + if (array1 === void 0 || array2 === void 0) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (let i = 0; i < array1.length; i++) { + if (!equalityComparer(array1[i], array2[i], i)) { + return false; + } + } + return true; +} +function compact(array) { + let result; + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + const v = array[i]; + if (result ?? !v) { + result ?? (result = array.slice(0, i)); + if (v) { + result.push(v); + } + } + } + } + return result ?? array; +} +function relativeComplement(arrayA, arrayB, comparer) { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; + const result = []; + loopB: + for (let offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: + for (const startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + continue loopB; + case 1 /* GreaterThan */: + continue loopA; + } + } + } + return result; +} +function append(to, value) { + if (value === void 0) return to; + if (to === void 0) return [value]; + to.push(value); + return to; +} +function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; +} +function addRange(to, from, start, end) { + if (from === void 0 || from.length === 0) return to; + if (to === void 0) return from.slice(start, end); + start = start === void 0 ? 0 : toOffset(from, start); + end = end === void 0 ? from.length : toOffset(from, end); + for (let i = start; i < end && i < from.length; i++) { + if (from[i] !== void 0) { + to.push(from[i]); + } + } + return to; +} +function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { + return false; + } else { + array.push(toAdd); + return true; + } +} +function appendIfUnique(array, toAdd, equalityComparer) { + if (array !== void 0) { + pushIfUnique(array, toAdd, equalityComparer); + return array; + } else { + return [toAdd]; + } +} +function stableSortIndices(array, indices, comparer) { + indices.sort((x, y) => comparer(array[x], array[y]) || compareValues(x, y)); +} +function toSorted(array, comparer) { + return array.length === 0 ? emptyArray : array.slice().sort(comparer); +} +function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; +} +var elementAt = !!Array.prototype.at ? (array, offset) => array == null ? void 0 : array.at(offset) : (array, offset) => { + if (array !== void 0) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return void 0; +}; +function firstOrUndefined(array) { + return array === void 0 || array.length === 0 ? void 0 : array[0]; +} +function firstOrUndefinedIterator(iter) { + if (iter !== void 0) { + for (const value of iter) { + return value; + } + } + return void 0; +} +function first(array) { + Debug.assert(array.length !== 0); + return array[0]; +} +function firstIterator(iter) { + for (const value of iter) { + return value; + } + Debug.fail("iterator is empty"); +} +function lastOrUndefined(array) { + return array === void 0 || array.length === 0 ? void 0 : array[array.length - 1]; +} +function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; +} +function singleOrUndefined(array) { + return array !== void 0 && array.length === 1 ? array[0] : void 0; +} +function singleOrMany(array) { + return array !== void 0 && array.length === 1 ? array[0] : array; +} +function replaceElement(array, index, value) { + const result = array.slice(0); + result[index] = value; + return result; +} +function binarySearch(array, value, keySelector, keyComparer, offset) { + return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); +} +function binarySearchKey(array, key, keySelector, keyComparer, offset) { + if (!some(array)) { + return -1; + } + let low = offset ?? 0; + let high = array.length - 1; + while (low <= high) { + const middle = low + (high - low >> 1); + const midKey = keySelector(array[middle], middle); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; + } + } + return ~low; +} +function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + const size = array.length; + if (size > 0) { + let pos = start === void 0 || start < 0 ? 0 : start; + const end = count === void 0 || pos + count > size - 1 ? size - 1 : pos + count; + let result; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } else { + result = initial; + } + while (pos <= end) { + result = f(result, array[pos], pos); + pos++; + } + return result; + } + } + return initial; +} +var hasOwnProperty = Object.prototype.hasOwnProperty; +function hasProperty(map2, key) { + return hasOwnProperty.call(map2, key); +} +function getOwnKeys(map2) { + const keys = []; + for (const key in map2) { + if (hasOwnProperty.call(map2, key)) { + keys.push(key); + } + } + return keys; +} +function getOwnValues(collection) { + const values = []; + for (const key in collection) { + if (hasOwnProperty.call(collection, key)) { + values.push(collection[key]); + } + } + return values; +} +function arrayOf(count, f) { + const result = new Array(count); + for (let i = 0; i < count; i++) { + result[i] = f(i); + } + return result; +} +function arrayFrom(iterator, map2) { + const result = []; + for (const value of iterator) { + result.push(map2 ? map2(value) : value); + } + return result; +} +function assign(t, ...args) { + for (const arg of args) { + if (arg === void 0) continue; + for (const p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; + } + } + } + return t; +} +function equalOwnProperties(left, right, equalityComparer = equateValues) { + if (left === right) return true; + if (!left || !right) return false; + for (const key in left) { + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key)) return false; + if (!equalityComparer(left[key], right[key])) return false; + } + } + for (const key in right) { + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) return false; + } + } + return true; +} +function arrayToMap(array, makeKey, makeValue = identity) { + const result = /* @__PURE__ */ new Map(); + for (let i = 0; i < array.length; i++) { + const value = array[i]; + const key = makeKey(value); + if (key !== void 0) result.set(key, makeValue(value)); + } + return result; +} +function arrayToMultiMap(values, makeKey, makeValue = identity) { + const result = createMultiMap(); + for (let i = 0; i < values.length; i++) { + const value = values[i]; + result.add(makeKey(value), makeValue(value)); + } + return result; +} +function group(values, getGroupId, resultSelector = identity) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector); +} +function groupBy(values, keySelector) { + const result = {}; + if (values !== void 0) { + for (let i = 0; i < values.length; i++) { + const value = values[i]; + const key = `${keySelector(value)}`; + const array = result[key] ?? (result[key] = []); + array.push(value); + } + } + return result; +} +function extend(first2, second) { + const result = {}; + for (const id in second) { + if (hasOwnProperty.call(second, id)) { + result[id] = second[id]; + } + } + for (const id in first2) { + if (hasOwnProperty.call(first2, id)) { + result[id] = first2[id]; + } + } + return result; +} +function copyProperties(first2, second) { + for (const id in second) { + if (hasOwnProperty.call(second, id)) { + first2[id] = second[id]; + } + } +} +function maybeBind(obj, fn) { + return fn == null ? void 0 : fn.bind(obj); +} +function createMultiMap() { + const map2 = /* @__PURE__ */ new Map(); + map2.add = multiMapAdd; + map2.remove = multiMapRemove; + return map2; +} +function multiMapAdd(key, value) { + let values = this.get(key); + if (values !== void 0) { + values.push(value); + } else { + this.set(key, values = [value]); + } + return values; +} +function multiMapRemove(key, value) { + const values = this.get(key); + if (values !== void 0) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } +} +function createQueue(items) { + const elements = (items == null ? void 0 : items.slice()) ?? []; + let headIndex = 0; + function isEmpty() { + return headIndex === elements.length; + } + function enqueue(...items2) { + elements.push(...items2); + } + function dequeue() { + if (isEmpty()) { + throw new Error("Queue is empty"); + } + const result = elements[headIndex]; + elements[headIndex] = void 0; + headIndex++; + if (headIndex > 100 && headIndex > elements.length >> 1) { + const newLength = elements.length - headIndex; + elements.copyWithin( + /*target*/ + 0, + /*start*/ + headIndex + ); + elements.length = newLength; + headIndex = 0; + } + return result; + } + return { + enqueue, + dequeue, + isEmpty + }; +} +function isArray(value) { + return Array.isArray(value); +} +function toArray(value) { + return isArray(value) ? value : [value]; +} +function isString(text) { + return typeof text === "string"; +} +function isNumber(x) { + return typeof x === "number"; +} +function tryCast(value, test) { + return value !== void 0 && test(value) ? value : void 0; +} +function cast(value, test) { + if (value !== void 0 && test(value)) return value; + return Debug.fail(`Invalid cast. The supplied value ${value} did not pass the test '${Debug.getFunctionName(test)}'.`); +} +function noop(_) { +} +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} +function returnUndefined() { + return void 0; +} +function identity(x) { + return x; +} +function toLowerCase(x) { + return x.toLowerCase(); +} +var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g; +function toFileNameLowerCase(x) { + return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x; +} +function notImplemented() { + throw new Error("Not implemented"); +} +function memoize(callback) { + let value; + return () => { + if (callback) { + value = callback(); + callback = void 0; + } + return value; + }; +} +function memoizeOne(callback) { + const map2 = /* @__PURE__ */ new Map(); + return (arg) => { + const key = `${typeof arg}:${arg}`; + let value = map2.get(key); + if (value === void 0 && !map2.has(key)) { + value = callback(arg); + map2.set(key, value); + } + return value; + }; +} +function equateValues(a, b) { + return a === b; +} +function equateStringsCaseInsensitive(a, b) { + return a === b || a !== void 0 && b !== void 0 && a.toUpperCase() === b.toUpperCase(); +} +function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); +} +function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : a === void 0 ? -1 /* LessThan */ : b === void 0 ? 1 /* GreaterThan */ : a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; +} +function compareValues(a, b) { + return compareComparableValues(a, b); +} +function maxBy(arr, init, mapper) { + for (let i = 0; i < arr.length; i++) { + init = Math.max(init, mapper(arr[i])); + } + return init; +} +function min(items, compare) { + return reduceLeft(items, (x, y) => compare(x, y) === -1 /* LessThan */ ? x : y); +} +function compareStringsCaseInsensitive(a, b) { + if (a === b) return 0 /* EqualTo */; + if (a === void 0) return -1 /* LessThan */; + if (b === void 0) return 1 /* GreaterThan */; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; +} +function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); +} +function getStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; +} +var uiComparerCaseSensitive; +var uiLocale; +function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = void 0; + } +} +function compareBooleans(a, b) { + return compareValues(a ? 1 : 0, b ? 1 : 0); +} +function getSpellingSuggestion(name, candidates, getName) { + const maximumLengthDifference = Math.max(2, Math.floor(name.length * 0.34)); + let bestDistance = Math.floor(name.length * 0.4) + 1; + let bestCandidate; + for (const candidate of candidates) { + const candidateName = getName(candidate); + if (candidateName !== void 0 && Math.abs(candidateName.length - name.length) <= maximumLengthDifference) { + if (candidateName === name) { + continue; + } + if (candidateName.length < 3 && candidateName.toLowerCase() !== name.toLowerCase()) { + continue; + } + const distance = levenshteinWithMax(name, candidateName, bestDistance - 0.1); + if (distance === void 0) { + continue; + } + Debug.assert(distance < bestDistance); + bestDistance = distance; + bestCandidate = candidate; + } + } + return bestCandidate; +} +function levenshteinWithMax(s1, s2, max) { + let previous = new Array(s2.length + 1); + let current = new Array(s2.length + 1); + const big = max + 0.01; + for (let i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (let i = 1; i <= s1.length; i++) { + const c1 = s1.charCodeAt(i - 1); + const minJ = Math.ceil(i > max ? i - max : 1); + const maxJ = Math.floor(s2.length > max + i ? max + i : s2.length); + current[0] = i; + let colMin = i; + for (let j = 1; j < minJ; j++) { + current[j] = big; + } + for (let j = minJ; j <= maxJ; j++) { + const substitutionDistance = s1[i - 1].toLowerCase() === s2[j - 1].toLowerCase() ? previous[j - 1] + 0.1 : previous[j - 1] + 2; + const dist = c1 === s2.charCodeAt(j - 1) ? previous[j - 1] : Math.min( + /*delete*/ + previous[j] + 1, + /*insert*/ + current[j - 1] + 1, + /*substitute*/ + substitutionDistance + ); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (let j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + return void 0; + } + const temp = previous; + previous = current; + current = temp; + } + const res = previous[s2.length]; + return res > max ? void 0 : res; +} +function endsWith(str, suffix, ignoreCase) { + const expectedPos = str.length - suffix.length; + return expectedPos >= 0 && (ignoreCase ? equateStringsCaseInsensitive(str.slice(expectedPos), suffix) : str.indexOf(suffix, expectedPos) === expectedPos); +} +function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; +} +function orderedRemoveItem(array, item) { + for (let i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; +} +function orderedRemoveItemAt(array, index) { + for (let i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); +} +function unorderedRemoveItemAt(array, index) { + array[index] = array[array.length - 1]; + array.pop(); +} +function unorderedRemoveItem(array, item) { + return unorderedRemoveFirstItemWhere(array, (element) => element === item); +} +function unorderedRemoveFirstItemWhere(array, predicate) { + for (let i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + return true; + } + } + return false; +} +function createGetCanonicalFileName(useCaseSensitiveFileNames2) { + return useCaseSensitiveFileNames2 ? identity : toFileNameLowerCase; +} +function patternText({ prefix, suffix }) { + return `${prefix}*${suffix}`; +} +function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); +} +function findBestPatternMatch(values, getPattern, candidate) { + let matchedValue; + let longestMatchPrefixLength = -1; + for (let i = 0; i < values.length; i++) { + const v = values[i]; + const pattern = getPattern(v); + if (pattern.prefix.length > longestMatchPrefixLength && isPatternMatch(pattern, candidate)) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; +} +function startsWith(str, prefix, ignoreCase) { + return ignoreCase ? equateStringsCaseInsensitive(str.slice(0, prefix.length), prefix) : str.lastIndexOf(prefix, 0) === 0; +} +function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; +} +function isPatternMatch({ prefix, suffix }, candidate) { + return candidate.length >= prefix.length + suffix.length && startsWith(candidate, prefix) && endsWith(candidate, suffix); +} +function and(f, g) { + return (arg) => f(arg) && g(arg); +} +function or(...fs) { + return (...args) => { + let lastResult; + for (const f of fs) { + lastResult = f(...args); + if (lastResult) { + return lastResult; + } + } + return lastResult; + }; +} +function not(fn) { + return (...args) => !fn(...args); +} +function assertType(_) { +} +function singleElementArray(t) { + return t === void 0 ? void 0 : [t]; +} +function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged ?? (unchanged = noop); + let newIndex = 0; + let oldIndex = 0; + const newLen = newItems.length; + const oldLen = oldItems.length; + let hasChanges = false; + while (newIndex < newLen && oldIndex < oldLen) { + const newItem = newItems[newIndex]; + const oldItem = oldItems[oldIndex]; + const compareResult = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + hasChanges = true; + } else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + hasChanges = true; + } else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + hasChanges = true; + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + hasChanges = true; + } + return hasChanges; +} +function cartesianProduct(arrays) { + const result = []; + cartesianProductWorker( + arrays, + result, + /*outer*/ + void 0, + 0 + ); + return result; +} +function cartesianProductWorker(arrays, result, outer, index) { + for (const element of arrays[index]) { + let inner; + if (outer) { + inner = outer.slice(); + inner.push(element); + } else { + inner = [element]; + } + if (index === arrays.length - 1) { + result.push(inner); + } else { + cartesianProductWorker(arrays, result, inner, index + 1); + } + } +} +function takeWhile(array, predicate) { + if (array !== void 0) { + const len = array.length; + let index = 0; + while (index < len && predicate(array[index])) { + index++; + } + return array.slice(0, index); + } +} +function skipWhile(array, predicate) { + if (array !== void 0) { + const len = array.length; + let index = 0; + while (index < len && predicate(array[index])) { + index++; + } + return array.slice(index); + } +} +function isNodeLikeSystem() { + return typeof process !== "undefined" && !!process.nextTick && !process.browser && typeof require !== "undefined"; +} + +// src/compiler/debug.ts +var Debug; +((Debug2) => { + let currentAssertionLevel = 0 /* None */; + Debug2.currentLogLevel = 2 /* Warning */; + Debug2.isDebugging = false; + function shouldLog(level) { + return Debug2.currentLogLevel <= level; + } + Debug2.shouldLog = shouldLog; + function logMessage(level, s) { + if (Debug2.loggingHost && shouldLog(level)) { + Debug2.loggingHost.log(level, s); + } + } + function log(s) { + logMessage(3 /* Info */, s); + } + Debug2.log = log; + ((_log) => { + function error(s) { + logMessage(1 /* Error */, s); + } + _log.error = error; + function warn(s) { + logMessage(2 /* Warning */, s); + } + _log.warn = warn; + function log2(s) { + logMessage(3 /* Info */, s); + } + _log.log = log2; + function trace2(s) { + logMessage(4 /* Verbose */, s); + } + _log.trace = trace2; + })(log = Debug2.log || (Debug2.log = {})); + const assertionCache = {}; + function getAssertionLevel() { + return currentAssertionLevel; + } + Debug2.getAssertionLevel = getAssertionLevel; + function setAssertionLevel(level) { + const prevAssertionLevel = currentAssertionLevel; + currentAssertionLevel = level; + if (level > prevAssertionLevel) { + for (const key of getOwnKeys(assertionCache)) { + const cachedFunc = assertionCache[key]; + if (cachedFunc !== void 0 && Debug2[key] !== cachedFunc.assertion && level >= cachedFunc.level) { + Debug2[key] = cachedFunc; + assertionCache[key] = void 0; + } + } + } + } + Debug2.setAssertionLevel = setAssertionLevel; + function shouldAssert(level) { + return currentAssertionLevel >= level; + } + Debug2.shouldAssert = shouldAssert; + function shouldAssertFunction(level, name) { + if (!shouldAssert(level)) { + assertionCache[name] = { level, assertion: Debug2[name] }; + Debug2[name] = noop; + return false; + } + return true; + } + function fail(message, stackCrawlMark) { + debugger; + const e = new Error(message ? `Debug Failure. ${message}` : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; + } + Debug2.fail = fail; + function failBadSyntaxKind(node, message, stackCrawlMark) { + return fail( + `${message || "Unexpected node."}\r +Node ${formatSyntaxKind(node.kind)} was unexpected.`, + stackCrawlMark || failBadSyntaxKind + ); + } + Debug2.failBadSyntaxKind = failBadSyntaxKind; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + message = message ? `False expression: ${message}` : "False expression."; + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message, stackCrawlMark || assert); + } + } + Debug2.assert = assert; + function assertEqual(a, b, msg, msg2, stackCrawlMark) { + if (a !== b) { + const message = msg ? msg2 ? `${msg} ${msg2}` : msg : ""; + fail(`Expected ${a} === ${b}. ${message}`, stackCrawlMark || assertEqual); + } + } + Debug2.assertEqual = assertEqual; + function assertLessThan(a, b, msg, stackCrawlMark) { + if (a >= b) { + fail(`Expected ${a} < ${b}. ${msg || ""}`, stackCrawlMark || assertLessThan); + } + } + Debug2.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b, stackCrawlMark) { + if (a > b) { + fail(`Expected ${a} <= ${b}`, stackCrawlMark || assertLessThanOrEqual); + } + } + Debug2.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b, stackCrawlMark) { + if (a < b) { + fail(`Expected ${a} >= ${b}`, stackCrawlMark || assertGreaterThanOrEqual); + } + } + Debug2.assertGreaterThanOrEqual = assertGreaterThanOrEqual; + function assertIsDefined(value, message, stackCrawlMark) { + if (value === void 0 || value === null) { + fail(message, stackCrawlMark || assertIsDefined); + } + } + Debug2.assertIsDefined = assertIsDefined; + function checkDefined(value, message, stackCrawlMark) { + assertIsDefined(value, message, stackCrawlMark || checkDefined); + return value; + } + Debug2.checkDefined = checkDefined; + function assertEachIsDefined(value, message, stackCrawlMark) { + for (const v of value) { + assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined); + } + } + Debug2.assertEachIsDefined = assertEachIsDefined; + function checkEachDefined(value, message, stackCrawlMark) { + assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined); + return value; + } + Debug2.checkEachDefined = checkEachDefined; + function assertNever(member, message = "Illegal value:", stackCrawlMark) { + const detail = typeof member === "object" && hasProperty(member, "kind") && hasProperty(member, "pos") ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member); + return fail(`${message} ${detail}`, stackCrawlMark || assertNever); + } + Debug2.assertNever = assertNever; + function assertEachNode(nodes, test, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) { + assert( + test === void 0 || every(nodes, test), + message || "Unexpected node.", + () => `Node array did not pass test '${getFunctionName(test)}'.`, + stackCrawlMark || assertEachNode + ); + } + } + Debug2.assertEachNode = assertEachNode; + function assertNode(node, test, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertNode")) { + assert( + node !== void 0 && (test === void 0 || test(node)), + message || "Unexpected node.", + () => `Node ${formatSyntaxKind(node == null ? void 0 : node.kind)} did not pass test '${getFunctionName(test)}'.`, + stackCrawlMark || assertNode + ); + } + } + Debug2.assertNode = assertNode; + function assertNotNode(node, test, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) { + assert( + node === void 0 || test === void 0 || !test(node), + message || "Unexpected node.", + () => `Node ${formatSyntaxKind(node.kind)} should not have passed test '${getFunctionName(test)}'.`, + stackCrawlMark || assertNotNode + ); + } + } + Debug2.assertNotNode = assertNotNode; + function assertOptionalNode(node, test, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) { + assert( + test === void 0 || node === void 0 || test(node), + message || "Unexpected node.", + () => `Node ${formatSyntaxKind(node == null ? void 0 : node.kind)} did not pass test '${getFunctionName(test)}'.`, + stackCrawlMark || assertOptionalNode + ); + } + } + Debug2.assertOptionalNode = assertOptionalNode; + function assertOptionalToken(node, kind, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) { + assert( + kind === void 0 || node === void 0 || node.kind === kind, + message || "Unexpected node.", + () => `Node ${formatSyntaxKind(node == null ? void 0 : node.kind)} was not a '${formatSyntaxKind(kind)}' token.`, + stackCrawlMark || assertOptionalToken + ); + } + } + Debug2.assertOptionalToken = assertOptionalToken; + function assertMissingNode(node, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) { + assert( + node === void 0, + message || "Unexpected node.", + () => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`, + stackCrawlMark || assertMissingNode + ); + } + } + Debug2.assertMissingNode = assertMissingNode; + function type(_value) { + } + Debug2.type = type; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } else if (hasProperty(func, "name")) { + return func.name; + } else { + const text = Function.prototype.toString.call(func); + const match = /^function\s+([\w$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug2.getFunctionName = getFunctionName; + function formatSymbol(symbol) { + return `{ name: ${unescapeLeadingUnderscores(symbol.escapedName)}; flags: ${formatSymbolFlags(symbol.flags)}; declarations: ${map(symbol.declarations, (node) => formatSyntaxKind(node.kind))} }`; + } + Debug2.formatSymbol = formatSymbol; + function formatEnum(value = 0, enumObject, isFlags) { + const members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + const result = []; + let remainingFlags = value; + for (const [enumValue, enumName] of members) { + if (enumValue > value) { + break; + } + if (enumValue !== 0 && enumValue & value) { + result.push(enumName); + remainingFlags &= ~enumValue; + } + } + if (remainingFlags === 0) { + return result.join("|"); + } + } else { + for (const [enumValue, enumName] of members) { + if (enumValue === value) { + return enumName; + } + } + } + return value.toString(); + } + Debug2.formatEnum = formatEnum; + const enumMemberCache = /* @__PURE__ */ new Map(); + function getEnumMembers(enumObject) { + const existing = enumMemberCache.get(enumObject); + if (existing) { + return existing; + } + const result = []; + for (const name in enumObject) { + const value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + const sorted = toSorted(result, (x, y) => compareValues(x[0], y[0])); + enumMemberCache.set(enumObject, sorted); + return sorted; + } + function formatSyntaxKind(kind) { + return formatEnum( + kind, + SyntaxKind, + /*isFlags*/ + false + ); + } + Debug2.formatSyntaxKind = formatSyntaxKind; + function formatSnippetKind(kind) { + return formatEnum( + kind, + SnippetKind, + /*isFlags*/ + false + ); + } + Debug2.formatSnippetKind = formatSnippetKind; + function formatScriptKind(kind) { + return formatEnum( + kind, + ScriptKind, + /*isFlags*/ + false + ); + } + Debug2.formatScriptKind = formatScriptKind; + function formatNodeFlags(flags) { + return formatEnum( + flags, + NodeFlags, + /*isFlags*/ + true + ); + } + Debug2.formatNodeFlags = formatNodeFlags; + function formatNodeCheckFlags(flags) { + return formatEnum( + flags, + NodeCheckFlags, + /*isFlags*/ + true + ); + } + Debug2.formatNodeCheckFlags = formatNodeCheckFlags; + function formatModifierFlags(flags) { + return formatEnum( + flags, + ModifierFlags, + /*isFlags*/ + true + ); + } + Debug2.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum( + flags, + TransformFlags, + /*isFlags*/ + true + ); + } + Debug2.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum( + flags, + EmitFlags, + /*isFlags*/ + true + ); + } + Debug2.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum( + flags, + SymbolFlags, + /*isFlags*/ + true + ); + } + Debug2.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum( + flags, + TypeFlags, + /*isFlags*/ + true + ); + } + Debug2.formatTypeFlags = formatTypeFlags; + function formatSignatureFlags(flags) { + return formatEnum( + flags, + SignatureFlags, + /*isFlags*/ + true + ); + } + Debug2.formatSignatureFlags = formatSignatureFlags; + function formatObjectFlags(flags) { + return formatEnum( + flags, + ObjectFlags, + /*isFlags*/ + true + ); + } + Debug2.formatObjectFlags = formatObjectFlags; + function formatFlowFlags(flags) { + return formatEnum( + flags, + FlowFlags, + /*isFlags*/ + true + ); + } + Debug2.formatFlowFlags = formatFlowFlags; + function formatRelationComparisonResult(result) { + return formatEnum( + result, + RelationComparisonResult, + /*isFlags*/ + true + ); + } + Debug2.formatRelationComparisonResult = formatRelationComparisonResult; + function formatCheckMode(mode) { + return formatEnum( + mode, + CheckMode, + /*isFlags*/ + true + ); + } + Debug2.formatCheckMode = formatCheckMode; + function formatSignatureCheckMode(mode) { + return formatEnum( + mode, + SignatureCheckMode, + /*isFlags*/ + true + ); + } + Debug2.formatSignatureCheckMode = formatSignatureCheckMode; + function formatTypeFacts(facts) { + return formatEnum( + facts, + TypeFacts, + /*isFlags*/ + true + ); + } + Debug2.formatTypeFacts = formatTypeFacts; + let isDebugInfoEnabled = false; + let flowNodeProto; + function attachFlowNodeDebugInfoWorker(flowNode) { + if (!("__debugFlowFlags" in flowNode)) { + Object.defineProperties(flowNode, { + // for use with vscode-js-debug's new customDescriptionGenerator in launch.json + __tsDebuggerDisplay: { + value() { + const flowHeader = this.flags & 2 /* Start */ ? "FlowStart" : this.flags & 4 /* BranchLabel */ ? "FlowBranchLabel" : this.flags & 8 /* LoopLabel */ ? "FlowLoopLabel" : this.flags & 16 /* Assignment */ ? "FlowAssignment" : this.flags & 32 /* TrueCondition */ ? "FlowTrueCondition" : this.flags & 64 /* FalseCondition */ ? "FlowFalseCondition" : this.flags & 128 /* SwitchClause */ ? "FlowSwitchClause" : this.flags & 256 /* ArrayMutation */ ? "FlowArrayMutation" : this.flags & 512 /* Call */ ? "FlowCall" : this.flags & 1024 /* ReduceLabel */ ? "FlowReduceLabel" : this.flags & 1 /* Unreachable */ ? "FlowUnreachable" : "UnknownFlow"; + const remainingFlags = this.flags & ~(2048 /* Referenced */ - 1); + return `${flowHeader}${remainingFlags ? ` (${formatFlowFlags(remainingFlags)})` : ""}`; + } + }, + __debugFlowFlags: { + get() { + return formatEnum( + this.flags, + FlowFlags, + /*isFlags*/ + true + ); + } + }, + __debugToString: { + value() { + return formatControlFlowGraph(this); + } + } + }); + } + } + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (typeof Object.setPrototypeOf === "function") { + if (!flowNodeProto) { + flowNodeProto = Object.create(Object.prototype); + attachFlowNodeDebugInfoWorker(flowNodeProto); + } + Object.setPrototypeOf(flowNode, flowNodeProto); + } else { + attachFlowNodeDebugInfoWorker(flowNode); + } + } + return flowNode; + } + Debug2.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; + let nodeArrayProto; + function attachNodeArrayDebugInfoWorker(array) { + if (!("__tsDebuggerDisplay" in array)) { + Object.defineProperties(array, { + __tsDebuggerDisplay: { + value(defaultValue) { + defaultValue = String(defaultValue).replace(/(?:,[\s\w]+:[^,]+)+\]$/, "]"); + return `NodeArray ${defaultValue}`; + } + } + }); + } + } + function attachNodeArrayDebugInfo(array) { + if (isDebugInfoEnabled) { + if (typeof Object.setPrototypeOf === "function") { + if (!nodeArrayProto) { + nodeArrayProto = Object.create(Array.prototype); + attachNodeArrayDebugInfoWorker(nodeArrayProto); + } + Object.setPrototypeOf(array, nodeArrayProto); + } else { + attachNodeArrayDebugInfoWorker(array); + } + } + } + Debug2.attachNodeArrayDebugInfo = attachNodeArrayDebugInfo; + function enableDebugInfo() { + if (isDebugInfoEnabled) return; + const weakTypeTextMap = /* @__PURE__ */ new WeakMap(); + const weakNodeTextMap = /* @__PURE__ */ new WeakMap(); + Object.defineProperties(objectAllocator.getSymbolConstructor().prototype, { + // for use with vscode-js-debug's new customDescriptionGenerator in launch.json + __tsDebuggerDisplay: { + value() { + const symbolHeader = this.flags & 33554432 /* Transient */ ? "TransientSymbol" : "Symbol"; + const remainingSymbolFlags = this.flags & ~33554432 /* Transient */; + return `${symbolHeader} '${symbolName(this)}'${remainingSymbolFlags ? ` (${formatSymbolFlags(remainingSymbolFlags)})` : ""}`; + } + }, + __debugFlags: { + get() { + return formatSymbolFlags(this.flags); + } + } + }); + Object.defineProperties(objectAllocator.getTypeConstructor().prototype, { + // for use with vscode-js-debug's new customDescriptionGenerator in launch.json + __tsDebuggerDisplay: { + value() { + const typeHeader = this.flags & 67359327 /* Intrinsic */ ? `IntrinsicType ${this.intrinsicName}${this.debugIntrinsicName ? ` (${this.debugIntrinsicName})` : ""}` : this.flags & 98304 /* Nullable */ ? "NullableType" : this.flags & 384 /* StringOrNumberLiteral */ ? `LiteralType ${JSON.stringify(this.value)}` : this.flags & 2048 /* BigIntLiteral */ ? `LiteralType ${this.value.negative ? "-" : ""}${this.value.base10Value}n` : this.flags & 8192 /* UniqueESSymbol */ ? "UniqueESSymbolType" : this.flags & 32 /* Enum */ ? "EnumType" : this.flags & 1048576 /* Union */ ? "UnionType" : this.flags & 2097152 /* Intersection */ ? "IntersectionType" : this.flags & 4194304 /* Index */ ? "IndexType" : this.flags & 8388608 /* IndexedAccess */ ? "IndexedAccessType" : this.flags & 16777216 /* Conditional */ ? "ConditionalType" : this.flags & 33554432 /* Substitution */ ? "SubstitutionType" : this.flags & 262144 /* TypeParameter */ ? "TypeParameter" : this.flags & 524288 /* Object */ ? this.objectFlags & 3 /* ClassOrInterface */ ? "InterfaceType" : this.objectFlags & 4 /* Reference */ ? "TypeReference" : this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; + const remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; + return `${typeHeader}${this.symbol ? ` '${symbolName(this.symbol)}'` : ""}${remainingObjectFlags ? ` (${formatObjectFlags(remainingObjectFlags)})` : ""}`; + } + }, + __debugFlags: { + get() { + return formatTypeFlags(this.flags); + } + }, + __debugObjectFlags: { + get() { + return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; + } + }, + __debugTypeToString: { + value() { + let text = weakTypeTextMap.get(this); + if (text === void 0) { + text = this.checker.typeToString(this); + weakTypeTextMap.set(this, text); + } + return text; + } + } + }); + Object.defineProperties(objectAllocator.getSignatureConstructor().prototype, { + __debugFlags: { + get() { + return formatSignatureFlags(this.flags); + } + }, + __debugSignatureToString: { + value() { + var _a; + return (_a = this.checker) == null ? void 0 : _a.signatureToString(this); + } + } + }); + const nodeConstructors = [ + objectAllocator.getNodeConstructor(), + objectAllocator.getIdentifierConstructor(), + objectAllocator.getTokenConstructor(), + objectAllocator.getSourceFileConstructor() + ]; + for (const ctor of nodeConstructors) { + if (!hasProperty(ctor.prototype, "__debugKind")) { + Object.defineProperties(ctor.prototype, { + // for use with vscode-js-debug's new customDescriptionGenerator in launch.json + __tsDebuggerDisplay: { + value() { + const nodeHeader = isGeneratedIdentifier(this) ? "GeneratedIdentifier" : isIdentifier(this) ? `Identifier '${idText(this)}'` : isPrivateIdentifier(this) ? `PrivateIdentifier '${idText(this)}'` : isStringLiteral(this) ? `StringLiteral ${JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...")}` : isNumericLiteral(this) ? `NumericLiteral ${this.text}` : isBigIntLiteral(this) ? `BigIntLiteral ${this.text}n` : isTypeParameterDeclaration(this) ? "TypeParameterDeclaration" : isParameter(this) ? "ParameterDeclaration" : isConstructorDeclaration(this) ? "ConstructorDeclaration" : isGetAccessorDeclaration(this) ? "GetAccessorDeclaration" : isSetAccessorDeclaration(this) ? "SetAccessorDeclaration" : isCallSignatureDeclaration(this) ? "CallSignatureDeclaration" : isConstructSignatureDeclaration(this) ? "ConstructSignatureDeclaration" : isIndexSignatureDeclaration(this) ? "IndexSignatureDeclaration" : isTypePredicateNode(this) ? "TypePredicateNode" : isTypeReferenceNode(this) ? "TypeReferenceNode" : isFunctionTypeNode(this) ? "FunctionTypeNode" : isConstructorTypeNode(this) ? "ConstructorTypeNode" : isTypeQueryNode(this) ? "TypeQueryNode" : isTypeLiteralNode(this) ? "TypeLiteralNode" : isArrayTypeNode(this) ? "ArrayTypeNode" : isTupleTypeNode(this) ? "TupleTypeNode" : isOptionalTypeNode(this) ? "OptionalTypeNode" : isRestTypeNode(this) ? "RestTypeNode" : isUnionTypeNode(this) ? "UnionTypeNode" : isIntersectionTypeNode(this) ? "IntersectionTypeNode" : isConditionalTypeNode(this) ? "ConditionalTypeNode" : isInferTypeNode(this) ? "InferTypeNode" : isParenthesizedTypeNode(this) ? "ParenthesizedTypeNode" : isThisTypeNode(this) ? "ThisTypeNode" : isTypeOperatorNode(this) ? "TypeOperatorNode" : isIndexedAccessTypeNode(this) ? "IndexedAccessTypeNode" : isMappedTypeNode(this) ? "MappedTypeNode" : isLiteralTypeNode(this) ? "LiteralTypeNode" : isNamedTupleMember(this) ? "NamedTupleMember" : isImportTypeNode(this) ? "ImportTypeNode" : formatSyntaxKind(this.kind); + return `${nodeHeader}${this.flags ? ` (${formatNodeFlags(this.flags)})` : ""}`; + } + }, + __debugKind: { + get() { + return formatSyntaxKind(this.kind); + } + }, + __debugNodeFlags: { + get() { + return formatNodeFlags(this.flags); + } + }, + __debugModifierFlags: { + get() { + return formatModifierFlags(getEffectiveModifierFlagsNoCache(this)); + } + }, + __debugTransformFlags: { + get() { + return formatTransformFlags(this.transformFlags); + } + }, + __debugIsParseTreeNode: { + get() { + return isParseTreeNode(this); + } + }, + __debugEmitFlags: { + get() { + return formatEmitFlags(getEmitFlags(this)); + } + }, + __debugGetText: { + value(includeTrivia) { + if (nodeIsSynthesized(this)) return ""; + let text = weakNodeTextMap.get(this); + if (text === void 0) { + const parseNode = getParseTreeNode(this); + const sourceFile = parseNode && getSourceFileOfNode(parseNode); + text = sourceFile ? getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + weakNodeTextMap.set(this, text); + } + return text; + } + } + }); + } + } + isDebugInfoEnabled = true; + } + Debug2.enableDebugInfo = enableDebugInfo; + function formatVariance(varianceFlags) { + const variance = varianceFlags & 7 /* VarianceMask */; + let result = variance === 0 /* Invariant */ ? "in out" : variance === 3 /* Bivariant */ ? "[bivariant]" : variance === 2 /* Contravariant */ ? "in" : variance === 1 /* Covariant */ ? "out" : variance === 4 /* Independent */ ? "[independent]" : ""; + if (varianceFlags & 8 /* Unmeasurable */) { + result += " (unmeasurable)"; + } else if (varianceFlags & 16 /* Unreliable */) { + result += " (unreliable)"; + } + return result; + } + Debug2.formatVariance = formatVariance; + class DebugTypeMapper { + __debugToString() { + var _a; + type(this); + switch (this.kind) { + case 3 /* Function */: + return ((_a = this.debugInfo) == null ? void 0 : _a.call(this)) || "(function mapper)"; + case 0 /* Simple */: + return `${this.source.__debugTypeToString()} -> ${this.target.__debugTypeToString()}`; + case 1 /* Array */: + return zipWith( + this.sources, + this.targets || map(this.sources, () => "any"), + (s, t) => `${s.__debugTypeToString()} -> ${typeof t === "string" ? t : t.__debugTypeToString()}` + ).join(", "); + case 2 /* Deferred */: + return zipWith( + this.sources, + this.targets, + (s, t) => `${s.__debugTypeToString()} -> ${t().__debugTypeToString()}` + ).join(", "); + case 5 /* Merged */: + case 4 /* Composite */: + return `m1: ${this.mapper1.__debugToString().split("\n").join("\n ")} +m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; + default: + return assertNever(this); + } + } + } + Debug2.DebugTypeMapper = DebugTypeMapper; + function attachDebugPrototypeIfDebug(mapper) { + if (Debug2.isDebugging) { + return Object.setPrototypeOf(mapper, DebugTypeMapper.prototype); + } + return mapper; + } + Debug2.attachDebugPrototypeIfDebug = attachDebugPrototypeIfDebug; + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug2.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + let nextDebugFlowId = -1; + function getDebugFlowNodeId(f) { + if (!f.id) { + f.id = nextDebugFlowId; + nextDebugFlowId--; + } + return f.id; + } + let BoxCharacter; + ((BoxCharacter2) => { + BoxCharacter2["lr"] = "\u2500"; + BoxCharacter2["ud"] = "\u2502"; + BoxCharacter2["dr"] = "\u256D"; + BoxCharacter2["dl"] = "\u256E"; + BoxCharacter2["ul"] = "\u256F"; + BoxCharacter2["ur"] = "\u2570"; + BoxCharacter2["udr"] = "\u251C"; + BoxCharacter2["udl"] = "\u2524"; + BoxCharacter2["dlr"] = "\u252C"; + BoxCharacter2["ulr"] = "\u2534"; + BoxCharacter2["udlr"] = "\u256B"; + })(BoxCharacter || (BoxCharacter = {})); + let Connection; + ((Connection2) => { + Connection2[Connection2["None"] = 0] = "None"; + Connection2[Connection2["Up"] = 1] = "Up"; + Connection2[Connection2["Down"] = 2] = "Down"; + Connection2[Connection2["Left"] = 4] = "Left"; + Connection2[Connection2["Right"] = 8] = "Right"; + Connection2[Connection2["UpDown"] = 3] = "UpDown"; + Connection2[Connection2["LeftRight"] = 12] = "LeftRight"; + Connection2[Connection2["UpLeft"] = 5] = "UpLeft"; + Connection2[Connection2["UpRight"] = 9] = "UpRight"; + Connection2[Connection2["DownLeft"] = 6] = "DownLeft"; + Connection2[Connection2["DownRight"] = 10] = "DownRight"; + Connection2[Connection2["UpDownLeft"] = 7] = "UpDownLeft"; + Connection2[Connection2["UpDownRight"] = 11] = "UpDownRight"; + Connection2[Connection2["UpLeftRight"] = 13] = "UpLeftRight"; + Connection2[Connection2["DownLeftRight"] = 14] = "DownLeftRight"; + Connection2[Connection2["UpDownLeftRight"] = 15] = "UpDownLeftRight"; + Connection2[Connection2["NoChildren"] = 16] = "NoChildren"; + })(Connection || (Connection = {})); + const hasAntecedentFlags = 16 /* Assignment */ | 96 /* Condition */ | 128 /* SwitchClause */ | 256 /* ArrayMutation */ | 512 /* Call */ | 1024 /* ReduceLabel */; + const hasNodeFlags = 2 /* Start */ | 16 /* Assignment */ | 512 /* Call */ | 96 /* Condition */ | 256 /* ArrayMutation */; + const links = /* @__PURE__ */ Object.create( + /*o*/ + null + ); + const nodes = []; + const edges = []; + const root = buildGraphNode(flowNode, /* @__PURE__ */ new Set()); + for (const node of nodes) { + node.text = renderFlowNode(node.flowNode, node.circular); + computeLevel(node); + } + const height = computeHeight(root); + const columnWidths = computeColumnWidths(height); + computeLanes(root, 0); + return renderGraph(); + function isFlowSwitchClause(f) { + return !!(f.flags & 128 /* SwitchClause */); + } + function hasAntecedents(f) { + return !!(f.flags & 12 /* Label */) && !!f.antecedent; + } + function hasAntecedent(f) { + return !!(f.flags & hasAntecedentFlags); + } + function hasNode(f) { + return !!(f.flags & hasNodeFlags); + } + function getChildren(node) { + const children = []; + for (const edge of node.edges) { + if (edge.source === node) { + children.push(edge.target); + } + } + return children; + } + function getParents(node) { + const parents = []; + for (const edge of node.edges) { + if (edge.target === node) { + parents.push(edge.source); + } + } + return parents; + } + function buildGraphNode(flowNode2, seen) { + const id = getDebugFlowNodeId(flowNode2); + let graphNode = links[id]; + if (graphNode && seen.has(flowNode2)) { + graphNode.circular = true; + graphNode = { + id: -1, + flowNode: flowNode2, + edges: [], + text: "", + lane: -1, + endLane: -1, + level: -1, + circular: "circularity" + }; + nodes.push(graphNode); + return graphNode; + } + seen.add(flowNode2); + if (!graphNode) { + links[id] = graphNode = { id, flowNode: flowNode2, edges: [], text: "", lane: -1, endLane: -1, level: -1, circular: false }; + nodes.push(graphNode); + if (hasAntecedents(flowNode2)) { + for (const antecedent of flowNode2.antecedent) { + buildGraphEdge(graphNode, antecedent, seen); + } + } else if (hasAntecedent(flowNode2)) { + buildGraphEdge(graphNode, flowNode2.antecedent, seen); + } + } + seen.delete(flowNode2); + return graphNode; + } + function buildGraphEdge(source, antecedent, seen) { + const target = buildGraphNode(antecedent, seen); + const edge = { source, target }; + edges.push(edge); + source.edges.push(edge); + target.edges.push(edge); + } + function computeLevel(node) { + if (node.level !== -1) { + return node.level; + } + let level = 0; + for (const parent of getParents(node)) { + level = Math.max(level, computeLevel(parent) + 1); + } + return node.level = level; + } + function computeHeight(node) { + let height2 = 0; + for (const child of getChildren(node)) { + height2 = Math.max(height2, computeHeight(child)); + } + return height2 + 1; + } + function computeColumnWidths(height2) { + const columns = fill(Array(height2), 0); + for (const node of nodes) { + columns[node.level] = Math.max(columns[node.level], node.text.length); + } + return columns; + } + function computeLanes(node, lane) { + if (node.lane === -1) { + node.lane = lane; + node.endLane = lane; + const children = getChildren(node); + for (let i = 0; i < children.length; i++) { + if (i > 0) lane++; + const child = children[i]; + computeLanes(child, lane); + if (child.endLane > node.endLane) { + lane = child.endLane; + } + } + node.endLane = lane; + } + } + function getHeader2(flags) { + if (flags & 2 /* Start */) return "Start"; + if (flags & 4 /* BranchLabel */) return "Branch"; + if (flags & 8 /* LoopLabel */) return "Loop"; + if (flags & 16 /* Assignment */) return "Assignment"; + if (flags & 32 /* TrueCondition */) return "True"; + if (flags & 64 /* FalseCondition */) return "False"; + if (flags & 128 /* SwitchClause */) return "SwitchClause"; + if (flags & 256 /* ArrayMutation */) return "ArrayMutation"; + if (flags & 512 /* Call */) return "Call"; + if (flags & 1024 /* ReduceLabel */) return "ReduceLabel"; + if (flags & 1 /* Unreachable */) return "Unreachable"; + throw new Error(); + } + function getNodeText(node) { + const sourceFile = getSourceFileOfNode(node); + return getSourceTextOfNodeFromSourceFile( + sourceFile, + node, + /*includeTrivia*/ + false + ); + } + function renderFlowNode(flowNode2, circular) { + let text = getHeader2(flowNode2.flags); + if (circular) { + text = `${text}#${getDebugFlowNodeId(flowNode2)}`; + } + if (isFlowSwitchClause(flowNode2)) { + const clauses = []; + const { switchStatement, clauseStart, clauseEnd } = flowNode2.node; + for (let i = clauseStart; i < clauseEnd; i++) { + const clause = switchStatement.caseBlock.clauses[i]; + if (isDefaultClause(clause)) { + clauses.push("default"); + } else { + clauses.push(getNodeText(clause.expression)); + } + } + text += ` (${clauses.join(", ")})`; + } else if (hasNode(flowNode2)) { + if (flowNode2.node) { + text += ` (${getNodeText(flowNode2.node)})`; + } + } + return circular === "circularity" ? `Circular(${text})` : text; + } + function renderGraph() { + const columnCount = columnWidths.length; + const laneCount = maxBy(nodes, 0, (n) => n.lane) + 1; + const lanes = fill(Array(laneCount), ""); + const grid = columnWidths.map(() => Array(laneCount)); + const connectors = columnWidths.map(() => fill(Array(laneCount), 0)); + for (const node of nodes) { + grid[node.level][node.lane] = node; + const children = getChildren(node); + for (let i = 0; i < children.length; i++) { + const child = children[i]; + let connector = 8 /* Right */; + if (child.lane === node.lane) connector |= 4 /* Left */; + if (i > 0) connector |= 1 /* Up */; + if (i < children.length - 1) connector |= 2 /* Down */; + connectors[node.level][child.lane] |= connector; + } + if (children.length === 0) { + connectors[node.level][node.lane] |= 16 /* NoChildren */; + } + const parents = getParents(node); + for (let i = 0; i < parents.length; i++) { + const parent = parents[i]; + let connector = 4 /* Left */; + if (i > 0) connector |= 1 /* Up */; + if (i < parents.length - 1) connector |= 2 /* Down */; + connectors[node.level - 1][parent.lane] |= connector; + } + } + for (let column = 0; column < columnCount; column++) { + for (let lane = 0; lane < laneCount; lane++) { + const left = column > 0 ? connectors[column - 1][lane] : 0; + const above = lane > 0 ? connectors[column][lane - 1] : 0; + let connector = connectors[column][lane]; + if (!connector) { + if (left & 8 /* Right */) connector |= 12 /* LeftRight */; + if (above & 2 /* Down */) connector |= 3 /* UpDown */; + connectors[column][lane] = connector; + } + } + } + for (let column = 0; column < columnCount; column++) { + for (let lane = 0; lane < lanes.length; lane++) { + const connector = connectors[column][lane]; + const fill2 = connector & 4 /* Left */ ? "\u2500" /* lr */ : " "; + const node = grid[column][lane]; + if (!node) { + if (column < columnCount - 1) { + writeLane(lane, repeat(fill2, columnWidths[column] + 1)); + } + } else { + writeLane(lane, node.text); + if (column < columnCount - 1) { + writeLane(lane, " "); + writeLane(lane, repeat(fill2, columnWidths[column] - node.text.length)); + } + } + writeLane(lane, getBoxCharacter(connector)); + writeLane(lane, connector & 8 /* Right */ && column < columnCount - 1 && !grid[column + 1][lane] ? "\u2500" /* lr */ : " "); + } + } + return ` +${lanes.join("\n")} +`; + function writeLane(lane, text) { + lanes[lane] += text; + } + } + function getBoxCharacter(connector) { + switch (connector) { + case 3 /* UpDown */: + return "\u2502" /* ud */; + case 12 /* LeftRight */: + return "\u2500" /* lr */; + case 5 /* UpLeft */: + return "\u256F" /* ul */; + case 9 /* UpRight */: + return "\u2570" /* ur */; + case 6 /* DownLeft */: + return "\u256E" /* dl */; + case 10 /* DownRight */: + return "\u256D" /* dr */; + case 7 /* UpDownLeft */: + return "\u2524" /* udl */; + case 11 /* UpDownRight */: + return "\u251C" /* udr */; + case 13 /* UpLeftRight */: + return "\u2534" /* ulr */; + case 14 /* DownLeftRight */: + return "\u252C" /* dlr */; + case 15 /* UpDownLeftRight */: + return "\u256B" /* udlr */; + } + return " "; + } + function fill(array, value) { + if (array.fill) { + array.fill(value); + } else { + for (let i = 0; i < array.length; i++) { + array[i] = value; + } + } + return array; + } + function repeat(ch, length2) { + if (ch.repeat) { + return length2 > 0 ? ch.repeat(length2) : ""; + } + let s = ""; + while (s.length < length2) { + s += ch; + } + return s; + } + } + Debug2.formatControlFlowGraph = formatControlFlowGraph; +})(Debug || (Debug = {})); + +// src/compiler/semver.ts +var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; +var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; +var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; +var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; +var buildPartRegExp = /^[a-z0-9-]+$/i; +var numericIdentifierRegExp = /^(?:0|[1-9]\d*)$/; +var _Version = class _Version { + constructor(major, minor = 0, patch = 0, prerelease = "", build2 = "") { + if (typeof major === "string") { + const result = Debug.checkDefined(tryParseComponents(major), "Invalid version"); + ({ major, minor, patch, prerelease, build: build2 } = result); + } + Debug.assert(major >= 0, "Invalid argument: major"); + Debug.assert(minor >= 0, "Invalid argument: minor"); + Debug.assert(patch >= 0, "Invalid argument: patch"); + const prereleaseArray = prerelease ? isArray(prerelease) ? prerelease : prerelease.split(".") : emptyArray; + const buildArray = build2 ? isArray(build2) ? build2 : build2.split(".") : emptyArray; + Debug.assert(every(prereleaseArray, (s) => prereleasePartRegExp.test(s)), "Invalid argument: prerelease"); + Debug.assert(every(buildArray, (s) => buildPartRegExp.test(s)), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prereleaseArray; + this.build = buildArray; + } + static tryParse(text) { + const result = tryParseComponents(text); + if (!result) return void 0; + const { major, minor, patch, prerelease, build: build2 } = result; + return new _Version(major, minor, patch, prerelease, build2); + } + compareTo(other) { + if (this === other) return 0 /* EqualTo */; + if (other === void 0) return 1 /* GreaterThan */; + return compareValues(this.major, other.major) || compareValues(this.minor, other.minor) || compareValues(this.patch, other.patch) || comparePrereleaseIdentifiers(this.prerelease, other.prerelease); + } + increment(field) { + switch (field) { + case "major": + return new _Version(this.major + 1, 0, 0); + case "minor": + return new _Version(this.major, this.minor + 1, 0); + case "patch": + return new _Version(this.major, this.minor, this.patch + 1); + default: + return Debug.assertNever(field); + } + } + with(fields) { + const { + major = this.major, + minor = this.minor, + patch = this.patch, + prerelease = this.prerelease, + build: build2 = this.build + } = fields; + return new _Version(major, minor, patch, prerelease, build2); + } + toString() { + let result = `${this.major}.${this.minor}.${this.patch}`; + if (some(this.prerelease)) result += `-${this.prerelease.join(".")}`; + if (some(this.build)) result += `+${this.build.join(".")}`; + return result; + } +}; +_Version.zero = new _Version(0, 0, 0, ["0"]); +var Version = _Version; +function tryParseComponents(text) { + const match = versionRegExp.exec(text); + if (!match) return void 0; + const [, major, minor = "0", patch = "0", prerelease = "", build2 = ""] = match; + if (prerelease && !prereleaseRegExp.test(prerelease)) return void 0; + if (build2 && !buildRegExp.test(build2)) return void 0; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease, + build: build2 + }; +} +function comparePrereleaseIdentifiers(left, right) { + if (left === right) return 0 /* EqualTo */; + if (left.length === 0) return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) return -1 /* LessThan */; + const length2 = Math.min(left.length, right.length); + for (let i = 0; i < length2; i++) { + const leftIdentifier = left[i]; + const rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) continue; + const leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + const rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + if (leftIsNumeric !== rightIsNumeric) return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + const result = compareValues(+leftIdentifier, +rightIdentifier); + if (result) return result; + } else { + const result = compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) return result; + } + } + return compareValues(left.length, right.length); +} +var VersionRange = class _VersionRange { + constructor(spec) { + this._alternatives = spec ? Debug.checkDefined(parseRange(spec), "Invalid range spec.") : emptyArray; + } + static tryParse(text) { + const sets = parseRange(text); + if (sets) { + const range = new _VersionRange(""); + range._alternatives = sets; + return range; + } + return void 0; + } + /** + * Tests whether a version matches the range. This is equivalent to `satisfies(version, range, { includePrerelease: true })`. + * in `node-semver`. + */ + test(version2) { + if (typeof version2 === "string") version2 = new Version(version2); + return testDisjunction(version2, this._alternatives); + } + toString() { + return formatDisjunction(this._alternatives); + } +}; +var logicalOrRegExp = /\|\|/; +var whitespaceRegExp = /\s+/; +var partialRegExp = /^([x*0]|[1-9]\d*)(?:\.([x*0]|[1-9]\d*)(?:\.([x*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; +var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; +var rangeRegExp = /^([~^<>=]|<=|>=)?\s*([a-z0-9-+.*]+)$/i; +function parseRange(text) { + const alternatives = []; + for (let range of text.trim().split(logicalOrRegExp)) { + if (!range) continue; + const comparators = []; + range = range.trim(); + const match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) return void 0; + } else { + for (const simple of range.split(whitespaceRegExp)) { + const match2 = rangeRegExp.exec(simple.trim()); + if (!match2 || !parseComparator(match2[1], match2[2], comparators)) return void 0; + } + } + alternatives.push(comparators); + } + return alternatives; +} +function parsePartial(text) { + const match = partialRegExp.exec(text); + if (!match) return void 0; + const [, major, minor = "*", patch = "*", prerelease, build2] = match; + const version2 = new Version( + isWildcard(major) ? 0 : parseInt(major, 10), + isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), + isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), + prerelease, + build2 + ); + return { version: version2, major, minor, patch }; +} +function parseHyphen(left, right, comparators) { + const leftResult = parsePartial(left); + if (!leftResult) return false; + const rightResult = parsePartial(right); + if (!rightResult) return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push( + isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : createComparator("<=", rightResult.version) + ); + } + return true; +} +function parseComparator(operator, text, comparators) { + const result = parsePartial(text); + if (!result) return false; + const { version: version2, major, minor, patch } = result; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version2)); + comparators.push(createComparator( + "<", + version2.increment( + isWildcard(minor) ? "major" : "minor" + ) + )); + break; + case "^": + comparators.push(createComparator(">=", version2)); + comparators.push(createComparator( + "<", + version2.increment( + version2.major > 0 || isWildcard(minor) ? "major" : version2.minor > 0 || isWildcard(patch) ? "minor" : "patch" + ) + )); + break; + case "<": + case ">=": + comparators.push( + isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version2.with({ prerelease: "0" })) : createComparator(operator, version2) + ); + break; + case "<=": + case ">": + comparators.push( + isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version2.increment("major").with({ prerelease: "0" })) : isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version2.increment("minor").with({ prerelease: "0" })) : createComparator(operator, version2) + ); + break; + case "=": + case void 0: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version2.with({ prerelease: "0" }))); + comparators.push(createComparator("<", version2.increment(isWildcard(minor) ? "major" : "minor").with({ prerelease: "0" }))); + } else { + comparators.push(createComparator("=", version2)); + } + break; + default: + return false; + } + } else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; +} +function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; +} +function createComparator(operator, operand) { + return { operator, operand }; +} +function testDisjunction(version2, alternatives) { + if (alternatives.length === 0) return true; + for (const alternative of alternatives) { + if (testAlternative(version2, alternative)) return true; + } + return false; +} +function testAlternative(version2, comparators) { + for (const comparator of comparators) { + if (!testComparator(version2, comparator.operator, comparator.operand)) return false; + } + return true; +} +function testComparator(version2, operator, operand) { + const cmp = version2.compareTo(operand); + switch (operator) { + case "<": + return cmp < 0; + case "<=": + return cmp <= 0; + case ">": + return cmp > 0; + case ">=": + return cmp >= 0; + case "=": + return cmp === 0; + default: + return Debug.assertNever(operator); + } +} +function formatDisjunction(alternatives) { + return map(alternatives, formatAlternative).join(" || ") || "*"; +} +function formatAlternative(comparators) { + return map(comparators, formatComparator).join(" "); +} +function formatComparator(comparator) { + return `${comparator.operator}${comparator.operand}`; +} + +// src/compiler/performanceCore.ts +function tryGetPerformance() { + if (isNodeLikeSystem()) { + try { + const { performance: performance2 } = require("perf_hooks"); + if (performance2) { + return { + shouldWriteNativeEvents: false, + performance: performance2 + }; + } + } catch { + } + } + if (typeof performance === "object") { + return { + shouldWriteNativeEvents: true, + performance + }; + } + return void 0; +} +function tryGetPerformanceHooks() { + const p = tryGetPerformance(); + if (!p) return void 0; + const { shouldWriteNativeEvents, performance: performance2 } = p; + const hooks = { + shouldWriteNativeEvents, + performance: void 0, + performanceTime: void 0 + }; + if (typeof performance2.timeOrigin === "number" && typeof performance2.now === "function") { + hooks.performanceTime = performance2; + } + if (hooks.performanceTime && typeof performance2.mark === "function" && typeof performance2.measure === "function" && typeof performance2.clearMarks === "function" && typeof performance2.clearMeasures === "function") { + hooks.performance = performance2; + } + return hooks; +} +var nativePerformanceHooks = tryGetPerformanceHooks(); +var nativePerformanceTime = nativePerformanceHooks == null ? void 0 : nativePerformanceHooks.performanceTime; +function tryGetNativePerformanceHooks() { + return nativePerformanceHooks; +} +var timestamp = nativePerformanceTime ? () => nativePerformanceTime.now() : Date.now; + +// src/compiler/performance.ts +var perfHooks; +var performanceImpl; +function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : nullTimer; +} +function createTimer(measureName, startMarkName, endMarkName) { + let enterCount = 0; + return { + enter, + exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } else if (enterCount < 0) { + Debug.fail("enter/exit count does not match."); + } + } +} +var nullTimer = { enter: noop, exit: noop }; +var enabled = false; +var timeorigin = timestamp(); +var marks = /* @__PURE__ */ new Map(); +var counts = /* @__PURE__ */ new Map(); +var durations = /* @__PURE__ */ new Map(); +function mark(markName) { + if (enabled) { + const count = counts.get(markName) ?? 0; + counts.set(markName, count + 1); + marks.set(markName, timestamp()); + performanceImpl == null ? void 0 : performanceImpl.mark(markName); + if (typeof onProfilerEvent === "function") { + onProfilerEvent(markName); + } + } +} +function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + const end = (endMarkName !== void 0 ? marks.get(endMarkName) : void 0) ?? timestamp(); + const start = (startMarkName !== void 0 ? marks.get(startMarkName) : void 0) ?? timeorigin; + const previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl == null ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } +} +function getCount(markName) { + return counts.get(markName) || 0; +} +function getDuration(measureName) { + return durations.get(measureName) || 0; +} +function forEachMeasure(cb) { + durations.forEach((duration, measureName) => cb(measureName, duration)); +} +function forEachMark(cb) { + marks.forEach((_time, markName) => cb(markName)); +} +function clearMeasures(name) { + if (name !== void 0) durations.delete(name); + else durations.clear(); + performanceImpl == null ? void 0 : performanceImpl.clearMeasures(name); +} +function clearMarks(name) { + if (name !== void 0) { + counts.delete(name); + marks.delete(name); + } else { + counts.clear(); + marks.clear(); + } + performanceImpl == null ? void 0 : performanceImpl.clearMarks(name); +} +function isEnabled() { + return enabled; +} +function enable(system = sys) { + var _a; + if (!enabled) { + enabled = true; + perfHooks || (perfHooks = tryGetNativePerformanceHooks()); + if (perfHooks == null ? void 0 : perfHooks.performance) { + timeorigin = perfHooks.performance.timeOrigin; + if (perfHooks.shouldWriteNativeEvents || ((_a = system == null ? void 0 : system.cpuProfilingEnabled) == null ? void 0 : _a.call(system)) || (system == null ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } + } + return true; +} +function disable() { + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = void 0; + enabled = false; + } +} + +// src/compiler/tracing.ts +var tracing; +var tracingEnabled; +((tracingEnabled2) => { + let fs; + let traceCount = 0; + let traceFd = 0; + let mode; + const typeCatalog = []; + let legendPath; + const legend = []; + function startTracing2(tracingMode, traceDir, configFilePath) { + Debug.assert(!tracing, "Tracing already started"); + if (fs === void 0) { + try { + fs = require("fs"); + } catch (e) { + throw new Error(`tracing requires having fs +(original error: ${e.message || e})`); + } + } + mode = tracingMode; + typeCatalog.length = 0; + if (legendPath === void 0) { + legendPath = combinePaths(traceDir, "legend.json"); + } + if (!fs.existsSync(traceDir)) { + fs.mkdirSync(traceDir, { recursive: true }); + } + const countPart = mode === "build" ? `.${process.pid}-${++traceCount}` : mode === "server" ? `.${process.pid}` : ``; + const tracePath = combinePaths(traceDir, `trace${countPart}.json`); + const typesPath = combinePaths(traceDir, `types${countPart}.json`); + legend.push({ + configFilePath, + tracePath, + typesPath + }); + traceFd = fs.openSync(tracePath, "w"); + tracing = tracingEnabled2; + const meta = { cat: "__metadata", ph: "M", ts: 1e3 * timestamp(), pid: 1, tid: 1 }; + fs.writeSync( + traceFd, + "[\n" + [{ name: "process_name", args: { name: "tsc" }, ...meta }, { name: "thread_name", args: { name: "Main" }, ...meta }, { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" }].map((v) => JSON.stringify(v)).join(",\n") + ); + } + tracingEnabled2.startTracing = startTracing2; + function stopTracing() { + Debug.assert(tracing, "Tracing is not in progress"); + Debug.assert(!!typeCatalog.length === (mode !== "server")); + fs.writeSync(traceFd, ` +] +`); + fs.closeSync(traceFd); + tracing = void 0; + if (typeCatalog.length) { + dumpTypes(typeCatalog); + } else { + legend[legend.length - 1].typesPath = void 0; + } + } + tracingEnabled2.stopTracing = stopTracing; + function recordType(type) { + if (mode !== "server") { + typeCatalog.push(type); + } + } + tracingEnabled2.recordType = recordType; + let Phase; + ((Phase2) => { + Phase2["Parse"] = "parse"; + Phase2["Program"] = "program"; + Phase2["Bind"] = "bind"; + Phase2["Check"] = "check"; + Phase2["CheckTypes"] = "checkTypes"; + Phase2["Emit"] = "emit"; + Phase2["Session"] = "session"; + })(Phase = tracingEnabled2.Phase || (tracingEnabled2.Phase = {})); + function instant(phase, name, args) { + writeEvent("I", phase, name, args, `"s":"g"`); + } + tracingEnabled2.instant = instant; + const eventStack = []; + function push(phase, name, args, separateBeginAndEnd = false) { + if (separateBeginAndEnd) { + writeEvent("B", phase, name, args); + } + eventStack.push({ phase, name, args, time: 1e3 * timestamp(), separateBeginAndEnd }); + } + tracingEnabled2.push = push; + function pop(results) { + Debug.assert(eventStack.length > 0); + writeStackEvent(eventStack.length - 1, 1e3 * timestamp(), results); + eventStack.length--; + } + tracingEnabled2.pop = pop; + function popAll() { + const endTime = 1e3 * timestamp(); + for (let i = eventStack.length - 1; i >= 0; i--) { + writeStackEvent(i, endTime); + } + eventStack.length = 0; + } + tracingEnabled2.popAll = popAll; + const sampleInterval = 1e3 * 10; + function writeStackEvent(index, endTime, results) { + const { phase, name, args, time, separateBeginAndEnd } = eventStack[index]; + if (separateBeginAndEnd) { + Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); + writeEvent( + "E", + phase, + name, + args, + /*extras*/ + void 0, + endTime + ); + } else if (sampleInterval - time % sampleInterval <= endTime - time) { + writeEvent("X", phase, name, { ...args, results }, `"dur":${endTime - time}`, time); + } + } + function writeEvent(eventType, phase, name, args, extras, time = 1e3 * timestamp()) { + if (mode === "server" && phase === "checkTypes" /* CheckTypes */) return; + mark("beginTracing"); + fs.writeSync(traceFd, `, +{"pid":1,"tid":1,"ph":"${eventType}","cat":"${phase}","ts":${time},"name":"${name}"`); + if (extras) fs.writeSync(traceFd, `,${extras}`); + if (args) fs.writeSync(traceFd, `,"args":${JSON.stringify(args)}`); + fs.writeSync(traceFd, `}`); + mark("endTracing"); + measure("Tracing", "beginTracing", "endTracing"); + } + function getLocation(node) { + const file = getSourceFileOfNode(node); + return !file ? void 0 : { + path: file.path, + start: indexFromOne(getLineAndCharacterOfPosition(file, node.pos)), + end: indexFromOne(getLineAndCharacterOfPosition(file, node.end)) + }; + function indexFromOne(lc) { + return { + line: lc.line + 1, + character: lc.character + 1 + }; + } + } + function dumpTypes(types) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s; + mark("beginDumpTypes"); + const typesPath = legend[legend.length - 1].typesPath; + const typesFd = fs.openSync(typesPath, "w"); + const recursionIdentityMap = /* @__PURE__ */ new Map(); + fs.writeSync(typesFd, "["); + const numTypes = types.length; + for (let i = 0; i < numTypes; i++) { + const type = types[i]; + const objectFlags = type.objectFlags; + const symbol = type.aliasSymbol ?? type.symbol; + let display; + if (objectFlags & 16 /* Anonymous */ | type.flags & 2944 /* Literal */) { + try { + display = (_a = type.checker) == null ? void 0 : _a.typeToString(type); + } catch { + display = void 0; + } + } + let indexedAccessProperties = {}; + if (type.flags & 8388608 /* IndexedAccess */) { + const indexedAccessType = type; + indexedAccessProperties = { + indexedAccessObjectType: (_b = indexedAccessType.objectType) == null ? void 0 : _b.id, + indexedAccessIndexType: (_c = indexedAccessType.indexType) == null ? void 0 : _c.id + }; + } + let referenceProperties = {}; + if (objectFlags & 4 /* Reference */) { + const referenceType = type; + referenceProperties = { + instantiatedType: (_d = referenceType.target) == null ? void 0 : _d.id, + typeArguments: (_e = referenceType.resolvedTypeArguments) == null ? void 0 : _e.map((t) => t.id), + referenceLocation: getLocation(referenceType.node) + }; + } + let conditionalProperties = {}; + if (type.flags & 16777216 /* Conditional */) { + const conditionalType = type; + conditionalProperties = { + conditionalCheckType: (_f = conditionalType.checkType) == null ? void 0 : _f.id, + conditionalExtendsType: (_g = conditionalType.extendsType) == null ? void 0 : _g.id, + conditionalTrueType: ((_h = conditionalType.resolvedTrueType) == null ? void 0 : _h.id) ?? -1, + conditionalFalseType: ((_i = conditionalType.resolvedFalseType) == null ? void 0 : _i.id) ?? -1 + }; + } + let substitutionProperties = {}; + if (type.flags & 33554432 /* Substitution */) { + const substitutionType = type; + substitutionProperties = { + substitutionBaseType: (_j = substitutionType.baseType) == null ? void 0 : _j.id, + constraintType: (_k = substitutionType.constraint) == null ? void 0 : _k.id + }; + } + let reverseMappedProperties = {}; + if (objectFlags & 1024 /* ReverseMapped */) { + const reverseMappedType = type; + reverseMappedProperties = { + reverseMappedSourceType: (_l = reverseMappedType.source) == null ? void 0 : _l.id, + reverseMappedMappedType: (_m = reverseMappedType.mappedType) == null ? void 0 : _m.id, + reverseMappedConstraintType: (_n = reverseMappedType.constraintType) == null ? void 0 : _n.id + }; + } + let evolvingArrayProperties = {}; + if (objectFlags & 256 /* EvolvingArray */) { + const evolvingArrayType = type; + evolvingArrayProperties = { + evolvingArrayElementType: evolvingArrayType.elementType.id, + evolvingArrayFinalType: (_o = evolvingArrayType.finalArrayType) == null ? void 0 : _o.id + }; + } + let recursionToken; + const recursionIdentity = type.checker.getRecursionIdentity(type); + if (recursionIdentity) { + recursionToken = recursionIdentityMap.get(recursionIdentity); + if (!recursionToken) { + recursionToken = recursionIdentityMap.size; + recursionIdentityMap.set(recursionIdentity, recursionToken); + } + } + const descriptor = { + id: type.id, + intrinsicName: type.intrinsicName, + symbolName: (symbol == null ? void 0 : symbol.escapedName) && unescapeLeadingUnderscores(symbol.escapedName), + recursionId: recursionToken, + isTuple: objectFlags & 8 /* Tuple */ ? true : void 0, + unionTypes: type.flags & 1048576 /* Union */ ? (_p = type.types) == null ? void 0 : _p.map((t) => t.id) : void 0, + intersectionTypes: type.flags & 2097152 /* Intersection */ ? type.types.map((t) => t.id) : void 0, + aliasTypeArguments: (_q = type.aliasTypeArguments) == null ? void 0 : _q.map((t) => t.id), + keyofType: type.flags & 4194304 /* Index */ ? (_r = type.type) == null ? void 0 : _r.id : void 0, + ...indexedAccessProperties, + ...referenceProperties, + ...conditionalProperties, + ...substitutionProperties, + ...reverseMappedProperties, + ...evolvingArrayProperties, + destructuringPattern: getLocation(type.pattern), + firstDeclaration: getLocation((_s = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _s[0]), + flags: Debug.formatTypeFlags(type.flags).split("|"), + display + }; + fs.writeSync(typesFd, JSON.stringify(descriptor)); + if (i < numTypes - 1) { + fs.writeSync(typesFd, ",\n"); + } + } + fs.writeSync(typesFd, "]\n"); + fs.closeSync(typesFd); + mark("endDumpTypes"); + measure("Dump types", "beginDumpTypes", "endDumpTypes"); + } + function dumpLegend() { + if (!legendPath) { + return; + } + fs.writeFileSync(legendPath, JSON.stringify(legend)); + } + tracingEnabled2.dumpLegend = dumpLegend; +})(tracingEnabled || (tracingEnabled = {})); +var startTracing = tracingEnabled.startTracing; +var dumpTracingLegend = tracingEnabled.dumpLegend; + +// src/compiler/types.ts +var SyntaxKind = /* @__PURE__ */ ((SyntaxKind4) => { + SyntaxKind4[SyntaxKind4["Unknown"] = 0] = "Unknown"; + SyntaxKind4[SyntaxKind4["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind4[SyntaxKind4["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind4[SyntaxKind4["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind4[SyntaxKind4["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind4[SyntaxKind4["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + SyntaxKind4[SyntaxKind4["ShebangTrivia"] = 6] = "ShebangTrivia"; + SyntaxKind4[SyntaxKind4["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + SyntaxKind4[SyntaxKind4["NonTextFileMarkerTrivia"] = 8] = "NonTextFileMarkerTrivia"; + SyntaxKind4[SyntaxKind4["NumericLiteral"] = 9] = "NumericLiteral"; + SyntaxKind4[SyntaxKind4["BigIntLiteral"] = 10] = "BigIntLiteral"; + SyntaxKind4[SyntaxKind4["StringLiteral"] = 11] = "StringLiteral"; + SyntaxKind4[SyntaxKind4["JsxText"] = 12] = "JsxText"; + SyntaxKind4[SyntaxKind4["JsxTextAllWhiteSpaces"] = 13] = "JsxTextAllWhiteSpaces"; + SyntaxKind4[SyntaxKind4["RegularExpressionLiteral"] = 14] = "RegularExpressionLiteral"; + SyntaxKind4[SyntaxKind4["NoSubstitutionTemplateLiteral"] = 15] = "NoSubstitutionTemplateLiteral"; + SyntaxKind4[SyntaxKind4["TemplateHead"] = 16] = "TemplateHead"; + SyntaxKind4[SyntaxKind4["TemplateMiddle"] = 17] = "TemplateMiddle"; + SyntaxKind4[SyntaxKind4["TemplateTail"] = 18] = "TemplateTail"; + SyntaxKind4[SyntaxKind4["OpenBraceToken"] = 19] = "OpenBraceToken"; + SyntaxKind4[SyntaxKind4["CloseBraceToken"] = 20] = "CloseBraceToken"; + SyntaxKind4[SyntaxKind4["OpenParenToken"] = 21] = "OpenParenToken"; + SyntaxKind4[SyntaxKind4["CloseParenToken"] = 22] = "CloseParenToken"; + SyntaxKind4[SyntaxKind4["OpenBracketToken"] = 23] = "OpenBracketToken"; + SyntaxKind4[SyntaxKind4["CloseBracketToken"] = 24] = "CloseBracketToken"; + SyntaxKind4[SyntaxKind4["DotToken"] = 25] = "DotToken"; + SyntaxKind4[SyntaxKind4["DotDotDotToken"] = 26] = "DotDotDotToken"; + SyntaxKind4[SyntaxKind4["SemicolonToken"] = 27] = "SemicolonToken"; + SyntaxKind4[SyntaxKind4["CommaToken"] = 28] = "CommaToken"; + SyntaxKind4[SyntaxKind4["QuestionDotToken"] = 29] = "QuestionDotToken"; + SyntaxKind4[SyntaxKind4["LessThanToken"] = 30] = "LessThanToken"; + SyntaxKind4[SyntaxKind4["LessThanSlashToken"] = 31] = "LessThanSlashToken"; + SyntaxKind4[SyntaxKind4["GreaterThanToken"] = 32] = "GreaterThanToken"; + SyntaxKind4[SyntaxKind4["LessThanEqualsToken"] = 33] = "LessThanEqualsToken"; + SyntaxKind4[SyntaxKind4["GreaterThanEqualsToken"] = 34] = "GreaterThanEqualsToken"; + SyntaxKind4[SyntaxKind4["EqualsEqualsToken"] = 35] = "EqualsEqualsToken"; + SyntaxKind4[SyntaxKind4["ExclamationEqualsToken"] = 36] = "ExclamationEqualsToken"; + SyntaxKind4[SyntaxKind4["EqualsEqualsEqualsToken"] = 37] = "EqualsEqualsEqualsToken"; + SyntaxKind4[SyntaxKind4["ExclamationEqualsEqualsToken"] = 38] = "ExclamationEqualsEqualsToken"; + SyntaxKind4[SyntaxKind4["EqualsGreaterThanToken"] = 39] = "EqualsGreaterThanToken"; + SyntaxKind4[SyntaxKind4["PlusToken"] = 40] = "PlusToken"; + SyntaxKind4[SyntaxKind4["MinusToken"] = 41] = "MinusToken"; + SyntaxKind4[SyntaxKind4["AsteriskToken"] = 42] = "AsteriskToken"; + SyntaxKind4[SyntaxKind4["AsteriskAsteriskToken"] = 43] = "AsteriskAsteriskToken"; + SyntaxKind4[SyntaxKind4["SlashToken"] = 44] = "SlashToken"; + SyntaxKind4[SyntaxKind4["PercentToken"] = 45] = "PercentToken"; + SyntaxKind4[SyntaxKind4["PlusPlusToken"] = 46] = "PlusPlusToken"; + SyntaxKind4[SyntaxKind4["MinusMinusToken"] = 47] = "MinusMinusToken"; + SyntaxKind4[SyntaxKind4["LessThanLessThanToken"] = 48] = "LessThanLessThanToken"; + SyntaxKind4[SyntaxKind4["GreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanToken"; + SyntaxKind4[SyntaxKind4["GreaterThanGreaterThanGreaterThanToken"] = 50] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind4[SyntaxKind4["AmpersandToken"] = 51] = "AmpersandToken"; + SyntaxKind4[SyntaxKind4["BarToken"] = 52] = "BarToken"; + SyntaxKind4[SyntaxKind4["CaretToken"] = 53] = "CaretToken"; + SyntaxKind4[SyntaxKind4["ExclamationToken"] = 54] = "ExclamationToken"; + SyntaxKind4[SyntaxKind4["TildeToken"] = 55] = "TildeToken"; + SyntaxKind4[SyntaxKind4["AmpersandAmpersandToken"] = 56] = "AmpersandAmpersandToken"; + SyntaxKind4[SyntaxKind4["BarBarToken"] = 57] = "BarBarToken"; + SyntaxKind4[SyntaxKind4["QuestionToken"] = 58] = "QuestionToken"; + SyntaxKind4[SyntaxKind4["ColonToken"] = 59] = "ColonToken"; + SyntaxKind4[SyntaxKind4["AtToken"] = 60] = "AtToken"; + SyntaxKind4[SyntaxKind4["QuestionQuestionToken"] = 61] = "QuestionQuestionToken"; + SyntaxKind4[SyntaxKind4["BacktickToken"] = 62] = "BacktickToken"; + SyntaxKind4[SyntaxKind4["HashToken"] = 63] = "HashToken"; + SyntaxKind4[SyntaxKind4["EqualsToken"] = 64] = "EqualsToken"; + SyntaxKind4[SyntaxKind4["PlusEqualsToken"] = 65] = "PlusEqualsToken"; + SyntaxKind4[SyntaxKind4["MinusEqualsToken"] = 66] = "MinusEqualsToken"; + SyntaxKind4[SyntaxKind4["AsteriskEqualsToken"] = 67] = "AsteriskEqualsToken"; + SyntaxKind4[SyntaxKind4["AsteriskAsteriskEqualsToken"] = 68] = "AsteriskAsteriskEqualsToken"; + SyntaxKind4[SyntaxKind4["SlashEqualsToken"] = 69] = "SlashEqualsToken"; + SyntaxKind4[SyntaxKind4["PercentEqualsToken"] = 70] = "PercentEqualsToken"; + SyntaxKind4[SyntaxKind4["LessThanLessThanEqualsToken"] = 71] = "LessThanLessThanEqualsToken"; + SyntaxKind4[SyntaxKind4["GreaterThanGreaterThanEqualsToken"] = 72] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind4[SyntaxKind4["GreaterThanGreaterThanGreaterThanEqualsToken"] = 73] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind4[SyntaxKind4["AmpersandEqualsToken"] = 74] = "AmpersandEqualsToken"; + SyntaxKind4[SyntaxKind4["BarEqualsToken"] = 75] = "BarEqualsToken"; + SyntaxKind4[SyntaxKind4["BarBarEqualsToken"] = 76] = "BarBarEqualsToken"; + SyntaxKind4[SyntaxKind4["AmpersandAmpersandEqualsToken"] = 77] = "AmpersandAmpersandEqualsToken"; + SyntaxKind4[SyntaxKind4["QuestionQuestionEqualsToken"] = 78] = "QuestionQuestionEqualsToken"; + SyntaxKind4[SyntaxKind4["CaretEqualsToken"] = 79] = "CaretEqualsToken"; + SyntaxKind4[SyntaxKind4["Identifier"] = 80] = "Identifier"; + SyntaxKind4[SyntaxKind4["PrivateIdentifier"] = 81] = "PrivateIdentifier"; + SyntaxKind4[SyntaxKind4["JSDocCommentTextToken"] = 82] = "JSDocCommentTextToken"; + SyntaxKind4[SyntaxKind4["BreakKeyword"] = 83] = "BreakKeyword"; + SyntaxKind4[SyntaxKind4["CaseKeyword"] = 84] = "CaseKeyword"; + SyntaxKind4[SyntaxKind4["CatchKeyword"] = 85] = "CatchKeyword"; + SyntaxKind4[SyntaxKind4["ClassKeyword"] = 86] = "ClassKeyword"; + SyntaxKind4[SyntaxKind4["ConstKeyword"] = 87] = "ConstKeyword"; + SyntaxKind4[SyntaxKind4["ContinueKeyword"] = 88] = "ContinueKeyword"; + SyntaxKind4[SyntaxKind4["DebuggerKeyword"] = 89] = "DebuggerKeyword"; + SyntaxKind4[SyntaxKind4["DefaultKeyword"] = 90] = "DefaultKeyword"; + SyntaxKind4[SyntaxKind4["DeleteKeyword"] = 91] = "DeleteKeyword"; + SyntaxKind4[SyntaxKind4["DoKeyword"] = 92] = "DoKeyword"; + SyntaxKind4[SyntaxKind4["ElseKeyword"] = 93] = "ElseKeyword"; + SyntaxKind4[SyntaxKind4["EnumKeyword"] = 94] = "EnumKeyword"; + SyntaxKind4[SyntaxKind4["ExportKeyword"] = 95] = "ExportKeyword"; + SyntaxKind4[SyntaxKind4["ExtendsKeyword"] = 96] = "ExtendsKeyword"; + SyntaxKind4[SyntaxKind4["FalseKeyword"] = 97] = "FalseKeyword"; + SyntaxKind4[SyntaxKind4["FinallyKeyword"] = 98] = "FinallyKeyword"; + SyntaxKind4[SyntaxKind4["ForKeyword"] = 99] = "ForKeyword"; + SyntaxKind4[SyntaxKind4["FunctionKeyword"] = 100] = "FunctionKeyword"; + SyntaxKind4[SyntaxKind4["IfKeyword"] = 101] = "IfKeyword"; + SyntaxKind4[SyntaxKind4["ImportKeyword"] = 102] = "ImportKeyword"; + SyntaxKind4[SyntaxKind4["InKeyword"] = 103] = "InKeyword"; + SyntaxKind4[SyntaxKind4["InstanceOfKeyword"] = 104] = "InstanceOfKeyword"; + SyntaxKind4[SyntaxKind4["NewKeyword"] = 105] = "NewKeyword"; + SyntaxKind4[SyntaxKind4["NullKeyword"] = 106] = "NullKeyword"; + SyntaxKind4[SyntaxKind4["ReturnKeyword"] = 107] = "ReturnKeyword"; + SyntaxKind4[SyntaxKind4["SuperKeyword"] = 108] = "SuperKeyword"; + SyntaxKind4[SyntaxKind4["SwitchKeyword"] = 109] = "SwitchKeyword"; + SyntaxKind4[SyntaxKind4["ThisKeyword"] = 110] = "ThisKeyword"; + SyntaxKind4[SyntaxKind4["ThrowKeyword"] = 111] = "ThrowKeyword"; + SyntaxKind4[SyntaxKind4["TrueKeyword"] = 112] = "TrueKeyword"; + SyntaxKind4[SyntaxKind4["TryKeyword"] = 113] = "TryKeyword"; + SyntaxKind4[SyntaxKind4["TypeOfKeyword"] = 114] = "TypeOfKeyword"; + SyntaxKind4[SyntaxKind4["VarKeyword"] = 115] = "VarKeyword"; + SyntaxKind4[SyntaxKind4["VoidKeyword"] = 116] = "VoidKeyword"; + SyntaxKind4[SyntaxKind4["WhileKeyword"] = 117] = "WhileKeyword"; + SyntaxKind4[SyntaxKind4["WithKeyword"] = 118] = "WithKeyword"; + SyntaxKind4[SyntaxKind4["ImplementsKeyword"] = 119] = "ImplementsKeyword"; + SyntaxKind4[SyntaxKind4["InterfaceKeyword"] = 120] = "InterfaceKeyword"; + SyntaxKind4[SyntaxKind4["LetKeyword"] = 121] = "LetKeyword"; + SyntaxKind4[SyntaxKind4["PackageKeyword"] = 122] = "PackageKeyword"; + SyntaxKind4[SyntaxKind4["PrivateKeyword"] = 123] = "PrivateKeyword"; + SyntaxKind4[SyntaxKind4["ProtectedKeyword"] = 124] = "ProtectedKeyword"; + SyntaxKind4[SyntaxKind4["PublicKeyword"] = 125] = "PublicKeyword"; + SyntaxKind4[SyntaxKind4["StaticKeyword"] = 126] = "StaticKeyword"; + SyntaxKind4[SyntaxKind4["YieldKeyword"] = 127] = "YieldKeyword"; + SyntaxKind4[SyntaxKind4["AbstractKeyword"] = 128] = "AbstractKeyword"; + SyntaxKind4[SyntaxKind4["AccessorKeyword"] = 129] = "AccessorKeyword"; + SyntaxKind4[SyntaxKind4["AsKeyword"] = 130] = "AsKeyword"; + SyntaxKind4[SyntaxKind4["AssertsKeyword"] = 131] = "AssertsKeyword"; + SyntaxKind4[SyntaxKind4["AssertKeyword"] = 132] = "AssertKeyword"; + SyntaxKind4[SyntaxKind4["AnyKeyword"] = 133] = "AnyKeyword"; + SyntaxKind4[SyntaxKind4["AsyncKeyword"] = 134] = "AsyncKeyword"; + SyntaxKind4[SyntaxKind4["AwaitKeyword"] = 135] = "AwaitKeyword"; + SyntaxKind4[SyntaxKind4["BooleanKeyword"] = 136] = "BooleanKeyword"; + SyntaxKind4[SyntaxKind4["ConstructorKeyword"] = 137] = "ConstructorKeyword"; + SyntaxKind4[SyntaxKind4["DeclareKeyword"] = 138] = "DeclareKeyword"; + SyntaxKind4[SyntaxKind4["GetKeyword"] = 139] = "GetKeyword"; + SyntaxKind4[SyntaxKind4["InferKeyword"] = 140] = "InferKeyword"; + SyntaxKind4[SyntaxKind4["IntrinsicKeyword"] = 141] = "IntrinsicKeyword"; + SyntaxKind4[SyntaxKind4["IsKeyword"] = 142] = "IsKeyword"; + SyntaxKind4[SyntaxKind4["KeyOfKeyword"] = 143] = "KeyOfKeyword"; + SyntaxKind4[SyntaxKind4["ModuleKeyword"] = 144] = "ModuleKeyword"; + SyntaxKind4[SyntaxKind4["NamespaceKeyword"] = 145] = "NamespaceKeyword"; + SyntaxKind4[SyntaxKind4["NeverKeyword"] = 146] = "NeverKeyword"; + SyntaxKind4[SyntaxKind4["OutKeyword"] = 147] = "OutKeyword"; + SyntaxKind4[SyntaxKind4["ReadonlyKeyword"] = 148] = "ReadonlyKeyword"; + SyntaxKind4[SyntaxKind4["RequireKeyword"] = 149] = "RequireKeyword"; + SyntaxKind4[SyntaxKind4["NumberKeyword"] = 150] = "NumberKeyword"; + SyntaxKind4[SyntaxKind4["ObjectKeyword"] = 151] = "ObjectKeyword"; + SyntaxKind4[SyntaxKind4["SatisfiesKeyword"] = 152] = "SatisfiesKeyword"; + SyntaxKind4[SyntaxKind4["SetKeyword"] = 153] = "SetKeyword"; + SyntaxKind4[SyntaxKind4["StringKeyword"] = 154] = "StringKeyword"; + SyntaxKind4[SyntaxKind4["SymbolKeyword"] = 155] = "SymbolKeyword"; + SyntaxKind4[SyntaxKind4["TypeKeyword"] = 156] = "TypeKeyword"; + SyntaxKind4[SyntaxKind4["UndefinedKeyword"] = 157] = "UndefinedKeyword"; + SyntaxKind4[SyntaxKind4["UniqueKeyword"] = 158] = "UniqueKeyword"; + SyntaxKind4[SyntaxKind4["UnknownKeyword"] = 159] = "UnknownKeyword"; + SyntaxKind4[SyntaxKind4["UsingKeyword"] = 160] = "UsingKeyword"; + SyntaxKind4[SyntaxKind4["FromKeyword"] = 161] = "FromKeyword"; + SyntaxKind4[SyntaxKind4["GlobalKeyword"] = 162] = "GlobalKeyword"; + SyntaxKind4[SyntaxKind4["BigIntKeyword"] = 163] = "BigIntKeyword"; + SyntaxKind4[SyntaxKind4["OverrideKeyword"] = 164] = "OverrideKeyword"; + SyntaxKind4[SyntaxKind4["OfKeyword"] = 165] = "OfKeyword"; + SyntaxKind4[SyntaxKind4["QualifiedName"] = 166] = "QualifiedName"; + SyntaxKind4[SyntaxKind4["ComputedPropertyName"] = 167] = "ComputedPropertyName"; + SyntaxKind4[SyntaxKind4["TypeParameter"] = 168] = "TypeParameter"; + SyntaxKind4[SyntaxKind4["Parameter"] = 169] = "Parameter"; + SyntaxKind4[SyntaxKind4["Decorator"] = 170] = "Decorator"; + SyntaxKind4[SyntaxKind4["PropertySignature"] = 171] = "PropertySignature"; + SyntaxKind4[SyntaxKind4["PropertyDeclaration"] = 172] = "PropertyDeclaration"; + SyntaxKind4[SyntaxKind4["MethodSignature"] = 173] = "MethodSignature"; + SyntaxKind4[SyntaxKind4["MethodDeclaration"] = 174] = "MethodDeclaration"; + SyntaxKind4[SyntaxKind4["ClassStaticBlockDeclaration"] = 175] = "ClassStaticBlockDeclaration"; + SyntaxKind4[SyntaxKind4["Constructor"] = 176] = "Constructor"; + SyntaxKind4[SyntaxKind4["GetAccessor"] = 177] = "GetAccessor"; + SyntaxKind4[SyntaxKind4["SetAccessor"] = 178] = "SetAccessor"; + SyntaxKind4[SyntaxKind4["CallSignature"] = 179] = "CallSignature"; + SyntaxKind4[SyntaxKind4["ConstructSignature"] = 180] = "ConstructSignature"; + SyntaxKind4[SyntaxKind4["IndexSignature"] = 181] = "IndexSignature"; + SyntaxKind4[SyntaxKind4["TypePredicate"] = 182] = "TypePredicate"; + SyntaxKind4[SyntaxKind4["TypeReference"] = 183] = "TypeReference"; + SyntaxKind4[SyntaxKind4["FunctionType"] = 184] = "FunctionType"; + SyntaxKind4[SyntaxKind4["ConstructorType"] = 185] = "ConstructorType"; + SyntaxKind4[SyntaxKind4["TypeQuery"] = 186] = "TypeQuery"; + SyntaxKind4[SyntaxKind4["TypeLiteral"] = 187] = "TypeLiteral"; + SyntaxKind4[SyntaxKind4["ArrayType"] = 188] = "ArrayType"; + SyntaxKind4[SyntaxKind4["TupleType"] = 189] = "TupleType"; + SyntaxKind4[SyntaxKind4["OptionalType"] = 190] = "OptionalType"; + SyntaxKind4[SyntaxKind4["RestType"] = 191] = "RestType"; + SyntaxKind4[SyntaxKind4["UnionType"] = 192] = "UnionType"; + SyntaxKind4[SyntaxKind4["IntersectionType"] = 193] = "IntersectionType"; + SyntaxKind4[SyntaxKind4["ConditionalType"] = 194] = "ConditionalType"; + SyntaxKind4[SyntaxKind4["InferType"] = 195] = "InferType"; + SyntaxKind4[SyntaxKind4["ParenthesizedType"] = 196] = "ParenthesizedType"; + SyntaxKind4[SyntaxKind4["ThisType"] = 197] = "ThisType"; + SyntaxKind4[SyntaxKind4["TypeOperator"] = 198] = "TypeOperator"; + SyntaxKind4[SyntaxKind4["IndexedAccessType"] = 199] = "IndexedAccessType"; + SyntaxKind4[SyntaxKind4["MappedType"] = 200] = "MappedType"; + SyntaxKind4[SyntaxKind4["LiteralType"] = 201] = "LiteralType"; + SyntaxKind4[SyntaxKind4["NamedTupleMember"] = 202] = "NamedTupleMember"; + SyntaxKind4[SyntaxKind4["TemplateLiteralType"] = 203] = "TemplateLiteralType"; + SyntaxKind4[SyntaxKind4["TemplateLiteralTypeSpan"] = 204] = "TemplateLiteralTypeSpan"; + SyntaxKind4[SyntaxKind4["ImportType"] = 205] = "ImportType"; + SyntaxKind4[SyntaxKind4["ObjectBindingPattern"] = 206] = "ObjectBindingPattern"; + SyntaxKind4[SyntaxKind4["ArrayBindingPattern"] = 207] = "ArrayBindingPattern"; + SyntaxKind4[SyntaxKind4["BindingElement"] = 208] = "BindingElement"; + SyntaxKind4[SyntaxKind4["ArrayLiteralExpression"] = 209] = "ArrayLiteralExpression"; + SyntaxKind4[SyntaxKind4["ObjectLiteralExpression"] = 210] = "ObjectLiteralExpression"; + SyntaxKind4[SyntaxKind4["PropertyAccessExpression"] = 211] = "PropertyAccessExpression"; + SyntaxKind4[SyntaxKind4["ElementAccessExpression"] = 212] = "ElementAccessExpression"; + SyntaxKind4[SyntaxKind4["CallExpression"] = 213] = "CallExpression"; + SyntaxKind4[SyntaxKind4["NewExpression"] = 214] = "NewExpression"; + SyntaxKind4[SyntaxKind4["TaggedTemplateExpression"] = 215] = "TaggedTemplateExpression"; + SyntaxKind4[SyntaxKind4["TypeAssertionExpression"] = 216] = "TypeAssertionExpression"; + SyntaxKind4[SyntaxKind4["ParenthesizedExpression"] = 217] = "ParenthesizedExpression"; + SyntaxKind4[SyntaxKind4["FunctionExpression"] = 218] = "FunctionExpression"; + SyntaxKind4[SyntaxKind4["ArrowFunction"] = 219] = "ArrowFunction"; + SyntaxKind4[SyntaxKind4["DeleteExpression"] = 220] = "DeleteExpression"; + SyntaxKind4[SyntaxKind4["TypeOfExpression"] = 221] = "TypeOfExpression"; + SyntaxKind4[SyntaxKind4["VoidExpression"] = 222] = "VoidExpression"; + SyntaxKind4[SyntaxKind4["AwaitExpression"] = 223] = "AwaitExpression"; + SyntaxKind4[SyntaxKind4["PrefixUnaryExpression"] = 224] = "PrefixUnaryExpression"; + SyntaxKind4[SyntaxKind4["PostfixUnaryExpression"] = 225] = "PostfixUnaryExpression"; + SyntaxKind4[SyntaxKind4["BinaryExpression"] = 226] = "BinaryExpression"; + SyntaxKind4[SyntaxKind4["ConditionalExpression"] = 227] = "ConditionalExpression"; + SyntaxKind4[SyntaxKind4["TemplateExpression"] = 228] = "TemplateExpression"; + SyntaxKind4[SyntaxKind4["YieldExpression"] = 229] = "YieldExpression"; + SyntaxKind4[SyntaxKind4["SpreadElement"] = 230] = "SpreadElement"; + SyntaxKind4[SyntaxKind4["ClassExpression"] = 231] = "ClassExpression"; + SyntaxKind4[SyntaxKind4["OmittedExpression"] = 232] = "OmittedExpression"; + SyntaxKind4[SyntaxKind4["ExpressionWithTypeArguments"] = 233] = "ExpressionWithTypeArguments"; + SyntaxKind4[SyntaxKind4["AsExpression"] = 234] = "AsExpression"; + SyntaxKind4[SyntaxKind4["NonNullExpression"] = 235] = "NonNullExpression"; + SyntaxKind4[SyntaxKind4["MetaProperty"] = 236] = "MetaProperty"; + SyntaxKind4[SyntaxKind4["SyntheticExpression"] = 237] = "SyntheticExpression"; + SyntaxKind4[SyntaxKind4["SatisfiesExpression"] = 238] = "SatisfiesExpression"; + SyntaxKind4[SyntaxKind4["TemplateSpan"] = 239] = "TemplateSpan"; + SyntaxKind4[SyntaxKind4["SemicolonClassElement"] = 240] = "SemicolonClassElement"; + SyntaxKind4[SyntaxKind4["Block"] = 241] = "Block"; + SyntaxKind4[SyntaxKind4["EmptyStatement"] = 242] = "EmptyStatement"; + SyntaxKind4[SyntaxKind4["VariableStatement"] = 243] = "VariableStatement"; + SyntaxKind4[SyntaxKind4["ExpressionStatement"] = 244] = "ExpressionStatement"; + SyntaxKind4[SyntaxKind4["IfStatement"] = 245] = "IfStatement"; + SyntaxKind4[SyntaxKind4["DoStatement"] = 246] = "DoStatement"; + SyntaxKind4[SyntaxKind4["WhileStatement"] = 247] = "WhileStatement"; + SyntaxKind4[SyntaxKind4["ForStatement"] = 248] = "ForStatement"; + SyntaxKind4[SyntaxKind4["ForInStatement"] = 249] = "ForInStatement"; + SyntaxKind4[SyntaxKind4["ForOfStatement"] = 250] = "ForOfStatement"; + SyntaxKind4[SyntaxKind4["ContinueStatement"] = 251] = "ContinueStatement"; + SyntaxKind4[SyntaxKind4["BreakStatement"] = 252] = "BreakStatement"; + SyntaxKind4[SyntaxKind4["ReturnStatement"] = 253] = "ReturnStatement"; + SyntaxKind4[SyntaxKind4["WithStatement"] = 254] = "WithStatement"; + SyntaxKind4[SyntaxKind4["SwitchStatement"] = 255] = "SwitchStatement"; + SyntaxKind4[SyntaxKind4["LabeledStatement"] = 256] = "LabeledStatement"; + SyntaxKind4[SyntaxKind4["ThrowStatement"] = 257] = "ThrowStatement"; + SyntaxKind4[SyntaxKind4["TryStatement"] = 258] = "TryStatement"; + SyntaxKind4[SyntaxKind4["DebuggerStatement"] = 259] = "DebuggerStatement"; + SyntaxKind4[SyntaxKind4["VariableDeclaration"] = 260] = "VariableDeclaration"; + SyntaxKind4[SyntaxKind4["VariableDeclarationList"] = 261] = "VariableDeclarationList"; + SyntaxKind4[SyntaxKind4["FunctionDeclaration"] = 262] = "FunctionDeclaration"; + SyntaxKind4[SyntaxKind4["ClassDeclaration"] = 263] = "ClassDeclaration"; + SyntaxKind4[SyntaxKind4["InterfaceDeclaration"] = 264] = "InterfaceDeclaration"; + SyntaxKind4[SyntaxKind4["TypeAliasDeclaration"] = 265] = "TypeAliasDeclaration"; + SyntaxKind4[SyntaxKind4["EnumDeclaration"] = 266] = "EnumDeclaration"; + SyntaxKind4[SyntaxKind4["ModuleDeclaration"] = 267] = "ModuleDeclaration"; + SyntaxKind4[SyntaxKind4["ModuleBlock"] = 268] = "ModuleBlock"; + SyntaxKind4[SyntaxKind4["CaseBlock"] = 269] = "CaseBlock"; + SyntaxKind4[SyntaxKind4["NamespaceExportDeclaration"] = 270] = "NamespaceExportDeclaration"; + SyntaxKind4[SyntaxKind4["ImportEqualsDeclaration"] = 271] = "ImportEqualsDeclaration"; + SyntaxKind4[SyntaxKind4["ImportDeclaration"] = 272] = "ImportDeclaration"; + SyntaxKind4[SyntaxKind4["ImportClause"] = 273] = "ImportClause"; + SyntaxKind4[SyntaxKind4["NamespaceImport"] = 274] = "NamespaceImport"; + SyntaxKind4[SyntaxKind4["NamedImports"] = 275] = "NamedImports"; + SyntaxKind4[SyntaxKind4["ImportSpecifier"] = 276] = "ImportSpecifier"; + SyntaxKind4[SyntaxKind4["ExportAssignment"] = 277] = "ExportAssignment"; + SyntaxKind4[SyntaxKind4["ExportDeclaration"] = 278] = "ExportDeclaration"; + SyntaxKind4[SyntaxKind4["NamedExports"] = 279] = "NamedExports"; + SyntaxKind4[SyntaxKind4["NamespaceExport"] = 280] = "NamespaceExport"; + SyntaxKind4[SyntaxKind4["ExportSpecifier"] = 281] = "ExportSpecifier"; + SyntaxKind4[SyntaxKind4["MissingDeclaration"] = 282] = "MissingDeclaration"; + SyntaxKind4[SyntaxKind4["ExternalModuleReference"] = 283] = "ExternalModuleReference"; + SyntaxKind4[SyntaxKind4["JsxElement"] = 284] = "JsxElement"; + SyntaxKind4[SyntaxKind4["JsxSelfClosingElement"] = 285] = "JsxSelfClosingElement"; + SyntaxKind4[SyntaxKind4["JsxOpeningElement"] = 286] = "JsxOpeningElement"; + SyntaxKind4[SyntaxKind4["JsxClosingElement"] = 287] = "JsxClosingElement"; + SyntaxKind4[SyntaxKind4["JsxFragment"] = 288] = "JsxFragment"; + SyntaxKind4[SyntaxKind4["JsxOpeningFragment"] = 289] = "JsxOpeningFragment"; + SyntaxKind4[SyntaxKind4["JsxClosingFragment"] = 290] = "JsxClosingFragment"; + SyntaxKind4[SyntaxKind4["JsxAttribute"] = 291] = "JsxAttribute"; + SyntaxKind4[SyntaxKind4["JsxAttributes"] = 292] = "JsxAttributes"; + SyntaxKind4[SyntaxKind4["JsxSpreadAttribute"] = 293] = "JsxSpreadAttribute"; + SyntaxKind4[SyntaxKind4["JsxExpression"] = 294] = "JsxExpression"; + SyntaxKind4[SyntaxKind4["JsxNamespacedName"] = 295] = "JsxNamespacedName"; + SyntaxKind4[SyntaxKind4["CaseClause"] = 296] = "CaseClause"; + SyntaxKind4[SyntaxKind4["DefaultClause"] = 297] = "DefaultClause"; + SyntaxKind4[SyntaxKind4["HeritageClause"] = 298] = "HeritageClause"; + SyntaxKind4[SyntaxKind4["CatchClause"] = 299] = "CatchClause"; + SyntaxKind4[SyntaxKind4["ImportAttributes"] = 300] = "ImportAttributes"; + SyntaxKind4[SyntaxKind4["ImportAttribute"] = 301] = "ImportAttribute"; + SyntaxKind4[SyntaxKind4["AssertClause"] = 300 /* ImportAttributes */] = "AssertClause"; + SyntaxKind4[SyntaxKind4["AssertEntry"] = 301 /* ImportAttribute */] = "AssertEntry"; + SyntaxKind4[SyntaxKind4["ImportTypeAssertionContainer"] = 302] = "ImportTypeAssertionContainer"; + SyntaxKind4[SyntaxKind4["PropertyAssignment"] = 303] = "PropertyAssignment"; + SyntaxKind4[SyntaxKind4["ShorthandPropertyAssignment"] = 304] = "ShorthandPropertyAssignment"; + SyntaxKind4[SyntaxKind4["SpreadAssignment"] = 305] = "SpreadAssignment"; + SyntaxKind4[SyntaxKind4["EnumMember"] = 306] = "EnumMember"; + SyntaxKind4[SyntaxKind4["SourceFile"] = 307] = "SourceFile"; + SyntaxKind4[SyntaxKind4["Bundle"] = 308] = "Bundle"; + SyntaxKind4[SyntaxKind4["JSDocTypeExpression"] = 309] = "JSDocTypeExpression"; + SyntaxKind4[SyntaxKind4["JSDocNameReference"] = 310] = "JSDocNameReference"; + SyntaxKind4[SyntaxKind4["JSDocMemberName"] = 311] = "JSDocMemberName"; + SyntaxKind4[SyntaxKind4["JSDocAllType"] = 312] = "JSDocAllType"; + SyntaxKind4[SyntaxKind4["JSDocUnknownType"] = 313] = "JSDocUnknownType"; + SyntaxKind4[SyntaxKind4["JSDocNullableType"] = 314] = "JSDocNullableType"; + SyntaxKind4[SyntaxKind4["JSDocNonNullableType"] = 315] = "JSDocNonNullableType"; + SyntaxKind4[SyntaxKind4["JSDocOptionalType"] = 316] = "JSDocOptionalType"; + SyntaxKind4[SyntaxKind4["JSDocFunctionType"] = 317] = "JSDocFunctionType"; + SyntaxKind4[SyntaxKind4["JSDocVariadicType"] = 318] = "JSDocVariadicType"; + SyntaxKind4[SyntaxKind4["JSDocNamepathType"] = 319] = "JSDocNamepathType"; + SyntaxKind4[SyntaxKind4["JSDoc"] = 320] = "JSDoc"; + SyntaxKind4[SyntaxKind4["JSDocComment"] = 320 /* JSDoc */] = "JSDocComment"; + SyntaxKind4[SyntaxKind4["JSDocText"] = 321] = "JSDocText"; + SyntaxKind4[SyntaxKind4["JSDocTypeLiteral"] = 322] = "JSDocTypeLiteral"; + SyntaxKind4[SyntaxKind4["JSDocSignature"] = 323] = "JSDocSignature"; + SyntaxKind4[SyntaxKind4["JSDocLink"] = 324] = "JSDocLink"; + SyntaxKind4[SyntaxKind4["JSDocLinkCode"] = 325] = "JSDocLinkCode"; + SyntaxKind4[SyntaxKind4["JSDocLinkPlain"] = 326] = "JSDocLinkPlain"; + SyntaxKind4[SyntaxKind4["JSDocTag"] = 327] = "JSDocTag"; + SyntaxKind4[SyntaxKind4["JSDocAugmentsTag"] = 328] = "JSDocAugmentsTag"; + SyntaxKind4[SyntaxKind4["JSDocImplementsTag"] = 329] = "JSDocImplementsTag"; + SyntaxKind4[SyntaxKind4["JSDocAuthorTag"] = 330] = "JSDocAuthorTag"; + SyntaxKind4[SyntaxKind4["JSDocDeprecatedTag"] = 331] = "JSDocDeprecatedTag"; + SyntaxKind4[SyntaxKind4["JSDocClassTag"] = 332] = "JSDocClassTag"; + SyntaxKind4[SyntaxKind4["JSDocPublicTag"] = 333] = "JSDocPublicTag"; + SyntaxKind4[SyntaxKind4["JSDocPrivateTag"] = 334] = "JSDocPrivateTag"; + SyntaxKind4[SyntaxKind4["JSDocProtectedTag"] = 335] = "JSDocProtectedTag"; + SyntaxKind4[SyntaxKind4["JSDocReadonlyTag"] = 336] = "JSDocReadonlyTag"; + SyntaxKind4[SyntaxKind4["JSDocOverrideTag"] = 337] = "JSDocOverrideTag"; + SyntaxKind4[SyntaxKind4["JSDocCallbackTag"] = 338] = "JSDocCallbackTag"; + SyntaxKind4[SyntaxKind4["JSDocOverloadTag"] = 339] = "JSDocOverloadTag"; + SyntaxKind4[SyntaxKind4["JSDocEnumTag"] = 340] = "JSDocEnumTag"; + SyntaxKind4[SyntaxKind4["JSDocParameterTag"] = 341] = "JSDocParameterTag"; + SyntaxKind4[SyntaxKind4["JSDocReturnTag"] = 342] = "JSDocReturnTag"; + SyntaxKind4[SyntaxKind4["JSDocThisTag"] = 343] = "JSDocThisTag"; + SyntaxKind4[SyntaxKind4["JSDocTypeTag"] = 344] = "JSDocTypeTag"; + SyntaxKind4[SyntaxKind4["JSDocTemplateTag"] = 345] = "JSDocTemplateTag"; + SyntaxKind4[SyntaxKind4["JSDocTypedefTag"] = 346] = "JSDocTypedefTag"; + SyntaxKind4[SyntaxKind4["JSDocSeeTag"] = 347] = "JSDocSeeTag"; + SyntaxKind4[SyntaxKind4["JSDocPropertyTag"] = 348] = "JSDocPropertyTag"; + SyntaxKind4[SyntaxKind4["JSDocThrowsTag"] = 349] = "JSDocThrowsTag"; + SyntaxKind4[SyntaxKind4["JSDocSatisfiesTag"] = 350] = "JSDocSatisfiesTag"; + SyntaxKind4[SyntaxKind4["JSDocImportTag"] = 351] = "JSDocImportTag"; + SyntaxKind4[SyntaxKind4["SyntaxList"] = 352] = "SyntaxList"; + SyntaxKind4[SyntaxKind4["NotEmittedStatement"] = 353] = "NotEmittedStatement"; + SyntaxKind4[SyntaxKind4["NotEmittedTypeElement"] = 354] = "NotEmittedTypeElement"; + SyntaxKind4[SyntaxKind4["PartiallyEmittedExpression"] = 355] = "PartiallyEmittedExpression"; + SyntaxKind4[SyntaxKind4["CommaListExpression"] = 356] = "CommaListExpression"; + SyntaxKind4[SyntaxKind4["SyntheticReferenceExpression"] = 357] = "SyntheticReferenceExpression"; + SyntaxKind4[SyntaxKind4["Count"] = 358] = "Count"; + SyntaxKind4[SyntaxKind4["FirstAssignment"] = 64 /* EqualsToken */] = "FirstAssignment"; + SyntaxKind4[SyntaxKind4["LastAssignment"] = 79 /* CaretEqualsToken */] = "LastAssignment"; + SyntaxKind4[SyntaxKind4["FirstCompoundAssignment"] = 65 /* PlusEqualsToken */] = "FirstCompoundAssignment"; + SyntaxKind4[SyntaxKind4["LastCompoundAssignment"] = 79 /* CaretEqualsToken */] = "LastCompoundAssignment"; + SyntaxKind4[SyntaxKind4["FirstReservedWord"] = 83 /* BreakKeyword */] = "FirstReservedWord"; + SyntaxKind4[SyntaxKind4["LastReservedWord"] = 118 /* WithKeyword */] = "LastReservedWord"; + SyntaxKind4[SyntaxKind4["FirstKeyword"] = 83 /* BreakKeyword */] = "FirstKeyword"; + SyntaxKind4[SyntaxKind4["LastKeyword"] = 165 /* OfKeyword */] = "LastKeyword"; + SyntaxKind4[SyntaxKind4["FirstFutureReservedWord"] = 119 /* ImplementsKeyword */] = "FirstFutureReservedWord"; + SyntaxKind4[SyntaxKind4["LastFutureReservedWord"] = 127 /* YieldKeyword */] = "LastFutureReservedWord"; + SyntaxKind4[SyntaxKind4["FirstTypeNode"] = 182 /* TypePredicate */] = "FirstTypeNode"; + SyntaxKind4[SyntaxKind4["LastTypeNode"] = 205 /* ImportType */] = "LastTypeNode"; + SyntaxKind4[SyntaxKind4["FirstPunctuation"] = 19 /* OpenBraceToken */] = "FirstPunctuation"; + SyntaxKind4[SyntaxKind4["LastPunctuation"] = 79 /* CaretEqualsToken */] = "LastPunctuation"; + SyntaxKind4[SyntaxKind4["FirstToken"] = 0 /* Unknown */] = "FirstToken"; + SyntaxKind4[SyntaxKind4["LastToken"] = 165 /* LastKeyword */] = "LastToken"; + SyntaxKind4[SyntaxKind4["FirstTriviaToken"] = 2 /* SingleLineCommentTrivia */] = "FirstTriviaToken"; + SyntaxKind4[SyntaxKind4["LastTriviaToken"] = 7 /* ConflictMarkerTrivia */] = "LastTriviaToken"; + SyntaxKind4[SyntaxKind4["FirstLiteralToken"] = 9 /* NumericLiteral */] = "FirstLiteralToken"; + SyntaxKind4[SyntaxKind4["LastLiteralToken"] = 15 /* NoSubstitutionTemplateLiteral */] = "LastLiteralToken"; + SyntaxKind4[SyntaxKind4["FirstTemplateToken"] = 15 /* NoSubstitutionTemplateLiteral */] = "FirstTemplateToken"; + SyntaxKind4[SyntaxKind4["LastTemplateToken"] = 18 /* TemplateTail */] = "LastTemplateToken"; + SyntaxKind4[SyntaxKind4["FirstBinaryOperator"] = 30 /* LessThanToken */] = "FirstBinaryOperator"; + SyntaxKind4[SyntaxKind4["LastBinaryOperator"] = 79 /* CaretEqualsToken */] = "LastBinaryOperator"; + SyntaxKind4[SyntaxKind4["FirstStatement"] = 243 /* VariableStatement */] = "FirstStatement"; + SyntaxKind4[SyntaxKind4["LastStatement"] = 259 /* DebuggerStatement */] = "LastStatement"; + SyntaxKind4[SyntaxKind4["FirstNode"] = 166 /* QualifiedName */] = "FirstNode"; + SyntaxKind4[SyntaxKind4["FirstJSDocNode"] = 309 /* JSDocTypeExpression */] = "FirstJSDocNode"; + SyntaxKind4[SyntaxKind4["LastJSDocNode"] = 351 /* JSDocImportTag */] = "LastJSDocNode"; + SyntaxKind4[SyntaxKind4["FirstJSDocTagNode"] = 327 /* JSDocTag */] = "FirstJSDocTagNode"; + SyntaxKind4[SyntaxKind4["LastJSDocTagNode"] = 351 /* JSDocImportTag */] = "LastJSDocTagNode"; + SyntaxKind4[SyntaxKind4["FirstContextualKeyword"] = 128 /* AbstractKeyword */] = "FirstContextualKeyword"; + SyntaxKind4[SyntaxKind4["LastContextualKeyword"] = 165 /* OfKeyword */] = "LastContextualKeyword"; + return SyntaxKind4; +})(SyntaxKind || {}); +var NodeFlags = /* @__PURE__ */ ((NodeFlags3) => { + NodeFlags3[NodeFlags3["None"] = 0] = "None"; + NodeFlags3[NodeFlags3["Let"] = 1] = "Let"; + NodeFlags3[NodeFlags3["Const"] = 2] = "Const"; + NodeFlags3[NodeFlags3["Using"] = 4] = "Using"; + NodeFlags3[NodeFlags3["AwaitUsing"] = 6] = "AwaitUsing"; + NodeFlags3[NodeFlags3["NestedNamespace"] = 8] = "NestedNamespace"; + NodeFlags3[NodeFlags3["Synthesized"] = 16] = "Synthesized"; + NodeFlags3[NodeFlags3["Namespace"] = 32] = "Namespace"; + NodeFlags3[NodeFlags3["OptionalChain"] = 64] = "OptionalChain"; + NodeFlags3[NodeFlags3["ExportContext"] = 128] = "ExportContext"; + NodeFlags3[NodeFlags3["ContainsThis"] = 256] = "ContainsThis"; + NodeFlags3[NodeFlags3["HasImplicitReturn"] = 512] = "HasImplicitReturn"; + NodeFlags3[NodeFlags3["HasExplicitReturn"] = 1024] = "HasExplicitReturn"; + NodeFlags3[NodeFlags3["GlobalAugmentation"] = 2048] = "GlobalAugmentation"; + NodeFlags3[NodeFlags3["HasAsyncFunctions"] = 4096] = "HasAsyncFunctions"; + NodeFlags3[NodeFlags3["DisallowInContext"] = 8192] = "DisallowInContext"; + NodeFlags3[NodeFlags3["YieldContext"] = 16384] = "YieldContext"; + NodeFlags3[NodeFlags3["DecoratorContext"] = 32768] = "DecoratorContext"; + NodeFlags3[NodeFlags3["AwaitContext"] = 65536] = "AwaitContext"; + NodeFlags3[NodeFlags3["DisallowConditionalTypesContext"] = 131072] = "DisallowConditionalTypesContext"; + NodeFlags3[NodeFlags3["ThisNodeHasError"] = 262144] = "ThisNodeHasError"; + NodeFlags3[NodeFlags3["JavaScriptFile"] = 524288] = "JavaScriptFile"; + NodeFlags3[NodeFlags3["ThisNodeOrAnySubNodesHasError"] = 1048576] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags3[NodeFlags3["HasAggregatedChildData"] = 2097152] = "HasAggregatedChildData"; + NodeFlags3[NodeFlags3["PossiblyContainsDynamicImport"] = 4194304] = "PossiblyContainsDynamicImport"; + NodeFlags3[NodeFlags3["PossiblyContainsImportMeta"] = 8388608] = "PossiblyContainsImportMeta"; + NodeFlags3[NodeFlags3["JSDoc"] = 16777216] = "JSDoc"; + NodeFlags3[NodeFlags3["Ambient"] = 33554432] = "Ambient"; + NodeFlags3[NodeFlags3["InWithStatement"] = 67108864] = "InWithStatement"; + NodeFlags3[NodeFlags3["JsonFile"] = 134217728] = "JsonFile"; + NodeFlags3[NodeFlags3["TypeCached"] = 268435456] = "TypeCached"; + NodeFlags3[NodeFlags3["Deprecated"] = 536870912] = "Deprecated"; + NodeFlags3[NodeFlags3["BlockScoped"] = 7] = "BlockScoped"; + NodeFlags3[NodeFlags3["Constant"] = 6] = "Constant"; + NodeFlags3[NodeFlags3["ReachabilityCheckFlags"] = 1536] = "ReachabilityCheckFlags"; + NodeFlags3[NodeFlags3["ReachabilityAndEmitFlags"] = 5632] = "ReachabilityAndEmitFlags"; + NodeFlags3[NodeFlags3["ContextFlags"] = 101441536] = "ContextFlags"; + NodeFlags3[NodeFlags3["TypeExcludesFlags"] = 81920] = "TypeExcludesFlags"; + NodeFlags3[NodeFlags3["PermanentlySetIncrementalFlags"] = 12582912] = "PermanentlySetIncrementalFlags"; + NodeFlags3[NodeFlags3["IdentifierHasExtendedUnicodeEscape"] = 256 /* ContainsThis */] = "IdentifierHasExtendedUnicodeEscape"; + NodeFlags3[NodeFlags3["IdentifierIsInJSDocNamespace"] = 4096 /* HasAsyncFunctions */] = "IdentifierIsInJSDocNamespace"; + return NodeFlags3; +})(NodeFlags || {}); +var ModifierFlags = /* @__PURE__ */ ((ModifierFlags3) => { + ModifierFlags3[ModifierFlags3["None"] = 0] = "None"; + ModifierFlags3[ModifierFlags3["Public"] = 1] = "Public"; + ModifierFlags3[ModifierFlags3["Private"] = 2] = "Private"; + ModifierFlags3[ModifierFlags3["Protected"] = 4] = "Protected"; + ModifierFlags3[ModifierFlags3["Readonly"] = 8] = "Readonly"; + ModifierFlags3[ModifierFlags3["Override"] = 16] = "Override"; + ModifierFlags3[ModifierFlags3["Export"] = 32] = "Export"; + ModifierFlags3[ModifierFlags3["Abstract"] = 64] = "Abstract"; + ModifierFlags3[ModifierFlags3["Ambient"] = 128] = "Ambient"; + ModifierFlags3[ModifierFlags3["Static"] = 256] = "Static"; + ModifierFlags3[ModifierFlags3["Accessor"] = 512] = "Accessor"; + ModifierFlags3[ModifierFlags3["Async"] = 1024] = "Async"; + ModifierFlags3[ModifierFlags3["Default"] = 2048] = "Default"; + ModifierFlags3[ModifierFlags3["Const"] = 4096] = "Const"; + ModifierFlags3[ModifierFlags3["In"] = 8192] = "In"; + ModifierFlags3[ModifierFlags3["Out"] = 16384] = "Out"; + ModifierFlags3[ModifierFlags3["Decorator"] = 32768] = "Decorator"; + ModifierFlags3[ModifierFlags3["Deprecated"] = 65536] = "Deprecated"; + ModifierFlags3[ModifierFlags3["JSDocPublic"] = 8388608] = "JSDocPublic"; + ModifierFlags3[ModifierFlags3["JSDocPrivate"] = 16777216] = "JSDocPrivate"; + ModifierFlags3[ModifierFlags3["JSDocProtected"] = 33554432] = "JSDocProtected"; + ModifierFlags3[ModifierFlags3["JSDocReadonly"] = 67108864] = "JSDocReadonly"; + ModifierFlags3[ModifierFlags3["JSDocOverride"] = 134217728] = "JSDocOverride"; + ModifierFlags3[ModifierFlags3["SyntacticOrJSDocModifiers"] = 31] = "SyntacticOrJSDocModifiers"; + ModifierFlags3[ModifierFlags3["SyntacticOnlyModifiers"] = 65504] = "SyntacticOnlyModifiers"; + ModifierFlags3[ModifierFlags3["SyntacticModifiers"] = 65535] = "SyntacticModifiers"; + ModifierFlags3[ModifierFlags3["JSDocCacheOnlyModifiers"] = 260046848] = "JSDocCacheOnlyModifiers"; + ModifierFlags3[ModifierFlags3["JSDocOnlyModifiers"] = 65536 /* Deprecated */] = "JSDocOnlyModifiers"; + ModifierFlags3[ModifierFlags3["NonCacheOnlyModifiers"] = 131071] = "NonCacheOnlyModifiers"; + ModifierFlags3[ModifierFlags3["HasComputedJSDocModifiers"] = 268435456] = "HasComputedJSDocModifiers"; + ModifierFlags3[ModifierFlags3["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + ModifierFlags3[ModifierFlags3["AccessibilityModifier"] = 7] = "AccessibilityModifier"; + ModifierFlags3[ModifierFlags3["ParameterPropertyModifier"] = 31] = "ParameterPropertyModifier"; + ModifierFlags3[ModifierFlags3["NonPublicAccessibilityModifier"] = 6] = "NonPublicAccessibilityModifier"; + ModifierFlags3[ModifierFlags3["TypeScriptModifier"] = 28895] = "TypeScriptModifier"; + ModifierFlags3[ModifierFlags3["ExportDefault"] = 2080] = "ExportDefault"; + ModifierFlags3[ModifierFlags3["All"] = 131071] = "All"; + ModifierFlags3[ModifierFlags3["Modifier"] = 98303] = "Modifier"; + return ModifierFlags3; +})(ModifierFlags || {}); +var RelationComparisonResult = /* @__PURE__ */ ((RelationComparisonResult3) => { + RelationComparisonResult3[RelationComparisonResult3["None"] = 0] = "None"; + RelationComparisonResult3[RelationComparisonResult3["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult3[RelationComparisonResult3["Failed"] = 2] = "Failed"; + RelationComparisonResult3[RelationComparisonResult3["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable"; + RelationComparisonResult3[RelationComparisonResult3["ReportsUnreliable"] = 16] = "ReportsUnreliable"; + RelationComparisonResult3[RelationComparisonResult3["ReportsMask"] = 24] = "ReportsMask"; + RelationComparisonResult3[RelationComparisonResult3["ComplexityOverflow"] = 32] = "ComplexityOverflow"; + RelationComparisonResult3[RelationComparisonResult3["StackDepthOverflow"] = 64] = "StackDepthOverflow"; + RelationComparisonResult3[RelationComparisonResult3["Overflow"] = 96] = "Overflow"; + return RelationComparisonResult3; +})(RelationComparisonResult || {}); +var GeneratedIdentifierFlags = /* @__PURE__ */ ((GeneratedIdentifierFlags2) => { + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["None"] = 0] = "None"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Node"] = 4] = "Node"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["KindMask"] = 7] = "KindMask"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["FileLevel"] = 32] = "FileLevel"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["AllowNameSubstitution"] = 64] = "AllowNameSubstitution"; + return GeneratedIdentifierFlags2; +})(GeneratedIdentifierFlags || {}); +var FlowFlags = /* @__PURE__ */ ((FlowFlags2) => { + FlowFlags2[FlowFlags2["Unreachable"] = 1] = "Unreachable"; + FlowFlags2[FlowFlags2["Start"] = 2] = "Start"; + FlowFlags2[FlowFlags2["BranchLabel"] = 4] = "BranchLabel"; + FlowFlags2[FlowFlags2["LoopLabel"] = 8] = "LoopLabel"; + FlowFlags2[FlowFlags2["Assignment"] = 16] = "Assignment"; + FlowFlags2[FlowFlags2["TrueCondition"] = 32] = "TrueCondition"; + FlowFlags2[FlowFlags2["FalseCondition"] = 64] = "FalseCondition"; + FlowFlags2[FlowFlags2["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags2[FlowFlags2["ArrayMutation"] = 256] = "ArrayMutation"; + FlowFlags2[FlowFlags2["Call"] = 512] = "Call"; + FlowFlags2[FlowFlags2["ReduceLabel"] = 1024] = "ReduceLabel"; + FlowFlags2[FlowFlags2["Referenced"] = 2048] = "Referenced"; + FlowFlags2[FlowFlags2["Shared"] = 4096] = "Shared"; + FlowFlags2[FlowFlags2["Label"] = 12] = "Label"; + FlowFlags2[FlowFlags2["Condition"] = 96] = "Condition"; + return FlowFlags2; +})(FlowFlags || {}); +var OperationCanceledException = class { +}; +var FileIncludeKind = /* @__PURE__ */ ((FileIncludeKind2) => { + FileIncludeKind2[FileIncludeKind2["RootFile"] = 0] = "RootFile"; + FileIncludeKind2[FileIncludeKind2["SourceFromProjectReference"] = 1] = "SourceFromProjectReference"; + FileIncludeKind2[FileIncludeKind2["OutputFromProjectReference"] = 2] = "OutputFromProjectReference"; + FileIncludeKind2[FileIncludeKind2["Import"] = 3] = "Import"; + FileIncludeKind2[FileIncludeKind2["ReferenceFile"] = 4] = "ReferenceFile"; + FileIncludeKind2[FileIncludeKind2["TypeReferenceDirective"] = 5] = "TypeReferenceDirective"; + FileIncludeKind2[FileIncludeKind2["LibFile"] = 6] = "LibFile"; + FileIncludeKind2[FileIncludeKind2["LibReferenceDirective"] = 7] = "LibReferenceDirective"; + FileIncludeKind2[FileIncludeKind2["AutomaticTypeDirectiveFile"] = 8] = "AutomaticTypeDirectiveFile"; + return FileIncludeKind2; +})(FileIncludeKind || {}); +var SymbolFlags = /* @__PURE__ */ ((SymbolFlags2) => { + SymbolFlags2[SymbolFlags2["None"] = 0] = "None"; + SymbolFlags2[SymbolFlags2["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags2[SymbolFlags2["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags2[SymbolFlags2["Property"] = 4] = "Property"; + SymbolFlags2[SymbolFlags2["EnumMember"] = 8] = "EnumMember"; + SymbolFlags2[SymbolFlags2["Function"] = 16] = "Function"; + SymbolFlags2[SymbolFlags2["Class"] = 32] = "Class"; + SymbolFlags2[SymbolFlags2["Interface"] = 64] = "Interface"; + SymbolFlags2[SymbolFlags2["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags2[SymbolFlags2["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags2[SymbolFlags2["ValueModule"] = 512] = "ValueModule"; + SymbolFlags2[SymbolFlags2["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags2[SymbolFlags2["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags2[SymbolFlags2["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags2[SymbolFlags2["Method"] = 8192] = "Method"; + SymbolFlags2[SymbolFlags2["Constructor"] = 16384] = "Constructor"; + SymbolFlags2[SymbolFlags2["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags2[SymbolFlags2["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags2[SymbolFlags2["Signature"] = 131072] = "Signature"; + SymbolFlags2[SymbolFlags2["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags2[SymbolFlags2["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags2[SymbolFlags2["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags2[SymbolFlags2["Alias"] = 2097152] = "Alias"; + SymbolFlags2[SymbolFlags2["Prototype"] = 4194304] = "Prototype"; + SymbolFlags2[SymbolFlags2["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags2[SymbolFlags2["Optional"] = 16777216] = "Optional"; + SymbolFlags2[SymbolFlags2["Transient"] = 33554432] = "Transient"; + SymbolFlags2[SymbolFlags2["Assignment"] = 67108864] = "Assignment"; + SymbolFlags2[SymbolFlags2["ModuleExports"] = 134217728] = "ModuleExports"; + SymbolFlags2[SymbolFlags2["All"] = -1] = "All"; + SymbolFlags2[SymbolFlags2["Enum"] = 384] = "Enum"; + SymbolFlags2[SymbolFlags2["Variable"] = 3] = "Variable"; + SymbolFlags2[SymbolFlags2["Value"] = 111551] = "Value"; + SymbolFlags2[SymbolFlags2["Type"] = 788968] = "Type"; + SymbolFlags2[SymbolFlags2["Namespace"] = 1920] = "Namespace"; + SymbolFlags2[SymbolFlags2["Module"] = 1536] = "Module"; + SymbolFlags2[SymbolFlags2["Accessor"] = 98304] = "Accessor"; + SymbolFlags2[SymbolFlags2["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes"; + SymbolFlags2[SymbolFlags2["BlockScopedVariableExcludes"] = 111551 /* Value */] = "BlockScopedVariableExcludes"; + SymbolFlags2[SymbolFlags2["ParameterExcludes"] = 111551 /* Value */] = "ParameterExcludes"; + SymbolFlags2[SymbolFlags2["PropertyExcludes"] = 0 /* None */] = "PropertyExcludes"; + SymbolFlags2[SymbolFlags2["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; + SymbolFlags2[SymbolFlags2["FunctionExcludes"] = 110991] = "FunctionExcludes"; + SymbolFlags2[SymbolFlags2["ClassExcludes"] = 899503] = "ClassExcludes"; + SymbolFlags2[SymbolFlags2["InterfaceExcludes"] = 788872] = "InterfaceExcludes"; + SymbolFlags2[SymbolFlags2["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; + SymbolFlags2[SymbolFlags2["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; + SymbolFlags2[SymbolFlags2["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; + SymbolFlags2[SymbolFlags2["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags2[SymbolFlags2["MethodExcludes"] = 103359] = "MethodExcludes"; + SymbolFlags2[SymbolFlags2["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes"; + SymbolFlags2[SymbolFlags2["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes"; + SymbolFlags2[SymbolFlags2["AccessorExcludes"] = 13247] = "AccessorExcludes"; + SymbolFlags2[SymbolFlags2["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes"; + SymbolFlags2[SymbolFlags2["TypeAliasExcludes"] = 788968 /* Type */] = "TypeAliasExcludes"; + SymbolFlags2[SymbolFlags2["AliasExcludes"] = 2097152 /* Alias */] = "AliasExcludes"; + SymbolFlags2[SymbolFlags2["ModuleMember"] = 2623475] = "ModuleMember"; + SymbolFlags2[SymbolFlags2["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags2[SymbolFlags2["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags2[SymbolFlags2["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags2[SymbolFlags2["ClassMember"] = 106500] = "ClassMember"; + SymbolFlags2[SymbolFlags2["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier"; + SymbolFlags2[SymbolFlags2["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier"; + SymbolFlags2[SymbolFlags2["Classifiable"] = 2885600] = "Classifiable"; + SymbolFlags2[SymbolFlags2["LateBindingContainer"] = 6256] = "LateBindingContainer"; + return SymbolFlags2; +})(SymbolFlags || {}); +var NodeCheckFlags = /* @__PURE__ */ ((NodeCheckFlags3) => { + NodeCheckFlags3[NodeCheckFlags3["None"] = 0] = "None"; + NodeCheckFlags3[NodeCheckFlags3["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags3[NodeCheckFlags3["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags3[NodeCheckFlags3["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags3[NodeCheckFlags3["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags3[NodeCheckFlags3["SuperInstance"] = 16] = "SuperInstance"; + NodeCheckFlags3[NodeCheckFlags3["SuperStatic"] = 32] = "SuperStatic"; + NodeCheckFlags3[NodeCheckFlags3["ContextChecked"] = 64] = "ContextChecked"; + NodeCheckFlags3[NodeCheckFlags3["MethodWithSuperPropertyAccessInAsync"] = 128] = "MethodWithSuperPropertyAccessInAsync"; + NodeCheckFlags3[NodeCheckFlags3["MethodWithSuperPropertyAssignmentInAsync"] = 256] = "MethodWithSuperPropertyAssignmentInAsync"; + NodeCheckFlags3[NodeCheckFlags3["CaptureArguments"] = 512] = "CaptureArguments"; + NodeCheckFlags3[NodeCheckFlags3["EnumValuesComputed"] = 1024] = "EnumValuesComputed"; + NodeCheckFlags3[NodeCheckFlags3["LexicalModuleMergesWithClass"] = 2048] = "LexicalModuleMergesWithClass"; + NodeCheckFlags3[NodeCheckFlags3["LoopWithCapturedBlockScopedBinding"] = 4096] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags3[NodeCheckFlags3["ContainsCapturedBlockScopeBinding"] = 8192] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags3[NodeCheckFlags3["CapturedBlockScopedBinding"] = 16384] = "CapturedBlockScopedBinding"; + NodeCheckFlags3[NodeCheckFlags3["BlockScopedBindingInLoop"] = 32768] = "BlockScopedBindingInLoop"; + NodeCheckFlags3[NodeCheckFlags3["NeedsLoopOutParameter"] = 65536] = "NeedsLoopOutParameter"; + NodeCheckFlags3[NodeCheckFlags3["AssignmentsMarked"] = 131072] = "AssignmentsMarked"; + NodeCheckFlags3[NodeCheckFlags3["ContainsConstructorReference"] = 262144] = "ContainsConstructorReference"; + NodeCheckFlags3[NodeCheckFlags3["ConstructorReference"] = 536870912] = "ConstructorReference"; + NodeCheckFlags3[NodeCheckFlags3["ContainsClassWithPrivateIdentifiers"] = 1048576] = "ContainsClassWithPrivateIdentifiers"; + NodeCheckFlags3[NodeCheckFlags3["ContainsSuperPropertyInStaticInitializer"] = 2097152] = "ContainsSuperPropertyInStaticInitializer"; + NodeCheckFlags3[NodeCheckFlags3["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; + NodeCheckFlags3[NodeCheckFlags3["PartiallyTypeChecked"] = 8388608] = "PartiallyTypeChecked"; + NodeCheckFlags3[NodeCheckFlags3["LazyFlags"] = 539358128] = "LazyFlags"; + return NodeCheckFlags3; +})(NodeCheckFlags || {}); +var TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { + TypeFlags2[TypeFlags2["Any"] = 1] = "Any"; + TypeFlags2[TypeFlags2["Unknown"] = 2] = "Unknown"; + TypeFlags2[TypeFlags2["String"] = 4] = "String"; + TypeFlags2[TypeFlags2["Number"] = 8] = "Number"; + TypeFlags2[TypeFlags2["Boolean"] = 16] = "Boolean"; + TypeFlags2[TypeFlags2["Enum"] = 32] = "Enum"; + TypeFlags2[TypeFlags2["BigInt"] = 64] = "BigInt"; + TypeFlags2[TypeFlags2["StringLiteral"] = 128] = "StringLiteral"; + TypeFlags2[TypeFlags2["NumberLiteral"] = 256] = "NumberLiteral"; + TypeFlags2[TypeFlags2["BooleanLiteral"] = 512] = "BooleanLiteral"; + TypeFlags2[TypeFlags2["EnumLiteral"] = 1024] = "EnumLiteral"; + TypeFlags2[TypeFlags2["BigIntLiteral"] = 2048] = "BigIntLiteral"; + TypeFlags2[TypeFlags2["ESSymbol"] = 4096] = "ESSymbol"; + TypeFlags2[TypeFlags2["UniqueESSymbol"] = 8192] = "UniqueESSymbol"; + TypeFlags2[TypeFlags2["Void"] = 16384] = "Void"; + TypeFlags2[TypeFlags2["Undefined"] = 32768] = "Undefined"; + TypeFlags2[TypeFlags2["Null"] = 65536] = "Null"; + TypeFlags2[TypeFlags2["Never"] = 131072] = "Never"; + TypeFlags2[TypeFlags2["TypeParameter"] = 262144] = "TypeParameter"; + TypeFlags2[TypeFlags2["Object"] = 524288] = "Object"; + TypeFlags2[TypeFlags2["Union"] = 1048576] = "Union"; + TypeFlags2[TypeFlags2["Intersection"] = 2097152] = "Intersection"; + TypeFlags2[TypeFlags2["Index"] = 4194304] = "Index"; + TypeFlags2[TypeFlags2["IndexedAccess"] = 8388608] = "IndexedAccess"; + TypeFlags2[TypeFlags2["Conditional"] = 16777216] = "Conditional"; + TypeFlags2[TypeFlags2["Substitution"] = 33554432] = "Substitution"; + TypeFlags2[TypeFlags2["NonPrimitive"] = 67108864] = "NonPrimitive"; + TypeFlags2[TypeFlags2["TemplateLiteral"] = 134217728] = "TemplateLiteral"; + TypeFlags2[TypeFlags2["StringMapping"] = 268435456] = "StringMapping"; + TypeFlags2[TypeFlags2["Reserved1"] = 536870912] = "Reserved1"; + TypeFlags2[TypeFlags2["Reserved2"] = 1073741824] = "Reserved2"; + TypeFlags2[TypeFlags2["AnyOrUnknown"] = 3] = "AnyOrUnknown"; + TypeFlags2[TypeFlags2["Nullable"] = 98304] = "Nullable"; + TypeFlags2[TypeFlags2["Literal"] = 2944] = "Literal"; + TypeFlags2[TypeFlags2["Unit"] = 109472] = "Unit"; + TypeFlags2[TypeFlags2["Freshable"] = 2976] = "Freshable"; + TypeFlags2[TypeFlags2["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; + TypeFlags2[TypeFlags2["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; + TypeFlags2[TypeFlags2["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; + TypeFlags2[TypeFlags2["PossiblyFalsy"] = 117724] = "PossiblyFalsy"; + TypeFlags2[TypeFlags2["Intrinsic"] = 67359327] = "Intrinsic"; + TypeFlags2[TypeFlags2["StringLike"] = 402653316] = "StringLike"; + TypeFlags2[TypeFlags2["NumberLike"] = 296] = "NumberLike"; + TypeFlags2[TypeFlags2["BigIntLike"] = 2112] = "BigIntLike"; + TypeFlags2[TypeFlags2["BooleanLike"] = 528] = "BooleanLike"; + TypeFlags2[TypeFlags2["EnumLike"] = 1056] = "EnumLike"; + TypeFlags2[TypeFlags2["ESSymbolLike"] = 12288] = "ESSymbolLike"; + TypeFlags2[TypeFlags2["VoidLike"] = 49152] = "VoidLike"; + TypeFlags2[TypeFlags2["Primitive"] = 402784252] = "Primitive"; + TypeFlags2[TypeFlags2["DefinitelyNonNullable"] = 470302716] = "DefinitelyNonNullable"; + TypeFlags2[TypeFlags2["DisjointDomains"] = 469892092] = "DisjointDomains"; + TypeFlags2[TypeFlags2["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; + TypeFlags2[TypeFlags2["StructuredType"] = 3670016] = "StructuredType"; + TypeFlags2[TypeFlags2["TypeVariable"] = 8650752] = "TypeVariable"; + TypeFlags2[TypeFlags2["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive"; + TypeFlags2[TypeFlags2["InstantiablePrimitive"] = 406847488] = "InstantiablePrimitive"; + TypeFlags2[TypeFlags2["Instantiable"] = 465829888] = "Instantiable"; + TypeFlags2[TypeFlags2["StructuredOrInstantiable"] = 469499904] = "StructuredOrInstantiable"; + TypeFlags2[TypeFlags2["ObjectFlagsType"] = 3899393] = "ObjectFlagsType"; + TypeFlags2[TypeFlags2["Simplifiable"] = 25165824] = "Simplifiable"; + TypeFlags2[TypeFlags2["Singleton"] = 67358815] = "Singleton"; + TypeFlags2[TypeFlags2["Narrowable"] = 536624127] = "Narrowable"; + TypeFlags2[TypeFlags2["IncludesMask"] = 473694207] = "IncludesMask"; + TypeFlags2[TypeFlags2["IncludesMissingType"] = 262144 /* TypeParameter */] = "IncludesMissingType"; + TypeFlags2[TypeFlags2["IncludesNonWideningType"] = 4194304 /* Index */] = "IncludesNonWideningType"; + TypeFlags2[TypeFlags2["IncludesWildcard"] = 8388608 /* IndexedAccess */] = "IncludesWildcard"; + TypeFlags2[TypeFlags2["IncludesEmptyObject"] = 16777216 /* Conditional */] = "IncludesEmptyObject"; + TypeFlags2[TypeFlags2["IncludesInstantiable"] = 33554432 /* Substitution */] = "IncludesInstantiable"; + TypeFlags2[TypeFlags2["IncludesConstrainedTypeVariable"] = 536870912 /* Reserved1 */] = "IncludesConstrainedTypeVariable"; + TypeFlags2[TypeFlags2["IncludesError"] = 1073741824 /* Reserved2 */] = "IncludesError"; + TypeFlags2[TypeFlags2["NotPrimitiveUnion"] = 36323331] = "NotPrimitiveUnion"; + return TypeFlags2; +})(TypeFlags || {}); +var ObjectFlags = /* @__PURE__ */ ((ObjectFlags3) => { + ObjectFlags3[ObjectFlags3["None"] = 0] = "None"; + ObjectFlags3[ObjectFlags3["Class"] = 1] = "Class"; + ObjectFlags3[ObjectFlags3["Interface"] = 2] = "Interface"; + ObjectFlags3[ObjectFlags3["Reference"] = 4] = "Reference"; + ObjectFlags3[ObjectFlags3["Tuple"] = 8] = "Tuple"; + ObjectFlags3[ObjectFlags3["Anonymous"] = 16] = "Anonymous"; + ObjectFlags3[ObjectFlags3["Mapped"] = 32] = "Mapped"; + ObjectFlags3[ObjectFlags3["Instantiated"] = 64] = "Instantiated"; + ObjectFlags3[ObjectFlags3["ObjectLiteral"] = 128] = "ObjectLiteral"; + ObjectFlags3[ObjectFlags3["EvolvingArray"] = 256] = "EvolvingArray"; + ObjectFlags3[ObjectFlags3["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; + ObjectFlags3[ObjectFlags3["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags3[ObjectFlags3["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags3[ObjectFlags3["JSLiteral"] = 4096] = "JSLiteral"; + ObjectFlags3[ObjectFlags3["FreshLiteral"] = 8192] = "FreshLiteral"; + ObjectFlags3[ObjectFlags3["ArrayLiteral"] = 16384] = "ArrayLiteral"; + ObjectFlags3[ObjectFlags3["PrimitiveUnion"] = 32768] = "PrimitiveUnion"; + ObjectFlags3[ObjectFlags3["ContainsWideningType"] = 65536] = "ContainsWideningType"; + ObjectFlags3[ObjectFlags3["ContainsObjectOrArrayLiteral"] = 131072] = "ContainsObjectOrArrayLiteral"; + ObjectFlags3[ObjectFlags3["NonInferrableType"] = 262144] = "NonInferrableType"; + ObjectFlags3[ObjectFlags3["CouldContainTypeVariablesComputed"] = 524288] = "CouldContainTypeVariablesComputed"; + ObjectFlags3[ObjectFlags3["CouldContainTypeVariables"] = 1048576] = "CouldContainTypeVariables"; + ObjectFlags3[ObjectFlags3["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags3[ObjectFlags3["RequiresWidening"] = 196608] = "RequiresWidening"; + ObjectFlags3[ObjectFlags3["PropagatingFlags"] = 458752] = "PropagatingFlags"; + ObjectFlags3[ObjectFlags3["InstantiatedMapped"] = 96] = "InstantiatedMapped"; + ObjectFlags3[ObjectFlags3["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + ObjectFlags3[ObjectFlags3["ContainsSpread"] = 2097152] = "ContainsSpread"; + ObjectFlags3[ObjectFlags3["ObjectRestType"] = 4194304] = "ObjectRestType"; + ObjectFlags3[ObjectFlags3["InstantiationExpressionType"] = 8388608] = "InstantiationExpressionType"; + ObjectFlags3[ObjectFlags3["SingleSignatureType"] = 134217728] = "SingleSignatureType"; + ObjectFlags3[ObjectFlags3["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + ObjectFlags3[ObjectFlags3["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; + ObjectFlags3[ObjectFlags3["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + ObjectFlags3[ObjectFlags3["IsGenericTypeComputed"] = 2097152] = "IsGenericTypeComputed"; + ObjectFlags3[ObjectFlags3["IsGenericObjectType"] = 4194304] = "IsGenericObjectType"; + ObjectFlags3[ObjectFlags3["IsGenericIndexType"] = 8388608] = "IsGenericIndexType"; + ObjectFlags3[ObjectFlags3["IsGenericType"] = 12582912] = "IsGenericType"; + ObjectFlags3[ObjectFlags3["ContainsIntersections"] = 16777216] = "ContainsIntersections"; + ObjectFlags3[ObjectFlags3["IsUnknownLikeUnionComputed"] = 33554432] = "IsUnknownLikeUnionComputed"; + ObjectFlags3[ObjectFlags3["IsUnknownLikeUnion"] = 67108864] = "IsUnknownLikeUnion"; + ObjectFlags3[ObjectFlags3["IsNeverIntersectionComputed"] = 16777216] = "IsNeverIntersectionComputed"; + ObjectFlags3[ObjectFlags3["IsNeverIntersection"] = 33554432] = "IsNeverIntersection"; + ObjectFlags3[ObjectFlags3["IsConstrainedTypeVariable"] = 67108864] = "IsConstrainedTypeVariable"; + return ObjectFlags3; +})(ObjectFlags || {}); +var SignatureFlags = /* @__PURE__ */ ((SignatureFlags4) => { + SignatureFlags4[SignatureFlags4["None"] = 0] = "None"; + SignatureFlags4[SignatureFlags4["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags4[SignatureFlags4["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags4[SignatureFlags4["Abstract"] = 4] = "Abstract"; + SignatureFlags4[SignatureFlags4["IsInnerCallChain"] = 8] = "IsInnerCallChain"; + SignatureFlags4[SignatureFlags4["IsOuterCallChain"] = 16] = "IsOuterCallChain"; + SignatureFlags4[SignatureFlags4["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile"; + SignatureFlags4[SignatureFlags4["IsNonInferrable"] = 64] = "IsNonInferrable"; + SignatureFlags4[SignatureFlags4["IsSignatureCandidateForOverloadFailure"] = 128] = "IsSignatureCandidateForOverloadFailure"; + SignatureFlags4[SignatureFlags4["PropagatingFlags"] = 167] = "PropagatingFlags"; + SignatureFlags4[SignatureFlags4["CallChainFlags"] = 24] = "CallChainFlags"; + return SignatureFlags4; +})(SignatureFlags || {}); +var DiagnosticCategory = /* @__PURE__ */ ((DiagnosticCategory2) => { + DiagnosticCategory2[DiagnosticCategory2["Warning"] = 0] = "Warning"; + DiagnosticCategory2[DiagnosticCategory2["Error"] = 1] = "Error"; + DiagnosticCategory2[DiagnosticCategory2["Suggestion"] = 2] = "Suggestion"; + DiagnosticCategory2[DiagnosticCategory2["Message"] = 3] = "Message"; + return DiagnosticCategory2; +})(DiagnosticCategory || {}); +function diagnosticCategoryName(d, lowerCase = true) { + const name = DiagnosticCategory[d.category]; + return lowerCase ? name.toLowerCase() : name; +} +var ModuleResolutionKind = /* @__PURE__ */ ((ModuleResolutionKind2) => { + ModuleResolutionKind2[ModuleResolutionKind2["Classic"] = 1] = "Classic"; + ModuleResolutionKind2[ModuleResolutionKind2["NodeJs"] = 2] = "NodeJs"; + ModuleResolutionKind2[ModuleResolutionKind2["Node10"] = 2] = "Node10"; + ModuleResolutionKind2[ModuleResolutionKind2["Node16"] = 3] = "Node16"; + ModuleResolutionKind2[ModuleResolutionKind2["NodeNext"] = 99] = "NodeNext"; + ModuleResolutionKind2[ModuleResolutionKind2["Bundler"] = 100] = "Bundler"; + return ModuleResolutionKind2; +})(ModuleResolutionKind || {}); +var ModuleKind = /* @__PURE__ */ ((ModuleKind2) => { + ModuleKind2[ModuleKind2["None"] = 0] = "None"; + ModuleKind2[ModuleKind2["CommonJS"] = 1] = "CommonJS"; + ModuleKind2[ModuleKind2["AMD"] = 2] = "AMD"; + ModuleKind2[ModuleKind2["UMD"] = 3] = "UMD"; + ModuleKind2[ModuleKind2["System"] = 4] = "System"; + ModuleKind2[ModuleKind2["ES2015"] = 5] = "ES2015"; + ModuleKind2[ModuleKind2["ES2020"] = 6] = "ES2020"; + ModuleKind2[ModuleKind2["ES2022"] = 7] = "ES2022"; + ModuleKind2[ModuleKind2["ESNext"] = 99] = "ESNext"; + ModuleKind2[ModuleKind2["Node16"] = 100] = "Node16"; + ModuleKind2[ModuleKind2["Node18"] = 101] = "Node18"; + ModuleKind2[ModuleKind2["NodeNext"] = 199] = "NodeNext"; + ModuleKind2[ModuleKind2["Preserve"] = 200] = "Preserve"; + return ModuleKind2; +})(ModuleKind || {}); +var ScriptKind = /* @__PURE__ */ ((ScriptKind3) => { + ScriptKind3[ScriptKind3["Unknown"] = 0] = "Unknown"; + ScriptKind3[ScriptKind3["JS"] = 1] = "JS"; + ScriptKind3[ScriptKind3["JSX"] = 2] = "JSX"; + ScriptKind3[ScriptKind3["TS"] = 3] = "TS"; + ScriptKind3[ScriptKind3["TSX"] = 4] = "TSX"; + ScriptKind3[ScriptKind3["External"] = 5] = "External"; + ScriptKind3[ScriptKind3["JSON"] = 6] = "JSON"; + ScriptKind3[ScriptKind3["Deferred"] = 7] = "Deferred"; + return ScriptKind3; +})(ScriptKind || {}); +var TransformFlags = /* @__PURE__ */ ((TransformFlags3) => { + TransformFlags3[TransformFlags3["None"] = 0] = "None"; + TransformFlags3[TransformFlags3["ContainsTypeScript"] = 1] = "ContainsTypeScript"; + TransformFlags3[TransformFlags3["ContainsJsx"] = 2] = "ContainsJsx"; + TransformFlags3[TransformFlags3["ContainsESNext"] = 4] = "ContainsESNext"; + TransformFlags3[TransformFlags3["ContainsES2022"] = 8] = "ContainsES2022"; + TransformFlags3[TransformFlags3["ContainsES2021"] = 16] = "ContainsES2021"; + TransformFlags3[TransformFlags3["ContainsES2020"] = 32] = "ContainsES2020"; + TransformFlags3[TransformFlags3["ContainsES2019"] = 64] = "ContainsES2019"; + TransformFlags3[TransformFlags3["ContainsES2018"] = 128] = "ContainsES2018"; + TransformFlags3[TransformFlags3["ContainsES2017"] = 256] = "ContainsES2017"; + TransformFlags3[TransformFlags3["ContainsES2016"] = 512] = "ContainsES2016"; + TransformFlags3[TransformFlags3["ContainsES2015"] = 1024] = "ContainsES2015"; + TransformFlags3[TransformFlags3["ContainsGenerator"] = 2048] = "ContainsGenerator"; + TransformFlags3[TransformFlags3["ContainsDestructuringAssignment"] = 4096] = "ContainsDestructuringAssignment"; + TransformFlags3[TransformFlags3["ContainsTypeScriptClassSyntax"] = 8192] = "ContainsTypeScriptClassSyntax"; + TransformFlags3[TransformFlags3["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags3[TransformFlags3["ContainsRestOrSpread"] = 32768] = "ContainsRestOrSpread"; + TransformFlags3[TransformFlags3["ContainsObjectRestOrSpread"] = 65536] = "ContainsObjectRestOrSpread"; + TransformFlags3[TransformFlags3["ContainsComputedPropertyName"] = 131072] = "ContainsComputedPropertyName"; + TransformFlags3[TransformFlags3["ContainsBlockScopedBinding"] = 262144] = "ContainsBlockScopedBinding"; + TransformFlags3[TransformFlags3["ContainsBindingPattern"] = 524288] = "ContainsBindingPattern"; + TransformFlags3[TransformFlags3["ContainsYield"] = 1048576] = "ContainsYield"; + TransformFlags3[TransformFlags3["ContainsAwait"] = 2097152] = "ContainsAwait"; + TransformFlags3[TransformFlags3["ContainsHoistedDeclarationOrCompletion"] = 4194304] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags3[TransformFlags3["ContainsDynamicImport"] = 8388608] = "ContainsDynamicImport"; + TransformFlags3[TransformFlags3["ContainsClassFields"] = 16777216] = "ContainsClassFields"; + TransformFlags3[TransformFlags3["ContainsDecorators"] = 33554432] = "ContainsDecorators"; + TransformFlags3[TransformFlags3["ContainsPossibleTopLevelAwait"] = 67108864] = "ContainsPossibleTopLevelAwait"; + TransformFlags3[TransformFlags3["ContainsLexicalSuper"] = 134217728] = "ContainsLexicalSuper"; + TransformFlags3[TransformFlags3["ContainsUpdateExpressionForIdentifier"] = 268435456] = "ContainsUpdateExpressionForIdentifier"; + TransformFlags3[TransformFlags3["ContainsPrivateIdentifierInExpression"] = 536870912] = "ContainsPrivateIdentifierInExpression"; + TransformFlags3[TransformFlags3["HasComputedFlags"] = -2147483648] = "HasComputedFlags"; + TransformFlags3[TransformFlags3["AssertTypeScript"] = 1 /* ContainsTypeScript */] = "AssertTypeScript"; + TransformFlags3[TransformFlags3["AssertJsx"] = 2 /* ContainsJsx */] = "AssertJsx"; + TransformFlags3[TransformFlags3["AssertESNext"] = 4 /* ContainsESNext */] = "AssertESNext"; + TransformFlags3[TransformFlags3["AssertES2022"] = 8 /* ContainsES2022 */] = "AssertES2022"; + TransformFlags3[TransformFlags3["AssertES2021"] = 16 /* ContainsES2021 */] = "AssertES2021"; + TransformFlags3[TransformFlags3["AssertES2020"] = 32 /* ContainsES2020 */] = "AssertES2020"; + TransformFlags3[TransformFlags3["AssertES2019"] = 64 /* ContainsES2019 */] = "AssertES2019"; + TransformFlags3[TransformFlags3["AssertES2018"] = 128 /* ContainsES2018 */] = "AssertES2018"; + TransformFlags3[TransformFlags3["AssertES2017"] = 256 /* ContainsES2017 */] = "AssertES2017"; + TransformFlags3[TransformFlags3["AssertES2016"] = 512 /* ContainsES2016 */] = "AssertES2016"; + TransformFlags3[TransformFlags3["AssertES2015"] = 1024 /* ContainsES2015 */] = "AssertES2015"; + TransformFlags3[TransformFlags3["AssertGenerator"] = 2048 /* ContainsGenerator */] = "AssertGenerator"; + TransformFlags3[TransformFlags3["AssertDestructuringAssignment"] = 4096 /* ContainsDestructuringAssignment */] = "AssertDestructuringAssignment"; + TransformFlags3[TransformFlags3["OuterExpressionExcludes"] = -2147483648 /* HasComputedFlags */] = "OuterExpressionExcludes"; + TransformFlags3[TransformFlags3["PropertyAccessExcludes"] = -2147483648 /* OuterExpressionExcludes */] = "PropertyAccessExcludes"; + TransformFlags3[TransformFlags3["NodeExcludes"] = -2147483648 /* PropertyAccessExcludes */] = "NodeExcludes"; + TransformFlags3[TransformFlags3["ArrowFunctionExcludes"] = -2072174592] = "ArrowFunctionExcludes"; + TransformFlags3[TransformFlags3["FunctionExcludes"] = -1937940480] = "FunctionExcludes"; + TransformFlags3[TransformFlags3["ConstructorExcludes"] = -1937948672] = "ConstructorExcludes"; + TransformFlags3[TransformFlags3["MethodOrAccessorExcludes"] = -2005057536] = "MethodOrAccessorExcludes"; + TransformFlags3[TransformFlags3["PropertyExcludes"] = -2013249536] = "PropertyExcludes"; + TransformFlags3[TransformFlags3["ClassExcludes"] = -2147344384] = "ClassExcludes"; + TransformFlags3[TransformFlags3["ModuleExcludes"] = -1941676032] = "ModuleExcludes"; + TransformFlags3[TransformFlags3["TypeExcludes"] = -2] = "TypeExcludes"; + TransformFlags3[TransformFlags3["ObjectLiteralExcludes"] = -2147278848] = "ObjectLiteralExcludes"; + TransformFlags3[TransformFlags3["ArrayLiteralOrCallOrNewExcludes"] = -2147450880] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags3[TransformFlags3["VariableDeclarationListExcludes"] = -2146893824] = "VariableDeclarationListExcludes"; + TransformFlags3[TransformFlags3["ParameterExcludes"] = -2147483648 /* NodeExcludes */] = "ParameterExcludes"; + TransformFlags3[TransformFlags3["CatchClauseExcludes"] = -2147418112] = "CatchClauseExcludes"; + TransformFlags3[TransformFlags3["BindingPatternExcludes"] = -2147450880] = "BindingPatternExcludes"; + TransformFlags3[TransformFlags3["ContainsLexicalThisOrSuper"] = 134234112] = "ContainsLexicalThisOrSuper"; + TransformFlags3[TransformFlags3["PropertyNamePropagatingFlags"] = 134234112] = "PropertyNamePropagatingFlags"; + return TransformFlags3; +})(TransformFlags || {}); +var SnippetKind = /* @__PURE__ */ ((SnippetKind3) => { + SnippetKind3[SnippetKind3["TabStop"] = 0] = "TabStop"; + SnippetKind3[SnippetKind3["Placeholder"] = 1] = "Placeholder"; + SnippetKind3[SnippetKind3["Choice"] = 2] = "Choice"; + SnippetKind3[SnippetKind3["Variable"] = 3] = "Variable"; + return SnippetKind3; +})(SnippetKind || {}); +var EmitFlags = /* @__PURE__ */ ((EmitFlags3) => { + EmitFlags3[EmitFlags3["None"] = 0] = "None"; + EmitFlags3[EmitFlags3["SingleLine"] = 1] = "SingleLine"; + EmitFlags3[EmitFlags3["MultiLine"] = 2] = "MultiLine"; + EmitFlags3[EmitFlags3["AdviseOnEmitNode"] = 4] = "AdviseOnEmitNode"; + EmitFlags3[EmitFlags3["NoSubstitution"] = 8] = "NoSubstitution"; + EmitFlags3[EmitFlags3["CapturesThis"] = 16] = "CapturesThis"; + EmitFlags3[EmitFlags3["NoLeadingSourceMap"] = 32] = "NoLeadingSourceMap"; + EmitFlags3[EmitFlags3["NoTrailingSourceMap"] = 64] = "NoTrailingSourceMap"; + EmitFlags3[EmitFlags3["NoSourceMap"] = 96] = "NoSourceMap"; + EmitFlags3[EmitFlags3["NoNestedSourceMaps"] = 128] = "NoNestedSourceMaps"; + EmitFlags3[EmitFlags3["NoTokenLeadingSourceMaps"] = 256] = "NoTokenLeadingSourceMaps"; + EmitFlags3[EmitFlags3["NoTokenTrailingSourceMaps"] = 512] = "NoTokenTrailingSourceMaps"; + EmitFlags3[EmitFlags3["NoTokenSourceMaps"] = 768] = "NoTokenSourceMaps"; + EmitFlags3[EmitFlags3["NoLeadingComments"] = 1024] = "NoLeadingComments"; + EmitFlags3[EmitFlags3["NoTrailingComments"] = 2048] = "NoTrailingComments"; + EmitFlags3[EmitFlags3["NoComments"] = 3072] = "NoComments"; + EmitFlags3[EmitFlags3["NoNestedComments"] = 4096] = "NoNestedComments"; + EmitFlags3[EmitFlags3["HelperName"] = 8192] = "HelperName"; + EmitFlags3[EmitFlags3["ExportName"] = 16384] = "ExportName"; + EmitFlags3[EmitFlags3["LocalName"] = 32768] = "LocalName"; + EmitFlags3[EmitFlags3["InternalName"] = 65536] = "InternalName"; + EmitFlags3[EmitFlags3["Indented"] = 131072] = "Indented"; + EmitFlags3[EmitFlags3["NoIndentation"] = 262144] = "NoIndentation"; + EmitFlags3[EmitFlags3["AsyncFunctionBody"] = 524288] = "AsyncFunctionBody"; + EmitFlags3[EmitFlags3["ReuseTempVariableScope"] = 1048576] = "ReuseTempVariableScope"; + EmitFlags3[EmitFlags3["CustomPrologue"] = 2097152] = "CustomPrologue"; + EmitFlags3[EmitFlags3["NoHoisting"] = 4194304] = "NoHoisting"; + EmitFlags3[EmitFlags3["Iterator"] = 8388608] = "Iterator"; + EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + return EmitFlags3; +})(EmitFlags || {}); +var LanguageFeatureMinimumTarget = { + Classes: 2 /* ES2015 */, + ForOf: 2 /* ES2015 */, + Generators: 2 /* ES2015 */, + Iteration: 2 /* ES2015 */, + SpreadElements: 2 /* ES2015 */, + RestElements: 2 /* ES2015 */, + TaggedTemplates: 2 /* ES2015 */, + DestructuringAssignment: 2 /* ES2015 */, + BindingPatterns: 2 /* ES2015 */, + ArrowFunctions: 2 /* ES2015 */, + BlockScopedVariables: 2 /* ES2015 */, + ObjectAssign: 2 /* ES2015 */, + RegularExpressionFlagsUnicode: 2 /* ES2015 */, + RegularExpressionFlagsSticky: 2 /* ES2015 */, + Exponentiation: 3 /* ES2016 */, + AsyncFunctions: 4 /* ES2017 */, + ForAwaitOf: 5 /* ES2018 */, + AsyncGenerators: 5 /* ES2018 */, + AsyncIteration: 5 /* ES2018 */, + ObjectSpreadRest: 5 /* ES2018 */, + RegularExpressionFlagsDotAll: 5 /* ES2018 */, + BindinglessCatch: 6 /* ES2019 */, + BigInt: 7 /* ES2020 */, + NullishCoalesce: 7 /* ES2020 */, + OptionalChaining: 7 /* ES2020 */, + LogicalAssignment: 8 /* ES2021 */, + TopLevelAwait: 9 /* ES2022 */, + ClassFields: 9 /* ES2022 */, + PrivateNamesAndClassStaticBlocks: 9 /* ES2022 */, + RegularExpressionFlagsHasIndices: 9 /* ES2022 */, + ShebangComments: 10 /* ES2023 */, + RegularExpressionFlagsUnicodeSets: 11 /* ES2024 */, + UsingAndAwaitUsing: 99 /* ESNext */, + ClassAndClassElementDecorators: 99 /* ESNext */ +}; +var commentPragmas = { + "reference": { + args: [ + { name: "types", optional: true, captureSpan: true }, + { name: "lib", optional: true, captureSpan: true }, + { name: "path", optional: true, captureSpan: true }, + { name: "no-default-lib", optional: true }, + { name: "resolution-mode", optional: true }, + { name: "preserve", optional: true } + ], + kind: 1 /* TripleSlashXML */ + }, + "amd-dependency": { + args: [{ name: "path" }, { name: "name", optional: true }], + kind: 1 /* TripleSlashXML */ + }, + "amd-module": { + args: [{ name: "name" }], + kind: 1 /* TripleSlashXML */ + }, + "ts-check": { + kind: 2 /* SingleLine */ + }, + "ts-nocheck": { + kind: 2 /* SingleLine */ + }, + "jsx": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + "jsxfrag": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + "jsximportsource": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + }, + "jsxruntime": { + args: [{ name: "factory" }], + kind: 4 /* MultiLine */ + } +}; + +// src/compiler/sys.ts +function generateDjb2Hash(data) { + let acc = 5381; + for (let i = 0; i < data.length; i++) { + acc = (acc << 5) + acc + data.charCodeAt(i); + } + return acc.toString(); +} +var PollingInterval = /* @__PURE__ */ ((PollingInterval3) => { + PollingInterval3[PollingInterval3["High"] = 2e3] = "High"; + PollingInterval3[PollingInterval3["Medium"] = 500] = "Medium"; + PollingInterval3[PollingInterval3["Low"] = 250] = "Low"; + return PollingInterval3; +})(PollingInterval || {}); +var missingFileModifiedTime = /* @__PURE__ */ new Date(0); +function getModifiedTime(host, fileName) { + return host.getModifiedTime(fileName) || missingFileModifiedTime; +} +function createPollingIntervalBasedLevels(levels) { + return { + [250 /* Low */]: levels.Low, + [500 /* Medium */]: levels.Medium, + [2e3 /* High */]: levels.High + }; +} +var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; +var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); +var unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); +function setCustomPollingValues(system) { + if (!system.getEnvironmentVariable) { + return; + } + const pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval); + pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; + unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || unchangedPollThresholds; + function getLevel(envVar, level) { + return system.getEnvironmentVariable(`${envVar}_${level.toUpperCase()}`); + } + function getCustomLevels(baseVariable) { + let customLevels; + setCustomLevel("Low"); + setCustomLevel("Medium"); + setCustomLevel("High"); + return customLevels; + function setCustomLevel(level) { + const customLevel = getLevel(baseVariable, level); + if (customLevel) { + (customLevels || (customLevels = {}))[level] = Number(customLevel); + } + } + } + function setCustomLevels(baseVariable, levels) { + const customLevels = getCustomLevels(baseVariable); + if (customLevels) { + setLevel("Low"); + setLevel("Medium"); + setLevel("High"); + return true; + } + return false; + function setLevel(level) { + levels[level] = customLevels[level] || levels[level]; + } + } + function getCustomPollingBasedLevels(baseVariable, defaultLevels) { + const customLevels = getCustomLevels(baseVariable); + return (pollingIntervalChanged || customLevels) && createPollingIntervalBasedLevels(customLevels ? { ...defaultLevels, ...customLevels } : defaultLevels); + } +} +function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) { + let definedValueCopyToIndex = pollIndex; + for (let canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) { + const watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } else if (watchedFile.isClosed) { + queue[pollIndex] = void 0; + continue; + } + chunkSize--; + const fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName)); + if (watchedFile.isClosed) { + queue[pollIndex] = void 0; + continue; + } + callbackOnWatchFileStat == null ? void 0 : callbackOnWatchFileStat(watchedFile, pollIndex, fileChanged); + if (queue[pollIndex]) { + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = void 0; + } + definedValueCopyToIndex++; + } + } + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } +} +function createDynamicPriorityPollingWatchFile(host) { + const watchedFiles = []; + const changedFilesInLastPoll = []; + const lowPollingIntervalQueue = createPollingIntervalQueue(250 /* Low */); + const mediumPollingIntervalQueue = createPollingIntervalQueue(500 /* Medium */); + const highPollingIntervalQueue = createPollingIntervalQueue(2e3 /* High */); + return watchFile2; + function watchFile2(fileName, callback, defaultPollingInterval) { + const file = { + fileName, + callback, + unchangedPolls: 0, + mtime: getModifiedTime(host, fileName) + }; + watchedFiles.push(file); + addToPollingIntervalQueue(file, defaultPollingInterval); + return { + close: () => { + file.isClosed = true; + unorderedRemoveItem(watchedFiles, file); + } + }; + } + function createPollingIntervalQueue(pollingInterval) { + const queue = []; + queue.pollingInterval = pollingInterval; + queue.pollIndex = 0; + queue.pollScheduled = false; + return queue; + } + function pollPollingIntervalQueue(_timeoutType, queue) { + queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]); + if (queue.length) { + scheduleNextPoll(queue.pollingInterval); + } else { + Debug.assert(queue.pollIndex === 0); + queue.pollScheduled = false; + } + } + function pollLowPollingIntervalQueue(_timeoutType, queue) { + pollQueue( + changedFilesInLastPoll, + 250 /* Low */, + /*pollIndex*/ + 0, + changedFilesInLastPoll.length + ); + pollPollingIntervalQueue(_timeoutType, queue); + if (!queue.pollScheduled && changedFilesInLastPoll.length) { + scheduleNextPoll(250 /* Low */); + } + } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { + return pollWatchedFileQueue( + host, + queue, + pollIndex, + chunkSize, + onWatchFileStat + ); + function onWatchFileStat(watchedFile, pollIndex2, fileChanged) { + if (fileChanged) { + watchedFile.unchangedPolls = 0; + if (queue !== changedFilesInLastPoll) { + queue[pollIndex2] = void 0; + addChangedFileToLowPollingIntervalQueue(watchedFile); + } + } else if (watchedFile.unchangedPolls !== unchangedPollThresholds[pollingInterval]) { + watchedFile.unchangedPolls++; + } else if (queue === changedFilesInLastPoll) { + watchedFile.unchangedPolls = 1; + queue[pollIndex2] = void 0; + addToPollingIntervalQueue(watchedFile, 250 /* Low */); + } else if (pollingInterval !== 2e3 /* High */) { + watchedFile.unchangedPolls++; + queue[pollIndex2] = void 0; + addToPollingIntervalQueue(watchedFile, pollingInterval === 250 /* Low */ ? 500 /* Medium */ : 2e3 /* High */); + } + } + } + function pollingIntervalQueue(pollingInterval) { + switch (pollingInterval) { + case 250 /* Low */: + return lowPollingIntervalQueue; + case 500 /* Medium */: + return mediumPollingIntervalQueue; + case 2e3 /* High */: + return highPollingIntervalQueue; + } + } + function addToPollingIntervalQueue(file, pollingInterval) { + pollingIntervalQueue(pollingInterval).push(file); + scheduleNextPollIfNotAlreadyScheduled(pollingInterval); + } + function addChangedFileToLowPollingIntervalQueue(file) { + changedFilesInLastPoll.push(file); + scheduleNextPollIfNotAlreadyScheduled(250 /* Low */); + } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { + if (!pollingIntervalQueue(pollingInterval).pollScheduled) { + scheduleNextPoll(pollingInterval); + } + } + function scheduleNextPoll(pollingInterval) { + pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === 250 /* Low */ ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingInterval === 250 /* Low */ ? "pollLowPollingIntervalQueue" : "pollPollingIntervalQueue", pollingIntervalQueue(pollingInterval)); + } +} +function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2, getModifiedTime3, fsWatchWithTimestamp) { + const fileWatcherCallbacks = createMultiMap(); + const fileTimestamps = fsWatchWithTimestamp ? /* @__PURE__ */ new Map() : void 0; + const dirWatchers = /* @__PURE__ */ new Map(); + const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + return nonPollingWatchFile; + function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) { + const filePath = toCanonicalName(fileName); + if (fileWatcherCallbacks.add(filePath, callback).length === 1 && fileTimestamps) { + fileTimestamps.set(filePath, getModifiedTime3(fileName) || missingFileModifiedTime); + } + const dirPath = getDirectoryPath(filePath) || "."; + const watcher = dirWatchers.get(dirPath) || createDirectoryWatcher(getDirectoryPath(fileName) || ".", dirPath, fallbackOptions); + watcher.referenceCount++; + return { + close: () => { + if (watcher.referenceCount === 1) { + watcher.close(); + dirWatchers.delete(dirPath); + } else { + watcher.referenceCount--; + } + fileWatcherCallbacks.remove(filePath, callback); + } + }; + } + function createDirectoryWatcher(dirName, dirPath, fallbackOptions) { + const watcher = fsWatch( + dirName, + 1 /* Directory */, + (eventName, relativeFileName) => { + if (!isString(relativeFileName)) return; + const fileName = getNormalizedAbsolutePath(relativeFileName, dirName); + const filePath = toCanonicalName(fileName); + const callbacks = fileName && fileWatcherCallbacks.get(filePath); + if (callbacks) { + let currentModifiedTime; + let eventKind = 1 /* Changed */; + if (fileTimestamps) { + const existingTime = fileTimestamps.get(filePath); + if (eventName === "change") { + currentModifiedTime = getModifiedTime3(fileName) || missingFileModifiedTime; + if (currentModifiedTime.getTime() === existingTime.getTime()) return; + } + currentModifiedTime || (currentModifiedTime = getModifiedTime3(fileName) || missingFileModifiedTime); + fileTimestamps.set(filePath, currentModifiedTime); + if (existingTime === missingFileModifiedTime) eventKind = 0 /* Created */; + else if (currentModifiedTime === missingFileModifiedTime) eventKind = 2 /* Deleted */; + } + for (const fileCallback of callbacks) { + fileCallback(fileName, eventKind, currentModifiedTime); + } + } + }, + /*recursive*/ + false, + 500 /* Medium */, + fallbackOptions + ); + watcher.referenceCount = 0; + dirWatchers.set(dirPath, watcher); + return watcher; + } +} +function createFixedChunkSizePollingWatchFile(host) { + const watchedFiles = []; + let pollIndex = 0; + let pollScheduled; + return watchFile2; + function watchFile2(fileName, callback) { + const file = { + fileName, + callback, + mtime: getModifiedTime(host, fileName) + }; + watchedFiles.push(file); + scheduleNextPoll(); + return { + close: () => { + file.isClosed = true; + unorderedRemoveItem(watchedFiles, file); + } + }; + } + function pollQueue() { + pollScheduled = void 0; + pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[250 /* Low */]); + scheduleNextPoll(); + } + function scheduleNextPoll() { + if (!watchedFiles.length || pollScheduled) return; + pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */, "pollQueue"); + } +} +function createSingleWatcherPerName(cache, useCaseSensitiveFileNames2, name, callback, createWatcher) { + const toCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + const path = toCanonicalFileName(name); + const existing = cache.get(path); + if (existing) { + existing.callbacks.push(callback); + } else { + cache.set(path, { + watcher: createWatcher( + // Cant infer types correctly so lets satisfy checker + (param1, param2, param3) => { + var _a; + return (_a = cache.get(path)) == null ? void 0 : _a.callbacks.slice().forEach((cb) => cb(param1, param2, param3)); + } + ), + callbacks: [callback] + }); + } + return { + close: () => { + const watcher = cache.get(path); + if (!watcher) return; + if (!orderedRemoveItem(watcher.callbacks, callback) || watcher.callbacks.length) return; + cache.delete(path); + closeFileWatcherOf(watcher); + } + }; +} +function onWatchedFileStat(watchedFile, modifiedTime) { + const oldTime = watchedFile.mtime.getTime(); + const newTime = modifiedTime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = modifiedTime; + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime), modifiedTime); + return true; + } + return false; +} +function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 ? 0 /* Created */ : newTime === 0 ? 2 /* Deleted */ : 1 /* Changed */; +} +var ignoredPaths = ["/node_modules/.", "/.git", "/.#"]; +var curSysLog = noop; +function sysLog(s) { + return curSysLog(s); +} +function setSysLog(logger) { + curSysLog = logger; +} +function createDirectoryWatcherSupportingRecursive({ + watchDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + getCurrentDirectory, + getAccessibleSortedChildDirectories, + fileSystemEntryExists, + realpath, + setTimeout: setTimeout2, + clearTimeout: clearTimeout2 +}) { + const cache = /* @__PURE__ */ new Map(); + const callbackCache = createMultiMap(); + const cacheToUpdateChildWatches = /* @__PURE__ */ new Map(); + let timerToUpdateChildWatches; + const filePathComparer = getStringComparer(!useCaseSensitiveFileNames2); + const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames2); + return (dirName, callback, recursive, options) => recursive ? createDirectoryWatcher(dirName, options, callback) : watchDirectory(dirName, callback, recursive, options); + function createDirectoryWatcher(dirName, options, callback, link) { + const dirPath = toCanonicalFilePath(dirName); + let directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } else { + directoryWatcher = { + watcher: watchDirectory( + dirName, + (fileName) => { + var _a; + if (isIgnoredPath(fileName, options)) return; + if (options == null ? void 0 : options.synchronousWatchDirectory) { + if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) invokeCallbacks(dirName, dirPath, fileName); + updateChildWatches(dirName, dirPath, options); + } else { + nonSyncUpdateChildWatches(dirName, dirPath, fileName, options); + } + }, + /*recursive*/ + false, + options + ), + refCount: 1, + childWatches: emptyArray, + targetWatcher: void 0, + links: void 0 + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath, options); + } + if (link) (directoryWatcher.links ?? (directoryWatcher.links = /* @__PURE__ */ new Set())).add(link); + const callbackToAdd = callback && { dirName, callback }; + if (callbackToAdd) { + callbackCache.add(dirPath, callbackToAdd); + } + return { + dirName, + close: () => { + var _a; + const directoryWatcher2 = Debug.checkDefined(cache.get(dirPath)); + if (callbackToAdd) callbackCache.remove(dirPath, callbackToAdd); + if (link) (_a = directoryWatcher2.links) == null ? void 0 : _a.delete(link); + directoryWatcher2.refCount--; + if (directoryWatcher2.refCount) return; + cache.delete(dirPath); + directoryWatcher2.links = void 0; + closeFileWatcherOf(directoryWatcher2); + closeTargetWatcher(directoryWatcher2); + directoryWatcher2.childWatches.forEach(closeFileWatcher); + } + }; + } + function invokeCallbacks(dirName, dirPath, fileNameOrInvokeMap, fileNames) { + var _a, _b; + let fileName; + let invokeMap; + if (isString(fileNameOrInvokeMap)) { + fileName = fileNameOrInvokeMap; + } else { + invokeMap = fileNameOrInvokeMap; + } + callbackCache.forEach((callbacks, rootDirName) => { + if (invokeMap && invokeMap.get(rootDirName) === true) return; + if (rootDirName === dirPath || startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === directorySeparator) { + if (invokeMap) { + if (fileNames) { + const existing = invokeMap.get(rootDirName); + if (existing) { + existing.push(...fileNames); + } else { + invokeMap.set(rootDirName, fileNames.slice()); + } + } else { + invokeMap.set(rootDirName, true); + } + } else { + callbacks.forEach(({ callback }) => callback(fileName)); + } + } + }); + (_b = (_a = cache.get(dirPath)) == null ? void 0 : _a.links) == null ? void 0 : _b.forEach((link) => { + const toPathInLink = (fileName2) => combinePaths(link, getRelativePathFromDirectory(dirName, fileName2, toCanonicalFilePath)); + if (invokeMap) { + invokeCallbacks(link, toCanonicalFilePath(link), invokeMap, fileNames == null ? void 0 : fileNames.map(toPathInLink)); + } else { + invokeCallbacks(link, toCanonicalFilePath(link), toPathInLink(fileName)); + } + }); + } + function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) { + const parentWatcher = cache.get(dirPath); + if (parentWatcher && fileSystemEntryExists(dirName, 1 /* Directory */)) { + scheduleUpdateChildWatches(dirName, dirPath, fileName, options); + return; + } + invokeCallbacks(dirName, dirPath, fileName); + closeTargetWatcher(parentWatcher); + removeChildWatches(parentWatcher); + } + function scheduleUpdateChildWatches(dirName, dirPath, fileName, options) { + const existing = cacheToUpdateChildWatches.get(dirPath); + if (existing) { + existing.fileNames.push(fileName); + } else { + cacheToUpdateChildWatches.set(dirPath, { dirName, options, fileNames: [fileName] }); + } + if (timerToUpdateChildWatches) { + clearTimeout2(timerToUpdateChildWatches); + timerToUpdateChildWatches = void 0; + } + timerToUpdateChildWatches = setTimeout2(onTimerToUpdateChildWatches, 1e3, "timerToUpdateChildWatches"); + } + function onTimerToUpdateChildWatches() { + var _a; + timerToUpdateChildWatches = void 0; + sysLog(`sysLog:: onTimerToUpdateChildWatches:: ${cacheToUpdateChildWatches.size}`); + const start = timestamp(); + const invokeMap = /* @__PURE__ */ new Map(); + while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) { + const result = cacheToUpdateChildWatches.entries().next(); + Debug.assert(!result.done); + const { value: [dirPath, { dirName, options, fileNames }] } = result; + cacheToUpdateChildWatches.delete(dirPath); + const hasChanges = updateChildWatches(dirName, dirPath, options); + if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) invokeCallbacks(dirName, dirPath, invokeMap, hasChanges ? void 0 : fileNames); + } + sysLog(`sysLog:: invokingWatchers:: Elapsed:: ${timestamp() - start}ms:: ${cacheToUpdateChildWatches.size}`); + callbackCache.forEach((callbacks, rootDirName) => { + const existing = invokeMap.get(rootDirName); + if (existing) { + callbacks.forEach(({ callback, dirName }) => { + if (isArray(existing)) { + existing.forEach(callback); + } else { + callback(dirName); + } + }); + } + }); + const elapsed = timestamp() - start; + sysLog(`sysLog:: Elapsed:: ${elapsed}ms:: onTimerToUpdateChildWatches:: ${cacheToUpdateChildWatches.size} ${timerToUpdateChildWatches}`); + } + function removeChildWatches(parentWatcher) { + if (!parentWatcher) return; + const existingChildWatches = parentWatcher.childWatches; + parentWatcher.childWatches = emptyArray; + for (const childWatcher of existingChildWatches) { + childWatcher.close(); + removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName))); + } + } + function closeTargetWatcher(watcher) { + if (watcher == null ? void 0 : watcher.targetWatcher) { + watcher.targetWatcher.close(); + watcher.targetWatcher = void 0; + } + } + function updateChildWatches(parentDir, parentDirPath, options) { + const parentWatcher = cache.get(parentDirPath); + if (!parentWatcher) return false; + const target = normalizePath(realpath(parentDir)); + let hasChanges; + let newChildWatches; + if (filePathComparer(target, parentDir) === 0 /* EqualTo */) { + hasChanges = enumerateInsertsAndDeletes( + fileSystemEntryExists(parentDir, 1 /* Directory */) ? mapDefined(getAccessibleSortedChildDirectories(parentDir), (child) => { + const childFullName = getNormalizedAbsolutePath(child, parentDir); + return !isIgnoredPath(childFullName, options) && filePathComparer(childFullName, normalizePath(realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : void 0; + }) : emptyArray, + parentWatcher.childWatches, + (child, childWatcher) => filePathComparer(child, childWatcher.dirName), + createAndAddChildDirectoryWatcher, + closeFileWatcher, + addChildDirectoryWatcher + ); + } else if (parentWatcher.targetWatcher && filePathComparer(target, parentWatcher.targetWatcher.dirName) === 0 /* EqualTo */) { + hasChanges = false; + Debug.assert(parentWatcher.childWatches === emptyArray); + } else { + closeTargetWatcher(parentWatcher); + parentWatcher.targetWatcher = createDirectoryWatcher( + target, + options, + /*callback*/ + void 0, + parentDir + ); + parentWatcher.childWatches.forEach(closeFileWatcher); + hasChanges = true; + } + parentWatcher.childWatches = newChildWatches || emptyArray; + return hasChanges; + function createAndAddChildDirectoryWatcher(childName) { + const result = createDirectoryWatcher(childName, options); + addChildDirectoryWatcher(result); + } + function addChildDirectoryWatcher(childWatcher) { + (newChildWatches || (newChildWatches = [])).push(childWatcher); + } + } + function isIgnoredPath(path, options) { + return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); + } + function isInPath(path, searchPath) { + if (path.includes(searchPath)) return true; + if (useCaseSensitiveFileNames2) return false; + return toCanonicalFilePath(path).includes(searchPath); + } +} +function createFileWatcherCallback(callback) { + return (_fileName, eventKind, modifiedTime) => callback(eventKind === 1 /* Changed */ ? "change" : "rename", "", modifiedTime); +} +function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime3) { + return (eventName, _relativeFileName, modifiedTime) => { + if (eventName === "rename") { + modifiedTime || (modifiedTime = getModifiedTime3(fileName) || missingFileModifiedTime); + callback(fileName, modifiedTime !== missingFileModifiedTime ? 0 /* Created */ : 2 /* Deleted */, modifiedTime); + } else { + callback(fileName, 1 /* Changed */, modifiedTime); + } + }; +} +function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames2, getCurrentDirectory) { + return ((options == null ? void 0 : options.excludeDirectories) || (options == null ? void 0 : options.excludeFiles)) && (matchesExclude(pathToCheck, options == null ? void 0 : options.excludeFiles, useCaseSensitiveFileNames2, getCurrentDirectory()) || matchesExclude(pathToCheck, options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2, getCurrentDirectory())); +} +function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory) { + return (eventName, relativeFileName) => { + if (eventName === "rename") { + const fileName = !relativeFileName ? directoryName : normalizePath(combinePaths(directoryName, relativeFileName)); + if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames2, getCurrentDirectory)) { + callback(fileName); + } + } + }; +} +function createSystemWatchFunctions({ + pollingWatchFileWorker, + getModifiedTime: getModifiedTime3, + setTimeout: setTimeout2, + clearTimeout: clearTimeout2, + fsWatchWorker, + fileSystemEntryExists, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + getCurrentDirectory, + fsSupportsRecursiveFsWatch, + getAccessibleSortedChildDirectories, + realpath, + tscWatchFile, + useNonPollingWatchers, + tscWatchDirectory, + inodeWatching, + fsWatchWithTimestamp, + sysLog: sysLog2 +}) { + const pollingWatches = /* @__PURE__ */ new Map(); + const fsWatches = /* @__PURE__ */ new Map(); + const fsWatchesRecursive = /* @__PURE__ */ new Map(); + let dynamicPollingWatchFile; + let fixedChunkSizePollingWatchFile; + let nonPollingWatchFile; + let hostRecursiveDirectoryWatcher; + let hitSystemWatcherLimit = false; + return { + watchFile: watchFile2, + watchDirectory + }; + function watchFile2(fileName, callback, pollingInterval, options) { + options = updateOptionsForWatchFile(options, useNonPollingWatchers); + const watchFileKind = Debug.checkDefined(options.watchFile); + switch (watchFileKind) { + case 0 /* FixedPollingInterval */: + return pollingWatchFile( + fileName, + callback, + 250 /* Low */, + /*options*/ + void 0 + ); + case 1 /* PriorityPollingInterval */: + return pollingWatchFile( + fileName, + callback, + pollingInterval, + /*options*/ + void 0 + ); + case 2 /* DynamicPriorityPolling */: + return ensureDynamicPollingWatchFile()( + fileName, + callback, + pollingInterval, + /*options*/ + void 0 + ); + case 3 /* FixedChunkSizePolling */: + return ensureFixedChunkSizePollingWatchFile()( + fileName, + callback, + /* pollingInterval */ + void 0, + /*options*/ + void 0 + ); + case 4 /* UseFsEvents */: + return fsWatch( + fileName, + 0 /* File */, + createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime3), + /*recursive*/ + false, + pollingInterval, + getFallbackOptions(options) + ); + case 5 /* UseFsEventsOnParentDirectory */: + if (!nonPollingWatchFile) { + nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2, getModifiedTime3, fsWatchWithTimestamp); + } + return nonPollingWatchFile(fileName, callback, pollingInterval, getFallbackOptions(options)); + default: + Debug.assertNever(watchFileKind); + } + } + function ensureDynamicPollingWatchFile() { + return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime3, setTimeout: setTimeout2 })); + } + function ensureFixedChunkSizePollingWatchFile() { + return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime3, setTimeout: setTimeout2 })); + } + function updateOptionsForWatchFile(options, useNonPollingWatchers2) { + if (options && options.watchFile !== void 0) return options; + switch (tscWatchFile) { + case "PriorityPollingInterval": + return { watchFile: 1 /* PriorityPollingInterval */ }; + case "DynamicPriorityPolling": + return { watchFile: 2 /* DynamicPriorityPolling */ }; + case "UseFsEvents": + return generateWatchFileOptions(4 /* UseFsEvents */, 1 /* PriorityInterval */, options); + case "UseFsEventsWithFallbackDynamicPolling": + return generateWatchFileOptions(4 /* UseFsEvents */, 2 /* DynamicPriority */, options); + case "UseFsEventsOnParentDirectory": + useNonPollingWatchers2 = true; + // fall through + default: + return useNonPollingWatchers2 ? ( + // Use notifications from FS to watch with falling back to fs.watchFile + generateWatchFileOptions(5 /* UseFsEventsOnParentDirectory */, 1 /* PriorityInterval */, options) + ) : ( + // Default to using fs events + { watchFile: 4 /* UseFsEvents */ } + ); + } + } + function generateWatchFileOptions(watchFile3, fallbackPolling, options) { + const defaultFallbackPolling = options == null ? void 0 : options.fallbackPolling; + return { + watchFile: watchFile3, + fallbackPolling: defaultFallbackPolling === void 0 ? fallbackPolling : defaultFallbackPolling + }; + } + function watchDirectory(directoryName, callback, recursive, options) { + if (fsSupportsRecursiveFsWatch) { + return fsWatch( + directoryName, + 1 /* Directory */, + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), + recursive, + 500 /* Medium */, + getFallbackOptions(options) + ); + } + if (!hostRecursiveDirectoryWatcher) { + hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + getCurrentDirectory, + fileSystemEntryExists, + getAccessibleSortedChildDirectories, + watchDirectory: nonRecursiveWatchDirectory, + realpath, + setTimeout: setTimeout2, + clearTimeout: clearTimeout2 + }); + } + return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options); + } + function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) { + Debug.assert(!recursive); + const watchDirectoryOptions = updateOptionsForWatchDirectory(options); + const watchDirectoryKind = Debug.checkDefined(watchDirectoryOptions.watchDirectory); + switch (watchDirectoryKind) { + case 1 /* FixedPollingInterval */: + return pollingWatchFile( + directoryName, + () => callback(directoryName), + 500 /* Medium */, + /*options*/ + void 0 + ); + case 2 /* DynamicPriorityPolling */: + return ensureDynamicPollingWatchFile()( + directoryName, + () => callback(directoryName), + 500 /* Medium */, + /*options*/ + void 0 + ); + case 3 /* FixedChunkSizePolling */: + return ensureFixedChunkSizePollingWatchFile()( + directoryName, + () => callback(directoryName), + /* pollingInterval */ + void 0, + /*options*/ + void 0 + ); + case 0 /* UseFsEvents */: + return fsWatch( + directoryName, + 1 /* Directory */, + createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), + recursive, + 500 /* Medium */, + getFallbackOptions(watchDirectoryOptions) + ); + default: + Debug.assertNever(watchDirectoryKind); + } + } + function updateOptionsForWatchDirectory(options) { + if (options && options.watchDirectory !== void 0) return options; + switch (tscWatchDirectory) { + case "RecursiveDirectoryUsingFsWatchFile": + return { watchDirectory: 1 /* FixedPollingInterval */ }; + case "RecursiveDirectoryUsingDynamicPriorityPolling": + return { watchDirectory: 2 /* DynamicPriorityPolling */ }; + default: + const defaultFallbackPolling = options == null ? void 0 : options.fallbackPolling; + return { + watchDirectory: 0 /* UseFsEvents */, + fallbackPolling: defaultFallbackPolling !== void 0 ? defaultFallbackPolling : void 0 + }; + } + } + function pollingWatchFile(fileName, callback, pollingInterval, options) { + return createSingleWatcherPerName( + pollingWatches, + useCaseSensitiveFileNames2, + fileName, + callback, + (cb) => pollingWatchFileWorker(fileName, cb, pollingInterval, options) + ); + } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + return createSingleWatcherPerName( + recursive ? fsWatchesRecursive : fsWatches, + useCaseSensitiveFileNames2, + fileOrDirectory, + callback, + (cb) => fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions) + ); + } + function fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + let lastDirectoryPartWithDirectorySeparator; + let lastDirectoryPart; + if (inodeWatching) { + lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substring(fileOrDirectory.lastIndexOf(directorySeparator)); + lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(directorySeparator.length); + } + let watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? watchMissingFileSystemEntry() : watchPresentFileSystemEntry(); + return { + close: () => { + if (watcher) { + watcher.close(); + watcher = void 0; + } + } + }; + function updateWatcher(createWatcher) { + if (watcher) { + sysLog2(`sysLog:: ${fileOrDirectory}:: Changing watcher to ${createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing"}FileSystemEntryWatcher`); + watcher.close(); + watcher = createWatcher(); + } + } + function watchPresentFileSystemEntry() { + if (hitSystemWatcherLimit) { + sysLog2(`sysLog:: ${fileOrDirectory}:: Defaulting to watchFile`); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + try { + const presentWatcher = (entryKind === 1 /* Directory */ || !fsWatchWithTimestamp ? fsWatchWorker : fsWatchWorkerHandlingTimestamp)( + fileOrDirectory, + recursive, + inodeWatching ? callbackChangingToMissingFileSystemEntry : callback + ); + presentWatcher.on("error", () => { + callback("rename", ""); + updateWatcher(watchMissingFileSystemEntry); + }); + return presentWatcher; + } catch (e) { + hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); + sysLog2(`sysLog:: ${fileOrDirectory}:: Changing to watchFile`); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + function callbackChangingToMissingFileSystemEntry(event, relativeName) { + let originalRelativeName; + if (relativeName && endsWith(relativeName, "~")) { + originalRelativeName = relativeName; + relativeName = relativeName.slice(0, relativeName.length - 1); + } + if (event === "rename" && (!relativeName || relativeName === lastDirectoryPart || endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { + const modifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime; + if (originalRelativeName) callback(event, originalRelativeName, modifiedTime); + callback(event, relativeName, modifiedTime); + if (inodeWatching) { + updateWatcher(modifiedTime === missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); + } else if (modifiedTime === missingFileModifiedTime) { + updateWatcher(watchMissingFileSystemEntry); + } + } else { + if (originalRelativeName) callback(event, originalRelativeName); + callback(event, relativeName); + } + } + function watchPresentFileSystemEntryWithFsWatchFile() { + return watchFile2( + fileOrDirectory, + createFileWatcherCallback(callback), + fallbackPollingInterval, + fallbackOptions + ); + } + function watchMissingFileSystemEntry() { + return watchFile2( + fileOrDirectory, + (_fileName, eventKind, modifiedTime) => { + if (eventKind === 0 /* Created */) { + modifiedTime || (modifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime); + if (modifiedTime !== missingFileModifiedTime) { + callback("rename", "", modifiedTime); + updateWatcher(watchPresentFileSystemEntry); + } + } + }, + fallbackPollingInterval, + fallbackOptions + ); + } + } + function fsWatchWorkerHandlingTimestamp(fileOrDirectory, recursive, callback) { + let modifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime; + return fsWatchWorker(fileOrDirectory, recursive, (eventName, relativeFileName, currentModifiedTime) => { + if (eventName === "change") { + currentModifiedTime || (currentModifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime); + if (currentModifiedTime.getTime() === modifiedTime.getTime()) return; + } + modifiedTime = currentModifiedTime || getModifiedTime3(fileOrDirectory) || missingFileModifiedTime; + callback(eventName, relativeFileName, modifiedTime); + }); + } +} +function patchWriteFileEnsuringDirectory(sys2) { + const originalWriteFile = sys2.writeFile; + sys2.writeFile = (path, data, writeBom) => writeFileEnsuringDirectories( + path, + data, + !!writeBom, + (path2, data2, writeByteOrderMark) => originalWriteFile.call(sys2, path2, data2, writeByteOrderMark), + (path2) => sys2.createDirectory(path2), + (path2) => sys2.directoryExists(path2) + ); +} +var sys = (() => { + const byteOrderMarkIndicator = "\uFEFF"; + function getNodeSystem() { + const nativePattern = /^native |^\([^)]+\)$|^(?:internal[\\/]|[\w\s]+(?:\.js)?$)/; + const _fs = require("fs"); + const _path = require("path"); + const _os = require("os"); + let _crypto; + try { + _crypto = require("crypto"); + } catch { + _crypto = void 0; + } + let activeSession; + let profilePath = "./profile.cpuprofile"; + const isMacOs = process.platform === "darwin"; + const isLinuxOrMacOs = process.platform === "linux" || isMacOs; + const statSyncOptions = { throwIfNoEntry: false }; + const platform = _os.platform(); + const useCaseSensitiveFileNames2 = isFileSystemCaseSensitive(); + const fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; + const executingFilePath = __filename.endsWith("sys.js") ? _path.join(_path.dirname(__dirname), "__fake__.js") : __filename; + const fsSupportsRecursiveFsWatch = process.platform === "win32" || isMacOs; + const getCurrentDirectory = memoize(() => process.cwd()); + const { watchFile: watchFile2, watchDirectory } = createSystemWatchFunctions({ + pollingWatchFileWorker: fsWatchFileWorker, + getModifiedTime: getModifiedTime3, + setTimeout, + clearTimeout, + fsWatchWorker, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + getCurrentDirectory, + fileSystemEntryExists, + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + fsSupportsRecursiveFsWatch, + getAccessibleSortedChildDirectories: (path) => getAccessibleFileSystemEntries(path).directories, + realpath, + tscWatchFile: process.env.TSC_WATCHFILE, + useNonPollingWatchers: !!process.env.TSC_NONPOLLING_WATCHER, + tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, + inodeWatching: isLinuxOrMacOs, + fsWatchWithTimestamp: isMacOs, + sysLog + }); + const nodeSystem = { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + write(s) { + process.stdout.write(s); + }, + getWidthOfTerminal() { + return process.stdout.columns; + }, + writeOutputIsTTY() { + return process.stdout.isTTY; + }, + readFile, + writeFile: writeFile2, + watchFile: watchFile2, + watchDirectory, + preferNonRecursiveWatch: !fsSupportsRecursiveFsWatch, + resolvePath: (path) => _path.resolve(path), + fileExists, + directoryExists, + getAccessibleFileSystemEntries, + createDirectory(directoryName) { + if (!nodeSystem.directoryExists(directoryName)) { + try { + _fs.mkdirSync(directoryName); + } catch (e) { + if (e.code !== "EEXIST") { + throw e; + } + } + } + }, + getExecutingFilePath() { + return executingFilePath; + }, + getCurrentDirectory, + getDirectories, + getEnvironmentVariable(name) { + return process.env[name] || ""; + }, + readDirectory, + getModifiedTime: getModifiedTime3, + setModifiedTime, + deleteFile, + createHash: _crypto ? createSHA256Hash : generateDjb2Hash, + createSHA256Hash: _crypto ? createSHA256Hash : void 0, + getMemoryUsage() { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + getFileSize(path) { + const stat = statSync(path); + if (stat == null ? void 0 : stat.isFile()) { + return stat.size; + } + return 0; + }, + exit(exitCode) { + disableCPUProfiler(() => process.exit(exitCode)); + }, + enableCPUProfiler, + disableCPUProfiler, + cpuProfilingEnabled: () => !!activeSession || contains(process.execArgv, "--cpu-prof") || contains(process.execArgv, "--prof"), + realpath, + debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || some(process.execArgv, (arg) => /^--(?:inspect|debug)(?:-brk)?(?:=\d+)?$/i.test(arg)) || !!process.recordreplay, + tryEnableSourceMapsForHost() { + try { + require("source-map-support").install(); + } catch { + } + }, + setTimeout, + clearTimeout, + clearScreen: () => { + process.stdout.write("\x1B[2J\x1B[3J\x1B[H"); + }, + setBlocking: () => { + var _a; + const handle = (_a = process.stdout) == null ? void 0 : _a._handle; + if (handle && handle.setBlocking) { + handle.setBlocking(true); + } + }, + base64decode: (input) => Buffer.from(input, "base64").toString("utf8"), + base64encode: (input) => Buffer.from(input).toString("base64"), + require: (baseDir, moduleName) => { + try { + const modulePath = resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath, error: void 0 }; + } catch (error) { + return { module: void 0, modulePath: void 0, error }; + } + } + }; + return nodeSystem; + function statSync(path) { + try { + return _fs.statSync(path, statSyncOptions); + } catch { + return void 0; + } + } + function enableCPUProfiler(path, cb) { + if (activeSession) { + cb(); + return false; + } + const inspector = require("inspector"); + if (!inspector || !inspector.Session) { + cb(); + return false; + } + const session = new inspector.Session(); + session.connect(); + session.post("Profiler.enable", () => { + session.post("Profiler.start", () => { + activeSession = session; + profilePath = path; + cb(); + }); + }); + return true; + } + function cleanupPaths(profile) { + let externalFileCounter = 0; + const remappedPaths = /* @__PURE__ */ new Map(); + const normalizedDir = normalizeSlashes(_path.dirname(executingFilePath)); + const fileUrlRoot = `file://${getRootLength(normalizedDir) === 1 ? "" : "/"}${normalizedDir}`; + for (const node of profile.nodes) { + if (node.callFrame.url) { + const url = normalizeSlashes(node.callFrame.url); + if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames2)) { + node.callFrame.url = getRelativePathToDirectoryOrUrl( + fileUrlRoot, + url, + fileUrlRoot, + createGetCanonicalFileName(useCaseSensitiveFileNames2), + /*isAbsolutePathAnUrl*/ + true + ); + } else if (!nativePattern.test(url)) { + node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, `external${externalFileCounter}.js`)).get(url); + externalFileCounter++; + } + } + } + return profile; + } + function disableCPUProfiler(cb) { + if (activeSession && activeSession !== "stopping") { + const s = activeSession; + activeSession.post("Profiler.stop", (err, { profile }) => { + var _a; + if (!err) { + if ((_a = statSync(profilePath)) == null ? void 0 : _a.isDirectory()) { + profilePath = _path.join(profilePath, `${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}+P${process.pid}.cpuprofile`); + } + try { + _fs.mkdirSync(_path.dirname(profilePath), { recursive: true }); + } catch { + } + _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile))); + } + activeSession = void 0; + s.disconnect(); + cb(); + }); + activeSession = "stopping"; + return true; + } else { + cb(); + return false; + } + } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(swapCase(__filename)); + } + function swapCase(s) { + return s.replace(/\w/g, (ch) => { + const up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); + } + function fsWatchFileWorker(fileName, callback, pollingInterval) { + _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged); + let eventKind; + return { + close: () => _fs.unwatchFile(fileName, fileChanged) + }; + function fileChanged(curr, prev) { + const isPreviouslyDeleted = +prev.mtime === 0 || eventKind === 2 /* Deleted */; + if (+curr.mtime === 0) { + if (isPreviouslyDeleted) { + return; + } + eventKind = 2 /* Deleted */; + } else if (isPreviouslyDeleted) { + eventKind = 0 /* Created */; + } else if (+curr.mtime === +prev.mtime) { + return; + } else { + eventKind = 1 /* Changed */; + } + callback(fileName, eventKind, curr.mtime); + } + } + function fsWatchWorker(fileOrDirectory, recursive, callback) { + return _fs.watch( + fileOrDirectory, + fsSupportsRecursiveFsWatch ? { persistent: true, recursive: !!recursive } : { persistent: true }, + callback + ); + } + function readFile(fileName, _encoding) { + let buffer; + try { + buffer = _fs.readFileSync(fileName); + } catch { + return void 0; + } + let len = buffer.length; + if (len >= 2 && buffer[0] === 254 && buffer[1] === 255) { + len &= ~1; + for (let i = 0; i < len; i += 2) { + const temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + } + return buffer.toString("utf16le", 2); + } + if (len >= 2 && buffer[0] === 255 && buffer[1] === 254) { + return buffer.toString("utf16le", 2); + } + if (len >= 3 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) { + return buffer.toString("utf8", 3); + } + return buffer.toString("utf8"); + } + function writeFile2(fileName, data, writeByteOrderMark) { + if (writeByteOrderMark) { + data = byteOrderMarkIndicator + data; + } + let fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync( + fd, + data, + /*position*/ + void 0, + "utf8" + ); + } finally { + if (fd !== void 0) { + _fs.closeSync(fd); + } + } + } + function getAccessibleFileSystemEntries(path) { + try { + const entries = _fs.readdirSync(path || ".", { withFileTypes: true }); + const files = []; + const directories = []; + for (const dirent of entries) { + const entry = typeof dirent === "string" ? dirent : dirent.name; + if (entry === "." || entry === "..") { + continue; + } + let stat; + if (typeof dirent === "string" || dirent.isSymbolicLink()) { + const name = combinePaths(path, entry); + stat = statSync(name); + if (!stat) { + continue; + } + } else { + stat = dirent; + } + if (stat.isFile()) { + files.push(entry); + } else if (stat.isDirectory()) { + directories.push(entry); + } + } + files.sort(); + directories.sort(); + return { files, directories }; + } catch { + return emptyFileSystemEntries; + } + } + function readDirectory(path, extensions, excludes, includes, depth) { + return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); + } + function fileSystemEntryExists(path, entryKind) { + const stat = statSync(path); + if (!stat) { + return false; + } + switch (entryKind) { + case 0 /* File */: + return stat.isFile(); + case 1 /* Directory */: + return stat.isDirectory(); + default: + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0 /* File */); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1 /* Directory */); + } + function getDirectories(path) { + return getAccessibleFileSystemEntries(path).directories.slice(); + } + function fsRealPathHandlingLongPath(path) { + return path.length < 260 ? _fs.realpathSync.native(path) : _fs.realpathSync(path); + } + function realpath(path) { + try { + return fsRealpath(path); + } catch { + return path; + } + } + function getModifiedTime3(path) { + var _a; + return (_a = statSync(path)) == null ? void 0 : _a.mtime; + } + function setModifiedTime(path, time) { + try { + _fs.utimesSync(path, time, time); + } catch { + return; + } + } + function deleteFile(path) { + try { + return _fs.unlinkSync(path); + } catch { + return; + } + } + function createSHA256Hash(data) { + const hash = _crypto.createHash("sha256"); + hash.update(data); + return hash.digest("hex"); + } + } + let sys2; + if (isNodeLikeSystem()) { + sys2 = getNodeSystem(); + } + if (sys2) { + patchWriteFileEnsuringDirectory(sys2); + } + return sys2; +})(); +if (sys && sys.getEnvironmentVariable) { + setCustomPollingValues(sys); + Debug.setAssertionLevel( + /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV")) ? 1 /* Normal */ : 0 /* None */ + ); +} +if (sys && sys.debugMode) { + Debug.isDebugging = true; +} + +// src/compiler/path.ts +var directorySeparator = "/"; +var altDirectorySeparator = "\\"; +var urlSchemeSeparator = "://"; +var backslashRegExp = /\\/g; +function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; +} +function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; +} +function isDiskPathRoot(path) { + const rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; +} +function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; +} +function pathIsRelative(path) { + return /^\.\.?(?:$|[\\/])/.test(path); +} +function pathIsBareSpecifier(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path); +} +function hasExtension(fileName) { + return getBaseFileName(fileName).includes("."); +} +function fileExtensionIs(path, extension) { + return path.length > extension.length && endsWith(path, extension); +} +function fileExtensionIsOneOf(path, extensions) { + for (const extension of extensions) { + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; +} +function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); +} +function isVolumeCharacter(charCode) { + return charCode >= 97 /* a */ && charCode <= 122 /* z */ || charCode >= 65 /* A */ && charCode <= 90 /* Z */; +} +function getFileUrlVolumeSeparatorEnd(url, start) { + const ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + const ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) return start + 3; + } + return -1; +} +function getEncodedRootLength(path) { + if (!path) return 0; + const ch0 = path.charCodeAt(0); + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) return 1; + const p1 = path.indexOf(ch0 === 47 /* slash */ ? directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) return path.length; + return p1 + 1; + } + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + const ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) return 3; + if (path.length === 2) return 2; + } + const schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + const authorityStart = schemeEnd + urlSchemeSeparator.length; + const authorityEnd = path.indexOf(directorySeparator, authorityStart); + if (authorityEnd !== -1) { + const scheme = path.slice(0, schemeEnd); + const authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); + } + return ~path.length; + } + return 0; +} +function getRootLength(path) { + const rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; +} +function getDirectoryPath(path) { + path = normalizeSlashes(path); + const rootLength = getRootLength(path); + if (rootLength === path.length) return path; + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator))); +} +function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + const rootLength = getRootLength(path); + if (rootLength === path.length) return ""; + path = removeTrailingDirectorySeparator(path); + const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1)); + const extension = extensions !== void 0 && ignoreCase !== void 0 ? getAnyExtensionFromPath(name, extensions, ignoreCase) : void 0; + return extension ? name.slice(0, name.length - extension.length) : name; +} +function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!startsWith(extension, ".")) extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + const pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } +} +function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (const extension of extensions) { + const result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) return result; + } + return ""; +} +function getAnyExtensionFromPath(path, extensions, ignoreCase) { + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive); + } + const baseFileName = getBaseFileName(path); + const extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; +} +function pathComponents(path, rootLength) { + const root = path.substring(0, rootLength); + const rest = path.substring(rootLength).split(directorySeparator); + if (rest.length && !lastOrUndefined(rest)) rest.pop(); + return [root, ...rest]; +} +function getPathComponents(path, currentDirectory = "") { + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); +} +function getPathFromPathComponents(pathComponents2, length2) { + if (pathComponents2.length === 0) return ""; + const root = pathComponents2[0] && ensureTrailingDirectorySeparator(pathComponents2[0]); + return root + pathComponents2.slice(1, length2).join(directorySeparator); +} +function normalizeSlashes(path) { + return path.includes("\\") ? path.replace(backslashRegExp, directorySeparator) : path; +} +function reducePathComponents(components) { + if (!some(components)) return []; + const reduced = [components[0]]; + for (let i = 1; i < components.length; i++) { + const component = components[i]; + if (!component) continue; + if (component === ".") continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } else if (reduced[0]) continue; + } + reduced.push(component); + } + return reduced; +} +function combinePaths(path, ...paths) { + if (path) path = normalizeSlashes(path); + for (let relativePath of paths) { + if (!relativePath) continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; +} +function resolvePath(path, ...paths) { + return normalizePath(some(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path)); +} +function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); +} +function getNormalizedAbsolutePath(path, currentDirectory) { + let rootLength = getRootLength(path); + if (rootLength === 0 && currentDirectory) { + path = combinePaths(currentDirectory, path); + rootLength = getRootLength(path); + } else { + path = normalizeSlashes(path); + } + const simpleNormalized = simpleNormalizePath(path); + if (simpleNormalized !== void 0) { + return simpleNormalized.length > rootLength ? removeTrailingDirectorySeparator(simpleNormalized) : simpleNormalized; + } + const length2 = path.length; + const root = path.substring(0, rootLength); + let normalized; + let index = rootLength; + let segmentStart = index; + let normalizedUpTo = index; + let seenNonDotDotSegment = rootLength !== 0; + while (index < length2) { + segmentStart = index; + let ch = path.charCodeAt(index); + while (ch === 47 /* slash */ && index + 1 < length2) { + index++; + ch = path.charCodeAt(index); + } + if (index > segmentStart) { + normalized ?? (normalized = path.substring(0, segmentStart - 1)); + segmentStart = index; + } + let segmentEnd = path.indexOf(directorySeparator, index + 1); + if (segmentEnd === -1) { + segmentEnd = length2; + } + const segmentLength = segmentEnd - segmentStart; + if (segmentLength === 1 && path.charCodeAt(index) === 46 /* dot */) { + normalized ?? (normalized = path.substring(0, normalizedUpTo)); + } else if (segmentLength === 2 && path.charCodeAt(index) === 46 /* dot */ && path.charCodeAt(index + 1) === 46 /* dot */) { + if (!seenNonDotDotSegment) { + if (normalized !== void 0) { + normalized += normalized.length === rootLength ? ".." : "/.."; + } else { + normalizedUpTo = index + 2; + } + } else if (normalized === void 0) { + if (normalizedUpTo - 2 >= 0) { + normalized = path.substring(0, Math.max(rootLength, path.lastIndexOf(directorySeparator, normalizedUpTo - 2))); + } else { + normalized = path.substring(0, normalizedUpTo); + } + } else { + const lastSlash = normalized.lastIndexOf(directorySeparator); + if (lastSlash !== -1) { + normalized = normalized.substring(0, Math.max(rootLength, lastSlash)); + } else { + normalized = root; + } + if (normalized.length === rootLength) { + seenNonDotDotSegment = rootLength !== 0; + } + } + } else if (normalized !== void 0) { + if (normalized.length !== rootLength) { + normalized += directorySeparator; + } + seenNonDotDotSegment = true; + normalized += path.substring(segmentStart, segmentEnd); + } else { + seenNonDotDotSegment = true; + normalizedUpTo = segmentEnd; + } + index = segmentEnd + 1; + } + return normalized ?? (length2 > rootLength ? removeTrailingDirectorySeparator(path) : path); +} +function normalizePath(path) { + path = normalizeSlashes(path); + let normalized = simpleNormalizePath(path); + if (normalized !== void 0) { + return normalized; + } + normalized = getNormalizedAbsolutePath(path, ""); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; +} +function simpleNormalizePath(path) { + if (!relativePathSegmentRegExp.test(path)) { + return path; + } + let simplified = path.replace(/\/\.\//g, "/"); + if (simplified.startsWith("./")) { + simplified = simplified.slice(2); + } + if (simplified !== path) { + path = simplified; + if (!relativePathSegmentRegExp.test(path)) { + return path; + } + } + return void 0; +} +function getPathWithoutRoot(pathComponents2) { + if (pathComponents2.length === 0) return ""; + return pathComponents2.slice(1).join(directorySeparator); +} +function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); +} +function toPath(fileName, basePath, getCanonicalFileName) { + const nonCanonicalizedPath = isRootedDiskPath(fileName) ? normalizePath(fileName) : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); +} +function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; +} +function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + directorySeparator; + } + return path; +} +function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; +} +function changeAnyExtension(path, ext, extensions, ignoreCase) { + const pathext = extensions !== void 0 && ignoreCase !== void 0 ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; +} +function changeFullExtension(path, newExtension) { + const declarationExtension = getDeclarationFileExtension(path); + if (declarationExtension) { + return path.slice(0, path.length - declarationExtension.length) + (startsWith(newExtension, ".") ? newExtension : "." + newExtension); + } + return changeAnyExtension(path, newExtension); +} +var relativePathSegmentRegExp = /\/\/|(?:^|\/)\.\.?(?:$|\/)/; +function comparePathsWorker(a, b, componentComparer) { + if (a === b) return 0 /* EqualTo */; + if (a === void 0) return -1 /* LessThan */; + if (b === void 0) return 1 /* GreaterThan */; + const aRoot = a.substring(0, getRootLength(a)); + const bRoot = b.substring(0, getRootLength(b)); + const result = compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + const aRest = a.substring(aRoot.length); + const bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + const aComponents = reducePathComponents(getPathComponents(a)); + const bComponents = reducePathComponents(getPathComponents(b)); + const sharedLength = Math.min(aComponents.length, bComponents.length); + for (let i = 1; i < sharedLength; i++) { + const result2 = componentComparer(aComponents[i], bComponents[i]); + if (result2 !== 0 /* EqualTo */) { + return result2; + } + } + return compareValues(aComponents.length, bComponents.length); +} +function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, getStringComparer(ignoreCase)); +} +function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === void 0 || child === void 0) return false; + if (parent === child) return true; + const parentComponents = reducePathComponents(getPathComponents(parent)); + const childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + const componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; + for (let i = 0; i < parentComponents.length; i++) { + const equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; +} +function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + const canonicalFileName = getCanonicalFileName(fileName); + const canonicalDirectoryName = getCanonicalFileName(directoryName); + return startsWith(canonicalFileName, canonicalDirectoryName + "/") || startsWith(canonicalFileName, canonicalDirectoryName + "\\"); +} +function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + const fromComponents = reducePathComponents(getPathComponents(from)); + const toComponents = reducePathComponents(getPathComponents(to)); + let start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + const fromComponent = getCanonicalFileName(fromComponents[start]); + const toComponent = getCanonicalFileName(toComponents[start]); + const comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) break; + } + if (start === 0) { + return toComponents; + } + const components = toComponents.slice(start); + const relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return ["", ...relative, ...components]; +} +function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert(getRootLength(fromDirectory) > 0 === getRootLength(to) > 0, "Paths must either both be absolute or both be relative"); + const getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity; + const ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + const pathComponents2 = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents2); +} +function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl( + basePath, + absoluteOrRelativePath, + basePath, + getCanonicalFileName, + /*isAbsolutePathAnUrl*/ + false + ); +} +function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); +} +function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + const pathComponents2 = getPathComponentsRelativeTo( + resolvePath(currentDirectory, directoryPathOrUrl), + resolvePath(currentDirectory, relativeOrAbsolutePath), + equateStringsCaseSensitive, + getCanonicalFileName + ); + const firstComponent = pathComponents2[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + const prefix = firstComponent.charAt(0) === directorySeparator ? "file://" : "file:///"; + pathComponents2[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents2); +} +function forEachAncestorDirectory(directory, callback) { + while (true) { + const result = callback(directory); + if (result !== void 0) { + return result; + } + const parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return void 0; + } + directory = parentPath; + } +} +function isNodeModulesDirectory(dirPath) { + return endsWith(dirPath, "/node_modules"); +} + +// src/compiler/diagnosticInformationMap.generated.ts +function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated) { + return { code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated }; +} +var Diagnostics = { + Unterminated_string_literal: diag(1002, 1 /* Error */, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, 1 /* Error */, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, 1 /* Error */, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, 1 /* Error */, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + The_parser_expected_to_find_a_1_to_match_the_0_token_here: diag(1007, 1 /* Error */, "The_parser_expected_to_find_a_1_to_match_the_0_token_here_1007", "The parser expected to find a '{1}' to match the '{0}' token here."), + Trailing_comma_not_allowed: diag(1009, 1 /* Error */, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, 1 /* Error */, "Asterisk_Slash_expected_1010", "'*/' expected."), + An_element_access_expression_should_take_an_argument: diag(1011, 1 /* Error */, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."), + Unexpected_token: diag(1012, 1 /* Error */, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, 1 /* Error */, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, 1 /* Error */, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, 1 /* Error */, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, 1 /* Error */, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, 1 /* Error */, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, 1 /* Error */, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, 1 /* Error */, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, 1 /* Error */, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, 1 /* Error */, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, 1 /* Error */, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, 1 /* Error */, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + An_index_signature_cannot_have_a_trailing_comma: diag(1025, 1 /* Error */, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."), + Accessibility_modifier_already_seen: diag(1028, 1 /* Error */, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, 1 /* Error */, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, 1 /* Error */, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_class_elements_of_this_kind: diag(1031, 1 /* Error */, "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031", "'{0}' modifier cannot appear on class elements of this kind."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, 1 /* Error */, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, 1 /* Error */, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, 1 /* Error */, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, 1 /* Error */, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, 1 /* Error */, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, 1 /* Error */, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_here: diag(1042, 1 /* Error */, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, 1 /* Error */, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier: diag(1046, 1 /* Error */, "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046", "Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier."), + A_rest_parameter_cannot_be_optional: diag(1047, 1 /* Error */, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, 1 /* Error */, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, 1 /* Error */, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, 1 /* Error */, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, 1 /* Error */, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, 1 /* Error */, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, 1 /* Error */, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, 1 /* Error */, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compa_1055", "Type '{0}' is not a valid async function return type in ES5 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, 1 /* Error */, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, 1 /* Error */, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, 1 /* Error */, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, 1 /* Error */, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, 1 /* Error */, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, 1 /* Error */, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, 1 /* Error */, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1065, 1 /* Error */, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, 1 /* Error */, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, 1 /* Error */, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, 1 /* Error */, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, 1 /* Error */, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, 1 /* Error */, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, 1 /* Error */, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, 1 /* Error */, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, 1 /* Error */, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, 1 /* Error */, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, 1 /* Error */, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, 1 /* Error */, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, 1 /* Error */, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, 1 /* Error */, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, 1 /* Error */, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, 1 /* Error */, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, 1 /* Error */, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, 1 /* Error */, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, 1 /* Error */, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, 1 /* Error */, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, 1 /* Error */, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, 1 /* Error */, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, 1 /* Error */, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, 1 /* Error */, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, 1 /* Error */, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + The_left_hand_side_of_a_for_of_statement_may_not_be_async: diag(1106, 1 /* Error */, "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106", "The left-hand side of a 'for...of' statement may not be 'async'."), + Jump_target_cannot_cross_function_boundary: diag(1107, 1 /* Error */, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, 1 /* Error */, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, 1 /* Error */, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, 1 /* Error */, "Type_expected_1110", "Type expected."), + Private_field_0_must_be_declared_in_an_enclosing_class: diag(1111, 1 /* Error */, "Private_field_0_must_be_declared_in_an_enclosing_class_1111", "Private field '{0}' must be declared in an enclosing class."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, 1 /* Error */, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, 1 /* Error */, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, 1 /* Error */, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, 1 /* Error */, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name: diag(1117, 1 /* Error */, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117", "An object literal cannot have multiple properties with the same name."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, 1 /* Error */, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, 1 /* Error */, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, 1 /* Error */, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_Use_the_syntax_0: diag(1121, 1 /* Error */, "Octal_literals_are_not_allowed_Use_the_syntax_0_1121", "Octal literals are not allowed. Use the syntax '{0}'."), + Variable_declaration_list_cannot_be_empty: diag(1123, 1 /* Error */, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, 1 /* Error */, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, 1 /* Error */, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, 1 /* Error */, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, 1 /* Error */, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, 1 /* Error */, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, 1 /* Error */, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, 1 /* Error */, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, 1 /* Error */, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, 1 /* Error */, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, 1 /* Error */, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, 1 /* Error */, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, 1 /* Error */, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, 1 /* Error */, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, 1 /* Error */, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, 1 /* Error */, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, 1 /* Error */, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, 1 /* Error */, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, 1 /* Error */, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, 1 /* Error */, "or_expected_1144", "'{' or ';' expected."), + or_JSX_element_expected: diag(1145, 1 /* Error */, "or_JSX_element_expected_1145", "'{' or JSX element expected."), + Declaration_expected: diag(1146, 1 /* Error */, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, 1 /* Error */, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, 1 /* Error */, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, 1 /* Error */, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + _0_declarations_must_be_initialized: diag(1155, 1 /* Error */, "_0_declarations_must_be_initialized_1155", "'{0}' declarations must be initialized."), + _0_declarations_can_only_be_declared_inside_a_block: diag(1156, 1 /* Error */, "_0_declarations_can_only_be_declared_inside_a_block_1156", "'{0}' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, 1 /* Error */, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, 1 /* Error */, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, 1 /* Error */, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, 1 /* Error */, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, 1 /* Error */, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, 1 /* Error */, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type: diag(1166, 1 /* Error */, "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166", "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, 1 /* Error */, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, 1 /* Error */, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, 1 /* Error */, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, 1 /* Error */, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, 1 /* Error */, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, 1 /* Error */, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, 1 /* Error */, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, 1 /* Error */, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, 1 /* Error */, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, 1 /* Error */, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, 1 /* Error */, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, 1 /* Error */, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, 1 /* Error */, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, 1 /* Error */, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, 1 /* Error */, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, 1 /* Error */, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, 1 /* Error */, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, 1 /* Error */, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, 1 /* Error */, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, 1 /* Error */, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, 1 /* Error */, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, 1 /* Error */, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, 1 /* Error */, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, 1 /* Error */, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, 1 /* Error */, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, 1 /* Error */, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, 1 /* Error */, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + export_Asterisk_does_not_re_export_a_default: diag(1195, 1 /* Error */, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."), + Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified: diag(1196, 1 /* Error */, "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196", "Catch clause variable type annotation must be 'any' or 'unknown' if specified."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, 1 /* Error */, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, 1 /* Error */, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, 1 /* Error */, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, 1 /* Error */, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, 1 /* Error */, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", `Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from "mod"', 'import {a} from "mod"', 'import d from "mod"', or another module format instead.`), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, 1 /* Error */, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), + Re_exporting_a_type_when_0_is_enabled_requires_using_export_type: diag(1205, 1 /* Error */, "Re_exporting_a_type_when_0_is_enabled_requires_using_export_type_1205", "Re-exporting a type when '{0}' is enabled requires using 'export type'."), + Decorators_are_not_valid_here: diag(1206, 1 /* Error */, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, 1 /* Error */, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0: diag(1209, 1 /* Error */, "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209", "Invalid optional chain from new expression. Did you mean to call '{0}()'?"), + Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, 1 /* Error */, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, 1 /* Error */, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, 1 /* Error */, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, 1 /* Error */, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, 1 /* Error */, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, 1 /* Error */, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, 1 /* Error */, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, 1 /* Error */, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, 1 /* Error */, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, 1 /* Error */, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, 1 /* Error */, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, 1 /* Error */, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, 1 /* Error */, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, 1 /* Error */, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, 1 /* Error */, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, 1 /* Error */, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, 1 /* Error */, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, 1 /* Error */, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, 1 /* Error */, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), + An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module: diag(1232, 1 /* Error */, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232", "An import declaration can only be used at the top level of a namespace or module."), + An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module: diag(1233, 1 /* Error */, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233", "An export declaration can only be used at the top level of a namespace or module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, 1 /* Error */, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module: diag(1235, 1 /* Error */, "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235", "A namespace declaration is only allowed at the top level of a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, 1 /* Error */, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, 1 /* Error */, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, 1 /* Error */, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, 1 /* Error */, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, 1 /* Error */, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, 1 /* Error */, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, 1 /* Error */, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, 1 /* Error */, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, 1 /* Error */, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, 1 /* Error */, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, 1 /* Error */, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, 1 /* Error */, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, 1 /* Error */, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, 1 /* Error */, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5: diag(1250, 1 /* Error */, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, 1 /* Error */, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definiti_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_automatically_in_strict_mode: diag(1252, 1 /* Error */, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_au_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES5'. Modules are automatically in strict mode."), + Abstract_properties_can_only_appear_within_an_abstract_class: diag(1253, 1 /* Error */, "Abstract_properties_can_only_appear_within_an_abstract_class_1253", "Abstract properties can only appear within an abstract class."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, 1 /* Error */, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), + A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, 1 /* Error */, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_required_element_cannot_follow_an_optional_element: diag(1257, 1 /* Error */, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, 1 /* Error */, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), + Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, 1 /* Error */, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), + Keywords_cannot_contain_escape_characters: diag(1260, 1 /* Error */, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), + Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, 1 /* Error */, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), + Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module: diag(1262, 1 /* Error */, "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262", "Identifier expected. '{0}' is a reserved word at the top-level of a module."), + Declarations_with_initializers_cannot_also_have_definite_assignment_assertions: diag(1263, 1 /* Error */, "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263", "Declarations with initializers cannot also have definite assignment assertions."), + Declarations_with_definite_assignment_assertions_must_also_have_type_annotations: diag(1264, 1 /* Error */, "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264", "Declarations with definite assignment assertions must also have type annotations."), + A_rest_element_cannot_follow_another_rest_element: diag(1265, 1 /* Error */, "A_rest_element_cannot_follow_another_rest_element_1265", "A rest element cannot follow another rest element."), + An_optional_element_cannot_follow_a_rest_element: diag(1266, 1 /* Error */, "An_optional_element_cannot_follow_a_rest_element_1266", "An optional element cannot follow a rest element."), + Property_0_cannot_have_an_initializer_because_it_is_marked_abstract: diag(1267, 1 /* Error */, "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267", "Property '{0}' cannot have an initializer because it is marked abstract."), + An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type: diag(1268, 1 /* Error */, "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268", "An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type."), + Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled: diag(1269, 1 /* Error */, "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled_1269", "Cannot use 'export import' on a type or type-only namespace when '{0}' is enabled."), + Decorator_function_return_type_0_is_not_assignable_to_type_1: diag(1270, 1 /* Error */, "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270", "Decorator function return type '{0}' is not assignable to type '{1}'."), + Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any: diag(1271, 1 /* Error */, "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271", "Decorator function return type is '{0}' but is expected to be 'void' or 'any'."), + A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled: diag(1272, 1 /* Error */, "A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_w_1272", "A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled."), + _0_modifier_cannot_appear_on_a_type_parameter: diag(1273, 1 /* Error */, "_0_modifier_cannot_appear_on_a_type_parameter_1273", "'{0}' modifier cannot appear on a type parameter"), + _0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias: diag(1274, 1 /* Error */, "_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias_1274", "'{0}' modifier can only appear on a type parameter of a class, interface or type alias"), + accessor_modifier_can_only_appear_on_a_property_declaration: diag(1275, 1 /* Error */, "accessor_modifier_can_only_appear_on_a_property_declaration_1275", "'accessor' modifier can only appear on a property declaration."), + An_accessor_property_cannot_be_declared_optional: diag(1276, 1 /* Error */, "An_accessor_property_cannot_be_declared_optional_1276", "An 'accessor' property cannot be declared optional."), + _0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class: diag(1277, 1 /* Error */, "_0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class_1277", "'{0}' modifier can only appear on a type parameter of a function, method or class"), + The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0: diag(1278, 1 /* Error */, "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0_1278", "The runtime will invoke the decorator with {1} arguments, but the decorator expects {0}."), + The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0: diag(1279, 1 /* Error */, "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0_1279", "The runtime will invoke the decorator with {1} arguments, but the decorator expects at least {0}."), + Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to_be_a_global_script_set_moduleDetection_to_force_or_add_an_empty_export_statement: diag(1280, 1 /* Error */, "Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to__1280", "Namespaces are not allowed in global script files when '{0}' is enabled. If this file is not intended to be a global script, set 'moduleDetection' to 'force' or add an empty 'export {}' statement."), + Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead: diag(1281, 1 /* Error */, "Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead_1281", "Cannot access '{0}' from another file without qualification when '{1}' is enabled. Use '{2}' instead."), + An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type: diag(1282, 1 /* Error */, "An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers__1282", "An 'export =' declaration must reference a value when 'verbatimModuleSyntax' is enabled, but '{0}' only refers to a type."), + An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration: diag(1283, 1 /* Error */, "An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolve_1283", "An 'export =' declaration must reference a real value when 'verbatimModuleSyntax' is enabled, but '{0}' resolves to a type-only declaration."), + An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type: diag(1284, 1 /* Error */, "An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_1284", "An 'export default' must reference a value when 'verbatimModuleSyntax' is enabled, but '{0}' only refers to a type."), + An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration: diag(1285, 1 /* Error */, "An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_1285", "An 'export default' must reference a real value when 'verbatimModuleSyntax' is enabled, but '{0}' resolves to a type-only declaration."), + ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled: diag(1286, 1 /* Error */, "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled_1286", "ESM syntax is not allowed in a CommonJS module when 'verbatimModuleSyntax' is enabled."), + A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled: diag(1287, 1 /* Error */, "A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimM_1287", "A top-level 'export' modifier cannot be used on value declarations in a CommonJS module when 'verbatimModuleSyntax' is enabled."), + An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled: diag(1288, 1 /* Error */, "An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabl_1288", "An import alias cannot resolve to a type or type-only declaration when 'verbatimModuleSyntax' is enabled."), + _0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported: diag(1289, 1 /* Error */, "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1289", "'{0}' resolves to a type-only declaration and must be marked type-only in this file before re-exporting when '{1}' is enabled. Consider using 'import type' where '{0}' is imported."), + _0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default: diag(1290, 1 /* Error */, "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1290", "'{0}' resolves to a type-only declaration and must be marked type-only in this file before re-exporting when '{1}' is enabled. Consider using 'export type { {0} as default }'."), + _0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported: diag(1291, 1 /* Error */, "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1291", "'{0}' resolves to a type and must be marked type-only in this file before re-exporting when '{1}' is enabled. Consider using 'import type' where '{0}' is imported."), + _0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default: diag(1292, 1 /* Error */, "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1292", "'{0}' resolves to a type and must be marked type-only in this file before re-exporting when '{1}' is enabled. Consider using 'export type { {0} as default }'."), + ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve: diag(1293, 1 /* Error */, "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve_1293", "ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'."), + This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled: diag(1294, 1 /* Error */, "This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled_1294", "This syntax is not allowed when 'erasableSyntaxOnly' is enabled."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, 1 /* Error */, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, 1 /* Error */, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), + The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level: diag(1309, 1 /* Error */, "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309", "The current file is a CommonJS module and cannot use 'await' at the top level."), + Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern: diag(1312, 1 /* Error */, "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312", "Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, 1 /* Error */, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, 1 /* Error */, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, 1 /* Error */, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, 1 /* Error */, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, 1 /* Error */, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, 1 /* Error */, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, 1 /* Error */, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, 1 /* Error */, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, 1 /* Error */, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, 1 /* Error */, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node16_node18_or_nodenext: diag(1323, 1 /* Error */, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node16', 'node18', or 'nodenext'."), + Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_nodenext_or_preserve: diag(1324, 1 /* Error */, "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_1324", "Dynamic imports only support a second argument when the '--module' option is set to 'esnext', 'node16', 'node18', 'nodenext', or 'preserve'."), + Argument_of_dynamic_import_cannot_be_spread_element: diag(1325, 1 /* Error */, "Argument_of_dynamic_import_cannot_be_spread_element_1325", "Argument of dynamic import cannot be spread element."), + This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments: diag(1326, 1 /* Error */, "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326", "This use of 'import' is invalid. 'import()' calls can be written, but they must have parentheses and cannot have type arguments."), + String_literal_with_double_quotes_expected: diag(1327, 1 /* Error */, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, 1 /* Error */, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: diag(1329, 1 /* Error */, "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329", "'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"), + A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: diag(1330, 1 /* Error */, "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330", "A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."), + A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: diag(1331, 1 /* Error */, "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331", "A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."), + A_variable_whose_type_is_a_unique_symbol_type_must_be_const: diag(1332, 1 /* Error */, "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332", "A variable whose type is a 'unique symbol' type must be 'const'."), + unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, 1 /* Error */, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), + unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, 1 /* Error */, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), + unique_symbol_types_are_not_allowed_here: diag(1335, 1 /* Error */, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead: diag(1337, 1 /* Error */, "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337", "An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead."), + infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, 1 /* Error */, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), + Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, 1 /* Error */, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, 1 /* Error */, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Class_constructor_may_not_be_an_accessor: diag(1341, 1 /* Error */, "Class_constructor_may_not_be_an_accessor_1341", "Class constructor may not be an accessor."), + The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_node18_or_nodenext: diag(1343, 1 /* Error */, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', 'node18', or 'nodenext'."), + A_label_is_not_allowed_here: diag(1344, 1 /* Error */, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, 1 /* Error */, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness."), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, 1 /* Error */, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, 1 /* Error */, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, 1 /* Error */, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, 1 /* Error */, "use_strict_directive_used_here_1349", "'use strict' directive used here."), + Print_the_final_configuration_instead_of_building: diag(1350, 3 /* Message */, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, 1 /* Error */, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."), + A_bigint_literal_cannot_use_exponential_notation: diag(1352, 1 /* Error */, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."), + A_bigint_literal_must_be_an_integer: diag(1353, 1 /* Error */, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."), + readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, 1 /* Error */, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."), + A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals: diag(1355, 1 /* Error */, "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355", "A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals."), + Did_you_mean_to_mark_this_function_as_async: diag(1356, 1 /* Error */, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"), + An_enum_member_name_must_be_followed_by_a_or: diag(1357, 1 /* Error */, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), + Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, 1 /* Error */, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), + Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, 1 /* Error */, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Type_0_does_not_satisfy_the_expected_type_1: diag(1360, 1 /* Error */, "Type_0_does_not_satisfy_the_expected_type_1_1360", "Type '{0}' does not satisfy the expected type '{1}'."), + _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, 1 /* Error */, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."), + _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, 1 /* Error */, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."), + A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, 1 /* Error */, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), + Convert_to_type_only_export: diag(1364, 3 /* Message */, "Convert_to_type_only_export_1364", "Convert to type-only export"), + Convert_all_re_exported_types_to_type_only_exports: diag(1365, 3 /* Message */, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"), + Split_into_two_separate_import_declarations: diag(1366, 3 /* Message */, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"), + Split_all_invalid_type_only_imports: diag(1367, 3 /* Message */, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"), + Class_constructor_may_not_be_a_generator: diag(1368, 1 /* Error */, "Class_constructor_may_not_be_a_generator_1368", "Class constructor may not be a generator."), + Did_you_mean_0: diag(1369, 3 /* Message */, "Did_you_mean_0_1369", "Did you mean '{0}'?"), + await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, 1 /* Error */, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + _0_was_imported_here: diag(1376, 3 /* Message */, "_0_was_imported_here_1376", "'{0}' was imported here."), + _0_was_exported_here: diag(1377, 3 /* Message */, "_0_was_exported_here_1377", "'{0}' was exported here."), + Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_node18_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher: diag(1378, 1 /* Error */, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', 'node18', 'nodenext', or 'preserve', and the 'target' option is set to 'es2017' or higher."), + An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type: diag(1379, 1 /* Error */, "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379", "An import alias cannot reference a declaration that was exported using 'export type'."), + An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type: diag(1380, 1 /* Error */, "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380", "An import alias cannot reference a declaration that was imported using 'import type'."), + Unexpected_token_Did_you_mean_or_rbrace: diag(1381, 1 /* Error */, "Unexpected_token_Did_you_mean_or_rbrace_1381", "Unexpected token. Did you mean `{'}'}` or `}`?"), + Unexpected_token_Did_you_mean_or_gt: diag(1382, 1 /* Error */, "Unexpected_token_Did_you_mean_or_gt_1382", "Unexpected token. Did you mean `{'>'}` or `>`?"), + Function_type_notation_must_be_parenthesized_when_used_in_a_union_type: diag(1385, 1 /* Error */, "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385", "Function type notation must be parenthesized when used in a union type."), + Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type: diag(1386, 1 /* Error */, "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386", "Constructor type notation must be parenthesized when used in a union type."), + Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, 1 /* Error */, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."), + Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, 1 /* Error */, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), + _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, 1 /* Error */, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), + _0_is_not_allowed_as_a_parameter_name: diag(1390, 1 /* Error */, "_0_is_not_allowed_as_a_parameter_name_1390", "'{0}' is not allowed as a parameter name."), + An_import_alias_cannot_use_import_type: diag(1392, 1 /* Error */, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), + Imported_via_0_from_file_1: diag(1393, 3 /* Message */, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), + Imported_via_0_from_file_1_with_packageId_2: diag(1394, 3 /* Message */, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), + Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions: diag(1395, 3 /* Message */, "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395", "Imported via {0} from file '{1}' to import 'importHelpers' as specified in compilerOptions"), + Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions: diag(1396, 3 /* Message */, "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396", "Imported via {0} from file '{1}' with packageId '{2}' to import 'importHelpers' as specified in compilerOptions"), + Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions: diag(1397, 3 /* Message */, "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397", "Imported via {0} from file '{1}' to import 'jsx' and 'jsxs' factory functions"), + Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions: diag(1398, 3 /* Message */, "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398", "Imported via {0} from file '{1}' with packageId '{2}' to import 'jsx' and 'jsxs' factory functions"), + File_is_included_via_import_here: diag(1399, 3 /* Message */, "File_is_included_via_import_here_1399", "File is included via import here."), + Referenced_via_0_from_file_1: diag(1400, 3 /* Message */, "Referenced_via_0_from_file_1_1400", "Referenced via '{0}' from file '{1}'"), + File_is_included_via_reference_here: diag(1401, 3 /* Message */, "File_is_included_via_reference_here_1401", "File is included via reference here."), + Type_library_referenced_via_0_from_file_1: diag(1402, 3 /* Message */, "Type_library_referenced_via_0_from_file_1_1402", "Type library referenced via '{0}' from file '{1}'"), + Type_library_referenced_via_0_from_file_1_with_packageId_2: diag(1403, 3 /* Message */, "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403", "Type library referenced via '{0}' from file '{1}' with packageId '{2}'"), + File_is_included_via_type_library_reference_here: diag(1404, 3 /* Message */, "File_is_included_via_type_library_reference_here_1404", "File is included via type library reference here."), + Library_referenced_via_0_from_file_1: diag(1405, 3 /* Message */, "Library_referenced_via_0_from_file_1_1405", "Library referenced via '{0}' from file '{1}'"), + File_is_included_via_library_reference_here: diag(1406, 3 /* Message */, "File_is_included_via_library_reference_here_1406", "File is included via library reference here."), + Matched_by_include_pattern_0_in_1: diag(1407, 3 /* Message */, "Matched_by_include_pattern_0_in_1_1407", "Matched by include pattern '{0}' in '{1}'"), + File_is_matched_by_include_pattern_specified_here: diag(1408, 3 /* Message */, "File_is_matched_by_include_pattern_specified_here_1408", "File is matched by include pattern specified here."), + Part_of_files_list_in_tsconfig_json: diag(1409, 3 /* Message */, "Part_of_files_list_in_tsconfig_json_1409", "Part of 'files' list in tsconfig.json"), + File_is_matched_by_files_list_specified_here: diag(1410, 3 /* Message */, "File_is_matched_by_files_list_specified_here_1410", "File is matched by 'files' list specified here."), + Output_from_referenced_project_0_included_because_1_specified: diag(1411, 3 /* Message */, "Output_from_referenced_project_0_included_because_1_specified_1411", "Output from referenced project '{0}' included because '{1}' specified"), + Output_from_referenced_project_0_included_because_module_is_specified_as_none: diag(1412, 3 /* Message */, "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412", "Output from referenced project '{0}' included because '--module' is specified as 'none'"), + File_is_output_from_referenced_project_specified_here: diag(1413, 3 /* Message */, "File_is_output_from_referenced_project_specified_here_1413", "File is output from referenced project specified here."), + Source_from_referenced_project_0_included_because_1_specified: diag(1414, 3 /* Message */, "Source_from_referenced_project_0_included_because_1_specified_1414", "Source from referenced project '{0}' included because '{1}' specified"), + Source_from_referenced_project_0_included_because_module_is_specified_as_none: diag(1415, 3 /* Message */, "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415", "Source from referenced project '{0}' included because '--module' is specified as 'none'"), + File_is_source_from_referenced_project_specified_here: diag(1416, 3 /* Message */, "File_is_source_from_referenced_project_specified_here_1416", "File is source from referenced project specified here."), + Entry_point_of_type_library_0_specified_in_compilerOptions: diag(1417, 3 /* Message */, "Entry_point_of_type_library_0_specified_in_compilerOptions_1417", "Entry point of type library '{0}' specified in compilerOptions"), + Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1: diag(1418, 3 /* Message */, "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418", "Entry point of type library '{0}' specified in compilerOptions with packageId '{1}'"), + File_is_entry_point_of_type_library_specified_here: diag(1419, 3 /* Message */, "File_is_entry_point_of_type_library_specified_here_1419", "File is entry point of type library specified here."), + Entry_point_for_implicit_type_library_0: diag(1420, 3 /* Message */, "Entry_point_for_implicit_type_library_0_1420", "Entry point for implicit type library '{0}'"), + Entry_point_for_implicit_type_library_0_with_packageId_1: diag(1421, 3 /* Message */, "Entry_point_for_implicit_type_library_0_with_packageId_1_1421", "Entry point for implicit type library '{0}' with packageId '{1}'"), + Library_0_specified_in_compilerOptions: diag(1422, 3 /* Message */, "Library_0_specified_in_compilerOptions_1422", "Library '{0}' specified in compilerOptions"), + File_is_library_specified_here: diag(1423, 3 /* Message */, "File_is_library_specified_here_1423", "File is library specified here."), + Default_library: diag(1424, 3 /* Message */, "Default_library_1424", "Default library"), + Default_library_for_target_0: diag(1425, 3 /* Message */, "Default_library_for_target_0_1425", "Default library for target '{0}'"), + File_is_default_library_for_target_specified_here: diag(1426, 3 /* Message */, "File_is_default_library_for_target_specified_here_1426", "File is default library for target specified here."), + Root_file_specified_for_compilation: diag(1427, 3 /* Message */, "Root_file_specified_for_compilation_1427", "Root file specified for compilation"), + File_is_output_of_project_reference_source_0: diag(1428, 3 /* Message */, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), + File_redirects_to_file_0: diag(1429, 3 /* Message */, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), + The_file_is_in_the_program_because_Colon: diag(1430, 3 /* Message */, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, 1 /* Error */, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_node18_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, 1 /* Error */, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_nod_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', 'node18', 'nodenext', or 'preserve', and the 'target' option is set to 'es2017' or higher."), + Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters: diag(1433, 1 /* Error */, "Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters_1433", "Neither decorators nor modifiers may be applied to 'this' parameters."), + Unexpected_keyword_or_identifier: diag(1434, 1 /* Error */, "Unexpected_keyword_or_identifier_1434", "Unexpected keyword or identifier."), + Unknown_keyword_or_identifier_Did_you_mean_0: diag(1435, 1 /* Error */, "Unknown_keyword_or_identifier_Did_you_mean_0_1435", "Unknown keyword or identifier. Did you mean '{0}'?"), + Decorators_must_precede_the_name_and_all_keywords_of_property_declarations: diag(1436, 1 /* Error */, "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436", "Decorators must precede the name and all keywords of property declarations."), + Namespace_must_be_given_a_name: diag(1437, 1 /* Error */, "Namespace_must_be_given_a_name_1437", "Namespace must be given a name."), + Interface_must_be_given_a_name: diag(1438, 1 /* Error */, "Interface_must_be_given_a_name_1438", "Interface must be given a name."), + Type_alias_must_be_given_a_name: diag(1439, 1 /* Error */, "Type_alias_must_be_given_a_name_1439", "Type alias must be given a name."), + Variable_declaration_not_allowed_at_this_location: diag(1440, 1 /* Error */, "Variable_declaration_not_allowed_at_this_location_1440", "Variable declaration not allowed at this location."), + Cannot_start_a_function_call_in_a_type_annotation: diag(1441, 1 /* Error */, "Cannot_start_a_function_call_in_a_type_annotation_1441", "Cannot start a function call in a type annotation."), + Expected_for_property_initializer: diag(1442, 1 /* Error */, "Expected_for_property_initializer_1442", "Expected '=' for property initializer."), + Module_declaration_names_may_only_use_or_quoted_strings: diag(1443, 1 /* Error */, "Module_declaration_names_may_only_use_or_quoted_strings_1443", `Module declaration names may only use ' or " quoted strings.`), + _0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled: diag(1448, 1 /* Error */, "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_1448", "'{0}' resolves to a type-only declaration and must be re-exported using a type-only re-export when '{1}' is enabled."), + Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, 3 /* Message */, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."), + Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments: diag(1450, 3 /* Message */, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional set of attributes as arguments"), + Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, 1 /* Error */, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), + resolution_mode_should_be_either_require_or_import: diag(1453, 1 /* Error */, "resolution_mode_should_be_either_require_or_import_1453", "`resolution-mode` should be either `require` or `import`."), + resolution_mode_can_only_be_set_for_type_only_imports: diag(1454, 1 /* Error */, "resolution_mode_can_only_be_set_for_type_only_imports_1454", "`resolution-mode` can only be set for type-only imports."), + resolution_mode_is_the_only_valid_key_for_type_import_assertions: diag(1455, 1 /* Error */, "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455", "`resolution-mode` is the only valid key for type import assertions."), + Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1456, 1 /* Error */, "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456", "Type import assertions should have exactly one key - `resolution-mode` - with value `import` or `require`."), + Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk: diag(1457, 3 /* Message */, "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457", "Matched by default include pattern '**/*'"), + File_is_ECMAScript_module_because_0_has_field_type_with_value_module: diag(1458, 3 /* Message */, "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458", `File is ECMAScript module because '{0}' has field "type" with value "module"`), + File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module: diag(1459, 3 /* Message */, "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459", `File is CommonJS module because '{0}' has field "type" whose value is not "module"`), + File_is_CommonJS_module_because_0_does_not_have_field_type: diag(1460, 3 /* Message */, "File_is_CommonJS_module_because_0_does_not_have_field_type_1460", `File is CommonJS module because '{0}' does not have field "type"`), + File_is_CommonJS_module_because_package_json_was_not_found: diag(1461, 3 /* Message */, "File_is_CommonJS_module_because_package_json_was_not_found_1461", "File is CommonJS module because 'package.json' was not found"), + resolution_mode_is_the_only_valid_key_for_type_import_attributes: diag(1463, 1 /* Error */, "resolution_mode_is_the_only_valid_key_for_type_import_attributes_1463", "'resolution-mode' is the only valid key for type import attributes."), + Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1464, 1 /* Error */, "Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1464", "Type import attributes should have exactly one key - 'resolution-mode' - with value 'import' or 'require'."), + The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, 1 /* Error */, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), + Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead: diag(1471, 1 /* Error */, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported with 'require'. Use an ECMAScript import instead."), + catch_or_finally_expected: diag(1472, 1 /* Error */, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), + An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, 1 /* Error */, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), + An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, 1 /* Error */, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), + Control_what_method_is_used_to_detect_module_format_JS_files: diag(1475, 3 /* Message */, "Control_what_method_is_used_to_detect_module_format_JS_files_1475", "Control what method is used to detect module-format JS files."), + auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules: diag(1476, 3 /* Message */, "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476", '"auto": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules.'), + An_instantiation_expression_cannot_be_followed_by_a_property_access: diag(1477, 1 /* Error */, "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477", "An instantiation expression cannot be followed by a property access."), + Identifier_or_string_literal_expected: diag(1478, 1 /* Error */, "Identifier_or_string_literal_expected_1478", "Identifier or string literal expected."), + The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead: diag(1479, 1 /* Error */, "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479", `The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("{0}")' call instead.`), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module: diag(1480, 3 /* Message */, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480", 'To convert this file to an ECMAScript module, change its file extension to \'{0}\' or create a local package.json file with `{ "type": "module" }`.'), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1: diag(1481, 3 /* Message */, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481", `To convert this file to an ECMAScript module, change its file extension to '{0}', or add the field \`"type": "module"\` to '{1}'.`), + To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0: diag(1482, 3 /* Message */, "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482", 'To convert this file to an ECMAScript module, add the field `"type": "module"` to \'{0}\'.'), + To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module: diag(1483, 3 /* Message */, "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483", 'To convert this file to an ECMAScript module, create a local package.json file with `{ "type": "module" }`.'), + _0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled: diag(1484, 1 /* Error */, "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled_1484", "'{0}' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled."), + _0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled: diag(1485, 1 /* Error */, "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimMo_1485", "'{0}' resolves to a type-only declaration and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled."), + Decorator_used_before_export_here: diag(1486, 1 /* Error */, "Decorator_used_before_export_here_1486", "Decorator used before 'export' here."), + Octal_escape_sequences_are_not_allowed_Use_the_syntax_0: diag(1487, 1 /* Error */, "Octal_escape_sequences_are_not_allowed_Use_the_syntax_0_1487", "Octal escape sequences are not allowed. Use the syntax '{0}'."), + Escape_sequence_0_is_not_allowed: diag(1488, 1 /* Error */, "Escape_sequence_0_is_not_allowed_1488", "Escape sequence '{0}' is not allowed."), + Decimals_with_leading_zeros_are_not_allowed: diag(1489, 1 /* Error */, "Decimals_with_leading_zeros_are_not_allowed_1489", "Decimals with leading zeros are not allowed."), + File_appears_to_be_binary: diag(1490, 1 /* Error */, "File_appears_to_be_binary_1490", "File appears to be binary."), + _0_modifier_cannot_appear_on_a_using_declaration: diag(1491, 1 /* Error */, "_0_modifier_cannot_appear_on_a_using_declaration_1491", "'{0}' modifier cannot appear on a 'using' declaration."), + _0_declarations_may_not_have_binding_patterns: diag(1492, 1 /* Error */, "_0_declarations_may_not_have_binding_patterns_1492", "'{0}' declarations may not have binding patterns."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration: diag(1493, 1 /* Error */, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493", "The left-hand side of a 'for...in' statement cannot be a 'using' declaration."), + The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration: diag(1494, 1 /* Error */, "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494", "The left-hand side of a 'for...in' statement cannot be an 'await using' declaration."), + _0_modifier_cannot_appear_on_an_await_using_declaration: diag(1495, 1 /* Error */, "_0_modifier_cannot_appear_on_an_await_using_declaration_1495", "'{0}' modifier cannot appear on an 'await using' declaration."), + Identifier_string_literal_or_number_literal_expected: diag(1496, 1 /* Error */, "Identifier_string_literal_or_number_literal_expected_1496", "Identifier, string literal, or number literal expected."), + Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator: diag(1497, 1 /* Error */, "Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator_1497", "Expression must be enclosed in parentheses to be used as a decorator."), + Invalid_syntax_in_decorator: diag(1498, 1 /* Error */, "Invalid_syntax_in_decorator_1498", "Invalid syntax in decorator."), + Unknown_regular_expression_flag: diag(1499, 1 /* Error */, "Unknown_regular_expression_flag_1499", "Unknown regular expression flag."), + Duplicate_regular_expression_flag: diag(1500, 1 /* Error */, "Duplicate_regular_expression_flag_1500", "Duplicate regular expression flag."), + This_regular_expression_flag_is_only_available_when_targeting_0_or_later: diag(1501, 1 /* Error */, "This_regular_expression_flag_is_only_available_when_targeting_0_or_later_1501", "This regular expression flag is only available when targeting '{0}' or later."), + The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously: diag(1502, 1 /* Error */, "The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously_1502", "The Unicode (u) flag and the Unicode Sets (v) flag cannot be set simultaneously."), + Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later: diag(1503, 1 /* Error */, "Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later_1503", "Named capturing groups are only available when targeting 'ES2018' or later."), + Subpattern_flags_must_be_present_when_there_is_a_minus_sign: diag(1504, 1 /* Error */, "Subpattern_flags_must_be_present_when_there_is_a_minus_sign_1504", "Subpattern flags must be present when there is a minus sign."), + Incomplete_quantifier_Digit_expected: diag(1505, 1 /* Error */, "Incomplete_quantifier_Digit_expected_1505", "Incomplete quantifier. Digit expected."), + Numbers_out_of_order_in_quantifier: diag(1506, 1 /* Error */, "Numbers_out_of_order_in_quantifier_1506", "Numbers out of order in quantifier."), + There_is_nothing_available_for_repetition: diag(1507, 1 /* Error */, "There_is_nothing_available_for_repetition_1507", "There is nothing available for repetition."), + Unexpected_0_Did_you_mean_to_escape_it_with_backslash: diag(1508, 1 /* Error */, "Unexpected_0_Did_you_mean_to_escape_it_with_backslash_1508", "Unexpected '{0}'. Did you mean to escape it with backslash?"), + This_regular_expression_flag_cannot_be_toggled_within_a_subpattern: diag(1509, 1 /* Error */, "This_regular_expression_flag_cannot_be_toggled_within_a_subpattern_1509", "This regular expression flag cannot be toggled within a subpattern."), + k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets: diag(1510, 1 /* Error */, "k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets_1510", "'\\k' must be followed by a capturing group name enclosed in angle brackets."), + q_is_only_available_inside_character_class: diag(1511, 1 /* Error */, "q_is_only_available_inside_character_class_1511", "'\\q' is only available inside character class."), + c_must_be_followed_by_an_ASCII_letter: diag(1512, 1 /* Error */, "c_must_be_followed_by_an_ASCII_letter_1512", "'\\c' must be followed by an ASCII letter."), + Undetermined_character_escape: diag(1513, 1 /* Error */, "Undetermined_character_escape_1513", "Undetermined character escape."), + Expected_a_capturing_group_name: diag(1514, 1 /* Error */, "Expected_a_capturing_group_name_1514", "Expected a capturing group name."), + Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other: diag(1515, 1 /* Error */, "Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other_1515", "Named capturing groups with the same name must be mutually exclusive to each other."), + A_character_class_range_must_not_be_bounded_by_another_character_class: diag(1516, 1 /* Error */, "A_character_class_range_must_not_be_bounded_by_another_character_class_1516", "A character class range must not be bounded by another character class."), + Range_out_of_order_in_character_class: diag(1517, 1 /* Error */, "Range_out_of_order_in_character_class_1517", "Range out of order in character class."), + Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class: diag(1518, 1 /* Error */, "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518", "Anything that would possibly match more than a single character is invalid inside a negated character class."), + Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead: diag(1519, 1 /* Error */, "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519", "Operators must not be mixed within a character class. Wrap it in a nested class instead."), + Expected_a_class_set_operand: diag(1520, 1 /* Error */, "Expected_a_class_set_operand_1520", "Expected a class set operand."), + q_must_be_followed_by_string_alternatives_enclosed_in_braces: diag(1521, 1 /* Error */, "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521", "'\\q' must be followed by string alternatives enclosed in braces."), + A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backslash: diag(1522, 1 /* Error */, "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522", "A character class must not contain a reserved double punctuator. Did you mean to escape it with backslash?"), + Expected_a_Unicode_property_name: diag(1523, 1 /* Error */, "Expected_a_Unicode_property_name_1523", "Expected a Unicode property name."), + Unknown_Unicode_property_name: diag(1524, 1 /* Error */, "Unknown_Unicode_property_name_1524", "Unknown Unicode property name."), + Expected_a_Unicode_property_value: diag(1525, 1 /* Error */, "Expected_a_Unicode_property_value_1525", "Expected a Unicode property value."), + Unknown_Unicode_property_value: diag(1526, 1 /* Error */, "Unknown_Unicode_property_value_1526", "Unknown Unicode property value."), + Expected_a_Unicode_property_name_or_value: diag(1527, 1 /* Error */, "Expected_a_Unicode_property_name_or_value_1527", "Expected a Unicode property name or value."), + Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_the_Unicode_Sets_v_flag_is_set: diag(1528, 1 /* Error */, "Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_t_1528", "Any Unicode property that would possibly match more than a single character is only available when the Unicode Sets (v) flag is set."), + Unknown_Unicode_property_name_or_value: diag(1529, 1 /* Error */, "Unknown_Unicode_property_name_or_value_1529", "Unknown Unicode property name or value."), + Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set: diag(1530, 1 /* Error */, "Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v__1530", "Unicode property value expressions are only available when the Unicode (u) flag or the Unicode Sets (v) flag is set."), + _0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces: diag(1531, 1 /* Error */, "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531", "'\\{0}' must be followed by a Unicode property value expression enclosed in braces."), + There_is_no_capturing_group_named_0_in_this_regular_expression: diag(1532, 1 /* Error */, "There_is_no_capturing_group_named_0_in_this_regular_expression_1532", "There is no capturing group named '{0}' in this regular expression."), + This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_regular_expression: diag(1533, 1 /* Error */, "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533", "This backreference refers to a group that does not exist. There are only {0} capturing groups in this regular expression."), + This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regular_expression: diag(1534, 1 /* Error */, "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534", "This backreference refers to a group that does not exist. There are no capturing groups in this regular expression."), + This_character_cannot_be_escaped_in_a_regular_expression: diag(1535, 1 /* Error */, "This_character_cannot_be_escaped_in_a_regular_expression_1535", "This character cannot be escaped in a regular expression."), + Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended_as_an_escape_sequence_use_the_syntax_0_instead: diag(1536, 1 /* Error */, "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536", "Octal escape sequences and backreferences are not allowed in a character class. If this was intended as an escape sequence, use the syntax '{0}' instead."), + Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class: diag(1537, 1 /* Error */, "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537", "Decimal escape sequences and backreferences are not allowed in a character class."), + Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set: diag(1538, 1 /* Error */, "Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_se_1538", "Unicode escape sequences are only available when the Unicode (u) flag or the Unicode Sets (v) flag is set."), + A_bigint_literal_cannot_be_used_as_a_property_name: diag(1539, 1 /* Error */, "A_bigint_literal_cannot_be_used_as_a_property_name_1539", "A 'bigint' literal cannot be used as a property name."), + A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_keyword_instead: diag( + 1540, + 2 /* Suggestion */, + "A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_key_1540", + "A 'namespace' declaration should not be declared using the 'module' keyword. Please use the 'namespace' keyword instead.", + /*reportsUnnecessary*/ + void 0, + /*elidedInCompatabilityPyramid*/ + void 0, + /*reportsDeprecated*/ + true + ), + Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute: diag(1541, 1 /* Error */, "Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribut_1541", "Type-only import of an ECMAScript module from a CommonJS module must have a 'resolution-mode' attribute."), + Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute: diag(1542, 1 /* Error */, "Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute_1542", "Type import of an ECMAScript module from a CommonJS module must have a 'resolution-mode' attribute."), + Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_module_is_set_to_0: diag(1543, 1 /* Error */, "Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_mod_1543", `Importing a JSON file into an ECMAScript module requires a 'type: "json"' import attribute when 'module' is set to '{0}'.`), + Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0: diag(1544, 1 /* Error */, "Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0_1544", "Named imports from a JSON file into an ECMAScript module are not allowed when 'module' is set to '{0}'."), + The_types_of_0_are_incompatible_between_these_types: diag(2200, 1 /* Error */, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), + The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, 1 /* Error */, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), + Call_signature_return_types_0_and_1_are_incompatible: diag( + 2202, + 1 /* Error */, + "Call_signature_return_types_0_and_1_are_incompatible_2202", + "Call signature return types '{0}' and '{1}' are incompatible.", + /*reportsUnnecessary*/ + void 0, + /*elidedInCompatabilityPyramid*/ + true + ), + Construct_signature_return_types_0_and_1_are_incompatible: diag( + 2203, + 1 /* Error */, + "Construct_signature_return_types_0_and_1_are_incompatible_2203", + "Construct signature return types '{0}' and '{1}' are incompatible.", + /*reportsUnnecessary*/ + void 0, + /*elidedInCompatabilityPyramid*/ + true + ), + Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag( + 2204, + 1 /* Error */, + "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204", + "Call signatures with no arguments have incompatible return types '{0}' and '{1}'.", + /*reportsUnnecessary*/ + void 0, + /*elidedInCompatabilityPyramid*/ + true + ), + Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag( + 2205, + 1 /* Error */, + "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", + "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", + /*reportsUnnecessary*/ + void 0, + /*elidedInCompatabilityPyramid*/ + true + ), + The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, 1 /* Error */, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."), + The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, 1 /* Error */, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."), + This_type_parameter_might_need_an_extends_0_constraint: diag(2208, 1 /* Error */, "This_type_parameter_might_need_an_extends_0_constraint_2208", "This type parameter might need an `extends {0}` constraint."), + The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2209, 1 /* Error */, "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209", "The project root is ambiguous, but is required to resolve export map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), + The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2210, 1 /* Error */, "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210", "The project root is ambiguous, but is required to resolve import map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), + Add_extends_constraint: diag(2211, 3 /* Message */, "Add_extends_constraint_2211", "Add `extends` constraint."), + Add_extends_constraint_to_all_type_parameters: diag(2212, 3 /* Message */, "Add_extends_constraint_to_all_type_parameters_2212", "Add `extends` constraint to all type parameters"), + Duplicate_identifier_0: diag(2300, 1 /* Error */, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, 1 /* Error */, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, 1 /* Error */, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, 1 /* Error */, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, 1 /* Error */, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, 1 /* Error */, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, 1 /* Error */, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0_or_its_corresponding_type_declarations: diag(2307, 1 /* Error */, "Cannot_find_module_0_or_its_corresponding_type_declarations_2307", "Cannot find module '{0}' or its corresponding type declarations."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, 1 /* Error */, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, 1 /* Error */, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, 1 /* Error */, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function: diag(2311, 1 /* Error */, "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311", "Cannot find name '{0}'. Did you mean to write this in an async function?"), + An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, 1 /* Error */, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), + Type_parameter_0_has_a_circular_constraint: diag(2313, 1 /* Error */, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, 1 /* Error */, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, 1 /* Error */, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, 1 /* Error */, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, 1 /* Error */, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, 1 /* Error */, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, 1 /* Error */, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, 1 /* Error */, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, 1 /* Error */, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, 1 /* Error */, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, 1 /* Error */, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, 1 /* Error */, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, 1 /* Error */, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, 1 /* Error */, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, 1 /* Error */, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, 1 /* Error */, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_for_type_0_is_missing_in_type_1: diag(2329, 1 /* Error */, "Index_signature_for_type_0_is_missing_in_type_1_2329", "Index signature for type '{0}' is missing in type '{1}'."), + _0_and_1_index_signatures_are_incompatible: diag(2330, 1 /* Error */, "_0_and_1_index_signatures_are_incompatible_2330", "'{0}' and '{1}' index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, 1 /* Error */, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, 1 /* Error */, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, 1 /* Error */, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, 1 /* Error */, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, 1 /* Error */, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, 1 /* Error */, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, 1 /* Error */, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, 1 /* Error */, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, 1 /* Error */, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, 1 /* Error */, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0: diag(2343, 1 /* Error */, "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343", "This syntax requires an imported helper named '{1}' which does not exist in '{0}'. Consider upgrading your version of '{0}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, 1 /* Error */, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, 1 /* Error */, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, 1 /* Error */, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, 1 /* Error */, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "Value of type '{0}' is not callable. Did you mean to include 'new'?"), + This_expression_is_not_callable: diag(2349, 1 /* Error */, "This_expression_is_not_callable_2349", "This expression is not callable."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, 1 /* Error */, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + This_expression_is_not_constructable: diag(2351, 1 /* Error */, "This_expression_is_not_constructable_2351", "This expression is not constructable."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, 1 /* Error */, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, 1 /* Error */, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, 1 /* Error */, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value: diag(2355, 1 /* Error */, "A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2356, 1 /* Error */, "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, 1 /* Error */, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, 1 /* Error */, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_type_assignable_to_the_Function_interface_type_or_an_object_type_with_a_Symbol_hasInstance_method: diag(2359, 1 /* Error */, "The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_2359", "The right-hand side of an 'instanceof' expression must be either of type 'any', a class, function, or other type assignable to the 'Function' interface type, or an object type with a 'Symbol.hasInstance' method."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, 1 /* Error */, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, 1 /* Error */, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, 1 /* Error */, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, 1 /* Error */, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, 1 /* Error */, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap: diag(2367, 1 /* Error */, "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367", "This comparison appears to be unintentional because the types '{0}' and '{1}' have no overlap."), + Type_parameter_name_cannot_be_0: diag(2368, 1 /* Error */, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, 1 /* Error */, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, 1 /* Error */, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, 1 /* Error */, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_reference_itself: diag(2372, 1 /* Error */, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."), + Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, 1 /* Error */, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_index_signature_for_type_0: diag(2374, 1 /* Error */, "Duplicate_index_signature_for_type_0_2374", "Duplicate index signature for type '{0}'."), + Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2375, 1 /* Error */, "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375", "Type '{0}' is not assignable to type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."), + A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, 1 /* Error */, "A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_2376", "A 'super' call must be the first statement in the constructor to refer to 'super' or 'this' when a derived class contains initialized properties, parameter properties, or private identifiers."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, 1 /* Error */, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, 1 /* Error */, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2379, 1 /* Error */, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379", "Argument of type '{0}' is not assignable to parameter of type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, 1 /* Error */, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, 1 /* Error */, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, 1 /* Error */, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, 1 /* Error */, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, 1 /* Error */, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, 1 /* Error */, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, 1 /* Error */, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, 1 /* Error */, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, 1 /* Error */, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, 1 /* Error */, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, 1 /* Error */, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, 1 /* Error */, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, 1 /* Error */, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, 1 /* Error */, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, 1 /* Error */, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + constructor_cannot_be_used_as_a_parameter_property_name: diag(2398, 1 /* Error */, "constructor_cannot_be_used_as_a_parameter_property_name_2398", "'constructor' cannot be used as a parameter property name."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, 1 /* Error */, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, 1 /* Error */, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2401, 1 /* Error */, "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401", "A 'super' call must be a root-level statement within a constructor of a derived class that contains initialized properties, parameter properties, or private identifiers."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, 1 /* Error */, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, 1 /* Error */, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, 1 /* Error */, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, 1 /* Error */, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, 1 /* Error */, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, 1 /* Error */, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."), + Setters_cannot_return_a_value: diag(2408, 1 /* Error */, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, 1 /* Error */, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, 1 /* Error */, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target: diag(2412, 1 /* Error */, "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412", "Type '{0}' is not assignable to type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the type of the target."), + Property_0_of_type_1_is_not_assignable_to_2_index_type_3: diag(2411, 1 /* Error */, "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411", "Property '{0}' of type '{1}' is not assignable to '{2}' index type '{3}'."), + _0_index_type_1_is_not_assignable_to_2_index_type_3: diag(2413, 1 /* Error */, "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413", "'{0}' index type '{1}' is not assignable to '{2}' index type '{3}'."), + Class_name_cannot_be_0: diag(2414, 1 /* Error */, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, 1 /* Error */, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, 1 /* Error */, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, 1 /* Error */, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, 1 /* Error */, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), + Types_of_construct_signatures_are_incompatible: diag(2419, 1 /* Error */, "Types_of_construct_signatures_are_incompatible_2419", "Types of construct signatures are incompatible."), + Class_0_incorrectly_implements_interface_1: diag(2420, 1 /* Error */, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, 1 /* Error */, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, 1 /* Error */, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, 1 /* Error */, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, 1 /* Error */, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, 1 /* Error */, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, 1 /* Error */, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, 1 /* Error */, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, 1 /* Error */, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, 1 /* Error */, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, 1 /* Error */, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, 1 /* Error */, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, 1 /* Error */, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, 1 /* Error */, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, 1 /* Error */, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, 1 /* Error */, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, 1 /* Error */, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, 1 /* Error */, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, 1 /* Error */, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, 1 /* Error */, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, 1 /* Error */, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, 1 /* Error */, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, 1 /* Error */, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2: diag(2446, 1 /* Error */, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, 1 /* Error */, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, 1 /* Error */, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, 1 /* Error */, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, 1 /* Error */, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, 1 /* Error */, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, 1 /* Error */, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + Variable_0_is_used_before_being_assigned: diag(2454, 1 /* Error */, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_alias_0_circularly_references_itself: diag(2456, 1 /* Error */, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, 1 /* Error */, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, 1 /* Error */, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Module_0_declares_1_locally_but_it_is_not_exported: diag(2459, 1 /* Error */, "Module_0_declares_1_locally_but_it_is_not_exported_2459", "Module '{0}' declares '{1}' locally, but it is not exported."), + Module_0_declares_1_locally_but_it_is_exported_as_2: diag(2460, 1 /* Error */, "Module_0_declares_1_locally_but_it_is_exported_as_2_2460", "Module '{0}' declares '{1}' locally, but it is exported as '{2}'."), + Type_0_is_not_an_array_type: diag(2461, 1 /* Error */, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, 1 /* Error */, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, 1 /* Error */, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, 1 /* Error */, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, 1 /* Error */, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, 1 /* Error */, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, 1 /* Error */, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, 1 /* Error */, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, 1 /* Error */, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, 1 /* Error */, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, 1 /* Error */, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + const_enum_member_initializers_must_be_constant_expressions: diag(2474, 1 /* Error */, "const_enum_member_initializers_must_be_constant_expressions_2474", "const enum member initializers must be constant expressions."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, 1 /* Error */, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, 1 /* Error */, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, 1 /* Error */, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, 1 /* Error */, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, 1 /* Error */, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, 1 /* Error */, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, 1 /* Error */, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, 1 /* Error */, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, 1 /* Error */, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, 1 /* Error */, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, 1 /* Error */, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property: diag(2490, 1 /* Error */, "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the '{0}()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, 1 /* Error */, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, 1 /* Error */, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, 1 /* Error */, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, 1 /* Error */, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, 1 /* Error */, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_function_expression: diag(2496, 1 /* Error */, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_func_2496", "The 'arguments' object cannot be referenced in an arrow function in ES5. Consider using a standard function expression."), + This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, 1 /* Error */, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, 1 /* Error */, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, 1 /* Error */, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, 1 /* Error */, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, 1 /* Error */, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, 1 /* Error */, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, 1 /* Error */, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, 1 /* Error */, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, 1 /* Error */, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, 1 /* Error */, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, 1 /* Error */, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, 1 /* Error */, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2509, 1 /* Error */, "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509", "Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, 1 /* Error */, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_an_abstract_class: diag(2511, 1 /* Error */, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, 1 /* Error */, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, 1 /* Error */, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + A_tuple_type_cannot_be_indexed_with_a_negative_value: diag(2514, 1 /* Error */, "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514", "A tuple type cannot be indexed with a negative value."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, 1 /* Error */, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member {1} from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, 1 /* Error */, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, 1 /* Error */, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, 1 /* Error */, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, 1 /* Error */, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, 1 /* Error */, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_standard_function_or_method: diag(2522, 1 /* Error */, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_sta_2522", "The 'arguments' object cannot be referenced in an async function or method in ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, 1 /* Error */, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, 1 /* Error */, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, 1 /* Error */, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, 1 /* Error */, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, 1 /* Error */, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, 1 /* Error */, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, 1 /* Error */, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, 1 /* Error */, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, 1 /* Error */, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, 1 /* Error */, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, 1 /* Error */, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, 1 /* Error */, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, 1 /* Error */, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, 1 /* Error */, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, 1 /* Error */, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_read_only_property: diag(2540, 1 /* Error */, "Cannot_assign_to_0_because_it_is_a_read_only_property_2540", "Cannot assign to '{0}' because it is a read-only property."), + Index_signature_in_type_0_only_permits_reading: diag(2542, 1 /* Error */, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, 1 /* Error */, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, 1 /* Error */, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, 1 /* Error */, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, 1 /* Error */, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, 1 /* Error */, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, 1 /* Error */, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, 1 /* Error */, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, 1 /* Error */, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, 1 /* Error */, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, 1 /* Error */, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, 1 /* Error */, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, 1 /* Error */, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, 1 /* Error */, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), + Expected_0_type_arguments_but_got_1: diag(2558, 1 /* Error */, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, 1 /* Error */, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, 1 /* Error */, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, 1 /* Error */, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, 1 /* Error */, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, 1 /* Error */, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, 1 /* Error */, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), + Property_0_is_used_before_being_assigned: diag(2565, 1 /* Error */, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, 1 /* Error */, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), + Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, 1 /* Error */, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."), + Property_0_may_not_exist_on_type_1_Did_you_mean_2: diag(2568, 1 /* Error */, "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568", "Property '{0}' may not exist on type '{1}'. Did you mean '{2}'?"), + Could_not_find_name_0_Did_you_mean_1: diag(2570, 1 /* Error */, "Could_not_find_name_0_Did_you_mean_1_2570", "Could not find name '{0}'. Did you mean '{1}'?"), + Object_is_of_type_unknown: diag(2571, 1 /* Error */, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + A_rest_element_type_must_be_an_array_type: diag(2574, 1 /* Error */, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, 1 /* Error */, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead: diag(2576, 1 /* Error */, "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576", "Property '{0}' does not exist on type '{1}'. Did you mean to access the static member '{2}' instead?"), + Return_type_annotation_circularly_references_itself: diag(2577, 1 /* Error */, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Unused_ts_expect_error_directive: diag(2578, 1 /* Error */, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, 1 /* Error */, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), + Cannot_assign_to_0_because_it_is_a_constant: diag(2588, 1 /* Error */, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), + Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, 1 /* Error */, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), + Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, 1 /* Error */, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), + This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, 1 /* Error */, "This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag_2594", "This module is declared with 'export =', and can only be used with a default import when using the '{0}' flag."), + _0_can_only_be_imported_by_using_a_default_import: diag(2595, 1 /* Error */, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), + _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, 1 /* Error */, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, 1 /* Error */, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, 1 /* Error */, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, 1 /* Error */, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, 1 /* Error */, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, 1 /* Error */, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, 1 /* Error */, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, 1 /* Error */, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, 1 /* Error */, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, 1 /* Error */, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + _0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property: diag(2610, 1 /* Error */, "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610", "'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property."), + _0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor: diag(2611, 1 /* Error */, "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611", "'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor."), + Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, 1 /* Error */, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), + Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, 1 /* Error */, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), + Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, 1 /* Error */, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), + Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, 1 /* Error */, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), + _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, 1 /* Error */, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."), + _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, 1 /* Error */, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."), + Source_has_0_element_s_but_target_requires_1: diag(2618, 1 /* Error */, "Source_has_0_element_s_but_target_requires_1_2618", "Source has {0} element(s) but target requires {1}."), + Source_has_0_element_s_but_target_allows_only_1: diag(2619, 1 /* Error */, "Source_has_0_element_s_but_target_allows_only_1_2619", "Source has {0} element(s) but target allows only {1}."), + Target_requires_0_element_s_but_source_may_have_fewer: diag(2620, 1 /* Error */, "Target_requires_0_element_s_but_source_may_have_fewer_2620", "Target requires {0} element(s) but source may have fewer."), + Target_allows_only_0_element_s_but_source_may_have_more: diag(2621, 1 /* Error */, "Target_allows_only_0_element_s_but_source_may_have_more_2621", "Target allows only {0} element(s) but source may have more."), + Source_provides_no_match_for_required_element_at_position_0_in_target: diag(2623, 1 /* Error */, "Source_provides_no_match_for_required_element_at_position_0_in_target_2623", "Source provides no match for required element at position {0} in target."), + Source_provides_no_match_for_variadic_element_at_position_0_in_target: diag(2624, 1 /* Error */, "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624", "Source provides no match for variadic element at position {0} in target."), + Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, 1 /* Error */, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."), + Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, 1 /* Error */, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."), + Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, 1 /* Error */, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."), + Cannot_assign_to_0_because_it_is_an_enum: diag(2628, 1 /* Error */, "Cannot_assign_to_0_because_it_is_an_enum_2628", "Cannot assign to '{0}' because it is an enum."), + Cannot_assign_to_0_because_it_is_a_class: diag(2629, 1 /* Error */, "Cannot_assign_to_0_because_it_is_a_class_2629", "Cannot assign to '{0}' because it is a class."), + Cannot_assign_to_0_because_it_is_a_function: diag(2630, 1 /* Error */, "Cannot_assign_to_0_because_it_is_a_function_2630", "Cannot assign to '{0}' because it is a function."), + Cannot_assign_to_0_because_it_is_a_namespace: diag(2631, 1 /* Error */, "Cannot_assign_to_0_because_it_is_a_namespace_2631", "Cannot assign to '{0}' because it is a namespace."), + Cannot_assign_to_0_because_it_is_an_import: diag(2632, 1 /* Error */, "Cannot_assign_to_0_because_it_is_an_import_2632", "Cannot assign to '{0}' because it is an import."), + JSX_property_access_expressions_cannot_include_JSX_namespace_names: diag(2633, 1 /* Error */, "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633", "JSX property access expressions cannot include JSX namespace names"), + _0_index_signatures_are_incompatible: diag(2634, 1 /* Error */, "_0_index_signatures_are_incompatible_2634", "'{0}' index signatures are incompatible."), + Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable: diag(2635, 1 /* Error */, "Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable_2635", "Type '{0}' has no signatures for which the type argument list is applicable."), + Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation: diag(2636, 1 /* Error */, "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636", "Type '{0}' is not assignable to type '{1}' as implied by variance annotation."), + Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types: diag(2637, 1 /* Error */, "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637", "Variance annotations are only supported in type aliases for object, function, constructor, and mapped types."), + Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operator: diag(2638, 1 /* Error */, "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638", "Type '{0}' may represent a primitive value, which is not permitted as the right operand of the 'in' operator."), + React_components_cannot_include_JSX_namespace_names: diag(2639, 1 /* Error */, "React_components_cannot_include_JSX_namespace_names_2639", "React components cannot include JSX namespace names"), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, 1 /* Error */, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and_2_more: diag(2650, 1 /* Error */, "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and__2650", "Non-abstract class expression is missing implementations for the following members of '{0}': {1} and {2} more."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, 1 /* Error */, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, 1 /* Error */, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, 1 /* Error */, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2: diag(2654, 1 /* Error */, "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_2654", "Non-abstract class '{0}' is missing implementations for the following members of '{1}': {2}."), + Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more: diag(2655, 1 /* Error */, "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more_2655", "Non-abstract class '{0}' is missing implementations for the following members of '{1}': {2} and {3} more."), + Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1: diag(2656, 1 /* Error */, "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_2656", "Non-abstract class expression is missing implementations for the following members of '{0}': {1}."), + JSX_expressions_must_have_one_parent_element: diag(2657, 1 /* Error */, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, 1 /* Error */, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, 1 /* Error */, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, 1 /* Error */, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, 1 /* Error */, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, 1 /* Error */, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, 1 /* Error */, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, 1 /* Error */, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, 1 /* Error */, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, 1 /* Error */, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, 1 /* Error */, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, 1 /* Error */, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, 1 /* Error */, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, 1 /* Error */, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, 1 /* Error */, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, 1 /* Error */, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, 1 /* Error */, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, 1 /* Error */, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, 1 /* Error */, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, 1 /* Error */, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, 1 /* Error */, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, 1 /* Error */, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, 1 /* Error */, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, 1 /* Error */, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, 1 /* Error */, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, 1 /* Error */, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, 1 /* Error */, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, 1 /* Error */, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, 1 /* Error */, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, 1 /* Error */, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, 1 /* Error */, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, 1 /* Error */, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0: diag(2690, 1 /* Error */, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690", "'{0}' only refers to a type, but is being used as a value here. Did you mean to use '{1} in {0}'?"), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, 1 /* Error */, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, 1 /* Error */, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, 1 /* Error */, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag( + 2695, + 1 /* Error */, + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", + "Left side of comma operator is unused and has no side effects.", + /*reportsUnnecessary*/ + true + ), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, 1 /* Error */, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, 1 /* Error */, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, 1 /* Error */, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, 1 /* Error */, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, 1 /* Error */, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, 1 /* Error */, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, 1 /* Error */, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, 1 /* Error */, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, 1 /* Error */, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, 1 /* Error */, "An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_2705", "An async function or method in ES5 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, 1 /* Error */, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, 1 /* Error */, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, 1 /* Error */, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, 1 /* Error */, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, 1 /* Error */, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, 1 /* Error */, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, 1 /* Error */, "A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_t_2712", "A dynamic import call in ES5 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, 1 /* Error */, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", `Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}["{1}"]'?`), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, 1 /* Error */, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), + Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, 1 /* Error */, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), + Type_parameter_0_has_a_circular_default: diag(2716, 1 /* Error */, "Type_parameter_0_has_a_circular_default_2716", "Type parameter '{0}' has a circular default."), + Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, 1 /* Error */, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), + Duplicate_property_0: diag(2718, 1 /* Error */, "Duplicate_property_0_2718", "Duplicate property '{0}'."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, 1 /* Error */, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, 1 /* Error */, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, 1 /* Error */, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, 1 /* Error */, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, 1 /* Error */, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), + _0_has_no_exported_member_named_1_Did_you_mean_2: diag(2724, 1 /* Error */, "_0_has_no_exported_member_named_1_Did_you_mean_2_2724", "'{0}' has no exported member named '{1}'. Did you mean '{2}'?"), + Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, 1 /* Error */, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), + Cannot_find_lib_definition_for_0: diag(2726, 1 /* Error */, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), + Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, 1 /* Error */, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, 3 /* Message */, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, 1 /* Error */, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, 1 /* Error */, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, 1 /* Error */, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, 1 /* Error */, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension."), + Property_0_was_also_declared_here: diag(2733, 1 /* Error */, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."), + Are_you_missing_a_semicolon: diag(2734, 1 /* Error */, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"), + Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, 1 /* Error */, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), + Operator_0_cannot_be_applied_to_type_1: diag(2736, 1 /* Error */, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), + BigInt_literals_are_not_available_when_targeting_lower_than_ES2020: diag(2737, 1 /* Error */, "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737", "BigInt literals are not available when targeting lower than ES2020."), + An_outer_value_of_this_is_shadowed_by_this_container: diag(2738, 3 /* Message */, "An_outer_value_of_this_is_shadowed_by_this_container_2738", "An outer value of 'this' is shadowed by this container."), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2: diag(2739, 1 /* Error */, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739", "Type '{0}' is missing the following properties from type '{1}': {2}"), + Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, 1 /* Error */, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), + Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, 1 /* Error */, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), + The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, 1 /* Error */, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, 1 /* Error */, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."), + Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, 1 /* Error */, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."), + This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, 1 /* Error */, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."), + This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, 1 /* Error */, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."), + _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, 1 /* Error */, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."), + Cannot_access_ambient_const_enums_when_0_is_enabled: diag(2748, 1 /* Error */, "Cannot_access_ambient_const_enums_when_0_is_enabled_2748", "Cannot access ambient const enums when '{0}' is enabled."), + _0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0: diag(2749, 1 /* Error */, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749", "'{0}' refers to a value, but is being used as a type here. Did you mean 'typeof {0}'?"), + The_implementation_signature_is_declared_here: diag(2750, 1 /* Error */, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."), + Circularity_originates_in_type_at_this_location: diag(2751, 1 /* Error */, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."), + The_first_export_default_is_here: diag(2752, 1 /* Error */, "The_first_export_default_is_here_2752", "The first export default is here."), + Another_export_default_is_here: diag(2753, 1 /* Error */, "Another_export_default_is_here_2753", "Another export default is here."), + super_may_not_use_type_arguments: diag(2754, 1 /* Error */, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."), + No_constituent_of_type_0_is_callable: diag(2755, 1 /* Error */, "No_constituent_of_type_0_is_callable_2755", "No constituent of type '{0}' is callable."), + Not_all_constituents_of_type_0_are_callable: diag(2756, 1 /* Error */, "Not_all_constituents_of_type_0_are_callable_2756", "Not all constituents of type '{0}' are callable."), + Type_0_has_no_call_signatures: diag(2757, 1 /* Error */, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."), + Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2758, 1 /* Error */, "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758", "Each member of the union type '{0}' has signatures, but none of those signatures are compatible with each other."), + No_constituent_of_type_0_is_constructable: diag(2759, 1 /* Error */, "No_constituent_of_type_0_is_constructable_2759", "No constituent of type '{0}' is constructable."), + Not_all_constituents_of_type_0_are_constructable: diag(2760, 1 /* Error */, "Not_all_constituents_of_type_0_are_constructable_2760", "Not all constituents of type '{0}' are constructable."), + Type_0_has_no_construct_signatures: diag(2761, 1 /* Error */, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."), + Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other: diag(2762, 1 /* Error */, "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762", "Each member of the union type '{0}' has construct signatures, but none of those signatures are compatible with each other."), + Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0: diag(2763, 1 /* Error */, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but for-of will always send '{0}'."), + Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0: diag(2764, 1 /* Error */, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array spread will always send '{0}'."), + Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0: diag(2765, 1 /* Error */, "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765", "Cannot iterate value because the 'next' method of its iterator expects type '{1}', but array destructuring will always send '{0}'."), + Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0: diag(2766, 1 /* Error */, "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766", "Cannot delegate iteration to value because the 'next' method of its iterator expects type '{1}', but the containing generator will always send '{0}'."), + The_0_property_of_an_iterator_must_be_a_method: diag(2767, 1 /* Error */, "The_0_property_of_an_iterator_must_be_a_method_2767", "The '{0}' property of an iterator must be a method."), + The_0_property_of_an_async_iterator_must_be_a_method: diag(2768, 1 /* Error */, "The_0_property_of_an_async_iterator_must_be_a_method_2768", "The '{0}' property of an async iterator must be a method."), + No_overload_matches_this_call: diag(2769, 1 /* Error */, "No_overload_matches_this_call_2769", "No overload matches this call."), + The_last_overload_gave_the_following_error: diag(2770, 1 /* Error */, "The_last_overload_gave_the_following_error_2770", "The last overload gave the following error."), + The_last_overload_is_declared_here: diag(2771, 1 /* Error */, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), + Overload_0_of_1_2_gave_the_following_error: diag(2772, 1 /* Error */, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), + Did_you_forget_to_use_await: diag(2773, 1 /* Error */, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, 1 /* Error */, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), + Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, 1 /* Error */, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), + Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, 1 /* Error */, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), + The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, 1 /* Error */, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), + The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access: diag(2778, 1 /* Error */, "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778", "The target of an object rest assignment may not be an optional property access."), + The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access: diag(2779, 1 /* Error */, "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779", "The left-hand side of an assignment expression may not be an optional property access."), + The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access: diag(2780, 1 /* Error */, "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780", "The left-hand side of a 'for...in' statement may not be an optional property access."), + The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access: diag(2781, 1 /* Error */, "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781", "The left-hand side of a 'for...of' statement may not be an optional property access."), + _0_needs_an_explicit_type_annotation: diag(2782, 3 /* Message */, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."), + _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, 1 /* Error */, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."), + get_and_set_accessors_cannot_declare_this_parameters: diag(2784, 1 /* Error */, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."), + This_spread_always_overwrites_this_property: diag(2785, 1 /* Error */, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."), + _0_cannot_be_used_as_a_JSX_component: diag(2786, 1 /* Error */, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."), + Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, 1 /* Error */, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."), + Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, 1 /* Error */, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."), + Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, 1 /* Error */, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."), + The_operand_of_a_delete_operator_must_be_optional: diag(2790, 1 /* Error */, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."), + Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, 1 /* Error */, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."), + Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option: diag(2792, 1 /* Error */, "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_t_2792", "Cannot find module '{0}'. Did you mean to set the 'moduleResolution' option to 'nodenext', or to add aliases to the 'paths' option?"), + The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_are_not_externally_visible: diag(2793, 1 /* Error */, "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793", "The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible."), + Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise: diag(2794, 1 /* Error */, "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794", "Expected {0} arguments, but got {1}. Did you forget to include 'void' in your type argument to 'Promise'?"), + The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, 1 /* Error */, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), + It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, 1 /* Error */, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), + A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, 1 /* Error */, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, 1 /* Error */, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, 1 /* Error */, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, 1 /* Error */, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, 1 /* Error */, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), + Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, 1 /* Error */, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), + Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, 1 /* Error */, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), + Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, 1 /* Error */, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), + Private_accessor_was_defined_without_a_getter: diag(2806, 1 /* Error */, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."), + This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, 1 /* Error */, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), + A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, 1 /* Error */, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), + Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_whole_assignment_in_parentheses: diag(2809, 1 /* Error */, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the whole assignment in parentheses."), + Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments: diag(2810, 1 /* Error */, "Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_2810", "Expected 1 argument, but got 0. 'new Promise()' needs a JSDoc hint to produce a 'resolve' that can be called without arguments."), + Initializer_for_property_0: diag(2811, 1 /* Error */, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, 1 /* Error */, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), + Class_declaration_cannot_implement_overload_list_for_0: diag(2813, 1 /* Error */, "Class_declaration_cannot_implement_overload_list_for_0_2813", "Class declaration cannot implement overload list for '{0}'."), + Function_with_bodies_can_only_merge_with_classes_that_are_ambient: diag(2814, 1 /* Error */, "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814", "Function with bodies can only merge with classes that are ambient."), + arguments_cannot_be_referenced_in_property_initializers: diag(2815, 1 /* Error */, "arguments_cannot_be_referenced_in_property_initializers_2815", "'arguments' cannot be referenced in property initializers."), + Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class: diag(2816, 1 /* Error */, "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816", "Cannot use 'this' in a static property initializer of a decorated class."), + Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block: diag(2817, 1 /* Error */, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817", "Property '{0}' has no initializer and is not definitely assigned in a class static block."), + Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers: diag(2818, 1 /* Error */, "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818", "Duplicate identifier '{0}'. Compiler reserves name '{1}' when emitting 'super' references in static initializers."), + Namespace_name_cannot_be_0: diag(2819, 1 /* Error */, "Namespace_name_cannot_be_0_2819", "Namespace name cannot be '{0}'."), + Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, 1 /* Error */, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), + Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_preserve: diag(2821, 1 /* Error */, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2821", "Import assertions are only supported when the '--module' option is set to 'esnext', 'node18', 'nodenext', or 'preserve'."), + Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, 1 /* Error */, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), + Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_preserve: diag(2823, 1 /* Error */, "Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2823", "Import attributes are only supported when the '--module' option is set to 'esnext', 'node18', 'nodenext', or 'preserve'."), + Cannot_find_namespace_0_Did_you_mean_1: diag(2833, 1 /* Error */, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), + Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, 1 /* Error */, "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Consider adding an extension to the import path."), + Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0: diag(2835, 1 /* Error */, "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean '{0}'?"), + Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls: diag(2836, 1 /* Error */, "Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2836", "Import assertions are not allowed on statements that compile to CommonJS 'require' calls."), + Import_assertion_values_must_be_string_literal_expressions: diag(2837, 1 /* Error */, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), + All_declarations_of_0_must_have_identical_constraints: diag(2838, 1 /* Error */, "All_declarations_of_0_must_have_identical_constraints_2838", "All declarations of '{0}' must have identical constraints."), + This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value: diag(2839, 1 /* Error */, "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839", "This condition will always return '{0}' since JavaScript compares objects by reference, not value."), + An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types: diag(2840, 1 /* Error */, "An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types_2840", "An interface cannot extend a primitive type like '{0}'. It can only extend other named object types."), + _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, 1 /* Error */, "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842", "'{0}' is an unused renaming of '{1}'. Did you intend to use it as a type annotation?"), + We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here: diag(2843, 1 /* Error */, "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843", "We can only write a type for '{0}' by adding a type for the entire parameter here."), + Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, 1 /* Error */, "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + This_condition_will_always_return_0: diag(2845, 1 /* Error */, "This_condition_will_always_return_0_2845", "This condition will always return '{0}'."), + A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead: diag(2846, 1 /* Error */, "A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_f_2846", "A declaration file cannot be imported without 'import type'. Did you mean to import an implementation file '{0}' instead?"), + The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression: diag(2848, 1 /* Error */, "The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression_2848", "The right-hand side of an 'instanceof' expression must not be an instantiation expression."), + Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1: diag(2849, 1 /* Error */, "Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1_2849", "Target signature provides too few arguments. Expected {0} or more, but got {1}."), + The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined: diag(2850, 1 /* Error */, "The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_n_2850", "The initializer of a 'using' declaration must be either an object with a '[Symbol.dispose]()' method, or be 'null' or 'undefined'."), + The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined: diag(2851, 1 /* Error */, "The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_2851", "The initializer of an 'await using' declaration must be either an object with a '[Symbol.asyncDispose]()' or '[Symbol.dispose]()' method, or be 'null' or 'undefined'."), + await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(2852, 1 /* Error */, "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852", "'await using' statements are only allowed within async functions and at the top levels of modules."), + await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(2853, 1 /* Error */, "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853", "'await using' statements are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_node18_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher: diag(2854, 1 /* Error */, "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854", "Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', 'node18', 'nodenext', or 'preserve', and the 'target' option is set to 'es2017' or higher."), + Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super: diag(2855, 1 /* Error */, "Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super_2855", "Class field '{0}' defined by the parent class is not accessible in the child class via super."), + Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls: diag(2856, 1 /* Error */, "Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2856", "Import attributes are not allowed on statements that compile to CommonJS 'require' calls."), + Import_attributes_cannot_be_used_with_type_only_imports_or_exports: diag(2857, 1 /* Error */, "Import_attributes_cannot_be_used_with_type_only_imports_or_exports_2857", "Import attributes cannot be used with type-only imports or exports."), + Import_attribute_values_must_be_string_literal_expressions: diag(2858, 1 /* Error */, "Import_attribute_values_must_be_string_literal_expressions_2858", "Import attribute values must be string literal expressions."), + Excessive_complexity_comparing_types_0_and_1: diag(2859, 1 /* Error */, "Excessive_complexity_comparing_types_0_and_1_2859", "Excessive complexity comparing types '{0}' and '{1}'."), + The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_hand_side_s_Symbol_hasInstance_method: diag(2860, 1 /* Error */, "The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_2860", "The left-hand side of an 'instanceof' expression must be assignable to the first argument of the right-hand side's '[Symbol.hasInstance]' method."), + An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_hand_side_of_an_instanceof_expression: diag(2861, 1 /* Error */, "An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_han_2861", "An object's '[Symbol.hasInstance]' method must return a boolean value for it to be used on the right-hand side of an 'instanceof' expression."), + Type_0_is_generic_and_can_only_be_indexed_for_reading: diag(2862, 1 /* Error */, "Type_0_is_generic_and_can_only_be_indexed_for_reading_2862", "Type '{0}' is generic and can only be indexed for reading."), + A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values: diag(2863, 1 /* Error */, "A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values_2863", "A class cannot extend a primitive type like '{0}'. Classes can only extend constructable values."), + A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types: diag(2864, 1 /* Error */, "A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types_2864", "A class cannot implement a primitive type like '{0}'. It can only implement other named object types."), + Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled: diag(2865, 1 /* Error */, "Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_2865", "Import '{0}' conflicts with local value, so must be declared with a type-only import when 'isolatedModules' is enabled."), + Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled: diag(2866, 1 /* Error */, "Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_w_2866", "Import '{0}' conflicts with global value used in this file, so must be declared with a type-only import when 'isolatedModules' is enabled."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun: diag(2867, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2867", "Cannot find name '{0}'. Do you need to install type definitions for Bun? Try `npm i --save-dev @types/bun`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_and_then_add_bun_to_the_types_field_in_your_tsconfig: diag(2868, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2868", "Cannot find name '{0}'. Do you need to install type definitions for Bun? Try `npm i --save-dev @types/bun` and then add 'bun' to the types field in your tsconfig."), + Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish: diag(2869, 1 /* Error */, "Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish_2869", "Right operand of ?? is unreachable because the left operand is never nullish."), + This_binary_expression_is_never_nullish_Are_you_missing_parentheses: diag(2870, 1 /* Error */, "This_binary_expression_is_never_nullish_Are_you_missing_parentheses_2870", "This binary expression is never nullish. Are you missing parentheses?"), + This_expression_is_always_nullish: diag(2871, 1 /* Error */, "This_expression_is_always_nullish_2871", "This expression is always nullish."), + This_kind_of_expression_is_always_truthy: diag(2872, 1 /* Error */, "This_kind_of_expression_is_always_truthy_2872", "This kind of expression is always truthy."), + This_kind_of_expression_is_always_falsy: diag(2873, 1 /* Error */, "This_kind_of_expression_is_always_falsy_2873", "This kind of expression is always falsy."), + This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found: diag(2874, 1 /* Error */, "This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found_2874", "This JSX tag requires '{0}' to be in scope, but it could not be found."), + This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_for_the_appropriate_package_installed: diag(2875, 1 /* Error */, "This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_fo_2875", "This JSX tag requires the module path '{0}' to exist, but none could be found. Make sure you have types for the appropriate package installed."), + This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolves_to_0: diag(2876, 1 /* Error */, "This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolv_2876", 'This relative import path is unsafe to rewrite because it looks like a file name, but actually resolves to "{0}".'), + This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_during_emit_because_it_is_not_a_relative_path: diag(2877, 1 /* Error */, "This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_duri_2877", "This import uses a '{0}' extension to resolve to an input TypeScript file, but will not be rewritten during emit because it is not a relative path."), + This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_between_the_projects_output_files_is_not_the_same_as_the_relative_path_between_its_input_files: diag(2878, 1 /* Error */, "This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_b_2878", "This import path is unsafe to rewrite because it resolves to another project, and the relative path between the projects' output files is not the same as the relative path between its input files."), + Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found: diag(2879, 1 /* Error */, "Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found_2879", "Using JSX fragments requires fragment factory '{0}' to be in scope, but it could not be found."), + Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert: diag(2880, 1 /* Error */, "Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880", "Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'."), + Import_declaration_0_is_using_private_name_1: diag(4e3, 1 /* Error */, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, 1 /* Error */, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, 1 /* Error */, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, 1 /* Error */, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, 1 /* Error */, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, 1 /* Error */, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, 1 /* Error */, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, 1 /* Error */, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, 1 /* Error */, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, 1 /* Error */, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, 1 /* Error */, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_has_or_is_using_private_name_0: diag(4021, 1 /* Error */, "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021", "'extends' clause of exported class has or is using private name '{0}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, 1 /* Error */, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, 1 /* Error */, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, 1 /* Error */, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, 1 /* Error */, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, 1 /* Error */, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, 1 /* Error */, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, 1 /* Error */, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, 1 /* Error */, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, 1 /* Error */, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, 1 /* Error */, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, 1 /* Error */, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, 1 /* Error */, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, 1 /* Error */, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034", "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4035, 1 /* Error */, "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, 1 /* Error */, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036", "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: diag(4037, 1 /* Error */, "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4038, 1 /* Error */, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4039, 1 /* Error */, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039", "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4040, 1 /* Error */, "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040", "Return type of public static getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4041, 1 /* Error */, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041", "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4042, 1 /* Error */, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042", "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."), + Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: diag(4043, 1 /* Error */, "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043", "Return type of public getter '{0}' from exported class has or is using private name '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, 1 /* Error */, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, 1 /* Error */, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, 1 /* Error */, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, 1 /* Error */, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, 1 /* Error */, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, 1 /* Error */, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, 1 /* Error */, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, 1 /* Error */, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, 1 /* Error */, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, 1 /* Error */, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, 1 /* Error */, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, 1 /* Error */, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, 1 /* Error */, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, 1 /* Error */, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, 1 /* Error */, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, 1 /* Error */, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, 1 /* Error */, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, 1 /* Error */, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, 1 /* Error */, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, 1 /* Error */, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, 1 /* Error */, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, 1 /* Error */, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, 1 /* Error */, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, 1 /* Error */, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, 1 /* Error */, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, 1 /* Error */, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, 1 /* Error */, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, 1 /* Error */, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, 1 /* Error */, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, 1 /* Error */, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, 1 /* Error */, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, 1 /* Error */, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, 1 /* Error */, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, 1 /* Error */, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, 1 /* Error */, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, 1 /* Error */, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, 1 /* Error */, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, 1 /* Error */, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, 1 /* Error */, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), + Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1: diag(4085, 1 /* Error */, "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085", "Extends clause for inferred type '{0}' has or is using private name '{1}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, 1 /* Error */, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, 1 /* Error */, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected: diag(4094, 1 /* Error */, "Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected_4094", "Property '{0}' of exported anonymous class type may not be private or protected."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, 1 /* Error */, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, 1 /* Error */, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, 1 /* Error */, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4098, 1 /* Error */, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098", "Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4099, 1 /* Error */, "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099", "Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, 1 /* Error */, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), + Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, 1 /* Error */, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, 1 /* Error */, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, 1 /* Error */, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."), + The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1: diag(4104, 1 /* Error */, "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104", "The type '{0}' is 'readonly' and cannot be assigned to the mutable type '{1}'."), + Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter: diag(4105, 1 /* Error */, "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105", "Private or protected member '{0}' cannot be accessed on a type parameter."), + Parameter_0_of_accessor_has_or_is_using_private_name_1: diag(4106, 1 /* Error */, "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106", "Parameter '{0}' of accessor has or is using private name '{1}'."), + Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2: diag(4107, 1 /* Error */, "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107", "Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4108, 1 /* Error */, "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108", "Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named."), + Type_arguments_for_0_circularly_reference_themselves: diag(4109, 1 /* Error */, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), + Tuple_type_arguments_circularly_reference_themselves: diag(4110, 1 /* Error */, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), + Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, 1 /* Error */, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."), + This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, 1 /* Error */, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), + This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, 1 /* Error */, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, 1 /* Error */, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, 1 /* Error */, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, 1 /* Error */, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), + This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4117, 1 /* Error */, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'. Did you mean '{1}'?"), + The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized: diag(4118, 1 /* Error */, "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118", "The type of this node cannot be serialized because its property '{0}' cannot be serialized."), + This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0: diag(4119, 1 /* Error */, "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119", "This member must have a JSDoc comment with an '@override' tag because it overrides a member in the base class '{0}'."), + This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0: diag(4120, 1 /* Error */, "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120", "This parameter property must have a JSDoc comment with an '@override' tag because it overrides a member in the base class '{0}'."), + This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class: diag(4121, 1 /* Error */, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121", "This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class."), + This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, 1 /* Error */, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), + This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, 1 /* Error */, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), + Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, 1 /* Error */, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given: diag(4125, 1 /* Error */, "Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given_4125", "Each declaration of '{0}.{1}' differs in its value, where '{2}' was expected but '{3}' was given."), + One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value: diag(4126, 1 /* Error */, "One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value_4126", "One value of '{0}.{1}' is the string '{2}', and the other is assumed to be an unknown numeric value."), + This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic: diag(4127, 1 /* Error */, "This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic_4127", "This member cannot have an 'override' modifier because its name is dynamic."), + This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic: diag(4128, 1 /* Error */, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic_4128", "This member cannot have a JSDoc comment with an '@override' tag because its name is dynamic."), + The_current_host_does_not_support_the_0_option: diag(5001, 1 /* Error */, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, 1 /* Error */, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, 1 /* Error */, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, 1 /* Error */, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, 1 /* Error */, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, 1 /* Error */, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Unknown_compiler_option_0_Did_you_mean_1: diag(5025, 1 /* Error */, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"), + Could_not_write_file_0_Colon_1: diag(5033, 1 /* Error */, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, 1 /* Error */, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, 1 /* Error */, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, 1 /* Error */, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, 1 /* Error */, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, 1 /* Error */, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, 1 /* Error */, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, 1 /* Error */, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, 1 /* Error */, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, 1 /* Error */, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, 1 /* Error */, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, 1 /* Error */, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, 1 /* Error */, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character: diag(5062, 1 /* Error */, "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, 1 /* Error */, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, 1 /* Error */, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, 1 /* Error */, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, 1 /* Error */, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, 1 /* Error */, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, 1 /* Error */, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, 1 /* Error */, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic: diag(5070, 1 /* Error */, "Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic_5070", "Option '--resolveJsonModule' cannot be specified when 'moduleResolution' is set to 'classic'."), + Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd: diag(5071, 1 /* Error */, "Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd_5071", "Option '--resolveJsonModule' cannot be specified when 'module' is set to 'none', 'system', or 'umd'."), + Unknown_build_option_0: diag(5072, 1 /* Error */, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, 1 /* Error */, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, 1 /* Error */, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), + _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, 1 /* Error */, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), + _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, 1 /* Error */, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), + Unknown_build_option_0_Did_you_mean_1: diag(5077, 1 /* Error */, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), + Unknown_watch_option_0: diag(5078, 1 /* Error */, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."), + Unknown_watch_option_0_Did_you_mean_1: diag(5079, 1 /* Error */, "Unknown_watch_option_0_Did_you_mean_1_5079", "Unknown watch option '{0}'. Did you mean '{1}'?"), + Watch_option_0_requires_a_value_of_type_1: diag(5080, 1 /* Error */, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."), + Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, 1 /* Error */, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."), + _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, 1 /* Error */, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."), + Cannot_read_file_0: diag(5083, 1 /* Error */, "Cannot_read_file_0_5083", "Cannot read file '{0}'."), + A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, 1 /* Error */, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), + A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, 1 /* Error */, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, 1 /* Error */, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), + The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, 1 /* Error */, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), + Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, 1 /* Error */, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), + Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, 1 /* Error */, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled: diag(5091, 1 /* Error */, "Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when '{0}' is enabled."), + The_root_value_of_a_0_file_must_be_an_object: diag(5092, 1 /* Error */, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, 1 /* Error */, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, 1 /* Error */, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), + Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later: diag(5095, 1 /* Error */, "Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later_5095", "Option '{0}' can only be used when 'module' is set to 'preserve' or to 'es2015' or later."), + Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set: diag(5096, 1 /* Error */, "Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set_5096", "Option 'allowImportingTsExtensions' can only be used when either 'noEmit' or 'emitDeclarationOnly' is set."), + An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled: diag(5097, 1 /* Error */, "An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled_5097", "An import path can only end with a '{0}' extension when 'allowImportingTsExtensions' is enabled."), + Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler: diag(5098, 1 /* Error */, "Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler_5098", "Option '{0}' can only be used when 'moduleResolution' is set to 'node16', 'nodenext', or 'bundler'."), + Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprecations_Colon_2_to_silence_this_error: diag(5101, 1 /* Error */, "Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprec_5101", `Option '{0}' is deprecated and will stop functioning in TypeScript {1}. Specify compilerOption '"ignoreDeprecations": "{2}"' to silence this error.`), + Option_0_has_been_removed_Please_remove_it_from_your_configuration: diag(5102, 1 /* Error */, "Option_0_has_been_removed_Please_remove_it_from_your_configuration_5102", "Option '{0}' has been removed. Please remove it from your configuration."), + Invalid_value_for_ignoreDeprecations: diag(5103, 1 /* Error */, "Invalid_value_for_ignoreDeprecations_5103", "Invalid value for '--ignoreDeprecations'."), + Option_0_is_redundant_and_cannot_be_specified_with_option_1: diag(5104, 1 /* Error */, "Option_0_is_redundant_and_cannot_be_specified_with_option_1_5104", "Option '{0}' is redundant and cannot be specified with option '{1}'."), + Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System: diag(5105, 1 /* Error */, "Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System_5105", "Option 'verbatimModuleSyntax' cannot be used when 'module' is set to 'UMD', 'AMD', or 'System'."), + Use_0_instead: diag(5106, 3 /* Message */, "Use_0_instead_5106", "Use '{0}' instead."), + Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDeprecations_Colon_3_to_silence_this_error: diag(5107, 1 /* Error */, "Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDepr_5107", `Option '{0}={1}' is deprecated and will stop functioning in TypeScript {2}. Specify compilerOption '"ignoreDeprecations": "{3}"' to silence this error.`), + Option_0_1_has_been_removed_Please_remove_it_from_your_configuration: diag(5108, 1 /* Error */, "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108", "Option '{0}={1}' has been removed. Please remove it from your configuration."), + Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1: diag(5109, 1 /* Error */, "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109", "Option 'moduleResolution' must be set to '{0}' (or left unspecified) when option 'module' is set to '{1}'."), + Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1: diag(5110, 1 /* Error */, "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110", "Option 'module' must be set to '{0}' when option 'moduleResolution' is set to '{1}'."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6e3, 3 /* Message */, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), + Concatenate_and_emit_output_to_single_file: diag(6001, 3 /* Message */, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, 3 /* Message */, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, 3 /* Message */, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, 3 /* Message */, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, 3 /* Message */, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, 3 /* Message */, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, 3 /* Message */, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, 3 /* Message */, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, 3 /* Message */, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, 3 /* Message */, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, 3 /* Message */, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Do_not_resolve_the_real_path_of_symlinks: diag(6013, 3 /* Message */, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, 3 /* Message */, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), + Specify_ECMAScript_target_version: diag(6015, 3 /* Message */, "Specify_ECMAScript_target_version_6015", "Specify ECMAScript target version."), + Specify_module_code_generation: diag(6016, 3 /* Message */, "Specify_module_code_generation_6016", "Specify module code generation."), + Print_this_message: diag(6017, 3 /* Message */, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, 3 /* Message */, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, 3 /* Message */, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, 3 /* Message */, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, 3 /* Message */, "options_6024", "options"), + file: diag(6025, 3 /* Message */, "file_6025", "file"), + Examples_Colon_0: diag(6026, 3 /* Message */, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, 3 /* Message */, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, 3 /* Message */, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, 3 /* Message */, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, 3 /* Message */, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), + File_change_detected_Starting_incremental_compilation: diag(6032, 3 /* Message */, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, 3 /* Message */, "KIND_6034", "KIND"), + FILE: diag(6035, 3 /* Message */, "FILE_6035", "FILE"), + VERSION: diag(6036, 3 /* Message */, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, 3 /* Message */, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, 3 /* Message */, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, 3 /* Message */, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, 3 /* Message */, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Errors_Files: diag(6041, 3 /* Message */, "Errors_Files_6041", "Errors Files"), + Generates_corresponding_map_file: diag(6043, 3 /* Message */, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, 1 /* Error */, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, 1 /* Error */, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, 1 /* Error */, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, 1 /* Error */, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unable_to_open_file_0: diag(6050, 1 /* Error */, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, 1 /* Error */, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, 3 /* Message */, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, 1 /* Error */, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, 1 /* Error */, "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has an unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, 3 /* Message */, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, 3 /* Message */, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, 3 /* Message */, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, 1 /* Error */, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, 3 /* Message */, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, 3 /* Message */, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line: diag(6064, 1 /* Error */, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'null' on command line."), + Enables_experimental_support_for_ES7_decorators: diag(6065, 3 /* Message */, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, 3 /* Message */, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, 3 /* Message */, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, 3 /* Message */, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, 3 /* Message */, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, 3 /* Message */, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, 3 /* Message */, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, 3 /* Message */, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, 3 /* Message */, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, 3 /* Message */, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, 3 /* Message */, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, 3 /* Message */, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), + Specify_JSX_code_generation: diag(6080, 3 /* Message */, "Specify_JSX_code_generation_6080", "Specify JSX code generation."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, 1 /* Error */, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, 3 /* Message */, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, 3 /* Message */, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, 3 /* Message */, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, 3 /* Message */, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, 3 /* Message */, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, 3 /* Message */, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, 3 /* Message */, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, 3 /* Message */, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, 3 /* Message */, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, 3 /* Message */, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, 3 /* Message */, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, 3 /* Message */, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1: diag(6095, 3 /* Message */, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1_6095", "Loading module as file / folder, candidate module location '{0}', target file types: {1}."), + File_0_does_not_exist: diag(6096, 3 /* Message */, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exists_use_it_as_a_name_resolution_result: diag(6097, 3 /* Message */, "File_0_exists_use_it_as_a_name_resolution_result_6097", "File '{0}' exists - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_types_Colon_1: diag(6098, 3 /* Message */, "Loading_module_0_from_node_modules_folder_target_file_types_Colon_1_6098", "Loading module '{0}' from 'node_modules' folder, target file types: {1}."), + Found_package_json_at_0: diag(6099, 3 /* Message */, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, 3 /* Message */, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, 3 /* Message */, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, 3 /* Message */, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, 3 /* Message */, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, 3 /* Message */, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, 3 /* Message */, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, 3 /* Message */, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, 3 /* Message */, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, 3 /* Message */, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, 3 /* Message */, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, 3 /* Message */, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, 3 /* Message */, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, 3 /* Message */, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, 1 /* Error */, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, 3 /* Message */, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, 3 /* Message */, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, 3 /* Message */, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, 3 /* Message */, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, 3 /* Message */, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, 3 /* Message */, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, 3 /* Message */, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, 3 /* Message */, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, 3 /* Message */, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, 3 /* Message */, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, 3 /* Message */, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, 3 /* Message */, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + Resolving_real_path_for_0_result_1: diag(6130, 3 /* Message */, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, 1 /* Error */, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, 3 /* Message */, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_its_value_is_never_read: diag( + 6133, + 1 /* Error */, + "_0_is_declared_but_its_value_is_never_read_6133", + "'{0}' is declared but its value is never read.", + /*reportsUnnecessary*/ + true + ), + Report_errors_on_unused_locals: diag(6134, 3 /* Message */, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, 3 /* Message */, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, 3 /* Message */, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, 1 /* Error */, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_its_value_is_never_read: diag( + 6138, + 1 /* Error */, + "Property_0_is_declared_but_its_value_is_never_read_6138", + "Property '{0}' is declared but its value is never read.", + /*reportsUnnecessary*/ + true + ), + Import_emit_helpers_from_tslib: diag(6139, 3 /* Message */, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, 1 /* Error */, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, 3 /* Message */, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", 'Parse in strict mode and emit "use strict" for each source file.'), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, 1 /* Error */, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, 3 /* Message */, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, 3 /* Message */, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, 3 /* Message */, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, 3 /* Message */, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, 3 /* Message */, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, 3 /* Message */, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, 3 /* Message */, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, 3 /* Message */, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, 3 /* Message */, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, 3 /* Message */, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, 3 /* Message */, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, 3 /* Message */, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, 3 /* Message */, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, 3 /* Message */, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, 3 /* Message */, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, 3 /* Message */, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, 3 /* Message */, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, 3 /* Message */, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, 3 /* Message */, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1: diag(6164, 3 /* Message */, "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164", "Skipping module '{0}' that looks like an absolute URI, target file types: {1}."), + Do_not_truncate_error_messages: diag(6165, 3 /* Message */, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, 3 /* Message */, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, 3 /* Message */, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, 3 /* Message */, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, 3 /* Message */, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, 3 /* Message */, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, 3 /* Message */, "Command_line_Options_6171", "Command-line Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5: diag(6179, 3 /* Message */, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5'."), + Enable_all_strict_type_checking_options: diag(6180, 3 /* Message */, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + Scoped_package_detected_looking_in_0: diag(6182, 3 /* Message */, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2: diag(6183, 3 /* Message */, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183", "Reusing resolution of module '{0}' from '{1}' of old program, it was successfully resolved to '{2}'."), + Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3: diag(6184, 3 /* Message */, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184", "Reusing resolution of module '{0}' from '{1}' of old program, it was successfully resolved to '{2}' with Package ID '{3}'."), + Enable_strict_checking_of_function_types: diag(6186, 3 /* Message */, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), + Enable_strict_checking_of_property_initialization_in_classes: diag(6187, 3 /* Message */, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, 1 /* Error */, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, 1 /* Error */, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, 3 /* Message */, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), + All_imports_in_import_declaration_are_unused: diag( + 6192, + 1 /* Error */, + "All_imports_in_import_declaration_are_unused_6192", + "All imports in import declaration are unused.", + /*reportsUnnecessary*/ + true + ), + Found_1_error_Watching_for_file_changes: diag(6193, 3 /* Message */, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), + Found_0_errors_Watching_for_file_changes: diag(6194, 3 /* Message */, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), + Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, 3 /* Message */, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), + _0_is_declared_but_never_used: diag( + 6196, + 1 /* Error */, + "_0_is_declared_but_never_used_6196", + "'{0}' is declared but never used.", + /*reportsUnnecessary*/ + true + ), + Include_modules_imported_with_json_extension: diag(6197, 3 /* Message */, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag( + 6198, + 1 /* Error */, + "All_destructured_elements_are_unused_6198", + "All destructured elements are unused.", + /*reportsUnnecessary*/ + true + ), + All_variables_are_unused: diag( + 6199, + 1 /* Error */, + "All_variables_are_unused_6199", + "All variables are unused.", + /*reportsUnnecessary*/ + true + ), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, 1 /* Error */, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, 3 /* Message */, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, 1 /* Error */, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + _0_was_also_declared_here: diag(6203, 3 /* Message */, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, 3 /* Message */, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, 1 /* Error */, "All_type_parameters_are_unused_6205", "All type parameters are unused."), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, 3 /* Message */, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, 3 /* Message */, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, 3 /* Message */, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, 3 /* Message */, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, 3 /* Message */, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, 3 /* Message */, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, 3 /* Message */, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, 3 /* Message */, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, 3 /* Message */, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), + Using_compiler_options_of_project_reference_redirect_0: diag(6215, 3 /* Message */, "Using_compiler_options_of_project_reference_redirect_0_6215", "Using compiler options of project reference redirect '{0}'."), + Found_1_error: diag(6216, 3 /* Message */, "Found_1_error_6216", "Found 1 error."), + Found_0_errors: diag(6217, 3 /* Message */, "Found_0_errors_6217", "Found {0} errors."), + Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2: diag(6218, 3 /* Message */, "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218", "======== Module name '{0}' was successfully resolved to '{1}' with Package ID '{2}'. ========"), + Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3: diag(6219, 3 /* Message */, "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219", "======== Type reference directive '{0}' was successfully resolved to '{1}' with Package ID '{2}', primary: {3}. ========"), + package_json_had_a_falsy_0_field: diag(6220, 3 /* Message */, "package_json_had_a_falsy_0_field_6220", "'package.json' had a falsy '{0}' field."), + Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects: diag(6221, 3 /* Message */, "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221", "Disable use of source files instead of declaration files from referenced projects."), + Emit_class_fields_with_Define_instead_of_Set: diag(6222, 3 /* Message */, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."), + Generates_a_CPU_profile: diag(6223, 3 /* Message */, "Generates_a_CPU_profile_6223", "Generates a CPU profile."), + Disable_solution_searching_for_this_project: diag(6224, 3 /* Message */, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."), + Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, 3 /* Message */, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), + Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling: diag(6226, 3 /* Message */, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'."), + Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize: diag(6227, 3 /* Message */, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'."), + Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, 1 /* Error */, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), + Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, 1 /* Error */, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), + Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, 1 /* Error */, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."), + Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, 1 /* Error */, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."), + This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, 1 /* Error */, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."), + This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without: diag(6234, 1 /* Error */, "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234", "This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'?"), + Disable_loading_referenced_projects: diag(6235, 3 /* Message */, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), + Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, 1 /* Error */, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), + Generates_an_event_trace_and_a_list_of_types: diag(6237, 3 /* Message */, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, 1 /* Error */, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, 3 /* Message */, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, 3 /* Message */, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, 3 /* Message */, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, 3 /* Message */, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), + Interpret_optional_property_types_as_written_rather_than_adding_undefined: diag(6243, 3 /* Message */, "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243", "Interpret optional property types as written, rather than adding 'undefined'."), + Modules: diag(6244, 3 /* Message */, "Modules_6244", "Modules"), + File_Management: diag(6245, 3 /* Message */, "File_Management_6245", "File Management"), + Emit: diag(6246, 3 /* Message */, "Emit_6246", "Emit"), + JavaScript_Support: diag(6247, 3 /* Message */, "JavaScript_Support_6247", "JavaScript Support"), + Type_Checking: diag(6248, 3 /* Message */, "Type_Checking_6248", "Type Checking"), + Editor_Support: diag(6249, 3 /* Message */, "Editor_Support_6249", "Editor Support"), + Watch_and_Build_Modes: diag(6250, 3 /* Message */, "Watch_and_Build_Modes_6250", "Watch and Build Modes"), + Compiler_Diagnostics: diag(6251, 3 /* Message */, "Compiler_Diagnostics_6251", "Compiler Diagnostics"), + Interop_Constraints: diag(6252, 3 /* Message */, "Interop_Constraints_6252", "Interop Constraints"), + Backwards_Compatibility: diag(6253, 3 /* Message */, "Backwards_Compatibility_6253", "Backwards Compatibility"), + Language_and_Environment: diag(6254, 3 /* Message */, "Language_and_Environment_6254", "Language and Environment"), + Projects: diag(6255, 3 /* Message */, "Projects_6255", "Projects"), + Output_Formatting: diag(6256, 3 /* Message */, "Output_Formatting_6256", "Output Formatting"), + Completeness: diag(6257, 3 /* Message */, "Completeness_6257", "Completeness"), + _0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file: diag(6258, 1 /* Error */, "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258", "'{0}' should be set inside the 'compilerOptions' object of the config json file"), + Found_1_error_in_0: diag(6259, 3 /* Message */, "Found_1_error_in_0_6259", "Found 1 error in {0}"), + Found_0_errors_in_the_same_file_starting_at_Colon_1: diag(6260, 3 /* Message */, "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260", "Found {0} errors in the same file, starting at: {1}"), + Found_0_errors_in_1_files: diag(6261, 3 /* Message */, "Found_0_errors_in_1_files_6261", "Found {0} errors in {1} files."), + File_name_0_has_a_1_extension_looking_up_2_instead: diag(6262, 3 /* Message */, "File_name_0_has_a_1_extension_looking_up_2_instead_6262", "File name '{0}' has a '{1}' extension - looking up '{2}' instead."), + Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set: diag(6263, 1 /* Error */, "Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set_6263", "Module '{0}' was resolved to '{1}', but '--allowArbitraryExtensions' is not set."), + Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present: diag(6264, 3 /* Message */, "Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present_6264", "Enable importing files with any extension, provided a declaration file is present."), + Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_node_modules_folder: diag(6265, 3 /* Message */, "Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_no_6265", "Resolving type reference directive for program that specifies custom typeRoots, skipping lookup in 'node_modules' folder."), + Option_0_can_only_be_specified_on_command_line: diag(6266, 1 /* Error */, "Option_0_can_only_be_specified_on_command_line_6266", "Option '{0}' can only be specified on command line."), + Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve: diag(6270, 3 /* Message */, "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270", "Directory '{0}' has no containing package.json scope. Imports will not resolve."), + Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1: diag(6271, 3 /* Message */, "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271", "Import specifier '{0}' does not exist in package.json scope at path '{1}'."), + Invalid_import_specifier_0_has_no_possible_resolutions: diag(6272, 3 /* Message */, "Invalid_import_specifier_0_has_no_possible_resolutions_6272", "Invalid import specifier '{0}' has no possible resolutions."), + package_json_scope_0_has_no_imports_defined: diag(6273, 3 /* Message */, "package_json_scope_0_has_no_imports_defined_6273", "package.json scope '{0}' has no imports defined."), + package_json_scope_0_explicitly_maps_specifier_1_to_null: diag(6274, 3 /* Message */, "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274", "package.json scope '{0}' explicitly maps specifier '{1}' to null."), + package_json_scope_0_has_invalid_type_for_target_of_specifier_1: diag(6275, 3 /* Message */, "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275", "package.json scope '{0}' has invalid type for target of specifier '{1}'"), + Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1: diag(6276, 3 /* Message */, "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276", "Export specifier '{0}' does not exist in package.json scope at path '{1}'."), + Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update: diag(6277, 3 /* Message */, "Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_i_6277", "Resolution of non-relative name failed; trying with modern Node resolution features disabled to see if npm library needs configuration update."), + There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings: diag(6278, 3 /* Message */, "There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278", `There are types at '{0}', but this result could not be resolved when respecting package.json "exports". The '{1}' library may need to update its package.json or typings.`), + Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_need_configuration_update: diag(6279, 3 /* Message */, "Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_ne_6279", "Resolution of non-relative name failed; trying with '--moduleResolution bundler' to see if project may need configuration update."), + There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setting_Consider_updating_to_node16_nodenext_or_bundler: diag(6280, 3 /* Message */, "There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setti_6280", "There are types at '{0}', but this result could not be resolved under your current 'moduleResolution' setting. Consider updating to 'node16', 'nodenext', or 'bundler'."), + package_json_has_a_peerDependencies_field: diag(6281, 3 /* Message */, "package_json_has_a_peerDependencies_field_6281", "'package.json' has a 'peerDependencies' field."), + Found_peerDependency_0_with_1_version: diag(6282, 3 /* Message */, "Found_peerDependency_0_with_1_version_6282", "Found peerDependency '{0}' with '{1}' version."), + Failed_to_find_peerDependency_0: diag(6283, 3 /* Message */, "Failed_to_find_peerDependency_0_6283", "Failed to find peerDependency '{0}'."), + Enable_project_compilation: diag(6302, 3 /* Message */, "Enable_project_compilation_6302", "Enable project compilation"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, 1 /* Error */, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, 1 /* Error */, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, 1 /* Error */, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", `Referenced project '{0}' must have setting "composite": true.`), + File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, 1 /* Error */, "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307", "File '{0}' is not listed within the file list of project '{1}'. Projects must list all files or use an 'include' pattern."), + Referenced_project_0_may_not_disable_emit: diag(6310, 1 /* Error */, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."), + Project_0_is_out_of_date_because_output_1_is_older_than_input_2: diag(6350, 3 /* Message */, "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350", "Project '{0}' is out of date because output '{1}' is older than input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2: diag(6351, 3 /* Message */, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than output '{2}'"), + Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, 3 /* Message */, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), + Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, 3 /* Message */, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), + Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, 3 /* Message */, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), + Projects_in_this_build_Colon_0: diag(6355, 3 /* Message */, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"), + A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, 3 /* Message */, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"), + A_non_dry_build_would_build_project_0: diag(6357, 3 /* Message */, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"), + Building_project_0: diag(6358, 3 /* Message */, "Building_project_0_6358", "Building project '{0}'..."), + Updating_output_timestamps_of_project_0: diag(6359, 3 /* Message */, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."), + Project_0_is_up_to_date: diag(6361, 3 /* Message */, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"), + Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, 3 /* Message */, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"), + Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, 3 /* Message */, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"), + Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, 3 /* Message */, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"), + Delete_the_outputs_of_all_projects: diag(6365, 3 /* Message */, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects."), + Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, 3 /* Message */, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"), + Option_build_must_be_the_first_command_line_argument: diag(6369, 1 /* Error */, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), + Options_0_and_1_cannot_be_combined: diag(6370, 1 /* Error */, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + Updating_unchanged_output_timestamps_of_project_0: diag(6371, 3 /* Message */, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."), + A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, 3 /* Message */, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"), + Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, 1 /* Error */, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"), + Composite_projects_may_not_disable_incremental_compilation: diag(6379, 1 /* Error */, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."), + Specify_file_to_store_incremental_compilation_information: diag(6380, 3 /* Message */, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"), + Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, 3 /* Message */, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"), + Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, 3 /* Message */, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), + Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, 3 /* Message */, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), + Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, 3 /* Message */, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), + _0_is_deprecated: diag( + 6385, + 2 /* Suggestion */, + "_0_is_deprecated_6385", + "'{0}' is deprecated.", + /*reportsUnnecessary*/ + void 0, + /*elidedInCompatabilityPyramid*/ + void 0, + /*reportsDeprecated*/ + true + ), + Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, 3 /* Message */, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag( + 6387, + 2 /* Suggestion */, + "The_signature_0_of_1_is_deprecated_6387", + "The signature '{0}' of '{1}' is deprecated.", + /*reportsUnnecessary*/ + void 0, + /*elidedInCompatabilityPyramid*/ + void 0, + /*reportsDeprecated*/ + true + ), + Project_0_is_being_forcibly_rebuilt: diag(6388, 3 /* Message */, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), + Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved: diag(6389, 3 /* Message */, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389", "Reusing resolution of module '{0}' from '{1}' of old program, it was not resolved."), + Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2: diag(6390, 3 /* Message */, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was successfully resolved to '{2}'."), + Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3: diag(6391, 3 /* Message */, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was successfully resolved to '{2}' with Package ID '{3}'."), + Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved: diag(6392, 3 /* Message */, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was not resolved."), + Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6393, 3 /* Message */, "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393", "Reusing resolution of module '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."), + Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6394, 3 /* Message */, "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394", "Reusing resolution of module '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."), + Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6395, 3 /* Message */, "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395", "Reusing resolution of module '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), + Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, 3 /* Message */, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."), + Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, 3 /* Message */, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."), + Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, 3 /* Message */, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), + Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted: diag(6399, 3 /* Message */, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399", "Project '{0}' is out of date because buildinfo file '{1}' indicates that some of the changes were not emitted"), + Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files: diag(6400, 3 /* Message */, "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400", "Project '{0}' is up to date but needs to update timestamps of output files that are older than input files"), + Project_0_is_out_of_date_because_there_was_error_reading_file_1: diag(6401, 3 /* Message */, "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401", "Project '{0}' is out of date because there was error reading file '{1}'"), + Resolving_in_0_mode_with_conditions_1: diag(6402, 3 /* Message */, "Resolving_in_0_mode_with_conditions_1_6402", "Resolving in {0} mode with conditions {1}."), + Matched_0_condition_1: diag(6403, 3 /* Message */, "Matched_0_condition_1_6403", "Matched '{0}' condition '{1}'."), + Using_0_subpath_1_with_target_2: diag(6404, 3 /* Message */, "Using_0_subpath_1_with_target_2_6404", "Using '{0}' subpath '{1}' with target '{2}'."), + Saw_non_matching_condition_0: diag(6405, 3 /* Message */, "Saw_non_matching_condition_0_6405", "Saw non-matching condition '{0}'."), + Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions: diag(6406, 3 /* Message */, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions_6406", "Project '{0}' is out of date because buildinfo file '{1}' indicates there is change in compilerOptions"), + Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noEmit_or_emitDeclarationOnly_to_be_set: diag(6407, 3 /* Message */, "Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noE_6407", "Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set."), + Use_the_package_json_exports_field_when_resolving_package_imports: diag(6408, 3 /* Message */, "Use_the_package_json_exports_field_when_resolving_package_imports_6408", "Use the package.json 'exports' field when resolving package imports."), + Use_the_package_json_imports_field_when_resolving_imports: diag(6409, 3 /* Message */, "Use_the_package_json_imports_field_when_resolving_imports_6409", "Use the package.json 'imports' field when resolving imports."), + Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports: diag(6410, 3 /* Message */, "Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports_6410", "Conditions to set in addition to the resolver-specific defaults when resolving imports."), + true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false: diag(6411, 3 /* Message */, "true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false_6411", "`true` when 'moduleResolution' is 'node16', 'nodenext', or 'bundler'; otherwise `false`."), + Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_but_not_any_more: diag(6412, 3 /* Message */, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_6412", "Project '{0}' is out of date because buildinfo file '{1}' indicates that file '{2}' was root file of compilation but not any more."), + Entering_conditional_exports: diag(6413, 3 /* Message */, "Entering_conditional_exports_6413", "Entering conditional exports."), + Resolved_under_condition_0: diag(6414, 3 /* Message */, "Resolved_under_condition_0_6414", "Resolved under condition '{0}'."), + Failed_to_resolve_under_condition_0: diag(6415, 3 /* Message */, "Failed_to_resolve_under_condition_0_6415", "Failed to resolve under condition '{0}'."), + Exiting_conditional_exports: diag(6416, 3 /* Message */, "Exiting_conditional_exports_6416", "Exiting conditional exports."), + Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0: diag(6417, 3 /* Message */, "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417", "Searching all ancestor node_modules directories for preferred extensions: {0}."), + Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0: diag(6418, 3 /* Message */, "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418", "Searching all ancestor node_modules directories for fallback extensions: {0}."), + Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors: diag(6419, 3 /* Message */, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419", "Project '{0}' is out of date because buildinfo file '{1}' indicates that program needs to report errors."), + Project_0_is_out_of_date_because_1: diag(6420, 3 /* Message */, "Project_0_is_out_of_date_because_1_6420", "Project '{0}' is out of date because {1}."), + Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_in_output_files: diag(6421, 3 /* Message */, "Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_i_6421", "Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files."), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, 3 /* Message */, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, 3 /* Message */, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, 3 /* Message */, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, 3 /* Message */, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), + File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, 1 /* Error */, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), + Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, 3 /* Message */, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."), + Consider_adding_a_declare_modifier_to_this_class: diag(6506, 3 /* Message */, "Consider_adding_a_declare_modifier_to_this_class_6506", "Consider adding a 'declare' modifier to this class."), + Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files: diag(6600, 3 /* Message */, "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600", "Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files."), + Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export: diag(6601, 3 /* Message */, "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601", "Allow 'import x from y' when a module doesn't have a default export."), + Allow_accessing_UMD_globals_from_modules: diag(6602, 3 /* Message */, "Allow_accessing_UMD_globals_from_modules_6602", "Allow accessing UMD globals from modules."), + Disable_error_reporting_for_unreachable_code: diag(6603, 3 /* Message */, "Disable_error_reporting_for_unreachable_code_6603", "Disable error reporting for unreachable code."), + Disable_error_reporting_for_unused_labels: diag(6604, 3 /* Message */, "Disable_error_reporting_for_unused_labels_6604", "Disable error reporting for unused labels."), + Ensure_use_strict_is_always_emitted: diag(6605, 3 /* Message */, "Ensure_use_strict_is_always_emitted_6605", "Ensure 'use strict' is always emitted."), + Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6606, 3 /* Message */, "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606", "Have recompiles in projects that use 'incremental' and 'watch' mode assume that changes within a file will only affect files directly depending on it."), + Specify_the_base_directory_to_resolve_non_relative_module_names: diag(6607, 3 /* Message */, "Specify_the_base_directory_to_resolve_non_relative_module_names_6607", "Specify the base directory to resolve non-relative module names."), + No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files: diag(6608, 3 /* Message */, "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608", "No longer supported. In early versions, manually set the text encoding for reading files."), + Enable_error_reporting_in_type_checked_JavaScript_files: diag(6609, 3 /* Message */, "Enable_error_reporting_in_type_checked_JavaScript_files_6609", "Enable error reporting in type-checked JavaScript files."), + Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references: diag(6611, 3 /* Message */, "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611", "Enable constraints that allow a TypeScript project to be used with project references."), + Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project: diag(6612, 3 /* Message */, "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612", "Generate .d.ts files from TypeScript and JavaScript files in your project."), + Specify_the_output_directory_for_generated_declaration_files: diag(6613, 3 /* Message */, "Specify_the_output_directory_for_generated_declaration_files_6613", "Specify the output directory for generated declaration files."), + Create_sourcemaps_for_d_ts_files: diag(6614, 3 /* Message */, "Create_sourcemaps_for_d_ts_files_6614", "Create sourcemaps for d.ts files."), + Output_compiler_performance_information_after_building: diag(6615, 3 /* Message */, "Output_compiler_performance_information_after_building_6615", "Output compiler performance information after building."), + Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project: diag(6616, 3 /* Message */, "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616", "Disables inference for type acquisition by looking at filenames in a project."), + Reduce_the_number_of_projects_loaded_automatically_by_TypeScript: diag(6617, 3 /* Message */, "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617", "Reduce the number of projects loaded automatically by TypeScript."), + Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server: diag(6618, 3 /* Message */, "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618", "Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server."), + Opt_a_project_out_of_multi_project_reference_checking_when_editing: diag(6619, 3 /* Message */, "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619", "Opt a project out of multi-project reference checking when editing."), + Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects: diag(6620, 3 /* Message */, "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620", "Disable preferring source files instead of declaration files when referencing composite projects."), + Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration: diag(6621, 3 /* Message */, "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621", "Emit more compliant, but verbose and less performant JavaScript for iteration."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6622, 3 /* Message */, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Only_output_d_ts_files_and_not_JavaScript_files: diag(6623, 3 /* Message */, "Only_output_d_ts_files_and_not_JavaScript_files_6623", "Only output d.ts files and not JavaScript files."), + Emit_design_type_metadata_for_decorated_declarations_in_source_files: diag(6624, 3 /* Message */, "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624", "Emit design-type metadata for decorated declarations in source files."), + Disable_the_type_acquisition_for_JavaScript_projects: diag(6625, 3 /* Message */, "Disable_the_type_acquisition_for_JavaScript_projects_6625", "Disable the type acquisition for JavaScript projects"), + Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility: diag(6626, 3 /* Message */, "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626", "Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility."), + Filters_results_from_the_include_option: diag(6627, 3 /* Message */, "Filters_results_from_the_include_option_6627", "Filters results from the `include` option."), + Remove_a_list_of_directories_from_the_watch_process: diag(6628, 3 /* Message */, "Remove_a_list_of_directories_from_the_watch_process_6628", "Remove a list of directories from the watch process."), + Remove_a_list_of_files_from_the_watch_mode_s_processing: diag(6629, 3 /* Message */, "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629", "Remove a list of files from the watch mode's processing."), + Enable_experimental_support_for_legacy_experimental_decorators: diag(6630, 3 /* Message */, "Enable_experimental_support_for_legacy_experimental_decorators_6630", "Enable experimental support for legacy experimental decorators."), + Print_files_read_during_the_compilation_including_why_it_was_included: diag(6631, 3 /* Message */, "Print_files_read_during_the_compilation_including_why_it_was_included_6631", "Print files read during the compilation including why it was included."), + Output_more_detailed_compiler_performance_information_after_building: diag(6632, 3 /* Message */, "Output_more_detailed_compiler_performance_information_after_building_6632", "Output more detailed compiler performance information after building."), + Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_are_inherited: diag(6633, 3 /* Message */, "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633", "Specify one or more path or node module references to base configuration files from which settings are inherited."), + Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers: diag(6634, 3 /* Message */, "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634", "Specify what approach the watcher should use if the system runs out of native file watchers."), + Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include: diag(6635, 3 /* Message */, "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635", "Include a list of files. This does not support glob patterns, as opposed to `include`."), + Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6636, 3 /* Message */, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636", "Build all projects, including those that appear to be up to date."), + Ensure_that_casing_is_correct_in_imports: diag(6637, 3 /* Message */, "Ensure_that_casing_is_correct_in_imports_6637", "Ensure that casing is correct in imports."), + Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging: diag(6638, 3 /* Message */, "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638", "Emit a v8 CPU profile of the compiler run for debugging."), + Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file: diag(6639, 3 /* Message */, "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639", "Allow importing helper functions from tslib once per project, instead of including them per-file."), + Skip_building_downstream_projects_on_error_in_upstream_project: diag(6640, 3 /* Message */, "Skip_building_downstream_projects_on_error_in_upstream_project_6640", "Skip building downstream projects on error in upstream project."), + Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation: diag(6641, 3 /* Message */, "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641", "Specify a list of glob patterns that match files to be included in compilation."), + Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects: diag(6642, 3 /* Message */, "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642", "Save .tsbuildinfo files to allow for incremental compilation of projects."), + Include_sourcemap_files_inside_the_emitted_JavaScript: diag(6643, 3 /* Message */, "Include_sourcemap_files_inside_the_emitted_JavaScript_6643", "Include sourcemap files inside the emitted JavaScript."), + Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript: diag(6644, 3 /* Message */, "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644", "Include source code in the sourcemaps inside the emitted JavaScript."), + Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports: diag(6645, 3 /* Message */, "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645", "Ensure that each file can be safely transpiled without relying on other imports."), + Specify_what_JSX_code_is_generated: diag(6646, 3 /* Message */, "Specify_what_JSX_code_is_generated_6646", "Specify what JSX code is generated."), + Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h: diag(6647, 3 /* Message */, "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647", "Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'."), + Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment: diag(6648, 3 /* Message */, "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648", "Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'."), + Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk: diag(6649, 3 /* Message */, "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649", "Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'."), + Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option: diag(6650, 3 /* Message */, "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650", "Make keyof only return strings instead of string, numbers or symbols. Legacy option."), + Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment: diag(6651, 3 /* Message */, "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651", "Specify a set of bundled library declaration files that describe the target runtime environment."), + Print_the_names_of_emitted_files_after_a_compilation: diag(6652, 3 /* Message */, "Print_the_names_of_emitted_files_after_a_compilation_6652", "Print the names of emitted files after a compilation."), + Print_all_of_the_files_read_during_the_compilation: diag(6653, 3 /* Message */, "Print_all_of_the_files_read_during_the_compilation_6653", "Print all of the files read during the compilation."), + Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit: diag(6654, 3 /* Message */, "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654", "Set the language of the messaging from TypeScript. This does not affect emit."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6655, 3 /* Message */, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs: diag(6656, 3 /* Message */, "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656", "Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'."), + Specify_what_module_code_is_generated: diag(6657, 3 /* Message */, "Specify_what_module_code_is_generated_6657", "Specify what module code is generated."), + Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier: diag(6658, 3 /* Message */, "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658", "Specify how TypeScript looks up a file from a given module specifier."), + Set_the_newline_character_for_emitting_files: diag(6659, 3 /* Message */, "Set_the_newline_character_for_emitting_files_6659", "Set the newline character for emitting files."), + Disable_emitting_files_from_a_compilation: diag(6660, 3 /* Message */, "Disable_emitting_files_from_a_compilation_6660", "Disable emitting files from a compilation."), + Disable_generating_custom_helper_functions_like_extends_in_compiled_output: diag(6661, 3 /* Message */, "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661", "Disable generating custom helper functions like '__extends' in compiled output."), + Disable_emitting_files_if_any_type_checking_errors_are_reported: diag(6662, 3 /* Message */, "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662", "Disable emitting files if any type checking errors are reported."), + Disable_truncating_types_in_error_messages: diag(6663, 3 /* Message */, "Disable_truncating_types_in_error_messages_6663", "Disable truncating types in error messages."), + Enable_error_reporting_for_fallthrough_cases_in_switch_statements: diag(6664, 3 /* Message */, "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664", "Enable error reporting for fallthrough cases in switch statements."), + Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type: diag(6665, 3 /* Message */, "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665", "Enable error reporting for expressions and declarations with an implied 'any' type."), + Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier: diag(6666, 3 /* Message */, "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666", "Ensure overriding members in derived classes are marked with an override modifier."), + Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function: diag(6667, 3 /* Message */, "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667", "Enable error reporting for codepaths that do not explicitly return in a function."), + Enable_error_reporting_when_this_is_given_the_type_any: diag(6668, 3 /* Message */, "Enable_error_reporting_when_this_is_given_the_type_any_6668", "Enable error reporting when 'this' is given the type 'any'."), + Disable_adding_use_strict_directives_in_emitted_JavaScript_files: diag(6669, 3 /* Message */, "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669", "Disable adding 'use strict' directives in emitted JavaScript files."), + Disable_including_any_library_files_including_the_default_lib_d_ts: diag(6670, 3 /* Message */, "Disable_including_any_library_files_including_the_default_lib_d_ts_6670", "Disable including any library files, including the default lib.d.ts."), + Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type: diag(6671, 3 /* Message */, "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671", "Enforces using indexed accessors for keys declared using an indexed type."), + Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project: diag(6672, 3 /* Message */, "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672", "Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6673, 3 /* Message */, "Disable_strict_checking_of_generic_signatures_in_function_types_6673", "Disable strict checking of generic signatures in function types."), + Add_undefined_to_a_type_when_accessed_using_an_index: diag(6674, 3 /* Message */, "Add_undefined_to_a_type_when_accessed_using_an_index_6674", "Add 'undefined' to a type when accessed using an index."), + Enable_error_reporting_when_local_variables_aren_t_read: diag(6675, 3 /* Message */, "Enable_error_reporting_when_local_variables_aren_t_read_6675", "Enable error reporting when local variables aren't read."), + Raise_an_error_when_a_function_parameter_isn_t_read: diag(6676, 3 /* Message */, "Raise_an_error_when_a_function_parameter_isn_t_read_6676", "Raise an error when a function parameter isn't read."), + Deprecated_setting_Use_outFile_instead: diag(6677, 3 /* Message */, "Deprecated_setting_Use_outFile_instead_6677", "Deprecated setting. Use 'outFile' instead."), + Specify_an_output_folder_for_all_emitted_files: diag(6678, 3 /* Message */, "Specify_an_output_folder_for_all_emitted_files_6678", "Specify an output folder for all emitted files."), + Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output: diag(6679, 3 /* Message */, "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679", "Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output."), + Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations: diag(6680, 3 /* Message */, "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680", "Specify a set of entries that re-map imports to additional lookup locations."), + Specify_a_list_of_language_service_plugins_to_include: diag(6681, 3 /* Message */, "Specify_a_list_of_language_service_plugins_to_include_6681", "Specify a list of language service plugins to include."), + Disable_erasing_const_enum_declarations_in_generated_code: diag(6682, 3 /* Message */, "Disable_erasing_const_enum_declarations_in_generated_code_6682", "Disable erasing 'const enum' declarations in generated code."), + Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node: diag(6683, 3 /* Message */, "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683", "Disable resolving symlinks to their realpath. This correlates to the same flag in node."), + Disable_wiping_the_console_in_watch_mode: diag(6684, 3 /* Message */, "Disable_wiping_the_console_in_watch_mode_6684", "Disable wiping the console in watch mode."), + Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read: diag(6685, 3 /* Message */, "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685", "Enable color and formatting in TypeScript's output to make compiler errors easier to read."), + Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit: diag(6686, 3 /* Message */, "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686", "Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit."), + Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references: diag(6687, 3 /* Message */, "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687", "Specify an array of objects that specify paths for projects. Used in project references."), + Disable_emitting_comments: diag(6688, 3 /* Message */, "Disable_emitting_comments_6688", "Disable emitting comments."), + Enable_importing_json_files: diag(6689, 3 /* Message */, "Enable_importing_json_files_6689", "Enable importing .json files."), + Specify_the_root_folder_within_your_source_files: diag(6690, 3 /* Message */, "Specify_the_root_folder_within_your_source_files_6690", "Specify the root folder within your source files."), + Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules: diag(6691, 3 /* Message */, "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691", "Allow multiple folders to be treated as one when resolving modules."), + Skip_type_checking_d_ts_files_that_are_included_with_TypeScript: diag(6692, 3 /* Message */, "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692", "Skip type checking .d.ts files that are included with TypeScript."), + Skip_type_checking_all_d_ts_files: diag(6693, 3 /* Message */, "Skip_type_checking_all_d_ts_files_6693", "Skip type checking all .d.ts files."), + Create_source_map_files_for_emitted_JavaScript_files: diag(6694, 3 /* Message */, "Create_source_map_files_for_emitted_JavaScript_files_6694", "Create source map files for emitted JavaScript files."), + Specify_the_root_path_for_debuggers_to_find_the_reference_source_code: diag(6695, 3 /* Message */, "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695", "Specify the root path for debuggers to find the reference source code."), + Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function: diag(6697, 3 /* Message */, "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697", "Check that the arguments for 'bind', 'call', and 'apply' methods match the original function."), + When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible: diag(6698, 3 /* Message */, "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698", "When assigning functions, check to ensure parameters and the return values are subtype-compatible."), + When_type_checking_take_into_account_null_and_undefined: diag(6699, 3 /* Message */, "When_type_checking_take_into_account_null_and_undefined_6699", "When type checking, take into account 'null' and 'undefined'."), + Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor: diag(6700, 3 /* Message */, "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700", "Check for class properties that are declared but not set in the constructor."), + Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments: diag(6701, 3 /* Message */, "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701", "Disable emitting declarations that have '@internal' in their JSDoc comments."), + Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals: diag(6702, 3 /* Message */, "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702", "Disable reporting of excess property errors during the creation of object literals."), + Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures: diag(6703, 3 /* Message */, "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703", "Suppress 'noImplicitAny' errors when indexing objects that lack index signatures."), + Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6704, 3 /* Message */, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704", "Synchronously call callbacks and update the state of directory watchers on platforms that don`t support recursive watching natively."), + Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations: diag(6705, 3 /* Message */, "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705", "Set the JavaScript language version for emitted JavaScript and include compatible library declarations."), + Log_paths_used_during_the_moduleResolution_process: diag(6706, 3 /* Message */, "Log_paths_used_during_the_moduleResolution_process_6706", "Log paths used during the 'moduleResolution' process."), + Specify_the_path_to_tsbuildinfo_incremental_compilation_file: diag(6707, 3 /* Message */, "Specify_the_path_to_tsbuildinfo_incremental_compilation_file_6707", "Specify the path to .tsbuildinfo incremental compilation file."), + Specify_options_for_automatic_acquisition_of_declaration_files: diag(6709, 3 /* Message */, "Specify_options_for_automatic_acquisition_of_declaration_files_6709", "Specify options for automatic acquisition of declaration files."), + Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types: diag(6710, 3 /* Message */, "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710", "Specify multiple folders that act like './node_modules/@types'."), + Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file: diag(6711, 3 /* Message */, "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711", "Specify type package names to be included without being referenced in a source file."), + Emit_ECMAScript_standard_compliant_class_fields: diag(6712, 3 /* Message */, "Emit_ECMAScript_standard_compliant_class_fields_6712", "Emit ECMAScript-standard-compliant class fields."), + Enable_verbose_logging: diag(6713, 3 /* Message */, "Enable_verbose_logging_6713", "Enable verbose logging."), + Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality: diag(6714, 3 /* Message */, "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714", "Specify how directories are watched on systems that lack recursive file-watching functionality."), + Specify_how_the_TypeScript_watch_mode_works: diag(6715, 3 /* Message */, "Specify_how_the_TypeScript_watch_mode_works_6715", "Specify how the TypeScript watch mode works."), + Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6717, 3 /* Message */, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717", "Require undeclared properties from index signatures to use element accesses."), + Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(6718, 3 /* Message */, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718", "Specify emit/checking behavior for imports that are only used for types."), + Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files: diag(6719, 3 /* Message */, "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719", "Require sufficient annotation on exports so other tools can trivially generate declaration files."), + Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any: diag(6720, 3 /* Message */, "Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any_6720", "Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'."), + Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript: diag(6721, 3 /* Message */, "Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript_6721", "Do not allow runtime constructs that are not part of ECMAScript."), + Default_catch_clause_variables_as_unknown_instead_of_any: diag(6803, 3 /* Message */, "Default_catch_clause_variables_as_unknown_instead_of_any_6803", "Default catch clause variables as 'unknown' instead of 'any'."), + Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_in_the_output_file_s_format_based_on_the_module_setting: diag(6804, 3 /* Message */, "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804", "Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting."), + Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported: diag(6805, 3 /* Message */, "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805", "Disable full type checking (only critical parse and emit errors will be reported)."), + Check_side_effect_imports: diag(6806, 3 /* Message */, "Check_side_effect_imports_6806", "Check side effect imports."), + This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2: diag(6807, 1 /* Error */, "This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2_6807", "This operation can be simplified. This shift is identical to `{0} {1} {2}`."), + Enable_lib_replacement: diag(6808, 3 /* Message */, "Enable_lib_replacement_6808", "Enable lib replacement."), + one_of_Colon: diag(6900, 3 /* Message */, "one_of_Colon_6900", "one of:"), + one_or_more_Colon: diag(6901, 3 /* Message */, "one_or_more_Colon_6901", "one or more:"), + type_Colon: diag(6902, 3 /* Message */, "type_Colon_6902", "type:"), + default_Colon: diag(6903, 3 /* Message */, "default_Colon_6903", "default:"), + module_system_or_esModuleInterop: diag(6904, 3 /* Message */, "module_system_or_esModuleInterop_6904", 'module === "system" or esModuleInterop'), + false_unless_strict_is_set: diag(6905, 3 /* Message */, "false_unless_strict_is_set_6905", "`false`, unless `strict` is set"), + false_unless_composite_is_set: diag(6906, 3 /* Message */, "false_unless_composite_is_set_6906", "`false`, unless `composite` is set"), + node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified: diag(6907, 3 /* Message */, "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907", '`["node_modules", "bower_components", "jspm_packages"]`, plus the value of `outDir` if one is specified.'), + if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk: diag(6908, 3 /* Message */, "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908", '`[]` if `files` is specified, otherwise `["**/*"]`'), + true_if_composite_false_otherwise: diag(6909, 3 /* Message */, "true_if_composite_false_otherwise_6909", "`true` if `composite`, `false` otherwise"), + module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node: diag(69010, 3 /* Message */, "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010", "module === `AMD` or `UMD` or `System` or `ES6`, then `Classic`, Otherwise `Node`"), + Computed_from_the_list_of_input_files: diag(6911, 3 /* Message */, "Computed_from_the_list_of_input_files_6911", "Computed from the list of input files"), + Platform_specific: diag(6912, 3 /* Message */, "Platform_specific_6912", "Platform specific"), + You_can_learn_about_all_of_the_compiler_options_at_0: diag(6913, 3 /* Message */, "You_can_learn_about_all_of_the_compiler_options_at_0_6913", "You can learn about all of the compiler options at {0}"), + Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_config_watch_mode_with_Colon: diag(6914, 3 /* Message */, "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914", "Including --watch, -w will start watching the current project for the file changes. Once set, you can config watch mode with:"), + Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0: diag(6915, 3 /* Message */, "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915", "Using --build, -b will make tsc behave more like a build orchestrator than a compiler. This is used to trigger building composite projects which you can learn more about at {0}"), + COMMON_COMMANDS: diag(6916, 3 /* Message */, "COMMON_COMMANDS_6916", "COMMON COMMANDS"), + ALL_COMPILER_OPTIONS: diag(6917, 3 /* Message */, "ALL_COMPILER_OPTIONS_6917", "ALL COMPILER OPTIONS"), + WATCH_OPTIONS: diag(6918, 3 /* Message */, "WATCH_OPTIONS_6918", "WATCH OPTIONS"), + BUILD_OPTIONS: diag(6919, 3 /* Message */, "BUILD_OPTIONS_6919", "BUILD OPTIONS"), + COMMON_COMPILER_OPTIONS: diag(6920, 3 /* Message */, "COMMON_COMPILER_OPTIONS_6920", "COMMON COMPILER OPTIONS"), + COMMAND_LINE_FLAGS: diag(6921, 3 /* Message */, "COMMAND_LINE_FLAGS_6921", "COMMAND LINE FLAGS"), + tsc_Colon_The_TypeScript_Compiler: diag(6922, 3 /* Message */, "tsc_Colon_The_TypeScript_Compiler_6922", "tsc: The TypeScript Compiler"), + Compiles_the_current_project_tsconfig_json_in_the_working_directory: diag(6923, 3 /* Message */, "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923", "Compiles the current project (tsconfig.json in the working directory.)"), + Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options: diag(6924, 3 /* Message */, "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924", "Ignoring tsconfig.json, compiles the specified files with default compiler options."), + Build_a_composite_project_in_the_working_directory: diag(6925, 3 /* Message */, "Build_a_composite_project_in_the_working_directory_6925", "Build a composite project in the working directory."), + Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory: diag(6926, 3 /* Message */, "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926", "Creates a tsconfig.json with the recommended settings in the working directory."), + Compiles_the_TypeScript_project_located_at_the_specified_path: diag(6927, 3 /* Message */, "Compiles_the_TypeScript_project_located_at_the_specified_path_6927", "Compiles the TypeScript project located at the specified path."), + An_expanded_version_of_this_information_showing_all_possible_compiler_options: diag(6928, 3 /* Message */, "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928", "An expanded version of this information, showing all possible compiler options"), + Compiles_the_current_project_with_additional_settings: diag(6929, 3 /* Message */, "Compiles_the_current_project_with_additional_settings_6929", "Compiles the current project, with additional settings."), + true_for_ES2022_and_above_including_ESNext: diag(6930, 3 /* Message */, "true_for_ES2022_and_above_including_ESNext_6930", "`true` for ES2022 and above, including ESNext."), + List_of_file_name_suffixes_to_search_when_resolving_a_module: diag(6931, 1 /* Error */, "List_of_file_name_suffixes_to_search_when_resolving_a_module_6931", "List of file name suffixes to search when resolving a module."), + Variable_0_implicitly_has_an_1_type: diag(7005, 1 /* Error */, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, 1 /* Error */, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, 1 /* Error */, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, 1 /* Error */, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, 1 /* Error */, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, 1 /* Error */, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation: diag(7012, 1 /* Error */, "This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation_7012", "This overload implicitly returns the type '{0}' because it lacks a return type annotation."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, 1 /* Error */, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7014, 1 /* Error */, "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014", "Function type, which lacks return-type annotation, implicitly has an '{0}' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, 1 /* Error */, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, 1 /* Error */, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, 1 /* Error */, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, 1 /* Error */, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, 1 /* Error */, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, 1 /* Error */, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, 1 /* Error */, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, 1 /* Error */, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, 1 /* Error */, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), + Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation: diag(7025, 1 /* Error */, "Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation_7025", "Generator implicitly has yield type '{0}'. Consider supplying a return type annotation."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, 1 /* Error */, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag( + 7027, + 1 /* Error */, + "Unreachable_code_detected_7027", + "Unreachable code detected.", + /*reportsUnnecessary*/ + true + ), + Unused_label: diag( + 7028, + 1 /* Error */, + "Unused_label_7028", + "Unused label.", + /*reportsUnnecessary*/ + true + ), + Fallthrough_case_in_switch: diag(7029, 1 /* Error */, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, 1 /* Error */, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, 1 /* Error */, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, 1 /* Error */, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, 1 /* Error */, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, 1 /* Error */, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, 1 /* Error */, "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035", "Try `npm i --save-dev @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, 1 /* Error */, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, 3 /* Message */, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, 3 /* Message */, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, 1 /* Error */, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, 1 /* Error */, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), + The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, 1 /* Error */, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, 1 /* Error */, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), + Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, 2 /* Suggestion */, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, 2 /* Suggestion */, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7045, 2 /* Suggestion */, "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045", "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), + Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage: diag(7046, 2 /* Suggestion */, "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046", "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."), + Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage: diag(7047, 2 /* Suggestion */, "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047", "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage: diag(7048, 2 /* Suggestion */, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048", "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."), + Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage: diag(7049, 2 /* Suggestion */, "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049", "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."), + _0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage: diag(7050, 2 /* Suggestion */, "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050", "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."), + Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1: diag(7051, 1 /* Error */, "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051", "Parameter has a name but no type. Did you mean '{0}: {1}'?"), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1: diag(7052, 1 /* Error */, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052", "Element implicitly has an 'any' type because type '{0}' has no index signature. Did you mean to call '{1}'?"), + Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1: diag(7053, 1 /* Error */, "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053", "Element implicitly has an 'any' type because expression of type '{0}' can't be used to index type '{1}'."), + No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1: diag(7054, 1 /* Error */, "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054", "No index signature with a parameter of type '{0}' was found on type '{1}'."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type: diag(7055, 1 /* Error */, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055", "'{0}', which lacks return-type annotation, implicitly has an '{1}' yield type."), + The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed: diag(7056, 1 /* Error */, "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056", "The inferred type of this node exceeds the maximum length the compiler will serialize. An explicit type annotation is needed."), + yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation: diag(7057, 1 /* Error */, "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057", "'yield' expression implicitly results in an 'any' type because its containing generator lacks a return-type annotation."), + If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1: diag(7058, 1 /* Error */, "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058", "If the '{0}' package actually exposes this module, try adding a new declaration (.d.ts) file containing `declare module '{1}';`"), + This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead: diag(7059, 1 /* Error */, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059", "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead."), + This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint: diag(7060, 1 /* Error */, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060", "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint."), + A_mapped_type_may_not_declare_properties_or_methods: diag(7061, 1 /* Error */, "A_mapped_type_may_not_declare_properties_or_methods_7061", "A mapped type may not declare properties or methods."), + You_cannot_rename_this_element: diag(8e3, 1 /* Error */, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, 1 /* Error */, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_TypeScript_files: diag(8002, 1 /* Error */, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."), + export_can_only_be_used_in_TypeScript_files: diag(8003, 1 /* Error */, "export_can_only_be_used_in_TypeScript_files_8003", "'export =' can only be used in TypeScript files."), + Type_parameter_declarations_can_only_be_used_in_TypeScript_files: diag(8004, 1 /* Error */, "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004", "Type parameter declarations can only be used in TypeScript files."), + implements_clauses_can_only_be_used_in_TypeScript_files: diag(8005, 1 /* Error */, "implements_clauses_can_only_be_used_in_TypeScript_files_8005", "'implements' clauses can only be used in TypeScript files."), + _0_declarations_can_only_be_used_in_TypeScript_files: diag(8006, 1 /* Error */, "_0_declarations_can_only_be_used_in_TypeScript_files_8006", "'{0}' declarations can only be used in TypeScript files."), + Type_aliases_can_only_be_used_in_TypeScript_files: diag(8008, 1 /* Error */, "Type_aliases_can_only_be_used_in_TypeScript_files_8008", "Type aliases can only be used in TypeScript files."), + The_0_modifier_can_only_be_used_in_TypeScript_files: diag(8009, 1 /* Error */, "The_0_modifier_can_only_be_used_in_TypeScript_files_8009", "The '{0}' modifier can only be used in TypeScript files."), + Type_annotations_can_only_be_used_in_TypeScript_files: diag(8010, 1 /* Error */, "Type_annotations_can_only_be_used_in_TypeScript_files_8010", "Type annotations can only be used in TypeScript files."), + Type_arguments_can_only_be_used_in_TypeScript_files: diag(8011, 1 /* Error */, "Type_arguments_can_only_be_used_in_TypeScript_files_8011", "Type arguments can only be used in TypeScript files."), + Parameter_modifiers_can_only_be_used_in_TypeScript_files: diag(8012, 1 /* Error */, "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012", "Parameter modifiers can only be used in TypeScript files."), + Non_null_assertions_can_only_be_used_in_TypeScript_files: diag(8013, 1 /* Error */, "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013", "Non-null assertions can only be used in TypeScript files."), + Type_assertion_expressions_can_only_be_used_in_TypeScript_files: diag(8016, 1 /* Error */, "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016", "Type assertion expressions can only be used in TypeScript files."), + Signature_declarations_can_only_be_used_in_TypeScript_files: diag(8017, 1 /* Error */, "Signature_declarations_can_only_be_used_in_TypeScript_files_8017", "Signature declarations can only be used in TypeScript files."), + Report_errors_in_js_files: diag(8019, 3 /* Message */, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, 1 /* Error */, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, 1 /* Error */, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), + JSDoc_0_is_not_attached_to_a_class: diag(8022, 1 /* Error */, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), + JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, 1 /* Error */, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, 1 /* Error */, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, 1 /* Error */, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), + Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, 1 /* Error */, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), + Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, 1 /* Error */, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), + JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, 1 /* Error */, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), + JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, 1 /* Error */, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, 1 /* Error */, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, 1 /* Error */, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, 1 /* Error */, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), + A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, 1 /* Error */, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."), + The_tag_was_first_specified_here: diag(8034, 1 /* Error */, "The_tag_was_first_specified_here_8034", "The tag was first specified here."), + You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder: diag(8035, 1 /* Error */, "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035", "You cannot rename elements that are defined in a 'node_modules' folder."), + You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, 1 /* Error */, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), + Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files: diag(8037, 1 /* Error */, "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037", "Type satisfaction expressions can only be used in TypeScript files."), + Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export: diag(8038, 1 /* Error */, "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038", "Decorators may not appear after 'export' or 'export default' if they also appear before 'export'."), + A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag: diag(8039, 1 /* Error */, "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039", "A JSDoc '@template' tag may not follow a '@typedef', '@callback', or '@overload' tag"), + Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), + Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), + Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations: diag(9007, 1 /* Error */, "Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9007", "Function must have an explicit return type annotation with --isolatedDeclarations."), + Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations: diag(9008, 1 /* Error */, "Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9008", "Method must have an explicit return type annotation with --isolatedDeclarations."), + At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations: diag(9009, 1 /* Error */, "At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9009", "At least one accessor must have an explicit type annotation with --isolatedDeclarations."), + Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations: diag(9010, 1 /* Error */, "Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9010", "Variable must have an explicit type annotation with --isolatedDeclarations."), + Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations: diag(9011, 1 /* Error */, "Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9011", "Parameter must have an explicit type annotation with --isolatedDeclarations."), + Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations: diag(9012, 1 /* Error */, "Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9012", "Property must have an explicit type annotation with --isolatedDeclarations."), + Expression_type_can_t_be_inferred_with_isolatedDeclarations: diag(9013, 1 /* Error */, "Expression_type_can_t_be_inferred_with_isolatedDeclarations_9013", "Expression type can't be inferred with --isolatedDeclarations."), + Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations: diag(9014, 1 /* Error */, "Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedD_9014", "Computed properties must be number or string literals, variables or dotted expressions with --isolatedDeclarations."), + Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations: diag(9015, 1 /* Error */, "Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations_9015", "Objects that contain spread assignments can't be inferred with --isolatedDeclarations."), + Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations: diag(9016, 1 /* Error */, "Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations_9016", "Objects that contain shorthand properties can't be inferred with --isolatedDeclarations."), + Only_const_arrays_can_be_inferred_with_isolatedDeclarations: diag(9017, 1 /* Error */, "Only_const_arrays_can_be_inferred_with_isolatedDeclarations_9017", "Only const arrays can be inferred with --isolatedDeclarations."), + Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations: diag(9018, 1 /* Error */, "Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations_9018", "Arrays with spread elements can't inferred with --isolatedDeclarations."), + Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations: diag(9019, 1 /* Error */, "Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations_9019", "Binding elements can't be exported directly with --isolatedDeclarations."), + Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDeclarations: diag(9020, 1 /* Error */, "Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDecl_9020", "Enum member initializers must be computable without references to external symbols with --isolatedDeclarations."), + Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations: diag(9021, 1 /* Error */, "Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations_9021", "Extends clause can't contain an expression with --isolatedDeclarations."), + Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations: diag(9022, 1 /* Error */, "Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations_9022", "Inference from class expressions is not supported with --isolatedDeclarations."), + Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations_Add_an_explicit_declaration_for_the_properties_assigned_to_this_function: diag(9023, 1 /* Error */, "Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations__9023", "Assigning properties to functions without declaring them is not supported with --isolatedDeclarations. Add an explicit declaration for the properties assigned to this function."), + Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_supported_with_isolatedDeclarations: diag(9025, 1 /* Error */, "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_sup_9025", "Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations."), + Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_supported_with_isolatedDeclarations: diag(9026, 1 /* Error */, "Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_support_9026", "Declaration emit for this file requires preserving this import for augmentations. This is not supported with --isolatedDeclarations."), + Add_a_type_annotation_to_the_variable_0: diag(9027, 1 /* Error */, "Add_a_type_annotation_to_the_variable_0_9027", "Add a type annotation to the variable {0}."), + Add_a_type_annotation_to_the_parameter_0: diag(9028, 1 /* Error */, "Add_a_type_annotation_to_the_parameter_0_9028", "Add a type annotation to the parameter {0}."), + Add_a_type_annotation_to_the_property_0: diag(9029, 1 /* Error */, "Add_a_type_annotation_to_the_property_0_9029", "Add a type annotation to the property {0}."), + Add_a_return_type_to_the_function_expression: diag(9030, 1 /* Error */, "Add_a_return_type_to_the_function_expression_9030", "Add a return type to the function expression."), + Add_a_return_type_to_the_function_declaration: diag(9031, 1 /* Error */, "Add_a_return_type_to_the_function_declaration_9031", "Add a return type to the function declaration."), + Add_a_return_type_to_the_get_accessor_declaration: diag(9032, 1 /* Error */, "Add_a_return_type_to_the_get_accessor_declaration_9032", "Add a return type to the get accessor declaration."), + Add_a_type_to_parameter_of_the_set_accessor_declaration: diag(9033, 1 /* Error */, "Add_a_type_to_parameter_of_the_set_accessor_declaration_9033", "Add a type to parameter of the set accessor declaration."), + Add_a_return_type_to_the_method: diag(9034, 1 /* Error */, "Add_a_return_type_to_the_method_9034", "Add a return type to the method"), + Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit: diag(9035, 1 /* Error */, "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035", "Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit."), + Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it: diag(9036, 1 /* Error */, "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036", "Move the expression in default export to a variable and add a type annotation to it."), + Default_exports_can_t_be_inferred_with_isolatedDeclarations: diag(9037, 1 /* Error */, "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037", "Default exports can't be inferred with --isolatedDeclarations."), + Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations: diag(9038, 1 /* Error */, "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038", "Computed property names on class or object literals cannot be inferred with --isolatedDeclarations."), + Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations: diag(9039, 1 /* Error */, "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039", "Type containing private name '{0}' can't be used with --isolatedDeclarations."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17e3, 1 /* Error */, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, 1 /* Error */, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, 1 /* Error */, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, 1 /* Error */, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, 1 /* Error */, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, 1 /* Error */, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, 1 /* Error */, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, 1 /* Error */, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, 1 /* Error */, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, 1 /* Error */, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, 1 /* Error */, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, 1 /* Error */, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, 1 /* Error */, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + JSX_fragment_has_no_corresponding_closing_tag: diag(17014, 1 /* Error */, "JSX_fragment_has_no_corresponding_closing_tag_17014", "JSX fragment has no corresponding closing tag."), + Expected_corresponding_closing_tag_for_JSX_fragment: diag(17015, 1 /* Error */, "Expected_corresponding_closing_tag_for_JSX_fragment_17015", "Expected corresponding closing tag for JSX fragment."), + The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option: diag(17016, 1 /* Error */, "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016", "The 'jsxFragmentFactory' compiler option must be provided to use JSX fragments with the 'jsxFactory' compiler option."), + An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments: diag(17017, 1 /* Error */, "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017", "An @jsxFrag pragma is required when using an @jsx pragma with JSX fragments."), + Unknown_type_acquisition_option_0_Did_you_mean_1: diag(17018, 1 /* Error */, "Unknown_type_acquisition_option_0_Did_you_mean_1_17018", "Unknown type acquisition option '{0}'. Did you mean '{1}'?"), + _0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1: diag(17019, 1 /* Error */, "_0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17019", "'{0}' at the end of a type is not valid TypeScript syntax. Did you mean to write '{1}'?"), + _0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1: diag(17020, 1 /* Error */, "_0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17020", "'{0}' at the start of a type is not valid TypeScript syntax. Did you mean to write '{1}'?"), + Unicode_escape_sequence_cannot_appear_here: diag(17021, 1 /* Error */, "Unicode_escape_sequence_cannot_appear_here_17021", "Unicode escape sequence cannot appear here."), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18e3, 1 /* Error */, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + The_files_list_in_config_file_0_is_empty: diag(18002, 1 /* Error */, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, 1 /* Error */, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module: diag(80001, 2 /* Suggestion */, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", "File is a CommonJS module; it may be converted to an ES module."), + This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, 2 /* Suggestion */, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), + Import_may_be_converted_to_a_default_import: diag(80003, 2 /* Suggestion */, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), + JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, 2 /* Suggestion */, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), + require_call_may_be_converted_to_an_import: diag(80005, 2 /* Suggestion */, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, 2 /* Suggestion */, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), + await_has_no_effect_on_the_type_of_this_expression: diag(80007, 2 /* Suggestion */, "await_has_no_effect_on_the_type_of_this_expression_80007", "'await' has no effect on the type of this expression."), + Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers: diag(80008, 2 /* Suggestion */, "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008", "Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers."), + JSDoc_typedef_may_be_converted_to_TypeScript_type: diag(80009, 2 /* Suggestion */, "JSDoc_typedef_may_be_converted_to_TypeScript_type_80009", "JSDoc typedef may be converted to TypeScript type."), + JSDoc_typedefs_may_be_converted_to_TypeScript_types: diag(80010, 2 /* Suggestion */, "JSDoc_typedefs_may_be_converted_to_TypeScript_types_80010", "JSDoc typedefs may be converted to TypeScript types."), + Add_missing_super_call: diag(90001, 3 /* Message */, "Add_missing_super_call_90001", "Add missing 'super()' call"), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, 3 /* Message */, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), + Change_extends_to_implements: diag(90003, 3 /* Message */, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), + Remove_unused_declaration_for_Colon_0: diag(90004, 3 /* Message */, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"), + Remove_import_from_0: diag(90005, 3 /* Message */, "Remove_import_from_0_90005", "Remove import from '{0}'"), + Implement_interface_0: diag(90006, 3 /* Message */, "Implement_interface_0_90006", "Implement interface '{0}'"), + Implement_inherited_abstract_class: diag(90007, 3 /* Message */, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), + Add_0_to_unresolved_variable: diag(90008, 3 /* Message */, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_variable_statement: diag(90010, 3 /* Message */, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, 3 /* Message */, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, 3 /* Message */, "Remove_type_parameters_90012", "Remove type parameters"), + Import_0_from_1: diag(90013, 3 /* Message */, "Import_0_from_1_90013", `Import '{0}' from "{1}"`), + Change_0_to_1: diag(90014, 3 /* Message */, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), + Declare_property_0: diag(90016, 3 /* Message */, "Declare_property_0_90016", "Declare property '{0}'"), + Add_index_signature_for_property_0: diag(90017, 3 /* Message */, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), + Disable_checking_for_this_file: diag(90018, 3 /* Message */, "Disable_checking_for_this_file_90018", "Disable checking for this file"), + Ignore_this_error_message: diag(90019, 3 /* Message */, "Ignore_this_error_message_90019", "Ignore this error message"), + Initialize_property_0_in_the_constructor: diag(90020, 3 /* Message */, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"), + Initialize_static_property_0: diag(90021, 3 /* Message */, "Initialize_static_property_0_90021", "Initialize static property '{0}'"), + Change_spelling_to_0: diag(90022, 3 /* Message */, "Change_spelling_to_0_90022", "Change spelling to '{0}'"), + Declare_method_0: diag(90023, 3 /* Message */, "Declare_method_0_90023", "Declare method '{0}'"), + Declare_static_method_0: diag(90024, 3 /* Message */, "Declare_static_method_0_90024", "Declare static method '{0}'"), + Prefix_0_with_an_underscore: diag(90025, 3 /* Message */, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"), + Rewrite_as_the_indexed_access_type_0: diag(90026, 3 /* Message */, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), + Declare_static_property_0: diag(90027, 3 /* Message */, "Declare_static_property_0_90027", "Declare static property '{0}'"), + Call_decorator_expression: diag(90028, 3 /* Message */, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, 3 /* Message */, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, 3 /* Message */, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, 3 /* Message */, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Add_parameter_name: diag(90034, 3 /* Message */, "Add_parameter_name_90034", "Add parameter name"), + Declare_private_property_0: diag(90035, 3 /* Message */, "Declare_private_property_0_90035", "Declare private property '{0}'"), + Replace_0_with_Promise_1: diag(90036, 3 /* Message */, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"), + Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, 3 /* Message */, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"), + Declare_private_method_0: diag(90038, 3 /* Message */, "Declare_private_method_0_90038", "Declare private method '{0}'"), + Remove_unused_destructuring_declaration: diag(90039, 3 /* Message */, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"), + Remove_unused_declarations_for_Colon_0: diag(90041, 3 /* Message */, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"), + Declare_a_private_field_named_0: diag(90053, 3 /* Message */, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), + Includes_imports_of_types_referenced_by_0: diag(90054, 3 /* Message */, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"), + Remove_type_from_import_declaration_from_0: diag(90055, 3 /* Message */, "Remove_type_from_import_declaration_from_0_90055", `Remove 'type' from import declaration from "{0}"`), + Remove_type_from_import_of_0_from_1: diag(90056, 3 /* Message */, "Remove_type_from_import_of_0_from_1_90056", `Remove 'type' from import of '{0}' from "{1}"`), + Add_import_from_0: diag(90057, 3 /* Message */, "Add_import_from_0_90057", 'Add import from "{0}"'), + Update_import_from_0: diag(90058, 3 /* Message */, "Update_import_from_0_90058", 'Update import from "{0}"'), + Export_0_from_module_1: diag(90059, 3 /* Message */, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), + Export_all_referenced_locals: diag(90060, 3 /* Message */, "Export_all_referenced_locals_90060", "Export all referenced locals"), + Update_modifiers_of_0: diag(90061, 3 /* Message */, "Update_modifiers_of_0_90061", "Update modifiers of '{0}'"), + Add_annotation_of_type_0: diag(90062, 3 /* Message */, "Add_annotation_of_type_0_90062", "Add annotation of type '{0}'"), + Add_return_type_0: diag(90063, 3 /* Message */, "Add_return_type_0_90063", "Add return type '{0}'"), + Extract_base_class_to_variable: diag(90064, 3 /* Message */, "Extract_base_class_to_variable_90064", "Extract base class to variable"), + Extract_default_export_to_variable: diag(90065, 3 /* Message */, "Extract_default_export_to_variable_90065", "Extract default export to variable"), + Extract_binding_expressions_to_variable: diag(90066, 3 /* Message */, "Extract_binding_expressions_to_variable_90066", "Extract binding expressions to variable"), + Add_all_missing_type_annotations: diag(90067, 3 /* Message */, "Add_all_missing_type_annotations_90067", "Add all missing type annotations"), + Add_satisfies_and_an_inline_type_assertion_with_0: diag(90068, 3 /* Message */, "Add_satisfies_and_an_inline_type_assertion_with_0_90068", "Add satisfies and an inline type assertion with '{0}'"), + Extract_to_variable_and_replace_with_0_as_typeof_0: diag(90069, 3 /* Message */, "Extract_to_variable_and_replace_with_0_as_typeof_0_90069", "Extract to variable and replace with '{0} as typeof {0}'"), + Mark_array_literal_as_const: diag(90070, 3 /* Message */, "Mark_array_literal_as_const_90070", "Mark array literal as const"), + Annotate_types_of_properties_expando_function_in_a_namespace: diag(90071, 3 /* Message */, "Annotate_types_of_properties_expando_function_in_a_namespace_90071", "Annotate types of properties expando function in a namespace"), + Convert_function_to_an_ES2015_class: diag(95001, 3 /* Message */, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_0_to_1_in_0: diag(95003, 3 /* Message */, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), + Extract_to_0_in_1: diag(95004, 3 /* Message */, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), + Extract_function: diag(95005, 3 /* Message */, "Extract_function_95005", "Extract function"), + Extract_constant: diag(95006, 3 /* Message */, "Extract_constant_95006", "Extract constant"), + Extract_to_0_in_enclosing_scope: diag(95007, 3 /* Message */, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"), + Extract_to_0_in_1_scope: diag(95008, 3 /* Message */, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"), + Annotate_with_type_from_JSDoc: diag(95009, 3 /* Message */, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"), + Infer_type_of_0_from_usage: diag(95011, 3 /* Message */, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"), + Infer_parameter_types_from_usage: diag(95012, 3 /* Message */, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), + Convert_to_default_import: diag(95013, 3 /* Message */, "Convert_to_default_import_95013", "Convert to default import"), + Install_0: diag(95014, 3 /* Message */, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, 3 /* Message */, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, 3 /* Message */, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES_module: diag(95017, 3 /* Message */, "Convert_to_ES_module_95017", "Convert to ES module"), + Add_undefined_type_to_property_0: diag(95018, 3 /* Message */, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), + Add_initializer_to_property_0: diag(95019, 3 /* Message */, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), + Add_definite_assignment_assertion_to_property_0: diag(95020, 3 /* Message */, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Convert_all_type_literals_to_mapped_type: diag(95021, 3 /* Message */, "Convert_all_type_literals_to_mapped_type_95021", "Convert all type literals to mapped type"), + Add_all_missing_members: diag(95022, 3 /* Message */, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, 3 /* Message */, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, 3 /* Message */, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, 3 /* Message */, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, 3 /* Message */, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, 3 /* Message */, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, 3 /* Message */, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, 3 /* Message */, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, 3 /* Message */, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, 3 /* Message */, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, 3 /* Message */, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, 3 /* Message */, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, 3 /* Message */, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, 3 /* Message */, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, 3 /* Message */, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, 3 /* Message */, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, 3 /* Message */, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, 3 /* Message */, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, 3 /* Message */, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, 3 /* Message */, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, 3 /* Message */, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, 3 /* Message */, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, 3 /* Message */, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, 3 /* Message */, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), + Generate_get_and_set_accessors: diag(95046, 3 /* Message */, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), + Convert_require_to_import: diag(95047, 3 /* Message */, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), + Convert_all_require_to_import: diag(95048, 3 /* Message */, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, 3 /* Message */, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, 3 /* Message */, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, 3 /* Message */, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, 3 /* Message */, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, 3 /* Message */, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, 3 /* Message */, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, 3 /* Message */, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), + Convert_namespace_import_to_named_imports: diag(95056, 3 /* Message */, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"), + Convert_named_imports_to_namespace_import: diag(95057, 3 /* Message */, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"), + Add_or_remove_braces_in_an_arrow_function: diag(95058, 3 /* Message */, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), + Add_braces_to_arrow_function: diag(95059, 3 /* Message */, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), + Remove_braces_from_arrow_function: diag(95060, 3 /* Message */, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, 3 /* Message */, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, 3 /* Message */, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, 3 /* Message */, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, 3 /* Message */, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, 3 /* Message */, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, 3 /* Message */, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Add_missing_call_parentheses: diag(95067, 3 /* Message */, "Add_missing_call_parentheses_95067", "Add missing call parentheses"), + Add_all_missing_call_parentheses: diag(95068, 3 /* Message */, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"), + Add_unknown_conversion_for_non_overlapping_types: diag(95069, 3 /* Message */, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), + Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, 3 /* Message */, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), + Add_missing_new_operator_to_call: diag(95071, 3 /* Message */, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), + Add_missing_new_operator_to_all_calls: diag(95072, 3 /* Message */, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), + Add_names_to_all_parameters_without_names: diag(95073, 3 /* Message */, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, 3 /* Message */, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"), + Convert_parameters_to_destructured_object: diag(95075, 3 /* Message */, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"), + Extract_type: diag(95077, 3 /* Message */, "Extract_type_95077", "Extract type"), + Extract_to_type_alias: diag(95078, 3 /* Message */, "Extract_to_type_alias_95078", "Extract to type alias"), + Extract_to_typedef: diag(95079, 3 /* Message */, "Extract_to_typedef_95079", "Extract to typedef"), + Infer_this_type_of_0_from_usage: diag(95080, 3 /* Message */, "Infer_this_type_of_0_from_usage_95080", "Infer 'this' type of '{0}' from usage"), + Add_const_to_unresolved_variable: diag(95081, 3 /* Message */, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"), + Add_const_to_all_unresolved_variables: diag(95082, 3 /* Message */, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"), + Add_await: diag(95083, 3 /* Message */, "Add_await_95083", "Add 'await'"), + Add_await_to_initializer_for_0: diag(95084, 3 /* Message */, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"), + Fix_all_expressions_possibly_missing_await: diag(95085, 3 /* Message */, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"), + Remove_unnecessary_await: diag(95086, 3 /* Message */, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"), + Remove_all_unnecessary_uses_of_await: diag(95087, 3 /* Message */, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"), + Enable_the_jsx_flag_in_your_configuration_file: diag(95088, 3 /* Message */, "Enable_the_jsx_flag_in_your_configuration_file_95088", "Enable the '--jsx' flag in your configuration file"), + Add_await_to_initializers: diag(95089, 3 /* Message */, "Add_await_to_initializers_95089", "Add 'await' to initializers"), + Extract_to_interface: diag(95090, 3 /* Message */, "Extract_to_interface_95090", "Extract to interface"), + Convert_to_a_bigint_numeric_literal: diag(95091, 3 /* Message */, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"), + Convert_all_to_bigint_numeric_literals: diag(95092, 3 /* Message */, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"), + Convert_const_to_let: diag(95093, 3 /* Message */, "Convert_const_to_let_95093", "Convert 'const' to 'let'"), + Prefix_with_declare: diag(95094, 3 /* Message */, "Prefix_with_declare_95094", "Prefix with 'declare'"), + Prefix_all_incorrect_property_declarations_with_declare: diag(95095, 3 /* Message */, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"), + Convert_to_template_string: diag(95096, 3 /* Message */, "Convert_to_template_string_95096", "Convert to template string"), + Add_export_to_make_this_file_into_a_module: diag(95097, 3 /* Message */, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"), + Set_the_target_option_in_your_configuration_file_to_0: diag(95098, 3 /* Message */, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"), + Set_the_module_option_in_your_configuration_file_to_0: diag(95099, 3 /* Message */, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"), + Convert_invalid_character_to_its_html_entity_code: diag(95100, 3 /* Message */, "Convert_invalid_character_to_its_html_entity_code_95100", "Convert invalid character to its html entity code"), + Convert_all_invalid_characters_to_HTML_entity_code: diag(95101, 3 /* Message */, "Convert_all_invalid_characters_to_HTML_entity_code_95101", "Convert all invalid characters to HTML entity code"), + Convert_all_const_to_let: diag(95102, 3 /* Message */, "Convert_all_const_to_let_95102", "Convert all 'const' to 'let'"), + Convert_function_expression_0_to_arrow_function: diag(95105, 3 /* Message */, "Convert_function_expression_0_to_arrow_function_95105", "Convert function expression '{0}' to arrow function"), + Convert_function_declaration_0_to_arrow_function: diag(95106, 3 /* Message */, "Convert_function_declaration_0_to_arrow_function_95106", "Convert function declaration '{0}' to arrow function"), + Fix_all_implicit_this_errors: diag(95107, 3 /* Message */, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"), + Wrap_invalid_character_in_an_expression_container: diag(95108, 3 /* Message */, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"), + Wrap_all_invalid_characters_in_an_expression_container: diag(95109, 3 /* Message */, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"), + Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file: diag(95110, 3 /* Message */, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig to read more about this file"), + Add_a_return_statement: diag(95111, 3 /* Message */, "Add_a_return_statement_95111", "Add a return statement"), + Remove_braces_from_arrow_function_body: diag(95112, 3 /* Message */, "Remove_braces_from_arrow_function_body_95112", "Remove braces from arrow function body"), + Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, 3 /* Message */, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"), + Add_all_missing_return_statement: diag(95114, 3 /* Message */, "Add_all_missing_return_statement_95114", "Add all missing return statement"), + Remove_braces_from_all_arrow_function_bodies_with_relevant_issues: diag(95115, 3 /* Message */, "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115", "Remove braces from all arrow function bodies with relevant issues"), + Wrap_all_object_literal_with_parentheses: diag(95116, 3 /* Message */, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"), + Move_labeled_tuple_element_modifiers_to_labels: diag(95117, 3 /* Message */, "Move_labeled_tuple_element_modifiers_to_labels_95117", "Move labeled tuple element modifiers to labels"), + Convert_overload_list_to_single_signature: diag(95118, 3 /* Message */, "Convert_overload_list_to_single_signature_95118", "Convert overload list to single signature"), + Generate_get_and_set_accessors_for_all_overriding_properties: diag(95119, 3 /* Message */, "Generate_get_and_set_accessors_for_all_overriding_properties_95119", "Generate 'get' and 'set' accessors for all overriding properties"), + Wrap_in_JSX_fragment: diag(95120, 3 /* Message */, "Wrap_in_JSX_fragment_95120", "Wrap in JSX fragment"), + Wrap_all_unparented_JSX_in_JSX_fragment: diag(95121, 3 /* Message */, "Wrap_all_unparented_JSX_in_JSX_fragment_95121", "Wrap all unparented JSX in JSX fragment"), + Convert_arrow_function_or_function_expression: diag(95122, 3 /* Message */, "Convert_arrow_function_or_function_expression_95122", "Convert arrow function or function expression"), + Convert_to_anonymous_function: diag(95123, 3 /* Message */, "Convert_to_anonymous_function_95123", "Convert to anonymous function"), + Convert_to_named_function: diag(95124, 3 /* Message */, "Convert_to_named_function_95124", "Convert to named function"), + Convert_to_arrow_function: diag(95125, 3 /* Message */, "Convert_to_arrow_function_95125", "Convert to arrow function"), + Remove_parentheses: diag(95126, 3 /* Message */, "Remove_parentheses_95126", "Remove parentheses"), + Could_not_find_a_containing_arrow_function: diag(95127, 3 /* Message */, "Could_not_find_a_containing_arrow_function_95127", "Could not find a containing arrow function"), + Containing_function_is_not_an_arrow_function: diag(95128, 3 /* Message */, "Containing_function_is_not_an_arrow_function_95128", "Containing function is not an arrow function"), + Could_not_find_export_statement: diag(95129, 3 /* Message */, "Could_not_find_export_statement_95129", "Could not find export statement"), + This_file_already_has_a_default_export: diag(95130, 3 /* Message */, "This_file_already_has_a_default_export_95130", "This file already has a default export"), + Could_not_find_import_clause: diag(95131, 3 /* Message */, "Could_not_find_import_clause_95131", "Could not find import clause"), + Could_not_find_namespace_import_or_named_imports: diag(95132, 3 /* Message */, "Could_not_find_namespace_import_or_named_imports_95132", "Could not find namespace import or named imports"), + Selection_is_not_a_valid_type_node: diag(95133, 3 /* Message */, "Selection_is_not_a_valid_type_node_95133", "Selection is not a valid type node"), + No_type_could_be_extracted_from_this_type_node: diag(95134, 3 /* Message */, "No_type_could_be_extracted_from_this_type_node_95134", "No type could be extracted from this type node"), + Could_not_find_property_for_which_to_generate_accessor: diag(95135, 3 /* Message */, "Could_not_find_property_for_which_to_generate_accessor_95135", "Could not find property for which to generate accessor"), + Name_is_not_valid: diag(95136, 3 /* Message */, "Name_is_not_valid_95136", "Name is not valid"), + Can_only_convert_property_with_modifier: diag(95137, 3 /* Message */, "Can_only_convert_property_with_modifier_95137", "Can only convert property with modifier"), + Switch_each_misused_0_to_1: diag(95138, 3 /* Message */, "Switch_each_misused_0_to_1_95138", "Switch each misused '{0}' to '{1}'"), + Convert_to_optional_chain_expression: diag(95139, 3 /* Message */, "Convert_to_optional_chain_expression_95139", "Convert to optional chain expression"), + Could_not_find_convertible_access_expression: diag(95140, 3 /* Message */, "Could_not_find_convertible_access_expression_95140", "Could not find convertible access expression"), + Could_not_find_matching_access_expressions: diag(95141, 3 /* Message */, "Could_not_find_matching_access_expressions_95141", "Could not find matching access expressions"), + Can_only_convert_logical_AND_access_chains: diag(95142, 3 /* Message */, "Can_only_convert_logical_AND_access_chains_95142", "Can only convert logical AND access chains"), + Add_void_to_Promise_resolved_without_a_value: diag(95143, 3 /* Message */, "Add_void_to_Promise_resolved_without_a_value_95143", "Add 'void' to Promise resolved without a value"), + Add_void_to_all_Promises_resolved_without_a_value: diag(95144, 3 /* Message */, "Add_void_to_all_Promises_resolved_without_a_value_95144", "Add 'void' to all Promises resolved without a value"), + Use_element_access_for_0: diag(95145, 3 /* Message */, "Use_element_access_for_0_95145", "Use element access for '{0}'"), + Use_element_access_for_all_undeclared_properties: diag(95146, 3 /* Message */, "Use_element_access_for_all_undeclared_properties_95146", "Use element access for all undeclared properties."), + Delete_all_unused_imports: diag(95147, 3 /* Message */, "Delete_all_unused_imports_95147", "Delete all unused imports"), + Infer_function_return_type: diag(95148, 3 /* Message */, "Infer_function_return_type_95148", "Infer function return type"), + Return_type_must_be_inferred_from_a_function: diag(95149, 3 /* Message */, "Return_type_must_be_inferred_from_a_function_95149", "Return type must be inferred from a function"), + Could_not_determine_function_return_type: diag(95150, 3 /* Message */, "Could_not_determine_function_return_type_95150", "Could not determine function return type"), + Could_not_convert_to_arrow_function: diag(95151, 3 /* Message */, "Could_not_convert_to_arrow_function_95151", "Could not convert to arrow function"), + Could_not_convert_to_named_function: diag(95152, 3 /* Message */, "Could_not_convert_to_named_function_95152", "Could not convert to named function"), + Could_not_convert_to_anonymous_function: diag(95153, 3 /* Message */, "Could_not_convert_to_anonymous_function_95153", "Could not convert to anonymous function"), + Can_only_convert_string_concatenations_and_string_literals: diag(95154, 3 /* Message */, "Can_only_convert_string_concatenations_and_string_literals_95154", "Can only convert string concatenations and string literals"), + Selection_is_not_a_valid_statement_or_statements: diag(95155, 3 /* Message */, "Selection_is_not_a_valid_statement_or_statements_95155", "Selection is not a valid statement or statements"), + Add_missing_function_declaration_0: diag(95156, 3 /* Message */, "Add_missing_function_declaration_0_95156", "Add missing function declaration '{0}'"), + Add_all_missing_function_declarations: diag(95157, 3 /* Message */, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"), + Method_not_implemented: diag(95158, 3 /* Message */, "Method_not_implemented_95158", "Method not implemented."), + Function_not_implemented: diag(95159, 3 /* Message */, "Function_not_implemented_95159", "Function not implemented."), + Add_override_modifier: diag(95160, 3 /* Message */, "Add_override_modifier_95160", "Add 'override' modifier"), + Remove_override_modifier: diag(95161, 3 /* Message */, "Remove_override_modifier_95161", "Remove 'override' modifier"), + Add_all_missing_override_modifiers: diag(95162, 3 /* Message */, "Add_all_missing_override_modifiers_95162", "Add all missing 'override' modifiers"), + Remove_all_unnecessary_override_modifiers: diag(95163, 3 /* Message */, "Remove_all_unnecessary_override_modifiers_95163", "Remove all unnecessary 'override' modifiers"), + Can_only_convert_named_export: diag(95164, 3 /* Message */, "Can_only_convert_named_export_95164", "Can only convert named export"), + Add_missing_properties: diag(95165, 3 /* Message */, "Add_missing_properties_95165", "Add missing properties"), + Add_all_missing_properties: diag(95166, 3 /* Message */, "Add_all_missing_properties_95166", "Add all missing properties"), + Add_missing_attributes: diag(95167, 3 /* Message */, "Add_missing_attributes_95167", "Add missing attributes"), + Add_all_missing_attributes: diag(95168, 3 /* Message */, "Add_all_missing_attributes_95168", "Add all missing attributes"), + Add_undefined_to_optional_property_type: diag(95169, 3 /* Message */, "Add_undefined_to_optional_property_type_95169", "Add 'undefined' to optional property type"), + Convert_named_imports_to_default_import: diag(95170, 3 /* Message */, "Convert_named_imports_to_default_import_95170", "Convert named imports to default import"), + Delete_unused_param_tag_0: diag(95171, 3 /* Message */, "Delete_unused_param_tag_0_95171", "Delete unused '@param' tag '{0}'"), + Delete_all_unused_param_tags: diag(95172, 3 /* Message */, "Delete_all_unused_param_tags_95172", "Delete all unused '@param' tags"), + Rename_param_tag_name_0_to_1: diag(95173, 3 /* Message */, "Rename_param_tag_name_0_to_1_95173", "Rename '@param' tag name '{0}' to '{1}'"), + Use_0: diag(95174, 3 /* Message */, "Use_0_95174", "Use `{0}`."), + Use_Number_isNaN_in_all_conditions: diag(95175, 3 /* Message */, "Use_Number_isNaN_in_all_conditions_95175", "Use `Number.isNaN` in all conditions."), + Convert_typedef_to_TypeScript_type: diag(95176, 3 /* Message */, "Convert_typedef_to_TypeScript_type_95176", "Convert typedef to TypeScript type."), + Convert_all_typedef_to_TypeScript_types: diag(95177, 3 /* Message */, "Convert_all_typedef_to_TypeScript_types_95177", "Convert all typedef to TypeScript types."), + Move_to_file: diag(95178, 3 /* Message */, "Move_to_file_95178", "Move to file"), + Cannot_move_to_file_selected_file_is_invalid: diag(95179, 3 /* Message */, "Cannot_move_to_file_selected_file_is_invalid_95179", "Cannot move to file, selected file is invalid"), + Use_import_type: diag(95180, 3 /* Message */, "Use_import_type_95180", "Use 'import type'"), + Use_type_0: diag(95181, 3 /* Message */, "Use_type_0_95181", "Use 'type {0}'"), + Fix_all_with_type_only_imports: diag(95182, 3 /* Message */, "Fix_all_with_type_only_imports_95182", "Fix all with type-only imports"), + Cannot_move_statements_to_the_selected_file: diag(95183, 3 /* Message */, "Cannot_move_statements_to_the_selected_file_95183", "Cannot move statements to the selected file"), + Inline_variable: diag(95184, 3 /* Message */, "Inline_variable_95184", "Inline variable"), + Could_not_find_variable_to_inline: diag(95185, 3 /* Message */, "Could_not_find_variable_to_inline_95185", "Could not find variable to inline."), + Variables_with_multiple_declarations_cannot_be_inlined: diag(95186, 3 /* Message */, "Variables_with_multiple_declarations_cannot_be_inlined_95186", "Variables with multiple declarations cannot be inlined."), + Add_missing_comma_for_object_member_completion_0: diag(95187, 3 /* Message */, "Add_missing_comma_for_object_member_completion_0_95187", "Add missing comma for object member completion '{0}'."), + Add_missing_parameter_to_0: diag(95188, 3 /* Message */, "Add_missing_parameter_to_0_95188", "Add missing parameter to '{0}'"), + Add_missing_parameters_to_0: diag(95189, 3 /* Message */, "Add_missing_parameters_to_0_95189", "Add missing parameters to '{0}'"), + Add_all_missing_parameters: diag(95190, 3 /* Message */, "Add_all_missing_parameters_95190", "Add all missing parameters"), + Add_optional_parameter_to_0: diag(95191, 3 /* Message */, "Add_optional_parameter_to_0_95191", "Add optional parameter to '{0}'"), + Add_optional_parameters_to_0: diag(95192, 3 /* Message */, "Add_optional_parameters_to_0_95192", "Add optional parameters to '{0}'"), + Add_all_optional_parameters: diag(95193, 3 /* Message */, "Add_all_optional_parameters_95193", "Add all optional parameters"), + Wrap_in_parentheses: diag(95194, 3 /* Message */, "Wrap_in_parentheses_95194", "Wrap in parentheses"), + Wrap_all_invalid_decorator_expressions_in_parentheses: diag(95195, 3 /* Message */, "Wrap_all_invalid_decorator_expressions_in_parentheses_95195", "Wrap all invalid decorator expressions in parentheses"), + Add_resolution_mode_import_attribute: diag(95196, 3 /* Message */, "Add_resolution_mode_import_attribute_95196", "Add 'resolution-mode' import attribute"), + Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it: diag(95197, 3 /* Message */, "Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it_95197", "Add 'resolution-mode' import attribute to all type-only imports that need it"), + No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, 1 /* Error */, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), + Classes_may_not_have_a_field_named_constructor: diag(18006, 1 /* Error */, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), + JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, 1 /* Error */, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), + Private_identifiers_cannot_be_used_as_parameters: diag(18009, 1 /* Error */, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters."), + An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, 1 /* Error */, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."), + The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, 1 /* Error */, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."), + constructor_is_a_reserved_word: diag(18012, 1 /* Error */, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."), + Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier: diag(18013, 1 /* Error */, "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013", "Property '{0}' is not accessible outside class '{1}' because it has a private identifier."), + The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling: diag(18014, 1 /* Error */, "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014", "The property '{0}' cannot be accessed on type '{1}' within this class because it is shadowed by another private identifier with the same spelling."), + Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2: diag(18015, 1 /* Error */, "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015", "Property '{0}' in type '{1}' refers to a different member that cannot be accessed from within type '{2}'."), + Private_identifiers_are_not_allowed_outside_class_bodies: diag(18016, 1 /* Error */, "Private_identifiers_are_not_allowed_outside_class_bodies_18016", "Private identifiers are not allowed outside class bodies."), + The_shadowing_declaration_of_0_is_defined_here: diag(18017, 1 /* Error */, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"), + The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, 1 /* Error */, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"), + _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, 1 /* Error */, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier."), + An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, 1 /* Error */, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), + can_only_be_used_at_the_start_of_a_file: diag(18026, 1 /* Error */, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), + Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, 1 /* Error */, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), + Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, 1 /* Error */, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), + Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, 1 /* Error */, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), + An_optional_chain_cannot_contain_private_identifiers: diag(18030, 1 /* Error */, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."), + The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, 1 /* Error */, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."), + The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, 1 /* Error */, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."), + Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values: diag(18033, 1 /* Error */, "Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values_18033", "Type '{0}' is not assignable to type '{1}' as required for computed enum member values."), + Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, 3 /* Message */, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."), + Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, 1 /* Error */, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."), + Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, 1 /* Error */, "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."), + await_expression_cannot_be_used_inside_a_class_static_block: diag(18037, 1 /* Error */, "await_expression_cannot_be_used_inside_a_class_static_block_18037", "'await' expression cannot be used inside a class static block."), + for_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, 1 /* Error */, "for_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'for await' loops cannot be used inside a class static block."), + Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, 1 /* Error */, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."), + A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, 1 /* Error */, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."), + _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, 1 /* Error */, "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), + Types_cannot_appear_in_export_declarations_in_JavaScript_files: diag(18043, 1 /* Error */, "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043", "Types cannot appear in export declarations in JavaScript files."), + _0_is_automatically_exported_here: diag(18044, 3 /* Message */, "_0_is_automatically_exported_here_18044", "'{0}' is automatically exported here."), + Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18045, 1 /* Error */, "Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher_18045", "Properties with the 'accessor' modifier are only available when targeting ECMAScript 2015 and higher."), + _0_is_of_type_unknown: diag(18046, 1 /* Error */, "_0_is_of_type_unknown_18046", "'{0}' is of type 'unknown'."), + _0_is_possibly_null: diag(18047, 1 /* Error */, "_0_is_possibly_null_18047", "'{0}' is possibly 'null'."), + _0_is_possibly_undefined: diag(18048, 1 /* Error */, "_0_is_possibly_undefined_18048", "'{0}' is possibly 'undefined'."), + _0_is_possibly_null_or_undefined: diag(18049, 1 /* Error */, "_0_is_possibly_null_or_undefined_18049", "'{0}' is possibly 'null' or 'undefined'."), + The_value_0_cannot_be_used_here: diag(18050, 1 /* Error */, "The_value_0_cannot_be_used_here_18050", "The value '{0}' cannot be used here."), + Compiler_option_0_cannot_be_given_an_empty_string: diag(18051, 1 /* Error */, "Compiler_option_0_cannot_be_given_an_empty_string_18051", "Compiler option '{0}' cannot be given an empty string."), + Its_type_0_is_not_a_valid_JSX_element_type: diag(18053, 1 /* Error */, "Its_type_0_is_not_a_valid_JSX_element_type_18053", "Its type '{0}' is not a valid JSX element type."), + await_using_statements_cannot_be_used_inside_a_class_static_block: diag(18054, 1 /* Error */, "await_using_statements_cannot_be_used_inside_a_class_static_block_18054", "'await using' statements cannot be used inside a class static block."), + _0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is_enabled: diag(18055, 1 /* Error */, "_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is__18055", "'{0}' has a string type, but must have syntactically recognizable string syntax when 'isolatedModules' is enabled."), + Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is_enabled: diag(18056, 1 /* Error */, "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056", "Enum member following a non-literal numeric member must have an initializer when 'isolatedModules' is enabled."), + String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es2020: diag(18057, 1 /* Error */, "String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es_18057", "String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'.") +}; + +// src/compiler/scanner.ts +function tokenIsIdentifierOrKeyword(token) { + return token >= 80 /* Identifier */; +} +function tokenIsIdentifierOrKeywordOrGreaterThan(token) { + return token === 32 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); +} +var textToKeywordObj = { + abstract: 128 /* AbstractKeyword */, + accessor: 129 /* AccessorKeyword */, + any: 133 /* AnyKeyword */, + as: 130 /* AsKeyword */, + asserts: 131 /* AssertsKeyword */, + assert: 132 /* AssertKeyword */, + bigint: 163 /* BigIntKeyword */, + boolean: 136 /* BooleanKeyword */, + break: 83 /* BreakKeyword */, + case: 84 /* CaseKeyword */, + catch: 85 /* CatchKeyword */, + class: 86 /* ClassKeyword */, + continue: 88 /* ContinueKeyword */, + const: 87 /* ConstKeyword */, + ["constructor"]: 137 /* ConstructorKeyword */, + debugger: 89 /* DebuggerKeyword */, + declare: 138 /* DeclareKeyword */, + default: 90 /* DefaultKeyword */, + delete: 91 /* DeleteKeyword */, + do: 92 /* DoKeyword */, + else: 93 /* ElseKeyword */, + enum: 94 /* EnumKeyword */, + export: 95 /* ExportKeyword */, + extends: 96 /* ExtendsKeyword */, + false: 97 /* FalseKeyword */, + finally: 98 /* FinallyKeyword */, + for: 99 /* ForKeyword */, + from: 161 /* FromKeyword */, + function: 100 /* FunctionKeyword */, + get: 139 /* GetKeyword */, + if: 101 /* IfKeyword */, + implements: 119 /* ImplementsKeyword */, + import: 102 /* ImportKeyword */, + in: 103 /* InKeyword */, + infer: 140 /* InferKeyword */, + instanceof: 104 /* InstanceOfKeyword */, + interface: 120 /* InterfaceKeyword */, + intrinsic: 141 /* IntrinsicKeyword */, + is: 142 /* IsKeyword */, + keyof: 143 /* KeyOfKeyword */, + let: 121 /* LetKeyword */, + module: 144 /* ModuleKeyword */, + namespace: 145 /* NamespaceKeyword */, + never: 146 /* NeverKeyword */, + new: 105 /* NewKeyword */, + null: 106 /* NullKeyword */, + number: 150 /* NumberKeyword */, + object: 151 /* ObjectKeyword */, + package: 122 /* PackageKeyword */, + private: 123 /* PrivateKeyword */, + protected: 124 /* ProtectedKeyword */, + public: 125 /* PublicKeyword */, + override: 164 /* OverrideKeyword */, + out: 147 /* OutKeyword */, + readonly: 148 /* ReadonlyKeyword */, + require: 149 /* RequireKeyword */, + global: 162 /* GlobalKeyword */, + return: 107 /* ReturnKeyword */, + satisfies: 152 /* SatisfiesKeyword */, + set: 153 /* SetKeyword */, + static: 126 /* StaticKeyword */, + string: 154 /* StringKeyword */, + super: 108 /* SuperKeyword */, + switch: 109 /* SwitchKeyword */, + symbol: 155 /* SymbolKeyword */, + this: 110 /* ThisKeyword */, + throw: 111 /* ThrowKeyword */, + true: 112 /* TrueKeyword */, + try: 113 /* TryKeyword */, + type: 156 /* TypeKeyword */, + typeof: 114 /* TypeOfKeyword */, + undefined: 157 /* UndefinedKeyword */, + unique: 158 /* UniqueKeyword */, + unknown: 159 /* UnknownKeyword */, + using: 160 /* UsingKeyword */, + var: 115 /* VarKeyword */, + void: 116 /* VoidKeyword */, + while: 117 /* WhileKeyword */, + with: 118 /* WithKeyword */, + yield: 127 /* YieldKeyword */, + async: 134 /* AsyncKeyword */, + await: 135 /* AwaitKeyword */, + of: 165 /* OfKeyword */ +}; +var textToKeyword = new Map(Object.entries(textToKeywordObj)); +var textToToken = new Map(Object.entries({ + ...textToKeywordObj, + "{": 19 /* OpenBraceToken */, + "}": 20 /* CloseBraceToken */, + "(": 21 /* OpenParenToken */, + ")": 22 /* CloseParenToken */, + "[": 23 /* OpenBracketToken */, + "]": 24 /* CloseBracketToken */, + ".": 25 /* DotToken */, + "...": 26 /* DotDotDotToken */, + ";": 27 /* SemicolonToken */, + ",": 28 /* CommaToken */, + "<": 30 /* LessThanToken */, + ">": 32 /* GreaterThanToken */, + "<=": 33 /* LessThanEqualsToken */, + ">=": 34 /* GreaterThanEqualsToken */, + "==": 35 /* EqualsEqualsToken */, + "!=": 36 /* ExclamationEqualsToken */, + "===": 37 /* EqualsEqualsEqualsToken */, + "!==": 38 /* ExclamationEqualsEqualsToken */, + "=>": 39 /* EqualsGreaterThanToken */, + "+": 40 /* PlusToken */, + "-": 41 /* MinusToken */, + "**": 43 /* AsteriskAsteriskToken */, + "*": 42 /* AsteriskToken */, + "/": 44 /* SlashToken */, + "%": 45 /* PercentToken */, + "++": 46 /* PlusPlusToken */, + "--": 47 /* MinusMinusToken */, + "<<": 48 /* LessThanLessThanToken */, + ">": 49 /* GreaterThanGreaterThanToken */, + ">>>": 50 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 51 /* AmpersandToken */, + "|": 52 /* BarToken */, + "^": 53 /* CaretToken */, + "!": 54 /* ExclamationToken */, + "~": 55 /* TildeToken */, + "&&": 56 /* AmpersandAmpersandToken */, + "||": 57 /* BarBarToken */, + "?": 58 /* QuestionToken */, + "??": 61 /* QuestionQuestionToken */, + "?.": 29 /* QuestionDotToken */, + ":": 59 /* ColonToken */, + "=": 64 /* EqualsToken */, + "+=": 65 /* PlusEqualsToken */, + "-=": 66 /* MinusEqualsToken */, + "*=": 67 /* AsteriskEqualsToken */, + "**=": 68 /* AsteriskAsteriskEqualsToken */, + "/=": 69 /* SlashEqualsToken */, + "%=": 70 /* PercentEqualsToken */, + "<<=": 71 /* LessThanLessThanEqualsToken */, + ">>=": 72 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 74 /* AmpersandEqualsToken */, + "|=": 75 /* BarEqualsToken */, + "^=": 79 /* CaretEqualsToken */, + "||=": 76 /* BarBarEqualsToken */, + "&&=": 77 /* AmpersandAmpersandEqualsToken */, + "??=": 78 /* QuestionQuestionEqualsToken */, + "@": 60 /* AtToken */, + "#": 63 /* HashToken */, + "`": 62 /* BacktickToken */ +})); +var charCodeToRegExpFlag = /* @__PURE__ */ new Map([ + [100 /* d */, 1 /* HasIndices */], + [103 /* g */, 2 /* Global */], + [105 /* i */, 4 /* IgnoreCase */], + [109 /* m */, 8 /* Multiline */], + [115 /* s */, 16 /* DotAll */], + [117 /* u */, 32 /* Unicode */], + [118 /* v */, 64 /* UnicodeSets */], + [121 /* y */, 128 /* Sticky */] +]); +var regExpFlagToFirstAvailableLanguageVersion = /* @__PURE__ */ new Map([ + [1 /* HasIndices */, LanguageFeatureMinimumTarget.RegularExpressionFlagsHasIndices], + [16 /* DotAll */, LanguageFeatureMinimumTarget.RegularExpressionFlagsDotAll], + [32 /* Unicode */, LanguageFeatureMinimumTarget.RegularExpressionFlagsUnicode], + [64 /* UnicodeSets */, LanguageFeatureMinimumTarget.RegularExpressionFlagsUnicodeSets], + [128 /* Sticky */, LanguageFeatureMinimumTarget.RegularExpressionFlagsSticky] +]); +var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6e3, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43e3, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; +var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43e3, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; +var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2160, 2183, 2185, 2190, 2208, 2249, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3165, 3165, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3293, 3294, 3296, 3297, 3313, 3314, 3332, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5905, 5919, 5937, 5952, 5969, 5984, 5996, 5998, 6e3, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6988, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12735, 12784, 12799, 13312, 19903, 19968, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42954, 42960, 42961, 42963, 42963, 42965, 42969, 42994, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43881, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 66928, 66938, 66940, 66954, 66956, 66962, 66964, 66965, 66967, 66977, 66979, 66993, 66995, 67001, 67003, 67004, 67072, 67382, 67392, 67413, 67424, 67431, 67456, 67461, 67463, 67504, 67506, 67514, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69248, 69289, 69296, 69297, 69376, 69404, 69415, 69415, 69424, 69445, 69488, 69505, 69552, 69572, 69600, 69622, 69635, 69687, 69745, 69746, 69749, 69749, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69959, 69959, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70207, 70208, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70753, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71488, 71494, 71680, 71723, 71840, 71903, 71935, 71942, 71945, 71945, 71948, 71955, 71957, 71958, 71960, 71983, 71999, 71999, 72001, 72001, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72368, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73474, 73474, 73476, 73488, 73490, 73523, 73648, 73648, 73728, 74649, 74752, 74862, 74880, 75075, 77712, 77808, 77824, 78895, 78913, 78918, 82944, 83526, 92160, 92728, 92736, 92766, 92784, 92862, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101589, 101632, 101640, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 122624, 122654, 122661, 122666, 122928, 122989, 123136, 123180, 123191, 123197, 123214, 123214, 123536, 123565, 123584, 123627, 124112, 124139, 124896, 124902, 124904, 124907, 124909, 124910, 124912, 124926, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173791, 173824, 177977, 177984, 178205, 178208, 183969, 183984, 191456, 191472, 192093, 194560, 195101, 196608, 201546, 201552, 205743]; +var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2160, 2183, 2185, 2190, 2200, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2901, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3132, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3165, 3165, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3293, 3294, 3296, 3299, 3302, 3311, 3313, 3315, 3328, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3457, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3790, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5909, 5919, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6159, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6847, 6862, 6912, 6988, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12543, 12549, 12591, 12593, 12686, 12704, 12735, 12784, 12799, 13312, 19903, 19968, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42954, 42960, 42961, 42963, 42963, 42965, 42969, 42994, 43047, 43052, 43052, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43881, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 66928, 66938, 66940, 66954, 66956, 66962, 66964, 66965, 66967, 66977, 66979, 66993, 66995, 67001, 67003, 67004, 67072, 67382, 67392, 67413, 67424, 67431, 67456, 67461, 67463, 67504, 67506, 67514, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69248, 69289, 69291, 69292, 69296, 69297, 69373, 69404, 69415, 69415, 69424, 69456, 69488, 69509, 69552, 69572, 69600, 69622, 69632, 69702, 69734, 69749, 69759, 69818, 69826, 69826, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69959, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70094, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70209, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70753, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71488, 71494, 71680, 71738, 71840, 71913, 71935, 71942, 71945, 71945, 71948, 71955, 71957, 71958, 71960, 71989, 71991, 71992, 71995, 72003, 72016, 72025, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72368, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73472, 73488, 73490, 73530, 73534, 73538, 73552, 73561, 73648, 73648, 73728, 74649, 74752, 74862, 74880, 75075, 77712, 77808, 77824, 78895, 78912, 78933, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92784, 92862, 92864, 92873, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94180, 94192, 94193, 94208, 100343, 100352, 101589, 101632, 101640, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 118528, 118573, 118576, 118598, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122624, 122654, 122661, 122666, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 122928, 122989, 123023, 123023, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123536, 123566, 123584, 123641, 124112, 124153, 124896, 124902, 124904, 124907, 124909, 124910, 124912, 124926, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 130032, 130041, 131072, 173791, 173824, 177977, 177984, 178205, 178208, 183969, 183984, 191456, 191472, 192093, 194560, 195101, 196608, 201546, 201552, 205743, 917760, 917999]; +var commentDirectiveRegExSingleLine = /^\/\/\/?\s*@(ts-expect-error|ts-ignore)/; +var commentDirectiveRegExMultiLine = /^(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; +var jsDocSeeOrLink = /@(?:see|link)/i; +function lookupInUnicodeMap(code, map2) { + if (code < map2[0]) { + return false; + } + let lo = 0; + let hi = map2.length; + let mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + mid -= mid % 2; + if (map2[mid] <= code && code <= map2[mid + 1]) { + return true; + } + if (code < map2[mid]) { + hi = mid; + } else { + lo = mid + 2; + } + } + return false; +} +function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion >= 2 /* ES2015 */ ? lookupInUnicodeMap(code, unicodeESNextIdentifierStart) : lookupInUnicodeMap(code, unicodeES5IdentifierStart); +} +function isUnicodeIdentifierPart(code, languageVersion) { + return languageVersion >= 2 /* ES2015 */ ? lookupInUnicodeMap(code, unicodeESNextIdentifierPart) : lookupInUnicodeMap(code, unicodeES5IdentifierPart); +} +function makeReverseMap(source) { + const result = []; + source.forEach((value, name) => { + result[value] = name; + }); + return result; +} +var tokenStrings = makeReverseMap(textToToken); +function tokenToString(t) { + return tokenStrings[t]; +} +function stringToToken(s) { + return textToToken.get(s); +} +var regExpFlagCharCodes = makeReverseMap(charCodeToRegExpFlag); +function characterCodeToRegularExpressionFlag(ch) { + return charCodeToRegExpFlag.get(ch); +} +function computeLineStarts(text) { + const result = []; + let pos = 0; + let lineStart = 0; + while (pos < text.length) { + const ch = text.charCodeAt(pos); + pos++; + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + result.push(lineStart); + lineStart = pos; + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) { + result.push(lineStart); + lineStart = pos; + } + break; + } + } + result.push(lineStart); + return result; +} +function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) { + return sourceFile.getPositionOfLineAndCharacter ? sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) : computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits); +} +function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { + if (line < 0 || line >= lineStarts.length) { + if (allowEdits) { + line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; + } else { + Debug.fail(`Bad line number. Line: ${line}, lineStarts.length: ${lineStarts.length} , line map is correct? ${debugText !== void 0 ? arrayIsEqualTo(lineStarts, computeLineStarts(debugText)) : "unknown"}`); + } + } + const res = lineStarts[line] + character; + if (allowEdits) { + return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res; + } + if (line < lineStarts.length - 1) { + Debug.assert(res < lineStarts[line + 1]); + } else if (debugText !== void 0) { + Debug.assert(res <= debugText.length); + } + return res; +} +function getLineStarts(sourceFile) { + return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); +} +function computeLineAndCharacterOfPosition(lineStarts, position) { + const lineNumber = computeLineOfPosition(lineStarts, position); + return { + line: lineNumber, + character: position - lineStarts[lineNumber] + }; +} +function computeLineOfPosition(lineStarts, position, lowerBound) { + let lineNumber = binarySearch(lineStarts, position, identity, compareValues, lowerBound); + if (lineNumber < 0) { + lineNumber = ~lineNumber - 1; + Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); + } + return lineNumber; +} +function getLinesBetweenPositions(sourceFile, pos1, pos2) { + if (pos1 === pos2) return 0; + const lineStarts = getLineStarts(sourceFile); + const lower = Math.min(pos1, pos2); + const isNegative = lower === pos2; + const upper = isNegative ? pos1 : pos2; + const lowerLine = computeLineOfPosition(lineStarts, lower); + const upperLine = computeLineOfPosition(lineStarts, upper, lowerLine); + return isNegative ? lowerLine - upperLine : upperLine - lowerLine; +} +function getLineAndCharacterOfPosition(sourceFile, position) { + return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); +} +function isWhiteSpaceLike(ch) { + return isWhiteSpaceSingleLine(ch) || isLineBreak(ch); +} +function isWhiteSpaceSingleLine(ch) { + return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ || ch === 160 /* nonBreakingSpace */ || ch === 133 /* nextLine */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */; +} +function isLineBreak(ch) { + return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */; +} +function isDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; +} +function isHexDigit(ch) { + return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */; +} +function isASCIILetter(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */; +} +function isWordCharacter(ch) { + return isASCIILetter(ch) || isDigit(ch) || ch === 95 /* _ */; +} +function isOctalDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; +} +function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { + if (positionIsSynthesized(pos)) { + return pos; + } + let canConsumeStar = false; + while (true) { + const ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (stopAfterLineBreak) { + return pos; + } + canConsumeStar = !!inJSDoc; + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + if (stopAtComments) { + break; + } + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + canConsumeStar = false; + continue; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + canConsumeStar = false; + continue; + } + break; + case 60 /* lessThan */: + case 124 /* bar */: + case 61 /* equals */: + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 35 /* hash */: + if (pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; + continue; + } + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && isWhiteSpaceLike(ch)) { + pos++; + continue; + } + break; + } + return pos; + } +} +var mergeConflictMarkerLength = "<<<<<<<".length; +function isConflictMarkerTrivia(text, pos) { + Debug.assert(pos >= 0); + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { + const ch = text.charCodeAt(pos); + if (pos + mergeConflictMarkerLength < text.length) { + for (let i = 0; i < mergeConflictMarkerLength; i++) { + if (text.charCodeAt(pos + i) !== ch) { + return false; + } + } + return ch === 61 /* equals */ || text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; + } + } + return false; +} +function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); + } + const ch = text.charCodeAt(pos); + const len = text.length; + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } else { + Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + while (pos < len) { + const currentChar = text.charCodeAt(pos); + if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } + } + return pos; +} +var shebangTriviaRegex = /^#!.*/; +function isShebangTrivia(text, pos) { + Debug.assert(pos === 0); + return shebangTriviaRegex.test(text); +} +function scanShebangTrivia(text, pos) { + const shebang = shebangTriviaRegex.exec(text)[0]; + pos = pos + shebang.length; + return pos; +} +function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { + let pendingPos; + let pendingEnd; + let pendingKind; + let pendingHasTrailingNewLine; + let hasPendingCommentRange = false; + let collecting = trailing; + let accumulator = initial; + if (pos === 0) { + collecting = true; + const shebang = getShebang(text); + if (shebang) { + pos = shebang.length; + } + } + scan: + while (pos >= 0 && pos < text.length) { + const ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + pos++; + if (trailing) { + break scan; + } + collecting = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + const nextChar = text.charCodeAt(pos + 1); + let hasTrailingNewLine = false; + if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { + const kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; + const startPos = pos; + pos += 2; + if (nextChar === 47 /* slash */) { + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + hasTrailingNewLine = true; + break; + } + pos++; + } + } else { + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + } + if (collecting) { + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + return accumulator; + } + } + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; + } + continue; + } + break scan; + default: + if (ch > 127 /* maxAsciiCharacter */ && isWhiteSpaceLike(ch)) { + if (hasPendingCommentRange && isLineBreak(ch)) { + pendingHasTrailingNewLine = true; + } + pos++; + continue; + } + break scan; + } + } + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + } + return accumulator; +} +function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges( + /*reduce*/ + false, + text, + pos, + /*trailing*/ + false, + cb, + state + ); +} +function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges( + /*reduce*/ + false, + text, + pos, + /*trailing*/ + true, + cb, + state + ); +} +function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges( + /*reduce*/ + true, + text, + pos, + /*trailing*/ + false, + cb, + state, + initial + ); +} +function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { + return iterateCommentRanges( + /*reduce*/ + true, + text, + pos, + /*trailing*/ + true, + cb, + state, + initial + ); +} +function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments = []) { + comments.push({ kind, pos, end, hasTrailingNewLine }); + return comments; +} +function getLeadingCommentRanges(text, pos) { + return reduceEachLeadingCommentRange( + text, + pos, + appendCommentRange, + /*state*/ + void 0, + /*initial*/ + void 0 + ); +} +function getTrailingCommentRanges(text, pos) { + return reduceEachTrailingCommentRange( + text, + pos, + appendCommentRange, + /*state*/ + void 0, + /*initial*/ + void 0 + ); +} +function getShebang(text) { + const match = shebangTriviaRegex.exec(text); + if (match) { + return match[0]; + } +} +function isIdentifierStart(ch, languageVersion) { + return isASCIILetter(ch) || ch === 36 /* $ */ || ch === 95 /* _ */ || ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); +} +function isIdentifierPart(ch, languageVersion, identifierVariant) { + return isWordCharacter(ch) || ch === 36 /* $ */ || // "-" and ":" are valid in JSX Identifiers + (identifierVariant === 1 /* JSX */ ? ch === 45 /* minus */ || ch === 58 /* colon */ : false) || ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); +} +function isIdentifierText(name, languageVersion, identifierVariant) { + let ch = codePointAt(name, 0); + if (!isIdentifierStart(ch, languageVersion)) { + return false; + } + for (let i = charSize(ch); i < name.length; i += charSize(ch)) { + if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) { + return false; + } + } + return true; +} +function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Standard */, textInitial, onError, start, length2) { + var text = textInitial; + var pos; + var end; + var fullStartPos; + var tokenStart; + var token; + var tokenValue; + var tokenFlags; + var commentDirectives; + var skipJsDocLeadingAsterisks = 0; + var scriptKind = 0 /* Unknown */; + var jsDocParsingMode = 0 /* ParseAll */; + setText(text, start, length2); + var scanner = { + getTokenFullStart: () => fullStartPos, + getStartPos: () => fullStartPos, + getTokenEnd: () => pos, + getTextPos: () => pos, + getToken: () => token, + getTokenStart: () => tokenStart, + getTokenPos: () => tokenStart, + getTokenText: () => text.substring(tokenStart, pos), + getTokenValue: () => tokenValue, + hasUnicodeEscape: () => (tokenFlags & 1024 /* UnicodeEscape */) !== 0, + hasExtendedUnicodeEscape: () => (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0, + hasPrecedingLineBreak: () => (tokenFlags & 1 /* PrecedingLineBreak */) !== 0, + hasPrecedingJSDocComment: () => (tokenFlags & 2 /* PrecedingJSDocComment */) !== 0, + hasPrecedingJSDocLeadingAsterisks: () => (tokenFlags & 32768 /* PrecedingJSDocLeadingAsterisks */) !== 0, + isIdentifier: () => token === 80 /* Identifier */ || token > 118 /* LastReservedWord */, + isReservedWord: () => token >= 83 /* FirstReservedWord */ && token <= 118 /* LastReservedWord */, + isUnterminated: () => (tokenFlags & 4 /* Unterminated */) !== 0, + getCommentDirectives: () => commentDirectives, + getNumericLiteralFlags: () => tokenFlags & 25584 /* NumericLiteralFlags */, + getTokenFlags: () => tokenFlags, + reScanGreaterToken, + reScanAsteriskEqualsToken, + reScanSlashToken, + reScanTemplateToken, + reScanTemplateHeadOrNoSubstitutionTemplate, + scanJsxIdentifier, + scanJsxAttributeValue, + reScanJsxAttributeValue, + reScanJsxToken, + reScanLessThanToken, + reScanHashToken, + reScanQuestionToken, + reScanInvalidIdentifier, + scanJsxToken, + scanJsDocToken, + scanJSDocCommentTextToken, + scan, + getText, + clearCommentDirectives, + setText, + setScriptTarget, + setLanguageVariant, + setScriptKind, + setJSDocParsingMode, + setOnError, + resetTokenState, + setTextPos: resetTokenState, + setSkipJsDocLeadingAsterisks, + tryScan, + lookAhead, + scanRange + }; + if (Debug.isDebugging) { + Object.defineProperty(scanner, "__debugShowCurrentPositionInText", { + get: () => { + const text2 = scanner.getText(); + return text2.slice(0, scanner.getTokenFullStart()) + "\u2551" + text2.slice(scanner.getTokenFullStart()); + } + }); + } + return scanner; + function codePointUnchecked(pos2) { + return codePointAt(text, pos2); + } + function codePointChecked(pos2) { + return pos2 >= 0 && pos2 < end ? codePointUnchecked(pos2) : -1 /* EOF */; + } + function charCodeUnchecked(pos2) { + return text.charCodeAt(pos2); + } + function charCodeChecked(pos2) { + return pos2 >= 0 && pos2 < end ? charCodeUnchecked(pos2) : -1 /* EOF */; + } + function error(message, errPos = pos, length3, arg0) { + if (onError) { + const oldPos = pos; + pos = errPos; + onError(message, length3 || 0, arg0); + pos = oldPos; + } + } + function scanNumberFragment() { + let start2 = pos; + let allowSeparator = false; + let isPreviousTokenSeparator = false; + let result = ""; + while (true) { + const ch = charCodeUnchecked(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start2, pos); + } else { + tokenFlags |= 16384 /* ContainsInvalidSeparator */; + if (isPreviousTokenSeparator) { + error(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } else { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + } + pos++; + start2 = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (charCodeUnchecked(pos - 1) === 95 /* _ */) { + tokenFlags |= 16384 /* ContainsInvalidSeparator */; + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start2, pos); + } + function scanNumber() { + let start2 = pos; + let mainFragment; + if (charCodeUnchecked(pos) === 48 /* _0 */) { + pos++; + if (charCodeUnchecked(pos) === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */ | 16384 /* ContainsInvalidSeparator */; + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + pos--; + mainFragment = scanNumberFragment(); + } else if (!scanDigits()) { + tokenFlags |= 8192 /* ContainsLeadingZero */; + mainFragment = "" + +tokenValue; + } else if (!tokenValue) { + mainFragment = "0"; + } else { + tokenValue = "" + parseInt(tokenValue, 8); + tokenFlags |= 32 /* Octal */; + const withMinus = token === 41 /* MinusToken */; + const literal = (withMinus ? "-" : "") + "0o" + (+tokenValue).toString(8); + if (withMinus) start2--; + error(Diagnostics.Octal_literals_are_not_allowed_Use_the_syntax_0, start2, pos - start2, literal); + return 9 /* NumericLiteral */; + } + } else { + mainFragment = scanNumberFragment(); + } + let decimalFragment; + let scientificFragment; + if (charCodeUnchecked(pos) === 46 /* dot */) { + pos++; + decimalFragment = scanNumberFragment(); + } + let end2 = pos; + if (charCodeUnchecked(pos) === 69 /* E */ || charCodeUnchecked(pos) === 101 /* e */) { + pos++; + tokenFlags |= 16 /* Scientific */; + if (charCodeUnchecked(pos) === 43 /* plus */ || charCodeUnchecked(pos) === 45 /* minus */) pos++; + const preNumericPart = pos; + const finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(Diagnostics.Digit_expected); + } else { + scientificFragment = text.substring(end2, preNumericPart) + finalFragment; + end2 = pos; + } + } + let result; + if (tokenFlags & 512 /* ContainsSeparator */) { + result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + } else { + result = text.substring(start2, end2); + } + if (tokenFlags & 8192 /* ContainsLeadingZero */) { + error(Diagnostics.Decimals_with_leading_zeros_are_not_allowed, start2, end2 - start2); + tokenValue = "" + +result; + return 9 /* NumericLiteral */; + } + if (decimalFragment !== void 0 || tokenFlags & 16 /* Scientific */) { + checkForIdentifierStartAfterNumericLiteral(start2, decimalFragment === void 0 && !!(tokenFlags & 16 /* Scientific */)); + tokenValue = "" + +result; + return 9 /* NumericLiteral */; + } else { + tokenValue = result; + const type = checkBigIntSuffix(); + checkForIdentifierStartAfterNumericLiteral(start2); + return type; + } + } + function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { + if (!isIdentifierStart(codePointUnchecked(pos), languageVersion)) { + return; + } + const identifierStart = pos; + const { length: length3 } = scanIdentifierParts(); + if (length3 === 1 && text[identifierStart] === "n") { + if (isScientific) { + error(Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); + } else { + error(Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); + } + } else { + error(Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length3); + pos = identifierStart; + } + } + function scanDigits() { + const start2 = pos; + let isOctal = true; + while (isDigit(charCodeChecked(pos))) { + if (!isOctalDigit(charCodeUnchecked(pos))) { + isOctal = false; + } + pos++; + } + tokenValue = text.substring(start2, pos); + return isOctal; + } + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + const valueString = scanHexDigits( + /*minCount*/ + count, + /*scanAsManyAsPossible*/ + false, + canHaveSeparators + ); + return valueString ? parseInt(valueString, 16) : -1; + } + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits( + /*minCount*/ + count, + /*scanAsManyAsPossible*/ + true, + canHaveSeparators + ); + } + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { + let valueChars = []; + let allowSeparator = false; + let isPreviousTokenSeparator = false; + while (valueChars.length < minCount || scanAsManyAsPossible) { + let ch = charCodeUnchecked(pos); + if (canHaveSeparators && ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } else if (isPreviousTokenSeparator) { + error(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } else { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; + if (ch >= 65 /* A */ && ch <= 70 /* F */) { + ch += 97 /* a */ - 65 /* A */; + } else if (!(ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch >= 97 /* a */ && ch <= 102 /* f */)) { + break; + } + valueChars.push(ch); + pos++; + isPreviousTokenSeparator = false; + } + if (valueChars.length < minCount) { + valueChars = []; + } + if (charCodeUnchecked(pos - 1) === 95 /* _ */) { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return String.fromCharCode(...valueChars); + } + function scanString(jsxAttributeString = false) { + const quote = charCodeUnchecked(pos); + pos++; + let result = ""; + let start2 = pos; + while (true) { + if (pos >= end) { + result += text.substring(start2, pos); + tokenFlags |= 4 /* Unterminated */; + error(Diagnostics.Unterminated_string_literal); + break; + } + const ch = charCodeUnchecked(pos); + if (ch === quote) { + result += text.substring(start2, pos); + pos++; + break; + } + if (ch === 92 /* backslash */ && !jsxAttributeString) { + result += text.substring(start2, pos); + result += scanEscapeSequence(1 /* String */ | 2 /* ReportErrors */); + start2 = pos; + continue; + } + if ((ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */) && !jsxAttributeString) { + result += text.substring(start2, pos); + tokenFlags |= 4 /* Unterminated */; + error(Diagnostics.Unterminated_string_literal); + break; + } + pos++; + } + return result; + } + function scanTemplateAndSetTokenValue(shouldEmitInvalidEscapeError) { + const startedWithBacktick = charCodeUnchecked(pos) === 96 /* backtick */; + pos++; + let start2 = pos; + let contents = ""; + let resultingToken; + while (true) { + if (pos >= end) { + contents += text.substring(start2, pos); + tokenFlags |= 4 /* Unterminated */; + error(Diagnostics.Unterminated_template_literal); + resultingToken = startedWithBacktick ? 15 /* NoSubstitutionTemplateLiteral */ : 18 /* TemplateTail */; + break; + } + const currChar = charCodeUnchecked(pos); + if (currChar === 96 /* backtick */) { + contents += text.substring(start2, pos); + pos++; + resultingToken = startedWithBacktick ? 15 /* NoSubstitutionTemplateLiteral */ : 18 /* TemplateTail */; + break; + } + if (currChar === 36 /* $ */ && pos + 1 < end && charCodeUnchecked(pos + 1) === 123 /* openBrace */) { + contents += text.substring(start2, pos); + pos += 2; + resultingToken = startedWithBacktick ? 16 /* TemplateHead */ : 17 /* TemplateMiddle */; + break; + } + if (currChar === 92 /* backslash */) { + contents += text.substring(start2, pos); + contents += scanEscapeSequence(1 /* String */ | (shouldEmitInvalidEscapeError ? 2 /* ReportErrors */ : 0)); + start2 = pos; + continue; + } + if (currChar === 13 /* carriageReturn */) { + contents += text.substring(start2, pos); + pos++; + if (pos < end && charCodeUnchecked(pos) === 10 /* lineFeed */) { + pos++; + } + contents += "\n"; + start2 = pos; + continue; + } + pos++; + } + Debug.assert(resultingToken !== void 0); + tokenValue = contents; + return resultingToken; + } + function scanEscapeSequence(flags) { + const start2 = pos; + pos++; + if (pos >= end) { + error(Diagnostics.Unexpected_end_of_text); + return ""; + } + const ch = charCodeUnchecked(pos); + pos++; + switch (ch) { + case 48 /* _0 */: + if (pos >= end || !isDigit(charCodeUnchecked(pos))) { + return "\0"; + } + // '\01', '\011' + // falls through + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + if (pos < end && isOctalDigit(charCodeUnchecked(pos))) { + pos++; + } + // '\17', '\177' + // falls through + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + if (pos < end && isOctalDigit(charCodeUnchecked(pos))) { + pos++; + } + tokenFlags |= 2048 /* ContainsInvalidEscape */; + if (flags & 6 /* ReportInvalidEscapeErrors */) { + const code = parseInt(text.substring(start2 + 1, pos), 8); + if (flags & 4 /* RegularExpression */ && !(flags & 32 /* AtomEscape */) && ch !== 48 /* _0 */) { + error(Diagnostics.Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended_as_an_escape_sequence_use_the_syntax_0_instead, start2, pos - start2, "\\x" + code.toString(16).padStart(2, "0")); + } else { + error(Diagnostics.Octal_escape_sequences_are_not_allowed_Use_the_syntax_0, start2, pos - start2, "\\x" + code.toString(16).padStart(2, "0")); + } + return String.fromCharCode(code); + } + return text.substring(start2, pos); + case 56 /* _8 */: + case 57 /* _9 */: + tokenFlags |= 2048 /* ContainsInvalidEscape */; + if (flags & 6 /* ReportInvalidEscapeErrors */) { + if (flags & 4 /* RegularExpression */ && !(flags & 32 /* AtomEscape */)) { + error(Diagnostics.Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class, start2, pos - start2); + } else { + error(Diagnostics.Escape_sequence_0_is_not_allowed, start2, pos - start2, text.substring(start2, pos)); + } + return String.fromCharCode(ch); + } + return text.substring(start2, pos); + case 98 /* b */: + return "\b"; + case 116 /* t */: + return " "; + case 110 /* n */: + return "\n"; + case 118 /* v */: + return "\v"; + case 102 /* f */: + return "\f"; + case 114 /* r */: + return "\r"; + case 39 /* singleQuote */: + return "'"; + case 34 /* doubleQuote */: + return '"'; + case 117 /* u */: + if (pos < end && charCodeUnchecked(pos) === 123 /* openBrace */) { + pos -= 2; + const result = scanExtendedUnicodeEscape(!!(flags & 6 /* ReportInvalidEscapeErrors */)); + if (!(flags & 17 /* AllowExtendedUnicodeEscape */)) { + tokenFlags |= 2048 /* ContainsInvalidEscape */; + if (flags & 6 /* ReportInvalidEscapeErrors */) { + error(Diagnostics.Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set, start2, pos - start2); + } + } + return result; + } + for (; pos < start2 + 6; pos++) { + if (!(pos < end && isHexDigit(charCodeUnchecked(pos)))) { + tokenFlags |= 2048 /* ContainsInvalidEscape */; + if (flags & 6 /* ReportInvalidEscapeErrors */) { + error(Diagnostics.Hexadecimal_digit_expected); + } + return text.substring(start2, pos); + } + } + tokenFlags |= 1024 /* UnicodeEscape */; + const escapedValue = parseInt(text.substring(start2 + 2, pos), 16); + const escapedValueString = String.fromCharCode(escapedValue); + if (flags & 16 /* AnyUnicodeMode */ && escapedValue >= 55296 && escapedValue <= 56319 && pos + 6 < end && text.substring(pos, pos + 2) === "\\u" && charCodeUnchecked(pos + 2) !== 123 /* openBrace */) { + const nextStart = pos; + let nextPos = pos + 2; + for (; nextPos < nextStart + 6; nextPos++) { + if (!isHexDigit(charCodeUnchecked(nextPos))) { + return escapedValueString; + } + } + const nextEscapedValue = parseInt(text.substring(nextStart + 2, nextPos), 16); + if (nextEscapedValue >= 56320 && nextEscapedValue <= 57343) { + pos = nextPos; + return escapedValueString + String.fromCharCode(nextEscapedValue); + } + } + return escapedValueString; + case 120 /* x */: + for (; pos < start2 + 4; pos++) { + if (!(pos < end && isHexDigit(charCodeUnchecked(pos)))) { + tokenFlags |= 2048 /* ContainsInvalidEscape */; + if (flags & 6 /* ReportInvalidEscapeErrors */) { + error(Diagnostics.Hexadecimal_digit_expected); + } + return text.substring(start2, pos); + } + } + tokenFlags |= 4096 /* HexEscape */; + return String.fromCharCode(parseInt(text.substring(start2 + 2, pos), 16)); + // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), + // the line terminator is interpreted to be "the empty code unit sequence". + case 13 /* carriageReturn */: + if (pos < end && charCodeUnchecked(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + case 8232 /* lineSeparator */: + case 8233 /* paragraphSeparator */: + return ""; + default: + if (flags & 16 /* AnyUnicodeMode */ || flags & 4 /* RegularExpression */ && !(flags & 8 /* AnnexB */) && isIdentifierPart(ch, languageVersion)) { + error(Diagnostics.This_character_cannot_be_escaped_in_a_regular_expression, pos - 2, 2); + } + return String.fromCharCode(ch); + } + } + function scanExtendedUnicodeEscape(shouldEmitInvalidEscapeError) { + const start2 = pos; + pos += 3; + const escapedStart = pos; + const escapedValueString = scanMinimumNumberOfHexDigits( + 1, + /*canHaveSeparators*/ + false + ); + const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + let isInvalidExtendedEscape = false; + if (escapedValue < 0) { + if (shouldEmitInvalidEscapeError) { + error(Diagnostics.Hexadecimal_digit_expected); + } + isInvalidExtendedEscape = true; + } else if (escapedValue > 1114111) { + if (shouldEmitInvalidEscapeError) { + error(Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive, escapedStart, pos - escapedStart); + } + isInvalidExtendedEscape = true; + } + if (pos >= end) { + if (shouldEmitInvalidEscapeError) { + error(Diagnostics.Unexpected_end_of_text); + } + isInvalidExtendedEscape = true; + } else if (charCodeUnchecked(pos) === 125 /* closeBrace */) { + pos++; + } else { + if (shouldEmitInvalidEscapeError) { + error(Diagnostics.Unterminated_Unicode_escape_sequence); + } + isInvalidExtendedEscape = true; + } + if (isInvalidExtendedEscape) { + tokenFlags |= 2048 /* ContainsInvalidEscape */; + return text.substring(start2, pos); + } + tokenFlags |= 8 /* ExtendedUnicodeEscape */; + return utf16EncodeAsString(escapedValue); + } + function peekUnicodeEscape() { + if (pos + 5 < end && charCodeUnchecked(pos + 1) === 117 /* u */) { + const start2 = pos; + pos += 2; + const value = scanExactNumberOfHexDigits( + 4, + /*canHaveSeparators*/ + false + ); + pos = start2; + return value; + } + return -1; + } + function peekExtendedUnicodeEscape() { + if (codePointUnchecked(pos + 1) === 117 /* u */ && codePointUnchecked(pos + 2) === 123 /* openBrace */) { + const start2 = pos; + pos += 3; + const escapedValueString = scanMinimumNumberOfHexDigits( + 1, + /*canHaveSeparators*/ + false + ); + const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + pos = start2; + return escapedValue; + } + return -1; + } + function scanIdentifierParts() { + let result = ""; + let start2 = pos; + while (pos < end) { + let ch = codePointUnchecked(pos); + if (isIdentifierPart(ch, languageVersion)) { + pos += charSize(ch); + } else if (ch === 92 /* backslash */) { + ch = peekExtendedUnicodeEscape(); + if (ch >= 0 && isIdentifierPart(ch, languageVersion)) { + result += scanExtendedUnicodeEscape( + /*shouldEmitInvalidEscapeError*/ + true + ); + start2 = pos; + continue; + } + ch = peekUnicodeEscape(); + if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { + break; + } + tokenFlags |= 1024 /* UnicodeEscape */; + result += text.substring(start2, pos); + result += utf16EncodeAsString(ch); + pos += 6; + start2 = pos; + } else { + break; + } + } + result += text.substring(start2, pos); + return result; + } + function getIdentifierToken() { + const len = tokenValue.length; + if (len >= 2 && len <= 12) { + const ch = tokenValue.charCodeAt(0); + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + const keyword = textToKeyword.get(tokenValue); + if (keyword !== void 0) { + return token = keyword; + } + } + } + return token = 80 /* Identifier */; + } + function scanBinaryOrOctalDigits(base) { + let value = ""; + let separatorAllowed = false; + let isPreviousTokenSeparator = false; + while (true) { + const ch = charCodeUnchecked(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } else if (isPreviousTokenSeparator) { + error(Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } else { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; + if (!isDigit(ch) || ch - 48 /* _0 */ >= base) { + break; + } + value += text[pos]; + pos++; + isPreviousTokenSeparator = false; + } + if (charCodeUnchecked(pos - 1) === 95 /* _ */) { + error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return value; + } + function checkBigIntSuffix() { + if (charCodeUnchecked(pos) === 110 /* n */) { + tokenValue += "n"; + if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { + tokenValue = parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + return 10 /* BigIntLiteral */; + } else { + const numericValue = tokenFlags & 128 /* BinarySpecifier */ ? parseInt(tokenValue.slice(2), 2) : tokenFlags & 256 /* OctalSpecifier */ ? parseInt(tokenValue.slice(2), 8) : +tokenValue; + tokenValue = "" + numericValue; + return 9 /* NumericLiteral */; + } + } + function scan() { + fullStartPos = pos; + tokenFlags = 0 /* None */; + while (true) { + tokenStart = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + const ch = codePointUnchecked(pos); + if (pos === 0) { + if (ch === 35 /* hash */ && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + if (skipTrivia2) { + continue; + } else { + return token = 6 /* ShebangTrivia */; + } + } + } + switch (ch) { + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; + if (skipTrivia2) { + pos++; + continue; + } else { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && charCodeUnchecked(pos + 1) === 10 /* lineFeed */) { + pos += 2; + } else { + pos++; + } + return token = 4 /* NewLineTrivia */; + } + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: + if (skipTrivia2) { + pos++; + continue; + } else { + while (pos < end && isWhiteSpaceSingleLine(charCodeUnchecked(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + } + case 33 /* exclamation */: + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { + return pos += 3, token = 38 /* ExclamationEqualsEqualsToken */; + } + return pos += 2, token = 36 /* ExclamationEqualsToken */; + } + pos++; + return token = 54 /* ExclamationToken */; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(); + return token = 11 /* StringLiteral */; + case 96 /* backtick */: + return token = scanTemplateAndSetTokenValue( + /*shouldEmitInvalidEscapeError*/ + false + ); + case 37 /* percent */: + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 70 /* PercentEqualsToken */; + } + pos++; + return token = 45 /* PercentToken */; + case 38 /* ampersand */: + if (charCodeUnchecked(pos + 1) === 38 /* ampersand */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { + return pos += 3, token = 77 /* AmpersandAmpersandEqualsToken */; + } + return pos += 2, token = 56 /* AmpersandAmpersandToken */; + } + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 74 /* AmpersandEqualsToken */; + } + pos++; + return token = 51 /* AmpersandToken */; + case 40 /* openParen */: + pos++; + return token = 21 /* OpenParenToken */; + case 41 /* closeParen */: + pos++; + return token = 22 /* CloseParenToken */; + case 42 /* asterisk */: + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 67 /* AsteriskEqualsToken */; + } + if (charCodeUnchecked(pos + 1) === 42 /* asterisk */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { + return pos += 3, token = 68 /* AsteriskAsteriskEqualsToken */; + } + return pos += 2, token = 43 /* AsteriskAsteriskToken */; + } + pos++; + if (skipJsDocLeadingAsterisks && (tokenFlags & 32768 /* PrecedingJSDocLeadingAsterisks */) === 0 && tokenFlags & 1 /* PrecedingLineBreak */) { + tokenFlags |= 32768 /* PrecedingJSDocLeadingAsterisks */; + continue; + } + return token = 42 /* AsteriskToken */; + case 43 /* plus */: + if (charCodeUnchecked(pos + 1) === 43 /* plus */) { + return pos += 2, token = 46 /* PlusPlusToken */; + } + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 65 /* PlusEqualsToken */; + } + pos++; + return token = 40 /* PlusToken */; + case 44 /* comma */: + pos++; + return token = 28 /* CommaToken */; + case 45 /* minus */: + if (charCodeUnchecked(pos + 1) === 45 /* minus */) { + return pos += 2, token = 47 /* MinusMinusToken */; + } + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 66 /* MinusEqualsToken */; + } + pos++; + return token = 41 /* MinusToken */; + case 46 /* dot */: + if (isDigit(charCodeUnchecked(pos + 1))) { + scanNumber(); + return token = 9 /* NumericLiteral */; + } + if (charCodeUnchecked(pos + 1) === 46 /* dot */ && charCodeUnchecked(pos + 2) === 46 /* dot */) { + return pos += 3, token = 26 /* DotDotDotToken */; + } + pos++; + return token = 25 /* DotToken */; + case 47 /* slash */: + if (charCodeUnchecked(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < end) { + if (isLineBreak(charCodeUnchecked(pos))) { + break; + } + pos++; + } + commentDirectives = appendIfCommentDirective( + commentDirectives, + text.slice(tokenStart, pos), + commentDirectiveRegExSingleLine, + tokenStart + ); + if (skipTrivia2) { + continue; + } else { + return token = 2 /* SingleLineCommentTrivia */; + } + } + if (charCodeUnchecked(pos + 1) === 42 /* asterisk */) { + pos += 2; + const isJSDoc2 = charCodeUnchecked(pos) === 42 /* asterisk */ && charCodeUnchecked(pos + 1) !== 47 /* slash */; + let commentClosed = false; + let lastLineStart = tokenStart; + while (pos < end) { + const ch2 = charCodeUnchecked(pos); + if (ch2 === 42 /* asterisk */ && charCodeUnchecked(pos + 1) === 47 /* slash */) { + pos += 2; + commentClosed = true; + break; + } + pos++; + if (isLineBreak(ch2)) { + lastLineStart = pos; + tokenFlags |= 1 /* PrecedingLineBreak */; + } + } + if (isJSDoc2 && shouldParseJSDoc()) { + tokenFlags |= 2 /* PrecedingJSDocComment */; + } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); + if (!commentClosed) { + error(Diagnostics.Asterisk_Slash_expected); + } + if (skipTrivia2) { + continue; + } else { + if (!commentClosed) { + tokenFlags |= 4 /* Unterminated */; + } + return token = 3 /* MultiLineCommentTrivia */; + } + } + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 69 /* SlashEqualsToken */; + } + pos++; + return token = 44 /* SlashToken */; + case 48 /* _0 */: + if (pos + 2 < end && (charCodeUnchecked(pos + 1) === 88 /* X */ || charCodeUnchecked(pos + 1) === 120 /* x */)) { + pos += 2; + tokenValue = scanMinimumNumberOfHexDigits( + 1, + /*canHaveSeparators*/ + true + ); + if (!tokenValue) { + error(Diagnostics.Hexadecimal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0x" + tokenValue; + tokenFlags |= 64 /* HexSpecifier */; + return token = checkBigIntSuffix(); + } else if (pos + 2 < end && (charCodeUnchecked(pos + 1) === 66 /* B */ || charCodeUnchecked(pos + 1) === 98 /* b */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits( + /* base */ + 2 + ); + if (!tokenValue) { + error(Diagnostics.Binary_digit_expected); + tokenValue = "0"; + } + tokenValue = "0b" + tokenValue; + tokenFlags |= 128 /* BinarySpecifier */; + return token = checkBigIntSuffix(); + } else if (pos + 2 < end && (charCodeUnchecked(pos + 1) === 79 /* O */ || charCodeUnchecked(pos + 1) === 111 /* o */)) { + pos += 2; + tokenValue = scanBinaryOrOctalDigits( + /* base */ + 8 + ); + if (!tokenValue) { + error(Diagnostics.Octal_digit_expected); + tokenValue = "0"; + } + tokenValue = "0o" + tokenValue; + tokenFlags |= 256 /* OctalSpecifier */; + return token = checkBigIntSuffix(); + } + // falls through + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: + return token = scanNumber(); + case 58 /* colon */: + pos++; + return token = 59 /* ColonToken */; + case 59 /* semicolon */: + pos++; + return token = 27 /* SemicolonToken */; + case 60 /* lessThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia2) { + continue; + } else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (charCodeUnchecked(pos + 1) === 60 /* lessThan */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { + return pos += 3, token = 71 /* LessThanLessThanEqualsToken */; + } + return pos += 2, token = 48 /* LessThanLessThanToken */; + } + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 33 /* LessThanEqualsToken */; + } + if (languageVariant === 1 /* JSX */ && charCodeUnchecked(pos + 1) === 47 /* slash */ && charCodeUnchecked(pos + 2) !== 42 /* asterisk */) { + return pos += 2, token = 31 /* LessThanSlashToken */; + } + pos++; + return token = 30 /* LessThanToken */; + case 61 /* equals */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia2) { + continue; + } else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { + return pos += 3, token = 37 /* EqualsEqualsEqualsToken */; + } + return pos += 2, token = 35 /* EqualsEqualsToken */; + } + if (charCodeUnchecked(pos + 1) === 62 /* greaterThan */) { + return pos += 2, token = 39 /* EqualsGreaterThanToken */; + } + pos++; + return token = 64 /* EqualsToken */; + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia2) { + continue; + } else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + pos++; + return token = 32 /* GreaterThanToken */; + case 63 /* question */: + if (charCodeUnchecked(pos + 1) === 46 /* dot */ && !isDigit(charCodeUnchecked(pos + 2))) { + return pos += 2, token = 29 /* QuestionDotToken */; + } + if (charCodeUnchecked(pos + 1) === 63 /* question */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { + return pos += 3, token = 78 /* QuestionQuestionEqualsToken */; + } + return pos += 2, token = 61 /* QuestionQuestionToken */; + } + pos++; + return token = 58 /* QuestionToken */; + case 91 /* openBracket */: + pos++; + return token = 23 /* OpenBracketToken */; + case 93 /* closeBracket */: + pos++; + return token = 24 /* CloseBracketToken */; + case 94 /* caret */: + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 79 /* CaretEqualsToken */; + } + pos++; + return token = 53 /* CaretToken */; + case 123 /* openBrace */: + pos++; + return token = 19 /* OpenBraceToken */; + case 124 /* bar */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia2) { + continue; + } else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (charCodeUnchecked(pos + 1) === 124 /* bar */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { + return pos += 3, token = 76 /* BarBarEqualsToken */; + } + return pos += 2, token = 57 /* BarBarToken */; + } + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 75 /* BarEqualsToken */; + } + pos++; + return token = 52 /* BarToken */; + case 125 /* closeBrace */: + pos++; + return token = 20 /* CloseBraceToken */; + case 126 /* tilde */: + pos++; + return token = 55 /* TildeToken */; + case 64 /* at */: + pos++; + return token = 60 /* AtToken */; + case 92 /* backslash */: + const extendedCookedChar = peekExtendedUnicodeEscape(); + if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) { + tokenValue = scanExtendedUnicodeEscape( + /*shouldEmitInvalidEscapeError*/ + true + ) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + const cookedChar = peekUnicodeEscape(); + if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { + pos += 6; + tokenFlags |= 1024 /* UnicodeEscape */; + tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + error(Diagnostics.Invalid_character); + pos++; + return token = 0 /* Unknown */; + case 35 /* hash */: + if (pos !== 0 && text[pos + 1] === "!") { + error(Diagnostics.can_only_be_used_at_the_start_of_a_file, pos, 2); + pos++; + return token = 0 /* Unknown */; + } + const charAfterHash = codePointUnchecked(pos + 1); + if (charAfterHash === 92 /* backslash */) { + pos++; + const extendedCookedChar2 = peekExtendedUnicodeEscape(); + if (extendedCookedChar2 >= 0 && isIdentifierStart(extendedCookedChar2, languageVersion)) { + tokenValue = "#" + scanExtendedUnicodeEscape( + /*shouldEmitInvalidEscapeError*/ + true + ) + scanIdentifierParts(); + return token = 81 /* PrivateIdentifier */; + } + const cookedChar2 = peekUnicodeEscape(); + if (cookedChar2 >= 0 && isIdentifierStart(cookedChar2, languageVersion)) { + pos += 6; + tokenFlags |= 1024 /* UnicodeEscape */; + tokenValue = "#" + String.fromCharCode(cookedChar2) + scanIdentifierParts(); + return token = 81 /* PrivateIdentifier */; + } + pos--; + } + if (isIdentifierStart(charAfterHash, languageVersion)) { + pos++; + scanIdentifier(charAfterHash, languageVersion); + } else { + tokenValue = "#"; + error(Diagnostics.Invalid_character, pos++, charSize(ch)); + } + return token = 81 /* PrivateIdentifier */; + case 65533 /* replacementCharacter */: + error(Diagnostics.File_appears_to_be_binary, 0, 0); + pos = end; + return token = 8 /* NonTextFileMarkerTrivia */; + default: + const identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; + } else if (isWhiteSpaceSingleLine(ch)) { + pos += charSize(ch); + continue; + } else if (isLineBreak(ch)) { + tokenFlags |= 1 /* PrecedingLineBreak */; + pos += charSize(ch); + continue; + } + const size = charSize(ch); + error(Diagnostics.Invalid_character, pos, size); + pos += size; + return token = 0 /* Unknown */; + } + } + } + function shouldParseJSDoc() { + switch (jsDocParsingMode) { + case 0 /* ParseAll */: + return true; + case 1 /* ParseNone */: + return false; + } + if (scriptKind !== 3 /* TS */ && scriptKind !== 4 /* TSX */) { + return true; + } + if (jsDocParsingMode === 3 /* ParseForTypeInfo */) { + return false; + } + return jsDocSeeOrLink.test(text.slice(fullStartPos, pos)); + } + function reScanInvalidIdentifier() { + Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenStart = fullStartPos; + tokenFlags = 0; + const ch = codePointUnchecked(pos); + const identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; + } + function scanIdentifier(startCharacter, languageVersion2) { + let ch = startCharacter; + if (isIdentifierStart(ch, languageVersion2)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointUnchecked(pos), languageVersion2)) pos += charSize(ch); + tokenValue = text.substring(tokenStart, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } + function reScanGreaterToken() { + if (token === 32 /* GreaterThanToken */) { + if (charCodeUnchecked(pos) === 62 /* greaterThan */) { + if (charCodeUnchecked(pos + 1) === 62 /* greaterThan */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { + return pos += 3, token = 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + } + return pos += 2, token = 50 /* GreaterThanGreaterThanGreaterThanToken */; + } + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + return pos += 2, token = 72 /* GreaterThanGreaterThanEqualsToken */; + } + pos++; + return token = 49 /* GreaterThanGreaterThanToken */; + } + if (charCodeUnchecked(pos) === 61 /* equals */) { + pos++; + return token = 34 /* GreaterThanEqualsToken */; + } + } + return token; + } + function reScanAsteriskEqualsToken() { + Debug.assert(token === 67 /* AsteriskEqualsToken */, "'reScanAsteriskEqualsToken' should only be called on a '*='"); + pos = tokenStart + 1; + return token = 64 /* EqualsToken */; + } + function reScanSlashToken(reportErrors2) { + if (token === 44 /* SlashToken */ || token === 69 /* SlashEqualsToken */) { + const startOfRegExpBody = tokenStart + 1; + pos = startOfRegExpBody; + let inEscape = false; + let namedCaptureGroups = false; + let inCharacterClass = false; + while (true) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || isLineBreak(ch)) { + tokenFlags |= 4 /* Unterminated */; + break; + } + if (inEscape) { + inEscape = false; + } else if (ch === 47 /* slash */ && !inCharacterClass) { + break; + } else if (ch === 91 /* openBracket */) { + inCharacterClass = true; + } else if (ch === 92 /* backslash */) { + inEscape = true; + } else if (ch === 93 /* closeBracket */) { + inCharacterClass = false; + } else if (!inCharacterClass && ch === 40 /* openParen */ && charCodeChecked(pos + 1) === 63 /* question */ && charCodeChecked(pos + 2) === 60 /* lessThan */ && charCodeChecked(pos + 3) !== 61 /* equals */ && charCodeChecked(pos + 3) !== 33 /* exclamation */) { + namedCaptureGroups = true; + } + pos++; + } + const endOfRegExpBody = pos; + if (tokenFlags & 4 /* Unterminated */) { + pos = startOfRegExpBody; + inEscape = false; + let characterClassDepth = 0; + let inDecimalQuantifier = false; + let groupDepth = 0; + while (pos < endOfRegExpBody) { + const ch = charCodeUnchecked(pos); + if (inEscape) { + inEscape = false; + } else if (ch === 92 /* backslash */) { + inEscape = true; + } else if (ch === 91 /* openBracket */) { + characterClassDepth++; + } else if (ch === 93 /* closeBracket */ && characterClassDepth) { + characterClassDepth--; + } else if (!characterClassDepth) { + if (ch === 123 /* openBrace */) { + inDecimalQuantifier = true; + } else if (ch === 125 /* closeBrace */ && inDecimalQuantifier) { + inDecimalQuantifier = false; + } else if (!inDecimalQuantifier) { + if (ch === 40 /* openParen */) { + groupDepth++; + } else if (ch === 41 /* closeParen */ && groupDepth) { + groupDepth--; + } else if (ch === 41 /* closeParen */ || ch === 93 /* closeBracket */ || ch === 125 /* closeBrace */) { + break; + } + } + } + pos++; + } + while (isWhiteSpaceLike(charCodeChecked(pos - 1)) || charCodeChecked(pos - 1) === 59 /* semicolon */) pos--; + error(Diagnostics.Unterminated_regular_expression_literal, tokenStart, pos - tokenStart); + } else { + pos++; + let regExpFlags = 0 /* None */; + while (true) { + const ch = codePointChecked(pos); + if (ch === -1 /* EOF */ || !isIdentifierPart(ch, languageVersion)) { + break; + } + const size = charSize(ch); + if (reportErrors2) { + const flag = characterCodeToRegularExpressionFlag(ch); + if (flag === void 0) { + error(Diagnostics.Unknown_regular_expression_flag, pos, size); + } else if (regExpFlags & flag) { + error(Diagnostics.Duplicate_regular_expression_flag, pos, size); + } else if (((regExpFlags | flag) & 96 /* AnyUnicodeMode */) === 96 /* AnyUnicodeMode */) { + error(Diagnostics.The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously, pos, size); + } else { + regExpFlags |= flag; + checkRegularExpressionFlagAvailability(flag, size); + } + } + pos += size; + } + if (reportErrors2) { + scanRange(startOfRegExpBody, endOfRegExpBody - startOfRegExpBody, () => { + scanRegularExpressionWorker( + regExpFlags, + /*annexB*/ + true, + namedCaptureGroups + ); + }); + } + } + tokenValue = text.substring(tokenStart, pos); + token = 14 /* RegularExpressionLiteral */; + } + return token; + } + function scanRegularExpressionWorker(regExpFlags, annexB, namedCaptureGroups) { + var unicodeSetsMode = !!(regExpFlags & 64 /* UnicodeSets */); + var anyUnicodeMode = !!(regExpFlags & 96 /* AnyUnicodeMode */); + var anyUnicodeModeOrNonAnnexB = anyUnicodeMode || !annexB; + var mayContainStrings = false; + var numberOfCapturingGroups = 0; + var groupSpecifiers; + var groupNameReferences; + var decimalEscapes; + var namedCapturingGroupsScopeStack = []; + var topNamedCapturingGroupsScope; + function scanDisjunction(isInGroup) { + while (true) { + namedCapturingGroupsScopeStack.push(topNamedCapturingGroupsScope); + topNamedCapturingGroupsScope = void 0; + scanAlternative(isInGroup); + topNamedCapturingGroupsScope = namedCapturingGroupsScopeStack.pop(); + if (charCodeChecked(pos) !== 124 /* bar */) { + return; + } + pos++; + } + } + function scanAlternative(isInGroup) { + let isPreviousTermQuantifiable = false; + while (true) { + const start2 = pos; + const ch = charCodeChecked(pos); + switch (ch) { + case -1 /* EOF */: + return; + case 94 /* caret */: + case 36 /* $ */: + pos++; + isPreviousTermQuantifiable = false; + break; + case 92 /* backslash */: + pos++; + switch (charCodeChecked(pos)) { + case 98 /* b */: + case 66 /* B */: + pos++; + isPreviousTermQuantifiable = false; + break; + default: + scanAtomEscape(); + isPreviousTermQuantifiable = true; + break; + } + break; + case 40 /* openParen */: + pos++; + if (charCodeChecked(pos) === 63 /* question */) { + pos++; + switch (charCodeChecked(pos)) { + case 61 /* equals */: + case 33 /* exclamation */: + pos++; + isPreviousTermQuantifiable = !anyUnicodeModeOrNonAnnexB; + break; + case 60 /* lessThan */: + const groupNameStart = pos; + pos++; + switch (charCodeChecked(pos)) { + case 61 /* equals */: + case 33 /* exclamation */: + pos++; + isPreviousTermQuantifiable = false; + break; + default: + scanGroupName( + /*isReference*/ + false + ); + scanExpectedChar(62 /* greaterThan */); + if (languageVersion < 5 /* ES2018 */) { + error(Diagnostics.Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later, groupNameStart, pos - groupNameStart); + } + numberOfCapturingGroups++; + isPreviousTermQuantifiable = true; + break; + } + break; + default: + const start3 = pos; + const setFlags = scanPatternModifiers(0 /* None */); + if (charCodeChecked(pos) === 45 /* minus */) { + pos++; + scanPatternModifiers(setFlags); + if (pos === start3 + 1) { + error(Diagnostics.Subpattern_flags_must_be_present_when_there_is_a_minus_sign, start3, pos - start3); + } + } + scanExpectedChar(58 /* colon */); + isPreviousTermQuantifiable = true; + break; + } + } else { + numberOfCapturingGroups++; + isPreviousTermQuantifiable = true; + } + scanDisjunction( + /*isInGroup*/ + true + ); + scanExpectedChar(41 /* closeParen */); + break; + case 123 /* openBrace */: + pos++; + const digitsStart = pos; + scanDigits(); + const min2 = tokenValue; + if (!anyUnicodeModeOrNonAnnexB && !min2) { + isPreviousTermQuantifiable = true; + break; + } + if (charCodeChecked(pos) === 44 /* comma */) { + pos++; + scanDigits(); + const max = tokenValue; + if (!min2) { + if (max || charCodeChecked(pos) === 125 /* closeBrace */) { + error(Diagnostics.Incomplete_quantifier_Digit_expected, digitsStart, 0); + } else { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, start2, 1, String.fromCharCode(ch)); + isPreviousTermQuantifiable = true; + break; + } + } else if (max && Number.parseInt(min2) > Number.parseInt(max) && (anyUnicodeModeOrNonAnnexB || charCodeChecked(pos) === 125 /* closeBrace */)) { + error(Diagnostics.Numbers_out_of_order_in_quantifier, digitsStart, pos - digitsStart); + } + } else if (!min2) { + if (anyUnicodeModeOrNonAnnexB) { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, start2, 1, String.fromCharCode(ch)); + } + isPreviousTermQuantifiable = true; + break; + } + if (charCodeChecked(pos) !== 125 /* closeBrace */) { + if (anyUnicodeModeOrNonAnnexB) { + error(Diagnostics._0_expected, pos, 0, String.fromCharCode(125 /* closeBrace */)); + pos--; + } else { + isPreviousTermQuantifiable = true; + break; + } + } + // falls through + case 42 /* asterisk */: + case 43 /* plus */: + case 63 /* question */: + pos++; + if (charCodeChecked(pos) === 63 /* question */) { + pos++; + } + if (!isPreviousTermQuantifiable) { + error(Diagnostics.There_is_nothing_available_for_repetition, start2, pos - start2); + } + isPreviousTermQuantifiable = false; + break; + case 46 /* dot */: + pos++; + isPreviousTermQuantifiable = true; + break; + case 91 /* openBracket */: + pos++; + if (unicodeSetsMode) { + scanClassSetExpression(); + } else { + scanClassRanges(); + } + scanExpectedChar(93 /* closeBracket */); + isPreviousTermQuantifiable = true; + break; + case 41 /* closeParen */: + if (isInGroup) { + return; + } + // falls through + case 93 /* closeBracket */: + case 125 /* closeBrace */: + if (anyUnicodeModeOrNonAnnexB || ch === 41 /* closeParen */) { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + } + pos++; + isPreviousTermQuantifiable = true; + break; + case 47 /* slash */: + case 124 /* bar */: + return; + default: + scanSourceCharacter(); + isPreviousTermQuantifiable = true; + break; + } + } + } + function scanPatternModifiers(currFlags) { + while (true) { + const ch = codePointChecked(pos); + if (ch === -1 /* EOF */ || !isIdentifierPart(ch, languageVersion)) { + break; + } + const size = charSize(ch); + const flag = characterCodeToRegularExpressionFlag(ch); + if (flag === void 0) { + error(Diagnostics.Unknown_regular_expression_flag, pos, size); + } else if (currFlags & flag) { + error(Diagnostics.Duplicate_regular_expression_flag, pos, size); + } else if (!(flag & 28 /* Modifiers */)) { + error(Diagnostics.This_regular_expression_flag_cannot_be_toggled_within_a_subpattern, pos, size); + } else { + currFlags |= flag; + checkRegularExpressionFlagAvailability(flag, size); + } + pos += size; + } + return currFlags; + } + function scanAtomEscape() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + switch (charCodeChecked(pos)) { + case 107 /* k */: + pos++; + if (charCodeChecked(pos) === 60 /* lessThan */) { + pos++; + scanGroupName( + /*isReference*/ + true + ); + scanExpectedChar(62 /* greaterThan */); + } else if (anyUnicodeModeOrNonAnnexB || namedCaptureGroups) { + error(Diagnostics.k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets, pos - 2, 2); + } + break; + case 113 /* q */: + if (unicodeSetsMode) { + pos++; + error(Diagnostics.q_is_only_available_inside_character_class, pos - 2, 2); + break; + } + // falls through + default: + Debug.assert(scanCharacterClassEscape() || scanDecimalEscape() || scanCharacterEscape( + /*atomEscape*/ + true + )); + break; + } + } + function scanDecimalEscape() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + const ch = charCodeChecked(pos); + if (ch >= 49 /* _1 */ && ch <= 57 /* _9 */) { + const start2 = pos; + scanDigits(); + decimalEscapes = append(decimalEscapes, { pos: start2, end: pos, value: +tokenValue }); + return true; + } + return false; + } + function scanCharacterEscape(atomEscape) { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + let ch = charCodeChecked(pos); + switch (ch) { + case -1 /* EOF */: + error(Diagnostics.Undetermined_character_escape, pos - 1, 1); + return "\\"; + case 99 /* c */: + pos++; + ch = charCodeChecked(pos); + if (isASCIILetter(ch)) { + pos++; + return String.fromCharCode(ch & 31); + } + if (anyUnicodeModeOrNonAnnexB) { + error(Diagnostics.c_must_be_followed_by_an_ASCII_letter, pos - 2, 2); + } else if (atomEscape) { + pos--; + return "\\"; + } + return String.fromCharCode(ch); + case 94 /* caret */: + case 36 /* $ */: + case 47 /* slash */: + case 92 /* backslash */: + case 46 /* dot */: + case 42 /* asterisk */: + case 43 /* plus */: + case 63 /* question */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 91 /* openBracket */: + case 93 /* closeBracket */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + case 124 /* bar */: + pos++; + return String.fromCharCode(ch); + default: + pos--; + return scanEscapeSequence( + 4 /* RegularExpression */ | (annexB ? 8 /* AnnexB */ : 0) | (anyUnicodeMode ? 16 /* AnyUnicodeMode */ : 0) | (atomEscape ? 32 /* AtomEscape */ : 0) + ); + } + } + function scanGroupName(isReference) { + Debug.assertEqual(charCodeUnchecked(pos - 1), 60 /* lessThan */); + tokenStart = pos; + scanIdentifier(codePointChecked(pos), languageVersion); + if (pos === tokenStart) { + error(Diagnostics.Expected_a_capturing_group_name); + } else if (isReference) { + groupNameReferences = append(groupNameReferences, { pos: tokenStart, end: pos, name: tokenValue }); + } else if ((topNamedCapturingGroupsScope == null ? void 0 : topNamedCapturingGroupsScope.has(tokenValue)) || namedCapturingGroupsScopeStack.some((group2) => group2 == null ? void 0 : group2.has(tokenValue))) { + error(Diagnostics.Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other, tokenStart, pos - tokenStart); + } else { + topNamedCapturingGroupsScope ?? (topNamedCapturingGroupsScope = /* @__PURE__ */ new Set()); + topNamedCapturingGroupsScope.add(tokenValue); + groupSpecifiers ?? (groupSpecifiers = /* @__PURE__ */ new Set()); + groupSpecifiers.add(tokenValue); + } + } + function isClassContentExit(ch) { + return ch === 93 /* closeBracket */ || ch === -1 /* EOF */ || pos >= end; + } + function scanClassRanges() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 91 /* openBracket */); + if (charCodeChecked(pos) === 94 /* caret */) { + pos++; + } + while (true) { + const ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + return; + } + const minStart = pos; + const minCharacter = scanClassAtom(); + if (charCodeChecked(pos) === 45 /* minus */) { + pos++; + const ch2 = charCodeChecked(pos); + if (isClassContentExit(ch2)) { + return; + } + if (!minCharacter && anyUnicodeModeOrNonAnnexB) { + error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, minStart, pos - 1 - minStart); + } + const maxStart = pos; + const maxCharacter = scanClassAtom(); + if (!maxCharacter && anyUnicodeModeOrNonAnnexB) { + error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, maxStart, pos - maxStart); + continue; + } + if (!minCharacter) { + continue; + } + const minCharacterValue = codePointAt(minCharacter, 0); + const maxCharacterValue = codePointAt(maxCharacter, 0); + if (minCharacter.length === charSize(minCharacterValue) && maxCharacter.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { + error(Diagnostics.Range_out_of_order_in_character_class, minStart, pos - minStart); + } + } + } + } + function scanClassSetExpression() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 91 /* openBracket */); + let isCharacterComplement = false; + if (charCodeChecked(pos) === 94 /* caret */) { + pos++; + isCharacterComplement = true; + } + let expressionMayContainStrings = false; + let ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + return; + } + let start2 = pos; + let operand; + switch (text.slice(pos, pos + 2)) { + // TODO: don't use slice + case "--": + case "&&": + error(Diagnostics.Expected_a_class_set_operand); + mayContainStrings = false; + break; + default: + operand = scanClassSetOperand(); + break; + } + switch (charCodeChecked(pos)) { + case 45 /* minus */: + if (charCodeChecked(pos + 1) === 45 /* minus */) { + if (isCharacterComplement && mayContainStrings) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + } + expressionMayContainStrings = mayContainStrings; + scanClassSetSubExpression(3 /* ClassSubtraction */); + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + return; + } + break; + case 38 /* ampersand */: + if (charCodeChecked(pos + 1) === 38 /* ampersand */) { + scanClassSetSubExpression(2 /* ClassIntersection */); + if (isCharacterComplement && mayContainStrings) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + } + expressionMayContainStrings = mayContainStrings; + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + return; + } else { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + } + break; + default: + if (isCharacterComplement && mayContainStrings) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + } + expressionMayContainStrings = mayContainStrings; + break; + } + while (true) { + ch = charCodeChecked(pos); + if (ch === -1 /* EOF */) { + break; + } + switch (ch) { + case 45 /* minus */: + pos++; + ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + return; + } + if (ch === 45 /* minus */) { + pos++; + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + start2 = pos - 2; + operand = text.slice(start2, pos); + continue; + } else { + if (!operand) { + error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, start2, pos - 1 - start2); + } + const secondStart = pos; + const secondOperand = scanClassSetOperand(); + if (isCharacterComplement && mayContainStrings) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, secondStart, pos - secondStart); + } + expressionMayContainStrings || (expressionMayContainStrings = mayContainStrings); + if (!secondOperand) { + error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, secondStart, pos - secondStart); + break; + } + if (!operand) { + break; + } + const minCharacterValue = codePointAt(operand, 0); + const maxCharacterValue = codePointAt(secondOperand, 0); + if (operand.length === charSize(minCharacterValue) && secondOperand.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { + error(Diagnostics.Range_out_of_order_in_character_class, start2, pos - start2); + } + } + break; + case 38 /* ampersand */: + start2 = pos; + pos++; + if (charCodeChecked(pos) === 38 /* ampersand */) { + pos++; + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + if (charCodeChecked(pos) === 38 /* ampersand */) { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + pos++; + } + } else { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); + } + operand = text.slice(start2, pos); + continue; + } + if (isClassContentExit(charCodeChecked(pos))) { + break; + } + start2 = pos; + switch (text.slice(pos, pos + 2)) { + // TODO: don't use slice + case "--": + case "&&": + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos, 2); + pos += 2; + operand = text.slice(start2, pos); + break; + default: + operand = scanClassSetOperand(); + break; + } + } + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + } + function scanClassSetSubExpression(expressionType) { + let expressionMayContainStrings = mayContainStrings; + while (true) { + let ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + break; + } + switch (ch) { + case 45 /* minus */: + pos++; + if (charCodeChecked(pos) === 45 /* minus */) { + pos++; + if (expressionType !== 3 /* ClassSubtraction */) { + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + } + } else { + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 1, 1); + } + break; + case 38 /* ampersand */: + pos++; + if (charCodeChecked(pos) === 38 /* ampersand */) { + pos++; + if (expressionType !== 2 /* ClassIntersection */) { + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + } + if (charCodeChecked(pos) === 38 /* ampersand */) { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + pos++; + } + } else { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); + } + break; + default: + switch (expressionType) { + case 3 /* ClassSubtraction */: + error(Diagnostics._0_expected, pos, 0, "--"); + break; + case 2 /* ClassIntersection */: + error(Diagnostics._0_expected, pos, 0, "&&"); + break; + default: + break; + } + break; + } + ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + error(Diagnostics.Expected_a_class_set_operand); + break; + } + scanClassSetOperand(); + expressionMayContainStrings && (expressionMayContainStrings = mayContainStrings); + } + mayContainStrings = expressionMayContainStrings; + } + function scanClassSetOperand() { + mayContainStrings = false; + switch (charCodeChecked(pos)) { + case -1 /* EOF */: + return ""; + case 91 /* openBracket */: + pos++; + scanClassSetExpression(); + scanExpectedChar(93 /* closeBracket */); + return ""; + case 92 /* backslash */: + pos++; + if (scanCharacterClassEscape()) { + return ""; + } else if (charCodeChecked(pos) === 113 /* q */) { + pos++; + if (charCodeChecked(pos) === 123 /* openBrace */) { + pos++; + scanClassStringDisjunctionContents(); + scanExpectedChar(125 /* closeBrace */); + return ""; + } else { + error(Diagnostics.q_must_be_followed_by_string_alternatives_enclosed_in_braces, pos - 2, 2); + return "q"; + } + } + pos--; + // falls through + default: + return scanClassSetCharacter(); + } + } + function scanClassStringDisjunctionContents() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 123 /* openBrace */); + let characterCount = 0; + while (true) { + const ch = charCodeChecked(pos); + switch (ch) { + case -1 /* EOF */: + return; + case 125 /* closeBrace */: + if (characterCount !== 1) { + mayContainStrings = true; + } + return; + case 124 /* bar */: + if (characterCount !== 1) { + mayContainStrings = true; + } + pos++; + start = pos; + characterCount = 0; + break; + default: + scanClassSetCharacter(); + characterCount++; + break; + } + } + } + function scanClassSetCharacter() { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */) { + return ""; + } + if (ch === 92 /* backslash */) { + pos++; + const ch2 = charCodeChecked(pos); + switch (ch2) { + case 98 /* b */: + pos++; + return "\b"; + case 38 /* ampersand */: + case 45 /* minus */: + case 33 /* exclamation */: + case 35 /* hash */: + case 37 /* percent */: + case 44 /* comma */: + case 58 /* colon */: + case 59 /* semicolon */: + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + case 64 /* at */: + case 96 /* backtick */: + case 126 /* tilde */: + pos++; + return String.fromCharCode(ch2); + default: + return scanCharacterEscape( + /*atomEscape*/ + false + ); + } + } else if (ch === charCodeChecked(pos + 1)) { + switch (ch) { + case 38 /* ampersand */: + case 33 /* exclamation */: + case 35 /* hash */: + case 37 /* percent */: + case 42 /* asterisk */: + case 43 /* plus */: + case 44 /* comma */: + case 46 /* dot */: + case 58 /* colon */: + case 59 /* semicolon */: + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + case 63 /* question */: + case 64 /* at */: + case 96 /* backtick */: + case 126 /* tilde */: + error(Diagnostics.A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backslash, pos, 2); + pos += 2; + return text.substring(pos - 2, pos); + } + } + switch (ch) { + case 47 /* slash */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 91 /* openBracket */: + case 93 /* closeBracket */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + case 45 /* minus */: + case 124 /* bar */: + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + pos++; + return String.fromCharCode(ch); + } + return scanSourceCharacter(); + } + function scanClassAtom() { + if (charCodeChecked(pos) === 92 /* backslash */) { + pos++; + const ch = charCodeChecked(pos); + switch (ch) { + case 98 /* b */: + pos++; + return "\b"; + case 45 /* minus */: + pos++; + return String.fromCharCode(ch); + default: + if (scanCharacterClassEscape()) { + return ""; + } + return scanCharacterEscape( + /*atomEscape*/ + false + ); + } + } else { + return scanSourceCharacter(); + } + } + function scanCharacterClassEscape() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + let isCharacterComplement = false; + const start2 = pos - 1; + const ch = charCodeChecked(pos); + switch (ch) { + case 100 /* d */: + case 68 /* D */: + case 115 /* s */: + case 83 /* S */: + case 119 /* w */: + case 87 /* W */: + pos++; + return true; + case 80 /* P */: + isCharacterComplement = true; + // falls through + case 112 /* p */: + pos++; + if (charCodeChecked(pos) === 123 /* openBrace */) { + pos++; + const propertyNameOrValueStart = pos; + const propertyNameOrValue = scanWordCharacters(); + if (charCodeChecked(pos) === 61 /* equals */) { + const propertyName = nonBinaryUnicodeProperties.get(propertyNameOrValue); + if (pos === propertyNameOrValueStart) { + error(Diagnostics.Expected_a_Unicode_property_name); + } else if (propertyName === void 0) { + error(Diagnostics.Unknown_Unicode_property_name, propertyNameOrValueStart, pos - propertyNameOrValueStart); + const suggestion = getSpellingSuggestion(propertyNameOrValue, nonBinaryUnicodeProperties.keys(), identity); + if (suggestion) { + error(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); + } + } + pos++; + const propertyValueStart = pos; + const propertyValue = scanWordCharacters(); + if (pos === propertyValueStart) { + error(Diagnostics.Expected_a_Unicode_property_value); + } else if (propertyName !== void 0 && !valuesOfNonBinaryUnicodeProperties[propertyName].has(propertyValue)) { + error(Diagnostics.Unknown_Unicode_property_value, propertyValueStart, pos - propertyValueStart); + const suggestion = getSpellingSuggestion(propertyValue, valuesOfNonBinaryUnicodeProperties[propertyName], identity); + if (suggestion) { + error(Diagnostics.Did_you_mean_0, propertyValueStart, pos - propertyValueStart, suggestion); + } + } + } else { + if (pos === propertyNameOrValueStart) { + error(Diagnostics.Expected_a_Unicode_property_name_or_value); + } else if (binaryUnicodePropertiesOfStrings.has(propertyNameOrValue)) { + if (!unicodeSetsMode) { + error(Diagnostics.Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_the_Unicode_Sets_v_flag_is_set, propertyNameOrValueStart, pos - propertyNameOrValueStart); + } else if (isCharacterComplement) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, propertyNameOrValueStart, pos - propertyNameOrValueStart); + } else { + mayContainStrings = true; + } + } else if (!valuesOfNonBinaryUnicodeProperties.General_Category.has(propertyNameOrValue) && !binaryUnicodeProperties.has(propertyNameOrValue)) { + error(Diagnostics.Unknown_Unicode_property_name_or_value, propertyNameOrValueStart, pos - propertyNameOrValueStart); + const suggestion = getSpellingSuggestion(propertyNameOrValue, [...valuesOfNonBinaryUnicodeProperties.General_Category, ...binaryUnicodeProperties, ...binaryUnicodePropertiesOfStrings], identity); + if (suggestion) { + error(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); + } + } + } + scanExpectedChar(125 /* closeBrace */); + if (!anyUnicodeMode) { + error(Diagnostics.Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set, start2, pos - start2); + } + } else if (anyUnicodeModeOrNonAnnexB) { + error(Diagnostics._0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces, pos - 2, 2, String.fromCharCode(ch)); + } else { + pos--; + return false; + } + return true; + } + return false; + } + function scanWordCharacters() { + let value = ""; + while (true) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || !isWordCharacter(ch)) { + break; + } + value += String.fromCharCode(ch); + pos++; + } + return value; + } + function scanSourceCharacter() { + const size = anyUnicodeMode ? charSize(codePointChecked(pos)) : 1; + pos += size; + return size > 0 ? text.substring(pos - size, pos) : ""; + } + function scanExpectedChar(ch) { + if (charCodeChecked(pos) === ch) { + pos++; + } else { + error(Diagnostics._0_expected, pos, 0, String.fromCharCode(ch)); + } + } + scanDisjunction( + /*isInGroup*/ + false + ); + forEach(groupNameReferences, (reference) => { + if (!(groupSpecifiers == null ? void 0 : groupSpecifiers.has(reference.name))) { + error(Diagnostics.There_is_no_capturing_group_named_0_in_this_regular_expression, reference.pos, reference.end - reference.pos, reference.name); + if (groupSpecifiers) { + const suggestion = getSpellingSuggestion(reference.name, groupSpecifiers, identity); + if (suggestion) { + error(Diagnostics.Did_you_mean_0, reference.pos, reference.end - reference.pos, suggestion); + } + } + } + }); + forEach(decimalEscapes, (escape) => { + if (escape.value > numberOfCapturingGroups) { + if (numberOfCapturingGroups) { + error(Diagnostics.This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_regular_expression, escape.pos, escape.end - escape.pos, numberOfCapturingGroups); + } else { + error(Diagnostics.This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regular_expression, escape.pos, escape.end - escape.pos); + } + } + }); + } + function checkRegularExpressionFlagAvailability(flag, size) { + const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag); + if (availableFrom && languageVersion < availableFrom) { + error(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, pos, size, getNameOfScriptTarget(availableFrom)); + } + } + function appendIfCommentDirective(commentDirectives2, text2, commentDirectiveRegEx, lineStart) { + const type = getDirectiveFromComment(text2.trimStart(), commentDirectiveRegEx); + if (type === void 0) { + return commentDirectives2; + } + return append( + commentDirectives2, + { + range: { pos: lineStart, end: pos }, + type + } + ); + } + function getDirectiveFromComment(text2, commentDirectiveRegEx) { + const match = commentDirectiveRegEx.exec(text2); + if (!match) { + return void 0; + } + switch (match[1]) { + case "ts-expect-error": + return 0 /* ExpectError */; + case "ts-ignore": + return 1 /* Ignore */; + } + return void 0; + } + function reScanTemplateToken(isTaggedTemplate) { + pos = tokenStart; + return token = scanTemplateAndSetTokenValue(!isTaggedTemplate); + } + function reScanTemplateHeadOrNoSubstitutionTemplate() { + pos = tokenStart; + return token = scanTemplateAndSetTokenValue( + /*shouldEmitInvalidEscapeError*/ + true + ); + } + function reScanJsxToken(allowMultilineJsxText = true) { + pos = tokenStart = fullStartPos; + return token = scanJsxToken(allowMultilineJsxText); + } + function reScanLessThanToken() { + if (token === 48 /* LessThanLessThanToken */) { + pos = tokenStart + 1; + return token = 30 /* LessThanToken */; + } + return token; + } + function reScanHashToken() { + if (token === 81 /* PrivateIdentifier */) { + pos = tokenStart + 1; + return token = 63 /* HashToken */; + } + return token; + } + function reScanQuestionToken() { + Debug.assert(token === 61 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'"); + pos = tokenStart + 1; + return token = 58 /* QuestionToken */; + } + function scanJsxToken(allowMultilineJsxText = true) { + fullStartPos = tokenStart = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + let char = charCodeUnchecked(pos); + if (char === 60 /* lessThan */) { + if (charCodeUnchecked(pos + 1) === 47 /* slash */) { + pos += 2; + return token = 31 /* LessThanSlashToken */; + } + pos++; + return token = 30 /* LessThanToken */; + } + if (char === 123 /* openBrace */) { + pos++; + return token = 19 /* OpenBraceToken */; + } + let firstNonWhitespace = 0; + while (pos < end) { + char = charCodeUnchecked(pos); + if (char === 123 /* openBrace */) { + break; + } + if (char === 60 /* lessThan */) { + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + return token = 7 /* ConflictMarkerTrivia */; + } + break; + } + if (char === 62 /* greaterThan */) { + error(Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1); + } + if (char === 125 /* closeBrace */) { + error(Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); + } + if (isLineBreak(char) && firstNonWhitespace === 0) { + firstNonWhitespace = -1; + } else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) { + break; + } else if (!isWhiteSpaceLike(char)) { + firstNonWhitespace = pos; + } + pos++; + } + tokenValue = text.substring(fullStartPos, pos); + return firstNonWhitespace === -1 ? 13 /* JsxTextAllWhiteSpaces */ : 12 /* JsxText */; + } + function scanJsxIdentifier() { + if (tokenIsIdentifierOrKeyword(token)) { + while (pos < end) { + const ch = charCodeUnchecked(pos); + if (ch === 45 /* minus */) { + tokenValue += "-"; + pos++; + continue; + } + const oldPos = pos; + tokenValue += scanIdentifierParts(); + if (pos === oldPos) { + break; + } + } + return getIdentifierToken(); + } + return token; + } + function scanJsxAttributeValue() { + fullStartPos = pos; + switch (charCodeUnchecked(pos)) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString( + /*jsxAttributeString*/ + true + ); + return token = 11 /* StringLiteral */; + default: + return scan(); + } + } + function reScanJsxAttributeValue() { + pos = tokenStart = fullStartPos; + return scanJsxAttributeValue(); + } + function scanJSDocCommentTextToken(inBackticks) { + fullStartPos = tokenStart = pos; + tokenFlags = 0 /* None */; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + for (let ch = charCodeUnchecked(pos); pos < end && (!isLineBreak(ch) && ch !== 96 /* backtick */); ch = codePointUnchecked(++pos)) { + if (!inBackticks) { + if (ch === 123 /* openBrace */) { + break; + } else if (ch === 64 /* at */ && pos - 1 >= 0 && isWhiteSpaceSingleLine(charCodeUnchecked(pos - 1)) && !(pos + 1 < end && isWhiteSpaceLike(charCodeUnchecked(pos + 1)))) { + break; + } + } + } + if (pos === tokenStart) { + return scanJsDocToken(); + } + tokenValue = text.substring(tokenStart, pos); + return token = 82 /* JSDocCommentTextToken */; + } + function scanJsDocToken() { + fullStartPos = tokenStart = pos; + tokenFlags = 0 /* None */; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + const ch = codePointUnchecked(pos); + pos += charSize(ch); + switch (ch) { + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + while (pos < end && isWhiteSpaceSingleLine(charCodeUnchecked(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + case 64 /* at */: + return token = 60 /* AtToken */; + case 13 /* carriageReturn */: + if (charCodeUnchecked(pos) === 10 /* lineFeed */) { + pos++; + } + // falls through + case 10 /* lineFeed */: + tokenFlags |= 1 /* PrecedingLineBreak */; + return token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: + return token = 42 /* AsteriskToken */; + case 123 /* openBrace */: + return token = 19 /* OpenBraceToken */; + case 125 /* closeBrace */: + return token = 20 /* CloseBraceToken */; + case 91 /* openBracket */: + return token = 23 /* OpenBracketToken */; + case 93 /* closeBracket */: + return token = 24 /* CloseBracketToken */; + case 40 /* openParen */: + return token = 21 /* OpenParenToken */; + case 41 /* closeParen */: + return token = 22 /* CloseParenToken */; + case 60 /* lessThan */: + return token = 30 /* LessThanToken */; + case 62 /* greaterThan */: + return token = 32 /* GreaterThanToken */; + case 61 /* equals */: + return token = 64 /* EqualsToken */; + case 44 /* comma */: + return token = 28 /* CommaToken */; + case 46 /* dot */: + return token = 25 /* DotToken */; + case 96 /* backtick */: + return token = 62 /* BacktickToken */; + case 35 /* hash */: + return token = 63 /* HashToken */; + case 92 /* backslash */: + pos--; + const extendedCookedChar = peekExtendedUnicodeEscape(); + if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) { + tokenValue = scanExtendedUnicodeEscape( + /*shouldEmitInvalidEscapeError*/ + true + ) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + const cookedChar = peekUnicodeEscape(); + if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { + pos += 6; + tokenFlags |= 1024 /* UnicodeEscape */; + tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + pos++; + return token = 0 /* Unknown */; + } + if (isIdentifierStart(ch, languageVersion)) { + let char = ch; + while (pos < end && isIdentifierPart(char = codePointUnchecked(pos), languageVersion) || char === 45 /* minus */) pos += charSize(char); + tokenValue = text.substring(tokenStart, pos); + if (char === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return token = getIdentifierToken(); + } else { + return token = 0 /* Unknown */; + } + } + function speculationHelper(callback, isLookahead) { + const savePos = pos; + const saveStartPos = fullStartPos; + const saveTokenPos = tokenStart; + const saveToken = token; + const saveTokenValue = tokenValue; + const saveTokenFlags = tokenFlags; + const result = callback(); + if (!result || isLookahead) { + pos = savePos; + fullStartPos = saveStartPos; + tokenStart = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + } + return result; + } + function scanRange(start2, length3, callback) { + const saveEnd = end; + const savePos = pos; + const saveStartPos = fullStartPos; + const saveTokenPos = tokenStart; + const saveToken = token; + const saveTokenValue = tokenValue; + const saveTokenFlags = tokenFlags; + const saveErrorExpectations = commentDirectives; + setText(text, start2, length3); + const result = callback(); + end = saveEnd; + pos = savePos; + fullStartPos = saveStartPos; + tokenStart = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + tokenFlags = saveTokenFlags; + commentDirectives = saveErrorExpectations; + return result; + } + function lookAhead(callback) { + return speculationHelper( + callback, + /*isLookahead*/ + true + ); + } + function tryScan(callback) { + return speculationHelper( + callback, + /*isLookahead*/ + false + ); + } + function getText() { + return text; + } + function clearCommentDirectives() { + commentDirectives = void 0; + } + function setText(newText, start2, length3) { + text = newText || ""; + end = length3 === void 0 ? text.length : start2 + length3; + resetTokenState(start2 || 0); + } + function setOnError(errorCallback) { + onError = errorCallback; + } + function setScriptTarget(scriptTarget) { + languageVersion = scriptTarget; + } + function setLanguageVariant(variant) { + languageVariant = variant; + } + function setScriptKind(kind) { + scriptKind = kind; + } + function setJSDocParsingMode(kind) { + jsDocParsingMode = kind; + } + function resetTokenState(position) { + Debug.assert(position >= 0); + pos = position; + fullStartPos = position; + tokenStart = position; + token = 0 /* Unknown */; + tokenValue = void 0; + tokenFlags = 0 /* None */; + } + function setSkipJsDocLeadingAsterisks(skip) { + skipJsDocLeadingAsterisks += skip ? 1 : -1; + } +} +function codePointAt(s, i) { + return s.codePointAt(i); +} +function charSize(ch) { + if (ch >= 65536) { + return 2; + } + if (ch === -1 /* EOF */) { + return 0; + } + return 1; +} +function utf16EncodeAsStringFallback(codePoint) { + Debug.assert(0 <= codePoint && codePoint <= 1114111); + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + const codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 55296; + const codeUnit2 = (codePoint - 65536) % 1024 + 56320; + return String.fromCharCode(codeUnit1, codeUnit2); +} +var utf16EncodeAsStringWorker = String.fromCodePoint ? (codePoint) => String.fromCodePoint(codePoint) : utf16EncodeAsStringFallback; +function utf16EncodeAsString(codePoint) { + return utf16EncodeAsStringWorker(codePoint); +} +var nonBinaryUnicodeProperties = new Map(Object.entries({ + General_Category: "General_Category", + gc: "General_Category", + Script: "Script", + sc: "Script", + Script_Extensions: "Script_Extensions", + scx: "Script_Extensions" +})); +var binaryUnicodeProperties = /* @__PURE__ */ new Set(["ASCII", "ASCII_Hex_Digit", "AHex", "Alphabetic", "Alpha", "Any", "Assigned", "Bidi_Control", "Bidi_C", "Bidi_Mirrored", "Bidi_M", "Case_Ignorable", "CI", "Cased", "Changes_When_Casefolded", "CWCF", "Changes_When_Casemapped", "CWCM", "Changes_When_Lowercased", "CWL", "Changes_When_NFKC_Casefolded", "CWKCF", "Changes_When_Titlecased", "CWT", "Changes_When_Uppercased", "CWU", "Dash", "Default_Ignorable_Code_Point", "DI", "Deprecated", "Dep", "Diacritic", "Dia", "Emoji", "Emoji_Component", "EComp", "Emoji_Modifier", "EMod", "Emoji_Modifier_Base", "EBase", "Emoji_Presentation", "EPres", "Extended_Pictographic", "ExtPict", "Extender", "Ext", "Grapheme_Base", "Gr_Base", "Grapheme_Extend", "Gr_Ext", "Hex_Digit", "Hex", "IDS_Binary_Operator", "IDSB", "IDS_Trinary_Operator", "IDST", "ID_Continue", "IDC", "ID_Start", "IDS", "Ideographic", "Ideo", "Join_Control", "Join_C", "Logical_Order_Exception", "LOE", "Lowercase", "Lower", "Math", "Noncharacter_Code_Point", "NChar", "Pattern_Syntax", "Pat_Syn", "Pattern_White_Space", "Pat_WS", "Quotation_Mark", "QMark", "Radical", "Regional_Indicator", "RI", "Sentence_Terminal", "STerm", "Soft_Dotted", "SD", "Terminal_Punctuation", "Term", "Unified_Ideograph", "UIdeo", "Uppercase", "Upper", "Variation_Selector", "VS", "White_Space", "space", "XID_Continue", "XIDC", "XID_Start", "XIDS"]); +var binaryUnicodePropertiesOfStrings = /* @__PURE__ */ new Set(["Basic_Emoji", "Emoji_Keycap_Sequence", "RGI_Emoji_Modifier_Sequence", "RGI_Emoji_Flag_Sequence", "RGI_Emoji_Tag_Sequence", "RGI_Emoji_ZWJ_Sequence", "RGI_Emoji"]); +var valuesOfNonBinaryUnicodeProperties = { + General_Category: /* @__PURE__ */ new Set(["C", "Other", "Cc", "Control", "cntrl", "Cf", "Format", "Cn", "Unassigned", "Co", "Private_Use", "Cs", "Surrogate", "L", "Letter", "LC", "Cased_Letter", "Ll", "Lowercase_Letter", "Lm", "Modifier_Letter", "Lo", "Other_Letter", "Lt", "Titlecase_Letter", "Lu", "Uppercase_Letter", "M", "Mark", "Combining_Mark", "Mc", "Spacing_Mark", "Me", "Enclosing_Mark", "Mn", "Nonspacing_Mark", "N", "Number", "Nd", "Decimal_Number", "digit", "Nl", "Letter_Number", "No", "Other_Number", "P", "Punctuation", "punct", "Pc", "Connector_Punctuation", "Pd", "Dash_Punctuation", "Pe", "Close_Punctuation", "Pf", "Final_Punctuation", "Pi", "Initial_Punctuation", "Po", "Other_Punctuation", "Ps", "Open_Punctuation", "S", "Symbol", "Sc", "Currency_Symbol", "Sk", "Modifier_Symbol", "Sm", "Math_Symbol", "So", "Other_Symbol", "Z", "Separator", "Zl", "Line_Separator", "Zp", "Paragraph_Separator", "Zs", "Space_Separator"]), + Script: /* @__PURE__ */ new Set(["Adlm", "Adlam", "Aghb", "Caucasian_Albanian", "Ahom", "Arab", "Arabic", "Armi", "Imperial_Aramaic", "Armn", "Armenian", "Avst", "Avestan", "Bali", "Balinese", "Bamu", "Bamum", "Bass", "Bassa_Vah", "Batk", "Batak", "Beng", "Bengali", "Bhks", "Bhaiksuki", "Bopo", "Bopomofo", "Brah", "Brahmi", "Brai", "Braille", "Bugi", "Buginese", "Buhd", "Buhid", "Cakm", "Chakma", "Cans", "Canadian_Aboriginal", "Cari", "Carian", "Cham", "Cher", "Cherokee", "Chrs", "Chorasmian", "Copt", "Coptic", "Qaac", "Cpmn", "Cypro_Minoan", "Cprt", "Cypriot", "Cyrl", "Cyrillic", "Deva", "Devanagari", "Diak", "Dives_Akuru", "Dogr", "Dogra", "Dsrt", "Deseret", "Dupl", "Duployan", "Egyp", "Egyptian_Hieroglyphs", "Elba", "Elbasan", "Elym", "Elymaic", "Ethi", "Ethiopic", "Geor", "Georgian", "Glag", "Glagolitic", "Gong", "Gunjala_Gondi", "Gonm", "Masaram_Gondi", "Goth", "Gothic", "Gran", "Grantha", "Grek", "Greek", "Gujr", "Gujarati", "Guru", "Gurmukhi", "Hang", "Hangul", "Hani", "Han", "Hano", "Hanunoo", "Hatr", "Hatran", "Hebr", "Hebrew", "Hira", "Hiragana", "Hluw", "Anatolian_Hieroglyphs", "Hmng", "Pahawh_Hmong", "Hmnp", "Nyiakeng_Puachue_Hmong", "Hrkt", "Katakana_Or_Hiragana", "Hung", "Old_Hungarian", "Ital", "Old_Italic", "Java", "Javanese", "Kali", "Kayah_Li", "Kana", "Katakana", "Kawi", "Khar", "Kharoshthi", "Khmr", "Khmer", "Khoj", "Khojki", "Kits", "Khitan_Small_Script", "Knda", "Kannada", "Kthi", "Kaithi", "Lana", "Tai_Tham", "Laoo", "Lao", "Latn", "Latin", "Lepc", "Lepcha", "Limb", "Limbu", "Lina", "Linear_A", "Linb", "Linear_B", "Lisu", "Lyci", "Lycian", "Lydi", "Lydian", "Mahj", "Mahajani", "Maka", "Makasar", "Mand", "Mandaic", "Mani", "Manichaean", "Marc", "Marchen", "Medf", "Medefaidrin", "Mend", "Mende_Kikakui", "Merc", "Meroitic_Cursive", "Mero", "Meroitic_Hieroglyphs", "Mlym", "Malayalam", "Modi", "Mong", "Mongolian", "Mroo", "Mro", "Mtei", "Meetei_Mayek", "Mult", "Multani", "Mymr", "Myanmar", "Nagm", "Nag_Mundari", "Nand", "Nandinagari", "Narb", "Old_North_Arabian", "Nbat", "Nabataean", "Newa", "Nkoo", "Nko", "Nshu", "Nushu", "Ogam", "Ogham", "Olck", "Ol_Chiki", "Orkh", "Old_Turkic", "Orya", "Oriya", "Osge", "Osage", "Osma", "Osmanya", "Ougr", "Old_Uyghur", "Palm", "Palmyrene", "Pauc", "Pau_Cin_Hau", "Perm", "Old_Permic", "Phag", "Phags_Pa", "Phli", "Inscriptional_Pahlavi", "Phlp", "Psalter_Pahlavi", "Phnx", "Phoenician", "Plrd", "Miao", "Prti", "Inscriptional_Parthian", "Rjng", "Rejang", "Rohg", "Hanifi_Rohingya", "Runr", "Runic", "Samr", "Samaritan", "Sarb", "Old_South_Arabian", "Saur", "Saurashtra", "Sgnw", "SignWriting", "Shaw", "Shavian", "Shrd", "Sharada", "Sidd", "Siddham", "Sind", "Khudawadi", "Sinh", "Sinhala", "Sogd", "Sogdian", "Sogo", "Old_Sogdian", "Sora", "Sora_Sompeng", "Soyo", "Soyombo", "Sund", "Sundanese", "Sylo", "Syloti_Nagri", "Syrc", "Syriac", "Tagb", "Tagbanwa", "Takr", "Takri", "Tale", "Tai_Le", "Talu", "New_Tai_Lue", "Taml", "Tamil", "Tang", "Tangut", "Tavt", "Tai_Viet", "Telu", "Telugu", "Tfng", "Tifinagh", "Tglg", "Tagalog", "Thaa", "Thaana", "Thai", "Tibt", "Tibetan", "Tirh", "Tirhuta", "Tnsa", "Tangsa", "Toto", "Ugar", "Ugaritic", "Vaii", "Vai", "Vith", "Vithkuqi", "Wara", "Warang_Citi", "Wcho", "Wancho", "Xpeo", "Old_Persian", "Xsux", "Cuneiform", "Yezi", "Yezidi", "Yiii", "Yi", "Zanb", "Zanabazar_Square", "Zinh", "Inherited", "Qaai", "Zyyy", "Common", "Zzzz", "Unknown"]), + Script_Extensions: void 0 +}; +valuesOfNonBinaryUnicodeProperties.Script_Extensions = valuesOfNonBinaryUnicodeProperties.Script; + +// src/compiler/utilitiesPublic.ts +function isExternalModuleNameRelative(moduleName) { + return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); +} +function sortAndDeduplicateDiagnostics(diagnostics) { + return sortAndDeduplicate(diagnostics, compareDiagnostics, diagnosticsEqualityComparer); +} +var targetToLibMap = /* @__PURE__ */ new Map([ + [99 /* ESNext */, "lib.esnext.full.d.ts"], + [11 /* ES2024 */, "lib.es2024.full.d.ts"], + [10 /* ES2023 */, "lib.es2023.full.d.ts"], + [9 /* ES2022 */, "lib.es2022.full.d.ts"], + [8 /* ES2021 */, "lib.es2021.full.d.ts"], + [7 /* ES2020 */, "lib.es2020.full.d.ts"], + [6 /* ES2019 */, "lib.es2019.full.d.ts"], + [5 /* ES2018 */, "lib.es2018.full.d.ts"], + [4 /* ES2017 */, "lib.es2017.full.d.ts"], + [3 /* ES2016 */, "lib.es2016.full.d.ts"], + [2 /* ES2015 */, "lib.es6.d.ts"] + // We don't use lib.es2015.full.d.ts due to breaking change. +]); +function getDefaultLibFileName(options) { + const target = getEmitScriptTarget(options); + switch (target) { + case 99 /* ESNext */: + case 11 /* ES2024 */: + case 10 /* ES2023 */: + case 9 /* ES2022 */: + case 8 /* ES2021 */: + case 7 /* ES2020 */: + case 6 /* ES2019 */: + case 5 /* ES2018 */: + case 4 /* ES2017 */: + case 3 /* ES2016 */: + case 2 /* ES2015 */: + return targetToLibMap.get(target); + default: + return "lib.d.ts"; + } +} +function textSpanEnd(span) { + return span.start + span.length; +} +function textSpanIsEmpty(span) { + return span.length === 0; +} +function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); +} +function textRangeContainsPositionInclusive(range, position) { + return position >= range.pos && position <= range.end; +} +function createTextSpan(start, length2) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length2 < 0) { + throw new Error("length < 0"); + } + return { start, length: length2 }; +} +function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); +} +function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); +} +function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; +} +function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span, newLength }; +} +var unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); +function isParameterPropertyDeclaration(node, parent) { + return isParameter(node) && hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */) && parent.kind === 176 /* Constructor */; +} +function walkUpBindingElementsAndPatterns(binding) { + let node = binding.parent; + while (isBindingElement(node.parent)) { + node = node.parent.parent; + } + return node.parent; +} +function getCombinedFlags(node, getFlags) { + if (isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + let flags = getFlags(node); + if (node.kind === 260 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 261 /* VariableDeclarationList */) { + flags |= getFlags(node); + node = node.parent; + } + if (node && node.kind === 243 /* VariableStatement */) { + flags |= getFlags(node); + } + return flags; +} +function getCombinedModifierFlags(node) { + return getCombinedFlags(node, getEffectiveModifierFlags); +} +function getCombinedNodeFlags(node) { + return getCombinedFlags(node, getNodeFlags); +} +function getNodeFlags(node) { + return node.flags; +} +var supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; +function validateLocaleAndSetLanguage(locale, sys2, errors) { + const lowerCaseLocale = locale.toLowerCase(); + const matchResult = /^([a-z]+)(?:[_-]([a-z]+))?$/.exec(lowerCaseLocale); + if (!matchResult) { + if (errors) { + errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + const language = matchResult[1]; + const territory = matchResult[2]; + if (contains(supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory( + language, + /*territory*/ + void 0, + errors + ); + } + setUILocale(locale); + function trySetLanguageAndTerritory(language2, territory2, errors2) { + const compilerFilePath = normalizePath(sys2.getExecutingFilePath()); + const containingDirectoryPath = getDirectoryPath(compilerFilePath); + let filePath = combinePaths(containingDirectoryPath, language2); + if (territory2) { + filePath = filePath + "-" + territory2; + } + filePath = sys2.resolvePath(combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys2.fileExists(filePath)) { + return false; + } + let fileContents = ""; + try { + fileContents = sys2.readFile(filePath); + } catch { + if (errors2) { + errors2.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + setLocalizedDiagnosticMessages(JSON.parse(fileContents)); + } catch { + if (errors2) { + errors2.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } +} +function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== void 0) { + node = node.original; + } + } + if (!node || !nodeTest) { + return node; + } + return nodeTest(node) ? node : void 0; +} +function findAncestor(node, callback) { + while (node) { + const result = callback(node); + if (result === "quit") { + return void 0; + } else if (result) { + return node; + } + node = node.parent; + } + return void 0; +} +function isParseTreeNode(node) { + return (node.flags & 16 /* Synthesized */) === 0; +} +function getParseTreeNode(node, nodeTest) { + if (node === void 0 || isParseTreeNode(node)) { + return node; + } + node = node.original; + while (node) { + if (isParseTreeNode(node)) { + return !nodeTest || nodeTest(node) ? node : void 0; + } + node = node.original; + } +} +function escapeLeadingUnderscores(identifier) { + return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; +} +function unescapeLeadingUnderscores(identifier) { + const id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; +} +function idText(identifierOrPrivateName) { + return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText); +} +function identifierToKeywordKind(node) { + const token = stringToToken(node.escapedText); + return token ? tryCast(token, isKeyword) : void 0; +} +function symbolName(symbol) { + if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { + return idText(symbol.valueDeclaration.name); + } + return unescapeLeadingUnderscores(symbol.escapedName); +} +function nameForNamelessJSDocTypedef(declaration) { + const hostNode = declaration.parent.parent; + if (!hostNode) { + return void 0; + } + if (isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + switch (hostNode.kind) { + case 243 /* VariableStatement */: + if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + break; + case 244 /* ExpressionStatement */: + let expr = hostNode.expression; + if (expr.kind === 226 /* BinaryExpression */ && expr.operatorToken.kind === 64 /* EqualsToken */) { + expr = expr.left; + } + switch (expr.kind) { + case 211 /* PropertyAccessExpression */: + return expr.name; + case 212 /* ElementAccessExpression */: + const arg = expr.argumentExpression; + if (isIdentifier(arg)) { + return arg; + } + } + break; + case 217 /* ParenthesizedExpression */: { + return getDeclarationIdentifier(hostNode.expression); + } + case 256 /* LabeledStatement */: { + if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + break; + } + } +} +function getDeclarationIdentifier(node) { + const name = getNameOfDeclaration(node); + return name && isIdentifier(name) ? name : void 0; +} +function nodeHasName(statement, name) { + if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) { + return true; + } + if (isVariableStatement(statement) && some(statement.declarationList.declarations, (d) => nodeHasName(d, name))) { + return true; + } + return false; +} +function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); +} +function isNamedDeclaration(node) { + return !!node.name; +} +function getNonAssignedNameOfDeclaration(declaration) { + switch (declaration.kind) { + case 80 /* Identifier */: + return declaration; + case 348 /* JSDocPropertyTag */: + case 341 /* JSDocParameterTag */: { + const { name } = declaration; + if (name.kind === 166 /* QualifiedName */) { + return name.right; + } + break; + } + case 213 /* CallExpression */: + case 226 /* BinaryExpression */: { + const expr2 = declaration; + switch (getAssignmentDeclarationKind(expr2)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return getElementOrPropertyAccessArgumentExpressionOrName(expr2.left); + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr2.arguments[1]; + default: + return void 0; + } + } + case 346 /* JSDocTypedefTag */: + return getNameOfJSDocTypedef(declaration); + case 340 /* JSDocEnumTag */: + return nameForNamelessJSDocTypedef(declaration); + case 277 /* ExportAssignment */: { + const { expression } = declaration; + return isIdentifier(expression) ? expression : void 0; + } + case 212 /* ElementAccessExpression */: + const expr = declaration; + if (isBindableStaticElementAccessExpression(expr)) { + return expr.argumentExpression; + } + } + return declaration.name; +} +function getNameOfDeclaration(declaration) { + if (declaration === void 0) return void 0; + return getNonAssignedNameOfDeclaration(declaration) || (isFunctionExpression(declaration) || isArrowFunction(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : void 0); +} +function getAssignedName(node) { + if (!node.parent) { + return void 0; + } else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) { + return node.parent.name; + } else if (isBinaryExpression(node.parent) && node === node.parent.right) { + if (isIdentifier(node.parent.left)) { + return node.parent.left; + } else if (isAccessExpression(node.parent.left)) { + return getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left); + } + } else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) { + return node.parent.name; + } +} +function getDecorators(node) { + if (hasDecorators(node)) { + return filter(node.modifiers, isDecorator); + } +} +function getModifiers(node) { + if (hasSyntacticModifier(node, 98303 /* Modifier */)) { + return filter(node.modifiers, isModifier); + } +} +function getJSDocParameterTagsWorker(param, noCache) { + if (param.name) { + if (isIdentifier(param.name)) { + const name = param.name.escapedText; + return getJSDocTagsWorker(param.parent, noCache).filter((tag) => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name); + } else { + const i = param.parent.parameters.indexOf(param); + Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); + const paramTags = getJSDocTagsWorker(param.parent, noCache).filter(isJSDocParameterTag); + if (i < paramTags.length) { + return [paramTags[i]]; + } + } + } + return emptyArray; +} +function getJSDocParameterTags(param) { + return getJSDocParameterTagsWorker( + param, + /*noCache*/ + false + ); +} +function getJSDocParameterTagsNoCache(param) { + return getJSDocParameterTagsWorker( + param, + /*noCache*/ + true + ); +} +function getJSDocTypeParameterTagsWorker(param, noCache) { + const name = param.name.escapedText; + return getJSDocTagsWorker(param.parent, noCache).filter((tag) => isJSDocTemplateTag(tag) && tag.typeParameters.some((tp) => tp.name.escapedText === name)); +} +function getJSDocTypeParameterTags(param) { + return getJSDocTypeParameterTagsWorker( + param, + /*noCache*/ + false + ); +} +function getJSDocTypeParameterTagsNoCache(param) { + return getJSDocTypeParameterTagsWorker( + param, + /*noCache*/ + true + ); +} +function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, isJSDocParameterTag); +} +function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, isJSDocAugmentsTag); +} +function getJSDocImplementsTags(node) { + return getAllJSDocTags(node, isJSDocImplementsTag); +} +function getJSDocClassTag(node) { + return getFirstJSDocTag(node, isJSDocClassTag); +} +function getJSDocPublicTagNoCache(node) { + return getFirstJSDocTag( + node, + isJSDocPublicTag, + /*noCache*/ + true + ); +} +function getJSDocPrivateTagNoCache(node) { + return getFirstJSDocTag( + node, + isJSDocPrivateTag, + /*noCache*/ + true + ); +} +function getJSDocProtectedTagNoCache(node) { + return getFirstJSDocTag( + node, + isJSDocProtectedTag, + /*noCache*/ + true + ); +} +function getJSDocReadonlyTagNoCache(node) { + return getFirstJSDocTag( + node, + isJSDocReadonlyTag, + /*noCache*/ + true + ); +} +function getJSDocOverrideTagNoCache(node) { + return getFirstJSDocTag( + node, + isJSDocOverrideTag, + /*noCache*/ + true + ); +} +function getJSDocDeprecatedTag(node) { + return getFirstJSDocTag(node, isJSDocDeprecatedTag); +} +function getJSDocDeprecatedTagNoCache(node) { + return getFirstJSDocTag( + node, + isJSDocDeprecatedTag, + /*noCache*/ + true + ); +} +function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, isJSDocEnumTag); +} +function getJSDocThisTag(node) { + return getFirstJSDocTag(node, isJSDocThisTag); +} +function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, isJSDocReturnTag); +} +function getJSDocSatisfiesTag(node) { + return getFirstJSDocTag(node, isJSDocSatisfiesTag); +} +function getJSDocTypeTag(node) { + const tag = getFirstJSDocTag(node, isJSDocTypeTag); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return void 0; +} +function getJSDocType(node) { + let tag = getFirstJSDocTag(node, isJSDocTypeTag); + if (!tag && isParameter(node)) { + tag = find(getJSDocParameterTags(node), (tag2) => !!tag2.typeExpression); + } + return tag && tag.typeExpression && tag.typeExpression.type; +} +function getJSDocReturnType(node) { + const returnTag = getJSDocReturnTag(node); + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + const typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + const type = typeTag.typeExpression.type; + if (isTypeLiteralNode(type)) { + const sig = find(type.members, isCallSignatureDeclaration); + return sig && sig.type; + } + if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) { + return type.type; + } + } +} +function getJSDocTagsWorker(node, noCache) { + var _a; + if (!canHaveJSDoc(node)) return emptyArray; + let tags = (_a = node.jsDoc) == null ? void 0 : _a.jsDocCache; + if (tags === void 0 || noCache) { + const comments = getJSDocCommentsAndTags(node, noCache); + Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + tags = flatMap(comments, (j) => isJSDoc(j) ? j.tags : j); + if (!noCache) { + node.jsDoc ?? (node.jsDoc = []); + node.jsDoc.jsDocCache = tags; + } + } + return tags; +} +function getJSDocTags(node) { + return getJSDocTagsWorker( + node, + /*noCache*/ + false + ); +} +function getFirstJSDocTag(node, predicate, noCache) { + return find(getJSDocTagsWorker(node, noCache), predicate); +} +function getAllJSDocTags(node, predicate) { + return getJSDocTags(node).filter(predicate); +} +function getTextOfJSDocComment(comment) { + return typeof comment === "string" ? comment : comment == null ? void 0 : comment.map((c) => c.kind === 321 /* JSDocText */ ? c.text : formatJSDocLink(c)).join(""); +} +function formatJSDocLink(link) { + const kind = link.kind === 324 /* JSDocLink */ ? "link" : link.kind === 325 /* JSDocLinkCode */ ? "linkcode" : "linkplain"; + const name = link.name ? entityNameToString(link.name) : ""; + const space = link.name && (link.text === "" || link.text.startsWith("://")) ? "" : " "; + return `{@${kind} ${name}${space}${link.text}}`; +} +function getEffectiveTypeParameterDeclarations(node) { + if (isJSDocSignature(node)) { + if (isJSDocOverloadTag(node.parent)) { + const jsDoc = getJSDocRoot(node.parent); + if (jsDoc && length(jsDoc.tags)) { + return flatMap(jsDoc.tags, (tag) => isJSDocTemplateTag(tag) ? tag.typeParameters : void 0); + } + } + return emptyArray; + } + if (isJSDocTypeAlias(node)) { + Debug.assert(node.parent.kind === 320 /* JSDoc */); + return flatMap(node.parent.tags, (tag) => isJSDocTemplateTag(tag) ? tag.typeParameters : void 0); + } + if (node.typeParameters) { + return node.typeParameters; + } + if (canHaveIllegalTypeParameters(node) && node.typeParameters) { + return node.typeParameters; + } + if (isInJSFile(node)) { + const decls = getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + const typeTag = getJSDocType(node); + if (typeTag && isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return emptyArray; +} +function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint : isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint : void 0; +} +function isMemberName(node) { + return node.kind === 80 /* Identifier */ || node.kind === 81 /* PrivateIdentifier */; +} +function isGetOrSetAccessorDeclaration(node) { + return node.kind === 178 /* SetAccessor */ || node.kind === 177 /* GetAccessor */; +} +function isPropertyAccessChain(node) { + return isPropertyAccessExpression(node) && !!(node.flags & 64 /* OptionalChain */); +} +function isElementAccessChain(node) { + return isElementAccessExpression(node) && !!(node.flags & 64 /* OptionalChain */); +} +function isCallChain(node) { + return isCallExpression(node) && !!(node.flags & 64 /* OptionalChain */); +} +function isOptionalChain(node) { + const kind = node.kind; + return !!(node.flags & 64 /* OptionalChain */) && (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */ || kind === 213 /* CallExpression */ || kind === 235 /* NonNullExpression */); +} +function isOptionalChainRoot(node) { + return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken; +} +function isExpressionOfOptionalChainRoot(node) { + return isOptionalChainRoot(node.parent) && node.parent.expression === node; +} +function isOutermostOptionalChain(node) { + return !isOptionalChain(node.parent) || isOptionalChainRoot(node.parent) || node !== node.parent.expression; +} +function isNullishCoalesce(node) { + return node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 61 /* QuestionQuestionToken */; +} +function isConstTypeReference(node) { + return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "const" && !node.typeArguments; +} +function skipPartiallyEmittedExpressions(node) { + return skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */); +} +function isNonNullChain(node) { + return isNonNullExpression(node) && !!(node.flags & 64 /* OptionalChain */); +} +function isNamedExportBindings(node) { + return node.kind === 280 /* NamespaceExport */ || node.kind === 279 /* NamedExports */; +} +function isJSDocPropertyLikeTag(node) { + return node.kind === 348 /* JSDocPropertyTag */ || node.kind === 341 /* JSDocParameterTag */; +} +function isNodeKind(kind) { + return kind >= 166 /* FirstNode */; +} +function isTokenKind(kind) { + return kind >= 0 /* FirstToken */ && kind <= 165 /* LastToken */; +} +function isNodeArray(array) { + return hasProperty(array, "pos") && hasProperty(array, "end"); +} +function isLiteralKind(kind) { + return 9 /* FirstLiteralToken */ <= kind && kind <= 15 /* LastLiteralToken */; +} +function isLiteralExpression(node) { + return isLiteralKind(node.kind); +} +function isLiteralExpressionOfObject(node) { + switch (node.kind) { + case 210 /* ObjectLiteralExpression */: + case 209 /* ArrayLiteralExpression */: + case 14 /* RegularExpressionLiteral */: + case 218 /* FunctionExpression */: + case 231 /* ClassExpression */: + return true; + } + return false; +} +function isTemplateLiteralKind(kind) { + return 15 /* FirstTemplateToken */ <= kind && kind <= 18 /* LastTemplateToken */; +} +function isTemplateMiddleOrTemplateTail(node) { + const kind = node.kind; + return kind === 17 /* TemplateMiddle */ || kind === 18 /* TemplateTail */; +} +function isImportOrExportSpecifier(node) { + return isImportSpecifier(node) || isExportSpecifier(node); +} +function isTypeOnlyImportDeclaration(node) { + switch (node.kind) { + case 276 /* ImportSpecifier */: + return node.isTypeOnly || node.parent.parent.isTypeOnly; + case 274 /* NamespaceImport */: + return node.parent.isTypeOnly; + case 273 /* ImportClause */: + case 271 /* ImportEqualsDeclaration */: + return node.isTypeOnly; + } + return false; +} +function isTypeOnlyExportDeclaration(node) { + switch (node.kind) { + case 281 /* ExportSpecifier */: + return node.isTypeOnly || node.parent.parent.isTypeOnly; + case 278 /* ExportDeclaration */: + return node.isTypeOnly && !!node.moduleSpecifier && !node.exportClause; + case 280 /* NamespaceExport */: + return node.parent.isTypeOnly; + } + return false; +} +function isTypeOnlyImportOrExportDeclaration(node) { + return isTypeOnlyImportDeclaration(node) || isTypeOnlyExportDeclaration(node); +} +function isPartOfTypeOnlyImportOrExportDeclaration(node) { + return findAncestor(node, isTypeOnlyImportOrExportDeclaration) !== void 0; +} +function isImportAttributeName(node) { + return isStringLiteral(node) || isIdentifier(node); +} +function isGeneratedIdentifier(node) { + var _a; + return isIdentifier(node) && ((_a = node.emitNode) == null ? void 0 : _a.autoGenerate) !== void 0; +} +function isGeneratedPrivateIdentifier(node) { + var _a; + return isPrivateIdentifier(node) && ((_a = node.emitNode) == null ? void 0 : _a.autoGenerate) !== void 0; +} +function isFileLevelReservedGeneratedIdentifier(node) { + const flags = node.emitNode.autoGenerate.flags; + return !!(flags & 32 /* FileLevel */) && !!(flags & 16 /* Optimistic */) && !!(flags & 8 /* ReservedInNestedScopes */); +} +function isPrivateIdentifierClassElementDeclaration(node) { + return (isPropertyDeclaration(node) || isMethodOrAccessor(node)) && isPrivateIdentifier(node.name); +} +function isPrivateIdentifierPropertyAccessExpression(node) { + return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name); +} +function isModifierKind(token) { + switch (token) { + case 128 /* AbstractKeyword */: + case 129 /* AccessorKeyword */: + case 134 /* AsyncKeyword */: + case 87 /* ConstKeyword */: + case 138 /* DeclareKeyword */: + case 90 /* DefaultKeyword */: + case 95 /* ExportKeyword */: + case 103 /* InKeyword */: + case 125 /* PublicKeyword */: + case 123 /* PrivateKeyword */: + case 124 /* ProtectedKeyword */: + case 148 /* ReadonlyKeyword */: + case 126 /* StaticKeyword */: + case 147 /* OutKeyword */: + case 164 /* OverrideKeyword */: + return true; + } + return false; +} +function isParameterPropertyModifier(kind) { + return !!(modifierToFlag(kind) & 31 /* ParameterPropertyModifier */); +} +function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 126 /* StaticKeyword */ || idToken === 164 /* OverrideKeyword */ || idToken === 129 /* AccessorKeyword */; +} +function isModifier(node) { + return isModifierKind(node.kind); +} +function isEntityName(node) { + const kind = node.kind; + return kind === 166 /* QualifiedName */ || kind === 80 /* Identifier */; +} +function isPropertyName(node) { + const kind = node.kind; + return kind === 80 /* Identifier */ || kind === 81 /* PrivateIdentifier */ || kind === 11 /* StringLiteral */ || kind === 9 /* NumericLiteral */ || kind === 167 /* ComputedPropertyName */; +} +function isBindingName(node) { + const kind = node.kind; + return kind === 80 /* Identifier */ || kind === 206 /* ObjectBindingPattern */ || kind === 207 /* ArrayBindingPattern */; +} +function isFunctionLike(node) { + return !!node && isFunctionLikeKind(node.kind); +} +function isFunctionLikeOrClassStaticBlockDeclaration(node) { + return !!node && (isFunctionLikeKind(node.kind) || isClassStaticBlockDeclaration(node)); +} +function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); +} +function isBooleanLiteral(node) { + return node.kind === 112 /* TrueKeyword */ || node.kind === 97 /* FalseKeyword */; +} +function isFunctionLikeDeclarationKind(kind) { + switch (kind) { + case 262 /* FunctionDeclaration */: + case 174 /* MethodDeclaration */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + return true; + default: + return false; + } +} +function isFunctionLikeKind(kind) { + switch (kind) { + case 173 /* MethodSignature */: + case 179 /* CallSignature */: + case 323 /* JSDocSignature */: + case 180 /* ConstructSignature */: + case 181 /* IndexSignature */: + case 184 /* FunctionType */: + case 317 /* JSDocFunctionType */: + case 185 /* ConstructorType */: + return true; + default: + return isFunctionLikeDeclarationKind(kind); + } +} +function isFunctionOrModuleBlock(node) { + return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent); +} +function isClassElement(node) { + const kind = node.kind; + return kind === 176 /* Constructor */ || kind === 172 /* PropertyDeclaration */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 181 /* IndexSignature */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 240 /* SemicolonClassElement */; +} +function isClassLike(node) { + return node && (node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */); +} +function isAccessor(node) { + return node && (node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */); +} +function isAutoAccessorPropertyDeclaration(node) { + return isPropertyDeclaration(node) && hasAccessorModifier(node); +} +function isClassInstanceProperty(node) { + if (isInJSFile(node) && isExpandoPropertyDeclaration(node)) { + return (!isBindableStaticAccessExpression(node) || !isPrototypeAccess(node.expression)) && !isBindableStaticNameExpression( + node, + /*excludeThisKeyword*/ + true + ); + } + return node.parent && isClassLike(node.parent) && isPropertyDeclaration(node) && !hasAccessorModifier(node); +} +function isMethodOrAccessor(node) { + switch (node.kind) { + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return true; + default: + return false; + } +} +function isModifierLike(node) { + return isModifier(node) || isDecorator(node); +} +function isTypeElement(node) { + const kind = node.kind; + return kind === 180 /* ConstructSignature */ || kind === 179 /* CallSignature */ || kind === 171 /* PropertySignature */ || kind === 173 /* MethodSignature */ || kind === 181 /* IndexSignature */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 354 /* NotEmittedTypeElement */; +} +function isObjectLiteralElementLike(node) { + const kind = node.kind; + return kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 305 /* SpreadAssignment */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; +} +function isTypeNode(node) { + return isTypeNodeKind(node.kind); +} +function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + return true; + } + return false; +} +function isBindingPattern(node) { + if (node) { + const kind = node.kind; + return kind === 207 /* ArrayBindingPattern */ || kind === 206 /* ObjectBindingPattern */; + } + return false; +} +function isAssignmentPattern(node) { + const kind = node.kind; + return kind === 209 /* ArrayLiteralExpression */ || kind === 210 /* ObjectLiteralExpression */; +} +function isArrayBindingElement(node) { + const kind = node.kind; + return kind === 208 /* BindingElement */ || kind === 232 /* OmittedExpression */; +} +function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 260 /* VariableDeclaration */: + case 169 /* Parameter */: + case 208 /* BindingElement */: + return true; + } + return false; +} +function isBindingOrAssignmentElement(node) { + return isVariableDeclaration(node) || isParameter(node) || isObjectBindingOrAssignmentElement(node) || isArrayBindingOrAssignmentElement(node); +} +function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) || isArrayBindingOrAssignmentPattern(node); +} +function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 206 /* ObjectBindingPattern */: + case 210 /* ObjectLiteralExpression */: + return true; + } + return false; +} +function isObjectBindingOrAssignmentElement(node) { + switch (node.kind) { + case 208 /* BindingElement */: + case 303 /* PropertyAssignment */: + // AssignmentProperty + case 304 /* ShorthandPropertyAssignment */: + // AssignmentProperty + case 305 /* SpreadAssignment */: + return true; + } + return false; +} +function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 207 /* ArrayBindingPattern */: + case 209 /* ArrayLiteralExpression */: + return true; + } + return false; +} +function isArrayBindingOrAssignmentElement(node) { + switch (node.kind) { + case 208 /* BindingElement */: + case 232 /* OmittedExpression */: + // Elision + case 230 /* SpreadElement */: + // AssignmentRestElement + case 209 /* ArrayLiteralExpression */: + // ArrayAssignmentPattern + case 210 /* ObjectLiteralExpression */: + // ObjectAssignmentPattern + case 80 /* Identifier */: + // DestructuringAssignmentTarget + case 211 /* PropertyAccessExpression */: + // DestructuringAssignmentTarget + case 212 /* ElementAccessExpression */: + return true; + } + return isAssignmentExpression( + node, + /*excludeCompoundAssignment*/ + true + ); +} +function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { + const kind = node.kind; + return kind === 211 /* PropertyAccessExpression */ || kind === 166 /* QualifiedName */ || kind === 205 /* ImportType */; +} +function isPropertyAccessOrQualifiedName(node) { + const kind = node.kind; + return kind === 211 /* PropertyAccessExpression */ || kind === 166 /* QualifiedName */; +} +function isCallLikeOrFunctionLikeExpression(node) { + return isCallLikeExpression(node) || isFunctionExpressionOrArrowFunction(node); +} +function isCallLikeExpression(node) { + switch (node.kind) { + case 213 /* CallExpression */: + case 214 /* NewExpression */: + case 215 /* TaggedTemplateExpression */: + case 170 /* Decorator */: + case 286 /* JsxOpeningElement */: + case 285 /* JsxSelfClosingElement */: + case 289 /* JsxOpeningFragment */: + return true; + case 226 /* BinaryExpression */: + return node.operatorToken.kind === 104 /* InstanceOfKeyword */; + default: + return false; + } +} +function isCallOrNewExpression(node) { + return node.kind === 213 /* CallExpression */ || node.kind === 214 /* NewExpression */; +} +function isTemplateLiteral(node) { + const kind = node.kind; + return kind === 228 /* TemplateExpression */ || kind === 15 /* NoSubstitutionTemplateLiteral */; +} +function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind); +} +function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + case 214 /* NewExpression */: + case 213 /* CallExpression */: + case 284 /* JsxElement */: + case 285 /* JsxSelfClosingElement */: + case 288 /* JsxFragment */: + case 215 /* TaggedTemplateExpression */: + case 209 /* ArrayLiteralExpression */: + case 217 /* ParenthesizedExpression */: + case 210 /* ObjectLiteralExpression */: + case 231 /* ClassExpression */: + case 218 /* FunctionExpression */: + case 80 /* Identifier */: + case 81 /* PrivateIdentifier */: + // technically this is only an Expression if it's in a `#field in expr` BinaryExpression + case 14 /* RegularExpressionLiteral */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 228 /* TemplateExpression */: + case 97 /* FalseKeyword */: + case 106 /* NullKeyword */: + case 110 /* ThisKeyword */: + case 112 /* TrueKeyword */: + case 108 /* SuperKeyword */: + case 235 /* NonNullExpression */: + case 233 /* ExpressionWithTypeArguments */: + case 236 /* MetaProperty */: + case 102 /* ImportKeyword */: + // technically this is only an Expression if it's in a CallExpression + case 282 /* MissingDeclaration */: + return true; + default: + return false; + } +} +function isUnaryExpression(node) { + return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind); +} +function isUnaryExpressionKind(kind) { + switch (kind) { + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + case 220 /* DeleteExpression */: + case 221 /* TypeOfExpression */: + case 222 /* VoidExpression */: + case 223 /* AwaitExpression */: + case 216 /* TypeAssertionExpression */: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } +} +function isLiteralTypeLiteral(node) { + switch (node.kind) { + case 106 /* NullKeyword */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 224 /* PrefixUnaryExpression */: + return true; + default: + return isLiteralExpression(node); + } +} +function isExpression(node) { + return isExpressionKind(skipPartiallyEmittedExpressions(node).kind); +} +function isExpressionKind(kind) { + switch (kind) { + case 227 /* ConditionalExpression */: + case 229 /* YieldExpression */: + case 219 /* ArrowFunction */: + case 226 /* BinaryExpression */: + case 230 /* SpreadElement */: + case 234 /* AsExpression */: + case 232 /* OmittedExpression */: + case 356 /* CommaListExpression */: + case 355 /* PartiallyEmittedExpression */: + case 238 /* SatisfiesExpression */: + return true; + default: + return isUnaryExpressionKind(kind); + } +} +function isAssertionExpression(node) { + const kind = node.kind; + return kind === 216 /* TypeAssertionExpression */ || kind === 234 /* AsExpression */; +} +function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + return true; + case 256 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; +} +function isScopeMarker(node) { + return isExportAssignment(node) || isExportDeclaration(node); +} +function hasScopeMarker(statements) { + return some(statements, isScopeMarker); +} +function needsScopeMarker(result) { + return !isAnyImportOrReExport(result) && !isExportAssignment(result) && !hasSyntacticModifier(result, 32 /* Export */) && !isAmbientModule(result); +} +function isExternalModuleIndicator(result) { + return isAnyImportOrReExport(result) || isExportAssignment(result) || hasSyntacticModifier(result, 32 /* Export */); +} +function isForInOrOfStatement(node) { + return node.kind === 249 /* ForInStatement */ || node.kind === 250 /* ForOfStatement */; +} +function isConciseBody(node) { + return isBlock(node) || isExpression(node); +} +function isForInitializer(node) { + return isVariableDeclarationList(node) || isExpression(node); +} +function isModuleBody(node) { + const kind = node.kind; + return kind === 268 /* ModuleBlock */ || kind === 267 /* ModuleDeclaration */ || kind === 80 /* Identifier */; +} +function isNamedImportBindings(node) { + const kind = node.kind; + return kind === 275 /* NamedImports */ || kind === 274 /* NamespaceImport */; +} +function isModuleOrEnumDeclaration(node) { + return node.kind === 267 /* ModuleDeclaration */ || node.kind === 266 /* EnumDeclaration */; +} +function canHaveSymbol(node) { + switch (node.kind) { + case 219 /* ArrowFunction */: + case 226 /* BinaryExpression */: + case 208 /* BindingElement */: + case 213 /* CallExpression */: + case 179 /* CallSignature */: + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 175 /* ClassStaticBlockDeclaration */: + case 176 /* Constructor */: + case 185 /* ConstructorType */: + case 180 /* ConstructSignature */: + case 212 /* ElementAccessExpression */: + case 266 /* EnumDeclaration */: + case 306 /* EnumMember */: + case 277 /* ExportAssignment */: + case 278 /* ExportDeclaration */: + case 281 /* ExportSpecifier */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 184 /* FunctionType */: + case 177 /* GetAccessor */: + case 80 /* Identifier */: + case 273 /* ImportClause */: + case 271 /* ImportEqualsDeclaration */: + case 276 /* ImportSpecifier */: + case 181 /* IndexSignature */: + case 264 /* InterfaceDeclaration */: + case 338 /* JSDocCallbackTag */: + case 340 /* JSDocEnumTag */: + case 317 /* JSDocFunctionType */: + case 341 /* JSDocParameterTag */: + case 348 /* JSDocPropertyTag */: + case 323 /* JSDocSignature */: + case 346 /* JSDocTypedefTag */: + case 322 /* JSDocTypeLiteral */: + case 291 /* JsxAttribute */: + case 292 /* JsxAttributes */: + case 293 /* JsxSpreadAttribute */: + case 200 /* MappedType */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 267 /* ModuleDeclaration */: + case 202 /* NamedTupleMember */: + case 280 /* NamespaceExport */: + case 270 /* NamespaceExportDeclaration */: + case 274 /* NamespaceImport */: + case 214 /* NewExpression */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 9 /* NumericLiteral */: + case 210 /* ObjectLiteralExpression */: + case 169 /* Parameter */: + case 211 /* PropertyAccessExpression */: + case 303 /* PropertyAssignment */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 178 /* SetAccessor */: + case 304 /* ShorthandPropertyAssignment */: + case 307 /* SourceFile */: + case 305 /* SpreadAssignment */: + case 11 /* StringLiteral */: + case 265 /* TypeAliasDeclaration */: + case 187 /* TypeLiteral */: + case 168 /* TypeParameter */: + case 260 /* VariableDeclaration */: + return true; + default: + return false; + } +} +function canHaveLocals(node) { + switch (node.kind) { + case 219 /* ArrowFunction */: + case 241 /* Block */: + case 179 /* CallSignature */: + case 269 /* CaseBlock */: + case 299 /* CatchClause */: + case 175 /* ClassStaticBlockDeclaration */: + case 194 /* ConditionalType */: + case 176 /* Constructor */: + case 185 /* ConstructorType */: + case 180 /* ConstructSignature */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 184 /* FunctionType */: + case 177 /* GetAccessor */: + case 181 /* IndexSignature */: + case 338 /* JSDocCallbackTag */: + case 340 /* JSDocEnumTag */: + case 317 /* JSDocFunctionType */: + case 323 /* JSDocSignature */: + case 346 /* JSDocTypedefTag */: + case 200 /* MappedType */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 267 /* ModuleDeclaration */: + case 178 /* SetAccessor */: + case 307 /* SourceFile */: + case 265 /* TypeAliasDeclaration */: + return true; + default: + return false; + } +} +function isDeclarationKind(kind) { + return kind === 219 /* ArrowFunction */ || kind === 208 /* BindingElement */ || kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 176 /* Constructor */ || kind === 266 /* EnumDeclaration */ || kind === 306 /* EnumMember */ || kind === 281 /* ExportSpecifier */ || kind === 262 /* FunctionDeclaration */ || kind === 218 /* FunctionExpression */ || kind === 177 /* GetAccessor */ || kind === 273 /* ImportClause */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 276 /* ImportSpecifier */ || kind === 264 /* InterfaceDeclaration */ || kind === 291 /* JsxAttribute */ || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 267 /* ModuleDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 274 /* NamespaceImport */ || kind === 280 /* NamespaceExport */ || kind === 169 /* Parameter */ || kind === 303 /* PropertyAssignment */ || kind === 172 /* PropertyDeclaration */ || kind === 171 /* PropertySignature */ || kind === 178 /* SetAccessor */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 265 /* TypeAliasDeclaration */ || kind === 168 /* TypeParameter */ || kind === 260 /* VariableDeclaration */ || kind === 346 /* JSDocTypedefTag */ || kind === 338 /* JSDocCallbackTag */ || kind === 348 /* JSDocPropertyTag */ || kind === 202 /* NamedTupleMember */; +} +function isDeclarationStatementKind(kind) { + return kind === 262 /* FunctionDeclaration */ || kind === 282 /* MissingDeclaration */ || kind === 263 /* ClassDeclaration */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 277 /* ExportAssignment */ || kind === 270 /* NamespaceExportDeclaration */; +} +function isStatementKindButNotDeclarationKind(kind) { + return kind === 252 /* BreakStatement */ || kind === 251 /* ContinueStatement */ || kind === 259 /* DebuggerStatement */ || kind === 246 /* DoStatement */ || kind === 244 /* ExpressionStatement */ || kind === 242 /* EmptyStatement */ || kind === 249 /* ForInStatement */ || kind === 250 /* ForOfStatement */ || kind === 248 /* ForStatement */ || kind === 245 /* IfStatement */ || kind === 256 /* LabeledStatement */ || kind === 253 /* ReturnStatement */ || kind === 255 /* SwitchStatement */ || kind === 257 /* ThrowStatement */ || kind === 258 /* TryStatement */ || kind === 243 /* VariableStatement */ || kind === 247 /* WhileStatement */ || kind === 254 /* WithStatement */ || kind === 353 /* NotEmittedStatement */; +} +function isDeclaration(node) { + if (node.kind === 168 /* TypeParameter */) { + return node.parent && node.parent.kind !== 345 /* JSDocTemplateTag */ || isInJSFile(node); + } + return isDeclarationKind(node.kind); +} +function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); +} +function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); +} +function isStatement(node) { + const kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) || isBlockStatement(node); +} +function isBlockStatement(node) { + if (node.kind !== 241 /* Block */) return false; + if (node.parent !== void 0) { + if (node.parent.kind === 258 /* TryStatement */ || node.parent.kind === 299 /* CatchClause */) { + return false; + } + } + return !isFunctionBlock(node); +} +function isStatementOrBlock(node) { + const kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) || kind === 241 /* Block */; +} +function isModuleReference(node) { + const kind = node.kind; + return kind === 283 /* ExternalModuleReference */ || kind === 166 /* QualifiedName */ || kind === 80 /* Identifier */; +} +function isJsxTagNameExpression(node) { + const kind = node.kind; + return kind === 110 /* ThisKeyword */ || kind === 80 /* Identifier */ || kind === 211 /* PropertyAccessExpression */ || kind === 295 /* JsxNamespacedName */; +} +function isJsxChild(node) { + const kind = node.kind; + return kind === 284 /* JsxElement */ || kind === 294 /* JsxExpression */ || kind === 285 /* JsxSelfClosingElement */ || kind === 12 /* JsxText */ || kind === 288 /* JsxFragment */; +} +function isJsxAttributeLike(node) { + const kind = node.kind; + return kind === 291 /* JsxAttribute */ || kind === 293 /* JsxSpreadAttribute */; +} +function isStringLiteralOrJsxExpression(node) { + const kind = node.kind; + return kind === 11 /* StringLiteral */ || kind === 294 /* JsxExpression */; +} +function isJsxOpeningLikeElement(node) { + const kind = node.kind; + return kind === 286 /* JsxOpeningElement */ || kind === 285 /* JsxSelfClosingElement */; +} +function isJsxCallLike(node) { + const kind = node.kind; + return kind === 286 /* JsxOpeningElement */ || kind === 285 /* JsxSelfClosingElement */ || kind === 289 /* JsxOpeningFragment */; +} +function isCaseOrDefaultClause(node) { + const kind = node.kind; + return kind === 296 /* CaseClause */ || kind === 297 /* DefaultClause */; +} +function isJSDocNode(node) { + return node.kind >= 309 /* FirstJSDocNode */ && node.kind <= 351 /* LastJSDocNode */; +} +function isJSDocTag(node) { + return node.kind >= 327 /* FirstJSDocTagNode */ && node.kind <= 351 /* LastJSDocTagNode */; +} +function isSetAccessor(node) { + return node.kind === 178 /* SetAccessor */; +} +function isGetAccessor(node) { + return node.kind === 177 /* GetAccessor */; +} +function hasJSDocNodes(node) { + if (!canHaveJSDoc(node)) return false; + const { jsDoc } = node; + return !!jsDoc && jsDoc.length > 0; +} +function hasType(node) { + return !!node.type; +} +function hasInitializer(node) { + return !!node.initializer; +} +function hasOnlyExpressionInitializer(node) { + switch (node.kind) { + case 260 /* VariableDeclaration */: + case 169 /* Parameter */: + case 208 /* BindingElement */: + case 172 /* PropertyDeclaration */: + case 303 /* PropertyAssignment */: + case 306 /* EnumMember */: + return true; + default: + return false; + } +} +function isTypeReferenceType(node) { + return node.kind === 183 /* TypeReference */ || node.kind === 233 /* ExpressionWithTypeArguments */; +} +var MAX_SMI_X86 = 1073741823; +function guessIndentation(lines) { + let indentation = MAX_SMI_X86; + for (const line of lines) { + if (!line.length) { + continue; + } + let i = 0; + for (; i < line.length && i < indentation; i++) { + if (!isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? void 0 : indentation; +} +function isStringLiteralLike(node) { + return node.kind === 11 /* StringLiteral */ || node.kind === 15 /* NoSubstitutionTemplateLiteral */; +} +function isJSDocLinkLike(node) { + return node.kind === 324 /* JSDocLink */ || node.kind === 325 /* JSDocLinkCode */ || node.kind === 326 /* JSDocLinkPlain */; +} +function hasRestParameter(s) { + const last2 = lastOrUndefined(s.parameters); + return !!last2 && isRestParameter(last2); +} +function isRestParameter(node) { + const type = isJSDocParameterTag(node) ? node.typeExpression && node.typeExpression.type : node.type; + return node.dotDotDotToken !== void 0 || !!type && type.kind === 318 /* JSDocVariadicType */; +} +function hasInternalAnnotation(range, sourceFile) { + const comment = sourceFile.text.substring(range.pos, range.end); + return comment.includes("@internal"); +} +function isInternalDeclaration(node, sourceFile) { + sourceFile ?? (sourceFile = getSourceFileOfNode(node)); + const parseTreeNode = getParseTreeNode(node); + if (parseTreeNode && parseTreeNode.kind === 169 /* Parameter */) { + const paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); + const previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : void 0; + const text = sourceFile.text; + const commentRanges = previousSibling ? concatenate( + // to handle + // ... parameters, /** @internal */ + // public param: string + getTrailingCommentRanges(text, skipTrivia( + text, + previousSibling.end + 1, + /*stopAfterLineBreak*/ + false, + /*stopAtComments*/ + true + )), + getLeadingCommentRanges(text, node.pos) + ) : getTrailingCommentRanges(text, skipTrivia( + text, + node.pos, + /*stopAfterLineBreak*/ + false, + /*stopAtComments*/ + true + )); + return some(commentRanges) && hasInternalAnnotation(last(commentRanges), sourceFile); + } + const leadingCommentRanges = parseTreeNode && getLeadingCommentRangesOfNode(parseTreeNode, sourceFile); + return !!forEach(leadingCommentRanges, (range) => { + return hasInternalAnnotation(range, sourceFile); + }); +} + +// src/compiler/utilities.ts +var resolvingEmptyArray = []; +var externalHelpersModuleNameText = "tslib"; +var defaultMaximumTruncationLength = 160; +var noTruncationMaximumTruncationLength = 1e6; +function getDeclarationOfKind(symbol, kind) { + const declarations = symbol.declarations; + if (declarations) { + for (const declaration of declarations) { + if (declaration.kind === kind) { + return declaration; + } + } + } + return void 0; +} +function getDeclarationsOfKind(symbol, kind) { + return filter(symbol.declarations || emptyArray, (d) => d.kind === kind); +} +function createSymbolTable(symbols) { + const result = /* @__PURE__ */ new Map(); + if (symbols) { + for (const symbol of symbols) { + result.set(symbol.escapedName, symbol); + } + } + return result; +} +function isTransientSymbol(symbol) { + return (symbol.flags & 33554432 /* Transient */) !== 0; +} +function isExternalModuleSymbol(moduleSymbol) { + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.escapedName.charCodeAt(0) === 34 /* doubleQuote */; +} +var stringWriter = createSingleLineStringWriter(); +function createSingleLineStringWriter() { + var str = ""; + const writeText = (text) => str += text; + return { + getText: () => str, + write: writeText, + rawWrite: writeText, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: (s, _) => writeText(s), + writeTrailingSemicolon: writeText, + writeComment: writeText, + getTextPos: () => str.length, + getLine: () => 0, + getColumn: () => 0, + getIndent: () => 0, + isAtStartOfLine: () => false, + hasTrailingComment: () => false, + hasTrailingWhitespace: () => !!str.length && isWhiteSpaceLike(str.charCodeAt(str.length - 1)), + // Completely ignore indentation for string writers. And map newlines to + // a single space. + writeLine: () => str += " ", + increaseIndent: noop, + decreaseIndent: noop, + clear: () => str = "" + }; +} +function changesAffectModuleResolution(oldOptions, newOptions) { + return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); +} +function optionsHaveModuleResolutionChanges(oldOptions, newOptions) { + return optionsHaveChanges(oldOptions, newOptions, moduleResolutionOptionDeclarations); +} +function changesAffectingProgramStructure(oldOptions, newOptions) { + return optionsHaveChanges(oldOptions, newOptions, optionsAffectingProgramStructure); +} +function optionsHaveChanges(oldOptions, newOptions, optionDeclarations2) { + return oldOptions !== newOptions && optionDeclarations2.some((o) => !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o))); +} +function forEachEntry(map2, callback) { + const iterator = map2.entries(); + for (const [key, value] of iterator) { + const result = callback(value, key); + if (result) { + return result; + } + } + return void 0; +} +function forEachKey(map2, callback) { + const iterator = map2.keys(); + for (const key of iterator) { + const result = callback(key); + if (result) { + return result; + } + } + return void 0; +} +function copyEntries(source, target) { + source.forEach((value, key) => { + target.set(key, value); + }); +} +function usingSingleLineStringWriter(action) { + const oldString = stringWriter.getText(); + try { + action(stringWriter); + return stringWriter.getText(); + } finally { + stringWriter.clear(); + stringWriter.writeKeyword(oldString); + } +} +function getFullWidth(node) { + return node.end - node.pos; +} +function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; +} +function moduleResolutionIsEqualTo(oldResolution, newResolution) { + return oldResolution === newResolution || oldResolution.resolvedModule === newResolution.resolvedModule || !!oldResolution.resolvedModule && !!newResolution.resolvedModule && oldResolution.resolvedModule.isExternalLibraryImport === newResolution.resolvedModule.isExternalLibraryImport && oldResolution.resolvedModule.extension === newResolution.resolvedModule.extension && oldResolution.resolvedModule.resolvedFileName === newResolution.resolvedModule.resolvedFileName && oldResolution.resolvedModule.originalPath === newResolution.resolvedModule.originalPath && packageIdIsEqual(oldResolution.resolvedModule.packageId, newResolution.resolvedModule.packageId) && oldResolution.alternateResult === newResolution.alternateResult; +} +function getResolvedModuleFromResolution(resolution) { + return resolution.resolvedModule; +} +function getResolvedTypeReferenceDirectiveFromResolution(resolution) { + return resolution.resolvedTypeReferenceDirective; +} +function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageName) { + var _a; + const alternateResult = (_a = host.getResolvedModule(sourceFile, moduleReference, mode)) == null ? void 0 : _a.alternateResult; + const alternateResultMessage = alternateResult && (getEmitModuleResolutionKind(host.getCompilerOptions()) === 2 /* Node10 */ ? [Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setting_Consider_updating_to_node16_nodenext_or_bundler, [alternateResult]] : [ + Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings, + [alternateResult, alternateResult.includes(nodeModulesPathPart + "@types/") ? `@types/${mangleScopedPackageName(packageName)}` : packageName] + ]); + const result = alternateResultMessage ? chainDiagnosticMessages( + /*details*/ + void 0, + alternateResultMessage[0], + ...alternateResultMessage[1] + ) : host.typesPackageExists(packageName) ? chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, + packageName, + mangleScopedPackageName(packageName) + ) : host.packageBundlesTypes(packageName) ? chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, + packageName, + moduleReference + ) : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, + moduleReference, + mangleScopedPackageName(packageName) + ); + if (result) result.repopulateInfo = () => ({ moduleReference, mode, packageName: packageName === moduleReference ? void 0 : packageName }); + return result; +} +function createModeMismatchDetails(currentSourceFile) { + const ext = tryGetExtensionFromPath2(currentSourceFile.fileName); + const scope = currentSourceFile.packageJsonScope; + const targetExt = ext === ".ts" /* Ts */ ? ".mts" /* Mts */ : ext === ".js" /* Js */ ? ".mjs" /* Mjs */ : void 0; + const result = scope && !scope.contents.packageJsonContent.type ? targetExt ? chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, + targetExt, + combinePaths(scope.packageDirectory, "package.json") + ) : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, + combinePaths(scope.packageDirectory, "package.json") + ) : targetExt ? chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, + targetExt + ) : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module + ); + result.repopulateInfo = () => true; + return result; +} +function packageIdIsEqual(a, b) { + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version && a.peerDependencies === b.peerDependencies; +} +function packageIdToPackageName({ name, subModuleName }) { + return subModuleName ? `${name}/${subModuleName}` : name; +} +function packageIdToString(packageId) { + return `${packageIdToPackageName(packageId)}@${packageId.version}${packageId.peerDependencies ?? ""}`; +} +function typeDirectiveIsEqualTo(oldResolution, newResolution) { + return oldResolution === newResolution || oldResolution.resolvedTypeReferenceDirective === newResolution.resolvedTypeReferenceDirective || !!oldResolution.resolvedTypeReferenceDirective && !!newResolution.resolvedTypeReferenceDirective && oldResolution.resolvedTypeReferenceDirective.resolvedFileName === newResolution.resolvedTypeReferenceDirective.resolvedFileName && !!oldResolution.resolvedTypeReferenceDirective.primary === !!newResolution.resolvedTypeReferenceDirective.primary && oldResolution.resolvedTypeReferenceDirective.originalPath === newResolution.resolvedTypeReferenceDirective.originalPath; +} +function hasChangesInResolutions(names, newResolutions, getOldResolution, comparer) { + Debug.assert(names.length === newResolutions.length); + for (let i = 0; i < names.length; i++) { + const newResolution = newResolutions[i]; + const entry = names[i]; + const oldResolution = getOldResolution(entry); + const changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; + if (changed) { + return true; + } + } + return false; +} +function containsParseError(node) { + aggregateChildData(node); + return (node.flags & 1048576 /* ThisNodeOrAnySubNodesHasError */) !== 0; +} +function aggregateChildData(node) { + if (!(node.flags & 2097152 /* HasAggregatedChildData */)) { + const thisNodeOrAnySubNodesHasError = (node.flags & 262144 /* ThisNodeHasError */) !== 0 || forEachChild(node, containsParseError); + if (thisNodeOrAnySubNodesHasError) { + node.flags |= 1048576 /* ThisNodeOrAnySubNodesHasError */; + } + node.flags |= 2097152 /* HasAggregatedChildData */; + } +} +function getSourceFileOfNode(node) { + while (node && node.kind !== 307 /* SourceFile */) { + node = node.parent; + } + return node; +} +function getSourceFileOfModule(module2) { + return getSourceFileOfNode(module2.valueDeclaration || getNonAugmentationDeclaration(module2)); +} +function isPlainJsFile(file, checkJs) { + return !!file && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */) && !file.checkJsDirective && checkJs === void 0; +} +function isStatementWithLocals(node) { + switch (node.kind) { + case 241 /* Block */: + case 269 /* CaseBlock */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + return true; + } + return false; +} +function getEndLinePosition(line, sourceFile) { + Debug.assert(line >= 0); + const lineStarts = getLineStarts(sourceFile); + const lineIndex = line; + const sourceText = sourceFile.text; + if (lineIndex + 1 === lineStarts.length) { + return sourceText.length - 1; + } else { + const start = lineStarts[lineIndex]; + let pos = lineStarts[lineIndex + 1] - 1; + Debug.assert(isLineBreak(sourceText.charCodeAt(pos))); + while (start <= pos && isLineBreak(sourceText.charCodeAt(pos))) { + pos--; + } + return pos; + } +} +function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); +} +function nodeIsMissing(node) { + if (node === void 0) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; +} +function nodeIsPresent(node) { + return !nodeIsMissing(node); +} +function insertStatementsAfterPrologue(to, from, isPrologueDirective2) { + if (from === void 0 || from.length === 0) return to; + let statementIndex = 0; + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective2(to[statementIndex])) { + break; + } + } + to.splice(statementIndex, 0, ...from); + return to; +} +function insertStatementAfterPrologue(to, statement, isPrologueDirective2) { + if (statement === void 0) return to; + let statementIndex = 0; + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective2(to[statementIndex])) { + break; + } + } + to.splice(statementIndex, 0, statement); + return to; +} +function isAnyPrologueDirective(node) { + return isPrologueDirective(node) || !!(getEmitFlags(node) & 2097152 /* CustomPrologue */); +} +function insertStatementsAfterStandardPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isPrologueDirective); +} +function insertStatementsAfterCustomPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); +} +function insertStatementAfterCustomPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective); +} +function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && commentPos + 2 < commentEnd && text.charCodeAt(commentPos + 2) === 47 /* slash */) { + const textSubStr = text.substring(commentPos, commentEnd); + return fullTripleSlashReferencePathRegEx.test(textSubStr) || fullTripleSlashAMDReferencePathRegEx.test(textSubStr) || fullTripleSlashAMDModuleRegEx.test(textSubStr) || fullTripleSlashReferenceTypeReferenceDirectiveRegEx.test(textSubStr) || fullTripleSlashLibReferenceRegEx.test(textSubStr) || defaultLibReferenceRegEx.test(textSubStr) ? true : false; + } + return false; +} +function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && text.charCodeAt(start + 2) === 33 /* exclamation */; +} +function createCommentDirectivesMap(sourceFile, commentDirectives) { + const directivesByLine = new Map( + commentDirectives.map((commentDirective) => [ + `${getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line}`, + commentDirective + ]) + ); + const usedLines = /* @__PURE__ */ new Map(); + return { getUnusedExpectations, markUsed }; + function getUnusedExpectations() { + return arrayFrom(directivesByLine.entries()).filter(([line, directive]) => directive.type === 0 /* ExpectError */ && !usedLines.get(line)).map(([_, directive]) => directive); + } + function markUsed(line) { + if (!directivesByLine.has(`${line}`)) { + return false; + } + usedLines.set(`${line}`, true); + return true; + } +} +function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + if (nodeIsMissing(node)) { + return node.pos; + } + if (isJSDocNode(node) || node.kind === 12 /* JsxText */) { + return skipTrivia( + (sourceFile ?? getSourceFileOfNode(node)).text, + node.pos, + /*stopAfterLineBreak*/ + false, + /*stopAtComments*/ + true + ); + } + if (includeJsDoc && hasJSDocNodes(node)) { + return getTokenPosOfNode(node.jsDoc[0], sourceFile); + } + if (node.kind === 352 /* SyntaxList */) { + sourceFile ?? (sourceFile = getSourceFileOfNode(node)); + const first2 = firstOrUndefined(getNodeChildren(node, sourceFile)); + if (first2) { + return getTokenPosOfNode(first2, sourceFile, includeJsDoc); + } + } + return skipTrivia( + (sourceFile ?? getSourceFileOfNode(node)).text, + node.pos, + /*stopAfterLineBreak*/ + false, + /*stopAtComments*/ + false, + isInJSDoc(node) + ); +} +function getNonModifierTokenPosOfNode(node, sourceFile) { + const lastModifier = !nodeIsMissing(node) && canHaveModifiers(node) && node.modifiers ? last(node.modifiers) : void 0; + if (!lastModifier) { + return getTokenPosOfNode(node, sourceFile); + } + return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastModifier.end); +} +function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia = false) { + return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); +} +function isJSDocTypeExpressionOrChild(node) { + return !!findAncestor(node, isJSDocTypeExpression); +} +function isExportNamespaceAsDefaultDeclaration(node) { + return !!(isExportDeclaration(node) && node.exportClause && isNamespaceExport(node.exportClause) && moduleExportNameIsDefault(node.exportClause.name)); +} +function moduleExportNameTextUnescaped(node) { + return node.kind === 11 /* StringLiteral */ ? node.text : unescapeLeadingUnderscores(node.escapedText); +} +function moduleExportNameTextEscaped(node) { + return node.kind === 11 /* StringLiteral */ ? escapeLeadingUnderscores(node.text) : node.escapedText; +} +function moduleExportNameIsDefault(node) { + return (node.kind === 11 /* StringLiteral */ ? node.text : node.escapedText) === "default" /* Default */; +} +function getTextOfNodeFromSourceText(sourceText, node, includeTrivia = false) { + if (nodeIsMissing(node)) { + return ""; + } + let text = sourceText.substring(includeTrivia ? node.pos : skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + text = text.split(/\r\n|\n|\r/).map((line) => line.replace(/^\s*\*/, "").trimStart()).join("\n"); + } + return text; +} +function getTextOfNode(node, includeTrivia = false) { + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); +} +function getPos(range) { + return range.pos; +} +function indexOfNode(nodeArray, node) { + return binarySearch(nodeArray, node, getPos, compareValues); +} +function getEmitFlags(node) { + const emitNode = node.emitNode; + return emitNode && emitNode.flags || 0; +} +function getInternalEmitFlags(node) { + const emitNode = node.emitNode; + return emitNode && emitNode.internalFlags || 0; +} +var getScriptTargetFeatures = /* @__PURE__ */ memoize( + () => new Map(Object.entries({ + Array: new Map(Object.entries({ + es2015: [ + "find", + "findIndex", + "fill", + "copyWithin", + "entries", + "keys", + "values" + ], + es2016: [ + "includes" + ], + es2019: [ + "flat", + "flatMap" + ], + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Iterator: new Map(Object.entries({ + es2015: emptyArray + })), + AsyncIterator: new Map(Object.entries({ + es2015: emptyArray + })), + ArrayBuffer: new Map(Object.entries({ + es2024: [ + "maxByteLength", + "resizable", + "resize", + "detached", + "transfer", + "transferToFixedLength" + ] + })), + Atomics: new Map(Object.entries({ + es2017: [ + "add", + "and", + "compareExchange", + "exchange", + "isLockFree", + "load", + "or", + "store", + "sub", + "wait", + "notify", + "xor" + ], + es2024: [ + "waitAsync" + ] + })), + SharedArrayBuffer: new Map(Object.entries({ + es2017: [ + "byteLength", + "slice" + ], + es2024: [ + "growable", + "maxByteLength", + "grow" + ] + })), + AsyncIterable: new Map(Object.entries({ + es2018: emptyArray + })), + AsyncIterableIterator: new Map(Object.entries({ + es2018: emptyArray + })), + AsyncGenerator: new Map(Object.entries({ + es2018: emptyArray + })), + AsyncGeneratorFunction: new Map(Object.entries({ + es2018: emptyArray + })), + RegExp: new Map(Object.entries({ + es2015: [ + "flags", + "sticky", + "unicode" + ], + es2018: [ + "dotAll" + ], + es2024: [ + "unicodeSets" + ] + })), + Reflect: new Map(Object.entries({ + es2015: [ + "apply", + "construct", + "defineProperty", + "deleteProperty", + "get", + "getOwnPropertyDescriptor", + "getPrototypeOf", + "has", + "isExtensible", + "ownKeys", + "preventExtensions", + "set", + "setPrototypeOf" + ] + })), + ArrayConstructor: new Map(Object.entries({ + es2015: [ + "from", + "of" + ], + esnext: [ + "fromAsync" + ] + })), + ObjectConstructor: new Map(Object.entries({ + es2015: [ + "assign", + "getOwnPropertySymbols", + "keys", + "is", + "setPrototypeOf" + ], + es2017: [ + "values", + "entries", + "getOwnPropertyDescriptors" + ], + es2019: [ + "fromEntries" + ], + es2022: [ + "hasOwn" + ], + es2024: [ + "groupBy" + ] + })), + NumberConstructor: new Map(Object.entries({ + es2015: [ + "isFinite", + "isInteger", + "isNaN", + "isSafeInteger", + "parseFloat", + "parseInt" + ] + })), + Math: new Map(Object.entries({ + es2015: [ + "clz32", + "imul", + "sign", + "log10", + "log2", + "log1p", + "expm1", + "cosh", + "sinh", + "tanh", + "acosh", + "asinh", + "atanh", + "hypot", + "trunc", + "fround", + "cbrt" + ], + esnext: [ + "f16round" + ] + })), + Map: new Map(Object.entries({ + es2015: [ + "entries", + "keys", + "values" + ] + })), + MapConstructor: new Map(Object.entries({ + es2024: [ + "groupBy" + ] + })), + Set: new Map(Object.entries({ + es2015: [ + "entries", + "keys", + "values" + ], + esnext: [ + "union", + "intersection", + "difference", + "symmetricDifference", + "isSubsetOf", + "isSupersetOf", + "isDisjointFrom" + ] + })), + PromiseConstructor: new Map(Object.entries({ + es2015: [ + "all", + "race", + "reject", + "resolve" + ], + es2020: [ + "allSettled" + ], + es2021: [ + "any" + ], + es2024: [ + "withResolvers" + ] + })), + Symbol: new Map(Object.entries({ + es2015: [ + "for", + "keyFor" + ], + es2019: [ + "description" + ] + })), + WeakMap: new Map(Object.entries({ + es2015: [ + "entries", + "keys", + "values" + ] + })), + WeakSet: new Map(Object.entries({ + es2015: [ + "entries", + "keys", + "values" + ] + })), + String: new Map(Object.entries({ + es2015: [ + "codePointAt", + "includes", + "endsWith", + "normalize", + "repeat", + "startsWith", + "anchor", + "big", + "blink", + "bold", + "fixed", + "fontcolor", + "fontsize", + "italics", + "link", + "small", + "strike", + "sub", + "sup" + ], + es2017: [ + "padStart", + "padEnd" + ], + es2019: [ + "trimStart", + "trimEnd", + "trimLeft", + "trimRight" + ], + es2020: [ + "matchAll" + ], + es2021: [ + "replaceAll" + ], + es2022: [ + "at" + ], + es2024: [ + "isWellFormed", + "toWellFormed" + ] + })), + StringConstructor: new Map(Object.entries({ + es2015: [ + "fromCodePoint", + "raw" + ] + })), + DateTimeFormat: new Map(Object.entries({ + es2017: [ + "formatToParts" + ] + })), + Promise: new Map(Object.entries({ + es2015: emptyArray, + es2018: [ + "finally" + ] + })), + RegExpMatchArray: new Map(Object.entries({ + es2018: [ + "groups" + ] + })), + RegExpExecArray: new Map(Object.entries({ + es2018: [ + "groups" + ] + })), + Intl: new Map(Object.entries({ + es2018: [ + "PluralRules" + ] + })), + NumberFormat: new Map(Object.entries({ + es2018: [ + "formatToParts" + ] + })), + SymbolConstructor: new Map(Object.entries({ + es2020: [ + "matchAll" + ], + esnext: [ + "metadata", + "dispose", + "asyncDispose" + ] + })), + DataView: new Map(Object.entries({ + es2020: [ + "setBigInt64", + "setBigUint64", + "getBigInt64", + "getBigUint64" + ], + esnext: [ + "setFloat16", + "getFloat16" + ] + })), + BigInt: new Map(Object.entries({ + es2020: emptyArray + })), + RelativeTimeFormat: new Map(Object.entries({ + es2020: [ + "format", + "formatToParts", + "resolvedOptions" + ] + })), + Int8Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Uint8Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Uint8ClampedArray: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Int16Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Uint16Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Int32Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Uint32Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Float16Array: new Map(Object.entries({ + esnext: emptyArray + })), + Float32Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Float64Array: new Map(Object.entries({ + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + BigInt64Array: new Map(Object.entries({ + es2020: emptyArray, + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + BigUint64Array: new Map(Object.entries({ + es2020: emptyArray, + es2022: [ + "at" + ], + es2023: [ + "findLastIndex", + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" + ] + })), + Error: new Map(Object.entries({ + es2022: [ + "cause" + ] + })) + })) +); +function getLiteralText(node, sourceFile, flags) { + if (sourceFile && canUseOriginalText(node, flags)) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + switch (node.kind) { + case 11 /* StringLiteral */: { + const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } + } + case 15 /* NoSubstitutionTemplateLiteral */: + case 16 /* TemplateHead */: + case 17 /* TemplateMiddle */: + case 18 /* TemplateTail */: { + const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const rawText = node.rawText ?? escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */)); + switch (node.kind) { + case 15 /* NoSubstitutionTemplateLiteral */: + return "`" + rawText + "`"; + case 16 /* TemplateHead */: + return "`" + rawText + "${"; + case 17 /* TemplateMiddle */: + return "}" + rawText + "${"; + case 18 /* TemplateTail */: + return "}" + rawText + "`"; + } + break; + } + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + return node.text; + case 14 /* RegularExpressionLiteral */: + if (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) { + return node.text + (node.text.charCodeAt(node.text.length - 1) === 92 /* backslash */ ? " /" : "/"); + } + return node.text; + } + return Debug.fail(`Literal kind '${node.kind}' not accounted for.`); +} +function canUseOriginalText(node, flags) { + if (nodeIsSynthesized(node) || !node.parent || flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) { + return false; + } + if (isNumericLiteral(node)) { + if (node.numericLiteralFlags & 26656 /* IsInvalid */) { + return false; + } + if (node.numericLiteralFlags & 512 /* ContainsSeparator */) { + return !!(flags & 8 /* AllowNumericSeparator */); + } + } + return !isBigIntLiteral(node); +} +function makeIdentifierFromModuleName(moduleName) { + return getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); +} +function isBlockOrCatchScoped(declaration) { + return (getCombinedNodeFlags(declaration) & 7 /* BlockScoped */) !== 0 || isCatchClauseVariableDeclarationOrBindingElement(declaration); +} +function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + const node = getRootDeclaration(declaration); + return node.kind === 260 /* VariableDeclaration */ && node.parent.kind === 299 /* CatchClause */; +} +function isAmbientModule(node) { + return isModuleDeclaration(node) && (node.name.kind === 11 /* StringLiteral */ || isGlobalScopeAugmentation(node)); +} +function isModuleWithStringLiteralName(node) { + return isModuleDeclaration(node) && node.name.kind === 11 /* StringLiteral */; +} +function isNonGlobalAmbientModule(node) { + return isModuleDeclaration(node) && isStringLiteral(node.name); +} +function isEffectiveModuleDeclaration(node) { + return isModuleDeclaration(node) || isIdentifier(node); +} +function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); +} +function isShorthandAmbientModule(node) { + return !!node && node.kind === 267 /* ModuleDeclaration */ && !node.body; +} +function isBlockScopedContainerTopLevel(node) { + return node.kind === 307 /* SourceFile */ || node.kind === 267 /* ModuleDeclaration */ || isFunctionLikeOrClassStaticBlockDeclaration(node); +} +function isGlobalScopeAugmentation(module2) { + return !!(module2.flags & 2048 /* GlobalAugmentation */); +} +function isExternalModuleAugmentation(node) { + return isAmbientModule(node) && isModuleAugmentationExternal(node); +} +function isModuleAugmentationExternal(node) { + switch (node.parent.kind) { + case 307 /* SourceFile */: + return isExternalModule(node.parent); + case 268 /* ModuleBlock */: + return isAmbientModule(node.parent.parent) && isSourceFile(node.parent.parent.parent) && !isExternalModule(node.parent.parent.parent); + } + return false; +} +function getNonAugmentationDeclaration(symbol) { + var _a; + return (_a = symbol.declarations) == null ? void 0 : _a.find((d) => !isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d))); +} +function isCommonJSContainingModuleKind(kind) { + return kind === 1 /* CommonJS */ || 100 /* Node16 */ <= kind && kind <= 199 /* NodeNext */; +} +function isEffectiveExternalModule(node, compilerOptions) { + return isExternalModule(node) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; +} +function isEffectiveStrictModeSourceFile(node, compilerOptions) { + switch (node.scriptKind) { + case 1 /* JS */: + case 3 /* TS */: + case 2 /* JSX */: + case 4 /* TSX */: + break; + default: + return false; + } + if (node.isDeclarationFile) { + return false; + } + if (getStrictOptionValue(compilerOptions, "alwaysStrict")) { + return true; + } + if (startsWithUseStrict(node.statements)) { + return true; + } + if (isExternalModule(node) || getIsolatedModules(compilerOptions)) { + return true; + } + return false; +} +function isAmbientPropertyDeclaration(node) { + return !!(node.flags & 33554432 /* Ambient */) || hasSyntacticModifier(node, 128 /* Ambient */); +} +function isBlockScope(node, parentNode) { + switch (node.kind) { + case 307 /* SourceFile */: + case 269 /* CaseBlock */: + case 299 /* CatchClause */: + case 267 /* ModuleDeclaration */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 172 /* PropertyDeclaration */: + case 175 /* ClassStaticBlockDeclaration */: + return true; + case 241 /* Block */: + return !isFunctionLikeOrClassStaticBlockDeclaration(parentNode); + } + return false; +} +function isAnyImportSyntax(node) { + switch (node.kind) { + case 272 /* ImportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } +} +function isLateVisibilityPaintedStatement(node) { + switch (node.kind) { + case 272 /* ImportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 243 /* VariableStatement */: + case 263 /* ClassDeclaration */: + case 262 /* FunctionDeclaration */: + case 267 /* ModuleDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 264 /* InterfaceDeclaration */: + case 266 /* EnumDeclaration */: + return true; + default: + return false; + } +} +function hasPossibleExternalModuleReference(node) { + return isAnyImportOrReExport(node) || isModuleDeclaration(node) || isImportTypeNode(node) || isImportCall(node); +} +function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || isExportDeclaration(node); +} +function getEnclosingContainer(node) { + return findAncestor(node.parent, (n) => !!(getContainerFlags(n) & 1 /* IsContainer */)); +} +function getEnclosingBlockScopeContainer(node) { + return findAncestor(node.parent, (current) => isBlockScope(current, current.parent)); +} +function forEachEnclosingBlockScopeContainer(node, cb) { + let container = getEnclosingBlockScopeContainer(node); + while (container) { + cb(container); + container = getEnclosingBlockScopeContainer(container); + } +} +function declarationNameToString(name) { + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); +} +function getNameFromIndexInfo(info) { + return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : void 0; +} +function isComputedNonLiteralName(name) { + return name.kind === 167 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); +} +function tryGetTextOfPropertyName(name) { + var _a; + switch (name.kind) { + case 80 /* Identifier */: + case 81 /* PrivateIdentifier */: + return ((_a = name.emitNode) == null ? void 0 : _a.autoGenerate) ? void 0 : name.escapedText; + case 11 /* StringLiteral */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + return escapeLeadingUnderscores(name.text); + case 167 /* ComputedPropertyName */: + if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text); + return void 0; + case 295 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); + default: + return Debug.assertNever(name); + } +} +function getTextOfPropertyName(name) { + return Debug.checkDefined(tryGetTextOfPropertyName(name)); +} +function entityNameToString(name) { + switch (name.kind) { + case 110 /* ThisKeyword */: + return "this"; + case 81 /* PrivateIdentifier */: + case 80 /* Identifier */: + return getFullWidth(name) === 0 ? idText(name) : getTextOfNode(name); + case 166 /* QualifiedName */: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 211 /* PropertyAccessExpression */: + if (isIdentifier(name.name) || isPrivateIdentifier(name.name)) { + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + } else { + return Debug.assertNever(name.name); + } + case 311 /* JSDocMemberName */: + return entityNameToString(name.left) + "#" + entityNameToString(name.right); + case 295 /* JsxNamespacedName */: + return entityNameToString(name.namespace) + ":" + entityNameToString(name.name); + default: + return Debug.assertNever(name); + } +} +function createDiagnosticForNode(node, message, ...args) { + const sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args); +} +function createDiagnosticForNodeArray(sourceFile, nodes, message, ...args) { + const start = skipTrivia(sourceFile.text, nodes.pos); + return createFileDiagnostic(sourceFile, start, nodes.end - start, message, ...args); +} +function createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args) { + const span = getErrorSpanForNode(sourceFile, node); + return createFileDiagnostic(sourceFile, span.start, span.length, message, ...args); +} +function createDiagnosticForNodeFromMessageChain(sourceFile, node, messageChain, relatedInformation) { + const span = getErrorSpanForNode(sourceFile, node); + return createFileDiagnosticFromMessageChain(sourceFile, span.start, span.length, messageChain, relatedInformation); +} +function createDiagnosticForNodeArrayFromMessageChain(sourceFile, nodes, messageChain, relatedInformation) { + const start = skipTrivia(sourceFile.text, nodes.pos); + return createFileDiagnosticFromMessageChain(sourceFile, start, nodes.end - start, messageChain, relatedInformation); +} +function assertDiagnosticLocation(sourceText, start, length2) { + Debug.assertGreaterThanOrEqual(start, 0); + Debug.assertGreaterThanOrEqual(length2, 0); + Debug.assertLessThanOrEqual(start, sourceText.length); + Debug.assertLessThanOrEqual(start + length2, sourceText.length); +} +function createFileDiagnosticFromMessageChain(file, start, length2, messageChain, relatedInformation) { + assertDiagnosticLocation(file.text, start, length2); + return { + file, + start, + length: length2, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation, + canonicalHead: messageChain.canonicalHead + }; +} +function createDiagnosticForFileFromMessageChain(sourceFile, messageChain, relatedInformation) { + return { + file: sourceFile, + start: 0, + length: 0, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation + }; +} +function createDiagnosticMessageChainFromDiagnostic(diagnostic) { + return typeof diagnostic.messageText === "string" ? { + code: diagnostic.code, + category: diagnostic.category, + messageText: diagnostic.messageText, + next: diagnostic.next + } : diagnostic.messageText; +} +function createDiagnosticForRange(sourceFile, range, message) { + return { + file: sourceFile, + start: range.pos, + length: range.end - range.pos, + code: message.code, + category: message.category, + messageText: message.message + }; +} +function getCanonicalDiagnostic(message, ...args) { + return { + code: message.code, + messageText: formatMessage(message, ...args) + }; +} +function getSpanOfTokenAtPosition(sourceFile, pos) { + const scanner = createScanner( + sourceFile.languageVersion, + /*skipTrivia*/ + true, + sourceFile.languageVariant, + sourceFile.text, + /*onError*/ + void 0, + pos + ); + scanner.scan(); + const start = scanner.getTokenStart(); + return createTextSpanFromBounds(start, scanner.getTokenEnd()); +} +function scanTokenAtPosition(sourceFile, pos) { + const scanner = createScanner( + sourceFile.languageVersion, + /*skipTrivia*/ + true, + sourceFile.languageVariant, + sourceFile.text, + /*onError*/ + void 0, + pos + ); + scanner.scan(); + return scanner.getToken(); +} +function getErrorSpanForArrowFunction(sourceFile, node) { + const pos = skipTrivia(sourceFile.text, node.pos); + if (node.body && node.body.kind === 241 /* Block */) { + const { line: startLine } = getLineAndCharacterOfPosition(sourceFile, node.body.pos); + const { line: endLine } = getLineAndCharacterOfPosition(sourceFile, node.body.end); + if (startLine < endLine) { + return createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); + } + } + return createTextSpanFromBounds(pos, node.end); +} +function getErrorSpanForNode(sourceFile, node) { + let errorNode = node; + switch (node.kind) { + case 307 /* SourceFile */: { + const pos2 = skipTrivia( + sourceFile.text, + 0, + /*stopAfterLineBreak*/ + false + ); + if (pos2 === sourceFile.text.length) { + return createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos2); + } + // This list is a work in progress. Add missing node kinds to improve their error + // spans. + case 260 /* VariableDeclaration */: + case 208 /* BindingElement */: + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 264 /* InterfaceDeclaration */: + case 267 /* ModuleDeclaration */: + case 266 /* EnumDeclaration */: + case 306 /* EnumMember */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 265 /* TypeAliasDeclaration */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 274 /* NamespaceImport */: + errorNode = node.name; + break; + case 219 /* ArrowFunction */: + return getErrorSpanForArrowFunction(sourceFile, node); + case 296 /* CaseClause */: + case 297 /* DefaultClause */: { + const start = skipTrivia(sourceFile.text, node.pos); + const end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return createTextSpanFromBounds(start, end); + } + case 253 /* ReturnStatement */: + case 229 /* YieldExpression */: { + const pos2 = skipTrivia(sourceFile.text, node.pos); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } + case 238 /* SatisfiesExpression */: { + const pos2 = skipTrivia(sourceFile.text, node.expression.end); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } + case 350 /* JSDocSatisfiesTag */: { + const pos2 = skipTrivia(sourceFile.text, node.tagName.pos); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } + case 176 /* Constructor */: { + const constructorDeclaration = node; + const start = skipTrivia(sourceFile.text, constructorDeclaration.pos); + const scanner = createScanner( + sourceFile.languageVersion, + /*skipTrivia*/ + true, + sourceFile.languageVariant, + sourceFile.text, + /*onError*/ + void 0, + start + ); + let token = scanner.scan(); + while (token !== 137 /* ConstructorKeyword */ && token !== 1 /* EndOfFileToken */) { + token = scanner.scan(); + } + const end = scanner.getTokenEnd(); + return createTextSpanFromBounds(start, end); + } + } + if (errorNode === void 0) { + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + Debug.assert(!isJSDoc(errorNode)); + const isMissing = nodeIsMissing(errorNode); + const pos = isMissing || isJsxText(node) ? errorNode.pos : skipTrivia(sourceFile.text, errorNode.pos); + if (isMissing) { + Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } else { + Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"); + } + return createTextSpanFromBounds(pos, errorNode.end); +} +function isGlobalSourceFile(node) { + return node.kind === 307 /* SourceFile */ && !isExternalOrCommonJsModule(node); +} +function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== void 0; +} +function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; +} +function isEnumConst(node) { + return !!(getCombinedModifierFlags(node) & 4096 /* Const */); +} +function isDeclarationReadonly(declaration) { + return !!(getCombinedModifierFlags(declaration) & 8 /* Readonly */ && !isParameterPropertyDeclaration(declaration, declaration.parent)); +} +function isVarAwaitUsing(node) { + return (getCombinedNodeFlags(node) & 7 /* BlockScoped */) === 6 /* AwaitUsing */; +} +function isVarUsing(node) { + return (getCombinedNodeFlags(node) & 7 /* BlockScoped */) === 4 /* Using */; +} +function isVarConst(node) { + return (getCombinedNodeFlags(node) & 7 /* BlockScoped */) === 2 /* Const */; +} +function isVarConstLike(node) { + const blockScopeKind = getCombinedNodeFlags(node) & 7 /* BlockScoped */; + return blockScopeKind === 2 /* Const */ || blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */; +} +function isLet(node) { + return (getCombinedNodeFlags(node) & 7 /* BlockScoped */) === 1 /* Let */; +} +function isSuperCall(n) { + return n.kind === 213 /* CallExpression */ && n.expression.kind === 108 /* SuperKeyword */; +} +function isImportCall(n) { + return n.kind === 213 /* CallExpression */ && n.expression.kind === 102 /* ImportKeyword */; +} +function isImportMeta(n) { + return isMetaProperty(n) && n.keywordToken === 102 /* ImportKeyword */ && n.name.escapedText === "meta"; +} +function isLiteralImportTypeNode(n) { + return isImportTypeNode(n) && isLiteralTypeNode(n.argument) && isStringLiteral(n.argument.literal); +} +function isPrologueDirective(node) { + return node.kind === 244 /* ExpressionStatement */ && node.expression.kind === 11 /* StringLiteral */; +} +function isCustomPrologue(node) { + return !!(getEmitFlags(node) & 2097152 /* CustomPrologue */); +} +function isHoistedFunction(node) { + return isCustomPrologue(node) && isFunctionDeclaration(node); +} +function isHoistedVariable(node) { + return isIdentifier(node.name) && !node.initializer; +} +function isHoistedVariableStatement(node) { + return isCustomPrologue(node) && isVariableStatement(node) && every(node.declarationList.declarations, isHoistedVariable); +} +function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return node.kind !== 12 /* JsxText */ ? getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : void 0; +} +function getJSDocCommentRanges(node, text) { + const commentRanges = node.kind === 169 /* Parameter */ || node.kind === 168 /* TypeParameter */ || node.kind === 218 /* FunctionExpression */ || node.kind === 219 /* ArrowFunction */ || node.kind === 217 /* ParenthesizedExpression */ || node.kind === 260 /* VariableDeclaration */ || node.kind === 281 /* ExportSpecifier */ ? concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRanges(text, node.pos); + return filter(commentRanges, (comment) => comment.end <= node.end && // Due to parse errors sometime empty parameter may get comments assigned to it that end up not in parameter range + text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */); +} +var fullTripleSlashReferencePathRegEx = /^\/\/\/\s*/; +var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^\/\/\/\s*/; +var fullTripleSlashLibReferenceRegEx = /^\/\/\/\s*/; +var fullTripleSlashAMDReferencePathRegEx = /^\/\/\/\s*/; +var fullTripleSlashAMDModuleRegEx = /^\/\/\/\s*/; +var defaultLibReferenceRegEx = /^\/\/\/\s*/; +function isPartOfTypeNode(node) { + if (182 /* FirstTypeNode */ <= node.kind && node.kind <= 205 /* LastTypeNode */) { + return true; + } + switch (node.kind) { + case 133 /* AnyKeyword */: + case 159 /* UnknownKeyword */: + case 150 /* NumberKeyword */: + case 163 /* BigIntKeyword */: + case 154 /* StringKeyword */: + case 136 /* BooleanKeyword */: + case 155 /* SymbolKeyword */: + case 151 /* ObjectKeyword */: + case 157 /* UndefinedKeyword */: + case 106 /* NullKeyword */: + case 146 /* NeverKeyword */: + return true; + case 116 /* VoidKeyword */: + return node.parent.kind !== 222 /* VoidExpression */; + case 233 /* ExpressionWithTypeArguments */: + return isPartOfTypeExpressionWithTypeArguments(node); + case 168 /* TypeParameter */: + return node.parent.kind === 200 /* MappedType */ || node.parent.kind === 195 /* InferType */; + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 80 /* Identifier */: + if (node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } else if (node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node) { + node = node.parent; + } + Debug.assert(node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */ || node.kind === 211 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + // falls through + case 166 /* QualifiedName */: + case 211 /* PropertyAccessExpression */: + case 110 /* ThisKeyword */: { + const { parent } = node; + if (parent.kind === 186 /* TypeQuery */) { + return false; + } + if (parent.kind === 205 /* ImportType */) { + return !parent.isTypeOf; + } + if (182 /* FirstTypeNode */ <= parent.kind && parent.kind <= 205 /* LastTypeNode */) { + return true; + } + switch (parent.kind) { + case 233 /* ExpressionWithTypeArguments */: + return isPartOfTypeExpressionWithTypeArguments(parent); + case 168 /* TypeParameter */: + return node === parent.constraint; + case 345 /* JSDocTemplateTag */: + return node === parent.constraint; + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 169 /* Parameter */: + case 260 /* VariableDeclaration */: + return node === parent.type; + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return node === parent.type; + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 181 /* IndexSignature */: + return node === parent.type; + case 216 /* TypeAssertionExpression */: + return node === parent.type; + case 213 /* CallExpression */: + case 214 /* NewExpression */: + case 215 /* TaggedTemplateExpression */: + return contains(parent.typeArguments, node); + } + } + } + return false; +} +function isPartOfTypeExpressionWithTypeArguments(node) { + return isJSDocImplementsTag(node.parent) || isJSDocAugmentsTag(node.parent) || isHeritageClause(node.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(node); +} +function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 253 /* ReturnStatement */: + return visitor(node); + case 269 /* CaseBlock */: + case 241 /* Block */: + case 245 /* IfStatement */: + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 254 /* WithStatement */: + case 255 /* SwitchStatement */: + case 296 /* CaseClause */: + case 297 /* DefaultClause */: + case 256 /* LabeledStatement */: + case 258 /* TryStatement */: + case 299 /* CatchClause */: + return forEachChild(node, traverse); + } + } +} +function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 229 /* YieldExpression */: + visitor(node); + const operand = node.expression; + if (operand) { + traverse(operand); + } + return; + case 266 /* EnumDeclaration */: + case 264 /* InterfaceDeclaration */: + case 267 /* ModuleDeclaration */: + case 265 /* TypeAliasDeclaration */: + return; + default: + if (isFunctionLike(node)) { + if (node.name && node.name.kind === 167 /* ComputedPropertyName */) { + traverse(node.name.expression); + return; + } + } else if (!isPartOfTypeNode(node)) { + forEachChild(node, traverse); + } + } + } +} +function getRestParameterElementType(node) { + if (node && node.kind === 188 /* ArrayType */) { + return node.elementType; + } else if (node && node.kind === 183 /* TypeReference */) { + return singleOrUndefined(node.typeArguments); + } else { + return void 0; + } +} +function getMembersOfDeclaration(node) { + switch (node.kind) { + case 264 /* InterfaceDeclaration */: + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 187 /* TypeLiteral */: + return node.members; + case 210 /* ObjectLiteralExpression */: + return node.properties; + } +} +function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 208 /* BindingElement */: + case 306 /* EnumMember */: + case 169 /* Parameter */: + case 303 /* PropertyAssignment */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 304 /* ShorthandPropertyAssignment */: + case 260 /* VariableDeclaration */: + return true; + } + } + return false; +} +function isVariableDeclarationInVariableStatement(node) { + return node.parent.kind === 261 /* VariableDeclarationList */ && node.parent.parent.kind === 243 /* VariableStatement */; +} +function isCommonJsExportedExpression(node) { + if (!isInJSFile(node)) return false; + return isObjectLiteralExpression(node.parent) && isBinaryExpression(node.parent.parent) && getAssignmentDeclarationKind(node.parent.parent) === 2 /* ModuleExports */ || isCommonJsExportPropertyAssignment(node.parent); +} +function isCommonJsExportPropertyAssignment(node) { + if (!isInJSFile(node)) return false; + return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 1 /* ExportsProperty */; +} +function isValidESSymbolDeclaration(node) { + return (isVariableDeclaration(node) ? isVarConst(node) && isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : isPropertyDeclaration(node) ? hasEffectiveReadonlyModifier(node) && hasStaticModifier(node) : isPropertySignature(node) && hasEffectiveReadonlyModifier(node)) || isCommonJsExportPropertyAssignment(node); +} +function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + return true; + } + return false; +} +function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { + while (true) { + if (beforeUnwrapLabelCallback) { + beforeUnwrapLabelCallback(node); + } + if (node.statement.kind !== 256 /* LabeledStatement */) { + return node.statement; + } + node = node.statement; + } +} +function isFunctionBlock(node) { + return node && node.kind === 241 /* Block */ && isFunctionLike(node.parent); +} +function isObjectLiteralMethod(node) { + return node && node.kind === 174 /* MethodDeclaration */ && node.parent.kind === 210 /* ObjectLiteralExpression */; +} +function isObjectLiteralOrClassExpressionMethodOrAccessor(node) { + return (node.kind === 174 /* MethodDeclaration */ || node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */) && (node.parent.kind === 210 /* ObjectLiteralExpression */ || node.parent.kind === 231 /* ClassExpression */); +} +function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; +} +function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0 /* This */; +} +function forEachPropertyAssignment(objectLiteral, key, callback, key2) { + return forEach(objectLiteral == null ? void 0 : objectLiteral.properties, (property) => { + if (!isPropertyAssignment(property)) return void 0; + const propName = tryGetTextOfPropertyName(property.name); + return key === propName || key2 && key2 === propName ? callback(property) : void 0; + }); +} +function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + const expression = tsConfigSourceFile.statements[0].expression; + return tryCast(expression, isObjectLiteralExpression); + } +} +function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + return forEachTsConfigPropArray(tsConfigSourceFile, propKey, (property) => isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element) => isStringLiteral(element) && element.text === elementValue) : void 0); +} +function forEachTsConfigPropArray(tsConfigSourceFile, propKey, callback) { + return forEachPropertyAssignment(getTsConfigObjectLiteralExpression(tsConfigSourceFile), propKey, callback); +} +function getContainingFunction(node) { + return findAncestor(node.parent, isFunctionLike); +} +function getContainingClass(node) { + return findAncestor(node.parent, isClassLike); +} +function getContainingClassStaticBlock(node) { + return findAncestor(node.parent, (n) => { + if (isClassLike(n) || isFunctionLike(n)) { + return "quit"; + } + return isClassStaticBlockDeclaration(n); + }); +} +function getContainingFunctionOrClassStaticBlock(node) { + return findAncestor(node.parent, isFunctionLikeOrClassStaticBlockDeclaration); +} +function getContainingClassExcludingClassDecorators(node) { + const decorator = findAncestor(node.parent, (n) => isClassLike(n) ? "quit" : isDecorator(n)); + return decorator && isClassLike(decorator.parent) ? getContainingClass(decorator.parent) : getContainingClass(decorator ?? node); +} +function getThisContainer(node, includeArrowFunctions, includeClassComputedPropertyName) { + Debug.assert(node.kind !== 307 /* SourceFile */); + while (true) { + node = node.parent; + if (!node) { + return Debug.fail(); + } + switch (node.kind) { + case 167 /* ComputedPropertyName */: + if (includeClassComputedPropertyName && isClassLike(node.parent.parent)) { + return node; + } + node = node.parent.parent; + break; + case 170 /* Decorator */: + if (node.parent.kind === 169 /* Parameter */ && isClassElement(node.parent.parent)) { + node = node.parent.parent; + } else if (isClassElement(node.parent)) { + node = node.parent; + } + break; + case 219 /* ArrowFunction */: + if (!includeArrowFunctions) { + continue; + } + // falls through + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 267 /* ModuleDeclaration */: + case 175 /* ClassStaticBlockDeclaration */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 181 /* IndexSignature */: + case 266 /* EnumDeclaration */: + case 307 /* SourceFile */: + return node; + } + } +} +function isThisContainerOrFunctionBlock(node) { + switch (node.kind) { + // Arrow functions use the same scope, but may do so in a "delayed" manner + // For example, `const getThis = () => this` may be before a super() call in a derived constructor + case 219 /* ArrowFunction */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 172 /* PropertyDeclaration */: + return true; + case 241 /* Block */: + switch (node.parent.kind) { + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return true; + default: + return false; + } + default: + return false; + } +} +function isInTopLevelContext(node) { + if (isIdentifier(node) && (isClassDeclaration(node.parent) || isFunctionDeclaration(node.parent)) && node.parent.name === node) { + node = node.parent; + } + const container = getThisContainer( + node, + /*includeArrowFunctions*/ + true, + /*includeClassComputedPropertyName*/ + false + ); + return isSourceFile(container); +} +function getNewTargetContainer(node) { + const container = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (container) { + switch (container.kind) { + case 176 /* Constructor */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + return container; + } + } + return void 0; +} +function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return void 0; + } + switch (node.kind) { + case 167 /* ComputedPropertyName */: + node = node.parent; + break; + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + // falls through + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 175 /* ClassStaticBlockDeclaration */: + return node; + case 170 /* Decorator */: + if (node.parent.kind === 169 /* Parameter */ && isClassElement(node.parent.parent)) { + node = node.parent.parent; + } else if (isClassElement(node.parent)) { + node = node.parent; + } + break; + } + } +} +function getImmediatelyInvokedFunctionExpression(func) { + if (func.kind === 218 /* FunctionExpression */ || func.kind === 219 /* ArrowFunction */) { + let prev = func; + let parent = func.parent; + while (parent.kind === 217 /* ParenthesizedExpression */) { + prev = parent; + parent = parent.parent; + } + if (parent.kind === 213 /* CallExpression */ && parent.expression === prev) { + return parent; + } + } +} +function isSuperProperty(node) { + const kind = node.kind; + return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */) && node.expression.kind === 108 /* SuperKeyword */; +} +function isThisProperty(node) { + const kind = node.kind; + return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */) && node.expression.kind === 110 /* ThisKeyword */; +} +function isThisInitializedDeclaration(node) { + var _a; + return !!node && isVariableDeclaration(node) && ((_a = node.initializer) == null ? void 0 : _a.kind) === 110 /* ThisKeyword */; +} +function isThisInitializedObjectBindingExpression(node) { + return !!node && (isShorthandPropertyAssignment(node) || isPropertyAssignment(node)) && isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 64 /* EqualsToken */ && node.parent.parent.right.kind === 110 /* ThisKeyword */; +} +function getEntityNameFromTypeNode(node) { + switch (node.kind) { + case 183 /* TypeReference */: + return node.typeName; + case 233 /* ExpressionWithTypeArguments */: + return isEntityNameExpression(node.expression) ? node.expression : void 0; + // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. + case 80 /* Identifier */: + case 166 /* QualifiedName */: + return node; + } + return void 0; +} +function getInvokedExpression(node) { + switch (node.kind) { + case 215 /* TaggedTemplateExpression */: + return node.tag; + case 286 /* JsxOpeningElement */: + case 285 /* JsxSelfClosingElement */: + return node.tagName; + case 226 /* BinaryExpression */: + return node.right; + case 289 /* JsxOpeningFragment */: + return node; + default: + return node.expression; + } +} +function nodeCanBeDecorated(useLegacyDecorators, node, parent, grandparent) { + if (useLegacyDecorators && isNamedDeclaration(node) && isPrivateIdentifier(node.name)) { + return false; + } + switch (node.kind) { + case 263 /* ClassDeclaration */: + return true; + case 231 /* ClassExpression */: + return !useLegacyDecorators; + case 172 /* PropertyDeclaration */: + return parent !== void 0 && (useLegacyDecorators ? isClassDeclaration(parent) : isClassLike(parent) && !hasAbstractModifier(node) && !hasAmbientModifier(node)); + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + return node.body !== void 0 && parent !== void 0 && (useLegacyDecorators ? isClassDeclaration(parent) : isClassLike(parent)); + case 169 /* Parameter */: + if (!useLegacyDecorators) return false; + return parent !== void 0 && parent.body !== void 0 && (parent.kind === 176 /* Constructor */ || parent.kind === 174 /* MethodDeclaration */ || parent.kind === 178 /* SetAccessor */) && getThisParameter(parent) !== node && grandparent !== void 0 && grandparent.kind === 263 /* ClassDeclaration */; + } + return false; +} +function nodeIsDecorated(useLegacyDecorators, node, parent, grandparent) { + return hasDecorators(node) && nodeCanBeDecorated(useLegacyDecorators, node, parent, grandparent); +} +function nodeOrChildIsDecorated(useLegacyDecorators, node, parent, grandparent) { + return nodeIsDecorated(useLegacyDecorators, node, parent, grandparent) || childIsDecorated(useLegacyDecorators, node, parent); +} +function childIsDecorated(useLegacyDecorators, node, parent) { + switch (node.kind) { + case 263 /* ClassDeclaration */: + return some(node.members, (m) => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent)); + case 231 /* ClassExpression */: + return !useLegacyDecorators && some(node.members, (m) => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent)); + case 174 /* MethodDeclaration */: + case 178 /* SetAccessor */: + case 176 /* Constructor */: + return some(node.parameters, (p) => nodeIsDecorated(useLegacyDecorators, p, node, parent)); + default: + return false; + } +} +function classOrConstructorParameterIsDecorated(useLegacyDecorators, node) { + if (nodeIsDecorated(useLegacyDecorators, node)) return true; + const constructor = getFirstConstructorWithBody(node); + return !!constructor && childIsDecorated(useLegacyDecorators, constructor, node); +} +function classElementOrClassElementParameterIsDecorated(useLegacyDecorators, node, parent) { + let parameters; + if (isAccessor(node)) { + const { firstAccessor, secondAccessor, setAccessor } = getAllAccessorDeclarations(parent.members, node); + const firstAccessorWithDecorators = hasDecorators(firstAccessor) ? firstAccessor : secondAccessor && hasDecorators(secondAccessor) ? secondAccessor : void 0; + if (!firstAccessorWithDecorators || node !== firstAccessorWithDecorators) { + return false; + } + parameters = setAccessor == null ? void 0 : setAccessor.parameters; + } else if (isMethodDeclaration(node)) { + parameters = node.parameters; + } + if (nodeIsDecorated(useLegacyDecorators, node, parent)) { + return true; + } + if (parameters) { + for (const parameter of parameters) { + if (parameterIsThisKeyword(parameter)) continue; + if (nodeIsDecorated(useLegacyDecorators, parameter, node, parent)) return true; + } + } + return false; +} +function isEmptyStringLiteral(node) { + if (node.textSourceNode) { + switch (node.textSourceNode.kind) { + case 11 /* StringLiteral */: + return isEmptyStringLiteral(node.textSourceNode); + case 15 /* NoSubstitutionTemplateLiteral */: + return node.text === ""; + } + return false; + } + return node.text === ""; +} +function isJSXTagName(node) { + const { parent } = node; + if (parent.kind === 286 /* JsxOpeningElement */ || parent.kind === 285 /* JsxSelfClosingElement */ || parent.kind === 287 /* JsxClosingElement */) { + return parent.tagName === node; + } + return false; +} +function isExpressionNode(node) { + switch (node.kind) { + case 108 /* SuperKeyword */: + case 106 /* NullKeyword */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 14 /* RegularExpressionLiteral */: + case 209 /* ArrayLiteralExpression */: + case 210 /* ObjectLiteralExpression */: + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + case 213 /* CallExpression */: + case 214 /* NewExpression */: + case 215 /* TaggedTemplateExpression */: + case 234 /* AsExpression */: + case 216 /* TypeAssertionExpression */: + case 238 /* SatisfiesExpression */: + case 235 /* NonNullExpression */: + case 217 /* ParenthesizedExpression */: + case 218 /* FunctionExpression */: + case 231 /* ClassExpression */: + case 219 /* ArrowFunction */: + case 222 /* VoidExpression */: + case 220 /* DeleteExpression */: + case 221 /* TypeOfExpression */: + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + case 226 /* BinaryExpression */: + case 227 /* ConditionalExpression */: + case 230 /* SpreadElement */: + case 228 /* TemplateExpression */: + case 232 /* OmittedExpression */: + case 284 /* JsxElement */: + case 285 /* JsxSelfClosingElement */: + case 288 /* JsxFragment */: + case 229 /* YieldExpression */: + case 223 /* AwaitExpression */: + case 236 /* MetaProperty */: + return true; + case 233 /* ExpressionWithTypeArguments */: + return !isHeritageClause(node.parent) && !isJSDocAugmentsTag(node.parent); + case 166 /* QualifiedName */: + while (node.parent.kind === 166 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 186 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node); + case 311 /* JSDocMemberName */: + while (isJSDocMemberName(node.parent)) { + node = node.parent; + } + return node.parent.kind === 186 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node); + case 81 /* PrivateIdentifier */: + return isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 103 /* InKeyword */; + case 80 /* Identifier */: + if (node.parent.kind === 186 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node)) { + return true; + } + // falls through + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 110 /* ThisKeyword */: + return isInExpressionContext(node); + default: + return false; + } +} +function isInExpressionContext(node) { + const { parent } = node; + switch (parent.kind) { + case 260 /* VariableDeclaration */: + case 169 /* Parameter */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 306 /* EnumMember */: + case 303 /* PropertyAssignment */: + case 208 /* BindingElement */: + return parent.initializer === node; + case 244 /* ExpressionStatement */: + case 245 /* IfStatement */: + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + case 253 /* ReturnStatement */: + case 254 /* WithStatement */: + case 255 /* SwitchStatement */: + case 296 /* CaseClause */: + case 257 /* ThrowStatement */: + return parent.expression === node; + case 248 /* ForStatement */: + const forStatement = parent; + return forStatement.initializer === node && forStatement.initializer.kind !== 261 /* VariableDeclarationList */ || forStatement.condition === node || forStatement.incrementor === node; + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + const forInOrOfStatement = parent; + return forInOrOfStatement.initializer === node && forInOrOfStatement.initializer.kind !== 261 /* VariableDeclarationList */ || forInOrOfStatement.expression === node; + case 216 /* TypeAssertionExpression */: + case 234 /* AsExpression */: + return node === parent.expression; + case 239 /* TemplateSpan */: + return node === parent.expression; + case 167 /* ComputedPropertyName */: + return node === parent.expression; + case 170 /* Decorator */: + case 294 /* JsxExpression */: + case 293 /* JsxSpreadAttribute */: + case 305 /* SpreadAssignment */: + return true; + case 233 /* ExpressionWithTypeArguments */: + return parent.expression === node && !isPartOfTypeNode(parent); + case 304 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; + case 238 /* SatisfiesExpression */: + return node === parent.expression; + default: + return isExpressionNode(parent); + } +} +function isPartOfTypeQuery(node) { + while (node.kind === 166 /* QualifiedName */ || node.kind === 80 /* Identifier */) { + node = node.parent; + } + return node.kind === 186 /* TypeQuery */; +} +function isNamespaceReexportDeclaration(node) { + return isNamespaceExport(node) && !!node.parent.moduleSpecifier; +} +function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 283 /* ExternalModuleReference */; +} +function getExternalModuleImportEqualsDeclarationExpression(node) { + Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; +} +function getExternalModuleRequireArgument(node) { + return isVariableDeclarationInitializedToBareOrAccessedRequire(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; +} +function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 283 /* ExternalModuleReference */; +} +function isFullSourceFile(sourceFile) { + return (sourceFile == null ? void 0 : sourceFile.kind) === 307 /* SourceFile */; +} +function isSourceFileJS(file) { + return isInJSFile(file); +} +function isInJSFile(node) { + return !!node && !!(node.flags & 524288 /* JavaScriptFile */); +} +function isInJsonFile(node) { + return !!node && !!(node.flags & 134217728 /* JsonFile */); +} +function isSourceFileNotJson(file) { + return !isJsonSourceFile(file); +} +function isInJSDoc(node) { + return !!node && !!(node.flags & 16777216 /* JSDoc */); +} +function isJSDocIndexSignature(node) { + return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && (node.typeArguments[0].kind === 154 /* StringKeyword */ || node.typeArguments[0].kind === 150 /* NumberKeyword */); +} +function isRequireCall(callExpression, requireStringLiteralLikeArgument) { + if (callExpression.kind !== 213 /* CallExpression */) { + return false; + } + const { expression, arguments: args } = callExpression; + if (expression.kind !== 80 /* Identifier */ || expression.escapedText !== "require") { + return false; + } + if (args.length !== 1) { + return false; + } + const arg = args[0]; + return !requireStringLiteralLikeArgument || isStringLiteralLike(arg); +} +function isVariableDeclarationInitializedToRequire(node) { + return isVariableDeclarationInitializedWithRequireHelper( + node, + /*allowAccessedRequire*/ + false + ); +} +function isVariableDeclarationInitializedToBareOrAccessedRequire(node) { + return isVariableDeclarationInitializedWithRequireHelper( + node, + /*allowAccessedRequire*/ + true + ); +} +function isBindingElementOfBareOrAccessedRequire(node) { + return isBindingElement(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); +} +function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { + return isVariableDeclaration(node) && !!node.initializer && isRequireCall( + allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, + /*requireStringLiteralLikeArgument*/ + true + ); +} +function isRequireVariableStatement(node) { + return isVariableStatement(node) && node.declarationList.declarations.length > 0 && every(node.declarationList.declarations, (decl) => isVariableDeclarationInitializedToRequire(decl)); +} +function isSingleOrDoubleQuote(charCode) { + return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; +} +function isStringDoubleQuoted(str, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; +} +function isAssignmentDeclaration(decl) { + return isBinaryExpression(decl) || isAccessExpression(decl) || isIdentifier(decl) || isCallExpression(decl); +} +function getEffectiveInitializer(node) { + if (isInJSFile(node) && node.initializer && isBinaryExpression(node.initializer) && (node.initializer.operatorToken.kind === 57 /* BarBarToken */ || node.initializer.operatorToken.kind === 61 /* QuestionQuestionToken */) && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + return node.initializer.right; + } + return node.initializer; +} +function getDeclaredExpandoInitializer(node) { + const init = getEffectiveInitializer(node); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); +} +function hasExpandoValueProperty(node, isPrototypeAssignment) { + return forEach(node.properties, (p) => isPropertyAssignment(p) && isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment)); +} +function getAssignedExpandoInitializer(node) { + if (node && node.parent && isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 64 /* EqualsToken */) { + const isPrototypeAssignment = isPrototypeAccess(node.parent.left); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + } + if (node && isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + const result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } + } +} +function getExpandoInitializer(initializer, isPrototypeAssignment) { + if (isCallExpression(initializer)) { + const e = skipParentheses(initializer.expression); + return e.kind === 218 /* FunctionExpression */ || e.kind === 219 /* ArrowFunction */ ? initializer : void 0; + } + if (initializer.kind === 218 /* FunctionExpression */ || initializer.kind === 231 /* ClassExpression */ || initializer.kind === 219 /* ArrowFunction */) { + return initializer; + } + if (isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { + return initializer; + } +} +function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + const e = isBinaryExpression(initializer) && (initializer.operatorToken.kind === 57 /* BarBarToken */ || initializer.operatorToken.kind === 61 /* QuestionQuestionToken */) && getExpandoInitializer(initializer.right, isPrototypeAssignment); + if (e && isSameEntityName(name, initializer.left)) { + return e; + } +} +function isDefaultedExpandoInitializer(node) { + const name = isVariableDeclaration(node.parent) ? node.parent.name : isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 64 /* EqualsToken */ ? node.parent.left : void 0; + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); +} +function getNameOfExpando(node) { + if (isBinaryExpression(node.parent)) { + const parent = (node.parent.operatorToken.kind === 57 /* BarBarToken */ || node.parent.operatorToken.kind === 61 /* QuestionQuestionToken */) && isBinaryExpression(node.parent.parent) ? node.parent.parent : node.parent; + if (parent.operatorToken.kind === 64 /* EqualsToken */ && isIdentifier(parent.left)) { + return parent.left; + } + } else if (isVariableDeclaration(node.parent)) { + return node.parent.name; + } +} +function isSameEntityName(name, initializer) { + if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) { + return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(initializer); + } + if (isMemberName(name) && isLiteralLikeAccess(initializer) && (initializer.expression.kind === 110 /* ThisKeyword */ || isIdentifier(initializer.expression) && (initializer.expression.escapedText === "window" || initializer.expression.escapedText === "self" || initializer.expression.escapedText === "global"))) { + return isSameEntityName(name, getNameOrArgument(initializer)); + } + if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) { + return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer) && isSameEntityName(name.expression, initializer.expression); + } + return false; +} +function getRightMostAssignedExpression(node) { + while (isAssignmentExpression( + node, + /*excludeCompoundAssignment*/ + true + )) { + node = node.right; + } + return node; +} +function isExportsIdentifier(node) { + return isIdentifier(node) && node.escapedText === "exports"; +} +function isModuleIdentifier(node) { + return isIdentifier(node) && node.escapedText === "module"; +} +function isModuleExportsAccessExpression(node) { + return (isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) && isModuleIdentifier(node.expression) && getElementOrPropertyAccessName(node) === "exports"; +} +function getAssignmentDeclarationKind(expr) { + const special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; +} +function isBindableObjectDefinePropertyCall(expr) { + return length(expr.arguments) === 3 && isPropertyAccessExpression(expr.expression) && isIdentifier(expr.expression.expression) && idText(expr.expression.expression) === "Object" && idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && isBindableStaticNameExpression( + expr.arguments[0], + /*excludeThisKeyword*/ + true + ); +} +function isLiteralLikeAccess(node) { + return isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node); +} +function isLiteralLikeElementAccess(node) { + return isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); +} +function isBindableStaticAccessExpression(node, excludeThisKeyword) { + return isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 110 /* ThisKeyword */ || isIdentifier(node.name) && isBindableStaticNameExpression( + node.expression, + /*excludeThisKeyword*/ + true + )) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); +} +function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { + return isLiteralLikeElementAccess(node) && (!excludeThisKeyword && node.expression.kind === 110 /* ThisKeyword */ || isEntityNameExpression(node.expression) || isBindableStaticAccessExpression( + node.expression, + /*excludeThisKeyword*/ + true + )); +} +function isBindableStaticNameExpression(node, excludeThisKeyword) { + return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); +} +function getNameOrArgument(expr) { + if (isPropertyAccessExpression(expr)) { + return expr.name; + } + return expr.argumentExpression; +} +function getAssignmentDeclarationKindWorker(expr) { + if (isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return 0 /* None */; + } + const entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) { + return 8 /* ObjectDefinePropertyExports */; + } + if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") { + return 9 /* ObjectDefinePrototypeProperty */; + } + return 7 /* ObjectDefinePropertyValue */; + } + if (expr.operatorToken.kind !== 64 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) { + return 0 /* None */; + } + if (isBindableStaticNameExpression( + expr.left.expression, + /*excludeThisKeyword*/ + true + ) && getElementOrPropertyAccessName(expr.left) === "prototype" && isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + return 6 /* Prototype */; + } + return getAssignmentDeclarationPropertyAccessKind(expr.left); +} +function isVoidZero(node) { + return isVoidExpression(node) && isNumericLiteral(node.expression) && node.expression.text === "0"; +} +function getElementOrPropertyAccessArgumentExpressionOrName(node) { + if (isPropertyAccessExpression(node)) { + return node.name; + } + const arg = skipParentheses(node.argumentExpression); + if (isNumericLiteral(arg) || isStringLiteralLike(arg)) { + return arg; + } + return node; +} +function getElementOrPropertyAccessName(node) { + const name = getElementOrPropertyAccessArgumentExpressionOrName(node); + if (name) { + if (isIdentifier(name)) { + return name.escapedText; + } + if (isStringLiteralLike(name) || isNumericLiteral(name)) { + return escapeLeadingUnderscores(name.text); + } + } + return void 0; +} +function getAssignmentDeclarationPropertyAccessKind(lhs) { + if (lhs.expression.kind === 110 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } else if (isModuleExportsAccessExpression(lhs)) { + return 2 /* ModuleExports */; + } else if (isBindableStaticNameExpression( + lhs.expression, + /*excludeThisKeyword*/ + true + )) { + if (isPrototypeAccess(lhs.expression)) { + return 3 /* PrototypeProperty */; + } + let nextToLast = lhs; + while (!isIdentifier(nextToLast.expression)) { + nextToLast = nextToLast.expression; + } + const id = nextToLast.expression; + if ((id.escapedText === "exports" || id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + return 1 /* ExportsProperty */; + } + if (isBindableStaticNameExpression( + lhs, + /*excludeThisKeyword*/ + true + ) || isElementAccessExpression(lhs) && isDynamicName(lhs)) { + return 5 /* Property */; + } + } + return 0 /* None */; +} +function getInitializerOfBinaryExpression(expr) { + while (isBinaryExpression(expr.right)) { + expr = expr.right; + } + return expr.right; +} +function isPrototypePropertyAssignment(node) { + return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; +} +function isSpecialPropertyDeclaration(expr) { + return isInJSFile(expr) && expr.parent && expr.parent.kind === 244 /* ExpressionStatement */ && (!isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!getJSDocTypeTag(expr.parent); +} +function setValueDeclaration(symbol, node) { + const { valueDeclaration } = symbol; + if (!valueDeclaration || !(node.flags & 33554432 /* Ambient */ && !isInJSFile(node) && !(valueDeclaration.flags & 33554432 /* Ambient */)) && (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration)) { + symbol.valueDeclaration = node; + } +} +function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + const decl = symbol.valueDeclaration; + return decl.kind === 262 /* FunctionDeclaration */ || isVariableDeclaration(decl) && decl.initializer && isFunctionLike(decl.initializer); +} +function canHaveModuleSpecifier(node) { + switch (node == null ? void 0 : node.kind) { + case 260 /* VariableDeclaration */: + case 208 /* BindingElement */: + case 272 /* ImportDeclaration */: + case 278 /* ExportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 273 /* ImportClause */: + case 280 /* NamespaceExport */: + case 274 /* NamespaceImport */: + case 281 /* ExportSpecifier */: + case 276 /* ImportSpecifier */: + case 205 /* ImportType */: + return true; + } + return false; +} +function tryGetModuleSpecifierFromDeclaration(node) { + var _a, _b; + switch (node.kind) { + case 260 /* VariableDeclaration */: + case 208 /* BindingElement */: + return (_a = findAncestor(node.initializer, (node2) => isRequireCall( + node2, + /*requireStringLiteralLikeArgument*/ + true + ))) == null ? void 0 : _a.arguments[0]; + case 272 /* ImportDeclaration */: + case 278 /* ExportDeclaration */: + case 351 /* JSDocImportTag */: + return tryCast(node.moduleSpecifier, isStringLiteralLike); + case 271 /* ImportEqualsDeclaration */: + return tryCast((_b = tryCast(node.moduleReference, isExternalModuleReference)) == null ? void 0 : _b.expression, isStringLiteralLike); + case 273 /* ImportClause */: + case 280 /* NamespaceExport */: + return tryCast(node.parent.moduleSpecifier, isStringLiteralLike); + case 274 /* NamespaceImport */: + case 281 /* ExportSpecifier */: + return tryCast(node.parent.parent.moduleSpecifier, isStringLiteralLike); + case 276 /* ImportSpecifier */: + return tryCast(node.parent.parent.parent.moduleSpecifier, isStringLiteralLike); + case 205 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : void 0; + default: + Debug.assertNever(node); + } +} +function shouldRewriteModuleSpecifier(specifier, compilerOptions) { + return !!compilerOptions.rewriteRelativeImportExtensions && pathIsRelative(specifier) && !isDeclarationFileName(specifier) && hasTSFileExtension(specifier); +} +function getExternalModuleName(node) { + switch (node.kind) { + case 272 /* ImportDeclaration */: + case 278 /* ExportDeclaration */: + case 351 /* JSDocImportTag */: + return node.moduleSpecifier; + case 271 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 283 /* ExternalModuleReference */ ? node.moduleReference.expression : void 0; + case 205 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : void 0; + case 213 /* CallExpression */: + return node.arguments[0]; + case 267 /* ModuleDeclaration */: + return node.name.kind === 11 /* StringLiteral */ ? node.name : void 0; + default: + return Debug.assertNever(node); + } +} +function getNamespaceDeclarationNode(node) { + switch (node.kind) { + case 272 /* ImportDeclaration */: + return node.importClause && tryCast(node.importClause.namedBindings, isNamespaceImport); + case 271 /* ImportEqualsDeclaration */: + return node; + case 278 /* ExportDeclaration */: + return node.exportClause && tryCast(node.exportClause, isNamespaceExport); + default: + return Debug.assertNever(node); + } +} +function isDefaultImport(node) { + return (node.kind === 272 /* ImportDeclaration */ || node.kind === 351 /* JSDocImportTag */) && !!node.importClause && !!node.importClause.name; +} +function hasQuestionToken(node) { + switch (node.kind) { + case 169 /* Parameter */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 304 /* ShorthandPropertyAssignment */: + case 303 /* PropertyAssignment */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + return node.questionToken !== void 0; + } + return false; +} +function isJSDocConstructSignature(node) { + const param = isJSDocFunctionType(node) ? firstOrUndefined(node.parameters) : void 0; + const name = tryCast(param && param.name, isIdentifier); + return !!name && name.escapedText === "new"; +} +function isJSDocTypeAlias(node) { + return node.kind === 346 /* JSDocTypedefTag */ || node.kind === 338 /* JSDocCallbackTag */ || node.kind === 340 /* JSDocEnumTag */; +} +function isTypeAlias(node) { + return isJSDocTypeAlias(node) || isTypeAliasDeclaration(node); +} +function getSourceOfAssignment(node) { + return isExpressionStatement(node) && isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 64 /* EqualsToken */ ? getRightMostAssignedExpression(node.expression) : void 0; +} +function getSourceOfDefaultedAssignment(node) { + return isExpressionStatement(node) && isBinaryExpression(node.expression) && getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && isBinaryExpression(node.expression.right) && (node.expression.right.operatorToken.kind === 57 /* BarBarToken */ || node.expression.right.operatorToken.kind === 61 /* QuestionQuestionToken */) ? node.expression.right.right : void 0; +} +function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { + switch (node.kind) { + case 243 /* VariableStatement */: + const v = getSingleVariableOfVariableStatement(node); + return v && v.initializer; + case 172 /* PropertyDeclaration */: + return node.initializer; + case 303 /* PropertyAssignment */: + return node.initializer; + } +} +function getSingleVariableOfVariableStatement(node) { + return isVariableStatement(node) ? firstOrUndefined(node.declarationList.declarations) : void 0; +} +function getNestedModuleDeclaration(node) { + return isModuleDeclaration(node) && node.body && node.body.kind === 267 /* ModuleDeclaration */ ? node.body : void 0; +} +function canHaveFlowNode(node) { + if (node.kind >= 243 /* FirstStatement */ && node.kind <= 259 /* LastStatement */) { + return true; + } + switch (node.kind) { + case 80 /* Identifier */: + case 110 /* ThisKeyword */: + case 108 /* SuperKeyword */: + case 166 /* QualifiedName */: + case 236 /* MetaProperty */: + case 212 /* ElementAccessExpression */: + case 211 /* PropertyAccessExpression */: + case 208 /* BindingElement */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return true; + default: + return false; + } +} +function canHaveJSDoc(node) { + switch (node.kind) { + case 219 /* ArrowFunction */: + case 226 /* BinaryExpression */: + case 241 /* Block */: + case 252 /* BreakStatement */: + case 179 /* CallSignature */: + case 296 /* CaseClause */: + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 175 /* ClassStaticBlockDeclaration */: + case 176 /* Constructor */: + case 185 /* ConstructorType */: + case 180 /* ConstructSignature */: + case 251 /* ContinueStatement */: + case 259 /* DebuggerStatement */: + case 246 /* DoStatement */: + case 212 /* ElementAccessExpression */: + case 242 /* EmptyStatement */: + case 1 /* EndOfFileToken */: + case 266 /* EnumDeclaration */: + case 306 /* EnumMember */: + case 277 /* ExportAssignment */: + case 278 /* ExportDeclaration */: + case 281 /* ExportSpecifier */: + case 244 /* ExpressionStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 248 /* ForStatement */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 184 /* FunctionType */: + case 177 /* GetAccessor */: + case 80 /* Identifier */: + case 245 /* IfStatement */: + case 272 /* ImportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 181 /* IndexSignature */: + case 264 /* InterfaceDeclaration */: + case 317 /* JSDocFunctionType */: + case 323 /* JSDocSignature */: + case 256 /* LabeledStatement */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 267 /* ModuleDeclaration */: + case 202 /* NamedTupleMember */: + case 270 /* NamespaceExportDeclaration */: + case 210 /* ObjectLiteralExpression */: + case 169 /* Parameter */: + case 217 /* ParenthesizedExpression */: + case 211 /* PropertyAccessExpression */: + case 303 /* PropertyAssignment */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 253 /* ReturnStatement */: + case 240 /* SemicolonClassElement */: + case 178 /* SetAccessor */: + case 304 /* ShorthandPropertyAssignment */: + case 305 /* SpreadAssignment */: + case 255 /* SwitchStatement */: + case 257 /* ThrowStatement */: + case 258 /* TryStatement */: + case 265 /* TypeAliasDeclaration */: + case 168 /* TypeParameter */: + case 260 /* VariableDeclaration */: + case 243 /* VariableStatement */: + case 247 /* WhileStatement */: + case 254 /* WithStatement */: + return true; + default: + return false; + } +} +function getJSDocCommentsAndTags(hostNode, noCache) { + let result; + if (isVariableLike(hostNode) && hasInitializer(hostNode) && hasJSDocNodes(hostNode.initializer)) { + result = addRange(result, filterOwnedJSDocTags(hostNode, hostNode.initializer.jsDoc)); + } + let node = hostNode; + while (node && node.parent) { + if (hasJSDocNodes(node)) { + result = addRange(result, filterOwnedJSDocTags(hostNode, node.jsDoc)); + } + if (node.kind === 169 /* Parameter */) { + result = addRange(result, (noCache ? getJSDocParameterTagsNoCache : getJSDocParameterTags)(node)); + break; + } + if (node.kind === 168 /* TypeParameter */) { + result = addRange(result, (noCache ? getJSDocTypeParameterTagsNoCache : getJSDocTypeParameterTags)(node)); + break; + } + node = getNextJSDocCommentLocation(node); + } + return result || emptyArray; +} +function filterOwnedJSDocTags(hostNode, comments) { + const lastJsDoc = last(comments); + return flatMap(comments, (jsDoc) => { + if (jsDoc === lastJsDoc) { + const ownedTags = filter(jsDoc.tags, (tag) => ownsJSDocTag(hostNode, tag)); + return jsDoc.tags === ownedTags ? [jsDoc] : ownedTags; + } else { + return filter(jsDoc.tags, isJSDocOverloadTag); + } + }); +} +function ownsJSDocTag(hostNode, tag) { + return !(isJSDocTypeTag(tag) || isJSDocSatisfiesTag(tag)) || !tag.parent || !isJSDoc(tag.parent) || !isParenthesizedExpression(tag.parent.parent) || tag.parent.parent === hostNode; +} +function getNextJSDocCommentLocation(node) { + const parent = node.parent; + if (parent.kind === 303 /* PropertyAssignment */ || parent.kind === 277 /* ExportAssignment */ || parent.kind === 172 /* PropertyDeclaration */ || parent.kind === 244 /* ExpressionStatement */ && node.kind === 211 /* PropertyAccessExpression */ || parent.kind === 253 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || isAssignmentExpression(node)) { + return parent; + } else if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node || isAssignmentExpression(parent))) { + return parent.parent; + } else if (parent.parent && parent.parent.parent && (getSingleVariableOfVariableStatement(parent.parent.parent) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } +} +function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!isIdentifier(node.name)) { + return void 0; + } + const name = node.name.escapedText; + const decl = getHostSignatureFromJSDoc(node); + if (!decl) { + return void 0; + } + const parameter = find(decl.parameters, (p) => p.name.kind === 80 /* Identifier */ && p.name.escapedText === name); + return parameter && parameter.symbol; +} +function getEffectiveContainerForJSDocTemplateTag(node) { + if (isJSDoc(node.parent) && node.parent.tags) { + const typeAlias = find(node.parent.tags, isJSDocTypeAlias); + if (typeAlias) { + return typeAlias; + } + } + return getHostSignatureFromJSDoc(node); +} +function getJSDocOverloadTags(node) { + return getAllJSDocTags(node, isJSDocOverloadTag); +} +function getHostSignatureFromJSDoc(node) { + const host = getEffectiveJSDocHost(node); + if (host) { + return isPropertySignature(host) && host.type && isFunctionLike(host.type) ? host.type : isFunctionLike(host) ? host : void 0; + } + return void 0; +} +function getEffectiveJSDocHost(node) { + const host = getJSDocHost(node); + if (host) { + return getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || host; + } +} +function getJSDocHost(node) { + const jsDoc = getJSDocRoot(node); + if (!jsDoc) { + return void 0; + } + const host = jsDoc.parent; + if (host && host.jsDoc && jsDoc === lastOrUndefined(host.jsDoc)) { + return host; + } +} +function getJSDocRoot(node) { + return findAncestor(node.parent, isJSDoc); +} +function getTypeParameterFromJsDoc(node) { + const name = node.name.escapedText; + const { typeParameters } = node.parent.parent.parent; + return typeParameters && find(typeParameters, (p) => p.name.escapedText === name); +} +function getAssignmentTarget(node) { + let parent = node.parent; + while (true) { + switch (parent.kind) { + case 226 /* BinaryExpression */: + const binaryExpression = parent; + const binaryOperator = binaryExpression.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && binaryExpression.left === node ? binaryExpression : void 0; + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + const unaryExpression = parent; + const unaryOperator = unaryExpression.operator; + return unaryOperator === 46 /* PlusPlusToken */ || unaryOperator === 47 /* MinusMinusToken */ ? unaryExpression : void 0; + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + const forInOrOfStatement = parent; + return forInOrOfStatement.initializer === node ? forInOrOfStatement : void 0; + case 217 /* ParenthesizedExpression */: + case 209 /* ArrayLiteralExpression */: + case 230 /* SpreadElement */: + case 235 /* NonNullExpression */: + node = parent; + break; + case 305 /* SpreadAssignment */: + node = parent.parent; + break; + case 304 /* ShorthandPropertyAssignment */: + if (parent.name !== node) { + return void 0; + } + node = parent.parent; + break; + case 303 /* PropertyAssignment */: + if (parent.name === node) { + return void 0; + } + node = parent.parent; + break; + default: + return void 0; + } + parent = node.parent; + } +} +function getAssignmentTargetKind(node) { + const target = getAssignmentTarget(node); + if (!target) { + return 0 /* None */; + } + switch (target.kind) { + case 226 /* BinaryExpression */: + const binaryOperator = target.operatorToken.kind; + return binaryOperator === 64 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */; + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + return 2 /* Compound */; + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + return 1 /* Definite */; + } +} +function isAssignmentTarget(node) { + return !!getAssignmentTarget(node); +} +function isCompoundLikeAssignment(assignment) { + const right = skipParentheses(assignment.right); + return right.kind === 226 /* BinaryExpression */ && isShiftOperatorOrHigher(right.operatorToken.kind); +} +function isInCompoundLikeAssignment(node) { + const target = getAssignmentTarget(node); + return !!target && isAssignmentExpression( + target, + /*excludeCompoundAssignment*/ + true + ) && isCompoundLikeAssignment(target); +} +function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 241 /* Block */: + case 243 /* VariableStatement */: + case 254 /* WithStatement */: + case 245 /* IfStatement */: + case 255 /* SwitchStatement */: + case 269 /* CaseBlock */: + case 296 /* CaseClause */: + case 297 /* DefaultClause */: + case 256 /* LabeledStatement */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + case 258 /* TryStatement */: + case 299 /* CatchClause */: + return true; + } + return false; +} +function isValueSignatureDeclaration(node) { + return isFunctionExpression(node) || isArrowFunction(node) || isMethodOrAccessor(node) || isFunctionDeclaration(node) || isConstructorDeclaration(node); +} +function walkUp(node, kind) { + while (node && node.kind === kind) { + node = node.parent; + } + return node; +} +function walkUpParenthesizedTypes(node) { + return walkUp(node, 196 /* ParenthesizedType */); +} +function walkUpParenthesizedExpressions(node) { + return walkUp(node, 217 /* ParenthesizedExpression */); +} +function walkUpParenthesizedTypesAndGetParentAndChild(node) { + let child; + while (node && node.kind === 196 /* ParenthesizedType */) { + child = node; + node = node.parent; + } + return [child, node]; +} +function skipTypeParentheses(node) { + while (isParenthesizedTypeNode(node)) node = node.type; + return node; +} +function skipParentheses(node, excludeJSDocTypeAssertions) { + const flags = excludeJSDocTypeAssertions ? 1 /* Parentheses */ | -2147483648 /* ExcludeJSDocTypeAssertion */ : 1 /* Parentheses */; + return skipOuterExpressions(node, flags); +} +function isDeleteTarget(node) { + if (node.kind !== 211 /* PropertyAccessExpression */ && node.kind !== 212 /* ElementAccessExpression */) { + return false; + } + node = walkUpParenthesizedExpressions(node.parent); + return node && node.kind === 220 /* DeleteExpression */; +} +function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) return true; + node = node.parent; + } + return false; +} +function isDeclarationName(name) { + return !isSourceFile(name) && !isBindingPattern(name) && isDeclaration(name.parent) && name.parent.name === name; +} +function isLiteralComputedPropertyDeclarationName(node) { + return isStringOrNumericLiteralLike(node) && node.parent.kind === 167 /* ComputedPropertyName */ && isDeclaration(node.parent.parent); +} +function isIdentifierName(node) { + const parent = node.parent; + switch (parent.kind) { + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 306 /* EnumMember */: + case 303 /* PropertyAssignment */: + case 211 /* PropertyAccessExpression */: + return parent.name === node; + case 166 /* QualifiedName */: + return parent.right === node; + case 208 /* BindingElement */: + case 276 /* ImportSpecifier */: + return parent.propertyName === node; + case 281 /* ExportSpecifier */: + case 291 /* JsxAttribute */: + case 285 /* JsxSelfClosingElement */: + case 286 /* JsxOpeningElement */: + case 287 /* JsxClosingElement */: + return true; + } + return false; +} +function getAliasDeclarationFromName(node) { + switch (node.parent.kind) { + case 273 /* ImportClause */: + case 276 /* ImportSpecifier */: + case 274 /* NamespaceImport */: + case 281 /* ExportSpecifier */: + case 277 /* ExportAssignment */: + case 271 /* ImportEqualsDeclaration */: + case 280 /* NamespaceExport */: + return node.parent; + case 166 /* QualifiedName */: + do { + node = node.parent; + } while (node.parent.kind === 166 /* QualifiedName */); + return getAliasDeclarationFromName(node); + } +} +function isAliasableExpression(e) { + return isEntityNameExpression(e) || isClassExpression(e); +} +function exportAssignmentIsAlias(node) { + const e = getExportAssignmentExpression(node); + return isAliasableExpression(e); +} +function getExportAssignmentExpression(node) { + return isExportAssignment(node) ? node.expression : node.right; +} +function getPropertyAssignmentAliasLikeExpression(node) { + return node.kind === 304 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 303 /* PropertyAssignment */ ? node.initializer : node.parent.right; +} +function getEffectiveBaseTypeNode(node) { + const baseType = getClassExtendsHeritageElement(node); + if (baseType && isInJSFile(node)) { + const tag = getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return baseType; +} +function getClassExtendsHeritageElement(node) { + const heritageClause = getHeritageClause(node.heritageClauses, 96 /* ExtendsKeyword */); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : void 0; +} +function getEffectiveImplementsTypeNodes(node) { + if (isInJSFile(node)) { + return getJSDocImplementsTags(node).map((n) => n.class); + } else { + const heritageClause = getHeritageClause(node.heritageClauses, 119 /* ImplementsKeyword */); + return heritageClause == null ? void 0 : heritageClause.types; + } +} +function getInterfaceBaseTypeNodes(node) { + const heritageClause = getHeritageClause(node.heritageClauses, 96 /* ExtendsKeyword */); + return heritageClause ? heritageClause.types : void 0; +} +function getHeritageClause(clauses, kind) { + if (clauses) { + for (const clause of clauses) { + if (clause.token === kind) { + return clause; + } + } + } + return void 0; +} +function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return void 0; +} +function isKeyword(token) { + return 83 /* FirstKeyword */ <= token && token <= 165 /* LastKeyword */; +} +function isPunctuation(token) { + return 19 /* FirstPunctuation */ <= token && token <= 79 /* LastPunctuation */; +} +function isKeywordOrPunctuation(token) { + return isKeyword(token) || isPunctuation(token); +} +function isContextualKeyword(token) { + return 128 /* FirstContextualKeyword */ <= token && token <= 165 /* LastContextualKeyword */; +} +function isNonContextualKeyword(token) { + return isKeyword(token) && !isContextualKeyword(token); +} +function isStringANonContextualKeyword(name) { + const token = stringToToken(name); + return token !== void 0 && isNonContextualKeyword(token); +} +function isIdentifierANonContextualKeyword(node) { + const originalKeywordKind = identifierToKeywordKind(node); + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); +} +function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } + let flags = 0 /* Normal */; + switch (node.kind) { + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 174 /* MethodDeclaration */: + if (node.asteriskToken) { + flags |= 1 /* Generator */; + } + // falls through + case 219 /* ArrowFunction */: + if (hasSyntacticModifier(node, 1024 /* Async */)) { + flags |= 2 /* Async */; + } + break; + } + if (!node.body) { + flags |= 4 /* Invalid */; + } + return flags; +} +function isAsyncFunction(node) { + switch (node.kind) { + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 174 /* MethodDeclaration */: + return node.body !== void 0 && node.asteriskToken === void 0 && hasSyntacticModifier(node, 1024 /* Async */); + } + return false; +} +function isStringOrNumericLiteralLike(node) { + return isStringLiteralLike(node) || isNumericLiteral(node); +} +function isSignedNumericLiteral(node) { + return isPrefixUnaryExpression(node) && (node.operator === 40 /* PlusToken */ || node.operator === 41 /* MinusToken */) && isNumericLiteral(node.operand); +} +function hasDynamicName(declaration) { + const name = getNameOfDeclaration(declaration); + return !!name && isDynamicName(name); +} +function isDynamicName(name) { + if (!(name.kind === 167 /* ComputedPropertyName */ || name.kind === 212 /* ElementAccessExpression */)) { + return false; + } + const expr = isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; + return !isStringOrNumericLiteralLike(expr) && !isSignedNumericLiteral(expr); +} +function getPropertyNameForPropertyNameNode(name) { + switch (name.kind) { + case 80 /* Identifier */: + case 81 /* PrivateIdentifier */: + return name.escapedText; + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + return escapeLeadingUnderscores(name.text); + case 167 /* ComputedPropertyName */: + const nameExpression = name.expression; + if (isStringOrNumericLiteralLike(nameExpression)) { + return escapeLeadingUnderscores(nameExpression.text); + } else if (isSignedNumericLiteral(nameExpression)) { + if (nameExpression.operator === 41 /* MinusToken */) { + return tokenToString(nameExpression.operator) + nameExpression.operand.text; + } + return nameExpression.operand.text; + } + return void 0; + case 295 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); + default: + return Debug.assertNever(name); + } +} +function isPropertyNameLiteral(node) { + switch (node.kind) { + case 80 /* Identifier */: + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 9 /* NumericLiteral */: + return true; + default: + return false; + } +} +function getTextOfIdentifierOrLiteral(node) { + return isMemberName(node) ? idText(node) : isJsxNamespacedName(node) ? getTextOfJsxNamespacedName(node) : node.text; +} +function getEscapedTextOfIdentifierOrLiteral(node) { + return isMemberName(node) ? node.escapedText : isJsxNamespacedName(node) ? getEscapedTextOfJsxNamespacedName(node) : escapeLeadingUnderscores(node.text); +} +function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) { + return `__#${getSymbolId(containingClassSymbol)}@${description}`; +} +function isKnownSymbol(symbol) { + return startsWith(symbol.escapedName, "__@"); +} +function isProtoSetter(node) { + return isIdentifier(node) ? idText(node) === "__proto__" : isStringLiteral(node) && node.text === "__proto__"; +} +function isAnonymousFunctionDefinition(node, cb) { + node = skipOuterExpressions(node); + switch (node.kind) { + case 231 /* ClassExpression */: + if (classHasDeclaredOrExplicitlyAssignedName(node)) { + return false; + } + break; + case 218 /* FunctionExpression */: + if (node.name) { + return false; + } + break; + case 219 /* ArrowFunction */: + break; + default: + return false; + } + return typeof cb === "function" ? cb(node) : true; +} +function isNamedEvaluationSource(node) { + switch (node.kind) { + case 303 /* PropertyAssignment */: + return !isProtoSetter(node.name); + case 304 /* ShorthandPropertyAssignment */: + return !!node.objectAssignmentInitializer; + case 260 /* VariableDeclaration */: + return isIdentifier(node.name) && !!node.initializer; + case 169 /* Parameter */: + return isIdentifier(node.name) && !!node.initializer && !node.dotDotDotToken; + case 208 /* BindingElement */: + return isIdentifier(node.name) && !!node.initializer && !node.dotDotDotToken; + case 172 /* PropertyDeclaration */: + return !!node.initializer; + case 226 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 64 /* EqualsToken */: + case 77 /* AmpersandAmpersandEqualsToken */: + case 76 /* BarBarEqualsToken */: + case 78 /* QuestionQuestionEqualsToken */: + return isIdentifier(node.left); + } + break; + case 277 /* ExportAssignment */: + return true; + } + return false; +} +function isNamedEvaluation(node, cb) { + if (!isNamedEvaluationSource(node)) return false; + switch (node.kind) { + case 303 /* PropertyAssignment */: + return isAnonymousFunctionDefinition(node.initializer, cb); + case 304 /* ShorthandPropertyAssignment */: + return isAnonymousFunctionDefinition(node.objectAssignmentInitializer, cb); + case 260 /* VariableDeclaration */: + case 169 /* Parameter */: + case 208 /* BindingElement */: + case 172 /* PropertyDeclaration */: + return isAnonymousFunctionDefinition(node.initializer, cb); + case 226 /* BinaryExpression */: + return isAnonymousFunctionDefinition(node.right, cb); + case 277 /* ExportAssignment */: + return isAnonymousFunctionDefinition(node.expression, cb); + } +} +function isPushOrUnshiftIdentifier(node) { + return node.escapedText === "push" || node.escapedText === "unshift"; +} +function isPartOfParameterDeclaration(node) { + const root = getRootDeclaration(node); + return root.kind === 169 /* Parameter */; +} +function getRootDeclaration(node) { + while (node.kind === 208 /* BindingElement */) { + node = node.parent.parent; + } + return node; +} +function nodeStartsNewLexicalEnvironment(node) { + const kind = node.kind; + return kind === 176 /* Constructor */ || kind === 218 /* FunctionExpression */ || kind === 262 /* FunctionDeclaration */ || kind === 219 /* ArrowFunction */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 267 /* ModuleDeclaration */ || kind === 307 /* SourceFile */; +} +function nodeIsSynthesized(range) { + return positionIsSynthesized(range.pos) || positionIsSynthesized(range.end); +} +function getExpressionAssociativity(expression) { + const operator = getOperator(expression); + const hasArguments = expression.kind === 214 /* NewExpression */ && expression.arguments !== void 0; + return getOperatorAssociativity(expression.kind, operator, hasArguments); +} +function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 214 /* NewExpression */: + return hasArguments ? 0 /* Left */ : 1 /* Right */; + case 224 /* PrefixUnaryExpression */: + case 221 /* TypeOfExpression */: + case 222 /* VoidExpression */: + case 220 /* DeleteExpression */: + case 223 /* AwaitExpression */: + case 227 /* ConditionalExpression */: + case 229 /* YieldExpression */: + return 1 /* Right */; + case 226 /* BinaryExpression */: + switch (operator) { + case 43 /* AsteriskAsteriskToken */: + case 64 /* EqualsToken */: + case 65 /* PlusEqualsToken */: + case 66 /* MinusEqualsToken */: + case 68 /* AsteriskAsteriskEqualsToken */: + case 67 /* AsteriskEqualsToken */: + case 69 /* SlashEqualsToken */: + case 70 /* PercentEqualsToken */: + case 71 /* LessThanLessThanEqualsToken */: + case 72 /* GreaterThanGreaterThanEqualsToken */: + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 74 /* AmpersandEqualsToken */: + case 79 /* CaretEqualsToken */: + case 75 /* BarEqualsToken */: + case 76 /* BarBarEqualsToken */: + case 77 /* AmpersandAmpersandEqualsToken */: + case 78 /* QuestionQuestionEqualsToken */: + return 1 /* Right */; + } + } + return 0 /* Left */; +} +function getExpressionPrecedence(expression) { + const operator = getOperator(expression); + const hasArguments = expression.kind === 214 /* NewExpression */ && expression.arguments !== void 0; + return getOperatorPrecedence(expression.kind, operator, hasArguments); +} +function getOperator(expression) { + if (expression.kind === 226 /* BinaryExpression */) { + return expression.operatorToken.kind; + } else if (expression.kind === 224 /* PrefixUnaryExpression */ || expression.kind === 225 /* PostfixUnaryExpression */) { + return expression.operator; + } else { + return expression.kind; + } +} +function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 356 /* CommaListExpression */: + return 0 /* Comma */; + case 230 /* SpreadElement */: + return 1 /* Spread */; + case 229 /* YieldExpression */: + return 2 /* Yield */; + case 227 /* ConditionalExpression */: + return 4 /* Conditional */; + case 226 /* BinaryExpression */: + switch (operatorKind) { + case 28 /* CommaToken */: + return 0 /* Comma */; + case 64 /* EqualsToken */: + case 65 /* PlusEqualsToken */: + case 66 /* MinusEqualsToken */: + case 68 /* AsteriskAsteriskEqualsToken */: + case 67 /* AsteriskEqualsToken */: + case 69 /* SlashEqualsToken */: + case 70 /* PercentEqualsToken */: + case 71 /* LessThanLessThanEqualsToken */: + case 72 /* GreaterThanGreaterThanEqualsToken */: + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 74 /* AmpersandEqualsToken */: + case 79 /* CaretEqualsToken */: + case 75 /* BarEqualsToken */: + case 76 /* BarBarEqualsToken */: + case 77 /* AmpersandAmpersandEqualsToken */: + case 78 /* QuestionQuestionEqualsToken */: + return 3 /* Assignment */; + default: + return getBinaryOperatorPrecedence(operatorKind); + } + // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? + case 216 /* TypeAssertionExpression */: + case 235 /* NonNullExpression */: + case 224 /* PrefixUnaryExpression */: + case 221 /* TypeOfExpression */: + case 222 /* VoidExpression */: + case 220 /* DeleteExpression */: + case 223 /* AwaitExpression */: + return 16 /* Unary */; + case 225 /* PostfixUnaryExpression */: + return 17 /* Update */; + case 213 /* CallExpression */: + return 18 /* LeftHandSide */; + case 214 /* NewExpression */: + return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */; + case 215 /* TaggedTemplateExpression */: + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + case 236 /* MetaProperty */: + return 19 /* Member */; + case 234 /* AsExpression */: + case 238 /* SatisfiesExpression */: + return 11 /* Relational */; + case 110 /* ThisKeyword */: + case 108 /* SuperKeyword */: + case 80 /* Identifier */: + case 81 /* PrivateIdentifier */: + case 106 /* NullKeyword */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 11 /* StringLiteral */: + case 209 /* ArrayLiteralExpression */: + case 210 /* ObjectLiteralExpression */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 231 /* ClassExpression */: + case 14 /* RegularExpressionLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 228 /* TemplateExpression */: + case 217 /* ParenthesizedExpression */: + case 232 /* OmittedExpression */: + case 284 /* JsxElement */: + case 285 /* JsxSelfClosingElement */: + case 288 /* JsxFragment */: + return 20 /* Primary */; + default: + return -1 /* Invalid */; + } +} +function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case 61 /* QuestionQuestionToken */: + return 4 /* Coalesce */; + case 57 /* BarBarToken */: + return 5 /* LogicalOR */; + case 56 /* AmpersandAmpersandToken */: + return 6 /* LogicalAND */; + case 52 /* BarToken */: + return 7 /* BitwiseOR */; + case 53 /* CaretToken */: + return 8 /* BitwiseXOR */; + case 51 /* AmpersandToken */: + return 9 /* BitwiseAND */; + case 35 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsToken */: + case 37 /* EqualsEqualsEqualsToken */: + case 38 /* ExclamationEqualsEqualsToken */: + return 10 /* Equality */; + case 30 /* LessThanToken */: + case 32 /* GreaterThanToken */: + case 33 /* LessThanEqualsToken */: + case 34 /* GreaterThanEqualsToken */: + case 104 /* InstanceOfKeyword */: + case 103 /* InKeyword */: + case 130 /* AsKeyword */: + case 152 /* SatisfiesKeyword */: + return 11 /* Relational */; + case 48 /* LessThanLessThanToken */: + case 49 /* GreaterThanGreaterThanToken */: + case 50 /* GreaterThanGreaterThanGreaterThanToken */: + return 12 /* Shift */; + case 40 /* PlusToken */: + case 41 /* MinusToken */: + return 13 /* Additive */; + case 42 /* AsteriskToken */: + case 44 /* SlashToken */: + case 45 /* PercentToken */: + return 14 /* Multiplicative */; + case 43 /* AsteriskAsteriskToken */: + return 15 /* Exponentiation */; + } + return -1; +} +function getSemanticJsxChildren(children) { + return filter(children, (i) => { + switch (i.kind) { + case 294 /* JsxExpression */: + return !!i.expression; + case 12 /* JsxText */: + return !i.containsOnlyTriviaWhiteSpaces; + default: + return true; + } + }); +} +function createDiagnosticCollection() { + let nonFileDiagnostics = []; + const filesWithDiagnostics = []; + const fileDiagnostics = /* @__PURE__ */ new Map(); + let hasReadNonFileDiagnostics = false; + return { + add, + lookup, + getGlobalDiagnostics, + getDiagnostics + }; + function lookup(diagnostic) { + let diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return void 0; + } + const result = binarySearch(diagnostics, diagnostic, identity, compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + if (~result > 0 && diagnosticsEqualityComparer(diagnostic, diagnostics[~result - 1])) { + return diagnostics[~result - 1]; + } + return void 0; + } + function add(diagnostic) { + let diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + if (!diagnostics) { + diagnostics = []; + fileDiagnostics.set(diagnostic.file.fileName, diagnostics); + insertSorted(filesWithDiagnostics, diagnostic.file.fileName, compareStringsCaseSensitive); + } + } else { + if (hasReadNonFileDiagnostics) { + hasReadNonFileDiagnostics = false; + nonFileDiagnostics = nonFileDiagnostics.slice(); + } + diagnostics = nonFileDiagnostics; + } + insertSorted(diagnostics, diagnostic, compareDiagnosticsSkipRelatedInformation, diagnosticsEqualityComparer); + } + function getGlobalDiagnostics() { + hasReadNonFileDiagnostics = true; + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + if (fileName) { + return fileDiagnostics.get(fileName) || []; + } + const fileDiags = flatMapToMutable(filesWithDiagnostics, (f) => fileDiagnostics.get(f)); + if (!nonFileDiagnostics.length) { + return fileDiags; + } + fileDiags.unshift(...nonFileDiagnostics); + return fileDiags; + } +} +var templateSubstitutionRegExp = /\$\{/g; +function escapeTemplateSubstitution(str) { + return str.replace(templateSubstitutionRegExp, "\\${"); +} +function containsInvalidEscapeFlag(node) { + return !!((node.templateFlags || 0) & 2048 /* ContainsInvalidEscape */); +} +function hasInvalidEscape(template) { + return template && !!(isNoSubstitutionTemplateLiteral(template) ? containsInvalidEscapeFlag(template) : containsInvalidEscapeFlag(template.head) || some(template.templateSpans, (span) => containsInvalidEscapeFlag(span.literal))); +} +var doubleQuoteEscapedCharsRegExp = /[\\"\u0000-\u001f\u2028\u2029\u0085]/g; +var singleQuoteEscapedCharsRegExp = /[\\'\u0000-\u001f\u2028\u2029\u0085]/g; +var backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u0009\u000b-\u001f\u2028\u2029\u0085]/g; +var escapedCharsMap = new Map(Object.entries({ + " ": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + '"': '\\"', + "'": "\\'", + "`": "\\`", + "\u2028": "\\u2028", + // lineSeparator + "\u2029": "\\u2029", + // paragraphSeparator + "\x85": "\\u0085", + // nextLine + "\r\n": "\\r\\n" + // special case for CRLFs in backticks +})); +function encodeUtf16EscapeSequence(charCode) { + const hexCharCode = charCode.toString(16).toUpperCase(); + const paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; +} +function getReplacement(c, offset, input) { + if (c.charCodeAt(0) === 0 /* nullCharacter */) { + const lookAhead = input.charCodeAt(offset + c.length); + if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + return "\\x00"; + } + return "\\0"; + } + return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0)); +} +function escapeString(s, quoteChar) { + const escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getReplacement); +} +var nonAsciiCharacters = /[^\u0000-\u007F]/g; +function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); + return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, (c) => encodeUtf16EscapeSequence(c.charCodeAt(0))) : s; +} +var jsxDoubleQuoteEscapedCharsRegExp = /["\u0000-\u001f\u2028\u2029\u0085]/g; +var jsxSingleQuoteEscapedCharsRegExp = /['\u0000-\u001f\u2028\u2029\u0085]/g; +var jsxEscapedCharsMap = new Map(Object.entries({ + '"': """, + "'": "'" +})); +function encodeJsxCharacterEntity(charCode) { + const hexCharCode = charCode.toString(16).toUpperCase(); + return "&#x" + hexCharCode + ";"; +} +function getJsxAttributeStringReplacement(c) { + if (c.charCodeAt(0) === 0 /* nullCharacter */) { + return "�"; + } + return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0)); +} +function escapeJsxAttributeString(s, quoteChar) { + const escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp : jsxDoubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement); +} +function stripQuotes(name) { + const length2 = name.length; + if (length2 >= 2 && name.charCodeAt(0) === name.charCodeAt(length2 - 1) && isQuoteOrBacktick(name.charCodeAt(0))) { + return name.substring(1, length2 - 1); + } + return name; +} +function isQuoteOrBacktick(charCode) { + return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */ || charCode === 96 /* backtick */; +} +function isIntrinsicJsxName(name) { + const ch = name.charCodeAt(0); + return ch >= 97 /* a */ && ch <= 122 /* z */ || name.includes("-"); +} +var indentStrings = ["", " "]; +function getIndentString(level) { + const singleLevel = indentStrings[1]; + for (let current = indentStrings.length; current <= level; current++) { + indentStrings.push(indentStrings[current - 1] + singleLevel); + } + return indentStrings[level]; +} +function getIndentSize() { + return indentStrings[1].length; +} +function createTextWriter(newLine) { + var output; + var indent2; + var lineStart; + var lineCount; + var linePos; + var hasTrailingComment = false; + function updateLineCountAndPosFor(s) { + const lineStartsOfS = computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + last(lineStartsOfS); + lineStart = linePos - output.length === 0; + } else { + lineStart = false; + } + } + function writeText(s) { + if (s && s.length) { + if (lineStart) { + s = getIndentString(indent2) + s; + lineStart = false; + } + output += s; + updateLineCountAndPosFor(s); + } + } + function write(s) { + if (s) hasTrailingComment = false; + writeText(s); + } + function writeComment(s) { + if (s) hasTrailingComment = true; + writeText(s); + } + function reset() { + output = ""; + indent2 = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + hasTrailingComment = false; + } + function rawWrite(s) { + if (s !== void 0) { + output += s; + updateLineCountAndPosFor(s); + hasTrailingComment = false; + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + } + } + function writeLine(force) { + if (!lineStart || force) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + hasTrailingComment = false; + } + } + reset(); + return { + write, + rawWrite, + writeLiteral, + writeLine, + increaseIndent: () => { + indent2++; + }, + decreaseIndent: () => { + indent2--; + }, + getIndent: () => indent2, + getTextPos: () => output.length, + getLine: () => lineCount, + getColumn: () => lineStart ? indent2 * getIndentSize() : output.length - linePos, + getText: () => output, + isAtStartOfLine: () => lineStart, + hasTrailingComment: () => hasTrailingComment, + hasTrailingWhitespace: () => !!output.length && isWhiteSpaceLike(output.charCodeAt(output.length - 1)), + clear: reset, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: (s, _) => write(s), + writeTrailingSemicolon: write, + writeComment + }; +} +function getTrailingSemicolonDeferringWriter(writer) { + let pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return { + ...writer, + writeTrailingSemicolon() { + pendingTrailingSemicolon = true; + }, + writeLiteral(s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral(s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol(s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation(s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword(s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator(s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter(s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace(s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty(s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment(s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine() { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent() { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent() { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } + }; +} +function hostUsesCaseSensitiveFileNames(host) { + return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; +} +function hostGetCanonicalFileName(host) { + return createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); +} +function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); +} +function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(getNormalizedAbsolutePath(path, host.getCurrentDirectory())); +} +function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + const file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || file.isDeclarationFile) { + return void 0; + } + const specifier = getExternalModuleName(declaration); + if (specifier && isStringLiteralLike(specifier) && !pathIsRelative(specifier.text) && !getCanonicalAbsolutePath(host, file.path).includes(getCanonicalAbsolutePath(host, ensureTrailingDirectorySeparator(host.getCommonSourceDirectory())))) { + return void 0; + } + return getResolvedExternalModuleName(host, file); +} +function getExternalModuleNameFromPath(host, fileName, referencePath) { + const getCanonicalFileName = (f) => host.getCanonicalFileName(f); + const dir = toPath(referencePath ? getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + const filePath = getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + const relativePath = getRelativePathToDirectoryOrUrl( + dir, + filePath, + dir, + getCanonicalFileName, + /*isAbsolutePathAnUrl*/ + false + ); + const extensionless = removeFileExtension(relativePath); + return referencePath ? ensurePathIsNonModuleName(extensionless) : extensionless; +} +function getOwnEmitOutputFilePath(fileName, host, extension) { + const compilerOptions = host.getCompilerOptions(); + let emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); + } else { + emitOutputFilePathWithoutExtension = removeFileExtension(fileName); + } + return emitOutputFilePathWithoutExtension + extension; +} +function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host); +} +function getDeclarationEmitOutputFilePathWorker(fileName, options, host) { + const outputDir = options.declarationDir || options.outDir; + const path = outputDir ? getSourceFilePathInNewDirWorker(fileName, outputDir, host.getCurrentDirectory(), host.getCommonSourceDirectory(), (f) => host.getCanonicalFileName(f)) : fileName; + const declarationExtension = getDeclarationEmitExtensionForPath(path); + return removeFileExtension(path) + declarationExtension; +} +function getDeclarationEmitExtensionForPath(path) { + return fileExtensionIsOneOf(path, [".mjs" /* Mjs */, ".mts" /* Mts */]) ? ".d.mts" /* Dmts */ : fileExtensionIsOneOf(path, [".cjs" /* Cjs */, ".cts" /* Cts */]) ? ".d.cts" /* Dcts */ : fileExtensionIsOneOf(path, [".json" /* Json */]) ? `.d.json.ts` : ( + // Drive-by redefinition of json declaration file output name so if it's ever enabled, it behaves well + ".d.ts" /* Dts */ + ); +} +function getPossibleOriginalInputExtensionForExtension(path) { + return fileExtensionIsOneOf(path, [".d.mts" /* Dmts */, ".mjs" /* Mjs */, ".mts" /* Mts */]) ? [".mts" /* Mts */, ".mjs" /* Mjs */] : fileExtensionIsOneOf(path, [".d.cts" /* Dcts */, ".cjs" /* Cjs */, ".cts" /* Cts */]) ? [".cts" /* Cts */, ".cjs" /* Cjs */] : fileExtensionIsOneOf(path, [`.d.json.ts`]) ? [".json" /* Json */] : [".tsx" /* Tsx */, ".ts" /* Ts */, ".jsx" /* Jsx */, ".js" /* Js */]; +} +function getPathsBasePath(options, host) { + var _a; + if (!options.paths) return void 0; + return options.baseUrl ?? Debug.checkDefined(options.pathsBasePath || ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'."); +} +function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) { + const options = host.getCompilerOptions(); + if (options.outFile) { + const moduleKind = getEmitModuleKind(options); + const moduleEmitEnabled = options.emitDeclarationOnly || moduleKind === 2 /* AMD */ || moduleKind === 4 /* System */; + return filter( + host.getSourceFiles(), + (sourceFile) => (moduleEmitEnabled || !isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) + ); + } else { + const sourceFiles = targetSourceFile === void 0 ? host.getSourceFiles() : [targetSourceFile]; + return filter( + sourceFiles, + (sourceFile) => sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) + ); + } +} +function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) { + const options = host.getCompilerOptions(); + if (options.noEmitForJsFiles && isSourceFileJS(sourceFile)) return false; + if (sourceFile.isDeclarationFile) return false; + if (host.isSourceFileFromExternalLibrary(sourceFile)) return false; + if (forceDtsEmit) return true; + if (host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) return false; + if (!isJsonSourceFile(sourceFile)) return true; + if (host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) return false; + if (options.outFile) return true; + if (!options.outDir) return false; + if (options.rootDir || options.composite && options.configFilePath) { + const commonDir = getNormalizedAbsolutePath(getCommonSourceDirectory(options, () => [], host.getCurrentDirectory(), host.getCanonicalFileName), host.getCurrentDirectory()); + const outputPath = getSourceFilePathInNewDirWorker(sourceFile.fileName, options.outDir, host.getCurrentDirectory(), commonDir, host.getCanonicalFileName); + if (comparePaths(sourceFile.fileName, outputPath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */) return false; + } + return true; +} +function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), (f) => host.getCanonicalFileName(f)); +} +function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + let sourceFilePath = getNormalizedAbsolutePath(fileName, currentDirectory); + const isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; + return combinePaths(newDirPath, sourceFilePath); +} +function writeFile(host, diagnostics, fileName, text, writeByteOrderMark, sourceFiles, data) { + host.writeFile( + fileName, + text, + writeByteOrderMark, + (hostErrorMessage) => { + diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, + sourceFiles, + data + ); +} +function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) { + if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { + const parentDirectory = getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists); + createDirectory(directoryPath); + } +} +function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile2, createDirectory, directoryExists) { + try { + writeFile2(path, data, writeByteOrderMark); + } catch { + ensureDirectoriesExist(getDirectoryPath(normalizePath(path)), createDirectory, directoryExists); + writeFile2(path, data, writeByteOrderMark); + } +} +function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return computeLineOfPosition(lineMap, pos); +} +function getFirstConstructorWithBody(node) { + return find(node.members, (member) => isConstructorDeclaration(member) && nodeIsPresent(member.body)); +} +function getSetAccessorValueParameter(accessor) { + if (accessor && accessor.parameters.length > 0) { + const hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); + return accessor.parameters[hasThis ? 1 : 0]; + } +} +function getSetAccessorTypeAnnotationNode(accessor) { + const parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; +} +function getThisParameter(signature) { + if (signature.parameters.length && !isJSDocSignature(signature)) { + const thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } +} +function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); +} +function isThisIdentifier(node) { + return !!node && node.kind === 80 /* Identifier */ && identifierIsThisKeyword(node); +} +function isInTypeQuery(node) { + return !!findAncestor( + node, + (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" + ); +} +function isThisInTypeQuery(node) { + if (!isThisIdentifier(node)) { + return false; + } + while (isQualifiedName(node.parent) && node.parent.left === node) { + node = node.parent; + } + return node.parent.kind === 186 /* TypeQuery */; +} +function identifierIsThisKeyword(id) { + return id.escapedText === "this"; +} +function getAllAccessorDeclarations(declarations, accessor) { + let firstAccessor; + let secondAccessor; + let getAccessor; + let setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 177 /* GetAccessor */) { + getAccessor = accessor; + } else if (accessor.kind === 178 /* SetAccessor */) { + setAccessor = accessor; + } else { + Debug.fail("Accessor has wrong kind"); + } + } else { + forEach(declarations, (member) => { + if (isAccessor(member) && isStatic(member) === isStatic(accessor)) { + const memberName = getPropertyNameForPropertyNameNode(member.name); + const accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 177 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 178 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor, + secondAccessor, + getAccessor, + setAccessor + }; +} +function getEffectiveTypeAnnotationNode(node) { + if (!isInJSFile(node) && isFunctionDeclaration(node)) return void 0; + if (isTypeAliasDeclaration(node)) return void 0; + const type = node.type; + if (type || !isInJSFile(node)) return type; + return isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : getJSDocType(node); +} +function getEffectiveReturnTypeNode(node) { + return isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : node.type || (isInJSFile(node) ? getJSDocReturnType(node) : void 0); +} +function getJSDocTypeParameterDeclarations(node) { + return flatMap(getJSDocTags(node), (tag) => isNonTypeAliasTemplate(tag) ? tag.typeParameters : void 0); +} +function isNonTypeAliasTemplate(tag) { + return isJSDocTemplateTag(tag) && !(tag.parent.kind === 320 /* JSDoc */ && (tag.parent.tags.some(isJSDocTypeAlias) || tag.parent.tags.some(isJSDocOverloadTag))); +} +function getEffectiveSetAccessorTypeAnnotationNode(node) { + const parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); +} +function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); +} +function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } +} +function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + if (pos !== commentPos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } +} +function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.writeSpace(" "); + } + let emitInterveningSeparator = false; + for (const comment of comments) { + if (emitInterveningSeparator) { + writer.writeSpace(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.writeSpace(" "); + } + } +} +function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + let leadingComments; + let currentDetachedCommentInfo; + if (removeComments) { + if (node.pos === 0) { + leadingComments = filter(getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); + } + } else { + leadingComments = getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + const detachedComments = []; + let lastComment; + for (const comment of leadingComments) { + if (lastComment) { + const lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + const commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + const lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, last(detachedComments).end); + const nodeLine = getLineOfLocalPositionFromLineMap(lineMap, skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments( + text, + lineMap, + writer, + detachedComments, + /*leadingSeparator*/ + false, + /*trailingSeparator*/ + true, + newLine, + writeComment + ); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: last(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment.pos); + } +} +function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { + const firstCommentLineAndCharacter = computeLineAndCharacterOfPosition(lineMap, commentPos); + const lineCount = lineMap.length; + let firstCommentLineIndent; + for (let pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + const nextLineStart = currentLine + 1 === lineCount ? text.length + 1 : lineMap[currentLine + 1]; + if (pos !== commentPos) { + if (firstCommentLineIndent === void 0) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + const currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + const spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + let numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + const indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + writer.rawWrite(indentSizeSpaceString); + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } else { + writer.rawWrite(""); + } + } + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } else { + writer.writeComment(text.substring(commentPos, commentEnd)); + } +} +function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + const end = Math.min(commentEnd, nextLineStart - 1); + const currentLineText = text.substring(pos, end).trim(); + if (currentLineText) { + writer.writeComment(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } else { + writer.rawWrite(newLine); + } +} +function calculateIndent(text, pos, end) { + let currentLineIndent = 0; + for (; pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9 /* tab */) { + currentLineIndent += getIndentSize() - currentLineIndent % getIndentSize(); + } else { + currentLineIndent++; + } + } + return currentLineIndent; +} +function hasEffectiveModifiers(node) { + return getEffectiveModifierFlags(node) !== 0 /* None */; +} +function hasSyntacticModifiers(node) { + return getSyntacticModifierFlags(node) !== 0 /* None */; +} +function hasEffectiveModifier(node, flags) { + return !!getSelectedEffectiveModifierFlags(node, flags); +} +function hasSyntacticModifier(node, flags) { + return !!getSelectedSyntacticModifierFlags(node, flags); +} +function isStatic(node) { + return isClassElement(node) && hasStaticModifier(node) || isClassStaticBlockDeclaration(node); +} +function hasStaticModifier(node) { + return hasSyntacticModifier(node, 256 /* Static */); +} +function hasOverrideModifier(node) { + return hasEffectiveModifier(node, 16 /* Override */); +} +function hasAbstractModifier(node) { + return hasSyntacticModifier(node, 64 /* Abstract */); +} +function hasAmbientModifier(node) { + return hasSyntacticModifier(node, 128 /* Ambient */); +} +function hasAccessorModifier(node) { + return hasSyntacticModifier(node, 512 /* Accessor */); +} +function hasEffectiveReadonlyModifier(node) { + return hasEffectiveModifier(node, 8 /* Readonly */); +} +function hasDecorators(node) { + return hasSyntacticModifier(node, 32768 /* Decorator */); +} +function getSelectedEffectiveModifierFlags(node, flags) { + return getEffectiveModifierFlags(node) & flags; +} +function getSelectedSyntacticModifierFlags(node, flags) { + return getSyntacticModifierFlags(node) & flags; +} +function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) { + if (node.kind >= 0 /* FirstToken */ && node.kind <= 165 /* LastToken */) { + return 0 /* None */; + } + if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) { + node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */; + } + if (alwaysIncludeJSDoc || includeJSDoc && isInJSFile(node)) { + if (!(node.modifierFlagsCache & 268435456 /* HasComputedJSDocModifiers */) && node.parent) { + node.modifierFlagsCache |= getRawJSDocModifierFlagsNoCache(node) | 268435456 /* HasComputedJSDocModifiers */; + } + return selectEffectiveModifierFlags(node.modifierFlagsCache); + } + return selectSyntacticModifierFlags(node.modifierFlagsCache); +} +function getEffectiveModifierFlags(node) { + return getModifierFlagsWorker( + node, + /*includeJSDoc*/ + true + ); +} +function getSyntacticModifierFlags(node) { + return getModifierFlagsWorker( + node, + /*includeJSDoc*/ + false + ); +} +function getRawJSDocModifierFlagsNoCache(node) { + let flags = 0 /* None */; + if (!!node.parent && !isParameter(node)) { + if (isInJSFile(node)) { + if (getJSDocPublicTagNoCache(node)) flags |= 8388608 /* JSDocPublic */; + if (getJSDocPrivateTagNoCache(node)) flags |= 16777216 /* JSDocPrivate */; + if (getJSDocProtectedTagNoCache(node)) flags |= 33554432 /* JSDocProtected */; + if (getJSDocReadonlyTagNoCache(node)) flags |= 67108864 /* JSDocReadonly */; + if (getJSDocOverrideTagNoCache(node)) flags |= 134217728 /* JSDocOverride */; + } + if (getJSDocDeprecatedTagNoCache(node)) flags |= 65536 /* Deprecated */; + } + return flags; +} +function selectSyntacticModifierFlags(flags) { + return flags & 65535 /* SyntacticModifiers */; +} +function selectEffectiveModifierFlags(flags) { + return flags & 131071 /* NonCacheOnlyModifiers */ | (flags & 260046848 /* JSDocCacheOnlyModifiers */) >>> 23; +} +function getJSDocModifierFlagsNoCache(node) { + return selectEffectiveModifierFlags(getRawJSDocModifierFlagsNoCache(node)); +} +function getEffectiveModifierFlagsNoCache(node) { + return getSyntacticModifierFlagsNoCache(node) | getJSDocModifierFlagsNoCache(node); +} +function getSyntacticModifierFlagsNoCache(node) { + let flags = canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0 /* None */; + if (node.flags & 8 /* NestedNamespace */ || node.kind === 80 /* Identifier */ && node.flags & 4096 /* IdentifierIsInJSDocNamespace */) { + flags |= 32 /* Export */; + } + return flags; +} +function modifiersToFlags(modifiers) { + let flags = 0 /* None */; + if (modifiers) { + for (const modifier of modifiers) { + flags |= modifierToFlag(modifier.kind); + } + } + return flags; +} +function modifierToFlag(token) { + switch (token) { + case 126 /* StaticKeyword */: + return 256 /* Static */; + case 125 /* PublicKeyword */: + return 1 /* Public */; + case 124 /* ProtectedKeyword */: + return 4 /* Protected */; + case 123 /* PrivateKeyword */: + return 2 /* Private */; + case 128 /* AbstractKeyword */: + return 64 /* Abstract */; + case 129 /* AccessorKeyword */: + return 512 /* Accessor */; + case 95 /* ExportKeyword */: + return 32 /* Export */; + case 138 /* DeclareKeyword */: + return 128 /* Ambient */; + case 87 /* ConstKeyword */: + return 4096 /* Const */; + case 90 /* DefaultKeyword */: + return 2048 /* Default */; + case 134 /* AsyncKeyword */: + return 1024 /* Async */; + case 148 /* ReadonlyKeyword */: + return 8 /* Readonly */; + case 164 /* OverrideKeyword */: + return 16 /* Override */; + case 103 /* InKeyword */: + return 8192 /* In */; + case 147 /* OutKeyword */: + return 16384 /* Out */; + case 170 /* Decorator */: + return 32768 /* Decorator */; + } + return 0 /* None */; +} +function isBinaryLogicalOperator(token) { + return token === 57 /* BarBarToken */ || token === 56 /* AmpersandAmpersandToken */; +} +function isLogicalOperator(token) { + return isBinaryLogicalOperator(token) || token === 54 /* ExclamationToken */; +} +function isLogicalOrCoalescingAssignmentOperator(token) { + return token === 76 /* BarBarEqualsToken */ || token === 77 /* AmpersandAmpersandEqualsToken */ || token === 78 /* QuestionQuestionEqualsToken */; +} +function isLogicalOrCoalescingAssignmentExpression(expr) { + return isBinaryExpression(expr) && isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind); +} +function isLogicalOrCoalescingBinaryOperator(token) { + return isBinaryLogicalOperator(token) || token === 61 /* QuestionQuestionToken */; +} +function isLogicalOrCoalescingBinaryExpression(expr) { + return isBinaryExpression(expr) && isLogicalOrCoalescingBinaryOperator(expr.operatorToken.kind); +} +function isAssignmentOperator(token) { + return token >= 64 /* FirstAssignment */ && token <= 79 /* LastAssignment */; +} +function tryGetClassExtendingExpressionWithTypeArguments(node) { + const cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : void 0; +} +function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + if (isExpressionWithTypeArguments(node)) { + if (isHeritageClause(node.parent) && isClassLike(node.parent.parent)) { + return { class: node.parent.parent, isImplements: node.parent.token === 119 /* ImplementsKeyword */ }; + } + if (isJSDocAugmentsTag(node.parent)) { + const host = getEffectiveJSDocHost(node.parent); + if (host && isClassLike(host)) { + return { class: host, isImplements: false }; + } + } + } + return void 0; +} +function isAssignmentExpression(node, excludeCompoundAssignment) { + return isBinaryExpression(node) && (excludeCompoundAssignment ? node.operatorToken.kind === 64 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && isLeftHandSideExpression(node.left); +} +function isDestructuringAssignment(node) { + if (isAssignmentExpression( + node, + /*excludeCompoundAssignment*/ + true + )) { + const kind = node.left.kind; + return kind === 210 /* ObjectLiteralExpression */ || kind === 209 /* ArrayLiteralExpression */; + } + return false; +} +function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== void 0; +} +function isEntityNameExpression(node) { + return node.kind === 80 /* Identifier */ || isPropertyAccessEntityNameExpression(node); +} +function getFirstIdentifier(node) { + switch (node.kind) { + case 80 /* Identifier */: + return node; + case 166 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 80 /* Identifier */); + return node; + case 211 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 80 /* Identifier */); + return node; + } +} +function isDottedName(node) { + return node.kind === 80 /* Identifier */ || node.kind === 110 /* ThisKeyword */ || node.kind === 108 /* SuperKeyword */ || node.kind === 236 /* MetaProperty */ || node.kind === 211 /* PropertyAccessExpression */ && isDottedName(node.expression) || node.kind === 217 /* ParenthesizedExpression */ && isDottedName(node.expression); +} +function isPropertyAccessEntityNameExpression(node) { + return isPropertyAccessExpression(node) && isIdentifier(node.name) && isEntityNameExpression(node.expression); +} +function tryGetPropertyAccessOrIdentifierToString(expr) { + if (isPropertyAccessExpression(expr)) { + const baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== void 0) { + return baseStr + "." + entityNameToString(expr.name); + } + } else if (isElementAccessExpression(expr)) { + const baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== void 0 && isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (isIdentifier(expr)) { + return unescapeLeadingUnderscores(expr.escapedText); + } else if (isJsxNamespacedName(expr)) { + return getTextOfJsxNamespacedName(expr); + } + return void 0; +} +function isPrototypeAccess(node) { + return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype"; +} +function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node || node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.name === node || node.parent.kind === 236 /* MetaProperty */ && node.parent.name === node; +} +function isRightSideOfAccessExpression(node) { + return !!node.parent && (isPropertyAccessExpression(node.parent) && node.parent.name === node || isElementAccessExpression(node.parent) && node.parent.argumentExpression === node); +} +function isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(node) { + return isQualifiedName(node.parent) && node.parent.right === node || isPropertyAccessExpression(node.parent) && node.parent.name === node || isJSDocMemberName(node.parent) && node.parent.right === node; +} +function isInstanceOfExpression(node) { + return isBinaryExpression(node) && node.operatorToken.kind === 104 /* InstanceOfKeyword */; +} +function isRightSideOfInstanceofExpression(node) { + return isInstanceOfExpression(node.parent) && node === node.parent.right; +} +function isEmptyObjectLiteral(expression) { + return expression.kind === 210 /* ObjectLiteralExpression */ && expression.properties.length === 0; +} +function isEmptyArrayLiteral(expression) { + return expression.kind === 209 /* ArrayLiteralExpression */ && expression.elements.length === 0; +} +function getLocalSymbolForExportDefault(symbol) { + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return void 0; + for (const decl of symbol.declarations) { + if (decl.localSymbol) return decl.localSymbol; + } + return void 0; +} +function isExportDefaultSymbol(symbol) { + return symbol && length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 2048 /* Default */); +} +function tryExtractTSExtension(fileName) { + return find(supportedTSExtensionsForExtractExtension, (extension) => fileExtensionIs(fileName, extension)); +} +function getExpandedCharCodes(input) { + const output = []; + const length2 = input.length; + for (let i = 0; i < length2; i++) { + const charCode = input.charCodeAt(i); + if (charCode < 128) { + output.push(charCode); + } else if (charCode < 2048) { + output.push(charCode >> 6 | 192); + output.push(charCode & 63 | 128); + } else if (charCode < 65536) { + output.push(charCode >> 12 | 224); + output.push(charCode >> 6 & 63 | 128); + output.push(charCode & 63 | 128); + } else if (charCode < 131072) { + output.push(charCode >> 18 | 240); + output.push(charCode >> 12 & 63 | 128); + output.push(charCode >> 6 & 63 | 128); + output.push(charCode & 63 | 128); + } else { + Debug.assert(false, "Unexpected code point"); + } + } + return output; +} +var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; +function convertToBase64(input) { + let result = ""; + const charCodes = getExpandedCharCodes(input); + let i = 0; + const length2 = charCodes.length; + let byte1, byte2, byte3, byte4; + while (i < length2) { + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + if (i + 1 >= length2) { + byte3 = byte4 = 64; + } else if (i + 2 >= length2) { + byte4 = 64; + } + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; +} +function base64encode(host, input) { + if (host && host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); +} +function readJsonOrUndefined(path, hostOrText) { + const jsonText = isString(hostOrText) ? hostOrText : hostOrText.readFile(path); + if (!jsonText) return void 0; + const result = parseConfigFileTextToJson(path, jsonText); + return !result.error ? result.config : void 0; +} +function readJson(path, host) { + return readJsonOrUndefined(path, host) || {}; +} +function tryParseJson(text) { + try { + return JSON.parse(text); + } catch { + return void 0; + } +} +function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); +} +var carriageReturnLineFeed = "\r\n"; +var lineFeed = "\n"; +function getNewLineCharacter(options) { + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + case void 0: + return lineFeed; + } +} +function createRange(pos, end = pos) { + Debug.assert(end >= pos || end === -1); + return { pos, end }; +} +function moveRangeEnd(range, end) { + return createRange(range.pos, end); +} +function moveRangePos(range, pos) { + return createRange(pos, range.end); +} +function moveRangePastDecorators(node) { + const lastDecorator = canHaveModifiers(node) ? findLast(node.modifiers, isDecorator) : void 0; + return lastDecorator && !positionIsSynthesized(lastDecorator.end) ? moveRangePos(node, lastDecorator.end) : node; +} +function moveRangePastModifiers(node) { + if (isPropertyDeclaration(node) || isMethodDeclaration(node)) { + return moveRangePos(node, node.name.pos); + } + const lastModifier = canHaveModifiers(node) ? lastOrUndefined(node.modifiers) : void 0; + return lastModifier && !positionIsSynthesized(lastModifier.end) ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); +} +function createTokenRange(pos, token) { + return createRange(pos, pos + tokenToString(token).length); +} +function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); +} +function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine( + getStartPositionOfRange( + range1, + sourceFile, + /*includeComments*/ + false + ), + getStartPositionOfRange( + range2, + sourceFile, + /*includeComments*/ + false + ), + sourceFile + ); +} +function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); +} +function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange( + range1, + sourceFile, + /*includeComments*/ + false + ), range2.end, sourceFile); +} +function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange( + range2, + sourceFile, + /*includeComments*/ + false + ), sourceFile); +} +function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) { + const range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments); + return getLinesBetweenPositions(sourceFile, range1.end, range2Start); +} +function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return getLinesBetweenPositions(sourceFile, pos1, pos2) === 0; +} +function getStartPositionOfRange(range, sourceFile, includeComments) { + return positionIsSynthesized(range.pos) ? -1 : skipTrivia( + sourceFile.text, + range.pos, + /*stopAfterLineBreak*/ + false, + includeComments + ); +} +function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { + const startPos = skipTrivia( + sourceFile.text, + pos, + /*stopAfterLineBreak*/ + false, + includeComments + ); + const prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); + return getLinesBetweenPositions(sourceFile, prevPos ?? stopPos, startPos); +} +function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { + const nextPos = skipTrivia( + sourceFile.text, + pos, + /*stopAfterLineBreak*/ + false, + includeComments + ); + return getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); +} +function rangeContainsRange(r1, r2) { + return startEndContainsRange(r1.pos, r1.end, r2); +} +function startEndContainsRange(start, end, range) { + return start <= range.pos && end >= range.end; +} +function getPreviousNonWhitespacePosition(pos, stopPos = 0, sourceFile) { + while (pos-- > stopPos) { + if (!isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { + return pos; + } + } +} +function isDeclarationNameOfEnumOrNamespace(node) { + const parseNode = getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 266 /* EnumDeclaration */: + case 267 /* ModuleDeclaration */: + return parseNode === parseNode.parent.name; + } + } + return false; +} +function getInitializedVariables(node) { + return filter(node.declarations, isInitializedVariable); +} +function isInitializedVariable(node) { + return isVariableDeclaration(node) && node.initializer !== void 0; +} +function isWatchSet(options) { + return options.watch && hasProperty(options, "watch"); +} +function closeFileWatcher(watcher) { + watcher.close(); +} +function getCheckFlags(symbol) { + return symbol.flags & 33554432 /* Transient */ ? symbol.links.checkFlags : 0; +} +function getDeclarationModifierFlagsFromSymbol(s, isWrite = false) { + if (s.valueDeclaration) { + const declaration = isWrite && s.declarations && find(s.declarations, isSetAccessorDeclaration) || s.flags & 32768 /* GetAccessor */ && find(s.declarations, isGetAccessorDeclaration) || s.valueDeclaration; + const flags = getCombinedModifierFlags(declaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~7 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 6 /* Synthetic */) { + const checkFlags = s.links.checkFlags; + const accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 2 /* Private */ : checkFlags & 256 /* ContainsPublic */ ? 1 /* Public */ : 4 /* Protected */; + const staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 256 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 4194304 /* Prototype */) { + return 1 /* Public */ | 256 /* Static */; + } + return 0; +} +function skipAlias(symbol, checker) { + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; +} +function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; +} +function isWriteOnlyAccess(node) { + return accessKind(node) === 1 /* Write */; +} +function isWriteAccess(node) { + return accessKind(node) !== 0 /* Read */; +} +function accessKind(node) { + const { parent } = node; + switch (parent == null ? void 0 : parent.kind) { + case 217 /* ParenthesizedExpression */: + return accessKind(parent); + case 225 /* PostfixUnaryExpression */: + case 224 /* PrefixUnaryExpression */: + const { operator } = parent; + return operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */ ? 2 /* ReadWrite */ : 0 /* Read */; + case 226 /* BinaryExpression */: + const { left, operatorToken } = parent; + return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 64 /* EqualsToken */ ? 1 /* Write */ : 2 /* ReadWrite */ : 0 /* Read */; + case 211 /* PropertyAccessExpression */: + return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 303 /* PropertyAssignment */: { + const parentAccess = accessKind(parent.parent); + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 304 /* ShorthandPropertyAssignment */: + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 209 /* ArrayLiteralExpression */: + return accessKind(parent); + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + return node === parent.initializer ? 1 /* Write */ : 0 /* Read */; + default: + return 0 /* Read */; + } +} +function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return Debug.assertNever(a); + } +} +function compareDataObjects(dst, src) { + if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { + return false; + } + for (const e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; +} +function clearMap(map2, onDeleteValue) { + map2.forEach(onDeleteValue); + map2.clear(); +} +function mutateMapSkippingNewValues(map2, newMap, options) { + const { onDeleteValue, onExistingValue } = options; + map2.forEach((existingValue, key) => { + var _a; + if (!(newMap == null ? void 0 : newMap.has(key))) { + map2.delete(key); + onDeleteValue(existingValue, key); + } else if (onExistingValue) { + onExistingValue(existingValue, (_a = newMap.get) == null ? void 0 : _a.call(newMap, key), key); + } + }); +} +function mutateMap(map2, newMap, options) { + mutateMapSkippingNewValues(map2, newMap, options); + const { createNewValue } = options; + newMap == null ? void 0 : newMap.forEach((valueInNewMap, key) => { + if (!map2.has(key)) { + map2.set(key, createNewValue(key, valueInNewMap)); + } + }); +} +function getClassLikeDeclarationOfSymbol(symbol) { + var _a; + return (_a = symbol.declarations) == null ? void 0 : _a.find(isClassLike); +} +function getObjectFlags(type) { + return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0; +} +function isUMDExportSymbol(symbol) { + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && isNamespaceExportDeclaration(symbol.declarations[0]); +} +function getLastChild(node) { + let lastChild; + forEachChild(node, (child) => { + if (nodeIsPresent(child)) lastChild = child; + }, (children) => { + for (let i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; +} +function addToSeen(seen, key) { + if (seen.has(key)) { + return false; + } + seen.add(key); + return true; +} +function isTypeNodeKind(kind) { + return kind >= 182 /* FirstTypeNode */ && kind <= 205 /* LastTypeNode */ || kind === 133 /* AnyKeyword */ || kind === 159 /* UnknownKeyword */ || kind === 150 /* NumberKeyword */ || kind === 163 /* BigIntKeyword */ || kind === 151 /* ObjectKeyword */ || kind === 136 /* BooleanKeyword */ || kind === 154 /* StringKeyword */ || kind === 155 /* SymbolKeyword */ || kind === 116 /* VoidKeyword */ || kind === 157 /* UndefinedKeyword */ || kind === 146 /* NeverKeyword */ || kind === 141 /* IntrinsicKeyword */ || kind === 233 /* ExpressionWithTypeArguments */ || kind === 312 /* JSDocAllType */ || kind === 313 /* JSDocUnknownType */ || kind === 314 /* JSDocNullableType */ || kind === 315 /* JSDocNonNullableType */ || kind === 316 /* JSDocOptionalType */ || kind === 317 /* JSDocFunctionType */ || kind === 318 /* JSDocVariadicType */; +} +function isAccessExpression(node) { + return node.kind === 211 /* PropertyAccessExpression */ || node.kind === 212 /* ElementAccessExpression */; +} +function getLeftmostAccessExpression(expr) { + while (isAccessExpression(expr)) { + expr = expr.expression; + } + return expr; +} +function getLeftmostExpression(node, stopAtCallExpressions) { + while (true) { + switch (node.kind) { + case 225 /* PostfixUnaryExpression */: + node = node.operand; + continue; + case 226 /* BinaryExpression */: + node = node.left; + continue; + case 227 /* ConditionalExpression */: + node = node.condition; + continue; + case 215 /* TaggedTemplateExpression */: + node = node.tag; + continue; + case 213 /* CallExpression */: + if (stopAtCallExpressions) { + return node; + } + // falls through + case 234 /* AsExpression */: + case 212 /* ElementAccessExpression */: + case 211 /* PropertyAccessExpression */: + case 235 /* NonNullExpression */: + case 355 /* PartiallyEmittedExpression */: + case 238 /* SatisfiesExpression */: + node = node.expression; + continue; + } + return node; + } +} +function Symbol4(flags, name) { + this.flags = flags; + this.escapedName = name; + this.declarations = void 0; + this.valueDeclaration = void 0; + this.id = 0; + this.mergeId = 0; + this.parent = void 0; + this.members = void 0; + this.exports = void 0; + this.exportSymbol = void 0; + this.constEnumOnlyModule = void 0; + this.isReferenced = void 0; + this.lastAssignmentPos = void 0; + this.links = void 0; +} +function Type3(checker, flags) { + this.flags = flags; + if (Debug.isDebugging || tracing) { + this.checker = checker; + } +} +function Signature2(checker, flags) { + this.flags = flags; + if (Debug.isDebugging) { + this.checker = checker; + } +} +function Node4(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = void 0; + this.original = void 0; + this.emitNode = void 0; +} +function Token(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = void 0; + this.emitNode = void 0; +} +function Identifier2(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = void 0; + this.original = void 0; + this.emitNode = void 0; +} +function SourceMapSource(fileName, text, skipTrivia2) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia2 || ((pos) => pos); +} +var objectAllocator = { + getNodeConstructor: () => Node4, + getTokenConstructor: () => Token, + getIdentifierConstructor: () => Identifier2, + getPrivateIdentifierConstructor: () => Node4, + getSourceFileConstructor: () => Node4, + getSymbolConstructor: () => Symbol4, + getTypeConstructor: () => Type3, + getSignatureConstructor: () => Signature2, + getSourceMapSourceConstructor: () => SourceMapSource +}; +function formatStringFromArgs(text, args) { + return text.replace(/\{(\d+)\}/g, (_match, index) => "" + Debug.checkDefined(args[+index])); +} +var localizedDiagnosticMessages; +function setLocalizedDiagnosticMessages(messages) { + localizedDiagnosticMessages = messages; +} +function getLocaleSpecificMessage(message) { + return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message; +} +function createDetachedDiagnostic(fileName, sourceText, start, length2, message, ...args) { + if (start + length2 > sourceText.length) { + length2 = sourceText.length - start; + } + assertDiagnosticLocation(sourceText, start, length2); + let text = getLocaleSpecificMessage(message); + if (some(args)) { + text = formatStringFromArgs(text, args); + } + return { + file: void 0, + start, + length: length2, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + fileName + }; +} +function isDiagnosticWithDetachedLocation(diagnostic) { + return diagnostic.file === void 0 && diagnostic.start !== void 0 && diagnostic.length !== void 0 && typeof diagnostic.fileName === "string"; +} +function attachFileToDiagnostic(diagnostic, file) { + const fileName = file.fileName || ""; + const length2 = file.text.length; + Debug.assertEqual(diagnostic.fileName, fileName); + Debug.assertLessThanOrEqual(diagnostic.start, length2); + Debug.assertLessThanOrEqual(diagnostic.start + diagnostic.length, length2); + const diagnosticWithLocation = { + file, + start: diagnostic.start, + length: diagnostic.length, + messageText: diagnostic.messageText, + category: diagnostic.category, + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary + }; + if (diagnostic.relatedInformation) { + diagnosticWithLocation.relatedInformation = []; + for (const related of diagnostic.relatedInformation) { + if (isDiagnosticWithDetachedLocation(related) && related.fileName === fileName) { + Debug.assertLessThanOrEqual(related.start, length2); + Debug.assertLessThanOrEqual(related.start + related.length, length2); + diagnosticWithLocation.relatedInformation.push(attachFileToDiagnostic(related, file)); + } else { + diagnosticWithLocation.relatedInformation.push(related); + } + } + } + return diagnosticWithLocation; +} +function attachFileToDiagnostics(diagnostics, file) { + const diagnosticsWithLocation = []; + for (const diagnostic of diagnostics) { + diagnosticsWithLocation.push(attachFileToDiagnostic(diagnostic, file)); + } + return diagnosticsWithLocation; +} +function createFileDiagnostic(file, start, length2, message, ...args) { + assertDiagnosticLocation(file.text, start, length2); + let text = getLocaleSpecificMessage(message); + if (some(args)) { + text = formatStringFromArgs(text, args); + } + return { + file, + start, + length: length2, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + reportsDeprecated: message.reportsDeprecated + }; +} +function formatMessage(message, ...args) { + let text = getLocaleSpecificMessage(message); + if (some(args)) { + text = formatStringFromArgs(text, args); + } + return text; +} +function createCompilerDiagnostic(message, ...args) { + let text = getLocaleSpecificMessage(message); + if (some(args)) { + text = formatStringFromArgs(text, args); + } + return { + file: void 0, + start: void 0, + length: void 0, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + reportsDeprecated: message.reportsDeprecated + }; +} +function createCompilerDiagnosticFromMessageChain(chain, relatedInformation) { + return { + file: void 0, + start: void 0, + length: void 0, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText, + relatedInformation + }; +} +function chainDiagnosticMessages(details, message, ...args) { + let text = getLocaleSpecificMessage(message); + if (some(args)) { + text = formatStringFromArgs(text, args); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details === void 0 || Array.isArray(details) ? details : [details] + }; +} +function concatenateDiagnosticMessageChains(headChain, tailChain) { + let lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next[0]; + } + lastChain.next = [tailChain]; +} +function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : void 0; +} +function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || 0 /* EqualTo */; +} +function compareDiagnosticsSkipRelatedInformation(d1, d2) { + const code1 = getDiagnosticCode(d1); + const code2 = getDiagnosticCode(d2); + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(code1, code2) || compareMessageText(d1, d2) || 0 /* EqualTo */; +} +function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0 /* EqualTo */; + } + if (d1.relatedInformation && d2.relatedInformation) { + return compareValues(d2.relatedInformation.length, d1.relatedInformation.length) || forEach(d1.relatedInformation, (d1i, index) => { + const d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); + }) || 0 /* EqualTo */; + } + return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; +} +function compareMessageText(d1, d2) { + let headMsg1 = getDiagnosticMessage(d1); + let headMsg2 = getDiagnosticMessage(d2); + if (typeof headMsg1 !== "string") { + headMsg1 = headMsg1.messageText; + } + if (typeof headMsg2 !== "string") { + headMsg2 = headMsg2.messageText; + } + const chain1 = typeof d1.messageText !== "string" ? d1.messageText.next : void 0; + const chain2 = typeof d2.messageText !== "string" ? d2.messageText.next : void 0; + let res = compareStringsCaseSensitive(headMsg1, headMsg2); + if (res) { + return res; + } + res = compareMessageChain(chain1, chain2); + if (res) { + return res; + } + if (d1.canonicalHead && !d2.canonicalHead) { + return -1 /* LessThan */; + } + if (d2.canonicalHead && !d1.canonicalHead) { + return 1 /* GreaterThan */; + } + return 0 /* EqualTo */; +} +function compareMessageChain(c1, c2) { + if (c1 === void 0 && c2 === void 0) { + return 0 /* EqualTo */; + } + if (c1 === void 0) { + return 1 /* GreaterThan */; + } + if (c2 === void 0) { + return -1 /* LessThan */; + } + return compareMessageChainSize(c1, c2) || compareMessageChainContent(c1, c2); +} +function compareMessageChainSize(c1, c2) { + if (c1 === void 0 && c2 === void 0) { + return 0 /* EqualTo */; + } + if (c1 === void 0) { + return 1 /* GreaterThan */; + } + if (c2 === void 0) { + return -1 /* LessThan */; + } + let res = compareValues(c2.length, c1.length); + if (res) { + return res; + } + for (let i = 0; i < c2.length; i++) { + res = compareMessageChainSize(c1[i].next, c2[i].next); + if (res) { + return res; + } + } + return 0 /* EqualTo */; +} +function compareMessageChainContent(c1, c2) { + let res; + for (let i = 0; i < c2.length; i++) { + res = compareStringsCaseSensitive(c1[i].messageText, c2[i].messageText); + if (res) { + return res; + } + if (c1[i].next === void 0) { + continue; + } + res = compareMessageChainContent(c1[i].next, c2[i].next); + if (res) { + return res; + } + } + return 0 /* EqualTo */; +} +function diagnosticsEqualityComparer(d1, d2) { + const code1 = getDiagnosticCode(d1); + const code2 = getDiagnosticCode(d2); + const msg1 = getDiagnosticMessage(d1); + const msg2 = getDiagnosticMessage(d2); + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) === 0 /* EqualTo */ && compareValues(d1.start, d2.start) === 0 /* EqualTo */ && compareValues(d1.length, d2.length) === 0 /* EqualTo */ && compareValues(code1, code2) === 0 /* EqualTo */ && messageTextEqualityComparer(msg1, msg2); +} +function getDiagnosticCode(d) { + var _a; + return ((_a = d.canonicalHead) == null ? void 0 : _a.code) || d.code; +} +function getDiagnosticMessage(d) { + var _a; + return ((_a = d.canonicalHead) == null ? void 0 : _a.messageText) || d.messageText; +} +function messageTextEqualityComparer(m1, m2) { + const t1 = typeof m1 === "string" ? m1 : m1.messageText; + const t2 = typeof m2 === "string" ? m2 : m2.messageText; + return compareStringsCaseSensitive(t1, t2) === 0 /* EqualTo */; +} +function getLanguageVariant(scriptKind) { + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; +} +function walkTreeForJSXTags(node) { + if (!(node.transformFlags & 2 /* ContainsJsx */)) return void 0; + return isJsxOpeningLikeElement(node) || isJsxFragment(node) ? node : forEachChild(node, walkTreeForJSXTags); +} +function isFileModuleFromUsingJSXTag(file) { + return !file.isDeclarationFile ? walkTreeForJSXTags(file) : void 0; +} +function isFileForcedToBeModuleByFormat(file, options) { + return (getImpliedNodeFormatForEmitWorker(file, options) === 99 /* ESNext */ || fileExtensionIsOneOf(file.fileName, [".cjs" /* Cjs */, ".cts" /* Cts */, ".mjs" /* Mjs */, ".mts" /* Mts */])) && !file.isDeclarationFile ? true : void 0; +} +function getSetExternalModuleIndicator(options) { + switch (getEmitModuleDetectionKind(options)) { + case 3 /* Force */: + return (file) => { + file.externalModuleIndicator = isFileProbablyExternalModule(file) || !file.isDeclarationFile || void 0; + }; + case 1 /* Legacy */: + return (file) => { + file.externalModuleIndicator = isFileProbablyExternalModule(file); + }; + case 2 /* Auto */: + const checks = [isFileProbablyExternalModule]; + if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) { + checks.push(isFileModuleFromUsingJSXTag); + } + checks.push(isFileForcedToBeModuleByFormat); + const combined = or(...checks); + const callback = (file) => void (file.externalModuleIndicator = combined(file, options)); + return callback; + } +} +function importSyntaxAffectsModuleResolution(options) { + const moduleResolution = getEmitModuleResolutionKind(options); + return 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */ || getResolvePackageJsonExports(options) || getResolvePackageJsonImports(options); +} +function createComputedCompilerOptions(options) { + return options; +} +var _computedOptions = createComputedCompilerOptions({ + allowImportingTsExtensions: { + dependencies: ["rewriteRelativeImportExtensions"], + computeValue: (compilerOptions) => { + return !!(compilerOptions.allowImportingTsExtensions || compilerOptions.rewriteRelativeImportExtensions); + } + }, + target: { + dependencies: ["module"], + computeValue: (compilerOptions) => { + const target = compilerOptions.target === 0 /* ES3 */ ? void 0 : compilerOptions.target; + return target ?? (compilerOptions.module === 100 /* Node16 */ && 9 /* ES2022 */ || compilerOptions.module === 101 /* Node18 */ && 9 /* ES2022 */ || compilerOptions.module === 199 /* NodeNext */ && 99 /* ESNext */ || 1 /* ES5 */); + } + }, + module: { + dependencies: ["target"], + computeValue: (compilerOptions) => { + return typeof compilerOptions.module === "number" ? compilerOptions.module : _computedOptions.target.computeValue(compilerOptions) >= 2 /* ES2015 */ ? 5 /* ES2015 */ : 1 /* CommonJS */; + } + }, + moduleResolution: { + dependencies: ["module", "target"], + computeValue: (compilerOptions) => { + let moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === void 0) { + switch (_computedOptions.module.computeValue(compilerOptions)) { + case 1 /* CommonJS */: + moduleResolution = 2 /* Node10 */; + break; + case 100 /* Node16 */: + case 101 /* Node18 */: + moduleResolution = 3 /* Node16 */; + break; + case 199 /* NodeNext */: + moduleResolution = 99 /* NodeNext */; + break; + case 200 /* Preserve */: + moduleResolution = 100 /* Bundler */; + break; + default: + moduleResolution = 1 /* Classic */; + break; + } + } + return moduleResolution; + } + }, + moduleDetection: { + dependencies: ["module", "target"], + computeValue: (compilerOptions) => { + if (compilerOptions.moduleDetection !== void 0) { + return compilerOptions.moduleDetection; + } + const moduleKind = _computedOptions.module.computeValue(compilerOptions); + return 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */ ? 3 /* Force */ : 2 /* Auto */; + } + }, + isolatedModules: { + dependencies: ["verbatimModuleSyntax"], + computeValue: (compilerOptions) => { + return !!(compilerOptions.isolatedModules || compilerOptions.verbatimModuleSyntax); + } + }, + esModuleInterop: { + dependencies: ["module", "target"], + computeValue: (compilerOptions) => { + if (compilerOptions.esModuleInterop !== void 0) { + return compilerOptions.esModuleInterop; + } + switch (_computedOptions.module.computeValue(compilerOptions)) { + case 100 /* Node16 */: + case 101 /* Node18 */: + case 199 /* NodeNext */: + case 200 /* Preserve */: + return true; + } + return false; + } + }, + allowSyntheticDefaultImports: { + dependencies: ["module", "target", "moduleResolution"], + computeValue: (compilerOptions) => { + if (compilerOptions.allowSyntheticDefaultImports !== void 0) { + return compilerOptions.allowSyntheticDefaultImports; + } + return _computedOptions.esModuleInterop.computeValue(compilerOptions) || _computedOptions.module.computeValue(compilerOptions) === 4 /* System */ || _computedOptions.moduleResolution.computeValue(compilerOptions) === 100 /* Bundler */; + } + }, + resolvePackageJsonExports: { + dependencies: ["moduleResolution"], + computeValue: (compilerOptions) => { + const moduleResolution = _computedOptions.moduleResolution.computeValue(compilerOptions); + if (!moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { + return false; + } + if (compilerOptions.resolvePackageJsonExports !== void 0) { + return compilerOptions.resolvePackageJsonExports; + } + switch (moduleResolution) { + case 3 /* Node16 */: + case 99 /* NodeNext */: + case 100 /* Bundler */: + return true; + } + return false; + } + }, + resolvePackageJsonImports: { + dependencies: ["moduleResolution", "resolvePackageJsonExports"], + computeValue: (compilerOptions) => { + const moduleResolution = _computedOptions.moduleResolution.computeValue(compilerOptions); + if (!moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { + return false; + } + if (compilerOptions.resolvePackageJsonExports !== void 0) { + return compilerOptions.resolvePackageJsonExports; + } + switch (moduleResolution) { + case 3 /* Node16 */: + case 99 /* NodeNext */: + case 100 /* Bundler */: + return true; + } + return false; + } + }, + resolveJsonModule: { + dependencies: ["moduleResolution", "module", "target"], + computeValue: (compilerOptions) => { + if (compilerOptions.resolveJsonModule !== void 0) { + return compilerOptions.resolveJsonModule; + } + return _computedOptions.moduleResolution.computeValue(compilerOptions) === 100 /* Bundler */; + } + }, + declaration: { + dependencies: ["composite"], + computeValue: (compilerOptions) => { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + }, + preserveConstEnums: { + dependencies: ["isolatedModules", "verbatimModuleSyntax"], + computeValue: (compilerOptions) => { + return !!(compilerOptions.preserveConstEnums || _computedOptions.isolatedModules.computeValue(compilerOptions)); + } + }, + incremental: { + dependencies: ["composite"], + computeValue: (compilerOptions) => { + return !!(compilerOptions.incremental || compilerOptions.composite); + } + }, + declarationMap: { + dependencies: ["declaration", "composite"], + computeValue: (compilerOptions) => { + return !!(compilerOptions.declarationMap && _computedOptions.declaration.computeValue(compilerOptions)); + } + }, + allowJs: { + dependencies: ["checkJs"], + computeValue: (compilerOptions) => { + return compilerOptions.allowJs === void 0 ? !!compilerOptions.checkJs : compilerOptions.allowJs; + } + }, + useDefineForClassFields: { + dependencies: ["target", "module"], + computeValue: (compilerOptions) => { + return compilerOptions.useDefineForClassFields === void 0 ? _computedOptions.target.computeValue(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; + } + }, + noImplicitAny: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "noImplicitAny"); + } + }, + noImplicitThis: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "noImplicitThis"); + } + }, + strictNullChecks: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "strictNullChecks"); + } + }, + strictFunctionTypes: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + } + }, + strictBindCallApply: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "strictBindCallApply"); + } + }, + strictPropertyInitialization: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + } + }, + strictBuiltinIteratorReturn: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "strictBuiltinIteratorReturn"); + } + }, + alwaysStrict: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "alwaysStrict"); + } + }, + useUnknownInCatchVariables: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "useUnknownInCatchVariables"); + } + } +}); +var computedOptions = _computedOptions; +var getAllowImportingTsExtensions = _computedOptions.allowImportingTsExtensions.computeValue; +var getEmitScriptTarget = _computedOptions.target.computeValue; +var getEmitModuleKind = _computedOptions.module.computeValue; +var getEmitModuleResolutionKind = _computedOptions.moduleResolution.computeValue; +var getEmitModuleDetectionKind = _computedOptions.moduleDetection.computeValue; +var getIsolatedModules = _computedOptions.isolatedModules.computeValue; +var getESModuleInterop = _computedOptions.esModuleInterop.computeValue; +var getAllowSyntheticDefaultImports = _computedOptions.allowSyntheticDefaultImports.computeValue; +var getResolvePackageJsonExports = _computedOptions.resolvePackageJsonExports.computeValue; +var getResolvePackageJsonImports = _computedOptions.resolvePackageJsonImports.computeValue; +var getResolveJsonModule = _computedOptions.resolveJsonModule.computeValue; +var getEmitDeclarations = _computedOptions.declaration.computeValue; +var shouldPreserveConstEnums = _computedOptions.preserveConstEnums.computeValue; +var isIncrementalCompilation = _computedOptions.incremental.computeValue; +var getAreDeclarationMapsEnabled = _computedOptions.declarationMap.computeValue; +var getAllowJSCompilerOption = _computedOptions.allowJs.computeValue; +var getUseDefineForClassFields = _computedOptions.useDefineForClassFields.computeValue; +function emitModuleKindIsNonNodeESM(moduleKind) { + return moduleKind >= 5 /* ES2015 */ && moduleKind <= 99 /* ESNext */; +} +function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case 0 /* None */: + case 4 /* System */: + case 3 /* UMD */: + return false; + } + return true; +} +function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; +} +function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; +} +function moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution) { + return moduleResolution >= 3 /* Node16 */ && moduleResolution <= 99 /* NodeNext */ || moduleResolution === 100 /* Bundler */; +} +function moduleSupportsImportAttributes(moduleKind) { + return 101 /* Node18 */ <= moduleKind && moduleKind <= 199 /* NodeNext */ || moduleKind === 200 /* Preserve */ || moduleKind === 99 /* ESNext */; +} +function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === void 0 ? !!compilerOptions.strict : !!compilerOptions[flag]; +} +function getNameOfScriptTarget(scriptTarget) { + return forEachEntry(targetOptionDeclaration.type, (value, key) => value === scriptTarget ? key : void 0); +} +function getEmitStandardClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields !== false && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */; +} +function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, semanticDiagnosticsOptionDeclarations); +} +function compilerOptionsAffectEmit(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, affectsEmitOptionDeclarations); +} +function compilerOptionsAffectDeclarationPath(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, affectsDeclarationPathOptionDeclarations); +} +function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : option.allowJsFlag ? getAllowJSCompilerOption(options) : options[option.name]; +} +function getJSXTransformEnabled(options) { + const jsx = options.jsx; + return jsx === 2 /* React */ || jsx === 4 /* ReactJSX */ || jsx === 5 /* ReactJSXDev */; +} +function getJSXImplicitImportBase(compilerOptions, file) { + const jsxImportSourcePragmas = file == null ? void 0 : file.pragmas.get("jsximportsource"); + const jsxImportSourcePragma = isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; + const jsxRuntimePragmas = file == null ? void 0 : file.pragmas.get("jsxruntime"); + const jsxRuntimePragma = isArray(jsxRuntimePragmas) ? jsxRuntimePragmas[jsxRuntimePragmas.length - 1] : jsxRuntimePragmas; + if ((jsxRuntimePragma == null ? void 0 : jsxRuntimePragma.arguments.factory) === "classic") { + return void 0; + } + return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || jsxImportSourcePragma || (jsxRuntimePragma == null ? void 0 : jsxRuntimePragma.arguments.factory) === "automatic" ? (jsxImportSourcePragma == null ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" : void 0; +} +function getJSXRuntimeImport(base, options) { + return base ? `${base}/${options.jsx === 5 /* ReactJSXDev */ ? "jsx-dev-runtime" : "jsx-runtime"}` : void 0; +} +function hasZeroOrOneAsteriskCharacter(str) { + let seenAsterisk = false; + for (let i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } else { + return false; + } + } + } + return true; +} +function createSymlinkCache(cwd, getCanonicalFileName) { + let symlinkedDirectories; + let symlinkedDirectoriesByRealpath; + let symlinkedFiles; + let hasProcessedResolutions = false; + return { + getSymlinkedFiles: () => symlinkedFiles, + getSymlinkedDirectories: () => symlinkedDirectories, + getSymlinkedDirectoriesByRealpath: () => symlinkedDirectoriesByRealpath, + setSymlinkedFile: (path, real) => (symlinkedFiles || (symlinkedFiles = /* @__PURE__ */ new Map())).set(path, real), + setSymlinkedDirectory: (symlink, real) => { + let symlinkPath = toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories == null ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = createMultiMap())).add(real.realPath, symlink); + } + (symlinkedDirectories || (symlinkedDirectories = /* @__PURE__ */ new Map())).set(symlinkPath, real); + } + }, + setSymlinksFromResolutions(forEachResolvedModule, forEachResolvedTypeReferenceDirective, typeReferenceDirectives) { + Debug.assert(!hasProcessedResolutions); + hasProcessedResolutions = true; + forEachResolvedModule((resolution) => processResolution(this, resolution.resolvedModule)); + forEachResolvedTypeReferenceDirective((resolution) => processResolution(this, resolution.resolvedTypeReferenceDirective)); + typeReferenceDirectives.forEach((resolution) => processResolution(this, resolution.resolvedTypeReferenceDirective)); + }, + hasProcessedResolutions: () => hasProcessedResolutions, + setSymlinksFromResolution(resolution) { + processResolution(this, resolution); + }, + hasAnySymlinks + }; + function hasAnySymlinks() { + return !!(symlinkedFiles == null ? void 0 : symlinkedFiles.size) || !!symlinkedDirectories && !!forEachEntry(symlinkedDirectories, (value) => !!value); + } + function processResolution(cache, resolution) { + if (!resolution || !resolution.originalPath || !resolution.resolvedFileName) return; + const { resolvedFileName, originalPath } = resolution; + cache.setSymlinkedFile(toPath(originalPath, cwd, getCanonicalFileName), resolvedFileName); + const [commonResolved, commonOriginal] = guessDirectorySymlink(resolvedFileName, originalPath, cwd, getCanonicalFileName) || emptyArray; + if (commonResolved && commonOriginal) { + cache.setSymlinkedDirectory( + commonOriginal, + { + real: ensureTrailingDirectorySeparator(commonResolved), + realPath: ensureTrailingDirectorySeparator(toPath(commonResolved, cwd, getCanonicalFileName)) + } + ); + } + } +} +function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + const aParts = getPathComponents(getNormalizedAbsolutePath(a, cwd)); + const bParts = getPathComponents(getNormalizedAbsolutePath(b, cwd)); + let isDirectory = false; + while (aParts.length >= 2 && bParts.length >= 2 && !isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { + aParts.pop(); + bParts.pop(); + isDirectory = true; + } + return isDirectory ? [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)] : void 0; +} +function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return s !== void 0 && (getCanonicalFileName(s) === "node_modules" || startsWith(s, "@")); +} +var reservedCharacterPattern = /[^\w\s/]/g; +var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; +var commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; +var implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`; +var filesMatcher = { + /** + * Matches any single directory segment unless it is the last segment and a .min.js file + * Breakdown: + * [^./] # matches everything up to the first . character (excluding directory separators) + * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension + */ + singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`, + replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment) +}; +var directoriesMatcher = { + singleAsteriskRegexFragment: "[^/]*", + /** + * Regex for the ** wildcard. Matches any number of subdirectories. When used for including + * files or directories, does not match subdirectories that start with a . character + */ + doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`, + replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment) +}; +var excludeMatcher = { + singleAsteriskRegexFragment: "[^/]*", + doubleAsteriskRegexFragment: "(/.+?)?", + replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment) +}; +var wildcardMatchers = { + files: filesMatcher, + directories: directoriesMatcher, + exclude: excludeMatcher +}; +function getRegularExpressionForWildcard(specs, basePath, usage) { + const patterns = getRegularExpressionsForWildcards(specs, basePath, usage); + if (!patterns || !patterns.length) { + return void 0; + } + const pattern = patterns.map((pattern2) => `(${pattern2})`).join("|"); + const terminator = usage === "exclude" ? "($|/)" : "$"; + return `^(${pattern})${terminator}`; +} +function getRegularExpressionsForWildcards(specs, basePath, usage) { + if (specs === void 0 || specs.length === 0) { + return void 0; + } + return flatMap(specs, (spec) => spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage])); +} +function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); +} +function getPatternFromSpec(spec, basePath, usage) { + const pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); + return pattern && `^(${pattern})${usage === "exclude" ? "($|/)" : "$"}`; +} +function getSubPatternFromSpec(spec, basePath, usage, { singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter: replaceWildcardCharacter2 } = wildcardMatchers[usage]) { + let subpattern = ""; + let hasWrittenComponent = false; + const components = getNormalizedPathComponents(spec, basePath); + const lastComponent = last(components); + if (usage !== "exclude" && lastComponent === "**") { + return void 0; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + let optionalCount = 0; + for (let component of components) { + if (component === "**") { + subpattern += doubleAsteriskRegexFragment; + } else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += directorySeparator; + } + if (usage !== "exclude") { + let componentPattern = ""; + if (component.charCodeAt(0) === 42 /* asterisk */) { + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } else if (component.charCodeAt(0) === 63 /* question */) { + componentPattern += "[^./]"; + component = component.substr(1); + } + componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter2); + if (componentPattern !== component) { + subpattern += implicitExcludePathRegexPattern; + } + subpattern += componentPattern; + } else { + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter2); + } + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; +} +function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; +} +function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + const absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePatterns: map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), (pattern) => `^${pattern}$`), + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames2) + }; +} +function getRegexFromPattern(pattern, useCaseSensitiveFileNames2) { + return new RegExp(pattern, useCaseSensitiveFileNames2 ? "" : "i"); +} +function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory); + const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames2)); + const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames2); + const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames2); + const results = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]]; + const visited = /* @__PURE__ */ new Map(); + const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames2); + for (const basePath of patterns.basePaths) { + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + } + return flatten(results); + function visitDirectory(path2, absolutePath, depth2) { + const canonicalPath = toCanonical(realpath(absolutePath)); + if (visited.has(canonicalPath)) return; + visited.set(canonicalPath, true); + const { files, directories } = getFileSystemEntries(path2); + for (const current of toSorted(files, compareStringsCaseSensitive)) { + const name = combinePaths(path2, current); + const absoluteName = combinePaths(absolutePath, current); + if (extensions && !fileExtensionIsOneOf(name, extensions)) continue; + if (excludeRegex && excludeRegex.test(absoluteName)) continue; + if (!includeFileRegexes) { + results[0].push(name); + } else { + const includeIndex = findIndex(includeFileRegexes, (re) => re.test(absoluteName)); + if (includeIndex !== -1) { + results[includeIndex].push(name); + } + } + } + if (depth2 !== void 0) { + depth2--; + if (depth2 === 0) { + return; + } + } + for (const current of toSorted(directories, compareStringsCaseSensitive)) { + const name = combinePaths(path2, current); + const absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name, absoluteName, depth2); + } + } + } +} +function getBasePaths(path, includes, useCaseSensitiveFileNames2) { + const basePaths = [path]; + if (includes) { + const includeBasePaths = []; + for (const include of includes) { + const absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); + includeBasePaths.push(getIncludeBasePath(absolute)); + } + includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames2)); + for (const includeBasePath of includeBasePaths) { + if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames2))) { + basePaths.push(includeBasePath); + } + } + } + return basePaths; +} +function getIncludeBasePath(absolute) { + const wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + return !hasExtension(absolute) ? absolute : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(directorySeparator, wildcardOffset)); +} +function ensureScriptKind(fileName, scriptKind) { + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; +} +function getScriptKindFromFileName(fileName) { + const ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js" /* Js */: + case ".cjs" /* Cjs */: + case ".mjs" /* Mjs */: + return 1 /* JS */; + case ".jsx" /* Jsx */: + return 2 /* JSX */; + case ".ts" /* Ts */: + case ".cts" /* Cts */: + case ".mts" /* Mts */: + return 3 /* TS */; + case ".tsx" /* Tsx */: + return 4 /* TSX */; + case ".json" /* Json */: + return 6 /* JSON */; + default: + return 0 /* Unknown */; + } +} +var supportedTSExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */], [".cts" /* Cts */, ".d.cts" /* Dcts */], [".mts" /* Mts */, ".d.mts" /* Dmts */]]; +var supportedTSExtensionsFlat = flatten(supportedTSExtensions); +var supportedTSExtensionsWithJson = [...supportedTSExtensions, [".json" /* Json */]]; +var supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; +var supportedJSExtensions = [[".js" /* Js */, ".jsx" /* Jsx */], [".mjs" /* Mjs */], [".cjs" /* Cjs */]]; +var supportedJSExtensionsFlat = flatten(supportedJSExtensions); +var allSupportedExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".js" /* Js */, ".jsx" /* Jsx */], [".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */], [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */]]; +var allSupportedExtensionsWithJson = [...allSupportedExtensions, [".json" /* Json */]]; +var supportedDeclarationExtensions = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */]; +var supportedTSImplementationExtensions = [".ts" /* Ts */, ".cts" /* Cts */, ".mts" /* Mts */, ".tsx" /* Tsx */]; +var extensionsNotSupportingExtensionlessResolution = [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */, ".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */]; +function getSupportedExtensions(options, extraFileExtensions) { + const needJsExtensions = options && getAllowJSCompilerOption(options); + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : supportedTSExtensions; + } + const builtins = needJsExtensions ? allSupportedExtensions : supportedTSExtensions; + const flatBuiltins = flatten(builtins); + const extensions = [ + ...builtins, + ...mapDefined(extraFileExtensions, (x) => x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) && !flatBuiltins.includes(x.extension) ? [x.extension] : void 0) + ]; + return extensions; +} +function getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !getResolveJsonModule(options)) return supportedExtensions; + if (supportedExtensions === allSupportedExtensions) return allSupportedExtensionsWithJson; + if (supportedExtensions === supportedTSExtensions) return supportedTSExtensionsWithJson; + return [...supportedExtensions, [".json" /* Json */]]; +} +function isJSLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; +} +function hasJSFileExtension(fileName) { + return some(supportedJSExtensionsFlat, (extension) => fileExtensionIs(fileName, extension)); +} +function hasTSFileExtension(fileName) { + return some(supportedTSExtensionsFlat, (extension) => fileExtensionIs(fileName, extension)); +} +function hasImplementationTSFileExtension(fileName) { + return some(supportedTSImplementationExtensions, (extension) => fileExtensionIs(fileName, extension)) && !isDeclarationFileName(fileName); +} +function usesExtensionsOnImports({ imports }, hasExtension2 = or(hasJSFileExtension, hasTSFileExtension)) { + return firstDefined(imports, ({ text }) => pathIsRelative(text) && !fileExtensionIsOneOf(text, extensionsNotSupportingExtensionlessResolution) ? hasExtension2(text) : void 0) || false; +} +function getModuleSpecifierEndingPreference(preference, resolutionMode, compilerOptions, sourceFile) { + const moduleResolution = getEmitModuleResolutionKind(compilerOptions); + const moduleResolutionIsNodeNext = 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */; + if (preference === "js" || resolutionMode === 99 /* ESNext */ && moduleResolutionIsNodeNext) { + if (!shouldAllowImportingTsExtension(compilerOptions)) { + return 2 /* JsExtension */; + } + return inferPreference() !== 2 /* JsExtension */ ? 3 /* TsExtension */ : 2 /* JsExtension */; + } + if (preference === "minimal") { + return 0 /* Minimal */; + } + if (preference === "index") { + return 1 /* Index */; + } + if (!shouldAllowImportingTsExtension(compilerOptions)) { + return sourceFile && usesExtensionsOnImports(sourceFile) ? 2 /* JsExtension */ : 0 /* Minimal */; + } + return inferPreference(); + function inferPreference() { + let usesJsExtensions = false; + const specifiers = (sourceFile == null ? void 0 : sourceFile.imports.length) ? sourceFile.imports : sourceFile && isSourceFileJS(sourceFile) ? getRequiresAtTopOfFile(sourceFile).map((r) => r.arguments[0]) : emptyArray; + for (const specifier of specifiers) { + if (pathIsRelative(specifier.text)) { + if (moduleResolutionIsNodeNext && resolutionMode === 1 /* CommonJS */ && getModeForUsageLocation(sourceFile, specifier, compilerOptions) === 99 /* ESNext */) { + continue; + } + if (fileExtensionIsOneOf(specifier.text, extensionsNotSupportingExtensionlessResolution)) { + continue; + } + if (hasTSFileExtension(specifier.text)) { + return 3 /* TsExtension */; + } + if (hasJSFileExtension(specifier.text)) { + usesJsExtensions = true; + } + } + } + return usesJsExtensions ? 2 /* JsExtension */ : 0 /* Minimal */; + } +} +function getRequiresAtTopOfFile(sourceFile) { + let nonRequireStatementCount = 0; + let requires; + for (const statement of sourceFile.statements) { + if (nonRequireStatementCount > 3) { + break; + } + if (isRequireVariableStatement(statement)) { + requires = concatenate(requires, statement.declarationList.declarations.map((d) => d.initializer)); + } else if (isExpressionStatement(statement) && isRequireCall( + statement.expression, + /*requireStringLiteralLikeArgument*/ + true + )) { + requires = append(requires, statement.expression); + } else { + nonRequireStatementCount++; + } + } + return requires || emptyArray; +} +function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { + if (!fileName) return false; + const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (const extension of flatten(getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions))) { + if (fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; +} +function numberOfDirectorySeparators(str) { + const match = str.match(/\//g); + return match ? match.length : 0; +} +function compareNumberOfDirectorySeparators(path1, path2) { + return compareValues( + numberOfDirectorySeparators(path1), + numberOfDirectorySeparators(path2) + ); +} +var extensionsToRemove = [".d.ts" /* Dts */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".mjs" /* Mjs */, ".mts" /* Mts */, ".cjs" /* Cjs */, ".cts" /* Cts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; +function removeFileExtension(path) { + for (const ext of extensionsToRemove) { + const extensionless = tryRemoveExtension(path, ext); + if (extensionless !== void 0) { + return extensionless; + } + } + return path; +} +function tryRemoveExtension(path, extension) { + return fileExtensionIs(path, extension) ? removeExtension(path, extension) : void 0; +} +function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); +} +function changeExtension(path, newExtension) { + return changeAnyExtension( + path, + newExtension, + extensionsToRemove, + /*ignoreCase*/ + false + ); +} +function tryParsePattern(pattern) { + const indexOfStar = pattern.indexOf("*"); + if (indexOfStar === -1) { + return pattern; + } + return pattern.indexOf("*", indexOfStar + 1) !== -1 ? void 0 : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; +} +var parsedPatternsCache = /* @__PURE__ */ new WeakMap(); +function tryParsePatterns(paths) { + let result = parsedPatternsCache.get(paths); + if (result !== void 0) { + return result; + } + let matchableStringSet; + let patterns; + const pathList = getOwnKeys(paths); + for (const path of pathList) { + const patternOrStr = tryParsePattern(path); + if (patternOrStr === void 0) { + continue; + } else if (typeof patternOrStr === "string") { + (matchableStringSet ?? (matchableStringSet = /* @__PURE__ */ new Set())).add(patternOrStr); + } else { + (patterns ?? (patterns = [])).push(patternOrStr); + } + } + parsedPatternsCache.set( + paths, + result = { + matchableStringSet, + patterns + } + ); + return result; +} +function positionIsSynthesized(pos) { + return !(pos >= 0); +} +function extensionIsTS(ext) { + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */ || ext === ".cts" /* Cts */ || ext === ".mts" /* Mts */ || ext === ".d.mts" /* Dmts */ || ext === ".d.cts" /* Dcts */ || startsWith(ext, ".d.") && endsWith(ext, ".ts"); +} +function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; +} +function extensionFromPath(path) { + const ext = tryGetExtensionFromPath2(path); + return ext !== void 0 ? ext : Debug.fail(`File ${path} has unknown extension.`); +} +function tryGetExtensionFromPath2(path) { + return find(extensionsToRemove, (e) => fileExtensionIs(path, e)); +} +function isCheckJsEnabledForFile(sourceFile, compilerOptions) { + return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; +} +var emptyFileSystemEntries = { + files: emptyArray, + directories: emptyArray +}; +function matchPatternOrExact(parsedPatterns, candidate) { + const { matchableStringSet, patterns } = parsedPatterns; + if (matchableStringSet == null ? void 0 : matchableStringSet.has(candidate)) { + return candidate; + } + if (patterns === void 0 || patterns.length === 0) { + return void 0; + } + return findBestPatternMatch(patterns, (_) => _, candidate); +} +function sliceAfter(arr, value) { + const index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); +} +function addRelatedInfo(diagnostic, ...relatedInformation) { + if (!relatedInformation.length) { + return diagnostic; + } + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + Debug.assert(diagnostic.relatedInformation !== emptyArray, "Diagnostic had empty array singleton for related info, but is still being constructed!"); + diagnostic.relatedInformation.push(...relatedInformation); + return diagnostic; +} +function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + let min2 = getValue(arr[0]); + let max = min2; + for (let i = 1; i < arr.length; i++) { + const value = getValue(arr[i]); + if (value < min2) { + min2 = value; + } else if (value > max) { + max = value; + } + } + return { min: min2, max }; +} +function rangeOfNode(node) { + return { pos: getTokenPosOfNode(node), end: node.end }; +} +function rangeOfTypeParameters(sourceFile, typeParameters) { + const pos = typeParameters.pos - 1; + const end = Math.min(sourceFile.text.length, skipTrivia(sourceFile.text, typeParameters.end) + 1); + return { pos, end }; +} +function skipTypeChecking(sourceFile, options, host) { + return skipTypeCheckingWorker( + sourceFile, + options, + host, + /*ignoreNoCheck*/ + false + ); +} +function skipTypeCheckingIgnoringNoCheck(sourceFile, options, host) { + return skipTypeCheckingWorker( + sourceFile, + options, + host, + /*ignoreNoCheck*/ + true + ); +} +function skipTypeCheckingWorker(sourceFile, options, host, ignoreNoCheck) { + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib || !ignoreNoCheck && options.noCheck || host.isSourceOfProjectReferenceRedirect(sourceFile.fileName) || !canIncludeBindAndCheckDiagnostics(sourceFile, options); +} +function canIncludeBindAndCheckDiagnostics(sourceFile, options) { + if (!!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false) return false; + if (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || sourceFile.scriptKind === 5 /* External */) return true; + const isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; + const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options); + const isPlainJs = isPlainJsFile(sourceFile, options.checkJs); + return isPlainJs || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; +} +function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && equalOwnProperties(a, b, isJsonEqual); +} +function parsePseudoBigInt(stringValue) { + let log2Base; + switch (stringValue.charCodeAt(1)) { + // "x" in "0x123" + case 98 /* b */: + case 66 /* B */: + log2Base = 1; + break; + case 111 /* o */: + case 79 /* O */: + log2Base = 3; + break; + case 120 /* x */: + case 88 /* X */: + log2Base = 4; + break; + default: + const nIndex = stringValue.length - 1; + let nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + const startIndex = 2, endIndex = stringValue.length - 1; + const bitsNeeded = (endIndex - startIndex) * log2Base; + const segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + for (let i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + const segment = bitOffset >>> 4; + const digitChar = stringValue.charCodeAt(i); + const digit = digitChar <= 57 /* _9 */ ? digitChar - 48 /* _0 */ : 10 + digitChar - (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */); + const shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + const residual = shiftedDigit >>> 16; + if (residual) segments[segment + 1] |= residual; + } + let base10Value = ""; + let firstNonzeroSegment = segments.length - 1; + let segmentsRemaining = true; + while (segmentsRemaining) { + let mod10 = 0; + segmentsRemaining = false; + for (let segment = firstNonzeroSegment; segment >= 0; segment--) { + const newSegment = mod10 << 16 | segments[segment]; + const segmentValue = newSegment / 10 | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; +} +function pseudoBigIntToString({ negative, base10Value }) { + return (negative && base10Value !== "0" ? "-" : "") + base10Value; +} +function parseValidBigInt(text) { + const negative = text.startsWith("-"); + const base10Value = parsePseudoBigInt(`${negative ? text.slice(1) : text}n`); + return { negative, base10Value }; +} +function isValidBigIntString(s, roundTripOnly) { + if (s === "") return false; + const scanner = createScanner( + 99 /* ESNext */, + /*skipTrivia*/ + false + ); + let success = true; + scanner.setOnError(() => success = false); + scanner.setText(s + "n"); + let result = scanner.scan(); + const negative = result === 41 /* MinusToken */; + if (negative) { + result = scanner.scan(); + } + const flags = scanner.getTokenFlags(); + return success && result === 10 /* BigIntLiteral */ && scanner.getTokenEnd() === s.length + 1 && !(flags & 512 /* ContainsSeparator */) && (!roundTripOnly || s === pseudoBigIntToString({ negative, base10Value: parsePseudoBigInt(scanner.getTokenValue()) })); +} +function isValidTypeOnlyAliasUseSite(useSite) { + return !!(useSite.flags & 33554432 /* Ambient */) || isInJSDoc(useSite) || isPartOfTypeQuery(useSite) || isIdentifierInNonEmittingHeritageClause(useSite) || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite) || !(isExpressionNode(useSite) || isShorthandPropertyNameUseSite(useSite)); +} +function isShorthandPropertyNameUseSite(useSite) { + return isIdentifier(useSite) && isShorthandPropertyAssignment(useSite.parent) && useSite.parent.name === useSite; +} +function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { + while (node.kind === 80 /* Identifier */ || node.kind === 211 /* PropertyAccessExpression */) { + node = node.parent; + } + if (node.kind !== 167 /* ComputedPropertyName */) { + return false; + } + if (hasSyntacticModifier(node.parent, 64 /* Abstract */)) { + return true; + } + const containerKind = node.parent.parent.kind; + return containerKind === 264 /* InterfaceDeclaration */ || containerKind === 187 /* TypeLiteral */; +} +function isIdentifierInNonEmittingHeritageClause(node) { + if (node.kind !== 80 /* Identifier */) return false; + const heritageClause = findAncestor(node.parent, (parent) => { + switch (parent.kind) { + case 298 /* HeritageClause */: + return true; + case 211 /* PropertyAccessExpression */: + case 233 /* ExpressionWithTypeArguments */: + return false; + default: + return "quit"; + } + }); + return (heritageClause == null ? void 0 : heritageClause.token) === 119 /* ImplementsKeyword */ || (heritageClause == null ? void 0 : heritageClause.parent.kind) === 264 /* InterfaceDeclaration */; +} +function isIdentifierTypeReference(node) { + return isTypeReferenceNode(node) && isIdentifier(node.typeName); +} +function arrayIsHomogeneous(array, comparer = equateValues) { + if (array.length < 2) return true; + const first2 = array[0]; + for (let i = 1, length2 = array.length; i < length2; i++) { + const target = array[i]; + if (!comparer(first2, target)) return false; + } + return true; +} +function setTextRangePos(range, pos) { + range.pos = pos; + return range; +} +function setTextRangeEnd(range, end) { + range.end = end; + return range; +} +function setTextRangePosEnd(range, pos, end) { + return setTextRangeEnd(setTextRangePos(range, pos), end); +} +function setTextRangePosWidth(range, pos, width) { + return setTextRangePosEnd(range, pos, pos + width); +} +function setNodeFlags(node, newFlags) { + if (node) { + node.flags = newFlags; + } + return node; +} +function setParent(child, parent) { + if (child && parent) { + child.parent = parent; + } + return child; +} +function setParentRecursive(rootNode, incremental) { + if (!rootNode) return rootNode; + forEachChildRecursively(rootNode, isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild); + return rootNode; + function bindParentToChildIgnoringJSDoc(child, parent) { + if (incremental && child.parent === parent) { + return "skip"; + } + setParent(child, parent); + } + function bindJSDoc(child) { + if (hasJSDocNodes(child)) { + for (const doc of child.jsDoc) { + bindParentToChildIgnoringJSDoc(doc, child); + forEachChildRecursively(doc, bindParentToChildIgnoringJSDoc); + } + } + } + function bindParentToChild(child, parent) { + return bindParentToChildIgnoringJSDoc(child, parent) || bindJSDoc(child); + } +} +function isPackedElement(node) { + return !isOmittedExpression(node); +} +function isPackedArrayLiteral(node) { + return isArrayLiteralExpression(node) && every(node.elements, isPackedElement); +} +function expressionResultIsUnused(node) { + Debug.assertIsDefined(node.parent); + while (true) { + const parent = node.parent; + if (isParenthesizedExpression(parent)) { + node = parent; + continue; + } + if (isExpressionStatement(parent) || isVoidExpression(parent) || isForStatement(parent) && (parent.initializer === node || parent.incrementor === node)) { + return true; + } + if (isCommaListExpression(parent)) { + if (node !== last(parent.elements)) return true; + node = parent; + continue; + } + if (isBinaryExpression(parent) && parent.operatorToken.kind === 28 /* CommaToken */) { + if (node === parent.left) return true; + node = parent; + continue; + } + return false; + } +} +function containsIgnoredPath(path) { + return some(ignoredPaths, (p) => path.includes(p)); +} +function getContainingNodeArray(node) { + if (!node.parent) return void 0; + switch (node.kind) { + case 168 /* TypeParameter */: + const { parent: parent2 } = node; + return parent2.kind === 195 /* InferType */ ? void 0 : parent2.typeParameters; + case 169 /* Parameter */: + return node.parent.parameters; + case 204 /* TemplateLiteralTypeSpan */: + return node.parent.templateSpans; + case 239 /* TemplateSpan */: + return node.parent.templateSpans; + case 170 /* Decorator */: { + const { parent: parent3 } = node; + return canHaveDecorators(parent3) ? parent3.modifiers : void 0; + } + case 298 /* HeritageClause */: + return node.parent.heritageClauses; + } + const { parent } = node; + if (isJSDocTag(node)) { + return isJSDocTypeLiteral(node.parent) ? void 0 : node.parent.tags; + } + switch (parent.kind) { + case 187 /* TypeLiteral */: + case 264 /* InterfaceDeclaration */: + return isTypeElement(node) ? parent.members : void 0; + case 192 /* UnionType */: + case 193 /* IntersectionType */: + return parent.types; + case 189 /* TupleType */: + case 209 /* ArrayLiteralExpression */: + case 356 /* CommaListExpression */: + case 275 /* NamedImports */: + case 279 /* NamedExports */: + return parent.elements; + case 210 /* ObjectLiteralExpression */: + case 292 /* JsxAttributes */: + return parent.properties; + case 213 /* CallExpression */: + case 214 /* NewExpression */: + return isTypeNode(node) ? parent.typeArguments : parent.expression === node ? void 0 : parent.arguments; + case 284 /* JsxElement */: + case 288 /* JsxFragment */: + return isJsxChild(node) ? parent.children : void 0; + case 286 /* JsxOpeningElement */: + case 285 /* JsxSelfClosingElement */: + return isTypeNode(node) ? parent.typeArguments : void 0; + case 241 /* Block */: + case 296 /* CaseClause */: + case 297 /* DefaultClause */: + case 268 /* ModuleBlock */: + return parent.statements; + case 269 /* CaseBlock */: + return parent.clauses; + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + return isClassElement(node) ? parent.members : void 0; + case 266 /* EnumDeclaration */: + return isEnumMember(node) ? parent.members : void 0; + case 307 /* SourceFile */: + return parent.statements; + } +} +function hasContextSensitiveParameters(node) { + if (!node.typeParameters) { + if (some(node.parameters, (p) => !getEffectiveTypeAnnotationNode(p))) { + return true; + } + if (node.kind !== 219 /* ArrowFunction */) { + const parameter = firstOrUndefined(node.parameters); + if (!(parameter && parameterIsThisKeyword(parameter))) { + return true; + } + } + } + return false; +} +function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; +} +function isCatchClauseVariableDeclaration(node) { + return node.kind === 260 /* VariableDeclaration */ && node.parent.kind === 299 /* CatchClause */; +} +function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 218 /* FunctionExpression */ || node.kind === 219 /* ArrowFunction */; +} +function isNumericLiteralName(name) { + return (+name).toString() === name; +} +function createPropertyNameNodeForIdentifierOrLiteral(name, target, singleQuote, stringNamed, isMethod) { + const isMethodNamedNew = isMethod && name === "new"; + return !isMethodNamedNew && isIdentifierText(name, target) ? factory.createIdentifier(name) : !stringNamed && !isMethodNamedNew && isNumericLiteralName(name) && +name >= 0 ? factory.createNumericLiteral(+name) : factory.createStringLiteral(name, !!singleQuote); +} +function isThisTypeParameter(type) { + return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType); +} +function getNodeModulePathParts(fullPath) { + let topLevelNodeModulesIndex = 0; + let topLevelPackageNameIndex = 0; + let packageRootIndex = 0; + let fileNameIndex = 0; + let States; + ((States2) => { + States2[States2["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States2[States2["NodeModules"] = 1] = "NodeModules"; + States2[States2["Scope"] = 2] = "Scope"; + States2[States2["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + let partStart = 0; + let partEnd = 0; + let state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) { + state = 1 /* NodeModules */; + } else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : void 0; +} +function isTypeDeclaration(node) { + switch (node.kind) { + case 168 /* TypeParameter */: + case 263 /* ClassDeclaration */: + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 266 /* EnumDeclaration */: + case 346 /* JSDocTypedefTag */: + case 338 /* JSDocCallbackTag */: + case 340 /* JSDocEnumTag */: + return true; + case 273 /* ImportClause */: + return node.isTypeOnly; + case 276 /* ImportSpecifier */: + case 281 /* ExportSpecifier */: + return node.parent.parent.isTypeOnly; + default: + return false; + } +} +function canHaveExportModifier(node) { + return isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isInterfaceDeclaration(node) || isTypeDeclaration(node) || isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node); +} +function isOptionalJSDocPropertyLikeTag(node) { + if (!isJSDocPropertyLikeTag(node)) { + return false; + } + const { isBracketed, typeExpression } = node; + return isBracketed || !!typeExpression && typeExpression.type.kind === 316 /* JSDocOptionalType */; +} +function canUsePropertyAccess(name, languageVersion) { + if (name.length === 0) { + return false; + } + const firstChar = name.charCodeAt(0); + return firstChar === 35 /* hash */ ? name.length > 1 && isIdentifierStart(name.charCodeAt(1), languageVersion) : isIdentifierStart(firstChar, languageVersion); +} +function isJSDocOptionalParameter(node) { + return isInJSFile(node) && // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + (node.type && node.type.kind === 316 /* JSDocOptionalType */ || getJSDocParameterTags(node).some(isOptionalJSDocPropertyLikeTag)); +} +function isOptionalDeclaration(declaration) { + switch (declaration.kind) { + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + return !!declaration.questionToken; + case 169 /* Parameter */: + return !!declaration.questionToken || isJSDocOptionalParameter(declaration); + case 348 /* JSDocPropertyTag */: + case 341 /* JSDocParameterTag */: + return isOptionalJSDocPropertyLikeTag(declaration); + default: + return false; + } +} +function isNonNullAccess(node) { + const kind = node.kind; + return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */) && isNonNullExpression(node.expression); +} +function isJSDocSatisfiesExpression(node) { + return isInJSFile(node) && isParenthesizedExpression(node) && hasJSDocNodes(node) && !!getJSDocSatisfiesTag(node); +} +function getJSDocSatisfiesExpressionType(node) { + return Debug.checkDefined(tryGetJSDocSatisfiesTypeNode(node)); +} +function tryGetJSDocSatisfiesTypeNode(node) { + const tag = getJSDocSatisfiesTag(node); + return tag && tag.typeExpression && tag.typeExpression.type; +} +function getEscapedTextOfJsxAttributeName(node) { + return isIdentifier(node) ? node.escapedText : getEscapedTextOfJsxNamespacedName(node); +} +function getTextOfJsxAttributeName(node) { + return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node); +} +function isJsxAttributeName(node) { + const kind = node.kind; + return kind === 80 /* Identifier */ || kind === 295 /* JsxNamespacedName */; +} +function getEscapedTextOfJsxNamespacedName(node) { + return `${node.namespace.escapedText}:${idText(node.name)}`; +} +function getTextOfJsxNamespacedName(node) { + return `${idText(node.namespace)}:${idText(node.name)}`; +} +function intrinsicTagNameToString(node) { + return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node); +} +function isTypeUsableAsPropertyName(type) { + return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); +} +function getPropertyNameFromType(type) { + if (type.flags & 8192 /* UniqueESSymbol */) { + return type.escapedName; + } + if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + return escapeLeadingUnderscores("" + type.value); + } + return Debug.fail(); +} +function isExpandoPropertyDeclaration(declaration) { + return !!declaration && (isPropertyAccessExpression(declaration) || isElementAccessExpression(declaration) || isBinaryExpression(declaration)); +} +function hasResolutionModeOverride(node) { + if (node === void 0) { + return false; + } + return !!getResolutionModeOverride(node.attributes); +} +var stringReplace = String.prototype.replace; +function replaceFirstStar(s, replacement) { + return stringReplace.call(s, "*", replacement); +} +function getNameFromImportAttribute(node) { + return isIdentifier(node.name) ? node.name.escapedText : escapeLeadingUnderscores(node.name.text); +} +function evaluatorResult(value, isSyntacticallyString = false, resolvedOtherFiles = false, hasExternalReferences = false) { + return { value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences }; +} +function createEvaluator({ evaluateElementAccessExpression, evaluateEntityNameExpression }) { + function evaluate(expr, location) { + let isSyntacticallyString = false; + let resolvedOtherFiles = false; + let hasExternalReferences = false; + expr = skipParentheses(expr); + switch (expr.kind) { + case 224 /* PrefixUnaryExpression */: + const result = evaluate(expr.operand, location); + resolvedOtherFiles = result.resolvedOtherFiles; + hasExternalReferences = result.hasExternalReferences; + if (typeof result.value === "number") { + switch (expr.operator) { + case 40 /* PlusToken */: + return evaluatorResult(result.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 41 /* MinusToken */: + return evaluatorResult(-result.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 55 /* TildeToken */: + return evaluatorResult(~result.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + } + } + break; + case 226 /* BinaryExpression */: { + const left = evaluate(expr.left, location); + const right = evaluate(expr.right, location); + isSyntacticallyString = (left.isSyntacticallyString || right.isSyntacticallyString) && expr.operatorToken.kind === 40 /* PlusToken */; + resolvedOtherFiles = left.resolvedOtherFiles || right.resolvedOtherFiles; + hasExternalReferences = left.hasExternalReferences || right.hasExternalReferences; + if (typeof left.value === "number" && typeof right.value === "number") { + switch (expr.operatorToken.kind) { + case 52 /* BarToken */: + return evaluatorResult(left.value | right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 51 /* AmpersandToken */: + return evaluatorResult(left.value & right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 49 /* GreaterThanGreaterThanToken */: + return evaluatorResult(left.value >> right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 50 /* GreaterThanGreaterThanGreaterThanToken */: + return evaluatorResult(left.value >>> right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 48 /* LessThanLessThanToken */: + return evaluatorResult(left.value << right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 53 /* CaretToken */: + return evaluatorResult(left.value ^ right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 42 /* AsteriskToken */: + return evaluatorResult(left.value * right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 44 /* SlashToken */: + return evaluatorResult(left.value / right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 40 /* PlusToken */: + return evaluatorResult(left.value + right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 41 /* MinusToken */: + return evaluatorResult(left.value - right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 45 /* PercentToken */: + return evaluatorResult(left.value % right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + case 43 /* AsteriskAsteriskToken */: + return evaluatorResult(left.value ** right.value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences); + } + } else if ((typeof left.value === "string" || typeof left.value === "number") && (typeof right.value === "string" || typeof right.value === "number") && expr.operatorToken.kind === 40 /* PlusToken */) { + return evaluatorResult( + "" + left.value + right.value, + isSyntacticallyString, + resolvedOtherFiles, + hasExternalReferences + ); + } + break; + } + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + return evaluatorResult( + expr.text, + /*isSyntacticallyString*/ + true + ); + case 228 /* TemplateExpression */: + return evaluateTemplateExpression(expr, location); + case 9 /* NumericLiteral */: + return evaluatorResult(+expr.text); + case 80 /* Identifier */: + return evaluateEntityNameExpression(expr, location); + case 211 /* PropertyAccessExpression */: + if (isEntityNameExpression(expr)) { + return evaluateEntityNameExpression(expr, location); + } + break; + case 212 /* ElementAccessExpression */: + return evaluateElementAccessExpression(expr, location); + } + return evaluatorResult( + /*value*/ + void 0, + isSyntacticallyString, + resolvedOtherFiles, + hasExternalReferences + ); + } + function evaluateTemplateExpression(expr, location) { + let result = expr.head.text; + let resolvedOtherFiles = false; + let hasExternalReferences = false; + for (const span of expr.templateSpans) { + const spanResult = evaluate(span.expression, location); + if (spanResult.value === void 0) { + return evaluatorResult( + /*value*/ + void 0, + /*isSyntacticallyString*/ + true + ); + } + result += spanResult.value; + result += span.literal.text; + resolvedOtherFiles || (resolvedOtherFiles = spanResult.resolvedOtherFiles); + hasExternalReferences || (hasExternalReferences = spanResult.hasExternalReferences); + } + return evaluatorResult( + result, + /*isSyntacticallyString*/ + true, + resolvedOtherFiles, + hasExternalReferences + ); + } + return evaluate; +} +function isConstAssertion(location) { + return isAssertionExpression(location) && isConstTypeReference(location.type) || isJSDocTypeTag(location) && isConstTypeReference(location.typeExpression); +} +function findConstructorDeclaration(node) { + const members = node.members; + for (const member of members) { + if (member.kind === 176 /* Constructor */ && nodeIsPresent(member.body)) { + return member; + } + } +} +function createNameResolver({ + compilerOptions, + requireSymbol, + argumentsSymbol, + error, + getSymbolOfDeclaration, + globals, + lookup, + setRequiresScopeChangeCache = returnUndefined, + getRequiresScopeChangeCache = returnUndefined, + onPropertyWithInvalidInitializer = returnFalse, + onFailedToResolveSymbol = returnUndefined, + onSuccessfullyResolvedSymbol = returnUndefined +}) { + var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules"; + var emitStandardClassFields = getEmitStandardClassFields(compilerOptions); + var emptySymbols = createSymbolTable(); + return resolveNameHelper; + function resolveNameHelper(location, nameArg, meaning, nameNotFoundMessage, isUse, excludeGlobals) { + var _a, _b, _c; + const originalLocation = location; + let result; + let lastLocation; + let lastSelfReferenceLocation; + let propertyWithInvalidInitializer; + let associatedDeclarationForContainingInitializerOrBindingName; + let withinDeferredContext = false; + let grandparent; + const name = isString(nameArg) ? nameArg : nameArg.escapedText; + loop: + while (location) { + if (name === "const" && isConstAssertion(location)) { + return void 0; + } + if (isModuleOrEnumDeclaration(location) && lastLocation && location.name === lastLocation) { + lastLocation = location; + location = location.parent; + } + if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { + if (result = lookup(location.locals, name, meaning)) { + let useResult = true; + if (isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 320 /* JSDoc */) { + useResult = result.flags & 262144 /* TypeParameter */ ? !!(lastLocation.flags & 16 /* Synthesized */) || // Synthetic fake scopes are added for signatures so type parameters are accessible from them + lastLocation === location.type || lastLocation.kind === 169 /* Parameter */ || lastLocation.kind === 341 /* JSDocParameterTag */ || lastLocation.kind === 342 /* JSDocReturnTag */ || lastLocation.kind === 168 /* TypeParameter */ : false; + } + if (meaning & result.flags & 3 /* Variable */) { + if (useOuterVariableScopeInParameter(result, location, lastLocation)) { + useResult = false; + } else if (result.flags & 1 /* FunctionScopedVariable */) { + useResult = lastLocation.kind === 169 /* Parameter */ || !!(lastLocation.flags & 16 /* Synthesized */) || // Synthetic fake scopes are added for signatures so parameters are accessible from them + lastLocation === location.type && !!findAncestor(result.valueDeclaration, isParameter); + } + } + } else if (location.kind === 194 /* ConditionalType */) { + useResult = lastLocation === location.trueType; + } + if (useResult) { + break loop; + } else { + result = void 0; + } + } + } + withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); + switch (location.kind) { + case 307 /* SourceFile */: + if (!isExternalOrCommonJsModule(location)) break; + // falls through + case 267 /* ModuleDeclaration */: + const moduleExports = ((_a = getSymbolOfDeclaration(location)) == null ? void 0 : _a.exports) || emptySymbols; + if (location.kind === 307 /* SourceFile */ || isModuleDeclaration(location) && location.flags & 33554432 /* Ambient */ && !isGlobalScopeAugmentation(location)) { + if (result = moduleExports.get("default" /* Default */)) { + const localSymbol = getLocalSymbolForExportDefault(result); + if (localSymbol && result.flags & meaning && localSymbol.escapedName === name) { + break loop; + } + result = void 0; + } + const moduleExport = moduleExports.get(name); + if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && (getDeclarationOfKind(moduleExport, 281 /* ExportSpecifier */) || getDeclarationOfKind(moduleExport, 280 /* NamespaceExport */))) { + break; + } + } + if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { + if (isSourceFile(location) && location.commonJsModuleIndicator && !((_b = result.declarations) == null ? void 0 : _b.some(isJSDocTypeAlias))) { + result = void 0; + } else { + break loop; + } + } + break; + case 266 /* EnumDeclaration */: + if (result = lookup(((_c = getSymbolOfDeclaration(location)) == null ? void 0 : _c.exports) || emptySymbols, name, meaning & 8 /* EnumMember */)) { + if (nameNotFoundMessage && getIsolatedModules(compilerOptions) && !(location.flags & 33554432 /* Ambient */) && getSourceFileOfNode(location) !== getSourceFileOfNode(result.valueDeclaration)) { + error( + originalLocation, + Diagnostics.Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead, + unescapeLeadingUnderscores(name), + isolatedModulesLikeFlagName, + `${unescapeLeadingUnderscores(getSymbolOfDeclaration(location).escapedName)}.${unescapeLeadingUnderscores(name)}` + ); + } + break loop; + } + break; + case 172 /* PropertyDeclaration */: + if (!isStatic(location)) { + const ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) { + Debug.assertNode(location, isPropertyDeclaration); + propertyWithInvalidInitializer = location; + } + } + } + break; + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 264 /* InterfaceDeclaration */: + if (result = lookup(getSymbolOfDeclaration(location).members || emptySymbols, name, meaning & 788968 /* Type */)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + result = void 0; + break; + } + if (lastLocation && isStatic(lastLocation)) { + if (nameNotFoundMessage) { + error(originalLocation, Diagnostics.Static_members_cannot_reference_class_type_parameters); + } + return void 0; + } + break loop; + } + if (isClassExpression(location) && meaning & 32 /* Class */) { + const className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 233 /* ExpressionWithTypeArguments */: + if (lastLocation === location.expression && location.parent.token === 96 /* ExtendsKeyword */) { + const container = location.parent.parent; + if (isClassLike(container) && (result = lookup(getSymbolOfDeclaration(container).members, name, meaning & 788968 /* Type */))) { + if (nameNotFoundMessage) { + error(originalLocation, Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return void 0; + } + } + break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 167 /* ComputedPropertyName */: + grandparent = location.parent.parent; + if (isClassLike(grandparent) || grandparent.kind === 264 /* InterfaceDeclaration */) { + if (result = lookup(getSymbolOfDeclaration(grandparent).members, name, meaning & 788968 /* Type */)) { + if (nameNotFoundMessage) { + error(originalLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + } + return void 0; + } + } + break; + case 219 /* ArrowFunction */: + if (getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */) { + break; + } + // falls through + case 174 /* MethodDeclaration */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 262 /* FunctionDeclaration */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 218 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + const functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 170 /* Decorator */: + if (location.parent && location.parent.kind === 169 /* Parameter */) { + location = location.parent; + } + if (location.parent && (isClassElement(location.parent) || location.parent.kind === 263 /* ClassDeclaration */)) { + location = location.parent; + } + break; + case 346 /* JSDocTypedefTag */: + case 338 /* JSDocCallbackTag */: + case 340 /* JSDocEnumTag */: + case 351 /* JSDocImportTag */: + const root = getJSDocRoot(location); + if (root) { + location = root.parent; + } + break; + case 169 /* Parameter */: + if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) { + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } + } + break; + case 208 /* BindingElement */: + if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) { + if (isPartOfParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } + } + break; + case 195 /* InferType */: + if (meaning & 262144 /* TypeParameter */) { + const parameterName = location.typeParameter.name; + if (parameterName && name === parameterName.escapedText) { + result = location.typeParameter.symbol; + break loop; + } + } + break; + case 281 /* ExportSpecifier */: + if (lastLocation && lastLocation === location.propertyName && location.parent.parent.moduleSpecifier) { + location = location.parent.parent.parent; + } + break; + } + if (isSelfReferenceLocation(location, lastLocation)) { + lastSelfReferenceLocation = location; + } + lastLocation = location; + location = isJSDocTemplateTag(location) ? getEffectiveContainerForJSDocTemplateTag(location) || location.parent : isJSDocParameterTag(location) || isJSDocReturnTag(location) ? getHostSignatureFromJSDoc(location) || location.parent : location.parent; + } + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + result.isReferenced |= meaning; + } + if (!result) { + if (lastLocation) { + Debug.assertNode(lastLocation, isSourceFile); + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { + return lastLocation.symbol; + } + } + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } + } + if (!result) { + if (originalLocation && isInJSFile(originalLocation) && originalLocation.parent) { + if (isRequireCall( + originalLocation.parent, + /*requireStringLiteralLikeArgument*/ + false + )) { + return requireSymbol; + } + } + } + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer && onPropertyWithInvalidInitializer(originalLocation, name, propertyWithInvalidInitializer, result)) { + return void 0; + } + if (!result) { + onFailedToResolveSymbol(originalLocation, nameArg, meaning, nameNotFoundMessage); + } else { + onSuccessfullyResolvedSymbol(originalLocation, result, meaning, lastLocation, associatedDeclarationForContainingInitializerOrBindingName, withinDeferredContext); + } + } + return result; + } + function useOuterVariableScopeInParameter(result, location, lastLocation) { + const target = getEmitScriptTarget(compilerOptions); + const functionLocation = location; + if (isParameter(lastLocation) && functionLocation.body && result.valueDeclaration && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (target >= 2 /* ES2015 */) { + let declarationRequiresScopeChange = getRequiresScopeChangeCache(functionLocation); + if (declarationRequiresScopeChange === void 0) { + declarationRequiresScopeChange = forEach(functionLocation.parameters, requiresScopeChange) || false; + setRequiresScopeChangeCache(functionLocation, declarationRequiresScopeChange); + } + return !declarationRequiresScopeChange; + } + } + return false; + function requiresScopeChange(node) { + return requiresScopeChangeWorker(node.name) || !!node.initializer && requiresScopeChangeWorker(node.initializer); + } + function requiresScopeChangeWorker(node) { + switch (node.kind) { + case 219 /* ArrowFunction */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 176 /* Constructor */: + return false; + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 303 /* PropertyAssignment */: + return requiresScopeChangeWorker(node.name); + case 172 /* PropertyDeclaration */: + if (hasStaticModifier(node)) { + return !emitStandardClassFields; + } + return requiresScopeChangeWorker(node.name); + default: + if (isNullishCoalesce(node) || isOptionalChain(node)) { + return target < 7 /* ES2020 */; + } + if (isBindingElement(node) && node.dotDotDotToken && isObjectBindingPattern(node.parent)) { + return target < 4 /* ES2017 */; + } + if (isTypeNode(node)) return false; + return forEachChild(node, requiresScopeChangeWorker) || false; + } + } + } + function getIsDeferredContext(location, lastLocation) { + if (location.kind !== 219 /* ArrowFunction */ && location.kind !== 218 /* FunctionExpression */) { + return isTypeQueryNode(location) || (isFunctionLikeDeclaration(location) || location.kind === 172 /* PropertyDeclaration */ && !isStatic(location)) && (!lastLocation || lastLocation !== location.name); + } + if (lastLocation && lastLocation === location.name) { + return false; + } + if (location.asteriskToken || hasSyntacticModifier(location, 1024 /* Async */)) { + return true; + } + return !getImmediatelyInvokedFunctionExpression(location); + } + function isSelfReferenceLocation(node, lastLocation) { + switch (node.kind) { + case 169 /* Parameter */: + return !!lastLocation && lastLocation === node.name; + case 262 /* FunctionDeclaration */: + case 263 /* ClassDeclaration */: + case 264 /* InterfaceDeclaration */: + case 266 /* EnumDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 267 /* ModuleDeclaration */: + return true; + default: + return false; + } + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + if (symbol.declarations) { + for (const decl of symbol.declarations) { + if (decl.kind === 168 /* TypeParameter */) { + const parent = isJSDocTemplateTag(decl.parent) ? getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(isJSDocTemplateTag(decl.parent) && find(decl.parent.parent.tags, isJSDocTypeAlias)); + } + } + } + } + return false; + } +} +function isPrimitiveLiteralValue(node, includeBigInt = true) { + Debug.type(node); + switch (node.kind) { + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 9 /* NumericLiteral */: + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + return true; + case 10 /* BigIntLiteral */: + return includeBigInt; + case 224 /* PrefixUnaryExpression */: + if (node.operator === 41 /* MinusToken */) { + return isNumericLiteral(node.operand) || includeBigInt && isBigIntLiteral(node.operand); + } + if (node.operator === 40 /* PlusToken */) { + return isNumericLiteral(node.operand); + } + return false; + default: + assertType(node); + return false; + } +} +function unwrapParenthesizedExpression(o) { + while (o.kind === 217 /* ParenthesizedExpression */) { + o = o.expression; + } + return o; +} +function hasInferredType(node) { + Debug.type(node); + switch (node.kind) { + case 169 /* Parameter */: + case 171 /* PropertySignature */: + case 172 /* PropertyDeclaration */: + case 208 /* BindingElement */: + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + case 226 /* BinaryExpression */: + case 260 /* VariableDeclaration */: + case 277 /* ExportAssignment */: + case 303 /* PropertyAssignment */: + case 304 /* ShorthandPropertyAssignment */: + case 341 /* JSDocParameterTag */: + case 348 /* JSDocPropertyTag */: + return true; + default: + assertType(node); + return false; + } +} +function isSideEffectImport(node) { + const ancestor = findAncestor(node, isImportDeclaration); + return !!ancestor && !ancestor.importClause; +} +var unprefixedNodeCoreModulesList = [ + "assert", + "assert/strict", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "diagnostics_channel", + "dns", + "dns/promises", + "domain", + "events", + "fs", + "fs/promises", + "http", + "http2", + "https", + "inspector", + "inspector/promises", + "module", + "net", + "os", + "path", + "path/posix", + "path/win32", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "readline/promises", + "repl", + "stream", + "stream/consumers", + "stream/promises", + "stream/web", + "string_decoder", + "sys", + "test/mock_loader", + "timers", + "timers/promises", + "tls", + "trace_events", + "tty", + "url", + "util", + "util/types", + "v8", + "vm", + "wasi", + "worker_threads", + "zlib" +]; +var unprefixedNodeCoreModules = new Set(unprefixedNodeCoreModulesList); +var exclusivelyPrefixedNodeCoreModules = /* @__PURE__ */ new Set([ + "node:sea", + "node:sqlite", + "node:test", + "node:test/reporters" +]); +var nodeCoreModules = /* @__PURE__ */ new Set([ + ...unprefixedNodeCoreModulesList, + ...unprefixedNodeCoreModulesList.map((name) => `node:${name}`), + ...exclusivelyPrefixedNodeCoreModules +]); +function forEachDynamicImportOrRequireCall(file, includeTypeSpaceImports, requireStringLiteralLikeArgument, cb) { + const isJavaScriptFile = isInJSFile(file); + const r = /import|require/g; + while (r.exec(file.text) !== null) { + const node = getNodeAtPosition( + file, + r.lastIndex, + /*includeJSDoc*/ + includeTypeSpaceImports + ); + if (isJavaScriptFile && isRequireCall(node, requireStringLiteralLikeArgument)) { + cb(node, node.arguments[0]); + } else if (isImportCall(node) && node.arguments.length >= 1 && (!requireStringLiteralLikeArgument || isStringLiteralLike(node.arguments[0]))) { + cb(node, node.arguments[0]); + } else if (includeTypeSpaceImports && isLiteralImportTypeNode(node)) { + cb(node, node.argument.literal); + } else if (includeTypeSpaceImports && isJSDocImportTag(node)) { + const moduleNameExpr = getExternalModuleName(node); + if (moduleNameExpr && isStringLiteral(moduleNameExpr) && moduleNameExpr.text) { + cb(node, moduleNameExpr); + } + } + } +} +function getNodeAtPosition(sourceFile, position, includeJSDoc) { + const isJavaScriptFile = isInJSFile(sourceFile); + let current = sourceFile; + const getContainingChild = (child) => { + if (child.pos <= position && (position < child.end || position === child.end && child.kind === 1 /* EndOfFileToken */)) { + return child; + } + }; + while (true) { + const child = isJavaScriptFile && includeJSDoc && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } +} +function isNewScopeNode(node) { + return isFunctionLike(node) || isJSDocSignature(node) || isMappedTypeNode(node); +} +function getLibNameFromLibReference(libReference) { + return toFileNameLowerCase(libReference.fileName); +} +function getLibFileNameFromLibReference(libReference) { + const libName = getLibNameFromLibReference(libReference); + return libMap.get(libName); +} +function forEachResolvedProjectReference(resolvedProjectReferences, cb) { + return forEachProjectReference( + /*projectReferences*/ + void 0, + resolvedProjectReferences, + (resolvedRef, parent) => resolvedRef && cb(resolvedRef, parent) + ); +} +function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { + let seenResolvedRefs; + return worker( + projectReferences, + resolvedProjectReferences, + /*parent*/ + void 0 + ); + function worker(projectReferences2, resolvedProjectReferences2, parent) { + if (cbRef) { + const result = cbRef(projectReferences2, parent); + if (result) return result; + } + let skipChildren; + return forEach( + resolvedProjectReferences2, + (resolvedRef, index) => { + if (resolvedRef && (seenResolvedRefs == null ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) { + (skipChildren ?? (skipChildren = /* @__PURE__ */ new Set())).add(resolvedRef); + return void 0; + } + const result = cbResolvedRef(resolvedRef, parent, index); + if (result || !resolvedRef) return result; + (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Set())).add(resolvedRef.sourceFile.path); + } + ) || forEach( + resolvedProjectReferences2, + (resolvedRef) => resolvedRef && !(skipChildren == null ? void 0 : skipChildren.has(resolvedRef)) ? worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef) : void 0 + ); + } +} +function getOptionsSyntaxByArrayElementValue(optionsObject, name, value) { + return optionsObject && getPropertyArrayElementValue(optionsObject, name, value); +} +function getPropertyArrayElementValue(objectLiteral, propKey, elementValue) { + return forEachPropertyAssignment(objectLiteral, propKey, (property) => isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element) => isStringLiteral(element) && element.text === elementValue) : void 0); +} +function getOptionsSyntaxByValue(optionsObject, name, value) { + return forEachOptionsSyntaxByName(optionsObject, name, (property) => isStringLiteral(property.initializer) && property.initializer.text === value ? property.initializer : void 0); +} +function forEachOptionsSyntaxByName(optionsObject, name, callback) { + return forEachPropertyAssignment(optionsObject, name, callback); +} + +// src/compiler/factory/baseNodeFactory.ts +function createBaseNodeFactory() { + let NodeConstructor2; + let TokenConstructor2; + let IdentifierConstructor2; + let PrivateIdentifierConstructor2; + let SourceFileConstructor2; + return { + createBaseSourceFileNode, + createBaseIdentifierNode, + createBasePrivateIdentifierNode, + createBaseTokenNode, + createBaseNode + }; + function createBaseSourceFileNode(kind) { + return new (SourceFileConstructor2 || (SourceFileConstructor2 = objectAllocator.getSourceFileConstructor()))( + kind, + /*pos*/ + -1, + /*end*/ + -1 + ); + } + function createBaseIdentifierNode(kind) { + return new (IdentifierConstructor2 || (IdentifierConstructor2 = objectAllocator.getIdentifierConstructor()))( + kind, + /*pos*/ + -1, + /*end*/ + -1 + ); + } + function createBasePrivateIdentifierNode(kind) { + return new (PrivateIdentifierConstructor2 || (PrivateIdentifierConstructor2 = objectAllocator.getPrivateIdentifierConstructor()))( + kind, + /*pos*/ + -1, + /*end*/ + -1 + ); + } + function createBaseTokenNode(kind) { + return new (TokenConstructor2 || (TokenConstructor2 = objectAllocator.getTokenConstructor()))( + kind, + /*pos*/ + -1, + /*end*/ + -1 + ); + } + function createBaseNode(kind) { + return new (NodeConstructor2 || (NodeConstructor2 = objectAllocator.getNodeConstructor()))( + kind, + /*pos*/ + -1, + /*end*/ + -1 + ); + } +} + +// src/compiler/factory/parenthesizerRules.ts +function createParenthesizerRules(factory2) { + let binaryLeftOperandParenthesizerCache; + let binaryRightOperandParenthesizerCache; + return { + getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator, + parenthesizeLeftSideOfBinary, + parenthesizeRightSideOfBinary, + parenthesizeExpressionOfComputedPropertyName, + parenthesizeConditionOfConditionalExpression, + parenthesizeBranchOfConditionalExpression, + parenthesizeExpressionOfExportDefault, + parenthesizeExpressionOfNew, + parenthesizeLeftSideOfAccess, + parenthesizeOperandOfPostfixUnary, + parenthesizeOperandOfPrefixUnary, + parenthesizeExpressionsOfCommaDelimitedList, + parenthesizeExpressionForDisallowedComma, + parenthesizeExpressionOfExpressionStatement, + parenthesizeConciseBodyOfArrowFunction, + parenthesizeCheckTypeOfConditionalType, + parenthesizeExtendsTypeOfConditionalType, + parenthesizeConstituentTypesOfUnionType, + parenthesizeConstituentTypeOfUnionType, + parenthesizeConstituentTypesOfIntersectionType, + parenthesizeConstituentTypeOfIntersectionType, + parenthesizeOperandOfTypeOperator, + parenthesizeOperandOfReadonlyTypeOperator, + parenthesizeNonArrayTypeOfPostfixType, + parenthesizeElementTypesOfTupleType, + parenthesizeElementTypeOfTupleType, + parenthesizeTypeOfOptionalType, + parenthesizeTypeArguments, + parenthesizeLeadingTypeArgument + }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = /* @__PURE__ */ new Map()); + let parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = (node) => parenthesizeLeftSideOfBinary(operatorKind, node); + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = /* @__PURE__ */ new Map()); + let parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = (node) => parenthesizeRightSideOfBinary( + operatorKind, + /*leftSide*/ + void 0, + node + ); + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + const binaryOperatorPrecedence = getOperatorPrecedence(226 /* BinaryExpression */, binaryOperator); + const binaryOperatorAssociativity = getOperatorAssociativity(226 /* BinaryExpression */, binaryOperator); + const emittedOperand = skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 219 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { + return true; + } + const operandPrecedence = getExpressionPrecedence(emittedOperand); + switch (compareValues(operandPrecedence, binaryOperatorPrecedence)) { + case -1 /* LessThan */: + if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ && operand.kind === 229 /* YieldExpression */) { + return false; + } + return true; + case 1 /* GreaterThan */: + return false; + case 0 /* EqualTo */: + if (isLeftSideOfBinary) { + return binaryOperatorAssociativity === 1 /* Right */; + } else { + if (isBinaryExpression(emittedOperand) && emittedOperand.operatorToken.kind === binaryOperator) { + if (operatorHasAssociativeProperty(binaryOperator)) { + return false; + } + if (binaryOperator === 40 /* PlusToken */) { + const leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */; + if (isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + return false; + } + } + } + const operandAssociativity = getExpressionAssociativity(emittedOperand); + return operandAssociativity === 0 /* Left */; + } + } + } + function operatorHasAssociativeProperty(binaryOperator) { + return binaryOperator === 42 /* AsteriskToken */ || binaryOperator === 52 /* BarToken */ || binaryOperator === 51 /* AmpersandToken */ || binaryOperator === 53 /* CaretToken */ || binaryOperator === 28 /* CommaToken */; + } + function getLiteralKindOfBinaryPlusOperand(node) { + node = skipPartiallyEmittedExpressions(node); + if (isLiteralKind(node.kind)) { + return node.kind; + } + if (node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 40 /* PlusToken */) { + if (node.cachedLiteralKind !== void 0) { + return node.cachedLiteralKind; + } + const leftKind = getLiteralKindOfBinaryPlusOperand(node.left); + const literalKind = isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind : 0 /* Unknown */; + node.cachedLiteralKind = literalKind; + return literalKind; + } + return 0 /* Unknown */; + } + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { + const skipped = skipPartiallyEmittedExpressions(operand); + if (skipped.kind === 217 /* ParenthesizedExpression */) { + return operand; + } + return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) ? factory2.createParenthesizedExpression(operand) : operand; + } + function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) { + return parenthesizeBinaryOperand( + binaryOperator, + leftSide, + /*isLeftSideOfBinary*/ + true + ); + } + function parenthesizeRightSideOfBinary(binaryOperator, leftSide, rightSide) { + return parenthesizeBinaryOperand( + binaryOperator, + rightSide, + /*isLeftSideOfBinary*/ + false, + leftSide + ); + } + function parenthesizeExpressionOfComputedPropertyName(expression) { + return isCommaSequence(expression) ? factory2.createParenthesizedExpression(expression) : expression; + } + function parenthesizeConditionOfConditionalExpression(condition) { + const conditionalPrecedence = getOperatorPrecedence(227 /* ConditionalExpression */, 58 /* QuestionToken */); + const emittedCondition = skipPartiallyEmittedExpressions(condition); + const conditionPrecedence = getExpressionPrecedence(emittedCondition); + if (compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { + return factory2.createParenthesizedExpression(condition); + } + return condition; + } + function parenthesizeBranchOfConditionalExpression(branch) { + const emittedExpression = skipPartiallyEmittedExpressions(branch); + return isCommaSequence(emittedExpression) ? factory2.createParenthesizedExpression(branch) : branch; + } + function parenthesizeExpressionOfExportDefault(expression) { + const check = skipPartiallyEmittedExpressions(expression); + let needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression( + check, + /*stopAtCallExpressions*/ + false + ).kind) { + case 231 /* ClassExpression */: + case 218 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? factory2.createParenthesizedExpression(expression) : expression; + } + function parenthesizeExpressionOfNew(expression) { + const leftmostExpr = getLeftmostExpression( + expression, + /*stopAtCallExpressions*/ + true + ); + switch (leftmostExpr.kind) { + case 213 /* CallExpression */: + return factory2.createParenthesizedExpression(expression); + case 214 /* NewExpression */: + return !leftmostExpr.arguments ? factory2.createParenthesizedExpression(expression) : expression; + } + return parenthesizeLeftSideOfAccess(expression); + } + function parenthesizeLeftSideOfAccess(expression, optionalChain) { + const emittedExpression = skipPartiallyEmittedExpressions(expression); + if (isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== 214 /* NewExpression */ || emittedExpression.arguments) && (optionalChain || !isOptionalChain(emittedExpression))) { + return expression; + } + return setTextRange(factory2.createParenthesizedExpression(expression), expression); + } + function parenthesizeOperandOfPostfixUnary(operand) { + return isLeftHandSideExpression(operand) ? operand : setTextRange(factory2.createParenthesizedExpression(operand), operand); + } + function parenthesizeOperandOfPrefixUnary(operand) { + return isUnaryExpression(operand) ? operand : setTextRange(factory2.createParenthesizedExpression(operand), operand); + } + function parenthesizeExpressionsOfCommaDelimitedList(elements) { + const result = sameMap(elements, parenthesizeExpressionForDisallowedComma); + return setTextRange(factory2.createNodeArray(result, elements.hasTrailingComma), elements); + } + function parenthesizeExpressionForDisallowedComma(expression) { + const emittedExpression = skipPartiallyEmittedExpressions(expression); + const expressionPrecedence = getExpressionPrecedence(emittedExpression); + const commaPrecedence = getOperatorPrecedence(226 /* BinaryExpression */, 28 /* CommaToken */); + return expressionPrecedence > commaPrecedence ? expression : setTextRange(factory2.createParenthesizedExpression(expression), expression); + } + function parenthesizeExpressionOfExpressionStatement(expression) { + const emittedExpression = skipPartiallyEmittedExpressions(expression); + if (isCallExpression(emittedExpression)) { + const callee = emittedExpression.expression; + const kind = skipPartiallyEmittedExpressions(callee).kind; + if (kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */) { + const updated = factory2.updateCallExpression( + emittedExpression, + setTextRange(factory2.createParenthesizedExpression(callee), callee), + emittedExpression.typeArguments, + emittedExpression.arguments + ); + return factory2.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */); + } + } + const leftmostExpressionKind = getLeftmostExpression( + emittedExpression, + /*stopAtCallExpressions*/ + false + ).kind; + if (leftmostExpressionKind === 210 /* ObjectLiteralExpression */ || leftmostExpressionKind === 218 /* FunctionExpression */) { + return setTextRange(factory2.createParenthesizedExpression(expression), expression); + } + return expression; + } + function parenthesizeConciseBodyOfArrowFunction(body) { + if (!isBlock(body) && (isCommaSequence(body) || getLeftmostExpression( + body, + /*stopAtCallExpressions*/ + false + ).kind === 210 /* ObjectLiteralExpression */)) { + return setTextRange(factory2.createParenthesizedExpression(body), body); + } + return body; + } + function parenthesizeCheckTypeOfConditionalType(checkType) { + switch (checkType.kind) { + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + case 194 /* ConditionalType */: + return factory2.createParenthesizedType(checkType); + } + return checkType; + } + function parenthesizeExtendsTypeOfConditionalType(extendsType) { + switch (extendsType.kind) { + case 194 /* ConditionalType */: + return factory2.createParenthesizedType(extendsType); + } + return extendsType; + } + function parenthesizeConstituentTypeOfUnionType(type) { + switch (type.kind) { + case 192 /* UnionType */: + // Not strictly necessary, but a union containing a union should have been flattened + case 193 /* IntersectionType */: + return factory2.createParenthesizedType(type); + } + return parenthesizeCheckTypeOfConditionalType(type); + } + function parenthesizeConstituentTypesOfUnionType(members) { + return factory2.createNodeArray(sameMap(members, parenthesizeConstituentTypeOfUnionType)); + } + function parenthesizeConstituentTypeOfIntersectionType(type) { + switch (type.kind) { + case 192 /* UnionType */: + case 193 /* IntersectionType */: + return factory2.createParenthesizedType(type); + } + return parenthesizeConstituentTypeOfUnionType(type); + } + function parenthesizeConstituentTypesOfIntersectionType(members) { + return factory2.createNodeArray(sameMap(members, parenthesizeConstituentTypeOfIntersectionType)); + } + function parenthesizeOperandOfTypeOperator(type) { + switch (type.kind) { + case 193 /* IntersectionType */: + return factory2.createParenthesizedType(type); + } + return parenthesizeConstituentTypeOfIntersectionType(type); + } + function parenthesizeOperandOfReadonlyTypeOperator(type) { + switch (type.kind) { + case 198 /* TypeOperator */: + return factory2.createParenthesizedType(type); + } + return parenthesizeOperandOfTypeOperator(type); + } + function parenthesizeNonArrayTypeOfPostfixType(type) { + switch (type.kind) { + case 195 /* InferType */: + case 198 /* TypeOperator */: + case 186 /* TypeQuery */: + return factory2.createParenthesizedType(type); + } + return parenthesizeOperandOfTypeOperator(type); + } + function parenthesizeElementTypesOfTupleType(types) { + return factory2.createNodeArray(sameMap(types, parenthesizeElementTypeOfTupleType)); + } + function parenthesizeElementTypeOfTupleType(type) { + if (hasJSDocPostfixQuestion(type)) return factory2.createParenthesizedType(type); + return type; + } + function hasJSDocPostfixQuestion(type) { + if (isJSDocNullableType(type)) return type.postfix; + if (isNamedTupleMember(type)) return hasJSDocPostfixQuestion(type.type); + if (isFunctionTypeNode(type) || isConstructorTypeNode(type) || isTypeOperatorNode(type)) return hasJSDocPostfixQuestion(type.type); + if (isConditionalTypeNode(type)) return hasJSDocPostfixQuestion(type.falseType); + if (isUnionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types)); + if (isIntersectionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types)); + if (isInferTypeNode(type)) return !!type.typeParameter.constraint && hasJSDocPostfixQuestion(type.typeParameter.constraint); + return false; + } + function parenthesizeTypeOfOptionalType(type) { + if (hasJSDocPostfixQuestion(type)) return factory2.createParenthesizedType(type); + return parenthesizeNonArrayTypeOfPostfixType(type); + } + function parenthesizeLeadingTypeArgument(node) { + return isFunctionOrConstructorTypeNode(node) && node.typeParameters ? factory2.createParenthesizedType(node) : node; + } + function parenthesizeOrdinalTypeArgument(node, i) { + return i === 0 ? parenthesizeLeadingTypeArgument(node) : node; + } + function parenthesizeTypeArguments(typeArguments) { + if (some(typeArguments)) { + return factory2.createNodeArray(sameMap(typeArguments, parenthesizeOrdinalTypeArgument)); + } + } +} +var nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: (_) => identity, + getParenthesizeRightSideOfBinaryForOperator: (_) => identity, + parenthesizeLeftSideOfBinary: (_binaryOperator, leftSide) => leftSide, + parenthesizeRightSideOfBinary: (_binaryOperator, _leftSide, rightSide) => rightSide, + parenthesizeExpressionOfComputedPropertyName: identity, + parenthesizeConditionOfConditionalExpression: identity, + parenthesizeBranchOfConditionalExpression: identity, + parenthesizeExpressionOfExportDefault: identity, + parenthesizeExpressionOfNew: (expression) => cast(expression, isLeftHandSideExpression), + parenthesizeLeftSideOfAccess: (expression) => cast(expression, isLeftHandSideExpression), + parenthesizeOperandOfPostfixUnary: (operand) => cast(operand, isLeftHandSideExpression), + parenthesizeOperandOfPrefixUnary: (operand) => cast(operand, isUnaryExpression), + parenthesizeExpressionsOfCommaDelimitedList: (nodes) => cast(nodes, isNodeArray), + parenthesizeExpressionForDisallowedComma: identity, + parenthesizeExpressionOfExpressionStatement: identity, + parenthesizeConciseBodyOfArrowFunction: identity, + parenthesizeCheckTypeOfConditionalType: identity, + parenthesizeExtendsTypeOfConditionalType: identity, + parenthesizeConstituentTypesOfUnionType: (nodes) => cast(nodes, isNodeArray), + parenthesizeConstituentTypeOfUnionType: identity, + parenthesizeConstituentTypesOfIntersectionType: (nodes) => cast(nodes, isNodeArray), + parenthesizeConstituentTypeOfIntersectionType: identity, + parenthesizeOperandOfTypeOperator: identity, + parenthesizeOperandOfReadonlyTypeOperator: identity, + parenthesizeNonArrayTypeOfPostfixType: identity, + parenthesizeElementTypesOfTupleType: (nodes) => cast(nodes, isNodeArray), + parenthesizeElementTypeOfTupleType: identity, + parenthesizeTypeOfOptionalType: identity, + parenthesizeTypeArguments: (nodes) => nodes && cast(nodes, isNodeArray), + parenthesizeLeadingTypeArgument: identity +}; + +// src/compiler/factory/nodeConverters.ts +function createNodeConverters(factory2) { + return { + convertToFunctionBlock, + convertToFunctionExpression, + convertToClassExpression, + convertToArrayAssignmentElement, + convertToObjectAssignmentElement, + convertToAssignmentPattern, + convertToObjectAssignmentPattern, + convertToArrayAssignmentPattern, + convertToAssignmentElementTarget + }; + function convertToFunctionBlock(node, multiLine) { + if (isBlock(node)) return node; + const returnStatement = factory2.createReturnStatement(node); + setTextRange(returnStatement, node); + const body = factory2.createBlock([returnStatement], multiLine); + setTextRange(body, node); + return body; + } + function convertToFunctionExpression(node) { + var _a; + if (!node.body) return Debug.fail(`Cannot convert a FunctionDeclaration without a body`); + const updated = factory2.createFunctionExpression( + (_a = getModifiers(node)) == null ? void 0 : _a.filter((modifier) => !isExportModifier(modifier) && !isDefaultModifier(modifier)), + node.asteriskToken, + node.name, + node.typeParameters, + node.parameters, + node.type, + node.body + ); + setOriginalNode(updated, node); + setTextRange(updated, node); + if (getStartsOnNewLine(node)) { + setStartsOnNewLine( + updated, + /*newLine*/ + true + ); + } + return updated; + } + function convertToClassExpression(node) { + var _a; + const updated = factory2.createClassExpression( + (_a = node.modifiers) == null ? void 0 : _a.filter((modifier) => !isExportModifier(modifier) && !isDefaultModifier(modifier)), + node.name, + node.typeParameters, + node.heritageClauses, + node.members + ); + setOriginalNode(updated, node); + setTextRange(updated, node); + if (getStartsOnNewLine(node)) { + setStartsOnNewLine( + updated, + /*newLine*/ + true + ); + } + return updated; + } + function convertToArrayAssignmentElement(element) { + if (isBindingElement(element)) { + if (element.dotDotDotToken) { + Debug.assertNode(element.name, isIdentifier); + return setOriginalNode(setTextRange(factory2.createSpreadElement(element.name), element), element); + } + const expression = convertToAssignmentElementTarget(element.name); + return element.initializer ? setOriginalNode( + setTextRange( + factory2.createAssignment(expression, element.initializer), + element + ), + element + ) : expression; + } + return cast(element, isExpression); + } + function convertToObjectAssignmentElement(element) { + if (isBindingElement(element)) { + if (element.dotDotDotToken) { + Debug.assertNode(element.name, isIdentifier); + return setOriginalNode(setTextRange(factory2.createSpreadAssignment(element.name), element), element); + } + if (element.propertyName) { + const expression = convertToAssignmentElementTarget(element.name); + return setOriginalNode(setTextRange(factory2.createPropertyAssignment(element.propertyName, element.initializer ? factory2.createAssignment(expression, element.initializer) : expression), element), element); + } + Debug.assertNode(element.name, isIdentifier); + return setOriginalNode(setTextRange(factory2.createShorthandPropertyAssignment(element.name, element.initializer), element), element); + } + return cast(element, isObjectLiteralElementLike); + } + function convertToAssignmentPattern(node) { + switch (node.kind) { + case 207 /* ArrayBindingPattern */: + case 209 /* ArrayLiteralExpression */: + return convertToArrayAssignmentPattern(node); + case 206 /* ObjectBindingPattern */: + case 210 /* ObjectLiteralExpression */: + return convertToObjectAssignmentPattern(node); + } + } + function convertToObjectAssignmentPattern(node) { + if (isObjectBindingPattern(node)) { + return setOriginalNode( + setTextRange( + factory2.createObjectLiteralExpression(map(node.elements, convertToObjectAssignmentElement)), + node + ), + node + ); + } + return cast(node, isObjectLiteralExpression); + } + function convertToArrayAssignmentPattern(node) { + if (isArrayBindingPattern(node)) { + return setOriginalNode( + setTextRange( + factory2.createArrayLiteralExpression(map(node.elements, convertToArrayAssignmentElement)), + node + ), + node + ); + } + return cast(node, isArrayLiteralExpression); + } + function convertToAssignmentElementTarget(node) { + if (isBindingPattern(node)) { + return convertToAssignmentPattern(node); + } + return cast(node, isExpression); + } +} +var nullNodeConverters = { + convertToFunctionBlock: notImplemented, + convertToFunctionExpression: notImplemented, + convertToClassExpression: notImplemented, + convertToArrayAssignmentElement: notImplemented, + convertToObjectAssignmentElement: notImplemented, + convertToAssignmentPattern: notImplemented, + convertToObjectAssignmentPattern: notImplemented, + convertToArrayAssignmentPattern: notImplemented, + convertToAssignmentElementTarget: notImplemented +}; + +// src/compiler/factory/nodeFactory.ts +var nextAutoGenerateId = 0; +var nodeFactoryPatchers = []; +function createNodeFactory(flags, baseFactory2) { + const setOriginal = flags & 8 /* NoOriginalNode */ ? identity : setOriginalNode; + const parenthesizerRules = memoize(() => flags & 1 /* NoParenthesizerRules */ ? nullParenthesizerRules : createParenthesizerRules(factory2)); + const converters = memoize(() => flags & 2 /* NoNodeConverters */ ? nullNodeConverters : createNodeConverters(factory2)); + const getBinaryCreateFunction = memoizeOne((operator) => (left, right) => createBinaryExpression(left, operator, right)); + const getPrefixUnaryCreateFunction = memoizeOne((operator) => (operand) => createPrefixUnaryExpression(operator, operand)); + const getPostfixUnaryCreateFunction = memoizeOne((operator) => (operand) => createPostfixUnaryExpression(operand, operator)); + const getJSDocPrimaryTypeCreateFunction = memoizeOne((kind) => () => createJSDocPrimaryTypeWorker(kind)); + const getJSDocUnaryTypeCreateFunction = memoizeOne((kind) => (type) => createJSDocUnaryTypeWorker(kind, type)); + const getJSDocUnaryTypeUpdateFunction = memoizeOne((kind) => (node, type) => updateJSDocUnaryTypeWorker(kind, node, type)); + const getJSDocPrePostfixUnaryTypeCreateFunction = memoizeOne((kind) => (type, postfix) => createJSDocPrePostfixUnaryTypeWorker(kind, type, postfix)); + const getJSDocPrePostfixUnaryTypeUpdateFunction = memoizeOne((kind) => (node, type) => updateJSDocPrePostfixUnaryTypeWorker(kind, node, type)); + const getJSDocSimpleTagCreateFunction = memoizeOne((kind) => (tagName, comment) => createJSDocSimpleTagWorker(kind, tagName, comment)); + const getJSDocSimpleTagUpdateFunction = memoizeOne((kind) => (node, tagName, comment) => updateJSDocSimpleTagWorker(kind, node, tagName, comment)); + const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind) => (tagName, typeExpression, comment) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); + const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind) => (node, tagName, typeExpression, comment) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); + const factory2 = { + get parenthesizer() { + return parenthesizerRules(); + }, + get converters() { + return converters(); + }, + baseFactory: baseFactory2, + flags, + createNodeArray, + createNumericLiteral, + createBigIntLiteral, + createStringLiteral, + createStringLiteralFromNode, + createRegularExpressionLiteral, + createLiteralLikeNode, + createIdentifier, + createTempVariable, + createLoopVariable, + createUniqueName, + getGeneratedNameForNode, + createPrivateIdentifier, + createUniquePrivateName, + getGeneratedPrivateNameForNode, + createToken, + createSuper, + createThis, + createNull, + createTrue, + createFalse, + createModifier, + createModifiersFromModifierFlags, + createQualifiedName, + updateQualifiedName, + createComputedPropertyName, + updateComputedPropertyName, + createTypeParameterDeclaration, + updateTypeParameterDeclaration, + createParameterDeclaration, + updateParameterDeclaration, + createDecorator, + updateDecorator, + createPropertySignature, + updatePropertySignature, + createPropertyDeclaration, + updatePropertyDeclaration, + createMethodSignature, + updateMethodSignature, + createMethodDeclaration, + updateMethodDeclaration, + createConstructorDeclaration, + updateConstructorDeclaration, + createGetAccessorDeclaration, + updateGetAccessorDeclaration, + createSetAccessorDeclaration, + updateSetAccessorDeclaration, + createCallSignature, + updateCallSignature, + createConstructSignature, + updateConstructSignature, + createIndexSignature, + updateIndexSignature, + createClassStaticBlockDeclaration, + updateClassStaticBlockDeclaration, + createTemplateLiteralTypeSpan, + updateTemplateLiteralTypeSpan, + createKeywordTypeNode, + createTypePredicateNode, + updateTypePredicateNode, + createTypeReferenceNode, + updateTypeReferenceNode, + createFunctionTypeNode, + updateFunctionTypeNode, + createConstructorTypeNode, + updateConstructorTypeNode, + createTypeQueryNode, + updateTypeQueryNode, + createTypeLiteralNode, + updateTypeLiteralNode, + createArrayTypeNode, + updateArrayTypeNode, + createTupleTypeNode, + updateTupleTypeNode, + createNamedTupleMember, + updateNamedTupleMember, + createOptionalTypeNode, + updateOptionalTypeNode, + createRestTypeNode, + updateRestTypeNode, + createUnionTypeNode, + updateUnionTypeNode, + createIntersectionTypeNode, + updateIntersectionTypeNode, + createConditionalTypeNode, + updateConditionalTypeNode, + createInferTypeNode, + updateInferTypeNode, + createImportTypeNode, + updateImportTypeNode, + createParenthesizedType, + updateParenthesizedType, + createThisTypeNode, + createTypeOperatorNode, + updateTypeOperatorNode, + createIndexedAccessTypeNode, + updateIndexedAccessTypeNode, + createMappedTypeNode, + updateMappedTypeNode, + createLiteralTypeNode, + updateLiteralTypeNode, + createTemplateLiteralType, + updateTemplateLiteralType, + createObjectBindingPattern, + updateObjectBindingPattern, + createArrayBindingPattern, + updateArrayBindingPattern, + createBindingElement, + updateBindingElement, + createArrayLiteralExpression, + updateArrayLiteralExpression, + createObjectLiteralExpression, + updateObjectLiteralExpression, + createPropertyAccessExpression: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ? (expression, name) => setEmitFlags(createPropertyAccessExpression(expression, name), 262144 /* NoIndentation */) : createPropertyAccessExpression, + updatePropertyAccessExpression, + createPropertyAccessChain: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ? (expression, questionDotToken, name) => setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), 262144 /* NoIndentation */) : createPropertyAccessChain, + updatePropertyAccessChain, + createElementAccessExpression, + updateElementAccessExpression, + createElementAccessChain, + updateElementAccessChain, + createCallExpression, + updateCallExpression, + createCallChain, + updateCallChain, + createNewExpression, + updateNewExpression, + createTaggedTemplateExpression, + updateTaggedTemplateExpression, + createTypeAssertion, + updateTypeAssertion, + createParenthesizedExpression, + updateParenthesizedExpression, + createFunctionExpression, + updateFunctionExpression, + createArrowFunction, + updateArrowFunction, + createDeleteExpression, + updateDeleteExpression, + createTypeOfExpression, + updateTypeOfExpression, + createVoidExpression, + updateVoidExpression, + createAwaitExpression, + updateAwaitExpression, + createPrefixUnaryExpression, + updatePrefixUnaryExpression, + createPostfixUnaryExpression, + updatePostfixUnaryExpression, + createBinaryExpression, + updateBinaryExpression, + createConditionalExpression, + updateConditionalExpression, + createTemplateExpression, + updateTemplateExpression, + createTemplateHead, + createTemplateMiddle, + createTemplateTail, + createNoSubstitutionTemplateLiteral, + createTemplateLiteralLikeNode, + createYieldExpression, + updateYieldExpression, + createSpreadElement, + updateSpreadElement, + createClassExpression, + updateClassExpression, + createOmittedExpression, + createExpressionWithTypeArguments, + updateExpressionWithTypeArguments, + createAsExpression, + updateAsExpression, + createNonNullExpression, + updateNonNullExpression, + createSatisfiesExpression, + updateSatisfiesExpression, + createNonNullChain, + updateNonNullChain, + createMetaProperty, + updateMetaProperty, + createTemplateSpan, + updateTemplateSpan, + createSemicolonClassElement, + createBlock, + updateBlock, + createVariableStatement, + updateVariableStatement, + createEmptyStatement, + createExpressionStatement, + updateExpressionStatement, + createIfStatement, + updateIfStatement, + createDoStatement, + updateDoStatement, + createWhileStatement, + updateWhileStatement, + createForStatement, + updateForStatement, + createForInStatement, + updateForInStatement, + createForOfStatement, + updateForOfStatement, + createContinueStatement, + updateContinueStatement, + createBreakStatement, + updateBreakStatement, + createReturnStatement, + updateReturnStatement, + createWithStatement, + updateWithStatement, + createSwitchStatement, + updateSwitchStatement, + createLabeledStatement, + updateLabeledStatement, + createThrowStatement, + updateThrowStatement, + createTryStatement, + updateTryStatement, + createDebuggerStatement, + createVariableDeclaration, + updateVariableDeclaration, + createVariableDeclarationList, + updateVariableDeclarationList, + createFunctionDeclaration, + updateFunctionDeclaration, + createClassDeclaration, + updateClassDeclaration, + createInterfaceDeclaration, + updateInterfaceDeclaration, + createTypeAliasDeclaration, + updateTypeAliasDeclaration, + createEnumDeclaration, + updateEnumDeclaration, + createModuleDeclaration, + updateModuleDeclaration, + createModuleBlock, + updateModuleBlock, + createCaseBlock, + updateCaseBlock, + createNamespaceExportDeclaration, + updateNamespaceExportDeclaration, + createImportEqualsDeclaration, + updateImportEqualsDeclaration, + createImportDeclaration, + updateImportDeclaration, + createImportClause, + updateImportClause, + createAssertClause, + updateAssertClause, + createAssertEntry, + updateAssertEntry, + createImportTypeAssertionContainer, + updateImportTypeAssertionContainer, + createImportAttributes, + updateImportAttributes, + createImportAttribute, + updateImportAttribute, + createNamespaceImport, + updateNamespaceImport, + createNamespaceExport, + updateNamespaceExport, + createNamedImports, + updateNamedImports, + createImportSpecifier, + updateImportSpecifier, + createExportAssignment, + updateExportAssignment, + createExportDeclaration, + updateExportDeclaration, + createNamedExports, + updateNamedExports, + createExportSpecifier, + updateExportSpecifier, + createMissingDeclaration, + createExternalModuleReference, + updateExternalModuleReference, + // lazily load factory members for JSDoc types with similar structure + get createJSDocAllType() { + return getJSDocPrimaryTypeCreateFunction(312 /* JSDocAllType */); + }, + get createJSDocUnknownType() { + return getJSDocPrimaryTypeCreateFunction(313 /* JSDocUnknownType */); + }, + get createJSDocNonNullableType() { + return getJSDocPrePostfixUnaryTypeCreateFunction(315 /* JSDocNonNullableType */); + }, + get updateJSDocNonNullableType() { + return getJSDocPrePostfixUnaryTypeUpdateFunction(315 /* JSDocNonNullableType */); + }, + get createJSDocNullableType() { + return getJSDocPrePostfixUnaryTypeCreateFunction(314 /* JSDocNullableType */); + }, + get updateJSDocNullableType() { + return getJSDocPrePostfixUnaryTypeUpdateFunction(314 /* JSDocNullableType */); + }, + get createJSDocOptionalType() { + return getJSDocUnaryTypeCreateFunction(316 /* JSDocOptionalType */); + }, + get updateJSDocOptionalType() { + return getJSDocUnaryTypeUpdateFunction(316 /* JSDocOptionalType */); + }, + get createJSDocVariadicType() { + return getJSDocUnaryTypeCreateFunction(318 /* JSDocVariadicType */); + }, + get updateJSDocVariadicType() { + return getJSDocUnaryTypeUpdateFunction(318 /* JSDocVariadicType */); + }, + get createJSDocNamepathType() { + return getJSDocUnaryTypeCreateFunction(319 /* JSDocNamepathType */); + }, + get updateJSDocNamepathType() { + return getJSDocUnaryTypeUpdateFunction(319 /* JSDocNamepathType */); + }, + createJSDocFunctionType, + updateJSDocFunctionType, + createJSDocTypeLiteral, + updateJSDocTypeLiteral, + createJSDocTypeExpression, + updateJSDocTypeExpression, + createJSDocSignature, + updateJSDocSignature, + createJSDocTemplateTag, + updateJSDocTemplateTag, + createJSDocTypedefTag, + updateJSDocTypedefTag, + createJSDocParameterTag, + updateJSDocParameterTag, + createJSDocPropertyTag, + updateJSDocPropertyTag, + createJSDocCallbackTag, + updateJSDocCallbackTag, + createJSDocOverloadTag, + updateJSDocOverloadTag, + createJSDocAugmentsTag, + updateJSDocAugmentsTag, + createJSDocImplementsTag, + updateJSDocImplementsTag, + createJSDocSeeTag, + updateJSDocSeeTag, + createJSDocImportTag, + updateJSDocImportTag, + createJSDocNameReference, + updateJSDocNameReference, + createJSDocMemberName, + updateJSDocMemberName, + createJSDocLink, + updateJSDocLink, + createJSDocLinkCode, + updateJSDocLinkCode, + createJSDocLinkPlain, + updateJSDocLinkPlain, + // lazily load factory members for JSDoc tags with similar structure + get createJSDocTypeTag() { + return getJSDocTypeLikeTagCreateFunction(344 /* JSDocTypeTag */); + }, + get updateJSDocTypeTag() { + return getJSDocTypeLikeTagUpdateFunction(344 /* JSDocTypeTag */); + }, + get createJSDocReturnTag() { + return getJSDocTypeLikeTagCreateFunction(342 /* JSDocReturnTag */); + }, + get updateJSDocReturnTag() { + return getJSDocTypeLikeTagUpdateFunction(342 /* JSDocReturnTag */); + }, + get createJSDocThisTag() { + return getJSDocTypeLikeTagCreateFunction(343 /* JSDocThisTag */); + }, + get updateJSDocThisTag() { + return getJSDocTypeLikeTagUpdateFunction(343 /* JSDocThisTag */); + }, + get createJSDocAuthorTag() { + return getJSDocSimpleTagCreateFunction(330 /* JSDocAuthorTag */); + }, + get updateJSDocAuthorTag() { + return getJSDocSimpleTagUpdateFunction(330 /* JSDocAuthorTag */); + }, + get createJSDocClassTag() { + return getJSDocSimpleTagCreateFunction(332 /* JSDocClassTag */); + }, + get updateJSDocClassTag() { + return getJSDocSimpleTagUpdateFunction(332 /* JSDocClassTag */); + }, + get createJSDocPublicTag() { + return getJSDocSimpleTagCreateFunction(333 /* JSDocPublicTag */); + }, + get updateJSDocPublicTag() { + return getJSDocSimpleTagUpdateFunction(333 /* JSDocPublicTag */); + }, + get createJSDocPrivateTag() { + return getJSDocSimpleTagCreateFunction(334 /* JSDocPrivateTag */); + }, + get updateJSDocPrivateTag() { + return getJSDocSimpleTagUpdateFunction(334 /* JSDocPrivateTag */); + }, + get createJSDocProtectedTag() { + return getJSDocSimpleTagCreateFunction(335 /* JSDocProtectedTag */); + }, + get updateJSDocProtectedTag() { + return getJSDocSimpleTagUpdateFunction(335 /* JSDocProtectedTag */); + }, + get createJSDocReadonlyTag() { + return getJSDocSimpleTagCreateFunction(336 /* JSDocReadonlyTag */); + }, + get updateJSDocReadonlyTag() { + return getJSDocSimpleTagUpdateFunction(336 /* JSDocReadonlyTag */); + }, + get createJSDocOverrideTag() { + return getJSDocSimpleTagCreateFunction(337 /* JSDocOverrideTag */); + }, + get updateJSDocOverrideTag() { + return getJSDocSimpleTagUpdateFunction(337 /* JSDocOverrideTag */); + }, + get createJSDocDeprecatedTag() { + return getJSDocSimpleTagCreateFunction(331 /* JSDocDeprecatedTag */); + }, + get updateJSDocDeprecatedTag() { + return getJSDocSimpleTagUpdateFunction(331 /* JSDocDeprecatedTag */); + }, + get createJSDocThrowsTag() { + return getJSDocTypeLikeTagCreateFunction(349 /* JSDocThrowsTag */); + }, + get updateJSDocThrowsTag() { + return getJSDocTypeLikeTagUpdateFunction(349 /* JSDocThrowsTag */); + }, + get createJSDocSatisfiesTag() { + return getJSDocTypeLikeTagCreateFunction(350 /* JSDocSatisfiesTag */); + }, + get updateJSDocSatisfiesTag() { + return getJSDocTypeLikeTagUpdateFunction(350 /* JSDocSatisfiesTag */); + }, + createJSDocEnumTag, + updateJSDocEnumTag, + createJSDocUnknownTag, + updateJSDocUnknownTag, + createJSDocText, + updateJSDocText, + createJSDocComment, + updateJSDocComment, + createJsxElement, + updateJsxElement, + createJsxSelfClosingElement, + updateJsxSelfClosingElement, + createJsxOpeningElement, + updateJsxOpeningElement, + createJsxClosingElement, + updateJsxClosingElement, + createJsxFragment, + createJsxText, + updateJsxText, + createJsxOpeningFragment, + createJsxJsxClosingFragment, + updateJsxFragment, + createJsxAttribute, + updateJsxAttribute, + createJsxAttributes, + updateJsxAttributes, + createJsxSpreadAttribute, + updateJsxSpreadAttribute, + createJsxExpression, + updateJsxExpression, + createJsxNamespacedName, + updateJsxNamespacedName, + createCaseClause, + updateCaseClause, + createDefaultClause, + updateDefaultClause, + createHeritageClause, + updateHeritageClause, + createCatchClause, + updateCatchClause, + createPropertyAssignment, + updatePropertyAssignment, + createShorthandPropertyAssignment, + updateShorthandPropertyAssignment, + createSpreadAssignment, + updateSpreadAssignment, + createEnumMember, + updateEnumMember, + createSourceFile: createSourceFile2, + updateSourceFile, + createRedirectedSourceFile, + createBundle, + updateBundle, + createSyntheticExpression, + createSyntaxList, + createNotEmittedStatement, + createNotEmittedTypeElement, + createPartiallyEmittedExpression, + updatePartiallyEmittedExpression, + createCommaListExpression, + updateCommaListExpression, + createSyntheticReferenceExpression, + updateSyntheticReferenceExpression, + cloneNode, + // Lazily load factory methods for common operator factories and utilities + get createComma() { + return getBinaryCreateFunction(28 /* CommaToken */); + }, + get createAssignment() { + return getBinaryCreateFunction(64 /* EqualsToken */); + }, + get createLogicalOr() { + return getBinaryCreateFunction(57 /* BarBarToken */); + }, + get createLogicalAnd() { + return getBinaryCreateFunction(56 /* AmpersandAmpersandToken */); + }, + get createBitwiseOr() { + return getBinaryCreateFunction(52 /* BarToken */); + }, + get createBitwiseXor() { + return getBinaryCreateFunction(53 /* CaretToken */); + }, + get createBitwiseAnd() { + return getBinaryCreateFunction(51 /* AmpersandToken */); + }, + get createStrictEquality() { + return getBinaryCreateFunction(37 /* EqualsEqualsEqualsToken */); + }, + get createStrictInequality() { + return getBinaryCreateFunction(38 /* ExclamationEqualsEqualsToken */); + }, + get createEquality() { + return getBinaryCreateFunction(35 /* EqualsEqualsToken */); + }, + get createInequality() { + return getBinaryCreateFunction(36 /* ExclamationEqualsToken */); + }, + get createLessThan() { + return getBinaryCreateFunction(30 /* LessThanToken */); + }, + get createLessThanEquals() { + return getBinaryCreateFunction(33 /* LessThanEqualsToken */); + }, + get createGreaterThan() { + return getBinaryCreateFunction(32 /* GreaterThanToken */); + }, + get createGreaterThanEquals() { + return getBinaryCreateFunction(34 /* GreaterThanEqualsToken */); + }, + get createLeftShift() { + return getBinaryCreateFunction(48 /* LessThanLessThanToken */); + }, + get createRightShift() { + return getBinaryCreateFunction(49 /* GreaterThanGreaterThanToken */); + }, + get createUnsignedRightShift() { + return getBinaryCreateFunction(50 /* GreaterThanGreaterThanGreaterThanToken */); + }, + get createAdd() { + return getBinaryCreateFunction(40 /* PlusToken */); + }, + get createSubtract() { + return getBinaryCreateFunction(41 /* MinusToken */); + }, + get createMultiply() { + return getBinaryCreateFunction(42 /* AsteriskToken */); + }, + get createDivide() { + return getBinaryCreateFunction(44 /* SlashToken */); + }, + get createModulo() { + return getBinaryCreateFunction(45 /* PercentToken */); + }, + get createExponent() { + return getBinaryCreateFunction(43 /* AsteriskAsteriskToken */); + }, + get createPrefixPlus() { + return getPrefixUnaryCreateFunction(40 /* PlusToken */); + }, + get createPrefixMinus() { + return getPrefixUnaryCreateFunction(41 /* MinusToken */); + }, + get createPrefixIncrement() { + return getPrefixUnaryCreateFunction(46 /* PlusPlusToken */); + }, + get createPrefixDecrement() { + return getPrefixUnaryCreateFunction(47 /* MinusMinusToken */); + }, + get createBitwiseNot() { + return getPrefixUnaryCreateFunction(55 /* TildeToken */); + }, + get createLogicalNot() { + return getPrefixUnaryCreateFunction(54 /* ExclamationToken */); + }, + get createPostfixIncrement() { + return getPostfixUnaryCreateFunction(46 /* PlusPlusToken */); + }, + get createPostfixDecrement() { + return getPostfixUnaryCreateFunction(47 /* MinusMinusToken */); + }, + // Compound nodes + createImmediatelyInvokedFunctionExpression, + createImmediatelyInvokedArrowFunction, + createVoidZero, + createExportDefault, + createExternalModuleExport, + createTypeCheck, + createIsNotTypeCheck, + createMethodCall, + createGlobalMethodCall, + createFunctionBindCall, + createFunctionCallCall, + createFunctionApplyCall, + createArraySliceCall, + createArrayConcatCall, + createObjectDefinePropertyCall, + createObjectGetOwnPropertyDescriptorCall, + createReflectGetCall, + createReflectSetCall, + createPropertyDescriptor, + createCallBinding, + createAssignmentTargetWrapper, + // Utilities + inlineExpressions, + getInternalName, + getLocalName, + getExportName, + getDeclarationName, + getNamespaceMemberName, + getExternalModuleOrNamespaceExportName, + restoreOuterExpressions, + restoreEnclosingLabel, + createUseStrictPrologue, + copyPrologue, + copyStandardPrologue, + copyCustomPrologue, + ensureUseStrict, + liftToBlock, + mergeLexicalEnvironment, + replaceModifiers, + replaceDecoratorsAndModifiers, + replacePropertyName + }; + forEach(nodeFactoryPatchers, (fn) => fn(factory2)); + return factory2; + function createNodeArray(elements, hasTrailingComma) { + if (elements === void 0 || elements === emptyArray) { + elements = []; + } else if (isNodeArray(elements)) { + if (hasTrailingComma === void 0 || elements.hasTrailingComma === hasTrailingComma) { + if (elements.transformFlags === void 0) { + aggregateChildrenFlags(elements); + } + Debug.attachNodeArrayDebugInfo(elements); + return elements; + } + const array2 = elements.slice(); + array2.pos = elements.pos; + array2.end = elements.end; + array2.hasTrailingComma = hasTrailingComma; + array2.transformFlags = elements.transformFlags; + Debug.attachNodeArrayDebugInfo(array2); + return array2; + } + const length2 = elements.length; + const array = length2 >= 1 && length2 <= 4 ? elements.slice() : elements; + array.pos = -1; + array.end = -1; + array.hasTrailingComma = !!hasTrailingComma; + array.transformFlags = 0 /* None */; + aggregateChildrenFlags(array); + Debug.attachNodeArrayDebugInfo(array); + return array; + } + function createBaseNode(kind) { + return baseFactory2.createBaseNode(kind); + } + function createBaseDeclaration(kind) { + const node = createBaseNode(kind); + node.symbol = void 0; + node.localSymbol = void 0; + return node; + } + function finishUpdateBaseSignatureDeclaration(updated, original) { + if (updated !== original) { + updated.typeArguments = original.typeArguments; + } + return update(updated, original); + } + function createNumericLiteral(value, numericLiteralFlags = 0 /* None */) { + const text = typeof value === "number" ? value + "" : value; + Debug.assert(text.charCodeAt(0) !== 45 /* minus */, "Negative numbers should be created in combination with createPrefixUnaryExpression"); + const node = createBaseDeclaration(9 /* NumericLiteral */); + node.text = text; + node.numericLiteralFlags = numericLiteralFlags; + if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) node.transformFlags |= 1024 /* ContainsES2015 */; + return node; + } + function createBigIntLiteral(value) { + const node = createBaseToken(10 /* BigIntLiteral */); + node.text = typeof value === "string" ? value : pseudoBigIntToString(value) + "n"; + node.transformFlags |= 32 /* ContainsES2020 */; + return node; + } + function createBaseStringLiteral(text, isSingleQuote) { + const node = createBaseDeclaration(11 /* StringLiteral */); + node.text = text; + node.singleQuote = isSingleQuote; + return node; + } + function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) { + const node = createBaseStringLiteral(text, isSingleQuote); + node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + if (hasExtendedUnicodeEscape) node.transformFlags |= 1024 /* ContainsES2015 */; + return node; + } + function createStringLiteralFromNode(sourceNode) { + const node = createBaseStringLiteral( + getTextOfIdentifierOrLiteral(sourceNode), + /*isSingleQuote*/ + void 0 + ); + node.textSourceNode = sourceNode; + return node; + } + function createRegularExpressionLiteral(text) { + const node = createBaseToken(14 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + function createLiteralLikeNode(kind, text) { + switch (kind) { + case 9 /* NumericLiteral */: + return createNumericLiteral( + text, + /*numericLiteralFlags*/ + 0 + ); + case 10 /* BigIntLiteral */: + return createBigIntLiteral(text); + case 11 /* StringLiteral */: + return createStringLiteral( + text, + /*isSingleQuote*/ + void 0 + ); + case 12 /* JsxText */: + return createJsxText( + text, + /*containsOnlyTriviaWhiteSpaces*/ + false + ); + case 13 /* JsxTextAllWhiteSpaces */: + return createJsxText( + text, + /*containsOnlyTriviaWhiteSpaces*/ + true + ); + case 14 /* RegularExpressionLiteral */: + return createRegularExpressionLiteral(text); + case 15 /* NoSubstitutionTemplateLiteral */: + return createTemplateLiteralLikeNode( + kind, + text, + /*rawText*/ + void 0, + /*templateFlags*/ + 0 + ); + } + } + function createBaseIdentifier(escapedText) { + const node = baseFactory2.createBaseIdentifierNode(80 /* Identifier */); + node.escapedText = escapedText; + node.jsDoc = void 0; + node.flowNode = void 0; + node.symbol = void 0; + return node; + } + function createBaseGeneratedIdentifier(text, autoGenerateFlags, prefix, suffix) { + const node = createBaseIdentifier(escapeLeadingUnderscores(text)); + setIdentifierAutoGenerate(node, { + flags: autoGenerateFlags, + id: nextAutoGenerateId, + prefix, + suffix + }); + nextAutoGenerateId++; + return node; + } + function createIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape) { + if (originalKeywordKind === void 0 && text) { + originalKeywordKind = stringToToken(text); + } + if (originalKeywordKind === 80 /* Identifier */) { + originalKeywordKind = void 0; + } + const node = createBaseIdentifier(escapeLeadingUnderscores(text)); + if (hasExtendedUnicodeEscape) node.flags |= 256 /* IdentifierHasExtendedUnicodeEscape */; + if (node.escapedText === "await") { + node.transformFlags |= 67108864 /* ContainsPossibleTopLevelAwait */; + } + if (node.flags & 256 /* IdentifierHasExtendedUnicodeEscape */) { + node.transformFlags |= 1024 /* ContainsES2015 */; + } + return node; + } + function createTempVariable(recordTempVariable, reservedInNestedScopes, prefix, suffix) { + let flags2 = 1 /* Auto */; + if (reservedInNestedScopes) flags2 |= 8 /* ReservedInNestedScopes */; + const name = createBaseGeneratedIdentifier("", flags2, prefix, suffix); + if (recordTempVariable) { + recordTempVariable(name); + } + return name; + } + function createLoopVariable(reservedInNestedScopes) { + let flags2 = 2 /* Loop */; + if (reservedInNestedScopes) flags2 |= 8 /* ReservedInNestedScopes */; + return createBaseGeneratedIdentifier( + "", + flags2, + /*prefix*/ + void 0, + /*suffix*/ + void 0 + ); + } + function createUniqueName(text, flags2 = 0 /* None */, prefix, suffix) { + Debug.assert(!(flags2 & 7 /* KindMask */), "Argument out of range: flags"); + Debug.assert((flags2 & (16 /* Optimistic */ | 32 /* FileLevel */)) !== 32 /* FileLevel */, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic"); + return createBaseGeneratedIdentifier(text, 3 /* Unique */ | flags2, prefix, suffix); + } + function getGeneratedNameForNode(node, flags2 = 0, prefix, suffix) { + Debug.assert(!(flags2 & 7 /* KindMask */), "Argument out of range: flags"); + const text = !node ? "" : isMemberName(node) ? formatGeneratedName( + /*privateName*/ + false, + prefix, + node, + suffix, + idText + ) : `generated@${getNodeId(node)}`; + if (prefix || suffix) flags2 |= 16 /* Optimistic */; + const name = createBaseGeneratedIdentifier(text, 4 /* Node */ | flags2, prefix, suffix); + name.original = node; + return name; + } + function createBasePrivateIdentifier(escapedText) { + const node = baseFactory2.createBasePrivateIdentifierNode(81 /* PrivateIdentifier */); + node.escapedText = escapedText; + node.transformFlags |= 16777216 /* ContainsClassFields */; + return node; + } + function createPrivateIdentifier(text) { + if (!startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text); + return createBasePrivateIdentifier(escapeLeadingUnderscores(text)); + } + function createBaseGeneratedPrivateIdentifier(text, autoGenerateFlags, prefix, suffix) { + const node = createBasePrivateIdentifier(escapeLeadingUnderscores(text)); + setIdentifierAutoGenerate(node, { + flags: autoGenerateFlags, + id: nextAutoGenerateId, + prefix, + suffix + }); + nextAutoGenerateId++; + return node; + } + function createUniquePrivateName(text, prefix, suffix) { + if (text && !startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text); + const autoGenerateFlags = 8 /* ReservedInNestedScopes */ | (text ? 3 /* Unique */ : 1 /* Auto */); + return createBaseGeneratedPrivateIdentifier(text ?? "", autoGenerateFlags, prefix, suffix); + } + function getGeneratedPrivateNameForNode(node, prefix, suffix) { + const text = isMemberName(node) ? formatGeneratedName( + /*privateName*/ + true, + prefix, + node, + suffix, + idText + ) : `#generated@${getNodeId(node)}`; + const flags2 = prefix || suffix ? 16 /* Optimistic */ : 0 /* None */; + const name = createBaseGeneratedPrivateIdentifier(text, 4 /* Node */ | flags2, prefix, suffix); + name.original = node; + return name; + } + function createBaseToken(kind) { + return baseFactory2.createBaseTokenNode(kind); + } + function createToken(token) { + Debug.assert(token >= 0 /* FirstToken */ && token <= 165 /* LastToken */, "Invalid token"); + Debug.assert(token <= 15 /* FirstTemplateToken */ || token >= 18 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); + Debug.assert(token <= 9 /* FirstLiteralToken */ || token >= 15 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals."); + Debug.assert(token !== 80 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers"); + const node = createBaseToken(token); + let transformFlags = 0 /* None */; + switch (token) { + case 134 /* AsyncKeyword */: + transformFlags = 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */; + break; + case 160 /* UsingKeyword */: + transformFlags = 4 /* ContainsESNext */; + break; + case 125 /* PublicKeyword */: + case 123 /* PrivateKeyword */: + case 124 /* ProtectedKeyword */: + case 148 /* ReadonlyKeyword */: + case 128 /* AbstractKeyword */: + case 138 /* DeclareKeyword */: + case 87 /* ConstKeyword */: + case 133 /* AnyKeyword */: + case 150 /* NumberKeyword */: + case 163 /* BigIntKeyword */: + case 146 /* NeverKeyword */: + case 151 /* ObjectKeyword */: + case 103 /* InKeyword */: + case 147 /* OutKeyword */: + case 164 /* OverrideKeyword */: + case 154 /* StringKeyword */: + case 136 /* BooleanKeyword */: + case 155 /* SymbolKeyword */: + case 116 /* VoidKeyword */: + case 159 /* UnknownKeyword */: + case 157 /* UndefinedKeyword */: + transformFlags = 1 /* ContainsTypeScript */; + break; + case 108 /* SuperKeyword */: + transformFlags = 1024 /* ContainsES2015 */ | 134217728 /* ContainsLexicalSuper */; + node.flowNode = void 0; + break; + case 126 /* StaticKeyword */: + transformFlags = 1024 /* ContainsES2015 */; + break; + case 129 /* AccessorKeyword */: + transformFlags = 16777216 /* ContainsClassFields */; + break; + case 110 /* ThisKeyword */: + transformFlags = 16384 /* ContainsLexicalThis */; + node.flowNode = void 0; + break; + } + if (transformFlags) { + node.transformFlags |= transformFlags; + } + return node; + } + function createSuper() { + return createToken(108 /* SuperKeyword */); + } + function createThis() { + return createToken(110 /* ThisKeyword */); + } + function createNull() { + return createToken(106 /* NullKeyword */); + } + function createTrue() { + return createToken(112 /* TrueKeyword */); + } + function createFalse() { + return createToken(97 /* FalseKeyword */); + } + function createModifier(kind) { + return createToken(kind); + } + function createModifiersFromModifierFlags(flags2) { + const result = []; + if (flags2 & 32 /* Export */) result.push(createModifier(95 /* ExportKeyword */)); + if (flags2 & 128 /* Ambient */) result.push(createModifier(138 /* DeclareKeyword */)); + if (flags2 & 2048 /* Default */) result.push(createModifier(90 /* DefaultKeyword */)); + if (flags2 & 4096 /* Const */) result.push(createModifier(87 /* ConstKeyword */)); + if (flags2 & 1 /* Public */) result.push(createModifier(125 /* PublicKeyword */)); + if (flags2 & 2 /* Private */) result.push(createModifier(123 /* PrivateKeyword */)); + if (flags2 & 4 /* Protected */) result.push(createModifier(124 /* ProtectedKeyword */)); + if (flags2 & 64 /* Abstract */) result.push(createModifier(128 /* AbstractKeyword */)); + if (flags2 & 256 /* Static */) result.push(createModifier(126 /* StaticKeyword */)); + if (flags2 & 16 /* Override */) result.push(createModifier(164 /* OverrideKeyword */)); + if (flags2 & 8 /* Readonly */) result.push(createModifier(148 /* ReadonlyKeyword */)); + if (flags2 & 512 /* Accessor */) result.push(createModifier(129 /* AccessorKeyword */)); + if (flags2 & 1024 /* Async */) result.push(createModifier(134 /* AsyncKeyword */)); + if (flags2 & 8192 /* In */) result.push(createModifier(103 /* InKeyword */)); + if (flags2 & 16384 /* Out */) result.push(createModifier(147 /* OutKeyword */)); + return result.length ? result : void 0; + } + function createQualifiedName(left, right) { + const node = createBaseNode(166 /* QualifiedName */); + node.left = left; + node.right = asName(right); + node.transformFlags |= propagateChildFlags(node.left) | propagateIdentifierNameFlags(node.right); + node.flowNode = void 0; + return node; + } + function updateQualifiedName(node, left, right) { + return node.left !== left || node.right !== right ? update(createQualifiedName(left, right), node) : node; + } + function createComputedPropertyName(expression) { + const node = createBaseNode(167 /* ComputedPropertyName */); + node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); + node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* ContainsES2015 */ | 131072 /* ContainsComputedPropertyName */; + return node; + } + function updateComputedPropertyName(node, expression) { + return node.expression !== expression ? update(createComputedPropertyName(expression), node) : node; + } + function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { + const node = createBaseDeclaration(168 /* TypeParameter */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.constraint = constraint; + node.default = defaultType; + node.transformFlags = 1 /* ContainsTypeScript */; + node.expression = void 0; + node.jsDoc = void 0; + return node; + } + function updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType) { + return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint || node.default !== defaultType ? update(createTypeParameterDeclaration(modifiers, name, constraint, defaultType), node) : node; + } + function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { + const node = createBaseDeclaration(169 /* Parameter */); + node.modifiers = asNodeArray(modifiers); + node.dotDotDotToken = dotDotDotToken; + node.name = asName(name); + node.questionToken = questionToken; + node.type = type; + node.initializer = asInitializer(initializer); + if (isThisIdentifier(node.name)) { + node.transformFlags = 1 /* ContainsTypeScript */; + } else { + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.initializer) | (node.questionToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (node.dotDotDotToken ?? node.initializer ? 1024 /* ContainsES2015 */ : 0 /* None */) | (modifiersToFlags(node.modifiers) & 31 /* ParameterPropertyModifier */ ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */); + } + node.jsDoc = void 0; + return node; + } + function updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; + } + function createDecorator(expression) { + const node = createBaseNode(170 /* Decorator */); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + false + ); + node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ | 8192 /* ContainsTypeScriptClassSyntax */ | 33554432 /* ContainsDecorators */; + return node; + } + function updateDecorator(node, expression) { + return node.expression !== expression ? update(createDecorator(expression), node) : node; + } + function createPropertySignature(modifiers, name, questionToken, type) { + const node = createBaseDeclaration(171 /* PropertySignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.type = type; + node.questionToken = questionToken; + node.transformFlags = 1 /* ContainsTypeScript */; + node.initializer = void 0; + node.jsDoc = void 0; + return node; + } + function updatePropertySignature(node, modifiers, name, questionToken, type) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== questionToken || node.type !== type ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node; + } + function finishUpdatePropertySignature(updated, original) { + if (updated !== original) { + updated.initializer = original.initializer; + } + return update(updated, original); + } + function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { + const node = createBaseDeclaration(172 /* PropertyDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionOrExclamationToken && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0; + node.exclamationToken = questionOrExclamationToken && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0; + node.type = type; + node.initializer = asInitializer(initializer); + const isAmbient = node.flags & 33554432 /* Ambient */ || modifiersToFlags(node.modifiers) & 128 /* Ambient */; + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (isAmbient || node.questionToken || node.exclamationToken || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (isComputedPropertyName(node.name) || modifiersToFlags(node.modifiers) & 256 /* Static */ && node.initializer ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */) | 16777216 /* ContainsClassFields */; + node.jsDoc = void 0; + return node; + } + function updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== void 0 && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0) || node.exclamationToken !== (questionOrExclamationToken !== void 0 && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : void 0) || node.type !== type || node.initializer !== initializer ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; + } + function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { + const node = createBaseDeclaration(173 /* MethodSignature */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.questionToken = questionToken; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.typeArguments = void 0; + return node; + } + function updateMethodSignature(node, modifiers, name, questionToken, typeParameters, parameters, type) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; + } + function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + const node = createBaseDeclaration(174 /* MethodDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.questionToken = questionToken; + node.exclamationToken = void 0; + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + if (!node.body) { + node.transformFlags = 1 /* ContainsTypeScript */; + } else { + const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */; + const isGenerator = !!node.asteriskToken; + const isAsyncGenerator = isAsync && isGenerator; + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.questionToken || node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 1024 /* ContainsES2015 */; + } + node.typeArguments = void 0; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.flowNode = void 0; + node.endFlowNode = void 0; + node.returnFlowNode = void 0; + return node; + } + function updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; + } + function finishUpdateMethodDeclaration(updated, original) { + if (updated !== original) { + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } + function createClassStaticBlockDeclaration(body) { + const node = createBaseDeclaration(175 /* ClassStaticBlockDeclaration */); + node.body = body; + node.transformFlags = propagateChildFlags(body) | 16777216 /* ContainsClassFields */; + node.modifiers = void 0; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.endFlowNode = void 0; + node.returnFlowNode = void 0; + return node; + } + function updateClassStaticBlockDeclaration(node, body) { + return node.body !== body ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) : node; + } + function finishUpdateClassStaticBlockDeclaration(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return update(updated, original); + } + function createConstructorDeclaration(modifiers, parameters, body) { + const node = createBaseDeclaration(176 /* Constructor */); + node.modifiers = asNodeArray(modifiers); + node.parameters = createNodeArray(parameters); + node.body = body; + if (!node.body) { + node.transformFlags = 1 /* ContainsTypeScript */; + } else { + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | 1024 /* ContainsES2015 */; + } + node.typeParameters = void 0; + node.type = void 0; + node.typeArguments = void 0; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.endFlowNode = void 0; + node.returnFlowNode = void 0; + return node; + } + function updateConstructorDeclaration(node, modifiers, parameters, body) { + return node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node; + } + function finishUpdateConstructorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } + function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { + const node = createBaseDeclaration(177 /* GetAccessor */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + if (!node.body) { + node.transformFlags = 1 /* ContainsTypeScript */; + } else { + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.type ? 1 /* ContainsTypeScript */ : 0 /* None */); + } + node.typeArguments = void 0; + node.typeParameters = void 0; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.flowNode = void 0; + node.endFlowNode = void 0; + node.returnFlowNode = void 0; + return node; + } + function updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node; + } + function finishUpdateGetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } + function createSetAccessorDeclaration(modifiers, name, parameters, body) { + const node = createBaseDeclaration(178 /* SetAccessor */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.parameters = createNodeArray(parameters); + node.body = body; + if (!node.body) { + node.transformFlags = 1 /* ContainsTypeScript */; + } else { + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.type ? 1 /* ContainsTypeScript */ : 0 /* None */); + } + node.typeArguments = void 0; + node.typeParameters = void 0; + node.type = void 0; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.flowNode = void 0; + node.endFlowNode = void 0; + node.returnFlowNode = void 0; + return node; + } + function updateSetAccessorDeclaration(node, modifiers, name, parameters, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node; + } + function finishUpdateSetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } + function createCallSignature(typeParameters, parameters, type) { + const node = createBaseDeclaration(179 /* CallSignature */); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.typeArguments = void 0; + return node; + } + function updateCallSignature(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; + } + function createConstructSignature(typeParameters, parameters, type) { + const node = createBaseDeclaration(180 /* ConstructSignature */); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.typeArguments = void 0; + return node; + } + function updateConstructSignature(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; + } + function createIndexSignature(modifiers, parameters, type) { + const node = createBaseDeclaration(181 /* IndexSignature */); + node.modifiers = asNodeArray(modifiers); + node.parameters = asNodeArray(parameters); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.typeArguments = void 0; + return node; + } + function updateIndexSignature(node, modifiers, parameters, type) { + return node.parameters !== parameters || node.type !== type || node.modifiers !== modifiers ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; + } + function createTemplateLiteralTypeSpan(type, literal) { + const node = createBaseNode(204 /* TemplateLiteralTypeSpan */); + node.type = type; + node.literal = literal; + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateTemplateLiteralTypeSpan(node, type, literal) { + return node.type !== type || node.literal !== literal ? update(createTemplateLiteralTypeSpan(type, literal), node) : node; + } + function createKeywordTypeNode(kind) { + return createToken(kind); + } + function createTypePredicateNode(assertsModifier, parameterName, type) { + const node = createBaseNode(182 /* TypePredicate */); + node.assertsModifier = assertsModifier; + node.parameterName = asName(parameterName); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateTypePredicateNode(node, assertsModifier, parameterName, type) { + return node.assertsModifier !== assertsModifier || node.parameterName !== parameterName || node.type !== type ? update(createTypePredicateNode(assertsModifier, parameterName, type), node) : node; + } + function createTypeReferenceNode(typeName, typeArguments) { + const node = createBaseNode(183 /* TypeReference */); + node.typeName = asName(typeName); + node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateTypeReferenceNode(node, typeName, typeArguments) { + return node.typeName !== typeName || node.typeArguments !== typeArguments ? update(createTypeReferenceNode(typeName, typeArguments), node) : node; + } + function createFunctionTypeNode(typeParameters, parameters, type) { + const node = createBaseDeclaration(184 /* FunctionType */); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + node.modifiers = void 0; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.typeArguments = void 0; + return node; + } + function updateFunctionTypeNode(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node; + } + function finishUpdateFunctionTypeNode(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } + function createConstructorTypeNode(...args) { + return args.length === 4 ? createConstructorTypeNode1(...args) : args.length === 3 ? createConstructorTypeNode2(...args) : Debug.fail("Incorrect number of arguments specified."); + } + function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { + const node = createBaseDeclaration(185 /* ConstructorType */); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = asNodeArray(parameters); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.typeArguments = void 0; + return node; + } + function createConstructorTypeNode2(typeParameters, parameters, type) { + return createConstructorTypeNode1( + /*modifiers*/ + void 0, + typeParameters, + parameters, + type + ); + } + function updateConstructorTypeNode(...args) { + return args.length === 5 ? updateConstructorTypeNode1(...args) : args.length === 4 ? updateConstructorTypeNode2(...args) : Debug.fail("Incorrect number of arguments specified."); + } + function updateConstructorTypeNode1(node, modifiers, typeParameters, parameters, type) { + return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; + } + function updateConstructorTypeNode2(node, typeParameters, parameters, type) { + return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type); + } + function createTypeQueryNode(exprName, typeArguments) { + const node = createBaseNode(186 /* TypeQuery */); + node.exprName = exprName; + node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateTypeQueryNode(node, exprName, typeArguments) { + return node.exprName !== exprName || node.typeArguments !== typeArguments ? update(createTypeQueryNode(exprName, typeArguments), node) : node; + } + function createTypeLiteralNode(members) { + const node = createBaseDeclaration(187 /* TypeLiteral */); + node.members = createNodeArray(members); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateTypeLiteralNode(node, members) { + return node.members !== members ? update(createTypeLiteralNode(members), node) : node; + } + function createArrayTypeNode(elementType) { + const node = createBaseNode(188 /* ArrayType */); + node.elementType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(elementType); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateArrayTypeNode(node, elementType) { + return node.elementType !== elementType ? update(createArrayTypeNode(elementType), node) : node; + } + function createTupleTypeNode(elements) { + const node = createBaseNode(189 /* TupleType */); + node.elements = createNodeArray(parenthesizerRules().parenthesizeElementTypesOfTupleType(elements)); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateTupleTypeNode(node, elements) { + return node.elements !== elements ? update(createTupleTypeNode(elements), node) : node; + } + function createNamedTupleMember(dotDotDotToken, name, questionToken, type) { + const node = createBaseDeclaration(202 /* NamedTupleMember */); + node.dotDotDotToken = dotDotDotToken; + node.name = name; + node.questionToken = questionToken; + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + node.jsDoc = void 0; + return node; + } + function updateNamedTupleMember(node, dotDotDotToken, name, questionToken, type) { + return node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node) : node; + } + function createOptionalTypeNode(type) { + const node = createBaseNode(190 /* OptionalType */); + node.type = parenthesizerRules().parenthesizeTypeOfOptionalType(type); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateOptionalTypeNode(node, type) { + return node.type !== type ? update(createOptionalTypeNode(type), node) : node; + } + function createRestTypeNode(type) { + const node = createBaseNode(191 /* RestType */); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateRestTypeNode(node, type) { + return node.type !== type ? update(createRestTypeNode(type), node) : node; + } + function createUnionOrIntersectionTypeNode(kind, types, parenthesize) { + const node = createBaseNode(kind); + node.types = factory2.createNodeArray(parenthesize(types)); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateUnionOrIntersectionTypeNode(node, types, parenthesize) { + return node.types !== types ? update(createUnionOrIntersectionTypeNode(node.kind, types, parenthesize), node) : node; + } + function createUnionTypeNode(types) { + return createUnionOrIntersectionTypeNode(192 /* UnionType */, types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType); + } + function updateUnionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType); + } + function createIntersectionTypeNode(types) { + return createUnionOrIntersectionTypeNode(193 /* IntersectionType */, types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType); + } + function updateIntersectionTypeNode(node, types) { + return updateUnionOrIntersectionTypeNode(node, types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType); + } + function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { + const node = createBaseNode(194 /* ConditionalType */); + node.checkType = parenthesizerRules().parenthesizeCheckTypeOfConditionalType(checkType); + node.extendsType = parenthesizerRules().parenthesizeExtendsTypeOfConditionalType(extendsType); + node.trueType = trueType; + node.falseType = falseType; + node.transformFlags = 1 /* ContainsTypeScript */; + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) { + return node.checkType !== checkType || node.extendsType !== extendsType || node.trueType !== trueType || node.falseType !== falseType ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) : node; + } + function createInferTypeNode(typeParameter) { + const node = createBaseNode(195 /* InferType */); + node.typeParameter = typeParameter; + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateInferTypeNode(node, typeParameter) { + return node.typeParameter !== typeParameter ? update(createInferTypeNode(typeParameter), node) : node; + } + function createTemplateLiteralType(head, templateSpans) { + const node = createBaseNode(203 /* TemplateLiteralType */); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateTemplateLiteralType(node, head, templateSpans) { + return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateLiteralType(head, templateSpans), node) : node; + } + function createImportTypeNode(argument, attributes, qualifier, typeArguments, isTypeOf = false) { + const node = createBaseNode(205 /* ImportType */); + node.argument = argument; + node.attributes = attributes; + if (node.assertions && node.assertions.assertClause && node.attributes) { + node.assertions.assertClause = node.attributes; + } + node.qualifier = qualifier; + node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); + node.isTypeOf = isTypeOf; + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateImportTypeNode(node, argument, attributes, qualifier, typeArguments, isTypeOf = node.isTypeOf) { + return node.argument !== argument || node.attributes !== attributes || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf ? update(createImportTypeNode(argument, attributes, qualifier, typeArguments, isTypeOf), node) : node; + } + function createParenthesizedType(type) { + const node = createBaseNode(196 /* ParenthesizedType */); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateParenthesizedType(node, type) { + return node.type !== type ? update(createParenthesizedType(type), node) : node; + } + function createThisTypeNode() { + const node = createBaseNode(197 /* ThisType */); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function createTypeOperatorNode(operator, type) { + const node = createBaseNode(198 /* TypeOperator */); + node.operator = operator; + node.type = operator === 148 /* ReadonlyKeyword */ ? parenthesizerRules().parenthesizeOperandOfReadonlyTypeOperator(type) : parenthesizerRules().parenthesizeOperandOfTypeOperator(type); + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateTypeOperatorNode(node, type) { + return node.type !== type ? update(createTypeOperatorNode(node.operator, type), node) : node; + } + function createIndexedAccessTypeNode(objectType, indexType) { + const node = createBaseNode(199 /* IndexedAccessType */); + node.objectType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(objectType); + node.indexType = indexType; + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateIndexedAccessTypeNode(node, objectType, indexType) { + return node.objectType !== objectType || node.indexType !== indexType ? update(createIndexedAccessTypeNode(objectType, indexType), node) : node; + } + function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) { + const node = createBaseDeclaration(200 /* MappedType */); + node.readonlyToken = readonlyToken; + node.typeParameter = typeParameter; + node.nameType = nameType; + node.questionToken = questionToken; + node.type = type; + node.members = members && createNodeArray(members); + node.transformFlags = 1 /* ContainsTypeScript */; + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) { + return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type || node.members !== members ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; + } + function createLiteralTypeNode(literal) { + const node = createBaseNode(201 /* LiteralType */); + node.literal = literal; + node.transformFlags = 1 /* ContainsTypeScript */; + return node; + } + function updateLiteralTypeNode(node, literal) { + return node.literal !== literal ? update(createLiteralTypeNode(literal), node) : node; + } + function createObjectBindingPattern(elements) { + const node = createBaseNode(206 /* ObjectBindingPattern */); + node.elements = createNodeArray(elements); + node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* ContainsES2015 */ | 524288 /* ContainsBindingPattern */; + if (node.transformFlags & 32768 /* ContainsRestOrSpread */) { + node.transformFlags |= 128 /* ContainsES2018 */ | 65536 /* ContainsObjectRestOrSpread */; + } + return node; + } + function updateObjectBindingPattern(node, elements) { + return node.elements !== elements ? update(createObjectBindingPattern(elements), node) : node; + } + function createArrayBindingPattern(elements) { + const node = createBaseNode(207 /* ArrayBindingPattern */); + node.elements = createNodeArray(elements); + node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* ContainsES2015 */ | 524288 /* ContainsBindingPattern */; + return node; + } + function updateArrayBindingPattern(node, elements) { + return node.elements !== elements ? update(createArrayBindingPattern(elements), node) : node; + } + function createBindingElement(dotDotDotToken, propertyName, name, initializer) { + const node = createBaseDeclaration(208 /* BindingElement */); + node.dotDotDotToken = dotDotDotToken; + node.propertyName = asName(propertyName); + node.name = asName(name); + node.initializer = asInitializer(initializer); + node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.propertyName) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (node.dotDotDotToken ? 32768 /* ContainsRestOrSpread */ : 0 /* None */) | 1024 /* ContainsES2015 */; + node.flowNode = void 0; + return node; + } + function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { + return node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) : node; + } + function createArrayLiteralExpression(elements, multiLine) { + const node = createBaseNode(209 /* ArrayLiteralExpression */); + const lastElement = elements && lastOrUndefined(elements); + const elementsArray = createNodeArray(elements, lastElement && isOmittedExpression(lastElement) ? true : void 0); + node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(elementsArray); + node.multiLine = multiLine; + node.transformFlags |= propagateChildrenFlags(node.elements); + return node; + } + function updateArrayLiteralExpression(node, elements) { + return node.elements !== elements ? update(createArrayLiteralExpression(elements, node.multiLine), node) : node; + } + function createObjectLiteralExpression(properties, multiLine) { + const node = createBaseDeclaration(210 /* ObjectLiteralExpression */); + node.properties = createNodeArray(properties); + node.multiLine = multiLine; + node.transformFlags |= propagateChildrenFlags(node.properties); + node.jsDoc = void 0; + return node; + } + function updateObjectLiteralExpression(node, properties) { + return node.properties !== properties ? update(createObjectLiteralExpression(properties, node.multiLine), node) : node; + } + function createBasePropertyAccessExpression(expression, questionDotToken, name) { + const node = createBaseDeclaration(211 /* PropertyAccessExpression */); + node.expression = expression; + node.questionDotToken = questionDotToken; + node.name = name; + node.transformFlags = propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : propagateChildFlags(node.name) | 536870912 /* ContainsPrivateIdentifierInExpression */); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function createPropertyAccessExpression(expression, name) { + const node = createBasePropertyAccessExpression( + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + false + ), + /*questionDotToken*/ + void 0, + asName(name) + ); + if (isSuperKeyword(expression)) { + node.transformFlags |= 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */; + } + return node; + } + function updatePropertyAccessExpression(node, expression, name) { + if (isPropertyAccessChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, cast(name, isIdentifier)); + } + return node.expression !== expression || node.name !== name ? update(createPropertyAccessExpression(expression, name), node) : node; + } + function createPropertyAccessChain(expression, questionDotToken, name) { + const node = createBasePropertyAccessExpression( + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + true + ), + questionDotToken, + asName(name) + ); + node.flags |= 64 /* OptionalChain */; + node.transformFlags |= 32 /* ContainsES2020 */; + return node; + } + function updatePropertyAccessChain(node, expression, questionDotToken, name) { + Debug.assert(!!(node.flags & 64 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead."); + return node.expression !== expression || node.questionDotToken !== questionDotToken || node.name !== name ? update(createPropertyAccessChain(expression, questionDotToken, name), node) : node; + } + function createBaseElementAccessExpression(expression, questionDotToken, argumentExpression) { + const node = createBaseDeclaration(212 /* ElementAccessExpression */); + node.expression = expression; + node.questionDotToken = questionDotToken; + node.argumentExpression = argumentExpression; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function createElementAccessExpression(expression, index) { + const node = createBaseElementAccessExpression( + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + false + ), + /*questionDotToken*/ + void 0, + asExpression(index) + ); + if (isSuperKeyword(expression)) { + node.transformFlags |= 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */; + } + return node; + } + function updateElementAccessExpression(node, expression, argumentExpression) { + if (isElementAccessChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } + return node.expression !== expression || node.argumentExpression !== argumentExpression ? update(createElementAccessExpression(expression, argumentExpression), node) : node; + } + function createElementAccessChain(expression, questionDotToken, index) { + const node = createBaseElementAccessExpression( + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + true + ), + questionDotToken, + asExpression(index) + ); + node.flags |= 64 /* OptionalChain */; + node.transformFlags |= 32 /* ContainsES2020 */; + return node; + } + function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) { + Debug.assert(!!(node.flags & 64 /* OptionalChain */), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead."); + return node.expression !== expression || node.questionDotToken !== questionDotToken || node.argumentExpression !== argumentExpression ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node) : node; + } + function createBaseCallExpression(expression, questionDotToken, typeArguments, argumentsArray) { + const node = createBaseDeclaration(213 /* CallExpression */); + node.expression = expression; + node.questionDotToken = questionDotToken; + node.typeArguments = typeArguments; + node.arguments = argumentsArray; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments); + if (node.typeArguments) { + node.transformFlags |= 1 /* ContainsTypeScript */; + } + if (isSuperProperty(node.expression)) { + node.transformFlags |= 16384 /* ContainsLexicalThis */; + } + return node; + } + function createCallExpression(expression, typeArguments, argumentsArray) { + const node = createBaseCallExpression( + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + false + ), + /*questionDotToken*/ + void 0, + asNodeArray(typeArguments), + parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)) + ); + if (isImportKeyword(node.expression)) { + node.transformFlags |= 8388608 /* ContainsDynamicImport */; + } + return node; + } + function updateCallExpression(node, expression, typeArguments, argumentsArray) { + if (isCallChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } + return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray ? update(createCallExpression(expression, typeArguments, argumentsArray), node) : node; + } + function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { + const node = createBaseCallExpression( + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + true + ), + questionDotToken, + asNodeArray(typeArguments), + parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)) + ); + node.flags |= 64 /* OptionalChain */; + node.transformFlags |= 32 /* ContainsES2020 */; + return node; + } + function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) { + Debug.assert(!!(node.flags & 64 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead."); + return node.expression !== expression || node.questionDotToken !== questionDotToken || node.typeArguments !== typeArguments || node.arguments !== argumentsArray ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node) : node; + } + function createNewExpression(expression, typeArguments, argumentsArray) { + const node = createBaseDeclaration(214 /* NewExpression */); + node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); + node.typeArguments = asNodeArray(typeArguments); + node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : void 0; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | 32 /* ContainsES2020 */; + if (node.typeArguments) { + node.transformFlags |= 1 /* ContainsTypeScript */; + } + return node; + } + function updateNewExpression(node, expression, typeArguments, argumentsArray) { + return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray ? update(createNewExpression(expression, typeArguments, argumentsArray), node) : node; + } + function createTaggedTemplateExpression(tag, typeArguments, template) { + const node = createBaseNode(215 /* TaggedTemplateExpression */); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess( + tag, + /*optionalChain*/ + false + ); + node.typeArguments = asNodeArray(typeArguments); + node.template = template; + node.transformFlags |= propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | 1024 /* ContainsES2015 */; + if (node.typeArguments) { + node.transformFlags |= 1 /* ContainsTypeScript */; + } + if (hasInvalidEscape(node.template)) { + node.transformFlags |= 128 /* ContainsES2018 */; + } + return node; + } + function updateTaggedTemplateExpression(node, tag, typeArguments, template) { + return node.tag !== tag || node.typeArguments !== typeArguments || node.template !== template ? update(createTaggedTemplateExpression(tag, typeArguments, template), node) : node; + } + function createTypeAssertion(type, expression) { + const node = createBaseNode(216 /* TypeAssertionExpression */); + node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); + node.type = type; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | 1 /* ContainsTypeScript */; + return node; + } + function updateTypeAssertion(node, type, expression) { + return node.type !== type || node.expression !== expression ? update(createTypeAssertion(type, expression), node) : node; + } + function createParenthesizedExpression(expression) { + const node = createBaseNode(217 /* ParenthesizedExpression */); + node.expression = expression; + node.transformFlags = propagateChildFlags(node.expression); + node.jsDoc = void 0; + return node; + } + function updateParenthesizedExpression(node, expression) { + return node.expression !== expression ? update(createParenthesizedExpression(expression), node) : node; + } + function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + const node = createBaseDeclaration(218 /* FunctionExpression */); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */; + const isGenerator = !!node.asteriskToken; + const isAsyncGenerator = isAsync && isGenerator; + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 4194304 /* ContainsHoistedDeclarationOrCompletion */; + node.typeArguments = void 0; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.flowNode = void 0; + node.endFlowNode = void 0; + node.returnFlowNode = void 0; + return node; + } + function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.name !== name || node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; + } + function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + const node = createBaseDeclaration(219 /* ArrowFunction */); + node.modifiers = asNodeArray(modifiers); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.equalsGreaterThanToken = equalsGreaterThanToken ?? createToken(39 /* EqualsGreaterThanToken */); + node.body = parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body); + const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */; + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.equalsGreaterThanToken) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (isAsync ? 256 /* ContainsES2017 */ | 16384 /* ContainsLexicalThis */ : 0 /* None */) | 1024 /* ContainsES2015 */; + node.typeArguments = void 0; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.flowNode = void 0; + node.endFlowNode = void 0; + node.returnFlowNode = void 0; + return node; + } + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { + return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; + } + function createDeleteExpression(expression) { + const node = createBaseNode(220 /* DeleteExpression */); + node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); + node.transformFlags |= propagateChildFlags(node.expression); + return node; + } + function updateDeleteExpression(node, expression) { + return node.expression !== expression ? update(createDeleteExpression(expression), node) : node; + } + function createTypeOfExpression(expression) { + const node = createBaseNode(221 /* TypeOfExpression */); + node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); + node.transformFlags |= propagateChildFlags(node.expression); + return node; + } + function updateTypeOfExpression(node, expression) { + return node.expression !== expression ? update(createTypeOfExpression(expression), node) : node; + } + function createVoidExpression(expression) { + const node = createBaseNode(222 /* VoidExpression */); + node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); + node.transformFlags |= propagateChildFlags(node.expression); + return node; + } + function updateVoidExpression(node, expression) { + return node.expression !== expression ? update(createVoidExpression(expression), node) : node; + } + function createAwaitExpression(expression) { + const node = createBaseNode(223 /* AwaitExpression */); + node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); + node.transformFlags |= propagateChildFlags(node.expression) | 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */ | 2097152 /* ContainsAwait */; + return node; + } + function updateAwaitExpression(node, expression) { + return node.expression !== expression ? update(createAwaitExpression(expression), node) : node; + } + function createPrefixUnaryExpression(operator, operand) { + const node = createBaseNode(224 /* PrefixUnaryExpression */); + node.operator = operator; + node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); + node.transformFlags |= propagateChildFlags(node.operand); + if ((operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand)) { + node.transformFlags |= 268435456 /* ContainsUpdateExpressionForIdentifier */; + } + return node; + } + function updatePrefixUnaryExpression(node, operand) { + return node.operand !== operand ? update(createPrefixUnaryExpression(node.operator, operand), node) : node; + } + function createPostfixUnaryExpression(operand, operator) { + const node = createBaseNode(225 /* PostfixUnaryExpression */); + node.operator = operator; + node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); + node.transformFlags |= propagateChildFlags(node.operand); + if (isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand)) { + node.transformFlags |= 268435456 /* ContainsUpdateExpressionForIdentifier */; + } + return node; + } + function updatePostfixUnaryExpression(node, operand) { + return node.operand !== operand ? update(createPostfixUnaryExpression(operand, node.operator), node) : node; + } + function createBinaryExpression(left, operator, right) { + const node = createBaseDeclaration(226 /* BinaryExpression */); + const operatorToken = asToken(operator); + const operatorKind = operatorToken.kind; + node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); + node.operatorToken = operatorToken; + node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right); + node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); + if (operatorKind === 61 /* QuestionQuestionToken */) { + node.transformFlags |= 32 /* ContainsES2020 */; + } else if (operatorKind === 64 /* EqualsToken */) { + if (isObjectLiteralExpression(node.left)) { + node.transformFlags |= 1024 /* ContainsES2015 */ | 128 /* ContainsES2018 */ | 4096 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); + } else if (isArrayLiteralExpression(node.left)) { + node.transformFlags |= 1024 /* ContainsES2015 */ | 4096 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); + } + } else if (operatorKind === 43 /* AsteriskAsteriskToken */ || operatorKind === 68 /* AsteriskAsteriskEqualsToken */) { + node.transformFlags |= 512 /* ContainsES2016 */; + } else if (isLogicalOrCoalescingAssignmentOperator(operatorKind)) { + node.transformFlags |= 16 /* ContainsES2021 */; + } + if (operatorKind === 103 /* InKeyword */ && isPrivateIdentifier(node.left)) { + node.transformFlags |= 536870912 /* ContainsPrivateIdentifierInExpression */; + } + node.jsDoc = void 0; + return node; + } + function propagateAssignmentPatternFlags(node) { + return containsObjectRestOrSpread(node) ? 65536 /* ContainsObjectRestOrSpread */ : 0 /* None */; + } + function updateBinaryExpression(node, left, operator, right) { + return node.left !== left || node.operatorToken !== operator || node.right !== right ? update(createBinaryExpression(left, operator, right), node) : node; + } + function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { + const node = createBaseNode(227 /* ConditionalExpression */); + node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); + node.questionToken = questionToken ?? createToken(58 /* QuestionToken */); + node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); + node.colonToken = colonToken ?? createToken(59 /* ColonToken */); + node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse); + node.transformFlags |= propagateChildFlags(node.condition) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.whenTrue) | propagateChildFlags(node.colonToken) | propagateChildFlags(node.whenFalse); + node.flowNodeWhenFalse = void 0; + node.flowNodeWhenTrue = void 0; + return node; + } + function updateConditionalExpression(node, condition, questionToken, whenTrue, colonToken, whenFalse) { + return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue || node.colonToken !== colonToken || node.whenFalse !== whenFalse ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node; + } + function createTemplateExpression(head, templateSpans) { + const node = createBaseNode(228 /* TemplateExpression */); + node.head = head; + node.templateSpans = createNodeArray(templateSpans); + node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | 1024 /* ContainsES2015 */; + return node; + } + function updateTemplateExpression(node, head, templateSpans) { + return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateExpression(head, templateSpans), node) : node; + } + function checkTemplateLiteralLikeNode(kind, text, rawText, templateFlags = 0 /* None */) { + Debug.assert(!(templateFlags & ~7176 /* TemplateLiteralLikeFlags */), "Unsupported template flags."); + let cooked = void 0; + if (rawText !== void 0 && rawText !== text) { + cooked = getCookedText(kind, rawText); + if (typeof cooked === "object") { + return Debug.fail("Invalid raw text"); + } + } + if (text === void 0) { + if (cooked === void 0) { + return Debug.fail("Arguments 'text' and 'rawText' may not both be undefined."); + } + text = cooked; + } else if (cooked !== void 0) { + Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'."); + } + return text; + } + function getTransformFlagsOfTemplateLiteralLike(templateFlags) { + let transformFlags = 1024 /* ContainsES2015 */; + if (templateFlags) { + transformFlags |= 128 /* ContainsES2018 */; + } + return transformFlags; + } + function createTemplateLiteralLikeToken(kind, text, rawText, templateFlags) { + const node = createBaseToken(kind); + node.text = text; + node.rawText = rawText; + node.templateFlags = templateFlags & 7176 /* TemplateLiteralLikeFlags */; + node.transformFlags = getTransformFlagsOfTemplateLiteralLike(node.templateFlags); + return node; + } + function createTemplateLiteralLikeDeclaration(kind, text, rawText, templateFlags) { + const node = createBaseDeclaration(kind); + node.text = text; + node.rawText = rawText; + node.templateFlags = templateFlags & 7176 /* TemplateLiteralLikeFlags */; + node.transformFlags = getTransformFlagsOfTemplateLiteralLike(node.templateFlags); + return node; + } + function createTemplateLiteralLikeNode(kind, text, rawText, templateFlags) { + if (kind === 15 /* NoSubstitutionTemplateLiteral */) { + return createTemplateLiteralLikeDeclaration(kind, text, rawText, templateFlags); + } + return createTemplateLiteralLikeToken(kind, text, rawText, templateFlags); + } + function createTemplateHead(text, rawText, templateFlags) { + text = checkTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags); + return createTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags); + } + function createTemplateMiddle(text, rawText, templateFlags) { + text = checkTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags); + return createTemplateLiteralLikeNode(17 /* TemplateMiddle */, text, rawText, templateFlags); + } + function createTemplateTail(text, rawText, templateFlags) { + text = checkTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags); + return createTemplateLiteralLikeNode(18 /* TemplateTail */, text, rawText, templateFlags); + } + function createNoSubstitutionTemplateLiteral(text, rawText, templateFlags) { + text = checkTemplateLiteralLikeNode(16 /* TemplateHead */, text, rawText, templateFlags); + return createTemplateLiteralLikeDeclaration(15 /* NoSubstitutionTemplateLiteral */, text, rawText, templateFlags); + } + function createYieldExpression(asteriskToken, expression) { + Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); + const node = createBaseNode(229 /* YieldExpression */); + node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + node.asteriskToken = asteriskToken; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | 1024 /* ContainsES2015 */ | 128 /* ContainsES2018 */ | 1048576 /* ContainsYield */; + return node; + } + function updateYieldExpression(node, asteriskToken, expression) { + return node.expression !== expression || node.asteriskToken !== asteriskToken ? update(createYieldExpression(asteriskToken, expression), node) : node; + } + function createSpreadElement(expression) { + const node = createBaseNode(230 /* SpreadElement */); + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* ContainsES2015 */ | 32768 /* ContainsRestOrSpread */; + return node; + } + function updateSpreadElement(node, expression) { + return node.expression !== expression ? update(createSpreadElement(expression), node) : node; + } + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + const node = createBaseDeclaration(231 /* ClassExpression */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.heritageClauses) | propagateChildrenFlags(node.members) | (node.typeParameters ? 1 /* ContainsTypeScript */ : 0 /* None */) | 1024 /* ContainsES2015 */; + node.jsDoc = void 0; + return node; + } + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; + } + function createOmittedExpression() { + return createBaseNode(232 /* OmittedExpression */); + } + function createExpressionWithTypeArguments(expression, typeArguments) { + const node = createBaseNode(233 /* ExpressionWithTypeArguments */); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + false + ); + node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | 1024 /* ContainsES2015 */; + return node; + } + function updateExpressionWithTypeArguments(node, expression, typeArguments) { + return node.expression !== expression || node.typeArguments !== typeArguments ? update(createExpressionWithTypeArguments(expression, typeArguments), node) : node; + } + function createAsExpression(expression, type) { + const node = createBaseNode(234 /* AsExpression */); + node.expression = expression; + node.type = type; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | 1 /* ContainsTypeScript */; + return node; + } + function updateAsExpression(node, expression, type) { + return node.expression !== expression || node.type !== type ? update(createAsExpression(expression, type), node) : node; + } + function createNonNullExpression(expression) { + const node = createBaseNode(235 /* NonNullExpression */); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + false + ); + node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */; + return node; + } + function updateNonNullExpression(node, expression) { + if (isNonNullChain(node)) { + return updateNonNullChain(node, expression); + } + return node.expression !== expression ? update(createNonNullExpression(expression), node) : node; + } + function createSatisfiesExpression(expression, type) { + const node = createBaseNode(238 /* SatisfiesExpression */); + node.expression = expression; + node.type = type; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | 1 /* ContainsTypeScript */; + return node; + } + function updateSatisfiesExpression(node, expression, type) { + return node.expression !== expression || node.type !== type ? update(createSatisfiesExpression(expression, type), node) : node; + } + function createNonNullChain(expression) { + const node = createBaseNode(235 /* NonNullExpression */); + node.flags |= 64 /* OptionalChain */; + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + true + ); + node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */; + return node; + } + function updateNonNullChain(node, expression) { + Debug.assert(!!(node.flags & 64 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead."); + return node.expression !== expression ? update(createNonNullChain(expression), node) : node; + } + function createMetaProperty(keywordToken, name) { + const node = createBaseNode(236 /* MetaProperty */); + node.keywordToken = keywordToken; + node.name = name; + node.transformFlags |= propagateChildFlags(node.name); + switch (keywordToken) { + case 105 /* NewKeyword */: + node.transformFlags |= 1024 /* ContainsES2015 */; + break; + case 102 /* ImportKeyword */: + node.transformFlags |= 32 /* ContainsES2020 */; + break; + default: + return Debug.assertNever(keywordToken); + } + node.flowNode = void 0; + return node; + } + function updateMetaProperty(node, name) { + return node.name !== name ? update(createMetaProperty(node.keywordToken, name), node) : node; + } + function createTemplateSpan(expression, literal) { + const node = createBaseNode(239 /* TemplateSpan */); + node.expression = expression; + node.literal = literal; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | 1024 /* ContainsES2015 */; + return node; + } + function updateTemplateSpan(node, expression, literal) { + return node.expression !== expression || node.literal !== literal ? update(createTemplateSpan(expression, literal), node) : node; + } + function createSemicolonClassElement() { + const node = createBaseNode(240 /* SemicolonClassElement */); + node.transformFlags |= 1024 /* ContainsES2015 */; + return node; + } + function createBlock(statements, multiLine) { + const node = createBaseNode(241 /* Block */); + node.statements = createNodeArray(statements); + node.multiLine = multiLine; + node.transformFlags |= propagateChildrenFlags(node.statements); + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateBlock(node, statements) { + return node.statements !== statements ? update(createBlock(statements, node.multiLine), node) : node; + } + function createVariableStatement(modifiers, declarationList) { + const node = createBaseNode(243 /* VariableStatement */); + node.modifiers = asNodeArray(modifiers); + node.declarationList = isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.declarationList); + if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) { + node.transformFlags = 1 /* ContainsTypeScript */; + } + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateVariableStatement(node, modifiers, declarationList) { + return node.modifiers !== modifiers || node.declarationList !== declarationList ? update(createVariableStatement(modifiers, declarationList), node) : node; + } + function createEmptyStatement() { + const node = createBaseNode(242 /* EmptyStatement */); + node.jsDoc = void 0; + return node; + } + function createExpressionStatement(expression) { + const node = createBaseNode(244 /* ExpressionStatement */); + node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); + node.transformFlags |= propagateChildFlags(node.expression); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateExpressionStatement(node, expression) { + return node.expression !== expression ? update(createExpressionStatement(expression), node) : node; + } + function createIfStatement(expression, thenStatement, elseStatement) { + const node = createBaseNode(245 /* IfStatement */); + node.expression = expression; + node.thenStatement = asEmbeddedStatement(thenStatement); + node.elseStatement = asEmbeddedStatement(elseStatement); + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thenStatement) | propagateChildFlags(node.elseStatement); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateIfStatement(node, expression, thenStatement, elseStatement) { + return node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement ? update(createIfStatement(expression, thenStatement, elseStatement), node) : node; + } + function createDoStatement(statement, expression) { + const node = createBaseNode(246 /* DoStatement */); + node.statement = asEmbeddedStatement(statement); + node.expression = expression; + node.transformFlags |= propagateChildFlags(node.statement) | propagateChildFlags(node.expression); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateDoStatement(node, statement, expression) { + return node.statement !== statement || node.expression !== expression ? update(createDoStatement(statement, expression), node) : node; + } + function createWhileStatement(expression, statement) { + const node = createBaseNode(247 /* WhileStatement */); + node.expression = expression; + node.statement = asEmbeddedStatement(statement); + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.statement); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateWhileStatement(node, expression, statement) { + return node.expression !== expression || node.statement !== statement ? update(createWhileStatement(expression, statement), node) : node; + } + function createForStatement(initializer, condition, incrementor, statement) { + const node = createBaseNode(248 /* ForStatement */); + node.initializer = initializer; + node.condition = condition; + node.incrementor = incrementor; + node.statement = asEmbeddedStatement(statement); + node.transformFlags |= propagateChildFlags(node.initializer) | propagateChildFlags(node.condition) | propagateChildFlags(node.incrementor) | propagateChildFlags(node.statement); + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.flowNode = void 0; + return node; + } + function updateForStatement(node, initializer, condition, incrementor, statement) { + return node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement ? update(createForStatement(initializer, condition, incrementor, statement), node) : node; + } + function createForInStatement(initializer, expression, statement) { + const node = createBaseNode(249 /* ForInStatement */); + node.initializer = initializer; + node.expression = expression; + node.statement = asEmbeddedStatement(statement); + node.transformFlags |= propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement); + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.flowNode = void 0; + return node; + } + function updateForInStatement(node, initializer, expression, statement) { + return node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? update(createForInStatement(initializer, expression, statement), node) : node; + } + function createForOfStatement(awaitModifier, initializer, expression, statement) { + const node = createBaseNode(250 /* ForOfStatement */); + node.awaitModifier = awaitModifier; + node.initializer = initializer; + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + node.statement = asEmbeddedStatement(statement); + node.transformFlags |= propagateChildFlags(node.awaitModifier) | propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | 1024 /* ContainsES2015 */; + if (awaitModifier) node.transformFlags |= 128 /* ContainsES2018 */; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.flowNode = void 0; + return node; + } + function updateForOfStatement(node, awaitModifier, initializer, expression, statement) { + return node.awaitModifier !== awaitModifier || node.initializer !== initializer || node.expression !== expression || node.statement !== statement ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node) : node; + } + function createContinueStatement(label) { + const node = createBaseNode(251 /* ContinueStatement */); + node.label = asName(label); + node.transformFlags |= propagateChildFlags(node.label) | 4194304 /* ContainsHoistedDeclarationOrCompletion */; + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateContinueStatement(node, label) { + return node.label !== label ? update(createContinueStatement(label), node) : node; + } + function createBreakStatement(label) { + const node = createBaseNode(252 /* BreakStatement */); + node.label = asName(label); + node.transformFlags |= propagateChildFlags(node.label) | 4194304 /* ContainsHoistedDeclarationOrCompletion */; + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateBreakStatement(node, label) { + return node.label !== label ? update(createBreakStatement(label), node) : node; + } + function createReturnStatement(expression) { + const node = createBaseNode(253 /* ReturnStatement */); + node.expression = expression; + node.transformFlags |= propagateChildFlags(node.expression) | 128 /* ContainsES2018 */ | 4194304 /* ContainsHoistedDeclarationOrCompletion */; + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateReturnStatement(node, expression) { + return node.expression !== expression ? update(createReturnStatement(expression), node) : node; + } + function createWithStatement(expression, statement) { + const node = createBaseNode(254 /* WithStatement */); + node.expression = expression; + node.statement = asEmbeddedStatement(statement); + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.statement); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateWithStatement(node, expression, statement) { + return node.expression !== expression || node.statement !== statement ? update(createWithStatement(expression, statement), node) : node; + } + function createSwitchStatement(expression, caseBlock) { + const node = createBaseNode(255 /* SwitchStatement */); + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + node.caseBlock = caseBlock; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.caseBlock); + node.jsDoc = void 0; + node.flowNode = void 0; + node.possiblyExhaustive = false; + return node; + } + function updateSwitchStatement(node, expression, caseBlock) { + return node.expression !== expression || node.caseBlock !== caseBlock ? update(createSwitchStatement(expression, caseBlock), node) : node; + } + function createLabeledStatement(label, statement) { + const node = createBaseNode(256 /* LabeledStatement */); + node.label = asName(label); + node.statement = asEmbeddedStatement(statement); + node.transformFlags |= propagateChildFlags(node.label) | propagateChildFlags(node.statement); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateLabeledStatement(node, label, statement) { + return node.label !== label || node.statement !== statement ? update(createLabeledStatement(label, statement), node) : node; + } + function createThrowStatement(expression) { + const node = createBaseNode(257 /* ThrowStatement */); + node.expression = expression; + node.transformFlags |= propagateChildFlags(node.expression); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateThrowStatement(node, expression) { + return node.expression !== expression ? update(createThrowStatement(expression), node) : node; + } + function createTryStatement(tryBlock, catchClause, finallyBlock) { + const node = createBaseNode(258 /* TryStatement */); + node.tryBlock = tryBlock; + node.catchClause = catchClause; + node.finallyBlock = finallyBlock; + node.transformFlags |= propagateChildFlags(node.tryBlock) | propagateChildFlags(node.catchClause) | propagateChildFlags(node.finallyBlock); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function updateTryStatement(node, tryBlock, catchClause, finallyBlock) { + return node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node) : node; + } + function createDebuggerStatement() { + const node = createBaseNode(259 /* DebuggerStatement */); + node.jsDoc = void 0; + node.flowNode = void 0; + return node; + } + function createVariableDeclaration(name, exclamationToken, type, initializer) { + const node = createBaseDeclaration(260 /* VariableDeclaration */); + node.name = asName(name); + node.exclamationToken = exclamationToken; + node.type = type; + node.initializer = asInitializer(initializer); + node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (node.exclamationToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */); + node.jsDoc = void 0; + return node; + } + function updateVariableDeclaration(node, name, exclamationToken, type, initializer) { + return node.name !== name || node.type !== type || node.exclamationToken !== exclamationToken || node.initializer !== initializer ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node) : node; + } + function createVariableDeclarationList(declarations, flags2 = 0 /* None */) { + const node = createBaseNode(261 /* VariableDeclarationList */); + node.flags |= flags2 & 7 /* BlockScoped */; + node.declarations = createNodeArray(declarations); + node.transformFlags |= propagateChildrenFlags(node.declarations) | 4194304 /* ContainsHoistedDeclarationOrCompletion */; + if (flags2 & 7 /* BlockScoped */) { + node.transformFlags |= 1024 /* ContainsES2015 */ | 262144 /* ContainsBlockScopedBinding */; + } + if (flags2 & 4 /* Using */) { + node.transformFlags |= 4 /* ContainsESNext */; + } + return node; + } + function updateVariableDeclarationList(node, declarations) { + return node.declarations !== declarations ? update(createVariableDeclarationList(declarations, node.flags), node) : node; + } + function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + const node = createBaseDeclaration(262 /* FunctionDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.asteriskToken = asteriskToken; + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.body = body; + if (!node.body || modifiersToFlags(node.modifiers) & 128 /* Ambient */) { + node.transformFlags = 1 /* ContainsTypeScript */; + } else { + const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */; + const isGenerator = !!node.asteriskToken; + const isAsyncGenerator = isAsync && isGenerator; + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 4194304 /* ContainsHoistedDeclarationOrCompletion */; + } + node.typeArguments = void 0; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.endFlowNode = void 0; + node.returnFlowNode = void 0; + return node; + } + function updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; + } + function finishUpdateFunctionDeclaration(updated, original) { + if (updated !== original) { + if (updated.modifiers === original.modifiers) { + updated.modifiers = original.modifiers; + } + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } + function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + const node = createBaseDeclaration(263 /* ClassDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) { + node.transformFlags = 1 /* ContainsTypeScript */; + } else { + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.heritageClauses) | propagateChildrenFlags(node.members) | (node.typeParameters ? 1 /* ContainsTypeScript */ : 0 /* None */) | 1024 /* ContainsES2015 */; + if (node.transformFlags & 8192 /* ContainsTypeScriptClassSyntax */) { + node.transformFlags |= 1 /* ContainsTypeScript */; + } + } + node.jsDoc = void 0; + return node; + } + function updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; + } + function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + const node = createBaseDeclaration(264 /* InterfaceDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.heritageClauses = asNodeArray(heritageClauses); + node.members = createNodeArray(members); + node.transformFlags = 1 /* ContainsTypeScript */; + node.jsDoc = void 0; + return node; + } + function updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members ? update(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; + } + function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { + const node = createBaseDeclaration(265 /* TypeAliasDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.typeParameters = asNodeArray(typeParameters); + node.type = type; + node.transformFlags = 1 /* ContainsTypeScript */; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type ? update(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; + } + function createEnumDeclaration(modifiers, name, members) { + const node = createBaseDeclaration(266 /* EnumDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.members = createNodeArray(members); + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.name) | propagateChildrenFlags(node.members) | 1 /* ContainsTypeScript */; + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + node.jsDoc = void 0; + return node; + } + function updateEnumDeclaration(node, modifiers, name, members) { + return node.modifiers !== modifiers || node.name !== name || node.members !== members ? update(createEnumDeclaration(modifiers, name, members), node) : node; + } + function createModuleDeclaration(modifiers, name, body, flags2 = 0 /* None */) { + const node = createBaseDeclaration(267 /* ModuleDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.flags |= flags2 & (32 /* Namespace */ | 8 /* NestedNamespace */ | 2048 /* GlobalAugmentation */); + node.name = name; + node.body = body; + if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) { + node.transformFlags = 1 /* ContainsTypeScript */; + } else { + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* ContainsTypeScript */; + } + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateModuleDeclaration(node, modifiers, name, body) { + return node.modifiers !== modifiers || node.name !== name || node.body !== body ? update(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; + } + function createModuleBlock(statements) { + const node = createBaseNode(268 /* ModuleBlock */); + node.statements = createNodeArray(statements); + node.transformFlags |= propagateChildrenFlags(node.statements); + node.jsDoc = void 0; + return node; + } + function updateModuleBlock(node, statements) { + return node.statements !== statements ? update(createModuleBlock(statements), node) : node; + } + function createCaseBlock(clauses) { + const node = createBaseNode(269 /* CaseBlock */); + node.clauses = createNodeArray(clauses); + node.transformFlags |= propagateChildrenFlags(node.clauses); + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateCaseBlock(node, clauses) { + return node.clauses !== clauses ? update(createCaseBlock(clauses), node) : node; + } + function createNamespaceExportDeclaration(name) { + const node = createBaseDeclaration(270 /* NamespaceExportDeclaration */); + node.name = asName(name); + node.transformFlags |= propagateIdentifierNameFlags(node.name) | 1 /* ContainsTypeScript */; + node.modifiers = void 0; + node.jsDoc = void 0; + return node; + } + function updateNamespaceExportDeclaration(node, name) { + return node.name !== name ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) : node; + } + function finishUpdateNamespaceExportDeclaration(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return update(updated, original); + } + function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { + const node = createBaseDeclaration(271 /* ImportEqualsDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.name = asName(name); + node.isTypeOnly = isTypeOnly; + node.moduleReference = moduleReference; + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateIdentifierNameFlags(node.name) | propagateChildFlags(node.moduleReference); + if (!isExternalModuleReference(node.moduleReference)) { + node.transformFlags |= 1 /* ContainsTypeScript */; + } + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + node.jsDoc = void 0; + return node; + } + function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference ? update(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; + } + function createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes) { + const node = createBaseNode(272 /* ImportDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + node.attributes = node.assertClause = attributes; + node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + node.jsDoc = void 0; + return node; + } + function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, attributes) { + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? update(createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes), node) : node; + } + function createImportClause(isTypeOnly, name, namedBindings) { + const node = createBaseDeclaration(273 /* ImportClause */); + node.isTypeOnly = isTypeOnly; + node.name = name; + node.namedBindings = namedBindings; + node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.namedBindings); + if (isTypeOnly) { + node.transformFlags |= 1 /* ContainsTypeScript */; + } + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + return node; + } + function updateImportClause(node, isTypeOnly, name, namedBindings) { + return node.isTypeOnly !== isTypeOnly || node.name !== name || node.namedBindings !== namedBindings ? update(createImportClause(isTypeOnly, name, namedBindings), node) : node; + } + function createAssertClause(elements, multiLine) { + const node = createBaseNode(300 /* AssertClause */); + node.elements = createNodeArray(elements); + node.multiLine = multiLine; + node.token = 132 /* AssertKeyword */; + node.transformFlags |= 4 /* ContainsESNext */; + return node; + } + function updateAssertClause(node, elements, multiLine) { + return node.elements !== elements || node.multiLine !== multiLine ? update(createAssertClause(elements, multiLine), node) : node; + } + function createAssertEntry(name, value) { + const node = createBaseNode(301 /* AssertEntry */); + node.name = name; + node.value = value; + node.transformFlags |= 4 /* ContainsESNext */; + return node; + } + function updateAssertEntry(node, name, value) { + return node.name !== name || node.value !== value ? update(createAssertEntry(name, value), node) : node; + } + function createImportTypeAssertionContainer(clause, multiLine) { + const node = createBaseNode(302 /* ImportTypeAssertionContainer */); + node.assertClause = clause; + node.multiLine = multiLine; + return node; + } + function updateImportTypeAssertionContainer(node, clause, multiLine) { + return node.assertClause !== clause || node.multiLine !== multiLine ? update(createImportTypeAssertionContainer(clause, multiLine), node) : node; + } + function createImportAttributes(elements, multiLine, token) { + const node = createBaseNode(300 /* ImportAttributes */); + node.token = token ?? 118 /* WithKeyword */; + node.elements = createNodeArray(elements); + node.multiLine = multiLine; + node.transformFlags |= 4 /* ContainsESNext */; + return node; + } + function updateImportAttributes(node, elements, multiLine) { + return node.elements !== elements || node.multiLine !== multiLine ? update(createImportAttributes(elements, multiLine, node.token), node) : node; + } + function createImportAttribute(name, value) { + const node = createBaseNode(301 /* ImportAttribute */); + node.name = name; + node.value = value; + node.transformFlags |= 4 /* ContainsESNext */; + return node; + } + function updateImportAttribute(node, name, value) { + return node.name !== name || node.value !== value ? update(createImportAttribute(name, value), node) : node; + } + function createNamespaceImport(name) { + const node = createBaseDeclaration(274 /* NamespaceImport */); + node.name = name; + node.transformFlags |= propagateChildFlags(node.name); + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + return node; + } + function updateNamespaceImport(node, name) { + return node.name !== name ? update(createNamespaceImport(name), node) : node; + } + function createNamespaceExport(name) { + const node = createBaseDeclaration(280 /* NamespaceExport */); + node.name = name; + node.transformFlags |= propagateChildFlags(node.name) | 32 /* ContainsES2020 */; + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + return node; + } + function updateNamespaceExport(node, name) { + return node.name !== name ? update(createNamespaceExport(name), node) : node; + } + function createNamedImports(elements) { + const node = createBaseNode(275 /* NamedImports */); + node.elements = createNodeArray(elements); + node.transformFlags |= propagateChildrenFlags(node.elements); + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + return node; + } + function updateNamedImports(node, elements) { + return node.elements !== elements ? update(createNamedImports(elements), node) : node; + } + function createImportSpecifier(isTypeOnly, propertyName, name) { + const node = createBaseDeclaration(276 /* ImportSpecifier */); + node.isTypeOnly = isTypeOnly; + node.propertyName = propertyName; + node.name = name; + node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + return node; + } + function updateImportSpecifier(node, isTypeOnly, propertyName, name) { + return node.isTypeOnly !== isTypeOnly || node.propertyName !== propertyName || node.name !== name ? update(createImportSpecifier(isTypeOnly, propertyName, name), node) : node; + } + function createExportAssignment(modifiers, isExportEquals, expression) { + const node = createBaseDeclaration(277 /* ExportAssignment */); + node.modifiers = asNodeArray(modifiers); + node.isExportEquals = isExportEquals; + node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary( + 64 /* EqualsToken */, + /*leftSide*/ + void 0, + expression + ) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + node.jsDoc = void 0; + return node; + } + function updateExportAssignment(node, modifiers, expression) { + return node.modifiers !== modifiers || node.expression !== expression ? update(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node; + } + function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes) { + const node = createBaseDeclaration(278 /* ExportDeclaration */); + node.modifiers = asNodeArray(modifiers); + node.isTypeOnly = isTypeOnly; + node.exportClause = exportClause; + node.moduleSpecifier = moduleSpecifier; + node.attributes = node.assertClause = attributes; + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + node.jsDoc = void 0; + return node; + } + function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes), node) : node; + } + function finishUpdateExportDeclaration(updated, original) { + if (updated !== original) { + if (updated.modifiers === original.modifiers) { + updated.modifiers = original.modifiers; + } + } + return update(updated, original); + } + function createNamedExports(elements) { + const node = createBaseNode(279 /* NamedExports */); + node.elements = createNodeArray(elements); + node.transformFlags |= propagateChildrenFlags(node.elements); + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + return node; + } + function updateNamedExports(node, elements) { + return node.elements !== elements ? update(createNamedExports(elements), node) : node; + } + function createExportSpecifier(isTypeOnly, propertyName, name) { + const node = createBaseNode(281 /* ExportSpecifier */); + node.isTypeOnly = isTypeOnly; + node.propertyName = asName(propertyName); + node.name = asName(name); + node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + node.jsDoc = void 0; + return node; + } + function updateExportSpecifier(node, isTypeOnly, propertyName, name) { + return node.isTypeOnly !== isTypeOnly || node.propertyName !== propertyName || node.name !== name ? update(createExportSpecifier(isTypeOnly, propertyName, name), node) : node; + } + function createMissingDeclaration() { + const node = createBaseDeclaration(282 /* MissingDeclaration */); + node.jsDoc = void 0; + return node; + } + function createExternalModuleReference(expression) { + const node = createBaseNode(283 /* ExternalModuleReference */); + node.expression = expression; + node.transformFlags |= propagateChildFlags(node.expression); + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; + return node; + } + function updateExternalModuleReference(node, expression) { + return node.expression !== expression ? update(createExternalModuleReference(expression), node) : node; + } + function createJSDocPrimaryTypeWorker(kind) { + return createBaseNode(kind); + } + function createJSDocPrePostfixUnaryTypeWorker(kind, type, postfix = false) { + const node = createJSDocUnaryTypeWorker( + kind, + postfix ? type && parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(type) : type + ); + node.postfix = postfix; + return node; + } + function createJSDocUnaryTypeWorker(kind, type) { + const node = createBaseNode(kind); + node.type = type; + return node; + } + function updateJSDocPrePostfixUnaryTypeWorker(kind, node, type) { + return node.type !== type ? update(createJSDocPrePostfixUnaryTypeWorker(kind, type, node.postfix), node) : node; + } + function updateJSDocUnaryTypeWorker(kind, node, type) { + return node.type !== type ? update(createJSDocUnaryTypeWorker(kind, type), node) : node; + } + function createJSDocFunctionType(parameters, type) { + const node = createBaseDeclaration(317 /* JSDocFunctionType */); + node.parameters = asNodeArray(parameters); + node.type = type; + node.transformFlags = propagateChildrenFlags(node.parameters) | (node.type ? 1 /* ContainsTypeScript */ : 0 /* None */); + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + node.typeArguments = void 0; + return node; + } + function updateJSDocFunctionType(node, parameters, type) { + return node.parameters !== parameters || node.type !== type ? update(createJSDocFunctionType(parameters, type), node) : node; + } + function createJSDocTypeLiteral(propertyTags, isArrayType = false) { + const node = createBaseDeclaration(322 /* JSDocTypeLiteral */); + node.jsDocPropertyTags = asNodeArray(propertyTags); + node.isArrayType = isArrayType; + return node; + } + function updateJSDocTypeLiteral(node, propertyTags, isArrayType) { + return node.jsDocPropertyTags !== propertyTags || node.isArrayType !== isArrayType ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node) : node; + } + function createJSDocTypeExpression(type) { + const node = createBaseNode(309 /* JSDocTypeExpression */); + node.type = type; + return node; + } + function updateJSDocTypeExpression(node, type) { + return node.type !== type ? update(createJSDocTypeExpression(type), node) : node; + } + function createJSDocSignature(typeParameters, parameters, type) { + const node = createBaseDeclaration(323 /* JSDocSignature */); + node.typeParameters = asNodeArray(typeParameters); + node.parameters = createNodeArray(parameters); + node.type = type; + node.jsDoc = void 0; + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateJSDocSignature(node, typeParameters, parameters, type) { + return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type ? update(createJSDocSignature(typeParameters, parameters, type), node) : node; + } + function getDefaultTagName(node) { + const defaultTagName = getDefaultTagNameForKind(node.kind); + return node.tagName.escapedText === escapeLeadingUnderscores(defaultTagName) ? node.tagName : createIdentifier(defaultTagName); + } + function createBaseJSDocTag(kind, tagName, comment) { + const node = createBaseNode(kind); + node.tagName = tagName; + node.comment = comment; + return node; + } + function createBaseJSDocTagDeclaration(kind, tagName, comment) { + const node = createBaseDeclaration(kind); + node.tagName = tagName; + node.comment = comment; + return node; + } + function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { + const node = createBaseJSDocTag(345 /* JSDocTemplateTag */, tagName ?? createIdentifier("template"), comment); + node.constraint = constraint; + node.typeParameters = createNodeArray(typeParameters); + return node; + } + function updateJSDocTemplateTag(node, tagName = getDefaultTagName(node), constraint, typeParameters, comment) { + return node.tagName !== tagName || node.constraint !== constraint || node.typeParameters !== typeParameters || node.comment !== comment ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node) : node; + } + function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { + const node = createBaseJSDocTagDeclaration(346 /* JSDocTypedefTag */, tagName ?? createIdentifier("typedef"), comment); + node.typeExpression = typeExpression; + node.fullName = fullName; + node.name = getJSDocTypeAliasName(fullName); + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateJSDocTypedefTag(node, tagName = getDefaultTagName(node), typeExpression, fullName, comment) { + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName || node.comment !== comment ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node) : node; + } + function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { + const node = createBaseJSDocTagDeclaration(341 /* JSDocParameterTag */, tagName ?? createIdentifier("param"), comment); + node.typeExpression = typeExpression; + node.name = name; + node.isNameFirst = !!isNameFirst; + node.isBracketed = isBracketed; + return node; + } + function updateJSDocParameterTag(node, tagName = getDefaultTagName(node), name, isBracketed, typeExpression, isNameFirst, comment) { + return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed || node.typeExpression !== typeExpression || node.isNameFirst !== isNameFirst || node.comment !== comment ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node; + } + function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { + const node = createBaseJSDocTagDeclaration(348 /* JSDocPropertyTag */, tagName ?? createIdentifier("prop"), comment); + node.typeExpression = typeExpression; + node.name = name; + node.isNameFirst = !!isNameFirst; + node.isBracketed = isBracketed; + return node; + } + function updateJSDocPropertyTag(node, tagName = getDefaultTagName(node), name, isBracketed, typeExpression, isNameFirst, comment) { + return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed || node.typeExpression !== typeExpression || node.isNameFirst !== isNameFirst || node.comment !== comment ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node; + } + function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { + const node = createBaseJSDocTagDeclaration(338 /* JSDocCallbackTag */, tagName ?? createIdentifier("callback"), comment); + node.typeExpression = typeExpression; + node.fullName = fullName; + node.name = getJSDocTypeAliasName(fullName); + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateJSDocCallbackTag(node, tagName = getDefaultTagName(node), typeExpression, fullName, comment) { + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName || node.comment !== comment ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node) : node; + } + function createJSDocOverloadTag(tagName, typeExpression, comment) { + const node = createBaseJSDocTag(339 /* JSDocOverloadTag */, tagName ?? createIdentifier("overload"), comment); + node.typeExpression = typeExpression; + return node; + } + function updateJSDocOverloadTag(node, tagName = getDefaultTagName(node), typeExpression, comment) { + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocOverloadTag(tagName, typeExpression, comment), node) : node; + } + function createJSDocAugmentsTag(tagName, className, comment) { + const node = createBaseJSDocTag(328 /* JSDocAugmentsTag */, tagName ?? createIdentifier("augments"), comment); + node.class = className; + return node; + } + function updateJSDocAugmentsTag(node, tagName = getDefaultTagName(node), className, comment) { + return node.tagName !== tagName || node.class !== className || node.comment !== comment ? update(createJSDocAugmentsTag(tagName, className, comment), node) : node; + } + function createJSDocImplementsTag(tagName, className, comment) { + const node = createBaseJSDocTag(329 /* JSDocImplementsTag */, tagName ?? createIdentifier("implements"), comment); + node.class = className; + return node; + } + function createJSDocSeeTag(tagName, name, comment) { + const node = createBaseJSDocTag(347 /* JSDocSeeTag */, tagName ?? createIdentifier("see"), comment); + node.name = name; + return node; + } + function updateJSDocSeeTag(node, tagName, name, comment) { + return node.tagName !== tagName || node.name !== name || node.comment !== comment ? update(createJSDocSeeTag(tagName, name, comment), node) : node; + } + function createJSDocNameReference(name) { + const node = createBaseNode(310 /* JSDocNameReference */); + node.name = name; + return node; + } + function updateJSDocNameReference(node, name) { + return node.name !== name ? update(createJSDocNameReference(name), node) : node; + } + function createJSDocMemberName(left, right) { + const node = createBaseNode(311 /* JSDocMemberName */); + node.left = left; + node.right = right; + node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.right); + return node; + } + function updateJSDocMemberName(node, left, right) { + return node.left !== left || node.right !== right ? update(createJSDocMemberName(left, right), node) : node; + } + function createJSDocLink(name, text) { + const node = createBaseNode(324 /* JSDocLink */); + node.name = name; + node.text = text; + return node; + } + function updateJSDocLink(node, name, text) { + return node.name !== name ? update(createJSDocLink(name, text), node) : node; + } + function createJSDocLinkCode(name, text) { + const node = createBaseNode(325 /* JSDocLinkCode */); + node.name = name; + node.text = text; + return node; + } + function updateJSDocLinkCode(node, name, text) { + return node.name !== name ? update(createJSDocLinkCode(name, text), node) : node; + } + function createJSDocLinkPlain(name, text) { + const node = createBaseNode(326 /* JSDocLinkPlain */); + node.name = name; + node.text = text; + return node; + } + function updateJSDocLinkPlain(node, name, text) { + return node.name !== name ? update(createJSDocLinkPlain(name, text), node) : node; + } + function updateJSDocImplementsTag(node, tagName = getDefaultTagName(node), className, comment) { + return node.tagName !== tagName || node.class !== className || node.comment !== comment ? update(createJSDocImplementsTag(tagName, className, comment), node) : node; + } + function createJSDocSimpleTagWorker(kind, tagName, comment) { + const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); + return node; + } + function updateJSDocSimpleTagWorker(kind, node, tagName = getDefaultTagName(node), comment) { + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) : node; + } + function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) { + const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); + node.typeExpression = typeExpression; + return node; + } + function updateJSDocTypeLikeTagWorker(kind, node, tagName = getDefaultTagName(node), typeExpression, comment) { + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node) : node; + } + function createJSDocUnknownTag(tagName, comment) { + const node = createBaseJSDocTag(327 /* JSDocTag */, tagName, comment); + return node; + } + function updateJSDocUnknownTag(node, tagName, comment) { + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocUnknownTag(tagName, comment), node) : node; + } + function createJSDocEnumTag(tagName, typeExpression, comment) { + const node = createBaseJSDocTagDeclaration(340 /* JSDocEnumTag */, tagName ?? createIdentifier(getDefaultTagNameForKind(340 /* JSDocEnumTag */)), comment); + node.typeExpression = typeExpression; + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateJSDocEnumTag(node, tagName = getDefaultTagName(node), typeExpression, comment) { + return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocEnumTag(tagName, typeExpression, comment), node) : node; + } + function createJSDocImportTag(tagName, importClause, moduleSpecifier, attributes, comment) { + const node = createBaseJSDocTag(351 /* JSDocImportTag */, tagName ?? createIdentifier("import"), comment); + node.importClause = importClause; + node.moduleSpecifier = moduleSpecifier; + node.attributes = attributes; + node.comment = comment; + return node; + } + function updateJSDocImportTag(node, tagName, importClause, moduleSpecifier, attributes, comment) { + return node.tagName !== tagName || node.comment !== comment || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.attributes !== attributes ? update(createJSDocImportTag(tagName, importClause, moduleSpecifier, attributes, comment), node) : node; + } + function createJSDocText(text) { + const node = createBaseNode(321 /* JSDocText */); + node.text = text; + return node; + } + function updateJSDocText(node, text) { + return node.text !== text ? update(createJSDocText(text), node) : node; + } + function createJSDocComment(comment, tags) { + const node = createBaseNode(320 /* JSDoc */); + node.comment = comment; + node.tags = asNodeArray(tags); + return node; + } + function updateJSDocComment(node, comment, tags) { + return node.comment !== comment || node.tags !== tags ? update(createJSDocComment(comment, tags), node) : node; + } + function createJsxElement(openingElement, children, closingElement) { + const node = createBaseNode(284 /* JsxElement */); + node.openingElement = openingElement; + node.children = createNodeArray(children); + node.closingElement = closingElement; + node.transformFlags |= propagateChildFlags(node.openingElement) | propagateChildrenFlags(node.children) | propagateChildFlags(node.closingElement) | 2 /* ContainsJsx */; + return node; + } + function updateJsxElement(node, openingElement, children, closingElement) { + return node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement ? update(createJsxElement(openingElement, children, closingElement), node) : node; + } + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { + const node = createBaseNode(285 /* JsxSelfClosingElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + node.transformFlags |= propagateChildFlags(node.tagName) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.attributes) | 2 /* ContainsJsx */; + if (node.typeArguments) { + node.transformFlags |= 1 /* ContainsTypeScript */; + } + return node; + } + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; + } + function createJsxOpeningElement(tagName, typeArguments, attributes) { + const node = createBaseNode(286 /* JsxOpeningElement */); + node.tagName = tagName; + node.typeArguments = asNodeArray(typeArguments); + node.attributes = attributes; + node.transformFlags |= propagateChildFlags(node.tagName) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.attributes) | 2 /* ContainsJsx */; + if (typeArguments) { + node.transformFlags |= 1 /* ContainsTypeScript */; + } + return node; + } + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { + return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; + } + function createJsxClosingElement(tagName) { + const node = createBaseNode(287 /* JsxClosingElement */); + node.tagName = tagName; + node.transformFlags |= propagateChildFlags(node.tagName) | 2 /* ContainsJsx */; + return node; + } + function updateJsxClosingElement(node, tagName) { + return node.tagName !== tagName ? update(createJsxClosingElement(tagName), node) : node; + } + function createJsxFragment(openingFragment, children, closingFragment) { + const node = createBaseNode(288 /* JsxFragment */); + node.openingFragment = openingFragment; + node.children = createNodeArray(children); + node.closingFragment = closingFragment; + node.transformFlags |= propagateChildFlags(node.openingFragment) | propagateChildrenFlags(node.children) | propagateChildFlags(node.closingFragment) | 2 /* ContainsJsx */; + return node; + } + function updateJsxFragment(node, openingFragment, children, closingFragment) { + return node.openingFragment !== openingFragment || node.children !== children || node.closingFragment !== closingFragment ? update(createJsxFragment(openingFragment, children, closingFragment), node) : node; + } + function createJsxText(text, containsOnlyTriviaWhiteSpaces) { + const node = createBaseNode(12 /* JsxText */); + node.text = text; + node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces; + node.transformFlags |= 2 /* ContainsJsx */; + return node; + } + function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) { + return node.text !== text || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node) : node; + } + function createJsxOpeningFragment() { + const node = createBaseNode(289 /* JsxOpeningFragment */); + node.transformFlags |= 2 /* ContainsJsx */; + return node; + } + function createJsxJsxClosingFragment() { + const node = createBaseNode(290 /* JsxClosingFragment */); + node.transformFlags |= 2 /* ContainsJsx */; + return node; + } + function createJsxAttribute(name, initializer) { + const node = createBaseDeclaration(291 /* JsxAttribute */); + node.name = name; + node.initializer = initializer; + node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer) | 2 /* ContainsJsx */; + return node; + } + function updateJsxAttribute(node, name, initializer) { + return node.name !== name || node.initializer !== initializer ? update(createJsxAttribute(name, initializer), node) : node; + } + function createJsxAttributes(properties) { + const node = createBaseDeclaration(292 /* JsxAttributes */); + node.properties = createNodeArray(properties); + node.transformFlags |= propagateChildrenFlags(node.properties) | 2 /* ContainsJsx */; + return node; + } + function updateJsxAttributes(node, properties) { + return node.properties !== properties ? update(createJsxAttributes(properties), node) : node; + } + function createJsxSpreadAttribute(expression) { + const node = createBaseNode(293 /* JsxSpreadAttribute */); + node.expression = expression; + node.transformFlags |= propagateChildFlags(node.expression) | 2 /* ContainsJsx */; + return node; + } + function updateJsxSpreadAttribute(node, expression) { + return node.expression !== expression ? update(createJsxSpreadAttribute(expression), node) : node; + } + function createJsxExpression(dotDotDotToken, expression) { + const node = createBaseNode(294 /* JsxExpression */); + node.dotDotDotToken = dotDotDotToken; + node.expression = expression; + node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | propagateChildFlags(node.expression) | 2 /* ContainsJsx */; + return node; + } + function updateJsxExpression(node, expression) { + return node.expression !== expression ? update(createJsxExpression(node.dotDotDotToken, expression), node) : node; + } + function createJsxNamespacedName(namespace, name) { + const node = createBaseNode(295 /* JsxNamespacedName */); + node.namespace = namespace; + node.name = name; + node.transformFlags |= propagateChildFlags(node.namespace) | propagateChildFlags(node.name) | 2 /* ContainsJsx */; + return node; + } + function updateJsxNamespacedName(node, namespace, name) { + return node.namespace !== namespace || node.name !== name ? update(createJsxNamespacedName(namespace, name), node) : node; + } + function createCaseClause(expression, statements) { + const node = createBaseNode(296 /* CaseClause */); + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + node.statements = createNodeArray(statements); + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.statements); + node.jsDoc = void 0; + return node; + } + function updateCaseClause(node, expression, statements) { + return node.expression !== expression || node.statements !== statements ? update(createCaseClause(expression, statements), node) : node; + } + function createDefaultClause(statements) { + const node = createBaseNode(297 /* DefaultClause */); + node.statements = createNodeArray(statements); + node.transformFlags = propagateChildrenFlags(node.statements); + return node; + } + function updateDefaultClause(node, statements) { + return node.statements !== statements ? update(createDefaultClause(statements), node) : node; + } + function createHeritageClause(token, types) { + const node = createBaseNode(298 /* HeritageClause */); + node.token = token; + node.types = createNodeArray(types); + node.transformFlags |= propagateChildrenFlags(node.types); + switch (token) { + case 96 /* ExtendsKeyword */: + node.transformFlags |= 1024 /* ContainsES2015 */; + break; + case 119 /* ImplementsKeyword */: + node.transformFlags |= 1 /* ContainsTypeScript */; + break; + default: + return Debug.assertNever(token); + } + return node; + } + function updateHeritageClause(node, types) { + return node.types !== types ? update(createHeritageClause(node.token, types), node) : node; + } + function createCatchClause(variableDeclaration, block) { + const node = createBaseNode(299 /* CatchClause */); + node.variableDeclaration = asVariableDeclaration(variableDeclaration); + node.block = block; + node.transformFlags |= propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block) | (!variableDeclaration ? 64 /* ContainsES2019 */ : 0 /* None */); + node.locals = void 0; + node.nextContainer = void 0; + return node; + } + function updateCatchClause(node, variableDeclaration, block) { + return node.variableDeclaration !== variableDeclaration || node.block !== block ? update(createCatchClause(variableDeclaration, block), node) : node; + } + function createPropertyAssignment(name, initializer) { + const node = createBaseDeclaration(303 /* PropertyAssignment */); + node.name = asName(name); + node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); + node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer); + node.modifiers = void 0; + node.questionToken = void 0; + node.exclamationToken = void 0; + node.jsDoc = void 0; + return node; + } + function updatePropertyAssignment(node, name, initializer) { + return node.name !== name || node.initializer !== initializer ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node; + } + function finishUpdatePropertyAssignment(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } + function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { + const node = createBaseDeclaration(304 /* ShorthandPropertyAssignment */); + node.name = asName(name); + node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); + node.transformFlags |= propagateIdentifierNameFlags(node.name) | propagateChildFlags(node.objectAssignmentInitializer) | 1024 /* ContainsES2015 */; + node.equalsToken = void 0; + node.modifiers = void 0; + node.questionToken = void 0; + node.exclamationToken = void 0; + node.jsDoc = void 0; + return node; + } + function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { + return node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node; + } + function finishUpdateShorthandPropertyAssignment(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + updated.equalsToken = original.equalsToken; + } + return update(updated, original); + } + function createSpreadAssignment(expression) { + const node = createBaseDeclaration(305 /* SpreadAssignment */); + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + node.transformFlags |= propagateChildFlags(node.expression) | 128 /* ContainsES2018 */ | 65536 /* ContainsObjectRestOrSpread */; + node.jsDoc = void 0; + return node; + } + function updateSpreadAssignment(node, expression) { + return node.expression !== expression ? update(createSpreadAssignment(expression), node) : node; + } + function createEnumMember(name, initializer) { + const node = createBaseDeclaration(306 /* EnumMember */); + node.name = asName(name); + node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); + node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer) | 1 /* ContainsTypeScript */; + node.jsDoc = void 0; + return node; + } + function updateEnumMember(node, name, initializer) { + return node.name !== name || node.initializer !== initializer ? update(createEnumMember(name, initializer), node) : node; + } + function createSourceFile2(statements, endOfFileToken, flags2) { + const node = baseFactory2.createBaseSourceFileNode(307 /* SourceFile */); + node.statements = createNodeArray(statements); + node.endOfFileToken = endOfFileToken; + node.flags |= flags2; + node.text = ""; + node.fileName = ""; + node.path = ""; + node.resolvedPath = ""; + node.originalFileName = ""; + node.languageVersion = 1 /* ES5 */; + node.languageVariant = 0; + node.scriptKind = 0; + node.isDeclarationFile = false; + node.hasNoDefaultLib = false; + node.transformFlags |= propagateChildrenFlags(node.statements) | propagateChildFlags(node.endOfFileToken); + node.locals = void 0; + node.nextContainer = void 0; + node.endFlowNode = void 0; + node.nodeCount = 0; + node.identifierCount = 0; + node.symbolCount = 0; + node.parseDiagnostics = void 0; + node.bindDiagnostics = void 0; + node.bindSuggestionDiagnostics = void 0; + node.lineMap = void 0; + node.externalModuleIndicator = void 0; + node.setExternalModuleIndicator = void 0; + node.pragmas = void 0; + node.checkJsDirective = void 0; + node.referencedFiles = void 0; + node.typeReferenceDirectives = void 0; + node.libReferenceDirectives = void 0; + node.amdDependencies = void 0; + node.commentDirectives = void 0; + node.identifiers = void 0; + node.packageJsonLocations = void 0; + node.packageJsonScope = void 0; + node.imports = void 0; + node.moduleAugmentations = void 0; + node.ambientModuleNames = void 0; + node.classifiableNames = void 0; + node.impliedNodeFormat = void 0; + return node; + } + function createRedirectedSourceFile(redirectInfo) { + const node = Object.create(redirectInfo.redirectTarget); + Object.defineProperties(node, { + id: { + get() { + return this.redirectInfo.redirectTarget.id; + }, + set(value) { + this.redirectInfo.redirectTarget.id = value; + } + }, + symbol: { + get() { + return this.redirectInfo.redirectTarget.symbol; + }, + set(value) { + this.redirectInfo.redirectTarget.symbol = value; + } + } + }); + node.redirectInfo = redirectInfo; + return node; + } + function cloneRedirectedSourceFile(source) { + const node = createRedirectedSourceFile(source.redirectInfo); + node.flags |= source.flags & ~16 /* Synthesized */; + node.fileName = source.fileName; + node.path = source.path; + node.resolvedPath = source.resolvedPath; + node.originalFileName = source.originalFileName; + node.packageJsonLocations = source.packageJsonLocations; + node.packageJsonScope = source.packageJsonScope; + node.emitNode = void 0; + return node; + } + function cloneSourceFileWorker(source) { + const node = baseFactory2.createBaseSourceFileNode(307 /* SourceFile */); + node.flags |= source.flags & ~16 /* Synthesized */; + for (const p in source) { + if (hasProperty(node, p) || !hasProperty(source, p)) { + continue; + } + if (p === "emitNode") { + node.emitNode = void 0; + continue; + } + node[p] = source[p]; + } + return node; + } + function cloneSourceFile(source) { + const node = source.redirectInfo ? cloneRedirectedSourceFile(source) : cloneSourceFileWorker(source); + setOriginal(node, source); + return node; + } + function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { + const node = cloneSourceFile(source); + node.statements = createNodeArray(statements); + node.isDeclarationFile = isDeclarationFile; + node.referencedFiles = referencedFiles; + node.typeReferenceDirectives = typeReferences; + node.hasNoDefaultLib = hasNoDefaultLib; + node.libReferenceDirectives = libReferences; + node.transformFlags = propagateChildrenFlags(node.statements) | propagateChildFlags(node.endOfFileToken); + return node; + } + function updateSourceFile(node, statements, isDeclarationFile = node.isDeclarationFile, referencedFiles = node.referencedFiles, typeReferenceDirectives = node.typeReferenceDirectives, hasNoDefaultLib = node.hasNoDefaultLib, libReferenceDirectives = node.libReferenceDirectives) { + return node.statements !== statements || node.isDeclarationFile !== isDeclarationFile || node.referencedFiles !== referencedFiles || node.typeReferenceDirectives !== typeReferenceDirectives || node.hasNoDefaultLib !== hasNoDefaultLib || node.libReferenceDirectives !== libReferenceDirectives ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node) : node; + } + function createBundle(sourceFiles) { + const node = createBaseNode(308 /* Bundle */); + node.sourceFiles = sourceFiles; + node.syntheticFileReferences = void 0; + node.syntheticTypeReferences = void 0; + node.syntheticLibReferences = void 0; + node.hasNoDefaultLib = void 0; + return node; + } + function updateBundle(node, sourceFiles) { + return node.sourceFiles !== sourceFiles ? update(createBundle(sourceFiles), node) : node; + } + function createSyntheticExpression(type, isSpread = false, tupleNameSource) { + const node = createBaseNode(237 /* SyntheticExpression */); + node.type = type; + node.isSpread = isSpread; + node.tupleNameSource = tupleNameSource; + return node; + } + function createSyntaxList(children) { + const node = createBaseNode(352 /* SyntaxList */); + node._children = children; + return node; + } + function createNotEmittedStatement(original) { + const node = createBaseNode(353 /* NotEmittedStatement */); + node.original = original; + setTextRange(node, original); + return node; + } + function createPartiallyEmittedExpression(expression, original) { + const node = createBaseNode(355 /* PartiallyEmittedExpression */); + node.expression = expression; + node.original = original; + node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */; + setTextRange(node, original); + return node; + } + function updatePartiallyEmittedExpression(node, expression) { + return node.expression !== expression ? update(createPartiallyEmittedExpression(expression, node.original), node) : node; + } + function createNotEmittedTypeElement() { + return createBaseNode(354 /* NotEmittedTypeElement */); + } + function flattenCommaElements(node) { + if (nodeIsSynthesized(node) && !isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + if (isCommaListExpression(node)) { + return node.elements; + } + if (isBinaryExpression(node) && isCommaToken(node.operatorToken)) { + return [node.left, node.right]; + } + } + return node; + } + function createCommaListExpression(elements) { + const node = createBaseNode(356 /* CommaListExpression */); + node.elements = createNodeArray(sameFlatMap(elements, flattenCommaElements)); + node.transformFlags |= propagateChildrenFlags(node.elements); + return node; + } + function updateCommaListExpression(node, elements) { + return node.elements !== elements ? update(createCommaListExpression(elements), node) : node; + } + function createSyntheticReferenceExpression(expression, thisArg) { + const node = createBaseNode(357 /* SyntheticReferenceExpression */); + node.expression = expression; + node.thisArg = thisArg; + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg); + return node; + } + function updateSyntheticReferenceExpression(node, expression, thisArg) { + return node.expression !== expression || node.thisArg !== thisArg ? update(createSyntheticReferenceExpression(expression, thisArg), node) : node; + } + function cloneGeneratedIdentifier(node) { + const clone = createBaseIdentifier(node.escapedText); + clone.flags |= node.flags & ~16 /* Synthesized */; + clone.transformFlags = node.transformFlags; + setOriginal(clone, node); + setIdentifierAutoGenerate(clone, { ...node.emitNode.autoGenerate }); + return clone; + } + function cloneIdentifier(node) { + const clone = createBaseIdentifier(node.escapedText); + clone.flags |= node.flags & ~16 /* Synthesized */; + clone.jsDoc = node.jsDoc; + clone.flowNode = node.flowNode; + clone.symbol = node.symbol; + clone.transformFlags = node.transformFlags; + setOriginal(clone, node); + const typeArguments = getIdentifierTypeArguments(node); + if (typeArguments) setIdentifierTypeArguments(clone, typeArguments); + return clone; + } + function cloneGeneratedPrivateIdentifier(node) { + const clone = createBasePrivateIdentifier(node.escapedText); + clone.flags |= node.flags & ~16 /* Synthesized */; + clone.transformFlags = node.transformFlags; + setOriginal(clone, node); + setIdentifierAutoGenerate(clone, { ...node.emitNode.autoGenerate }); + return clone; + } + function clonePrivateIdentifier(node) { + const clone = createBasePrivateIdentifier(node.escapedText); + clone.flags |= node.flags & ~16 /* Synthesized */; + clone.transformFlags = node.transformFlags; + setOriginal(clone, node); + return clone; + } + function cloneNode(node) { + if (node === void 0) { + return node; + } + if (isSourceFile(node)) { + return cloneSourceFile(node); + } + if (isGeneratedIdentifier(node)) { + return cloneGeneratedIdentifier(node); + } + if (isIdentifier(node)) { + return cloneIdentifier(node); + } + if (isGeneratedPrivateIdentifier(node)) { + return cloneGeneratedPrivateIdentifier(node); + } + if (isPrivateIdentifier(node)) { + return clonePrivateIdentifier(node); + } + const clone = !isNodeKind(node.kind) ? baseFactory2.createBaseTokenNode(node.kind) : baseFactory2.createBaseNode(node.kind); + clone.flags |= node.flags & ~16 /* Synthesized */; + clone.transformFlags = node.transformFlags; + setOriginal(clone, node); + for (const key in node) { + if (hasProperty(clone, key) || !hasProperty(node, key)) { + continue; + } + clone[key] = node[key]; + } + return clone; + } + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCallExpression( + createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + /*parameters*/ + param ? [param] : [], + /*type*/ + void 0, + createBlock( + statements, + /*multiLine*/ + true + ) + ), + /*typeArguments*/ + void 0, + /*argumentsArray*/ + paramValue ? [paramValue] : [] + ); + } + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCallExpression( + createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + /*parameters*/ + param ? [param] : [], + /*type*/ + void 0, + /*equalsGreaterThanToken*/ + void 0, + createBlock( + statements, + /*multiLine*/ + true + ) + ), + /*typeArguments*/ + void 0, + /*argumentsArray*/ + paramValue ? [paramValue] : [] + ); + } + function createVoidZero() { + return createVoidExpression(createNumericLiteral("0")); + } + function createExportDefault(expression) { + return createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + expression + ); + } + function createExternalModuleExport(exportName) { + return createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + createNamedExports([ + createExportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + exportName + ) + ]) + ); + } + function createTypeCheck(value, tag) { + return tag === "null" ? factory2.createStrictEquality(value, createNull()) : tag === "undefined" ? factory2.createStrictEquality(value, createVoidZero()) : factory2.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag)); + } + function createIsNotTypeCheck(value, tag) { + return tag === "null" ? factory2.createStrictInequality(value, createNull()) : tag === "undefined" ? factory2.createStrictInequality(value, createVoidZero()) : factory2.createStrictInequality(createTypeOfExpression(value), createStringLiteral(tag)); + } + function createMethodCall(object, methodName, argumentsList) { + if (isCallChain(object)) { + return createCallChain( + createPropertyAccessChain( + object, + /*questionDotToken*/ + void 0, + methodName + ), + /*questionDotToken*/ + void 0, + /*typeArguments*/ + void 0, + argumentsList + ); + } + return createCallExpression( + createPropertyAccessExpression(object, methodName), + /*typeArguments*/ + void 0, + argumentsList + ); + } + function createFunctionBindCall(target, thisArg, argumentsList) { + return createMethodCall(target, "bind", [thisArg, ...argumentsList]); + } + function createFunctionCallCall(target, thisArg, argumentsList) { + return createMethodCall(target, "call", [thisArg, ...argumentsList]); + } + function createFunctionApplyCall(target, thisArg, argumentsExpression) { + return createMethodCall(target, "apply", [thisArg, argumentsExpression]); + } + function createGlobalMethodCall(globalObjectName, methodName, argumentsList) { + return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList); + } + function createArraySliceCall(array, start) { + return createMethodCall(array, "slice", start === void 0 ? [] : [asExpression(start)]); + } + function createArrayConcatCall(array, argumentsList) { + return createMethodCall(array, "concat", argumentsList); + } + function createObjectDefinePropertyCall(target, propertyName, attributes) { + return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]); + } + function createObjectGetOwnPropertyDescriptorCall(target, propertyName) { + return createGlobalMethodCall("Object", "getOwnPropertyDescriptor", [target, asExpression(propertyName)]); + } + function createReflectGetCall(target, propertyKey, receiver) { + return createGlobalMethodCall("Reflect", "get", receiver ? [target, propertyKey, receiver] : [target, propertyKey]); + } + function createReflectSetCall(target, propertyKey, value, receiver) { + return createGlobalMethodCall("Reflect", "set", receiver ? [target, propertyKey, value, receiver] : [target, propertyKey, value]); + } + function tryAddPropertyAssignment(properties, propertyName, expression) { + if (expression) { + properties.push(createPropertyAssignment(propertyName, expression)); + return true; + } + return false; + } + function createPropertyDescriptor(attributes, singleLine) { + const properties = []; + tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable)); + tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable)); + let isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable)); + isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData; + let isAccessor2 = tryAddPropertyAssignment(properties, "get", attributes.get); + isAccessor2 = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor2; + Debug.assert(!(isData && isAccessor2), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor."); + return createObjectLiteralExpression(properties, !singleLine); + } + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 217 /* ParenthesizedExpression */: + return updateParenthesizedExpression(outerExpression, expression); + case 216 /* TypeAssertionExpression */: + return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 234 /* AsExpression */: + return updateAsExpression(outerExpression, expression, outerExpression.type); + case 238 /* SatisfiesExpression */: + return updateSatisfiesExpression(outerExpression, expression, outerExpression.type); + case 235 /* NonNullExpression */: + return updateNonNullExpression(outerExpression, expression); + case 233 /* ExpressionWithTypeArguments */: + return updateExpressionWithTypeArguments(outerExpression, expression, outerExpression.typeArguments); + case 355 /* PartiallyEmittedExpression */: + return updatePartiallyEmittedExpression(outerExpression, expression); + } + } + function isIgnorableParen(node) { + return isParenthesizedExpression(node) && nodeIsSynthesized(node) && nodeIsSynthesized(getSourceMapRange(node)) && nodeIsSynthesized(getCommentRange(node)) && !some(getSyntheticLeadingComments(node)) && !some(getSyntheticTrailingComments(node)); + } + function restoreOuterExpressions(outerExpression, innerExpression, kinds = 63 /* All */) { + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { + return updateOuterExpression( + outerExpression, + restoreOuterExpressions(outerExpression.expression, innerExpression) + ); + } + return innerExpression; + } + function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) { + if (!outermostLabeledStatement) { + return node; + } + const updated = updateLabeledStatement( + outermostLabeledStatement, + outermostLabeledStatement.label, + isLabeledStatement(outermostLabeledStatement.statement) ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node + ); + if (afterRestoreLabelCallback) { + afterRestoreLabelCallback(outermostLabeledStatement); + } + return updated; + } + function shouldBeCapturedInTempVariable(node, cacheIdentifiers) { + const target = skipParentheses(node); + switch (target.kind) { + case 80 /* Identifier */: + return cacheIdentifiers; + case 110 /* ThisKeyword */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 11 /* StringLiteral */: + return false; + case 209 /* ArrayLiteralExpression */: + const elements = target.elements; + if (elements.length === 0) { + return false; + } + return true; + case 210 /* ObjectLiteralExpression */: + return target.properties.length > 0; + default: + return true; + } + } + function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers = false) { + const callee = skipOuterExpressions(expression, 63 /* All */); + let thisArg; + let target; + if (isSuperProperty(callee)) { + thisArg = createThis(); + target = callee; + } else if (isSuperKeyword(callee)) { + thisArg = createThis(); + target = languageVersion !== void 0 && languageVersion < 2 /* ES2015 */ ? setTextRange(createIdentifier("_super"), callee) : callee; + } else if (getEmitFlags(callee) & 8192 /* HelperName */) { + thisArg = createVoidZero(); + target = parenthesizerRules().parenthesizeLeftSideOfAccess( + callee, + /*optionalChain*/ + false + ); + } else if (isPropertyAccessExpression(callee)) { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = createTempVariable(recordTempVariable); + target = createPropertyAccessExpression( + setTextRange( + factory2.createAssignment( + thisArg, + callee.expression + ), + callee.expression + ), + callee.name + ); + setTextRange(target, callee); + } else { + thisArg = callee.expression; + target = callee; + } + } else if (isElementAccessExpression(callee)) { + if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + thisArg = createTempVariable(recordTempVariable); + target = createElementAccessExpression( + setTextRange( + factory2.createAssignment( + thisArg, + callee.expression + ), + callee.expression + ), + callee.argumentExpression + ); + setTextRange(target, callee); + } else { + thisArg = callee.expression; + target = callee; + } + } else { + thisArg = createVoidZero(); + target = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ + false + ); + } + return { target, thisArg }; + } + function createAssignmentTargetWrapper(paramName, expression) { + return createPropertyAccessExpression( + // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) + createParenthesizedExpression( + createObjectLiteralExpression([ + createSetAccessorDeclaration( + /*modifiers*/ + void 0, + "value", + [createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + paramName, + /*questionToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + )], + createBlock([ + createExpressionStatement(expression) + ]) + ) + ]) + ), + "value" + ); + } + function inlineExpressions(expressions) { + return expressions.length > 10 ? createCommaListExpression(expressions) : reduceLeft(expressions, factory2.createComma); + } + function getName(node, allowComments, allowSourceMaps, emitFlags = 0, ignoreAssignedName) { + const nodeName = ignoreAssignedName ? node && getNonAssignedNameOfDeclaration(node) : getNameOfDeclaration(node); + if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { + const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); + emitFlags |= getEmitFlags(nodeName); + if (!allowSourceMaps) emitFlags |= 96 /* NoSourceMap */; + if (!allowComments) emitFlags |= 3072 /* NoComments */; + if (emitFlags) setEmitFlags(name, emitFlags); + return name; + } + return getGeneratedNameForNode(node); + } + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ | 65536 /* InternalName */); + } + function getLocalName(node, allowComments, allowSourceMaps, ignoreAssignedName) { + return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */, ignoreAssignedName); + } + function getExportName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* ExportName */); + } + function getDeclarationName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps); + } + function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { + const qualifiedName = createPropertyAccessExpression(ns, nodeIsSynthesized(name) ? name : cloneNode(name)); + setTextRange(qualifiedName, name); + let emitFlags = 0; + if (!allowSourceMaps) emitFlags |= 96 /* NoSourceMap */; + if (!allowComments) emitFlags |= 3072 /* NoComments */; + if (emitFlags) setEmitFlags(qualifiedName, emitFlags); + return qualifiedName; + } + function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { + if (ns && hasSyntacticModifier(node, 32 /* Export */)) { + return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + } + return getExportName(node, allowComments, allowSourceMaps); + } + function copyPrologue(source, target, ensureUseStrict2, visitor) { + const offset = copyStandardPrologue(source, target, 0, ensureUseStrict2); + return copyCustomPrologue(source, target, offset, visitor); + } + function isUseStrictPrologue2(node) { + return isStringLiteral(node.expression) && node.expression.text === "use strict"; + } + function createUseStrictPrologue() { + return startOnNewLine(createExpressionStatement(createStringLiteral("use strict"))); + } + function copyStandardPrologue(source, target, statementOffset = 0, ensureUseStrict2) { + Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); + let foundUseStrict = false; + const numStatements = source.length; + while (statementOffset < numStatements) { + const statement = source[statementOffset]; + if (isPrologueDirective(statement)) { + if (isUseStrictPrologue2(statement)) { + foundUseStrict = true; + } + target.push(statement); + } else { + break; + } + statementOffset++; + } + if (ensureUseStrict2 && !foundUseStrict) { + target.push(createUseStrictPrologue()); + } + return statementOffset; + } + function copyCustomPrologue(source, target, statementOffset, visitor, filter2 = returnTrue) { + const numStatements = source.length; + while (statementOffset !== void 0 && statementOffset < numStatements) { + const statement = source[statementOffset]; + if (getEmitFlags(statement) & 2097152 /* CustomPrologue */ && filter2(statement)) { + append(target, visitor ? visitNode(statement, visitor, isStatement) : statement); + } else { + break; + } + statementOffset++; + } + return statementOffset; + } + function ensureUseStrict(statements) { + const foundUseStrict = findUseStrictPrologue(statements); + if (!foundUseStrict) { + return setTextRange(createNodeArray([createUseStrictPrologue(), ...statements]), statements); + } + return statements; + } + function liftToBlock(nodes) { + Debug.assert(every(nodes, isStatementOrBlock), "Cannot lift nodes to a Block."); + return singleOrUndefined(nodes) || createBlock(nodes); + } + function findSpanEnd(array, test, start) { + let i = start; + while (i < array.length && test(array[i])) { + i++; + } + return i; + } + function mergeLexicalEnvironment(statements, declarations) { + if (!some(declarations)) { + return statements; + } + const leftStandardPrologueEnd = findSpanEnd(statements, isPrologueDirective, 0); + const leftHoistedFunctionsEnd = findSpanEnd(statements, isHoistedFunction, leftStandardPrologueEnd); + const leftHoistedVariablesEnd = findSpanEnd(statements, isHoistedVariableStatement, leftHoistedFunctionsEnd); + const rightStandardPrologueEnd = findSpanEnd(declarations, isPrologueDirective, 0); + const rightHoistedFunctionsEnd = findSpanEnd(declarations, isHoistedFunction, rightStandardPrologueEnd); + const rightHoistedVariablesEnd = findSpanEnd(declarations, isHoistedVariableStatement, rightHoistedFunctionsEnd); + const rightCustomPrologueEnd = findSpanEnd(declarations, isCustomPrologue, rightHoistedVariablesEnd); + Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues"); + const left = isNodeArray(statements) ? statements.slice() : statements; + if (rightCustomPrologueEnd > rightHoistedVariablesEnd) { + left.splice(leftHoistedVariablesEnd, 0, ...declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)); + } + if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) { + left.splice(leftHoistedFunctionsEnd, 0, ...declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)); + } + if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) { + left.splice(leftStandardPrologueEnd, 0, ...declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)); + } + if (rightStandardPrologueEnd > 0) { + if (leftStandardPrologueEnd === 0) { + left.splice(0, 0, ...declarations.slice(0, rightStandardPrologueEnd)); + } else { + const leftPrologues = /* @__PURE__ */ new Map(); + for (let i = 0; i < leftStandardPrologueEnd; i++) { + const leftPrologue = statements[i]; + leftPrologues.set(leftPrologue.expression.text, true); + } + for (let i = rightStandardPrologueEnd - 1; i >= 0; i--) { + const rightPrologue = declarations[i]; + if (!leftPrologues.has(rightPrologue.expression.text)) { + left.unshift(rightPrologue); + } + } + } + } + if (isNodeArray(statements)) { + return setTextRange(createNodeArray(left, statements.hasTrailingComma), statements); + } + return statements; + } + function replaceModifiers(node, modifiers) { + let modifierArray; + if (typeof modifiers === "number") { + modifierArray = createModifiersFromModifierFlags(modifiers); + } else { + modifierArray = modifiers; + } + return isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.attributes) : isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.attributes) : Debug.assertNever(node); + } + function replaceDecoratorsAndModifiers(node, modifierArray) { + return isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : Debug.assertNever(node); + } + function replacePropertyName(node, name) { + switch (node.kind) { + case 177 /* GetAccessor */: + return updateGetAccessorDeclaration(node, node.modifiers, name, node.parameters, node.type, node.body); + case 178 /* SetAccessor */: + return updateSetAccessorDeclaration(node, node.modifiers, name, node.parameters, node.body); + case 174 /* MethodDeclaration */: + return updateMethodDeclaration(node, node.modifiers, node.asteriskToken, name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body); + case 173 /* MethodSignature */: + return updateMethodSignature(node, node.modifiers, name, node.questionToken, node.typeParameters, node.parameters, node.type); + case 172 /* PropertyDeclaration */: + return updatePropertyDeclaration(node, node.modifiers, name, node.questionToken ?? node.exclamationToken, node.type, node.initializer); + case 171 /* PropertySignature */: + return updatePropertySignature(node, node.modifiers, name, node.questionToken, node.type); + case 303 /* PropertyAssignment */: + return updatePropertyAssignment(node, name, node.initializer); + } + } + function asNodeArray(array) { + return array ? createNodeArray(array) : void 0; + } + function asName(name) { + return typeof name === "string" ? createIdentifier(name) : name; + } + function asExpression(value) { + return typeof value === "string" ? createStringLiteral(value) : typeof value === "number" ? createNumericLiteral(value) : typeof value === "boolean" ? value ? createTrue() : createFalse() : value; + } + function asInitializer(node) { + return node && parenthesizerRules().parenthesizeExpressionForDisallowedComma(node); + } + function asToken(value) { + return typeof value === "number" ? createToken(value) : value; + } + function asEmbeddedStatement(statement) { + return statement && isNotEmittedStatement(statement) ? setTextRange(setOriginal(createEmptyStatement(), statement), statement) : statement; + } + function asVariableDeclaration(variableDeclaration) { + if (typeof variableDeclaration === "string" || variableDeclaration && !isVariableDeclaration(variableDeclaration)) { + return createVariableDeclaration( + variableDeclaration, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ); + } + return variableDeclaration; + } + function update(updated, original) { + if (updated !== original) { + setOriginal(updated, original); + setTextRange(updated, original); + } + return updated; + } +} +function getDefaultTagNameForKind(kind) { + switch (kind) { + case 344 /* JSDocTypeTag */: + return "type"; + case 342 /* JSDocReturnTag */: + return "returns"; + case 343 /* JSDocThisTag */: + return "this"; + case 340 /* JSDocEnumTag */: + return "enum"; + case 330 /* JSDocAuthorTag */: + return "author"; + case 332 /* JSDocClassTag */: + return "class"; + case 333 /* JSDocPublicTag */: + return "public"; + case 334 /* JSDocPrivateTag */: + return "private"; + case 335 /* JSDocProtectedTag */: + return "protected"; + case 336 /* JSDocReadonlyTag */: + return "readonly"; + case 337 /* JSDocOverrideTag */: + return "override"; + case 345 /* JSDocTemplateTag */: + return "template"; + case 346 /* JSDocTypedefTag */: + return "typedef"; + case 341 /* JSDocParameterTag */: + return "param"; + case 348 /* JSDocPropertyTag */: + return "prop"; + case 338 /* JSDocCallbackTag */: + return "callback"; + case 339 /* JSDocOverloadTag */: + return "overload"; + case 328 /* JSDocAugmentsTag */: + return "augments"; + case 329 /* JSDocImplementsTag */: + return "implements"; + case 351 /* JSDocImportTag */: + return "import"; + default: + return Debug.fail(`Unsupported kind: ${Debug.formatSyntaxKind(kind)}`); + } +} +var rawTextScanner; +var invalidValueSentinel = {}; +function getCookedText(kind, rawText) { + if (!rawTextScanner) { + rawTextScanner = createScanner( + 99 /* Latest */, + /*skipTrivia*/ + false, + 0 /* Standard */ + ); + } + switch (kind) { + case 15 /* NoSubstitutionTemplateLiteral */: + rawTextScanner.setText("`" + rawText + "`"); + break; + case 16 /* TemplateHead */: + rawTextScanner.setText("`" + rawText + "${"); + break; + case 17 /* TemplateMiddle */: + rawTextScanner.setText("}" + rawText + "${"); + break; + case 18 /* TemplateTail */: + rawTextScanner.setText("}" + rawText + "`"); + break; + } + let token = rawTextScanner.scan(); + if (token === 20 /* CloseBraceToken */) { + token = rawTextScanner.reScanTemplateToken( + /*isTaggedTemplate*/ + false + ); + } + if (rawTextScanner.isUnterminated()) { + rawTextScanner.setText(void 0); + return invalidValueSentinel; + } + let tokenValue; + switch (token) { + case 15 /* NoSubstitutionTemplateLiteral */: + case 16 /* TemplateHead */: + case 17 /* TemplateMiddle */: + case 18 /* TemplateTail */: + tokenValue = rawTextScanner.getTokenValue(); + break; + } + if (tokenValue === void 0 || rawTextScanner.scan() !== 1 /* EndOfFileToken */) { + rawTextScanner.setText(void 0); + return invalidValueSentinel; + } + rawTextScanner.setText(void 0); + return tokenValue; +} +function propagateNameFlags(node) { + return node && isIdentifier(node) ? propagateIdentifierNameFlags(node) : propagateChildFlags(node); +} +function propagateIdentifierNameFlags(node) { + return propagateChildFlags(node) & ~67108864 /* ContainsPossibleTopLevelAwait */; +} +function propagatePropertyNameFlagsOfChild(node, transformFlags) { + return transformFlags | node.transformFlags & 134234112 /* PropertyNamePropagatingFlags */; +} +function propagateChildFlags(child) { + if (!child) return 0 /* None */; + const childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind); + return isNamedDeclaration(child) && isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags; +} +function propagateChildrenFlags(children) { + return children ? children.transformFlags : 0 /* None */; +} +function aggregateChildrenFlags(children) { + let subtreeFlags = 0 /* None */; + for (const child of children) { + subtreeFlags |= propagateChildFlags(child); + } + children.transformFlags = subtreeFlags; +} +function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 182 /* FirstTypeNode */ && kind <= 205 /* LastTypeNode */) { + return -2 /* TypeExcludes */; + } + switch (kind) { + case 213 /* CallExpression */: + case 214 /* NewExpression */: + case 209 /* ArrayLiteralExpression */: + return -2147450880 /* ArrayLiteralOrCallOrNewExcludes */; + case 267 /* ModuleDeclaration */: + return -1941676032 /* ModuleExcludes */; + case 169 /* Parameter */: + return -2147483648 /* ParameterExcludes */; + case 219 /* ArrowFunction */: + return -2072174592 /* ArrowFunctionExcludes */; + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + return -1937940480 /* FunctionExcludes */; + case 261 /* VariableDeclarationList */: + return -2146893824 /* VariableDeclarationListExcludes */; + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + return -2147344384 /* ClassExcludes */; + case 176 /* Constructor */: + return -1937948672 /* ConstructorExcludes */; + case 172 /* PropertyDeclaration */: + return -2013249536 /* PropertyExcludes */; + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return -2005057536 /* MethodOrAccessorExcludes */; + case 133 /* AnyKeyword */: + case 150 /* NumberKeyword */: + case 163 /* BigIntKeyword */: + case 146 /* NeverKeyword */: + case 154 /* StringKeyword */: + case 151 /* ObjectKeyword */: + case 136 /* BooleanKeyword */: + case 155 /* SymbolKeyword */: + case 116 /* VoidKeyword */: + case 168 /* TypeParameter */: + case 171 /* PropertySignature */: + case 173 /* MethodSignature */: + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 181 /* IndexSignature */: + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + return -2 /* TypeExcludes */; + case 210 /* ObjectLiteralExpression */: + return -2147278848 /* ObjectLiteralExcludes */; + case 299 /* CatchClause */: + return -2147418112 /* CatchClauseExcludes */; + case 206 /* ObjectBindingPattern */: + case 207 /* ArrayBindingPattern */: + return -2147450880 /* BindingPatternExcludes */; + case 216 /* TypeAssertionExpression */: + case 238 /* SatisfiesExpression */: + case 234 /* AsExpression */: + case 355 /* PartiallyEmittedExpression */: + case 217 /* ParenthesizedExpression */: + case 108 /* SuperKeyword */: + return -2147483648 /* OuterExpressionExcludes */; + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + return -2147483648 /* PropertyAccessExcludes */; + default: + return -2147483648 /* NodeExcludes */; + } +} +var baseFactory = createBaseNodeFactory(); +function makeSynthetic(node) { + node.flags |= 16 /* Synthesized */; + return node; +} +var syntheticFactory = { + createBaseSourceFileNode: (kind) => makeSynthetic(baseFactory.createBaseSourceFileNode(kind)), + createBaseIdentifierNode: (kind) => makeSynthetic(baseFactory.createBaseIdentifierNode(kind)), + createBasePrivateIdentifierNode: (kind) => makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)), + createBaseTokenNode: (kind) => makeSynthetic(baseFactory.createBaseTokenNode(kind)), + createBaseNode: (kind) => makeSynthetic(baseFactory.createBaseNode(kind)) +}; +var factory = createNodeFactory(4 /* NoIndentationOnFreshPropertyAccess */, syntheticFactory); +function setOriginalNode(node, original) { + if (node.original !== original) { + node.original = original; + if (original) { + const emitNode = original.emitNode; + if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode); + } + } + return node; +} +function mergeEmitNode(sourceEmitNode, destEmitNode) { + const { + flags, + internalFlags, + leadingComments, + trailingComments, + commentRange, + sourceMapRange, + tokenSourceMapRanges, + constantValue, + helpers, + startsOnNewLine, + snippetElement, + classThis, + assignedName + } = sourceEmitNode; + if (!destEmitNode) destEmitNode = {}; + if (flags) { + destEmitNode.flags = flags; + } + if (internalFlags) { + destEmitNode.internalFlags = internalFlags & ~8 /* Immutable */; + } + if (leadingComments) { + destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments); + } + if (trailingComments) { + destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments); + } + if (commentRange) { + destEmitNode.commentRange = commentRange; + } + if (sourceMapRange) { + destEmitNode.sourceMapRange = sourceMapRange; + } + if (tokenSourceMapRanges) { + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + } + if (constantValue !== void 0) { + destEmitNode.constantValue = constantValue; + } + if (helpers) { + for (const helper of helpers) { + destEmitNode.helpers = appendIfUnique(destEmitNode.helpers, helper); + } + } + if (startsOnNewLine !== void 0) { + destEmitNode.startsOnNewLine = startsOnNewLine; + } + if (snippetElement !== void 0) { + destEmitNode.snippetElement = snippetElement; + } + if (classThis) { + destEmitNode.classThis = classThis; + } + if (assignedName) { + destEmitNode.assignedName = assignedName; + } + return destEmitNode; +} +function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) destRanges = []; + for (const key in sourceRanges) { + destRanges[key] = sourceRanges[key]; + } + return destRanges; +} + +// src/compiler/factory/emitNode.ts +function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (isParseTreeNode(node)) { + if (node.kind === 307 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + const sourceFile = getSourceFileOfNode(getParseTreeNode(getSourceFileOfNode(node))) ?? Debug.fail("Could not determine parsed source file."); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } else { + Debug.assert(!(node.emitNode.internalFlags & 8 /* Immutable */), "Invalid attempt to mutate an immutable node."); + } + return node.emitNode; +} +function disposeEmitNodes(sourceFile) { + var _a, _b; + const annotatedNodes = (_b = (_a = getSourceFileOfNode(getParseTreeNode(sourceFile))) == null ? void 0 : _a.emitNode) == null ? void 0 : _b.annotatedNodes; + if (annotatedNodes) { + for (const node of annotatedNodes) { + node.emitNode = void 0; + } + } +} +function removeAllComments(node) { + const emitNode = getOrCreateEmitNode(node); + emitNode.flags |= 3072 /* NoComments */; + emitNode.leadingComments = void 0; + emitNode.trailingComments = void 0; + return node; +} +function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; +} +function addEmitFlags(node, emitFlags) { + const emitNode = getOrCreateEmitNode(node); + emitNode.flags = emitNode.flags | emitFlags; + return node; +} +function setInternalEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).internalFlags = emitFlags; + return node; +} +function addInternalEmitFlags(node, emitFlags) { + const emitNode = getOrCreateEmitNode(node); + emitNode.internalFlags = emitNode.internalFlags | emitFlags; + return node; +} +function getSourceMapRange(node) { + var _a; + return ((_a = node.emitNode) == null ? void 0 : _a.sourceMapRange) ?? node; +} +function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; +} +function setTokenSourceMapRange(node, token, range) { + const emitNode = getOrCreateEmitNode(node); + const tokenSourceMapRanges = emitNode.tokenSourceMapRanges ?? (emitNode.tokenSourceMapRanges = []); + tokenSourceMapRanges[token] = range; + return node; +} +function getStartsOnNewLine(node) { + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.startsOnNewLine; +} +function setStartsOnNewLine(node, newLine) { + getOrCreateEmitNode(node).startsOnNewLine = newLine; + return node; +} +function getCommentRange(node) { + var _a; + return ((_a = node.emitNode) == null ? void 0 : _a.commentRange) ?? node; +} +function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; +} +function getSyntheticLeadingComments(node) { + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.leadingComments; +} +function setSyntheticLeadingComments(node, comments) { + getOrCreateEmitNode(node).leadingComments = comments; + return node; +} +function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticLeadingComments(node, append(getSyntheticLeadingComments(node), { kind, pos: -1, end: -1, hasTrailingNewLine, text })); +} +function getSyntheticTrailingComments(node) { + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.trailingComments; +} +function setSyntheticTrailingComments(node, comments) { + getOrCreateEmitNode(node).trailingComments = comments; + return node; +} +function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) { + return setSyntheticTrailingComments(node, append(getSyntheticTrailingComments(node), { kind, pos: -1, end: -1, hasTrailingNewLine, text })); +} +function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + const emit = getOrCreateEmitNode(original); + emit.leadingComments = void 0; + emit.trailingComments = void 0; + return node; +} +function getConstantValue(node) { + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.constantValue; +} +function setConstantValue(node, value) { + const emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; +} +function addEmitHelper(node, helper) { + const emitNode = getOrCreateEmitNode(node); + emitNode.helpers = append(emitNode.helpers, helper); + return node; +} +function addEmitHelpers(node, helpers) { + if (some(helpers)) { + const emitNode = getOrCreateEmitNode(node); + for (const helper of helpers) { + emitNode.helpers = appendIfUnique(emitNode.helpers, helper); + } + } + return node; +} +function getEmitHelpers(node) { + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.helpers; +} +function moveEmitHelpers(source, target, predicate) { + const sourceEmitNode = source.emitNode; + const sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; + if (!some(sourceEmitHelpers)) return; + const targetEmitNode = getOrCreateEmitNode(target); + let helpersRemoved = 0; + for (let i = 0; i < sourceEmitHelpers.length; i++) { + const helper = sourceEmitHelpers[i]; + if (predicate(helper)) { + helpersRemoved++; + targetEmitNode.helpers = appendIfUnique(targetEmitNode.helpers, helper); + } else if (helpersRemoved > 0) { + sourceEmitHelpers[i - helpersRemoved] = helper; + } + } + if (helpersRemoved > 0) { + sourceEmitHelpers.length -= helpersRemoved; + } +} +function getSnippetElement(node) { + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.snippetElement; +} +function setTypeNode(node, type) { + const emitNode = getOrCreateEmitNode(node); + emitNode.typeNode = type; + return node; +} +function getTypeNode(node) { + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.typeNode; +} +function setIdentifierTypeArguments(node, typeArguments) { + getOrCreateEmitNode(node).identifierTypeArguments = typeArguments; + return node; +} +function getIdentifierTypeArguments(node) { + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.identifierTypeArguments; +} +function setIdentifierAutoGenerate(node, autoGenerate) { + getOrCreateEmitNode(node).autoGenerate = autoGenerate; + return node; +} +function setIdentifierGeneratedImportReference(node, value) { + getOrCreateEmitNode(node).generatedImportReference = value; + return node; +} +function getIdentifierGeneratedImportReference(node) { + var _a; + return (_a = node.emitNode) == null ? void 0 : _a.generatedImportReference; +} + +// src/compiler/factory/emitHelpers.ts +function createEmitHelperFactory(context) { + const factory2 = context.factory; + const immutableTrue = memoize(() => setInternalEmitFlags(factory2.createTrue(), 8 /* Immutable */)); + const immutableFalse = memoize(() => setInternalEmitFlags(factory2.createFalse(), 8 /* Immutable */)); + return { + getUnscopedHelperName, + // TypeScript Helpers + createDecorateHelper, + createMetadataHelper, + createParamHelper, + // ES Decorators Helpers + createESDecorateHelper, + createRunInitializersHelper, + // ES2018 Helpers + createAssignHelper, + createAwaitHelper, + createAsyncGeneratorHelper, + createAsyncDelegatorHelper, + createAsyncValuesHelper, + // ES2018 Destructuring Helpers + createRestHelper, + // ES2017 Helpers + createAwaiterHelper, + // ES2015 Helpers + createExtendsHelper, + createTemplateObjectHelper, + createSpreadArrayHelper, + createPropKeyHelper, + createSetFunctionNameHelper, + // ES2015 Destructuring Helpers + createValuesHelper, + createReadHelper, + // ES2015 Generator Helpers + createGeneratorHelper, + // ES Module Helpers + createImportStarHelper, + createImportStarCallbackHelper, + createImportDefaultHelper, + createExportStarHelper, + // Class Fields Helpers + createClassPrivateFieldGetHelper, + createClassPrivateFieldSetHelper, + createClassPrivateFieldInHelper, + // 'using' helpers + createAddDisposableResourceHelper, + createDisposeResourcesHelper, + // --rewriteRelativeImportExtensions helpers + createRewriteRelativeImportExtensionsHelper + }; + function getUnscopedHelperName(name) { + return setEmitFlags(factory2.createIdentifier(name), 8192 /* HelperName */ | 4 /* AdviseOnEmitNode */); + } + function createDecorateHelper(decoratorExpressions, target, memberName, descriptor) { + context.requestEmitHelper(decorateHelper); + const argumentsArray = []; + argumentsArray.push(factory2.createArrayLiteralExpression( + decoratorExpressions, + /*multiLine*/ + true + )); + argumentsArray.push(target); + if (memberName) { + argumentsArray.push(memberName); + if (descriptor) { + argumentsArray.push(descriptor); + } + } + return factory2.createCallExpression( + getUnscopedHelperName("__decorate"), + /*typeArguments*/ + void 0, + argumentsArray + ); + } + function createMetadataHelper(metadataKey, metadataValue) { + context.requestEmitHelper(metadataHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__metadata"), + /*typeArguments*/ + void 0, + [ + factory2.createStringLiteral(metadataKey), + metadataValue + ] + ); + } + function createParamHelper(expression, parameterOffset, location) { + context.requestEmitHelper(paramHelper); + return setTextRange( + factory2.createCallExpression( + getUnscopedHelperName("__param"), + /*typeArguments*/ + void 0, + [ + factory2.createNumericLiteral(parameterOffset + ""), + expression + ] + ), + location + ); + } + function createESDecorateClassContextObject(contextIn) { + const properties = [ + factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral("class")), + factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name), + factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata) + ]; + return factory2.createObjectLiteralExpression(properties); + } + function createESDecorateClassElementAccessGetMethod(elementName) { + const accessor = elementName.computed ? factory2.createElementAccessExpression(factory2.createIdentifier("obj"), elementName.name) : factory2.createPropertyAccessExpression(factory2.createIdentifier("obj"), elementName.name); + return factory2.createPropertyAssignment( + "get", + factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + factory2.createIdentifier("obj") + )], + /*type*/ + void 0, + /*equalsGreaterThanToken*/ + void 0, + accessor + ) + ); + } + function createESDecorateClassElementAccessSetMethod(elementName) { + const accessor = elementName.computed ? factory2.createElementAccessExpression(factory2.createIdentifier("obj"), elementName.name) : factory2.createPropertyAccessExpression(factory2.createIdentifier("obj"), elementName.name); + return factory2.createPropertyAssignment( + "set", + factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + [ + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + factory2.createIdentifier("obj") + ), + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + factory2.createIdentifier("value") + ) + ], + /*type*/ + void 0, + /*equalsGreaterThanToken*/ + void 0, + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment( + accessor, + factory2.createIdentifier("value") + ) + ) + ]) + ) + ); + } + function createESDecorateClassElementAccessHasMethod(elementName) { + const propertyName = elementName.computed ? elementName.name : isIdentifier(elementName.name) ? factory2.createStringLiteralFromNode(elementName.name) : elementName.name; + return factory2.createPropertyAssignment( + "has", + factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + factory2.createIdentifier("obj") + )], + /*type*/ + void 0, + /*equalsGreaterThanToken*/ + void 0, + factory2.createBinaryExpression( + propertyName, + 103 /* InKeyword */, + factory2.createIdentifier("obj") + ) + ) + ); + } + function createESDecorateClassElementAccessObject(name, access) { + const properties = []; + properties.push(createESDecorateClassElementAccessHasMethod(name)); + if (access.get) properties.push(createESDecorateClassElementAccessGetMethod(name)); + if (access.set) properties.push(createESDecorateClassElementAccessSetMethod(name)); + return factory2.createObjectLiteralExpression(properties); + } + function createESDecorateClassElementContextObject(contextIn) { + const properties = [ + factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral(contextIn.kind)), + factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name.computed ? contextIn.name.name : factory2.createStringLiteralFromNode(contextIn.name.name)), + factory2.createPropertyAssignment(factory2.createIdentifier("static"), contextIn.static ? factory2.createTrue() : factory2.createFalse()), + factory2.createPropertyAssignment(factory2.createIdentifier("private"), contextIn.private ? factory2.createTrue() : factory2.createFalse()), + factory2.createPropertyAssignment(factory2.createIdentifier("access"), createESDecorateClassElementAccessObject(contextIn.name, contextIn.access)), + factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata) + ]; + return factory2.createObjectLiteralExpression(properties); + } + function createESDecorateContextObject(contextIn) { + return contextIn.kind === "class" ? createESDecorateClassContextObject(contextIn) : createESDecorateClassElementContextObject(contextIn); + } + function createESDecorateHelper(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + context.requestEmitHelper(esDecorateHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__esDecorate"), + /*typeArguments*/ + void 0, + [ + ctor ?? factory2.createNull(), + descriptorIn ?? factory2.createNull(), + decorators, + createESDecorateContextObject(contextIn), + initializers, + extraInitializers + ] + ); + } + function createRunInitializersHelper(thisArg, initializers, value) { + context.requestEmitHelper(runInitializersHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__runInitializers"), + /*typeArguments*/ + void 0, + value ? [thisArg, initializers, value] : [thisArg, initializers] + ); + } + function createAssignHelper(attributesSegments) { + if (getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) { + return factory2.createCallExpression( + factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "assign"), + /*typeArguments*/ + void 0, + attributesSegments + ); + } + context.requestEmitHelper(assignHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__assign"), + /*typeArguments*/ + void 0, + attributesSegments + ); + } + function createAwaitHelper(expression) { + context.requestEmitHelper(awaitHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__await"), + /*typeArguments*/ + void 0, + [expression] + ); + } + function createAsyncGeneratorHelper(generatorFunc, hasLexicalThis) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncGeneratorHelper); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 524288 /* AsyncFunctionBody */ | 1048576 /* ReuseTempVariableScope */; + return factory2.createCallExpression( + getUnscopedHelperName("__asyncGenerator"), + /*typeArguments*/ + void 0, + [ + hasLexicalThis ? factory2.createThis() : factory2.createVoidZero(), + factory2.createIdentifier("arguments"), + generatorFunc + ] + ); + } + function createAsyncDelegatorHelper(expression) { + context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(asyncDelegator); + return factory2.createCallExpression( + getUnscopedHelperName("__asyncDelegator"), + /*typeArguments*/ + void 0, + [expression] + ); + } + function createAsyncValuesHelper(expression) { + context.requestEmitHelper(asyncValues); + return factory2.createCallExpression( + getUnscopedHelperName("__asyncValues"), + /*typeArguments*/ + void 0, + [expression] + ); + } + function createRestHelper(value, elements, computedTempVariables, location) { + context.requestEmitHelper(restHelper); + const propertyNames = []; + let computedTempVariableOffset = 0; + for (let i = 0; i < elements.length - 1; i++) { + const propertyName = getPropertyNameOfBindingOrAssignmentElement(elements[i]); + if (propertyName) { + if (isComputedPropertyName(propertyName)) { + Debug.assertIsDefined(computedTempVariables, "Encountered computed property name but 'computedTempVariables' argument was not provided."); + const temp = computedTempVariables[computedTempVariableOffset]; + computedTempVariableOffset++; + propertyNames.push( + factory2.createConditionalExpression( + factory2.createTypeCheck(temp, "symbol"), + /*questionToken*/ + void 0, + temp, + /*colonToken*/ + void 0, + factory2.createAdd(temp, factory2.createStringLiteral("")) + ) + ); + } else { + propertyNames.push(factory2.createStringLiteralFromNode(propertyName)); + } + } + } + return factory2.createCallExpression( + getUnscopedHelperName("__rest"), + /*typeArguments*/ + void 0, + [ + value, + setTextRange( + factory2.createArrayLiteralExpression(propertyNames), + location + ) + ] + ); + } + function createAwaiterHelper(hasLexicalThis, argumentsExpression, promiseConstructor, parameters, body) { + context.requestEmitHelper(awaiterHelper); + const generatorFunc = factory2.createFunctionExpression( + /*modifiers*/ + void 0, + factory2.createToken(42 /* AsteriskToken */), + /*name*/ + void 0, + /*typeParameters*/ + void 0, + parameters ?? [], + /*type*/ + void 0, + body + ); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 524288 /* AsyncFunctionBody */ | 1048576 /* ReuseTempVariableScope */; + return factory2.createCallExpression( + getUnscopedHelperName("__awaiter"), + /*typeArguments*/ + void 0, + [ + hasLexicalThis ? factory2.createThis() : factory2.createVoidZero(), + argumentsExpression ?? factory2.createVoidZero(), + promiseConstructor ? createExpressionFromEntityName(factory2, promiseConstructor) : factory2.createVoidZero(), + generatorFunc + ] + ); + } + function createExtendsHelper(name) { + context.requestEmitHelper(extendsHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__extends"), + /*typeArguments*/ + void 0, + [name, factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)] + ); + } + function createTemplateObjectHelper(cooked, raw) { + context.requestEmitHelper(templateObjectHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__makeTemplateObject"), + /*typeArguments*/ + void 0, + [cooked, raw] + ); + } + function createSpreadArrayHelper(to, from, packFrom) { + context.requestEmitHelper(spreadArrayHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__spreadArray"), + /*typeArguments*/ + void 0, + [to, from, packFrom ? immutableTrue() : immutableFalse()] + ); + } + function createPropKeyHelper(expr) { + context.requestEmitHelper(propKeyHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__propKey"), + /*typeArguments*/ + void 0, + [expr] + ); + } + function createSetFunctionNameHelper(f, name, prefix) { + context.requestEmitHelper(setFunctionNameHelper); + return context.factory.createCallExpression( + getUnscopedHelperName("__setFunctionName"), + /*typeArguments*/ + void 0, + prefix ? [f, name, context.factory.createStringLiteral(prefix)] : [f, name] + ); + } + function createValuesHelper(expression) { + context.requestEmitHelper(valuesHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__values"), + /*typeArguments*/ + void 0, + [expression] + ); + } + function createReadHelper(iteratorRecord, count) { + context.requestEmitHelper(readHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__read"), + /*typeArguments*/ + void 0, + count !== void 0 ? [iteratorRecord, factory2.createNumericLiteral(count + "")] : [iteratorRecord] + ); + } + function createGeneratorHelper(body) { + context.requestEmitHelper(generatorHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__generator"), + /*typeArguments*/ + void 0, + [factory2.createThis(), body] + ); + } + function createImportStarHelper(expression) { + context.requestEmitHelper(importStarHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__importStar"), + /*typeArguments*/ + void 0, + [expression] + ); + } + function createImportStarCallbackHelper() { + context.requestEmitHelper(importStarHelper); + return getUnscopedHelperName("__importStar"); + } + function createImportDefaultHelper(expression) { + context.requestEmitHelper(importDefaultHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__importDefault"), + /*typeArguments*/ + void 0, + [expression] + ); + } + function createExportStarHelper(moduleExpression, exportsExpression = factory2.createIdentifier("exports")) { + context.requestEmitHelper(exportStarHelper); + context.requestEmitHelper(createBindingHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__exportStar"), + /*typeArguments*/ + void 0, + [moduleExpression, exportsExpression] + ); + } + function createClassPrivateFieldGetHelper(receiver, state, kind, f) { + context.requestEmitHelper(classPrivateFieldGetHelper); + let args; + if (!f) { + args = [receiver, state, factory2.createStringLiteral(kind)]; + } else { + args = [receiver, state, factory2.createStringLiteral(kind), f]; + } + return factory2.createCallExpression( + getUnscopedHelperName("__classPrivateFieldGet"), + /*typeArguments*/ + void 0, + args + ); + } + function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) { + context.requestEmitHelper(classPrivateFieldSetHelper); + let args; + if (!f) { + args = [receiver, state, value, factory2.createStringLiteral(kind)]; + } else { + args = [receiver, state, value, factory2.createStringLiteral(kind), f]; + } + return factory2.createCallExpression( + getUnscopedHelperName("__classPrivateFieldSet"), + /*typeArguments*/ + void 0, + args + ); + } + function createClassPrivateFieldInHelper(state, receiver) { + context.requestEmitHelper(classPrivateFieldInHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__classPrivateFieldIn"), + /*typeArguments*/ + void 0, + [state, receiver] + ); + } + function createAddDisposableResourceHelper(envBinding, value, async) { + context.requestEmitHelper(addDisposableResourceHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__addDisposableResource"), + /*typeArguments*/ + void 0, + [envBinding, value, async ? factory2.createTrue() : factory2.createFalse()] + ); + } + function createDisposeResourcesHelper(envBinding) { + context.requestEmitHelper(disposeResourcesHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__disposeResources"), + /*typeArguments*/ + void 0, + [envBinding] + ); + } + function createRewriteRelativeImportExtensionsHelper(expression) { + context.requestEmitHelper(rewriteRelativeImportExtensionsHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__rewriteRelativeImportExtension"), + /*typeArguments*/ + void 0, + context.getCompilerOptions().jsx === 1 /* Preserve */ ? [expression, factory2.createTrue()] : [expression] + ); + } +} +function compareEmitHelpers(x, y) { + if (x === y) return 0 /* EqualTo */; + if (x.priority === y.priority) return 0 /* EqualTo */; + if (x.priority === void 0) return 1 /* GreaterThan */; + if (y.priority === void 0) return -1 /* LessThan */; + return compareValues(x.priority, y.priority); +} +function helperString(input, ...args) { + return (uniqueName) => { + let result = ""; + for (let i = 0; i < args.length; i++) { + result += input[i]; + result += uniqueName(args[i]); + } + result += input[input.length - 1]; + return result; + }; +} +var decorateHelper = { + name: "typescript:decorate", + importName: "__decorate", + scoped: false, + priority: 2, + text: ` + var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + };` +}; +var metadataHelper = { + name: "typescript:metadata", + importName: "__metadata", + scoped: false, + priority: 3, + text: ` + var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); + };` +}; +var paramHelper = { + name: "typescript:param", + importName: "__param", + scoped: false, + priority: 4, + text: ` + var __param = (this && this.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + };` +}; +var esDecorateHelper = { + name: "typescript:esDecorate", + importName: "__esDecorate", + scoped: false, + priority: 2, + text: ` + var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + };` +}; +var runInitializersHelper = { + name: "typescript:runInitializers", + importName: "__runInitializers", + scoped: false, + priority: 2, + text: ` + var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + };` +}; +var assignHelper = { + name: "typescript:assign", + importName: "__assign", + scoped: false, + priority: 1, + text: ` + var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + };` +}; +var awaitHelper = { + name: "typescript:await", + importName: "__await", + scoped: false, + text: ` + var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }` +}; +var asyncGeneratorHelper = { + name: "typescript:asyncGenerator", + importName: "__asyncGenerator", + scoped: false, + dependencies: [awaitHelper], + text: ` + var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + };` +}; +var asyncDelegator = { + name: "typescript:asyncDelegator", + importName: "__asyncDelegator", + scoped: false, + dependencies: [awaitHelper], + text: ` + var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + };` +}; +var asyncValues = { + name: "typescript:asyncValues", + importName: "__asyncValues", + scoped: false, + text: ` + var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + };` +}; +var restHelper = { + name: "typescript:rest", + importName: "__rest", + scoped: false, + text: ` + var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + };` +}; +var awaiterHelper = { + name: "typescript:awaiter", + importName: "__awaiter", + scoped: false, + priority: 5, + text: ` + var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + };` +}; +var extendsHelper = { + name: "typescript:extends", + importName: "__extends", + scoped: false, + priority: 0, + text: ` + var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })();` +}; +var templateObjectHelper = { + name: "typescript:makeTemplateObject", + importName: "__makeTemplateObject", + scoped: false, + priority: 0, + text: ` + var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + };` +}; +var readHelper = { + name: "typescript:read", + importName: "__read", + scoped: false, + text: ` + var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + };` +}; +var spreadArrayHelper = { + name: "typescript:spreadArray", + importName: "__spreadArray", + scoped: false, + text: ` + var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + };` +}; +var propKeyHelper = { + name: "typescript:propKey", + importName: "__propKey", + scoped: false, + text: ` + var __propKey = (this && this.__propKey) || function (x) { + return typeof x === "symbol" ? x : "".concat(x); + };` +}; +var setFunctionNameHelper = { + name: "typescript:setFunctionName", + importName: "__setFunctionName", + scoped: false, + text: ` + var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + };` +}; +var valuesHelper = { + name: "typescript:values", + importName: "__values", + scoped: false, + text: ` + var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + };` +}; +var generatorHelper = { + name: "typescript:generator", + importName: "__generator", + scoped: false, + priority: 6, + text: ` + var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + };` +}; +var createBindingHelper = { + name: "typescript:commonjscreatebinding", + importName: "__createBinding", + scoped: false, + priority: 1, + text: ` + var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }));` +}; +var setModuleDefaultHelper = { + name: "typescript:commonjscreatevalue", + importName: "__setModuleDefault", + scoped: false, + priority: 1, + text: ` + var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + });` +}; +var importStarHelper = { + name: "typescript:commonjsimportstar", + importName: "__importStar", + scoped: false, + dependencies: [createBindingHelper, setModuleDefaultHelper], + priority: 2, + text: ` + var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; + })();` +}; +var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + importName: "__importDefault", + scoped: false, + text: ` + var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + };` +}; +var exportStarHelper = { + name: "typescript:export-star", + importName: "__exportStar", + scoped: false, + dependencies: [createBindingHelper], + priority: 2, + text: ` + var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); + };` +}; +var classPrivateFieldGetHelper = { + name: "typescript:classPrivateFieldGet", + importName: "__classPrivateFieldGet", + scoped: false, + text: ` + var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + };` +}; +var classPrivateFieldSetHelper = { + name: "typescript:classPrivateFieldSet", + importName: "__classPrivateFieldSet", + scoped: false, + text: ` + var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + };` +}; +var classPrivateFieldInHelper = { + name: "typescript:classPrivateFieldIn", + importName: "__classPrivateFieldIn", + scoped: false, + text: ` + var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + };` +}; +var addDisposableResourceHelper = { + name: "typescript:addDisposableResource", + importName: "__addDisposableResource", + scoped: false, + text: ` + var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + };` +}; +var disposeResourcesHelper = { + name: "typescript:disposeResources", + importName: "__disposeResources", + scoped: false, + text: ` + var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { + return function (env) { + function fail(e) { + env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; + })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + });` +}; +var rewriteRelativeImportExtensionsHelper = { + name: "typescript:rewriteRelativeImportExtensions", + importName: "__rewriteRelativeImportExtension", + scoped: false, + text: ` + var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) { + if (typeof path === "string" && /^\\.\\.?\\//.test(path)) { + return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; + };` +}; +var asyncSuperHelper = { + name: "typescript:async-super", + scoped: true, + text: helperString` + const ${"_superIndex"} = name => super[name];` +}; +var advancedAsyncSuperHelper = { + name: "typescript:advanced-async-super", + scoped: true, + text: helperString` + const ${"_superIndex"} = (function (geti, seti) { + const cache = Object.create(null); + return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + })(name => super[name], (name, value) => super[name] = value);` +}; +function isCallToHelper(firstSegment, helperName) { + return isCallExpression(firstSegment) && isIdentifier(firstSegment.expression) && (getEmitFlags(firstSegment.expression) & 8192 /* HelperName */) !== 0 && firstSegment.expression.escapedText === helperName; +} + +// src/compiler/factory/nodeTests.ts +function isNumericLiteral(node) { + return node.kind === 9 /* NumericLiteral */; +} +function isBigIntLiteral(node) { + return node.kind === 10 /* BigIntLiteral */; +} +function isStringLiteral(node) { + return node.kind === 11 /* StringLiteral */; +} +function isJsxText(node) { + return node.kind === 12 /* JsxText */; +} +function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 15 /* NoSubstitutionTemplateLiteral */; +} +function isTemplateHead(node) { + return node.kind === 16 /* TemplateHead */; +} +function isDotDotDotToken(node) { + return node.kind === 26 /* DotDotDotToken */; +} +function isCommaToken(node) { + return node.kind === 28 /* CommaToken */; +} +function isPlusToken(node) { + return node.kind === 40 /* PlusToken */; +} +function isMinusToken(node) { + return node.kind === 41 /* MinusToken */; +} +function isAsteriskToken(node) { + return node.kind === 42 /* AsteriskToken */; +} +function isExclamationToken(node) { + return node.kind === 54 /* ExclamationToken */; +} +function isQuestionToken(node) { + return node.kind === 58 /* QuestionToken */; +} +function isColonToken(node) { + return node.kind === 59 /* ColonToken */; +} +function isQuestionDotToken(node) { + return node.kind === 29 /* QuestionDotToken */; +} +function isEqualsGreaterThanToken(node) { + return node.kind === 39 /* EqualsGreaterThanToken */; +} +function isIdentifier(node) { + return node.kind === 80 /* Identifier */; +} +function isPrivateIdentifier(node) { + return node.kind === 81 /* PrivateIdentifier */; +} +function isExportModifier(node) { + return node.kind === 95 /* ExportKeyword */; +} +function isDefaultModifier(node) { + return node.kind === 90 /* DefaultKeyword */; +} +function isAsyncModifier(node) { + return node.kind === 134 /* AsyncKeyword */; +} +function isAssertsKeyword(node) { + return node.kind === 131 /* AssertsKeyword */; +} +function isAwaitKeyword(node) { + return node.kind === 135 /* AwaitKeyword */; +} +function isReadonlyKeyword(node) { + return node.kind === 148 /* ReadonlyKeyword */; +} +function isStaticModifier(node) { + return node.kind === 126 /* StaticKeyword */; +} +function isAccessorModifier(node) { + return node.kind === 129 /* AccessorKeyword */; +} +function isSuperKeyword(node) { + return node.kind === 108 /* SuperKeyword */; +} +function isImportKeyword(node) { + return node.kind === 102 /* ImportKeyword */; +} +function isQualifiedName(node) { + return node.kind === 166 /* QualifiedName */; +} +function isComputedPropertyName(node) { + return node.kind === 167 /* ComputedPropertyName */; +} +function isTypeParameterDeclaration(node) { + return node.kind === 168 /* TypeParameter */; +} +function isParameter(node) { + return node.kind === 169 /* Parameter */; +} +function isDecorator(node) { + return node.kind === 170 /* Decorator */; +} +function isPropertySignature(node) { + return node.kind === 171 /* PropertySignature */; +} +function isPropertyDeclaration(node) { + return node.kind === 172 /* PropertyDeclaration */; +} +function isMethodSignature(node) { + return node.kind === 173 /* MethodSignature */; +} +function isMethodDeclaration(node) { + return node.kind === 174 /* MethodDeclaration */; +} +function isClassStaticBlockDeclaration(node) { + return node.kind === 175 /* ClassStaticBlockDeclaration */; +} +function isConstructorDeclaration(node) { + return node.kind === 176 /* Constructor */; +} +function isGetAccessorDeclaration(node) { + return node.kind === 177 /* GetAccessor */; +} +function isSetAccessorDeclaration(node) { + return node.kind === 178 /* SetAccessor */; +} +function isCallSignatureDeclaration(node) { + return node.kind === 179 /* CallSignature */; +} +function isConstructSignatureDeclaration(node) { + return node.kind === 180 /* ConstructSignature */; +} +function isIndexSignatureDeclaration(node) { + return node.kind === 181 /* IndexSignature */; +} +function isTypePredicateNode(node) { + return node.kind === 182 /* TypePredicate */; +} +function isTypeReferenceNode(node) { + return node.kind === 183 /* TypeReference */; +} +function isFunctionTypeNode(node) { + return node.kind === 184 /* FunctionType */; +} +function isConstructorTypeNode(node) { + return node.kind === 185 /* ConstructorType */; +} +function isTypeQueryNode(node) { + return node.kind === 186 /* TypeQuery */; +} +function isTypeLiteralNode(node) { + return node.kind === 187 /* TypeLiteral */; +} +function isArrayTypeNode(node) { + return node.kind === 188 /* ArrayType */; +} +function isTupleTypeNode(node) { + return node.kind === 189 /* TupleType */; +} +function isNamedTupleMember(node) { + return node.kind === 202 /* NamedTupleMember */; +} +function isOptionalTypeNode(node) { + return node.kind === 190 /* OptionalType */; +} +function isRestTypeNode(node) { + return node.kind === 191 /* RestType */; +} +function isUnionTypeNode(node) { + return node.kind === 192 /* UnionType */; +} +function isIntersectionTypeNode(node) { + return node.kind === 193 /* IntersectionType */; +} +function isConditionalTypeNode(node) { + return node.kind === 194 /* ConditionalType */; +} +function isInferTypeNode(node) { + return node.kind === 195 /* InferType */; +} +function isParenthesizedTypeNode(node) { + return node.kind === 196 /* ParenthesizedType */; +} +function isThisTypeNode(node) { + return node.kind === 197 /* ThisType */; +} +function isTypeOperatorNode(node) { + return node.kind === 198 /* TypeOperator */; +} +function isIndexedAccessTypeNode(node) { + return node.kind === 199 /* IndexedAccessType */; +} +function isMappedTypeNode(node) { + return node.kind === 200 /* MappedType */; +} +function isLiteralTypeNode(node) { + return node.kind === 201 /* LiteralType */; +} +function isImportTypeNode(node) { + return node.kind === 205 /* ImportType */; +} +function isTemplateLiteralTypeSpan(node) { + return node.kind === 204 /* TemplateLiteralTypeSpan */; +} +function isObjectBindingPattern(node) { + return node.kind === 206 /* ObjectBindingPattern */; +} +function isArrayBindingPattern(node) { + return node.kind === 207 /* ArrayBindingPattern */; +} +function isBindingElement(node) { + return node.kind === 208 /* BindingElement */; +} +function isArrayLiteralExpression(node) { + return node.kind === 209 /* ArrayLiteralExpression */; +} +function isObjectLiteralExpression(node) { + return node.kind === 210 /* ObjectLiteralExpression */; +} +function isPropertyAccessExpression(node) { + return node.kind === 211 /* PropertyAccessExpression */; +} +function isElementAccessExpression(node) { + return node.kind === 212 /* ElementAccessExpression */; +} +function isCallExpression(node) { + return node.kind === 213 /* CallExpression */; +} +function isNewExpression(node) { + return node.kind === 214 /* NewExpression */; +} +function isTaggedTemplateExpression(node) { + return node.kind === 215 /* TaggedTemplateExpression */; +} +function isTypeAssertionExpression(node) { + return node.kind === 216 /* TypeAssertionExpression */; +} +function isParenthesizedExpression(node) { + return node.kind === 217 /* ParenthesizedExpression */; +} +function isFunctionExpression(node) { + return node.kind === 218 /* FunctionExpression */; +} +function isArrowFunction(node) { + return node.kind === 219 /* ArrowFunction */; +} +function isTypeOfExpression(node) { + return node.kind === 221 /* TypeOfExpression */; +} +function isVoidExpression(node) { + return node.kind === 222 /* VoidExpression */; +} +function isAwaitExpression(node) { + return node.kind === 223 /* AwaitExpression */; +} +function isPrefixUnaryExpression(node) { + return node.kind === 224 /* PrefixUnaryExpression */; +} +function isPostfixUnaryExpression(node) { + return node.kind === 225 /* PostfixUnaryExpression */; +} +function isBinaryExpression(node) { + return node.kind === 226 /* BinaryExpression */; +} +function isConditionalExpression(node) { + return node.kind === 227 /* ConditionalExpression */; +} +function isSpreadElement(node) { + return node.kind === 230 /* SpreadElement */; +} +function isClassExpression(node) { + return node.kind === 231 /* ClassExpression */; +} +function isOmittedExpression(node) { + return node.kind === 232 /* OmittedExpression */; +} +function isExpressionWithTypeArguments(node) { + return node.kind === 233 /* ExpressionWithTypeArguments */; +} +function isAsExpression(node) { + return node.kind === 234 /* AsExpression */; +} +function isSatisfiesExpression(node) { + return node.kind === 238 /* SatisfiesExpression */; +} +function isNonNullExpression(node) { + return node.kind === 235 /* NonNullExpression */; +} +function isMetaProperty(node) { + return node.kind === 236 /* MetaProperty */; +} +function isPartiallyEmittedExpression(node) { + return node.kind === 355 /* PartiallyEmittedExpression */; +} +function isCommaListExpression(node) { + return node.kind === 356 /* CommaListExpression */; +} +function isTemplateSpan(node) { + return node.kind === 239 /* TemplateSpan */; +} +function isSemicolonClassElement(node) { + return node.kind === 240 /* SemicolonClassElement */; +} +function isBlock(node) { + return node.kind === 241 /* Block */; +} +function isVariableStatement(node) { + return node.kind === 243 /* VariableStatement */; +} +function isEmptyStatement(node) { + return node.kind === 242 /* EmptyStatement */; +} +function isExpressionStatement(node) { + return node.kind === 244 /* ExpressionStatement */; +} +function isIfStatement(node) { + return node.kind === 245 /* IfStatement */; +} +function isForStatement(node) { + return node.kind === 248 /* ForStatement */; +} +function isForInStatement(node) { + return node.kind === 249 /* ForInStatement */; +} +function isForOfStatement(node) { + return node.kind === 250 /* ForOfStatement */; +} +function isReturnStatement(node) { + return node.kind === 253 /* ReturnStatement */; +} +function isWithStatement(node) { + return node.kind === 254 /* WithStatement */; +} +function isSwitchStatement(node) { + return node.kind === 255 /* SwitchStatement */; +} +function isLabeledStatement(node) { + return node.kind === 256 /* LabeledStatement */; +} +function isTryStatement(node) { + return node.kind === 258 /* TryStatement */; +} +function isVariableDeclaration(node) { + return node.kind === 260 /* VariableDeclaration */; +} +function isVariableDeclarationList(node) { + return node.kind === 261 /* VariableDeclarationList */; +} +function isFunctionDeclaration(node) { + return node.kind === 262 /* FunctionDeclaration */; +} +function isClassDeclaration(node) { + return node.kind === 263 /* ClassDeclaration */; +} +function isInterfaceDeclaration(node) { + return node.kind === 264 /* InterfaceDeclaration */; +} +function isTypeAliasDeclaration(node) { + return node.kind === 265 /* TypeAliasDeclaration */; +} +function isEnumDeclaration(node) { + return node.kind === 266 /* EnumDeclaration */; +} +function isModuleDeclaration(node) { + return node.kind === 267 /* ModuleDeclaration */; +} +function isModuleBlock(node) { + return node.kind === 268 /* ModuleBlock */; +} +function isCaseBlock(node) { + return node.kind === 269 /* CaseBlock */; +} +function isNamespaceExportDeclaration(node) { + return node.kind === 270 /* NamespaceExportDeclaration */; +} +function isImportEqualsDeclaration(node) { + return node.kind === 271 /* ImportEqualsDeclaration */; +} +function isImportDeclaration(node) { + return node.kind === 272 /* ImportDeclaration */; +} +function isImportClause(node) { + return node.kind === 273 /* ImportClause */; +} +function isAssertClause(node) { + return node.kind === 300 /* AssertClause */; +} +function isImportAttributes(node) { + return node.kind === 300 /* ImportAttributes */; +} +function isImportAttribute(node) { + return node.kind === 301 /* ImportAttribute */; +} +function isNamespaceImport(node) { + return node.kind === 274 /* NamespaceImport */; +} +function isNamespaceExport(node) { + return node.kind === 280 /* NamespaceExport */; +} +function isNamedImports(node) { + return node.kind === 275 /* NamedImports */; +} +function isImportSpecifier(node) { + return node.kind === 276 /* ImportSpecifier */; +} +function isExportAssignment(node) { + return node.kind === 277 /* ExportAssignment */; +} +function isExportDeclaration(node) { + return node.kind === 278 /* ExportDeclaration */; +} +function isNamedExports(node) { + return node.kind === 279 /* NamedExports */; +} +function isExportSpecifier(node) { + return node.kind === 281 /* ExportSpecifier */; +} +function isModuleExportName(node) { + return node.kind === 80 /* Identifier */ || node.kind === 11 /* StringLiteral */; +} +function isNotEmittedStatement(node) { + return node.kind === 353 /* NotEmittedStatement */; +} +function isSyntheticReference(node) { + return node.kind === 357 /* SyntheticReferenceExpression */; +} +function isExternalModuleReference(node) { + return node.kind === 283 /* ExternalModuleReference */; +} +function isJsxElement(node) { + return node.kind === 284 /* JsxElement */; +} +function isJsxSelfClosingElement(node) { + return node.kind === 285 /* JsxSelfClosingElement */; +} +function isJsxOpeningElement(node) { + return node.kind === 286 /* JsxOpeningElement */; +} +function isJsxClosingElement(node) { + return node.kind === 287 /* JsxClosingElement */; +} +function isJsxFragment(node) { + return node.kind === 288 /* JsxFragment */; +} +function isJsxOpeningFragment(node) { + return node.kind === 289 /* JsxOpeningFragment */; +} +function isJsxClosingFragment(node) { + return node.kind === 290 /* JsxClosingFragment */; +} +function isJsxAttribute(node) { + return node.kind === 291 /* JsxAttribute */; +} +function isJsxAttributes(node) { + return node.kind === 292 /* JsxAttributes */; +} +function isJsxSpreadAttribute(node) { + return node.kind === 293 /* JsxSpreadAttribute */; +} +function isJsxExpression(node) { + return node.kind === 294 /* JsxExpression */; +} +function isJsxNamespacedName(node) { + return node.kind === 295 /* JsxNamespacedName */; +} +function isCaseClause(node) { + return node.kind === 296 /* CaseClause */; +} +function isDefaultClause(node) { + return node.kind === 297 /* DefaultClause */; +} +function isHeritageClause(node) { + return node.kind === 298 /* HeritageClause */; +} +function isCatchClause(node) { + return node.kind === 299 /* CatchClause */; +} +function isPropertyAssignment(node) { + return node.kind === 303 /* PropertyAssignment */; +} +function isShorthandPropertyAssignment(node) { + return node.kind === 304 /* ShorthandPropertyAssignment */; +} +function isSpreadAssignment(node) { + return node.kind === 305 /* SpreadAssignment */; +} +function isEnumMember(node) { + return node.kind === 306 /* EnumMember */; +} +function isSourceFile(node) { + return node.kind === 307 /* SourceFile */; +} +function isBundle(node) { + return node.kind === 308 /* Bundle */; +} +function isJSDocTypeExpression(node) { + return node.kind === 309 /* JSDocTypeExpression */; +} +function isJSDocNameReference(node) { + return node.kind === 310 /* JSDocNameReference */; +} +function isJSDocMemberName(node) { + return node.kind === 311 /* JSDocMemberName */; +} +function isJSDocAllType(node) { + return node.kind === 312 /* JSDocAllType */; +} +function isJSDocUnknownType(node) { + return node.kind === 313 /* JSDocUnknownType */; +} +function isJSDocNullableType(node) { + return node.kind === 314 /* JSDocNullableType */; +} +function isJSDocNonNullableType(node) { + return node.kind === 315 /* JSDocNonNullableType */; +} +function isJSDocOptionalType(node) { + return node.kind === 316 /* JSDocOptionalType */; +} +function isJSDocFunctionType(node) { + return node.kind === 317 /* JSDocFunctionType */; +} +function isJSDocVariadicType(node) { + return node.kind === 318 /* JSDocVariadicType */; +} +function isJSDoc(node) { + return node.kind === 320 /* JSDoc */; +} +function isJSDocTypeLiteral(node) { + return node.kind === 322 /* JSDocTypeLiteral */; +} +function isJSDocSignature(node) { + return node.kind === 323 /* JSDocSignature */; +} +function isJSDocAugmentsTag(node) { + return node.kind === 328 /* JSDocAugmentsTag */; +} +function isJSDocClassTag(node) { + return node.kind === 332 /* JSDocClassTag */; +} +function isJSDocCallbackTag(node) { + return node.kind === 338 /* JSDocCallbackTag */; +} +function isJSDocPublicTag(node) { + return node.kind === 333 /* JSDocPublicTag */; +} +function isJSDocPrivateTag(node) { + return node.kind === 334 /* JSDocPrivateTag */; +} +function isJSDocProtectedTag(node) { + return node.kind === 335 /* JSDocProtectedTag */; +} +function isJSDocReadonlyTag(node) { + return node.kind === 336 /* JSDocReadonlyTag */; +} +function isJSDocOverrideTag(node) { + return node.kind === 337 /* JSDocOverrideTag */; +} +function isJSDocOverloadTag(node) { + return node.kind === 339 /* JSDocOverloadTag */; +} +function isJSDocDeprecatedTag(node) { + return node.kind === 331 /* JSDocDeprecatedTag */; +} +function isJSDocEnumTag(node) { + return node.kind === 340 /* JSDocEnumTag */; +} +function isJSDocParameterTag(node) { + return node.kind === 341 /* JSDocParameterTag */; +} +function isJSDocReturnTag(node) { + return node.kind === 342 /* JSDocReturnTag */; +} +function isJSDocThisTag(node) { + return node.kind === 343 /* JSDocThisTag */; +} +function isJSDocTypeTag(node) { + return node.kind === 344 /* JSDocTypeTag */; +} +function isJSDocTemplateTag(node) { + return node.kind === 345 /* JSDocTemplateTag */; +} +function isJSDocTypedefTag(node) { + return node.kind === 346 /* JSDocTypedefTag */; +} +function isJSDocPropertyTag(node) { + return node.kind === 348 /* JSDocPropertyTag */; +} +function isJSDocImplementsTag(node) { + return node.kind === 329 /* JSDocImplementsTag */; +} +function isJSDocSatisfiesTag(node) { + return node.kind === 350 /* JSDocSatisfiesTag */; +} +function isJSDocImportTag(node) { + return node.kind === 351 /* JSDocImportTag */; +} + +// src/compiler/factory/nodeChildren.ts +var sourceFileToNodeChildren = /* @__PURE__ */ new WeakMap(); +function getNodeChildren(node, sourceFile) { + var _a; + const kind = node.kind; + if (!isNodeKind(kind)) { + return emptyArray; + } + if (kind === 352 /* SyntaxList */) { + return node._children; + } + return (_a = sourceFileToNodeChildren.get(sourceFile)) == null ? void 0 : _a.get(node); +} +function unsetNodeChildren(node, origSourceFile) { + var _a; + if (node.kind === 352 /* SyntaxList */) { + Debug.fail("Did not expect to unset the children of a SyntaxList."); + } + (_a = sourceFileToNodeChildren.get(origSourceFile)) == null ? void 0 : _a.delete(node); +} +function transferSourceFileChildren(sourceFile, targetSourceFile) { + const map2 = sourceFileToNodeChildren.get(sourceFile); + if (map2 !== void 0) { + sourceFileToNodeChildren.delete(sourceFile); + sourceFileToNodeChildren.set(targetSourceFile, map2); + } +} + +// src/compiler/factory/utilities.ts +function createEmptyExports(factory2) { + return factory2.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory2.createNamedExports([]), + /*moduleSpecifier*/ + void 0 + ); +} +function createMemberAccessForPropertyName(factory2, target, memberName, location) { + if (isComputedPropertyName(memberName)) { + return setTextRange(factory2.createElementAccessExpression(target, memberName.expression), location); + } else { + const expression = setTextRange( + isMemberName(memberName) ? factory2.createPropertyAccessExpression(target, memberName) : factory2.createElementAccessExpression(target, memberName), + memberName + ); + addEmitFlags(expression, 128 /* NoNestedSourceMaps */); + return expression; + } +} +function createReactNamespace(reactNamespace, parent) { + const react = parseNodeFactory.createIdentifier(reactNamespace || "React"); + setParent(react, getParseTreeNode(parent)); + return react; +} +function createJsxFactoryExpressionFromEntityName(factory2, jsxFactory, parent) { + if (isQualifiedName(jsxFactory)) { + const left = createJsxFactoryExpressionFromEntityName(factory2, jsxFactory.left, parent); + const right = factory2.createIdentifier(idText(jsxFactory.right)); + right.escapedText = jsxFactory.right.escapedText; + return factory2.createPropertyAccessExpression(left, right); + } else { + return createReactNamespace(idText(jsxFactory), parent); + } +} +function createJsxFactoryExpression(factory2, jsxFactoryEntity, reactNamespace, parent) { + return jsxFactoryEntity ? createJsxFactoryExpressionFromEntityName(factory2, jsxFactoryEntity, parent) : factory2.createPropertyAccessExpression( + createReactNamespace(reactNamespace, parent), + "createElement" + ); +} +function createJsxFragmentFactoryExpression(factory2, jsxFragmentFactoryEntity, reactNamespace, parent) { + return jsxFragmentFactoryEntity ? createJsxFactoryExpressionFromEntityName(factory2, jsxFragmentFactoryEntity, parent) : factory2.createPropertyAccessExpression( + createReactNamespace(reactNamespace, parent), + "Fragment" + ); +} +function createExpressionForJsxElement(factory2, callee, tagName, props, children, location) { + const argumentsList = [tagName]; + if (props) { + argumentsList.push(props); + } + if (children && children.length > 0) { + if (!props) { + argumentsList.push(factory2.createNull()); + } + if (children.length > 1) { + for (const child of children) { + startOnNewLine(child); + argumentsList.push(child); + } + } else { + argumentsList.push(children[0]); + } + } + return setTextRange( + factory2.createCallExpression( + callee, + /*typeArguments*/ + void 0, + argumentsList + ), + location + ); +} +function createExpressionForJsxFragment(factory2, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) { + const tagName = createJsxFragmentFactoryExpression(factory2, jsxFragmentFactoryEntity, reactNamespace, parentElement); + const argumentsList = [tagName, factory2.createNull()]; + if (children && children.length > 0) { + if (children.length > 1) { + for (const child of children) { + startOnNewLine(child); + argumentsList.push(child); + } + } else { + argumentsList.push(children[0]); + } + } + return setTextRange( + factory2.createCallExpression( + createJsxFactoryExpression(factory2, jsxFactoryEntity, reactNamespace, parentElement), + /*typeArguments*/ + void 0, + argumentsList + ), + location + ); +} +function createForOfBindingStatement(factory2, node, boundValue) { + if (isVariableDeclarationList(node)) { + const firstDeclaration = first(node.declarations); + const updatedDeclaration = factory2.updateVariableDeclaration( + firstDeclaration, + firstDeclaration.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + boundValue + ); + return setTextRange( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.updateVariableDeclarationList(node, [updatedDeclaration]) + ), + /*location*/ + node + ); + } else { + const updatedExpression = setTextRange( + factory2.createAssignment(node, boundValue), + /*location*/ + node + ); + return setTextRange( + factory2.createExpressionStatement(updatedExpression), + /*location*/ + node + ); + } +} +function createExpressionFromEntityName(factory2, node) { + if (isQualifiedName(node)) { + const left = createExpressionFromEntityName(factory2, node.left); + const right = setParent(setTextRange(factory2.cloneNode(node.right), node.right), node.right.parent); + return setTextRange(factory2.createPropertyAccessExpression(left, right), node); + } else { + return setParent(setTextRange(factory2.cloneNode(node), node), node.parent); + } +} +function createExpressionForPropertyName(factory2, memberName) { + if (isIdentifier(memberName)) { + return factory2.createStringLiteralFromNode(memberName); + } else if (isComputedPropertyName(memberName)) { + return setParent(setTextRange(factory2.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent); + } else { + return setParent(setTextRange(factory2.cloneNode(memberName), memberName), memberName.parent); + } +} +function createExpressionForAccessorDeclaration(factory2, properties, property, receiver, multiLine) { + const { firstAccessor, getAccessor, setAccessor } = getAllAccessorDeclarations(properties, property); + if (property === firstAccessor) { + return setTextRange( + factory2.createObjectDefinePropertyCall( + receiver, + createExpressionForPropertyName(factory2, property.name), + factory2.createPropertyDescriptor({ + enumerable: factory2.createFalse(), + configurable: true, + get: getAccessor && setTextRange( + setOriginalNode( + factory2.createFunctionExpression( + getModifiers(getAccessor), + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + getAccessor.parameters, + /*type*/ + void 0, + getAccessor.body + // TODO: GH#18217 + ), + getAccessor + ), + getAccessor + ), + set: setAccessor && setTextRange( + setOriginalNode( + factory2.createFunctionExpression( + getModifiers(setAccessor), + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + setAccessor.parameters, + /*type*/ + void 0, + setAccessor.body + // TODO: GH#18217 + ), + setAccessor + ), + setAccessor + ) + }, !multiLine) + ), + firstAccessor + ); + } + return void 0; +} +function createExpressionForPropertyAssignment(factory2, property, receiver) { + return setOriginalNode( + setTextRange( + factory2.createAssignment( + createMemberAccessForPropertyName( + factory2, + receiver, + property.name, + /*location*/ + property.name + ), + property.initializer + ), + property + ), + property + ); +} +function createExpressionForShorthandPropertyAssignment(factory2, property, receiver) { + return setOriginalNode( + setTextRange( + factory2.createAssignment( + createMemberAccessForPropertyName( + factory2, + receiver, + property.name, + /*location*/ + property.name + ), + factory2.cloneNode(property.name) + ), + /*location*/ + property + ), + /*original*/ + property + ); +} +function createExpressionForMethodDeclaration(factory2, method, receiver) { + return setOriginalNode( + setTextRange( + factory2.createAssignment( + createMemberAccessForPropertyName( + factory2, + receiver, + method.name, + /*location*/ + method.name + ), + setOriginalNode( + setTextRange( + factory2.createFunctionExpression( + getModifiers(method), + method.asteriskToken, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + method.parameters, + /*type*/ + void 0, + method.body + // TODO: GH#18217 + ), + /*location*/ + method + ), + /*original*/ + method + ) + ), + /*location*/ + method + ), + /*original*/ + method + ); +} +function createExpressionForObjectLiteralElementLike(factory2, node, property, receiver) { + if (property.name && isPrivateIdentifier(property.name)) { + Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); + } + switch (property.kind) { + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return createExpressionForAccessorDeclaration(factory2, node.properties, property, receiver, !!node.multiLine); + case 303 /* PropertyAssignment */: + return createExpressionForPropertyAssignment(factory2, property, receiver); + case 304 /* ShorthandPropertyAssignment */: + return createExpressionForShorthandPropertyAssignment(factory2, property, receiver); + case 174 /* MethodDeclaration */: + return createExpressionForMethodDeclaration(factory2, property, receiver); + } +} +function expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, recordTempVariable, resultVariable) { + const operator = node.operator; + Debug.assert(operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */, "Expected 'node' to be a pre- or post-increment or pre- or post-decrement expression"); + const temp = factory2.createTempVariable(recordTempVariable); + expression = factory2.createAssignment(temp, expression); + setTextRange(expression, node.operand); + let operation = isPrefixUnaryExpression(node) ? factory2.createPrefixUnaryExpression(operator, temp) : factory2.createPostfixUnaryExpression(temp, operator); + setTextRange(operation, node); + if (resultVariable) { + operation = factory2.createAssignment(resultVariable, operation); + setTextRange(operation, node); + } + expression = factory2.createComma(expression, operation); + setTextRange(expression, node); + if (isPostfixUnaryExpression(node)) { + expression = factory2.createComma(expression, temp); + setTextRange(expression, node); + } + return expression; +} +function isInternalName(node) { + return (getEmitFlags(node) & 65536 /* InternalName */) !== 0; +} +function isLocalName(node) { + return (getEmitFlags(node) & 32768 /* LocalName */) !== 0; +} +function isExportName(node) { + return (getEmitFlags(node) & 16384 /* ExportName */) !== 0; +} +function isUseStrictPrologue(node) { + return isStringLiteral(node.expression) && node.expression.text === "use strict"; +} +function findUseStrictPrologue(statements) { + for (const statement of statements) { + if (isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } else { + break; + } + } + return void 0; +} +function startsWithUseStrict(statements) { + const firstStatement = firstOrUndefined(statements); + return firstStatement !== void 0 && isPrologueDirective(firstStatement) && isUseStrictPrologue(firstStatement); +} +function isCommaExpression(node) { + return node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 28 /* CommaToken */; +} +function isCommaSequence(node) { + return isCommaExpression(node) || isCommaListExpression(node); +} +function isJSDocTypeAssertion(node) { + return isParenthesizedExpression(node) && isInJSFile(node) && !!getJSDocTypeTag(node); +} +function getJSDocTypeAssertionType(node) { + const type = getJSDocType(node); + Debug.assertIsDefined(type); + return type; +} +function isOuterExpression(node, kinds = 63 /* All */) { + switch (node.kind) { + case 217 /* ParenthesizedExpression */: + if (kinds & -2147483648 /* ExcludeJSDocTypeAssertion */ && isJSDocTypeAssertion(node)) { + return false; + } + return (kinds & 1 /* Parentheses */) !== 0; + case 216 /* TypeAssertionExpression */: + case 234 /* AsExpression */: + return (kinds & 2 /* TypeAssertions */) !== 0; + case 238 /* SatisfiesExpression */: + return (kinds & (2 /* TypeAssertions */ | 32 /* Satisfies */)) !== 0; + case 233 /* ExpressionWithTypeArguments */: + return (kinds & 16 /* ExpressionsWithTypeArguments */) !== 0; + case 235 /* NonNullExpression */: + return (kinds & 4 /* NonNullAssertions */) !== 0; + case 355 /* PartiallyEmittedExpression */: + return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0; + } + return false; +} +function skipOuterExpressions(node, kinds = 63 /* All */) { + while (isOuterExpression(node, kinds)) { + node = node.expression; + } + return node; +} +function walkUpOuterExpressions(node, kinds = 63 /* All */) { + let parent = node.parent; + while (isOuterExpression(parent, kinds)) { + parent = parent.parent; + Debug.assert(parent); + } + return parent; +} +function startOnNewLine(node) { + return setStartsOnNewLine( + node, + /*newLine*/ + true + ); +} +function getExternalHelpersModuleName(node) { + const parseNode = getOriginalNode(node, isSourceFile); + const emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; +} +function hasRecordedExternalHelpers(sourceFile) { + const parseNode = getOriginalNode(sourceFile, isSourceFile); + const emitNode = parseNode && parseNode.emitNode; + return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers); +} +function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) { + if (compilerOptions.importHelpers && isEffectiveExternalModule(sourceFile, compilerOptions)) { + const moduleKind = getEmitModuleKind(compilerOptions); + const impliedModuleKind = getImpliedNodeFormatForEmitWorker(sourceFile, compilerOptions); + const helpers = getImportedHelpers(sourceFile); + if (moduleKind >= 5 /* ES2015 */ && moduleKind <= 99 /* ESNext */ || impliedModuleKind === 99 /* ESNext */ || impliedModuleKind === void 0 && moduleKind === 200 /* Preserve */) { + if (helpers) { + const helperNames = []; + for (const helper of helpers) { + const importName = helper.importName; + if (importName) { + pushIfUnique(helperNames, importName); + } + } + if (some(helperNames)) { + helperNames.sort(compareStringsCaseSensitive); + const namedBindings = nodeFactory.createNamedImports( + map(helperNames, (name) => isFileLevelUniqueName(sourceFile, name) ? nodeFactory.createImportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + nodeFactory.createIdentifier(name) + ) : nodeFactory.createImportSpecifier( + /*isTypeOnly*/ + false, + nodeFactory.createIdentifier(name), + helperFactory.getUnscopedHelperName(name) + )) + ); + const parseNode = getOriginalNode(sourceFile, isSourceFile); + const emitNode = getOrCreateEmitNode(parseNode); + emitNode.externalHelpers = true; + const externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( + /*modifiers*/ + void 0, + nodeFactory.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + namedBindings + ), + nodeFactory.createStringLiteral(externalHelpersModuleNameText), + /*attributes*/ + void 0 + ); + addInternalEmitFlags(externalHelpersImportDeclaration, 2 /* NeverApplyImportHelper */); + return externalHelpersImportDeclaration; + } + } + } else { + const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, helpers, hasExportStarsToExportValues, hasImportStar || hasImportDefault); + if (externalHelpersModuleName) { + const externalHelpersImportDeclaration = nodeFactory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + externalHelpersModuleName, + nodeFactory.createExternalModuleReference(nodeFactory.createStringLiteral(externalHelpersModuleNameText)) + ); + addInternalEmitFlags(externalHelpersImportDeclaration, 2 /* NeverApplyImportHelper */); + return externalHelpersImportDeclaration; + } + } + } +} +function getImportedHelpers(sourceFile) { + return filter(getEmitHelpers(sourceFile), (helper) => !helper.scoped); +} +function getOrCreateExternalHelpersModuleNameIfNeeded(factory2, node, compilerOptions, helpers, hasExportStarsToExportValues, hasImportStarOrImportDefault) { + const externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + const create = some(helpers) || (hasExportStarsToExportValues || getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault) && getEmitModuleFormatOfFileWorker(node, compilerOptions) < 4 /* System */; + if (create) { + const parseNode = getOriginalNode(node, isSourceFile); + const emitNode = getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory2.createUniqueName(externalHelpersModuleNameText)); + } +} +function getLocalNameForExternalImport(factory2, node, sourceFile) { + const namespaceDeclaration = getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !isDefaultImport(node) && !isExportNamespaceAsDefaultDeclaration(node)) { + const name = namespaceDeclaration.name; + if (name.kind === 11 /* StringLiteral */) { + return factory2.getGeneratedNameForNode(node); + } + return isGeneratedIdentifier(name) ? name : factory2.createIdentifier(getSourceTextOfNodeFromSourceFile(sourceFile, name) || idText(name)); + } + if (node.kind === 272 /* ImportDeclaration */ && node.importClause) { + return factory2.getGeneratedNameForNode(node); + } + if (node.kind === 278 /* ExportDeclaration */ && node.moduleSpecifier) { + return factory2.getGeneratedNameForNode(node); + } + return void 0; +} +function getExternalModuleNameLiteral(factory2, importNode, sourceFile, host, resolver, compilerOptions) { + const moduleName = getExternalModuleName(importNode); + if (moduleName && isStringLiteral(moduleName)) { + return tryGetModuleNameFromDeclaration(importNode, host, factory2, resolver, compilerOptions) || tryRenameExternalModule(factory2, moduleName, sourceFile) || factory2.cloneNode(moduleName); + } + return void 0; +} +function tryRenameExternalModule(factory2, moduleName, sourceFile) { + const rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text); + return rename ? factory2.createStringLiteral(rename) : void 0; +} +function tryGetModuleNameFromFile(factory2, file, host, options) { + if (!file) { + return void 0; + } + if (file.moduleName) { + return factory2.createStringLiteral(file.moduleName); + } + if (!file.isDeclarationFile && options.outFile) { + return factory2.createStringLiteral(getExternalModuleNameFromPath(host, file.fileName)); + } + return void 0; +} +function tryGetModuleNameFromDeclaration(declaration, host, factory2, resolver, compilerOptions) { + return tryGetModuleNameFromFile(factory2, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); +} +function getInitializerOfBindingOrAssignmentElement(bindingElement) { + if (isDeclarationBindingElement(bindingElement)) { + return bindingElement.initializer; + } + if (isPropertyAssignment(bindingElement)) { + const initializer = bindingElement.initializer; + return isAssignmentExpression( + initializer, + /*excludeCompoundAssignment*/ + true + ) ? initializer.right : void 0; + } + if (isShorthandPropertyAssignment(bindingElement)) { + return bindingElement.objectAssignmentInitializer; + } + if (isAssignmentExpression( + bindingElement, + /*excludeCompoundAssignment*/ + true + )) { + return bindingElement.right; + } + if (isSpreadElement(bindingElement)) { + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + } +} +function getTargetOfBindingOrAssignmentElement(bindingElement) { + if (isDeclarationBindingElement(bindingElement)) { + return bindingElement.name; + } + if (isObjectLiteralElementLike(bindingElement)) { + switch (bindingElement.kind) { + case 303 /* PropertyAssignment */: + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + case 304 /* ShorthandPropertyAssignment */: + return bindingElement.name; + case 305 /* SpreadAssignment */: + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return void 0; + } + if (isAssignmentExpression( + bindingElement, + /*excludeCompoundAssignment*/ + true + )) { + return getTargetOfBindingOrAssignmentElement(bindingElement.left); + } + if (isSpreadElement(bindingElement)) { + return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + } + return bindingElement; +} +function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 169 /* Parameter */: + case 208 /* BindingElement */: + return bindingElement.dotDotDotToken; + case 230 /* SpreadElement */: + case 305 /* SpreadAssignment */: + return bindingElement; + } + return void 0; +} +function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { + const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement); + Debug.assert(!!propertyName || isSpreadAssignment(bindingElement), "Invalid property name for binding element."); + return propertyName; +} +function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { + switch (bindingElement.kind) { + case 208 /* BindingElement */: + if (bindingElement.propertyName) { + const propertyName = bindingElement.propertyName; + if (isPrivateIdentifier(propertyName)) { + return Debug.failBadSyntaxKind(propertyName); + } + return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; + } + break; + case 303 /* PropertyAssignment */: + if (bindingElement.name) { + const propertyName = bindingElement.name; + if (isPrivateIdentifier(propertyName)) { + return Debug.failBadSyntaxKind(propertyName); + } + return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; + } + break; + case 305 /* SpreadAssignment */: + if (bindingElement.name && isPrivateIdentifier(bindingElement.name)) { + return Debug.failBadSyntaxKind(bindingElement.name); + } + return bindingElement.name; + } + const target = getTargetOfBindingOrAssignmentElement(bindingElement); + if (target && isPropertyName(target)) { + return target; + } +} +function isStringOrNumericLiteral(node) { + const kind = node.kind; + return kind === 11 /* StringLiteral */ || kind === 9 /* NumericLiteral */; +} +function getElementsOfBindingOrAssignmentPattern(name) { + switch (name.kind) { + case 206 /* ObjectBindingPattern */: + case 207 /* ArrayBindingPattern */: + case 209 /* ArrayLiteralExpression */: + return name.elements; + case 210 /* ObjectLiteralExpression */: + return name.properties; + } +} +function getJSDocTypeAliasName(fullName) { + if (fullName) { + let rightNode = fullName; + while (true) { + if (isIdentifier(rightNode) || !rightNode.body) { + return isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; + } + } +} +function canHaveIllegalTypeParameters(node) { + const kind = node.kind; + return kind === 176 /* Constructor */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; +} +function canHaveIllegalDecorators(node) { + const kind = node.kind; + return kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 262 /* FunctionDeclaration */ || kind === 176 /* Constructor */ || kind === 181 /* IndexSignature */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 282 /* MissingDeclaration */ || kind === 243 /* VariableStatement */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 277 /* ExportAssignment */; +} +function canHaveIllegalModifiers(node) { + const kind = node.kind; + return kind === 175 /* ClassStaticBlockDeclaration */ || kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 282 /* MissingDeclaration */ || kind === 270 /* NamespaceExportDeclaration */; +} +function isQuestionOrExclamationToken(node) { + return isQuestionToken(node) || isExclamationToken(node); +} +function isIdentifierOrThisTypeNode(node) { + return isIdentifier(node) || isThisTypeNode(node); +} +function isReadonlyKeywordOrPlusOrMinusToken(node) { + return isReadonlyKeyword(node) || isPlusToken(node) || isMinusToken(node); +} +function isQuestionOrPlusOrMinusToken(node) { + return isQuestionToken(node) || isPlusToken(node) || isMinusToken(node); +} +function isModuleName(node) { + return isIdentifier(node) || isStringLiteral(node); +} +function isExponentiationOperator(kind) { + return kind === 43 /* AsteriskAsteriskToken */; +} +function isMultiplicativeOperator(kind) { + return kind === 42 /* AsteriskToken */ || kind === 44 /* SlashToken */ || kind === 45 /* PercentToken */; +} +function isMultiplicativeOperatorOrHigher(kind) { + return isExponentiationOperator(kind) || isMultiplicativeOperator(kind); +} +function isAdditiveOperator(kind) { + return kind === 40 /* PlusToken */ || kind === 41 /* MinusToken */; +} +function isAdditiveOperatorOrHigher(kind) { + return isAdditiveOperator(kind) || isMultiplicativeOperatorOrHigher(kind); +} +function isShiftOperator(kind) { + return kind === 48 /* LessThanLessThanToken */ || kind === 49 /* GreaterThanGreaterThanToken */ || kind === 50 /* GreaterThanGreaterThanGreaterThanToken */; +} +function isShiftOperatorOrHigher(kind) { + return isShiftOperator(kind) || isAdditiveOperatorOrHigher(kind); +} +function isRelationalOperator(kind) { + return kind === 30 /* LessThanToken */ || kind === 33 /* LessThanEqualsToken */ || kind === 32 /* GreaterThanToken */ || kind === 34 /* GreaterThanEqualsToken */ || kind === 104 /* InstanceOfKeyword */ || kind === 103 /* InKeyword */; +} +function isRelationalOperatorOrHigher(kind) { + return isRelationalOperator(kind) || isShiftOperatorOrHigher(kind); +} +function isEqualityOperator(kind) { + return kind === 35 /* EqualsEqualsToken */ || kind === 37 /* EqualsEqualsEqualsToken */ || kind === 36 /* ExclamationEqualsToken */ || kind === 38 /* ExclamationEqualsEqualsToken */; +} +function isEqualityOperatorOrHigher(kind) { + return isEqualityOperator(kind) || isRelationalOperatorOrHigher(kind); +} +function isBitwiseOperator(kind) { + return kind === 51 /* AmpersandToken */ || kind === 52 /* BarToken */ || kind === 53 /* CaretToken */; +} +function isBitwiseOperatorOrHigher(kind) { + return isBitwiseOperator(kind) || isEqualityOperatorOrHigher(kind); +} +function isLogicalOperator2(kind) { + return kind === 56 /* AmpersandAmpersandToken */ || kind === 57 /* BarBarToken */; +} +function isLogicalOperatorOrHigher(kind) { + return isLogicalOperator2(kind) || isBitwiseOperatorOrHigher(kind); +} +function isAssignmentOperatorOrHigher(kind) { + return kind === 61 /* QuestionQuestionToken */ || isLogicalOperatorOrHigher(kind) || isAssignmentOperator(kind); +} +function isBinaryOperator(kind) { + return isAssignmentOperatorOrHigher(kind) || kind === 28 /* CommaToken */; +} +function isBinaryOperatorToken(node) { + return isBinaryOperator(node.kind); +} +var BinaryExpressionState; +((BinaryExpressionState2) => { + function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) { + const prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : void 0; + Debug.assertEqual(stateStack[stackIndex], enter); + userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); + stateStack[stackIndex] = nextState(machine, enter); + return stackIndex; + } + BinaryExpressionState2.enter = enter; + function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + Debug.assertEqual(stateStack[stackIndex], left); + Debug.assertIsDefined(machine.onLeft); + stateStack[stackIndex] = nextState(machine, left); + const nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState2.left = left; + function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + Debug.assertEqual(stateStack[stackIndex], operator); + Debug.assertIsDefined(machine.onOperator); + stateStack[stackIndex] = nextState(machine, operator); + machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]); + return stackIndex; + } + BinaryExpressionState2.operator = operator; + function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + Debug.assertEqual(stateStack[stackIndex], right); + Debug.assertIsDefined(machine.onRight); + stateStack[stackIndex] = nextState(machine, right); + const nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState2.right = right; + function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) { + Debug.assertEqual(stateStack[stackIndex], exit); + stateStack[stackIndex] = nextState(machine, exit); + const result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); + if (stackIndex > 0) { + stackIndex--; + if (machine.foldState) { + const side = stateStack[stackIndex] === exit ? "right" : "left"; + userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side); + } + } else { + resultHolder.value = result; + } + return stackIndex; + } + BinaryExpressionState2.exit = exit; + function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) { + Debug.assertEqual(stateStack[stackIndex], done); + return stackIndex; + } + BinaryExpressionState2.done = done; + function nextState(machine, currentState) { + switch (currentState) { + case enter: + if (machine.onLeft) return left; + // falls through + case left: + if (machine.onOperator) return operator; + // falls through + case operator: + if (machine.onRight) return right; + // falls through + case right: + return exit; + case exit: + return done; + case done: + return done; + default: + Debug.fail("Invalid state"); + } + } + BinaryExpressionState2.nextState = nextState; + function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) { + stackIndex++; + stateStack[stackIndex] = enter; + nodeStack[stackIndex] = node; + userStateStack[stackIndex] = void 0; + return stackIndex; + } + function checkCircularity(stackIndex, nodeStack, node) { + if (Debug.shouldAssert(2 /* Aggressive */)) { + while (stackIndex >= 0) { + Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected."); + stackIndex--; + } + } + } +})(BinaryExpressionState || (BinaryExpressionState = {})); +var BinaryExpressionStateMachine = class { + constructor(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + this.onEnter = onEnter; + this.onLeft = onLeft; + this.onOperator = onOperator; + this.onRight = onRight; + this.onExit = onExit; + this.foldState = foldState; + } +}; +function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + const machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return trampoline; + function trampoline(node, outerState) { + const resultHolder = { value: void 0 }; + const stateStack = [BinaryExpressionState.enter]; + const nodeStack = [node]; + const userStateStack = [void 0]; + let stackIndex = 0; + while (stateStack[stackIndex] !== BinaryExpressionState.done) { + stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState); + } + Debug.assertEqual(stackIndex, 0); + return resultHolder.value; + } +} +function isExportOrDefaultKeywordKind(kind) { + return kind === 95 /* ExportKeyword */ || kind === 90 /* DefaultKeyword */; +} +function isExportOrDefaultModifier(node) { + const kind = node.kind; + return isExportOrDefaultKeywordKind(kind); +} +function elideNodes(factory2, nodes) { + if (nodes === void 0) return void 0; + if (nodes.length === 0) return nodes; + return setTextRange(factory2.createNodeArray([], nodes.hasTrailingComma), nodes); +} +function getNodeForGeneratedName(name) { + var _a; + const autoGenerate = name.emitNode.autoGenerate; + if (autoGenerate.flags & 4 /* Node */) { + const autoGenerateId = autoGenerate.id; + let node = name; + let original = node.original; + while (original) { + node = original; + const autoGenerate2 = (_a = node.emitNode) == null ? void 0 : _a.autoGenerate; + if (isMemberName(node) && (autoGenerate2 === void 0 || !!(autoGenerate2.flags & 4 /* Node */) && autoGenerate2.id !== autoGenerateId)) { + break; + } + original = node.original; + } + return node; + } + return name; +} +function formatGeneratedNamePart(part, generateName) { + return typeof part === "object" ? formatGeneratedName( + /*privateName*/ + false, + part.prefix, + part.node, + part.suffix, + generateName + ) : typeof part === "string" ? part.length > 0 && part.charCodeAt(0) === 35 /* hash */ ? part.slice(1) : part : ""; +} +function formatIdentifier(name, generateName) { + return typeof name === "string" ? name : formatIdentifierWorker(name, Debug.checkDefined(generateName)); +} +function formatIdentifierWorker(node, generateName) { + return isGeneratedPrivateIdentifier(node) ? generateName(node).slice(1) : isGeneratedIdentifier(node) ? generateName(node) : isPrivateIdentifier(node) ? node.escapedText.slice(1) : idText(node); +} +function formatGeneratedName(privateName, prefix, baseName, suffix, generateName) { + prefix = formatGeneratedNamePart(prefix, generateName); + suffix = formatGeneratedNamePart(suffix, generateName); + baseName = formatIdentifier(baseName, generateName); + return `${privateName ? "#" : ""}${prefix}${baseName}${suffix}`; +} +function createAccessorPropertyBackingField(factory2, node, modifiers, initializer) { + return factory2.updatePropertyDeclaration( + node, + modifiers, + factory2.getGeneratedPrivateNameForNode( + node.name, + /*prefix*/ + void 0, + "_accessor_storage" + ), + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + initializer + ); +} +function createAccessorPropertyGetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { + return factory2.createGetAccessorDeclaration( + modifiers, + name, + [], + /*type*/ + void 0, + factory2.createBlock([ + factory2.createReturnStatement( + factory2.createPropertyAccessExpression( + receiver, + factory2.getGeneratedPrivateNameForNode( + node.name, + /*prefix*/ + void 0, + "_accessor_storage" + ) + ) + ) + ]) + ); +} +function createAccessorPropertySetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { + return factory2.createSetAccessorDeclaration( + modifiers, + name, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "value" + )], + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createPropertyAccessExpression( + receiver, + factory2.getGeneratedPrivateNameForNode( + node.name, + /*prefix*/ + void 0, + "_accessor_storage" + ) + ), + factory2.createIdentifier("value") + ) + ) + ]) + ); +} +function findComputedPropertyNameCacheAssignment(name) { + let node = name.expression; + while (true) { + node = skipOuterExpressions(node); + if (isCommaListExpression(node)) { + node = last(node.elements); + continue; + } + if (isCommaExpression(node)) { + node = node.right; + continue; + } + if (isAssignmentExpression( + node, + /*excludeCompoundAssignment*/ + true + ) && isGeneratedIdentifier(node.left)) { + return node; + } + break; + } +} +function isSyntheticParenthesizedExpression(node) { + return isParenthesizedExpression(node) && nodeIsSynthesized(node) && !node.emitNode; +} +function flattenCommaListWorker(node, expressions) { + if (isSyntheticParenthesizedExpression(node)) { + flattenCommaListWorker(node.expression, expressions); + } else if (isCommaExpression(node)) { + flattenCommaListWorker(node.left, expressions); + flattenCommaListWorker(node.right, expressions); + } else if (isCommaListExpression(node)) { + for (const child of node.elements) { + flattenCommaListWorker(child, expressions); + } + } else { + expressions.push(node); + } +} +function flattenCommaList(node) { + const expressions = []; + flattenCommaListWorker(node, expressions); + return expressions; +} +function containsObjectRestOrSpread(node) { + if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) return true; + if (node.transformFlags & 128 /* ContainsES2018 */) { + for (const element of getElementsOfBindingOrAssignmentPattern(node)) { + const target = getTargetOfBindingOrAssignmentElement(element); + if (target && isAssignmentPattern(target)) { + if (target.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { + return true; + } + if (target.transformFlags & 128 /* ContainsES2018 */) { + if (containsObjectRestOrSpread(target)) return true; + } + } + } + } + return false; +} + +// src/compiler/factory/utilitiesPublic.ts +function setTextRange(range, location) { + return location ? setTextRangePosEnd(range, location.pos, location.end) : range; +} +function canHaveModifiers(node) { + const kind = node.kind; + return kind === 168 /* TypeParameter */ || kind === 169 /* Parameter */ || kind === 171 /* PropertySignature */ || kind === 172 /* PropertyDeclaration */ || kind === 173 /* MethodSignature */ || kind === 174 /* MethodDeclaration */ || kind === 176 /* Constructor */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 181 /* IndexSignature */ || kind === 185 /* ConstructorType */ || kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */ || kind === 231 /* ClassExpression */ || kind === 243 /* VariableStatement */ || kind === 262 /* FunctionDeclaration */ || kind === 263 /* ClassDeclaration */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 277 /* ExportAssignment */ || kind === 278 /* ExportDeclaration */; +} +function canHaveDecorators(node) { + const kind = node.kind; + return kind === 169 /* Parameter */ || kind === 172 /* PropertyDeclaration */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 231 /* ClassExpression */ || kind === 263 /* ClassDeclaration */; +} + +// src/compiler/parser.ts +var NodeConstructor; +var TokenConstructor; +var IdentifierConstructor; +var PrivateIdentifierConstructor; +var SourceFileConstructor; +var parseBaseNodeFactory = { + createBaseSourceFileNode: (kind) => new (SourceFileConstructor || (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, -1, -1), + createBaseIdentifierNode: (kind) => new (IdentifierConstructor || (IdentifierConstructor = objectAllocator.getIdentifierConstructor()))(kind, -1, -1), + createBasePrivateIdentifierNode: (kind) => new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1), + createBaseTokenNode: (kind) => new (TokenConstructor || (TokenConstructor = objectAllocator.getTokenConstructor()))(kind, -1, -1), + createBaseNode: (kind) => new (NodeConstructor || (NodeConstructor = objectAllocator.getNodeConstructor()))(kind, -1, -1) +}; +var parseNodeFactory = createNodeFactory(1 /* NoParenthesizerRules */, parseBaseNodeFactory); +function visitNode2(cbNode, node) { + return node && cbNode(node); +} +function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (const node of nodes) { + const result = cbNode(node); + if (result) { + return result; + } + } + } +} +function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && text.charCodeAt(start + 2) === 42 /* asterisk */ && text.charCodeAt(start + 3) !== 47 /* slash */; +} +function isFileProbablyExternalModule(sourceFile) { + return forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || getImportMetaIfNecessary(sourceFile); +} +function isAnExternalModuleIndicatorNode(node) { + return canHaveModifiers(node) && hasModifierOfKind(node, 95 /* ExportKeyword */) || isImportEqualsDeclaration(node) && isExternalModuleReference(node.moduleReference) || isImportDeclaration(node) || isExportAssignment(node) || isExportDeclaration(node) ? node : void 0; +} +function getImportMetaIfNecessary(sourceFile) { + return sourceFile.flags & 8388608 /* PossiblyContainsImportMeta */ ? walkTreeForImportMeta(sourceFile) : void 0; +} +function walkTreeForImportMeta(node) { + return isImportMeta2(node) ? node : forEachChild(node, walkTreeForImportMeta); +} +function hasModifierOfKind(node, kind) { + return some(node.modifiers, (m) => m.kind === kind); +} +function isImportMeta2(node) { + return isMetaProperty(node) && node.keywordToken === 102 /* ImportKeyword */ && node.name.escapedText === "meta"; +} +var forEachChildTable = { + [166 /* QualifiedName */]: function forEachChildInQualifiedName(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.left) || visitNode2(cbNode, node.right); + }, + [168 /* TypeParameter */]: function forEachChildInTypeParameter(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.constraint) || visitNode2(cbNode, node.default) || visitNode2(cbNode, node.expression); + }, + [304 /* ShorthandPropertyAssignment */]: function forEachChildInShorthandPropertyAssignment(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.equalsToken) || visitNode2(cbNode, node.objectAssignmentInitializer); + }, + [305 /* SpreadAssignment */]: function forEachChildInSpreadAssignment(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [169 /* Parameter */]: function forEachChildInParameter(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer); + }, + [172 /* PropertyDeclaration */]: function forEachChildInPropertyDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer); + }, + [171 /* PropertySignature */]: function forEachChildInPropertySignature(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer); + }, + [303 /* PropertyAssignment */]: function forEachChildInPropertyAssignment(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.initializer); + }, + [260 /* VariableDeclaration */]: function forEachChildInVariableDeclaration(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.exclamationToken) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.initializer); + }, + [208 /* BindingElement */]: function forEachChildInBindingElement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.propertyName) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.initializer); + }, + [181 /* IndexSignature */]: function forEachChildInIndexSignature(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); + }, + [185 /* ConstructorType */]: function forEachChildInConstructorType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); + }, + [184 /* FunctionType */]: function forEachChildInFunctionType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); + }, + [179 /* CallSignature */]: forEachChildInCallOrConstructSignature, + [180 /* ConstructSignature */]: forEachChildInCallOrConstructSignature, + [174 /* MethodDeclaration */]: function forEachChildInMethodDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); + }, + [173 /* MethodSignature */]: function forEachChildInMethodSignature(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); + }, + [176 /* Constructor */]: function forEachChildInConstructor(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); + }, + [177 /* GetAccessor */]: function forEachChildInGetAccessor(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); + }, + [178 /* SetAccessor */]: function forEachChildInSetAccessor(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); + }, + [262 /* FunctionDeclaration */]: function forEachChildInFunctionDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); + }, + [218 /* FunctionExpression */]: function forEachChildInFunctionExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.body); + }, + [219 /* ArrowFunction */]: function forEachChildInArrowFunction(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type) || visitNode2(cbNode, node.equalsGreaterThanToken) || visitNode2(cbNode, node.body); + }, + [175 /* ClassStaticBlockDeclaration */]: function forEachChildInClassStaticBlockDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.body); + }, + [183 /* TypeReference */]: function forEachChildInTypeReference(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); + }, + [182 /* TypePredicate */]: function forEachChildInTypePredicate(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.assertsModifier) || visitNode2(cbNode, node.parameterName) || visitNode2(cbNode, node.type); + }, + [186 /* TypeQuery */]: function forEachChildInTypeQuery(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.exprName) || visitNodes(cbNode, cbNodes, node.typeArguments); + }, + [187 /* TypeLiteral */]: function forEachChildInTypeLiteral(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.members); + }, + [188 /* ArrayType */]: function forEachChildInArrayType(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.elementType); + }, + [189 /* TupleType */]: function forEachChildInTupleType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + }, + [192 /* UnionType */]: forEachChildInUnionOrIntersectionType, + [193 /* IntersectionType */]: forEachChildInUnionOrIntersectionType, + [194 /* ConditionalType */]: function forEachChildInConditionalType(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.checkType) || visitNode2(cbNode, node.extendsType) || visitNode2(cbNode, node.trueType) || visitNode2(cbNode, node.falseType); + }, + [195 /* InferType */]: function forEachChildInInferType(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.typeParameter); + }, + [205 /* ImportType */]: function forEachChildInImportType(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.argument) || visitNode2(cbNode, node.attributes) || visitNode2(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); + }, + [302 /* ImportTypeAssertionContainer */]: function forEachChildInImportTypeAssertionContainer(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.assertClause); + }, + [196 /* ParenthesizedType */]: forEachChildInParenthesizedTypeOrTypeOperator, + [198 /* TypeOperator */]: forEachChildInParenthesizedTypeOrTypeOperator, + [199 /* IndexedAccessType */]: function forEachChildInIndexedAccessType(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.objectType) || visitNode2(cbNode, node.indexType); + }, + [200 /* MappedType */]: function forEachChildInMappedType(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.readonlyToken) || visitNode2(cbNode, node.typeParameter) || visitNode2(cbNode, node.nameType) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type) || visitNodes(cbNode, cbNodes, node.members); + }, + [201 /* LiteralType */]: function forEachChildInLiteralType(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.literal); + }, + [202 /* NamedTupleMember */]: function forEachChildInNamedTupleMember(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.type); + }, + [206 /* ObjectBindingPattern */]: forEachChildInObjectOrArrayBindingPattern, + [207 /* ArrayBindingPattern */]: forEachChildInObjectOrArrayBindingPattern, + [209 /* ArrayLiteralExpression */]: function forEachChildInArrayLiteralExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + }, + [210 /* ObjectLiteralExpression */]: function forEachChildInObjectLiteralExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.properties); + }, + [211 /* PropertyAccessExpression */]: function forEachChildInPropertyAccessExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.questionDotToken) || visitNode2(cbNode, node.name); + }, + [212 /* ElementAccessExpression */]: function forEachChildInElementAccessExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.questionDotToken) || visitNode2(cbNode, node.argumentExpression); + }, + [213 /* CallExpression */]: forEachChildInCallOrNewExpression, + [214 /* NewExpression */]: forEachChildInCallOrNewExpression, + [215 /* TaggedTemplateExpression */]: function forEachChildInTaggedTemplateExpression(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tag) || visitNode2(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode2(cbNode, node.template); + }, + [216 /* TypeAssertionExpression */]: function forEachChildInTypeAssertionExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.type) || visitNode2(cbNode, node.expression); + }, + [217 /* ParenthesizedExpression */]: function forEachChildInParenthesizedExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [220 /* DeleteExpression */]: function forEachChildInDeleteExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [221 /* TypeOfExpression */]: function forEachChildInTypeOfExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [222 /* VoidExpression */]: function forEachChildInVoidExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [224 /* PrefixUnaryExpression */]: function forEachChildInPrefixUnaryExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.operand); + }, + [229 /* YieldExpression */]: function forEachChildInYieldExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.asteriskToken) || visitNode2(cbNode, node.expression); + }, + [223 /* AwaitExpression */]: function forEachChildInAwaitExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [225 /* PostfixUnaryExpression */]: function forEachChildInPostfixUnaryExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.operand); + }, + [226 /* BinaryExpression */]: function forEachChildInBinaryExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.left) || visitNode2(cbNode, node.operatorToken) || visitNode2(cbNode, node.right); + }, + [234 /* AsExpression */]: function forEachChildInAsExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.type); + }, + [235 /* NonNullExpression */]: function forEachChildInNonNullExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [238 /* SatisfiesExpression */]: function forEachChildInSatisfiesExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.type); + }, + [236 /* MetaProperty */]: function forEachChildInMetaProperty(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name); + }, + [227 /* ConditionalExpression */]: function forEachChildInConditionalExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.condition) || visitNode2(cbNode, node.questionToken) || visitNode2(cbNode, node.whenTrue) || visitNode2(cbNode, node.colonToken) || visitNode2(cbNode, node.whenFalse); + }, + [230 /* SpreadElement */]: function forEachChildInSpreadElement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [241 /* Block */]: forEachChildInBlock, + [268 /* ModuleBlock */]: forEachChildInBlock, + [307 /* SourceFile */]: function forEachChildInSourceFile(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.statements) || visitNode2(cbNode, node.endOfFileToken); + }, + [243 /* VariableStatement */]: function forEachChildInVariableStatement(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.declarationList); + }, + [261 /* VariableDeclarationList */]: function forEachChildInVariableDeclarationList(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.declarations); + }, + [244 /* ExpressionStatement */]: function forEachChildInExpressionStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [245 /* IfStatement */]: function forEachChildInIfStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.thenStatement) || visitNode2(cbNode, node.elseStatement); + }, + [246 /* DoStatement */]: function forEachChildInDoStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.statement) || visitNode2(cbNode, node.expression); + }, + [247 /* WhileStatement */]: function forEachChildInWhileStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement); + }, + [248 /* ForStatement */]: function forEachChildInForStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.initializer) || visitNode2(cbNode, node.condition) || visitNode2(cbNode, node.incrementor) || visitNode2(cbNode, node.statement); + }, + [249 /* ForInStatement */]: function forEachChildInForInStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.initializer) || visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement); + }, + [250 /* ForOfStatement */]: function forEachChildInForOfStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.awaitModifier) || visitNode2(cbNode, node.initializer) || visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement); + }, + [251 /* ContinueStatement */]: forEachChildInContinueOrBreakStatement, + [252 /* BreakStatement */]: forEachChildInContinueOrBreakStatement, + [253 /* ReturnStatement */]: function forEachChildInReturnStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [254 /* WithStatement */]: function forEachChildInWithStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.statement); + }, + [255 /* SwitchStatement */]: function forEachChildInSwitchStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.caseBlock); + }, + [269 /* CaseBlock */]: function forEachChildInCaseBlock(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.clauses); + }, + [296 /* CaseClause */]: function forEachChildInCaseClause(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); + }, + [297 /* DefaultClause */]: function forEachChildInDefaultClause(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.statements); + }, + [256 /* LabeledStatement */]: function forEachChildInLabeledStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.label) || visitNode2(cbNode, node.statement); + }, + [257 /* ThrowStatement */]: function forEachChildInThrowStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [258 /* TryStatement */]: function forEachChildInTryStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.tryBlock) || visitNode2(cbNode, node.catchClause) || visitNode2(cbNode, node.finallyBlock); + }, + [299 /* CatchClause */]: function forEachChildInCatchClause(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.variableDeclaration) || visitNode2(cbNode, node.block); + }, + [170 /* Decorator */]: function forEachChildInDecorator(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [263 /* ClassDeclaration */]: forEachChildInClassDeclarationOrExpression, + [231 /* ClassExpression */]: forEachChildInClassDeclarationOrExpression, + [264 /* InterfaceDeclaration */]: function forEachChildInInterfaceDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); + }, + [265 /* TypeAliasDeclaration */]: function forEachChildInTypeAliasDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode2(cbNode, node.type); + }, + [266 /* EnumDeclaration */]: function forEachChildInEnumDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); + }, + [306 /* EnumMember */]: function forEachChildInEnumMember(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.initializer); + }, + [267 /* ModuleDeclaration */]: function forEachChildInModuleDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.body); + }, + [271 /* ImportEqualsDeclaration */]: function forEachChildInImportEqualsDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNode2(cbNode, node.moduleReference); + }, + [272 /* ImportDeclaration */]: function forEachChildInImportDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.importClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.attributes); + }, + [273 /* ImportClause */]: function forEachChildInImportClause(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.namedBindings); + }, + [300 /* ImportAttributes */]: function forEachChildInImportAttributes(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + }, + [301 /* ImportAttribute */]: function forEachChildInImportAttribute(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.value); + }, + [270 /* NamespaceExportDeclaration */]: function forEachChildInNamespaceExportDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name); + }, + [274 /* NamespaceImport */]: function forEachChildInNamespaceImport(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name); + }, + [280 /* NamespaceExport */]: function forEachChildInNamespaceExport(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name); + }, + [275 /* NamedImports */]: forEachChildInNamedImportsOrExports, + [279 /* NamedExports */]: forEachChildInNamedImportsOrExports, + [278 /* ExportDeclaration */]: function forEachChildInExportDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.exportClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.attributes); + }, + [276 /* ImportSpecifier */]: forEachChildInImportOrExportSpecifier, + [281 /* ExportSpecifier */]: forEachChildInImportOrExportSpecifier, + [277 /* ExportAssignment */]: function forEachChildInExportAssignment(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.expression); + }, + [228 /* TemplateExpression */]: function forEachChildInTemplateExpression(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + }, + [239 /* TemplateSpan */]: function forEachChildInTemplateSpan(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression) || visitNode2(cbNode, node.literal); + }, + [203 /* TemplateLiteralType */]: function forEachChildInTemplateLiteralType(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + }, + [204 /* TemplateLiteralTypeSpan */]: function forEachChildInTemplateLiteralTypeSpan(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.type) || visitNode2(cbNode, node.literal); + }, + [167 /* ComputedPropertyName */]: function forEachChildInComputedPropertyName(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [298 /* HeritageClause */]: function forEachChildInHeritageClause(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.types); + }, + [233 /* ExpressionWithTypeArguments */]: function forEachChildInExpressionWithTypeArguments(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); + }, + [283 /* ExternalModuleReference */]: function forEachChildInExternalModuleReference(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [282 /* MissingDeclaration */]: function forEachChildInMissingDeclaration(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers); + }, + [356 /* CommaListExpression */]: function forEachChildInCommaListExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); + }, + [284 /* JsxElement */]: function forEachChildInJsxElement(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode2(cbNode, node.closingElement); + }, + [288 /* JsxFragment */]: function forEachChildInJsxFragment(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode2(cbNode, node.closingFragment); + }, + [285 /* JsxSelfClosingElement */]: forEachChildInJsxOpeningOrSelfClosingElement, + [286 /* JsxOpeningElement */]: forEachChildInJsxOpeningOrSelfClosingElement, + [292 /* JsxAttributes */]: function forEachChildInJsxAttributes(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.properties); + }, + [291 /* JsxAttribute */]: function forEachChildInJsxAttribute(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name) || visitNode2(cbNode, node.initializer); + }, + [293 /* JsxSpreadAttribute */]: function forEachChildInJsxSpreadAttribute(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); + }, + [294 /* JsxExpression */]: function forEachChildInJsxExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.dotDotDotToken) || visitNode2(cbNode, node.expression); + }, + [287 /* JsxClosingElement */]: function forEachChildInJsxClosingElement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.tagName); + }, + [295 /* JsxNamespacedName */]: function forEachChildInJsxNamespacedName(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.namespace) || visitNode2(cbNode, node.name); + }, + [190 /* OptionalType */]: forEachChildInOptionalRestOrJSDocParameterModifier, + [191 /* RestType */]: forEachChildInOptionalRestOrJSDocParameterModifier, + [309 /* JSDocTypeExpression */]: forEachChildInOptionalRestOrJSDocParameterModifier, + [315 /* JSDocNonNullableType */]: forEachChildInOptionalRestOrJSDocParameterModifier, + [314 /* JSDocNullableType */]: forEachChildInOptionalRestOrJSDocParameterModifier, + [316 /* JSDocOptionalType */]: forEachChildInOptionalRestOrJSDocParameterModifier, + [318 /* JSDocVariadicType */]: forEachChildInOptionalRestOrJSDocParameterModifier, + [317 /* JSDocFunctionType */]: function forEachChildInJSDocFunctionType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); + }, + [320 /* JSDoc */]: function forEachChildInJSDoc(node, cbNode, cbNodes) { + return (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)) || visitNodes(cbNode, cbNodes, node.tags); + }, + [347 /* JSDocSeeTag */]: function forEachChildInJSDocSeeTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.name) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); + }, + [310 /* JSDocNameReference */]: function forEachChildInJSDocNameReference(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name); + }, + [311 /* JSDocMemberName */]: function forEachChildInJSDocMemberName(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.left) || visitNode2(cbNode, node.right); + }, + [341 /* JSDocParameterTag */]: forEachChildInJSDocParameterOrPropertyTag, + [348 /* JSDocPropertyTag */]: forEachChildInJSDocParameterOrPropertyTag, + [330 /* JSDocAuthorTag */]: function forEachChildInJSDocAuthorTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); + }, + [329 /* JSDocImplementsTag */]: function forEachChildInJSDocImplementsTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.class) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); + }, + [328 /* JSDocAugmentsTag */]: function forEachChildInJSDocAugmentsTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.class) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); + }, + [345 /* JSDocTemplateTag */]: function forEachChildInJSDocTemplateTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); + }, + [346 /* JSDocTypedefTag */]: function forEachChildInJSDocTypedefTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || (node.typeExpression && node.typeExpression.kind === 309 /* JSDocTypeExpression */ ? visitNode2(cbNode, node.typeExpression) || visitNode2(cbNode, node.fullName) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)) : visitNode2(cbNode, node.fullName) || visitNode2(cbNode, node.typeExpression) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment))); + }, + [338 /* JSDocCallbackTag */]: function forEachChildInJSDocCallbackTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.fullName) || visitNode2(cbNode, node.typeExpression) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); + }, + [342 /* JSDocReturnTag */]: forEachChildInJSDocTypeLikeTag, + [344 /* JSDocTypeTag */]: forEachChildInJSDocTypeLikeTag, + [343 /* JSDocThisTag */]: forEachChildInJSDocTypeLikeTag, + [340 /* JSDocEnumTag */]: forEachChildInJSDocTypeLikeTag, + [350 /* JSDocSatisfiesTag */]: forEachChildInJSDocTypeLikeTag, + [349 /* JSDocThrowsTag */]: forEachChildInJSDocTypeLikeTag, + [339 /* JSDocOverloadTag */]: forEachChildInJSDocTypeLikeTag, + [323 /* JSDocSignature */]: function forEachChildInJSDocSignature(node, cbNode, _cbNodes) { + return forEach(node.typeParameters, cbNode) || forEach(node.parameters, cbNode) || visitNode2(cbNode, node.type); + }, + [324 /* JSDocLink */]: forEachChildInJSDocLinkCodeOrPlain, + [325 /* JSDocLinkCode */]: forEachChildInJSDocLinkCodeOrPlain, + [326 /* JSDocLinkPlain */]: forEachChildInJSDocLinkCodeOrPlain, + [322 /* JSDocTypeLiteral */]: function forEachChildInJSDocTypeLiteral(node, cbNode, _cbNodes) { + return forEach(node.jsDocPropertyTags, cbNode); + }, + [327 /* JSDocTag */]: forEachChildInJSDocTag, + [332 /* JSDocClassTag */]: forEachChildInJSDocTag, + [333 /* JSDocPublicTag */]: forEachChildInJSDocTag, + [334 /* JSDocPrivateTag */]: forEachChildInJSDocTag, + [335 /* JSDocProtectedTag */]: forEachChildInJSDocTag, + [336 /* JSDocReadonlyTag */]: forEachChildInJSDocTag, + [331 /* JSDocDeprecatedTag */]: forEachChildInJSDocTag, + [337 /* JSDocOverrideTag */]: forEachChildInJSDocTag, + [351 /* JSDocImportTag */]: forEachChildInJSDocImportTag, + [355 /* PartiallyEmittedExpression */]: forEachChildInPartiallyEmittedExpression +}; +function forEachChildInCallOrConstructSignature(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); +} +function forEachChildInUnionOrIntersectionType(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.types); +} +function forEachChildInParenthesizedTypeOrTypeOperator(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.type); +} +function forEachChildInObjectOrArrayBindingPattern(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); +} +function forEachChildInCallOrNewExpression(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.expression) || // TODO: should we separate these branches out? + visitNode2(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); +} +function forEachChildInBlock(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.statements); +} +function forEachChildInContinueOrBreakStatement(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.label); +} +function forEachChildInClassDeclarationOrExpression(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode2(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); +} +function forEachChildInNamedImportsOrExports(node, cbNode, cbNodes) { + return visitNodes(cbNode, cbNodes, node.elements); +} +function forEachChildInImportOrExportSpecifier(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.propertyName) || visitNode2(cbNode, node.name); +} +function forEachChildInJsxOpeningOrSelfClosingElement(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode2(cbNode, node.attributes); +} +function forEachChildInOptionalRestOrJSDocParameterModifier(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.type); +} +function forEachChildInJSDocParameterOrPropertyTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || (node.isNameFirst ? visitNode2(cbNode, node.name) || visitNode2(cbNode, node.typeExpression) : visitNode2(cbNode, node.typeExpression) || visitNode2(cbNode, node.name)) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); +} +function forEachChildInJSDocTypeLikeTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.typeExpression) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); +} +function forEachChildInJSDocLinkCodeOrPlain(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.name); +} +function forEachChildInJSDocTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); +} +function forEachChildInJSDocImportTag(node, cbNode, cbNodes) { + return visitNode2(cbNode, node.tagName) || visitNode2(cbNode, node.importClause) || visitNode2(cbNode, node.moduleSpecifier) || visitNode2(cbNode, node.attributes) || (typeof node.comment === "string" ? void 0 : visitNodes(cbNode, cbNodes, node.comment)); +} +function forEachChildInPartiallyEmittedExpression(node, cbNode, _cbNodes) { + return visitNode2(cbNode, node.expression); +} +function forEachChild(node, cbNode, cbNodes) { + if (node === void 0 || node.kind <= 165 /* LastToken */) { + return; + } + const fn = forEachChildTable[node.kind]; + return fn === void 0 ? void 0 : fn(node, cbNode, cbNodes); +} +function forEachChildRecursively(rootNode, cbNode, cbNodes) { + const queue = gatherPossibleChildren(rootNode); + const parents = []; + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + const current = queue.pop(); + const parent = parents.pop(); + if (isArray(current)) { + if (cbNodes) { + const res = cbNodes(current, parent); + if (res) { + if (res === "skip") continue; + return res; + } + } + for (let i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } else { + const res = cbNode(current, parent); + if (res) { + if (res === "skip") continue; + return res; + } + if (current.kind >= 166 /* FirstNode */) { + for (const child of gatherPossibleChildren(current)) { + queue.push(child); + parents.push(current); + } + } + } + } +} +function gatherPossibleChildren(node) { + const children = []; + forEachChild(node, addWorkItem, addWorkItem); + return children; + function addWorkItem(n) { + children.unshift(n); + } +} +function setExternalModuleIndicator(sourceFile) { + sourceFile.externalModuleIndicator = isFileProbablyExternalModule(sourceFile); +} +function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes = false, scriptKind) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push( + tracing.Phase.Parse, + "createSourceFile", + { path: fileName }, + /*separateBeginAndEnd*/ + true + ); + mark("beforeParse"); + let result; + const { + languageVersion, + setExternalModuleIndicator: overrideSetExternalModuleIndicator, + impliedNodeFormat: format, + jsDocParsingMode + } = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : { languageVersion: languageVersionOrOptions }; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseSourceFile( + fileName, + sourceText, + languageVersion, + /*syntaxCursor*/ + void 0, + setParentNodes, + 6 /* JSON */, + noop, + jsDocParsingMode + ); + } else { + const setIndicator = format === void 0 ? overrideSetExternalModuleIndicator : (file) => { + file.impliedNodeFormat = format; + return (overrideSetExternalModuleIndicator || setExternalModuleIndicator)(file); + }; + result = Parser.parseSourceFile( + fileName, + sourceText, + languageVersion, + /*syntaxCursor*/ + void 0, + setParentNodes, + scriptKind, + setIndicator, + jsDocParsingMode + ); + } + mark("afterParse"); + measure("Parse", "beforeParse", "afterParse"); + (_b = tracing) == null ? void 0 : _b.pop(); + return result; +} +function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); +} +function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); +} +function isExternalModule(file) { + return file.externalModuleIndicator !== void 0; +} +var Parser; +((Parser2) => { + var scanner = createScanner( + 99 /* Latest */, + /*skipTrivia*/ + true + ); + var disallowInAndDecoratorContext = 8192 /* DisallowInContext */ | 32768 /* DecoratorContext */; + var NodeConstructor2; + var TokenConstructor2; + var IdentifierConstructor2; + var PrivateIdentifierConstructor2; + var SourceFileConstructor2; + function countNode(node) { + nodeCount++; + return node; + } + var baseNodeFactory = { + createBaseSourceFileNode: (kind) => countNode(new SourceFileConstructor2( + kind, + /*pos*/ + 0, + /*end*/ + 0 + )), + createBaseIdentifierNode: (kind) => countNode(new IdentifierConstructor2( + kind, + /*pos*/ + 0, + /*end*/ + 0 + )), + createBasePrivateIdentifierNode: (kind) => countNode(new PrivateIdentifierConstructor2( + kind, + /*pos*/ + 0, + /*end*/ + 0 + )), + createBaseTokenNode: (kind) => countNode(new TokenConstructor2( + kind, + /*pos*/ + 0, + /*end*/ + 0 + )), + createBaseNode: (kind) => countNode(new NodeConstructor2( + kind, + /*pos*/ + 0, + /*end*/ + 0 + )) + }; + var factory2 = createNodeFactory(1 /* NoParenthesizerRules */ | 2 /* NoNodeConverters */ | 8 /* NoOriginalNode */, baseNodeFactory); + var { + createNodeArray: factoryCreateNodeArray, + createNumericLiteral: factoryCreateNumericLiteral, + createStringLiteral: factoryCreateStringLiteral, + createLiteralLikeNode: factoryCreateLiteralLikeNode, + createIdentifier: factoryCreateIdentifier, + createPrivateIdentifier: factoryCreatePrivateIdentifier, + createToken: factoryCreateToken, + createArrayLiteralExpression: factoryCreateArrayLiteralExpression, + createObjectLiteralExpression: factoryCreateObjectLiteralExpression, + createPropertyAccessExpression: factoryCreatePropertyAccessExpression, + createPropertyAccessChain: factoryCreatePropertyAccessChain, + createElementAccessExpression: factoryCreateElementAccessExpression, + createElementAccessChain: factoryCreateElementAccessChain, + createCallExpression: factoryCreateCallExpression, + createCallChain: factoryCreateCallChain, + createNewExpression: factoryCreateNewExpression, + createParenthesizedExpression: factoryCreateParenthesizedExpression, + createBlock: factoryCreateBlock, + createVariableStatement: factoryCreateVariableStatement, + createExpressionStatement: factoryCreateExpressionStatement, + createIfStatement: factoryCreateIfStatement, + createWhileStatement: factoryCreateWhileStatement, + createForStatement: factoryCreateForStatement, + createForOfStatement: factoryCreateForOfStatement, + createVariableDeclaration: factoryCreateVariableDeclaration, + createVariableDeclarationList: factoryCreateVariableDeclarationList + } = factory2; + var fileName; + var sourceFlags; + var sourceText; + var languageVersion; + var scriptKind; + var languageVariant; + var parseDiagnostics; + var jsDocDiagnostics; + var syntaxCursor; + var currentToken; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + var notParenthesizedArrow; + var contextFlags; + var topLevel = true; + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName2, sourceText2, languageVersion2, syntaxCursor2, setParentNodes = false, scriptKind2, setExternalModuleIndicatorOverride, jsDocParsingMode = 0 /* ParseAll */) { + var _a; + scriptKind2 = ensureScriptKind(fileName2, scriptKind2); + if (scriptKind2 === 6 /* JSON */) { + const result2 = parseJsonText2(fileName2, sourceText2, languageVersion2, syntaxCursor2, setParentNodes); + convertToJson( + result2, + (_a = result2.statements[0]) == null ? void 0 : _a.expression, + result2.parseDiagnostics, + /*returnValue*/ + false, + /*jsonConversionNotifier*/ + void 0 + ); + result2.referencedFiles = emptyArray; + result2.typeReferenceDirectives = emptyArray; + result2.libReferenceDirectives = emptyArray; + result2.amdDependencies = emptyArray; + result2.hasNoDefaultLib = false; + result2.pragmas = emptyMap; + return result2; + } + initializeState(fileName2, sourceText2, languageVersion2, syntaxCursor2, scriptKind2, jsDocParsingMode); + const result = parseSourceFileWorker(languageVersion2, setParentNodes, scriptKind2, setExternalModuleIndicatorOverride || setExternalModuleIndicator, jsDocParsingMode); + clearState(); + return result; + } + Parser2.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName2(content, languageVersion2) { + initializeState( + "", + content, + languageVersion2, + /*syntaxCursor*/ + void 0, + 1 /* JS */, + 0 /* ParseAll */ + ); + nextToken(); + const entityName = parseEntityName( + /*allowReservedWords*/ + true + ); + const isValid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isValid ? entityName : void 0; + } + Parser2.parseIsolatedEntityName = parseIsolatedEntityName2; + function parseJsonText2(fileName2, sourceText2, languageVersion2 = 2 /* ES2015 */, syntaxCursor2, setParentNodes = false) { + initializeState(fileName2, sourceText2, languageVersion2, syntaxCursor2, 6 /* JSON */, 0 /* ParseAll */); + sourceFlags = contextFlags; + nextToken(); + const pos = getNodePos(); + let statements, endOfFileToken; + if (token() === 1 /* EndOfFileToken */) { + statements = createNodeArray([], pos, pos); + endOfFileToken = parseTokenNode(); + } else { + let expressions; + while (token() !== 1 /* EndOfFileToken */) { + let expression2; + switch (token()) { + case 23 /* OpenBracketToken */: + expression2 = parseArrayLiteralExpression(); + break; + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 106 /* NullKeyword */: + expression2 = parseTokenNode(); + break; + case 41 /* MinusToken */: + if (lookAhead(() => nextToken() === 9 /* NumericLiteral */ && nextToken() !== 59 /* ColonToken */)) { + expression2 = parsePrefixUnaryExpression(); + } else { + expression2 = parseObjectLiteralExpression(); + } + break; + case 9 /* NumericLiteral */: + case 11 /* StringLiteral */: + if (lookAhead(() => nextToken() !== 59 /* ColonToken */)) { + expression2 = parseLiteralNode(); + break; + } + // falls through + default: + expression2 = parseObjectLiteralExpression(); + break; + } + if (expressions && isArray(expressions)) { + expressions.push(expression2); + } else if (expressions) { + expressions = [expressions, expression2]; + } else { + expressions = expression2; + if (token() !== 1 /* EndOfFileToken */) { + parseErrorAtCurrentToken(Diagnostics.Unexpected_token); + } + } + } + const expression = isArray(expressions) ? finishNode(factoryCreateArrayLiteralExpression(expressions), pos) : Debug.checkDefined(expressions); + const statement = factoryCreateExpressionStatement(expression); + finishNode(statement, pos); + statements = createNodeArray([statement], pos); + endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, Diagnostics.Unexpected_token); + } + const sourceFile = createSourceFile2( + fileName2, + 2 /* ES2015 */, + 6 /* JSON */, + /*isDeclarationFile*/ + false, + statements, + endOfFileToken, + sourceFlags, + noop + ); + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); + if (jsDocDiagnostics) { + sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile); + } + const result = sourceFile; + clearState(); + return result; + } + Parser2.parseJsonText = parseJsonText2; + function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind, _jsDocParsingMode) { + NodeConstructor2 = objectAllocator.getNodeConstructor(); + TokenConstructor2 = objectAllocator.getTokenConstructor(); + IdentifierConstructor2 = objectAllocator.getIdentifierConstructor(); + PrivateIdentifierConstructor2 = objectAllocator.getPrivateIdentifierConstructor(); + SourceFileConstructor2 = objectAllocator.getSourceFileConstructor(); + fileName = normalizePath(_fileName); + sourceText = _sourceText; + languageVersion = _languageVersion; + syntaxCursor = _syntaxCursor; + scriptKind = _scriptKind; + languageVariant = getLanguageVariant(_scriptKind); + parseDiagnostics = []; + parsingContext = 0; + identifiers = /* @__PURE__ */ new Map(); + identifierCount = 0; + nodeCount = 0; + sourceFlags = 0; + topLevel = true; + switch (scriptKind) { + case 1 /* JS */: + case 2 /* JSX */: + contextFlags = 524288 /* JavaScriptFile */; + break; + case 6 /* JSON */: + contextFlags = 524288 /* JavaScriptFile */ | 134217728 /* JsonFile */; + break; + default: + contextFlags = 0 /* None */; + break; + } + parseErrorBeforeNextFinishedNode = false; + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(languageVariant); + scanner.setScriptKind(scriptKind); + scanner.setJSDocParsingMode(_jsDocParsingMode); + } + function clearState() { + scanner.clearCommentDirectives(); + scanner.setText(""); + scanner.setOnError(void 0); + scanner.setScriptKind(0 /* Unknown */); + scanner.setJSDocParsingMode(0 /* ParseAll */); + sourceText = void 0; + languageVersion = void 0; + syntaxCursor = void 0; + scriptKind = void 0; + languageVariant = void 0; + sourceFlags = 0; + parseDiagnostics = void 0; + jsDocDiagnostics = void 0; + parsingContext = 0; + identifiers = void 0; + notParenthesizedArrow = void 0; + topLevel = true; + } + function parseSourceFileWorker(languageVersion2, setParentNodes, scriptKind2, setExternalModuleIndicator2, jsDocParsingMode) { + const isDeclarationFile = isDeclarationFileName(fileName); + if (isDeclarationFile) { + contextFlags |= 33554432 /* Ambient */; + } + sourceFlags = contextFlags; + nextToken(); + const statements = parseList(0 /* SourceElements */, parseStatement); + Debug.assert(token() === 1 /* EndOfFileToken */); + const endHasJSDoc = hasPrecedingJSDocComment(); + const endOfFileToken = withJSDoc(parseTokenNode(), endHasJSDoc); + const sourceFile = createSourceFile2(fileName, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator2); + processCommentPragmas(sourceFile, sourceText); + processPragmasIntoFields(sourceFile, reportPragmaDiagnostic); + sourceFile.commentDirectives = scanner.getCommentDirectives(); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); + sourceFile.jsDocParsingMode = jsDocParsingMode; + if (jsDocDiagnostics) { + sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile); + } + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + function reportPragmaDiagnostic(pos, end, diagnostic) { + parseDiagnostics.push(createDetachedDiagnostic(fileName, sourceText, pos, end, diagnostic)); + } + } + let hasDeprecatedTag = false; + function withJSDoc(node, hasJSDoc) { + if (!hasJSDoc) { + return node; + } + Debug.assert(!node.jsDoc); + const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); + if (jsDoc.length) node.jsDoc = jsDoc; + if (hasDeprecatedTag) { + hasDeprecatedTag = false; + node.flags |= 536870912 /* Deprecated */; + } + return node; + } + function reparseTopLevelAwait(sourceFile) { + const savedSyntaxCursor = syntaxCursor; + const baseSyntaxCursor = IncrementalParser.createSyntaxCursor(sourceFile); + syntaxCursor = { currentNode: currentNode2 }; + const statements = []; + const savedParseDiagnostics = parseDiagnostics; + parseDiagnostics = []; + let pos = 0; + let start = findNextStatementWithAwait(sourceFile.statements, 0); + while (start !== -1) { + const prevStatement = sourceFile.statements[pos]; + const nextStatement = sourceFile.statements[start]; + addRange(statements, sourceFile.statements, pos, start); + pos = findNextStatementWithoutAwait(sourceFile.statements, start); + const diagnosticStart = findIndex(savedParseDiagnostics, (diagnostic) => diagnostic.start >= prevStatement.pos); + const diagnosticEnd = diagnosticStart >= 0 ? findIndex(savedParseDiagnostics, (diagnostic) => diagnostic.start >= nextStatement.pos, diagnosticStart) : -1; + if (diagnosticStart >= 0) { + addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : void 0); + } + speculationHelper(() => { + const savedContextFlags = contextFlags; + contextFlags |= 65536 /* AwaitContext */; + scanner.resetTokenState(nextStatement.pos); + nextToken(); + while (token() !== 1 /* EndOfFileToken */) { + const startPos = scanner.getTokenFullStart(); + const statement = parseListElement(0 /* SourceElements */, parseStatement); + statements.push(statement); + if (startPos === scanner.getTokenFullStart()) { + nextToken(); + } + if (pos >= 0) { + const nonAwaitStatement = sourceFile.statements[pos]; + if (statement.end === nonAwaitStatement.pos) { + break; + } + if (statement.end > nonAwaitStatement.pos) { + pos = findNextStatementWithoutAwait(sourceFile.statements, pos + 1); + } + } + } + contextFlags = savedContextFlags; + }, 2 /* Reparse */); + start = pos >= 0 ? findNextStatementWithAwait(sourceFile.statements, pos) : -1; + } + if (pos >= 0) { + const prevStatement = sourceFile.statements[pos]; + addRange(statements, sourceFile.statements, pos); + const diagnosticStart = findIndex(savedParseDiagnostics, (diagnostic) => diagnostic.start >= prevStatement.pos); + if (diagnosticStart >= 0) { + addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart); + } + } + syntaxCursor = savedSyntaxCursor; + return factory2.updateSourceFile(sourceFile, setTextRange(factoryCreateNodeArray(statements), sourceFile.statements)); + function containsPossibleTopLevelAwait(node) { + return !(node.flags & 65536 /* AwaitContext */) && !!(node.transformFlags & 67108864 /* ContainsPossibleTopLevelAwait */); + } + function findNextStatementWithAwait(statements2, start2) { + for (let i = start2; i < statements2.length; i++) { + if (containsPossibleTopLevelAwait(statements2[i])) { + return i; + } + } + return -1; + } + function findNextStatementWithoutAwait(statements2, start2) { + for (let i = start2; i < statements2.length; i++) { + if (!containsPossibleTopLevelAwait(statements2[i])) { + return i; + } + } + return -1; + } + function currentNode2(position) { + const node = baseSyntaxCursor.currentNode(position); + if (topLevel && node && containsPossibleTopLevelAwait(node)) { + markAsIntersectingIncrementalChange(node); + } + return node; + } + } + function fixupParentReferences(rootNode) { + setParentRecursive( + rootNode, + /*incremental*/ + true + ); + } + Parser2.fixupParentReferences = fixupParentReferences; + function createSourceFile2(fileName2, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, flags, setExternalModuleIndicator2) { + let sourceFile = factory2.createSourceFile(statements, endOfFileToken, flags); + setTextRangePosWidth(sourceFile, 0, sourceText.length); + setFields(sourceFile); + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* ContainsPossibleTopLevelAwait */) { + const oldSourceFile = sourceFile; + sourceFile = reparseTopLevelAwait(sourceFile); + if (oldSourceFile !== sourceFile) setFields(sourceFile); + } + return sourceFile; + function setFields(sourceFile2) { + sourceFile2.text = sourceText; + sourceFile2.bindDiagnostics = []; + sourceFile2.bindSuggestionDiagnostics = void 0; + sourceFile2.languageVersion = languageVersion2; + sourceFile2.fileName = fileName2; + sourceFile2.languageVariant = getLanguageVariant(scriptKind2); + sourceFile2.isDeclarationFile = isDeclarationFile; + sourceFile2.scriptKind = scriptKind2; + setExternalModuleIndicator2(sourceFile2); + sourceFile2.setExternalModuleIndicator = setExternalModuleIndicator2; + } + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 8192 /* DisallowInContext */); + } + function setYieldContext(val) { + setContextFlag(val, 16384 /* YieldContext */); + } + function setDecoratorContext(val) { + setContextFlag(val, 32768 /* DecoratorContext */); + } + function setAwaitContext(val) { + setContextFlag(val, 65536 /* AwaitContext */); + } + function doOutsideOfContext(context, func) { + const contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + setContextFlag( + /*val*/ + false, + contextFlagsToClear + ); + const result = func(); + setContextFlag( + /*val*/ + true, + contextFlagsToClear + ); + return result; + } + return func(); + } + function doInsideOfContext(context, func) { + const contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + setContextFlag( + /*val*/ + true, + contextFlagsToSet + ); + const result = func(); + setContextFlag( + /*val*/ + false, + contextFlagsToSet + ); + return result; + } + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(8192 /* DisallowInContext */, func); + } + function disallowInAnd(func) { + return doInsideOfContext(8192 /* DisallowInContext */, func); + } + function allowConditionalTypesAnd(func) { + return doOutsideOfContext(131072 /* DisallowConditionalTypesContext */, func); + } + function disallowConditionalTypesAnd(func) { + return doInsideOfContext(131072 /* DisallowConditionalTypesContext */, func); + } + function doInYieldContext(func) { + return doInsideOfContext(16384 /* YieldContext */, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(32768 /* DecoratorContext */, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(65536 /* AwaitContext */, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(65536 /* AwaitContext */, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(16384 /* YieldContext */ | 65536 /* AwaitContext */, func); + } + function doOutsideOfYieldAndAwaitContext(func) { + return doOutsideOfContext(16384 /* YieldContext */ | 65536 /* AwaitContext */, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(16384 /* YieldContext */); + } + function inDisallowInContext() { + return inContext(8192 /* DisallowInContext */); + } + function inDisallowConditionalTypesContext() { + return inContext(131072 /* DisallowConditionalTypesContext */); + } + function inDecoratorContext() { + return inContext(32768 /* DecoratorContext */); + } + function inAwaitContext() { + return inContext(65536 /* AwaitContext */); + } + function parseErrorAtCurrentToken(message, ...args) { + return parseErrorAt(scanner.getTokenStart(), scanner.getTokenEnd(), message, ...args); + } + function parseErrorAtPosition(start, length2, message, ...args) { + const lastError = lastOrUndefined(parseDiagnostics); + let result; + if (!lastError || start !== lastError.start) { + result = createDetachedDiagnostic(fileName, sourceText, start, length2, message, ...args); + parseDiagnostics.push(result); + } + parseErrorBeforeNextFinishedNode = true; + return result; + } + function parseErrorAt(start, end, message, ...args) { + return parseErrorAtPosition(start, end - start, message, ...args); + } + function parseErrorAtRange(range, message, ...args) { + parseErrorAt(range.pos, range.end, message, ...args); + } + function scanError(message, length2, arg0) { + parseErrorAtPosition(scanner.getTokenEnd(), length2, message, arg0); + } + function getNodePos() { + return scanner.getTokenFullStart(); + } + function hasPrecedingJSDocComment() { + return scanner.hasPrecedingJSDocComment(); + } + function token() { + return currentToken; + } + function nextTokenWithoutCheck() { + return currentToken = scanner.scan(); + } + function nextTokenAnd(func) { + nextToken(); + return func(); + } + function nextToken() { + if (isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) { + parseErrorAt(scanner.getTokenStart(), scanner.getTokenEnd(), Diagnostics.Keywords_cannot_contain_escape_characters); + } + return nextTokenWithoutCheck(); + } + function nextTokenJSDoc() { + return currentToken = scanner.scanJsDocToken(); + } + function nextJSDocCommentTextToken(inBackticks) { + return currentToken = scanner.scanJSDocCommentTextToken(inBackticks); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken(isTaggedTemplate) { + return currentToken = scanner.reScanTemplateToken(isTaggedTemplate); + } + function reScanLessThanToken() { + return currentToken = scanner.reScanLessThanToken(); + } + function reScanHashToken() { + return currentToken = scanner.reScanHashToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, speculationKind) { + const saveToken = currentToken; + const saveParseDiagnosticsLength = parseDiagnostics.length; + const saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + const saveContextFlags = contextFlags; + const result = speculationKind !== 0 /* TryParse */ ? scanner.lookAhead(callback) : scanner.tryScan(callback); + Debug.assert(saveContextFlags === contextFlags); + if (!result || speculationKind !== 0 /* TryParse */) { + currentToken = saveToken; + if (speculationKind !== 2 /* Reparse */) { + parseDiagnostics.length = saveParseDiagnosticsLength; + } + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, 1 /* Lookahead */); + } + function tryParse(callback) { + return speculationHelper(callback, 0 /* TryParse */); + } + function isBindingIdentifier() { + if (token() === 80 /* Identifier */) { + return true; + } + return token() > 118 /* LastReservedWord */; + } + function isIdentifier2() { + if (token() === 80 /* Identifier */) { + return true; + } + if (token() === 127 /* YieldKeyword */ && inYieldContext()) { + return false; + } + if (token() === 135 /* AwaitKeyword */ && inAwaitContext()) { + return false; + } + return token() > 118 /* LastReservedWord */; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance = true) { + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } else { + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(kind)); + } + return false; + } + const viableKeywordSuggestions = Object.keys(textToKeywordObj).filter((keyword) => keyword.length > 2); + function parseErrorForMissingSemicolonAfter(node) { + if (isTaggedTemplateExpression(node)) { + parseErrorAt(skipTrivia(sourceText, node.template.pos), node.template.end, Diagnostics.Module_declaration_names_may_only_use_or_quoted_strings); + return; + } + const expressionText = isIdentifier(node) ? idText(node) : void 0; + if (!expressionText || !isIdentifierText(expressionText, languageVersion)) { + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(27 /* SemicolonToken */)); + return; + } + const pos = skipTrivia(sourceText, node.pos); + switch (expressionText) { + case "const": + case "let": + case "var": + parseErrorAt(pos, node.end, Diagnostics.Variable_declaration_not_allowed_at_this_location); + return; + case "declare": + return; + case "interface": + parseErrorForInvalidName(Diagnostics.Interface_name_cannot_be_0, Diagnostics.Interface_must_be_given_a_name, 19 /* OpenBraceToken */); + return; + case "is": + parseErrorAt(pos, scanner.getTokenStart(), Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + case "module": + case "namespace": + parseErrorForInvalidName(Diagnostics.Namespace_name_cannot_be_0, Diagnostics.Namespace_must_be_given_a_name, 19 /* OpenBraceToken */); + return; + case "type": + parseErrorForInvalidName(Diagnostics.Type_alias_name_cannot_be_0, Diagnostics.Type_alias_must_be_given_a_name, 64 /* EqualsToken */); + return; + } + const suggestion = getSpellingSuggestion(expressionText, viableKeywordSuggestions, identity) ?? getSpaceSuggestion(expressionText); + if (suggestion) { + parseErrorAt(pos, node.end, Diagnostics.Unknown_keyword_or_identifier_Did_you_mean_0, suggestion); + return; + } + if (token() === 0 /* Unknown */) { + return; + } + parseErrorAt(pos, node.end, Diagnostics.Unexpected_keyword_or_identifier); + } + function parseErrorForInvalidName(nameDiagnostic, blankDiagnostic, tokenIfBlankName) { + if (token() === tokenIfBlankName) { + parseErrorAtCurrentToken(blankDiagnostic); + } else { + parseErrorAtCurrentToken(nameDiagnostic, scanner.getTokenValue()); + } + } + function getSpaceSuggestion(expressionText) { + for (const keyword of viableKeywordSuggestions) { + if (expressionText.length > keyword.length + 2 && startsWith(expressionText, keyword)) { + return `${keyword} ${expressionText.slice(keyword.length)}`; + } + } + return void 0; + } + function parseSemicolonAfterPropertyName(name, type, initializer) { + if (token() === 60 /* AtToken */ && !scanner.hasPrecedingLineBreak()) { + parseErrorAtCurrentToken(Diagnostics.Decorators_must_precede_the_name_and_all_keywords_of_property_declarations); + return; + } + if (token() === 21 /* OpenParenToken */) { + parseErrorAtCurrentToken(Diagnostics.Cannot_start_a_function_call_in_a_type_annotation); + nextToken(); + return; + } + if (type && !canParseSemicolon()) { + if (initializer) { + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(27 /* SemicolonToken */)); + } else { + parseErrorAtCurrentToken(Diagnostics.Expected_for_property_initializer); + } + return; + } + if (tryParseSemicolon()) { + return; + } + if (initializer) { + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(27 /* SemicolonToken */)); + return; + } + parseErrorForMissingSemicolonAfter(name); + } + function parseExpectedJSDoc(kind) { + if (token() === kind) { + nextTokenJSDoc(); + return true; + } + Debug.assert(isKeywordOrPunctuation(kind)); + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(kind)); + return false; + } + function parseExpectedMatchingBrackets(openKind, closeKind, openParsed, openPosition) { + if (token() === closeKind) { + nextToken(); + return; + } + const lastError = parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(closeKind)); + if (!openParsed) { + return; + } + if (lastError) { + addRelatedInfo( + lastError, + createDetachedDiagnostic(fileName, sourceText, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)) + ); + } + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return void 0; + } + function parseOptionalTokenJSDoc(t) { + if (token() === t) { + return parseTokenNodeJSDoc(); + } + return void 0; + } + function parseExpectedToken(t, diagnosticMessage, arg0) { + return parseOptionalToken(t) || createMissingNode( + t, + /*reportAtCurrentPosition*/ + false, + diagnosticMessage || Diagnostics._0_expected, + arg0 || tokenToString(t) + ); + } + function parseExpectedTokenJSDoc(t) { + const optional = parseOptionalTokenJSDoc(t); + if (optional) return optional; + Debug.assert(isKeywordOrPunctuation(t)); + return createMissingNode( + t, + /*reportAtCurrentPosition*/ + false, + Diagnostics._0_expected, + tokenToString(t) + ); + } + function parseTokenNode() { + const pos = getNodePos(); + const kind = token(); + nextToken(); + return finishNode(factoryCreateToken(kind), pos); + } + function parseTokenNodeJSDoc() { + const pos = getNodePos(); + const kind = token(); + nextTokenJSDoc(); + return finishNode(factoryCreateToken(kind), pos); + } + function canParseSemicolon() { + if (token() === 27 /* SemicolonToken */) { + return true; + } + return token() === 20 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function tryParseSemicolon() { + if (!canParseSemicolon()) { + return false; + } + if (token() === 27 /* SemicolonToken */) { + nextToken(); + } + return true; + } + function parseSemicolon() { + return tryParseSemicolon() || parseExpected(27 /* SemicolonToken */); + } + function createNodeArray(elements, pos, end, hasTrailingComma) { + const array = factoryCreateNodeArray(elements, hasTrailingComma); + setTextRangePosEnd(array, pos, end ?? scanner.getTokenFullStart()); + return array; + } + function finishNode(node, pos, end) { + setTextRangePosEnd(node, pos, end ?? scanner.getTokenFullStart()); + if (contextFlags) { + node.flags |= contextFlags; + } + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 262144 /* ThisNodeHasError */; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, ...args) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getTokenFullStart(), 0, diagnosticMessage, ...args); + } else if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage, ...args); + } + const pos = getNodePos(); + const result = kind === 80 /* Identifier */ ? factoryCreateIdentifier( + "", + /*originalKeywordKind*/ + void 0 + ) : isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode( + kind, + "", + "", + /*templateFlags*/ + void 0 + ) : kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral( + "", + /*numericLiteralFlags*/ + void 0 + ) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral( + "", + /*isSingleQuote*/ + void 0 + ) : kind === 282 /* MissingDeclaration */ ? factory2.createMissingDeclaration() : factoryCreateToken(kind); + return finishNode(result, pos); + } + function internIdentifier(text) { + let identifier = identifiers.get(text); + if (identifier === void 0) { + identifiers.set(text, identifier = text); + } + return identifier; + } + function createIdentifier(isIdentifier3, diagnosticMessage, privateIdentifierDiagnosticMessage) { + if (isIdentifier3) { + identifierCount++; + const pos = scanner.hasPrecedingJSDocLeadingAsterisks() ? scanner.getTokenStart() : getNodePos(); + const originalKeywordKind = token(); + const text = internIdentifier(scanner.getTokenValue()); + const hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); + nextTokenWithoutCheck(); + return finishNode(factoryCreateIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape), pos); + } + if (token() === 81 /* PrivateIdentifier */) { + parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + return createIdentifier( + /*isIdentifier*/ + true + ); + } + if (token() === 0 /* Unknown */ && scanner.tryScan(() => scanner.reScanInvalidIdentifier() === 80 /* Identifier */)) { + return createIdentifier( + /*isIdentifier*/ + true + ); + } + identifierCount++; + const reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; + const isReservedWord = scanner.isReservedWord(); + const msgArg = scanner.getTokenText(); + const defaultMessage = isReservedWord ? Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : Diagnostics.Identifier_expected; + return createMissingNode(80 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); + } + function parseBindingIdentifier(privateIdentifierDiagnosticMessage) { + return createIdentifier( + isBindingIdentifier(), + /*diagnosticMessage*/ + void 0, + privateIdentifierDiagnosticMessage + ); + } + function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) { + return createIdentifier(isIdentifier2(), diagnosticMessage, privateIdentifierDiagnosticMessage); + } + function parseIdentifierName(diagnosticMessage) { + return createIdentifier(tokenIsIdentifierOrKeyword(token()), diagnosticMessage); + } + function parseIdentifierNameErrorOnUnicodeEscapeSequence() { + if (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape()) { + parseErrorAtCurrentToken(Diagnostics.Unicode_escape_sequence_cannot_appear_here); + } + return createIdentifier(tokenIsIdentifierOrKeyword(token())); + } + function isLiteralPropertyName() { + return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */; + } + function isImportAttributeName2() { + return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */) { + const node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 23 /* OpenBracketToken */) { + return parseComputedPropertyName(); + } + if (token() === 81 /* PrivateIdentifier */) { + return parsePrivateIdentifier(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker( + /*allowComputedPropertyNames*/ + true + ); + } + function parseComputedPropertyName() { + const pos = getNodePos(); + parseExpected(23 /* OpenBracketToken */); + const expression = allowInAnd(parseExpression); + parseExpected(24 /* CloseBracketToken */); + return finishNode(factory2.createComputedPropertyName(expression), pos); + } + function parsePrivateIdentifier() { + const pos = getNodePos(); + const node = factoryCreatePrivateIdentifier(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node, pos); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + switch (token()) { + case 87 /* ConstKeyword */: + return nextToken() === 94 /* EnumKeyword */; + case 95 /* ExportKeyword */: + nextToken(); + if (token() === 90 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + if (token() === 156 /* TypeKeyword */) { + return lookAhead(nextTokenCanFollowExportModifier); + } + return canFollowExportModifier(); + case 90 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 126 /* StaticKeyword */: + nextToken(); + return canFollowModifier(); + case 139 /* GetKeyword */: + case 153 /* SetKeyword */: + nextToken(); + return canFollowGetOrSetKeyword(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + } + function canFollowExportModifier() { + return token() === 60 /* AtToken */ || token() !== 42 /* AsteriskToken */ && token() !== 130 /* AsKeyword */ && token() !== 19 /* OpenBraceToken */ && canFollowModifier(); + } + function nextTokenCanFollowExportModifier() { + nextToken(); + return canFollowExportModifier(); + } + function parseAnyContextualModifier() { + return isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */ || token() === 42 /* AsteriskToken */ || token() === 26 /* DotDotDotToken */ || isLiteralPropertyName(); + } + function canFollowGetOrSetKeyword() { + return token() === 23 /* OpenBracketToken */ || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 86 /* ClassKeyword */ || token() === 100 /* FunctionKeyword */ || token() === 120 /* InterfaceKeyword */ || token() === 60 /* AtToken */ || token() === 128 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine) || token() === 134 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine); + } + function isListElement(parsingContext2, inErrorRecovery) { + const node = currentNode(parsingContext2); + if (node) { + return true; + } + switch (parsingContext2) { + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return !(token() === 27 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token() === 84 /* CaseKeyword */ || token() === 90 /* DefaultKeyword */; + case 4 /* TypeMembers */: + return lookAhead(isTypeMemberStart); + case 5 /* ClassMembers */: + return lookAhead(isClassMemberStart) || token() === 27 /* SemicolonToken */ && !inErrorRecovery; + case 6 /* EnumMembers */: + return token() === 23 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + switch (token()) { + case 23 /* OpenBracketToken */: + case 42 /* AsteriskToken */: + case 26 /* DotDotDotToken */: + case 25 /* DotToken */: + return true; + default: + return isLiteralPropertyName(); + } + case 18 /* RestProperties */: + return isLiteralPropertyName(); + case 9 /* ObjectBindingElements */: + return token() === 23 /* OpenBracketToken */ || token() === 26 /* DotDotDotToken */ || isLiteralPropertyName(); + case 24 /* ImportAttributes */: + return isImportAttributeName2(); + case 7 /* HeritageClauseElement */: + if (token() === 19 /* OpenBraceToken */) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } else { + return isIdentifier2() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8 /* VariableDeclarations */: + return isBindingIdentifierOrPrivateIdentifierOrPattern(); + case 10 /* ArrayBindingElements */: + return token() === 28 /* CommaToken */ || token() === 26 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern(); + case 19 /* TypeParameters */: + return token() === 103 /* InKeyword */ || token() === 87 /* ConstKeyword */ || isIdentifier2(); + case 15 /* ArrayLiteralMembers */: + switch (token()) { + case 28 /* CommaToken */: + case 25 /* DotToken */: + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 26 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: + return isStartOfParameter( + /*isJSDocParameter*/ + false + ); + case 17 /* JSDocParameters */: + return isStartOfParameter( + /*isJSDocParameter*/ + true + ); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: + return token() === 28 /* CommaToken */ || isStartOfType(); + case 22 /* HeritageClauses */: + return isHeritageClause2(); + case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */ && lookAhead(nextTokenIsStringLiteral)) { + return false; + } + if (token() === 11 /* StringLiteral */) { + return true; + } + return tokenIsIdentifierOrKeyword(token()); + case 13 /* JsxAttributes */: + return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; + case 14 /* JsxChildren */: + return true; + case 25 /* JSDocComment */: + return true; + case 26 /* Count */: + return Debug.fail("ParsingContext.Count used as a context"); + // Not a real context, only a marker. + default: + Debug.assertNever(parsingContext2, "Non-exhaustive case in 'isListElement'."); + } + } + function isValidHeritageClauseObjectLiteral() { + Debug.assert(token() === 19 /* OpenBraceToken */); + if (nextToken() === 20 /* CloseBraceToken */) { + const next = nextToken(); + return next === 28 /* CommaToken */ || next === 19 /* OpenBraceToken */ || next === 96 /* ExtendsKeyword */ || next === 119 /* ImplementsKeyword */; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier2(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return tokenIsIdentifierOrKeyword(token()); + } + function nextTokenIsIdentifierOrKeywordOrGreaterThan() { + nextToken(); + return tokenIsIdentifierOrKeywordOrGreaterThan(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 119 /* ImplementsKeyword */ || token() === 96 /* ExtendsKeyword */) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function nextTokenIsStartOfType() { + nextToken(); + return isStartOfType(); + } + function isListTerminator(kind) { + if (token() === 1 /* EndOfFileToken */) { + return true; + } + switch (kind) { + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 23 /* ImportOrExportSpecifiers */: + case 24 /* ImportAttributes */: + return token() === 20 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token() === 20 /* CloseBraceToken */ || token() === 84 /* CaseKeyword */ || token() === 90 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token() === 19 /* OpenBraceToken */ || token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 19 /* TypeParameters */: + return token() === 32 /* GreaterThanToken */ || token() === 21 /* OpenParenToken */ || token() === 19 /* OpenBraceToken */ || token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + return token() === 22 /* CloseParenToken */ || token() === 27 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 21 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token() === 24 /* CloseBracketToken */; + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + case 18 /* RestProperties */: + return token() === 22 /* CloseParenToken */ || token() === 24 /* CloseBracketToken */; + case 20 /* TypeArguments */: + return token() !== 28 /* CommaToken */; + case 22 /* HeritageClauses */: + return token() === 19 /* OpenBraceToken */ || token() === 20 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token() === 32 /* GreaterThanToken */ || token() === 44 /* SlashToken */; + case 14 /* JsxChildren */: + return token() === 30 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; + } + } + function isVariableDeclaratorListTerminator() { + if (canParseSemicolon()) { + return true; + } + if (isInOrOfKeyword(token())) { + return true; + } + if (token() === 39 /* EqualsGreaterThanToken */) { + return true; + } + return false; + } + function isInSomeParsingContext() { + Debug.assert(parsingContext, "Missing parsing context"); + for (let kind = 0; kind < 26 /* Count */; kind++) { + if (parsingContext & 1 << kind) { + if (isListElement( + kind, + /*inErrorRecovery*/ + true + ) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + function parseList(kind, parseElement) { + const saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + const list = []; + const listPos = getNodePos(); + while (!isListTerminator(kind)) { + if (isListElement( + kind, + /*inErrorRecovery*/ + false + )) { + list.push(parseListElement(kind, parseElement)); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseListElement(parsingContext2, parseElement) { + const node = currentNode(parsingContext2); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext2, pos) { + var _a; + if (!syntaxCursor || !isReusableParsingContext(parsingContext2) || parseErrorBeforeNextFinishedNode) { + return void 0; + } + const node = syntaxCursor.currentNode(pos ?? scanner.getTokenFullStart()); + if (nodeIsMissing(node) || intersectsIncrementalChange(node) || containsParseError(node)) { + return void 0; + } + const nodeContextFlags = node.flags & 101441536 /* ContextFlags */; + if (nodeContextFlags !== contextFlags) { + return void 0; + } + if (!canReuseNode(node, parsingContext2)) { + return void 0; + } + if (canHaveJSDoc(node) && ((_a = node.jsDoc) == null ? void 0 : _a.jsDocCache)) { + node.jsDoc.jsDocCache = void 0; + } + return node; + } + function consumeNode(node) { + scanner.resetTokenState(node.end); + nextToken(); + return node; + } + function isReusableParsingContext(parsingContext2) { + switch (parsingContext2) { + case 5 /* ClassMembers */: + case 2 /* SwitchClauses */: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + case 6 /* EnumMembers */: + case 4 /* TypeMembers */: + case 8 /* VariableDeclarations */: + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return true; + } + return false; + } + function canReuseNode(node, parsingContext2) { + switch (parsingContext2) { + case 5 /* ClassMembers */: + return isReusableClassMember(node); + case 2 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 6 /* EnumMembers */: + return isReusableEnumMember(node); + case 4 /* TypeMembers */: + return isReusableTypeMember(node); + case 8 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return isReusableParameter(node); + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 176 /* Constructor */: + case 181 /* IndexSignature */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 172 /* PropertyDeclaration */: + case 240 /* SemicolonClassElement */: + return true; + case 174 /* MethodDeclaration */: + const methodDeclaration = node; + const nameIsConstructor = methodDeclaration.name.kind === 80 /* Identifier */ && methodDeclaration.name.escapedText === "constructor"; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 296 /* CaseClause */: + case 297 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 262 /* FunctionDeclaration */: + case 243 /* VariableStatement */: + case 241 /* Block */: + case 245 /* IfStatement */: + case 244 /* ExpressionStatement */: + case 257 /* ThrowStatement */: + case 253 /* ReturnStatement */: + case 255 /* SwitchStatement */: + case 252 /* BreakStatement */: + case 251 /* ContinueStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 248 /* ForStatement */: + case 247 /* WhileStatement */: + case 254 /* WithStatement */: + case 242 /* EmptyStatement */: + case 258 /* TryStatement */: + case 256 /* LabeledStatement */: + case 246 /* DoStatement */: + case 259 /* DebuggerStatement */: + case 272 /* ImportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 278 /* ExportDeclaration */: + case 277 /* ExportAssignment */: + case 267 /* ModuleDeclaration */: + case 263 /* ClassDeclaration */: + case 264 /* InterfaceDeclaration */: + case 266 /* EnumDeclaration */: + case 265 /* TypeAliasDeclaration */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 306 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 180 /* ConstructSignature */: + case 173 /* MethodSignature */: + case 181 /* IndexSignature */: + case 171 /* PropertySignature */: + case 179 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 260 /* VariableDeclaration */) { + return false; + } + const variableDeclarator = node; + return variableDeclarator.initializer === void 0; + } + function isReusableParameter(node) { + if (node.kind !== 169 /* Parameter */) { + return false; + } + const parameter = node; + return parameter.initializer === void 0; + } + function abortParsingListOrMoveToNextToken(kind) { + parsingContextErrors(kind); + if (isInSomeParsingContext()) { + return true; + } + nextToken(); + return false; + } + function parsingContextErrors(context) { + switch (context) { + case 0 /* SourceElements */: + return token() === 90 /* DefaultKeyword */ ? parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(95 /* ExportKeyword */)) : parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); + case 1 /* BlockStatements */: + return parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); + case 2 /* SwitchClauses */: + return parseErrorAtCurrentToken(Diagnostics.case_or_default_expected); + case 3 /* SwitchClauseStatements */: + return parseErrorAtCurrentToken(Diagnostics.Statement_expected); + case 18 /* RestProperties */: + // fallthrough + case 4 /* TypeMembers */: + return parseErrorAtCurrentToken(Diagnostics.Property_or_signature_expected); + case 5 /* ClassMembers */: + return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected); + case 6 /* EnumMembers */: + return parseErrorAtCurrentToken(Diagnostics.Enum_member_expected); + case 7 /* HeritageClauseElement */: + return parseErrorAtCurrentToken(Diagnostics.Expression_expected); + case 8 /* VariableDeclarations */: + return isKeyword(token()) ? parseErrorAtCurrentToken(Diagnostics._0_is_not_allowed_as_a_variable_declaration_name, tokenToString(token())) : parseErrorAtCurrentToken(Diagnostics.Variable_declaration_expected); + case 9 /* ObjectBindingElements */: + return parseErrorAtCurrentToken(Diagnostics.Property_destructuring_pattern_expected); + case 10 /* ArrayBindingElements */: + return parseErrorAtCurrentToken(Diagnostics.Array_element_destructuring_pattern_expected); + case 11 /* ArgumentExpressions */: + return parseErrorAtCurrentToken(Diagnostics.Argument_expression_expected); + case 12 /* ObjectLiteralMembers */: + return parseErrorAtCurrentToken(Diagnostics.Property_assignment_expected); + case 15 /* ArrayLiteralMembers */: + return parseErrorAtCurrentToken(Diagnostics.Expression_or_comma_expected); + case 17 /* JSDocParameters */: + return parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected); + case 16 /* Parameters */: + return isKeyword(token()) ? parseErrorAtCurrentToken(Diagnostics._0_is_not_allowed_as_a_parameter_name, tokenToString(token())) : parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected); + case 19 /* TypeParameters */: + return parseErrorAtCurrentToken(Diagnostics.Type_parameter_declaration_expected); + case 20 /* TypeArguments */: + return parseErrorAtCurrentToken(Diagnostics.Type_argument_expected); + case 21 /* TupleElementTypes */: + return parseErrorAtCurrentToken(Diagnostics.Type_expected); + case 22 /* HeritageClauses */: + return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); + case 23 /* ImportOrExportSpecifiers */: + if (token() === 161 /* FromKeyword */) { + return parseErrorAtCurrentToken(Diagnostics._0_expected, "}"); + } + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 13 /* JsxAttributes */: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 14 /* JsxChildren */: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 24 /* ImportAttributes */: + return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); + case 25 /* JSDocComment */: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 26 /* Count */: + return Debug.fail("ParsingContext.Count used as a context"); + // Not a real context, only a marker. + default: + Debug.assertNever(context); + } + } + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { + const saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + const list = []; + const listPos = getNodePos(); + let commaStart = -1; + while (true) { + if (isListElement( + kind, + /*inErrorRecovery*/ + false + )) { + const startPos = scanner.getTokenFullStart(); + const result = parseListElement(kind, parseElement); + if (!result) { + parsingContext = saveParsingContext; + return void 0; + } + list.push(result); + commaStart = scanner.getTokenStart(); + if (parseOptional(28 /* CommaToken */)) { + continue; + } + commaStart = -1; + if (isListTerminator(kind)) { + break; + } + parseExpected(28 /* CommaToken */, getExpectedCommaDiagnostic(kind)); + if (considerSemicolonAsDelimiter && token() === 27 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + } + if (startPos === scanner.getTokenFullStart()) { + nextToken(); + } + continue; + } + if (isListTerminator(kind)) { + break; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + parsingContext = saveParsingContext; + return createNodeArray( + list, + listPos, + /*end*/ + void 0, + commaStart >= 0 + ); + } + function getExpectedCommaDiagnostic(kind) { + return kind === 6 /* EnumMembers */ ? Diagnostics.An_enum_member_name_must_be_followed_by_a_or : void 0; + } + function createMissingList() { + const list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + const result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + const pos = getNodePos(); + let entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); + while (parseOptional(25 /* DotToken */)) { + if (token() === 30 /* LessThanToken */) { + break; + } + entity = finishNode( + factory2.createQualifiedName( + entity, + parseRightSideOfDot( + allowReservedWords, + /*allowPrivateIdentifiers*/ + false, + /*allowUnicodeEscapeSequenceInIdentifierName*/ + true + ) + ), + pos + ); + } + return entity; + } + function createQualifiedName(entity, name) { + return finishNode(factory2.createQualifiedName(entity, name), entity.pos); + } + function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers, allowUnicodeEscapeSequenceInIdentifierName) { + if (scanner.hasPrecedingLineBreak() && tokenIsIdentifierOrKeyword(token())) { + const matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + return createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + true, + Diagnostics.Identifier_expected + ); + } + } + if (token() === 81 /* PrivateIdentifier */) { + const node = parsePrivateIdentifier(); + return allowPrivateIdentifiers ? node : createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + true, + Diagnostics.Identifier_expected + ); + } + if (allowIdentifierNames) { + return allowUnicodeEscapeSequenceInIdentifierName ? parseIdentifierName() : parseIdentifierNameErrorOnUnicodeEscapeSequence(); + } + return parseIdentifier(); + } + function parseTemplateSpans(isTaggedTemplate) { + const pos = getNodePos(); + const list = []; + let node; + do { + node = parseTemplateSpan(isTaggedTemplate); + list.push(node); + } while (node.literal.kind === 17 /* TemplateMiddle */); + return createNodeArray(list, pos); + } + function parseTemplateExpression(isTaggedTemplate) { + const pos = getNodePos(); + return finishNode( + factory2.createTemplateExpression( + parseTemplateHead(isTaggedTemplate), + parseTemplateSpans(isTaggedTemplate) + ), + pos + ); + } + function parseTemplateType() { + const pos = getNodePos(); + return finishNode( + factory2.createTemplateLiteralType( + parseTemplateHead( + /*isTaggedTemplate*/ + false + ), + parseTemplateTypeSpans() + ), + pos + ); + } + function parseTemplateTypeSpans() { + const pos = getNodePos(); + const list = []; + let node; + do { + node = parseTemplateTypeSpan(); + list.push(node); + } while (node.literal.kind === 17 /* TemplateMiddle */); + return createNodeArray(list, pos); + } + function parseTemplateTypeSpan() { + const pos = getNodePos(); + return finishNode( + factory2.createTemplateLiteralTypeSpan( + parseType(), + parseLiteralOfTemplateSpan( + /*isTaggedTemplate*/ + false + ) + ), + pos + ); + } + function parseLiteralOfTemplateSpan(isTaggedTemplate) { + if (token() === 20 /* CloseBraceToken */) { + reScanTemplateToken(isTaggedTemplate); + return parseTemplateMiddleOrTemplateTail(); + } else { + return parseExpectedToken(18 /* TemplateTail */, Diagnostics._0_expected, tokenToString(20 /* CloseBraceToken */)); + } + } + function parseTemplateSpan(isTaggedTemplate) { + const pos = getNodePos(); + return finishNode( + factory2.createTemplateSpan( + allowInAnd(parseExpression), + parseLiteralOfTemplateSpan(isTaggedTemplate) + ), + pos + ); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead(isTaggedTemplate) { + if (!isTaggedTemplate && scanner.getTokenFlags() & 26656 /* IsInvalid */) { + reScanTemplateToken( + /*isTaggedTemplate*/ + false + ); + } + const fragment = parseLiteralLikeNode(token()); + Debug.assert(fragment.kind === 16 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + const fragment = parseLiteralLikeNode(token()); + Debug.assert(fragment.kind === 17 /* TemplateMiddle */ || fragment.kind === 18 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; + } + function getTemplateLiteralRawText(kind) { + const isLast = kind === 15 /* NoSubstitutionTemplateLiteral */ || kind === 18 /* TemplateTail */; + const tokenText = scanner.getTokenText(); + return tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2)); + } + function parseLiteralLikeNode(kind) { + const pos = getNodePos(); + const node = isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & 7176 /* TemplateLiteralLikeFlags */) : ( + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal. But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral( + scanner.getTokenValue(), + /*isSingleQuote*/ + void 0, + scanner.hasExtendedUnicodeEscape() + ) : isLiteralKind(kind) ? factoryCreateLiteralLikeNode(kind, scanner.getTokenValue()) : Debug.fail() + ); + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + nextToken(); + return finishNode(node, pos); + } + function parseEntityNameOfTypeReference() { + return parseEntityName( + /*allowReservedWords*/ + true, + Diagnostics.Type_expected + ); + } + function parseTypeArgumentsOfTypeReference() { + if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 30 /* LessThanToken */) { + return parseBracketedList(20 /* TypeArguments */, parseType, 30 /* LessThanToken */, 32 /* GreaterThanToken */); + } + } + function parseTypeReference() { + const pos = getNodePos(); + return finishNode( + factory2.createTypeReferenceNode( + parseEntityNameOfTypeReference(), + parseTypeArgumentsOfTypeReference() + ), + pos + ); + } + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 183 /* TypeReference */: + return nodeIsMissing(node.typeName); + case 184 /* FunctionType */: + case 185 /* ConstructorType */: { + const { parameters, type } = node; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } + case 196 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } + function parseThisTypePredicate(lhs) { + nextToken(); + return finishNode(factory2.createTypePredicateNode( + /*assertsModifier*/ + void 0, + lhs, + parseType() + ), lhs.pos); + } + function parseThisTypeNode() { + const pos = getNodePos(); + nextToken(); + return finishNode(factory2.createThisTypeNode(), pos); + } + function parseJSDocAllType() { + const pos = getNodePos(); + nextToken(); + return finishNode(factory2.createJSDocAllType(), pos); + } + function parseJSDocNonNullableType() { + const pos = getNodePos(); + nextToken(); + return finishNode(factory2.createJSDocNonNullableType( + parseNonArrayType(), + /*postfix*/ + false + ), pos); + } + function parseJSDocUnknownOrNullableType() { + const pos = getNodePos(); + nextToken(); + if (token() === 28 /* CommaToken */ || token() === 20 /* CloseBraceToken */ || token() === 22 /* CloseParenToken */ || token() === 32 /* GreaterThanToken */ || token() === 64 /* EqualsToken */ || token() === 52 /* BarToken */) { + return finishNode(factory2.createJSDocUnknownType(), pos); + } else { + return finishNode(factory2.createJSDocNullableType( + parseType(), + /*postfix*/ + false + ), pos); + } + } + function parseJSDocFunctionType() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + if (tryParse(nextTokenIsOpenParen)) { + const parameters = parseParameters(4 /* Type */ | 32 /* JSDoc */); + const type = parseReturnType( + 59 /* ColonToken */, + /*isType*/ + false + ); + return withJSDoc(finishNode(factory2.createJSDocFunctionType(parameters, type), pos), hasJSDoc); + } + return finishNode(factory2.createTypeReferenceNode( + parseIdentifierName(), + /*typeArguments*/ + void 0 + ), pos); + } + function parseJSDocParameter() { + const pos = getNodePos(); + let name; + if (token() === 110 /* ThisKeyword */ || token() === 105 /* NewKeyword */) { + name = parseIdentifierName(); + parseExpected(59 /* ColonToken */); + } + return finishNode( + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? + name, + /*questionToken*/ + void 0, + parseJSDocType(), + /*initializer*/ + void 0 + ), + pos + ); + } + function parseJSDocType() { + scanner.setSkipJsDocLeadingAsterisks(true); + const pos = getNodePos(); + if (parseOptional(144 /* ModuleKeyword */)) { + const moduleTag = factory2.createJSDocNamepathType( + /*type*/ + void 0 + ); + terminate: + while (true) { + switch (token()) { + case 20 /* CloseBraceToken */: + case 1 /* EndOfFileToken */: + case 28 /* CommaToken */: + case 5 /* WhitespaceTrivia */: + break terminate; + default: + nextTokenJSDoc(); + } + } + scanner.setSkipJsDocLeadingAsterisks(false); + return finishNode(moduleTag, pos); + } + const hasDotDotDot = parseOptional(26 /* DotDotDotToken */); + let type = parseTypeOrTypePredicate(); + scanner.setSkipJsDocLeadingAsterisks(false); + if (hasDotDotDot) { + type = finishNode(factory2.createJSDocVariadicType(type), pos); + } + if (token() === 64 /* EqualsToken */) { + nextToken(); + return finishNode(factory2.createJSDocOptionalType(type), pos); + } + return type; + } + function parseTypeQuery() { + const pos = getNodePos(); + parseExpected(114 /* TypeOfKeyword */); + const entityName = parseEntityName( + /*allowReservedWords*/ + true + ); + const typeArguments = !scanner.hasPrecedingLineBreak() ? tryParseTypeArguments() : void 0; + return finishNode(factory2.createTypeQueryNode(entityName, typeArguments), pos); + } + function parseTypeParameter() { + const pos = getNodePos(); + const modifiers = parseModifiers( + /*allowDecorators*/ + false, + /*permitConstAsModifier*/ + true + ); + const name = parseIdentifier(); + let constraint; + let expression; + if (parseOptional(96 /* ExtendsKeyword */)) { + if (isStartOfType() || !isStartOfExpression()) { + constraint = parseType(); + } else { + expression = parseUnaryExpressionOrHigher(); + } + } + const defaultType = parseOptional(64 /* EqualsToken */) ? parseType() : void 0; + const node = factory2.createTypeParameterDeclaration(modifiers, name, constraint, defaultType); + node.expression = expression; + return finishNode(node, pos); + } + function parseTypeParameters() { + if (token() === 30 /* LessThanToken */) { + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 30 /* LessThanToken */, 32 /* GreaterThanToken */); + } + } + function isStartOfParameter(isJSDocParameter) { + return token() === 26 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern() || isModifierKind(token()) || token() === 60 /* AtToken */ || isStartOfType( + /*inStartOfParameter*/ + !isJSDocParameter + ); + } + function parseNameOfParameter(modifiers) { + const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_cannot_be_used_as_parameters); + if (getFullWidth(name) === 0 && !some(modifiers) && isModifierKind(token())) { + nextToken(); + } + return name; + } + function isParameterNameStart() { + return isBindingIdentifier() || token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */; + } + function parseParameter(inOuterAwaitContext) { + return parseParameterWorker(inOuterAwaitContext); + } + function parseParameterForSpeculation(inOuterAwaitContext) { + return parseParameterWorker( + inOuterAwaitContext, + /*allowAmbiguity*/ + false + ); + } + function parseParameterWorker(inOuterAwaitContext, allowAmbiguity = true) { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const modifiers = inOuterAwaitContext ? doInAwaitContext(() => parseModifiers( + /*allowDecorators*/ + true + )) : doOutsideOfAwaitContext(() => parseModifiers( + /*allowDecorators*/ + true + )); + if (token() === 110 /* ThisKeyword */) { + const node2 = factory2.createParameterDeclaration( + modifiers, + /*dotDotDotToken*/ + void 0, + createIdentifier( + /*isIdentifier*/ + true + ), + /*questionToken*/ + void 0, + parseTypeAnnotation(), + /*initializer*/ + void 0 + ); + const modifier = firstOrUndefined(modifiers); + if (modifier) { + parseErrorAtRange(modifier, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters); + } + return withJSDoc(finishNode(node2, pos), hasJSDoc); + } + const savedTopLevel = topLevel; + topLevel = false; + const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */); + if (!allowAmbiguity && !isParameterNameStart()) { + return void 0; + } + const node = withJSDoc( + finishNode( + factory2.createParameterDeclaration( + modifiers, + dotDotDotToken, + parseNameOfParameter(modifiers), + parseOptionalToken(58 /* QuestionToken */), + parseTypeAnnotation(), + parseInitializer() + ), + pos + ), + hasJSDoc + ); + topLevel = savedTopLevel; + return node; + } + function parseReturnType(returnToken, isType) { + if (shouldParseReturnType(returnToken, isType)) { + return allowConditionalTypesAnd(parseTypeOrTypePredicate); + } + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 39 /* EqualsGreaterThanToken */) { + parseExpected(returnToken); + return true; + } else if (parseOptional(59 /* ColonToken */)) { + return true; + } else if (isType && token() === 39 /* EqualsGreaterThanToken */) { + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(59 /* ColonToken */)); + nextToken(); + return true; + } + return false; + } + function parseParametersWorker(flags, allowAmbiguity) { + const savedYieldContext = inYieldContext(); + const savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + const parameters = flags & 32 /* JSDoc */ ? parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : parseDelimitedList(16 /* Parameters */, () => allowAmbiguity ? parseParameter(savedAwaitContext) : parseParameterForSpeculation(savedAwaitContext)); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parameters; + } + function parseParameters(flags) { + if (!parseExpected(21 /* OpenParenToken */)) { + return createMissingList(); + } + const parameters = parseParametersWorker( + flags, + /*allowAmbiguity*/ + true + ); + parseExpected(22 /* CloseParenToken */); + return parameters; + } + function parseTypeMemberSemicolon() { + if (parseOptional(28 /* CommaToken */)) { + return; + } + parseSemicolon(); + } + function parseSignatureMember(kind) { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + if (kind === 180 /* ConstructSignature */) { + parseExpected(105 /* NewKeyword */); + } + const typeParameters = parseTypeParameters(); + const parameters = parseParameters(4 /* Type */); + const type = parseReturnType( + 59 /* ColonToken */, + /*isType*/ + true + ); + parseTypeMemberSemicolon(); + const node = kind === 179 /* CallSignature */ ? factory2.createCallSignature(typeParameters, parameters, type) : factory2.createConstructSignature(typeParameters, parameters, type); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function isIndexSignature() { + return token() === 23 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + nextToken(); + if (token() === 26 /* DotDotDotToken */ || token() === 24 /* CloseBracketToken */) { + return true; + } + if (isModifierKind(token())) { + nextToken(); + if (isIdentifier2()) { + return true; + } + } else if (!isIdentifier2()) { + return false; + } else { + nextToken(); + } + if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */) { + return true; + } + if (token() !== 58 /* QuestionToken */) { + return false; + } + nextToken(); + return token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 24 /* CloseBracketToken */; + } + function parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers) { + const parameters = parseBracketedList(16 /* Parameters */, () => parseParameter( + /*inOuterAwaitContext*/ + false + ), 23 /* OpenBracketToken */, 24 /* CloseBracketToken */); + const type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + const node = factory2.createIndexSignature(modifiers, parameters, type); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) { + const name = parsePropertyName(); + const questionToken = parseOptionalToken(58 /* QuestionToken */); + let node; + if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) { + const typeParameters = parseTypeParameters(); + const parameters = parseParameters(4 /* Type */); + const type = parseReturnType( + 59 /* ColonToken */, + /*isType*/ + true + ); + node = factory2.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type); + } else { + const type = parseTypeAnnotation(); + node = factory2.createPropertySignature(modifiers, name, questionToken, type); + if (token() === 64 /* EqualsToken */) node.initializer = parseInitializer(); + } + parseTypeMemberSemicolon(); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function isTypeMemberStart() { + if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 139 /* GetKeyword */ || token() === 153 /* SetKeyword */) { + return true; + } + let idToken = false; + while (isModifierKind(token())) { + idToken = true; + nextToken(); + } + if (token() === 23 /* OpenBracketToken */) { + return true; + } + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + if (idToken) { + return token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 58 /* QuestionToken */ || token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) { + return parseSignatureMember(179 /* CallSignature */); + } + if (token() === 105 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(180 /* ConstructSignature */); + } + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const modifiers = parseModifiers( + /*allowDecorators*/ + false + ); + if (parseContextualModifier(139 /* GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */, 4 /* Type */); + } + if (parseContextualModifier(153 /* SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */, 4 /* Type */); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers); + } + return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */; + } + function nextTokenIsDot() { + return nextToken() === 25 /* DotToken */; + } + function nextTokenIsOpenParenOrLessThanOrDot() { + switch (nextToken()) { + case 21 /* OpenParenToken */: + case 30 /* LessThanToken */: + case 25 /* DotToken */: + return true; + } + return false; + } + function parseTypeLiteral() { + const pos = getNodePos(); + return finishNode(factory2.createTypeLiteralNode(parseObjectTypeMembers()), pos); + } + function parseObjectTypeMembers() { + let members; + if (parseExpected(19 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(20 /* CloseBraceToken */); + } else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */) { + return nextToken() === 148 /* ReadonlyKeyword */; + } + if (token() === 148 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 23 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 103 /* InKeyword */; + } + function parseMappedTypeParameter() { + const pos = getNodePos(); + const name = parseIdentifierName(); + parseExpected(103 /* InKeyword */); + const type = parseType(); + return finishNode(factory2.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + name, + type, + /*defaultType*/ + void 0 + ), pos); + } + function parseMappedType() { + const pos = getNodePos(); + parseExpected(19 /* OpenBraceToken */); + let readonlyToken; + if (token() === 148 /* ReadonlyKeyword */ || token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */) { + readonlyToken = parseTokenNode(); + if (readonlyToken.kind !== 148 /* ReadonlyKeyword */) { + parseExpected(148 /* ReadonlyKeyword */); + } + } + parseExpected(23 /* OpenBracketToken */); + const typeParameter = parseMappedTypeParameter(); + const nameType = parseOptional(130 /* AsKeyword */) ? parseType() : void 0; + parseExpected(24 /* CloseBracketToken */); + let questionToken; + if (token() === 58 /* QuestionToken */ || token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */) { + questionToken = parseTokenNode(); + if (questionToken.kind !== 58 /* QuestionToken */) { + parseExpected(58 /* QuestionToken */); + } + } + const type = parseTypeAnnotation(); + parseSemicolon(); + const members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(20 /* CloseBraceToken */); + return finishNode(factory2.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); + } + function parseTupleElementType() { + const pos = getNodePos(); + if (parseOptional(26 /* DotDotDotToken */)) { + return finishNode(factory2.createRestTypeNode(parseType()), pos); + } + const type = parseType(); + if (isJSDocNullableType(type) && type.pos === type.type.pos) { + const node = factory2.createOptionalTypeNode(type.type); + setTextRange(node, type); + node.flags = type.flags; + return node; + } + return type; + } + function isNextTokenColonOrQuestionColon() { + return nextToken() === 59 /* ColonToken */ || token() === 58 /* QuestionToken */ && nextToken() === 59 /* ColonToken */; + } + function isTupleElementName() { + if (token() === 26 /* DotDotDotToken */) { + return tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon(); + } + return tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon(); + } + function parseTupleElementNameOrTupleElementType() { + if (lookAhead(isTupleElementName)) { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */); + const name = parseIdentifierName(); + const questionToken = parseOptionalToken(58 /* QuestionToken */); + parseExpected(59 /* ColonToken */); + const type = parseTupleElementType(); + const node = factory2.createNamedTupleMember(dotDotDotToken, name, questionToken, type); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + return parseTupleElementType(); + } + function parseTupleType() { + const pos = getNodePos(); + return finishNode( + factory2.createTupleTypeNode( + parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 23 /* OpenBracketToken */, 24 /* CloseBracketToken */) + ), + pos + ); + } + function parseParenthesizedType() { + const pos = getNodePos(); + parseExpected(21 /* OpenParenToken */); + const type = parseType(); + parseExpected(22 /* CloseParenToken */); + return finishNode(factory2.createParenthesizedType(type), pos); + } + function parseModifiersForConstructorType() { + let modifiers; + if (token() === 128 /* AbstractKeyword */) { + const pos = getNodePos(); + nextToken(); + const modifier = finishNode(factoryCreateToken(128 /* AbstractKeyword */), pos); + modifiers = createNodeArray([modifier], pos); + } + return modifiers; + } + function parseFunctionOrConstructorType() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const modifiers = parseModifiersForConstructorType(); + const isConstructorType = parseOptional(105 /* NewKeyword */); + Debug.assert(!modifiers || isConstructorType, "Per isStartOfFunctionOrConstructorType, a function type cannot have modifiers."); + const typeParameters = parseTypeParameters(); + const parameters = parseParameters(4 /* Type */); + const type = parseReturnType( + 39 /* EqualsGreaterThanToken */, + /*isType*/ + false + ); + const node = isConstructorType ? factory2.createConstructorTypeNode(modifiers, typeParameters, parameters, type) : factory2.createFunctionTypeNode(typeParameters, parameters, type); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseKeywordAndNoDot() { + const node = parseTokenNode(); + return token() === 25 /* DotToken */ ? void 0 : node; + } + function parseLiteralTypeNode(negative) { + const pos = getNodePos(); + if (negative) { + nextToken(); + } + let expression = token() === 112 /* TrueKeyword */ || token() === 97 /* FalseKeyword */ || token() === 106 /* NullKeyword */ ? parseTokenNode() : parseLiteralLikeNode(token()); + if (negative) { + expression = finishNode(factory2.createPrefixUnaryExpression(41 /* MinusToken */, expression), pos); + } + return finishNode(factory2.createLiteralTypeNode(expression), pos); + } + function isStartOfTypeOfImportType() { + nextToken(); + return token() === 102 /* ImportKeyword */; + } + function parseImportType() { + sourceFlags |= 4194304 /* PossiblyContainsDynamicImport */; + const pos = getNodePos(); + const isTypeOf = parseOptional(114 /* TypeOfKeyword */); + parseExpected(102 /* ImportKeyword */); + parseExpected(21 /* OpenParenToken */); + const type = parseType(); + let attributes; + if (parseOptional(28 /* CommaToken */)) { + const openBracePosition = scanner.getTokenStart(); + parseExpected(19 /* OpenBraceToken */); + const currentToken2 = token(); + if (currentToken2 === 118 /* WithKeyword */ || currentToken2 === 132 /* AssertKeyword */) { + nextToken(); + } else { + parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(118 /* WithKeyword */)); + } + parseExpected(59 /* ColonToken */); + attributes = parseImportAttributes( + currentToken2, + /*skipKeyword*/ + true + ); + if (!parseExpected(20 /* CloseBraceToken */)) { + const lastError = lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === Diagnostics._0_expected.code) { + addRelatedInfo( + lastError, + createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") + ); + } + } + } + parseExpected(22 /* CloseParenToken */); + const qualifier = parseOptional(25 /* DotToken */) ? parseEntityNameOfTypeReference() : void 0; + const typeArguments = parseTypeArgumentsOfTypeReference(); + return finishNode(factory2.createImportTypeNode(type, attributes, qualifier, typeArguments, isTypeOf), pos); + } + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */; + } + function parseNonArrayType() { + switch (token()) { + case 133 /* AnyKeyword */: + case 159 /* UnknownKeyword */: + case 154 /* StringKeyword */: + case 150 /* NumberKeyword */: + case 163 /* BigIntKeyword */: + case 155 /* SymbolKeyword */: + case 136 /* BooleanKeyword */: + case 157 /* UndefinedKeyword */: + case 146 /* NeverKeyword */: + case 151 /* ObjectKeyword */: + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 67 /* AsteriskEqualsToken */: + scanner.reScanAsteriskEqualsToken(); + // falls through + case 42 /* AsteriskToken */: + return parseJSDocAllType(); + case 61 /* QuestionQuestionToken */: + scanner.reScanQuestionToken(); + // falls through + case 58 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 100 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 54 /* ExclamationToken */: + return parseJSDocNonNullableType(); + case 15 /* NoSubstitutionTemplateLiteral */: + case 11 /* StringLiteral */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 106 /* NullKeyword */: + return parseLiteralTypeNode(); + case 41 /* MinusToken */: + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode( + /*negative*/ + true + ) : parseTypeReference(); + case 116 /* VoidKeyword */: + return parseTokenNode(); + case 110 /* ThisKeyword */: { + const thisKeyword = parseThisTypeNode(); + if (token() === 142 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } else { + return thisKeyword; + } + } + case 114 /* TypeOfKeyword */: + return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); + case 19 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 23 /* OpenBracketToken */: + return parseTupleType(); + case 21 /* OpenParenToken */: + return parseParenthesizedType(); + case 102 /* ImportKeyword */: + return parseImportType(); + case 131 /* AssertsKeyword */: + return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference(); + case 16 /* TemplateHead */: + return parseTemplateType(); + default: + return parseTypeReference(); + } + } + function isStartOfType(inStartOfParameter) { + switch (token()) { + case 133 /* AnyKeyword */: + case 159 /* UnknownKeyword */: + case 154 /* StringKeyword */: + case 150 /* NumberKeyword */: + case 163 /* BigIntKeyword */: + case 136 /* BooleanKeyword */: + case 148 /* ReadonlyKeyword */: + case 155 /* SymbolKeyword */: + case 158 /* UniqueKeyword */: + case 116 /* VoidKeyword */: + case 157 /* UndefinedKeyword */: + case 106 /* NullKeyword */: + case 110 /* ThisKeyword */: + case 114 /* TypeOfKeyword */: + case 146 /* NeverKeyword */: + case 19 /* OpenBraceToken */: + case 23 /* OpenBracketToken */: + case 30 /* LessThanToken */: + case 52 /* BarToken */: + case 51 /* AmpersandToken */: + case 105 /* NewKeyword */: + case 11 /* StringLiteral */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 151 /* ObjectKeyword */: + case 42 /* AsteriskToken */: + case 58 /* QuestionToken */: + case 54 /* ExclamationToken */: + case 26 /* DotDotDotToken */: + case 140 /* InferKeyword */: + case 102 /* ImportKeyword */: + case 131 /* AssertsKeyword */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 16 /* TemplateHead */: + return true; + case 100 /* FunctionKeyword */: + return !inStartOfParameter; + case 41 /* MinusToken */: + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + case 21 /* OpenParenToken */: + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier2(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 22 /* CloseParenToken */ || isStartOfParameter( + /*isJSDocParameter*/ + false + ) || isStartOfType(); + } + function parsePostfixTypeOrHigher() { + const pos = getNodePos(); + let type = parseNonArrayType(); + while (!scanner.hasPrecedingLineBreak()) { + switch (token()) { + case 54 /* ExclamationToken */: + nextToken(); + type = finishNode(factory2.createJSDocNonNullableType( + type, + /*postfix*/ + true + ), pos); + break; + case 58 /* QuestionToken */: + if (lookAhead(nextTokenIsStartOfType)) { + return type; + } + nextToken(); + type = finishNode(factory2.createJSDocNullableType( + type, + /*postfix*/ + true + ), pos); + break; + case 23 /* OpenBracketToken */: + parseExpected(23 /* OpenBracketToken */); + if (isStartOfType()) { + const indexType = parseType(); + parseExpected(24 /* CloseBracketToken */); + type = finishNode(factory2.createIndexedAccessTypeNode(type, indexType), pos); + } else { + parseExpected(24 /* CloseBracketToken */); + type = finishNode(factory2.createArrayTypeNode(type), pos); + } + break; + default: + return type; + } + } + return type; + } + function parseTypeOperator(operator) { + const pos = getNodePos(); + parseExpected(operator); + return finishNode(factory2.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos); + } + function tryParseConstraintOfInferType() { + if (parseOptional(96 /* ExtendsKeyword */)) { + const constraint = disallowConditionalTypesAnd(parseType); + if (inDisallowConditionalTypesContext() || token() !== 58 /* QuestionToken */) { + return constraint; + } + } + } + function parseTypeParameterOfInferType() { + const pos = getNodePos(); + const name = parseIdentifier(); + const constraint = tryParse(tryParseConstraintOfInferType); + const node = factory2.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + name, + constraint + ); + return finishNode(node, pos); + } + function parseInferType() { + const pos = getNodePos(); + parseExpected(140 /* InferKeyword */); + return finishNode(factory2.createInferTypeNode(parseTypeParameterOfInferType()), pos); + } + function parseTypeOperatorOrHigher() { + const operator = token(); + switch (operator) { + case 143 /* KeyOfKeyword */: + case 158 /* UniqueKeyword */: + case 148 /* ReadonlyKeyword */: + return parseTypeOperator(operator); + case 140 /* InferKeyword */: + return parseInferType(); + } + return allowConditionalTypesAnd(parsePostfixTypeOrHigher); + } + function parseFunctionOrConstructorTypeToError(isInUnionType) { + if (isStartOfFunctionTypeOrConstructorType()) { + const type = parseFunctionOrConstructorType(); + let diagnostic; + if (isFunctionTypeNode(type)) { + diagnostic = isInUnionType ? Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_a_union_type : Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type; + } else { + diagnostic = isInUnionType ? Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type : Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type; + } + parseErrorAtRange(type, diagnostic); + return type; + } + return void 0; + } + function parseUnionOrIntersectionType(operator, parseConstituentType, createTypeNode) { + const pos = getNodePos(); + const isUnionType = operator === 52 /* BarToken */; + const hasLeadingOperator = parseOptional(operator); + let type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType(); + if (token() === operator || hasLeadingOperator) { + const types = [type]; + while (parseOptional(operator)) { + types.push(parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType()); + } + type = finishNode(createTypeNode(createNodeArray(types, pos)), pos); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(51 /* AmpersandToken */, parseTypeOperatorOrHigher, factory2.createIntersectionTypeNode); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(52 /* BarToken */, parseIntersectionTypeOrHigher, factory2.createUnionTypeNode); + } + function nextTokenIsNewKeyword() { + nextToken(); + return token() === 105 /* NewKeyword */; + } + function isStartOfFunctionTypeOrConstructorType() { + if (token() === 30 /* LessThanToken */) { + return true; + } + if (token() === 21 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) { + return true; + } + return token() === 105 /* NewKeyword */ || token() === 128 /* AbstractKeyword */ && lookAhead(nextTokenIsNewKeyword); + } + function skipParameterStart() { + if (isModifierKind(token())) { + parseModifiers( + /*allowDecorators*/ + false + ); + } + if (isIdentifier2() || token() === 110 /* ThisKeyword */) { + nextToken(); + return true; + } + if (token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */) { + const previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 22 /* CloseParenToken */ || token() === 26 /* DotDotDotToken */) { + return true; + } + if (skipParameterStart()) { + if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 58 /* QuestionToken */ || token() === 64 /* EqualsToken */) { + return true; + } + if (token() === 22 /* CloseParenToken */) { + nextToken(); + if (token() === 39 /* EqualsGreaterThanToken */) { + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + const pos = getNodePos(); + const typePredicateVariable = isIdentifier2() && tryParse(parseTypePredicatePrefix); + const type = parseType(); + if (typePredicateVariable) { + return finishNode(factory2.createTypePredicateNode( + /*assertsModifier*/ + void 0, + typePredicateVariable, + type + ), pos); + } else { + return type; + } + } + function parseTypePredicatePrefix() { + const id = parseIdentifier(); + if (token() === 142 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseAssertsTypePredicate() { + const pos = getNodePos(); + const assertsModifier = parseExpectedToken(131 /* AssertsKeyword */); + const parameterName = token() === 110 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier(); + const type = parseOptional(142 /* IsKeyword */) ? parseType() : void 0; + return finishNode(factory2.createTypePredicateNode(assertsModifier, parameterName, type), pos); + } + function parseType() { + if (contextFlags & 81920 /* TypeExcludesFlags */) { + return doOutsideOfContext(81920 /* TypeExcludesFlags */, parseType); + } + if (isStartOfFunctionTypeOrConstructorType()) { + return parseFunctionOrConstructorType(); + } + const pos = getNodePos(); + const type = parseUnionTypeOrHigher(); + if (!inDisallowConditionalTypesContext() && !scanner.hasPrecedingLineBreak() && parseOptional(96 /* ExtendsKeyword */)) { + const extendsType = disallowConditionalTypesAnd(parseType); + parseExpected(58 /* QuestionToken */); + const trueType = allowConditionalTypesAnd(parseType); + parseExpected(59 /* ColonToken */); + const falseType = allowConditionalTypesAnd(parseType); + return finishNode(factory2.createConditionalTypeNode(type, extendsType, trueType, falseType), pos); + } + return type; + } + function parseTypeAnnotation() { + return parseOptional(59 /* ColonToken */) ? parseType() : void 0; + } + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 110 /* ThisKeyword */: + case 108 /* SuperKeyword */: + case 106 /* NullKeyword */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 16 /* TemplateHead */: + case 21 /* OpenParenToken */: + case 23 /* OpenBracketToken */: + case 19 /* OpenBraceToken */: + case 100 /* FunctionKeyword */: + case 86 /* ClassKeyword */: + case 105 /* NewKeyword */: + case 44 /* SlashToken */: + case 69 /* SlashEqualsToken */: + case 80 /* Identifier */: + return true; + case 102 /* ImportKeyword */: + return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + default: + return isIdentifier2(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 40 /* PlusToken */: + case 41 /* MinusToken */: + case 55 /* TildeToken */: + case 54 /* ExclamationToken */: + case 91 /* DeleteKeyword */: + case 114 /* TypeOfKeyword */: + case 116 /* VoidKeyword */: + case 46 /* PlusPlusToken */: + case 47 /* MinusMinusToken */: + case 30 /* LessThanToken */: + case 135 /* AwaitKeyword */: + case 127 /* YieldKeyword */: + case 81 /* PrivateIdentifier */: + case 60 /* AtToken */: + return true; + default: + if (isBinaryOperator2()) { + return true; + } + return isIdentifier2(); + } + } + function isStartOfExpressionStatement() { + return token() !== 19 /* OpenBraceToken */ && token() !== 100 /* FunctionKeyword */ && token() !== 86 /* ClassKeyword */ && token() !== 60 /* AtToken */ && isStartOfExpression(); + } + function parseExpression() { + const saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext( + /*val*/ + false + ); + } + const pos = getNodePos(); + let expr = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + ); + let operatorToken; + while (operatorToken = parseOptionalToken(28 /* CommaToken */)) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + ), pos); + } + if (saveDecoratorContext) { + setDecoratorContext( + /*val*/ + true + ); + } + return expr; + } + function parseInitializer() { + return parseOptional(64 /* EqualsToken */) ? parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + ) : void 0; + } + function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { + if (isYieldExpression()) { + return parseYieldExpression(); + } + const arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); + if (arrowExpression) { + return arrowExpression; + } + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); + if (expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) { + return parseSimpleArrowFunctionExpression( + pos, + expr, + allowReturnTypeInArrowFunction, + hasJSDoc, + /*asyncModifier*/ + void 0 + ); + } + if (isLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); + } + return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); + } + function isYieldExpression() { + if (token() === 127 /* YieldKeyword */) { + if (inYieldContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier2(); + } + function parseYieldExpression() { + const pos = getNodePos(); + nextToken(); + if (!scanner.hasPrecedingLineBreak() && (token() === 42 /* AsteriskToken */ || isStartOfExpression())) { + return finishNode( + factory2.createYieldExpression( + parseOptionalToken(42 /* AsteriskToken */), + parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + ) + ), + pos + ); + } else { + return finishNode(factory2.createYieldExpression( + /*asteriskToken*/ + void 0, + /*expression*/ + void 0 + ), pos); + } + } + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier) { + Debug.assert(token() === 39 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + const parameter = factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + identifier, + /*questionToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ); + finishNode(parameter, identifier.pos); + const parameters = createNodeArray([parameter], parameter.pos, parameter.end); + const equalsGreaterThanToken = parseExpectedToken(39 /* EqualsGreaterThanToken */); + const body = parseArrowFunctionExpressionBody( + /*isAsync*/ + !!asyncModifier, + allowReturnTypeInArrowFunction + ); + const node = factory2.createArrowFunction( + asyncModifier, + /*typeParameters*/ + void 0, + parameters, + /*type*/ + void 0, + equalsGreaterThanToken, + body + ); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { + const triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + return void 0; + } + return triState === 1 /* True */ ? parseParenthesizedArrowFunctionExpression( + /*allowAmbiguity*/ + true, + /*allowReturnTypeInArrowFunction*/ + true + ) : tryParse(() => parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction)); + } + function isParenthesizedArrowFunctionExpression() { + if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 134 /* AsyncKeyword */) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 39 /* EqualsGreaterThanToken */) { + return 1 /* True */; + } + return 0 /* False */; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 134 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0 /* False */; + } + if (token() !== 21 /* OpenParenToken */ && token() !== 30 /* LessThanToken */) { + return 0 /* False */; + } + } + const first2 = token(); + const second = nextToken(); + if (first2 === 21 /* OpenParenToken */) { + if (second === 22 /* CloseParenToken */) { + const third = nextToken(); + switch (third) { + case 39 /* EqualsGreaterThanToken */: + case 59 /* ColonToken */: + case 19 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + if (second === 23 /* OpenBracketToken */ || second === 19 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + if (second === 26 /* DotDotDotToken */) { + return 1 /* True */; + } + if (isModifierKind(second) && second !== 134 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { + if (nextToken() === 130 /* AsKeyword */) { + return 0 /* False */; + } + return 1 /* True */; + } + if (!isIdentifier2() && second !== 110 /* ThisKeyword */) { + return 0 /* False */; + } + switch (nextToken()) { + case 59 /* ColonToken */: + return 1 /* True */; + case 58 /* QuestionToken */: + nextToken(); + if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 64 /* EqualsToken */ || token() === 22 /* CloseParenToken */) { + return 1 /* True */; + } + return 0 /* False */; + case 28 /* CommaToken */: + case 64 /* EqualsToken */: + case 22 /* CloseParenToken */: + return 2 /* Unknown */; + } + return 0 /* False */; + } else { + Debug.assert(first2 === 30 /* LessThanToken */); + if (!isIdentifier2() && token() !== 87 /* ConstKeyword */) { + return 0 /* False */; + } + if (languageVariant === 1 /* JSX */) { + const isArrowFunctionInJsx = lookAhead(() => { + parseOptional(87 /* ConstKeyword */); + const third = nextToken(); + if (third === 96 /* ExtendsKeyword */) { + const fourth = nextToken(); + switch (fourth) { + case 64 /* EqualsToken */: + case 32 /* GreaterThanToken */: + case 44 /* SlashToken */: + return false; + default: + return true; + } + } else if (third === 28 /* CommaToken */ || third === 64 /* EqualsToken */) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1 /* True */; + } + return 0 /* False */; + } + return 2 /* Unknown */; + } + } + function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { + const tokenPos = scanner.getTokenStart(); + if (notParenthesizedArrow == null ? void 0 : notParenthesizedArrow.has(tokenPos)) { + return void 0; + } + const result = parseParenthesizedArrowFunctionExpression( + /*allowAmbiguity*/ + false, + allowReturnTypeInArrowFunction + ); + if (!result) { + (notParenthesizedArrow || (notParenthesizedArrow = /* @__PURE__ */ new Set())).add(tokenPos); + } + return result; + } + function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { + if (token() === 134 /* AsyncKeyword */) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const asyncModifier = parseModifiersForArrowFunction(); + const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier); + } + } + return void 0; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + if (token() === 134 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak() || token() === 39 /* EqualsGreaterThanToken */) { + return 0 /* False */; + } + const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) { + return 1 /* True */; + } + } + return 0 /* False */; + } + function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const modifiers = parseModifiersForArrowFunction(); + const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */; + const typeParameters = parseTypeParameters(); + let parameters; + if (!parseExpected(21 /* OpenParenToken */)) { + if (!allowAmbiguity) { + return void 0; + } + parameters = createMissingList(); + } else { + if (!allowAmbiguity) { + const maybeParameters = parseParametersWorker(isAsync, allowAmbiguity); + if (!maybeParameters) { + return void 0; + } + parameters = maybeParameters; + } else { + parameters = parseParametersWorker(isAsync, allowAmbiguity); + } + if (!parseExpected(22 /* CloseParenToken */) && !allowAmbiguity) { + return void 0; + } + } + const hasReturnColon = token() === 59 /* ColonToken */; + const type = parseReturnType( + 59 /* ColonToken */, + /*isType*/ + false + ); + if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { + return void 0; + } + let unwrappedType = type; + while ((unwrappedType == null ? void 0 : unwrappedType.kind) === 196 /* ParenthesizedType */) { + unwrappedType = unwrappedType.type; + } + const hasJSDocFunctionType = unwrappedType && isJSDocFunctionType(unwrappedType); + if (!allowAmbiguity && token() !== 39 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 19 /* OpenBraceToken */)) { + return void 0; + } + const lastToken = token(); + const equalsGreaterThanToken = parseExpectedToken(39 /* EqualsGreaterThanToken */); + const body = lastToken === 39 /* EqualsGreaterThanToken */ || lastToken === 19 /* OpenBraceToken */ ? parseArrowFunctionExpressionBody(some(modifiers, isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); + if (!allowReturnTypeInArrowFunction && hasReturnColon) { + if (token() !== 59 /* ColonToken */) { + return void 0; + } + } + const node = factory2.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) { + if (token() === 19 /* OpenBraceToken */) { + return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); + } + if (token() !== 27 /* SemicolonToken */ && token() !== 100 /* FunctionKeyword */ && token() !== 86 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { + return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); + } + const savedTopLevel = topLevel; + topLevel = false; + const node = isAsync ? doInAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)) : doOutsideOfAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)); + topLevel = savedTopLevel; + return node; + } + function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) { + const questionToken = parseOptionalToken(58 /* QuestionToken */); + if (!questionToken) { + return leftOperand; + } + let colonToken; + return finishNode( + factory2.createConditionalExpression( + leftOperand, + questionToken, + doOutsideOfContext(disallowInAndDecoratorContext, () => parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + false + )), + colonToken = parseExpectedToken(59 /* ColonToken */), + nodeIsPresent(colonToken) ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + false, + Diagnostics._0_expected, + tokenToString(59 /* ColonToken */) + ) + ), + pos + ); + } + function parseBinaryExpressionOrHigher(precedence) { + const pos = getNodePos(); + const leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand, pos); + } + function isInOrOfKeyword(t) { + return t === 103 /* InKeyword */ || t === 165 /* OfKeyword */; + } + function parseBinaryExpressionRest(precedence, leftOperand, pos) { + while (true) { + reScanGreaterToken(); + const newPrecedence = getBinaryOperatorPrecedence(token()); + const consumeCurrentOperator = token() === 43 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 103 /* InKeyword */ && inDisallowInContext()) { + break; + } + if (token() === 130 /* AsKeyword */ || token() === 152 /* SatisfiesKeyword */) { + if (scanner.hasPrecedingLineBreak()) { + break; + } else { + const keywordKind = token(); + nextToken(); + leftOperand = keywordKind === 152 /* SatisfiesKeyword */ ? makeSatisfiesExpression(leftOperand, parseType()) : makeAsExpression(leftOperand, parseType()); + } + } else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos); + } + } + return leftOperand; + } + function isBinaryOperator2() { + if (inDisallowInContext() && token() === 103 /* InKeyword */) { + return false; + } + return getBinaryOperatorPrecedence(token()) > 0; + } + function makeSatisfiesExpression(left, right) { + return finishNode(factory2.createSatisfiesExpression(left, right), left.pos); + } + function makeBinaryExpression(left, operatorToken, right, pos) { + return finishNode(factory2.createBinaryExpression(left, operatorToken, right), pos); + } + function makeAsExpression(left, right) { + return finishNode(factory2.createAsExpression(left, right), left.pos); + } + function parsePrefixUnaryExpression() { + const pos = getNodePos(); + return finishNode(factory2.createPrefixUnaryExpression(token(), nextTokenAnd(parseSimpleUnaryExpression)), pos); + } + function parseDeleteExpression() { + const pos = getNodePos(); + return finishNode(factory2.createDeleteExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); + } + function parseTypeOfExpression() { + const pos = getNodePos(); + return finishNode(factory2.createTypeOfExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); + } + function parseVoidExpression() { + const pos = getNodePos(); + return finishNode(factory2.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); + } + function isAwaitExpression2() { + if (token() === 135 /* AwaitKeyword */) { + if (inAwaitContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + const pos = getNodePos(); + return finishNode(factory2.createAwaitExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); + } + function parseUnaryExpressionOrHigher() { + if (isUpdateExpression()) { + const pos = getNodePos(); + const updateExpression = parseUpdateExpression(); + return token() === 43 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(token()), updateExpression, pos) : updateExpression; + } + const unaryOperator = token(); + const simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 43 /* AsteriskAsteriskToken */) { + const pos = skipTrivia(sourceText, simpleUnaryExpression.pos); + const { end } = simpleUnaryExpression; + if (simpleUnaryExpression.kind === 216 /* TypeAssertionExpression */) { + parseErrorAt(pos, end, Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } else { + Debug.assert(isKeywordOrPunctuation(unaryOperator)); + parseErrorAt(pos, end, Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + function parseSimpleUnaryExpression() { + switch (token()) { + case 40 /* PlusToken */: + case 41 /* MinusToken */: + case 55 /* TildeToken */: + case 54 /* ExclamationToken */: + return parsePrefixUnaryExpression(); + case 91 /* DeleteKeyword */: + return parseDeleteExpression(); + case 114 /* TypeOfKeyword */: + return parseTypeOfExpression(); + case 116 /* VoidKeyword */: + return parseVoidExpression(); + case 30 /* LessThanToken */: + if (languageVariant === 1 /* JSX */) { + return parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ + true, + /*topInvalidNodePosition*/ + void 0, + /*openingTag*/ + void 0, + /*mustBeUnary*/ + true + ); + } + return parseTypeAssertion(); + case 135 /* AwaitKeyword */: + if (isAwaitExpression2()) { + return parseAwaitExpression(); + } + // falls through + default: + return parseUpdateExpression(); + } + } + function isUpdateExpression() { + switch (token()) { + case 40 /* PlusToken */: + case 41 /* MinusToken */: + case 55 /* TildeToken */: + case 54 /* ExclamationToken */: + case 91 /* DeleteKeyword */: + case 114 /* TypeOfKeyword */: + case 116 /* VoidKeyword */: + case 135 /* AwaitKeyword */: + return false; + case 30 /* LessThanToken */: + if (languageVariant !== 1 /* JSX */) { + return false; + } + // We are in JSX context and the token is part of JSXElement. + // falls through + default: + return true; + } + } + function parseUpdateExpression() { + if (token() === 46 /* PlusPlusToken */ || token() === 47 /* MinusMinusToken */) { + const pos = getNodePos(); + return finishNode(factory2.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos); + } else if (languageVariant === 1 /* JSX */ && token() === 30 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + return parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ + true + ); + } + const expression = parseLeftHandSideExpressionOrHigher(); + Debug.assert(isLeftHandSideExpression(expression)); + if ((token() === 46 /* PlusPlusToken */ || token() === 47 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + const operator = token(); + nextToken(); + return finishNode(factory2.createPostfixUnaryExpression(expression, operator), expression.pos); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + const pos = getNodePos(); + let expression; + if (token() === 102 /* ImportKeyword */) { + if (lookAhead(nextTokenIsOpenParenOrLessThan)) { + sourceFlags |= 4194304 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } else if (lookAhead(nextTokenIsDot)) { + nextToken(); + nextToken(); + expression = finishNode(factory2.createMetaProperty(102 /* ImportKeyword */, parseIdentifierName()), pos); + sourceFlags |= 8388608 /* PossiblyContainsImportMeta */; + } else { + expression = parseMemberExpressionOrHigher(); + } + } else { + expression = token() === 108 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + return parseCallExpressionRest(pos, expression); + } + function parseMemberExpressionOrHigher() { + const pos = getNodePos(); + const expression = parsePrimaryExpression(); + return parseMemberExpressionRest( + pos, + expression, + /*allowOptionalChain*/ + true + ); + } + function parseSuperExpression() { + const pos = getNodePos(); + let expression = parseTokenNode(); + if (token() === 30 /* LessThanToken */) { + const startPos = getNodePos(); + const typeArguments = tryParse(parseTypeArgumentsInExpression); + if (typeArguments !== void 0) { + parseErrorAt(startPos, getNodePos(), Diagnostics.super_may_not_use_type_arguments); + if (!isTemplateStartOfTaggedTemplate()) { + expression = factory2.createExpressionWithTypeArguments(expression, typeArguments); + } + } + } + if (token() === 21 /* OpenParenToken */ || token() === 25 /* DotToken */ || token() === 23 /* OpenBracketToken */) { + return expression; + } + parseExpectedToken(25 /* DotToken */, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + return finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( + /*allowIdentifierNames*/ + true, + /*allowPrivateIdentifiers*/ + true, + /*allowUnicodeEscapeSequenceInIdentifierName*/ + true + )), pos); + } + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition, openingTag, mustBeUnary = false) { + const pos = getNodePos(); + const opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); + let result; + if (opening.kind === 286 /* JsxOpeningElement */) { + let children = parseJsxChildren(opening); + let closingElement; + const lastChild = children[children.length - 1]; + if ((lastChild == null ? void 0 : lastChild.kind) === 284 /* JsxElement */ && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName) && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) { + const end = lastChild.children.end; + const newLast = finishNode( + factory2.createJsxElement( + lastChild.openingElement, + lastChild.children, + finishNode(factory2.createJsxClosingElement(finishNode(factoryCreateIdentifier(""), end, end)), end, end) + ), + lastChild.openingElement.pos, + end + ); + children = createNodeArray([...children.slice(0, children.length - 1), newLast], children.pos, end); + closingElement = lastChild.closingElement; + } else { + closingElement = parseJsxClosingElement(opening, inExpressionContext); + if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { + if (openingTag && isJsxOpeningElement(openingTag) && tagNamesAreEquivalent(closingElement.tagName, openingTag.tagName)) { + parseErrorAtRange(opening.tagName, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, opening.tagName)); + } else { + parseErrorAtRange(closingElement.tagName, Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, getTextOfNodeFromSourceText(sourceText, opening.tagName)); + } + } + } + result = finishNode(factory2.createJsxElement(opening, children, closingElement), pos); + } else if (opening.kind === 289 /* JsxOpeningFragment */) { + result = finishNode(factory2.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); + } else { + Debug.assert(opening.kind === 285 /* JsxSelfClosingElement */); + result = opening; + } + if (!mustBeUnary && inExpressionContext && token() === 30 /* LessThanToken */) { + const topBadPos = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition; + const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ + true, + topBadPos + )); + if (invalidElement) { + const operatorToken = createMissingNode( + 28 /* CommaToken */, + /*reportAtCurrentPosition*/ + false + ); + setTextRangePosWidth(operatorToken, invalidElement.pos, 0); + parseErrorAt(skipTrivia(sourceText, topBadPos), invalidElement.end, Diagnostics.JSX_expressions_must_have_one_parent_element); + return finishNode(factory2.createBinaryExpression(result, operatorToken, invalidElement), pos); + } + } + return result; + } + function parseJsxText() { + const pos = getNodePos(); + const node = factory2.createJsxText(scanner.getTokenValue(), currentToken === 13 /* JsxTextAllWhiteSpaces */); + currentToken = scanner.scanJsxToken(); + return finishNode(node, pos); + } + function parseJsxChild(openingTag, token2) { + switch (token2) { + case 1 /* EndOfFileToken */: + if (isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } else { + const tag = openingTag.tagName; + const start = Math.min(skipTrivia(sourceText, tag.pos), tag.end); + parseErrorAt(start, tag.end, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return void 0; + case 31 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return void 0; + case 12 /* JsxText */: + case 13 /* JsxTextAllWhiteSpaces */: + return parseJsxText(); + case 19 /* OpenBraceToken */: + return parseJsxExpression( + /*inExpressionContext*/ + false + ); + case 30 /* LessThanToken */: + return parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ + false, + /*topInvalidNodePosition*/ + void 0, + openingTag + ); + default: + return Debug.assertNever(token2); + } + } + function parseJsxChildren(openingTag) { + const list = []; + const listPos = getNodePos(); + const saveParsingContext = parsingContext; + parsingContext |= 1 << 14 /* JsxChildren */; + while (true) { + const child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) break; + list.push(child); + if (isJsxOpeningElement(openingTag) && (child == null ? void 0 : child.kind) === 284 /* JsxElement */ && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) { + break; + } + } + parsingContext = saveParsingContext; + return createNodeArray(list, listPos); + } + function parseJsxAttributes() { + const pos = getNodePos(); + return finishNode(factory2.createJsxAttributes(parseList(13 /* JsxAttributes */, parseJsxAttribute)), pos); + } + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) { + const pos = getNodePos(); + parseExpected(30 /* LessThanToken */); + if (token() === 32 /* GreaterThanToken */) { + scanJsxText(); + return finishNode(factory2.createJsxOpeningFragment(), pos); + } + const tagName = parseJsxElementName(); + const typeArguments = (contextFlags & 524288 /* JavaScriptFile */) === 0 ? tryParseTypeArguments() : void 0; + const attributes = parseJsxAttributes(); + let node; + if (token() === 32 /* GreaterThanToken */) { + scanJsxText(); + node = factory2.createJsxOpeningElement(tagName, typeArguments, attributes); + } else { + parseExpected(44 /* SlashToken */); + if (parseExpected( + 32 /* GreaterThanToken */, + /*diagnosticMessage*/ + void 0, + /*shouldAdvance*/ + false + )) { + if (inExpressionContext) { + nextToken(); + } else { + scanJsxText(); + } + } + node = factory2.createJsxSelfClosingElement(tagName, typeArguments, attributes); + } + return finishNode(node, pos); + } + function parseJsxElementName() { + const pos = getNodePos(); + const initialExpression = parseJsxTagName(); + if (isJsxNamespacedName(initialExpression)) { + return initialExpression; + } + let expression = initialExpression; + while (parseOptional(25 /* DotToken */)) { + expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( + /*allowIdentifierNames*/ + true, + /*allowPrivateIdentifiers*/ + false, + /*allowUnicodeEscapeSequenceInIdentifierName*/ + false + )), pos); + } + return expression; + } + function parseJsxTagName() { + const pos = getNodePos(); + scanJsxIdentifier(); + const isThis = token() === 110 /* ThisKeyword */; + const tagName = parseIdentifierNameErrorOnUnicodeEscapeSequence(); + if (parseOptional(59 /* ColonToken */)) { + scanJsxIdentifier(); + return finishNode(factory2.createJsxNamespacedName(tagName, parseIdentifierNameErrorOnUnicodeEscapeSequence()), pos); + } + return isThis ? finishNode(factory2.createToken(110 /* ThisKeyword */), pos) : tagName; + } + function parseJsxExpression(inExpressionContext) { + const pos = getNodePos(); + if (!parseExpected(19 /* OpenBraceToken */)) { + return void 0; + } + let dotDotDotToken; + let expression; + if (token() !== 20 /* CloseBraceToken */) { + if (!inExpressionContext) { + dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */); + } + expression = parseExpression(); + } + if (inExpressionContext) { + parseExpected(20 /* CloseBraceToken */); + } else { + if (parseExpected( + 20 /* CloseBraceToken */, + /*diagnosticMessage*/ + void 0, + /*shouldAdvance*/ + false + )) { + scanJsxText(); + } + } + return finishNode(factory2.createJsxExpression(dotDotDotToken, expression), pos); + } + function parseJsxAttribute() { + if (token() === 19 /* OpenBraceToken */) { + return parseJsxSpreadAttribute(); + } + const pos = getNodePos(); + return finishNode(factory2.createJsxAttribute(parseJsxAttributeName(), parseJsxAttributeValue()), pos); + } + function parseJsxAttributeValue() { + if (token() === 64 /* EqualsToken */) { + if (scanJsxAttributeValue() === 11 /* StringLiteral */) { + return parseLiteralNode(); + } + if (token() === 19 /* OpenBraceToken */) { + return parseJsxExpression( + /*inExpressionContext*/ + true + ); + } + if (token() === 30 /* LessThanToken */) { + return parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ + true + ); + } + parseErrorAtCurrentToken(Diagnostics.or_JSX_element_expected); + } + return void 0; + } + function parseJsxAttributeName() { + const pos = getNodePos(); + scanJsxIdentifier(); + const attrName = parseIdentifierNameErrorOnUnicodeEscapeSequence(); + if (parseOptional(59 /* ColonToken */)) { + scanJsxIdentifier(); + return finishNode(factory2.createJsxNamespacedName(attrName, parseIdentifierNameErrorOnUnicodeEscapeSequence()), pos); + } + return attrName; + } + function parseJsxSpreadAttribute() { + const pos = getNodePos(); + parseExpected(19 /* OpenBraceToken */); + parseExpected(26 /* DotDotDotToken */); + const expression = parseExpression(); + parseExpected(20 /* CloseBraceToken */); + return finishNode(factory2.createJsxSpreadAttribute(expression), pos); + } + function parseJsxClosingElement(open, inExpressionContext) { + const pos = getNodePos(); + parseExpected(31 /* LessThanSlashToken */); + const tagName = parseJsxElementName(); + if (parseExpected( + 32 /* GreaterThanToken */, + /*diagnosticMessage*/ + void 0, + /*shouldAdvance*/ + false + )) { + if (inExpressionContext || !tagNamesAreEquivalent(open.tagName, tagName)) { + nextToken(); + } else { + scanJsxText(); + } + } + return finishNode(factory2.createJsxClosingElement(tagName), pos); + } + function parseJsxClosingFragment(inExpressionContext) { + const pos = getNodePos(); + parseExpected(31 /* LessThanSlashToken */); + if (parseExpected( + 32 /* GreaterThanToken */, + Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment, + /*shouldAdvance*/ + false + )) { + if (inExpressionContext) { + nextToken(); + } else { + scanJsxText(); + } + } + return finishNode(factory2.createJsxJsxClosingFragment(), pos); + } + function parseTypeAssertion() { + Debug.assert(languageVariant !== 1 /* JSX */, "Type assertions should never be parsed in JSX; they should be parsed as comparisons or JSX elements/fragments."); + const pos = getNodePos(); + parseExpected(30 /* LessThanToken */); + const type = parseType(); + parseExpected(32 /* GreaterThanToken */); + const expression = parseSimpleUnaryExpression(); + return finishNode(factory2.createTypeAssertion(type, expression), pos); + } + function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() { + nextToken(); + return tokenIsIdentifierOrKeyword(token()) || token() === 23 /* OpenBracketToken */ || isTemplateStartOfTaggedTemplate(); + } + function isStartOfOptionalPropertyOrElementAccessChain() { + return token() === 29 /* QuestionDotToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate); + } + function tryReparseOptionalChain(node) { + if (node.flags & 64 /* OptionalChain */) { + return true; + } + if (isNonNullExpression(node)) { + let expr = node.expression; + while (isNonNullExpression(expr) && !(expr.flags & 64 /* OptionalChain */)) { + expr = expr.expression; + } + if (expr.flags & 64 /* OptionalChain */) { + while (isNonNullExpression(node)) { + node.flags |= 64 /* OptionalChain */; + node = node.expression; + } + return true; + } + } + return false; + } + function parsePropertyAccessExpressionRest(pos, expression, questionDotToken) { + const name = parseRightSideOfDot( + /*allowIdentifierNames*/ + true, + /*allowPrivateIdentifiers*/ + true, + /*allowUnicodeEscapeSequenceInIdentifierName*/ + true + ); + const isOptionalChain2 = questionDotToken || tryReparseOptionalChain(expression); + const propertyAccess = isOptionalChain2 ? factoryCreatePropertyAccessChain(expression, questionDotToken, name) : factoryCreatePropertyAccessExpression(expression, name); + if (isOptionalChain2 && isPrivateIdentifier(propertyAccess.name)) { + parseErrorAtRange(propertyAccess.name, Diagnostics.An_optional_chain_cannot_contain_private_identifiers); + } + if (isExpressionWithTypeArguments(expression) && expression.typeArguments) { + const pos2 = expression.typeArguments.pos - 1; + const end = skipTrivia(sourceText, expression.typeArguments.end) + 1; + parseErrorAt(pos2, end, Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access); + } + return finishNode(propertyAccess, pos); + } + function parseElementAccessExpressionRest(pos, expression, questionDotToken) { + let argumentExpression; + if (token() === 24 /* CloseBracketToken */) { + argumentExpression = createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + true, + Diagnostics.An_element_access_expression_should_take_an_argument + ); + } else { + const argument = allowInAnd(parseExpression); + if (isStringOrNumericLiteralLike(argument)) { + argument.text = internIdentifier(argument.text); + } + argumentExpression = argument; + } + parseExpected(24 /* CloseBracketToken */); + const indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ? factoryCreateElementAccessChain(expression, questionDotToken, argumentExpression) : factoryCreateElementAccessExpression(expression, argumentExpression); + return finishNode(indexedAccess, pos); + } + function parseMemberExpressionRest(pos, expression, allowOptionalChain) { + while (true) { + let questionDotToken; + let isPropertyAccess = false; + if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) { + questionDotToken = parseExpectedToken(29 /* QuestionDotToken */); + isPropertyAccess = tokenIsIdentifierOrKeyword(token()); + } else { + isPropertyAccess = parseOptional(25 /* DotToken */); + } + if (isPropertyAccess) { + expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken); + continue; + } + if ((questionDotToken || !inDecoratorContext()) && parseOptional(23 /* OpenBracketToken */)) { + expression = parseElementAccessExpressionRest(pos, expression, questionDotToken); + continue; + } + if (isTemplateStartOfTaggedTemplate()) { + expression = !questionDotToken && expression.kind === 233 /* ExpressionWithTypeArguments */ ? parseTaggedTemplateRest(pos, expression.expression, questionDotToken, expression.typeArguments) : parseTaggedTemplateRest( + pos, + expression, + questionDotToken, + /*typeArguments*/ + void 0 + ); + continue; + } + if (!questionDotToken) { + if (token() === 54 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + expression = finishNode(factory2.createNonNullExpression(expression), pos); + continue; + } + const typeArguments = tryParse(parseTypeArgumentsInExpression); + if (typeArguments) { + expression = finishNode(factory2.createExpressionWithTypeArguments(expression, typeArguments), pos); + continue; + } + } + return expression; + } + } + function isTemplateStartOfTaggedTemplate() { + return token() === 15 /* NoSubstitutionTemplateLiteral */ || token() === 16 /* TemplateHead */; + } + function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) { + const tagExpression = factory2.createTaggedTemplateExpression( + tag, + typeArguments, + token() === 15 /* NoSubstitutionTemplateLiteral */ ? (reScanTemplateToken( + /*isTaggedTemplate*/ + true + ), parseLiteralNode()) : parseTemplateExpression( + /*isTaggedTemplate*/ + true + ) + ); + if (questionDotToken || tag.flags & 64 /* OptionalChain */) { + tagExpression.flags |= 64 /* OptionalChain */; + } + tagExpression.questionDotToken = questionDotToken; + return finishNode(tagExpression, pos); + } + function parseCallExpressionRest(pos, expression) { + while (true) { + expression = parseMemberExpressionRest( + pos, + expression, + /*allowOptionalChain*/ + true + ); + let typeArguments; + const questionDotToken = parseOptionalToken(29 /* QuestionDotToken */); + if (questionDotToken) { + typeArguments = tryParse(parseTypeArgumentsInExpression); + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments); + continue; + } + } + if (typeArguments || token() === 21 /* OpenParenToken */) { + if (!questionDotToken && expression.kind === 233 /* ExpressionWithTypeArguments */) { + typeArguments = expression.typeArguments; + expression = expression.expression; + } + const argumentList = parseArgumentList(); + const callExpr = questionDotToken || tryReparseOptionalChain(expression) ? factoryCreateCallChain(expression, questionDotToken, typeArguments, argumentList) : factoryCreateCallExpression(expression, typeArguments, argumentList); + expression = finishNode(callExpr, pos); + continue; + } + if (questionDotToken) { + const name = createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + false, + Diagnostics.Identifier_expected + ); + expression = finishNode(factoryCreatePropertyAccessChain(expression, questionDotToken, name), pos); + } + break; + } + return expression; + } + function parseArgumentList() { + parseExpected(21 /* OpenParenToken */); + const result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(22 /* CloseParenToken */); + return result; + } + function parseTypeArgumentsInExpression() { + if ((contextFlags & 524288 /* JavaScriptFile */) !== 0) { + return void 0; + } + if (reScanLessThanToken() !== 30 /* LessThanToken */) { + return void 0; + } + nextToken(); + const typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); + if (reScanGreaterToken() !== 32 /* GreaterThanToken */) { + return void 0; + } + nextToken(); + return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments : void 0; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + // These tokens can follow a type argument list in a call expression. + case 21 /* OpenParenToken */: + // foo( + case 15 /* NoSubstitutionTemplateLiteral */: + // foo `...` + case 16 /* TemplateHead */: + return true; + // A type argument list followed by `<` never makes sense, and a type argument list followed + // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in + // this context, `+` and `-` are unary operators, not binary operators. + case 30 /* LessThanToken */: + case 32 /* GreaterThanToken */: + case 40 /* PlusToken */: + case 41 /* MinusToken */: + return false; + } + return scanner.hasPrecedingLineBreak() || isBinaryOperator2() || !isStartOfExpression(); + } + function parsePrimaryExpression() { + switch (token()) { + case 15 /* NoSubstitutionTemplateLiteral */: + if (scanner.getTokenFlags() & 26656 /* IsInvalid */) { + reScanTemplateToken( + /*isTaggedTemplate*/ + false + ); + } + // falls through + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 11 /* StringLiteral */: + return parseLiteralNode(); + case 110 /* ThisKeyword */: + case 108 /* SuperKeyword */: + case 106 /* NullKeyword */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + return parseTokenNode(); + case 21 /* OpenParenToken */: + return parseParenthesizedExpression(); + case 23 /* OpenBracketToken */: + return parseArrayLiteralExpression(); + case 19 /* OpenBraceToken */: + return parseObjectLiteralExpression(); + case 134 /* AsyncKeyword */: + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 60 /* AtToken */: + return parseDecoratedExpression(); + case 86 /* ClassKeyword */: + return parseClassExpression(); + case 100 /* FunctionKeyword */: + return parseFunctionExpression(); + case 105 /* NewKeyword */: + return parseNewExpressionOrNewDotTarget(); + case 44 /* SlashToken */: + case 69 /* SlashEqualsToken */: + if (reScanSlashToken() === 14 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + case 16 /* TemplateHead */: + return parseTemplateExpression( + /*isTaggedTemplate*/ + false + ); + case 81 /* PrivateIdentifier */: + return parsePrivateIdentifier(); + } + return parseIdentifier(Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(21 /* OpenParenToken */); + const expression = allowInAnd(parseExpression); + parseExpected(22 /* CloseParenToken */); + return withJSDoc(finishNode(factoryCreateParenthesizedExpression(expression), pos), hasJSDoc); + } + function parseSpreadElement() { + const pos = getNodePos(); + parseExpected(26 /* DotDotDotToken */); + const expression = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + ); + return finishNode(factory2.createSpreadElement(expression), pos); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 26 /* DotDotDotToken */ ? parseSpreadElement() : token() === 28 /* CommaToken */ ? finishNode(factory2.createOmittedExpression(), getNodePos()) : parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + ); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + const pos = getNodePos(); + const openBracketPosition = scanner.getTokenStart(); + const openBracketParsed = parseExpected(23 /* OpenBracketToken */); + const multiLine = scanner.hasPrecedingLineBreak(); + const elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpectedMatchingBrackets(23 /* OpenBracketToken */, 24 /* CloseBracketToken */, openBracketParsed, openBracketPosition); + return finishNode(factoryCreateArrayLiteralExpression(elements, multiLine), pos); + } + function parseObjectLiteralElement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + if (parseOptionalToken(26 /* DotDotDotToken */)) { + const expression = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + ); + return withJSDoc(finishNode(factory2.createSpreadAssignment(expression), pos), hasJSDoc); + } + const modifiers = parseModifiers( + /*allowDecorators*/ + true + ); + if (parseContextualModifier(139 /* GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */, 0 /* None */); + } + if (parseContextualModifier(153 /* SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */, 0 /* None */); + } + const asteriskToken = parseOptionalToken(42 /* AsteriskToken */); + const tokenIsIdentifier = isIdentifier2(); + const name = parsePropertyName(); + const questionToken = parseOptionalToken(58 /* QuestionToken */); + const exclamationToken = parseOptionalToken(54 /* ExclamationToken */); + if (asteriskToken || token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) { + return parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, exclamationToken); + } + let node; + const isShorthandPropertyAssignment2 = tokenIsIdentifier && token() !== 59 /* ColonToken */; + if (isShorthandPropertyAssignment2) { + const equalsToken = parseOptionalToken(64 /* EqualsToken */); + const objectAssignmentInitializer = equalsToken ? allowInAnd(() => parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + )) : void 0; + node = factory2.createShorthandPropertyAssignment(name, objectAssignmentInitializer); + node.equalsToken = equalsToken; + } else { + parseExpected(59 /* ColonToken */); + const initializer = allowInAnd(() => parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + )); + node = factory2.createPropertyAssignment(name, initializer); + } + node.modifiers = modifiers; + node.questionToken = questionToken; + node.exclamationToken = exclamationToken; + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseObjectLiteralExpression() { + const pos = getNodePos(); + const openBracePosition = scanner.getTokenStart(); + const openBraceParsed = parseExpected(19 /* OpenBraceToken */); + const multiLine = scanner.hasPrecedingLineBreak(); + const properties = parseDelimitedList( + 12 /* ObjectLiteralMembers */, + parseObjectLiteralElement, + /*considerSemicolonAsDelimiter*/ + true + ); + parseExpectedMatchingBrackets(19 /* OpenBraceToken */, 20 /* CloseBraceToken */, openBraceParsed, openBracePosition); + return finishNode(factoryCreateObjectLiteralExpression(properties, multiLine), pos); + } + function parseFunctionExpression() { + const savedDecoratorContext = inDecoratorContext(); + setDecoratorContext( + /*val*/ + false + ); + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const modifiers = parseModifiers( + /*allowDecorators*/ + false + ); + parseExpected(100 /* FunctionKeyword */); + const asteriskToken = parseOptionalToken(42 /* AsteriskToken */); + const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */; + const name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) : isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) : isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) : parseOptionalBindingIdentifier(); + const typeParameters = parseTypeParameters(); + const parameters = parseParameters(isGenerator | isAsync); + const type = parseReturnType( + 59 /* ColonToken */, + /*isType*/ + false + ); + const body = parseFunctionBlock(isGenerator | isAsync); + setDecoratorContext(savedDecoratorContext); + const node = factory2.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseOptionalBindingIdentifier() { + return isBindingIdentifier() ? parseBindingIdentifier() : void 0; + } + function parseNewExpressionOrNewDotTarget() { + const pos = getNodePos(); + parseExpected(105 /* NewKeyword */); + if (parseOptional(25 /* DotToken */)) { + const name = parseIdentifierName(); + return finishNode(factory2.createMetaProperty(105 /* NewKeyword */, name), pos); + } + const expressionPos = getNodePos(); + let expression = parseMemberExpressionRest( + expressionPos, + parsePrimaryExpression(), + /*allowOptionalChain*/ + false + ); + let typeArguments; + if (expression.kind === 233 /* ExpressionWithTypeArguments */) { + typeArguments = expression.typeArguments; + expression = expression.expression; + } + if (token() === 29 /* QuestionDotToken */) { + parseErrorAtCurrentToken(Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, getTextOfNodeFromSourceText(sourceText, expression)); + } + const argumentList = token() === 21 /* OpenParenToken */ ? parseArgumentList() : void 0; + return finishNode(factoryCreateNewExpression(expression, typeArguments, argumentList), pos); + } + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const openBracePosition = scanner.getTokenStart(); + const openBraceParsed = parseExpected(19 /* OpenBraceToken */, diagnosticMessage); + if (openBraceParsed || ignoreMissingOpenBrace) { + const multiLine = scanner.hasPrecedingLineBreak(); + const statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpectedMatchingBrackets(19 /* OpenBraceToken */, 20 /* CloseBraceToken */, openBraceParsed, openBracePosition); + const result = withJSDoc(finishNode(factoryCreateBlock(statements, multiLine), pos), hasJSDoc); + if (token() === 64 /* EqualsToken */) { + parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_whole_assignment_in_parentheses); + nextToken(); + } + return result; + } else { + const statements = createMissingList(); + return withJSDoc(finishNode(factoryCreateBlock( + statements, + /*multiLine*/ + void 0 + ), pos), hasJSDoc); + } + } + function parseFunctionBlock(flags, diagnosticMessage) { + const savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + const savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2 /* Await */)); + const savedTopLevel = topLevel; + topLevel = false; + const saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext( + /*val*/ + false + ); + } + const block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext( + /*val*/ + true + ); + } + topLevel = savedTopLevel; + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(27 /* SemicolonToken */); + return withJSDoc(finishNode(factory2.createEmptyStatement(), pos), hasJSDoc); + } + function parseIfStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(101 /* IfKeyword */); + const openParenPosition = scanner.getTokenStart(); + const openParenParsed = parseExpected(21 /* OpenParenToken */); + const expression = allowInAnd(parseExpression); + parseExpectedMatchingBrackets(21 /* OpenParenToken */, 22 /* CloseParenToken */, openParenParsed, openParenPosition); + const thenStatement = parseStatement(); + const elseStatement = parseOptional(93 /* ElseKeyword */) ? parseStatement() : void 0; + return withJSDoc(finishNode(factoryCreateIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); + } + function parseDoStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(92 /* DoKeyword */); + const statement = parseStatement(); + parseExpected(117 /* WhileKeyword */); + const openParenPosition = scanner.getTokenStart(); + const openParenParsed = parseExpected(21 /* OpenParenToken */); + const expression = allowInAnd(parseExpression); + parseExpectedMatchingBrackets(21 /* OpenParenToken */, 22 /* CloseParenToken */, openParenParsed, openParenPosition); + parseOptional(27 /* SemicolonToken */); + return withJSDoc(finishNode(factory2.createDoStatement(statement, expression), pos), hasJSDoc); + } + function parseWhileStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(117 /* WhileKeyword */); + const openParenPosition = scanner.getTokenStart(); + const openParenParsed = parseExpected(21 /* OpenParenToken */); + const expression = allowInAnd(parseExpression); + parseExpectedMatchingBrackets(21 /* OpenParenToken */, 22 /* CloseParenToken */, openParenParsed, openParenPosition); + const statement = parseStatement(); + return withJSDoc(finishNode(factoryCreateWhileStatement(expression, statement), pos), hasJSDoc); + } + function parseForOrForInOrForOfStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(99 /* ForKeyword */); + const awaitToken = parseOptionalToken(135 /* AwaitKeyword */); + parseExpected(21 /* OpenParenToken */); + let initializer; + if (token() !== 27 /* SemicolonToken */) { + if (token() === 115 /* VarKeyword */ || token() === 121 /* LetKeyword */ || token() === 87 /* ConstKeyword */ || token() === 160 /* UsingKeyword */ && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || // this one is meant to allow of + token() === 135 /* AwaitKeyword */ && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine)) { + initializer = parseVariableDeclarationList( + /*inForStatementInitializer*/ + true + ); + } else { + initializer = disallowInAnd(parseExpression); + } + } + let node; + if (awaitToken ? parseExpected(165 /* OfKeyword */) : parseOptional(165 /* OfKeyword */)) { + const expression = allowInAnd(() => parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + )); + parseExpected(22 /* CloseParenToken */); + node = factoryCreateForOfStatement(awaitToken, initializer, expression, parseStatement()); + } else if (parseOptional(103 /* InKeyword */)) { + const expression = allowInAnd(parseExpression); + parseExpected(22 /* CloseParenToken */); + node = factory2.createForInStatement(initializer, expression, parseStatement()); + } else { + parseExpected(27 /* SemicolonToken */); + const condition = token() !== 27 /* SemicolonToken */ && token() !== 22 /* CloseParenToken */ ? allowInAnd(parseExpression) : void 0; + parseExpected(27 /* SemicolonToken */); + const incrementor = token() !== 22 /* CloseParenToken */ ? allowInAnd(parseExpression) : void 0; + parseExpected(22 /* CloseParenToken */); + node = factoryCreateForStatement(initializer, condition, incrementor, parseStatement()); + } + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseBreakOrContinueStatement(kind) { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(kind === 252 /* BreakStatement */ ? 83 /* BreakKeyword */ : 88 /* ContinueKeyword */); + const label = canParseSemicolon() ? void 0 : parseIdentifier(); + parseSemicolon(); + const node = kind === 252 /* BreakStatement */ ? factory2.createBreakStatement(label) : factory2.createContinueStatement(label); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseReturnStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(107 /* ReturnKeyword */); + const expression = canParseSemicolon() ? void 0 : allowInAnd(parseExpression); + parseSemicolon(); + return withJSDoc(finishNode(factory2.createReturnStatement(expression), pos), hasJSDoc); + } + function parseWithStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(118 /* WithKeyword */); + const openParenPosition = scanner.getTokenStart(); + const openParenParsed = parseExpected(21 /* OpenParenToken */); + const expression = allowInAnd(parseExpression); + parseExpectedMatchingBrackets(21 /* OpenParenToken */, 22 /* CloseParenToken */, openParenParsed, openParenPosition); + const statement = doInsideOfContext(67108864 /* InWithStatement */, parseStatement); + return withJSDoc(finishNode(factory2.createWithStatement(expression, statement), pos), hasJSDoc); + } + function parseCaseClause() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(84 /* CaseKeyword */); + const expression = allowInAnd(parseExpression); + parseExpected(59 /* ColonToken */); + const statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return withJSDoc(finishNode(factory2.createCaseClause(expression, statements), pos), hasJSDoc); + } + function parseDefaultClause() { + const pos = getNodePos(); + parseExpected(90 /* DefaultKeyword */); + parseExpected(59 /* ColonToken */); + const statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(factory2.createDefaultClause(statements), pos); + } + function parseCaseOrDefaultClause() { + return token() === 84 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseCaseBlock() { + const pos = getNodePos(); + parseExpected(19 /* OpenBraceToken */); + const clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(20 /* CloseBraceToken */); + return finishNode(factory2.createCaseBlock(clauses), pos); + } + function parseSwitchStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(109 /* SwitchKeyword */); + parseExpected(21 /* OpenParenToken */); + const expression = allowInAnd(parseExpression); + parseExpected(22 /* CloseParenToken */); + const caseBlock = parseCaseBlock(); + return withJSDoc(finishNode(factory2.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); + } + function parseThrowStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(111 /* ThrowKeyword */); + let expression = scanner.hasPrecedingLineBreak() ? void 0 : allowInAnd(parseExpression); + if (expression === void 0) { + identifierCount++; + expression = finishNode(factoryCreateIdentifier(""), getNodePos()); + } + if (!tryParseSemicolon()) { + parseErrorForMissingSemicolonAfter(expression); + } + return withJSDoc(finishNode(factory2.createThrowStatement(expression), pos), hasJSDoc); + } + function parseTryStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(113 /* TryKeyword */); + const tryBlock = parseBlock( + /*ignoreMissingOpenBrace*/ + false + ); + const catchClause = token() === 85 /* CatchKeyword */ ? parseCatchClause() : void 0; + let finallyBlock; + if (!catchClause || token() === 98 /* FinallyKeyword */) { + parseExpected(98 /* FinallyKeyword */, Diagnostics.catch_or_finally_expected); + finallyBlock = parseBlock( + /*ignoreMissingOpenBrace*/ + false + ); + } + return withJSDoc(finishNode(factory2.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); + } + function parseCatchClause() { + const pos = getNodePos(); + parseExpected(85 /* CatchKeyword */); + let variableDeclaration; + if (parseOptional(21 /* OpenParenToken */)) { + variableDeclaration = parseVariableDeclaration(); + parseExpected(22 /* CloseParenToken */); + } else { + variableDeclaration = void 0; + } + const block = parseBlock( + /*ignoreMissingOpenBrace*/ + false + ); + return finishNode(factory2.createCatchClause(variableDeclaration, block), pos); + } + function parseDebuggerStatement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(89 /* DebuggerKeyword */); + parseSemicolon(); + return withJSDoc(finishNode(factory2.createDebuggerStatement(), pos), hasJSDoc); + } + function parseExpressionOrLabeledStatement() { + const pos = getNodePos(); + let hasJSDoc = hasPrecedingJSDocComment(); + let node; + const hasParen = token() === 21 /* OpenParenToken */; + const expression = allowInAnd(parseExpression); + if (isIdentifier(expression) && parseOptional(59 /* ColonToken */)) { + node = factory2.createLabeledStatement(expression, parseStatement()); + } else { + if (!tryParseSemicolon()) { + parseErrorForMissingSemicolonAfter(expression); + } + node = factoryCreateExpressionStatement(expression); + if (hasParen) { + hasJSDoc = false; + } + } + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 86 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 100 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (tokenIsIdentifierOrKeyword(token()) || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */ || token() === 11 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration2() { + while (true) { + switch (token()) { + case 115 /* VarKeyword */: + case 121 /* LetKeyword */: + case 87 /* ConstKeyword */: + case 100 /* FunctionKeyword */: + case 86 /* ClassKeyword */: + case 94 /* EnumKeyword */: + return true; + case 160 /* UsingKeyword */: + return isUsingDeclaration(); + case 135 /* AwaitKeyword */: + return isAwaitUsingDeclaration(); + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 120 /* InterfaceKeyword */: + case 156 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 144 /* ModuleKeyword */: + case 145 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 128 /* AbstractKeyword */: + case 129 /* AccessorKeyword */: + case 134 /* AsyncKeyword */: + case 138 /* DeclareKeyword */: + case 123 /* PrivateKeyword */: + case 124 /* ProtectedKeyword */: + case 125 /* PublicKeyword */: + case 148 /* ReadonlyKeyword */: + const previousToken = token(); + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + if (previousToken === 138 /* DeclareKeyword */ && token() === 156 /* TypeKeyword */) { + return true; + } + continue; + case 162 /* GlobalKeyword */: + nextToken(); + return token() === 19 /* OpenBraceToken */ || token() === 80 /* Identifier */ || token() === 95 /* ExportKeyword */; + case 102 /* ImportKeyword */: + nextToken(); + return token() === 11 /* StringLiteral */ || token() === 42 /* AsteriskToken */ || token() === 19 /* OpenBraceToken */ || tokenIsIdentifierOrKeyword(token()); + case 95 /* ExportKeyword */: + let currentToken2 = nextToken(); + if (currentToken2 === 156 /* TypeKeyword */) { + currentToken2 = lookAhead(nextToken); + } + if (currentToken2 === 64 /* EqualsToken */ || currentToken2 === 42 /* AsteriskToken */ || currentToken2 === 19 /* OpenBraceToken */ || currentToken2 === 90 /* DefaultKeyword */ || currentToken2 === 130 /* AsKeyword */ || currentToken2 === 60 /* AtToken */) { + return true; + } + continue; + case 126 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration2); + } + function isStartOfStatement() { + switch (token()) { + case 60 /* AtToken */: + case 27 /* SemicolonToken */: + case 19 /* OpenBraceToken */: + case 115 /* VarKeyword */: + case 121 /* LetKeyword */: + case 160 /* UsingKeyword */: + case 100 /* FunctionKeyword */: + case 86 /* ClassKeyword */: + case 94 /* EnumKeyword */: + case 101 /* IfKeyword */: + case 92 /* DoKeyword */: + case 117 /* WhileKeyword */: + case 99 /* ForKeyword */: + case 88 /* ContinueKeyword */: + case 83 /* BreakKeyword */: + case 107 /* ReturnKeyword */: + case 118 /* WithKeyword */: + case 109 /* SwitchKeyword */: + case 111 /* ThrowKeyword */: + case 113 /* TryKeyword */: + case 89 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + // falls through + case 85 /* CatchKeyword */: + case 98 /* FinallyKeyword */: + return true; + case 102 /* ImportKeyword */: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + case 87 /* ConstKeyword */: + case 95 /* ExportKeyword */: + return isStartOfDeclaration(); + case 134 /* AsyncKeyword */: + case 138 /* DeclareKeyword */: + case 120 /* InterfaceKeyword */: + case 144 /* ModuleKeyword */: + case 145 /* NamespaceKeyword */: + case 156 /* TypeKeyword */: + case 162 /* GlobalKeyword */: + return true; + case 129 /* AccessorKeyword */: + case 125 /* PublicKeyword */: + case 123 /* PrivateKeyword */: + case 124 /* ProtectedKeyword */: + case 126 /* StaticKeyword */: + case 148 /* ReadonlyKeyword */: + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsBindingIdentifierOrStartOfDestructuring() { + nextToken(); + return isBindingIdentifier() || token() === 19 /* OpenBraceToken */ || token() === 23 /* OpenBracketToken */; + } + function isLetDeclaration() { + return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuring); + } + function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf() { + return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine( + /*disallowOf*/ + true + ); + } + function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf) { + nextToken(); + if (disallowOf && token() === 165 /* OfKeyword */) return false; + return (isBindingIdentifier() || token() === 19 /* OpenBraceToken */) && !scanner.hasPrecedingLineBreak(); + } + function isUsingDeclaration() { + return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine); + } + function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(disallowOf) { + if (nextToken() === 160 /* UsingKeyword */) { + return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf); + } + return false; + } + function isAwaitUsingDeclaration() { + return lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine); + } + function parseStatement() { + switch (token()) { + case 27 /* SemicolonToken */: + return parseEmptyStatement(); + case 19 /* OpenBraceToken */: + return parseBlock( + /*ignoreMissingOpenBrace*/ + false + ); + case 115 /* VarKeyword */: + return parseVariableStatement( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ + void 0 + ); + case 121 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ + void 0 + ); + } + break; + case 135 /* AwaitKeyword */: + if (isAwaitUsingDeclaration()) { + return parseVariableStatement( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ + void 0 + ); + } + break; + case 160 /* UsingKeyword */: + if (isUsingDeclaration()) { + return parseVariableStatement( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ + void 0 + ); + } + break; + case 100 /* FunctionKeyword */: + return parseFunctionDeclaration( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ + void 0 + ); + case 86 /* ClassKeyword */: + return parseClassDeclaration( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ + void 0 + ); + case 101 /* IfKeyword */: + return parseIfStatement(); + case 92 /* DoKeyword */: + return parseDoStatement(); + case 117 /* WhileKeyword */: + return parseWhileStatement(); + case 99 /* ForKeyword */: + return parseForOrForInOrForOfStatement(); + case 88 /* ContinueKeyword */: + return parseBreakOrContinueStatement(251 /* ContinueStatement */); + case 83 /* BreakKeyword */: + return parseBreakOrContinueStatement(252 /* BreakStatement */); + case 107 /* ReturnKeyword */: + return parseReturnStatement(); + case 118 /* WithKeyword */: + return parseWithStatement(); + case 109 /* SwitchKeyword */: + return parseSwitchStatement(); + case 111 /* ThrowKeyword */: + return parseThrowStatement(); + case 113 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + // falls through + case 85 /* CatchKeyword */: + case 98 /* FinallyKeyword */: + return parseTryStatement(); + case 89 /* DebuggerKeyword */: + return parseDebuggerStatement(); + case 60 /* AtToken */: + return parseDeclaration(); + case 134 /* AsyncKeyword */: + case 120 /* InterfaceKeyword */: + case 156 /* TypeKeyword */: + case 144 /* ModuleKeyword */: + case 145 /* NamespaceKeyword */: + case 138 /* DeclareKeyword */: + case 87 /* ConstKeyword */: + case 94 /* EnumKeyword */: + case 95 /* ExportKeyword */: + case 102 /* ImportKeyword */: + case 123 /* PrivateKeyword */: + case 124 /* ProtectedKeyword */: + case 125 /* PublicKeyword */: + case 128 /* AbstractKeyword */: + case 129 /* AccessorKeyword */: + case 126 /* StaticKeyword */: + case 148 /* ReadonlyKeyword */: + case 162 /* GlobalKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function isDeclareModifier(modifier) { + return modifier.kind === 138 /* DeclareKeyword */; + } + function parseDeclaration() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const modifiers = parseModifiers( + /*allowDecorators*/ + true + ); + const isAmbient = some(modifiers, isDeclareModifier); + if (isAmbient) { + const node = tryReuseAmbientDeclaration(pos); + if (node) { + return node; + } + for (const m of modifiers) { + m.flags |= 33554432 /* Ambient */; + } + return doInsideOfContext(33554432 /* Ambient */, () => parseDeclarationWorker(pos, hasJSDoc, modifiers)); + } else { + return parseDeclarationWorker(pos, hasJSDoc, modifiers); + } + } + function tryReuseAmbientDeclaration(pos) { + return doInsideOfContext(33554432 /* Ambient */, () => { + const node = currentNode(parsingContext, pos); + if (node) { + return consumeNode(node); + } + }); + } + function parseDeclarationWorker(pos, hasJSDoc, modifiersIn) { + switch (token()) { + case 115 /* VarKeyword */: + case 121 /* LetKeyword */: + case 87 /* ConstKeyword */: + case 160 /* UsingKeyword */: + case 135 /* AwaitKeyword */: + return parseVariableStatement(pos, hasJSDoc, modifiersIn); + case 100 /* FunctionKeyword */: + return parseFunctionDeclaration(pos, hasJSDoc, modifiersIn); + case 86 /* ClassKeyword */: + return parseClassDeclaration(pos, hasJSDoc, modifiersIn); + case 120 /* InterfaceKeyword */: + return parseInterfaceDeclaration(pos, hasJSDoc, modifiersIn); + case 156 /* TypeKeyword */: + return parseTypeAliasDeclaration(pos, hasJSDoc, modifiersIn); + case 94 /* EnumKeyword */: + return parseEnumDeclaration(pos, hasJSDoc, modifiersIn); + case 162 /* GlobalKeyword */: + case 144 /* ModuleKeyword */: + case 145 /* NamespaceKeyword */: + return parseModuleDeclaration(pos, hasJSDoc, modifiersIn); + case 102 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, modifiersIn); + case 95 /* ExportKeyword */: + nextToken(); + switch (token()) { + case 90 /* DefaultKeyword */: + case 64 /* EqualsToken */: + return parseExportAssignment(pos, hasJSDoc, modifiersIn); + case 130 /* AsKeyword */: + return parseNamespaceExportDeclaration(pos, hasJSDoc, modifiersIn); + default: + return parseExportDeclaration(pos, hasJSDoc, modifiersIn); + } + default: + if (modifiersIn) { + const missing = createMissingNode( + 282 /* MissingDeclaration */, + /*reportAtCurrentPosition*/ + true, + Diagnostics.Declaration_expected + ); + setTextRangePos(missing, pos); + missing.modifiers = modifiersIn; + return missing; + } + return void 0; + } + } + function nextTokenIsStringLiteral() { + return nextToken() === 11 /* StringLiteral */; + } + function nextTokenIsFromKeywordOrEqualsToken() { + nextToken(); + return token() === 161 /* FromKeyword */ || token() === 64 /* EqualsToken */; + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier2() || token() === 11 /* StringLiteral */); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 19 /* OpenBraceToken */) { + if (flags & 4 /* Type */) { + parseTypeMemberSemicolon(); + return; + } + if (canParseSemicolon()) { + parseSemicolon(); + return; + } + } + return parseFunctionBlock(flags, diagnosticMessage); + } + function parseArrayBindingElement() { + const pos = getNodePos(); + if (token() === 28 /* CommaToken */) { + return finishNode(factory2.createOmittedExpression(), pos); + } + const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */); + const name = parseIdentifierOrPattern(); + const initializer = parseInitializer(); + return finishNode(factory2.createBindingElement( + dotDotDotToken, + /*propertyName*/ + void 0, + name, + initializer + ), pos); + } + function parseObjectBindingElement() { + const pos = getNodePos(); + const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */); + const tokenIsIdentifier = isBindingIdentifier(); + let propertyName = parsePropertyName(); + let name; + if (tokenIsIdentifier && token() !== 59 /* ColonToken */) { + name = propertyName; + propertyName = void 0; + } else { + parseExpected(59 /* ColonToken */); + name = parseIdentifierOrPattern(); + } + const initializer = parseInitializer(); + return finishNode(factory2.createBindingElement(dotDotDotToken, propertyName, name, initializer), pos); + } + function parseObjectBindingPattern() { + const pos = getNodePos(); + parseExpected(19 /* OpenBraceToken */); + const elements = allowInAnd(() => parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement)); + parseExpected(20 /* CloseBraceToken */); + return finishNode(factory2.createObjectBindingPattern(elements), pos); + } + function parseArrayBindingPattern() { + const pos = getNodePos(); + parseExpected(23 /* OpenBracketToken */); + const elements = allowInAnd(() => parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement)); + parseExpected(24 /* CloseBracketToken */); + return finishNode(factory2.createArrayBindingPattern(elements), pos); + } + function isBindingIdentifierOrPrivateIdentifierOrPattern() { + return token() === 19 /* OpenBraceToken */ || token() === 23 /* OpenBracketToken */ || token() === 81 /* PrivateIdentifier */ || isBindingIdentifier(); + } + function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) { + if (token() === 23 /* OpenBracketToken */) { + return parseArrayBindingPattern(); + } + if (token() === 19 /* OpenBraceToken */) { + return parseObjectBindingPattern(); + } + return parseBindingIdentifier(privateIdentifierDiagnosticMessage); + } + function parseVariableDeclarationAllowExclamation() { + return parseVariableDeclaration( + /*allowExclamation*/ + true + ); + } + function parseVariableDeclaration(allowExclamation) { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); + let exclamationToken; + if (allowExclamation && name.kind === 80 /* Identifier */ && token() === 54 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + exclamationToken = parseTokenNode(); + } + const type = parseTypeAnnotation(); + const initializer = isInOrOfKeyword(token()) ? void 0 : parseInitializer(); + const node = factoryCreateVariableDeclaration(name, exclamationToken, type, initializer); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseVariableDeclarationList(inForStatementInitializer) { + const pos = getNodePos(); + let flags = 0; + switch (token()) { + case 115 /* VarKeyword */: + break; + case 121 /* LetKeyword */: + flags |= 1 /* Let */; + break; + case 87 /* ConstKeyword */: + flags |= 2 /* Const */; + break; + case 160 /* UsingKeyword */: + flags |= 4 /* Using */; + break; + case 135 /* AwaitKeyword */: + Debug.assert(isAwaitUsingDeclaration()); + flags |= 6 /* AwaitUsing */; + nextToken(); + break; + default: + Debug.fail(); + } + nextToken(); + let declarations; + if (token() === 165 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + declarations = createMissingList(); + } else { + const savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + declarations = parseDelimitedList( + 8 /* VariableDeclarations */, + inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation + ); + setDisallowInContext(savedDisallowIn); + } + return finishNode(factoryCreateVariableDeclarationList(declarations, flags), pos); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 22 /* CloseParenToken */; + } + function parseVariableStatement(pos, hasJSDoc, modifiers) { + const declarationList = parseVariableDeclarationList( + /*inForStatementInitializer*/ + false + ); + parseSemicolon(); + const node = factoryCreateVariableStatement(modifiers, declarationList); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseFunctionDeclaration(pos, hasJSDoc, modifiers) { + const savedAwaitContext = inAwaitContext(); + const modifierFlags = modifiersToFlags(modifiers); + parseExpected(100 /* FunctionKeyword */); + const asteriskToken = parseOptionalToken(42 /* AsteriskToken */); + const name = modifierFlags & 2048 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier(); + const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + const isAsync = modifierFlags & 1024 /* Async */ ? 2 /* Await */ : 0 /* None */; + const typeParameters = parseTypeParameters(); + if (modifierFlags & 32 /* Export */) setAwaitContext( + /*value*/ + true + ); + const parameters = parseParameters(isGenerator | isAsync); + const type = parseReturnType( + 59 /* ColonToken */, + /*isType*/ + false + ); + const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, Diagnostics.or_expected); + setAwaitContext(savedAwaitContext); + const node = factory2.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseConstructorName() { + if (token() === 137 /* ConstructorKeyword */) { + return parseExpected(137 /* ConstructorKeyword */); + } + if (token() === 11 /* StringLiteral */ && lookAhead(nextToken) === 21 /* OpenParenToken */) { + return tryParse(() => { + const literalNode = parseLiteralNode(); + return literalNode.text === "constructor" ? literalNode : void 0; + }); + } + } + function tryParseConstructorDeclaration(pos, hasJSDoc, modifiers) { + return tryParse(() => { + if (parseConstructorName()) { + const typeParameters = parseTypeParameters(); + const parameters = parseParameters(0 /* None */); + const type = parseReturnType( + 59 /* ColonToken */, + /*isType*/ + false + ); + const body = parseFunctionBlockOrSemicolon(0 /* None */, Diagnostics.or_expected); + const node = factory2.createConstructorDeclaration(modifiers, parameters, body); + node.typeParameters = typeParameters; + node.type = type; + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + }); + } + function parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, exclamationToken, diagnosticMessage) { + const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */; + const typeParameters = parseTypeParameters(); + const parameters = parseParameters(isGenerator | isAsync); + const type = parseReturnType( + 59 /* ColonToken */, + /*isType*/ + false + ); + const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + const node = factory2.createMethodDeclaration( + modifiers, + asteriskToken, + name, + questionToken, + typeParameters, + parameters, + type, + body + ); + node.exclamationToken = exclamationToken; + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, questionToken) { + const exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(54 /* ExclamationToken */) : void 0; + const type = parseTypeAnnotation(); + const initializer = doOutsideOfContext(16384 /* YieldContext */ | 65536 /* AwaitContext */ | 8192 /* DisallowInContext */, parseInitializer); + parseSemicolonAfterPropertyName(name, type, initializer); + const node = factory2.createPropertyDeclaration( + modifiers, + name, + questionToken || exclamationToken, + type, + initializer + ); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers) { + const asteriskToken = parseOptionalToken(42 /* AsteriskToken */); + const name = parsePropertyName(); + const questionToken = parseOptionalToken(58 /* QuestionToken */); + if (asteriskToken || token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) { + return parseMethodDeclaration( + pos, + hasJSDoc, + modifiers, + asteriskToken, + name, + questionToken, + /*exclamationToken*/ + void 0, + Diagnostics.or_expected + ); + } + return parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, questionToken); + } + function parseAccessorDeclaration(pos, hasJSDoc, modifiers, kind, flags) { + const name = parsePropertyName(); + const typeParameters = parseTypeParameters(); + const parameters = parseParameters(0 /* None */); + const type = parseReturnType( + 59 /* ColonToken */, + /*isType*/ + false + ); + const body = parseFunctionBlockOrSemicolon(flags); + const node = kind === 177 /* GetAccessor */ ? factory2.createGetAccessorDeclaration(modifiers, name, parameters, type, body) : factory2.createSetAccessorDeclaration(modifiers, name, parameters, body); + node.typeParameters = typeParameters; + if (isSetAccessorDeclaration(node)) node.type = type; + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function isClassMemberStart() { + let idToken; + if (token() === 60 /* AtToken */) { + return true; + } + while (isModifierKind(token())) { + idToken = token(); + if (isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 42 /* AsteriskToken */) { + return true; + } + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + if (token() === 23 /* OpenBracketToken */) { + return true; + } + if (idToken !== void 0) { + if (!isKeyword(idToken) || idToken === 153 /* SetKeyword */ || idToken === 139 /* GetKeyword */) { + return true; + } + switch (token()) { + case 21 /* OpenParenToken */: + // Method declaration + case 30 /* LessThanToken */: + // Generic Method declaration + case 54 /* ExclamationToken */: + // Non-null assertion on property name + case 59 /* ColonToken */: + // Type Annotation for declaration + case 64 /* EqualsToken */: + // Initializer for declaration + case 58 /* QuestionToken */: + return true; + default: + return canParseSemicolon(); + } + } + return false; + } + function parseClassStaticBlockDeclaration(pos, hasJSDoc, modifiers) { + parseExpectedToken(126 /* StaticKeyword */); + const body = parseClassStaticBlockBody(); + const node = withJSDoc(finishNode(factory2.createClassStaticBlockDeclaration(body), pos), hasJSDoc); + node.modifiers = modifiers; + return node; + } + function parseClassStaticBlockBody() { + const savedYieldContext = inYieldContext(); + const savedAwaitContext = inAwaitContext(); + setYieldContext(false); + setAwaitContext(true); + const body = parseBlock( + /*ignoreMissingOpenBrace*/ + false + ); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return body; + } + function parseDecoratorExpression() { + if (inAwaitContext() && token() === 135 /* AwaitKeyword */) { + const pos = getNodePos(); + const awaitExpression = parseIdentifier(Diagnostics.Expression_expected); + nextToken(); + const memberExpression = parseMemberExpressionRest( + pos, + awaitExpression, + /*allowOptionalChain*/ + true + ); + return parseCallExpressionRest(pos, memberExpression); + } + return parseLeftHandSideExpressionOrHigher(); + } + function tryParseDecorator() { + const pos = getNodePos(); + if (!parseOptional(60 /* AtToken */)) { + return void 0; + } + const expression = doInDecoratorContext(parseDecoratorExpression); + return finishNode(factory2.createDecorator(expression), pos); + } + function tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock) { + const pos = getNodePos(); + const kind = token(); + if (token() === 87 /* ConstKeyword */ && permitConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + return void 0; + } + } else if (stopOnStartOfClassStaticBlock && token() === 126 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) { + return void 0; + } else if (hasSeenStaticModifier && token() === 126 /* StaticKeyword */) { + return void 0; + } else { + if (!parseAnyContextualModifier()) { + return void 0; + } + } + return finishNode(factoryCreateToken(kind), pos); + } + function parseModifiers(allowDecorators, permitConstAsModifier, stopOnStartOfClassStaticBlock) { + const pos = getNodePos(); + let list; + let decorator, modifier, hasSeenStaticModifier = false, hasLeadingModifier = false, hasTrailingDecorator = false; + if (allowDecorators && token() === 60 /* AtToken */) { + while (decorator = tryParseDecorator()) { + list = append(list, decorator); + } + } + while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) { + if (modifier.kind === 126 /* StaticKeyword */) hasSeenStaticModifier = true; + list = append(list, modifier); + hasLeadingModifier = true; + } + if (hasLeadingModifier && allowDecorators && token() === 60 /* AtToken */) { + while (decorator = tryParseDecorator()) { + list = append(list, decorator); + hasTrailingDecorator = true; + } + } + if (hasTrailingDecorator) { + while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) { + if (modifier.kind === 126 /* StaticKeyword */) hasSeenStaticModifier = true; + list = append(list, modifier); + } + } + return list && createNodeArray(list, pos); + } + function parseModifiersForArrowFunction() { + let modifiers; + if (token() === 134 /* AsyncKeyword */) { + const pos = getNodePos(); + nextToken(); + const modifier = finishNode(factoryCreateToken(134 /* AsyncKeyword */), pos); + modifiers = createNodeArray([modifier], pos); + } + return modifiers; + } + function parseClassElement() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + if (token() === 27 /* SemicolonToken */) { + nextToken(); + return withJSDoc(finishNode(factory2.createSemicolonClassElement(), pos), hasJSDoc); + } + const modifiers = parseModifiers( + /*allowDecorators*/ + true, + /*permitConstAsModifier*/ + true, + /*stopOnStartOfClassStaticBlock*/ + true + ); + if (token() === 126 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) { + return parseClassStaticBlockDeclaration(pos, hasJSDoc, modifiers); + } + if (parseContextualModifier(139 /* GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */, 0 /* None */); + } + if (parseContextualModifier(153 /* SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */, 0 /* None */); + } + if (token() === 137 /* ConstructorKeyword */ || token() === 11 /* StringLiteral */) { + const constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, modifiers); + if (constructorDeclaration) { + return constructorDeclaration; + } + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers); + } + if (tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */ || token() === 42 /* AsteriskToken */ || token() === 23 /* OpenBracketToken */) { + const isAmbient = some(modifiers, isDeclareModifier); + if (isAmbient) { + for (const m of modifiers) { + m.flags |= 33554432 /* Ambient */; + } + return doInsideOfContext(33554432 /* Ambient */, () => parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers)); + } else { + return parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers); + } + } + if (modifiers) { + const name = createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + true, + Diagnostics.Declaration_expected + ); + return parsePropertyDeclaration( + pos, + hasJSDoc, + modifiers, + name, + /*questionToken*/ + void 0 + ); + } + return Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseDecoratedExpression() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const modifiers = parseModifiers( + /*allowDecorators*/ + true + ); + if (token() === 86 /* ClassKeyword */) { + return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 231 /* ClassExpression */); + } + const missing = createMissingNode( + 282 /* MissingDeclaration */, + /*reportAtCurrentPosition*/ + true, + Diagnostics.Expression_expected + ); + setTextRangePos(missing, pos); + missing.modifiers = modifiers; + return missing; + } + function parseClassExpression() { + return parseClassDeclarationOrExpression( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ + void 0, + 231 /* ClassExpression */ + ); + } + function parseClassDeclaration(pos, hasJSDoc, modifiers) { + return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 263 /* ClassDeclaration */); + } + function parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, kind) { + const savedAwaitContext = inAwaitContext(); + parseExpected(86 /* ClassKeyword */); + const name = parseNameOfClassDeclarationOrExpression(); + const typeParameters = parseTypeParameters(); + if (some(modifiers, isExportModifier)) setAwaitContext( + /*value*/ + true + ); + const heritageClauses = parseHeritageClauses(); + let members; + if (parseExpected(19 /* OpenBraceToken */)) { + members = parseClassMembers(); + parseExpected(20 /* CloseBraceToken */); + } else { + members = createMissingList(); + } + setAwaitContext(savedAwaitContext); + const node = kind === 263 /* ClassDeclaration */ ? factory2.createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) : factory2.createClassExpression(modifiers, name, typeParameters, heritageClauses, members); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseNameOfClassDeclarationOrExpression() { + return isBindingIdentifier() && !isImplementsClause() ? createIdentifier(isBindingIdentifier()) : void 0; + } + function isImplementsClause() { + return token() === 119 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + if (isHeritageClause2()) { + return parseList(22 /* HeritageClauses */, parseHeritageClause); + } + return void 0; + } + function parseHeritageClause() { + const pos = getNodePos(); + const tok = token(); + Debug.assert(tok === 96 /* ExtendsKeyword */ || tok === 119 /* ImplementsKeyword */); + nextToken(); + const types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(factory2.createHeritageClause(tok, types), pos); + } + function parseExpressionWithTypeArguments() { + const pos = getNodePos(); + const expression = parseLeftHandSideExpressionOrHigher(); + if (expression.kind === 233 /* ExpressionWithTypeArguments */) { + return expression; + } + const typeArguments = tryParseTypeArguments(); + return finishNode(factory2.createExpressionWithTypeArguments(expression, typeArguments), pos); + } + function tryParseTypeArguments() { + return token() === 30 /* LessThanToken */ ? parseBracketedList(20 /* TypeArguments */, parseType, 30 /* LessThanToken */, 32 /* GreaterThanToken */) : void 0; + } + function isHeritageClause2() { + return token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */; + } + function parseClassMembers() { + return parseList(5 /* ClassMembers */, parseClassElement); + } + function parseInterfaceDeclaration(pos, hasJSDoc, modifiers) { + parseExpected(120 /* InterfaceKeyword */); + const name = parseIdentifier(); + const typeParameters = parseTypeParameters(); + const heritageClauses = parseHeritageClauses(); + const members = parseObjectTypeMembers(); + const node = factory2.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseTypeAliasDeclaration(pos, hasJSDoc, modifiers) { + parseExpected(156 /* TypeKeyword */); + if (scanner.hasPrecedingLineBreak()) { + parseErrorAtCurrentToken(Diagnostics.Line_break_not_permitted_here); + } + const name = parseIdentifier(); + const typeParameters = parseTypeParameters(); + parseExpected(64 /* EqualsToken */); + const type = token() === 141 /* IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); + parseSemicolon(); + const node = factory2.createTypeAliasDeclaration(modifiers, name, typeParameters, type); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseEnumMember() { + const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); + const name = parsePropertyName(); + const initializer = allowInAnd(parseInitializer); + return withJSDoc(finishNode(factory2.createEnumMember(name, initializer), pos), hasJSDoc); + } + function parseEnumDeclaration(pos, hasJSDoc, modifiers) { + parseExpected(94 /* EnumKeyword */); + const name = parseIdentifier(); + let members; + if (parseExpected(19 /* OpenBraceToken */)) { + members = doOutsideOfYieldAndAwaitContext(() => parseDelimitedList(6 /* EnumMembers */, parseEnumMember)); + parseExpected(20 /* CloseBraceToken */); + } else { + members = createMissingList(); + } + const node = factory2.createEnumDeclaration(modifiers, name, members); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseModuleBlock() { + const pos = getNodePos(); + let statements; + if (parseExpected(19 /* OpenBraceToken */)) { + statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(20 /* CloseBraceToken */); + } else { + statements = createMissingList(); + } + return finishNode(factory2.createModuleBlock(statements), pos); + } + function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, modifiers, flags) { + const namespaceFlag = flags & 32 /* Namespace */; + const name = flags & 8 /* NestedNamespace */ ? parseIdentifierName() : parseIdentifier(); + const body = parseOptional(25 /* DotToken */) ? parseModuleOrNamespaceDeclaration( + getNodePos(), + /*hasJSDoc*/ + false, + /*modifiers*/ + void 0, + 8 /* NestedNamespace */ | namespaceFlag + ) : parseModuleBlock(); + const node = factory2.createModuleDeclaration(modifiers, name, body, flags); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn) { + let flags = 0; + let name; + if (token() === 162 /* GlobalKeyword */) { + name = parseIdentifier(); + flags |= 2048 /* GlobalAugmentation */; + } else { + name = parseLiteralNode(); + name.text = internIdentifier(name.text); + } + let body; + if (token() === 19 /* OpenBraceToken */) { + body = parseModuleBlock(); + } else { + parseSemicolon(); + } + const node = factory2.createModuleDeclaration(modifiersIn, name, body, flags); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseModuleDeclaration(pos, hasJSDoc, modifiersIn) { + let flags = 0; + if (token() === 162 /* GlobalKeyword */) { + return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn); + } else if (parseOptional(145 /* NamespaceKeyword */)) { + flags |= 32 /* Namespace */; + } else { + parseExpected(144 /* ModuleKeyword */); + if (token() === 11 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn); + } + } + return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, modifiersIn, flags); + } + function isExternalModuleReference2() { + return token() === 149 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 21 /* OpenParenToken */; + } + function nextTokenIsOpenBrace() { + return nextToken() === 19 /* OpenBraceToken */; + } + function nextTokenIsSlash() { + return nextToken() === 44 /* SlashToken */; + } + function parseNamespaceExportDeclaration(pos, hasJSDoc, modifiers) { + parseExpected(130 /* AsKeyword */); + parseExpected(145 /* NamespaceKeyword */); + const name = parseIdentifier(); + parseSemicolon(); + const node = factory2.createNamespaceExportDeclaration(name); + node.modifiers = modifiers; + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, modifiers) { + parseExpected(102 /* ImportKeyword */); + const afterImportPos = scanner.getTokenFullStart(); + let identifier; + if (isIdentifier2()) { + identifier = parseIdentifier(); + } + let isTypeOnly = false; + if ((identifier == null ? void 0 : identifier.escapedText) === "type" && (token() !== 161 /* FromKeyword */ || isIdentifier2() && lookAhead(nextTokenIsFromKeywordOrEqualsToken)) && (isIdentifier2() || tokenAfterImportDefinitelyProducesImportDeclaration())) { + isTypeOnly = true; + identifier = isIdentifier2() ? parseIdentifier() : void 0; + } + if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) { + return parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly); + } + const importClause = tryParseImportClause(identifier, afterImportPos, isTypeOnly); + const moduleSpecifier = parseModuleSpecifier(); + const attributes = tryParseImportAttributes(); + parseSemicolon(); + const node = factory2.createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function tryParseImportClause(identifier, pos, isTypeOnly, skipJsDocLeadingAsterisks = false) { + let importClause; + if (identifier || // import id + token() === 42 /* AsteriskToken */ || // import * + token() === 19 /* OpenBraceToken */) { + importClause = parseImportClause(identifier, pos, isTypeOnly, skipJsDocLeadingAsterisks); + parseExpected(161 /* FromKeyword */); + } + return importClause; + } + function tryParseImportAttributes() { + const currentToken2 = token(); + if ((currentToken2 === 118 /* WithKeyword */ || currentToken2 === 132 /* AssertKeyword */) && !scanner.hasPrecedingLineBreak()) { + return parseImportAttributes(currentToken2); + } + } + function parseImportAttribute() { + const pos = getNodePos(); + const name = tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(11 /* StringLiteral */); + parseExpected(59 /* ColonToken */); + const value = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + ); + return finishNode(factory2.createImportAttribute(name, value), pos); + } + function parseImportAttributes(token2, skipKeyword) { + const pos = getNodePos(); + if (!skipKeyword) { + parseExpected(token2); + } + const openBracePosition = scanner.getTokenStart(); + if (parseExpected(19 /* OpenBraceToken */)) { + const multiLine = scanner.hasPrecedingLineBreak(); + const elements = parseDelimitedList( + 24 /* ImportAttributes */, + parseImportAttribute, + /*considerSemicolonAsDelimiter*/ + true + ); + if (!parseExpected(20 /* CloseBraceToken */)) { + const lastError = lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === Diagnostics._0_expected.code) { + addRelatedInfo( + lastError, + createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") + ); + } + } + return finishNode(factory2.createImportAttributes(elements, multiLine, token2), pos); + } else { + const elements = createNodeArray( + [], + getNodePos(), + /*end*/ + void 0, + /*hasTrailingComma*/ + false + ); + return finishNode(factory2.createImportAttributes( + elements, + /*multiLine*/ + false, + token2 + ), pos); + } + } + function tokenAfterImportDefinitelyProducesImportDeclaration() { + return token() === 42 /* AsteriskToken */ || token() === 19 /* OpenBraceToken */; + } + function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() { + return token() === 28 /* CommaToken */ || token() === 161 /* FromKeyword */; + } + function parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly) { + parseExpected(64 /* EqualsToken */); + const moduleReference = parseModuleReference(); + parseSemicolon(); + const node = factory2.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); + const finished = withJSDoc(finishNode(node, pos), hasJSDoc); + return finished; + } + function parseImportClause(identifier, pos, isTypeOnly, skipJsDocLeadingAsterisks) { + let namedBindings; + if (!identifier || parseOptional(28 /* CommaToken */)) { + if (skipJsDocLeadingAsterisks) scanner.setSkipJsDocLeadingAsterisks(true); + namedBindings = token() === 42 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(275 /* NamedImports */); + if (skipJsDocLeadingAsterisks) scanner.setSkipJsDocLeadingAsterisks(false); + } + return finishNode(factory2.createImportClause(isTypeOnly, identifier, namedBindings), pos); + } + function parseModuleReference() { + return isExternalModuleReference2() ? parseExternalModuleReference() : parseEntityName( + /*allowReservedWords*/ + false + ); + } + function parseExternalModuleReference() { + const pos = getNodePos(); + parseExpected(149 /* RequireKeyword */); + parseExpected(21 /* OpenParenToken */); + const expression = parseModuleSpecifier(); + parseExpected(22 /* CloseParenToken */); + return finishNode(factory2.createExternalModuleReference(expression), pos); + } + function parseModuleSpecifier() { + if (token() === 11 /* StringLiteral */) { + const result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } else { + return parseExpression(); + } + } + function parseNamespaceImport() { + const pos = getNodePos(); + parseExpected(42 /* AsteriskToken */); + parseExpected(130 /* AsKeyword */); + const name = parseIdentifier(); + return finishNode(factory2.createNamespaceImport(name), pos); + } + function canParseModuleExportName() { + return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */; + } + function parseModuleExportName(parseName) { + return token() === 11 /* StringLiteral */ ? parseLiteralNode() : parseName(); + } + function parseNamedImportsOrExports(kind) { + const pos = getNodePos(); + const node = kind === 275 /* NamedImports */ ? factory2.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 19 /* OpenBraceToken */, 20 /* CloseBraceToken */)) : factory2.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 19 /* OpenBraceToken */, 20 /* CloseBraceToken */)); + return finishNode(node, pos); + } + function parseExportSpecifier() { + const hasJSDoc = hasPrecedingJSDocComment(); + return withJSDoc(parseImportOrExportSpecifier(281 /* ExportSpecifier */), hasJSDoc); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(276 /* ImportSpecifier */); + } + function parseImportOrExportSpecifier(kind) { + const pos = getNodePos(); + let checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier2(); + let checkIdentifierStart = scanner.getTokenStart(); + let checkIdentifierEnd = scanner.getTokenEnd(); + let isTypeOnly = false; + let propertyName; + let canParseAsKeyword = true; + let name = parseModuleExportName(parseIdentifierName); + if (name.kind === 80 /* Identifier */ && name.escapedText === "type") { + if (token() === 130 /* AsKeyword */) { + const firstAs = parseIdentifierName(); + if (token() === 130 /* AsKeyword */) { + const secondAs = parseIdentifierName(); + if (canParseModuleExportName()) { + isTypeOnly = true; + propertyName = firstAs; + name = parseModuleExportName(parseNameWithKeywordCheck); + canParseAsKeyword = false; + } else { + propertyName = name; + name = secondAs; + canParseAsKeyword = false; + } + } else if (canParseModuleExportName()) { + propertyName = name; + canParseAsKeyword = false; + name = parseModuleExportName(parseNameWithKeywordCheck); + } else { + isTypeOnly = true; + name = firstAs; + } + } else if (canParseModuleExportName()) { + isTypeOnly = true; + name = parseModuleExportName(parseNameWithKeywordCheck); + } + } + if (canParseAsKeyword && token() === 130 /* AsKeyword */) { + propertyName = name; + parseExpected(130 /* AsKeyword */); + name = parseModuleExportName(parseNameWithKeywordCheck); + } + if (kind === 276 /* ImportSpecifier */) { + if (name.kind !== 80 /* Identifier */) { + parseErrorAt(skipTrivia(sourceText, name.pos), name.end, Diagnostics.Identifier_expected); + name = setTextRangePosEnd(createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + false + ), name.pos, name.pos); + } else if (checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected); + } + } + const node = kind === 276 /* ImportSpecifier */ ? factory2.createImportSpecifier(isTypeOnly, propertyName, name) : factory2.createExportSpecifier(isTypeOnly, propertyName, name); + return finishNode(node, pos); + function parseNameWithKeywordCheck() { + checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier2(); + checkIdentifierStart = scanner.getTokenStart(); + checkIdentifierEnd = scanner.getTokenEnd(); + return parseIdentifierName(); + } + } + function parseNamespaceExport(pos) { + return finishNode(factory2.createNamespaceExport(parseModuleExportName(parseIdentifierName)), pos); + } + function parseExportDeclaration(pos, hasJSDoc, modifiers) { + const savedAwaitContext = inAwaitContext(); + setAwaitContext( + /*value*/ + true + ); + let exportClause; + let moduleSpecifier; + let attributes; + const isTypeOnly = parseOptional(156 /* TypeKeyword */); + const namespaceExportPos = getNodePos(); + if (parseOptional(42 /* AsteriskToken */)) { + if (parseOptional(130 /* AsKeyword */)) { + exportClause = parseNamespaceExport(namespaceExportPos); + } + parseExpected(161 /* FromKeyword */); + moduleSpecifier = parseModuleSpecifier(); + } else { + exportClause = parseNamedImportsOrExports(279 /* NamedExports */); + if (token() === 161 /* FromKeyword */ || token() === 11 /* StringLiteral */ && !scanner.hasPrecedingLineBreak()) { + parseExpected(161 /* FromKeyword */); + moduleSpecifier = parseModuleSpecifier(); + } + } + const currentToken2 = token(); + if (moduleSpecifier && (currentToken2 === 118 /* WithKeyword */ || currentToken2 === 132 /* AssertKeyword */) && !scanner.hasPrecedingLineBreak()) { + attributes = parseImportAttributes(currentToken2); + } + parseSemicolon(); + setAwaitContext(savedAwaitContext); + const node = factory2.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + function parseExportAssignment(pos, hasJSDoc, modifiers) { + const savedAwaitContext = inAwaitContext(); + setAwaitContext( + /*value*/ + true + ); + let isExportEquals; + if (parseOptional(64 /* EqualsToken */)) { + isExportEquals = true; + } else { + parseExpected(90 /* DefaultKeyword */); + } + const expression = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ + true + ); + parseSemicolon(); + setAwaitContext(savedAwaitContext); + const node = factory2.createExportAssignment(modifiers, isExportEquals, expression); + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + let ParsingContext; + ((ParsingContext2) => { + ParsingContext2[ParsingContext2["SourceElements"] = 0] = "SourceElements"; + ParsingContext2[ParsingContext2["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext2[ParsingContext2["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext2[ParsingContext2["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext2[ParsingContext2["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext2[ParsingContext2["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext2[ParsingContext2["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext2[ParsingContext2["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext2[ParsingContext2["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext2[ParsingContext2["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext2[ParsingContext2["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext2[ParsingContext2["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext2[ParsingContext2["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext2[ParsingContext2["JsxAttributes"] = 13] = "JsxAttributes"; + ParsingContext2[ParsingContext2["JsxChildren"] = 14] = "JsxChildren"; + ParsingContext2[ParsingContext2["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; + ParsingContext2[ParsingContext2["Parameters"] = 16] = "Parameters"; + ParsingContext2[ParsingContext2["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext2[ParsingContext2["RestProperties"] = 18] = "RestProperties"; + ParsingContext2[ParsingContext2["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext2[ParsingContext2["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext2[ParsingContext2["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext2[ParsingContext2["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext2[ParsingContext2["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext2[ParsingContext2["ImportAttributes"] = 24] = "ImportAttributes"; + ParsingContext2[ParsingContext2["JSDocComment"] = 25] = "JSDocComment"; + ParsingContext2[ParsingContext2["Count"] = 26] = "Count"; + })(ParsingContext || (ParsingContext = {})); + let Tristate; + ((Tristate2) => { + Tristate2[Tristate2["False"] = 0] = "False"; + Tristate2[Tristate2["True"] = 1] = "True"; + Tristate2[Tristate2["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); + let JSDocParser; + ((JSDocParser2) => { + function parseJSDocTypeExpressionForTests(content, start, length2) { + initializeState( + "file.js", + content, + 99 /* Latest */, + /*syntaxCursor*/ + void 0, + 1 /* JS */, + 0 /* ParseAll */ + ); + scanner.setText(content, start, length2); + currentToken = scanner.scan(); + const jsDocTypeExpression = parseJSDocTypeExpression(); + const sourceFile = createSourceFile2( + "file.js", + 99 /* Latest */, + 1 /* JS */, + /*isDeclarationFile*/ + false, + [], + factoryCreateToken(1 /* EndOfFileToken */), + 0 /* None */, + noop + ); + const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); + if (jsDocDiagnostics) { + sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile); + } + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression, diagnostics } : void 0; + } + JSDocParser2.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + function parseJSDocTypeExpression(mayOmitBraces) { + const pos = getNodePos(); + const hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(19 /* OpenBraceToken */); + const type = doInsideOfContext(16777216 /* JSDoc */, parseJSDocType); + if (!mayOmitBraces || hasBrace) { + parseExpectedJSDoc(20 /* CloseBraceToken */); + } + const result = factory2.createJSDocTypeExpression(type); + fixupParentReferences(result); + return finishNode(result, pos); + } + JSDocParser2.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseJSDocNameReference() { + const pos = getNodePos(); + const hasBrace = parseOptional(19 /* OpenBraceToken */); + const p2 = getNodePos(); + let entityName = parseEntityName( + /*allowReservedWords*/ + false + ); + while (token() === 81 /* PrivateIdentifier */) { + reScanHashToken(); + nextTokenJSDoc(); + entityName = finishNode(factory2.createJSDocMemberName(entityName, parseIdentifier()), p2); + } + if (hasBrace) { + parseExpectedJSDoc(20 /* CloseBraceToken */); + } + const result = factory2.createJSDocNameReference(entityName); + fixupParentReferences(result); + return finishNode(result, pos); + } + JSDocParser2.parseJSDocNameReference = parseJSDocNameReference; + function parseIsolatedJSDocComment(content, start, length2) { + initializeState( + "", + content, + 99 /* Latest */, + /*syntaxCursor*/ + void 0, + 1 /* JS */, + 0 /* ParseAll */ + ); + const jsDoc = doInsideOfContext(16777216 /* JSDoc */, () => parseJSDocCommentWorker(start, length2)); + const sourceFile = { languageVariant: 0 /* Standard */, text: content }; + const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); + clearState(); + return jsDoc ? { jsDoc, diagnostics } : void 0; + } + JSDocParser2.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length2) { + const saveToken = currentToken; + const saveParseDiagnosticsLength = parseDiagnostics.length; + const saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + const comment = doInsideOfContext(16777216 /* JSDoc */, () => parseJSDocCommentWorker(start, length2)); + setParent(comment, parent); + if (contextFlags & 524288 /* JavaScriptFile */) { + if (!jsDocDiagnostics) { + jsDocDiagnostics = []; + } + addRange(jsDocDiagnostics, parseDiagnostics, saveParseDiagnosticsLength); + } + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + return comment; + } + JSDocParser2.parseJSDocComment = parseJSDocComment; + let JSDocState; + ((JSDocState2) => { + JSDocState2[JSDocState2["BeginningOfLine"] = 0] = "BeginningOfLine"; + JSDocState2[JSDocState2["SawAsterisk"] = 1] = "SawAsterisk"; + JSDocState2[JSDocState2["SavingComments"] = 2] = "SavingComments"; + JSDocState2[JSDocState2["SavingBackticks"] = 3] = "SavingBackticks"; + })(JSDocState || (JSDocState = {})); + let PropertyLikeParse; + ((PropertyLikeParse2) => { + PropertyLikeParse2[PropertyLikeParse2["Property"] = 1] = "Property"; + PropertyLikeParse2[PropertyLikeParse2["Parameter"] = 2] = "Parameter"; + PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter"; + })(PropertyLikeParse || (PropertyLikeParse = {})); + function parseJSDocCommentWorker(start = 0, length2) { + const content = sourceText; + const end = length2 === void 0 ? content.length : start + length2; + length2 = end - start; + Debug.assert(start >= 0); + Debug.assert(start <= end); + Debug.assert(end <= content.length); + if (!isJSDocLikeText(content, start)) { + return void 0; + } + let tags; + let tagsPos; + let tagsEnd; + let linkEnd; + let commentsPos; + let comments = []; + const parts = []; + const saveParsingContext = parsingContext; + parsingContext |= 1 << 25 /* JSDocComment */; + const result = scanner.scanRange(start + 3, length2 - 5, doJSDocScan); + parsingContext = saveParsingContext; + return result; + function doJSDocScan() { + let state = 1 /* SawAsterisk */; + let margin; + let indent2 = start - (content.lastIndexOf("\n", start) + 1) + 4; + function pushComment(text) { + if (!margin) { + margin = indent2; + } + comments.push(text); + indent2 += text.length; + } + nextTokenJSDoc(); + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) ; + if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { + state = 0 /* BeginningOfLine */; + indent2 = 0; + } + loop: + while (true) { + switch (token()) { + case 60 /* AtToken */: + removeTrailingWhitespace(comments); + if (!commentsPos) commentsPos = getNodePos(); + addTag(parseTag(indent2)); + state = 0 /* BeginningOfLine */; + margin = void 0; + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent2 = 0; + break; + case 42 /* AsteriskToken */: + const asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */) { + state = 2 /* SavingComments */; + pushComment(asterisk); + } else { + Debug.assert(state === 0 /* BeginningOfLine */); + state = 1 /* SawAsterisk */; + indent2 += asterisk.length; + } + break; + case 5 /* WhitespaceTrivia */: + Debug.assert(state !== 2 /* SavingComments */, "whitespace shouldn't come from the scanner while saving top-level comment text"); + const whitespace = scanner.getTokenText(); + if (margin !== void 0 && indent2 + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent2)); + } + indent2 += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break loop; + case 82 /* JSDocCommentTextToken */: + state = 2 /* SavingComments */; + pushComment(scanner.getTokenValue()); + break; + case 19 /* OpenBraceToken */: + state = 2 /* SavingComments */; + const commentEnd = scanner.getTokenFullStart(); + const linkStart = scanner.getTokenEnd() - 1; + const link = parseJSDocLink(linkStart); + if (link) { + if (!linkEnd) { + removeLeadingNewlines(comments); + } + parts.push(finishNode(factory2.createJSDocText(comments.join("")), linkEnd ?? start, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTokenEnd(); + break; + } + // fallthrough if it's not a {@link sequence + default: + state = 2 /* SavingComments */; + pushComment(scanner.getTokenText()); + break; + } + if (state === 2 /* SavingComments */) { + nextJSDocCommentTextToken( + /*inBackticks*/ + false + ); + } else { + nextTokenJSDoc(); + } + } + const trimmedComments = comments.join("").trimEnd(); + if (parts.length && trimmedComments.length) { + parts.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd ?? start, commentsPos)); + } + if (parts.length && tags) Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); + return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start, end); + } + function removeLeadingNewlines(comments2) { + while (comments2.length && (comments2[0] === "\n" || comments2[0] === "\r")) { + comments2.shift(); + } + } + function removeTrailingWhitespace(comments2) { + while (comments2.length) { + const trimmed = comments2[comments2.length - 1].trimEnd(); + if (trimmed === "") { + comments2.pop(); + } else if (trimmed.length < comments2[comments2.length - 1].length) { + comments2[comments2.length - 1] = trimmed; + break; + } else { + break; + } + } + } + function isNextNonwhitespaceTokenEndOfFile() { + while (true) { + nextTokenJSDoc(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } + function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; + } + } + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + nextTokenJSDoc(); + } + } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return ""; + } + } + let precedingLineBreak = scanner.hasPrecedingLineBreak(); + let seenLineBreak = false; + let indentText = ""; + while (precedingLineBreak && token() === 42 /* AsteriskToken */ || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + indentText += scanner.getTokenText(); + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + seenLineBreak = true; + indentText = ""; + } else if (token() === 42 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextTokenJSDoc(); + } + return seenLineBreak ? indentText : ""; + } + function parseTag(margin) { + Debug.assert(token() === 60 /* AtToken */); + const start2 = scanner.getTokenStart(); + nextTokenJSDoc(); + const tagName = parseJSDocIdentifierName( + /*message*/ + void 0 + ); + const indentText = skipWhitespaceOrAsterisk(); + let tag; + switch (tagName.escapedText) { + case "author": + tag = parseAuthorTag(start2, tagName, margin, indentText); + break; + case "implements": + tag = parseImplementsTag(start2, tagName, margin, indentText); + break; + case "augments": + case "extends": + tag = parseAugmentsTag(start2, tagName, margin, indentText); + break; + case "class": + case "constructor": + tag = parseSimpleTag(start2, factory2.createJSDocClassTag, tagName, margin, indentText); + break; + case "public": + tag = parseSimpleTag(start2, factory2.createJSDocPublicTag, tagName, margin, indentText); + break; + case "private": + tag = parseSimpleTag(start2, factory2.createJSDocPrivateTag, tagName, margin, indentText); + break; + case "protected": + tag = parseSimpleTag(start2, factory2.createJSDocProtectedTag, tagName, margin, indentText); + break; + case "readonly": + tag = parseSimpleTag(start2, factory2.createJSDocReadonlyTag, tagName, margin, indentText); + break; + case "override": + tag = parseSimpleTag(start2, factory2.createJSDocOverrideTag, tagName, margin, indentText); + break; + case "deprecated": + hasDeprecatedTag = true; + tag = parseSimpleTag(start2, factory2.createJSDocDeprecatedTag, tagName, margin, indentText); + break; + case "this": + tag = parseThisTag(start2, tagName, margin, indentText); + break; + case "enum": + tag = parseEnumTag(start2, tagName, margin, indentText); + break; + case "arg": + case "argument": + case "param": + return parseParameterOrPropertyTag(start2, tagName, 2 /* Parameter */, margin); + case "return": + case "returns": + tag = parseReturnTag(start2, tagName, margin, indentText); + break; + case "template": + tag = parseTemplateTag(start2, tagName, margin, indentText); + break; + case "type": + tag = parseTypeTag(start2, tagName, margin, indentText); + break; + case "typedef": + tag = parseTypedefTag(start2, tagName, margin, indentText); + break; + case "callback": + tag = parseCallbackTag(start2, tagName, margin, indentText); + break; + case "overload": + tag = parseOverloadTag(start2, tagName, margin, indentText); + break; + case "satisfies": + tag = parseSatisfiesTag(start2, tagName, margin, indentText); + break; + case "see": + tag = parseSeeTag(start2, tagName, margin, indentText); + break; + case "exception": + case "throws": + tag = parseThrowsTag(start2, tagName, margin, indentText); + break; + case "import": + tag = parseImportTag(start2, tagName, margin, indentText); + break; + default: + tag = parseUnknownTag(start2, tagName, margin, indentText); + break; + } + return tag; + } + function parseTrailingTagComments(pos, end2, margin, indentText) { + if (!indentText) { + margin += end2 - pos; + } + return parseTagComments(margin, indentText.slice(margin)); + } + function parseTagComments(indent2, initialMargin) { + const commentsPos2 = getNodePos(); + let comments2 = []; + const parts2 = []; + let linkEnd2; + let state = 0 /* BeginningOfLine */; + let margin; + function pushComment(text) { + if (!margin) { + margin = indent2; + } + comments2.push(text); + indent2 += text.length; + } + if (initialMargin !== void 0) { + if (initialMargin !== "") { + pushComment(initialMargin); + } + state = 1 /* SawAsterisk */; + } + let tok = token(); + loop: + while (true) { + switch (tok) { + case 4 /* NewLineTrivia */: + state = 0 /* BeginningOfLine */; + comments2.push(scanner.getTokenText()); + indent2 = 0; + break; + case 60 /* AtToken */: + scanner.resetTokenState(scanner.getTokenEnd() - 1); + break loop; + case 1 /* EndOfFileToken */: + break loop; + case 5 /* WhitespaceTrivia */: + Debug.assert(state !== 2 /* SavingComments */ && state !== 3 /* SavingBackticks */, "whitespace shouldn't come from the scanner while saving comment text"); + const whitespace = scanner.getTokenText(); + if (margin !== void 0 && indent2 + whitespace.length > margin) { + comments2.push(whitespace.slice(margin - indent2)); + state = 2 /* SavingComments */; + } + indent2 += whitespace.length; + break; + case 19 /* OpenBraceToken */: + state = 2 /* SavingComments */; + const commentEnd = scanner.getTokenFullStart(); + const linkStart = scanner.getTokenEnd() - 1; + const link = parseJSDocLink(linkStart); + if (link) { + parts2.push(finishNode(factory2.createJSDocText(comments2.join("")), linkEnd2 ?? commentsPos2, commentEnd)); + parts2.push(link); + comments2 = []; + linkEnd2 = scanner.getTokenEnd(); + } else { + pushComment(scanner.getTokenText()); + } + break; + case 62 /* BacktickToken */: + if (state === 3 /* SavingBackticks */) { + state = 2 /* SavingComments */; + } else { + state = 3 /* SavingBackticks */; + } + pushComment(scanner.getTokenText()); + break; + case 82 /* JSDocCommentTextToken */: + if (state !== 3 /* SavingBackticks */) { + state = 2 /* SavingComments */; + } + pushComment(scanner.getTokenValue()); + break; + case 42 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + state = 1 /* SawAsterisk */; + indent2 += 1; + break; + } + // record the * as a comment + // falls through + default: + if (state !== 3 /* SavingBackticks */) { + state = 2 /* SavingComments */; + } + pushComment(scanner.getTokenText()); + break; + } + if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) { + tok = nextJSDocCommentTextToken(state === 3 /* SavingBackticks */); + } else { + tok = nextTokenJSDoc(); + } + } + removeLeadingNewlines(comments2); + const trimmedComments = comments2.join("").trimEnd(); + if (parts2.length) { + if (trimmedComments.length) { + parts2.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd2 ?? commentsPos2)); + } + return createNodeArray(parts2, commentsPos2, scanner.getTokenEnd()); + } else if (trimmedComments.length) { + return trimmedComments; + } + } + function parseJSDocLink(start2) { + const linkType = tryParse(parseJSDocLinkPrefix); + if (!linkType) { + return void 0; + } + nextTokenJSDoc(); + skipWhitespace(); + const name = parseJSDocLinkName(); + const text = []; + while (token() !== 20 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */) { + text.push(scanner.getTokenText()); + nextTokenJSDoc(); + } + const create = linkType === "link" ? factory2.createJSDocLink : linkType === "linkcode" ? factory2.createJSDocLinkCode : factory2.createJSDocLinkPlain; + return finishNode(create(name, text.join("")), start2, scanner.getTokenEnd()); + } + function parseJSDocLinkName() { + if (tokenIsIdentifierOrKeyword(token())) { + const pos = getNodePos(); + let name = parseIdentifierName(); + while (parseOptional(25 /* DotToken */)) { + name = finishNode(factory2.createQualifiedName(name, token() === 81 /* PrivateIdentifier */ ? createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + false + ) : parseIdentifierName()), pos); + } + while (token() === 81 /* PrivateIdentifier */) { + reScanHashToken(); + nextTokenJSDoc(); + name = finishNode(factory2.createJSDocMemberName(name, parseIdentifier()), pos); + } + return name; + } + return void 0; + } + function parseJSDocLinkPrefix() { + skipWhitespaceOrAsterisk(); + if (token() === 19 /* OpenBraceToken */ && nextTokenJSDoc() === 60 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc())) { + const kind = scanner.getTokenValue(); + if (isJSDocLinkTag(kind)) return kind; + } + } + function isJSDocLinkTag(kind) { + return kind === "link" || kind === "linkcode" || kind === "linkplain"; + } + function parseUnknownTag(start2, tagName, indent2, indentText) { + return finishNode(factory2.createJSDocUnknownTag(tagName, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2); + } + function addTag(tag) { + if (!tag) { + return; + } + if (!tags) { + tags = [tag]; + tagsPos = tag.pos; + } else { + tags.push(tag); + } + tagsEnd = tag.end; + } + function tryParseTypeExpression() { + skipWhitespaceOrAsterisk(); + return token() === 19 /* OpenBraceToken */ ? parseJSDocTypeExpression() : void 0; + } + function parseBracketNameInPropertyAndParamTag() { + const isBracketed = parseOptionalJsdoc(23 /* OpenBracketToken */); + if (isBracketed) { + skipWhitespace(); + } + const isBackquoted = parseOptionalJsdoc(62 /* BacktickToken */); + const name = parseJSDocEntityName(); + if (isBackquoted) { + parseExpectedTokenJSDoc(62 /* BacktickToken */); + } + if (isBracketed) { + skipWhitespace(); + if (parseOptionalToken(64 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(24 /* CloseBracketToken */); + } + return { name, isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 151 /* ObjectKeyword */: + return true; + case 188 /* ArrayType */: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; + } + } + function parseParameterOrPropertyTag(start2, tagName, target, indent2) { + let typeExpression = tryParseTypeExpression(); + let isNameFirst = !typeExpression; + skipWhitespaceOrAsterisk(); + const { name, isBracketed } = parseBracketNameInPropertyAndParamTag(); + const indentText = skipWhitespaceOrAsterisk(); + if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { + typeExpression = tryParseTypeExpression(); + } + const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent2); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + const result2 = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); + return finishNode(result2, start2); + } + function parseNestedTypeLiteral(typeExpression, name, target, indent2) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + const pos = getNodePos(); + let child; + let children; + while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent2, name))) { + if (child.kind === 341 /* JSDocParameterTag */ || child.kind === 348 /* JSDocPropertyTag */) { + children = append(children, child); + } else if (child.kind === 345 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + } + } + if (children) { + const literal = finishNode(factory2.createJSDocTypeLiteral(children, typeExpression.type.kind === 188 /* ArrayType */), pos); + return finishNode(factory2.createJSDocTypeExpression(literal), pos); + } + } + } + function parseReturnTag(start2, tagName, indent2, indentText) { + if (some(tags, isJSDocReturnTag)) { + parseErrorAt(tagName.pos, scanner.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText)); + } + const typeExpression = tryParseTypeExpression(); + return finishNode(factory2.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2); + } + function parseTypeTag(start2, tagName, indent2, indentText) { + if (some(tags, isJSDocTypeTag)) { + parseErrorAt(tagName.pos, scanner.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText)); + } + const typeExpression = parseJSDocTypeExpression( + /*mayOmitBraces*/ + true + ); + const comments2 = indent2 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent2, indentText) : void 0; + return finishNode(factory2.createJSDocTypeTag(tagName, typeExpression, comments2), start2); + } + function parseSeeTag(start2, tagName, indent2, indentText) { + const isMarkdownOrJSDocLink = token() === 23 /* OpenBracketToken */ || lookAhead(() => nextTokenJSDoc() === 60 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && isJSDocLinkTag(scanner.getTokenValue())); + const nameExpression = isMarkdownOrJSDocLink ? void 0 : parseJSDocNameReference(); + const comments2 = indent2 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent2, indentText) : void 0; + return finishNode(factory2.createJSDocSeeTag(tagName, nameExpression, comments2), start2); + } + function parseThrowsTag(start2, tagName, indent2, indentText) { + const typeExpression = tryParseTypeExpression(); + const comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); + return finishNode(factory2.createJSDocThrowsTag(tagName, typeExpression, comment), start2); + } + function parseAuthorTag(start2, tagName, indent2, indentText) { + const commentStart = getNodePos(); + const textOnly = parseAuthorNameAndEmail(); + let commentEnd = scanner.getTokenFullStart(); + const comments2 = parseTrailingTagComments(start2, commentEnd, indent2, indentText); + if (!comments2) { + commentEnd = scanner.getTokenFullStart(); + } + const allParts = typeof comments2 !== "string" ? createNodeArray(concatenate([finishNode(textOnly, commentStart, commentEnd)], comments2), commentStart) : textOnly.text + comments2; + return finishNode(factory2.createJSDocAuthorTag(tagName, allParts), start2); + } + function parseAuthorNameAndEmail() { + const comments2 = []; + let inEmail = false; + let token2 = scanner.getToken(); + while (token2 !== 1 /* EndOfFileToken */ && token2 !== 4 /* NewLineTrivia */) { + if (token2 === 30 /* LessThanToken */) { + inEmail = true; + } else if (token2 === 60 /* AtToken */ && !inEmail) { + break; + } else if (token2 === 32 /* GreaterThanToken */ && inEmail) { + comments2.push(scanner.getTokenText()); + scanner.resetTokenState(scanner.getTokenEnd()); + break; + } + comments2.push(scanner.getTokenText()); + token2 = nextTokenJSDoc(); + } + return factory2.createJSDocText(comments2.join("")); + } + function parseImplementsTag(start2, tagName, margin, indentText) { + const className = parseExpressionWithTypeArgumentsForAugments(); + return finishNode(factory2.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); + } + function parseAugmentsTag(start2, tagName, margin, indentText) { + const className = parseExpressionWithTypeArgumentsForAugments(); + return finishNode(factory2.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); + } + function parseSatisfiesTag(start2, tagName, margin, indentText) { + const typeExpression = parseJSDocTypeExpression( + /*mayOmitBraces*/ + false + ); + const comments2 = margin !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), margin, indentText) : void 0; + return finishNode(factory2.createJSDocSatisfiesTag(tagName, typeExpression, comments2), start2); + } + function parseImportTag(start2, tagName, margin, indentText) { + const afterImportTagPos = scanner.getTokenFullStart(); + let identifier; + if (isIdentifier2()) { + identifier = parseIdentifier(); + } + const importClause = tryParseImportClause( + identifier, + afterImportTagPos, + /*isTypeOnly*/ + true, + /*skipJsDocLeadingAsterisks*/ + true + ); + const moduleSpecifier = parseModuleSpecifier(); + const attributes = tryParseImportAttributes(); + const comments2 = margin !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), margin, indentText) : void 0; + return finishNode(factory2.createJSDocImportTag(tagName, importClause, moduleSpecifier, attributes, comments2), start2); + } + function parseExpressionWithTypeArgumentsForAugments() { + const usedBrace = parseOptional(19 /* OpenBraceToken */); + const pos = getNodePos(); + const expression = parsePropertyAccessEntityNameExpression(); + scanner.setSkipJsDocLeadingAsterisks(true); + const typeArguments = tryParseTypeArguments(); + scanner.setSkipJsDocLeadingAsterisks(false); + const node = factory2.createExpressionWithTypeArguments(expression, typeArguments); + const res = finishNode(node, pos); + if (usedBrace) { + skipWhitespace(); + parseExpected(20 /* CloseBraceToken */); + } + return res; + } + function parsePropertyAccessEntityNameExpression() { + const pos = getNodePos(); + let node = parseJSDocIdentifierName(); + while (parseOptional(25 /* DotToken */)) { + const name = parseJSDocIdentifierName(); + node = finishNode(factoryCreatePropertyAccessExpression(node, name), pos); + } + return node; + } + function parseSimpleTag(start2, createTag, tagName, margin, indentText) { + return finishNode(createTag(tagName, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); + } + function parseThisTag(start2, tagName, margin, indentText) { + const typeExpression = parseJSDocTypeExpression( + /*mayOmitBraces*/ + true + ); + skipWhitespace(); + return finishNode(factory2.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); + } + function parseEnumTag(start2, tagName, margin, indentText) { + const typeExpression = parseJSDocTypeExpression( + /*mayOmitBraces*/ + true + ); + skipWhitespace(); + return finishNode(factory2.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); + } + function parseTypedefTag(start2, tagName, indent2, indentText) { + let typeExpression = tryParseTypeExpression(); + skipWhitespaceOrAsterisk(); + const fullName = parseJSDocTypeNameWithNamespace(); + skipWhitespace(); + let comment = parseTagComments(indent2); + let end2; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + let child; + let childTypeTag; + let jsDocPropertyTags; + let hasChildren = false; + while (child = tryParse(() => parseChildPropertyTag(indent2))) { + if (child.kind === 345 /* JSDocTemplateTag */) { + break; + } + hasChildren = true; + if (child.kind === 344 /* JSDocTypeTag */) { + if (childTypeTag) { + const lastError = parseErrorAtCurrentToken(Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); + if (lastError) { + addRelatedInfo(lastError, createDetachedDiagnostic(fileName, sourceText, 0, 0, Diagnostics.The_tag_was_first_specified_here)); + } + break; + } else { + childTypeTag = child; + } + } else { + jsDocPropertyTags = append(jsDocPropertyTags, child); + } + } + if (hasChildren) { + const isArrayType = typeExpression && typeExpression.type.kind === 188 /* ArrayType */; + const jsdocTypeLiteral = factory2.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); + typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral, start2); + end2 = typeExpression.end; + } + } + end2 = end2 || comment !== void 0 ? getNodePos() : (fullName ?? typeExpression ?? tagName).end; + if (!comment) { + comment = parseTrailingTagComments(start2, end2, indent2, indentText); + } + const typedefTag = factory2.createJSDocTypedefTag(tagName, typeExpression, fullName, comment); + return finishNode(typedefTag, start2, end2); + } + function parseJSDocTypeNameWithNamespace(nested) { + const start2 = scanner.getTokenStart(); + if (!tokenIsIdentifierOrKeyword(token())) { + return void 0; + } + const typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (parseOptional(25 /* DotToken */)) { + const body = parseJSDocTypeNameWithNamespace( + /*nested*/ + true + ); + const jsDocNamespaceNode = factory2.createModuleDeclaration( + /*modifiers*/ + void 0, + typeNameOrNamespaceName, + body, + nested ? 8 /* NestedNamespace */ : void 0 + ); + return finishNode(jsDocNamespaceNode, start2); + } + if (nested) { + typeNameOrNamespaceName.flags |= 4096 /* IdentifierIsInJSDocNamespace */; + } + return typeNameOrNamespaceName; + } + function parseCallbackTagParameters(indent2) { + const pos = getNodePos(); + let child; + let parameters; + while (child = tryParse(() => parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent2))) { + if (child.kind === 345 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + break; + } + parameters = append(parameters, child); + } + return createNodeArray(parameters || [], pos); + } + function parseJSDocSignature(start2, indent2) { + const parameters = parseCallbackTagParameters(indent2); + const returnTag = tryParse(() => { + if (parseOptionalJsdoc(60 /* AtToken */)) { + const tag = parseTag(indent2); + if (tag && tag.kind === 342 /* JSDocReturnTag */) { + return tag; + } + } + }); + return finishNode(factory2.createJSDocSignature( + /*typeParameters*/ + void 0, + parameters, + returnTag + ), start2); + } + function parseCallbackTag(start2, tagName, indent2, indentText) { + const fullName = parseJSDocTypeNameWithNamespace(); + skipWhitespace(); + let comment = parseTagComments(indent2); + const typeExpression = parseJSDocSignature(start2, indent2); + if (!comment) { + comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); + } + const end2 = comment !== void 0 ? getNodePos() : typeExpression.end; + return finishNode(factory2.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start2, end2); + } + function parseOverloadTag(start2, tagName, indent2, indentText) { + skipWhitespace(); + let comment = parseTagComments(indent2); + const typeExpression = parseJSDocSignature(start2, indent2); + if (!comment) { + comment = parseTrailingTagComments(start2, getNodePos(), indent2, indentText); + } + const end2 = comment !== void 0 ? getNodePos() : typeExpression.end; + return finishNode(factory2.createJSDocOverloadTag(tagName, typeExpression, comment), start2, end2); + } + function escapedTextsEqual(a, b) { + while (!isIdentifier(a) || !isIdentifier(b)) { + if (!isIdentifier(a) && !isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildPropertyTag(indent2) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent2); + } + function parseChildParameterOrPropertyTag(target, indent2, name) { + let canParseTag = true; + let seenAsterisk = false; + while (true) { + switch (nextTokenJSDoc()) { + case 60 /* AtToken */: + if (canParseTag) { + const child = tryParseChildTag(target, indent2); + if (child && (child.kind === 341 /* JSDocParameterTag */ || child.kind === 348 /* JSDocPropertyTag */) && name && (isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + canParseTag = true; + seenAsterisk = false; + break; + case 42 /* AsteriskToken */: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 80 /* Identifier */: + canParseTag = false; + break; + case 1 /* EndOfFileToken */: + return false; + } + } + } + function tryParseChildTag(target, indent2) { + Debug.assert(token() === 60 /* AtToken */); + const start2 = scanner.getTokenFullStart(); + nextTokenJSDoc(); + const tagName = parseJSDocIdentifierName(); + const indentText = skipWhitespaceOrAsterisk(); + let t; + switch (tagName.escapedText) { + case "type": + return target === 1 /* Property */ && parseTypeTag(start2, tagName); + case "prop": + case "property": + t = 1 /* Property */; + break; + case "arg": + case "argument": + case "param": + t = 2 /* Parameter */ | 4 /* CallbackParameter */; + break; + case "template": + return parseTemplateTag(start2, tagName, indent2, indentText); + case "this": + return parseThisTag(start2, tagName, indent2, indentText); + default: + return false; + } + if (!(target & t)) { + return false; + } + return parseParameterOrPropertyTag(start2, tagName, target, indent2); + } + function parseTemplateTagTypeParameter() { + const typeParameterPos = getNodePos(); + const isBracketed = parseOptionalJsdoc(23 /* OpenBracketToken */); + if (isBracketed) { + skipWhitespace(); + } + const modifiers = parseModifiers( + /*allowDecorators*/ + false, + /*permitConstAsModifier*/ + true + ); + const name = parseJSDocIdentifierName(Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + let defaultType; + if (isBracketed) { + skipWhitespace(); + parseExpected(64 /* EqualsToken */); + defaultType = doInsideOfContext(16777216 /* JSDoc */, parseJSDocType); + parseExpected(24 /* CloseBracketToken */); + } + if (nodeIsMissing(name)) { + return void 0; + } + return finishNode(factory2.createTypeParameterDeclaration( + modifiers, + name, + /*constraint*/ + void 0, + defaultType + ), typeParameterPos); + } + function parseTemplateTagTypeParameters() { + const pos = getNodePos(); + const typeParameters = []; + do { + skipWhitespace(); + const node = parseTemplateTagTypeParameter(); + if (node !== void 0) { + typeParameters.push(node); + } + skipWhitespaceOrAsterisk(); + } while (parseOptionalJsdoc(28 /* CommaToken */)); + return createNodeArray(typeParameters, pos); + } + function parseTemplateTag(start2, tagName, indent2, indentText) { + const constraint = token() === 19 /* OpenBraceToken */ ? parseJSDocTypeExpression() : void 0; + const typeParameters = parseTemplateTagTypeParameters(); + return finishNode(factory2.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start2, getNodePos(), indent2, indentText)), start2); + } + function parseOptionalJsdoc(t) { + if (token() === t) { + nextTokenJSDoc(); + return true; + } + return false; + } + function parseJSDocEntityName() { + let entity = parseJSDocIdentifierName(); + if (parseOptional(23 /* OpenBracketToken */)) { + parseExpected(24 /* CloseBracketToken */); + } + while (parseOptional(25 /* DotToken */)) { + const name = parseJSDocIdentifierName(); + if (parseOptional(23 /* OpenBracketToken */)) { + parseExpected(24 /* CloseBracketToken */); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(message) { + if (!tokenIsIdentifierOrKeyword(token())) { + return createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + !message, + message || Diagnostics.Identifier_expected + ); + } + identifierCount++; + const start2 = scanner.getTokenStart(); + const end2 = scanner.getTokenEnd(); + const originalKeywordKind = token(); + const text = internIdentifier(scanner.getTokenValue()); + const result2 = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); + nextTokenJSDoc(); + return result2; + } + } + })(JSDocParser = Parser2.JSDocParser || (Parser2.JSDocParser = {})); +})(Parser || (Parser = {})); +var incrementallyParsedFiles = /* @__PURE__ */ new WeakSet(); +function markAsIncrementallyParsed(sourceFile) { + if (incrementallyParsedFiles.has(sourceFile)) { + Debug.fail("Source file has already been incrementally parsed"); + } + incrementallyParsedFiles.add(sourceFile); +} +var intersectingChangeSet = /* @__PURE__ */ new WeakSet(); +function intersectsIncrementalChange(node) { + return intersectingChangeSet.has(node); +} +function markAsIntersectingIncrementalChange(node) { + intersectingChangeSet.add(node); +} +var IncrementalParser; +((IncrementalParser2) => { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || Debug.shouldAssert(2 /* Aggressive */); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (textChangeRangeIsUnchanged(textChangeRange)) { + return sourceFile; + } + if (sourceFile.statements.length === 0) { + return Parser.parseSourceFile( + sourceFile.fileName, + newText, + sourceFile.languageVersion, + /*syntaxCursor*/ + void 0, + /*setParentNodes*/ + true, + sourceFile.scriptKind, + sourceFile.setExternalModuleIndicator, + sourceFile.jsDocParsingMode + ); + } + markAsIncrementallyParsed(sourceFile); + Parser.fixupParentReferences(sourceFile); + const oldText = sourceFile.text; + const syntaxCursor = createSyntaxCursor(sourceFile); + const changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + Debug.assert(changeRange.span.start <= textChangeRange.span.start); + Debug.assert(textSpanEnd(changeRange.span) === textSpanEnd(textChangeRange.span)); + Debug.assert(textSpanEnd(textChangeRangeNewSpan(changeRange)) === textSpanEnd(textChangeRangeNewSpan(textChangeRange))); + const delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + updateTokenPositionsAndMarkElements(sourceFile, changeRange.span.start, textSpanEnd(changeRange.span), textSpanEnd(textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + const result = Parser.parseSourceFile( + sourceFile.fileName, + newText, + sourceFile.languageVersion, + syntaxCursor, + /*setParentNodes*/ + true, + sourceFile.scriptKind, + sourceFile.setExternalModuleIndicator, + sourceFile.jsDocParsingMode + ); + result.commentDirectives = getNewCommentDirectives( + sourceFile.commentDirectives, + result.commentDirectives, + changeRange.span.start, + textSpanEnd(changeRange.span), + delta, + oldText, + newText, + aggressiveChecks + ); + result.impliedNodeFormat = sourceFile.impliedNodeFormat; + transferSourceFileChildren(sourceFile, result); + return result; + } + IncrementalParser2.updateSourceFile = updateSourceFile; + function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { + if (!oldDirectives) return newDirectives; + let commentDirectives; + let addedNewlyScannedDirectives = false; + for (const directive of oldDirectives) { + const { range, type } = directive; + if (range.end < changeStart) { + commentDirectives = append(commentDirectives, directive); + } else if (range.pos > changeRangeOldEnd) { + addNewlyScannedDirectives(); + const updatedDirective = { + range: { pos: range.pos + delta, end: range.end + delta }, + type + }; + commentDirectives = append(commentDirectives, updatedDirective); + if (aggressiveChecks) { + Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end)); + } + } + } + addNewlyScannedDirectives(); + return commentDirectives; + function addNewlyScannedDirectives() { + if (addedNewlyScannedDirectives) return; + addedNewlyScannedDirectives = true; + if (!commentDirectives) { + commentDirectives = newDirectives; + } else if (newDirectives) { + commentDirectives.push(...newDirectives); + } + } + } + function moveElementEntirelyPastChangeRange(element, origSourceFile, isArray2, delta, oldText, newText, aggressiveChecks) { + if (isArray2) { + visitArray2(element); + } else { + visitNode3(element); + } + return; + function visitNode3(node) { + let text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + unsetNodeChildren(node, origSourceFile); + setTextRangePosEnd(node, node.pos + delta, node.end + delta); + if (aggressiveChecks && shouldCheckNode(node)) { + Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode3, visitArray2); + if (hasJSDocNodes(node)) { + for (const jsDocComment of node.jsDoc) { + visitNode3(jsDocComment); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray2(array) { + setTextRangePosEnd(array, array.pos + delta, array.end + delta); + for (const node of array) { + visitNode3(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 11 /* StringLiteral */: + case 9 /* NumericLiteral */: + case 80 /* Identifier */: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + Debug.assert(element.pos <= element.end); + const pos = Math.min(element.pos, changeRangeNewEnd); + const end = element.end >= changeRangeOldEnd ? ( + // Element ends after the change range. Always adjust the end pos. + element.end + delta + ) : ( + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + Math.min(element.end, changeRangeNewEnd) + ); + Debug.assert(pos <= end); + if (element.parent) { + const parent = element.parent; + Debug.assertGreaterThanOrEqual(pos, parent.pos); + Debug.assertLessThanOrEqual(end, parent.end); + } + setTextRangePosEnd(element, pos, end); + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + let pos = node.pos; + const visitNode3 = (child) => { + Debug.assert(child.pos >= pos); + pos = child.end; + }; + if (hasJSDocNodes(node)) { + for (const jsDocComment of node.jsDoc) { + visitNode3(jsDocComment); + } + } + forEachChild(node, visitNode3); + Debug.assert(pos <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode3(sourceFile); + return; + function visitNode3(child) { + Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange( + child, + sourceFile, + /*isArray*/ + false, + delta, + oldText, + newText, + aggressiveChecks + ); + return; + } + const fullEnd = child.end; + if (fullEnd >= changeStart) { + markAsIntersectingIncrementalChange(child); + unsetNodeChildren(child, sourceFile); + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode3, visitArray2); + if (hasJSDocNodes(child)) { + for (const jsDocComment of child.jsDoc) { + visitNode3(jsDocComment); + } + } + checkNodePositions(child, aggressiveChecks); + return; + } + Debug.assert(fullEnd < changeStart); + } + function visitArray2(array) { + Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange( + array, + sourceFile, + /*isArray*/ + true, + delta, + oldText, + newText, + aggressiveChecks + ); + return; + } + const fullEnd = array.end; + if (fullEnd >= changeStart) { + markAsIntersectingIncrementalChange(array); + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (const node of array) { + visitNode3(node); + } + return; + } + Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + const maxLookahead = 1; + let start = changeRange.span.start; + for (let i = 0; start > 0 && i <= maxLookahead; i++) { + const nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + Debug.assert(nearestNode.pos <= start); + const position = nearestNode.pos; + start = Math.max(0, position - 1); + } + const finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span)); + const finalLength = changeRange.newLength + (changeRange.span.start - start); + return createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + let bestResult = sourceFile; + let lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + const lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastDescendant(node) { + while (true) { + const lastChild = getLastChild(node); + if (lastChild) { + node = lastChild; + } else { + return node; + } + } + } + function visit(child) { + if (nodeIsMissing(child)) { + return; + } + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + bestResult = child; + } + if (position < child.end) { + forEachChild(child, visit); + return true; + } else { + Debug.assert(child.end <= position); + lastNodeEntirelyBeforePosition = child; + } + } else { + Debug.assert(child.pos > position); + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + const oldText = sourceFile.text; + if (textChangeRange) { + Debug.assert(oldText.length - textChangeRange.span.length + textChangeRange.newLength === newText.length); + if (aggressiveChecks || Debug.shouldAssert(3 /* VeryAggressive */)) { + const oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + const newTextPrefix = newText.substr(0, textChangeRange.span.start); + Debug.assert(oldTextPrefix === newTextPrefix); + const oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length); + const newTextSuffix = newText.substring(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.length); + Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + let currentArray = sourceFile.statements; + let currentArrayIndex = 0; + Debug.assert(currentArrayIndex < currentArray.length); + let current = currentArray[currentArrayIndex]; + let lastQueriedPosition = -1 /* Value */; + return { + currentNode(position) { + if (position !== lastQueriedPosition) { + if (current && current.end === position && currentArrayIndex < currentArray.length - 1) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + lastQueriedPosition = position; + Debug.assert(!current || current.pos === position); + return current; + } + }; + function findHighestListElementThatStartsAtPosition(position) { + currentArray = void 0; + currentArrayIndex = -1 /* Value */; + current = void 0; + forEachChild(sourceFile, visitNode3, visitArray2); + return; + function visitNode3(node) { + if (position >= node.pos && position < node.end) { + forEachChild(node, visitNode3, visitArray2); + return true; + } + return false; + } + function visitArray2(array) { + if (position >= array.pos && position < array.end) { + for (let i = 0; i < array.length; i++) { + const child = array[i]; + if (child) { + if (child.pos === position) { + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } else { + if (child.pos < position && position < child.end) { + forEachChild(child, visitNode3, visitArray2); + return true; + } + } + } + } + } + return false; + } + } + } + IncrementalParser2.createSyntaxCursor = createSyntaxCursor; + let InvalidPosition; + ((InvalidPosition2) => { + InvalidPosition2[InvalidPosition2["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); +})(IncrementalParser || (IncrementalParser = {})); +function isDeclarationFileName(fileName) { + return getDeclarationFileExtension(fileName) !== void 0; +} +function getDeclarationFileExtension(fileName) { + const standardExtension = getAnyExtensionFromPath( + fileName, + supportedDeclarationExtensions, + /*ignoreCase*/ + false + ); + if (standardExtension) { + return standardExtension; + } + if (fileExtensionIs(fileName, ".ts" /* Ts */)) { + const baseName = getBaseFileName(fileName); + const index = baseName.lastIndexOf(".d."); + if (index >= 0) { + return baseName.substring(index); + } + } + return void 0; +} +function parseResolutionMode(mode, pos, end, reportDiagnostic) { + if (!mode) { + return void 0; + } + if (mode === "import") { + return 99 /* ESNext */; + } + if (mode === "require") { + return 1 /* CommonJS */; + } + reportDiagnostic(pos, end - pos, Diagnostics.resolution_mode_should_be_either_require_or_import); + return void 0; +} +function processCommentPragmas(context, sourceText) { + const pragmas = []; + for (const range of getLeadingCommentRanges(sourceText, 0) || emptyArray) { + const comment = sourceText.substring(range.pos, range.end); + extractPragmas(pragmas, range, comment); + } + context.pragmas = /* @__PURE__ */ new Map(); + for (const pragma of pragmas) { + if (context.pragmas.has(pragma.name)) { + const currentValue = context.pragmas.get(pragma.name); + if (currentValue instanceof Array) { + currentValue.push(pragma.args); + } else { + context.pragmas.set(pragma.name, [currentValue, pragma.args]); + } + continue; + } + context.pragmas.set(pragma.name, pragma.args); + } +} +function processPragmasIntoFields(context, reportDiagnostic) { + context.checkJsDirective = void 0; + context.referencedFiles = []; + context.typeReferenceDirectives = []; + context.libReferenceDirectives = []; + context.amdDependencies = []; + context.hasNoDefaultLib = false; + context.pragmas.forEach((entryOrList, key) => { + switch (key) { + case "reference": { + const referencedFiles = context.referencedFiles; + const typeReferenceDirectives = context.typeReferenceDirectives; + const libReferenceDirectives = context.libReferenceDirectives; + forEach(toArray(entryOrList), (arg) => { + const { types, lib, path, ["resolution-mode"]: res, preserve: _preserve } = arg.arguments; + const preserve = _preserve === "true" ? true : void 0; + if (arg.arguments["no-default-lib"] === "true") { + context.hasNoDefaultLib = true; + } else if (types) { + const parsed = parseResolutionMode(res, types.pos, types.end, reportDiagnostic); + typeReferenceDirectives.push({ pos: types.pos, end: types.end, fileName: types.value, ...parsed ? { resolutionMode: parsed } : {}, ...preserve ? { preserve } : {} }); + } else if (lib) { + libReferenceDirectives.push({ pos: lib.pos, end: lib.end, fileName: lib.value, ...preserve ? { preserve } : {} }); + } else if (path) { + referencedFiles.push({ pos: path.pos, end: path.end, fileName: path.value, ...preserve ? { preserve } : {} }); + } else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, Diagnostics.Invalid_reference_directive_syntax); + } + }); + break; + } + case "amd-dependency": { + context.amdDependencies = map( + toArray(entryOrList), + (x) => ({ name: x.arguments.name, path: x.arguments.path }) + ); + break; + } + case "amd-module": { + if (entryOrList instanceof Array) { + for (const entry of entryOrList) { + if (context.moduleName) { + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } else { + context.moduleName = entryOrList.arguments.name; + } + break; + } + case "ts-nocheck": + case "ts-check": { + forEach(toArray(entryOrList), (entry) => { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } + case "jsx": + case "jsxfrag": + case "jsximportsource": + case "jsxruntime": + return; + // Accessed directly + default: + Debug.fail("Unhandled pragma kind"); + } + }); +} +var namedArgRegExCache = /* @__PURE__ */ new Map(); +function getNamedArgRegEx(name) { + if (namedArgRegExCache.has(name)) { + return namedArgRegExCache.get(name); + } + const result = new RegExp(`(\\s${name}\\s*=\\s*)(?:(?:'([^']*)')|(?:"([^"]*)"))`, "im"); + namedArgRegExCache.set(name, result); + return result; +} +var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/m; +var singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)((?:[^\S\r\n]|:).*)?$/m; +function extractPragmas(pragmas, range, text) { + const tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); + if (tripleSlash) { + const name = tripleSlash[1].toLowerCase(); + const pragma = commentPragmas[name]; + if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) { + return; + } + if (pragma.args) { + const argument = {}; + for (const arg of pragma.args) { + const matcher = getNamedArgRegEx(arg.name); + const matchResult = matcher.exec(text); + if (!matchResult && !arg.optional) { + return; + } else if (matchResult) { + const value = matchResult[2] || matchResult[3]; + if (arg.captureSpan) { + const startPos = range.pos + matchResult.index + matchResult[1].length + 1; + argument[arg.name] = { + value, + pos: startPos, + end: startPos + value.length + }; + } else { + argument[arg.name] = value; + } + } + } + pragmas.push({ name, args: { arguments: argument, range } }); + } else { + pragmas.push({ name, args: { arguments: {}, range } }); + } + return; + } + const singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text); + if (singleLine) { + return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); + } + if (range.kind === 3 /* MultiLineCommentTrivia */) { + const multiLinePragmaRegEx = /@(\S+)(\s+(?:\S.*)?)?$/gm; + let multiLineMatch; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } + } +} +function addPragmaForMatch(pragmas, range, kind, match) { + if (!match) return; + const name = match[1].toLowerCase(); + const pragma = commentPragmas[name]; + if (!pragma || !(pragma.kind & kind)) { + return; + } + const args = match[2]; + const argument = getNamedPragmaArguments(pragma, args); + if (argument === "fail") return; + pragmas.push({ name, args: { arguments: argument, range } }); + return; +} +function getNamedPragmaArguments(pragma, text) { + if (!text) return {}; + if (!pragma.args) return {}; + const args = text.trim().split(/\s+/); + const argMap = {}; + for (let i = 0; i < pragma.args.length; i++) { + const argument = pragma.args[i]; + if (!args[i] && !argument.optional) { + return "fail"; + } + if (argument.captureSpan) { + return Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + } + argMap[argument.name] = args[i]; + } + return argMap; +} +function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 80 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 110 /* ThisKeyword */) { + return true; + } + if (lhs.kind === 295 /* JsxNamespacedName */) { + return lhs.namespace.escapedText === rhs.namespace.escapedText && lhs.name.escapedText === rhs.name.escapedText; + } + return lhs.name.escapedText === rhs.name.escapedText && tagNamesAreEquivalent(lhs.expression, rhs.expression); +} + +// src/compiler/commandLineParser.ts +var compileOnSaveCommandLineOption = { + name: "compileOnSave", + type: "boolean", + defaultValueDescription: false +}; +var jsxOptionMap = new Map(Object.entries({ + "preserve": 1 /* Preserve */, + "react-native": 3 /* ReactNative */, + "react": 2 /* React */, + "react-jsx": 4 /* ReactJSX */, + "react-jsxdev": 5 /* ReactJSXDev */ +})); +var inverseJsxOptionMap = new Map(mapIterator(jsxOptionMap.entries(), ([key, value]) => ["" + value, key])); +var libEntries = [ + // JavaScript only + ["es5", "lib.es5.d.ts"], + ["es6", "lib.es2015.d.ts"], + ["es2015", "lib.es2015.d.ts"], + ["es7", "lib.es2016.d.ts"], + ["es2016", "lib.es2016.d.ts"], + ["es2017", "lib.es2017.d.ts"], + ["es2018", "lib.es2018.d.ts"], + ["es2019", "lib.es2019.d.ts"], + ["es2020", "lib.es2020.d.ts"], + ["es2021", "lib.es2021.d.ts"], + ["es2022", "lib.es2022.d.ts"], + ["es2023", "lib.es2023.d.ts"], + ["es2024", "lib.es2024.d.ts"], + ["esnext", "lib.esnext.d.ts"], + // Host only + ["dom", "lib.dom.d.ts"], + ["dom.iterable", "lib.dom.iterable.d.ts"], + ["dom.asynciterable", "lib.dom.asynciterable.d.ts"], + ["webworker", "lib.webworker.d.ts"], + ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], + ["webworker.iterable", "lib.webworker.iterable.d.ts"], + ["webworker.asynciterable", "lib.webworker.asynciterable.d.ts"], + ["scripthost", "lib.scripthost.d.ts"], + // ES2015 Or ESNext By-feature options + ["es2015.core", "lib.es2015.core.d.ts"], + ["es2015.collection", "lib.es2015.collection.d.ts"], + ["es2015.generator", "lib.es2015.generator.d.ts"], + ["es2015.iterable", "lib.es2015.iterable.d.ts"], + ["es2015.promise", "lib.es2015.promise.d.ts"], + ["es2015.proxy", "lib.es2015.proxy.d.ts"], + ["es2015.reflect", "lib.es2015.reflect.d.ts"], + ["es2015.symbol", "lib.es2015.symbol.d.ts"], + ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], + ["es2016.array.include", "lib.es2016.array.include.d.ts"], + ["es2016.intl", "lib.es2016.intl.d.ts"], + ["es2017.arraybuffer", "lib.es2017.arraybuffer.d.ts"], + ["es2017.date", "lib.es2017.date.d.ts"], + ["es2017.object", "lib.es2017.object.d.ts"], + ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], + ["es2017.string", "lib.es2017.string.d.ts"], + ["es2017.intl", "lib.es2017.intl.d.ts"], + ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"], + ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"], + ["es2018.intl", "lib.es2018.intl.d.ts"], + ["es2018.promise", "lib.es2018.promise.d.ts"], + ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["es2019.array", "lib.es2019.array.d.ts"], + ["es2019.object", "lib.es2019.object.d.ts"], + ["es2019.string", "lib.es2019.string.d.ts"], + ["es2019.symbol", "lib.es2019.symbol.d.ts"], + ["es2019.intl", "lib.es2019.intl.d.ts"], + ["es2020.bigint", "lib.es2020.bigint.d.ts"], + ["es2020.date", "lib.es2020.date.d.ts"], + ["es2020.promise", "lib.es2020.promise.d.ts"], + ["es2020.sharedmemory", "lib.es2020.sharedmemory.d.ts"], + ["es2020.string", "lib.es2020.string.d.ts"], + ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], + ["es2020.intl", "lib.es2020.intl.d.ts"], + ["es2020.number", "lib.es2020.number.d.ts"], + ["es2021.promise", "lib.es2021.promise.d.ts"], + ["es2021.string", "lib.es2021.string.d.ts"], + ["es2021.weakref", "lib.es2021.weakref.d.ts"], + ["es2021.intl", "lib.es2021.intl.d.ts"], + ["es2022.array", "lib.es2022.array.d.ts"], + ["es2022.error", "lib.es2022.error.d.ts"], + ["es2022.intl", "lib.es2022.intl.d.ts"], + ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.string", "lib.es2022.string.d.ts"], + ["es2022.regexp", "lib.es2022.regexp.d.ts"], + ["es2023.array", "lib.es2023.array.d.ts"], + ["es2023.collection", "lib.es2023.collection.d.ts"], + ["es2023.intl", "lib.es2023.intl.d.ts"], + ["es2024.arraybuffer", "lib.es2024.arraybuffer.d.ts"], + ["es2024.collection", "lib.es2024.collection.d.ts"], + ["es2024.object", "lib.es2024.object.d.ts"], + ["es2024.promise", "lib.es2024.promise.d.ts"], + ["es2024.regexp", "lib.es2024.regexp.d.ts"], + ["es2024.sharedmemory", "lib.es2024.sharedmemory.d.ts"], + ["es2024.string", "lib.es2024.string.d.ts"], + ["esnext.array", "lib.es2023.array.d.ts"], + ["esnext.collection", "lib.esnext.collection.d.ts"], + ["esnext.symbol", "lib.es2019.symbol.d.ts"], + ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.disposable", "lib.esnext.disposable.d.ts"], + ["esnext.bigint", "lib.es2020.bigint.d.ts"], + ["esnext.string", "lib.es2022.string.d.ts"], + ["esnext.promise", "lib.es2024.promise.d.ts"], + ["esnext.weakref", "lib.es2021.weakref.d.ts"], + ["esnext.decorators", "lib.esnext.decorators.d.ts"], + ["esnext.object", "lib.es2024.object.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.regexp", "lib.es2024.regexp.d.ts"], + ["esnext.string", "lib.es2024.string.d.ts"], + ["esnext.iterator", "lib.esnext.iterator.d.ts"], + ["esnext.promise", "lib.esnext.promise.d.ts"], + ["esnext.float16", "lib.esnext.float16.d.ts"], + ["decorators", "lib.decorators.d.ts"], + ["decorators.legacy", "lib.decorators.legacy.d.ts"] +]; +var libs = libEntries.map((entry) => entry[0]); +var libMap = new Map(libEntries); +var optionsForWatch = [ + { + name: "watchFile", + type: new Map(Object.entries({ + fixedpollinginterval: 0 /* FixedPollingInterval */, + prioritypollinginterval: 1 /* PriorityPollingInterval */, + dynamicprioritypolling: 2 /* DynamicPriorityPolling */, + fixedchunksizepolling: 3 /* FixedChunkSizePolling */, + usefsevents: 4 /* UseFsEvents */, + usefseventsonparentdirectory: 5 /* UseFsEventsOnParentDirectory */ + })), + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Specify_how_the_TypeScript_watch_mode_works, + defaultValueDescription: 4 /* UseFsEvents */ + }, + { + name: "watchDirectory", + type: new Map(Object.entries({ + usefsevents: 0 /* UseFsEvents */, + fixedpollinginterval: 1 /* FixedPollingInterval */, + dynamicprioritypolling: 2 /* DynamicPriorityPolling */, + fixedchunksizepolling: 3 /* FixedChunkSizePolling */ + })), + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality, + defaultValueDescription: 0 /* UseFsEvents */ + }, + { + name: "fallbackPolling", + type: new Map(Object.entries({ + fixedinterval: 0 /* FixedInterval */, + priorityinterval: 1 /* PriorityInterval */, + dynamicpriority: 2 /* DynamicPriority */, + fixedchunksize: 3 /* FixedChunkSize */ + })), + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers, + defaultValueDescription: 1 /* PriorityInterval */ + }, + { + name: "synchronousWatchDirectory", + type: "boolean", + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, + defaultValueDescription: false + }, + { + name: "excludeDirectories", + type: "list", + element: { + name: "excludeDirectory", + type: "string", + isFilePath: true, + extraValidation: specToDiagnostic + }, + allowConfigDirTemplateSubstitution: true, + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Remove_a_list_of_directories_from_the_watch_process + }, + { + name: "excludeFiles", + type: "list", + element: { + name: "excludeFile", + type: "string", + isFilePath: true, + extraValidation: specToDiagnostic + }, + allowConfigDirTemplateSubstitution: true, + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Remove_a_list_of_files_from_the_watch_mode_s_processing + } +]; +var commonOptionsWithBuild = [ + { + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + isCommandLineOnly: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Print_this_message, + defaultValueDescription: false + }, + { + name: "help", + shortName: "?", + type: "boolean", + isCommandLineOnly: true, + category: Diagnostics.Command_line_Options, + defaultValueDescription: false + }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + isCommandLineOnly: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Watch_input_files, + defaultValueDescription: false + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: Diagnostics.Output_Formatting, + description: Diagnostics.Disable_wiping_the_console_in_watch_mode, + defaultValueDescription: false + }, + { + name: "listFiles", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Print_all_of_the_files_read_during_the_compilation, + defaultValueDescription: false + }, + { + name: "explainFiles", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, + defaultValueDescription: false + }, + { + name: "listEmittedFiles", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Print_the_names_of_emitted_files_after_a_compilation, + defaultValueDescription: false + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Output_Formatting, + description: Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read, + defaultValueDescription: true + }, + { + name: "traceResolution", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Log_paths_used_during_the_moduleResolution_process, + defaultValueDescription: false + }, + { + name: "diagnostics", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Output_compiler_performance_information_after_building, + defaultValueDescription: false + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Output_more_detailed_compiler_performance_information_after_building, + defaultValueDescription: false + }, + { + name: "generateCpuProfile", + type: "string", + isFilePath: true, + paramType: Diagnostics.FILE_OR_DIRECTORY, + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging, + defaultValueDescription: "profile.cpuprofile" + }, + { + name: "generateTrace", + type: "string", + isFilePath: true, + paramType: Diagnostics.DIRECTORY, + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Generates_an_event_trace_and_a_list_of_types + }, + { + name: "incremental", + shortName: "i", + type: "boolean", + category: Diagnostics.Projects, + description: Diagnostics.Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects, + transpileOptionValue: void 0, + defaultValueDescription: Diagnostics.false_unless_composite_is_set + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + transpileOptionValue: void 0, + description: Diagnostics.Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project, + defaultValueDescription: Diagnostics.false_unless_composite_is_set + }, + { + name: "declarationMap", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + defaultValueDescription: false, + description: Diagnostics.Create_sourcemaps_for_d_ts_files + }, + { + name: "emitDeclarationOnly", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + description: Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, + transpileOptionValue: void 0, + defaultValueDescription: false + }, + { + name: "sourceMap", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + defaultValueDescription: false, + description: Diagnostics.Create_source_map_files_for_emitted_JavaScript_files + }, + { + name: "inlineSourceMap", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, + defaultValueDescription: false + }, + { + name: "noCheck", + type: "boolean", + showInSimplifiedHelpView: false, + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported, + transpileOptionValue: true, + defaultValueDescription: false + // Not setting affectsSemanticDiagnostics or affectsBuildInfo because we dont want all diagnostics to go away, its handled in builder + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + description: Diagnostics.Disable_emitting_files_from_a_compilation, + transpileOptionValue: void 0, + defaultValueDescription: false + }, + { + name: "assumeChangesOnlyAffectDirectDependencies", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, + defaultValueDescription: false + }, + { + name: "locale", + type: "string", + category: Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: Diagnostics.Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit, + defaultValueDescription: Diagnostics.Platform_specific + } +]; +var targetOptionDeclaration = { + name: "target", + shortName: "t", + type: new Map(Object.entries({ + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + es2019: 6 /* ES2019 */, + es2020: 7 /* ES2020 */, + es2021: 8 /* ES2021 */, + es2022: 9 /* ES2022 */, + es2023: 10 /* ES2023 */, + es2024: 11 /* ES2024 */, + esnext: 99 /* ESNext */ + })), + affectsSourceFile: true, + affectsModuleResolution: true, + affectsEmit: true, + affectsBuildInfo: true, + deprecatedKeys: /* @__PURE__ */ new Set(["es3"]), + paramType: Diagnostics.VERSION, + showInSimplifiedHelpView: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, + defaultValueDescription: 1 /* ES5 */ +}; +var moduleOptionDeclaration = { + name: "module", + shortName: "m", + type: new Map(Object.entries({ + none: 0 /* None */, + commonjs: 1 /* CommonJS */, + amd: 2 /* AMD */, + system: 4 /* System */, + umd: 3 /* UMD */, + es6: 5 /* ES2015 */, + es2015: 5 /* ES2015 */, + es2020: 6 /* ES2020 */, + es2022: 7 /* ES2022 */, + esnext: 99 /* ESNext */, + node16: 100 /* Node16 */, + node18: 101 /* Node18 */, + nodenext: 199 /* NodeNext */, + preserve: 200 /* Preserve */ + })), + affectsSourceFile: true, + affectsModuleResolution: true, + affectsEmit: true, + affectsBuildInfo: true, + paramType: Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: Diagnostics.Modules, + description: Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: void 0 +}; +var commandOptionsWithoutBuild = [ + // CommandLine only options + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Show_all_compiler_options, + defaultValueDescription: false + }, + { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Print_the_compiler_s_version, + defaultValueDescription: false + }, + { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + defaultValueDescription: false + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + paramType: Diagnostics.FILE_OR_DIRECTORY, + description: Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json + }, + { + name: "showConfig", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: Diagnostics.Print_the_final_configuration_instead_of_building, + defaultValueDescription: false + }, + { + name: "listFilesOnly", + type: "boolean", + category: Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, + defaultValueDescription: false + }, + // Basic + targetOptionDeclaration, + moduleOptionDeclaration, + { + name: "lib", + type: "list", + element: { + name: "lib", + type: libMap, + defaultValueDescription: void 0 + }, + affectsProgramStructure: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment, + transpileOptionValue: void 0 + }, + { + name: "allowJs", + type: "boolean", + allowJsFlag: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.JavaScript_Support, + description: Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files, + defaultValueDescription: false + }, + { + name: "checkJs", + type: "boolean", + affectsModuleResolution: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.JavaScript_Support, + description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, + defaultValueDescription: false + }, + { + name: "jsx", + type: jsxOptionMap, + affectsSourceFile: true, + affectsEmit: true, + affectsBuildInfo: true, + affectsModuleResolution: true, + // The checker emits an error when it sees JSX but this option is not set in compilerOptions. + // This is effectively a semantic error, so mark this option as affecting semantic diagnostics + // so we know to refresh errors when this option is changed. + affectsSemanticDiagnostics: true, + paramType: Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_what_JSX_code_is_generated, + defaultValueDescription: void 0 + }, + { + name: "outFile", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: true, + paramType: Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + description: Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, + transpileOptionValue: void 0 + }, + { + name: "outDir", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: true, + paramType: Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + description: Diagnostics.Specify_an_output_folder_for_all_emitted_files + }, + { + name: "rootDir", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: true, + paramType: Diagnostics.LOCATION, + category: Diagnostics.Modules, + description: Diagnostics.Specify_the_root_folder_within_your_source_files, + defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files + }, + { + name: "composite", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + isTSConfigOnly: true, + category: Diagnostics.Projects, + transpileOptionValue: void 0, + defaultValueDescription: false, + description: Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references + }, + { + name: "tsBuildInfoFile", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + isFilePath: true, + paramType: Diagnostics.FILE, + category: Diagnostics.Projects, + transpileOptionValue: void 0, + defaultValueDescription: ".tsbuildinfo", + description: Diagnostics.Specify_the_path_to_tsbuildinfo_incremental_compilation_file + }, + { + name: "removeComments", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + defaultValueDescription: false, + description: Diagnostics.Disable_emitting_comments + }, + { + name: "importHelpers", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + affectsSourceFile: true, + category: Diagnostics.Emit, + description: Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, + defaultValueDescription: false + }, + { + name: "importsNotUsedAsValues", + type: new Map(Object.entries({ + remove: 0 /* Remove */, + preserve: 1 /* Preserve */, + error: 2 /* Error */ + })), + affectsEmit: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, + defaultValueDescription: 0 /* Remove */ + }, + { + name: "downlevelIteration", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, + defaultValueDescription: false + }, + { + name: "isolatedModules", + type: "boolean", + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports, + transpileOptionValue: true, + defaultValueDescription: false + }, + { + name: "verbatimModuleSyntax", + type: "boolean", + affectsEmit: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_in_the_output_file_s_format_based_on_the_module_setting, + defaultValueDescription: false + }, + { + name: "isolatedDeclarations", + type: "boolean", + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files, + defaultValueDescription: false, + affectsBuildInfo: true, + affectsSemanticDiagnostics: true + }, + { + name: "erasableSyntaxOnly", + type: "boolean", + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript, + defaultValueDescription: false, + affectsBuildInfo: true, + affectsSemanticDiagnostics: true + }, + { + name: "libReplacement", + type: "boolean", + affectsProgramStructure: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Enable_lib_replacement, + defaultValueDescription: true + }, + // Strict Type Checks + { + name: "strict", + type: "boolean", + // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here + // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. + // But we need to store `strict` in builf info, even though it won't be examined directly, so that the + // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_all_strict_type_checking_options, + defaultValueDescription: false + }, + { + name: "noImplicitAny", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + { + name: "strictNullChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.When_type_checking_take_into_account_null_and_undefined, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + { + name: "strictFunctionTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + { + name: "strictBindCallApply", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + { + name: "strictPropertyInitialization", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + { + name: "strictBuiltinIteratorReturn", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + { + name: "noImplicitThis", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + { + name: "useUnknownInCatchVariables", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + { + name: "alwaysStrict", + type: "boolean", + affectsSourceFile: true, + affectsEmit: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Ensure_use_strict_is_always_emitted, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + // Additional Checks + { + name: "noUnusedLocals", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, + defaultValueDescription: false + }, + { + name: "noUnusedParameters", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, + defaultValueDescription: false + }, + { + name: "exactOptionalPropertyTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, + defaultValueDescription: false + }, + { + name: "noImplicitReturns", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, + defaultValueDescription: false + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, + defaultValueDescription: false + }, + { + name: "noUncheckedIndexedAccess", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, + defaultValueDescription: false + }, + { + name: "noImplicitOverride", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, + defaultValueDescription: false + }, + { + name: "noPropertyAccessFromIndexSignature", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: false, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, + defaultValueDescription: false + }, + // Module Resolution + { + name: "moduleResolution", + type: new Map(Object.entries({ + // N.B. The first entry specifies the value shown in `tsc --init` + node10: 2 /* Node10 */, + node: 2 /* Node10 */, + classic: 1 /* Classic */, + node16: 3 /* Node16 */, + nodenext: 99 /* NodeNext */, + bundler: 100 /* Bundler */ + })), + deprecatedKeys: /* @__PURE__ */ new Set(["node"]), + affectsSourceFile: true, + affectsModuleResolution: true, + paramType: Diagnostics.STRATEGY, + category: Diagnostics.Modules, + description: Diagnostics.Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier, + defaultValueDescription: Diagnostics.module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node + }, + { + name: "baseUrl", + type: "string", + affectsModuleResolution: true, + isFilePath: true, + category: Diagnostics.Modules, + description: Diagnostics.Specify_the_base_directory_to_resolve_non_relative_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + affectsModuleResolution: true, + allowConfigDirTemplateSubstitution: true, + isTSConfigOnly: true, + category: Diagnostics.Modules, + description: Diagnostics.Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations, + transpileOptionValue: void 0 + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + allowConfigDirTemplateSubstitution: true, + category: Diagnostics.Modules, + description: Diagnostics.Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules, + transpileOptionValue: void 0, + defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files + }, + { + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + }, + affectsModuleResolution: true, + allowConfigDirTemplateSubstitution: true, + category: Diagnostics.Modules, + description: Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types + }, + { + name: "types", + type: "list", + element: { + name: "types", + type: "string" + }, + affectsProgramStructure: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Modules, + description: Diagnostics.Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file, + transpileOptionValue: void 0 + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, + defaultValueDescription: Diagnostics.module_system_or_esModuleInterop + }, + { + name: "esModuleInterop", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, + defaultValueDescription: false + }, + { + name: "preserveSymlinks", + type: "boolean", + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, + defaultValueDescription: false + }, + { + name: "allowUmdGlobalAccess", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Modules, + description: Diagnostics.Allow_accessing_UMD_globals_from_modules, + defaultValueDescription: false + }, + { + name: "moduleSuffixes", + type: "list", + element: { + name: "suffix", + type: "string" + }, + listPreserveFalsyValues: true, + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.List_of_file_name_suffixes_to_search_when_resolving_a_module + }, + { + name: "allowImportingTsExtensions", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Modules, + description: Diagnostics.Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noEmit_or_emitDeclarationOnly_to_be_set, + defaultValueDescription: false, + transpileOptionValue: void 0 + }, + { + name: "rewriteRelativeImportExtensions", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Modules, + description: Diagnostics.Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_in_output_files, + defaultValueDescription: false + }, + { + name: "resolvePackageJsonExports", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Use_the_package_json_exports_field_when_resolving_package_imports, + defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false + }, + { + name: "resolvePackageJsonImports", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Use_the_package_json_imports_field_when_resolving_imports, + defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false + }, + { + name: "customConditions", + type: "list", + element: { + name: "condition", + type: "string" + }, + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports + }, + { + name: "noUncheckedSideEffectImports", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Modules, + description: Diagnostics.Check_side_effect_imports, + defaultValueDescription: false + }, + // Source Maps + { + name: "sourceRoot", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + paramType: Diagnostics.LOCATION, + category: Diagnostics.Emit, + description: Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code + }, + { + name: "mapRoot", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + paramType: Diagnostics.LOCATION, + category: Diagnostics.Emit, + description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations + }, + { + name: "inlineSources", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, + defaultValueDescription: false + }, + // Experimental + { + name: "experimentalDecorators", + type: "boolean", + affectsEmit: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Enable_experimental_support_for_legacy_experimental_decorators, + defaultValueDescription: false + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, + defaultValueDescription: false + }, + // Advanced + { + name: "jsxFactory", + type: "string", + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h, + defaultValueDescription: "`React.createElement`" + }, + { + name: "jsxFragmentFactory", + type: "string", + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment, + defaultValueDescription: "React.Fragment" + }, + { + name: "jsxImportSource", + type: "string", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + affectsModuleResolution: true, + affectsSourceFile: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, + defaultValueDescription: "react" + }, + { + name: "resolveJsonModule", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Enable_importing_json_files, + defaultValueDescription: false + }, + { + name: "allowArbitraryExtensions", + type: "boolean", + affectsProgramStructure: true, + category: Diagnostics.Modules, + description: Diagnostics.Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present, + defaultValueDescription: false + }, + { + name: "out", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: false, + // This is intentionally broken to support compatibility with existing tsconfig files + // for correct behaviour, please use outFile + category: Diagnostics.Backwards_Compatibility, + paramType: Diagnostics.FILE, + transpileOptionValue: void 0, + description: Diagnostics.Deprecated_setting_Use_outFile_instead + }, + { + name: "reactNamespace", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, + defaultValueDescription: "`React`" + }, + { + name: "skipDefaultLibCheck", + type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsBuildInfo: true, + category: Diagnostics.Completeness, + description: Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, + defaultValueDescription: false + }, + { + name: "charset", + type: "string", + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files, + defaultValueDescription: "utf8" + }, + { + name: "emitBOM", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, + defaultValueDescription: false + }, + { + name: "newLine", + type: new Map(Object.entries({ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ + })), + affectsEmit: true, + affectsBuildInfo: true, + paramType: Diagnostics.NEWLINE, + category: Diagnostics.Emit, + description: Diagnostics.Set_the_newline_character_for_emitting_files, + defaultValueDescription: "lf" + }, + { + name: "noErrorTruncation", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Output_Formatting, + description: Diagnostics.Disable_truncating_types_in_error_messages, + defaultValueDescription: false + }, + { + name: "noLib", + type: "boolean", + category: Diagnostics.Language_and_Environment, + affectsProgramStructure: true, + description: Diagnostics.Disable_including_any_library_files_including_the_default_lib_d_ts, + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + transpileOptionValue: true, + defaultValueDescription: false + }, + { + name: "noResolve", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project, + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + transpileOptionValue: true, + defaultValueDescription: false + }, + { + name: "stripInternal", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, + defaultValueDescription: false + }, + { + name: "disableSizeLimit", + type: "boolean", + affectsProgramStructure: true, + category: Diagnostics.Editor_Support, + description: Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server, + defaultValueDescription: false + }, + { + name: "disableSourceOfProjectReferenceRedirect", + type: "boolean", + isTSConfigOnly: true, + category: Diagnostics.Projects, + description: Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, + defaultValueDescription: false + }, + { + name: "disableSolutionSearching", + type: "boolean", + isTSConfigOnly: true, + category: Diagnostics.Projects, + description: Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, + defaultValueDescription: false + }, + { + name: "disableReferencedProjectLoad", + type: "boolean", + isTSConfigOnly: true, + category: Diagnostics.Projects, + description: Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, + defaultValueDescription: false + }, + { + name: "noImplicitUseStrict", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, + defaultValueDescription: false + }, + { + name: "noEmitHelpers", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, + defaultValueDescription: false + }, + { + name: "noEmitOnError", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + transpileOptionValue: void 0, + description: Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, + defaultValueDescription: false + }, + { + name: "preserveConstEnums", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, + defaultValueDescription: false + }, + { + name: "declarationDir", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: true, + paramType: Diagnostics.DIRECTORY, + category: Diagnostics.Emit, + transpileOptionValue: void 0, + description: Diagnostics.Specify_the_output_directory_for_generated_declaration_files + }, + { + name: "skipLibCheck", + type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsBuildInfo: true, + category: Diagnostics.Completeness, + description: Diagnostics.Skip_type_checking_all_d_ts_files, + defaultValueDescription: false + }, + { + name: "allowUnusedLabels", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Disable_error_reporting_for_unused_labels, + defaultValueDescription: void 0 + }, + { + name: "allowUnreachableCode", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Disable_error_reporting_for_unreachable_code, + defaultValueDescription: void 0 + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, + defaultValueDescription: false + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, + defaultValueDescription: false + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Ensure_that_casing_is_correct_in_imports, + defaultValueDescription: true + }, + { + name: "maxNodeModuleJsDepth", + type: "number", + affectsModuleResolution: true, + category: Diagnostics.JavaScript_Support, + description: Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs, + defaultValueDescription: 0 + }, + { + name: "noStrictGenericChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + defaultValueDescription: false + }, + { + name: "useDefineForClassFields", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, + defaultValueDescription: Diagnostics.true_for_ES2022_and_above_including_ESNext + }, + { + name: "preserveValueImports", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, + defaultValueDescription: false + }, + { + name: "keyofStringsOnly", + type: "boolean", + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option, + defaultValueDescription: false + }, + { + // A list of plugins to load in the language service + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" + }, + description: Diagnostics.Specify_a_list_of_language_service_plugins_to_include, + category: Diagnostics.Editor_Support + }, + { + name: "moduleDetection", + type: new Map(Object.entries({ + auto: 2 /* Auto */, + legacy: 1 /* Legacy */, + force: 3 /* Force */ + })), + affectsSourceFile: true, + affectsModuleResolution: true, + description: Diagnostics.Control_what_method_is_used_to_detect_module_format_JS_files, + category: Diagnostics.Language_and_Environment, + defaultValueDescription: Diagnostics.auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules + }, + { + name: "ignoreDeprecations", + type: "string", + defaultValueDescription: void 0 + } +]; +var optionDeclarations = [ + ...commonOptionsWithBuild, + ...commandOptionsWithoutBuild +]; +var semanticDiagnosticsOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsSemanticDiagnostics); +var affectsEmitOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsEmit); +var affectsDeclarationPathOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsDeclarationPath); +var moduleResolutionOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsModuleResolution); +var sourceFileAffectingCompilerOptions = optionDeclarations.filter((option) => !!option.affectsSourceFile || !!option.affectsBindDiagnostics); +var optionsAffectingProgramStructure = optionDeclarations.filter((option) => !!option.affectsProgramStructure); +var transpileOptionValueCompilerOptions = optionDeclarations.filter((option) => hasProperty(option, "transpileOptionValue")); +var configDirTemplateSubstitutionOptions = optionDeclarations.filter( + (option) => option.allowConfigDirTemplateSubstitution || !option.isCommandLineOnly && option.isFilePath +); +var configDirTemplateSubstitutionWatchOptions = optionsForWatch.filter( + (option) => option.allowConfigDirTemplateSubstitution || !option.isCommandLineOnly && option.isFilePath +); +var commandLineOptionOfCustomType = optionDeclarations.filter(isCommandLineOptionOfCustomType); +function isCommandLineOptionOfCustomType(option) { + return !isString(option.type); +} +var tscBuildOption = { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, + defaultValueDescription: false +}; +var optionsForBuild = [ + tscBuildOption, + { + name: "verbose", + shortName: "v", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Enable_verbose_logging, + type: "boolean", + defaultValueDescription: false + }, + { + name: "dry", + shortName: "d", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean", + defaultValueDescription: false + }, + { + name: "force", + shortName: "f", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean", + defaultValueDescription: false + }, + { + name: "clean", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean", + defaultValueDescription: false + }, + { + name: "stopBuildOnErrors", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Skip_building_downstream_projects_on_error_in_upstream_project, + type: "boolean", + defaultValueDescription: false + } +]; +var buildOpts = [ + ...commonOptionsWithBuild, + ...optionsForBuild +]; +var typeAcquisitionDeclarations = [ + { + name: "enable", + type: "boolean", + defaultValueDescription: false + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + { + name: "disableFilenameBasedTypeAcquisition", + type: "boolean", + defaultValueDescription: false + } +]; +function createOptionNameMap(optionDeclarations2) { + const optionsNameMap = /* @__PURE__ */ new Map(); + const shortOptionNames = /* @__PURE__ */ new Map(); + forEach(optionDeclarations2, (option) => { + optionsNameMap.set(option.name.toLowerCase(), option); + if (option.shortName) { + shortOptionNames.set(option.shortName, option.name); + } + }); + return { optionsNameMap, shortOptionNames }; +} +var optionsNameMapCache; +function getOptionsNameMap() { + return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(optionDeclarations)); +} +var compilerOptionsAlternateMode = { + diagnostic: Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap +}; +var defaultInitCompilerOptions = { + module: 1 /* CommonJS */, + target: 3 /* ES2016 */, + strict: true, + esModuleInterop: true, + forceConsistentCasingInFileNames: true, + skipLibCheck: true +}; +function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + const namesOfType = arrayFrom(opt.type.keys()); + const stringNames = (opt.deprecatedKeys ? namesOfType.filter((k) => !opt.deprecatedKeys.has(k)) : namesOfType).map((key) => `'${key}'`).join(", "); + return createDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, stringNames); +} +function parseCustomTypeOption(opt, value, errors) { + return convertJsonOptionOfCustomType(opt, (value ?? "").trim(), errors); +} +function parseListTypeOption(opt, value = "", errors) { + value = value.trim(); + if (startsWith(value, "-")) { + return void 0; + } + if (opt.type === "listOrElement" && !value.includes(",")) { + return validateJsonOptionValue(opt, value, errors); + } + if (value === "") { + return []; + } + const values = value.split(","); + switch (opt.element.type) { + case "number": + return mapDefined(values, (v) => validateJsonOptionValue(opt.element, parseInt(v), errors)); + case "string": + return mapDefined(values, (v) => validateJsonOptionValue(opt.element, v || "", errors)); + case "boolean": + case "object": + return Debug.fail(`List of ${opt.element.type} is not yet supported.`); + default: + return mapDefined(values, (v) => parseCustomTypeOption(opt.element, v, errors)); + } +} +function getOptionName(option) { + return option.name; +} +function createUnknownOptionError(unknownOption, diagnostics, unknownOptionErrorText, node, sourceFile) { + var _a; + const otherOption = (_a = diagnostics.alternateMode) == null ? void 0 : _a.getOptionsNameMap().optionsNameMap.get(unknownOption.toLowerCase()); + if (otherOption) { + return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic( + sourceFile, + node, + otherOption !== tscBuildOption ? diagnostics.alternateMode.diagnostic : Diagnostics.Option_build_must_be_the_first_command_line_argument, + unknownOption + ); + } + const possibleOption = getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); + return possibleOption ? createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption); +} +function parseCommandLineWorker(diagnostics, commandLine, readFile) { + const options = {}; + let watchOptions; + const fileNames = []; + const errors = []; + parseStrings(commandLine); + return { + options, + watchOptions, + fileNames, + errors + }; + function parseStrings(args) { + let i = 0; + while (i < args.length) { + const s = args[i]; + i++; + if (s.charCodeAt(0) === 64 /* at */) { + parseResponseFile(s.slice(1)); + } else if (s.charCodeAt(0) === 45 /* minus */) { + const inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1); + const opt = getOptionDeclarationFromName( + diagnostics.getOptionsNameMap, + inputOptionName, + /*allowShort*/ + true + ); + if (opt) { + i = parseOptionValue(args, i, diagnostics, opt, options, errors); + } else { + const watchOpt = getOptionDeclarationFromName( + watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, + inputOptionName, + /*allowShort*/ + true + ); + if (watchOpt) { + i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors); + } else { + errors.push(createUnknownOptionError(inputOptionName, diagnostics, s)); + } + } + } else { + fileNames.push(s); + } + } + } + function parseResponseFile(fileName) { + const text = tryReadFile(fileName, readFile || ((fileName2) => sys.readFile(fileName2))); + if (!isString(text)) { + errors.push(text); + return; + } + const args = []; + let pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) pos++; + if (pos >= text.length) break; + const start = pos; + if (text.charCodeAt(start) === 34 /* doubleQuote */) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } else { + errors.push(createCompilerDiagnostic(Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } + } else { + while (text.charCodeAt(pos) > 32 /* space */) pos++; + args.push(text.substring(start, pos)); + } + } + parseStrings(args); + } +} +function parseOptionValue(args, i, diagnostics, opt, options, errors) { + if (opt.isTSConfigOnly) { + const optValue = args[i]; + if (optValue === "null") { + options[opt.name] = void 0; + i++; + } else if (opt.type === "boolean") { + if (optValue === "false") { + options[opt.name] = validateJsonOptionValue( + opt, + /*value*/ + false, + errors + ); + i++; + } else { + if (optValue === "true") i++; + errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name)); + } + } else { + errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name)); + if (optValue && !startsWith(optValue, "-")) i++; + } + } else { + if (!args[i] && opt.type !== "boolean") { + errors.push(createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt))); + } + if (args[i] !== "null") { + switch (opt.type) { + case "number": + options[opt.name] = validateJsonOptionValue(opt, parseInt(args[i]), errors); + i++; + break; + case "boolean": + const optValue = args[i]; + options[opt.name] = validateJsonOptionValue(opt, optValue !== "false", errors); + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = validateJsonOptionValue(opt, args[i] || "", errors); + i++; + break; + case "list": + const result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + case "listOrElement": + Debug.fail("listOrElement not supported here"); + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } else { + options[opt.name] = void 0; + i++; + } + } + return i; +} +var compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, + getOptionsNameMap, + optionDeclarations, + unknownOptionDiagnostic: Diagnostics.Unknown_compiler_option_0, + unknownDidYouMeanDiagnostic: Diagnostics.Unknown_compiler_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: Diagnostics.Compiler_option_0_expects_an_argument +}; +function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile); +} +function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort = false) { + optionName = optionName.toLowerCase(); + const { optionsNameMap, shortOptionNames } = getOptionNameMap(); + if (allowShort) { + const short = shortOptionNames.get(optionName); + if (short !== void 0) { + optionName = short; + } + } + return optionsNameMap.get(optionName); +} +var buildOptionsNameMapCache; +function getBuildOptionsNameMap() { + return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(buildOpts)); +} +var buildOptionsAlternateMode = { + diagnostic: Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap +}; +var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, + getOptionsNameMap: getBuildOptionsNameMap, + optionDeclarations: buildOpts, + unknownOptionDiagnostic: Diagnostics.Unknown_build_option_0, + unknownDidYouMeanDiagnostic: Diagnostics.Unknown_build_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: Diagnostics.Build_option_0_requires_a_value_of_type_1 +}; +function parseBuildCommand(commandLine) { + const { options, watchOptions, fileNames: projects, errors } = parseCommandLineWorker( + buildOptionsDidYouMeanDiagnostics, + commandLine + ); + const buildOptions = options; + if (projects.length === 0) { + projects.push("."); + } + if (buildOptions.clean && buildOptions.force) { + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions, watchOptions, projects, errors }; +} +function getDiagnosticText(message, ...args) { + return cast(createCompilerDiagnostic(message, ...args).messageText, isString); +} +function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { + const configFileText = tryReadFile(configFileName, (fileName) => host.readFile(fileName)); + if (!isString(configFileText)) { + host.onUnRecoverableConfigFileDiagnostic(configFileText); + return void 0; + } + const result = parseJsonText(configFileName, configFileText); + const cwd = host.getCurrentDirectory(); + result.path = toPath(configFileName, cwd, createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return parseJsonSourceFileConfigFileContent( + result, + host, + getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), + optionsToExtend, + getNormalizedAbsolutePath(configFileName, cwd), + /*resolutionStack*/ + void 0, + extraFileExtensions, + extendedConfigCache, + watchOptionsToExtend + ); +} +function parseConfigFileTextToJson(fileName, jsonText) { + const jsonSourceFile = parseJsonText(fileName, jsonText); + return { + config: convertConfigFileToObject( + jsonSourceFile, + jsonSourceFile.parseDiagnostics, + /*jsonConversionNotifier*/ + void 0 + ), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : void 0 + }; +} +function readJsonConfigFile(fileName, readFile) { + const textOrDiagnostic = tryReadFile(fileName, readFile); + return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] }; +} +function tryReadFile(fileName, readFile) { + let text; + try { + text = readFile(fileName); + } catch (e) { + return createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === void 0 ? createCompilerDiagnostic(Diagnostics.Cannot_read_file_0, fileName) : text; +} +function commandLineOptionsToMap(options) { + return arrayToMap(options, getOptionName); +} +var typeAcquisitionDidYouMeanDiagnostics = { + optionDeclarations: typeAcquisitionDeclarations, + unknownOptionDiagnostic: Diagnostics.Unknown_type_acquisition_option_0, + unknownDidYouMeanDiagnostic: Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1 +}; +var watchOptionsNameMapCache; +function getWatchOptionsNameMap() { + return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(optionsForWatch)); +} +var watchOptionsDidYouMeanDiagnostics = { + getOptionsNameMap: getWatchOptionsNameMap, + optionDeclarations: optionsForWatch, + unknownOptionDiagnostic: Diagnostics.Unknown_watch_option_0, + unknownDidYouMeanDiagnostic: Diagnostics.Unknown_watch_option_0_Did_you_mean_1, + optionTypeMismatchDiagnostic: Diagnostics.Watch_option_0_requires_a_value_of_type_1 +}; +var commandLineCompilerOptionsMapCache; +function getCommandLineCompilerOptionsMap() { + return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(optionDeclarations)); +} +var commandLineWatchOptionsMapCache; +function getCommandLineWatchOptionsMap() { + return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(optionsForWatch)); +} +var commandLineTypeAcquisitionMapCache; +function getCommandLineTypeAcquisitionMap() { + return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(typeAcquisitionDeclarations)); +} +var extendsOptionDeclaration = { + name: "extends", + type: "listOrElement", + element: { + name: "extends", + type: "string" + }, + category: Diagnostics.File_Management, + disallowNullOrUndefined: true +}; +var compilerOptionsDeclaration = { + name: "compilerOptions", + type: "object", + elementOptions: getCommandLineCompilerOptionsMap(), + extraKeyDiagnostics: compilerOptionsDidYouMeanDiagnostics +}; +var watchOptionsDeclaration = { + name: "watchOptions", + type: "object", + elementOptions: getCommandLineWatchOptionsMap(), + extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics +}; +var typeAcquisitionDeclaration = { + name: "typeAcquisition", + type: "object", + elementOptions: getCommandLineTypeAcquisitionMap(), + extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics +}; +var _tsconfigRootOptions; +function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === void 0) { + _tsconfigRootOptions = { + name: void 0, + // should never be needed since this is root + type: "object", + elementOptions: commandLineOptionsToMap([ + compilerOptionsDeclaration, + watchOptionsDeclaration, + typeAcquisitionDeclaration, + extendsOptionDeclaration, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + }, + category: Diagnostics.Projects + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + }, + category: Diagnostics.File_Management + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + }, + category: Diagnostics.File_Management, + defaultValueDescription: Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + }, + category: Diagnostics.File_Management, + defaultValueDescription: Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified + }, + compileOnSaveCommandLineOption + ]) + }; + } + return _tsconfigRootOptions; +} +function convertConfigFileToObject(sourceFile, errors, jsonConversionNotifier) { + var _a; + const rootExpression = (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression; + if (rootExpression && rootExpression.kind !== 210 /* ObjectLiteralExpression */) { + errors.push(createDiagnosticForNodeInSourceFile( + sourceFile, + rootExpression, + Diagnostics.The_root_value_of_a_0_file_must_be_an_object, + getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json" + )); + if (isArrayLiteralExpression(rootExpression)) { + const firstObject = find(rootExpression.elements, isObjectLiteralExpression); + if (firstObject) { + return convertToJson( + sourceFile, + firstObject, + errors, + /*returnValue*/ + true, + jsonConversionNotifier + ); + } + } + return {}; + } + return convertToJson( + sourceFile, + rootExpression, + errors, + /*returnValue*/ + true, + jsonConversionNotifier + ); +} +function convertToObject(sourceFile, errors) { + var _a; + return convertToJson( + sourceFile, + (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression, + errors, + /*returnValue*/ + true, + /*jsonConversionNotifier*/ + void 0 + ); +} +function convertToJson(sourceFile, rootExpression, errors, returnValue, jsonConversionNotifier) { + if (!rootExpression) { + return returnValue ? {} : void 0; + } + return convertPropertyValueToJson(rootExpression, jsonConversionNotifier == null ? void 0 : jsonConversionNotifier.rootOptions); + function convertObjectLiteralExpressionToJson(node, objectOption) { + var _a; + const result = returnValue ? {} : void 0; + for (const element of node.properties) { + if (element.kind !== 303 /* PropertyAssignment */) { + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element, Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.name, Diagnostics.String_literal_with_double_quotes_expected)); + } + const textOfKey = isComputedNonLiteralName(element.name) ? void 0 : getTextOfPropertyName(element.name); + const keyText = textOfKey && unescapeLeadingUnderscores(textOfKey); + const option = keyText ? (_a = objectOption == null ? void 0 : objectOption.elementOptions) == null ? void 0 : _a.get(keyText) : void 0; + const value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined") { + if (returnValue) { + result[keyText] = value; + } + jsonConversionNotifier == null ? void 0 : jsonConversionNotifier.onPropertySet(keyText, value, element, objectOption, option); + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + if (!returnValue) { + elements.forEach((element) => convertPropertyValueToJson(element, elementOption)); + return void 0; + } + return filter(elements.map((element) => convertPropertyValueToJson(element, elementOption)), (v) => v !== void 0); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 112 /* TrueKeyword */: + return true; + case 97 /* FalseKeyword */: + return false; + case 106 /* NullKeyword */: + return null; + // eslint-disable-line no-restricted-syntax + case 11 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.String_literal_with_double_quotes_expected)); + } + return valueExpression.text; + case 9 /* NumericLiteral */: + return Number(valueExpression.text); + case 224 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 41 /* MinusToken */ || valueExpression.operand.kind !== 9 /* NumericLiteral */) { + break; + } + return -Number(valueExpression.operand.text); + case 210 /* ObjectLiteralExpression */: + const objectLiteralExpression = valueExpression; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, option); + case 209 /* ArrayLiteralExpression */: + return convertArrayLiteralExpressionToJson( + valueExpression.elements, + option && option.element + ); + } + if (option) { + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } else { + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return void 0; + } + function isDoubleQuotedString(node) { + return isStringLiteral(node) && isStringDoubleQuoted(node, sourceFile); + } +} +function getCompilerOptionValueTypeString(option) { + return option.type === "listOrElement" ? `${getCompilerOptionValueTypeString(option.element)} or Array` : option.type === "list" ? "Array" : isString(option.type) ? option.type : "string"; +} +function isCompilerOptionsValue(option, value) { + if (option) { + if (isNullOrUndefined(value)) return !option.disallowNullOrUndefined; + if (option.type === "list") { + return isArray(value); + } + if (option.type === "listOrElement") { + return isArray(value) || isCompilerOptionsValue(option.element, value); + } + const expectedType = isString(option.type) ? option.type : "string"; + return typeof value === expectedType; + } + return false; +} +function convertToTSConfig(configParseResult, configFileName, host) { + var _a, _b, _c; + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + const files = map( + filter( + configParseResult.fileNames, + !((_b = (_a = configParseResult.options.configFile) == null ? void 0 : _a.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs) ? returnTrue : matchesSpecs( + configFileName, + configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, + configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, + host + ) + ), + (f) => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName) + ); + const pathOptions = { configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }; + const optionMap = serializeCompilerOptions(configParseResult.options, pathOptions); + const watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions); + const config = { + compilerOptions: { + ...optionMapToObject(optionMap), + showConfig: void 0, + configFile: void 0, + configFilePath: void 0, + help: void 0, + init: void 0, + listFiles: void 0, + listEmittedFiles: void 0, + project: void 0, + build: void 0, + version: void 0 + }, + watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), + references: map(configParseResult.projectReferences, (r) => ({ ...r, path: r.originalPath ? r.originalPath : "", originalPath: void 0 })), + files: length(files) ? files : void 0, + ...((_c = configParseResult.options.configFile) == null ? void 0 : _c.configFileSpecs) ? { + include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs + } : {}, + compileOnSave: !!configParseResult.compileOnSave ? true : void 0 + }; + const providedKeys = new Set(optionMap.keys()); + const impliedCompilerOptions = {}; + for (const option in computedOptions) { + if (!providedKeys.has(option) && optionDependsOn(option, providedKeys)) { + const implied = computedOptions[option].computeValue(configParseResult.options); + const defaultValue = computedOptions[option].computeValue({}); + if (implied !== defaultValue) { + impliedCompilerOptions[option] = computedOptions[option].computeValue(configParseResult.options); + } + } + } + assign(config.compilerOptions, optionMapToObject(serializeCompilerOptions(impliedCompilerOptions, pathOptions))); + return config; +} +function optionDependsOn(option, dependsOn) { + const seen = /* @__PURE__ */ new Set(); + return optionDependsOnRecursive(option); + function optionDependsOnRecursive(option2) { + var _a; + if (addToSeen(seen, option2)) { + return some((_a = computedOptions[option2]) == null ? void 0 : _a.dependencies, (dep) => dependsOn.has(dep) || optionDependsOnRecursive(dep)); + } + return false; + } +} +function optionMapToObject(optionMap) { + return Object.fromEntries(optionMap); +} +function filterSameAsDefaultInclude(specs) { + if (!length(specs)) return void 0; + if (length(specs) !== 1) return specs; + if (specs[0] === defaultIncludeSpec) return void 0; + return specs; +} +function matchesSpecs(path, includeSpecs, excludeSpecs, host) { + if (!includeSpecs) return returnTrue; + const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return (path2) => !(includeRe.test(path2) && !excludeRe.test(path2)); + } + return (path2) => !includeRe.test(path2); + } + if (excludeRe) { + return (path2) => excludeRe.test(path2); + } + return returnTrue; +} +function getCustomTypeMapOfCommandLineOption(optionDefinition) { + switch (optionDefinition.type) { + case "string": + case "number": + case "boolean": + case "object": + return void 0; + case "list": + case "listOrElement": + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + default: + return optionDefinition.type; + } +} +function getNameOfCompilerOptionValue(value, customTypeMap) { + return forEachEntry(customTypeMap, (mapValue, key) => { + if (mapValue === value) { + return key; + } + }); +} +function serializeCompilerOptions(options, pathOptions) { + return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); +} +function serializeWatchOptions(options) { + return serializeOptionBaseObject(options, getWatchOptionsNameMap()); +} +function serializeOptionBaseObject(options, { optionsNameMap }, pathOptions) { + const result = /* @__PURE__ */ new Map(); + const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + for (const name in options) { + if (hasProperty(options, name)) { + if (optionsNameMap.has(name) && (optionsNameMap.get(name).category === Diagnostics.Command_line_Options || optionsNameMap.get(name).category === Diagnostics.Output_Formatting)) { + continue; + } + const value = options[name]; + const optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + Debug.assert(optionDefinition.type !== "listOrElement"); + const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap) { + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(value, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)); + } else if (pathOptions && optionDefinition.type === "list" && optionDefinition.element.isFilePath) { + result.set(name, value.map((v) => getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(v, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName))); + } else { + result.set(name, value); + } + } else { + if (optionDefinition.type === "list") { + result.set(name, value.map((element) => getNameOfCompilerOptionValue(element, customTypeMap))); + } else { + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap)); + } + } + } + } + } + return result; +} +function getCompilerOptionsDiffValue(options, newLine) { + const compilerOptionsMap = getSerializedCompilerOption(options); + return getOverwrittenDefaultOptions(); + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function getOverwrittenDefaultOptions() { + const result = []; + const tab = makePadding(2); + commandOptionsWithoutBuild.forEach((cmd) => { + if (!compilerOptionsMap.has(cmd.name)) { + return; + } + const newValue = compilerOptionsMap.get(cmd.name); + const defaultValue = getDefaultValueForOption(cmd); + if (newValue !== defaultValue) { + result.push(`${tab}${cmd.name}: ${newValue}`); + } else if (hasProperty(defaultInitCompilerOptions, cmd.name)) { + result.push(`${tab}${cmd.name}: ${defaultValue}`); + } + }); + return result.join(newLine) + newLine; + } +} +function getSerializedCompilerOption(options) { + const compilerOptions = extend(options, defaultInitCompilerOptions); + return serializeCompilerOptions(compilerOptions); +} +function generateTSConfig(options, fileNames, newLine) { + const compilerOptionsMap = getSerializedCompilerOption(options); + return writeConfigurations(); + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function isAllowedOptionForOutput({ category, name, isCommandLineOnly }) { + const categoriesToSkip = [Diagnostics.Command_line_Options, Diagnostics.Editor_Support, Diagnostics.Compiler_Diagnostics, Diagnostics.Backwards_Compatibility, Diagnostics.Watch_and_Build_Modes, Diagnostics.Output_Formatting]; + return !isCommandLineOnly && category !== void 0 && (!categoriesToSkip.includes(category) || compilerOptionsMap.has(name)); + } + function writeConfigurations() { + const categorizedOptions = /* @__PURE__ */ new Map(); + categorizedOptions.set(Diagnostics.Projects, []); + categorizedOptions.set(Diagnostics.Language_and_Environment, []); + categorizedOptions.set(Diagnostics.Modules, []); + categorizedOptions.set(Diagnostics.JavaScript_Support, []); + categorizedOptions.set(Diagnostics.Emit, []); + categorizedOptions.set(Diagnostics.Interop_Constraints, []); + categorizedOptions.set(Diagnostics.Type_Checking, []); + categorizedOptions.set(Diagnostics.Completeness, []); + for (const option of optionDeclarations) { + if (isAllowedOptionForOutput(option)) { + let listForCategory = categorizedOptions.get(option.category); + if (!listForCategory) categorizedOptions.set(option.category, listForCategory = []); + listForCategory.push(option); + } + } + let marginLength = 0; + let seenKnownKeys = 0; + const entries = []; + categorizedOptions.forEach((options2, category) => { + if (entries.length !== 0) { + entries.push({ value: "" }); + } + entries.push({ value: `/* ${getLocaleSpecificMessage(category)} */` }); + for (const option of options2) { + let optionName; + if (compilerOptionsMap.has(option.name)) { + optionName = `"${option.name}": ${JSON.stringify(compilerOptionsMap.get(option.name))}${(seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","}`; + } else { + optionName = `// "${option.name}": ${JSON.stringify(getDefaultValueForOption(option))},`; + } + entries.push({ + value: optionName, + description: `/* ${option.description && getLocaleSpecificMessage(option.description) || option.name} */` + }); + marginLength = Math.max(optionName.length, marginLength); + } + }); + const tab = makePadding(2); + const result = []; + result.push(`{`); + result.push(`${tab}"compilerOptions": {`); + result.push(`${tab}${tab}/* ${getLocaleSpecificMessage(Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file)} */`); + result.push(""); + for (const entry of entries) { + const { value, description = "" } = entry; + result.push(value && `${tab}${tab}${value}${description && makePadding(marginLength - value.length + 2) + description}`); + } + if (fileNames.length) { + result.push(`${tab}},`); + result.push(`${tab}"files": [`); + for (let i = 0; i < fileNames.length; i++) { + result.push(`${tab}${tab}${JSON.stringify(fileNames[i])}${i === fileNames.length - 1 ? "" : ","}`); + } + result.push(`${tab}]`); + } else { + result.push(`${tab}}`); + } + result.push(`}`); + return result.join(newLine) + newLine; + } +} +function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + const result = {}; + const optionsNameMap = getOptionsNameMap().optionsNameMap; + for (const name in options) { + if (hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths( + optionsNameMap.get(name.toLowerCase()), + options[name], + toAbsolutePath + ); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; +} +function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option && !isNullOrUndefined(value)) { + if (option.type === "list") { + const values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } else if (option.isFilePath) { + return toAbsolutePath(value); + } + Debug.assert(option.type !== "listOrElement"); + } + return value; +} +function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName }); + const result = parseJsonConfigFileContentWorker( + /*json*/ + void 0, + sourceFile, + host, + basePath, + existingOptions, + existingWatchOptions, + configFileName, + resolutionStack, + extraFileExtensions, + extendedConfigCache + ); + (_b = tracing) == null ? void 0 : _b.pop(); + return result; +} +function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } +} +function isNullOrUndefined(x) { + return x === void 0 || x === null; +} +function directoryOfCombinedPath(fileName, basePath) { + return getDirectoryPath(getNormalizedAbsolutePath(fileName, basePath)); +} +var defaultIncludeSpec = "**/*"; +function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions = {}, existingWatchOptions, configFileName, resolutionStack = [], extraFileExtensions = [], extendedConfigCache) { + Debug.assert(json === void 0 && sourceFile !== void 0 || json !== void 0 && sourceFile === void 0); + const errors = []; + const parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache); + const { raw } = parsedConfig; + const options = handleOptionConfigDirTemplateSubstitution( + extend(existingOptions, parsedConfig.options || {}), + configDirTemplateSubstitutionOptions, + basePath + ); + const watchOptions = handleWatchOptionsConfigDirTemplateSubstitution( + existingWatchOptions && parsedConfig.watchOptions ? extend(existingWatchOptions, parsedConfig.watchOptions) : parsedConfig.watchOptions || existingWatchOptions, + basePath + ); + options.configFilePath = configFileName && normalizeSlashes(configFileName); + const basePathForFileNames = normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath); + const configFileSpecs = getConfigFileSpecs(); + if (sourceFile) sourceFile.configFileSpecs = configFileSpecs; + setConfigFileInOptions(options, sourceFile); + return { + options, + watchOptions, + fileNames: getFileNames(basePathForFileNames), + projectReferences: getProjectReferences(basePathForFileNames), + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw, + errors, + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + wildcardDirectories: getWildcardDirectories(configFileSpecs, basePathForFileNames, host.useCaseSensitiveFileNames), + compileOnSave: !!raw.compileOnSave + }; + function getConfigFileSpecs() { + const referencesOfRaw = getPropFromRaw("references", (element) => typeof element === "object", "object"); + const filesSpecs = toPropValue(getSpecsFromRaw("files")); + if (filesSpecs) { + const hasZeroOrNoReferences = referencesOfRaw === "no-prop" || isArray(referencesOfRaw) && referencesOfRaw.length === 0; + const hasExtends = hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + const fileName = configFileName || "tsconfig.json"; + const diagnosticMessage = Diagnostics.The_files_list_in_config_file_0_is_empty; + const nodeValue = forEachTsConfigPropArray(sourceFile, "files", (property) => property.initializer); + const error = createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, nodeValue, diagnosticMessage, fileName); + errors.push(error); + } else { + createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } + } + } + let includeSpecs = toPropValue(getSpecsFromRaw("include")); + const excludeOfRaw = getSpecsFromRaw("exclude"); + let isDefaultIncludeSpec = false; + let excludeSpecs = toPropValue(excludeOfRaw); + if (excludeOfRaw === "no-prop") { + const outDir = options.outDir; + const declarationDir = options.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = filter([outDir, declarationDir], (d) => !!d); + } + } + if (filesSpecs === void 0 && includeSpecs === void 0) { + includeSpecs = [defaultIncludeSpec]; + isDefaultIncludeSpec = true; + } + let validatedIncludeSpecsBeforeSubstitution, validatedExcludeSpecsBeforeSubstitution; + let validatedIncludeSpecs, validatedExcludeSpecs; + if (includeSpecs) { + validatedIncludeSpecsBeforeSubstitution = validateSpecs( + includeSpecs, + errors, + /*disallowTrailingRecursion*/ + true, + sourceFile, + "include" + ); + validatedIncludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate( + validatedIncludeSpecsBeforeSubstitution, + basePathForFileNames + ) || validatedIncludeSpecsBeforeSubstitution; + } + if (excludeSpecs) { + validatedExcludeSpecsBeforeSubstitution = validateSpecs( + excludeSpecs, + errors, + /*disallowTrailingRecursion*/ + false, + sourceFile, + "exclude" + ); + validatedExcludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate( + validatedExcludeSpecsBeforeSubstitution, + basePathForFileNames + ) || validatedExcludeSpecsBeforeSubstitution; + } + const validatedFilesSpecBeforeSubstitution = filter(filesSpecs, isString); + const validatedFilesSpec = getSubstitutedStringArrayWithConfigDirTemplate( + validatedFilesSpecBeforeSubstitution, + basePathForFileNames + ) || validatedFilesSpecBeforeSubstitution; + return { + filesSpecs, + includeSpecs, + excludeSpecs, + validatedFilesSpec, + validatedIncludeSpecs, + validatedExcludeSpecs, + validatedFilesSpecBeforeSubstitution, + validatedIncludeSpecsBeforeSubstitution, + validatedExcludeSpecsBeforeSubstitution, + isDefaultIncludeSpec + }; + } + function getFileNames(basePath2) { + const fileNames = getFileNamesFromConfigSpecs(configFileSpecs, basePath2, options, host, extraFileExtensions); + if (shouldReportNoInputFiles(fileNames, canJsonReportNoInputFiles(raw), resolutionStack)) { + errors.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + return fileNames; + } + function getProjectReferences(basePath2) { + let projectReferences; + const referencesOfRaw = getPropFromRaw("references", (element) => typeof element === "object", "object"); + if (isArray(referencesOfRaw)) { + for (const ref of referencesOfRaw) { + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } else { + (projectReferences || (projectReferences = [])).push({ + path: getNormalizedAbsolutePath(ref.path, basePath2), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + } + return projectReferences; + } + function toPropValue(specResult) { + return isArray(specResult) ? specResult : void 0; + } + function getSpecsFromRaw(prop) { + return getPropFromRaw(prop, isString, "string"); + } + function getPropFromRaw(prop, validateElement, elementTypeName) { + if (hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) { + if (isArray(raw[prop])) { + const result = raw[prop]; + if (!sourceFile && !every(result, validateElement)) { + errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName)); + } + return result; + } else { + createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, "Array"); + return "not-array"; + } + } + return "no-prop"; + } + function createCompilerDiagnosticOnlyIfJson(message, ...args) { + if (!sourceFile) { + errors.push(createCompilerDiagnostic(message, ...args)); + } + } +} +function handleWatchOptionsConfigDirTemplateSubstitution(watchOptions, basePath) { + return handleOptionConfigDirTemplateSubstitution(watchOptions, configDirTemplateSubstitutionWatchOptions, basePath); +} +function handleOptionConfigDirTemplateSubstitution(options, optionDeclarations2, basePath) { + if (!options) return options; + let result; + for (const option of optionDeclarations2) { + if (options[option.name] !== void 0) { + const value = options[option.name]; + switch (option.type) { + case "string": + Debug.assert(option.isFilePath); + if (startsWithConfigDirTemplate(value)) { + setOptionValue(option, getSubstitutedPathWithConfigDirTemplate(value, basePath)); + } + break; + case "list": + Debug.assert(option.element.isFilePath); + const listResult = getSubstitutedStringArrayWithConfigDirTemplate(value, basePath); + if (listResult) setOptionValue(option, listResult); + break; + case "object": + Debug.assert(option.name === "paths"); + const objectResult = getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(value, basePath); + if (objectResult) setOptionValue(option, objectResult); + break; + default: + Debug.fail("option type not supported"); + } + } + } + return result || options; + function setOptionValue(option, value) { + (result ?? (result = assign({}, options)))[option.name] = value; + } +} +var configDirTemplate = `\${configDir}`; +function startsWithConfigDirTemplate(value) { + return isString(value) && startsWith( + value, + configDirTemplate, + /*ignoreCase*/ + true + ); +} +function getSubstitutedPathWithConfigDirTemplate(value, basePath) { + return getNormalizedAbsolutePath(value.replace(configDirTemplate, "./"), basePath); +} +function getSubstitutedStringArrayWithConfigDirTemplate(list, basePath) { + if (!list) return list; + let result; + list.forEach((element, index) => { + if (!startsWithConfigDirTemplate(element)) return; + (result ?? (result = list.slice()))[index] = getSubstitutedPathWithConfigDirTemplate(element, basePath); + }); + return result; +} +function getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(mapLike, basePath) { + let result; + const ownKeys = getOwnKeys(mapLike); + ownKeys.forEach((key) => { + if (!isArray(mapLike[key])) return; + const subStitution = getSubstitutedStringArrayWithConfigDirTemplate(mapLike[key], basePath); + if (!subStitution) return; + (result ?? (result = assign({}, mapLike)))[key] = subStitution; + }); + return result; +} +function isErrorNoInputFiles(error) { + return error.code === Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; +} +function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }, configFileName) { + return createCompilerDiagnostic( + Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + configFileName || "tsconfig.json", + JSON.stringify(includeSpecs || []), + JSON.stringify(excludeSpecs || []) + ); +} +function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) { + return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); +} +function isSolutionConfig(config) { + return !config.fileNames.length && hasProperty(config.raw, "references"); +} +function canJsonReportNoInputFiles(raw) { + return !hasProperty(raw, "files") && !hasProperty(raw, "references"); +} +function updateErrorForNoInputFiles(fileNames, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + const existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } else { + filterMutate(configParseDiagnostics, (error) => !isErrorNoInputFiles(error)); + } + return existingErrors !== configParseDiagnostics.length; +} +function isSuccessfulParsedTsconfig(value) { + return !!value.options; +} +function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) { + var _a; + basePath = normalizeSlashes(basePath); + const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath); + if (resolutionStack.includes(resolvedPath)) { + errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))); + return { raw: json || convertToObject(sourceFile, errors) }; + } + const ownConfig = json ? parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); + if ((_a = ownConfig.options) == null ? void 0 : _a.paths) { + ownConfig.options.pathsBasePath = basePath; + } + if (ownConfig.extendedConfigPath) { + resolutionStack = resolutionStack.concat([resolvedPath]); + const result = { options: {} }; + if (isString(ownConfig.extendedConfigPath)) { + applyExtendedConfig(result, ownConfig.extendedConfigPath); + } else { + ownConfig.extendedConfigPath.forEach((extendedConfigPath) => applyExtendedConfig(result, extendedConfigPath)); + } + if (result.include) ownConfig.raw.include = result.include; + if (result.exclude) ownConfig.raw.exclude = result.exclude; + if (result.files) ownConfig.raw.files = result.files; + if (ownConfig.raw.compileOnSave === void 0 && result.compileOnSave) ownConfig.raw.compileOnSave = result.compileOnSave; + if (sourceFile && result.extendedSourceFiles) sourceFile.extendedSourceFiles = arrayFrom(result.extendedSourceFiles.keys()); + ownConfig.options = assign(result.options, ownConfig.options); + ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ? assignWatchOptions(result, ownConfig.watchOptions) : ownConfig.watchOptions || result.watchOptions; + } + return ownConfig; + function applyExtendedConfig(result, extendedConfigPath) { + const extendedConfig = getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache, result); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + const extendsRaw = extendedConfig.raw; + let relativeDifference; + const setPropertyInResultIfNotUndefined = (propertyName) => { + if (ownConfig.raw[propertyName]) return; + if (extendsRaw[propertyName]) { + result[propertyName] = map(extendsRaw[propertyName], (path) => startsWithConfigDirTemplate(path) || isRootedDiskPath(path) ? path : combinePaths( + relativeDifference || (relativeDifference = convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames))), + path + )); + } + }; + setPropertyInResultIfNotUndefined("include"); + setPropertyInResultIfNotUndefined("exclude"); + setPropertyInResultIfNotUndefined("files"); + if (extendsRaw.compileOnSave !== void 0) { + result.compileOnSave = extendsRaw.compileOnSave; + } + assign(result.options, extendedConfig.options); + result.watchOptions = result.watchOptions && extendedConfig.watchOptions ? assignWatchOptions(result, extendedConfig.watchOptions) : result.watchOptions || extendedConfig.watchOptions; + } + } + function assignWatchOptions(result, watchOptions) { + if (result.watchOptionsCopied) return assign(result.watchOptions, watchOptions); + result.watchOptionsCopied = true; + return assign({}, result.watchOptions, watchOptions); + } +} +function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { + if (hasProperty(json, "excludes")) { + errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + const options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + const typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition, basePath, errors, configFileName); + const watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + const extendedConfigPath = json.extends || json.extends === "" ? getExtendsConfigPathOrArray(json.extends, host, basePath, configFileName, errors) : void 0; + return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath }; +} +function getExtendsConfigPathOrArray(value, host, basePath, configFileName, errors, propertyAssignment, valueExpression, sourceFile) { + let extendedConfigPath; + const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + if (isString(value)) { + extendedConfigPath = getExtendsConfigPath( + value, + host, + newBase, + errors, + valueExpression, + sourceFile + ); + } else if (isArray(value)) { + extendedConfigPath = []; + for (let index = 0; index < value.length; index++) { + const fileName = value[index]; + if (isString(fileName)) { + extendedConfigPath = append( + extendedConfigPath, + getExtendsConfigPath( + fileName, + host, + newBase, + errors, + valueExpression == null ? void 0 : valueExpression.elements[index], + sourceFile + ) + ); + } else { + convertJsonOption(extendsOptionDeclaration.element, value, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile); + } + } + } else { + convertJsonOption(extendsOptionDeclaration, value, basePath, errors, propertyAssignment, valueExpression, sourceFile); + } + return extendedConfigPath; +} +function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { + const options = getDefaultCompilerOptions(configFileName); + let typeAcquisition; + let watchOptions; + let extendedConfigPath; + let rootCompilerOptions; + const rootOptions = getTsconfigRootOptionsMap(); + const json = convertConfigFileToObject( + sourceFile, + errors, + { rootOptions, onPropertySet } + ); + if (!typeAcquisition) { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + if (rootCompilerOptions && json && json.compilerOptions === void 0) { + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, rootCompilerOptions[0], Diagnostics._0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file, getTextOfPropertyName(rootCompilerOptions[0]))); + } + return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath }; + function onPropertySet(keyText, value, propertyAssignment, parentOption, option) { + if (option && option !== extendsOptionDeclaration) value = convertJsonOption(option, value, basePath, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); + if (parentOption == null ? void 0 : parentOption.name) { + if (option) { + let currentOption; + if (parentOption === compilerOptionsDeclaration) currentOption = options; + else if (parentOption === watchOptionsDeclaration) currentOption = watchOptions ?? (watchOptions = {}); + else if (parentOption === typeAcquisitionDeclaration) currentOption = typeAcquisition ?? (typeAcquisition = getDefaultTypeAcquisition(configFileName)); + else Debug.fail("Unknown option"); + currentOption[option.name] = value; + } else if (keyText && (parentOption == null ? void 0 : parentOption.extraKeyDiagnostics)) { + if (parentOption.elementOptions) { + errors.push(createUnknownOptionError( + keyText, + parentOption.extraKeyDiagnostics, + /*unknownOptionErrorText*/ + void 0, + propertyAssignment.name, + sourceFile + )); + } else { + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, parentOption.extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); + } + } + } else if (parentOption === rootOptions) { + if (option === extendsOptionDeclaration) { + extendedConfigPath = getExtendsConfigPathOrArray(value, host, basePath, configFileName, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); + } else if (!option) { + if (keyText === "excludes") { + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + if (find(commandOptionsWithoutBuild, (opt) => opt.name === keyText)) { + rootCompilerOptions = append(rootCompilerOptions, propertyAssignment.name); + } + } + } + } +} +function getExtendsConfigPath(extendedConfig, host, basePath, errors, valueExpression, sourceFile) { + extendedConfig = normalizeSlashes(extendedConfig); + if (isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, "./") || startsWith(extendedConfig, "../")) { + let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = `${extendedConfigPath}.json`; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig)); + return void 0; + } + } + return extendedConfigPath; + } + const resolved = nodeNextJsonConfigResolver(extendedConfig, combinePaths(basePath, "tsconfig.json"), host); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + if (extendedConfig === "") { + errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_cannot_be_given_an_empty_string, "extends")); + } else { + errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig)); + } + return void 0; +} +function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache, result) { + const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toFileNameLowerCase(extendedConfigPath); + let value; + let extendedResult; + let extendedConfig; + if (extendedConfigCache && (value = extendedConfigCache.get(path))) { + ({ extendedResult, extendedConfig } = value); + } else { + extendedResult = readJsonConfigFile(extendedConfigPath, (path2) => host.readFile(path2)); + if (!extendedResult.parseDiagnostics.length) { + extendedConfig = parseConfig( + /*json*/ + void 0, + extendedResult, + host, + getDirectoryPath(extendedConfigPath), + getBaseFileName(extendedConfigPath), + resolutionStack, + errors, + extendedConfigCache + ); + } + if (extendedConfigCache) { + extendedConfigCache.set(path, { extendedResult, extendedConfig }); + } + } + if (sourceFile) { + (result.extendedSourceFiles ?? (result.extendedSourceFiles = /* @__PURE__ */ new Set())).add(extendedResult.fileName); + if (extendedResult.extendedSourceFiles) { + for (const extenedSourceFile of extendedResult.extendedSourceFiles) { + result.extendedSourceFiles.add(extenedSourceFile); + } + } + } + if (extendedResult.parseDiagnostics.length) { + errors.push(...extendedResult.parseDiagnostics); + return void 0; + } + return extendedConfig; +} +function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) { + return false; + } + const result = convertJsonOption(compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); + return typeof result === "boolean" && result; +} +function getDefaultCompilerOptions(configFileName) { + const options = configFileName && getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {}; + return options; +} +function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + const options = getDefaultCompilerOptions(configFileName); + convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, compilerOptionsDidYouMeanDiagnostics, errors); + if (configFileName) { + options.configFilePath = normalizeSlashes(configFileName); + } + return options; +} +function getDefaultTypeAcquisition(configFileName) { + return { enable: !!configFileName && getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; +} +function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + const options = getDefaultTypeAcquisition(configFileName); + convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), jsonOptions, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors); + return options; +} +function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) { + return convertOptionsFromJson( + getCommandLineWatchOptionsMap(), + jsonOptions, + basePath, + /*defaultOptions*/ + void 0, + watchOptionsDidYouMeanDiagnostics, + errors + ); +} +function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) { + if (!jsonOptions) { + return; + } + for (const id in jsonOptions) { + const opt = optionsNameMap.get(id); + if (opt) { + (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); + } else { + errors.push(createUnknownOptionError(id, diagnostics)); + } + } + return defaultOptions; +} +function createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, message, ...args) { + return sourceFile && node ? createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args) : createCompilerDiagnostic(message, ...args); +} +function convertJsonOption(opt, value, basePath, errors, propertyAssignment, valueExpression, sourceFile) { + if (opt.isCommandLineOnly) { + errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, propertyAssignment == null ? void 0 : propertyAssignment.name, Diagnostics.Option_0_can_only_be_specified_on_command_line, opt.name)); + return void 0; + } + if (isCompilerOptionsValue(opt, value)) { + const optType = opt.type; + if (optType === "list" && isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors, propertyAssignment, valueExpression, sourceFile); + } else if (optType === "listOrElement") { + return isArray(value) ? convertJsonOptionOfListType(opt, value, basePath, errors, propertyAssignment, valueExpression, sourceFile) : convertJsonOption(opt.element, value, basePath, errors, propertyAssignment, valueExpression, sourceFile); + } else if (!isString(opt.type)) { + return convertJsonOptionOfCustomType(opt, value, errors, valueExpression, sourceFile); + } + const validatedValue = validateJsonOptionValue(opt, value, errors, valueExpression, sourceFile); + return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue); + } else { + errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } +} +function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = normalizeSlashes(value); + value = !startsWithConfigDirTemplate(value) ? getNormalizedAbsolutePath(value, basePath) : value; + if (value === "") { + value = "."; + } + } + return value; +} +function validateJsonOptionValue(opt, value, errors, valueExpression, sourceFile) { + var _a; + if (isNullOrUndefined(value)) return void 0; + const d = (_a = opt.extraValidation) == null ? void 0 : _a.call(opt, value); + if (!d) return value; + errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, ...d)); + return void 0; +} +function convertJsonOptionOfCustomType(opt, value, errors, valueExpression, sourceFile) { + if (isNullOrUndefined(value)) return void 0; + const key = value.toLowerCase(); + const val = opt.type.get(key); + if (val !== void 0) { + return validateJsonOptionValue(opt, val, errors, valueExpression, sourceFile); + } else { + errors.push(createDiagnosticForInvalidCustomType(opt, (message, ...args) => createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, message, ...args))); + } +} +function convertJsonOptionOfListType(option, values, basePath, errors, propertyAssignment, valueExpression, sourceFile) { + return filter(map(values, (v, index) => convertJsonOption(option.element, v, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile)), (v) => option.listPreserveFalsyValues ? true : !!v); +} +var invalidTrailingRecursionPattern = /(?:^|\/)\*\*\/?$/; +var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; +function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions = emptyArray) { + basePath = normalizePath(basePath); + const keyMapper = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + const literalFileMap = /* @__PURE__ */ new Map(); + const wildcardFileMap = /* @__PURE__ */ new Map(); + const wildCardJsonFileMap = /* @__PURE__ */ new Map(); + const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = configFileSpecs; + const supportedExtensions = getSupportedExtensions(options, extraFileExtensions); + const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + if (validatedFilesSpec) { + for (const fileName of validatedFilesSpec) { + const file = getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file), file); + } + } + let jsonOnlyIncludeRegexes; + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + for (const file of host.readDirectory( + basePath, + flatten(supportedExtensionsWithJsonIfResolveJsonModule), + validatedExcludeSpecs, + validatedIncludeSpecs, + /*depth*/ + void 0 + )) { + if (fileExtensionIs(file, ".json" /* Json */)) { + if (!jsonOnlyIncludeRegexes) { + const includes = validatedIncludeSpecs.filter((s) => endsWith(s, ".json" /* Json */)); + const includeFilePatterns = map(getRegularExpressionsForWildcards(includes, basePath, "files"), (pattern) => `^${pattern}$`); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, host.useCaseSensitiveFileNames)) : emptyArray; + } + const includeIndex = findIndex(jsonOnlyIncludeRegexes, (re) => re.test(file)); + if (includeIndex !== -1) { + const key2 = keyMapper(file); + if (!literalFileMap.has(key2) && !wildCardJsonFileMap.has(key2)) { + wildCardJsonFileMap.set(key2, file); + } + } + continue; + } + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + const key = keyMapper(file); + if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { + wildcardFileMap.set(key, file); + } + } + } + const literalFiles = arrayFrom(literalFileMap.values()); + const wildcardFiles = arrayFrom(wildcardFileMap.values()); + return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())); +} +function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) { + const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; + if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; + basePath = normalizePath(basePath); + const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2); + if (validatedFilesSpec) { + for (const fileName of validatedFilesSpec) { + if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false; + } + } + return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath); +} +function invalidDotDotAfterRecursiveWildcard(s) { + const wildcardIndex = startsWith(s, "**/") ? 0 : s.indexOf("/**/"); + if (wildcardIndex === -1) { + return false; + } + const lastDotIndex = endsWith(s, "/..") ? s.length : s.lastIndexOf("/../"); + return lastDotIndex > wildcardIndex; +} +function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) { + return matchesExcludeWorker( + pathToCheck, + filter(excludeSpecs, (spec) => !invalidDotDotAfterRecursiveWildcard(spec)), + useCaseSensitiveFileNames2, + currentDirectory + ); +} +function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) { + const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); + const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2); + if (!excludeRegex) return false; + if (excludeRegex.test(pathToCheck)) return true; + return !hasExtension(pathToCheck) && excludeRegex.test(ensureTrailingDirectorySeparator(pathToCheck)); +} +function validateSpecs(specs, errors, disallowTrailingRecursion, jsonSourceFile, specKey) { + return specs.filter((spec) => { + if (!isString(spec)) return false; + const diag2 = specToDiagnostic(spec, disallowTrailingRecursion); + if (diag2 !== void 0) { + errors.push(createDiagnostic(...diag2)); + } + return diag2 === void 0; + }); + function createDiagnostic(message, spec) { + const element = getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(jsonSourceFile, element, message, spec); + } +} +function specToDiagnostic(spec, disallowTrailingRecursion) { + Debug.assert(typeof spec === "string"); + if (disallowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + return [Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec]; + } else if (invalidDotDotAfterRecursiveWildcard(spec)) { + return [Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec]; + } +} +function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, basePath, useCaseSensitiveFileNames2) { + const rawExcludeRegex = getRegularExpressionForWildcard(exclude, basePath, "exclude"); + const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames2 ? "" : "i"); + const wildcardDirectories = {}; + const wildCardKeyToPath = /* @__PURE__ */ new Map(); + if (include !== void 0) { + const recursiveKeys = []; + for (const file of include) { + const spec = normalizePath(combinePaths(basePath, file)); + if (excludeRegex && excludeRegex.test(spec)) { + continue; + } + const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2); + if (match) { + const { key, path, flags } = match; + const existingPath = wildCardKeyToPath.get(key); + const existingFlags = existingPath !== void 0 ? wildcardDirectories[existingPath] : void 0; + if (existingFlags === void 0 || existingFlags < flags) { + wildcardDirectories[existingPath !== void 0 ? existingPath : path] = flags; + if (existingPath === void 0) wildCardKeyToPath.set(key, path); + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + for (const path in wildcardDirectories) { + if (hasProperty(wildcardDirectories, path)) { + for (const recursiveKey of recursiveKeys) { + const key = toCanonicalKey(path, useCaseSensitiveFileNames2); + if (key !== recursiveKey && containsPath(recursiveKey, key, basePath, !useCaseSensitiveFileNames2)) { + delete wildcardDirectories[path]; + } + } + } + } + } + return wildcardDirectories; +} +function toCanonicalKey(path, useCaseSensitiveFileNames2) { + return useCaseSensitiveFileNames2 ? path : toFileNameLowerCase(path); +} +function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2) { + const match = wildcardDirectoryPattern.exec(spec); + if (match) { + const questionWildcardIndex = spec.indexOf("?"); + const starWildcardIndex = spec.indexOf("*"); + const lastDirectorySeperatorIndex = spec.lastIndexOf(directorySeparator); + return { + key: toCanonicalKey(match[0], useCaseSensitiveFileNames2), + path: match[0], + flags: questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex || starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) { + const path = removeTrailingDirectorySeparator(spec); + return { + key: toCanonicalKey(path, useCaseSensitiveFileNames2), + path, + flags: 1 /* Recursive */ + }; + } + return void 0; +} +function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + const extensionGroup = forEach(extensions, (group2) => fileExtensionIsOneOf(file, group2) ? group2 : void 0); + if (!extensionGroup) { + return false; + } + for (const ext of extensionGroup) { + if (fileExtensionIs(file, ext) && (ext !== ".ts" /* Ts */ || !fileExtensionIs(file, ".d.ts" /* Dts */))) { + return false; + } + const higherPriorityPath = keyMapper(changeExtension(file, ext)); + if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { + if (ext === ".d.ts" /* Dts */ && (fileExtensionIs(file, ".js" /* Js */) || fileExtensionIs(file, ".jsx" /* Jsx */))) { + continue; + } + return true; + } + } + return false; +} +function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + const extensionGroup = forEach(extensions, (group2) => fileExtensionIsOneOf(file, group2) ? group2 : void 0); + if (!extensionGroup) { + return; + } + for (let i = extensionGroup.length - 1; i >= 0; i--) { + const ext = extensionGroup[i]; + if (fileExtensionIs(file, ext)) { + return; + } + const lowerPriorityPath = keyMapper(changeExtension(file, ext)); + wildcardFiles.delete(lowerPriorityPath); + } +} +function getDefaultValueForOption(option) { + switch (option.type) { + case "number": + return 1; + case "boolean": + return true; + case "string": + const defaultValue = option.defaultValueDescription; + return option.isFilePath ? `./${defaultValue && typeof defaultValue === "string" ? defaultValue : ""}` : ""; + case "list": + return []; + case "listOrElement": + return getDefaultValueForOption(option.element); + case "object": + return {}; + default: + const value = firstOrUndefinedIterator(option.type.keys()); + if (value !== void 0) return value; + return Debug.fail("Expected 'option.type' to have entries."); + } +} + +// src/compiler/moduleNameResolver.ts +function trace(host, message, ...args) { + host.trace(formatMessage(message, ...args)); +} +function isTraceEnabled(compilerOptions, host) { + return !!compilerOptions.traceResolution && host.trace !== void 0; +} +function withPackageId(packageInfo, r, state) { + let packageId; + if (r && packageInfo) { + const packageJsonContent = packageInfo.contents.packageJsonContent; + if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") { + packageId = { + name: packageJsonContent.name, + subModuleName: r.path.slice(packageInfo.packageDirectory.length + directorySeparator.length), + version: packageJsonContent.version, + peerDependencies: getPeerDependenciesOfPackageJsonInfo(packageInfo, state) + }; + } + } + return r && { path: r.path, extension: r.ext, packageId, resolvedUsingTsExtension: r.resolvedUsingTsExtension }; +} +function noPackageId(r) { + return withPackageId( + /*packageInfo*/ + void 0, + r, + /*state*/ + void 0 + ); +} +function removeIgnoredPackageId(r) { + if (r) { + Debug.assert(r.packageId === void 0); + return { path: r.path, ext: r.extension, resolvedUsingTsExtension: r.resolvedUsingTsExtension }; + } +} +function formatExtensions(extensions) { + const result = []; + if (extensions & 1 /* TypeScript */) result.push("TypeScript"); + if (extensions & 2 /* JavaScript */) result.push("JavaScript"); + if (extensions & 4 /* Declaration */) result.push("Declaration"); + if (extensions & 8 /* Json */) result.push("JSON"); + return result.join(", "); +} +function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return void 0; + } + Debug.assert(extensionIsTS(resolved.extension)); + return { fileName: resolved.path, packageId: resolved.packageId }; +} +function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, cache, alternateResult) { + if (!state.resultFromCache && !state.compilerOptions.preserveSymlinks && resolved && isExternalLibraryImport && !resolved.originalPath && !isExternalModuleNameRelative(moduleName)) { + const { resolvedFileName, originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled); + if (originalPath) resolved = { ...resolved, path: resolvedFileName, originalPath }; + } + return createResolvedModuleWithFailedLookupLocations( + resolved, + isExternalLibraryImport, + failedLookupLocations, + affectingLocations, + diagnostics, + state.resultFromCache, + cache, + alternateResult + ); +} +function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache, cache, alternateResult) { + if (resultFromCache) { + if (!(cache == null ? void 0 : cache.isReadonly)) { + resultFromCache.failedLookupLocations = updateResolutionField(resultFromCache.failedLookupLocations, failedLookupLocations); + resultFromCache.affectingLocations = updateResolutionField(resultFromCache.affectingLocations, affectingLocations); + resultFromCache.resolutionDiagnostics = updateResolutionField(resultFromCache.resolutionDiagnostics, diagnostics); + return resultFromCache; + } else { + return { + ...resultFromCache, + failedLookupLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.failedLookupLocations, failedLookupLocations), + affectingLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.affectingLocations, affectingLocations), + resolutionDiagnostics: initializeResolutionFieldForReadonlyCache(resultFromCache.resolutionDiagnostics, diagnostics) + }; + } + } + return { + resolvedModule: resolved && { + resolvedFileName: resolved.path, + originalPath: resolved.originalPath === true ? void 0 : resolved.originalPath, + extension: resolved.extension, + isExternalLibraryImport, + packageId: resolved.packageId, + resolvedUsingTsExtension: !!resolved.resolvedUsingTsExtension + }, + failedLookupLocations: initializeResolutionField(failedLookupLocations), + affectingLocations: initializeResolutionField(affectingLocations), + resolutionDiagnostics: initializeResolutionField(diagnostics), + alternateResult + }; +} +function initializeResolutionField(value) { + return value.length ? value : void 0; +} +function updateResolutionField(to, value) { + if (!(value == null ? void 0 : value.length)) return to; + if (!(to == null ? void 0 : to.length)) return value; + to.push(...value); + return to; +} +function initializeResolutionFieldForReadonlyCache(fromCache, value) { + if (!(fromCache == null ? void 0 : fromCache.length)) return initializeResolutionField(value); + if (!value.length) return fromCache.slice(); + return [...fromCache, ...value]; +} +function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + const value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; +} +function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + const fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === void 0) { + return; + } + if (!fileName) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_had_a_falsy_0_field, fieldName); + } + return; + } + const path = normalizePath(combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; +} +function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); +} +function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); +} +function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); +} +function readPackageJsonTypesVersionsField(jsonContent, state) { + const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === void 0) return; + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; +} +function readPackageJsonTypesVersionPaths(jsonContent, state) { + const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === void 0) return; + if (state.traceEnabled) { + for (const key in typesVersions) { + if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + const result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor); + } + return; + } + const { version: bestVersionKey, paths: bestVersionPaths } = result; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths); + } + return; + } + return result; +} +var typeScriptVersion; +function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) typeScriptVersion = new Version(version); + for (const key in typesVersions) { + if (!hasProperty(typesVersions, key)) continue; + const keyRange = VersionRange.tryParse(key); + if (keyRange === void 0) { + continue; + } + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; + } + } +} +function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + let currentDirectory; + if (options.configFilePath) { + currentDirectory = getDirectoryPath(options.configFilePath); + } else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== void 0) { + return getDefaultTypeRoots(currentDirectory); + } +} +function getDefaultTypeRoots(currentDirectory) { + let typeRoots; + forEachAncestorDirectory(normalizePath(currentDirectory), (directory) => { + const atTypes = combinePaths(directory, nodeModulesAtTypes); + (typeRoots ?? (typeRoots = [])).push(atTypes); + }); + return typeRoots; +} +var nodeModulesAtTypes = combinePaths("node_modules", "@types"); +function arePathsEqual(path1, path2, host) { + const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; + return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */; +} +function getOriginalAndResolvedFileName(fileName, host, traceEnabled) { + const resolvedFileName = realPath(fileName, host, traceEnabled); + const pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); + return { + // If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedFileName: pathsAreEqual ? fileName : resolvedFileName, + originalPath: pathsAreEqual ? void 0 : fileName + }; +} +function getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState) { + const nameForLookup = endsWith(typeRoot, "/node_modules/@types") || endsWith(typeRoot, "/node_modules/@types/") ? mangleScopedPackageNameWithTrace(typeReferenceDirectiveName, moduleResolutionState) : typeReferenceDirectiveName; + return combinePaths(typeRoot, nameForLookup); +} +function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache, resolutionMode) { + Debug.assert(typeof typeReferenceDirectiveName === "string", "Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself."); + const traceEnabled = isTraceEnabled(options, host); + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } + const containingDirectory = containingFile ? getDirectoryPath(containingFile) : void 0; + let result = containingDirectory ? cache == null ? void 0 : cache.getFromDirectoryCache(typeReferenceDirectiveName, resolutionMode, containingDirectory, redirectedReference) : void 0; + if (!result && containingDirectory && !isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = cache == null ? void 0 : cache.getFromNonRelativeNameCache(typeReferenceDirectiveName, resolutionMode, containingDirectory, redirectedReference); + } + if (result) { + if (traceEnabled) { + trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } + const typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === void 0) { + if (typeRoots === void 0) { + trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } else { + trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } else { + if (typeRoots === void 0) { + trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } else { + trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + if (redirectedReference) { + trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + const failedLookupLocations = []; + const affectingLocations = []; + let features = getNodeResolutionFeatures(options); + if (resolutionMode !== void 0) { + features |= 30 /* AllFeatures */; + } + const moduleResolution = getEmitModuleResolutionKind(options); + if (resolutionMode === 99 /* ESNext */ && (3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */)) { + features |= 32 /* EsmMode */; + } + const conditions = features & 8 /* Exports */ ? getConditions(options, resolutionMode) : []; + const diagnostics = []; + const moduleResolutionState = { + compilerOptions: options, + host, + traceEnabled, + failedLookupLocations, + affectingLocations, + packageJsonInfoCache: cache, + features, + conditions, + requestContainingDirectory: containingDirectory, + reportDiagnostic: (diag2) => void diagnostics.push(diag2), + isConfigLookup: false, + candidateIsFromPackageJsonField: false, + resolvedPackageDirectory: false + }; + let resolved = primaryLookup(); + let primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + let resolvedTypeReferenceDirective; + if (resolved) { + const { fileName, packageId } = resolved; + let resolvedFileName = fileName, originalPath; + if (!options.preserveSymlinks) ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled)); + resolvedTypeReferenceDirective = { + primary, + resolvedFileName, + originalPath, + packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName) + }; + } + result = { + resolvedTypeReferenceDirective, + failedLookupLocations: initializeResolutionField(failedLookupLocations), + affectingLocations: initializeResolutionField(affectingLocations), + resolutionDiagnostics: initializeResolutionField(diagnostics) + }; + if (containingDirectory && cache && !cache.isReadonly) { + cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set( + typeReferenceDirectiveName, + /*mode*/ + resolutionMode, + result + ); + if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { + cache.getOrCreateCacheForNonRelativeName(typeReferenceDirectiveName, resolutionMode, redirectedReference).set(containingDirectory, result); + } + } + if (traceEnabled) traceResult(result); + return result; + function traceResult(result2) { + var _a; + if (!((_a = result2.resolvedTypeReferenceDirective) == null ? void 0 : _a.resolvedFileName)) { + trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } else if (result2.resolvedTypeReferenceDirective.packageId) { + trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result2.resolvedTypeReferenceDirective.resolvedFileName, packageIdToString(result2.resolvedTypeReferenceDirective.packageId), result2.resolvedTypeReferenceDirective.primary); + } else { + trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result2.resolvedTypeReferenceDirective.resolvedFileName, result2.resolvedTypeReferenceDirective.primary); + } + } + function primaryLookup() { + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return firstDefined(typeRoots, (typeRoot) => { + const candidate = getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState); + const directoryExists = directoryProbablyExists(typeRoot, host); + if (!directoryExists && traceEnabled) { + trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, typeRoot); + } + if (options.typeRoots) { + const resolvedFromFile = loadModuleFromFile(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState); + if (resolvedFromFile) { + const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path); + const packageInfo = packageDirectory ? getPackageJsonInfo( + packageDirectory, + /*onlyRecordFailures*/ + false, + moduleResolutionState + ) : void 0; + return resolvedTypeScriptOnly(withPackageId(packageInfo, resolvedFromFile, moduleResolutionState)); + } + } + return resolvedTypeScriptOnly( + loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState) + ); + }); + } else { + if (traceEnabled) { + trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== void 0) { + let result2; + if (!options.typeRoots || !endsWith(containingFile, inferredTypesContainingFile)) { + if (traceEnabled) { + trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { + const searchResult = loadModuleFromNearestNodeModulesDirectory( + 4 /* Declaration */, + typeReferenceDirectiveName, + initialLocationForSecondaryLookup, + moduleResolutionState, + /*cache*/ + void 0, + /*redirectedReference*/ + void 0 + ); + result2 = searchResult && searchResult.value; + } else { + const { path: candidate } = normalizePathForCJSResolution(initialLocationForSecondaryLookup, typeReferenceDirectiveName); + result2 = nodeLoadModuleByRelativeName( + 4 /* Declaration */, + candidate, + /*onlyRecordFailures*/ + false, + moduleResolutionState, + /*considerPackageJson*/ + true + ); + } + } else if (traceEnabled) { + trace(host, Diagnostics.Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_node_modules_folder); + } + return resolvedTypeScriptOnly(result2); + } else { + if (traceEnabled) { + trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } +} +function getNodeResolutionFeatures(options) { + let features = 0 /* None */; + switch (getEmitModuleResolutionKind(options)) { + case 3 /* Node16 */: + features = 30 /* Node16Default */; + break; + case 99 /* NodeNext */: + features = 30 /* NodeNextDefault */; + break; + case 100 /* Bundler */: + features = 30 /* BundlerDefault */; + break; + } + if (options.resolvePackageJsonExports) { + features |= 8 /* Exports */; + } else if (options.resolvePackageJsonExports === false) { + features &= ~8 /* Exports */; + } + if (options.resolvePackageJsonImports) { + features |= 2 /* Imports */; + } else if (options.resolvePackageJsonImports === false) { + features &= ~2 /* Imports */; + } + return features; +} +function getConditions(options, resolutionMode) { + const moduleResolution = getEmitModuleResolutionKind(options); + if (resolutionMode === void 0) { + if (moduleResolution === 100 /* Bundler */) { + resolutionMode = 99 /* ESNext */; + } else if (moduleResolution === 2 /* Node10 */) { + return []; + } + } + const conditions = resolutionMode === 99 /* ESNext */ ? ["import"] : ["require"]; + if (!options.noDtsResolution) { + conditions.push("types"); + } + if (moduleResolution !== 100 /* Bundler */) { + conditions.push("node"); + } + return concatenate(conditions, options.customConditions); +} +function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + const result = []; + if (host.directoryExists && host.getDirectories) { + const typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (const root of typeRoots) { + if (host.directoryExists(root)) { + for (const typeDirectivePath of host.getDirectories(root)) { + const normalized = normalizePath(typeDirectivePath); + const packageJsonPath = combinePaths(root, normalized, "package.json"); + const isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + const baseFileName = getBaseFileName(normalized); + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + result.push(baseFileName); + } + } + } + } + } + } + } + return result; +} +function isPackageJsonInfo(entry) { + return !!(entry == null ? void 0 : entry.contents); +} +function isMissingPackageJsonInfo(entry) { + return !!entry && !entry.contents; +} +function compilerOptionValueToString(value) { + var _a; + if (value === null || typeof value !== "object") { + return "" + value; + } + if (isArray(value)) { + return `[${(_a = value.map((e) => compilerOptionValueToString(e))) == null ? void 0 : _a.join(",")}]`; + } + let str = "{"; + for (const key in value) { + if (hasProperty(value, key)) { + str += `${key}: ${compilerOptionValueToString(value[key])}`; + } + } + return str + "}"; +} +function getKeyForCompilerOptions(options, affectingOptionDeclarations) { + return affectingOptionDeclarations.map((option) => compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + `|${options.pathsBasePath}`; +} +function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) { + const redirectsMap = /* @__PURE__ */ new Map(); + const redirectsKeyToMap = /* @__PURE__ */ new Map(); + let ownMap = /* @__PURE__ */ new Map(); + if (ownOptions) redirectsMap.set(ownOptions, ownMap); + return { + getMapOfCacheRedirects, + getOrCreateMapOfCacheRedirects, + update, + clear: clear2, + getOwnMap: () => ownMap + }; + function getMapOfCacheRedirects(redirectedReference) { + return redirectedReference ? getOrCreateMap( + redirectedReference.commandLine.options, + /*create*/ + false + ) : ownMap; + } + function getOrCreateMapOfCacheRedirects(redirectedReference) { + return redirectedReference ? getOrCreateMap( + redirectedReference.commandLine.options, + /*create*/ + true + ) : ownMap; + } + function update(newOptions) { + if (ownOptions !== newOptions) { + if (ownOptions) ownMap = getOrCreateMap( + newOptions, + /*create*/ + true + ); + else redirectsMap.set(newOptions, ownMap); + ownOptions = newOptions; + } + } + function getOrCreateMap(redirectOptions, create) { + let result = redirectsMap.get(redirectOptions); + if (result) return result; + const key = getRedirectsCacheKey(redirectOptions); + result = redirectsKeyToMap.get(key); + if (!result) { + if (ownOptions) { + const ownKey = getRedirectsCacheKey(ownOptions); + if (ownKey === key) result = ownMap; + else if (!redirectsKeyToMap.has(ownKey)) redirectsKeyToMap.set(ownKey, ownMap); + } + if (create) result ?? (result = /* @__PURE__ */ new Map()); + if (result) redirectsKeyToMap.set(key, result); + } + if (result) redirectsMap.set(redirectOptions, result); + return result; + } + function clear2() { + const ownKey = ownOptions && optionsToRedirectsKey.get(ownOptions); + ownMap.clear(); + redirectsMap.clear(); + optionsToRedirectsKey.clear(); + redirectsKeyToMap.clear(); + if (ownOptions) { + if (ownKey) optionsToRedirectsKey.set(ownOptions, ownKey); + redirectsMap.set(ownOptions, ownMap); + } + } + function getRedirectsCacheKey(options) { + let result = optionsToRedirectsKey.get(options); + if (!result) { + optionsToRedirectsKey.set(options, result = getKeyForCompilerOptions(options, moduleResolutionOptionDeclarations)); + } + return result; + } +} +function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + let cache; + return { getPackageJsonInfo: getPackageJsonInfo2, setPackageJsonInfo, clear: clear2, getInternalMap }; + function getPackageJsonInfo2(packageJsonPath) { + return cache == null ? void 0 : cache.get(toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = /* @__PURE__ */ new Map())).set(toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear2() { + cache = void 0; + } + function getInternalMap() { + return cache; + } +} +function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + const cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + let result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; +} +function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, options, optionsToRedirectsKey) { + const directoryToModuleNameMap = createCacheWithRedirects(options, optionsToRedirectsKey); + return { + getFromDirectoryCache, + getOrCreateCacheForDirectory, + clear: clear2, + update, + directoryToModuleNameMap + }; + function clear2() { + directoryToModuleNameMap.clear(); + } + function update(options2) { + directoryToModuleNameMap.update(options2); + } + function getOrCreateCacheForDirectory(directoryName, redirectedReference) { + const path = toPath(directoryName, currentDirectory, getCanonicalFileName); + return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, () => createModeAwareCache()); + } + function getFromDirectoryCache(name, mode, directoryName, redirectedReference) { + var _a, _b; + const path = toPath(directoryName, currentDirectory, getCanonicalFileName); + return (_b = (_a = directoryToModuleNameMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a.get(path)) == null ? void 0 : _b.get(name, mode); + } +} +function createModeAwareCacheKey(specifier, mode) { + return mode === void 0 ? specifier : `${mode}|${specifier}`; +} +function createModeAwareCache() { + const underlying = /* @__PURE__ */ new Map(); + const memoizedReverseKeys = /* @__PURE__ */ new Map(); + const cache = { + get(specifier, mode) { + return underlying.get(getUnderlyingCacheKey(specifier, mode)); + }, + set(specifier, mode, value) { + underlying.set(getUnderlyingCacheKey(specifier, mode), value); + return cache; + }, + delete(specifier, mode) { + underlying.delete(getUnderlyingCacheKey(specifier, mode)); + return cache; + }, + has(specifier, mode) { + return underlying.has(getUnderlyingCacheKey(specifier, mode)); + }, + forEach(cb) { + return underlying.forEach((elem, key) => { + const [specifier, mode] = memoizedReverseKeys.get(key); + return cb(elem, specifier, mode); + }); + }, + size() { + return underlying.size; + } + }; + return cache; + function getUnderlyingCacheKey(specifier, mode) { + const result = createModeAwareCacheKey(specifier, mode); + memoizedReverseKeys.set(result, [specifier, mode]); + return result; + } +} +function getOriginalOrResolvedModuleFileName(result) { + return result.resolvedModule && (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); +} +function getOriginalOrResolvedTypeReferenceFileName(result) { + return result.resolvedTypeReferenceDirective && (result.resolvedTypeReferenceDirective.originalPath || result.resolvedTypeReferenceDirective.resolvedFileName); +} +function createNonRelativeNameResolutionCache(currentDirectory, getCanonicalFileName, options, getResolvedFileName, optionsToRedirectsKey) { + const moduleNameToDirectoryMap = createCacheWithRedirects(options, optionsToRedirectsKey); + return { + getFromNonRelativeNameCache, + getOrCreateCacheForNonRelativeName, + clear: clear2, + update + }; + function clear2() { + moduleNameToDirectoryMap.clear(); + } + function update(options2) { + moduleNameToDirectoryMap.update(options2); + } + function getFromNonRelativeNameCache(nonRelativeModuleName, mode, directoryName, redirectedReference) { + var _a, _b; + Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName)); + return (_b = (_a = moduleNameToDirectoryMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a.get(createModeAwareCacheKey(nonRelativeModuleName, mode))) == null ? void 0 : _b.get(directoryName); + } + function getOrCreateCacheForNonRelativeName(nonRelativeModuleName, mode, redirectedReference) { + Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName)); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, createModeAwareCacheKey(nonRelativeModuleName, mode), createPerModuleNameCache); + } + function createPerModuleNameCache() { + const directoryPathMap = /* @__PURE__ */ new Map(); + return { get, set }; + function get(directory) { + return directoryPathMap.get(toPath(directory, currentDirectory, getCanonicalFileName)); + } + function set(directory, result) { + const path = toPath(directory, currentDirectory, getCanonicalFileName); + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + const resolvedFileName = getResolvedFileName(result); + const commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); + let current = path; + while (current !== commonPrefix) { + const parent = getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + } + } + function getCommonPrefix(directory, resolution) { + const resolutionDirectory = toPath(getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + let i = 0; + const limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === directorySeparator)) { + return directory; + } + const rootLength = getRootLength(directory); + if (i < rootLength) { + return void 0; + } + const sep = directory.lastIndexOf(directorySeparator, i - 1); + if (sep === -1) { + return void 0; + } + return directory.substr(0, Math.max(sep, rootLength)); + } + } +} +function createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getResolvedFileName, optionsToRedirectsKey) { + optionsToRedirectsKey ?? (optionsToRedirectsKey = /* @__PURE__ */ new Map()); + const perDirectoryResolutionCache = createPerDirectoryResolutionCache( + currentDirectory, + getCanonicalFileName, + options, + optionsToRedirectsKey + ); + const nonRelativeNameResolutionCache = createNonRelativeNameResolutionCache( + currentDirectory, + getCanonicalFileName, + options, + getResolvedFileName, + optionsToRedirectsKey + ); + packageJsonInfoCache ?? (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return { + ...packageJsonInfoCache, + ...perDirectoryResolutionCache, + ...nonRelativeNameResolutionCache, + clear: clear2, + update, + getPackageJsonInfoCache: () => packageJsonInfoCache, + clearAllExceptPackageJsonInfoCache, + optionsToRedirectsKey + }; + function clear2() { + clearAllExceptPackageJsonInfoCache(); + packageJsonInfoCache.clear(); + } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + nonRelativeNameResolutionCache.clear(); + } + function update(options2) { + perDirectoryResolutionCache.update(options2); + nonRelativeNameResolutionCache.update(options2); + } +} +function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) { + const result = createModuleOrTypeReferenceResolutionCache( + currentDirectory, + getCanonicalFileName, + options, + packageJsonInfoCache, + getOriginalOrResolvedModuleFileName, + optionsToRedirectsKey + ); + result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference); + return result; +} +function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) { + return createModuleOrTypeReferenceResolutionCache( + currentDirectory, + getCanonicalFileName, + options, + packageJsonInfoCache, + getOriginalOrResolvedTypeReferenceFileName, + optionsToRedirectsKey + ); +} +function getOptionsForLibraryResolution(options) { + return { moduleResolution: 2 /* Node10 */, traceResolution: options.traceResolution }; +} +function resolveLibrary(libraryName, resolveFrom, compilerOptions, host, cache) { + return resolveModuleName(libraryName, resolveFrom, getOptionsForLibraryResolution(compilerOptions), host, cache); +} +function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { + const traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } + if (traceEnabled) { + trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } + } + const containingDirectory = getDirectoryPath(containingFile); + let result = cache == null ? void 0 : cache.getFromDirectoryCache(moduleName, resolutionMode, containingDirectory, redirectedReference); + if (result) { + if (traceEnabled) { + trace(host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + } else { + let moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === void 0) { + moduleResolution = getEmitModuleResolutionKind(compilerOptions); + if (traceEnabled) { + trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]); + } + } else { + if (traceEnabled) { + trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case 3 /* Node16 */: + result = node16ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); + break; + case 99 /* NodeNext */: + result = nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); + break; + case 2 /* Node10 */: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode ? getConditions(compilerOptions, resolutionMode) : void 0); + break; + case 1 /* Classic */: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); + break; + case 100 /* Bundler */: + result = bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode ? getConditions(compilerOptions, resolutionMode) : void 0); + break; + default: + return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); + } + if (cache && !cache.isReadonly) { + cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(moduleName, resolutionMode, result); + if (!isExternalModuleNameRelative(moduleName)) { + cache.getOrCreateCacheForNonRelativeName(moduleName, resolutionMode, redirectedReference).set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + if (result.resolvedModule.packageId) { + trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, packageIdToString(result.resolvedModule.packageId)); + } else { + trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + } else { + trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; +} +function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { + const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) return resolved.value; + if (!isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); + } else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); + } +} +function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { + const { baseUrl, paths } = state.compilerOptions; + if (paths && !pathIsRelative(moduleName)) { + if (state.traceEnabled) { + if (baseUrl) { + trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + } + trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + const baseDirectory = getPathsBasePath(state.compilerOptions, state.host); + const pathPatterns = tryParsePatterns(paths); + return tryLoadModuleUsingPaths( + extensions, + moduleName, + baseDirectory, + paths, + pathPatterns, + loader, + /*onlyRecordFailures*/ + false, + state + ); + } +} +function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { + if (!state.compilerOptions.rootDirs) { + return void 0; + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); + let matchedRootDir; + let matchedNormalizedPrefix; + for (const rootDir of state.compilerOptions.rootDirs) { + let normalizedRoot = normalizePath(rootDir); + if (!endsWith(normalizedRoot, directorySeparator)) { + normalizedRoot += directorySeparator; + } + const isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && (matchedNormalizedPrefix === void 0 || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + const suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs); + } + for (const rootDir of state.compilerOptions.rootDirs) { + if (rootDir === matchedRootDir) { + continue; + } + const candidate2 = combinePaths(normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate2); + } + const baseDirectory = getDirectoryPath(candidate2); + const resolvedFileName2 = loader(extensions, candidate2, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName2) { + return resolvedFileName2; + } + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return void 0; +} +function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + const { baseUrl } = state.compilerOptions; + if (!baseUrl) { + return void 0; + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + } + const candidate = normalizePath(combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); + } + return loader(extensions, candidate, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); +} +function resolveJSModule(moduleName, initialDir, host) { + const { resolvedModule, failedLookupLocations } = tryResolveJSModuleWorker(moduleName, initialDir, host); + if (!resolvedModule) { + throw new Error(`Could not resolve JS module '${moduleName}' starting at '${initialDir}'. Looked in: ${failedLookupLocations == null ? void 0 : failedLookupLocations.join(", ")}`); + } + return resolvedModule.resolvedFileName; +} +function node16ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { + return nodeNextModuleNameResolverWorker( + 30 /* Node16Default */, + moduleName, + containingFile, + compilerOptions, + host, + cache, + redirectedReference, + resolutionMode + ); +} +function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { + return nodeNextModuleNameResolverWorker( + 30 /* NodeNextDefault */, + moduleName, + containingFile, + compilerOptions, + host, + cache, + redirectedReference, + resolutionMode + ); +} +function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode, conditions) { + const containingDirectory = getDirectoryPath(containingFile); + const esmMode = resolutionMode === 99 /* ESNext */ ? 32 /* EsmMode */ : 0; + let extensions = compilerOptions.noDtsResolution ? 3 /* ImplementationFiles */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */; + if (getResolveJsonModule(compilerOptions)) { + extensions |= 8 /* Json */; + } + return nodeModuleNameResolverWorker( + features | esmMode, + moduleName, + containingDirectory, + compilerOptions, + host, + cache, + extensions, + /*isConfigLookup*/ + false, + redirectedReference, + conditions + ); +} +function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker( + 0 /* None */, + moduleName, + initialDir, + { moduleResolution: 2 /* Node10 */, allowJs: true }, + host, + /*cache*/ + void 0, + 2 /* JavaScript */, + /*isConfigLookup*/ + false, + /*redirectedReference*/ + void 0, + /*conditions*/ + void 0 + ); +} +function bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions) { + const containingDirectory = getDirectoryPath(containingFile); + let extensions = compilerOptions.noDtsResolution ? 3 /* ImplementationFiles */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */; + if (getResolveJsonModule(compilerOptions)) { + extensions |= 8 /* Json */; + } + return nodeModuleNameResolverWorker( + getNodeResolutionFeatures(compilerOptions), + moduleName, + containingDirectory, + compilerOptions, + host, + cache, + extensions, + /*isConfigLookup*/ + false, + redirectedReference, + conditions + ); +} +function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions, isConfigLookup) { + let extensions; + if (isConfigLookup) { + extensions = 8 /* Json */; + } else if (compilerOptions.noDtsResolution) { + extensions = 3 /* ImplementationFiles */; + if (getResolveJsonModule(compilerOptions)) extensions |= 8 /* Json */; + } else { + extensions = getResolveJsonModule(compilerOptions) ? 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */ | 8 /* Json */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */; + } + return nodeModuleNameResolverWorker(conditions ? 30 /* AllFeatures */ : 0 /* None */, moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, extensions, !!isConfigLookup, redirectedReference, conditions); +} +function nodeNextJsonConfigResolver(moduleName, containingFile, host) { + return nodeModuleNameResolverWorker( + 30 /* NodeNextDefault */, + moduleName, + getDirectoryPath(containingFile), + { moduleResolution: 99 /* NodeNext */ }, + host, + /*cache*/ + void 0, + 8 /* Json */, + /*isConfigLookup*/ + true, + /*redirectedReference*/ + void 0, + /*conditions*/ + void 0 + ); +} +function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, compilerOptions, host, cache, extensions, isConfigLookup, redirectedReference, conditions) { + var _a, _b, _c, _d, _e; + const traceEnabled = isTraceEnabled(compilerOptions, host); + const failedLookupLocations = []; + const affectingLocations = []; + const moduleResolution = getEmitModuleResolutionKind(compilerOptions); + conditions ?? (conditions = getConditions( + compilerOptions, + moduleResolution === 100 /* Bundler */ || moduleResolution === 2 /* Node10 */ ? void 0 : features & 32 /* EsmMode */ ? 99 /* ESNext */ : 1 /* CommonJS */ + )); + const diagnostics = []; + const state = { + compilerOptions, + host, + traceEnabled, + failedLookupLocations, + affectingLocations, + packageJsonInfoCache: cache, + features, + conditions: conditions ?? emptyArray, + requestContainingDirectory: containingDirectory, + reportDiagnostic: (diag2) => void diagnostics.push(diag2), + isConfigLookup, + candidateIsFromPackageJsonField: false, + resolvedPackageDirectory: false + }; + if (traceEnabled && moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { + trace(host, Diagnostics.Resolving_in_0_mode_with_conditions_1, features & 32 /* EsmMode */ ? "ESM" : "CJS", state.conditions.map((c) => `'${c}'`).join(", ")); + } + let result; + if (moduleResolution === 2 /* Node10 */) { + const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */); + const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */); + result = priorityExtensions && tryResolve(priorityExtensions, state) || secondaryExtensions && tryResolve(secondaryExtensions, state) || void 0; + } else { + result = tryResolve(extensions, state); + } + let alternateResult; + if (state.resolvedPackageDirectory && !isConfigLookup && !isExternalModuleNameRelative(moduleName)) { + const wantedTypesButGotJs = (result == null ? void 0 : result.value) && extensions & (1 /* TypeScript */ | 4 /* Declaration */) && !extensionIsOk(1 /* TypeScript */ | 4 /* Declaration */, result.value.resolved.extension); + if (((_a = result == null ? void 0 : result.value) == null ? void 0 : _a.isExternalLibraryImport) && wantedTypesButGotJs && features & 8 /* Exports */ && (conditions == null ? void 0 : conditions.includes("import"))) { + traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update); + const diagnosticState = { + ...state, + features: state.features & ~8 /* Exports */, + reportDiagnostic: noop + }; + const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState); + if ((_b = diagnosticResult == null ? void 0 : diagnosticResult.value) == null ? void 0 : _b.isExternalLibraryImport) { + alternateResult = diagnosticResult.value.resolved.path; + } + } else if ((!(result == null ? void 0 : result.value) || wantedTypesButGotJs) && moduleResolution === 2 /* Node10 */) { + traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_need_configuration_update); + const diagnosticsCompilerOptions = { ...state.compilerOptions, moduleResolution: 100 /* Bundler */ }; + const diagnosticState = { + ...state, + compilerOptions: diagnosticsCompilerOptions, + features: 30 /* BundlerDefault */, + conditions: getConditions(diagnosticsCompilerOptions), + reportDiagnostic: noop + }; + const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState); + if ((_c = diagnosticResult == null ? void 0 : diagnosticResult.value) == null ? void 0 : _c.isExternalLibraryImport) { + alternateResult = diagnosticResult.value.resolved.path; + } + } + } + return createResolvedModuleWithFailedLookupLocationsHandlingSymlink( + moduleName, + (_d = result == null ? void 0 : result.value) == null ? void 0 : _d.resolved, + (_e = result == null ? void 0 : result.value) == null ? void 0 : _e.isExternalLibraryImport, + failedLookupLocations, + affectingLocations, + diagnostics, + state, + cache, + alternateResult + ); + function tryResolve(extensions2, state2) { + const loader = (extensions3, candidate, onlyRecordFailures, state3) => nodeLoadModuleByRelativeName( + extensions3, + candidate, + onlyRecordFailures, + state3, + /*considerPackageJson*/ + true + ); + const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions2, moduleName, containingDirectory, loader, state2); + if (resolved) { + return toSearchResult({ resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); + } + if (!isExternalModuleNameRelative(moduleName)) { + if (features & 2 /* Imports */ && startsWith(moduleName, "#")) { + const resolved3 = loadModuleFromImports(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); + if (resolved3) { + return resolved3.value && { value: { resolved: resolved3.value, isExternalLibraryImport: false } }; + } + } + if (features & 4 /* SelfName */) { + const resolved3 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); + if (resolved3) { + return resolved3.value && { value: { resolved: resolved3.value, isExternalLibraryImport: false } }; + } + } + if (moduleName.includes(":")) { + if (traceEnabled) { + trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + } + return void 0; + } + if (traceEnabled) { + trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + } + let resolved2 = loadModuleFromNearestNodeModulesDirectory(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); + if (extensions2 & 4 /* Declaration */) { + resolved2 ?? (resolved2 = resolveFromTypeRoot(moduleName, state2)); + } + return resolved2 && { value: resolved2.value && { resolved: resolved2.value, isExternalLibraryImport: true } }; + } else { + const { path: candidate, parts } = normalizePathForCJSResolution(containingDirectory, moduleName); + const resolved2 = nodeLoadModuleByRelativeName( + extensions2, + candidate, + /*onlyRecordFailures*/ + false, + state2, + /*considerPackageJson*/ + true + ); + return resolved2 && toSearchResult({ resolved: resolved2, isExternalLibraryImport: contains(parts, "node_modules") }); + } + } +} +function normalizePathForCJSResolution(containingDirectory, moduleName) { + const combined = combinePaths(containingDirectory, moduleName); + const parts = getPathComponents(combined); + const lastPart = lastOrUndefined(parts); + const path = lastPart === "." || lastPart === ".." ? ensureTrailingDirectorySeparator(normalizePath(combined)) : normalizePath(combined); + return { path, parts }; +} +function realPath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + const real = normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; +} +function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1, candidate, formatExtensions(extensions)); + } + if (!hasTrailingDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + const parentOfCandidate = getDirectoryPath(candidate); + if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); + if (resolvedFromFile) { + const packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : void 0; + const packageInfo = packageDirectory ? getPackageJsonInfo( + packageDirectory, + /*onlyRecordFailures*/ + false, + state + ) : void 0; + return withPackageId(packageInfo, resolvedFromFile, state); + } + } + if (!onlyRecordFailures) { + const candidateExists = directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + if (!(state.features & 32 /* EsmMode */)) { + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); + } + return void 0; +} +var nodeModulesPathPart = "/node_modules/"; +function pathContainsNodeModules(path) { + return path.includes(nodeModulesPathPart); +} +function parseNodeModuleFromPath(resolved, isFolder) { + const path = normalizePath(resolved); + const idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return void 0; + } + const indexAfterNodeModules = idx + nodeModulesPathPart.length; + let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules, isFolder); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName, isFolder); + } + return path.slice(0, indexAfterPackageName); +} +function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex, isFolder) { + const nextSeparatorIndex = path.indexOf(directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? isFolder ? path.length : prevSeparatorIndex : nextSeparatorIndex; +} +function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); +} +function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { + const resolvedByReplacingExtension = loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state); + if (resolvedByReplacingExtension) { + return resolvedByReplacingExtension; + } + if (!(state.features & 32 /* EsmMode */)) { + const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, "", onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + } +} +function loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state) { + const filename = getBaseFileName(candidate); + if (!filename.includes(".")) { + return void 0; + } + let extensionless = removeFileExtension(candidate); + if (extensionless === candidate) { + extensionless = candidate.substring(0, candidate.lastIndexOf(".")); + } + const extension = candidate.substring(extensionless.length); + if (state.traceEnabled) { + trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, extension, onlyRecordFailures, state); +} +function loadFileNameFromPackageJsonField(extensions, candidate, packageJsonValue, onlyRecordFailures, state) { + if (extensions & 1 /* TypeScript */ && fileExtensionIsOneOf(candidate, supportedTSImplementationExtensions) || extensions & 4 /* Declaration */ && fileExtensionIsOneOf(candidate, supportedDeclarationExtensions)) { + const result = tryFile(candidate, onlyRecordFailures, state); + const ext = tryExtractTSExtension(candidate); + return result !== void 0 ? { path: candidate, ext, resolvedUsingTsExtension: packageJsonValue ? !endsWith(packageJsonValue, ext) : void 0 } : void 0; + } + if (state.isConfigLookup && extensions === 8 /* Json */ && fileExtensionIs(candidate, ".json" /* Json */)) { + const result = tryFile(candidate, onlyRecordFailures, state); + return result !== void 0 ? { path: candidate, ext: ".json" /* Json */, resolvedUsingTsExtension: void 0 } : void 0; + } + return loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state); +} +function tryAddingExtensions(candidate, extensions, originalExtension, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + const directory = getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + switch (originalExtension) { + case ".mjs" /* Mjs */: + case ".mts" /* Mts */: + case ".d.mts" /* Dmts */: + return extensions & 1 /* TypeScript */ && tryExtension(".mts" /* Mts */, originalExtension === ".mts" /* Mts */ || originalExtension === ".d.mts" /* Dmts */) || extensions & 4 /* Declaration */ && tryExtension(".d.mts" /* Dmts */, originalExtension === ".mts" /* Mts */ || originalExtension === ".d.mts" /* Dmts */) || extensions & 2 /* JavaScript */ && tryExtension(".mjs" /* Mjs */) || void 0; + case ".cjs" /* Cjs */: + case ".cts" /* Cts */: + case ".d.cts" /* Dcts */: + return extensions & 1 /* TypeScript */ && tryExtension(".cts" /* Cts */, originalExtension === ".cts" /* Cts */ || originalExtension === ".d.cts" /* Dcts */) || extensions & 4 /* Declaration */ && tryExtension(".d.cts" /* Dcts */, originalExtension === ".cts" /* Cts */ || originalExtension === ".d.cts" /* Dcts */) || extensions & 2 /* JavaScript */ && tryExtension(".cjs" /* Cjs */) || void 0; + case ".json" /* Json */: + return extensions & 4 /* Declaration */ && tryExtension(".d.json.ts") || extensions & 8 /* Json */ && tryExtension(".json" /* Json */) || void 0; + case ".tsx" /* Tsx */: + case ".jsx" /* Jsx */: + return extensions & 1 /* TypeScript */ && (tryExtension(".tsx" /* Tsx */, originalExtension === ".tsx" /* Tsx */) || tryExtension(".ts" /* Ts */, originalExtension === ".tsx" /* Tsx */)) || extensions & 4 /* Declaration */ && tryExtension(".d.ts" /* Dts */, originalExtension === ".tsx" /* Tsx */) || extensions & 2 /* JavaScript */ && (tryExtension(".jsx" /* Jsx */) || tryExtension(".js" /* Js */)) || void 0; + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + case ".js" /* Js */: + case "": + return extensions & 1 /* TypeScript */ && (tryExtension(".ts" /* Ts */, originalExtension === ".ts" /* Ts */ || originalExtension === ".d.ts" /* Dts */) || tryExtension(".tsx" /* Tsx */, originalExtension === ".ts" /* Ts */ || originalExtension === ".d.ts" /* Dts */)) || extensions & 4 /* Declaration */ && tryExtension(".d.ts" /* Dts */, originalExtension === ".ts" /* Ts */ || originalExtension === ".d.ts" /* Dts */) || extensions & 2 /* JavaScript */ && (tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */)) || state.isConfigLookup && tryExtension(".json" /* Json */) || void 0; + default: + return extensions & 4 /* Declaration */ && !isDeclarationFileName(candidate + originalExtension) && tryExtension(`.d${originalExtension}.ts`) || void 0; + } + function tryExtension(ext, resolvedUsingTsExtension) { + const path = tryFile(candidate + ext, onlyRecordFailures, state); + return path === void 0 ? void 0 : { path, ext, resolvedUsingTsExtension: !state.candidateIsFromPackageJsonField && resolvedUsingTsExtension }; + } +} +function tryFile(fileName, onlyRecordFailures, state) { + var _a; + if (!((_a = state.compilerOptions.moduleSuffixes) == null ? void 0 : _a.length)) { + return tryFileLookup(fileName, onlyRecordFailures, state); + } + const ext = tryGetExtensionFromPath2(fileName) ?? ""; + const fileNameNoExtension = ext ? removeExtension(fileName, ext) : fileName; + return forEach(state.compilerOptions.moduleSuffixes, (suffix) => tryFileLookup(fileNameNoExtension + suffix + ext, onlyRecordFailures, state)); +} +function tryFileLookup(fileName, onlyRecordFailures, state) { + var _a; + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.File_0_exists_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } else { + if (state.traceEnabled) { + trace(state.host, Diagnostics.File_0_does_not_exist, fileName); + } + } + } + (_a = state.failedLookupLocations) == null ? void 0 : _a.push(fileName); + return void 0; +} +function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson = true) { + const packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : void 0; + return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo), state); +} +function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) { + return { + host, + compilerOptions: options, + traceEnabled: isTraceEnabled(options, host), + failedLookupLocations: void 0, + affectingLocations: void 0, + packageJsonInfoCache, + features: 0 /* None */, + conditions: emptyArray, + requestContainingDirectory: void 0, + reportDiagnostic: noop, + isConfigLookup: false, + candidateIsFromPackageJsonField: false, + resolvedPackageDirectory: false + }; +} +function getPackageScopeForPath(directory, state) { + return forEachAncestorDirectoryStoppingAtGlobalCache( + state.host, + directory, + (dir) => getPackageJsonInfo( + dir, + /*onlyRecordFailures*/ + false, + state + ) + ); +} +function getVersionPathsOfPackageJsonInfo(packageJsonInfo, state) { + if (packageJsonInfo.contents.versionPaths === void 0) { + packageJsonInfo.contents.versionPaths = readPackageJsonTypesVersionPaths(packageJsonInfo.contents.packageJsonContent, state) || false; + } + return packageJsonInfo.contents.versionPaths || void 0; +} +function getPeerDependenciesOfPackageJsonInfo(packageJsonInfo, state) { + if (packageJsonInfo.contents.peerDependencies === void 0) { + packageJsonInfo.contents.peerDependencies = readPackageJsonPeerDependencies(packageJsonInfo, state) || false; + } + return packageJsonInfo.contents.peerDependencies || void 0; +} +function readPackageJsonPeerDependencies(packageJsonInfo, state) { + const peerDependencies = readPackageJsonField(packageJsonInfo.contents.packageJsonContent, "peerDependencies", "object", state); + if (peerDependencies === void 0) return void 0; + if (state.traceEnabled) trace(state.host, Diagnostics.package_json_has_a_peerDependencies_field); + const packageDirectory = realPath(packageJsonInfo.packageDirectory, state.host, state.traceEnabled); + const nodeModules = packageDirectory.substring(0, packageDirectory.lastIndexOf("node_modules") + "node_modules".length) + directorySeparator; + let result = ""; + for (const key in peerDependencies) { + if (hasProperty(peerDependencies, key)) { + const peerPackageJson = getPackageJsonInfo( + nodeModules + key, + /*onlyRecordFailures*/ + false, + state + ); + if (peerPackageJson) { + const version2 = peerPackageJson.contents.packageJsonContent.version; + result += `+${key}@${version2}`; + if (state.traceEnabled) trace(state.host, Diagnostics.Found_peerDependency_0_with_1_version, key, version2); + } else { + if (state.traceEnabled) trace(state.host, Diagnostics.Failed_to_find_peerDependency_0, key); + } + } + } + return result; +} +function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c, _d, _e, _f; + const { host, traceEnabled } = state; + const packageJsonPath = combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + (_a = state.failedLookupLocations) == null ? void 0 : _a.push(packageJsonPath); + return void 0; + } + const existing = (_b = state.packageJsonInfoCache) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); + if (existing !== void 0) { + if (isPackageJsonInfo(existing)) { + if (traceEnabled) trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + (_c = state.affectingLocations) == null ? void 0 : _c.push(packageJsonPath); + return existing.packageDirectory === packageDirectory ? existing : { packageDirectory, contents: existing.contents }; + } else { + if (existing.directoryExists && traceEnabled) trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + (_d = state.failedLookupLocations) == null ? void 0 : _d.push(packageJsonPath); + return void 0; + } + } + const directoryExists = directoryProbablyExists(packageDirectory, host); + if (directoryExists && host.fileExists(packageJsonPath)) { + const packageJsonContent = readJson(packageJsonPath, host); + if (traceEnabled) { + trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); + } + const result = { packageDirectory, contents: { packageJsonContent, versionPaths: void 0, resolvedEntrypoints: void 0, peerDependencies: void 0 } }; + if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, result); + (_e = state.affectingLocations) == null ? void 0 : _e.push(packageJsonPath); + return result; + } else { + if (directoryExists && traceEnabled) { + trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath); + } + if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, { packageDirectory, directoryExists }); + (_f = state.failedLookupLocations) == null ? void 0 : _f.push(packageJsonPath); + } +} +function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJson) { + const versionPaths = packageJson && getVersionPathsOfPackageJsonInfo(packageJson, state); + let packageFile; + if (packageJson && arePathsEqual(packageJson == null ? void 0 : packageJson.packageDirectory, candidate, state.host)) { + if (state.isConfigLookup) { + packageFile = readPackageJsonTSConfigField(packageJson.contents.packageJsonContent, packageJson.packageDirectory, state); + } else { + packageFile = extensions & 4 /* Declaration */ && readPackageJsonTypesFields(packageJson.contents.packageJsonContent, packageJson.packageDirectory, state) || extensions & (3 /* ImplementationFiles */ | 4 /* Declaration */) && readPackageJsonMainField(packageJson.contents.packageJsonContent, packageJson.packageDirectory, state) || void 0; + } + } + const loader = (extensions2, candidate2, onlyRecordFailures2, state2) => { + const fromFile = loadFileNameFromPackageJsonField( + extensions2, + candidate2, + /*packageJsonValue*/ + void 0, + onlyRecordFailures2, + state2 + ); + if (fromFile) { + return noPackageId(fromFile); + } + const expandedExtensions = extensions2 === 4 /* Declaration */ ? 1 /* TypeScript */ | 4 /* Declaration */ : extensions2; + const features = state2.features; + const candidateIsFromPackageJsonField = state2.candidateIsFromPackageJsonField; + state2.candidateIsFromPackageJsonField = true; + if ((packageJson == null ? void 0 : packageJson.contents.packageJsonContent.type) !== "module") { + state2.features &= ~32 /* EsmMode */; + } + const result = nodeLoadModuleByRelativeName( + expandedExtensions, + candidate2, + onlyRecordFailures2, + state2, + /*considerPackageJson*/ + false + ); + state2.features = features; + state2.candidateIsFromPackageJsonField = candidateIsFromPackageJsonField; + return result; + }; + const onlyRecordFailuresForPackageFile = packageFile ? !directoryProbablyExists(getDirectoryPath(packageFile), state.host) : void 0; + const onlyRecordFailuresForIndex = onlyRecordFailures || !directoryProbablyExists(candidate, state.host); + const indexPath = combinePaths(candidate, state.isConfigLookup ? "tsconfig" : "index"); + if (versionPaths && (!packageFile || containsPath(candidate, packageFile))) { + const moduleName = getRelativePathFromDirectory( + candidate, + packageFile || indexPath, + /*ignoreCase*/ + false + ); + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, moduleName); + } + const pathPatterns = tryParsePatterns(versionPaths.paths); + const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, pathPatterns, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); + } + } + const packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) return packageFileResult; + if (!(state.features & 32 /* EsmMode */)) { + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); + } +} +function extensionIsOk(extensions, extension) { + return extensions & 2 /* JavaScript */ && (extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */ || extension === ".mjs" /* Mjs */ || extension === ".cjs" /* Cjs */) || extensions & 1 /* TypeScript */ && (extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".mts" /* Mts */ || extension === ".cts" /* Cts */) || extensions & 4 /* Declaration */ && (extension === ".d.ts" /* Dts */ || extension === ".d.mts" /* Dmts */ || extension === ".d.cts" /* Dcts */) || extensions & 8 /* Json */ && extension === ".json" /* Json */ || false; +} +function parsePackageName(moduleName) { + let idx = moduleName.indexOf(directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; +} +function allKeysStartWithDot(obj) { + return every(getOwnKeys(obj), (k) => startsWith(k, ".")); +} +function noKeyStartsWithDot(obj) { + return !some(getOwnKeys(obj), (k) => startsWith(k, ".")); +} +function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) { + var _a, _b; + const directoryPath = getNormalizedAbsolutePath(directory, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); + const scope = getPackageScopeForPath(directoryPath, state); + if (!scope || !scope.contents.packageJsonContent.exports) { + return void 0; + } + if (typeof scope.contents.packageJsonContent.name !== "string") { + return void 0; + } + const parts = getPathComponents(moduleName); + const nameParts = getPathComponents(scope.contents.packageJsonContent.name); + if (!every(nameParts, (p, i) => parts[i] === p)) { + return void 0; + } + const trailingParts = parts.slice(nameParts.length); + const subpath = !length(trailingParts) ? "." : `.${directorySeparator}${trailingParts.join(directorySeparator)}`; + if (getAllowJSCompilerOption(state.compilerOptions) && !pathContainsNodeModules(directory)) { + return loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference); + } + const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */); + const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */); + return loadModuleFromExports(scope, priorityExtensions, subpath, state, cache, redirectedReference) || loadModuleFromExports(scope, secondaryExtensions, subpath, state, cache, redirectedReference); +} +function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { + if (!scope.contents.packageJsonContent.exports) { + return void 0; + } + if (subpath === ".") { + let mainExport; + if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports)) { + mainExport = scope.contents.packageJsonContent.exports; + } else if (hasProperty(scope.contents.packageJsonContent.exports, ".")) { + mainExport = scope.contents.packageJsonContent.exports["."]; + } + if (mainExport) { + const loadModuleFromTargetExportOrImport = getLoadModuleFromTargetExportOrImport( + extensions, + state, + cache, + redirectedReference, + subpath, + scope, + /*isImports*/ + false + ); + return loadModuleFromTargetExportOrImport( + mainExport, + "", + /*pattern*/ + false, + "." + ); + } + } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { + if (typeof scope.contents.packageJsonContent.exports !== "object") { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + const result = loadModuleFromExportsOrImports( + extensions, + state, + cache, + redirectedReference, + subpath, + scope.contents.packageJsonContent.exports, + scope, + /*isImports*/ + false + ); + if (result) { + return result; + } + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory); + } + return toSearchResult( + /*value*/ + void 0 + ); +} +function loadModuleFromImports(extensions, moduleName, directory, state, cache, redirectedReference) { + var _a, _b; + if (moduleName === "#" || startsWith(moduleName, "#/")) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Invalid_import_specifier_0_has_no_possible_resolutions, moduleName); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + const directoryPath = getNormalizedAbsolutePath(directory, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); + const scope = getPackageScopeForPath(directoryPath, state); + if (!scope) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + if (!scope.contents.packageJsonContent.imports) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + const result = loadModuleFromExportsOrImports( + extensions, + state, + cache, + redirectedReference, + moduleName, + scope.contents.packageJsonContent.imports, + scope, + /*isImports*/ + true + ); + if (result) { + return result; + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1, moduleName, scope.packageDirectory); + } + return toSearchResult( + /*value*/ + void 0 + ); +} +function comparePatternKeys(a, b) { + const aPatternIndex = a.indexOf("*"); + const bPatternIndex = b.indexOf("*"); + const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLenA > baseLenB) return -1 /* LessThan */; + if (baseLenB > baseLenA) return 1 /* GreaterThan */; + if (aPatternIndex === -1) return 1 /* GreaterThan */; + if (bPatternIndex === -1) return -1 /* LessThan */; + if (a.length > b.length) return -1 /* LessThan */; + if (b.length > a.length) return 1 /* GreaterThan */; + return 0 /* EqualTo */; +} +function loadModuleFromExportsOrImports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { + const loadModuleFromTargetExportOrImport = getLoadModuleFromTargetExportOrImport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); + if (!endsWith(moduleName, directorySeparator) && !moduleName.includes("*") && hasProperty(lookupTable, moduleName)) { + const target = lookupTable[moduleName]; + return loadModuleFromTargetExportOrImport( + target, + /*subpath*/ + "", + /*pattern*/ + false, + moduleName + ); + } + const expandingKeys = toSorted(filter(getOwnKeys(lookupTable), (k) => hasOneAsterisk(k) || endsWith(k, "/")), comparePatternKeys); + for (const potentialTarget of expandingKeys) { + if (state.features & 16 /* ExportsPatternTrailers */ && matchesPatternWithTrailer(potentialTarget, moduleName)) { + const target = lookupTable[potentialTarget]; + const starPos = potentialTarget.indexOf("*"); + const subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); + return loadModuleFromTargetExportOrImport( + target, + subpath, + /*pattern*/ + true, + potentialTarget + ); + } else if (endsWith(potentialTarget, "*") && startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { + const target = lookupTable[potentialTarget]; + const subpath = moduleName.substring(potentialTarget.length - 1); + return loadModuleFromTargetExportOrImport( + target, + subpath, + /*pattern*/ + true, + potentialTarget + ); + } else if (startsWith(moduleName, potentialTarget)) { + const target = lookupTable[potentialTarget]; + const subpath = moduleName.substring(potentialTarget.length); + return loadModuleFromTargetExportOrImport( + target, + subpath, + /*pattern*/ + false, + potentialTarget + ); + } + } + function matchesPatternWithTrailer(target, name) { + if (endsWith(target, "*")) return false; + const starPos = target.indexOf("*"); + if (starPos === -1) return false; + return startsWith(name, target.substring(0, starPos)) && endsWith(name, target.substring(starPos + 1)); + } +} +function hasOneAsterisk(patternKey) { + const firstStar = patternKey.indexOf("*"); + return firstStar !== -1 && firstStar === patternKey.lastIndexOf("*"); +} +function getLoadModuleFromTargetExportOrImport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { + return loadModuleFromTargetExportOrImport; + function loadModuleFromTargetExportOrImport(target, subpath, pattern, key) { + var _a, _b; + if (typeof target === "string") { + if (!pattern && subpath.length > 0 && !endsWith(target, "/")) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + if (!startsWith(target, "./")) { + if (isImports && !startsWith(target, "../") && !startsWith(target, "/") && !isRootedDiskPath(target)) { + const combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath; + traceIfEnabled(state, Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); + traceIfEnabled(state, Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); + const result = nodeModuleNameResolverWorker( + state.features, + combinedLookup, + scope.packageDirectory + "/", + state.compilerOptions, + state.host, + cache, + extensions, + /*isConfigLookup*/ + false, + redirectedReference, + state.conditions + ); + (_a = state.failedLookupLocations) == null ? void 0 : _a.push(...result.failedLookupLocations ?? emptyArray); + (_b = state.affectingLocations) == null ? void 0 : _b.push(...result.affectingLocations ?? emptyArray); + return toSearchResult( + result.resolvedModule ? { + path: result.resolvedModule.resolvedFileName, + extension: result.resolvedModule.extension, + packageId: result.resolvedModule.packageId, + originalPath: result.resolvedModule.originalPath, + resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension + } : void 0 + ); + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + const parts = pathIsRelative(target) ? getPathComponents(target).slice(1) : getPathComponents(target); + const partsAfterFirst = parts.slice(1); + if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + const resolvedTarget = combinePaths(scope.packageDirectory, target); + const subpathParts = getPathComponents(subpath); + if (subpathParts.includes("..") || subpathParts.includes(".") || subpathParts.includes("node_modules")) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); + } + const finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); + const inputLink = tryLoadInputFileForPath(finalPath, subpath, combinePaths(scope.packageDirectory, "package.json"), isImports); + if (inputLink) return inputLink; + return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( + extensions, + finalPath, + target, + /*onlyRecordFailures*/ + false, + state + ), state)); + } else if (typeof target === "object" && target !== null) { + if (!Array.isArray(target)) { + traceIfEnabled(state, Diagnostics.Entering_conditional_exports); + for (const condition of getOwnKeys(target)) { + if (condition === "default" || state.conditions.includes(condition) || isApplicableVersionedTypesKey(state.conditions, condition)) { + traceIfEnabled(state, Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); + const subTarget = target[condition]; + const result = loadModuleFromTargetExportOrImport(subTarget, subpath, pattern, key); + if (result) { + traceIfEnabled(state, Diagnostics.Resolved_under_condition_0, condition); + traceIfEnabled(state, Diagnostics.Exiting_conditional_exports); + return result; + } else { + traceIfEnabled(state, Diagnostics.Failed_to_resolve_under_condition_0, condition); + } + } else { + traceIfEnabled(state, Diagnostics.Saw_non_matching_condition_0, condition); + } + } + traceIfEnabled(state, Diagnostics.Exiting_conditional_exports); + return void 0; + } else { + if (!length(target)) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + for (const elem of target) { + const result = loadModuleFromTargetExportOrImport(elem, subpath, pattern, key); + if (result) { + return result; + } + } + } + } else if (target === null) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_scope_0_explicitly_maps_specifier_1_to_null, scope.packageDirectory, moduleName); + } + return toSearchResult( + /*value*/ + void 0 + ); + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); + } + return toSearchResult( + /*value*/ + void 0 + ); + function toAbsolutePath(path) { + var _a2, _b2; + if (path === void 0) return path; + return getNormalizedAbsolutePath(path, (_b2 = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b2.call(_a2)); + } + function combineDirectoryPath(root, dir) { + return ensureTrailingDirectorySeparator(combinePaths(root, dir)); + } + function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) { + var _a2, _b2, _c, _d; + if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && !finalPath.includes("/node_modules/") && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) { + const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) }); + const commonSourceDirGuesses = []; + if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) { + const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [], ((_b2 = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b2.call(_a2)) || "", getCanonicalFileName)); + commonSourceDirGuesses.push(commonDir); + } else if (state.requestContainingDirectory) { + const requestingFile = toAbsolutePath(combinePaths(state.requestContainingDirectory, "index.ts")); + const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [requestingFile, toAbsolutePath(packagePath)], ((_d = (_c = state.host).getCurrentDirectory) == null ? void 0 : _d.call(_c)) || "", getCanonicalFileName)); + commonSourceDirGuesses.push(commonDir); + let fragment = ensureTrailingDirectorySeparator(commonDir); + while (fragment && fragment.length > 1) { + const parts = getPathComponents(fragment); + parts.pop(); + const commonDir2 = getPathFromPathComponents(parts); + commonSourceDirGuesses.unshift(commonDir2); + fragment = ensureTrailingDirectorySeparator(commonDir2); + } + } + if (commonSourceDirGuesses.length > 1) { + state.reportDiagnostic(createCompilerDiagnostic( + isImports2 ? Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate : Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate, + entry === "" ? "." : entry, + // replace empty string with `.` - the reverse of the operation done when entries are built - so main entrypoint errors don't look weird + packagePath + )); + } + for (const commonSourceDirGuess of commonSourceDirGuesses) { + const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess); + for (const candidateDir of candidateDirectories) { + if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) { + const pathFragment = finalPath.slice(candidateDir.length + 1); + const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment); + const jsAndDtsExtensions = [".mjs" /* Mjs */, ".cjs" /* Cjs */, ".js" /* Js */, ".json" /* Json */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".d.ts" /* Dts */]; + for (const ext of jsAndDtsExtensions) { + if (fileExtensionIs(possibleInputBase, ext)) { + const inputExts = getPossibleOriginalInputExtensionForExtension(possibleInputBase); + for (const possibleExt of inputExts) { + if (!extensionIsOk(extensions, possibleExt)) continue; + const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state)); + if (state.host.fileExists(possibleInputWithInputExtension)) { + return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( + extensions, + possibleInputWithInputExtension, + /*packageJsonValue*/ + void 0, + /*onlyRecordFailures*/ + false, + state + ), state)); + } + } + } + } + } + } + } + } + return void 0; + function getOutputDirectoriesForBaseDirectory(commonSourceDirGuess) { + var _a3, _b3; + const currentDir = state.compilerOptions.configFile ? ((_b3 = (_a3 = state.host).getCurrentDirectory) == null ? void 0 : _b3.call(_a3)) || "" : commonSourceDirGuess; + const candidateDirectories = []; + if (state.compilerOptions.declarationDir) { + candidateDirectories.push(toAbsolutePath(combineDirectoryPath(currentDir, state.compilerOptions.declarationDir))); + } + if (state.compilerOptions.outDir && state.compilerOptions.outDir !== state.compilerOptions.declarationDir) { + candidateDirectories.push(toAbsolutePath(combineDirectoryPath(currentDir, state.compilerOptions.outDir))); + } + return candidateDirectories; + } + } + } +} +function isApplicableVersionedTypesKey(conditions, key) { + if (!conditions.includes("types")) return false; + if (!startsWith(key, "types@")) return false; + const range = VersionRange.tryParse(key.substring("types@".length)); + if (!range) return false; + return range.test(version); +} +function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { + return loadModuleFromNearestNodeModulesDirectoryWorker( + extensions, + moduleName, + directory, + state, + /*typesScopeOnly*/ + false, + cache, + redirectedReference + ); +} +function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + return loadModuleFromNearestNodeModulesDirectoryWorker( + 4 /* Declaration */, + moduleName, + directory, + state, + /*typesScopeOnly*/ + true, + /*cache*/ + void 0, + /*redirectedReference*/ + void 0 + ); +} +function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + const mode = state.features === 0 ? void 0 : state.features & 32 /* EsmMode */ || state.conditions.includes("import") ? 99 /* ESNext */ : 1 /* CommonJS */; + const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */); + const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */); + if (priorityExtensions) { + traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0, formatExtensions(priorityExtensions)); + const result = lookup(priorityExtensions); + if (result) return result; + } + if (secondaryExtensions && !typesScopeOnly) { + traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0, formatExtensions(secondaryExtensions)); + return lookup(secondaryExtensions); + } + function lookup(extensions2) { + return forEachAncestorDirectoryStoppingAtGlobalCache( + state.host, + normalizeSlashes(directory), + (ancestorDirectory) => { + if (getBaseFileName(ancestorDirectory) !== "node_modules") { + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, ancestorDirectory, redirectedReference, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions2, moduleName, ancestorDirectory, state, typesScopeOnly, cache, redirectedReference)); + } + } + ); + } +} +function forEachAncestorDirectoryStoppingAtGlobalCache(host, directory, callback) { + var _a; + const globalCache = (_a = host == null ? void 0 : host.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(host); + return forEachAncestorDirectory(directory, (ancestorDirectory) => { + const result = callback(ancestorDirectory); + if (result !== void 0) return result; + if (ancestorDirectory === globalCache) return false; + }) || void 0; +} +function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { + const nodeModulesFolder = combinePaths(directory, "node_modules"); + const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + if (!typesScopeOnly) { + const packageResult = loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state, cache, redirectedReference); + if (packageResult) { + return packageResult; + } + } + if (extensions & 4 /* Declaration */) { + const nodeModulesAtTypes2 = combinePaths(nodeModulesFolder, "@types"); + let nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes2, state.host)) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes2); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromSpecificNodeModulesDirectory(4 /* Declaration */, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes2, nodeModulesAtTypesExists, state, cache, redirectedReference); + } +} +function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state, cache, redirectedReference) { + var _a, _b; + const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName)); + const { packageName, rest } = parsePackageName(moduleName); + const packageDirectory = combinePaths(nodeModulesDirectory, packageName); + let rootPackageInfo; + let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state); + if (rest !== "" && packageInfo && (!(state.features & 8 /* Exports */) || !hasProperty(((_a = rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state)) == null ? void 0 : _a.contents.packageJsonContent) ?? emptyArray, "exports"))) { + const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + const fromDirectory = loadNodeModuleFromDirectoryWorker( + extensions, + candidate, + !nodeModulesDirectoryExists, + state, + packageInfo + ); + return withPackageId(packageInfo, fromDirectory, state); + } + const loader = (extensions2, candidate2, onlyRecordFailures, state2) => { + let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( + extensions2, + candidate2, + onlyRecordFailures, + state2, + packageInfo + ); + if (!pathAndExtension && !rest && packageInfo && (packageInfo.contents.packageJsonContent.exports === void 0 || packageInfo.contents.packageJsonContent.exports === null) && state2.features & 32 /* EsmMode */) { + pathAndExtension = loadModuleFromFile(extensions2, combinePaths(candidate2, "index.js"), onlyRecordFailures, state2); + } + return withPackageId(packageInfo, pathAndExtension, state2); + }; + if (rest !== "") { + packageInfo = rootPackageInfo ?? getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state); + } + if (packageInfo) { + state.resolvedPackageDirectory = true; + } + if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & 8 /* Exports */) { + return (_b = loadModuleFromExports(packageInfo, extensions, combinePaths(".", rest), state, cache, redirectedReference)) == null ? void 0 : _b.value; + } + const versionPaths = rest !== "" && packageInfo ? getVersionPathsOfPackageJsonInfo(packageInfo, state) : void 0; + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest); + } + const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host); + const pathPatterns = tryParsePatterns(versionPaths.paths); + const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, pathPatterns, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); +} +function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, onlyRecordFailures, state) { + const matchedPattern = matchPatternOrExact(pathPatterns, moduleName); + if (matchedPattern) { + const matchedStar = isString(matchedPattern) ? void 0 : matchedText(matchedPattern, moduleName); + const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + const resolved = forEach(paths[matchedPatternText], (subst) => { + const path = matchedStar ? replaceFirstStar(subst, matchedStar) : subst; + const candidate = normalizePath(combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + const extension = tryGetExtensionFromPath2(subst); + if (extension !== void 0) { + const path2 = tryFile(candidate, onlyRecordFailures, state); + if (path2 !== void 0) { + return noPackageId({ path: path2, ext: extension, resolvedUsingTsExtension: void 0 }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; + } +} +var mangledScopedPackageSeparator = "__"; +function mangleScopedPackageNameWithTrace(packageName, state) { + const mangled = mangleScopedPackageName(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; +} +function getTypesPackageName(packageName) { + return `@types/${mangleScopedPackageName(packageName)}`; +} +function mangleScopedPackageName(packageName) { + if (startsWith(packageName, "@")) { + const replaceSlash = packageName.replace(directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); + } + } + return packageName; +} +function getPackageNameFromTypesPackageName(mangledName) { + const withoutAtTypePrefix = removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return unmangleScopedPackageName(withoutAtTypePrefix); + } + return mangledName; +} +function unmangleScopedPackageName(typesPackageName) { + return typesPackageName.includes(mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName; +} +function tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, containingDirectory, redirectedReference, state) { + const result = cache && cache.getFromNonRelativeNameCache(moduleName, mode, containingDirectory, redirectedReference); + if (result) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + } + state.resultFromCache = result; + return { + value: result.resolvedModule && { + path: result.resolvedModule.resolvedFileName, + originalPath: result.resolvedModule.originalPath || true, + extension: result.resolvedModule.extension, + packageId: result.resolvedModule.packageId, + resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension + } + }; + } +} +function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { + const traceEnabled = isTraceEnabled(compilerOptions, host); + const failedLookupLocations = []; + const affectingLocations = []; + const containingDirectory = getDirectoryPath(containingFile); + const diagnostics = []; + const state = { + compilerOptions, + host, + traceEnabled, + failedLookupLocations, + affectingLocations, + packageJsonInfoCache: cache, + features: 0 /* None */, + conditions: [], + requestContainingDirectory: containingDirectory, + reportDiagnostic: (diag2) => void diagnostics.push(diag2), + isConfigLookup: false, + candidateIsFromPackageJsonField: false, + resolvedPackageDirectory: false + }; + const resolved = tryResolve(1 /* TypeScript */ | 4 /* Declaration */) || tryResolve(2 /* JavaScript */ | (compilerOptions.resolveJsonModule ? 8 /* Json */ : 0)); + return createResolvedModuleWithFailedLookupLocationsHandlingSymlink( + moduleName, + resolved && resolved.value, + (resolved == null ? void 0 : resolved.value) && pathContainsNodeModules(resolved.value.path), + failedLookupLocations, + affectingLocations, + diagnostics, + state, + cache + ); + function tryResolve(extensions) { + const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + if (!isExternalModuleNameRelative(moduleName)) { + const resolved2 = forEachAncestorDirectoryStoppingAtGlobalCache( + state.host, + containingDirectory, + (directory) => { + const resolutionFromCache = tryFindNonRelativeModuleNameInCache( + cache, + moduleName, + /*mode*/ + void 0, + directory, + redirectedReference, + state + ); + if (resolutionFromCache) { + return resolutionFromCache; + } + const searchName = normalizePath(combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId( + extensions, + searchName, + /*onlyRecordFailures*/ + false, + state + )); + } + ); + if (resolved2) return resolved2; + if (extensions & (1 /* TypeScript */ | 4 /* Declaration */)) { + let resolved3 = loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); + if (extensions & 4 /* Declaration */) resolved3 ?? (resolved3 = resolveFromTypeRoot(moduleName, state)); + return resolved3; + } + } else { + const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId( + extensions, + candidate, + /*onlyRecordFailures*/ + false, + state + )); + } + } +} +function resolveFromTypeRoot(moduleName, state) { + if (!state.compilerOptions.typeRoots) return; + for (const typeRoot of state.compilerOptions.typeRoots) { + const candidate = getCandidateFromTypeRoot(typeRoot, moduleName, state); + const directoryExists = directoryProbablyExists(typeRoot, state.host); + if (!directoryExists && state.traceEnabled) { + trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, typeRoot); + } + const resolvedFromFile = loadModuleFromFile(4 /* Declaration */, candidate, !directoryExists, state); + if (resolvedFromFile) { + const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path); + const packageInfo = packageDirectory ? getPackageJsonInfo( + packageDirectory, + /*onlyRecordFailures*/ + false, + state + ) : void 0; + return toSearchResult(withPackageId(packageInfo, resolvedFromFile, state)); + } + const resolved = loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, state); + if (resolved) return toSearchResult(resolved); + } +} +function shouldAllowImportingTsExtension(compilerOptions, fromFileName) { + return getAllowImportingTsExtensions(compilerOptions) || !!fromFileName && isDeclarationFileName(fromFileName); +} +function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { + const traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + const failedLookupLocations = []; + const affectingLocations = []; + const diagnostics = []; + const state = { + compilerOptions, + host, + traceEnabled, + failedLookupLocations, + affectingLocations, + packageJsonInfoCache, + features: 0 /* None */, + conditions: [], + requestContainingDirectory: void 0, + reportDiagnostic: (diag2) => void diagnostics.push(diag2), + isConfigLookup: false, + candidateIsFromPackageJsonField: false, + resolvedPackageDirectory: false + }; + const resolved = loadModuleFromImmediateNodeModulesDirectory( + 4 /* Declaration */, + moduleName, + globalCache, + state, + /*typesScopeOnly*/ + false, + /*cache*/ + void 0, + /*redirectedReference*/ + void 0 + ); + return createResolvedModuleWithFailedLookupLocations( + resolved, + /*isExternalLibraryImport*/ + true, + failedLookupLocations, + affectingLocations, + diagnostics, + state.resultFromCache, + /*cache*/ + void 0 + ); +} +function toSearchResult(value) { + return value !== void 0 ? { value } : void 0; +} +function traceIfEnabled(state, diagnostic, ...args) { + if (state.traceEnabled) { + trace(state.host, diagnostic, ...args); + } +} +function useCaseSensitiveFileNames(state) { + return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); +} + +// src/compiler/binder.ts +function getModuleInstanceState(node, visited) { + if (node.body && !node.body.parent) { + setParent(node.body, node); + setParentRecursive( + node.body, + /*incremental*/ + false + ); + } + return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */; +} +function getModuleInstanceStateCached(node, visited = /* @__PURE__ */ new Map()) { + const nodeId = getNodeId(node); + if (visited.has(nodeId)) { + return visited.get(nodeId) || 0 /* NonInstantiated */; + } + visited.set(nodeId, void 0); + const result = getModuleInstanceStateWorker(node, visited); + visited.set(nodeId, result); + return result; +} +function getModuleInstanceStateWorker(node, visited) { + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 266 /* EnumDeclaration */: + if (isEnumConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 272 /* ImportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + if (!hasSyntacticModifier(node, 32 /* Export */)) { + return 0 /* NonInstantiated */; + } + break; + // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain + case 278 /* ExportDeclaration */: + const exportDeclaration = node; + if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 279 /* NamedExports */) { + let state = 0 /* NonInstantiated */; + for (const specifier of exportDeclaration.exportClause.elements) { + const specifierState = getModuleInstanceStateForAliasTarget(specifier, visited); + if (specifierState > state) { + state = specifierState; + } + if (state === 1 /* Instantiated */) { + return state; + } + } + return state; + } + break; + // 5. other uninstantiated module declarations. + case 268 /* ModuleBlock */: { + let state = 0 /* NonInstantiated */; + forEachChild(node, (n) => { + const childState = getModuleInstanceStateCached(n, visited); + switch (childState) { + case 0 /* NonInstantiated */: + return; + case 2 /* ConstEnumOnly */: + state = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + state = 1 /* Instantiated */; + return true; + default: + Debug.assertNever(childState); + } + }); + return state; + } + case 267 /* ModuleDeclaration */: + return getModuleInstanceState(node, visited); + case 80 /* Identifier */: + if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */) { + return 0 /* NonInstantiated */; + } + } + return 1 /* Instantiated */; +} +function getModuleInstanceStateForAliasTarget(specifier, visited) { + const name = specifier.propertyName || specifier.name; + if (name.kind !== 80 /* Identifier */) { + return 1 /* Instantiated */; + } + let p = specifier.parent; + while (p) { + if (isBlock(p) || isModuleBlock(p) || isSourceFile(p)) { + const statements = p.statements; + let found; + for (const statement of statements) { + if (nodeHasName(statement, name)) { + if (!statement.parent) { + setParent(statement, p); + setParentRecursive( + statement, + /*incremental*/ + false + ); + } + const state = getModuleInstanceStateCached(statement, visited); + if (found === void 0 || state > found) { + found = state; + } + if (found === 1 /* Instantiated */) { + return found; + } + if (statement.kind === 271 /* ImportEqualsDeclaration */) { + found = 1 /* Instantiated */; + } + } + } + if (found !== void 0) { + return found; + } + } + p = p.parent; + } + return 1 /* Instantiated */; +} +function createFlowNode(flags, node, antecedent) { + return Debug.attachFlowNodeDebugInfo({ flags, id: 0, node, antecedent }); +} +var binder = /* @__PURE__ */ createBinder(); +function bindSourceFile(file, options) { + mark("beforeBind"); + binder(file, options); + mark("afterBind"); + measure("Bind", "beforeBind", "afterBind"); +} +function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var thisParentContainer; + var blockScopeContainer; + var lastContainer; + var delayedTypeAliases; + var seenThisKeyword; + var jsDocImports; + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var currentExceptionTarget; + var preSwitchCaseFlow; + var activeLabelList; + var hasExplicitReturn; + var inReturnPosition; + var hasFlowEffects; + var emitFlags; + var inStrictMode; + var inAssignmentPattern = false; + var symbolCount = 0; + var Symbol13; + var classifiableNames; + var unreachableFlow = createFlowNode( + 1 /* Unreachable */, + /*node*/ + void 0, + /*antecedent*/ + void 0 + ); + var reportedUnreachableFlow = createFlowNode( + 1 /* Unreachable */, + /*node*/ + void 0, + /*antecedent*/ + void 0 + ); + var bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); + return bindSourceFile2; + function createDiagnosticForNode2(node, message, ...args) { + return createDiagnosticForNodeInSourceFile(getSourceFileOfNode(node) || file, node, message, ...args); + } + function bindSourceFile2(f, opts) { + var _a, _b; + file = f; + options = opts; + languageVersion = getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = /* @__PURE__ */ new Set(); + symbolCount = 0; + Symbol13 = objectAllocator.getSymbolConstructor(); + Debug.attachFlowNodeDebugInfo(unreachableFlow); + Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); + if (!file.locals) { + (_a = tracing) == null ? void 0 : _a.push( + tracing.Phase.Bind, + "bindSourceFile", + { path: file.path }, + /*separateBeginAndEnd*/ + true + ); + bind(file); + (_b = tracing) == null ? void 0 : _b.pop(); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + delayedBindJSDocTypedefTag(); + bindJSDocImports(); + } + file = void 0; + options = void 0; + languageVersion = void 0; + parent = void 0; + container = void 0; + thisParentContainer = void 0; + blockScopeContainer = void 0; + lastContainer = void 0; + delayedTypeAliases = void 0; + jsDocImports = void 0; + seenThisKeyword = false; + currentFlow = void 0; + currentBreakTarget = void 0; + currentContinueTarget = void 0; + currentReturnTarget = void 0; + currentTrueTarget = void 0; + currentFalseTarget = void 0; + currentExceptionTarget = void 0; + activeLabelList = void 0; + hasExplicitReturn = false; + inReturnPosition = false; + hasFlowEffects = false; + inAssignmentPattern = false; + emitFlags = 0 /* None */; + } + function bindInStrictMode(file2, opts) { + if (getStrictOptionValue(opts, "alwaysStrict") && !file2.isDeclarationFile) { + return true; + } else { + return !!file2.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol13(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + symbol.declarations = appendIfUnique(symbol.declarations, node); + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { + symbol.exports = createSymbolTable(); + } + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { + symbol.members = createSymbolTable(); + } + if (symbol.constEnumOnlyModule && symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { + symbol.constEnumOnlyModule = false; + } + if (symbolFlags & 111551 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function getDeclarationName(node) { + if (node.kind === 277 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } + const name = getNameOfDeclaration(node); + if (name) { + if (isAmbientModule(node)) { + const moduleName = getTextOfIdentifierOrLiteral(name); + return isGlobalScopeAugmentation(node) ? "__global" : `"${moduleName}"`; + } + if (name.kind === 167 /* ComputedPropertyName */) { + const nameExpression = name.expression; + if (isStringOrNumericLiteralLike(nameExpression)) { + return escapeLeadingUnderscores(nameExpression.text); + } + if (isSignedNumericLiteral(nameExpression)) { + return tokenToString(nameExpression.operator) + nameExpression.operand.text; + } else { + Debug.fail("Only computed properties with literal names have declaration names"); + } + } + if (isPrivateIdentifier(name)) { + const containingClass = getContainingClass(node); + if (!containingClass) { + return void 0; + } + const containingClassSymbol = containingClass.symbol; + return getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText); + } + if (isJsxNamespacedName(name)) { + return getEscapedTextOfJsxNamespacedName(name); + } + return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0; + } + switch (node.kind) { + case 176 /* Constructor */: + return "__constructor" /* Constructor */; + case 184 /* FunctionType */: + case 179 /* CallSignature */: + case 323 /* JSDocSignature */: + return "__call" /* Call */; + case 185 /* ConstructorType */: + case 180 /* ConstructSignature */: + return "__new" /* New */; + case 181 /* IndexSignature */: + return "__index" /* Index */; + case 278 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 307 /* SourceFile */: + return "export=" /* ExportEquals */; + case 226 /* BinaryExpression */: + if (getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { + return "export=" /* ExportEquals */; + } + Debug.fail("Unknown binary declaration kind"); + break; + case 317 /* JSDocFunctionType */: + return isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */; + case 169 /* Parameter */: + Debug.assert(node.parent.kind === 317 /* JSDocFunctionType */, "Impossible parameter parent kind", () => `parent is: ${Debug.formatSyntaxKind(node.parent.kind)}, expected JSDocFunctionType`); + const functionType = node.parent; + const index = functionType.parameters.indexOf(node); + return "arg" + index; + } + } + function getDisplayName(node) { + return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(Debug.checkDefined(getDeclarationName(node))); + } + function declareSymbol(symbolTable, parent2, node, includes, excludes, isReplaceableByMethod, isComputedName) { + Debug.assert(isComputedName || !hasDynamicName(node)); + const isDefaultExport = hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) && moduleExportNameIsDefault(node.name); + const name = isComputedName ? "__computed" /* Computed */ : isDefaultExport && parent2 ? "default" /* Default */ : getDeclarationName(node); + let symbol; + if (name === void 0) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } else { + symbol = symbolTable.get(name); + if (includes & 2885600 /* Classifiable */) { + classifiableNames.add(name); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) symbol.isReplaceableByMethod = true; + } else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + return symbol; + } else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + if (isNamedDeclaration(node)) { + setParent(node.name, node); + } + let message = symbol.flags & 2 /* BlockScopedVariable */ ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; + let messageNeedsName = true; + if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { + message = Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName = false; + } + let multipleDefaultExports = false; + if (length(symbol.declarations)) { + if (isDefaultExport) { + message = Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName = false; + multipleDefaultExports = true; + } else { + if (symbol.declarations && symbol.declarations.length && (node.kind === 277 /* ExportAssignment */ && !node.isExportEquals)) { + message = Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName = false; + multipleDefaultExports = true; + } + } + } + const relatedInformation = []; + if (isTypeAliasDeclaration(node) && nodeIsMissing(node.type) && hasSyntacticModifier(node, 32 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) { + relatedInformation.push(createDiagnosticForNode2(node, Diagnostics.Did_you_mean_0, `export type { ${unescapeLeadingUnderscores(node.name.escapedText)} }`)); + } + const declarationName = getNameOfDeclaration(node) || node; + forEach(symbol.declarations, (declaration, index) => { + const decl = getNameOfDeclaration(declaration) || declaration; + const diag3 = messageNeedsName ? createDiagnosticForNode2(decl, message, getDisplayName(declaration)) : createDiagnosticForNode2(decl, message); + file.bindDiagnostics.push( + multipleDefaultExports ? addRelatedInfo(diag3, createDiagnosticForNode2(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag3 + ); + if (multipleDefaultExports) { + relatedInformation.push(createDiagnosticForNode2(decl, Diagnostics.The_first_export_default_is_here)); + } + }); + const diag2 = messageNeedsName ? createDiagnosticForNode2(declarationName, message, getDisplayName(node)) : createDiagnosticForNode2(declarationName, message); + file.bindDiagnostics.push(addRelatedInfo(diag2, ...relatedInformation)); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + if (symbol.parent) { + Debug.assert(symbol.parent === parent2, "Existing symbol parent should match new one"); + } else { + symbol.parent = parent2; + } + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + const hasExportModifier = !!(getCombinedModifierFlags(node) & 32 /* Export */) || jsdocTreatAsExported(node); + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 281 /* ExportSpecifier */ || node.kind === 271 /* ImportEqualsDeclaration */ && hasExportModifier) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } else { + Debug.assertNode(container, canHaveLocals); + return declareSymbol( + container.locals, + /*parent*/ + void 0, + node, + symbolFlags, + symbolExcludes + ); + } + } else { + if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); + if (!isAmbientModule(node) && (hasExportModifier || container.flags & 128 /* ExportContext */)) { + if (!canHaveLocals(container) || !container.locals || hasSyntacticModifier(node, 2048 /* Default */) && !getDeclarationName(node)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + const exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0; + const local = declareSymbol( + container.locals, + /*parent*/ + void 0, + node, + exportKind, + symbolExcludes + ); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } else { + Debug.assertNode(container, canHaveLocals); + return declareSymbol( + container.locals, + /*parent*/ + void 0, + node, + symbolFlags, + symbolExcludes + ); + } + } + } + function jsdocTreatAsExported(node) { + if (node.parent && isModuleDeclaration(node)) { + node = node.parent; + } + if (!isJSDocTypeAlias(node)) return false; + if (!isJSDocEnumTag(node) && !!node.fullName) return true; + const declName = getNameOfDeclaration(node); + if (!declName) return false; + if (isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent)) return true; + if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & 32 /* Export */) return true; + return false; + } + function bindContainer(node, containerFlags) { + const saveContainer = container; + const saveThisParentContainer = thisParentContainer; + const savedBlockScopeContainer = blockScopeContainer; + const savedInReturnPosition = inReturnPosition; + if (node.kind === 219 /* ArrowFunction */ && node.body.kind !== 241 /* Block */) inReturnPosition = true; + if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 219 /* ArrowFunction */) { + thisParentContainer = container; + } + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = createSymbolTable(); + addToContainerChain(container); + } + } else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + blockScopeContainer.locals = void 0; + } + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + const saveCurrentFlow = currentFlow; + const saveBreakTarget = currentBreakTarget; + const saveContinueTarget = currentContinueTarget; + const saveReturnTarget = currentReturnTarget; + const saveExceptionTarget = currentExceptionTarget; + const saveActiveLabelList = activeLabelList; + const saveHasExplicitReturn = hasExplicitReturn; + const isImmediatelyInvoked = containerFlags & 16 /* IsFunctionExpression */ && !hasSyntacticModifier(node, 1024 /* Async */) && !node.asteriskToken && !!getImmediatelyInvokedFunctionExpression(node) || node.kind === 175 /* ClassStaticBlockDeclaration */; + if (!isImmediatelyInvoked) { + currentFlow = createFlowNode( + 2 /* Start */, + /*node*/ + void 0, + /*antecedent*/ + void 0 + ); + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */)) { + currentFlow.node = node; + } + } + currentReturnTarget = isImmediatelyInvoked || node.kind === 176 /* Constructor */ || isInJSFile(node) && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */) ? createBranchLabel() : void 0; + currentExceptionTarget = void 0; + currentBreakTarget = void 0; + currentContinueTarget = void 0; + activeLabelList = void 0; + hasExplicitReturn = false; + bindChildren(node); + node.flags &= ~5632 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && nodeIsPresent(node.body)) { + node.flags |= 512 /* HasImplicitReturn */; + if (hasExplicitReturn) node.flags |= 1024 /* HasExplicitReturn */; + node.endFlowNode = currentFlow; + } + if (node.kind === 307 /* SourceFile */) { + node.flags |= emitFlags; + node.endFlowNode = currentFlow; + } + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 176 /* Constructor */ || node.kind === 175 /* ClassStaticBlockDeclaration */ || isInJSFile(node) && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */)) { + node.returnFlowNode = currentFlow; + } + } + if (!isImmediatelyInvoked) { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + currentExceptionTarget = saveExceptionTarget; + activeLabelList = saveActiveLabelList; + hasExplicitReturn = saveHasExplicitReturn; + } else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + Debug.assertNotNode(node, isIdentifier); + node.flags = seenThisKeyword ? node.flags | 256 /* ContainsThis */ : node.flags & ~256 /* ContainsThis */; + } else { + bindChildren(node); + } + inReturnPosition = savedInReturnPosition; + container = saveContainer; + thisParentContainer = saveThisParentContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, (n) => n.kind === 262 /* FunctionDeclaration */ ? bind(n) : void 0); + bindEach(nodes, (n) => n.kind !== 262 /* FunctionDeclaration */ ? bind(n) : void 0); + } + function bindEach(nodes, bindFunction = bind) { + if (nodes === void 0) { + return; + } + forEach(nodes, bindFunction); + } + function bindEachChild(node) { + forEachChild(node, bind, bindEach); + } + function bindChildren(node) { + const saveInAssignmentPattern = inAssignmentPattern; + inAssignmentPattern = false; + if (checkUnreachable(node)) { + if (canHaveFlowNode(node) && node.flowNode) { + node.flowNode = void 0; + } + bindEachChild(node); + bindJSDoc(node); + inAssignmentPattern = saveInAssignmentPattern; + return; + } + if (node.kind >= 243 /* FirstStatement */ && node.kind <= 259 /* LastStatement */ && (!options.allowUnreachableCode || node.kind === 253 /* ReturnStatement */)) { + node.flowNode = currentFlow; + } + switch (node.kind) { + case 247 /* WhileStatement */: + bindWhileStatement(node); + break; + case 246 /* DoStatement */: + bindDoStatement(node); + break; + case 248 /* ForStatement */: + bindForStatement(node); + break; + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 245 /* IfStatement */: + bindIfStatement(node); + break; + case 253 /* ReturnStatement */: + case 257 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 252 /* BreakStatement */: + case 251 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 258 /* TryStatement */: + bindTryStatement(node); + break; + case 255 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 269 /* CaseBlock */: + bindCaseBlock(node); + break; + case 296 /* CaseClause */: + bindCaseClause(node); + break; + case 244 /* ExpressionStatement */: + bindExpressionStatement(node); + break; + case 256 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 224 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 225 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 226 /* BinaryExpression */: + if (isDestructuringAssignment(node)) { + inAssignmentPattern = saveInAssignmentPattern; + bindDestructuringAssignmentFlow(node); + return; + } + bindBinaryExpressionFlow(node); + break; + case 220 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 227 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 260 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + bindAccessExpressionFlow(node); + break; + case 213 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 235 /* NonNullExpression */: + bindNonNullExpressionFlow(node); + break; + case 346 /* JSDocTypedefTag */: + case 338 /* JSDocCallbackTag */: + case 340 /* JSDocEnumTag */: + bindJSDocTypeAlias(node); + break; + case 351 /* JSDocImportTag */: + bindJSDocImportTag(node); + break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 307 /* SourceFile */: { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } + case 241 /* Block */: + case 268 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; + case 208 /* BindingElement */: + bindBindingElementFlow(node); + break; + case 169 /* Parameter */: + bindParameterFlow(node); + break; + case 210 /* ObjectLiteralExpression */: + case 209 /* ArrayLiteralExpression */: + case 303 /* PropertyAssignment */: + case 230 /* SpreadElement */: + inAssignmentPattern = saveInAssignmentPattern; + // falls through + default: + bindEachChild(node); + break; + } + bindJSDoc(node); + inAssignmentPattern = saveInAssignmentPattern; + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 80 /* Identifier */: + case 110 /* ThisKeyword */: + return true; + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + return containsNarrowableReference(expr); + case 213 /* CallExpression */: + return hasNarrowableArgument(expr); + case 217 /* ParenthesizedExpression */: + if (isJSDocTypeAssertion(expr)) { + return false; + } + // fallthrough + case 235 /* NonNullExpression */: + return isNarrowingExpression(expr.expression); + case 226 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 224 /* PrefixUnaryExpression */: + return expr.operator === 54 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 221 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); + } + return false; + } + function isNarrowableReference(expr) { + switch (expr.kind) { + case 80 /* Identifier */: + case 110 /* ThisKeyword */: + case 108 /* SuperKeyword */: + case 236 /* MetaProperty */: + return true; + case 211 /* PropertyAccessExpression */: + case 217 /* ParenthesizedExpression */: + case 235 /* NonNullExpression */: + return isNarrowableReference(expr.expression); + case 212 /* ElementAccessExpression */: + return (isStringOrNumericLiteralLike(expr.argumentExpression) || isEntityNameExpression(expr.argumentExpression)) && isNarrowableReference(expr.expression); + case 226 /* BinaryExpression */: + return expr.operatorToken.kind === 28 /* CommaToken */ && isNarrowableReference(expr.right) || isAssignmentOperator(expr.operatorToken.kind) && isLeftHandSideExpression(expr.left); + } + return false; + } + function containsNarrowableReference(expr) { + return isNarrowableReference(expr) || isOptionalChain(expr) && containsNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (const argument of expr.arguments) { + if (containsNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 211 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && isStringLiteralLike(expr2); + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 64 /* EqualsToken */: + case 76 /* BarBarEqualsToken */: + case 77 /* AmpersandAmpersandEqualsToken */: + case 78 /* QuestionQuestionEqualsToken */: + return containsNarrowableReference(expr.left); + case 35 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsToken */: + case 37 /* EqualsEqualsEqualsToken */: + case 38 /* ExclamationEqualsEqualsToken */: + const left = skipParentheses(expr.left); + const right = skipParentheses(expr.right); + return isNarrowableOperand(left) || isNarrowableOperand(right) || isNarrowingTypeofOperands(right, left) || isNarrowingTypeofOperands(left, right) || (isBooleanLiteral(right) && isNarrowingExpression(left) || isBooleanLiteral(left) && isNarrowingExpression(right)); + case 104 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 103 /* InKeyword */: + return isNarrowingExpression(expr.right); + case 28 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 217 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 226 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 64 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 28 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return containsNarrowableReference(expr); + } + function createBranchLabel() { + return createFlowNode( + 4 /* BranchLabel */, + /*node*/ + void 0, + /*antecedent*/ + void 0 + ); + } + function createLoopLabel() { + return createFlowNode( + 8 /* LoopLabel */, + /*node*/ + void 0, + /*antecedent*/ + void 0 + ); + } + function createReduceLabel(target, antecedents, antecedent) { + return createFlowNode(1024 /* ReduceLabel */, { target, antecedents }, antecedent); + } + function setFlowNodeReferenced(flow) { + flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !contains(label.antecedent, antecedent)) { + (label.antecedent || (label.antecedent = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if ((expression.kind === 112 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 97 /* FalseKeyword */ && flags & 32 /* TrueCondition */) && !isExpressionOfOptionalChainRoot(expression) && !isNullishCoalesce(expression.parent)) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return createFlowNode(flags, expression, antecedent); + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + setFlowNodeReferenced(antecedent); + return createFlowNode(128 /* SwitchClause */, { switchStatement, clauseStart, clauseEnd }, antecedent); + } + function createFlowMutation(flags, antecedent, node) { + setFlowNodeReferenced(antecedent); + hasFlowEffects = true; + const result = createFlowNode(flags, node, antecedent); + if (currentExceptionTarget) { + addAntecedent(currentExceptionTarget, result); + } + return result; + } + function createFlowCall(antecedent, node) { + setFlowNodeReferenced(antecedent); + hasFlowEffects = true; + return createFlowNode(512 /* Call */, node, antecedent); + } + function finishFlowLabel(flow) { + const antecedents = flow.antecedent; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + const parent2 = node.parent; + switch (parent2.kind) { + case 245 /* IfStatement */: + case 247 /* WhileStatement */: + case 246 /* DoStatement */: + return parent2.expression === node; + case 248 /* ForStatement */: + case 227 /* ConditionalExpression */: + return parent2.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 217 /* ParenthesizedExpression */) { + node = node.expression; + } else if (node.kind === 224 /* PrefixUnaryExpression */ && node.operator === 54 /* ExclamationToken */) { + node = node.operand; + } else { + return isLogicalOrCoalescingBinaryExpression(node); + } + } + } + function isLogicalAssignmentExpression(node) { + return isLogicalOrCoalescingAssignmentExpression(skipParentheses(node)); + } + function isTopLevelLogicalExpression(node) { + while (isParenthesizedExpression(node.parent) || isPrefixUnaryExpression(node.parent) && node.parent.operator === 54 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent) && !(isOptionalChain(node.parent) && node.parent.expression === node); + } + function doWithConditionalBranches(action, value, trueTarget, falseTarget) { + const savedTrueTarget = currentTrueTarget; + const savedFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + action(value); + currentTrueTarget = savedTrueTarget; + currentFalseTarget = savedFalseTarget; + } + function bindCondition(node, trueTarget, falseTarget) { + doWithConditionalBranches(bind, node, trueTarget, falseTarget); + if (!node || !isLogicalAssignmentExpression(node) && !isLogicalExpression(node) && !(isOptionalChain(node) && isOutermostOptionalChain(node))) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + const saveBreakTarget = currentBreakTarget; + const saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function setContinueTarget(node, target) { + let label = activeLabelList; + while (label && node.parent.kind === 256 /* LabeledStatement */) { + label.continueTarget = target; + label = label.next; + node = node.parent; + } + return target; + } + function bindWhileStatement(node) { + const preWhileLabel = setContinueTarget(node, createLoopLabel()); + const preBodyLabel = createBranchLabel(); + const postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + const preDoLabel = createLoopLabel(); + const preConditionLabel = setContinueTarget(node, createBranchLabel()); + const postDoLabel = createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + const preLoopLabel = setContinueTarget(node, createLoopLabel()); + const preBodyLabel = createBranchLabel(); + const preIncrementorLabel = createBranchLabel(); + const postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preIncrementorLabel); + addAntecedent(preIncrementorLabel, currentFlow); + currentFlow = finishFlowLabel(preIncrementorLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + const preLoopLabel = setContinueTarget(node, createLoopLabel()); + const postLoopLabel = createBranchLabel(); + bind(node.expression); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 250 /* ForOfStatement */) { + bind(node.awaitModifier); + } + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 261 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + const thenLabel = createBranchLabel(); + const elseLabel = createBranchLabel(); + const postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + const savedInReturnPosition = inReturnPosition; + inReturnPosition = true; + bind(node.expression); + inReturnPosition = savedInReturnPosition; + if (node.kind === 253 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + hasFlowEffects = true; + } + function findActiveLabel(name) { + for (let label = activeLabelList; label; label = label.next) { + if (label.name === name) { + return label; + } + } + return void 0; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + const flowLabel = node.kind === 252 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + hasFlowEffects = true; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + const activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + const saveReturnTarget = currentReturnTarget; + const saveExceptionTarget = currentExceptionTarget; + const normalExitLabel = createBranchLabel(); + const returnLabel = createBranchLabel(); + let exceptionLabel = createBranchLabel(); + if (node.finallyBlock) { + currentReturnTarget = returnLabel; + } + addAntecedent(exceptionLabel, currentFlow); + currentExceptionTarget = exceptionLabel; + bind(node.tryBlock); + addAntecedent(normalExitLabel, currentFlow); + if (node.catchClause) { + currentFlow = finishFlowLabel(exceptionLabel); + exceptionLabel = createBranchLabel(); + addAntecedent(exceptionLabel, currentFlow); + currentExceptionTarget = exceptionLabel; + bind(node.catchClause); + addAntecedent(normalExitLabel, currentFlow); + } + currentReturnTarget = saveReturnTarget; + currentExceptionTarget = saveExceptionTarget; + if (node.finallyBlock) { + const finallyLabel = createBranchLabel(); + finallyLabel.antecedent = concatenate(concatenate(normalExitLabel.antecedent, exceptionLabel.antecedent), returnLabel.antecedent); + currentFlow = finallyLabel; + bind(node.finallyBlock); + if (currentFlow.flags & 1 /* Unreachable */) { + currentFlow = unreachableFlow; + } else { + if (currentReturnTarget && returnLabel.antecedent) { + addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedent, currentFlow)); + } + if (currentExceptionTarget && exceptionLabel.antecedent) { + addAntecedent(currentExceptionTarget, createReduceLabel(finallyLabel, exceptionLabel.antecedent, currentFlow)); + } + currentFlow = normalExitLabel.antecedent ? createReduceLabel(finallyLabel, normalExitLabel.antecedent, currentFlow) : unreachableFlow; + } + } else { + currentFlow = finishFlowLabel(normalExitLabel); + } + } + function bindSwitchStatement(node) { + const postSwitchLabel = createBranchLabel(); + bind(node.expression); + const saveBreakTarget = currentBreakTarget; + const savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + const hasDefault = forEach(node.caseBlock.clauses, (c) => c.kind === 297 /* DefaultClause */); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedent; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + const clauses = node.clauses; + const isNarrowingSwitch = node.parent.expression.kind === 112 /* TrueKeyword */ || isNarrowingExpression(node.parent.expression); + let fallthroughFlow = unreachableFlow; + for (let i = 0; i < clauses.length; i++) { + const clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + if (fallthroughFlow === unreachableFlow) { + currentFlow = preSwitchCaseFlow; + } + bind(clauses[i]); + i++; + } + const preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + const clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + clause.fallthroughFlowNode = currentFlow; + } + } + } + function bindCaseClause(node) { + const saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function bindExpressionStatement(node) { + bind(node.expression); + maybeBindExpressionFlowIfCall(node.expression); + } + function maybeBindExpressionFlowIfCall(node) { + if (node.kind === 213 /* CallExpression */) { + const call = node; + if (call.expression.kind !== 108 /* SuperKeyword */ && isDottedName(call.expression)) { + currentFlow = createFlowCall(currentFlow, call); + } + } + } + function bindLabeledStatement(node) { + const postStatementLabel = createBranchLabel(); + activeLabelList = { + next: activeLabelList, + name: node.label.escapedText, + breakTarget: postStatementLabel, + continueTarget: void 0, + referenced: false + }; + bind(node.label); + bind(node.statement); + if (!activeLabelList.referenced && !options.allowUnusedLabels) { + errorOrSuggestionOnNode(unusedLabelIsError(options), node.label, Diagnostics.Unused_label); + } + activeLabelList = activeLabelList.next; + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); + } else if (node.kind === 209 /* ArrayLiteralExpression */) { + for (const e of node.elements) { + if (e.kind === 230 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } else { + bindDestructuringTargetFlow(e); + } + } + } else if (node.kind === 210 /* ObjectLiteralExpression */) { + for (const p of node.properties) { + if (p.kind === 303 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } else if (p.kind === 304 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } else if (p.kind === 305 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalLikeExpression(node, trueTarget, falseTarget) { + const preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 77 /* AmpersandAmpersandEqualsToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + if (isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind)) { + doWithConditionalBranches(bind, node.right, trueTarget, falseTarget); + bindAssignmentTargetFlow(node.left); + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } else { + bindCondition(node.right, trueTarget, falseTarget); + } + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 54 /* ExclamationToken */) { + const saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } else { + bindEachChild(node); + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindDestructuringAssignmentFlow(node) { + if (inAssignmentPattern) { + inAssignmentPattern = false; + bind(node.operatorToken); + bind(node.right); + inAssignmentPattern = true; + bind(node.left); + } else { + inAssignmentPattern = true; + bind(node.left); + inAssignmentPattern = false; + bind(node.operatorToken); + bind(node.right); + } + bindAssignmentTargetFlow(node.left); + } + function createBindBinaryExpressionFlow() { + return createBinaryExpressionTrampoline( + onEnter, + onLeft, + onOperator, + onRight, + onExit, + /*foldState*/ + void 0 + ); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + setParent(node, parent); + const saveInStrictMode = inStrictMode; + bindWorker(node); + const saveParent = parent; + parent = node; + state.skip = false; + state.inStrictModeStack[state.stackIndex] = saveInStrictMode; + state.parentStack[state.stackIndex] = saveParent; + } else { + state = { + stackIndex: 0, + skip: false, + inStrictModeStack: [void 0], + parentStack: [void 0] + }; + } + const operator = node.operatorToken.kind; + if (isLogicalOrCoalescingBinaryOperator(operator) || isLogicalOrCoalescingAssignmentOperator(operator)) { + if (isTopLevelLogicalExpression(node)) { + const postExpressionLabel = createBranchLabel(); + const saveCurrentFlow = currentFlow; + const saveHasFlowEffects = hasFlowEffects; + hasFlowEffects = false; + bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = hasFlowEffects ? finishFlowLabel(postExpressionLabel) : saveCurrentFlow; + hasFlowEffects || (hasFlowEffects = saveHasFlowEffects); + } else { + bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); + } + state.skip = true; + } + return state; + } + function onLeft(left, state, node) { + if (!state.skip) { + const maybeBound = maybeBind2(left); + if (node.operatorToken.kind === 28 /* CommaToken */) { + maybeBindExpressionFlowIfCall(left); + } + return maybeBound; + } + } + function onOperator(operatorToken, state, _node) { + if (!state.skip) { + bind(operatorToken); + } + } + function onRight(right, state, node) { + if (!state.skip) { + const maybeBound = maybeBind2(right); + if (node.operatorToken.kind === 28 /* CommaToken */) { + maybeBindExpressionFlowIfCall(right); + } + return maybeBound; + } + } + function onExit(node, state) { + if (!state.skip) { + const operator = node.operatorToken.kind; + if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 64 /* EqualsToken */ && node.left.kind === 212 /* ElementAccessExpression */) { + const elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); + } + } + } + } + const savedInStrictMode = state.inStrictModeStack[state.stackIndex]; + const savedParent = state.parentStack[state.stackIndex]; + if (savedInStrictMode !== void 0) { + inStrictMode = savedInStrictMode; + } + if (savedParent !== void 0) { + parent = savedParent; + } + state.skip = false; + state.stackIndex--; + } + function maybeBind2(node) { + if (node && isBinaryExpression(node) && !isDestructuringAssignment(node)) { + return node; + } + bind(node); + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 211 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + const trueLabel = createBranchLabel(); + const falseLabel = createBranchLabel(); + const postExpressionLabel = createBranchLabel(); + const saveCurrentFlow = currentFlow; + const saveHasFlowEffects = hasFlowEffects; + hasFlowEffects = false; + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + if (inReturnPosition) { + node.flowNodeWhenTrue = currentFlow; + } + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + if (inReturnPosition) { + node.flowNodeWhenFalse = currentFlow; + } + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = hasFlowEffects ? finishFlowLabel(postExpressionLabel) : saveCurrentFlow; + hasFlowEffects || (hasFlowEffects = saveHasFlowEffects); + } + function bindInitializedVariableFlow(node) { + const name = !isOmittedExpression(node) ? node.name : void 0; + if (isBindingPattern(name)) { + for (const child of name.elements) { + bindInitializedVariableFlow(child); + } + } else { + currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindBindingElementFlow(node) { + bind(node.dotDotDotToken); + bind(node.propertyName); + bindInitializer(node.initializer); + bind(node.name); + } + function bindParameterFlow(node) { + bindEach(node.modifiers); + bind(node.dotDotDotToken); + bind(node.questionToken); + bind(node.type); + bindInitializer(node.initializer); + bind(node.name); + } + function bindInitializer(node) { + if (!node) { + return; + } + const entryFlow = currentFlow; + bind(node); + if (entryFlow === unreachableFlow || entryFlow === currentFlow) { + return; + } + const exitFlow = createBranchLabel(); + addAntecedent(exitFlow, entryFlow); + addAntecedent(exitFlow, currentFlow); + currentFlow = finishFlowLabel(exitFlow); + } + function bindJSDocTypeAlias(node) { + bind(node.tagName); + if (node.kind !== 340 /* JSDocEnumTag */ && node.fullName) { + setParent(node.fullName, node); + setParentRecursive( + node.fullName, + /*incremental*/ + false + ); + } + if (typeof node.comment !== "string") { + bindEach(node.comment); + } + } + function bindJSDocClassTag(node) { + bindEachChild(node); + const host = getHostSignatureFromJSDoc(node); + if (host && host.kind !== 174 /* MethodDeclaration */) { + addDeclarationToSymbol(host.symbol, host, 32 /* Class */); + } + } + function bindJSDocImportTag(node) { + bind(node.tagName); + bind(node.moduleSpecifier); + bind(node.attributes); + if (typeof node.comment !== "string") { + bindEach(node.comment); + } + } + function bindOptionalExpression(node, trueTarget, falseTarget) { + doWithConditionalBranches(bind, node, trueTarget, falseTarget); + if (!isOptionalChain(node) || isOutermostOptionalChain(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindOptionalChainRest(node) { + switch (node.kind) { + case 211 /* PropertyAccessExpression */: + bind(node.questionDotToken); + bind(node.name); + break; + case 212 /* ElementAccessExpression */: + bind(node.questionDotToken); + bind(node.argumentExpression); + break; + case 213 /* CallExpression */: + bind(node.questionDotToken); + bindEach(node.typeArguments); + bindEach(node.arguments); + break; + } + } + function bindOptionalChain(node, trueTarget, falseTarget) { + const preChainLabel = isOptionalChainRoot(node) ? createBranchLabel() : void 0; + bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget); + if (preChainLabel) { + currentFlow = finishFlowLabel(preChainLabel); + } + doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget); + if (isOutermostOptionalChain(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindOptionalChainFlow(node) { + if (isTopLevelLogicalExpression(node)) { + const postExpressionLabel = createBranchLabel(); + const saveCurrentFlow = currentFlow; + const saveHasFlowEffects = hasFlowEffects; + bindOptionalChain(node, postExpressionLabel, postExpressionLabel); + currentFlow = hasFlowEffects ? finishFlowLabel(postExpressionLabel) : saveCurrentFlow; + hasFlowEffects || (hasFlowEffects = saveHasFlowEffects); + } else { + bindOptionalChain(node, currentTrueTarget, currentFalseTarget); + } + } + function bindNonNullExpressionFlow(node) { + if (isOptionalChain(node)) { + bindOptionalChainFlow(node); + } else { + bindEachChild(node); + } + } + function bindAccessExpressionFlow(node) { + if (isOptionalChain(node)) { + bindOptionalChainFlow(node); + } else { + bindEachChild(node); + } + } + function bindCallExpressionFlow(node) { + if (isOptionalChain(node)) { + bindOptionalChainFlow(node); + } else { + const expr = skipParentheses(node.expression); + if (expr.kind === 218 /* FunctionExpression */ || expr.kind === 219 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } else { + bindEachChild(node); + if (node.expression.kind === 108 /* SuperKeyword */) { + currentFlow = createFlowCall(currentFlow, node); + } + } + } + if (node.expression.kind === 211 /* PropertyAccessExpression */) { + const propertyAccess = node.expression; + if (isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); + } + } + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 267 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 307 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 231 /* ClassExpression */: + case 263 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 266 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 187 /* TypeLiteral */: + case 322 /* JSDocTypeLiteral */: + case 210 /* ObjectLiteralExpression */: + case 264 /* InterfaceDeclaration */: + case 292 /* JsxAttributes */: + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 323 /* JSDocSignature */: + case 181 /* IndexSignature */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 317 /* JSDocFunctionType */: + case 175 /* ClassStaticBlockDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 200 /* MappedType */: + if (container.locals) Debug.assertNode(container, canHaveLocals); + return declareSymbol( + container.locals, + /*parent*/ + void 0, + node, + symbolFlags, + symbolExcludes + ); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return isStatic(node) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return isExternalModule(file) ? declareModuleMember(node, symbolFlags, symbolExcludes) : declareSymbol( + file.locals, + /*parent*/ + void 0, + node, + symbolFlags, + symbolExcludes + ); + } + function hasExportDeclarations(node) { + const body = isSourceFile(node) ? node : tryCast(node.body, isModuleBlock); + return !!body && body.statements.some((s) => isExportDeclaration(s) || isExportAssignment(s)); + } + function setExportContextFlag(node) { + if (node.flags & 33554432 /* Ambient */ && !hasExportDeclarations(node)) { + node.flags |= 128 /* ExportContext */; + } else { + node.flags &= ~128 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (isAmbientModule(node)) { + if (hasSyntacticModifier(node, 32 /* Export */)) { + errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (isModuleAugmentationExternal(node)) { + declareModuleSymbol(node); + } else { + let pattern; + if (node.name.kind === 11 /* StringLiteral */) { + const { text } = node.name; + pattern = tryParsePattern(text); + if (pattern === void 0) { + errorOnFirstToken(node.name, Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + const symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); + file.patternAmbientModules = append(file.patternAmbientModules, pattern && !isString(pattern) ? { pattern, symbol } : void 0); + } + } else { + const state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + const { symbol } = node; + symbol.constEnumOnlyModule = !(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) && state === 2 /* ConstEnumOnly */ && symbol.constEnumOnlyModule !== false; + } + } + } + function declareModuleSymbol(node) { + const state = getModuleInstanceState(node); + const instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable( + node, + instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, + instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */ + ); + return state; + } + function bindFunctionOrConstructorType(node) { + const symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + const typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, symbol); + } + function bindObjectLiteralExpression(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + const symbol = createSymbol(symbolFlags, name); + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { + symbol.parent = container.symbol; + } + addDeclarationToSymbol(symbol, node, symbolFlags); + return symbol; + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 267 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 307 /* SourceFile */: + if (isExternalOrCommonJsModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + Debug.assertNode(blockScopeContainer, canHaveLocals); + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol( + blockScopeContainer.locals, + /*parent*/ + void 0, + node, + symbolFlags, + symbolExcludes + ); + } + } + function delayedBindJSDocTypedefTag() { + if (!delayedTypeAliases) { + return; + } + const saveContainer = container; + const saveLastContainer = lastContainer; + const saveBlockScopeContainer = blockScopeContainer; + const saveParent = parent; + const saveCurrentFlow = currentFlow; + for (const typeAlias of delayedTypeAliases) { + const host = typeAlias.parent.parent; + container = getEnclosingContainer(host) || file; + blockScopeContainer = getEnclosingBlockScopeContainer(host) || file; + currentFlow = createFlowNode( + 2 /* Start */, + /*node*/ + void 0, + /*antecedent*/ + void 0 + ); + parent = typeAlias; + bind(typeAlias.typeExpression); + const declName = getNameOfDeclaration(typeAlias); + if ((isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && isPropertyAccessEntityNameExpression(declName.parent)) { + const isTopLevel = isTopLevelNamespaceAssignment(declName.parent); + if (isTopLevel) { + bindPotentiallyMissingNamespaces( + file.symbol, + declName.parent, + isTopLevel, + !!findAncestor(declName, (d) => isPropertyAccessExpression(d) && d.name.escapedText === "prototype"), + /*containerIsClass*/ + false + ); + const oldContainer = container; + switch (getAssignmentDeclarationPropertyAccessKind(declName.parent)) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + if (!isExternalOrCommonJsModule(file)) { + container = void 0; + } else { + container = file; + } + break; + case 4 /* ThisProperty */: + container = declName.parent.expression; + break; + case 3 /* PrototypeProperty */: + container = declName.parent.expression.name; + break; + case 5 /* Property */: + container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file : isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name : declName.parent.expression; + break; + case 0 /* None */: + return Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration"); + } + if (container) { + declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + } + container = oldContainer; + } + } else if (isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 80 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + } else { + bind(typeAlias.fullName); + } + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + function bindJSDocImports() { + if (jsDocImports === void 0) { + return; + } + const saveContainer = container; + const saveLastContainer = lastContainer; + const saveBlockScopeContainer = blockScopeContainer; + const saveParent = parent; + const saveCurrentFlow = currentFlow; + for (const jsDocImportTag of jsDocImports) { + const host = getJSDocHost(jsDocImportTag); + const enclosingContainer = host ? getEnclosingContainer(host) : void 0; + const enclosingBlockScopeContainer = host ? getEnclosingBlockScopeContainer(host) : void 0; + container = enclosingContainer || file; + blockScopeContainer = enclosingBlockScopeContainer || file; + currentFlow = createFlowNode( + 2 /* Start */, + /*node*/ + void 0, + /*antecedent*/ + void 0 + ); + parent = jsDocImportTag; + bind(jsDocImportTag.importClause); + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + function checkContextualIdentifier(node) { + if (!file.parseDiagnostics.length && !(node.flags & 33554432 /* Ambient */) && !(node.flags & 16777216 /* JSDoc */) && !isIdentifierName(node)) { + const originalKeywordKind = identifierToKeywordKind(node); + if (originalKeywordKind === void 0) { + return; + } + if (inStrictMode && originalKeywordKind >= 119 /* FirstFutureReservedWord */ && originalKeywordKind <= 127 /* LastFutureReservedWord */) { + file.bindDiagnostics.push(createDiagnosticForNode2(node, getStrictModeIdentifierMessage(node), declarationNameToString(node))); + } else if (originalKeywordKind === 135 /* AwaitKeyword */) { + if (isExternalModule(file) && isInTopLevelContext(node)) { + file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, declarationNameToString(node))); + } else if (node.flags & 65536 /* AwaitContext */) { + file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); + } + } else if (originalKeywordKind === 127 /* YieldKeyword */ && node.flags & 16384 /* YieldContext */) { + file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + if (getContainingClass(node)) { + return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkPrivateIdentifier(node) { + if (node.escapedText === "#constructor") { + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.constructor_is_a_reserved_word, declarationNameToString(node))); + } + } + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && isLeftHandSideExpression(node.left) && isAssignmentOperator(node.operatorToken.kind)) { + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + if (inStrictMode && node.expression.kind === 80 /* Identifier */) { + const span = getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 80 /* Identifier */) { + const identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + const span = getErrorSpanForNode(file, name); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), idText(identifier))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + if (getContainingClass(node)) { + return Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode; + } + if (file.externalModuleIndicator) { + return Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode && !(node.flags & 33554432 /* Ambient */)) { + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + if (getContainingClass(node)) { + return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_automatically_in_strict_mode; + } + return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + if (blockScopeContainer.kind !== 307 /* SourceFile */ && blockScopeContainer.kind !== 267 /* ModuleDeclaration */ && !isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) { + const errorSpan = getErrorSpanForNode(file, node); + file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModePostfixUnaryExpression(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + if (inStrictMode) { + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + if (inStrictMode) { + errorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function checkStrictModeLabeledStatement(node) { + if (inStrictMode && getEmitScriptTarget(options) >= 2 /* ES2015 */) { + if (isDeclarationStatement(node.statement) || isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, Diagnostics.A_label_is_not_allowed_here); + } + } + } + function errorOnFirstToken(node, message, ...args) { + const span = getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, ...args)); + } + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + const diag2 = createFileDiagnostic(file, range.pos, range.end - range.pos, message); + if (isError) { + file.bindDiagnostics.push(diag2); + } else { + file.bindSuggestionDiagnostics = append(file.bindSuggestionDiagnostics, { ...diag2, category: 2 /* Suggestion */ }); + } + } + function bind(node) { + if (!node) { + return; + } + setParent(node, parent); + if (tracing) node.tracingPath = file.path; + const saveInStrictMode = inStrictMode; + bindWorker(node); + if (node.kind > 165 /* LastToken */) { + const saveParent = parent; + parent = node; + const containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } else { + const saveParent = parent; + if (node.kind === 1 /* EndOfFileToken */) parent = node; + bindJSDoc(node); + parent = saveParent; + } + inStrictMode = saveInStrictMode; + } + function bindJSDoc(node) { + if (hasJSDocNodes(node)) { + if (isInJSFile(node)) { + for (const j of node.jsDoc) { + bind(j); + } + } else { + for (const j of node.jsDoc) { + setParent(j, node); + setParentRecursive( + j, + /*incremental*/ + false + ); + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (const statement of statements) { + if (!isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + function isUseStrictPrologueDirective(node) { + const nodeText = getSourceTextOfNodeFromSourceFile(file, node.expression); + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 80 /* Identifier */: + if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */) { + let parentNode = node.parent; + while (parentNode && !isJSDocTypeAlias(parentNode)) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + break; + } + // falls through + case 110 /* ThisKeyword */: + if (currentFlow && (isExpression(node) || parent.kind === 304 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkContextualIdentifier(node); + case 166 /* QualifiedName */: + if (currentFlow && isPartOfTypeQuery(node)) { + node.flowNode = currentFlow; + } + break; + case 236 /* MetaProperty */: + case 108 /* SuperKeyword */: + node.flowNode = currentFlow; + break; + case 81 /* PrivateIdentifier */: + return checkPrivateIdentifier(node); + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + const expr = node; + if (currentFlow && isNarrowableReference(expr)) { + expr.flowNode = currentFlow; + } + if (isSpecialPropertyDeclaration(expr)) { + bindSpecialPropertyDeclaration(expr); + } + if (isInJSFile(expr) && file.commonJsModuleIndicator && isModuleExportsAccessExpression(expr) && !lookupSymbolForName(blockScopeContainer, "module")) { + declareSymbol( + file.locals, + /*parent*/ + void 0, + expr.expression, + 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, + 111550 /* FunctionScopedVariableExcludes */ + ); + } + break; + case 226 /* BinaryExpression */: + const specialKind = getAssignmentDeclarationKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + const expression = node.left.expression; + if (isInJSFile(node) && isIdentifier(expression)) { + const symbol = lookupSymbolForName(blockScopeContainer, expression.escapedText); + if (isThisInitializedDeclaration(symbol == null ? void 0 : symbol.valueDeclaration)) { + bindThisPropertyAssignment(node); + break; + } + } + bindSpecialPropertyAssignment(node); + break; + case 0 /* None */: + break; + default: + Debug.fail("Unknown binary expression special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 299 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 220 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 225 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 224 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 254 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 256 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); + case 197 /* ThisType */: + seenThisKeyword = true; + return; + case 182 /* TypePredicate */: + break; + // Binding the children will handle everything + case 168 /* TypeParameter */: + return bindTypeParameter(node); + case 169 /* Parameter */: + return bindParameter(node); + case 260 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 208 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + return bindPropertyWorker(node); + case 303 /* PropertyAssignment */: + case 304 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 306 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 181 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */); + case 262 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 176 /* Constructor */: + return declareSymbolAndAddToSymbolTable( + node, + 16384 /* Constructor */, + /*symbolExcludes:*/ + 0 /* None */ + ); + case 177 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */); + case 178 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */); + case 184 /* FunctionType */: + case 317 /* JSDocFunctionType */: + case 323 /* JSDocSignature */: + case 185 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 187 /* TypeLiteral */: + case 322 /* JSDocTypeLiteral */: + case 200 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 332 /* JSDocClassTag */: + return bindJSDocClassTag(node); + case 210 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + return bindFunctionExpression(node); + case 213 /* CallExpression */: + const assignmentKind = getAssignmentDeclarationKind(node); + switch (assignmentKind) { + case 7 /* ObjectDefinePropertyValue */: + return bindObjectDefinePropertyAssignment(node); + case 8 /* ObjectDefinePropertyExports */: + return bindObjectDefinePropertyExport(node); + case 9 /* ObjectDefinePrototypeProperty */: + return bindObjectDefinePrototypeProperty(node); + case 0 /* None */: + break; + // Nothing to do + default: + return Debug.fail("Unknown call expression assignment declaration kind"); + } + if (isInJSFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 231 /* ClassExpression */: + case 263 /* ClassDeclaration */: + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 264 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */); + case 265 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); + case 266 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 267 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 292 /* JsxAttributes */: + return bindJsxAttributes(node); + case 291 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 271 /* ImportEqualsDeclaration */: + case 274 /* NamespaceImport */: + case 276 /* ImportSpecifier */: + case 281 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 270 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 273 /* ImportClause */: + return bindImportClause(node); + case 278 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 277 /* ExportAssignment */: + return bindExportAssignment(node); + case 307 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 241 /* Block */: + if (!isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) { + return; + } + // falls through + case 268 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 341 /* JSDocParameterTag */: + if (node.parent.kind === 323 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 322 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 348 /* JSDocPropertyTag */: + const propTag = node; + const flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 316 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 346 /* JSDocTypedefTag */: + case 338 /* JSDocCallbackTag */: + case 340 /* JSDocEnumTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); + case 339 /* JSDocOverloadTag */: + return bind(node.typeExpression); + case 351 /* JSDocImportTag */: + return (jsDocImports || (jsDocImports = [])).push(node); + } + } + function bindPropertyWorker(node) { + const isAutoAccessor = isAutoAccessorPropertyDeclaration(node); + const includes = isAutoAccessor ? 98304 /* Accessor */ : 4 /* Property */; + const excludes = isAutoAccessor ? 13247 /* AccessorExcludes */ : 0 /* PropertyExcludes */; + return bindPropertyOrMethodOrAccessor(node, includes | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), excludes); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } else if (isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + const originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, -1 /* All */); + file.symbol = originalSymbol; + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, `"${removeFileExtension(file.fileName)}"`); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); + } else { + const flags = exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */; + const symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, -1 /* All */); + if (node.isExportEquals) { + setValueDeclaration(symbol, node); + } + } + } + function bindNamespaceExportDeclaration(node) { + if (some(node.modifiers)) { + file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Modifiers_cannot_appear_here)); + } + const diag2 = !isSourceFile(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_at_top_level : !isExternalModule(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_in_module_files : !node.parent.isDeclarationFile ? Diagnostics.Global_module_exports_may_only_appear_in_declaration_files : void 0; + if (diag2) { + file.bindDiagnostics.push(createDiagnosticForNode2(node, diag2)); + } else { + file.symbol.globalExports = file.symbol.globalExports || createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } else if (!node.exportClause) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } else if (isNamespaceExport(node.exportClause)) { + setParent(node.exportClause, node); + declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator && file.externalModuleIndicator !== true) { + return false; + } + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } + } + return true; + } + function bindObjectDefinePropertyExport(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + const symbol = forEachIdentifierInEntityName( + node.arguments[0], + /*parent*/ + void 0, + (id, symbol2) => { + if (symbol2) { + addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol2; + } + ); + if (symbol) { + const flags = 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); + } + } + function bindExportsPropertyAssignment(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + const symbol = forEachIdentifierInEntityName( + node.left.expression, + /*parent*/ + void 0, + (id, symbol2) => { + if (symbol2) { + addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */); + } + return symbol2; + } + ); + if (symbol) { + const isAlias = isAliasableExpression(node.right) && (isExportsIdentifier(node.left.expression) || isModuleExportsAccessExpression(node.left.expression)); + const flags = isAlias ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */; + setParent(node.left, node); + declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */); + } + } + function bindModuleExportsAssignment(node) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + const assignedExpression = getRightMostAssignedExpression(node.right); + if (isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { + return; + } + if (isObjectLiteralExpression(assignedExpression) && every(assignedExpression.properties, isShorthandPropertyAssignment)) { + forEach(assignedExpression.properties, bindExportAssignedObjectMemberAlias); + return; + } + const flags = exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; + const symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); + } + function bindExportAssignedObjectMemberAlias(node) { + declareSymbol(file.symbol.exports, file.symbol, node, 2097152 /* Alias */ | 67108864 /* Assignment */, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + Debug.assert(isInJSFile(node)); + const hasPrivateIdentifier = isBinaryExpression(node) && isPropertyAccessExpression(node.left) && isPrivateIdentifier(node.left.name) || isPropertyAccessExpression(node) && isPrivateIdentifier(node.name); + if (hasPrivateIdentifier) { + return; + } + const thisContainer = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + switch (thisContainer.kind) { + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + let constructorSymbol = thisContainer.symbol; + if (isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 64 /* EqualsToken */) { + const l = thisContainer.parent.left; + if (isBindableStaticAccessExpression(l) && isPrototypeAccess(l.expression)) { + constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol && constructorSymbol.valueDeclaration) { + constructorSymbol.members = constructorSymbol.members || createSymbolTable(); + if (hasDynamicName(node)) { + bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol, constructorSymbol.members); + } else { + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } + addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */); + } + break; + case 176 /* Constructor */: + case 172 /* PropertyDeclaration */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 175 /* ClassStaticBlockDeclaration */: + const containingClass = thisContainer.parent; + const symbolTable = isStatic(thisContainer) ? containingClass.symbol.exports : containingClass.symbol.members; + if (hasDynamicName(node)) { + bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol, symbolTable); + } else { + declareSymbol( + symbolTable, + containingClass.symbol, + node, + 4 /* Property */ | 67108864 /* Assignment */, + 0 /* None */, + /*isReplaceableByMethod*/ + true + ); + } + break; + case 307 /* SourceFile */: + if (hasDynamicName(node)) { + break; + } else if (thisContainer.commonJsModuleIndicator) { + declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + } else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */); + } + break; + // Namespaces are not allowed in javascript files, so do nothing here + case 267 /* ModuleDeclaration */: + break; + default: + Debug.failBadSyntaxKind(thisContainer); + } + } + function bindDynamicallyNamedThisPropertyAssignment(node, symbol, symbolTable) { + declareSymbol( + symbolTable, + symbol, + node, + 4 /* Property */, + 0 /* None */, + /*isReplaceableByMethod*/ + true, + /*isComputedName*/ + true + ); + addLateBoundAssignmentDeclarationToSymbol(node, symbol); + } + function addLateBoundAssignmentDeclarationToSymbol(node, symbol) { + if (symbol) { + (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = /* @__PURE__ */ new Map())).set(getNodeId(node), node); + } + } + function bindSpecialPropertyDeclaration(node) { + if (node.expression.kind === 110 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } else if (isBindableStaticAccessExpression(node) && node.parent.parent.kind === 307 /* SourceFile */) { + if (isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } else { + bindStaticPropertyAssignment(node); + } + } + } + function bindPrototypeAssignment(node) { + setParent(node.left, node); + setParent(node.right, node); + bindPropertyAssignment( + node.left.expression, + node.left, + /*isPrototypeProperty*/ + false, + /*containerIsClass*/ + true + ); + } + function bindObjectDefinePrototypeProperty(node) { + const namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol && namespaceSymbol.valueDeclaration) { + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } + bindPotentiallyNewExpandoMemberToNamespace( + node, + namespaceSymbol, + /*isPrototypeProperty*/ + true + ); + } + function bindPrototypePropertyAssignment(lhs, parent2) { + const classPrototype = lhs.expression; + const constructorFunction = classPrototype.expression; + setParent(constructorFunction, classPrototype); + setParent(classPrototype, lhs); + setParent(lhs, parent2); + bindPropertyAssignment( + constructorFunction, + lhs, + /*isPrototypeProperty*/ + true, + /*containerIsClass*/ + true + ); + } + function bindObjectDefinePropertyAssignment(node) { + let namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + const isToplevel = node.parent.parent.kind === 307 /* SourceFile */; + namespaceSymbol = bindPotentiallyMissingNamespaces( + namespaceSymbol, + node.arguments[0], + isToplevel, + /*isPrototypeProperty*/ + false, + /*containerIsClass*/ + false + ); + bindPotentiallyNewExpandoMemberToNamespace( + node, + namespaceSymbol, + /*isPrototypeProperty*/ + false + ); + } + function bindSpecialPropertyAssignment(node) { + var _a; + const parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer) || lookupSymbolForPropertyAccess(node.left.expression, container); + if (!isInJSFile(node) && !isFunctionSymbol(parentSymbol)) { + return; + } + const rootExpr = getLeftmostAccessExpression(node.left); + if (isIdentifier(rootExpr) && ((_a = lookupSymbolForName(container, rootExpr.escapedText)) == null ? void 0 : _a.flags) & 2097152 /* Alias */) { + return; + } + setParent(node.left, node); + setParent(node.right, node); + if (isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) { + bindExportsPropertyAssignment(node); + } else if (hasDynamicName(node)) { + bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */); + const sym = bindPotentiallyMissingNamespaces( + parentSymbol, + node.left.expression, + isTopLevelNamespaceAssignment(node.left), + /*isPrototypeProperty*/ + false, + /*containerIsClass*/ + false + ); + addLateBoundAssignmentDeclarationToSymbol(node, sym); + } else { + bindStaticPropertyAssignment(cast(node.left, isBindableStaticNameExpression)); + } + } + function bindStaticPropertyAssignment(node) { + Debug.assert(!isIdentifier(node)); + setParent(node.expression, node); + bindPropertyAssignment( + node.expression, + node, + /*isPrototypeProperty*/ + false, + /*containerIsClass*/ + false + ); + } + function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) { + if ((namespaceSymbol == null ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) { + return namespaceSymbol; + } + if (isToplevel && !isPrototypeProperty) { + const flags = 1536 /* Module */ | 67108864 /* Assignment */; + const excludeFlags = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, (id, symbol, parent2) => { + if (symbol) { + addDeclarationToSymbol(symbol, id, flags); + return symbol; + } else { + const table = parent2 ? parent2.exports : file.jsGlobalAugmentations || (file.jsGlobalAugmentations = createSymbolTable()); + return declareSymbol(table, parent2, id, flags, excludeFlags); + } + }); + } + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } + return namespaceSymbol; + } + function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { + return; + } + const symbolTable = isPrototypeProperty ? namespaceSymbol.members || (namespaceSymbol.members = createSymbolTable()) : namespaceSymbol.exports || (namespaceSymbol.exports = createSymbolTable()); + let includes = 0 /* None */; + let excludes = 0 /* None */; + if (isFunctionLikeDeclaration(getAssignedExpandoInitializer(declaration))) { + includes = 8192 /* Method */; + excludes = 103359 /* MethodExcludes */; + } else if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) { + if (some(declaration.arguments[2].properties, (p) => { + const id = getNameOfDeclaration(p); + return !!id && isIdentifier(id) && idText(id) === "set"; + })) { + includes |= 65536 /* SetAccessor */ | 4 /* Property */; + excludes |= 78783 /* SetAccessorExcludes */; + } + if (some(declaration.arguments[2].properties, (p) => { + const id = getNameOfDeclaration(p); + return !!id && isIdentifier(id) && idText(id) === "get"; + })) { + includes |= 32768 /* GetAccessor */ | 4 /* Property */; + excludes |= 46015 /* GetAccessorExcludes */; + } + } + if (includes === 0 /* None */) { + includes = 4 /* Property */; + excludes = 0 /* PropertyExcludes */; + } + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); + } + function isTopLevelNamespaceAssignment(propertyAccess) { + return isBinaryExpression(propertyAccess.parent) ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 307 /* SourceFile */ : propertyAccess.parent.parent.kind === 307 /* SourceFile */; + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { + let namespaceSymbol = lookupSymbolForPropertyAccess(name, blockScopeContainer) || lookupSymbolForPropertyAccess(name, container); + const isToplevel = isTopLevelNamespaceAssignment(propertyAccess); + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); + } + function isExpandoSymbol(symbol) { + if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { + return true; + } + const node = symbol.valueDeclaration; + if (node && isCallExpression(node)) { + return !!getAssignedExpandoInitializer(node); + } + let init = !node ? void 0 : isVariableDeclaration(node) ? node.initializer : isBinaryExpression(node) ? node.right : isPropertyAccessExpression(node) && isBinaryExpression(node.parent) ? node.parent.right : void 0; + init = init && getRightMostAssignedExpression(init); + if (init) { + const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node) ? node.name : isBinaryExpression(node) ? node.left : node); + return !!getExpandoInitializer(isBinaryExpression(init) && (init.operatorToken.kind === 57 /* BarBarToken */ || init.operatorToken.kind === 61 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment); + } + return false; + } + function getParentOfBinaryExpression(expr) { + while (isBinaryExpression(expr.parent)) { + expr = expr.parent; + } + return expr.parent; + } + function lookupSymbolForPropertyAccess(node, lookupContainer = container) { + if (isIdentifier(node)) { + return lookupSymbolForName(lookupContainer, node.escapedText); + } else { + const symbol = lookupSymbolForPropertyAccess(node.expression); + return symbol && symbol.exports && symbol.exports.get(getElementOrPropertyAccessName(node)); + } + } + function forEachIdentifierInEntityName(e, parent2, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } else if (isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e), parent2); + } else { + const s = forEachIdentifierInEntityName(e.expression, parent2, action); + const name = getNameOrArgument(e); + if (isPrivateIdentifier(name)) { + Debug.fail("unexpected PrivateIdentifier"); + } + return action(name, s && s.exports && s.exports.get(getElementOrPropertyAccessName(e)), s); + } + } + function bindCallExpression(node) { + if (!file.commonJsModuleIndicator && isRequireCall( + node, + /*requireStringLiteralLikeArgument*/ + false + )) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 263 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */); + } else { + const bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + if (node.name) { + classifiableNames.add(node.name.escapedText); + } + } + const { symbol } = node; + const prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + const symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + setParent(node.name, node); + } + file.bindDiagnostics.push(createDiagnosticForNode2(symbolExport.declarations[0], Diagnostics.Duplicate_identifier_0, symbolName(prototypeSymbol))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return isEnumConst(node) ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!isBindingPattern(node.name)) { + const possibleVariableDecl = node.kind === 260 /* VariableDeclaration */ ? node : node.parent.parent; + if (isInJSFile(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && !getJSDocTypeTag(node) && !(getCombinedModifierFlags(node) & 32 /* Export */)) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } else if (isBlockOrCatchScoped(node)) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */); + } else if (isPartOfParameterDeclaration(node)) { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */); + } else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */); + } + } + } + function bindParameter(node) { + if (node.kind === 341 /* JSDocParameterTag */ && container.kind !== 323 /* JSDocSignature */) { + return; + } + if (inStrictMode && !(node.flags & 33554432 /* Ambient */)) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); + } else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */); + } + if (isParameterPropertyDeclaration(node, node.parent)) { + const classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */)) { + if (isAsyncFunction(node)) { + emitFlags |= 4096 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */); + } else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */)) { + if (isAsyncFunction(node)) { + emitFlags |= 4096 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + const bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */) && isAsyncFunction(node)) { + emitFlags |= 4096 /* HasAsyncFunctions */; + } + if (currentFlow && isObjectLiteralOrClassExpressionMethodOrAccessor(node)) { + node.flowNode = currentFlow; + } + return hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function getInferTypeContainer(node) { + const extendsType = findAncestor(node, (n) => n.parent && isConditionalTypeNode(n.parent) && n.parent.extendsType === n); + return extendsType && extendsType.parent; + } + function bindTypeParameter(node) { + if (isJSDocTemplateTag(node.parent)) { + const container2 = getEffectiveContainerForJSDocTemplateTag(node.parent); + if (container2) { + Debug.assertNode(container2, canHaveLocals); + container2.locals ?? (container2.locals = createSymbolTable()); + declareSymbol( + container2.locals, + /*parent*/ + void 0, + node, + 262144 /* TypeParameter */, + 526824 /* TypeParameterExcludes */ + ); + } else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); + } + } else if (node.parent.kind === 195 /* InferType */) { + const container2 = getInferTypeContainer(node.parent); + if (container2) { + Debug.assertNode(container2, canHaveLocals); + container2.locals ?? (container2.locals = createSymbolTable()); + declareSymbol( + container2.locals, + /*parent*/ + void 0, + node, + 262144 /* TypeParameter */, + 526824 /* TypeParameterExcludes */ + ); + } else { + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); + } + } else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); + } + } + function shouldReportErrorOnModuleDeclaration(node) { + const instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || instanceState === 2 /* ConstEnumOnly */ && shouldPreserveConstEnums(options); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + const reportError = ( + // report error on all statements except empty ones + isStatementButNotDeclaration(node) && node.kind !== 242 /* EmptyStatement */ || // report error on class declarations + node.kind === 263 /* ClassDeclaration */ || // report errors on enums with preserved emit + isEnumDeclarationWithPreservedEmit(node, options) || // report error on instantiated modules + node.kind === 267 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node) + ); + if (reportError) { + currentFlow = reportedUnreachableFlow; + if (!options.allowUnreachableCode) { + const isError = unreachableCodeIsError(options) && !(node.flags & 33554432 /* Ambient */) && (!isVariableStatement(node) || !!(getCombinedNodeFlags(node.declarationList) & 7 /* BlockScoped */) || node.declarationList.declarations.some((d) => !!d.initializer)); + eachUnreachableRange(node, options, (start, end) => errorOrSuggestionOnRange(isError, start, end, Diagnostics.Unreachable_code_detected)); + } + } + } + return true; + } +} +function isEnumDeclarationWithPreservedEmit(node, options) { + return node.kind === 266 /* EnumDeclaration */ && (!isEnumConst(node) || shouldPreserveConstEnums(options)); +} +function eachUnreachableRange(node, options, cb) { + if (isStatement(node) && isExecutableStatement(node) && isBlock(node.parent)) { + const { statements } = node.parent; + const slice = sliceAfter(statements, node); + getRangesWhere(slice, isExecutableStatement, (start, afterEnd) => cb(slice[start], slice[afterEnd - 1])); + } else { + cb(node, node); + } + function isExecutableStatement(s) { + return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && // `var x;` may declare a variable used above + !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & 7 /* BlockScoped */) && s.declarationList.declarations.some((d) => !d.initializer)); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + return true; + case 267 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 266 /* EnumDeclaration */: + return !isEnumDeclarationWithPreservedEmit(s, options); + default: + return false; + } + } +} +function isExportsOrModuleExportsOrAlias(sourceFile, node) { + let i = 0; + const q = createQueue(); + q.enqueue(node); + while (!q.isEmpty() && i < 100) { + i++; + node = q.dequeue(); + if (isExportsIdentifier(node) || isModuleExportsAccessExpression(node)) { + return true; + } else if (isIdentifier(node)) { + const symbol = lookupSymbolForName(sourceFile, node.escapedText); + if (!!symbol && !!symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) { + const init = symbol.valueDeclaration.initializer; + q.enqueue(init); + if (isAssignmentExpression( + init, + /*excludeCompoundAssignment*/ + true + )) { + q.enqueue(init.left); + q.enqueue(init.right); + } + } + } + } + return false; +} +function getContainerFlags(node) { + switch (node.kind) { + case 231 /* ClassExpression */: + case 263 /* ClassDeclaration */: + case 266 /* EnumDeclaration */: + case 210 /* ObjectLiteralExpression */: + case 187 /* TypeLiteral */: + case 322 /* JSDocTypeLiteral */: + case 292 /* JsxAttributes */: + return 1 /* IsContainer */; + case 264 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 267 /* ModuleDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 200 /* MappedType */: + case 181 /* IndexSignature */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 307 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + if (isObjectLiteralOrClassExpressionMethodOrAccessor(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */; + } + // falls through + case 176 /* Constructor */: + case 262 /* FunctionDeclaration */: + case 173 /* MethodSignature */: + case 179 /* CallSignature */: + case 323 /* JSDocSignature */: + case 317 /* JSDocFunctionType */: + case 184 /* FunctionType */: + case 180 /* ConstructSignature */: + case 185 /* ConstructorType */: + case 175 /* ClassStaticBlockDeclaration */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 268 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 172 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 299 /* CatchClause */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 269 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */ | 32 /* HasLocals */; + case 241 /* Block */: + return isFunctionLike(node.parent) || isClassStaticBlockDeclaration(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */ | 32 /* HasLocals */; + } + return 0 /* None */; +} +function lookupSymbolForName(container, name) { + var _a, _b, _c, _d; + const local = (_b = (_a = tryCast(container, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(name); + if (local) { + return local.exportSymbol ?? local; + } + if (isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } + if (canHaveSymbol(container)) { + return (_d = (_c = container.symbol) == null ? void 0 : _c.exports) == null ? void 0 : _d.get(name); + } +} + +// src/compiler/symbolWalker.ts +function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getConstraintOfTypeParameter, getFirstIdentifier2, getTypeArguments) { + return getSymbolWalker; + function getSymbolWalker(accept = () => true) { + const visitedTypes = []; + const visitedSymbols = []; + return { + walkType: (type) => { + try { + visitType(type); + return { visitedTypes: getOwnValues(visitedTypes), visitedSymbols: getOwnValues(visitedSymbols) }; + } finally { + clear(visitedTypes); + clear(visitedSymbols); + } + }, + walkSymbol: (symbol) => { + try { + visitSymbol(symbol); + return { visitedTypes: getOwnValues(visitedTypes), visitedSymbols: getOwnValues(visitedSymbols) }; + } finally { + clear(visitedTypes); + clear(visitedSymbols); + } + } + }; + function visitType(type) { + if (!type) { + return; + } + if (visitedTypes[type.id]) { + return; + } + visitedTypes[type.id] = type; + const shouldBail = visitSymbol(type.symbol); + if (shouldBail) return; + if (type.flags & 524288 /* Object */) { + const objectType = type; + const objectFlags = objectType.objectFlags; + if (objectFlags & 4 /* Reference */) { + visitTypeReference(type); + } + if (objectFlags & 32 /* Mapped */) { + visitMappedType(type); + } + if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { + visitInterfaceType(type); + } + if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { + visitObjectType(objectType); + } + } + if (type.flags & 262144 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 4194304 /* Index */) { + visitIndexType(type); + } + if (type.flags & 8388608 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeReference(type) { + visitType(type.target); + forEach(getTypeArguments(type), visitType); + } + function visitTypeParameter(type) { + visitType(getConstraintOfTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + forEach(type.types, visitType); + } + function visitIndexType(type) { + visitType(type.type); + } + function visitIndexedAccessType(type) { + visitType(type.objectType); + visitType(type.indexType); + visitType(type.constraint); + } + function visitMappedType(type) { + visitType(type.typeParameter); + visitType(type.constraintType); + visitType(type.templateType); + visitType(type.modifiersType); + } + function visitSignature(signature) { + const typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); + } + forEach(signature.typeParameters, visitType); + for (const parameter of signature.parameters) { + visitSymbol(parameter); + } + visitType(getRestTypeOfSignature(signature)); + visitType(getReturnTypeOfSignature(signature)); + } + function visitInterfaceType(interfaceT) { + visitObjectType(interfaceT); + forEach(interfaceT.typeParameters, visitType); + forEach(getBaseTypes(interfaceT), visitType); + visitType(interfaceT.thisType); + } + function visitObjectType(type) { + const resolved = resolveStructuredTypeMembers(type); + for (const info of resolved.indexInfos) { + visitType(info.keyType); + visitType(info.type); + } + for (const signature of resolved.callSignatures) { + visitSignature(signature); + } + for (const signature of resolved.constructSignatures) { + visitSignature(signature); + } + for (const p of resolved.properties) { + visitSymbol(p); + } + } + function visitSymbol(symbol) { + if (!symbol) { + return false; + } + const symbolId = getSymbolId(symbol); + if (visitedSymbols[symbolId]) { + return false; + } + visitedSymbols[symbolId] = symbol; + if (!accept(symbol)) { + return true; + } + const t = getTypeOfSymbol(symbol); + visitType(t); + if (symbol.exports) { + symbol.exports.forEach(visitSymbol); + } + forEach(symbol.declarations, (d) => { + if (d.type && d.type.kind === 186 /* TypeQuery */) { + const query = d.type; + const entity = getResolvedSymbol(getFirstIdentifier2(query.exprName)); + visitSymbol(entity); + } + }); + return false; + } + } +} + +// src/compiler/moduleSpecifiers.ts +var stringToRegex = memoizeOne((pattern) => { + try { + let slash = pattern.indexOf("/"); + if (slash !== 0) { + return new RegExp(pattern); + } + const lastSlash = pattern.lastIndexOf("/"); + if (slash === lastSlash) { + return new RegExp(pattern); + } + while ((slash = pattern.indexOf("/", slash + 1)) !== lastSlash) { + if (pattern[slash - 1] !== "\\") { + return new RegExp(pattern); + } + } + const flags = pattern.substring(lastSlash + 1).replace(/[^iu]/g, ""); + pattern = pattern.substring(1, lastSlash); + return new RegExp(pattern, flags); + } catch { + return void 0; + } +}); +function getModuleSpecifierPreferences({ importModuleSpecifierPreference, importModuleSpecifierEnding, autoImportSpecifierExcludeRegexes }, host, compilerOptions, importingSourceFile, oldImportSpecifier) { + const filePreferredEnding = getPreferredEnding(); + return { + excludeRegexes: autoImportSpecifierExcludeRegexes, + relativePreference: oldImportSpecifier !== void 0 ? isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */ : importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : importModuleSpecifierPreference === "project-relative" ? 3 /* ExternalNonRelative */ : 2 /* Shortest */, + getAllowedEndingsInPreferredOrder: (syntaxImpliedNodeFormat) => { + const impliedNodeFormat = getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions); + const preferredEnding = syntaxImpliedNodeFormat !== impliedNodeFormat ? getPreferredEnding(syntaxImpliedNodeFormat) : filePreferredEnding; + const moduleResolution = getEmitModuleResolutionKind(compilerOptions); + if ((syntaxImpliedNodeFormat ?? impliedNodeFormat) === 99 /* ESNext */ && 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */) { + if (shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName)) { + return [3 /* TsExtension */, 2 /* JsExtension */]; + } + return [2 /* JsExtension */]; + } + if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */) { + return preferredEnding === 2 /* JsExtension */ ? [2 /* JsExtension */, 1 /* Index */] : [1 /* Index */, 2 /* JsExtension */]; + } + const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName); + switch (preferredEnding) { + case 2 /* JsExtension */: + return allowImportingTsExtension ? [2 /* JsExtension */, 3 /* TsExtension */, 0 /* Minimal */, 1 /* Index */] : [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */]; + case 3 /* TsExtension */: + return [3 /* TsExtension */, 0 /* Minimal */, 2 /* JsExtension */, 1 /* Index */]; + case 1 /* Index */: + return allowImportingTsExtension ? [1 /* Index */, 0 /* Minimal */, 3 /* TsExtension */, 2 /* JsExtension */] : [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */]; + case 0 /* Minimal */: + return allowImportingTsExtension ? [0 /* Minimal */, 1 /* Index */, 3 /* TsExtension */, 2 /* JsExtension */] : [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */]; + default: + Debug.assertNever(preferredEnding); + } + } + }; + function getPreferredEnding(resolutionMode) { + if (oldImportSpecifier !== void 0) { + if (hasJSFileExtension(oldImportSpecifier)) return 2 /* JsExtension */; + if (endsWith(oldImportSpecifier, "/index")) return 1 /* Index */; + } + return getModuleSpecifierEndingPreference( + importModuleSpecifierEnding, + resolutionMode ?? getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions), + compilerOptions, + isFullSourceFile(importingSourceFile) ? importingSourceFile : void 0 + ); + } +} +function tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences, options = {}) { + var _a; + const moduleSourceFile = getSourceFileOfModule(moduleSymbol); + if (!moduleSourceFile) { + return emptyArray; + } + const cache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host); + const cached = cache == null ? void 0 : cache.get(importingSourceFile.path, moduleSourceFile.path, userPreferences, options); + return [cached == null ? void 0 : cached.kind, cached == null ? void 0 : cached.moduleSpecifiers, moduleSourceFile, cached == null ? void 0 : cached.modulePaths, cache]; +} +function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}) { + return getModuleSpecifiersWithCacheInfo( + moduleSymbol, + checker, + compilerOptions, + importingSourceFile, + host, + userPreferences, + options, + /*forAutoImport*/ + false + ).moduleSpecifiers; +} +function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { + let computedWithoutCache = false; + const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker); + if (ambient) { + return { + kind: "ambient", + moduleSpecifiers: !(forAutoImport && isExcludedByRegex(ambient, userPreferences.autoImportSpecifierExcludeRegexes)) ? [ambient] : emptyArray, + computedWithoutCache + }; + } + let [kind, specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker( + moduleSymbol, + importingSourceFile, + host, + userPreferences, + options + ); + if (specifiers) return { kind, moduleSpecifiers: specifiers, computedWithoutCache }; + if (!moduleSourceFile) return { kind: void 0, moduleSpecifiers: emptyArray, computedWithoutCache }; + computedWithoutCache = true; + modulePaths || (modulePaths = getAllModulePathsWorker(getInfo(importingSourceFile.fileName, host), moduleSourceFile.originalFileName, host, compilerOptions, options)); + const result = computeModuleSpecifiers( + modulePaths, + compilerOptions, + importingSourceFile, + host, + userPreferences, + options, + forAutoImport + ); + cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, result.kind, modulePaths, result.moduleSpecifiers); + return result; +} +function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { + const info = getInfo(importingSourceFile.fileName, host); + const preferences = getModuleSpecifierPreferences(userPreferences, host, compilerOptions, importingSourceFile); + const existingSpecifier = isFullSourceFile(importingSourceFile) && forEach(modulePaths, (modulePath) => forEach( + host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), + (reason) => { + if (reason.kind !== 3 /* Import */ || reason.file !== importingSourceFile.path) return void 0; + const existingMode = host.getModeForResolutionAtIndex(importingSourceFile, reason.index); + const targetMode = options.overrideImportMode ?? host.getDefaultResolutionModeForFile(importingSourceFile); + if (existingMode !== targetMode && existingMode !== void 0 && targetMode !== void 0) { + return void 0; + } + const specifier = getModuleNameStringLiteralAt(importingSourceFile, reason.index).text; + return preferences.relativePreference !== 1 /* NonRelative */ || !pathIsRelative(specifier) ? specifier : void 0; + } + )); + if (existingSpecifier) { + return { kind: void 0, moduleSpecifiers: [existingSpecifier], computedWithoutCache: true }; + } + const importedFileIsInNodeModules = some(modulePaths, (p) => p.isInNodeModules); + let nodeModulesSpecifiers; + let pathsSpecifiers; + let redirectPathsSpecifiers; + let relativeSpecifiers; + for (const modulePath of modulePaths) { + const specifier = modulePath.isInNodeModules ? tryGetModuleNameAsNodeModule( + modulePath, + info, + importingSourceFile, + host, + compilerOptions, + userPreferences, + /*packageNameOnly*/ + void 0, + options.overrideImportMode + ) : void 0; + if (specifier && !(forAutoImport && isExcludedByRegex(specifier, preferences.excludeRegexes))) { + nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier); + if (modulePath.isRedirect) { + return { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true }; + } + } + const local = getLocalModuleSpecifier( + modulePath.path, + info, + compilerOptions, + host, + options.overrideImportMode || importingSourceFile.impliedNodeFormat, + preferences, + /*pathsOnly*/ + modulePath.isRedirect || !!specifier + ); + if (!local || forAutoImport && isExcludedByRegex(local, preferences.excludeRegexes)) { + continue; + } + if (modulePath.isRedirect) { + redirectPathsSpecifiers = append(redirectPathsSpecifiers, local); + } else if (pathIsBareSpecifier(local)) { + if (pathContainsNodeModules(local)) { + relativeSpecifiers = append(relativeSpecifiers, local); + } else { + pathsSpecifiers = append(pathsSpecifiers, local); + } + } else if (forAutoImport || !importedFileIsInNodeModules || modulePath.isInNodeModules) { + relativeSpecifiers = append(relativeSpecifiers, local); + } + } + return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? { kind: "paths", moduleSpecifiers: pathsSpecifiers, computedWithoutCache: true } : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? { kind: "redirect", moduleSpecifiers: redirectPathsSpecifiers, computedWithoutCache: true } : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true } : { kind: "relative", moduleSpecifiers: relativeSpecifiers ?? emptyArray, computedWithoutCache: true }; +} +function isExcludedByRegex(moduleSpecifier, excludeRegexes) { + return some(excludeRegexes, (pattern) => { + var _a; + return !!((_a = stringToRegex(pattern)) == null ? void 0 : _a.test(moduleSpecifier)); + }); +} +function getInfo(importingSourceFileName, host) { + importingSourceFileName = getNormalizedAbsolutePath(importingSourceFileName, host.getCurrentDirectory()); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); + const sourceDirectory = getDirectoryPath(importingSourceFileName); + return { + getCanonicalFileName, + importingSourceFileName, + sourceDirectory, + canonicalSourceDirectory: getCanonicalFileName(sourceDirectory) + }; +} +function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, { getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder, relativePreference, excludeRegexes }, pathsOnly) { + const { baseUrl, paths, rootDirs } = compilerOptions; + if (pathsOnly && !paths) { + return void 0; + } + const { sourceDirectory, canonicalSourceDirectory, getCanonicalFileName } = info; + const allowedEndings = getAllowedEndingsInPrefererredOrder(importMode); + const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, allowedEndings, compilerOptions) || processEnding(ensurePathIsNonModuleName(getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), allowedEndings, compilerOptions); + if (!baseUrl && !paths && !getResolvePackageJsonImports(compilerOptions) || relativePreference === 0 /* Relative */) { + return pathsOnly ? void 0 : relativePath; + } + const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); + const relativeToBaseUrl = getRelativePathIfInSameVolume(moduleFileName, baseDirectory, getCanonicalFileName); + if (!relativeToBaseUrl) { + return pathsOnly ? void 0 : relativePath; + } + const fromPackageJsonImports = pathsOnly ? void 0 : tryGetModuleNameFromPackageJsonImports( + moduleFileName, + sourceDirectory, + compilerOptions, + host, + importMode, + prefersTsExtension(allowedEndings) + ); + const fromPaths = pathsOnly || fromPackageJsonImports === void 0 ? paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, baseDirectory, getCanonicalFileName, host, compilerOptions) : void 0; + if (pathsOnly) { + return fromPaths; + } + const maybeNonRelative = fromPackageJsonImports ?? (fromPaths === void 0 && baseUrl !== void 0 ? processEnding(relativeToBaseUrl, allowedEndings, compilerOptions) : fromPaths); + if (!maybeNonRelative) { + return relativePath; + } + const relativeIsExcluded = isExcludedByRegex(relativePath, excludeRegexes); + const nonRelativeIsExcluded = isExcludedByRegex(maybeNonRelative, excludeRegexes); + if (!relativeIsExcluded && nonRelativeIsExcluded) { + return relativePath; + } + if (relativeIsExcluded && !nonRelativeIsExcluded) { + return maybeNonRelative; + } + if (relativePreference === 1 /* NonRelative */ && !pathIsRelative(maybeNonRelative)) { + return maybeNonRelative; + } + if (relativePreference === 3 /* ExternalNonRelative */ && !pathIsRelative(maybeNonRelative)) { + const projectDirectory = compilerOptions.configFilePath ? toPath(getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : info.getCanonicalFileName(host.getCurrentDirectory()); + const modulePath = toPath(moduleFileName, projectDirectory, getCanonicalFileName); + const sourceIsInternal = startsWith(canonicalSourceDirectory, projectDirectory); + const targetIsInternal = startsWith(modulePath, projectDirectory); + if (sourceIsInternal && !targetIsInternal || !sourceIsInternal && targetIsInternal) { + return maybeNonRelative; + } + const nearestTargetPackageJson = getNearestAncestorDirectoryWithPackageJson(host, getDirectoryPath(modulePath)); + const nearestSourcePackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory); + const ignoreCase = !hostUsesCaseSensitiveFileNames(host); + if (!packageJsonPathsAreEqual(nearestTargetPackageJson, nearestSourcePackageJson, ignoreCase)) { + return maybeNonRelative; + } + return relativePath; + } + return isPathRelativeToParent(maybeNonRelative) || countPathComponents(relativePath) < countPathComponents(maybeNonRelative) ? relativePath : maybeNonRelative; +} +function packageJsonPathsAreEqual(a, b, ignoreCase) { + if (a === b) return true; + if (a === void 0 || b === void 0) return false; + return comparePaths(a, b, ignoreCase) === 0 /* EqualTo */; +} +function countPathComponents(path) { + let count = 0; + for (let i = startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) count++; + } + return count; +} +function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { + return compareBooleans(b.isRedirect, a.isRedirect) || compareNumberOfDirectorySeparators(a.path, b.path); +} +function getNearestAncestorDirectoryWithPackageJson(host, fileName) { + if (host.getNearestAncestorDirectoryWithPackageJson) { + return host.getNearestAncestorDirectoryWithPackageJson(fileName); + } + return forEachAncestorDirectoryStoppingAtGlobalCache( + host, + fileName, + (directory) => host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0 + ); +} +function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) { + var _a; + const getCanonicalFileName = hostGetCanonicalFileName(host); + const cwd = host.getCurrentDirectory(); + const referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : void 0; + const importedPath = toPath(importedFileName, cwd, getCanonicalFileName); + const redirects = host.redirectTargetsMap.get(importedPath) || emptyArray; + const importedFileNames = [...referenceRedirect ? [referenceRedirect] : emptyArray, importedFileName, ...redirects]; + const targets = importedFileNames.map((f) => getNormalizedAbsolutePath(f, cwd)); + let shouldFilterIgnoredPaths = !every(targets, containsIgnoredPath); + if (!preferSymlinks) { + const result2 = forEach(targets, (p) => !(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p)); + if (result2) return result2; + } + const symlinkedDirectories = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); + const fullImportedFileName = getNormalizedAbsolutePath(importedFileName, cwd); + const result = symlinkedDirectories && forEachAncestorDirectoryStoppingAtGlobalCache( + host, + getDirectoryPath(fullImportedFileName), + (realPathDirectory) => { + const symlinkDirectories = symlinkedDirectories.get(ensureTrailingDirectorySeparator(toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) return void 0; + if (startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; + } + return forEach(targets, (target) => { + if (!startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { + return; + } + const relative = getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (const symlinkDirectory of symlinkDirectories) { + const option = resolvePath(symlinkDirectory, relative); + const result2 = cb(option, target === referenceRedirect); + shouldFilterIgnoredPaths = true; + if (result2) return result2; + } + }); + } + ); + return result || (preferSymlinks ? forEach(targets, (p) => shouldFilterIgnoredPaths && containsIgnoredPath(p) ? void 0 : cb(p, p === referenceRedirect)) : void 0); +} +var runtimeDependencyFields = ["dependencies", "peerDependencies", "optionalDependencies"]; +function getAllRuntimeDependencies(packageJson) { + let result; + for (const field of runtimeDependencyFields) { + const deps = packageJson[field]; + if (deps && typeof deps === "object") { + result = concatenate(result, getOwnKeys(deps)); + } + } + return result; +} +function getAllModulePathsWorker(info, importedFileName, host, compilerOptions, options) { + var _a, _b; + const cache = (_a = host.getModuleResolutionCache) == null ? void 0 : _a.call(host); + const links = (_b = host.getSymlinkCache) == null ? void 0 : _b.call(host); + if (cache && links && host.readFile && !pathContainsNodeModules(info.importingSourceFileName)) { + Debug.type(host); + const state = getTemporaryModuleResolutionState(cache.getPackageJsonInfoCache(), host, {}); + const packageJson = getPackageScopeForPath(getDirectoryPath(info.importingSourceFileName), state); + if (packageJson) { + const toResolve = getAllRuntimeDependencies(packageJson.contents.packageJsonContent); + for (const depName of toResolve || emptyArray) { + const resolved = resolveModuleName( + depName, + combinePaths(packageJson.packageDirectory, "package.json"), + compilerOptions, + host, + cache, + /*redirectedReference*/ + void 0, + options.overrideImportMode + ); + links.setSymlinksFromResolution(resolved.resolvedModule); + } + } + } + const allFileNames = /* @__PURE__ */ new Map(); + let importedFileFromNodeModules = false; + forEachFileNameOfModule( + info.importingSourceFileName, + importedFileName, + host, + /*preferSymlinks*/ + true, + (path, isRedirect) => { + const isInNodeModules = pathContainsNodeModules(path); + allFileNames.set(path, { path: info.getCanonicalFileName(path), isRedirect, isInNodeModules }); + importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules; + } + ); + const sortedPaths = []; + for (let directory = info.canonicalSourceDirectory; allFileNames.size !== 0; ) { + const directoryStart = ensureTrailingDirectorySeparator(directory); + let pathsInDirectory; + allFileNames.forEach(({ path, isRedirect, isInNodeModules }, fileName) => { + if (startsWith(path, directoryStart)) { + (pathsInDirectory || (pathsInDirectory = [])).push({ path: fileName, isRedirect, isInNodeModules }); + allFileNames.delete(fileName); + } + }); + if (pathsInDirectory) { + if (pathsInDirectory.length > 1) { + pathsInDirectory.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); + } + sortedPaths.push(...pathsInDirectory); + } + const newDirectory = getDirectoryPath(directory); + if (newDirectory === directory) break; + directory = newDirectory; + } + if (allFileNames.size) { + const remainingPaths = arrayFrom( + allFileNames.entries(), + ([fileName, { isRedirect, isInNodeModules }]) => ({ path: fileName, isRedirect, isInNodeModules }) + ); + if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); + sortedPaths.push(...remainingPaths); + } + return sortedPaths; +} +function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { + var _a; + const decl = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find( + (d) => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name))) + ); + if (decl) { + return decl.name.text; + } + const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, (d) => { + var _a2, _b, _c, _d; + if (!isModuleDeclaration(d)) return; + const topNamespace = getTopNamespace(d); + if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) return; + const exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) == null ? void 0 : _b.get("export=")) == null ? void 0 : _c.valueDeclaration) == null ? void 0 : _d.expression; + if (!exportAssignment) return; + const exportSymbol = checker.getSymbolAtLocation(exportAssignment); + if (!exportSymbol) return; + const originalExportSymbol = (exportSymbol == null ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol; + if (originalExportSymbol === d.symbol) return topNamespace.parent.parent; + function getTopNamespace(namespaceDeclaration) { + while (namespaceDeclaration.flags & 8 /* NestedNamespace */) { + namespaceDeclaration = namespaceDeclaration.parent; + } + return namespaceDeclaration; + } + }); + const ambientModuleDeclare = ambientModuleDeclareCandidates[0]; + if (ambientModuleDeclare) { + return ambientModuleDeclare.name.text; + } +} +function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, baseDirectory, getCanonicalFileName, host, compilerOptions) { + for (const key in paths) { + for (const patternText2 of paths[key]) { + const normalized = normalizePath(patternText2); + const pattern = getRelativePathIfInSameVolume(normalized, baseDirectory, getCanonicalFileName) ?? normalized; + const indexOfStar = pattern.indexOf("*"); + const candidates = allowedEndings.map((ending) => ({ + ending, + value: processEnding(relativeToBaseUrl, [ending], compilerOptions) + })); + if (tryGetExtensionFromPath2(pattern)) { + candidates.push({ ending: void 0, value: relativeToBaseUrl }); + } + if (indexOfStar !== -1) { + const prefix = pattern.substring(0, indexOfStar); + const suffix = pattern.substring(indexOfStar + 1); + for (const { ending, value } of candidates) { + if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { + const matchedStar = value.substring(prefix.length, value.length - suffix.length); + if (!pathIsRelative(matchedStar)) { + return replaceFirstStar(key, matchedStar); + } + } + } + } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { + return key; + } + } + } + function validateEnding({ ending, value }) { + return ending !== 0 /* Minimal */ || value === processEnding(relativeToBaseUrl, [ending], compilerOptions, host); + } +} +function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, exports2, conditions, mode, isImports, preferTsExtension) { + if (typeof exports2 === "string") { + const ignoreCase = !hostUsesCaseSensitiveFileNames(host); + const getCommonSourceDirectory2 = () => host.getCommonSourceDirectory(); + const outputFile = isImports && getOutputJSFileNameWorker(targetFilePath, options, ignoreCase, getCommonSourceDirectory2); + const declarationFile = isImports && getOutputDeclarationFileNameWorker(targetFilePath, options, ignoreCase, getCommonSourceDirectory2); + const pathOrPattern = getNormalizedAbsolutePath( + combinePaths(packageDirectory, exports2), + /*currentDirectory*/ + void 0 + ); + const extensionSwappedTarget = hasTSFileExtension(targetFilePath) ? removeFileExtension(targetFilePath) + tryGetJSExtensionForFile(targetFilePath, options) : void 0; + const canTryTsExtension = preferTsExtension && hasImplementationTSFileExtension(targetFilePath); + switch (mode) { + case 0 /* Exact */: + if (extensionSwappedTarget && comparePaths(extensionSwappedTarget, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || comparePaths(targetFilePath, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || outputFile && comparePaths(outputFile, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || declarationFile && comparePaths(declarationFile, pathOrPattern, ignoreCase) === 0 /* EqualTo */) { + return { moduleFileToTry: packageName }; + } + break; + case 1 /* Directory */: + if (canTryTsExtension && containsPath(targetFilePath, pathOrPattern, ignoreCase)) { + const fragment = getRelativePathFromDirectory( + pathOrPattern, + targetFilePath, + /*ignoreCase*/ + false + ); + return { moduleFileToTry: getNormalizedAbsolutePath( + combinePaths(combinePaths(packageName, exports2), fragment), + /*currentDirectory*/ + void 0 + ) }; + } + if (extensionSwappedTarget && containsPath(pathOrPattern, extensionSwappedTarget, ignoreCase)) { + const fragment = getRelativePathFromDirectory( + pathOrPattern, + extensionSwappedTarget, + /*ignoreCase*/ + false + ); + return { moduleFileToTry: getNormalizedAbsolutePath( + combinePaths(combinePaths(packageName, exports2), fragment), + /*currentDirectory*/ + void 0 + ) }; + } + if (!canTryTsExtension && containsPath(pathOrPattern, targetFilePath, ignoreCase)) { + const fragment = getRelativePathFromDirectory( + pathOrPattern, + targetFilePath, + /*ignoreCase*/ + false + ); + return { moduleFileToTry: getNormalizedAbsolutePath( + combinePaths(combinePaths(packageName, exports2), fragment), + /*currentDirectory*/ + void 0 + ) }; + } + if (outputFile && containsPath(pathOrPattern, outputFile, ignoreCase)) { + const fragment = getRelativePathFromDirectory( + pathOrPattern, + outputFile, + /*ignoreCase*/ + false + ); + return { moduleFileToTry: combinePaths(packageName, fragment) }; + } + if (declarationFile && containsPath(pathOrPattern, declarationFile, ignoreCase)) { + const fragment = changeFullExtension(getRelativePathFromDirectory( + pathOrPattern, + declarationFile, + /*ignoreCase*/ + false + ), getJSExtensionForFile(declarationFile, options)); + return { moduleFileToTry: combinePaths(packageName, fragment) }; + } + break; + case 2 /* Pattern */: + const starPos = pathOrPattern.indexOf("*"); + const leadingSlice = pathOrPattern.slice(0, starPos); + const trailingSlice = pathOrPattern.slice(starPos + 1); + if (canTryTsExtension && startsWith(targetFilePath, leadingSlice, ignoreCase) && endsWith(targetFilePath, trailingSlice, ignoreCase)) { + const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length); + return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) }; + } + if (extensionSwappedTarget && startsWith(extensionSwappedTarget, leadingSlice, ignoreCase) && endsWith(extensionSwappedTarget, trailingSlice, ignoreCase)) { + const starReplacement = extensionSwappedTarget.slice(leadingSlice.length, extensionSwappedTarget.length - trailingSlice.length); + return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) }; + } + if (!canTryTsExtension && startsWith(targetFilePath, leadingSlice, ignoreCase) && endsWith(targetFilePath, trailingSlice, ignoreCase)) { + const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length); + return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) }; + } + if (outputFile && startsWith(outputFile, leadingSlice, ignoreCase) && endsWith(outputFile, trailingSlice, ignoreCase)) { + const starReplacement = outputFile.slice(leadingSlice.length, outputFile.length - trailingSlice.length); + return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) }; + } + if (declarationFile && startsWith(declarationFile, leadingSlice, ignoreCase) && endsWith(declarationFile, trailingSlice, ignoreCase)) { + const starReplacement = declarationFile.slice(leadingSlice.length, declarationFile.length - trailingSlice.length); + const substituted = replaceFirstStar(packageName, starReplacement); + const jsExtension = tryGetJSExtensionForFile(declarationFile, options); + return jsExtension ? { moduleFileToTry: changeFullExtension(substituted, jsExtension) } : void 0; + } + break; + } + } else if (Array.isArray(exports2)) { + return forEach(exports2, (e) => tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, e, conditions, mode, isImports, preferTsExtension)); + } else if (typeof exports2 === "object" && exports2 !== null) { + for (const key of getOwnKeys(exports2)) { + if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) { + const subTarget = exports2[key]; + const result = tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode, isImports, preferTsExtension); + if (result) { + return result; + } + } + } + } + return void 0; +} +function tryGetModuleNameFromExports(options, host, targetFilePath, packageDirectory, packageName, exports2, conditions) { + if (typeof exports2 === "object" && exports2 !== null && !Array.isArray(exports2) && allKeysStartWithDot(exports2)) { + return forEach(getOwnKeys(exports2), (k) => { + const subPackageName = getNormalizedAbsolutePath( + combinePaths(packageName, k), + /*currentDirectory*/ + void 0 + ); + const mode = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */; + return tryGetModuleNameFromExportsOrImports( + options, + host, + targetFilePath, + packageDirectory, + subPackageName, + exports2[k], + conditions, + mode, + /*isImports*/ + false, + /*preferTsExtension*/ + false + ); + }); + } + return tryGetModuleNameFromExportsOrImports( + options, + host, + targetFilePath, + packageDirectory, + packageName, + exports2, + conditions, + 0 /* Exact */, + /*isImports*/ + false, + /*preferTsExtension*/ + false + ); +} +function tryGetModuleNameFromPackageJsonImports(moduleFileName, sourceDirectory, options, host, importMode, preferTsExtension) { + var _a, _b, _c; + if (!host.readFile || !getResolvePackageJsonImports(options)) { + return void 0; + } + const ancestorDirectoryWithPackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory); + if (!ancestorDirectoryWithPackageJson) { + return void 0; + } + const packageJsonPath = combinePaths(ancestorDirectoryWithPackageJson, "package.json"); + const cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); + if (isMissingPackageJsonInfo(cachedPackageJson) || !host.fileExists(packageJsonPath)) { + return void 0; + } + const packageJsonContent = (cachedPackageJson == null ? void 0 : cachedPackageJson.contents.packageJsonContent) || tryParseJson(host.readFile(packageJsonPath)); + const imports = packageJsonContent == null ? void 0 : packageJsonContent.imports; + if (!imports) { + return void 0; + } + const conditions = getConditions(options, importMode); + return (_c = forEach(getOwnKeys(imports), (k) => { + if (!startsWith(k, "#") || k === "#" || startsWith(k, "#/")) return void 0; + const mode = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */; + return tryGetModuleNameFromExportsOrImports( + options, + host, + moduleFileName, + ancestorDirectoryWithPackageJson, + k, + imports[k], + conditions, + mode, + /*isImports*/ + true, + preferTsExtension + ); + })) == null ? void 0 : _c.moduleFileToTry; +} +function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, allowedEndings, compilerOptions) { + const normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPaths === void 0) { + return void 0; + } + const normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + const relativePaths = flatMap(normalizedSourcePaths, (sourcePath) => { + return map(normalizedTargetPaths, (targetPath) => ensurePathIsNonModuleName(getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName))); + }); + const shortest = min(relativePaths, compareNumberOfDirectorySeparators); + if (!shortest) { + return void 0; + } + return processEnding(shortest, allowedEndings, compilerOptions); +} +function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileName, canonicalSourceDirectory }, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { + if (!host.fileExists || !host.readFile) { + return void 0; + } + const parts = getNodeModulePathParts(path); + if (!parts) { + return void 0; + } + const preferences = getModuleSpecifierPreferences(userPreferences, host, options, importingSourceFile); + const allowedEndings = preferences.getAllowedEndingsInPreferredOrder(); + let moduleSpecifier = path; + let isPackageRootPath = false; + if (!packageNameOnly) { + let packageRootIndex = parts.packageRootIndex; + let moduleFileName; + while (true) { + const { moduleFileToTry, packageRootPath, blockedByExports, verbatimFromExports } = tryDirectoryWithPackageJson(packageRootIndex); + if (getEmitModuleResolutionKind(options) !== 1 /* Classic */) { + if (blockedByExports) { + return void 0; + } + if (verbatimFromExports) { + return moduleFileToTry; + } + } + if (packageRootPath) { + moduleSpecifier = packageRootPath; + isPackageRootPath = true; + break; + } + if (!moduleFileName) moduleFileName = moduleFileToTry; + packageRootIndex = path.indexOf(directorySeparator, packageRootIndex + 1); + if (packageRootIndex === -1) { + moduleSpecifier = processEnding(moduleFileName, allowedEndings, options, host); + break; + } + } + } + if (isRedirect && !isPackageRootPath) { + return void 0; + } + const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); + const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(startsWith(canonicalSourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { + return void 0; + } + const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + return getEmitModuleResolutionKind(options) === 1 /* Classic */ && packageName === nodeModulesDirectoryName ? void 0 : packageName; + function tryDirectoryWithPackageJson(packageRootIndex) { + var _a, _b; + const packageRootPath = path.substring(0, packageRootIndex); + const packageJsonPath = combinePaths(packageRootPath, "package.json"); + let moduleFileToTry = path; + let maybeBlockedByTypesVersions = false; + const cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); + if (isPackageJsonInfo(cachedPackageJson) || cachedPackageJson === void 0 && host.fileExists(packageJsonPath)) { + const packageJsonContent = (cachedPackageJson == null ? void 0 : cachedPackageJson.contents.packageJsonContent) || tryParseJson(host.readFile(packageJsonPath)); + const importMode = overrideMode || getDefaultResolutionModeForFile(importingSourceFile, host, options); + if (getResolvePackageJsonExports(options)) { + const nodeModulesDirectoryName2 = packageRootPath.substring(parts.topLevelPackageNameIndex + 1); + const packageName2 = getPackageNameFromTypesPackageName(nodeModulesDirectoryName2); + const conditions = getConditions(options, importMode); + const fromExports = (packageJsonContent == null ? void 0 : packageJsonContent.exports) ? tryGetModuleNameFromExports( + options, + host, + path, + packageRootPath, + packageName2, + packageJsonContent.exports, + conditions + ) : void 0; + if (fromExports) { + return { ...fromExports, verbatimFromExports: true }; + } + if (packageJsonContent == null ? void 0 : packageJsonContent.exports) { + return { moduleFileToTry: path, blockedByExports: true }; + } + } + const versionPaths = (packageJsonContent == null ? void 0 : packageJsonContent.typesVersions) ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) : void 0; + if (versionPaths) { + const subModuleName = path.slice(packageRootPath.length + 1); + const fromPaths = tryGetModuleNameFromPaths( + subModuleName, + versionPaths.paths, + allowedEndings, + packageRootPath, + getCanonicalFileName, + host, + options + ); + if (fromPaths === void 0) { + maybeBlockedByTypesVersions = true; + } else { + moduleFileToTry = combinePaths(packageRootPath, fromPaths); + } + } + const mainFileRelative = (packageJsonContent == null ? void 0 : packageJsonContent.typings) || (packageJsonContent == null ? void 0 : packageJsonContent.types) || (packageJsonContent == null ? void 0 : packageJsonContent.main) || "index.js"; + if (isString(mainFileRelative) && !(maybeBlockedByTypesVersions && matchPatternOrExact(tryParsePatterns(versionPaths.paths), mainFileRelative))) { + const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + const canonicalModuleFileToTry = getCanonicalFileName(moduleFileToTry); + if (removeFileExtension(mainExportFile) === removeFileExtension(canonicalModuleFileToTry)) { + return { packageRootPath, moduleFileToTry }; + } else if ((packageJsonContent == null ? void 0 : packageJsonContent.type) !== "module" && !fileExtensionIsOneOf(canonicalModuleFileToTry, extensionsNotSupportingExtensionlessResolution) && startsWith(canonicalModuleFileToTry, mainExportFile) && getDirectoryPath(canonicalModuleFileToTry) === removeTrailingDirectorySeparator(mainExportFile) && removeFileExtension(getBaseFileName(canonicalModuleFileToTry)) === "index") { + return { packageRootPath, moduleFileToTry }; + } + } + } else { + const fileName = getCanonicalFileName(moduleFileToTry.substring(parts.packageRootIndex + 1)); + if (fileName === "index.d.ts" || fileName === "index.js" || fileName === "index.ts" || fileName === "index.tsx") { + return { moduleFileToTry, packageRootPath }; + } + } + return { moduleFileToTry }; + } +} +function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) return; + const extensions = flatten(getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }])); + for (const e of extensions) { + const fullPath = path + e; + if (host.fileExists(fullPath)) { + return fullPath; + } + } +} +function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return mapDefined(rootDirs, (rootDir) => { + const relativePath = getRelativePathIfInSameVolume(path, rootDir, getCanonicalFileName); + return relativePath !== void 0 && isPathRelativeToParent(relativePath) ? void 0 : relativePath; + }); +} +function processEnding(fileName, allowedEndings, options, host) { + if (fileExtensionIsOneOf(fileName, [".json" /* Json */, ".mjs" /* Mjs */, ".cjs" /* Cjs */])) { + return fileName; + } + const noExtension = removeFileExtension(fileName); + if (fileName === noExtension) { + return fileName; + } + const jsPriority = allowedEndings.indexOf(2 /* JsExtension */); + const tsPriority = allowedEndings.indexOf(3 /* TsExtension */); + if (fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".cts" /* Cts */]) && tsPriority !== -1 && tsPriority < jsPriority) { + return fileName; + } else if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { + return noExtension + getJSExtensionForFile(fileName, options); + } else if (!fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */]) && fileExtensionIsOneOf(fileName, [".ts" /* Ts */]) && fileName.includes(".d.")) { + return tryGetRealFileNameForNonJsDeclarationFileName(fileName); + } + switch (allowedEndings[0]) { + case 0 /* Minimal */: + const withoutIndex = removeSuffix(noExtension, "/index"); + if (host && withoutIndex !== noExtension && tryGetAnyFileFromPath(host, withoutIndex)) { + return noExtension; + } + return withoutIndex; + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + case 3 /* TsExtension */: + if (isDeclarationFileName(fileName)) { + const extensionlessPriority = allowedEndings.findIndex((e) => e === 0 /* Minimal */ || e === 1 /* Index */); + return extensionlessPriority !== -1 && extensionlessPriority < jsPriority ? noExtension : noExtension + getJSExtensionForFile(fileName, options); + } + return fileName; + default: + return Debug.assertNever(allowedEndings[0]); + } +} +function tryGetRealFileNameForNonJsDeclarationFileName(fileName) { + const baseName = getBaseFileName(fileName); + if (!endsWith(fileName, ".ts" /* Ts */) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [".d.ts" /* Dts */])) return void 0; + const noExtension = removeExtension(fileName, ".ts" /* Ts */); + const ext = noExtension.substring(noExtension.lastIndexOf(".")); + return noExtension.substring(0, noExtension.indexOf(".d.")) + ext; +} +function getJSExtensionForFile(fileName, options) { + return tryGetJSExtensionForFile(fileName, options) ?? Debug.fail(`Extension ${extensionFromPath(fileName)} is unsupported:: FileName:: ${fileName}`); +} +function tryGetJSExtensionForFile(fileName, options) { + const ext = tryGetExtensionFromPath2(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + case ".d.mts" /* Dmts */: + case ".mts" /* Mts */: + case ".mjs" /* Mjs */: + return ".mjs" /* Mjs */; + case ".d.cts" /* Dcts */: + case ".cts" /* Cts */: + case ".cjs" /* Cjs */: + return ".cjs" /* Cjs */; + default: + return void 0; + } +} +function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName) { + const relativePath = getRelativePathToDirectoryOrUrl( + directoryPath, + path, + directoryPath, + getCanonicalFileName, + /*isAbsolutePathAnUrl*/ + false + ); + return isRootedDiskPath(relativePath) ? void 0 : relativePath; +} +function isPathRelativeToParent(path) { + return startsWith(path, ".."); +} +function getDefaultResolutionModeForFile(file, host, compilerOptions) { + return isFullSourceFile(file) ? host.getDefaultResolutionModeForFile(file) : getDefaultResolutionModeForFileWorker(file, compilerOptions); +} +function prefersTsExtension(allowedEndings) { + const tsPriority = allowedEndings.indexOf(3 /* TsExtension */); + return tsPriority > -1 && tsPriority < allowedEndings.indexOf(2 /* JsExtension */); +} + +// src/compiler/checker.ts +var ambientModuleSymbolRegex = /^".+"$/; +var anon = "(anonymous)"; +var nextSymbolId = 1; +var nextNodeId = 1; +var nextMergeId = 1; +var nextFlowId = 1; +var TypeFacts = /* @__PURE__ */ ((TypeFacts3) => { + TypeFacts3[TypeFacts3["None"] = 0] = "None"; + TypeFacts3[TypeFacts3["TypeofEQString"] = 1] = "TypeofEQString"; + TypeFacts3[TypeFacts3["TypeofEQNumber"] = 2] = "TypeofEQNumber"; + TypeFacts3[TypeFacts3["TypeofEQBigInt"] = 4] = "TypeofEQBigInt"; + TypeFacts3[TypeFacts3["TypeofEQBoolean"] = 8] = "TypeofEQBoolean"; + TypeFacts3[TypeFacts3["TypeofEQSymbol"] = 16] = "TypeofEQSymbol"; + TypeFacts3[TypeFacts3["TypeofEQObject"] = 32] = "TypeofEQObject"; + TypeFacts3[TypeFacts3["TypeofEQFunction"] = 64] = "TypeofEQFunction"; + TypeFacts3[TypeFacts3["TypeofEQHostObject"] = 128] = "TypeofEQHostObject"; + TypeFacts3[TypeFacts3["TypeofNEString"] = 256] = "TypeofNEString"; + TypeFacts3[TypeFacts3["TypeofNENumber"] = 512] = "TypeofNENumber"; + TypeFacts3[TypeFacts3["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt"; + TypeFacts3[TypeFacts3["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean"; + TypeFacts3[TypeFacts3["TypeofNESymbol"] = 4096] = "TypeofNESymbol"; + TypeFacts3[TypeFacts3["TypeofNEObject"] = 8192] = "TypeofNEObject"; + TypeFacts3[TypeFacts3["TypeofNEFunction"] = 16384] = "TypeofNEFunction"; + TypeFacts3[TypeFacts3["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject"; + TypeFacts3[TypeFacts3["EQUndefined"] = 65536] = "EQUndefined"; + TypeFacts3[TypeFacts3["EQNull"] = 131072] = "EQNull"; + TypeFacts3[TypeFacts3["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull"; + TypeFacts3[TypeFacts3["NEUndefined"] = 524288] = "NEUndefined"; + TypeFacts3[TypeFacts3["NENull"] = 1048576] = "NENull"; + TypeFacts3[TypeFacts3["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; + TypeFacts3[TypeFacts3["Truthy"] = 4194304] = "Truthy"; + TypeFacts3[TypeFacts3["Falsy"] = 8388608] = "Falsy"; + TypeFacts3[TypeFacts3["IsUndefined"] = 16777216] = "IsUndefined"; + TypeFacts3[TypeFacts3["IsNull"] = 33554432] = "IsNull"; + TypeFacts3[TypeFacts3["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull"; + TypeFacts3[TypeFacts3["All"] = 134217727] = "All"; + TypeFacts3[TypeFacts3["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts"; + TypeFacts3[TypeFacts3["BaseStringFacts"] = 12582401] = "BaseStringFacts"; + TypeFacts3[TypeFacts3["StringStrictFacts"] = 16317953] = "StringStrictFacts"; + TypeFacts3[TypeFacts3["StringFacts"] = 16776705] = "StringFacts"; + TypeFacts3[TypeFacts3["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts"; + TypeFacts3[TypeFacts3["EmptyStringFacts"] = 12582401 /* BaseStringFacts */] = "EmptyStringFacts"; + TypeFacts3[TypeFacts3["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts"; + TypeFacts3[TypeFacts3["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts"; + TypeFacts3[TypeFacts3["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts"; + TypeFacts3[TypeFacts3["BaseNumberFacts"] = 12582146] = "BaseNumberFacts"; + TypeFacts3[TypeFacts3["NumberStrictFacts"] = 16317698] = "NumberStrictFacts"; + TypeFacts3[TypeFacts3["NumberFacts"] = 16776450] = "NumberFacts"; + TypeFacts3[TypeFacts3["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts"; + TypeFacts3[TypeFacts3["ZeroNumberFacts"] = 12582146 /* BaseNumberFacts */] = "ZeroNumberFacts"; + TypeFacts3[TypeFacts3["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts"; + TypeFacts3[TypeFacts3["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts"; + TypeFacts3[TypeFacts3["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts"; + TypeFacts3[TypeFacts3["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts"; + TypeFacts3[TypeFacts3["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts"; + TypeFacts3[TypeFacts3["BigIntFacts"] = 16775940] = "BigIntFacts"; + TypeFacts3[TypeFacts3["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts"; + TypeFacts3[TypeFacts3["ZeroBigIntFacts"] = 12581636 /* BaseBigIntFacts */] = "ZeroBigIntFacts"; + TypeFacts3[TypeFacts3["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts"; + TypeFacts3[TypeFacts3["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts"; + TypeFacts3[TypeFacts3["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts"; + TypeFacts3[TypeFacts3["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts"; + TypeFacts3[TypeFacts3["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts"; + TypeFacts3[TypeFacts3["BooleanFacts"] = 16774920] = "BooleanFacts"; + TypeFacts3[TypeFacts3["FalseStrictFacts"] = 12121864] = "FalseStrictFacts"; + TypeFacts3[TypeFacts3["FalseFacts"] = 12580616 /* BaseBooleanFacts */] = "FalseFacts"; + TypeFacts3[TypeFacts3["TrueStrictFacts"] = 7927560] = "TrueStrictFacts"; + TypeFacts3[TypeFacts3["TrueFacts"] = 16774920] = "TrueFacts"; + TypeFacts3[TypeFacts3["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts"; + TypeFacts3[TypeFacts3["SymbolFacts"] = 16772880] = "SymbolFacts"; + TypeFacts3[TypeFacts3["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts"; + TypeFacts3[TypeFacts3["ObjectFacts"] = 16736160] = "ObjectFacts"; + TypeFacts3[TypeFacts3["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; + TypeFacts3[TypeFacts3["FunctionFacts"] = 16728e3] = "FunctionFacts"; + TypeFacts3[TypeFacts3["VoidFacts"] = 9830144] = "VoidFacts"; + TypeFacts3[TypeFacts3["UndefinedFacts"] = 26607360] = "UndefinedFacts"; + TypeFacts3[TypeFacts3["NullFacts"] = 42917664] = "NullFacts"; + TypeFacts3[TypeFacts3["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts"; + TypeFacts3[TypeFacts3["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts"; + TypeFacts3[TypeFacts3["UnknownFacts"] = 83886079] = "UnknownFacts"; + TypeFacts3[TypeFacts3["AllTypeofNE"] = 556800] = "AllTypeofNE"; + TypeFacts3[TypeFacts3["OrFactsMask"] = 8256] = "OrFactsMask"; + TypeFacts3[TypeFacts3["AndFactsMask"] = 134209471] = "AndFactsMask"; + return TypeFacts3; +})(TypeFacts || {}); +var typeofNEFacts = new Map(Object.entries({ + string: 256 /* TypeofNEString */, + number: 512 /* TypeofNENumber */, + bigint: 1024 /* TypeofNEBigInt */, + boolean: 2048 /* TypeofNEBoolean */, + symbol: 4096 /* TypeofNESymbol */, + undefined: 524288 /* NEUndefined */, + object: 8192 /* TypeofNEObject */, + function: 16384 /* TypeofNEFunction */ +})); +var CheckMode = /* @__PURE__ */ ((CheckMode3) => { + CheckMode3[CheckMode3["Normal"] = 0] = "Normal"; + CheckMode3[CheckMode3["Contextual"] = 1] = "Contextual"; + CheckMode3[CheckMode3["Inferential"] = 2] = "Inferential"; + CheckMode3[CheckMode3["SkipContextSensitive"] = 4] = "SkipContextSensitive"; + CheckMode3[CheckMode3["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; + CheckMode3[CheckMode3["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; + CheckMode3[CheckMode3["RestBindingElement"] = 32] = "RestBindingElement"; + CheckMode3[CheckMode3["TypeOnly"] = 64] = "TypeOnly"; + return CheckMode3; +})(CheckMode || {}); +var SignatureCheckMode = /* @__PURE__ */ ((SignatureCheckMode3) => { + SignatureCheckMode3[SignatureCheckMode3["None"] = 0] = "None"; + SignatureCheckMode3[SignatureCheckMode3["BivariantCallback"] = 1] = "BivariantCallback"; + SignatureCheckMode3[SignatureCheckMode3["StrictCallback"] = 2] = "StrictCallback"; + SignatureCheckMode3[SignatureCheckMode3["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes"; + SignatureCheckMode3[SignatureCheckMode3["StrictArity"] = 8] = "StrictArity"; + SignatureCheckMode3[SignatureCheckMode3["StrictTopSignature"] = 16] = "StrictTopSignature"; + SignatureCheckMode3[SignatureCheckMode3["Callback"] = 3] = "Callback"; + return SignatureCheckMode3; +})(SignatureCheckMode || {}); +var isNotOverloadAndNotAccessor = and(isNotOverload, isNotAccessor); +var intrinsicTypeKinds = new Map(Object.entries({ + Uppercase: 0 /* Uppercase */, + Lowercase: 1 /* Lowercase */, + Capitalize: 2 /* Capitalize */, + Uncapitalize: 3 /* Uncapitalize */, + NoInfer: 4 /* NoInfer */ +})); +var SymbolLinks = class { +}; +function NodeLinks() { + this.flags = 0 /* None */; +} +function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; +} +function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; +} +function isInstantiatedModule(node, preserveConstEnums) { + const moduleState = getModuleInstanceState(node); + return moduleState === 1 /* Instantiated */ || preserveConstEnums && moduleState === 2 /* ConstEnumOnly */; +} +function createTypeChecker(host) { + var deferredDiagnosticsCallbacks = []; + var addLazyDiagnostic = (arg) => { + deferredDiagnosticsCallbacks.push(arg); + }; + var cancellationToken; + var scanner; + var Symbol13 = objectAllocator.getSymbolConstructor(); + var Type7 = objectAllocator.getTypeConstructor(); + var Signature5 = objectAllocator.getSignatureConstructor(); + var typeCount = 0; + var symbolCount = 0; + var totalInstantiationCount = 0; + var instantiationCount = 0; + var instantiationDepth = 0; + var inlineLevel = 0; + var currentNode; + var varianceTypeParameter; + var isInferencePartiallyBlocked = false; + var emptySymbols = createSymbolTable(); + var arrayVariances = [1 /* Covariant */]; + var compilerOptions = host.getCompilerOptions(); + var languageVersion = getEmitScriptTarget(compilerOptions); + var moduleKind = getEmitModuleKind(compilerOptions); + var legacyDecorators = !!compilerOptions.experimentalDecorators; + var useDefineForClassFields = getUseDefineForClassFields(compilerOptions); + var emitStandardClassFields = getEmitStandardClassFields(compilerOptions); + var allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions); + var strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); + var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = getStrictOptionValue(compilerOptions, "strictBindCallApply"); + var strictPropertyInitialization = getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var strictBuiltinIteratorReturn = getStrictOptionValue(compilerOptions, "strictBuiltinIteratorReturn"); + var noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny"); + var noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis"); + var useUnknownInCatchVariables = getStrictOptionValue(compilerOptions, "useUnknownInCatchVariables"); + var exactOptionalPropertyTypes = compilerOptions.exactOptionalPropertyTypes; + var noUncheckedSideEffectImports = !!compilerOptions.noUncheckedSideEffectImports; + var checkBinaryExpression = createCheckBinaryExpression(); + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var syntacticNodeBuilder = createSyntacticTypeNodeBuilder(compilerOptions, nodeBuilder.syntacticBuilderResolver); + var evaluate = createEvaluator({ + evaluateElementAccessExpression, + evaluateEntityNameExpression + }); + var globals = createSymbolTable(); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); + undefinedSymbol.declarations = []; + var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); + globalThisSymbol.exports = globals; + globalThisSymbol.declarations = []; + globals.set(globalThisSymbol.escapedName, globalThisSymbol); + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + var requireSymbol = createSymbol(4 /* Property */, "require"); + var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules"; + var canCollectSymbolAliasAccessabilityData = !compilerOptions.verbatimModuleSyntax; + var apparentArgumentCount; + var lastGetCombinedNodeFlagsNode; + var lastGetCombinedNodeFlagsResult = 0 /* None */; + var lastGetCombinedModifierFlagsNode; + var lastGetCombinedModifierFlagsResult = 0 /* None */; + var resolveName = createNameResolver({ + compilerOptions, + requireSymbol, + argumentsSymbol, + globals, + getSymbolOfDeclaration, + error, + getRequiresScopeChangeCache, + setRequiresScopeChangeCache, + lookup: getSymbol, + onPropertyWithInvalidInitializer: checkAndReportErrorForInvalidInitializer, + onFailedToResolveSymbol, + onSuccessfullyResolvedSymbol + }); + var resolveNameForSymbolSuggestion = createNameResolver({ + compilerOptions, + requireSymbol, + argumentsSymbol, + globals, + getSymbolOfDeclaration, + error, + getRequiresScopeChangeCache, + setRequiresScopeChangeCache, + lookup: getSuggestionForSymbolNameLookup + }); + const checker = { + getNodeCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.nodeCount, 0), + getIdentifierCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.identifierCount, 0), + getSymbolCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.symbolCount, symbolCount), + getTypeCount: () => typeCount, + getInstantiationCount: () => totalInstantiationCount, + getRelationCacheSizes: () => ({ + assignable: assignableRelation.size, + identity: identityRelation.size, + subtype: subtypeRelation.size, + strictSubtype: strictSubtypeRelation.size + }), + isUndefinedSymbol: (symbol) => symbol === undefinedSymbol, + isArgumentsSymbol: (symbol) => symbol === argumentsSymbol, + isUnknownSymbol: (symbol) => symbol === unknownSymbol, + getMergedSymbol, + symbolIsValue, + getDiagnostics, + getGlobalDiagnostics, + getRecursionIdentity, + getUnmatchedProperties, + getTypeOfSymbolAtLocation: (symbol, locationIn) => { + const location = getParseTreeNode(locationIn); + return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; + }, + getTypeOfSymbol, + getSymbolsOfParameterPropertyDeclaration: (parameterIn, parameterName) => { + const parameter = getParseTreeNode(parameterIn, isParameter); + if (parameter === void 0) return Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + Debug.assert(isParameterPropertyDeclaration(parameter, parameter.parent)); + return getSymbolsOfParameterPropertyDeclaration(parameter, escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol, + getPropertiesOfType, + getPropertyOfType: (type, name) => getPropertyOfType(type, escapeLeadingUnderscores(name)), + getPrivateIdentifierPropertyOfType: (leftType, name, location) => { + const node = getParseTreeNode(location); + if (!node) { + return void 0; + } + const propName = escapeLeadingUnderscores(name); + const lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node); + return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : void 0; + }, + getTypeOfPropertyOfType: (type, name) => getTypeOfPropertyOfType(type, escapeLeadingUnderscores(name)), + getIndexInfoOfType: (type, kind) => getIndexInfoOfType(type, kind === 0 /* String */ ? stringType : numberType), + getIndexInfosOfType, + getIndexInfosOfIndexSymbol, + getSignaturesOfType, + getIndexTypeOfType: (type, kind) => getIndexTypeOfType(type, kind === 0 /* String */ ? stringType : numberType), + getIndexType: (type) => getIndexType(type), + getBaseTypes, + getBaseTypeOfLiteralType, + getWidenedType, + getWidenedLiteralType, + fillMissingTypeArguments, + getTypeFromTypeNode: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isTypeNode); + return node ? getTypeFromTypeNode(node) : errorType; + }, + getParameterType: getTypeAtPosition, + getParameterIdentifierInfoAtPosition, + getPromisedTypeOfPromise, + getAwaitedType: (type) => getAwaitedType(type), + getReturnTypeOfSignature, + isNullableType, + getNullableType, + getNonNullableType, + getNonOptionalType: removeOptionalTypeMarker, + getTypeArguments, + typeToTypeNode: nodeBuilder.typeToTypeNode, + typePredicateToTypePredicateNode: nodeBuilder.typePredicateToTypePredicateNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToNode: nodeBuilder.symbolToNode, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, + getSymbolsInScope: (locationIn, meaning) => { + const location = getParseTreeNode(locationIn); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: (nodeIn) => { + const node = getParseTreeNode(nodeIn); + return node ? getSymbolAtLocation( + node, + /*ignoreErrors*/ + true + ) : void 0; + }, + getIndexInfosAtLocation: (nodeIn) => { + const node = getParseTreeNode(nodeIn); + return node ? getIndexInfosAtLocation(node) : void 0; + }, + getShorthandAssignmentValueSymbol: (nodeIn) => { + const node = getParseTreeNode(nodeIn); + return node ? getShorthandAssignmentValueSymbol(node) : void 0; + }, + getExportSpecifierLocalTargetSymbol: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : void 0; + }, + getExportSymbolOfSymbol(symbol) { + return getMergedSymbol(symbol.exportSymbol || symbol); + }, + getTypeAtLocation: (nodeIn) => { + const node = getParseTreeNode(nodeIn); + return node ? getTypeOfNode(node) : errorType; + }, + getTypeOfAssignmentPattern: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isAssignmentPattern); + return node && getTypeOfAssignmentPattern(node) || errorType; + }, + getPropertySymbolOfDestructuringAssignment: (locationIn) => { + const location = getParseTreeNode(locationIn, isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : void 0; + }, + signatureToString: (signature, enclosingDeclaration, flags, kind) => { + return signatureToString(signature, getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: (type, enclosingDeclaration, flags) => { + return typeToString(type, getParseTreeNode(enclosingDeclaration), flags); + }, + symbolToString: (symbol, enclosingDeclaration, meaning, flags) => { + return symbolToString(symbol, getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: (predicate, enclosingDeclaration, flags) => { + return typePredicateToString(predicate, getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: (signature, enclosingDeclaration, flags, kind, writer) => { + return signatureToString(signature, getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: (type, enclosingDeclaration, flags, writer) => { + return typeToString(type, getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: (symbol, enclosingDeclaration, meaning, flags, writer) => { + return symbolToString(symbol, getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: (predicate, enclosingDeclaration, flags, writer) => { + return typePredicateToString(predicate, getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getAugmentedPropertiesOfType, + getRootSymbols, + getSymbolOfExpando, + getContextualType: (nodeIn, contextFlags) => { + const node = getParseTreeNode(nodeIn, isExpression); + if (!node) { + return void 0; + } + if (contextFlags & 4 /* Completions */) { + return runWithInferenceBlockedFromSourceNode(node, () => getContextualType(node, contextFlags)); + } + return getContextualType(node, contextFlags); + }, + getContextualTypeForObjectLiteralElement: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement( + node, + /*contextFlags*/ + void 0 + ) : void 0; + }, + getContextualTypeForArgumentAtIndex: (nodeIn, argIndex) => { + const node = getParseTreeNode(nodeIn, isCallLikeExpression); + return node && getContextualTypeForArgumentAtIndex(node, argIndex); + }, + getContextualTypeForJsxAttribute: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isJsxAttributeLike); + return node && getContextualTypeForJsxAttribute( + node, + /*contextFlags*/ + void 0 + ); + }, + isContextSensitive, + getTypeOfPropertyOfContextualType, + getFullyQualifiedName, + getResolvedSignature: (node, candidatesOutArray, argumentCount) => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */), + getCandidateSignaturesForStringLiteralCompletions, + getResolvedSignatureForSignatureHelp: (node, candidatesOutArray, argumentCount) => runWithoutResolvedSignatureCaching(node, () => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */)), + getExpandedParameters, + hasEffectiveRestParameter, + containsArgumentsReference, + getConstantValue: (nodeIn) => { + const node = getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue2(node) : void 0; + }, + isValidPropertyAccess: (nodeIn, propertyName) => { + const node = getParseTreeNode(nodeIn, isPropertyAccessOrQualifiedNameOrImportTypeNode); + return !!node && isValidPropertyAccess(node, escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: (nodeIn, type, property) => { + const node = getParseTreeNode(nodeIn, isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); + }, + getSignatureFromDeclaration: (declarationIn) => { + const declaration = getParseTreeNode(declarationIn, isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : void 0; + }, + isImplementationOfOverload: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isFunctionLike); + return node ? isImplementationOfOverload(node) : void 0; + }, + getImmediateAliasedSymbol, + getAliasedSymbol: resolveAlias, + getEmitResolver, + requiresAddingImplicitUndefined, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule, + forEachExportAndPropertyOfModule, + getSymbolWalker: createGetSymbolWalker( + getRestTypeOfSignature, + getTypePredicateOfSignature, + getReturnTypeOfSignature, + getBaseTypes, + resolveStructuredTypeMembers, + getTypeOfSymbol, + getResolvedSymbol, + getConstraintOfTypeParameter, + getFirstIdentifier, + getTypeArguments + ), + getAmbientModules, + getJsxIntrinsicTagNamesAt, + isOptionalParameter: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: (name, symbol) => tryGetMemberInModuleExports(escapeLeadingUnderscores(name), symbol), + tryGetMemberInModuleExportsAndProperties: (name, symbol) => tryGetMemberInModuleExportsAndProperties(escapeLeadingUnderscores(name), symbol), + tryFindAmbientModule: (moduleName) => tryFindAmbientModule( + moduleName, + /*withAugmentations*/ + true + ), + getApparentType, + getUnionType, + isTypeAssignableTo, + createAnonymousType, + createSignature, + createSymbol, + createIndexInfo, + getAnyType: () => anyType, + getStringType: () => stringType, + getStringLiteralType, + getNumberType: () => numberType, + getNumberLiteralType, + getBigIntType: () => bigintType, + getBigIntLiteralType, + getUnknownType: () => unknownType, + createPromiseType, + createArrayType, + getElementTypeOfArrayType, + getBooleanType: () => booleanType, + getFalseType: (fresh) => fresh ? falseType : regularFalseType, + getTrueType: (fresh) => fresh ? trueType : regularTrueType, + getVoidType: () => voidType, + getUndefinedType: () => undefinedType, + getNullType: () => nullType, + getESSymbolType: () => esSymbolType, + getNeverType: () => neverType, + getOptionalType: () => optionalType, + getPromiseType: () => getGlobalPromiseType( + /*reportErrors*/ + false + ), + getPromiseLikeType: () => getGlobalPromiseLikeType( + /*reportErrors*/ + false + ), + getAnyAsyncIterableType: () => { + const type = getGlobalAsyncIterableType( + /*reportErrors*/ + false + ); + if (type === emptyGenericType) return void 0; + return createTypeReference(type, [anyType, anyType, anyType]); + }, + isSymbolAccessible, + isArrayType, + isTupleType, + isArrayLikeType, + isEmptyAnonymousObjectType, + isTypeInvalidDueToUnionDiscriminant, + getExactOptionalProperties, + getAllPossiblePropertiesOfTypes, + getSuggestedSymbolForNonexistentProperty, + getSuggestedSymbolForNonexistentJSXAttribute, + getSuggestedSymbolForNonexistentSymbol: (location, name, meaning) => getSuggestedSymbolForNonexistentSymbol(location, escapeLeadingUnderscores(name), meaning), + getSuggestedSymbolForNonexistentModule, + getSuggestedSymbolForNonexistentClassMember, + getBaseConstraintOfType, + getDefaultFromTypeParameter: (type) => type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : void 0, + resolveName(name, location, meaning, excludeGlobals) { + return resolveName( + location, + escapeLeadingUnderscores(name), + meaning, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false, + excludeGlobals + ); + }, + getJsxNamespace: (n) => unescapeLeadingUnderscores(getJsxNamespace(n)), + getJsxFragmentFactory: (n) => { + const jsxFragmentFactory = getJsxFragmentFactoryEntity(n); + return jsxFragmentFactory && unescapeLeadingUnderscores(getFirstIdentifier(jsxFragmentFactory).escapedText); + }, + getAccessibleSymbolChain, + getTypePredicateOfSignature, + resolveExternalModuleName: (moduleSpecifierIn) => { + const moduleSpecifier = getParseTreeNode(moduleSpecifierIn, isExpression); + return moduleSpecifier && resolveExternalModuleName( + moduleSpecifier, + moduleSpecifier, + /*ignoreErrors*/ + true + ); + }, + resolveExternalModuleSymbol, + tryGetThisTypeAt: (nodeIn, includeGlobalThis, container) => { + const node = getParseTreeNode(nodeIn); + return node && tryGetThisTypeAt(node, includeGlobalThis, container); + }, + getTypeArgumentConstraint: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isTypeNode); + return node && getTypeArgumentConstraint(node); + }, + getSuggestionDiagnostics: (fileIn, ct) => { + const file = getParseTreeNode(fileIn, isSourceFile) || Debug.fail("Could not determine parsed source file."); + if (skipTypeChecking(file, compilerOptions, host)) { + return emptyArray; + } + let diagnostics2; + try { + cancellationToken = ct; + checkSourceFileWithEagerDiagnostics(file); + Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); + diagnostics2 = addRange(diagnostics2, suggestionDiagnostics.getDiagnostics(file.fileName)); + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), (containingNode, kind, diag2) => { + if (!containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 33554432 /* Ambient */))) { + (diagnostics2 || (diagnostics2 = [])).push({ ...diag2, category: 2 /* Suggestion */ }); + } + }); + return diagnostics2 || emptyArray; + } finally { + cancellationToken = void 0; + } + }, + runWithCancellationToken: (token, callback) => { + try { + cancellationToken = token; + return callback(checker); + } finally { + cancellationToken = void 0; + } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, + isDeclarationVisible, + isPropertyAccessible, + getTypeOnlyAliasDeclaration, + getMemberOverrideModifierStatus, + isTypeParameterPossiblyReferenced, + typeHasCallOrConstructSignatures, + getSymbolFlags, + getTypeArgumentsForResolvedSignature + }; + function getTypeArgumentsForResolvedSignature(signature) { + if (signature.mapper === void 0) return void 0; + return instantiateTypes((signature.target || signature).typeParameters, signature.mapper); + } + function getCandidateSignaturesForStringLiteralCompletions(call, editingArgument) { + const candidatesSet = /* @__PURE__ */ new Set(); + const candidates = []; + runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker( + call, + candidates, + /*argumentCount*/ + void 0, + 0 /* Normal */ + )); + for (const candidate of candidates) { + candidatesSet.add(candidate); + } + candidates.length = 0; + runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker( + call, + candidates, + /*argumentCount*/ + void 0, + 0 /* Normal */ + )); + for (const candidate of candidates) { + candidatesSet.add(candidate); + } + return arrayFrom(candidatesSet); + } + function runWithoutResolvedSignatureCaching(node, fn) { + node = findAncestor(node, isCallLikeOrFunctionLikeExpression); + if (node) { + const cachedResolvedSignatures = []; + const cachedTypes2 = []; + while (node) { + const nodeLinks2 = getNodeLinks(node); + cachedResolvedSignatures.push([nodeLinks2, nodeLinks2.resolvedSignature]); + nodeLinks2.resolvedSignature = void 0; + if (isFunctionExpressionOrArrowFunction(node)) { + const symbolLinks2 = getSymbolLinks(getSymbolOfDeclaration(node)); + const type = symbolLinks2.type; + cachedTypes2.push([symbolLinks2, type]); + symbolLinks2.type = void 0; + } + node = findAncestor(node.parent, isCallLikeOrFunctionLikeExpression); + } + const result = fn(); + for (const [nodeLinks2, resolvedSignature] of cachedResolvedSignatures) { + nodeLinks2.resolvedSignature = resolvedSignature; + } + for (const [symbolLinks2, type] of cachedTypes2) { + symbolLinks2.type = type; + } + return result; + } + return fn(); + } + function runWithInferenceBlockedFromSourceNode(node, fn) { + const containingCall = findAncestor(node, isCallLikeExpression); + if (containingCall) { + let toMarkSkip = node; + do { + getNodeLinks(toMarkSkip).skipDirectInference = true; + toMarkSkip = toMarkSkip.parent; + } while (toMarkSkip && toMarkSkip !== containingCall); + } + isInferencePartiallyBlocked = true; + const result = runWithoutResolvedSignatureCaching(node, fn); + isInferencePartiallyBlocked = false; + if (containingCall) { + let toMarkSkip = node; + do { + getNodeLinks(toMarkSkip).skipDirectInference = void 0; + toMarkSkip = toMarkSkip.parent; + } while (toMarkSkip && toMarkSkip !== containingCall); + } + return result; + } + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) { + const node = getParseTreeNode(nodeIn, isCallLikeExpression); + apparentArgumentCount = argumentCount; + const res = !node ? void 0 : getResolvedSignature(node, candidatesOutArray, checkMode); + apparentArgumentCount = void 0; + return res; + } + var tupleTypes = /* @__PURE__ */ new Map(); + var unionTypes = /* @__PURE__ */ new Map(); + var unionOfUnionTypes = /* @__PURE__ */ new Map(); + var intersectionTypes = /* @__PURE__ */ new Map(); + var stringLiteralTypes = /* @__PURE__ */ new Map(); + var numberLiteralTypes = /* @__PURE__ */ new Map(); + var bigIntLiteralTypes = /* @__PURE__ */ new Map(); + var enumLiteralTypes = /* @__PURE__ */ new Map(); + var indexedAccessTypes = /* @__PURE__ */ new Map(); + var templateLiteralTypes = /* @__PURE__ */ new Map(); + var stringMappingTypes = /* @__PURE__ */ new Map(); + var substitutionTypes = /* @__PURE__ */ new Map(); + var subtypeReductionCache = /* @__PURE__ */ new Map(); + var decoratorContextOverrideTypeCache = /* @__PURE__ */ new Map(); + var cachedTypes = /* @__PURE__ */ new Map(); + var evolvingArrayTypes = []; + var undefinedProperties = /* @__PURE__ */ new Map(); + var markerTypes = /* @__PURE__ */ new Set(); + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); + var unresolvedSymbols = /* @__PURE__ */ new Map(); + var errorTypes = /* @__PURE__ */ new Map(); + var seenIntrinsicNames = /* @__PURE__ */ new Set(); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any", 262144 /* NonInferrableType */, "auto"); + var wildcardType = createIntrinsicType( + 1 /* Any */, + "any", + /*objectFlags*/ + void 0, + "wildcard" + ); + var blockedStringType = createIntrinsicType( + 1 /* Any */, + "any", + /*objectFlags*/ + void 0, + "blocked string" + ); + var errorType = createIntrinsicType(1 /* Any */, "error"); + var unresolvedType = createIntrinsicType(1 /* Any */, "unresolved"); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 65536 /* ContainsWideningType */, "non-inferrable"); + var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); + var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); + var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 65536 /* ContainsWideningType */, "widening"); + var missingType = createIntrinsicType( + 32768 /* Undefined */, + "undefined", + /*objectFlags*/ + void 0, + "missing" + ); + var undefinedOrMissingType = exactOptionalPropertyTypes ? missingType : undefinedType; + var optionalType = createIntrinsicType( + 32768 /* Undefined */, + "undefined", + /*objectFlags*/ + void 0, + "optional" + ); + var nullType = createIntrinsicType(65536 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 65536 /* ContainsWideningType */, "widening"); + var stringType = createIntrinsicType(4 /* String */, "string"); + var numberType = createIntrinsicType(8 /* Number */, "number"); + var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); + var falseType = createIntrinsicType( + 512 /* BooleanLiteral */, + "false", + /*objectFlags*/ + void 0, + "fresh" + ); + var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType( + 512 /* BooleanLiteral */, + "true", + /*objectFlags*/ + void 0, + "fresh" + ); + var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); + trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = getUnionType([regularFalseType, regularTrueType]); + var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16384 /* Void */, "void"); + var neverType = createIntrinsicType(131072 /* Never */, "never"); + var silentNeverType = createIntrinsicType(131072 /* Never */, "never", 262144 /* NonInferrableType */, "silent"); + var implicitNeverType = createIntrinsicType( + 131072 /* Never */, + "never", + /*objectFlags*/ + void 0, + "implicit" + ); + var unreachableNeverType = createIntrinsicType( + 131072 /* Never */, + "never", + /*objectFlags*/ + void 0, + "unreachable" + ); + var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); + var stringOrNumberType = getUnionType([stringType, numberType]); + var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); + var numberOrBigIntType = getUnionType([numberType, bigintType]); + var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]); + var numericStringType = getTemplateLiteralType(["", ""], [numberType]); + var restrictiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t, () => "(restrictive mapper)"); + var permissiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? wildcardType : t, () => "(permissive mapper)"); + var uniqueLiteralType = createIntrinsicType( + 131072 /* Never */, + "never", + /*objectFlags*/ + void 0, + "unique literal" + ); + var uniqueLiteralMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? uniqueLiteralType : t, () => "(unique literal mapper)"); + var outofbandVarianceMarkerHandler; + var reportUnreliableMapper = makeFunctionTypeMapper((t) => { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler( + /*onlyUnreliable*/ + true + ); + } + return t; + }, () => "(unmeasurable reporter)"); + var reportUnmeasurableMapper = makeFunctionTypeMapper((t) => { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler( + /*onlyUnreliable*/ + false + ); + } + return t; + }, () => "(unreliable reporter)"); + var emptyObjectType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + var emptyJsxObjectType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; + var emptyFreshJsxObjectType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + emptyFreshJsxObjectType.objectFlags |= 2048 /* JsxAttributes */ | 8192 /* FreshLiteral */ | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + emptyTypeLiteralSymbol.members = createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, emptyArray); + var unknownEmptyObjectType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, unknownEmptyObjectType]) : unknownType; + var emptyGenericType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + emptyGenericType.instantiations = /* @__PURE__ */ new Map(); + var anyFunctionType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + anyFunctionType.objectFlags |= 262144 /* NonInferrableType */; + var noConstraintType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + var circularConstraintType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + var resolvingDefaultType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + var markerSuperType = createTypeParameter(); + var markerSubType = createTypeParameter(); + markerSubType.constraint = markerSuperType; + var markerOtherType = createTypeParameter(); + var markerSuperTypeForCheck = createTypeParameter(); + var markerSubTypeForCheck = createTypeParameter(); + markerSubTypeForCheck.constraint = markerSuperTypeForCheck; + var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); + var anySignature = createSignature( + /*declaration*/ + void 0, + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + emptyArray, + anyType, + /*resolvedTypePredicate*/ + void 0, + 0, + 0 /* None */ + ); + var unknownSignature = createSignature( + /*declaration*/ + void 0, + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + emptyArray, + errorType, + /*resolvedTypePredicate*/ + void 0, + 0, + 0 /* None */ + ); + var resolvingSignature = createSignature( + /*declaration*/ + void 0, + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + emptyArray, + anyType, + /*resolvedTypePredicate*/ + void 0, + 0, + 0 /* None */ + ); + var silentNeverSignature = createSignature( + /*declaration*/ + void 0, + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + emptyArray, + silentNeverType, + /*resolvedTypePredicate*/ + void 0, + 0, + 0 /* None */ + ); + var enumNumberIndexInfo = createIndexInfo( + numberType, + stringType, + /*isReadonly*/ + true + ); + var anyBaseTypeIndexInfo = createIndexInfo( + stringType, + anyType, + /*isReadonly*/ + false + ); + var iterationTypesCache = /* @__PURE__ */ new Map(); + var noIterationTypes = { + get yieldType() { + return Debug.fail("Not supported"); + }, + get returnType() { + return Debug.fail("Not supported"); + }, + get nextType() { + return Debug.fail("Not supported"); + } + }; + var anyIterationTypes = createIterationTypes(anyType, anyType, anyType); + var asyncIterationTypesResolver = { + iterableCacheKey: "iterationTypesOfAsyncIterable", + iteratorCacheKey: "iterationTypesOfAsyncIterator", + iteratorSymbolName: "asyncIterator", + getGlobalIteratorType: getGlobalAsyncIteratorType, + getGlobalIterableType: getGlobalAsyncIterableType, + getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType, + getGlobalIteratorObjectType: getGlobalAsyncIteratorObjectType, + getGlobalGeneratorType: getGlobalAsyncGeneratorType, + getGlobalBuiltinIteratorTypes: getGlobalBuiltinAsyncIteratorTypes, + resolveIterationType: (type, errorNode) => getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member), + mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method, + mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method, + mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + }; + var syncIterationTypesResolver = { + iterableCacheKey: "iterationTypesOfIterable", + iteratorCacheKey: "iterationTypesOfIterator", + iteratorSymbolName: "iterator", + getGlobalIteratorType, + getGlobalIterableType, + getGlobalIterableIteratorType, + getGlobalIteratorObjectType, + getGlobalGeneratorType, + getGlobalBuiltinIteratorTypes, + resolveIterationType: (type, _errorNode) => type, + mustHaveANextMethodDiagnostic: Diagnostics.An_iterator_must_have_a_next_method, + mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_iterator_must_be_a_method, + mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property + }; + var amalgamatedDuplicates; + var reverseMappedCache = /* @__PURE__ */ new Map(); + var reverseHomomorphicMappedCache = /* @__PURE__ */ new Map(); + var ambientModulesCache; + var patternAmbientModules; + var patternAmbientModuleAugmentations; + var globalObjectType; + var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalNonNullableTypeAlias; + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolConstructorTypeSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalIteratorObjectType; + var deferredGlobalGeneratorType; + var deferredGlobalIteratorYieldResultType; + var deferredGlobalIteratorReturnResultType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalBuiltinIteratorTypes; + var deferredGlobalBuiltinAsyncIteratorTypes; + var deferredGlobalAsyncIteratorObjectType; + var deferredGlobalAsyncGeneratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredGlobalImportMetaType; + var deferredGlobalImportMetaExpressionType; + var deferredGlobalImportCallOptionsType; + var deferredGlobalImportAttributesType; + var deferredGlobalDisposableType; + var deferredGlobalAsyncDisposableType; + var deferredGlobalExtractSymbol; + var deferredGlobalOmitSymbol; + var deferredGlobalAwaitedSymbol; + var deferredGlobalBigIntType; + var deferredGlobalNaNSymbol; + var deferredGlobalRecordSymbol; + var deferredGlobalClassDecoratorContextType; + var deferredGlobalClassMethodDecoratorContextType; + var deferredGlobalClassGetterDecoratorContextType; + var deferredGlobalClassSetterDecoratorContextType; + var deferredGlobalClassAccessorDecoratorContextType; + var deferredGlobalClassAccessorDecoratorTargetType; + var deferredGlobalClassAccessorDecoratorResultType; + var deferredGlobalClassFieldDecoratorContextType; + var allPotentiallyUnusedIdentifiers = /* @__PURE__ */ new Map(); + var flowLoopStart = 0; + var flowLoopCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; + var flowInvocationCount = 0; + var lastFlowNode; + var lastFlowNodeReachable; + var flowTypeCache; + var contextualTypeNodes = []; + var contextualTypes = []; + var contextualIsCache = []; + var contextualTypeCount = 0; + var contextualBindingPatterns = []; + var inferenceContextNodes = []; + var inferenceContexts = []; + var inferenceContextCount = 0; + var emptyStringType = getStringLiteralType(""); + var zeroType = getNumberLiteralType(0); + var zeroBigIntType = getBigIntLiteralType({ negative: false, base10Value: "0" }); + var resolutionTargets = []; + var resolutionResults = []; + var resolutionPropertyNames = []; + var resolutionStart = 0; + var inVarianceComputation = false; + var suggestionCount = 0; + var maximumSuggestionCount = 10; + var mergedSymbols = []; + var symbolLinks = []; + var nodeLinks = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; + var flowNodeReachable = []; + var flowNodePostSuper = []; + var potentialThisCollisions = []; + var potentialNewTargetCollisions = []; + var potentialWeakMapSetCollisions = []; + var potentialReflectCollisions = []; + var potentialUnusedRenamedBindingElementsInTypes = []; + var awaitedTypeStack = []; + var reverseMappedSourceStack = []; + var reverseMappedTargetStack = []; + var reverseExpandingFlags = 0 /* None */; + var diagnostics = createDiagnosticCollection(); + var suggestionDiagnostics = createDiagnosticCollection(); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var subtypeRelation = /* @__PURE__ */ new Map(); + var strictSubtypeRelation = /* @__PURE__ */ new Map(); + var assignableRelation = /* @__PURE__ */ new Map(); + var comparableRelation = /* @__PURE__ */ new Map(); + var identityRelation = /* @__PURE__ */ new Map(); + var enumRelation = /* @__PURE__ */ new Map(); + var suggestedExtensions = [ + [".mts", ".mjs"], + [".ts", ".js"], + [".cts", ".cjs"], + [".mjs", ".mjs"], + [".js", ".js"], + [".cjs", ".cjs"], + [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"], + [".jsx", ".jsx"], + [".json", ".json"] + ]; + initializeTypeChecker(); + return checker; + function isDefinitelyReferenceToGlobalSymbolObject(node) { + if (!isPropertyAccessExpression(node)) return false; + if (!isIdentifier(node.name)) return false; + if (!isPropertyAccessExpression(node.expression) && !isIdentifier(node.expression)) return false; + if (isIdentifier(node.expression)) { + return idText(node.expression) === "Symbol" && getResolvedSymbol(node.expression) === (getGlobalSymbol( + "Symbol", + 111551 /* Value */ | 1048576 /* ExportValue */, + /*diagnostic*/ + void 0 + ) || unknownSymbol); + } + if (!isIdentifier(node.expression.expression)) return false; + return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && getResolvedSymbol(node.expression.expression) === globalThisSymbol; + } + function getCachedType(key) { + return key ? cachedTypes.get(key) : void 0; + } + function setCachedType(key, type) { + if (key) cachedTypes.set(key, type); + return type; + } + function getJsxNamespace(location) { + if (location) { + const file = getSourceFileOfNode(location); + if (file) { + if (isJsxOpeningFragment(location)) { + if (file.localJsxFragmentNamespace) { + return file.localJsxFragmentNamespace; + } + const jsxFragmentPragma = file.pragmas.get("jsxfrag"); + if (jsxFragmentPragma) { + const chosenPragma = isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma; + file.localJsxFragmentFactory = parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion); + visitNode(file.localJsxFragmentFactory, markAsSynthetic, isEntityName); + if (file.localJsxFragmentFactory) { + return file.localJsxFragmentNamespace = getFirstIdentifier(file.localJsxFragmentFactory).escapedText; + } + } + const entity = getJsxFragmentFactoryEntity(location); + if (entity) { + file.localJsxFragmentFactory = entity; + return file.localJsxFragmentNamespace = getFirstIdentifier(entity).escapedText; + } + } else { + const localJsxNamespace = getLocalJsxNamespace(file); + if (localJsxNamespace) { + return file.localJsxNamespace = localJsxNamespace; + } + } + } + } + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + visitNode(_jsxFactoryEntity, markAsSynthetic); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } else if (compilerOptions.reactNamespace) { + _jsxNamespace = escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + if (!_jsxFactoryEntity) { + _jsxFactoryEntity = factory.createQualifiedName(factory.createIdentifier(unescapeLeadingUnderscores(_jsxNamespace)), "createElement"); + } + return _jsxNamespace; + } + function getLocalJsxNamespace(file) { + if (file.localJsxNamespace) { + return file.localJsxNamespace; + } + const jsxPragma = file.pragmas.get("jsx"); + if (jsxPragma) { + const chosenPragma = isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + file.localJsxFactory = parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion); + visitNode(file.localJsxFactory, markAsSynthetic, isEntityName); + if (file.localJsxFactory) { + return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + } + } + } + function markAsSynthetic(node) { + setTextRangePosEnd(node, -1, -1); + return visitEachChild( + node, + markAsSynthetic, + /*context*/ + void 0 + ); + } + function getEmitResolver(sourceFile, cancellationToken2, skipDiagnostics) { + if (!skipDiagnostics) getDiagnostics(sourceFile, cancellationToken2); + return emitResolver; + } + function lookupOrIssueError(location, message, ...args) { + const diagnostic = location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args); + const existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function errorSkippedOn(key, location, message, ...args) { + const diagnostic = error(location, message, ...args); + diagnostic.skippedOn = key; + return diagnostic; + } + function createError(location, message, ...args) { + return location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args); + } + function error(location, message, ...args) { + const diagnostic = createError(location, message, ...args); + diagnostics.add(diagnostic); + return diagnostic; + } + function addErrorOrSuggestion(isError, diagnostic) { + if (isError) { + diagnostics.add(diagnostic); + } else { + suggestionDiagnostics.add({ ...diagnostic, category: 2 /* Suggestion */ }); + } + } + function errorOrSuggestion(isError, location, message, ...args) { + if (location.pos < 0 || location.end < 0) { + if (!isError) { + return; + } + const file = getSourceFileOfNode(location); + addErrorOrSuggestion(isError, "message" in message ? createFileDiagnostic(file, 0, 0, message, ...args) : createDiagnosticForFileFromMessageChain(file, message)); + return; + } + addErrorOrSuggestion(isError, "message" in message ? createDiagnosticForNode(location, message, ...args) : createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(location), location, message)); + } + function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, ...args) { + const diagnostic = error(location, message, ...args); + if (maybeMissingAwait) { + const related = createDiagnosticForNode(location, Diagnostics.Did_you_forget_to_use_await); + addRelatedInfo(diagnostic, related); + } + return diagnostic; + } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + const deprecatedTag = Array.isArray(declarations) ? forEach(declarations, getJSDocDeprecatedTag) : getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + addRelatedInfo( + diagnostic, + createDiagnosticForNode(deprecatedTag, Diagnostics.The_declaration_was_marked_as_deprecated_here) + ); + } + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function isDeprecatedSymbol(symbol) { + const parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol && length(symbol.declarations) > 1) { + return parentSymbol.flags & 64 /* Interface */ ? some(symbol.declarations, isDeprecatedDeclaration) : every(symbol.declarations, isDeprecatedDeclaration); + } + return !!symbol.valueDeclaration && isDeprecatedDeclaration(symbol.valueDeclaration) || length(symbol.declarations) && every(symbol.declarations, isDeprecatedDeclaration); + } + function isDeprecatedDeclaration(declaration) { + return !!(getCombinedNodeFlagsCached(declaration) & 536870912 /* Deprecated */); + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + const diagnostic = deprecatedEntity ? createDiagnosticForNode(location, Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) : createDiagnosticForNode(location, Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } + function createSymbol(flags, name, checkFlags) { + symbolCount++; + const symbol = new Symbol13(flags | 33554432 /* Transient */, name); + symbol.links = new SymbolLinks(); + symbol.links.checkFlags = checkFlags || 0 /* None */; + return symbol; + } + function createParameter(name, type) { + const symbol = createSymbol(1 /* FunctionScopedVariable */, name); + symbol.links.type = type; + return symbol; + } + function createProperty(name, type) { + const symbol = createSymbol(4 /* Property */, name); + symbol.links.type = type; + return symbol; + } + function getExcludedSymbolFlags(flags) { + let result = 0; + if (flags & 2 /* BlockScopedVariable */) result |= 111551 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) result |= 111550 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) result |= 900095 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) result |= 110991 /* FunctionExcludes */; + if (flags & 32 /* Class */) result |= 899503 /* ClassExcludes */; + if (flags & 64 /* Interface */) result |= 788872 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) result |= 899327 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) result |= 899967 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) result |= 110735 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) result |= 103359 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) result |= 46015 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) result |= 78783 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) result |= 526824 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) result |= 788968 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + const result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; + if (symbol.members) result.members = new Map(symbol.members); + if (symbol.exports) result.exports = new Map(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + function mergeSymbol(target, source, unidirectional = false) { + if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* Assignment */) { + if (source === target) { + return target; + } + if (!(target.flags & 33554432 /* Transient */)) { + const resolvedTarget = resolveSymbol(target); + if (resolvedTarget === unknownSymbol) { + return source; + } + if (!(resolvedTarget.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | resolvedTarget.flags) & 67108864 /* Assignment */) { + target = cloneSymbol(resolvedTarget); + } else { + reportMergeSymbolError(target, source); + return source; + } + } + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration) { + setValueDeclaration(target, source.valueDeclaration); + } + addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) target.members = createSymbolTable(); + mergeSymbolTable(target.members, source.members, unidirectional); + } + if (source.exports) { + if (!target.exports) target.exports = createSymbolTable(); + mergeSymbolTable(target.exports, source.exports, unidirectional, target); + } + if (!unidirectional) { + recordMergedSymbol(target, source); + } + } else if (target.flags & 1024 /* NamespaceModule */) { + if (target !== globalThisSymbol) { + error( + source.declarations && getNameOfDeclaration(source.declarations[0]), + Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, + symbolToString(target) + ); + } + } else { + reportMergeSymbolError(target, source); + } + return target; + function reportMergeSymbolError(target2, source2) { + const isEitherEnum = !!(target2.flags & 384 /* Enum */ || source2.flags & 384 /* Enum */); + const isEitherBlockScoped = !!(target2.flags & 2 /* BlockScopedVariable */ || source2.flags & 2 /* BlockScopedVariable */); + const message = isEitherEnum ? Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations : isEitherBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; + const sourceSymbolFile = source2.declarations && getSourceFileOfNode(source2.declarations[0]); + const targetSymbolFile = target2.declarations && getSourceFileOfNode(target2.declarations[0]); + const isSourcePlainJs = isPlainJsFile(sourceSymbolFile, compilerOptions.checkJs); + const isTargetPlainJs = isPlainJsFile(targetSymbolFile, compilerOptions.checkJs); + const symbolName2 = symbolToString(source2); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + const firstFile = comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + const secondFile = firstFile === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, () => ({ firstFile, secondFile, conflictingSymbols: /* @__PURE__ */ new Map() })); + const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName2, () => ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] })); + if (!isSourcePlainJs) addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source2); + if (!isTargetPlainJs) addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target2); + } else { + if (!isSourcePlainJs) addDuplicateDeclarationErrorsForSymbols(source2, message, symbolName2, target2); + if (!isTargetPlainJs) addDuplicateDeclarationErrorsForSymbols(target2, message, symbolName2, source2); + } + } + function addDuplicateLocations(locs, symbol) { + if (symbol.declarations) { + for (const decl of symbol.declarations) { + pushIfUnique(locs, decl); + } + } + } + } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName2, source) { + forEach(target.declarations, (node) => { + addDuplicateDeclarationError(node, message, symbolName2, source.declarations); + }); + } + function addDuplicateDeclarationError(node, message, symbolName2, relatedNodes) { + const errorNode = (getExpandoInitializer( + node, + /*isPrototypeAssignment*/ + false + ) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; + const err = lookupOrIssueError(errorNode, message, symbolName2); + for (const relatedNode of relatedNodes || emptyArray) { + const adjustedNode = (getExpandoInitializer( + relatedNode, + /*isPrototypeAssignment*/ + false + ) ? getNameOfExpando(relatedNode) : getNameOfDeclaration(relatedNode)) || relatedNode; + if (adjustedNode === errorNode) continue; + err.relatedInformation = err.relatedInformation || []; + const leadingMessage = createDiagnosticForNode(adjustedNode, Diagnostics._0_was_also_declared_here, symbolName2); + const followOnMessage = createDiagnosticForNode(adjustedNode, Diagnostics.and_here); + if (length(err.relatedInformation) >= 5 || some(err.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */)) continue; + addRelatedInfo(err, !length(err.relatedInformation) ? leadingMessage : followOnMessage); + } + } + function combineSymbolTables(first2, second) { + if (!(first2 == null ? void 0 : first2.size)) return second; + if (!(second == null ? void 0 : second.size)) return first2; + const combined = createSymbolTable(); + mergeSymbolTable(combined, first2); + mergeSymbolTable(combined, second); + return combined; + } + function mergeSymbolTable(target, source, unidirectional = false, mergedParent) { + source.forEach((sourceSymbol, id) => { + const targetSymbol = target.get(id); + const merged = targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : getMergedSymbol(sourceSymbol); + if (mergedParent && targetSymbol) { + merged.parent = mergedParent; + } + target.set(id, merged); + }); + } + function mergeModuleAugmentation(moduleName) { + var _a, _b, _c; + const moduleAugmentation = moduleName.parent; + if (((_a = moduleAugmentation.symbol.declarations) == null ? void 0 : _a[0]) !== moduleAugmentation) { + Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } else { + const moduleNotFoundError = !(moduleName.parent.parent.flags & 33554432 /* Ambient */) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : void 0; + let mainModule = resolveExternalModuleNameWorker( + moduleName, + moduleName, + moduleNotFoundError, + /*ignoreErrors*/ + false, + /*isForAugmentation*/ + true + ); + if (!mainModule) { + return; + } + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920 /* Namespace */) { + if (some(patternAmbientModules, (module2) => mainModule === module2.symbol)) { + const merged = mergeSymbol( + moduleAugmentation.symbol, + mainModule, + /*unidirectional*/ + true + ); + if (!patternAmbientModuleAugmentations) { + patternAmbientModuleAugmentations = /* @__PURE__ */ new Map(); + } + patternAmbientModuleAugmentations.set(moduleName.text, merged); + } else { + if (((_b = mainModule.exports) == null ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) == null ? void 0 : _c.size)) { + const resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule, "resolvedExports" /* resolvedExports */); + for (const [key, value] of arrayFrom(moduleAugmentation.symbol.exports.entries())) { + if (resolvedExports.has(key) && !mainModule.exports.has(key)) { + mergeSymbol(resolvedExports.get(key), value); + } + } + } + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + } else { + error(moduleName, Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addUndefinedToGlobalsOrErrorOnRedeclaration() { + const name = undefinedSymbol.escapedName; + const targetSymbol = globals.get(name); + if (targetSymbol) { + forEach(targetSymbol.declarations, (declaration) => { + if (!isTypeDeclaration(declaration)) { + diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name))); + } + }); + } else { + globals.set(name, undefinedSymbol); + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432 /* Transient */) return symbol.links; + const id = getSymbolId(symbol); + return symbolLinks[id] ?? (symbolLinks[id] = new SymbolLinks()); + } + function getNodeLinks(node) { + const nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + const symbol = getMergedSymbol(symbols.get(name)); + if (symbol) { + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152 /* Alias */) { + const targetFlags = getSymbolFlags(symbol); + if (targetFlags & meaning) { + return symbol; + } + } + } + } + } + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + const constructorDeclaration = parameter.parent; + const classDeclaration = parameter.parent.parent; + const parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */); + const propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + return Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + const declarationFile = getSourceFileOfNode(declaration); + const useFile = getSourceFileOfNode(usage); + const declContainer = getEnclosingBlockScopeContainer(declaration); + if (declarationFile !== useFile) { + if (moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator) || !compilerOptions.outFile || isInTypeQuery(usage) || declaration.flags & 33554432 /* Ambient */) { + return true; + } + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + const sourceFiles = host.getSourceFiles(); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); + } + if (!!(usage.flags & 16777216 /* JSDoc */) || isInTypeQuery(usage) || isInAmbientOrTypeNode(usage)) { + return true; + } + if (declaration.pos <= usage.pos && !(isPropertyDeclaration(declaration) && isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { + if (declaration.kind === 208 /* BindingElement */) { + const errorBindingElement = getAncestor(usage, 208 /* BindingElement */); + if (errorBindingElement) { + return findAncestor(errorBindingElement, isBindingElement) !== findAncestor(declaration, isBindingElement) || declaration.pos < errorBindingElement.pos; + } + return isBlockScopedNameDeclaredBeforeUse(getAncestor(declaration, 260 /* VariableDeclaration */), usage); + } else if (declaration.kind === 260 /* VariableDeclaration */) { + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } else if (isClassLike(declaration)) { + const container = findAncestor(usage, (n) => n === declaration ? "quit" : isComputedPropertyName(n) ? n.parent.parent === declaration : !legacyDecorators && isDecorator(n) && (n.parent === declaration || isMethodDeclaration(n.parent) && n.parent.parent === declaration || isGetOrSetAccessorDeclaration(n.parent) && n.parent.parent === declaration || isPropertyDeclaration(n.parent) && n.parent.parent === declaration || isParameter(n.parent) && n.parent.parent.parent === declaration)); + if (!container) { + return true; + } + if (!legacyDecorators && isDecorator(container)) { + return !!findAncestor(usage, (n) => n === container ? "quit" : isFunctionLike(n) && !getImmediatelyInvokedFunctionExpression(n)); + } + return false; + } else if (isPropertyDeclaration(declaration)) { + return !isPropertyImmediatelyReferencedWithinDeclaration( + declaration, + usage, + /*stopAtAnyPropertyDeclaration*/ + false + ); + } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) { + return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); + } + return true; + } + if (usage.parent.kind === 281 /* ExportSpecifier */ || usage.parent.kind === 277 /* ExportAssignment */ && usage.parent.isExportEquals) { + return true; + } + if (usage.kind === 277 /* ExportAssignment */ && usage.isExportEquals) { + return true; + } + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + return !isPropertyImmediatelyReferencedWithinDeclaration( + declaration, + usage, + /*stopAtAnyPropertyDeclaration*/ + true + ); + } else { + return true; + } + } + return false; + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration2, usage2) { + switch (declaration2.parent.parent.kind) { + case 243 /* VariableStatement */: + case 248 /* ForStatement */: + case 250 /* ForOfStatement */: + if (isSameScopeDescendentOf(usage2, declaration2, declContainer)) { + return true; + } + break; + } + const grandparent = declaration2.parent.parent; + return isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage2, grandparent.expression, declContainer); + } + function isUsedInFunctionOrInstanceProperty(usage2, declaration2) { + return !!findAncestor(usage2, (current) => { + if (current === declContainer) { + return "quit"; + } + if (isFunctionLike(current)) { + return true; + } + if (isClassStaticBlockDeclaration(current)) { + return declaration2.pos < usage2.pos; + } + const propertyDeclaration = tryCast(current.parent, isPropertyDeclaration); + if (propertyDeclaration) { + const initializerOfProperty = propertyDeclaration.initializer === current; + if (initializerOfProperty) { + if (isStatic(current.parent)) { + if (declaration2.kind === 174 /* MethodDeclaration */) { + return true; + } + if (isPropertyDeclaration(declaration2) && getContainingClass(usage2) === getContainingClass(declaration2)) { + const propName = declaration2.name; + if (isIdentifier(propName) || isPrivateIdentifier(propName)) { + const type = getTypeOfSymbol(getSymbolOfDeclaration(declaration2)); + const staticBlocks = filter(declaration2.parent.members, isClassStaticBlockDeclaration); + if (isPropertyInitializedInStaticBlocks(propName, type, staticBlocks, declaration2.parent.pos, current.pos)) { + return true; + } + } + } + } else { + const isDeclarationInstanceProperty = declaration2.kind === 172 /* PropertyDeclaration */ && !isStatic(declaration2); + if (!isDeclarationInstanceProperty || getContainingClass(usage2) !== getContainingClass(declaration2)) { + return true; + } + } + } + } + return false; + }); + } + function isPropertyImmediatelyReferencedWithinDeclaration(declaration2, usage2, stopAtAnyPropertyDeclaration) { + if (usage2.end > declaration2.end) { + return false; + } + const ancestorChangingReferenceScope = findAncestor(usage2, (node) => { + if (node === declaration2) { + return "quit"; + } + switch (node.kind) { + case 219 /* ArrowFunction */: + return true; + case 172 /* PropertyDeclaration */: + return stopAtAnyPropertyDeclaration && (isPropertyDeclaration(declaration2) && node.parent === declaration2.parent || isParameterPropertyDeclaration(declaration2, declaration2.parent) && node.parent === declaration2.parent.parent) ? "quit" : true; + case 241 /* Block */: + switch (node.parent.kind) { + case 177 /* GetAccessor */: + case 174 /* MethodDeclaration */: + case 178 /* SetAccessor */: + return true; + default: + return false; + } + default: + return false; + } + }); + return ancestorChangingReferenceScope === void 0; + } + } + function getRequiresScopeChangeCache(node) { + return getNodeLinks(node).declarationRequiresScopeChange; + } + function setRequiresScopeChangeCache(node, value) { + getNodeLinks(node).declarationRequiresScopeChange = value; + } + function checkAndReportErrorForInvalidInitializer(errorLocation, name, propertyWithInvalidInitializer, result) { + if (!emitStandardClassFields) { + if (errorLocation && !result && checkAndReportErrorForMissingPrefix(errorLocation, name, name)) { + return true; + } + error( + errorLocation, + errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, + declarationNameToString(propertyWithInvalidInitializer.name), + diagnosticName(name) + ); + return true; + } + return false; + } + function onFailedToResolveSymbol(errorLocation, nameArg, meaning, nameNotFoundMessage) { + const name = isString(nameArg) ? nameArg : nameArg.escapedText; + addLazyDiagnostic(() => { + if (!errorLocation || errorLocation.parent.kind !== 324 /* JSDocLink */ && !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { + let suggestion; + let suggestedLib; + if (nameArg) { + suggestedLib = getSuggestedLibForNonExistentName(nameArg); + if (suggestedLib) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); + } + } + if (!suggestedLib && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestedSymbolForNonexistentSymbol(errorLocation, name, meaning); + const isGlobalScopeAugmentationDeclaration = (suggestion == null ? void 0 : suggestion.valueDeclaration) && isAmbientModule(suggestion.valueDeclaration) && isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = void 0; + } + if (suggestion) { + const suggestionName = symbolToString(suggestion); + const isUncheckedJS = isUncheckedJSSuggestion( + errorLocation, + suggestion, + /*excludeClasses*/ + false + ); + const message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && nodeIsSynthesized(nameArg) ? Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 : isUncheckedJS ? Diagnostics.Could_not_find_name_0_Did_you_mean_1 : Diagnostics.Cannot_find_name_0_Did_you_mean_1; + const diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName); + diagnostic.canonicalHead = getCanonicalDiagnostic(nameNotFoundMessage, diagnosticName(nameArg)); + addErrorOrSuggestion(!isUncheckedJS, diagnostic); + if (suggestion.valueDeclaration) { + addRelatedInfo( + diagnostic, + createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName) + ); + } + } + } + if (!suggestion && !suggestedLib && nameArg) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + }); + } + function onSuccessfullyResolvedSymbol(errorLocation, result, meaning, lastLocation, associatedDeclarationForContainingInitializerOrBindingName, withinDeferredContext) { + addLazyDiagnostic(() => { + var _a; + const name = result.escapedName; + const isInExternalModule = lastLocation && isSourceFile(lastLocation) && isExternalOrCommonJsModule(lastLocation); + if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || (meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */)) { + const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + if (isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(errorLocation.flags & 16777216 /* JSDoc */)) { + const merged = getMergedSymbol(result); + if (length(merged.declarations) && every(merged.declarations, (d) => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) { + errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); + } + } + if (associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { + const candidate = getMergedSymbol(getLateBoundSymbol(result)); + const root = getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName); + if (candidate === getSymbolOfDeclaration(associatedDeclarationForContainingInitializerOrBindingName)) { + error(errorLocation, Diagnostics.Parameter_0_cannot_reference_itself, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); + } else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && getSymbol(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation)); + } + } + if (errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */ && !(result.flags & 111551 /* Value */) && !isValidTypeOnlyAliasUseSite(errorLocation)) { + const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* Value */); + if (typeOnlyDeclaration) { + const message = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type : Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; + const unescapedName = unescapeLeadingUnderscores(name); + addTypeOnlyDeclarationRelatedInfo( + error(errorLocation, message, unescapedName), + typeOnlyDeclaration, + unescapedName + ); + } + } + if (compilerOptions.isolatedModules && result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */) { + const isGlobal = getSymbol(globals, name, meaning) === result; + const nonValueSymbol = isGlobal && isSourceFile(lastLocation) && lastLocation.locals && getSymbol(lastLocation.locals, name, ~111551 /* Value */); + if (nonValueSymbol) { + const importDecl = (_a = nonValueSymbol.declarations) == null ? void 0 : _a.find((d) => d.kind === 276 /* ImportSpecifier */ || d.kind === 273 /* ImportClause */ || d.kind === 274 /* NamespaceImport */ || d.kind === 271 /* ImportEqualsDeclaration */); + if (importDecl && !isTypeOnlyImportDeclaration(importDecl)) { + error(importDecl, Diagnostics.Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled, unescapeLeadingUnderscores(name)); + } + } + } + }); + } + function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) { + if (!typeOnlyDeclaration) return diagnostic; + return addRelatedInfo( + diagnostic, + createDiagnosticForNode( + typeOnlyDeclaration, + typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here, + unescapedName + ) + ); + } + function diagnosticName(nameArg) { + return isString(nameArg) ? unescapeLeadingUnderscores(nameArg) : declarationNameToString(nameArg); + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { + return false; + } + const container = getThisContainer( + errorLocation, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + let location = container; + while (location) { + if (isClassLike(location.parent)) { + const classSymbol = getSymbolOfDeclaration(location.parent); + if (!classSymbol) { + break; + } + const constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + if (location === container && !isStatic(location)) { + const instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + const expression = getEntityNameForExtendingInterface(errorLocation); + if (expression && resolveEntityName( + expression, + 64 /* Interface */, + /*ignoreErrors*/ + true + )) { + error(errorLocation, Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, getTextOfNode(expression)); + return true; + } + return false; + } + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 80 /* Identifier */: + case 211 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : void 0; + case 233 /* ExpressionWithTypeArguments */: + if (isEntityNameExpression(node.expression)) { + return node.expression; + } + // falls through + default: + return void 0; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + const namespaceMeaning = 1920 /* Namespace */ | (isInJSFile(errorLocation) ? 111551 /* Value */ : 0); + if (meaning === namespaceMeaning) { + const symbol = resolveSymbol(resolveName( + errorLocation, + name, + 788968 /* Type */ & ~namespaceMeaning, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + )); + const parent = errorLocation.parent; + if (symbol) { + if (isQualifiedName(parent)) { + Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + const propName = parent.right.escapedText; + const propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error( + parent, + Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, + unescapeLeadingUnderscores(name), + unescapeLeadingUnderscores(propName) + ); + return true; + } + } + error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) { + if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) { + const symbol = resolveSymbol(resolveName( + errorLocation, + name, + ~788968 /* Type */ & 111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + )); + if (symbol && !(symbol.flags & 1920 /* Namespace */)) { + error(errorLocation, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function isPrimitiveTypeName(name) { + return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown"; + } + function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) { + if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 281 /* ExportSpecifier */) { + error(errorLocation, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); + return true; + } + return false; + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { + if (meaning & 111551 /* Value */) { + if (isPrimitiveTypeName(name)) { + const grandparent = errorLocation.parent.parent; + if (grandparent && grandparent.parent && isHeritageClause(grandparent)) { + const heritageKind = grandparent.token; + const containerKind = grandparent.parent.kind; + if (containerKind === 264 /* InterfaceDeclaration */ && heritageKind === 96 /* ExtendsKeyword */) { + error(errorLocation, Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types, unescapeLeadingUnderscores(name)); + } else if (isClassLike(grandparent.parent) && heritageKind === 96 /* ExtendsKeyword */) { + error(errorLocation, Diagnostics.A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values, unescapeLeadingUnderscores(name)); + } else if (isClassLike(grandparent.parent) && heritageKind === 119 /* ImplementsKeyword */) { + error(errorLocation, Diagnostics.A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types, unescapeLeadingUnderscores(name)); + } + } else { + error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name)); + } + return true; + } + const symbol = resolveSymbol(resolveName( + errorLocation, + name, + 788968 /* Type */ & ~111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + )); + const allFlags = symbol && getSymbolFlags(symbol); + if (symbol && allFlags !== void 0 && !(allFlags & 111551 /* Value */)) { + const rawName = unescapeLeadingUnderscores(name); + if (isES2015OrLaterConstructorName(name)) { + error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); + } else if (maybeMappedType(errorLocation, symbol)) { + error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0, rawName, rawName === "K" ? "P" : "K"); + } else { + error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName); + } + return true; + } + } + return false; + } + function maybeMappedType(node, symbol) { + const container = findAncestor(node.parent, (n) => isComputedPropertyName(n) || isPropertySignature(n) ? false : isTypeLiteralNode(n) || "quit"); + if (container && container.members.length === 1) { + const type = getDeclaredTypeOfSymbol(symbol); + return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind( + type, + 384 /* StringOrNumberLiteral */, + /*strict*/ + true + ); + } + return false; + } + function isES2015OrLaterConstructorName(n) { + switch (n) { + case "Promise": + case "Symbol": + case "Map": + case "WeakMap": + case "Set": + case "WeakSet": + return true; + } + return false; + } + function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) { + if (meaning & (111551 /* Value */ & ~788968 /* Type */)) { + const symbol = resolveSymbol(resolveName( + errorLocation, + name, + 1024 /* NamespaceModule */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + )); + if (symbol) { + error( + errorLocation, + Diagnostics.Cannot_use_namespace_0_as_a_value, + unescapeLeadingUnderscores(name) + ); + return true; + } + } else if (meaning & (788968 /* Type */ & ~111551 /* Value */)) { + const symbol = resolveSymbol(resolveName( + errorLocation, + name, + 1536 /* Module */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + )); + if (symbol) { + error(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_type, unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + var _a; + Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); + if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) { + return; + } + const declaration = (_a = result.declarations) == null ? void 0 : _a.find( + (d) => isBlockOrCatchScoped(d) || isClassLike(d) || d.kind === 266 /* EnumDeclaration */ + ); + if (declaration === void 0) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); + if (!(declaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + let diagnosticMessage; + const declarationName = declarationNameToString(getNameOfDeclaration(declaration)); + if (result.flags & 2 /* BlockScopedVariable */) { + diagnosticMessage = error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); + } else if (result.flags & 32 /* Class */) { + diagnosticMessage = error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationName); + } else if (result.flags & 256 /* RegularEnum */) { + diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } else { + Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (getIsolatedModules(compilerOptions)) { + diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, createDiagnosticForNode(declaration, Diagnostics._0_is_declared_here, declarationName)); + } + } + } + function isSameScopeDescendentOf(initial, parent, stopAt) { + return !!parent && !!findAncestor(initial, (n) => n === parent || (n === stopAt || isFunctionLike(n) && (!getImmediatelyInvokedFunctionExpression(n) || getFunctionFlags(n) & 3 /* AsyncGenerator */) ? "quit" : false)); + } + function getAnyImportSyntax(node) { + switch (node.kind) { + case 271 /* ImportEqualsDeclaration */: + return node; + case 273 /* ImportClause */: + return node.parent; + case 274 /* NamespaceImport */: + return node.parent.parent; + case 276 /* ImportSpecifier */: + return node.parent.parent.parent; + default: + return void 0; + } + } + function getDeclarationOfAliasSymbol(symbol) { + return symbol.declarations && findLast(symbol.declarations, isAliasSymbolDeclaration); + } + function isAliasSymbolDeclaration(node) { + return node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 270 /* NamespaceExportDeclaration */ || node.kind === 273 /* ImportClause */ && !!node.name || node.kind === 274 /* NamespaceImport */ || node.kind === 280 /* NamespaceExport */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 281 /* ExportSpecifier */ || node.kind === 277 /* ExportAssignment */ && exportAssignmentIsAlias(node) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || isAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) || node.kind === 304 /* ShorthandPropertyAssignment */ || node.kind === 303 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) || node.kind === 260 /* VariableDeclaration */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node) || node.kind === 208 /* BindingElement */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); + } + function isAliasableOrJsExpression(e) { + return isAliasableExpression(e) || isFunctionExpression(e) && isJSConstructor(e); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + const commonJSPropertyAccess = getCommonJSPropertyAccess(node); + if (commonJSPropertyAccess) { + const name = getLeftmostAccessExpression(commonJSPropertyAccess.expression).arguments[0]; + return isIdentifier(commonJSPropertyAccess.name) ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : void 0; + } + if (isVariableDeclaration(node) || node.moduleReference.kind === 283 /* ExternalModuleReference */) { + const immediate = resolveExternalModuleName( + node, + getExternalModuleRequireArgument(node) || getExternalModuleImportEqualsDeclarationExpression(node) + ); + const resolved2 = resolveExternalModuleSymbol(immediate); + markSymbolOfAliasDeclarationIfTypeOnly( + node, + immediate, + resolved2, + /*overwriteEmpty*/ + false + ); + return resolved2; + } + const resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved); + return resolved; + } + function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) { + if (markSymbolOfAliasDeclarationIfTypeOnly( + node, + /*immediateTarget*/ + void 0, + resolved, + /*overwriteEmpty*/ + false + ) && !node.isTypeOnly) { + const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfDeclaration(node)); + const isExport = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */; + const message = isExport ? Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type : Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type; + const relatedMessage = isExport ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here; + const name = typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? "*" : moduleExportNameTextUnescaped(typeOnlyDeclaration.name); + addRelatedInfo(error(node.moduleReference, message), createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name)); + } + } + function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) { + const exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + const exportSymbol = exportValue ? getPropertyOfType( + getTypeOfSymbol(exportValue), + name, + /*skipObjectFunctionPropertyAugment*/ + true + ) : moduleSymbol.exports.get(name); + const resolved = resolveSymbol(exportSymbol, dontResolveAlias); + markSymbolOfAliasDeclarationIfTypeOnly( + sourceNode, + exportSymbol, + resolved, + /*overwriteEmpty*/ + false + ); + return resolved; + } + function isSyntacticDefault(node) { + return isExportAssignment(node) && !node.isExportEquals || hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) || isNamespaceExport(node); + } + function getEmitSyntaxForModuleSpecifierExpression(usage) { + return isStringLiteralLike(usage) ? host.getEmitSyntaxForUsageLocation(getSourceFileOfNode(usage), usage) : void 0; + } + function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { + return usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */; + } + function isOnlyImportableAsDefault(usage, resolvedModule) { + if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { + const usageMode = getEmitSyntaxForModuleSpecifierExpression(usage); + if (usageMode === 99 /* ESNext */) { + resolvedModule ?? (resolvedModule = resolveExternalModuleName( + usage, + usage, + /*ignoreErrors*/ + true + )); + const targetFile = resolvedModule && getSourceFileOfModule(resolvedModule); + return targetFile && (isJsonSourceFile(targetFile) || getDeclarationFileExtension(targetFile.fileName) === ".d.json.ts"); + } + } + return false; + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) { + const usageMode = file && getEmitSyntaxForModuleSpecifierExpression(usage); + if (file && usageMode !== void 0) { + const targetMode = host.getImpliedNodeFormatForEmit(file); + if (usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */ && 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { + return true; + } + if (usageMode === 99 /* ESNext */ && targetMode === 99 /* ESNext */) { + return false; + } + } + if (!allowSyntheticDefaultImports) { + return false; + } + if (!file || file.isDeclarationFile) { + const defaultExportSymbol = resolveExportByName( + moduleSymbol, + "default" /* Default */, + /*sourceNode*/ + void 0, + /*dontResolveAlias*/ + true + ); + if (defaultExportSymbol && some(defaultExportSymbol.declarations, isSyntacticDefault)) { + return false; + } + if (resolveExportByName( + moduleSymbol, + escapeLeadingUnderscores("__esModule"), + /*sourceNode*/ + void 0, + dontResolveAlias + )) { + return false; + } + return true; + } + if (!isSourceFileJS(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + return typeof file.externalModuleIndicator !== "object" && !resolveExportByName( + moduleSymbol, + escapeLeadingUnderscores("__esModule"), + /*sourceNode*/ + void 0, + dontResolveAlias + ); + } + function getTargetOfImportClause(node, dontResolveAlias) { + const moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias); + } + } + function getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias) { + var _a; + let exportDefaultSymbol; + if (isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } else { + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); + } + const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); + const specifier = getModuleSpecifierForImportOrExport(node); + if (!specifier) { + return exportDefaultSymbol; + } + const hasDefaultOnly = isOnlyImportableAsDefault(specifier, moduleSymbol); + const hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, specifier); + if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { + if (hasExportAssignmentSymbol(moduleSymbol) && !allowSyntheticDefaultImports) { + const compilerOptionName = moduleKind >= 5 /* ES2015 */ ? "allowSyntheticDefaultImports" : "esModuleInterop"; + const exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); + const exportAssignment = exportEqualsSymbol.valueDeclaration; + const err = error(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); + if (exportAssignment) { + addRelatedInfo( + err, + createDiagnosticForNode( + exportAssignment, + Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, + compilerOptionName + ) + ); + } + } else if (isImportClause(node)) { + reportNonDefaultExport(moduleSymbol, node); + } else { + errorNoModuleMemberSymbol(moduleSymbol, moduleSymbol, node, isImportOrExportSpecifier(node) && node.propertyName || node.name); + } + } else if (hasSyntheticDefault || hasDefaultOnly) { + const resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + markSymbolOfAliasDeclarationIfTypeOnly( + node, + moduleSymbol, + resolved, + /*overwriteEmpty*/ + false + ); + return resolved; + } + markSymbolOfAliasDeclarationIfTypeOnly( + node, + exportDefaultSymbol, + /*finalTarget*/ + void 0, + /*overwriteEmpty*/ + false + ); + return exportDefaultSymbol; + } + function getModuleSpecifierForImportOrExport(node) { + switch (node.kind) { + case 273 /* ImportClause */: + return node.parent.moduleSpecifier; + case 271 /* ImportEqualsDeclaration */: + return isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : void 0; + case 274 /* NamespaceImport */: + return node.parent.parent.moduleSpecifier; + case 276 /* ImportSpecifier */: + return node.parent.parent.parent.moduleSpecifier; + case 281 /* ExportSpecifier */: + return node.parent.parent.moduleSpecifier; + default: + return Debug.assertNever(node); + } + } + function reportNonDefaultExport(moduleSymbol, node) { + var _a, _b, _c; + if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has(node.symbol.escapedName)) { + error( + node.name, + Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, + symbolToString(moduleSymbol), + symbolToString(node.symbol) + ); + } else { + const diagnostic = error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + const exportStar = (_b = moduleSymbol.exports) == null ? void 0 : _b.get("__export" /* ExportStar */); + if (exportStar) { + const defaultExport = (_c = exportStar.declarations) == null ? void 0 : _c.find( + (decl) => { + var _a2, _b2; + return !!(isExportDeclaration(decl) && decl.moduleSpecifier && ((_b2 = (_a2 = resolveExternalModuleName(decl, decl.moduleSpecifier)) == null ? void 0 : _a2.exports) == null ? void 0 : _b2.has("default" /* Default */))); + } + ); + if (defaultExport) { + addRelatedInfo(diagnostic, createDiagnosticForNode(defaultExport, Diagnostics.export_Asterisk_does_not_re_export_a_default)); + } + } + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + const moduleSpecifier = node.parent.parent.moduleSpecifier; + const immediate = resolveExternalModuleName(node, moduleSpecifier); + const resolved = resolveESModuleSymbol( + immediate, + moduleSpecifier, + dontResolveAlias, + /*suppressInteropError*/ + false + ); + markSymbolOfAliasDeclarationIfTypeOnly( + node, + immediate, + resolved, + /*overwriteEmpty*/ + false + ); + return resolved; + } + function getTargetOfNamespaceExport(node, dontResolveAlias) { + const moduleSpecifier = node.parent.moduleSpecifier; + const immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier); + const resolved = moduleSpecifier && resolveESModuleSymbol( + immediate, + moduleSpecifier, + dontResolveAlias, + /*suppressInteropError*/ + false + ); + markSymbolOfAliasDeclarationIfTypeOnly( + node, + immediate, + resolved, + /*overwriteEmpty*/ + false + ); + return resolved; + } + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) { + return valueSymbol; + } + const result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + Debug.assert(valueSymbol.declarations || typeSymbol.declarations); + result.declarations = deduplicate(concatenate(valueSymbol.declarations, typeSymbol.declarations), equateValues); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) result.members = new Map(typeSymbol.members); + if (valueSymbol.exports) result.exports = new Map(valueSymbol.exports); + return result; + } + function getExportOfModule(symbol, nameText, specifier, dontResolveAlias) { + var _a; + if (symbol.flags & 1536 /* Module */) { + const exportSymbol = getExportsOfSymbol(symbol).get(nameText); + const resolved = resolveSymbol(exportSymbol, dontResolveAlias); + const exportStarDeclaration = (_a = getSymbolLinks(symbol).typeOnlyExportStarMap) == null ? void 0 : _a.get(nameText); + markSymbolOfAliasDeclarationIfTypeOnly( + specifier, + exportSymbol, + resolved, + /*overwriteEmpty*/ + false, + exportStarDeclaration, + nameText + ); + return resolved; + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3 /* Variable */) { + const typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias = false) { + var _a; + const moduleSpecifier = getExternalModuleRequireArgument(node) || node.moduleSpecifier; + const moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); + const name = !isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name; + if (!isIdentifier(name) && name.kind !== 11 /* StringLiteral */) { + return void 0; + } + const nameText = moduleExportNameTextEscaped(name); + const suppressInteropError = nameText === "default" /* Default */ && allowSyntheticDefaultImports; + const targetSymbol = resolveESModuleSymbol( + moduleSymbol, + moduleSpecifier, + /*dontResolveAlias*/ + false, + suppressInteropError + ); + if (targetSymbol) { + if (nameText || name.kind === 11 /* StringLiteral */) { + if (isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + let symbolFromVariable; + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { + symbolFromVariable = getPropertyOfType( + getTypeOfSymbol(targetSymbol), + nameText, + /*skipObjectFunctionPropertyAugment*/ + true + ); + } else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, nameText); + } + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + let symbolFromModule = getExportOfModule(targetSymbol, nameText, specifier, dontResolveAlias); + if (symbolFromModule === void 0 && nameText === "default" /* Default */) { + const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); + if (isOnlyImportableAsDefault(moduleSpecifier, moduleSymbol) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + } + const symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; + if (isImportOrExportSpecifier(specifier) && isOnlyImportableAsDefault(moduleSpecifier, moduleSymbol) && nameText !== "default" /* Default */) { + error(name, Diagnostics.Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0, ModuleKind[moduleKind]); + } else if (!symbol) { + errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name); + } + return symbol; + } + } + } + function errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name) { + var _a; + const moduleName = getFullyQualifiedName(moduleSymbol, node); + const declarationName = declarationNameToString(name); + const suggestion = isIdentifier(name) ? getSuggestedSymbolForNonexistentModule(name, targetSymbol) : void 0; + if (suggestion !== void 0) { + const suggestionName = symbolToString(suggestion); + const diagnostic = error(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName)); + } + } else { + if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has("default" /* Default */)) { + error( + name, + Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, + moduleName, + declarationName + ); + } else { + reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); + } + } + } + function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { + var _a, _b; + const localSymbol = (_b = (_a = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(moduleExportNameTextEscaped(name)); + const exports2 = moduleSymbol.exports; + if (localSymbol) { + const exportedEqualsSymbol = exports2 == null ? void 0 : exports2.get("export=" /* ExportEquals */); + if (exportedEqualsSymbol) { + getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } else { + const exportedSymbol = exports2 ? find(symbolsToArray(exports2), (symbol) => !!getSymbolIfSameReference(symbol, localSymbol)) : void 0; + const diagnostic = exportedSymbol ? error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); + if (localSymbol.declarations) { + addRelatedInfo(diagnostic, ...map(localSymbol.declarations, (decl, index) => createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName))); + } + } + } else { + error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + } + function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) { + if (moduleKind >= 5 /* ES2015 */) { + const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } else { + if (isInJSFile(node)) { + const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } else { + const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName, declarationName, moduleName); + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + if (isImportSpecifier(node) && moduleExportNameIsDefault(node.propertyName || node.name)) { + const specifier = getModuleSpecifierForImportOrExport(node); + const moduleSymbol = specifier && resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias); + } + } + const root = isBindingElement(node) ? getRootDeclaration(node) : node.parent.parent.parent; + const commonJSPropertyAccess = getCommonJSPropertyAccess(root); + const resolved = getExternalModuleMember(root, commonJSPropertyAccess || node, dontResolveAlias); + const name = node.propertyName || node.name; + if (commonJSPropertyAccess && resolved && isIdentifier(name)) { + return resolveSymbol(getPropertyOfType(getTypeOfSymbol(resolved), name.escapedText), dontResolveAlias); + } + markSymbolOfAliasDeclarationIfTypeOnly( + node, + /*immediateTarget*/ + void 0, + resolved, + /*overwriteEmpty*/ + false + ); + return resolved; + } + function getCommonJSPropertyAccess(node) { + if (isVariableDeclaration(node) && node.initializer && isPropertyAccessExpression(node.initializer)) { + return node.initializer; + } + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + if (canHaveSymbol(node.parent)) { + const resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + markSymbolOfAliasDeclarationIfTypeOnly( + node, + /*immediateTarget*/ + void 0, + resolved, + /*overwriteEmpty*/ + false + ); + return resolved; + } + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + const name = node.propertyName || node.name; + if (moduleExportNameIsDefault(name)) { + const specifier = getModuleSpecifierForImportOrExport(node); + const moduleSymbol = specifier && resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + return getTargetofModuleDefault(moduleSymbol, node, !!dontResolveAlias); + } + } + const resolved = node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : name.kind === 11 /* StringLiteral */ ? void 0 : ( + // Skip for invalid syntax like this: export { "x" } + resolveEntityName( + name, + meaning, + /*ignoreErrors*/ + false, + dontResolveAlias + ) + ); + markSymbolOfAliasDeclarationIfTypeOnly( + node, + /*immediateTarget*/ + void 0, + resolved, + /*overwriteEmpty*/ + false + ); + return resolved; + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + const expression = isExportAssignment(node) ? node.expression : node.right; + const resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias); + markSymbolOfAliasDeclarationIfTypeOnly( + node, + /*immediateTarget*/ + void 0, + resolved, + /*overwriteEmpty*/ + false + ); + return resolved; + } + function getTargetOfAliasLikeExpression(expression, dontResolveAlias) { + if (isClassExpression(expression)) { + return checkExpressionCached(expression).symbol; + } + if (!isEntityName(expression) && !isEntityNameExpression(expression)) { + return void 0; + } + const aliasLike = resolveEntityName( + expression, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, + /*ignoreErrors*/ + true, + dontResolveAlias + ); + if (aliasLike) { + return aliasLike; + } + checkExpressionCached(expression); + return getNodeLinks(expression).resolvedSymbol; + } + function getTargetOfAccessExpression(node, dontRecursivelyResolve) { + if (!(isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */)) { + return void 0; + } + return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve); + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve = false) { + switch (node.kind) { + case 271 /* ImportEqualsDeclaration */: + case 260 /* VariableDeclaration */: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 273 /* ImportClause */: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 274 /* NamespaceImport */: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 280 /* NamespaceExport */: + return getTargetOfNamespaceExport(node, dontRecursivelyResolve); + case 276 /* ImportSpecifier */: + case 208 /* BindingElement */: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 281 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 277 /* ExportAssignment */: + case 226 /* BinaryExpression */: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 270 /* NamespaceExportDeclaration */: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + case 304 /* ShorthandPropertyAssignment */: + return resolveEntityName( + node.name, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, + /*ignoreErrors*/ + true, + dontRecursivelyResolve + ); + case 303 /* PropertyAssignment */: + return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); + case 212 /* ElementAccessExpression */: + case 211 /* PropertyAccessExpression */: + return getTargetOfAccessExpression(node, dontRecursivelyResolve); + default: + return Debug.fail(); + } + } + function isNonLocalAlias(symbol, excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */) { + if (!symbol) return false; + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); + } + function resolveSymbol(symbol, dontResolveAlias) { + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + const links = getSymbolLinks(symbol); + if (!links.aliasTarget) { + links.aliasTarget = resolvingSymbol; + const node = getDeclarationOfAliasSymbol(symbol); + if (!node) return Debug.fail(); + const target = getTargetOfAliasDeclaration(node); + if (links.aliasTarget === resolvingSymbol) { + links.aliasTarget = target || unknownSymbol; + } else { + error(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } else if (links.aliasTarget === resolvingSymbol) { + links.aliasTarget = unknownSymbol; + } + return links.aliasTarget; + } + function tryResolveAlias(symbol) { + const links = getSymbolLinks(symbol); + if (links.aliasTarget !== resolvingSymbol) { + return resolveAlias(symbol); + } + return void 0; + } + function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) { + const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol); + const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration); + const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName( + typeOnlyDeclaration.moduleSpecifier, + typeOnlyDeclaration.moduleSpecifier, + /*ignoreErrors*/ + true + ) : resolveAlias(typeOnlyDeclaration.symbol)); + const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0; + let flags = excludeLocalMeanings ? 0 /* None */ : symbol.flags; + let seenSymbols; + while (symbol.flags & 2097152 /* Alias */) { + const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); + if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || (typeOnlyExportStarTargets == null ? void 0 : typeOnlyExportStarTargets.get(target.escapedName)) === target) { + break; + } + if (target === unknownSymbol) { + return -1 /* All */; + } + if (target === symbol || (seenSymbols == null ? void 0 : seenSymbols.has(target))) { + break; + } + if (target.flags & 2097152 /* Alias */) { + if (seenSymbols) { + seenSymbols.add(target); + } else { + seenSymbols = /* @__PURE__ */ new Set([symbol, target]); + } + } + flags |= target.flags; + symbol = target; + } + return flags; + } + function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty, exportStarDeclaration, exportStarName) { + if (!aliasDeclaration || isPropertyAccessExpression(aliasDeclaration)) return false; + const sourceSymbol = getSymbolOfDeclaration(aliasDeclaration); + if (isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) { + const links2 = getSymbolLinks(sourceSymbol); + links2.typeOnlyDeclaration = aliasDeclaration; + return true; + } + if (exportStarDeclaration) { + const links2 = getSymbolLinks(sourceSymbol); + links2.typeOnlyDeclaration = exportStarDeclaration; + if (sourceSymbol.escapedName !== exportStarName) { + links2.typeOnlyExportStarName = exportStarName; + } + return true; + } + const links = getSymbolLinks(sourceSymbol); + return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty) || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty); + } + function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) { + var _a; + if (target && (aliasDeclarationLinks.typeOnlyDeclaration === void 0 || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) { + const exportSymbol = ((_a = target.exports) == null ? void 0 : _a.get("export=" /* ExportEquals */)) ?? target; + const typeOnly = exportSymbol.declarations && find(exportSymbol.declarations, isTypeOnlyImportOrExportDeclaration); + aliasDeclarationLinks.typeOnlyDeclaration = typeOnly ?? getSymbolLinks(exportSymbol).typeOnlyDeclaration ?? false; + } + return !!aliasDeclarationLinks.typeOnlyDeclaration; + } + function getTypeOnlyAliasDeclaration(symbol, include) { + var _a; + if (!(symbol.flags & 2097152 /* Alias */)) { + return void 0; + } + const links = getSymbolLinks(symbol); + if (links.typeOnlyDeclaration === void 0) { + links.typeOnlyDeclaration = false; + const resolved = resolveSymbol(symbol); + markSymbolOfAliasDeclarationIfTypeOnly( + (_a = symbol.declarations) == null ? void 0 : _a[0], + getDeclarationOfAliasSymbol(symbol) && getImmediateAliasedSymbol(symbol), + resolved, + /*overwriteEmpty*/ + true + ); + } + if (include === void 0) { + return links.typeOnlyDeclaration || void 0; + } + if (links.typeOnlyDeclaration) { + const resolved = links.typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol); + return getSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0; + } + return void 0; + } + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + if (entityName.kind === 80 /* Identifier */ && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (entityName.kind === 80 /* Identifier */ || entityName.parent.kind === 166 /* QualifiedName */) { + return resolveEntityName( + entityName, + 1920 /* Namespace */, + /*ignoreErrors*/ + false, + dontResolveAlias + ); + } else { + Debug.assert(entityName.parent.kind === 271 /* ImportEqualsDeclaration */); + return resolveEntityName( + entityName, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, + /*ignoreErrors*/ + false, + dontResolveAlias + ); + } + } + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString( + symbol, + containingLocation, + /*meaning*/ + void 0, + 32 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */ + ); + } + function getContainingQualifiedNameNode(node) { + while (isQualifiedName(node.parent)) { + node = node.parent; + } + return node; + } + function tryGetQualifiedNameAsValue(node) { + let left = getFirstIdentifier(node); + let symbol = resolveName( + left, + left, + 111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (!symbol) { + return void 0; + } + while (isQualifiedName(left.parent)) { + const type = getTypeOfSymbol(symbol); + symbol = getPropertyOfType(type, left.parent.right.escapedText); + if (!symbol) { + return void 0; + } + left = left.parent; + } + return symbol; + } + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (nodeIsMissing(name)) { + return void 0; + } + const namespaceMeaning = 1920 /* Namespace */ | (isInJSFile(name) ? meaning & 111551 /* Value */ : 0); + let symbol; + if (name.kind === 80 /* Identifier */) { + const message = meaning === namespaceMeaning || nodeIsSynthesized(name) ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + const symbolFromJSPrototype = isInJSFile(name) && !nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : void 0; + symbol = getMergedSymbol(resolveName( + location || name, + name, + meaning, + ignoreErrors || symbolFromJSPrototype ? void 0 : message, + /*isUse*/ + true, + /*excludeGlobals*/ + false + )); + if (!symbol) { + return getMergedSymbol(symbolFromJSPrototype); + } + } else if (name.kind === 166 /* QualifiedName */ || name.kind === 211 /* PropertyAccessExpression */) { + const left = name.kind === 166 /* QualifiedName */ ? name.left : name.expression; + const right = name.kind === 166 /* QualifiedName */ ? name.right : name.name; + let namespace = resolveEntityName( + left, + namespaceMeaning, + ignoreErrors, + /*dontResolveAlias*/ + false, + location + ); + if (!namespace || nodeIsMissing(right)) { + return void 0; + } else if (namespace === unknownSymbol) { + return namespace; + } + if (namespace.valueDeclaration && isInJSFile(namespace.valueDeclaration) && getEmitModuleResolutionKind(compilerOptions) !== 100 /* Bundler */ && isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && isCommonJsRequire(namespace.valueDeclaration.initializer)) { + const moduleName = namespace.valueDeclaration.initializer.arguments[0]; + const moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; + } + } + } + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning)); + if (!symbol && namespace.flags & 2097152 /* Alias */) { + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(resolveAlias(namespace)), right.escapedText, meaning)); + } + if (!symbol) { + if (!ignoreErrors) { + const namespaceName = getFullyQualifiedName(namespace); + const declarationName = declarationNameToString(right); + const suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace); + if (suggestionForNonexistentModule) { + error(right, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule)); + return void 0; + } + const containingQualifiedName = isQualifiedName(name) && getContainingQualifiedNameNode(name); + const canSuggestTypeof = globalObjectType && meaning & 788968 /* Type */ && containingQualifiedName && !isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName); + if (canSuggestTypeof) { + error( + containingQualifiedName, + Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, + entityNameToString(containingQualifiedName) + ); + return void 0; + } + if (meaning & 1920 /* Namespace */ && isQualifiedName(name.parent)) { + const exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); + if (exportedTypeSymbol) { + error( + name.parent.right, + Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, + symbolToString(exportedTypeSymbol), + unescapeLeadingUnderscores(name.parent.right.escapedText) + ); + return void 0; + } + } + error(right, Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); + } + return void 0; + } + } else { + Debug.assertNever(name, "Unknown entity name kind."); + } + if (!nodeIsSynthesized(name) && isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 277 /* ExportAssignment */)) { + markSymbolOfAliasDeclarationIfTypeOnly( + getAliasDeclarationFromName(name), + symbol, + /*finalTarget*/ + void 0, + /*overwriteEmpty*/ + true + ); + } + return symbol.flags & meaning || dontResolveAlias ? symbol : resolveAlias(symbol); + } + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + const secondaryLocation = getAssignmentDeclarationLocation(name.parent); + if (secondaryLocation) { + return resolveName( + secondaryLocation, + name, + meaning, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + } + } + } + function getAssignmentDeclarationLocation(node) { + const typeAlias = findAncestor(node, (node2) => !(isJSDocNode(node2) || node2.flags & 16777216 /* JSDoc */) ? "quit" : isJSDocTypeAlias(node2)); + if (typeAlias) { + return; + } + const host2 = getJSDocHost(node); + if (host2 && isExpressionStatement(host2) && isPrototypePropertyAssignment(host2.expression)) { + const symbol = getSymbolOfDeclaration(host2.expression.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if (host2 && isFunctionExpression(host2) && isPrototypePropertyAssignment(host2.parent) && isExpressionStatement(host2.parent.parent)) { + const symbol = getSymbolOfDeclaration(host2.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if (host2 && (isObjectLiteralMethod(host2) || isPropertyAssignment(host2)) && isBinaryExpression(host2.parent.parent) && getAssignmentDeclarationKind(host2.parent.parent) === 6 /* Prototype */) { + const symbol = getSymbolOfDeclaration(host2.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + const sig = getEffectiveJSDocHost(node); + if (sig && isFunctionLike(sig)) { + const symbol = getSymbolOfDeclaration(sig); + return symbol && symbol.valueDeclaration; + } + } + function getDeclarationOfJSPrototypeContainer(symbol) { + const decl = symbol.parent.valueDeclaration; + if (!decl) { + return void 0; + } + const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : void 0; + return initializer || decl; + } + function getExpandoSymbol(symbol) { + const decl = symbol.valueDeclaration; + if (!decl || !isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || getExpandoInitializer( + decl, + /*isPrototypeAssignment*/ + false + )) { + return void 0; + } + const init = isVariableDeclaration(decl) ? getDeclaredExpandoInitializer(decl) : getAssignedExpandoInitializer(decl); + if (init) { + const initSymbol = getSymbolOfNode(init); + if (initSymbol) { + return mergeJSSymbols(initSymbol, symbol); + } + } + } + function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { + const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */; + const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? void 0 : errorMessage, ignoreErrors); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, ignoreErrors = false, isForAugmentation = false) { + return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, !ignoreErrors ? moduleReferenceExpression : void 0, isForAugmentation) : void 0; + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; + if (errorNode && startsWith(moduleReference, "@types/")) { + const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; + const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); + error(errorNode, diag2, withoutAtTypePrefix, moduleReference); + } + const ambientModule = tryFindAmbientModule( + moduleReference, + /*withAugmentations*/ + true + ); + if (ambientModule) { + return ambientModule; + } + const currentSourceFile = getSourceFileOfNode(location); + const contextSpecifier = isStringLiteralLike(location) ? location : ((_a = isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : void 0) == null ? void 0 : _a.name) || ((_b = isLiteralImportTypeNode(location) ? location : void 0) == null ? void 0 : _b.argument.literal) || (isVariableDeclaration(location) && location.initializer && isRequireCall( + location.initializer, + /*requireStringLiteralLikeArgument*/ + true + ) ? location.initializer.arguments[0] : void 0) || ((_c = findAncestor(location, isImportCall)) == null ? void 0 : _c.arguments[0]) || ((_d = findAncestor(location, or(isImportDeclaration, isJSDocImportTag, isExportDeclaration))) == null ? void 0 : _d.moduleSpecifier) || ((_e = findAncestor(location, isExternalModuleImportEqualsDeclaration)) == null ? void 0 : _e.moduleReference.expression); + const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? host.getModeForUsageLocation(currentSourceFile, contextSpecifier) : host.getDefaultResolutionModeForFile(currentSourceFile); + const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions); + const resolvedModule = (_f = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _f.resolvedModule; + const resolutionDiagnostic = errorNode && resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile); + const sourceFile = resolvedModule && (!resolutionDiagnostic || resolutionDiagnostic === Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) { + const importOrExport = ((_g = findAncestor(location, isImportDeclaration)) == null ? void 0 : _g.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + if (errorNode && importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) { + error( + errorNode, + Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead, + getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference))) + ); + } + } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { + const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + if (errorNode && !((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) { + const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); + error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); + } + } else if (compilerOptions.rewriteRelativeImportExtensions && !(location.flags & 33554432 /* Ambient */) && !isDeclarationFileName(moduleReference) && !isLiteralImportTypeNode(location) && !isPartOfTypeOnlyImportOrExportDeclaration(location)) { + const shouldRewrite = shouldRewriteModuleSpecifier(moduleReference, compilerOptions); + if (!resolvedModule.resolvedUsingTsExtension && shouldRewrite) { + error( + errorNode, + Diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolves_to_0, + getRelativePathFromFile(getNormalizedAbsolutePath(currentSourceFile.fileName, host.getCurrentDirectory()), resolvedModule.resolvedFileName, hostGetCanonicalFileName(host)) + ); + } else if (resolvedModule.resolvedUsingTsExtension && !shouldRewrite && sourceFileMayBeEmitted(sourceFile, host)) { + error( + errorNode, + Diagnostics.This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_during_emit_because_it_is_not_a_relative_path, + getAnyExtensionFromPath(moduleReference) + ); + } else if (resolvedModule.resolvedUsingTsExtension && shouldRewrite) { + const redirect = host.getResolvedProjectReferenceToRedirect(sourceFile.path); + if (redirect) { + const ignoreCase = !host.useCaseSensitiveFileNames(); + const ownRootDir = host.getCommonSourceDirectory(); + const otherRootDir = getCommonSourceDirectoryOfConfig(redirect.commandLine, ignoreCase); + const rootDirPath = getRelativePathFromDirectory(ownRootDir, otherRootDir, ignoreCase); + const outDirPath = getRelativePathFromDirectory(compilerOptions.outDir || ownRootDir, redirect.commandLine.options.outDir || otherRootDir, ignoreCase); + if (rootDirPath !== outDirPath) { + error( + errorNode, + Diagnostics.This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_between_the_projects_output_files_is_not_the_same_as_the_relative_path_between_its_input_files + ); + } + } + } + } + if (sourceFile.symbol) { + if (errorNode && resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { + errorOnImplicitAnyModule( + /*isError*/ + false, + errorNode, + currentSourceFile, + mode, + resolvedModule, + moduleReference + ); + } + if (errorNode && (moduleKind === 100 /* Node16 */ || moduleKind === 101 /* Node18 */)) { + const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration); + const overrideHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l) || isJSDocImportTag(l)); + if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !hasResolutionModeOverride(overrideHost)) { + if (findAncestor(location, isImportEqualsDeclaration)) { + error(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); + } else { + let diagnosticDetails; + const ext = tryGetExtensionFromPath2(currentSourceFile.fileName); + if (ext === ".ts" /* Ts */ || ext === ".js" /* Js */ || ext === ".tsx" /* Tsx */ || ext === ".jsx" /* Jsx */) { + diagnosticDetails = createModeMismatchDetails(currentSourceFile); + } + const message = (overrideHost == null ? void 0 : overrideHost.kind) === 272 /* ImportDeclaration */ && ((_i = overrideHost.importClause) == null ? void 0 : _i.isTypeOnly) ? Diagnostics.Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute : (overrideHost == null ? void 0 : overrideHost.kind) === 205 /* ImportType */ ? Diagnostics.Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute : Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead; + diagnostics.add(createDiagnosticForNodeFromMessageChain( + getSourceFileOfNode(errorNode), + errorNode, + chainDiagnosticMessages(diagnosticDetails, message, moduleReference) + )); + } + } + } + return getMergedSymbol(sourceFile.symbol); + } + if (errorNode && moduleNotFoundError && !isSideEffectImport(errorNode)) { + error(errorNode, Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return void 0; + } + if (patternAmbientModules) { + const pattern = findBestPatternMatch(patternAmbientModules, (_) => _.pattern, moduleReference); + if (pattern) { + const augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference); + if (augmentation) { + return getMergedSymbol(augmentation); + } + return getMergedSymbol(pattern.symbol); + } + } + if (!errorNode) { + return void 0; + } + if (resolvedModule && !resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === void 0 || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (isForAugmentation) { + const diag2 = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag2, moduleReference, resolvedModule.resolvedFileName); + } else { + errorOnImplicitAnyModule( + /*isError*/ + noImplicitAny && !!moduleNotFoundError, + errorNode, + currentSourceFile, + mode, + resolvedModule, + moduleReference + ); + } + return void 0; + } + if (moduleNotFoundError) { + if (resolvedModule) { + const redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName); + if (redirect) { + error(errorNode, Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); + return void 0; + } + } + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } else { + const isExtensionlessRelativePathImport = pathIsRelative(moduleReference) && !hasExtension(moduleReference); + const resolutionIsNode16OrNext = moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */; + if (!getResolveJsonModule(compilerOptions) && fileExtensionIs(moduleReference, ".json" /* Json */) && moduleResolutionKind !== 1 /* Classic */ && hasJsonModuleEmitEnabled(compilerOptions)) { + error(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } else if (mode === 99 /* ESNext */ && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) { + const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path)); + const suggestedExt = (_j = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _j[1]; + if (suggestedExt) { + error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); + } else { + error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path); + } + } else { + if ((_k = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _k.alternateResult) { + const errorInfo = createModuleNotFoundChain(currentSourceFile, host, moduleReference, mode, moduleReference); + errorOrSuggestion( + /*isError*/ + true, + errorNode, + chainDiagnosticMessages(errorInfo, moduleNotFoundError, moduleReference) + ); + } else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + } + return void 0; + function getSuggestedImportSource(tsExtension) { + const importSourceWithoutExtension = removeExtension(moduleReference, tsExtension); + if (emitModuleKindIsNonNodeESM(moduleKind) || mode === 99 /* ESNext */) { + const preferTs = isDeclarationFileName(moduleReference) && shouldAllowImportingTsExtension(compilerOptions); + const ext = tsExtension === ".mts" /* Mts */ || tsExtension === ".d.mts" /* Dmts */ ? preferTs ? ".mts" : ".mjs" : tsExtension === ".cts" /* Cts */ || tsExtension === ".d.mts" /* Dmts */ ? preferTs ? ".cts" : ".cjs" : preferTs ? ".ts" : ".js"; + return importSourceWithoutExtension + ext; + } + return importSourceWithoutExtension; + } + } + function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) { + if (isSideEffectImport(errorNode)) { + return; + } + let errorInfo; + if (!isExternalModuleNameRelative(moduleReference) && packageId) { + errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); + } + errorOrSuggestion( + isError, + errorNode, + chainDiagnosticMessages( + errorInfo, + Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, + moduleReference, + resolvedFileName + ) + ); + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + if (moduleSymbol == null ? void 0 : moduleSymbol.exports) { + const exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); + const exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol)); + return getMergedSymbol(exported) || moduleSymbol; + } + return void 0; + } + function getCommonJsExportEquals(exported, moduleSymbol) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) { + return exported; + } + const links = getSymbolLinks(exported); + if (links.cjsExportMerged) { + return links.cjsExportMerged; + } + const merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported); + merged.flags = merged.flags | 512 /* ValueModule */; + if (merged.exports === void 0) { + merged.exports = createSymbolTable(); + } + moduleSymbol.exports.forEach((s, name) => { + if (name === "export=" /* ExportEquals */) return; + merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); + }); + if (merged === exported) { + getSymbolLinks(merged).resolvedExports = void 0; + getSymbolLinks(merged).resolvedMembers = void 0; + } + getSymbolLinks(merged).cjsExportMerged = merged; + return links.cjsExportMerged = merged; + } + function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) { + var _a; + const symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); + if (!dontResolveAlias && symbol) { + if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !getDeclarationOfKind(symbol, 307 /* SourceFile */)) { + const compilerOptionName = moduleKind >= 5 /* ES2015 */ ? "allowSyntheticDefaultImports" : "esModuleInterop"; + error(referencingLocation, Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); + return symbol; + } + const referenceParent = referencingLocation.parent; + if (isImportDeclaration(referenceParent) && getNamespaceDeclarationNode(referenceParent) || isImportCall(referenceParent)) { + const reference = isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier; + const type = getTypeOfSymbol(symbol); + const defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference); + if (defaultOnlyType) { + return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent); + } + const targetFile = (_a = moduleSymbol == null ? void 0 : moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); + const isEsmCjsRef = targetFile && isESMFormatImportImportingCommonjsFormatFile(getEmitSyntaxForModuleSpecifierExpression(reference), host.getImpliedNodeFormatForEmit(targetFile)); + if (getESModuleInterop(compilerOptions) || isEsmCjsRef) { + let sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length || getPropertyOfType( + type, + "default" /* Default */, + /*skipObjectFunctionPropertyAugment*/ + true + ) || isEsmCjsRef) { + const moduleType = type.flags & 3670016 /* StructuredType */ ? getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference) : createDefaultPropertyWrapperForModule(symbol, symbol.parent); + return cloneTypeAsModuleType(symbol, moduleType, referenceParent); + } + } + } + } + return symbol; + } + function cloneTypeAsModuleType(symbol, moduleType, referenceParent) { + const result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.links.target = symbol; + result.links.originatingImport = referenceParent; + if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; + if (symbol.members) result.members = new Map(symbol.members); + if (symbol.exports) result.exports = new Map(symbol.exports); + const resolvedModuleType = resolveStructuredTypeMembers(moduleType); + result.links.type = createAnonymousType(result, resolvedModuleType.members, emptyArray, emptyArray, resolvedModuleType.indexInfos); + return result; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=" /* ExportEquals */) !== void 0; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + const exports2 = getExportsOfModuleAsArray(moduleSymbol); + const exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + const type = getTypeOfSymbol(exportEquals); + if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { + addRange(exports2, getPropertiesOfType(type)); + } + } + return exports2; + } + function forEachExportAndPropertyOfModule(moduleSymbol, cb) { + const exports2 = getExportsOfModule(moduleSymbol); + exports2.forEach((symbol, key) => { + if (!isReservedMemberName(key)) { + cb(symbol, key); + } + }); + const exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + const type = getTypeOfSymbol(exportEquals); + if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { + forEachPropertyOfType(type, (symbol, escapedName) => { + cb(symbol, escapedName); + }); + } + } + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + const symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + const symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (symbol) { + return symbol; + } + const exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals === moduleSymbol) { + return void 0; + } + const type = getTypeOfSymbol(exportEquals); + return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : void 0; + } + function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) { + return !(resolvedExternalModuleType.flags & 402784252 /* Primitive */ || getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + isArrayType(resolvedExternalModuleType) || isTupleType(resolvedExternalModuleType)); + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + const links = getSymbolLinks(moduleSymbol); + if (!links.resolvedExports) { + const { exports: exports2, typeOnlyExportStarMap } = getExportsOfModuleWorker(moduleSymbol); + links.resolvedExports = exports2; + links.typeOnlyExportStarMap = typeOnlyExportStarMap; + } + return links.resolvedExports; + } + function extendExportSymbols(target, source, lookupTable, exportNode) { + if (!source) return; + source.forEach((sourceSymbol, id) => { + if (id === "default" /* Default */) return; + const targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: getTextOfNode(exportNode.moduleSpecifier) + }); + } + } else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + const collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + const visitedSymbols = []; + let typeOnlyExportStarMap; + const nonTypeOnlyNames = /* @__PURE__ */ new Set(); + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + const exports2 = visit(moduleSymbol) || emptySymbols; + if (typeOnlyExportStarMap) { + nonTypeOnlyNames.forEach((name) => typeOnlyExportStarMap.delete(name)); + } + return { + exports: exports2, + typeOnlyExportStarMap + }; + function visit(symbol, exportStar, isTypeOnly) { + if (!isTypeOnly && (symbol == null ? void 0 : symbol.exports)) { + symbol.exports.forEach((_, name) => nonTypeOnlyNames.add(name)); + } + if (!(symbol && symbol.exports && pushIfUnique(visitedSymbols, symbol))) { + return; + } + const symbols = new Map(symbol.exports); + const exportStars = symbol.exports.get("__export" /* ExportStar */); + if (exportStars) { + const nestedSymbols = createSymbolTable(); + const lookupTable = /* @__PURE__ */ new Map(); + if (exportStars.declarations) { + for (const node of exportStars.declarations) { + const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + const exportedSymbols = visit(resolvedModule, node, isTypeOnly || node.isTypeOnly); + extendExportSymbols( + nestedSymbols, + exportedSymbols, + lookupTable, + node + ); + } + } + lookupTable.forEach(({ exportsWithDuplicate }, id) => { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (const node of exportsWithDuplicate) { + diagnostics.add(createDiagnosticForNode( + node, + Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, + lookupTable.get(id).specifierText, + unescapeLeadingUnderscores(id) + )); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + if (exportStar == null ? void 0 : exportStar.isTypeOnly) { + typeOnlyExportStarMap ?? (typeOnlyExportStarMap = /* @__PURE__ */ new Map()); + symbols.forEach( + (_, escapedName) => typeOnlyExportStarMap.set( + escapedName, + exportStar + ) + ); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + let merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfDeclaration(node) { + return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol)); + } + function getSymbolOfNode(node) { + return canHaveSymbol(node) ? getSymbolOfDeclaration(node) : void 0; + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); + } + function getFunctionExpressionParentSymbolOrSymbol(symbol) { + var _a, _b; + return ((_a = symbol.valueDeclaration) == null ? void 0 : _a.kind) === 219 /* ArrowFunction */ || ((_b = symbol.valueDeclaration) == null ? void 0 : _b.kind) === 218 /* FunctionExpression */ ? getSymbolOfNode(symbol.valueDeclaration.parent) || symbol : symbol; + } + function getAlternativeContainingModules(symbol, enclosingDeclaration) { + const containingFile = getSourceFileOfNode(enclosingDeclaration); + const id = getNodeId(containingFile); + const links = getSymbolLinks(symbol); + let results; + if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) { + return results; + } + if (containingFile && containingFile.imports) { + for (const importRef of containingFile.imports) { + if (nodeIsSynthesized(importRef)) continue; + const resolvedModule = resolveExternalModuleName( + enclosingDeclaration, + importRef, + /*ignoreErrors*/ + true + ); + if (!resolvedModule) continue; + const ref = getAliasForSymbolInContainer(resolvedModule, symbol); + if (!ref) continue; + results = append(results, resolvedModule); + } + if (length(results)) { + (links.extendedContainersByFile || (links.extendedContainersByFile = /* @__PURE__ */ new Map())).set(id, results); + return results; + } + } + if (links.extendedContainers) { + return links.extendedContainers; + } + const otherFiles = host.getSourceFiles(); + for (const file of otherFiles) { + if (!isExternalModule(file)) continue; + const sym = getSymbolOfDeclaration(file); + const ref = getAliasForSymbolInContainer(sym, symbol); + if (!ref) continue; + results = append(results, sym); + } + return links.extendedContainers = results || emptyArray; + } + function getContainersOfSymbol(symbol, enclosingDeclaration, meaning) { + const container = getParentOfSymbol(symbol); + if (container && !(symbol.flags & 262144 /* TypeParameter */)) { + return getWithAlternativeContainers(container); + } + const candidates = mapDefined(symbol.declarations, (d) => { + if (!isAmbientModule(d) && d.parent) { + if (hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { + return getSymbolOfDeclaration(d.parent); + } + if (isModuleBlock(d.parent) && d.parent.parent && resolveExternalModuleSymbol(getSymbolOfDeclaration(d.parent.parent)) === symbol) { + return getSymbolOfDeclaration(d.parent.parent); + } + } + if (isClassExpression(d) && isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 64 /* EqualsToken */ && isAccessExpression(d.parent.left) && isEntityNameExpression(d.parent.left.expression)) { + if (isModuleExportsAccessExpression(d.parent.left) || isExportsIdentifier(d.parent.left.expression)) { + return getSymbolOfDeclaration(getSourceFileOfNode(d)); + } + checkExpressionCached(d.parent.left.expression); + return getNodeLinks(d.parent.left.expression).resolvedSymbol; + } + }); + if (!length(candidates)) { + return void 0; + } + const containers = mapDefined(candidates, (candidate) => getAliasForSymbolInContainer(candidate, symbol) ? candidate : void 0); + let bestContainers = []; + let alternativeContainers = []; + for (const container2 of containers) { + const [bestMatch, ...rest] = getWithAlternativeContainers(container2); + bestContainers = append(bestContainers, bestMatch); + alternativeContainers = addRange(alternativeContainers, rest); + } + return concatenate(bestContainers, alternativeContainers); + function getWithAlternativeContainers(container2) { + const additionalContainers = mapDefined(container2.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + const reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); + const objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container2, meaning); + if (enclosingDeclaration && container2.flags & getQualifiedLeftMeaning(meaning) && getAccessibleSymbolChain( + container2, + enclosingDeclaration, + 1920 /* Namespace */, + /*useOnlyExternalAliasing*/ + false + )) { + return append(concatenate(concatenate([container2], additionalContainers), reexportContainers), objectLiteralContainer); + } + const firstVariableMatch = !(container2.flags & getQualifiedLeftMeaning(meaning)) && container2.flags & 788968 /* Type */ && getDeclaredTypeOfSymbol(container2).flags & 524288 /* Object */ && meaning === 111551 /* Value */ ? forEachSymbolTableInScope(enclosingDeclaration, (t) => { + return forEachEntry(t, (s) => { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container2)) { + return s; + } + }); + }) : void 0; + let res = firstVariableMatch ? [firstVariableMatch, ...additionalContainers, container2] : [...additionalContainers, container2]; + res = append(res, objectLiteralContainer); + res = addRange(res, reexportContainers); + return res; + } + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container); + } + } + function getVariableDeclarationOfObjectLiteral(symbol, meaning) { + const firstDecl = !!length(symbol.declarations) && first(symbol.declarations); + if (meaning & 111551 /* Value */ && firstDecl && firstDecl.parent && isVariableDeclaration(firstDecl.parent)) { + if (isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) { + return getSymbolOfDeclaration(firstDecl.parent); + } + } + } + function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) { + const fileSymbol = getExternalModuleContainer(d); + const exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : void 0; + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + return symbol; + } + const exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */); + if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) { + return container; + } + const exports2 = getExportsOfSymbol(container); + const quick = exports2.get(symbol.escapedName); + if (quick && getSymbolIfSameReference(quick, symbol)) { + return quick; + } + return forEachEntry(exports2, (exported) => { + if (getSymbolIfSameReference(exported, symbol)) { + return exported; + } + }); + } + function getSymbolIfSameReference(s1, s2) { + if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) { + return s1; + } + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 && symbol.exportSymbol || symbol); + } + function symbolIsValue(symbol, includeTypeOnlyMembers) { + return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getSymbolFlags(symbol, !includeTypeOnlyMembers) & 111551 /* Value */); + } + function createType(flags) { + var _a; + const result = new Type7(checker, flags); + typeCount++; + result.id = typeCount; + (_a = tracing) == null ? void 0 : _a.recordType(result); + return result; + } + function createTypeWithSymbol(flags, symbol) { + const result = createType(flags); + result.symbol = symbol; + return result; + } + function createOriginType(flags) { + return new Type7(checker, flags); + } + function createIntrinsicType(kind, intrinsicName, objectFlags = 0 /* None */, debugIntrinsicName) { + checkIntrinsicName(intrinsicName, debugIntrinsicName); + const type = createType(kind); + type.intrinsicName = intrinsicName; + type.debugIntrinsicName = debugIntrinsicName; + type.objectFlags = objectFlags | 524288 /* CouldContainTypeVariablesComputed */ | 2097152 /* IsGenericTypeComputed */ | 33554432 /* IsUnknownLikeUnionComputed */ | 16777216 /* IsNeverIntersectionComputed */; + return type; + } + function checkIntrinsicName(name, debug) { + const key = `${name},${debug ?? ""}`; + if (seenIntrinsicNames.has(key)) { + Debug.fail(`Duplicate intrinsic type name ${name}${debug ? ` (${debug})` : ""}; you may need to pass a name to createIntrinsicType.`); + } + seenIntrinsicNames.add(key); + } + function createObjectType(objectFlags, symbol) { + const type = createTypeWithSymbol(524288 /* Object */, symbol); + type.objectFlags = objectFlags; + type.members = void 0; + type.properties = void 0; + type.callSignatures = void 0; + type.constructSignatures = void 0; + type.indexInfos = void 0; + return type; + } + function createTypeofType() { + return getUnionType(arrayFrom(typeofNEFacts.keys(), getStringLiteralType)); + } + function createTypeParameter(symbol) { + return createTypeWithSymbol(262144 /* TypeParameter */, symbol); + } + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) !== 95 /* _ */ && name.charCodeAt(2) !== 64 /* at */ && name.charCodeAt(2) !== 35 /* hash */; + } + function getNamedMembers(members) { + let result; + members.forEach((symbol, id) => { + if (isNamedMember(symbol, id)) { + (result || (result = [])).push(symbol); + } + }); + return result || emptyArray; + } + function isNamedMember(member, escapedName) { + return !isReservedMemberName(escapedName) && symbolIsValue(member); + } + function getNamedOrIndexSignatureMembers(members) { + const result = getNamedMembers(members); + const index = getIndexSymbolFromSymbolTable(members); + return index ? concatenate(result, [index]) : result; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos) { + const resolved = type; + resolved.members = members; + resolved.properties = emptyArray; + resolved.callSignatures = callSignatures; + resolved.constructSignatures = constructSignatures; + resolved.indexInfos = indexInfos; + if (members !== emptySymbols) resolved.properties = getNamedMembers(members); + return resolved; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, indexInfos) { + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, indexInfos); + } + function getResolvedTypeWithoutAbstractConstructSignatures(type) { + if (type.constructSignatures.length === 0) return type; + if (type.objectTypeWithoutAbstractConstructSignatures) return type.objectTypeWithoutAbstractConstructSignatures; + const constructSignatures = filter(type.constructSignatures, (signature) => !(signature.flags & 4 /* Abstract */)); + if (type.constructSignatures === constructSignatures) return type; + const typeCopy = createAnonymousType( + type.symbol, + type.members, + type.callSignatures, + some(constructSignatures) ? constructSignatures : emptyArray, + type.indexInfos + ); + type.objectTypeWithoutAbstractConstructSignatures = typeCopy; + typeCopy.objectTypeWithoutAbstractConstructSignatures = typeCopy; + return typeCopy; + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + let result; + for (let location = enclosingDeclaration; location; location = location.parent) { + if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { + if (result = callback( + location.locals, + /*ignoreQualification*/ + void 0, + /*isLocalNameLookup*/ + true, + location + )) { + return result; + } + } + switch (location.kind) { + case 307 /* SourceFile */: + if (!isExternalOrCommonJsModule(location)) { + break; + } + // falls through + case 267 /* ModuleDeclaration */: + const sym = getSymbolOfDeclaration(location); + if (result = callback( + (sym == null ? void 0 : sym.exports) || emptySymbols, + /*ignoreQualification*/ + void 0, + /*isLocalNameLookup*/ + true, + location + )) { + return result; + } + break; + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 264 /* InterfaceDeclaration */: + let table; + (getSymbolOfDeclaration(location).members || emptySymbols).forEach((memberSymbol, key) => { + if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) { + (table || (table = createSymbolTable())).set(key, memberSymbol); + } + }); + if (table && (result = callback( + table, + /*ignoreQualification*/ + void 0, + /*isLocalNameLookup*/ + false, + location + ))) { + return result; + } + break; + } + } + return callback( + globals, + /*ignoreQualification*/ + void 0, + /*isLocalNameLookup*/ + true + ); + } + function getQualifiedLeftMeaning(rightMeaning) { + return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap = /* @__PURE__ */ new Map()) { + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return void 0; + } + const links = getSymbolLinks(symbol); + const cache = links.accessibleChainCache || (links.accessibleChainCache = /* @__PURE__ */ new Map()); + const firstRelevantLocation = forEachSymbolTableInScope(enclosingDeclaration, (_, __, ___, node) => node); + const key = `${useOnlyExternalAliasing ? 0 : 1}|${firstRelevantLocation ? getNodeId(firstRelevantLocation) : 0}|${meaning}`; + if (cache.has(key)) { + return cache.get(key); + } + const id = getSymbolId(symbol); + let visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { + visitedSymbolTablesMap.set(id, visitedSymbolTables = []); + } + const result = forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + cache.set(key, result); + return result; + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { + if (!pushIfUnique(visitedSymbolTables, symbols)) { + return void 0; + } + const result2 = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); + visitedSymbolTables.pop(); + return result2; + } + function canQualifySymbol(symbolFromSymbolTable, meaning2) { + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning2) || // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning2), useOnlyExternalAliasing, visitedSymbolTablesMap); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { + return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) && // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + !some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); + } + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { + if (isAccessible( + symbols.get(symbol.escapedName), + /*resolvedAliasSymbol*/ + void 0, + ignoreQualification + )) { + return [symbol]; + } + const result2 = forEachEntry(symbols, (symbolFromSymbolTable) => { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) && (isLocalNameLookup ? !some(symbolFromSymbolTable.declarations, isNamespaceReexportDeclaration) : true) && (ignoreQualification || !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */))) { + const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + const candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); + if (candidate) { + return candidate; + } + } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible( + getMergedSymbol(symbolFromSymbolTable.exportSymbol), + /*resolvedAliasSymbol*/ + void 0, + ignoreQualification + )) { + return [symbol]; + } + } + }); + return result2 || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : void 0); + } + function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) { + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { + return [symbolFromSymbolTable]; + } + const candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + const accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable( + candidateTable, + /*ignoreQualification*/ + true + ); + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + let qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, (symbolTable) => { + let symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); + if (!symbolFromSymbolTable) { + return false; + } + if (symbolFromSymbolTable === symbol) { + return true; + } + const shouldResolveAlias = symbolFromSymbolTable.flags & 2097152 /* Alias */ && !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */); + symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + if (flags & meaning) { + qualify = true; + return true; + } + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (const declaration of symbol.declarations) { + switch (declaration.kind) { + case 172 /* PropertyDeclaration */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { + const access = isSymbolAccessibleWorker( + typeSymbol, + enclosingDeclaration, + 788968 /* Type */, + /*shouldComputeAliasesToMakeVisible*/ + false, + /*allowModules*/ + true + ); + return access.accessibility === 0 /* Accessible */; + } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + const access = isSymbolAccessibleWorker( + typeSymbol, + enclosingDeclaration, + 111551 /* Value */, + /*shouldComputeAliasesToMakeVisible*/ + false, + /*allowModules*/ + true + ); + return access.accessibility === 0 /* Accessible */; + } + function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) { + const access = isSymbolAccessibleWorker( + typeSymbol, + enclosingDeclaration, + flags, + /*shouldComputeAliasesToMakeVisible*/ + false, + /*allowModules*/ + false + ); + return access.accessibility === 0 /* Accessible */; + } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) { + if (!length(symbols)) return; + let hadAccessibleChain; + let earlyModuleBail = false; + for (const symbol of symbols) { + const accessibleSymbolChain = getAccessibleSymbolChain( + symbol, + enclosingDeclaration, + meaning, + /*useOnlyExternalAliasing*/ + false + ); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + if (allowModules) { + if (some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + if (shouldComputeAliasesToMakeVisible) { + earlyModuleBail = true; + continue; + } + return { + accessibility: 0 /* Accessible */ + }; + } + } + const containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning); + const parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules); + if (parentResult) { + return parentResult; + } + } + if (earlyModuleBail) { + return { + accessibility: 0 /* Accessible */ + }; + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : void 0 + }; + } + } + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + return isSymbolAccessibleWorker( + symbol, + enclosingDeclaration, + meaning, + shouldComputeAliasesToMakeVisible, + /*allowModules*/ + true + ); + } + function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) { + if (symbol && enclosingDeclaration) { + const result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible, allowModules); + if (result) { + return result; + } + const symbolExternalModule = forEach(symbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + const enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + return { + accessibility: 2 /* CannotBeNamed */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule), + errorNode: isInJSFile(enclosingDeclaration) ? enclosingDeclaration : void 0 + }; + } + } + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning) + }; + } + return { accessibility: 0 /* Accessible */ }; + } + function getExternalModuleContainer(declaration) { + const node = findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfDeclaration(node); + } + function hasExternalModuleSymbol(declaration) { + return isAmbientModule(declaration) || declaration.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(declaration); + } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return isModuleWithStringLiteralName(declaration) || declaration.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(declaration); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + let aliasesToMakeVisible; + if (!every(filter(symbol.declarations, (d) => d.kind !== 80 /* Identifier */), getIsDeclarationVisible)) { + return void 0; + } + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + var _a, _b; + if (!isDeclarationVisible(declaration)) { + const anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, 32 /* Export */) && // import clause without export + isDeclarationVisible(anyImportSyntax.parent)) { + return addVisibleAlias(declaration, anyImportSyntax); + } else if (isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && !hasSyntacticModifier(declaration.parent.parent, 32 /* Export */) && // unexported variable statement + isDeclarationVisible(declaration.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent); + } else if (isLateVisibilityPaintedStatement(declaration) && !hasSyntacticModifier(declaration, 32 /* Export */) && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); + } else if (isBindingElement(declaration)) { + if (symbol.flags & 2097152 /* Alias */ && isInJSFile(declaration) && ((_a = declaration.parent) == null ? void 0 : _a.parent) && isVariableDeclaration(declaration.parent.parent) && ((_b = declaration.parent.parent.parent) == null ? void 0 : _b.parent) && isVariableStatement(declaration.parent.parent.parent.parent) && !hasSyntacticModifier(declaration.parent.parent.parent.parent, 32 /* Export */) && declaration.parent.parent.parent.parent.parent && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + } else if (symbol.flags & 2 /* BlockScopedVariable */) { + const variableStatement = findAncestor(declaration, isVariableStatement); + if (hasSyntacticModifier(variableStatement, 32 /* Export */)) { + return true; + } + if (!isDeclarationVisible(variableStatement.parent)) { + return false; + } + return addVisibleAlias(declaration, variableStatement); + } + } + return false; + } + return true; + } + function addVisibleAlias(declaration, aliasingStatement) { + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + aliasesToMakeVisible = appendIfUnique(aliasesToMakeVisible, aliasingStatement); + } + return true; + } + } + function getMeaningOfEntityNameReference(entityName) { + let meaning; + if (entityName.parent.kind === 186 /* TypeQuery */ || entityName.parent.kind === 233 /* ExpressionWithTypeArguments */ && !isPartOfTypeNode(entityName.parent) || entityName.parent.kind === 167 /* ComputedPropertyName */ || entityName.parent.kind === 182 /* TypePredicate */ && entityName.parent.parameterName === entityName) { + meaning = 111551 /* Value */ | 1048576 /* ExportValue */; + } else if (entityName.kind === 166 /* QualifiedName */ || entityName.kind === 211 /* PropertyAccessExpression */ || entityName.parent.kind === 271 /* ImportEqualsDeclaration */ || entityName.parent.kind === 166 /* QualifiedName */ && entityName.parent.left === entityName || entityName.parent.kind === 211 /* PropertyAccessExpression */ && entityName.parent.expression === entityName || entityName.parent.kind === 212 /* ElementAccessExpression */ && entityName.parent.expression === entityName) { + meaning = 1920 /* Namespace */; + } else { + meaning = 788968 /* Type */; + } + return meaning; + } + function isEntityNameVisible(entityName, enclosingDeclaration, shouldComputeAliasToMakeVisible = true) { + const meaning = getMeaningOfEntityNameReference(entityName); + const firstIdentifier = getFirstIdentifier(entityName); + const symbol = resolveName( + enclosingDeclaration, + firstIdentifier.escapedText, + meaning, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */) { + return { accessibility: 0 /* Accessible */ }; + } + if (!symbol && isThisIdentifier(firstIdentifier) && isSymbolAccessible( + getSymbolOfDeclaration(getThisContainer( + firstIdentifier, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + )), + firstIdentifier, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility === 0 /* Accessible */) { + return { accessibility: 0 /* Accessible */ }; + } + if (!symbol) { + return { + accessibility: 3 /* NotResolved */, + errorSymbolName: getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + return hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) || { + accessibility: 1 /* NotAccessible */, + errorSymbolName: getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function symbolToString(symbol, enclosingDeclaration, meaning, flags = 4 /* AllowAnyNodeKind */, writer) { + let nodeFlags = 70221824 /* IgnoreErrors */; + let internalNodeFlags = 0 /* None */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { + nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; + } + if (flags & 32 /* DoNotIncludeSymbolChain */) { + internalNodeFlags |= 4 /* DoNotIncludeSymbolChain */; + } + if (flags & 16 /* WriteComputedProps */) { + internalNodeFlags |= 1 /* WriteComputedProps */; + } + const builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToNode : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer2) { + const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags, internalNodeFlags); + const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 307 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments(); + const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); + printer.writeNode( + 4 /* Unspecified */, + entity, + /*sourceFile*/ + sourceFile, + writer2 + ); + return writer2; + } + } + function signatureToString(signature, enclosingDeclaration, flags = 0 /* None */, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer2) { + let sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 185 /* ConstructorType */ : 184 /* FunctionType */; + } else { + sigOutput = kind === 1 /* Construct */ ? 180 /* ConstructSignature */ : 179 /* CallSignature */; + } + const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); + const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); + printer.writeNode( + 4 /* Unspecified */, + sig, + /*sourceFile*/ + sourceFile, + getTrailingSemicolonDeferringWriter(writer2) + ); + return writer2; + } + } + function typeToString(type, enclosingDeclaration, flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer = createTextWriter("")) { + const noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + const typeNode = nodeBuilder.typeToTypeNode( + type, + enclosingDeclaration, + toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0 /* None */), + /*internalFlags*/ + void 0 + ); + if (typeNode === void 0) return Debug.fail("should always get typenode"); + const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults(); + const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); + printer.writeNode( + 4 /* Unspecified */, + typeNode, + /*sourceFile*/ + sourceFile, + writer + ); + const result = writer.getText(); + const maxLength = noTruncation ? noTruncationMaximumTruncationLength * 2 : defaultMaximumTruncationLength * 2; + if (maxLength && result && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + } + function getTypeNamesForErrorDisplay(left, right) { + let leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left); + let rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right); + if (leftStr === rightStr) { + leftStr = getTypeNameForErrorDisplay(left); + rightStr = getTypeNameForErrorDisplay(right); + } + return [leftStr, rightStr]; + } + function getTypeNameForErrorDisplay(type) { + return typeToString( + type, + /*enclosingDeclaration*/ + void 0, + 64 /* UseFullyQualifiedType */ + ); + } + function symbolValueDeclarationIsContextSensitive(symbol) { + return symbol && !!symbol.valueDeclaration && isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); + } + function toNodeBuilderFlags(flags = 0 /* None */) { + return flags & 848330095 /* NodeBuilderFlagsMask */; + } + function isClassInstanceSide(type) { + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(type.flags & 524288 /* Object */) && !!(getObjectFlags(type) & 16777216 /* IsClassInstanceClone */)); + } + function getTypeFromTypeNodeWithoutContext(node) { + return getTypeFromTypeNode(node); + } + function createNodeBuilder() { + const syntacticBuilderResolver = { + evaluateEntityNameExpression, + isExpandoFunctionDeclaration, + hasLateBindableName, + shouldRemoveDeclaration(context, node) { + return !(context.internalFlags & 8 /* AllowUnresolvedNames */ && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & 1 /* Any */); + }, + createRecoveryBoundary(context) { + return createRecoveryBoundary(context); + }, + isDefinitelyReferenceToGlobalSymbolObject, + getAllAccessorDeclarations: getAllAccessorDeclarationsForDeclaration, + requiresAddingImplicitUndefined(declaration, symbol, enclosingDeclaration) { + var _a; + switch (declaration.kind) { + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 348 /* JSDocPropertyTag */: + symbol ?? (symbol = getSymbolOfDeclaration(declaration)); + const type = getTypeOfSymbol(symbol); + return !!(symbol.flags & 4 /* Property */ && symbol.flags & 16777216 /* Optional */ && isOptionalDeclaration(declaration) && ((_a = symbol.links) == null ? void 0 : _a.mappedType) && containsNonMissingUndefinedType(type)); + case 169 /* Parameter */: + case 341 /* JSDocParameterTag */: + return requiresAddingImplicitUndefined(declaration, enclosingDeclaration); + default: + Debug.assertNever(declaration); + } + }, + isOptionalParameter, + isUndefinedIdentifierExpression(node) { + Debug.assert(isExpressionNode(node)); + return getSymbolAtLocation(node) === undefinedSymbol; + }, + isEntityNameVisible(context, entityName, shouldComputeAliasToMakeVisible) { + return isEntityNameVisible(entityName, context.enclosingDeclaration, shouldComputeAliasToMakeVisible); + }, + serializeExistingTypeNode(context, typeNode, addUndefined) { + return serializeExistingTypeNode(context, typeNode, !!addUndefined); + }, + serializeReturnTypeForSignature(syntacticContext, signatureDeclaration, symbol) { + const context = syntacticContext; + const signature = getSignatureFromDeclaration(signatureDeclaration); + symbol ?? (symbol = getSymbolOfDeclaration(signatureDeclaration)); + const returnType = context.enclosingSymbolTypes.get(getSymbolId(symbol)) ?? instantiateType(getReturnTypeOfSignature(signature), context.mapper); + return serializeInferredReturnTypeForSignature(context, signature, returnType); + }, + serializeTypeOfExpression(syntacticContext, expr) { + const context = syntacticContext; + const type = instantiateType(getWidenedType(getRegularTypeOfExpression(expr)), context.mapper); + return typeToTypeNodeHelper(type, context); + }, + serializeTypeOfDeclaration(syntacticContext, declaration, symbol) { + var _a; + const context = syntacticContext; + symbol ?? (symbol = getSymbolOfDeclaration(declaration)); + let type = (_a = context.enclosingSymbolTypes) == null ? void 0 : _a.get(getSymbolId(symbol)); + if (type === void 0) { + type = symbol.flags & 98304 /* Accessor */ && declaration.kind === 178 /* SetAccessor */ ? instantiateType(getWriteTypeOfSymbol(symbol), context.mapper) : symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? instantiateType(getWidenedLiteralType(getTypeOfSymbol(symbol)), context.mapper) : errorType; + } + const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration); + if (addUndefinedForParameter) { + type = getOptionalType(type); + } + return serializeInferredTypeForDeclaration(symbol, context, type); + }, + serializeNameOfParameter(context, parameter) { + return parameterToParameterDeclarationName(getSymbolOfDeclaration(parameter), parameter, context); + }, + serializeEntityName(syntacticContext, node) { + const context = syntacticContext; + const symbol = getSymbolAtLocation( + node, + /*ignoreErrors*/ + true + ); + if (!symbol) return void 0; + if (!isValueSymbolAccessible(symbol, context.enclosingDeclaration)) return void 0; + return symbolToExpression(symbol, context, 111551 /* Value */ | 1048576 /* ExportValue */); + }, + serializeTypeName(context, node, isTypeOf, typeArguments) { + return serializeTypeName(context, node, isTypeOf, typeArguments); + }, + getJsDocPropertyOverride(syntacticContext, jsDocTypeLiteral, jsDocProperty) { + const context = syntacticContext; + const name = isIdentifier(jsDocProperty.name) ? jsDocProperty.name : jsDocProperty.name.right; + const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode2(context, jsDocTypeLiteral), name.escapedText); + const overrideTypeNode = typeViaParent && jsDocProperty.typeExpression && getTypeFromTypeNode2(context, jsDocProperty.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0; + return overrideTypeNode; + }, + enterNewScope(context, node) { + if (isFunctionLike(node) || isJSDocSignature(node)) { + const signature = getSignatureFromDeclaration(node); + return enterNewScope(context, node, signature.parameters, signature.typeParameters); + } else { + const typeParameters = isConditionalTypeNode(node) ? getInferTypeParameters(node) : [getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))]; + return enterNewScope( + context, + node, + /*expandedParams*/ + void 0, + typeParameters + ); + } + }, + markNodeReuse(context, range, location) { + return setTextRange2(context, range, location); + }, + trackExistingEntityName(context, node) { + return trackExistingEntityName(node, context); + }, + trackComputedName(context, accessExpression) { + trackComputedName(accessExpression, context.enclosingDeclaration, context); + }, + getModuleSpecifierOverride(syntacticContext, parent, lit) { + const context = syntacticContext; + if (context.bundled || context.enclosingFile !== getSourceFileOfNode(lit)) { + let name = lit.text; + const originalName = name; + const nodeSymbol = getNodeLinks(parent).resolvedSymbol; + const meaning = parent.isTypeOf ? 111551 /* Value */ : 788968 /* Type */; + const parentSymbol = nodeSymbol && isSymbolAccessible( + nodeSymbol, + context.enclosingDeclaration, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility === 0 /* Accessible */ && lookupSymbolChain( + nodeSymbol, + context, + meaning, + /*yieldModuleSymbol*/ + true + )[0]; + if (parentSymbol && isExternalModuleSymbol(parentSymbol)) { + name = getSpecifierForModuleSymbol(parentSymbol, context); + } else { + const targetFile = getExternalModuleFileFromDeclaration(parent); + if (targetFile) { + name = getSpecifierForModuleSymbol(targetFile.symbol, context); + } + } + if (name.includes("/node_modules/")) { + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(name); + } + } + if (name !== originalName) { + return name; + } + } + }, + canReuseTypeNode(context, typeNode) { + return canReuseTypeNode(context, typeNode); + }, + canReuseTypeNodeAnnotation(syntacticContext, node, existing, symbol, requiresAddingUndefined) { + var _a; + const context = syntacticContext; + if (context.enclosingDeclaration === void 0) return false; + symbol ?? (symbol = getSymbolOfDeclaration(node)); + let type = (_a = context.enclosingSymbolTypes) == null ? void 0 : _a.get(getSymbolId(symbol)); + if (type === void 0) { + if (symbol.flags & 98304 /* Accessor */) { + type = node.kind === 178 /* SetAccessor */ ? getWriteTypeOfSymbol(symbol) : getTypeOfAccessors(symbol); + } else if (isValueSignatureDeclaration(node)) { + type = getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } else { + type = getTypeOfSymbol(symbol); + } + } + let annotationType = getTypeFromTypeNodeWithoutContext(existing); + if (isErrorType(annotationType)) { + return true; + } + if (requiresAddingUndefined && annotationType) { + annotationType = addOptionality(annotationType, !isParameter(node)); + } + return !!annotationType && typeNodeIsEquivalentToType(node, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type); + } + }; + return { + syntacticBuilderResolver, + typeToTypeNode: (type, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeToTypeNodeHelper(type, context)), + typePredicateToTypePredicateNode: (typePredicate, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typePredicateToTypePredicateNodeHelper(typePredicate, context)), + serializeTypeForExpression: (expr, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeTypeOfExpression(expr, context)), + serializeTypeForDeclaration: (declaration, symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeTypeOfDeclaration(declaration, symbol, context)), + serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeReturnTypeForSignature(signature, getSymbolOfDeclaration(signature), context)), + indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => indexInfoToIndexSignatureDeclarationHelper( + indexInfo, + context, + /*typeNode*/ + void 0 + )), + signatureToSignatureDeclaration: (signature, kind, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => signatureToSignatureDeclarationHelper(signature, kind, context)), + symbolToEntityName: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToName( + symbol, + context, + meaning, + /*expectsIdentifier*/ + false + )), + symbolToExpression: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToExpression(symbol, context, meaning)), + symbolToTypeParameterDeclarations: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParametersToTypeParameterDeclarations(symbol, context)), + symbolToParameterDeclaration: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToParameterDeclaration(symbol, context)), + typeParameterToDeclaration: (parameter, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParameterToDeclaration(parameter, context)), + symbolTableToDeclarationStatements: (symbolTable, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context)), + symbolToNode: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToNode(symbol, context, meaning)) + }; + function getTypeFromTypeNode2(context, node, noMappedTypes) { + const type = getTypeFromTypeNodeWithoutContext(node); + if (!context.mapper) return type; + const mappedType = instantiateType(type, context.mapper); + return noMappedTypes && mappedType !== type ? void 0 : mappedType; + } + function setTextRange2(context, range, location) { + if (!nodeIsSynthesized(range) || !(range.flags & 16 /* Synthesized */) || !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(getOriginalNode(range))) { + range = factory.cloneNode(range); + } + if (range === location) return range; + if (!location) { + return range; + } + let original = range.original; + while (original && original !== location) { + original = original.original; + } + if (!original) { + setOriginalNode(range, location); + } + if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(getOriginalNode(location))) { + return setTextRange(range, location); + } + return range; + } + function symbolToNode(symbol, context, meaning) { + if (context.internalFlags & 1 /* WriteComputedProps */) { + if (symbol.valueDeclaration) { + const name = getNameOfDeclaration(symbol.valueDeclaration); + if (name && isComputedPropertyName(name)) return name; + } + const nameType = getSymbolLinks(symbol).nameType; + if (nameType && nameType.flags & (1024 /* EnumLiteral */ | 8192 /* UniqueESSymbol */)) { + context.enclosingDeclaration = nameType.symbol.valueDeclaration; + return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, meaning)); + } + } + return symbolToExpression(symbol, context, meaning); + } + function withContext(enclosingDeclaration, flags, internalFlags, tracker, cb) { + const moduleResolverHost = (tracker == null ? void 0 : tracker.trackSymbol) ? tracker.moduleResolverHost : (internalFlags || 0 /* None */) & 4 /* DoNotIncludeSymbolChain */ ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : void 0; + const context = { + enclosingDeclaration, + enclosingFile: enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration), + flags: flags || 0 /* None */, + internalFlags: internalFlags || 0 /* None */, + tracker: void 0, + encounteredError: false, + suppressReportInferenceFallback: false, + reportedDiagnostic: false, + visitedTypes: void 0, + symbolDepth: void 0, + inferTypeParameters: void 0, + approximateLength: 0, + trackedSymbols: void 0, + bundled: !!compilerOptions.outFile && !!enclosingDeclaration && isExternalOrCommonJsModule(getSourceFileOfNode(enclosingDeclaration)), + truncating: false, + usedSymbolNames: void 0, + remappedSymbolNames: void 0, + remappedSymbolReferences: void 0, + reverseMappedStack: void 0, + mustCreateTypeParameterSymbolList: true, + typeParameterSymbolList: void 0, + mustCreateTypeParametersNamesLookups: true, + typeParameterNames: void 0, + typeParameterNamesByText: void 0, + typeParameterNamesByTextNextNameCount: void 0, + enclosingSymbolTypes: /* @__PURE__ */ new Map(), + mapper: void 0 + }; + context.tracker = new SymbolTrackerImpl(context, tracker, moduleResolverHost); + const resultingNode = cb(context); + if (context.truncating && context.flags & 1 /* NoTruncation */) { + context.tracker.reportTruncationError(); + } + return context.encounteredError ? void 0 : resultingNode; + } + function addSymbolTypeToContext(context, symbol, type) { + const id = getSymbolId(symbol); + const oldType = context.enclosingSymbolTypes.get(id); + context.enclosingSymbolTypes.set(id, type); + return restore; + function restore() { + if (oldType) { + context.enclosingSymbolTypes.set(id, oldType); + } else { + context.enclosingSymbolTypes.delete(id); + } + } + } + function saveRestoreFlags(context) { + const flags = context.flags; + const internalFlags = context.internalFlags; + return restore; + function restore() { + context.flags = flags; + context.internalFlags = internalFlags; + } + } + function checkTruncationLength(context) { + if (context.truncating) return context.truncating; + return context.truncating = context.approximateLength > (context.flags & 1 /* NoTruncation */ ? noTruncationMaximumTruncationLength : defaultMaximumTruncationLength); + } + function typeToTypeNodeHelper(type, context) { + const restoreFlags = saveRestoreFlags(context); + const typeNode = typeToTypeNodeWorker(type, context); + restoreFlags(); + return typeNode; + } + function typeToTypeNodeWorker(type, context) { + var _a, _b; + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + const inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; + if (!type) { + if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + return void 0; + } + context.approximateLength += 3; + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + if (!(context.flags & 536870912 /* NoTypeReduction */)) { + type = getReducedType(type); + } + if (type.flags & 1 /* Any */) { + if (type.aliasSymbol) { + return factory.createTypeReferenceNode(symbolToEntityNameNode(type.aliasSymbol), mapToTypeNodes(type.aliasTypeArguments, context)); + } + if (type === unresolvedType) { + return addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "unresolved"); + } + context.approximateLength += 3; + return factory.createKeywordTypeNode(type === intrinsicMarkerType ? 141 /* IntrinsicKeyword */ : 133 /* AnyKeyword */); + } + if (type.flags & 2 /* Unknown */) { + return factory.createKeywordTypeNode(159 /* UnknownKeyword */); + } + if (type.flags & 4 /* String */) { + context.approximateLength += 6; + return factory.createKeywordTypeNode(154 /* StringKeyword */); + } + if (type.flags & 8 /* Number */) { + context.approximateLength += 6; + return factory.createKeywordTypeNode(150 /* NumberKeyword */); + } + if (type.flags & 64 /* BigInt */) { + context.approximateLength += 6; + return factory.createKeywordTypeNode(163 /* BigIntKeyword */); + } + if (type.flags & 16 /* Boolean */ && !type.aliasSymbol) { + context.approximateLength += 7; + return factory.createKeywordTypeNode(136 /* BooleanKeyword */); + } + if (type.flags & 1056 /* EnumLike */) { + if (type.symbol.flags & 8 /* EnumMember */) { + const parentSymbol = getParentOfSymbol(type.symbol); + const parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */); + if (getDeclaredTypeOfSymbol(parentSymbol) === type) { + return parentName; + } + const memberName = symbolName(type.symbol); + if (isIdentifierText(memberName, 1 /* ES5 */)) { + return appendReferenceToType( + parentName, + factory.createTypeReferenceNode( + memberName, + /*typeArguments*/ + void 0 + ) + ); + } + if (isImportTypeNode(parentName)) { + parentName.isTypeOf = true; + return factory.createIndexedAccessTypeNode(parentName, factory.createLiteralTypeNode(factory.createStringLiteral(memberName))); + } else if (isTypeReferenceNode(parentName)) { + return factory.createIndexedAccessTypeNode(factory.createTypeQueryNode(parentName.typeName), factory.createLiteralTypeNode(factory.createStringLiteral(memberName))); + } else { + return Debug.fail("Unhandled type node kind returned from `symbolToTypeNode`."); + } + } + return symbolToTypeNode(type.symbol, context, 788968 /* Type */); + } + if (type.flags & 128 /* StringLiteral */) { + context.approximateLength += type.value.length + 2; + return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */)); + } + if (type.flags & 256 /* NumberLiteral */) { + const value = type.value; + context.approximateLength += ("" + value).length; + return factory.createLiteralTypeNode(value < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-value)) : factory.createNumericLiteral(value)); + } + if (type.flags & 2048 /* BigIntLiteral */) { + context.approximateLength += pseudoBigIntToString(type.value).length + 1; + return factory.createLiteralTypeNode(factory.createBigIntLiteral(type.value)); + } + if (type.flags & 512 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; + return factory.createLiteralTypeNode(type.intrinsicName === "true" ? factory.createTrue() : factory.createFalse()); + } + if (type.flags & 8192 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; + return symbolToTypeNode(type.symbol, context, 111551 /* Value */); + } + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } + context.approximateLength += 13; + return factory.createTypeOperatorNode(158 /* UniqueKeyword */, factory.createKeywordTypeNode(155 /* SymbolKeyword */)); + } + if (type.flags & 16384 /* Void */) { + context.approximateLength += 4; + return factory.createKeywordTypeNode(116 /* VoidKeyword */); + } + if (type.flags & 32768 /* Undefined */) { + context.approximateLength += 9; + return factory.createKeywordTypeNode(157 /* UndefinedKeyword */); + } + if (type.flags & 65536 /* Null */) { + context.approximateLength += 4; + return factory.createLiteralTypeNode(factory.createNull()); + } + if (type.flags & 131072 /* Never */) { + context.approximateLength += 5; + return factory.createKeywordTypeNode(146 /* NeverKeyword */); + } + if (type.flags & 4096 /* ESSymbol */) { + context.approximateLength += 6; + return factory.createKeywordTypeNode(155 /* SymbolKeyword */); + } + if (type.flags & 67108864 /* NonPrimitive */) { + context.approximateLength += 6; + return factory.createKeywordTypeNode(151 /* ObjectKeyword */); + } + if (isThisTypeParameter(type)) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { + context.encounteredError = true; + } + (_b = (_a = context.tracker).reportInaccessibleThisError) == null ? void 0 : _b.call(_a); + } + context.approximateLength += 4; + return factory.createThisTypeNode(); + } + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { + const typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return factory.createTypeReferenceNode(factory.createIdentifier(""), typeArgumentNodes); + if (length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { + return factory.createArrayTypeNode(typeArgumentNodes[0]); + } + return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes); + } + const objectFlags = getObjectFlags(type); + if (objectFlags & 4 /* Reference */) { + Debug.assert(!!(type.flags & 524288 /* Object */)); + return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type); + } + if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 262144 /* TypeParameter */ && contains(context.inferTypeParameters, type)) { + context.approximateLength += symbolName(type.symbol).length + 6; + let constraintNode; + const constraint = getConstraintOfTypeParameter(type); + if (constraint) { + const inferredConstraint = getInferredTypeParameterConstraint( + type, + /*omitTypeReferences*/ + true + ); + if (!(inferredConstraint && isTypeIdenticalTo(constraint, inferredConstraint))) { + context.approximateLength += 9; + constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + } + } + return factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, constraintNode)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && type.flags & 262144 /* TypeParameter */) { + const name2 = typeParameterToName(type, context); + context.approximateLength += idText(name2).length; + return factory.createTypeReferenceNode( + factory.createIdentifier(idText(name2)), + /*typeArguments*/ + void 0 + ); + } + if (type.symbol) { + return symbolToTypeNode(type.symbol, context, 788968 /* Type */); + } + const name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? (type === markerSubTypeForCheck ? "sub-" : "super-") + symbolName(varianceTypeParameter.symbol) : "?"; + return factory.createTypeReferenceNode( + factory.createIdentifier(name), + /*typeArguments*/ + void 0 + ); + } + if (type.flags & 1048576 /* Union */ && type.origin) { + type = type.origin; + } + if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { + const types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } + const typeNodes = mapToTypeNodes( + types, + context, + /*isBareList*/ + true + ); + if (typeNodes && typeNodes.length > 0) { + return type.flags & 1048576 /* Union */ ? factory.createUnionTypeNode(typeNodes) : factory.createIntersectionTypeNode(typeNodes); + } else { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + } + return void 0; + } + } + if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { + Debug.assert(!!(type.flags & 524288 /* Object */)); + return createAnonymousTypeNode(type); + } + if (type.flags & 4194304 /* Index */) { + const indexedType = type.type; + context.approximateLength += 6; + const indexTypeNode = typeToTypeNodeHelper(indexedType, context); + return factory.createTypeOperatorNode(143 /* KeyOfKeyword */, indexTypeNode); + } + if (type.flags & 134217728 /* TemplateLiteral */) { + const texts = type.texts; + const types = type.types; + const templateHead = factory.createTemplateHead(texts[0]); + const templateSpans = factory.createNodeArray( + map(types, (t, i) => factory.createTemplateLiteralTypeSpan( + typeToTypeNodeHelper(t, context), + (i < types.length - 1 ? factory.createTemplateMiddle : factory.createTemplateTail)(texts[i + 1]) + )) + ); + context.approximateLength += 2; + return factory.createTemplateLiteralType(templateHead, templateSpans); + } + if (type.flags & 268435456 /* StringMapping */) { + const typeNode = typeToTypeNodeHelper(type.type, context); + return symbolToTypeNode(type.symbol, context, 788968 /* Type */, [typeNode]); + } + if (type.flags & 8388608 /* IndexedAccess */) { + const objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + const indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; + return factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + if (type.flags & 16777216 /* Conditional */) { + return visitAndTransformType(type, (type2) => conditionalTypeToTypeNode(type2)); + } + if (type.flags & 33554432 /* Substitution */) { + const typeNode = typeToTypeNodeHelper(type.baseType, context); + const noInferSymbol = isNoInferType(type) && getGlobalTypeSymbol( + "NoInfer", + /*reportErrors*/ + false + ); + return noInferSymbol ? symbolToTypeNode(noInferSymbol, context, 788968 /* Type */, [typeNode]) : typeNode; + } + return Debug.fail("Should be unreachable."); + function conditionalTypeToTypeNode(type2) { + const checkTypeNode = typeToTypeNodeHelper(type2.checkType, context); + context.approximateLength += 15; + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && type2.root.isDistributive && !(type2.checkType.flags & 262144 /* TypeParameter */)) { + const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); + const name = typeParameterToName(newParam, context); + const newTypeVariable = factory.createTypeReferenceNode(name); + context.approximateLength += 37; + const newMapper = prependTypeMapping(type2.root.checkType, newParam, type2.mapper); + const saveInferTypeParameters2 = context.inferTypeParameters; + context.inferTypeParameters = type2.root.inferTypeParameters; + const extendsTypeNode2 = typeToTypeNodeHelper(instantiateType(type2.root.extendsType, newMapper), context); + context.inferTypeParameters = saveInferTypeParameters2; + const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.trueType), newMapper)); + const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.falseType), newMapper)); + return factory.createConditionalTypeNode( + checkTypeNode, + factory.createInferTypeNode(factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + factory.cloneNode(newTypeVariable.typeName) + )), + factory.createConditionalTypeNode( + factory.createTypeReferenceNode(factory.cloneNode(name)), + typeToTypeNodeHelper(type2.checkType, context), + factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode2, trueTypeNode2, falseTypeNode2), + factory.createKeywordTypeNode(146 /* NeverKeyword */) + ), + factory.createKeywordTypeNode(146 /* NeverKeyword */) + ); + } + const saveInferTypeParameters = context.inferTypeParameters; + context.inferTypeParameters = type2.root.inferTypeParameters; + const extendsTypeNode = typeToTypeNodeHelper(type2.extendsType, context); + context.inferTypeParameters = saveInferTypeParameters; + const trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type2)); + const falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type2)); + return factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); + } + function typeToTypeNodeOrCircularityElision(type2) { + var _a2, _b2, _c; + if (type2.flags & 1048576 /* Union */) { + if ((_a2 = context.visitedTypes) == null ? void 0 : _a2.has(getTypeId(type2))) { + if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + (_c = (_b2 = context.tracker) == null ? void 0 : _b2.reportCyclicStructureError) == null ? void 0 : _c.call(_b2); + } + return createElidedInformationPlaceholder(context); + } + return visitAndTransformType(type2, (type3) => typeToTypeNodeHelper(type3, context)); + } + return typeToTypeNodeHelper(type2, context); + } + function isMappedTypeHomomorphic(type2) { + return !!getHomomorphicTypeVariable(type2); + } + function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) { + return !!type2.target && isMappedTypeHomomorphic(type2.target) && !isMappedTypeHomomorphic(type2); + } + function createMappedTypeNodeFromType(type2) { + var _a2; + Debug.assert(!!(type2.flags & 524288 /* Object */)); + const readonlyToken = type2.declaration.readonlyToken ? factory.createToken(type2.declaration.readonlyToken.kind) : void 0; + const questionToken = type2.declaration.questionToken ? factory.createToken(type2.declaration.questionToken.kind) : void 0; + let appropriateConstraintTypeNode; + let newTypeVariable; + const needsModifierPreservingWrapper = !isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & 2 /* Unknown */) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && !(getConstraintTypeFromMappedType(type2).flags & 262144 /* TypeParameter */ && ((_a2 = getConstraintOfTypeParameter(getConstraintTypeFromMappedType(type2))) == null ? void 0 : _a2.flags) & 4194304 /* Index */); + if (isMappedTypeWithKeyofConstraintDeclaration(type2)) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { + const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); + const name = typeParameterToName(newParam, context); + newTypeVariable = factory.createTypeReferenceNode(name); + } + appropriateConstraintTypeNode = factory.createTypeOperatorNode(143 /* KeyOfKeyword */, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)); + } else if (needsModifierPreservingWrapper) { + const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T")); + const name = typeParameterToName(newParam, context); + newTypeVariable = factory.createTypeReferenceNode(name); + appropriateConstraintTypeNode = newTypeVariable; + } else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context); + } + const typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type2), context, appropriateConstraintTypeNode); + const nameTypeNode = type2.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type2), context) : void 0; + const templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type2), !!(getMappedTypeModifiers(type2) & 4 /* IncludeOptional */)), context); + const mappedTypeNode = factory.createMappedTypeNode( + readonlyToken, + typeParameterNode, + nameTypeNode, + questionToken, + templateTypeNode, + /*members*/ + void 0 + ); + context.approximateLength += 10; + const result = setEmitFlags(mappedTypeNode, 1 /* SingleLine */); + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { + const originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode2(context, type2.declaration.typeParameter.constraint.type)) || unknownType, type2.mapper); + return factory.createConditionalTypeNode( + typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context), + factory.createInferTypeNode(factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + factory.cloneNode(newTypeVariable.typeName), + originalConstraint.flags & 2 /* Unknown */ ? void 0 : typeToTypeNodeHelper(originalConstraint, context) + )), + result, + factory.createKeywordTypeNode(146 /* NeverKeyword */) + ); + } else if (needsModifierPreservingWrapper) { + return factory.createConditionalTypeNode( + typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context), + factory.createInferTypeNode(factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + factory.cloneNode(newTypeVariable.typeName), + factory.createTypeOperatorNode(143 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)) + )), + result, + factory.createKeywordTypeNode(146 /* NeverKeyword */) + ); + } + return result; + } + function createAnonymousTypeNode(type2) { + var _a2, _b2; + const typeId = type2.id; + const symbol = type2.symbol; + if (symbol) { + const isInstantiationExpressionType = !!(getObjectFlags(type2) & 8388608 /* InstantiationExpressionType */); + if (isInstantiationExpressionType) { + const instantiationExpressionType = type2; + const existing = instantiationExpressionType.node; + if (isTypeQueryNode(existing) && getTypeFromTypeNode2(context, existing) === type2) { + const typeNode = syntacticNodeBuilder.tryReuseExistingTypeNode(context, existing); + if (typeNode) { + return typeNode; + } + } + if ((_a2 = context.visitedTypes) == null ? void 0 : _a2.has(typeId)) { + return createElidedInformationPlaceholder(context); + } + return visitAndTransformType(type2, createTypeNodeFromObjectType); + } + const isInstanceType = isClassInstanceSide(type2) ? 788968 /* Type */ : 111551 /* Value */; + if (isJSConstructor(symbol.valueDeclaration)) { + return symbolToTypeNode(symbol, context, isInstanceType); + } else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible( + symbol, + context.enclosingDeclaration, + isInstanceType, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility !== 0 /* Accessible */)) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { + return symbolToTypeNode(symbol, context, isInstanceType); + } else if ((_b2 = context.visitedTypes) == null ? void 0 : _b2.has(typeId)) { + const typeAlias = getTypeAliasForTypeLiteral(type2); + if (typeAlias) { + return symbolToTypeNode(typeAlias, context, 788968 /* Type */); + } else { + return createElidedInformationPlaceholder(context); + } + } else { + return visitAndTransformType(type2, createTypeNodeFromObjectType); + } + } else { + return createTypeNodeFromObjectType(type2); + } + function shouldWriteTypeOfFunctionSymbol() { + var _a3; + const isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method + some(symbol.declarations, (declaration) => isStatic(declaration) && !isLateBindableIndexSignature(getNameOfDeclaration(declaration))); + const isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol + forEach(symbol.declarations, (declaration) => declaration.parent.kind === 307 /* SourceFile */ || declaration.parent.kind === 268 /* ModuleBlock */)); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ((_a3 = context.visitedTypes) == null ? void 0 : _a3.has(typeId))) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); + } + } + } + function visitAndTransformType(type2, transform) { + var _a2, _b2, _c; + const typeId = type2.id; + const isConstructorObject = getObjectFlags(type2) & 16 /* Anonymous */ && type2.symbol && type2.symbol.flags & 32 /* Class */; + const id = getObjectFlags(type2) & 4 /* Reference */ && type2.node ? "N" + getNodeId(type2.node) : type2.flags & 16777216 /* Conditional */ ? "N" + getNodeId(type2.root.node) : type2.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type2.symbol) : void 0; + if (!context.visitedTypes) { + context.visitedTypes = /* @__PURE__ */ new Set(); + } + if (id && !context.symbolDepth) { + context.symbolDepth = /* @__PURE__ */ new Map(); + } + const links = context.enclosingDeclaration && getNodeLinks(context.enclosingDeclaration); + const key = `${getTypeId(type2)}|${context.flags}|${context.internalFlags}`; + if (links) { + links.serializedTypes || (links.serializedTypes = /* @__PURE__ */ new Map()); + } + const cachedResult = (_a2 = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _a2.get(key); + if (cachedResult) { + (_b2 = cachedResult.trackedSymbols) == null ? void 0 : _b2.forEach( + ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol( + symbol, + enclosingDeclaration, + meaning + ) + ); + if (cachedResult.truncating) { + context.truncating = true; + } + context.approximateLength += cachedResult.addedLength; + return deepCloneOrReuseNode(cachedResult.node); + } + let depth; + if (id) { + depth = context.symbolDepth.get(id) || 0; + if (depth > 10) { + return createElidedInformationPlaceholder(context); + } + context.symbolDepth.set(id, depth + 1); + } + context.visitedTypes.add(typeId); + const prevTrackedSymbols = context.trackedSymbols; + context.trackedSymbols = void 0; + const startLength = context.approximateLength; + const result = transform(type2); + const addedLength = context.approximateLength - startLength; + if (!context.reportedDiagnostic && !context.encounteredError) { + (_c = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _c.set(key, { + node: result, + truncating: context.truncating, + addedLength, + trackedSymbols: context.trackedSymbols + }); + } + context.visitedTypes.delete(typeId); + if (id) { + context.symbolDepth.set(id, depth); + } + context.trackedSymbols = prevTrackedSymbols; + return result; + function deepCloneOrReuseNode(node) { + if (!nodeIsSynthesized(node) && getParseTreeNode(node) === node) { + return node; + } + return setTextRange2(context, factory.cloneNode(visitEachChild( + node, + deepCloneOrReuseNode, + /*context*/ + void 0, + deepCloneOrReuseNodes, + deepCloneOrReuseNode + )), node); + } + function deepCloneOrReuseNodes(nodes, visitor, test, start, count) { + if (nodes && nodes.length === 0) { + return setTextRange(factory.createNodeArray( + /*elements*/ + void 0, + nodes.hasTrailingComma + ), nodes); + } + return visitNodes2(nodes, visitor, test, start, count); + } + } + function createTypeNodeFromObjectType(type2) { + if (isGenericMappedType(type2) || type2.containsError) { + return createMappedTypeNodeFromType(type2); + } + const resolved = resolveStructuredTypeMembers(type2); + if (!resolved.properties.length && !resolved.indexInfos.length) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; + return setEmitFlags(factory.createTypeLiteralNode( + /*members*/ + void 0 + ), 1 /* SingleLine */); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + const signature = resolved.callSignatures[0]; + const signatureNode = signatureToSignatureDeclarationHelper(signature, 184 /* FunctionType */, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + const signature = resolved.constructSignatures[0]; + const signatureNode = signatureToSignatureDeclarationHelper(signature, 185 /* ConstructorType */, context); + return signatureNode; + } + } + const abstractSignatures = filter(resolved.constructSignatures, (signature) => !!(signature.flags & 4 /* Abstract */)); + if (some(abstractSignatures)) { + const types = map(abstractSignatures, (s) => getOrCreateTypeFromSignature(s)); + const typeElementCount = resolved.callSignatures.length + (resolved.constructSignatures.length - abstractSignatures.length) + resolved.indexInfos.length + // exclude `prototype` when writing a class expression as a type literal, as per + // the logic in `createTypeNodesFromResolvedType`. + (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ ? countWhere(resolved.properties, (p) => !(p.flags & 4194304 /* Prototype */)) : length(resolved.properties)); + if (typeElementCount) { + types.push(getResolvedTypeWithoutAbstractConstructSignatures(resolved)); + } + return typeToTypeNodeHelper(getIntersectionType(types), context); + } + const restoreFlags = saveRestoreFlags(context); + context.flags |= 4194304 /* InObjectTypeLiteral */; + const members = createTypeNodesFromResolvedType(resolved); + restoreFlags(); + const typeLiteralNode = factory.createTypeLiteralNode(members); + context.approximateLength += 2; + setEmitFlags(typeLiteralNode, context.flags & 1024 /* MultilineObjectLiterals */ ? 0 : 1 /* SingleLine */); + return typeLiteralNode; + } + function typeReferenceToTypeNode(type2) { + let typeArguments = getTypeArguments(type2); + if (type2.target === globalArrayType || type2.target === globalReadonlyArrayType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { + const typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); + return factory.createTypeReferenceNode(type2.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]); + } + const elementType = typeToTypeNodeHelper(typeArguments[0], context); + const arrayType = factory.createArrayTypeNode(elementType); + return type2.target === globalArrayType ? arrayType : factory.createTypeOperatorNode(148 /* ReadonlyKeyword */, arrayType); + } else if (type2.target.objectFlags & 8 /* Tuple */) { + typeArguments = sameMap(typeArguments, (t, i) => removeMissingType(t, !!(type2.target.elementFlags[i] & 2 /* Optional */))); + if (typeArguments.length > 0) { + const arity = getTypeReferenceArity(type2); + const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + if (tupleConstituentNodes) { + const { labeledElementDeclarations } = type2.target; + for (let i = 0; i < tupleConstituentNodes.length; i++) { + const flags = type2.target.elementFlags[i]; + const labeledElementDeclaration = labeledElementDeclarations == null ? void 0 : labeledElementDeclarations[i]; + if (labeledElementDeclaration) { + tupleConstituentNodes[i] = factory.createNamedTupleMember( + flags & 12 /* Variable */ ? factory.createToken(26 /* DotDotDotToken */) : void 0, + factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel(labeledElementDeclaration))), + flags & 2 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, + flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i] + ); + } else { + tupleConstituentNodes[i] = flags & 12 /* Variable */ ? factory.createRestTypeNode(flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : flags & 2 /* Optional */ ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]; + } + } + const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode(tupleConstituentNodes), 1 /* SingleLine */); + return type2.target.readonly ? factory.createTypeOperatorNode(148 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode; + } + } + if (context.encounteredError || context.flags & 524288 /* AllowEmptyTuple */) { + const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode([]), 1 /* SingleLine */); + return type2.target.readonly ? factory.createTypeOperatorNode(148 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode; + } + context.encounteredError = true; + return void 0; + } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type2.symbol.valueDeclaration && isClassLike(type2.symbol.valueDeclaration) && !isValueSymbolAccessible(type2.symbol, context.enclosingDeclaration)) { + return createAnonymousTypeNode(type2); + } else { + const outerTypeParameters = type2.target.outerTypeParameters; + let i = 0; + let resultType; + if (outerTypeParameters) { + const length2 = outerTypeParameters.length; + while (i < length2) { + const start = i; + const parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { + const typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); + const restoreFlags2 = saveRestoreFlags(context); + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + const ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice); + restoreFlags2(); + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); + } + } + } + let typeArgumentNodes; + if (typeArguments.length > 0) { + let typeParameterCount = 0; + if (type2.target.typeParameters) { + typeParameterCount = Math.min(type2.target.typeParameters.length, typeArguments.length); + if (isReferenceToType(type2, getGlobalIterableType( + /*reportErrors*/ + false + )) || isReferenceToType(type2, getGlobalIterableIteratorType( + /*reportErrors*/ + false + )) || isReferenceToType(type2, getGlobalAsyncIterableType( + /*reportErrors*/ + false + )) || isReferenceToType(type2, getGlobalAsyncIterableIteratorType( + /*reportErrors*/ + false + ))) { + if (!type2.node || !isTypeReferenceNode(type2.node) || !type2.node.typeArguments || type2.node.typeArguments.length < typeParameterCount) { + while (typeParameterCount > 0) { + const typeArgument = typeArguments[typeParameterCount - 1]; + const typeParameter = type2.target.typeParameters[typeParameterCount - 1]; + const defaultType = getDefaultFromTypeParameter(typeParameter); + if (!defaultType || !isTypeIdenticalTo(typeArgument, defaultType)) { + break; + } + typeParameterCount--; + } + } + } + } + typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); + } + const restoreFlags = saveRestoreFlags(context); + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + const finalRef = symbolToTypeNode(type2.symbol, context, 788968 /* Type */, typeArgumentNodes); + restoreFlags(); + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); + } + } + function appendReferenceToType(root, ref) { + if (isImportTypeNode(root)) { + let typeArguments = root.typeArguments; + let qualifier = root.qualifier; + if (qualifier) { + if (isIdentifier(qualifier)) { + if (typeArguments !== getIdentifierTypeArguments(qualifier)) { + qualifier = setIdentifierTypeArguments(factory.cloneNode(qualifier), typeArguments); + } + } else { + if (typeArguments !== getIdentifierTypeArguments(qualifier.right)) { + qualifier = factory.updateQualifiedName(qualifier, qualifier.left, setIdentifierTypeArguments(factory.cloneNode(qualifier.right), typeArguments)); + } + } + } + typeArguments = ref.typeArguments; + const ids = getAccessStack(ref); + for (const id of ids) { + qualifier = qualifier ? factory.createQualifiedName(qualifier, id) : id; + } + return factory.updateImportTypeNode( + root, + root.argument, + root.attributes, + qualifier, + typeArguments, + root.isTypeOf + ); + } else { + let typeArguments = root.typeArguments; + let typeName = root.typeName; + if (isIdentifier(typeName)) { + if (typeArguments !== getIdentifierTypeArguments(typeName)) { + typeName = setIdentifierTypeArguments(factory.cloneNode(typeName), typeArguments); + } + } else { + if (typeArguments !== getIdentifierTypeArguments(typeName.right)) { + typeName = factory.updateQualifiedName(typeName, typeName.left, setIdentifierTypeArguments(factory.cloneNode(typeName.right), typeArguments)); + } + } + typeArguments = ref.typeArguments; + const ids = getAccessStack(ref); + for (const id of ids) { + typeName = factory.createQualifiedName(typeName, id); + } + return factory.updateTypeReferenceNode( + root, + typeName, + typeArguments + ); + } + } + function getAccessStack(ref) { + let state = ref.typeName; + const ids = []; + while (!isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; + } + function indexInfoToObjectComputedNamesOrSignatureDeclaration(indexInfo, context2, typeNode) { + if (indexInfo.components) { + const allComponentComputedNamesSerializable = every(indexInfo.components, (e) => { + var _a2; + return !!(e.name && isComputedPropertyName(e.name) && isEntityNameExpression(e.name.expression) && context2.enclosingDeclaration && ((_a2 = isEntityNameVisible( + e.name.expression, + context2.enclosingDeclaration, + /*shouldComputeAliasToMakeVisible*/ + false + )) == null ? void 0 : _a2.accessibility) === 0 /* Accessible */); + }); + if (allComponentComputedNamesSerializable) { + const newComponents = filter(indexInfo.components, (e) => { + return !hasLateBindableName(e); + }); + return map(newComponents, (e) => { + trackComputedName(e.name.expression, context2.enclosingDeclaration, context2); + return setTextRange2( + context2, + factory.createPropertySignature( + indexInfo.isReadonly ? [factory.createModifier(148 /* ReadonlyKeyword */)] : void 0, + e.name, + (isPropertySignature(e) || isPropertyDeclaration(e) || isMethodSignature(e) || isMethodDeclaration(e) || isGetAccessor(e) || isSetAccessor(e)) && e.questionToken ? factory.createToken(58 /* QuestionToken */) : void 0, + typeNode || typeToTypeNodeHelper(getTypeOfSymbol(e.symbol), context2) + ), + e + ); + }); + } + } + return [indexInfoToIndexSignatureDeclarationHelper(indexInfo, context2, typeNode)]; + } + function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + if (context.flags & 1 /* NoTruncation */) { + return [addSyntheticTrailingComment(factory.createNotEmittedTypeElement(), 3 /* MultiLineCommentTrivia */, "elided")]; + } + return [factory.createPropertySignature( + /*modifiers*/ + void 0, + "...", + /*questionToken*/ + void 0, + /*type*/ + void 0 + )]; + } + const typeElements = []; + for (const signature of resolvedType.callSignatures) { + typeElements.push(signatureToSignatureDeclarationHelper(signature, 179 /* CallSignature */, context)); + } + for (const signature of resolvedType.constructSignatures) { + if (signature.flags & 4 /* Abstract */) continue; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 180 /* ConstructSignature */, context)); + } + for (const info of resolvedType.indexInfos) { + typeElements.push(...indexInfoToObjectComputedNamesOrSignatureDeclaration(info, context, resolvedType.objectFlags & 1024 /* ReverseMapped */ ? createElidedInformationPlaceholder(context) : void 0)); + } + const properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + let i = 0; + for (const propertySymbol of properties) { + i++; + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (getDeclarationModifierFlagsFromSymbol(propertySymbol) & (2 /* Private */ | 4 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + if (checkTruncationLength(context) && i + 2 < properties.length - 1) { + if (context.flags & 1 /* NoTruncation */) { + const typeElement = typeElements.pop(); + typeElements.push(addSyntheticTrailingComment(typeElement, 3 /* MultiLineCommentTrivia */, `... ${properties.length - i} more elided ...`)); + } else { + typeElements.push(factory.createPropertySignature( + /*modifiers*/ + void 0, + `... ${properties.length - i} more ...`, + /*questionToken*/ + void 0, + /*type*/ + void 0 + )); + } + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; + } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : void 0; + } + } + function createElidedInformationPlaceholder(context) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return factory.createTypeReferenceNode( + factory.createIdentifier("..."), + /*typeArguments*/ + void 0 + ); + } + return addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "elided"); + } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + const depth = 3; + return !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) && (contains(context.reverseMappedStack, propertySymbol) || ((_a = context.reverseMappedStack) == null ? void 0 : _a[0]) && !(getObjectFlags(last(context.reverseMappedStack).links.propertyType) & 16 /* Anonymous */) || isDeeplyNestedReverseMappedTypeProperty()); + function isDeeplyNestedReverseMappedTypeProperty() { + var _a2; + if ((((_a2 = context.reverseMappedStack) == null ? void 0 : _a2.length) ?? 0) < depth) { + return false; + } + for (let i = 0; i < depth; i++) { + const prop = context.reverseMappedStack[context.reverseMappedStack.length - 1 - i]; + if (prop.links.mappedType.symbol !== propertySymbol.links.mappedType.symbol) { + return false; + } + } + return true; + } + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var _a; + const propertyIsReverseMapped = !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); + const propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getNonMissingTypeOfSymbol(propertySymbol); + const saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = void 0; + if (context.tracker.canTrackSymbol && isLateBoundName(propertySymbol.escapedName)) { + if (propertySymbol.declarations) { + const decl = first(propertySymbol.declarations); + if (hasLateBindableName(decl)) { + if (isBinaryExpression(decl)) { + const name = getNameOfDeclaration(decl); + if (name && isElementAccessExpression(name) && isPropertyAccessEntityNameExpression(name.argumentExpression)) { + trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context); + } + } else { + trackComputedName(decl.name.expression, saveEnclosingDeclaration, context); + } + } + } else { + context.tracker.reportNonSerializableProperty(symbolToString(propertySymbol)); + } + } + context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) == null ? void 0 : _a[0]) || saveEnclosingDeclaration; + const propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.enclosingDeclaration = saveEnclosingDeclaration; + context.approximateLength += symbolName(propertySymbol).length + 1; + if (propertySymbol.flags & 98304 /* Accessor */) { + const writeType = getWriteTypeOfSymbol(propertySymbol); + if (propertyType !== writeType && !isErrorType(propertyType) && !isErrorType(writeType)) { + const symbolMapper = getSymbolLinks(propertySymbol).mapper; + const getterDeclaration = getDeclarationOfKind(propertySymbol, 177 /* GetAccessor */); + const getterSignature = getSignatureFromDeclaration(getterDeclaration); + typeElements.push( + setCommentRange2( + context, + signatureToSignatureDeclarationHelper(symbolMapper ? instantiateSignature(getterSignature, symbolMapper) : getterSignature, 177 /* GetAccessor */, context, { name: propertyName }), + getterDeclaration + ) + ); + const setterDeclaration = getDeclarationOfKind(propertySymbol, 178 /* SetAccessor */); + const setterSignature = getSignatureFromDeclaration(setterDeclaration); + typeElements.push( + setCommentRange2( + context, + signatureToSignatureDeclarationHelper(symbolMapper ? instantiateSignature(setterSignature, symbolMapper) : setterSignature, 178 /* SetAccessor */, context, { name: propertyName }), + setterDeclaration + ) + ); + return; + } + } + const optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { + const signatures = getSignaturesOfType(filterType(propertyType, (t) => !(t.flags & 32768 /* Undefined */)), 0 /* Call */); + for (const signature of signatures) { + const methodDeclaration = signatureToSignatureDeclarationHelper(signature, 173 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); + typeElements.push(preserveCommentsOn(methodDeclaration, signature.declaration || propertySymbol.valueDeclaration)); + } + if (signatures.length || !optionalToken) { + return; + } + } + let propertyTypeNode; + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { + propertyTypeNode = createElidedInformationPlaceholder(context); + } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } + propertyTypeNode = propertyType ? serializeTypeForDeclaration( + context, + /*declaration*/ + void 0, + propertyType, + propertySymbol + ) : factory.createKeywordTypeNode(133 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } + } + const modifiers = isReadonlySymbol(propertySymbol) ? [factory.createToken(148 /* ReadonlyKeyword */)] : void 0; + if (modifiers) { + context.approximateLength += 9; + } + const propertySignature = factory.createPropertySignature( + modifiers, + propertyName, + optionalToken, + propertyTypeNode + ); + typeElements.push(preserveCommentsOn(propertySignature, propertySymbol.valueDeclaration)); + function preserveCommentsOn(node, range) { + var _a2; + const jsdocPropertyTag = (_a2 = propertySymbol.declarations) == null ? void 0 : _a2.find((d) => d.kind === 348 /* JSDocPropertyTag */); + if (jsdocPropertyTag) { + const commentText = getTextOfJSDocComment(jsdocPropertyTag.comment); + if (commentText) { + setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); + } + } else if (range) { + setCommentRange2(context, node, range); + } + return node; + } + } + function setCommentRange2(context, node, range) { + if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(range)) { + return setCommentRange(node, range); + } + return node; + } + function mapToTypeNodes(types, context, isBareList) { + if (some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ + context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "elided") : factory.createTypeReferenceNode( + "...", + /*typeArguments*/ + void 0 + ) + ]; + } else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, `... ${types.length - 2} more elided ...`) : factory.createTypeReferenceNode( + `... ${types.length - 2} more ...`, + /*typeArguments*/ + void 0 + ), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } + const mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); + const seenNames = mayHaveNameCollisions ? createMultiMap() : void 0; + const result = []; + let i = 0; + for (const type of types) { + i++; + if (checkTruncationLength(context) && i + 2 < types.length - 1) { + result.push( + context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, `... ${types.length - i} more elided ...`) : factory.createTypeReferenceNode( + `... ${types.length - i} more ...`, + /*typeArguments*/ + void 0 + ) + ); + const typeNode2 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode2) { + result.push(typeNode2); + } + break; + } + context.approximateLength += 2; + const typeNode = typeToTypeNodeHelper(type, context); + if (typeNode) { + result.push(typeNode); + if (seenNames && isIdentifierTypeReference(typeNode)) { + seenNames.add(typeNode.typeName.escapedText, [type, result.length - 1]); + } + } + } + if (seenNames) { + const restoreFlags = saveRestoreFlags(context); + context.flags |= 64 /* UseFullyQualifiedType */; + seenNames.forEach((types2) => { + if (!arrayIsHomogeneous(types2, ([a], [b]) => typesAreSameReference(a, b))) { + for (const [type, resultIndex] of types2) { + result[resultIndex] = typeToTypeNodeHelper(type, context); + } + } + }); + restoreFlags(); + } + return result; + } + } + function typesAreSameReference(a, b) { + return a === b || !!a.symbol && a.symbol === b.symbol || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol; + } + function indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, typeNode) { + const name = getNameFromIndexInfo(indexInfo) || "x"; + const indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context); + const indexingParameter = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + name, + /*questionToken*/ + void 0, + indexerTypeNode, + /*initializer*/ + void 0 + ); + if (!typeNode) { + typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); + } + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } + context.approximateLength += name.length + 4; + return factory.createIndexSignature( + indexInfo.isReadonly ? [factory.createToken(148 /* ReadonlyKeyword */)] : void 0, + [indexingParameter], + typeNode + ); + } + function signatureToSignatureDeclarationHelper(signature, kind, context, options) { + var _a; + let typeParameters; + let typeArguments; + const expandedParams = getExpandedParameters( + signature, + /*skipUnionExpanding*/ + true + )[0]; + const cleanup = enterNewScope(context, signature.declaration, expandedParams, signature.typeParameters, signature.parameters, signature.mapper); + context.approximateLength += 3; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map((parameter) => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context)); + } else { + typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context)); + } + const restoreFlags = saveRestoreFlags(context); + context.flags &= ~256 /* SuppressAnyReturnType */; + const parameters = (some(expandedParams, (p) => p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */)) ? signature.parameters : expandedParams).map((parameter) => symbolToParameterDeclaration(parameter, context, kind === 176 /* Constructor */)); + const thisParameter = context.flags & 33554432 /* OmitThisParameter */ ? void 0 : tryGetThisParameterDeclaration(signature, context); + if (thisParameter) { + parameters.unshift(thisParameter); + } + restoreFlags(); + const returnTypeNode = serializeReturnTypeForSignature(context, signature); + let modifiers = options == null ? void 0 : options.modifiers; + if (kind === 185 /* ConstructorType */ && signature.flags & 4 /* Abstract */) { + const flags = modifiersToFlags(modifiers); + modifiers = factory.createModifiersFromModifierFlags(flags | 64 /* Abstract */); + } + const node = kind === 179 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 180 /* ConstructSignature */ ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 173 /* MethodSignature */ ? factory.createMethodSignature(modifiers, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), options == null ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : kind === 174 /* MethodDeclaration */ ? factory.createMethodDeclaration( + modifiers, + /*asteriskToken*/ + void 0, + (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), + /*questionToken*/ + void 0, + typeParameters, + parameters, + returnTypeNode, + /*body*/ + void 0 + ) : kind === 176 /* Constructor */ ? factory.createConstructorDeclaration( + modifiers, + parameters, + /*body*/ + void 0 + ) : kind === 177 /* GetAccessor */ ? factory.createGetAccessorDeclaration( + modifiers, + (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), + parameters, + returnTypeNode, + /*body*/ + void 0 + ) : kind === 178 /* SetAccessor */ ? factory.createSetAccessorDeclaration( + modifiers, + (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), + parameters, + /*body*/ + void 0 + ) : kind === 181 /* IndexSignature */ ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 /* JSDocFunctionType */ ? factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 184 /* FunctionType */ ? factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 185 /* ConstructorType */ ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 262 /* FunctionDeclaration */ ? factory.createFunctionDeclaration( + modifiers, + /*asteriskToken*/ + void 0, + (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), + typeParameters, + parameters, + returnTypeNode, + /*body*/ + void 0 + ) : kind === 218 /* FunctionExpression */ ? factory.createFunctionExpression( + modifiers, + /*asteriskToken*/ + void 0, + (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), + typeParameters, + parameters, + returnTypeNode, + factory.createBlock([]) + ) : kind === 219 /* ArrowFunction */ ? factory.createArrowFunction( + modifiers, + typeParameters, + parameters, + returnTypeNode, + /*equalsGreaterThanToken*/ + void 0, + factory.createBlock([]) + ) : Debug.assertNever(kind); + if (typeArguments) { + node.typeArguments = factory.createNodeArray(typeArguments); + } + if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 323 /* JSDocSignature */ && signature.declaration.parent.kind === 339 /* JSDocOverloadTag */) { + const comment = getTextOfNode( + signature.declaration.parent.parent, + /*includeTrivia*/ + true + ).slice(2, -2).split(/\r\n|\n|\r/).map((line) => line.replace(/^\s+/, " ")).join("\n"); + addSyntheticLeadingComment( + node, + 3 /* MultiLineCommentTrivia */, + comment, + /*hasTrailingNewLine*/ + true + ); + } + cleanup == null ? void 0 : cleanup(); + return node; + } + function createRecoveryBoundary(context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + let trackedSymbols; + let unreportedErrors; + let hadError = false; + const oldTracker = context.tracker; + const oldTrackedSymbols = context.trackedSymbols; + context.trackedSymbols = void 0; + const oldEncounteredError = context.encounteredError; + context.tracker = new SymbolTrackerImpl(context, { + ...oldTracker.inner, + reportCyclicStructureError() { + markError(() => oldTracker.reportCyclicStructureError()); + }, + reportInaccessibleThisError() { + markError(() => oldTracker.reportInaccessibleThisError()); + }, + reportInaccessibleUniqueSymbolError() { + markError(() => oldTracker.reportInaccessibleUniqueSymbolError()); + }, + reportLikelyUnsafeImportRequiredError(specifier) { + markError(() => oldTracker.reportLikelyUnsafeImportRequiredError(specifier)); + }, + reportNonSerializableProperty(name) { + markError(() => oldTracker.reportNonSerializableProperty(name)); + }, + reportPrivateInBaseOfClassExpression(propertyName) { + markError(() => oldTracker.reportPrivateInBaseOfClassExpression(propertyName)); + }, + trackSymbol(sym, decl, meaning) { + (trackedSymbols ?? (trackedSymbols = [])).push([sym, decl, meaning]); + return false; + }, + moduleResolverHost: context.tracker.moduleResolverHost + }, context.tracker.moduleResolverHost); + return { + startRecoveryScope, + finalizeBoundary, + markError, + hadError: () => hadError + }; + function markError(unreportedError) { + hadError = true; + if (unreportedError) { + (unreportedErrors ?? (unreportedErrors = [])).push(unreportedError); + } + } + function startRecoveryScope() { + const trackedSymbolsTop = (trackedSymbols == null ? void 0 : trackedSymbols.length) ?? 0; + const unreportedErrorsTop = (unreportedErrors == null ? void 0 : unreportedErrors.length) ?? 0; + return () => { + hadError = false; + if (trackedSymbols) { + trackedSymbols.length = trackedSymbolsTop; + } + if (unreportedErrors) { + unreportedErrors.length = unreportedErrorsTop; + } + }; + } + function finalizeBoundary() { + context.tracker = oldTracker; + context.trackedSymbols = oldTrackedSymbols; + context.encounteredError = oldEncounteredError; + unreportedErrors == null ? void 0 : unreportedErrors.forEach((fn) => fn()); + if (hadError) { + return false; + } + trackedSymbols == null ? void 0 : trackedSymbols.forEach( + ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol( + symbol, + enclosingDeclaration, + meaning + ) + ); + return true; + } + } + function enterNewScope(context, declaration, expandedParams, typeParameters, originalParameters, mapper) { + const cleanupContext = cloneNodeBuilderContext(context); + let cleanupParams; + let cleanupTypeParams; + const oldEnclosingDecl = context.enclosingDeclaration; + const oldMapper = context.mapper; + if (mapper) { + context.mapper = mapper; + } + if (context.enclosingDeclaration && declaration) { + let pushFakeScope2 = function(kind, addAll) { + Debug.assert(context.enclosingDeclaration); + let existingFakeScope; + if (getNodeLinks(context.enclosingDeclaration).fakeScopeForSignatureDeclaration === kind) { + existingFakeScope = context.enclosingDeclaration; + } else if (context.enclosingDeclaration.parent && getNodeLinks(context.enclosingDeclaration.parent).fakeScopeForSignatureDeclaration === kind) { + existingFakeScope = context.enclosingDeclaration.parent; + } + Debug.assertOptionalNode(existingFakeScope, isBlock); + const locals = (existingFakeScope == null ? void 0 : existingFakeScope.locals) ?? createSymbolTable(); + let newLocals; + let oldLocals; + addAll((name, symbol) => { + if (existingFakeScope) { + const oldSymbol = locals.get(name); + if (!oldSymbol) { + newLocals = append(newLocals, name); + } else { + oldLocals = append(oldLocals, { name, oldSymbol }); + } + } + locals.set(name, symbol); + }); + if (!existingFakeScope) { + const fakeScope = factory.createBlock(emptyArray); + getNodeLinks(fakeScope).fakeScopeForSignatureDeclaration = kind; + fakeScope.locals = locals; + setParent(fakeScope, context.enclosingDeclaration); + context.enclosingDeclaration = fakeScope; + } else { + return function undo() { + forEach(newLocals, (s) => locals.delete(s)); + forEach(oldLocals, (s) => locals.set(s.name, s.oldSymbol)); + }; + } + }; + var pushFakeScope = pushFakeScope2; + cleanupParams = !some(expandedParams) ? void 0 : pushFakeScope2( + "params", + (add) => { + if (!expandedParams) return; + for (let pIndex = 0; pIndex < expandedParams.length; pIndex++) { + const param = expandedParams[pIndex]; + const originalParam = originalParameters == null ? void 0 : originalParameters[pIndex]; + if (originalParameters && originalParam !== param) { + add(param.escapedName, unknownSymbol); + if (originalParam) { + add(originalParam.escapedName, unknownSymbol); + } + } else if (!forEach(param.declarations, (d) => { + if (isParameter(d) && isBindingPattern(d.name)) { + bindPattern(d.name); + return true; + } + return void 0; + function bindPattern(p) { + forEach(p.elements, (e) => { + switch (e.kind) { + case 232 /* OmittedExpression */: + return; + case 208 /* BindingElement */: + return bindElement(e); + default: + return Debug.assertNever(e); + } + }); + } + function bindElement(e) { + if (isBindingPattern(e.name)) { + return bindPattern(e.name); + } + const symbol = getSymbolOfDeclaration(e); + add(symbol.escapedName, symbol); + } + })) { + add(param.escapedName, param); + } + } + } + ); + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && some(typeParameters)) { + cleanupTypeParams = pushFakeScope2( + "typeParams", + (add) => { + for (const typeParam of typeParameters ?? emptyArray) { + const typeParamName = typeParameterToName(typeParam, context).escapedText; + add(typeParamName, typeParam.symbol); + } + } + ); + } + } + return () => { + cleanupParams == null ? void 0 : cleanupParams(); + cleanupTypeParams == null ? void 0 : cleanupTypeParams(); + cleanupContext(); + context.enclosingDeclaration = oldEnclosingDecl; + context.mapper = oldMapper; + }; + } + function tryGetThisParameterDeclaration(signature, context) { + if (signature.thisParameter) { + return symbolToParameterDeclaration(signature.thisParameter, context); + } + if (signature.declaration && isInJSFile(signature.declaration)) { + const thisTag = getJSDocThisTag(signature.declaration); + if (thisTag && thisTag.typeExpression) { + return factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "this", + /*questionToken*/ + void 0, + typeToTypeNodeHelper(getTypeFromTypeNode2(context, thisTag.typeExpression), context) + ); + } + } + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { + const restoreFlags = saveRestoreFlags(context); + context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; + const modifiers = factory.createModifiersFromModifierFlags(getTypeParameterModifiers(type)); + const name = typeParameterToName(type, context); + const defaultParameter = getDefaultFromTypeParameter(type); + const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + restoreFlags(); + return factory.createTypeParameterDeclaration(modifiers, name, constraintNode, defaultParameterNode); + } + function typeToTypeNodeHelperWithPossibleReusableTypeNode(type, typeNode, context) { + return typeNode && getTypeFromTypeNode2(context, typeNode) === type && syntacticNodeBuilder.tryReuseExistingTypeNode(context, typeNode) || typeToTypeNodeHelper(type, context); + } + function typeParameterToDeclaration(type, context, constraint = getConstraintOfTypeParameter(type)) { + const constraintNode = constraint && typeToTypeNodeHelperWithPossibleReusableTypeNode(constraint, getConstraintDeclaration(type), context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } + function typePredicateToTypePredicateNodeHelper(typePredicate, context) { + const assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */) : void 0; + const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : factory.createThisTypeNode(); + const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context); + return factory.createTypePredicateNode(assertsModifier, parameterName, typeNode); + } + function getEffectiveParameterDeclaration(parameterSymbol) { + const parameterDeclaration = getDeclarationOfKind(parameterSymbol, 169 /* Parameter */); + if (parameterDeclaration) { + return parameterDeclaration; + } + if (!isTransientSymbol(parameterSymbol)) { + return getDeclarationOfKind(parameterSymbol, 341 /* JSDocParameterTag */); + } + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + const parameterDeclaration = getEffectiveParameterDeclaration(parameterSymbol); + const parameterType = getTypeOfSymbol(parameterSymbol); + const parameterTypeNode = serializeTypeForDeclaration(context, parameterDeclaration, parameterType, parameterSymbol); + const modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0; + const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; + const dotDotDotToken = isRest ? factory.createToken(26 /* DotDotDotToken */) : void 0; + const name = parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context); + const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */; + const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; + const parameterNode = factory.createParameterDeclaration( + modifiers, + dotDotDotToken, + name, + questionToken, + parameterTypeNode, + /*initializer*/ + void 0 + ); + context.approximateLength += symbolName(parameterSymbol).length + 3; + return parameterNode; + } + function parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context) { + return parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 166 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); + function cloneBindingName(node) { + return elideInitializerAndSetEmitFlags(node); + function elideInitializerAndSetEmitFlags(node2) { + if (context.tracker.canTrackSymbol && isComputedPropertyName(node2) && isLateBindableName(node2)) { + trackComputedName(node2.expression, context.enclosingDeclaration, context); + } + let visited = visitEachChild( + node2, + elideInitializerAndSetEmitFlags, + /*context*/ + void 0, + /*nodesVisitor*/ + void 0, + elideInitializerAndSetEmitFlags + ); + if (isBindingElement(visited)) { + visited = factory.updateBindingElement( + visited, + visited.dotDotDotToken, + visited.propertyName, + visited.name, + /*initializer*/ + void 0 + ); + } + if (!nodeIsSynthesized(visited)) { + visited = factory.cloneNode(visited); + } + return setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); + } + } + } + function trackComputedName(accessExpression, enclosingDeclaration, context) { + if (!context.tracker.canTrackSymbol) return; + const firstIdentifier = getFirstIdentifier(accessExpression); + const name = resolveName( + enclosingDeclaration, + firstIdentifier.escapedText, + 111551 /* Value */ | 1048576 /* ExportValue */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); + } else { + const fallback = resolveName( + firstIdentifier, + firstIdentifier.escapedText, + 111551 /* Value */ | 1048576 /* ExportValue */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (fallback) { + context.tracker.trackSymbol(fallback, enclosingDeclaration, 111551 /* Value */); + } + } + } + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); + return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol); + } + function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) { + let chain; + const isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.internalFlags & 4 /* DoNotIncludeSymbolChain */)) { + chain = Debug.checkDefined(getSymbolChain( + symbol, + meaning, + /*endOfChain*/ + true + )); + Debug.assert(chain && chain.length > 0); + } else { + chain = [symbol]; + } + return chain; + function getSymbolChain(symbol2, meaning2, endOfChain) { + let accessibleSymbolChain = getAccessibleSymbolChain(symbol2, context.enclosingDeclaration, meaning2, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); + let parentSpecifiers; + if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning2 : getQualifiedLeftMeaning(meaning2))) { + const parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol2, context.enclosingDeclaration, meaning2); + if (length(parents)) { + parentSpecifiers = parents.map( + (symbol3) => some(symbol3.declarations, hasNonGlobalAugmentationExternalModuleSymbol) ? getSpecifierForModuleSymbol(symbol3, context) : void 0 + ); + const indices = parents.map((_, i) => i); + indices.sort(sortByBestName); + const sortedParents = indices.map((i) => parents[i]); + for (const parent of sortedParents) { + const parentChain = getSymbolChain( + parent, + getQualifiedLeftMeaning(meaning2), + /*endOfChain*/ + false + ); + if (parentChain) { + if (parent.exports && parent.exports.get("export=" /* ExportEquals */) && getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol2)) { + accessibleSymbolChain = parentChain; + break; + } + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol2) || symbol2]); + break; + } + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || // If a parent symbol is an anonymous type, don't write it. + !(symbol2.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */)) + ) { + if (!endOfChain && !yieldModuleSymbol && !!forEach(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } + return [symbol2]; + } + function sortByBestName(a, b) { + const specifierA = parentSpecifiers[a]; + const specifierB = parentSpecifiers[b]; + if (specifierA && specifierB) { + const isBRelative = pathIsRelative(specifierB); + if (pathIsRelative(specifierA) === isBRelative) { + return countPathComponents(specifierA) - countPathComponents(specifierB); + } + if (isBRelative) { + return -1; + } + return 1; + } + return 0; + } + } + } + function typeParametersToTypeParameterDeclarations(symbol, context) { + let typeParameterNodes; + const targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = factory.createNodeArray(map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), (tp) => typeParameterToDeclaration(tp, context))); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + var _a; + Debug.assert(chain && 0 <= index && index < chain.length); + const symbol = chain[index]; + const symbolId = getSymbolId(symbol); + if ((_a = context.typeParameterSymbolList) == null ? void 0 : _a.has(symbolId)) { + return void 0; + } + if (context.mustCreateTypeParameterSymbolList) { + context.mustCreateTypeParameterSymbolList = false; + context.typeParameterSymbolList = new Set(context.typeParameterSymbolList); + } + context.typeParameterSymbolList.add(symbolId); + let typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < chain.length - 1) { + const parentSymbol = symbol; + const nextSymbol = chain[index + 1]; + if (getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + const params = getTypeParametersOfClassOrInterface( + parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol + ); + typeParameterNodes = mapToTypeNodes(map(params, (t) => getMappedType(t, nextSymbol.links.mapper)), context); + } else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function getTopmostIndexedAccessType(top) { + if (isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function getSpecifierForModuleSymbol(symbol, context, overrideImportMode) { + let file = getDeclarationOfKind(symbol, 307 /* SourceFile */); + if (!file) { + const equivalentFileSymbol = firstDefined(symbol.declarations, (d) => getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol)); + if (equivalentFileSymbol) { + file = getDeclarationOfKind(equivalentFileSymbol, 307 /* SourceFile */); + } + } + if (file && file.moduleName !== void 0) { + return file.moduleName; + } + if (!file) { + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + } + if (!context.enclosingFile || !context.tracker.moduleResolverHost) { + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + return getSourceFileOfNode(getNonAugmentationDeclaration(symbol)).fileName; + } + const enclosingDeclaration = getOriginalNode(context.enclosingDeclaration); + const originalModuleSpecifier = canHaveModuleSpecifier(enclosingDeclaration) ? tryGetModuleSpecifierFromDeclaration(enclosingDeclaration) : void 0; + const contextFile = context.enclosingFile; + const resolutionMode = overrideImportMode || originalModuleSpecifier && host.getModeForUsageLocation(contextFile, originalModuleSpecifier) || contextFile && host.getDefaultResolutionModeForFile(contextFile); + const cacheKey = createModeAwareCacheKey(contextFile.path, resolutionMode); + const links = getSymbolLinks(symbol); + let specifier = links.specifierCache && links.specifierCache.get(cacheKey); + if (!specifier) { + const isBundle2 = !!compilerOptions.outFile; + const { moduleResolverHost } = context.tracker; + const specifierCompilerOptions = isBundle2 ? { ...compilerOptions, baseUrl: moduleResolverHost.getCommonSourceDirectory() } : compilerOptions; + specifier = first(getModuleSpecifiers( + symbol, + checker, + specifierCompilerOptions, + contextFile, + moduleResolverHost, + { + importModuleSpecifierPreference: isBundle2 ? "non-relative" : "project-relative", + importModuleSpecifierEnding: isBundle2 ? "minimal" : resolutionMode === 99 /* ESNext */ ? "js" : void 0 + }, + { overrideImportMode } + )); + links.specifierCache ?? (links.specifierCache = /* @__PURE__ */ new Map()); + links.specifierCache.set(cacheKey, specifier); + } + return specifier; + } + function symbolToEntityNameNode(symbol) { + const identifier = factory.createIdentifier(unescapeLeadingUnderscores(symbol.escapedName)); + return symbol.parent ? factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier; + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + const chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); + const isTypeOf = meaning === 111551 /* Value */; + if (some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + const nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : void 0; + const typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + const contextFile = getSourceFileOfNode(getOriginalNode(context.enclosingDeclaration)); + const targetFile = getSourceFileOfModule(chain[0]); + let specifier; + let attributes; + if (getEmitModuleResolutionKind(compilerOptions) === 3 /* Node16 */ || getEmitModuleResolutionKind(compilerOptions) === 99 /* NodeNext */) { + if ((targetFile == null ? void 0 : targetFile.impliedNodeFormat) === 99 /* ESNext */ && targetFile.impliedNodeFormat !== (contextFile == null ? void 0 : contextFile.impliedNodeFormat)) { + specifier = getSpecifierForModuleSymbol(chain[0], context, 99 /* ESNext */); + attributes = factory.createImportAttributes( + factory.createNodeArray([ + factory.createImportAttribute( + factory.createStringLiteral("resolution-mode"), + factory.createStringLiteral("import") + ) + ]) + ); + } + } + if (!specifier) { + specifier = getSpecifierForModuleSymbol(chain[0], context); + } + if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && getEmitModuleResolutionKind(compilerOptions) !== 1 /* Classic */ && specifier.includes("/node_modules/")) { + const oldSpecifier = specifier; + if (getEmitModuleResolutionKind(compilerOptions) === 3 /* Node16 */ || getEmitModuleResolutionKind(compilerOptions) === 99 /* NodeNext */) { + const swappedMode = (contextFile == null ? void 0 : contextFile.impliedNodeFormat) === 99 /* ESNext */ ? 1 /* CommonJS */ : 99 /* ESNext */; + specifier = getSpecifierForModuleSymbol(chain[0], context, swappedMode); + if (specifier.includes("/node_modules/")) { + specifier = oldSpecifier; + } else { + attributes = factory.createImportAttributes( + factory.createNodeArray([ + factory.createImportAttribute( + factory.createStringLiteral("resolution-mode"), + factory.createStringLiteral(swappedMode === 99 /* ESNext */ ? "import" : "require") + ) + ]) + ); + } + } + if (!attributes) { + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(oldSpecifier); + } + } + } + const lit = factory.createLiteralTypeNode(factory.createStringLiteral(specifier)); + context.approximateLength += specifier.length + 10; + if (!nonRootParts || isEntityName(nonRootParts)) { + if (nonRootParts) { + const lastId = isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + setIdentifierTypeArguments( + lastId, + /*typeArguments*/ + void 0 + ); + } + return factory.createImportTypeNode(lit, attributes, nonRootParts, typeParameterNodes, isTypeOf); + } else { + const splitNode = getTopmostIndexedAccessType(nonRootParts); + const qualifier = splitNode.objectType.typeName; + return factory.createIndexedAccessTypeNode(factory.createImportTypeNode(lit, attributes, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } + } + const entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (isIndexedAccessTypeNode(entityName)) { + return entityName; + } + if (isTypeOf) { + return factory.createTypeQueryNode(entityName); + } else { + const lastId = isIdentifier(entityName) ? entityName : entityName.right; + const lastTypeArgs = getIdentifierTypeArguments(lastId); + setIdentifierTypeArguments( + lastId, + /*typeArguments*/ + void 0 + ); + return factory.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain2, index, stopper) { + const typeParameterNodes = index === chain2.length - 1 ? overrideTypeArguments : lookupTypeParameterNodes(chain2, index, context); + const symbol2 = chain2[index]; + const parent = chain2[index - 1]; + let symbolName2; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + symbolName2 = getNameOfSymbolAsWritten(symbol2, context); + context.approximateLength += (symbolName2 ? symbolName2.length : 0) + 1; + context.flags ^= 16777216 /* InInitialEntityName */; + } else { + if (parent && getExportsOfSymbol(parent)) { + const exports2 = getExportsOfSymbol(parent); + forEachEntry(exports2, (ex, name) => { + if (getSymbolIfSameReference(ex, symbol2) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) { + symbolName2 = unescapeLeadingUnderscores(name); + return true; + } + }); + } + } + if (symbolName2 === void 0) { + const name = firstDefined(symbol2.declarations, getNameOfDeclaration); + if (name && isComputedPropertyName(name) && isEntityName(name.expression)) { + const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper); + if (isEntityName(LHS)) { + return factory.createIndexedAccessTypeNode(factory.createParenthesizedType(factory.createTypeQueryNode(LHS)), factory.createTypeQueryNode(name.expression)); + } + return LHS; + } + symbolName2 = getNameOfSymbolAsWritten(symbol2, context); + } + context.approximateLength += symbolName2.length + 1; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol2.escapedName) && getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol2.escapedName), symbol2)) { + const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper); + if (isIndexedAccessTypeNode(LHS)) { + return factory.createIndexedAccessTypeNode(LHS, factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2))); + } else { + return factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(LHS, typeParameterNodes), factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2))); + } + } + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + identifier.symbol = symbol2; + if (index > stopper) { + const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper); + if (!isEntityName(LHS)) { + return Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return factory.createQualifiedName(LHS, identifier); + } + return identifier; + } + } + function typeParameterShadowsOtherTypeParameterInScope(escapedName, context, type) { + const result = resolveName( + context.enclosingDeclaration, + escapedName, + 788968 /* Type */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + if (result && result.flags & 262144 /* TypeParameter */) { + return result !== type.symbol; + } + return false; + } + function typeParameterToName(type, context) { + var _a, _b, _c, _d; + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { + const cached = context.typeParameterNames.get(getTypeId(type)); + if (cached) { + return cached; + } + } + let result = symbolToName( + type.symbol, + context, + 788968 /* Type */, + /*expectsIdentifier*/ + true + ); + if (!(result.kind & 80 /* Identifier */)) { + return factory.createIdentifier("(Missing type parameter)"); + } + const decl = (_b = (_a = type.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b[0]; + if (decl && isTypeParameterDeclaration(decl)) { + result = setTextRange2(context, result, decl.name); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { + const rawtext = result.escapedText; + let i = ((_c = context.typeParameterNamesByTextNextNameCount) == null ? void 0 : _c.get(rawtext)) || 0; + let text = rawtext; + while (((_d = context.typeParameterNamesByText) == null ? void 0 : _d.has(text)) || typeParameterShadowsOtherTypeParameterInScope(text, context, type)) { + i++; + text = `${rawtext}_${i}`; + } + if (text !== rawtext) { + const typeArguments = getIdentifierTypeArguments(result); + result = factory.createIdentifier(text); + setIdentifierTypeArguments(result, typeArguments); + } + if (context.mustCreateTypeParametersNamesLookups) { + context.mustCreateTypeParametersNamesLookups = false; + context.typeParameterNames = new Map(context.typeParameterNames); + context.typeParameterNamesByTextNextNameCount = new Map(context.typeParameterNamesByTextNextNameCount); + context.typeParameterNamesByText = new Set(context.typeParameterNamesByText); + } + context.typeParameterNamesByTextNextNameCount.set(rawtext, i); + context.typeParameterNames.set(getTypeId(type), result); + context.typeParameterNamesByText.add(text); + } + return result; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + const chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 && !context.encounteredError && !(context.flags & 65536 /* AllowQualifiedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain2, index) { + const typeParameterNodes = lookupTypeParameterNodes(chain2, index, context); + const symbol2 = chain2[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + const symbolName2 = getNameOfSymbolAsWritten(symbol2, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + identifier.symbol = symbol2; + return index > 0 ? factory.createQualifiedName(createEntityNameFromSymbolChain(chain2, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + const chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain2, index) { + const typeParameterNodes = lookupTypeParameterNodes(chain2, index, context); + const symbol2 = chain2[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + let symbolName2 = getNameOfSymbolAsWritten(symbol2, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + let firstChar = symbolName2.charCodeAt(0); + if (isSingleOrDoubleQuote(firstChar) && some(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context)); + } + if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) { + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + identifier.symbol = symbol2; + return index > 0 ? factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), identifier) : identifier; + } else { + if (firstChar === 91 /* openBracket */) { + symbolName2 = symbolName2.substring(1, symbolName2.length - 1); + firstChar = symbolName2.charCodeAt(0); + } + let expression; + if (isSingleOrDoubleQuote(firstChar) && !(symbol2.flags & 8 /* EnumMember */)) { + expression = factory.createStringLiteral(stripQuotes(symbolName2).replace(/\\./g, (s) => s.substring(1)), firstChar === 39 /* singleQuote */); + } else if ("" + +symbolName2 === symbolName2) { + expression = factory.createNumericLiteral(+symbolName2); + } + if (!expression) { + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + identifier.symbol = symbol2; + expression = identifier; + } + return factory.createElementAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), expression); + } + } + } + function isStringNamed(d) { + const name = getNameOfDeclaration(d); + if (!name) { + return false; + } + if (isComputedPropertyName(name)) { + const type = checkExpression(name.expression); + return !!(type.flags & 402653316 /* StringLike */); + } + if (isElementAccessExpression(name)) { + const type = checkExpression(name.argumentExpression); + return !!(type.flags & 402653316 /* StringLike */); + } + return isStringLiteral(name); + } + function isSingleQuotedStringNamed(d) { + const name = getNameOfDeclaration(d); + return !!(name && isStringLiteral(name) && (name.singleQuote || !nodeIsSynthesized(name) && startsWith(getTextOfNode( + name, + /*includeTrivia*/ + false + ), "'"))); + } + function getPropertyNameNodeForSymbol(symbol, context) { + const stringNamed = !!length(symbol.declarations) && every(symbol.declarations, isStringNamed); + const singleQuote = !!length(symbol.declarations) && every(symbol.declarations, isSingleQuotedStringNamed); + const isMethod = !!(symbol.flags & 8192 /* Method */); + const fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod); + if (fromNameType) { + return fromNameType; + } + const rawName = unescapeLeadingUnderscores(symbol.escapedName); + return createPropertyNameNodeForIdentifierOrLiteral(rawName, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod); + } + function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod) { + const nameType = getSymbolLinks(symbol).nameType; + if (nameType) { + if (nameType.flags & 384 /* StringOrNumberLiteral */) { + const name = "" + nameType.value; + if (!isIdentifierText(name, getEmitScriptTarget(compilerOptions)) && (stringNamed || !isNumericLiteralName(name))) { + return factory.createStringLiteral(name, !!singleQuote); + } + if (isNumericLiteralName(name) && startsWith(name, "-")) { + return factory.createComputedPropertyName(factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-name))); + } + return createPropertyNameNodeForIdentifierOrLiteral(name, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod); + } + if (nameType.flags & 8192 /* UniqueESSymbol */) { + return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */)); + } + } + } + function cloneNodeBuilderContext(context) { + const oldMustCreateTypeParameterSymbolList = context.mustCreateTypeParameterSymbolList; + const oldMustCreateTypeParametersNamesLookups = context.mustCreateTypeParametersNamesLookups; + context.mustCreateTypeParameterSymbolList = true; + context.mustCreateTypeParametersNamesLookups = true; + const oldTypeParameterNames = context.typeParameterNames; + const oldTypeParameterNamesByText = context.typeParameterNamesByText; + const oldTypeParameterNamesByTextNextNameCount = context.typeParameterNamesByTextNextNameCount; + const oldTypeParameterSymbolList = context.typeParameterSymbolList; + return () => { + context.typeParameterNames = oldTypeParameterNames; + context.typeParameterNamesByText = oldTypeParameterNamesByText; + context.typeParameterNamesByTextNextNameCount = oldTypeParameterNamesByTextNextNameCount; + context.typeParameterSymbolList = oldTypeParameterSymbolList; + context.mustCreateTypeParameterSymbolList = oldMustCreateTypeParameterSymbolList; + context.mustCreateTypeParametersNamesLookups = oldMustCreateTypeParametersNamesLookups; + }; + } + function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { + return symbol.declarations && find(symbol.declarations, (s) => !!getNonlocalEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!findAncestor(s, (n) => n === enclosingDeclaration))); + } + function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) { + if (!(getObjectFlags(type) & 4 /* Reference */)) return true; + if (!isTypeReferenceNode(existing)) return true; + void getTypeFromTypeReference(existing); + const symbol = getNodeLinks(existing).resolvedSymbol; + const existingTarget = symbol && getDeclaredTypeOfSymbol(symbol); + if (!existingTarget || existingTarget !== type.target) return true; + return length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters); + } + function getEnclosingDeclarationIgnoringFakeScope(enclosingDeclaration) { + while (getNodeLinks(enclosingDeclaration).fakeScopeForSignatureDeclaration) { + enclosingDeclaration = enclosingDeclaration.parent; + } + return enclosingDeclaration; + } + function serializeInferredTypeForDeclaration(symbol, context, type) { + if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, (d) => getSourceFileOfNode(d) === context.enclosingFile))) { + context.flags |= 1048576 /* AllowUniqueESSymbolType */; + } + const result = typeToTypeNodeHelper(type, context); + return result; + } + function serializeTypeForDeclaration(context, declaration, type, symbol) { + var _a; + let result; + const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration); + const decl = declaration ?? symbol.valueDeclaration ?? getDeclarationWithTypeAnnotation(symbol) ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]); + if (decl) { + const restore = addSymbolTypeToContext(context, symbol, type); + if (isAccessor(decl)) { + result = syntacticNodeBuilder.serializeTypeOfAccessor(decl, symbol, context); + } else if (hasInferredType(decl) && !nodeIsSynthesized(decl) && !(getObjectFlags(type) & 196608 /* RequiresWidening */)) { + result = syntacticNodeBuilder.serializeTypeOfDeclaration(decl, symbol, context); + } + restore(); + } + if (!result) { + if (addUndefinedForParameter) { + type = getOptionalType(type); + } + result = serializeInferredTypeForDeclaration(symbol, context, type); + } + return result ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + function typeNodeIsEquivalentToType(annotatedDeclaration, type, typeFromTypeNode) { + if (typeFromTypeNode === type) { + return true; + } + if (!annotatedDeclaration) { + return false; + } + if ((isPropertySignature(annotatedDeclaration) || isPropertyDeclaration(annotatedDeclaration)) && annotatedDeclaration.questionToken) { + return getTypeWithFacts(type, 524288 /* NEUndefined */) === typeFromTypeNode; + } + if (isParameter(annotatedDeclaration) && hasEffectiveQuestionToken(annotatedDeclaration)) { + return getTypeWithFacts(type, 524288 /* NEUndefined */) === typeFromTypeNode; + } + return false; + } + function serializeReturnTypeForSignature(context, signature) { + const suppressAny = context.flags & 256 /* SuppressAnyReturnType */; + const restoreFlags = saveRestoreFlags(context); + if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; + let returnTypeNode; + const returnType = getReturnTypeOfSignature(signature); + if (!(suppressAny && isTypeAny(returnType))) { + if (signature.declaration && !nodeIsSynthesized(signature.declaration)) { + const declarationSymbol = getSymbolOfDeclaration(signature.declaration); + const restore = addSymbolTypeToContext(context, declarationSymbol, returnType); + returnTypeNode = syntacticNodeBuilder.serializeReturnTypeForSignature(signature.declaration, declarationSymbol, context); + restore(); + } + if (!returnTypeNode) { + returnTypeNode = serializeInferredReturnTypeForSignature(context, signature, returnType); + } + } + if (!returnTypeNode && !suppressAny) { + returnTypeNode = factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + restoreFlags(); + return returnTypeNode; + } + function serializeInferredReturnTypeForSignature(context, signature, returnType) { + const oldSuppressReportInferenceFallback = context.suppressReportInferenceFallback; + context.suppressReportInferenceFallback = true; + const typePredicate = getTypePredicateOfSignature(signature); + const returnTypeNode = typePredicate ? typePredicateToTypePredicateNodeHelper(context.mapper ? instantiateTypePredicate(typePredicate, context.mapper) : typePredicate, context) : typeToTypeNodeHelper(returnType, context); + context.suppressReportInferenceFallback = oldSuppressReportInferenceFallback; + return returnTypeNode; + } + function trackExistingEntityName(node, context, enclosingDeclaration = context.enclosingDeclaration) { + let introducesError = false; + const leftmost = getFirstIdentifier(node); + if (isInJSFile(node) && (isExportsIdentifier(leftmost) || isModuleExportsAccessExpression(leftmost.parent) || isQualifiedName(leftmost.parent) && isModuleIdentifier(leftmost.parent.left) && isExportsIdentifier(leftmost.parent.right))) { + introducesError = true; + return { introducesError, node }; + } + const meaning = getMeaningOfEntityNameReference(node); + let sym; + if (isThisIdentifier(leftmost)) { + sym = getSymbolOfDeclaration(getThisContainer( + leftmost, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + )); + if (isSymbolAccessible( + sym, + leftmost, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility !== 0 /* Accessible */) { + introducesError = true; + context.tracker.reportInaccessibleThisError(); + } + return { introducesError, node: attachSymbolToLeftmostIdentifier(node) }; + } + sym = resolveEntityName( + leftmost, + meaning, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true + ); + if (context.enclosingDeclaration && !(sym && sym.flags & 262144 /* TypeParameter */)) { + sym = getExportSymbolOfValueSymbolIfExported(sym); + const symAtLocation = resolveEntityName( + leftmost, + meaning, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + context.enclosingDeclaration + ); + if ( + // Check for unusable parameters symbols + symAtLocation === unknownSymbol || // If the symbol is not found, but was not found in the original scope either we probably have an error, don't reuse the node + symAtLocation === void 0 && sym !== void 0 || // If the symbol is found both in declaration scope and in current scope then it should point to the same reference + symAtLocation && sym && !getSymbolIfSameReference(getExportSymbolOfValueSymbolIfExported(symAtLocation), sym) + ) { + if (symAtLocation !== unknownSymbol) { + context.tracker.reportInferenceFallback(node); + } + introducesError = true; + return { introducesError, node, sym }; + } else { + sym = symAtLocation; + } + } + if (sym) { + if (sym.flags & 1 /* FunctionScopedVariable */ && sym.valueDeclaration) { + if (isPartOfParameterDeclaration(sym.valueDeclaration) || isJSDocParameterTag(sym.valueDeclaration)) { + return { introducesError, node: attachSymbolToLeftmostIdentifier(node) }; + } + } + if (!(sym.flags & 262144 /* TypeParameter */) && // Type parameters are visible in the current context if they are are resolvable + !isDeclarationName(node) && isSymbolAccessible( + sym, + enclosingDeclaration, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility !== 0 /* Accessible */) { + context.tracker.reportInferenceFallback(node); + introducesError = true; + } else { + context.tracker.trackSymbol(sym, enclosingDeclaration, meaning); + } + return { introducesError, node: attachSymbolToLeftmostIdentifier(node) }; + } + return { introducesError, node }; + function attachSymbolToLeftmostIdentifier(node2) { + if (node2 === leftmost) { + const type = getDeclaredTypeOfSymbol(sym); + const name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(type, context) : factory.cloneNode(node2); + name.symbol = sym; + return setTextRange2(context, setEmitFlags(name, 16777216 /* NoAsciiEscaping */), node2); + } + const updated = visitEachChild( + node2, + (c) => attachSymbolToLeftmostIdentifier(c), + /*context*/ + void 0 + ); + return setTextRange2(context, updated, node2); + } + } + function serializeTypeName(context, node, isTypeOf, typeArguments) { + const meaning = isTypeOf ? 111551 /* Value */ : 788968 /* Type */; + const symbol = resolveEntityName( + node, + meaning, + /*ignoreErrors*/ + true + ); + if (!symbol) return void 0; + const resolvedSymbol = symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol; + if (isSymbolAccessible( + symbol, + context.enclosingDeclaration, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility !== 0 /* Accessible */) return void 0; + return symbolToTypeNode(resolvedSymbol, context, meaning, typeArguments); + } + function canReuseTypeNode(context, existing) { + const type = getTypeFromTypeNode2( + context, + existing, + /*noMappedTypes*/ + true + ); + if (!type) { + return false; + } + if (isInJSFile(existing)) { + if (isLiteralImportTypeNode(existing)) { + void getTypeFromImportTypeNode(existing); + const nodeSymbol = getNodeLinks(existing).resolvedSymbol; + return !nodeSymbol || !// The import type resolved using jsdoc fallback logic + (!existing.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */) || // The import type had type arguments autofilled by js fallback logic + !(length(existing.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol)))); + } + } + if (isTypeReferenceNode(existing)) { + if (isConstTypeReference(existing)) return false; + const symbol = getNodeLinks(existing).resolvedSymbol; + if (!symbol) return false; + if (symbol.flags & 262144 /* TypeParameter */) { + const declaredType = getDeclaredTypeOfSymbol(symbol); + return !(context.mapper && getMappedType(declaredType, context.mapper) !== declaredType); + } + if (isInJSDoc(existing)) { + return existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) && !getIntendedTypeFromJSDocTypeReference(existing) && !!(symbol.flags & 788968 /* Type */); + } + } + if (isTypeOperatorNode(existing) && existing.operator === 158 /* UniqueKeyword */ && existing.type.kind === 155 /* SymbolKeyword */) { + const effectiveEnclosingContext = context.enclosingDeclaration && getEnclosingDeclarationIgnoringFakeScope(context.enclosingDeclaration); + return !!findAncestor(existing, (n) => n === effectiveEnclosingContext); + } + return true; + } + function serializeExistingTypeNode(context, typeNode, addUndefined) { + const type = getTypeFromTypeNode2(context, typeNode); + if (addUndefined && !someType(type, (t) => !!(t.flags & 32768 /* Undefined */)) && canReuseTypeNode(context, typeNode)) { + const clone = syntacticNodeBuilder.tryReuseExistingTypeNode(context, typeNode); + if (clone) { + return factory.createUnionTypeNode([clone, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + } + } + return typeToTypeNodeHelper(type, context); + } + function symbolTableToDeclarationStatements(symbolTable, context) { + var _a; + const serializePropertySymbolForClass = makeSerializePropertySymbol( + factory.createPropertyDeclaration, + 174 /* MethodDeclaration */, + /*useAccessors*/ + true + ); + const serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol( + (mods, name, question, type) => factory.createPropertySignature(mods, name, question, type), + 173 /* MethodSignature */, + /*useAccessors*/ + false + ); + const enclosingDeclaration = context.enclosingDeclaration; + let results = []; + const visitedSymbols = /* @__PURE__ */ new Set(); + const deferredPrivatesStack = []; + const oldcontext = context; + context = { + ...oldcontext, + usedSymbolNames: new Set(oldcontext.usedSymbolNames), + remappedSymbolNames: /* @__PURE__ */ new Map(), + remappedSymbolReferences: new Map((_a = oldcontext.remappedSymbolReferences) == null ? void 0 : _a.entries()), + tracker: void 0 + }; + const tracker = { + ...oldcontext.tracker.inner, + trackSymbol: (sym, decl, meaning) => { + var _a2, _b; + if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) return false; + const accessibleResult = isSymbolAccessible( + sym, + decl, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ); + if (accessibleResult.accessibility === 0 /* Accessible */) { + const chain = lookupSymbolChainWorker(sym, context, meaning); + if (!(sym.flags & 4 /* Property */)) { + const root = chain[0]; + const contextFile = getSourceFileOfNode(oldcontext.enclosingDeclaration); + if (some(root.declarations, (d) => getSourceFileOfNode(d) === contextFile)) { + includePrivateSymbol(root); + } + } + } else if ((_b = oldcontext.tracker.inner) == null ? void 0 : _b.trackSymbol) { + return oldcontext.tracker.inner.trackSymbol(sym, decl, meaning); + } + return false; + } + }; + context.tracker = new SymbolTrackerImpl(context, tracker, oldcontext.tracker.moduleResolverHost); + forEachEntry(symbolTable, (symbol, name) => { + const baseName = unescapeLeadingUnderscores(name); + void getInternalSymbolName(symbol, baseName); + }); + let addingDeclare = !context.bundled; + const exportEquals = symbolTable.get("export=" /* ExportEquals */); + if (exportEquals && symbolTable.size > 1 && exportEquals.flags & (2097152 /* Alias */ | 1536 /* Module */)) { + symbolTable = createSymbolTable(); + symbolTable.set("export=" /* ExportEquals */, exportEquals); + } + visitSymbolTable(symbolTable); + return mergeRedundantStatements(results); + function isIdentifierAndNotUndefined(node) { + return !!node && node.kind === 80 /* Identifier */; + } + function getNamesOfDeclaration(statement) { + if (isVariableStatement(statement)) { + return filter(map(statement.declarationList.declarations, getNameOfDeclaration), isIdentifierAndNotUndefined); + } + return filter([getNameOfDeclaration(statement)], isIdentifierAndNotUndefined); + } + function flattenExportAssignedNamespace(statements) { + const exportAssignment = find(statements, isExportAssignment); + const nsIndex = findIndex(statements, isModuleDeclaration); + let ns = nsIndex !== -1 ? statements[nsIndex] : void 0; + if (ns && exportAssignment && exportAssignment.isExportEquals && isIdentifier(exportAssignment.expression) && isIdentifier(ns.name) && idText(ns.name) === idText(exportAssignment.expression) && ns.body && isModuleBlock(ns.body)) { + const excessExports = filter(statements, (s) => !!(getEffectiveModifierFlags(s) & 32 /* Export */)); + const name = ns.name; + let body = ns.body; + if (length(excessExports)) { + ns = factory.updateModuleDeclaration( + ns, + ns.modifiers, + ns.name, + body = factory.updateModuleBlock( + body, + factory.createNodeArray([ + ...ns.body.statements, + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports(map(flatMap(excessExports, (e) => getNamesOfDeclaration(e)), (id) => factory.createExportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + id + ))), + /*moduleSpecifier*/ + void 0 + ) + ]) + ) + ); + statements = [...statements.slice(0, nsIndex), ns, ...statements.slice(nsIndex + 1)]; + } + if (!find(statements, (s) => s !== ns && nodeHasName(s, name))) { + results = []; + const mixinExportFlag = !some(body.statements, (s) => hasSyntacticModifier(s, 32 /* Export */) || isExportAssignment(s) || isExportDeclaration(s)); + forEach(body.statements, (s) => { + addResult(s, mixinExportFlag ? 32 /* Export */ : 0 /* None */); + }); + statements = [...filter(statements, (s) => s !== ns && s !== exportAssignment), ...results]; + } + } + return statements; + } + function mergeExportDeclarations(statements) { + const exports2 = filter(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)); + if (length(exports2) > 1) { + const nonExports = filter(statements, (d) => !isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause); + statements = [ + ...nonExports, + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports(flatMap(exports2, (e) => cast(e.exportClause, isNamedExports).elements)), + /*moduleSpecifier*/ + void 0 + ) + ]; + } + const reexports = filter(statements, (d) => isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)); + if (length(reexports) > 1) { + const groups = group(reexports, (decl) => isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"); + if (groups.length !== reexports.length) { + for (const group2 of groups) { + if (group2.length > 1) { + statements = [ + ...filter(statements, (s) => !group2.includes(s)), + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports(flatMap(group2, (e) => cast(e.exportClause, isNamedExports).elements)), + group2[0].moduleSpecifier + ) + ]; + } + } + } + } + return statements; + } + function inlineExportModifiers(statements) { + const index = findIndex(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !d.attributes && !!d.exportClause && isNamedExports(d.exportClause)); + if (index >= 0) { + const exportDecl = statements[index]; + const replacements = mapDefined(exportDecl.exportClause.elements, (e) => { + if (!e.propertyName && e.name.kind !== 11 /* StringLiteral */) { + const name = e.name; + const indices = indicesOf(statements); + const associatedIndices = filter(indices, (i) => nodeHasName(statements[i], name)); + if (length(associatedIndices) && every(associatedIndices, (i) => canHaveExportModifier(statements[i]))) { + for (const index2 of associatedIndices) { + statements[index2] = addExportModifier(statements[index2]); + } + return void 0; + } + } + return e; + }); + if (!length(replacements)) { + orderedRemoveItemAt(statements, index); + } else { + statements[index] = factory.updateExportDeclaration( + exportDecl, + exportDecl.modifiers, + exportDecl.isTypeOnly, + factory.updateNamedExports( + exportDecl.exportClause, + replacements + ), + exportDecl.moduleSpecifier, + exportDecl.attributes + ); + } + } + return statements; + } + function mergeRedundantStatements(statements) { + statements = flattenExportAssignedNamespace(statements); + statements = mergeExportDeclarations(statements); + statements = inlineExportModifiers(statements); + if (enclosingDeclaration && (isSourceFile(enclosingDeclaration) && isExternalOrCommonJsModule(enclosingDeclaration) || isModuleDeclaration(enclosingDeclaration)) && (!some(statements, isExternalModuleIndicator) || !hasScopeMarker(statements) && some(statements, needsScopeMarker))) { + statements.push(createEmptyExports(factory)); + } + return statements; + } + function addExportModifier(node) { + const flags = (getEffectiveModifierFlags(node) | 32 /* Export */) & ~128 /* Ambient */; + return factory.replaceModifiers(node, flags); + } + function removeExportModifier(node) { + const flags = getEffectiveModifierFlags(node) & ~32 /* Export */; + return factory.replaceModifiers(node, flags); + } + function visitSymbolTable(symbolTable2, suppressNewPrivateContext, propertyAsAlias) { + if (!suppressNewPrivateContext) { + deferredPrivatesStack.push(/* @__PURE__ */ new Map()); + } + symbolTable2.forEach((symbol) => { + serializeSymbol( + symbol, + /*isPrivate*/ + false, + !!propertyAsAlias + ); + }); + if (!suppressNewPrivateContext) { + deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach((symbol) => { + serializeSymbol( + symbol, + /*isPrivate*/ + true, + !!propertyAsAlias + ); + }); + deferredPrivatesStack.pop(); + } + } + function serializeSymbol(symbol, isPrivate, propertyAsAlias) { + void getPropertiesOfType(getTypeOfSymbol(symbol)); + const visitedSym = getMergedSymbol(symbol); + if (visitedSymbols.has(getSymbolId(visitedSym))) { + return; + } + visitedSymbols.add(getSymbolId(visitedSym)); + const skipMembershipCheck = !isPrivate; + if (skipMembershipCheck || !!length(symbol.declarations) && some(symbol.declarations, (d) => !!findAncestor(d, (n) => n === enclosingDeclaration))) { + const scopeCleanup = cloneNodeBuilderContext(context); + context.tracker.pushErrorFallbackNode(find(symbol.declarations, (d) => getSourceFileOfNode(d) === context.enclosingFile)); + serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); + context.tracker.popErrorFallbackNode(); + scopeCleanup(); + } + } + function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias, escapedSymbolName = symbol.escapedName) { + var _a2, _b, _c, _d, _e, _f; + const symbolName2 = unescapeLeadingUnderscores(escapedSymbolName); + const isDefault = escapedSymbolName === "default" /* Default */; + if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && isStringANonContextualKeyword(symbolName2) && !isDefault) { + context.encounteredError = true; + return; + } + let needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */ || symbol.flags & 16 /* Function */ && length(getPropertiesOfType(getTypeOfSymbol(symbol)))) && !(symbol.flags & 2097152 /* Alias */); + let needsExportDeclaration = !needsPostExportDefault && !isPrivate && isStringANonContextualKeyword(symbolName2) && !isDefault; + if (needsPostExportDefault || needsExportDeclaration) { + isPrivate = true; + } + const modifierFlags = (!isPrivate ? 32 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 2048 /* Default */ : 0); + const isConstMergedWithNS = symbol.flags & 1536 /* Module */ && symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && escapedSymbolName !== "export=" /* ExportEquals */; + const isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol); + if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) { + serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags); + } + if (symbol.flags & 524288 /* TypeAlias */) { + serializeTypeAlias(symbol, symbolName2, modifierFlags); + } + if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */ | 98304 /* Accessor */) && escapedSymbolName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { + if (propertyAsAlias) { + const createdExport = serializeMaybeAliasAssignment(symbol); + if (createdExport) { + needsExportDeclaration = false; + needsPostExportDefault = false; + } + } else { + const type = getTypeOfSymbol(symbol); + const localName = getInternalSymbolName(symbol, symbolName2); + if (type.symbol && type.symbol !== symbol && type.symbol.flags & 16 /* Function */ && some(type.symbol.declarations, isFunctionExpressionOrArrowFunction) && (((_a2 = type.symbol.members) == null ? void 0 : _a2.size) || ((_b = type.symbol.exports) == null ? void 0 : _b.size))) { + if (!context.remappedSymbolReferences) { + context.remappedSymbolReferences = /* @__PURE__ */ new Map(); + } + context.remappedSymbolReferences.set(getSymbolId(type.symbol), symbol); + serializeSymbolWorker(type.symbol, isPrivate, propertyAsAlias, escapedSymbolName); + context.remappedSymbolReferences.delete(getSymbolId(type.symbol)); + } else if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) { + serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags); + } else { + const flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? ((_c = symbol.parent) == null ? void 0 : _c.valueDeclaration) && isSourceFile((_d = symbol.parent) == null ? void 0 : _d.valueDeclaration) ? 2 /* Const */ : void 0 : isConstantVariable(symbol) ? 2 /* Const */ : 1 /* Let */; + const name = needsPostExportDefault || !(symbol.flags & 4 /* Property */) ? localName : getUnusedName(localName, symbol); + let textRange = symbol.declarations && find(symbol.declarations, (d) => isVariableDeclaration(d)); + if (textRange && isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { + textRange = textRange.parent.parent; + } + const propertyAccessRequire = (_e = symbol.declarations) == null ? void 0 : _e.find(isPropertyAccessExpression); + if (propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) && ((_f = type.symbol) == null ? void 0 : _f.valueDeclaration) && isSourceFile(type.symbol.valueDeclaration)) { + const alias = localName === propertyAccessRequire.parent.right.escapedText ? void 0 : propertyAccessRequire.parent.right; + addResult( + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports([factory.createExportSpecifier( + /*isTypeOnly*/ + false, + alias, + localName + )]) + ), + 0 /* None */ + ); + context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* Value */); + } else { + const statement = setTextRange2( + context, + factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + serializeTypeForDeclaration( + context, + /*declaration*/ + void 0, + type, + symbol + ) + ) + ], flags) + ), + textRange + ); + addResult(statement, name !== localName ? modifierFlags & ~32 /* Export */ : modifierFlags); + if (name !== localName && !isPrivate) { + addResult( + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports([factory.createExportSpecifier( + /*isTypeOnly*/ + false, + name, + localName + )]) + ), + 0 /* None */ + ); + needsExportDeclaration = false; + needsPostExportDefault = false; + } + } + } + } + } + if (symbol.flags & 384 /* Enum */) { + serializeEnum(symbol, symbolName2, modifierFlags); + } + if (symbol.flags & 32 /* Class */) { + if (symbol.flags & 4 /* Property */ && symbol.valueDeclaration && isBinaryExpression(symbol.valueDeclaration.parent) && isClassExpression(symbol.valueDeclaration.parent.right)) { + serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags); + } else { + serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags); + } + } + if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol)) || isConstMergedWithNSPrintableAsSignatureMerge) { + serializeModule(symbol, symbolName2, modifierFlags); + } + if (symbol.flags & 64 /* Interface */ && !(symbol.flags & 32 /* Class */)) { + serializeInterface(symbol, symbolName2, modifierFlags); + } + if (symbol.flags & 2097152 /* Alias */) { + serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags); + } + if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) { + serializeMaybeAliasAssignment(symbol); + } + if (symbol.flags & 8388608 /* ExportStar */) { + if (symbol.declarations) { + for (const node of symbol.declarations) { + const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + if (!resolvedModule) continue; + addResult(factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + node.isTypeOnly, + /*exportClause*/ + void 0, + factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context)) + ), 0 /* None */); + } + } + } + if (needsPostExportDefault) { + addResult(factory.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + factory.createIdentifier(getInternalSymbolName(symbol, symbolName2)) + ), 0 /* None */); + } else if (needsExportDeclaration) { + addResult( + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports([factory.createExportSpecifier( + /*isTypeOnly*/ + false, + getInternalSymbolName(symbol, symbolName2), + symbolName2 + )]) + ), + 0 /* None */ + ); + } + } + function includePrivateSymbol(symbol) { + if (some(symbol.declarations, isPartOfParameterDeclaration)) return; + Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]); + getUnusedName(unescapeLeadingUnderscores(symbol.escapedName), symbol); + const isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !some(symbol.declarations, (d) => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference)); + deferredPrivatesStack[isExternalImportAlias ? 0 : deferredPrivatesStack.length - 1].set(getSymbolId(symbol), symbol); + } + function isExportingScope(enclosingDeclaration2) { + return isSourceFile(enclosingDeclaration2) && (isExternalOrCommonJsModule(enclosingDeclaration2) || isJsonSourceFile(enclosingDeclaration2)) || isAmbientModule(enclosingDeclaration2) && !isGlobalScopeAugmentation(enclosingDeclaration2); + } + function addResult(node, additionalModifierFlags) { + if (canHaveModifiers(node)) { + let newModifierFlags = 0 /* None */; + const enclosingDeclaration2 = context.enclosingDeclaration && (isJSDocTypeAlias(context.enclosingDeclaration) ? getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); + if (additionalModifierFlags & 32 /* Export */ && enclosingDeclaration2 && (isExportingScope(enclosingDeclaration2) || isModuleDeclaration(enclosingDeclaration2)) && canHaveExportModifier(node)) { + newModifierFlags |= 32 /* Export */; + } + if (addingDeclare && !(newModifierFlags & 32 /* Export */) && (!enclosingDeclaration2 || !(enclosingDeclaration2.flags & 33554432 /* Ambient */)) && (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) { + newModifierFlags |= 128 /* Ambient */; + } + if (additionalModifierFlags & 2048 /* Default */ && (isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionDeclaration(node))) { + newModifierFlags |= 2048 /* Default */; + } + if (newModifierFlags) { + node = factory.replaceModifiers(node, newModifierFlags | getEffectiveModifierFlags(node)); + } + } + results.push(node); + } + function serializeTypeAlias(symbol, symbolName2, modifierFlags) { + var _a2; + const aliasType = getDeclaredTypeOfTypeAlias(symbol); + const typeParams = getSymbolLinks(symbol).typeParameters; + const typeParamDecls = map(typeParams, (p) => typeParameterToDeclaration(p, context)); + const jsdocAliasDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isJSDocTypeAlias); + const commentText = getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : void 0); + const restoreFlags = saveRestoreFlags(context); + context.flags |= 8388608 /* InTypeAlias */; + const oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; + const typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && syntacticNodeBuilder.tryReuseExistingTypeNode(context, jsdocAliasDecl.typeExpression.type) || typeToTypeNodeHelper(aliasType, context); + addResult( + setSyntheticLeadingComments( + factory.createTypeAliasDeclaration( + /*modifiers*/ + void 0, + getInternalSymbolName(symbol, symbolName2), + typeParamDecls, + typeNode + ), + !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }] + ), + modifierFlags + ); + restoreFlags(); + context.enclosingDeclaration = oldEnclosingDecl; + } + function serializeInterface(symbol, symbolName2, modifierFlags) { + const interfaceType = getDeclaredTypeOfClassOrInterface(symbol); + const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context)); + const baseTypes = getBaseTypes(interfaceType); + const baseType = length(baseTypes) ? getIntersectionType(baseTypes) : void 0; + const members = flatMap(getPropertiesOfType(interfaceType), (p) => serializePropertySymbolForInterface(p, baseType)); + const callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 179 /* CallSignature */); + const constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 180 /* ConstructSignature */); + const indexSignatures = serializeIndexSignatures(interfaceType, baseType); + const heritageClauses = !length(baseTypes) ? void 0 : [factory.createHeritageClause(96 /* ExtendsKeyword */, mapDefined(baseTypes, (b) => trySerializeAsTypeReference(b, 111551 /* Value */)))]; + addResult( + factory.createInterfaceDeclaration( + /*modifiers*/ + void 0, + getInternalSymbolName(symbol, symbolName2), + typeParamDecls, + heritageClauses, + [...indexSignatures, ...constructSignatures, ...callSignatures, ...members] + ), + modifierFlags + ); + } + function getNamespaceMembersForSerialization(symbol) { + let exports2 = arrayFrom(getExportsOfSymbol(symbol).values()); + const merged = getMergedSymbol(symbol); + if (merged !== symbol) { + const membersSet = new Set(exports2); + for (const exported of getExportsOfSymbol(merged).values()) { + if (!(getSymbolFlags(resolveSymbol(exported)) & 111551 /* Value */)) { + membersSet.add(exported); + } + } + exports2 = arrayFrom(membersSet); + } + return filter(exports2, (m) => isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */)); + } + function isTypeOnlyNamespace(symbol) { + return every(getNamespaceMembersForSerialization(symbol), (m) => !(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); + } + function serializeModule(symbol, symbolName2, modifierFlags) { + const members = getNamespaceMembersForSerialization(symbol); + const locationMap = arrayToMultiMap(members, (m) => m.parent && m.parent === symbol ? "real" : "merged"); + const realMembers = locationMap.get("real") || emptyArray; + const mergedMembers = locationMap.get("merged") || emptyArray; + if (length(realMembers)) { + const localName = getInternalSymbolName(symbol, symbolName2); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); + } + if (length(mergedMembers)) { + const containingFile = getSourceFileOfNode(context.enclosingDeclaration); + const localName = getInternalSymbolName(symbol, symbolName2); + const nsBody = factory.createModuleBlock([factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports(mapDefined(filter(mergedMembers, (n) => n.escapedName !== "export=" /* ExportEquals */), (s) => { + var _a2, _b; + const name = unescapeLeadingUnderscores(s.escapedName); + const localName2 = getInternalSymbolName(s, name); + const aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + if (containingFile && (aliasDecl ? containingFile !== getSourceFileOfNode(aliasDecl) : !some(s.declarations, (d) => getSourceFileOfNode(d) === containingFile))) { + (_b = (_a2 = context.tracker) == null ? void 0 : _a2.reportNonlocalAugmentation) == null ? void 0 : _b.call(_a2, containingFile, symbol, s); + return void 0; + } + const target = aliasDecl && getTargetOfAliasDeclaration( + aliasDecl, + /*dontRecursivelyResolve*/ + true + ); + includePrivateSymbol(target || s); + const targetName = target ? getInternalSymbolName(target, unescapeLeadingUnderscores(target.escapedName)) : localName2; + return factory.createExportSpecifier( + /*isTypeOnly*/ + false, + name === targetName ? void 0 : targetName, + name + ); + })) + )]); + addResult( + factory.createModuleDeclaration( + /*modifiers*/ + void 0, + factory.createIdentifier(localName), + nsBody, + 32 /* Namespace */ + ), + 0 /* None */ + ); + } + } + function serializeEnum(symbol, symbolName2, modifierFlags) { + addResult( + factory.createEnumDeclaration( + factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 4096 /* Const */ : 0), + getInternalSymbolName(symbol, symbolName2), + map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), (p) => !!(p.flags & 8 /* EnumMember */)), (p) => { + const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue2(p.declarations[0]) : void 0; + return factory.createEnumMember( + unescapeLeadingUnderscores(p.escapedName), + initializedValue === void 0 ? void 0 : typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : factory.createNumericLiteral(initializedValue) + ); + }) + ), + modifierFlags + ); + } + function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) { + const signatures = getSignaturesOfType(type, 0 /* Call */); + for (const sig of signatures) { + const decl = signatureToSignatureDeclarationHelper(sig, 262 /* FunctionDeclaration */, context, { name: factory.createIdentifier(localName) }); + addResult(setTextRange2(context, decl, getSignatureTextRangeLocation(sig)), modifierFlags); + } + if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { + const props = filter(getPropertiesOfType(type), isNamespaceMember); + serializeAsNamespaceDeclaration( + props, + localName, + modifierFlags, + /*suppressNewPrivateContext*/ + true + ); + } + } + function getSignatureTextRangeLocation(signature) { + if (signature.declaration && signature.declaration.parent) { + if (isBinaryExpression(signature.declaration.parent) && getAssignmentDeclarationKind(signature.declaration.parent) === 5 /* Property */) { + return signature.declaration.parent; + } + if (isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) { + return signature.declaration.parent.parent; + } + } + return signature.declaration; + } + function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) { + if (length(props)) { + const localVsRemoteMap = arrayToMultiMap(props, (p) => !length(p.declarations) || some(p.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)) ? "local" : "remote"); + const localProps = localVsRemoteMap.get("local") || emptyArray; + let fakespace = parseNodeFactory.createModuleDeclaration( + /*modifiers*/ + void 0, + factory.createIdentifier(localName), + factory.createModuleBlock([]), + 32 /* Namespace */ + ); + setParent(fakespace, enclosingDeclaration); + fakespace.locals = createSymbolTable(props); + fakespace.symbol = props[0].parent; + const oldResults = results; + results = []; + const oldAddingDeclare = addingDeclare; + addingDeclare = false; + const subcontext = { ...context, enclosingDeclaration: fakespace }; + const oldContext = context; + context = subcontext; + visitSymbolTable( + createSymbolTable(localProps), + suppressNewPrivateContext, + /*propertyAsAlias*/ + true + ); + context = oldContext; + addingDeclare = oldAddingDeclare; + const declarations = results; + results = oldResults; + const defaultReplaced = map(declarations, (d) => isExportAssignment(d) && !d.isExportEquals && isIdentifier(d.expression) ? factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports([factory.createExportSpecifier( + /*isTypeOnly*/ + false, + d.expression, + factory.createIdentifier("default" /* Default */) + )]) + ) : d); + const exportModifierStripped = every(defaultReplaced, (d) => hasSyntacticModifier(d, 32 /* Export */)) ? map(defaultReplaced, removeExportModifier) : defaultReplaced; + fakespace = factory.updateModuleDeclaration( + fakespace, + fakespace.modifiers, + fakespace.name, + factory.createModuleBlock(exportModifierStripped) + ); + addResult(fakespace, modifierFlags); + } + } + function isNamespaceMember(p) { + return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) || !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && isStatic(p.valueDeclaration) && isClassLike(p.valueDeclaration.parent)); + } + function sanitizeJSDocImplements(clauses) { + const result = mapDefined(clauses, (e) => { + const oldEnclosing = context.enclosingDeclaration; + context.enclosingDeclaration = e; + let expr = e.expression; + if (isEntityNameExpression(expr)) { + if (isIdentifier(expr) && idText(expr) === "") { + return cleanup( + /*result*/ + void 0 + ); + } + let introducesError; + ({ introducesError, node: expr } = trackExistingEntityName(expr, context)); + if (introducesError) { + return cleanup( + /*result*/ + void 0 + ); + } + } + return cleanup(factory.createExpressionWithTypeArguments( + expr, + map(e.typeArguments, (a) => syntacticNodeBuilder.tryReuseExistingTypeNode(context, a) || typeToTypeNodeHelper(getTypeFromTypeNode2(context, a), context)) + )); + function cleanup(result2) { + context.enclosingDeclaration = oldEnclosing; + return result2; + } + }); + if (result.length === clauses.length) { + return result; + } + return void 0; + } + function serializeAsClass(symbol, localName, modifierFlags) { + var _a2, _b; + const originalDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isClassLike); + const oldEnclosing = context.enclosingDeclaration; + context.enclosingDeclaration = originalDecl || oldEnclosing; + const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context)); + const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol)); + const baseTypes = getBaseTypes(classType); + const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl); + const implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || mapDefined(getImplementsTypes(classType), serializeImplementedType); + const staticType = getTypeOfSymbol(symbol); + const isClass = !!((_b = staticType.symbol) == null ? void 0 : _b.valueDeclaration) && isClassLike(staticType.symbol.valueDeclaration); + const staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType; + const heritageClauses = [ + ...!length(baseTypes) ? [] : [factory.createHeritageClause(96 /* ExtendsKeyword */, map(baseTypes, (b) => serializeBaseType(b, staticBaseType, localName)))], + ...!length(implementsExpressions) ? [] : [factory.createHeritageClause(119 /* ImplementsKeyword */, implementsExpressions)] + ]; + const symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); + const publicSymbolProps = filter(symbolProps, (s) => { + const valueDecl = s.valueDeclaration; + return !!valueDecl && !(isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name)); + }); + const hasPrivateIdentifier = some(symbolProps, (s) => { + const valueDecl = s.valueDeclaration; + return !!valueDecl && isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name); + }); + const privateProperties = hasPrivateIdentifier ? [factory.createPropertyDeclaration( + /*modifiers*/ + void 0, + factory.createPrivateIdentifier("#private"), + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + )] : emptyArray; + const publicProperties = flatMap(publicSymbolProps, (p) => serializePropertySymbolForClass( + p, + /*isStatic*/ + false, + baseTypes[0] + )); + const staticMembers = flatMap( + filter(getPropertiesOfType(staticType), (p) => !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p)), + (p) => serializePropertySymbolForClass( + p, + /*isStatic*/ + true, + staticBaseType + ) + ); + const isNonConstructableClassLikeInJsFile = !isClass && !!symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && !some(getSignaturesOfType(staticType, 1 /* Construct */)); + const constructors = isNonConstructableClassLikeInJsFile ? [factory.createConstructorDeclaration( + factory.createModifiersFromModifierFlags(2 /* Private */), + [], + /*body*/ + void 0 + )] : serializeSignatures(1 /* Construct */, staticType, staticBaseType, 176 /* Constructor */); + const indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); + context.enclosingDeclaration = oldEnclosing; + addResult( + setTextRange2( + context, + factory.createClassDeclaration( + /*modifiers*/ + void 0, + localName, + typeParamDecls, + heritageClauses, + [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties] + ), + symbol.declarations && filter(symbol.declarations, (d) => isClassDeclaration(d) || isClassExpression(d))[0] + ), + modifierFlags + ); + } + function getSomeTargetNameFromDeclarations(declarations) { + return firstDefined(declarations, (d) => { + if (isImportSpecifier(d) || isExportSpecifier(d)) { + return moduleExportNameTextUnescaped(d.propertyName || d.name); + } + if (isBinaryExpression(d) || isExportAssignment(d)) { + const expression = isExportAssignment(d) ? d.expression : d.right; + if (isPropertyAccessExpression(expression)) { + return idText(expression.name); + } + } + if (isAliasSymbolDeclaration(d)) { + const name = getNameOfDeclaration(d); + if (name && isIdentifier(name)) { + return idText(name); + } + } + return void 0; + }); + } + function serializeAsAlias(symbol, localName, modifierFlags) { + var _a2, _b, _c, _d, _e; + const node = getDeclarationOfAliasSymbol(symbol); + if (!node) return Debug.fail(); + const target = getMergedSymbol(getTargetOfAliasDeclaration( + node, + /*dontRecursivelyResolve*/ + true + )); + if (!target) { + return; + } + let verbatimTargetName = isShorthandAmbientModuleSymbol(target) && getSomeTargetNameFromDeclarations(symbol.declarations) || unescapeLeadingUnderscores(target.escapedName); + if (verbatimTargetName === "export=" /* ExportEquals */ && allowSyntheticDefaultImports) { + verbatimTargetName = "default" /* Default */; + } + const targetName = getInternalSymbolName(target, verbatimTargetName); + includePrivateSymbol(target); + switch (node.kind) { + case 208 /* BindingElement */: + if (((_b = (_a2 = node.parent) == null ? void 0 : _a2.parent) == null ? void 0 : _b.kind) === 260 /* VariableDeclaration */) { + const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context); + const { propertyName } = node; + addResult( + factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + factory.createNamedImports([factory.createImportSpecifier( + /*isTypeOnly*/ + false, + propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : void 0, + factory.createIdentifier(localName) + )]) + ), + factory.createStringLiteral(specifier2), + /*attributes*/ + void 0 + ), + 0 /* None */ + ); + break; + } + Debug.failBadSyntaxKind(((_c = node.parent) == null ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); + break; + case 304 /* ShorthandPropertyAssignment */: + if (((_e = (_d = node.parent) == null ? void 0 : _d.parent) == null ? void 0 : _e.kind) === 226 /* BinaryExpression */) { + serializeExportSpecifier( + unescapeLeadingUnderscores(symbol.escapedName), + targetName + ); + } + break; + case 260 /* VariableDeclaration */: + if (isPropertyAccessExpression(node.initializer)) { + const initializer = node.initializer; + const uniqueName = factory.createUniqueName(localName); + const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + uniqueName, + factory.createExternalModuleReference(factory.createStringLiteral(specifier2)) + ), + 0 /* None */ + ); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createIdentifier(localName), + factory.createQualifiedName(uniqueName, initializer.name) + ), + modifierFlags + ); + break; + } + // else fall through and treat commonjs require just like import= + case 271 /* ImportEqualsDeclaration */: + if (target.escapedName === "export=" /* ExportEquals */ && some(target.declarations, (d) => isSourceFile(d) && isJsonSourceFile(d))) { + serializeMaybeAliasAssignment(symbol); + break; + } + const isLocalImport = !(target.flags & 512 /* ValueModule */) && !isVariableDeclaration(node); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createIdentifier(localName), + isLocalImport ? symbolToName( + target, + context, + -1 /* All */, + /*expectsIdentifier*/ + false + ) : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))) + ), + isLocalImport ? modifierFlags : 0 /* None */ + ); + break; + case 270 /* NamespaceExportDeclaration */: + addResult(factory.createNamespaceExportDeclaration(idText(node.name)), 0 /* None */); + break; + case 273 /* ImportClause */: { + const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); + const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.moduleSpecifier; + const attributes = isImportDeclaration(node.parent) ? node.parent.attributes : void 0; + const isTypeOnly = isJSDocImportTag(node.parent); + addResult( + factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + isTypeOnly, + factory.createIdentifier(localName), + /*namedBindings*/ + void 0 + ), + specifier2, + attributes + ), + 0 /* None */ + ); + break; + } + case 274 /* NamespaceImport */: { + const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); + const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.moduleSpecifier; + const isTypeOnly = isJSDocImportTag(node.parent.parent); + addResult( + factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + isTypeOnly, + /*name*/ + void 0, + factory.createNamespaceImport(factory.createIdentifier(localName)) + ), + specifier2, + node.parent.attributes + ), + 0 /* None */ + ); + break; + } + case 280 /* NamespaceExport */: + addResult( + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamespaceExport(factory.createIdentifier(localName)), + factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)) + ), + 0 /* None */ + ); + break; + case 276 /* ImportSpecifier */: { + const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); + const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.parent.moduleSpecifier; + const isTypeOnly = isJSDocImportTag(node.parent.parent.parent); + addResult( + factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + isTypeOnly, + /*name*/ + void 0, + factory.createNamedImports([ + factory.createImportSpecifier( + /*isTypeOnly*/ + false, + localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : void 0, + factory.createIdentifier(localName) + ) + ]) + ), + specifier2, + node.parent.parent.parent.attributes + ), + 0 /* None */ + ); + break; + } + case 281 /* ExportSpecifier */: + const specifier = node.parent.parent.moduleSpecifier; + if (specifier) { + const propertyName = node.propertyName; + if (propertyName && moduleExportNameIsDefault(propertyName)) { + verbatimTargetName = "default" /* Default */; + } + } + serializeExportSpecifier( + unescapeLeadingUnderscores(symbol.escapedName), + specifier ? verbatimTargetName : targetName, + specifier && isStringLiteralLike(specifier) ? factory.createStringLiteral(specifier.text) : void 0 + ); + break; + case 277 /* ExportAssignment */: + serializeMaybeAliasAssignment(symbol); + break; + case 226 /* BinaryExpression */: + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) { + serializeMaybeAliasAssignment(symbol); + } else { + serializeExportSpecifier(localName, targetName); + } + break; + default: + return Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!"); + } + } + function serializeExportSpecifier(localName, targetName, specifier) { + addResult( + factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports([factory.createExportSpecifier( + /*isTypeOnly*/ + false, + localName !== targetName ? targetName : void 0, + localName + )]), + specifier + ), + 0 /* None */ + ); + } + function serializeMaybeAliasAssignment(symbol) { + var _a2; + if (symbol.flags & 4194304 /* Prototype */) { + return false; + } + const name = unescapeLeadingUnderscores(symbol.escapedName); + const isExportEquals = name === "export=" /* ExportEquals */; + const isDefault = name === "default" /* Default */; + const isExportAssignmentCompatibleSymbolName = isExportEquals || isDefault; + const aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol); + const target = aliasDecl && getTargetOfAliasDeclaration( + aliasDecl, + /*dontRecursivelyResolve*/ + true + ); + if (target && length(target.declarations) && some(target.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(enclosingDeclaration))) { + const expr = aliasDecl && (isExportAssignment(aliasDecl) || isBinaryExpression(aliasDecl) ? getExportAssignmentExpression(aliasDecl) : getPropertyAssignmentAliasLikeExpression(aliasDecl)); + const first2 = expr && isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : void 0; + const referenced = first2 && resolveEntityName( + first2, + -1 /* All */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + enclosingDeclaration + ); + if (referenced || target) { + includePrivateSymbol(referenced || target); + } + const prevDisableTrackSymbol = context.tracker.disableTrackSymbol; + context.tracker.disableTrackSymbol = true; + if (isExportAssignmentCompatibleSymbolName) { + results.push(factory.createExportAssignment( + /*modifiers*/ + void 0, + isExportEquals, + symbolToExpression(target, context, -1 /* All */) + )); + } else { + if (first2 === expr && first2) { + serializeExportSpecifier(name, idText(first2)); + } else if (expr && isClassExpression(expr)) { + serializeExportSpecifier(name, getInternalSymbolName(target, symbolName(target))); + } else { + const varName = getUnusedName(name, symbol); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createIdentifier(varName), + symbolToName( + target, + context, + -1 /* All */, + /*expectsIdentifier*/ + false + ) + ), + 0 /* None */ + ); + serializeExportSpecifier(name, varName); + } + } + context.tracker.disableTrackSymbol = prevDisableTrackSymbol; + return true; + } else { + const varName = getUnusedName(name, symbol); + const typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol))); + if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) { + serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 32 /* Export */); + } else { + const flags = ((_a2 = context.enclosingDeclaration) == null ? void 0 : _a2.kind) === 267 /* ModuleDeclaration */ && (!(symbol.flags & 98304 /* Accessor */) || symbol.flags & 65536 /* SetAccessor */) ? 1 /* Let */ : 2 /* Const */; + const statement = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + varName, + /*exclamationToken*/ + void 0, + serializeTypeForDeclaration( + context, + /*declaration*/ + void 0, + typeToSerialize, + symbol + ) + ) + ], flags) + ); + addResult( + statement, + target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 128 /* Ambient */ : name === varName ? 32 /* Export */ : 0 /* None */ + ); + } + if (isExportAssignmentCompatibleSymbolName) { + results.push(factory.createExportAssignment( + /*modifiers*/ + void 0, + isExportEquals, + factory.createIdentifier(varName) + )); + return true; + } else if (name !== varName) { + serializeExportSpecifier(name, varName); + return true; + } + return false; + } + } + function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) { + var _a2; + const ctxSrc = getSourceFileOfNode(context.enclosingDeclaration); + return getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !some((_a2 = typeToSerialize.symbol) == null ? void 0 : _a2.declarations, isTypeNode) && // If the type comes straight from a type node, we shouldn't try to break it up + !length(getIndexInfosOfType(typeToSerialize)) && !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class + !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && !some(getPropertiesOfType(typeToSerialize), (p) => isLateBoundName(p.escapedName)) && !some(getPropertiesOfType(typeToSerialize), (p) => some(p.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && every(getPropertiesOfType(typeToSerialize), (p) => { + if (!isIdentifierText(symbolName(p), languageVersion)) { + return false; + } + if (!(p.flags & 98304 /* Accessor */)) { + return true; + } + return getNonMissingTypeOfSymbol(p) === getWriteTypeOfSymbol(p); + }); + } + function makeSerializePropertySymbol(createProperty2, methodKind, useAccessors) { + return function serializePropertySymbol(p, isStatic2, baseType) { + var _a2, _b, _c, _d, _e, _f; + const modifierFlags = getDeclarationModifierFlagsFromSymbol(p); + const isPrivate = !!(modifierFlags & 2 /* Private */); + if (isStatic2 && p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) { + return []; + } + if (p.flags & 4194304 /* Prototype */ || p.escapedName === "constructor" || baseType && getPropertyOfType(baseType, p.escapedName) && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName))) { + return []; + } + const flag = modifierFlags & ~1024 /* Async */ | (isStatic2 ? 256 /* Static */ : 0); + const name = getPropertyNameNodeForSymbol(p, context); + const firstPropertyLikeDecl = (_a2 = p.declarations) == null ? void 0 : _a2.find(or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression)); + if (p.flags & 98304 /* Accessor */ && useAccessors) { + const result = []; + if (p.flags & 65536 /* SetAccessor */) { + const setter = p.declarations && forEach(p.declarations, (d) => { + if (d.kind === 178 /* SetAccessor */) { + return d; + } + if (isCallExpression(d) && isBindableObjectDefinePropertyCall(d)) { + return forEach(d.arguments[2].properties, (propDecl) => { + const id = getNameOfDeclaration(propDecl); + if (!!id && isIdentifier(id) && idText(id) === "set") { + return propDecl; + } + }); + } + }); + Debug.assert(!!setter); + const paramSymbol = isFunctionLikeDeclaration(setter) ? getSignatureFromDeclaration(setter).parameters[0] : void 0; + const setterDeclaration = (_b = p.declarations) == null ? void 0 : _b.find(isSetAccessor); + result.push(setTextRange2( + context, + factory.createSetAccessorDeclaration( + factory.createModifiersFromModifierFlags(flag), + name, + [factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + paramSymbol ? parameterToParameterDeclarationName(paramSymbol, getEffectiveParameterDeclaration(paramSymbol), context) : "value", + /*questionToken*/ + void 0, + isPrivate ? void 0 : serializeTypeForDeclaration(context, setterDeclaration, getWriteTypeOfSymbol(p), p) + )], + /*body*/ + void 0 + ), + setterDeclaration ?? firstPropertyLikeDecl + )); + } + if (p.flags & 32768 /* GetAccessor */) { + const isPrivate2 = modifierFlags & 2 /* Private */; + const getterDeclaration = (_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor); + result.push(setTextRange2( + context, + factory.createGetAccessorDeclaration( + factory.createModifiersFromModifierFlags(flag), + name, + [], + isPrivate2 ? void 0 : serializeTypeForDeclaration(context, getterDeclaration, getTypeOfSymbol(p), p), + /*body*/ + void 0 + ), + getterDeclaration ?? firstPropertyLikeDecl + )); + } + return result; + } else if (p.flags & (4 /* Property */ | 3 /* Variable */ | 98304 /* Accessor */)) { + return setTextRange2( + context, + createProperty2( + factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag), + name, + p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, + isPrivate ? void 0 : serializeTypeForDeclaration(context, (_d = p.declarations) == null ? void 0 : _d.find(isSetAccessorDeclaration), getWriteTypeOfSymbol(p), p), + // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 + // interface members can't have initializers, however class members _can_ + /*initializer*/ + void 0 + ), + ((_e = p.declarations) == null ? void 0 : _e.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl + ); + } + if (p.flags & (8192 /* Method */ | 16 /* Function */)) { + const type = getTypeOfSymbol(p); + const signatures = getSignaturesOfType(type, 0 /* Call */); + if (flag & 2 /* Private */) { + return setTextRange2( + context, + createProperty2( + factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag), + name, + p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ), + ((_f = p.declarations) == null ? void 0 : _f.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0] + ); + } + const results2 = []; + for (const sig of signatures) { + const decl = signatureToSignatureDeclarationHelper( + sig, + methodKind, + context, + { + name, + questionToken: p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, + modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : void 0 + } + ); + const location = sig.declaration && isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; + results2.push(setTextRange2(context, decl, location)); + } + return results2; + } + return Debug.fail(`Unhandled class member kind! ${p.__debugFlags || p.flags}`); + }; + } + function serializePropertySymbolForInterface(p, baseType) { + return serializePropertySymbolForInterfaceWorker( + p, + /*isStatic*/ + false, + baseType + ); + } + function serializeSignatures(kind, input, baseType, outputKind) { + const signatures = getSignaturesOfType(input, kind); + if (kind === 1 /* Construct */) { + if (!baseType && every(signatures, (s) => length(s.parameters) === 0)) { + return []; + } + if (baseType) { + const baseSigs = getSignaturesOfType(baseType, 1 /* Construct */); + if (!length(baseSigs) && every(signatures, (s) => length(s.parameters) === 0)) { + return []; + } + if (baseSigs.length === signatures.length) { + let failed2 = false; + for (let i = 0; i < baseSigs.length; i++) { + if (!compareSignaturesIdentical( + signatures[i], + baseSigs[i], + /*partialMatch*/ + false, + /*ignoreThisTypes*/ + false, + /*ignoreReturnTypes*/ + true, + compareTypesIdentical + )) { + failed2 = true; + break; + } + } + if (!failed2) { + return []; + } + } + } + let privateProtected = 0; + for (const s of signatures) { + if (s.declaration) { + privateProtected |= getSelectedEffectiveModifierFlags(s.declaration, 2 /* Private */ | 4 /* Protected */); + } + } + if (privateProtected) { + return [setTextRange2( + context, + factory.createConstructorDeclaration( + factory.createModifiersFromModifierFlags(privateProtected), + /*parameters*/ + [], + /*body*/ + void 0 + ), + signatures[0].declaration + )]; + } + } + const results2 = []; + for (const sig of signatures) { + const decl = signatureToSignatureDeclarationHelper(sig, outputKind, context); + results2.push(setTextRange2(context, decl, sig.declaration)); + } + return results2; + } + function serializeIndexSignatures(input, baseType) { + const results2 = []; + for (const info of getIndexInfosOfType(input)) { + if (baseType) { + const baseInfo = getIndexInfoOfType(baseType, info.keyType); + if (baseInfo) { + if (isTypeIdenticalTo(info.type, baseInfo.type)) { + continue; + } + } + } + results2.push(indexInfoToIndexSignatureDeclarationHelper( + info, + context, + /*typeNode*/ + void 0 + )); + } + return results2; + } + function serializeBaseType(t, staticType, rootName) { + const ref = trySerializeAsTypeReference(t, 111551 /* Value */); + if (ref) { + return ref; + } + const tempName = getUnusedName(`${rootName}_base`); + const statement = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + tempName, + /*exclamationToken*/ + void 0, + typeToTypeNodeHelper(staticType, context) + ) + ], 2 /* Const */) + ); + addResult(statement, 0 /* None */); + return factory.createExpressionWithTypeArguments( + factory.createIdentifier(tempName), + /*typeArguments*/ + void 0 + ); + } + function trySerializeAsTypeReference(t, flags) { + let typeArgs; + let reference; + if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) { + typeArgs = map(getTypeArguments(t), (t2) => typeToTypeNodeHelper(t2, context)); + reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */); + } else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) { + reference = symbolToExpression(t.symbol, context, 788968 /* Type */); + } + if (reference) { + return factory.createExpressionWithTypeArguments(reference, typeArgs); + } + } + function serializeImplementedType(t) { + const ref = trySerializeAsTypeReference(t, 788968 /* Type */); + if (ref) { + return ref; + } + if (t.symbol) { + return factory.createExpressionWithTypeArguments( + symbolToExpression(t.symbol, context, 788968 /* Type */), + /*typeArguments*/ + void 0 + ); + } + } + function getUnusedName(input, symbol) { + var _a2, _b; + const id = symbol ? getSymbolId(symbol) : void 0; + if (id) { + if (context.remappedSymbolNames.has(id)) { + return context.remappedSymbolNames.get(id); + } + } + if (symbol) { + input = getNameCandidateWorker(symbol, input); + } + let i = 0; + const original = input; + while ((_a2 = context.usedSymbolNames) == null ? void 0 : _a2.has(input)) { + i++; + input = `${original}_${i}`; + } + (_b = context.usedSymbolNames) == null ? void 0 : _b.add(input); + if (id) { + context.remappedSymbolNames.set(id, input); + } + return input; + } + function getNameCandidateWorker(symbol, localName) { + if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) { + const restoreFlags = saveRestoreFlags(context); + context.flags |= 16777216 /* InInitialEntityName */; + const nameCandidate = getNameOfSymbolAsWritten(symbol, context); + restoreFlags(); + localName = nameCandidate.length > 0 && isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? stripQuotes(nameCandidate) : nameCandidate; + } + if (localName === "default" /* Default */) { + localName = "_default"; + } else if (localName === "export=" /* ExportEquals */) { + localName = "_exports"; + } + localName = isIdentifierText(localName, languageVersion) && !isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-z0-9]/gi, "_"); + return localName; + } + function getInternalSymbolName(symbol, localName) { + const id = getSymbolId(symbol); + if (context.remappedSymbolNames.has(id)) { + return context.remappedSymbolNames.get(id); + } + localName = getNameCandidateWorker(symbol, localName); + context.remappedSymbolNames.set(id, localName); + return localName; + } + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags = 16384 /* UseAliasDefinedOutsideCurrentScope */, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer2) { + const nodeBuilderFlags = toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */; + const predicate = nodeBuilder.typePredicateToTypePredicateNode(typePredicate, enclosingDeclaration, nodeBuilderFlags); + const printer = createPrinterWithRemoveComments(); + const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); + printer.writeNode( + 4 /* Unspecified */, + predicate, + /*sourceFile*/ + sourceFile, + writer2 + ); + return writer2; + } + } + function formatUnionTypes(types) { + const result = []; + let flags = 0; + for (let i = 0; i < types.length; i++) { + const t = types[i]; + flags |= t.flags; + if (!(t.flags & 98304 /* Nullable */)) { + if (t.flags & (512 /* BooleanLiteral */ | 1056 /* EnumLike */)) { + const baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLikeType(t); + if (baseType.flags & 1048576 /* Union */) { + const count = baseType.types.length; + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { + result.push(baseType); + i += count - 1; + continue; + } + } + } + result.push(t); + } + } + if (flags & 65536 /* Null */) result.push(nullType); + if (flags & 32768 /* Undefined */) result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 2 /* Private */) { + return "private"; + } + if (flags === 4 /* Protected */) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && type.symbol.declarations) { + const node = walkUpParenthesizedTypes(type.symbol.declarations[0].parent); + if (isTypeAliasDeclaration(node)) { + return getSymbolOfDeclaration(node); + } + } + return void 0; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && node.parent.kind === 268 /* ModuleBlock */ && isExternalModuleAugmentation(node.parent.parent); + } + function isDefaultBindingContext(location) { + return location.kind === 307 /* SourceFile */ || isAmbientModule(location); + } + function getNameOfSymbolFromNameType(symbol, context) { + const nameType = getSymbolLinks(symbol).nameType; + if (nameType) { + if (nameType.flags & 384 /* StringOrNumberLiteral */) { + const name = "" + nameType.value; + if (!isIdentifierText(name, getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) { + return `"${escapeString(name, 34 /* doubleQuote */)}"`; + } + if (isNumericLiteralName(name) && startsWith(name, "-")) { + return `[${name}]`; + } + return name; + } + if (nameType.flags & 8192 /* UniqueESSymbol */) { + return `[${getNameOfSymbolAsWritten(nameType.symbol, context)}]`; + } + } + } + function getNameOfSymbolAsWritten(symbol, context) { + var _a; + if ((_a = context == null ? void 0 : context.remappedSymbolReferences) == null ? void 0 : _a.has(getSymbolId(symbol))) { + symbol = context.remappedSymbolReferences.get(getSymbolId(symbol)); + } + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && // If it's not the first part of an entity name, it must print as `default` + (!(context.flags & 16777216 /* InInitialEntityName */) || // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || // if not in the same binding context (source file, module declaration), it must print as `default` + context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext))) { + return "default"; + } + if (symbol.declarations && symbol.declarations.length) { + let declaration = firstDefined(symbol.declarations, (d) => getNameOfDeclaration(d) ? d : void 0); + const name2 = declaration && getNameOfDeclaration(declaration); + if (declaration && name2) { + if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) { + return symbolName(symbol); + } + if (isComputedPropertyName(name2) && !(getCheckFlags(symbol) & 4096 /* Late */)) { + const nameType = getSymbolLinks(symbol).nameType; + if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) { + const result = getNameOfSymbolFromNameType(symbol, context); + if (result !== void 0) { + return result; + } + } + } + return declarationNameToString(name2); + } + if (!declaration) { + declaration = symbol.declarations[0]; + } + if (declaration.parent && declaration.parent.kind === 260 /* VariableDeclaration */) { + return declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 231 /* ClassExpression */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + } + return declaration.kind === 231 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + } + } + const name = getNameOfSymbolFromNameType(symbol, context); + return name !== void 0 ? name : symbolName(symbol); + } + function isDeclarationVisible(node) { + if (node) { + const links = getNodeLinks(node); + if (links.isVisible === void 0) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 338 /* JSDocCallbackTag */: + case 346 /* JSDocTypedefTag */: + case 340 /* JSDocEnumTag */: + return !!(node.parent && node.parent.parent && node.parent.parent.parent && isSourceFile(node.parent.parent.parent)); + case 208 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 260 /* VariableDeclaration */: + if (isBindingPattern(node.name) && !node.name.elements.length) { + return false; + } + // falls through + case 267 /* ModuleDeclaration */: + case 263 /* ClassDeclaration */: + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 262 /* FunctionDeclaration */: + case 266 /* EnumDeclaration */: + case 271 /* ImportEqualsDeclaration */: + if (isExternalModuleAugmentation(node)) { + return true; + } + const parent = getDeclarationContainer(node); + if (!(getCombinedModifierFlagsCached(node) & 32 /* Export */) && !(node.kind !== 271 /* ImportEqualsDeclaration */ && parent.kind !== 307 /* SourceFile */ && parent.flags & 33554432 /* Ambient */)) { + return isGlobalSourceFile(parent); + } + return isDeclarationVisible(parent); + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + if (hasEffectiveModifier(node, 2 /* Private */ | 4 /* Protected */)) { + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 176 /* Constructor */: + case 180 /* ConstructSignature */: + case 179 /* CallSignature */: + case 181 /* IndexSignature */: + case 169 /* Parameter */: + case 268 /* ModuleBlock */: + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + case 187 /* TypeLiteral */: + case 183 /* TypeReference */: + case 188 /* ArrayType */: + case 189 /* TupleType */: + case 192 /* UnionType */: + case 193 /* IntersectionType */: + case 196 /* ParenthesizedType */: + case 202 /* NamedTupleMember */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 273 /* ImportClause */: + case 274 /* NamespaceImport */: + case 276 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 168 /* TypeParameter */: + // Source file and namespace export are always visible + // falls through + case 307 /* SourceFile */: + case 270 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 277 /* ExportAssignment */: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node, setVisibility) { + let exportSymbol; + if (node.kind !== 11 /* StringLiteral */ && node.parent && node.parent.kind === 277 /* ExportAssignment */) { + exportSymbol = resolveName( + node, + node, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + } else if (node.parent.kind === 281 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + let result; + let visited; + if (exportSymbol) { + visited = /* @__PURE__ */ new Set(); + visited.add(getSymbolId(exportSymbol)); + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + forEach(declarations, (declaration) => { + const resultNode = getAnyImportSyntax(declaration) || declaration; + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; + } else { + result = result || []; + pushIfUnique(result, resultNode); + } + if (isInternalModuleImportEqualsDeclaration(declaration)) { + const internalModuleReference = declaration.moduleReference; + const firstIdentifier = getFirstIdentifier(internalModuleReference); + const importSymbol = resolveName( + declaration, + firstIdentifier.escapedText, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + if (importSymbol && visited) { + if (tryAddToSet(visited, getSymbolId(importSymbol))) { + buildVisibleNodeList(importSymbol.declarations); + } + } + } + }); + } + } + function pushTypeResolution(target, propertyName) { + const resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + const { length: length2 } = resolutionTargets; + for (let i = resolutionCycleStartIndex; i < length2; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push( + /*items*/ + true + ); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (let i = resolutionTargets.length - 1; i >= resolutionStart; i--) { + if (resolutionTargetHasProperty(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function resolutionTargetHasProperty(target, propertyName) { + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + case 5 /* ResolvedTypeArguments */: + return !!target.resolvedTypeArguments; + case 6 /* ResolvedBaseTypes */: + return !!target.baseTypesResolved; + case 7 /* WriteType */: + return !!getSymbolLinks(target).writeType; + case 8 /* ParameterInitializerContainsUndefined */: + return getNodeLinks(target).parameterInitializerContainsUndefined !== void 0; + } + return Debug.assertNever(propertyName); + } + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + return findAncestor(getRootDeclaration(node), (node2) => { + switch (node2.kind) { + case 260 /* VariableDeclaration */: + case 261 /* VariableDeclarationList */: + case 276 /* ImportSpecifier */: + case 275 /* NamedImports */: + case 274 /* NamespaceImport */: + case 273 /* ImportClause */: + return false; + default: + return true; + } + }).parent; + } + function getTypeOfPrototypeProperty(prototype) { + const classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, (_) => anyType)) : classType; + } + function getTypeOfPropertyOfType(type, name) { + const prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : void 0; + } + function getTypeOfPropertyOrIndexSignatureOfType(type, name) { + var _a; + let propType; + return getTypeOfPropertyOfType(type, name) || (propType = (_a = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a.type) && addOptionality( + propType, + /*isProperty*/ + true, + /*isOptional*/ + true + ); + } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } + function isErrorType(type) { + return type === errorType || !!(type.flags & 1 /* Any */ && type.aliasSymbol); + } + function getTypeForBindingElementParent(node, checkMode) { + if (checkMode !== 0 /* Normal */) { + return getTypeForVariableLikeDeclaration( + node, + /*includeOptionality*/ + false, + checkMode + ); + } + const symbol = getSymbolOfDeclaration(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration( + node, + /*includeOptionality*/ + false, + checkMode + ); + } + function getRestType(source, properties, symbol) { + source = filterType(source, (t) => !(t.flags & 98304 /* Nullable */)); + if (source.flags & 131072 /* Never */) { + return emptyObjectType; + } + if (source.flags & 1048576 /* Union */) { + return mapType(source, (t) => getRestType(t, properties, symbol)); + } + let omitKeyType = getUnionType(map(properties, getLiteralTypeFromPropertyName)); + const spreadableProperties = []; + const unspreadableToRestKeys = []; + for (const prop of getPropertiesOfType(source)) { + const literalTypeFromProperty = getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */); + if (!isTypeAssignableTo(literalTypeFromProperty, omitKeyType) && !(getDeclarationModifierFlagsFromSymbol(prop) & (2 /* Private */ | 4 /* Protected */)) && isSpreadableProperty(prop)) { + spreadableProperties.push(prop); + } else { + unspreadableToRestKeys.push(literalTypeFromProperty); + } + } + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (unspreadableToRestKeys.length) { + omitKeyType = getUnionType([omitKeyType, ...unspreadableToRestKeys]); + } + if (omitKeyType.flags & 131072 /* Never */) { + return source; + } + const omitTypeAlias = getGlobalOmitSymbol(); + if (!omitTypeAlias) { + return errorType; + } + return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]); + } + const members = createSymbolTable(); + for (const prop of spreadableProperties) { + members.set(prop.escapedName, getSpreadSymbol( + prop, + /*readonly*/ + false + )); + } + const result = createAnonymousType(symbol, members, emptyArray, emptyArray, getIndexInfosOfType(source)); + result.objectFlags |= 4194304 /* ObjectRestType */; + return result; + } + function isGenericTypeWithUndefinedConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */); + } + function getNonUndefinedType(type) { + const typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, (t) => t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t) : type; + return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */); + } + function getFlowTypeOfDestructuring(node, declaredType) { + const reference = getSyntheticElementAccess(node); + return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; + } + function getSyntheticElementAccess(node) { + const parentAccess = getParentElementAccess(node); + if (parentAccess && canHaveFlowNode(parentAccess) && parentAccess.flowNode) { + const propName = getDestructuringPropertyName(node); + if (propName) { + const literal = setTextRange(parseNodeFactory.createStringLiteral(propName), node); + const lhsExpr = isLeftHandSideExpression(parentAccess) ? parentAccess : parseNodeFactory.createParenthesizedExpression(parentAccess); + const result = setTextRange(parseNodeFactory.createElementAccessExpression(lhsExpr, literal), node); + setParent(literal, result); + setParent(result, node); + if (lhsExpr !== parentAccess) { + setParent(lhsExpr, result); + } + result.flowNode = parentAccess.flowNode; + return result; + } + } + } + function getParentElementAccess(node) { + const ancestor = node.parent.parent; + switch (ancestor.kind) { + case 208 /* BindingElement */: + case 303 /* PropertyAssignment */: + return getSyntheticElementAccess(ancestor); + case 209 /* ArrayLiteralExpression */: + return getSyntheticElementAccess(node.parent); + case 260 /* VariableDeclaration */: + return ancestor.initializer; + case 226 /* BinaryExpression */: + return ancestor.right; + } + } + function getDestructuringPropertyName(node) { + const parent = node.parent; + if (node.kind === 208 /* BindingElement */ && parent.kind === 206 /* ObjectBindingPattern */) { + return getLiteralPropertyNameText(node.propertyName || node.name); + } + if (node.kind === 303 /* PropertyAssignment */ || node.kind === 304 /* ShorthandPropertyAssignment */) { + return getLiteralPropertyNameText(node.name); + } + return "" + parent.elements.indexOf(node); + } + function getLiteralPropertyNameText(name) { + const type = getLiteralTypeFromPropertyName(name); + return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : void 0; + } + function getTypeForBindingElement(declaration) { + const checkMode = declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */; + const parentType = getTypeForBindingElementParent(declaration.parent.parent, checkMode); + return parentType && getBindingElementTypeFromParentType( + declaration, + parentType, + /*noTupleBoundsCheck*/ + false + ); + } + function getBindingElementTypeFromParentType(declaration, parentType, noTupleBoundsCheck) { + if (isTypeAny(parentType)) { + return parentType; + } + const pattern = declaration.parent; + if (strictNullChecks && declaration.flags & 33554432 /* Ambient */ && isPartOfParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } else if (strictNullChecks && pattern.parent.initializer && !hasTypeFacts(getTypeOfInitializer(pattern.parent.initializer), 65536 /* EQUndefined */)) { + parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); + } + const accessFlags = 32 /* ExpressionPosition */ | (noTupleBoundsCheck || hasDefaultValue(declaration) ? 16 /* AllowMissing */ : 0); + let type; + if (pattern.kind === 206 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + parentType = getReducedType(parentType); + if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { + error(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types); + return errorType; + } + const literalMembers = []; + for (const element of pattern.elements) { + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } else { + const name = declaration.propertyName || declaration.name; + const indexType = getLiteralTypeFromPropertyName(name); + const declaredType = getIndexedAccessType(parentType, indexType, accessFlags, name); + type = getFlowTypeOfDestructuring(declaration, declaredType); + } + } else { + const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern); + const index = pattern.elements.indexOf(declaration); + if (declaration.dotDotDotToken) { + const baseConstraint = mapType(parentType, (t) => t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t); + type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType); + } else if (isArrayLikeType(parentType)) { + const indexType = getNumberLiteralType(index); + const declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, accessFlags, declaration.name) || errorType; + type = getFlowTypeOfDestructuring(declaration, declaredType); + } else { + type = elementType; + } + } + if (!declaration.initializer) { + return type; + } + if (getEffectiveTypeAnnotationNode(walkUpBindingElementsAndPatterns(declaration))) { + return strictNullChecks && !hasTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */), 16777216 /* IsUndefined */) ? getNonUndefinedType(type) : type; + } + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* Normal */)], 2 /* Subtype */)); + } + function getTypeForDeclarationFromJSDocComment(declaration) { + const jsdocType = getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return void 0; + } + function isNullOrUndefined2(node) { + const expr = skipParentheses( + node, + /*excludeJSDocTypeAssertions*/ + true + ); + return expr.kind === 106 /* NullKeyword */ || expr.kind === 80 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral2(node) { + const expr = skipParentheses( + node, + /*excludeJSDocTypeAssertions*/ + true + ); + return expr.kind === 209 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } + function addOptionality(type, isProperty = false, isOptional = true) { + return strictNullChecks && isOptional ? getOptionalType(type, isProperty) : type; + } + function getTypeForVariableLikeDeclaration(declaration, includeOptionality, checkMode) { + if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 249 /* ForInStatement */) { + const indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression( + declaration.parent.parent.expression, + /*checkMode*/ + checkMode + ))); + return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; + } + if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 250 /* ForOfStatement */) { + const forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement) || anyType; + } + if (isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + const isProperty = isPropertyDeclaration(declaration) && !hasAccessorModifier(declaration) || isPropertySignature(declaration) || isJSDocPropertyTag(declaration); + const isOptional = includeOptionality && isOptionalDeclaration(declaration); + const declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + if (declaredType) { + return isTypeAny(declaredType) || declaredType === unknownType ? declaredType : errorType; + } + return useUnknownInCatchVariables ? unknownType : anyType; + } + if (declaredType) { + return addOptionality(declaredType, isProperty, isOptional); + } + if ((noImplicitAny || isInJSFile(declaration)) && isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && !(getCombinedModifierFlagsCached(declaration) & 32 /* Export */) && !(declaration.flags & 33554432 /* Ambient */)) { + if (!(getCombinedNodeFlagsCached(declaration) & 6 /* Constant */) && (!declaration.initializer || isNullOrUndefined2(declaration.initializer))) { + return autoType; + } + if (declaration.initializer && isEmptyArrayLiteral2(declaration.initializer)) { + return autoArrayType; + } + } + if (isParameter(declaration)) { + if (!declaration.symbol) { + return; + } + const func = declaration.parent; + if (func.kind === 178 /* SetAccessor */ && hasBindableName(func)) { + const getter = getDeclarationOfKind(getSymbolOfDeclaration(declaration.parent), 177 /* GetAccessor */); + if (getter) { + const getterSignature = getSignatureFromDeclaration(getter); + const thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + const parameterTypeOfTypeTag = getParameterTypeOfTypeTag(func, declaration); + if (parameterTypeOfTypeTag) return parameterTypeOfTypeTag; + const type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); + if (type) { + return addOptionality( + type, + /*isProperty*/ + false, + isOptional + ); + } + } + if (hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) { + if (isInJSFile(declaration) && !isParameter(declaration)) { + const containerObjectType = getJSContainerObjectType(declaration, getSymbolOfDeclaration(declaration), getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; + } + } + const type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration, checkMode)); + return addOptionality(type, isProperty, isOptional); + } + if (isPropertyDeclaration(declaration) && (noImplicitAny || isInJSFile(declaration))) { + if (!hasStaticModifier(declaration)) { + const constructor = findConstructorDeclaration(declaration.parent); + const type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0; + return type && addOptionality( + type, + /*isProperty*/ + true, + isOptional + ); + } else { + const staticBlocks = filter(declaration.parent.members, isClassStaticBlockDeclaration); + const type = staticBlocks.length ? getFlowTypeInStaticBlocks(declaration.symbol, staticBlocks) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0; + return type && addOptionality( + type, + /*isProperty*/ + true, + isOptional + ); + } + } + if (isJsxAttribute(declaration)) { + return trueType; + } + if (isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern( + declaration.name, + /*includePatternInType*/ + false, + /*reportErrors*/ + true + ); + } + return void 0; + } + function isConstructorDeclaredProperty(symbol) { + if (symbol.valueDeclaration && isBinaryExpression(symbol.valueDeclaration)) { + const links = getSymbolLinks(symbol); + if (links.isConstructorDeclaredProperty === void 0) { + links.isConstructorDeclaredProperty = false; + links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, (declaration) => isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && (declaration.left.kind !== 212 /* ElementAccessExpression */ || isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration( + /*declaredType*/ + void 0, + declaration, + symbol, + declaration + )); + } + return links.isConstructorDeclaredProperty; + } + return false; + } + function isAutoTypedProperty(symbol) { + const declaration = symbol.valueDeclaration; + return declaration && isPropertyDeclaration(declaration) && !getEffectiveTypeAnnotationNode(declaration) && !declaration.initializer && (noImplicitAny || isInJSFile(declaration)); + } + function getDeclaringConstructor(symbol) { + if (!symbol.declarations) { + return; + } + for (const declaration of symbol.declarations) { + const container = getThisContainer( + declaration, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (container && (container.kind === 176 /* Constructor */ || isJSConstructor(container))) { + return container; + } + } + } + function getFlowTypeFromCommonJSExport(symbol) { + const file = getSourceFileOfNode(symbol.declarations[0]); + const accessName = unescapeLeadingUnderscores(symbol.escapedName); + const areAllModuleExports = symbol.declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && isModuleExportsAccessExpression(d.expression)); + const reference = areAllModuleExports ? factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(factory.createIdentifier("module"), factory.createIdentifier("exports")), accessName) : factory.createPropertyAccessExpression(factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + setParent(reference.expression.expression, reference.expression); + } + setParent(reference.expression, reference); + setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); + } + function getFlowTypeInStaticBlocks(symbol, staticBlocks) { + const accessName = startsWith(symbol.escapedName, "__#") ? factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) : unescapeLeadingUnderscores(symbol.escapedName); + for (const staticBlock of staticBlocks) { + const reference = factory.createPropertyAccessExpression(factory.createThis(), accessName); + setParent(reference.expression, reference); + setParent(reference, staticBlock); + reference.flowNode = staticBlock.returnFlowNode; + const flowType = getFlowTypeOfProperty(reference, symbol); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) { + error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + if (everyType(flowType, isNullableType)) { + continue; + } + return convertAutoToAny(flowType); + } + } + function getFlowTypeInConstructor(symbol, constructor) { + const accessName = startsWith(symbol.escapedName, "__#") ? factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) : unescapeLeadingUnderscores(symbol.escapedName); + const reference = factory.createPropertyAccessExpression(factory.createThis(), accessName); + setParent(reference.expression, reference); + setParent(reference, constructor); + reference.flowNode = constructor.returnFlowNode; + const flowType = getFlowTypeOfProperty(reference, symbol); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) { + error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return everyType(flowType, isNullableType) ? void 0 : convertAutoToAny(flowType); + } + function getFlowTypeOfProperty(reference, prop) { + const initialType = (prop == null ? void 0 : prop.valueDeclaration) && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & 128 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + return getFlowTypeOfReference(reference, autoType, initialType); + } + function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { + const container = getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + const tag = isInJSFile(container) ? getJSDocTypeTag(container) : void 0; + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + const containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); + } + let type; + let definedInConstructor = false; + let definedInMethod = false; + if (isConstructorDeclaredProperty(symbol)) { + type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); + } + if (!type) { + let types; + if (symbol.declarations) { + let jsdocType; + for (const declaration of symbol.declarations) { + const expression = isBinaryExpression(declaration) || isCallExpression(declaration) ? declaration : isAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : void 0; + if (!expression) { + continue; + } + const kind = isAccessExpression(expression) ? getAssignmentDeclarationPropertyAccessKind(expression) : getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */ || isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } else { + definedInMethod = true; + } + } + if (!isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push(isBinaryExpression(expression) || isCallExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } + } + type = jsdocType; + } + if (!type) { + if (!length(types)) { + return errorType; + } + let constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : void 0; + if (definedInMethod) { + const propType = getTypeOfPropertyInBaseClass(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + const sourceTypes = some(constructorTypes, (t) => !!(t.flags & ~98304 /* Nullable */)) ? constructorTypes : types; + type = getUnionType(sourceTypes); + } + } + const widened = getWidenedType(addOptionality( + type, + /*isProperty*/ + false, + definedInMethod && !definedInConstructor + )); + if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { + reportImplicitAny(symbol.valueDeclaration, anyType); + return anyType; + } + return widened; + } + function getJSContainerObjectType(decl, symbol, init) { + var _a, _b; + if (!isInJSFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) { + return void 0; + } + const exports2 = createSymbolTable(); + while (isBinaryExpression(decl) || isPropertyAccessExpression(decl)) { + const s2 = getSymbolOfNode(decl); + if ((_a = s2 == null ? void 0 : s2.exports) == null ? void 0 : _a.size) { + mergeSymbolTable(exports2, s2.exports); + } + decl = isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + const s = getSymbolOfNode(decl); + if ((_b = s == null ? void 0 : s.exports) == null ? void 0 : _b.size) { + mergeSymbolTable(exports2, s.exports); + } + const type = createAnonymousType(symbol, exports2, emptyArray, emptyArray, emptyArray); + type.objectFlags |= 4096 /* JSLiteral */; + return type; + } + function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { + var _a; + const typeNode = getEffectiveTypeAnnotationNode(expression.parent); + if (typeNode) { + const type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } else if (!isErrorType(declaredType) && !isErrorType(type) && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType( + /*firstDeclaration*/ + void 0, + declaredType, + declaration, + type + ); + } + } + if ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) { + const possiblyAnnotatedSymbol = getFunctionExpressionParentSymbolOrSymbol(symbol.parent); + if (possiblyAnnotatedSymbol.valueDeclaration) { + const typeNode2 = getEffectiveTypeAnnotationNode(possiblyAnnotatedSymbol.valueDeclaration); + if (typeNode2) { + const annotationSymbol = getPropertyOfType(getTypeFromTypeNode(typeNode2), symbol.escapedName); + if (annotationSymbol) { + return getNonMissingTypeOfSymbol(annotationSymbol); + } + } + } + } + return declaredType; + } + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { + if (isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); + } + const objectLitType = checkExpressionCached(expression.arguments[2]); + const valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + return valueType; + } + const getFunc = getTypeOfPropertyOfType(objectLitType, "get"); + if (getFunc) { + const getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + const setFunc = getTypeOfPropertyOfType(objectLitType, "set"); + if (setFunc) { + const setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } + if (containsSameNamedThisProperty(expression.left, expression.right)) { + return anyType; + } + const isDirectExport = kind === 1 /* ExportsProperty */ && (isPropertyAccessExpression(expression.left) || isElementAccessExpression(expression.left)) && (isModuleExportsAccessExpression(expression.left.expression) || isIdentifier(expression.left.expression) && isExportsIdentifier(expression.left.expression)); + const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : isDirectExport ? getRegularTypeOfLiteralType(checkExpressionCached(expression.right)) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 524288 /* Object */ && kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { + const exportedType = resolveStructuredTypeMembers(type); + const members = createSymbolTable(); + copyEntries(exportedType.members, members); + const initialSize = members.size; + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach((s, name) => { + var _a; + const exportedMember = members.get(name); + if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* Alias */)) { + if (s.flags & 111551 /* Value */ && exportedMember.flags & 111551 /* Value */) { + if (s.valueDeclaration && exportedMember.valueDeclaration && getSourceFileOfNode(s.valueDeclaration) !== getSourceFileOfNode(exportedMember.valueDeclaration)) { + const unescapedName = unescapeLeadingUnderscores(s.escapedName); + const exportedMemberName = ((_a = tryCast(exportedMember.valueDeclaration, isNamedDeclaration)) == null ? void 0 : _a.name) || exportedMember.valueDeclaration; + addRelatedInfo( + error(s.valueDeclaration, Diagnostics.Duplicate_identifier_0, unescapedName), + createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName) + ); + addRelatedInfo( + error(exportedMemberName, Diagnostics.Duplicate_identifier_0, unescapedName), + createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName) + ); + } + const union = createSymbol(s.flags | exportedMember.flags, name); + union.links.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + union.valueDeclaration = exportedMember.valueDeclaration; + union.declarations = concatenate(exportedMember.declarations, s.declarations); + members.set(name, union); + } else { + members.set(name, mergeSymbol(s, exportedMember)); + } + } else { + members.set(name, s); + } + }); + const result = createAnonymousType( + initialSize !== members.size ? void 0 : exportedType.symbol, + // Only set the type's symbol if it looks to be the same as the original type + members, + exportedType.callSignatures, + exportedType.constructSignatures, + exportedType.indexInfos + ); + if (initialSize === members.size) { + if (type.aliasSymbol) { + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = type.aliasTypeArguments; + } + if (getObjectFlags(type) & 4 /* Reference */) { + result.aliasSymbol = type.symbol; + const args = getTypeArguments(type); + result.aliasTypeArguments = length(args) ? args : void 0; + } + } + result.objectFlags |= getPropagatingFlagsOfTypes([type]) | getObjectFlags(type) & (4096 /* JSLiteral */ | 16384 /* ArrayLiteral */ | 128 /* ObjectLiteral */); + if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { + result.objectFlags |= 16777216 /* IsClassInstanceClone */; + } + return result; + } + if (isEmptyArrayLiteralType(type)) { + reportImplicitAny(expression, anyArrayType); + return anyArrayType; + } + return type; + } + function containsSameNamedThisProperty(thisProperty, expression) { + return isPropertyAccessExpression(thisProperty) && thisProperty.expression.kind === 110 /* ThisKeyword */ && forEachChildRecursively(expression, (n) => isMatchingReference(thisProperty, n)); + } + function isDeclarationInConstructor(expression) { + const thisContainer = getThisContainer( + expression, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + return thisContainer.kind === 176 /* Constructor */ || thisContainer.kind === 262 /* FunctionDeclaration */ || thisContainer.kind === 218 /* FunctionExpression */ && !isPrototypePropertyAssignment(thisContainer.parent); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + Debug.assert(types.length === declarations.length); + return types.filter((_, i) => { + const declaration = declarations[i]; + const expression = isBinaryExpression(declaration) ? declaration : isBinaryExpression(declaration.parent) ? declaration.parent : void 0; + return expression && isDeclarationInConstructor(expression); + }); + } + function getTypeFromBindingElement(element, includePatternInType, reportErrors2) { + if (element.initializer) { + const contextualType = isBindingPattern(element.name) ? getTypeFromBindingPattern( + element.name, + /*includePatternInType*/ + true, + /*reportErrors*/ + false + ) : unknownType; + return addOptionality(getWidenedLiteralTypeForInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType))); + } + if (isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors2); + } + if (reportErrors2 && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); + } + return includePatternInType ? nonInferrableAnyType : anyType; + } + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) { + const members = createSymbolTable(); + let stringIndexInfo; + let objectFlags = 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; + forEach(pattern.elements, (e) => { + const name = e.propertyName || e.name; + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo( + stringType, + anyType, + /*isReadonly*/ + false + ); + return; + } + const exprType = getLiteralTypeFromPropertyName(name); + if (!isTypeUsableAsPropertyName(exprType)) { + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + return; + } + const text = getPropertyNameFromType(exprType); + const flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); + const symbol = createSymbol(flags, text); + symbol.links.type = getTypeFromBindingElement(e, includePatternInType, reportErrors2); + members.set(symbol.escapedName, symbol); + }); + const result = createAnonymousType( + /*symbol*/ + void 0, + members, + emptyArray, + emptyArray, + stringIndexInfo ? [stringIndexInfo] : emptyArray + ); + result.objectFlags |= objectFlags; + if (includePatternInType) { + result.pattern = pattern; + result.objectFlags |= 131072 /* ContainsObjectOrArrayLiteral */; + } + return result; + } + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2) { + const elements = pattern.elements; + const lastElement = lastOrUndefined(elements); + const restElement = lastElement && lastElement.kind === 208 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : void 0; + if (elements.length === 0 || elements.length === 1 && restElement) { + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; + } + const elementTypes = map(elements, (e) => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors2)); + const minLength = findLastIndex(elements, (e) => !(e === restElement || isOmittedExpression(e) || hasDefaultValue(e)), elements.length - 1) + 1; + const elementFlags = map(elements, (e, i) => e === restElement ? 4 /* Rest */ : i >= minLength ? 2 /* Optional */ : 1 /* Required */); + let result = createTupleType(elementTypes, elementFlags); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + result.objectFlags |= 131072 /* ContainsObjectOrArrayLiteral */; + } + return result; + } + function getTypeFromBindingPattern(pattern, includePatternInType = false, reportErrors2 = false) { + if (includePatternInType) contextualBindingPatterns.push(pattern); + const result = pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2); + if (includePatternInType) contextualBindingPatterns.pop(); + return result; + } + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors2) { + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration( + declaration, + /*includeOptionality*/ + true, + 0 /* Normal */ + ), declaration, reportErrors2); + } + function getTypeFromImportAttributes(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const symbol = createSymbol(4096 /* ObjectLiteral */, "__importAttributes" /* ImportAttributes */); + const members = createSymbolTable(); + forEach(node.elements, (attr) => { + const member = createSymbol(4 /* Property */, getNameFromImportAttribute(attr)); + member.parent = symbol; + member.links.type = checkImportAttribute(attr); + member.links.target = member; + members.set(member.escapedName, member); + }); + const type = createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray); + type.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* NonInferrableType */; + links.resolvedType = type; + } + return links.resolvedType; + } + function isGlobalSymbolConstructor(node) { + const symbol = getSymbolOfNode(node); + const globalSymbol = getGlobalESSymbolConstructorTypeSymbol( + /*reportErrors*/ + false + ); + return globalSymbol && symbol && symbol === globalSymbol; + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors2) { + if (type) { + if (type.flags & 4096 /* ESSymbol */ && isGlobalSymbolConstructor(declaration.parent)) { + type = getESSymbolLikeTypeForNode(declaration); + } + if (reportErrors2) { + reportErrorsFromWidening(declaration, type); + } + if (type.flags & 8192 /* UniqueESSymbol */ && (isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfDeclaration(declaration)) { + type = esSymbolType; + } + return getWidenedType(type); + } + type = isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; + if (reportErrors2) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAny(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + const root = getRootDeclaration(declaration); + const memberDeclaration = root.kind === 169 /* Parameter */ ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function tryGetTypeFromEffectiveTypeNode(node) { + const typeNode = getEffectiveTypeAnnotationNode(node); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } + function isParameterOfContextSensitiveSignature(symbol) { + let decl = symbol.valueDeclaration; + if (!decl) { + return false; + } + if (isBindingElement(decl)) { + decl = walkUpBindingElementsAndPatterns(decl); + } + if (isParameter(decl)) { + return isContextSensitiveFunctionOrObjectLiteralMethod(decl.parent); + } + return false; + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + const links = getSymbolLinks(symbol); + if (!links.type) { + const type = getTypeOfVariableOrParameterOrPropertyWorker(symbol); + if (!links.type && !isParameterOfContextSensitiveSignature(symbol)) { + links.type = type; + } + return type; + } + return links.type; + } + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */ && symbol.valueDeclaration) { + const fileSymbol = getSymbolOfDeclaration(getSourceFileOfNode(symbol.valueDeclaration)); + const result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.links.target = fileSymbol; + if (fileSymbol.valueDeclaration) result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) result.members = new Map(fileSymbol.members); + if (fileSymbol.exports) result.exports = new Map(fileSymbol.exports); + const members = createSymbolTable(); + members.set("exports", result); + return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray); + } + Debug.assertIsDefined(symbol.valueDeclaration); + const declaration = symbol.valueDeclaration; + if (isSourceFile(declaration) && isJsonSourceFile(declaration)) { + if (!declaration.statements.length) { + return emptyObjectType; + } + return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression))); + } + if (isAccessor(declaration)) { + return getTypeOfAccessors(symbol); + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + return reportCircularityError(symbol); + } + let type; + if (declaration.kind === 277 /* ExportAssignment */) { + type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached(declaration.expression), declaration); + } else if (isBinaryExpression(declaration) || isInJSFile(declaration) && (isCallExpression(declaration) || (isPropertyAccessExpression(declaration) || isBindableStaticElementAccessExpression(declaration)) && isBinaryExpression(declaration.parent))) { + type = getWidenedTypeForAssignmentDeclaration(symbol); + } else if (isPropertyAccessExpression(declaration) || isElementAccessExpression(declaration) || isIdentifier(declaration) || isStringLiteralLike(declaration) || isNumericLiteral(declaration) || isClassDeclaration(declaration) || isFunctionDeclaration(declaration) || isMethodDeclaration(declaration) && !isObjectLiteralMethod(declaration) || isMethodSignature(declaration) || isSourceFile(declaration)) { + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = isBinaryExpression(declaration.parent) ? getWidenedTypeForAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } else if (isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } else if (isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } else if (isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } else if (isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } else if (isParameter(declaration) || isPropertyDeclaration(declaration) || isPropertySignature(declaration) || isVariableDeclaration(declaration) || isBindingElement(declaration) || isJSDocPropertyLikeTag(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration( + declaration, + /*reportErrors*/ + true + ); + } else if (isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } else if (isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } else { + return Debug.fail("Unhandled declaration kind! " + Debug.formatSyntaxKind(declaration.kind) + " for " + Debug.formatSymbol(symbol)); + } + if (!popTypeResolution()) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + return reportCircularityError(symbol); + } + return type; + } + function getAnnotatedAccessorTypeNode(accessor) { + if (accessor) { + switch (accessor.kind) { + case 177 /* GetAccessor */: + const getterTypeAnnotation = getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation; + case 178 /* SetAccessor */: + const setterTypeAnnotation = getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation; + case 172 /* PropertyDeclaration */: + Debug.assert(hasAccessorModifier(accessor)); + const accessorTypeAnnotation = getEffectiveTypeAnnotationNode(accessor); + return accessorTypeAnnotation; + } + } + return void 0; + } + function getAnnotatedAccessorType(accessor) { + const node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } + function getAnnotatedAccessorThisParameter(accessor) { + const parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + const links = getSymbolLinks(symbol); + if (!links.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */); + const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */); + const accessor = tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration); + let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && getWidenedTypeForVariableLikeDeclaration( + accessor, + /*reportErrors*/ + true + ); + if (!type) { + if (setter && !isPrivateWithinAmbient(setter)) { + errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } else if (getter && !isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } else if (accessor && !isPrivateWithinAmbient(accessor)) { + errorOrSuggestion(noImplicitAny, accessor, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), "any"); + } + type = anyType; + } + if (!popTypeResolution()) { + if (getAnnotatedAccessorTypeNode(getter)) { + error(getter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } else if (getAnnotatedAccessorTypeNode(setter)) { + error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } else if (getAnnotatedAccessorTypeNode(accessor)) { + error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } else if (getter && noImplicitAny) { + error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } + type = anyType; + } + links.type ?? (links.type = type); + } + return links.type; + } + function getWriteTypeOfAccessors(symbol) { + const links = getSymbolLinks(symbol); + if (!links.writeType) { + if (!pushTypeResolution(symbol, 7 /* WriteType */)) { + return errorType; + } + const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */) ?? tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration); + let writeType = getAnnotatedAccessorType(setter); + if (!popTypeResolution()) { + if (getAnnotatedAccessorTypeNode(setter)) { + error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } + writeType = anyType; + } + links.writeType ?? (links.writeType = writeType || getTypeOfAccessors(symbol)); + } + return links.writeType; + } + function getBaseTypeVariableOfClass(symbol) { + const baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : baseConstructorType.flags & 2097152 /* Intersection */ ? find(baseConstructorType.types, (t) => !!(t.flags & 8650752 /* TypeVariable */)) : void 0; + } + function getTypeOfFuncClassEnumModule(symbol) { + let links = getSymbolLinks(symbol); + const originalLinks = links; + if (!links.type) { + const expando = symbol.valueDeclaration && getSymbolOfExpando( + symbol.valueDeclaration, + /*allowDeclaration*/ + false + ); + if (expando) { + const merged = mergeJSSymbols(symbol, expando); + if (merged) { + symbol = merged; + links = merged.links; + } + } + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + const declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } else if (declaration && (declaration.kind === 226 /* BinaryExpression */ || isAccessExpression(declaration) && declaration.parent.kind === 226 /* BinaryExpression */)) { + return getWidenedTypeForAssignmentDeclaration(symbol); + } else if (symbol.flags & 512 /* ValueModule */ && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + const resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + const exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + const type2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? void 0 : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); + } + return type2; + } + } + const type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + const baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType( + type, + /*isProperty*/ + true + ) : type; + } + } + function getTypeOfEnumMember(symbol) { + const links = getSymbolLinks(symbol); + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); + } + function getTypeOfAlias(symbol) { + const links = getSymbolLinks(symbol); + if (!links.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + const targetSymbol = resolveAlias(symbol); + const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration( + getDeclarationOfAliasSymbol(symbol), + /*dontRecursivelyResolve*/ + true + ); + const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); + links.type ?? (links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType); + if (!popTypeResolution()) { + reportCircularityError(exportSymbol ?? symbol); + return links.type ?? (links.type = errorType); + } + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + const links = getSymbolLinks(symbol); + return links.type || (links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper)); + } + function getWriteTypeOfInstantiatedSymbol(symbol) { + const links = getSymbolLinks(symbol); + return links.writeType || (links.writeType = instantiateType(getWriteTypeOfSymbol(links.target), links.mapper)); + } + function reportCircularityError(symbol) { + const declaration = symbol.valueDeclaration; + if (declaration) { + if (getEffectiveTypeAnnotationNode(declaration)) { + error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return errorType; + } + if (noImplicitAny && (declaration.kind !== 169 /* Parameter */ || declaration.initializer)) { + error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + } else if (symbol.flags & 2097152 /* Alias */) { + const node = getDeclarationOfAliasSymbol(symbol); + if (node) { + error(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + return anyType; + } + function getTypeOfSymbolWithDeferredType(symbol) { + const links = getSymbolLinks(symbol); + if (!links.type) { + Debug.assertIsDefined(links.deferralParent); + Debug.assertIsDefined(links.deferralConstituents); + links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents); + } + return links.type; + } + function getWriteTypeOfSymbolWithDeferredType(symbol) { + const links = getSymbolLinks(symbol); + if (!links.writeType && links.deferralWriteConstituents) { + Debug.assertIsDefined(links.deferralParent); + Debug.assertIsDefined(links.deferralConstituents); + links.writeType = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralWriteConstituents) : getIntersectionType(links.deferralWriteConstituents); + } + return links.writeType; + } + function getWriteTypeOfSymbol(symbol) { + const checkFlags = getCheckFlags(symbol); + if (symbol.flags & 4 /* Property */) { + return checkFlags & 2 /* SyntheticProperty */ ? checkFlags & 65536 /* DeferredType */ ? getWriteTypeOfSymbolWithDeferredType(symbol) || getTypeOfSymbolWithDeferredType(symbol) : ( + // NOTE: cast to TransientSymbol should be safe because only TransientSymbols can have CheckFlags.SyntheticProperty + symbol.links.writeType || symbol.links.type + ) : removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */)); + } + if (symbol.flags & 98304 /* Accessor */) { + return checkFlags & 1 /* Instantiated */ ? getWriteTypeOfInstantiatedSymbol(symbol) : getWriteTypeOfAccessors(symbol); + } + return getTypeOfSymbol(symbol); + } + function getTypeOfSymbol(symbol) { + const checkFlags = getCheckFlags(symbol); + if (checkFlags & 65536 /* DeferredType */) { + return getTypeOfSymbolWithDeferredType(symbol); + } + if (checkFlags & 1 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (checkFlags & 262144 /* Mapped */) { + return getTypeOfMappedSymbol(symbol); + } + if (checkFlags & 8192 /* ReverseMapped */) { + return getTypeOfReverseMappedSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304 /* Accessor */) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getTypeOfAlias(symbol); + } + return errorType; + } + function getNonMissingTypeOfSymbol(symbol) { + return removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */)); + } + function isReferenceToSomeType(type, targets) { + if (type === void 0 || (getObjectFlags(type) & 4 /* Reference */) === 0) { + return false; + } + for (const target of targets) { + if (type.target === target) { + return true; + } + } + return false; + } + function isReferenceToType(type, target) { + return type !== void 0 && target !== void 0 && (getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target; + } + function getTargetType(type) { + return getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + } + function hasBaseType(type, checkBase) { + return check(type); + function check(type2) { + if (getObjectFlags(type2) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + const target = getTargetType(type2); + return target === checkBase || some(getBaseTypes(target), check); + } else if (type2.flags & 2097152 /* Intersection */) { + return some(type2.types, check); + } + return false; + } + } + function appendTypeParameters(typeParameters, declarations) { + for (const declaration of declarations) { + typeParameters = appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(declaration))); + } + return typeParameters; + } + function getOuterTypeParameters(node, includeThisTypes) { + while (true) { + node = node.parent; + if (node && isBinaryExpression(node)) { + const assignmentKind = getAssignmentDeclarationKind(node); + if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) { + const symbol = getSymbolOfDeclaration(node.left); + if (symbol && symbol.parent && !findAncestor(symbol.parent.valueDeclaration, (d) => node === d)) { + node = symbol.parent.valueDeclaration; + } + } + } + if (!node) { + return void 0; + } + const kind = node.kind; + switch (kind) { + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 264 /* InterfaceDeclaration */: + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 173 /* MethodSignature */: + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + case 317 /* JSDocFunctionType */: + case 262 /* FunctionDeclaration */: + case 174 /* MethodDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 265 /* TypeAliasDeclaration */: + case 345 /* JSDocTemplateTag */: + case 346 /* JSDocTypedefTag */: + case 340 /* JSDocEnumTag */: + case 338 /* JSDocCallbackTag */: + case 200 /* MappedType */: + case 194 /* ConditionalType */: { + const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if ((kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */ || isObjectLiteralMethod(node)) && isContextSensitive(node)) { + const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfDeclaration(node)), 0 /* Call */)); + if (signature && signature.typeParameters) { + return [...outerTypeParameters || emptyArray, ...signature.typeParameters]; + } + } + if (kind === 200 /* MappedType */) { + return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))); + } else if (kind === 194 /* ConditionalType */) { + return concatenate(outerTypeParameters, getInferTypeParameters(node)); + } + const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node)); + const thisType = includeThisTypes && (kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 264 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType; + return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; + } + case 341 /* JSDocParameterTag */: + const paramSymbol = getParameterSymbolFromJSDoc(node); + if (paramSymbol) { + node = paramSymbol.valueDeclaration; + } + break; + case 320 /* JSDoc */: { + const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + return node.tags ? appendTypeParameters(outerTypeParameters, flatMap(node.tags, (t) => isJSDocTemplateTag(t) ? t.typeParameters : void 0)) : outerTypeParameters; + } + } + } + } + function getOuterTypeParametersOfClassOrInterface(symbol) { + var _a; + const declaration = symbol.flags & 32 /* Class */ || symbol.flags & 16 /* Function */ ? symbol.valueDeclaration : (_a = symbol.declarations) == null ? void 0 : _a.find((decl) => { + if (decl.kind === 264 /* InterfaceDeclaration */) { + return true; + } + if (decl.kind !== 260 /* VariableDeclaration */) { + return false; + } + const initializer = decl.initializer; + return !!initializer && (initializer.kind === 218 /* FunctionExpression */ || initializer.kind === 219 /* ArrowFunction */); + }); + Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); + return getOuterTypeParameters(declaration); + } + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + if (!symbol.declarations) { + return; + } + let result; + for (const node of symbol.declarations) { + if (node.kind === 264 /* InterfaceDeclaration */ || node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ || isJSConstructor(node) || isTypeAlias(node)) { + const declaration = node; + result = appendTypeParameters(result, getEffectiveTypeParameterDeclarations(declaration)); + } + } + return result; + } + function getTypeParametersOfClassOrInterface(symbol) { + return concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + function isMixinConstructorType(type) { + const signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length === 1) { + const s = signatures[0]; + if (!s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s)) { + const paramType = getTypeOfParameter(s.parameters[0]); + return isTypeAny(paramType) || getElementTypeOfArrayType(paramType) === anyType; + } + } + return false; + } + function isConstructorType(type) { + if (getSignaturesOfType(type, 1 /* Construct */).length > 0) { + return true; + } + if (type.flags & 8650752 /* TypeVariable */) { + const constraint = getBaseConstraintOfType(type); + return !!constraint && isMixinConstructorType(constraint); + } + return false; + } + function getBaseTypeNodeOfClass(type) { + const decl = getClassLikeDeclarationOfSymbol(type.symbol); + return decl && getEffectiveBaseTypeNode(decl); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + const typeArgCount = length(typeArgumentNodes); + const isJavascript = isInJSFile(location); + return filter(getSignaturesOfType(type, 1 /* Construct */), (sig) => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); + return sameMap(signatures, (sig) => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig); + } + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + const decl = getClassLikeDeclarationOfSymbol(type.symbol); + const extended = decl && getEffectiveBaseTypeNode(decl); + const baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { + return errorType; + } + const baseConstructorType = checkExpression(baseTypeNode.expression); + if (extended && baseTypeNode !== extended) { + Debug.assert(!extended.typeArguments); + checkExpression(extended.expression); + } + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType); + } + if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + const err = error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & 262144 /* TypeParameter */) { + const constraint = getConstraintFromTypeParameter(baseConstructorType); + let ctorReturn = unknownType; + if (constraint) { + const ctorSig = getSignaturesOfType(constraint, 1 /* Construct */); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + if (baseConstructorType.symbol.declarations) { + addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } + } + return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType); + } + type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = baseConstructorType); + } + return type.resolvedBaseConstructorType; + } + function getImplementsTypes(type) { + let resolvedImplementsTypes = emptyArray; + if (type.symbol.declarations) { + for (const declaration of type.symbol.declarations) { + const implementsTypeNodes = getEffectiveImplementsTypeNodes(declaration); + if (!implementsTypeNodes) continue; + for (const node of implementsTypeNodes) { + const implementsType = getTypeFromTypeNode(node); + if (!isErrorType(implementsType)) { + if (resolvedImplementsTypes === emptyArray) { + resolvedImplementsTypes = [implementsType]; + } else { + resolvedImplementsTypes.push(implementsType); + } + } + } + } + } + return resolvedImplementsTypes; + } + function reportCircularBaseType(node, type) { + error(node, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString( + type, + /*enclosingDeclaration*/ + void 0, + 2 /* WriteArrayAsGenericType */ + )); + } + function getBaseTypes(type) { + if (!type.baseTypesResolved) { + if (pushTypeResolution(type, 6 /* ResolvedBaseTypes */)) { + if (type.objectFlags & 8 /* Tuple */) { + type.resolvedBaseTypes = [getTupleBaseType(type)]; + } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } else { + Debug.fail("type must be class or interface"); + } + if (!popTypeResolution() && type.symbol.declarations) { + for (const declaration of type.symbol.declarations) { + if (declaration.kind === 263 /* ClassDeclaration */ || declaration.kind === 264 /* InterfaceDeclaration */) { + reportCircularBaseType(declaration, type); + } + } + } + } + type.baseTypesResolved = true; + } + return type.resolvedBaseTypes; + } + function getTupleBaseType(type) { + const elementTypes = sameMap(type.typeParameters, (t, i) => type.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t); + return createArrayType(getUnionType(elementTypes || emptyArray), type.readonly); + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = resolvingEmptyArray; + const baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) { + return type.resolvedBaseTypes = emptyArray; + } + const baseTypeNode = getBaseTypeNodeOfClass(type); + let baseType; + const originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : void 0; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); + } else if (baseConstructorType.flags & 1 /* Any */) { + baseType = baseConstructorType; + } else { + const constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return type.resolvedBaseTypes = emptyArray; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (isErrorType(baseType)) { + return type.resolvedBaseTypes = emptyArray; + } + const reducedBaseType = getReducedType(baseType); + if (!isValidBaseType(reducedBaseType)) { + const elaboration = elaborateNeverIntersection( + /*errorInfo*/ + void 0, + baseType + ); + const diagnostic = chainDiagnosticMessages(elaboration, Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType)); + diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(baseTypeNode.expression), baseTypeNode.expression, diagnostic)); + return type.resolvedBaseTypes = emptyArray; + } + if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { + error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString( + type, + /*enclosingDeclaration*/ + void 0, + 2 /* WriteArrayAsGenericType */ + )); + return type.resolvedBaseTypes = emptyArray; + } + if (type.resolvedBaseTypes === resolvingEmptyArray) { + type.members = void 0; + } + return type.resolvedBaseTypes = [reducedBaseType]; + } + function areAllOuterTypeParametersApplied(type) { + const outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + const last2 = outerTypeParameters.length - 1; + const typeArguments = getTypeArguments(type); + return outerTypeParameters[last2].symbol !== typeArguments[last2].symbol; + } + return true; + } + function isValidBaseType(type) { + if (type.flags & 262144 /* TypeParameter */) { + const constraint = getBaseConstraintOfType(type); + if (constraint) { + return isValidBaseType(constraint); + } + } + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || type.flags & 2097152 /* Intersection */ && every(type.types, isValidBaseType)); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; + if (type.symbol.declarations) { + for (const declaration of type.symbol.declarations) { + if (declaration.kind === 264 /* InterfaceDeclaration */ && getInterfaceBaseTypeNodes(declaration)) { + for (const node of getInterfaceBaseTypeNodes(declaration)) { + const baseType = getReducedType(getTypeFromTypeNode(node)); + if (!isErrorType(baseType)) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === emptyArray) { + type.resolvedBaseTypes = [baseType]; + } else { + type.resolvedBaseTypes.push(baseType); + } + } else { + reportCircularBaseType(declaration, type); + } + } else { + error(node, Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + } + } + } + } + } + function isThislessInterface(symbol) { + if (!symbol.declarations) { + return true; + } + for (const declaration of symbol.declarations) { + if (declaration.kind === 264 /* InterfaceDeclaration */) { + if (declaration.flags & 256 /* ContainsThis */) { + return false; + } + const baseTypeNodes = getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (const node of baseTypeNodes) { + if (isEntityNameExpression(node.expression)) { + const baseSymbol = resolveEntityName( + node.expression, + 788968 /* Type */, + /*ignoreErrors*/ + true + ); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + let links = getSymbolLinks(symbol); + const originalLinks = links; + if (!links.declaredType) { + const kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; + const merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration)); + if (merged) { + symbol = merged; + links = merged.links; + } + const type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol); + const outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + const localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; + type.typeParameters = concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = /* @__PURE__ */ new Map(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.resolvedTypeArguments = type.typeParameters; + type.thisType = createTypeParameter(symbol); + type.thisType.isThisType = true; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var _a; + const links = getSymbolLinks(symbol); + if (!links.declaredType) { + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { + return errorType; + } + const declaration = Debug.checkDefined((_a = symbol.declarations) == null ? void 0 : _a.find(isTypeAlias), "Type alias symbol with no valid declaration found"); + const typeNode = isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; + let type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; + if (popTypeResolution()) { + const typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + links.typeParameters = typeParameters; + links.instantiations = /* @__PURE__ */ new Map(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + if (type === intrinsicMarkerType && symbol.escapedName === "BuiltinIteratorReturn") { + type = getBuiltinIteratorReturnType(); + } + } else { + type = errorType; + if (declaration.kind === 340 /* JSDocEnumTag */) { + error(declaration.typeExpression.type, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } else { + error(isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + } + links.declaredType ?? (links.declaredType = type); + } + return links.declaredType; + } + function getBaseTypeOfEnumLikeType(type) { + return type.flags & 1056 /* EnumLike */ && type.symbol.flags & 8 /* EnumMember */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + } + function getDeclaredTypeOfEnum(symbol) { + const links = getSymbolLinks(symbol); + if (!links.declaredType) { + const memberTypeList = []; + if (symbol.declarations) { + for (const declaration of symbol.declarations) { + if (declaration.kind === 266 /* EnumDeclaration */) { + for (const member of declaration.members) { + if (hasBindableName(member)) { + const memberSymbol = getSymbolOfDeclaration(member); + const value = getEnumMemberValue(member).value; + const memberType = getFreshTypeOfLiteralType( + value !== void 0 ? getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : createComputedEnumType(memberSymbol) + ); + getSymbolLinks(memberSymbol).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } + } + } + } + } + const enumType = memberTypeList.length ? getUnionType( + memberTypeList, + 1 /* Literal */, + symbol, + /*aliasTypeArguments*/ + void 0 + ) : createComputedEnumType(symbol); + if (enumType.flags & 1048576 /* Union */) { + enumType.flags |= 1024 /* EnumLiteral */; + enumType.symbol = symbol; + } + links.declaredType = enumType; + } + return links.declaredType; + } + function createComputedEnumType(symbol) { + const regularType = createTypeWithSymbol(32 /* Enum */, symbol); + const freshType = createTypeWithSymbol(32 /* Enum */, symbol); + regularType.regularType = regularType; + regularType.freshType = freshType; + freshType.regularType = regularType; + freshType.freshType = freshType; + return regularType; + } + function getDeclaredTypeOfEnumMember(symbol) { + const links = getSymbolLinks(symbol); + if (!links.declaredType) { + const enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + const links = getSymbolLinks(symbol); + return links.declaredType || (links.declaredType = createTypeParameter(symbol)); + } + function getDeclaredTypeOfAlias(symbol) { + const links = getSymbolLinks(symbol); + return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol))); + } + function getDeclaredTypeOfSymbol(symbol) { + return tryGetDeclaredTypeOfSymbol(symbol) || errorType; + } + function tryGetDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getDeclaredTypeOfAlias(symbol); + } + return void 0; + } + function isThislessType(node) { + switch (node.kind) { + case 133 /* AnyKeyword */: + case 159 /* UnknownKeyword */: + case 154 /* StringKeyword */: + case 150 /* NumberKeyword */: + case 163 /* BigIntKeyword */: + case 136 /* BooleanKeyword */: + case 155 /* SymbolKeyword */: + case 151 /* ObjectKeyword */: + case 116 /* VoidKeyword */: + case 157 /* UndefinedKeyword */: + case 146 /* NeverKeyword */: + case 201 /* LiteralType */: + return true; + case 188 /* ArrayType */: + return isThislessType(node.elementType); + case 183 /* TypeReference */: + return !node.typeArguments || node.typeArguments.every(isThislessType); + } + return false; + } + function isThislessTypeParameter(node) { + const constraint = getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); + } + function isThislessVariableLikeDeclaration(node) { + const typeNode = getEffectiveTypeAnnotationNode(node); + return typeNode ? isThislessType(typeNode) : !hasInitializer(node); + } + function isThislessFunctionLikeDeclaration(node) { + const returnType = getEffectiveReturnTypeNode(node); + const typeParameters = getEffectiveTypeParameterDeclarations(node); + return (node.kind === 176 /* Constructor */ || !!returnType && isThislessType(returnType)) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); + } + function isThisless(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + const declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + return isThislessVariableLikeDeclaration(declaration); + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return isThislessFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + const result = createSymbolTable(); + for (const symbol of symbols) { + result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (const base of baseSymbols) { + if (isStaticPrivateIdentifierProperty(base)) { + continue; + } + const derived = symbols.get(base.escapedName); + if (!derived || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration) && !isConstructorDeclaredProperty(derived) && !getContainingClassStaticBlock(derived.valueDeclaration)) { + symbols.set(base.escapedName, base); + symbols.set(base.escapedName, base); + } + } + } + function isStaticPrivateIdentifierProperty(s) { + return !!s.valueDeclaration && isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && isStatic(s.valueDeclaration); + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + const symbol = type.symbol; + const members = getMembersOfSymbol(symbol); + type.declaredProperties = getNamedMembers(members); + type.declaredCallSignatures = emptyArray; + type.declaredConstructSignatures = emptyArray; + type.declaredIndexInfos = emptyArray; + type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + type.declaredIndexInfos = getIndexInfosOfSymbol(symbol); + } + return type; + } + function isLateBindableName(node) { + return isLateBindableAST(node) && isTypeUsableAsPropertyName(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(node.argumentExpression)); + } + function isLateBindableIndexSignature(node) { + return isLateBindableAST(node) && isTypeUsableAsIndexSignature(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(node.argumentExpression)); + } + function isLateBindableAST(node) { + if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) { + return false; + } + const expr = isComputedPropertyName(node) ? node.expression : node.argumentExpression; + return isEntityNameExpression(expr); + } + function isTypeUsableAsIndexSignature(type) { + return isTypeAssignableTo(type, stringNumberSymbolType); + } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) === 64 /* at */; + } + function hasLateBindableName(node) { + const name = getNameOfDeclaration(node); + return !!name && isLateBindableName(name); + } + function hasLateBindableIndexSignature(node) { + const name = getNameOfDeclaration(node); + return !!name && isLateBindableIndexSignature(name); + } + function hasBindableName(node) { + return !hasDynamicName(node) || hasLateBindableName(node); + } + function isNonBindableDynamicName(node) { + return isDynamicName(node) && !isLateBindableName(node); + } + function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { + Debug.assert(!!(getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol."); + symbol.flags |= symbolFlags; + getSymbolLinks(member.symbol).lateSymbol = symbol; + if (!symbol.declarations) { + symbol.declarations = [member]; + } else if (!member.symbol.isReplaceableByMethod) { + symbol.declarations.push(member); + } + if (symbolFlags & 111551 /* Value */) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { + symbol.valueDeclaration = member; + } + } + } + function lateBindMember(parent, earlySymbols, lateSymbols, decl) { + Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); + const links = getNodeLinks(decl); + if (!links.resolvedSymbol) { + links.resolvedSymbol = decl.symbol; + const declName = isBinaryExpression(decl) ? decl.left : decl.name; + const type = isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName); + if (isTypeUsableAsPropertyName(type)) { + const memberName = getPropertyNameFromType(type); + const symbolFlags = decl.symbol.flags; + let lateSymbol = lateSymbols.get(memberName); + if (!lateSymbol) lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */)); + const earlySymbol = earlySymbols && earlySymbols.get(memberName); + if (!(parent.flags & 32 /* Class */) && lateSymbol.flags & getExcludedSymbolFlags(symbolFlags)) { + const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; + const name = !(type.flags & 8192 /* UniqueESSymbol */) && unescapeLeadingUnderscores(memberName) || declarationNameToString(declName); + forEach(declarations, (declaration) => error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name)); + error(declName || decl, Diagnostics.Duplicate_property_0, name); + lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */); + } + lateSymbol.links.nameType = type; + addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); + if (lateSymbol.parent) { + Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); + } else { + lateSymbol.parent = parent; + } + return links.resolvedSymbol = lateSymbol; + } + } + return links.resolvedSymbol; + } + function lateBindIndexSignature(parent, earlySymbols, lateSymbols, decl) { + let indexSymbol = lateSymbols.get("__index" /* Index */); + if (!indexSymbol) { + const early = earlySymbols == null ? void 0 : earlySymbols.get("__index" /* Index */); + if (!early) { + indexSymbol = createSymbol(0 /* None */, "__index" /* Index */, 4096 /* Late */); + } else { + indexSymbol = cloneSymbol(early); + indexSymbol.links.checkFlags |= 4096 /* Late */; + } + lateSymbols.set("__index" /* Index */, indexSymbol); + } + if (!indexSymbol.declarations) { + indexSymbol.declarations = [decl]; + } else if (!decl.symbol.isReplaceableByMethod) { + indexSymbol.declarations.push(decl); + } + } + function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { + const links = getSymbolLinks(symbol); + if (!links[resolutionKind]) { + const isStatic2 = resolutionKind === "resolvedExports" /* resolvedExports */; + const earlySymbols = !isStatic2 ? symbol.members : symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol).exports : symbol.exports; + links[resolutionKind] = earlySymbols || emptySymbols; + const lateSymbols = createSymbolTable(); + for (const decl of symbol.declarations || emptyArray) { + const members = getMembersOfDeclaration(decl); + if (members) { + for (const member of members) { + if (isStatic2 === hasStaticModifier(member)) { + if (hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } else if (hasLateBindableIndexSignature(member)) { + lateBindIndexSignature(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + } + const assignments = getFunctionExpressionParentSymbolOrSymbol(symbol).assignmentDeclarationMembers; + if (assignments) { + const decls = arrayFrom(assignments.values()); + for (const member of decls) { + const assignmentKind = getAssignmentDeclarationKind(member); + const isInstanceMember = assignmentKind === 3 /* PrototypeProperty */ || isBinaryExpression(member) && isPossiblyAliasedThisProperty(member, assignmentKind) || assignmentKind === 9 /* ObjectDefinePrototypeProperty */ || assignmentKind === 6 /* Prototype */; + if (isStatic2 === !isInstanceMember) { + if (hasLateBindableName(member)) { + lateBindMember(symbol, earlySymbols, lateSymbols, member); + } + } + } + } + let resolved = combineSymbolTables(earlySymbols, lateSymbols); + if (symbol.flags & 33554432 /* Transient */ && links.cjsExportMerged && symbol.declarations) { + for (const decl of symbol.declarations) { + const original = getSymbolLinks(decl.symbol)[resolutionKind]; + if (!resolved) { + resolved = original; + continue; + } + if (!original) continue; + original.forEach((s, name) => { + const existing = resolved.get(name); + if (!existing) resolved.set(name, s); + else if (existing === s) return; + else resolved.set(name, mergeSymbol(existing, s)); + }); + } + } + links[resolutionKind] = resolved || emptySymbols; + } + return links[resolutionKind]; + } + function getMembersOfSymbol(symbol) { + return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) : symbol.members || emptySymbols; + } + function getLateBoundSymbol(symbol) { + if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) { + const links = getSymbolLinks(symbol); + if (!links.lateSymbol && some(symbol.declarations, hasLateBindableName)) { + const parent = getMergedSymbol(symbol.parent); + if (some(symbol.declarations, hasStaticModifier)) { + getExportsOfSymbol(parent); + } else { + getMembersOfSymbol(parent); + } + } + return links.lateSymbol || (links.lateSymbol = symbol); + } + return symbol; + } + function getTypeWithThisArgument(type, thisArgument, needApparentType) { + if (getObjectFlags(type) & 4 /* Reference */) { + const target = type.target; + const typeArguments = getTypeArguments(type); + return length(target.typeParameters) === length(typeArguments) ? createTypeReference(target, concatenate(typeArguments, [thisArgument || target.thisType])) : type; + } else if (type.flags & 2097152 /* Intersection */) { + const types = sameMap(type.types, (t) => getTypeWithThisArgument(t, thisArgument, needApparentType)); + return types !== type.types ? getIntersectionType(types) : type; + } + return needApparentType ? getApparentType(type) : type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + let mapper; + let members; + let callSignatures; + let constructSignatures; + let indexInfos; + if (rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + members = source.symbol ? getMembersOfSymbol(source.symbol) : createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + indexInfos = source.declaredIndexInfos; + } else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable( + source.declaredProperties, + mapper, + /*mappingThisOnly*/ + typeParameters.length === 1 + ); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + indexInfos = instantiateIndexInfos(source.declaredIndexInfos, mapper); + } + const baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === getMembersOfSymbol(source.symbol)) { + const symbolTable = createSymbolTable(source.declaredProperties); + const sourceIndex = getIndexSymbol(source.symbol); + if (sourceIndex) { + symbolTable.set("__index" /* Index */, sourceIndex); + } + members = symbolTable; + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos); + const thisArgument = lastOrUndefined(typeArguments); + for (const baseType of baseTypes) { + const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + const inheritedIndexInfos = instantiatedBaseType !== anyType ? getIndexInfosOfType(instantiatedBaseType) : [anyBaseTypeIndexInfo]; + indexInfos = concatenate(indexInfos, filter(inheritedIndexInfos, (info) => !findIndexInfo(indexInfos, info.keyType))); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); + } + function resolveTypeReferenceMembers(type) { + const source = resolveDeclaredMembers(type.target); + const typeParameters = concatenate(source.typeParameters, [source.thisType]); + const typeArguments = getTypeArguments(type); + const paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : concatenate(typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + const sig = new Signature5(checker, flags); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.resolvedTypePredicate = resolvedTypePredicate; + sig.minArgumentCount = minArgumentCount; + sig.resolvedMinArgumentCount = void 0; + sig.target = void 0; + sig.mapper = void 0; + sig.compositeSignatures = void 0; + sig.compositeKind = void 0; + return sig; + } + function cloneSignature(sig) { + const result = createSignature( + sig.declaration, + sig.typeParameters, + sig.thisParameter, + sig.parameters, + /*resolvedReturnType*/ + void 0, + /*resolvedTypePredicate*/ + void 0, + sig.minArgumentCount, + sig.flags & 167 /* PropagatingFlags */ + ); + result.target = sig.target; + result.mapper = sig.mapper; + result.compositeSignatures = sig.compositeSignatures; + result.compositeKind = sig.compositeKind; + return result; + } + function createUnionSignature(signature, unionSignatures) { + const result = cloneSignature(signature); + result.compositeSignatures = unionSignatures; + result.compositeKind = 1048576 /* Union */; + result.target = void 0; + result.mapper = void 0; + return result; + } + function getOptionalCallSignature(signature, callChainFlags) { + if ((signature.flags & 24 /* CallChainFlags */) === callChainFlags) { + return signature; + } + if (!signature.optionalCallSignatureCache) { + signature.optionalCallSignatureCache = {}; + } + const key = callChainFlags === 8 /* IsInnerCallChain */ ? "inner" : "outer"; + return signature.optionalCallSignatureCache[key] || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags)); + } + function createOptionalCallSignature(signature, callChainFlags) { + Debug.assert(callChainFlags === 8 /* IsInnerCallChain */ || callChainFlags === 16 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); + const result = cloneSignature(signature); + result.flags |= callChainFlags; + return result; + } + function getExpandedParameters(sig, skipUnionExpanding) { + if (signatureHasRestParameter(sig)) { + const restIndex = sig.parameters.length - 1; + const restSymbol = sig.parameters[restIndex]; + const restType = getTypeOfSymbol(restSymbol); + if (isTupleType(restType)) { + return [expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol)]; + } else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && every(restType.types, isTupleType)) { + return map(restType.types, (t) => expandSignatureParametersWithTupleMembers(t, restIndex, restSymbol)); + } + } + return [sig.parameters]; + function expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol) { + const elementTypes = getTypeArguments(restType); + const associatedNames = getUniqAssociatedNamesFromTupleType(restType, restSymbol); + const restParams = map(elementTypes, (t, i) => { + const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType); + const flags = restType.target.elementFlags[i]; + const checkFlags = flags & 12 /* Variable */ ? 32768 /* RestParameter */ : flags & 2 /* Optional */ ? 16384 /* OptionalParameter */ : 0; + const symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); + symbol.links.type = flags & 4 /* Rest */ ? createArrayType(t) : t; + return symbol; + }); + return concatenate(sig.parameters.slice(0, restIndex), restParams); + } + function getUniqAssociatedNamesFromTupleType(type, restSymbol) { + const names = map(type.target.labeledElementDeclarations, (labeledElement, i) => getTupleElementLabel(labeledElement, i, type.target.elementFlags[i], restSymbol)); + if (names) { + const duplicates = []; + const uniqueNames = /* @__PURE__ */ new Set(); + for (let i = 0; i < names.length; i++) { + const name = names[i]; + if (!tryAddToSet(uniqueNames, name)) { + duplicates.push(i); + } + } + const counters = /* @__PURE__ */ new Map(); + for (const i of duplicates) { + let counter = counters.get(names[i]) ?? 1; + let name; + while (!tryAddToSet(uniqueNames, name = `${names[i]}_${counter}`)) { + counter++; + } + names[i] = name; + counters.set(names[i], counter + 1); + } + } + return names; + } + } + function getDefaultConstructSignatures(classType) { + const baseConstructorType = getBaseConstructorTypeOfClass(classType); + const baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + const declaration = getClassLikeDeclarationOfSymbol(classType.symbol); + const isAbstract = !!declaration && hasSyntacticModifier(declaration, 64 /* Abstract */); + if (baseSignatures.length === 0) { + return [createSignature( + /*declaration*/ + void 0, + classType.localTypeParameters, + /*thisParameter*/ + void 0, + emptyArray, + classType, + /*resolvedTypePredicate*/ + void 0, + 0, + isAbstract ? 4 /* Abstract */ : 0 /* None */ + )]; + } + const baseTypeNode = getBaseTypeNodeOfClass(classType); + const isJavaScript = isInJSFile(baseTypeNode); + const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + const typeArgCount = length(typeArguments); + const result = []; + for (const baseSig of baseSignatures) { + const minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + const typeParamCount = length(baseSig.typeParameters); + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { + const sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + sig.flags = isAbstract ? sig.flags | 4 /* Abstract */ : sig.flags & ~4 /* Abstract */; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (const s of signatureList) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + if (listIndex > 0) { + return void 0; + } + for (let i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature( + signatureLists[i], + signature, + /*partialMatch*/ + false, + /*ignoreThisTypes*/ + false, + /*ignoreReturnTypes*/ + false + )) { + return void 0; + } + } + return [signature]; + } + let result; + for (let i = 0; i < signatureLists.length; i++) { + const match = i === listIndex ? signature : findMatchingSignature( + signatureLists[i], + signature, + /*partialMatch*/ + false, + /*ignoreThisTypes*/ + false, + /*ignoreReturnTypes*/ + true + ) || findMatchingSignature( + signatureLists[i], + signature, + /*partialMatch*/ + true, + /*ignoreThisTypes*/ + false, + /*ignoreReturnTypes*/ + true + ); + if (!match) { + return void 0; + } + result = appendIfUnique(result, match); + } + return result; + } + function getUnionSignatures(signatureLists) { + let result; + let indexWithLengthOverOne; + for (let i = 0; i < signatureLists.length; i++) { + if (signatureLists[i].length === 0) return emptyArray; + if (signatureLists[i].length > 1) { + indexWithLengthOverOne = indexWithLengthOverOne === void 0 ? i : -1; + } + for (const signature of signatureLists[i]) { + if (!result || !findMatchingSignature( + result, + signature, + /*partialMatch*/ + false, + /*ignoreThisTypes*/ + false, + /*ignoreReturnTypes*/ + true + )) { + const unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + let s = signature; + if (unionSignatures.length > 1) { + let thisParameter = signature.thisParameter; + const firstThisParameterOfUnionSignatures = forEach(unionSignatures, (sig) => sig.thisParameter); + if (firstThisParameterOfUnionSignatures) { + const thisType = getIntersectionType(mapDefined(unionSignatures, (sig) => sig.thisParameter && getTypeOfSymbol(sig.thisParameter))); + thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType); + } + s = createUnionSignature(signature, unionSignatures); + s.thisParameter = thisParameter; + } + (result || (result = [])).push(s); + } + } + } + } + if (!length(result) && indexWithLengthOverOne !== -1) { + const masterList = signatureLists[indexWithLengthOverOne !== void 0 ? indexWithLengthOverOne : 0]; + let results = masterList.slice(); + for (const signatures of signatureLists) { + if (signatures !== masterList) { + const signature = signatures[0]; + Debug.assert(!!signature, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); + results = !!signature.typeParameters && some(results, (s) => !!s.typeParameters && !compareTypeParametersIdentical(signature.typeParameters, s.typeParameters)) ? void 0 : map(results, (sig) => combineSignaturesOfUnionMembers(sig, signature)); + if (!results) { + break; + } + } + } + result = results; + } + return result || emptyArray; + } + function compareTypeParametersIdentical(sourceParams, targetParams) { + if (length(sourceParams) !== length(targetParams)) { + return false; + } + if (!sourceParams || !targetParams) { + return true; + } + const mapper = createTypeMapper(targetParams, sourceParams); + for (let i = 0; i < sourceParams.length; i++) { + const source = sourceParams[i]; + const target = targetParams[i]; + if (source === target) continue; + if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper))) return false; + } + return true; + } + function combineUnionThisParam(left, right, mapper) { + if (!left || !right) { + return left || right; + } + const thisType = getIntersectionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]); + return createSymbolWithType(left, thisType); + } + function combineUnionParameters(left, right, mapper) { + const leftCount = getParameterCount(left); + const rightCount = getParameterCount(right); + const longest = leftCount >= rightCount ? left : right; + const shorter = longest === left ? right : left; + const longestCount = longest === left ? leftCount : rightCount; + const eitherHasEffectiveRest = hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right); + const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (let i = 0; i < longestCount; i++) { + let longestParamType = tryGetTypeAtPosition(longest, i); + if (longest === right) { + longestParamType = instantiateType(longestParamType, mapper); + } + let shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + if (shorter === right) { + shorterParamType = instantiateType(shorterParamType, mapper); + } + const unionParamType = getIntersectionType([longestParamType, shorterParamType]); + const isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === longestCount - 1; + const isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + const leftName = i >= leftCount ? void 0 : getParameterNameAtPosition(left, i); + const rightName = i >= rightCount ? void 0 : getParameterNameAtPosition(right, i); + const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0; + const paramSymbol = createSymbol( + 1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), + paramName || `arg${i}`, + isRestParam ? 32768 /* RestParameter */ : isOptional ? 16384 /* OptionalParameter */ : 0 + ); + paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + const restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args", 32768 /* RestParameter */); + restParamSymbol.links.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + if (shorter === right) { + restParamSymbol.links.type = instantiateType(restParamSymbol.links.type, mapper); + } + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfUnionMembers(left, right) { + const typeParams = left.typeParameters || right.typeParameters; + let paramMapper; + if (left.typeParameters && right.typeParameters) { + paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); + } + let flags = (left.flags | right.flags) & (167 /* PropagatingFlags */ & ~1 /* HasRestParameter */); + const declaration = left.declaration; + const params = combineUnionParameters(left, right, paramMapper); + const lastParam = lastOrUndefined(params); + if (lastParam && getCheckFlags(lastParam) & 32768 /* RestParameter */) { + flags |= 1 /* HasRestParameter */; + } + const thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper); + const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + const result = createSignature( + declaration, + typeParams, + thisParam, + params, + /*resolvedReturnType*/ + void 0, + /*resolvedTypePredicate*/ + void 0, + minArgCount, + flags + ); + result.compositeKind = 1048576 /* Union */; + result.compositeSignatures = concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); + if (paramMapper) { + result.mapper = left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + } else if (left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures) { + result.mapper = left.mapper; + } + return result; + } + function getUnionIndexInfos(types) { + const sourceInfos = getIndexInfosOfType(types[0]); + if (sourceInfos) { + const result = []; + for (const info of sourceInfos) { + const indexType = info.keyType; + if (every(types, (t) => !!getIndexInfoOfType(t, indexType))) { + result.push(createIndexInfo(indexType, getUnionType(map(types, (t) => getIndexTypeOfType(t, indexType))), some(types, (t) => getIndexInfoOfType(t, indexType).isReadonly))); + } + } + return result; + } + return emptyArray; + } + function resolveUnionTypeMembers(type) { + const callSignatures = getUnionSignatures(map(type.types, (t) => t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */))); + const constructSignatures = getUnionSignatures(map(type.types, (t) => getSignaturesOfType(t, 1 /* Construct */))); + const indexInfos = getUnionIndexInfos(type.types); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, indexInfos); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function findMixins(types) { + const constructorTypeCount = countWhere(types, (t) => getSignaturesOfType(t, 1 /* Construct */).length > 0); + const mixinFlags = map(types, isMixinConstructorType); + if (constructorTypeCount > 0 && constructorTypeCount === countWhere(mixinFlags, (b) => b)) { + const firstMixinIndex = mixinFlags.indexOf( + /*searchElement*/ + true + ); + mixinFlags[firstMixinIndex] = false; + } + return mixinFlags; + } + function includeMixinType(type, types, mixinFlags, index) { + const mixedTypes = []; + for (let i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } else if (mixinFlags[i]) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + let callSignatures; + let constructSignatures; + let indexInfos; + const types = type.types; + const mixinFlags = findMixins(types); + const mixinCount = countWhere(mixinFlags, (b) => b); + for (let i = 0; i < types.length; i++) { + const t = type.types[i]; + if (!mixinFlags[i]) { + let signatures = getSignaturesOfType(t, 1 /* Construct */); + if (signatures.length && mixinCount > 0) { + signatures = map(signatures, (s) => { + const clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i); + return clone; + }); + } + constructSignatures = appendSignatures(constructSignatures, signatures); + } + callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + indexInfos = reduceLeft(getIndexInfosOfType(t), (infos, newInfo) => appendIndexInfo( + infos, + newInfo, + /*union*/ + false + ), indexInfos); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures || emptyArray, constructSignatures || emptyArray, indexInfos || emptyArray); + } + function appendSignatures(signatures, newSignatures) { + for (const sig of newSignatures) { + if (!signatures || every(signatures, (s) => !compareSignaturesIdentical( + s, + sig, + /*partialMatch*/ + false, + /*ignoreThisTypes*/ + false, + /*ignoreReturnTypes*/ + false, + compareTypesIdentical + ))) { + signatures = append(signatures, sig); + } + } + return signatures; + } + function appendIndexInfo(indexInfos, newInfo, union) { + if (indexInfos) { + for (let i = 0; i < indexInfos.length; i++) { + const info = indexInfos[i]; + if (info.keyType === newInfo.keyType) { + indexInfos[i] = createIndexInfo(info.keyType, union ? getUnionType([info.type, newInfo.type]) : getIntersectionType([info.type, newInfo.type]), union ? info.isReadonly || newInfo.isReadonly : info.isReadonly && newInfo.isReadonly); + return indexInfos; + } + } + } + return append(indexInfos, newInfo); + } + function resolveAnonymousTypeMembers(type) { + if (type.target) { + setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray); + const members2 = createInstantiatedSymbolTable( + getPropertiesOfObjectType(type.target), + type.mapper, + /*mappingThisOnly*/ + false + ); + const callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + const constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); + const indexInfos2 = instantiateIndexInfos(getIndexInfosOfType(type.target), type.mapper); + setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2); + return; + } + const symbol = getMergedSymbol(type.symbol); + if (symbol.flags & 2048 /* TypeLiteral */) { + setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray); + const members2 = getMembersOfSymbol(symbol); + const callSignatures = getSignaturesOfSymbol(members2.get("__call" /* Call */)); + const constructSignatures = getSignaturesOfSymbol(members2.get("__new" /* New */)); + const indexInfos2 = getIndexInfosOfSymbol(symbol); + setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2); + return; + } + let members = getExportsOfSymbol(symbol); + let indexInfos; + if (symbol === globalThisSymbol) { + const varsOnly = /* @__PURE__ */ new Map(); + members.forEach((p) => { + var _a; + if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { + varsOnly.set(p.escapedName, p); + } + }); + members = varsOnly; + } + let baseConstructorIndexInfo; + setStructuredTypeMembers(type, members, emptyArray, emptyArray, emptyArray); + if (symbol.flags & 32 /* Class */) { + const classType = getDeclaredTypeOfClassOrInterface(symbol); + const baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { + members = createSymbolTable(getNamedOrIndexSignatureMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } else if (baseConstructorType === anyType) { + baseConstructorIndexInfo = anyBaseTypeIndexInfo; + } + } + const indexSymbol = getIndexSymbolFromSymbolTable(members); + if (indexSymbol) { + indexInfos = getIndexInfosOfIndexSymbol(indexSymbol, arrayFrom(members.values())); + } else { + if (baseConstructorIndexInfo) { + indexInfos = append(indexInfos, baseConstructorIndexInfo); + } + if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || some(type.properties, (prop) => !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */)))) { + indexInfos = append(indexInfos, enumNumberIndexInfo); + } + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos || emptyArray); + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } + if (symbol.flags & 32 /* Class */) { + const classType = getDeclaredTypeOfClassOrInterface(symbol); + let constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : emptyArray; + if (symbol.flags & 16 /* Function */) { + constructSignatures = addRange( + constructSignatures.slice(), + mapDefined( + type.callSignatures, + (sig) => isJSConstructor(sig.declaration) ? createSignature( + sig.declaration, + sig.typeParameters, + sig.thisParameter, + sig.parameters, + classType, + /*resolvedTypePredicate*/ + void 0, + sig.minArgumentCount, + sig.flags & 167 /* PropagatingFlags */ + ) : void 0 + ) + ); + } + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + type.constructSignatures = constructSignatures; + } + } + function replaceIndexedAccess(instantiable, type, replacement) { + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getNumberLiteralType(0), createTupleType([replacement])])); + } + function getLimitedConstraint(type) { + const constraint = getConstraintTypeFromMappedType(type.mappedType); + if (!(constraint.flags & 1048576 /* Union */ || constraint.flags & 2097152 /* Intersection */)) { + return; + } + const origin = constraint.flags & 1048576 /* Union */ ? constraint.origin : constraint; + if (!origin || !(origin.flags & 2097152 /* Intersection */)) { + return; + } + const limitedConstraint = getIntersectionType(origin.types.filter((t) => t !== type.constraintType)); + return limitedConstraint !== neverType ? limitedConstraint : void 0; + } + function resolveReverseMappedTypeMembers(type) { + const indexInfo = getIndexInfoOfType(type.source, stringType); + const modifiers = getMappedTypeModifiers(type.mappedType); + const readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true; + const optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */; + const indexInfos = indexInfo ? [createIndexInfo(stringType, inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType) || unknownType, readonlyMask && indexInfo.isReadonly)] : emptyArray; + const members = createSymbolTable(); + const limitedConstraint = getLimitedConstraint(type); + for (const prop of getPropertiesOfType(type.source)) { + if (limitedConstraint) { + const propertyNameType = getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */); + if (!isTypeAssignableTo(propertyNameType, limitedConstraint)) { + continue; + } + } + const checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + const inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.links.nameType = getSymbolLinks(prop).nameType; + inferredProp.links.propertyType = getTypeOfSymbol(prop); + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + const newTypeParam = type.constraintType.type.objectType; + const newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.links.mappedType = newMappedType; + inferredProp.links.constraintType = getIndexType(newTypeParam); + } else { + inferredProp.links.mappedType = type.mappedType; + inferredProp.links.constraintType = type.constraintType; + } + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos); + } + function getLowerBoundOfKeyType(type) { + if (type.flags & 4194304 /* Index */) { + const t = getApparentType(type.type); + return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t); + } + if (type.flags & 16777216 /* Conditional */) { + if (type.root.isDistributive) { + const checkType = type.checkType; + const constraint = getLowerBoundOfKeyType(checkType); + if (constraint !== checkType) { + return getConditionalTypeInstantiation( + type, + prependTypeMapping(type.root.checkType, constraint, type.mapper), + /*forConstraint*/ + false + ); + } + } + return type; + } + if (type.flags & 1048576 /* Union */) { + return mapType( + type, + getLowerBoundOfKeyType, + /*noReductions*/ + true + ); + } + if (type.flags & 2097152 /* Intersection */) { + const types = type.types; + if (types.length === 2 && !!(types[0].flags & (4 /* String */ | 8 /* Number */ | 64 /* BigInt */)) && types[1] === emptyTypeLiteralType) { + return type; + } + return getIntersectionType(sameMap(type.types, getLowerBoundOfKeyType)); + } + return type; + } + function getIsLateCheckFlag(s) { + return getCheckFlags(s) & 4096 /* Late */; + } + function forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(type, include, stringsOnly, cb) { + for (const prop of getPropertiesOfType(type)) { + cb(getLiteralTypeFromProperty(prop, include)); + } + if (type.flags & 1 /* Any */) { + cb(stringType); + } else { + for (const info of getIndexInfosOfType(type)) { + if (!stringsOnly || info.keyType.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) { + cb(info.keyType); + } + } + } + } + function resolveMappedTypeMembers(type) { + const members = createSymbolTable(); + let indexInfos; + setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray); + const typeParameter = getTypeParameterFromMappedType(type); + const constraintType = getConstraintTypeFromMappedType(type); + const mappedType = type.target || type; + const nameType = getNameTypeFromMappedType(mappedType); + const shouldLinkPropDeclarations = getMappedTypeNameTypeKind(mappedType) !== 2 /* Remapping */; + const templateType = getTemplateTypeFromMappedType(mappedType); + const modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + const templateModifiers = getMappedTypeModifiers(type); + const include = 8576 /* StringOrNumberLiteralOrUnique */; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType( + modifiersType, + include, + /*stringsOnly*/ + false, + addMemberForKeyType + ); + } else { + forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); + } + setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos || emptyArray); + function addMemberForKeyType(keyType) { + const propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType; + forEachType(propNameType, (t) => addMemberForKeyTypeWorker(keyType, t)); + } + function addMemberForKeyTypeWorker(keyType, propNameType) { + if (isTypeUsableAsPropertyName(propNameType)) { + const propName = getPropertyNameFromType(propNameType); + const existingProp = members.get(propName); + if (existingProp) { + existingProp.links.nameType = getUnionType([existingProp.links.nameType, propNameType]); + existingProp.links.keyType = getUnionType([existingProp.links.keyType, keyType]); + } else { + const modifiersProp = isTypeUsableAsPropertyName(keyType) ? getPropertyOfType(modifiersType, getPropertyNameFromType(keyType)) : void 0; + const isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); + const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); + const stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */; + const lateFlag = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0; + const prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, lateFlag | 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0)); + prop.links.mappedType = type; + prop.links.nameType = propNameType; + prop.links.keyType = keyType; + if (modifiersProp) { + prop.links.syntheticOrigin = modifiersProp; + prop.declarations = shouldLinkPropDeclarations ? modifiersProp.declarations : void 0; + } + members.set(propName, prop); + } + } else if (isValidIndexKeyType(propNameType) || propNameType.flags & (1 /* Any */ | 32 /* Enum */)) { + const indexKeyType = propNameType.flags & (1 /* Any */ | 4 /* String */) ? stringType : propNameType.flags & (8 /* Number */ | 32 /* Enum */) ? numberType : propNameType; + const propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType)); + const modifiersIndexInfo = getApplicableIndexInfo(modifiersType, propNameType); + const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && (modifiersIndexInfo == null ? void 0 : modifiersIndexInfo.isReadonly)); + const indexInfo = createIndexInfo(indexKeyType, propType, isReadonly); + indexInfos = appendIndexInfo( + indexInfos, + indexInfo, + /*union*/ + true + ); + } + } + } + function getTypeOfMappedSymbol(symbol) { + var _a; + if (!symbol.links.type) { + const mappedType = symbol.links.mappedType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + mappedType.containsError = true; + return errorType; + } + const templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType); + const mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.links.keyType); + const propType = instantiateType(templateType, mapper); + let type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType( + propType, + /*isProperty*/ + true + ) : symbol.links.checkFlags & 524288 /* StripOptional */ ? removeMissingOrUndefinedType(propType) : propType; + if (!popTypeResolution()) { + error(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType)); + type = errorType; + } + (_a = symbol.links).type ?? (_a.type = type); + } + return symbol.links.type; + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); + } + function getNameTypeFromMappedType(type) { + return type.declaration.nameType ? type.nameType || (type.nameType = instantiateType(getTypeFromTypeNode(type.declaration.nameType), type.mapper)) : void 0; + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || (type.templateType = type.declaration.type ? instantiateType(addOptionality( + getTypeFromTypeNode(type.declaration.type), + /*isProperty*/ + true, + !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */) + ), type.mapper) : errorType); + } + function getConstraintDeclarationForMappedType(type) { + return getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + const constraintDeclaration = getConstraintDeclarationForMappedType(type); + return constraintDeclaration.kind === 198 /* TypeOperator */ && constraintDeclaration.operator === 143 /* KeyOfKeyword */; + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper); + } else { + const declaredType = getTypeFromMappedTypeNode(type.declaration); + const constraint = getConstraintTypeFromMappedType(declaredType); + const extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType; + } + } + return type.modifiersType; + } + function getMappedTypeModifiers(type) { + const declaration = type.declaration; + return (declaration.readonlyToken ? declaration.readonlyToken.kind === 41 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | (declaration.questionToken ? declaration.questionToken.kind === 41 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0); + } + function getMappedTypeOptionality(type) { + const modifiers = getMappedTypeModifiers(type); + return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0; + } + function getCombinedMappedTypeOptionality(type) { + if (getObjectFlags(type) & 32 /* Mapped */) { + return getMappedTypeOptionality(type) || getCombinedMappedTypeOptionality(getModifiersTypeFromMappedType(type)); + } + if (type.flags & 2097152 /* Intersection */) { + const optionality = getCombinedMappedTypeOptionality(type.types[0]); + return every(type.types, (t, i) => i === 0 || getCombinedMappedTypeOptionality(t) === optionality) ? optionality : 0; + } + return 0; + } + function isPartialMappedType(type) { + return !!(getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); + } + function isGenericMappedType(type) { + if (getObjectFlags(type) & 32 /* Mapped */) { + const constraint = getConstraintTypeFromMappedType(type); + if (isGenericIndexType(constraint)) { + return true; + } + const nameType = getNameTypeFromMappedType(type); + if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) { + return true; + } + } + return false; + } + function getMappedTypeNameTypeKind(type) { + const nameType = getNameTypeFromMappedType(type); + if (!nameType) { + return 0 /* None */; + } + return isTypeAssignableTo(nameType, getTypeParameterFromMappedType(type)) ? 1 /* Filtering */ : 2 /* Remapping */; + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 524288 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } else if (type.objectFlags & 1024 /* ReverseMapped */) { + resolveReverseMappedTypeMembers(type); + } else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } else { + Debug.fail("Unhandled object type " + Debug.formatObjectFlags(type.objectFlags)); + } + } else if (type.flags & 1048576 /* Union */) { + resolveUnionTypeMembers(type); + } else if (type.flags & 2097152 /* Intersection */) { + resolveIntersectionTypeMembers(type); + } else { + Debug.fail("Unhandled type " + Debug.formatTypeFlags(type.flags)); + } + } + return type; + } + function getPropertiesOfObjectType(type) { + if (type.flags & 524288 /* Object */) { + return resolveStructuredTypeMembers(type).properties; + } + return emptyArray; + } + function getPropertyOfObjectType(type, name) { + if (type.flags & 524288 /* Object */) { + const resolved = resolveStructuredTypeMembers(type); + const symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + const members = createSymbolTable(); + for (const current of type.types) { + for (const prop of getPropertiesOfType(current)) { + if (!members.has(prop.escapedName)) { + const combinedProp = getPropertyOfUnionOrIntersectionType( + type, + prop.escapedName, + /*skipObjectFunctionPropertyAugment*/ + !!(type.flags & 2097152 /* Intersection */) + ); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + if (type.flags & 1048576 /* Union */ && getIndexInfosOfType(current).length === 0) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getReducedApparentType(type); + return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + } + function forEachPropertyOfType(type, action) { + type = getReducedApparentType(type); + if (type.flags & 3670016 /* StructuredType */) { + resolveStructuredTypeMembers(type).members.forEach((symbol, escapedName) => { + if (isNamedMember(symbol, escapedName)) { + action(symbol, escapedName); + } + }); + } + } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + const list = obj.properties; + return list.some((property) => { + const nameType = property.name && (isJsxNamespacedName(property.name) ? getStringLiteralType(getTextOfJsxAttributeName(property.name)) : getLiteralTypeFromPropertyName(property.name)); + const name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : void 0; + const expected = name === void 0 ? void 0 : getTypeOfPropertyOfType(contextualType, name); + return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected); + }); + } + function getAllPossiblePropertiesOfTypes(types) { + const unionType = getUnionType(types); + if (!(unionType.flags & 1048576 /* Union */)) { + return getAugmentedPropertiesOfType(unionType); + } + const props = createSymbolTable(); + for (const memberType of types) { + for (const { escapedName } of getAugmentedPropertiesOfType(memberType)) { + if (!props.has(escapedName)) { + const prop = createUnionOrIntersectionProperty(unionType, escapedName); + if (prop) props.set(escapedName, prop); + } + } + } + return arrayFrom(props.values()); + } + function getConstraintOfType(type) { + return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : void 0; + } + function isConstMappedType(type, depth) { + const typeVariable = getHomomorphicTypeVariable(type); + return !!typeVariable && isConstTypeVariable(typeVariable, depth); + } + function isConstTypeVariable(type, depth = 0) { + var _a; + return depth < 5 && !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 4096 /* Const */)) || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, (t) => isConstTypeVariable(t, depth)) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType, depth + 1) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type), depth + 1) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType, depth) || getObjectFlags(type) & 32 /* Mapped */ && isConstMappedType(type, depth) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t, depth)) >= 0)); + } + function getConstraintOfIndexedAccess(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0; + } + function getSimplifiedTypeOrConstraint(type) { + const simplified = getSimplifiedType( + type, + /*writing*/ + false + ); + return simplified !== type ? simplified : getConstraintOfType(type); + } + function getConstraintFromIndexedAccess(type) { + if (isMappedTypeGenericIndexedAccess(type)) { + return substituteIndexedMappedType(type.objectType, type.indexType); + } + const indexConstraint = getSimplifiedTypeOrConstraint(type.indexType); + if (indexConstraint && indexConstraint !== type.indexType) { + const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.accessFlags); + if (indexedAccess) { + return indexedAccess; + } + } + const objectConstraint = getSimplifiedTypeOrConstraint(type.objectType); + if (objectConstraint && objectConstraint !== type.objectType) { + return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.accessFlags); + } + return void 0; + } + function getDefaultConstraintOfConditionalType(type) { + if (!type.resolvedDefaultConstraint) { + const trueConstraint = getInferredTrueTypeFromConditionalType(type); + const falseConstraint = getFalseTypeFromConditionalType(type); + type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); + } + return type.resolvedDefaultConstraint; + } + function getConstraintOfDistributiveConditionalType(type) { + if (type.resolvedConstraintOfDistributive !== void 0) { + return type.resolvedConstraintOfDistributive || void 0; + } + if (type.root.isDistributive && type.restrictiveInstantiation !== type) { + const simplified = getSimplifiedType( + type.checkType, + /*writing*/ + false + ); + const constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; + if (constraint && constraint !== type.checkType) { + const instantiated = getConditionalTypeInstantiation( + type, + prependTypeMapping(type.root.checkType, constraint, type.mapper), + /*forConstraint*/ + true + ); + if (!(instantiated.flags & 131072 /* Never */)) { + type.resolvedConstraintOfDistributive = instantiated; + return instantiated; + } + } + } + type.resolvedConstraintOfDistributive = false; + return void 0; + } + function getConstraintFromConditionalType(type) { + return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); + } + function getConstraintOfConditionalType(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : void 0; + } + function getEffectiveConstraintOfIntersection(types, targetIsUnion) { + let constraints; + let hasDisjointDomainType = false; + for (const t of types) { + if (t.flags & 465829888 /* Instantiable */) { + let constraint = getConstraintOfType(t); + while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) { + constraint = getConstraintOfType(constraint); + } + if (constraint) { + constraints = append(constraints, constraint); + if (targetIsUnion) { + constraints = append(constraints, t); + } + } + } else if (t.flags & 469892092 /* DisjointDomains */ || isEmptyAnonymousObjectType(t)) { + hasDisjointDomainType = true; + } + } + if (constraints && (targetIsUnion || hasDisjointDomainType)) { + if (hasDisjointDomainType) { + for (const t of types) { + if (t.flags & 469892092 /* DisjointDomains */ || isEmptyAnonymousObjectType(t)) { + constraints = append(constraints, t); + } + } + } + return getNormalizedType( + getIntersectionType(constraints, 2 /* NoConstraintReduction */), + /*writing*/ + false + ); + } + return void 0; + } + function getBaseConstraintOfType(type) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || isGenericTupleType(type)) { + const constraint = getResolvedBaseConstraint(type); + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : void 0; + } + return type.flags & 4194304 /* Index */ ? stringNumberSymbolType : void 0; + } + function getBaseConstraintOrType(type) { + return getBaseConstraintOfType(type) || type; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + function getResolvedBaseConstraint(type) { + if (type.resolvedBaseConstraint) { + return type.resolvedBaseConstraint; + } + const stack = []; + return type.resolvedBaseConstraint = getImmediateBaseConstraint(type); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + let result; + const identity2 = getRecursionIdentity(t); + if (stack.length < 10 || stack.length < 50 && !contains(stack, identity2)) { + stack.push(identity2); + result = computeBaseConstraint(getSimplifiedType( + t, + /*writing*/ + false + )); + stack.pop(); + } + if (!popTypeResolution()) { + if (t.flags & 262144 /* TypeParameter */) { + const errorNode = getConstraintDeclaration(t); + if (errorNode) { + const diagnostic = error(errorNode, Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t)); + if (currentNode && !isNodeDescendantOf(errorNode, currentNode) && !isNodeDescendantOf(currentNode, errorNode)) { + addRelatedInfo(diagnostic, createDiagnosticForNode(currentNode, Diagnostics.Circularity_originates_in_type_at_this_location)); + } + } + } + result = circularConstraintType; + } + t.immediateBaseConstraint ?? (t.immediateBaseConstraint = result || noConstraintType); + } + return t.immediateBaseConstraint; + } + function getBaseConstraint(t) { + const c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : void 0; + } + function computeBaseConstraint(t) { + if (t.flags & 262144 /* TypeParameter */) { + const constraint = getConstraintFromTypeParameter(t); + return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint); + } + if (t.flags & 3145728 /* UnionOrIntersection */) { + const types = t.types; + const baseTypes = []; + let different = false; + for (const type2 of types) { + const baseType = getBaseConstraint(type2); + if (baseType) { + if (baseType !== type2) { + different = true; + } + baseTypes.push(baseType); + } else { + different = true; + } + } + if (!different) { + return t; + } + return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : void 0; + } + if (t.flags & 4194304 /* Index */) { + return stringNumberSymbolType; + } + if (t.flags & 134217728 /* TemplateLiteral */) { + const types = t.types; + const constraints = mapDefined(types, getBaseConstraint); + return constraints.length === types.length ? getTemplateLiteralType(t.texts, constraints) : stringType; + } + if (t.flags & 268435456 /* StringMapping */) { + const constraint = getBaseConstraint(t.type); + return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType; + } + if (t.flags & 8388608 /* IndexedAccess */) { + if (isMappedTypeGenericIndexedAccess(t)) { + return getBaseConstraint(substituteIndexedMappedType(t.objectType, t.indexType)); + } + const baseObjectType = getBaseConstraint(t.objectType); + const baseIndexType = getBaseConstraint(t.indexType); + const baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.accessFlags); + return baseIndexedAccess && getBaseConstraint(baseIndexedAccess); + } + if (t.flags & 16777216 /* Conditional */) { + const constraint = getConstraintFromConditionalType(t); + return constraint && getBaseConstraint(constraint); + } + if (t.flags & 33554432 /* Substitution */) { + return getBaseConstraint(getSubstitutionIntersection(t)); + } + if (isGenericTupleType(t)) { + const newElements = map(getElementTypes(t), (v, i) => { + const constraint = v.flags & 262144 /* TypeParameter */ && t.target.elementFlags[i] & 8 /* Variadic */ && getBaseConstraint(v) || v; + return constraint !== v && everyType(constraint, (c) => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v; + }); + return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations); + } + return t; + } + } + function getApparentTypeOfIntersectionType(type, thisArgument) { + if (type === thisArgument) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument( + type, + thisArgument, + /*needApparentType*/ + true + )); + } + const key = `I${getTypeId(type)},${getTypeId(thisArgument)}`; + return getCachedType(key) ?? setCachedType(key, getTypeWithThisArgument( + type, + thisArgument, + /*needApparentType*/ + true + )); + } + function getResolvedTypeParameterDefault(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + const targetDefault = getResolvedTypeParameterDefault(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } else { + typeParameter.default = resolvingDefaultType; + const defaultDeclaration = typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default); + const defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = defaultType; + } + } + } else if (typeParameter.default === resolvingDefaultType) { + typeParameter.default = circularConstraintType; + } + return typeParameter.default; + } + function getDefaultFromTypeParameter(typeParameter) { + const defaultType = getResolvedTypeParameterDefault(typeParameter); + return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : void 0; + } + function hasNonCircularTypeParameterDefault(typeParameter) { + return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; + } + function hasTypeParameterDefault(typeParameter) { + return !!(typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default)); + } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + const target = type.target ?? type; + const typeVariable = getHomomorphicTypeVariable(target); + if (typeVariable && !target.declaration.nameType) { + const modifiersType = getModifiersTypeFromMappedType(type); + const baseConstraint = isGenericMappedType(modifiersType) ? getApparentTypeOfMappedType(modifiersType) : getBaseConstraintOfType(modifiersType); + if (baseConstraint && everyType(baseConstraint, (t) => isArrayOrTupleType(t) || isArrayOrTupleOrIntersection(t))) { + return instantiateType(target, prependTypeMapping(typeVariable, baseConstraint, type.mapper)); + } + } + return type; + } + function isArrayOrTupleOrIntersection(type) { + return !!(type.flags & 2097152 /* Intersection */) && every(type.types, isArrayOrTupleType); + } + function isMappedTypeGenericIndexedAccess(type) { + let objectType; + return !!(type.flags & 8388608 /* IndexedAccess */ && getObjectFlags(objectType = type.objectType) & 32 /* Mapped */ && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && !(getMappedTypeModifiers(objectType) & 8 /* ExcludeOptional */) && !objectType.declaration.nameType); + } + function getApparentType(type) { + const t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; + const objectFlags = getObjectFlags(t); + return objectFlags & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : objectFlags & 4 /* Reference */ && t !== type ? getTypeWithThisArgument(t, type) : t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t, type) : t.flags & 402653316 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType() : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType() : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : t.flags & 4194304 /* Index */ ? stringNumberSymbolType : t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType : t; + } + function getReducedApparentType(type) { + return getReducedType(getApparentType(getReducedType(type))); + } + function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b, _c; + let singleProp; + let propSet; + let indexTypes; + const isUnion = containingType.flags & 1048576 /* Union */; + let optionalFlag; + let syntheticFlag = 4 /* SyntheticMethod */; + let checkFlags = isUnion ? 0 : 8 /* Readonly */; + let mergedInstantiations = false; + for (const current of containingType.types) { + const type = getApparentType(current); + if (!(isErrorType(type) || type.flags & 131072 /* Never */)) { + const prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); + const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop) { + if (prop.flags & 106500 /* ClassMember */) { + optionalFlag ?? (optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */); + if (isUnion) { + optionalFlag |= prop.flags & 16777216 /* Optional */; + } else { + optionalFlag &= prop.flags; + } + } + if (!singleProp) { + singleProp = prop; + } else if (prop !== singleProp) { + const isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + if (isInstantiation && compareProperties(singleProp, prop, (a, b) => a === b ? -1 /* True */ : 0 /* False */) === -1 /* True */) { + mergedInstantiations = !!singleProp.parent && !!length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); + } else { + if (!propSet) { + propSet = /* @__PURE__ */ new Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + const id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } + } + } + if (isUnion && isReadonlySymbol(prop)) { + checkFlags |= 8 /* Readonly */; + } else if (!isUnion && !isReadonlySymbol(prop)) { + checkFlags &= ~8 /* Readonly */; + } + checkFlags |= (!(modifiers & 6 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | (modifiers & 4 /* Protected */ ? 512 /* ContainsProtected */ : 0) | (modifiers & 2 /* Private */ ? 1024 /* ContainsPrivate */ : 0) | (modifiers & 256 /* Static */ ? 2048 /* ContainsStatic */ : 0); + if (!isPrototypeProperty(prop)) { + syntheticFlag = 2 /* SyntheticProperty */; + } + } else if (isUnion) { + const indexInfo = !isLateBoundName(name) && getApplicableIndexInfoForName(type, name); + if (indexInfo) { + checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); + indexTypes = append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); + } else if (isObjectLiteralType(type) && !(getObjectFlags(type) & 2097152 /* ContainsSpread */)) { + checkFlags |= 32 /* WritePartial */; + indexTypes = append(indexTypes, undefinedType); + } else { + checkFlags |= 16 /* ReadPartial */; + } + } + } + } + if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */) && !(propSet && getCommonDeclarationsOfSymbols(propSet.values()))) { + return void 0; + } + if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { + if (mergedInstantiations) { + const links = (_a = tryCast(singleProp, isTransientSymbol)) == null ? void 0 : _a.links; + const clone = createSymbolWithType(singleProp, links == null ? void 0 : links.type); + clone.parent = (_c = (_b = singleProp.valueDeclaration) == null ? void 0 : _b.symbol) == null ? void 0 : _c.parent; + clone.links.containingType = containingType; + clone.links.mapper = links == null ? void 0 : links.mapper; + clone.links.writeType = getWriteTypeOfSymbol(singleProp); + return clone; + } else { + return singleProp; + } + } + const props = propSet ? arrayFrom(propSet.values()) : [singleProp]; + let declarations; + let firstType; + let nameType; + const propTypes = []; + let writeTypes; + let firstValueDeclaration; + let hasNonUniformValueDeclaration = false; + for (const prop of props) { + if (!firstValueDeclaration) { + firstValueDeclaration = prop.valueDeclaration; + } else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) { + hasNonUniformValueDeclaration = true; + } + declarations = addRange(declarations, prop.declarations); + const type = getTypeOfSymbol(prop); + if (!firstType) { + firstType = type; + nameType = getSymbolLinks(prop).nameType; + } + const writeType = getWriteTypeOfSymbol(prop); + if (writeTypes || writeType !== type) { + writeTypes = append(!writeTypes ? propTypes.slice() : writeTypes, writeType); + } + if (type !== firstType) { + checkFlags |= 64 /* HasNonUniformType */; + } + if (isLiteralType(type) || isPatternLiteralType(type)) { + checkFlags |= 128 /* HasLiteralType */; + } + if (type.flags & 131072 /* Never */ && type !== uniqueLiteralType) { + checkFlags |= 131072 /* HasNeverType */; + } + propTypes.push(type); + } + addRange(propTypes, indexTypes); + const result = createSymbol(4 /* Property */ | (optionalFlag ?? 0), name, syntheticFlag | checkFlags); + result.links.containingType = containingType; + if (!hasNonUniformValueDeclaration && firstValueDeclaration) { + result.valueDeclaration = firstValueDeclaration; + if (firstValueDeclaration.symbol.parent) { + result.parent = firstValueDeclaration.symbol.parent; + } + } + result.declarations = declarations; + result.links.nameType = nameType; + if (propTypes.length > 2) { + result.links.checkFlags |= 65536 /* DeferredType */; + result.links.deferralParent = containingType; + result.links.deferralConstituents = propTypes; + result.links.deferralWriteConstituents = writeTypes; + } else { + result.links.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + if (writeTypes) { + result.links.writeType = isUnion ? getUnionType(writeTypes) : getIntersectionType(writeTypes); + } + } + return result; + } + function getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment) { + var _a, _b, _c; + let property = skipObjectFunctionPropertyAugment ? (_a = type.propertyCacheWithoutObjectFunctionPropertyAugment) == null ? void 0 : _a.get(name) : (_b = type.propertyCache) == null ? void 0 : _b.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment); + if (property) { + const properties = skipObjectFunctionPropertyAugment ? type.propertyCacheWithoutObjectFunctionPropertyAugment || (type.propertyCacheWithoutObjectFunctionPropertyAugment = createSymbolTable()) : type.propertyCache || (type.propertyCache = createSymbolTable()); + properties.set(name, property); + if (skipObjectFunctionPropertyAugment && !(getCheckFlags(property) & 48 /* Partial */) && !((_c = type.propertyCache) == null ? void 0 : _c.get(name))) { + const properties2 = type.propertyCache || (type.propertyCache = createSymbolTable()); + properties2.set(name, property); + } + } + } + return property; + } + function getCommonDeclarationsOfSymbols(symbols) { + let commonDeclarations; + for (const symbol of symbols) { + if (!symbol.declarations) { + return void 0; + } + if (!commonDeclarations) { + commonDeclarations = new Set(symbol.declarations); + continue; + } + commonDeclarations.forEach((declaration) => { + if (!contains(symbol.declarations, declaration)) { + commonDeclarations.delete(declaration); + } + }); + if (commonDeclarations.size === 0) { + return void 0; + } + } + return commonDeclarations; + } + function getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment) { + const property = getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment); + return property && !(getCheckFlags(property) & 16 /* ReadPartial */) ? property : void 0; + } + function getReducedType(type) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 16777216 /* ContainsIntersections */) { + return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); + } else if (type.flags & 2097152 /* Intersection */) { + if (!(type.objectFlags & 16777216 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 16777216 /* IsNeverIntersectionComputed */ | (some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 33554432 /* IsNeverIntersection */ : 0); + } + return type.objectFlags & 33554432 /* IsNeverIntersection */ ? neverType : type; + } + return type; + } + function getReducedUnionType(unionType) { + const reducedTypes = sameMap(unionType.types, getReducedType); + if (reducedTypes === unionType.types) { + return unionType; + } + const reduced = getUnionType(reducedTypes); + if (reduced.flags & 1048576 /* Union */) { + reduced.resolvedReducedType = reduced; + } + return reduced; + } + function isNeverReducedProperty(prop) { + return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop); + } + function isDiscriminantWithNeverType(prop) { + return !(prop.flags & 16777216 /* Optional */) && (getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); + } + function isConflictingPrivateProperty(prop) { + return !prop.valueDeclaration && !!(getCheckFlags(prop) & 1024 /* ContainsPrivate */); + } + function isGenericReducibleType(type) { + return !!(type.flags & 1048576 /* Union */ && type.objectFlags & 16777216 /* ContainsIntersections */ && some(type.types, isGenericReducibleType) || type.flags & 2097152 /* Intersection */ && isReducibleIntersection(type)); + } + function isReducibleIntersection(type) { + const uniqueFilled = type.uniqueLiteralFilledInstantiation || (type.uniqueLiteralFilledInstantiation = instantiateType(type, uniqueLiteralMapper)); + return getReducedType(uniqueFilled) !== uniqueFilled; + } + function elaborateNeverIntersection(errorInfo, type) { + if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 33554432 /* IsNeverIntersection */) { + const neverProp = find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); + if (neverProp) { + return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString( + type, + /*enclosingDeclaration*/ + void 0, + 536870912 /* NoTypeReduction */ + ), symbolToString(neverProp)); + } + const privateProp = find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); + if (privateProp) { + return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString( + type, + /*enclosingDeclaration*/ + void 0, + 536870912 /* NoTypeReduction */ + ), symbolToString(privateProp)); + } + } + return errorInfo; + } + function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) { + var _a, _b; + type = getReducedApparentType(type); + if (type.flags & 524288 /* Object */) { + const resolved = resolveStructuredTypeMembers(type); + const symbol = resolved.members.get(name); + if (symbol && !includeTypeOnlyMembers && ((_a = type.symbol) == null ? void 0 : _a.flags) & 512 /* ValueModule */ && ((_b = getSymbolLinks(type.symbol).typeOnlyExportStarMap) == null ? void 0 : _b.has(name))) { + return void 0; + } + if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { + return symbol; + } + if (skipObjectFunctionPropertyAugment) return void 0; + const functionType = resolved === anyFunctionType ? globalFunctionType : resolved.callSignatures.length ? globalCallableFunctionType : resolved.constructSignatures.length ? globalNewableFunctionType : void 0; + if (functionType) { + const symbol2 = getPropertyOfObjectType(functionType, name); + if (symbol2) { + return symbol2; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 2097152 /* Intersection */) { + const prop = getPropertyOfUnionOrIntersectionType( + type, + name, + /*skipObjectFunctionPropertyAugment*/ + true + ); + if (prop) { + return prop; + } + if (!skipObjectFunctionPropertyAugment) { + return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment); + } + return void 0; + } + if (type.flags & 1048576 /* Union */) { + return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment); + } + return void 0; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 3670016 /* StructuredType */) { + const resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return emptyArray; + } + function getSignaturesOfType(type, kind) { + const result = getSignaturesOfStructuredType(getReducedApparentType(type), kind); + if (kind === 0 /* Call */ && !length(result) && type.flags & 1048576 /* Union */) { + if (type.arrayFallbackSignatures) { + return type.arrayFallbackSignatures; + } + let memberName; + if (everyType(type, (t) => { + var _a; + return !!((_a = t.symbol) == null ? void 0 : _a.parent) && isArrayOrTupleSymbol(t.symbol.parent) && (!memberName ? (memberName = t.symbol.escapedName, true) : memberName === t.symbol.escapedName); + })) { + const arrayArg = mapType(type, (t) => getMappedType((isReadonlyArraySymbol(t.symbol.parent) ? globalReadonlyArrayType : globalArrayType).typeParameters[0], t.mapper)); + const arrayType = createArrayType(arrayArg, someType(type, (t) => isReadonlyArraySymbol(t.symbol.parent))); + return type.arrayFallbackSignatures = getSignaturesOfType(getTypeOfPropertyOfType(arrayType, memberName), kind); + } + type.arrayFallbackSignatures = result; + } + return result; + } + function isArrayOrTupleSymbol(symbol) { + if (!symbol || !globalArrayType.symbol || !globalReadonlyArrayType.symbol) { + return false; + } + return !!getSymbolIfSameReference(symbol, globalArrayType.symbol) || !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol); + } + function isReadonlyArraySymbol(symbol) { + if (!symbol || !globalReadonlyArrayType.symbol) { + return false; + } + return !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol); + } + function findIndexInfo(indexInfos, keyType) { + return find(indexInfos, (info) => info.keyType === keyType); + } + function findApplicableIndexInfo(indexInfos, keyType) { + let stringIndexInfo; + let applicableInfo; + let applicableInfos; + for (const info of indexInfos) { + if (info.keyType === stringType) { + stringIndexInfo = info; + } else if (isApplicableIndexType(keyType, info.keyType)) { + if (!applicableInfo) { + applicableInfo = info; + } else { + (applicableInfos || (applicableInfos = [applicableInfo])).push(info); + } + } + } + return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, (info) => info.type)), reduceLeft( + applicableInfos, + (isReadonly, info) => isReadonly && info.isReadonly, + /*initial*/ + true + )) : applicableInfo ? applicableInfo : stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : void 0; + } + function isApplicableIndexType(source, target) { + return isTypeAssignableTo(source, target) || target === stringType && isTypeAssignableTo(source, numberType) || target === numberType && (source === numericStringType || !!(source.flags & 128 /* StringLiteral */) && isNumericLiteralName(source.value)); + } + function getIndexInfosOfStructuredType(type) { + if (type.flags & 3670016 /* StructuredType */) { + const resolved = resolveStructuredTypeMembers(type); + return resolved.indexInfos; + } + return emptyArray; + } + function getIndexInfosOfType(type) { + return getIndexInfosOfStructuredType(getReducedApparentType(type)); + } + function getIndexInfoOfType(type, keyType) { + return findIndexInfo(getIndexInfosOfType(type), keyType); + } + function getIndexTypeOfType(type, keyType) { + var _a; + return (_a = getIndexInfoOfType(type, keyType)) == null ? void 0 : _a.type; + } + function getApplicableIndexInfos(type, keyType) { + return getIndexInfosOfType(type).filter((info) => isApplicableIndexType(keyType, info.keyType)); + } + function getApplicableIndexInfo(type, keyType) { + return findApplicableIndexInfo(getIndexInfosOfType(type), keyType); + } + function getApplicableIndexInfoForName(type, name) { + return getApplicableIndexInfo(type, isLateBoundName(name) ? esSymbolType : getStringLiteralType(unescapeLeadingUnderscores(name))); + } + function getTypeParametersFromDeclaration(declaration) { + var _a; + let result; + for (const node of getEffectiveTypeParameterDeclarations(declaration)) { + result = appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); + } + return (result == null ? void 0 : result.length) ? result : isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) == null ? void 0 : _a.typeParameters : void 0; + } + function symbolsToArray(symbols) { + const result = []; + symbols.forEach((symbol, id) => { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (isExternalModuleNameRelative(moduleName)) { + return void 0; + } + const symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function hasEffectiveQuestionToken(node) { + return hasQuestionToken(node) || isOptionalJSDocPropertyLikeTag(node) || isParameter(node) && isJSDocOptionalParameter(node); + } + function isOptionalParameter(node) { + if (hasEffectiveQuestionToken(node)) { + return true; + } + if (!isParameter(node)) { + return false; + } + if (node.initializer) { + const signature = getSignatureFromDeclaration(node.parent); + const parameterIndex = node.parent.parameters.indexOf(node); + Debug.assert(parameterIndex >= 0); + return parameterIndex >= getMinArgumentCount(signature, 1 /* StrongArityForUntypedJS */ | 2 /* VoidIsNonOptional */); + } + const iife = getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && !node.dotDotDotToken && node.parent.parameters.indexOf(node) >= getEffectiveCallArguments(iife).length; + } + return false; + } + function isOptionalPropertyDeclaration(node) { + return isPropertyDeclaration(node) && !hasAccessorModifier(node) && node.questionToken; + } + function createTypePredicate(kind, parameterName, parameterIndex, type) { + return { kind, parameterName, parameterIndex, type }; + } + function getMinTypeArgumentCount(typeParameters) { + let minTypeArgumentCount = 0; + if (typeParameters) { + for (let i = 0; i < typeParameters.length; i++) { + if (!hasTypeParameterDefault(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { + const numTypeParameters = length(typeParameters); + if (!numTypeParameters) { + return []; + } + const numTypeArguments = length(typeArguments); + if (isJavaScriptImplicitAny || numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters) { + const result = typeArguments ? typeArguments.slice() : []; + for (let i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = errorType; + } + const baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + for (let i = numTypeArguments; i < numTypeParameters; i++) { + let defaultType = getDefaultFromTypeParameter(typeParameters[i]); + if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType; + } + result.length = typeParameters.length; + return result; + } + return typeArguments && typeArguments.slice(); + } + function getSignatureFromDeclaration(declaration) { + const links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + const parameters = []; + let flags = 0 /* None */; + let minArgumentCount = 0; + let thisParameter; + let thisTag = isInJSFile(declaration) ? getJSDocThisTag(declaration) : void 0; + let hasThisParameter = false; + const iife = getImmediatelyInvokedFunctionExpression(declaration); + const isJSConstructSignature = isJSDocConstructSignature(declaration); + const isUntypedSignatureInJSFile = !iife && isInJSFile(declaration) && isValueSignatureDeclaration(declaration) && !hasJSDocParameterTags(declaration) && !getJSDocType(declaration); + if (isUntypedSignatureInJSFile) { + flags |= 32 /* IsUntypedSignatureInJSFile */; + } + for (let i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + const param = declaration.parameters[i]; + if (isInJSFile(param) && isJSDocThisTag(param)) { + thisTag = param; + continue; + } + let paramSymbol = param.symbol; + const type = isJSDocParameterTag(param) ? param.typeExpression && param.typeExpression.type : param.type; + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !isBindingPattern(param.name)) { + const resolvedSymbol = resolveName( + param, + paramSymbol.escapedName, + 111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { + hasThisParameter = true; + thisParameter = param.symbol; + } else { + parameters.push(paramSymbol); + } + if (type && type.kind === 201 /* LiteralType */) { + flags |= 2 /* HasLiteralTypes */; + } + const isOptionalParameter2 = hasEffectiveQuestionToken(param) || isParameter(param) && param.initializer || isRestParameter(param) || iife && parameters.length > iife.arguments.length && !type; + if (!isOptionalParameter2) { + minArgumentCount = parameters.length; + } + } + if ((declaration.kind === 177 /* GetAccessor */ || declaration.kind === 178 /* SetAccessor */) && hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { + const otherKind = declaration.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */; + const other = getDeclarationOfKind(getSymbolOfDeclaration(declaration), otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + if (thisTag && thisTag.typeExpression) { + thisParameter = createSymbolWithType(createSymbol(1 /* FunctionScopedVariable */, "this" /* This */), getTypeFromTypeNode(thisTag.typeExpression)); + } + const hostDeclaration = isJSDocSignature(declaration) ? getEffectiveJSDocHost(declaration) : declaration; + const classType = hostDeclaration && isConstructorDeclaration(hostDeclaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(hostDeclaration.parent.symbol)) : void 0; + const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } + if (isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, 64 /* Abstract */) || isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, 64 /* Abstract */)) { + flags |= 4 /* Abstract */; + } + links.resolvedSignature = createSignature( + declaration, + typeParameters, + thisParameter, + parameters, + /*resolvedReturnType*/ + void 0, + /*resolvedTypePredicate*/ + void 0, + minArgumentCount, + flags + ); + } + return links.resolvedSignature; + } + function maybeAddJsSyntheticRestParameter(declaration, parameters) { + if (isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { + return false; + } + const lastParam = lastOrUndefined(declaration.parameters); + const lastParamTags = lastParam ? getJSDocParameterTags(lastParam) : getJSDocTags(declaration).filter(isJSDocParameterTag); + const lastParamVariadicType = firstDefined(lastParamTags, (p) => p.typeExpression && isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : void 0); + const syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */); + if (lastParamVariadicType) { + syntheticArgsSymbol.links.type = createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)); + } else { + syntheticArgsSymbol.links.checkFlags |= 65536 /* DeferredType */; + syntheticArgsSymbol.links.deferralParent = neverType; + syntheticArgsSymbol.links.deferralConstituents = [anyArrayType]; + syntheticArgsSymbol.links.deferralWriteConstituents = [anyArrayType]; + } + if (lastParamVariadicType) { + parameters.pop(); + } + parameters.push(syntheticArgsSymbol); + return true; + } + function getSignatureOfTypeTag(node) { + if (!(isInJSFile(node) && isFunctionLikeDeclaration(node))) return void 0; + const typeTag = getJSDocTypeTag(node); + return (typeTag == null ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + } + function getParameterTypeOfTypeTag(func, parameter) { + const signature = getSignatureOfTypeTag(func); + if (!signature) return void 0; + const pos = func.parameters.indexOf(parameter); + return parameter.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos); + } + function getReturnTypeOfTypeTag(node) { + const signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); + } + function containsArgumentsReference(declaration) { + const links = getNodeLinks(declaration); + if (links.containsArgumentsReference === void 0) { + if (links.flags & 512 /* CaptureArguments */) { + links.containsArgumentsReference = true; + } else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) return false; + switch (node.kind) { + case 80 /* Identifier */: + return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; + case 172 /* PropertyDeclaration */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return node.name.kind === 167 /* ComputedPropertyName */ && traverse(node.name); + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + return traverse(node.expression); + case 303 /* PropertyAssignment */: + return traverse(node.initializer); + default: + return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && !!forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol || !symbol.declarations) return emptyArray; + const result = []; + for (let i = 0; i < symbol.declarations.length; i++) { + const decl = symbol.declarations[i]; + if (!isFunctionLike(decl)) continue; + if (i > 0 && decl.body) { + const previous = symbol.declarations[i - 1]; + if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { + continue; + } + } + if (isInJSFile(decl) && decl.jsDoc) { + const tags = getJSDocOverloadTags(decl); + if (length(tags)) { + for (const tag of tags) { + const jsDocSignature = tag.typeExpression; + if (jsDocSignature.type === void 0 && !isConstructorDeclaration(decl)) { + reportImplicitAny(jsDocSignature, anyType); + } + result.push(getSignatureFromDeclaration(jsDocSignature)); + } + continue; + } + } + result.push( + !isFunctionExpressionOrArrowFunction(decl) && !isObjectLiteralMethod(decl) && getSignatureOfTypeTag(decl) || getSignatureFromDeclaration(decl) + ); + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + const moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + const targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } else if (signature.compositeSignatures) { + signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate; + } else { + const type = signature.declaration && getEffectiveReturnTypeNode(signature.declaration); + let jsdocPredicate; + if (!type) { + const jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } + if (type || jsdocPredicate) { + signature.resolvedTypePredicate = type && isTypePredicateNode(type) ? createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate; + } else if (signature.declaration && isFunctionLikeDeclaration(signature.declaration) && (!signature.resolvedReturnType || signature.resolvedReturnType.flags & 16 /* Boolean */) && getParameterCount(signature) > 0) { + const { declaration } = signature; + signature.resolvedTypePredicate = noTypePredicate; + signature.resolvedTypePredicate = getTypePredicateFromBody(declaration) || noTypePredicate; + } else { + signature.resolvedTypePredicate = noTypePredicate; + } + } + Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? void 0 : signature.resolvedTypePredicate; + } + function createTypePredicateFromTypePredicateNode(node, signature) { + const parameterName = node.parameterName; + const type = node.type && getTypeFromTypeNode(node.type); + return parameterName.kind === 197 /* ThisType */ ? createTypePredicate( + node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, + /*parameterName*/ + void 0, + /*parameterIndex*/ + void 0, + type + ) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, findIndex(signature.parameters, (p) => p.escapedName === parameterName.escapedText), type); + } + function getUnionOrIntersectionType(types, kind, unionReduction) { + return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types); + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { + return errorType; + } + let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, 2 /* Subtype */), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); + if (signature.flags & 8 /* IsInnerCallChain */) { + type = addOptionalTypeMarker(type); + } else if (signature.flags & 16 /* IsOuterCallChain */) { + type = getOptionalType(type); + } + if (!popTypeResolution()) { + if (signature.declaration) { + const typeNode = getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, Diagnostics.Return_type_annotation_circularly_references_itself); + } else if (noImplicitAny) { + const declaration = signature.declaration; + const name = getNameOfDeclaration(declaration); + if (name) { + error(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name)); + } else { + error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } + } + } + type = anyType; + } + signature.resolvedReturnType ?? (signature.resolvedReturnType = type); + } + return signature.resolvedReturnType; + } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 176 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + const typeNode = getEffectiveReturnTypeNode(declaration); + if (isJSDocSignature(declaration)) { + const root = getJSDocRoot(declaration); + if (root && isConstructorDeclaration(root.parent) && !typeNode) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(root.parent.parent.symbol)); + } + } + if (isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); + } + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 177 /* GetAccessor */ && hasBindableName(declaration)) { + const jsDocType = isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + const setter = getDeclarationOfKind(getSymbolOfDeclaration(declaration), 178 /* SetAccessor */); + const setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } + function isResolvingReturnTypeOfSignature(signature) { + return signature.compositeSignatures && some(signature.compositeSignatures, isResolvingReturnTypeOfSignature) || !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; + } + function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + if (signatureHasRestParameter(signature)) { + const sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + const restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, numberType); + } + return void 0; + } + function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) { + const instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + if (inferredTypeParameters) { + const returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature)); + if (returnSignature) { + const newReturnSignature = cloneSignature(returnSignature); + newReturnSignature.typeParameters = inferredTypeParameters; + const newInstantiatedSignature = cloneSignature(instantiatedSignature); + newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature); + return newInstantiatedSignature; + } + } + return instantiatedSignature; + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { + const instantiations = signature.instantiations || (signature.instantiations = /* @__PURE__ */ new Map()); + const id = getTypeListId(typeArguments); + let instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature( + signature, + createSignatureTypeMapper(signature, typeArguments), + /*eraseTypeParameters*/ + true + ); + } + function getTypeParametersForMapper(signature) { + return sameMap(signature.typeParameters, (tp) => tp.mapper ? instantiateType(tp, tp.mapper) : tp); + } + function createSignatureTypeMapper(signature, typeArguments) { + return createTypeMapper(getTypeParametersForMapper(signature), typeArguments); + } + function getErasedSignature(signature) { + return signature.typeParameters ? signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : signature; + } + function createErasedSignature(signature) { + return instantiateSignature( + signature, + createTypeEraser(signature.typeParameters), + /*eraseTypeParameters*/ + true + ); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : signature; + } + function createCanonicalSignature(signature) { + return getSignatureInstantiation( + signature, + map(signature.typeParameters, (tp) => tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp), + isInJSFile(signature.declaration) + ); + } + function getImplementationSignature(signature) { + return signature.typeParameters ? signature.implementationSignatureCache || (signature.implementationSignatureCache = createImplementationSignature(signature)) : signature; + } + function createImplementationSignature(signature) { + return signature.typeParameters ? instantiateSignature(signature, createTypeMapper([], [])) : signature; + } + function getBaseSignature(signature) { + const typeParameters = signature.typeParameters; + if (typeParameters) { + if (signature.baseSignatureCache) { + return signature.baseSignatureCache; + } + const typeEraser = createTypeEraser(typeParameters); + const baseConstraintMapper = createTypeMapper(typeParameters, map(typeParameters, (tp) => getConstraintOfTypeParameter(tp) || unknownType)); + let baseConstraints = map(typeParameters, (tp) => instantiateType(tp, baseConstraintMapper) || unknownType); + for (let i = 0; i < typeParameters.length - 1; i++) { + baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper); + } + baseConstraints = instantiateTypes(baseConstraints, typeEraser); + return signature.baseSignatureCache = instantiateSignature( + signature, + createTypeMapper(typeParameters, baseConstraints), + /*eraseTypeParameters*/ + true + ); + } + return signature; + } + function getOrCreateTypeFromSignature(signature, outerTypeParameters) { + var _a; + if (!signature.isolatedSignatureType) { + const kind = (_a = signature.declaration) == null ? void 0 : _a.kind; + const isConstructor = kind === void 0 || kind === 176 /* Constructor */ || kind === 180 /* ConstructSignature */ || kind === 185 /* ConstructorType */; + const type = createObjectType(16 /* Anonymous */ | 134217728 /* SingleSignatureType */, createSymbol(16 /* Function */, "__function" /* Function */)); + if (signature.declaration && !nodeIsSynthesized(signature.declaration)) { + type.symbol.declarations = [signature.declaration]; + type.symbol.valueDeclaration = signature.declaration; + } + outerTypeParameters || (outerTypeParameters = signature.declaration && getOuterTypeParameters( + signature.declaration, + /*includeThisTypes*/ + true + )); + type.outerTypeParameters = outerTypeParameters; + type.members = emptySymbols; + type.properties = emptyArray; + type.callSignatures = !isConstructor ? [signature] : emptyArray; + type.constructSignatures = isConstructor ? [signature] : emptyArray; + type.indexInfos = emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members ? getIndexSymbolFromSymbolTable(getMembersOfSymbol(symbol)) : void 0; + } + function getIndexSymbolFromSymbolTable(symbolTable) { + return symbolTable.get("__index" /* Index */); + } + function createIndexInfo(keyType, type, isReadonly, declaration, components) { + return { keyType, type, isReadonly, declaration, components }; + } + function getIndexInfosOfSymbol(symbol) { + const indexSymbol = getIndexSymbol(symbol); + return indexSymbol ? getIndexInfosOfIndexSymbol(indexSymbol, arrayFrom(getMembersOfSymbol(symbol).values())) : emptyArray; + } + function getIndexInfosOfIndexSymbol(indexSymbol, siblingSymbols = indexSymbol.parent ? arrayFrom(getMembersOfSymbol(indexSymbol.parent).values()) : void 0) { + if (indexSymbol.declarations) { + const indexInfos = []; + let hasComputedNumberProperty = false; + let readonlyComputedNumberProperty = true; + let hasComputedSymbolProperty = false; + let readonlyComputedSymbolProperty = true; + let hasComputedStringProperty = false; + let readonlyComputedStringProperty = true; + const computedPropertySymbols = []; + for (const declaration of indexSymbol.declarations) { + if (isIndexSignatureDeclaration(declaration)) { + if (declaration.parameters.length === 1) { + const parameter = declaration.parameters[0]; + if (parameter.type) { + forEachType(getTypeFromTypeNode(parameter.type), (keyType) => { + if (isValidIndexKeyType(keyType) && !findIndexInfo(indexInfos, keyType)) { + indexInfos.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, hasEffectiveModifier(declaration, 8 /* Readonly */), declaration)); + } + }); + } + } + } else if (hasLateBindableIndexSignature(declaration)) { + const declName = isBinaryExpression(declaration) ? declaration.left : declaration.name; + const keyType = isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName); + if (findIndexInfo(indexInfos, keyType)) { + continue; + } + if (isTypeAssignableTo(keyType, stringNumberSymbolType)) { + if (isTypeAssignableTo(keyType, numberType)) { + hasComputedNumberProperty = true; + if (!hasEffectiveReadonlyModifier(declaration)) { + readonlyComputedNumberProperty = false; + } + } else if (isTypeAssignableTo(keyType, esSymbolType)) { + hasComputedSymbolProperty = true; + if (!hasEffectiveReadonlyModifier(declaration)) { + readonlyComputedSymbolProperty = false; + } + } else { + hasComputedStringProperty = true; + if (!hasEffectiveReadonlyModifier(declaration)) { + readonlyComputedStringProperty = false; + } + } + computedPropertySymbols.push(declaration.symbol); + } + } + } + const allPropertySymbols = concatenate(computedPropertySymbols, filter(siblingSymbols, (s) => s !== indexSymbol)); + if (hasComputedStringProperty && !findIndexInfo(indexInfos, stringType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedStringProperty, 0, allPropertySymbols, stringType)); + if (hasComputedNumberProperty && !findIndexInfo(indexInfos, numberType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedNumberProperty, 0, allPropertySymbols, numberType)); + if (hasComputedSymbolProperty && !findIndexInfo(indexInfos, esSymbolType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedSymbolProperty, 0, allPropertySymbols, esSymbolType)); + return indexInfos; + } + return emptyArray; + } + function isValidIndexKeyType(type) { + return !!(type.flags & (4 /* String */ | 8 /* Number */ | 4096 /* ESSymbol */)) || isPatternLiteralType(type) || !!(type.flags & 2097152 /* Intersection */) && !isGenericType(type) && some(type.types, isValidIndexKeyType); + } + function getConstraintDeclaration(type) { + return mapDefined(filter(type.symbol && type.symbol.declarations, isTypeParameterDeclaration), getEffectiveConstraintOfTypeParameter)[0]; + } + function getInferredTypeParameterConstraint(typeParameter, omitTypeReferences) { + var _a; + let inferences; + if ((_a = typeParameter.symbol) == null ? void 0 : _a.declarations) { + for (const declaration of typeParameter.symbol.declarations) { + if (declaration.parent.kind === 195 /* InferType */) { + const [childTypeParameter = declaration.parent, grandParent] = walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent); + if (grandParent.kind === 183 /* TypeReference */ && !omitTypeReferences) { + const typeReference = grandParent; + const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReference); + if (typeParameters) { + const index = typeReference.typeArguments.indexOf(childTypeParameter); + if (index < typeParameters.length) { + const declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + const mapper = makeDeferredTypeMapper( + typeParameters, + typeParameters.map((_, index2) => () => { + return getEffectiveTypeArgumentAtIndex(typeReference, typeParameters, index2); + }) + ); + const constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = append(inferences, constraint); + } + } + } + } + } else if (grandParent.kind === 169 /* Parameter */ && grandParent.dotDotDotToken || grandParent.kind === 191 /* RestType */ || grandParent.kind === 202 /* NamedTupleMember */ && grandParent.dotDotDotToken) { + inferences = append(inferences, createArrayType(unknownType)); + } else if (grandParent.kind === 204 /* TemplateLiteralTypeSpan */) { + inferences = append(inferences, stringType); + } else if (grandParent.kind === 168 /* TypeParameter */ && grandParent.parent.kind === 200 /* MappedType */) { + inferences = append(inferences, stringNumberSymbolType); + } else if (grandParent.kind === 200 /* MappedType */ && grandParent.type && skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 194 /* ConditionalType */ && grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 200 /* MappedType */ && grandParent.parent.checkType.type) { + const checkMappedType2 = grandParent.parent.checkType; + const nodeType = getTypeFromTypeNode(checkMappedType2.type); + inferences = append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(checkMappedType2.typeParameter)), checkMappedType2.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType2.typeParameter.constraint) : stringNumberSymbolType))); + } + } + } + } + return inferences && getIntersectionType(inferences); + } + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + const targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } else { + const constraintDeclaration = getConstraintDeclaration(typeParameter); + if (!constraintDeclaration) { + typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType; + } else { + let type = getTypeFromTypeNode(constraintDeclaration); + if (type.flags & 1 /* Any */ && !isErrorType(type)) { + type = constraintDeclaration.parent.parent.kind === 200 /* MappedType */ ? stringNumberSymbolType : unknownType; + } + typeParameter.constraint = type; + } + } + } + return typeParameter.constraint === noConstraintType ? void 0 : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + const tp = getDeclarationOfKind(typeParameter.symbol, 168 /* TypeParameter */); + const host2 = isJSDocTemplateTag(tp.parent) ? getEffectiveContainerForJSDocTemplateTag(tp.parent) : tp.parent; + return host2 && getSymbolOfNode(host2); + } + function getTypeListId(types) { + let result = ""; + if (types) { + const length2 = types.length; + let i = 0; + while (i < length2) { + const startId = types[i].id; + let count = 1; + while (i + count < length2 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? `@${getSymbolId(aliasSymbol)}` + (aliasTypeArguments ? `:${getTypeListId(aliasTypeArguments)}` : "") : ""; + } + function getPropagatingFlagsOfTypes(types, excludeKinds) { + let result = 0; + for (const type of types) { + if (excludeKinds === void 0 || !(type.flags & excludeKinds)) { + result |= getObjectFlags(type); + } + } + return result & 458752 /* PropagatingFlags */; + } + function tryCreateTypeReference(target, typeArguments) { + if (some(typeArguments) && target === emptyGenericType) { + return unknownType; + } + return createTypeReference(target, typeArguments); + } + function createTypeReference(target, typeArguments) { + const id = getTypeListId(typeArguments); + let type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4 /* Reference */, target.symbol); + target.instantiations.set(id, type); + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0; + type.target = target; + type.resolvedTypeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + const type = createTypeWithSymbol(source.flags, source.symbol); + type.objectFlags = source.objectFlags; + type.target = source.target; + type.resolvedTypeArguments = source.resolvedTypeArguments; + return type; + } + function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) { + if (!aliasSymbol) { + aliasSymbol = getAliasSymbolForTypeNode(node); + const localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments; + } + const type = createObjectType(4 /* Reference */, target.symbol); + type.target = target; + type.node = node; + type.mapper = mapper; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + return type; + } + function getTypeArguments(type) { + var _a, _b; + if (!type.resolvedTypeArguments) { + if (!pushTypeResolution(type, 5 /* ResolvedTypeArguments */)) { + return concatenate(type.target.outerTypeParameters, (_a = type.target.localTypeParameters) == null ? void 0 : _a.map(() => errorType)) || emptyArray; + } + const node = type.node; + const typeArguments = !node ? emptyArray : node.kind === 183 /* TypeReference */ ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === 188 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode); + if (popTypeResolution()) { + type.resolvedTypeArguments ?? (type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments); + } else { + type.resolvedTypeArguments ?? (type.resolvedTypeArguments = concatenate(type.target.outerTypeParameters, ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(() => errorType)) || emptyArray)); + error( + type.node || currentNode, + type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves, + type.target.symbol && symbolToString(type.target.symbol) + ); + } + } + return type.resolvedTypeArguments; + } + function getTypeReferenceArity(type) { + return length(type.target.typeParameters); + } + function getTypeFromClassOrInterfaceReference(node, symbol) { + const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + const typeParameters = type.localTypeParameters; + if (typeParameters) { + const numTypeArguments = length(node.typeArguments); + const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + const isJs = isInJSFile(node); + const isJsImplicitAny = !noImplicitAny && isJs; + if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + const missingAugmentsTag = isJs && isExpressionWithTypeArguments(node) && !isJSDocAugmentsTag(node.parent); + const diag2 = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_1_type_argument_s : missingAugmentsTag ? Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + const typeStr = typeToString( + type, + /*enclosingDeclaration*/ + void 0, + 2 /* WriteArrayAsGenericType */ + ); + error(node, diag2, typeStr, minTypeArgumentCount, typeParameters.length); + if (!isJs) { + return errorType; + } + } + if (node.kind === 183 /* TypeReference */ && isDeferredTypeReferenceNode(node, length(node.typeArguments) !== typeParameters.length)) { + return createDeferredTypeReference( + type, + node, + /*mapper*/ + void 0 + ); + } + const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs)); + return createTypeReference(type, typeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) { + const type = getDeclaredTypeOfSymbol(symbol); + if (type === intrinsicMarkerType) { + const typeKind = intrinsicTypeKinds.get(symbol.escapedName); + if (typeKind !== void 0 && typeArguments && typeArguments.length === 1) { + return typeKind === 4 /* NoInfer */ ? getNoInferType(typeArguments[0]) : getStringMappingType(symbol, typeArguments[0]); + } + } + const links = getSymbolLinks(symbol); + const typeParameters = links.typeParameters; + const id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); + let instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); + } + return instantiation; + } + function getTypeFromTypeAliasReference(node, symbol) { + if (getCheckFlags(symbol) & 1048576 /* Unresolved */) { + const typeArguments = typeArgumentsFromTypeReferenceNode(node); + const id = getAliasId(symbol, typeArguments); + let errorType2 = errorTypes.get(id); + if (!errorType2) { + errorType2 = createIntrinsicType( + 1 /* Any */, + "error", + /*objectFlags*/ + void 0, + `alias ${id}` + ); + errorType2.aliasSymbol = symbol; + errorType2.aliasTypeArguments = typeArguments; + errorTypes.set(id, errorType2); + } + return errorType2; + } + const type = getDeclaredTypeOfSymbol(symbol); + const typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + const numTypeArguments = length(node.typeArguments); + const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error( + node, + minTypeArgumentCount === typeParameters.length ? Diagnostics.Generic_type_0_requires_1_type_argument_s : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, + symbolToString(symbol), + minTypeArgumentCount, + typeParameters.length + ); + return errorType; + } + const aliasSymbol = getAliasSymbolForTypeNode(node); + let newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : void 0; + let aliasTypeArguments; + if (newAliasSymbol) { + aliasTypeArguments = getTypeArgumentsForAliasSymbol(newAliasSymbol); + } else if (isTypeReferenceType(node)) { + const aliasSymbol2 = resolveTypeReferenceName( + node, + 2097152 /* Alias */, + /*ignoreErrors*/ + true + ); + if (aliasSymbol2 && aliasSymbol2 !== unknownSymbol) { + const resolved = resolveAlias(aliasSymbol2); + if (resolved && resolved.flags & 524288 /* TypeAlias */) { + newAliasSymbol = resolved; + aliasTypeArguments = typeArgumentsFromTypeReferenceNode(node) || (typeParameters ? [] : void 0); + } + } + } + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, aliasTypeArguments); + } + return checkNoTypeArguments(node, symbol) ? type : errorType; + } + function isLocalTypeAlias(symbol) { + var _a; + const declaration = (_a = symbol.declarations) == null ? void 0 : _a.find(isTypeAlias); + return !!(declaration && getContainingFunction(declaration)); + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 183 /* TypeReference */: + return node.typeName; + case 233 /* ExpressionWithTypeArguments */: + const expr = node.expression; + if (isEntityNameExpression(expr)) { + return expr; + } + } + return void 0; + } + function getSymbolPath(symbol) { + return symbol.parent ? `${getSymbolPath(symbol.parent)}.${symbol.escapedName}` : symbol.escapedName; + } + function getUnresolvedSymbolForEntityName(name) { + const identifier = name.kind === 166 /* QualifiedName */ ? name.right : name.kind === 211 /* PropertyAccessExpression */ ? name.name : name; + const text = identifier.escapedText; + if (text) { + const parentSymbol = name.kind === 166 /* QualifiedName */ ? getUnresolvedSymbolForEntityName(name.left) : name.kind === 211 /* PropertyAccessExpression */ ? getUnresolvedSymbolForEntityName(name.expression) : void 0; + const path = parentSymbol ? `${getSymbolPath(parentSymbol)}.${text}` : text; + let result = unresolvedSymbols.get(path); + if (!result) { + unresolvedSymbols.set(path, result = createSymbol(524288 /* TypeAlias */, text, 1048576 /* Unresolved */)); + result.parent = parentSymbol; + result.links.declaredType = unresolvedType; + } + return result; + } + return unknownSymbol; + } + function resolveTypeReferenceName(typeReference, meaning, ignoreErrors) { + const name = getTypeReferenceName(typeReference); + if (!name) { + return unknownSymbol; + } + const symbol = resolveEntityName(name, meaning, ignoreErrors); + return symbol && symbol !== unknownSymbol ? symbol : ignoreErrors ? unknownSymbol : getUnresolvedSymbolForEntityName(name); + } + function getTypeReferenceType(node, symbol) { + if (symbol === unknownSymbol) { + return errorType; + } + symbol = getExpandoSymbol(symbol) || symbol; + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getTypeFromClassOrInterfaceReference(node, symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol); + } + const res = tryGetDeclaredTypeOfSymbol(symbol); + if (res) { + return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType; + } + if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { + const jsdocType = getTypeFromJSDocValueReference(node, symbol); + if (jsdocType) { + return jsdocType; + } else { + resolveTypeReferenceName(node, 788968 /* Type */); + return getTypeOfSymbol(symbol); + } + } + return errorType; + } + function getTypeFromJSDocValueReference(node, symbol) { + const links = getNodeLinks(node); + if (!links.resolvedJSDocType) { + const valueType = getTypeOfSymbol(symbol); + let typeType = valueType; + if (symbol.valueDeclaration) { + const isImportTypeWithQualifier = node.kind === 205 /* ImportType */ && node.qualifier; + if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) { + typeType = getTypeReferenceType(node, valueType.symbol); + } + } + links.resolvedJSDocType = typeType; + } + return links.resolvedJSDocType; + } + function getNoInferType(type) { + return isNoInferTargetType(type) ? getOrCreateSubstitutionType(type, unknownType) : type; + } + function isNoInferTargetType(type) { + return !!(type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, isNoInferTargetType) || type.flags & 33554432 /* Substitution */ && !isNoInferType(type) && isNoInferTargetType(type.baseType) || type.flags & 524288 /* Object */ && !isEmptyAnonymousObjectType(type) || type.flags & (465829888 /* Instantiable */ & ~33554432 /* Substitution */) && !isPatternLiteralType(type)); + } + function isNoInferType(type) { + return !!(type.flags & 33554432 /* Substitution */ && type.constraint.flags & 2 /* Unknown */); + } + function getSubstitutionType(baseType, constraint) { + return constraint.flags & 3 /* AnyOrUnknown */ || constraint === baseType || baseType.flags & 1 /* Any */ ? baseType : getOrCreateSubstitutionType(baseType, constraint); + } + function getOrCreateSubstitutionType(baseType, constraint) { + const id = `${getTypeId(baseType)}>${getTypeId(constraint)}`; + const cached = substitutionTypes.get(id); + if (cached) { + return cached; + } + const result = createType(33554432 /* Substitution */); + result.baseType = baseType; + result.constraint = constraint; + substitutionTypes.set(id, result); + return result; + } + function getSubstitutionIntersection(substitutionType) { + return isNoInferType(substitutionType) ? substitutionType.baseType : getIntersectionType([substitutionType.constraint, substitutionType.baseType]); + } + function isUnaryTupleTypeNode(node) { + return node.kind === 189 /* TupleType */ && node.elements.length === 1; + } + function getImpliedConstraint(type, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : getActualTypeVariable(getTypeFromTypeNode(checkNode)) === getActualTypeVariable(type) ? getTypeFromTypeNode(extendsNode) : void 0; + } + function getConditionalFlowTypeOfType(type, node) { + let constraints; + let covariant = true; + while (node && !isStatement(node) && node.kind !== 320 /* JSDoc */) { + const parent = node.parent; + if (parent.kind === 169 /* Parameter */) { + covariant = !covariant; + } + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 194 /* ConditionalType */ && node === parent.trueType) { + const constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); + if (constraint) { + constraints = append(constraints, constraint); + } + } else if (type.flags & 262144 /* TypeParameter */ && parent.kind === 200 /* MappedType */ && !parent.nameType && node === parent.type) { + const mappedType = getTypeFromTypeNode(parent); + if (getTypeParameterFromMappedType(mappedType) === getActualTypeVariable(type)) { + const typeParameter = getHomomorphicTypeVariable(mappedType); + if (typeParameter) { + const constraint = getConstraintOfTypeParameter(typeParameter); + if (constraint && everyType(constraint, isArrayOrTupleType)) { + constraints = append(constraints, getUnionType([numberType, numericStringType])); + } + } + } + } + node = parent; + } + return constraints ? getSubstitutionType(type, getIntersectionType(constraints)) : type; + } + function isJSDocTypeReference(node) { + return !!(node.flags & 16777216 /* JSDoc */) && (node.kind === 183 /* TypeReference */ || node.kind === 205 /* ImportType */); + } + function checkNoTypeArguments(node, symbol) { + if (node.typeArguments) { + error(node, Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? declarationNameToString(node.typeName) : anon); + return false; + } + return true; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (isIdentifier(node.typeName)) { + const typeArgs = node.typeArguments; + switch (node.typeName.escapedText) { + case "String": + checkNoTypeArguments(node); + return stringType; + case "Number": + checkNoTypeArguments(node); + return numberType; + case "BigInt": + checkNoTypeArguments(node); + return bigintType; + case "Boolean": + checkNoTypeArguments(node); + return booleanType; + case "Void": + checkNoTypeArguments(node); + return voidType; + case "Undefined": + checkNoTypeArguments(node); + return undefinedType; + case "Null": + checkNoTypeArguments(node); + return nullType; + case "Function": + case "function": + checkNoTypeArguments(node); + return globalFunctionType; + case "array": + return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : void 0; + case "promise": + return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : void 0; + case "Object": + if (typeArgs && typeArgs.length === 2) { + if (isJSDocIndexSignature(node)) { + const indexed = getTypeFromTypeNode(typeArgs[0]); + const target = getTypeFromTypeNode(typeArgs[1]); + const indexInfo = indexed === stringType || indexed === numberType ? [createIndexInfo( + indexed, + target, + /*isReadonly*/ + false + )] : emptyArray; + return createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + indexInfo + ); + } + return anyType; + } + checkNoTypeArguments(node); + return !noImplicitAny ? anyType : void 0; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + const type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type; + } + function getTypeFromTypeReference(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + if (isConstTypeReference(node) && isAssertionExpression(node.parent)) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = checkExpressionCached(node.parent.expression); + } + let symbol; + let type; + const meaning = 788968 /* Type */; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + if (!type) { + symbol = resolveTypeReferenceName( + node, + meaning, + /*ignoreErrors*/ + true + ); + if (symbol === unknownSymbol) { + symbol = resolveTypeReferenceName(node, meaning | 111551 /* Value */); + } else { + resolveTypeReferenceName(node, meaning); + } + type = getTypeReferenceType(node, symbol); + } + } + if (!type) { + symbol = resolveTypeReferenceName(node, meaning); + type = getTypeReferenceType(node, symbol); + } + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + return links.resolvedType; + } + function typeArgumentsFromTypeReferenceNode(node) { + return map(node.typeArguments, getTypeFromTypeNode); + } + function getTypeFromTypeQueryNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const type = checkExpressionWithTypeArguments(node); + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(type)); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol2) { + const declarations = symbol2.declarations; + if (declarations) { + for (const declaration of declarations) { + switch (declaration.kind) { + case 263 /* ClassDeclaration */: + case 264 /* InterfaceDeclaration */: + case 266 /* EnumDeclaration */: + return declaration; + } + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + const type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 524288 /* Object */)) { + error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbolName(symbol)); + return arity ? emptyGenericType : emptyObjectType; + } + if (length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors2) { + return getGlobalSymbol(name, 111551 /* Value */, reportErrors2 ? Diagnostics.Cannot_find_global_value_0 : void 0); + } + function getGlobalTypeSymbol(name, reportErrors2) { + return getGlobalSymbol(name, 788968 /* Type */, reportErrors2 ? Diagnostics.Cannot_find_global_type_0 : void 0); + } + function getGlobalTypeAliasSymbol(name, arity, reportErrors2) { + const symbol = getGlobalSymbol(name, 788968 /* Type */, reportErrors2 ? Diagnostics.Cannot_find_global_type_0 : void 0); + if (symbol) { + getDeclaredTypeOfSymbol(symbol); + if (length(getSymbolLinks(symbol).typeParameters) !== arity) { + const decl = symbol.declarations && find(symbol.declarations, isTypeAliasDeclaration); + error(decl, Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity); + return void 0; + } + } + return symbol; + } + function getGlobalSymbol(name, meaning, diagnostic) { + return resolveName( + /*location*/ + void 0, + name, + meaning, + diagnostic, + /*isUse*/ + false, + /*excludeGlobals*/ + false + ); + } + function getGlobalType(name, arity, reportErrors2) { + const symbol = getGlobalTypeSymbol(name, reportErrors2); + return symbol || reportErrors2 ? getTypeOfGlobalSymbol(symbol, arity) : void 0; + } + function getGlobalBuiltinTypes(typeNames, arity) { + let types; + for (const typeName of typeNames) { + types = append(types, getGlobalType( + typeName, + arity, + /*reportErrors*/ + false + )); + } + return types ?? emptyArray; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType( + "TypedPropertyDescriptor", + /*arity*/ + 1, + /*reportErrors*/ + true + ) || emptyGenericType); + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType( + "TemplateStringsArray", + /*arity*/ + 0, + /*reportErrors*/ + true + ) || emptyObjectType); + } + function getGlobalImportMetaType() { + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType( + "ImportMeta", + /*arity*/ + 0, + /*reportErrors*/ + true + ) || emptyObjectType); + } + function getGlobalImportMetaExpressionType() { + if (!deferredGlobalImportMetaExpressionType) { + const symbol = createSymbol(0 /* None */, "ImportMetaExpression"); + const importMetaType = getGlobalImportMetaType(); + const metaPropertySymbol = createSymbol(4 /* Property */, "meta", 8 /* Readonly */); + metaPropertySymbol.parent = symbol; + metaPropertySymbol.links.type = importMetaType; + const members = createSymbolTable([metaPropertySymbol]); + symbol.members = members; + deferredGlobalImportMetaExpressionType = createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray); + } + return deferredGlobalImportMetaExpressionType; + } + function getGlobalImportCallOptionsType(reportErrors2) { + return deferredGlobalImportCallOptionsType || (deferredGlobalImportCallOptionsType = getGlobalType( + "ImportCallOptions", + /*arity*/ + 0, + reportErrors2 + )) || emptyObjectType; + } + function getGlobalImportAttributesType(reportErrors2) { + return deferredGlobalImportAttributesType || (deferredGlobalImportAttributesType = getGlobalType( + "ImportAttributes", + /*arity*/ + 0, + reportErrors2 + )) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors2) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors2)); + } + function getGlobalESSymbolConstructorTypeSymbol(reportErrors2) { + return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors2)); + } + function getGlobalESSymbolType() { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType( + "Symbol", + /*arity*/ + 0, + /*reportErrors*/ + false + )) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors2) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType( + "Promise", + /*arity*/ + 1, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalPromiseLikeType(reportErrors2) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType( + "PromiseLike", + /*arity*/ + 1, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors2) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors2)); + } + function getGlobalPromiseConstructorLikeType(reportErrors2) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType( + "PromiseConstructorLike", + /*arity*/ + 0, + reportErrors2 + )) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors2) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType( + "AsyncIterable", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors2) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType( + "AsyncIterator", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors2) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType( + "AsyncIterableIterator", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalBuiltinAsyncIteratorTypes() { + return deferredGlobalBuiltinAsyncIteratorTypes ?? (deferredGlobalBuiltinAsyncIteratorTypes = getGlobalBuiltinTypes(["ReadableStreamAsyncIterator"], 1)); + } + function getGlobalAsyncIteratorObjectType(reportErrors2) { + return deferredGlobalAsyncIteratorObjectType || (deferredGlobalAsyncIteratorObjectType = getGlobalType( + "AsyncIteratorObject", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalAsyncGeneratorType(reportErrors2) { + return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType( + "AsyncGenerator", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalIterableType(reportErrors2) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType( + "Iterable", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors2) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType( + "Iterator", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors2) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType( + "IterableIterator", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getBuiltinIteratorReturnType() { + return strictBuiltinIteratorReturn ? undefinedType : anyType; + } + function getGlobalBuiltinIteratorTypes() { + return deferredGlobalBuiltinIteratorTypes ?? (deferredGlobalBuiltinIteratorTypes = getGlobalBuiltinTypes(["ArrayIterator", "MapIterator", "SetIterator", "StringIterator"], 1)); + } + function getGlobalIteratorObjectType(reportErrors2) { + return deferredGlobalIteratorObjectType || (deferredGlobalIteratorObjectType = getGlobalType( + "IteratorObject", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalGeneratorType(reportErrors2) { + return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType( + "Generator", + /*arity*/ + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalIteratorYieldResultType(reportErrors2) { + return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType( + "IteratorYieldResult", + /*arity*/ + 1, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalIteratorReturnResultType(reportErrors2) { + return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType( + "IteratorReturnResult", + /*arity*/ + 1, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalDisposableType(reportErrors2) { + return deferredGlobalDisposableType || (deferredGlobalDisposableType = getGlobalType( + "Disposable", + /*arity*/ + 0, + reportErrors2 + )) || emptyObjectType; + } + function getGlobalAsyncDisposableType(reportErrors2) { + return deferredGlobalAsyncDisposableType || (deferredGlobalAsyncDisposableType = getGlobalType( + "AsyncDisposable", + /*arity*/ + 0, + reportErrors2 + )) || emptyObjectType; + } + function getGlobalTypeOrUndefined(name, arity = 0) { + const symbol = getGlobalSymbol( + name, + 788968 /* Type */, + /*diagnostic*/ + void 0 + ); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getGlobalExtractSymbol() { + deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalTypeAliasSymbol( + "Extract", + /*arity*/ + 2, + /*reportErrors*/ + true + ) || unknownSymbol); + return deferredGlobalExtractSymbol === unknownSymbol ? void 0 : deferredGlobalExtractSymbol; + } + function getGlobalOmitSymbol() { + deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalTypeAliasSymbol( + "Omit", + /*arity*/ + 2, + /*reportErrors*/ + true + ) || unknownSymbol); + return deferredGlobalOmitSymbol === unknownSymbol ? void 0 : deferredGlobalOmitSymbol; + } + function getGlobalAwaitedSymbol(reportErrors2) { + deferredGlobalAwaitedSymbol || (deferredGlobalAwaitedSymbol = getGlobalTypeAliasSymbol( + "Awaited", + /*arity*/ + 1, + reportErrors2 + ) || (reportErrors2 ? unknownSymbol : void 0)); + return deferredGlobalAwaitedSymbol === unknownSymbol ? void 0 : deferredGlobalAwaitedSymbol; + } + function getGlobalBigIntType() { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType( + "BigInt", + /*arity*/ + 0, + /*reportErrors*/ + false + )) || emptyObjectType; + } + function getGlobalClassDecoratorContextType(reportErrors2) { + return deferredGlobalClassDecoratorContextType ?? (deferredGlobalClassDecoratorContextType = getGlobalType( + "ClassDecoratorContext", + /*arity*/ + 1, + reportErrors2 + )) ?? emptyGenericType; + } + function getGlobalClassMethodDecoratorContextType(reportErrors2) { + return deferredGlobalClassMethodDecoratorContextType ?? (deferredGlobalClassMethodDecoratorContextType = getGlobalType( + "ClassMethodDecoratorContext", + /*arity*/ + 2, + reportErrors2 + )) ?? emptyGenericType; + } + function getGlobalClassGetterDecoratorContextType(reportErrors2) { + return deferredGlobalClassGetterDecoratorContextType ?? (deferredGlobalClassGetterDecoratorContextType = getGlobalType( + "ClassGetterDecoratorContext", + /*arity*/ + 2, + reportErrors2 + )) ?? emptyGenericType; + } + function getGlobalClassSetterDecoratorContextType(reportErrors2) { + return deferredGlobalClassSetterDecoratorContextType ?? (deferredGlobalClassSetterDecoratorContextType = getGlobalType( + "ClassSetterDecoratorContext", + /*arity*/ + 2, + reportErrors2 + )) ?? emptyGenericType; + } + function getGlobalClassAccessorDecoratorContextType(reportErrors2) { + return deferredGlobalClassAccessorDecoratorContextType ?? (deferredGlobalClassAccessorDecoratorContextType = getGlobalType( + "ClassAccessorDecoratorContext", + /*arity*/ + 2, + reportErrors2 + )) ?? emptyGenericType; + } + function getGlobalClassAccessorDecoratorTargetType(reportErrors2) { + return deferredGlobalClassAccessorDecoratorTargetType ?? (deferredGlobalClassAccessorDecoratorTargetType = getGlobalType( + "ClassAccessorDecoratorTarget", + /*arity*/ + 2, + reportErrors2 + )) ?? emptyGenericType; + } + function getGlobalClassAccessorDecoratorResultType(reportErrors2) { + return deferredGlobalClassAccessorDecoratorResultType ?? (deferredGlobalClassAccessorDecoratorResultType = getGlobalType( + "ClassAccessorDecoratorResult", + /*arity*/ + 2, + reportErrors2 + )) ?? emptyGenericType; + } + function getGlobalClassFieldDecoratorContextType(reportErrors2) { + return deferredGlobalClassFieldDecoratorContextType ?? (deferredGlobalClassFieldDecoratorContextType = getGlobalType( + "ClassFieldDecoratorContext", + /*arity*/ + 2, + reportErrors2 + )) ?? emptyGenericType; + } + function getGlobalNaNSymbol() { + return deferredGlobalNaNSymbol || (deferredGlobalNaNSymbol = getGlobalValueSymbol( + "NaN", + /*reportErrors*/ + false + )); + } + function getGlobalRecordSymbol() { + deferredGlobalRecordSymbol || (deferredGlobalRecordSymbol = getGlobalTypeAliasSymbol( + "Record", + /*arity*/ + 2, + /*reportErrors*/ + true + ) || unknownSymbol); + return deferredGlobalRecordSymbol === unknownSymbol ? void 0 : deferredGlobalRecordSymbol; + } + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType( + /*reportErrors*/ + true + ), [iteratedType, voidType, undefinedType]); + } + function createArrayType(elementType, readonly) { + return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]); + } + function getTupleElementFlags(node) { + switch (node.kind) { + case 190 /* OptionalType */: + return 2 /* Optional */; + case 191 /* RestType */: + return getRestTypeElementFlags(node); + case 202 /* NamedTupleMember */: + return node.questionToken ? 2 /* Optional */ : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1 /* Required */; + default: + return 1 /* Required */; + } + } + function getRestTypeElementFlags(node) { + return getArrayElementTypeNode(node.type) ? 4 /* Rest */ : 8 /* Variadic */; + } + function getArrayOrTupleTargetType(node) { + const readonly = isReadonlyTypeOperator(node.parent); + const elementType = getArrayElementTypeNode(node); + if (elementType) { + return readonly ? globalReadonlyArrayType : globalArrayType; + } + const elementFlags = map(node.elements, getTupleElementFlags); + return getTupleTargetType(elementFlags, readonly, map(node.elements, memberIfLabeledElementDeclaration)); + } + function memberIfLabeledElementDeclaration(member) { + return isNamedTupleMember(member) || isParameter(member) ? member : void 0; + } + function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 188 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : node.kind === 189 /* TupleType */ ? some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || some(node.typeArguments, mayResolveTypeAlias)); + } + function isResolvedByTypeAlias(node) { + const parent = node.parent; + switch (parent.kind) { + case 196 /* ParenthesizedType */: + case 202 /* NamedTupleMember */: + case 183 /* TypeReference */: + case 192 /* UnionType */: + case 193 /* IntersectionType */: + case 199 /* IndexedAccessType */: + case 194 /* ConditionalType */: + case 198 /* TypeOperator */: + case 188 /* ArrayType */: + case 189 /* TupleType */: + return isResolvedByTypeAlias(parent); + case 265 /* TypeAliasDeclaration */: + return true; + } + return false; + } + function mayResolveTypeAlias(node) { + switch (node.kind) { + case 183 /* TypeReference */: + return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node, 788968 /* Type */).flags & 524288 /* TypeAlias */); + case 186 /* TypeQuery */: + return true; + case 198 /* TypeOperator */: + return node.operator !== 158 /* UniqueKeyword */ && mayResolveTypeAlias(node.type); + case 196 /* ParenthesizedType */: + case 190 /* OptionalType */: + case 202 /* NamedTupleMember */: + case 316 /* JSDocOptionalType */: + case 314 /* JSDocNullableType */: + case 315 /* JSDocNonNullableType */: + case 309 /* JSDocTypeExpression */: + return mayResolveTypeAlias(node.type); + case 191 /* RestType */: + return node.type.kind !== 188 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); + case 192 /* UnionType */: + case 193 /* IntersectionType */: + return some(node.types, mayResolveTypeAlias); + case 199 /* IndexedAccessType */: + return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); + case 194 /* ConditionalType */: + return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); + } + return false; + } + function getTypeFromArrayOrTupleTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const target = getArrayOrTupleTargetType(node); + if (target === emptyGenericType) { + links.resolvedType = emptyObjectType; + } else if (!(node.kind === 189 /* TupleType */ && some(node.elements, (e) => !!(getTupleElementFlags(e) & 8 /* Variadic */))) && isDeferredTypeReferenceNode(node)) { + links.resolvedType = node.kind === 189 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference( + target, + node, + /*mapper*/ + void 0 + ); + } else { + const elementTypes = node.kind === 188 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode); + links.resolvedType = createNormalizedTypeReference(target, elementTypes); + } + } + return links.resolvedType; + } + function isReadonlyTypeOperator(node) { + return isTypeOperatorNode(node) && node.operator === 148 /* ReadonlyKeyword */; + } + function createTupleType(elementTypes, elementFlags, readonly = false, namedMemberDeclarations = []) { + const tupleTarget = getTupleTargetType(elementFlags || map(elementTypes, (_) => 1 /* Required */), readonly, namedMemberDeclarations); + return tupleTarget === emptyGenericType ? emptyObjectType : elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) : tupleTarget; + } + function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) { + if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */) { + return readonly ? globalReadonlyArrayType : globalArrayType; + } + const key = map(elementFlags, (f) => f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*").join() + (readonly ? "R" : "") + (some(namedMemberDeclarations, (node) => !!node) ? "," + map(namedMemberDeclarations, (node) => node ? getNodeId(node) : "_").join(",") : ""); + let type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations)); + } + return type; + } + function createTupleTargetType(elementFlags, readonly, namedMemberDeclarations) { + const arity = elementFlags.length; + const minLength = countWhere(elementFlags, (f) => !!(f & (1 /* Required */ | 8 /* Variadic */))); + let typeParameters; + const properties = []; + let combinedFlags = 0; + if (arity) { + typeParameters = new Array(arity); + for (let i = 0; i < arity; i++) { + const typeParameter = typeParameters[i] = createTypeParameter(); + const flags = elementFlags[i]; + combinedFlags |= flags; + if (!(combinedFlags & 12 /* Variable */)) { + const property = createSymbol(4 /* Property */ | (flags & 2 /* Optional */ ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0); + property.links.tupleLabelDeclaration = namedMemberDeclarations == null ? void 0 : namedMemberDeclarations[i]; + property.links.type = typeParameter; + properties.push(property); + } + } + } + const fixedLength = properties.length; + const lengthSymbol = createSymbol(4 /* Property */, "length", readonly ? 8 /* Readonly */ : 0); + if (combinedFlags & 12 /* Variable */) { + lengthSymbol.links.type = numberType; + } else { + const literalTypes = []; + for (let i = minLength; i <= arity; i++) literalTypes.push(getNumberLiteralType(i)); + lengthSymbol.links.type = getUnionType(literalTypes); + } + properties.push(lengthSymbol); + const type = createObjectType(8 /* Tuple */ | 4 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = void 0; + type.localTypeParameters = typeParameters; + type.instantiations = /* @__PURE__ */ new Map(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.resolvedTypeArguments = type.typeParameters; + type.thisType = createTypeParameter(); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = emptyArray; + type.declaredConstructSignatures = emptyArray; + type.declaredIndexInfos = emptyArray; + type.elementFlags = elementFlags; + type.minLength = minLength; + type.fixedLength = fixedLength; + type.hasRestElement = !!(combinedFlags & 12 /* Variable */); + type.combinedFlags = combinedFlags; + type.readonly = readonly; + type.labeledElementDeclarations = namedMemberDeclarations; + return type; + } + function createNormalizedTypeReference(target, typeArguments) { + return target.objectFlags & 8 /* Tuple */ ? createNormalizedTupleType(target, typeArguments) : createTypeReference(target, typeArguments); + } + function createNormalizedTupleType(target, elementTypes) { + var _a, _b, _c, _d; + if (!(target.combinedFlags & 14 /* NonRequired */)) { + return createTypeReference(target, elementTypes); + } + if (target.combinedFlags & 8 /* Variadic */) { + const unionIndex = findIndex(elementTypes, (t, i) => !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */))); + if (unionIndex >= 0) { + return checkCrossProductUnion(map(elementTypes, (t, i) => target.elementFlags[i] & 8 /* Variadic */ ? t : unknownType)) ? mapType(elementTypes[unionIndex], (t) => createNormalizedTupleType(target, replaceElement(elementTypes, unionIndex, t))) : errorType; + } + } + const expandedTypes = []; + const expandedFlags = []; + const expandedDeclarations = []; + let lastRequiredIndex = -1; + let firstRestIndex = -1; + let lastOptionalOrRestIndex = -1; + for (let i = 0; i < elementTypes.length; i++) { + const type = elementTypes[i]; + const flags = target.elementFlags[i]; + if (flags & 8 /* Variadic */) { + if (type.flags & 1 /* Any */) { + addElement(type, 4 /* Rest */, (_a = target.labeledElementDeclarations) == null ? void 0 : _a[i]); + } else if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) { + addElement(type, 8 /* Variadic */, (_b = target.labeledElementDeclarations) == null ? void 0 : _b[i]); + } else if (isTupleType(type)) { + const elements = getElementTypes(type); + if (elements.length + expandedTypes.length >= 1e4) { + error( + currentNode, + isPartOfTypeNode(currentNode) ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent + ); + return errorType; + } + forEach(elements, (t, n) => { + var _a2; + return addElement(t, type.target.elementFlags[n], (_a2 = type.target.labeledElementDeclarations) == null ? void 0 : _a2[n]); + }); + } else { + addElement(isArrayLikeType(type) && getIndexTypeOfType(type, numberType) || errorType, 4 /* Rest */, (_c = target.labeledElementDeclarations) == null ? void 0 : _c[i]); + } + } else { + addElement(type, flags, (_d = target.labeledElementDeclarations) == null ? void 0 : _d[i]); + } + } + for (let i = 0; i < lastRequiredIndex; i++) { + if (expandedFlags[i] & 2 /* Optional */) expandedFlags[i] = 1 /* Required */; + } + if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) { + expandedTypes[firstRestIndex] = getUnionType(sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), (t, i) => expandedFlags[firstRestIndex + i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t)); + expandedTypes.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); + expandedFlags.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); + expandedDeclarations.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); + } + const tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations); + return tupleTarget === emptyGenericType ? emptyObjectType : expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) : tupleTarget; + function addElement(type, flags, declaration) { + if (flags & 1 /* Required */) { + lastRequiredIndex = expandedFlags.length; + } + if (flags & 4 /* Rest */ && firstRestIndex < 0) { + firstRestIndex = expandedFlags.length; + } + if (flags & (2 /* Optional */ | 4 /* Rest */)) { + lastOptionalOrRestIndex = expandedFlags.length; + } + expandedTypes.push(flags & 2 /* Optional */ ? addOptionality( + type, + /*isProperty*/ + true + ) : type); + expandedFlags.push(flags); + expandedDeclarations.push(declaration); + } + } + function sliceTupleType(type, index, endSkipCount = 0) { + const target = type.target; + const endIndex = getTypeReferenceArity(type) - endSkipCount; + return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(emptyArray) : createTupleType( + getTypeArguments(type).slice(index, endIndex), + target.elementFlags.slice(index, endIndex), + /*readonly*/ + false, + target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex) + ); + } + function getKnownKeysOfTupleType(type) { + return getUnionType(append(arrayOf(type.target.fixedLength, (i) => getStringLiteralType("" + i)), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType))); + } + function getStartElementCount(type, flags) { + const index = findIndex(type.elementFlags, (f) => !(f & flags)); + return index >= 0 ? index : type.elementFlags.length; + } + function getEndElementCount(type, flags) { + return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; + } + function getTotalFixedElementCount(type) { + return type.fixedLength + getEndElementCount(type, 3 /* Fixed */); + } + function getElementTypes(type) { + const typeArguments = getTypeArguments(type); + const arity = getTypeReferenceArity(type); + return typeArguments.length === arity ? typeArguments : typeArguments.slice(0, arity); + } + function getTypeFromOptionalTypeNode(node) { + return addOptionality( + getTypeFromTypeNode(node.type), + /*isProperty*/ + true + ); + } + function getTypeId(type) { + return type.id; + } + function containsType(types, type) { + return binarySearch(types, type, getTypeId, compareValues) >= 0; + } + function insertType(types, type) { + const index = binarySearch(types, type, getTypeId, compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } + function addTypeToUnion(typeSet, includes, type) { + const flags = type.flags; + if (!(flags & 131072 /* Never */)) { + includes |= flags & 473694207 /* IncludesMask */; + if (flags & 465829888 /* Instantiable */) includes |= 33554432 /* IncludesInstantiable */; + if (flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) includes |= 536870912 /* IncludesConstrainedTypeVariable */; + if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; + if (isErrorType(type)) includes |= 1073741824 /* IncludesError */; + if (!strictNullChecks && flags & 98304 /* Nullable */) { + if (!(getObjectFlags(type) & 65536 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; + } else { + const len = typeSet.length; + const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues); + if (index < 0) { + typeSet.splice(~index, 0, type); + } + } + } + return includes; + } + function addTypesToUnion(typeSet, includes, types) { + let lastType; + for (const type of types) { + if (type !== lastType) { + includes = type.flags & 1048576 /* Union */ ? addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? 1048576 /* Union */ : 0), type.types) : addTypeToUnion(typeSet, includes, type); + lastType = type; + } + } + return includes; + } + function removeSubtypes(types, hasObjectTypes) { + var _a; + if (types.length < 2) { + return types; + } + const id = getTypeListId(types); + const match = subtypeReductionCache.get(id); + if (match) { + return match; + } + const hasEmptyObject = hasObjectTypes && some(types, (t) => !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t))); + const len = types.length; + let i = len; + let count = 0; + while (i > 0) { + i--; + const source = types[i]; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + if (source.flags & 262144 /* TypeParameter */ && getBaseConstraintOrType(source).flags & 1048576 /* Union */) { + if (isTypeRelatedTo(source, getUnionType(map(types, (t) => t === source ? neverType : t)), strictSubtypeRelation)) { + orderedRemoveItemAt(types, i); + } + continue; + } + const keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? find(getPropertiesOfType(source), (p) => isUnitType(getTypeOfSymbol(p))) : void 0; + const keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty)); + for (const target of types) { + if (source !== target) { + if (count === 1e5) { + const estimatedCount = count / (len - i) * len; + if (estimatedCount > 1e6) { + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "removeSubtypes_DepthLimit", { typeIds: types.map((t) => t.id) }); + error(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return void 0; + } + } + count++; + if (keyProperty && target.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + const t = getTypeOfPropertyOfType(target, keyProperty.escapedName); + if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) { + continue; + } + } + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(getObjectFlags(getTargetType(source)) & 1 /* Class */) || !(getObjectFlags(getTargetType(target)) & 1 /* Class */) || isTypeDerivedFrom(source, target))) { + orderedRemoveItemAt(types, i); + break; + } + } + } + } + } + subtypeReductionCache.set(id, types); + return types; + } + function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) { + let i = types.length; + while (i > 0) { + i--; + const t = types[i]; + const flags = t.flags; + const remove = flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && includes & 4 /* String */ || flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); + if (remove) { + orderedRemoveItemAt(types, i); + } + } + } + function removeStringLiteralsMatchedByTemplateLiterals(types) { + const templates = filter(types, isPatternLiteralType); + if (templates.length) { + let i = types.length; + while (i > 0) { + i--; + const t = types[i]; + if (t.flags & 128 /* StringLiteral */ && some(templates, (template) => isTypeMatchedByTemplateLiteralOrStringMapping(t, template))) { + orderedRemoveItemAt(types, i); + } + } + } + } + function isTypeMatchedByTemplateLiteralOrStringMapping(type, template) { + return template.flags & 134217728 /* TemplateLiteral */ ? isTypeMatchedByTemplateLiteralType(type, template) : isMemberOfStringMapping(type, template); + } + function removeConstrainedTypeVariables(types) { + const typeVariables = []; + for (const type of types) { + if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) { + const index = type.types[0].flags & 8650752 /* TypeVariable */ ? 0 : 1; + pushIfUnique(typeVariables, type.types[index]); + } + } + for (const typeVariable of typeVariables) { + const primitives = []; + for (const type of types) { + if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) { + const index = type.types[0].flags & 8650752 /* TypeVariable */ ? 0 : 1; + if (type.types[index] === typeVariable) { + insertType(primitives, type.types[1 - index]); + } + } + } + const constraint = getBaseConstraintOfType(typeVariable); + if (everyType(constraint, (t) => containsType(primitives, t))) { + let i = types.length; + while (i > 0) { + i--; + const type = types[i]; + if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) { + const index = type.types[0].flags & 8650752 /* TypeVariable */ ? 0 : 1; + if (type.types[index] === typeVariable && containsType(primitives, type.types[1 - index])) { + orderedRemoveItemAt(types, i); + } + } + } + insertType(types, typeVariable); + } + } + } + function isNamedUnionType(type) { + return !!(type.flags & 1048576 /* Union */ && (type.aliasSymbol || type.origin)); + } + function addNamedUnions(namedUnions, types) { + for (const t of types) { + if (t.flags & 1048576 /* Union */) { + const origin = t.origin; + if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) { + pushIfUnique(namedUnions, t); + } else if (origin && origin.flags & 1048576 /* Union */) { + addNamedUnions(namedUnions, origin.types); + } + } + } + } + function createOriginUnionOrIntersectionType(flags, types) { + const result = createOriginType(flags); + result.types = types; + return result; + } + function getUnionType(types, unionReduction = 1 /* Literal */, aliasSymbol, aliasTypeArguments, origin) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + if (types.length === 2 && !origin && (types[0].flags & 1048576 /* Union */ || types[1].flags & 1048576 /* Union */)) { + const infix = unionReduction === 0 /* None */ ? "N" : unionReduction === 2 /* Subtype */ ? "S" : "L"; + const index = types[0].id < types[1].id ? 0 : 1; + const id = types[index].id + infix + types[1 - index].id + getAliasId(aliasSymbol, aliasTypeArguments); + let type = unionOfUnionTypes.get(id); + if (!type) { + type = getUnionTypeWorker( + types, + unionReduction, + aliasSymbol, + aliasTypeArguments, + /*origin*/ + void 0 + ); + unionOfUnionTypes.set(id, type); + } + return type; + } + return getUnionTypeWorker(types, unionReduction, aliasSymbol, aliasTypeArguments, origin); + } + function getUnionTypeWorker(types, unionReduction, aliasSymbol, aliasTypeArguments, origin) { + let typeSet = []; + const includes = addTypesToUnion(typeSet, 0, types); + if (unionReduction !== 0 /* None */) { + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : includes & 1073741824 /* IncludesError */ ? errorType : anyType : unknownType; + } + if (includes & 32768 /* Undefined */) { + if (typeSet.length >= 2 && typeSet[0] === undefinedType && typeSet[1] === missingType) { + orderedRemoveItemAt(typeSet, 1); + } + } + if (includes & (32 /* Enum */ | 2944 /* Literal */ | 8192 /* UniqueESSymbol */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */)); + } + if (includes & 128 /* StringLiteral */ && includes & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + if (includes & 536870912 /* IncludesConstrainedTypeVariable */) { + removeConstrainedTypeVariables(typeSet); + } + if (unionReduction === 2 /* Subtype */) { + typeSet = removeSubtypes(typeSet, !!(includes & 524288 /* Object */)); + if (!typeSet) { + return errorType; + } + } + if (typeSet.length === 0) { + return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : neverType; + } + } + if (!origin && includes & 1048576 /* Union */) { + const namedUnions = []; + addNamedUnions(namedUnions, types); + const reducedTypes = []; + for (const t of typeSet) { + if (!some(namedUnions, (union) => containsType(union.types, t))) { + reducedTypes.push(t); + } + } + if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) { + return namedUnions[0]; + } + const namedTypesCount = reduceLeft(namedUnions, (sum, union) => sum + union.types.length, 0); + if (namedTypesCount + reducedTypes.length === typeSet.length) { + for (const t of namedUnions) { + insertType(reducedTypes, t); + } + origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); + } + } + const objectFlags = (includes & 36323331 /* NotPrimitiveUnion */ ? 0 : 32768 /* PrimitiveUnion */) | (includes & 2097152 /* Intersection */ ? 16777216 /* ContainsIntersections */ : 0); + return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); + } + function getUnionOrIntersectionTypePredicate(signatures, kind) { + let last2; + const types = []; + for (const sig of signatures) { + const pred = getTypePredicateOfSignature(sig); + if (pred) { + if (pred.kind !== 0 /* This */ && pred.kind !== 1 /* Identifier */ || last2 && !typePredicateKindsMatch(last2, pred)) { + return void 0; + } + last2 = pred; + types.push(pred.type); + } else { + const returnType = kind !== 2097152 /* Intersection */ ? getReturnTypeOfSignature(sig) : void 0; + if (returnType !== falseType && returnType !== regularFalseType) { + return void 0; + } + } + } + if (!last2) { + return void 0; + } + const compositeType = getUnionOrIntersectionType(types, kind); + return createTypePredicate(last2.kind, last2.parameterName, last2.parameterIndex, compositeType); + } + function typePredicateKindsMatch(a, b) { + return a.kind === b.kind && a.parameterIndex === b.parameterIndex; + } + function getUnionTypeFromSortedList(types, precomputedObjectFlags, aliasSymbol, aliasTypeArguments, origin) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + const typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? `|${getTypeListId(origin.types)}` : origin.flags & 2097152 /* Intersection */ ? `&${getTypeListId(origin.types)}` : `#${origin.type.id}|${getTypeListId(types)}`; + const id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); + let type = unionTypes.get(id); + if (!type) { + type = createType(1048576 /* Union */); + type.objectFlags = precomputedObjectFlags | getPropagatingFlagsOfTypes( + types, + /*excludeKinds*/ + 98304 /* Nullable */ + ); + type.types = types; + type.origin = origin; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + if (types.length === 2 && types[0].flags & 512 /* BooleanLiteral */ && types[1].flags & 512 /* BooleanLiteral */) { + type.flags |= 16 /* Boolean */; + type.intrinsicName = "boolean"; + } + unionTypes.set(id, type); + } + return type; + } + function getTypeFromUnionTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, includes, type) { + const flags = type.flags; + if (flags & 2097152 /* Intersection */) { + return addTypesToIntersection(typeSet, includes, type.types); + } + if (isEmptyAnonymousObjectType(type)) { + if (!(includes & 16777216 /* IncludesEmptyObject */)) { + includes |= 16777216 /* IncludesEmptyObject */; + typeSet.set(type.id.toString(), type); + } + } else { + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; + if (isErrorType(type)) includes |= 1073741824 /* IncludesError */; + } else if (strictNullChecks || !(flags & 98304 /* Nullable */)) { + if (type === missingType) { + includes |= 262144 /* IncludesMissingType */; + type = undefinedType; + } + if (!typeSet.has(type.id.toString())) { + if (type.flags & 109472 /* Unit */ && includes & 109472 /* Unit */) { + includes |= 67108864 /* NonPrimitive */; + } + typeSet.set(type.id.toString(), type); + } + } + includes |= flags & 473694207 /* IncludesMask */; + } + return includes; + } + function addTypesToIntersection(typeSet, includes, types) { + for (const type of types) { + includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); + } + return includes; + } + function removeRedundantSupertypes(types, includes) { + let i = types.length; + while (i > 0) { + i--; + const t = types[i]; + const remove = t.flags & 4 /* String */ && includes & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ || t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */ || t.flags & 16384 /* Void */ && includes & 32768 /* Undefined */ || isEmptyAnonymousObjectType(t) && includes & 470302716 /* DefinitelyNonNullable */; + if (remove) { + orderedRemoveItemAt(types, i); + } + } + } + function eachUnionContains(unionTypes2, type) { + for (const u of unionTypes2) { + if (!containsType(u.types, type)) { + if (type === missingType) { + return containsType(u.types, undefinedType); + } + if (type === undefinedType) { + return containsType(u.types, missingType); + } + const primitive = type.flags & 128 /* StringLiteral */ ? stringType : type.flags & (32 /* Enum */ | 256 /* NumberLiteral */) ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : void 0; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + function extractRedundantTemplateLiterals(types) { + let i = types.length; + const literals = filter(types, (t) => !!(t.flags & 128 /* StringLiteral */)); + while (i > 0) { + i--; + const t = types[i]; + if (!(t.flags & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */))) continue; + for (const t2 of literals) { + if (isTypeSubtypeOf(t2, t)) { + orderedRemoveItemAt(types, i); + break; + } else if (isPatternLiteralType(t)) { + return true; + } + } + } + return false; + } + function removeFromEach(types, flag) { + for (let i = 0; i < types.length; i++) { + types[i] = filterType(types[i], (t) => !(t.flags & flag)); + } + } + function intersectUnionsOfPrimitiveTypes(types) { + let unionTypes2; + const index = findIndex(types, (t) => !!(getObjectFlags(t) & 32768 /* PrimitiveUnion */)); + if (index < 0) { + return false; + } + let i = index + 1; + while (i < types.length) { + const t = types[i]; + if (getObjectFlags(t) & 32768 /* PrimitiveUnion */) { + (unionTypes2 || (unionTypes2 = [types[index]])).push(t); + orderedRemoveItemAt(types, i); + } else { + i++; + } + } + if (!unionTypes2) { + return false; + } + const checked = []; + const result = []; + for (const u of unionTypes2) { + for (const t of u.types) { + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes2, t)) { + if (t === undefinedType && result.length && result[0] === missingType) { + continue; + } + if (t === missingType && result.length && result[0] === undefinedType) { + result[0] = missingType; + continue; + } + insertType(result, t); + } + } + } + } + types[index] = getUnionTypeFromSortedList(result, 32768 /* PrimitiveUnion */); + return true; + } + function createIntersectionType(types, objectFlags, aliasSymbol, aliasTypeArguments) { + const result = createType(2097152 /* Intersection */); + result.objectFlags = objectFlags | getPropagatingFlagsOfTypes( + types, + /*excludeKinds*/ + 98304 /* Nullable */ + ); + result.types = types; + result.aliasSymbol = aliasSymbol; + result.aliasTypeArguments = aliasTypeArguments; + return result; + } + function getIntersectionType(types, flags = 0 /* None */, aliasSymbol, aliasTypeArguments) { + const typeMembershipMap = /* @__PURE__ */ new Map(); + const includes = addTypesToIntersection(typeMembershipMap, 0, types); + const typeSet = arrayFrom(typeMembershipMap.values()); + let objectFlags = 0 /* None */; + if (includes & 131072 /* Never */) { + return contains(typeSet, silentNeverType) ? silentNeverType : neverType; + } + if (strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) || includes & 67108864 /* NonPrimitive */ && includes & (469892092 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || includes & 402653316 /* StringLike */ && includes & (469892092 /* DisjointDomains */ & ~402653316 /* StringLike */) || includes & 296 /* NumberLike */ && includes & (469892092 /* DisjointDomains */ & ~296 /* NumberLike */) || includes & 2112 /* BigIntLike */ && includes & (469892092 /* DisjointDomains */ & ~2112 /* BigIntLike */) || includes & 12288 /* ESSymbolLike */ && includes & (469892092 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) || includes & 49152 /* VoidLike */ && includes & (469892092 /* DisjointDomains */ & ~49152 /* VoidLike */)) { + return neverType; + } + if (includes & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && includes & 128 /* StringLiteral */ && extractRedundantTemplateLiterals(typeSet)) { + return neverType; + } + if (includes & 1 /* Any */) { + return includes & 8388608 /* IncludesWildcard */ ? wildcardType : includes & 1073741824 /* IncludesError */ ? errorType : anyType; + } + if (!strictNullChecks && includes & 98304 /* Nullable */) { + return includes & 16777216 /* IncludesEmptyObject */ ? neverType : includes & 32768 /* Undefined */ ? undefinedType : nullType; + } + if (includes & 4 /* String */ && includes & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */ || includes & 16384 /* Void */ && includes & 32768 /* Undefined */ || includes & 16777216 /* IncludesEmptyObject */ && includes & 470302716 /* DefinitelyNonNullable */) { + if (!(flags & 1 /* NoSupertypeReduction */)) removeRedundantSupertypes(typeSet, includes); + } + if (includes & 262144 /* IncludesMissingType */) { + typeSet[typeSet.indexOf(undefinedType)] = missingType; + } + if (typeSet.length === 0) { + return unknownType; + } + if (typeSet.length === 1) { + return typeSet[0]; + } + if (typeSet.length === 2 && !(flags & 2 /* NoConstraintReduction */)) { + const typeVarIndex = typeSet[0].flags & 8650752 /* TypeVariable */ ? 0 : 1; + const typeVariable = typeSet[typeVarIndex]; + const primitiveType = typeSet[1 - typeVarIndex]; + if (typeVariable.flags & 8650752 /* TypeVariable */ && (primitiveType.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */) && !isGenericStringLikeType(primitiveType) || includes & 16777216 /* IncludesEmptyObject */)) { + const constraint = getBaseConstraintOfType(typeVariable); + if (constraint && everyType(constraint, (t) => !!(t.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */)) || isEmptyAnonymousObjectType(t))) { + if (isTypeStrictSubtypeOf(constraint, primitiveType)) { + return typeVariable; + } + if (!(constraint.flags & 1048576 /* Union */ && someType(constraint, (c) => isTypeStrictSubtypeOf(c, primitiveType)))) { + if (!isTypeStrictSubtypeOf(primitiveType, constraint)) { + return neverType; + } + } + objectFlags = 67108864 /* IsConstrainedTypeVariable */; + } + } + } + const id = getTypeListId(typeSet) + (flags & 2 /* NoConstraintReduction */ ? "*" : getAliasId(aliasSymbol, aliasTypeArguments)); + let result = intersectionTypes.get(id); + if (!result) { + if (includes & 1048576 /* Union */) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { + result = getIntersectionType(typeSet, flags, aliasSymbol, aliasTypeArguments); + } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && t.types[0].flags & 32768 /* Undefined */))) { + const containedUndefinedType = some(typeSet, containsMissingType) ? missingType : undefinedType; + removeFromEach(typeSet, 32768 /* Undefined */); + result = getUnionType([getIntersectionType(typeSet, flags), containedUndefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); + } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && (t.types[0].flags & 65536 /* Null */ || t.types[1].flags & 65536 /* Null */)))) { + removeFromEach(typeSet, 65536 /* Null */); + result = getUnionType([getIntersectionType(typeSet, flags), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); + } else if (typeSet.length >= 3 && types.length > 2) { + const middle = Math.floor(typeSet.length / 2); + result = getIntersectionType([getIntersectionType(typeSet.slice(0, middle), flags), getIntersectionType(typeSet.slice(middle), flags)], flags, aliasSymbol, aliasTypeArguments); + } else { + if (!checkCrossProductUnion(typeSet)) { + return errorType; + } + const constituents = getCrossProductIntersections(typeSet, flags); + const origin = some(constituents, (t) => !!(t.flags & 2097152 /* Intersection */)) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* Intersection */, typeSet) : void 0; + result = getUnionType(constituents, 1 /* Literal */, aliasSymbol, aliasTypeArguments, origin); + } + } else { + result = createIntersectionType(typeSet, objectFlags, aliasSymbol, aliasTypeArguments); + } + intersectionTypes.set(id, result); + } + return result; + } + function getCrossProductUnionSize(types) { + return reduceLeft(types, (n, t) => t.flags & 1048576 /* Union */ ? n * t.types.length : t.flags & 131072 /* Never */ ? 0 : n, 1); + } + function checkCrossProductUnion(types) { + var _a; + const size = getCrossProductUnionSize(types); + if (size >= 1e5) { + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "checkCrossProductUnion_DepthLimit", { typeIds: types.map((t) => t.id), size }); + error(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return false; + } + return true; + } + function getCrossProductIntersections(types, flags) { + const count = getCrossProductUnionSize(types); + const intersections = []; + for (let i = 0; i < count; i++) { + const constituents = types.slice(); + let n = i; + for (let j = types.length - 1; j >= 0; j--) { + if (types[j].flags & 1048576 /* Union */) { + const sourceTypes = types[j].types; + const length2 = sourceTypes.length; + constituents[j] = sourceTypes[n % length2]; + n = Math.floor(n / length2); + } + } + const t = getIntersectionType(constituents, flags); + if (!(t.flags & 131072 /* Never */)) intersections.push(t); + } + return intersections; + } + function getConstituentCount(type) { + return !(type.flags & 3145728 /* UnionOrIntersection */) || type.aliasSymbol ? 1 : type.flags & 1048576 /* Union */ && type.origin ? getConstituentCount(type.origin) : getConstituentCountOfTypes(type.types); + } + function getConstituentCountOfTypes(types) { + return reduceLeft(types, (n, t) => n + getConstituentCount(t), 0); + } + function getTypeFromIntersectionTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const aliasSymbol = getAliasSymbolForTypeNode(node); + const types = map(node.types, getTypeFromTypeNode); + const emptyIndex = types.length === 2 ? types.indexOf(emptyTypeLiteralType) : -1; + const t = emptyIndex >= 0 ? types[1 - emptyIndex] : unknownType; + const noSupertypeReduction = !!(t.flags & (4 /* String */ | 8 /* Number */ | 64 /* BigInt */) || t.flags & 134217728 /* TemplateLiteral */ && isPatternLiteralType(t)); + links.resolvedType = getIntersectionType(types, noSupertypeReduction ? 1 /* NoSupertypeReduction */ : 0, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + } + return links.resolvedType; + } + function createIndexType(type, indexFlags) { + const result = createType(4194304 /* Index */); + result.type = type; + result.indexFlags = indexFlags; + return result; + } + function createOriginIndexType(type) { + const result = createOriginType(4194304 /* Index */); + result.type = type; + return result; + } + function getIndexTypeForGenericType(type, indexFlags) { + return indexFlags & 1 /* StringsOnly */ ? type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, 1 /* StringsOnly */)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, 0 /* None */)); + } + function getIndexTypeForMappedType(type, indexFlags) { + const typeParameter = getTypeParameterFromMappedType(type); + const constraintType = getConstraintTypeFromMappedType(type); + const nameType = getNameTypeFromMappedType(type.target || type); + if (!nameType && !(indexFlags & 2 /* NoIndexSignatures */)) { + return constraintType; + } + const keyTypes = []; + if (isGenericIndexType(constraintType)) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + return getIndexTypeForGenericType(type, indexFlags); + } + forEachType(constraintType, addMemberForKeyType); + } else if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + const modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(modifiersType, 8576 /* StringOrNumberLiteralOrUnique */, !!(indexFlags & 1 /* StringsOnly */), addMemberForKeyType); + } else { + forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); + } + const result = indexFlags & 2 /* NoIndexSignatures */ ? filterType(getUnionType(keyTypes), (t) => !(t.flags & (1 /* Any */ | 4 /* String */))) : getUnionType(keyTypes); + if (result.flags & 1048576 /* Union */ && constraintType.flags & 1048576 /* Union */ && getTypeListId(result.types) === getTypeListId(constraintType.types)) { + return constraintType; + } + return result; + function addMemberForKeyType(keyType) { + const propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType; + keyTypes.push(propNameType === stringType ? stringOrNumberType : propNameType); + } + } + function hasDistributiveNameType(mappedType) { + const typeVariable = getTypeParameterFromMappedType(mappedType); + return isDistributive(getNameTypeFromMappedType(mappedType) || typeVariable); + function isDistributive(type) { + return type.flags & (3 /* AnyOrUnknown */ | 402784252 /* Primitive */ | 131072 /* Never */ | 262144 /* TypeParameter */ | 524288 /* Object */ | 67108864 /* NonPrimitive */) ? true : type.flags & 16777216 /* Conditional */ ? type.root.isDistributive && type.checkType === typeVariable : type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */) ? every(type.types, isDistributive) : type.flags & 8388608 /* IndexedAccess */ ? isDistributive(type.objectType) && isDistributive(type.indexType) : type.flags & 33554432 /* Substitution */ ? isDistributive(type.baseType) && isDistributive(type.constraint) : type.flags & 268435456 /* StringMapping */ ? isDistributive(type.type) : false; + } + } + function getLiteralTypeFromPropertyName(name) { + if (isPrivateIdentifier(name)) { + return neverType; + } + if (isNumericLiteral(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + if (isComputedPropertyName(name)) { + return getRegularTypeOfLiteralType(checkComputedPropertyName(name)); + } + const propertyName = getPropertyNameForPropertyNameNode(name); + if (propertyName !== void 0) { + return getStringLiteralType(unescapeLeadingUnderscores(propertyName)); + } + if (isExpression(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + return neverType; + } + function getLiteralTypeFromProperty(prop, include, includeNonPublic) { + if (includeNonPublic || !(getDeclarationModifierFlagsFromSymbol(prop) & 6 /* NonPublicAccessibilityModifier */)) { + let type = getSymbolLinks(getLateBoundSymbol(prop)).nameType; + if (!type) { + const name = getNameOfDeclaration(prop.valueDeclaration); + type = prop.escapedName === "default" /* Default */ ? getStringLiteralType("default") : name && getLiteralTypeFromPropertyName(name) || (!isKnownSymbol(prop) ? getStringLiteralType(symbolName(prop)) : void 0); + } + if (type && type.flags & include) { + return type; + } + } + return neverType; + } + function isKeyTypeIncluded(keyType, include) { + return !!(keyType.flags & include || keyType.flags & 2097152 /* Intersection */ && some(keyType.types, (t) => isKeyTypeIncluded(t, include))); + } + function getLiteralTypeFromProperties(type, include, includeOrigin) { + const origin = includeOrigin && (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */) || type.aliasSymbol) ? createOriginIndexType(type) : void 0; + const propertyTypes = map(getPropertiesOfType(type), (prop) => getLiteralTypeFromProperty(prop, include)); + const indexKeyTypes = map(getIndexInfosOfType(type), (info) => info !== enumNumberIndexInfo && isKeyTypeIncluded(info.keyType, include) ? info.keyType === stringType && include & 8 /* Number */ ? stringOrNumberType : info.keyType : neverType); + return getUnionType( + concatenate(propertyTypes, indexKeyTypes), + 1 /* Literal */, + /*aliasSymbol*/ + void 0, + /*aliasTypeArguments*/ + void 0, + origin + ); + } + function shouldDeferIndexType(type, indexFlags = 0 /* None */) { + return !!(type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && (!hasDistributiveNameType(type) || getMappedTypeNameTypeKind(type) === 2 /* Remapping */) || type.flags & 1048576 /* Union */ && !(indexFlags & 4 /* NoReducibleCheck */) && isGenericReducibleType(type) || type.flags & 2097152 /* Intersection */ && maybeTypeOfKind(type, 465829888 /* Instantiable */) && some(type.types, isEmptyAnonymousObjectType)); + } + function getIndexType(type, indexFlags = 0 /* None */) { + type = getReducedType(type); + return isNoInferType(type) ? getNoInferType(getIndexType(type.baseType, indexFlags)) : shouldDeferIndexType(type, indexFlags) ? getIndexTypeForGenericType(type, indexFlags) : type.flags & 1048576 /* Union */ ? getIntersectionType(map(type.types, (t) => getIndexType(t, indexFlags))) : type.flags & 2097152 /* Intersection */ ? getUnionType(map(type.types, (t) => getIndexType(t, indexFlags))) : getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, indexFlags) : type === wildcardType ? wildcardType : type.flags & 2 /* Unknown */ ? neverType : type.flags & (1 /* Any */ | 131072 /* Never */) ? stringNumberSymbolType : getLiteralTypeFromProperties(type, (indexFlags & 2 /* NoIndexSignatures */ ? 128 /* StringLiteral */ : 402653316 /* StringLike */) | (indexFlags & 1 /* StringsOnly */ ? 0 : 296 /* NumberLike */ | 12288 /* ESSymbolLike */), indexFlags === 0 /* None */); + } + function getExtractStringType(type) { + const extractTypeAlias = getGlobalExtractSymbol(); + return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType; + } + function getIndexTypeOrString(type) { + const indexType = getExtractStringType(getIndexType(type)); + return indexType.flags & 131072 /* Never */ ? stringType : indexType; + } + function getTypeFromTypeOperatorNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + switch (node.operator) { + case 143 /* KeyOfKeyword */: + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + break; + case 158 /* UniqueKeyword */: + links.resolvedType = node.type.kind === 155 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(walkUpParenthesizedTypes(node.parent)) : errorType; + break; + case 148 /* ReadonlyKeyword */: + links.resolvedType = getTypeFromTypeNode(node.type); + break; + default: + Debug.assertNever(node.operator); + } + } + return links.resolvedType; + } + function getTypeFromTemplateTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getTemplateLiteralType( + [node.head.text, ...map(node.templateSpans, (span) => span.literal.text)], + map(node.templateSpans, (span) => getTypeFromTypeNode(span.type)) + ); + } + return links.resolvedType; + } + function getTemplateLiteralType(texts, types) { + const unionIndex = findIndex(types, (t) => !!(t.flags & (131072 /* Never */ | 1048576 /* Union */))); + if (unionIndex >= 0) { + return checkCrossProductUnion(types) ? mapType(types[unionIndex], (t) => getTemplateLiteralType(texts, replaceElement(types, unionIndex, t))) : errorType; + } + if (contains(types, wildcardType)) { + return wildcardType; + } + const newTypes = []; + const newTexts = []; + let text = texts[0]; + if (!addSpans(texts, types)) { + return stringType; + } + if (newTypes.length === 0) { + return getStringLiteralType(text); + } + newTexts.push(text); + if (every(newTexts, (t) => t === "")) { + if (every(newTypes, (t) => !!(t.flags & 4 /* String */))) { + return stringType; + } + if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) { + return newTypes[0]; + } + } + const id = `${getTypeListId(newTypes)}|${map(newTexts, (t) => t.length).join(",")}|${newTexts.join("")}`; + let type = templateLiteralTypes.get(id); + if (!type) { + templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); + } + return type; + function addSpans(texts2, types2) { + for (let i = 0; i < types2.length; i++) { + const t = types2[i]; + if (t.flags & (2944 /* Literal */ | 65536 /* Null */ | 32768 /* Undefined */)) { + text += getTemplateStringForType(t) || ""; + text += texts2[i + 1]; + } else if (t.flags & 134217728 /* TemplateLiteral */) { + text += t.texts[0]; + if (!addSpans(t.texts, t.types)) return false; + text += texts2[i + 1]; + } else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) { + newTypes.push(t); + newTexts.push(text); + text = texts2[i + 1]; + } else { + return false; + } + } + return true; + } + } + function getTemplateStringForType(type) { + return type.flags & 128 /* StringLiteral */ ? type.value : type.flags & 256 /* NumberLiteral */ ? "" + type.value : type.flags & 2048 /* BigIntLiteral */ ? pseudoBigIntToString(type.value) : type.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) ? type.intrinsicName : void 0; + } + function createTemplateLiteralType(texts, types) { + const type = createType(134217728 /* TemplateLiteral */); + type.texts = texts; + type.types = types; + return type; + } + function getStringMappingType(symbol, type) { + return type.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapType(type, (t) => getStringMappingType(symbol, t)) : type.flags & 128 /* StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : type.flags & 134217728 /* TemplateLiteral */ ? getTemplateLiteralType(...applyTemplateStringMapping(symbol, type.texts, type.types)) : ( + // Mapping> === Mapping + type.flags & 268435456 /* StringMapping */ && symbol === type.symbol ? type : type.flags & (1 /* Any */ | 4 /* String */ | 268435456 /* StringMapping */) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : ( + // This handles Mapping<`${number}`> and Mapping<`${bigint}`> + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : type + ) + ); + } + function applyStringMapping(symbol, str) { + switch (intrinsicTypeKinds.get(symbol.escapedName)) { + case 0 /* Uppercase */: + return str.toUpperCase(); + case 1 /* Lowercase */: + return str.toLowerCase(); + case 2 /* Capitalize */: + return str.charAt(0).toUpperCase() + str.slice(1); + case 3 /* Uncapitalize */: + return str.charAt(0).toLowerCase() + str.slice(1); + } + return str; + } + function applyTemplateStringMapping(symbol, texts, types) { + switch (intrinsicTypeKinds.get(symbol.escapedName)) { + case 0 /* Uppercase */: + return [texts.map((t) => t.toUpperCase()), types.map((t) => getStringMappingType(symbol, t))]; + case 1 /* Lowercase */: + return [texts.map((t) => t.toLowerCase()), types.map((t) => getStringMappingType(symbol, t))]; + case 2 /* Capitalize */: + return [texts[0] === "" ? texts : [texts[0].charAt(0).toUpperCase() + texts[0].slice(1), ...texts.slice(1)], texts[0] === "" ? [getStringMappingType(symbol, types[0]), ...types.slice(1)] : types]; + case 3 /* Uncapitalize */: + return [texts[0] === "" ? texts : [texts[0].charAt(0).toLowerCase() + texts[0].slice(1), ...texts.slice(1)], texts[0] === "" ? [getStringMappingType(symbol, types[0]), ...types.slice(1)] : types]; + } + return [texts, types]; + } + function getStringMappingTypeForGenericType(symbol, type) { + const id = `${getSymbolId(symbol)},${getTypeId(type)}`; + let result = stringMappingTypes.get(id); + if (!result) { + stringMappingTypes.set(id, result = createStringMappingType(symbol, type)); + } + return result; + } + function createStringMappingType(symbol, type) { + const result = createTypeWithSymbol(268435456 /* StringMapping */, symbol); + result.type = type; + return result; + } + function createIndexedAccessType(objectType, indexType, accessFlags, aliasSymbol, aliasTypeArguments) { + const type = createType(8388608 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + type.accessFlags = accessFlags; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + return type; + } + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; + } + if (getObjectFlags(type) & 4096 /* JSLiteral */) { + return true; + } + if (type.flags & 1048576 /* Union */) { + return every(type.types, isJSLiteralType); + } + if (type.flags & 2097152 /* Intersection */) { + return some(type.types, isJSLiteralType); + } + if (type.flags & 465829888 /* Instantiable */) { + const constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); + } + return false; + } + function getPropertyNameFromIndex(indexType, accessNode) { + return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : accessNode && isPropertyName(accessNode) ? ( + // late bound names are handled in the first branch, so here we only need to handle normal names + getPropertyNameForPropertyNameNode(accessNode) + ) : void 0; + } + function isUncalledFunctionReference(node, symbol) { + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + const parent = findAncestor(node.parent, (n) => !isAccessExpression(n)) || node.parent; + if (isCallLikeExpression(parent)) { + return isCallOrNewExpression(parent) && isIdentifier(node) && hasMatchingArgument(parent, node); + } + return every(symbol.declarations, (d) => !isFunctionLike(d) || isDeprecatedDeclaration(d)); + } + return true; + } + function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, accessNode, accessFlags) { + const accessExpression = accessNode && accessNode.kind === 212 /* ElementAccessExpression */ ? accessNode : void 0; + const propName = accessNode && isPrivateIdentifier(accessNode) ? void 0 : getPropertyNameFromIndex(indexType, accessNode); + if (propName !== void 0) { + if (accessFlags & 256 /* Contextual */) { + return getTypeOfPropertyOfContextualType(objectType, propName) || anyType; + } + const prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessFlags & 64 /* ReportDeprecated */ && accessNode && prop.declarations && isDeprecatedSymbol(prop) && isUncalledFunctionReference(accessNode, prop)) { + const deprecatedNode = (accessExpression == null ? void 0 : accessExpression.argumentExpression) ?? (isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); + } + if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol)); + if (isAssignmentToReadonlyEntity(accessExpression, prop, getAssignmentTargetKind(accessExpression))) { + error(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); + return void 0; + } + if (accessFlags & 8 /* CacheSymbol */) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + if (isThisPropertyAccessInConstructor(accessExpression, prop)) { + return autoType; + } + } + const propType = accessFlags & 4 /* Writing */ ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop); + return accessExpression && getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? getFlowTypeOfReference(accessExpression, propType) : accessNode && isIndexedAccessTypeNode(accessNode) && containsMissingType(propType) ? getUnionType([propType, undefinedType]) : propType; + } + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName)) { + const index = +propName; + if (accessNode && everyType(objectType, (t) => !(t.target.combinedFlags & 12 /* Variable */)) && !(accessFlags & 16 /* AllowMissing */)) { + const indexNode = getIndexNodeForAccessExpression(accessNode); + if (isTupleType(objectType)) { + if (index < 0) { + error(indexNode, Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); + return undefinedType; + } + error(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName)); + } else { + error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + } + if (index >= 0) { + errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); + return getTupleElementTypeOutOfStartCount(objectType, index, accessFlags & 1 /* IncludeUndefined */ ? missingType : void 0); + } + } + } + if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) { + if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) { + return objectType; + } + const indexInfo = getApplicableIndexInfo(objectType, indexType) || getIndexInfoOfType(objectType, stringType); + if (indexInfo) { + if (accessFlags & 2 /* NoIndexSignatures */ && indexInfo.keyType !== numberType) { + if (accessExpression) { + if (accessFlags & 4 /* Writing */) { + error(accessExpression, Diagnostics.Type_0_is_generic_and_can_only_be_indexed_for_reading, typeToString(originalObjectType)); + } else { + error(accessExpression, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType)); + } + } + return void 0; + } + if (accessNode && indexInfo.keyType === stringType && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { + const indexNode = getIndexNodeForAccessExpression(accessNode); + error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([indexInfo.type, missingType]) : indexInfo.type; + } + errorIfWritingToReadonlyIndex(indexInfo); + if (accessFlags & 1 /* IncludeUndefined */ && !(objectType.symbol && objectType.symbol.flags & (256 /* RegularEnum */ | 128 /* ConstEnum */) && (indexType.symbol && indexType.flags & 1024 /* EnumLiteral */ && getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + return getUnionType([indexInfo.type, missingType]); + } + return indexInfo.type; + } + if (indexType.flags & 131072 /* Never */) { + return neverType; + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (isObjectLiteralType(objectType)) { + if (noImplicitAny && indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + diagnostics.add(createDiagnosticForNode(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType))); + return undefinedType; + } else if (indexType.flags & (8 /* Number */ | 4 /* String */)) { + const types = map(objectType.properties, (property) => { + return getTypeOfSymbol(property); + }); + return getUnionType(append(types, undefinedType)); + } + } + if (objectType.symbol === globalThisSymbol && propName !== void 0 && globalThisSymbol.exports.has(propName) && globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */) { + error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); + } else if (noImplicitAny && !(accessFlags & 128 /* SuppressNoImplicitAnyError */)) { + if (propName !== void 0 && typeHasStaticProperty(propName, objectType)) { + const typeName = typeToString(objectType); + error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "[" + getTextOfNode(accessExpression.argumentExpression) + "]"); + } else if (getIndexTypeOfType(objectType, numberType)) { + error(accessExpression.argumentExpression, Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } else { + let suggestion; + if (propName !== void 0 && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== void 0) { + error(accessExpression.argumentExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } else { + const suggestion2 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType); + if (suggestion2 !== void 0) { + error(accessExpression, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1, typeToString(objectType), suggestion2); + } else { + let errorInfo; + if (indexType.flags & 1024 /* EnumLiteral */) { + errorInfo = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Property_0_does_not_exist_on_type_1, + "[" + typeToString(indexType) + "]", + typeToString(objectType) + ); + } else if (indexType.flags & 8192 /* UniqueESSymbol */) { + const symbolName2 = getFullyQualifiedName(indexType.symbol, accessExpression); + errorInfo = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Property_0_does_not_exist_on_type_1, + "[" + symbolName2 + "]", + typeToString(objectType) + ); + } else if (indexType.flags & 128 /* StringLiteral */) { + errorInfo = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Property_0_does_not_exist_on_type_1, + indexType.value, + typeToString(objectType) + ); + } else if (indexType.flags & 256 /* NumberLiteral */) { + errorInfo = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Property_0_does_not_exist_on_type_1, + indexType.value, + typeToString(objectType) + ); + } else if (indexType.flags & (8 /* Number */ | 4 /* String */)) { + errorInfo = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1, + typeToString(indexType), + typeToString(objectType) + ); + } + errorInfo = chainDiagnosticMessages( + errorInfo, + Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, + typeToString(fullIndexType), + typeToString(objectType) + ); + diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(accessExpression), accessExpression, errorInfo)); + } + } + } + } + return void 0; + } + } + if (accessFlags & 16 /* AllowMissing */ && isObjectLiteralType(objectType)) { + return undefinedType; + } + if (isJSLiteralType(objectType)) { + return anyType; + } + if (accessNode) { + const indexNode = getIndexNodeForAccessExpression(accessNode); + if (indexNode.kind !== 10 /* BigIntLiteral */ && indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); + } else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { + error(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); + } else { + const typeString = indexNode.kind === 10 /* BigIntLiteral */ ? "bigint" : typeToString(indexType); + error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeString); + } + } + if (isTypeAny(indexType)) { + return indexType; + } + return void 0; + function errorIfWritingToReadonlyIndex(indexInfo) { + if (indexInfo && indexInfo.isReadonly && accessExpression && (isAssignmentTarget(accessExpression) || isDeleteTarget(accessExpression))) { + error(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + } + } + function getIndexNodeForAccessExpression(accessNode) { + return accessNode.kind === 212 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.kind === 199 /* IndexedAccessType */ ? accessNode.indexType : accessNode.kind === 167 /* ComputedPropertyName */ ? accessNode.expression : accessNode; + } + function isPatternLiteralPlaceholderType(type) { + if (type.flags & 2097152 /* Intersection */) { + let seenPlaceholder = false; + for (const t of type.types) { + if (t.flags & (2944 /* Literal */ | 98304 /* Nullable */) || isPatternLiteralPlaceholderType(t)) { + seenPlaceholder = true; + } else if (!(t.flags & 524288 /* Object */)) { + return false; + } + } + return seenPlaceholder; + } + return !!(type.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 64 /* BigInt */)) || isPatternLiteralType(type); + } + function isPatternLiteralType(type) { + return !!(type.flags & 134217728 /* TemplateLiteral */) && every(type.types, isPatternLiteralPlaceholderType) || !!(type.flags & 268435456 /* StringMapping */) && isPatternLiteralPlaceholderType(type.type); + } + function isGenericStringLikeType(type) { + return !!(type.flags & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); + } + function isGenericType(type) { + return !!getGenericObjectFlags(type); + } + function isGenericObjectType(type) { + return !!(getGenericObjectFlags(type) & 4194304 /* IsGenericObjectType */); + } + function isGenericIndexType(type) { + return !!(getGenericObjectFlags(type) & 8388608 /* IsGenericIndexType */); + } + function getGenericObjectFlags(type) { + if (type.flags & 3145728 /* UnionOrIntersection */) { + if (!(type.objectFlags & 2097152 /* IsGenericTypeComputed */)) { + type.objectFlags |= 2097152 /* IsGenericTypeComputed */ | reduceLeft(type.types, (flags, t) => flags | getGenericObjectFlags(t), 0); + } + return type.objectFlags & 12582912 /* IsGenericType */; + } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 2097152 /* IsGenericTypeComputed */)) { + type.objectFlags |= 2097152 /* IsGenericTypeComputed */ | getGenericObjectFlags(type.baseType) | getGenericObjectFlags(type.constraint); + } + return type.objectFlags & 12582912 /* IsGenericType */; + } + return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 4194304 /* IsGenericObjectType */ : 0) | (type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */) || isGenericStringLikeType(type) ? 8388608 /* IsGenericIndexType */ : 0); + } + function getSimplifiedType(type, writing) { + return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) : type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) : type; + } + function distributeIndexOverObjectType(objectType, indexType, writing) { + if (objectType.flags & 1048576 /* Union */ || objectType.flags & 2097152 /* Intersection */ && !shouldDeferIndexType(objectType)) { + const types = map(objectType.types, (t) => getSimplifiedType(getIndexedAccessType(t, indexType), writing)); + return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types); + } + } + function distributeObjectOverIndexType(objectType, indexType, writing) { + if (indexType.flags & 1048576 /* Union */) { + const types = map(indexType.types, (t) => getSimplifiedType(getIndexedAccessType(objectType, t), writing)); + return writing ? getIntersectionType(types) : getUnionType(types); + } + } + function getSimplifiedIndexedAccessType(type, writing) { + const cache = writing ? "simplifiedForWriting" : "simplifiedForReading"; + if (type[cache]) { + return type[cache] === circularConstraintType ? type : type[cache]; + } + type[cache] = circularConstraintType; + const objectType = getSimplifiedType(type.objectType, writing); + const indexType = getSimplifiedType(type.indexType, writing); + const distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing); + if (distributedOverIndex) { + return type[cache] = distributedOverIndex; + } + if (!(indexType.flags & 465829888 /* Instantiable */)) { + const distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing); + if (distributedOverObject) { + return type[cache] = distributedOverObject; + } + } + if (isGenericTupleType(objectType) && indexType.flags & 296 /* NumberLike */) { + const elementType = getElementTypeOfSliceOfTupleType( + objectType, + indexType.flags & 8 /* Number */ ? 0 : objectType.target.fixedLength, + /*endSkipCount*/ + 0, + writing + ); + if (elementType) { + return type[cache] = elementType; + } + } + if (isGenericMappedType(objectType)) { + if (getMappedTypeNameTypeKind(objectType) !== 2 /* Remapping */) { + return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), (t) => getSimplifiedType(t, writing)); + } + } + return type[cache] = type; + } + function getSimplifiedConditionalType(type, writing) { + const checkType = type.checkType; + const extendsType = type.extendsType; + const trueType2 = getTrueTypeFromConditionalType(type); + const falseType2 = getFalseTypeFromConditionalType(type); + if (falseType2.flags & 131072 /* Never */ && getActualTypeVariable(trueType2) === getActualTypeVariable(checkType)) { + if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { + return getSimplifiedType(trueType2, writing); + } else if (isIntersectionEmpty(checkType, extendsType)) { + return neverType; + } + } else if (trueType2.flags & 131072 /* Never */ && getActualTypeVariable(falseType2) === getActualTypeVariable(checkType)) { + if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { + return neverType; + } else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { + return getSimplifiedType(falseType2, writing); + } + } + return type; + } + function isIntersectionEmpty(type1, type2) { + return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */); + } + function substituteIndexedMappedType(objectType, index) { + const mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); + const templateMapper = combineTypeMappers(objectType.mapper, mapper); + const instantiatedTemplateType = instantiateType(getTemplateTypeFromMappedType(objectType.target || objectType), templateMapper); + const isOptional = getMappedTypeOptionality(objectType) > 0 || (isGenericType(objectType) ? getCombinedMappedTypeOptionality(getModifiersTypeFromMappedType(objectType)) > 0 : couldAccessOptionalProperty(objectType, index)); + return addOptionality( + instantiatedTemplateType, + /*isProperty*/ + true, + isOptional + ); + } + function couldAccessOptionalProperty(objectType, indexType) { + const indexConstraint = getBaseConstraintOfType(indexType); + return !!indexConstraint && some(getPropertiesOfType(objectType), (p) => !!(p.flags & 16777216 /* Optional */) && isTypeAssignableTo(getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */), indexConstraint)); + } + function getIndexedAccessType(objectType, indexType, accessFlags = 0 /* None */, accessNode, aliasSymbol, aliasTypeArguments) { + return getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType); + } + function indexTypeLessThan(indexType, limit) { + return everyType(indexType, (t) => { + if (t.flags & 384 /* StringOrNumberLiteral */) { + const propName = getPropertyNameFromType(t); + if (isNumericLiteralName(propName)) { + const index = +propName; + return index >= 0 && index < limit; + } + } + return false; + }); + } + function getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags = 0 /* None */, accessNode, aliasSymbol, aliasTypeArguments) { + if (objectType === wildcardType || indexType === wildcardType) { + return wildcardType; + } + objectType = getReducedType(objectType); + if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { + indexType = stringType; + } + if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) accessFlags |= 1 /* IncludeUndefined */; + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) { + if (objectType.flags & 3 /* AnyOrUnknown */) { + return objectType; + } + const persistentAccessFlags = accessFlags & 1 /* Persistent */; + const id = objectType.id + "," + indexType.id + "," + persistentAccessFlags + getAliasId(aliasSymbol, aliasTypeArguments); + let type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, persistentAccessFlags, aliasSymbol, aliasTypeArguments)); + } + return type; + } + const apparentObjectType = getReducedApparentType(objectType); + if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { + const propTypes = []; + let wasMissingProp = false; + for (const t of indexType.types) { + const propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, accessNode, accessFlags | (wasMissingProp ? 128 /* SuppressNoImplicitAnyError */ : 0)); + if (propType) { + propTypes.push(propType); + } else if (!accessNode) { + return void 0; + } else { + wasMissingProp = true; + } + } + if (wasMissingProp) { + return void 0; + } + return accessFlags & 4 /* Writing */ ? getIntersectionType(propTypes, 0 /* None */, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments); + } + return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, accessNode, accessFlags | 8 /* CacheSymbol */ | 64 /* ReportDeprecated */); + } + function getTypeFromIndexedAccessTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const objectType = getTypeFromTypeNode(node.objectType); + const indexType = getTypeFromTypeNode(node.indexType); + const potentialAlias = getAliasSymbolForTypeNode(node); + links.resolvedType = getIndexedAccessType(objectType, indexType, 0 /* None */, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias)); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); + links.resolvedType = type; + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getActualTypeVariable(type) { + if (type.flags & 33554432 /* Substitution */) { + return getActualTypeVariable(type.baseType); + } + if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ || type.indexType.flags & 33554432 /* Substitution */)) { + return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType)); + } + return type; + } + function isSimpleTupleType(node) { + return isTupleTypeNode(node) && length(node.elements) > 0 && !some(node.elements, (e) => isOptionalTypeNode(e) || isRestTypeNode(e) || isNamedTupleMember(e) && !!(e.questionToken || e.dotDotDotToken)); + } + function isDeferredType(type, checkTuples) { + return isGenericType(type) || checkTuples && isTupleType(type) && some(getElementTypes(type), isGenericType); + } + function getConditionalType(root, mapper, forConstraint, aliasSymbol, aliasTypeArguments) { + let result; + let extraTypes; + let tailCount = 0; + while (true) { + if (tailCount === 1e3) { + error(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); + return errorType; + } + const checkType = instantiateType(getActualTypeVariable(root.checkType), mapper); + const extendsType = instantiateType(root.extendsType, mapper); + if (checkType === errorType || extendsType === errorType) { + return errorType; + } + if (checkType === wildcardType || extendsType === wildcardType) { + return wildcardType; + } + const checkTypeNode = skipTypeParentheses(root.node.checkType); + const extendsTypeNode = skipTypeParentheses(root.node.extendsType); + const checkTuples = isSimpleTupleType(checkTypeNode) && isSimpleTupleType(extendsTypeNode) && length(checkTypeNode.elements) === length(extendsTypeNode.elements); + const checkTypeDeferred = isDeferredType(checkType, checkTuples); + let combinedMapper; + if (root.inferTypeParameters) { + const context = createInferenceContext( + root.inferTypeParameters, + /*signature*/ + void 0, + 0 /* None */ + ); + if (mapper) { + context.nonFixingMapper = combineTypeMappers(context.nonFixingMapper, mapper); + } + if (!checkTypeDeferred) { + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); + } + combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper; + } + const inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + if (!checkTypeDeferred && !isDeferredType(inferredExtendsType, checkTuples)) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (checkType.flags & 1 /* Any */ || forConstraint && !(inferredExtendsType.flags & 131072 /* Never */) && someType(getPermissiveInstantiation(inferredExtendsType), (t) => isTypeAssignableTo(t, getPermissiveInstantiation(checkType)))) { + (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); + } + const falseType2 = getTypeFromTypeNode(root.node.falseType); + if (falseType2.flags & 16777216 /* Conditional */) { + const newRoot = falseType2.root; + if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { + root = newRoot; + continue; + } + if (canTailRecurse(falseType2, mapper)) { + continue; + } + } + result = instantiateType(falseType2, mapper); + break; + } + if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { + const trueType2 = getTypeFromTypeNode(root.node.trueType); + const trueMapper = combinedMapper || mapper; + if (canTailRecurse(trueType2, trueMapper)) { + continue; + } + result = instantiateType(trueType2, trueMapper); + break; + } + } + result = createType(16777216 /* Conditional */); + result.root = root; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = aliasSymbol || root.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); + break; + } + return extraTypes ? getUnionType(append(extraTypes, result)) : result; + function canTailRecurse(newType, newMapper) { + if (newType.flags & 16777216 /* Conditional */ && newMapper) { + const newRoot = newType.root; + if (newRoot.outerTypeParameters) { + const typeParamMapper = combineTypeMappers(newType.mapper, newMapper); + const typeArguments = map(newRoot.outerTypeParameters, (t) => getMappedType(t, typeParamMapper)); + const newRootMapper = createTypeMapper(newRoot.outerTypeParameters, typeArguments); + const newCheckType = newRoot.isDistributive ? getMappedType(newRoot.checkType, newRootMapper) : void 0; + if (!newCheckType || newCheckType === newRoot.checkType || !(newCheckType.flags & (1048576 /* Union */ | 131072 /* Never */))) { + root = newRoot; + mapper = newRootMapper; + aliasSymbol = void 0; + aliasTypeArguments = void 0; + if (newRoot.aliasSymbol) { + tailCount++; + } + return true; + } + } + } + return false; + } + } + function getTrueTypeFromConditionalType(type) { + return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.mapper)); + } + function getFalseTypeFromConditionalType(type) { + return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(getTypeFromTypeNode(type.root.node.falseType), type.mapper)); + } + function getInferredTrueTypeFromConditionalType(type) { + return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.combinedMapper) : getTrueTypeFromConditionalType(type)); + } + function getInferTypeParameters(node) { + let result; + if (node.locals) { + node.locals.forEach((symbol) => { + if (symbol.flags & 262144 /* TypeParameter */) { + result = append(result, getDeclaredTypeOfSymbol(symbol)); + } + }); + } + return result; + } + function isDistributionDependent(root) { + return root.isDistributive && (isTypeParameterPossiblyReferenced(root.checkType, root.node.trueType) || isTypeParameterPossiblyReferenced(root.checkType, root.node.falseType)); + } + function getTypeFromConditionalTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const checkType = getTypeFromTypeNode(node.checkType); + const aliasSymbol = getAliasSymbolForTypeNode(node); + const aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + const allOuterTypeParameters = getOuterTypeParameters( + node, + /*includeThisTypes*/ + true + ); + const outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : filter(allOuterTypeParameters, (tp) => isTypeParameterPossiblyReferenced(tp, node)); + const root = { + node, + checkType, + extendsType: getTypeFromTypeNode(node.extendsType), + isDistributive: !!(checkType.flags & 262144 /* TypeParameter */), + inferTypeParameters: getInferTypeParameters(node), + outerTypeParameters, + instantiations: void 0, + aliasSymbol, + aliasTypeArguments + }; + links.resolvedType = getConditionalType( + root, + /*mapper*/ + void 0, + /*forConstraint*/ + false + ); + if (outerTypeParameters) { + root.instantiations = /* @__PURE__ */ new Map(); + root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); + } + } + return links.resolvedType; + } + function getTypeFromInferTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter)); + } + return links.resolvedType; + } + function getIdentifierChain(node) { + if (isIdentifier(node)) { + return [node]; + } else { + return append(getIdentifierChain(node.left), node.right); + } + } + function getTypeFromImportTypeNode(node) { + var _a; + const links = getNodeLinks(node); + if (!links.resolvedType) { + if (!isLiteralImportTypeNode(node)) { + error(node.argument, Diagnostics.String_literal_expected); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + const targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 16777216 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */; + const innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); + if (!innerModuleSymbol) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + const isExportEquals = !!((_a = innerModuleSymbol.exports) == null ? void 0 : _a.get("export=" /* ExportEquals */)); + const moduleSymbol = resolveExternalModuleSymbol( + innerModuleSymbol, + /*dontResolveAlias*/ + false + ); + if (!nodeIsMissing(node.qualifier)) { + const nameStack = getIdentifierChain(node.qualifier); + let currentNamespace = moduleSymbol; + let current; + while (current = nameStack.shift()) { + const meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; + const mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); + const symbolFromVariable = node.isTypeOf || isInJSFile(node) && isExportEquals ? getPropertyOfType( + getTypeOfSymbol(mergedResolvedSymbol), + current.escapedText, + /*skipObjectFunctionPropertyAugment*/ + false, + /*includeTypeOnlyMembers*/ + true + ) : void 0; + const symbolFromModule = node.isTypeOf ? void 0 : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + const next = symbolFromModule ?? symbolFromVariable; + if (!next) { + error(current, Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), declarationNameToString(current)); + return links.resolvedType = errorType; + } + getNodeLinks(current).resolvedSymbol = next; + getNodeLinks(current.parent).resolvedSymbol = next; + currentNamespace = next; + } + links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning); + } else { + if (moduleSymbol.flags & targetMeaning) { + links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); + } else { + const errorMessage = targetMeaning === 111551 /* Value */ ? Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); + links.resolvedSymbol = unknownSymbol; + links.resolvedType = errorType; + } + } + } + return links.resolvedType; + } + function resolveImportSymbolType(node, links, symbol, meaning) { + const resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; + if (meaning === 111551 /* Value */) { + return getInstantiationExpressionType(getTypeOfSymbol(symbol), node); + } else { + return getTypeReferenceType(node, resolvedSymbol); + } + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const aliasSymbol = getAliasSymbolForTypeNode(node); + if (!node.symbol || getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } else { + let type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + if (isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + let host2 = node.parent; + while (isParenthesizedTypeNode(host2) || isJSDocTypeExpression(host2) || isTypeOperatorNode(host2) && host2.operator === 148 /* ReadonlyKeyword */) { + host2 = host2.parent; + } + return isTypeAlias(host2) ? getSymbolOfDeclaration(host2) : void 0; + } + function getTypeArgumentsForAliasSymbol(symbol) { + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : void 0; + } + function isNonGenericObjectType(type) { + return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type); + } + function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) { + return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)); + } + function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) { + if (!(type.flags & 1048576 /* Union */)) { + return type; + } + if (every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) { + return find(type.types, isEmptyObjectType) || emptyObjectType; + } + const firstType = find(type.types, (t) => !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t)); + if (!firstType) { + return type; + } + const secondType = find(type.types, (t) => t !== firstType && !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t)); + if (secondType) { + return type; + } + return getAnonymousPartialType(firstType); + function getAnonymousPartialType(type2) { + const members = createSymbolTable(); + for (const prop of getPropertiesOfType(type2)) { + if (getDeclarationModifierFlagsFromSymbol(prop) & (2 /* Private */ | 4 /* Protected */)) { + } else if (isSpreadableProperty(prop)) { + const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + const flags = 4 /* Property */ | 16777216 /* Optional */; + const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* Readonly */ : 0)); + result.links.type = isSetonlyAccessor ? undefinedType : addOptionality( + getTypeOfSymbol(prop), + /*isProperty*/ + true + ); + result.declarations = prop.declarations; + result.links.nameType = getSymbolLinks(prop).nameType; + result.links.syntheticOrigin = prop; + members.set(prop.escapedName, result); + } + } + const spread = createAnonymousType(type2.symbol, members, emptyArray, emptyArray, getIndexInfosOfType(type2)); + spread.objectFlags |= 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; + return spread; + } + } + function getSpreadType(left, right, symbol, objectFlags, readonly) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { + return unknownType; + } + if (left.flags & 131072 /* Never */) { + return right; + } + if (right.flags & 131072 /* Never */) { + return left; + } + left = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly); + if (left.flags & 1048576 /* Union */) { + return checkCrossProductUnion([left, right]) ? mapType(left, (t) => getSpreadType(t, right, symbol, objectFlags, readonly)) : errorType; + } + right = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly); + if (right.flags & 1048576 /* Union */) { + return checkCrossProductUnion([left, right]) ? mapType(right, (t) => getSpreadType(left, t, symbol, objectFlags, readonly)) : errorType; + } + if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { + return left; + } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + if (left.flags & 2097152 /* Intersection */) { + const types = left.types; + const lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)])); + } + } + return getIntersectionType([left, right]); + } + const members = createSymbolTable(); + const skippedPrivateMembers = /* @__PURE__ */ new Set(); + const indexInfos = left === emptyObjectType ? getIndexInfosOfType(right) : getUnionIndexInfos([left, right]); + for (const rightProp of getPropertiesOfType(right)) { + if (getDeclarationModifierFlagsFromSymbol(rightProp) & (2 /* Private */ | 4 /* Protected */)) { + skippedPrivateMembers.add(rightProp.escapedName); + } else if (isSpreadableProperty(rightProp)) { + members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly)); + } + } + for (const leftProp of getPropertiesOfType(left)) { + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + const rightProp = members.get(leftProp.escapedName); + const rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216 /* Optional */) { + const declarations = concatenate(leftProp.declarations, rightProp.declarations); + const flags = 4 /* Property */ | leftProp.flags & 16777216 /* Optional */; + const result = createSymbol(flags, leftProp.escapedName); + const leftType = getTypeOfSymbol(leftProp); + const leftTypeWithoutUndefined = removeMissingOrUndefinedType(leftType); + const rightTypeWithoutUndefined = removeMissingOrUndefinedType(rightType); + result.links.type = leftTypeWithoutUndefined === rightTypeWithoutUndefined ? leftType : getUnionType([leftType, rightTypeWithoutUndefined], 2 /* Subtype */); + result.links.leftSpread = leftProp; + result.links.rightSpread = rightProp; + result.declarations = declarations; + result.links.nameType = getSymbolLinks(leftProp).nameType; + members.set(leftProp.escapedName, result); + } + } else { + members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly)); + } + } + const spread = createAnonymousType(symbol, members, emptyArray, emptyArray, sameMap(indexInfos, (info) => getIndexInfoWithReadonly(info, readonly))); + spread.objectFlags |= 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */ | 2097152 /* ContainsSpread */ | objectFlags; + return spread; + } + function isSpreadableProperty(prop) { + var _a; + return !some(prop.declarations, isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || !((_a = prop.declarations) == null ? void 0 : _a.some((decl) => isClassLike(decl.parent)))); + } + function getSpreadSymbol(prop, readonly) { + const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) { + return prop; + } + const flags = 4 /* Property */ | prop.flags & 16777216 /* Optional */; + const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* Readonly */ : 0)); + result.links.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.links.nameType = getSymbolLinks(prop).nameType; + result.links.syntheticOrigin = prop; + return result; + } + function getIndexInfoWithReadonly(info, readonly) { + return info.isReadonly !== readonly ? createIndexInfo(info.keyType, info.type, readonly, info.declaration, info.components) : info; + } + function createLiteralType(flags, value, symbol, regularType) { + const type = createTypeWithSymbol(flags, symbol); + type.value = value; + type.regularType = regularType || type; + return type; + } + function getFreshTypeOfLiteralType(type) { + if (type.flags & 2976 /* Freshable */) { + if (!type.freshType) { + const freshType = createLiteralType(type.flags, type.value, type.symbol, type); + freshType.freshType = freshType; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 2976 /* Freshable */ ? type.regularType : type.flags & 1048576 /* Union */ ? type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType)) : type; + } + function isFreshLiteralType(type) { + return !!(type.flags & 2976 /* Freshable */) && type.freshType === type; + } + function getStringLiteralType(value) { + let type; + return stringLiteralTypes.get(value) || (stringLiteralTypes.set(value, type = createLiteralType(128 /* StringLiteral */, value)), type); + } + function getNumberLiteralType(value) { + let type; + return numberLiteralTypes.get(value) || (numberLiteralTypes.set(value, type = createLiteralType(256 /* NumberLiteral */, value)), type); + } + function getBigIntLiteralType(value) { + let type; + const key = pseudoBigIntToString(value); + return bigIntLiteralTypes.get(key) || (bigIntLiteralTypes.set(key, type = createLiteralType(2048 /* BigIntLiteral */, value)), type); + } + function getEnumLiteralType(value, enumId, symbol) { + let type; + const key = `${enumId}${typeof value === "string" ? "@" : "#"}${value}`; + const flags = 1024 /* EnumLiteral */ | (typeof value === "string" ? 128 /* StringLiteral */ : 256 /* NumberLiteral */); + return enumLiteralTypes.get(key) || (enumLiteralTypes.set(key, type = createLiteralType(flags, value, symbol)), type); + } + function getTypeFromLiteralTypeNode(node) { + if (node.literal.kind === 106 /* NullKeyword */) { + return nullType; + } + const links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function createUniqueESSymbolType(symbol) { + const type = createTypeWithSymbol(8192 /* UniqueESSymbol */, symbol); + type.escapedName = `__@${type.symbol.escapedName}@${getSymbolId(type.symbol)}`; + return type; + } + function getESSymbolLikeTypeForNode(node) { + if (isInJSFile(node) && isJSDocTypeExpression(node)) { + const host2 = getJSDocHost(node); + if (host2) { + node = getSingleVariableOfVariableStatement(host2) || host2; + } + } + if (isValidESSymbolDeclaration(node)) { + const symbol = isCommonJsExportPropertyAssignment(node) ? getSymbolOfNode(node.left) : getSymbolOfNode(node); + if (symbol) { + const links = getSymbolLinks(symbol); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); + } + } + return esSymbolType; + } + function getThisType(node) { + const container = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + const parent = container && container.parent; + if (parent && (isClassLike(parent) || parent.kind === 264 /* InterfaceDeclaration */)) { + if (!isStatic(container) && (!isConstructorDeclaration(container) || isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(parent)).thisType; + } + } + if (parent && isObjectLiteralExpression(parent) && isBinaryExpression(parent.parent) && getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType; + } + const host2 = node.flags & 16777216 /* JSDoc */ ? getHostSignatureFromJSDoc(node) : void 0; + if (host2 && isFunctionExpression(host2) && isBinaryExpression(host2.parent) && getAssignmentDeclarationKind(host2.parent) === 3 /* PrototypeProperty */) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host2.parent.left).parent).thisType; + } + if (isJSConstructor(container) && isNodeDescendantOf(node, container.body)) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(container)).thisType; + } + error(node, Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return errorType; + } + function getTypeFromThisTypeNode(node) { + const links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromRestTypeNode(node) { + return getTypeFromTypeNode(getArrayElementTypeNode(node.type) || node.type); + } + function getArrayElementTypeNode(node) { + switch (node.kind) { + case 196 /* ParenthesizedType */: + return getArrayElementTypeNode(node.type); + case 189 /* TupleType */: + if (node.elements.length === 1) { + node = node.elements[0]; + if (node.kind === 191 /* RestType */ || node.kind === 202 /* NamedTupleMember */ && node.dotDotDotToken) { + return getArrayElementTypeNode(node.type); + } + } + break; + case 188 /* ArrayType */: + return node.elementType; + } + return void 0; + } + function getTypeFromNamedTupleTypeNode(node) { + const links = getNodeLinks(node); + return links.resolvedType || (links.resolvedType = node.dotDotDotToken ? getTypeFromRestTypeNode(node) : addOptionality( + getTypeFromTypeNode(node.type), + /*isProperty*/ + true, + !!node.questionToken + )); + } + function getTypeFromTypeNode(node) { + return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node); + } + function getTypeFromTypeNodeWorker(node) { + switch (node.kind) { + case 133 /* AnyKeyword */: + case 312 /* JSDocAllType */: + case 313 /* JSDocUnknownType */: + return anyType; + case 159 /* UnknownKeyword */: + return unknownType; + case 154 /* StringKeyword */: + return stringType; + case 150 /* NumberKeyword */: + return numberType; + case 163 /* BigIntKeyword */: + return bigintType; + case 136 /* BooleanKeyword */: + return booleanType; + case 155 /* SymbolKeyword */: + return esSymbolType; + case 116 /* VoidKeyword */: + return voidType; + case 157 /* UndefinedKeyword */: + return undefinedType; + case 106 /* NullKeyword */: + return nullType; + case 146 /* NeverKeyword */: + return neverType; + case 151 /* ObjectKeyword */: + return node.flags & 524288 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType; + case 141 /* IntrinsicKeyword */: + return intrinsicMarkerType; + case 197 /* ThisType */: + case 110 /* ThisKeyword */: + return getTypeFromThisTypeNode(node); + case 201 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 183 /* TypeReference */: + return getTypeFromTypeReference(node); + case 182 /* TypePredicate */: + return node.assertsModifier ? voidType : booleanType; + case 233 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 186 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 188 /* ArrayType */: + case 189 /* TupleType */: + return getTypeFromArrayOrTupleTypeNode(node); + case 190 /* OptionalType */: + return getTypeFromOptionalTypeNode(node); + case 192 /* UnionType */: + return getTypeFromUnionTypeNode(node); + case 193 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 314 /* JSDocNullableType */: + return getTypeFromJSDocNullableTypeNode(node); + case 316 /* JSDocOptionalType */: + return addOptionality(getTypeFromTypeNode(node.type)); + case 202 /* NamedTupleMember */: + return getTypeFromNamedTupleTypeNode(node); + case 196 /* ParenthesizedType */: + case 315 /* JSDocNonNullableType */: + case 309 /* JSDocTypeExpression */: + return getTypeFromTypeNode(node.type); + case 191 /* RestType */: + return getTypeFromRestTypeNode(node); + case 318 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + case 187 /* TypeLiteral */: + case 322 /* JSDocTypeLiteral */: + case 317 /* JSDocFunctionType */: + case 323 /* JSDocSignature */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 198 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 199 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 200 /* MappedType */: + return getTypeFromMappedTypeNode(node); + case 194 /* ConditionalType */: + return getTypeFromConditionalTypeNode(node); + case 195 /* InferType */: + return getTypeFromInferTypeNode(node); + case 203 /* TemplateLiteralType */: + return getTypeFromTemplateTypeNode(node); + case 205 /* ImportType */: + return getTypeFromImportTypeNode(node); + // This function assumes that an identifier, qualified name, or property access expression is a type expression + // Callers should first ensure this by calling `isPartOfTypeNode` + // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. + case 80 /* Identifier */: + case 166 /* QualifiedName */: + case 211 /* PropertyAccessExpression */: + const symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + default: + return errorType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + for (let i = 0; i < items.length; i++) { + const item = items[i]; + const mapped = instantiator(item, mapper); + if (item !== mapped) { + const result = i === 0 ? [] : items.slice(0, i); + result.push(mapped); + for (i++; i < items.length; i++) { + result.push(instantiator(items[i], mapper)); + } + return result; + } + } + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateIndexInfos(indexInfos, mapper) { + return instantiateList(indexInfos, mapper, instantiateIndexInfo); + } + function createTypeMapper(sources, targets) { + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets); + } + function getMappedType(type, mapper) { + switch (mapper.kind) { + case 0 /* Simple */: + return type === mapper.source ? mapper.target : type; + case 1 /* Array */: { + const sources = mapper.sources; + const targets = mapper.targets; + for (let i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return type; + } + case 2 /* Deferred */: { + const sources = mapper.sources; + const targets = mapper.targets; + for (let i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets[i](); + } + } + return type; + } + case 3 /* Function */: + return mapper.func(type); + case 4 /* Composite */: + case 5 /* Merged */: + const t1 = getMappedType(type, mapper.mapper1); + return t1 !== type && mapper.kind === 4 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); + } + } + function makeUnaryTypeMapper(source, target) { + return Debug.attachDebugPrototypeIfDebug({ kind: 0 /* Simple */, source, target }); + } + function makeArrayTypeMapper(sources, targets) { + return Debug.attachDebugPrototypeIfDebug({ kind: 1 /* Array */, sources, targets }); + } + function makeFunctionTypeMapper(func, debugInfo) { + return Debug.attachDebugPrototypeIfDebug({ kind: 3 /* Function */, func, debugInfo: Debug.isDebugging ? debugInfo : void 0 }); + } + function makeDeferredTypeMapper(sources, targets) { + return Debug.attachDebugPrototypeIfDebug({ kind: 2 /* Deferred */, sources, targets }); + } + function makeCompositeTypeMapper(kind, mapper1, mapper2) { + return Debug.attachDebugPrototypeIfDebug({ kind, mapper1, mapper2 }); + } + function createTypeEraser(sources) { + return createTypeMapper( + sources, + /*targets*/ + void 0 + ); + } + function createBackreferenceMapper(context, index) { + const forwardInferences = context.inferences.slice(index); + return createTypeMapper(map(forwardInferences, (i) => i.typeParameter), map(forwardInferences, () => unknownType)); + } + function combineTypeMappers(mapper1, mapper2) { + return mapper1 ? makeCompositeTypeMapper(4 /* Composite */, mapper1, mapper2) : mapper2; + } + function mergeTypeMappers(mapper1, mapper2) { + return mapper1 ? makeCompositeTypeMapper(5 /* Merged */, mapper1, mapper2) : mapper2; + } + function prependTypeMapping(source, target, mapper) { + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* Merged */, makeUnaryTypeMapper(source, target), mapper); + } + function appendTypeMapping(mapper, source, target) { + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* Merged */, mapper, makeUnaryTypeMapper(source, target)); + } + function getRestrictiveTypeParameter(tp) { + return !tp.constraint && !getConstraintDeclaration(tp) || tp.constraint === noConstraintType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), tp.restrictiveInstantiation.constraint = noConstraintType, tp.restrictiveInstantiation); + } + function cloneTypeParameter(typeParameter) { + const result = createTypeParameter(typeParameter.symbol); + result.target = typeParameter; + return result; + } + function instantiateTypePredicate(predicate, mapper) { + return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper)); + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + let freshTypeParameters; + if (signature.typeParameters && !eraseTypeParameters) { + freshTypeParameters = map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (const tp of freshTypeParameters) { + tp.mapper = mapper; + } + } + const result = createSignature( + signature.declaration, + freshTypeParameters, + signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), + instantiateList(signature.parameters, mapper, instantiateSymbol), + /*resolvedReturnType*/ + void 0, + /*resolvedTypePredicate*/ + void 0, + signature.minArgumentCount, + signature.flags & 167 /* PropagatingFlags */ + ); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + const links = getSymbolLinks(symbol); + if (links.type && !couldContainTypeVariables(links.type)) { + if (!(symbol.flags & 65536 /* SetAccessor */)) { + return symbol; + } + if (links.writeType && !couldContainTypeVariables(links.writeType)) { + return symbol; + } + } + if (getCheckFlags(symbol) & 1 /* Instantiated */) { + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + const result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */)); + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.links.target = symbol; + result.links.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + if (links.nameType) { + result.links.nameType = links.nameType; + } + return result; + } + function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { + const declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.objectFlags & 8388608 /* InstantiationExpressionType */ ? type.node : type.symbol.declarations[0]; + const links = getNodeLinks(declaration); + const target = type.objectFlags & 4 /* Reference */ ? links.resolvedType : type.objectFlags & 64 /* Instantiated */ ? type.target : type; + let typeParameters = type.objectFlags & 134217728 /* SingleSignatureType */ ? type.outerTypeParameters : links.outerTypeParameters; + if (!typeParameters) { + let outerTypeParameters = getOuterTypeParameters( + declaration, + /*includeThisTypes*/ + true + ); + if (isJSConstructor(declaration)) { + const templateTagParameters = getTypeParametersFromDeclaration(declaration); + outerTypeParameters = addRange(outerTypeParameters, templateTagParameters); + } + typeParameters = outerTypeParameters || emptyArray; + const allDeclarations = type.objectFlags & (4 /* Reference */ | 8388608 /* InstantiationExpressionType */) ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & (4 /* Reference */ | 8388608 /* InstantiationExpressionType */) || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? filter(typeParameters, (tp) => some(allDeclarations, (d) => isTypeParameterPossiblyReferenced(tp, d))) : typeParameters; + links.outerTypeParameters = typeParameters; + } + if (typeParameters.length) { + const combinedMapper = combineTypeMappers(type.mapper, mapper); + const typeArguments = map(typeParameters, (t) => getMappedType(t, combinedMapper)); + const newAliasSymbol = aliasSymbol || type.aliasSymbol; + const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + const id = (type.objectFlags & 134217728 /* SingleSignatureType */ ? "S" : "") + getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); + if (!target.instantiations) { + target.instantiations = /* @__PURE__ */ new Map(); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); + } + let result = target.instantiations.get(id); + if (!result) { + if (type.objectFlags & 134217728 /* SingleSignatureType */) { + result = instantiateAnonymousType(type, mapper); + target.instantiations.set(id, result); + return result; + } + const newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); + target.instantiations.set(id, result); + const resultObjectFlags = getObjectFlags(result); + if (result.flags & 3899393 /* ObjectFlagsType */ && !(resultObjectFlags & 524288 /* CouldContainTypeVariablesComputed */)) { + const resultCouldContainTypeVariables = some(typeArguments, couldContainTypeVariables); + if (!(getObjectFlags(result) & 524288 /* CouldContainTypeVariablesComputed */)) { + if (resultObjectFlags & (32 /* Mapped */ | 16 /* Anonymous */ | 4 /* Reference */)) { + result.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (resultCouldContainTypeVariables ? 1048576 /* CouldContainTypeVariables */ : 0); + } else { + result.objectFlags |= !resultCouldContainTypeVariables ? 524288 /* CouldContainTypeVariablesComputed */ : 0; + } + } + } + } + return result; + } + return type; + } + function maybeTypeParameterReference(node) { + return !(node.parent.kind === 183 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || node.parent.kind === 205 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); + } + function isTypeParameterPossiblyReferenced(tp, node) { + if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { + const container = tp.symbol.declarations[0].parent; + for (let n = node; n !== container; n = n.parent) { + if (!n || n.kind === 241 /* Block */ || n.kind === 194 /* ConditionalType */ && forEachChild(n.extendsType, containsReference)) { + return true; + } + } + return containsReference(node); + } + return true; + function containsReference(node2) { + switch (node2.kind) { + case 197 /* ThisType */: + return !!tp.isThisType; + case 80 /* Identifier */: + return !tp.isThisType && isPartOfTypeNode(node2) && maybeTypeParameterReference(node2) && getTypeFromTypeNodeWorker(node2) === tp; + // use worker because we're looking for === equality + case 186 /* TypeQuery */: + const entityName = node2.exprName; + const firstIdentifier = getFirstIdentifier(entityName); + if (!isThisIdentifier(firstIdentifier)) { + const firstIdentifierSymbol = getResolvedSymbol(firstIdentifier); + const tpDeclaration = tp.symbol.declarations[0]; + const tpScope = tpDeclaration.kind === 168 /* TypeParameter */ ? tpDeclaration.parent : ( + // Type parameter is a regular type parameter, e.g. foo + tp.isThisType ? tpDeclaration : ( + // Type parameter is the this type, and its declaration is the class declaration. + void 0 + ) + ); + if (firstIdentifierSymbol.declarations && tpScope) { + return some(firstIdentifierSymbol.declarations, (idDecl) => isNodeDescendantOf(idDecl, tpScope)) || some(node2.typeArguments, containsReference); + } + } + return true; + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + return !node2.type && !!node2.body || some(node2.typeParameters, containsReference) || some(node2.parameters, containsReference) || !!node2.type && containsReference(node2.type); + } + return !!forEachChild(node2, containsReference); + } + } + function getHomomorphicTypeVariable(type) { + const constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 4194304 /* Index */) { + const typeVariable = getActualTypeVariable(constraintType.type); + if (typeVariable.flags & 262144 /* TypeParameter */) { + return typeVariable; + } + } + return void 0; + } + function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) { + const typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + const mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + return mapTypeWithAlias(getReducedType(mappedTypeVariable), instantiateConstituent, aliasSymbol, aliasTypeArguments); + } + } + return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments); + function instantiateConstituent(t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { + if (!type.declaration.nameType) { + let constraint; + if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, isArrayOrTupleType)) { + return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); + } + if (isTupleType(t)) { + return instantiateMappedTupleType(t, type, typeVariable, mapper); + } + if (isArrayOrTupleOrIntersection(t)) { + return getIntersectionType(map(t.types, instantiateConstituent)); + } + } + return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); + } + return t; + } + } + function getModifiedReadonlyState(state, modifiers) { + return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state; + } + function instantiateMappedTupleType(tupleType, mappedType, typeVariable, mapper) { + const elementFlags = tupleType.target.elementFlags; + const fixedLength = tupleType.target.fixedLength; + const fixedMapper = fixedLength ? prependTypeMapping(typeVariable, tupleType, mapper) : mapper; + const newElementTypes = map(getElementTypes(tupleType), (type, i) => { + const flags = elementFlags[i]; + return i < fixedLength ? instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(flags & 2 /* Optional */), fixedMapper) : flags & 8 /* Variadic */ ? instantiateType(mappedType, prependTypeMapping(typeVariable, type, mapper)) : getElementTypeOfArrayType(instantiateType(mappedType, prependTypeMapping(typeVariable, createArrayType(type), mapper))) ?? unknownType; + }); + const modifiers = getMappedTypeModifiers(mappedType); + const newElementFlags = modifiers & 4 /* IncludeOptional */ ? map(elementFlags, (f) => f & 1 /* Required */ ? 2 /* Optional */ : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : elementFlags; + const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, getMappedTypeModifiers(mappedType)); + return contains(newElementTypes, errorType) ? errorType : createTupleType(newElementTypes, newElementFlags, newReadonly, tupleType.target.labeledElementDeclarations); + } + function instantiateMappedArrayType(arrayType, mappedType, mapper) { + const elementType = instantiateMappedTypeTemplate( + mappedType, + numberType, + /*isOptional*/ + true, + mapper + ); + return isErrorType(elementType) ? errorType : createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType))); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + const templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key); + const propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + const modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType( + propType, + /*isProperty*/ + true + ) : strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; + } + function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) { + Debug.assert(type.symbol, "anonymous type must have symbol to be instantiated"); + const result = createObjectType(type.objectFlags & ~(524288 /* CouldContainTypeVariablesComputed */ | 1048576 /* CouldContainTypeVariables */) | 64 /* Instantiated */, type.symbol); + if (type.objectFlags & 32 /* Mapped */) { + result.declaration = type.declaration; + const origTypeParameter = getTypeParameterFromMappedType(type); + const freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; + } + if (type.objectFlags & 8388608 /* InstantiationExpressionType */) { + result.node = type.node; + } + if (type.objectFlags & 134217728 /* SingleSignatureType */) { + result.outerTypeParameters = type.outerTypeParameters; + } + result.target = type; + result.mapper = mapper; + result.aliasSymbol = aliasSymbol || type.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + result.objectFlags |= result.aliasTypeArguments ? getPropagatingFlagsOfTypes(result.aliasTypeArguments) : 0; + return result; + } + function getConditionalTypeInstantiation(type, mapper, forConstraint, aliasSymbol, aliasTypeArguments) { + const root = type.root; + if (root.outerTypeParameters) { + const typeArguments = map(root.outerTypeParameters, (t) => getMappedType(t, mapper)); + const id = (forConstraint ? "C" : "") + getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); + let result = root.instantiations.get(id); + if (!result) { + const newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); + const checkType = root.checkType; + const distributionType = root.isDistributive ? getReducedType(getMappedType(checkType, newMapper)) : void 0; + result = distributionType && checkType !== distributionType && distributionType.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapTypeWithAlias(distributionType, (t) => getConditionalType(root, prependTypeMapping(checkType, t, newMapper), forConstraint), aliasSymbol, aliasTypeArguments) : getConditionalType(root, newMapper, forConstraint, aliasSymbol, aliasTypeArguments); + root.instantiations.set(id, result); + } + return result; + } + return type; + } + function instantiateType(type, mapper) { + return type && mapper ? instantiateTypeWithAlias( + type, + mapper, + /*aliasSymbol*/ + void 0, + /*aliasTypeArguments*/ + void 0 + ) : type; + } + function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + var _a; + if (!couldContainTypeVariables(type)) { + return type; + } + if (instantiationDepth === 100 || instantiationCount >= 5e6) { + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth, instantiationCount }); + error(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); + return errorType; + } + totalInstantiationCount++; + instantiationCount++; + instantiationDepth++; + const result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) { + const flags = type.flags; + if (flags & 262144 /* TypeParameter */) { + return getMappedType(type, mapper); + } + if (flags & 524288 /* Object */) { + const objectFlags = type.objectFlags; + if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { + if (objectFlags & 4 /* Reference */ && !type.node) { + const resolvedTypeArguments = type.resolvedTypeArguments; + const newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); + return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; + } + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } + return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); + } + return type; + } + if (flags & 3145728 /* UnionOrIntersection */) { + const origin = type.flags & 1048576 /* Union */ ? type.origin : void 0; + const types = origin && origin.flags & 3145728 /* UnionOrIntersection */ ? origin.types : type.types; + const newTypes = instantiateTypes(types, mapper); + if (newTypes === types && aliasSymbol === type.aliasSymbol) { + return type; + } + const newAliasSymbol = aliasSymbol || type.aliasSymbol; + const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? getIntersectionType(newTypes, 0 /* None */, newAliasSymbol, newAliasTypeArguments) : getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); + } + if (flags & 4194304 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 134217728 /* TemplateLiteral */) { + return getTemplateLiteralType(type.texts, instantiateTypes(type.types, mapper)); + } + if (flags & 268435456 /* StringMapping */) { + return getStringMappingType(type.symbol, instantiateType(type.type, mapper)); + } + if (flags & 8388608 /* IndexedAccess */) { + const newAliasSymbol = aliasSymbol || type.aliasSymbol; + const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return getIndexedAccessType( + instantiateType(type.objectType, mapper), + instantiateType(type.indexType, mapper), + type.accessFlags, + /*accessNode*/ + void 0, + newAliasSymbol, + newAliasTypeArguments + ); + } + if (flags & 16777216 /* Conditional */) { + return getConditionalTypeInstantiation( + type, + combineTypeMappers(type.mapper, mapper), + /*forConstraint*/ + false, + aliasSymbol, + aliasTypeArguments + ); + } + if (flags & 33554432 /* Substitution */) { + const newBaseType = instantiateType(type.baseType, mapper); + if (isNoInferType(type)) { + return getNoInferType(newBaseType); + } + const newConstraint = instantiateType(type.constraint, mapper); + if (newBaseType.flags & 8650752 /* TypeVariable */ && isGenericType(newConstraint)) { + return getSubstitutionType(newBaseType, newConstraint); + } + if (newConstraint.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(newBaseType), getRestrictiveInstantiation(newConstraint))) { + return newBaseType; + } + return newBaseType.flags & 8650752 /* TypeVariable */ ? getSubstitutionType(newBaseType, newConstraint) : getIntersectionType([newConstraint, newBaseType]); + } + return type; + } + function instantiateReverseMappedType(type, mapper) { + const innerMappedType = instantiateType(type.mappedType, mapper); + if (!(getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + const innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + const instantiated = inferTypeForHomomorphicMappedType( + instantiateType(type.source, mapper), + innerMappedType, + innerIndexType + ); + if (instantiated) { + return instantiated; + } + return type; + } + function getPermissiveInstantiation(type) { + return type.flags & (402784252 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); + } + function getRestrictiveInstantiation(type) { + if (type.flags & (402784252 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) { + return type; + } + if (type.restrictiveInstantiation) { + return type.restrictiveInstantiation; + } + type.restrictiveInstantiation = instantiateType(type, restrictiveMapper); + type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation; + return type.restrictiveInstantiation; + } + function instantiateIndexInfo(info, mapper) { + return createIndexInfo(info.keyType, instantiateType(info.type, mapper), info.isReadonly, info.declaration, info.components); + } + function isContextSensitive(node) { + Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node)); + switch (node.kind) { + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 174 /* MethodDeclaration */: + case 262 /* FunctionDeclaration */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 210 /* ObjectLiteralExpression */: + return some(node.properties, isContextSensitive); + case 209 /* ArrayLiteralExpression */: + return some(node.elements, isContextSensitive); + case 227 /* ConditionalExpression */: + return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); + case 226 /* BinaryExpression */: + return (node.operatorToken.kind === 57 /* BarBarToken */ || node.operatorToken.kind === 61 /* QuestionQuestionToken */) && (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 303 /* PropertyAssignment */: + return isContextSensitive(node.initializer); + case 217 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); + case 292 /* JsxAttributes */: + return some(node.properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); + case 291 /* JsxAttribute */: { + const { initializer } = node; + return !!initializer && isContextSensitive(initializer); + } + case 294 /* JsxExpression */: { + const { expression } = node; + return !!expression && isContextSensitive(expression); + } + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + return hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { + if (node.typeParameters || getEffectiveReturnTypeNode(node) || !node.body) { + return false; + } + if (node.body.kind !== 241 /* Block */) { + return isContextSensitive(node.body); + } + return !!forEachReturnStatement(node.body, (statement) => !!statement.expression && isContextSensitive(statement.expression)); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 524288 /* Object */) { + const resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length || resolved.callSignatures.length) { + const result = createObjectType(16 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = emptyArray; + result.constructSignatures = emptyArray; + result.indexInfos = emptyArray; + return result; + } + } else if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(map(type.types, getTypeWithoutSignatures)); + } + return type; + } + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeStrictSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, strictSubtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + function isTypeDerivedFrom(source, target) { + return source.flags & 1048576 /* Union */ ? every(source.types, (t) => isTypeDerivedFrom(t, target)) : target.flags & 1048576 /* Union */ ? some(target.types, (t) => isTypeDerivedFrom(source, t)) : source.flags & 2097152 /* Intersection */ ? some(source.types, (t) => isTypeDerivedFrom(t, target)) : source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) : isEmptyAnonymousObjectType(target) ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) && !isEmptyAnonymousObjectType(source) : target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : hasBaseType(source, getTargetType(target)) || isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType); + } + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + return checkTypeRelatedToAndOptionallyElaborate( + source, + target, + assignableRelation, + errorNode, + expr, + headMessage, + containingMessageChain, + /*errorOutputContainer*/ + void 0 + ); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) { + if (isTypeRelatedTo(source, target, relation)) return true; + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer); + } + return false; + } + function isOrHasGenericConditional(type) { + return !!(type.flags & 16777216 /* Conditional */ || type.flags & 2097152 /* Intersection */ && some(type.types, isOrHasGenericConditional)); + } + function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo( + source, + target, + relation, + /*errorNode*/ + void 0 + ) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) { + return true; + } + switch (node.kind) { + case 234 /* AsExpression */: + if (!isConstAssertion(node)) { + break; + } + // fallthrough + case 294 /* JsxExpression */: + case 217 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); + case 226 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 64 /* EqualsToken */: + case 28 /* CommaToken */: + return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); + } + break; + case 210 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); + case 209 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); + case 292 /* JsxAttributes */: + return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); + case 219 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) { + const callSignatures = getSignaturesOfType(source, 0 /* Call */); + const constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (const signatures of [constructSignatures, callSignatures]) { + if (some(signatures, (s) => { + const returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo( + returnType, + target, + relation, + /*errorNode*/ + void 0 + ); + })) { + const resultObj = errorOutputContainer || {}; + checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj); + const diagnostic = resultObj.errors[resultObj.errors.length - 1]; + addRelatedInfo( + diagnostic, + createDiagnosticForNode( + node, + signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression + ) + ); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) { + if (isBlock(node.body)) { + return false; + } + if (some(node.parameters, hasType)) { + return false; + } + const sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + const targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!length(targetSignatures)) { + return false; + } + const returnExpression = node.body; + const sourceReturn = getReturnTypeOfSignature(sourceSig); + const targetReturn = getUnionType(map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo( + sourceReturn, + targetReturn, + relation, + /*errorNode*/ + void 0 + )) { + const elaborated = returnExpression && elaborateError( + returnExpression, + sourceReturn, + targetReturn, + relation, + /*headMessage*/ + void 0, + containingMessageChain, + errorOutputContainer + ); + if (elaborated) { + return elaborated; + } + const resultObj = errorOutputContainer || {}; + checkTypeRelatedTo( + sourceReturn, + targetReturn, + relation, + returnExpression, + /*headMessage*/ + void 0, + containingMessageChain, + resultObj + ); + if (resultObj.errors) { + if (target.symbol && length(target.symbol.declarations)) { + addRelatedInfo( + resultObj.errors[resultObj.errors.length - 1], + createDiagnosticForNode( + target.symbol.declarations[0], + Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature + ) + ); + } + if ((getFunctionFlags(node) & 2 /* Async */) === 0 && !getTypeOfPropertyOfType(sourceReturn, "then") && checkTypeRelatedTo( + createPromiseType(sourceReturn), + targetReturn, + relation, + /*errorNode*/ + void 0 + )) { + addRelatedInfo( + resultObj.errors[resultObj.errors.length - 1], + createDiagnosticForNode( + node, + Diagnostics.Did_you_mean_to_mark_this_function_as_async + ) + ); + } + return true; + } + } + return false; + } + function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) { + const idx = getIndexedAccessTypeOrUndefined(target, nameType); + if (idx) { + return idx; + } + if (target.flags & 1048576 /* Union */) { + const best = getBestMatchingType(source, target); + if (best) { + return getIndexedAccessTypeOrUndefined(best, nameType); + } + } + } + function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) { + pushContextualType( + next, + sourcePropType, + /*isCache*/ + false + ); + const result = checkExpressionForMutableLocation(next, 1 /* Contextual */); + popContextualType(); + return result; + } + function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) { + let reportedError = false; + for (const value of iterator) { + const { errorNode: prop, innerExpression: next, nameType, errorMessage } = value; + let targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType); + if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */) continue; + let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); + if (!sourcePropType) continue; + const propName = getPropertyNameFromIndex( + nameType, + /*accessNode*/ + void 0 + ); + if (!checkTypeRelatedTo( + sourcePropType, + targetPropType, + relation, + /*errorNode*/ + void 0 + )) { + const elaborated = next && elaborateError( + next, + sourcePropType, + targetPropType, + relation, + /*headMessage*/ + void 0, + containingMessageChain, + errorOutputContainer + ); + reportedError = true; + if (!elaborated) { + const resultObj = errorOutputContainer || {}; + const specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; + if (exactOptionalPropertyTypes && isExactOptionalPropertyMismatch(specificSource, targetPropType)) { + const diag2 = createDiagnosticForNode(prop, Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target, typeToString(specificSource), typeToString(targetPropType)); + diagnostics.add(diag2); + resultObj.errors = [diag2]; + } else { + const targetIsOptional = !!(propName && (getPropertyOfType(target, propName) || unknownSymbol).flags & 16777216 /* Optional */); + const sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & 16777216 /* Optional */); + targetPropType = removeMissingType(targetPropType, targetIsOptional); + sourcePropType = removeMissingType(sourcePropType, targetIsOptional && sourceIsOptional); + const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); + if (result && specificSource !== sourcePropType) { + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); + } + } + if (resultObj.errors) { + const reportedDiag = resultObj.errors[resultObj.errors.length - 1]; + const propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : void 0; + const targetProp = propertyName !== void 0 ? getPropertyOfType(target, propertyName) : void 0; + let issuedElaboration = false; + if (!targetProp) { + const indexInfo = getApplicableIndexInfo(target, nameType); + if (indexInfo && indexInfo.declaration && !getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, createDiagnosticForNode(indexInfo.declaration, Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && length(targetProp.declarations) || target.symbol && length(target.symbol.declarations))) { + const targetNode = targetProp && length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo( + reportedDiag, + createDiagnosticForNode( + targetNode, + Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, + propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), + typeToString(target) + ) + ); + } + } + } + } + } + } + return reportedError; + } + function elaborateIterableOrArrayLikeTargetElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) { + const tupleOrArrayLikeTargetParts = filterType(target, isArrayOrTupleLikeType); + const nonTupleOrArrayLikeTargetParts = filterType(target, (t) => !isArrayOrTupleLikeType(t)); + const iterationType = nonTupleOrArrayLikeTargetParts !== neverType ? getIterationTypeOfIterable( + 13 /* ForOf */, + 0 /* Yield */, + nonTupleOrArrayLikeTargetParts, + /*errorNode*/ + void 0 + ) : void 0; + let reportedError = false; + for (let status = iterator.next(); !status.done; status = iterator.next()) { + const { errorNode: prop, innerExpression: next, nameType, errorMessage } = status.value; + let targetPropType = iterationType; + const targetIndexedPropType = tupleOrArrayLikeTargetParts !== neverType ? getBestMatchIndexedAccessTypeOrUndefined(source, tupleOrArrayLikeTargetParts, nameType) : void 0; + if (targetIndexedPropType && !(targetIndexedPropType.flags & 8388608 /* IndexedAccess */)) { + targetPropType = iterationType ? getUnionType([iterationType, targetIndexedPropType]) : targetIndexedPropType; + } + if (!targetPropType) continue; + let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); + if (!sourcePropType) continue; + const propName = getPropertyNameFromIndex( + nameType, + /*accessNode*/ + void 0 + ); + if (!checkTypeRelatedTo( + sourcePropType, + targetPropType, + relation, + /*errorNode*/ + void 0 + )) { + const elaborated = next && elaborateError( + next, + sourcePropType, + targetPropType, + relation, + /*headMessage*/ + void 0, + containingMessageChain, + errorOutputContainer + ); + reportedError = true; + if (!elaborated) { + const resultObj = errorOutputContainer || {}; + const specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; + if (exactOptionalPropertyTypes && isExactOptionalPropertyMismatch(specificSource, targetPropType)) { + const diag2 = createDiagnosticForNode(prop, Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target, typeToString(specificSource), typeToString(targetPropType)); + diagnostics.add(diag2); + resultObj.errors = [diag2]; + } else { + const targetIsOptional = !!(propName && (getPropertyOfType(tupleOrArrayLikeTargetParts, propName) || unknownSymbol).flags & 16777216 /* Optional */); + const sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & 16777216 /* Optional */); + targetPropType = removeMissingType(targetPropType, targetIsOptional); + sourcePropType = removeMissingType(sourcePropType, targetIsOptional && sourceIsOptional); + const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); + if (result && specificSource !== sourcePropType) { + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); + } + } + } + } + } + return reportedError; + } + function* generateJsxAttributes(node) { + if (!length(node.properties)) return; + for (const prop of node.properties) { + if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(getTextOfJsxAttributeName(prop.name))) continue; + yield { errorNode: prop.name, innerExpression: prop.initializer, nameType: getStringLiteralType(getTextOfJsxAttributeName(prop.name)) }; + } + } + function* generateJsxChildren(node, getInvalidTextDiagnostic) { + if (!length(node.children)) return; + let memberOffset = 0; + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + const nameType = getNumberLiteralType(i - memberOffset); + const elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic); + if (elem) { + yield elem; + } else { + memberOffset++; + } + } + } + function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { + switch (child.kind) { + case 294 /* JsxExpression */: + return { errorNode: child, innerExpression: child.expression, nameType }; + case 12 /* JsxText */: + if (child.containsOnlyTriviaWhiteSpaces) { + break; + } + return { errorNode: child, innerExpression: void 0, nameType, errorMessage: getInvalidTextDiagnostic() }; + case 284 /* JsxElement */: + case 285 /* JsxSelfClosingElement */: + case 288 /* JsxFragment */: + return { errorNode: child, innerExpression: child, nameType }; + default: + return Debug.assertNever(child, "Found invalid jsx child"); + } + } + function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) { + let result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer); + let invalidTextDiagnostic; + if (isJsxOpeningElement(node.parent) && isJsxElement(node.parent.parent)) { + const containingElement = node.parent.parent; + const childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + const childrenPropName = childPropName === void 0 ? "children" : unescapeLeadingUnderscores(childPropName); + const childrenNameType = getStringLiteralType(childrenPropName); + const childrenTargetType = getIndexedAccessType(target, childrenNameType); + const validChildren = getSemanticJsxChildren(containingElement.children); + if (!length(validChildren)) { + return result; + } + const moreThanOneRealChildren = length(validChildren) > 1; + let arrayLikeTargetParts; + let nonArrayLikeTargetParts; + const iterableType = getGlobalIterableType( + /*reportErrors*/ + false + ); + if (iterableType !== emptyGenericType) { + const anyIterable = createIterableType(anyType); + arrayLikeTargetParts = filterType(childrenTargetType, (t) => isTypeAssignableTo(t, anyIterable)); + nonArrayLikeTargetParts = filterType(childrenTargetType, (t) => !isTypeAssignableTo(t, anyIterable)); + } else { + arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType); + nonArrayLikeTargetParts = filterType(childrenTargetType, (t) => !isArrayOrTupleLikeType(t)); + } + if (moreThanOneRealChildren) { + if (arrayLikeTargetParts !== neverType) { + const realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */)); + const children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic); + result = elaborateIterableOrArrayLikeTargetElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result; + } else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + result = true; + const diag2 = error( + containingElement.openingElement.tagName, + Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, + childrenPropName, + typeToString(childrenTargetType) + ); + if (errorOutputContainer && errorOutputContainer.skipLogging) { + (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); + } + } + } else { + if (nonArrayLikeTargetParts !== neverType) { + const child = validChildren[0]; + const elem = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); + if (elem) { + result = elaborateElementwise( + function* () { + yield elem; + }(), + source, + target, + relation, + containingMessageChain, + errorOutputContainer + ) || result; + } + } else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + result = true; + const diag2 = error( + containingElement.openingElement.tagName, + Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, + childrenPropName, + typeToString(childrenTargetType) + ); + if (errorOutputContainer && errorOutputContainer.skipLogging) { + (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); + } + } + } + } + return result; + function getInvalidTextualChildDiagnostic() { + if (!invalidTextDiagnostic) { + const tagNameText = getTextOfNode(node.parent.tagName); + const childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + const childrenPropName = childPropName === void 0 ? "children" : unescapeLeadingUnderscores(childPropName); + const childrenTargetType = getIndexedAccessType(target, getStringLiteralType(childrenPropName)); + const diagnostic = Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; + invalidTextDiagnostic = { ...diagnostic, key: "!!ALREADY FORMATTED!!", message: formatMessage(diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }; + } + return invalidTextDiagnostic; + } + } + function* generateLimitedTupleElements(node, target) { + const len = length(node.elements); + if (!len) return; + for (let i = 0; i < len; i++) { + if (isTupleLikeType(target) && !getPropertyOfType(target, "" + i)) continue; + const elem = node.elements[i]; + if (isOmittedExpression(elem)) continue; + const nameType = getNumberLiteralType(i); + const checkNode = getEffectiveCheckNode(elem); + yield { errorNode: checkNode, innerExpression: checkNode, nameType }; + } + } + function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { + if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) return false; + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); + } + pushContextualType( + node, + target, + /*isCache*/ + false + ); + const tupleizedType = checkArrayLiteral( + node, + 1 /* Contextual */, + /*forceTuple*/ + true + ); + popContextualType(); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer); + } + return false; + } + function* generateObjectLiteralElements(node) { + if (!length(node.properties)) return; + for (const prop of node.properties) { + if (isSpreadAssignment(prop)) continue; + const type = getLiteralTypeFromProperty(getSymbolOfDeclaration(prop), 8576 /* StringOrNumberLiteralOrUnique */); + if (!type || type.flags & 131072 /* Never */) { + continue; + } + switch (prop.kind) { + case 178 /* SetAccessor */: + case 177 /* GetAccessor */: + case 174 /* MethodDeclaration */: + case 304 /* ShorthandPropertyAssignment */: + yield { errorNode: prop.name, innerExpression: void 0, nameType: type }; + break; + case 303 /* PropertyAssignment */: + yield { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : void 0 }; + break; + default: + Debug.assertNever(prop); + } + } + } + function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { + if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) return false; + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); + } + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated( + source, + target, + ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0 /* None */, + /*reportErrors*/ + false, + /*errorReporter*/ + void 0, + /*incompatibleErrorReporter*/ + void 0, + compareTypesAssignable, + /*reportUnreliableMarkers*/ + void 0 + ) !== 0 /* False */; + } + function isTopSignature(s) { + if (!s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && signatureHasRestParameter(s)) { + const paramType = getTypeOfParameter(s.parameters[0]); + const restType = isArrayType(paramType) ? getTypeArguments(paramType)[0] : paramType; + return !!(restType.flags & (1 /* Any */ | 131072 /* Never */) && getReturnTypeOfSignature(s).flags & 3 /* AnyOrUnknown */); + } + return false; + } + function compareSignaturesRelated(source, target, checkMode, reportErrors2, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) { + if (source === target) { + return -1 /* True */; + } + if (!(checkMode & 16 /* StrictTopSignature */ && isTopSignature(source)) && isTopSignature(target)) { + return -1 /* True */; + } + if (checkMode & 16 /* StrictTopSignature */ && isTopSignature(source) && !isTopSignature(target)) { + return 0 /* False */; + } + const targetCount = getParameterCount(target); + const sourceHasMoreParameters = !hasEffectiveRestParameter(target) && (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount); + if (sourceHasMoreParameters) { + if (reportErrors2 && !(checkMode & 8 /* StrictArity */)) { + errorReporter(Diagnostics.Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1, getMinArgumentCount(source), targetCount); + } + return 0 /* False */; + } + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); + source = instantiateSignatureInContextOf( + source, + target, + /*inferenceContext*/ + void 0, + compareTypes + ); + } + const sourceCount = getParameterCount(source); + const sourceRestType = getNonArrayRestType(source); + const targetRestType = getNonArrayRestType(target); + if (sourceRestType || targetRestType) { + void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers); + } + const kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + const strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 174 /* MethodDeclaration */ && kind !== 173 /* MethodSignature */ && kind !== 176 /* Constructor */; + let result = -1 /* True */; + const sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + const targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + const related = !strictVariance && compareTypes( + sourceThisType, + targetThisType, + /*reportErrors*/ + false + ) || compareTypes(targetThisType, sourceThisType, reportErrors2); + if (!related) { + if (reportErrors2) { + errorReporter(Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0 /* False */; + } + result &= related; + } + } + const paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + const restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; + for (let i = 0; i < paramCount; i++) { + const sourceType = i === restIndex ? getRestOrAnyTypeAtPosition(source, i) : tryGetTypeAtPosition(source, i); + const targetType = i === restIndex ? getRestOrAnyTypeAtPosition(target, i) : tryGetTypeAtPosition(target, i); + if (sourceType && targetType && (sourceType !== targetType || checkMode & 8 /* StrictArity */)) { + const sourceSig = checkMode & 3 /* Callback */ || isInstantiatedGenericParameter(source, i) ? void 0 : getSingleCallSignature(getNonNullableType(sourceType)); + const targetSig = checkMode & 3 /* Callback */ || isInstantiatedGenericParameter(target, i) ? void 0 : getSingleCallSignature(getNonNullableType(targetType)); + const callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && getTypeFacts(sourceType, 50331648 /* IsUndefinedOrNull */) === getTypeFacts(targetType, 50331648 /* IsUndefinedOrNull */); + let related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, checkMode & 8 /* StrictArity */ | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors2, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes( + sourceType, + targetType, + /*reportErrors*/ + false + ) || compareTypes(targetType, sourceType, reportErrors2); + if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes( + sourceType, + targetType, + /*reportErrors*/ + false + )) { + related = 0 /* False */; + } + if (!related) { + if (reportErrors2) { + errorReporter(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); + } + return 0 /* False */; + } + result &= related; + } + } + if (!(checkMode & 4 /* IgnoreReturnTypes */)) { + const targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol)) : getReturnTypeOfSignature(target); + if (targetReturnType === voidType || targetReturnType === anyType) { + return result; + } + const sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol)) : getReturnTypeOfSignature(source); + const targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + const sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors2, errorReporter, compareTypes); + } else if (isIdentifierTypePredicate(targetTypePredicate) || isThisTypePredicate(targetTypePredicate)) { + if (reportErrors2) { + errorReporter(Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } else { + result &= checkMode & 1 /* BivariantCallback */ && compareTypes( + targetReturnType, + sourceReturnType, + /*reportErrors*/ + false + ) || compareTypes(sourceReturnType, targetReturnType, reportErrors2); + if (!result && reportErrors2 && incompatibleErrorReporter) { + incompatibleErrorReporter(sourceReturnType, targetReturnType); + } + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors2, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors2) { + errorReporter(Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) { + if (source.parameterIndex !== target.parameterIndex) { + if (reportErrors2) { + errorReporter(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName); + errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + const related = source.type === target.type ? -1 /* True */ : source.type && target.type ? compareTypes(source.type, target.type, reportErrors2) : 0 /* False */; + if (related === 0 /* False */ && reportErrors2) { + errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + const erasedSource = getErasedSignature(implementation); + const erasedTarget = getErasedSignature(overload); + const sourceReturnType = getReturnTypeOfSignature(erasedSource); + const targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo( + erasedSource, + erasedTarget, + /*ignoreReturnTypes*/ + true + ); + } + return false; + } + function isEmptyResolvedType(t) { + return t !== anyFunctionType && t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && t.indexInfos.length === 0; + } + function isEmptyObjectType(type) { + return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 67108864 /* NonPrimitive */ ? true : type.flags & 1048576 /* Union */ ? some(type.types, isEmptyObjectType) : type.flags & 2097152 /* Intersection */ ? every(type.types, isEmptyObjectType) : false; + } + function isEmptyAnonymousObjectType(type) { + return !!(getObjectFlags(type) & 16 /* Anonymous */ && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0)); + } + function isUnknownLikeUnionType(type) { + if (strictNullChecks && type.flags & 1048576 /* Union */) { + if (!(type.objectFlags & 33554432 /* IsUnknownLikeUnionComputed */)) { + const types = type.types; + type.objectFlags |= 33554432 /* IsUnknownLikeUnionComputed */ | (types.length >= 3 && types[0].flags & 32768 /* Undefined */ && types[1].flags & 65536 /* Null */ && some(types, isEmptyAnonymousObjectType) ? 67108864 /* IsUnknownLikeUnion */ : 0); + } + return !!(type.objectFlags & 67108864 /* IsUnknownLikeUnion */); + } + return false; + } + function containsUndefinedType(type) { + return !!((type.flags & 1048576 /* Union */ ? type.types[0] : type).flags & 32768 /* Undefined */); + } + function containsNonMissingUndefinedType(type) { + const candidate = type.flags & 1048576 /* Union */ ? type.types[0] : type; + return !!(candidate.flags & 32768 /* Undefined */) && candidate !== missingType; + } + function isStringIndexSignatureOnlyType(type) { + return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 /* UnionOrIntersection */ && every(type.types, isStringIndexSignatureOnlyType) || false; + } + function isEnumTypeRelatedTo(source, target, errorReporter) { + const sourceSymbol = source.flags & 8 /* EnumMember */ ? getParentOfSymbol(source) : source; + const targetSymbol = target.flags & 8 /* EnumMember */ ? getParentOfSymbol(target) : target; + if (sourceSymbol === targetSymbol) { + return true; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { + return false; + } + const id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + const entry = enumRelation.get(id); + if (entry !== void 0 && !(entry & 2 /* Failed */ && errorReporter)) { + return !!(entry & 1 /* Succeeded */); + } + const targetEnumType = getTypeOfSymbol(targetSymbol); + for (const sourceProperty of getPropertiesOfType(getTypeOfSymbol(sourceSymbol))) { + if (sourceProperty.flags & 8 /* EnumMember */) { + const targetProperty = getPropertyOfType(targetEnumType, sourceProperty.escapedName); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(Diagnostics.Property_0_is_missing_in_type_1, symbolName(sourceProperty), typeToString( + getDeclaredTypeOfSymbol(targetSymbol), + /*enclosingDeclaration*/ + void 0, + 64 /* UseFullyQualifiedType */ + )); + } + enumRelation.set(id, 2 /* Failed */); + return false; + } + const sourceValue = getEnumMemberValue(getDeclarationOfKind(sourceProperty, 306 /* EnumMember */)).value; + const targetValue = getEnumMemberValue(getDeclarationOfKind(targetProperty, 306 /* EnumMember */)).value; + if (sourceValue !== targetValue) { + const sourceIsString = typeof sourceValue === "string"; + const targetIsString = typeof targetValue === "string"; + if (sourceValue !== void 0 && targetValue !== void 0) { + if (errorReporter) { + const escapedSource = sourceIsString ? `"${escapeString(sourceValue)}"` : sourceValue; + const escapedTarget = targetIsString ? `"${escapeString(targetValue)}"` : targetValue; + errorReporter(Diagnostics.Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given, symbolName(targetSymbol), symbolName(targetProperty), escapedTarget, escapedSource); + } + enumRelation.set(id, 2 /* Failed */); + return false; + } + if (sourceIsString || targetIsString) { + if (errorReporter) { + const knownStringValue = sourceValue ?? targetValue; + Debug.assert(typeof knownStringValue === "string"); + const escapedValue = `"${escapeString(knownStringValue)}"`; + errorReporter(Diagnostics.One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value, symbolName(targetSymbol), symbolName(targetProperty), escapedValue); + } + enumRelation.set(id, 2 /* Failed */); + return false; + } + } + } + } + enumRelation.set(id, 1 /* Succeeded */); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + const s = source.flags; + const t = target.flags; + if (t & 1 /* Any */ || s & 131072 /* Never */ || source === wildcardType) return true; + if (t & 2 /* Unknown */ && !(relation === strictSubtypeRelation && s & 1 /* Any */)) return true; + if (t & 131072 /* Never */) return false; + if (s & 402653316 /* StringLike */ && t & 4 /* String */) return true; + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; + if (s & 296 /* NumberLike */ && t & 8 /* Number */) return true; + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) return true; + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) return true; + if (s & 32 /* Enum */ && t & 32 /* Enum */ && source.symbol.escapedName === target.symbol.escapedName && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + } + if (s & 32768 /* Undefined */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & (32768 /* Undefined */ | 16384 /* Void */))) return true; + if (s & 65536 /* Null */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & 65536 /* Null */)) return true; + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(getObjectFlags(source) & 8192 /* FreshLiteral */))) return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (s & 1 /* Any */) return true; + if (s & 8 /* Number */ && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; + if (s & 256 /* NumberLiteral */ && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */ && source.value === target.value)) return true; + if (isUnknownLikeUnionType(target)) return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (isFreshLiteralType(source)) { + source = source.regularType; + } + if (isFreshLiteralType(target)) { + target = target.regularType; + } + if (source === target) { + return true; + } + if (relation !== identityRelation) { + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + } else if (!((source.flags | target.flags) & (3145728 /* UnionOrIntersection */ | 8388608 /* IndexedAccess */ | 16777216 /* Conditional */ | 33554432 /* Substitution */))) { + if (source.flags !== target.flags) return false; + if (source.flags & 67358815 /* Singleton */) return true; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + const related = relation.get(getRelationKey( + source, + target, + 0 /* None */, + relation, + /*ignoreConstraints*/ + false + )); + if (related !== void 0) { + return !!(related & 1 /* Succeeded */); + } + } + if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) { + return checkTypeRelatedTo( + source, + target, + relation, + /*errorNode*/ + void 0 + ); + } + return false; + } + function isIgnoredJsxProperty(source, sourceProp) { + return getObjectFlags(source) & 2048 /* JsxAttributes */ && isHyphenatedJsxName(sourceProp.escapedName); + } + function getNormalizedType(type, writing) { + while (true) { + const t = isFreshLiteralType(type) ? type.regularType : isGenericTupleType(type) ? getNormalizedTupleType(type, writing) : getObjectFlags(type) & 4 /* Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : type.flags & 3145728 /* UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : getSubstitutionIntersection(type) : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + if (t === type) return t; + type = t; + } + } + function getNormalizedUnionOrIntersectionType(type, writing) { + const reduced = getReducedType(type); + if (reduced !== type) { + return reduced; + } + if (type.flags & 2097152 /* Intersection */ && shouldNormalizeIntersection(type)) { + const normalizedTypes = sameMap(type.types, (t) => getNormalizedType(t, writing)); + if (normalizedTypes !== type.types) { + return getIntersectionType(normalizedTypes); + } + } + return type; + } + function shouldNormalizeIntersection(type) { + let hasInstantiable = false; + let hasNullableOrEmpty = false; + for (const t of type.types) { + hasInstantiable || (hasInstantiable = !!(t.flags & 465829888 /* Instantiable */)); + hasNullableOrEmpty || (hasNullableOrEmpty = !!(t.flags & 98304 /* Nullable */) || isEmptyAnonymousObjectType(t)); + if (hasInstantiable && hasNullableOrEmpty) return true; + } + return false; + } + function getNormalizedTupleType(type, writing) { + const elements = getElementTypes(type); + const normalizedElements = sameMap(elements, (t) => t.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(t, writing) : t); + return elements !== normalizedElements ? createNormalizedTupleType(type.target, normalizedElements) : type; + } + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { + var _a; + let errorInfo; + let relatedInfo; + let maybeKeys; + let maybeKeysSet; + let sourceStack; + let targetStack; + let maybeCount = 0; + let sourceDepth = 0; + let targetDepth = 0; + let expandingFlags = 0 /* None */; + let overflow = false; + let overrideNextErrorInfo = 0; + let skipParentCounter = 0; + let lastSkippedInfo; + let incompatibleStack; + let relationCount = 16e6 - relation.size >> 3; + Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + const result = isRelatedTo( + source, + target, + 3 /* Both */, + /*reportErrors*/ + !!errorNode, + headMessage + ); + if (incompatibleStack) { + reportIncompatibleStack(); + } + if (overflow) { + const id = getRelationKey( + source, + target, + /*intersectionState*/ + 0 /* None */, + relation, + /*ignoreConstraints*/ + false + ); + relation.set(id, 2 /* Failed */ | (relationCount <= 0 ? 32 /* ComplexityOverflow */ : 64 /* StackDepthOverflow */)); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: sourceDepth, targetDepth }); + const message = relationCount <= 0 ? Diagnostics.Excessive_complexity_comparing_types_0_and_1 : Diagnostics.Excessive_stack_depth_comparing_types_0_and_1; + const diag2 = error(errorNode || currentNode, message, typeToString(source), typeToString(target)); + if (errorOutputContainer) { + (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); + } + } else if (errorInfo) { + if (containingMessageChain) { + const chain = containingMessageChain(); + if (chain) { + concatenateDiagnosticMessageChains(chain, errorInfo); + errorInfo = chain; + } + } + let relatedInformation; + if (headMessage && errorNode && !result && source.symbol) { + const links = getSymbolLinks(source.symbol); + if (links.originatingImport && !isImportCall(links.originatingImport)) { + const helpfulRetry = checkTypeRelatedTo( + getTypeOfSymbol(links.target), + target, + relation, + /*errorNode*/ + void 0 + ); + if (helpfulRetry) { + const diag3 = createDiagnosticForNode(links.originatingImport, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = append(relatedInformation, diag3); + } + } + } + const diag2 = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo(diag2, ...relatedInfo); + } + if (errorOutputContainer) { + (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); + } + if (!errorOutputContainer || !errorOutputContainer.skipLogging) { + diagnostics.add(diag2); + } + } + if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) { + Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error."); + } + return result !== 0 /* False */; + function resetErrorInfo(saved) { + errorInfo = saved.errorInfo; + lastSkippedInfo = saved.lastSkippedInfo; + incompatibleStack = saved.incompatibleStack; + overrideNextErrorInfo = saved.overrideNextErrorInfo; + skipParentCounter = saved.skipParentCounter; + relatedInfo = saved.relatedInfo; + } + function captureErrorCalculationState() { + return { + errorInfo, + lastSkippedInfo, + incompatibleStack: incompatibleStack == null ? void 0 : incompatibleStack.slice(), + overrideNextErrorInfo, + skipParentCounter, + relatedInfo: relatedInfo == null ? void 0 : relatedInfo.slice() + }; + } + function reportIncompatibleError(message, ...args) { + overrideNextErrorInfo++; + lastSkippedInfo = void 0; + (incompatibleStack || (incompatibleStack = [])).push([message, ...args]); + } + function reportIncompatibleStack() { + const stack = incompatibleStack || []; + incompatibleStack = void 0; + const info = lastSkippedInfo; + lastSkippedInfo = void 0; + if (stack.length === 1) { + reportError(...stack[0]); + if (info) { + reportRelationError( + /*message*/ + void 0, + ...info + ); + } + return; + } + let path = ""; + const secondaryRootErrors = []; + while (stack.length) { + const [msg, ...args] = stack.pop(); + switch (msg.code) { + case Diagnostics.Types_of_property_0_are_incompatible.code: { + if (path.indexOf("new ") === 0) { + path = `(${path})`; + } + const str = "" + args[0]; + if (path.length === 0) { + path = `${str}`; + } else if (isIdentifierText(str, getEmitScriptTarget(compilerOptions))) { + path = `${path}.${str}`; + } else if (str[0] === "[" && str[str.length - 1] === "]") { + path = `${path}${str}`; + } else { + path = `${path}[${str}]`; + } + break; + } + case Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code: + case Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code: + case Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: + case Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: { + if (path.length === 0) { + let mappedMsg = msg; + if (msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) { + mappedMsg = Diagnostics.Call_signature_return_types_0_and_1_are_incompatible; + } else if (msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) { + mappedMsg = Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible; + } + secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]); + } else { + const prefix = msg.code === Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ? "new " : ""; + const params = msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ? "" : "..."; + path = `${prefix}${path}(${params})`; + } + break; + } + case Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: { + secondaryRootErrors.unshift([Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); + break; + } + case Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: { + secondaryRootErrors.unshift([Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); + break; + } + default: + return Debug.fail(`Unhandled Diagnostic: ${msg.code}`); + } + } + if (path) { + reportError( + path[path.length - 1] === ")" ? Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types : Diagnostics.The_types_of_0_are_incompatible_between_these_types, + path + ); + } else { + secondaryRootErrors.shift(); + } + for (const [msg, ...args] of secondaryRootErrors) { + const originalValue = msg.elidedInCompatabilityPyramid; + msg.elidedInCompatabilityPyramid = false; + reportError(msg, ...args); + msg.elidedInCompatabilityPyramid = originalValue; + } + if (info) { + reportRelationError( + /*message*/ + void 0, + ...info + ); + } + } + function reportError(message, ...args) { + Debug.assert(!!errorNode); + if (incompatibleStack) reportIncompatibleStack(); + if (message.elidedInCompatabilityPyramid) return; + if (skipParentCounter === 0) { + errorInfo = chainDiagnosticMessages(errorInfo, message, ...args); + } else { + skipParentCounter--; + } + } + function reportParentSkippedError(message, ...args) { + reportError(message, ...args); + skipParentCounter++; + } + function associateRelatedInfo(info) { + Debug.assert(!!errorInfo); + if (!relatedInfo) { + relatedInfo = [info]; + } else { + relatedInfo.push(info); + } + } + function reportRelationError(message, source2, target2) { + if (incompatibleStack) reportIncompatibleStack(); + const [sourceType, targetType] = getTypeNamesForErrorDisplay(source2, target2); + let generalizedSource = source2; + let generalizedSourceType = sourceType; + if (!(target2.flags & 131072 /* Never */) && isLiteralType(source2) && !typeCouldHaveTopLevelSingletonTypes(target2)) { + generalizedSource = getBaseTypeOfLiteralType(source2); + Debug.assert(!isTypeAssignableTo(generalizedSource, target2), "generalized source shouldn't be assignable"); + generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); + } + const targetFlags = target2.flags & 8388608 /* IndexedAccess */ && !(source2.flags & 8388608 /* IndexedAccess */) ? target2.objectType.flags : target2.flags; + if (targetFlags & 262144 /* TypeParameter */ && target2 !== markerSuperTypeForCheck && target2 !== markerSubTypeForCheck) { + const constraint = getBaseConstraintOfType(target2); + let needsOriginalSource; + if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source2, constraint)))) { + reportError( + Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, + needsOriginalSource ? sourceType : generalizedSourceType, + targetType, + typeToString(constraint) + ); + } else { + errorInfo = void 0; + reportError( + Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, + targetType, + generalizedSourceType + ); + } + } + if (!message) { + if (relation === comparableRelation) { + message = Diagnostics.Type_0_is_not_comparable_to_type_1; + } else if (sourceType === targetType) { + message = Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } else if (exactOptionalPropertyTypes && getExactOptionalUnassignableProperties(source2, target2).length) { + message = Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties; + } else { + if (source2.flags & 128 /* StringLiteral */ && target2.flags & 1048576 /* Union */) { + const suggestedType = getSuggestedTypeForNonexistentStringLiteralType(source2, target2); + if (suggestedType) { + reportError(Diagnostics.Type_0_is_not_assignable_to_type_1_Did_you_mean_2, generalizedSourceType, targetType, typeToString(suggestedType)); + return; + } + } + message = Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } else if (message === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1 && exactOptionalPropertyTypes && getExactOptionalUnassignableProperties(source2, target2).length) { + message = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties; + } + reportError(message, generalizedSourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source2, target2) { + const sourceType = symbolValueDeclarationIsContextSensitive(source2.symbol) ? typeToString(source2, source2.symbol.valueDeclaration) : typeToString(source2); + const targetType = symbolValueDeclarationIsContextSensitive(target2.symbol) ? typeToString(target2, target2.symbol.valueDeclaration) : typeToString(target2); + if (globalStringType === source2 && stringType === target2 || globalNumberType === source2 && numberType === target2 || globalBooleanType === source2 && booleanType === target2 || getGlobalESSymbolType() === source2 && esSymbolType === target2) { + reportError(Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function tryElaborateArrayLikeErrors(source2, target2, reportErrors2) { + if (isTupleType(source2)) { + if (source2.target.readonly && isMutableArrayOrTuple(target2)) { + if (reportErrors2) { + reportError(Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source2), typeToString(target2)); + } + return false; + } + return isArrayOrTupleType(target2); + } + if (isReadonlyArrayType(source2) && isMutableArrayOrTuple(target2)) { + if (reportErrors2) { + reportError(Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source2), typeToString(target2)); + } + return false; + } + if (isTupleType(target2)) { + return isArrayType(source2); + } + return true; + } + function isRelatedToWorker(source2, target2, reportErrors2) { + return isRelatedTo(source2, target2, 3 /* Both */, reportErrors2); + } + function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors2 = false, headMessage2, intersectionState = 0 /* None */) { + if (originalSource === originalTarget) return -1 /* True */; + if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 402784252 /* Primitive */) { + if (relation === comparableRelation && !(originalTarget.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors2 ? reportError : void 0)) { + return -1 /* True */; + } + if (reportErrors2) { + reportErrorResults(originalSource, originalTarget, originalSource, originalTarget, headMessage2); + } + return 0 /* False */; + } + const source2 = getNormalizedType( + originalSource, + /*writing*/ + false + ); + let target2 = getNormalizedType( + originalTarget, + /*writing*/ + true + ); + if (source2 === target2) return -1 /* True */; + if (relation === identityRelation) { + if (source2.flags !== target2.flags) return 0 /* False */; + if (source2.flags & 67358815 /* Singleton */) return -1 /* True */; + traceUnionsOrIntersectionsTooLarge(source2, target2); + return recursiveTypeRelatedTo( + source2, + target2, + /*reportErrors*/ + false, + 0 /* None */, + recursionFlags + ); + } + if (source2.flags & 262144 /* TypeParameter */ && getConstraintOfType(source2) === target2) { + return -1 /* True */; + } + if (source2.flags & 470302716 /* DefinitelyNonNullable */ && target2.flags & 1048576 /* Union */) { + const types = target2.types; + const candidate = types.length === 2 && types[0].flags & 98304 /* Nullable */ ? types[1] : types.length === 3 && types[0].flags & 98304 /* Nullable */ && types[1].flags & 98304 /* Nullable */ ? types[2] : void 0; + if (candidate && !(candidate.flags & 98304 /* Nullable */)) { + target2 = getNormalizedType( + candidate, + /*writing*/ + true + ); + if (source2 === target2) return -1 /* True */; + } + } + if (relation === comparableRelation && !(target2.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target2, source2, relation) || isSimpleTypeRelatedTo(source2, target2, relation, reportErrors2 ? reportError : void 0)) return -1 /* True */; + if (source2.flags & 469499904 /* StructuredOrInstantiable */ || target2.flags & 469499904 /* StructuredOrInstantiable */) { + const isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source2) && getObjectFlags(source2) & 8192 /* FreshLiteral */); + if (isPerformingExcessPropertyChecks) { + if (hasExcessProperties(source2, target2, reportErrors2)) { + if (reportErrors2) { + reportRelationError(headMessage2, source2, originalTarget.aliasSymbol ? originalTarget : target2); + } + return 0 /* False */; + } + } + const isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source2)) && !(intersectionState & 2 /* Target */) && source2.flags & (402784252 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source2 !== globalObjectType && target2.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target2) && (getPropertiesOfType(source2).length > 0 || typeHasCallOrConstructSignatures(source2)); + const isComparingJsxAttributes = !!(getObjectFlags(source2) & 2048 /* JsxAttributes */); + if (isPerformingCommonPropertyChecks && !hasCommonProperties(source2, target2, isComparingJsxAttributes)) { + if (reportErrors2) { + const sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source2); + const targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target2); + const calls = getSignaturesOfType(source2, 0 /* Call */); + const constructs = getSignaturesOfType(source2, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo( + getReturnTypeOfSignature(calls[0]), + target2, + 1 /* Source */, + /*reportErrors*/ + false + ) || constructs.length > 0 && isRelatedTo( + getReturnTypeOfSignature(constructs[0]), + target2, + 1 /* Source */, + /*reportErrors*/ + false + )) { + reportError(Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString); + } else { + reportError(Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString); + } + } + return 0 /* False */; + } + traceUnionsOrIntersectionsTooLarge(source2, target2); + const skipCaching = source2.flags & 1048576 /* Union */ && source2.types.length < 4 && !(target2.flags & 1048576 /* Union */) || target2.flags & 1048576 /* Union */ && target2.types.length < 4 && !(source2.flags & 469499904 /* StructuredOrInstantiable */); + const result2 = skipCaching ? unionOrIntersectionRelatedTo(source2, target2, reportErrors2, intersectionState) : recursiveTypeRelatedTo(source2, target2, reportErrors2, intersectionState, recursionFlags); + if (result2) { + return result2; + } + } + if (reportErrors2) { + reportErrorResults(originalSource, originalTarget, source2, target2, headMessage2); + } + return 0 /* False */; + } + function reportErrorResults(originalSource, originalTarget, source2, target2, headMessage2) { + var _a2, _b; + const sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + const targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source2 = originalSource.aliasSymbol || sourceHasBase ? originalSource : source2; + target2 = originalTarget.aliasSymbol || targetHasBase ? originalTarget : target2; + let maybeSuppress = overrideNextErrorInfo > 0; + if (maybeSuppress) { + overrideNextErrorInfo--; + } + if (source2.flags & 524288 /* Object */ && target2.flags & 524288 /* Object */) { + const currentError = errorInfo; + tryElaborateArrayLikeErrors( + source2, + target2, + /*reportErrors*/ + true + ); + if (errorInfo !== currentError) { + maybeSuppress = !!errorInfo; + } + } + if (source2.flags & 524288 /* Object */ && target2.flags & 402784252 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source2, target2); + } else if (source2.symbol && source2.flags & 524288 /* Object */ && globalObjectType === source2) { + reportError(Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } else if (getObjectFlags(source2) & 2048 /* JsxAttributes */ && target2.flags & 2097152 /* Intersection */) { + const targetTypes = target2.types; + const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + const intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) && (contains(targetTypes, intrinsicAttributes) || contains(targetTypes, intrinsicClassAttributes))) { + return; + } + } else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); + } + if (!headMessage2 && maybeSuppress) { + const savedErrorState = captureErrorCalculationState(); + reportRelationError(headMessage2, source2, target2); + let canonical; + if (errorInfo && errorInfo !== savedErrorState.errorInfo) { + canonical = { code: errorInfo.code, messageText: errorInfo.messageText }; + } + resetErrorInfo(savedErrorState); + if (canonical && errorInfo) { + errorInfo.canonicalHead = canonical; + } + lastSkippedInfo = [source2, target2]; + return; + } + reportRelationError(headMessage2, source2, target2); + if (source2.flags & 262144 /* TypeParameter */ && ((_b = (_a2 = source2.symbol) == null ? void 0 : _a2.declarations) == null ? void 0 : _b[0]) && !getConstraintOfType(source2)) { + const syntheticParam = cloneTypeParameter(source2); + syntheticParam.constraint = instantiateType(target2, makeUnaryTypeMapper(source2, syntheticParam)); + if (hasNonCircularBaseConstraint(syntheticParam)) { + const targetConstraintString = typeToString(target2, source2.symbol.declarations[0]); + associateRelatedInfo(createDiagnosticForNode(source2.symbol.declarations[0], Diagnostics.This_type_parameter_might_need_an_extends_0_constraint, targetConstraintString)); + } + } + } + function traceUnionsOrIntersectionsTooLarge(source2, target2) { + if (!tracing) { + return; + } + if (source2.flags & 3145728 /* UnionOrIntersection */ && target2.flags & 3145728 /* UnionOrIntersection */) { + const sourceUnionOrIntersection = source2; + const targetUnionOrIntersection = target2; + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 32768 /* PrimitiveUnion */) { + return; + } + const sourceSize = sourceUnionOrIntersection.types.length; + const targetSize = targetUnionOrIntersection.types.length; + if (sourceSize * targetSize > 1e6) { + tracing.instant(tracing.Phase.CheckTypes, "traceUnionsOrIntersectionsTooLarge_DepthLimit", { + sourceId: source2.id, + sourceSize, + targetId: target2.id, + targetSize, + pos: errorNode == null ? void 0 : errorNode.pos, + end: errorNode == null ? void 0 : errorNode.end + }); + } + } + } + function getTypeOfPropertyInTypes(types, name) { + const appendPropType = (propTypes, type) => { + var _a2; + type = getApparentType(type); + const prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name); + const propType = prop && getTypeOfSymbol(prop) || ((_a2 = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a2.type) || undefinedType; + return append(propTypes, propType); + }; + return getUnionType(reduceLeft( + types, + appendPropType, + /*initial*/ + void 0 + ) || emptyArray); + } + function hasExcessProperties(source2, target2, reportErrors2) { + var _a2; + if (!isExcessPropertyCheckTarget(target2) || !noImplicitAny && getObjectFlags(target2) & 4096 /* JSLiteral */) { + return false; + } + const isComparingJsxAttributes = !!(getObjectFlags(source2) & 2048 /* JsxAttributes */); + if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target2) || !isComparingJsxAttributes && isEmptyObjectType(target2))) { + return false; + } + let reducedTarget = target2; + let checkTypes; + if (target2.flags & 1048576 /* Union */) { + reducedTarget = findMatchingDiscriminantType(source2, target2, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target2); + checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget]; + } + for (const prop of getPropertiesOfType(source2)) { + if (shouldCheckAsExcessProperty(prop, source2.symbol) && !isIgnoredJsxProperty(source2, prop)) { + if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors2) { + const errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget); + if (!errorNode) return Debug.fail(); + if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode) || isJsxOpeningLikeElement(errorNode.parent)) { + if (prop.valueDeclaration && isJsxAttribute(prop.valueDeclaration) && getSourceFileOfNode(errorNode) === getSourceFileOfNode(prop.valueDeclaration.name)) { + errorNode = prop.valueDeclaration.name; + } + const propName = symbolToString(prop); + const suggestionSymbol = getSuggestedSymbolForNonexistentJSXAttribute(propName, errorTarget); + const suggestion = suggestionSymbol ? symbolToString(suggestionSymbol) : void 0; + if (suggestion) { + reportError(Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(errorTarget), suggestion); + } else { + reportError(Diagnostics.Property_0_does_not_exist_on_type_1, propName, typeToString(errorTarget)); + } + } else { + const objectLiteralDeclaration = ((_a2 = source2.symbol) == null ? void 0 : _a2.declarations) && firstOrUndefined(source2.symbol.declarations); + let suggestion; + if (prop.valueDeclaration && findAncestor(prop.valueDeclaration, (d) => d === objectLiteralDeclaration) && getSourceFileOfNode(objectLiteralDeclaration) === getSourceFileOfNode(errorNode)) { + const propDeclaration = prop.valueDeclaration; + Debug.assertNode(propDeclaration, isObjectLiteralElementLike); + const name = propDeclaration.name; + errorNode = name; + if (isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, errorTarget); + } + } + if (suggestion !== void 0) { + reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); + } else { + reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget)); + } + } + } + return true; + } + if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), 3 /* Both */, reportErrors2)) { + if (reportErrors2) { + reportIncompatibleError(Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop)); + } + return true; + } + } + } + return false; + } + function shouldCheckAsExcessProperty(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; + } + function unionOrIntersectionRelatedTo(source2, target2, reportErrors2, intersectionState) { + if (source2.flags & 1048576 /* Union */) { + if (target2.flags & 1048576 /* Union */) { + const sourceOrigin = source2.origin; + if (sourceOrigin && sourceOrigin.flags & 2097152 /* Intersection */ && target2.aliasSymbol && contains(sourceOrigin.types, target2)) { + return -1 /* True */; + } + const targetOrigin = target2.origin; + if (targetOrigin && targetOrigin.flags & 1048576 /* Union */ && source2.aliasSymbol && contains(targetOrigin.types, source2)) { + return -1 /* True */; + } + } + return relation === comparableRelation ? someTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */), intersectionState) : eachTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */), intersectionState); + } + if (target2.flags & 1048576 /* Union */) { + return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source2), target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */) && !(target2.flags & 402784252 /* Primitive */), intersectionState); + } + if (target2.flags & 2097152 /* Intersection */) { + return typeRelatedToEachType(source2, target2, reportErrors2, 2 /* Target */); + } + if (relation === comparableRelation && target2.flags & 402784252 /* Primitive */) { + const constraints = sameMap(source2.types, (t) => t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(t) || unknownType : t); + if (constraints !== source2.types) { + source2 = getIntersectionType(constraints); + if (source2.flags & 131072 /* Never */) { + return 0 /* False */; + } + if (!(source2.flags & 2097152 /* Intersection */)) { + return isRelatedTo( + source2, + target2, + 1 /* Source */, + /*reportErrors*/ + false + ) || isRelatedTo( + target2, + source2, + 1 /* Source */, + /*reportErrors*/ + false + ); + } + } + } + return someTypeRelatedToType( + source2, + target2, + /*reportErrors*/ + false, + 1 /* Source */ + ); + } + function eachTypeRelatedToSomeType(source2, target2) { + let result2 = -1 /* True */; + const sourceTypes = source2.types; + for (const sourceType of sourceTypes) { + const related = typeRelatedToSomeType( + sourceType, + target2, + /*reportErrors*/ + false, + 0 /* None */ + ); + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + return result2; + } + function typeRelatedToSomeType(source2, target2, reportErrors2, intersectionState) { + const targetTypes = target2.types; + if (target2.flags & 1048576 /* Union */) { + if (containsType(targetTypes, source2)) { + return -1 /* True */; + } + if (relation !== comparableRelation && getObjectFlags(target2) & 32768 /* PrimitiveUnion */ && !(source2.flags & 1024 /* EnumLiteral */) && (source2.flags & (128 /* StringLiteral */ | 512 /* BooleanLiteral */ | 2048 /* BigIntLiteral */) || (relation === subtypeRelation || relation === strictSubtypeRelation) && source2.flags & 256 /* NumberLiteral */)) { + const alternateForm = source2 === source2.regularType ? source2.freshType : source2.regularType; + const primitive = source2.flags & 128 /* StringLiteral */ ? stringType : source2.flags & 256 /* NumberLiteral */ ? numberType : source2.flags & 2048 /* BigIntLiteral */ ? bigintType : void 0; + return primitive && containsType(targetTypes, primitive) || alternateForm && containsType(targetTypes, alternateForm) ? -1 /* True */ : 0 /* False */; + } + const match = getMatchingUnionConstituentForType(target2, source2); + if (match) { + const related = isRelatedTo( + source2, + match, + 2 /* Target */, + /*reportErrors*/ + false, + /*headMessage*/ + void 0, + intersectionState + ); + if (related) { + return related; + } + } + } + for (const type of targetTypes) { + const related = isRelatedTo( + source2, + type, + 2 /* Target */, + /*reportErrors*/ + false, + /*headMessage*/ + void 0, + intersectionState + ); + if (related) { + return related; + } + } + if (reportErrors2) { + const bestMatchingType = getBestMatchingType(source2, target2, isRelatedTo); + if (bestMatchingType) { + isRelatedTo( + source2, + bestMatchingType, + 2 /* Target */, + /*reportErrors*/ + true, + /*headMessage*/ + void 0, + intersectionState + ); + } + } + return 0 /* False */; + } + function typeRelatedToEachType(source2, target2, reportErrors2, intersectionState) { + let result2 = -1 /* True */; + const targetTypes = target2.types; + for (const targetType of targetTypes) { + const related = isRelatedTo( + source2, + targetType, + 2 /* Target */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + return result2; + } + function someTypeRelatedToType(source2, target2, reportErrors2, intersectionState) { + const sourceTypes = source2.types; + if (source2.flags & 1048576 /* Union */ && containsType(sourceTypes, target2)) { + return -1 /* True */; + } + const len = sourceTypes.length; + for (let i = 0; i < len; i++) { + const related = isRelatedTo( + sourceTypes[i], + target2, + 1 /* Source */, + reportErrors2 && i === len - 1, + /*headMessage*/ + void 0, + intersectionState + ); + if (related) { + return related; + } + } + return 0 /* False */; + } + function getUndefinedStrippedTargetIfNeeded(source2, target2) { + if (source2.flags & 1048576 /* Union */ && target2.flags & 1048576 /* Union */ && !(source2.types[0].flags & 32768 /* Undefined */) && target2.types[0].flags & 32768 /* Undefined */) { + return extractTypesOfKind(target2, ~32768 /* Undefined */); + } + return target2; + } + function eachTypeRelatedToType(source2, target2, reportErrors2, intersectionState) { + let result2 = -1 /* True */; + const sourceTypes = source2.types; + const undefinedStrippedTarget = getUndefinedStrippedTargetIfNeeded(source2, target2); + for (let i = 0; i < sourceTypes.length; i++) { + const sourceType = sourceTypes[i]; + if (undefinedStrippedTarget.flags & 1048576 /* Union */ && sourceTypes.length >= undefinedStrippedTarget.types.length && sourceTypes.length % undefinedStrippedTarget.types.length === 0) { + const related2 = isRelatedTo( + sourceType, + undefinedStrippedTarget.types[i % undefinedStrippedTarget.types.length], + 3 /* Both */, + /*reportErrors*/ + false, + /*headMessage*/ + void 0, + intersectionState + ); + if (related2) { + result2 &= related2; + continue; + } + } + const related = isRelatedTo( + sourceType, + target2, + 1 /* Source */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + return result2; + } + function typeArgumentsRelatedTo(sources = emptyArray, targets = emptyArray, variances = emptyArray, reportErrors2, intersectionState) { + if (sources.length !== targets.length && relation === identityRelation) { + return 0 /* False */; + } + const length2 = sources.length <= targets.length ? sources.length : targets.length; + let result2 = -1 /* True */; + for (let i = 0; i < length2; i++) { + const varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */; + const variance = varianceFlags & 7 /* VarianceMask */; + if (variance !== 4 /* Independent */) { + const s = sources[i]; + const t = targets[i]; + let related = -1 /* True */; + if (varianceFlags & 8 /* Unmeasurable */) { + related = relation === identityRelation ? isRelatedTo( + s, + t, + 3 /* Both */, + /*reportErrors*/ + false + ) : compareTypesIdentical(s, t); + } else if (variance === 1 /* Covariant */) { + related = isRelatedTo( + s, + t, + 3 /* Both */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + } else if (variance === 2 /* Contravariant */) { + related = isRelatedTo( + t, + s, + 3 /* Both */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + } else if (variance === 3 /* Bivariant */) { + related = isRelatedTo( + t, + s, + 3 /* Both */, + /*reportErrors*/ + false + ); + if (!related) { + related = isRelatedTo( + s, + t, + 3 /* Both */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + } + } else { + related = isRelatedTo( + s, + t, + 3 /* Both */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + if (related) { + related &= isRelatedTo( + t, + s, + 3 /* Both */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + } + } + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + } + return result2; + } + function recursiveTypeRelatedTo(source2, target2, reportErrors2, intersectionState, recursionFlags) { + var _a2, _b, _c; + if (overflow) { + return 0 /* False */; + } + const id = getRelationKey( + source2, + target2, + intersectionState, + relation, + /*ignoreConstraints*/ + false + ); + const entry = relation.get(id); + if (entry !== void 0) { + if (reportErrors2 && entry & 2 /* Failed */ && !(entry & 96 /* Overflow */)) { + } else { + if (outofbandVarianceMarkerHandler) { + const saved = entry & 24 /* ReportsMask */; + if (saved & 8 /* ReportsUnmeasurable */) { + instantiateType(source2, reportUnmeasurableMapper); + } + if (saved & 16 /* ReportsUnreliable */) { + instantiateType(source2, reportUnreliableMapper); + } + } + if (reportErrors2 && entry & 96 /* Overflow */) { + const message = entry & 32 /* ComplexityOverflow */ ? Diagnostics.Excessive_complexity_comparing_types_0_and_1 : Diagnostics.Excessive_stack_depth_comparing_types_0_and_1; + reportError(message, typeToString(source2), typeToString(target2)); + overrideNextErrorInfo++; + } + return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } + } + if (relationCount <= 0) { + overflow = true; + return 0 /* False */; + } + if (!maybeKeys) { + maybeKeys = []; + maybeKeysSet = /* @__PURE__ */ new Set(); + sourceStack = []; + targetStack = []; + } else { + if (maybeKeysSet.has(id)) { + return 3 /* Maybe */; + } + const broadestEquivalentId = id.startsWith("*") ? getRelationKey( + source2, + target2, + intersectionState, + relation, + /*ignoreConstraints*/ + true + ) : void 0; + if (broadestEquivalentId && maybeKeysSet.has(broadestEquivalentId)) { + return 3 /* Maybe */; + } + if (sourceDepth === 100 || targetDepth === 100) { + overflow = true; + return 0 /* False */; + } + } + const maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeKeysSet.add(id); + maybeCount++; + const saveExpandingFlags = expandingFlags; + if (recursionFlags & 1 /* Source */) { + sourceStack[sourceDepth] = source2; + sourceDepth++; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source2, sourceStack, sourceDepth)) expandingFlags |= 1 /* Source */; + } + if (recursionFlags & 2 /* Target */) { + targetStack[targetDepth] = target2; + targetDepth++; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target2, targetStack, targetDepth)) expandingFlags |= 2 /* Target */; + } + let originalHandler; + let propagatingVarianceFlags = 0; + if (outofbandVarianceMarkerHandler) { + originalHandler = outofbandVarianceMarkerHandler; + outofbandVarianceMarkerHandler = (onlyUnreliable) => { + propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */; + return originalHandler(onlyUnreliable); + }; + } + let result2; + if (expandingFlags === 3 /* Both */) { + (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "recursiveTypeRelatedTo_DepthLimit", { + sourceId: source2.id, + sourceIdStack: sourceStack.map((t) => t.id), + targetId: target2.id, + targetIdStack: targetStack.map((t) => t.id), + depth: sourceDepth, + targetDepth + }); + result2 = 3 /* Maybe */; + } else { + (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.CheckTypes, "structuredTypeRelatedTo", { sourceId: source2.id, targetId: target2.id }); + result2 = structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState); + (_c = tracing) == null ? void 0 : _c.pop(); + } + if (outofbandVarianceMarkerHandler) { + outofbandVarianceMarkerHandler = originalHandler; + } + if (recursionFlags & 1 /* Source */) { + sourceDepth--; + } + if (recursionFlags & 2 /* Target */) { + targetDepth--; + } + expandingFlags = saveExpandingFlags; + if (result2) { + if (result2 === -1 /* True */ || sourceDepth === 0 && targetDepth === 0) { + if (result2 === -1 /* True */ || result2 === 3 /* Maybe */) { + resetMaybeStack( + /*markAllAsSucceeded*/ + true + ); + } else { + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); + } + } + } else { + relation.set(id, 2 /* Failed */ | propagatingVarianceFlags); + relationCount--; + resetMaybeStack( + /*markAllAsSucceeded*/ + false + ); + } + return result2; + function resetMaybeStack(markAllAsSucceeded) { + for (let i = maybeStart; i < maybeCount; i++) { + maybeKeysSet.delete(maybeKeys[i]); + if (markAllAsSucceeded) { + relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags); + relationCount--; + } + } + maybeCount = maybeStart; + } + } + function structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState) { + const saveErrorInfo = captureErrorCalculationState(); + let result2 = structuredTypeRelatedToWorker(source2, target2, reportErrors2, intersectionState, saveErrorInfo); + if (relation !== identityRelation) { + if (!result2 && (source2.flags & 2097152 /* Intersection */ || source2.flags & 262144 /* TypeParameter */ && target2.flags & 1048576 /* Union */)) { + const constraint = getEffectiveConstraintOfIntersection(source2.flags & 2097152 /* Intersection */ ? source2.types : [source2], !!(target2.flags & 1048576 /* Union */)); + if (constraint && everyType(constraint, (c) => c !== source2)) { + result2 = isRelatedTo( + constraint, + target2, + 1 /* Source */, + /*reportErrors*/ + false, + /*headMessage*/ + void 0, + intersectionState + ); + } + } + if (result2 && !(intersectionState & 2 /* Target */) && target2.flags & 2097152 /* Intersection */ && !isGenericObjectType(target2) && source2.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + result2 &= propertiesRelatedTo( + source2, + target2, + reportErrors2, + /*excludedProperties*/ + void 0, + /*optionalsOnly*/ + false, + 0 /* None */ + ); + if (result2 && isObjectLiteralType(source2) && getObjectFlags(source2) & 8192 /* FreshLiteral */) { + result2 &= indexSignaturesRelatedTo( + source2, + target2, + /*sourceIsPrimitive*/ + false, + reportErrors2, + 0 /* None */ + ); + } + } else if (result2 && isNonGenericObjectType(target2) && !isArrayOrTupleType(target2) && source2.flags & 2097152 /* Intersection */ && getApparentType(source2).flags & 3670016 /* StructuredType */ && !some(source2.types, (t) => t === target2 || !!(getObjectFlags(t) & 262144 /* NonInferrableType */))) { + result2 &= propertiesRelatedTo( + source2, + target2, + reportErrors2, + /*excludedProperties*/ + void 0, + /*optionalsOnly*/ + true, + intersectionState + ); + } + } + if (result2) { + resetErrorInfo(saveErrorInfo); + } + return result2; + } + function getApparentMappedTypeKeys(nameType, targetType) { + const modifiersType = getApparentType(getModifiersTypeFromMappedType(targetType)); + const mappedKeys = []; + forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType( + modifiersType, + 8576 /* StringOrNumberLiteralOrUnique */, + /*stringsOnly*/ + false, + (t) => void mappedKeys.push(instantiateType(nameType, appendTypeMapping(targetType.mapper, getTypeParameterFromMappedType(targetType), t))) + ); + return getUnionType(mappedKeys); + } + function structuredTypeRelatedToWorker(source2, target2, reportErrors2, intersectionState, saveErrorInfo) { + let result2; + let originalErrorInfo; + let varianceCheckFailed = false; + let sourceFlags = source2.flags; + const targetFlags = target2.flags; + if (relation === identityRelation) { + if (sourceFlags & 3145728 /* UnionOrIntersection */) { + let result3 = eachTypeRelatedToSomeType(source2, target2); + if (result3) { + result3 &= eachTypeRelatedToSomeType(target2, source2); + } + return result3; + } + if (sourceFlags & 4194304 /* Index */) { + return isRelatedTo( + source2.type, + target2.type, + 3 /* Both */, + /*reportErrors*/ + false + ); + } + if (sourceFlags & 8388608 /* IndexedAccess */) { + if (result2 = isRelatedTo( + source2.objectType, + target2.objectType, + 3 /* Both */, + /*reportErrors*/ + false + )) { + if (result2 &= isRelatedTo( + source2.indexType, + target2.indexType, + 3 /* Both */, + /*reportErrors*/ + false + )) { + return result2; + } + } + } + if (sourceFlags & 16777216 /* Conditional */) { + if (source2.root.isDistributive === target2.root.isDistributive) { + if (result2 = isRelatedTo( + source2.checkType, + target2.checkType, + 3 /* Both */, + /*reportErrors*/ + false + )) { + if (result2 &= isRelatedTo( + source2.extendsType, + target2.extendsType, + 3 /* Both */, + /*reportErrors*/ + false + )) { + if (result2 &= isRelatedTo( + getTrueTypeFromConditionalType(source2), + getTrueTypeFromConditionalType(target2), + 3 /* Both */, + /*reportErrors*/ + false + )) { + if (result2 &= isRelatedTo( + getFalseTypeFromConditionalType(source2), + getFalseTypeFromConditionalType(target2), + 3 /* Both */, + /*reportErrors*/ + false + )) { + return result2; + } + } + } + } + } + } + if (sourceFlags & 33554432 /* Substitution */) { + if (result2 = isRelatedTo( + source2.baseType, + target2.baseType, + 3 /* Both */, + /*reportErrors*/ + false + )) { + if (result2 &= isRelatedTo( + source2.constraint, + target2.constraint, + 3 /* Both */, + /*reportErrors*/ + false + )) { + return result2; + } + } + } + if (!(sourceFlags & 524288 /* Object */)) { + return 0 /* False */; + } + } else if (sourceFlags & 3145728 /* UnionOrIntersection */ || targetFlags & 3145728 /* UnionOrIntersection */) { + if (result2 = unionOrIntersectionRelatedTo(source2, target2, reportErrors2, intersectionState)) { + return result2; + } + if (!(sourceFlags & 465829888 /* Instantiable */ || sourceFlags & 524288 /* Object */ && targetFlags & 1048576 /* Union */ || sourceFlags & 2097152 /* Intersection */ && targetFlags & (524288 /* Object */ | 1048576 /* Union */ | 465829888 /* Instantiable */))) { + return 0 /* False */; + } + } + if (sourceFlags & (524288 /* Object */ | 16777216 /* Conditional */) && source2.aliasSymbol && source2.aliasTypeArguments && source2.aliasSymbol === target2.aliasSymbol && !(isMarkerType(source2) || isMarkerType(target2))) { + const variances = getAliasVariances(source2.aliasSymbol); + if (variances === emptyArray) { + return 1 /* Unknown */; + } + const params = getSymbolLinks(source2.aliasSymbol).typeParameters; + const minParams = getMinTypeArgumentCount(params); + const sourceTypes = fillMissingTypeArguments(source2.aliasTypeArguments, params, minParams, isInJSFile(source2.aliasSymbol.valueDeclaration)); + const targetTypes = fillMissingTypeArguments(target2.aliasTypeArguments, params, minParams, isInJSFile(source2.aliasSymbol.valueDeclaration)); + const varianceResult = relateVariances(sourceTypes, targetTypes, variances, intersectionState); + if (varianceResult !== void 0) { + return varianceResult; + } + } + if (isSingleElementGenericTupleType(source2) && !source2.target.readonly && (result2 = isRelatedTo(getTypeArguments(source2)[0], target2, 1 /* Source */)) || isSingleElementGenericTupleType(target2) && (target2.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source2) || source2)) && (result2 = isRelatedTo(source2, getTypeArguments(target2)[0], 2 /* Target */))) { + return result2; + } + if (targetFlags & 262144 /* TypeParameter */) { + if (getObjectFlags(source2) & 32 /* Mapped */ && !source2.declaration.nameType && isRelatedTo(getIndexType(target2), getConstraintTypeFromMappedType(source2), 3 /* Both */)) { + if (!(getMappedTypeModifiers(source2) & 4 /* IncludeOptional */)) { + const templateType = getTemplateTypeFromMappedType(source2); + const indexedAccessType = getIndexedAccessType(target2, getTypeParameterFromMappedType(source2)); + if (result2 = isRelatedTo(templateType, indexedAccessType, 3 /* Both */, reportErrors2)) { + return result2; + } + } + } + if (relation === comparableRelation && sourceFlags & 262144 /* TypeParameter */) { + let constraint = getConstraintOfTypeParameter(source2); + if (constraint) { + while (constraint && someType(constraint, (c) => !!(c.flags & 262144 /* TypeParameter */))) { + if (result2 = isRelatedTo( + constraint, + target2, + 1 /* Source */, + /*reportErrors*/ + false + )) { + return result2; + } + constraint = getConstraintOfTypeParameter(constraint); + } + } + return 0 /* False */; + } + } else if (targetFlags & 4194304 /* Index */) { + const targetType = target2.type; + if (sourceFlags & 4194304 /* Index */) { + if (result2 = isRelatedTo( + targetType, + source2.type, + 3 /* Both */, + /*reportErrors*/ + false + )) { + return result2; + } + } + if (isTupleType(targetType)) { + if (result2 = isRelatedTo(source2, getKnownKeysOfTupleType(targetType), 2 /* Target */, reportErrors2)) { + return result2; + } + } else { + const constraint = getSimplifiedTypeOrConstraint(targetType); + if (constraint) { + if (isRelatedTo(source2, getIndexType(constraint, target2.indexFlags | 4 /* NoReducibleCheck */), 2 /* Target */, reportErrors2) === -1 /* True */) { + return -1 /* True */; + } + } else if (isGenericMappedType(targetType)) { + const nameType = getNameTypeFromMappedType(targetType); + const constraintType = getConstraintTypeFromMappedType(targetType); + let targetKeys; + if (nameType && isMappedTypeWithKeyofConstraintDeclaration(targetType)) { + const mappedKeys = getApparentMappedTypeKeys(nameType, targetType); + targetKeys = getUnionType([mappedKeys, nameType]); + } else { + targetKeys = nameType || constraintType; + } + if (isRelatedTo(source2, targetKeys, 2 /* Target */, reportErrors2) === -1 /* True */) { + return -1 /* True */; + } + } + } + } else if (targetFlags & 8388608 /* IndexedAccess */) { + if (sourceFlags & 8388608 /* IndexedAccess */) { + if (result2 = isRelatedTo(source2.objectType, target2.objectType, 3 /* Both */, reportErrors2)) { + result2 &= isRelatedTo(source2.indexType, target2.indexType, 3 /* Both */, reportErrors2); + } + if (result2) { + return result2; + } + if (reportErrors2) { + originalErrorInfo = errorInfo; + } + } + if (relation === assignableRelation || relation === comparableRelation) { + const objectType = target2.objectType; + const indexType = target2.indexType; + const baseObjectType = getBaseConstraintOfType(objectType) || objectType; + const baseIndexType = getBaseConstraintOfType(indexType) || indexType; + if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { + const accessFlags = 4 /* Writing */ | (baseObjectType !== objectType ? 2 /* NoIndexSignatures */ : 0); + const constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, accessFlags); + if (constraint) { + if (reportErrors2 && originalErrorInfo) { + resetErrorInfo(saveErrorInfo); + } + if (result2 = isRelatedTo( + source2, + constraint, + 2 /* Target */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + )) { + return result2; + } + if (reportErrors2 && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } + } + } + } + if (reportErrors2) { + originalErrorInfo = void 0; + } + } else if (isGenericMappedType(target2) && relation !== identityRelation) { + const keysRemapped = !!target2.declaration.nameType; + const templateType = getTemplateTypeFromMappedType(target2); + const modifiers = getMappedTypeModifiers(target2); + if (!(modifiers & 8 /* ExcludeOptional */)) { + if (!keysRemapped && templateType.flags & 8388608 /* IndexedAccess */ && templateType.objectType === source2 && templateType.indexType === getTypeParameterFromMappedType(target2)) { + return -1 /* True */; + } + if (!isGenericMappedType(source2)) { + const targetKeys = keysRemapped ? getNameTypeFromMappedType(target2) : getConstraintTypeFromMappedType(target2); + const sourceKeys = getIndexType(source2, 2 /* NoIndexSignatures */); + const includeOptional = modifiers & 4 /* IncludeOptional */; + const filteredByApplicability = includeOptional ? intersectTypes(targetKeys, sourceKeys) : void 0; + if (includeOptional ? !(filteredByApplicability.flags & 131072 /* Never */) : isRelatedTo(targetKeys, sourceKeys, 3 /* Both */)) { + const templateType2 = getTemplateTypeFromMappedType(target2); + const typeParameter = getTypeParameterFromMappedType(target2); + const nonNullComponent = extractTypesOfKind(templateType2, ~98304 /* Nullable */); + if (!keysRemapped && nonNullComponent.flags & 8388608 /* IndexedAccess */ && nonNullComponent.indexType === typeParameter) { + if (result2 = isRelatedTo(source2, nonNullComponent.objectType, 2 /* Target */, reportErrors2)) { + return result2; + } + } else { + const indexingType = keysRemapped ? filteredByApplicability || targetKeys : filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter; + const indexedAccessType = getIndexedAccessType(source2, indexingType); + if (result2 = isRelatedTo(indexedAccessType, templateType2, 3 /* Both */, reportErrors2)) { + return result2; + } + } + } + originalErrorInfo = errorInfo; + resetErrorInfo(saveErrorInfo); + } + } + } else if (targetFlags & 16777216 /* Conditional */) { + if (isDeeplyNestedType(target2, targetStack, targetDepth, 10)) { + return 3 /* Maybe */; + } + const c = target2; + if (!c.root.inferTypeParameters && !isDistributionDependent(c.root) && !(source2.flags & 16777216 /* Conditional */ && source2.root === c.root)) { + const skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + const skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); + if (result2 = skipTrue ? -1 /* True */ : isRelatedTo( + source2, + getTrueTypeFromConditionalType(c), + 2 /* Target */, + /*reportErrors*/ + false, + /*headMessage*/ + void 0, + intersectionState + )) { + result2 &= skipFalse ? -1 /* True */ : isRelatedTo( + source2, + getFalseTypeFromConditionalType(c), + 2 /* Target */, + /*reportErrors*/ + false, + /*headMessage*/ + void 0, + intersectionState + ); + if (result2) { + return result2; + } + } + } + } else if (targetFlags & 134217728 /* TemplateLiteral */) { + if (sourceFlags & 134217728 /* TemplateLiteral */) { + if (relation === comparableRelation) { + return templateLiteralTypesDefinitelyUnrelated(source2, target2) ? 0 /* False */ : -1 /* True */; + } + instantiateType(source2, reportUnreliableMapper); + } + if (isTypeMatchedByTemplateLiteralType(source2, target2)) { + return -1 /* True */; + } + } else if (target2.flags & 268435456 /* StringMapping */) { + if (!(source2.flags & 268435456 /* StringMapping */)) { + if (isMemberOfStringMapping(source2, target2)) { + return -1 /* True */; + } + } + } + if (sourceFlags & 8650752 /* TypeVariable */) { + if (!(sourceFlags & 8388608 /* IndexedAccess */ && targetFlags & 8388608 /* IndexedAccess */)) { + const constraint = getConstraintOfType(source2) || unknownType; + if (result2 = isRelatedTo( + constraint, + target2, + 1 /* Source */, + /*reportErrors*/ + false, + /*headMessage*/ + void 0, + intersectionState + )) { + return result2; + } else if (result2 = isRelatedTo( + getTypeWithThisArgument(constraint, source2), + target2, + 1 /* Source */, + reportErrors2 && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* TypeParameter */), + /*headMessage*/ + void 0, + intersectionState + )) { + return result2; + } + if (isMappedTypeGenericIndexedAccess(source2)) { + const indexConstraint = getConstraintOfType(source2.indexType); + if (indexConstraint) { + if (result2 = isRelatedTo(getIndexedAccessType(source2.objectType, indexConstraint), target2, 1 /* Source */, reportErrors2)) { + return result2; + } + } + } + } + } else if (sourceFlags & 4194304 /* Index */) { + const isDeferredMappedIndex = shouldDeferIndexType(source2.type, source2.indexFlags) && getObjectFlags(source2.type) & 32 /* Mapped */; + if (result2 = isRelatedTo(stringNumberSymbolType, target2, 1 /* Source */, reportErrors2 && !isDeferredMappedIndex)) { + return result2; + } + if (isDeferredMappedIndex) { + const mappedType = source2.type; + const nameType = getNameTypeFromMappedType(mappedType); + const sourceMappedKeys = nameType && isMappedTypeWithKeyofConstraintDeclaration(mappedType) ? getApparentMappedTypeKeys(nameType, mappedType) : nameType || getConstraintTypeFromMappedType(mappedType); + if (result2 = isRelatedTo(sourceMappedKeys, target2, 1 /* Source */, reportErrors2)) { + return result2; + } + } + } else if (sourceFlags & 134217728 /* TemplateLiteral */ && !(targetFlags & 524288 /* Object */)) { + if (!(targetFlags & 134217728 /* TemplateLiteral */)) { + const constraint = getBaseConstraintOfType(source2); + if (constraint && constraint !== source2 && (result2 = isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2))) { + return result2; + } + } + } else if (sourceFlags & 268435456 /* StringMapping */) { + if (targetFlags & 268435456 /* StringMapping */) { + if (source2.symbol !== target2.symbol) { + return 0 /* False */; + } + if (result2 = isRelatedTo(source2.type, target2.type, 3 /* Both */, reportErrors2)) { + return result2; + } + } else { + const constraint = getBaseConstraintOfType(source2); + if (constraint && (result2 = isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2))) { + return result2; + } + } + } else if (sourceFlags & 16777216 /* Conditional */) { + if (isDeeplyNestedType(source2, sourceStack, sourceDepth, 10)) { + return 3 /* Maybe */; + } + if (targetFlags & 16777216 /* Conditional */) { + const sourceParams = source2.root.inferTypeParameters; + let sourceExtends = source2.extendsType; + let mapper; + if (sourceParams) { + const ctx = createInferenceContext( + sourceParams, + /*signature*/ + void 0, + 0 /* None */, + isRelatedToWorker + ); + inferTypes(ctx.inferences, target2.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); + sourceExtends = instantiateType(sourceExtends, ctx.mapper); + mapper = ctx.mapper; + } + if (isTypeIdenticalTo(sourceExtends, target2.extendsType) && (isRelatedTo(source2.checkType, target2.checkType, 3 /* Both */) || isRelatedTo(target2.checkType, source2.checkType, 3 /* Both */))) { + if (result2 = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source2), mapper), getTrueTypeFromConditionalType(target2), 3 /* Both */, reportErrors2)) { + result2 &= isRelatedTo(getFalseTypeFromConditionalType(source2), getFalseTypeFromConditionalType(target2), 3 /* Both */, reportErrors2); + } + if (result2) { + return result2; + } + } + } + const defaultConstraint = getDefaultConstraintOfConditionalType(source2); + if (defaultConstraint) { + if (result2 = isRelatedTo(defaultConstraint, target2, 1 /* Source */, reportErrors2)) { + return result2; + } + } + const distributiveConstraint = !(targetFlags & 16777216 /* Conditional */) && hasNonCircularBaseConstraint(source2) ? getConstraintOfDistributiveConditionalType(source2) : void 0; + if (distributiveConstraint) { + resetErrorInfo(saveErrorInfo); + if (result2 = isRelatedTo(distributiveConstraint, target2, 1 /* Source */, reportErrors2)) { + return result2; + } + } + } else { + if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target2) && isEmptyObjectType(source2)) { + return -1 /* True */; + } + if (isGenericMappedType(target2)) { + if (isGenericMappedType(source2)) { + if (result2 = mappedTypeRelatedTo(source2, target2, reportErrors2)) { + return result2; + } + } + return 0 /* False */; + } + const sourceIsPrimitive = !!(sourceFlags & 402784252 /* Primitive */); + if (relation !== identityRelation) { + source2 = getApparentType(source2); + sourceFlags = source2.flags; + } else if (isGenericMappedType(source2)) { + return 0 /* False */; + } + if (getObjectFlags(source2) & 4 /* Reference */ && getObjectFlags(target2) & 4 /* Reference */ && source2.target === target2.target && !isTupleType(source2) && !(isMarkerType(source2) || isMarkerType(target2))) { + if (isEmptyArrayLiteralType(source2)) { + return -1 /* True */; + } + const variances = getVariances(source2.target); + if (variances === emptyArray) { + return 1 /* Unknown */; + } + const varianceResult = relateVariances(getTypeArguments(source2), getTypeArguments(target2), variances, intersectionState); + if (varianceResult !== void 0) { + return varianceResult; + } + } else if (isReadonlyArrayType(target2) ? everyType(source2, isArrayOrTupleType) : isArrayType(target2) && everyType(source2, (t) => isTupleType(t) && !t.target.readonly)) { + if (relation !== identityRelation) { + return isRelatedTo(getIndexTypeOfType(source2, numberType) || anyType, getIndexTypeOfType(target2, numberType) || anyType, 3 /* Both */, reportErrors2); + } else { + return 0 /* False */; + } + } else if (isGenericTupleType(source2) && isTupleType(target2) && !isGenericTupleType(target2)) { + const constraint = getBaseConstraintOrType(source2); + if (constraint !== source2) { + return isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2); + } + } else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target2) && getObjectFlags(target2) & 8192 /* FreshLiteral */ && !isEmptyObjectType(source2)) { + return 0 /* False */; + } + if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 524288 /* Object */) { + const reportStructuralErrors = reportErrors2 && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive; + result2 = propertiesRelatedTo( + source2, + target2, + reportStructuralErrors, + /*excludedProperties*/ + void 0, + /*optionalsOnly*/ + false, + intersectionState + ); + if (result2) { + result2 &= signaturesRelatedTo(source2, target2, 0 /* Call */, reportStructuralErrors, intersectionState); + if (result2) { + result2 &= signaturesRelatedTo(source2, target2, 1 /* Construct */, reportStructuralErrors, intersectionState); + if (result2) { + result2 &= indexSignaturesRelatedTo(source2, target2, sourceIsPrimitive, reportStructuralErrors, intersectionState); + } + } + } + if (varianceCheckFailed && result2) { + errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; + } else if (result2) { + return result2; + } + } + if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 1048576 /* Union */) { + const objectOnlyTarget = extractTypesOfKind(target2, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); + if (objectOnlyTarget.flags & 1048576 /* Union */) { + const result3 = typeRelatedToDiscriminatedType(source2, objectOnlyTarget); + if (result3) { + return result3; + } + } + } + } + return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) return 0; + return reduceLeft(info, (value, chain) => value + 1 + countMessageChainBreadth(chain.next), 0); + } + function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState2) { + if (result2 = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors2, intersectionState2)) { + return result2; + } + if (some(variances, (v) => !!(v & 24 /* AllowsStructuralFallback */))) { + originalErrorInfo = void 0; + resetErrorInfo(saveErrorInfo); + return void 0; + } + const allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances); + varianceCheckFailed = !allowStructuralFallback; + if (variances !== emptyArray && !allowStructuralFallback) { + if (varianceCheckFailed && !(reportErrors2 && some(variances, (v) => (v & 7 /* VarianceMask */) === 0 /* Invariant */))) { + return 0 /* False */; + } + originalErrorInfo = errorInfo; + resetErrorInfo(saveErrorInfo); + } + } + } + function mappedTypeRelatedTo(source2, target2, reportErrors2) { + const modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source2) === getMappedTypeModifiers(target2) : getCombinedMappedTypeOptionality(source2) <= getCombinedMappedTypeOptionality(target2)); + if (modifiersRelated) { + let result2; + const targetConstraint = getConstraintTypeFromMappedType(target2); + const sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source2), getCombinedMappedTypeOptionality(source2) < 0 ? reportUnmeasurableMapper : reportUnreliableMapper); + if (result2 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors2)) { + const mapper = createTypeMapper([getTypeParameterFromMappedType(source2)], [getTypeParameterFromMappedType(target2)]); + if (instantiateType(getNameTypeFromMappedType(source2), mapper) === instantiateType(getNameTypeFromMappedType(target2), mapper)) { + return result2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source2), mapper), getTemplateTypeFromMappedType(target2), 3 /* Both */, reportErrors2); + } + } + } + return 0 /* False */; + } + function typeRelatedToDiscriminatedType(source2, target2) { + var _a2; + const sourceProperties = getPropertiesOfType(source2); + const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target2); + if (!sourcePropertiesFiltered) return 0 /* False */; + let numCombinations = 1; + for (const sourceProperty of sourcePropertiesFiltered) { + numCombinations *= countTypes(getNonMissingTypeOfSymbol(sourceProperty)); + if (numCombinations > 25) { + (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source2.id, targetId: target2.id, numCombinations }); + return 0 /* False */; + } + } + const sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length); + const excludedProperties = /* @__PURE__ */ new Set(); + for (let i = 0; i < sourcePropertiesFiltered.length; i++) { + const sourceProperty = sourcePropertiesFiltered[i]; + const sourcePropertyType = getNonMissingTypeOfSymbol(sourceProperty); + sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */ ? sourcePropertyType.types : [sourcePropertyType]; + excludedProperties.add(sourceProperty.escapedName); + } + const discriminantCombinations = cartesianProduct(sourceDiscriminantTypes); + const matchingTypes = []; + for (const combination of discriminantCombinations) { + let hasMatch = false; + outer: + for (const type of target2.types) { + for (let i = 0; i < sourcePropertiesFiltered.length; i++) { + const sourceProperty = sourcePropertiesFiltered[i]; + const targetProperty = getPropertyOfType(type, sourceProperty.escapedName); + if (!targetProperty) continue outer; + if (sourceProperty === targetProperty) continue; + const related = propertyRelatedTo( + source2, + target2, + sourceProperty, + targetProperty, + (_) => combination[i], + /*reportErrors*/ + false, + 0 /* None */, + /*skipOptional*/ + strictNullChecks || relation === comparableRelation + ); + if (!related) { + continue outer; + } + } + pushIfUnique(matchingTypes, type, equateValues); + hasMatch = true; + } + if (!hasMatch) { + return 0 /* False */; + } + } + let result2 = -1 /* True */; + for (const type of matchingTypes) { + result2 &= propertiesRelatedTo( + source2, + type, + /*reportErrors*/ + false, + excludedProperties, + /*optionalsOnly*/ + false, + 0 /* None */ + ); + if (result2) { + result2 &= signaturesRelatedTo( + source2, + type, + 0 /* Call */, + /*reportErrors*/ + false, + 0 /* None */ + ); + if (result2) { + result2 &= signaturesRelatedTo( + source2, + type, + 1 /* Construct */, + /*reportErrors*/ + false, + 0 /* None */ + ); + if (result2 && !(isTupleType(source2) && isTupleType(type))) { + result2 &= indexSignaturesRelatedTo( + source2, + type, + /*sourceIsPrimitive*/ + false, + /*reportErrors*/ + false, + 0 /* None */ + ); + } + } + } + if (!result2) { + return result2; + } + } + return result2; + } + function excludeProperties(properties, excludedProperties) { + if (!excludedProperties || properties.length === 0) return properties; + let result2; + for (let i = 0; i < properties.length; i++) { + if (!excludedProperties.has(properties[i].escapedName)) { + if (result2) { + result2.push(properties[i]); + } + } else if (!result2) { + result2 = properties.slice(0, i); + } + } + return result2 || properties; + } + function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors2, intersectionState) { + const targetIsOptional = strictNullChecks && !!(getCheckFlags(targetProp) & 48 /* Partial */); + const effectiveTarget = addOptionality( + getNonMissingTypeOfSymbol(targetProp), + /*isProperty*/ + false, + targetIsOptional + ); + const effectiveSource = getTypeOfSourceProperty(sourceProp); + return isRelatedTo( + effectiveSource, + effectiveTarget, + 3 /* Both */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + } + function propertyRelatedTo(source2, target2, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors2, intersectionState, skipOptional) { + const sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); + const targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 2 /* Private */ || targetPropFlags & 2 /* Private */) { + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { + if (reportErrors2) { + if (sourcePropFlags & 2 /* Private */ && targetPropFlags & 2 /* Private */) { + reportError(Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } else { + reportError(Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 2 /* Private */ ? source2 : target2), typeToString(sourcePropFlags & 2 /* Private */ ? target2 : source2)); + } + } + return 0 /* False */; + } + } else if (targetPropFlags & 4 /* Protected */) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors2) { + reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source2), typeToString(getDeclaringClass(targetProp) || target2)); + } + return 0 /* False */; + } + } else if (sourcePropFlags & 4 /* Protected */) { + if (reportErrors2) { + reportError(Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source2), typeToString(target2)); + } + return 0 /* False */; + } + if (relation === strictSubtypeRelation && isReadonlySymbol(sourceProp) && !isReadonlySymbol(targetProp)) { + return 0 /* False */; + } + const related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors2, intersectionState); + if (!related) { + if (reportErrors2) { + reportIncompatibleError(Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0 /* False */; + } + if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && targetProp.flags & 106500 /* ClassMember */ && !(targetProp.flags & 16777216 /* Optional */)) { + if (reportErrors2) { + reportError(Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source2), typeToString(target2)); + } + return 0 /* False */; + } + return related; + } + function reportUnmatchedProperty(source2, target2, unmatchedProperty, requireOptionalProperties) { + let shouldSkipElaboration = false; + if (unmatchedProperty.valueDeclaration && isNamedDeclaration(unmatchedProperty.valueDeclaration) && isPrivateIdentifier(unmatchedProperty.valueDeclaration.name) && source2.symbol && source2.symbol.flags & 32 /* Class */) { + const privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText; + const symbolTableKey = getSymbolNameForPrivateIdentifier(source2.symbol, privateIdentifierDescription); + if (symbolTableKey && getPropertyOfType(source2, symbolTableKey)) { + const sourceName = factory.getDeclarationName(source2.symbol.valueDeclaration); + const targetName = factory.getDeclarationName(target2.symbol.valueDeclaration); + reportError( + Diagnostics.Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2, + diagnosticName(privateIdentifierDescription), + diagnosticName(sourceName.escapedText === "" ? anon : sourceName), + diagnosticName(targetName.escapedText === "" ? anon : targetName) + ); + return; + } + } + const props = arrayFrom(getUnmatchedProperties( + source2, + target2, + requireOptionalProperties, + /*matchDiscriminantProperties*/ + false + )); + if (!headMessage || headMessage.code !== Diagnostics.Class_0_incorrectly_implements_interface_1.code && headMessage.code !== Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code) { + shouldSkipElaboration = true; + } + if (props.length === 1) { + const propName = symbolToString( + unmatchedProperty, + /*enclosingDeclaration*/ + void 0, + 0 /* None */, + 4 /* AllowAnyNodeKind */ | 16 /* WriteComputedProps */ + ); + reportError(Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, ...getTypeNamesForErrorDisplay(source2, target2)); + if (length(unmatchedProperty.declarations)) { + associateRelatedInfo(createDiagnosticForNode(unmatchedProperty.declarations[0], Diagnostics._0_is_declared_here, propName)); + } + if (shouldSkipElaboration && errorInfo) { + overrideNextErrorInfo++; + } + } else if (tryElaborateArrayLikeErrors( + source2, + target2, + /*reportErrors*/ + false + )) { + if (props.length > 5) { + reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source2), typeToString(target2), map(props.slice(0, 4), (p) => symbolToString(p)).join(", "), props.length - 4); + } else { + reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source2), typeToString(target2), map(props, (p) => symbolToString(p)).join(", ")); + } + if (shouldSkipElaboration && errorInfo) { + overrideNextErrorInfo++; + } + } + } + function propertiesRelatedTo(source2, target2, reportErrors2, excludedProperties, optionalsOnly, intersectionState) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source2, target2, excludedProperties); + } + let result2 = -1 /* True */; + if (isTupleType(target2)) { + if (isArrayOrTupleType(source2)) { + if (!target2.target.readonly && (isReadonlyArrayType(source2) || isTupleType(source2) && source2.target.readonly)) { + return 0 /* False */; + } + const sourceArity = getTypeReferenceArity(source2); + const targetArity = getTypeReferenceArity(target2); + const sourceRestFlag = isTupleType(source2) ? source2.target.combinedFlags & 4 /* Rest */ : 4 /* Rest */; + const targetHasRestElement = !!(target2.target.combinedFlags & 12 /* Variable */); + const sourceMinLength = isTupleType(source2) ? source2.target.minLength : 0; + const targetMinLength = target2.target.minLength; + if (!sourceRestFlag && sourceArity < targetMinLength) { + if (reportErrors2) { + reportError(Diagnostics.Source_has_0_element_s_but_target_requires_1, sourceArity, targetMinLength); + } + return 0 /* False */; + } + if (!targetHasRestElement && targetArity < sourceMinLength) { + if (reportErrors2) { + reportError(Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity); + } + return 0 /* False */; + } + if (!targetHasRestElement && (sourceRestFlag || targetArity < sourceArity)) { + if (reportErrors2) { + if (sourceMinLength < targetMinLength) { + reportError(Diagnostics.Target_requires_0_element_s_but_source_may_have_fewer, targetMinLength); + } else { + reportError(Diagnostics.Target_allows_only_0_element_s_but_source_may_have_more, targetArity); + } + } + return 0 /* False */; + } + const sourceTypeArguments = getTypeArguments(source2); + const targetTypeArguments = getTypeArguments(target2); + const targetStartCount = getStartElementCount(target2.target, 11 /* NonRest */); + const targetEndCount = getEndElementCount(target2.target, 11 /* NonRest */); + let canExcludeDiscriminants = !!excludedProperties; + for (let sourcePosition = 0; sourcePosition < sourceArity; sourcePosition++) { + const sourceFlags = isTupleType(source2) ? source2.target.elementFlags[sourcePosition] : 4 /* Rest */; + const sourcePositionFromEnd = sourceArity - 1 - sourcePosition; + const targetPosition = targetHasRestElement && sourcePosition >= targetStartCount ? targetArity - 1 - Math.min(sourcePositionFromEnd, targetEndCount) : sourcePosition; + const targetFlags = target2.target.elementFlags[targetPosition]; + if (targetFlags & 8 /* Variadic */ && !(sourceFlags & 8 /* Variadic */)) { + if (reportErrors2) { + reportError(Diagnostics.Source_provides_no_match_for_variadic_element_at_position_0_in_target, targetPosition); + } + return 0 /* False */; + } + if (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */)) { + if (reportErrors2) { + reportError(Diagnostics.Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target, sourcePosition, targetPosition); + } + return 0 /* False */; + } + if (targetFlags & 1 /* Required */ && !(sourceFlags & 1 /* Required */)) { + if (reportErrors2) { + reportError(Diagnostics.Source_provides_no_match_for_required_element_at_position_0_in_target, targetPosition); + } + return 0 /* False */; + } + if (canExcludeDiscriminants) { + if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) { + canExcludeDiscriminants = false; + } + if (canExcludeDiscriminants && (excludedProperties == null ? void 0 : excludedProperties.has("" + sourcePosition))) { + continue; + } + } + const sourceType = removeMissingType(sourceTypeArguments[sourcePosition], !!(sourceFlags & targetFlags & 2 /* Optional */)); + const targetType = targetTypeArguments[targetPosition]; + const targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) : removeMissingType(targetType, !!(targetFlags & 2 /* Optional */)); + const related = isRelatedTo( + sourceType, + targetCheckType, + 3 /* Both */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + if (!related) { + if (reportErrors2 && (targetArity > 1 || sourceArity > 1)) { + if (targetHasRestElement && sourcePosition >= targetStartCount && sourcePositionFromEnd >= targetEndCount && targetStartCount !== sourceArity - targetEndCount - 1) { + reportIncompatibleError(Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, targetStartCount, sourceArity - targetEndCount - 1, targetPosition); + } else { + reportIncompatibleError(Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, sourcePosition, targetPosition); + } + } + return 0 /* False */; + } + result2 &= related; + } + return result2; + } + if (target2.target.combinedFlags & 12 /* Variable */) { + return 0 /* False */; + } + } + const requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source2) && !isEmptyArrayLiteralType(source2) && !isTupleType(source2); + const unmatchedProperty = getUnmatchedProperty( + source2, + target2, + requireOptionalProperties, + /*matchDiscriminantProperties*/ + false + ); + if (unmatchedProperty) { + if (reportErrors2 && shouldReportUnmatchedPropertyError(source2, target2)) { + reportUnmatchedProperty(source2, target2, unmatchedProperty, requireOptionalProperties); + } + return 0 /* False */; + } + if (isObjectLiteralType(target2)) { + for (const sourceProp of excludeProperties(getPropertiesOfType(source2), excludedProperties)) { + if (!getPropertyOfObjectType(target2, sourceProp.escapedName)) { + const sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType.flags & 32768 /* Undefined */)) { + if (reportErrors2) { + reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target2)); + } + return 0 /* False */; + } + } + } + } + const properties = getPropertiesOfType(target2); + const numericNamesOnly = isTupleType(source2) && isTupleType(target2); + for (const targetProp of excludeProperties(properties, excludedProperties)) { + const name = targetProp.escapedName; + if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length") && (!optionalsOnly || targetProp.flags & 16777216 /* Optional */)) { + const sourceProp = getPropertyOfType(source2, name); + if (sourceProp && sourceProp !== targetProp) { + const related = propertyRelatedTo(source2, target2, sourceProp, targetProp, getNonMissingTypeOfSymbol, reportErrors2, intersectionState, relation === comparableRelation); + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + } + } + return result2; + } + function propertiesIdenticalTo(source2, target2, excludedProperties) { + if (!(source2.flags & 524288 /* Object */ && target2.flags & 524288 /* Object */)) { + return 0 /* False */; + } + const sourceProperties = excludeProperties(getPropertiesOfObjectType(source2), excludedProperties); + const targetProperties = excludeProperties(getPropertiesOfObjectType(target2), excludedProperties); + if (sourceProperties.length !== targetProperties.length) { + return 0 /* False */; + } + let result2 = -1 /* True */; + for (const sourceProp of sourceProperties) { + const targetProp = getPropertyOfObjectType(target2, sourceProp.escapedName); + if (!targetProp) { + return 0 /* False */; + } + const related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + return result2; + } + function signaturesRelatedTo(source2, target2, kind, reportErrors2, intersectionState) { + var _a2, _b; + if (relation === identityRelation) { + return signaturesIdenticalTo(source2, target2, kind); + } + if (target2 === anyFunctionType || source2 === anyFunctionType) { + return -1 /* True */; + } + const sourceIsJSConstructor = source2.symbol && isJSConstructor(source2.symbol.valueDeclaration); + const targetIsJSConstructor = target2.symbol && isJSConstructor(target2.symbol.valueDeclaration); + const sourceSignatures = getSignaturesOfType( + source2, + sourceIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind + ); + const targetSignatures = getSignaturesOfType( + target2, + targetIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind + ); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + const sourceIsAbstract = !!(sourceSignatures[0].flags & 4 /* Abstract */); + const targetIsAbstract = !!(targetSignatures[0].flags & 4 /* Abstract */); + if (sourceIsAbstract && !targetIsAbstract) { + if (reportErrors2) { + reportError(Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors2)) { + return 0 /* False */; + } + } + let result2 = -1 /* True */; + const incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn; + const sourceObjectFlags = getObjectFlags(source2); + const targetObjectFlags = getObjectFlags(target2); + if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source2.symbol === target2.symbol || sourceObjectFlags & 4 /* Reference */ && targetObjectFlags & 4 /* Reference */ && source2.target === target2.target) { + Debug.assertEqual(sourceSignatures.length, targetSignatures.length); + for (let i = 0; i < targetSignatures.length; i++) { + const related = signatureRelatedTo( + sourceSignatures[i], + targetSignatures[i], + /*erase*/ + true, + reportErrors2, + intersectionState, + incompatibleReporter(sourceSignatures[i], targetSignatures[i]) + ); + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + } else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + const eraseGenerics = relation === comparableRelation; + const sourceSignature = first(sourceSignatures); + const targetSignature = first(targetSignatures); + result2 = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors2, intersectionState, incompatibleReporter(sourceSignature, targetSignature)); + if (!result2 && reportErrors2 && kind === 1 /* Construct */ && sourceObjectFlags & targetObjectFlags && (((_a2 = targetSignature.declaration) == null ? void 0 : _a2.kind) === 176 /* Constructor */ || ((_b = sourceSignature.declaration) == null ? void 0 : _b.kind) === 176 /* Constructor */)) { + const constructSignatureToString = (signature) => signatureToString( + signature, + /*enclosingDeclaration*/ + void 0, + 262144 /* WriteArrowStyleSignature */, + kind + ); + reportError(Diagnostics.Type_0_is_not_assignable_to_type_1, constructSignatureToString(sourceSignature), constructSignatureToString(targetSignature)); + reportError(Diagnostics.Types_of_construct_signatures_are_incompatible); + return result2; + } + } else { + outer: + for (const t of targetSignatures) { + const saveErrorInfo = captureErrorCalculationState(); + let shouldElaborateErrors = reportErrors2; + for (const s of sourceSignatures) { + const related = signatureRelatedTo( + s, + t, + /*erase*/ + true, + shouldElaborateErrors, + intersectionState, + incompatibleReporter(s, t) + ); + if (related) { + result2 &= related; + resetErrorInfo(saveErrorInfo); + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source2), signatureToString( + t, + /*enclosingDeclaration*/ + void 0, + /*flags*/ + void 0, + kind + )); + } + return 0 /* False */; + } + } + return result2; + } + function shouldReportUnmatchedPropertyError(source2, target2) { + const typeCallSignatures = getSignaturesOfStructuredType(source2, 0 /* Call */); + const typeConstructSignatures = getSignaturesOfStructuredType(source2, 1 /* Construct */); + const typeProperties = getPropertiesOfObjectType(source2); + if ((typeCallSignatures.length || typeConstructSignatures.length) && !typeProperties.length) { + if (getSignaturesOfType(target2, 0 /* Call */).length && typeCallSignatures.length || getSignaturesOfType(target2, 1 /* Construct */).length && typeConstructSignatures.length) { + return true; + } + return false; + } + return true; + } + function reportIncompatibleCallSignatureReturn(siga, sigb) { + if (siga.parameters.length === 0 && sigb.parameters.length === 0) { + return (source2, target2) => reportIncompatibleError(Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source2), typeToString(target2)); + } + return (source2, target2) => reportIncompatibleError(Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source2), typeToString(target2)); + } + function reportIncompatibleConstructSignatureReturn(siga, sigb) { + if (siga.parameters.length === 0 && sigb.parameters.length === 0) { + return (source2, target2) => reportIncompatibleError(Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source2), typeToString(target2)); + } + return (source2, target2) => reportIncompatibleError(Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source2), typeToString(target2)); + } + function signatureRelatedTo(source2, target2, erase, reportErrors2, intersectionState, incompatibleReporter) { + const checkMode = relation === subtypeRelation ? 16 /* StrictTopSignature */ : relation === strictSubtypeRelation ? 16 /* StrictTopSignature */ | 8 /* StrictArity */ : 0 /* None */; + return compareSignaturesRelated(erase ? getErasedSignature(source2) : source2, erase ? getErasedSignature(target2) : target2, checkMode, reportErrors2, reportError, incompatibleReporter, isRelatedToWorker2, reportUnreliableMapper); + function isRelatedToWorker2(source3, target3, reportErrors3) { + return isRelatedTo( + source3, + target3, + 3 /* Both */, + reportErrors3, + /*headMessage*/ + void 0, + intersectionState + ); + } + } + function signaturesIdenticalTo(source2, target2, kind) { + const sourceSignatures = getSignaturesOfType(source2, kind); + const targetSignatures = getSignaturesOfType(target2, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0 /* False */; + } + let result2 = -1 /* True */; + for (let i = 0; i < sourceSignatures.length; i++) { + const related = compareSignaturesIdentical( + sourceSignatures[i], + targetSignatures[i], + /*partialMatch*/ + false, + /*ignoreThisTypes*/ + false, + /*ignoreReturnTypes*/ + false, + isRelatedTo + ); + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + return result2; + } + function membersRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState) { + let result2 = -1 /* True */; + const keyType = targetInfo.keyType; + const props = source2.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source2) : getPropertiesOfObjectType(source2); + for (const prop of props) { + if (isIgnoredJsxProperty(source2, prop)) { + continue; + } + if (isApplicableIndexType(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), keyType)) { + const propType = getNonMissingTypeOfSymbol(prop); + const type = exactOptionalPropertyTypes || propType.flags & 32768 /* Undefined */ || keyType === numberType || !(prop.flags & 16777216 /* Optional */) ? propType : getTypeWithFacts(propType, 524288 /* NEUndefined */); + const related = isRelatedTo( + type, + targetInfo.type, + 3 /* Both */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + if (!related) { + if (reportErrors2) { + reportError(Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; + } + result2 &= related; + } + } + for (const info of getIndexInfosOfType(source2)) { + if (isApplicableIndexType(info.keyType, keyType)) { + const related = indexInfoRelatedTo(info, targetInfo, reportErrors2, intersectionState); + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + } + return result2; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors2, intersectionState) { + const related = isRelatedTo( + sourceInfo.type, + targetInfo.type, + 3 /* Both */, + reportErrors2, + /*headMessage*/ + void 0, + intersectionState + ); + if (!related && reportErrors2) { + if (sourceInfo.keyType === targetInfo.keyType) { + reportError(Diagnostics._0_index_signatures_are_incompatible, typeToString(sourceInfo.keyType)); + } else { + reportError(Diagnostics._0_and_1_index_signatures_are_incompatible, typeToString(sourceInfo.keyType), typeToString(targetInfo.keyType)); + } + } + return related; + } + function indexSignaturesRelatedTo(source2, target2, sourceIsPrimitive, reportErrors2, intersectionState) { + if (relation === identityRelation) { + return indexSignaturesIdenticalTo(source2, target2); + } + const indexInfos = getIndexInfosOfType(target2); + const targetHasStringIndex = some(indexInfos, (info) => info.keyType === stringType); + let result2 = -1 /* True */; + for (const targetInfo of indexInfos) { + const related = relation !== strictSubtypeRelation && !sourceIsPrimitive && targetHasStringIndex && targetInfo.type.flags & 1 /* Any */ ? -1 /* True */ : isGenericMappedType(source2) && targetHasStringIndex ? isRelatedTo(getTemplateTypeFromMappedType(source2), targetInfo.type, 3 /* Both */, reportErrors2) : typeRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState); + if (!related) { + return 0 /* False */; + } + result2 &= related; + } + return result2; + } + function typeRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState) { + const sourceInfo = getApplicableIndexInfo(source2, targetInfo.keyType); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors2, intersectionState); + } + if (!(intersectionState & 1 /* Source */) && (relation !== strictSubtypeRelation || getObjectFlags(source2) & 8192 /* FreshLiteral */) && isObjectTypeWithInferableIndex(source2)) { + return membersRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState); + } + if (reportErrors2) { + reportError(Diagnostics.Index_signature_for_type_0_is_missing_in_type_1, typeToString(targetInfo.keyType), typeToString(source2)); + } + return 0 /* False */; + } + function indexSignaturesIdenticalTo(source2, target2) { + const sourceInfos = getIndexInfosOfType(source2); + const targetInfos = getIndexInfosOfType(target2); + if (sourceInfos.length !== targetInfos.length) { + return 0 /* False */; + } + for (const targetInfo of targetInfos) { + const sourceInfo = getIndexInfoOfType(source2, targetInfo.keyType); + if (!(sourceInfo && isRelatedTo(sourceInfo.type, targetInfo.type, 3 /* Both */) && sourceInfo.isReadonly === targetInfo.isReadonly)) { + return 0 /* False */; + } + } + return -1 /* True */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors2) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + const sourceAccessibility = getSelectedEffectiveModifierFlags(sourceSignature.declaration, 6 /* NonPublicAccessibilityModifier */); + const targetAccessibility = getSelectedEffectiveModifierFlags(targetSignature.declaration, 6 /* NonPublicAccessibilityModifier */); + if (targetAccessibility === 2 /* Private */) { + return true; + } + if (targetAccessibility === 4 /* Protected */ && sourceAccessibility !== 2 /* Private */) { + return true; + } + if (targetAccessibility !== 4 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors2) { + reportError(Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function typeCouldHaveTopLevelSingletonTypes(type) { + if (type.flags & 16 /* Boolean */) { + return false; + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + return !!forEach(type.types, typeCouldHaveTopLevelSingletonTypes); + } + if (type.flags & 465829888 /* Instantiable */) { + const constraint = getConstraintOfType(type); + if (constraint && constraint !== type) { + return typeCouldHaveTopLevelSingletonTypes(constraint); + } + } + return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */) || !!(type.flags & 268435456 /* StringMapping */); + } + function getExactOptionalUnassignableProperties(source, target) { + if (isTupleType(source) && isTupleType(target)) return emptyArray; + return getPropertiesOfType(target).filter((targetProp) => isExactOptionalPropertyMismatch(getTypeOfPropertyOfType(source, targetProp.escapedName), getTypeOfSymbol(targetProp))); + } + function isExactOptionalPropertyMismatch(source, target) { + return !!source && !!target && maybeTypeOfKind(source, 32768 /* Undefined */) && !!containsMissingType(target); + } + function getExactOptionalProperties(type) { + return getPropertiesOfType(type).filter((targetProp) => containsMissingType(getTypeOfSymbol(targetProp))); + } + function getBestMatchingType(source, target, isRelatedTo = compareTypesAssignable) { + return findMatchingDiscriminantType(source, target, isRelatedTo) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); + } + function discriminateTypeByDiscriminableItems(target, discriminators, related) { + const types = target.types; + const include = types.map((t) => t.flags & 402784252 /* Primitive */ ? 0 /* False */ : -1 /* True */); + for (const [getDiscriminatingType, propertyName] of discriminators) { + let matched = false; + for (let i = 0; i < types.length; i++) { + if (include[i]) { + const targetType = getTypeOfPropertyOrIndexSignatureOfType(types[i], propertyName); + if (targetType && someType(getDiscriminatingType(), (t) => !!related(t, targetType))) { + matched = true; + } else { + include[i] = 3 /* Maybe */; + } + } + } + for (let i = 0; i < types.length; i++) { + if (include[i] === 3 /* Maybe */) { + include[i] = matched ? 0 /* False */ : -1 /* True */; + } + } + } + const filtered = contains(include, 0 /* False */) ? getUnionType(types.filter((_, i) => include[i]), 0 /* None */) : target; + return filtered.flags & 131072 /* Never */ ? target : filtered; + } + function isWeakType(type) { + if (type.flags & 524288 /* Object */) { + const resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && resolved.indexInfos.length === 0 && resolved.properties.length > 0 && every(resolved.properties, (p) => !!(p.flags & 16777216 /* Optional */)); + } + if (type.flags & 33554432 /* Substitution */) { + return isWeakType(type.baseType); + } + if (type.flags & 2097152 /* Intersection */) { + return every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target, isComparingJsxAttributes) { + for (const prop of getPropertiesOfType(source)) { + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + function getVariances(type) { + return type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */ ? arrayVariances : getVariancesWorker(type.symbol, type.typeParameters); + } + function getAliasVariances(symbol) { + return getVariancesWorker(symbol, getSymbolLinks(symbol).typeParameters); + } + function getVariancesWorker(symbol, typeParameters = emptyArray) { + var _a, _b; + const links = getSymbolLinks(symbol); + if (!links.variances) { + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); + const oldVarianceComputation = inVarianceComputation; + const saveResolutionStart = resolutionStart; + if (!inVarianceComputation) { + inVarianceComputation = true; + resolutionStart = resolutionTargets.length; + } + links.variances = emptyArray; + const variances = []; + for (const tp of typeParameters) { + const modifiers = getTypeParameterModifiers(tp); + let variance = modifiers & 16384 /* Out */ ? modifiers & 8192 /* In */ ? 0 /* Invariant */ : 1 /* Covariant */ : modifiers & 8192 /* In */ ? 2 /* Contravariant */ : void 0; + if (variance === void 0) { + let unmeasurable = false; + let unreliable = false; + const oldHandler = outofbandVarianceMarkerHandler; + outofbandVarianceMarkerHandler = (onlyUnreliable) => onlyUnreliable ? unreliable = true : unmeasurable = true; + const typeWithSuper = createMarkerType(symbol, tp, markerSuperType); + const typeWithSub = createMarkerType(symbol, tp, markerSubType); + variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); + if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(symbol, tp, markerOtherType), typeWithSuper)) { + variance = 4 /* Independent */; + } + outofbandVarianceMarkerHandler = oldHandler; + if (unmeasurable || unreliable) { + if (unmeasurable) { + variance |= 8 /* Unmeasurable */; + } + if (unreliable) { + variance |= 16 /* Unreliable */; + } + } + } + variances.push(variance); + } + if (!oldVarianceComputation) { + inVarianceComputation = false; + resolutionStart = saveResolutionStart; + } + links.variances = variances; + (_b = tracing) == null ? void 0 : _b.pop({ variances: variances.map(Debug.formatVariance) }); + } + return links.variances; + } + function createMarkerType(symbol, source, target) { + const mapper = makeUnaryTypeMapper(source, target); + const type = getDeclaredTypeOfSymbol(symbol); + if (isErrorType(type)) { + return type; + } + const result = symbol.flags & 524288 /* TypeAlias */ ? getTypeAliasInstantiation(symbol, instantiateTypes(getSymbolLinks(symbol).typeParameters, mapper)) : createTypeReference(type, instantiateTypes(type.typeParameters, mapper)); + markerTypes.add(getTypeId(result)); + return result; + } + function isMarkerType(type) { + return markerTypes.has(getTypeId(type)); + } + function getTypeParameterModifiers(tp) { + var _a; + return reduceLeft((_a = tp.symbol) == null ? void 0 : _a.declarations, (modifiers, d) => modifiers | getEffectiveModifierFlags(d), 0 /* None */) & (8192 /* In */ | 16384 /* Out */ | 4096 /* Const */); + } + function hasCovariantVoidArgument(typeArguments, variances) { + for (let i = 0; i < variances.length; i++) { + if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) { + return true; + } + } + return false; + } + function isUnconstrainedTypeParameter(type) { + return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type); + } + function isNonDeferredTypeReference(type) { + return !!(getObjectFlags(type) & 4 /* Reference */) && !type.node; + } + function isTypeReferenceWithGenericArguments(type) { + return isNonDeferredTypeReference(type) && some(getTypeArguments(type), (t) => !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t)); + } + function getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) { + const typeParameters = []; + let constraintMarker = ""; + const sourceId = getTypeReferenceId(source, 0); + const targetId = getTypeReferenceId(target, 0); + return `${constraintMarker}${sourceId},${targetId}${postFix}`; + function getTypeReferenceId(type, depth = 0) { + let result = "" + type.target.id; + for (const t of getTypeArguments(type)) { + if (t.flags & 262144 /* TypeParameter */) { + if (ignoreConstraints || isUnconstrainedTypeParameter(t)) { + let index = typeParameters.indexOf(t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + continue; + } + constraintMarker = "*"; + } else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, depth + 1) + ">"; + continue; + } + result += "-" + t.id; + } + return result; + } + } + function getRelationKey(source, target, intersectionState, relation, ignoreConstraints) { + if (relation === identityRelation && source.id > target.id) { + const temp = source; + source = target; + target = temp; + } + const postFix = intersectionState ? ":" + intersectionState : ""; + return isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target) ? getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) : `${source.id},${target.id}${postFix}`; + } + function forEachProperty(prop, callback) { + if (getCheckFlags(prop) & 6 /* Synthetic */) { + for (const t of prop.links.containingType.types) { + const p = getPropertyOfType(t, prop.escapedName); + const result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return void 0; + } + return callback(prop); + } + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : void 0; + } + function getTypeOfPropertyInBaseClass(property) { + const classType = getDeclaringClass(property); + const baseClassType = classType && getBaseTypes(classType)[0]; + return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName); + } + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, (sp) => { + const sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, (tp) => getDeclarationModifierFlagsFromSymbol(tp) & 4 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false); + } + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, (p) => getDeclarationModifierFlagsFromSymbol(p, writing) & 4 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? void 0 : checkClass; + } + function isDeeplyNestedType(type, stack, depth, maxDepth = 3) { + if (depth >= maxDepth) { + if ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */) { + type = getMappedTargetWithSymbol(type); + } + if (type.flags & 2097152 /* Intersection */) { + return some(type.types, (t) => isDeeplyNestedType(t, stack, depth, maxDepth)); + } + const identity2 = getRecursionIdentity(type); + let count = 0; + let lastTypeId = 0; + for (let i = 0; i < depth; i++) { + const t = stack[i]; + if (hasMatchingRecursionIdentity(t, identity2)) { + if (t.id >= lastTypeId) { + count++; + if (count >= maxDepth) { + return true; + } + } + lastTypeId = t.id; + } + } + } + return false; + } + function getMappedTargetWithSymbol(type) { + let target; + while ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */ && (target = getModifiersTypeFromMappedType(type)) && (target.symbol || target.flags & 2097152 /* Intersection */ && some(target.types, (t) => !!t.symbol))) { + type = target; + } + return type; + } + function hasMatchingRecursionIdentity(type, identity2) { + if ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */) { + type = getMappedTargetWithSymbol(type); + } + if (type.flags & 2097152 /* Intersection */) { + return some(type.types, (t) => hasMatchingRecursionIdentity(t, identity2)); + } + return getRecursionIdentity(type) === identity2; + } + function getRecursionIdentity(type) { + if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { + if (getObjectFlags(type) & 4 /* Reference */ && type.node) { + return type.node; + } + if (type.symbol && !(getObjectFlags(type) & 16 /* Anonymous */ && type.symbol.flags & 32 /* Class */)) { + return type.symbol; + } + if (isTupleType(type)) { + return type.target; + } + } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } + if (type.flags & 8388608 /* IndexedAccess */) { + do { + type = type.objectType; + } while (type.flags & 8388608 /* IndexedAccess */); + return type; + } + if (type.flags & 16777216 /* Conditional */) { + return type.root; + } + return type; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + if (sourceProp === targetProp) { + return -1 /* True */; + } + const sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 6 /* NonPublicAccessibilityModifier */; + const targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 6 /* NonPublicAccessibilityModifier */; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0 /* False */; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0 /* False */; + } + } else { + if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) { + return 0 /* False */; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + const sourceParameterCount = getParameterCount(source); + const targetParameterCount = getParameterCount(target); + const sourceMinArgumentCount = getMinArgumentCount(source); + const targetMinArgumentCount = getMinArgumentCount(target); + const sourceHasRestParameter = hasEffectiveRestParameter(source); + const targetHasRestParameter = hasEffectiveRestParameter(target); + if (sourceParameterCount === targetParameterCount && sourceMinArgumentCount === targetMinArgumentCount && sourceHasRestParameter === targetHasRestParameter) { + return true; + } + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) { + return true; + } + return false; + } + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + if (source === target) { + return -1 /* True */; + } + if (!isMatchingSignature(source, target, partialMatch)) { + return 0 /* False */; + } + if (length(source.typeParameters) !== length(target.typeParameters)) { + return 0 /* False */; + } + if (target.typeParameters) { + const mapper = createTypeMapper(source.typeParameters, target.typeParameters); + for (let i = 0; i < target.typeParameters.length; i++) { + const s = source.typeParameters[i]; + const t = target.typeParameters[i]; + if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) && compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) { + return 0 /* False */; + } + } + source = instantiateSignature( + source, + mapper, + /*eraseTypeParameters*/ + true + ); + } + let result = -1 /* True */; + if (!ignoreThisTypes) { + const sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + const targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + const related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + } + const targetLen = getParameterCount(target); + for (let i = 0; i < targetLen; i++) { + const s = getTypeAtPosition(source, i); + const t = getTypeAtPosition(target, i); + const related = compareTypes(t, s); + if (!related) { + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + const sourceTypePredicate = getTypePredicateOfSignature(source); + const targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate || targetTypePredicate ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ : source.type === target.type ? -1 /* True */ : source.type && target.type ? compareTypes(source.type, target.type) : 0 /* False */; + } + function literalTypesWithSameBaseType(types) { + let commonBaseType; + for (const t of types) { + if (!(t.flags & 131072 /* Never */)) { + const baseType = getBaseTypeOfLiteralType(t); + commonBaseType ?? (commonBaseType = baseType); + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + } + return true; + } + function getCombinedTypeFlags(types) { + return reduceLeft(types, (flags, t) => flags | (t.flags & 1048576 /* Union */ ? getCombinedTypeFlags(t.types) : t.flags), 0); + } + function getCommonSupertype(types) { + if (types.length === 1) { + return types[0]; + } + const primaryTypes = strictNullChecks ? sameMap(types, (t) => filterType(t, (u) => !(u.flags & 98304 /* Nullable */))) : types; + const superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? getUnionType(primaryTypes) : reduceLeft(primaryTypes, (s, t) => isTypeSubtypeOf(s, t) ? t : s); + return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304 /* Nullable */); + } + function getCommonSubtype(types) { + return reduceLeft(types, (s, t) => isTypeSubtypeOf(t, s) ? t : s); + } + function isArrayType(type) { + return !!(getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType); + } + function isReadonlyArrayType(type) { + return !!(getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } + function isArrayOrTupleType(type) { + return isArrayType(type) || isTupleType(type); + } + function isMutableArrayOrTuple(type) { + return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly; + } + function getElementTypeOfArrayType(type) { + return isArrayType(type) ? getTypeArguments(type)[0] : void 0; + } + function isArrayLikeType(type) { + return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isMutableArrayLikeType(type) { + return isMutableArrayOrTuple(type) || !(type.flags & (1 /* Any */ | 98304 /* Nullable */)) && isTypeAssignableTo(type, anyArrayType); + } + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(getObjectFlags(type) & 4 /* Reference */) || !(getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return void 0; + } + if (getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : void 0; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + const target = type.target; + if (getObjectFlags(target) & 1 /* Class */) { + const baseTypeNode = getBaseTypeNodeOfClass(target); + if (baseTypeNode && baseTypeNode.expression.kind !== 80 /* Identifier */ && baseTypeNode.expression.kind !== 211 /* PropertyAccessExpression */) { + return void 0; + } + } + const bases = getBaseTypes(target); + if (bases.length !== 1) { + return void 0; + } + if (getMembersOfSymbol(type.symbol).size) { + return void 0; + } + let instantiatedBase = !length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (length(getTypeArguments(type)) > length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; + } + function isEmptyLiteralType(type) { + return strictNullChecks ? type === implicitNeverType : type === undefinedWideningType; + } + function isEmptyArrayLiteralType(type) { + const elementType = getElementTypeOfArrayType(type); + return !!elementType && isEmptyLiteralType(elementType); + } + function isTupleLikeType(type) { + let lengthType; + return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, (t) => !!(t.flags & 256 /* NumberLiteral */)); + } + function isArrayOrTupleLikeType(type) { + return isArrayLikeType(type) || isTupleLikeType(type); + } + function getTupleElementType(type, index) { + const propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType)) { + return getTupleElementTypeOutOfStartCount(type, index, compilerOptions.noUncheckedIndexedAccess ? undefinedType : void 0); + } + return void 0; + } + function isNeitherUnitTypeNorNever(type) { + return !(type.flags & (109472 /* Unit */ | 131072 /* Never */)); + } + function isUnitType(type) { + return !!(type.flags & 109472 /* Unit */); + } + function isUnitLikeType(type) { + const t = getBaseConstraintOrType(type); + return t.flags & 2097152 /* Intersection */ ? some(t.types, isUnitType) : isUnitType(t); + } + function extractUnitType(type) { + return type.flags & 2097152 /* Intersection */ ? find(type.types, isUnitType) || type : type; + } + function isLiteralType(type) { + return type.flags & 16 /* Boolean */ ? true : type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : every(type.types, isUnitType) : isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + return type.flags & 1056 /* EnumLike */ ? getBaseTypeOfEnumLikeType(type) : type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type; + } + function getBaseTypeOfLiteralTypeUnion(type) { + const key = `B${getTypeId(type)}`; + return getCachedType(key) ?? setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + } + function getBaseTypeOfLiteralTypeForComparison(type) { + return type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & (256 /* NumberLiteral */ | 32 /* Enum */) ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* Union */ ? mapType(type, getBaseTypeOfLiteralTypeForComparison) : type; + } + function getWidenedLiteralType(type) { + return type.flags & 1056 /* EnumLike */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLikeType(type) : type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : type.flags & 1048576 /* Union */ ? mapType(type, getWidenedLiteralType) : type; + } + function getWidenedUniqueESSymbolType(type) { + return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : type.flags & 1048576 /* Union */ ? mapType(type, getWidenedUniqueESSymbolType) : type; + } + function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { + if (!isLiteralOfContextualType(type, contextualType)) { + type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type)); + } + return getRegularTypeOfLiteralType(type); + } + function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) { + if (type && isUnitType(type)) { + const contextualType = !contextualSignatureReturnType ? void 0 : isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) : contextualSignatureReturnType; + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + return type; + } + function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) { + if (type && isUnitType(type)) { + const contextualType = !contextualSignatureReturnType ? void 0 : getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator); + type = getWidenedLiteralLikeTypeForContextualType(type, contextualType); + } + return type; + } + function isTupleType(type) { + return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + } + function isGenericTupleType(type) { + return isTupleType(type) && !!(type.target.combinedFlags & 8 /* Variadic */); + } + function isSingleElementGenericTupleType(type) { + return isGenericTupleType(type) && type.target.elementFlags.length === 1; + } + function getRestTypeOfTupleType(type) { + return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength); + } + function getTupleElementTypeOutOfStartCount(type, index, undefinedOrMissingType2) { + return mapType(type, (t) => { + const tupleType = t; + const restType = getRestTypeOfTupleType(tupleType); + if (!restType) { + return undefinedType; + } + if (undefinedOrMissingType2 && index >= getTotalFixedElementCount(tupleType.target)) { + return getUnionType([restType, undefinedOrMissingType2]); + } + return restType; + }); + } + function getRestArrayTypeOfTupleType(type) { + const restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } + function getElementTypeOfSliceOfTupleType(type, index, endSkipCount = 0, writing = false, noReductions = false) { + const length2 = getTypeReferenceArity(type) - endSkipCount; + if (index < length2) { + const typeArguments = getTypeArguments(type); + const elementTypes = []; + for (let i = index; i < length2; i++) { + const t = typeArguments[i]; + elementTypes.push(type.target.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t); + } + return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes, noReductions ? 0 /* None */ : 1 /* Literal */); + } + return void 0; + } + function isTupleTypeStructureMatching(t1, t2) { + return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) && every(t1.target.elementFlags, (f, i) => (f & 12 /* Variable */) === (t2.target.elementFlags[i] & 12 /* Variable */)); + } + function isZeroBigInt({ value }) { + return value.base10Value === "0"; + } + function removeDefinitelyFalsyTypes(type) { + return filterType(type, (t) => hasTypeFacts(t, 4194304 /* Truthy */)); + } + function extractDefinitelyFalsyTypes(type) { + return mapType(type, getDefinitelyFalsyPartOfType); + } + function getDefinitelyFalsyPartOfType(type) { + return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : type.flags & 64 /* BigInt */ ? zeroBigIntType : type === regularFalseType || type === falseType || type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */ | 3 /* AnyOrUnknown */) || type.flags & 128 /* StringLiteral */ && type.value === "" || type.flags & 256 /* NumberLiteral */ && type.value === 0 || type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : neverType; + } + function getNullableType(type, flags) { + const missing = flags & ~type.flags & (32768 /* Undefined */ | 65536 /* Null */); + return missing === 0 ? type : missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : missing === 65536 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); + } + function getOptionalType(type, isProperty = false) { + Debug.assert(strictNullChecks); + const missingOrUndefined = isProperty ? undefinedOrMissingType : undefinedType; + return type === missingOrUndefined || type.flags & 1048576 /* Union */ && type.types[0] === missingOrUndefined ? type : getUnionType([type, missingOrUndefined]); + } + function getGlobalNonNullableTypeInstantiation(type) { + if (!deferredGlobalNonNullableTypeAlias) { + deferredGlobalNonNullableTypeAlias = getGlobalSymbol( + "NonNullable", + 524288 /* TypeAlias */, + /*diagnostic*/ + void 0 + ) || unknownSymbol; + } + return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : getIntersectionType([type, emptyObjectType]); + } + function getNonNullableType(type) { + return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } + function addOptionalTypeMarker(type) { + return strictNullChecks ? getUnionType([type, optionalType]) : type; + } + function removeOptionalTypeMarker(type) { + return strictNullChecks ? removeType(type, optionalType) : type; + } + function propagateOptionalTypeMarker(type, node, wasOptional) { + return wasOptional ? isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type; + } + function getOptionalExpressionType(exprType, expression) { + return isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : exprType; + } + function removeMissingType(type, isOptional) { + return exactOptionalPropertyTypes && isOptional ? removeType(type, missingType) : type; + } + function containsMissingType(type) { + return type === missingType || !!(type.flags & 1048576 /* Union */) && type.types[0] === missingType; + } + function removeMissingOrUndefinedType(type) { + return exactOptionalPropertyTypes ? removeType(type, missingType) : getTypeWithFacts(type, 524288 /* NEUndefined */); + } + function isCoercibleUnderDoubleEquals(source, target) { + return (source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0 && (target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0; + } + function isObjectTypeWithInferableIndex(type) { + const objectFlags = getObjectFlags(type); + return type.flags & 2097152 /* Intersection */ ? every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && !(type.symbol.flags & 32 /* Class */) && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304 /* ObjectRestType */) || !!(objectFlags & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + } + function createSymbolWithType(source, type) { + const symbol = createSymbol(source.flags, source.escapedName, getCheckFlags(source) & 8 /* Readonly */); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.links.type = type; + symbol.links.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + const nameType = getSymbolLinks(source).nameType; + if (nameType) { + symbol.links.nameType = nameType; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + const members = createSymbolTable(); + for (const property of getPropertiesOfObjectType(type)) { + const original = getTypeOfSymbol(property); + const updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + function getRegularTypeOfObjectLiteral(type) { + if (!(isObjectLiteralType(type) && getObjectFlags(type) & 8192 /* FreshLiteral */)) { + return type; + } + const regularType = type.regularType; + if (regularType) { + return regularType; + } + const resolved = type; + const members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + const regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.indexInfos); + regularNew.flags = resolved.flags; + regularNew.objectFlags |= resolved.objectFlags & ~8192 /* FreshLiteral */; + type.regularType = regularNew; + return regularNew; + } + function createWideningContext(parent, propertyName, siblings) { + return { parent, propertyName, siblings, resolvedProperties: void 0 }; + } + function getSiblingsOfContext(context) { + if (!context.siblings) { + const siblings = []; + for (const type of getSiblingsOfContext(context.parent)) { + if (isObjectLiteralType(type)) { + const prop = getPropertyOfObjectType(type, context.propertyName); + if (prop) { + forEachType(getTypeOfSymbol(prop), (t) => { + siblings.push(t); + }); + } + } + } + context.siblings = siblings; + } + return context.siblings; + } + function getPropertiesOfContext(context) { + if (!context.resolvedProperties) { + const names = /* @__PURE__ */ new Map(); + for (const t of getSiblingsOfContext(context)) { + if (isObjectLiteralType(t) && !(getObjectFlags(t) & 2097152 /* ContainsSpread */)) { + for (const prop of getPropertiesOfType(t)) { + names.set(prop.escapedName, prop); + } + } + } + context.resolvedProperties = arrayFrom(names.values()); + } + return context.resolvedProperties; + } + function getWidenedProperty(prop, context) { + if (!(prop.flags & 4 /* Property */)) { + return prop; + } + const original = getTypeOfSymbol(prop); + const propContext = context && createWideningContext( + context, + prop.escapedName, + /*siblings*/ + void 0 + ); + const widened = getWidenedTypeWithContext(original, propContext); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getUndefinedProperty(prop) { + const cached = undefinedProperties.get(prop.escapedName); + if (cached) { + return cached; + } + const result = createSymbolWithType(prop, undefinedOrMissingType); + result.flags |= 16777216 /* Optional */; + undefinedProperties.set(prop.escapedName, result); + return result; + } + function getWidenedTypeOfObjectLiteral(type, context) { + const members = createSymbolTable(); + for (const prop of getPropertiesOfObjectType(type)) { + members.set(prop.escapedName, getWidenedProperty(prop, context)); + } + if (context) { + for (const prop of getPropertiesOfContext(context)) { + if (!members.has(prop.escapedName)) { + members.set(prop.escapedName, getUndefinedProperty(prop)); + } + } + } + const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, sameMap(getIndexInfosOfType(type), (info) => createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly, info.declaration, info.components))); + result.objectFlags |= getObjectFlags(type) & (4096 /* JSLiteral */ | 262144 /* NonInferrableType */); + return result; + } + function getWidenedType(type) { + return getWidenedTypeWithContext( + type, + /*context*/ + void 0 + ); + } + function getWidenedTypeWithContext(type, context) { + if (getObjectFlags(type) & 196608 /* RequiresWidening */) { + if (context === void 0 && type.widened) { + return type.widened; + } + let result; + if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) { + result = anyType; + } else if (isObjectLiteralType(type)) { + result = getWidenedTypeOfObjectLiteral(type, context); + } else if (type.flags & 1048576 /* Union */) { + const unionContext = context || createWideningContext( + /*parent*/ + void 0, + /*propertyName*/ + void 0, + type.types + ); + const widenedTypes = sameMap(type.types, (t) => t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext)); + result = getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); + } else if (type.flags & 2097152 /* Intersection */) { + result = getIntersectionType(sameMap(type.types, getWidenedType)); + } else if (isArrayOrTupleType(type)) { + result = createTypeReference(type.target, sameMap(getTypeArguments(type), getWidenedType)); + } + if (result && context === void 0) { + type.widened = result; + } + return result || type; + } + return type; + } + function reportWideningErrorsInType(type) { + var _a; + let errorReported = false; + if (getObjectFlags(type) & 65536 /* ContainsWideningType */) { + if (type.flags & 1048576 /* Union */) { + if (some(type.types, isEmptyObjectType)) { + errorReported = true; + } else { + for (const t of type.types) { + errorReported || (errorReported = reportWideningErrorsInType(t)); + } + } + } else if (isArrayOrTupleType(type)) { + for (const t of getTypeArguments(type)) { + errorReported || (errorReported = reportWideningErrorsInType(t)); + } + } else if (isObjectLiteralType(type)) { + for (const p of getPropertiesOfObjectType(type)) { + const t = getTypeOfSymbol(p); + if (getObjectFlags(t) & 65536 /* ContainsWideningType */) { + errorReported = reportWideningErrorsInType(t); + if (!errorReported) { + const valueDeclaration = (_a = p.declarations) == null ? void 0 : _a.find((d) => { + var _a2; + return ((_a2 = d.symbol.valueDeclaration) == null ? void 0 : _a2.parent) === type.symbol.valueDeclaration; + }); + if (valueDeclaration) { + error(valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + errorReported = true; + } + } + } + } + } + } + return errorReported; + } + function reportImplicitAny(declaration, type, wideningKind) { + const typeAsString = typeToString(getWidenedType(type)); + if (isInJSFile(declaration) && !isCheckJsEnabledForFile(getSourceFileOfNode(declaration), compilerOptions)) { + return; + } + let diagnostic; + switch (declaration.kind) { + case 226 /* BinaryExpression */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + diagnostic = noImplicitAny ? Diagnostics.Member_0_implicitly_has_an_1_type : Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 169 /* Parameter */: + const param = declaration; + if (isIdentifier(param.name)) { + const originalKeywordKind = identifierToKeywordKind(param.name); + if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.includes(param) && (resolveName( + param, + param.name.escapedText, + 788968 /* Type */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ) || originalKeywordKind && isTypeNodeKind(originalKeywordKind))) { + const newName = "arg" + param.parent.parameters.indexOf(param); + const typeName = declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); + errorOrSuggestion(noImplicitAny, declaration, Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); + return; + } + } + diagnostic = declaration.dotDotDotToken ? noImplicitAny ? Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? Diagnostics.Parameter_0_implicitly_has_an_1_type : Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + break; + case 208 /* BindingElement */: + diagnostic = Diagnostics.Binding_element_0_implicitly_has_an_1_type; + if (!noImplicitAny) { + return; + } + break; + case 317 /* JSDocFunctionType */: + error(declaration, Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + case 323 /* JSDocSignature */: + if (noImplicitAny && isJSDocOverloadTag(declaration.parent)) { + error(declaration.parent.tagName, Diagnostics.This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation, typeAsString); + } + return; + case 262 /* FunctionDeclaration */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + if (noImplicitAny && !declaration.name) { + if (wideningKind === 3 /* GeneratorYield */) { + error(declaration, Diagnostics.Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation, typeAsString); + } else { + error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + } + return; + } + diagnostic = !noImplicitAny ? Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : wideningKind === 3 /* GeneratorYield */ ? Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + break; + case 200 /* MappedType */: + if (noImplicitAny) { + error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } + return; + default: + diagnostic = noImplicitAny ? Diagnostics.Variable_0_implicitly_has_an_1_type : Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; + } + errorOrSuggestion(noImplicitAny, declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); + } + function shouldReportErrorsFromWideningWithContextualSignature(declaration, wideningKind) { + const signature = getContextualSignatureForFunctionLikeDeclaration(declaration); + if (!signature) { + return true; + } + let returnType = getReturnTypeOfSignature(signature); + const flags = getFunctionFlags(declaration); + switch (wideningKind) { + case 1 /* FunctionReturn */: + if (flags & 1 /* Generator */) { + returnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, !!(flags & 2 /* Async */)) ?? returnType; + } else if (flags & 2 /* Async */) { + returnType = getAwaitedTypeNoAlias(returnType) ?? returnType; + } + return isGenericType(returnType); + case 3 /* GeneratorYield */: + const yieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, !!(flags & 2 /* Async */)); + return !!yieldType && isGenericType(yieldType); + case 2 /* GeneratorNext */: + const nextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, !!(flags & 2 /* Async */)); + return !!nextType && isGenericType(nextType); + } + return false; + } + function reportErrorsFromWidening(declaration, type, wideningKind) { + addLazyDiagnostic(() => { + if (noImplicitAny && getObjectFlags(type) & 65536 /* ContainsWideningType */) { + if (!wideningKind || isFunctionLikeDeclaration(declaration) && shouldReportErrorsFromWideningWithContextualSignature(declaration, wideningKind)) { + if (!reportWideningErrorsInType(type)) { + reportImplicitAny(declaration, type, wideningKind); + } + } + } + }); + } + function applyToParameterTypes(source, target, callback) { + const sourceCount = getParameterCount(source); + const targetCount = getParameterCount(target); + const sourceRestType = getEffectiveRestType(source); + const targetRestType = getEffectiveRestType(target); + const targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + const paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + const sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + const targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } + for (let i = 0; i < paramCount; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + if (targetRestType) { + callback(getRestTypeAtPosition( + source, + paramCount, + /*readonly*/ + isConstTypeVariable(targetRestType) && !someType(targetRestType, isMutableArrayLikeType) + ), targetRestType); + } + } + function applyToReturnTypes(source, target, callback) { + const targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + const sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + return; + } + } + const targetReturnType = getReturnTypeOfSignature(target); + if (couldContainTypeVariables(targetReturnType)) { + callback(getReturnTypeOfSignature(source), targetReturnType); + } + } + function createInferenceContext(typeParameters, signature, flags, compareTypes) { + return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable); + } + function cloneInferenceContext(context, extraFlags = 0) { + return context && createInferenceContextWorker(map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes); + } + function createInferenceContextWorker(inferences, signature, flags, compareTypes) { + const context = { + inferences, + signature, + flags, + compareTypes, + mapper: reportUnmeasurableMapper, + // initialize to a noop mapper so the context object is available, but the underlying object shape is right upon construction + nonFixingMapper: reportUnmeasurableMapper + }; + context.mapper = makeFixingMapperForContext(context); + context.nonFixingMapper = makeNonFixingMapperForContext(context); + return context; + } + function makeFixingMapperForContext(context) { + return makeDeferredTypeMapper( + map(context.inferences, (i) => i.typeParameter), + map(context.inferences, (inference, i) => () => { + if (!inference.isFixed) { + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; + } + return getInferredType(context, i); + }) + ); + } + function makeNonFixingMapperForContext(context) { + return makeDeferredTypeMapper( + map(context.inferences, (i) => i.typeParameter), + map(context.inferences, (_, i) => () => { + return getInferredType(context, i); + }) + ); + } + function clearCachedInferences(inferences) { + for (const inference of inferences) { + if (!inference.isFixed) { + inference.inferredType = void 0; + } + } + } + function addIntraExpressionInferenceSite(context, node, type) { + (context.intraExpressionInferenceSites ?? (context.intraExpressionInferenceSites = [])).push({ node, type }); + } + function inferFromIntraExpressionSites(context) { + if (context.intraExpressionInferenceSites) { + for (const { node, type } of context.intraExpressionInferenceSites) { + const contextualType = node.kind === 174 /* MethodDeclaration */ ? getContextualTypeForObjectLiteralMethod(node, 2 /* NoConstraints */) : getContextualType(node, 2 /* NoConstraints */); + if (contextualType) { + inferTypes(context.inferences, type, contextualType); + } + } + context.intraExpressionInferenceSites = void 0; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter, + candidates: void 0, + contraCandidates: void 0, + inferredType: void 0, + priority: void 0, + topLevel: true, + isFixed: false, + impliedArity: void 0 + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed, + impliedArity: inference.impliedArity + }; + } + function cloneInferredPartOfContext(context) { + const inferences = filter(context.inferences, hasInferenceCandidates); + return inferences.length ? createInferenceContextWorker(map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) : void 0; + } + function getMapperFromContext(context) { + return context && context.mapper; + } + function couldContainTypeVariables(type) { + const objectFlags = getObjectFlags(type); + if (objectFlags & 524288 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 1048576 /* CouldContainTypeVariables */); + } + const result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || some(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 134217728 /* SingleSignatureType */ && !!length(type.outerTypeParameters) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 4194304 /* ObjectRestType */ | 8388608 /* InstantiationExpressionType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && some(type.types, couldContainTypeVariables)); + if (type.flags & 3899393 /* ObjectFlagsType */) { + type.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (result ? 1048576 /* CouldContainTypeVariables */ : 0); + } + return result; + } + function isNonGenericTopLevelType(type) { + if (type.aliasSymbol && !type.aliasTypeArguments) { + const declaration = getDeclarationOfKind(type.aliasSymbol, 265 /* TypeAliasDeclaration */); + return !!(declaration && findAncestor(declaration.parent, (n) => n.kind === 307 /* SourceFile */ ? true : n.kind === 267 /* ModuleDeclaration */ ? false : "quit")); + } + return false; + } + function isTypeParameterAtTopLevel(type, tp, depth = 0) { + return !!(type === tp || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, (t) => isTypeParameterAtTopLevel(t, tp, depth)) || depth < 3 && type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), tp, depth + 1) || isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), tp, depth + 1))); + } + function isTypeParameterAtTopLevelInReturnType(signature, typeParameter) { + const typePredicate = getTypePredicateOfSignature(signature); + return typePredicate ? !!typePredicate.type && isTypeParameterAtTopLevel(typePredicate.type, typeParameter) : isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), typeParameter); + } + function createEmptyObjectTypeFromStringLiteral(type) { + const members = createSymbolTable(); + forEachType(type, (t) => { + if (!(t.flags & 128 /* StringLiteral */)) { + return; + } + const name = escapeLeadingUnderscores(t.value); + const literalProp = createSymbol(4 /* Property */, name); + literalProp.links.type = anyType; + if (t.symbol) { + literalProp.declarations = t.symbol.declarations; + literalProp.valueDeclaration = t.symbol.valueDeclaration; + } + members.set(name, literalProp); + }); + const indexInfos = type.flags & 4 /* String */ ? [createIndexInfo( + stringType, + emptyObjectType, + /*isReadonly*/ + false + )] : emptyArray; + return createAnonymousType( + /*symbol*/ + void 0, + members, + emptyArray, + emptyArray, + indexInfos + ); + } + function inferTypeForHomomorphicMappedType(source, target, constraint) { + const cacheKey = source.id + "," + target.id + "," + constraint.id; + if (reverseHomomorphicMappedCache.has(cacheKey)) { + return reverseHomomorphicMappedCache.get(cacheKey); + } + const type = createReverseMappedType(source, target, constraint); + reverseHomomorphicMappedCache.set(cacheKey, type); + return type; + } + function isPartiallyInferableType(type) { + return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType); + } + function createReverseMappedType(source, target, constraint) { + if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) { + return void 0; + } + if (isArrayType(source)) { + const elementType = inferReverseMappedType(getTypeArguments(source)[0], target, constraint); + if (!elementType) { + return void 0; + } + return createArrayType(elementType, isReadonlyArrayType(source)); + } + if (isTupleType(source)) { + const elementTypes = map(getElementTypes(source), (t) => inferReverseMappedType(t, target, constraint)); + if (!every(elementTypes, (t) => !!t)) { + return void 0; + } + const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags; + return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations); + } + const reversed = createObjectType( + 1024 /* ReverseMapped */ | 16 /* Anonymous */, + /*symbol*/ + void 0 + ); + reversed.source = source; + reversed.mappedType = target; + reversed.constraintType = constraint; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + const links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.links.propertyType, symbol.links.mappedType, symbol.links.constraintType) || unknownType; + } + return links.type; + } + function inferReverseMappedTypeWorker(sourceType, target, constraint) { + const typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); + const templateType = getTemplateTypeFromMappedType(target); + const inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return getTypeFromInference(inference) || unknownType; + } + function inferReverseMappedType(source, target, constraint) { + const cacheKey = source.id + "," + target.id + "," + constraint.id; + if (reverseMappedCache.has(cacheKey)) { + return reverseMappedCache.get(cacheKey) || unknownType; + } + reverseMappedSourceStack.push(source); + reverseMappedTargetStack.push(target); + const saveExpandingFlags = reverseExpandingFlags; + if (isDeeplyNestedType(source, reverseMappedSourceStack, reverseMappedSourceStack.length, 2)) reverseExpandingFlags |= 1 /* Source */; + if (isDeeplyNestedType(target, reverseMappedTargetStack, reverseMappedTargetStack.length, 2)) reverseExpandingFlags |= 2 /* Target */; + let type; + if (reverseExpandingFlags !== 3 /* Both */) { + type = inferReverseMappedTypeWorker(source, target, constraint); + } + reverseMappedSourceStack.pop(); + reverseMappedTargetStack.pop(); + reverseExpandingFlags = saveExpandingFlags; + reverseMappedCache.set(cacheKey, type); + return type; + } + function* getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) { + const properties = getPropertiesOfType(target); + for (const targetProp of properties) { + if (isStaticPrivateIdentifierProperty(targetProp)) { + continue; + } + if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || getCheckFlags(targetProp) & 48 /* Partial */)) { + const sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (!sourceProp) { + yield targetProp; + } else if (matchDiscriminantProperties) { + const targetType = getTypeOfSymbol(targetProp); + if (targetType.flags & 109472 /* Unit */) { + const sourceType = getTypeOfSymbol(sourceProp); + if (!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) { + yield targetProp; + } + } + } + } + } + } + function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) { + return firstOrUndefinedIterator(getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties)); + } + function tupleTypesDefinitelyUnrelated(source, target) { + return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength || !(target.target.combinedFlags & 12 /* Variable */) && (!!(source.target.combinedFlags & 12 /* Variable */) || target.target.fixedLength < source.target.fixedLength); + } + function typesDefinitelyUnrelated(source, target) { + return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) : !!getUnmatchedProperty( + source, + target, + /*requireOptionalProperties*/ + false, + /*matchDiscriminantProperties*/ + true + ) && !!getUnmatchedProperty( + target, + source, + /*requireOptionalProperties*/ + false, + /*matchDiscriminantProperties*/ + false + ); + } + function getTypeFromInference(inference) { + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : void 0; + } + function hasSkipDirectInferenceFlag(node) { + return !!getNodeLinks(node).skipDirectInference; + } + function isFromInferenceBlockedSource(type) { + return !!(type.symbol && some(type.symbol.declarations, hasSkipDirectInferenceFlag)); + } + function templateLiteralTypesDefinitelyUnrelated(source, target) { + const sourceStart = source.texts[0]; + const targetStart = target.texts[0]; + const sourceEnd = source.texts[source.texts.length - 1]; + const targetEnd = target.texts[target.texts.length - 1]; + const startLen = Math.min(sourceStart.length, targetStart.length); + const endLen = Math.min(sourceEnd.length, targetEnd.length); + return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); + } + function isValidNumberString(s, roundTripOnly) { + if (s === "") return false; + const n = +s; + return isFinite(n) && (!roundTripOnly || "" + n === s); + } + function parseBigIntLiteralType(text) { + return getBigIntLiteralType(parseValidBigInt(text)); + } + function isMemberOfStringMapping(source, target) { + if (target.flags & 1 /* Any */) { + return true; + } + if (target.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) { + return isTypeAssignableTo(source, target); + } + if (target.flags & 268435456 /* StringMapping */) { + const mappingStack = []; + while (target.flags & 268435456 /* StringMapping */) { + mappingStack.unshift(target.symbol); + target = target.type; + } + const mappedSource = reduceLeft(mappingStack, (memo, value) => getStringMappingType(value, memo), source); + return mappedSource === source && isMemberOfStringMapping(source, target); + } + return false; + } + function isValidTypeForTemplateLiteralPlaceholder(source, target) { + if (target.flags & 2097152 /* Intersection */) { + return every(target.types, (t) => t === emptyTypeLiteralType || isValidTypeForTemplateLiteralPlaceholder(source, t)); + } + if (target.flags & 4 /* String */ || isTypeAssignableTo(source, target)) { + return true; + } + if (source.flags & 128 /* StringLiteral */) { + const value = source.value; + return !!(target.flags & 8 /* Number */ && isValidNumberString( + value, + /*roundTripOnly*/ + false + ) || target.flags & 64 /* BigInt */ && isValidBigIntString( + value, + /*roundTripOnly*/ + false + ) || target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName || target.flags & 268435456 /* StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target) || target.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source, target)); + } + if (source.flags & 134217728 /* TemplateLiteral */) { + const texts = source.texts; + return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target); + } + return false; + } + function inferTypesFromTemplateLiteralType(source, target) { + return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], emptyArray, target) : source.flags & 134217728 /* TemplateLiteral */ ? arrayIsEqualTo(source.texts, target.texts) ? map(source.types, (s, i) => { + return isTypeAssignableTo(getBaseConstraintOrType(s), getBaseConstraintOrType(target.types[i])) ? s : getStringLikeTypeForType(s); + }) : inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : void 0; + } + function isTypeMatchedByTemplateLiteralType(source, target) { + const inferences = inferTypesFromTemplateLiteralType(source, target); + return !!inferences && every(inferences, (r, i) => isValidTypeForTemplateLiteralPlaceholder(r, target.types[i])); + } + function getStringLikeTypeForType(type) { + return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); + } + function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) { + const lastSourceIndex = sourceTexts.length - 1; + const sourceStartText = sourceTexts[0]; + const sourceEndText = sourceTexts[lastSourceIndex]; + const targetTexts = target.texts; + const lastTargetIndex = targetTexts.length - 1; + const targetStartText = targetTexts[0]; + const targetEndText = targetTexts[lastTargetIndex]; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return void 0; + const remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); + const matches = []; + let seg = 0; + let pos = targetStartText.length; + for (let i = 1; i < lastTargetIndex; i++) { + const delim = targetTexts[i]; + if (delim.length > 0) { + let s = seg; + let p = pos; + while (true) { + p = getSourceText(s).indexOf(delim, p); + if (p >= 0) break; + s++; + if (s === sourceTexts.length) return void 0; + p = 0; + } + addMatch(s, p); + pos += delim.length; + } else if (pos < getSourceText(seg).length) { + addMatch(seg, pos + 1); + } else if (seg < lastSourceIndex) { + addMatch(seg + 1, 0); + } else { + return void 0; + } + } + addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length); + return matches; + function getSourceText(index) { + return index < lastSourceIndex ? sourceTexts[index] : remainingEndText; + } + function addMatch(s, p) { + const matchType = s === seg ? getStringLiteralType(getSourceText(s).slice(pos, p)) : getTemplateLiteralType( + [sourceTexts[seg].slice(pos), ...sourceTexts.slice(seg + 1, s), getSourceText(s).slice(0, p)], + sourceTypes.slice(seg, s) + ); + matches.push(matchType); + seg = s; + pos = p; + } + } + function isTupleOfSelf(typeParameter, type) { + return isTupleType(type) && getTupleElementType(type, 0) === getIndexedAccessType(typeParameter, getNumberLiteralType(0)) && !getTypeOfPropertyOfType(type, "1"); + } + function inferTypes(inferences, originalSource, originalTarget, priority = 0 /* None */, contravariant = false) { + let bivariant = false; + let propagationType; + let inferencePriority = 2048 /* MaxValue */; + let visited; + let sourceStack; + let targetStack; + let expandingFlags = 0 /* None */; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target) || isNoInferType(target)) { + return; + } + if (source === wildcardType || source === blockedStringType) { + const savePropagationType = propagationType; + propagationType = source; + inferFromTypes(target, target); + propagationType = savePropagationType; + return; + } + if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) { + if (source.aliasTypeArguments) { + const params = getSymbolLinks(source.aliasSymbol).typeParameters; + const minParams = getMinTypeArgumentCount(params); + const sourceTypes = fillMissingTypeArguments(source.aliasTypeArguments, params, minParams, isInJSFile(source.aliasSymbol.valueDeclaration)); + const targetTypes = fillMissingTypeArguments(target.aliasTypeArguments, params, minParams, isInJSFile(source.aliasSymbol.valueDeclaration)); + inferFromTypeArguments(sourceTypes, targetTypes, getAliasVariances(source.aliasSymbol)); + } + return; + } + if (source === target && source.flags & 3145728 /* UnionOrIntersection */) { + for (const t of source.types) { + inferFromTypes(t, t); + } + return; + } + if (target.flags & 1048576 /* Union */) { + const [tempSources, tempTargets] = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo); + const [sources, targets] = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy); + if (targets.length === 0) { + return; + } + target = getUnionType(targets); + if (sources.length === 0) { + inferWithPriority(source, target, 1 /* NakedTypeVariable */); + return; + } + source = getUnionType(sources); + } else if (target.flags & 2097152 /* Intersection */ && !every(target.types, isNonGenericObjectType)) { + if (!(source.flags & 1048576 /* Union */)) { + const [sources, targets] = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo); + if (sources.length === 0 || targets.length === 0) { + return; + } + source = getIntersectionType(sources); + target = getIntersectionType(targets); + } + } + if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) { + if (isNoInferType(target)) { + return; + } + target = getActualTypeVariable(target); + } + if (target.flags & 8650752 /* TypeVariable */) { + if (isFromInferenceBlockedSource(source)) { + return; + } + const inference = getInferenceInfoForType(target); + if (inference) { + if (getObjectFlags(source) & 262144 /* NonInferrableType */ || source === nonInferrableAnyType) { + return; + } + if (!inference.isFixed) { + const candidate = propagationType || source; + if (candidate === blockedStringType) { + return; + } + if (inference.priority === void 0 || priority < inference.priority) { + inference.candidates = void 0; + inference.contraCandidates = void 0; + inference.topLevel = true; + inference.priority = priority; + } + if (priority === inference.priority) { + if (isTupleOfSelf(inference.typeParameter, candidate)) { + return; + } + if (contravariant && !bivariant) { + if (!contains(inference.contraCandidates, candidate)) { + inference.contraCandidates = append(inference.contraCandidates, candidate); + clearCachedInferences(inferences); + } + } else if (!contains(inference.candidates, candidate)) { + inference.candidates = append(inference.candidates, candidate); + clearCachedInferences(inferences); + } + } + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + clearCachedInferences(inferences); + } + } + inferencePriority = Math.min(inferencePriority, priority); + return; + } + const simplified = getSimplifiedType( + target, + /*writing*/ + false + ); + if (simplified !== target) { + inferFromTypes(source, simplified); + } else if (target.flags & 8388608 /* IndexedAccess */) { + const indexType = getSimplifiedType( + target.indexType, + /*writing*/ + false + ); + if (indexType.flags & 465829888 /* Instantiable */) { + const simplified2 = distributeIndexOverObjectType( + getSimplifiedType( + target.objectType, + /*writing*/ + false + ), + indexType, + /*writing*/ + false + ); + if (simplified2 && simplified2 !== target) { + inferFromTypes(source, simplified2); + } + } + } + } + if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) && !(source.node && target.node)) { + inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); + } else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) { + inferFromContravariantTypes(source.type, target.type); + } else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { + const empty = createEmptyObjectTypeFromStringLiteral(source); + inferFromContravariantTypesWithPriority(empty, target.type, 256 /* LiteralKeyof */); + } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } else if (source.flags & 268435456 /* StringMapping */ && target.flags & 268435456 /* StringMapping */) { + if (source.symbol === target.symbol) { + inferFromTypes(source.type, target.type); + } + } else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + inferWithPriority(getSubstitutionIntersection(source), target, 4 /* SubstituteSource */); + } else if (target.flags & 16777216 /* Conditional */) { + invokeOnce(source, target, inferToConditionalType); + } else if (target.flags & 3145728 /* UnionOrIntersection */) { + inferToMultipleTypes(source, target.types, target.flags); + } else if (source.flags & 1048576 /* Union */) { + const sourceTypes = source.types; + for (const sourceType of sourceTypes) { + inferFromTypes(sourceType, target); + } + } else if (target.flags & 134217728 /* TemplateLiteral */) { + inferToTemplateLiteralType(source, target); + } else { + source = getReducedType(source); + if (isGenericMappedType(source) && isGenericMappedType(target)) { + invokeOnce(source, target, inferFromGenericMappedTypes); + } + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + const apparentSource = getApparentType(source); + if (apparentSource !== source && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) { + return inferFromTypes(apparentSource, target); + } + source = apparentSource; + } + if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { + invokeOnce(source, target, inferFromObjectTypes); + } + } + } + function inferWithPriority(source, target, newPriority) { + const savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } + function inferFromContravariantTypesWithPriority(source, target, newPriority) { + const savePriority = priority; + priority |= newPriority; + inferFromContravariantTypes(source, target); + priority = savePriority; + } + function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) { + const savePriority = priority; + priority |= newPriority; + inferToMultipleTypes(source, targets, targetFlags); + priority = savePriority; + } + function invokeOnce(source, target, action) { + const key = source.id + "," + target.id; + const status = visited && visited.get(key); + if (status !== void 0) { + inferencePriority = Math.min(inferencePriority, status); + return; + } + (visited || (visited = /* @__PURE__ */ new Map())).set(key, -1 /* Circularity */); + const saveInferencePriority = inferencePriority; + inferencePriority = 2048 /* MaxValue */; + const saveExpandingFlags = expandingFlags; + (sourceStack ?? (sourceStack = [])).push(source); + (targetStack ?? (targetStack = [])).push(target); + if (isDeeplyNestedType(source, sourceStack, sourceStack.length, 2)) expandingFlags |= 1 /* Source */; + if (isDeeplyNestedType(target, targetStack, targetStack.length, 2)) expandingFlags |= 2 /* Target */; + if (expandingFlags !== 3 /* Both */) { + action(source, target); + } else { + inferencePriority = -1 /* Circularity */; + } + targetStack.pop(); + sourceStack.pop(); + expandingFlags = saveExpandingFlags; + visited.set(key, inferencePriority); + inferencePriority = Math.min(inferencePriority, saveInferencePriority); + } + function inferFromMatchingTypes(sources, targets, matches) { + let matchedSources; + let matchedTargets; + for (const t of targets) { + for (const s of sources) { + if (matches(s, t)) { + inferFromTypes(s, t); + matchedSources = appendIfUnique(matchedSources, s); + matchedTargets = appendIfUnique(matchedTargets, t); + } + } + } + return [ + matchedSources ? filter(sources, (t) => !contains(matchedSources, t)) : sources, + matchedTargets ? filter(targets, (t) => !contains(matchedTargets, t)) : targets + ]; + } + function inferFromTypeArguments(sourceTypes, targetTypes, variances) { + const count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + for (let i = 0; i < count; i++) { + if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) { + inferFromContravariantTypes(sourceTypes[i], targetTypes[i]); + } else { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + } + function inferFromContravariantTypes(source, target) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + function inferFromContravariantTypesIfStrictFunctionTypes(source, target) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { + inferFromContravariantTypes(source, target); + } else { + inferFromTypes(source, target); + } + } + function getInferenceInfoForType(type) { + if (type.flags & 8650752 /* TypeVariable */) { + for (const inference of inferences) { + if (type === inference.typeParameter) { + return inference; + } + } + } + return void 0; + } + function getSingleTypeVariableFromIntersectionTypes(types) { + let typeVariable; + for (const type of types) { + const t = type.flags & 2097152 /* Intersection */ && find(type.types, (t2) => !!getInferenceInfoForType(t2)); + if (!t || typeVariable && t !== typeVariable) { + return void 0; + } + typeVariable = t; + } + return typeVariable; + } + function inferToMultipleTypes(source, targets, targetFlags) { + let typeVariableCount = 0; + if (targetFlags & 1048576 /* Union */) { + let nakedTypeVariable; + const sources = source.flags & 1048576 /* Union */ ? source.types : [source]; + const matched = new Array(sources.length); + let inferenceCircularity = false; + for (const t of targets) { + if (getInferenceInfoForType(t)) { + nakedTypeVariable = t; + typeVariableCount++; + } else { + for (let i = 0; i < sources.length; i++) { + const saveInferencePriority = inferencePriority; + inferencePriority = 2048 /* MaxValue */; + inferFromTypes(sources[i], t); + if (inferencePriority === priority) matched[i] = true; + inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */; + inferencePriority = Math.min(inferencePriority, saveInferencePriority); + } + } + } + if (typeVariableCount === 0) { + const intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } + if (typeVariableCount === 1 && !inferenceCircularity) { + const unmatched = flatMap(sources, (s, i) => matched[i] ? void 0 : s); + if (unmatched.length) { + inferFromTypes(getUnionType(unmatched), nakedTypeVariable); + return; + } + } + } else { + for (const t of targets) { + if (getInferenceInfoForType(t)) { + typeVariableCount++; + } else { + inferFromTypes(source, t); + } + } + } + if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { + for (const t of targets) { + if (getInferenceInfoForType(t)) { + inferWithPriority(source, t, 1 /* NakedTypeVariable */); + } + } + } + } + function inferToMappedType(source, target, constraintType) { + if (constraintType.flags & 1048576 /* Union */ || constraintType.flags & 2097152 /* Intersection */) { + let result = false; + for (const type of constraintType.types) { + result = inferToMappedType(source, target, type) || result; + } + return result; + } + if (constraintType.flags & 4194304 /* Index */) { + const inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) { + const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + inferWithPriority( + inferredType, + inference.typeParameter, + getObjectFlags(source) & 262144 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */ + ); + } + } + return true; + } + if (constraintType.flags & 262144 /* TypeParameter */) { + inferWithPriority(getIndexType( + source, + /*indexFlags*/ + !!source.pattern ? 2 /* NoIndexSignatures */ : 0 /* None */ + ), constraintType, 32 /* MappedTypeConstraint */); + const extendedConstraint = getConstraintOfType(constraintType); + if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) { + return true; + } + const propTypes = map(getPropertiesOfType(source), getTypeOfSymbol); + const indexTypes = map(getIndexInfosOfType(source), (info) => info !== enumNumberIndexInfo ? info.type : neverType); + inferFromTypes(getUnionType(concatenate(propTypes, indexTypes)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } + function inferToConditionalType(source, target) { + if (source.flags & 16777216 /* Conditional */) { + inferFromTypes(source.checkType, target.checkType); + inferFromTypes(source.extendsType, target.extendsType); + inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + } else { + const targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; + inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? 64 /* ContravariantConditional */ : 0); + } + } + function inferToTemplateLiteralType(source, target) { + const matches = inferTypesFromTemplateLiteralType(source, target); + const types = target.types; + if (matches || every(target.texts, (s) => s.length === 0)) { + for (let i = 0; i < types.length; i++) { + const source2 = matches ? matches[i] : neverType; + const target2 = types[i]; + if (source2.flags & 128 /* StringLiteral */ && target2.flags & 8650752 /* TypeVariable */) { + const inferenceContext = getInferenceInfoForType(target2); + const constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : void 0; + if (constraint && !isTypeAny(constraint)) { + const constraintTypes = constraint.flags & 1048576 /* Union */ ? constraint.types : [constraint]; + let allTypeFlags = reduceLeft(constraintTypes, (flags, t) => flags | t.flags, 0); + if (!(allTypeFlags & 4 /* String */)) { + const str = source2.value; + if (allTypeFlags & 296 /* NumberLike */ && !isValidNumberString( + str, + /*roundTripOnly*/ + true + )) { + allTypeFlags &= ~296 /* NumberLike */; + } + if (allTypeFlags & 2112 /* BigIntLike */ && !isValidBigIntString( + str, + /*roundTripOnly*/ + true + )) { + allTypeFlags &= ~2112 /* BigIntLike */; + } + const matchingType = reduceLeft(constraintTypes, (left, right) => !(right.flags & allTypeFlags) ? left : left.flags & 4 /* String */ ? left : right.flags & 4 /* String */ ? source2 : left.flags & 134217728 /* TemplateLiteral */ ? left : right.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source2, right) ? source2 : left.flags & 268435456 /* StringMapping */ ? left : right.flags & 268435456 /* StringMapping */ && str === applyStringMapping(right.symbol, str) ? source2 : left.flags & 128 /* StringLiteral */ ? left : right.flags & 128 /* StringLiteral */ && right.value === str ? right : left.flags & 8 /* Number */ ? left : right.flags & 8 /* Number */ ? getNumberLiteralType(+str) : left.flags & 32 /* Enum */ ? left : right.flags & 32 /* Enum */ ? getNumberLiteralType(+str) : left.flags & 256 /* NumberLiteral */ ? left : right.flags & 256 /* NumberLiteral */ && right.value === +str ? right : left.flags & 64 /* BigInt */ ? left : right.flags & 64 /* BigInt */ ? parseBigIntLiteralType(str) : left.flags & 2048 /* BigIntLiteral */ ? left : right.flags & 2048 /* BigIntLiteral */ && pseudoBigIntToString(right.value) === str ? right : left.flags & 16 /* Boolean */ ? left : right.flags & 16 /* Boolean */ ? str === "true" ? trueType : str === "false" ? falseType : booleanType : left.flags & 512 /* BooleanLiteral */ ? left : right.flags & 512 /* BooleanLiteral */ && right.intrinsicName === str ? right : left.flags & 32768 /* Undefined */ ? left : right.flags & 32768 /* Undefined */ && right.intrinsicName === str ? right : left.flags & 65536 /* Null */ ? left : right.flags & 65536 /* Null */ && right.intrinsicName === str ? right : left, neverType); + if (!(matchingType.flags & 131072 /* Never */)) { + inferFromTypes(matchingType, target2); + continue; + } + } + } + } + inferFromTypes(source2, target2); + } + } + } + function inferFromGenericMappedTypes(source, target) { + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + const sourceNameType = getNameTypeFromMappedType(source); + const targetNameType = getNameTypeFromMappedType(target); + if (sourceNameType && targetNameType) inferFromTypes(sourceNameType, targetNameType); + } + function inferFromObjectTypes(source, target) { + var _a, _b; + if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) { + inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); + return; + } + if (isGenericMappedType(source) && isGenericMappedType(target)) { + inferFromGenericMappedTypes(source, target); + } + if (getObjectFlags(target) & 32 /* Mapped */ && !target.declaration.nameType) { + const constraintType = getConstraintTypeFromMappedType(target); + if (inferToMappedType(source, target, constraintType)) { + return; + } + } + if (!typesDefinitelyUnrelated(source, target)) { + if (isArrayOrTupleType(source)) { + if (isTupleType(target)) { + const sourceArity = getTypeReferenceArity(source); + const targetArity = getTypeReferenceArity(target); + const elementTypes = getTypeArguments(target); + const elementFlags = target.target.elementFlags; + if (isTupleType(source) && isTupleTypeStructureMatching(source, target)) { + for (let i = 0; i < targetArity; i++) { + inferFromTypes(getTypeArguments(source)[i], elementTypes[i]); + } + return; + } + const startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0; + const endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, 3 /* Fixed */) : 0, target.target.combinedFlags & 12 /* Variable */ ? getEndElementCount(target.target, 3 /* Fixed */) : 0); + for (let i = 0; i < startLength; i++) { + inferFromTypes(getTypeArguments(source)[i], elementTypes[i]); + } + if (!isTupleType(source) || sourceArity - startLength - endLength === 1 && source.target.elementFlags[startLength] & 4 /* Rest */) { + const restType = getTypeArguments(source)[startLength]; + for (let i = startLength; i < targetArity - endLength; i++) { + inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(restType) : restType, elementTypes[i]); + } + } else { + const middleLength = targetArity - startLength - endLength; + if (middleLength === 2) { + if (elementFlags[startLength] & elementFlags[startLength + 1] & 8 /* Variadic */) { + const targetInfo = getInferenceInfoForType(elementTypes[startLength]); + if (targetInfo && targetInfo.impliedArity !== void 0) { + inferFromTypes(sliceTupleType(source, startLength, endLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]); + inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, endLength), elementTypes[startLength + 1]); + } + } else if (elementFlags[startLength] & 8 /* Variadic */ && elementFlags[startLength + 1] & 4 /* Rest */) { + const param = (_a = getInferenceInfoForType(elementTypes[startLength])) == null ? void 0 : _a.typeParameter; + const constraint = param && getBaseConstraintOfType(param); + if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & 12 /* Variable */)) { + const impliedArity = constraint.target.fixedLength; + inferFromTypes(sliceTupleType(source, startLength, sourceArity - (startLength + impliedArity)), elementTypes[startLength]); + inferFromTypes(getElementTypeOfSliceOfTupleType(source, startLength + impliedArity, endLength), elementTypes[startLength + 1]); + } + } else if (elementFlags[startLength] & 4 /* Rest */ && elementFlags[startLength + 1] & 8 /* Variadic */) { + const param = (_b = getInferenceInfoForType(elementTypes[startLength + 1])) == null ? void 0 : _b.typeParameter; + const constraint = param && getBaseConstraintOfType(param); + if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & 12 /* Variable */)) { + const impliedArity = constraint.target.fixedLength; + const endIndex = sourceArity - getEndElementCount(target.target, 3 /* Fixed */); + const startIndex = endIndex - impliedArity; + const trailingSlice = createTupleType( + getTypeArguments(source).slice(startIndex, endIndex), + source.target.elementFlags.slice(startIndex, endIndex), + /*readonly*/ + false, + source.target.labeledElementDeclarations && source.target.labeledElementDeclarations.slice(startIndex, endIndex) + ); + inferFromTypes(getElementTypeOfSliceOfTupleType(source, startLength, endLength + impliedArity), elementTypes[startLength]); + inferFromTypes(trailingSlice, elementTypes[startLength + 1]); + } + } + } else if (middleLength === 1 && elementFlags[startLength] & 8 /* Variadic */) { + const endsInOptional = target.target.elementFlags[targetArity - 1] & 2 /* Optional */; + const sourceSlice = sliceTupleType(source, startLength, endLength); + inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? 2 /* SpeculativeTuple */ : 0); + } else if (middleLength === 1 && elementFlags[startLength] & 4 /* Rest */) { + const restType = getElementTypeOfSliceOfTupleType(source, startLength, endLength); + if (restType) { + inferFromTypes(restType, elementTypes[startLength]); + } + } + } + for (let i = 0; i < endLength; i++) { + inferFromTypes(getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]); + } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } + } + function inferFromProperties(source, target) { + const properties = getPropertiesOfObjectType(target); + for (const targetProp of properties) { + const sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && !some(sourceProp.declarations, hasSkipDirectInferenceFlag)) { + inferFromTypes( + removeMissingType(getTypeOfSymbol(sourceProp), !!(sourceProp.flags & 16777216 /* Optional */)), + removeMissingType(getTypeOfSymbol(targetProp), !!(targetProp.flags & 16777216 /* Optional */)) + ); + } + } + } + function inferFromSignatures(source, target, kind) { + const sourceSignatures = getSignaturesOfType(source, kind); + const sourceLen = sourceSignatures.length; + if (sourceLen > 0) { + const targetSignatures = getSignaturesOfType(target, kind); + const targetLen = targetSignatures.length; + for (let i = 0; i < targetLen; i++) { + const sourceIndex = Math.max(sourceLen - targetLen + i, 0); + inferFromSignature(getBaseSignature(sourceSignatures[sourceIndex]), getErasedSignature(targetSignatures[i])); + } + } + } + function inferFromSignature(source, target) { + if (!(source.flags & 64 /* IsNonInferrable */)) { + const saveBivariant = bivariant; + const kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + bivariant = bivariant || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 176 /* Constructor */; + applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); + bivariant = saveBivariant; + } + applyToReturnTypes(source, target, inferFromTypes); + } + function inferFromIndexTypes(source, target) { + const priority2 = getObjectFlags(source) & getObjectFlags(target) & 32 /* Mapped */ ? 8 /* HomomorphicMappedType */ : 0; + const indexInfos = getIndexInfosOfType(target); + if (isObjectTypeWithInferableIndex(source)) { + for (const targetInfo of indexInfos) { + const propTypes = []; + for (const prop of getPropertiesOfType(source)) { + if (isApplicableIndexType(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), targetInfo.keyType)) { + const propType = getTypeOfSymbol(prop); + propTypes.push(prop.flags & 16777216 /* Optional */ ? removeMissingOrUndefinedType(propType) : propType); + } + } + for (const info of getIndexInfosOfType(source)) { + if (isApplicableIndexType(info.keyType, targetInfo.keyType)) { + propTypes.push(info.type); + } + } + if (propTypes.length) { + inferWithPriority(getUnionType(propTypes), targetInfo.type, priority2); + } + } + } + for (const targetInfo of indexInfos) { + const sourceInfo = getApplicableIndexInfo(source, targetInfo.keyType); + if (sourceInfo) { + inferWithPriority(sourceInfo.type, targetInfo.type, priority2); + } + } + } + } + function isTypeOrBaseIdenticalTo(s, t) { + return t === missingType ? s === t : isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + } + function isTypeCloselyMatchedBy(s, t) { + return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol); + } + function hasPrimitiveConstraint(type) { + const constraint = getConstraintOfTypeParameter(type); + return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 402784252 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */); + } + function isObjectLiteralType(type) { + return !!(getObjectFlags(type) & 128 /* ObjectLiteral */); + } + function isObjectOrArrayLiteralType(type) { + return !!(getObjectFlags(type) & (128 /* ObjectLiteral */ | 16384 /* ArrayLiteral */)); + } + function unionObjectAndArrayLiteralCandidates(candidates) { + if (candidates.length > 1) { + const objectLiterals = filter(candidates, isObjectOrArrayLiteralType); + if (objectLiterals.length) { + const literalsType = getUnionType(objectLiterals, 2 /* Subtype */); + return concatenate(filter(candidates, (t) => !isObjectOrArrayLiteralType(t)), [literalsType]); + } + } + return candidates; + } + function getContravariantInference(inference) { + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + } + function getCovariantInference(inference, signature) { + const candidates = unionObjectAndArrayLiteralCandidates(inference.candidates); + const primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter) || isConstTypeVariable(inference.typeParameter); + const widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevelInReturnType(signature, inference.typeParameter)); + const baseCandidates = primitiveConstraint ? sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? sameMap(candidates, getWidenedLiteralType) : candidates; + const unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); + return getWidenedType(unwidenedType); + } + function getInferredType(context, index) { + const inference = context.inferences[index]; + if (!inference.inferredType) { + let inferredType; + let fallbackType; + if (context.signature) { + const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0; + const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0; + if (inferredCovariantType || inferredContravariantType) { + const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & (131072 /* Never */ | 1 /* Any */)) && some(inference.contraCandidates, (t) => isTypeAssignableTo(inferredCovariantType, t)) && every(context.inferences, (other) => other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || every(other.candidates, (t) => isTypeAssignableTo(t, inferredCovariantType)))); + inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType; + fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType; + } else if (context.flags & 1 /* NoDefault */) { + inferredType = silentNeverType; + } else { + const defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper)); + } + } + } else { + inferredType = getTypeFromInference(inference); + } + inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); + const constraint = getConstraintOfTypeParameter(inference.typeParameter); + if (constraint) { + const instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper); + if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = fallbackType && context.compareTypes(fallbackType, getTypeWithThisArgument(instantiatedConstraint, fallbackType)) ? fallbackType : instantiatedConstraint; + } + } + } + return inference.inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : unknownType; + } + function getInferredTypes(context) { + const result = []; + for (let i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + function getCannotFindNameDiagnosticForName(node) { + switch (node.escapedText) { + case "document": + case "console": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode; + case "Bun": + return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_and_then_add_bun_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + case "SharedArrayBuffer": + case "Atomics": + case "AsyncIterable": + case "AsyncIterableIterator": + case "AsyncGenerator": + case "AsyncGeneratorFunction": + case "BigInt": + case "Reflect": + case "BigInt64Array": + case "BigUint64Array": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later; + case "await": + if (isCallExpression(node.parent)) { + return Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function; + } + // falls through + default: + if (node.parent.kind === 304 /* ShorthandPropertyAssignment */) { + return Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; + } else { + return Diagnostics.Cannot_find_name_0; + } + } + } + function getResolvedSymbol(node) { + const links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !nodeIsMissing(node) && resolveName( + node, + node, + 111551 /* Value */ | 1048576 /* ExportValue */, + getCannotFindNameDiagnosticForName(node), + !isWriteOnlyAccess(node), + /*excludeGlobals*/ + false + ) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInAmbientOrTypeNode(node) { + return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, (n) => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n))); + } + function getFlowCacheKey(node, declaredType, initialType, flowContainer) { + switch (node.kind) { + case 80 /* Identifier */: + if (!isThisInTypeQuery(node)) { + const symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${getSymbolId(symbol)}` : void 0; + } + // falls through + case 110 /* ThisKeyword */: + return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`; + case 235 /* NonNullExpression */: + case 217 /* ParenthesizedExpression */: + return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); + case 166 /* QualifiedName */: + const left = getFlowCacheKey(node.left, declaredType, initialType, flowContainer); + return left && `${left}.${node.right.escapedText}`; + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + const propName = getAccessedPropertyName(node); + if (propName !== void 0) { + const key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); + return key && `${key}.${propName}`; + } + if (isElementAccessExpression(node) && isIdentifier(node.argumentExpression)) { + const symbol = getResolvedSymbol(node.argumentExpression); + if (isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol)) { + const key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); + return key && `${key}.@${getSymbolId(symbol)}`; + } + } + break; + case 206 /* ObjectBindingPattern */: + case 207 /* ArrayBindingPattern */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 174 /* MethodDeclaration */: + return `${getNodeId(node)}#${getTypeId(declaredType)}`; + } + return void 0; + } + function isMatchingReference(source, target) { + switch (target.kind) { + case 217 /* ParenthesizedExpression */: + case 235 /* NonNullExpression */: + return isMatchingReference(source, target.expression); + case 226 /* BinaryExpression */: + return isAssignmentExpression(target) && isMatchingReference(source, target.left) || isBinaryExpression(target) && target.operatorToken.kind === 28 /* CommaToken */ && isMatchingReference(source, target.right); + } + switch (source.kind) { + case 236 /* MetaProperty */: + return target.kind === 236 /* MetaProperty */ && source.keywordToken === target.keywordToken && source.name.escapedText === target.name.escapedText; + case 80 /* Identifier */: + case 81 /* PrivateIdentifier */: + return isThisInTypeQuery(source) ? target.kind === 110 /* ThisKeyword */ : target.kind === 80 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || (isVariableDeclaration(target) || isBindingElement(target)) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfDeclaration(target); + case 110 /* ThisKeyword */: + return target.kind === 110 /* ThisKeyword */; + case 108 /* SuperKeyword */: + return target.kind === 108 /* SuperKeyword */; + case 235 /* NonNullExpression */: + case 217 /* ParenthesizedExpression */: + case 238 /* SatisfiesExpression */: + return isMatchingReference(source.expression, target); + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + const sourcePropertyName = getAccessedPropertyName(source); + if (sourcePropertyName !== void 0) { + const targetPropertyName = isAccessExpression(target) ? getAccessedPropertyName(target) : void 0; + if (targetPropertyName !== void 0) { + return targetPropertyName === sourcePropertyName && isMatchingReference(source.expression, target.expression); + } + } + if (isElementAccessExpression(source) && isElementAccessExpression(target) && isIdentifier(source.argumentExpression) && isIdentifier(target.argumentExpression)) { + const symbol = getResolvedSymbol(source.argumentExpression); + if (symbol === getResolvedSymbol(target.argumentExpression) && (isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol))) { + return isMatchingReference(source.expression, target.expression); + } + } + break; + case 166 /* QualifiedName */: + return isAccessExpression(target) && source.right.escapedText === getAccessedPropertyName(target) && isMatchingReference(source.left, target.expression); + case 226 /* BinaryExpression */: + return isBinaryExpression(source) && source.operatorToken.kind === 28 /* CommaToken */ && isMatchingReference(source.right, target); + } + return false; + } + function getAccessedPropertyName(access) { + if (isPropertyAccessExpression(access)) { + return access.name.escapedText; + } + if (isElementAccessExpression(access)) { + return tryGetElementAccessExpressionName(access); + } + if (isBindingElement(access)) { + const name = getDestructuringPropertyName(access); + return name ? escapeLeadingUnderscores(name) : void 0; + } + if (isParameter(access)) { + return "" + access.parent.parameters.indexOf(access); + } + return void 0; + } + function tryGetNameFromType(type) { + return type.flags & 8192 /* UniqueESSymbol */ ? type.escapedName : type.flags & 384 /* StringOrNumberLiteral */ ? escapeLeadingUnderscores("" + type.value) : void 0; + } + function tryGetElementAccessExpressionName(node) { + return isStringOrNumericLiteralLike(node.argumentExpression) ? escapeLeadingUnderscores(node.argumentExpression.text) : isEntityNameExpression(node.argumentExpression) ? tryGetNameFromEntityNameExpression(node.argumentExpression) : void 0; + } + function tryGetNameFromEntityNameExpression(node) { + const symbol = resolveEntityName( + node, + 111551 /* Value */, + /*ignoreErrors*/ + true + ); + if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* EnumMember */)) return void 0; + const declaration = symbol.valueDeclaration; + if (declaration === void 0) return void 0; + const type = tryGetTypeFromEffectiveTypeNode(declaration); + if (type) { + const name = tryGetNameFromType(type); + if (name !== void 0) { + return name; + } + } + if (hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node)) { + const initializer = getEffectiveInitializer(declaration); + if (initializer) { + const initializerType = isBindingPattern(declaration.parent) ? getTypeForBindingElement(declaration) : getTypeOfExpression(initializer); + return initializerType && tryGetNameFromType(initializerType); + } + if (isEnumMember(declaration)) { + return getTextOfPropertyName(declaration.name); + } + } + return void 0; + } + function containsMatchingReference(source, target) { + while (isAccessExpression(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + function optionalChainContainsReference(source, target) { + while (isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 1048576 /* Union */) { + const prop = getUnionOrIntersectionProperty(type, name); + if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.links.isDiscriminantProperty === void 0) { + prop.links.isDiscriminantProperty = (prop.links.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ && !isGenericType(getTypeOfSymbol(prop)); + } + return !!prop.links.isDiscriminantProperty; + } + } + return false; + } + function findDiscriminantProperties(sourceProperties, target) { + let result; + for (const sourceProperty of sourceProperties) { + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + if (result) { + result.push(sourceProperty); + continue; + } + result = [sourceProperty]; + } + } + return result; + } + function mapTypesByKeyProperty(types, name) { + const map2 = /* @__PURE__ */ new Map(); + let count = 0; + for (const type of types) { + if (type.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + const discriminant = getTypeOfPropertyOfType(type, name); + if (discriminant) { + if (!isLiteralType(discriminant)) { + return void 0; + } + let duplicate = false; + forEachType(discriminant, (t) => { + const id = getTypeId(getRegularTypeOfLiteralType(t)); + const existing = map2.get(id); + if (!existing) { + map2.set(id, type); + } else if (existing !== unknownType) { + map2.set(id, unknownType); + duplicate = true; + } + }); + if (!duplicate) count++; + } + } + } + return count >= 10 && count * 2 >= types.length ? map2 : void 0; + } + function getKeyPropertyName(unionType) { + const types = unionType.types; + if (types.length < 10 || getObjectFlags(unionType) & 32768 /* PrimitiveUnion */ || countWhere(types, (t) => !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */))) < 10) { + return void 0; + } + if (unionType.keyPropertyName === void 0) { + const keyPropertyName = forEach(types, (t) => t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? forEach(getPropertiesOfType(t), (p) => isUnitType(getTypeOfSymbol(p)) ? p.escapedName : void 0) : void 0); + const mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName); + unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : ""; + unionType.constituentMap = mapByKeyProperty; + } + return unionType.keyPropertyName.length ? unionType.keyPropertyName : void 0; + } + function getConstituentTypeForKeyType(unionType, keyType) { + var _a; + const result = (_a = unionType.constituentMap) == null ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType))); + return result !== unknownType ? result : void 0; + } + function getMatchingUnionConstituentForType(unionType, type) { + const keyPropertyName = getKeyPropertyName(unionType); + const propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + function getMatchingUnionConstituentForObjectLiteral(unionType, node) { + const keyPropertyName = getKeyPropertyName(unionType); + const propNode = keyPropertyName && find(node.properties, (p) => p.symbol && p.kind === 303 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer)); + const propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(expression, reference) { + if (expression.arguments) { + for (const argument of expression.arguments) { + if (isOrContainsMatchingReference(reference, argument) || optionalChainContainsReference(argument, reference)) { + return true; + } + } + } + if (expression.expression.kind === 211 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (flow.id <= 0) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 1048576 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (const t of source.types) { + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType === assignedType) { + return declaredType; + } + if (assignedType.flags & 131072 /* Never */) { + return assignedType; + } + const key = `A${getTypeId(declaredType)},${getTypeId(assignedType)}`; + return getCachedType(key) ?? setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + } + function getAssignmentReducedTypeWorker(declaredType, assignedType) { + const filteredType = filterType(declaredType, (t) => typeMaybeAssignableTo(assignedType, t)); + const reducedType = assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType; + return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; + } + function isFunctionObjectType(type) { + if (getObjectFlags(type) & 256 /* EvolvingArray */) { + return false; + } + const resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type, mask) { + return getTypeFactsWorker(type, mask) & mask; + } + function hasTypeFacts(type, mask) { + return getTypeFacts(type, mask) !== 0; + } + function getTypeFactsWorker(type, callerOnlyNeeds) { + if (type.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */)) { + type = getBaseConstraintOfType(type) || unknownType; + } + const flags = type.flags; + if (flags & (4 /* String */ | 268435456 /* StringMapping */)) { + return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; + } + if (flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */)) { + const isEmpty = flags & 128 /* StringLiteral */ && type.value === ""; + return strictNullChecks ? isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; + } + if (flags & (8 /* Number */ | 32 /* Enum */)) { + return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; + } + if (flags & 256 /* NumberLiteral */) { + const isZero = type.value === 0; + return strictNullChecks ? isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; + } + if (flags & 64 /* BigInt */) { + return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; + } + if (flags & 2048 /* BigIntLiteral */) { + const isZero = isZeroBigInt(type); + return strictNullChecks ? isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; + } + if (flags & 16 /* Boolean */) { + return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; + } + if (flags & 528 /* BooleanLike */) { + return strictNullChecks ? type === falseType || type === regularFalseType ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : type === falseType || type === regularFalseType ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; + } + if (flags & 524288 /* Object */) { + const possibleFacts = strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ | 7880640 /* FunctionStrictFacts */ | 7888800 /* ObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ | 16728e3 /* FunctionFacts */ | 16736160 /* ObjectFacts */; + if ((callerOnlyNeeds & possibleFacts) === 0) { + return 0; + } + return getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728e3 /* FunctionFacts */ : strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & 16384 /* Void */) { + return 9830144 /* VoidFacts */; + } + if (flags & 32768 /* Undefined */) { + return 26607360 /* UndefinedFacts */; + } + if (flags & 65536 /* Null */) { + return 42917664 /* NullFacts */; + } + if (flags & 12288 /* ESSymbolLike */) { + return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; + } + if (flags & 67108864 /* NonPrimitive */) { + return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; + } + if (flags & 131072 /* Never */) { + return 0 /* None */; + } + if (flags & 1048576 /* Union */) { + return reduceLeft(type.types, (facts, t) => facts | getTypeFactsWorker(t, callerOnlyNeeds), 0 /* None */); + } + if (flags & 2097152 /* Intersection */) { + return getIntersectionTypeFacts(type, callerOnlyNeeds); + } + return 83886079 /* UnknownFacts */; + } + function getIntersectionTypeFacts(type, callerOnlyNeeds) { + const ignoreObjects = maybeTypeOfKind(type, 402784252 /* Primitive */); + let oredFacts = 0 /* None */; + let andedFacts = 134217727 /* All */; + for (const t of type.types) { + if (!(ignoreObjects && t.flags & 524288 /* Object */)) { + const f = getTypeFactsWorker(t, callerOnlyNeeds); + oredFacts |= f; + andedFacts &= f; + } + } + return oredFacts & 8256 /* OrFactsMask */ | andedFacts & 134209471 /* AndFactsMask */; + } + function getTypeWithFacts(type, include) { + return filterType(type, (t) => hasTypeFacts(t, include)); + } + function getAdjustedTypeWithFacts(type, facts) { + const reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* Unknown */ ? unknownUnionType : type, facts)); + if (strictNullChecks) { + switch (facts) { + case 524288 /* NEUndefined */: + return removeNullableByIntersection(reduced, 65536 /* EQUndefined */, 131072 /* EQNull */, 33554432 /* IsNull */, nullType); + case 1048576 /* NENull */: + return removeNullableByIntersection(reduced, 131072 /* EQNull */, 65536 /* EQUndefined */, 16777216 /* IsUndefined */, undefinedType); + case 2097152 /* NEUndefinedOrNull */: + case 4194304 /* Truthy */: + return mapType(reduced, (t) => hasTypeFacts(t, 262144 /* EQUndefinedOrNull */) ? getGlobalNonNullableTypeInstantiation(t) : t); + } + } + return reduced; + } + function removeNullableByIntersection(type, targetFacts, otherFacts, otherIncludesFacts, otherType) { + const facts = getTypeFacts(type, 65536 /* EQUndefined */ | 131072 /* EQNull */ | 16777216 /* IsUndefined */ | 33554432 /* IsNull */); + if (!(facts & targetFacts)) { + return type; + } + const emptyAndOtherUnion = getUnionType([emptyObjectType, otherType]); + return mapType(type, (t) => hasTypeFacts(t, targetFacts) ? getIntersectionType([t, !(facts & otherIncludesFacts) && hasTypeFacts(t, otherFacts) ? emptyAndOtherUnion : emptyObjectType]) : t); + } + function recombineUnknownType(type) { + return type === unknownUnionType ? unknownType : type; + } + function getTypeWithDefault(type, defaultExpression) { + return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : type; + } + function getTypeOfDestructuredProperty(type, name) { + var _a; + const nameType = getLiteralTypeFromPropertyName(name); + if (!isTypeUsableAsPropertyName(nameType)) return errorType; + const text = getPropertyNameFromType(nameType); + return getTypeOfPropertyOfType(type, text) || includeUndefinedInIndexSignature((_a = getApplicableIndexInfoForName(type, text)) == null ? void 0 : _a.type) || errorType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || includeUndefinedInIndexSignature(checkIteratedTypeOrElementType( + 65 /* Destructuring */, + type, + undefinedType, + /*errorNode*/ + void 0 + )) || errorType; + } + function includeUndefinedInIndexSignature(type) { + if (!type) return type; + return compilerOptions.noUncheckedIndexedAccess ? getUnionType([type, missingType]) : type; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType( + 65 /* Destructuring */, + type, + undefinedType, + /*errorNode*/ + void 0 + ) || errorType); + } + function getAssignedTypeOfBinaryExpression(node) { + const isDestructuringDefaultAssignment = node.parent.kind === 209 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || node.parent.kind === 303 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 226 /* BinaryExpression */ && parent.parent.left === parent || parent.parent.kind === 250 /* ForOfStatement */ && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + const { parent } = node; + switch (parent.kind) { + case 249 /* ForInStatement */: + return stringType; + case 250 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent) || errorType; + case 226 /* BinaryExpression */: + return getAssignedTypeOfBinaryExpression(parent); + case 220 /* DeleteExpression */: + return undefinedType; + case 209 /* ArrayLiteralExpression */: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 230 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 303 /* PropertyAssignment */: + return getAssignedTypeOfPropertyAssignment(parent); + case 304 /* ShorthandPropertyAssignment */: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return errorType; + } + function getInitialTypeOfBindingElement(node) { + const pattern = node.parent; + const parentType = getInitialType(pattern.parent); + const type = pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + const links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 249 /* ForInStatement */) { + return stringType; + } + if (node.parent.parent.kind === 250 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent) || errorType; + } + return errorType; + } + function getInitialType(node) { + return node.kind === 260 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); + } + function isEmptyArrayAssignment(node) { + return node.kind === 260 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral2(node.initializer) || node.kind !== 208 /* BindingElement */ && node.parent.kind === 226 /* BinaryExpression */ && isEmptyArrayLiteral2(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 217 /* ParenthesizedExpression */: + return getReferenceCandidate(node.expression); + case 226 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 64 /* EqualsToken */: + case 76 /* BarBarEqualsToken */: + case 77 /* AmpersandAmpersandEqualsToken */: + case 78 /* QuestionQuestionEqualsToken */: + return getReferenceCandidate(node.left); + case 28 /* CommaToken */: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + const { parent } = node; + return parent.kind === 217 /* ParenthesizedExpression */ || parent.kind === 226 /* BinaryExpression */ && parent.operatorToken.kind === 64 /* EqualsToken */ && parent.left === node || parent.kind === 226 /* BinaryExpression */ && parent.operatorToken.kind === 28 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 296 /* CaseClause */) { + return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + const links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (const clause of switchStatement.caseBlock.clauses) { + links.switchTypes.push(getTypeOfSwitchClause(clause)); + } + } + return links.switchTypes; + } + function getSwitchClauseTypeOfWitnesses(switchStatement) { + if (some(switchStatement.caseBlock.clauses, (clause) => clause.kind === 296 /* CaseClause */ && !isStringLiteralLike(clause.expression))) { + return void 0; + } + const witnesses = []; + for (const clause of switchStatement.caseBlock.clauses) { + const text = clause.kind === 296 /* CaseClause */ ? clause.expression.text : void 0; + witnesses.push(text && !contains(witnesses, text) ? text : void 0); + } + return witnesses; + } + function eachTypeContainedIn(source, types) { + return source.flags & 1048576 /* Union */ ? !forEach(source.types, (t) => !contains(types, t)) : contains(types, source); + } + function isTypeSubsetOf(source, target) { + return !!(source === target || source.flags & 131072 /* Never */ || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target)); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 1048576 /* Union */) { + for (const t of source.types) { + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 1056 /* EnumLike */ && getBaseTypeOfEnumLikeType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 1048576 /* Union */ ? forEach(type.types, f) : f(type); + } + function someType(type, f) { + return type.flags & 1048576 /* Union */ ? some(type.types, f) : f(type); + } + function everyType(type, f) { + return type.flags & 1048576 /* Union */ ? every(type.types, f) : f(type); + } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? every(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 1048576 /* Union */) { + const types = type.types; + const filtered = filter(types, f); + if (filtered === types) { + return type; + } + const origin = type.origin; + let newOrigin; + if (origin && origin.flags & 1048576 /* Union */) { + const originTypes = origin.types; + const originFiltered = filter(originTypes, (t) => !!(t.flags & 1048576 /* Union */) || f(t)); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList( + filtered, + type.objectFlags & (32768 /* PrimitiveUnion */ | 16777216 /* ContainsIntersections */), + /*aliasSymbol*/ + void 0, + /*aliasTypeArguments*/ + void 0, + newOrigin + ); + } + return type.flags & 131072 /* Never */ || f(type) ? type : neverType; + } + function removeType(type, targetType) { + return filterType(type, (t) => t !== targetType); + } + function countTypes(type) { + return type.flags & 1048576 /* Union */ ? type.types.length : 1; + } + function mapType(type, mapper, noReductions) { + if (type.flags & 131072 /* Never */) { + return type; + } + if (!(type.flags & 1048576 /* Union */)) { + return mapper(type); + } + const origin = type.origin; + const types = origin && origin.flags & 1048576 /* Union */ ? origin.types : type.types; + let mappedTypes; + let changed = false; + for (const t of types) { + const mapped = t.flags & 1048576 /* Union */ ? mapType(t, mapper, noReductions) : mapper(t); + changed || (changed = t !== mapped); + if (mapped) { + if (!mappedTypes) { + mappedTypes = [mapped]; + } else { + mappedTypes.push(mapped); + } + } + } + return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type; + } + function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + return type.flags & 1048576 /* Union */ && aliasSymbol ? getUnionType(map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : mapType(type, mapper); + } + function extractTypesOfKind(type, kind) { + return filterType(type, (t) => (t.flags & kind) !== 0); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (maybeTypeOfKind(typeWithPrimitives, 4 /* String */ | 134217728 /* TemplateLiteral */ | 8 /* Number */ | 64 /* BigInt */) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 256 /* NumberLiteral */ | 2048 /* BigIntLiteral */)) { + return mapType(typeWithPrimitives, (t) => t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) : isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, 4 /* String */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? extractTypesOfKind(typeWithLiterals, 128 /* StringLiteral */) : t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type.flags & 131072 /* Never */ ? silentNeverType : type } : type; + } + function createEvolvingArrayType(elementType) { + const result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + function addEvolvingArrayElementType(evolvingArrayType, node) { + const elementType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node))); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 131072 /* Never */ ? autoArrayType : createArrayType( + elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType + ); + } + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + let hasEvolvingArrayType = false; + for (const t of types) { + if (!(t.flags & 131072 /* Never */)) { + if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + function isEvolvingArrayOperationTarget(node) { + const root = getReferenceRoot(node); + const parent = root.parent; + const isLengthPushOrUnshift = isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || parent.parent.kind === 213 /* CallExpression */ && isIdentifier(parent.name) && isPushOrUnshiftIdentifier(parent.name)); + const isElementAssignment = parent.kind === 212 /* ElementAccessExpression */ && parent.expression === root && parent.parent.kind === 226 /* BinaryExpression */ && parent.parent.operatorToken.kind === 64 /* EqualsToken */ && parent.parent.left === parent && !isAssignmentTarget(parent.parent) && isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */); + return isLengthPushOrUnshift || isElementAssignment; + } + function isDeclarationWithExplicitTypeAnnotation(node) { + return (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isParameter(node)) && !!(getEffectiveTypeAnnotationNode(node) || isInJSFile(node) && hasInitializer(node) && node.initializer && isFunctionExpressionOrArrowFunction(node.initializer) && getEffectiveReturnTypeNode(node.initializer)); + } + function getExplicitTypeOfSymbol(symbol, diagnostic) { + symbol = resolveSymbol(symbol); + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) { + return getTypeOfSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + if (getCheckFlags(symbol) & 262144 /* Mapped */) { + const origin = symbol.links.syntheticOrigin; + if (origin && getExplicitTypeOfSymbol(origin)) { + return getTypeOfSymbol(symbol); + } + } + const declaration = symbol.valueDeclaration; + if (declaration) { + if (isDeclarationWithExplicitTypeAnnotation(declaration)) { + return getTypeOfSymbol(symbol); + } + if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 250 /* ForOfStatement */) { + const statement = declaration.parent.parent; + const expressionType = getTypeOfDottedName( + statement.expression, + /*diagnostic*/ + void 0 + ); + if (expressionType) { + const use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; + return checkIteratedTypeOrElementType( + use, + expressionType, + undefinedType, + /*errorNode*/ + void 0 + ); + } + } + if (diagnostic) { + addRelatedInfo(diagnostic, createDiagnosticForNode(declaration, Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol))); + } + } + } + } + function getTypeOfDottedName(node, diagnostic) { + if (!(node.flags & 67108864 /* InWithStatement */)) { + switch (node.kind) { + case 80 /* Identifier */: + const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); + return getExplicitTypeOfSymbol(symbol, diagnostic); + case 110 /* ThisKeyword */: + return getExplicitThisType(node); + case 108 /* SuperKeyword */: + return checkSuperExpression(node); + case 211 /* PropertyAccessExpression */: { + const type = getTypeOfDottedName(node.expression, diagnostic); + if (type) { + const name = node.name; + let prop; + if (isPrivateIdentifier(name)) { + if (!type.symbol) { + return void 0; + } + prop = getPropertyOfType(type, getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); + } else { + prop = getPropertyOfType(type, name.escapedText); + } + return prop && getExplicitTypeOfSymbol(prop, diagnostic); + } + return void 0; + } + case 217 /* ParenthesizedExpression */: + return getTypeOfDottedName(node.expression, diagnostic); + } + } + } + function getEffectsSignature(node) { + const links = getNodeLinks(node); + let signature = links.effectsSignature; + if (signature === void 0) { + let funcType; + if (isBinaryExpression(node)) { + const rightType = checkNonNullExpression(node.right); + funcType = getSymbolHasInstanceMethodOfObjectType(rightType); + } else if (node.parent.kind === 244 /* ExpressionStatement */) { + funcType = getTypeOfDottedName( + node.expression, + /*diagnostic*/ + void 0 + ); + } else if (node.expression.kind !== 108 /* SuperKeyword */) { + if (isOptionalChain(node)) { + funcType = checkNonNullType( + getOptionalExpressionType(checkExpression(node.expression), node.expression), + node.expression + ); + } else { + funcType = checkNonNullExpression(node.expression); + } + } + const signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); + const candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : void 0; + signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature; + } + return signature === unknownSignature ? void 0 : signature; + } + function hasTypePredicateOrNeverReturnType(signature) { + return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); + } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + const invokedExpression = skipParentheses(callExpression.expression); + return isAccessExpression(invokedExpression) ? skipParentheses(invokedExpression.expression) : void 0; + } + function reportFlowControlError(node) { + const block = findAncestor(node, isFunctionOrModuleBlock); + const sourceFile = getSourceFileOfNode(node); + const span = getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } + function isReachableFlowNode(flow) { + const result = isReachableFlowNodeWorker( + flow, + /*noCacheCheck*/ + false + ); + lastFlowNode = flow; + lastFlowNodeReachable = result; + return result; + } + function isFalseExpression(expr) { + const node = skipParentheses( + expr, + /*excludeJSDocTypeAssertions*/ + true + ); + return node.kind === 97 /* FalseKeyword */ || node.kind === 226 /* BinaryExpression */ && (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 57 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } + function isReachableFlowNodeWorker(flow, noCacheCheck) { + while (true) { + if (flow === lastFlowNode) { + return lastFlowNodeReachable; + } + const flags = flow.flags; + if (flags & 4096 /* Shared */) { + if (!noCacheCheck) { + const id = getFlowNodeId(flow); + const reachable = flowNodeReachable[id]; + return reachable !== void 0 ? reachable : flowNodeReachable[id] = isReachableFlowNodeWorker( + flow, + /*noCacheCheck*/ + true + ); + } + noCacheCheck = false; + } + if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) { + flow = flow.antecedent; + } else if (flags & 512 /* Call */) { + const signature = getEffectsSignature(flow.node); + if (signature) { + const predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */ && !predicate.type) { + const predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } + } + flow = flow.antecedent; + } else if (flags & 4 /* BranchLabel */) { + return some(flow.antecedent, (f) => isReachableFlowNodeWorker( + f, + /*noCacheCheck*/ + false + )); + } else if (flags & 8 /* LoopLabel */) { + const antecedents = flow.antecedent; + if (antecedents === void 0 || antecedents.length === 0) { + return false; + } + flow = antecedents[0]; + } else if (flags & 128 /* SwitchClause */) { + const data = flow.node; + if (data.clauseStart === data.clauseEnd && isExhaustiveSwitchStatement(data.switchStatement)) { + return false; + } + flow = flow.antecedent; + } else if (flags & 1024 /* ReduceLabel */) { + lastFlowNode = void 0; + const target = flow.node.target; + const saveAntecedents = target.antecedent; + target.antecedent = flow.node.antecedents; + const result = isReachableFlowNodeWorker( + flow.antecedent, + /*noCacheCheck*/ + false + ); + target.antecedent = saveAntecedents; + return result; + } else { + return !(flags & 1 /* Unreachable */); + } + } + } + function isPostSuperFlowNode(flow, noCacheCheck) { + while (true) { + const flags = flow.flags; + if (flags & 4096 /* Shared */) { + if (!noCacheCheck) { + const id = getFlowNodeId(flow); + const postSuper = flowNodePostSuper[id]; + return postSuper !== void 0 ? postSuper : flowNodePostSuper[id] = isPostSuperFlowNode( + flow, + /*noCacheCheck*/ + true + ); + } + noCacheCheck = false; + } + if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 128 /* SwitchClause */)) { + flow = flow.antecedent; + } else if (flags & 512 /* Call */) { + if (flow.node.expression.kind === 108 /* SuperKeyword */) { + return true; + } + flow = flow.antecedent; + } else if (flags & 4 /* BranchLabel */) { + return every(flow.antecedent, (f) => isPostSuperFlowNode( + f, + /*noCacheCheck*/ + false + )); + } else if (flags & 8 /* LoopLabel */) { + flow = flow.antecedent[0]; + } else if (flags & 1024 /* ReduceLabel */) { + const target = flow.node.target; + const saveAntecedents = target.antecedent; + target.antecedent = flow.node.antecedents; + const result = isPostSuperFlowNode( + flow.antecedent, + /*noCacheCheck*/ + false + ); + target.antecedent = saveAntecedents; + return result; + } else { + return !!(flags & 1 /* Unreachable */); + } + } + } + function isConstantReference(node) { + switch (node.kind) { + case 110 /* ThisKeyword */: + return true; + case 80 /* Identifier */: + if (!isThisInTypeQuery(node)) { + const symbol = getResolvedSymbol(node); + return isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol) || !!symbol.valueDeclaration && isFunctionExpression(symbol.valueDeclaration); + } + break; + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + return isConstantReference(node.expression) && isReadonlySymbol(getNodeLinks(node).resolvedSymbol || unknownSymbol); + case 206 /* ObjectBindingPattern */: + case 207 /* ArrayBindingPattern */: + const rootDeclaration = getRootDeclaration(node.parent); + return isParameter(rootDeclaration) || isCatchClauseVariableDeclaration(rootDeclaration) ? !isSomeSymbolAssigned(rootDeclaration) : isVariableDeclaration(rootDeclaration) && isVarConstLike2(rootDeclaration); + } + return false; + } + function getFlowTypeOfReference(reference, declaredType, initialType = declaredType, flowContainer, flowNode = ((_a) => (_a = tryCast(reference, canHaveFlowNode)) == null ? void 0 : _a.flowNode)()) { + let key; + let isKeySet = false; + let flowDepth = 0; + if (flowAnalysisDisabled) { + return errorType; + } + if (!flowNode) { + return declaredType; + } + flowInvocationCount++; + const sharedFlowStart = sharedFlowCount; + const evolvedType = getTypeFromFlowType(getTypeAtFlowNode(flowNode)); + sharedFlowCount = sharedFlowStart; + const resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 235 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + return declaredType; + } + return resultType; + function getOrSetCacheKey() { + if (isKeySet) { + return key; + } + isKeySet = true; + return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer); + } + function getTypeAtFlowNode(flow) { + var _a2; + if (flowDepth === 2e3) { + (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return errorType; + } + flowDepth++; + let sharedFlow; + while (true) { + const flags = flow.flags; + if (flags & 4096 /* Shared */) { + for (let i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; + } + } + sharedFlow = flow; + } + let type; + if (flags & 16 /* Assignment */) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } else if (flags & 512 /* Call */) { + type = getTypeAtFlowCall(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } else if (flags & 96 /* Condition */) { + type = getTypeAtFlowCondition(flow); + } else if (flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } else if (flags & 12 /* Label */) { + if (flow.antecedent.length === 1) { + flow = flow.antecedent[0]; + continue; + } + type = flags & 4 /* BranchLabel */ ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); + } else if (flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } else if (flags & 1024 /* ReduceLabel */) { + const target = flow.node.target; + const saveAntecedents = target.antecedent; + target.antecedent = flow.node.antecedents; + type = getTypeAtFlowNode(flow.antecedent); + target.antecedent = saveAntecedents; + } else if (flags & 2 /* Start */) { + const container = flow.node; + if (container && container !== flowContainer && reference.kind !== 211 /* PropertyAccessExpression */ && reference.kind !== 212 /* ElementAccessExpression */ && !(reference.kind === 110 /* ThisKeyword */ && container.kind !== 219 /* ArrowFunction */)) { + flow = container.flowNode; + continue; + } + type = initialType; + } else { + type = convertAutoToAny(declaredType); + } + if (sharedFlow) { + sharedFlowNodes[sharedFlowCount] = sharedFlow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; + } + flowDepth--; + return type; + } + } + function getInitialOrAssignedType(flow) { + const node = flow.node; + return getNarrowableTypeForReference( + node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), + reference + ); + } + function getTypeAtFlowAssignment(flow) { + const node = flow.node; + if (isMatchingReference(reference, node)) { + if (!isReachableFlowNode(flow)) { + return unreachableNeverType; + } + if (getAssignmentTargetKind(node) === 2 /* Compound */) { + const flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + const assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + const t = isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(declaredType) : declaredType; + if (t.flags & 1048576 /* Union */) { + return getAssignmentReducedType(t, getInitialOrAssignedType(flow)); + } + return t; + } + if (containsMatchingReference(reference, node)) { + if (!isReachableFlowNode(flow)) { + return unreachableNeverType; + } + if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConstLike2(node))) { + const init = getDeclaredExpandoInitializer(node); + if (init && (init.kind === 218 /* FunctionExpression */ || init.kind === 219 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } + return declaredType; + } + if (isVariableDeclaration(node) && node.parent.parent.kind === 249 /* ForInStatement */ && (isMatchingReference(reference, node.parent.parent.expression) || optionalChainContainsReference(node.parent.parent.expression, reference))) { + return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); + } + return void 0; + } + function narrowTypeByAssertion(type, expr) { + const node = skipParentheses( + expr, + /*excludeJSDocTypeAssertions*/ + true + ); + if (node.kind === 97 /* FalseKeyword */) { + return unreachableNeverType; + } + if (node.kind === 226 /* BinaryExpression */) { + if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { + return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); + } + if (node.operatorToken.kind === 57 /* BarBarToken */) { + return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]); + } + } + return narrowType( + type, + node, + /*assumeTrue*/ + true + ); + } + function getTypeAtFlowCall(flow) { + const signature = getEffectsSignature(flow.node); + if (signature) { + const predicate = getTypePredicateOfSignature(signature); + if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) { + const flowType = getTypeAtFlowNode(flow.antecedent); + const type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType)); + const narrowedType = predicate.type ? narrowTypeByTypePredicate( + type, + predicate, + flow.node, + /*assumeTrue*/ + true + ) : predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; + return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return unreachableNeverType; + } + } + return void 0; + } + function getTypeAtFlowArrayMutation(flow) { + if (declaredType === autoType || declaredType === autoArrayType) { + const node = flow.node; + const expr = node.kind === 213 /* CallExpression */ ? node.expression.expression : node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + const flowType = getTypeAtFlowNode(flow.antecedent); + const type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256 /* EvolvingArray */) { + let evolvedType2 = type; + if (node.kind === 213 /* CallExpression */) { + for (const arg of node.arguments) { + evolvedType2 = addEvolvingArrayElementType(evolvedType2, arg); + } + } else { + const indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) { + evolvedType2 = addEvolvingArrayElementType(evolvedType2, node.right); + } + } + return evolvedType2 === type ? flowType : createFlowType(evolvedType2, isIncomplete(flowType)); + } + return flowType; + } + } + return void 0; + } + function getTypeAtFlowCondition(flow) { + const flowType = getTypeAtFlowNode(flow.antecedent); + const type = getTypeFromFlowType(flowType); + if (type.flags & 131072 /* Never */) { + return flowType; + } + const assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + const nonEvolvingType = finalizeEvolvingArrayType(type); + const narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + return createFlowType(narrowedType, isIncomplete(flowType)); + } + function getTypeAtSwitchClause(flow) { + const expr = skipParentheses(flow.node.switchStatement.expression); + const flowType = getTypeAtFlowNode(flow.antecedent); + let type = getTypeFromFlowType(flowType); + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.node); + } else if (expr.kind === 221 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowTypeBySwitchOnTypeOf(type, flow.node); + } else if (expr.kind === 112 /* TrueKeyword */) { + type = narrowTypeBySwitchOnTrue(type, flow.node); + } else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.node, (t) => !(t.flags & (32768 /* Undefined */ | 131072 /* Never */))); + } else if (expr.kind === 221 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.node, (t) => !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined")); + } + } + const access = getDiscriminantPropertyAccess(expr, type); + if (access) { + type = narrowTypeBySwitchOnDiscriminantProperty(type, access, flow.node); + } + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + const antecedentTypes = []; + let subtypeReduction = false; + let seenIncomplete = false; + let bypassFlow; + for (const antecedent of flow.antecedent) { + if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.node.clauseStart === antecedent.node.clauseEnd) { + bypassFlow = antecedent; + continue; + } + const flowType = getTypeAtFlowNode(antecedent); + const type = getTypeFromFlowType(flowType); + if (type === declaredType && declaredType === initialType) { + return type; + } + pushIfUnique(antecedentTypes, type); + if (!isTypeSubsetOf(type, initialType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + if (bypassFlow) { + const flowType = getTypeAtFlowNode(bypassFlow); + const type = getTypeFromFlowType(flowType); + if (!(type.flags & 131072 /* Never */) && !contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.node.switchStatement)) { + if (type === declaredType && declaredType === initialType) { + return type; + } + antecedentTypes.push(type); + if (!isTypeSubsetOf(type, initialType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + const id = getFlowNodeId(flow); + const cache = flowLoopCaches[id] || (flowLoopCaches[id] = /* @__PURE__ */ new Map()); + const key2 = getOrSetCacheKey(); + if (!key2) { + return declaredType; + } + const cached = cache.get(key2); + if (cached) { + return cached; + } + for (let i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key2 && flowLoopTypes[i].length) { + return createFlowType( + getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), + /*incomplete*/ + true + ); + } + } + const antecedentTypes = []; + let subtypeReduction = false; + let firstAntecedentType; + for (const antecedent of flow.antecedent) { + let flowType; + if (!firstAntecedentType) { + flowType = firstAntecedentType = getTypeAtFlowNode(antecedent); + } else { + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key2; + flowLoopTypes[flowLoopCount] = antecedentTypes; + flowLoopCount++; + const saveFlowTypeCache = flowTypeCache; + flowTypeCache = void 0; + flowType = getTypeAtFlowNode(antecedent); + flowTypeCache = saveFlowTypeCache; + flowLoopCount--; + const cached2 = cache.get(key2); + if (cached2) { + return cached2; + } + } + const type = getTypeFromFlowType(flowType); + pushIfUnique(antecedentTypes, type); + if (!isTypeSubsetOf(type, initialType)) { + subtypeReduction = true; + } + if (type === declaredType) { + break; + } + } + const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); + if (isIncomplete(firstAntecedentType)) { + return createFlowType( + result, + /*incomplete*/ + true + ); + } + cache.set(key2, result); + return result; + } + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + if (isEvolvingArrayTypeList(types)) { + return getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))); + } + const result = recombineUnknownType(getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction)); + if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* Union */ && arrayIsEqualTo(result.types, declaredType.types)) { + return declaredType; + } + return result; + } + function getCandidateDiscriminantPropertyAccess(expr) { + if (isBindingPattern(reference) || isFunctionExpressionOrArrowFunction(reference) || isObjectLiteralMethod(reference)) { + if (isIdentifier(expr)) { + const symbol = getResolvedSymbol(expr); + const declaration = symbol.valueDeclaration; + if (declaration && (isBindingElement(declaration) || isParameter(declaration)) && reference === declaration.parent && !declaration.initializer && !declaration.dotDotDotToken) { + return declaration; + } + } + } else if (isAccessExpression(expr)) { + if (isMatchingReference(reference, expr.expression)) { + return expr; + } + } else if (isIdentifier(expr)) { + const symbol = getResolvedSymbol(expr); + if (isConstantVariable(symbol)) { + const declaration = symbol.valueDeclaration; + if (isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isAccessExpression(declaration.initializer) && isMatchingReference(reference, declaration.initializer.expression)) { + return declaration.initializer; + } + if (isBindingElement(declaration) && !declaration.initializer) { + const parent = declaration.parent.parent; + if (isVariableDeclaration(parent) && !parent.type && parent.initializer && (isIdentifier(parent.initializer) || isAccessExpression(parent.initializer)) && isMatchingReference(reference, parent.initializer)) { + return declaration; + } + } + } + } + return void 0; + } + function getDiscriminantPropertyAccess(expr, computedType) { + if (declaredType.flags & 1048576 /* Union */ || computedType.flags & 1048576 /* Union */) { + const access = getCandidateDiscriminantPropertyAccess(expr); + if (access) { + const name = getAccessedPropertyName(access); + if (name) { + const type = declaredType.flags & 1048576 /* Union */ && isTypeSubsetOf(computedType, declaredType) ? declaredType : computedType; + if (isDiscriminantProperty(type, name)) { + return access; + } + } + } + } + return void 0; + } + function narrowTypeByDiscriminant(type, access, narrowType2) { + const propName = getAccessedPropertyName(access); + if (propName === void 0) { + return type; + } + const optionalChain = isOptionalChain(access); + const removeNullable = strictNullChecks && (optionalChain || isNonNullAccess(access)) && maybeTypeOfKind(type, 98304 /* Nullable */); + let propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); + if (!propType) { + return type; + } + propType = removeNullable && optionalChain ? getOptionalType(propType) : propType; + const narrowedPropType = narrowType2(propType); + return filterType(type, (t) => { + const discriminantType = getTypeOfPropertyOrIndexSignatureOfType(t, propName) || unknownType; + return !(discriminantType.flags & 131072 /* Never */) && !(narrowedPropType.flags & 131072 /* Never */) && areTypesComparable(narrowedPropType, discriminantType); + }); + } + function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) { + if ((operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */) && type.flags & 1048576 /* Union */) { + const keyPropertyName = getKeyPropertyName(type); + if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { + const candidate = getConstituentTypeForKeyType(type, getTypeOfExpression(value)); + if (candidate) { + return operator === (assumeTrue ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */) ? candidate : isUnitType(getTypeOfPropertyOfType(candidate, keyPropertyName) || unknownType) ? removeType(type, candidate) : type; + } + } + } + return narrowTypeByDiscriminant(type, access, (t) => narrowTypeByEquality(t, operator, value, assumeTrue)); + } + function narrowTypeBySwitchOnDiscriminantProperty(type, access, data) { + if (data.clauseStart < data.clauseEnd && type.flags & 1048576 /* Union */ && getKeyPropertyName(type) === getAccessedPropertyName(access)) { + const clauseTypes = getSwitchClauseTypes(data.switchStatement).slice(data.clauseStart, data.clauseEnd); + const candidate = getUnionType(map(clauseTypes, (t) => getConstituentTypeForKeyType(type, t) || unknownType)); + if (candidate !== unknownType) { + return candidate; + } + } + return narrowTypeByDiscriminant(type, access, (t) => narrowTypeBySwitchOnDiscriminant(t, data)); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); + } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } + const access = getDiscriminantPropertyAccess(expr, type); + if (access) { + return narrowTypeByDiscriminant(type, access, (t) => getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */)); + } + return type; + } + function isTypePresencePossible(type, propName, assumeTrue) { + const prop = getPropertyOfType(type, propName); + return prop ? !!(prop.flags & 16777216 /* Optional */ || getCheckFlags(prop) & 48 /* Partial */) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; + } + function narrowTypeByInKeyword(type, nameType, assumeTrue) { + const name = getPropertyNameFromType(nameType); + const isKnownProperty2 = someType(type, (t) => isTypePresencePossible( + t, + name, + /*assumeTrue*/ + true + )); + if (isKnownProperty2) { + return filterType(type, (t) => isTypePresencePossible(t, name, assumeTrue)); + } + if (assumeTrue) { + const recordSymbol = getGlobalRecordSymbol(); + if (recordSymbol) { + return getIntersectionType([type, getTypeAliasInstantiation(recordSymbol, [nameType, unknownType])]); + } + } + return type; + } + function narrowTypeByBooleanComparison(type, expr, bool, operator, assumeTrue) { + assumeTrue = assumeTrue !== (bool.kind === 112 /* TrueKeyword */) !== (operator !== 38 /* ExclamationEqualsEqualsToken */ && operator !== 36 /* ExclamationEqualsToken */); + return narrowType(type, expr, assumeTrue); + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 64 /* EqualsToken */: + case 76 /* BarBarEqualsToken */: + case 77 /* AmpersandAmpersandEqualsToken */: + case 78 /* QuestionQuestionEqualsToken */: + return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue); + case 35 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsToken */: + case 37 /* EqualsEqualsEqualsToken */: + case 38 /* ExclamationEqualsEqualsToken */: + const operator = expr.operatorToken.kind; + const left = getReferenceCandidate(expr.left); + const right = getReferenceCandidate(expr.right); + if (left.kind === 221 /* TypeOfExpression */ && isStringLiteralLike(right)) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 221 /* TypeOfExpression */ && isStringLiteralLike(left)) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (isMatchingReference(reference, left)) { + return narrowTypeByEquality(type, operator, right, assumeTrue); + } + if (isMatchingReference(reference, right)) { + return narrowTypeByEquality(type, operator, left, assumeTrue); + } + if (strictNullChecks) { + if (optionalChainContainsReference(left, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue); + } else if (optionalChainContainsReference(right, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue); + } + } + const leftAccess = getDiscriminantPropertyAccess(left, type); + if (leftAccess) { + return narrowTypeByDiscriminantProperty(type, leftAccess, operator, right, assumeTrue); + } + const rightAccess = getDiscriminantPropertyAccess(right, type); + if (rightAccess) { + return narrowTypeByDiscriminantProperty(type, rightAccess, operator, left, assumeTrue); + } + if (isMatchingConstructorReference(left)) { + return narrowTypeByConstructor(type, operator, right, assumeTrue); + } + if (isMatchingConstructorReference(right)) { + return narrowTypeByConstructor(type, operator, left, assumeTrue); + } + if (isBooleanLiteral(right) && !isAccessExpression(left)) { + return narrowTypeByBooleanComparison(type, left, right, operator, assumeTrue); + } + if (isBooleanLiteral(left) && !isAccessExpression(right)) { + return narrowTypeByBooleanComparison(type, right, left, operator, assumeTrue); + } + break; + case 104 /* InstanceOfKeyword */: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 103 /* InKeyword */: + if (isPrivateIdentifier(expr.left)) { + return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue); + } + const target = getReferenceCandidate(expr.right); + if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) { + return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */); + } + } + if (isMatchingReference(reference, target)) { + const leftType = getTypeOfExpression(expr.left); + if (isTypeUsableAsPropertyName(leftType)) { + return narrowTypeByInKeyword(type, leftType, assumeTrue); + } + } + break; + case 28 /* CommaToken */: + return narrowType(type, expr.right, assumeTrue); + // Ordinarily we won't see && and || expressions in control flow analysis because the Binder breaks those + // expressions down to individual conditional control flows. However, we may encounter them when analyzing + // aliased conditional expressions. + case 56 /* AmpersandAmpersandToken */: + return assumeTrue ? narrowType( + narrowType( + type, + expr.left, + /*assumeTrue*/ + true + ), + expr.right, + /*assumeTrue*/ + true + ) : getUnionType([narrowType( + type, + expr.left, + /*assumeTrue*/ + false + ), narrowType( + type, + expr.right, + /*assumeTrue*/ + false + )]); + case 57 /* BarBarToken */: + return assumeTrue ? getUnionType([narrowType( + type, + expr.left, + /*assumeTrue*/ + true + ), narrowType( + type, + expr.right, + /*assumeTrue*/ + true + )]) : narrowType( + narrowType( + type, + expr.left, + /*assumeTrue*/ + false + ), + expr.right, + /*assumeTrue*/ + false + ); + } + return type; + } + function narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue) { + const target = getReferenceCandidate(expr.right); + if (!isMatchingReference(reference, target)) { + return type; + } + Debug.assertNode(expr.left, isPrivateIdentifier); + const symbol = getSymbolForPrivateIdentifierExpression(expr.left); + if (symbol === void 0) { + return type; + } + const classSymbol = symbol.parent; + const targetType = hasStaticModifier(Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); + return getNarrowedType( + type, + targetType, + assumeTrue, + /*checkDerived*/ + true + ); + } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + const equalsOperator = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */; + const nullableFlags = operator === 35 /* EqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */; + const valueType = getTypeOfExpression(value); + const removeNullable = equalsOperator !== assumeTrue && everyType(valueType, (t) => !!(t.flags & nullableFlags)) || equalsOperator === assumeTrue && everyType(valueType, (t) => !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags))); + return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + if (operator === 36 /* ExclamationEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + const valueType = getTypeOfExpression(value); + const doubleEquals = operator === 35 /* EqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */; + if (valueType.flags & 98304 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + const facts = doubleEquals ? assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : valueType.flags & 65536 /* Null */ ? assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */; + return getAdjustedTypeWithFacts(type, facts); + } + if (assumeTrue) { + if (!doubleEquals && (type.flags & 2 /* Unknown */ || someType(type, isEmptyAnonymousObjectType))) { + if (valueType.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */) || isEmptyAnonymousObjectType(valueType)) { + return valueType; + } + if (valueType.flags & 524288 /* Object */) { + return nonPrimitiveType; + } + } + const filteredType = filterType(type, (t) => areTypesComparable(t, valueType) || doubleEquals && isCoercibleUnderDoubleEquals(t, valueType)); + return replacePrimitivesWithLiterals(filteredType, valueType); + } + if (isUnitType(valueType)) { + return filterType(type, (t) => !(isUnitLikeType(t) && areTypesComparable(t, valueType))); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + if (operator === 36 /* ExclamationEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + const target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } + const propertyAccess = getDiscriminantPropertyAccess(target, type); + if (propertyAccess) { + return narrowTypeByDiscriminant(type, propertyAccess, (t) => narrowTypeByLiteralExpression(t, literal, assumeTrue)); + } + return type; + } + return narrowTypeByLiteralExpression(type, literal, assumeTrue); + } + function narrowTypeByLiteralExpression(type, literal, assumeTrue) { + return assumeTrue ? narrowTypeByTypeName(type, literal.text) : getAdjustedTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */); + } + function narrowTypeBySwitchOptionalChainContainment(type, { switchStatement, clauseStart, clauseEnd }, clauseCheck) { + const everyClauseChecks = clauseStart !== clauseEnd && every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } + function narrowTypeBySwitchOnDiscriminant(type, { switchStatement, clauseStart, clauseEnd }) { + const switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + const clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + const hasDefaultClause = clauseStart === clauseEnd || contains(clauseTypes, neverType); + if (type.flags & 2 /* Unknown */ && !hasDefaultClause) { + let groundClauseTypes; + for (let i = 0; i < clauseTypes.length; i += 1) { + const t = clauseTypes[i]; + if (t.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */)) { + if (groundClauseTypes !== void 0) { + groundClauseTypes.push(t); + } + } else if (t.flags & 524288 /* Object */) { + if (groundClauseTypes === void 0) { + groundClauseTypes = clauseTypes.slice(0, i); + } + groundClauseTypes.push(nonPrimitiveType); + } else { + return type; + } + } + return getUnionType(groundClauseTypes === void 0 ? clauseTypes : groundClauseTypes); + } + const discriminantType = getUnionType(clauseTypes); + const caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, (t) => areTypesComparable(discriminantType, t)), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + const defaultType = filterType(type, (t) => !(isUnitLikeType(t) && contains(switchTypes, t.flags & 32768 /* Undefined */ ? undefinedType : getRegularTypeOfLiteralType(extractUnitType(t))))); + return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function narrowTypeByTypeName(type, typeName) { + switch (typeName) { + case "string": + return narrowTypeByTypeFacts(type, stringType, 1 /* TypeofEQString */); + case "number": + return narrowTypeByTypeFacts(type, numberType, 2 /* TypeofEQNumber */); + case "bigint": + return narrowTypeByTypeFacts(type, bigintType, 4 /* TypeofEQBigInt */); + case "boolean": + return narrowTypeByTypeFacts(type, booleanType, 8 /* TypeofEQBoolean */); + case "symbol": + return narrowTypeByTypeFacts(type, esSymbolType, 16 /* TypeofEQSymbol */); + case "object": + return type.flags & 1 /* Any */ ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* EQNull */)]); + case "function": + return type.flags & 1 /* Any */ ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64 /* TypeofEQFunction */); + case "undefined": + return narrowTypeByTypeFacts(type, undefinedType, 65536 /* EQUndefined */); + } + return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeofEQHostObject */); + } + function narrowTypeByTypeFacts(type, impliedType, facts) { + return mapType(type, (t) => ( + // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate + // the constituent based on its type facts. We use the strict subtype relation because it treats `object` + // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, + // but are classified as "function" according to `typeof`. + isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? hasTypeFacts(t, facts) ? t : neverType : ( + // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied + // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. + isTypeSubtypeOf(impliedType, t) ? impliedType : ( + // Neither the constituent nor the implied type is a subtype of the other, however their domains may still + // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate + // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. + hasTypeFacts(t, facts) ? getIntersectionType([t, impliedType]) : neverType + ) + ) + )); + } + function narrowTypeBySwitchOnTypeOf(type, { switchStatement, clauseStart, clauseEnd }) { + const witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!witnesses) { + return type; + } + const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause) => clause.kind === 297 /* DefaultClause */); + const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd; + if (hasDefaultClause) { + const notEqualFacts = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); + return filterType(type, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts); + } + const clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); + return getUnionType(map(clauseWitnesses, (text) => text ? narrowTypeByTypeName(type, text) : neverType)); + } + function narrowTypeBySwitchOnTrue(type, { switchStatement, clauseStart, clauseEnd }) { + const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause) => clause.kind === 297 /* DefaultClause */); + const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd; + for (let i = 0; i < clauseStart; i++) { + const clause = switchStatement.caseBlock.clauses[i]; + if (clause.kind === 296 /* CaseClause */) { + type = narrowType( + type, + clause.expression, + /*assumeTrue*/ + false + ); + } + } + if (hasDefaultClause) { + for (let i = clauseEnd; i < switchStatement.caseBlock.clauses.length; i++) { + const clause = switchStatement.caseBlock.clauses[i]; + if (clause.kind === 296 /* CaseClause */) { + type = narrowType( + type, + clause.expression, + /*assumeTrue*/ + false + ); + } + } + return type; + } + const clauses = switchStatement.caseBlock.clauses.slice(clauseStart, clauseEnd); + return getUnionType(map(clauses, (clause) => clause.kind === 296 /* CaseClause */ ? narrowType( + type, + clause.expression, + /*assumeTrue*/ + true + ) : neverType)); + } + function isMatchingConstructorReference(expr) { + return (isPropertyAccessExpression(expr) && idText(expr.name) === "constructor" || isElementAccessExpression(expr) && isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && isMatchingReference(reference, expr.expression); + } + function narrowTypeByConstructor(type, operator, identifier, assumeTrue) { + if (assumeTrue ? operator !== 35 /* EqualsEqualsToken */ && operator !== 37 /* EqualsEqualsEqualsToken */ : operator !== 36 /* ExclamationEqualsToken */ && operator !== 38 /* ExclamationEqualsEqualsToken */) { + return type; + } + const identifierType = getTypeOfExpression(identifier); + if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) { + return type; + } + const prototypeProperty = getPropertyOfType(identifierType, "prototype"); + if (!prototypeProperty) { + return type; + } + const prototypeType = getTypeOfSymbol(prototypeProperty); + const candidate = !isTypeAny(prototypeType) ? prototypeType : void 0; + if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) { + return type; + } + if (isTypeAny(type)) { + return candidate; + } + return filterType(type, (t) => isConstructedBy(t, candidate)); + function isConstructedBy(source, target) { + if (source.flags & 524288 /* Object */ && getObjectFlags(source) & 1 /* Class */ || target.flags & 524288 /* Object */ && getObjectFlags(target) & 1 /* Class */) { + return source.symbol === target.symbol; + } + return isTypeSubtypeOf(source, target); + } + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + const left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } + return type; + } + const right = expr.right; + const rightType = getTypeOfExpression(right); + if (!isTypeDerivedFrom(rightType, globalObjectType)) { + return type; + } + const signature = getEffectsSignature(expr); + const predicate = signature && getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 1 /* Identifier */ && predicate.parameterIndex === 0) { + return getNarrowedType( + type, + predicate.type, + assumeTrue, + /*checkDerived*/ + true + ); + } + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { + return type; + } + const instanceType = mapType(rightType, getInstanceType); + if (isTypeAny(type) && (instanceType === globalObjectType || instanceType === globalFunctionType) || !assumeTrue && !(instanceType.flags & 524288 /* Object */ && !isEmptyAnonymousObjectType(instanceType))) { + return type; + } + return getNarrowedType( + type, + instanceType, + assumeTrue, + /*checkDerived*/ + true + ); + } + function getInstanceType(constructorType) { + const prototypePropertyType = getTypeOfPropertyOfType(constructorType, "prototype"); + if (prototypePropertyType && !isTypeAny(prototypePropertyType)) { + return prototypePropertyType; + } + const constructSignatures = getSignaturesOfType(constructorType, 1 /* Construct */); + if (constructSignatures.length) { + return getUnionType(map(constructSignatures, (signature) => getReturnTypeOfSignature(getErasedSignature(signature)))); + } + return emptyObjectType; + } + function getNarrowedType(type, candidate, assumeTrue, checkDerived) { + const key2 = type.flags & 1048576 /* Union */ ? `N${getTypeId(type)},${getTypeId(candidate)},${(assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)}` : void 0; + return getCachedType(key2) ?? setCachedType(key2, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); + } + function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { + if (!assumeTrue) { + if (type === candidate) { + return neverType; + } + if (checkDerived) { + return filterType(type, (t) => !isTypeDerivedFrom(t, candidate)); + } + type = type.flags & 2 /* Unknown */ ? unknownUnionType : type; + const trueType2 = getNarrowedType( + type, + candidate, + /*assumeTrue*/ + true, + /*checkDerived*/ + false + ); + return recombineUnknownType(filterType(type, (t) => !isTypeSubsetOf(t, trueType2))); + } + if (type.flags & 3 /* AnyOrUnknown */) { + return candidate; + } + if (type === candidate) { + return candidate; + } + const isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf; + const keyPropertyName = type.flags & 1048576 /* Union */ ? getKeyPropertyName(type) : void 0; + const narrowedType = mapType(candidate, (c) => { + const discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); + const matching = discriminant && getConstituentTypeForKeyType(type, discriminant); + const directlyRelated = mapType( + matching || type, + checkDerived ? (t) => isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType : (t) => isTypeStrictSubtypeOf(t, c) ? t : isTypeStrictSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : isTypeSubtypeOf(c, t) ? c : neverType + ); + return directlyRelated.flags & 131072 /* Never */ ? mapType(type, (t) => maybeTypeOfKind(t, 465829888 /* Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType) : directlyRelated; + }); + return !(narrowedType.flags & 131072 /* Never */) ? narrowedType : isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : isTypeAssignableTo(candidate, type) ? candidate : getIntersectionType([type, candidate]); + } + function narrowTypeByCallExpression(type, callExpression, assumeTrue) { + if (hasMatchingArgument(callExpression, reference)) { + const signature = assumeTrue || !isCallChain(callExpression) ? getEffectsSignature(callExpression) : void 0; + const predicate = signature && getTypePredicateOfSignature(signature); + if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) { + return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue); + } + } + if (containsMissingType(type) && isAccessExpression(reference) && isPropertyAccessExpression(callExpression.expression)) { + const callAccess = callExpression.expression; + if (isMatchingReference(reference.expression, getReferenceCandidate(callAccess.expression)) && isIdentifier(callAccess.name) && callAccess.name.escapedText === "hasOwnProperty" && callExpression.arguments.length === 1) { + const argument = callExpression.arguments[0]; + if (isStringLiteralLike(argument) && getAccessedPropertyName(reference) === escapeLeadingUnderscores(argument.text)) { + return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */); + } + } + } + return type; + } + function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + const predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType( + type, + predicate.type, + assumeTrue, + /*checkDerived*/ + false + ); + } + if (strictNullChecks && optionalChainContainsReference(predicateArgument, reference) && (assumeTrue && !hasTypeFacts(predicate.type, 65536 /* EQUndefined */) || !assumeTrue && everyType(predicate.type, isNullableType))) { + type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } + const access = getDiscriminantPropertyAccess(predicateArgument, type); + if (access) { + return narrowTypeByDiscriminant(type, access, (t) => getNarrowedType( + t, + predicate.type, + assumeTrue, + /*checkDerived*/ + false + )); + } + } + } + return type; + } + function narrowType(type, expr, assumeTrue) { + if (isExpressionOfOptionalChainRoot(expr) || isBinaryExpression(expr.parent) && (expr.parent.operatorToken.kind === 61 /* QuestionQuestionToken */ || expr.parent.operatorToken.kind === 78 /* QuestionQuestionEqualsToken */) && expr.parent.left === expr) { + return narrowTypeByOptionality(type, expr, assumeTrue); + } + switch (expr.kind) { + case 80 /* Identifier */: + if (!isMatchingReference(reference, expr) && inlineLevel < 5) { + const symbol = getResolvedSymbol(expr); + if (isConstantVariable(symbol)) { + const declaration = symbol.valueDeclaration; + if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isConstantReference(reference)) { + inlineLevel++; + const result = narrowType(type, declaration.initializer, assumeTrue); + inlineLevel--; + return result; + } + } + } + // falls through + case 110 /* ThisKeyword */: + case 108 /* SuperKeyword */: + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 213 /* CallExpression */: + return narrowTypeByCallExpression(type, expr, assumeTrue); + case 217 /* ParenthesizedExpression */: + case 235 /* NonNullExpression */: + case 238 /* SatisfiesExpression */: + return narrowType(type, expr.expression, assumeTrue); + case 226 /* BinaryExpression */: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 224 /* PrefixUnaryExpression */: + if (expr.operator === 54 /* ExclamationToken */) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + function narrowTypeByOptionality(type, expr, assumePresent) { + if (isMatchingReference(reference, expr)) { + return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); + } + const access = getDiscriminantPropertyAccess(expr, type); + if (access) { + return narrowTypeByDiscriminant(type, access, (t) => getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */)); + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = getExportSymbolOfValueSymbolIfExported(symbol); + if (location.kind === 80 /* Identifier */ || location.kind === 81 /* PrivateIdentifier */) { + if (isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) { + const type = removeOptionalTypeMarker( + isWriteAccess(location) && location.kind === 211 /* PropertyAccessExpression */ ? checkPropertyAccessExpression( + location, + /*checkMode*/ + void 0, + /*writeOnly*/ + true + ) : getTypeOfExpression(location) + ); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + if (isDeclarationName(location) && isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return getWriteTypeOfAccessors(location.parent.symbol); + } + return isRightSideOfAccessExpression(location) && isWriteAccess(location.parent) ? getWriteTypeOfSymbol(symbol) : getNonMissingTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 268 /* ModuleBlock */ || node2.kind === 307 /* SourceFile */ || node2.kind === 172 /* PropertyDeclaration */); + } + function isSymbolAssignedDefinitely(symbol) { + if (symbol.lastAssignmentPos !== void 0) { + return symbol.lastAssignmentPos < 0; + } + return isSymbolAssigned(symbol) && symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0; + } + function isSymbolAssigned(symbol) { + return !isPastLastAssignment( + symbol, + /*location*/ + void 0 + ); + } + function isPastLastAssignment(symbol, location) { + const parent = findAncestor(symbol.valueDeclaration, isFunctionOrSourceFile); + if (!parent) { + return false; + } + const links = getNodeLinks(parent); + if (!(links.flags & 131072 /* AssignmentsMarked */)) { + links.flags |= 131072 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(parent)) { + markNodeAssignments(parent); + } + } + return !symbol.lastAssignmentPos || location && Math.abs(symbol.lastAssignmentPos) < location.pos; + } + function isSomeSymbolAssigned(rootDeclaration) { + Debug.assert(isVariableDeclaration(rootDeclaration) || isParameter(rootDeclaration)); + return isSomeSymbolAssignedWorker(rootDeclaration.name); + } + function isSomeSymbolAssignedWorker(node) { + if (node.kind === 80 /* Identifier */) { + return isSymbolAssigned(getSymbolOfDeclaration(node.parent)); + } + return some(node.elements, (e) => e.kind !== 232 /* OmittedExpression */ && isSomeSymbolAssignedWorker(e.name)); + } + function hasParentWithAssignmentsMarked(node) { + return !!findAncestor(node.parent, (node2) => isFunctionOrSourceFile(node2) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */)); + } + function isFunctionOrSourceFile(node) { + return isFunctionLikeDeclaration(node) || isSourceFile(node); + } + function markNodeAssignments(node) { + switch (node.kind) { + case 80 /* Identifier */: + const assigmentTarget = getAssignmentTargetKind(node); + if (assigmentTarget !== 0 /* None */) { + const symbol = getResolvedSymbol(node); + const hasDefiniteAssignment = assigmentTarget === 1 /* Definite */ || symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0; + if (isParameterOrMutableLocalVariable(symbol)) { + if (symbol.lastAssignmentPos === void 0 || Math.abs(symbol.lastAssignmentPos) !== Number.MAX_VALUE) { + const referencingFunction = findAncestor(node, isFunctionOrSourceFile); + const declaringFunction = findAncestor(symbol.valueDeclaration, isFunctionOrSourceFile); + symbol.lastAssignmentPos = referencingFunction === declaringFunction ? extendAssignmentPosition(node, symbol.valueDeclaration) : Number.MAX_VALUE; + } + if (hasDefiniteAssignment && symbol.lastAssignmentPos > 0) { + symbol.lastAssignmentPos *= -1; + } + } + } + return; + case 281 /* ExportSpecifier */: + const exportDeclaration = node.parent.parent; + const name = node.propertyName || node.name; + if (!node.isTypeOnly && !exportDeclaration.isTypeOnly && !exportDeclaration.moduleSpecifier && name.kind !== 11 /* StringLiteral */) { + const symbol = resolveEntityName( + name, + 111551 /* Value */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true + ); + if (symbol && isParameterOrMutableLocalVariable(symbol)) { + const sign = symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0 ? -1 : 1; + symbol.lastAssignmentPos = sign * Number.MAX_VALUE; + } + } + return; + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 266 /* EnumDeclaration */: + return; + } + if (isTypeNode(node)) { + return; + } + forEachChild(node, markNodeAssignments); + } + function extendAssignmentPosition(node, declaration) { + let pos = node.pos; + while (node && node.pos > declaration.pos) { + switch (node.kind) { + case 243 /* VariableStatement */: + case 244 /* ExpressionStatement */: + case 245 /* IfStatement */: + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 254 /* WithStatement */: + case 255 /* SwitchStatement */: + case 258 /* TryStatement */: + case 263 /* ClassDeclaration */: + pos = node.end; + } + node = node.parent; + } + return pos; + } + function isConstantVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* Constant */) !== 0; + } + function isParameterOrMutableLocalVariable(symbol) { + const declaration = symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration); + return !!declaration && (isParameter(declaration) || isVariableDeclaration(declaration) && (isCatchClause(declaration.parent) || isMutableLocalVariableDeclaration(declaration))); + } + function isMutableLocalVariableDeclaration(declaration) { + return !!(declaration.parent.flags & 1 /* Let */) && !(getCombinedModifierFlags(declaration) & 32 /* Export */ || declaration.parent.parent.kind === 243 /* VariableStatement */ && isGlobalSourceFile(declaration.parent.parent.parent)); + } + function parameterInitializerContainsUndefined(declaration) { + const links = getNodeLinks(declaration); + if (links.parameterInitializerContainsUndefined === void 0) { + if (!pushTypeResolution(declaration, 8 /* ParameterInitializerContainsUndefined */)) { + reportCircularityError(declaration.symbol); + return true; + } + const containsUndefined = !!hasTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */), 16777216 /* IsUndefined */); + if (!popTypeResolution()) { + reportCircularityError(declaration.symbol); + return true; + } + links.parameterInitializerContainsUndefined ?? (links.parameterInitializerContainsUndefined = containsUndefined); + } + return links.parameterInitializerContainsUndefined; + } + function removeOptionalityFromDeclaredType(declaredType, declaration) { + const removeUndefined = strictNullChecks && declaration.kind === 169 /* Parameter */ && declaration.initializer && hasTypeFacts(declaredType, 16777216 /* IsUndefined */) && !parameterInitializerContainsUndefined(declaration); + return removeUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; + } + function isConstraintPosition(type, node) { + const parent = node.parent; + return parent.kind === 211 /* PropertyAccessExpression */ || parent.kind === 166 /* QualifiedName */ || parent.kind === 213 /* CallExpression */ && parent.expression === node || parent.kind === 214 /* NewExpression */ && parent.expression === node || parent.kind === 212 /* ElementAccessExpression */ && parent.expression === node && !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); + } + function isGenericTypeWithUnionConstraint(type) { + return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithUnionConstraint) : !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); + } + function isGenericTypeWithoutNullableConstraint(type) { + return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithoutNullableConstraint) : !!(type.flags & 465829888 /* Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* Nullable */)); + } + function hasContextualTypeWithNoGenericTypes(node, checkMode) { + const contextualType = (isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node)) && !((isJsxOpeningElement(node.parent) || isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 32 /* RestBindingElement */ ? getContextualType(node, 8 /* SkipBindingPatterns */) : getContextualType( + node, + /*contextFlags*/ + void 0 + )); + return contextualType && !isGenericType(contextualType); + } + function getNarrowableTypeForReference(type, reference, checkMode) { + if (isNoInferType(type)) { + type = type.baseType; + } + const substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); + return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; + } + function isExportOrExportExpression(location) { + return !!findAncestor(location, (n) => { + const parent = n.parent; + if (parent === void 0) { + return "quit"; + } + if (isExportAssignment(parent)) { + return parent.expression === n && isEntityNameExpression(n); + } + if (isExportSpecifier(parent)) { + return parent.name === n || parent.propertyName === n; + } + return false; + }); + } + function markLinkedReferences(location, hint, propSymbol, parentType) { + if (!canCollectSymbolAliasAccessabilityData) { + return; + } + if (location.flags & 33554432 /* Ambient */ && !isPropertySignature(location) && !isPropertyDeclaration(location)) { + return; + } + switch (hint) { + case 1 /* Identifier */: + return markIdentifierAliasReferenced(location); + case 2 /* Property */: + return markPropertyAliasReferenced(location, propSymbol, parentType); + case 3 /* ExportAssignment */: + return markExportAssignmentAliasReferenced(location); + case 4 /* Jsx */: + return markJsxAliasReferenced(location); + case 5 /* AsyncFunction */: + return markAsyncFunctionAliasReferenced(location); + case 6 /* ExportImportEquals */: + return markImportEqualsAliasReferenced(location); + case 7 /* ExportSpecifier */: + return markExportSpecifierAliasReferenced(location); + case 8 /* Decorator */: + return markDecoratorAliasReferenced(location); + case 0 /* Unspecified */: { + if (isIdentifier(location) && (isExpressionNode(location) || isShorthandPropertyAssignment(location.parent) || isImportEqualsDeclaration(location.parent) && location.parent.moduleReference === location) && shouldMarkIdentifierAliasReferenced(location)) { + if (isPropertyAccessOrQualifiedName(location.parent)) { + const left = isPropertyAccessExpression(location.parent) ? location.parent.expression : location.parent.left; + if (left !== location) return; + } + markIdentifierAliasReferenced(location); + return; + } + if (isPropertyAccessOrQualifiedName(location)) { + let topProp = location; + while (isPropertyAccessOrQualifiedName(topProp)) { + if (isPartOfTypeNode(topProp)) return; + topProp = topProp.parent; + } + return markPropertyAliasReferenced(location); + } + if (isExportAssignment(location)) { + return markExportAssignmentAliasReferenced(location); + } + if (isJsxOpeningLikeElement(location) || isJsxOpeningFragment(location)) { + return markJsxAliasReferenced(location); + } + if (isImportEqualsDeclaration(location)) { + if (isInternalModuleImportEqualsDeclaration(location) || checkExternalImportOrExportDeclaration(location)) { + return markImportEqualsAliasReferenced(location); + } + return; + } + if (isExportSpecifier(location)) { + return markExportSpecifierAliasReferenced(location); + } + if (isFunctionLikeDeclaration(location) || isMethodSignature(location)) { + markAsyncFunctionAliasReferenced(location); + } + if (!compilerOptions.emitDecoratorMetadata) { + return; + } + if (!canHaveDecorators(location) || !hasDecorators(location) || !location.modifiers || !nodeCanBeDecorated(legacyDecorators, location, location.parent, location.parent.parent)) { + return; + } + return markDecoratorAliasReferenced(location); + } + default: + Debug.assertNever(hint, `Unhandled reference hint: ${hint}`); + } + } + function markIdentifierAliasReferenced(location) { + const symbol = getResolvedSymbol(location); + if (symbol && symbol !== argumentsSymbol && symbol !== unknownSymbol && !isThisInTypeQuery(location)) { + markAliasReferenced(symbol, location); + } + } + function markPropertyAliasReferenced(location, propSymbol, parentType) { + const left = isPropertyAccessExpression(location) ? location.expression : location.left; + if (isThisIdentifier(left) || !isIdentifier(left)) { + return; + } + const parentSymbol = getResolvedSymbol(left); + if (!parentSymbol || parentSymbol === unknownSymbol) { + return; + } + if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location)) { + markAliasReferenced(parentSymbol, location); + return; + } + const leftType = parentType || checkExpressionCached(left); + if (isTypeAny(leftType) || leftType === silentNeverType) { + markAliasReferenced(parentSymbol, location); + return; + } + let prop = propSymbol; + if (!prop && !parentType) { + const right = isPropertyAccessExpression(location) ? location.name : location.right; + const lexicallyScopedSymbol = isPrivateIdentifier(right) && lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + const assignmentKind = getAssignmentTargetKind(location); + const apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(location) ? getWidenedType(leftType) : leftType); + prop = isPrivateIdentifier(right) ? lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(apparentType, lexicallyScopedSymbol) || void 0 : getPropertyOfType(apparentType, right.escapedText); + } + if (!(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* EnumMember */ && location.parent.kind === 306 /* EnumMember */))) { + markAliasReferenced(parentSymbol, location); + } + return; + } + function markExportAssignmentAliasReferenced(location) { + if (isIdentifier(location.expression)) { + const id = location.expression; + const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName( + id, + -1 /* All */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + location + )); + if (sym) { + markAliasReferenced(sym, id); + } + } + } + function markJsxAliasReferenced(node) { + if (!getJsxNamespaceContainerForImplicitImport(node)) { + const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? Diagnostics.This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found : void 0; + const jsxFactoryNamespace = getJsxNamespace(node); + const jsxFactoryLocation = isJsxOpeningLikeElement(node) ? node.tagName : node; + const shouldFactoryRefErr = compilerOptions.jsx !== 1 /* Preserve */ && compilerOptions.jsx !== 3 /* ReactNative */; + let jsxFactorySym; + if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) { + jsxFactorySym = resolveName( + jsxFactoryLocation, + jsxFactoryNamespace, + shouldFactoryRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */, + jsxFactoryRefErr, + /*isUse*/ + true + ); + } + if (jsxFactorySym) { + jsxFactorySym.isReferenced = -1 /* All */; + if (canCollectSymbolAliasAccessabilityData && jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) { + markAliasSymbolAsReferenced(jsxFactorySym); + } + } + if (isJsxOpeningFragment(node)) { + const file = getSourceFileOfNode(node); + const entity = getJsxFactoryEntity(file); + if (entity) { + const localJsxNamespace = getFirstIdentifier(entity).escapedText; + resolveName( + jsxFactoryLocation, + localJsxNamespace, + shouldFactoryRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */, + jsxFactoryRefErr, + /*isUse*/ + true + ); + } + } + } + return; + } + function markAsyncFunctionAliasReferenced(location) { + if (languageVersion < 2 /* ES2015 */) { + if (getFunctionFlags(location) & 2 /* Async */) { + const returnTypeNode = getEffectiveReturnTypeNode(location); + markTypeNodeAsReferenced(returnTypeNode); + } + } + } + function markImportEqualsAliasReferenced(location) { + if (hasSyntacticModifier(location, 32 /* Export */)) { + markExportAsReferenced(location); + } + } + function markExportSpecifierAliasReferenced(location) { + if (!location.parent.parent.moduleSpecifier && !location.isTypeOnly && !location.parent.parent.isTypeOnly) { + const exportedName = location.propertyName || location.name; + if (exportedName.kind === 11 /* StringLiteral */) { + return; + } + const symbol = resolveName( + exportedName, + exportedName.escapedText, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + } else { + const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); + if (!target || getSymbolFlags(target) & 111551 /* Value */) { + markExportAsReferenced(location); + markIdentifierAliasReferenced(exportedName); + } + } + return; + } + } + function markDecoratorAliasReferenced(node) { + if (compilerOptions.emitDecoratorMetadata) { + const firstDecorator = find(node.modifiers, isDecorator); + if (!firstDecorator) { + return; + } + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + switch (node.kind) { + case 263 /* ClassDeclaration */: + const constructor = getFirstConstructorWithBody(node); + if (constructor) { + for (const parameter of constructor.parameters) { + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + const otherKind = node.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */; + const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 174 /* MethodDeclaration */: + for (const parameter of node.parameters) { + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node)); + break; + case 172 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node)); + break; + case 169 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + const containingSignature = node.parent; + for (const parameter of containingSignature.parameters) { + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); + break; + } + } + } + function markAliasReferenced(symbol, location) { + if (!canCollectSymbolAliasAccessabilityData) { + return; + } + if (isNonLocalAlias( + symbol, + /*excludes*/ + 111551 /* Value */ + ) && !isInTypeQuery(location)) { + const target = resolveAlias(symbol); + if (getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & (111551 /* Value */ | 1048576 /* ExportValue */)) { + if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { + markAliasSymbolAsReferenced(symbol); + } + } + } + } + function markAliasSymbolAsReferenced(symbol) { + Debug.assert(canCollectSymbolAliasAccessabilityData); + const links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + const node = getDeclarationOfAliasSymbol(symbol); + if (!node) return Debug.fail(); + if (isInternalModuleImportEqualsDeclaration(node)) { + if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { + const left = getFirstIdentifier(node.moduleReference); + markIdentifierAliasReferenced(left); + } + } + } + } + function markExportAsReferenced(node) { + const symbol = getSymbolOfDeclaration(node); + const target = resolveAlias(symbol); + if (target) { + const markAlias = target === unknownSymbol || getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) { + if (!typeName) return; + const rootName = getFirstIdentifier(typeName); + const meaning = (typeName.kind === 80 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + const rootSymbol = resolveName( + rootName, + rootName.escapedText, + meaning, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */) { + if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) { + markAliasSymbolAsReferenced(rootSymbol); + } else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) { + const diag2 = error(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); + const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration); + if (aliasDeclaration) { + addRelatedInfo(diag2, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName))); + } + } + } + } + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference( + node && getEntityNameFromTypeNode(node), + /*forDecoratorMetadata*/ + false + ); + } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + const entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference( + entityName, + /*forDecoratorMetadata*/ + true + ); + } + } + function getNarrowedTypeOfSymbol(symbol, location) { + var _a; + const type = getTypeOfSymbol(symbol); + const declaration = symbol.valueDeclaration; + if (declaration) { + if (isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) { + const parent = declaration.parent.parent; + const rootDeclaration = getRootDeclaration(parent); + if (rootDeclaration.kind === 260 /* VariableDeclaration */ && getCombinedNodeFlagsCached(rootDeclaration) & 6 /* Constant */ || rootDeclaration.kind === 169 /* Parameter */) { + const links = getNodeLinks(parent); + if (!(links.flags & 4194304 /* InCheckIdentifier */)) { + links.flags |= 4194304 /* InCheckIdentifier */; + const parentType = getTypeForBindingElementParent(parent, 0 /* Normal */); + const parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType); + links.flags &= ~4194304 /* InCheckIdentifier */; + if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(rootDeclaration.kind === 169 /* Parameter */ && isSomeSymbolAssigned(rootDeclaration))) { + const pattern = declaration.parent; + const narrowedType = getFlowTypeOfReference( + pattern, + parentTypeConstraint, + parentTypeConstraint, + /*flowContainer*/ + void 0, + location.flowNode + ); + if (narrowedType.flags & 131072 /* Never */) { + return neverType; + } + return getBindingElementTypeFromParentType( + declaration, + narrowedType, + /*noTupleBoundsCheck*/ + true + ); + } + } + } + } + if (isParameter(declaration) && !declaration.type && !declaration.initializer && !declaration.dotDotDotToken) { + const func = declaration.parent; + if (func.parameters.length >= 2 && isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + const contextualSignature = getContextualSignature(func); + if (contextualSignature && contextualSignature.parameters.length === 1 && signatureHasRestParameter(contextualSignature)) { + const restType = getReducedApparentType(instantiateType(getTypeOfSymbol(contextualSignature.parameters[0]), (_a = getInferenceContext(func)) == null ? void 0 : _a.nonFixingMapper)); + if (restType.flags & 1048576 /* Union */ && everyType(restType, isTupleType) && !some(func.parameters, isSomeSymbolAssigned)) { + const narrowedType = getFlowTypeOfReference( + func, + restType, + restType, + /*flowContainer*/ + void 0, + location.flowNode + ); + const index = func.parameters.indexOf(declaration) - (getThisParameter(func) ? 1 : 0); + return getIndexedAccessType(narrowedType, getNumberLiteralType(index)); + } + } + } + } + } + return type; + } + function checkIdentifierCalculateNodeCheckFlags(node, symbol) { + if (isThisInTypeQuery(node)) return; + if (symbol === argumentsSymbol) { + if (isInPropertyInitializerOrClassStaticBlock(node)) { + error(node, Diagnostics.arguments_cannot_be_referenced_in_property_initializers); + return; + } + let container = getContainingFunction(node); + if (container) { + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 219 /* ArrowFunction */) { + error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_function_expression); + } else if (hasSyntacticModifier(container, 1024 /* Async */)) { + error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 512 /* CaptureArguments */; + while (container && isArrowFunction(container)) { + container = getContainingFunction(container); + if (container) { + getNodeLinks(container).flags |= 512 /* CaptureArguments */; + } + } + } + return; + } + const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node); + if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) { + addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); + } + const declaration = localOrExportSymbol.valueDeclaration; + if (declaration && localOrExportSymbol.flags & 32 /* Class */) { + if (isClassLike(declaration) && declaration.name !== node) { + let container = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + while (container.kind !== 307 /* SourceFile */ && container.parent !== declaration) { + container = getThisContainer( + container, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + } + if (container.kind !== 307 /* SourceFile */) { + getNodeLinks(declaration).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(container).flags |= 262144 /* ContainsConstructorReference */; + getNodeLinks(node).flags |= 536870912 /* ConstructorReference */; + } + } + } + checkNestedBlockScopedBinding(node, symbol); + } + function checkIdentifier(node, checkMode) { + if (isThisInTypeQuery(node)) { + return checkThisExpression(node); + } + const symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return errorType; + } + checkIdentifierCalculateNodeCheckFlags(node, symbol); + if (symbol === argumentsSymbol) { + if (isInPropertyInitializerOrClassStaticBlock(node)) { + return errorType; + } + return getTypeOfSymbol(symbol); + } + if (shouldMarkIdentifierAliasReferenced(node)) { + markLinkedReferences(node, 1 /* Identifier */); + } + const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + let declaration = localOrExportSymbol.valueDeclaration; + const immediateDeclaration = declaration; + if (declaration && declaration.kind === 208 /* BindingElement */ && contains(contextualBindingPatterns, declaration.parent) && findAncestor(node, (parent) => parent === declaration.parent)) { + return nonInferrableAnyType; + } + let type = getNarrowedTypeOfSymbol(localOrExportSymbol, node); + const assignmentKind = getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) && !(isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + const assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? Diagnostics.Cannot_assign_to_0_because_it_is_an_enum : localOrExportSymbol.flags & 32 /* Class */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_class : localOrExportSymbol.flags & 1536 /* Module */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace : localOrExportSymbol.flags & 16 /* Function */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_function : localOrExportSymbol.flags & 2097152 /* Alias */ ? Diagnostics.Cannot_assign_to_0_because_it_is_an_import : Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; + error(node, assignmentError, symbolToString(symbol)); + return errorType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + if (localOrExportSymbol.flags & 3 /* Variable */) { + error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol)); + } else { + error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol)); + } + return errorType; + } + } + const isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; + if (localOrExportSymbol.flags & 3 /* Variable */) { + if (assignmentKind === 1 /* Definite */) { + return isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(type) : type; + } + } else if (isAlias) { + declaration = getDeclarationOfAliasSymbol(symbol); + } else { + return type; + } + if (!declaration) { + return type; + } + type = getNarrowableTypeForReference(type, node, checkMode); + const isParameter2 = getRootDeclaration(declaration).kind === 169 /* Parameter */; + const declarationContainer = getControlFlowContainer(declaration); + let flowContainer = getControlFlowContainer(node); + const isOuterVariable = flowContainer !== declarationContainer; + const isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + const isModuleExports = symbol.flags & 134217728 /* ModuleExports */; + const typeIsAutomatic = type === autoType || type === autoArrayType; + const isAutomaticTypeInNonNull = typeIsAutomatic && node.parent.kind === 235 /* NonNullExpression */; + while (flowContainer !== declarationContainer && (flowContainer.kind === 218 /* FunctionExpression */ || flowContainer.kind === 219 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameterOrMutableLocalVariable(localOrExportSymbol) && isPastLastAssignment(localOrExportSymbol, node))) { + flowContainer = getControlFlowContainer(flowContainer); + } + const isNeverInitialized = immediateDeclaration && isVariableDeclaration(immediateDeclaration) && !immediateDeclaration.initializer && !immediateDeclaration.exclamationToken && isMutableLocalVariableDeclaration(immediateDeclaration) && !isSymbolAssignedDefinitely(symbol); + const assumeInitialized = isParameter2 || isAlias || isOuterVariable && !isNeverInitialized || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 281 /* ExportSpecifier */) || node.parent.kind === 235 /* NonNullExpression */ || declaration.kind === 260 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 33554432 /* Ambient */; + const initialType = isAutomaticTypeInNonNull ? undefinedType : assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : typeIsAutomatic ? undefinedType : getOptionalType(type); + const flowType = isAutomaticTypeInNonNull ? getNonNullableType(getFlowTypeOfReference(node, type, initialType, flowContainer)) : getFlowTypeOfReference(node, type, initialType, flowContainer); + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + error(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return convertAutoToAny(flowType); + } + } else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) { + error(node, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isSameScopedBindingElement(node, declaration) { + if (isBindingElement(declaration)) { + const bindingElement = findAncestor(node, isBindingElement); + return bindingElement && getRootDeclaration(bindingElement) === getRootDeclaration(declaration); + } + } + function shouldMarkIdentifierAliasReferenced(node) { + var _a; + const parent = node.parent; + if (parent) { + if (isPropertyAccessExpression(parent) && parent.expression === node) { + return false; + } + if (isExportSpecifier(parent) && parent.isTypeOnly) { + return false; + } + const greatGrandparent = (_a = parent.parent) == null ? void 0 : _a.parent; + if (greatGrandparent && isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) { + return false; + } + } + return true; + } + function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { + return !!findAncestor(node, (n) => n === threshold ? "quit" : isFunctionLike(n) || n.parent && isPropertyDeclaration(n.parent) && !hasStaticModifier(n.parent) && n.parent.initializer === n); + } + function getPartOfForStatementContainingNode(node, container) { + return findAncestor(node, (n) => n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement); + } + function getEnclosingIterationStatement(node) { + return findAncestor(node, (n) => !n || nodeStartsNewLexicalEnvironment(n) ? "quit" : isIterationStatement( + n, + /*lookInLabeledStatements*/ + false + )); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || !symbol.valueDeclaration || isSourceFile(symbol.valueDeclaration) || symbol.valueDeclaration.parent.kind === 299 /* CatchClause */) { + return; + } + const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); + const isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container); + const enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + if (isCaptured) { + let capturesBlockScopeBindingInLoopBody = true; + if (isForStatement(container)) { + const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */); + if (varDeclList && varDeclList.parent === container) { + const part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + const links = getNodeLinks(part); + links.flags |= 8192 /* ContainsCapturedBlockScopeBinding */; + const capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; + } + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(enclosingIterationStatement).flags |= 4096 /* LoopWithCapturedBlockScopedBinding */; + } + } + if (isForStatement(container)) { + const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */); + if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 65536 /* NeedsLoopOutParameter */; + } + } + getNodeLinks(symbol.valueDeclaration).flags |= 32768 /* BlockScopedBindingInLoop */; + } + if (isCaptured) { + getNodeLinks(symbol.valueDeclaration).flags |= 16384 /* CapturedBlockScopedBinding */; + } + } + function isBindingCapturedByNode(node, decl) { + const links = getNodeLinks(node); + return !!links && contains(links.capturedBlockScopeBindings, getSymbolOfDeclaration(decl)); + } + function isAssignedInBodyOfForStatement(node, container) { + let current = node; + while (current.parent.kind === 217 /* ParenthesizedExpression */) { + current = current.parent; + } + let isAssigned = false; + if (isAssignmentTarget(current)) { + isAssigned = true; + } else if (current.parent.kind === 224 /* PrefixUnaryExpression */ || current.parent.kind === 225 /* PostfixUnaryExpression */) { + const expr = current.parent; + isAssigned = expr.operator === 46 /* PlusPlusToken */ || expr.operator === 47 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + return !!findAncestor(current, (n) => n === container ? "quit" : n === container.statement); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 172 /* PropertyDeclaration */ || container.kind === 176 /* Constructor */) { + const classNode = container.parent; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function findFirstSuperCall(node) { + return isSuperCall(node) ? node : isFunctionLike(node) ? void 0 : forEachChild(node, findFirstSuperCall); + } + function classDeclarationExtendsNull(classDecl) { + const classSymbol = getSymbolOfDeclaration(classDecl); + const classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + const baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + const containingClassDecl = container.parent; + const baseTypeNode = getClassExtendsHeritageElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + if (canHaveFlowNode(node) && node.flowNode && !isPostSuperFlowNode( + node.flowNode, + /*noCacheCheck*/ + false + )) { + error(node, diagnosticMessage); + } + } + } + function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) { + if (isPropertyDeclaration(container) && hasStaticModifier(container) && legacyDecorators && container.initializer && textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && hasDecorators(container.parent)) { + error(thisExpression, Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); + } + } + function checkThisExpression(node) { + const isNodeInTypeQuery = isInTypeQuery(node); + let container = getThisContainer( + node, + /*includeArrowFunctions*/ + true, + /*includeClassComputedPropertyName*/ + true + ); + let capturedByArrowFunction = false; + let thisInComputedPropertyName = false; + if (container.kind === 176 /* Constructor */) { + checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + while (true) { + if (container.kind === 219 /* ArrowFunction */) { + container = getThisContainer( + container, + /*includeArrowFunctions*/ + false, + !thisInComputedPropertyName + ); + capturedByArrowFunction = true; + } + if (container.kind === 167 /* ComputedPropertyName */) { + container = getThisContainer( + container, + !capturedByArrowFunction, + /*includeClassComputedPropertyName*/ + false + ); + thisInComputedPropertyName = true; + continue; + } + break; + } + checkThisInStaticClassFieldInitializerInDecoratedClass(node, container); + if (thisInComputedPropertyName) { + error(node, Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + } else { + switch (container.kind) { + case 267 /* ModuleDeclaration */: + error(node, Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + break; + case 266 /* EnumDeclaration */: + error(node, Diagnostics.this_cannot_be_referenced_in_current_location); + break; + } + } + if (!isNodeInTypeQuery && capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { + captureLexicalThis(node, container); + } + const type = tryGetThisTypeAt( + node, + /*includeGlobalThis*/ + true, + container + ); + if (noImplicitThis) { + const globalThisType2 = getTypeOfSymbol(globalThisSymbol); + if (type === globalThisType2 && capturedByArrowFunction) { + error(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this); + } else if (!type) { + const diag2 = error(node, Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!isSourceFile(container)) { + const outsideThis = tryGetThisTypeAt(container); + if (outsideThis && outsideThis !== globalThisType2) { + addRelatedInfo(diag2, createDiagnosticForNode(container, Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } + } + } + return type || anyType; + } + function tryGetThisTypeAt(node, includeGlobalThis = true, container = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + )) { + const isInJS = isInJSFile(node); + if (isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container))) { + let thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container); + if (!thisType) { + const className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { + const classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && classSymbol.flags & 16 /* Function */) { + thisType = getDeclaredTypeOfSymbol(classSymbol).thisType; + } + } else if (isJSConstructor(container)) { + thisType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType; + } + thisType || (thisType = getContextualThisParameterType(container)); + } + if (thisType) { + return getFlowTypeOfReference(node, thisType); + } + } + if (isClassLike(container.parent)) { + const symbol = getSymbolOfDeclaration(container.parent); + const type = isStatic(container) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (isSourceFile(container)) { + if (container.commonJsModuleIndicator) { + const fileSymbol = getSymbolOfDeclaration(container); + return fileSymbol && getTypeOfSymbol(fileSymbol); + } else if (container.externalModuleIndicator) { + return undefinedType; + } else if (includeGlobalThis) { + return getTypeOfSymbol(globalThisSymbol); + } + } + } + function getExplicitThisType(node) { + const container = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (isFunctionLike(container)) { + const signature = getSignatureFromDeclaration(container); + if (signature.thisParameter) { + return getExplicitTypeOfSymbol(signature.thisParameter); + } + } + if (isClassLike(container.parent)) { + const symbol = getSymbolOfDeclaration(container.parent); + return isStatic(container) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + } + } + function getClassNameFromPrototypeMethod(container) { + if (container.kind === 218 /* FunctionExpression */ && isBinaryExpression(container.parent) && getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + return container.parent.left.expression.expression; + } else if (container.kind === 174 /* MethodDeclaration */ && container.parent.kind === 210 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent) && getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } else if (container.kind === 218 /* FunctionExpression */ && container.parent.kind === 303 /* PropertyAssignment */ && container.parent.parent.kind === 210 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent.parent) && getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } else if (container.kind === 218 /* FunctionExpression */ && isPropertyAssignment(container.parent) && isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && isObjectLiteralExpression(container.parent.parent) && isCallExpression(container.parent.parent.parent) && container.parent.parent.parent.arguments[2] === container.parent.parent && getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.parent.arguments[0].expression; + } else if (isMethodDeclaration(container) && isIdentifier(container.name) && (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && isObjectLiteralExpression(container.parent) && isCallExpression(container.parent.parent) && container.parent.parent.arguments[2] === container.parent && getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) { + return container.parent.parent.arguments[0].expression; + } + } + function getTypeForThisExpressionFromJSDoc(node) { + const thisTag = getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } + const signature = getSignatureOfTypeTag(node); + if (signature) { + return getThisTypeOfSignature(signature); + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!findAncestor(node, (n) => isFunctionLikeDeclaration(n) ? "quit" : n.kind === 169 /* Parameter */ && n.parent === constructorDecl); + } + function checkSuperExpression(node) { + const isCallExpression2 = node.parent.kind === 213 /* CallExpression */ && node.parent.expression === node; + const immediateContainer = getSuperContainer( + node, + /*stopOnFunctions*/ + true + ); + let container = immediateContainer; + let needToCaptureLexicalThis = false; + let inAsyncFunction = false; + if (!isCallExpression2) { + while (container && container.kind === 219 /* ArrowFunction */) { + if (hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true; + container = getSuperContainer( + container, + /*stopOnFunctions*/ + true + ); + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; + } + if (container && hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true; + } + let nodeCheckFlag = 0; + if (!container || !isLegalUsageOfSuperExpression(container)) { + const current = findAncestor(node, (n) => n === container ? "quit" : n.kind === 167 /* ComputedPropertyName */); + if (current && current.kind === 167 /* ComputedPropertyName */) { + error(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } else if (isCallExpression2) { + error(node, Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } else if (!container || !container.parent || !(isClassLike(container.parent) || container.parent.kind === 210 /* ObjectLiteralExpression */)) { + error(node, Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { + error(node, Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return errorType; + } + if (!isCallExpression2 && immediateContainer.kind === 176 /* Constructor */) { + checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if (isStatic(container) || isCallExpression2) { + nodeCheckFlag = 32 /* SuperStatic */; + if (!isCallExpression2 && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) { + forEachEnclosingBlockScopeContainer(node.parent, (current) => { + if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) { + getNodeLinks(current).flags |= 2097152 /* ContainsSuperPropertyInStaticInitializer */; + } + }); + } + } else { + nodeCheckFlag = 16 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (container.kind === 174 /* MethodDeclaration */ && inAsyncFunction) { + if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 256 /* MethodWithSuperPropertyAssignmentInAsync */; + } else { + getNodeLinks(container).flags |= 128 /* MethodWithSuperPropertyAccessInAsync */; + } + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 210 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { + error(node, Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return errorType; + } else { + return anyType; + } + } + const classLikeDeclaration = container.parent; + if (!getClassExtendsHeritageElement(classLikeDeclaration)) { + error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return errorType; + } + if (classDeclarationExtendsNull(classLikeDeclaration)) { + return isCallExpression2 ? errorType : nullWideningType; + } + const classType = getDeclaredTypeOfSymbol(getSymbolOfDeclaration(classLikeDeclaration)); + const baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + return errorType; + } + if (container.kind === 176 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + error(node, Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return errorType; + } + return nodeCheckFlag === 32 /* SuperStatic */ ? getBaseConstructorTypeOfClass(classType) : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container2) { + if (isCallExpression2) { + return container2.kind === 176 /* Constructor */; + } else { + if (isClassLike(container2.parent) || container2.parent.kind === 210 /* ObjectLiteralExpression */) { + if (isStatic(container2)) { + return container2.kind === 174 /* MethodDeclaration */ || container2.kind === 173 /* MethodSignature */ || container2.kind === 177 /* GetAccessor */ || container2.kind === 178 /* SetAccessor */ || container2.kind === 172 /* PropertyDeclaration */ || container2.kind === 175 /* ClassStaticBlockDeclaration */; + } else { + return container2.kind === 174 /* MethodDeclaration */ || container2.kind === 173 /* MethodSignature */ || container2.kind === 177 /* GetAccessor */ || container2.kind === 178 /* SetAccessor */ || container2.kind === 172 /* PropertyDeclaration */ || container2.kind === 171 /* PropertySignature */ || container2.kind === 176 /* Constructor */; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 174 /* MethodDeclaration */ || func.kind === 177 /* GetAccessor */ || func.kind === 178 /* SetAccessor */) && func.parent.kind === 210 /* ObjectLiteralExpression */ ? func.parent : func.kind === 218 /* FunctionExpression */ && func.parent.kind === 303 /* PropertyAssignment */ ? func.parent.parent : void 0; + } + function getThisTypeArgument(type) { + return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : void 0; + } + function getThisTypeFromContextualType(type) { + return mapType(type, (t) => { + return t.flags & 2097152 /* Intersection */ ? forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType) { + let literal = containingLiteral; + let type = contextualType; + while (type) { + const thisType = getThisTypeFromContextualType(type); + if (thisType) { + return thisType; + } + if (literal.parent.kind !== 303 /* PropertyAssignment */) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType( + literal, + /*contextFlags*/ + void 0 + ); + } + } + function getContextualThisParameterType(func) { + if (func.kind === 219 /* ArrowFunction */) { + return void 0; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + const contextualSignature = getContextualSignature(func); + if (contextualSignature) { + const thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + const inJs = isInJSFile(func); + if (noImplicitThis || inJs) { + const containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + const contextualType = getApparentTypeOfContextualType( + containingLiteral, + /*contextFlags*/ + void 0 + ); + const thisType = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType); + if (thisType) { + return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); + } + return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral)); + } + const parent = walkUpParenthesizedExpressions(func.parent); + if (isAssignmentExpression(parent)) { + const target = parent.left; + if (isAccessExpression(target)) { + const { expression } = target; + if (inJs && isIdentifier(expression)) { + const sourceFile = getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return void 0; + } + } + return getWidenedType(checkExpressionCached(expression)); + } + } + } + return void 0; + } + function getContextuallyTypedParameterType(parameter) { + const func = parameter.parent; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return void 0; + } + const iife = getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + const args = getEffectiveCallArguments(iife); + const indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + return getSpreadArgumentType( + args, + indexOfParameter, + args.length, + anyType, + /*context*/ + void 0, + 0 /* Normal */ + ); + } + const links = getNodeLinks(iife); + const cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + const type = indexOfParameter < args.length ? getWidenedLiteralType(checkExpression(args[indexOfParameter])) : parameter.initializer ? void 0 : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + const contextualSignature = getContextualSignature(func); + if (contextualSignature) { + const index = func.parameters.indexOf(parameter) - (getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && lastOrUndefined(func.parameters) === parameter ? getRestTypeAtPosition(contextualSignature, index) : tryGetTypeAtPosition(contextualSignature, index); + } + } + function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) { + const typeNode = getEffectiveTypeAnnotationNode(declaration) || (isInJSFile(declaration) ? tryGetJSDocSatisfiesTypeNode(declaration) : void 0); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + switch (declaration.kind) { + case 169 /* Parameter */: + return getContextuallyTypedParameterType(declaration); + case 208 /* BindingElement */: + return getContextualTypeForBindingElement(declaration, contextFlags); + case 172 /* PropertyDeclaration */: + if (isStatic(declaration)) { + return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); + } + } + } + function getContextualTypeForBindingElement(declaration, contextFlags) { + const parent = declaration.parent.parent; + const name = declaration.propertyName || declaration.name; + const parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 208 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */); + if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) return void 0; + if (parent.name.kind === 207 /* ArrayBindingPattern */) { + const index = indexOfNode(declaration.parent.elements, declaration); + if (index < 0) return void 0; + return getContextualTypeForElementExpression(parentType, index); + } + const nameType = getLiteralTypeFromPropertyName(name); + if (isTypeUsableAsPropertyName(nameType)) { + const text = getPropertyNameFromType(nameType); + return getTypeOfPropertyOfType(parentType, text); + } + } + function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { + const parentType = isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags); + if (!parentType) return void 0; + return getTypeOfPropertyOfContextualType(parentType, getSymbolOfDeclaration(declaration).escapedName); + } + function getContextualTypeForInitializerExpression(node, contextFlags) { + const declaration = node.parent; + if (hasInitializer(declaration) && node === declaration.initializer) { + const result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags); + if (result) { + return result; + } + if (!(contextFlags & 8 /* SkipBindingPatterns */) && isBindingPattern(declaration.name) && declaration.name.elements.length > 0) { + return getTypeFromBindingPattern( + declaration.name, + /*includePatternInType*/ + true, + /*reportErrors*/ + false + ); + } + } + return void 0; + } + function getContextualTypeForReturnExpression(node, contextFlags) { + const func = getContainingFunction(node); + if (func) { + let contextualReturnType = getContextualReturnType(func, contextFlags); + if (contextualReturnType) { + const functionFlags = getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { + const isAsyncGenerator = (functionFlags & 2 /* Async */) !== 0; + if (contextualReturnType.flags & 1048576 /* Union */) { + contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator)); + } + const iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0); + if (!iterationReturnType) { + return void 0; + } + contextualReturnType = iterationReturnType; + } + if (functionFlags & 2 /* Async */) { + const contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeNoAlias); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; + } + } + return void 0; + } + function getContextualTypeForAwaitOperand(node, contextFlags) { + const contextualType = getContextualType(node, contextFlags); + if (contextualType) { + const contextualAwaitedType = getAwaitedTypeNoAlias(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return void 0; + } + function getContextualTypeForYieldOperand(node, contextFlags) { + const func = getContainingFunction(node); + if (func) { + const functionFlags = getFunctionFlags(func); + let contextualReturnType = getContextualReturnType(func, contextFlags); + if (contextualReturnType) { + const isAsyncGenerator = (functionFlags & 2 /* Async */) !== 0; + if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* Union */) { + contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator)); + } + if (node.asteriskToken) { + const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(contextualReturnType, isAsyncGenerator); + const yieldType = (iterationTypes == null ? void 0 : iterationTypes.yieldType) ?? silentNeverType; + const returnType = getContextualType(node, contextFlags) ?? silentNeverType; + const nextType = (iterationTypes == null ? void 0 : iterationTypes.nextType) ?? unknownType; + const generatorType = createGeneratorType( + yieldType, + returnType, + nextType, + /*isAsyncGenerator*/ + false + ); + if (isAsyncGenerator) { + const asyncGeneratorType = createGeneratorType( + yieldType, + returnType, + nextType, + /*isAsyncGenerator*/ + true + ); + return getUnionType([generatorType, asyncGeneratorType]); + } + return generatorType; + } + return getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, isAsyncGenerator); + } + } + return void 0; + } + function isInParameterInitializerBeforeContainingFunction(node) { + let inBindingInitializer = false; + while (node.parent && !isFunctionLike(node.parent)) { + if (isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) { + return true; + } + if (isBindingElement(node.parent) && node.parent.initializer === node) { + inBindingInitializer = true; + } + node = node.parent; + } + return false; + } + function getContextualIterationType(kind, functionDecl) { + const isAsync = !!(getFunctionFlags(functionDecl) & 2 /* Async */); + const contextualReturnType = getContextualReturnType( + functionDecl, + /*contextFlags*/ + void 0 + ); + if (contextualReturnType) { + return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || void 0; + } + return void 0; + } + function getContextualReturnType(functionDecl, contextFlags) { + const returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; + } + const signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature && !isResolvingReturnTypeOfSignature(signature)) { + const returnType2 = getReturnTypeOfSignature(signature); + const functionFlags = getFunctionFlags(functionDecl); + if (functionFlags & 1 /* Generator */) { + return filterType(returnType2, (t) => { + return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || checkGeneratorInstantiationAssignabilityToReturnType( + t, + functionFlags, + /*errorNode*/ + void 0 + ); + }); + } + if (functionFlags & 2 /* Async */) { + return filterType(returnType2, (t) => { + return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || !!getAwaitedTypeOfPromise(t); + }); + } + return returnType2; + } + const iife = getImmediatelyInvokedFunctionExpression(functionDecl); + if (iife) { + return getContextualType(iife, contextFlags); + } + return void 0; + } + function getContextualTypeForArgument(callTarget, arg) { + const args = getEffectiveCallArguments(callTarget); + const argIndex = args.indexOf(arg); + return argIndex === -1 ? void 0 : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + } + function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + if (isImportCall(callTarget)) { + return argIndex === 0 ? stringType : argIndex === 1 ? getGlobalImportCallOptionsType( + /*reportErrors*/ + false + ) : anyType; + } + const signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } + const restIndex = signature.parameters.length - 1; + return signatureHasRestParameter(signature) && argIndex >= restIndex ? getIndexedAccessType(getTypeOfSymbol(signature.parameters[restIndex]), getNumberLiteralType(argIndex - restIndex), 256 /* Contextual */) : getTypeAtPosition(signature, argIndex); + } + function getContextualTypeForDecorator(decorator) { + const signature = getDecoratorCallSignature(decorator); + return signature ? getOrCreateTypeFromSignature(signature) : void 0; + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 215 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return void 0; + } + function getContextualTypeForBinaryOperand(node, contextFlags) { + const binaryExpression = node.parent; + const { left, operatorToken, right } = binaryExpression; + switch (operatorToken.kind) { + case 64 /* EqualsToken */: + case 77 /* AmpersandAmpersandEqualsToken */: + case 76 /* BarBarEqualsToken */: + case 78 /* QuestionQuestionEqualsToken */: + return node === right ? getContextualTypeForAssignmentDeclaration(binaryExpression) : void 0; + case 57 /* BarBarToken */: + case 61 /* QuestionQuestionToken */: + const type = getContextualType(binaryExpression, contextFlags); + return node === right && (type && type.pattern || !type && !isDefaultedExpandoInitializer(binaryExpression)) ? getTypeOfExpression(left) : type; + case 56 /* AmpersandAmpersandToken */: + case 28 /* CommaToken */: + return node === right ? getContextualType(binaryExpression, contextFlags) : void 0; + default: + return void 0; + } + } + function getSymbolForExpression(e) { + if (canHaveSymbol(e) && e.symbol) { + return e.symbol; + } + if (isIdentifier(e)) { + return getResolvedSymbol(e); + } + if (isPropertyAccessExpression(e)) { + const lhsType = getTypeOfExpression(e.expression); + return isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText); + } + if (isElementAccessExpression(e)) { + const propType = checkExpressionCached(e.argumentExpression); + if (!isTypeUsableAsPropertyName(propType)) { + return void 0; + } + const lhsType = getTypeOfExpression(e.expression); + return getPropertyOfType(lhsType, getPropertyNameFromType(propType)); + } + return void 0; + function tryGetPrivateIdentifierPropertyOfType(type, id) { + const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id); + return lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(type, lexicallyScopedSymbol); + } + } + function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; + const kind = getAssignmentDeclarationKind(binaryExpression); + switch (kind) { + case 0 /* None */: + case 4 /* ThisProperty */: + const lhsSymbol = getSymbolForExpression(binaryExpression.left); + const decl = lhsSymbol && lhsSymbol.valueDeclaration; + if (decl && (isPropertyDeclaration(decl) || isPropertySignature(decl))) { + const overallAnnotation = getEffectiveTypeAnnotationNode(decl); + return overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper) || (isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : void 0); + } + if (kind === 0 /* None */) { + return getTypeOfExpression(binaryExpression.left); + } + return getContextualTypeForThisPropertyAssignment(binaryExpression); + case 5 /* Property */: + if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { + return getContextualTypeForThisPropertyAssignment(binaryExpression); + } else if (!canHaveSymbol(binaryExpression.left) || !binaryExpression.left.symbol) { + return getTypeOfExpression(binaryExpression.left); + } else { + const decl2 = binaryExpression.left.symbol.valueDeclaration; + if (!decl2) { + return void 0; + } + const lhs = cast(binaryExpression.left, isAccessExpression); + const overallAnnotation = getEffectiveTypeAnnotationNode(decl2); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); + } else if (isIdentifier(lhs.expression)) { + const id = lhs.expression; + const parentSymbol = resolveName( + id, + id.escapedText, + 111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (parentSymbol) { + const annotated2 = parentSymbol.valueDeclaration && getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated2) { + const nameStr = getElementOrPropertyAccessName(lhs); + if (nameStr !== void 0) { + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated2), nameStr); + } + } + return void 0; + } + } + return isInJSFile(decl2) || decl2 === binaryExpression.left ? void 0 : getTypeOfExpression(binaryExpression.left); + } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 2 /* ModuleExports */: + let valueDeclaration; + if (kind !== 2 /* ModuleExports */) { + valueDeclaration = canHaveSymbol(binaryExpression.left) ? (_a = binaryExpression.left.symbol) == null ? void 0 : _a.valueDeclaration : void 0; + } + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) == null ? void 0 : _b.valueDeclaration); + const annotated = valueDeclaration && getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : void 0; + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return Debug.fail("Does not apply"); + default: + return Debug.assertNever(kind); + } + } + function isPossiblyAliasedThisProperty(declaration, kind = getAssignmentDeclarationKind(declaration)) { + if (kind === 4 /* ThisProperty */) { + return true; + } + if (!isInJSFile(declaration) || kind !== 5 /* Property */ || !isIdentifier(declaration.left.expression)) { + return false; + } + const name = declaration.left.expression.escapedText; + const symbol = resolveName( + declaration.left, + name, + 111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true, + /*excludeGlobals*/ + true + ); + return isThisInitializedDeclaration(symbol == null ? void 0 : symbol.valueDeclaration); + } + function getContextualTypeForThisPropertyAssignment(binaryExpression) { + if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); + if (binaryExpression.symbol.valueDeclaration) { + const annotated = getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + const type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + const thisAccess = cast(binaryExpression.left, isAccessExpression); + if (!isObjectLiteralMethod(getThisContainer( + thisAccess.expression, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ))) { + return void 0; + } + const thisType = checkThisExpression(thisAccess.expression); + const nameStr = getElementOrPropertyAccessName(thisAccess); + return nameStr !== void 0 && getTypeOfPropertyOfContextualType(thisType, nameStr) || void 0; + } + function isCircularMappedProperty(symbol) { + return !!(getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.links.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0); + } + function isExcludedMappedPropertyName(constraint, propertyNameType) { + if (constraint.flags & 16777216 /* Conditional */) { + const type = constraint; + return !!(getReducedType(getTrueTypeFromConditionalType(type)).flags & 131072 /* Never */) && getActualTypeVariable(getFalseTypeFromConditionalType(type)) === getActualTypeVariable(type.checkType) && isTypeAssignableTo(propertyNameType, type.extendsType); + } + if (constraint.flags & 2097152 /* Intersection */) { + return some(constraint.types, (t) => isExcludedMappedPropertyName(t, propertyNameType)); + } + return false; + } + function getTypeOfPropertyOfContextualType(type, name, nameType) { + return mapType( + type, + (t) => { + if (t.flags & 2097152 /* Intersection */) { + let types; + let indexInfoCandidates; + let ignoreIndexInfos = false; + for (const constituentType of t.types) { + if (!(constituentType.flags & 524288 /* Object */)) { + continue; + } + if (isGenericMappedType(constituentType) && getMappedTypeNameTypeKind(constituentType) !== 2 /* Remapping */) { + const substitutedType = getIndexedMappedTypeSubstitutedTypeOfContextualType(constituentType, name, nameType); + types = appendContextualPropertyTypeConstituent(types, substitutedType); + continue; + } + const propertyType = getTypeOfConcretePropertyOfContextualType(constituentType, name); + if (!propertyType) { + if (!ignoreIndexInfos) { + indexInfoCandidates = append(indexInfoCandidates, constituentType); + } + continue; + } + ignoreIndexInfos = true; + indexInfoCandidates = void 0; + types = appendContextualPropertyTypeConstituent(types, propertyType); + } + if (indexInfoCandidates) { + for (const candidate of indexInfoCandidates) { + const indexInfoType = getTypeFromIndexInfosOfContextualType(candidate, name, nameType); + types = appendContextualPropertyTypeConstituent(types, indexInfoType); + } + } + if (!types) { + return; + } + if (types.length === 1) { + return types[0]; + } + return getIntersectionType(types); + } + if (!(t.flags & 524288 /* Object */)) { + return; + } + return isGenericMappedType(t) && getMappedTypeNameTypeKind(t) !== 2 /* Remapping */ ? getIndexedMappedTypeSubstitutedTypeOfContextualType(t, name, nameType) : getTypeOfConcretePropertyOfContextualType(t, name) ?? getTypeFromIndexInfosOfContextualType(t, name, nameType); + }, + /*noReductions*/ + true + ); + } + function appendContextualPropertyTypeConstituent(types, type) { + return type ? append(types, type.flags & 1 /* Any */ ? unknownType : type) : types; + } + function getIndexedMappedTypeSubstitutedTypeOfContextualType(type, name, nameType) { + const propertyNameType = nameType || getStringLiteralType(unescapeLeadingUnderscores(name)); + const constraint = getConstraintTypeFromMappedType(type); + if (type.nameType && isExcludedMappedPropertyName(type.nameType, propertyNameType) || isExcludedMappedPropertyName(constraint, propertyNameType)) { + return; + } + const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; + if (!isTypeAssignableTo(propertyNameType, constraintOfConstraint)) { + return; + } + return substituteIndexedMappedType(type, propertyNameType); + } + function getTypeOfConcretePropertyOfContextualType(type, name) { + const prop = getPropertyOfType(type, name); + if (!prop || isCircularMappedProperty(prop)) { + return; + } + return removeMissingType(getTypeOfSymbol(prop), !!(prop.flags & 16777216 /* Optional */)); + } + function getTypeFromIndexInfosOfContextualType(type, name, nameType) { + var _a; + if (isTupleType(type) && isNumericLiteralName(name) && +name >= 0) { + const restType = getElementTypeOfSliceOfTupleType( + type, + type.target.fixedLength, + /*endSkipCount*/ + 0, + /*writing*/ + false, + /*noReductions*/ + true + ); + if (restType) { + return restType; + } + } + return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(type), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))) == null ? void 0 : _a.type; + } + function getContextualTypeForObjectLiteralMethod(node, contextFlags) { + Debug.assert(isObjectLiteralMethod(node)); + if (node.flags & 67108864 /* InWithStatement */) { + return void 0; + } + return getContextualTypeForObjectLiteralElement(node, contextFlags); + } + function getContextualTypeForObjectLiteralElement(element, contextFlags) { + const objectLiteral = element.parent; + const propertyAssignmentType = isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags); + if (propertyAssignmentType) { + return propertyAssignmentType; + } + const type = getApparentTypeOfContextualType(objectLiteral, contextFlags); + if (type) { + if (hasBindableName(element)) { + const symbol = getSymbolOfDeclaration(element); + return getTypeOfPropertyOfContextualType(type, symbol.escapedName, getSymbolLinks(symbol).nameType); + } + if (hasDynamicName(element)) { + const name = getNameOfDeclaration(element); + if (name && isComputedPropertyName(name)) { + const exprType = checkExpression(name.expression); + const propType = isTypeUsableAsPropertyName(exprType) && getTypeOfPropertyOfContextualType(type, getPropertyNameFromType(exprType)); + if (propType) { + return propType; + } + } + } + if (element.name) { + const nameType = getLiteralTypeFromPropertyName(element.name); + return mapType( + type, + (t) => { + var _a; + return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType)) == null ? void 0 : _a.type; + }, + /*noReductions*/ + true + ); + } + } + return void 0; + } + function getSpreadIndices(elements) { + let first2, last2; + for (let i = 0; i < elements.length; i++) { + if (isSpreadElement(elements[i])) { + first2 ?? (first2 = i); + last2 = i; + } + } + return { first: first2, last: last2 }; + } + function getContextualTypeForElementExpression(type, index, length2, firstSpreadIndex, lastSpreadIndex) { + return type && mapType( + type, + (t) => { + if (isTupleType(t)) { + if ((firstSpreadIndex === void 0 || index < firstSpreadIndex) && index < t.target.fixedLength) { + return removeMissingType(getTypeArguments(t)[index], !!(t.target.elementFlags[index] && 2 /* Optional */)); + } + const offset = length2 !== void 0 && (lastSpreadIndex === void 0 || index > lastSpreadIndex) ? length2 - index : 0; + const fixedEndLength = offset > 0 && t.target.combinedFlags & 12 /* Variable */ ? getEndElementCount(t.target, 3 /* Fixed */) : 0; + if (offset > 0 && offset <= fixedEndLength) { + return getTypeArguments(t)[getTypeReferenceArity(t) - offset]; + } + return getElementTypeOfSliceOfTupleType( + t, + firstSpreadIndex === void 0 ? t.target.fixedLength : Math.min(t.target.fixedLength, firstSpreadIndex), + length2 === void 0 || lastSpreadIndex === void 0 ? fixedEndLength : Math.min(fixedEndLength, length2 - lastSpreadIndex), + /*writing*/ + false, + /*noReductions*/ + true + ); + } + return (!firstSpreadIndex || index < firstSpreadIndex) && getTypeOfPropertyOfContextualType(t, "" + index) || getIteratedTypeOrElementType( + 1 /* Element */, + t, + undefinedType, + /*errorNode*/ + void 0, + /*checkAssignability*/ + false + ); + }, + /*noReductions*/ + true + ); + } + function getContextualTypeForConditionalOperand(node, contextFlags) { + const conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : void 0; + } + function getContextualTypeForChildJsxExpression(node, child, contextFlags) { + const attributesType = getApparentTypeOfContextualType(node.openingElement.attributes, contextFlags); + const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { + return void 0; + } + const realChildren = getSemanticJsxChildren(node.children); + const childIndex = realChildren.indexOf(child); + const childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); + return childFieldType && (realChildren.length === 1 ? childFieldType : mapType( + childFieldType, + (t) => { + if (isArrayLikeType(t)) { + return getIndexedAccessType(t, getNumberLiteralType(childIndex)); + } else { + return t; + } + }, + /*noReductions*/ + true + )); + } + function getContextualTypeForJsxExpression(node, contextFlags) { + const exprParent = node.parent; + return isJsxAttributeLike(exprParent) ? getContextualType(node, contextFlags) : isJsxElement(exprParent) ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : void 0; + } + function getContextualTypeForJsxAttribute(attribute, contextFlags) { + if (isJsxAttribute(attribute)) { + const attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags); + if (!attributesType || isTypeAny(attributesType)) { + return void 0; + } + return getTypeOfPropertyOfContextualType(attributesType, getEscapedTextOfJsxAttributeName(attribute.name)); + } else { + return getContextualType(attribute.parent, contextFlags); + } + } + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 11 /* StringLiteral */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 228 /* TemplateExpression */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 106 /* NullKeyword */: + case 80 /* Identifier */: + case 157 /* UndefinedKeyword */: + return true; + case 211 /* PropertyAccessExpression */: + case 217 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + case 294 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); + } + return false; + } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + const key = `D${getNodeId(node)},${getTypeId(contextualType)}`; + return getCachedType(key) ?? setCachedType( + key, + getMatchingUnionConstituentForObjectLiteral(contextualType, node) ?? discriminateTypeByDiscriminableItems( + contextualType, + concatenate( + map( + filter(node.properties, (p) => { + if (!p.symbol) { + return false; + } + if (p.kind === 303 /* PropertyAssignment */) { + return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); + } + if (p.kind === 304 /* ShorthandPropertyAssignment */) { + return isDiscriminantProperty(contextualType, p.symbol.escapedName); + } + return false; + }), + (prop) => [() => getContextFreeTypeOfExpression(prop.kind === 303 /* PropertyAssignment */ ? prop.initializer : prop.name), prop.symbol.escapedName] + ), + map( + filter(getPropertiesOfType(contextualType), (s) => { + var _a; + return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + }), + (s) => [() => undefinedType, s.escapedName] + ) + ), + isTypeAssignableTo + ) + ); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + const key = `D${getNodeId(node)},${getTypeId(contextualType)}`; + const cached = getCachedType(key); + if (cached) return cached; + const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + return setCachedType( + key, + discriminateTypeByDiscriminableItems( + contextualType, + concatenate( + map( + filter(node.properties, (p) => !!p.symbol && p.kind === 291 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), + (prop) => [!prop.initializer ? () => trueType : () => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName] + ), + map( + filter(getPropertiesOfType(contextualType), (s) => { + var _a; + if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) { + return false; + } + const element = node.parent.parent; + if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) { + return false; + } + return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + }), + (s) => [() => undefinedType, s.escapedName] + ) + ), + isTypeAssignableTo + ) + ); + } + function getApparentTypeOfContextualType(node, contextFlags) { + const contextualType = isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node, contextFlags) : getContextualType(node, contextFlags); + const instantiatedType = instantiateContextualType(contextualType, node, contextFlags); + if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) { + const apparentType = mapType( + instantiatedType, + // When obtaining apparent type of *contextual* type we don't want to get apparent type of mapped types. + // That would evaluate mapped types with array or tuple type constraints too eagerly + // and thus it would prevent `getTypeOfPropertyOfContextualType` from obtaining per-position contextual type for elements of array literal expressions. + // Apparent type of other mapped types is already the mapped type itself so we can just avoid calling `getApparentType` here for all mapped types. + (t) => getObjectFlags(t) & 32 /* Mapped */ ? t : getApparentType(t), + /*noReductions*/ + true + ); + return apparentType.flags & 1048576 /* Union */ && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : apparentType.flags & 1048576 /* Union */ && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : apparentType; + } + } + function instantiateContextualType(contextualType, node, contextFlags) { + if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* Instantiable */)) { + const inferenceContext = getInferenceContext(node); + if (inferenceContext && contextFlags & 1 /* Signature */ && some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) { + return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); + } + if (inferenceContext == null ? void 0 : inferenceContext.returnMapper) { + const type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); + return type.flags & 1048576 /* Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? filterType(type, (t) => t !== regularFalseType && t !== regularTrueType) : type; + } + } + return contextualType; + } + function instantiateInstantiableTypes(type, mapper) { + if (type.flags & 465829888 /* Instantiable */) { + return instantiateType(type, mapper); + } + if (type.flags & 1048576 /* Union */) { + return getUnionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper)), 0 /* None */); + } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper))); + } + return type; + } + function getContextualType(node, contextFlags) { + var _a; + if (node.flags & 67108864 /* InWithStatement */) { + return void 0; + } + const index = findContextualNode( + node, + /*includeCaches*/ + !contextFlags + ); + if (index >= 0) { + return contextualTypes[index]; + } + const { parent } = node; + switch (parent.kind) { + case 260 /* VariableDeclaration */: + case 169 /* Parameter */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 208 /* BindingElement */: + return getContextualTypeForInitializerExpression(node, contextFlags); + case 219 /* ArrowFunction */: + case 253 /* ReturnStatement */: + return getContextualTypeForReturnExpression(node, contextFlags); + case 229 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent, contextFlags); + case 223 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent, contextFlags); + case 213 /* CallExpression */: + case 214 /* NewExpression */: + return getContextualTypeForArgument(parent, node); + case 170 /* Decorator */: + return getContextualTypeForDecorator(parent); + case 216 /* TypeAssertionExpression */: + case 234 /* AsExpression */: + return isConstTypeReference(parent.type) ? getContextualType(parent, contextFlags) : getTypeFromTypeNode(parent.type); + case 226 /* BinaryExpression */: + return getContextualTypeForBinaryOperand(node, contextFlags); + case 303 /* PropertyAssignment */: + case 304 /* ShorthandPropertyAssignment */: + return getContextualTypeForObjectLiteralElement(parent, contextFlags); + case 305 /* SpreadAssignment */: + return getContextualType(parent.parent, contextFlags); + case 209 /* ArrayLiteralExpression */: { + const arrayLiteral = parent; + const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); + const elementIndex = indexOfNode(arrayLiteral.elements, node); + const spreadIndices = (_a = getNodeLinks(arrayLiteral)).spreadIndices ?? (_a.spreadIndices = getSpreadIndices(arrayLiteral.elements)); + return getContextualTypeForElementExpression(type, elementIndex, arrayLiteral.elements.length, spreadIndices.first, spreadIndices.last); + } + case 227 /* ConditionalExpression */: + return getContextualTypeForConditionalOperand(node, contextFlags); + case 239 /* TemplateSpan */: + Debug.assert(parent.parent.kind === 228 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 217 /* ParenthesizedExpression */: { + if (isInJSFile(parent)) { + if (isJSDocSatisfiesExpression(parent)) { + return getTypeFromTypeNode(getJSDocSatisfiesExpressionType(parent)); + } + const typeTag = getJSDocTypeTag(parent); + if (typeTag && !isConstTypeReference(typeTag.typeExpression.type)) { + return getTypeFromTypeNode(typeTag.typeExpression.type); + } + } + return getContextualType(parent, contextFlags); + } + case 235 /* NonNullExpression */: + return getContextualType(parent, contextFlags); + case 238 /* SatisfiesExpression */: + return getTypeFromTypeNode(parent.type); + case 277 /* ExportAssignment */: + return tryGetTypeFromEffectiveTypeNode(parent); + case 294 /* JsxExpression */: + return getContextualTypeForJsxExpression(parent, contextFlags); + case 291 /* JsxAttribute */: + case 293 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent, contextFlags); + case 286 /* JsxOpeningElement */: + case 285 /* JsxSelfClosingElement */: + return getContextualJsxElementAttributesType(parent, contextFlags); + case 301 /* ImportAttribute */: + return getContextualImportAttributeType(parent); + } + return void 0; + } + function pushCachedContextualType(node) { + pushContextualType( + node, + getContextualType( + node, + /*contextFlags*/ + void 0 + ), + /*isCache*/ + true + ); + } + function pushContextualType(node, type, isCache) { + contextualTypeNodes[contextualTypeCount] = node; + contextualTypes[contextualTypeCount] = type; + contextualIsCache[contextualTypeCount] = isCache; + contextualTypeCount++; + } + function popContextualType() { + contextualTypeCount--; + } + function findContextualNode(node, includeCaches) { + for (let i = contextualTypeCount - 1; i >= 0; i--) { + if (node === contextualTypeNodes[i] && (includeCaches || !contextualIsCache[i])) { + return i; + } + } + return -1; + } + function pushInferenceContext(node, inferenceContext) { + inferenceContextNodes[inferenceContextCount] = node; + inferenceContexts[inferenceContextCount] = inferenceContext; + inferenceContextCount++; + } + function popInferenceContext() { + inferenceContextCount--; + } + function getInferenceContext(node) { + for (let i = inferenceContextCount - 1; i >= 0; i--) { + if (isNodeDescendantOf(node, inferenceContextNodes[i])) { + return inferenceContexts[i]; + } + } + } + function getContextualImportAttributeType(node) { + return getTypeOfPropertyOfContextualType(getGlobalImportAttributesType( + /*reportErrors*/ + false + ), getNameFromImportAttribute(node)); + } + function getContextualJsxElementAttributesType(node, contextFlags) { + if (isJsxOpeningElement(node) && contextFlags !== 4 /* Completions */) { + const index = findContextualNode( + node.parent, + /*includeCaches*/ + !contextFlags + ); + if (index >= 0) { + return contextualTypes[index]; + } + } + return getContextualTypeForArgumentAtIndex(node, 0); + } + function getEffectiveFirstArgumentForJsxSignature(signature, node) { + return isJsxOpeningFragment(node) || getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); + } + function getJsxPropsTypeFromCallSignature(sig, context) { + let propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); + const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (!isErrorType(intrinsicAttribs)) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + if (sig.compositeSignatures) { + const results = []; + for (const signature of sig.compositeSignatures) { + const instance = getReturnTypeOfSignature(signature); + if (isTypeAny(instance)) { + return instance; + } + const propType = getTypeOfPropertyOfType(instance, forcedLookupLocation); + if (!propType) { + return; + } + results.push(propType); + } + return getIntersectionType(results); + } + const instanceType = getReturnTypeOfSignature(sig); + return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); + } + function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxOpeningFragment(context)) return getJSXFragmentType(context); + if (isJsxIntrinsicTagName(context.tagName)) { + const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + const fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + const tagType = checkExpressionCached(context.tagName); + if (tagType.flags & 128 /* StringLiteral */) { + const result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context); + if (!result) { + return errorType; + } + const fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + const managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + const ctorType = getStaticTypeOfReferencedJsxConstructor(context); + const result = instantiateAliasOrInterfaceWithDefaults(managedSym, isInJSFile(context), ctorType, attributesType); + if (result) { + return result; + } + } + return attributesType; + } + function getJsxPropsTypeFromClassType(sig, context) { + const ns = getJsxNamespaceAt(context); + const forcedLookupLocation = getJsxElementPropertiesName(ns); + let attributesType = forcedLookupLocation === void 0 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType) : forcedLookupLocation === "" ? getReturnTypeOfSignature(sig) : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + if (!attributesType) { + if (!!forcedLookupLocation && !!length(context.attributes.properties)) { + error(context, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(forcedLookupLocation)); + } + return unknownType; + } + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { + return attributesType; + } else { + let apparentAttributesType = attributesType; + const intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); + if (!isErrorType(intrinsicClassAttribs)) { + const typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + const hostClassType = getReturnTypeOfSignature(sig); + let libraryManagedAttributeType; + if (typeParams) { + const inferredArgs = fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context)); + libraryManagedAttributeType = instantiateType(intrinsicClassAttribs, createTypeMapper(typeParams, inferredArgs)); + } else libraryManagedAttributeType = intrinsicClassAttribs; + apparentAttributesType = intersectTypes(libraryManagedAttributeType, apparentAttributesType); + } + const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (!isErrorType(intrinsicAttribs)) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + function getIntersectedSignatures(signatures) { + return getStrictOptionValue(compilerOptions, "noImplicitAny") ? reduceLeft( + signatures, + (left, right) => left === right || !left ? left : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) : void 0 + ) : void 0; + } + function combineIntersectionThisParam(left, right, mapper) { + if (!left || !right) { + return left || right; + } + const thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]); + return createSymbolWithType(left, thisType); + } + function combineIntersectionParameters(left, right, mapper) { + const leftCount = getParameterCount(left); + const rightCount = getParameterCount(right); + const longest = leftCount >= rightCount ? left : right; + const shorter = longest === left ? right : left; + const longestCount = longest === left ? leftCount : rightCount; + const eitherHasEffectiveRest = hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right); + const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (let i = 0; i < longestCount; i++) { + let longestParamType = tryGetTypeAtPosition(longest, i); + if (longest === right) { + longestParamType = instantiateType(longestParamType, mapper); + } + let shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + if (shorter === right) { + shorterParamType = instantiateType(shorterParamType, mapper); + } + const unionParamType = getUnionType([longestParamType, shorterParamType]); + const isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === longestCount - 1; + const isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + const leftName = i >= leftCount ? void 0 : getParameterNameAtPosition(left, i); + const rightName = i >= rightCount ? void 0 : getParameterNameAtPosition(right, i); + const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0; + const paramSymbol = createSymbol( + 1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), + paramName || `arg${i}`, + isRestParam ? 32768 /* RestParameter */ : isOptional ? 16384 /* OptionalParameter */ : 0 + ); + paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + const restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args", 32768 /* RestParameter */); + restParamSymbol.links.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + if (shorter === right) { + restParamSymbol.links.type = instantiateType(restParamSymbol.links.type, mapper); + } + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfIntersectionMembers(left, right) { + const typeParams = left.typeParameters || right.typeParameters; + let paramMapper; + if (left.typeParameters && right.typeParameters) { + paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); + } + let flags = (left.flags | right.flags) & (167 /* PropagatingFlags */ & ~1 /* HasRestParameter */); + const declaration = left.declaration; + const params = combineIntersectionParameters(left, right, paramMapper); + const lastParam = lastOrUndefined(params); + if (lastParam && getCheckFlags(lastParam) & 32768 /* RestParameter */) { + flags |= 1 /* HasRestParameter */; + } + const thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); + const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + const result = createSignature( + declaration, + typeParams, + thisParam, + params, + /*resolvedReturnType*/ + void 0, + /*resolvedTypePredicate*/ + void 0, + minArgCount, + flags + ); + result.compositeKind = 2097152 /* Intersection */; + result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); + if (paramMapper) { + result.mapper = left.compositeKind === 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + } + return result; + } + function getContextualCallSignature(type, node) { + const signatures = getSignaturesOfType(type, 0 /* Call */); + const applicableByArity = filter(signatures, (s) => !isAritySmaller(s, node)); + return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity); + } + function isAritySmaller(signature, target) { + let targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + const param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + return isFunctionExpressionOrArrowFunction(node) || isObjectLiteralMethod(node) ? getContextualSignature(node) : void 0; + } + function getContextualSignature(node) { + Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node)); + const typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; + } + const type = getApparentTypeOfContextualType(node, 1 /* Signature */); + if (!type) { + return void 0; + } + if (!(type.flags & 1048576 /* Union */)) { + return getContextualCallSignature(type, node); + } + let signatureList; + const types = type.types; + for (const current of types) { + const signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + signatureList = [signature]; + } else if (!compareSignaturesIdentical( + signatureList[0], + signature, + /*partialMatch*/ + false, + /*ignoreThisTypes*/ + true, + /*ignoreReturnTypes*/ + true, + compareTypesIdentical + )) { + return void 0; + } else { + signatureList.push(signature); + } + } + } + if (signatureList) { + return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList); + } + } + function checkGrammarRegularExpressionLiteral(node) { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile) && !node.isUnterminated) { + let lastError; + scanner ?? (scanner = createScanner( + 99 /* ESNext */, + /*skipTrivia*/ + true + )); + scanner.setScriptTarget(sourceFile.languageVersion); + scanner.setLanguageVariant(sourceFile.languageVariant); + scanner.setOnError((message, length2, arg0) => { + const start = scanner.getTokenEnd(); + if (message.category === 3 /* Message */ && lastError && start === lastError.start && length2 === lastError.length) { + const error2 = createDetachedDiagnostic(sourceFile.fileName, sourceFile.text, start, length2, message, arg0); + addRelatedInfo(lastError, error2); + } else if (!lastError || start !== lastError.start) { + lastError = createFileDiagnostic(sourceFile, start, length2, message, arg0); + diagnostics.add(lastError); + } + }); + scanner.setText(sourceFile.text, node.pos, node.end - node.pos); + try { + scanner.scan(); + Debug.assert(scanner.reScanSlashToken( + /*reportErrors*/ + true + ) === 14 /* RegularExpressionLiteral */, "Expected scanner to rescan RegularExpressionLiteral"); + return !!lastError; + } finally { + scanner.setText(""); + scanner.setOnError( + /*onError*/ + void 0 + ); + } + } + return false; + } + function checkRegularExpressionLiteral(node) { + const nodeLinks2 = getNodeLinks(node); + if (!(nodeLinks2.flags & 1 /* TypeChecked */)) { + nodeLinks2.flags |= 1 /* TypeChecked */; + addLazyDiagnostic(() => checkGrammarRegularExpressionLiteral(node)); + } + return globalRegExpType; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) { + checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); + } + const arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression); + } + function checkSyntheticExpression(node) { + return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; + } + function hasDefaultValue(node) { + return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 303 /* PropertyAssignment */ && hasDefaultValue(node.initializer) || node.kind === 304 /* ShorthandPropertyAssignment */ && !!node.objectAssignmentInitializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */; + } + function isSpreadIntoCallOrNew(node) { + const parent = walkUpParenthesizedExpressions(node.parent); + return isSpreadElement(parent) && isCallOrNewExpression(parent.parent); + } + function checkArrayLiteral(node, checkMode, forceTuple) { + const elements = node.elements; + const elementCount = elements.length; + const elementTypes = []; + const elementFlags = []; + pushCachedContextualType(node); + const inDestructuringPattern = isAssignmentTarget(node); + const inConstContext = isConstContext(node); + const contextualType = getApparentTypeOfContextualType( + node, + /*contextFlags*/ + void 0 + ); + const inTupleContext = isSpreadIntoCallOrNew(node) || !!contextualType && someType(contextualType, (t) => isTupleLikeType(t) || isGenericMappedType(t) && !t.nameType && !!getHomomorphicTypeVariable(t.target || t)); + let hasOmittedExpression = false; + for (let i = 0; i < elementCount; i++) { + const e = elements[i]; + if (e.kind === 230 /* SpreadElement */) { + if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) { + checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); + } + const spreadType = checkExpression(e.expression, checkMode, forceTuple); + if (isArrayLikeType(spreadType)) { + elementTypes.push(spreadType); + elementFlags.push(8 /* Variadic */); + } else if (inDestructuringPattern) { + const restElementType = getIndexTypeOfType(spreadType, numberType) || getIteratedTypeOrElementType( + 65 /* Destructuring */, + spreadType, + undefinedType, + /*errorNode*/ + void 0, + /*checkAssignability*/ + false + ) || unknownType; + elementTypes.push(restElementType); + elementFlags.push(4 /* Rest */); + } else { + elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, e.expression)); + elementFlags.push(4 /* Rest */); + } + } else if (exactOptionalPropertyTypes && e.kind === 232 /* OmittedExpression */) { + hasOmittedExpression = true; + elementTypes.push(undefinedOrMissingType); + elementFlags.push(2 /* Optional */); + } else { + const type = checkExpressionForMutableLocation(e, checkMode, forceTuple); + elementTypes.push(addOptionality( + type, + /*isProperty*/ + true, + hasOmittedExpression + )); + elementFlags.push(hasOmittedExpression ? 2 /* Optional */ : 1 /* Required */); + if (inTupleContext && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(e)) { + const inferenceContext = getInferenceContext(node); + Debug.assert(inferenceContext); + addIntraExpressionInferenceSite(inferenceContext, e, type); + } + } + } + popContextualType(); + if (inDestructuringPattern) { + return createTupleType(elementTypes, elementFlags); + } + if (forceTuple || inConstContext || inTupleContext) { + return createArrayLiteralType(createTupleType( + elementTypes, + elementFlags, + /*readonly*/ + inConstContext && !(contextualType && someType(contextualType, isMutableArrayLikeType)) + )); + } + return createArrayLiteralType(createArrayType( + elementTypes.length ? getUnionType(sameMap(elementTypes, (t, i) => elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType, + inConstContext + )); + } + function createArrayLiteralType(type) { + if (!(getObjectFlags(type) & 4 /* Reference */)) { + return type; + } + let literalType = type.literalType; + if (!literalType) { + literalType = type.literalType = cloneTypeReference(type); + literalType.objectFlags |= 16384 /* ArrayLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; + } + return literalType; + } + function isNumericName(name) { + switch (name.kind) { + case 167 /* ComputedPropertyName */: + return isNumericComputedName(name); + case 80 /* Identifier */: + return isNumericLiteralName(name.escapedText); + case 9 /* NumericLiteral */: + case 11 /* StringLiteral */: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); + } + function checkComputedPropertyName(node) { + const links = getNodeLinks(node.expression); + if (!links.resolvedType) { + if ((isTypeLiteralNode(node.parent.parent) || isClassLike(node.parent.parent) || isInterfaceDeclaration(node.parent.parent)) && isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 103 /* InKeyword */ && node.parent.kind !== 177 /* GetAccessor */ && node.parent.kind !== 178 /* SetAccessor */) { + return links.resolvedType = errorType; + } + links.resolvedType = checkExpression(node.expression); + if (isPropertyDeclaration(node.parent) && !hasStaticModifier(node.parent) && isClassExpression(node.parent.parent)) { + const container = getEnclosingBlockScopeContainer(node.parent.parent); + const enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + getNodeLinks(enclosingIterationStatement).flags |= 4096 /* LoopWithCapturedBlockScopedBinding */; + getNodeLinks(node).flags |= 32768 /* BlockScopedBindingInLoop */; + getNodeLinks(node.parent.parent).flags |= 32768 /* BlockScopedBindingInLoop */; + } + } + if (links.resolvedType.flags & 98304 /* Nullable */ || !isTypeAssignableToKind(links.resolvedType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { + error(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + } + return links.resolvedType; + } + function isSymbolWithNumericName(symbol) { + var _a; + const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0]; + return isNumericLiteralName(symbol.escapedName) || firstDecl && isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name); + } + function isSymbolWithSymbolName(symbol) { + var _a; + const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0]; + return isKnownSymbol(symbol) || firstDecl && isNamedDeclaration(firstDecl) && isComputedPropertyName(firstDecl.name) && isTypeAssignableToKind(checkComputedPropertyName(firstDecl.name), 4096 /* ESSymbol */); + } + function isSymbolWithComputedName(symbol) { + var _a; + const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0]; + return firstDecl && isNamedDeclaration(firstDecl) && isComputedPropertyName(firstDecl.name); + } + function getObjectLiteralIndexInfo(isReadonly, offset, properties, keyType) { + var _a; + const propTypes = []; + let components; + for (let i = offset; i < properties.length; i++) { + const prop = properties[i]; + if (keyType === stringType && !isSymbolWithSymbolName(prop) || keyType === numberType && isSymbolWithNumericName(prop) || keyType === esSymbolType && isSymbolWithSymbolName(prop)) { + propTypes.push(getTypeOfSymbol(properties[i])); + if (isSymbolWithComputedName(properties[i])) { + components = append(components, (_a = properties[i].declarations) == null ? void 0 : _a[0]); + } + } + } + const unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; + return createIndexInfo( + keyType, + unionType, + isReadonly, + /*declaration*/ + void 0, + components + ); + } + function getImmediateAliasedSymbol(symbol) { + Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + const links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + const node = getDeclarationOfAliasSymbol(symbol); + if (!node) return Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration( + node, + /*dontRecursivelyResolve*/ + true + ); + } + return links.immediateTarget; + } + function checkObjectLiteral(node, checkMode = 0 /* Normal */) { + const inDestructuringPattern = isAssignmentTarget(node); + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + const allPropertiesTable = strictNullChecks ? createSymbolTable() : void 0; + let propertiesTable = createSymbolTable(); + let propertiesArray = []; + let spread = emptyObjectType; + pushCachedContextualType(node); + const contextualType = getApparentTypeOfContextualType( + node, + /*contextFlags*/ + void 0 + ); + const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 206 /* ObjectBindingPattern */ || contextualType.pattern.kind === 210 /* ObjectLiteralExpression */); + const inConstContext = isConstContext(node); + const checkFlags = inConstContext ? 8 /* Readonly */ : 0; + const isInJavascript = isInJSFile(node) && !isInJsonFile(node); + const enumTag = isInJavascript ? getJSDocEnumTag(node) : void 0; + const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; + let objectFlags = 8192 /* FreshLiteral */; + let patternWithComputedProperties = false; + let hasComputedStringProperty = false; + let hasComputedNumberProperty = false; + let hasComputedSymbolProperty = false; + for (const elem of node.properties) { + if (elem.name && isComputedPropertyName(elem.name)) { + checkComputedPropertyName(elem.name); + } + } + let offset = 0; + for (const memberDecl of node.properties) { + let member = getSymbolOfDeclaration(memberDecl); + const computedNameType = memberDecl.name && memberDecl.name.kind === 167 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : void 0; + if (memberDecl.kind === 303 /* PropertyAssignment */ || memberDecl.kind === 304 /* ShorthandPropertyAssignment */ || isObjectLiteralMethod(memberDecl)) { + let type = memberDecl.kind === 303 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : ( + // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring + // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. + // we don't want to say "could not find 'a'". + memberDecl.kind === 304 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode) + ); + if (isInJavascript) { + const jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); + if (jsDocType) { + checkTypeAssignableTo(type, jsDocType, memberDecl); + type = jsDocType; + } else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } + } + objectFlags |= getObjectFlags(type) & 458752 /* PropagatingFlags */; + const nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : void 0; + const prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags); + if (nameType) { + prop.links.nameType = nameType; + } + if (inDestructuringPattern && hasDefaultValue(memberDecl)) { + prop.flags |= 16777216 /* Optional */; + } else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + const impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216 /* Optional */; + } else if (!getIndexInfoOfType(contextualType, stringType)) { + error(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.links.type = type; + prop.links.target = member; + member = prop; + allPropertiesTable == null ? void 0 : allPropertiesTable.set(prop.escapedName, prop); + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 303 /* PropertyAssignment */ || memberDecl.kind === 174 /* MethodDeclaration */) && isContextSensitive(memberDecl)) { + const inferenceContext = getInferenceContext(node); + Debug.assert(inferenceContext); + const inferenceNode = memberDecl.kind === 303 /* PropertyAssignment */ ? memberDecl.initializer : memberDecl; + addIntraExpressionInferenceSite(inferenceContext, inferenceNode, type); + } + } else if (memberDecl.kind === 305 /* SpreadAssignment */) { + if (languageVersion < LanguageFeatureMinimumTarget.ObjectAssign) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); + propertiesArray = []; + propertiesTable = createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + hasComputedSymbolProperty = false; + } + const type = getReducedType(checkExpression(memberDecl.expression, checkMode & 2 /* Inferential */)); + if (isValidSpreadType(type)) { + const mergedType = tryMergeUnionOfObjectTypeAndEmptyObject(type, inConstContext); + if (allPropertiesTable) { + checkSpreadPropOverrides(mergedType, allPropertiesTable, memberDecl); + } + offset = propertiesArray.length; + if (isErrorType(spread)) { + continue; + } + spread = getSpreadType(spread, mergedType, node.symbol, objectFlags, inConstContext); + } else { + error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); + spread = errorType; + } + continue; + } else { + Debug.assert(memberDecl.kind === 177 /* GetAccessor */ || memberDecl.kind === 178 /* SetAccessor */); + checkNodeDeferred(memberDecl); + } + if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { + if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { + if (isTypeAssignableTo(computedNameType, numberType)) { + hasComputedNumberProperty = true; + } else if (isTypeAssignableTo(computedNameType, esSymbolType)) { + hasComputedSymbolProperty = true; + } else { + hasComputedStringProperty = true; + } + if (inDestructuringPattern) { + patternWithComputedProperties = true; + } + } + } else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + popContextualType(); + if (isErrorType(spread)) { + return errorType; + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); + propertiesArray = []; + propertiesTable = createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + } + return mapType(spread, (t) => t === emptyObjectType ? createObjectLiteralType() : t); + } + return createObjectLiteralType(); + function createObjectLiteralType() { + const indexInfos = []; + const isReadonly = isConstContext(node); + if (hasComputedStringProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, stringType)); + if (hasComputedNumberProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, numberType)); + if (hasComputedSymbolProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, esSymbolType)); + const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, indexInfos); + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; + if (isJSObjectLiteral) { + result.objectFlags |= 4096 /* JSLiteral */; + } + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + return result; + } + } + function isValidSpreadType(type) { + const t = removeDefinitelyFalsyTypes(mapType(type, getBaseConstraintOrType)); + return !!(t.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || t.flags & 3145728 /* UnionOrIntersection */ && every(t.types, isValidSpreadType)); + } + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + if (isJsxIntrinsicTagName(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } else { + checkExpression(node.closingElement.tagName); + } + checkJsxChildren(node); + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); + return getJsxElementTypeAt(node) || anyType; + } + function checkJsxFragment(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + const nodeSourceFile = getSourceFileOfNode(node); + if (getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx")) && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) { + error( + node, + compilerOptions.jsxFactory ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments + ); + } + checkJsxChildren(node); + const jsxElementType = getJsxElementTypeAt(node); + return isErrorType(jsxElementType) ? anyType : jsxElementType; + } + function isHyphenatedJsxName(name) { + return name.includes("-"); + } + function isJsxIntrinsicTagName(tagName) { + return isIdentifier(tagName) && isIntrinsicJsxName(tagName.escapedText) || isJsxNamespacedName(tagName); + } + function checkJsxAttribute(node, checkMode) { + return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) : trueType; + } + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode = 0 /* Normal */) { + const allAttributesTable = strictNullChecks ? createSymbolTable() : void 0; + let attributesTable = createSymbolTable(); + let spread = emptyJsxObjectType; + let hasSpreadAnyType = false; + let typeToIntersect; + let explicitlySpecifyChildrenAttribute = false; + let objectFlags = 2048 /* JsxAttributes */; + const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); + const isJsxOpenFragment = isJsxOpeningFragment(openingLikeElement); + let attributesSymbol; + let attributeParent = openingLikeElement; + if (!isJsxOpenFragment) { + const attributes = openingLikeElement.attributes; + attributesSymbol = attributes.symbol; + attributeParent = attributes; + const contextualType = getContextualType(attributes, 0 /* None */); + for (const attributeDecl of attributes.properties) { + const member = attributeDecl.symbol; + if (isJsxAttribute(attributeDecl)) { + const exprType = checkJsxAttribute(attributeDecl, checkMode); + objectFlags |= getObjectFlags(exprType) & 458752 /* PropagatingFlags */; + const attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.links.type = exprType; + attributeSymbol.links.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + allAttributesTable == null ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol); + if (getEscapedTextOfJsxAttributeName(attributeDecl.name) === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + if (contextualType) { + const prop = getPropertyOfType(contextualType, member.escapedName); + if (prop && prop.declarations && isDeprecatedSymbol(prop) && isIdentifier(attributeDecl.name)) { + addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); + } + } + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { + const inferenceContext = getInferenceContext(attributes); + Debug.assert(inferenceContext); + const inferenceNode = attributeDecl.initializer.expression; + addIntraExpressionInferenceSite(inferenceContext, inferenceNode, exprType); + } + } else { + Debug.assert(attributeDecl.kind === 293 /* JsxSpreadAttribute */); + if (attributesTable.size > 0) { + spread = getSpreadType( + spread, + createJsxAttributesTypeHelper(), + attributes.symbol, + objectFlags, + /*readonly*/ + false + ); + attributesTable = createSymbolTable(); + } + const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */)); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType( + spread, + exprType, + attributes.symbol, + objectFlags, + /*readonly*/ + false + ); + if (allAttributesTable) { + checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl); + } + } else { + error(attributeDecl.expression, Diagnostics.Spread_types_may_only_be_created_from_object_types); + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (attributesTable.size > 0) { + spread = getSpreadType( + spread, + createJsxAttributesTypeHelper(), + attributes.symbol, + objectFlags, + /*readonly*/ + false + ); + } + } + } + const parent = openingLikeElement.parent; + if ((isJsxElement(parent) && parent.openingElement === openingLikeElement || isJsxFragment(parent) && parent.openingFragment === openingLikeElement) && getSemanticJsxChildren(parent.children).length > 0) { + const childrenTypes = checkJsxChildren(parent, checkMode); + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { + error(attributeParent, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + const contextualType = isJsxOpeningElement(openingLikeElement) ? getApparentTypeOfContextualType( + openingLikeElement.attributes, + /*contextFlags*/ + void 0 + ) : void 0; + const childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); + const childrenPropSymbol = createSymbol(4 /* Property */, jsxChildrenPropertyName); + childrenPropSymbol.links.type = childrenTypes.length === 1 ? childrenTypes[0] : childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); + childrenPropSymbol.valueDeclaration = factory.createPropertySignature( + /*modifiers*/ + void 0, + unescapeLeadingUnderscores(jsxChildrenPropertyName), + /*questionToken*/ + void 0, + /*type*/ + void 0 + ); + setParent(childrenPropSymbol.valueDeclaration, attributeParent); + childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol; + const childPropMap = createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType( + spread, + createAnonymousType(attributesSymbol, childPropMap, emptyArray, emptyArray, emptyArray), + attributesSymbol, + objectFlags, + /*readonly*/ + false + ); + } + } + if (hasSpreadAnyType) { + return anyType; + } + if (typeToIntersect && spread !== emptyJsxObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesTypeHelper() : spread); + function createJsxAttributesTypeHelper() { + objectFlags |= 8192 /* FreshLiteral */; + return createJsxAttributesType(objectFlags, attributesSymbol, attributesTable); + } + } + function createJsxAttributesType(objectFlags, attributesSymbol, attributesTable) { + const result = createAnonymousType(attributesSymbol, attributesTable, emptyArray, emptyArray, emptyArray); + result.objectFlags |= objectFlags | 8192 /* FreshLiteral */ | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; + return result; + } + function checkJsxChildren(node, checkMode) { + const childrenTypes = []; + for (const child of node.children) { + if (child.kind === 12 /* JsxText */) { + if (!child.containsOnlyTriviaWhiteSpaces) { + childrenTypes.push(stringType); + } + } else if (child.kind === 294 /* JsxExpression */ && !child.expression) { + continue; + } else { + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); + } + } + return childrenTypes; + } + function checkSpreadPropOverrides(type, props, spread) { + for (const right of getPropertiesOfType(type)) { + if (!(right.flags & 16777216 /* Optional */)) { + const left = props.get(right.escapedName); + if (left) { + const diagnostic = error(left.valueDeclaration, Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, unescapeLeadingUnderscores(left.escapedName)); + addRelatedInfo(diagnostic, createDiagnosticForNode(spread, Diagnostics.This_spread_always_overwrites_this_property)); + } + } + } + } + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); + } + function getJsxType(name, location) { + const namespace = getJsxNamespaceAt(location); + const exports2 = namespace && getExportsOfSymbol(namespace); + const typeSymbol = exports2 && getSymbol(exports2, name, 788968 /* Type */); + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; + } + function getIntrinsicTagSymbol(node) { + const links = getNodeLinks(node); + if (!links.resolvedSymbol) { + const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); + if (!isErrorType(intrinsicElementsType)) { + if (!isIdentifier(node.tagName) && !isJsxNamespacedName(node.tagName)) return Debug.fail(); + const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText; + const intrinsicProp = getPropertyOfType(intrinsicElementsType, propName); + if (intrinsicProp) { + links.jsxFlags |= 1 /* IntrinsicNamedElement */; + return links.resolvedSymbol = intrinsicProp; + } + const indexSymbol = getApplicableIndexSymbol(intrinsicElementsType, getStringLiteralType(unescapeLeadingUnderscores(propName))); + if (indexSymbol) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = indexSymbol; + } + if (getTypeOfPropertyOrIndexSignatureOfType(intrinsicElementsType, propName)) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + error(node, Diagnostics.Property_0_does_not_exist_on_type_1, intrinsicTagNameToString(node.tagName), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } else { + if (noImplicitAny) { + error(node, Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxNamespaceContainerForImplicitImport(location) { + const file = location && getSourceFileOfNode(location); + const links = file && getNodeLinks(file); + if (links && links.jsxImplicitImportContainer === false) { + return void 0; + } + if (links && links.jsxImplicitImportContainer) { + return links.jsxImplicitImportContainer; + } + const runtimeImportSpecifier = getJSXRuntimeImport(getJSXImplicitImportBase(compilerOptions, file), compilerOptions); + if (!runtimeImportSpecifier) { + return void 0; + } + const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */; + const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_for_the_appropriate_package_installed; + const specifier = getJSXRuntimeImportSpecifier(file, runtimeImportSpecifier); + const mod = resolveExternalModule(specifier || location, runtimeImportSpecifier, errorMessage, location); + const result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : void 0; + if (links) { + links.jsxImplicitImportContainer = result || false; + } + return result; + } + function getJsxNamespaceAt(location) { + const links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + let resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location); + if (!resolvedNamespace || resolvedNamespace === unknownSymbol) { + const namespaceName = getJsxNamespace(location); + resolvedNamespace = resolveName( + location, + namespaceName, + 1920 /* Namespace */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + } + if (resolvedNamespace) { + const candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */)); + if (candidate && candidate !== unknownSymbol) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + } + if (links) { + links.jsxNamespace = false; + } + } + const s = resolveSymbol(getGlobalSymbol( + JsxNames.JSX, + 1920 /* Namespace */, + /*diagnostic*/ + void 0 + )); + if (s === unknownSymbol) { + return void 0; + } + return s; + } + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { + const jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */); + const jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + const propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) { + error(jsxElementAttribPropInterfaceSym.declarations[0], Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return void 0; + } + function getJsxLibraryManagedAttributes(jsxNamespace) { + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */); + } + function getJsxElementTypeSymbol(jsxNamespace) { + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementType, 788968 /* Type */); + } + function getJsxElementPropertiesName(jsxNamespace) { + return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); + } + function getJsxElementChildrenPropertyName(jsxNamespace) { + if (compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */) { + return "children"; + } + return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); + } + function getUninstantiatedJsxSignaturesOfType(elementType, caller) { + if (elementType.flags & 4 /* String */) { + return [anySignature]; + } else if (elementType.flags & 128 /* StringLiteral */) { + const intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller); + if (!intrinsicType) { + error(caller, Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements); + return emptyArray; + } else { + const fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType); + return [fakeSignature]; + } + } + const apparentElemType = getApparentType(elementType); + let signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */); + if (signatures.length === 0) { + signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); + } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { + signatures = getUnionSignatures(map(apparentElemType.types, (t) => getUninstantiatedJsxSignaturesOfType(t, caller))); + } + return signatures; + } + function getIntrinsicAttributesTypeFromStringLiteralType(type, location) { + const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (!isErrorType(intrinsicElementsType)) { + const stringLiteralTypeName = type.value; + const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, stringType); + if (indexSignatureType) { + return indexSignatureType; + } + return void 0; + } + return anyType; + } + function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) { + if (refKind === 1 /* Function */) { + const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + } else if (refKind === 0 /* Component */) { + const classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + } else { + const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + const classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { + return; + } + const combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + function generateInitialErrorChain() { + const componentName = getTextOfNode(openingLikeElement.tagName); + return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics._0_cannot_be_used_as_a_JSX_component, + componentName + ); + } + } + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + var _a; + Debug.assert(isJsxIntrinsicTagName(node.tagName)); + const links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + const symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType; + } else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText; + return links.resolvedJsxElementAttributesType = ((_a = getApplicableIndexInfoForName(getJsxType(JsxNames.IntrinsicElements, node), propName)) == null ? void 0 : _a.type) || errorType; + } else { + return links.resolvedJsxElementAttributesType = errorType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getJsxElementClassTypeAt(location) { + const type = getJsxType(JsxNames.ElementClass, location); + if (isErrorType(type)) return void 0; + return type; + } + function getJsxElementTypeAt(location) { + return getJsxType(JsxNames.Element, location); + } + function getJsxStatelessElementTypeAt(location) { + const jsxElementType = getJsxElementTypeAt(location); + if (jsxElementType) { + return getUnionType([jsxElementType, nullType]); + } + } + function getJsxElementTypeTypeAt(location) { + const ns = getJsxNamespaceAt(location); + if (!ns) return void 0; + const sym = getJsxElementTypeSymbol(ns); + if (!sym) return void 0; + const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location)); + if (!type || isErrorType(type)) return void 0; + return type; + } + function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) { + const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + if (managedSym.flags & 524288 /* TypeAlias */) { + const params = getSymbolLinks(managedSym).typeParameters; + if (length(params) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, params, typeArguments.length, inJs); + return length(args) === 0 ? declaredManagedType : getTypeAliasInstantiation(managedSym, args); + } + } + if (length(declaredManagedType.typeParameters) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, declaredManagedType.typeParameters, typeArguments.length, inJs); + return createTypeReference(declaredManagedType, args); + } + return void 0; + } + function getJsxIntrinsicTagNamesAt(location) { + const intrinsics = getJsxType(JsxNames.IntrinsicElements, location); + return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; + } + function checkJsxPreconditions(errorNode) { + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { + error(errorNode, Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxElementTypeAt(errorNode) === void 0) { + if (noImplicitAny) { + error(errorNode, Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElementOrOpeningFragment(node) { + const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node); + if (isNodeOpeningLikeElement) { + checkGrammarJsxElement(node); + } + checkJsxPreconditions(node); + markJsxAliasReferenced(node); + const sig = getResolvedSignature(node); + checkDeprecatedSignature(sig, node); + if (isNodeOpeningLikeElement) { + const jsxOpeningLikeNode = node; + const elementTypeConstraint = getJsxElementTypeTypeAt(jsxOpeningLikeNode); + if (elementTypeConstraint !== void 0) { + const tagName = jsxOpeningLikeNode.tagName; + const tagType = isJsxIntrinsicTagName(tagName) ? getStringLiteralType(intrinsicTagNameToString(tagName)) : checkExpression(tagName); + checkTypeRelatedTo(tagType, elementTypeConstraint, assignableRelation, tagName, Diagnostics.Its_type_0_is_not_a_valid_JSX_element_type, () => { + const componentName = getTextOfNode(tagName); + return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics._0_cannot_be_used_as_a_JSX_component, + componentName + ); + }); + } else { + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); + } + } + } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 524288 /* Object */) { + if (getPropertyOfObjectType(targetType, name) || getApplicableIndexInfoForName(targetType, name) || isLateBoundName(name) && getIndexInfoOfType(targetType, stringType) || isComparingJsxAttributes && isHyphenatedJsxName(name)) { + return true; + } + } + if (targetType.flags & 33554432 /* Substitution */) { + return isKnownProperty(targetType.baseType, name, isComparingJsxAttributes); + } + if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) { + for (const t of targetType.types) { + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } + function isExcessPropertyCheckTarget(type) { + return !!(type.flags & 524288 /* Object */ && !(getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) || type.flags & 67108864 /* NonPrimitive */ || type.flags & 33554432 /* Substitution */ && isExcessPropertyCheckTarget(type.baseType) || type.flags & 1048576 /* Union */ && some(type.types, isExcessPropertyCheckTarget) || type.flags & 2097152 /* Intersection */ && every(type.types, isExcessPropertyCheckTarget)); + } + function checkJsxExpression(node, checkMode) { + checkGrammarJsxExpression(node); + if (node.expression) { + const type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, Diagnostics.JSX_spread_child_must_be_an_array_type); + } + return type; + } else { + return errorType; + } + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? getCombinedNodeFlagsCached(s.valueDeclaration) : 0; + } + function isPrototypeProperty(symbol) { + if (symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */) { + return true; + } + if (isInJSFile(symbol.valueDeclaration)) { + const parent = symbol.valueDeclaration.parent; + return parent && isBinaryExpression(parent) && getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; + } + } + function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError = true) { + const errorNode = !reportError ? void 0 : node.kind === 166 /* QualifiedName */ ? node.right : node.kind === 205 /* ImportType */ ? node : node.kind === 208 /* BindingElement */ && node.propertyName ? node.propertyName : node.name; + return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode); + } + function checkPropertyAccessibilityAtLocation(location, isSuper, writing, containingType, prop, errorNode) { + var _a; + const flags = getDeclarationModifierFlagsFromSymbol(prop, writing); + if (isSuper) { + if (languageVersion < 2 /* ES2015 */) { + if (symbolHasNonMethodDeclaration(prop)) { + if (errorNode) { + error(errorNode, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } + return false; + } + } + if (flags & 64 /* Abstract */) { + if (errorNode) { + error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } + return false; + } + if (!(flags & 256 /* Static */) && ((_a = prop.declarations) == null ? void 0 : _a.some(isClassInstanceProperty))) { + if (errorNode) { + error(errorNode, Diagnostics.Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super, symbolToString(prop)); + } + return false; + } + } + if (flags & 64 /* Abstract */ && symbolHasNonMethodDeclaration(prop) && (isThisProperty(location) || isThisInitializedObjectBindingExpression(location) || isObjectBindingPattern(location.parent) && isThisInitializedDeclaration(location.parent.parent))) { + const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(location)) { + if (errorNode) { + error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + } + return false; + } + } + if (!(flags & 6 /* NonPublicAccessibilityModifier */)) { + return true; + } + if (flags & 2 /* Private */) { + const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(location, declaringClassDeclaration)) { + if (errorNode) { + error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } + return false; + } + return true; + } + if (isSuper) { + return true; + } + let enclosingClass = forEachEnclosingClass(location, (enclosingDeclaration) => { + const enclosingClass2 = getDeclaredTypeOfSymbol(getSymbolOfDeclaration(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass2, prop, writing); + }); + if (!enclosingClass) { + enclosingClass = getEnclosingClassFromThisParameter(location); + enclosingClass = enclosingClass && isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing); + if (flags & 256 /* Static */ || !enclosingClass) { + if (errorNode) { + error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || containingType)); + } + return false; + } + } + if (flags & 256 /* Static */) { + return true; + } + if (containingType.flags & 262144 /* TypeParameter */) { + containingType = containingType.isThisType ? getConstraintOfTypeParameter(containingType) : getBaseConstraintOfType(containingType); + } + if (!containingType || !hasBaseType(containingType, enclosingClass)) { + if (errorNode) { + error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(containingType)); + } + return false; + } + return true; + } + function getEnclosingClassFromThisParameter(node) { + const thisParameter = getThisParameterFromNodeContext(node); + let thisType = (thisParameter == null ? void 0 : thisParameter.type) && getTypeFromTypeNode(thisParameter.type); + if (thisType) { + if (thisType.flags & 262144 /* TypeParameter */) { + thisType = getConstraintOfTypeParameter(thisType); + } + } else { + const thisContainer = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (isFunctionLike(thisContainer)) { + thisType = getContextualThisParameterType(thisContainer); + } + } + if (thisType && getObjectFlags(thisType) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + return getTargetType(thisType); + } + return void 0; + } + function getThisParameterFromNodeContext(node) { + const thisContainer = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + return thisContainer && isFunctionLike(thisContainer) ? getThisParameter(thisContainer) : void 0; + } + function symbolHasNonMethodDeclaration(symbol) { + return !!forEachProperty(symbol, (prop) => !(prop.flags & 8192 /* Method */)); + } + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); + } + function isNullableType(type) { + return hasTypeFacts(type, 50331648 /* IsUndefinedOrNull */); + } + function getNonNullableTypeIfNeeded(type) { + return isNullableType(type) ? getNonNullableType(type) : type; + } + function reportObjectPossiblyNullOrUndefinedError(node, facts) { + const nodeText = isEntityNameExpression(node) ? entityNameToString(node) : void 0; + if (node.kind === 106 /* NullKeyword */) { + error(node, Diagnostics.The_value_0_cannot_be_used_here, "null"); + return; + } + if (nodeText !== void 0 && nodeText.length < 100) { + if (isIdentifier(node) && nodeText === "undefined") { + error(node, Diagnostics.The_value_0_cannot_be_used_here, "undefined"); + return; + } + error( + node, + facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics._0_is_possibly_null_or_undefined : Diagnostics._0_is_possibly_undefined : Diagnostics._0_is_possibly_null, + nodeText + ); + } else { + error( + node, + facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Object_is_possibly_null_or_undefined : Diagnostics.Object_is_possibly_undefined : Diagnostics.Object_is_possibly_null + ); + } + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { + error( + node, + facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_null + ); + } + function checkNonNullTypeWithReporter(type, node, reportError) { + if (strictNullChecks && type.flags & 2 /* Unknown */) { + if (isEntityNameExpression(node)) { + const nodeText = entityNameToString(node); + if (nodeText.length < 100) { + error(node, Diagnostics._0_is_of_type_unknown, nodeText); + return errorType; + } + } + error(node, Diagnostics.Object_is_of_type_unknown); + return errorType; + } + const facts = getTypeFacts(type, 50331648 /* IsUndefinedOrNull */); + if (facts & 50331648 /* IsUndefinedOrNull */) { + reportError(node, facts); + const t = getNonNullableType(type); + return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; + } + return type; + } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } + function checkNonNullNonVoidType(type, node) { + const nonNullType = checkNonNullType(type, node); + if (nonNullType.flags & 16384 /* Void */) { + if (isEntityNameExpression(node)) { + const nodeText = entityNameToString(node); + if (isIdentifier(node) && nodeText === "undefined") { + error(node, Diagnostics.The_value_0_cannot_be_used_here, nodeText); + return nonNullType; + } + if (nodeText.length < 100) { + error(node, Diagnostics._0_is_possibly_undefined, nodeText); + return nonNullType; + } + } + error(node, Diagnostics.Object_is_possibly_undefined); + } + return nonNullType; + } + function checkPropertyAccessExpression(node, checkMode, writeOnly) { + return node.flags & 64 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) : checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode, writeOnly); + } + function checkPropertyAccessChain(node, checkMode) { + const leftType = checkExpression(node.expression); + const nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType); + } + function checkQualifiedName(node, checkMode) { + const leftType = isPartOfTypeQuery(node) && isThisIdentifier(node.left) ? checkNonNullType(checkThisExpression(node.left), node.left) : checkNonNullExpression(node.left); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, leftType, node.right, checkMode); + } + function isMethodAccessForCall(node) { + while (node.parent.kind === 217 /* ParenthesizedExpression */) { + node = node.parent; + } + return isCallOrNewExpression(node.parent) && node.parent.expression === node; + } + function lookupSymbolForPrivateIdentifierDeclaration(propName, location) { + for (let containingClass = getContainingClassExcludingClassDecorators(location); !!containingClass; containingClass = getContainingClass(containingClass)) { + const { symbol } = containingClass; + const name = getSymbolNameForPrivateIdentifier(symbol, propName); + const prop = symbol.members && symbol.members.get(name) || symbol.exports && symbol.exports.get(name); + if (prop) { + return prop; + } + } + } + function checkGrammarPrivateIdentifierExpression(privId) { + if (!getContainingClass(privId)) { + return grammarErrorOnNode(privId, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + if (!isForInStatement(privId.parent)) { + if (!isExpressionNode(privId)) { + return grammarErrorOnNode(privId, Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression); + } + const isInOperation = isBinaryExpression(privId.parent) && privId.parent.operatorToken.kind === 103 /* InKeyword */; + if (!getSymbolForPrivateIdentifierExpression(privId) && !isInOperation) { + return grammarErrorOnNode(privId, Diagnostics.Cannot_find_name_0, idText(privId)); + } + } + return false; + } + function checkPrivateIdentifierExpression(privId) { + checkGrammarPrivateIdentifierExpression(privId); + const symbol = getSymbolForPrivateIdentifierExpression(privId); + if (symbol) { + markPropertyAsReferenced( + symbol, + /*nodeForCheckWriteOnly*/ + void 0, + /*isSelfTypeAccess*/ + false + ); + } + return anyType; + } + function getSymbolForPrivateIdentifierExpression(privId) { + if (!isExpressionNode(privId)) { + return void 0; + } + const links = getNodeLinks(privId); + if (links.resolvedSymbol === void 0) { + links.resolvedSymbol = lookupSymbolForPrivateIdentifierDeclaration(privId.escapedText, privId); + } + return links.resolvedSymbol; + } + function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) { + return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName); + } + function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) { + let propertyOnType; + const properties = getPropertiesOfType(leftType); + if (properties) { + forEach(properties, (symbol) => { + const decl = symbol.valueDeclaration; + if (decl && isNamedDeclaration(decl) && isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) { + propertyOnType = symbol; + return true; + } + }); + } + const diagName = diagnosticName(right); + if (propertyOnType) { + const typeValueDecl = Debug.checkDefined(propertyOnType.valueDeclaration); + const typeClass = Debug.checkDefined(getContainingClass(typeValueDecl)); + if (lexicallyScopedIdentifier == null ? void 0 : lexicallyScopedIdentifier.valueDeclaration) { + const lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration; + const lexicalClass = getContainingClass(lexicalValueDecl); + Debug.assert(!!lexicalClass); + if (findAncestor(lexicalClass, (n) => typeClass === n)) { + const diagnostic = error( + right, + Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling, + diagName, + typeToString(leftType) + ); + addRelatedInfo( + diagnostic, + createDiagnosticForNode( + lexicalValueDecl, + Diagnostics.The_shadowing_declaration_of_0_is_defined_here, + diagName + ), + createDiagnosticForNode( + typeValueDecl, + Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here, + diagName + ) + ); + return true; + } + } + error( + right, + Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, + diagName, + diagnosticName(typeClass.name || anon) + ); + return true; + } + return false; + } + function isThisPropertyAccessInConstructor(node, prop) { + return (isConstructorDeclaredProperty(prop) || isThisProperty(node) && isAutoTypedProperty(prop)) && getThisContainer( + node, + /*includeArrowFunctions*/ + true, + /*includeClassComputedPropertyName*/ + false + ) === getDeclaringConstructor(prop); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode, writeOnly) { + const parentSymbol = getNodeLinks(left).resolvedSymbol; + const assignmentKind = getAssignmentTargetKind(node); + const apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); + const isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType; + let prop; + if (isPrivateIdentifier(right)) { + if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) { + if (assignmentKind !== 0 /* None */) { + checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */); + } + if (assignmentKind !== 1 /* Definite */) { + checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); + } + } + const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { + grammarErrorOnNode(right, Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, idText(right)); + } + if (isAnyLike) { + if (lexicallyScopedSymbol) { + return isErrorType(apparentType) ? errorType : apparentType; + } + if (getContainingClassExcludingClassDecorators(right) === void 0) { + grammarErrorOnNode(right, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + return anyType; + } + } + prop = lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol); + if (prop === void 0) { + if (checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) { + return errorType; + } + const containingClass = getContainingClassExcludingClassDecorators(right); + if (containingClass && isPlainJsFile(getSourceFileOfNode(containingClass), compilerOptions.checkJs)) { + grammarErrorOnNode(right, Diagnostics.Private_field_0_must_be_declared_in_an_enclosing_class, idText(right)); + } + } else { + const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */) { + error(node, Diagnostics.Private_accessor_was_defined_without_a_getter); + } + } + } else { + if (isAnyLike) { + if (isIdentifier(left) && parentSymbol) { + markLinkedReferences( + node, + 2 /* Property */, + /*propSymbol*/ + void 0, + leftType + ); + } + return isErrorType(apparentType) ? errorType : apparentType; + } + prop = getPropertyOfType( + apparentType, + right.escapedText, + /*skipObjectFunctionPropertyAugment*/ + isConstEnumObjectType(apparentType), + /*includeTypeOnlyMembers*/ + node.kind === 166 /* QualifiedName */ + ); + } + markLinkedReferences(node, 2 /* Property */, prop, leftType); + let propType; + if (!prop) { + const indexInfo = !isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getApplicableIndexInfoForName(apparentType, right.escapedText) : void 0; + if (!(indexInfo && indexInfo.type)) { + const isUncheckedJS = isUncheckedJSSuggestion( + node, + leftType.symbol, + /*excludeClasses*/ + true + ); + if (!isUncheckedJS && isJSLiteralType(leftType)) { + return anyType; + } + if (leftType.symbol === globalThisSymbol) { + if (globalThisSymbol.exports.has(right.escapedText) && globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */) { + error(right, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); + } else if (noImplicitAny) { + error(right, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); + } + return anyType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS); + } + return errorType; + } + if (indexInfo.isReadonly && (isAssignmentTarget(node) || isDeleteTarget(node))) { + error(node, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); + } + propType = indexInfo.type; + if (compilerOptions.noUncheckedIndexedAccess && getAssignmentTargetKind(node) !== 1 /* Definite */) { + propType = getUnionType([propType, missingType]); + } + if (compilerOptions.noPropertyAccessFromIndexSignature && isPropertyAccessExpression(node)) { + error(right, Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, unescapeLeadingUnderscores(right.escapedText)); + } + if (indexInfo.declaration && isDeprecatedDeclaration(indexInfo.declaration)) { + addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText); + } + } else { + const targetPropSymbol = resolveAliasWithDeprecationCheck(prop, right); + if (isDeprecatedSymbol(targetPropSymbol) && isUncalledFunctionReference(node, targetPropSymbol) && targetPropSymbol.declarations) { + addDeprecatedSuggestion(right, targetPropSymbol.declarations, right.escapedText); + } + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left.kind === 108 /* SuperKeyword */, isWriteAccess(node), apparentType, prop); + if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) { + error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, idText(right)); + return errorType; + } + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writeOnly || isWriteOnlyAccess(node) ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop); + } + return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); + } + function isUncheckedJSSuggestion(node, suggestion, excludeClasses) { + var _a; + const file = getSourceFileOfNode(node); + if (file) { + if (compilerOptions.checkJs === void 0 && file.checkJsDirective === void 0 && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */)) { + const declarationFile = forEach(suggestion == null ? void 0 : suggestion.declarations, getSourceFileOfNode); + const suggestionHasNoExtendsOrDecorators = !(suggestion == null ? void 0 : suggestion.valueDeclaration) || !isClassLike(suggestion.valueDeclaration) || ((_a = suggestion.valueDeclaration.heritageClauses) == null ? void 0 : _a.length) || classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ + false, + suggestion.valueDeclaration + ); + return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile)) && !(excludeClasses && suggestion && suggestion.flags & 32 /* Class */ && suggestionHasNoExtendsOrDecorators) && !(!!node && excludeClasses && isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && suggestionHasNoExtendsOrDecorators); + } + } + return false; + } + function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) { + const assignmentKind = getAssignmentTargetKind(node); + if (assignmentKind === 1 /* Definite */) { + return removeMissingType(propType, !!(prop && prop.flags & 16777216 /* Optional */)); + } + if (prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) && !isDuplicatedCommonJSExport(prop.declarations)) { + return propType; + } + if (propType === autoType) { + return getFlowTypeOfProperty(node, prop); + } + propType = getNarrowableTypeForReference(propType, node, checkMode); + let assumeUninitialized = false; + if (strictNullChecks && strictPropertyInitialization && isAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */) { + const declaration = prop && prop.valueDeclaration; + if (declaration && isPropertyWithoutInitializer(declaration)) { + if (!isStatic(declaration)) { + const flowContainer = getControlFlowContainer(node); + if (flowContainer.kind === 176 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 33554432 /* Ambient */)) { + assumeUninitialized = true; + } + } + } + } else if (strictNullChecks && prop && prop.valueDeclaration && isPropertyAccessExpression(prop.valueDeclaration) && getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } + const flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); + if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) { + error(errorNode, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + return propType; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + const { valueDeclaration } = prop; + if (!valueDeclaration || getSourceFileOfNode(node).isDeclarationFile) { + return; + } + let diagnosticMessage; + const declarationName = idText(right); + if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 256 /* Static */) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { + diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + } else if (valueDeclaration.kind === 263 /* ClassDeclaration */ && node.parent.kind !== 183 /* TypeReference */ && !(valueDeclaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + diagnosticMessage = error(right, Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, createDiagnosticForNode(valueDeclaration, Diagnostics._0_is_declared_here, declarationName)); + } + } + function isInPropertyInitializerOrClassStaticBlock(node) { + return !!findAncestor(node, (node2) => { + switch (node2.kind) { + case 172 /* PropertyDeclaration */: + return true; + case 303 /* PropertyAssignment */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 305 /* SpreadAssignment */: + case 167 /* ComputedPropertyName */: + case 239 /* TemplateSpan */: + case 294 /* JsxExpression */: + case 291 /* JsxAttribute */: + case 292 /* JsxAttributes */: + case 293 /* JsxSpreadAttribute */: + case 286 /* JsxOpeningElement */: + case 233 /* ExpressionWithTypeArguments */: + case 298 /* HeritageClause */: + return false; + case 219 /* ArrowFunction */: + case 244 /* ExpressionStatement */: + return isBlock(node2.parent) && isClassStaticBlockDeclaration(node2.parent.parent) ? true : "quit"; + default: + return isExpressionNode(node2) ? false : "quit"; + } + }); + } + function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32 /* Class */)) { + return false; + } + let classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = classType.symbol && getSuperClass(classType); + if (!classType) { + return false; + } + const superProperty = getPropertyOfType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + const x = getBaseTypes(classType); + if (x.length === 0) { + return void 0; + } + return getIntersectionType(x); + } + function reportNonexistentProperty(propNode, containingType, isUncheckedJS) { + const links = getNodeLinks(propNode); + const cache = links.nonExistentPropCheckCache || (links.nonExistentPropCheckCache = /* @__PURE__ */ new Set()); + const key = `${getTypeId(containingType)}|${isUncheckedJS}`; + if (cache.has(key)) { + return; + } + cache.add(key); + let errorInfo; + let relatedInfo; + if (!isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 402784252 /* Primitive */)) { + for (const subtype of containingType.types) { + if (!getPropertyOfType(subtype, propNode.escapedText) && !getApplicableIndexInfoForName(subtype, propNode.escapedText)) { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + const propName = declarationNameToString(propNode); + const typeName = typeToString(containingType); + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "." + propName); + } else { + const promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType)); + relatedInfo = createDiagnosticForNode(propNode, Diagnostics.Did_you_forget_to_use_await); + } else { + const missingProperty = declarationNameToString(propNode); + const container = typeToString(containingType); + const libSuggestion = getSuggestedLibForNonExistentProperty(missingProperty, containingType); + if (libSuggestion !== void 0) { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later, missingProperty, container, libSuggestion); + } else { + const suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== void 0) { + const suggestedName = symbolName(suggestion); + const message = isUncheckedJS ? Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2 : Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2; + errorInfo = chainDiagnosticMessages(errorInfo, message, missingProperty, container, suggestedName); + relatedInfo = suggestion.valueDeclaration && createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestedName); + } else { + const diagnostic = containerSeemsToBeEmptyDomElement(containingType) ? Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom : Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); + } + } + } + } + const resultDiagnostic = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(propNode), propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic); + } + function containerSeemsToBeEmptyDomElement(containingType) { + return compilerOptions.lib && !compilerOptions.lib.includes("dom") && everyContainedType(containingType, (type) => type.symbol && /^(?:EventTarget|Node|(?:HTML[a-zA-Z]*)?Element)$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && isEmptyObjectType(containingType); + } + function typeHasStaticProperty(propName, containingType) { + const prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== void 0 && !!prop.valueDeclaration && isStatic(prop.valueDeclaration); + } + function getSuggestedLibForNonExistentName(name) { + const missingName = diagnosticName(name); + const allFeatures = getScriptTargetFeatures(); + const typeFeatures = allFeatures.get(missingName); + return typeFeatures && firstIterator(typeFeatures.keys()); + } + function getSuggestedLibForNonExistentProperty(missingProperty, containingType) { + const container = getApparentType(containingType).symbol; + if (!container) { + return void 0; + } + const containingTypeName = symbolName(container); + const allFeatures = getScriptTargetFeatures(); + const typeFeatures = allFeatures.get(containingTypeName); + if (typeFeatures) { + for (const [libTarget, featuresOfType] of typeFeatures) { + if (contains(featuresOfType, missingProperty)) { + return libTarget; + } + } + } + } + function getSuggestedSymbolForNonexistentClassMember(name, baseType) { + return getSpellingSuggestionForName(name, getPropertiesOfType(baseType), 106500 /* ClassMember */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + let props = getPropertiesOfType(containingType); + if (typeof name !== "string") { + const parent = name.parent; + if (isPropertyAccessExpression(parent)) { + props = filter(props, (prop) => isValidPropertyAccessForCompletions(parent, containingType, prop)); + } + name = idText(name); + } + return getSpellingSuggestionForName(name, props, 111551 /* Value */); + } + function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) { + const strName = isString(name) ? name : idText(name); + const properties = getPropertiesOfType(containingType); + const jsxSpecific = strName === "for" ? find(properties, (x) => symbolName(x) === "htmlFor") : strName === "class" ? find(properties, (x) => symbolName(x) === "className") : void 0; + return jsxSpecific ?? getSpellingSuggestionForName(strName, properties, 111551 /* Value */); + } + function getSuggestionForNonexistentProperty(name, containingType) { + const suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); + return suggestion && symbolName(suggestion); + } + function getSuggestionForSymbolNameLookup(symbols, name, meaning) { + const symbol = getSymbol(symbols, name, meaning); + if (symbol) return symbol; + let candidates; + if (symbols === globals) { + const primitives = mapDefined( + ["string", "number", "boolean", "object", "bigint", "symbol"], + (s) => symbols.has(s.charAt(0).toUpperCase() + s.slice(1)) ? createSymbol(524288 /* TypeAlias */, s) : void 0 + ); + candidates = primitives.concat(arrayFrom(symbols.values())); + } else { + candidates = arrayFrom(symbols.values()); + } + return getSpellingSuggestionForName(unescapeLeadingUnderscores(name), candidates, meaning); + } + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { + Debug.assert(outerName !== void 0, "outername should always be defined"); + const result = resolveNameForSymbolSuggestion( + location, + outerName, + meaning, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false, + /*excludeGlobals*/ + false + ); + return result; + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) { + function hasProp(name) { + const prop = getPropertyOfObjectType(objectType, name); + if (prop) { + const s = getSingleCallSignature(getTypeOfSymbol(prop)); + return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0)); + } + return false; + } + const suggestedMethod = isAssignmentTarget(expr) ? "set" : "get"; + if (!hasProp(suggestedMethod)) { + return void 0; + } + let suggestion = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (suggestion === void 0) { + suggestion = suggestedMethod; + } else { + suggestion += "." + suggestedMethod; + } + return suggestion; + } + function getSuggestedTypeForNonexistentStringLiteralType(source, target) { + const candidates = target.types.filter((type) => !!(type.flags & 128 /* StringLiteral */)); + return getSpellingSuggestion(source.value, candidates, (type) => type.value); + } + function getSpellingSuggestionForName(name, symbols, meaning) { + return getSpellingSuggestion(name, symbols, getCandidateName); + function getCandidateName(candidate) { + const candidateName = symbolName(candidate); + if (startsWith(candidateName, '"')) { + return void 0; + } + if (candidate.flags & meaning) { + return candidateName; + } + if (candidate.flags & 2097152 /* Alias */) { + const alias = tryResolveAlias(candidate); + if (alias && alias.flags & meaning) { + return candidateName; + } + } + return void 0; + } + } + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess2) { + const valueDeclaration = prop && prop.flags & 106500 /* ClassMember */ && prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + const hasPrivateModifier = hasEffectiveModifier(valueDeclaration, 2 /* Private */); + const hasPrivateIdentifier = prop.valueDeclaration && isNamedDeclaration(prop.valueDeclaration) && isPrivateIdentifier(prop.valueDeclaration.name); + if (!hasPrivateModifier && !hasPrivateIdentifier) { + return; + } + if (nodeForCheckWriteOnly && isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) { + return; + } + if (isSelfTypeAccess2) { + const containingMethod = findAncestor(nodeForCheckWriteOnly, isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } + (getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = -1 /* All */; + } + function isSelfTypeAccess(name, parent) { + return name.kind === 110 /* ThisKeyword */ || !!parent && isEntityNameExpression(name) && parent === getResolvedSymbol(getFirstIdentifier(name)); + } + function isValidPropertyAccess(node, propertyName) { + switch (node.kind) { + case 211 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 108 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); + case 166 /* QualifiedName */: + return isValidPropertyAccessWithType( + node, + /*isSuper*/ + false, + propertyName, + getWidenedType(checkExpression(node.left)) + ); + case 205 /* ImportType */: + return isValidPropertyAccessWithType( + node, + /*isSuper*/ + false, + propertyName, + getTypeFromTypeNode(node) + ); + } + } + function isValidPropertyAccessForCompletions(node, type, property) { + return isPropertyAccessible( + node, + node.kind === 211 /* PropertyAccessExpression */ && node.expression.kind === 108 /* SuperKeyword */, + /*isWrite*/ + false, + type, + property + ); + } + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { + if (isTypeAny(type)) { + return true; + } + const prop = getPropertyOfType(type, propertyName); + return !!prop && isPropertyAccessible( + node, + isSuper, + /*isWrite*/ + false, + type, + prop + ); + } + function isPropertyAccessible(node, isSuper, isWrite, containingType, property) { + if (isTypeAny(containingType)) { + return true; + } + if (property.valueDeclaration && isPrivateIdentifierClassElementDeclaration(property.valueDeclaration)) { + const declClass = getContainingClass(property.valueDeclaration); + return !isOptionalChain(node) && !!findAncestor(node, (parent) => parent === declClass); + } + return checkPropertyAccessibilityAtLocation(node, isSuper, isWrite, containingType, property); + } + function getForInVariableSymbol(node) { + const initializer = node.initializer; + if (initializer.kind === 261 /* VariableDeclarationList */) { + const variable = initializer.declarations[0]; + if (variable && !isBindingPattern(variable.name)) { + return getSymbolOfDeclaration(variable); + } + } else if (initializer.kind === 80 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return void 0; + } + function hasNumericPropertyNames(type) { + return getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, numberType); + } + function isForInVariableForNumericPropertyNames(expr) { + const e = skipParentheses(expr); + if (e.kind === 80 /* Identifier */) { + const symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + let child = expr; + let node = expr.parent; + while (node) { + if (node.kind === 249 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node, checkMode) { + return node.flags & 64 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) : checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); + } + function checkElementAccessChain(node, checkMode) { + const exprType = checkExpression(node.expression); + const nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType, checkMode) { + const objectType = getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; + const indexExpression = node.argumentExpression; + const indexType = checkExpression(indexExpression); + if (isErrorType(objectType) || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && !isStringLiteralLike(indexExpression)) { + error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return errorType; + } + const effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType; + const assignmentTargetKind = getAssignmentTargetKind(node); + let accessFlags; + if (assignmentTargetKind === 0 /* None */) { + accessFlags = 32 /* ExpressionPosition */; + } else { + accessFlags = 4 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 2 /* NoIndexSignatures */ : 0); + if (assignmentTargetKind === 2 /* Compound */) { + accessFlags |= 32 /* ExpressionPosition */; + } + } + const indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, accessFlags, node) || errorType; + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); + } + function callLikeExpressionMayHaveTypeArguments(node) { + return isCallOrNewExpression(node) || isTaggedTemplateExpression(node) || isJsxOpeningLikeElement(node); + } + function resolveUntypedCall(node) { + if (callLikeExpressionMayHaveTypeArguments(node)) { + forEach(node.typeArguments, checkSourceElement); + } + if (node.kind === 215 /* TaggedTemplateExpression */) { + checkExpression(node.template); + } else if (isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } else if (isBinaryExpression(node)) { + checkExpression(node.left); + } else if (isCallOrNewExpression(node)) { + forEach(node.arguments, (argument) => { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + function reorderCandidates(signatures, result, callChainFlags) { + let lastParent; + let lastSymbol; + let cutoffIndex = 0; + let index; + let specializedIndex = -1; + let spliceIndex; + Debug.assert(!result.length); + for (const signature of signatures) { + const symbol = signature.declaration && getSymbolOfDeclaration(signature.declaration); + const parent = signature.declaration && signature.declaration.parent; + if (!lastSymbol || symbol === lastSymbol) { + if (lastParent && parent === lastParent) { + index = index + 1; + } else { + lastParent = parent; + index = cutoffIndex; + } + } else { + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + if (signatureHasLiteralTypes(signature)) { + specializedIndex++; + spliceIndex = specializedIndex; + cutoffIndex++; + } else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature); + } + } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 230 /* SpreadElement */ || arg.kind === 237 /* SyntheticExpression */ && arg.isSpread); + } + function getSpreadArgumentIndex(args) { + return findIndex(args, isSpreadArgument); + } + function acceptsVoid(t) { + return !!(t.flags & 16384 /* Void */); + } + function acceptsVoidUndefinedUnknownOrAny(t) { + return !!(t.flags & (16384 /* Void */ | 32768 /* Undefined */ | 2 /* Unknown */ | 1 /* Any */)); + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma = false) { + if (isJsxOpeningFragment(node)) return true; + let argCount; + let callIsIncomplete = false; + let effectiveParameterCount = getParameterCount(signature); + let effectiveMinimumArguments = getMinArgumentCount(signature); + if (node.kind === 215 /* TaggedTemplateExpression */) { + argCount = args.length; + if (node.template.kind === 228 /* TemplateExpression */) { + const lastSpan = last(node.template.templateSpans); + callIsIncomplete = nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } else { + const templateLiteral = node.template; + Debug.assert(templateLiteral.kind === 15 /* NoSubstitutionTemplateLiteral */); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } else if (node.kind === 170 /* Decorator */) { + argCount = getDecoratorArgumentCount(node, signature); + } else if (node.kind === 226 /* BinaryExpression */) { + argCount = 1; + } else if (isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); + } else if (!node.arguments) { + Debug.assert(node.kind === 214 /* NewExpression */); + return getMinArgumentCount(signature) === 0; + } else { + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + callIsIncomplete = node.arguments.end === node.end; + const spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } + } + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { + return false; + } + if (callIsIncomplete || argCount >= effectiveMinimumArguments) { + return true; + } + for (let i = argCount; i < effectiveMinimumArguments; i++) { + const type = getTypeAtPosition(signature, i); + if (filterType(type, isInJSFile(node) && !strictNullChecks ? acceptsVoidUndefinedUnknownOrAny : acceptsVoid).flags & 131072 /* Never */) { + return false; + } + } + return true; + } + function hasCorrectTypeArgumentArity(signature, typeArguments) { + const numTypeParameters = length(signature.typeParameters); + const minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + return !some(typeArguments) || typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters; + } + function isInstantiatedGenericParameter(signature, pos) { + let type; + return !!(signature.target && (type = tryGetTypeAtPosition(signature.target, pos)) && isGenericType(type)); + } + function getSingleCallSignature(type) { + return getSingleSignature( + type, + 0 /* Call */, + /*allowMembers*/ + false + ); + } + function getSingleCallOrConstructSignature(type) { + return getSingleSignature( + type, + 0 /* Call */, + /*allowMembers*/ + false + ) || getSingleSignature( + type, + 1 /* Construct */, + /*allowMembers*/ + false + ); + } + function getSingleSignature(type, kind, allowMembers) { + if (type.flags & 524288 /* Object */) { + const resolved = resolveStructuredTypeMembers(type); + if (allowMembers || resolved.properties.length === 0 && resolved.indexInfos.length === 0) { + if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) { + return resolved.callSignatures[0]; + } + if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) { + return resolved.constructSignatures[0]; + } + } + } + return void 0; + } + function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) { + const context = createInferenceContext(getTypeParametersForMapper(signature), signature, 0 /* None */, compareTypes); + const restType = getEffectiveRestType(contextualSignature); + const mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper); + const sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature; + applyToParameterTypes(sourceSignature, signature, (source, target) => { + inferTypes(context.inferences, source, target); + }); + if (!inferenceContext) { + applyToReturnTypes(contextualSignature, signature, (source, target) => { + inferTypes(context.inferences, source, target, 128 /* ReturnType */); + }); + } + return getSignatureInstantiation(signature, getInferredTypes(context), isInJSFile(contextualSignature.declaration)); + } + function inferJsxTypeArguments(node, signature, checkMode, context) { + const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + const checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode); + inferTypes(context.inferences, checkAttrType, paramType); + return getInferredTypes(context); + } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + const thisArgumentType = checkExpression(thisArgumentNode); + return isRightSideOfInstanceofExpression(thisArgumentNode) ? thisArgumentType : isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : thisArgumentType; + } + function inferTypeArguments(node, signature, args, checkMode, context) { + if (isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, checkMode, context); + } + if (node.kind !== 170 /* Decorator */ && node.kind !== 226 /* BinaryExpression */) { + const skipBindingPatterns = every(signature.typeParameters, (p) => !!getDefaultFromTypeParameter(p)); + const contextualType = getContextualType(node, skipBindingPatterns ? 8 /* SkipBindingPatterns */ : 0 /* None */); + if (contextualType) { + const inferenceTargetType = getReturnTypeOfSignature(signature); + if (couldContainTypeVariables(inferenceTargetType)) { + const outerContext = getInferenceContext(node); + const isFromBindingPattern = !skipBindingPatterns && getContextualType(node, 8 /* SkipBindingPatterns */) !== contextualType; + if (!isFromBindingPattern) { + const outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */)); + const instantiatedType = instantiateType(contextualType, outerMapper); + const contextualSignature = getSingleCallSignature(instantiatedType); + const inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType; + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* ReturnType */); + } + const returnContext = createInferenceContext(signature.typeParameters, signature, context.flags); + const returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper); + inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType); + context.returnMapper = some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : void 0; + } + } + } + const restType = getNonArrayRestType(signature); + const argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + if (restType && restType.flags & 262144 /* TypeParameter */) { + const info = find(context.inferences, (info2) => info2.typeParameter === restType); + if (info) { + info.impliedArity = findIndex(args, isSpreadArgument, argCount) < 0 ? args.length - argCount : void 0; + } + } + const thisType = getThisTypeOfSignature(signature); + if (thisType && couldContainTypeVariables(thisType)) { + const thisArgumentNode = getThisArgumentOfCall(node); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); + } + for (let i = 0; i < argCount; i++) { + const arg = args[i]; + if (arg.kind !== 232 /* OmittedExpression */) { + const paramType = getTypeAtPosition(signature, i); + if (couldContainTypeVariables(paramType)) { + const argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); + inferTypes(context.inferences, argType, paramType); + } + } + } + if (restType && couldContainTypeVariables(restType)) { + const spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context, checkMode); + inferTypes(context.inferences, spreadType, restType); + } + return getInferredTypes(context); + } + function getMutableArrayOrTupleType(type) { + return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType( + getElementTypes(type), + type.target.elementFlags, + /*readonly*/ + false, + type.target.labeledElementDeclarations + ) : createTupleType([type], [8 /* Variadic */]); + } + function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) { + const inConstContext = isConstTypeVariable(restType); + if (index >= argCount - 1) { + const arg = args[argCount - 1]; + if (isSpreadArgument(arg)) { + const spreadType = arg.kind === 237 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode); + if (isArrayLikeType(spreadType)) { + return getMutableArrayOrTupleType(spreadType); + } + return createArrayType(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 230 /* SpreadElement */ ? arg.expression : arg), inConstContext); + } + } + const types = []; + const flags = []; + const names = []; + for (let i = index; i < argCount; i++) { + const arg = args[i]; + if (isSpreadArgument(arg)) { + const spreadType = arg.kind === 237 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); + if (isArrayLikeType(spreadType)) { + types.push(spreadType); + flags.push(8 /* Variadic */); + } else { + types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 230 /* SpreadElement */ ? arg.expression : arg)); + flags.push(4 /* Rest */); + } + } else { + const contextualType = isTupleType(restType) ? getContextualTypeForElementExpression(restType, i - index, argCount - index) || unknownType : getIndexedAccessType(restType, getNumberLiteralType(i - index), 256 /* Contextual */); + const argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode); + const hasPrimitiveContextualType = inConstContext || maybeTypeOfKind(contextualType, 402784252 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */); + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + flags.push(1 /* Required */); + } + if (arg.kind === 237 /* SyntheticExpression */ && arg.tupleNameSource) { + names.push(arg.tupleNameSource); + } else { + names.push(void 0); + } + } + return createTupleType(types, flags, inConstContext && !someType(restType, isMutableArrayLikeType), names); + } + function checkTypeArguments(signature, typeArgumentNodes, reportErrors2, headMessage) { + const isJavascript = isInJSFile(signature.declaration); + const typeParameters = signature.typeParameters; + const typeArgumentTypes = fillMissingTypeArguments(map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); + let mapper; + for (let i = 0; i < typeArgumentNodes.length; i++) { + Debug.assert(typeParameters[i] !== void 0, "Should not call checkTypeArguments with too many type arguments"); + const constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + const errorInfo = reportErrors2 && headMessage ? () => chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Type_0_does_not_satisfy_the_constraint_1 + ) : void 0; + const typeArgumentHeadMessage = headMessage || Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + const typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo( + typeArgument, + getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), + reportErrors2 ? typeArgumentNodes[i] : void 0, + typeArgumentHeadMessage, + errorInfo + )) { + return void 0; + } + } + } + return typeArgumentTypes; + } + function getJsxReferenceKind(node) { + if (isJsxIntrinsicTagName(node.tagName)) { + return 2 /* Mixed */; + } + const tagType = getApparentType(checkExpression(node.tagName)); + if (length(getSignaturesOfType(tagType, 1 /* Construct */))) { + return 0 /* Component */; + } + if (length(getSignaturesOfType(tagType, 0 /* Call */))) { + return 1 /* Function */; + } + return 2 /* Mixed */; + } + function checkApplicableSignatureForJsxCallLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer) { + const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); + const attributesType = isJsxOpeningFragment(node) ? createJsxAttributesTypeFromAttributesProperty(node) : checkExpressionWithContextualType( + node.attributes, + paramType, + /*inferenceContext*/ + void 0, + checkMode + ); + const checkAttributesType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(attributesType) : attributesType; + return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate( + checkAttributesType, + paramType, + relation, + reportErrors2 ? isJsxOpeningFragment(node) ? node : node.tagName : void 0, + isJsxOpeningFragment(node) ? void 0 : node.attributes, + /*headMessage*/ + void 0, + containingMessageChain, + errorOutputContainer + ); + function checkTagNameDoesNotExpectTooManyArguments() { + var _a; + if (getJsxNamespaceContainerForImplicitImport(node)) { + return true; + } + const tagType = (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) && !(isJsxIntrinsicTagName(node.tagName) || isJsxNamespacedName(node.tagName)) ? checkExpression(node.tagName) : void 0; + if (!tagType) { + return true; + } + const tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */); + if (!length(tagCallSignatures)) { + return true; + } + const factory2 = getJsxFactoryEntity(node); + if (!factory2) { + return true; + } + const factorySymbol = resolveEntityName( + factory2, + 111551 /* Value */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + false, + node + ); + if (!factorySymbol) { + return true; + } + const factoryType = getTypeOfSymbol(factorySymbol); + const callSignatures = getSignaturesOfType(factoryType, 0 /* Call */); + if (!length(callSignatures)) { + return true; + } + let hasFirstParamSignatures = false; + let maxParamCount = 0; + for (const sig of callSignatures) { + const firstparam = getTypeAtPosition(sig, 0); + const signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */); + if (!length(signaturesOfParam)) continue; + for (const paramSig of signaturesOfParam) { + hasFirstParamSignatures = true; + if (hasEffectiveRestParameter(paramSig)) { + return true; + } + const paramCount = getParameterCount(paramSig); + if (paramCount > maxParamCount) { + maxParamCount = paramCount; + } + } + } + if (!hasFirstParamSignatures) { + return true; + } + let absoluteMinArgCount = Infinity; + for (const tagSig of tagCallSignatures) { + const tagRequiredArgCount = getMinArgumentCount(tagSig); + if (tagRequiredArgCount < absoluteMinArgCount) { + absoluteMinArgCount = tagRequiredArgCount; + } + } + if (absoluteMinArgCount <= maxParamCount) { + return true; + } + if (reportErrors2) { + const tagName = node.tagName; + const diag2 = createDiagnosticForNode(tagName, Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, entityNameToString(tagName), absoluteMinArgCount, entityNameToString(factory2), maxParamCount); + const tagNameDeclaration = (_a = getSymbolAtLocation(tagName)) == null ? void 0 : _a.valueDeclaration; + if (tagNameDeclaration) { + addRelatedInfo(diag2, createDiagnosticForNode(tagNameDeclaration, Diagnostics._0_is_declared_here, entityNameToString(tagName))); + } + if (errorOutputContainer && errorOutputContainer.skipLogging) { + (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); + } + if (!errorOutputContainer.skipLogging) { + diagnostics.add(diag2); + } + } + return false; + } + } + function getEffectiveCheckNode(argument) { + const flags = isInJSFile(argument) ? 1 /* Parentheses */ | 32 /* Satisfies */ | -2147483648 /* ExcludeJSDocTypeAssertion */ : 1 /* Parentheses */ | 32 /* Satisfies */; + return skipOuterExpressions(argument, flags); + } + function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors2, containingMessageChain, inferenceContext) { + const errorOutputContainer = { errors: void 0, skipLogging: true }; + if (isJsxCallLike(node)) { + if (!checkApplicableSignatureForJsxCallLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer)) { + Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "jsx should have errors when reporting errors"); + return errorOutputContainer.errors || emptyArray; + } + return void 0; + } + const thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && !(isNewExpression(node) || isCallExpression(node) && isSuperProperty(node.expression))) { + const thisArgumentNode = getThisArgumentOfCall(node); + const thisArgumentType = getThisArgumentType(thisArgumentNode); + const errorNode = reportErrors2 ? thisArgumentNode || node : void 0; + const headMessage2 = Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage2, containingMessageChain, errorOutputContainer)) { + Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors"); + return errorOutputContainer.errors || emptyArray; + } + } + const headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + const restType = getNonArrayRestType(signature); + const argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; + for (let i = 0; i < argCount; i++) { + const arg = args[i]; + if (arg.kind !== 232 /* OmittedExpression */) { + const paramType = getTypeAtPosition(signature, i); + const argType = checkExpressionWithContextualType( + arg, + paramType, + /*inferenceContext*/ + void 0, + checkMode + ); + const regularArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType; + const checkArgType = inferenceContext ? instantiateType(regularArgType, inferenceContext.nonFixingMapper) : regularArgType; + const effectiveCheckArgumentNode = getEffectiveCheckNode(arg); + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors2 ? effectiveCheckArgumentNode : void 0, effectiveCheckArgumentNode, headMessage, containingMessageChain, errorOutputContainer)) { + Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "parameter should have errors when reporting errors"); + maybeAddMissingAwaitInfo(arg, checkArgType, paramType); + return errorOutputContainer.errors || emptyArray; + } + } + } + if (restType) { + const spreadType = getSpreadArgumentType( + args, + argCount, + args.length, + restType, + /*context*/ + void 0, + checkMode + ); + const restArgCount = args.length - argCount; + const errorNode = !reportErrors2 ? void 0 : restArgCount === 0 ? node : restArgCount === 1 ? getEffectiveCheckNode(args[argCount]) : setTextRangePosEnd(createSyntheticExpression(node, spreadType), args[argCount].pos, args[args.length - 1].end); + if (!checkTypeRelatedTo( + spreadType, + restType, + relation, + errorNode, + headMessage, + /*containingMessageChain*/ + void 0, + errorOutputContainer + )) { + Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors"); + maybeAddMissingAwaitInfo(errorNode, spreadType, restType); + return errorOutputContainer.errors || emptyArray; + } + } + return void 0; + function maybeAddMissingAwaitInfo(errorNode, source, target) { + if (errorNode && reportErrors2 && errorOutputContainer.errors && errorOutputContainer.errors.length) { + if (getAwaitedTypeOfPromise(target)) { + return; + } + const awaitedTypeOfSource = getAwaitedTypeOfPromise(source); + if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) { + addRelatedInfo(errorOutputContainer.errors[0], createDiagnosticForNode(errorNode, Diagnostics.Did_you_forget_to_use_await)); + } + } + } + } + function getThisArgumentOfCall(node) { + if (node.kind === 226 /* BinaryExpression */) { + return node.right; + } + const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : node.kind === 170 /* Decorator */ && !legacyDecorators ? node.expression : void 0; + if (expression) { + const callee = skipOuterExpressions(expression); + if (isAccessExpression(callee)) { + return callee.expression; + } + } + } + function createSyntheticExpression(parent, type, isSpread, tupleNameSource) { + const result = parseNodeFactory.createSyntheticExpression(type, isSpread, tupleNameSource); + setTextRange(result, parent); + setParent(result, parent); + return result; + } + function getEffectiveCallArguments(node) { + if (isJsxOpeningFragment(node)) { + return [createSyntheticExpression(node, emptyFreshJsxObjectType)]; + } + if (node.kind === 215 /* TaggedTemplateExpression */) { + const template = node.template; + const args2 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; + if (template.kind === 228 /* TemplateExpression */) { + forEach(template.templateSpans, (span) => { + args2.push(span.expression); + }); + } + return args2; + } + if (node.kind === 170 /* Decorator */) { + return getEffectiveDecoratorArguments(node); + } + if (node.kind === 226 /* BinaryExpression */) { + return [node.left]; + } + if (isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 || isJsxOpeningElement(node) && node.parent.children.length > 0 ? [node.attributes] : emptyArray; + } + const args = node.arguments || emptyArray; + const spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex >= 0) { + const effectiveArgs = args.slice(0, spreadIndex); + for (let i = spreadIndex; i < args.length; i++) { + const arg = args[i]; + const spreadType = arg.kind === 230 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); + if (spreadType && isTupleType(spreadType)) { + forEach(getElementTypes(spreadType), (t, i2) => { + var _a; + const flags = spreadType.target.elementFlags[i2]; + const syntheticArg = createSyntheticExpression(arg, flags & 4 /* Rest */ ? createArrayType(t) : t, !!(flags & 12 /* Variable */), (_a = spreadType.target.labeledElementDeclarations) == null ? void 0 : _a[i2]); + effectiveArgs.push(syntheticArg); + }); + } else { + effectiveArgs.push(arg); + } + } + return effectiveArgs; + } + return args; + } + function getEffectiveDecoratorArguments(node) { + const expr = node.expression; + const signature = getDecoratorCallSignature(node); + if (signature) { + const args = []; + for (const param of signature.parameters) { + const type = getTypeOfSymbol(param); + args.push(createSyntheticExpression(expr, type)); + } + return args; + } + return Debug.fail(); + } + function getDecoratorArgumentCount(node, signature) { + return compilerOptions.experimentalDecorators ? getLegacyDecoratorArgumentCount(node, signature) : ( + // Allow the runtime to oversupply arguments to an ES decorator as long as there's at least one parameter. + Math.min(Math.max(getParameterCount(signature), 1), 2) + ); + } + function getLegacyDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + return 1; + case 172 /* PropertyDeclaration */: + return hasAccessorModifier(node.parent) ? 3 : 2; + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return signature.parameters.length <= 2 ? 2 : 3; + case 169 /* Parameter */: + return 3; + default: + return Debug.fail(); + } + } + function getDiagnosticSpanForCallNode(node) { + const sourceFile = getSourceFileOfNode(node); + const { start, length: length2 } = getErrorSpanForNode(sourceFile, isPropertyAccessExpression(node.expression) ? node.expression.name : node.expression); + return { start, length: length2, sourceFile }; + } + function getDiagnosticForCallNode(node, message, ...args) { + if (isCallExpression(node)) { + const { sourceFile, start, length: length2 } = getDiagnosticSpanForCallNode(node); + if ("message" in message) { + return createFileDiagnostic(sourceFile, start, length2, message, ...args); + } + return createDiagnosticForFileFromMessageChain(sourceFile, message); + } else { + if ("message" in message) { + return createDiagnosticForNode(node, message, ...args); + } + return createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node), node, message); + } + } + function getErrorNodeForCallNode(callLike) { + if (isCallOrNewExpression(callLike)) { + return isPropertyAccessExpression(callLike.expression) ? callLike.expression.name : callLike.expression; + } + if (isTaggedTemplateExpression(callLike)) { + return isPropertyAccessExpression(callLike.tag) ? callLike.tag.name : callLike.tag; + } + if (isJsxOpeningLikeElement(callLike)) { + return callLike.tagName; + } + return callLike; + } + function isPromiseResolveArityError(node) { + if (!isCallExpression(node) || !isIdentifier(node.expression)) return false; + const symbol = resolveName( + node.expression, + node.expression.escapedText, + 111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + const decl = symbol == null ? void 0 : symbol.valueDeclaration; + if (!decl || !isParameter(decl) || !isFunctionExpressionOrArrowFunction(decl.parent) || !isNewExpression(decl.parent.parent) || !isIdentifier(decl.parent.parent.expression)) { + return false; + } + const globalPromiseSymbol = getGlobalPromiseConstructorSymbol( + /*reportErrors*/ + false + ); + if (!globalPromiseSymbol) return false; + const constructorSymbol = getSymbolAtLocation( + decl.parent.parent.expression, + /*ignoreErrors*/ + true + ); + return constructorSymbol === globalPromiseSymbol; + } + function getArgumentArityError(node, signatures, args, headMessage) { + var _a; + const spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return createDiagnosticForNode(args[spreadIndex], Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + let min2 = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; + let maxBelow = Number.NEGATIVE_INFINITY; + let minAbove = Number.POSITIVE_INFINITY; + let closestSignature; + for (const sig of signatures) { + const minParameter = getMinArgumentCount(sig); + const maxParameter = getParameterCount(sig); + if (minParameter < min2) { + min2 = minParameter; + closestSignature = sig; + } + max = Math.max(max, maxParameter); + if (minParameter < args.length && minParameter > maxBelow) maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) minAbove = maxParameter; + } + const hasRestParameter2 = some(signatures, hasEffectiveRestParameter); + const parameterRange = hasRestParameter2 ? min2 : min2 < max ? min2 + "-" + max : min2; + const isVoidPromiseError = !hasRestParameter2 && parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node); + if (isVoidPromiseError && isInJSFile(node)) { + return getDiagnosticForCallNode(node, Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments); + } + const error2 = isDecorator(node) ? hasRestParameter2 ? Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0 : Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0 : hasRestParameter2 ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : isVoidPromiseError ? Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : Diagnostics.Expected_0_arguments_but_got_1; + if (min2 < args.length && args.length < max) { + if (headMessage) { + let chain = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, + args.length, + maxBelow, + minAbove + ); + chain = chainDiagnosticMessages(chain, headMessage); + return getDiagnosticForCallNode(node, chain); + } + return getDiagnosticForCallNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } else if (args.length < min2) { + let diagnostic; + if (headMessage) { + let chain = chainDiagnosticMessages( + /*details*/ + void 0, + error2, + parameterRange, + args.length + ); + chain = chainDiagnosticMessages(chain, headMessage); + diagnostic = getDiagnosticForCallNode(node, chain); + } else { + diagnostic = getDiagnosticForCallNode(node, error2, parameterRange, args.length); + } + const parameter = (_a = closestSignature == null ? void 0 : closestSignature.declaration) == null ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + const messageAndArgs = isBindingPattern(parameter.name) ? [Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided] : isRestParameter(parameter) ? [Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided, idText(getFirstIdentifier(parameter.name))] : [Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : idText(getFirstIdentifier(parameter.name))]; + const parameterError = createDiagnosticForNode(parameter, ...messageAndArgs); + return addRelatedInfo(diagnostic, parameterError); + } + return diagnostic; + } else { + const errorSpan = factory.createNodeArray(args.slice(max)); + const pos = first(errorSpan).pos; + let end = last(errorSpan).end; + if (end === pos) { + end++; + } + setTextRangePosEnd(errorSpan, pos, end); + if (headMessage) { + let chain = chainDiagnosticMessages( + /*details*/ + void 0, + error2, + parameterRange, + args.length + ); + chain = chainDiagnosticMessages(chain, headMessage); + return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), errorSpan, chain); + } + return createDiagnosticForNodeArray(getSourceFileOfNode(node), errorSpan, error2, parameterRange, args.length); + } + } + function getTypeArgumentArityError(node, signatures, typeArguments, headMessage) { + const argCount = typeArguments.length; + if (signatures.length === 1) { + const sig = signatures[0]; + const min2 = getMinTypeArgumentCount(sig.typeParameters); + const max = length(sig.typeParameters); + if (headMessage) { + let chain = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Expected_0_type_arguments_but_got_1, + min2 < max ? min2 + "-" + max : min2, + argCount + ); + chain = chainDiagnosticMessages(chain, headMessage); + return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain); + } + return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, min2 < max ? min2 + "-" + max : min2, argCount); + } + let belowArgCount = -Infinity; + let aboveArgCount = Infinity; + for (const sig of signatures) { + const min2 = getMinTypeArgumentCount(sig.typeParameters); + const max = length(sig.typeParameters); + if (min2 > argCount) { + aboveArgCount = Math.min(aboveArgCount, min2); + } else if (max < argCount) { + belowArgCount = Math.max(belowArgCount, max); + } + } + if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) { + if (headMessage) { + let chain = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, + argCount, + belowArgCount, + aboveArgCount + ); + chain = chainDiagnosticMessages(chain, headMessage); + return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain); + } + return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); + } + if (headMessage) { + let chain = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Expected_0_type_arguments_but_got_1, + belowArgCount === -Infinity ? aboveArgCount : belowArgCount, + argCount + ); + chain = chainDiagnosticMessages(chain, headMessage); + return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain); + } + return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); + } + function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, headMessage) { + const isTaggedTemplate = node.kind === 215 /* TaggedTemplateExpression */; + const isDecorator2 = node.kind === 170 /* Decorator */; + const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); + const isJsxOpenFragment = isJsxOpeningFragment(node); + const isInstanceof = node.kind === 226 /* BinaryExpression */; + const reportErrors2 = !isInferencePartiallyBlocked && !candidatesOutArray; + let candidatesForArgumentError; + let candidateForArgumentArityError; + let candidateForTypeArgumentError; + let result; + let argCheckMode = 0 /* Normal */; + let candidates = []; + let typeArguments; + if (!isDecorator2 && !isInstanceof && !isSuperCall(node) && !isJsxOpenFragment) { + typeArguments = node.typeArguments; + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 108 /* SuperKeyword */) { + forEach(typeArguments, checkSourceElement); + } + } + candidates = candidatesOutArray || []; + reorderCandidates(signatures, candidates, callChainFlags); + if (!isJsxOpenFragment) { + Debug.assert(candidates.length, "Revert #54442 and add a testcase with whatever triggered this"); + } + const args = getEffectiveCallArguments(node); + const isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; + if (!isDecorator2 && !isSingleNonGenericCandidate && some(args, isContextSensitive)) { + argCheckMode = 4 /* SkipContextSensitive */; + } + const signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 213 /* CallExpression */ && node.arguments.hasTrailingComma; + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma); + } + const links = getNodeLinks(node); + if (links.resolvedSignature !== resolvingSignature && !candidatesOutArray) { + Debug.assert(links.resolvedSignature); + return links.resolvedSignature; + } + if (result) { + return result; + } + result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + links.resolvedSignature = result; + if (reportErrors2) { + if (!headMessage && isInstanceof) { + headMessage = Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_hand_side_s_Symbol_hasInstance_method; + } + if (candidatesForArgumentError) { + if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) { + const last2 = candidatesForArgumentError[candidatesForArgumentError.length - 1]; + let chain; + if (candidatesForArgumentError.length > 3) { + chain = chainDiagnosticMessages(chain, Diagnostics.The_last_overload_gave_the_following_error); + chain = chainDiagnosticMessages(chain, Diagnostics.No_overload_matches_this_call); + } + if (headMessage) { + chain = chainDiagnosticMessages(chain, headMessage); + } + const diags = getSignatureApplicabilityError( + node, + args, + last2, + assignableRelation, + 0 /* Normal */, + /*reportErrors*/ + true, + () => chain, + /*inferenceContext*/ + void 0 + ); + if (diags) { + for (const d of diags) { + if (last2.declaration && candidatesForArgumentError.length > 3) { + addRelatedInfo(d, createDiagnosticForNode(last2.declaration, Diagnostics.The_last_overload_is_declared_here)); + } + addImplementationSuccessElaboration(last2, d); + diagnostics.add(d); + } + } else { + Debug.fail("No error for last overload signature"); + } + } else { + const allDiagnostics = []; + let max = 0; + let min2 = Number.MAX_VALUE; + let minIndex = 0; + let i = 0; + for (const c of candidatesForArgumentError) { + const chain2 = () => chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Overload_0_of_1_2_gave_the_following_error, + i + 1, + candidates.length, + signatureToString(c) + ); + const diags2 = getSignatureApplicabilityError( + node, + args, + c, + assignableRelation, + 0 /* Normal */, + /*reportErrors*/ + true, + chain2, + /*inferenceContext*/ + void 0 + ); + if (diags2) { + if (diags2.length <= min2) { + min2 = diags2.length; + minIndex = i; + } + max = Math.max(max, diags2.length); + allDiagnostics.push(diags2); + } else { + Debug.fail("No error for 3 or fewer overload signatures"); + } + i++; + } + const diags = max > 1 ? allDiagnostics[minIndex] : flatten(allDiagnostics); + Debug.assert(diags.length > 0, "No errors reported for 3 or fewer overload signatures"); + let chain = chainDiagnosticMessages( + map(diags, createDiagnosticMessageChainFromDiagnostic), + Diagnostics.No_overload_matches_this_call + ); + if (headMessage) { + chain = chainDiagnosticMessages(chain, headMessage); + } + const related = [...flatMap(diags, (d) => d.relatedInformation)]; + let diag2; + if (every(diags, (d) => d.start === diags[0].start && d.length === diags[0].length && d.file === diags[0].file)) { + const { file, start, length: length2 } = diags[0]; + diag2 = { file, start, length: length2, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }; + } else { + diag2 = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node), getErrorNodeForCallNode(node), chain, related); + } + addImplementationSuccessElaboration(candidatesForArgumentError[0], diag2); + diagnostics.add(diag2); + } + } else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args, headMessage)); + } else if (candidateForTypeArgumentError) { + checkTypeArguments( + candidateForTypeArgumentError, + node.typeArguments, + /*reportErrors*/ + true, + headMessage + ); + } else if (!isJsxOpenFragment) { + const signaturesWithCorrectTypeArgumentArity = filter(signatures, (s) => hasCorrectTypeArgumentArity(s, typeArguments)); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments, headMessage)); + } else { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args, headMessage)); + } + } + } + return result; + function addImplementationSuccessElaboration(failed2, diagnostic) { + var _a, _b; + const oldCandidatesForArgumentError = candidatesForArgumentError; + const oldCandidateForArgumentArityError = candidateForArgumentArityError; + const oldCandidateForTypeArgumentError = candidateForTypeArgumentError; + const failedSignatureDeclarations = ((_b = (_a = failed2.declaration) == null ? void 0 : _a.symbol) == null ? void 0 : _b.declarations) || emptyArray; + const isOverload = failedSignatureDeclarations.length > 1; + const implDecl = isOverload ? find(failedSignatureDeclarations, (d) => isFunctionLikeDeclaration(d) && nodeIsPresent(d.body)) : void 0; + if (implDecl) { + const candidate = getSignatureFromDeclaration(implDecl); + const isSingleNonGenericCandidate2 = !candidate.typeParameters; + if (chooseOverload([candidate], assignableRelation, isSingleNonGenericCandidate2)) { + addRelatedInfo(diagnostic, createDiagnosticForNode(implDecl, Diagnostics.The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_are_not_externally_visible)); + } + } + candidatesForArgumentError = oldCandidatesForArgumentError; + candidateForArgumentArityError = oldCandidateForArgumentArityError; + candidateForTypeArgumentError = oldCandidateForTypeArgumentError; + } + function chooseOverload(candidates2, relation, isSingleNonGenericCandidate2, signatureHelpTrailingComma2 = false) { + var _a, _b; + candidatesForArgumentError = void 0; + candidateForArgumentArityError = void 0; + candidateForTypeArgumentError = void 0; + if (isSingleNonGenericCandidate2) { + const candidate = candidates2[0]; + if (some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma2)) { + return void 0; + } + if (getSignatureApplicabilityError( + node, + args, + candidate, + relation, + 0 /* Normal */, + /*reportErrors*/ + false, + /*containingMessageChain*/ + void 0, + /*inferenceContext*/ + void 0 + )) { + candidatesForArgumentError = [candidate]; + return void 0; + } + return candidate; + } + for (let candidateIndex = 0; candidateIndex < candidates2.length; candidateIndex++) { + let candidate = candidates2[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma2)) { + continue; + } + let checkCandidate; + let inferenceContext; + if (candidate.typeParameters) { + const paramLocation = (_b = (_a = candidate.typeParameters[0].symbol.declarations) == null ? void 0 : _a[0]) == null ? void 0 : _b.parent; + const candidateParameterContext = paramLocation || (candidate.declaration && isConstructorDeclaration(candidate.declaration) ? candidate.declaration.parent : candidate.declaration); + if (candidateParameterContext && findAncestor(node, (a) => a === candidateParameterContext)) { + candidate = getImplementationSignature(candidate); + } + let typeArgumentTypes; + if (some(typeArguments)) { + typeArgumentTypes = checkTypeArguments( + candidate, + typeArguments, + /*reportErrors*/ + false + ); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; + } + } else { + inferenceContext = createInferenceContext( + candidate.typeParameters, + candidate, + /*flags*/ + isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */ + ); + typeArgumentTypes = instantiateTypes(inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext), inferenceContext.nonFixingMapper); + argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */; + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma2)) { + candidateForArgumentArityError = checkCandidate; + continue; + } + } else { + checkCandidate = candidate; + } + if (getSignatureApplicabilityError( + node, + args, + checkCandidate, + relation, + argCheckMode, + /*reportErrors*/ + false, + /*containingMessageChain*/ + void 0, + inferenceContext + )) { + (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate); + continue; + } + if (argCheckMode) { + argCheckMode = 0 /* Normal */; + if (inferenceContext) { + const typeArgumentTypes = instantiateTypes(inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext), inferenceContext.mapper); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters); + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma2)) { + candidateForArgumentArityError = checkCandidate; + continue; + } + } + if (getSignatureApplicabilityError( + node, + args, + checkCandidate, + relation, + argCheckMode, + /*reportErrors*/ + false, + /*containingMessageChain*/ + void 0, + inferenceContext + )) { + (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate); + continue; + } + } + candidates2[candidateIndex] = checkCandidate; + return checkCandidate; + } + return void 0; + } + } + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray, checkMode) { + Debug.assert(candidates.length > 0); + checkNodeDeferred(node); + return hasCandidatesOutArray || candidates.length === 1 || candidates.some((c) => !!c.typeParameters) ? pickLongestCandidateSignature(node, candidates, args, checkMode) : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + const thisParameters = mapDefined(candidates, (c) => c.thisParameter); + let thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + const { min: minArgumentCount, max: maxNonRestParam } = minAndMax(candidates, getNumNonRestParameters); + const parameters = []; + for (let i = 0; i < maxNonRestParam; i++) { + const symbols = mapDefined(candidates, (s) => signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : last(s.parameters) : i < s.parameters.length ? s.parameters[i] : void 0); + Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, (candidate) => tryGetTypeAtPosition(candidate, i)))); + } + const restParameterSymbols = mapDefined(candidates, (c) => signatureHasRestParameter(c) ? last(c.parameters) : void 0); + let flags = 128 /* IsSignatureCandidateForOverloadFailure */; + if (restParameterSymbols.length !== 0) { + const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; + } + return createSignature( + candidates[0].declaration, + /*typeParameters*/ + void 0, + // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, + parameters, + /*resolvedReturnType*/ + getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*resolvedTypePredicate*/ + void 0, + minArgumentCount, + flags + ); + } + function getNumNonRestParameters(signature) { + const numParams = signature.parameters.length; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + return createSymbolWithType(first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args, checkMode) { + const bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === void 0 ? args.length : apparentArgumentCount); + const candidate = candidates[bestIndex]; + const { typeParameters } = candidate; + if (!typeParameters) { + return candidate; + } + const typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : void 0; + const instantiated = typeArgumentNodes ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJSFile(node))) : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args, checkMode); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { + const typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getDefaultFromTypeParameter(typeParameters[typeArguments.length]) || getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); + } + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args, checkMode) { + const inferenceContext = createInferenceContext( + typeParameters, + candidate, + /*flags*/ + isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */ + ); + const typeArgumentTypes = inferTypeArguments(node, candidate, args, checkMode | 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); + } + function getLongestCandidateIndex(candidates, argsCount) { + let maxParamsIndex = -1; + let maxParams = -1; + for (let i = 0; i < candidates.length; i++) { + const candidate = candidates[i]; + const paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { + return i; + } + if (paramCount > maxParams) { + maxParams = paramCount; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray, checkMode) { + if (node.expression.kind === 108 /* SuperKeyword */) { + const superType = checkSuperExpression(node.expression); + if (isTypeAny(superType)) { + for (const arg of node.arguments) { + checkExpression(arg); + } + return anySignature; + } + if (!isErrorType(superType)) { + const baseTypeNode = getEffectiveBaseTypeNode(getContainingClass(node)); + if (baseTypeNode) { + const baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */); + } + } + return resolveUntypedCall(node); + } + let callChainFlags; + let funcType = checkExpression(node.expression); + if (isCallChain(node)) { + const nonOptionalType = getOptionalExpressionType(funcType, node.expression); + callChainFlags = nonOptionalType === funcType ? 0 /* None */ : isOutermostOptionalChain(node) ? 16 /* IsOuterCallChain */ : 8 /* IsInnerCallChain */; + funcType = nonOptionalType; + } else { + callChainFlags = 0 /* None */; + } + funcType = checkNonNullTypeWithReporter( + funcType, + node.expression, + reportCannotInvokePossiblyNullOrUndefinedError + ); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + const apparentType = getApparentType(funcType); + if (isErrorType(apparentType)) { + return resolveErrorCall(node); + } + const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + if (!isErrorType(funcType) && node.typeArguments) { + error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + if (numConstructSignatures) { + error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } else { + let relatedInformation; + if (node.arguments.length === 1) { + const text = getSourceFileOfNode(node).text; + if (isLineBreak(text.charCodeAt(skipTrivia( + text, + node.expression.end, + /*stopAfterLineBreak*/ + true + ) - 1))) { + relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.Are_you_missing_a_semicolon); + } + } + invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation); + } + return resolveErrorCall(node); + } + if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) { + skippedGenericFunction(node, checkMode); + return resolvingSignature; + } + if (callSignatures.some((sig) => isInJSFile(sig.declaration) && !!getJSDocClassTag(sig.declaration))) { + error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags); + } + function isGenericFunctionReturningFunction(signature) { + return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature))); + } + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576 /* Union */) && !(getReducedType(apparentFuncType).flags & 131072 /* Never */) && isTypeAssignableTo(funcType, globalFunctionType); + } + function resolveNewExpression(node, candidatesOutArray, checkMode) { + let expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + expressionType = getApparentType(expressionType); + if (isErrorType(expressionType)) { + return resolveErrorCall(node); + } + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + const constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + if (someSignature(constructSignatures, (signature) => !!(signature.flags & 4 /* Abstract */))) { + error(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + return resolveErrorCall(node); + } + const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && hasSyntacticModifier(valueDecl, 64 /* Abstract */)) { + error(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class); + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */); + } + const callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + const signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + } + return signature; + } + invocationError(node.expression, expressionType, 1 /* Construct */); + return resolveErrorCall(node); + } + function someSignature(signatures, f) { + if (isArray(signatures)) { + return some(signatures, (signature) => someSignature(signature, f)); + } + return signatures.compositeKind === 1048576 /* Union */ ? some(signatures.compositeSignatures, f) : f(signatures); + } + function typeHasProtectedAccessibleBase(target, type) { + const baseTypes = getBaseTypes(type); + if (!length(baseTypes)) { + return false; + } + const firstBase = baseTypes[0]; + if (firstBase.flags & 2097152 /* Intersection */) { + const types = firstBase.types; + const mixinFlags = findMixins(types); + let i = 0; + for (const intersectionMember of firstBase.types) { + if (!mixinFlags[i]) { + if (getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + i++; + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + const declaration = signature.declaration; + const modifiers = getSelectedEffectiveModifierFlags(declaration, 6 /* NonPublicAccessibilityModifier */); + if (!modifiers || declaration.kind !== 176 /* Constructor */) { + return true; + } + const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + const declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + const containingClass = getContainingClass(node); + if (containingClass && modifiers & 4 /* Protected */) { + const containingType = getTypeOfNode(containingClass); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; + } + } + if (modifiers & 2 /* Private */) { + error(node, Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 4 /* Protected */) { + error(node, Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function invocationErrorDetails(errorTarget, apparentType, kind) { + let errorInfo; + const isCall = kind === 0 /* Call */; + const awaitedType = getAwaitedType(apparentType); + const maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0; + if (apparentType.flags & 1048576 /* Union */) { + const types = apparentType.types; + let hasSignatures = false; + for (const constituent of types) { + const signatures = getSignaturesOfType(constituent, kind); + if (signatures.length !== 0) { + hasSignatures = true; + if (errorInfo) { + break; + } + } else { + if (!errorInfo) { + errorInfo = chainDiagnosticMessages( + errorInfo, + isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures, + typeToString(constituent) + ); + errorInfo = chainDiagnosticMessages( + errorInfo, + isCall ? Diagnostics.Not_all_constituents_of_type_0_are_callable : Diagnostics.Not_all_constituents_of_type_0_are_constructable, + typeToString(apparentType) + ); + } + if (hasSignatures) { + break; + } + } + } + if (!hasSignatures) { + errorInfo = chainDiagnosticMessages( + /*details*/ + void 0, + isCall ? Diagnostics.No_constituent_of_type_0_is_callable : Diagnostics.No_constituent_of_type_0_is_constructable, + typeToString(apparentType) + ); + } + if (!errorInfo) { + errorInfo = chainDiagnosticMessages( + errorInfo, + isCall ? Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other : Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, + typeToString(apparentType) + ); + } + } else { + errorInfo = chainDiagnosticMessages( + errorInfo, + isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures, + typeToString(apparentType) + ); + } + let headMessage = isCall ? Diagnostics.This_expression_is_not_callable : Diagnostics.This_expression_is_not_constructable; + if (isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) { + const { resolvedSymbol } = getNodeLinks(errorTarget); + if (resolvedSymbol && resolvedSymbol.flags & 32768 /* GetAccessor */) { + headMessage = Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without; + } + } + return { + messageChain: chainDiagnosticMessages(errorInfo, headMessage), + relatedMessage: maybeMissingAwait ? Diagnostics.Did_you_forget_to_use_await : void 0 + }; + } + function invocationError(errorTarget, apparentType, kind, relatedInformation) { + const { messageChain, relatedMessage: relatedInfo } = invocationErrorDetails(errorTarget, apparentType, kind); + const diagnostic = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorTarget), errorTarget, messageChain); + if (relatedInfo) { + addRelatedInfo(diagnostic, createDiagnosticForNode(errorTarget, relatedInfo)); + } + if (isCallExpression(errorTarget.parent)) { + const { start, length: length2 } = getDiagnosticSpanForCallNode(errorTarget.parent); + diagnostic.start = start; + diagnostic.length = length2; + } + diagnostics.add(diagnostic); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); + } + function invocationErrorRecovery(apparentType, kind, diagnostic) { + if (!apparentType.symbol) { + return; + } + const importNode = getSymbolLinks(apparentType.symbol).originatingImport; + if (importNode && !isImportCall(importNode)) { + const sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) return; + addRelatedInfo(diagnostic, createDiagnosticForNode(importNode, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); + } + } + function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) { + const tagType = checkExpression(node.tag); + const apparentType = getApparentType(tagType); + if (isErrorType(apparentType)) { + return resolveErrorCall(node); + } + const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + if (isArrayLiteralExpression(node.parent)) { + const diagnostic = createDiagnosticForNode(node.tag, Diagnostics.It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked); + diagnostics.add(diagnostic); + return resolveErrorCall(node); + } + invocationError(node.tag, apparentType, 0 /* Call */); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); + } + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + return Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 169 /* Parameter */: + return Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 172 /* PropertyDeclaration */: + return Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return Debug.fail(); + } + } + function resolveDecorator(node, candidatesOutArray, checkMode) { + const funcType = checkExpression(node.expression); + const apparentType = getApparentType(funcType); + if (isErrorType(apparentType)) { + return resolveErrorCall(node); + } + const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { + return resolveUntypedCall(node); + } + if (isPotentiallyUncalledDecorator(node, callSignatures) && !isParenthesizedExpression(node.expression)) { + const nodeStr = getTextOfNode( + node.expression, + /*includeTrivia*/ + false + ); + error(node, Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); + return resolveErrorCall(node); + } + const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + const errorDetails = invocationErrorDetails(node.expression, apparentType, 0 /* Call */); + const messageChain = chainDiagnosticMessages(errorDetails.messageChain, headMessage); + const diag2 = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node.expression), node.expression, messageChain); + if (errorDetails.relatedMessage) { + addRelatedInfo(diag2, createDiagnosticForNode(node.expression, errorDetails.relatedMessage)); + } + diagnostics.add(diag2); + invocationErrorRecovery(apparentType, 0 /* Call */, diag2); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage); + } + function createSignatureForJSXIntrinsic(node, result) { + const namespace = getJsxNamespaceAt(node); + const exports2 = namespace && getExportsOfSymbol(namespace); + const typeSymbol = exports2 && getSymbol(exports2, JsxNames.Element, 788968 /* Type */); + const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node); + const declaration = factory.createFunctionTypeNode( + /*typeParameters*/ + void 0, + [factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "props", + /*questionToken*/ + void 0, + nodeBuilder.typeToTypeNode(result, node) + )], + returnNode ? factory.createTypeReferenceNode( + returnNode, + /*typeArguments*/ + void 0 + ) : factory.createKeywordTypeNode(133 /* AnyKeyword */) + ); + const parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); + parameterSymbol.links.type = result; + return createSignature( + declaration, + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + [parameterSymbol], + typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*resolvedTypePredicate*/ + void 0, + 1, + 0 /* None */ + ); + } + function getJSXFragmentType(node) { + const sourceFileLinks = getNodeLinks(getSourceFileOfNode(node)); + if (sourceFileLinks.jsxFragmentType !== void 0) return sourceFileLinks.jsxFragmentType; + const jsxFragmentFactoryName = getJsxNamespace(node); + const shouldResolveFactoryReference = (compilerOptions.jsx === 2 /* React */ || compilerOptions.jsxFragmentFactory !== void 0) && jsxFragmentFactoryName !== "null"; + if (!shouldResolveFactoryReference) return sourceFileLinks.jsxFragmentType = anyType; + const shouldModuleRefErr = compilerOptions.jsx !== 1 /* Preserve */ && compilerOptions.jsx !== 3 /* ReactNative */; + const jsxFactoryRefErr = diagnostics ? Diagnostics.Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found : void 0; + const jsxFactorySymbol = getJsxNamespaceContainerForImplicitImport(node) ?? resolveName( + node, + jsxFragmentFactoryName, + shouldModuleRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */, + /*nameNotFoundMessage*/ + jsxFactoryRefErr, + /*isUse*/ + true + ); + if (jsxFactorySymbol === void 0) return sourceFileLinks.jsxFragmentType = errorType; + if (jsxFactorySymbol.escapedName === ReactNames.Fragment) return sourceFileLinks.jsxFragmentType = getTypeOfSymbol(jsxFactorySymbol); + const resolvedAlias = (jsxFactorySymbol.flags & 2097152 /* Alias */) === 0 ? jsxFactorySymbol : resolveAlias(jsxFactorySymbol); + const reactExports = jsxFactorySymbol && getExportsOfSymbol(resolvedAlias); + const typeSymbol = reactExports && getSymbol(reactExports, ReactNames.Fragment, 2 /* BlockScopedVariable */); + const type = typeSymbol && getTypeOfSymbol(typeSymbol); + return sourceFileLinks.jsxFragmentType = type === void 0 ? errorType : type; + } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { + const isJsxOpenFragment = isJsxOpeningFragment(node); + let exprTypes; + if (!isJsxOpenFragment) { + if (isJsxIntrinsicTagName(node.tagName)) { + const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + const fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType( + node.attributes, + getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), + /*inferenceContext*/ + void 0, + 0 /* Normal */ + ), result, node.tagName, node.attributes); + if (length(node.typeArguments)) { + forEach(node.typeArguments, checkSourceElement); + diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), node.typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, 0, length(node.typeArguments))); + } + return fakeSignature; + } + exprTypes = checkExpression(node.tagName); + } else { + exprTypes = getJSXFragmentType(node); + } + const apparentType = getApparentType(exprTypes); + if (isErrorType(apparentType)) { + return resolveErrorCall(node); + } + const signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); + if (isUntypedFunctionCall( + exprTypes, + apparentType, + signatures.length, + /*constructSignatures*/ + 0 + )) { + return resolveUntypedCall(node); + } + if (signatures.length === 0) { + if (isJsxOpenFragment) { + error(node, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node)); + } else { + error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); + } + return resolveErrorCall(node); + } + return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */); + } + function resolveInstanceofExpression(node, candidatesOutArray, checkMode) { + const rightType = checkExpression(node.right); + if (!isTypeAny(rightType)) { + const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(rightType); + if (hasInstanceMethodType) { + const apparentType = getApparentType(hasInstanceMethodType); + if (isErrorType(apparentType)) { + return resolveErrorCall(node); + } + const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + const constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(hasInstanceMethodType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + if (callSignatures.length) { + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); + } + } else if (!(typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { + error(node.right, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_type_assignable_to_the_Function_interface_type_or_an_object_type_with_a_Symbol_hasInstance_method); + return resolveErrorCall(node); + } + } + return anySignature; + } + function isPotentiallyUncalledDecorator(decorator, signatures) { + return signatures.length && every(signatures, (signature) => signature.minArgumentCount === 0 && !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature)); + } + function resolveSignature(node, candidatesOutArray, checkMode) { + switch (node.kind) { + case 213 /* CallExpression */: + return resolveCallExpression(node, candidatesOutArray, checkMode); + case 214 /* NewExpression */: + return resolveNewExpression(node, candidatesOutArray, checkMode); + case 215 /* TaggedTemplateExpression */: + return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); + case 170 /* Decorator */: + return resolveDecorator(node, candidatesOutArray, checkMode); + case 289 /* JsxOpeningFragment */: + case 286 /* JsxOpeningElement */: + case 285 /* JsxSelfClosingElement */: + return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); + case 226 /* BinaryExpression */: + return resolveInstanceofExpression(node, candidatesOutArray, checkMode); + } + Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + } + function getResolvedSignature(node, candidatesOutArray, checkMode) { + const links = getNodeLinks(node); + const cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + const saveResolutionStart = resolutionStart; + if (!cached) { + resolutionStart = resolutionTargets.length; + } + links.resolvedSignature = resolvingSignature; + const result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */); + resolutionStart = saveResolutionStart; + if (result !== resolvingSignature) { + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + } + return result; + } + function isJSConstructor(node) { + var _a; + if (!node || !isInJSFile(node)) { + return false; + } + const func = isFunctionDeclaration(node) || isFunctionExpression(node) ? node : (isVariableDeclaration(node) || isPropertyAssignment(node)) && node.initializer && isFunctionExpression(node.initializer) ? node.initializer : void 0; + if (func) { + if (getJSDocClassTag(node)) return true; + if (isPropertyAssignment(walkUpParenthesizedExpressions(func.parent))) return false; + const symbol = getSymbolOfDeclaration(func); + return !!((_a = symbol == null ? void 0 : symbol.members) == null ? void 0 : _a.size); + } + return false; + } + function mergeJSSymbols(target, source) { + var _a, _b; + if (source) { + const links = getSymbolLinks(source); + if (!links.inferredClassSymbol || !links.inferredClassSymbol.has(getSymbolId(target))) { + const inferred = isTransientSymbol(target) ? target : cloneSymbol(target); + inferred.exports = inferred.exports || createSymbolTable(); + inferred.members = inferred.members || createSymbolTable(); + inferred.flags |= source.flags & 32 /* Class */; + if ((_a = source.exports) == null ? void 0 : _a.size) { + mergeSymbolTable(inferred.exports, source.exports); + } + if ((_b = source.members) == null ? void 0 : _b.size) { + mergeSymbolTable(inferred.members, source.members); + } + (links.inferredClassSymbol || (links.inferredClassSymbol = /* @__PURE__ */ new Map())).set(getSymbolId(inferred), inferred); + return inferred; + } + return links.inferredClassSymbol.get(getSymbolId(target)); + } + } + function getAssignedClassSymbol(decl) { + var _a; + const assignmentSymbol = decl && getSymbolOfExpando( + decl, + /*allowDeclaration*/ + true + ); + const prototype = (_a = assignmentSymbol == null ? void 0 : assignmentSymbol.exports) == null ? void 0 : _a.get("prototype"); + const init = (prototype == null ? void 0 : prototype.valueDeclaration) && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? getSymbolOfDeclaration(init) : void 0; + } + function getSymbolOfExpando(node, allowDeclaration) { + if (!node.parent) { + return void 0; + } + let name; + let decl; + if (isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJSFile(node) && !(isVarConstLike2(node.parent) && isFunctionLikeDeclaration(node))) { + return void 0; + } + name = node.parent.name; + decl = node.parent; + } else if (isBinaryExpression(node.parent)) { + const parentNode = node.parent; + const parentNodeOperator = node.parent.operatorToken.kind; + if (parentNodeOperator === 64 /* EqualsToken */ && (allowDeclaration || parentNode.right === node)) { + name = parentNode.left; + decl = name; + } else if (parentNodeOperator === 57 /* BarBarToken */ || parentNodeOperator === 61 /* QuestionQuestionToken */) { + if (isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) { + name = parentNode.parent.name; + decl = parentNode.parent; + } else if (isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 64 /* EqualsToken */ && (allowDeclaration || parentNode.parent.right === parentNode)) { + name = parentNode.parent.left; + decl = name; + } + if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) { + return void 0; + } + } + } else if (allowDeclaration && isFunctionDeclaration(node)) { + name = node.name; + decl = node; + } + if (!decl || !name || !allowDeclaration && !getExpandoInitializer(node, isPrototypeAccess(name))) { + return void 0; + } + return getSymbolOfNode(decl); + } + function getAssignedJSPrototype(node) { + if (!node.parent) { + return false; + } + let parent = node.parent; + while (parent && parent.kind === 211 /* PropertyAccessExpression */) { + parent = parent.parent; + } + if (parent && isBinaryExpression(parent) && isPrototypeAccess(parent.left) && parent.operatorToken.kind === 64 /* EqualsToken */) { + const right = getInitializerOfBinaryExpression(parent); + return isObjectLiteralExpression(right) && right; + } + } + function checkCallExpression(node, checkMode) { + var _a, _b, _c; + checkGrammarTypeArguments(node, node.typeArguments); + const signature = getResolvedSignature( + node, + /*candidatesOutArray*/ + void 0, + checkMode + ); + if (signature === resolvingSignature) { + return silentNeverType; + } + checkDeprecatedSignature(signature, node); + if (node.expression.kind === 108 /* SuperKeyword */) { + return voidType; + } + if (node.kind === 214 /* NewExpression */) { + const declaration = signature.declaration; + if (declaration && declaration.kind !== 176 /* Constructor */ && declaration.kind !== 180 /* ConstructSignature */ && declaration.kind !== 185 /* ConstructorType */ && !(isJSDocSignature(declaration) && ((_b = (_a = getJSDocRoot(declaration)) == null ? void 0 : _a.parent) == null ? void 0 : _b.kind) === 176 /* Constructor */) && !isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { + if (noImplicitAny) { + error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + if (isInJSFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + const returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + return getESSymbolLikeTypeForNode(walkUpParenthesizedExpressions(node.parent)); + } + if (node.kind === 213 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 244 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { + if (!isDottedName(node.expression)) { + error(node.expression, Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); + } else if (!getEffectsSignature(node)) { + const diagnostic = error(node.expression, Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation); + getTypeOfDottedName(node.expression, diagnostic); + } + } + if (isInJSFile(node)) { + const jsSymbol = getSymbolOfExpando( + node, + /*allowDeclaration*/ + false + ); + if ((_c = jsSymbol == null ? void 0 : jsSymbol.exports) == null ? void 0 : _c.size) { + const jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, emptyArray, emptyArray, emptyArray); + jsAssignmentType.objectFlags |= 4096 /* JSLiteral */; + return getIntersectionType([returnType, jsAssignmentType]); + } + } + return returnType; + } + function checkDeprecatedSignature(signature, node) { + if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) return; + if (signature.declaration && signature.declaration.flags & 536870912 /* Deprecated */) { + const suggestionNode = getDeprecatedSuggestionNode(node); + const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); + } + } + function getDeprecatedSuggestionNode(node) { + node = skipParentheses(node); + switch (node.kind) { + case 213 /* CallExpression */: + case 170 /* Decorator */: + case 214 /* NewExpression */: + return getDeprecatedSuggestionNode(node.expression); + case 215 /* TaggedTemplateExpression */: + return getDeprecatedSuggestionNode(node.tag); + case 286 /* JsxOpeningElement */: + case 285 /* JsxSelfClosingElement */: + return getDeprecatedSuggestionNode(node.tagName); + case 212 /* ElementAccessExpression */: + return node.argumentExpression; + case 211 /* PropertyAccessExpression */: + return node.name; + case 183 /* TypeReference */: + const typeReference = node; + return isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; + default: + return node; + } + } + function isSymbolOrSymbolForCall(node) { + if (!isCallExpression(node)) return false; + let left = node.expression; + if (isPropertyAccessExpression(left) && left.name.escapedText === "for") { + left = left.expression; + } + if (!isIdentifier(left) || left.escapedText !== "Symbol") { + return false; + } + const globalESSymbol = getGlobalESSymbolConstructorSymbol( + /*reportErrors*/ + false + ); + if (!globalESSymbol) { + return false; + } + return globalESSymbol === resolveName( + left, + "Symbol", + 111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + } + function checkImportCallExpression(node) { + checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + const specifier = node.arguments[0]; + const specifierType = checkExpressionCached(specifier); + const optionsType = node.arguments.length > 1 ? checkExpressionCached(node.arguments[1]) : void 0; + for (let i = 2; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + if (optionsType) { + const importCallOptionsType = getGlobalImportCallOptionsType( + /*reportErrors*/ + true + ); + if (importCallOptionsType !== emptyObjectType) { + checkTypeAssignableTo(optionsType, getNullableType(importCallOptionsType, 32768 /* Undefined */), node.arguments[1]); + } + } + const moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + const esModuleSymbol = resolveESModuleSymbol( + moduleSymbol, + specifier, + /*dontResolveAlias*/ + true, + /*suppressInteropError*/ + false + ); + if (esModuleSymbol) { + return createPromiseReturnType( + node, + getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) + ); + } + } + return createPromiseReturnType(node, anyType); + } + function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) { + const memberTable = createSymbolTable(); + const newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.parent = originalSymbol; + newSymbol.links.nameType = getStringLiteralType("default"); + newSymbol.links.aliasTarget = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + return createAnonymousType(anonymousSymbol, memberTable, emptyArray, emptyArray, emptyArray); + } + function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) { + const hasDefaultOnly = isOnlyImportableAsDefault(moduleSpecifier); + if (hasDefaultOnly && type && !isErrorType(type)) { + const synthType = type; + if (!synthType.defaultOnlyType) { + const type2 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type2; + } + return synthType.defaultOnlyType; + } + return void 0; + } + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) { + var _a; + if (allowSyntheticDefaultImports && type && !isErrorType(type)) { + const synthType = type; + if (!synthType.syntheticType) { + const file = (_a = originalSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); + const hasSyntheticDefault = canHaveSyntheticDefault( + file, + originalSymbol, + /*dontResolveAlias*/ + false, + moduleSpecifier + ); + if (hasSyntheticDefault) { + const anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + const defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol); + anonymousSymbol.links.type = defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType( + type, + defaultContainingObject, + anonymousSymbol, + /*objectFlags*/ + 0, + /*readonly*/ + false + ) : defaultContainingObject; + } else { + synthType.syntheticType = type; + } + } + return synthType.syntheticType; + } + return type; + } + function isCommonJsRequire(node) { + if (!isRequireCall( + node, + /*requireStringLiteralLikeArgument*/ + true + )) { + return false; + } + if (!isIdentifier(node.expression)) return Debug.fail(); + const resolvedRequire = resolveName( + node.expression, + node.expression.escapedText, + 111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (resolvedRequire === requireSymbol) { + return true; + } + if (resolvedRequire.flags & 2097152 /* Alias */) { + return false; + } + const targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ ? 262 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ ? 260 /* VariableDeclaration */ : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + const decl = getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + return !!decl && !!(decl.flags & 33554432 /* Ambient */); + } + return false; + } + function checkTaggedTemplateExpression(node) { + if (!checkGrammarTaggedTemplateChain(node)) checkGrammarTypeArguments(node, node.typeArguments); + if (languageVersion < LanguageFeatureMinimumTarget.TaggedTemplates) { + checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */); + } + const signature = getResolvedSignature(node); + checkDeprecatedSignature(signature, node); + return getReturnTypeOfSignature(signature); + } + function checkAssertion(node, checkMode) { + if (node.kind === 216 /* TypeAssertionExpression */) { + const file = getSourceFileOfNode(node); + if (file && fileExtensionIsOneOf(file.fileName, [".cts" /* Cts */, ".mts" /* Mts */])) { + grammarErrorOnNode(node, Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead); + } + if (compilerOptions.erasableSyntaxOnly) { + const start = skipTrivia(file.text, node.pos); + const end = node.expression.pos; + diagnostics.add(createFileDiagnostic(file, start, end - start, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled)); + } + } + return checkAssertionWorker(node, checkMode); + } + function isValidConstAssertionArgument(node) { + switch (node.kind) { + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 209 /* ArrayLiteralExpression */: + case 210 /* ObjectLiteralExpression */: + case 228 /* TemplateExpression */: + return true; + case 217 /* ParenthesizedExpression */: + return isValidConstAssertionArgument(node.expression); + case 224 /* PrefixUnaryExpression */: + const op = node.operator; + const arg = node.operand; + return op === 41 /* MinusToken */ && (arg.kind === 9 /* NumericLiteral */ || arg.kind === 10 /* BigIntLiteral */) || op === 40 /* PlusToken */ && arg.kind === 9 /* NumericLiteral */; + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + const expr = skipParentheses(node.expression); + const symbol = isEntityNameExpression(expr) ? resolveEntityName( + expr, + 111551 /* Value */, + /*ignoreErrors*/ + true + ) : void 0; + return !!(symbol && symbol.flags & 384 /* Enum */); + } + return false; + } + function checkAssertionWorker(node, checkMode) { + const { type, expression } = getAssertionTypeAndExpression(node); + const exprType = checkExpression(expression, checkMode); + if (isConstTypeReference(type)) { + if (!isValidConstAssertionArgument(expression)) { + error(expression, Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals); + } + return getRegularTypeOfLiteralType(exprType); + } + const links = getNodeLinks(node); + links.assertionExpressionType = exprType; + checkSourceElement(type); + checkNodeDeferred(node); + return getTypeFromTypeNode(type); + } + function getAssertionTypeAndExpression(node) { + let type; + let expression; + switch (node.kind) { + case 234 /* AsExpression */: + case 216 /* TypeAssertionExpression */: + type = node.type; + expression = node.expression; + break; + case 217 /* ParenthesizedExpression */: + type = getJSDocTypeAssertionType(node); + expression = node.expression; + break; + } + return { type, expression }; + } + function checkAssertionDeferred(node) { + const { type } = getAssertionTypeAndExpression(node); + const errNode = isParenthesizedExpression(node) ? type : node; + const links = getNodeLinks(node); + Debug.assertIsDefined(links.assertionExpressionType); + const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(links.assertionExpressionType)); + const targetType = getTypeFromTypeNode(type); + if (!isErrorType(targetType)) { + addLazyDiagnostic(() => { + const widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); + } + }); + } + } + function checkNonNullChain(node) { + const leftType = checkExpression(node.expression); + const nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType); + } + function checkNonNullAssertion(node) { + return node.flags & 64 /* OptionalChain */ ? checkNonNullChain(node) : getNonNullableType(checkExpression(node.expression)); + } + function checkExpressionWithTypeArguments(node) { + checkGrammarExpressionWithTypeArguments(node); + forEach(node.typeArguments, checkSourceElement); + if (node.kind === 233 /* ExpressionWithTypeArguments */) { + const parent = walkUpParenthesizedExpressions(node.parent); + if (parent.kind === 226 /* BinaryExpression */ && parent.operatorToken.kind === 104 /* InstanceOfKeyword */ && isNodeDescendantOf(node, parent.right)) { + error(node, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression); + } + } + const exprType = node.kind === 233 /* ExpressionWithTypeArguments */ ? checkExpression(node.expression) : isThisIdentifier(node.exprName) ? checkThisExpression(node.exprName) : checkExpression(node.exprName); + return getInstantiationExpressionType(exprType, node); + } + function getInstantiationExpressionType(exprType, node) { + const typeArguments = node.typeArguments; + if (exprType === silentNeverType || isErrorType(exprType) || !some(typeArguments)) { + return exprType; + } + const links = getNodeLinks(node); + if (!links.instantiationExpressionTypes) { + links.instantiationExpressionTypes = /* @__PURE__ */ new Map(); + } + if (links.instantiationExpressionTypes.has(exprType.id)) { + return links.instantiationExpressionTypes.get(exprType.id); + } + let hasSomeApplicableSignature = false; + let nonApplicableType; + const result = getInstantiatedType(exprType); + links.instantiationExpressionTypes.set(exprType.id, result); + const errorType2 = hasSomeApplicableSignature ? nonApplicableType : exprType; + if (errorType2) { + diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable, typeToString(errorType2))); + } + return result; + function getInstantiatedType(type) { + let hasSignatures = false; + let hasApplicableSignature = false; + const result2 = getInstantiatedTypePart(type); + hasSomeApplicableSignature || (hasSomeApplicableSignature = hasApplicableSignature); + if (hasSignatures && !hasApplicableSignature) { + nonApplicableType ?? (nonApplicableType = type); + } + return result2; + function getInstantiatedTypePart(type2) { + if (type2.flags & 524288 /* Object */) { + const resolved = resolveStructuredTypeMembers(type2); + const callSignatures = getInstantiatedSignatures(resolved.callSignatures); + const constructSignatures = getInstantiatedSignatures(resolved.constructSignatures); + hasSignatures || (hasSignatures = resolved.callSignatures.length !== 0 || resolved.constructSignatures.length !== 0); + hasApplicableSignature || (hasApplicableSignature = callSignatures.length !== 0 || constructSignatures.length !== 0); + if (callSignatures !== resolved.callSignatures || constructSignatures !== resolved.constructSignatures) { + const result3 = createAnonymousType(createSymbol(0 /* None */, "__instantiationExpression" /* InstantiationExpression */), resolved.members, callSignatures, constructSignatures, resolved.indexInfos); + result3.objectFlags |= 8388608 /* InstantiationExpressionType */; + result3.node = node; + return result3; + } + } else if (type2.flags & 58982400 /* InstantiableNonPrimitive */) { + const constraint = getBaseConstraintOfType(type2); + if (constraint) { + const instantiated = getInstantiatedTypePart(constraint); + if (instantiated !== constraint) { + return instantiated; + } + } + } else if (type2.flags & 1048576 /* Union */) { + return mapType(type2, getInstantiatedType); + } else if (type2.flags & 2097152 /* Intersection */) { + return getIntersectionType(sameMap(type2.types, getInstantiatedTypePart)); + } + return type2; + } + } + function getInstantiatedSignatures(signatures) { + const applicableSignatures = filter(signatures, (sig) => !!sig.typeParameters && hasCorrectTypeArgumentArity(sig, typeArguments)); + return sameMap(applicableSignatures, (sig) => { + const typeArgumentTypes = checkTypeArguments( + sig, + typeArguments, + /*reportErrors*/ + true + ); + return typeArgumentTypes ? getSignatureInstantiation(sig, typeArgumentTypes, isInJSFile(sig.declaration)) : sig; + }); + } + } + function checkSatisfiesExpression(node) { + checkSourceElement(node.type); + return checkSatisfiesExpressionWorker(node.expression, node.type); + } + function checkSatisfiesExpressionWorker(expression, target, checkMode) { + const exprType = checkExpression(expression, checkMode); + const targetType = getTypeFromTypeNode(target); + if (isErrorType(targetType)) { + return targetType; + } + const errorNode = findAncestor(target.parent, (n) => n.kind === 238 /* SatisfiesExpression */ || n.kind === 350 /* JSDocSatisfiesTag */); + checkTypeAssignableToAndOptionallyElaborate(exprType, targetType, errorNode, expression, Diagnostics.Type_0_does_not_satisfy_the_expected_type_1); + return exprType; + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + if (node.keywordToken === 105 /* NewKeyword */) { + return checkNewTargetMetaProperty(node); + } + if (node.keywordToken === 102 /* ImportKeyword */) { + return checkImportMetaProperty(node); + } + return Debug.assertNever(node.keywordToken); + } + function checkMetaPropertyKeyword(node) { + switch (node.keywordToken) { + case 102 /* ImportKeyword */: + return getGlobalImportMetaExpressionType(); + case 105 /* NewKeyword */: + const type = checkNewTargetMetaProperty(node); + return isErrorType(type) ? errorType : createNewTargetExpressionType(type); + default: + Debug.assertNever(node.keywordToken); + } + } + function checkNewTargetMetaProperty(node) { + const container = getNewTargetContainer(node); + if (!container) { + error(node, Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return errorType; + } else if (container.kind === 176 /* Constructor */) { + const symbol = getSymbolOfDeclaration(container.parent); + return getTypeOfSymbol(symbol); + } else { + const symbol = getSymbolOfDeclaration(container); + return getTypeOfSymbol(symbol); + } + } + function checkImportMetaProperty(node) { + if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { + if (getSourceFileOfNode(node).impliedNodeFormat !== 99 /* ESNext */) { + error(node, Diagnostics.The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output); + } + } else if (moduleKind < 6 /* ES2020 */ && moduleKind !== 4 /* System */) { + error(node, Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_node18_or_nodenext); + } + const file = getSourceFileOfNode(node); + Debug.assert(!!(file.flags & 8388608 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag."); + return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; + } + function getTypeOfParameter(symbol) { + const declaration = symbol.valueDeclaration; + return addOptionality( + getTypeOfSymbol(symbol), + /*isProperty*/ + false, + /*isOptional*/ + !!declaration && (hasInitializer(declaration) || isOptionalDeclaration(declaration)) + ); + } + function getTupleElementLabelFromBindingElement(node, index, elementFlags) { + switch (node.name.kind) { + case 80 /* Identifier */: { + const name = node.name.escapedText; + if (node.dotDotDotToken) { + return elementFlags & 12 /* Variable */ ? name : `${name}_${index}`; + } else { + return elementFlags & 3 /* Fixed */ ? name : `${name}_n`; + } + } + case 207 /* ArrayBindingPattern */: { + if (node.dotDotDotToken) { + const elements = node.name.elements; + const lastElement = tryCast(lastOrUndefined(elements), isBindingElement); + const elementCount = elements.length - ((lastElement == null ? void 0 : lastElement.dotDotDotToken) ? 1 : 0); + if (index < elementCount) { + const element = elements[index]; + if (isBindingElement(element)) { + return getTupleElementLabelFromBindingElement(element, index, elementFlags); + } + } else if (lastElement == null ? void 0 : lastElement.dotDotDotToken) { + return getTupleElementLabelFromBindingElement(lastElement, index - elementCount, elementFlags); + } + } + break; + } + } + return `arg_${index}`; + } + function getTupleElementLabel(d, index = 0, elementFlags = 3 /* Fixed */, restSymbol) { + if (!d) { + const restParameter = tryCast(restSymbol == null ? void 0 : restSymbol.valueDeclaration, isParameter); + return restParameter ? getTupleElementLabelFromBindingElement(restParameter, index, elementFlags) : `${(restSymbol == null ? void 0 : restSymbol.escapedName) ?? "arg"}_${index}`; + } + Debug.assert(isIdentifier(d.name)); + return d.name.escapedText; + } + function getParameterNameAtPosition(signature, pos, overrideRestType) { + var _a; + const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + const restParameter = signature.parameters[paramCount] || unknownSymbol; + const restType = overrideRestType || getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + const tupleType = restType.target; + const index = pos - paramCount; + const associatedName = (_a = tupleType.labeledElementDeclarations) == null ? void 0 : _a[index]; + const elementFlags = tupleType.elementFlags[index]; + return getTupleElementLabel(associatedName, index, elementFlags, restParameter); + } + return restParameter.escapedName; + } + function getParameterIdentifierInfoAtPosition(signature, pos) { + var _a; + if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 317 /* JSDocFunctionType */) { + return void 0; + } + const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); + if (pos < paramCount) { + const param = signature.parameters[pos]; + const paramIdent = getParameterDeclarationIdentifier(param); + return paramIdent ? { + parameter: paramIdent, + parameterName: param.escapedName, + isRestParameter: false + } : void 0; + } + const restParameter = signature.parameters[paramCount] || unknownSymbol; + const restIdent = getParameterDeclarationIdentifier(restParameter); + if (!restIdent) { + return void 0; + } + const restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + const associatedNames = restType.target.labeledElementDeclarations; + const index = pos - paramCount; + const associatedName = associatedNames == null ? void 0 : associatedNames[index]; + const isRestTupleElement = !!(associatedName == null ? void 0 : associatedName.dotDotDotToken); + if (associatedName) { + Debug.assert(isIdentifier(associatedName.name)); + return { parameter: associatedName.name, parameterName: associatedName.name.escapedText, isRestParameter: isRestTupleElement }; + } + return void 0; + } + if (pos === paramCount) { + return { parameter: restIdent, parameterName: restParameter.escapedName, isRestParameter: true }; + } + return void 0; + } + function getParameterDeclarationIdentifier(symbol) { + return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name) && symbol.valueDeclaration.name; + } + function isValidDeclarationForTupleLabel(d) { + return d.kind === 202 /* NamedTupleMember */ || isParameter(d) && d.name && isIdentifier(d.name); + } + function getNameableDeclarationAtPosition(signature, pos) { + const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); + if (pos < paramCount) { + const decl = signature.parameters[pos].valueDeclaration; + return decl && isValidDeclarationForTupleLabel(decl) ? decl : void 0; + } + const restParameter = signature.parameters[paramCount] || unknownSymbol; + const restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + const associatedNames = restType.target.labeledElementDeclarations; + const index = pos - paramCount; + return associatedNames && associatedNames[index]; + } + return restParameter.valueDeclaration && isValidDeclarationForTupleLabel(restParameter.valueDeclaration) ? restParameter.valueDeclaration : void 0; + } + function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signatureHasRestParameter(signature)) { + const restType = getTypeOfSymbol(signature.parameters[paramCount]); + const index = pos - paramCount; + if (!isTupleType(restType) || restType.target.combinedFlags & 12 /* Variable */ || index < restType.target.fixedLength) { + return getIndexedAccessType(restType, getNumberLiteralType(index)); + } + } + return void 0; + } + function getRestTypeAtPosition(source, pos, readonly) { + const parameterCount = getParameterCount(source); + const minArgumentCount = getMinArgumentCount(source); + const restType = getEffectiveRestType(source); + if (restType && pos >= parameterCount - 1) { + return pos === parameterCount - 1 ? restType : createArrayType(getIndexedAccessType(restType, numberType)); + } + const types = []; + const flags = []; + const names = []; + for (let i = pos; i < parameterCount; i++) { + if (!restType || i < parameterCount - 1) { + types.push(getTypeAtPosition(source, i)); + flags.push(i < minArgumentCount ? 1 /* Required */ : 2 /* Optional */); + } else { + types.push(restType); + flags.push(8 /* Variadic */); + } + names.push(getNameableDeclarationAtPosition(source, i)); + } + return createTupleType(types, flags, readonly, names); + } + function getRestOrAnyTypeAtPosition(source, pos) { + const restType = getRestTypeAtPosition(source, pos); + const elementType = restType && getElementTypeOfArrayType(restType); + return elementType && isTypeAny(elementType) ? anyType : restType; + } + function getParameterCount(signature) { + const length2 = signature.parameters.length; + if (signatureHasRestParameter(signature)) { + const restType = getTypeOfSymbol(signature.parameters[length2 - 1]); + if (isTupleType(restType)) { + return length2 + restType.target.fixedLength - (restType.target.combinedFlags & 12 /* Variable */ ? 0 : 1); + } + } + return length2; + } + function getMinArgumentCount(signature, flags) { + const strongArityForUntypedJS = flags & 1 /* StrongArityForUntypedJS */; + const voidIsNonOptional = flags & 2 /* VoidIsNonOptional */; + if (voidIsNonOptional || signature.resolvedMinArgumentCount === void 0) { + let minArgumentCount; + if (signatureHasRestParameter(signature)) { + const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + const firstOptionalIndex = findIndex(restType.target.elementFlags, (f) => !(f & 1 /* Required */)); + const requiredCount = firstOptionalIndex < 0 ? restType.target.fixedLength : firstOptionalIndex; + if (requiredCount > 0) { + minArgumentCount = signature.parameters.length - 1 + requiredCount; + } + } + } + if (minArgumentCount === void 0) { + if (!strongArityForUntypedJS && signature.flags & 32 /* IsUntypedSignatureInJSFile */) { + return 0; + } + minArgumentCount = signature.minArgumentCount; + } + if (voidIsNonOptional) { + return minArgumentCount; + } + for (let i = minArgumentCount - 1; i >= 0; i--) { + const type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & 131072 /* Never */) { + break; + } + minArgumentCount = i; + } + signature.resolvedMinArgumentCount = minArgumentCount; + } + return signature.resolvedMinArgumentCount; + } + function hasEffectiveRestParameter(signature) { + if (signatureHasRestParameter(signature)) { + const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || !!(restType.target.combinedFlags & 12 /* Variable */); + } + return false; + } + function getEffectiveRestType(signature) { + if (signatureHasRestParameter(signature)) { + const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (!isTupleType(restType)) { + return isTypeAny(restType) ? anyArrayType : restType; + } + if (restType.target.combinedFlags & 12 /* Variable */) { + return sliceTupleType(restType, restType.target.fixedLength); + } + } + return void 0; + } + function getNonArrayRestType(signature) { + const restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : void 0; + } + function getTypeOfFirstParameterOfSignature(signature) { + return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); + } + function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; + } + function inferFromAnnotatedParameters(signature, context, inferenceContext) { + const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); + for (let i = 0; i < len; i++) { + const declaration = signature.parameters[i].valueDeclaration; + const typeNode = getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + const source = addOptionality( + getTypeFromTypeNode(typeNode), + /*isProperty*/ + false, + isOptionalDeclaration(declaration) + ); + const target = getTypeAtPosition(context, i); + inferTypes(inferenceContext.inferences, source, target); + } + } + } + function assignContextualParameterTypes(signature, context) { + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } else { + return; + } + } + if (context.thisParameter) { + const parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType( + context.thisParameter, + /*type*/ + void 0 + ); + } + assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); + for (let i = 0; i < len; i++) { + const parameter = signature.parameters[i]; + const declaration = parameter.valueDeclaration; + if (!getEffectiveTypeAnnotationNode(declaration)) { + let type = tryGetTypeAtPosition(context, i); + if (type && declaration.initializer) { + let initializerType = checkDeclarationInitializer(declaration, 0 /* Normal */); + if (!isTypeAssignableTo(initializerType, type) && isTypeAssignableTo(type, initializerType = widenTypeInferredFromInitializer(declaration, initializerType))) { + type = initializerType; + } + } + assignParameterType(parameter, type); + } + } + if (signatureHasRestParameter(signature)) { + const parameter = last(signature.parameters); + if (parameter.valueDeclaration ? !getEffectiveTypeAnnotationNode(parameter.valueDeclaration) : !!(getCheckFlags(parameter) & 65536 /* DeferredType */)) { + const contextualParameterType = getRestTypeAtPosition(context, len); + assignParameterType(parameter, contextualParameterType); + } + } + } + function assignNonContextualParameterTypes(signature) { + if (signature.thisParameter) { + assignParameterType(signature.thisParameter); + } + for (const parameter of signature.parameters) { + assignParameterType(parameter); + } + } + function assignParameterType(parameter, contextualType) { + const links = getSymbolLinks(parameter); + if (!links.type) { + const declaration = parameter.valueDeclaration; + links.type = addOptionality( + contextualType || (declaration ? getWidenedTypeForVariableLikeDeclaration( + declaration, + /*reportErrors*/ + true + ) : getTypeOfSymbol(parameter)), + /*isProperty*/ + false, + /*isOptional*/ + !!declaration && !declaration.initializer && isOptionalDeclaration(declaration) + ); + if (declaration && declaration.name.kind !== 80 /* Identifier */) { + if (links.type === unknownType) { + links.type = getTypeFromBindingPattern(declaration.name); + } + assignBindingElementTypes(declaration.name, links.type); + } + } else if (contextualType) { + Debug.assertEqual(links.type, contextualType, "Parameter symbol already has a cached type which differs from newly assigned type"); + } + } + function assignBindingElementTypes(pattern, parentType) { + for (const element of pattern.elements) { + if (!isOmittedExpression(element)) { + const type = getBindingElementTypeFromParentType( + element, + parentType, + /*noTupleBoundsCheck*/ + false + ); + if (element.name.kind === 80 /* Identifier */) { + getSymbolLinks(getSymbolOfDeclaration(element)).type = type; + } else { + assignBindingElementTypes(element.name, type); + } + } + } + } + function createClassDecoratorContextType(classType) { + return tryCreateTypeReference(getGlobalClassDecoratorContextType( + /*reportErrors*/ + true + ), [classType]); + } + function createClassMethodDecoratorContextType(thisType, valueType) { + return tryCreateTypeReference(getGlobalClassMethodDecoratorContextType( + /*reportErrors*/ + true + ), [thisType, valueType]); + } + function createClassGetterDecoratorContextType(thisType, valueType) { + return tryCreateTypeReference(getGlobalClassGetterDecoratorContextType( + /*reportErrors*/ + true + ), [thisType, valueType]); + } + function createClassSetterDecoratorContextType(thisType, valueType) { + return tryCreateTypeReference(getGlobalClassSetterDecoratorContextType( + /*reportErrors*/ + true + ), [thisType, valueType]); + } + function createClassAccessorDecoratorContextType(thisType, valueType) { + return tryCreateTypeReference(getGlobalClassAccessorDecoratorContextType( + /*reportErrors*/ + true + ), [thisType, valueType]); + } + function createClassFieldDecoratorContextType(thisType, valueType) { + return tryCreateTypeReference(getGlobalClassFieldDecoratorContextType( + /*reportErrors*/ + true + ), [thisType, valueType]); + } + function getClassMemberDecoratorContextOverrideType(nameType, isPrivate, isStatic2) { + const key = `${isPrivate ? "p" : "P"}${isStatic2 ? "s" : "S"}${nameType.id}`; + let overrideType = decoratorContextOverrideTypeCache.get(key); + if (!overrideType) { + const members = createSymbolTable(); + members.set("name", createProperty("name", nameType)); + members.set("private", createProperty("private", isPrivate ? trueType : falseType)); + members.set("static", createProperty("static", isStatic2 ? trueType : falseType)); + overrideType = createAnonymousType( + /*symbol*/ + void 0, + members, + emptyArray, + emptyArray, + emptyArray + ); + decoratorContextOverrideTypeCache.set(key, overrideType); + } + return overrideType; + } + function createClassMemberDecoratorContextTypeForNode(node, thisType, valueType) { + const isStatic2 = hasStaticModifier(node); + const isPrivate = isPrivateIdentifier(node.name); + const nameType = isPrivate ? getStringLiteralType(idText(node.name)) : getLiteralTypeFromPropertyName(node.name); + const contextType = isMethodDeclaration(node) ? createClassMethodDecoratorContextType(thisType, valueType) : isGetAccessorDeclaration(node) ? createClassGetterDecoratorContextType(thisType, valueType) : isSetAccessorDeclaration(node) ? createClassSetterDecoratorContextType(thisType, valueType) : isAutoAccessorPropertyDeclaration(node) ? createClassAccessorDecoratorContextType(thisType, valueType) : isPropertyDeclaration(node) ? createClassFieldDecoratorContextType(thisType, valueType) : Debug.failBadSyntaxKind(node); + const overrideType = getClassMemberDecoratorContextOverrideType(nameType, isPrivate, isStatic2); + return getIntersectionType([contextType, overrideType]); + } + function createClassAccessorDecoratorTargetType(thisType, valueType) { + return tryCreateTypeReference(getGlobalClassAccessorDecoratorTargetType( + /*reportErrors*/ + true + ), [thisType, valueType]); + } + function createClassAccessorDecoratorResultType(thisType, valueType) { + return tryCreateTypeReference(getGlobalClassAccessorDecoratorResultType( + /*reportErrors*/ + true + ), [thisType, valueType]); + } + function createClassFieldDecoratorInitializerMutatorType(thisType, valueType) { + const thisParam = createParameter("this", thisType); + const valueParam = createParameter("value", valueType); + return createFunctionType( + /*typeParameters*/ + void 0, + thisParam, + [valueParam], + valueType, + /*typePredicate*/ + void 0, + 1 + ); + } + function createESDecoratorCallSignature(targetType, contextType, nonOptionalReturnType) { + const targetParam = createParameter("target", targetType); + const contextParam = createParameter("context", contextType); + const returnType = getUnionType([nonOptionalReturnType, voidType]); + return createCallSignature( + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + [targetParam, contextParam], + returnType + ); + } + function getESDecoratorCallSignature(decorator) { + const { parent } = decorator; + const links = getNodeLinks(parent); + if (!links.decoratorSignature) { + links.decoratorSignature = anySignature; + switch (parent.kind) { + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: { + const node = parent; + const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node)); + const contextType = createClassDecoratorContextType(targetType); + links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, targetType); + break; + } + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: { + const node = parent; + if (!isClassLike(node.parent)) break; + const valueType = isMethodDeclaration(node) ? getOrCreateTypeFromSignature(getSignatureFromDeclaration(node)) : getTypeOfNode(node); + const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent)); + const targetType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType; + const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType); + const returnType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType; + links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType); + break; + } + case 172 /* PropertyDeclaration */: { + const node = parent; + if (!isClassLike(node.parent)) break; + const valueType = getTypeOfNode(node); + const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent)); + const targetType = hasAccessorModifier(node) ? createClassAccessorDecoratorTargetType(thisType, valueType) : undefinedType; + const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType); + const returnType = hasAccessorModifier(node) ? createClassAccessorDecoratorResultType(thisType, valueType) : createClassFieldDecoratorInitializerMutatorType(thisType, valueType); + links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType); + break; + } + } + } + return links.decoratorSignature === anySignature ? void 0 : links.decoratorSignature; + } + function getLegacyDecoratorCallSignature(decorator) { + const { parent } = decorator; + const links = getNodeLinks(parent); + if (!links.decoratorSignature) { + links.decoratorSignature = anySignature; + switch (parent.kind) { + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: { + const node = parent; + const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node)); + const targetParam = createParameter("target", targetType); + links.decoratorSignature = createCallSignature( + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + [targetParam], + getUnionType([targetType, voidType]) + ); + break; + } + case 169 /* Parameter */: { + const node = parent; + if (!isConstructorDeclaration(node.parent) && !(isMethodDeclaration(node.parent) || isSetAccessorDeclaration(node.parent) && isClassLike(node.parent.parent))) { + break; + } + if (getThisParameter(node.parent) === node) { + break; + } + const index = getThisParameter(node.parent) ? node.parent.parameters.indexOf(node) - 1 : node.parent.parameters.indexOf(node); + Debug.assert(index >= 0); + const targetType = isConstructorDeclaration(node.parent) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent.parent)) : getParentTypeOfClassElement(node.parent); + const keyType = isConstructorDeclaration(node.parent) ? undefinedType : getClassElementPropertyKeyType(node.parent); + const indexType = getNumberLiteralType(index); + const targetParam = createParameter("target", targetType); + const keyParam = createParameter("propertyKey", keyType); + const indexParam = createParameter("parameterIndex", indexType); + links.decoratorSignature = createCallSignature( + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + [targetParam, keyParam, indexParam], + voidType + ); + break; + } + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 172 /* PropertyDeclaration */: { + const node = parent; + if (!isClassLike(node.parent)) break; + const targetType = getParentTypeOfClassElement(node); + const targetParam = createParameter("target", targetType); + const keyType = getClassElementPropertyKeyType(node); + const keyParam = createParameter("propertyKey", keyType); + const returnType = isPropertyDeclaration(node) ? voidType : createTypedPropertyDescriptorType(getTypeOfNode(node)); + const hasPropDesc = !isPropertyDeclaration(parent) || hasAccessorModifier(parent); + if (hasPropDesc) { + const descriptorType = createTypedPropertyDescriptorType(getTypeOfNode(node)); + const descriptorParam = createParameter("descriptor", descriptorType); + links.decoratorSignature = createCallSignature( + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + [targetParam, keyParam, descriptorParam], + getUnionType([returnType, voidType]) + ); + } else { + links.decoratorSignature = createCallSignature( + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + [targetParam, keyParam], + getUnionType([returnType, voidType]) + ); + } + break; + } + } + } + return links.decoratorSignature === anySignature ? void 0 : links.decoratorSignature; + } + function getDecoratorCallSignature(decorator) { + return legacyDecorators ? getLegacyDecoratorCallSignature(decorator) : getESDecoratorCallSignature(decorator); + } + function createPromiseType(promisedType) { + const globalPromiseType = getGlobalPromiseType( + /*reportErrors*/ + true + ); + if (globalPromiseType !== emptyGenericType) { + promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return unknownType; + } + function createPromiseLikeType(promisedType) { + const globalPromiseLikeType = getGlobalPromiseLikeType( + /*reportErrors*/ + true + ); + if (globalPromiseLikeType !== emptyGenericType) { + promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return unknownType; + } + function createPromiseReturnType(func, promisedType) { + const promiseType = createPromiseType(promisedType); + if (promiseType === unknownType) { + error( + func, + isImportCall(func) ? Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option + ); + return errorType; + } else if (!getGlobalPromiseConstructorSymbol( + /*reportErrors*/ + true + )) { + error( + func, + isImportCall(func) ? Diagnostics.A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option + ); + } + return promiseType; + } + function createNewTargetExpressionType(targetType) { + const symbol = createSymbol(0 /* None */, "NewTargetExpression"); + const targetPropertySymbol = createSymbol(4 /* Property */, "target", 8 /* Readonly */); + targetPropertySymbol.parent = symbol; + targetPropertySymbol.links.type = targetType; + const members = createSymbolTable([targetPropertySymbol]); + symbol.members = members; + return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray); + } + function getReturnTypeFromBody(func, checkMode) { + if (!func.body) { + return errorType; + } + const functionFlags = getFunctionFlags(func); + const isAsync = (functionFlags & 2 /* Async */) !== 0; + const isGenerator = (functionFlags & 1 /* Generator */) !== 0; + let returnType; + let yieldType; + let nextType; + let fallbackReturnType = voidType; + if (func.body.kind !== 241 /* Block */) { + returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */); + if (isAsync) { + returnType = unwrapAwaitedType(checkAwaitedType( + returnType, + /*withAlias*/ + false, + /*errorNode*/ + func, + Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + )); + } + } else if (isGenerator) { + const returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (!returnTypes) { + fallbackReturnType = neverType; + } else if (returnTypes.length > 0) { + returnType = getUnionType(returnTypes, 2 /* Subtype */); + } + const { yieldTypes, nextTypes } = checkAndAggregateYieldOperandTypes(func, checkMode); + yieldType = some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : void 0; + nextType = some(nextTypes) ? getIntersectionType(nextTypes) : void 0; + } else { + const types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (!types) { + return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, neverType) : neverType; + } + if (types.length === 0) { + const contextualReturnType = getContextualReturnType( + func, + /*contextFlags*/ + void 0 + ); + const returnType2 = contextualReturnType && (unwrapReturnType(contextualReturnType, functionFlags) || voidType).flags & 32768 /* Undefined */ ? undefinedType : voidType; + return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, returnType2) : ( + // Async function + returnType2 + ); + } + returnType = getUnionType(types, 2 /* Subtype */); + } + if (returnType || yieldType || nextType) { + if (yieldType) reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); + if (returnType) reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); + if (nextType) reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); + if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { + const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + const contextualType = !contextualSignature ? void 0 : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? void 0 : returnType : instantiateContextualType( + getReturnTypeOfSignature(contextualSignature), + func, + /*contextFlags*/ + void 0 + ); + if (isGenerator) { + yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync); + returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync); + nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync); + } else { + returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync); + } + } + if (yieldType) yieldType = getWidenedType(yieldType); + if (returnType) returnType = getWidenedType(returnType); + if (nextType) nextType = getWidenedType(nextType); + } + if (isGenerator) { + return createGeneratorType( + yieldType || neverType, + returnType || fallbackReturnType, + nextType || getContextualIterationType(2 /* Next */, func) || unknownType, + isAsync + ); + } else { + return isAsync ? createPromiseType(returnType || fallbackReturnType) : returnType || fallbackReturnType; + } + } + function createGeneratorType(yieldType, returnType, nextType, isAsyncGenerator) { + const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; + const globalGeneratorType = resolver.getGlobalGeneratorType( + /*reportErrors*/ + false + ); + yieldType = resolver.resolveIterationType( + yieldType, + /*errorNode*/ + void 0 + ) || unknownType; + returnType = resolver.resolveIterationType( + returnType, + /*errorNode*/ + void 0 + ) || unknownType; + if (globalGeneratorType === emptyGenericType) { + const globalIterableIteratorType = resolver.getGlobalIterableIteratorType( + /*reportErrors*/ + false + ); + if (globalIterableIteratorType !== emptyGenericType) { + return createTypeFromGenericGlobalType(globalIterableIteratorType, [yieldType, returnType, nextType]); + } + resolver.getGlobalIterableIteratorType( + /*reportErrors*/ + true + ); + return emptyObjectType; + } + return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]); + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + const yieldTypes = []; + const nextTypes = []; + const isAsync = (getFunctionFlags(func) & 2 /* Async */) !== 0; + forEachYieldExpression(func.body, (yieldExpression) => { + const yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType; + pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync)); + let nextType; + if (yieldExpression.asteriskToken) { + const iterationTypes = getIterationTypesOfIterable( + yieldExpressionType, + isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, + yieldExpression.expression + ); + nextType = iterationTypes && iterationTypes.nextType; + } else { + nextType = getContextualType( + yieldExpression, + /*contextFlags*/ + void 0 + ); + } + if (nextType) pushIfUnique(nextTypes, nextType); + }); + return { yieldTypes, nextTypes }; + } + function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) { + const errorNode = node.expression || node; + const yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType; + return !isAsync ? yieldedType : getAwaitedType( + yieldedType, + errorNode, + node.asteriskToken ? Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + ); + } + function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { + let facts = 0 /* None */; + for (let i = 0; i < witnesses.length; i++) { + const witness = i < start || i >= end ? witnesses[i] : void 0; + facts |= witness !== void 0 ? typeofNEFacts.get(witness) || 32768 /* TypeofNEHostObject */ : 0; + } + return facts; + } + function isExhaustiveSwitchStatement(node) { + const links = getNodeLinks(node); + if (links.isExhaustive === void 0) { + links.isExhaustive = 0; + const exhaustive = computeExhaustiveSwitchStatement(node); + if (links.isExhaustive === 0) { + links.isExhaustive = exhaustive; + } + } else if (links.isExhaustive === 0) { + links.isExhaustive = false; + } + return links.isExhaustive; + } + function computeExhaustiveSwitchStatement(node) { + if (node.expression.kind === 221 /* TypeOfExpression */) { + const witnesses = getSwitchClauseTypeOfWitnesses(node); + if (!witnesses) { + return false; + } + const operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); + const notEqualFacts = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); + if (operandConstraint.flags & 3 /* AnyOrUnknown */) { + return (556800 /* AllTypeofNE */ & notEqualFacts) === 556800 /* AllTypeofNE */; + } + return !someType(operandConstraint, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts); + } + const type = getBaseConstraintOrType(checkExpressionCached(node.expression)); + if (!isLiteralType(type)) { + return false; + } + const switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length || some(switchTypes, isNeitherUnitTypeNorNever)) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + return func.endFlowNode && isReachableFlowNode(func.endFlowNode); + } + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + const functionFlags = getFunctionFlags(func); + const aggregatedTypes = []; + let hasReturnWithNoExpression = functionHasImplicitReturn(func); + let hasReturnOfTypeNever = false; + forEachReturnStatement(func.body, (returnStatement) => { + let expr = returnStatement.expression; + if (expr) { + expr = skipParentheses( + expr, + /*excludeJSDocTypeAssertions*/ + true + ); + if (functionFlags & 2 /* Async */ && expr.kind === 223 /* AwaitExpression */) { + expr = skipParentheses( + expr.expression, + /*excludeJSDocTypeAssertions*/ + true + ); + } + if (expr.kind === 213 /* CallExpression */ && expr.expression.kind === 80 /* Identifier */ && checkExpressionCached(expr.expression).symbol === getMergedSymbol(func.symbol) && (!isFunctionExpressionOrArrowFunction(func.symbol.valueDeclaration) || isConstantReference(expr.expression))) { + hasReturnOfTypeNever = true; + return; + } + let type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */); + if (functionFlags & 2 /* Async */) { + type = unwrapAwaitedType(checkAwaitedType( + type, + /*withAlias*/ + false, + func, + Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + )); + } + if (type.flags & 131072 /* Never */) { + hasReturnOfTypeNever = true; + } + pushIfUnique(aggregatedTypes, type); + } else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { + return void 0; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && !(isJSConstructor(func) && aggregatedTypes.some((t) => t.symbol === func.symbol))) { + pushIfUnique(aggregatedTypes, undefinedType); + } + return aggregatedTypes; + } + function mayReturnNever(func) { + switch (func.kind) { + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + return true; + case 174 /* MethodDeclaration */: + return func.parent.kind === 210 /* ObjectLiteralExpression */; + default: + return false; + } + } + function getTypePredicateFromBody(func) { + switch (func.kind) { + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return void 0; + } + const functionFlags = getFunctionFlags(func); + if (functionFlags !== 0 /* Normal */) return void 0; + let singleReturn; + if (func.body && func.body.kind !== 241 /* Block */) { + singleReturn = func.body; + } else { + const bailedEarly = forEachReturnStatement(func.body, (returnStatement) => { + if (singleReturn || !returnStatement.expression) return true; + singleReturn = returnStatement.expression; + }); + if (bailedEarly || !singleReturn || functionHasImplicitReturn(func)) return void 0; + } + return checkIfExpressionRefinesAnyParameter(func, singleReturn); + } + function checkIfExpressionRefinesAnyParameter(func, expr) { + expr = skipParentheses( + expr, + /*excludeJSDocTypeAssertions*/ + true + ); + const returnType = checkExpressionCached(expr); + if (!(returnType.flags & 16 /* Boolean */)) return void 0; + return forEach(func.parameters, (param, i) => { + const initType = getTypeOfSymbol(param.symbol); + if (!initType || initType.flags & 16 /* Boolean */ || !isIdentifier(param.name) || isSymbolAssigned(param.symbol) || isRestParameter(param)) { + return; + } + const trueType2 = checkIfExpressionRefinesParameter(func, expr, param, initType); + if (trueType2) { + return createTypePredicate(1 /* Identifier */, unescapeLeadingUnderscores(param.name.escapedText), i, trueType2); + } + }); + } + function checkIfExpressionRefinesParameter(func, expr, param, initType) { + const antecedent = canHaveFlowNode(expr) && expr.flowNode || expr.parent.kind === 253 /* ReturnStatement */ && expr.parent.flowNode || createFlowNode( + 2 /* Start */, + /*node*/ + void 0, + /*antecedent*/ + void 0 + ); + const trueCondition = createFlowNode(32 /* TrueCondition */, expr, antecedent); + const trueType2 = getFlowTypeOfReference(param.name, initType, initType, func, trueCondition); + if (trueType2 === initType) return void 0; + const falseCondition = createFlowNode(64 /* FalseCondition */, expr, antecedent); + const falseSubtype = getFlowTypeOfReference(param.name, initType, trueType2, func, falseCondition); + return falseSubtype.flags & 131072 /* Never */ ? trueType2 : void 0; + } + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + addLazyDiagnostic(checkAllCodePathsInNonVoidFunctionReturnOrThrowDiagnostics); + return; + function checkAllCodePathsInNonVoidFunctionReturnOrThrowDiagnostics() { + const functionFlags = getFunctionFlags(func); + const type = returnType && unwrapReturnType(returnType, functionFlags); + if (type && (maybeTypeOfKind(type, 16384 /* Void */) || type.flags & (1 /* Any */ | 32768 /* Undefined */))) { + return; + } + if (func.kind === 173 /* MethodSignature */ || nodeIsMissing(func.body) || func.body.kind !== 241 /* Block */ || !functionHasImplicitReturn(func)) { + return; + } + const hasExplicitReturn = func.flags & 1024 /* HasExplicitReturn */; + const errorNode = getEffectiveReturnTypeNode(func) || func; + if (type && type.flags & 131072 /* Never */) { + error(errorNode, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } else if (type && !hasExplicitReturn) { + error(errorNode, Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value); + } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { + error(errorNode, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } else if (compilerOptions.noImplicitReturns) { + if (!type) { + if (!hasExplicitReturn) { + return; + } + const inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeUndefinedVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(errorNode, Diagnostics.Not_all_code_paths_return_a_value); + } + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node)); + checkNodeDeferred(node); + if (isFunctionExpression(node)) { + checkCollisionsForDeclarationName(node, node.name); + } + if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) { + if (!getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) { + const contextualSignature = getContextualSignature(node); + if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) { + const links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } + const returnType = getReturnTypeFromBody(node, checkMode); + const returnOnlySignature = createSignature( + /*declaration*/ + void 0, + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + emptyArray, + returnType, + /*resolvedTypePredicate*/ + void 0, + 0, + 64 /* IsNonInferrable */ + ); + const returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], emptyArray, emptyArray); + returnOnlyType.objectFlags |= 262144 /* NonInferrableType */; + return links.contextFreeType = returnOnlyType; + } + } + return anyFunctionType; + } + const hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 218 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } + contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return getTypeOfSymbol(getSymbolOfDeclaration(node)); + } + function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + const links = getNodeLinks(node); + if (!(links.flags & 64 /* ContextChecked */)) { + const contextualSignature = getContextualSignature(node); + if (!(links.flags & 64 /* ContextChecked */)) { + links.flags |= 64 /* ContextChecked */; + const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfDeclaration(node)), 0 /* Call */)); + if (!signature) { + return; + } + if (isContextSensitive(node)) { + if (contextualSignature) { + const inferenceContext = getInferenceContext(node); + let instantiatedContextualSignature; + if (checkMode && checkMode & 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); + const restType = getEffectiveRestType(contextualSignature); + if (restType && restType.flags & 262144 /* TypeParameter */) { + instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper); + } + } + instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } else { + assignNonContextualParameterTypes(signature); + } + } else if (contextualSignature && !node.typeParameters && contextualSignature.parameters.length > node.parameters.length) { + const inferenceContext = getInferenceContext(node); + if (checkMode && checkMode & 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); + } + } + if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { + const returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + checkSignatureDeclaration(node); + } + } + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node)); + const functionFlags = getFunctionFlags(node); + const returnType = getReturnTypeFromAnnotation(node); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + if (node.body) { + if (!getEffectiveReturnTypeNode(node)) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 241 /* Block */) { + checkSourceElement(node.body); + } else { + const exprType = checkExpression(node.body); + const returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); + if (returnOrPromisedType) { + checkReturnExpression(node, returnOrPromisedType, node.body, node.body, exprType); + } + } + } + } + function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid = false) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { + const awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type); + errorAndMaybeSuggestAwait( + operand, + !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), + diagnostic + ); + return false; + } + return true; + } + function isReadonlyAssignmentDeclaration(d) { + if (!isCallExpression(d)) { + return false; + } + if (!isBindableObjectDefinePropertyCall(d)) { + return false; + } + const objectLitType = checkExpressionCached(d.arguments[2]); + const valueType = getTypeOfPropertyOfType(objectLitType, "value"); + if (valueType) { + const writableProp = getPropertyOfType(objectLitType, "writable"); + const writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + if (writableProp && writableProp.valueDeclaration && isPropertyAssignment(writableProp.valueDeclaration)) { + const initializer = writableProp.valueDeclaration.initializer; + const rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + const setProp = getPropertyOfType(objectLitType, "set"); + return !setProp; + } + function isReadonlySymbol(symbol) { + return !!(getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 8 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* Constant */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */ || some(symbol.declarations, isReadonlyAssignmentDeclaration)); + } + function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) { + var _a, _b; + if (assignmentKind === 0 /* None */) { + return false; + } + if (isReadonlySymbol(symbol)) { + if (symbol.flags & 4 /* Property */ && isAccessExpression(expr) && expr.expression.kind === 110 /* ThisKeyword */) { + const ctor = getControlFlowContainer(expr); + if (!(ctor && (ctor.kind === 176 /* Constructor */ || isJSConstructor(ctor)))) { + return true; + } + if (symbol.valueDeclaration) { + const isAssignmentDeclaration2 = isBinaryExpression(symbol.valueDeclaration); + const isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent; + const isLocalParameterProperty = ctor === symbol.valueDeclaration.parent; + const isLocalThisPropertyAssignment = isAssignmentDeclaration2 && ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) === ctor.parent; + const isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration2 && ((_b = symbol.parent) == null ? void 0 : _b.valueDeclaration) === ctor; + const isWriteableSymbol = isLocalPropertyDeclaration || isLocalParameterProperty || isLocalThisPropertyAssignment || isLocalThisPropertyAssignmentConstructorFunction; + return !isWriteableSymbol; + } + } + return true; + } + if (isAccessExpression(expr)) { + const node = skipParentheses(expr.expression); + if (node.kind === 80 /* Identifier */) { + const symbol2 = getNodeLinks(node).resolvedSymbol; + if (symbol2.flags & 2097152 /* Alias */) { + const declaration = getDeclarationOfAliasSymbol(symbol2); + return !!declaration && declaration.kind === 274 /* NamespaceImport */; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) { + const node = skipOuterExpressions(expr, 38 /* Assertions */ | 1 /* Parentheses */); + if (node.kind !== 80 /* Identifier */ && !isAccessExpression(node)) { + error(expr, invalidReferenceMessage); + return false; + } + if (node.flags & 64 /* OptionalChain */) { + error(expr, invalidOptionalChainMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + const expr = skipParentheses(node.expression); + if (!isAccessExpression(expr)) { + error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + if (isPropertyAccessExpression(expr) && isPrivateIdentifier(expr.name)) { + error(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier); + } + const links = getNodeLinks(expr); + const symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol) { + if (isReadonlySymbol(symbol)) { + error(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } else { + checkDeleteExpressionMustBeOptional(expr, symbol); + } + } + return booleanType; + } + function checkDeleteExpressionMustBeOptional(expr, symbol) { + const type = getTypeOfSymbol(symbol); + if (strictNullChecks && !(type.flags & (3 /* AnyOrUnknown */ | 131072 /* Never */)) && !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* Optional */ : hasTypeFacts(type, 16777216 /* IsUndefined */))) { + error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_optional); + } + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkNodeDeferred(node); + return undefinedWideningType; + } + function checkAwaitGrammar(node) { + let hasError = false; + const container = getContainingFunctionOrClassStaticBlock(node); + if (container && isClassStaticBlockDeclaration(container)) { + const message = isAwaitExpression(node) ? Diagnostics.await_expression_cannot_be_used_inside_a_class_static_block : Diagnostics.await_using_statements_cannot_be_used_inside_a_class_static_block; + error(node, message); + hasError = true; + } else if (!(node.flags & 65536 /* AwaitContext */)) { + if (isInTopLevelContext(node)) { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + let span; + if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { + span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); + const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module : Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module; + const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message); + diagnostics.add(diagnostic); + hasError = true; + } + switch (moduleKind) { + case 100 /* Node16 */: + case 101 /* Node18 */: + case 199 /* NodeNext */: + if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) { + span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); + diagnostics.add( + createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level) + ); + hasError = true; + break; + } + // fallthrough + case 7 /* ES2022 */: + case 99 /* ESNext */: + case 200 /* Preserve */: + case 4 /* System */: + if (languageVersion >= 4 /* ES2017 */) { + break; + } + // fallthrough + default: + span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); + const message = isAwaitExpression(node) ? Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_node18_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher : Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_node18_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher; + diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message)); + hasError = true; + break; + } + } + } else { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); + const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules : Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules; + const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message); + if (container && container.kind !== 176 /* Constructor */ && (getFunctionFlags(container) & 2 /* Async */) === 0) { + const relatedInfo = createDiagnosticForNode(container, Diagnostics.Did_you_mean_to_mark_this_function_as_async); + addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + hasError = true; + } + } + } + if (isAwaitExpression(node) && isInParameterInitializerBeforeContainingFunction(node)) { + error(node, Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + hasError = true; + } + return hasError; + } + function checkAwaitExpression(node) { + addLazyDiagnostic(() => checkAwaitGrammar(node)); + const operandType = checkExpression(node.expression); + const awaitedType = checkAwaitedType( + operandType, + /*withAlias*/ + true, + node, + Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + ); + if (awaitedType === operandType && !isErrorType(awaitedType) && !(operandType.flags & 3 /* AnyOrUnknown */)) { + addErrorOrSuggestion( + /*isError*/ + false, + createDiagnosticForNode(node, Diagnostics.await_has_no_effect_on_the_type_of_this_expression) + ); + } + return awaitedType; + } + function checkPrefixUnaryExpression(node) { + const operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + switch (node.operand.kind) { + case 9 /* NumericLiteral */: + switch (node.operator) { + case 41 /* MinusToken */: + return getFreshTypeOfLiteralType(getNumberLiteralType(-node.operand.text)); + case 40 /* PlusToken */: + return getFreshTypeOfLiteralType(getNumberLiteralType(+node.operand.text)); + } + break; + case 10 /* BigIntLiteral */: + if (node.operator === 41 /* MinusToken */) { + return getFreshTypeOfLiteralType(getBigIntLiteralType({ + negative: true, + base10Value: parsePseudoBigInt(node.operand.text) + })); + } + } + switch (node.operator) { + case 40 /* PlusToken */: + case 41 /* MinusToken */: + case 55 /* TildeToken */: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 12288 /* ESSymbolLike */)) { + error(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator)); + } + if (node.operator === 40 /* PlusToken */) { + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* BigIntLike */)) { + error(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); + } + return numberType; + } + return getUnaryResultType(operandType); + case 54 /* ExclamationToken */: + checkTruthinessOfType(operandType, node.operand); + const facts = getTypeFacts(operandType, 4194304 /* Truthy */ | 8388608 /* Falsy */); + return facts === 4194304 /* Truthy */ ? falseType : facts === 8388608 /* Falsy */ ? trueType : booleanType; + case 46 /* PlusPlusToken */: + case 47 /* MinusMinusToken */: + const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + if (ok) { + checkReferenceExpression( + node.operand, + Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, + Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access + ); + } + return getUnaryResultType(operandType); + } + return errorType; + } + function checkPostfixUnaryExpression(node) { + const operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + const ok = checkArithmeticOperandType( + node.operand, + checkNonNullType(operandType, node.operand), + Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type + ); + if (ok) { + checkReferenceExpression( + node.operand, + Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, + Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access + ); + } + return getUnaryResultType(operandType); + } + function getUnaryResultType(operandType) { + if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) { + return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) ? numberOrBigIntType : bigintType; + } + return numberType; + } + function maybeTypeOfKindConsideringBaseConstraint(type, kind) { + if (maybeTypeOfKind(type, kind)) { + return true; + } + const baseConstraint = getBaseConstraintOrType(type); + return !!baseConstraint && maybeTypeOfKind(baseConstraint, kind); + } + function maybeTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 3145728 /* UnionOrIntersection */) { + const types = type.types; + for (const t of types) { + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeAssignableToKind(source, kind, strict) { + if (source.flags & kind) { + return true; + } + if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) { + return false; + } + return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || !!(kind & 402653316 /* StringLike */) && isTypeAssignableTo(source, stringType) || !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); + } + function allTypesAssignableToKind(source, kind, strict) { + return source.flags & 1048576 /* Union */ ? every(source.types, (subType) => allTypesAssignableToKind(subType, kind, strict)) : isTypeAssignableToKind(source, kind, strict); + } + function isConstEnumObjectType(type) { + return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128 /* ConstEnum */) !== 0; + } + function getSymbolHasInstanceMethodOfObjectType(type) { + const hasInstancePropertyName = getPropertyNameForKnownSymbolName("hasInstance"); + if (allTypesAssignableToKind(type, 67108864 /* NonPrimitive */)) { + const hasInstanceProperty = getPropertyOfType(type, hasInstancePropertyName); + if (hasInstanceProperty) { + const hasInstancePropertyType = getTypeOfSymbol(hasInstanceProperty); + if (hasInstancePropertyType && getSignaturesOfType(hasInstancePropertyType, 0 /* Call */).length !== 0) { + return hasInstancePropertyType; + } + } + } + } + function checkInstanceOfExpression(left, right, leftType, rightType, checkMode) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAny(leftType) && allTypesAssignableToKind(leftType, 402784252 /* Primitive */)) { + error(left, Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + Debug.assert(isInstanceOfExpression(left.parent)); + const signature = getResolvedSignature( + left.parent, + /*candidatesOutArray*/ + void 0, + checkMode + ); + if (signature === resolvingSignature) { + return silentNeverType; + } + const returnType = getReturnTypeOfSignature(signature); + checkTypeAssignableTo(returnType, booleanType, right, Diagnostics.An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_hand_side_of_an_instanceof_expression); + return booleanType; + } + function hasEmptyObjectIntersection(type) { + return someType(type, (t) => t === unknownEmptyObjectType || !!(t.flags & 2097152 /* Intersection */) && isEmptyAnonymousObjectType(getBaseConstraintOrType(t))); + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (isPrivateIdentifier(left)) { + if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) { + checkExternalEmitHelpers(left, 2097152 /* ClassPrivateFieldIn */); + } + if (!getNodeLinks(left).resolvedSymbol && getContainingClass(left)) { + const isUncheckedJS = isUncheckedJSSuggestion( + left, + rightType.symbol, + /*excludeClasses*/ + true + ); + reportNonexistentProperty(left, rightType, isUncheckedJS); + } + } else { + checkTypeAssignableTo(checkNonNullType(leftType, left), stringNumberSymbolType, left); + } + if (checkTypeAssignableTo(checkNonNullType(rightType, right), nonPrimitiveType, right)) { + if (hasEmptyObjectIntersection(rightType)) { + error(right, Diagnostics.Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operator, typeToString(rightType)); + } + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { + const properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } + for (let i = 0; i < properties.length; i++) { + checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis); + } + return sourceType; + } + function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis = false) { + const properties = node.properties; + const property = properties[propertyIndex]; + if (property.kind === 303 /* PropertyAssignment */ || property.kind === 304 /* ShorthandPropertyAssignment */) { + const name = property.name; + const exprType = getLiteralTypeFromPropertyName(name); + if (isTypeUsableAsPropertyName(exprType)) { + const text = getPropertyNameFromType(exprType); + const prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility( + property, + /*isSuper*/ + false, + /*writing*/ + true, + objectLiteralType, + prop + ); + } + } + const elementType = getIndexedAccessType(objectLiteralType, exprType, 32 /* ExpressionPosition */ | (hasDefaultValue(property) ? 16 /* AllowMissing */ : 0), name); + const type = getFlowTypeOfDestructuring(property, elementType); + return checkDestructuringAssignment(property.kind === 304 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + } else if (property.kind === 305 /* SpreadAssignment */) { + if (propertyIndex < properties.length - 1) { + error(property, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } else { + if (languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + const nonRestNames = []; + if (allProperties) { + for (const otherProperty of allProperties) { + if (!isSpreadAssignment(otherProperty)) { + nonRestNames.push(otherProperty.name); + } + } + } + const type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + checkGrammarForDisallowedTrailingComma(allProperties, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + return checkDestructuringAssignment(property.expression, type); + } + } else { + error(property, Diagnostics.Property_assignment_expected); + } + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + const elements = node.elements; + if (languageVersion < LanguageFeatureMinimumTarget.DestructuringAssignment && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + const possiblyOutOfBoundsType = checkIteratedTypeOrElementType(65 /* Destructuring */ | 128 /* PossiblyOutOfBounds */, sourceType, undefinedType, node) || errorType; + let inBoundsType = compilerOptions.noUncheckedIndexedAccess ? void 0 : possiblyOutOfBoundsType; + for (let i = 0; i < elements.length; i++) { + let type = possiblyOutOfBoundsType; + if (node.elements[i].kind === 230 /* SpreadElement */) { + type = inBoundsType = inBoundsType ?? (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType); + } + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + const elements = node.elements; + const element = elements[elementIndex]; + if (element.kind !== 232 /* OmittedExpression */) { + if (element.kind !== 230 /* SpreadElement */) { + const indexType = getNumberLiteralType(elementIndex); + if (isArrayLikeType(sourceType)) { + const accessFlags = 32 /* ExpressionPosition */ | (hasDefaultValue(element) ? 16 /* AllowMissing */ : 0); + const elementType2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, accessFlags, createSyntheticExpression(element, indexType)) || errorType; + const assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType2, 524288 /* NEUndefined */) : elementType2; + const type = getFlowTypeOfDestructuring(element, assignedType); + return checkDestructuringAssignment(element, type, checkMode); + } + return checkDestructuringAssignment(element, elementType, checkMode); + } + if (elementIndex < elements.length - 1) { + error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } else { + const restExpression = element.expression; + if (restExpression.kind === 226 /* BinaryExpression */ && restExpression.operatorToken.kind === 64 /* EqualsToken */) { + error(restExpression.operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); + } else { + checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + const type = everyType(sourceType, isTupleType) ? mapType(sourceType, (t) => sliceTupleType(t, elementIndex)) : createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); + } + } + } + return void 0; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { + let target; + if (exprOrAssignment.kind === 304 /* ShorthandPropertyAssignment */) { + const prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + if (strictNullChecks && !hasTypeFacts(checkExpression(prop.objectAssignmentInitializer), 16777216 /* IsUndefined */)) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } else { + target = exprOrAssignment; + } + if (target.kind === 226 /* BinaryExpression */ && target.operatorToken.kind === 64 /* EqualsToken */) { + checkBinaryExpression(target, checkMode); + target = target.left; + if (strictNullChecks) { + sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); + } + } + if (target.kind === 210 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); + } + if (target.kind === 209 /* ArrayLiteralExpression */) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + const targetType = checkExpression(target, checkMode); + const error2 = target.parent.kind === 305 /* SpreadAssignment */ ? Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + const optionalError = target.parent.kind === 305 /* SpreadAssignment */ ? Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; + if (checkReferenceExpression(target, error2, optionalError)) { + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); + } + if (isPrivateIdentifierPropertyAccessExpression(target)) { + checkExternalEmitHelpers(target.parent, 1048576 /* ClassPrivateFieldSet */); + } + return sourceType; + } + function isSideEffectFree(node) { + node = skipParentheses(node); + switch (node.kind) { + case 80 /* Identifier */: + case 11 /* StringLiteral */: + case 14 /* RegularExpressionLiteral */: + case 215 /* TaggedTemplateExpression */: + case 228 /* TemplateExpression */: + case 15 /* NoSubstitutionTemplateLiteral */: + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + case 106 /* NullKeyword */: + case 157 /* UndefinedKeyword */: + case 218 /* FunctionExpression */: + case 231 /* ClassExpression */: + case 219 /* ArrowFunction */: + case 209 /* ArrayLiteralExpression */: + case 210 /* ObjectLiteralExpression */: + case 221 /* TypeOfExpression */: + case 235 /* NonNullExpression */: + case 285 /* JsxSelfClosingElement */: + case 284 /* JsxElement */: + return true; + case 227 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); + case 226 /* BinaryExpression */: + if (isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && isSideEffectFree(node.right); + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + switch (node.operator) { + case 54 /* ExclamationToken */: + case 40 /* PlusToken */: + case 41 /* MinusToken */: + case 55 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 222 /* VoidExpression */: + // Explicit opt-out + case 216 /* TypeAssertionExpression */: + // Not SEF, but can produce useful type warnings + case 234 /* AsExpression */: + // Not SEF, but can produce useful type warnings + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function createCheckBinaryExpression() { + const trampoline = createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return (node, checkMode) => { + const result = trampoline(node, checkMode); + Debug.assertIsDefined(result); + return result; + }; + function onEnter(node, state, checkMode) { + if (state) { + state.stackIndex++; + state.skip = false; + setLeftType( + state, + /*type*/ + void 0 + ); + setLastResult( + state, + /*type*/ + void 0 + ); + } else { + state = { + checkMode, + skip: false, + stackIndex: 0, + typeStack: [void 0, void 0] + }; + } + if (isInJSFile(node) && getAssignedExpandoInitializer(node)) { + state.skip = true; + setLastResult(state, checkExpression(node.right, checkMode)); + return state; + } + checkNullishCoalesceOperands(node); + const operator = node.operatorToken.kind; + if (operator === 64 /* EqualsToken */ && (node.left.kind === 210 /* ObjectLiteralExpression */ || node.left.kind === 209 /* ArrayLiteralExpression */)) { + state.skip = true; + setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 110 /* ThisKeyword */)); + return state; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + const leftType = getLastResult(state); + Debug.assertIsDefined(leftType); + setLeftType(state, leftType); + setLastResult( + state, + /*type*/ + void 0 + ); + const operator = operatorToken.kind; + if (isLogicalOrCoalescingBinaryOperator(operator)) { + let parent = node.parent; + while (parent.kind === 217 /* ParenthesizedExpression */ || isLogicalOrCoalescingBinaryExpression(parent)) { + parent = parent.parent; + } + if (operator === 56 /* AmpersandAmpersandToken */ || isIfStatement(parent)) { + checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.left, leftType, isIfStatement(parent) ? parent.thenStatement : void 0); + } + if (isBinaryLogicalOperator(operator)) { + checkTruthinessOfType(leftType, node.left); + } + } + } + } + function onRight(right, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, right); + } + } + function onExit(node, state) { + let result; + if (state.skip) { + result = getLastResult(state); + } else { + const leftType = getLeftType(state); + Debug.assertIsDefined(leftType); + const rightType = getLastResult(state); + Debug.assertIsDefined(rightType); + result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, state.checkMode, node); + } + state.skip = false; + setLeftType( + state, + /*type*/ + void 0 + ); + setLastResult( + state, + /*type*/ + void 0 + ); + state.stackIndex--; + return result; + } + function foldState(state, result, _side) { + setLastResult(state, result); + return state; + } + function maybeCheckExpression(state, node) { + if (isBinaryExpression(node)) { + return node; + } + setLastResult(state, checkExpression(node, state.checkMode)); + } + function getLeftType(state) { + return state.typeStack[state.stackIndex]; + } + function setLeftType(state, type) { + state.typeStack[state.stackIndex] = type; + } + function getLastResult(state) { + return state.typeStack[state.stackIndex + 1]; + } + function setLastResult(state, type) { + state.typeStack[state.stackIndex + 1] = type; + } + } + function checkNullishCoalesceOperands(node) { + const { left, operatorToken, right } = node; + if (operatorToken.kind === 61 /* QuestionQuestionToken */) { + if (isBinaryExpression(left) && (left.operatorToken.kind === 57 /* BarBarToken */ || left.operatorToken.kind === 56 /* AmpersandAmpersandToken */)) { + grammarErrorOnNode(left, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(left.operatorToken.kind), tokenToString(operatorToken.kind)); + } + if (isBinaryExpression(right) && (right.operatorToken.kind === 57 /* BarBarToken */ || right.operatorToken.kind === 56 /* AmpersandAmpersandToken */)) { + grammarErrorOnNode(right, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(right.operatorToken.kind), tokenToString(operatorToken.kind)); + } + const leftTarget = skipOuterExpressions(left, 63 /* All */); + const nullishSemantics = getSyntacticNullishnessSemantics(leftTarget); + if (nullishSemantics !== 3 /* Sometimes */) { + if (node.parent.kind === 226 /* BinaryExpression */) { + error(leftTarget, Diagnostics.This_binary_expression_is_never_nullish_Are_you_missing_parentheses); + } else { + if (nullishSemantics === 1 /* Always */) { + error(leftTarget, Diagnostics.This_expression_is_always_nullish); + } else { + error(leftTarget, Diagnostics.Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish); + } + } + } + } + } + function getSyntacticNullishnessSemantics(node) { + node = skipOuterExpressions(node); + switch (node.kind) { + case 223 /* AwaitExpression */: + case 213 /* CallExpression */: + case 215 /* TaggedTemplateExpression */: + case 212 /* ElementAccessExpression */: + case 236 /* MetaProperty */: + case 214 /* NewExpression */: + case 211 /* PropertyAccessExpression */: + case 229 /* YieldExpression */: + case 110 /* ThisKeyword */: + return 3 /* Sometimes */; + case 226 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 64 /* EqualsToken */: + case 61 /* QuestionQuestionToken */: + case 78 /* QuestionQuestionEqualsToken */: + case 57 /* BarBarToken */: + case 76 /* BarBarEqualsToken */: + case 56 /* AmpersandAmpersandToken */: + case 77 /* AmpersandAmpersandEqualsToken */: + return 3 /* Sometimes */; + case 28 /* CommaToken */: + return getSyntacticNullishnessSemantics(node.right); + } + return 2 /* Never */; + case 227 /* ConditionalExpression */: + return getSyntacticNullishnessSemantics(node.whenTrue) | getSyntacticNullishnessSemantics(node.whenFalse); + case 106 /* NullKeyword */: + return 1 /* Always */; + case 80 /* Identifier */: + if (getResolvedSymbol(node) === undefinedSymbol) { + return 1 /* Always */; + } + return 3 /* Sometimes */; + } + return 2 /* Never */; + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + const operator = operatorToken.kind; + if (operator === 64 /* EqualsToken */ && (left.kind === 210 /* ObjectLiteralExpression */ || left.kind === 209 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 110 /* ThisKeyword */); + } + let leftType; + if (isBinaryLogicalOperator(operator)) { + leftType = checkTruthinessExpression(left, checkMode); + } else { + leftType = checkExpression(left, checkMode); + } + const rightType = checkExpression(right, checkMode); + return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, checkMode, errorNode); + } + function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, checkMode, errorNode) { + const operator = operatorToken.kind; + switch (operator) { + case 42 /* AsteriskToken */: + case 43 /* AsteriskAsteriskToken */: + case 67 /* AsteriskEqualsToken */: + case 68 /* AsteriskAsteriskEqualsToken */: + case 44 /* SlashToken */: + case 69 /* SlashEqualsToken */: + case 45 /* PercentToken */: + case 70 /* PercentEqualsToken */: + case 41 /* MinusToken */: + case 66 /* MinusEqualsToken */: + case 48 /* LessThanLessThanToken */: + case 71 /* LessThanLessThanEqualsToken */: + case 49 /* GreaterThanGreaterThanToken */: + case 72 /* GreaterThanGreaterThanEqualsToken */: + case 50 /* GreaterThanGreaterThanGreaterThanToken */: + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 52 /* BarToken */: + case 75 /* BarEqualsToken */: + case 53 /* CaretToken */: + case 79 /* CaretEqualsToken */: + case 51 /* AmpersandToken */: + case 74 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + let suggestedOperator; + if (leftType.flags & 528 /* BooleanLike */ && rightType.flags & 528 /* BooleanLike */ && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== void 0) { + error(errorNode || operatorToken, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(operatorToken.kind), tokenToString(suggestedOperator)); + return numberType; + } else { + const leftOk = checkArithmeticOperandType( + left, + leftType, + Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, + /*isAwaitValid*/ + true + ); + const rightOk = checkArithmeticOperandType( + right, + rightType, + Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, + /*isAwaitValid*/ + true + ); + let resultType2; + if (isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */) || // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { + resultType2 = numberType; + } else if (bothAreBigIntLike(leftType, rightType)) { + switch (operator) { + case 50 /* GreaterThanGreaterThanGreaterThanToken */: + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + reportOperatorError(); + break; + case 43 /* AsteriskAsteriskToken */: + case 68 /* AsteriskAsteriskEqualsToken */: + if (languageVersion < 3 /* ES2016 */) { + error(errorNode, Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later); + } + } + resultType2 = bigintType; + } else { + reportOperatorError(bothAreBigIntLike); + resultType2 = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType2); + switch (operator) { + case 48 /* LessThanLessThanToken */: + case 71 /* LessThanLessThanEqualsToken */: + case 49 /* GreaterThanGreaterThanToken */: + case 72 /* GreaterThanGreaterThanEqualsToken */: + case 50 /* GreaterThanGreaterThanGreaterThanToken */: + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + const rhsEval = evaluate(right); + if (typeof rhsEval.value === "number" && Math.abs(rhsEval.value) >= 32) { + errorOrSuggestion( + isEnumMember(walkUpParenthesizedExpressions(right.parent.parent)), + // elevate from suggestion to error within an enum member + errorNode || operatorToken, + Diagnostics.This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2, + getTextOfNode(left), + tokenToString(operator), + rhsEval.value % 32 + ); + } + break; + default: + break; + } + } + return resultType2; + } + case 40 /* PlusToken */: + case 65 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeAssignableToKind(leftType, 402653316 /* StringLike */) && !isTypeAssignableToKind(rightType, 402653316 /* StringLike */)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + let resultType; + if (isTypeAssignableToKind( + leftType, + 296 /* NumberLike */, + /*strict*/ + true + ) && isTypeAssignableToKind( + rightType, + 296 /* NumberLike */, + /*strict*/ + true + )) { + resultType = numberType; + } else if (isTypeAssignableToKind( + leftType, + 2112 /* BigIntLike */, + /*strict*/ + true + ) && isTypeAssignableToKind( + rightType, + 2112 /* BigIntLike */, + /*strict*/ + true + )) { + resultType = bigintType; + } else if (isTypeAssignableToKind( + leftType, + 402653316 /* StringLike */, + /*strict*/ + true + ) || isTypeAssignableToKind( + rightType, + 402653316 /* StringLike */, + /*strict*/ + true + )) { + resultType = stringType; + } else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = isErrorType(leftType) || isErrorType(rightType) ? errorType : anyType; + } + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + if (!resultType) { + const closeEnoughKind = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 3 /* AnyOrUnknown */; + reportOperatorError( + (left2, right2) => isTypeAssignableToKind(left2, closeEnoughKind) && isTypeAssignableToKind(right2, closeEnoughKind) + ); + return anyType; + } + if (operator === 65 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 30 /* LessThanToken */: + case 32 /* GreaterThanToken */: + case 33 /* LessThanEqualsToken */: + case 34 /* GreaterThanEqualsToken */: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralTypeForComparison(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralTypeForComparison(checkNonNullType(rightType, right)); + reportOperatorErrorUnless((left2, right2) => { + if (isTypeAny(left2) || isTypeAny(right2)) { + return true; + } + const leftAssignableToNumber = isTypeAssignableTo(left2, numberOrBigIntType); + const rightAssignableToNumber = isTypeAssignableTo(right2, numberOrBigIntType); + return leftAssignableToNumber && rightAssignableToNumber || !leftAssignableToNumber && !rightAssignableToNumber && areTypesComparable(left2, right2); + }); + } + return booleanType; + case 35 /* EqualsEqualsToken */: + case 36 /* ExclamationEqualsToken */: + case 37 /* EqualsEqualsEqualsToken */: + case 38 /* ExclamationEqualsEqualsToken */: + if (!(checkMode && checkMode & 64 /* TypeOnly */)) { + if ((isLiteralExpressionOfObject(left) || isLiteralExpressionOfObject(right)) && // only report for === and !== in JS, not == or != + (!isInJSFile(left) || (operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */))) { + const eqType = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */; + error(errorNode, Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); + } + checkNaNEquality(errorNode, operator, left, right); + reportOperatorErrorUnless((left2, right2) => isTypeEqualityComparableTo(left2, right2) || isTypeEqualityComparableTo(right2, left2)); + } + return booleanType; + case 104 /* InstanceOfKeyword */: + return checkInstanceOfExpression(left, right, leftType, rightType, checkMode); + case 103 /* InKeyword */: + return checkInExpression(left, right, leftType, rightType); + case 56 /* AmpersandAmpersandToken */: + case 77 /* AmpersandAmpersandEqualsToken */: { + const resultType2 = hasTypeFacts(leftType, 4194304 /* Truthy */) ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; + if (operator === 77 /* AmpersandAmpersandEqualsToken */) { + checkAssignmentOperator(rightType); + } + return resultType2; + } + case 57 /* BarBarToken */: + case 76 /* BarBarEqualsToken */: { + const resultType2 = hasTypeFacts(leftType, 8388608 /* Falsy */) ? getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* Subtype */) : leftType; + if (operator === 76 /* BarBarEqualsToken */) { + checkAssignmentOperator(rightType); + } + return resultType2; + } + case 61 /* QuestionQuestionToken */: + case 78 /* QuestionQuestionEqualsToken */: { + const resultType2 = hasTypeFacts(leftType, 262144 /* EQUndefinedOrNull */) ? getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) : leftType; + if (operator === 78 /* QuestionQuestionEqualsToken */) { + checkAssignmentOperator(rightType); + } + return resultType2; + } + case 64 /* EqualsToken */: + const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, rightType); + if (isAssignmentDeclaration2(declKind)) { + if (!(rightType.flags & 524288 /* Object */) || declKind !== 2 /* ModuleExports */ && declKind !== 6 /* Prototype */ && !isEmptyObjectType(rightType) && !isFunctionObjectType(rightType) && !(getObjectFlags(rightType) & 1 /* Class */)) { + checkAssignmentOperator(rightType); + } + return leftType; + } else { + checkAssignmentOperator(rightType); + return rightType; + } + case 28 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isIndirectCall(left.parent)) { + const sf = getSourceFileOfNode(left); + const sourceText = sf.text; + const start = skipTrivia(sourceText, left.pos); + const isInDiag2657 = sf.parseDiagnostics.some((diag2) => { + if (diag2.code !== Diagnostics.JSX_expressions_must_have_one_parent_element.code) return false; + return textSpanContainsPosition(diag2, start); + }); + if (!isInDiag2657) error(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + default: + return Debug.fail(); + } + function bothAreBigIntLike(left2, right2) { + return isTypeAssignableToKind(left2, 2112 /* BigIntLike */) && isTypeAssignableToKind(right2, 2112 /* BigIntLike */); + } + function checkAssignmentDeclaration(kind, rightType2) { + if (kind === 2 /* ModuleExports */) { + for (const prop of getPropertiesOfObjectType(rightType2)) { + const propType = getTypeOfSymbol(prop); + if (propType.symbol && propType.symbol.flags & 32 /* Class */) { + const name = prop.escapedName; + const symbol = resolveName( + prop.valueDeclaration, + name, + 788968 /* Type */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + if ((symbol == null ? void 0 : symbol.declarations) && symbol.declarations.some(isJSDocTypedefTag)) { + addDuplicateDeclarationErrorsForSymbols(symbol, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), prop); + addDuplicateDeclarationErrorsForSymbols(prop, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), symbol); + } + } + } + } + } + function isIndirectCall(node) { + return node.parent.kind === 217 /* ParenthesizedExpression */ && isNumericLiteral(node.left) && node.left.text === "0" && (isCallExpression(node.parent.parent) && node.parent.parent.expression === node.parent || node.parent.parent.kind === 215 /* TaggedTemplateExpression */) && // special-case for "eval" because it's the only non-access case where an indirect call actually affects behavior. + (isAccessExpression(node.right) || isIdentifier(node.right) && node.right.escapedText === "eval"); + } + function checkForDisallowedESSymbolOperand(operator2) { + const offendingSymbolOperand = maybeTypeOfKindConsideringBaseConstraint(leftType, 12288 /* ESSymbolLike */) ? left : maybeTypeOfKindConsideringBaseConstraint(rightType, 12288 /* ESSymbolLike */) ? right : void 0; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator2)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator2) { + switch (operator2) { + case 52 /* BarToken */: + case 75 /* BarEqualsToken */: + return 57 /* BarBarToken */; + case 53 /* CaretToken */: + case 79 /* CaretEqualsToken */: + return 38 /* ExclamationEqualsEqualsToken */; + case 51 /* AmpersandToken */: + case 74 /* AmpersandEqualsToken */: + return 56 /* AmpersandAmpersandToken */; + default: + return void 0; + } + } + function checkAssignmentOperator(valueType) { + if (isAssignmentOperator(operator)) { + addLazyDiagnostic(checkAssignmentOperatorWorker); + } + function checkAssignmentOperatorWorker() { + let assigneeType = leftType; + if (isCompoundAssignment(operatorToken.kind) && left.kind === 211 /* PropertyAccessExpression */) { + assigneeType = checkPropertyAccessExpression( + left, + /*checkMode*/ + void 0, + /*writeOnly*/ + true + ); + } + if (checkReferenceExpression(left, Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)) { + let headMessage; + if (exactOptionalPropertyTypes && isPropertyAccessExpression(left) && maybeTypeOfKind(valueType, 32768 /* Undefined */)) { + const target = getTypeOfPropertyOfType(getTypeOfExpression(left.expression), left.name.escapedText); + if (isExactOptionalPropertyMismatch(valueType, target)) { + headMessage = Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target; + } + } + checkTypeAssignableToAndOptionallyElaborate(valueType, assigneeType, left, right, headMessage); + } + } + } + function isAssignmentDeclaration2(kind) { + var _a; + switch (kind) { + case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: + case 5 /* Property */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + const symbol = getSymbolOfNode(left); + const init = getAssignedExpandoInitializer(right); + return !!init && isObjectLiteralExpression(init) && !!((_a = symbol == null ? void 0 : symbol.exports) == null ? void 0 : _a.size); + default: + return false; + } + } + function reportOperatorErrorUnless(typesAreCompatible) { + if (!typesAreCompatible(leftType, rightType)) { + reportOperatorError(typesAreCompatible); + return true; + } + return false; + } + function reportOperatorError(isRelated) { + let wouldWorkWithAwait = false; + const errNode = errorNode || operatorToken; + if (isRelated) { + const awaitedLeftType = getAwaitedTypeNoAlias(leftType); + const awaitedRightType = getAwaitedTypeNoAlias(rightType); + wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType) && !!(awaitedLeftType && awaitedRightType) && isRelated(awaitedLeftType, awaitedRightType); + } + let effectiveLeft = leftType; + let effectiveRight = rightType; + if (!wouldWorkWithAwait && isRelated) { + [effectiveLeft, effectiveRight] = getBaseTypesIfUnrelated(leftType, rightType, isRelated); + } + const [leftStr, rightStr] = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight); + if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) { + errorAndMaybeSuggestAwait( + errNode, + wouldWorkWithAwait, + Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, + tokenToString(operatorToken.kind), + leftStr, + rightStr + ); + } + } + function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) { + switch (operatorToken.kind) { + case 37 /* EqualsEqualsEqualsToken */: + case 35 /* EqualsEqualsToken */: + case 38 /* ExclamationEqualsEqualsToken */: + case 36 /* ExclamationEqualsToken */: + return errorAndMaybeSuggestAwait( + errNode, + maybeMissingAwait, + Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap, + leftStr, + rightStr + ); + default: + return void 0; + } + } + function checkNaNEquality(errorNode2, operator2, left2, right2) { + const isLeftNaN = isGlobalNaN(skipParentheses(left2)); + const isRightNaN = isGlobalNaN(skipParentheses(right2)); + if (isLeftNaN || isRightNaN) { + const err = error(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 37 /* EqualsEqualsEqualsToken */ || operator2 === 35 /* EqualsEqualsToken */ ? 97 /* FalseKeyword */ : 112 /* TrueKeyword */)); + if (isLeftNaN && isRightNaN) return; + const operatorString = operator2 === 38 /* ExclamationEqualsEqualsToken */ || operator2 === 36 /* ExclamationEqualsToken */ ? tokenToString(54 /* ExclamationToken */) : ""; + const location = isLeftNaN ? right2 : left2; + const expression = skipParentheses(location); + addRelatedInfo(err, createDiagnosticForNode(location, Diagnostics.Did_you_mean_0, `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})`)); + } + } + function isGlobalNaN(expr) { + if (isIdentifier(expr) && expr.escapedText === "NaN") { + const globalNaNSymbol = getGlobalNaNSymbol(); + return !!globalNaNSymbol && globalNaNSymbol === getResolvedSymbol(expr); + } + return false; + } + } + function getBaseTypesIfUnrelated(leftType, rightType, isRelated) { + let effectiveLeft = leftType; + let effectiveRight = rightType; + const leftBase = getBaseTypeOfLiteralType(leftType); + const rightBase = getBaseTypeOfLiteralType(rightType); + if (!isRelated(leftBase, rightBase)) { + effectiveLeft = leftBase; + effectiveRight = rightBase; + } + return [effectiveLeft, effectiveRight]; + } + function checkYieldExpression(node) { + addLazyDiagnostic(checkYieldExpressionGrammar); + const func = getContainingFunction(node); + if (!func) return anyType; + const functionFlags = getFunctionFlags(func); + if (!(functionFlags & 1 /* Generator */)) { + return anyType; + } + const isAsync = (functionFlags & 2 /* Async */) !== 0; + if (node.asteriskToken) { + if (isAsync && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); + } + if (!isAsync && languageVersion < LanguageFeatureMinimumTarget.Generators && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); + } + } + let returnType = getReturnTypeFromAnnotation(func); + if (returnType && returnType.flags & 1048576 /* Union */) { + returnType = filterType(returnType, (t) => checkGeneratorInstantiationAssignabilityToReturnType( + t, + functionFlags, + /*errorNode*/ + void 0 + )); + } + const iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync); + const signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType; + const signatureNextType = iterationTypes && iterationTypes.nextType || anyType; + const yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType; + const yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, signatureNextType, isAsync); + if (returnType && yieldedType) { + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression); + } + if (node.asteriskToken) { + const use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */; + return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression) || anyType; + } else if (returnType) { + return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync) || anyType; + } + let type = getContextualIterationType(2 /* Next */, func); + if (!type) { + type = anyType; + addLazyDiagnostic(() => { + if (noImplicitAny && !expressionResultIsUnused(node)) { + const contextualType = getContextualType( + node, + /*contextFlags*/ + void 0 + ); + if (!contextualType || isTypeAny(contextualType)) { + error(node, Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); + } + } + }); + } + return type; + function checkYieldExpressionGrammar() { + if (!(node.flags & 16384 /* YieldContext */)) { + grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + } + function checkConditionalExpression(node, checkMode) { + const type = checkTruthinessExpression(node.condition, checkMode); + checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.condition, type, node.whenTrue); + const type1 = checkExpression(node.whenTrue, checkMode); + const type2 = checkExpression(node.whenFalse, checkMode); + return getUnionType([type1, type2], 2 /* Subtype */); + } + function isTemplateLiteralContext(node) { + const parent = node.parent; + return isParenthesizedExpression(parent) && isTemplateLiteralContext(parent) || isElementAccessExpression(parent) && parent.argumentExpression === node; + } + function checkTemplateExpression(node) { + const texts = [node.head.text]; + const types = []; + for (const span of node.templateSpans) { + const type = checkExpression(span.expression); + if (maybeTypeOfKindConsideringBaseConstraint(type, 12288 /* ESSymbolLike */)) { + error(span.expression, Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); + } + texts.push(span.literal.text); + types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); + } + const evaluated = node.parent.kind !== 215 /* TaggedTemplateExpression */ && evaluate(node).value; + if (evaluated) { + return getFreshTypeOfLiteralType(getStringLiteralType(evaluated)); + } + if (isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType( + node, + /*contextFlags*/ + void 0 + ) || unknownType, isTemplateLiteralContextualType)) { + return getTemplateLiteralType(texts, types); + } + return stringType; + } + function isTemplateLiteralContextualType(type) { + return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */)); + } + function getContextNode(node) { + if (isJsxAttributes(node) && !isJsxSelfClosingElement(node.parent)) { + return node.parent.parent; + } + return node; + } + function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) { + const contextNode = getContextNode(node); + pushContextualType( + contextNode, + contextualType, + /*isCache*/ + false + ); + pushInferenceContext(contextNode, inferenceContext); + const type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0)); + if (inferenceContext && inferenceContext.intraExpressionInferenceSites) { + inferenceContext.intraExpressionInferenceSites = void 0; + } + const result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType( + contextualType, + node, + /*contextFlags*/ + void 0 + )) ? getRegularTypeOfLiteralType(type) : type; + popInferenceContext(); + popContextualType(); + return result; + } + function checkExpressionCached(node, checkMode) { + if (checkMode) { + return checkExpression(node, checkMode); + } + const links = getNodeLinks(node); + if (!links.resolvedType) { + const saveFlowLoopStart = flowLoopStart; + const saveFlowTypeCache = flowTypeCache; + flowLoopStart = flowLoopCount; + flowTypeCache = void 0; + links.resolvedType = checkExpression(node, checkMode); + flowTypeCache = saveFlowTypeCache; + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = skipParentheses( + node, + /*excludeJSDocTypeAssertions*/ + true + ); + return node.kind === 216 /* TypeAssertionExpression */ || node.kind === 234 /* AsExpression */ || isJSDocTypeAssertion(node); + } + function checkDeclarationInitializer(declaration, checkMode, contextualType) { + const initializer = getEffectiveInitializer(declaration); + if (isInJSFile(declaration)) { + const typeNode = tryGetJSDocSatisfiesTypeNode(declaration); + if (typeNode) { + return checkSatisfiesExpressionWorker(initializer, typeNode, checkMode); + } + } + const type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType( + initializer, + contextualType, + /*inferenceContext*/ + void 0, + checkMode || 0 /* Normal */ + ) : checkExpressionCached(initializer, checkMode)); + if (isParameter(isBindingElement(declaration) ? walkUpBindingElementsAndPatterns(declaration) : declaration)) { + if (declaration.name.kind === 206 /* ObjectBindingPattern */ && isObjectLiteralType(type)) { + return padObjectLiteralType(type, declaration.name); + } + if (declaration.name.kind === 207 /* ArrayBindingPattern */ && isTupleType(type)) { + return padTupleType(type, declaration.name); + } + } + return type; + } + function padObjectLiteralType(type, pattern) { + let missingElements; + for (const e of pattern.elements) { + if (e.initializer) { + const name = getPropertyNameFromBindingElement(e); + if (name && !getPropertyOfType(type, name)) { + missingElements = append(missingElements, e); + } + } + } + if (!missingElements) { + return type; + } + const members = createSymbolTable(); + for (const prop of getPropertiesOfObjectType(type)) { + members.set(prop.escapedName, prop); + } + for (const e of missingElements) { + const symbol = createSymbol(4 /* Property */ | 16777216 /* Optional */, getPropertyNameFromBindingElement(e)); + symbol.links.type = getTypeFromBindingElement( + e, + /*includePatternInType*/ + false, + /*reportErrors*/ + false + ); + members.set(symbol.escapedName, symbol); + } + const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, getIndexInfosOfType(type)); + result.objectFlags = type.objectFlags; + return result; + } + function getPropertyNameFromBindingElement(e) { + const exprType = getLiteralTypeFromPropertyName(e.propertyName || e.name); + return isTypeUsableAsPropertyName(exprType) ? getPropertyNameFromType(exprType) : void 0; + } + function padTupleType(type, pattern) { + if (type.target.combinedFlags & 12 /* Variable */ || getTypeReferenceArity(type) >= pattern.elements.length) { + return type; + } + const patternElements = pattern.elements; + const elementTypes = getElementTypes(type).slice(); + const elementFlags = type.target.elementFlags.slice(); + for (let i = getTypeReferenceArity(type); i < patternElements.length; i++) { + const e = patternElements[i]; + if (i < patternElements.length - 1 || !(e.kind === 208 /* BindingElement */ && e.dotDotDotToken)) { + elementTypes.push(!isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement( + e, + /*includePatternInType*/ + false, + /*reportErrors*/ + false + ) : anyType); + elementFlags.push(2 /* Optional */); + if (!isOmittedExpression(e) && !hasDefaultValue(e)) { + reportImplicitAny(e, anyType); + } + } + } + return createTupleType(elementTypes, elementFlags, type.target.readonly); + } + function widenTypeInferredFromInitializer(declaration, type) { + const widened = getWidenedLiteralTypeForInitializer(declaration, type); + if (isInJSFile(declaration)) { + if (isEmptyLiteralType(widened)) { + reportImplicitAny(declaration, anyType); + return anyType; + } else if (isEmptyArrayLiteralType(widened)) { + reportImplicitAny(declaration, anyArrayType); + return anyArrayType; + } + } + return widened; + } + function getWidenedLiteralTypeForInitializer(declaration, type) { + return getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type); + } + function isLiteralOfContextualType(candidateType, contextualType) { + if (contextualType) { + if (contextualType.flags & 3145728 /* UnionOrIntersection */) { + const types = contextualType.types; + return some(types, (t) => isLiteralOfContextualType(candidateType, t)); + } + if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { + const constraint = getBaseConstraintOfType(contextualType) || unknownType; + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); + } + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); + } + return false; + } + function isConstContext(node) { + const parent = node.parent; + return isAssertionExpression(parent) && isConstTypeReference(parent.type) || isJSDocTypeAssertion(parent) && isConstTypeReference(getJSDocTypeAssertionType(parent)) || isValidConstAssertionArgument(node) && isConstTypeVariable(getContextualType(node, 0 /* None */)) || (isParenthesizedExpression(parent) || isArrayLiteralExpression(parent) || isSpreadElement(parent)) && isConstContext(parent) || (isPropertyAssignment(parent) || isShorthandPropertyAssignment(parent) || isTemplateSpan(parent)) && isConstContext(parent.parent); + } + function checkExpressionForMutableLocation(node, checkMode, forceTuple) { + const type = checkExpression(node, checkMode, forceTuple); + return isConstContext(node) || isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType( + getContextualType( + node, + /*contextFlags*/ + void 0 + ), + node, + /*contextFlags*/ + void 0 + )); + } + function checkPropertyAssignment(node, checkMode) { + if (node.name.kind === 167 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + checkGrammarMethod(node); + if (node.name.kind === 167 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + const uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) { + const callSignature = getSingleSignature( + type, + 0 /* Call */, + /*allowMembers*/ + true + ); + const constructSignature = getSingleSignature( + type, + 1 /* Construct */, + /*allowMembers*/ + true + ); + const signature = callSignature || constructSignature; + if (signature && signature.typeParameters) { + const contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */); + if (contextualType) { + const contextualSignature = getSingleSignature( + getNonNullableType(contextualType), + callSignature ? 0 /* Call */ : 1 /* Construct */, + /*allowMembers*/ + false + ); + if (contextualSignature && !contextualSignature.typeParameters) { + if (checkMode & 8 /* SkipGenericFunctions */) { + skippedGenericFunction(node, checkMode); + return anyFunctionType; + } + const context = getInferenceContext(node); + const returnType = context.signature && getReturnTypeOfSignature(context.signature); + const returnSignature = returnType && getSingleCallOrConstructSignature(returnType); + if (returnSignature && !returnSignature.typeParameters && !every(context.inferences, hasInferenceCandidates)) { + const uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters); + const instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters); + const inferences = map(context.inferences, (info) => createInferenceInfo(info.typeParameter)); + applyToParameterTypes(instantiatedSignature, contextualSignature, (source, target) => { + inferTypes( + inferences, + source, + target, + /*priority*/ + 0, + /*contravariant*/ + true + ); + }); + if (some(inferences, hasInferenceCandidates)) { + applyToReturnTypes(instantiatedSignature, contextualSignature, (source, target) => { + inferTypes(inferences, source, target); + }); + if (!hasOverlappingInferences(context.inferences, inferences)) { + mergeInferences(context.inferences, inferences); + context.inferredTypeParameters = concatenate(context.inferredTypeParameters, uniqueTypeParameters); + return getOrCreateTypeFromSignature(instantiatedSignature); + } + } + } + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context), flatMap(inferenceContexts, (c) => c && map(c.inferences, (i) => i.typeParameter)).slice()); + } + } + } + } + return type; + } + function skippedGenericFunction(node, checkMode) { + if (checkMode & 2 /* Inferential */) { + const context = getInferenceContext(node); + context.flags |= 4 /* SkippedGenericFunction */; + } + } + function hasInferenceCandidates(info) { + return !!(info.candidates || info.contraCandidates); + } + function hasInferenceCandidatesOrDefault(info) { + return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter)); + } + function hasOverlappingInferences(a, b) { + for (let i = 0; i < a.length; i++) { + if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) { + return true; + } + } + return false; + } + function mergeInferences(target, source) { + for (let i = 0; i < target.length; i++) { + if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) { + target[i] = source[i]; + } + } + } + function getUniqueTypeParameters(context, typeParameters) { + const result = []; + let oldTypeParameters; + let newTypeParameters; + for (const tp of typeParameters) { + const name = tp.symbol.escapedName; + if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) { + const newName = getUniqueTypeParameterName(concatenate(context.inferredTypeParameters, result), name); + const symbol = createSymbol(262144 /* TypeParameter */, newName); + const newTypeParameter = createTypeParameter(symbol); + newTypeParameter.target = tp; + oldTypeParameters = append(oldTypeParameters, tp); + newTypeParameters = append(newTypeParameters, newTypeParameter); + result.push(newTypeParameter); + } else { + result.push(tp); + } + } + if (newTypeParameters) { + const mapper = createTypeMapper(oldTypeParameters, newTypeParameters); + for (const tp of newTypeParameters) { + tp.mapper = mapper; + } + } + return result; + } + function hasTypeParameterByName(typeParameters, name) { + return some(typeParameters, (tp) => tp.symbol.escapedName === name); + } + function getUniqueTypeParameterName(typeParameters, baseName) { + let len = baseName.length; + while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */) len--; + const s = baseName.slice(0, len); + for (let index = 1; true; index++) { + const augmentedName = s + index; + if (!hasTypeParameterByName(typeParameters, augmentedName)) { + return augmentedName; + } + } + } + function getReturnTypeOfSingleNonGenericCallSignature(funcType) { + const signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) { + const funcType = checkExpression(expr.expression); + const nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + const returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType); + return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType); + } + function getTypeOfExpression(node) { + const quickType = getQuickTypeOfExpression(node); + if (quickType) { + return quickType; + } + if (node.flags & 268435456 /* TypeCached */ && flowTypeCache) { + const cachedType = flowTypeCache[getNodeId(node)]; + if (cachedType) { + return cachedType; + } + } + const startInvocationCount = flowInvocationCount; + const type = checkExpression(node, 64 /* TypeOnly */); + if (flowInvocationCount !== startInvocationCount) { + const cache = flowTypeCache || (flowTypeCache = []); + cache[getNodeId(node)] = type; + setNodeFlags(node, node.flags | 268435456 /* TypeCached */); + } + return type; + } + function getQuickTypeOfExpression(node) { + let expr = skipParentheses( + node, + /*excludeJSDocTypeAssertions*/ + true + ); + if (isJSDocTypeAssertion(expr)) { + const type = getJSDocTypeAssertionType(expr); + if (!isConstTypeReference(type)) { + return getTypeFromTypeNode(type); + } + } + expr = skipParentheses(node); + if (isAwaitExpression(expr)) { + const type = getQuickTypeOfExpression(expr.expression); + return type ? getAwaitedType(type) : void 0; + } + if (isCallExpression(expr) && expr.expression.kind !== 108 /* SuperKeyword */ && !isRequireCall( + expr, + /*requireStringLiteralLikeArgument*/ + true + ) && !isSymbolOrSymbolForCall(expr)) { + return isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); + } else if (isAssertionExpression(expr) && !isConstTypeReference(expr.type)) { + return getTypeFromTypeNode(expr.type); + } else if (isLiteralExpression(node) || isBooleanLiteral(node)) { + return checkExpression(node); + } + return void 0; + } + function getContextFreeTypeOfExpression(node) { + const links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } + pushContextualType( + node, + anyType, + /*isCache*/ + false + ); + const type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */); + popContextualType(); + return type; + } + function checkExpression(node, checkMode, forceTuple) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); + const saveCurrentNode = currentNode; + currentNode = node; + instantiationCount = 0; + const uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); + const type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + if (isConstEnumObjectType(type)) { + checkConstEnumAccess(node, type); + } + currentNode = saveCurrentNode; + (_b = tracing) == null ? void 0 : _b.pop(); + return type; + } + function checkConstEnumAccess(node, type) { + const ok = node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.expression === node || node.parent.kind === 212 /* ElementAccessExpression */ && node.parent.expression === node || ((node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || node.parent.kind === 186 /* TypeQuery */ && node.parent.exprName === node) || node.parent.kind === 281 /* ExportSpecifier */; + if (!ok) { + error(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); + } + if (compilerOptions.isolatedModules || compilerOptions.verbatimModuleSyntax && ok && !resolveName( + node, + getFirstIdentifier(node), + 2097152 /* Alias */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false, + /*excludeGlobals*/ + true + )) { + Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */)); + const constEnumDeclaration = type.symbol.valueDeclaration; + const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath); + if (constEnumDeclaration.flags & 33554432 /* Ambient */ && !isValidTypeOnlyAliasUseSite(node) && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) { + error(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName); + } + } + } + function checkParenthesizedExpression(node, checkMode) { + if (hasJSDocNodes(node)) { + if (isJSDocSatisfiesExpression(node)) { + return checkSatisfiesExpressionWorker(node.expression, getJSDocSatisfiesExpressionType(node), checkMode); + } + if (isJSDocTypeAssertion(node)) { + return checkAssertionWorker(node, checkMode); + } + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode, forceTuple) { + const kind = node.kind; + if (cancellationToken) { + switch (kind) { + case 231 /* ClassExpression */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 80 /* Identifier */: + return checkIdentifier(node, checkMode); + case 81 /* PrivateIdentifier */: + return checkPrivateIdentifierExpression(node); + case 110 /* ThisKeyword */: + return checkThisExpression(node); + case 108 /* SuperKeyword */: + return checkSuperExpression(node); + case 106 /* NullKeyword */: + return nullWideningType; + case 15 /* NoSubstitutionTemplateLiteral */: + case 11 /* StringLiteral */: + return hasSkipDirectInferenceFlag(node) ? blockedStringType : getFreshTypeOfLiteralType(getStringLiteralType(node.text)); + case 9 /* NumericLiteral */: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getNumberLiteralType(+node.text)); + case 10 /* BigIntLiteral */: + checkGrammarBigIntLiteral(node); + return getFreshTypeOfLiteralType(getBigIntLiteralType({ + negative: false, + base10Value: parsePseudoBigInt(node.text) + })); + case 112 /* TrueKeyword */: + return trueType; + case 97 /* FalseKeyword */: + return falseType; + case 228 /* TemplateExpression */: + return checkTemplateExpression(node); + case 14 /* RegularExpressionLiteral */: + return checkRegularExpressionLiteral(node); + case 209 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode, forceTuple); + case 210 /* ObjectLiteralExpression */: + return checkObjectLiteral(node, checkMode); + case 211 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node, checkMode); + case 166 /* QualifiedName */: + return checkQualifiedName(node, checkMode); + case 212 /* ElementAccessExpression */: + return checkIndexedAccess(node, checkMode); + case 213 /* CallExpression */: + if (node.expression.kind === 102 /* ImportKeyword */) { + return checkImportCallExpression(node); + } + // falls through + case 214 /* NewExpression */: + return checkCallExpression(node, checkMode); + case 215 /* TaggedTemplateExpression */: + return checkTaggedTemplateExpression(node); + case 217 /* ParenthesizedExpression */: + return checkParenthesizedExpression(node, checkMode); + case 231 /* ClassExpression */: + return checkClassExpression(node); + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 221 /* TypeOfExpression */: + return checkTypeOfExpression(node); + case 216 /* TypeAssertionExpression */: + case 234 /* AsExpression */: + return checkAssertion(node, checkMode); + case 235 /* NonNullExpression */: + return checkNonNullAssertion(node); + case 233 /* ExpressionWithTypeArguments */: + return checkExpressionWithTypeArguments(node); + case 238 /* SatisfiesExpression */: + return checkSatisfiesExpression(node); + case 236 /* MetaProperty */: + return checkMetaProperty(node); + case 220 /* DeleteExpression */: + return checkDeleteExpression(node); + case 222 /* VoidExpression */: + return checkVoidExpression(node); + case 223 /* AwaitExpression */: + return checkAwaitExpression(node); + case 224 /* PrefixUnaryExpression */: + return checkPrefixUnaryExpression(node); + case 225 /* PostfixUnaryExpression */: + return checkPostfixUnaryExpression(node); + case 226 /* BinaryExpression */: + return checkBinaryExpression(node, checkMode); + case 227 /* ConditionalExpression */: + return checkConditionalExpression(node, checkMode); + case 230 /* SpreadElement */: + return checkSpreadExpression(node, checkMode); + case 232 /* OmittedExpression */: + return undefinedWideningType; + case 229 /* YieldExpression */: + return checkYieldExpression(node); + case 237 /* SyntheticExpression */: + return checkSyntheticExpression(node); + case 294 /* JsxExpression */: + return checkJsxExpression(node, checkMode); + case 284 /* JsxElement */: + return checkJsxElement(node, checkMode); + case 285 /* JsxSelfClosingElement */: + return checkJsxSelfClosingElement(node, checkMode); + case 288 /* JsxFragment */: + return checkJsxFragment(node); + case 292 /* JsxAttributes */: + return checkJsxAttributes(node, checkMode); + case 286 /* JsxOpeningElement */: + Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return errorType; + } + function checkTypeParameter(node) { + checkGrammarModifiers(node); + if (node.expression) { + grammarErrorOnFirstToken(node.expression, Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node)); + getBaseConstraintOfType(typeParameter); + if (!hasNonCircularTypeParameterDefault(typeParameter)) { + error(node.default, Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); + } + const constraintType = getConstraintOfTypeParameter(typeParameter); + const defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + checkNodeDeferred(node); + addLazyDiagnostic(() => checkTypeNameIsReserved(node.name, Diagnostics.Type_parameter_name_cannot_be_0)); + } + function checkTypeParameterDeferred(node) { + var _a, _b; + if (isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent)) { + const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node)); + const modifiers = getTypeParameterModifiers(typeParameter) & (8192 /* In */ | 16384 /* Out */); + if (modifiers) { + const symbol = getSymbolOfDeclaration(node.parent); + if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & (16 /* Anonymous */ | 32 /* Mapped */))) { + error(node, Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); + } else if (modifiers === 8192 /* In */ || modifiers === 16384 /* Out */) { + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); + const source = createMarkerType(symbol, typeParameter, modifiers === 16384 /* Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); + const target = createMarkerType(symbol, typeParameter, modifiers === 16384 /* Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); + const saveVarianceTypeParameter = typeParameter; + varianceTypeParameter = typeParameter; + checkTypeAssignableTo(source, target, node, Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); + varianceTypeParameter = saveVarianceTypeParameter; + (_b = tracing) == null ? void 0 : _b.pop(); + } + } + } + } + function checkParameter(node) { + checkGrammarModifiers(node); + checkVariableLikeDeclaration(node); + const func = getContainingFunction(node); + if (hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */)) { + if (compilerOptions.erasableSyntaxOnly) { + error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); + } + if (!(func.kind === 176 /* Constructor */ && nodeIsPresent(func.body))) { + error(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + if (func.kind === 176 /* Constructor */ && isIdentifier(node.name) && node.name.escapedText === "constructor") { + error(node.name, Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); + } + } + if (!node.initializer && isOptionalDeclaration(node) && isBindingPattern(node.name) && func.body) { + error(node, Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (func.parameters.indexOf(node) !== 0) { + error(node, Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 176 /* Constructor */ || func.kind === 180 /* ConstructSignature */ || func.kind === 185 /* ConstructorType */) { + error(node, Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + if (func.kind === 219 /* ArrowFunction */) { + error(node, Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } + if (func.kind === 177 /* GetAccessor */ || func.kind === 178 /* SetAccessor */) { + error(node, Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); + } + } + if (node.dotDotDotToken && !isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) { + error(node, Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function checkTypePredicate(node) { + const parent = getTypePredicateParent(node); + if (!parent) { + error(node, Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + const signature = getSignatureFromDeclaration(parent); + const typePredicate = getTypePredicateOfSignature(signature); + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + const { parameterName } = node; + if (typePredicate.kind !== 0 /* This */ && typePredicate.kind !== 2 /* AssertsThis */) { + if (typePredicate.parameterIndex >= 0) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { + error(parameterName, Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } else { + if (typePredicate.type) { + const leadingError = () => chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type + ); + checkTypeAssignableTo( + typePredicate.type, + getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), + node.type, + /*headMessage*/ + void 0, + leadingError + ); + } + } + } else if (parameterName) { + let hasReportedError = false; + for (const { name } of parent.parameters) { + if (isBindingPattern(name) && checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 219 /* ArrowFunction */: + case 179 /* CallSignature */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 184 /* FunctionType */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + const parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (const element of pattern.elements) { + if (isOmittedExpression(element)) { + continue; + } + const name = element.name; + if (name.kind === 80 /* Identifier */ && name.escapedText === predicateVariableName) { + error(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } else if (name.kind === 207 /* ArrayBindingPattern */ || name.kind === 206 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern( + name, + predicateVariableNode, + predicateVariableName + )) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + if (node.kind === 181 /* IndexSignature */) { + checkGrammarIndexSignature(node); + } else if (node.kind === 184 /* FunctionType */ || node.kind === 262 /* FunctionDeclaration */ || node.kind === 185 /* ConstructorType */ || node.kind === 179 /* CallSignature */ || node.kind === 176 /* Constructor */ || node.kind === 180 /* ConstructSignature */) { + checkGrammarFunctionLikeDeclaration(node); + } + const functionFlags = getFunctionFlags(node); + if (!(functionFlags & 4 /* Invalid */)) { + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); + } + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < LanguageFeatureMinimumTarget.AsyncFunctions) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < LanguageFeatureMinimumTarget.Generators) { + checkExternalEmitHelpers(node, 128 /* Generator */); + } + } + checkTypeParameters(getEffectiveTypeParameterDeclarations(node)); + checkUnmatchedJSDocParameters(node); + forEach(node.parameters, checkParameter); + if (node.type) { + checkSourceElement(node.type); + } + addLazyDiagnostic(checkSignatureDeclarationDiagnostics); + function checkSignatureDeclarationDiagnostics() { + checkCollisionWithArgumentsInGeneratedCode(node); + let returnTypeNode = getEffectiveReturnTypeNode(node); + let returnTypeErrorLocation = returnTypeNode; + if (isInJSFile(node)) { + const typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && isTypeReferenceNode(typeTag.typeExpression.type)) { + const signature = getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + if (signature && signature.declaration) { + returnTypeNode = getEffectiveReturnTypeNode(signature.declaration); + returnTypeErrorLocation = typeTag.typeExpression.type; + } + } + } + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 180 /* ConstructSignature */: + error(node, Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 179 /* CallSignature */: + error(node, Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode && returnTypeErrorLocation) { + const functionFlags2 = getFunctionFlags(node); + if ((functionFlags2 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { + const returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } else { + checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags2, returnTypeErrorLocation); + } + } else if ((functionFlags2 & 3 /* AsyncGenerator */) === 2 /* Async */) { + checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation); + } + } + if (node.kind !== 181 /* IndexSignature */ && node.kind !== 317 /* JSDocFunctionType */) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags, errorNode) { + const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags & 2 /* Async */) !== 0) || anyType; + const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags & 2 /* Async */) !== 0) || generatorYieldType; + const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags & 2 /* Async */) !== 0) || unknownType; + const generatorInstantiation = createGeneratorType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & 2 /* Async */)); + return checkTypeAssignableTo(generatorInstantiation, returnType, errorNode); + } + function checkClassForDuplicateDeclarations(node) { + const instanceNames = /* @__PURE__ */ new Map(); + const staticNames = /* @__PURE__ */ new Map(); + const privateIdentifiers = /* @__PURE__ */ new Map(); + for (const member of node.members) { + if (member.kind === 176 /* Constructor */) { + for (const param of member.parameters) { + if (isParameterPropertyDeclaration(param, member) && !isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */); + } + } + } else { + const isStaticMember = isStatic(member); + const name = member.name; + if (!name) { + continue; + } + const isPrivate = isPrivateIdentifier(name); + const privateStaticFlags = isPrivate && isStaticMember ? 16 /* PrivateStatic */ : 0; + const names = isPrivate ? privateIdentifiers : isStaticMember ? staticNames : instanceNames; + const memberName = name && getEffectivePropertyNameForPropertyNameNode(name); + if (memberName) { + switch (member.kind) { + case 177 /* GetAccessor */: + addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags); + break; + case 178 /* SetAccessor */: + addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags); + break; + case 172 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags); + break; + case 174 /* MethodDeclaration */: + addName(names, name, memberName, 8 /* Method */ | privateStaticFlags); + break; + } + } + } + } + function addName(names, location, name, meaning) { + const prev = names.get(name); + if (prev) { + if ((prev & 16 /* PrivateStatic */) !== (meaning & 16 /* PrivateStatic */)) { + error(location, Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, getTextOfNode(location)); + } else { + const prevIsMethod = !!(prev & 8 /* Method */); + const isMethod = !!(meaning & 8 /* Method */); + if (prevIsMethod || isMethod) { + if (prevIsMethod !== isMethod) { + error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); + } + } else if (prev & meaning & ~16 /* PrivateStatic */) { + error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); + } else { + names.set(name, prev | meaning); + } + } + } else { + names.set(name, meaning); + } + } + } + function checkClassForStaticPropertyNameConflicts(node) { + for (const member of node.members) { + const memberNameNode = member.name; + const isStaticMember = isStatic(member); + if (isStaticMember && memberNameNode) { + const memberName = getEffectivePropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + if (useDefineForClassFields) { + break; + } + // fall through + case "prototype": + const message = Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + const className = getNameOfSymbolAsWritten(getSymbolOfDeclaration(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + const names = /* @__PURE__ */ new Map(); + for (const member of node.members) { + if (member.kind === 171 /* PropertySignature */) { + let memberName; + const name = member.name; + switch (name.kind) { + case 11 /* StringLiteral */: + case 9 /* NumericLiteral */: + memberName = name.text; + break; + case 80 /* Identifier */: + memberName = idText(name); + break; + default: + continue; + } + if (names.get(memberName)) { + error(getNameOfDeclaration(member.symbol.valueDeclaration), Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, Diagnostics.Duplicate_identifier_0, memberName); + } else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 264 /* InterfaceDeclaration */) { + const nodeSymbol = getSymbolOfDeclaration(node); + if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + const indexSymbol = getIndexSymbol(getSymbolOfDeclaration(node)); + if (indexSymbol == null ? void 0 : indexSymbol.declarations) { + const indexSignatureMap = /* @__PURE__ */ new Map(); + for (const declaration of indexSymbol.declarations) { + if (isIndexSignatureDeclaration(declaration)) { + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + forEachType(getTypeFromTypeNode(declaration.parameters[0].type), (type) => { + const entry = indexSignatureMap.get(getTypeId(type)); + if (entry) { + entry.declarations.push(declaration); + } else { + indexSignatureMap.set(getTypeId(type), { type, declarations: [declaration] }); + } + }); + } + } + } + indexSignatureMap.forEach((entry) => { + if (entry.declarations.length > 1) { + for (const declaration of entry.declarations) { + error(declaration, Diagnostics.Duplicate_index_signature_for_type_0, typeToString(entry.type)); + } + } + }); + } + } + function checkPropertyDeclaration(node) { + if (!checkGrammarModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + setNodeLinksForPrivateIdentifierScope(node); + if (hasSyntacticModifier(node, 64 /* Abstract */) && node.kind === 172 /* PropertyDeclaration */ && node.initializer) { + error(node, Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, declarationNameToString(node.name)); + } + } + function checkPropertySignature(node) { + if (isPrivateIdentifier(node.name)) { + error(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + return checkPropertyDeclaration(node); + } + function checkMethodDeclaration(node) { + if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); + if (isMethodDeclaration(node) && node.asteriskToken && isIdentifier(node.name) && idText(node.name) === "constructor") { + error(node.name, Diagnostics.Class_constructor_may_not_be_a_generator); + } + checkFunctionOrMethodDeclaration(node); + if (hasSyntacticModifier(node, 64 /* Abstract */) && node.kind === 174 /* MethodDeclaration */ && node.body) { + error(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name)); + } + if (isPrivateIdentifier(node.name) && !getContainingClass(node)) { + error(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + setNodeLinksForPrivateIdentifierScope(node); + } + function setNodeLinksForPrivateIdentifierScope(node) { + if (isPrivateIdentifier(node.name)) { + if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) { + for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) { + getNodeLinks(lexicalScope).flags |= 1048576 /* ContainsClassWithPrivateIdentifiers */; + } + if (isClassExpression(node.parent)) { + const enclosingIterationStatement = getEnclosingIterationStatement(node.parent); + if (enclosingIterationStatement) { + getNodeLinks(node.name).flags |= 32768 /* BlockScopedBindingInLoop */; + getNodeLinks(enclosingIterationStatement).flags |= 4096 /* LoopWithCapturedBlockScopedBinding */; + } + } + } + } + } + function checkClassStaticBlockDeclaration(node) { + checkGrammarModifiers(node); + forEachChild(node, checkSourceElement); + } + function checkConstructorDeclaration(node) { + checkSignatureDeclaration(node); + if (!checkGrammarConstructorTypeParameters(node)) checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + const symbol = getSymbolOfDeclaration(node); + const firstDeclaration = getDeclarationOfKind(symbol, node.kind); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + if (nodeIsMissing(node.body)) { + return; + } + addLazyDiagnostic(checkConstructorDeclarationDiagnostics); + return; + function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) { + if (isPrivateIdentifierClassElementDeclaration(n)) { + return true; + } + return n.kind === 172 /* PropertyDeclaration */ && !isStatic(n) && !!n.initializer; + } + function checkConstructorDeclarationDiagnostics() { + const containingClassDecl = node.parent; + if (getClassExtendsHeritageElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + const classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + const superCall = findFirstSuperCall(node.body); + if (superCall) { + if (classExtendsNull) { + error(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 31 /* ParameterPropertyModifier */))); + if (superCallShouldBeRootLevel) { + if (!superCallIsRootLevelInConstructor(superCall, node.body)) { + error(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); + } else { + let superCallStatement; + for (const statement of node.body.statements) { + if (isExpressionStatement(statement) && isSuperCall(skipOuterExpressions(statement.expression))) { + superCallStatement = statement; + break; + } + if (nodeImmediatelyReferencesSuperOrThis(statement)) { + break; + } + } + if (superCallStatement === void 0) { + error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_class_contains_initialized_properties_parameter_properties_or_private_identifiers); + } + } + } + } else if (!classExtendsNull) { + error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + } + function superCallIsRootLevelInConstructor(superCall, body) { + const superCallParent = walkUpParenthesizedExpressions(superCall.parent); + return isExpressionStatement(superCallParent) && superCallParent.parent === body; + } + function nodeImmediatelyReferencesSuperOrThis(node) { + if (node.kind === 108 /* SuperKeyword */ || node.kind === 110 /* ThisKeyword */) { + return true; + } + if (isThisContainerOrFunctionBlock(node)) { + return false; + } + return !!forEachChild(node, nodeImmediatelyReferencesSuperOrThis); + } + function checkAccessorDeclaration(node) { + if (isIdentifier(node.name) && idText(node.name) === "constructor" && isClassLike(node.parent)) { + error(node.name, Diagnostics.Class_constructor_may_not_be_an_accessor); + } + addLazyDiagnostic(checkAccessorDeclarationDiagnostics); + checkSourceElement(node.body); + setNodeLinksForPrivateIdentifierScope(node); + function checkAccessorDeclarationDiagnostics() { + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 177 /* GetAccessor */) { + if (!(node.flags & 33554432 /* Ambient */) && nodeIsPresent(node.body) && node.flags & 512 /* HasImplicitReturn */) { + if (!(node.flags & 1024 /* HasExplicitReturn */)) { + error(node.name, Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + if (node.name.kind === 167 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + if (hasBindableName(node)) { + const symbol = getSymbolOfDeclaration(node); + const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */); + const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */); + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; + const getterFlags = getEffectiveModifierFlags(getter); + const setterFlags = getEffectiveModifierFlags(setter); + if ((getterFlags & 64 /* Abstract */) !== (setterFlags & 64 /* Abstract */)) { + error(getter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + if (getterFlags & 4 /* Protected */ && !(setterFlags & (4 /* Protected */ | 2 /* Private */)) || getterFlags & 2 /* Private */ && !(setterFlags & 2 /* Private */)) { + error(getter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + } + } + } + const returnType = getTypeOfAccessors(getSymbolOfDeclaration(node)); + if (node.kind === 177 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) { + if (node.typeArguments && index < node.typeArguments.length) { + return getTypeFromTypeNode(node.typeArguments[index]); + } + return getEffectiveTypeArguments(node, typeParameters)[index]; + } + function getEffectiveTypeArguments(node, typeParameters) { + return fillMissingTypeArguments(map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(node)); + } + function checkTypeArgumentConstraints(node, typeParameters) { + let typeArguments; + let mapper; + let result = true; + for (let i = 0; i < typeParameters.length; i++) { + const constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = getEffectiveTypeArguments(node, typeParameters); + mapper = createTypeMapper(typeParameters, typeArguments); + } + result = result && checkTypeAssignableTo( + typeArguments[i], + instantiateType(constraint, mapper), + node.typeArguments[i], + Diagnostics.Type_0_does_not_satisfy_the_constraint_1 + ); + } + } + return result; + } + function getTypeParametersForTypeAndSymbol(type, symbol) { + if (!isErrorType(type)) { + return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters || (getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : void 0); + } + return void 0; + } + function getTypeParametersForTypeReferenceOrImport(node) { + const type = getTypeFromTypeNode(node); + if (!isErrorType(type)) { + const symbol = getNodeLinks(node).resolvedSymbol; + if (symbol) { + return getTypeParametersForTypeAndSymbol(type, symbol); + } + } + return void 0; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 183 /* TypeReference */ && !isInJSFile(node) && !isInJSDoc(node) && node.typeArguments && node.typeName.end !== node.typeArguments.pos) { + const sourceFile = getSourceFileOfNode(node); + if (scanTokenAtPosition(sourceFile, node.typeName.end) === 25 /* DotToken */) { + grammarErrorAtPos(node, skipTrivia(sourceFile.text, node.typeName.end), 1, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + forEach(node.typeArguments, checkSourceElement); + checkTypeReferenceOrImport(node); + } + function checkTypeReferenceOrImport(node) { + const type = getTypeFromTypeNode(node); + if (!isErrorType(type)) { + if (node.typeArguments) { + addLazyDiagnostic(() => { + const typeParameters = getTypeParametersForTypeReferenceOrImport(node); + if (typeParameters) { + checkTypeArgumentConstraints(node, typeParameters); + } + }); + } + const symbol = getNodeLinks(node).resolvedSymbol; + if (symbol) { + if (some(symbol.declarations, (d) => isTypeDeclaration(d) && !!(d.flags & 536870912 /* Deprecated */))) { + addDeprecatedSuggestion( + getDeprecatedSuggestionNode(node), + symbol.declarations, + symbol.escapedName + ); + } + } + } + } + function getTypeArgumentConstraint(node) { + const typeReferenceNode = tryCast(node.parent, isTypeReferenceType); + if (!typeReferenceNode) return void 0; + const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReferenceNode); + if (!typeParameters) return void 0; + const constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); + return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + forEach(node.members, checkSourceElement); + addLazyDiagnostic(checkTypeLiteralDiagnostics); + function checkTypeLiteralDiagnostics() { + const type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type, type.symbol); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + let seenOptionalElement = false; + let seenRestElement = false; + for (const e of node.elements) { + let flags = getTupleElementFlags(e); + if (flags & 8 /* Variadic */) { + const type = getTypeFromTypeNode(e.type); + if (!isArrayLikeType(type)) { + error(e, Diagnostics.A_rest_element_type_must_be_an_array_type); + break; + } + if (isArrayType(type) || isTupleType(type) && type.target.combinedFlags & 4 /* Rest */) { + flags |= 4 /* Rest */; + } + } + if (flags & 4 /* Rest */) { + if (seenRestElement) { + grammarErrorOnNode(e, Diagnostics.A_rest_element_cannot_follow_another_rest_element); + break; + } + seenRestElement = true; + } else if (flags & 2 /* Optional */) { + if (seenRestElement) { + grammarErrorOnNode(e, Diagnostics.An_optional_element_cannot_follow_a_rest_element); + break; + } + seenOptionalElement = true; + } else if (flags & 1 /* Required */ && seenOptionalElement) { + grammarErrorOnNode(e, Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } + } + forEach(node.elements, checkSourceElement); + getTypeFromTypeNode(node); + } + function checkUnionOrIntersectionType(node) { + forEach(node.types, checkSourceElement); + getTypeFromTypeNode(node); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 8388608 /* IndexedAccess */)) { + return type; + } + const objectType = type.objectType; + const indexType = type.indexType; + const objectIndexType = isGenericMappedType(objectType) && getMappedTypeNameTypeKind(objectType) === 2 /* Remapping */ ? getIndexTypeForMappedType(objectType, 0 /* None */) : getIndexType(objectType, 0 /* None */); + const hasNumberIndexInfo = !!getIndexInfoOfType(objectType, numberType); + if (everyType(indexType, (t) => isTypeAssignableTo(t, objectIndexType) || hasNumberIndexInfo && isApplicableIndexType(t, numberType))) { + if (accessNode.kind === 212 /* ElementAccessExpression */ && isAssignmentTarget(accessNode) && getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { + error(accessNode, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } + return type; + } + if (isGenericObjectType(objectType)) { + const propertyName = getPropertyNameFromIndex(indexType, accessNode); + if (propertyName) { + const propertySymbol = forEachType(getApparentType(objectType), (t) => getPropertyOfType(t, propertyName)); + if (propertySymbol && getDeclarationModifierFlagsFromSymbol(propertySymbol) & 6 /* NonPublicAccessibilityModifier */) { + error(accessNode, Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, unescapeLeadingUnderscores(propertyName)); + return errorType; + } + } + } + error(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return errorType; + } + function checkIndexedAccessType(node) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkGrammarMappedType(node); + checkSourceElement(node.typeParameter); + checkSourceElement(node.nameType); + checkSourceElement(node.type); + if (!node.type) { + reportImplicitAny(node, anyType); + } + const type = getTypeFromMappedTypeNode(node); + const nameType = getNameTypeFromMappedType(type); + if (nameType) { + checkTypeAssignableTo(nameType, stringNumberSymbolType, node.nameType); + } else { + const constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, stringNumberSymbolType, getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + } + function checkGrammarMappedType(node) { + var _a; + if ((_a = node.members) == null ? void 0 : _a.length) { + return grammarErrorOnNode(node.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); + } + function checkTypeOperator(node) { + checkGrammarTypeOperatorNode(node); + checkSourceElement(node.type); + } + function checkConditionalType(node) { + forEachChild(node, checkSourceElement); + } + function checkInferType(node) { + if (!findAncestor(node, (n) => n.parent && n.parent.kind === 194 /* ConditionalType */ && n.parent.extendsType === n)) { + grammarErrorOnNode(node, Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); + } + checkSourceElement(node.typeParameter); + const symbol = getSymbolOfDeclaration(node.typeParameter); + if (symbol.declarations && symbol.declarations.length > 1) { + const links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + const typeParameter = getDeclaredTypeOfTypeParameter(symbol); + const declarations = getDeclarationsOfKind(symbol, 168 /* TypeParameter */); + if (!areTypeParametersIdentical(declarations, [typeParameter], (decl) => [decl])) { + const name = symbolToString(symbol); + for (const declaration of declarations) { + error(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_constraints, name); + } + } + } + } + registerForUnusedIdentifiersCheck(node); + } + function checkTemplateLiteralType(node) { + for (const span of node.templateSpans) { + checkSourceElement(span.type); + const type = getTypeFromTypeNode(span.type); + checkTypeAssignableTo(type, templateConstraintType, span.type); + } + getTypeFromTypeNode(node); + } + function checkImportType(node) { + checkSourceElement(node.argument); + if (node.attributes) { + getResolutionModeOverride(node.attributes, grammarErrorOnNode); + } + checkTypeReferenceOrImport(node); + } + function checkNamedTupleMember(node) { + if (node.dotDotDotToken && node.questionToken) { + grammarErrorOnNode(node, Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest); + } + if (node.type.kind === 190 /* OptionalType */) { + grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); + } + if (node.type.kind === 191 /* RestType */) { + grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); + } + checkSourceElement(node.type); + getTypeFromTypeNode(node); + } + function isPrivateWithinAmbient(node) { + return (hasEffectiveModifier(node, 2 /* Private */) || isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 33554432 /* Ambient */); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + let flags = getCombinedModifierFlagsCached(n); + if (n.parent.kind !== 264 /* InterfaceDeclaration */ && n.parent.kind !== 263 /* ClassDeclaration */ && n.parent.kind !== 231 /* ClassExpression */ && n.flags & 33554432 /* Ambient */) { + const container = getEnclosingContainer(n); + if (container && container.flags & 128 /* ExportContext */ && !(flags & 128 /* Ambient */) && !(isModuleBlock(n.parent) && isModuleDeclaration(n.parent.parent) && isGlobalScopeAugmentation(n.parent.parent))) { + flags |= 32 /* Export */; + } + flags |= 128 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + addLazyDiagnostic(() => checkFunctionOrConstructorSymbolWorker(symbol)); + } + function checkFunctionOrConstructorSymbolWorker(symbol) { + function getCanonicalOverload(overloads, implementation) { + const implementationSharesContainerWithFirstOverload = implementation !== void 0 && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck2, someOverloadFlags, allOverloadFlags) { + const someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + const canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck2); + group(overloads, (o) => getSourceFileOfNode(o).fileName).forEach((overloadsInFile) => { + const canonicalFlagsForFile = getEffectiveDeclarationFlags(getCanonicalOverload(overloadsInFile, implementation), flagsToCheck2); + for (const o of overloadsInFile) { + const deviation = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlags; + const deviationInFile = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlagsForFile; + if (deviationInFile & 32 /* Export */) { + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } else if (deviationInFile & 128 /* Ambient */) { + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } else if (deviation & (2 /* Private */ | 4 /* Protected */)) { + error(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } else if (deviation & 64 /* Abstract */) { + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken2, allHaveQuestionToken2) { + if (someHaveQuestionToken2 !== allHaveQuestionToken2) { + const canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation)); + forEach(overloads, (o) => { + const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; + if (deviation) { + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + const flagsToCheck = 32 /* Export */ | 128 /* Ambient */ | 2 /* Private */ | 4 /* Protected */ | 64 /* Abstract */; + let someNodeFlags = 0 /* None */; + let allNodeFlags = flagsToCheck; + let someHaveQuestionToken = false; + let allHaveQuestionToken = true; + let hasOverloads = false; + let bodyDeclaration; + let lastSeenNonAmbientDeclaration; + let previousDeclaration; + const declarations = symbol.declarations; + const isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && nodeIsMissing(node.name)) { + return; + } + let seen = false; + const subsequentNode = forEachChild(node.parent, (c) => { + if (seen) { + return c; + } else { + seen = c === node; + } + }); + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + const errorNode2 = subsequentNode.name || subsequentNode; + const subsequentName = subsequentNode.name; + if (node.name && subsequentName && // both are private identifiers + (isPrivateIdentifier(node.name) && isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText || // Both are computed property names + isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) && isTypeIdenticalTo(checkComputedPropertyName(node.name), checkComputedPropertyName(subsequentName)) || // Both are literal property names that are the same. + isPropertyNameLiteral(node.name) && isPropertyNameLiteral(subsequentName) && getEscapedTextOfIdentifierOrLiteral(node.name) === getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + const reportError = (node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */) && isStatic(node) !== isStatic(subsequentNode); + if (reportError) { + const diagnostic = isStatic(node) ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; + error(errorNode2, diagnostic); + } + return; + } + if (nodeIsPresent(subsequentNode.body)) { + error(errorNode2, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name)); + return; + } + } + } + const errorNode = node.name || node; + if (isConstructor) { + error(errorNode, Diagnostics.Constructor_implementation_is_missing); + } else { + if (hasSyntacticModifier(node, 64 /* Abstract */)) { + error(errorNode, Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } else { + error(errorNode, Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + let duplicateFunctionDeclaration = false; + let multipleConstructorImplementation = false; + let hasNonAmbientClass = false; + const functionDeclarations = []; + if (declarations) { + for (const current of declarations) { + const node = current; + const inAmbientContext = node.flags & 33554432 /* Ambient */; + const inAmbientContextOrInterface = node.parent && (node.parent.kind === 264 /* InterfaceDeclaration */ || node.parent.kind === 187 /* TypeLiteral */) || inAmbientContext; + if (inAmbientContextOrInterface) { + previousDeclaration = void 0; + } + if ((node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */) && !inAmbientContext) { + hasNonAmbientClass = true; + } + if (node.kind === 262 /* FunctionDeclaration */ || node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */ || node.kind === 176 /* Constructor */) { + functionDeclarations.push(node); + const currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && hasQuestionToken(node); + const bodyIsPresent = nodeIsPresent(node.body); + if (bodyIsPresent && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } else { + duplicateFunctionDeclaration = true; + } + } else if ((previousDeclaration == null ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (bodyIsPresent) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + if (isInJSFile(current) && isFunctionLike(current) && current.jsDoc) { + hasOverloads = length(getJSDocOverloadTags(current)) > 0; + } + } + } + if (multipleConstructorImplementation) { + forEach(functionDeclarations, (declaration) => { + error(declaration, Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + forEach(functionDeclarations, (declaration) => { + error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Duplicate_function_implementation); + }); + } + if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */ && declarations) { + const relatedDiagnostics = filter(declarations, (d) => d.kind === 263 /* ClassDeclaration */).map((d) => createDiagnosticForNode(d, Diagnostics.Consider_adding_a_declare_modifier_to_this_class)); + forEach(declarations, (declaration) => { + const diagnostic = declaration.kind === 263 /* ClassDeclaration */ ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 : declaration.kind === 262 /* FunctionDeclaration */ ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient : void 0; + if (diagnostic) { + addRelatedInfo( + error(getNameOfDeclaration(declaration) || declaration, diagnostic, symbolName(symbol)), + ...relatedDiagnostics + ); + } + }); + } + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !hasSyntacticModifier(lastSeenNonAmbientDeclaration, 64 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + if (declarations) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + } + if (bodyDeclaration) { + const signatures = getSignaturesOfSymbol(symbol); + const bodySignature = getSignatureFromDeclaration(bodyDeclaration); + for (const signature of signatures) { + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + const errorNode = signature.declaration && isJSDocSignature(signature.declaration) ? signature.declaration.parent.tagName : signature.declaration; + addRelatedInfo( + error(errorNode, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), + createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here) + ); + break; + } + } + } + } + } + function checkExportsOnMergedDeclarations(node) { + addLazyDiagnostic(() => checkExportsOnMergedDeclarationsWorker(node)); + } + function checkExportsOnMergedDeclarationsWorker(node) { + let symbol = node.localSymbol; + if (!symbol) { + symbol = getSymbolOfDeclaration(node); + if (!symbol.exportSymbol) { + return; + } + } + if (getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + let exportedDeclarationSpaces = 0 /* None */; + let nonExportedDeclarationSpaces = 0 /* None */; + let defaultExportedDeclarationSpaces = 0 /* None */; + for (const d of symbol.declarations) { + const declarationSpaces = getDeclarationSpaces(d); + const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 32 /* Export */ | 2048 /* Default */); + if (effectiveDeclarationFlags & 32 /* Export */) { + if (effectiveDeclarationFlags & 2048 /* Default */) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } else { + exportedDeclarationSpaces |= declarationSpaces; + } + } else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + const nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + const commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + const commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + for (const d of symbol.declarations) { + const declarationSpaces = getDeclarationSpaces(d); + const name = getNameOfDeclaration(d); + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { + error(name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(name)); + } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { + error(name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(name)); + } + } + } + function getDeclarationSpaces(decl) { + let d = decl; + switch (d.kind) { + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + // A jsdoc typedef and callback are, by definition, type aliases. + // falls through + case 346 /* JSDocTypedefTag */: + case 338 /* JSDocCallbackTag */: + case 340 /* JSDocEnumTag */: + return 2 /* ExportType */; + case 267 /* ModuleDeclaration */: + return isAmbientModule(d) || getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; + case 263 /* ClassDeclaration */: + case 266 /* EnumDeclaration */: + case 306 /* EnumMember */: + return 2 /* ExportType */ | 1 /* ExportValue */; + case 307 /* SourceFile */: + return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; + case 277 /* ExportAssignment */: + case 226 /* BinaryExpression */: + const node2 = d; + const expression = isExportAssignment(node2) ? node2.expression : node2.right; + if (!isEntityNameExpression(expression)) { + return 1 /* ExportValue */; + } + d = expression; + // The below options all declare an Alias, which is allowed to merge with other values within the importing module. + // falls through + case 271 /* ImportEqualsDeclaration */: + case 274 /* NamespaceImport */: + case 273 /* ImportClause */: + let result = 0 /* None */; + const target = resolveAlias(getSymbolOfDeclaration(d)); + forEach(target.declarations, (d2) => { + result |= getDeclarationSpaces(d2); + }); + return result; + case 260 /* VariableDeclaration */: + case 208 /* BindingElement */: + case 262 /* FunctionDeclaration */: + case 276 /* ImportSpecifier */: + // https://github.com/Microsoft/TypeScript/pull/7591 + case 80 /* Identifier */: + return 1 /* ExportValue */; + case 173 /* MethodSignature */: + case 171 /* PropertySignature */: + return 2 /* ExportType */; + default: + return Debug.failBadSyntaxKind(d); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, ...args) { + const promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, ...args); + } + function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) { + if (isTypeAny(type)) { + return void 0; + } + const typeAsPromise = type; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(type, getGlobalPromiseType( + /*reportErrors*/ + false + ))) { + return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; + } + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 402784252 /* Primitive */ | 131072 /* Never */)) { + return void 0; + } + const thenFunction = getTypeOfPropertyOfType(type, "then"); + if (isTypeAny(thenFunction)) { + return void 0; + } + const thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, Diagnostics.A_promise_must_have_a_then_method); + } + return void 0; + } + let thisTypeForError; + let candidates; + for (const thenSignature of thenSignatures) { + const thisType = getThisTypeOfSignature(thenSignature); + if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) { + thisTypeForError = thisType; + } else { + candidates = append(candidates, thenSignature); + } + } + if (!candidates) { + Debug.assertIsDefined(thisTypeForError); + if (thisTypeForErrorOut) { + thisTypeForErrorOut.value = thisTypeForError; + } + if (errorNode) { + error(errorNode, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); + } + return void 0; + } + const onfulfilledParameterType = getTypeWithFacts(getUnionType(map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */); + if (isTypeAny(onfulfilledParameterType)) { + return void 0; + } + const onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return void 0; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); + } + function checkAwaitedType(type, withAlias, errorNode, diagnosticMessage, ...args) { + const awaitedType = withAlias ? getAwaitedType(type, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args); + return awaitedType || errorType; + } + function isThenableType(type) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 402784252 /* Primitive */ | 131072 /* Never */)) { + return false; + } + const thenFunction = getTypeOfPropertyOfType(type, "then"); + return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0; + } + function isAwaitedTypeInstantiation(type) { + var _a; + if (type.flags & 16777216 /* Conditional */) { + const awaitedSymbol = getGlobalAwaitedSymbol( + /*reportErrors*/ + false + ); + return !!awaitedSymbol && type.aliasSymbol === awaitedSymbol && ((_a = type.aliasTypeArguments) == null ? void 0 : _a.length) === 1; + } + return false; + } + function unwrapAwaitedType(type) { + return type.flags & 1048576 /* Union */ ? mapType(type, unwrapAwaitedType) : isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type; + } + function isAwaitedTypeNeeded(type) { + if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) { + return false; + } + if (isGenericObjectType(type)) { + const baseConstraint = getBaseConstraintOfType(type); + if (baseConstraint ? baseConstraint.flags & 3 /* AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, 8650752 /* TypeVariable */)) { + return true; + } + } + return false; + } + function tryCreateAwaitedType(type) { + const awaitedSymbol = getGlobalAwaitedSymbol( + /*reportErrors*/ + true + ); + if (awaitedSymbol) { + return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); + } + return void 0; + } + function createAwaitedTypeIfNeeded(type) { + if (isAwaitedTypeNeeded(type)) { + return tryCreateAwaitedType(type) ?? type; + } + Debug.assert(isAwaitedTypeInstantiation(type) || getPromisedTypeOfPromise(type) === void 0, "type provided should not be a non-generic 'promise'-like."); + return type; + } + function getAwaitedType(type, errorNode, diagnosticMessage, ...args) { + const awaitedType = getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args); + return awaitedType && createAwaitedTypeIfNeeded(awaitedType); + } + function getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args) { + if (isTypeAny(type)) { + return type; + } + if (isAwaitedTypeInstantiation(type)) { + return type; + } + const typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (type.flags & 1048576 /* Union */) { + if (awaitedTypeStack.lastIndexOf(type.id) >= 0) { + if (errorNode) { + error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return void 0; + } + const mapper = errorNode ? (constituentType) => getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias; + awaitedTypeStack.push(type.id); + const mapped = mapType(type, mapper); + awaitedTypeStack.pop(); + return typeAsAwaitable.awaitedTypeOfType = mapped; + } + if (isAwaitedTypeNeeded(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + const thisTypeForErrorOut = { value: void 0 }; + const promisedType = getPromisedTypeOfPromise( + type, + /*errorNode*/ + void 0, + thisTypeForErrorOut + ); + if (promisedType) { + if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { + if (errorNode) { + error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return void 0; + } + awaitedTypeStack.push(type.id); + const awaitedType = getAwaitedTypeNoAlias(promisedType, errorNode, diagnosticMessage, ...args); + awaitedTypeStack.pop(); + if (!awaitedType) { + return void 0; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + if (isThenableType(type)) { + if (errorNode) { + Debug.assertIsDefined(diagnosticMessage); + let chain; + if (thisTypeForErrorOut.value) { + chain = chainDiagnosticMessages(chain, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value)); + } + chain = chainDiagnosticMessages(chain, diagnosticMessage, ...args); + diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, chain)); + } + return void 0; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + function checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation) { + const returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2 /* ES2015 */) { + if (isErrorType(returnType)) { + return; + } + const globalPromiseType = getGlobalPromiseType( + /*reportErrors*/ + true + ); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + reportErrorForInvalidReturnType(Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, returnTypeNode, returnTypeErrorLocation, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); + return; + } + } else { + markLinkedReferences(node, 5 /* AsyncFunction */); + if (isErrorType(returnType)) { + return; + } + const promiseConstructorName = getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === void 0) { + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, typeToString(returnType)); + return; + } + const promiseConstructorSymbol = resolveEntityName( + promiseConstructorName, + 111551 /* Value */, + /*ignoreErrors*/ + true + ); + const promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; + if (isErrorType(promiseConstructorType)) { + if (promiseConstructorName.kind === 80 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType( + /*reportErrors*/ + false + )) { + error(returnTypeErrorLocation, Diagnostics.An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } else { + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); + } + return; + } + const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType( + /*reportErrors*/ + true + ); + if (globalPromiseConstructorLikeType === emptyObjectType) { + reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); + return; + } + const headMessage = Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value; + const errorInfo = () => returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type + ); + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeErrorLocation, headMessage, errorInfo)) { + return; + } + const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + const collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, idText(rootName), entityNameToString(promiseConstructorName)); + return; + } + } + checkAwaitedType( + returnType, + /*withAlias*/ + false, + node, + Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + ); + function reportErrorForInvalidReturnType(message, returnTypeNode2, returnTypeErrorLocation2, typeName) { + if (returnTypeNode2 === returnTypeErrorLocation2) { + error(returnTypeErrorLocation2, message, typeName); + } else { + const diag2 = error(returnTypeErrorLocation2, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + addRelatedInfo(diag2, createDiagnosticForNode(returnTypeNode2, message, typeName)); + } + } + } + function checkGrammarDecorator(decorator) { + const sourceFile = getSourceFileOfNode(decorator); + if (!hasParseDiagnostics(sourceFile)) { + let node = decorator.expression; + if (isParenthesizedExpression(node)) { + return false; + } + let canHaveCallExpression = true; + let errorNode; + while (true) { + if (isExpressionWithTypeArguments(node) || isNonNullExpression(node)) { + node = node.expression; + continue; + } + if (isCallExpression(node)) { + if (!canHaveCallExpression) { + errorNode = node; + } + if (node.questionDotToken) { + errorNode = node.questionDotToken; + } + node = node.expression; + canHaveCallExpression = false; + continue; + } + if (isPropertyAccessExpression(node)) { + if (node.questionDotToken) { + errorNode = node.questionDotToken; + } + node = node.expression; + canHaveCallExpression = false; + continue; + } + if (!isIdentifier(node)) { + errorNode = node; + } + break; + } + if (errorNode) { + addRelatedInfo( + error(decorator.expression, Diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator), + createDiagnosticForNode(errorNode, Diagnostics.Invalid_syntax_in_decorator) + ); + return true; + } + } + return false; + } + function checkDecorator(node) { + checkGrammarDecorator(node); + const signature = getResolvedSignature(node); + checkDeprecatedSignature(signature, node); + const returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + const decoratorSignature = getDecoratorCallSignature(node); + if (!(decoratorSignature == null ? void 0 : decoratorSignature.resolvedReturnType)) return; + let headMessage; + const expectedReturnType = decoratorSignature.resolvedReturnType; + switch (node.parent.kind) { + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; + break; + case 172 /* PropertyDeclaration */: + if (!legacyDecorators) { + headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; + break; + } + // falls through + case 169 /* Parameter */: + headMessage = Diagnostics.Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any; + break; + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; + break; + default: + return Debug.failBadSyntaxKind(node.parent); + } + checkTypeAssignableTo(returnType, expectedReturnType, node.expression, headMessage); + } + function createCallSignature(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount = parameters.length, flags = 0 /* None */) { + const decl = factory.createFunctionTypeNode( + /*typeParameters*/ + void 0, + emptyArray, + factory.createKeywordTypeNode(133 /* AnyKeyword */) + ); + return createSignature(decl, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags); + } + function createFunctionType(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags) { + const signature = createCallSignature(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags); + return getOrCreateTypeFromSignature(signature); + } + function createGetterFunctionType(type) { + return createFunctionType( + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + emptyArray, + type + ); + } + function createSetterFunctionType(type) { + const valueParam = createParameter("value", type); + return createFunctionType( + /*typeParameters*/ + void 0, + /*thisParameter*/ + void 0, + [valueParam], + voidType + ); + } + function getEntityNameForDecoratorMetadata(node) { + if (node) { + switch (node.kind) { + case 193 /* IntersectionType */: + case 192 /* UnionType */: + return getEntityNameForDecoratorMetadataFromTypeList(node.types); + case 194 /* ConditionalType */: + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); + case 196 /* ParenthesizedType */: + case 202 /* NamedTupleMember */: + return getEntityNameForDecoratorMetadata(node.type); + case 183 /* TypeReference */: + return node.typeName; + } + } + } + function getEntityNameForDecoratorMetadataFromTypeList(types) { + let commonEntityName; + for (let typeNode of types) { + while (typeNode.kind === 196 /* ParenthesizedType */ || typeNode.kind === 202 /* NamedTupleMember */) { + typeNode = typeNode.type; + } + if (typeNode.kind === 146 /* NeverKeyword */) { + continue; + } + if (!strictNullChecks && (typeNode.kind === 201 /* LiteralType */ && typeNode.literal.kind === 106 /* NullKeyword */ || typeNode.kind === 157 /* UndefinedKeyword */)) { + continue; + } + const individualEntityName = getEntityNameForDecoratorMetadata(typeNode); + if (!individualEntityName) { + return void 0; + } + if (commonEntityName) { + if (!isIdentifier(commonEntityName) || !isIdentifier(individualEntityName) || commonEntityName.escapedText !== individualEntityName.escapedText) { + return void 0; + } + } else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + } + function getParameterTypeNodeForDecoratorCheck(node) { + const typeNode = getEffectiveTypeAnnotationNode(node); + return isRestParameter(node) ? getRestParameterElementType(typeNode) : typeNode; + } + function checkDecorators(node) { + if (!canHaveDecorators(node) || !hasDecorators(node) || !node.modifiers || !nodeCanBeDecorated(legacyDecorators, node, node.parent, node.parent.parent)) { + return; + } + const firstDecorator = find(node.modifiers, isDecorator); + if (!firstDecorator) { + return; + } + if (legacyDecorators) { + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 169 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } + } else if (languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators) { + checkExternalEmitHelpers(firstDecorator, 8 /* ESDecorateAndRunInitializers */); + if (isClassDeclaration(node)) { + if (!node.name) { + checkExternalEmitHelpers(firstDecorator, 4194304 /* SetFunctionName */); + } else { + const member = getFirstTransformableStaticClassElement(node); + if (member) { + checkExternalEmitHelpers(firstDecorator, 4194304 /* SetFunctionName */); + } + } + } else if (!isClassExpression(node)) { + if (isPrivateIdentifier(node.name) && (isMethodDeclaration(node) || isAccessor(node) || isAutoAccessorPropertyDeclaration(node))) { + checkExternalEmitHelpers(firstDecorator, 4194304 /* SetFunctionName */); + } + if (isComputedPropertyName(node.name)) { + checkExternalEmitHelpers(firstDecorator, 8388608 /* PropKey */); + } + } + } + markLinkedReferences(node, 8 /* Decorator */); + for (const modifier of node.modifiers) { + if (isDecorator(modifier)) { + checkDecorator(modifier); + } + } + } + function checkFunctionDeclaration(node) { + addLazyDiagnostic(checkFunctionDeclarationDiagnostics); + function checkFunctionDeclarationDiagnostics() { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionsForDeclarationName(node, node.name); + } + } + function checkJSDocTypeAliasTag(node) { + if (!node.typeExpression) { + error(node.name, Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); + } + if (node.name) { + checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0); + } + checkSourceElement(node.typeExpression); + checkTypeParameters(getEffectiveTypeParameterDeclarations(node)); + } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (const tp of node.typeParameters) { + checkSourceElement(tp); + } + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); + } + function checkJSDocSatisfiesTag(node) { + checkSourceElement(node.typeExpression); + const host2 = getEffectiveJSDocHost(node); + if (host2) { + const tags = getAllJSDocTags(host2, isJSDocSatisfiesTag); + if (length(tags) > 1) { + for (let i = 1; i < length(tags); i++) { + const tagName = tags[i].tagName; + error(tagName, Diagnostics._0_tag_already_specified, idText(tagName)); + } + } + } + } + function checkJSDocLinkLikeTag(node) { + if (node.name) { + resolveJSDocMemberName( + node.name, + /*ignoreErrors*/ + true + ); + } + } + function checkJSDocParameterTag(node) { + checkSourceElement(node.typeExpression); + } + function checkJSDocPropertyTag(node) { + checkSourceElement(node.typeExpression); + } + function checkJSDocFunctionType(node) { + addLazyDiagnostic(checkJSDocFunctionTypeImplicitAny); + checkSignatureDeclaration(node); + function checkJSDocFunctionTypeImplicitAny() { + if (!node.type && !isJSDocConstructSignature(node)) { + reportImplicitAny(node, anyType); + } + } + } + function checkJSDocThisTag(node) { + const host2 = getEffectiveJSDocHost(node); + if (host2 && isArrowFunction(host2)) { + error(node.tagName, Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } + } + function checkJSDocImportTag(node) { + checkImportAttributes(node); + } + function checkJSDocImplementsTag(node) { + const classLike = getEffectiveJSDocHost(node); + if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) { + error(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName)); + } + } + function checkJSDocAugmentsTag(node) { + const classLike = getEffectiveJSDocHost(node); + if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) { + error(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName)); + return; + } + const augmentsTags = getJSDocTags(classLike).filter(isJSDocAugmentsTag); + Debug.assert(augmentsTags.length > 0); + if (augmentsTags.length > 1) { + error(augmentsTags[1], Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); + } + const name = getIdentifierFromEntityNameExpression(node.class.expression); + const extend2 = getClassExtendsHeritageElement(classLike); + if (extend2) { + const className = getIdentifierFromEntityNameExpression(extend2.expression); + if (className && name.escapedText !== className.escapedText) { + error(name, Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, idText(node.tagName), idText(name), idText(className)); + } + } + } + function checkJSDocAccessibilityModifiers(node) { + const host2 = getJSDocHost(node); + if (host2 && isPrivateIdentifierClassElementDeclaration(host2)) { + error(node, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); + } + } + function getIdentifierFromEntityNameExpression(node) { + switch (node.kind) { + case 80 /* Identifier */: + return node; + case 211 /* PropertyAccessExpression */: + return node.name; + default: + return void 0; + } + } + function checkFunctionOrMethodDeclaration(node) { + var _a; + checkDecorators(node); + checkSignatureDeclaration(node); + const functionFlags = getFunctionFlags(node); + if (node.name && node.name.kind === 167 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + if (hasBindableName(node)) { + const symbol = getSymbolOfDeclaration(node); + const localSymbol = node.localSymbol || symbol; + const firstDeclaration = (_a = localSymbol.declarations) == null ? void 0 : _a.find( + // Get first non javascript function declaration + (declaration) => declaration.kind === node.kind && !(declaration.flags & 524288 /* JavaScriptFile */) + ); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + checkFunctionOrConstructorSymbol(symbol); + } + } + const body = node.kind === 173 /* MethodSignature */ ? void 0 : node.body; + checkSourceElement(body); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); + addLazyDiagnostic(checkFunctionOrMethodDeclarationDiagnostics); + if (isInJSFile(node)) { + const typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag.typeExpression.type, Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } + function checkFunctionOrMethodDeclarationDiagnostics() { + if (!getEffectiveReturnTypeNode(node)) { + if (nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); + } + if (functionFlags & 1 /* Generator */ && nodeIsPresent(body)) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + } + } + function registerForUnusedIdentifiersCheck(node) { + addLazyDiagnostic(registerForUnusedIdentifiersCheckDiagnostics); + function registerForUnusedIdentifiersCheckDiagnostics() { + const sourceFile = getSourceFileOfNode(node); + let potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } + potentiallyUnusedIdentifiers.push(node); + } + } + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { + for (const node of potentiallyUnusedIdentifiers) { + switch (node.kind) { + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + checkUnusedClassMembers(node, addDiagnostic); + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 307 /* SourceFile */: + case 267 /* ModuleDeclaration */: + case 241 /* Block */: + case 269 /* CaseBlock */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node, addDiagnostic); + break; + case 176 /* Constructor */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 219 /* ArrowFunction */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + if (node.body) { + checkUnusedLocalsAndParameters(node, addDiagnostic); + } + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 173 /* MethodSignature */: + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + case 265 /* TypeAliasDeclaration */: + case 264 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 195 /* InferType */: + checkUnusedInferTypeParameter(node, addDiagnostic); + break; + default: + Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); + } + } + } + function errorUnusedLocal(declaration, name, addDiagnostic) { + const node = getNameOfDeclaration(declaration) || declaration; + const message = isTypeDeclaration(declaration) ? Diagnostics._0_is_declared_but_never_used : Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(declaration, 0 /* Local */, createDiagnosticForNode(node, message, name)); + } + function isIdentifierThatStartsWithUnderscore(node) { + return isIdentifier(node) && idText(node).charCodeAt(0) === 95 /* _ */; + } + function checkUnusedClassMembers(node, addDiagnostic) { + for (const member of node.members) { + switch (member.kind) { + case 174 /* MethodDeclaration */: + case 172 /* PropertyDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + if (member.kind === 178 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + break; + } + const symbol = getSymbolOfDeclaration(member); + if (!symbol.isReferenced && (hasEffectiveModifier(member, 2 /* Private */) || isNamedDeclaration(member) && isPrivateIdentifier(member.name)) && !(member.flags & 33554432 /* Ambient */)) { + addDiagnostic(member, 0 /* Local */, createDiagnosticForNode(member.name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + } + break; + case 176 /* Constructor */: + for (const parameter of member.parameters) { + if (!parameter.symbol.isReferenced && hasSyntacticModifier(parameter, 2 /* Private */)) { + addDiagnostic(parameter, 0 /* Local */, createDiagnosticForNode(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol))); + } + } + break; + case 181 /* IndexSignature */: + case 240 /* SemicolonClassElement */: + case 175 /* ClassStaticBlockDeclaration */: + break; + default: + Debug.fail("Unexpected class member"); + } + } + } + function checkUnusedInferTypeParameter(node, addDiagnostic) { + const { typeParameter } = node; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, createDiagnosticForNode(node, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(typeParameter.name))); + } + } + function checkUnusedTypeParameters(node, addDiagnostic) { + const declarations = getSymbolOfDeclaration(node).declarations; + if (!declarations || last(declarations) !== node) return; + const typeParameters = getEffectiveTypeParameterDeclarations(node); + const seenParentsWithEveryUnused = /* @__PURE__ */ new Set(); + for (const typeParameter of typeParameters) { + if (!isTypeParameterUnused(typeParameter)) continue; + const name = idText(typeParameter.name); + const { parent } = typeParameter; + if (parent.kind !== 195 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (tryAddToSet(seenParentsWithEveryUnused, parent)) { + const sourceFile = getSourceFileOfNode(parent); + const range = isJSDocTemplateTag(parent) ? rangeOfNode(parent) : rangeOfTypeParameters(sourceFile, parent.typeParameters); + const only = parent.typeParameters.length === 1; + const messageAndArg = only ? [Diagnostics._0_is_declared_but_its_value_is_never_read, name] : [Diagnostics.All_type_parameters_are_unused]; + addDiagnostic(typeParameter, 1 /* Parameter */, createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ...messageAndArg)); + } + } else { + addDiagnostic(typeParameter, 1 /* Parameter */, createDiagnosticForNode(typeParameter, Diagnostics._0_is_declared_but_its_value_is_never_read, name)); + } + } + } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } + function addToGroup(map2, key, value, getKey) { + const keyString = String(getKey(key)); + const group2 = map2.get(keyString); + if (group2) { + group2[1].push(value); + } else { + map2.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return tryCast(getRootDeclaration(node), isParameter); + } + function isValidUnusedLocalDeclaration(declaration) { + if (isBindingElement(declaration)) { + if (isObjectBindingPattern(declaration.parent)) { + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); + } + return isAmbientModule(declaration) || (isVariableDeclaration(declaration) && isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + const unusedImports = /* @__PURE__ */ new Map(); + const unusedDestructures = /* @__PURE__ */ new Map(); + const unusedVariables = /* @__PURE__ */ new Map(); + nodeWithLocals.locals.forEach((local) => { + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + if (local.declarations) { + for (const declaration of local.declarations) { + if (isValidUnusedLocalDeclaration(declaration)) { + continue; + } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } else if (isBindingElement(declaration) && isObjectBindingPattern(declaration.parent)) { + const lastElement = last(declaration.parent.elements); + if (declaration === lastElement || !last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } else if (isVariableDeclaration(declaration)) { + const blockScopeKind = getCombinedNodeFlagsCached(declaration) & 7 /* BlockScoped */; + const name = getNameOfDeclaration(declaration); + if (blockScopeKind !== 4 /* Using */ && blockScopeKind !== 6 /* AwaitUsing */ || !name || !isIdentifierThatStartsWithUnderscore(name)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + } else { + const parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + const name = local.valueDeclaration && getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!isParameterPropertyDeclaration(parameter, parameter.parent) && !parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + if (isBindingElement(declaration) && isArrayBindingPattern(declaration.parent)) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } else { + addDiagnostic(parameter, 1 /* Parameter */, createDiagnosticForNode(name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolName(local))); + } + } + } else { + errorUnusedLocal(declaration, symbolName(local), addDiagnostic); + } + } + } + } + }); + unusedImports.forEach(([importClause, unuseds]) => { + const importDecl = importClause.parent; + const nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? importClause.namedBindings.kind === 274 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic( + importDecl, + 0 /* Local */, + unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused) + ); + } else { + for (const unused of unuseds) errorUnusedLocal(unused, idText(unused.name), addDiagnostic); + } + }); + unusedDestructures.forEach(([bindingPattern, bindingElements]) => { + const kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 260 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 261 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); + } else { + addDiagnostic( + bindingPattern, + kind, + bindingElements.length === 1 ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused) + ); + } + } else { + for (const e of bindingElements) { + addDiagnostic(e, kind, createDiagnosticForNode(e, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); + } + } + }); + unusedVariables.forEach(([declarationList, declarations]) => { + if (declarationList.declarations.length === declarations.length) { + addDiagnostic( + declarationList, + 0 /* Local */, + declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === 243 /* VariableStatement */ ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused) + ); + } else { + for (const decl of declarations) { + addDiagnostic(decl, 0 /* Local */, createDiagnosticForNode(decl, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); + } + } + }); + } + function checkPotentialUncheckedRenamedBindingElementsInTypes() { + var _a; + for (const node of potentialUnusedRenamedBindingElementsInTypes) { + if (!((_a = getSymbolOfDeclaration(node)) == null ? void 0 : _a.isReferenced)) { + const wrappingDeclaration = walkUpBindingElementsAndPatterns(node); + Debug.assert(isPartOfParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); + const diagnostic = createDiagnosticForNode(node.name, Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, declarationNameToString(node.name), declarationNameToString(node.propertyName)); + if (!wrappingDeclaration.type) { + addRelatedInfo( + diagnostic, + createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 0, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName)) + ); + } + diagnostics.add(diagnostic); + } + } + } + function bindingNameText(name) { + switch (name.kind) { + case 80 /* Identifier */: + return idText(name); + case 207 /* ArrayBindingPattern */: + case 206 /* ObjectBindingPattern */: + return bindingNameText(cast(first(name.elements), isBindingElement).name); + default: + return Debug.assertNever(name); + } + } + function isImportedDeclaration(node) { + return node.kind === 273 /* ImportClause */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 274 /* NamespaceImport */; + } + function importClauseFromImported(decl) { + return decl.kind === 273 /* ImportClause */ ? decl : decl.kind === 274 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + } + function checkBlock(node) { + if (node.kind === 241 /* Block */) { + checkGrammarStatementInAmbientContext(node); + } + if (isFunctionOrModuleBlock(node)) { + const saveFlowAnalysisDisabled = flowAnalysisDisabled; + forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } else { + forEach(node.statements, checkSourceElement); + } + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + if (languageVersion >= 2 /* ES2015 */ || !hasRestParameter(node) || node.flags & 33554432 /* Ambient */ || nodeIsMissing(node.body)) { + return; + } + forEach(node.parameters, (p) => { + if (p.name && !isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + errorSkippedOn("noEmit", p, Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if ((identifier == null ? void 0 : identifier.escapedText) !== name) { + return false; + } + if (node.kind === 172 /* PropertyDeclaration */ || node.kind === 171 /* PropertySignature */ || node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */ || node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */ || node.kind === 303 /* PropertyAssignment */) { + return false; + } + if (node.flags & 33554432 /* Ambient */) { + return false; + } + if (isImportClause(node) || isImportEqualsDeclaration(node) || isImportSpecifier(node)) { + if (isTypeOnlyImportOrExportDeclaration(node)) { + return false; + } + } + const root = getRootDeclaration(node); + if (isParameter(root) && nodeIsMissing(root.parent.body)) { + return false; + } + return true; + } + function checkIfThisIsCapturedInEnclosingScope(node) { + findAncestor(node, (current) => { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + const isDeclaration2 = node.kind !== 80 /* Identifier */; + if (isDeclaration2) { + error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + } else { + error(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + } + return true; + } + return false; + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + findAncestor(node, (current) => { + if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { + const isDeclaration2 = node.kind !== 80 /* Identifier */; + if (isDeclaration2) { + error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + } else { + error(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); + } + return true; + } + return false; + }); + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) >= 5 /* ES2015 */) { + return; + } + if (!name || !needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + if (isModuleDeclaration(node) && getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + const parent = getDeclarationContainer(node); + if (parent.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(parent)) { + errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (!name || languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + if (isModuleDeclaration(node) && getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + const parent = getDeclarationContainer(node); + if (parent.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(parent) && parent.flags & 4096 /* HasAsyncFunctions */) { + errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name)); + } + } + function recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name) { + if (languageVersion <= 8 /* ES2021 */ && (needCollisionCheckForIdentifier(node, name, "WeakMap") || needCollisionCheckForIdentifier(node, name, "WeakSet"))) { + potentialWeakMapSetCollisions.push(node); + } + } + function checkWeakMapSetCollision(node) { + const enclosingBlockScope = getEnclosingBlockScopeContainer(node); + if (getNodeCheckFlags(enclosingBlockScope) & 1048576 /* ContainsClassWithPrivateIdentifiers */) { + Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); + errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); + } + } + function recordPotentialCollisionWithReflectInGeneratedCode(node, name) { + if (name && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && needCollisionCheckForIdentifier(node, name, "Reflect")) { + potentialReflectCollisions.push(node); + } + } + function checkReflectCollision(node) { + let hasCollision = false; + if (isClassExpression(node)) { + for (const member of node.members) { + if (getNodeCheckFlags(member) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { + hasCollision = true; + break; + } + } + } else if (isFunctionExpression(node)) { + if (getNodeCheckFlags(node) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { + hasCollision = true; + } + } else { + const container = getEnclosingBlockScopeContainer(node); + if (container && getNodeCheckFlags(container) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) { + hasCollision = true; + } + } + if (hasCollision) { + Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name), "The target of a Reflect collision check should be an identifier"); + errorSkippedOn("noEmit", node, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers, declarationNameToString(node.name), "Reflect"); + } + } + function checkCollisionsForDeclarationName(node, name) { + if (!name) return; + checkCollisionWithRequireExportsInGeneratedCode(node, name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, name); + recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name); + recordPotentialCollisionWithReflectInGeneratedCode(node, name); + if (isClassLike(node)) { + checkTypeNameIsReserved(name, Diagnostics.Class_name_cannot_be_0); + if (!(node.flags & 33554432 /* Ambient */)) { + checkClassNameCollisionWithObject(name); + } + } else if (isEnumDeclaration(node)) { + checkTypeNameIsReserved(name, Diagnostics.Enum_name_cannot_be_0); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + if ((getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */) !== 0 || isPartOfParameterDeclaration(node)) { + return; + } + const symbol = getSymbolOfDeclaration(node); + if (symbol.flags & 1 /* FunctionScopedVariable */) { + if (!isIdentifier(node.name)) return Debug.fail(); + const localDeclarationSymbol = resolveName( + node, + node.name.escapedText, + 3 /* Variable */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + ); + if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 7 /* BlockScoped */) { + const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, 261 /* VariableDeclarationList */); + const container = varDeclList.parent.kind === 243 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : void 0; + const namesShareScope = container && (container.kind === 241 /* Block */ && isFunctionLike(container.parent) || container.kind === 268 /* ModuleBlock */ || container.kind === 267 /* ModuleDeclaration */ || container.kind === 307 /* SourceFile */); + if (!namesShareScope) { + const name = symbolToString(localDeclarationSymbol); + error(node, Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + function checkVariableLikeDeclaration(node) { + var _a; + checkDecorators(node); + if (!isBindingElement(node)) { + checkSourceElement(node.type); + } + if (!node.name) { + return; + } + if (node.name.kind === 167 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + if (hasOnlyExpressionInitializer(node) && node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (isBindingElement(node)) { + if (node.propertyName && isIdentifier(node.name) && isPartOfParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) { + potentialUnusedRenamedBindingElementsInTypes.push(node); + return; + } + if (isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } + if (node.propertyName && node.propertyName.kind === 167 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + const parent = node.parent.parent; + const parentCheckMode = node.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */; + const parentType = getTypeForBindingElementParent(parent, parentCheckMode); + const name = node.propertyName || node.name; + if (parentType && !isBindingPattern(name)) { + const exprType = getLiteralTypeFromPropertyName(name); + if (isTypeUsableAsPropertyName(exprType)) { + const nameText = getPropertyNameFromType(exprType); + const property = getPropertyOfType(parentType, nameText); + if (property) { + markPropertyAsReferenced( + property, + /*nodeForCheckWriteOnly*/ + void 0, + /*isSelfTypeAccess*/ + false + ); + checkPropertyAccessibility( + node, + !!parent.initializer && parent.initializer.kind === 108 /* SuperKeyword */, + /*writing*/ + false, + parentType, + property + ); + } + } + } + } + if (isBindingPattern(node.name)) { + if (node.name.kind === 207 /* ArrayBindingPattern */ && languageVersion < LanguageFeatureMinimumTarget.BindingPatterns && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + forEach(node.name.elements, checkSourceElement); + } + if (node.initializer && isPartOfParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) { + error(node, Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + if (isBindingPattern(node.name)) { + if (isInAmbientOrTypeNode(node)) { + return; + } + const needCheckInitializer = hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 249 /* ForInStatement */; + const needCheckWidenedType = !some(node.name.elements, not(isOmittedExpression)); + if (needCheckInitializer || needCheckWidenedType) { + const widenedType = getWidenedTypeForVariableLikeDeclaration(node); + if (needCheckInitializer) { + const initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && needCheckWidenedType) { + checkNonNullNonVoidType(initializerType, node); + } else { + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); + } + } + if (needCheckWidenedType) { + if (isArrayBindingPattern(node.name)) { + checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node); + } else if (strictNullChecks) { + checkNonNullNonVoidType(widenedType, node); + } + } + } + return; + } + const symbol = getSymbolOfDeclaration(node); + if (symbol.flags & 2097152 /* Alias */ && (isVariableDeclarationInitializedToBareOrAccessedRequire(node) || isBindingElementOfBareOrAccessedRequire(node))) { + checkAliasSymbol(node); + return; + } + if (node.name.kind === 10 /* BigIntLiteral */) { + error(node.name, Diagnostics.A_bigint_literal_cannot_be_used_as_a_property_name); + } + const type = convertAutoToAny(getTypeOfSymbol(symbol)); + if (node === symbol.valueDeclaration) { + const initializer = hasOnlyExpressionInitializer(node) && getEffectiveInitializer(node); + if (initializer) { + const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && !!((_a = symbol.exports) == null ? void 0 : _a.size); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 249 /* ForInStatement */) { + const initializerType = checkExpressionCached(initializer); + checkTypeAssignableToAndOptionallyElaborate( + initializerType, + type, + node, + initializer, + /*headMessage*/ + void 0 + ); + const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */; + if (blockScopeKind === 6 /* AwaitUsing */) { + const globalAsyncDisposableType = getGlobalAsyncDisposableType( + /*reportErrors*/ + true + ); + const globalDisposableType = getGlobalDisposableType( + /*reportErrors*/ + true + ); + if (globalAsyncDisposableType !== emptyObjectType && globalDisposableType !== emptyObjectType) { + const optionalDisposableType = getUnionType([globalAsyncDisposableType, globalDisposableType, nullType, undefinedType]); + checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined); + } + } else if (blockScopeKind === 4 /* Using */) { + const globalDisposableType = getGlobalDisposableType( + /*reportErrors*/ + true + ); + if (globalDisposableType !== emptyObjectType) { + const optionalDisposableType = getUnionType([globalDisposableType, nullType, undefinedType]); + checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined); + } + } + } + } + if (symbol.declarations && symbol.declarations.length > 1) { + if (some(symbol.declarations, (d) => d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) { + error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); + } + } + } else { + const declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (!isErrorType(type) && !isErrorType(declarationType) && !isTypeIdenticalTo(type, declarationType) && !(symbol.flags & 67108864 /* Assignment */)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); + } + if (hasOnlyExpressionInitializer(node) && node.initializer) { + checkTypeAssignableToAndOptionallyElaborate( + checkExpressionCached(node.initializer), + declarationType, + node, + node.initializer, + /*headMessage*/ + void 0 + ); + } + if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); + } + } + if (node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 171 /* PropertySignature */) { + checkExportsOnMergedDeclarations(node); + if (node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionsForDeclarationName(node, node.name); + } + } + function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) { + const nextDeclarationName = getNameOfDeclaration(nextDeclaration); + const message = nextDeclaration.kind === 172 /* PropertyDeclaration */ || nextDeclaration.kind === 171 /* PropertySignature */ ? Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; + const declName = declarationNameToString(nextDeclarationName); + const err = error( + nextDeclarationName, + message, + declName, + typeToString(firstType), + typeToString(nextType) + ); + if (firstDeclaration) { + addRelatedInfo(err, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName)); + } + } + function areDeclarationFlagsIdentical(left, right) { + if (left.kind === 169 /* Parameter */ && right.kind === 260 /* VariableDeclaration */ || left.kind === 260 /* VariableDeclaration */ && right.kind === 169 /* Parameter */) { + return true; + } + if (hasQuestionToken(left) !== hasQuestionToken(right)) { + return false; + } + const interestingFlags = 2 /* Private */ | 4 /* Protected */ | 1024 /* Async */ | 64 /* Abstract */ | 8 /* Readonly */ | 256 /* Static */; + return getSelectedEffectiveModifierFlags(left, interestingFlags) === getSelectedEffectiveModifierFlags(right, interestingFlags); + } + function checkVariableDeclaration(node) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); + checkGrammarVariableDeclaration(node); + checkVariableLikeDeclaration(node); + (_b = tracing) == null ? void 0 : _b.pop(); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableDeclarationList(node) { + const blockScopeKind = getCombinedNodeFlags(node) & 7 /* BlockScoped */; + if ((blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */) && languageVersion < LanguageFeatureMinimumTarget.UsingAndAwaitUsing) { + checkExternalEmitHelpers(node, 16777216 /* AddDisposableResourceAndDisposeResources */); + } + forEach(node.declarations, checkSourceElement); + } + function checkVariableStatement(node) { + if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedBlockScopedVariableStatement(node); + checkVariableDeclarationList(node.declarationList); + } + function checkExpressionStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + checkGrammarStatementInAmbientContext(node); + const type = checkTruthinessExpression(node.expression); + checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.expression, type, node.thenStatement); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 242 /* EmptyStatement */) { + error(node.thenStatement, Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(condExpr, condType, body) { + if (!strictNullChecks) return; + bothHelper(condExpr, body); + function bothHelper(condExpr2, body2) { + condExpr2 = skipParentheses(condExpr2); + helper(condExpr2, body2); + while (isBinaryExpression(condExpr2) && (condExpr2.operatorToken.kind === 57 /* BarBarToken */ || condExpr2.operatorToken.kind === 61 /* QuestionQuestionToken */)) { + condExpr2 = skipParentheses(condExpr2.left); + helper(condExpr2, body2); + } + } + function helper(condExpr2, body2) { + const location = isLogicalOrCoalescingBinaryExpression(condExpr2) ? skipParentheses(condExpr2.right) : condExpr2; + if (isModuleExportsAccessExpression(location)) { + return; + } + if (isLogicalOrCoalescingBinaryExpression(location)) { + bothHelper(location, body2); + return; + } + const type = location === condExpr2 ? condType : checkExpression(location); + if (type.flags & 1024 /* EnumLiteral */ && isPropertyAccessExpression(location) && (getNodeLinks(location.expression).resolvedSymbol ?? unknownSymbol).flags & 384 /* Enum */) { + error(location, Diagnostics.This_condition_will_always_return_0, !!type.value ? "true" : "false"); + return; + } + const isPropertyExpressionCast = isPropertyAccessExpression(location) && isTypeAssertion(location.expression); + if (!hasTypeFacts(type, 4194304 /* Truthy */) || isPropertyExpressionCast) return; + const callSignatures = getSignaturesOfType(type, 0 /* Call */); + const isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { + return; + } + const testedNode = isIdentifier(location) ? location : isPropertyAccessExpression(location) ? location.name : void 0; + const testedSymbol = testedNode && getSymbolAtLocation(testedNode); + if (!testedSymbol && !isPromise) { + return; + } + const isUsed = testedSymbol && isBinaryExpression(condExpr2.parent) && isSymbolUsedInBinaryExpressionChain(condExpr2.parent, testedSymbol) || testedSymbol && body2 && isSymbolUsedInConditionBody(condExpr2, body2, testedNode, testedSymbol); + if (!isUsed) { + if (isPromise) { + errorAndMaybeSuggestAwait( + location, + /*maybeMissingAwait*/ + true, + Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, + getTypeNameForErrorDisplay(type) + ); + } else { + error(location, Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } + } + } + } + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { + return !!forEachChild(body, function check(childNode) { + if (isIdentifier(childNode)) { + const childSymbol = getSymbolAtLocation(childNode); + if (childSymbol && childSymbol === testedSymbol) { + if (isIdentifier(expr) || isIdentifier(testedNode) && isBinaryExpression(testedNode.parent)) { + return true; + } + let testedExpression = testedNode.parent; + let childExpression = childNode.parent; + while (testedExpression && childExpression) { + if (isIdentifier(testedExpression) && isIdentifier(childExpression) || testedExpression.kind === 110 /* ThisKeyword */ && childExpression.kind === 110 /* ThisKeyword */) { + return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); + } else if (isPropertyAccessExpression(testedExpression) && isPropertyAccessExpression(childExpression)) { + if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) { + return false; + } + childExpression = childExpression.expression; + testedExpression = testedExpression.expression; + } else if (isCallExpression(testedExpression) && isCallExpression(childExpression)) { + childExpression = childExpression.expression; + testedExpression = testedExpression.expression; + } else { + return false; + } + } + } + } + return forEachChild(childNode, check); + }); + } + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { + while (isBinaryExpression(node) && node.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { + const isUsed = forEachChild(node.right, function visit(child) { + if (isIdentifier(child)) { + const symbol = getSymbolAtLocation(child); + if (symbol && symbol === testedSymbol) { + return true; + } + } + return forEachChild(child, visit); + }); + if (isUsed) { + return true; + } + node = node.parent; + } + return false; + } + function checkDoStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkTruthinessExpression(node.expression); + } + function checkWhileStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkTruthinessExpression(node.expression); + checkSourceElement(node.statement); + } + function checkTruthinessOfType(type, node) { + if (type.flags & 16384 /* Void */) { + error(node, Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } else { + const semantics = getSyntacticTruthySemantics(node); + if (semantics !== 3 /* Sometimes */) { + error( + node, + semantics === 1 /* Always */ ? Diagnostics.This_kind_of_expression_is_always_truthy : Diagnostics.This_kind_of_expression_is_always_falsy + ); + } + } + return type; + } + function getSyntacticTruthySemantics(node) { + node = skipOuterExpressions(node); + switch (node.kind) { + case 9 /* NumericLiteral */: + if (node.text === "0" || node.text === "1") { + return 3 /* Sometimes */; + } + return 1 /* Always */; + case 209 /* ArrayLiteralExpression */: + case 219 /* ArrowFunction */: + case 10 /* BigIntLiteral */: + case 231 /* ClassExpression */: + case 218 /* FunctionExpression */: + case 284 /* JsxElement */: + case 285 /* JsxSelfClosingElement */: + case 210 /* ObjectLiteralExpression */: + case 14 /* RegularExpressionLiteral */: + return 1 /* Always */; + case 222 /* VoidExpression */: + case 106 /* NullKeyword */: + return 2 /* Never */; + case 15 /* NoSubstitutionTemplateLiteral */: + case 11 /* StringLiteral */: + return !!node.text ? 1 /* Always */ : 2 /* Never */; + case 227 /* ConditionalExpression */: + return getSyntacticTruthySemantics(node.whenTrue) | getSyntacticTruthySemantics(node.whenFalse); + case 80 /* Identifier */: + if (getResolvedSymbol(node) === undefinedSymbol) { + return 2 /* Never */; + } + return 3 /* Sometimes */; + } + return 3 /* Sometimes */; + } + function checkTruthinessExpression(node, checkMode) { + return checkTruthinessOfType(checkExpression(node, checkMode), node); + } + function checkForStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 261 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 261 /* VariableDeclarationList */) { + checkVariableDeclarationList(node.initializer); + } else { + checkExpression(node.initializer); + } + } + if (node.condition) checkTruthinessExpression(node.condition); + if (node.incrementor) checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + const container = getContainingFunctionOrClassStaticBlock(node); + if (node.awaitModifier) { + if (container && isClassStaticBlockDeclaration(container)) { + grammarErrorOnNode(node.awaitModifier, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block); + } else { + const functionFlags = getFunctionFlags(container); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < LanguageFeatureMinimumTarget.ForAwaitOf) { + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); + } + } + } else if (compilerOptions.downlevelIteration && languageVersion < LanguageFeatureMinimumTarget.ForOf) { + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } + if (node.initializer.kind === 261 /* VariableDeclarationList */) { + checkVariableDeclarationList(node.initializer); + } else { + const varExpr = node.initializer; + const iteratedType = checkRightHandSideOfForOf(node); + if (varExpr.kind === 209 /* ArrayLiteralExpression */ || varExpr.kind === 210 /* ObjectLiteralExpression */) { + checkDestructuringAssignment(varExpr, iteratedType || errorType); + } else { + const leftType = checkExpression(varExpr); + checkReferenceExpression( + varExpr, + Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access, + Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access + ); + if (iteratedType) { + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + checkGrammarForInOrForOfStatement(node); + const rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); + if (node.initializer.kind === 261 /* VariableDeclarationList */) { + const variable = node.initializer.declarations[0]; + if (variable && isBindingPattern(variable.name)) { + error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkVariableDeclarationList(node.initializer); + } else { + const varExpr = node.initializer; + const leftType = checkExpression(varExpr); + if (varExpr.kind === 209 /* ArrayLiteralExpression */ || varExpr.kind === 210 /* ObjectLiteralExpression */) { + error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } else { + checkReferenceExpression( + varExpr, + Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access, + Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access + ); + } + } + if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { + error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType)); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkRightHandSideOfForOf(statement) { + const use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); + } + function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType( + use, + inputType, + sentType, + errorNode, + /*checkAssignability*/ + true + ) || anyType; + } + function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) { + const allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0; + if (inputType === neverType) { + if (errorNode) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); + } + return void 0; + } + const uplevelIteration = languageVersion >= 2 /* ES2015 */; + const downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + const possibleOutOfBounds = compilerOptions.noUncheckedIndexedAccess && !!(use & 128 /* PossiblyOutOfBounds */); + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + const iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : void 0); + if (checkAssignability) { + if (iterationTypes) { + const diagnostic = use & 8 /* ForOfFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 : use & 32 /* SpreadFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 : use & 64 /* DestructuringFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 : use & 16 /* YieldStarFlag */ ? Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 : void 0; + if (diagnostic) { + checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic); + } + } + } + if (iterationTypes || uplevelIteration) { + return possibleOutOfBounds ? includeUndefinedInIndexSignature(iterationTypes && iterationTypes.yieldType) : iterationTypes && iterationTypes.yieldType; + } + } + let arrayType = inputType; + let hasStringConstituent = false; + if (use & 4 /* AllowsStringInputFlag */) { + if (arrayType.flags & 1048576 /* Union */) { + const arrayTypes = inputType.types; + const filteredTypes = filter(arrayTypes, (t) => !(t.flags & 402653316 /* StringLike */)); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, 2 /* Subtype */); + } + } else if (arrayType.flags & 402653316 /* StringLike */) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (arrayType.flags & 131072 /* Never */) { + return possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode) { + const allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent; + const [defaultDiagnostic, maybeMissingAwait] = getIterationDiagnosticDetails(allowsStrings, downlevelIteration); + errorAndMaybeSuggestAwait( + errorNode, + maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), + defaultDiagnostic, + typeToString(arrayType) + ); + } + return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : void 0; + } + const arrayElementType = getIndexTypeOfType(arrayType, numberType); + if (hasStringConstituent && arrayElementType) { + if (arrayElementType.flags & 402653316 /* StringLike */ && !compilerOptions.noUncheckedIndexedAccess) { + return stringType; + } + return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */); + } + return use & 128 /* PossiblyOutOfBounds */ ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; + function getIterationDiagnosticDetails(allowsStrings, downlevelIteration2) { + var _a; + if (downlevelIteration2) { + return allowsStrings ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] : [Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]; + } + const yieldType = getIterationTypeOfIterable( + use, + 0 /* Yield */, + inputType, + /*errorNode*/ + void 0 + ); + if (yieldType) { + return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, false]; + } + if (isES2015OrLaterIterable((_a = inputType.symbol) == null ? void 0 : _a.escapedName)) { + return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true]; + } + return allowsStrings ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] : [Diagnostics.Type_0_is_not_an_array_type, true]; + } + } + function isES2015OrLaterIterable(n) { + switch (n) { + case "Float32Array": + case "Float64Array": + case "Int16Array": + case "Int32Array": + case "Int8Array": + case "NodeList": + case "Uint16Array": + case "Uint32Array": + case "Uint8Array": + case "Uint8ClampedArray": + return true; + } + return false; + } + function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) { + if (isTypeAny(inputType)) { + return void 0; + } + const iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode); + return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)]; + } + function createIterationTypes(yieldType = neverType, returnType = neverType, nextType = unknownType) { + if (yieldType.flags & 67359327 /* Intrinsic */ && returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) && nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) { + const id = getTypeListId([yieldType, returnType, nextType]); + let iterationTypes = iterationTypesCache.get(id); + if (!iterationTypes) { + iterationTypes = { yieldType, returnType, nextType }; + iterationTypesCache.set(id, iterationTypes); + } + return iterationTypes; + } + return { yieldType, returnType, nextType }; + } + function combineIterationTypes(array) { + let yieldTypes; + let returnTypes; + let nextTypes; + for (const iterationTypes of array) { + if (iterationTypes === void 0 || iterationTypes === noIterationTypes) { + continue; + } + if (iterationTypes === anyIterationTypes) { + return anyIterationTypes; + } + yieldTypes = append(yieldTypes, iterationTypes.yieldType); + returnTypes = append(returnTypes, iterationTypes.returnType); + nextTypes = append(nextTypes, iterationTypes.nextType); + } + if (yieldTypes || returnTypes || nextTypes) { + return createIterationTypes( + yieldTypes && getUnionType(yieldTypes), + returnTypes && getUnionType(returnTypes), + nextTypes && getIntersectionType(nextTypes) + ); + } + return noIterationTypes; + } + function getCachedIterationTypes(type, cacheKey) { + return type[cacheKey]; + } + function setCachedIterationTypes(type, cacheKey, cachedTypes2) { + return type[cacheKey] = cachedTypes2; + } + function getIterationTypesOfIterable(type, use, errorNode) { + var _a, _b; + if (isTypeAny(type)) { + return anyIterationTypes; + } + if (!(type.flags & 1048576 /* Union */)) { + const errorOutputContainer = errorNode ? { errors: void 0, skipLogging: true } : void 0; + const iterationTypes2 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); + if (iterationTypes2 === noIterationTypes) { + if (errorNode) { + const rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */)); + if (errorOutputContainer == null ? void 0 : errorOutputContainer.errors) { + addRelatedInfo(rootDiag, ...errorOutputContainer.errors); + } + } + return void 0; + } else if ((_a = errorOutputContainer == null ? void 0 : errorOutputContainer.errors) == null ? void 0 : _a.length) { + for (const diag2 of errorOutputContainer.errors) { + diagnostics.add(diag2); + } + } + return iterationTypes2; + } + const cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; + const cachedTypes2 = getCachedIterationTypes(type, cacheKey); + if (cachedTypes2) return cachedTypes2 === noIterationTypes ? void 0 : cachedTypes2; + let allIterationTypes; + for (const constituent of type.types) { + const errorOutputContainer = errorNode ? { errors: void 0 } : void 0; + const iterationTypes2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); + if (iterationTypes2 === noIterationTypes) { + if (errorNode) { + const rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */)); + if (errorOutputContainer == null ? void 0 : errorOutputContainer.errors) { + addRelatedInfo(rootDiag, ...errorOutputContainer.errors); + } + } + setCachedIterationTypes(type, cacheKey, noIterationTypes); + return void 0; + } else if ((_b = errorOutputContainer == null ? void 0 : errorOutputContainer.errors) == null ? void 0 : _b.length) { + for (const diag2 of errorOutputContainer.errors) { + diagnostics.add(diag2); + } + } + allIterationTypes = append(allIterationTypes, iterationTypes2); + } + const iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes; + setCachedIterationTypes(type, cacheKey, iterationTypes); + return iterationTypes === noIterationTypes ? void 0 : iterationTypes; + } + function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) { + if (iterationTypes === noIterationTypes) return noIterationTypes; + if (iterationTypes === anyIterationTypes) return anyIterationTypes; + const { yieldType, returnType, nextType } = iterationTypes; + if (errorNode) { + getGlobalAwaitedSymbol( + /*reportErrors*/ + true + ); + } + return createIterationTypes( + getAwaitedType(yieldType, errorNode) || anyType, + getAwaitedType(returnType, errorNode) || anyType, + nextType + ); + } + function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) { + if (isTypeAny(type)) { + return anyIterationTypes; + } + let noCache = false; + if (use & 2 /* AllowsAsyncIterablesFlag */) { + const iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver); + if (iterationTypes) { + if (iterationTypes === noIterationTypes && errorNode) { + noCache = true; + } else { + return use & 8 /* ForOfFlag */ ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : iterationTypes; + } + } + } + if (use & 1 /* AllowsSyncIterablesFlag */) { + let iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver); + if (iterationTypes) { + if (iterationTypes === noIterationTypes && errorNode) { + noCache = true; + } else { + if (use & 2 /* AllowsAsyncIterablesFlag */) { + if (iterationTypes !== noIterationTypes) { + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); + } + } else { + return iterationTypes; + } + } + } + } + if (use & 2 /* AllowsAsyncIterablesFlag */) { + const iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache); + if (iterationTypes !== noIterationTypes) { + return iterationTypes; + } + } + if (use & 1 /* AllowsSyncIterablesFlag */) { + let iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache); + if (iterationTypes !== noIterationTypes) { + if (use & 2 /* AllowsAsyncIterablesFlag */) { + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); + } else { + return iterationTypes; + } + } + } + return noIterationTypes; + } + function getIterationTypesOfIterableCached(type, resolver) { + return getCachedIterationTypes(type, resolver.iterableCacheKey); + } + function getIterationTypesOfIterableFast(type, resolver) { + if (isReferenceToType(type, resolver.getGlobalIterableType( + /*reportErrors*/ + false + )) || isReferenceToType(type, resolver.getGlobalIteratorObjectType( + /*reportErrors*/ + false + )) || isReferenceToType(type, resolver.getGlobalIterableIteratorType( + /*reportErrors*/ + false + )) || isReferenceToType(type, resolver.getGlobalGeneratorType( + /*reportErrors*/ + false + ))) { + const [yieldType, returnType, nextType] = getTypeArguments(type); + return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType( + yieldType, + /*errorNode*/ + void 0 + ) || yieldType, resolver.resolveIterationType( + returnType, + /*errorNode*/ + void 0 + ) || returnType, nextType)); + } + if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) { + const [yieldType] = getTypeArguments(type); + const returnType = getBuiltinIteratorReturnType(); + const nextType = unknownType; + return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType( + yieldType, + /*errorNode*/ + void 0 + ) || yieldType, resolver.resolveIterationType( + returnType, + /*errorNode*/ + void 0 + ) || returnType, nextType)); + } + } + function getPropertyNameForKnownSymbolName(symbolName2) { + const ctorType = getGlobalESSymbolConstructorSymbol( + /*reportErrors*/ + false + ); + const uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), escapeLeadingUnderscores(symbolName2)); + return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : `__@${symbolName2}`; + } + function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { + const method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); + const methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : void 0; + if (isTypeAny(methodType)) { + return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); + } + const allSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : void 0; + const validSignatures = filter(allSignatures, (sig) => getMinArgumentCount(sig) === 0); + if (!some(validSignatures)) { + if (errorNode && some(allSignatures)) { + checkTypeAssignableTo( + type, + resolver.getGlobalIterableType( + /*reportErrors*/ + true + ), + errorNode, + /*headMessage*/ + void 0, + /*containingMessageChain*/ + void 0, + errorOutputContainer + ); + } + return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); + } + const iteratorType = getIntersectionType(map(validSignatures, getReturnTypeOfSignature)); + const iterationTypes = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache) ?? noIterationTypes; + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); + } + function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { + const message = allowAsyncIterables ? Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; + const suggestAwait = ( + // for (const x of Promise<...>) or [...Promise<...>] + !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType( + /*reportErrors*/ + false + ) !== emptyGenericType && isTypeAssignableTo(type, createTypeFromGenericGlobalType(getGlobalAsyncIterableType( + /*reportErrors*/ + false + ), [anyType, anyType, anyType])) + ); + return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); + } + function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { + return getIterationTypesOfIteratorWorker( + type, + resolver, + errorNode, + errorOutputContainer, + /*noCache*/ + false + ); + } + function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) { + if (isTypeAny(type)) { + return anyIterationTypes; + } + let iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || getIterationTypesOfIteratorFast(type, resolver); + if (iterationTypes === noIterationTypes && errorNode) { + iterationTypes = void 0; + noCache = true; + } + iterationTypes ?? (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); + return iterationTypes === noIterationTypes ? void 0 : iterationTypes; + } + function getIterationTypesOfIteratorCached(type, resolver) { + return getCachedIterationTypes(type, resolver.iteratorCacheKey); + } + function getIterationTypesOfIteratorFast(type, resolver) { + if (isReferenceToType(type, resolver.getGlobalIterableIteratorType( + /*reportErrors*/ + false + )) || isReferenceToType(type, resolver.getGlobalIteratorType( + /*reportErrors*/ + false + )) || isReferenceToType(type, resolver.getGlobalIteratorObjectType( + /*reportErrors*/ + false + )) || isReferenceToType(type, resolver.getGlobalGeneratorType( + /*reportErrors*/ + false + ))) { + const [yieldType, returnType, nextType] = getTypeArguments(type); + return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); + } + if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) { + const [yieldType] = getTypeArguments(type); + const returnType = getBuiltinIteratorReturnType(); + const nextType = unknownType; + return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); + } + } + function isIteratorResult(type, kind) { + const doneType = getTypeOfPropertyOfType(type, "done") || falseType; + return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType); + } + function isYieldIteratorResult(type) { + return isIteratorResult(type, 0 /* Yield */); + } + function isReturnIteratorResult(type) { + return isIteratorResult(type, 1 /* Return */); + } + function getIterationTypesOfIteratorResult(type) { + if (isTypeAny(type)) { + return anyIterationTypes; + } + const cachedTypes2 = getCachedIterationTypes(type, "iterationTypesOfIteratorResult"); + if (cachedTypes2) { + return cachedTypes2; + } + if (isReferenceToType(type, getGlobalIteratorYieldResultType( + /*reportErrors*/ + false + ))) { + const yieldType2 = getTypeArguments(type)[0]; + return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes( + yieldType2, + /*returnType*/ + void 0, + /*nextType*/ + void 0 + )); + } + if (isReferenceToType(type, getGlobalIteratorReturnResultType( + /*reportErrors*/ + false + ))) { + const returnType2 = getTypeArguments(type)[0]; + return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes( + /*yieldType*/ + void 0, + returnType2, + /*nextType*/ + void 0 + )); + } + const yieldIteratorResult = filterType(type, isYieldIteratorResult); + const yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : void 0; + const returnIteratorResult = filterType(type, isReturnIteratorResult); + const returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : void 0; + if (!yieldType && !returnType) { + return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes); + } + return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes( + yieldType, + returnType || voidType, + /*nextType*/ + void 0 + )); + } + function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { + var _a, _b, _c, _d; + const method = getPropertyOfType(type, methodName); + if (!method && methodName !== "next") { + return void 0; + } + const methodType = method && !(methodName === "next" && method.flags & 16777216 /* Optional */) ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */) : void 0; + if (isTypeAny(methodType)) { + return anyIterationTypes; + } + const methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : emptyArray; + if (methodSignatures.length === 0) { + if (errorNode) { + const diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; + if (errorOutputContainer) { + errorOutputContainer.errors ?? (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, diagnostic, methodName)); + } else { + error(errorNode, diagnostic, methodName); + } + } + return methodName === "next" ? noIterationTypes : void 0; + } + if ((methodType == null ? void 0 : methodType.symbol) && methodSignatures.length === 1) { + const globalGeneratorType = resolver.getGlobalGeneratorType( + /*reportErrors*/ + false + ); + const globalIteratorType = resolver.getGlobalIteratorType( + /*reportErrors*/ + false + ); + const isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) == null ? void 0 : _a.members) == null ? void 0 : _b.get(methodName)) === methodType.symbol; + const isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) == null ? void 0 : _c.members) == null ? void 0 : _d.get(methodName)) === methodType.symbol; + if (isGeneratorMethod || isIteratorMethod) { + const globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; + const { mapper } = methodType; + return createIterationTypes( + getMappedType(globalType.typeParameters[0], mapper), + getMappedType(globalType.typeParameters[1], mapper), + methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : void 0 + ); + } + } + let methodParameterTypes; + let methodReturnTypes; + for (const signature of methodSignatures) { + if (methodName !== "throw" && some(signature.parameters)) { + methodParameterTypes = append(methodParameterTypes, getTypeAtPosition(signature, 0)); + } + methodReturnTypes = append(methodReturnTypes, getReturnTypeOfSignature(signature)); + } + let returnTypes; + let nextType; + if (methodName !== "throw") { + const methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType; + if (methodName === "next") { + nextType = methodParameterType; + } else if (methodName === "return") { + const resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType; + returnTypes = append(returnTypes, resolvedMethodParameterType); + } + } + let yieldType; + const methodReturnType = methodReturnTypes ? getIntersectionType(methodReturnTypes) : neverType; + const resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType; + const iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType); + if (iterationTypes === noIterationTypes) { + if (errorNode) { + if (errorOutputContainer) { + errorOutputContainer.errors ?? (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); + } else { + error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + } + } + yieldType = anyType; + returnTypes = append(returnTypes, anyType); + } else { + yieldType = iterationTypes.yieldType; + returnTypes = append(returnTypes, iterationTypes.returnType); + } + return createIterationTypes(yieldType, getUnionType(returnTypes), nextType); + } + function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) { + const iterationTypes = combineIterationTypes([ + getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer) + ]); + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); + } + function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return void 0; + } + const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator); + return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)]; + } + function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) { + if (isTypeAny(type)) { + return anyIterationTypes; + } + const use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */; + const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; + return getIterationTypesOfIterable( + type, + use, + /*errorNode*/ + void 0 + ) || getIterationTypesOfIterator( + type, + resolver, + /*errorNode*/ + void 0, + /*errorOutputContainer*/ + void 0 + ); + } + function checkBreakOrContinueStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) checkGrammarBreakOrContinueStatement(node); + } + function unwrapReturnType(returnType, functionFlags) { + const isGenerator = !!(functionFlags & 1 /* Generator */); + const isAsync = !!(functionFlags & 2 /* Async */); + if (isGenerator) { + const returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync); + if (!returnIterationType) { + return errorType; + } + return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType; + } + return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType; + } + function isUnwrappedReturnTypeUndefinedVoidOrAny(func, returnType) { + const type = unwrapReturnType(returnType, getFunctionFlags(func)); + return !!(type && (maybeTypeOfKind(type, 16384 /* Void */) || type.flags & (1 /* Any */ | 32768 /* Undefined */))); + } + function checkReturnStatement(node) { + if (checkGrammarStatementInAmbientContext(node)) { + return; + } + const container = getContainingFunctionOrClassStaticBlock(node); + if (container && isClassStaticBlockDeclaration(container)) { + grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block); + return; + } + if (!container) { + grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + const signature = getSignatureFromDeclaration(container); + const returnType = getReturnTypeOfSignature(signature); + if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { + const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (container.kind === 178 /* SetAccessor */) { + if (node.expression) { + error(node, Diagnostics.Setters_cannot_return_a_value); + } + } else if (container.kind === 176 /* Constructor */) { + const exprType2 = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType2, returnType, node, node.expression)) { + error(node, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } else if (getReturnTypeFromAnnotation(container)) { + const unwrappedReturnType = unwrapReturnType(returnType, getFunctionFlags(container)) ?? returnType; + checkReturnExpression(container, unwrappedReturnType, node, node.expression, exprType); + } + } else if (container.kind !== 176 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeUndefinedVoidOrAny(container, returnType)) { + error(node, Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkReturnExpression(container, unwrappedReturnType, node, expr, exprType, inConditionalExpression = false) { + const excludeJSDocTypeAssertions = isInJSFile(node); + const functionFlags = getFunctionFlags(container); + if (expr) { + const unwrappedExpr = skipParentheses(expr, excludeJSDocTypeAssertions); + if (isConditionalExpression(unwrappedExpr)) { + checkReturnExpression( + container, + unwrappedReturnType, + node, + unwrappedExpr.whenTrue, + checkExpression(unwrappedExpr.whenTrue), + /*inConditionalExpression*/ + true + ); + checkReturnExpression( + container, + unwrappedReturnType, + node, + unwrappedExpr.whenFalse, + checkExpression(unwrappedExpr.whenFalse), + /*inConditionalExpression*/ + true + ); + return; + } + } + const inReturnStatement = node.kind === 253 /* ReturnStatement */; + const unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType( + exprType, + /*withAlias*/ + false, + node, + Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + ) : exprType; + const effectiveExpr = expr && getEffectiveCheckNode(expr); + const errorNode = inReturnStatement && !inConditionalExpression ? node : effectiveExpr; + checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, errorNode, effectiveExpr); + } + function checkWithStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 65536 /* AwaitContext */) { + grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + const start = getSpanOfTokenAtPosition(sourceFile, node.pos).start; + const end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + checkGrammarStatementInAmbientContext(node); + let firstDefaultClause; + let hasDuplicateDefaultClause = false; + const expressionType = checkExpression(node.expression); + forEach(node.caseBlock.clauses, (clause) => { + if (clause.kind === 297 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (firstDefaultClause === void 0) { + firstDefaultClause = clause; + } else { + grammarErrorOnNode(clause, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (clause.kind === 296 /* CaseClause */) { + addLazyDiagnostic(createLazyCaseClauseDiagnostics(clause)); + } + forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, Diagnostics.Fallthrough_case_in_switch); + } + function createLazyCaseClauseDiagnostics(clause2) { + return () => { + const caseType = checkExpression(clause2.expression); + if (!isTypeEqualityComparableTo(expressionType, caseType)) { + checkTypeComparableTo( + caseType, + expressionType, + clause2.expression, + /*headMessage*/ + void 0 + ); + } + }; + } + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + findAncestor(node.parent, (current) => { + if (isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 256 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNode(node.label)); + return true; + } + return false; + }); + } + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (isIdentifier(node.expression) && !node.expression.escapedText) { + grammarErrorAfterFirstToken(node, Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + const catchClause = node.catchClause; + if (catchClause) { + if (catchClause.variableDeclaration) { + const declaration = catchClause.variableDeclaration; + checkVariableLikeDeclaration(declaration); + const typeNode = getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + const type = getTypeFromTypeNode(typeNode); + if (type && !(type.flags & 3 /* AnyOrUnknown */)) { + grammarErrorOnFirstToken(typeNode, Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); + } + } else if (declaration.initializer) { + grammarErrorOnFirstToken(declaration.initializer, Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } else { + const blockLocals = catchClause.block.locals; + if (blockLocals) { + forEachKey(catchClause.locals, (caughtName) => { + const blockLocal = blockLocals.get(caughtName); + if ((blockLocal == null ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, unescapeLeadingUnderscores(caughtName)); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type, symbol, isStaticIndex) { + const indexInfos = getIndexInfosOfType(type); + if (indexInfos.length === 0) { + return; + } + for (const prop of getPropertiesOfObjectType(type)) { + if (!(isStaticIndex && prop.flags & 4194304 /* Prototype */)) { + checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty( + prop, + 8576 /* StringOrNumberLiteralOrUnique */, + /*includeNonPublic*/ + true + ), getNonMissingTypeOfSymbol(prop)); + } + } + const typeDeclaration = symbol.valueDeclaration; + if (typeDeclaration && isClassLike(typeDeclaration)) { + for (const member of typeDeclaration.members) { + if ((!isStaticIndex && !isStatic(member) || isStaticIndex && isStatic(member)) && !hasBindableName(member)) { + const symbol2 = getSymbolOfDeclaration(member); + checkIndexConstraintForProperty(type, symbol2, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol2)); + } + } + } + if (indexInfos.length > 1) { + for (const info of indexInfos) { + checkIndexConstraintForIndexSignature(type, info); + } + } + } + function checkIndexConstraintForProperty(type, prop, propNameType, propType) { + const declaration = prop.valueDeclaration; + const name = getNameOfDeclaration(declaration); + if (name && isPrivateIdentifier(name)) { + return; + } + const indexInfos = getApplicableIndexInfos(type, propNameType); + const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */) : void 0; + const propDeclaration = declaration && declaration.kind === 226 /* BinaryExpression */ || name && name.kind === 167 /* ComputedPropertyName */ ? declaration : void 0; + const localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : void 0; + for (const info of indexInfos) { + const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0; + const errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0); + if (errorNode && !isTypeAssignableTo(propType, info.type)) { + const diagnostic = createError(errorNode, Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + if (propDeclaration && errorNode !== propDeclaration) { + addRelatedInfo(diagnostic, createDiagnosticForNode(propDeclaration, Diagnostics._0_is_declared_here, symbolToString(prop))); + } + diagnostics.add(diagnostic); + } + } + } + function checkIndexConstraintForIndexSignature(type, checkInfo) { + const declaration = checkInfo.declaration; + const indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); + const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */) : void 0; + const localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfDeclaration(declaration)) === type.symbol ? declaration : void 0; + for (const info of indexInfos) { + if (info === checkInfo) continue; + const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0; + const errorNode = localCheckDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0); + if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) { + error(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type)); + } + } + } + function checkTypeNameIsReserved(name, message) { + switch (name.escapedText) { + case "any": + case "unknown": + case "never": + case "number": + case "bigint": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + case "undefined": + error(name, message, name.escapedText); + } + } + function checkClassNameCollisionWithObject(name) { + if (languageVersion >= 1 /* ES5 */ && name.escapedText === "Object" && host.getEmitModuleFormatOfFile(getSourceFileOfNode(name)) < 5 /* ES2015 */) { + error(name, Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ModuleKind[moduleKind]); + } + } + function checkUnmatchedJSDocParameters(node) { + const jsdocParameters = filter(getJSDocTags(node), isJSDocParameterTag); + if (!length(jsdocParameters)) return; + const isJs = isInJSFile(node); + const parameters = /* @__PURE__ */ new Set(); + const excludedParameters = /* @__PURE__ */ new Set(); + forEach(node.parameters, ({ name }, index) => { + if (isIdentifier(name)) { + parameters.add(name.escapedText); + } + if (isBindingPattern(name)) { + excludedParameters.add(index); + } + }); + const containsArguments = containsArgumentsReference(node); + if (containsArguments) { + const lastJSDocParamIndex = jsdocParameters.length - 1; + const lastJSDocParam = jsdocParameters[lastJSDocParamIndex]; + if (isJs && lastJSDocParam && isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !excludedParameters.has(lastJSDocParamIndex) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) { + error(lastJSDocParam.name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, idText(lastJSDocParam.name)); + } + } else { + forEach(jsdocParameters, ({ name, isNameFirst }, index) => { + if (excludedParameters.has(index) || isIdentifier(name) && parameters.has(name.escapedText)) { + return; + } + if (isQualifiedName(name)) { + if (isJs) { + error(name, Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, entityNameToString(name), entityNameToString(name.left)); + } + } else { + if (!isNameFirst) { + errorOrSuggestion(isJs, name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, idText(name)); + } + } + }); + } + } + function checkTypeParameters(typeParameterDeclarations) { + let seenDefault = false; + if (typeParameterDeclarations) { + for (let i = 0; i < typeParameterDeclarations.length; i++) { + const node = typeParameterDeclarations[i]; + checkTypeParameter(node); + addLazyDiagnostic(createCheckTypeParameterDiagnostic(node, i)); + } + } + function createCheckTypeParameterDiagnostic(node, i) { + return () => { + if (node.default) { + seenDefault = true; + checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); + } else if (seenDefault) { + error(node, Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (let j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name)); + } + } + }; + } + } + function checkTypeParametersNotReferenced(root, typeParameters, index) { + visit(root); + function visit(node) { + if (node.kind === 183 /* TypeReference */) { + const type = getTypeFromTypeReference(node); + if (type.flags & 262144 /* TypeParameter */) { + for (let i = index; i < typeParameters.length; i++) { + if (type.symbol === getSymbolOfDeclaration(typeParameters[i])) { + error(node, Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); + } + } + } + } + forEachChild(node, visit); + } + } + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + return; + } + const links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + const declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (!declarations || declarations.length <= 1) { + return; + } + const type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters, getEffectiveTypeParameterDeclarations)) { + const name = symbolToString(symbol); + for (const declaration of declarations) { + error(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, targetParameters, getTypeParameterDeclarations) { + const maxTypeArgumentCount = length(targetParameters); + const minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); + for (const declaration of declarations) { + const sourceParameters = getTypeParameterDeclarations(declaration); + const numTypeParameters = sourceParameters.length; + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (let i = 0; i < numTypeParameters; i++) { + const source = sourceParameters[i]; + const target = targetParameters[i]; + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + const constraint = getEffectiveConstraintOfTypeParameter(source); + const sourceConstraint = constraint && getTypeFromTypeNode(constraint); + const targetConstraint = getConstraintOfTypeParameter(target); + if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } + const sourceDefault = source.default && getTypeFromTypeNode(source.default); + const targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function getFirstTransformableStaticClassElement(node) { + const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators && classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ + false, + node + ); + const willTransformPrivateElementsOrClassStaticBlocks = languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators; + const willTransformInitializers = !emitStandardClassFields; + if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) { + for (const member of node.members) { + if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated( + /*useLegacyDecorators*/ + false, + member, + node + )) { + return firstOrUndefined(getDecorators(node)) ?? node; + } else if (willTransformPrivateElementsOrClassStaticBlocks) { + if (isClassStaticBlockDeclaration(member)) { + return member; + } else if (isStatic(member)) { + if (isPrivateIdentifierClassElementDeclaration(member) || willTransformInitializers && isInitializedProperty(member)) { + return member; + } + } + } + } + } + } + function checkClassExpressionExternalHelpers(node) { + if (node.name) return; + const parent = walkUpOuterExpressions(node); + if (!isNamedEvaluationSource(parent)) return; + const willTransformESDecorators = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators; + let location; + if (willTransformESDecorators && classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ + false, + node + )) { + location = firstOrUndefined(getDecorators(node)) ?? node; + } else { + location = getFirstTransformableStaticClassElement(node); + } + if (location) { + checkExternalEmitHelpers(location, 4194304 /* SetFunctionName */); + if ((isPropertyAssignment(parent) || isPropertyDeclaration(parent) || isBindingElement(parent)) && isComputedPropertyName(parent.name)) { + checkExternalEmitHelpers(location, 8388608 /* PropKey */); + } + } + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + checkClassExpressionExternalHelpers(node); + return getTypeOfSymbol(getSymbolOfDeclaration(node)); + } + function checkClassExpressionDeferred(node) { + forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + const firstDecorator = find(node.modifiers, isDecorator); + if (legacyDecorators && firstDecorator && some(node.members, (p) => hasStaticModifier(p) && isPrivateIdentifierClassElementDeclaration(p))) { + grammarErrorOnNode(firstDecorator, Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + } + if (!node.name && !hasSyntacticModifier(node, 2048 /* Default */)) { + grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + checkCollisionsForDeclarationName(node, node.name); + checkTypeParameters(getEffectiveTypeParameterDeclarations(node)); + checkExportsOnMergedDeclarations(node); + const symbol = getSymbolOfDeclaration(node); + const type = getDeclaredTypeOfSymbol(symbol); + const typeWithThis = getTypeWithThisArgument(type); + const staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkFunctionOrConstructorSymbol(symbol); + checkClassForDuplicateDeclarations(node); + const nodeInAmbientContext = !!(node.flags & 33554432 /* Ambient */); + if (!nodeInAmbientContext) { + checkClassForStaticPropertyNameConflicts(node); + } + const baseTypeNode = getEffectiveBaseTypeNode(node); + if (baseTypeNode) { + forEach(baseTypeNode.typeArguments, checkSourceElement); + if (languageVersion < LanguageFeatureMinimumTarget.Classes) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } + const extendsNode = getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } + const baseTypes = getBaseTypes(type); + if (baseTypes.length) { + addLazyDiagnostic(() => { + const baseType = baseTypes[0]; + const baseConstructorType = getBaseConstructorTypeOfClass(type); + const staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + if (some(baseTypeNode.typeArguments)) { + forEach(baseTypeNode.typeArguments, checkSourceElement); + for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode)) { + if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) { + break; + } + } + } + const baseWithThis = getTypeWithThisArgument(baseType, type.thisType); + if (!checkTypeAssignableTo( + typeWithThis, + baseWithThis, + /*errorNode*/ + void 0 + )) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); + } else { + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } + if (baseConstructorType.flags & 8650752 /* TypeVariable */) { + if (!isMixinConstructorType(staticType)) { + error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } else { + const constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (constructSignatures.some((signature) => signature.flags & 4 /* Abstract */) && !hasSyntacticModifier(node, 64 /* Abstract */)) { + error(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract); + } + } + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { + const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (forEach(constructors, (sig) => !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) { + error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType); + }); + } + } + checkMembersForOverrideModifier(node, type, typeWithThis, staticType); + const implementedTypeNodes = getEffectiveImplementsTypeNodes(node); + if (implementedTypeNodes) { + for (const typeRefNode of implementedTypeNodes) { + if (!isEntityNameExpression(typeRefNode.expression) || isOptionalChain(typeRefNode.expression)) { + error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + addLazyDiagnostic(createImplementsDiagnostics(typeRefNode)); + } + } + addLazyDiagnostic(() => { + checkIndexConstraints(type, symbol); + checkIndexConstraints( + staticType, + symbol, + /*isStaticIndex*/ + true + ); + checkTypeForDuplicateIndexSignatures(node); + checkPropertyInitialization(node); + }); + function createImplementsDiagnostics(typeRefNode) { + return () => { + const t = getReducedType(getTypeFromTypeNode(typeRefNode)); + if (!isErrorType(t)) { + if (isValidBaseType(t)) { + const genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : Diagnostics.Class_0_incorrectly_implements_interface_1; + const baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo( + typeWithThis, + baseWithThis, + /*errorNode*/ + void 0 + )) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } + } else { + error(typeRefNode, Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members); + } + } + }; + } + } + function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) { + const baseTypeNode = getEffectiveBaseTypeNode(node); + const baseTypes = baseTypeNode && getBaseTypes(type); + const baseWithThis = (baseTypes == null ? void 0 : baseTypes.length) ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0; + const baseStaticType = getBaseConstructorTypeOfClass(type); + for (const member of node.members) { + if (hasAmbientModifier(member)) { + continue; + } + if (isConstructorDeclaration(member)) { + forEach(member.parameters, (param) => { + if (isParameterPropertyDeclaration(param, member)) { + checkExistingMemberForOverrideModifier( + node, + staticType, + baseStaticType, + baseWithThis, + type, + typeWithThis, + param, + /*memberIsParameterProperty*/ + true + ); + } + }); + } + checkExistingMemberForOverrideModifier( + node, + staticType, + baseStaticType, + baseWithThis, + type, + typeWithThis, + member, + /*memberIsParameterProperty*/ + false + ); + } + } + function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors2 = true) { + const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (!declaredProp) { + return 0 /* Ok */; + } + return checkMemberForOverrideModifier( + node, + staticType, + baseStaticType, + baseWithThis, + type, + typeWithThis, + hasOverrideModifier(member), + hasAbstractModifier(member), + isStatic(member), + memberIsParameterProperty, + declaredProp, + reportErrors2 ? member : void 0 + ); + } + function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, member, errorNode) { + const isJs = isInJSFile(node); + const nodeInAmbientContext = !!(node.flags & 33554432 /* Ambient */); + if (memberHasOverrideModifier && (member == null ? void 0 : member.valueDeclaration) && isClassElement(member.valueDeclaration) && member.valueDeclaration.name && isNonBindableDynamicName(member.valueDeclaration.name)) { + error( + errorNode, + isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic + ); + return 2 /* HasInvalidOverride */; + } + if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) { + const thisType = memberIsStatic ? staticType : typeWithThis; + const baseType = memberIsStatic ? baseStaticType : baseWithThis; + const prop = getPropertyOfType(thisType, member.escapedName); + const baseProp = getPropertyOfType(baseType, member.escapedName); + const baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && memberHasOverrideModifier) { + if (errorNode) { + const suggestion = getSuggestedSymbolForNonexistentClassMember(symbolName(member), baseType); + suggestion ? error( + errorNode, + isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, + baseClassName, + symbolToString(suggestion) + ) : error( + errorNode, + isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, + baseClassName + ); + } + return 2 /* HasInvalidOverride */; + } else if (prop && (baseProp == null ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + const baseHasAbstract = some(baseProp.declarations, hasAbstractModifier); + if (memberHasOverrideModifier) { + return 0 /* Ok */; + } + if (!baseHasAbstract) { + if (errorNode) { + const diag2 = memberIsParameterProperty ? isJs ? Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : isJs ? Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; + error(errorNode, diag2, baseClassName); + } + return 1 /* NeedsOverride */; + } else if (memberHasAbstractModifier && baseHasAbstract) { + if (errorNode) { + error(errorNode, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + } + return 1 /* NeedsOverride */; + } + } + } else if (memberHasOverrideModifier) { + if (errorNode) { + const className = typeToString(type); + error( + errorNode, + isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, + className + ); + } + return 2 /* HasInvalidOverride */; + } + return 0 /* Ok */; + } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + let issuedMemberError = false; + for (const member of node.members) { + if (isStatic(member)) { + continue; + } + const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + const prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + const baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + const rootChain = () => chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, + symbolToString(declaredProp), + typeToString(typeWithThis), + typeToString(baseWithThis) + ); + if (!checkTypeAssignableTo( + getTypeOfSymbol(prop), + getTypeOfSymbol(baseProp), + member.name || member, + /*headMessage*/ + void 0, + rootChain + )) { + issuedMemberError = true; + } + } + } + } + if (!issuedMemberError) { + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } + function checkBaseTypeAccessibility(type, node) { + const signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + const declaration = signatures[0].declaration; + if (declaration && hasEffectiveModifier(declaration, 2 /* Private */)) { + const typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getMemberOverrideModifierStatus(node, member, memberSymbol) { + if (!member.name) { + return 0 /* Ok */; + } + const classSymbol = getSymbolOfDeclaration(node); + const type = getDeclaredTypeOfSymbol(classSymbol); + const typeWithThis = getTypeWithThisArgument(type); + const staticType = getTypeOfSymbol(classSymbol); + const baseTypeNode = getEffectiveBaseTypeNode(node); + const baseTypes = baseTypeNode && getBaseTypes(type); + const baseWithThis = (baseTypes == null ? void 0 : baseTypes.length) ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0; + const baseStaticType = getBaseConstructorTypeOfClass(type); + const memberHasOverrideModifier = member.parent ? hasOverrideModifier(member) : hasSyntacticModifier(member, 16 /* Override */); + return checkMemberForOverrideModifier( + node, + staticType, + baseStaticType, + baseWithThis, + type, + typeWithThis, + memberHasOverrideModifier, + hasAbstractModifier(member), + isStatic(member), + /*memberIsParameterProperty*/ + false, + memberSymbol + ); + } + function getTargetSymbol(s) { + return getCheckFlags(s) & 1 /* Instantiated */ ? s.links.target : s; + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return filter(symbol.declarations, (d) => d.kind === 263 /* ClassDeclaration */ || d.kind === 264 /* InterfaceDeclaration */); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + var _a, _b, _c, _d, _e; + const baseProperties = getPropertiesOfType(baseType); + const notImplementedInfo = /* @__PURE__ */ new Map(); + basePropertyCheck: for (const baseProperty of baseProperties) { + const base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + const baseSymbol = getPropertyOfObjectType(type, base.escapedName); + if (!baseSymbol) { + continue; + } + const derived = getTargetSymbol(baseSymbol); + const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived === base) { + const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + if (baseDeclarationFlags & 64 /* Abstract */ && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, 64 /* Abstract */))) { + for (const otherBaseType of getBaseTypes(type)) { + if (otherBaseType === baseType) continue; + const baseSymbol2 = getPropertyOfObjectType(otherBaseType, base.escapedName); + const derivedElsewhere = baseSymbol2 && getTargetSymbol(baseSymbol2); + if (derivedElsewhere && derivedElsewhere !== base) { + continue basePropertyCheck; + } + } + const baseTypeName = typeToString(baseType); + const typeName = typeToString(type); + const basePropertyName = symbolToString(baseProperty); + const missedProperties = append((_a = notImplementedInfo.get(derivedClassDecl)) == null ? void 0 : _a.missedProperties, basePropertyName); + notImplementedInfo.set(derivedClassDecl, { baseTypeName, typeName, missedProperties }); + } + } else { + const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) { + continue; + } + let errorMessage; + const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */; + const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */; + if (basePropertyFlags && derivedPropertyFlags) { + if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_b = base.declarations) == null ? void 0 : _b.some((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_c = base.declarations) == null ? void 0 : _c.every((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) { + continue; + } + const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; + const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; + error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); + } else if (useDefineForClassFields) { + const uninitialized = (_d = derived.declarations) == null ? void 0 : _d.find((d) => d.kind === 172 /* PropertyDeclaration */ && !d.initializer); + if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_e = derived.declarations) == null ? void 0 : _e.some((d) => !!(d.flags & 33554432 /* Ambient */)))) { + const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)); + const propName = uninitialized.name; + if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { + const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType)); + } + } + } + continue; + } else if (isPrototypeProperty(base)) { + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + continue; + } else { + Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + } else if (base.flags & 98304 /* Accessor */) { + errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } else { + errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + for (const [errorNode, memberInfo] of notImplementedInfo) { + if (length(memberInfo.missedProperties) === 1) { + if (isClassExpression(errorNode)) { + error(errorNode, Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, first(memberInfo.missedProperties), memberInfo.baseTypeName); + } else { + error(errorNode, Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, memberInfo.typeName, first(memberInfo.missedProperties), memberInfo.baseTypeName); + } + } else if (length(memberInfo.missedProperties) > 5) { + const missedProperties = map(memberInfo.missedProperties.slice(0, 4), (prop) => `'${prop}'`).join(", "); + const remainingMissedProperties = length(memberInfo.missedProperties) - 4; + if (isClassExpression(errorNode)) { + error(errorNode, Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and_2_more, memberInfo.baseTypeName, missedProperties, remainingMissedProperties); + } else { + error(errorNode, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more, memberInfo.typeName, memberInfo.baseTypeName, missedProperties, remainingMissedProperties); + } + } else { + const missedProperties = map(memberInfo.missedProperties, (prop) => `'${prop}'`).join(", "); + if (isClassExpression(errorNode)) { + error(errorNode, Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1, memberInfo.baseTypeName, missedProperties); + } else { + error(errorNode, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2, memberInfo.typeName, memberInfo.baseTypeName, missedProperties); + } + } + } + } + function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { + return baseDeclarationFlags & 64 /* Abstract */ && (!isPropertyDeclaration(declaration) || !declaration.initializer) || isInterfaceDeclaration(declaration.parent); + } + function getNonInheritedProperties(type, baseTypes, properties) { + if (!length(baseTypes)) { + return properties; + } + const seen = /* @__PURE__ */ new Map(); + forEach(properties, (p) => { + seen.set(p.escapedName, p); + }); + for (const base of baseTypes) { + const properties2 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (const prop of properties2) { + const existing = seen.get(prop.escapedName); + if (existing && prop.parent === existing.parent) { + seen.delete(prop.escapedName); + } + } + } + return arrayFrom(seen.values()); + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + const baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + const seen = /* @__PURE__ */ new Map(); + forEach(resolveDeclaredMembers(type).declaredProperties, (p) => { + seen.set(p.escapedName, { prop: p, containingType: type }); + }); + let ok = true; + for (const base of baseTypes) { + const properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (const prop of properties) { + const existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop, containingType: base }); + } else { + const isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + const typeName1 = typeToString(existing.containingType); + const typeName2 = typeToString(base); + let errorInfo = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, + symbolToString(prop), + typeName1, + typeName2 + ); + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(typeNode), typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkPropertyInitialization(node) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 33554432 /* Ambient */) { + return; + } + const constructor = findConstructorDeclaration(node); + for (const member of node.members) { + if (getEffectiveModifierFlags(member) & 128 /* Ambient */) { + continue; + } + if (!isStatic(member) && isPropertyWithoutInitializer(member)) { + const propName = member.name; + if (isIdentifier(propName) || isPrivateIdentifier(propName) || isComputedPropertyName(propName)) { + const type = getTypeOfSymbol(getSymbolOfDeclaration(member)); + if (!(type.flags & 3 /* AnyOrUnknown */ || containsUndefinedType(type))) { + if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { + error(member.name, Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, declarationNameToString(propName)); + } + } + } + } + } + } + function isPropertyWithoutInitializer(node) { + return node.kind === 172 /* PropertyDeclaration */ && !hasAbstractModifier(node) && !node.exclamationToken && !node.initializer; + } + function isPropertyInitializedInStaticBlocks(propName, propType, staticBlocks, startPos, endPos) { + for (const staticBlock of staticBlocks) { + if (staticBlock.pos >= startPos && staticBlock.pos <= endPos) { + const reference = factory.createPropertyAccessExpression(factory.createThis(), propName); + setParent(reference.expression, reference); + setParent(reference, staticBlock); + reference.flowNode = staticBlock.returnFlowNode; + const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + if (!containsUndefinedType(flowType)) { + return true; + } + } + } + return false; + } + function isPropertyInitializedInConstructor(propName, propType, constructor) { + const reference = isComputedPropertyName(propName) ? factory.createElementAccessExpression(factory.createThis(), propName.expression) : factory.createPropertyAccessExpression(factory.createThis(), propName); + setParent(reference.expression, reference); + setParent(reference, constructor); + reference.flowNode = constructor.returnFlowNode; + const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); + return !containsUndefinedType(flowType); + } + function checkInterfaceDeclaration(node) { + if (!checkGrammarModifiers(node)) checkGrammarInterfaceDeclaration(node); + if (!allowBlockDeclarations(node.parent)) { + grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, "interface"); + } + checkTypeParameters(node.typeParameters); + addLazyDiagnostic(() => { + checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + const symbol = getSymbolOfDeclaration(node); + checkTypeParameterListsIdentical(symbol); + const firstInterfaceDecl = getDeclarationOfKind(symbol, 264 /* InterfaceDeclaration */); + if (node === firstInterfaceDecl) { + const type = getDeclaredTypeOfSymbol(symbol); + const typeWithThis = getTypeWithThisArgument(type); + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (const baseType of getBaseTypes(type)) { + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type, symbol); + } + } + checkObjectTypeForDuplicateDeclarations(node); + }); + forEach(getInterfaceBaseTypeNodes(node), (heritageElement) => { + if (!isEntityNameExpression(heritageElement.expression) || isOptionalChain(heritageElement.expression)) { + error(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + forEach(node.members, checkSourceElement); + addLazyDiagnostic(() => { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + }); + } + function checkTypeAliasDeclaration(node) { + checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0); + if (!allowBlockDeclarations(node.parent)) { + grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, "type"); + } + checkExportsOnMergedDeclarations(node); + checkTypeParameters(node.typeParameters); + if (node.type.kind === 141 /* IntrinsicKeyword */) { + const typeParameterCount = length(node.typeParameters); + const valid = typeParameterCount === 0 ? node.name.escapedText === "BuiltinIteratorReturn" : typeParameterCount === 1 && intrinsicTypeKinds.has(node.name.escapedText); + if (!valid) { + error(node.type, Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types); + } + } else { + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + } + function computeEnumMemberValues(node) { + const nodeLinks2 = getNodeLinks(node); + if (!(nodeLinks2.flags & 1024 /* EnumValuesComputed */)) { + nodeLinks2.flags |= 1024 /* EnumValuesComputed */; + let autoValue = 0; + let previous; + for (const member of node.members) { + const result = computeEnumMemberValue(member, autoValue, previous); + getNodeLinks(member).enumMemberValue = result; + autoValue = typeof result.value === "number" ? result.value + 1 : void 0; + previous = member; + } + } + } + function computeEnumMemberValue(member, autoValue, previous) { + if (isComputedNonLiteralName(member.name)) { + error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } else { + const text = getTextOfPropertyName(member.name); + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { + error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + } + if (member.initializer) { + return computeConstantEnumMemberValue(member); + } + if (member.parent.flags & 33554432 /* Ambient */ && !isEnumConst(member.parent)) { + return evaluatorResult( + /*value*/ + void 0 + ); + } + if (autoValue === void 0) { + error(member.name, Diagnostics.Enum_member_must_have_initializer); + return evaluatorResult( + /*value*/ + void 0 + ); + } + if (getIsolatedModules(compilerOptions) && (previous == null ? void 0 : previous.initializer)) { + const prevValue = getEnumMemberValue(previous); + if (!(typeof prevValue.value === "number" && !prevValue.resolvedOtherFiles)) { + error( + member.name, + Diagnostics.Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is_enabled + ); + } + } + return evaluatorResult(autoValue); + } + function computeConstantEnumMemberValue(member) { + const isConstEnum = isEnumConst(member.parent); + const initializer = member.initializer; + const result = evaluate(initializer, member); + if (result.value !== void 0) { + if (isConstEnum && typeof result.value === "number" && !isFinite(result.value)) { + error( + initializer, + isNaN(result.value) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value + ); + } else if (getIsolatedModules(compilerOptions) && typeof result.value === "string" && !result.isSyntacticallyString) { + error( + initializer, + Diagnostics._0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is_enabled, + `${idText(member.parent.name)}.${getTextOfPropertyName(member.name)}` + ); + } + } else if (isConstEnum) { + error(initializer, Diagnostics.const_enum_member_initializers_must_be_constant_expressions); + } else if (member.parent.flags & 33554432 /* Ambient */) { + error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } else { + checkTypeAssignableTo(checkExpression(initializer), numberType, initializer, Diagnostics.Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values); + } + return result; + } + function evaluateEntityNameExpression(expr, location) { + const symbol = resolveEntityName( + expr, + 111551 /* Value */, + /*ignoreErrors*/ + true + ); + if (!symbol) return evaluatorResult( + /*value*/ + void 0 + ); + if (expr.kind === 80 /* Identifier */) { + const identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText) && symbol === getGlobalSymbol( + identifier.escapedText, + 111551 /* Value */, + /*diagnostic*/ + void 0 + )) { + return evaluatorResult( + +identifier.escapedText, + /*isSyntacticallyString*/ + false + ); + } + } + if (symbol.flags & 8 /* EnumMember */) { + return location ? evaluateEnumMember(expr, symbol, location) : getEnumMemberValue(symbol.valueDeclaration); + } + if (isConstantVariable(symbol)) { + const declaration = symbol.valueDeclaration; + if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) { + const result = evaluate(declaration.initializer, declaration); + if (location && getSourceFileOfNode(location) !== getSourceFileOfNode(declaration)) { + return evaluatorResult( + result.value, + /*isSyntacticallyString*/ + false, + /*resolvedOtherFiles*/ + true, + /*hasExternalReferences*/ + true + ); + } + return evaluatorResult( + result.value, + result.isSyntacticallyString, + result.resolvedOtherFiles, + /*hasExternalReferences*/ + true + ); + } + } + return evaluatorResult( + /*value*/ + void 0 + ); + } + function evaluateElementAccessExpression(expr, location) { + const root = expr.expression; + if (isEntityNameExpression(root) && isStringLiteralLike(expr.argumentExpression)) { + const rootSymbol = resolveEntityName( + root, + 111551 /* Value */, + /*ignoreErrors*/ + true + ); + if (rootSymbol && rootSymbol.flags & 384 /* Enum */) { + const name = escapeLeadingUnderscores(expr.argumentExpression.text); + const member = rootSymbol.exports.get(name); + if (member) { + Debug.assert(getSourceFileOfNode(member.valueDeclaration) === getSourceFileOfNode(rootSymbol.valueDeclaration)); + return location ? evaluateEnumMember(expr, member, location) : getEnumMemberValue(member.valueDeclaration); + } + } + } + return evaluatorResult( + /*value*/ + void 0 + ); + } + function evaluateEnumMember(expr, symbol, location) { + const declaration = symbol.valueDeclaration; + if (!declaration || declaration === location) { + error(expr, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(symbol)); + return evaluatorResult( + /*value*/ + void 0 + ); + } + if (!isBlockScopedNameDeclaredBeforeUse(declaration, location)) { + error(expr, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return evaluatorResult( + /*value*/ + 0 + ); + } + const value = getEnumMemberValue(declaration); + if (location.parent !== declaration.parent) { + return evaluatorResult( + value.value, + value.isSyntacticallyString, + value.resolvedOtherFiles, + /*hasExternalReferences*/ + true + ); + } + return value; + } + function checkEnumDeclaration(node) { + addLazyDiagnostic(() => checkEnumDeclarationWorker(node)); + } + function checkEnumDeclarationWorker(node) { + checkGrammarModifiers(node); + checkCollisionsForDeclarationName(node, node.name); + checkExportsOnMergedDeclarations(node); + node.members.forEach(checkEnumMember); + if (compilerOptions.erasableSyntaxOnly && !(node.flags & 33554432 /* Ambient */)) { + error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); + } + computeEnumMemberValues(node); + const enumSymbol = getSymbolOfDeclaration(node); + const firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { + const enumIsConst = isEnumConst(node); + forEach(enumSymbol.declarations, (decl) => { + if (isEnumDeclaration(decl) && isEnumConst(decl) !== enumIsConst) { + error(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + let seenEnumMissingInitialInitializer = false; + forEach(enumSymbol.declarations, (declaration) => { + if (declaration.kind !== 266 /* EnumDeclaration */) { + return false; + } + const enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + const firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer) { + error(firstEnumMember.name, Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } else { + seenEnumMissingInitialInitializer = true; + } + } + }); + } + } + function checkEnumMember(node) { + if (isPrivateIdentifier(node.name)) { + error(node, Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier); + } + if (node.initializer) { + checkExpression(node.initializer); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + const declarations = symbol.declarations; + if (declarations) { + for (const declaration of declarations) { + if ((declaration.kind === 263 /* ClassDeclaration */ || declaration.kind === 262 /* FunctionDeclaration */ && nodeIsPresent(declaration.body)) && !(declaration.flags & 33554432 /* Ambient */)) { + return declaration; + } + } + } + return void 0; + } + function inSameLexicalScope(node1, node2) { + const container1 = getEnclosingBlockScopeContainer(node1); + const container2 = getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } else if (isGlobalSourceFile(container2)) { + return false; + } else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (node.body) { + checkSourceElement(node.body); + if (!isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + addLazyDiagnostic(checkModuleDeclarationDiagnostics); + function checkModuleDeclarationDiagnostics() { + var _a, _b; + const isGlobalAugmentation = isGlobalScopeAugmentation(node); + const inAmbientContext = node.flags & 33554432 /* Ambient */; + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + const isAmbientExternalModule = isAmbientModule(node); + const contextErrorMessage = isAmbientExternalModule ? Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : Diagnostics.A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + return; + } + if (!checkGrammarModifiers(node)) { + if (!inAmbientContext && node.name.kind === 11 /* StringLiteral */) { + grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (isIdentifier(node.name)) { + checkCollisionsForDeclarationName(node, node.name); + if (!(node.flags & (32 /* Namespace */ | 2048 /* GlobalAugmentation */))) { + const sourceFile = getSourceFileOfNode(node); + const pos = getNonModifierTokenPosOfNode(node); + const span = getSpanOfTokenAtPosition(sourceFile, pos); + suggestionDiagnostics.add( + createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_keyword_instead) + ); + } + } + checkExportsOnMergedDeclarations(node); + const symbol = getSymbolOfDeclaration(node); + if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext && isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions))) { + if (compilerOptions.erasableSyntaxOnly) { + error(node.name, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); + } + if (getIsolatedModules(compilerOptions) && !getSourceFileOfNode(node).externalModuleIndicator) { + error(node.name, Diagnostics.Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to_be_a_global_script_set_moduleDetection_to_force_or_add_an_empty_export_statement, isolatedModulesLikeFlagName); + } + if (((_a = symbol.declarations) == null ? void 0 : _a.length) > 1) { + const firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (getSourceFileOfNode(node) !== getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + const mergedClass = getDeclarationOfKind(symbol, 263 /* ClassDeclaration */); + if (mergedClass && inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 2048 /* LexicalModuleMergesWithClass */; + } + } + if (compilerOptions.verbatimModuleSyntax && node.parent.kind === 307 /* SourceFile */ && host.getEmitModuleFormatOfFile(node.parent) === 1 /* CommonJS */) { + const exportModifier = (_b = node.modifiers) == null ? void 0 : _b.find((m) => m.kind === 95 /* ExportKeyword */); + if (exportModifier) { + error(exportModifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + } + } + } + if (isAmbientExternalModule) { + if (isExternalModuleAugmentation(node)) { + const checkBody = isGlobalAugmentation || getSymbolOfDeclaration(node).flags & 33554432 /* Transient */; + if (checkBody && node.body) { + for (const statement of node.body.statements) { + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } else if (isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } else { + if (isGlobalAugmentation) { + error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } else { + error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 243 /* VariableStatement */: + for (const decl of node.declarationList.declarations) { + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 277 /* ExportAssignment */: + case 278 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 271 /* ImportEqualsDeclaration */: + if (isInternalModuleImportEqualsDeclaration(node)) break; + // falls through + case 272 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 208 /* BindingElement */: + case 260 /* VariableDeclaration */: + const name = node.name; + if (isBindingPattern(name)) { + for (const el of name.elements) { + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // falls through + case 263 /* ClassDeclaration */: + case 266 /* EnumDeclaration */: + case 262 /* FunctionDeclaration */: + case 264 /* InterfaceDeclaration */: + case 267 /* ModuleDeclaration */: + case 265 /* TypeAliasDeclaration */: + if (isGlobalAugmentation) { + return; + } + break; + } + } + function getFirstNonModuleExportsIdentifier(node) { + switch (node.kind) { + case 80 /* Identifier */: + return node; + case 166 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 80 /* Identifier */); + return node; + case 211 /* PropertyAccessExpression */: + do { + if (isModuleExportsAccessExpression(node.expression) && !isPrivateIdentifier(node.name)) { + return node.name; + } + node = node.expression; + } while (node.kind !== 80 /* Identifier */); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + const moduleName = getExternalModuleName(node); + if (!moduleName || nodeIsMissing(moduleName)) { + return false; + } + if (!isStringLiteral(moduleName)) { + error(moduleName, Diagnostics.String_literal_expected); + return false; + } + const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent); + if (node.parent.kind !== 307 /* SourceFile */ && !inAmbientExternalModule) { + error( + moduleName, + node.kind === 278 /* ExportDeclaration */ ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module + ); + return false; + } + if (inAmbientExternalModule && isExternalModuleNameRelative(moduleName.text)) { + if (!isTopLevelInExternalModuleAugmentation(node)) { + error(node, Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + if (!isImportEqualsDeclaration(node) && node.attributes) { + const diagnostic = node.attributes.token === 118 /* WithKeyword */ ? Diagnostics.Import_attribute_values_must_be_string_literal_expressions : Diagnostics.Import_assertion_values_must_be_string_literal_expressions; + let hasError = false; + for (const attr of node.attributes.elements) { + if (!isStringLiteral(attr.value)) { + hasError = true; + error(attr.value, diagnostic); + } + } + return !hasError; + } + return true; + } + function checkModuleExportName(name, allowStringLiteral = true) { + if (name === void 0 || name.kind !== 11 /* StringLiteral */) { + return; + } + if (!allowStringLiteral) { + grammarErrorOnNode(name, Diagnostics.Identifier_expected); + } else if (moduleKind === 5 /* ES2015 */ || moduleKind === 6 /* ES2020 */) { + grammarErrorOnNode(name, Diagnostics.String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es2020); + } + } + function checkAliasSymbol(node) { + var _a, _b, _c, _d; + let symbol = getSymbolOfDeclaration(node); + const target = resolveAlias(symbol); + if (target !== unknownSymbol) { + symbol = getMergedSymbol(symbol.exportSymbol || symbol); + if (isInJSFile(node) && !(target.flags & 111551 /* Value */) && !isTypeOnlyImportOrExportDeclaration(node)) { + const errorNode = isImportOrExportSpecifier(node) ? node.propertyName || node.name : isNamedDeclaration(node) ? node.name : node; + Debug.assert(node.kind !== 280 /* NamespaceExport */); + if (node.kind === 281 /* ExportSpecifier */) { + const diag2 = error(errorNode, Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); + const alreadyExportedSymbol = (_b = (_a = getSourceFileOfNode(node).symbol) == null ? void 0 : _a.exports) == null ? void 0 : _b.get(moduleExportNameTextEscaped(node.propertyName || node.name)); + if (alreadyExportedSymbol === target) { + const exportingDeclaration = (_c = alreadyExportedSymbol.declarations) == null ? void 0 : _c.find(isJSDocNode); + if (exportingDeclaration) { + addRelatedInfo( + diag2, + createDiagnosticForNode( + exportingDeclaration, + Diagnostics._0_is_automatically_exported_here, + unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName) + ) + ); + } + } + } else { + Debug.assert(node.kind !== 260 /* VariableDeclaration */); + const importDeclaration = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration)); + const moduleSpecifier = (importDeclaration && ((_d = tryGetModuleSpecifierFromDeclaration(importDeclaration)) == null ? void 0 : _d.text)) ?? "..."; + const importedIdentifier = unescapeLeadingUnderscores(isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); + error( + errorNode, + Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, + importedIdentifier, + `import("${moduleSpecifier}").${importedIdentifier}` + ); + } + return; + } + const targetFlags = getSymbolFlags(target); + const excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) | (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + if (targetFlags & excludedMeanings) { + const message = node.kind === 281 /* ExportSpecifier */ ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } else if (node.kind !== 281 /* ExportSpecifier */) { + const appearsValueyToTranspiler = compilerOptions.isolatedModules && !findAncestor(node, isTypeOnlyImportOrExportDeclaration); + if (appearsValueyToTranspiler && symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */)) { + error( + node, + Diagnostics.Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled, + symbolToString(symbol), + isolatedModulesLikeFlagName + ); + } + } + if (getIsolatedModules(compilerOptions) && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 33554432 /* Ambient */)) { + const typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); + const isType = !(targetFlags & 111551 /* Value */); + if (isType || typeOnlyAlias) { + switch (node.kind) { + case 273 /* ImportClause */: + case 276 /* ImportSpecifier */: + case 271 /* ImportEqualsDeclaration */: { + if (compilerOptions.verbatimModuleSyntax) { + Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name"); + const message = compilerOptions.verbatimModuleSyntax && isInternalModuleImportEqualsDeclaration(node) ? Diagnostics.An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled : isType ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled; + const name = moduleExportNameTextUnescaped(node.kind === 276 /* ImportSpecifier */ ? node.propertyName || node.name : node.name); + addTypeOnlyDeclarationRelatedInfo( + error(node, message, name), + isType ? void 0 : typeOnlyAlias, + name + ); + } + if (isType && node.kind === 271 /* ImportEqualsDeclaration */ && hasEffectiveModifier(node, 32 /* Export */)) { + error(node, Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled, isolatedModulesLikeFlagName); + } + break; + } + case 281 /* ExportSpecifier */: { + if (compilerOptions.verbatimModuleSyntax || getSourceFileOfNode(typeOnlyAlias) !== getSourceFileOfNode(node)) { + const name = moduleExportNameTextUnescaped(node.propertyName || node.name); + const diagnostic = isType ? error(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) : error(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName); + addTypeOnlyDeclarationRelatedInfo(diagnostic, isType ? void 0 : typeOnlyAlias, name); + break; + } + } + } + } + if (compilerOptions.verbatimModuleSyntax && node.kind !== 271 /* ImportEqualsDeclaration */ && !isInJSFile(node) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) { + error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + } else if (moduleKind === 200 /* Preserve */ && node.kind !== 271 /* ImportEqualsDeclaration */ && node.kind !== 260 /* VariableDeclaration */ && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) { + error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve); + } + if (compilerOptions.verbatimModuleSyntax && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 33554432 /* Ambient */) && targetFlags & 128 /* ConstEnum */) { + const constEnumDeclaration = target.valueDeclaration; + const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath); + if (constEnumDeclaration.flags & 33554432 /* Ambient */ && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) { + error(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName); + } + } + } + if (isImportSpecifier(node)) { + const targetSymbol = resolveAliasWithDeprecationCheck(symbol, node); + if (isDeprecatedSymbol(targetSymbol) && targetSymbol.declarations) { + addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName); + } + } + } + } + function resolveAliasWithDeprecationCheck(symbol, location) { + if (!(symbol.flags & 2097152 /* Alias */) || isDeprecatedSymbol(symbol) || !getDeclarationOfAliasSymbol(symbol)) { + return symbol; + } + const targetSymbol = resolveAlias(symbol); + if (targetSymbol === unknownSymbol) return targetSymbol; + while (symbol.flags & 2097152 /* Alias */) { + const target = getImmediateAliasedSymbol(symbol); + if (target) { + if (target === targetSymbol) break; + if (target.declarations && length(target.declarations)) { + if (isDeprecatedSymbol(target)) { + addDeprecatedSuggestion(location, target.declarations, target.escapedName); + break; + } else { + if (symbol === targetSymbol) break; + symbol = target; + } + } + } else { + break; + } + } + return targetSymbol; + } + function checkImportBinding(node) { + checkCollisionsForDeclarationName(node, node.name); + checkAliasSymbol(node); + if (node.kind === 276 /* ImportSpecifier */) { + checkModuleExportName(node.propertyName); + if (moduleExportNameIsDefault(node.propertyName || node.name) && getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */) { + checkExternalEmitHelpers(node, 131072 /* ImportDefault */); + } + } + } + function checkImportAttributes(declaration) { + var _a; + const node = declaration.attributes; + if (node) { + const importAttributesType = getGlobalImportAttributesType( + /*reportErrors*/ + true + ); + if (importAttributesType !== emptyObjectType) { + checkTypeAssignableTo(getTypeFromImportAttributes(node), getNullableType(importAttributesType, 32768 /* Undefined */), node); + } + const validForTypeAttributes = isExclusivelyTypeOnlyImportOrExport(declaration); + const override = getResolutionModeOverride(node, validForTypeAttributes ? grammarErrorOnNode : void 0); + const isImportAttributes2 = declaration.attributes.token === 118 /* WithKeyword */; + if (validForTypeAttributes && override) { + return; + } + if (!moduleSupportsImportAttributes(moduleKind)) { + return grammarErrorOnNode( + node, + isImportAttributes2 ? Diagnostics.Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_preserve : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_preserve + ); + } + if (moduleKind === 199 /* NodeNext */ && !isImportAttributes2) { + return grammarErrorOnFirstToken(node, Diagnostics.Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert); + } + if (declaration.moduleSpecifier && getEmitSyntaxForModuleSpecifierExpression(declaration.moduleSpecifier) === 1 /* CommonJS */) { + return grammarErrorOnNode( + node, + isImportAttributes2 ? Diagnostics.Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls + ); + } + const isTypeOnly = isJSDocImportTag(declaration) || (isImportDeclaration(declaration) ? (_a = declaration.importClause) == null ? void 0 : _a.isTypeOnly : declaration.isTypeOnly); + if (isTypeOnly) { + return grammarErrorOnNode(node, isImportAttributes2 ? Diagnostics.Import_attributes_cannot_be_used_with_type_only_imports_or_exports : Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports); + } + if (override) { + return grammarErrorOnNode(node, Diagnostics.resolution_mode_can_only_be_set_for_type_only_imports); + } + } + } + function checkImportAttribute(node) { + return getRegularTypeOfLiteralType(checkExpressionCached(node.value)); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { + return; + } + if (!checkGrammarModifiers(node) && node.modifiers) { + grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + let resolvedModule; + const importClause = node.importClause; + if (importClause && !checkGrammarImportClause(importClause)) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 274 /* NamespaceImport */) { + checkImportBinding(importClause.namedBindings); + if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && getESModuleInterop(compilerOptions)) { + checkExternalEmitHelpers(node, 65536 /* ImportStar */); + } + } else { + resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + if (resolvedModule) { + forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + if (!importClause.isTypeOnly && 101 /* Node18 */ <= moduleKind && moduleKind <= 199 /* NodeNext */ && isOnlyImportableAsDefault(node.moduleSpecifier, resolvedModule) && !hasTypeJsonImportAttribute(node)) { + error(node.moduleSpecifier, Diagnostics.Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_module_is_set_to_0, ModuleKind[moduleKind]); + } + } else if (noUncheckedSideEffectImports && !importClause) { + void resolveExternalModuleName(node, node.moduleSpecifier); + } + } + checkImportAttributes(node); + } + function hasTypeJsonImportAttribute(node) { + return !!node.attributes && node.attributes.elements.some((attr) => { + var _a; + return getTextOfIdentifierOrLiteral(attr.name) === "type" && ((_a = tryCast(attr.value, isStringLiteralLike)) == null ? void 0 : _a.text) === "json"; + }); + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { + return; + } + checkGrammarModifiers(node); + if (compilerOptions.erasableSyntaxOnly && !(node.flags & 33554432 /* Ambient */)) { + error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); + } + if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + markLinkedReferences(node, 6 /* ExportImportEquals */); + if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) { + const target = resolveAlias(getSymbolOfDeclaration(node)); + if (target !== unknownSymbol) { + const targetFlags = getSymbolFlags(target); + if (targetFlags & 111551 /* Value */) { + const moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName)); + } + } + if (targetFlags & 788968 /* Type */) { + checkTypeNameIsReserved(node.name, Diagnostics.Import_name_cannot_be_0); + } + } + if (node.isTypeOnly) { + grammarErrorOnNode(node, Diagnostics.An_import_alias_cannot_use_import_type); + } + } else { + if (5 /* ES2015 */ <= moduleKind && moduleKind <= 99 /* ESNext */ && !node.isTypeOnly && !(node.flags & 33554432 /* Ambient */)) { + grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { + return; + } + if (!checkGrammarModifiers(node) && hasSyntacticModifiers(node)) { + grammarErrorOnFirstToken(node, Diagnostics.An_export_declaration_cannot_have_modifiers); + } + checkGrammarExportDeclaration(node); + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause && !isNamespaceExport(node.exportClause)) { + forEach(node.exportClause.elements, checkExportSpecifier); + const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent); + const inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 268 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 33554432 /* Ambient */; + if (node.parent.kind !== 307 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } else { + const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } else if (node.exportClause) { + checkAliasSymbol(node.exportClause); + checkModuleExportName(node.exportClause.name); + } + if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */) { + if (node.exportClause) { + if (getESModuleInterop(compilerOptions)) { + checkExternalEmitHelpers(node, 65536 /* ImportStar */); + } + } else { + checkExternalEmitHelpers(node, 32768 /* ExportStar */); + } + } + } + } + checkImportAttributes(node); + } + function checkGrammarExportDeclaration(node) { + var _a; + if (node.isTypeOnly && ((_a = node.exportClause) == null ? void 0 : _a.kind) === 279 /* NamedExports */) { + return checkGrammarNamedImportsOrExports(node.exportClause); + } + return false; + } + function checkGrammarModuleElementContext(node, errorMessage) { + const isInAppropriateContext = node.parent.kind === 307 /* SourceFile */ || node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 267 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + const hasModuleSpecifier = node.parent.parent.moduleSpecifier !== void 0; + checkModuleExportName(node.propertyName, hasModuleSpecifier); + checkModuleExportName(node.name); + if (getEmitDeclarations(compilerOptions)) { + collectLinkedAliases( + node.propertyName || node.name, + /*setVisibility*/ + true + ); + } + if (!hasModuleSpecifier) { + const exportedName = node.propertyName || node.name; + if (exportedName.kind === 11 /* StringLiteral */) { + return; + } + const symbol = resolveName( + exportedName, + exportedName.escapedText, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); + } else { + markLinkedReferences(node, 7 /* ExportSpecifier */); + } + } else { + if (getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && moduleExportNameIsDefault(node.propertyName || node.name)) { + checkExternalEmitHelpers(node, 131072 /* ImportDefault */); + } + } + } + function checkExportAssignment(node) { + const illegalContextMessage = node.isExportEquals ? Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration : Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { + return; + } + if (compilerOptions.erasableSyntaxOnly && node.isExportEquals && !(node.flags & 33554432 /* Ambient */)) { + error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); + } + const container = node.parent.kind === 307 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 267 /* ModuleDeclaration */ && !isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } else { + error(node, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + if (!checkGrammarModifiers(node) && hasEffectiveModifiers(node)) { + grammarErrorOnFirstToken(node, Diagnostics.An_export_assignment_cannot_have_modifiers); + } + const typeAnnotationNode = getEffectiveTypeAnnotationNode(node); + if (typeAnnotationNode) { + checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression); + } + const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */; + if (node.expression.kind === 80 /* Identifier */) { + const id = node.expression; + const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName( + id, + -1 /* All */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + node + )); + if (sym) { + markLinkedReferences(node, 3 /* ExportAssignment */); + const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(sym, 111551 /* Value */); + if (getSymbolFlags(sym) & 111551 /* Value */) { + checkExpressionCached(id); + if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && typeOnlyDeclaration) { + error( + id, + node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration : Diagnostics.An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration, + idText(id) + ); + } + } else if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax) { + error( + id, + node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type : Diagnostics.An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type, + idText(id) + ); + } + if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && getIsolatedModules(compilerOptions) && !(sym.flags & 111551 /* Value */)) { + const nonLocalMeanings = getSymbolFlags( + sym, + /*excludeTypeOnlyMeanings*/ + false, + /*excludeLocalMeanings*/ + true + ); + if (sym.flags & 2097152 /* Alias */ && nonLocalMeanings & 788968 /* Type */ && !(nonLocalMeanings & 111551 /* Value */) && (!typeOnlyDeclaration || getSourceFileOfNode(typeOnlyDeclaration) !== getSourceFileOfNode(node))) { + error( + id, + node.isExportEquals ? Diagnostics._0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported : Diagnostics._0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default, + idText(id), + isolatedModulesLikeFlagName + ); + } else if (typeOnlyDeclaration && getSourceFileOfNode(typeOnlyDeclaration) !== getSourceFileOfNode(node)) { + addTypeOnlyDeclarationRelatedInfo( + error( + id, + node.isExportEquals ? Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default, + idText(id), + isolatedModulesLikeFlagName + ), + typeOnlyDeclaration, + idText(id) + ); + } + } + } else { + checkExpressionCached(id); + } + if (getEmitDeclarations(compilerOptions)) { + collectLinkedAliases( + id, + /*setVisibility*/ + true + ); + } + } else { + checkExpressionCached(node.expression); + } + if (isIllegalExportDefaultInCJS) { + error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + } + checkExternalModuleExports(container); + if (node.flags & 33554432 /* Ambient */ && !isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } + if (node.isExportEquals) { + if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && (node.flags & 33554432 /* Ambient */ && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === 99 /* ESNext */ || !(node.flags & 33554432 /* Ambient */) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== 1 /* CommonJS */)) { + grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); + } else if (moduleKind === 4 /* System */ && !(node.flags & 33554432 /* Ambient */)) { + grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return forEachEntry(moduleSymbol.exports, (_, id) => id !== "export="); + } + function checkExternalModuleExports(node) { + const moduleSymbol = getSymbolOfDeclaration(node); + const links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + const exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) { + error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + const exports2 = getExportsOfModule(moduleSymbol); + if (exports2) { + exports2.forEach(({ declarations, flags }, id) => { + if (id === "__export") { + return; + } + if (flags & (1920 /* Namespace */ | 384 /* Enum */)) { + return; + } + const exportedDeclarationsCount = countWhere(declarations, and(isNotOverloadAndNotAccessor, not(isInterfaceDeclaration))); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + return; + } + if (exportedDeclarationsCount > 1) { + if (!isDuplicatedCommonJSExport(declarations)) { + for (const declaration of declarations) { + if (isNotOverload(declaration)) { + diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, unescapeLeadingUnderscores(id))); + } + } + } + } + }); + } + links.exportsChecked = true; + } + } + function isDuplicatedCommonJSExport(declarations) { + return declarations && declarations.length > 1 && declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && (isExportsIdentifier(d.expression) || isModuleExportsAccessExpression(d.expression))); + } + function checkSourceElement(node) { + if (node) { + const saveCurrentNode = currentNode; + currentNode = node; + instantiationCount = 0; + checkSourceElementWorker(node); + currentNode = saveCurrentNode; + } + } + function checkSourceElementWorker(node) { + if (getNodeCheckFlags(node) & 8388608 /* PartiallyTypeChecked */) { + return; + } + if (canHaveJSDoc(node)) { + forEach(node.jsDoc, ({ comment, tags }) => { + checkJSDocCommentWorker(comment); + forEach(tags, (tag) => { + checkJSDocCommentWorker(tag.comment); + if (isInJSFile(node)) { + checkSourceElement(tag); + } + }); + }); + } + const kind = node.kind; + if (cancellationToken) { + switch (kind) { + case 267 /* ModuleDeclaration */: + case 263 /* ClassDeclaration */: + case 264 /* InterfaceDeclaration */: + case 262 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + if (kind >= 243 /* FirstStatement */ && kind <= 259 /* LastStatement */ && canHaveFlowNode(node) && node.flowNode && !isReachableFlowNode(node.flowNode)) { + errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, Diagnostics.Unreachable_code_detected); + } + switch (kind) { + case 168 /* TypeParameter */: + return checkTypeParameter(node); + case 169 /* Parameter */: + return checkParameter(node); + case 172 /* PropertyDeclaration */: + return checkPropertyDeclaration(node); + case 171 /* PropertySignature */: + return checkPropertySignature(node); + case 185 /* ConstructorType */: + case 184 /* FunctionType */: + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 181 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + return checkMethodDeclaration(node); + case 175 /* ClassStaticBlockDeclaration */: + return checkClassStaticBlockDeclaration(node); + case 176 /* Constructor */: + return checkConstructorDeclaration(node); + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 183 /* TypeReference */: + return checkTypeReferenceNode(node); + case 182 /* TypePredicate */: + return checkTypePredicate(node); + case 186 /* TypeQuery */: + return checkTypeQuery(node); + case 187 /* TypeLiteral */: + return checkTypeLiteral(node); + case 188 /* ArrayType */: + return checkArrayType(node); + case 189 /* TupleType */: + return checkTupleType(node); + case 192 /* UnionType */: + case 193 /* IntersectionType */: + return checkUnionOrIntersectionType(node); + case 196 /* ParenthesizedType */: + case 190 /* OptionalType */: + case 191 /* RestType */: + return checkSourceElement(node.type); + case 197 /* ThisType */: + return checkThisType(node); + case 198 /* TypeOperator */: + return checkTypeOperator(node); + case 194 /* ConditionalType */: + return checkConditionalType(node); + case 195 /* InferType */: + return checkInferType(node); + case 203 /* TemplateLiteralType */: + return checkTemplateLiteralType(node); + case 205 /* ImportType */: + return checkImportType(node); + case 202 /* NamedTupleMember */: + return checkNamedTupleMember(node); + case 328 /* JSDocAugmentsTag */: + return checkJSDocAugmentsTag(node); + case 329 /* JSDocImplementsTag */: + return checkJSDocImplementsTag(node); + case 346 /* JSDocTypedefTag */: + case 338 /* JSDocCallbackTag */: + case 340 /* JSDocEnumTag */: + return checkJSDocTypeAliasTag(node); + case 345 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 344 /* JSDocTypeTag */: + return checkJSDocTypeTag(node); + case 324 /* JSDocLink */: + case 325 /* JSDocLinkCode */: + case 326 /* JSDocLinkPlain */: + return checkJSDocLinkLikeTag(node); + case 341 /* JSDocParameterTag */: + return checkJSDocParameterTag(node); + case 348 /* JSDocPropertyTag */: + return checkJSDocPropertyTag(node); + case 317 /* JSDocFunctionType */: + checkJSDocFunctionType(node); + // falls through + case 315 /* JSDocNonNullableType */: + case 314 /* JSDocNullableType */: + case 312 /* JSDocAllType */: + case 313 /* JSDocUnknownType */: + case 322 /* JSDocTypeLiteral */: + checkJSDocTypeIsInJsFile(node); + forEachChild(node, checkSourceElement); + return; + case 318 /* JSDocVariadicType */: + checkJSDocVariadicType(node); + return; + case 309 /* JSDocTypeExpression */: + return checkSourceElement(node.type); + case 333 /* JSDocPublicTag */: + case 335 /* JSDocProtectedTag */: + case 334 /* JSDocPrivateTag */: + return checkJSDocAccessibilityModifiers(node); + case 350 /* JSDocSatisfiesTag */: + return checkJSDocSatisfiesTag(node); + case 343 /* JSDocThisTag */: + return checkJSDocThisTag(node); + case 351 /* JSDocImportTag */: + return checkJSDocImportTag(node); + case 199 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 200 /* MappedType */: + return checkMappedType(node); + case 262 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 241 /* Block */: + case 268 /* ModuleBlock */: + return checkBlock(node); + case 243 /* VariableStatement */: + return checkVariableStatement(node); + case 244 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 245 /* IfStatement */: + return checkIfStatement(node); + case 246 /* DoStatement */: + return checkDoStatement(node); + case 247 /* WhileStatement */: + return checkWhileStatement(node); + case 248 /* ForStatement */: + return checkForStatement(node); + case 249 /* ForInStatement */: + return checkForInStatement(node); + case 250 /* ForOfStatement */: + return checkForOfStatement(node); + case 251 /* ContinueStatement */: + case 252 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 253 /* ReturnStatement */: + return checkReturnStatement(node); + case 254 /* WithStatement */: + return checkWithStatement(node); + case 255 /* SwitchStatement */: + return checkSwitchStatement(node); + case 256 /* LabeledStatement */: + return checkLabeledStatement(node); + case 257 /* ThrowStatement */: + return checkThrowStatement(node); + case 258 /* TryStatement */: + return checkTryStatement(node); + case 260 /* VariableDeclaration */: + return checkVariableDeclaration(node); + case 208 /* BindingElement */: + return checkBindingElement(node); + case 263 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 264 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 265 /* TypeAliasDeclaration */: + return checkTypeAliasDeclaration(node); + case 266 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 267 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 272 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 271 /* ImportEqualsDeclaration */: + return checkImportEqualsDeclaration(node); + case 278 /* ExportDeclaration */: + return checkExportDeclaration(node); + case 277 /* ExportAssignment */: + return checkExportAssignment(node); + case 242 /* EmptyStatement */: + case 259 /* DebuggerStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 282 /* MissingDeclaration */: + return checkMissingDeclaration(node); + } + } + function checkJSDocCommentWorker(node) { + if (isArray(node)) { + forEach(node, (tag) => { + if (isJSDocLinkLike(tag)) { + checkSourceElement(tag); + } + }); + } + } + function checkJSDocTypeIsInJsFile(node) { + if (!isInJSFile(node)) { + if (isJSDocNonNullableType(node) || isJSDocNullableType(node)) { + const token = tokenToString(isJSDocNonNullableType(node) ? 54 /* ExclamationToken */ : 58 /* QuestionToken */); + const diagnostic = node.postfix ? Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1 : Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1; + const typeNode = node.type; + const type = getTypeFromTypeNode(typeNode); + grammarErrorOnNode( + node, + diagnostic, + token, + typeToString( + isJSDocNullableType(node) && !(type === neverType || type === voidType) ? getUnionType(append([type, undefinedType], node.postfix ? void 0 : nullType)) : type + ) + ); + } else { + grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + } + } + function checkJSDocVariadicType(node) { + checkJSDocTypeIsInJsFile(node); + checkSourceElement(node.type); + const { parent } = node; + if (isParameter(parent) && isJSDocFunctionType(parent.parent)) { + if (last(parent.parent.parameters) !== parent) { + error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } + if (!isJSDocTypeExpression(parent)) { + error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + } + const paramTag = node.parent.parent; + if (!isJSDocParameterTag(paramTag)) { + error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); + return; + } + const param = getParameterSymbolFromJSDoc(paramTag); + if (!param) { + return; + } + const host2 = getHostSignatureFromJSDoc(paramTag); + if (!host2 || last(host2.parameters).symbol !== param) { + error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + } + function getTypeFromJSDocVariadicType(node) { + const type = getTypeFromTypeNode(node.type); + const { parent } = node; + const paramTag = node.parent.parent; + if (isJSDocTypeExpression(node.parent) && isJSDocParameterTag(paramTag)) { + const host2 = getHostSignatureFromJSDoc(paramTag); + const isCallbackTag = isJSDocCallbackTag(paramTag.parent.parent); + if (host2 || isCallbackTag) { + const lastParamDeclaration = isCallbackTag ? lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) : lastOrUndefined(host2.parameters); + const symbol = getParameterSymbolFromJSDoc(paramTag); + if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && isRestParameter(lastParamDeclaration)) { + return createArrayType(type); + } + } + } + if (isParameter(parent) && isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } + return addOptionality(type); + } + function checkNodeDeferred(node) { + const enclosingFile = getSourceFileOfNode(node); + const links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes || (links.deferredNodes = /* @__PURE__ */ new Set()); + links.deferredNodes.add(node); + } else { + Debug.assert(!links.deferredNodes, "A type-checked file should have no deferred nodes."); + } + } + function checkDeferredNodes(context) { + const links = getNodeLinks(context); + if (links.deferredNodes) { + links.deferredNodes.forEach(checkDeferredNode); + } + links.deferredNodes = void 0; + } + function checkDeferredNode(node) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); + const saveCurrentNode = currentNode; + currentNode = node; + instantiationCount = 0; + switch (node.kind) { + case 213 /* CallExpression */: + case 214 /* NewExpression */: + case 215 /* TaggedTemplateExpression */: + case 170 /* Decorator */: + case 286 /* JsxOpeningElement */: + resolveUntypedCall(node); + break; + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + checkAccessorDeclaration(node); + break; + case 231 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + case 168 /* TypeParameter */: + checkTypeParameterDeferred(node); + break; + case 285 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 284 /* JsxElement */: + checkJsxElementDeferred(node); + break; + case 216 /* TypeAssertionExpression */: + case 234 /* AsExpression */: + case 217 /* ParenthesizedExpression */: + checkAssertionDeferred(node); + break; + case 222 /* VoidExpression */: + checkExpression(node.expression); + break; + case 226 /* BinaryExpression */: + if (isInstanceOfExpression(node)) { + resolveUntypedCall(node); + } + break; + } + currentNode = saveCurrentNode; + (_b = tracing) == null ? void 0 : _b.pop(); + } + function checkSourceFile(node, nodesToCheck) { + var _a, _b; + (_a = tracing) == null ? void 0 : _a.push( + tracing.Phase.Check, + nodesToCheck ? "checkSourceFileNodes" : "checkSourceFile", + { path: node.path }, + /*separateBeginAndEnd*/ + true + ); + const beforeMark = nodesToCheck ? "beforeCheckNodes" : "beforeCheck"; + const afterMark = nodesToCheck ? "afterCheckNodes" : "afterCheck"; + mark(beforeMark); + nodesToCheck ? checkSourceFileNodesWorker(node, nodesToCheck) : checkSourceFileWorker(node); + mark(afterMark); + measure("Check", beforeMark, afterMark); + (_b = tracing) == null ? void 0 : _b.pop(); + } + function unusedIsError(kind, isAmbient) { + if (isAmbient) { + return false; + } + switch (kind) { + case 0 /* Local */: + return !!compilerOptions.noUnusedLocals; + case 1 /* Parameter */: + return !!compilerOptions.noUnusedParameters; + default: + return Debug.assertNever(kind); + } + } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || emptyArray; + } + function checkSourceFileWorker(node) { + const links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + if (skipTypeChecking(node, compilerOptions, host)) { + return; + } + checkGrammarSourceFile(node); + clear(potentialThisCollisions); + clear(potentialNewTargetCollisions); + clear(potentialWeakMapSetCollisions); + clear(potentialReflectCollisions); + clear(potentialUnusedRenamedBindingElementsInTypes); + if (links.flags & 8388608 /* PartiallyTypeChecked */) { + potentialThisCollisions = links.potentialThisCollisions; + potentialNewTargetCollisions = links.potentialNewTargetCollisions; + potentialWeakMapSetCollisions = links.potentialWeakMapSetCollisions; + potentialReflectCollisions = links.potentialReflectCollisions; + potentialUnusedRenamedBindingElementsInTypes = links.potentialUnusedRenamedBindingElementsInTypes; + } + forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); + checkDeferredNodes(node); + if (isExternalOrCommonJsModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + addLazyDiagnostic(() => { + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), (containingNode, kind, diag2) => { + if (!containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 33554432 /* Ambient */))) { + diagnostics.add(diag2); + } + }); + } + if (!node.isDeclarationFile) { + checkPotentialUncheckedRenamedBindingElementsInTypes(); + } + }); + if (isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + clear(potentialNewTargetCollisions); + } + if (potentialWeakMapSetCollisions.length) { + forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision); + clear(potentialWeakMapSetCollisions); + } + if (potentialReflectCollisions.length) { + forEach(potentialReflectCollisions, checkReflectCollision); + clear(potentialReflectCollisions); + } + links.flags |= 1 /* TypeChecked */; + } + } + function checkSourceFileNodesWorker(file, nodes) { + const links = getNodeLinks(file); + if (!(links.flags & 1 /* TypeChecked */)) { + if (skipTypeChecking(file, compilerOptions, host)) { + return; + } + checkGrammarSourceFile(file); + clear(potentialThisCollisions); + clear(potentialNewTargetCollisions); + clear(potentialWeakMapSetCollisions); + clear(potentialReflectCollisions); + clear(potentialUnusedRenamedBindingElementsInTypes); + forEach(nodes, checkSourceElement); + checkDeferredNodes(file); + (links.potentialThisCollisions || (links.potentialThisCollisions = [])).push(...potentialThisCollisions); + (links.potentialNewTargetCollisions || (links.potentialNewTargetCollisions = [])).push(...potentialNewTargetCollisions); + (links.potentialWeakMapSetCollisions || (links.potentialWeakMapSetCollisions = [])).push(...potentialWeakMapSetCollisions); + (links.potentialReflectCollisions || (links.potentialReflectCollisions = [])).push(...potentialReflectCollisions); + (links.potentialUnusedRenamedBindingElementsInTypes || (links.potentialUnusedRenamedBindingElementsInTypes = [])).push( + ...potentialUnusedRenamedBindingElementsInTypes + ); + links.flags |= 8388608 /* PartiallyTypeChecked */; + for (const node of nodes) { + const nodeLinks2 = getNodeLinks(node); + nodeLinks2.flags |= 8388608 /* PartiallyTypeChecked */; + } + } + } + function getDiagnostics(sourceFile, ct, nodesToCheck) { + try { + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile, nodesToCheck); + } finally { + cancellationToken = void 0; + } + } + function ensurePendingDiagnosticWorkComplete() { + for (const cb of deferredDiagnosticsCallbacks) { + cb(); + } + deferredDiagnosticsCallbacks = []; + } + function checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck) { + ensurePendingDiagnosticWorkComplete(); + const oldAddLazyDiagnostics = addLazyDiagnostic; + addLazyDiagnostic = (cb) => cb(); + checkSourceFile(sourceFile, nodesToCheck); + addLazyDiagnostic = oldAddLazyDiagnostics; + } + function getDiagnosticsWorker(sourceFile, nodesToCheck) { + if (sourceFile) { + ensurePendingDiagnosticWorkComplete(); + const previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + const previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck); + const semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + if (nodesToCheck) { + return semanticDiagnostics; + } + const currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + const deferredGlobalDiagnostics = relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, compareDiagnostics); + return concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + return concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + forEach(host.getSourceFiles(), (file) => checkSourceFileWithEagerDiagnostics(file)); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + ensurePendingDiagnosticWorkComplete(); + return diagnostics.getGlobalDiagnostics(); + } + function getSymbolsInScope(location, meaning) { + if (location.flags & 67108864 /* InWithStatement */) { + return []; + } + const symbols = createSymbolTable(); + let isStaticSymbol = false; + populateSymbols(); + symbols.delete("this" /* This */); + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 307 /* SourceFile */: + if (!isExternalModule(location)) break; + // falls through + case 267 /* ModuleDeclaration */: + copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports, meaning & 2623475 /* ModuleMember */); + break; + case 266 /* EnumDeclaration */: + copySymbols(getSymbolOfDeclaration(location).exports, meaning & 8 /* EnumMember */); + break; + case 231 /* ClassExpression */: + const className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration. + // falls through + case 263 /* ClassDeclaration */: + case 264 /* InterfaceDeclaration */: + if (!isStaticSymbol) { + copySymbols(getMembersOfSymbol(getSymbolOfDeclaration(location)), meaning & 788968 /* Type */); + } + break; + case 218 /* FunctionExpression */: + const funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + isStaticSymbol = isStatic(location); + location = location.parent; + } + copySymbols(globals, meaning); + } + function copySymbol(symbol, meaning2) { + if (getCombinedLocalAndExportSymbolFlags(symbol) & meaning2) { + const id = symbol.escapedName; + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning2) { + if (meaning2) { + source.forEach((symbol) => { + copySymbol(symbol, meaning2); + }); + } + } + function copyLocallyVisibleExportSymbols(source, meaning2) { + if (meaning2) { + source.forEach((symbol) => { + if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */) && symbol.escapedName !== "default" /* Default */) { + copySymbol(symbol, meaning2); + } + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 80 /* Identifier */ && isTypeDeclaration(name.parent) && getNameOfDeclaration(name.parent) === name; + } + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 166 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 183 /* TypeReference */; + } + function isInNameOfExpressionWithTypeArguments(node) { + while (node.parent.kind === 211 /* PropertyAccessExpression */) { + node = node.parent; + } + return node.parent.kind === 233 /* ExpressionWithTypeArguments */; + } + function forEachEnclosingClass(node, callback) { + let result; + let containingClass = getContainingClass(node); + while (containingClass) { + if (result = callback(containingClass)) break; + containingClass = getContainingClass(containingClass); + } + return result; + } + function isNodeUsedDuringClassInitialization(node) { + return !!findAncestor(node, (element) => { + if (isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) { + return true; + } else if (isClassLike(element) || isFunctionLikeDeclaration(element)) { + return "quit"; + } + return false; + }); + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, (n) => n === classDeclaration); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 166 /* QualifiedName */) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 271 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : void 0; + } + if (nodeOnRightSide.parent.kind === 277 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : void 0; + } + return void 0; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== void 0; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + const specialPropertyAssignmentKind = getAssignmentDeclarationKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 5 /* Property */: + if (isPropertyAccessExpression(entityName.parent) && getLeftmostAccessExpression(entityName.parent) === entityName) { + return void 0; + } + // falls through + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + return getSymbolOfDeclaration(entityName.parent.parent); + } + } + function isImportTypeQualifierPart(node) { + let parent = node.parent; + while (isQualifiedName(parent)) { + node = parent; + parent = parent.parent; + } + if (parent && parent.kind === 205 /* ImportType */ && parent.qualifier === node) { + return parent; + } + return void 0; + } + function isThisPropertyAndThisTyped(node) { + if (node.expression.kind === 110 /* ThisKeyword */) { + const container = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (isFunctionLike(container)) { + const containingLiteral = getContainingObjectLiteral(container); + if (containingLiteral) { + const contextualType = getApparentTypeOfContextualType( + containingLiteral, + /*contextFlags*/ + void 0 + ); + const type = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType); + return type && !isTypeAny(type); + } + } + } + } + function getSymbolOfNameOrPropertyAccessExpression(name) { + if (isDeclarationName(name)) { + return getSymbolOfNode(name.parent); + } + if (isInJSFile(name) && name.parent.kind === 211 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) { + if (!isPrivateIdentifier(name) && !isJSDocMemberName(name) && !isThisPropertyAndThisTyped(name.parent)) { + const specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + } + if (name.parent.kind === 277 /* ExportAssignment */ && isEntityNameExpression(name)) { + const success = resolveEntityName( + name, + /*all meanings*/ + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*ignoreErrors*/ + true + ); + if (success && success !== unknownSymbol) { + return success; + } + } else if (isEntityName(name) && isInRightSideOfImportOrExportAssignment(name)) { + const importEqualsDeclaration = getAncestor(name, 271 /* ImportEqualsDeclaration */); + Debug.assert(importEqualsDeclaration !== void 0); + return getSymbolOfPartOfRightHandSideOfImportEquals( + name, + /*dontResolveAlias*/ + true + ); + } + if (isEntityName(name)) { + const possibleImportNode = isImportTypeQualifierPart(name); + if (possibleImportNode) { + getTypeFromTypeNode(possibleImportNode); + const sym = getNodeLinks(name).resolvedSymbol; + return sym === unknownSymbol ? void 0 : sym; + } + } + while (isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(name)) { + name = name.parent; + } + if (isInNameOfExpressionWithTypeArguments(name)) { + let meaning = 0 /* None */; + if (name.parent.kind === 233 /* ExpressionWithTypeArguments */) { + meaning = isPartOfTypeNode(name) ? 788968 /* Type */ : 111551 /* Value */; + if (isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) { + meaning |= 111551 /* Value */; + } + } else { + meaning = 1920 /* Namespace */; + } + meaning |= 2097152 /* Alias */; + const entityNameSymbol = isEntityNameExpression(name) ? resolveEntityName( + name, + meaning, + /*ignoreErrors*/ + true + ) : void 0; + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (name.parent.kind === 341 /* JSDocParameterTag */) { + return getParameterSymbolFromJSDoc(name.parent); + } + if (name.parent.kind === 168 /* TypeParameter */ && name.parent.parent.kind === 345 /* JSDocTemplateTag */) { + Debug.assert(!isInJSFile(name)); + const typeParameter = getTypeParameterFromJsDoc(name.parent); + return typeParameter && typeParameter.symbol; + } + if (isExpressionNode(name)) { + if (nodeIsMissing(name)) { + return void 0; + } + const isJSDoc2 = findAncestor(name, or(isJSDocLinkLike, isJSDocNameReference, isJSDocMemberName)); + const meaning = isJSDoc2 ? 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */ : 111551 /* Value */; + if (name.kind === 80 /* Identifier */) { + if (isJSXTagName(name) && isJsxIntrinsicTagName(name)) { + const symbol = getIntrinsicTagSymbol(name.parent); + return symbol === unknownSymbol ? void 0 : symbol; + } + const result = resolveEntityName( + name, + meaning, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + getHostSignatureFromJSDoc(name) + ); + if (!result && isJSDoc2) { + const container = findAncestor(name, or(isClassLike, isInterfaceDeclaration)); + if (container) { + return resolveJSDocMemberName( + name, + /*ignoreErrors*/ + true, + getSymbolOfDeclaration(container) + ); + } + } + if (result && isJSDoc2) { + const container = getJSDocHost(name); + if (container && isEnumMember(container) && container === result.valueDeclaration) { + return resolveEntityName( + name, + meaning, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + getSourceFileOfNode(container) + ) || result; + } + } + return result; + } else if (isPrivateIdentifier(name)) { + return getSymbolForPrivateIdentifierExpression(name); + } else if (name.kind === 211 /* PropertyAccessExpression */ || name.kind === 166 /* QualifiedName */) { + const links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (name.kind === 211 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(name, 0 /* Normal */); + if (!links.resolvedSymbol) { + links.resolvedSymbol = getApplicableIndexSymbol(checkExpressionCached(name.expression), getLiteralTypeFromPropertyName(name.name)); + } + } else { + checkQualifiedName(name, 0 /* Normal */); + } + if (!links.resolvedSymbol && isJSDoc2 && isQualifiedName(name)) { + return resolveJSDocMemberName(name); + } + return links.resolvedSymbol; + } else if (isJSDocMemberName(name)) { + return resolveJSDocMemberName(name); + } + } else if (isEntityName(name) && isTypeReferenceIdentifier(name)) { + const meaning = name.parent.kind === 183 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; + const symbol = resolveEntityName( + name, + meaning, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true + ); + return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name); + } + if (name.parent.kind === 182 /* TypePredicate */) { + return resolveEntityName( + name, + /*meaning*/ + 1 /* FunctionScopedVariable */, + /*ignoreErrors*/ + true + ); + } + return void 0; + } + function getApplicableIndexSymbol(type, keyType) { + const infos = getApplicableIndexInfos(type, keyType); + if (infos.length && type.members) { + const symbol = getIndexSymbolFromSymbolTable(resolveStructuredTypeMembers(type).members); + if (infos === getIndexInfosOfType(type)) { + return symbol; + } else if (symbol) { + const symbolLinks2 = getSymbolLinks(symbol); + const declarationList = mapDefined(infos, (i) => i.declaration); + const nodeListId = map(declarationList, getNodeId).join(","); + if (!symbolLinks2.filteredIndexSymbolCache) { + symbolLinks2.filteredIndexSymbolCache = /* @__PURE__ */ new Map(); + } + if (symbolLinks2.filteredIndexSymbolCache.has(nodeListId)) { + return symbolLinks2.filteredIndexSymbolCache.get(nodeListId); + } else { + const copy = createSymbol(131072 /* Signature */, "__index" /* Index */); + copy.declarations = mapDefined(infos, (i) => i.declaration); + copy.parent = type.aliasSymbol ? type.aliasSymbol : type.symbol ? type.symbol : getSymbolAtLocation(copy.declarations[0].parent); + symbolLinks2.filteredIndexSymbolCache.set(nodeListId, copy); + return copy; + } + } + } + } + function resolveJSDocMemberName(name, ignoreErrors, container) { + if (isEntityName(name)) { + const meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; + let symbol = resolveEntityName( + name, + meaning, + ignoreErrors, + /*dontResolveAlias*/ + true, + getHostSignatureFromJSDoc(name) + ); + if (!symbol && isIdentifier(name) && container) { + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning)); + } + if (symbol) { + return symbol; + } + } + const left = isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container); + const right = isIdentifier(name) ? name.escapedText : name.right.escapedText; + if (left) { + const proto = left.flags & 111551 /* Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype"); + const t = proto ? getTypeOfSymbol(proto) : getDeclaredTypeOfSymbol(left); + return getPropertyOfType(t, right); + } + } + function getSymbolAtLocation(node, ignoreErrors) { + if (isSourceFile(node)) { + return isExternalModule(node) ? getMergedSymbol(node.symbol) : void 0; + } + const { parent } = node; + const grandParent = parent.parent; + if (node.flags & 67108864 /* InWithStatement */) { + return void 0; + } + if (isDeclarationNameOrImportPropertyName(node)) { + const parentSymbol = getSymbolOfDeclaration(parent); + return isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node ? getImmediateAliasedSymbol(parentSymbol) : parentSymbol; + } else if (isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfDeclaration(parent.parent); + } + if (node.kind === 80 /* Identifier */) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfNameOrPropertyAccessExpression(node); + } else if (parent.kind === 208 /* BindingElement */ && grandParent.kind === 206 /* ObjectBindingPattern */ && node === parent.propertyName) { + const typeOfPattern = getTypeOfNode(grandParent); + const propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } else if (isMetaProperty(parent) && parent.name === node) { + if (parent.keywordToken === 105 /* NewKeyword */ && idText(node) === "target") { + return checkNewTargetMetaProperty(parent).symbol; + } + if (parent.keywordToken === 102 /* ImportKeyword */ && idText(node) === "meta") { + return getGlobalImportMetaExpressionType().members.get("meta"); + } + return void 0; + } + } + switch (node.kind) { + case 80 /* Identifier */: + case 81 /* PrivateIdentifier */: + case 211 /* PropertyAccessExpression */: + case 166 /* QualifiedName */: + if (!isThisInTypeQuery(node)) { + return getSymbolOfNameOrPropertyAccessExpression(node); + } + // falls through + case 110 /* ThisKeyword */: + const container = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (isFunctionLike(container)) { + const sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + if (isInExpressionContext(node)) { + return checkExpression(node).symbol; + } + // falls through + case 197 /* ThisType */: + return getTypeFromThisTypeNode(node).symbol; + case 108 /* SuperKeyword */: + return checkExpression(node).symbol; + case 137 /* ConstructorKeyword */: + const constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 176 /* Constructor */) { + return constructorDeclaration.parent.symbol; + } + return void 0; + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + if (isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node || (node.parent.kind === 272 /* ImportDeclaration */ || node.parent.kind === 278 /* ExportDeclaration */) && node.parent.moduleSpecifier === node || isInJSFile(node) && isJSDocImportTag(node.parent) && node.parent.moduleSpecifier === node || (isInJSFile(node) && isRequireCall( + node.parent, + /*requireStringLiteralLikeArgument*/ + false + ) || isImportCall(node.parent)) || isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) { + return resolveExternalModuleName(node, node, ignoreErrors); + } + if (isCallExpression(parent) && isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfDeclaration(parent); + } + // falls through + case 9 /* NumericLiteral */: + const objectType = isElementAccessExpression(parent) ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : void 0 : isLiteralTypeNode(parent) && isIndexedAccessTypeNode(grandParent) ? getTypeFromTypeNode(grandParent.objectType) : void 0; + return objectType && getPropertyOfType(objectType, escapeLeadingUnderscores(node.text)); + case 90 /* DefaultKeyword */: + case 100 /* FunctionKeyword */: + case 39 /* EqualsGreaterThanToken */: + case 86 /* ClassKeyword */: + return getSymbolOfNode(node.parent); + case 205 /* ImportType */: + return isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : void 0; + case 95 /* ExportKeyword */: + return isExportAssignment(node.parent) ? Debug.checkDefined(node.parent.symbol) : void 0; + case 102 /* ImportKeyword */: + case 105 /* NewKeyword */: + return isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : void 0; + case 104 /* InstanceOfKeyword */: + if (isBinaryExpression(node.parent)) { + const type = getTypeOfExpression(node.parent.right); + const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(type); + return (hasInstanceMethodType == null ? void 0 : hasInstanceMethodType.symbol) ?? type.symbol; + } + return void 0; + case 236 /* MetaProperty */: + return checkExpression(node).symbol; + case 295 /* JsxNamespacedName */: + if (isJSXTagName(node) && isJsxIntrinsicTagName(node)) { + const symbol = getIntrinsicTagSymbol(node.parent); + return symbol === unknownSymbol ? void 0 : symbol; + } + // falls through + default: + return void 0; + } + } + function getIndexInfosAtLocation(node) { + if (isIdentifier(node) && isPropertyAccessExpression(node.parent) && node.parent.name === node) { + const keyType = getLiteralTypeFromPropertyName(node); + const objectType = getTypeOfExpression(node.parent.expression); + const objectTypes = objectType.flags & 1048576 /* Union */ ? objectType.types : [objectType]; + return flatMap(objectTypes, (t) => filter(getIndexInfosOfType(t), (info) => isApplicableIndexType(keyType, info.keyType))); + } + return void 0; + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 304 /* ShorthandPropertyAssignment */) { + return resolveEntityName( + location.name, + 111551 /* Value */ | 2097152 /* Alias */, + /*ignoreErrors*/ + true + ); + } + return void 0; + } + function getExportSpecifierLocalTargetSymbol(node) { + if (isExportSpecifier(node)) { + const name = node.propertyName || node.name; + return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : name.kind === 11 /* StringLiteral */ ? void 0 : ( + // Skip for invalid syntax like this: export { "x" } + resolveEntityName( + name, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*ignoreErrors*/ + true + ) + ); + } else { + return resolveEntityName( + node, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*ignoreErrors*/ + true + ); + } + } + function getTypeOfNode(node) { + if (isSourceFile(node) && !isExternalModule(node)) { + return errorType; + } + if (node.flags & 67108864 /* InWithStatement */) { + return errorType; + } + const classDecl = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + const classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(classDecl.class)); + if (isPartOfTypeNode(node)) { + const typeFromTypeNode = getTypeFromTypeNode(node); + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; + } + if (isExpressionNode(node)) { + return getRegularTypeOfExpression(node); + } + if (classType && !classDecl.isImplements) { + const baseType = firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; + } + if (isTypeDeclaration(node)) { + const symbol = getSymbolOfDeclaration(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + const symbol = getSymbolAtLocation(node); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; + } + if (isBindingElement(node)) { + return getTypeForVariableLikeDeclaration( + node, + /*includeOptionality*/ + true, + 0 /* Normal */ + ) || errorType; + } + if (isDeclaration(node)) { + const symbol = getSymbolOfDeclaration(node); + return symbol ? getTypeOfSymbol(symbol) : errorType; + } + if (isDeclarationNameOrImportPropertyName(node)) { + const symbol = getSymbolAtLocation(node); + if (symbol) { + return getTypeOfSymbol(symbol); + } + return errorType; + } + if (isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration( + node.parent, + /*includeOptionality*/ + true, + 0 /* Normal */ + ) || errorType; + } + if (isInRightSideOfImportOrExportAssignment(node)) { + const symbol = getSymbolAtLocation(node); + if (symbol) { + const declaredType = getDeclaredTypeOfSymbol(symbol); + return !isErrorType(declaredType) ? declaredType : getTypeOfSymbol(symbol); + } + } + if (isMetaProperty(node.parent) && node.parent.keywordToken === node.kind) { + return checkMetaPropertyKeyword(node.parent); + } + if (isImportAttributes(node)) { + return getGlobalImportAttributesType( + /*reportErrors*/ + false + ); + } + return errorType; + } + function getTypeOfAssignmentPattern(expr) { + Debug.assert(expr.kind === 210 /* ObjectLiteralExpression */ || expr.kind === 209 /* ArrayLiteralExpression */); + if (expr.parent.kind === 250 /* ForOfStatement */) { + const iteratedType = checkRightHandSideOfForOf(expr.parent); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + if (expr.parent.kind === 226 /* BinaryExpression */) { + const iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || errorType); + } + if (expr.parent.kind === 303 /* PropertyAssignment */) { + const node2 = cast(expr.parent.parent, isObjectLiteralExpression); + const typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node2) || errorType; + const propertyIndex = indexOfNode(node2.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node2, typeOfParentObjectLiteral, propertyIndex); + } + const node = cast(expr.parent, isArrayLiteralExpression); + const typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType; + const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType; + return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType); + } + function getPropertySymbolOfDestructuringAssignment(location) { + const typeOfObjectLiteral = getTypeOfAssignmentPattern(cast(location.parent.parent, isAssignmentPattern)); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + function getParentTypeOfClassElement(node) { + const classSymbol = getSymbolOfNode(node.parent); + return isStatic(node) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); + } + function getClassElementPropertyKeyType(element) { + const name = element.name; + switch (name.kind) { + case 80 /* Identifier */: + return getStringLiteralType(idText(name)); + case 9 /* NumericLiteral */: + case 11 /* StringLiteral */: + return getStringLiteralType(name.text); + case 167 /* ComputedPropertyName */: + const nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; + default: + return Debug.fail("Unsupported property name."); + } + } + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + const propsByName = createSymbolTable(getPropertiesOfType(type)); + const functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : void 0; + if (functionType) { + forEach(getPropertiesOfType(functionType), (p) => { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function typeHasCallOrConstructSignatures(type) { + return getSignaturesOfType(type, 0 /* Call */).length !== 0 || getSignaturesOfType(type, 1 /* Construct */).length !== 0; + } + function getRootSymbols(symbol) { + const roots = getImmediateRootSymbols(symbol); + return roots ? flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { + if (getCheckFlags(symbol) & 6 /* Synthetic */) { + return mapDefined(getSymbolLinks(symbol).containingType.types, (type) => getPropertyOfType(type, symbol.escapedName)); + } else if (symbol.flags & 33554432 /* Transient */) { + const { links: { leftSpread, rightSpread, syntheticOrigin } } = symbol; + return leftSpread ? [leftSpread, rightSpread] : syntheticOrigin ? [syntheticOrigin] : singleElementArray(tryGetTarget(symbol)); + } + return void 0; + } + function tryGetTarget(symbol) { + let target; + let next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + return target; + } + function isArgumentsLocalBinding(nodeIn) { + if (isGeneratedIdentifier(nodeIn)) return false; + const node = getParseTreeNode(nodeIn, isIdentifier); + if (!node) return false; + const parent = node.parent; + if (!parent) return false; + const isPropertyName2 = (isPropertyAccessExpression(parent) || isPropertyAssignment(parent)) && parent.name === node; + return !isPropertyName2 && getReferencedValueSymbol(node) === argumentsSymbol; + } + function isNameOfModuleOrEnumDeclaration(node) { + return isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; + } + function getReferencedExportContainer(nodeIn, prefixLocals) { + var _a; + const node = getParseTreeNode(nodeIn, isIdentifier); + if (node) { + let symbol = getReferencedValueSymbol( + node, + /*startInDeclarationContainer*/ + isNameOfModuleOrEnumDeclaration(node) + ); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + const exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) { + return void 0; + } + symbol = exportSymbol; + } + const parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 /* ValueModule */ && ((_a = parentSymbol.valueDeclaration) == null ? void 0 : _a.kind) === 307 /* SourceFile */) { + const symbolFile = parentSymbol.valueDeclaration; + const referenceFile = getSourceFileOfNode(node); + const symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? void 0 : symbolFile; + } + return findAncestor(node.parent, (n) => isModuleOrEnumDeclaration(n) && getSymbolOfDeclaration(n) === parentSymbol); + } + } + } + } + function getReferencedImportDeclaration(nodeIn) { + const specifier = getIdentifierGeneratedImportReference(nodeIn); + if (specifier) { + return specifier; + } + const node = getParseTreeNode(nodeIn, isIdentifier); + if (node) { + const symbol = getReferencedValueOrAliasSymbol(node); + if (isNonLocalAlias( + symbol, + /*excludes*/ + 111551 /* Value */ + ) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return void 0; + } + function isSymbolOfDestructuredElementOfCatchBinding(symbol) { + return symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration) && walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 299 /* CatchClause */; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !isSourceFile(symbol.valueDeclaration)) { + const links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === void 0) { + const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) { + if (resolveName( + container.parent, + symbol.escapedName, + 111551 /* Value */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false + )) { + links.isDeclarationWithCollidingName = true; + } else if (hasNodeCheckFlag(symbol.valueDeclaration, 16384 /* CapturedBlockScopedBinding */)) { + const isDeclaredInLoop = hasNodeCheckFlag(symbol.valueDeclaration, 32768 /* BlockScopedBindingInLoop */); + const inLoopInitializer = isIterationStatement( + container, + /*lookInLabeledStatements*/ + false + ); + const inLoopBodyBlock = container.kind === 241 /* Block */ && isIterationStatement( + container.parent, + /*lookInLabeledStatements*/ + false + ); + links.isDeclarationWithCollidingName = !isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || !inLoopInitializer && !inLoopBodyBlock); + } else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!isGeneratedIdentifier(nodeIn)) { + const node = getParseTreeNode(nodeIn, isIdentifier); + if (node) { + const symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return void 0; + } + function isDeclarationWithCollidingName(nodeIn) { + const node = getParseTreeNode(nodeIn, isDeclaration); + if (node) { + const symbol = getSymbolOfDeclaration(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + Debug.assert(canCollectSymbolAliasAccessabilityData); + switch (node.kind) { + case 271 /* ImportEqualsDeclaration */: + return isAliasResolvedToValue(getSymbolOfDeclaration(node)); + case 273 /* ImportClause */: + case 274 /* NamespaceImport */: + case 276 /* ImportSpecifier */: + case 281 /* ExportSpecifier */: + const symbol = getSymbolOfDeclaration(node); + return !!symbol && isAliasResolvedToValue( + symbol, + /*excludeTypeOnlyValues*/ + true + ); + case 278 /* ExportDeclaration */: + const exportClause = node.exportClause; + return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration)); + case 277 /* ExportAssignment */: + return node.expression && node.expression.kind === 80 /* Identifier */ ? isAliasResolvedToValue( + getSymbolOfDeclaration(node), + /*excludeTypeOnlyValues*/ + true + ) : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + const node = getParseTreeNode(nodeIn, isImportEqualsDeclaration); + if (node === void 0 || node.parent.kind !== 307 /* SourceFile */ || !isInternalModuleImportEqualsDeclaration(node)) { + return false; + } + const isValue = isAliasResolvedToValue(getSymbolOfDeclaration(node)); + return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol, excludeTypeOnlyValues) { + if (!symbol) { + return false; + } + const container = getSourceFileOfNode(symbol.valueDeclaration); + const fileSymbol = container && getSymbolOfDeclaration(container); + void resolveExternalModuleSymbol(fileSymbol); + const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); + if (target === unknownSymbol) { + return !excludeTypeOnlyValues || !getTypeOnlyAliasDeclaration(symbol); + } + return !!(getSymbolFlags( + symbol, + excludeTypeOnlyValues, + /*excludeLocalMeanings*/ + true + ) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + Debug.assert(canCollectSymbolAliasAccessabilityData); + if (isAliasSymbolDeclaration(node)) { + const symbol = getSymbolOfDeclaration(node); + const links = symbol && getSymbolLinks(symbol); + if (links == null ? void 0 : links.referenced) { + return true; + } + const target = getSymbolLinks(symbol).aliasTarget; + if (target && getEffectiveModifierFlags(node) & 32 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { + return true; + } + } + if (checkChildren) { + return !!forEachChild(node, (node2) => isReferencedAliasDeclaration(node2, checkChildren)); + } + return false; + } + function isImplementationOfOverload(node) { + if (nodeIsPresent(node.body)) { + if (isGetAccessor(node) || isSetAccessor(node)) return false; + const symbol = getSymbolOfDeclaration(node); + const signaturesOfSymbol = getSignaturesOfSymbol(symbol); + return signaturesOfSymbol.length > 1 || // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node; + } + return false; + } + function declaredParameterTypeContainsUndefined(parameter) { + const typeNode = getNonlocalEffectiveTypeAnnotationNode(parameter); + if (!typeNode) return false; + const type = getTypeFromTypeNode(typeNode); + return isErrorType(type) || containsUndefinedType(type); + } + function requiresAddingImplicitUndefined(parameter, enclosingDeclaration) { + return (isRequiredInitializedParameter(parameter, enclosingDeclaration) || isOptionalUninitializedParameterProperty(parameter)) && !declaredParameterTypeContainsUndefined(parameter); + } + function isRequiredInitializedParameter(parameter, enclosingDeclaration) { + if (!strictNullChecks || isOptionalParameter(parameter) || isJSDocParameterTag(parameter) || !parameter.initializer) { + return false; + } + if (hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */)) { + return !!enclosingDeclaration && isFunctionLikeDeclaration(enclosingDeclaration); + } + return true; + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && isOptionalParameter(parameter) && (isJSDocParameterTag(parameter) || !parameter.initializer) && hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */); + } + function isExpandoFunctionDeclaration(node) { + const declaration = getParseTreeNode(node, (n) => isFunctionDeclaration(n) || isVariableDeclaration(n)); + if (!declaration) { + return false; + } + let symbol; + if (isVariableDeclaration(declaration)) { + if (declaration.type || !isInJSFile(declaration) && !isVarConstLike2(declaration)) { + return false; + } + const initializer = getDeclaredExpandoInitializer(declaration); + if (!initializer || !canHaveSymbol(initializer)) { + return false; + } + symbol = getSymbolOfDeclaration(initializer); + } else { + symbol = getSymbolOfDeclaration(declaration); + } + if (!symbol || !(symbol.flags & 16 /* Function */ | 3 /* Variable */)) { + return false; + } + return !!forEachEntry(getExportsOfSymbol(symbol), (p) => p.flags & 111551 /* Value */ && isExpandoPropertyDeclaration(p.valueDeclaration)); + } + function getPropertiesOfContainerFunction(node) { + const declaration = getParseTreeNode(node, isFunctionDeclaration); + if (!declaration) { + return emptyArray; + } + const symbol = getSymbolOfDeclaration(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || emptyArray; + } + function getNodeCheckFlags(node) { + var _a; + const nodeId = node.id || 0; + if (nodeId < 0 || nodeId >= nodeLinks.length) return 0; + return ((_a = nodeLinks[nodeId]) == null ? void 0 : _a.flags) || 0; + } + function hasNodeCheckFlag(node, flag) { + calculateNodeCheckFlagWorker(node, flag); + return !!(getNodeCheckFlags(node) & flag); + } + function calculateNodeCheckFlagWorker(node, flag) { + if (!compilerOptions.noCheck && canIncludeBindAndCheckDiagnostics(getSourceFileOfNode(node), compilerOptions)) { + return; + } + const links = getNodeLinks(node); + if (links.calculatedFlags & flag) { + return; + } + switch (flag) { + case 16 /* SuperInstance */: + case 32 /* SuperStatic */: + return checkSingleSuperExpression(node); + case 128 /* MethodWithSuperPropertyAccessInAsync */: + case 256 /* MethodWithSuperPropertyAssignmentInAsync */: + case 2097152 /* ContainsSuperPropertyInStaticInitializer */: + return checkChildSuperExpressions(node); + case 512 /* CaptureArguments */: + case 8192 /* ContainsCapturedBlockScopeBinding */: + case 65536 /* NeedsLoopOutParameter */: + case 262144 /* ContainsConstructorReference */: + return checkChildIdentifiers(node); + case 536870912 /* ConstructorReference */: + return checkSingleIdentifier(node); + case 4096 /* LoopWithCapturedBlockScopedBinding */: + case 32768 /* BlockScopedBindingInLoop */: + case 16384 /* CapturedBlockScopedBinding */: + return checkContainingBlockScopeBindingUses(node); + default: + return Debug.assertNever(flag, `Unhandled node check flag calculation: ${Debug.formatNodeCheckFlags(flag)}`); + } + function forEachNodeRecursively(root, cb) { + const rootResult = cb(root, root.parent); + if (rootResult === "skip") return void 0; + if (rootResult) return rootResult; + return forEachChildRecursively(root, cb); + } + function checkSuperExpressions(node2) { + const links2 = getNodeLinks(node2); + if (links2.calculatedFlags & flag) return "skip"; + links2.calculatedFlags |= 128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */ | 2097152 /* ContainsSuperPropertyInStaticInitializer */; + checkSingleSuperExpression(node2); + return void 0; + } + function checkChildSuperExpressions(node2) { + forEachNodeRecursively(node2, checkSuperExpressions); + } + function checkSingleSuperExpression(node2) { + const nodeLinks2 = getNodeLinks(node2); + nodeLinks2.calculatedFlags |= 16 /* SuperInstance */ | 32 /* SuperStatic */; + if (node2.kind === 108 /* SuperKeyword */) { + checkSuperExpression(node2); + } + } + function checkIdentifiers(node2) { + const links2 = getNodeLinks(node2); + if (links2.calculatedFlags & flag) return "skip"; + links2.calculatedFlags |= 512 /* CaptureArguments */ | 8192 /* ContainsCapturedBlockScopeBinding */ | 65536 /* NeedsLoopOutParameter */ | 262144 /* ContainsConstructorReference */; + checkSingleIdentifier(node2); + return void 0; + } + function checkChildIdentifiers(node2) { + forEachNodeRecursively(node2, checkIdentifiers); + } + function isExpressionNodeOrShorthandPropertyAssignmentName(node2) { + return isExpressionNode(node2) || isShorthandPropertyAssignment(node2.parent) && (node2.parent.objectAssignmentInitializer ?? node2.parent.name) === node2; + } + function checkSingleIdentifier(node2) { + const nodeLinks2 = getNodeLinks(node2); + nodeLinks2.calculatedFlags |= 536870912 /* ConstructorReference */; + if (isIdentifier(node2)) { + nodeLinks2.calculatedFlags |= 32768 /* BlockScopedBindingInLoop */ | 16384 /* CapturedBlockScopedBinding */; + if (isExpressionNodeOrShorthandPropertyAssignmentName(node2) && !(isPropertyAccessExpression(node2.parent) && node2.parent.name === node2)) { + const s = getResolvedSymbol(node2); + if (s && s !== unknownSymbol) { + checkIdentifierCalculateNodeCheckFlags(node2, s); + } + } + } + } + function checkBlockScopeBindings(node2) { + const links2 = getNodeLinks(node2); + if (links2.calculatedFlags & flag) return "skip"; + links2.calculatedFlags |= 4096 /* LoopWithCapturedBlockScopedBinding */ | 32768 /* BlockScopedBindingInLoop */ | 16384 /* CapturedBlockScopedBinding */; + checkSingleBlockScopeBinding(node2); + return void 0; + } + function checkContainingBlockScopeBindingUses(node2) { + const scope = getEnclosingBlockScopeContainer(isDeclarationName(node2) ? node2.parent : node2); + forEachNodeRecursively(scope, checkBlockScopeBindings); + } + function checkSingleBlockScopeBinding(node2) { + checkSingleIdentifier(node2); + if (isComputedPropertyName(node2)) { + checkComputedPropertyName(node2); + } + if (isPrivateIdentifier(node2) && isClassElement(node2.parent)) { + setNodeLinksForPrivateIdentifierScope(node2.parent); + } + } + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue ?? evaluatorResult( + /*value*/ + void 0 + ); + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 306 /* EnumMember */: + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + return true; + } + return false; + } + function getConstantValue2(node) { + if (node.kind === 306 /* EnumMember */) { + return getEnumMemberValue(node).value; + } + if (!getNodeLinks(node).resolvedSymbol) { + void checkExpressionCached(node); + } + const symbol = getNodeLinks(node).resolvedSymbol || (isEntityNameExpression(node) ? resolveEntityName( + node, + 111551 /* Value */, + /*ignoreErrors*/ + true + ) : void 0); + if (symbol && symbol.flags & 8 /* EnumMember */) { + const member = symbol.valueDeclaration; + if (isEnumConst(member.parent)) { + return getEnumMemberValue(member).value; + } + } + return void 0; + } + function isFunctionType(type) { + return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; + } + function getTypeReferenceSerializationKind(typeNameIn, location) { + var _a; + const typeName = getParseTreeNode(typeNameIn, isEntityName); + if (!typeName) return 0 /* Unknown */; + if (location) { + location = getParseTreeNode(location); + if (!location) return 0 /* Unknown */; + } + let isTypeOnly = false; + if (isQualifiedName(typeName)) { + const rootValueSymbol = resolveEntityName( + getFirstIdentifier(typeName), + 111551 /* Value */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + location + ); + isTypeOnly = !!((_a = rootValueSymbol == null ? void 0 : rootValueSymbol.declarations) == null ? void 0 : _a.every(isTypeOnlyImportOrExportDeclaration)); + } + const valueSymbol = resolveEntityName( + typeName, + 111551 /* Value */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + location + ); + const resolvedValueSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol; + isTypeOnly || (isTypeOnly = !!(valueSymbol && getTypeOnlyAliasDeclaration(valueSymbol, 111551 /* Value */))); + const typeSymbol = resolveEntityName( + typeName, + 788968 /* Type */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + location + ); + const resolvedTypeSymbol = typeSymbol && typeSymbol.flags & 2097152 /* Alias */ ? resolveAlias(typeSymbol) : typeSymbol; + if (!valueSymbol) { + isTypeOnly || (isTypeOnly = !!(typeSymbol && getTypeOnlyAliasDeclaration(typeSymbol, 788968 /* Type */))); + } + if (resolvedValueSymbol && resolvedValueSymbol === resolvedTypeSymbol) { + const globalPromiseSymbol = getGlobalPromiseConstructorSymbol( + /*reportErrors*/ + false + ); + if (globalPromiseSymbol && resolvedValueSymbol === globalPromiseSymbol) { + return 9 /* Promise */; + } + const constructorType = getTypeOfSymbol(resolvedValueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return isTypeOnly ? 10 /* TypeWithCallSignature */ : 1 /* TypeWithConstructSignatureAndValue */; + } + } + if (!resolvedTypeSymbol) { + return isTypeOnly ? 11 /* ObjectType */ : 0 /* Unknown */; + } + const type = getDeclaredTypeOfSymbol(resolvedTypeSymbol); + if (isErrorType(type)) { + return isTypeOnly ? 11 /* ObjectType */ : 0 /* Unknown */; + } else if (type.flags & 3 /* AnyOrUnknown */) { + return 11 /* ObjectType */; + } else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) { + return 2 /* VoidNullableOrNeverType */; + } else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) { + return 6 /* BooleanType */; + } else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) { + return 3 /* NumberLikeType */; + } else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) { + return 4 /* BigIntLikeType */; + } else if (isTypeAssignableToKind(type, 402653316 /* StringLike */)) { + return 5 /* StringLikeType */; + } else if (isTupleType(type)) { + return 7 /* ArrayLikeType */; + } else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) { + return 8 /* ESSymbolType */; + } else if (isFunctionType(type)) { + return 10 /* TypeWithCallSignature */; + } else if (isArrayType(type)) { + return 7 /* ArrayLikeType */; + } else { + return 11 /* ObjectType */; + } + } + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, internalFlags, tracker) { + const declaration = getParseTreeNode(declarationIn, hasInferredType); + if (!declaration) { + return factory.createToken(133 /* AnyKeyword */); + } + const symbol = getSymbolOfDeclaration(declaration); + return nodeBuilder.serializeTypeForDeclaration(declaration, symbol, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); + } + function getAllAccessorDeclarationsForDeclaration(accessor) { + accessor = getParseTreeNode(accessor, isGetOrSetAccessorDeclaration); + const otherKind = accessor.kind === 178 /* SetAccessor */ ? 177 /* GetAccessor */ : 178 /* SetAccessor */; + const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(accessor), otherKind); + const firstAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? otherAccessor : accessor; + const secondAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? accessor : otherAccessor; + const setAccessor = accessor.kind === 178 /* SetAccessor */ ? accessor : otherAccessor; + const getAccessor = accessor.kind === 177 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor, + secondAccessor, + setAccessor, + getAccessor + }; + } + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, internalFlags, tracker) { + const signatureDeclaration = getParseTreeNode(signatureDeclarationIn, isFunctionLike); + if (!signatureDeclaration) { + return factory.createToken(133 /* AnyKeyword */); + } + return nodeBuilder.serializeReturnTypeForSignature(signatureDeclaration, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); + } + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, internalFlags, tracker) { + const expr = getParseTreeNode(exprIn, isExpression); + if (!expr) { + return factory.createToken(133 /* AnyKeyword */); + } + return nodeBuilder.serializeTypeForExpression(expr, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); + } + function hasGlobalName(name) { + return globals.has(escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + const resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + let location = reference; + if (startInDeclarationContainer) { + const parent = reference.parent; + if (isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName( + location, + reference.escapedText, + 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + } + function getReferencedValueOrAliasSymbol(reference) { + const resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol && resolvedSymbol !== unknownSymbol) { + return resolvedSymbol; + } + return resolveName( + reference, + reference.escapedText, + 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true, + /*excludeGlobals*/ + void 0 + ); + } + function getReferencedValueDeclaration(referenceIn) { + if (!isGeneratedIdentifier(referenceIn)) { + const reference = getParseTreeNode(referenceIn, isIdentifier); + if (reference) { + const symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return void 0; + } + function getReferencedValueDeclarations(referenceIn) { + if (!isGeneratedIdentifier(referenceIn)) { + const reference = getParseTreeNode(referenceIn, isIdentifier); + if (reference) { + const symbol = getReferencedValueSymbol(reference); + if (symbol) { + return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration) => { + switch (declaration.kind) { + case 260 /* VariableDeclaration */: + case 169 /* Parameter */: + case 208 /* BindingElement */: + case 172 /* PropertyDeclaration */: + case 303 /* PropertyAssignment */: + case 304 /* ShorthandPropertyAssignment */: + case 306 /* EnumMember */: + case 210 /* ObjectLiteralExpression */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 266 /* EnumDeclaration */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 267 /* ModuleDeclaration */: + return true; + } + return false; + }); + } + } + } + return void 0; + } + function isLiteralConstDeclaration(node) { + if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike2(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node))); + } + return false; + } + function literalTypeToNode(type, enclosing, tracker) { + const enumResult = type.flags & 1056 /* EnumLike */ ? nodeBuilder.symbolToExpression( + type.symbol, + 111551 /* Value */, + enclosing, + /*flags*/ + void 0, + /*internalFlags*/ + void 0, + tracker + ) : type === trueType ? factory.createTrue() : type === falseType && factory.createFalse(); + if (enumResult) return enumResult; + const literalValue = type.value; + return typeof literalValue === "object" ? factory.createBigIntLiteral(literalValue) : typeof literalValue === "string" ? factory.createStringLiteral(literalValue) : literalValue < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-literalValue)) : factory.createNumericLiteral(literalValue); + } + function createLiteralConstValue(node, tracker) { + const type = getTypeOfSymbol(getSymbolOfDeclaration(node)); + return literalTypeToNode(type, node, tracker); + } + function getJsxFactoryEntity(location) { + return location ? (getJsxNamespace(location), getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity) : _jsxFactoryEntity; + } + function getJsxFragmentFactoryEntity(location) { + if (location) { + const file = getSourceFileOfNode(location); + if (file) { + if (file.localJsxFragmentFactory) { + return file.localJsxFragmentFactory; + } + const jsxFragPragmas = file.pragmas.get("jsxfrag"); + const jsxFragPragma = isArray(jsxFragPragmas) ? jsxFragPragmas[0] : jsxFragPragmas; + if (jsxFragPragma) { + file.localJsxFragmentFactory = parseIsolatedEntityName(jsxFragPragma.arguments.factory, languageVersion); + return file.localJsxFragmentFactory; + } + } + } + if (compilerOptions.jsxFragmentFactory) { + return parseIsolatedEntityName(compilerOptions.jsxFragmentFactory, languageVersion); + } + } + function getNonlocalEffectiveTypeAnnotationNode(node) { + const direct = getEffectiveTypeAnnotationNode(node); + if (direct) { + return direct; + } + if (node.kind === 169 /* Parameter */ && node.parent.kind === 178 /* SetAccessor */) { + const other = getAllAccessorDeclarationsForDeclaration(node.parent).getAccessor; + if (other) { + return getEffectiveReturnTypeNode(other); + } + } + return void 0; + } + function createResolver() { + return { + getReferencedExportContainer, + getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName, + isValueAliasDeclaration: (nodeIn) => { + const node = getParseTreeNode(nodeIn); + return node && canCollectSymbolAliasAccessabilityData ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName, + isReferencedAliasDeclaration: (nodeIn, checkChildren) => { + const node = getParseTreeNode(nodeIn); + return node && canCollectSymbolAliasAccessabilityData ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + hasNodeCheckFlag: (nodeIn, flag) => { + const node = getParseTreeNode(nodeIn); + if (!node) return false; + return hasNodeCheckFlag(node, flag); + }, + isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible, + isImplementationOfOverload, + requiresAddingImplicitUndefined, + isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction, + createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration, + createTypeOfExpression, + createLiteralConstValue, + isSymbolAccessible, + isEntityNameVisible, + getConstantValue: (nodeIn) => { + const node = getParseTreeNode(nodeIn, canHaveConstantValue); + return node ? getConstantValue2(node) : void 0; + }, + getEnumMemberValue: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isEnumMember); + return node ? getEnumMemberValue(node) : void 0; + }, + collectLinkedAliases, + markLinkedReferences: (nodeIn) => { + const node = getParseTreeNode(nodeIn); + return node && markLinkedReferences(node, 0 /* Unspecified */); + }, + getReferencedValueDeclaration, + getReferencedValueDeclarations, + getTypeReferenceSerializationKind, + isOptionalParameter, + isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: (nodeIn) => { + const node = getParseTreeNode(nodeIn, hasPossibleExternalModuleReference); + return node && getExternalModuleFileFromDeclaration(node); + }, + isLiteralConstDeclaration, + isLateBound: (nodeIn) => { + const node = getParseTreeNode(nodeIn, isDeclaration); + const symbol = node && getSymbolOfDeclaration(node); + return !!(symbol && getCheckFlags(symbol) & 4096 /* Late */); + }, + getJsxFactoryEntity, + getJsxFragmentFactoryEntity, + isBindingCapturedByNode: (node, decl) => { + const parseNode = getParseTreeNode(node); + const parseDecl = getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (isVariableDeclaration(parseDecl) || isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + }, + getDeclarationStatementsForSourceFile: (node, flags, internalFlags, tracker) => { + const n = getParseTreeNode(node); + Debug.assert(n && n.kind === 307 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); + const sym = getSymbolOfDeclaration(node); + if (!sym) { + return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, internalFlags, tracker); + } + resolveExternalModuleSymbol(sym); + return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, internalFlags, tracker); + }, + isImportRequiredByAugmentation, + isDefinitelyReferenceToGlobalSymbolObject, + createLateBoundIndexSignatures: (cls, enclosing, flags, internalFlags, tracker) => { + const sym = cls.symbol; + const staticInfos = getIndexInfosOfType(getTypeOfSymbol(sym)); + const instanceIndexSymbol = getIndexSymbol(sym); + const instanceInfos = instanceIndexSymbol && getIndexInfosOfIndexSymbol(instanceIndexSymbol, arrayFrom(getMembersOfSymbol(sym).values())); + let result; + for (const infoList of [staticInfos, instanceInfos]) { + if (!length(infoList)) continue; + result || (result = []); + for (const info of infoList) { + if (info.declaration) continue; + if (info === anyBaseTypeIndexInfo) continue; + if (info.components) { + const allComponentComputedNamesSerializable = every(info.components, (e) => { + var _a; + return !!(e.name && isComputedPropertyName(e.name) && isEntityNameExpression(e.name.expression) && enclosing && ((_a = isEntityNameVisible( + e.name.expression, + enclosing, + /*shouldComputeAliasToMakeVisible*/ + false + )) == null ? void 0 : _a.accessibility) === 0 /* Accessible */); + }); + if (allComponentComputedNamesSerializable) { + const newComponents = filter(info.components, (e) => { + return !hasLateBindableName(e); + }); + result.push(...map(newComponents, (e) => { + trackComputedName(e.name.expression); + const mods = infoList === staticInfos ? [factory.createModifier(126 /* StaticKeyword */)] : void 0; + return factory.createPropertyDeclaration( + append(mods, info.isReadonly ? factory.createModifier(148 /* ReadonlyKeyword */) : void 0), + e.name, + (isPropertySignature(e) || isPropertyDeclaration(e) || isMethodSignature(e) || isMethodDeclaration(e) || isGetAccessor(e) || isSetAccessor(e)) && e.questionToken ? factory.createToken(58 /* QuestionToken */) : void 0, + nodeBuilder.typeToTypeNode(getTypeOfSymbol(e.symbol), enclosing, flags, internalFlags, tracker), + /*initializer*/ + void 0 + ); + })); + continue; + } + } + const node = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, enclosing, flags, internalFlags, tracker); + if (node && infoList === staticInfos) { + (node.modifiers || (node.modifiers = factory.createNodeArray())).unshift(factory.createModifier(126 /* StaticKeyword */)); + } + if (node) { + result.push(node); + } + } + } + return result; + function trackComputedName(accessExpression) { + if (!tracker.trackSymbol) return; + const firstIdentifier = getFirstIdentifier(accessExpression); + const name = resolveName( + firstIdentifier, + firstIdentifier.escapedText, + 111551 /* Value */ | 1048576 /* ExportValue */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (name) { + tracker.trackSymbol(name, enclosing, 111551 /* Value */); + } + } + } + }; + function isImportRequiredByAugmentation(node) { + const file = getSourceFileOfNode(node); + if (!file.symbol) return false; + const importTarget = getExternalModuleFileFromDeclaration(node); + if (!importTarget) return false; + if (importTarget === file) return false; + const exports2 = getExportsOfModule(file.symbol); + for (const s of arrayFrom(exports2.values())) { + if (s.mergeId) { + const merged = getMergedSymbol(s); + if (merged.declarations) { + for (const d of merged.declarations) { + const declFile = getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } + } + } + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + const specifier = declaration.kind === 267 /* ModuleDeclaration */ ? tryCast(declaration.name, isStringLiteral) : getExternalModuleName(declaration); + const moduleSymbol = resolveExternalModuleNameWorker( + specifier, + specifier, + /*moduleNotFoundError*/ + void 0 + ); + if (!moduleSymbol) { + return void 0; + } + return getDeclarationOfKind(moduleSymbol, 307 /* SourceFile */); + } + function initializeTypeChecker() { + for (const file of host.getSourceFiles()) { + bindSourceFile(file, compilerOptions); + } + amalgamatedDuplicates = /* @__PURE__ */ new Map(); + let augmentations; + for (const file of host.getSourceFiles()) { + if (file.redirectInfo) { + continue; + } + if (!isExternalOrCommonJsModule(file)) { + const fileGlobalThisSymbol = file.locals.get("globalThis"); + if (fileGlobalThisSymbol == null ? void 0 : fileGlobalThisSymbol.declarations) { + for (const declaration of fileGlobalThisSymbol.declarations) { + diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); + } + } + mergeSymbolTable(globals, file.locals); + } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + const source = file.symbol.globalExports; + source.forEach((sourceSymbol, id) => { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + if (augmentations) { + for (const list of augmentations) { + for (const augmentation of list) { + if (!isGlobalScopeAugmentation(augmentation.parent)) continue; + mergeModuleAugmentation(augmentation); + } + } + } + addUndefinedToGlobalsOrErrorOnRedeclaration(); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType( + "IArguments", + /*arity*/ + 0, + /*reportErrors*/ + true + ); + getSymbolLinks(unknownSymbol).type = errorType; + getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol); + globalArrayType = getGlobalType( + "Array", + /*arity*/ + 1, + /*reportErrors*/ + true + ); + globalObjectType = getGlobalType( + "Object", + /*arity*/ + 0, + /*reportErrors*/ + true + ); + globalFunctionType = getGlobalType( + "Function", + /*arity*/ + 0, + /*reportErrors*/ + true + ); + globalCallableFunctionType = strictBindCallApply && getGlobalType( + "CallableFunction", + /*arity*/ + 0, + /*reportErrors*/ + true + ) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType( + "NewableFunction", + /*arity*/ + 0, + /*reportErrors*/ + true + ) || globalFunctionType; + globalStringType = getGlobalType( + "String", + /*arity*/ + 0, + /*reportErrors*/ + true + ); + globalNumberType = getGlobalType( + "Number", + /*arity*/ + 0, + /*reportErrors*/ + true + ); + globalBooleanType = getGlobalType( + "Boolean", + /*arity*/ + 0, + /*reportErrors*/ + true + ); + globalRegExpType = getGlobalType( + "RegExp", + /*arity*/ + 0, + /*reportErrors*/ + true + ); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + if (autoArrayType === emptyObjectType) { + autoArrayType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + } + globalReadonlyArrayType = getGlobalTypeOrUndefined( + "ReadonlyArray", + /*arity*/ + 1 + ) || globalArrayType; + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined( + "ThisType", + /*arity*/ + 1 + ); + if (augmentations) { + for (const list of augmentations) { + for (const augmentation of list) { + if (isGlobalScopeAugmentation(augmentation.parent)) continue; + mergeModuleAugmentation(augmentation); + } + } + } + amalgamatedDuplicates.forEach(({ firstFile, secondFile, conflictingSymbols }) => { + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(({ isBlockScoped, firstFileLocations, secondFileLocations }, symbolName2) => { + const message = isBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; + for (const node of firstFileLocations) { + addDuplicateDeclarationError(node, message, symbolName2, secondFileLocations); + } + for (const node of secondFileLocations) { + addDuplicateDeclarationError(node, message, symbolName2, firstFileLocations); + } + }); + } else { + const list = arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo( + createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), + createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file) + )); + diagnostics.add(addRelatedInfo( + createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), + createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file) + )); + } + }); + amalgamatedDuplicates = void 0; + } + function checkExternalEmitHelpers(location, helpers) { + if (compilerOptions.importHelpers) { + const sourceFile = getSourceFileOfNode(location); + if (isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 33554432 /* Ambient */)) { + const helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + const links = getSymbolLinks(helpersModule); + links.requestedExternalEmitHelpers ?? (links.requestedExternalEmitHelpers = 0); + if ((links.requestedExternalEmitHelpers & helpers) !== helpers) { + const uncheckedHelpers = helpers & ~links.requestedExternalEmitHelpers; + for (let helper = 1 /* FirstEmitHelper */; helper <= 16777216 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + for (const name of getHelperNames(helper)) { + const symbol = resolveSymbol(getSymbol(getExportsOfModule(helpersModule), escapeLeadingUnderscores(name), 111551 /* Value */)); + if (!symbol) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name); + } else if (helper & 524288 /* ClassPrivateFieldGet */) { + if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 3)) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4); + } + } else if (helper & 1048576 /* ClassPrivateFieldSet */) { + if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 4)) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5); + } + } else if (helper & 1024 /* SpreadArray */) { + if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 2)) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3); + } + } + } + } + } + } + links.requestedExternalEmitHelpers |= helpers; + } + } + } + } + function getHelperNames(helper) { + switch (helper) { + case 1 /* Extends */: + return ["__extends"]; + case 2 /* Assign */: + return ["__assign"]; + case 4 /* Rest */: + return ["__rest"]; + case 8 /* Decorate */: + return legacyDecorators ? ["__decorate"] : ["__esDecorate", "__runInitializers"]; + case 16 /* Metadata */: + return ["__metadata"]; + case 32 /* Param */: + return ["__param"]; + case 64 /* Awaiter */: + return ["__awaiter"]; + case 128 /* Generator */: + return ["__generator"]; + case 256 /* Values */: + return ["__values"]; + case 512 /* Read */: + return ["__read"]; + case 1024 /* SpreadArray */: + return ["__spreadArray"]; + case 2048 /* Await */: + return ["__await"]; + case 4096 /* AsyncGenerator */: + return ["__asyncGenerator"]; + case 8192 /* AsyncDelegator */: + return ["__asyncDelegator"]; + case 16384 /* AsyncValues */: + return ["__asyncValues"]; + case 32768 /* ExportStar */: + return ["__exportStar"]; + case 65536 /* ImportStar */: + return ["__importStar"]; + case 131072 /* ImportDefault */: + return ["__importDefault"]; + case 262144 /* MakeTemplateObject */: + return ["__makeTemplateObject"]; + case 524288 /* ClassPrivateFieldGet */: + return ["__classPrivateFieldGet"]; + case 1048576 /* ClassPrivateFieldSet */: + return ["__classPrivateFieldSet"]; + case 2097152 /* ClassPrivateFieldIn */: + return ["__classPrivateFieldIn"]; + case 4194304 /* SetFunctionName */: + return ["__setFunctionName"]; + case 8388608 /* PropKey */: + return ["__propKey"]; + case 16777216 /* AddDisposableResourceAndDisposeResources */: + return ["__addDisposableResource", "__disposeResources"]; + case 33554432 /* RewriteRelativeImportExtension */: + return ["__rewriteRelativeImportExtension"]; + default: + return Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(file, errorNode) { + const links = getNodeLinks(file); + if (!links.externalHelpersModule) { + links.externalHelpersModule = resolveExternalModule(getImportHelpersImportSpecifier(file), externalHelpersModuleNameText, Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return links.externalHelpersModule; + } + function checkGrammarModifiers(node) { + var _a; + const quickResult = reportObviousDecoratorErrors(node) || reportObviousModifierErrors(node); + if (quickResult !== void 0) { + return quickResult; + } + if (isParameter(node) && parameterIsThisKeyword(node)) { + return grammarErrorOnFirstToken(node, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters); + } + const blockScopeKind = isVariableStatement(node) ? node.declarationList.flags & 7 /* BlockScoped */ : 0 /* None */; + let lastStatic, lastDeclare, lastAsync, lastOverride, firstDecorator; + let flags = 0 /* None */; + let sawExportBeforeDecorators = false; + let hasLeadingDecorators = false; + for (const modifier of node.modifiers) { + if (isDecorator(modifier)) { + if (!nodeCanBeDecorated(legacyDecorators, node, node.parent, node.parent.parent)) { + if (node.kind === 174 /* MethodDeclaration */ && !nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } else { + return grammarErrorOnFirstToken(node, Diagnostics.Decorators_are_not_valid_here); + } + } else if (legacyDecorators && (node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */)) { + const accessors = getAllAccessorDeclarationsForDeclaration(node); + if (hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + if (flags & ~(2080 /* ExportDefault */ | 32768 /* Decorator */)) { + return grammarErrorOnNode(modifier, Diagnostics.Decorators_are_not_valid_here); + } + if (hasLeadingDecorators && flags & 98303 /* Modifier */) { + Debug.assertIsDefined(firstDecorator); + const sourceFile = getSourceFileOfNode(modifier); + if (!hasParseDiagnostics(sourceFile)) { + addRelatedInfo( + error(modifier, Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export), + createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here) + ); + return true; + } + return false; + } + flags |= 32768 /* Decorator */; + if (!(flags & 98303 /* Modifier */)) { + hasLeadingDecorators = true; + } else if (flags & 32 /* Export */) { + sawExportBeforeDecorators = true; + } + firstDecorator ?? (firstDecorator = modifier); + } else { + if (modifier.kind !== 148 /* ReadonlyKeyword */) { + if (node.kind === 171 /* PropertySignature */ || node.kind === 173 /* MethodSignature */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_member, tokenToString(modifier.kind)); + } + if (node.kind === 181 /* IndexSignature */ && (modifier.kind !== 126 /* StaticKeyword */ || !isClassLike(node.parent))) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_index_signature, tokenToString(modifier.kind)); + } + } + if (modifier.kind !== 103 /* InKeyword */ && modifier.kind !== 147 /* OutKeyword */ && modifier.kind !== 87 /* ConstKeyword */) { + if (node.kind === 168 /* TypeParameter */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_parameter, tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 87 /* ConstKeyword */: { + if (node.kind !== 266 /* EnumDeclaration */ && node.kind !== 168 /* TypeParameter */) { + return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(87 /* ConstKeyword */)); + } + const parent = isJSDocTemplateTag(node.parent) && getEffectiveJSDocHost(node.parent) || node.parent; + if (node.kind === 168 /* TypeParameter */ && !(isFunctionLikeDeclaration(parent) || isClassLike(parent) || isFunctionTypeNode(parent) || isConstructorTypeNode(parent) || isCallSignatureDeclaration(parent) || isConstructSignatureDeclaration(parent) || isMethodSignature(parent))) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class, tokenToString(modifier.kind)); + } + break; + } + case 164 /* OverrideKeyword */: + if (flags & 16 /* Override */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "override"); + } else if (flags & 128 /* Ambient */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); + } else if (flags & 8 /* Readonly */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); + } else if (flags & 512 /* Accessor */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "accessor"); + } else if (flags & 1024 /* Async */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); + } + flags |= 16 /* Override */; + lastOverride = modifier; + break; + case 125 /* PublicKeyword */: + case 124 /* ProtectedKeyword */: + case 123 /* PrivateKeyword */: + const text = visibilityToString(modifierToFlag(modifier.kind)); + if (flags & 7 /* AccessibilityModifier */) { + return grammarErrorOnNode(modifier, Diagnostics.Accessibility_modifier_already_seen); + } else if (flags & 16 /* Override */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); + } else if (flags & 256 /* Static */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } else if (flags & 512 /* Accessor */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "accessor"); + } else if (flags & 8 /* Readonly */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } else if (flags & 1024 /* Async */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } else if (flags & 64 /* Abstract */) { + if (modifier.kind === 123 /* PrivateKeyword */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } else { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } else if (isPrivateIdentifierClassElementDeclaration(node)) { + return grammarErrorOnNode(modifier, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); + } + flags |= modifierToFlag(modifier.kind); + break; + case 126 /* StaticKeyword */: + if (flags & 256 /* Static */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "static"); + } else if (flags & 8 /* Readonly */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } else if (flags & 1024 /* Async */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } else if (flags & 512 /* Accessor */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "accessor"); + } else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } else if (node.kind === 169 /* Parameter */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } else if (flags & 64 /* Abstract */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } else if (flags & 16 /* Override */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); + } + flags |= 256 /* Static */; + lastStatic = modifier; + break; + case 129 /* AccessorKeyword */: + if (flags & 512 /* Accessor */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "accessor"); + } else if (flags & 8 /* Readonly */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "readonly"); + } else if (flags & 128 /* Ambient */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "declare"); + } else if (node.kind !== 172 /* PropertyDeclaration */) { + return grammarErrorOnNode(modifier, Diagnostics.accessor_modifier_can_only_appear_on_a_property_declaration); + } + flags |= 512 /* Accessor */; + break; + case 148 /* ReadonlyKeyword */: + if (flags & 8 /* Readonly */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly"); + } else if (node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 171 /* PropertySignature */ && node.kind !== 181 /* IndexSignature */ && node.kind !== 169 /* Parameter */) { + return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } else if (flags & 512 /* Accessor */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "readonly", "accessor"); + } + flags |= 8 /* Readonly */; + break; + case 95 /* ExportKeyword */: + if (compilerOptions.verbatimModuleSyntax && !(node.flags & 33554432 /* Ambient */) && node.kind !== 265 /* TypeAliasDeclaration */ && node.kind !== 264 /* InterfaceDeclaration */ && // ModuleDeclaration needs to be checked that it is uninstantiated later + node.kind !== 267 /* ModuleDeclaration */ && node.parent.kind === 307 /* SourceFile */ && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) { + return grammarErrorOnNode(modifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + } + if (flags & 32 /* Export */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "export"); + } else if (flags & 128 /* Ambient */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } else if (flags & 64 /* Abstract */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } else if (flags & 1024 /* Async */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } else if (isClassLike(node.parent)) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); + } else if (node.kind === 169 /* Parameter */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } else if (blockScopeKind === 4 /* Using */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "export"); + } else if (blockScopeKind === 6 /* AwaitUsing */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "export"); + } + flags |= 32 /* Export */; + break; + case 90 /* DefaultKeyword */: + const container = node.parent.kind === 307 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 267 /* ModuleDeclaration */ && !isAmbientModule(container)) { + return grammarErrorOnNode(modifier, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } else if (blockScopeKind === 4 /* Using */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "default"); + } else if (blockScopeKind === 6 /* AwaitUsing */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "default"); + } else if (!(flags & 32 /* Export */)) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "default"); + } else if (sawExportBeforeDecorators) { + return grammarErrorOnNode(firstDecorator, Diagnostics.Decorators_are_not_valid_here); + } + flags |= 2048 /* Default */; + break; + case 138 /* DeclareKeyword */: + if (flags & 128 /* Ambient */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "declare"); + } else if (flags & 1024 /* Async */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } else if (flags & 16 /* Override */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); + } else if (isClassLike(node.parent) && !isPropertyDeclaration(node)) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); + } else if (node.kind === 169 /* Parameter */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } else if (blockScopeKind === 4 /* Using */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "declare"); + } else if (blockScopeKind === 6 /* AwaitUsing */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "declare"); + } else if (node.parent.flags & 33554432 /* Ambient */ && node.parent.kind === 268 /* ModuleBlock */) { + return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } else if (isPrivateIdentifierClassElementDeclaration(node)) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); + } else if (flags & 512 /* Accessor */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "declare", "accessor"); + } + flags |= 128 /* Ambient */; + lastDeclare = modifier; + break; + case 128 /* AbstractKeyword */: + if (flags & 64 /* Abstract */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 263 /* ClassDeclaration */ && node.kind !== 185 /* ConstructorType */) { + if (node.kind !== 174 /* MethodDeclaration */ && node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 177 /* GetAccessor */ && node.kind !== 178 /* SetAccessor */) { + return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 263 /* ClassDeclaration */ && hasSyntacticModifier(node.parent, 64 /* Abstract */))) { + const message = node.kind === 172 /* PropertyDeclaration */ ? Diagnostics.Abstract_properties_can_only_appear_within_an_abstract_class : Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class; + return grammarErrorOnNode(modifier, message); + } + if (flags & 256 /* Static */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 2 /* Private */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + if (flags & 1024 /* Async */ && lastAsync) { + return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); + } + if (flags & 16 /* Override */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } + if (flags & 512 /* Accessor */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "accessor"); + } + } + if (isNamedDeclaration(node) && node.name.kind === 81 /* PrivateIdentifier */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); + } + flags |= 64 /* Abstract */; + break; + case 134 /* AsyncKeyword */: + if (flags & 1024 /* Async */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "async"); + } else if (flags & 128 /* Ambient */ || node.parent.flags & 33554432 /* Ambient */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } else if (node.kind === 169 /* Parameter */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + if (flags & 64 /* Abstract */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); + } + flags |= 1024 /* Async */; + lastAsync = modifier; + break; + case 103 /* InKeyword */: + case 147 /* OutKeyword */: { + const inOutFlag = modifier.kind === 103 /* InKeyword */ ? 8192 /* In */ : 16384 /* Out */; + const inOutText = modifier.kind === 103 /* InKeyword */ ? "in" : "out"; + const parent = isJSDocTemplateTag(node.parent) && (getEffectiveJSDocHost(node.parent) || find((_a = getJSDocRoot(node.parent)) == null ? void 0 : _a.tags, isJSDocTypedefTag)) || node.parent; + if (node.kind !== 168 /* TypeParameter */ || parent && !(isInterfaceDeclaration(parent) || isClassLike(parent) || isTypeAliasDeclaration(parent) || isJSDocTypedefTag(parent))) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText); + } + if (flags & inOutFlag) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, inOutText); + } + if (inOutFlag & 8192 /* In */ && flags & 16384 /* Out */) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "in", "out"); + } + flags |= inOutFlag; + break; + } + } + } + } + if (node.kind === 176 /* Constructor */) { + if (flags & 256 /* Static */) { + return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 16 /* Override */) { + return grammarErrorOnNode(lastOverride, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); + } + if (flags & 1024 /* Async */) { + return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + return false; + } else if ((node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */) && flags & 128 /* Ambient */) { + return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } else if (node.kind === 169 /* Parameter */ && flags & 31 /* ParameterPropertyModifier */ && isBindingPattern(node.name)) { + return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } else if (node.kind === 169 /* Parameter */ && flags & 31 /* ParameterPropertyModifier */ && node.dotDotDotToken) { + return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 1024 /* Async */) { + return checkGrammarAsyncModifier(node, lastAsync); + } + return false; + } + function reportObviousModifierErrors(node) { + if (!node.modifiers) return false; + const modifier = findFirstIllegalModifier(node); + return modifier && grammarErrorOnFirstToken(modifier, Diagnostics.Modifiers_cannot_appear_here); + } + function findFirstModifierExcept(node, allowedModifier) { + const modifier = find(node.modifiers, isModifier); + return modifier && modifier.kind !== allowedModifier ? modifier : void 0; + } + function findFirstIllegalModifier(node) { + switch (node.kind) { + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 176 /* Constructor */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 181 /* IndexSignature */: + case 267 /* ModuleDeclaration */: + case 272 /* ImportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 278 /* ExportDeclaration */: + case 277 /* ExportAssignment */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 169 /* Parameter */: + case 168 /* TypeParameter */: + return void 0; + case 175 /* ClassStaticBlockDeclaration */: + case 303 /* PropertyAssignment */: + case 304 /* ShorthandPropertyAssignment */: + case 270 /* NamespaceExportDeclaration */: + case 282 /* MissingDeclaration */: + return find(node.modifiers, isModifier); + default: + if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) { + return void 0; + } + switch (node.kind) { + case 262 /* FunctionDeclaration */: + return findFirstModifierExcept(node, 134 /* AsyncKeyword */); + case 263 /* ClassDeclaration */: + case 185 /* ConstructorType */: + return findFirstModifierExcept(node, 128 /* AbstractKeyword */); + case 231 /* ClassExpression */: + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + return find(node.modifiers, isModifier); + case 243 /* VariableStatement */: + return node.declarationList.flags & 4 /* Using */ ? findFirstModifierExcept(node, 135 /* AwaitKeyword */) : find(node.modifiers, isModifier); + case 266 /* EnumDeclaration */: + return findFirstModifierExcept(node, 87 /* ConstKeyword */); + default: + Debug.assertNever(node); + } + } + } + function reportObviousDecoratorErrors(node) { + const decorator = findFirstIllegalDecorator(node); + return decorator && grammarErrorOnFirstToken(decorator, Diagnostics.Decorators_are_not_valid_here); + } + function findFirstIllegalDecorator(node) { + return canHaveIllegalDecorators(node) ? find(node.modifiers, isDecorator) : void 0; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 174 /* MethodDeclaration */: + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + return false; + } + return grammarErrorOnNode(asyncModifier, Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list, diag2 = Diagnostics.Trailing_comma_not_allowed) { + if (list && list.hasTrailingComma) { + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag2); + } + return false; + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (typeParameters && typeParameters.length === 0) { + const start = typeParameters.pos - "<".length; + const end = skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, Diagnostics.Type_parameter_list_cannot_be_empty); + } + return false; + } + function checkGrammarParameterList(parameters) { + let seenOptionalParameter = false; + const parameterCount = parameters.length; + for (let i = 0; i < parameterCount; i++) { + const parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== parameterCount - 1) { + return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (!(parameter.flags & 33554432 /* Ambient */)) { + checkGrammarForDisallowedTrailingComma(parameters, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } else if (hasEffectiveQuestionToken(parameter)) { + seenOptionalParameter = true; + if (parameter.questionToken && parameter.initializer) { + return grammarErrorOnNode(parameter.name, Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function getNonSimpleParameters(parameters) { + return filter(parameters, (parameter) => !!parameter.initializer || isBindingPattern(parameter.name) || isRestParameter(parameter)); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + const useStrictDirective = node.body && isBlock(node.body) && findUseStrictPrologue(node.body.statements); + if (useStrictDirective) { + const nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (length(nonSimpleParameters)) { + forEach(nonSimpleParameters, (parameter) => { + addRelatedInfo( + error(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), + createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here) + ); + }); + const diagnostics2 = nonSimpleParameters.map((parameter, index) => index === 0 ? createDiagnosticForNode(parameter, Diagnostics.Non_simple_parameter_declared_here) : createDiagnosticForNode(parameter, Diagnostics.and_here)); + addRelatedInfo(error(useStrictDirective, Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list), ...diagnostics2); + return true; + } + } + } + return false; + } + function checkGrammarFunctionLikeDeclaration(node) { + const file = getSourceFileOfNode(node); + return checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node); + } + function checkGrammarClassLikeDeclaration(node) { + const file = getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (!isArrowFunction(node)) { + return false; + } + if (node.typeParameters && !(length(node.typeParameters) > 1 || node.typeParameters.hasTrailingComma || node.typeParameters[0].constraint)) { + if (file && fileExtensionIsOneOf(file.fileName, [".mts" /* Mts */, ".cts" /* Cts */])) { + grammarErrorOnNode(node.typeParameters[0], Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint); + } + } + const { equalsGreaterThanToken } = node; + const startLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line; + const endLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line; + return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, Diagnostics.Line_terminator_not_permitted_before_arrow); + } + function checkGrammarIndexSignatureParameters(node) { + const parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } else { + return grammarErrorOnNode(node, Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + checkGrammarForDisallowedTrailingComma(node.parameters, Diagnostics.An_index_signature_cannot_have_a_trailing_comma); + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (hasEffectiveModifiers(parameter)) { + return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + const type = getTypeFromTypeNode(parameter.type); + if (someType(type, (t) => !!(t.flags & 8576 /* StringOrNumberLiteralOrUnique */)) || isGenericType(type)) { + return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead); + } + if (!everyType(type, isValidIndexKeyType)) { + return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type); + } + if (!node.type) { + return grammarErrorOnNode(node, Diagnostics.An_index_signature_must_have_a_type_annotation); + } + return false; + } + function checkGrammarIndexSignature(node) { + return checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + const sourceFile = getSourceFileOfNode(node); + const start = typeArguments.pos - "<".length; + const end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Type_argument_list_cannot_be_empty); + } + return false; + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarTaggedTemplateChain(node) { + if (node.questionDotToken || node.flags & 64 /* OptionalChain */) { + return grammarErrorOnNode(node.template, Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain); + } + return false; + } + function checkGrammarHeritageClause(node) { + const types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + const listType = tokenToString(node.token); + return grammarErrorAtPos(node, types.pos, 0, Diagnostics._0_list_cannot_be_empty, listType); + } + return some(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + if (isExpressionWithTypeArguments(node) && isImportKeyword(node.expression) && node.typeArguments) { + return grammarErrorOnNode(node, Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments); + } + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + let seenExtendsClause = false; + let seenImplementsClause = false; + if (!checkGrammarModifiers(node) && node.heritageClauses) { + for (const heritageClause of node.heritageClauses) { + if (heritageClause.token === 96 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } else { + Debug.assert(heritageClause.token === 119 /* ImplementsKeyword */); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + let seenExtendsClause = false; + if (node.heritageClauses) { + for (const heritageClause of node.heritageClauses) { + if (heritageClause.token === 96 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } else { + Debug.assert(heritageClause.token === 119 /* ImplementsKeyword */); + return grammarErrorOnFirstToken(heritageClause, Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + if (node.kind !== 167 /* ComputedPropertyName */) { + return false; + } + const computedPropertyName = node; + if (computedPropertyName.expression.kind === 226 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 28 /* CommaToken */) { + return grammarErrorOnNode(computedPropertyName.expression, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + return false; + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + Debug.assert( + node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */ || node.kind === 174 /* MethodDeclaration */ + ); + if (node.flags & 33554432 /* Ambient */) { + return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + return !!questionToken && grammarErrorOnNode(questionToken, message); + } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + const seen = /* @__PURE__ */ new Map(); + for (const prop of node.properties) { + if (prop.kind === 305 /* SpreadAssignment */) { + if (inDestructuring) { + const expression = skipParentheses(prop.expression); + if (isArrayLiteralExpression(expression) || isObjectLiteralExpression(expression)) { + return grammarErrorOnNode(prop.expression, Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + } + continue; + } + const name = prop.name; + if (name.kind === 167 /* ComputedPropertyName */) { + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 304 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + grammarErrorOnNode(prop.equalsToken, Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); + } + if (name.kind === 81 /* PrivateIdentifier */) { + grammarErrorOnNode(name, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + if (canHaveModifiers(prop) && prop.modifiers) { + for (const mod of prop.modifiers) { + if (isModifier(mod) && (mod.kind !== 134 /* AsyncKeyword */ || prop.kind !== 174 /* MethodDeclaration */)) { + grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod)); + } + } + } else if (canHaveIllegalModifiers(prop) && prop.modifiers) { + for (const mod of prop.modifiers) { + if (isModifier(mod)) { + grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod)); + } + } + } + let currentKind; + switch (prop.kind) { + case 304 /* ShorthandPropertyAssignment */: + case 303 /* PropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + checkGrammarForInvalidQuestionMark(prop.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 9 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + if (name.kind === 10 /* BigIntLiteral */) { + addErrorOrSuggestion( + /*isError*/ + true, + createDiagnosticForNode(name, Diagnostics.A_bigint_literal_cannot_be_used_as_a_property_name) + ); + } + currentKind = 4 /* PropertyAssignment */; + break; + case 174 /* MethodDeclaration */: + currentKind = 8 /* Method */; + break; + case 177 /* GetAccessor */: + currentKind = 1 /* GetAccessor */; + break; + case 178 /* SetAccessor */: + currentKind = 2 /* SetAccessor */; + break; + default: + Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + } + if (!inDestructuring) { + const effectiveName = getEffectivePropertyNameForPropertyNameNode(name); + if (effectiveName === void 0) { + continue; + } + const existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } else { + if (currentKind & 8 /* Method */ && existingKind & 8 /* Method */) { + grammarErrorOnNode(name, Diagnostics.Duplicate_identifier_0, getTextOfNode(name)); + } else if (currentKind & 4 /* PropertyAssignment */ && existingKind & 4 /* PropertyAssignment */) { + grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name, getTextOfNode(name)); + } else if (currentKind & 3 /* GetOrSetAccessor */ && existingKind & 3 /* GetOrSetAccessor */) { + if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } else { + return grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } else { + return grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + } + function checkGrammarJsxElement(node) { + checkGrammarJsxName(node.tagName); + checkGrammarTypeArguments(node, node.typeArguments); + const seen = /* @__PURE__ */ new Map(); + for (const attr of node.attributes.properties) { + if (attr.kind === 293 /* JsxSpreadAttribute */) { + continue; + } + const { name, initializer } = attr; + const escapedText = getEscapedTextOfJsxAttributeName(name); + if (!seen.get(escapedText)) { + seen.set(escapedText, true); + } else { + return grammarErrorOnNode(name, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + if (initializer && initializer.kind === 294 /* JsxExpression */ && !initializer.expression) { + return grammarErrorOnNode(initializer, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarJsxName(node) { + if (isPropertyAccessExpression(node) && isJsxNamespacedName(node.expression)) { + return grammarErrorOnNode(node.expression, Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); + } + if (isJsxNamespacedName(node) && getJSXTransformEnabled(compilerOptions) && !isIntrinsicJsxName(node.namespace.escapedText)) { + return grammarErrorOnNode(node, Diagnostics.React_components_cannot_include_JSX_namespace_names); + } + } + function checkGrammarJsxExpression(node) { + if (node.expression && isCommaSequence(node.expression)) { + return grammarErrorOnNode(node.expression, Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array); + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 250 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (!(forInOrOfStatement.flags & 65536 /* AwaitContext */)) { + const sourceFile = getSourceFileOfNode(forInOrOfStatement); + if (isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + switch (moduleKind) { + case 100 /* Node16 */: + case 101 /* Node18 */: + case 199 /* NodeNext */: + if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) { + diagnostics.add( + createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level) + ); + break; + } + // fallthrough + case 7 /* ES2022 */: + case 99 /* ESNext */: + case 200 /* Preserve */: + case 4 /* System */: + if (languageVersion >= 4 /* ES2017 */) { + break; + } + // fallthrough + default: + diagnostics.add( + createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_node18_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher) + ); + break; + } + } + } else { + if (!hasParseDiagnostics(sourceFile)) { + const diagnostic = createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + const func = getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 176 /* Constructor */) { + Debug.assert((getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + const relatedInfo = createDiagnosticForNode(func, Diagnostics.Did_you_mean_to_mark_this_function_as_async); + addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } + } + } + } + if (isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & 65536 /* AwaitContext */) && isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async") { + grammarErrorOnNode(forInOrOfStatement.initializer, Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async); + return false; + } + if (forInOrOfStatement.initializer.kind === 261 /* VariableDeclarationList */) { + const variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + const declarations = variableList.declarations; + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + const diagnostic = forInOrOfStatement.kind === 249 /* ForInStatement */ ? Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + const firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + const diagnostic = forInOrOfStatement.kind === 249 /* ForInStatement */ ? Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + const diagnostic = forInOrOfStatement.kind === 249 /* ForInStatement */ ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + if (!(accessor.flags & 33554432 /* Ambient */) && accessor.parent.kind !== 187 /* TypeLiteral */ && accessor.parent.kind !== 264 /* InterfaceDeclaration */) { + if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(accessor.name)) { + return grammarErrorOnNode(accessor.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } + if (accessor.body === void 0 && !hasSyntacticModifier(accessor, 64 /* Abstract */)) { + return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, Diagnostics._0_expected, "{"); + } + } + if (accessor.body) { + if (hasSyntacticModifier(accessor, 64 /* Abstract */)) { + return grammarErrorOnNode(accessor, Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + if (accessor.parent.kind === 187 /* TypeLiteral */ || accessor.parent.kind === 264 /* InterfaceDeclaration */) { + return grammarErrorOnNode(accessor.body, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + } + if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_have_type_parameters); + } + if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode( + accessor.name, + accessor.kind === 177 /* GetAccessor */ ? Diagnostics.A_get_accessor_cannot_have_parameters : Diagnostics.A_set_accessor_must_have_exactly_one_parameter + ); + } + if (accessor.kind === 178 /* SetAccessor */) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + const parameter = Debug.checkDefined(getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion."); + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + return false; + } + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 177 /* GetAccessor */ ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 177 /* GetAccessor */ ? 1 : 2)) { + return getThisParameter(accessor); + } + } + function checkGrammarTypeOperatorNode(node) { + if (node.operator === 158 /* UniqueKeyword */) { + if (node.type.kind !== 155 /* SymbolKeyword */) { + return grammarErrorOnNode(node.type, Diagnostics._0_expected, tokenToString(155 /* SymbolKeyword */)); + } + let parent = walkUpParenthesizedTypes(node.parent); + if (isInJSFile(parent) && isJSDocTypeExpression(parent)) { + const host2 = getJSDocHost(parent); + if (host2) { + parent = getSingleVariableOfVariableStatement(host2) || host2; + } + } + switch (parent.kind) { + case 260 /* VariableDeclaration */: + const decl = parent; + if (decl.name.kind !== 80 /* Identifier */) { + return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); + } + if (!isVariableDeclarationInVariableStatement(decl)) { + return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); + } + if (!(decl.parent.flags & 2 /* Const */)) { + return grammarErrorOnNode(parent.name, Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + } + break; + case 172 /* PropertyDeclaration */: + if (!isStatic(parent) || !hasEffectiveReadonlyModifier(parent)) { + return grammarErrorOnNode(parent.name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + } + break; + case 171 /* PropertySignature */: + if (!hasSyntacticModifier(parent, 8 /* Readonly */)) { + return grammarErrorOnNode(parent.name, Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + } + break; + default: + return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_not_allowed_here); + } + } else if (node.operator === 148 /* ReadonlyKeyword */) { + if (node.type.kind !== 188 /* ArrayType */ && node.type.kind !== 189 /* TupleType */) { + return grammarErrorOnFirstToken(node, Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, tokenToString(155 /* SymbolKeyword */)); + } + } + } + function checkGrammarForInvalidDynamicName(node, message) { + if (isNonBindableDynamicName(node) && !isEntityNameExpression(isElementAccessExpression(node) ? skipParentheses(node.argumentExpression) : node.expression)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarFunctionLikeDeclaration(node)) { + return true; + } + if (node.kind === 174 /* MethodDeclaration */) { + if (node.parent.kind === 210 /* ObjectLiteralExpression */) { + if (node.modifiers && !(node.modifiers.length === 1 && first(node.modifiers).kind === 134 /* AsyncKeyword */)) { + return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here); + } else if (checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === void 0) { + return grammarErrorAtPos(node, node.end - 1, ";".length, Diagnostics._0_expected, "{"); + } + } + if (checkGrammarForGenerator(node)) { + return true; + } + } + if (isClassLike(node.parent)) { + if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(node.name)) { + return grammarErrorOnNode(node.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } + if (node.flags & 33554432 /* Ambient */) { + return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } else if (node.kind === 174 /* MethodDeclaration */ && !node.body) { + return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } else if (node.parent.kind === 264 /* InterfaceDeclaration */) { + return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } else if (node.parent.kind === 187 /* TypeLiteral */) { + return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); + } + } + function checkGrammarBreakOrContinueStatement(node) { + let current = node; + while (current) { + if (isFunctionLikeOrClassStaticBlockDeclaration(current)) { + return grammarErrorOnNode(node, Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 256 /* LabeledStatement */: + if (node.label && current.label.escapedText === node.label.escapedText) { + const isMisplacedContinueLabel = node.kind === 251 /* ContinueStatement */ && !isIterationStatement( + current.statement, + /*lookInLabeledStatements*/ + true + ); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 255 /* SwitchStatement */: + if (node.kind === 252 /* BreakStatement */ && !node.label) { + return false; + } + break; + default: + if (isIterationStatement( + current, + /*lookInLabeledStatements*/ + false + ) && !node.label) { + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + const message = node.kind === 252 /* BreakStatement */ ? Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } else { + const message = node.kind === 252 /* BreakStatement */ ? Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + const elements = node.parent.elements; + if (node !== last(elements)) { + return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + checkGrammarForDisallowedTrailingComma(elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (node.propertyName) { + return grammarErrorOnNode(node.name, Diagnostics.A_rest_element_cannot_have_a_property_name); + } + } + if (node.dotDotDotToken && node.initializer) { + return grammarErrorAtPos(node, node.initializer.pos - 1, 1, Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + function isStringOrNumberLiteralExpression(expr) { + return isStringOrNumericLiteralLike(expr) || expr.kind === 224 /* PrefixUnaryExpression */ && expr.operator === 41 /* MinusToken */ && expr.operand.kind === 9 /* NumericLiteral */; + } + function isBigIntLiteralExpression(expr) { + return expr.kind === 10 /* BigIntLiteral */ || expr.kind === 224 /* PrefixUnaryExpression */ && expr.operator === 41 /* MinusToken */ && expr.operand.kind === 10 /* BigIntLiteral */; + } + function isSimpleLiteralEnumReference(expr) { + if ((isPropertyAccessExpression(expr) || isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression)) && isEntityNameExpression(expr.expression)) { + return !!(checkExpressionCached(expr).flags & 1056 /* EnumLike */); + } + } + function checkAmbientInitializer(node) { + const initializer = node.initializer; + if (initializer) { + const isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || isSimpleLiteralEnumReference(initializer) || initializer.kind === 112 /* TrueKeyword */ || initializer.kind === 97 /* FalseKeyword */ || isBigIntLiteralExpression(initializer)); + const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike2(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } else { + return grammarErrorOnNode(initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } + function checkGrammarVariableDeclaration(node) { + const nodeFlags = getCombinedNodeFlagsCached(node); + const blockScopeKind = nodeFlags & 7 /* BlockScoped */; + if (isBindingPattern(node.name)) { + switch (blockScopeKind) { + case 6 /* AwaitUsing */: + return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "await using"); + case 4 /* Using */: + return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "using"); + } + } + if (node.parent.parent.kind !== 249 /* ForInStatement */ && node.parent.parent.kind !== 250 /* ForOfStatement */) { + if (nodeFlags & 33554432 /* Ambient */) { + checkAmbientInitializer(node); + } else if (!node.initializer) { + if (isBindingPattern(node.name) && !isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + switch (blockScopeKind) { + case 6 /* AwaitUsing */: + return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "await using"); + case 4 /* Using */: + return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "using"); + case 2 /* Const */: + return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "const"); + } + } + } + if (node.exclamationToken && (node.parent.parent.kind !== 243 /* VariableStatement */ || !node.type || node.initializer || nodeFlags & 33554432 /* Ambient */)) { + const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; + return grammarErrorOnNode(node.exclamationToken, message); + } + if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && !(node.parent.parent.flags & 33554432 /* Ambient */) && hasSyntacticModifier(node.parent.parent, 32 /* Export */)) { + checkESModuleMarker(node.name); + } + return !!blockScopeKind && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 80 /* Identifier */) { + if (idText(name) === "__esModule") { + return grammarErrorOnNodeSkippedOn("noEmit", name, Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } else { + const elements = name.elements; + for (const element of elements) { + if (!isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + return false; + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 80 /* Identifier */) { + if (name.escapedText === "let") { + return grammarErrorOnNode(name, Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } else { + const elements = name.elements; + for (const element of elements) { + if (!isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + return false; + } + function checkGrammarVariableDeclarationList(declarationList) { + const declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, Diagnostics.Variable_declaration_list_cannot_be_empty); + } + const blockScopeFlags = declarationList.flags & 7 /* BlockScoped */; + if ((blockScopeFlags === 4 /* Using */ || blockScopeFlags === 6 /* AwaitUsing */) && isForInStatement(declarationList.parent)) { + return grammarErrorOnNode( + declarationList, + blockScopeFlags === 4 /* Using */ ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration : Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration + ); + } + if (blockScopeFlags === 6 /* AwaitUsing */) { + return checkAwaitGrammar(declarationList); + } + return false; + } + function allowBlockDeclarations(parent) { + switch (parent.kind) { + case 245 /* IfStatement */: + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + case 254 /* WithStatement */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + return false; + case 256 /* LabeledStatement */: + return allowBlockDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedBlockScopedVariableStatement(node) { + if (!allowBlockDeclarations(node.parent)) { + const blockScopeKind = getCombinedNodeFlagsCached(node.declarationList) & 7 /* BlockScoped */; + if (blockScopeKind) { + const keyword = blockScopeKind === 1 /* Let */ ? "let" : blockScopeKind === 2 /* Const */ ? "const" : blockScopeKind === 4 /* Using */ ? "using" : blockScopeKind === 6 /* AwaitUsing */ ? "await using" : Debug.fail("Unknown BlockScope flag"); + return grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, keyword); + } + } + } + function checkGrammarMetaProperty(node) { + const escapedText = node.name.escapedText; + switch (node.keywordToken) { + case 105 /* NewKeyword */: + if (escapedText !== "target") { + return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "target"); + } + break; + case 102 /* ImportKeyword */: + if (escapedText !== "meta") { + return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "meta"); + } + break; + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, ...args) { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message, ...args)); + return true; + } + return false; + } + function grammarErrorAtPos(nodeForSourceFile, start, length2, message, ...args) { + const sourceFile = getSourceFileOfNode(nodeForSourceFile); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(createFileDiagnostic(sourceFile, start, length2, message, ...args)); + return true; + } + return false; + } + function grammarErrorOnNodeSkippedOn(key, node, message, ...args) { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + errorSkippedOn(key, node, message, ...args); + return true; + } + return false; + } + function grammarErrorOnNode(node, message, ...args) { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(createDiagnosticForNode(node, message, ...args)); + return true; + } + return false; + } + function checkGrammarConstructorTypeParameters(node) { + const jsdocTypeParameters = isInJSFile(node) ? getJSDocTypeParameterDeclarations(node) : void 0; + const range = node.typeParameters || jsdocTypeParameters && firstOrUndefined(jsdocTypeParameters); + if (range) { + const pos = range.pos === range.end ? range.pos : skipTrivia(getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + const type = node.type || getEffectiveReturnTypeNode(node); + if (type) { + return grammarErrorOnNode(type, Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (isComputedPropertyName(node.name) && isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 103 /* InKeyword */) { + return grammarErrorOnNode(node.parent.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } + if (isClassLike(node.parent)) { + if (isStringLiteral(node.name) && node.name.text === "constructor") { + return grammarErrorOnNode(node.name, Diagnostics.Classes_may_not_have_a_field_named_constructor); + } + if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) { + return true; + } + if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(node.name)) { + return grammarErrorOnNode(node.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } + if (languageVersion < 2 /* ES2015 */ && isAutoAccessorPropertyDeclaration(node)) { + return grammarErrorOnNode(node.name, Diagnostics.Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } + if (isAutoAccessorPropertyDeclaration(node) && checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_accessor_property_cannot_be_declared_optional)) { + return true; + } + } else if (node.parent.kind === 264 /* InterfaceDeclaration */) { + if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + Debug.assertNode(node, isPropertySignature); + if (node.initializer) { + return grammarErrorOnNode(node.initializer, Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } else if (isTypeLiteralNode(node.parent)) { + if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + return true; + } + Debug.assertNode(node, isPropertySignature); + if (node.initializer) { + return grammarErrorOnNode(node.initializer, Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (node.flags & 33554432 /* Ambient */) { + checkAmbientInitializer(node); + } + if (isPropertyDeclaration(node) && node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || node.flags & 33554432 /* Ambient */ || isStatic(node) || hasAbstractModifier(node))) { + const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; + return grammarErrorOnNode(node.exclamationToken, message); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + if (node.kind === 264 /* InterfaceDeclaration */ || node.kind === 265 /* TypeAliasDeclaration */ || node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 278 /* ExportDeclaration */ || node.kind === 277 /* ExportAssignment */ || node.kind === 270 /* NamespaceExportDeclaration */ || hasSyntacticModifier(node, 128 /* Ambient */ | 32 /* Export */ | 2048 /* Default */)) { + return false; + } + return grammarErrorOnFirstToken(node, Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (const decl of file.statements) { + if (isDeclaration(decl) || decl.kind === 243 /* VariableStatement */) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + return false; + } + function checkGrammarSourceFile(node) { + return !!(node.flags & 33554432 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (node.flags & 33554432 /* Ambient */) { + const links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && (isFunctionLike(node.parent) || isAccessor(node.parent))) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + if (node.parent.kind === 241 /* Block */ || node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) { + const links2 = getNodeLinks(node.parent); + if (!links2.hasReportedStatementInAmbientContext) { + return links2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } else { + } + } + return false; + } + function checkGrammarNumericLiteral(node) { + const isFractional = getTextOfNode(node).includes("."); + const isScientific = node.numericLiteralFlags & 16 /* Scientific */; + if (isFractional || isScientific) { + return; + } + const value = +node.text; + if (value <= 2 ** 53 - 1) { + return; + } + addErrorOrSuggestion( + /*isError*/ + false, + createDiagnosticForNode(node, Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers) + ); + } + function checkGrammarBigIntLiteral(node) { + const literalType = isLiteralTypeNode(node.parent) || isPrefixUnaryExpression(node.parent) && isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < 7 /* ES2020 */) { + if (grammarErrorOnNode(node, Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) { + return true; + } + } + } + return false; + } + function grammarErrorAfterFirstToken(node, message, ...args) { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(createFileDiagnostic( + sourceFile, + textSpanEnd(span), + /*length*/ + 0, + message, + ...args + )); + return true; + } + return false; + } + function getAmbientModules() { + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach((global2, sym) => { + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global2); + } + }); + } + return ambientModulesCache; + } + function checkGrammarImportClause(node) { + var _a; + if (node.isTypeOnly && node.name && node.namedBindings) { + return grammarErrorOnNode(node, Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both); + } + if (node.isTypeOnly && ((_a = node.namedBindings) == null ? void 0 : _a.kind) === 275 /* NamedImports */) { + return checkGrammarNamedImportsOrExports(node.namedBindings); + } + return false; + } + function checkGrammarNamedImportsOrExports(namedBindings) { + return !!forEach(namedBindings.elements, (specifier) => { + if (specifier.isTypeOnly) { + return grammarErrorOnFirstToken( + specifier, + specifier.kind === 276 /* ImportSpecifier */ ? Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement : Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement + ); + } + }); + } + function checkGrammarImportCallExpression(node) { + if (compilerOptions.verbatimModuleSyntax && moduleKind === 1 /* CommonJS */) { + return grammarErrorOnNode(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + } + if (moduleKind === 5 /* ES2015 */) { + return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node16_node18_or_nodenext); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments); + } + const nodeArguments = node.arguments; + if (!(100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) && moduleKind !== 99 /* ESNext */ && moduleKind !== 200 /* Preserve */) { + checkGrammarForDisallowedTrailingComma(nodeArguments); + if (nodeArguments.length > 1) { + const importAttributesArgument = nodeArguments[1]; + return grammarErrorOnNode(importAttributesArgument, Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_nodenext_or_preserve); + } + } + if (nodeArguments.length === 0 || nodeArguments.length > 2) { + return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments); + } + const spreadElement = find(nodeArguments, isSpreadElement); + if (spreadElement) { + return grammarErrorOnNode(spreadElement, Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element); + } + return false; + } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + const sourceObjectFlags = getObjectFlags(source); + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { + return find(unionTarget.types, (target) => { + if (target.flags & 524288 /* Object */) { + const overlapObjFlags = sourceObjectFlags & getObjectFlags(target); + if (overlapObjFlags & 4 /* Reference */) { + return source.target === target.target; + } + if (overlapObjFlags & 16 /* Anonymous */) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (getObjectFlags(source) & 128 /* ObjectLiteral */ && someType(unionTarget, isArrayLikeType)) { + return find(unionTarget.types, (t) => !isArrayLikeType(t)); + } + } + function findBestTypeForInvokable(source, unionTarget) { + let signatureKind = 0 /* Call */; + const hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return find(unionTarget.types, (t) => getSignaturesOfType(t, signatureKind).length > 0); + } + } + function findMostOverlappyType(source, unionTarget) { + let bestMatch; + if (!(source.flags & (402784252 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) { + let matchingCount = 0; + for (const target of unionTarget.types) { + if (!(target.flags & (402784252 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) { + const overlap = getIntersectionType([getIndexType(source), getIndexType(target)]); + if (overlap.flags & 4194304 /* Index */) { + return target; + } else if (isUnitType(overlap) || overlap.flags & 1048576 /* Union */) { + const len = overlap.flags & 1048576 /* Union */ ? countWhere(overlap.types, isUnitType) : 1; + if (len >= matchingCount) { + bestMatch = target; + matchingCount = len; + } + } + } + } + } + return bestMatch; + } + function filterPrimitivesIfContainsNonPrimitive(type) { + if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) { + const result = filterType(type, (t) => !(t.flags & 402784252 /* Primitive */)); + if (!(result.flags & 131072 /* Never */)) { + return result; + } + } + return type; + } + function findMatchingDiscriminantType(source, target, isRelatedTo) { + if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { + const match = getMatchingUnionConstituentForType(target, source); + if (match) { + return match; + } + const sourceProperties = getPropertiesOfType(source); + if (sourceProperties) { + const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + const discriminated = discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, (p) => [() => getTypeOfSymbol(p), p.escapedName]), isRelatedTo); + if (discriminated !== target) { + return discriminated; + } + } + } + } + return void 0; + } + function getEffectivePropertyNameForPropertyNameNode(node) { + const name = getPropertyNameForPropertyNameNode(node); + return name ? name : isComputedPropertyName(node) ? tryGetNameFromType(getTypeOfExpression(node.expression)) : void 0; + } + function getCombinedModifierFlagsCached(node) { + if (lastGetCombinedModifierFlagsNode === node) { + return lastGetCombinedModifierFlagsResult; + } + lastGetCombinedModifierFlagsNode = node; + lastGetCombinedModifierFlagsResult = getCombinedModifierFlags(node); + return lastGetCombinedModifierFlagsResult; + } + function getCombinedNodeFlagsCached(node) { + if (lastGetCombinedNodeFlagsNode === node) { + return lastGetCombinedNodeFlagsResult; + } + lastGetCombinedNodeFlagsNode = node; + lastGetCombinedNodeFlagsResult = getCombinedNodeFlags(node); + return lastGetCombinedNodeFlagsResult; + } + function isVarConstLike2(node) { + const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */; + return blockScopeKind === 2 /* Const */ || blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */; + } + function getJSXRuntimeImportSpecifier(file, specifierText) { + const jsxImportIndex = compilerOptions.importHelpers ? 1 : 0; + const specifier = file == null ? void 0 : file.imports[jsxImportIndex]; + if (specifier) { + Debug.assert(nodeIsSynthesized(specifier) && specifier.text === specifierText, `Expected sourceFile.imports[${jsxImportIndex}] to be the synthesized JSX runtime import`); + } + return specifier; + } + function getImportHelpersImportSpecifier(file) { + Debug.assert(compilerOptions.importHelpers, "Expected importHelpers to be enabled"); + const specifier = file.imports[0]; + Debug.assert(specifier && nodeIsSynthesized(specifier) && specifier.text === "tslib", `Expected sourceFile.imports[0] to be the synthesized tslib import`); + return specifier; + } +} +function isNotAccessor(declaration) { + return !isAccessor(declaration); +} +function isNotOverload(declaration) { + return declaration.kind !== 262 /* FunctionDeclaration */ && declaration.kind !== 174 /* MethodDeclaration */ || !!declaration.body; +} +function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 276 /* ImportSpecifier */: + case 281 /* ExportSpecifier */: + return isIdentifier(name) || name.kind === 11 /* StringLiteral */; + default: + return isDeclarationName(name); + } +} +var JsxNames; +((JsxNames2) => { + JsxNames2.JSX = "JSX"; + JsxNames2.IntrinsicElements = "IntrinsicElements"; + JsxNames2.ElementClass = "ElementClass"; + JsxNames2.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; + JsxNames2.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; + JsxNames2.Element = "Element"; + JsxNames2.ElementType = "ElementType"; + JsxNames2.IntrinsicAttributes = "IntrinsicAttributes"; + JsxNames2.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames2.LibraryManagedAttributes = "LibraryManagedAttributes"; +})(JsxNames || (JsxNames = {})); +var ReactNames; +((ReactNames2) => { + ReactNames2.Fragment = "Fragment"; +})(ReactNames || (ReactNames = {})); +function getIterationTypesKeyFromIterationTypeKind(typeKind) { + switch (typeKind) { + case 0 /* Yield */: + return "yieldType"; + case 1 /* Return */: + return "returnType"; + case 2 /* Next */: + return "nextType"; + } +} +function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); +} +function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); +} +function createBasicNodeBuilderModuleSpecifierResolutionHost(host) { + return { + getCommonSourceDirectory: !!host.getCommonSourceDirectory ? () => host.getCommonSourceDirectory() : () => "", + getCurrentDirectory: () => host.getCurrentDirectory(), + getSymlinkCache: maybeBind(host, host.getSymlinkCache), + getPackageJsonInfoCache: () => { + var _a; + return (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host); + }, + useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(), + redirectTargetsMap: host.redirectTargetsMap, + getProjectReferenceRedirect: (fileName) => host.getProjectReferenceRedirect(fileName), + isSourceOfProjectReferenceRedirect: (fileName) => host.isSourceOfProjectReferenceRedirect(fileName), + fileExists: (fileName) => host.fileExists(fileName), + getFileIncludeReasons: () => host.getFileIncludeReasons(), + readFile: host.readFile ? (fileName) => host.readFile(fileName) : void 0, + getDefaultResolutionModeForFile: (file) => host.getDefaultResolutionModeForFile(file), + getModeForResolutionAtIndex: (file, index) => host.getModeForResolutionAtIndex(file, index), + getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation) + }; +} +var SymbolTrackerImpl = class _SymbolTrackerImpl { + constructor(context, tracker, moduleResolverHost) { + this.moduleResolverHost = void 0; + this.inner = void 0; + this.disableTrackSymbol = false; + var _a; + while (tracker instanceof _SymbolTrackerImpl) { + tracker = tracker.inner; + } + this.inner = tracker; + this.moduleResolverHost = moduleResolverHost; + this.context = context; + this.canTrackSymbol = !!((_a = this.inner) == null ? void 0 : _a.trackSymbol); + } + trackSymbol(symbol, enclosingDeclaration, meaning) { + var _a, _b; + if (((_a = this.inner) == null ? void 0 : _a.trackSymbol) && !this.disableTrackSymbol) { + if (this.inner.trackSymbol(symbol, enclosingDeclaration, meaning)) { + this.onDiagnosticReported(); + return true; + } + if (!(symbol.flags & 262144 /* TypeParameter */)) ((_b = this.context).trackedSymbols ?? (_b.trackedSymbols = [])).push([symbol, enclosingDeclaration, meaning]); + } + return false; + } + reportInaccessibleThisError() { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportInaccessibleThisError) { + this.onDiagnosticReported(); + this.inner.reportInaccessibleThisError(); + } + } + reportPrivateInBaseOfClassExpression(propertyName) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportPrivateInBaseOfClassExpression) { + this.onDiagnosticReported(); + this.inner.reportPrivateInBaseOfClassExpression(propertyName); + } + } + reportInaccessibleUniqueSymbolError() { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportInaccessibleUniqueSymbolError) { + this.onDiagnosticReported(); + this.inner.reportInaccessibleUniqueSymbolError(); + } + } + reportCyclicStructureError() { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportCyclicStructureError) { + this.onDiagnosticReported(); + this.inner.reportCyclicStructureError(); + } + } + reportLikelyUnsafeImportRequiredError(specifier) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportLikelyUnsafeImportRequiredError) { + this.onDiagnosticReported(); + this.inner.reportLikelyUnsafeImportRequiredError(specifier); + } + } + reportTruncationError() { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportTruncationError) { + this.onDiagnosticReported(); + this.inner.reportTruncationError(); + } + } + reportNonlocalAugmentation(containingFile, parentSymbol, augmentingSymbol) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportNonlocalAugmentation) { + this.onDiagnosticReported(); + this.inner.reportNonlocalAugmentation(containingFile, parentSymbol, augmentingSymbol); + } + } + reportNonSerializableProperty(propertyName) { + var _a; + if ((_a = this.inner) == null ? void 0 : _a.reportNonSerializableProperty) { + this.onDiagnosticReported(); + this.inner.reportNonSerializableProperty(propertyName); + } + } + onDiagnosticReported() { + this.context.reportedDiagnostic = true; + } + reportInferenceFallback(node) { + var _a; + if (((_a = this.inner) == null ? void 0 : _a.reportInferenceFallback) && !this.context.suppressReportInferenceFallback) { + this.onDiagnosticReported(); + this.inner.reportInferenceFallback(node); + } + } + pushErrorFallbackNode(node) { + var _a, _b; + return (_b = (_a = this.inner) == null ? void 0 : _a.pushErrorFallbackNode) == null ? void 0 : _b.call(_a, node); + } + popErrorFallbackNode() { + var _a, _b; + return (_b = (_a = this.inner) == null ? void 0 : _a.popErrorFallbackNode) == null ? void 0 : _b.call(_a); + } +}; + +// src/compiler/visitorPublic.ts +function visitNode(node, visitor, test, lift) { + if (node === void 0) { + return node; + } + const visited = visitor(node); + let visitedNode; + if (visited === void 0) { + return void 0; + } else if (isArray(visited)) { + visitedNode = (lift || extractSingleNode)(visited); + } else { + visitedNode = visited; + } + Debug.assertNode(visitedNode, test); + return visitedNode; +} +function visitNodes2(nodes, visitor, test, start, count) { + if (nodes === void 0) { + return nodes; + } + const length2 = nodes.length; + if (start === void 0 || start < 0) { + start = 0; + } + if (count === void 0 || count > length2 - start) { + count = length2 - start; + } + let hasTrailingComma; + let pos = -1; + let end = -1; + if (start > 0 || count < length2) { + hasTrailingComma = nodes.hasTrailingComma && start + count === length2; + } else { + pos = nodes.pos; + end = nodes.end; + hasTrailingComma = nodes.hasTrailingComma; + } + const updated = visitArrayWorker(nodes, visitor, test, start, count); + if (updated !== nodes) { + const updatedArray = factory.createNodeArray(updated, hasTrailingComma); + setTextRangePosEnd(updatedArray, pos, end); + return updatedArray; + } + return nodes; +} +function visitArray(nodes, visitor, test, start, count) { + if (nodes === void 0) { + return nodes; + } + const length2 = nodes.length; + if (start === void 0 || start < 0) { + start = 0; + } + if (count === void 0 || count > length2 - start) { + count = length2 - start; + } + return visitArrayWorker(nodes, visitor, test, start, count); +} +function visitArrayWorker(nodes, visitor, test, start, count) { + let updated; + const length2 = nodes.length; + if (start > 0 || count < length2) { + updated = []; + } + for (let i = 0; i < count; i++) { + const node = nodes[i + start]; + const visited = node !== void 0 ? visitor ? visitor(node) : node : void 0; + if (updated !== void 0 || visited === void 0 || visited !== node) { + if (updated === void 0) { + updated = nodes.slice(0, i); + Debug.assertEachNode(updated, test); + } + if (visited) { + if (isArray(visited)) { + for (const visitedNode of visited) { + Debug.assertNode(visitedNode, test); + updated.push(visitedNode); + } + } else { + Debug.assertNode(visited, test); + updated.push(visited); + } + } + } + } + if (updated) { + return updated; + } + Debug.assertEachNode(nodes, test); + return nodes; +} +function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict, nodesVisitor = visitNodes2) { + context.startLexicalEnvironment(); + statements = nodesVisitor(statements, visitor, isStatement, start); + if (ensureUseStrict) statements = context.factory.ensureUseStrict(statements); + return factory.mergeLexicalEnvironment(statements, context.endLexicalEnvironment()); +} +function visitParameterList(nodes, visitor, context, nodesVisitor = visitNodes2) { + let updated; + context.startLexicalEnvironment(); + if (nodes) { + context.setLexicalEnvironmentFlags(1 /* InParameters */, true); + updated = nodesVisitor(nodes, visitor, isParameter); + if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ && getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) { + updated = addDefaultValueAssignmentsIfNeeded(updated, context); + } + context.setLexicalEnvironmentFlags(1 /* InParameters */, false); + } + context.suspendLexicalEnvironment(); + return updated; +} +function addDefaultValueAssignmentsIfNeeded(parameters, context) { + let result; + for (let i = 0; i < parameters.length; i++) { + const parameter = parameters[i]; + const updated = addDefaultValueAssignmentIfNeeded(parameter, context); + if (result || updated !== parameter) { + if (!result) result = parameters.slice(0, i); + result[i] = updated; + } + } + if (result) { + return setTextRange(context.factory.createNodeArray(result, parameters.hasTrailingComma), parameters); + } + return parameters; +} +function addDefaultValueAssignmentIfNeeded(parameter, context) { + return parameter.dotDotDotToken ? parameter : isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : parameter; +} +function addDefaultValueAssignmentForBindingPattern(parameter, context) { + const { factory: factory2 } = context; + context.addInitializationStatement( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + parameter.name, + /*exclamationToken*/ + void 0, + parameter.type, + parameter.initializer ? factory2.createConditionalExpression( + factory2.createStrictEquality( + factory2.getGeneratedNameForNode(parameter), + factory2.createVoidZero() + ), + /*questionToken*/ + void 0, + parameter.initializer, + /*colonToken*/ + void 0, + factory2.getGeneratedNameForNode(parameter) + ) : factory2.getGeneratedNameForNode(parameter) + ) + ]) + ) + ); + return factory2.updateParameterDeclaration( + parameter, + parameter.modifiers, + parameter.dotDotDotToken, + factory2.getGeneratedNameForNode(parameter), + parameter.questionToken, + parameter.type, + /*initializer*/ + void 0 + ); +} +function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { + const factory2 = context.factory; + context.addInitializationStatement( + factory2.createIfStatement( + factory2.createTypeCheck(factory2.cloneNode(name), "undefined"), + setEmitFlags( + setTextRange( + factory2.createBlock([ + factory2.createExpressionStatement( + setEmitFlags( + setTextRange( + factory2.createAssignment( + setEmitFlags(factory2.cloneNode(name), 96 /* NoSourceMap */), + setEmitFlags(initializer, 96 /* NoSourceMap */ | getEmitFlags(initializer) | 3072 /* NoComments */) + ), + parameter + ), + 3072 /* NoComments */ + ) + ) + ]), + parameter + ), + 1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */ + ) + ) + ); + return factory2.updateParameterDeclaration( + parameter, + parameter.modifiers, + parameter.dotDotDotToken, + parameter.name, + parameter.questionToken, + parameter.type, + /*initializer*/ + void 0 + ); +} +function visitFunctionBody(node, visitor, context, nodeVisitor = visitNode) { + context.resumeLexicalEnvironment(); + const updated = nodeVisitor(node, visitor, isConciseBody); + const declarations = context.endLexicalEnvironment(); + if (some(declarations)) { + if (!updated) { + return context.factory.createBlock(declarations); + } + const block = context.factory.converters.convertToFunctionBlock(updated); + const statements = factory.mergeLexicalEnvironment(block.statements, declarations); + return context.factory.updateBlock(block, statements); + } + return updated; +} +function visitIterationBody(body, visitor, context, nodeVisitor = visitNode) { + context.startBlockScope(); + const updated = nodeVisitor(body, visitor, isStatement, context.factory.liftToBlock); + Debug.assert(updated); + const declarations = context.endBlockScope(); + if (some(declarations)) { + if (isBlock(updated)) { + declarations.push(...updated.statements); + return context.factory.updateBlock(updated, declarations); + } + declarations.push(updated); + return context.factory.createBlock(declarations); + } + return updated; +} +function visitCommaListElements(elements, visitor, discardVisitor = visitor) { + if (discardVisitor === visitor || elements.length <= 1) { + return visitNodes2(elements, visitor, isExpression); + } + let i = 0; + const length2 = elements.length; + return visitNodes2(elements, (node) => { + const discarded = i < length2 - 1; + i++; + return discarded ? discardVisitor(node) : visitor(node); + }, isExpression); +} +function visitEachChild(node, visitor, context = nullTransformationContext, nodesVisitor = visitNodes2, tokenVisitor, nodeVisitor = visitNode) { + if (node === void 0) { + return void 0; + } + const fn = visitEachChildTable[node.kind]; + return fn === void 0 ? node : fn(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor); +} +var visitEachChildTable = { + [166 /* QualifiedName */]: function visitEachChildOfQualifiedName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateQualifiedName( + node, + Debug.checkDefined(nodeVisitor(node.left, visitor, isEntityName)), + Debug.checkDefined(nodeVisitor(node.right, visitor, isIdentifier)) + ); + }, + [167 /* ComputedPropertyName */]: function visitEachChildOfComputedPropertyName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateComputedPropertyName( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + // Signature elements + [168 /* TypeParameter */]: function visitEachChildOfTypeParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeParameterDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifier), + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + nodeVisitor(node.constraint, visitor, isTypeNode), + nodeVisitor(node.default, visitor, isTypeNode) + ); + }, + [169 /* Parameter */]: function visitEachChildOfParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateParameterDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, + Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), + tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, + nodeVisitor(node.type, visitor, isTypeNode), + nodeVisitor(node.initializer, visitor, isExpression) + ); + }, + [170 /* Decorator */]: function visitEachChildOfDecorator(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateDecorator( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + // Type elements + [171 /* PropertySignature */]: function visitEachChildOfPropertySignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updatePropertySignature( + node, + nodesVisitor(node.modifiers, visitor, isModifier), + Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), + tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, + nodeVisitor(node.type, visitor, isTypeNode) + ); + }, + [172 /* PropertyDeclaration */]: function visitEachChildOfPropertyDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updatePropertyDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), + // QuestionToken and ExclamationToken are mutually exclusive in PropertyDeclaration + tokenVisitor ? nodeVisitor(node.questionToken ?? node.exclamationToken, tokenVisitor, isQuestionOrExclamationToken) : node.questionToken ?? node.exclamationToken, + nodeVisitor(node.type, visitor, isTypeNode), + nodeVisitor(node.initializer, visitor, isExpression) + ); + }, + [173 /* MethodSignature */]: function visitEachChildOfMethodSignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateMethodSignature( + node, + nodesVisitor(node.modifiers, visitor, isModifier), + Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), + tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameter), + nodeVisitor(node.type, visitor, isTypeNode) + ); + }, + [174 /* MethodDeclaration */]: function visitEachChildOfMethodDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateMethodDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, + Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), + tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + visitFunctionBody(node.body, visitor, context, nodeVisitor) + ); + }, + [176 /* Constructor */]: function visitEachChildOfConstructorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateConstructorDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + visitFunctionBody(node.body, visitor, context, nodeVisitor) + ); + }, + [177 /* GetAccessor */]: function visitEachChildOfGetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateGetAccessorDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + visitFunctionBody(node.body, visitor, context, nodeVisitor) + ); + }, + [178 /* SetAccessor */]: function visitEachChildOfSetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSetAccessorDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + visitFunctionBody(node.body, visitor, context, nodeVisitor) + ); + }, + [175 /* ClassStaticBlockDeclaration */]: function visitEachChildOfClassStaticBlockDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + context.startLexicalEnvironment(); + context.suspendLexicalEnvironment(); + return context.factory.updateClassStaticBlockDeclaration( + node, + visitFunctionBody(node.body, visitor, context, nodeVisitor) + ); + }, + [179 /* CallSignature */]: function visitEachChildOfCallSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateCallSignature( + node, + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameter), + nodeVisitor(node.type, visitor, isTypeNode) + ); + }, + [180 /* ConstructSignature */]: function visitEachChildOfConstructSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateConstructSignature( + node, + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameter), + nodeVisitor(node.type, visitor, isTypeNode) + ); + }, + [181 /* IndexSignature */]: function visitEachChildOfIndexSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateIndexSignature( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + nodesVisitor(node.parameters, visitor, isParameter), + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + // Types + [182 /* TypePredicate */]: function visitEachChildOfTypePredicateNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypePredicateNode( + node, + nodeVisitor(node.assertsModifier, visitor, isAssertsKeyword), + Debug.checkDefined(nodeVisitor(node.parameterName, visitor, isIdentifierOrThisTypeNode)), + nodeVisitor(node.type, visitor, isTypeNode) + ); + }, + [183 /* TypeReference */]: function visitEachChildOfTypeReferenceNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeReferenceNode( + node, + Debug.checkDefined(nodeVisitor(node.typeName, visitor, isEntityName)), + nodesVisitor(node.typeArguments, visitor, isTypeNode) + ); + }, + [184 /* FunctionType */]: function visitEachChildOfFunctionTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateFunctionTypeNode( + node, + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameter), + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [185 /* ConstructorType */]: function visitEachChildOfConstructorTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateConstructorTypeNode( + node, + nodesVisitor(node.modifiers, visitor, isModifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameter), + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [186 /* TypeQuery */]: function visitEachChildOfTypeQueryNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeQueryNode( + node, + Debug.checkDefined(nodeVisitor(node.exprName, visitor, isEntityName)), + nodesVisitor(node.typeArguments, visitor, isTypeNode) + ); + }, + [187 /* TypeLiteral */]: function visitEachChildOfTypeLiteralNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeLiteralNode( + node, + nodesVisitor(node.members, visitor, isTypeElement) + ); + }, + [188 /* ArrayType */]: function visitEachChildOfArrayTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateArrayTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.elementType, visitor, isTypeNode)) + ); + }, + [189 /* TupleType */]: function visitEachChildOfTupleTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateTupleTypeNode( + node, + nodesVisitor(node.elements, visitor, isTypeNode) + ); + }, + [190 /* OptionalType */]: function visitEachChildOfOptionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateOptionalTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [191 /* RestType */]: function visitEachChildOfRestTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateRestTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [192 /* UnionType */]: function visitEachChildOfUnionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateUnionTypeNode( + node, + nodesVisitor(node.types, visitor, isTypeNode) + ); + }, + [193 /* IntersectionType */]: function visitEachChildOfIntersectionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateIntersectionTypeNode( + node, + nodesVisitor(node.types, visitor, isTypeNode) + ); + }, + [194 /* ConditionalType */]: function visitEachChildOfConditionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateConditionalTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.checkType, visitor, isTypeNode)), + Debug.checkDefined(nodeVisitor(node.extendsType, visitor, isTypeNode)), + Debug.checkDefined(nodeVisitor(node.trueType, visitor, isTypeNode)), + Debug.checkDefined(nodeVisitor(node.falseType, visitor, isTypeNode)) + ); + }, + [195 /* InferType */]: function visitEachChildOfInferTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateInferTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)) + ); + }, + [205 /* ImportType */]: function visitEachChildOfImportTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.argument, visitor, isTypeNode)), + nodeVisitor(node.attributes, visitor, isImportAttributes), + nodeVisitor(node.qualifier, visitor, isEntityName), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + node.isTypeOf + ); + }, + [302 /* ImportTypeAssertionContainer */]: function visitEachChildOfImportTypeAssertionContainer(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportTypeAssertionContainer( + node, + Debug.checkDefined(nodeVisitor(node.assertClause, visitor, isAssertClause)), + node.multiLine + ); + }, + [202 /* NamedTupleMember */]: function visitEachChildOfNamedTupleMember(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateNamedTupleMember( + node, + tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [196 /* ParenthesizedType */]: function visitEachChildOfParenthesizedType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateParenthesizedType( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [198 /* TypeOperator */]: function visitEachChildOfTypeOperatorNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeOperatorNode( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [199 /* IndexedAccessType */]: function visitEachChildOfIndexedAccessType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateIndexedAccessTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.objectType, visitor, isTypeNode)), + Debug.checkDefined(nodeVisitor(node.indexType, visitor, isTypeNode)) + ); + }, + [200 /* MappedType */]: function visitEachChildOfMappedType(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateMappedTypeNode( + node, + tokenVisitor ? nodeVisitor(node.readonlyToken, tokenVisitor, isReadonlyKeywordOrPlusOrMinusToken) : node.readonlyToken, + Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)), + nodeVisitor(node.nameType, visitor, isTypeNode), + tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionOrPlusOrMinusToken) : node.questionToken, + nodeVisitor(node.type, visitor, isTypeNode), + nodesVisitor(node.members, visitor, isTypeElement) + ); + }, + [201 /* LiteralType */]: function visitEachChildOfLiteralTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateLiteralTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.literal, visitor, isLiteralTypeLiteral)) + ); + }, + [203 /* TemplateLiteralType */]: function visitEachChildOfTemplateLiteralType(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTemplateLiteralType( + node, + Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), + nodesVisitor(node.templateSpans, visitor, isTemplateLiteralTypeSpan) + ); + }, + [204 /* TemplateLiteralTypeSpan */]: function visitEachChildOfTemplateLiteralTypeSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTemplateLiteralTypeSpan( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail)) + ); + }, + // Binding patterns + [206 /* ObjectBindingPattern */]: function visitEachChildOfObjectBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateObjectBindingPattern( + node, + nodesVisitor(node.elements, visitor, isBindingElement) + ); + }, + [207 /* ArrayBindingPattern */]: function visitEachChildOfArrayBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateArrayBindingPattern( + node, + nodesVisitor(node.elements, visitor, isArrayBindingElement) + ); + }, + [208 /* BindingElement */]: function visitEachChildOfBindingElement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateBindingElement( + node, + tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, + nodeVisitor(node.propertyName, visitor, isPropertyName), + Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), + nodeVisitor(node.initializer, visitor, isExpression) + ); + }, + // Expression + [209 /* ArrayLiteralExpression */]: function visitEachChildOfArrayLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateArrayLiteralExpression( + node, + nodesVisitor(node.elements, visitor, isExpression) + ); + }, + [210 /* ObjectLiteralExpression */]: function visitEachChildOfObjectLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateObjectLiteralExpression( + node, + nodesVisitor(node.properties, visitor, isObjectLiteralElementLike) + ); + }, + [211 /* PropertyAccessExpression */]: function visitEachChildOfPropertyAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return isPropertyAccessChain(node) ? context.factory.updatePropertyAccessChain( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, + Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName)) + ) : context.factory.updatePropertyAccessExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName)) + ); + }, + [212 /* ElementAccessExpression */]: function visitEachChildOfElementAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return isElementAccessChain(node) ? context.factory.updateElementAccessChain( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, + Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression)) + ) : context.factory.updateElementAccessExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression)) + ); + }, + [213 /* CallExpression */]: function visitEachChildOfCallExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return isCallChain(node) ? context.factory.updateCallChain( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, + nodesVisitor(node.typeArguments, visitor, isTypeNode), + nodesVisitor(node.arguments, visitor, isExpression) + ) : context.factory.updateCallExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + nodesVisitor(node.arguments, visitor, isExpression) + ); + }, + [214 /* NewExpression */]: function visitEachChildOfNewExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateNewExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + nodesVisitor(node.arguments, visitor, isExpression) + ); + }, + [215 /* TaggedTemplateExpression */]: function visitEachChildOfTaggedTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTaggedTemplateExpression( + node, + Debug.checkDefined(nodeVisitor(node.tag, visitor, isExpression)), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + Debug.checkDefined(nodeVisitor(node.template, visitor, isTemplateLiteral)) + ); + }, + [216 /* TypeAssertionExpression */]: function visitEachChildOfTypeAssertionExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeAssertion( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [217 /* ParenthesizedExpression */]: function visitEachChildOfParenthesizedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateParenthesizedExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [218 /* FunctionExpression */]: function visitEachChildOfFunctionExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateFunctionExpression( + node, + nodesVisitor(node.modifiers, visitor, isModifier), + tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + visitFunctionBody(node.body, visitor, context, nodeVisitor) + ); + }, + [219 /* ArrowFunction */]: function visitEachChildOfArrowFunction(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateArrowFunction( + node, + nodesVisitor(node.modifiers, visitor, isModifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + tokenVisitor ? Debug.checkDefined(nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, isEqualsGreaterThanToken)) : node.equalsGreaterThanToken, + visitFunctionBody(node.body, visitor, context, nodeVisitor) + ); + }, + [220 /* DeleteExpression */]: function visitEachChildOfDeleteExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateDeleteExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [221 /* TypeOfExpression */]: function visitEachChildOfTypeOfExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeOfExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [222 /* VoidExpression */]: function visitEachChildOfVoidExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateVoidExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [223 /* AwaitExpression */]: function visitEachChildOfAwaitExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateAwaitExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [224 /* PrefixUnaryExpression */]: function visitEachChildOfPrefixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updatePrefixUnaryExpression( + node, + Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression)) + ); + }, + [225 /* PostfixUnaryExpression */]: function visitEachChildOfPostfixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updatePostfixUnaryExpression( + node, + Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression)) + ); + }, + [226 /* BinaryExpression */]: function visitEachChildOfBinaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateBinaryExpression( + node, + Debug.checkDefined(nodeVisitor(node.left, visitor, isExpression)), + tokenVisitor ? Debug.checkDefined(nodeVisitor(node.operatorToken, tokenVisitor, isBinaryOperatorToken)) : node.operatorToken, + Debug.checkDefined(nodeVisitor(node.right, visitor, isExpression)) + ); + }, + [227 /* ConditionalExpression */]: function visitEachChildOfConditionalExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateConditionalExpression( + node, + Debug.checkDefined(nodeVisitor(node.condition, visitor, isExpression)), + tokenVisitor ? Debug.checkDefined(nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken)) : node.questionToken, + Debug.checkDefined(nodeVisitor(node.whenTrue, visitor, isExpression)), + tokenVisitor ? Debug.checkDefined(nodeVisitor(node.colonToken, tokenVisitor, isColonToken)) : node.colonToken, + Debug.checkDefined(nodeVisitor(node.whenFalse, visitor, isExpression)) + ); + }, + [228 /* TemplateExpression */]: function visitEachChildOfTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTemplateExpression( + node, + Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), + nodesVisitor(node.templateSpans, visitor, isTemplateSpan) + ); + }, + [229 /* YieldExpression */]: function visitEachChildOfYieldExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateYieldExpression( + node, + tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, + nodeVisitor(node.expression, visitor, isExpression) + ); + }, + [230 /* SpreadElement */]: function visitEachChildOfSpreadElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSpreadElement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [231 /* ClassExpression */]: function visitEachChildOfClassExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateClassExpression( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.heritageClauses, visitor, isHeritageClause), + nodesVisitor(node.members, visitor, isClassElement) + ); + }, + [233 /* ExpressionWithTypeArguments */]: function visitEachChildOfExpressionWithTypeArguments(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExpressionWithTypeArguments( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + nodesVisitor(node.typeArguments, visitor, isTypeNode) + ); + }, + [234 /* AsExpression */]: function visitEachChildOfAsExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateAsExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [238 /* SatisfiesExpression */]: function visitEachChildOfSatisfiesExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSatisfiesExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [235 /* NonNullExpression */]: function visitEachChildOfNonNullExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return isOptionalChain(node) ? context.factory.updateNonNullChain( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ) : context.factory.updateNonNullExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [236 /* MetaProperty */]: function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateMetaProperty( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) + ); + }, + // Misc + [239 /* TemplateSpan */]: function visitEachChildOfTemplateSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTemplateSpan( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail)) + ); + }, + // Element + [241 /* Block */]: function visitEachChildOfBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateBlock( + node, + nodesVisitor(node.statements, visitor, isStatement) + ); + }, + [243 /* VariableStatement */]: function visitEachChildOfVariableStatement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateVariableStatement( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + Debug.checkDefined(nodeVisitor(node.declarationList, visitor, isVariableDeclarationList)) + ); + }, + [244 /* ExpressionStatement */]: function visitEachChildOfExpressionStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExpressionStatement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [245 /* IfStatement */]: function visitEachChildOfIfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateIfStatement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + Debug.checkDefined(nodeVisitor(node.thenStatement, visitor, isStatement, context.factory.liftToBlock)), + nodeVisitor(node.elseStatement, visitor, isStatement, context.factory.liftToBlock) + ); + }, + [246 /* DoStatement */]: function visitEachChildOfDoStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateDoStatement( + node, + visitIterationBody(node.statement, visitor, context, nodeVisitor), + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [247 /* WhileStatement */]: function visitEachChildOfWhileStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateWhileStatement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + visitIterationBody(node.statement, visitor, context, nodeVisitor) + ); + }, + [248 /* ForStatement */]: function visitEachChildOfForStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateForStatement( + node, + nodeVisitor(node.initializer, visitor, isForInitializer), + nodeVisitor(node.condition, visitor, isExpression), + nodeVisitor(node.incrementor, visitor, isExpression), + visitIterationBody(node.statement, visitor, context, nodeVisitor) + ); + }, + [249 /* ForInStatement */]: function visitEachChildOfForInStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateForInStatement( + node, + Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + visitIterationBody(node.statement, visitor, context, nodeVisitor) + ); + }, + [250 /* ForOfStatement */]: function visitEachChildOfForOfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateForOfStatement( + node, + tokenVisitor ? nodeVisitor(node.awaitModifier, tokenVisitor, isAwaitKeyword) : node.awaitModifier, + Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + visitIterationBody(node.statement, visitor, context, nodeVisitor) + ); + }, + [251 /* ContinueStatement */]: function visitEachChildOfContinueStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateContinueStatement( + node, + nodeVisitor(node.label, visitor, isIdentifier) + ); + }, + [252 /* BreakStatement */]: function visitEachChildOfBreakStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateBreakStatement( + node, + nodeVisitor(node.label, visitor, isIdentifier) + ); + }, + [253 /* ReturnStatement */]: function visitEachChildOfReturnStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateReturnStatement( + node, + nodeVisitor(node.expression, visitor, isExpression) + ); + }, + [254 /* WithStatement */]: function visitEachChildOfWithStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateWithStatement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock)) + ); + }, + [255 /* SwitchStatement */]: function visitEachChildOfSwitchStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSwitchStatement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + Debug.checkDefined(nodeVisitor(node.caseBlock, visitor, isCaseBlock)) + ); + }, + [256 /* LabeledStatement */]: function visitEachChildOfLabeledStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateLabeledStatement( + node, + Debug.checkDefined(nodeVisitor(node.label, visitor, isIdentifier)), + Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock)) + ); + }, + [257 /* ThrowStatement */]: function visitEachChildOfThrowStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateThrowStatement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [258 /* TryStatement */]: function visitEachChildOfTryStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTryStatement( + node, + Debug.checkDefined(nodeVisitor(node.tryBlock, visitor, isBlock)), + nodeVisitor(node.catchClause, visitor, isCatchClause), + nodeVisitor(node.finallyBlock, visitor, isBlock) + ); + }, + [260 /* VariableDeclaration */]: function visitEachChildOfVariableDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateVariableDeclaration( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), + tokenVisitor ? nodeVisitor(node.exclamationToken, tokenVisitor, isExclamationToken) : node.exclamationToken, + nodeVisitor(node.type, visitor, isTypeNode), + nodeVisitor(node.initializer, visitor, isExpression) + ); + }, + [261 /* VariableDeclarationList */]: function visitEachChildOfVariableDeclarationList(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateVariableDeclarationList( + node, + nodesVisitor(node.declarations, visitor, isVariableDeclaration) + ); + }, + [262 /* FunctionDeclaration */]: function visitEachChildOfFunctionDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { + return context.factory.updateFunctionDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifier), + tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + visitFunctionBody(node.body, visitor, context, nodeVisitor) + ); + }, + [263 /* ClassDeclaration */]: function visitEachChildOfClassDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateClassDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.heritageClauses, visitor, isHeritageClause), + nodesVisitor(node.members, visitor, isClassElement) + ); + }, + [264 /* InterfaceDeclaration */]: function visitEachChildOfInterfaceDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateInterfaceDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.heritageClauses, visitor, isHeritageClause), + nodesVisitor(node.members, visitor, isTypeElement) + ); + }, + [265 /* TypeAliasDeclaration */]: function visitEachChildOfTypeAliasDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateTypeAliasDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) + ); + }, + [266 /* EnumDeclaration */]: function visitEachChildOfEnumDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateEnumDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + nodesVisitor(node.members, visitor, isEnumMember) + ); + }, + [267 /* ModuleDeclaration */]: function visitEachChildOfModuleDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateModuleDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleName)), + nodeVisitor(node.body, visitor, isModuleBody) + ); + }, + [268 /* ModuleBlock */]: function visitEachChildOfModuleBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateModuleBlock( + node, + nodesVisitor(node.statements, visitor, isStatement) + ); + }, + [269 /* CaseBlock */]: function visitEachChildOfCaseBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateCaseBlock( + node, + nodesVisitor(node.clauses, visitor, isCaseOrDefaultClause) + ); + }, + [270 /* NamespaceExportDeclaration */]: function visitEachChildOfNamespaceExportDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateNamespaceExportDeclaration( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) + ); + }, + [271 /* ImportEqualsDeclaration */]: function visitEachChildOfImportEqualsDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportEqualsDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + node.isTypeOnly, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + Debug.checkDefined(nodeVisitor(node.moduleReference, visitor, isModuleReference)) + ); + }, + [272 /* ImportDeclaration */]: function visitEachChildOfImportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + nodeVisitor(node.importClause, visitor, isImportClause), + Debug.checkDefined(nodeVisitor(node.moduleSpecifier, visitor, isExpression)), + nodeVisitor(node.attributes, visitor, isImportAttributes) + ); + }, + [300 /* ImportAttributes */]: function visitEachChildOfImportAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateImportAttributes( + node, + nodesVisitor(node.elements, visitor, isImportAttribute), + node.multiLine + ); + }, + [301 /* ImportAttribute */]: function visitEachChildOfImportAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportAttribute( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isImportAttributeName)), + Debug.checkDefined(nodeVisitor(node.value, visitor, isExpression)) + ); + }, + [273 /* ImportClause */]: function visitEachChildOfImportClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportClause( + node, + node.isTypeOnly, + nodeVisitor(node.name, visitor, isIdentifier), + nodeVisitor(node.namedBindings, visitor, isNamedImportBindings) + ); + }, + [274 /* NamespaceImport */]: function visitEachChildOfNamespaceImport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateNamespaceImport( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) + ); + }, + [280 /* NamespaceExport */]: function visitEachChildOfNamespaceExport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateNamespaceExport( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) + ); + }, + [275 /* NamedImports */]: function visitEachChildOfNamedImports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateNamedImports( + node, + nodesVisitor(node.elements, visitor, isImportSpecifier) + ); + }, + [276 /* ImportSpecifier */]: function visitEachChildOfImportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportSpecifier( + node, + node.isTypeOnly, + nodeVisitor(node.propertyName, visitor, isModuleExportName), + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) + ); + }, + [277 /* ExportAssignment */]: function visitEachChildOfExportAssignment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExportAssignment( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [278 /* ExportDeclaration */]: function visitEachChildOfExportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExportDeclaration( + node, + nodesVisitor(node.modifiers, visitor, isModifierLike), + node.isTypeOnly, + nodeVisitor(node.exportClause, visitor, isNamedExportBindings), + nodeVisitor(node.moduleSpecifier, visitor, isExpression), + nodeVisitor(node.attributes, visitor, isImportAttributes) + ); + }, + [279 /* NamedExports */]: function visitEachChildOfNamedExports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateNamedExports( + node, + nodesVisitor(node.elements, visitor, isExportSpecifier) + ); + }, + [281 /* ExportSpecifier */]: function visitEachChildOfExportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExportSpecifier( + node, + node.isTypeOnly, + nodeVisitor(node.propertyName, visitor, isModuleExportName), + Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleExportName)) + ); + }, + // Module references + [283 /* ExternalModuleReference */]: function visitEachChildOfExternalModuleReference(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateExternalModuleReference( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + // JSX + [284 /* JsxElement */]: function visitEachChildOfJsxElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxElement( + node, + Debug.checkDefined(nodeVisitor(node.openingElement, visitor, isJsxOpeningElement)), + nodesVisitor(node.children, visitor, isJsxChild), + Debug.checkDefined(nodeVisitor(node.closingElement, visitor, isJsxClosingElement)) + ); + }, + [285 /* JsxSelfClosingElement */]: function visitEachChildOfJsxSelfClosingElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxSelfClosingElement( + node, + Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes)) + ); + }, + [286 /* JsxOpeningElement */]: function visitEachChildOfJsxOpeningElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxOpeningElement( + node, + Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes)) + ); + }, + [287 /* JsxClosingElement */]: function visitEachChildOfJsxClosingElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxClosingElement( + node, + Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)) + ); + }, + [295 /* JsxNamespacedName */]: function forEachChildInJsxNamespacedName2(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxNamespacedName( + node, + Debug.checkDefined(nodeVisitor(node.namespace, visitor, isIdentifier)), + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) + ); + }, + [288 /* JsxFragment */]: function visitEachChildOfJsxFragment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxFragment( + node, + Debug.checkDefined(nodeVisitor(node.openingFragment, visitor, isJsxOpeningFragment)), + nodesVisitor(node.children, visitor, isJsxChild), + Debug.checkDefined(nodeVisitor(node.closingFragment, visitor, isJsxClosingFragment)) + ); + }, + [291 /* JsxAttribute */]: function visitEachChildOfJsxAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxAttribute( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isJsxAttributeName)), + nodeVisitor(node.initializer, visitor, isStringLiteralOrJsxExpression) + ); + }, + [292 /* JsxAttributes */]: function visitEachChildOfJsxAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxAttributes( + node, + nodesVisitor(node.properties, visitor, isJsxAttributeLike) + ); + }, + [293 /* JsxSpreadAttribute */]: function visitEachChildOfJsxSpreadAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxSpreadAttribute( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [294 /* JsxExpression */]: function visitEachChildOfJsxExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateJsxExpression( + node, + nodeVisitor(node.expression, visitor, isExpression) + ); + }, + // Clauses + [296 /* CaseClause */]: function visitEachChildOfCaseClause(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateCaseClause( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + nodesVisitor(node.statements, visitor, isStatement) + ); + }, + [297 /* DefaultClause */]: function visitEachChildOfDefaultClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateDefaultClause( + node, + nodesVisitor(node.statements, visitor, isStatement) + ); + }, + [298 /* HeritageClause */]: function visitEachChildOfHeritageClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateHeritageClause( + node, + nodesVisitor(node.types, visitor, isExpressionWithTypeArguments) + ); + }, + [299 /* CatchClause */]: function visitEachChildOfCatchClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateCatchClause( + node, + nodeVisitor(node.variableDeclaration, visitor, isVariableDeclaration), + Debug.checkDefined(nodeVisitor(node.block, visitor, isBlock)) + ); + }, + // Property assignments + [303 /* PropertyAssignment */]: function visitEachChildOfPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updatePropertyAssignment( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), + Debug.checkDefined(nodeVisitor(node.initializer, visitor, isExpression)) + ); + }, + [304 /* ShorthandPropertyAssignment */]: function visitEachChildOfShorthandPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateShorthandPropertyAssignment( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + nodeVisitor(node.objectAssignmentInitializer, visitor, isExpression) + ); + }, + [305 /* SpreadAssignment */]: function visitEachChildOfSpreadAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateSpreadAssignment( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + // Enum + [306 /* EnumMember */]: function visitEachChildOfEnumMember(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateEnumMember( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), + nodeVisitor(node.initializer, visitor, isExpression) + ); + }, + // Top-level nodes + [307 /* SourceFile */]: function visitEachChildOfSourceFile(node, visitor, context, _nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateSourceFile( + node, + visitLexicalEnvironment(node.statements, visitor, context) + ); + }, + // Transformation nodes + [355 /* PartiallyEmittedExpression */]: function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updatePartiallyEmittedExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) + ); + }, + [356 /* CommaListExpression */]: function visitEachChildOfCommaListExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + return context.factory.updateCommaListExpression( + node, + nodesVisitor(node.elements, visitor, isExpression) + ); + } +}; +function extractSingleNode(nodes) { + Debug.assert(nodes.length <= 1, "Too many nodes written to output."); + return singleOrUndefined(nodes); +} + +// src/compiler/sourcemap.ts +function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { + var { enter, exit } = generatorOptions.extendedDiagnostics ? createTimer("Source Map", "beforeSourcemap", "afterSourcemap") : nullTimer; + var rawSources = []; + var sources = []; + var sourceToSourceIndexMap = /* @__PURE__ */ new Map(); + var sourcesContent; + var names = []; + var nameToNameIndexMap; + var mappingCharCodes = []; + var mappings = ""; + var lastGeneratedLine = 0; + var lastGeneratedCharacter = 0; + var lastSourceIndex = 0; + var lastSourceLine = 0; + var lastSourceCharacter = 0; + var lastNameIndex = 0; + var hasLast = false; + var pendingGeneratedLine = 0; + var pendingGeneratedCharacter = 0; + var pendingSourceIndex = 0; + var pendingSourceLine = 0; + var pendingSourceCharacter = 0; + var pendingNameIndex = 0; + var hasPending = false; + var hasPendingSource = false; + var hasPendingName = false; + return { + getSources: () => rawSources, + addSource, + setSourceContent, + addName, + addMapping, + appendSourceMap, + toJSON, + toString: () => JSON.stringify(toJSON()) + }; + function addSource(fileName) { + enter(); + const source = getRelativePathToDirectoryOrUrl( + sourcesDirectoryPath, + fileName, + host.getCurrentDirectory(), + host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ + true + ); + let sourceIndex = sourceToSourceIndexMap.get(source); + if (sourceIndex === void 0) { + sourceIndex = sources.length; + sources.push(source); + rawSources.push(fileName); + sourceToSourceIndexMap.set(source, sourceIndex); + } + exit(); + return sourceIndex; + } + function setSourceContent(sourceIndex, content) { + enter(); + if (content !== null) { + if (!sourcesContent) sourcesContent = []; + while (sourcesContent.length < sourceIndex) { + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = content; + } + exit(); + } + function addName(name) { + enter(); + if (!nameToNameIndexMap) nameToNameIndexMap = /* @__PURE__ */ new Map(); + let nameIndex = nameToNameIndexMap.get(name); + if (nameIndex === void 0) { + nameIndex = names.length; + names.push(name); + nameToNameIndexMap.set(name, nameIndex); + } + exit(); + return nameIndex; + } + function isNewGeneratedPosition(generatedLine, generatedCharacter) { + return !hasPending || pendingGeneratedLine !== generatedLine || pendingGeneratedCharacter !== generatedCharacter; + } + function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) { + return sourceIndex !== void 0 && sourceLine !== void 0 && sourceCharacter !== void 0 && pendingSourceIndex === sourceIndex && (pendingSourceLine > sourceLine || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter); + } + function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) { + Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + Debug.assert(sourceIndex === void 0 || sourceIndex >= 0, "sourceIndex cannot be negative"); + Debug.assert(sourceLine === void 0 || sourceLine >= 0, "sourceLine cannot be negative"); + Debug.assert(sourceCharacter === void 0 || sourceCharacter >= 0, "sourceCharacter cannot be negative"); + enter(); + if (isNewGeneratedPosition(generatedLine, generatedCharacter) || isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + commitPendingMapping(); + pendingGeneratedLine = generatedLine; + pendingGeneratedCharacter = generatedCharacter; + hasPendingSource = false; + hasPendingName = false; + hasPending = true; + } + if (sourceIndex !== void 0 && sourceLine !== void 0 && sourceCharacter !== void 0) { + pendingSourceIndex = sourceIndex; + pendingSourceLine = sourceLine; + pendingSourceCharacter = sourceCharacter; + hasPendingSource = true; + if (nameIndex !== void 0) { + pendingNameIndex = nameIndex; + hasPendingName = true; + } + } + exit(); + } + function appendSourceMap(generatedLine, generatedCharacter, map2, sourceMapPath, start, end) { + Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); + Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); + enter(); + const sourceIndexToNewSourceIndexMap = []; + let nameIndexToNewNameIndexMap; + const mappingIterator = decodeMappings(map2.mappings); + for (const raw of mappingIterator) { + if (end && (raw.generatedLine > end.line || raw.generatedLine === end.line && raw.generatedCharacter > end.character)) { + break; + } + if (start && (raw.generatedLine < start.line || start.line === raw.generatedLine && raw.generatedCharacter < start.character)) { + continue; + } + let newSourceIndex; + let newSourceLine; + let newSourceCharacter; + let newNameIndex; + if (raw.sourceIndex !== void 0) { + newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex]; + if (newSourceIndex === void 0) { + const rawPath = map2.sources[raw.sourceIndex]; + const relativePath = map2.sourceRoot ? combinePaths(map2.sourceRoot, rawPath) : rawPath; + const combinedPath = combinePaths(getDirectoryPath(sourceMapPath), relativePath); + sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath); + if (map2.sourcesContent && typeof map2.sourcesContent[raw.sourceIndex] === "string") { + setSourceContent(newSourceIndex, map2.sourcesContent[raw.sourceIndex]); + } + } + newSourceLine = raw.sourceLine; + newSourceCharacter = raw.sourceCharacter; + if (map2.names && raw.nameIndex !== void 0) { + if (!nameIndexToNewNameIndexMap) nameIndexToNewNameIndexMap = []; + newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; + if (newNameIndex === void 0) { + nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map2.names[raw.nameIndex]); + } + } + } + const rawGeneratedLine = raw.generatedLine - (start ? start.line : 0); + const newGeneratedLine = rawGeneratedLine + generatedLine; + const rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter; + const newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter; + addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); + } + exit(); + } + function shouldCommitMapping() { + return !hasLast || lastGeneratedLine !== pendingGeneratedLine || lastGeneratedCharacter !== pendingGeneratedCharacter || lastSourceIndex !== pendingSourceIndex || lastSourceLine !== pendingSourceLine || lastSourceCharacter !== pendingSourceCharacter || lastNameIndex !== pendingNameIndex; + } + function appendMappingCharCode(charCode) { + mappingCharCodes.push(charCode); + if (mappingCharCodes.length >= 1024) { + flushMappingBuffer(); + } + } + function commitPendingMapping() { + if (!hasPending || !shouldCommitMapping()) { + return; + } + enter(); + if (lastGeneratedLine < pendingGeneratedLine) { + do { + appendMappingCharCode(59 /* semicolon */); + lastGeneratedLine++; + } while (lastGeneratedLine < pendingGeneratedLine); + lastGeneratedCharacter = 0; + } else { + Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); + if (hasLast) { + appendMappingCharCode(44 /* comma */); + } + } + appendBase64VLQ(pendingGeneratedCharacter - lastGeneratedCharacter); + lastGeneratedCharacter = pendingGeneratedCharacter; + if (hasPendingSource) { + appendBase64VLQ(pendingSourceIndex - lastSourceIndex); + lastSourceIndex = pendingSourceIndex; + appendBase64VLQ(pendingSourceLine - lastSourceLine); + lastSourceLine = pendingSourceLine; + appendBase64VLQ(pendingSourceCharacter - lastSourceCharacter); + lastSourceCharacter = pendingSourceCharacter; + if (hasPendingName) { + appendBase64VLQ(pendingNameIndex - lastNameIndex); + lastNameIndex = pendingNameIndex; + } + } + hasLast = true; + exit(); + } + function flushMappingBuffer() { + if (mappingCharCodes.length > 0) { + mappings += String.fromCharCode.apply(void 0, mappingCharCodes); + mappingCharCodes.length = 0; + } + } + function toJSON() { + commitPendingMapping(); + flushMappingBuffer(); + return { + version: 3, + file, + sourceRoot, + sources, + names, + mappings, + sourcesContent + }; + } + function appendBase64VLQ(inValue) { + if (inValue < 0) { + inValue = (-inValue << 1) + 1; + } else { + inValue = inValue << 1; + } + do { + let currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + appendMappingCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + } +} +var sourceMapCommentRegExpDontCareLineStart = /\/\/[@#] source[M]appingURL=(.+)\r?\n?$/; +var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\r?\n?$/; +var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; +function decodeMappings(mappings) { + let done = false; + let pos = 0; + let generatedLine = 0; + let generatedCharacter = 0; + let sourceIndex = 0; + let sourceLine = 0; + let sourceCharacter = 0; + let nameIndex = 0; + let error; + return { + get pos() { + return pos; + }, + get error() { + return error; + }, + get state() { + return captureMapping( + /*hasSource*/ + true, + /*hasName*/ + true + ); + }, + next() { + while (!done && pos < mappings.length) { + const ch = mappings.charCodeAt(pos); + if (ch === 59 /* semicolon */) { + generatedLine++; + generatedCharacter = 0; + pos++; + continue; + } + if (ch === 44 /* comma */) { + pos++; + continue; + } + let hasSource = false; + let hasName = false; + generatedCharacter += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (generatedCharacter < 0) return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasSource = true; + sourceIndex += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (sourceIndex < 0) return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + sourceLine += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (sourceLine < 0) return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + sourceCharacter += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (sourceCharacter < 0) return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (!isSourceMappingSegmentEnd()) { + hasName = true; + nameIndex += base64VLQFormatDecode(); + if (hasReportedError()) return stopIterating(); + if (nameIndex < 0) return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + } + } + return { value: captureMapping(hasSource, hasName), done }; + } + return stopIterating(); + }, + [Symbol.iterator]() { + return this; + } + }; + function captureMapping(hasSource, hasName) { + return { + generatedLine, + generatedCharacter, + sourceIndex: hasSource ? sourceIndex : void 0, + sourceLine: hasSource ? sourceLine : void 0, + sourceCharacter: hasSource ? sourceCharacter : void 0, + nameIndex: hasName ? nameIndex : void 0 + }; + } + function stopIterating() { + done = true; + return { value: void 0, done: true }; + } + function setError(message) { + if (error === void 0) { + error = message; + } + } + function setErrorAndStopIterating(message) { + setError(message); + return stopIterating(); + } + function hasReportedError() { + return error !== void 0; + } + function isSourceMappingSegmentEnd() { + return pos === mappings.length || mappings.charCodeAt(pos) === 44 /* comma */ || mappings.charCodeAt(pos) === 59 /* semicolon */; + } + function base64VLQFormatDecode() { + let moreDigits = true; + let shiftCount = 0; + let value = 0; + for (; moreDigits; pos++) { + if (pos >= mappings.length) return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + const currentByte = base64FormatDecode(mappings.charCodeAt(pos)); + if (currentByte === -1) return setError("Invalid character in VLQ"), -1; + moreDigits = (currentByte & 32) !== 0; + value = value | (currentByte & 31) << shiftCount; + shiftCount += 5; + } + if ((value & 1) === 0) { + value = value >> 1; + } else { + value = value >> 1; + value = -value; + } + return value; + } +} +function base64FormatEncode(value) { + return value >= 0 && value < 26 ? 65 /* A */ + value : value >= 26 && value < 52 ? 97 /* a */ + value - 26 : value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : value === 62 ? 43 /* plus */ : value === 63 ? 47 /* slash */ : Debug.fail(`${value}: not a base64 value`); +} +function base64FormatDecode(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : ch === 43 /* plus */ ? 62 : ch === 47 /* slash */ ? 63 : -1; +} + +// src/compiler/transformers/utilities.ts +function getOriginalNodeId(node) { + node = getOriginalNode(node); + return node ? getNodeId(node) : 0; +} +function containsDefaultReference(node) { + if (!node) return false; + if (!isNamedImports(node) && !isNamedExports(node)) return false; + return some(node.elements, isNamedDefaultReference); +} +function isNamedDefaultReference(e) { + return moduleExportNameIsDefault(e.propertyName || e.name); +} +function chainBundle(context, transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 307 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return context.factory.createBundle(map(node.sourceFiles, transformSourceFile)); + } +} +function getExportNeedsImportStarHelper(node) { + return !!getNamespaceDeclarationNode(node); +} +function getImportNeedsImportStarHelper(node) { + if (!!getNamespaceDeclarationNode(node)) { + return true; + } + const bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!isNamedImports(bindings)) return false; + let defaultRefCount = 0; + for (const binding of bindings.elements) { + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + return defaultRefCount > 0 && defaultRefCount !== bindings.elements.length || !!(bindings.elements.length - defaultRefCount) && isDefaultImport(node); +} +function getImportNeedsImportDefaultHelper(node) { + return !getImportNeedsImportStarHelper(node) && (isDefaultImport(node) || !!node.importClause && isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings)); +} +function collectExternalModuleInfo(context, sourceFile) { + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const externalImports = []; + const exportSpecifiers = new IdentifierNameMultiMap(); + const exportedBindings = []; + const uniqueExports = /* @__PURE__ */ new Map(); + const exportedFunctions = /* @__PURE__ */ new Set(); + let exportedNames; + let hasExportDefault = false; + let exportEquals; + let hasExportStarsToExportValues = false; + let hasImportStar = false; + let hasImportDefault = false; + for (const node of sourceFile.statements) { + switch (node.kind) { + case 272 /* ImportDeclaration */: + externalImports.push(node); + if (!hasImportStar && getImportNeedsImportStarHelper(node)) { + hasImportStar = true; + } + if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) { + hasImportDefault = true; + } + break; + case 271 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 283 /* ExternalModuleReference */) { + externalImports.push(node); + } + break; + case 278 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } else { + externalImports.push(node); + if (isNamedExports(node.exportClause)) { + addExportedNamesForExportDeclaration(node); + hasImportDefault || (hasImportDefault = containsDefaultReference(node.exportClause)); + } else { + const name = node.exportClause.name; + const nameText = moduleExportNameTextUnescaped(name); + if (!uniqueExports.get(nameText)) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(nameText, true); + exportedNames = append(exportedNames, name); + } + hasImportStar = true; + } + } + } else { + addExportedNamesForExportDeclaration(node); + } + break; + case 277 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + case 243 /* VariableStatement */: + if (hasSyntacticModifier(node, 32 /* Export */)) { + for (const decl of node.declarationList.declarations) { + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings); + } + } + break; + case 262 /* FunctionDeclaration */: + if (hasSyntacticModifier(node, 32 /* Export */)) { + addExportedFunctionDeclaration( + node, + /*name*/ + void 0, + hasSyntacticModifier(node, 2048 /* Default */) + ); + } + break; + case 263 /* ClassDeclaration */: + if (hasSyntacticModifier(node, 32 /* Export */)) { + if (hasSyntacticModifier(node, 2048 /* Default */)) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node)); + hasExportDefault = true; + } + } else { + const name = node.name; + if (name && !uniqueExports.get(idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(idText(name), true); + exportedNames = append(exportedNames, name); + } + } + } + break; + } + } + const externalHelpersImportDeclaration = createExternalHelpersImportDeclarationIfNeeded(context.factory, context.getEmitHelperFactory(), sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault); + if (externalHelpersImportDeclaration) { + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues, exportedBindings, exportedNames, exportedFunctions, externalHelpersImportDeclaration }; + function addExportedNamesForExportDeclaration(node) { + for (const specifier of cast(node.exportClause, isNamedExports).elements) { + const specifierNameText = moduleExportNameTextUnescaped(specifier.name); + if (!uniqueExports.get(specifierNameText)) { + const name = specifier.propertyName || specifier.name; + if (name.kind !== 11 /* StringLiteral */) { + if (!node.moduleSpecifier) { + exportSpecifiers.add(name, specifier); + } + const decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); + if (decl) { + if (decl.kind === 262 /* FunctionDeclaration */) { + addExportedFunctionDeclaration(decl, specifier.name, moduleExportNameIsDefault(specifier.name)); + continue; + } + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + } + uniqueExports.set(specifierNameText, true); + exportedNames = append(exportedNames, specifier.name); + } + } + } + function addExportedFunctionDeclaration(node, name, isDefault) { + exportedFunctions.add(getOriginalNode(node, isFunctionDeclaration)); + if (isDefault) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name ?? context.factory.getDeclarationName(node)); + hasExportDefault = true; + } + } else { + name ?? (name = node.name); + const nameText = moduleExportNameTextUnescaped(name); + if (!uniqueExports.get(nameText)) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(nameText, true); + } + } + } +} +function collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings) { + if (isBindingPattern(decl.name)) { + for (const element of decl.name.elements) { + if (!isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames, exportedBindings); + } + } + } else if (!isGeneratedIdentifier(decl.name)) { + const text = idText(decl.name); + if (!uniqueExports.get(text)) { + uniqueExports.set(text, true); + exportedNames = append(exportedNames, decl.name); + if (isLocalName(decl.name)) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), decl.name); + } + } + } + return exportedNames; +} +function multiMapSparseArrayAdd(map2, key, value) { + let values = map2[key]; + if (values) { + values.push(value); + } else { + map2[key] = values = [value]; + } + return values; +} +var IdentifierNameMap = class _IdentifierNameMap { + constructor() { + this._map = /* @__PURE__ */ new Map(); + } + get size() { + return this._map.size; + } + has(key) { + return this._map.has(_IdentifierNameMap.toKey(key)); + } + get(key) { + return this._map.get(_IdentifierNameMap.toKey(key)); + } + set(key, value) { + this._map.set(_IdentifierNameMap.toKey(key), value); + return this; + } + delete(key) { + var _a; + return ((_a = this._map) == null ? void 0 : _a.delete(_IdentifierNameMap.toKey(key))) ?? false; + } + clear() { + this._map.clear(); + } + values() { + return this._map.values(); + } + static toKey(name) { + if (isGeneratedPrivateIdentifier(name) || isGeneratedIdentifier(name)) { + const autoGenerate = name.emitNode.autoGenerate; + if ((autoGenerate.flags & 7 /* KindMask */) === 4 /* Node */) { + const node = getNodeForGeneratedName(name); + const baseName = isMemberName(node) && node !== name ? _IdentifierNameMap.toKey(node) : `(generated@${getNodeId(node)})`; + return formatGeneratedName( + /*privateName*/ + false, + autoGenerate.prefix, + baseName, + autoGenerate.suffix, + _IdentifierNameMap.toKey + ); + } else { + const baseName = `(auto@${autoGenerate.id})`; + return formatGeneratedName( + /*privateName*/ + false, + autoGenerate.prefix, + baseName, + autoGenerate.suffix, + _IdentifierNameMap.toKey + ); + } + } + if (isPrivateIdentifier(name)) { + return idText(name).slice(1); + } + return idText(name); + } +}; +var IdentifierNameMultiMap = class extends IdentifierNameMap { + add(key, value) { + let values = this.get(key); + if (values) { + values.push(value); + } else { + this.set(key, values = [value]); + } + return values; + } + remove(key, value) { + const values = this.get(key); + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } + } +}; +function isSimpleCopiableExpression(expression) { + return isStringLiteralLike(expression) || expression.kind === 9 /* NumericLiteral */ || isKeyword(expression.kind) || isIdentifier(expression); +} +function isSimpleInlineableExpression(expression) { + return !isIdentifier(expression) && isSimpleCopiableExpression(expression); +} +function isCompoundAssignment(kind) { + return kind >= 65 /* FirstCompoundAssignment */ && kind <= 79 /* LastCompoundAssignment */; +} +function getNonAssignmentOperatorForCompoundAssignment(kind) { + switch (kind) { + case 65 /* PlusEqualsToken */: + return 40 /* PlusToken */; + case 66 /* MinusEqualsToken */: + return 41 /* MinusToken */; + case 67 /* AsteriskEqualsToken */: + return 42 /* AsteriskToken */; + case 68 /* AsteriskAsteriskEqualsToken */: + return 43 /* AsteriskAsteriskToken */; + case 69 /* SlashEqualsToken */: + return 44 /* SlashToken */; + case 70 /* PercentEqualsToken */: + return 45 /* PercentToken */; + case 71 /* LessThanLessThanEqualsToken */: + return 48 /* LessThanLessThanToken */; + case 72 /* GreaterThanGreaterThanEqualsToken */: + return 49 /* GreaterThanGreaterThanToken */; + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return 50 /* GreaterThanGreaterThanGreaterThanToken */; + case 74 /* AmpersandEqualsToken */: + return 51 /* AmpersandToken */; + case 75 /* BarEqualsToken */: + return 52 /* BarToken */; + case 79 /* CaretEqualsToken */: + return 53 /* CaretToken */; + case 76 /* BarBarEqualsToken */: + return 57 /* BarBarToken */; + case 77 /* AmpersandAmpersandEqualsToken */: + return 56 /* AmpersandAmpersandToken */; + case 78 /* QuestionQuestionEqualsToken */: + return 61 /* QuestionQuestionToken */; + } +} +function getSuperCallFromStatement(statement) { + if (!isExpressionStatement(statement)) { + return void 0; + } + const expression = skipParentheses(statement.expression); + return isSuperCall(expression) ? expression : void 0; +} +function findSuperStatementIndexPathWorker(statements, start, indices) { + for (let i = start; i < statements.length; i += 1) { + const statement = statements[i]; + if (getSuperCallFromStatement(statement)) { + indices.unshift(i); + return true; + } else if (isTryStatement(statement) && findSuperStatementIndexPathWorker(statement.tryBlock.statements, 0, indices)) { + indices.unshift(i); + return true; + } + } + return false; +} +function findSuperStatementIndexPath(statements, start) { + const indices = []; + findSuperStatementIndexPathWorker(statements, start, indices); + return indices; +} +function getProperties(node, requireInitializer, isStatic2) { + return filter(node.members, (m) => isInitializedOrStaticProperty(m, requireInitializer, isStatic2)); +} +function isStaticPropertyDeclarationOrClassStaticBlockDeclaration(element) { + return isStaticPropertyDeclaration(element) || isClassStaticBlockDeclaration(element); +} +function getStaticPropertiesAndClassStaticBlock(node) { + return filter(node.members, isStaticPropertyDeclarationOrClassStaticBlockDeclaration); +} +function isInitializedOrStaticProperty(member, requireInitializer, isStatic2) { + return isPropertyDeclaration(member) && (!!member.initializer || !requireInitializer) && hasStaticModifier(member) === isStatic2; +} +function isStaticPropertyDeclaration(member) { + return isPropertyDeclaration(member) && hasStaticModifier(member); +} +function isInitializedProperty(member) { + return member.kind === 172 /* PropertyDeclaration */ && member.initializer !== void 0; +} +function isNonStaticMethodOrAccessorWithPrivateName(member) { + return !isStatic(member) && (isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member)) && isPrivateIdentifier(member.name); +} +function getDecoratorsOfParameters(node) { + let decorators; + if (node) { + const parameters = node.parameters; + const firstParameterIsThis = parameters.length > 0 && parameterIsThisKeyword(parameters[0]); + const firstParameterOffset = firstParameterIsThis ? 1 : 0; + const numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (let i = 0; i < numParameters; i++) { + const parameter = parameters[i + firstParameterOffset]; + if (decorators || hasDecorators(parameter)) { + if (!decorators) { + decorators = new Array(numParameters); + } + decorators[i] = getDecorators(parameter); + } + } + } + return decorators; +} +function getAllDecoratorsOfClass(node, useLegacyDecorators) { + const decorators = getDecorators(node); + const parameters = useLegacyDecorators ? getDecoratorsOfParameters(getFirstConstructorWithBody(node)) : void 0; + if (!some(decorators) && !some(parameters)) { + return void 0; + } + return { + decorators, + parameters + }; +} +function getAllDecoratorsOfClassElement(member, parent, useLegacyDecorators) { + switch (member.kind) { + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + if (!useLegacyDecorators) { + return getAllDecoratorsOfMethod( + member, + /*useLegacyDecorators*/ + false + ); + } + return getAllDecoratorsOfAccessors( + member, + parent, + /*useLegacyDecorators*/ + true + ); + case 174 /* MethodDeclaration */: + return getAllDecoratorsOfMethod(member, useLegacyDecorators); + case 172 /* PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return void 0; + } +} +function getAllDecoratorsOfAccessors(accessor, parent, useLegacyDecorators) { + if (!accessor.body) { + return void 0; + } + const { firstAccessor, secondAccessor, getAccessor, setAccessor } = getAllAccessorDeclarations(parent.members, accessor); + const firstAccessorWithDecorators = hasDecorators(firstAccessor) ? firstAccessor : secondAccessor && hasDecorators(secondAccessor) ? secondAccessor : void 0; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return void 0; + } + const decorators = getDecorators(firstAccessorWithDecorators); + const parameters = useLegacyDecorators ? getDecoratorsOfParameters(setAccessor) : void 0; + if (!some(decorators) && !some(parameters)) { + return void 0; + } + return { + decorators, + parameters, + getDecorators: getAccessor && getDecorators(getAccessor), + setDecorators: setAccessor && getDecorators(setAccessor) + }; +} +function getAllDecoratorsOfMethod(method, useLegacyDecorators) { + if (!method.body) { + return void 0; + } + const decorators = getDecorators(method); + const parameters = useLegacyDecorators ? getDecoratorsOfParameters(method) : void 0; + if (!some(decorators) && !some(parameters)) { + return void 0; + } + return { decorators, parameters }; +} +function getAllDecoratorsOfProperty(property) { + const decorators = getDecorators(property); + if (!some(decorators)) { + return void 0; + } + return { decorators }; +} +function walkUpLexicalEnvironments(env, cb) { + while (env) { + const result = cb(env); + if (result !== void 0) return result; + env = env.previous; + } +} +function newPrivateEnvironment(data) { + return { data }; +} +function getPrivateIdentifier(privateEnv, name) { + var _a, _b; + return isGeneratedPrivateIdentifier(name) ? (_a = privateEnv == null ? void 0 : privateEnv.generatedIdentifiers) == null ? void 0 : _a.get(getNodeForGeneratedName(name)) : (_b = privateEnv == null ? void 0 : privateEnv.identifiers) == null ? void 0 : _b.get(name.escapedText); +} +function setPrivateIdentifier(privateEnv, name, entry) { + if (isGeneratedPrivateIdentifier(name)) { + privateEnv.generatedIdentifiers ?? (privateEnv.generatedIdentifiers = /* @__PURE__ */ new Map()); + privateEnv.generatedIdentifiers.set(getNodeForGeneratedName(name), entry); + } else { + privateEnv.identifiers ?? (privateEnv.identifiers = /* @__PURE__ */ new Map()); + privateEnv.identifiers.set(name.escapedText, entry); + } +} +function accessPrivateIdentifier(env, name) { + return walkUpLexicalEnvironments(env, (env2) => getPrivateIdentifier(env2.privateEnv, name)); +} +function isSimpleParameter(node) { + return !node.initializer && isIdentifier(node.name); +} +function isSimpleParameterList(nodes) { + return every(nodes, isSimpleParameter); +} +function rewriteModuleSpecifier(node, compilerOptions) { + if (!node || !isStringLiteral(node) || !shouldRewriteModuleSpecifier(node.text, compilerOptions)) { + return node; + } + const updatedText = changeExtension(node.text, getOutputExtension(node.text, compilerOptions)); + return updatedText !== node.text ? setOriginalNode(setTextRange(factory.createStringLiteral(updatedText, node.singleQuote), node), node) : node; +} + +// src/compiler/transformers/destructuring.ts +function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { + let location = node; + let value; + if (isDestructuringAssignment(node)) { + value = node.right; + while (isEmptyArrayLiteral(node.left) || isEmptyObjectLiteral(node.left)) { + if (isDestructuringAssignment(value)) { + location = node = value; + value = node.right; + } else { + return Debug.checkDefined(visitNode(value, visitor, isExpression)); + } + } + } + let expressions; + const flattenContext = { + context, + level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables: true, + emitExpression, + emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: (elements) => makeArrayAssignmentPattern(context.factory, elements), + createObjectBindingOrAssignmentPattern: (elements) => makeObjectAssignmentPattern(context.factory, elements), + createArrayBindingOrAssignmentElement: makeAssignmentElement, + visitor + }; + if (value) { + value = visitNode(value, visitor, isExpression); + Debug.assert(value); + if (isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || bindingOrAssignmentElementContainsNonLiteralComputedName(node)) { + value = ensureIdentifier( + flattenContext, + value, + /*reuseIdentifierExpressions*/ + false, + location + ); + } else if (needsValue) { + value = ensureIdentifier( + flattenContext, + value, + /*reuseIdentifierExpressions*/ + true, + location + ); + } else if (nodeIsSynthesized(node)) { + location = value; + } + } + flattenBindingOrAssignmentElement( + flattenContext, + node, + value, + location, + /*skipInitializer*/ + isDestructuringAssignment(node) + ); + if (value && needsValue) { + if (!some(expressions)) { + return value; + } + expressions.push(value); + } + return context.factory.inlineExpressions(expressions) || context.factory.createOmittedExpression(); + function emitExpression(expression) { + expressions = append(expressions, expression); + } + function emitBindingOrAssignment(target, value2, location2, original) { + Debug.assertNode(target, createAssignmentCallback ? isIdentifier : isExpression); + const expression = createAssignmentCallback ? createAssignmentCallback(target, value2, location2) : setTextRange( + context.factory.createAssignment(Debug.checkDefined(visitNode(target, visitor, isExpression)), value2), + location2 + ); + expression.original = original; + emitExpression(expression); + } +} +function bindingOrAssignmentElementAssignsToName(element, escapedName) { + const target = getTargetOfBindingOrAssignmentElement(element); + if (isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } else if (isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; +} +function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + const elements = getElementsOfBindingOrAssignmentPattern(pattern); + for (const element of elements) { + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; +} +function bindingOrAssignmentElementContainsNonLiteralComputedName(element) { + const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(element); + if (propertyName && isComputedPropertyName(propertyName) && !isLiteralExpression(propertyName.expression)) { + return true; + } + const target = getTargetOfBindingOrAssignmentElement(element); + return !!target && isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target); +} +function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) { + return !!forEach(getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName); +} +function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables = false, skipInitializer) { + let pendingExpressions; + const pendingDeclarations = []; + const declarations = []; + const flattenContext = { + context, + level, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, + hoistTempVariables, + emitExpression, + emitBindingOrAssignment, + createArrayBindingOrAssignmentPattern: (elements) => makeArrayBindingPattern(context.factory, elements), + createObjectBindingOrAssignmentPattern: (elements) => makeObjectBindingPattern(context.factory, elements), + createArrayBindingOrAssignmentElement: (name) => makeBindingElement(context.factory, name), + visitor + }; + if (isVariableDeclaration(node)) { + let initializer = getInitializerOfBindingOrAssignmentElement(node); + if (initializer && (isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || bindingOrAssignmentElementContainsNonLiteralComputedName(node))) { + initializer = ensureIdentifier( + flattenContext, + Debug.checkDefined(visitNode(initializer, flattenContext.visitor, isExpression)), + /*reuseIdentifierExpressions*/ + false, + initializer + ); + node = context.factory.updateVariableDeclaration( + node, + node.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + initializer + ); + } + } + flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + if (pendingExpressions) { + const temp = context.factory.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + if (hoistTempVariables) { + const value = context.factory.inlineExpressions(pendingExpressions); + pendingExpressions = void 0; + emitBindingOrAssignment( + temp, + value, + /*location*/ + void 0, + /*original*/ + void 0 + ); + } else { + context.hoistVariableDeclaration(temp); + const pendingDeclaration = last(pendingDeclarations); + pendingDeclaration.pendingExpressions = append( + pendingDeclaration.pendingExpressions, + context.factory.createAssignment(temp, pendingDeclaration.value) + ); + addRange(pendingDeclaration.pendingExpressions, pendingExpressions); + pendingDeclaration.value = temp; + } + } + for (const { pendingExpressions: pendingExpressions2, name, value, location, original } of pendingDeclarations) { + const variable = context.factory.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + pendingExpressions2 ? context.factory.inlineExpressions(append(pendingExpressions2, value)) : value + ); + variable.original = original; + setTextRange(variable, location); + declarations.push(variable); + } + return declarations; + function emitExpression(value) { + pendingExpressions = append(pendingExpressions, value); + } + function emitBindingOrAssignment(target, value, location, original) { + Debug.assertNode(target, isBindingName); + if (pendingExpressions) { + value = context.factory.inlineExpressions(append(pendingExpressions, value)); + pendingExpressions = void 0; + } + pendingDeclarations.push({ pendingExpressions, name: target, value, location, original }); + } +} +function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { + const bindingTarget = getTargetOfBindingOrAssignmentElement(element); + if (!skipInitializer) { + const initializer = visitNode(getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, isExpression); + if (initializer) { + if (value) { + value = createDefaultValueCheck(flattenContext, value, initializer, location); + if (!isSimpleInlineableExpression(initializer) && isBindingOrAssignmentPattern(bindingTarget)) { + value = ensureIdentifier( + flattenContext, + value, + /*reuseIdentifierExpressions*/ + true, + location + ); + } + } else { + value = initializer; + } + } else if (!value) { + value = flattenContext.context.factory.createVoidZero(); + } + } + if (isObjectBindingOrAssignmentPattern(bindingTarget)) { + flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } else if (isArrayBindingOrAssignmentPattern(bindingTarget)) { + flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); + } else { + flattenContext.emitBindingOrAssignment( + bindingTarget, + value, + location, + /*original*/ + element + ); + } +} +function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + const elements = getElementsOfBindingOrAssignmentPattern(pattern); + const numElements = elements.length; + if (numElements !== 1) { + const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + let bindingElements; + let computedTempVariables; + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { + const propertyName = getPropertyNameOfBindingOrAssignmentElement(element); + if (flattenContext.level >= 1 /* ObjectRest */ && !(element.transformFlags & (32768 /* ContainsRestOrSpread */ | 65536 /* ContainsObjectRestOrSpread */)) && !(getTargetOfBindingOrAssignmentElement(element).transformFlags & (32768 /* ContainsRestOrSpread */ | 65536 /* ContainsObjectRestOrSpread */)) && !isComputedPropertyName(propertyName)) { + bindingElements = append(bindingElements, visitNode(element, flattenContext.visitor, isBindingOrAssignmentElement)); + } else { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = void 0; + } + const rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + if (isComputedPropertyName(propertyName)) { + computedTempVariables = append(computedTempVariables, rhsValue.argumentExpression); + } + flattenBindingOrAssignmentElement( + flattenContext, + element, + rhsValue, + /*location*/ + element + ); + } + } else if (i === numElements - 1) { + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + bindingElements = void 0; + } + const rhsValue = flattenContext.context.getEmitHelperFactory().createRestHelper(value, elements, computedTempVariables, pattern); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } +} +function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) { + const elements = getElementsOfBindingOrAssignmentPattern(pattern); + const numElements = elements.length; + if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) { + value = ensureIdentifier( + flattenContext, + setTextRange( + flattenContext.context.getEmitHelperFactory().createReadHelper( + value, + numElements > 0 && getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) ? void 0 : numElements + ), + location + ), + /*reuseIdentifierExpressions*/ + false, + location + ); + } else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) || every(elements, isOmittedExpression)) { + const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0; + value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + } + let bindingElements; + let restContainingElements; + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + if (flattenContext.level >= 1 /* ObjectRest */) { + if (element.transformFlags & 65536 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + flattenContext.hasTransformedPriorElement = true; + const temp = flattenContext.context.factory.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + } + restContainingElements = append(restContainingElements, [temp, element]); + bindingElements = append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + } else { + bindingElements = append(bindingElements, element); + } + } else if (isOmittedExpression(element)) { + continue; + } else if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { + const rhsValue = flattenContext.context.factory.createElementAccessExpression(value, i); + flattenBindingOrAssignmentElement( + flattenContext, + element, + rhsValue, + /*location*/ + element + ); + } else if (i === numElements - 1) { + const rhsValue = flattenContext.context.factory.createArraySliceCall(value, i); + flattenBindingOrAssignmentElement( + flattenContext, + element, + rhsValue, + /*location*/ + element + ); + } + } + if (bindingElements) { + flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + } + if (restContainingElements) { + for (const [id, element] of restContainingElements) { + flattenBindingOrAssignmentElement(flattenContext, element, id, element); + } + } +} +function isSimpleBindingOrAssignmentElement(element) { + const target = getTargetOfBindingOrAssignmentElement(element); + if (!target || isOmittedExpression(target)) return true; + const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(element); + if (propertyName && !isPropertyNameLiteral(propertyName)) return false; + const initializer = getInitializerOfBindingOrAssignmentElement(element); + if (initializer && !isSimpleInlineableExpression(initializer)) return false; + if (isBindingOrAssignmentPattern(target)) return every(getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement); + return isIdentifier(target); +} +function createDefaultValueCheck(flattenContext, value, defaultValue, location) { + value = ensureIdentifier( + flattenContext, + value, + /*reuseIdentifierExpressions*/ + true, + location + ); + return flattenContext.context.factory.createConditionalExpression( + flattenContext.context.factory.createTypeCheck(value, "undefined"), + /*questionToken*/ + void 0, + defaultValue, + /*colonToken*/ + void 0, + value + ); +} +function createDestructuringPropertyAccess(flattenContext, value, propertyName) { + const { factory: factory2 } = flattenContext.context; + if (isComputedPropertyName(propertyName)) { + const argumentExpression = ensureIdentifier( + flattenContext, + Debug.checkDefined(visitNode(propertyName.expression, flattenContext.visitor, isExpression)), + /*reuseIdentifierExpressions*/ + false, + /*location*/ + propertyName + ); + return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression); + } else if (isStringOrNumericLiteralLike(propertyName) || isBigIntLiteral(propertyName)) { + const argumentExpression = factory2.cloneNode(propertyName); + return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression); + } else { + const name = flattenContext.context.factory.createIdentifier(idText(propertyName)); + return flattenContext.context.factory.createPropertyAccessExpression(value, name); + } +} +function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) { + if (isIdentifier(value) && reuseIdentifierExpressions) { + return value; + } else { + const temp = flattenContext.context.factory.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + if (flattenContext.hoistTempVariables) { + flattenContext.context.hoistVariableDeclaration(temp); + flattenContext.emitExpression(setTextRange(flattenContext.context.factory.createAssignment(temp, value), location)); + } else { + flattenContext.emitBindingOrAssignment( + temp, + value, + location, + /*original*/ + void 0 + ); + } + return temp; + } +} +function makeArrayBindingPattern(factory2, elements) { + Debug.assertEachNode(elements, isArrayBindingElement); + return factory2.createArrayBindingPattern(elements); +} +function makeArrayAssignmentPattern(factory2, elements) { + Debug.assertEachNode(elements, isArrayBindingOrAssignmentElement); + return factory2.createArrayLiteralExpression(map(elements, factory2.converters.convertToArrayAssignmentElement)); +} +function makeObjectBindingPattern(factory2, elements) { + Debug.assertEachNode(elements, isBindingElement); + return factory2.createObjectBindingPattern(elements); +} +function makeObjectAssignmentPattern(factory2, elements) { + Debug.assertEachNode(elements, isObjectBindingOrAssignmentElement); + return factory2.createObjectLiteralExpression(map(elements, factory2.converters.convertToObjectAssignmentElement)); +} +function makeBindingElement(factory2, name) { + return factory2.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + name + ); +} +function makeAssignmentElement(name) { + return name; +} + +// src/compiler/transformers/classThis.ts +function createClassThisAssignmentBlock(factory2, classThis, thisExpression = factory2.createThis()) { + const expression = factory2.createAssignment(classThis, thisExpression); + const statement = factory2.createExpressionStatement(expression); + const body = factory2.createBlock( + [statement], + /*multiLine*/ + false + ); + const block = factory2.createClassStaticBlockDeclaration(body); + getOrCreateEmitNode(block).classThis = classThis; + return block; +} +function isClassThisAssignmentBlock(node) { + var _a; + if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) { + return false; + } + const statement = node.body.statements[0]; + return isExpressionStatement(statement) && isAssignmentExpression( + statement.expression, + /*excludeCompoundAssignment*/ + true + ) && isIdentifier(statement.expression.left) && ((_a = node.emitNode) == null ? void 0 : _a.classThis) === statement.expression.left && statement.expression.right.kind === 110 /* ThisKeyword */; +} +function classHasClassThisAssignment(node) { + var _a; + return !!((_a = node.emitNode) == null ? void 0 : _a.classThis) && some(node.members, isClassThisAssignmentBlock); +} +function injectClassThisAssignmentIfMissing(factory2, node, classThis, thisExpression) { + if (classHasClassThisAssignment(node)) { + return node; + } + const staticBlock = createClassThisAssignmentBlock(factory2, classThis, thisExpression); + if (node.name) { + setSourceMapRange(staticBlock.body.statements[0], node.name); + } + const members = factory2.createNodeArray([staticBlock, ...node.members]); + setTextRange(members, node.members); + const updatedNode = isClassDeclaration(node) ? factory2.updateClassDeclaration( + node, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + members + ) : factory2.updateClassExpression( + node, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + members + ); + getOrCreateEmitNode(updatedNode).classThis = classThis; + return updatedNode; +} + +// src/compiler/transformers/namedEvaluation.ts +function getAssignedNameOfIdentifier(factory2, name, expression) { + const original = getOriginalNode(skipOuterExpressions(expression)); + if ((isClassDeclaration(original) || isFunctionDeclaration(original)) && !original.name && hasSyntacticModifier(original, 2048 /* Default */)) { + return factory2.createStringLiteral("default"); + } + return factory2.createStringLiteralFromNode(name); +} +function getAssignedNameOfPropertyName(context, name, assignedNameText) { + const { factory: factory2 } = context; + if (assignedNameText !== void 0) { + const assignedName2 = factory2.createStringLiteral(assignedNameText); + return { assignedName: assignedName2, name }; + } + if (isPropertyNameLiteral(name) || isPrivateIdentifier(name)) { + const assignedName2 = factory2.createStringLiteralFromNode(name); + return { assignedName: assignedName2, name }; + } + if (isPropertyNameLiteral(name.expression) && !isIdentifier(name.expression)) { + const assignedName2 = factory2.createStringLiteralFromNode(name.expression); + return { assignedName: assignedName2, name }; + } + const assignedName = factory2.getGeneratedNameForNode(name); + context.hoistVariableDeclaration(assignedName); + const key = context.getEmitHelperFactory().createPropKeyHelper(name.expression); + const assignment = factory2.createAssignment(assignedName, key); + const updatedName = factory2.updateComputedPropertyName(name, assignment); + return { assignedName, name: updatedName }; +} +function createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression = context.factory.createThis()) { + const { factory: factory2 } = context; + const expression = context.getEmitHelperFactory().createSetFunctionNameHelper(thisExpression, assignedName); + const statement = factory2.createExpressionStatement(expression); + const body = factory2.createBlock( + [statement], + /*multiLine*/ + false + ); + const block = factory2.createClassStaticBlockDeclaration(body); + getOrCreateEmitNode(block).assignedName = assignedName; + return block; +} +function isClassNamedEvaluationHelperBlock(node) { + var _a; + if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) { + return false; + } + const statement = node.body.statements[0]; + return isExpressionStatement(statement) && isCallToHelper(statement.expression, "___setFunctionName") && statement.expression.arguments.length >= 2 && statement.expression.arguments[1] === ((_a = node.emitNode) == null ? void 0 : _a.assignedName); +} +function classHasExplicitlyAssignedName(node) { + var _a; + return !!((_a = node.emitNode) == null ? void 0 : _a.assignedName) && some(node.members, isClassNamedEvaluationHelperBlock); +} +function classHasDeclaredOrExplicitlyAssignedName(node) { + return !!node.name || classHasExplicitlyAssignedName(node); +} +function injectClassNamedEvaluationHelperBlockIfMissing(context, node, assignedName, thisExpression) { + if (classHasExplicitlyAssignedName(node)) { + return node; + } + const { factory: factory2 } = context; + const namedEvaluationBlock = createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression); + if (node.name) { + setSourceMapRange(namedEvaluationBlock.body.statements[0], node.name); + } + const insertionIndex = findIndex(node.members, isClassThisAssignmentBlock) + 1; + const leading = node.members.slice(0, insertionIndex); + const trailing = node.members.slice(insertionIndex); + const members = factory2.createNodeArray([...leading, namedEvaluationBlock, ...trailing]); + setTextRange(members, node.members); + node = isClassDeclaration(node) ? factory2.updateClassDeclaration( + node, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + members + ) : factory2.updateClassExpression( + node, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + members + ); + getOrCreateEmitNode(node).assignedName = assignedName; + return node; +} +function finishTransformNamedEvaluation(context, expression, assignedName, ignoreEmptyStringLiteral) { + if (ignoreEmptyStringLiteral && isStringLiteral(assignedName) && isEmptyStringLiteral(assignedName)) { + return expression; + } + const { factory: factory2 } = context; + const innerExpression = skipOuterExpressions(expression); + const updatedExpression = isClassExpression(innerExpression) ? cast(injectClassNamedEvaluationHelperBlockIfMissing(context, innerExpression, assignedName), isClassExpression) : context.getEmitHelperFactory().createSetFunctionNameHelper(innerExpression, assignedName); + return factory2.restoreOuterExpressions(expression, updatedExpression); +} +function transformNamedEvaluationOfPropertyAssignment(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updatePropertyAssignment( + node, + name, + initializer + ); +} +function transformNamedEvaluationOfShorthandAssignmentProperty(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.objectAssignmentInitializer); + const objectAssignmentInitializer = finishTransformNamedEvaluation(context, node.objectAssignmentInitializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updateShorthandPropertyAssignment( + node, + node.name, + objectAssignmentInitializer + ); +} +function transformNamedEvaluationOfVariableDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updateVariableDeclaration( + node, + node.name, + node.exclamationToken, + node.type, + initializer + ); +} +function transformNamedEvaluationOfParameterDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updateParameterDeclaration( + node, + node.modifiers, + node.dotDotDotToken, + node.name, + node.questionToken, + node.type, + initializer + ); +} +function transformNamedEvaluationOfBindingElement(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updateBindingElement( + node, + node.dotDotDotToken, + node.propertyName, + node.name, + initializer + ); +} +function transformNamedEvaluationOfPropertyDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); + const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); + return factory2.updatePropertyDeclaration( + node, + node.modifiers, + name, + node.questionToken ?? node.exclamationToken, + node.type, + initializer + ); +} +function transformNamedEvaluationOfAssignmentExpression(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.left, node.right); + const right = finishTransformNamedEvaluation(context, node.right, assignedName, ignoreEmptyStringLiteral); + return factory2.updateBinaryExpression( + node, + node.left, + node.operatorToken, + right + ); +} +function transformNamedEvaluationOfExportAssignment(context, node, ignoreEmptyStringLiteral, assignedNameText) { + const { factory: factory2 } = context; + const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : factory2.createStringLiteral(node.isExportEquals ? "" : "default"); + const expression = finishTransformNamedEvaluation(context, node.expression, assignedName, ignoreEmptyStringLiteral); + return factory2.updateExportAssignment( + node, + node.modifiers, + expression + ); +} +function transformNamedEvaluation(context, node, ignoreEmptyStringLiteral, assignedName) { + switch (node.kind) { + case 303 /* PropertyAssignment */: + return transformNamedEvaluationOfPropertyAssignment(context, node, ignoreEmptyStringLiteral, assignedName); + case 304 /* ShorthandPropertyAssignment */: + return transformNamedEvaluationOfShorthandAssignmentProperty(context, node, ignoreEmptyStringLiteral, assignedName); + case 260 /* VariableDeclaration */: + return transformNamedEvaluationOfVariableDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); + case 169 /* Parameter */: + return transformNamedEvaluationOfParameterDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); + case 208 /* BindingElement */: + return transformNamedEvaluationOfBindingElement(context, node, ignoreEmptyStringLiteral, assignedName); + case 172 /* PropertyDeclaration */: + return transformNamedEvaluationOfPropertyDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); + case 226 /* BinaryExpression */: + return transformNamedEvaluationOfAssignmentExpression(context, node, ignoreEmptyStringLiteral, assignedName); + case 277 /* ExportAssignment */: + return transformNamedEvaluationOfExportAssignment(context, node, ignoreEmptyStringLiteral, assignedName); + } +} + +// src/compiler/transformers/taggedTemplate.ts +function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) { + const tag = visitNode(node.tag, visitor, isExpression); + Debug.assert(tag); + const templateArguments = [void 0]; + const cookedStrings = []; + const rawStrings = []; + const template = node.template; + if (level === 0 /* LiftRestriction */ && !hasInvalidEscape(template)) { + return visitEachChild(node, visitor, context); + } + const { factory: factory2 } = context; + if (isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(createTemplateCooked(factory2, template)); + rawStrings.push(getRawLiteral(factory2, template, currentSourceFile)); + } else { + cookedStrings.push(createTemplateCooked(factory2, template.head)); + rawStrings.push(getRawLiteral(factory2, template.head, currentSourceFile)); + for (const templateSpan of template.templateSpans) { + cookedStrings.push(createTemplateCooked(factory2, templateSpan.literal)); + rawStrings.push(getRawLiteral(factory2, templateSpan.literal, currentSourceFile)); + templateArguments.push(Debug.checkDefined(visitNode(templateSpan.expression, visitor, isExpression))); + } + } + const helperCall = context.getEmitHelperFactory().createTemplateObjectHelper( + factory2.createArrayLiteralExpression(cookedStrings), + factory2.createArrayLiteralExpression(rawStrings) + ); + if (isExternalModule(currentSourceFile)) { + const tempVar = factory2.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = factory2.createLogicalOr( + tempVar, + factory2.createAssignment( + tempVar, + helperCall + ) + ); + } else { + templateArguments[0] = helperCall; + } + return factory2.createCallExpression( + tag, + /*typeArguments*/ + void 0, + templateArguments + ); +} +function createTemplateCooked(factory2, template) { + return template.templateFlags & 26656 /* IsInvalid */ ? factory2.createVoidZero() : factory2.createStringLiteral(template.text); +} +function getRawLiteral(factory2, node, currentSourceFile) { + let text = node.rawText; + if (text === void 0) { + Debug.assertIsDefined(currentSourceFile, "Template literal node is missing 'rawText' and does not have a source file. Possibly bad transform."); + text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + const isLast = node.kind === 15 /* NoSubstitutionTemplateLiteral */ || node.kind === 18 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + } + text = text.replace(/\r\n?/g, "\n"); + return setTextRange(factory2.createStringLiteral(text), node); +} + +// src/compiler/transformers/ts.ts +var USE_NEW_TYPE_METADATA_FORMAT = false; +function transformTypeScript(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + startLexicalEnvironment, + resumeLexicalEnvironment, + endLexicalEnvironment, + hoistVariableDeclaration + } = context; + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + const moduleKind = getEmitModuleKind(compilerOptions); + const legacyDecorators = !!compilerOptions.experimentalDecorators; + const typeSerializer = compilerOptions.emitDecoratorMetadata ? createRuntimeTypeSerializer(context) : void 0; + const previousOnEmitNode = context.onEmitNode; + const previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(211 /* PropertyAccessExpression */); + context.enableSubstitution(212 /* ElementAccessExpression */); + let currentSourceFile; + let currentNamespace; + let currentNamespaceContainerName; + let currentLexicalScope; + let currentScopeFirstDeclarationsOfName; + let enabledSubstitutions = 0 /* None */; + let applicableSubstitutions; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 308 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return factory2.createBundle( + node.sourceFiles.map(transformSourceFile) + ); + } + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + const visited = saveStateAndInvoke(node, visitSourceFile); + addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = void 0; + return visited; + } + function saveStateAndInvoke(node, f) { + const savedCurrentScope = currentLexicalScope; + const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + onBeforeVisitNode(node); + const visited = f(node); + if (currentLexicalScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } + currentLexicalScope = savedCurrentScope; + return visited; + } + function onBeforeVisitNode(node) { + switch (node.kind) { + case 307 /* SourceFile */: + case 269 /* CaseBlock */: + case 268 /* ModuleBlock */: + case 241 /* Block */: + currentLexicalScope = node; + currentScopeFirstDeclarationsOfName = void 0; + break; + case 263 /* ClassDeclaration */: + case 262 /* FunctionDeclaration */: + if (hasSyntacticModifier(node, 128 /* Ambient */)) { + break; + } + if (node.name) { + recordEmittedDeclarationInScope(node); + } else { + Debug.assert(node.kind === 263 /* ClassDeclaration */ || hasSyntacticModifier(node, 2048 /* Default */)); + } + break; + } + } + function visitor(node) { + return saveStateAndInvoke(node, visitorWorker); + } + function visitorWorker(node) { + if (node.transformFlags & 1 /* ContainsTypeScript */) { + return visitTypeScript(node); + } + return node; + } + function sourceElementVisitor(node) { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 272 /* ImportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 277 /* ExportAssignment */: + case 278 /* ExportDeclaration */: + return visitElidableStatement(node); + default: + return visitorWorker(node); + } + } + function isElisionBlocked(node) { + const parsed = getParseTreeNode(node); + if (parsed === node || isExportAssignment(node)) { + return false; + } + if (!parsed || parsed.kind !== node.kind) { + return true; + } + switch (node.kind) { + case 272 /* ImportDeclaration */: + Debug.assertNode(parsed, isImportDeclaration); + if (node.importClause !== parsed.importClause) { + return true; + } + if (node.attributes !== parsed.attributes) { + return true; + } + break; + case 271 /* ImportEqualsDeclaration */: + Debug.assertNode(parsed, isImportEqualsDeclaration); + if (node.name !== parsed.name) { + return true; + } + if (node.isTypeOnly !== parsed.isTypeOnly) { + return true; + } + if (node.moduleReference !== parsed.moduleReference && (isEntityName(node.moduleReference) || isEntityName(parsed.moduleReference))) { + return true; + } + break; + case 278 /* ExportDeclaration */: + Debug.assertNode(parsed, isExportDeclaration); + if (node.exportClause !== parsed.exportClause) { + return true; + } + if (node.attributes !== parsed.attributes) { + return true; + } + break; + } + return false; + } + function visitElidableStatement(node) { + if (isElisionBlocked(node)) { + if (node.transformFlags & 1 /* ContainsTypeScript */) { + return visitEachChild(node, visitor, context); + } + return node; + } + switch (node.kind) { + case 272 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 271 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 277 /* ExportAssignment */: + return visitExportAssignment(node); + case 278 /* ExportDeclaration */: + return visitExportDeclaration(node); + default: + Debug.fail("Unhandled ellided statement"); + } + } + function namespaceElementVisitor(node) { + return saveStateAndInvoke(node, namespaceElementVisitorWorker); + } + function namespaceElementVisitorWorker(node) { + if (node.kind === 278 /* ExportDeclaration */ || node.kind === 272 /* ImportDeclaration */ || node.kind === 273 /* ImportClause */ || node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 283 /* ExternalModuleReference */) { + return void 0; + } else if (node.transformFlags & 1 /* ContainsTypeScript */ || hasSyntacticModifier(node, 32 /* Export */)) { + return visitTypeScript(node); + } + return node; + } + function getClassElementVisitor(parent) { + return (node) => saveStateAndInvoke(node, (n) => classElementVisitorWorker(n, parent)); + } + function classElementVisitorWorker(node, parent) { + switch (node.kind) { + case 176 /* Constructor */: + return visitConstructor(node); + case 172 /* PropertyDeclaration */: + return visitPropertyDeclaration(node, parent); + case 177 /* GetAccessor */: + return visitGetAccessor(node, parent); + case 178 /* SetAccessor */: + return visitSetAccessor(node, parent); + case 174 /* MethodDeclaration */: + return visitMethodDeclaration(node, parent); + case 175 /* ClassStaticBlockDeclaration */: + return visitEachChild(node, visitor, context); + case 240 /* SemicolonClassElement */: + return node; + case 181 /* IndexSignature */: + return; + default: + return Debug.failBadSyntaxKind(node); + } + } + function getObjectLiteralElementVisitor(parent) { + return (node) => saveStateAndInvoke(node, (n) => objectLiteralElementVisitorWorker(n, parent)); + } + function objectLiteralElementVisitorWorker(node, parent) { + switch (node.kind) { + case 303 /* PropertyAssignment */: + case 304 /* ShorthandPropertyAssignment */: + case 305 /* SpreadAssignment */: + return visitor(node); + case 177 /* GetAccessor */: + return visitGetAccessor(node, parent); + case 178 /* SetAccessor */: + return visitSetAccessor(node, parent); + case 174 /* MethodDeclaration */: + return visitMethodDeclaration(node, parent); + default: + return Debug.failBadSyntaxKind(node); + } + } + function decoratorElidingVisitor(node) { + return isDecorator(node) ? void 0 : visitor(node); + } + function modifierElidingVisitor(node) { + return isModifier(node) ? void 0 : visitor(node); + } + function modifierVisitor(node) { + if (isDecorator(node)) return void 0; + if (modifierToFlag(node.kind) & 28895 /* TypeScriptModifier */) { + return void 0; + } else if (currentNamespace && node.kind === 95 /* ExportKeyword */) { + return void 0; + } + return node; + } + function visitTypeScript(node) { + if (isStatement(node) && hasSyntacticModifier(node, 128 /* Ambient */)) { + return factory2.createNotEmittedStatement(node); + } + switch (node.kind) { + case 95 /* ExportKeyword */: + case 90 /* DefaultKeyword */: + return currentNamespace ? void 0 : node; + case 125 /* PublicKeyword */: + case 123 /* PrivateKeyword */: + case 124 /* ProtectedKeyword */: + case 128 /* AbstractKeyword */: + case 164 /* OverrideKeyword */: + case 87 /* ConstKeyword */: + case 138 /* DeclareKeyword */: + case 148 /* ReadonlyKeyword */: + case 103 /* InKeyword */: + case 147 /* OutKeyword */: + // TypeScript accessibility and readonly modifiers are elided + // falls through + case 188 /* ArrayType */: + case 189 /* TupleType */: + case 190 /* OptionalType */: + case 191 /* RestType */: + case 187 /* TypeLiteral */: + case 182 /* TypePredicate */: + case 168 /* TypeParameter */: + case 133 /* AnyKeyword */: + case 159 /* UnknownKeyword */: + case 136 /* BooleanKeyword */: + case 154 /* StringKeyword */: + case 150 /* NumberKeyword */: + case 146 /* NeverKeyword */: + case 116 /* VoidKeyword */: + case 155 /* SymbolKeyword */: + case 185 /* ConstructorType */: + case 184 /* FunctionType */: + case 186 /* TypeQuery */: + case 183 /* TypeReference */: + case 192 /* UnionType */: + case 193 /* IntersectionType */: + case 194 /* ConditionalType */: + case 196 /* ParenthesizedType */: + case 197 /* ThisType */: + case 198 /* TypeOperator */: + case 199 /* IndexedAccessType */: + case 200 /* MappedType */: + case 201 /* LiteralType */: + // TypeScript type nodes are elided. + // falls through + case 181 /* IndexSignature */: + return void 0; + case 265 /* TypeAliasDeclaration */: + return factory2.createNotEmittedStatement(node); + case 270 /* NamespaceExportDeclaration */: + return void 0; + case 264 /* InterfaceDeclaration */: + return factory2.createNotEmittedStatement(node); + case 263 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 231 /* ClassExpression */: + return visitClassExpression(node); + case 298 /* HeritageClause */: + return visitHeritageClause(node); + case 233 /* ExpressionWithTypeArguments */: + return visitExpressionWithTypeArguments(node); + case 210 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 176 /* Constructor */: + case 172 /* PropertyDeclaration */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 175 /* ClassStaticBlockDeclaration */: + return Debug.fail("Class and object literal elements must be visited with their respective visitors"); + case 262 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 218 /* FunctionExpression */: + return visitFunctionExpression(node); + case 219 /* ArrowFunction */: + return visitArrowFunction(node); + case 169 /* Parameter */: + return visitParameter(node); + case 217 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node); + case 216 /* TypeAssertionExpression */: + case 234 /* AsExpression */: + return visitAssertionExpression(node); + case 238 /* SatisfiesExpression */: + return visitSatisfiesExpression(node); + case 213 /* CallExpression */: + return visitCallExpression(node); + case 214 /* NewExpression */: + return visitNewExpression(node); + case 215 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 235 /* NonNullExpression */: + return visitNonNullExpression(node); + case 266 /* EnumDeclaration */: + return visitEnumDeclaration(node); + case 243 /* VariableStatement */: + return visitVariableStatement(node); + case 260 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 267 /* ModuleDeclaration */: + return visitModuleDeclaration(node); + case 271 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 285 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node); + case 286 /* JsxOpeningElement */: + return visitJsxJsxOpeningElement(node); + default: + return visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + const alwaysStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") && !(isExternalModule(node) && moduleKind >= 5 /* ES2015 */) && !isJsonSourceFile(node); + return factory2.updateSourceFile( + node, + visitLexicalEnvironment( + node.statements, + sourceElementVisitor, + context, + /*start*/ + 0, + alwaysStrict + ) + ); + } + function visitObjectLiteralExpression(node) { + return factory2.updateObjectLiteralExpression( + node, + visitNodes2(node.properties, getObjectLiteralElementVisitor(node), isObjectLiteralElementLike) + ); + } + function getClassFacts(node) { + let facts = 0 /* None */; + if (some(getProperties( + node, + /*requireInitializer*/ + true, + /*isStatic*/ + true + ))) facts |= 1 /* HasStaticInitializedProperties */; + const extendsClauseElement = getEffectiveBaseTypeNode(node); + if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; + if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) facts |= 2 /* HasClassOrConstructorParameterDecorators */; + if (childIsDecorated(legacyDecorators, node)) facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) facts |= 16 /* IsNamedExternalExport */; + return facts; + } + function hasTypeScriptClassSyntax(node) { + return !!(node.transformFlags & 8192 /* ContainsTypeScriptClassSyntax */); + } + function isClassLikeDeclarationWithTypeScriptSyntax(node) { + return hasDecorators(node) || some(node.typeParameters) || some(node.heritageClauses, hasTypeScriptClassSyntax) || some(node.members, hasTypeScriptClassSyntax); + } + function visitClassDeclaration(node) { + const facts = getClassFacts(node); + const promoteToIIFE = languageVersion <= 1 /* ES5 */ && !!(facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */); + if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !classOrConstructorParameterIsDecorated(legacyDecorators, node) && !isExportOfNamespace(node)) { + return factory2.updateClassDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + node.name, + /*typeParameters*/ + void 0, + visitNodes2(node.heritageClauses, visitor, isHeritageClause), + visitNodes2(node.members, getClassElementVisitor(node), isClassElement) + ); + } + if (promoteToIIFE) { + context.startLexicalEnvironment(); + } + const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */; + let modifiers = moveModifiers ? visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, visitor, isModifierLike); + if (facts & 2 /* HasClassOrConstructorParameterDecorators */) { + modifiers = injectClassTypeMetadata(modifiers, node); + } + const needsName = moveModifiers && !node.name || facts & 4 /* HasMemberDecorators */ || facts & 1 /* HasStaticInitializedProperties */; + const name = needsName ? node.name ?? factory2.getGeneratedNameForNode(node) : node.name; + const classDeclaration = factory2.updateClassDeclaration( + node, + modifiers, + name, + /*typeParameters*/ + void 0, + visitNodes2(node.heritageClauses, visitor, isHeritageClause), + transformClassMembers(node) + ); + let emitFlags = getEmitFlags(node); + if (facts & 1 /* HasStaticInitializedProperties */) { + emitFlags |= 64 /* NoTrailingSourceMap */; + } + setEmitFlags(classDeclaration, emitFlags); + let statement; + if (promoteToIIFE) { + const statements = [classDeclaration]; + const closingBraceLocation = createTokenRange(skipTrivia(currentSourceFile.text, node.members.end), 20 /* CloseBraceToken */); + const localName = factory2.getInternalName(node); + const outer = factory2.createPartiallyEmittedExpression(localName); + setTextRangeEnd(outer, closingBraceLocation.end); + setEmitFlags(outer, 3072 /* NoComments */); + const returnStatement = factory2.createReturnStatement(outer); + setTextRangePos(returnStatement, closingBraceLocation.pos); + setEmitFlags(returnStatement, 3072 /* NoComments */ | 768 /* NoTokenSourceMaps */); + statements.push(returnStatement); + insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); + const iife = factory2.createImmediatelyInvokedArrowFunction(statements); + setInternalEmitFlags(iife, 1 /* TypeScriptClassWrapper */); + const varDecl = factory2.createVariableDeclaration( + factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + false + ), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + iife + ); + setOriginalNode(varDecl, node); + const varStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([varDecl], 1 /* Let */) + ); + setOriginalNode(varStatement, node); + setCommentRange(varStatement, node); + setSourceMapRange(varStatement, moveRangePastDecorators(node)); + startOnNewLine(varStatement); + statement = varStatement; + } else { + statement = classDeclaration; + } + if (moveModifiers) { + if (facts & 8 /* IsExportOfNamespace */) { + return [ + statement, + createExportMemberAssignmentStatement(node) + ]; + } + if (facts & 32 /* IsDefaultExternalExport */) { + return [ + statement, + factory2.createExportDefault(factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + )) + ]; + } + if (facts & 16 /* IsNamedExternalExport */) { + return [ + statement, + factory2.createExternalModuleExport(factory2.getDeclarationName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + )) + ]; + } + } + return statement; + } + function visitClassExpression(node) { + let modifiers = visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike); + if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) { + modifiers = injectClassTypeMetadata(modifiers, node); + } + return factory2.updateClassExpression( + node, + modifiers, + node.name, + /*typeParameters*/ + void 0, + visitNodes2(node.heritageClauses, visitor, isHeritageClause), + transformClassMembers(node) + ); + } + function transformClassMembers(node) { + const members = visitNodes2(node.members, getClassElementVisitor(node), isClassElement); + let newMembers; + const constructor = getFirstConstructorWithBody(node); + const parametersWithPropertyAssignments = constructor && filter(constructor.parameters, (p) => isParameterPropertyDeclaration(p, constructor)); + if (parametersWithPropertyAssignments) { + for (const parameter of parametersWithPropertyAssignments) { + const parameterProperty = factory2.createPropertyDeclaration( + /*modifiers*/ + void 0, + parameter.name, + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ); + setOriginalNode(parameterProperty, parameter); + newMembers = append(newMembers, parameterProperty); + } + } + if (newMembers) { + newMembers = addRange(newMembers, members); + return setTextRange( + factory2.createNodeArray(newMembers), + /*location*/ + node.members + ); + } + return members; + } + function injectClassTypeMetadata(modifiers, node) { + const metadata = getTypeMetadata(node, node); + if (some(metadata)) { + const modifiersArray = []; + addRange(modifiersArray, takeWhile(modifiers, isExportOrDefaultModifier)); + addRange(modifiersArray, filter(modifiers, isDecorator)); + addRange(modifiersArray, metadata); + addRange(modifiersArray, filter(skipWhile(modifiers, isExportOrDefaultModifier), isModifier)); + modifiers = setTextRange(factory2.createNodeArray(modifiersArray), modifiers); + } + return modifiers; + } + function injectClassElementTypeMetadata(modifiers, node, container) { + if (isClassLike(container) && classElementOrClassElementParameterIsDecorated(legacyDecorators, node, container)) { + const metadata = getTypeMetadata(node, container); + if (some(metadata)) { + const modifiersArray = []; + addRange(modifiersArray, filter(modifiers, isDecorator)); + addRange(modifiersArray, metadata); + addRange(modifiersArray, filter(modifiers, isModifier)); + modifiers = setTextRange(factory2.createNodeArray(modifiersArray), modifiers); + } + } + return modifiers; + } + function getTypeMetadata(node, container) { + if (!legacyDecorators) return void 0; + return USE_NEW_TYPE_METADATA_FORMAT ? getNewTypeMetadata(node, container) : getOldTypeMetadata(node, container); + } + function getOldTypeMetadata(node, container) { + if (typeSerializer) { + let decorators; + if (shouldAddTypeMetadata(node)) { + const typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope, currentNameScope: container }, node, container)); + decorators = append(decorators, factory2.createDecorator(typeMetadata)); + } + if (shouldAddParamTypesMetadata(node)) { + const paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope, currentNameScope: container }, node, container)); + decorators = append(decorators, factory2.createDecorator(paramTypesMetadata)); + } + if (shouldAddReturnTypeMetadata(node)) { + const returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope, currentNameScope: container }, node)); + decorators = append(decorators, factory2.createDecorator(returnTypeMetadata)); + } + return decorators; + } + } + function getNewTypeMetadata(node, container) { + if (typeSerializer) { + let properties; + if (shouldAddTypeMetadata(node)) { + const typeProperty = factory2.createPropertyAssignment("type", factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + [], + /*type*/ + void 0, + factory2.createToken(39 /* EqualsGreaterThanToken */), + typeSerializer.serializeTypeOfNode({ currentLexicalScope, currentNameScope: container }, node, container) + )); + properties = append(properties, typeProperty); + } + if (shouldAddParamTypesMetadata(node)) { + const paramTypeProperty = factory2.createPropertyAssignment("paramTypes", factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + [], + /*type*/ + void 0, + factory2.createToken(39 /* EqualsGreaterThanToken */), + typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope, currentNameScope: container }, node, container) + )); + properties = append(properties, paramTypeProperty); + } + if (shouldAddReturnTypeMetadata(node)) { + const returnTypeProperty = factory2.createPropertyAssignment("returnType", factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + [], + /*type*/ + void 0, + factory2.createToken(39 /* EqualsGreaterThanToken */), + typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope, currentNameScope: container }, node) + )); + properties = append(properties, returnTypeProperty); + } + if (properties) { + const typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory2.createObjectLiteralExpression( + properties, + /*multiLine*/ + true + )); + return [factory2.createDecorator(typeInfoMetadata)]; + } + } + } + function shouldAddTypeMetadata(node) { + const kind = node.kind; + return kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 172 /* PropertyDeclaration */; + } + function shouldAddReturnTypeMetadata(node) { + return node.kind === 174 /* MethodDeclaration */; + } + function shouldAddParamTypesMetadata(node) { + switch (node.kind) { + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + return getFirstConstructorWithBody(node) !== void 0; + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return true; + } + return false; + } + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + const name = member.name; + if (isPrivateIdentifier(name)) { + return factory2.createIdentifier(""); + } else if (isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? factory2.getGeneratedNameForNode(name) : name.expression; + } else if (isIdentifier(name)) { + return factory2.createStringLiteral(idText(name)); + } else { + return factory2.cloneNode(name); + } + } + function visitPropertyNameOfClassElement(member) { + const name = member.name; + if (legacyDecorators && isComputedPropertyName(name) && hasDecorators(member)) { + const expression = visitNode(name.expression, visitor, isExpression); + Debug.assert(expression); + const innerExpression = skipPartiallyEmittedExpressions(expression); + if (!isSimpleInlineableExpression(innerExpression)) { + const generatedName = factory2.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return factory2.updateComputedPropertyName(name, factory2.createAssignment(generatedName, expression)); + } + } + return Debug.checkDefined(visitNode(name, visitor, isPropertyName)); + } + function visitHeritageClause(node) { + if (node.token === 119 /* ImplementsKeyword */) { + return void 0; + } + return visitEachChild(node, visitor, context); + } + function visitExpressionWithTypeArguments(node) { + return factory2.updateExpressionWithTypeArguments( + node, + Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression)), + /*typeArguments*/ + void 0 + ); + } + function shouldEmitFunctionLikeDeclaration(node) { + return !nodeIsMissing(node.body); + } + function visitPropertyDeclaration(node, parent) { + const isAmbient = node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 64 /* Abstract */); + if (isAmbient && !(legacyDecorators && hasDecorators(node))) { + return void 0; + } + let modifiers = isClassLike(parent) ? !isAmbient ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike); + modifiers = injectClassElementTypeMetadata(modifiers, node, parent); + if (isAmbient) { + return factory2.updatePropertyDeclaration( + node, + concatenate(modifiers, factory2.createModifiersFromModifierFlags(128 /* Ambient */)), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ); + } + return factory2.updatePropertyDeclaration( + node, + modifiers, + visitPropertyNameOfClassElement(node), + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ); + } + function visitConstructor(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return void 0; + } + return factory2.updateConstructorDeclaration( + node, + /*modifiers*/ + void 0, + visitParameterList(node.parameters, visitor, context), + transformConstructorBody(node.body, node) + ); + } + function transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements) { + const superStatementIndex = superPath[superPathDepth]; + const superStatement = statementsIn[superStatementIndex]; + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); + if (isTryStatement(superStatement)) { + const tryBlockStatements = []; + transformConstructorBodyWorker( + tryBlockStatements, + superStatement.tryBlock.statements, + /*statementOffset*/ + 0, + superPath, + superPathDepth + 1, + initializerStatements + ); + const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); + setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); + statementsOut.push(factory2.updateTryStatement( + superStatement, + factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), + visitNode(superStatement.catchClause, visitor, isCatchClause), + visitNode(superStatement.finallyBlock, visitor, isBlock) + )); + } else { + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1)); + addRange(statementsOut, initializerStatements); + } + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1)); + } + function transformConstructorBody(body, constructor) { + const parametersWithPropertyAssignments = constructor && filter(constructor.parameters, (p) => isParameterPropertyDeclaration(p, constructor)); + if (!some(parametersWithPropertyAssignments)) { + return visitFunctionBody(body, visitor, context); + } + let statements = []; + resumeLexicalEnvironment(); + const prologueStatementCount = factory2.copyPrologue( + body.statements, + statements, + /*ensureUseStrict*/ + false, + visitor + ); + const superPath = findSuperStatementIndexPath(body.statements, prologueStatementCount); + const parameterPropertyAssignments = mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment); + if (superPath.length) { + transformConstructorBodyWorker( + statements, + body.statements, + prologueStatementCount, + superPath, + /*superPathDepth*/ + 0, + parameterPropertyAssignments + ); + } else { + addRange(statements, parameterPropertyAssignments); + addRange(statements, visitNodes2(body.statements, visitor, isStatement, prologueStatementCount)); + } + statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + const block = factory2.createBlock( + setTextRange(factory2.createNodeArray(statements), body.statements), + /*multiLine*/ + true + ); + setTextRange( + block, + /*location*/ + body + ); + setOriginalNode(block, body); + return block; + } + function transformParameterWithPropertyAssignment(node) { + const name = node.name; + if (!isIdentifier(name)) { + return void 0; + } + const propertyName = setParent(setTextRange(factory2.cloneNode(name), name), name.parent); + setEmitFlags(propertyName, 3072 /* NoComments */ | 96 /* NoSourceMap */); + const localName = setParent(setTextRange(factory2.cloneNode(name), name), name.parent); + setEmitFlags(localName, 3072 /* NoComments */); + return startOnNewLine( + removeAllComments( + setTextRange( + setOriginalNode( + factory2.createExpressionStatement( + factory2.createAssignment( + setTextRange( + factory2.createPropertyAccessExpression( + factory2.createThis(), + propertyName + ), + node.name + ), + localName + ) + ), + node + ), + moveRangePos(node, -1) + ) + ) + ); + } + function visitMethodDeclaration(node, parent) { + if (!(node.transformFlags & 1 /* ContainsTypeScript */)) { + return node; + } + if (!shouldEmitFunctionLikeDeclaration(node)) { + return void 0; + } + let modifiers = isClassLike(parent) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike); + modifiers = injectClassElementTypeMetadata(modifiers, node, parent); + return factory2.updateMethodDeclaration( + node, + modifiers, + node.asteriskToken, + visitPropertyNameOfClassElement(node), + /*questionToken*/ + void 0, + /*typeParameters*/ + void 0, + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + visitFunctionBody(node.body, visitor, context) + ); + } + function shouldEmitAccessorDeclaration(node) { + return !(nodeIsMissing(node.body) && hasSyntacticModifier(node, 64 /* Abstract */)); + } + function visitGetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* ContainsTypeScript */)) { + return node; + } + if (!shouldEmitAccessorDeclaration(node)) { + return void 0; + } + let modifiers = isClassLike(parent) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike); + modifiers = injectClassElementTypeMetadata(modifiers, node, parent); + return factory2.updateGetAccessorDeclaration( + node, + modifiers, + visitPropertyNameOfClassElement(node), + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + visitFunctionBody(node.body, visitor, context) || factory2.createBlock([]) + ); + } + function visitSetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* ContainsTypeScript */)) { + return node; + } + if (!shouldEmitAccessorDeclaration(node)) { + return void 0; + } + let modifiers = isClassLike(parent) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike); + modifiers = injectClassElementTypeMetadata(modifiers, node, parent); + return factory2.updateSetAccessorDeclaration( + node, + modifiers, + visitPropertyNameOfClassElement(node), + visitParameterList(node.parameters, visitor, context), + visitFunctionBody(node.body, visitor, context) || factory2.createBlock([]) + ); + } + function visitFunctionDeclaration(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return factory2.createNotEmittedStatement(node); + } + const updated = factory2.updateFunctionDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + node.asteriskToken, + node.name, + /*typeParameters*/ + void 0, + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + visitFunctionBody(node.body, visitor, context) || factory2.createBlock([]) + ); + if (isExportOfNamespace(node)) { + const statements = [updated]; + addExportMemberAssignment(statements, node); + return statements; + } + return updated; + } + function visitFunctionExpression(node) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return factory2.createOmittedExpression(); + } + const updated = factory2.updateFunctionExpression( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + node.asteriskToken, + node.name, + /*typeParameters*/ + void 0, + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + visitFunctionBody(node.body, visitor, context) || factory2.createBlock([]) + ); + return updated; + } + function visitArrowFunction(node) { + const updated = factory2.updateArrowFunction( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + /*typeParameters*/ + void 0, + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + node.equalsGreaterThanToken, + visitFunctionBody(node.body, visitor, context) + ); + return updated; + } + function visitParameter(node) { + if (parameterIsThisKeyword(node)) { + return void 0; + } + const updated = factory2.updateParameterDeclaration( + node, + visitNodes2(node.modifiers, (node2) => isDecorator(node2) ? visitor(node2) : void 0, isModifierLike), + node.dotDotDotToken, + Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), + /*questionToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ); + if (updated !== node) { + setCommentRange(updated, node); + setTextRange(updated, moveRangePastModifiers(node)); + setSourceMapRange(updated, moveRangePastModifiers(node)); + setEmitFlags(updated.name, 64 /* NoTrailingSourceMap */); + } + return updated; + } + function visitVariableStatement(node) { + if (isExportOfNamespace(node)) { + const variables = getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return void 0; + } + return setTextRange( + factory2.createExpressionStatement( + factory2.inlineExpressions( + map(variables, transformInitializedVariable) + ) + ), + node + ); + } else { + return visitEachChild(node, visitor, context); + } + } + function transformInitializedVariable(node) { + const name = node.name; + if (isBindingPattern(name)) { + return flattenDestructuringAssignment( + node, + visitor, + context, + 0 /* All */, + /*needsValue*/ + false, + createNamespaceExportExpression + ); + } else { + return setTextRange( + factory2.createAssignment( + getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), + Debug.checkDefined(visitNode(node.initializer, visitor, isExpression)) + ), + /*location*/ + node + ); + } + } + function visitVariableDeclaration(node) { + const updated = factory2.updateVariableDeclaration( + node, + Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ); + if (node.type) { + setTypeNode(updated.name, node.type); + } + return updated; + } + function visitParenthesizedExpression(node) { + const innerExpression = skipOuterExpressions(node.expression, ~(38 /* Assertions */ | 16 /* ExpressionsWithTypeArguments */)); + if (isAssertionExpression(innerExpression) || isSatisfiesExpression(innerExpression)) { + const expression = visitNode(node.expression, visitor, isExpression); + Debug.assert(expression); + return factory2.createPartiallyEmittedExpression(expression, node); + } + return visitEachChild(node, visitor, context); + } + function visitAssertionExpression(node) { + const expression = visitNode(node.expression, visitor, isExpression); + Debug.assert(expression); + return factory2.createPartiallyEmittedExpression(expression, node); + } + function visitNonNullExpression(node) { + const expression = visitNode(node.expression, visitor, isLeftHandSideExpression); + Debug.assert(expression); + return factory2.createPartiallyEmittedExpression(expression, node); + } + function visitSatisfiesExpression(node) { + const expression = visitNode(node.expression, visitor, isExpression); + Debug.assert(expression); + return factory2.createPartiallyEmittedExpression(expression, node); + } + function visitCallExpression(node) { + return factory2.updateCallExpression( + node, + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + /*typeArguments*/ + void 0, + visitNodes2(node.arguments, visitor, isExpression) + ); + } + function visitNewExpression(node) { + return factory2.updateNewExpression( + node, + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + /*typeArguments*/ + void 0, + visitNodes2(node.arguments, visitor, isExpression) + ); + } + function visitTaggedTemplateExpression(node) { + return factory2.updateTaggedTemplateExpression( + node, + Debug.checkDefined(visitNode(node.tag, visitor, isExpression)), + /*typeArguments*/ + void 0, + Debug.checkDefined(visitNode(node.template, visitor, isTemplateLiteral)) + ); + } + function visitJsxSelfClosingElement(node) { + return factory2.updateJsxSelfClosingElement( + node, + Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)), + /*typeArguments*/ + void 0, + Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes)) + ); + } + function visitJsxJsxOpeningElement(node) { + return factory2.updateJsxOpeningElement( + node, + Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)), + /*typeArguments*/ + void 0, + Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes)) + ); + } + function shouldEmitEnumDeclaration(node) { + return !isEnumConst(node) || shouldPreserveConstEnums(compilerOptions); + } + function visitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { + return factory2.createNotEmittedStatement(node); + } + const statements = []; + let emitFlags = 4 /* AdviseOnEmitNode */; + const varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + if (moduleKind !== 4 /* System */ || currentLexicalScope !== currentSourceFile) { + emitFlags |= 1024 /* NoLeadingComments */; + } + } + const parameterName = getNamespaceParameterName(node); + const containerName = getNamespaceContainerName(node); + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( + currentNamespaceContainerName, + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ) : factory2.getDeclarationName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ); + let moduleArg = factory2.createLogicalOr( + exportName, + factory2.createAssignment( + exportName, + factory2.createObjectLiteralExpression() + ) + ); + if (isExportOfNamespace(node)) { + const localName = factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ); + moduleArg = factory2.createAssignment(localName, moduleArg); + } + const enumStatement = factory2.createExpressionStatement( + factory2.createCallExpression( + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + parameterName + )], + /*type*/ + void 0, + transformEnumBody(node, containerName) + ), + /*typeArguments*/ + void 0, + [moduleArg] + ) + ); + setOriginalNode(enumStatement, node); + if (varAdded) { + setSyntheticLeadingComments(enumStatement, void 0); + setSyntheticTrailingComments(enumStatement, void 0); + } + setTextRange(enumStatement, node); + addEmitFlags(enumStatement, emitFlags); + statements.push(enumStatement); + return statements; + } + function transformEnumBody(node, localName) { + const savedCurrentNamespaceLocalName = currentNamespaceContainerName; + currentNamespaceContainerName = localName; + const statements = []; + startLexicalEnvironment(); + const members = map(node.members, transformEnumMember); + insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); + addRange(statements, members); + currentNamespaceContainerName = savedCurrentNamespaceLocalName; + return factory2.createBlock( + setTextRange( + factory2.createNodeArray(statements), + /*location*/ + node.members + ), + /*multiLine*/ + true + ); + } + function transformEnumMember(member) { + const name = getExpressionForPropertyName( + member, + /*generateNameForComputedPropertyName*/ + false + ); + const evaluated = resolver.getEnumMemberValue(member); + const valueExpression = transformEnumMemberDeclarationValue(member, evaluated == null ? void 0 : evaluated.value); + const innerAssignment = factory2.createAssignment( + factory2.createElementAccessExpression( + currentNamespaceContainerName, + name + ), + valueExpression + ); + const outerAssignment = typeof (evaluated == null ? void 0 : evaluated.value) === "string" || (evaluated == null ? void 0 : evaluated.isSyntacticallyString) ? innerAssignment : factory2.createAssignment( + factory2.createElementAccessExpression( + currentNamespaceContainerName, + innerAssignment + ), + name + ); + return setTextRange( + factory2.createExpressionStatement( + setTextRange( + outerAssignment, + member + ) + ), + member + ); + } + function transformEnumMemberDeclarationValue(member, constantValue) { + if (constantValue !== void 0) { + return typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : constantValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(-constantValue)) : factory2.createNumericLiteral(constantValue); + } else { + enableSubstitutionForNonQualifiedEnumMembers(); + if (member.initializer) { + return Debug.checkDefined(visitNode(member.initializer, visitor, isExpression)); + } else { + return factory2.createVoidZero(); + } + } + } + function shouldEmitModuleDeclaration(nodeIn) { + const node = getParseTreeNode(nodeIn, isModuleDeclaration); + if (!node) { + return true; + } + return isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions)); + } + function recordEmittedDeclarationInScope(node) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = /* @__PURE__ */ new Map(); + } + const name = declaredNameInScope(node); + if (!currentScopeFirstDeclarationsOfName.has(name)) { + currentScopeFirstDeclarationsOfName.set(name, node); + } + } + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + const name = declaredNameInScope(node); + return currentScopeFirstDeclarationsOfName.get(name) === node; + } + return true; + } + function declaredNameInScope(node) { + Debug.assertNode(node.name, isIdentifier); + return node.name.escapedText; + } + function addVarForEnumOrModuleDeclaration(statements, node) { + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + )); + const varFlags = currentLexicalScope.kind === 307 /* SourceFile */ ? 0 /* None */ : 1 /* Let */; + const statement = factory2.createVariableStatement( + visitNodes2(node.modifiers, modifierVisitor, isModifier), + factory2.createVariableDeclarationList([varDecl], varFlags) + ); + setOriginalNode(varDecl, node); + setSyntheticLeadingComments(varDecl, void 0); + setSyntheticTrailingComments(varDecl, void 0); + setOriginalNode(statement, node); + recordEmittedDeclarationInScope(node); + if (isFirstEmittedDeclarationInScope(node)) { + if (node.kind === 266 /* EnumDeclaration */) { + setSourceMapRange(statement.declarationList, node); + } else { + setSourceMapRange(statement, node); + } + setCommentRange(statement, node); + addEmitFlags(statement, 2048 /* NoTrailingComments */); + statements.push(statement); + return true; + } + return false; + } + function visitModuleDeclaration(node) { + if (!shouldEmitModuleDeclaration(node)) { + return factory2.createNotEmittedStatement(node); + } + Debug.assertNode(node.name, isIdentifier, "A TypeScript namespace should have an Identifier name."); + enableSubstitutionForNamespaceExports(); + const statements = []; + let emitFlags = 4 /* AdviseOnEmitNode */; + const varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { + if (moduleKind !== 4 /* System */ || currentLexicalScope !== currentSourceFile) { + emitFlags |= 1024 /* NoLeadingComments */; + } + } + const parameterName = getNamespaceParameterName(node); + const containerName = getNamespaceContainerName(node); + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( + currentNamespaceContainerName, + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ) : factory2.getDeclarationName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ); + let moduleArg = factory2.createLogicalOr( + exportName, + factory2.createAssignment( + exportName, + factory2.createObjectLiteralExpression() + ) + ); + if (isExportOfNamespace(node)) { + const localName = factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ); + moduleArg = factory2.createAssignment(localName, moduleArg); + } + const moduleStatement = factory2.createExpressionStatement( + factory2.createCallExpression( + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + parameterName + )], + /*type*/ + void 0, + transformModuleBody(node, containerName) + ), + /*typeArguments*/ + void 0, + [moduleArg] + ) + ); + setOriginalNode(moduleStatement, node); + if (varAdded) { + setSyntheticLeadingComments(moduleStatement, void 0); + setSyntheticTrailingComments(moduleStatement, void 0); + } + setTextRange(moduleStatement, node); + addEmitFlags(moduleStatement, emitFlags); + statements.push(moduleStatement); + return statements; + } + function transformModuleBody(node, namespaceLocalName) { + const savedCurrentNamespaceContainerName = currentNamespaceContainerName; + const savedCurrentNamespace = currentNamespace; + const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; + currentNamespaceContainerName = namespaceLocalName; + currentNamespace = node; + currentScopeFirstDeclarationsOfName = void 0; + const statements = []; + startLexicalEnvironment(); + let statementsLocation; + let blockLocation; + if (node.body) { + if (node.body.kind === 268 /* ModuleBlock */) { + saveStateAndInvoke(node.body, (body) => addRange(statements, visitNodes2(body.statements, namespaceElementVisitor, isStatement))); + statementsLocation = node.body.statements; + blockLocation = node.body; + } else { + const result = visitModuleDeclaration(node.body); + if (result) { + if (isArray(result)) { + addRange(statements, result); + } else { + statements.push(result); + } + } + const moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = moveRangePos(moduleBlock.statements, -1); + } + } + insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); + currentNamespaceContainerName = savedCurrentNamespaceContainerName; + currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + const block = factory2.createBlock( + setTextRange( + factory2.createNodeArray(statements), + /*location*/ + statementsLocation + ), + /*multiLine*/ + true + ); + setTextRange(block, blockLocation); + if (!node.body || node.body.kind !== 268 /* ModuleBlock */) { + setEmitFlags(block, getEmitFlags(block) | 3072 /* NoComments */); + } + return block; + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 267 /* ModuleDeclaration */) { + const recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + function visitImportDeclaration(node) { + if (!node.importClause) { + return node; + } + if (node.importClause.isTypeOnly) { + return void 0; + } + const importClause = visitNode(node.importClause, visitImportClause, isImportClause); + return importClause ? factory2.updateImportDeclaration( + node, + /*modifiers*/ + void 0, + importClause, + node.moduleSpecifier, + node.attributes + ) : void 0; + } + function visitImportClause(node) { + Debug.assert(!node.isTypeOnly); + const name = shouldEmitAliasDeclaration(node) ? node.name : void 0; + const namedBindings = visitNode(node.namedBindings, visitNamedImportBindings, isNamedImportBindings); + return name || namedBindings ? factory2.updateImportClause( + node, + /*isTypeOnly*/ + false, + name, + namedBindings + ) : void 0; + } + function visitNamedImportBindings(node) { + if (node.kind === 274 /* NamespaceImport */) { + return shouldEmitAliasDeclaration(node) ? node : void 0; + } else { + const allowEmpty = compilerOptions.verbatimModuleSyntax; + const elements = visitNodes2(node.elements, visitImportSpecifier, isImportSpecifier); + return allowEmpty || some(elements) ? factory2.updateNamedImports(node, elements) : void 0; + } + } + function visitImportSpecifier(node) { + return !node.isTypeOnly && shouldEmitAliasDeclaration(node) ? node : void 0; + } + function visitExportAssignment(node) { + return compilerOptions.verbatimModuleSyntax || resolver.isValueAliasDeclaration(node) ? visitEachChild(node, visitor, context) : void 0; + } + function visitExportDeclaration(node) { + if (node.isTypeOnly) { + return void 0; + } + if (!node.exportClause || isNamespaceExport(node.exportClause)) { + return factory2.updateExportDeclaration( + node, + node.modifiers, + node.isTypeOnly, + node.exportClause, + node.moduleSpecifier, + node.attributes + ); + } + const allowEmpty = !!compilerOptions.verbatimModuleSyntax; + const exportClause = visitNode( + node.exportClause, + (bindings) => visitNamedExportBindings(bindings, allowEmpty), + isNamedExportBindings + ); + return exportClause ? factory2.updateExportDeclaration( + node, + /*modifiers*/ + void 0, + node.isTypeOnly, + exportClause, + node.moduleSpecifier, + node.attributes + ) : void 0; + } + function visitNamedExports(node, allowEmpty) { + const elements = visitNodes2(node.elements, visitExportSpecifier, isExportSpecifier); + return allowEmpty || some(elements) ? factory2.updateNamedExports(node, elements) : void 0; + } + function visitNamespaceExports(node) { + return factory2.updateNamespaceExport(node, Debug.checkDefined(visitNode(node.name, visitor, isIdentifier))); + } + function visitNamedExportBindings(node, allowEmpty) { + return isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node, allowEmpty); + } + function visitExportSpecifier(node) { + return !node.isTypeOnly && (compilerOptions.verbatimModuleSyntax || resolver.isValueAliasDeclaration(node)) ? node : void 0; + } + function shouldEmitImportEqualsDeclaration(node) { + return shouldEmitAliasDeclaration(node) || !isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node); + } + function visitImportEqualsDeclaration(node) { + if (node.isTypeOnly) { + return void 0; + } + if (isExternalModuleImportEqualsDeclaration(node)) { + if (!shouldEmitAliasDeclaration(node)) { + return void 0; + } + return visitEachChild(node, visitor, context); + } + if (!shouldEmitImportEqualsDeclaration(node)) { + return void 0; + } + const moduleReference = createExpressionFromEntityName(factory2, node.moduleReference); + setEmitFlags(moduleReference, 3072 /* NoComments */ | 4096 /* NoNestedComments */); + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { + return setOriginalNode( + setTextRange( + factory2.createVariableStatement( + visitNodes2(node.modifiers, modifierVisitor, isModifier), + factory2.createVariableDeclarationList([ + setOriginalNode( + factory2.createVariableDeclaration( + node.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + moduleReference + ), + node + ) + ]) + ), + node + ), + node + ); + } else { + return setOriginalNode( + createNamespaceExport( + node.name, + moduleReference, + node + ), + node + ); + } + } + function isExportOfNamespace(node) { + return currentNamespace !== void 0 && hasSyntacticModifier(node, 32 /* Export */); + } + function isExternalModuleExport(node) { + return currentNamespace === void 0 && hasSyntacticModifier(node, 32 /* Export */); + } + function isNamedExternalModuleExport(node) { + return isExternalModuleExport(node) && !hasSyntacticModifier(node, 2048 /* Default */); + } + function isDefaultExternalModuleExport(node) { + return isExternalModuleExport(node) && hasSyntacticModifier(node, 2048 /* Default */); + } + function createExportMemberAssignmentStatement(node) { + const expression = factory2.createAssignment( + factory2.getExternalModuleOrNamespaceExportName( + currentNamespaceContainerName, + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ), + factory2.getLocalName(node) + ); + setSourceMapRange(expression, createRange(node.name ? node.name.pos : node.pos, node.end)); + const statement = factory2.createExpressionStatement(expression); + setSourceMapRange(statement, createRange(-1, node.end)); + return statement; + } + function addExportMemberAssignment(statements, node) { + statements.push(createExportMemberAssignmentStatement(node)); + } + function createNamespaceExport(exportName, exportValue, location) { + return setTextRange( + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.getNamespaceMemberName( + currentNamespaceContainerName, + exportName, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ), + exportValue + ) + ), + location + ); + } + function createNamespaceExportExpression(exportName, exportValue, location) { + return setTextRange(factory2.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); + } + function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { + return factory2.getNamespaceMemberName( + currentNamespaceContainerName, + name, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ); + } + function getNamespaceParameterName(node) { + const name = factory2.getGeneratedNameForNode(node); + setSourceMapRange(name, node.name); + return name; + } + function getNamespaceContainerName(node) { + return factory2.getGeneratedNameForNode(node); + } + function enableSubstitutionForNonQualifiedEnumMembers() { + if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) { + enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */; + context.enableSubstitution(80 /* Identifier */); + } + } + function enableSubstitutionForNamespaceExports() { + if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { + enabledSubstitutions |= 2 /* NamespaceExports */; + context.enableSubstitution(80 /* Identifier */); + context.enableSubstitution(304 /* ShorthandPropertyAssignment */); + context.enableEmitNotification(267 /* ModuleDeclaration */); + } + } + function isTransformedModuleDeclaration(node) { + return getOriginalNode(node).kind === 267 /* ModuleDeclaration */; + } + function isTransformedEnumDeclaration(node) { + return getOriginalNode(node).kind === 266 /* EnumDeclaration */; + } + function onEmitNode(hint, node, emitCallback) { + const savedApplicableSubstitutions = applicableSubstitutions; + const savedCurrentSourceFile = currentSourceFile; + if (isSourceFile(node)) { + currentSourceFile = node; + } + if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { + applicableSubstitutions |= 2 /* NamespaceExports */; + } + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { + applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; + } + previousOnEmitNode(hint, node, emitCallback); + applicableSubstitutions = savedApplicableSubstitutions; + currentSourceFile = savedCurrentSourceFile; + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } else if (isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + if (enabledSubstitutions & 2 /* NamespaceExports */) { + const name = node.name; + const exportedName = trySubstituteNamespaceExportedName(name); + if (exportedName) { + if (node.objectAssignmentInitializer) { + const initializer = factory2.createAssignment(exportedName, node.objectAssignmentInitializer); + return setTextRange(factory2.createPropertyAssignment(name, initializer), node); + } + return setTextRange(factory2.createPropertyAssignment(name, exportedName), node); + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 80 /* Identifier */: + return substituteExpressionIdentifier(node); + case 211 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 212 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteNamespaceExportedName(node) || node; + } + function trySubstituteNamespaceExportedName(node) { + if (enabledSubstitutions & applicableSubstitutions && !isGeneratedIdentifier(node) && !isLocalName(node)) { + const container = resolver.getReferencedExportContainer( + node, + /*prefixLocals*/ + false + ); + if (container && container.kind !== 307 /* SourceFile */) { + const substitute = applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 267 /* ModuleDeclaration */ || applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 266 /* EnumDeclaration */; + if (substitute) { + return setTextRange( + factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(container), node), + /*location*/ + node + ); + } + } + } + return void 0; + } + function substitutePropertyAccessExpression(node) { + return substituteConstantValue(node); + } + function substituteElementAccessExpression(node) { + return substituteConstantValue(node); + } + function safeMultiLineComment(value) { + return value.replace(/\*\//g, "*_/"); + } + function substituteConstantValue(node) { + const constantValue = tryGetConstEnumValue(node); + if (constantValue !== void 0) { + setConstantValue(node, constantValue); + const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : constantValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(-constantValue)) : factory2.createNumericLiteral(constantValue); + if (!compilerOptions.removeComments) { + const originalNode = getOriginalNode(node, isAccessExpression); + addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, ` ${safeMultiLineComment(getTextOfNode(originalNode))} `); + } + return substitute; + } + return node; + } + function tryGetConstEnumValue(node) { + if (getIsolatedModules(compilerOptions)) { + return void 0; + } + return isPropertyAccessExpression(node) || isElementAccessExpression(node) ? resolver.getConstantValue(node) : void 0; + } + function shouldEmitAliasDeclaration(node) { + return compilerOptions.verbatimModuleSyntax || isInJSFile(node) || resolver.isReferencedAliasDeclaration(node); + } +} + +// src/compiler/transformers/classFields.ts +function transformClassFields(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + hoistVariableDeclaration, + endLexicalEnvironment, + startLexicalEnvironment, + resumeLexicalEnvironment, + addBlockScopedVariable + } = context; + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + const useDefineForClassFields = getUseDefineForClassFields(compilerOptions); + const legacyDecorators = !!compilerOptions.experimentalDecorators; + const shouldTransformInitializersUsingSet = !useDefineForClassFields; + const shouldTransformInitializersUsingDefine = useDefineForClassFields && languageVersion < 9 /* ES2022 */; + const shouldTransformInitializers = shouldTransformInitializersUsingSet || shouldTransformInitializersUsingDefine; + const shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < 9 /* ES2022 */; + const shouldTransformAutoAccessors = languageVersion < 99 /* ESNext */ ? -1 /* True */ : !useDefineForClassFields ? 3 /* Maybe */ : 0 /* False */; + const shouldTransformThisInStaticInitializers = languageVersion < 9 /* ES2022 */; + const shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && languageVersion >= 2 /* ES2015 */; + const shouldTransformAnything = shouldTransformInitializers || shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformAutoAccessors === -1 /* True */; + const previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + const previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + let shouldTransformPrivateStaticElementsInFile = false; + let enabledSubstitutions = 0 /* None */; + let classAliases; + let pendingExpressions; + let pendingStatements; + let lexicalEnvironment; + const lexicalEnvironmentMap = /* @__PURE__ */ new Map(); + const noSubstitution = /* @__PURE__ */ new Set(); + let currentClassContainer; + let currentClassElement; + let shouldSubstituteThisWithClassThis = false; + let previousShouldSubstituteThisWithClassThis = false; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + lexicalEnvironment = void 0; + shouldTransformPrivateStaticElementsInFile = !!(getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */); + if (!shouldTransformAnything && !shouldTransformPrivateStaticElementsInFile) { + return node; + } + const visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function modifierVisitor(node) { + switch (node.kind) { + case 129 /* AccessorKeyword */: + return shouldTransformAutoAccessorsInCurrentClass() ? void 0 : node; + default: + return tryCast(node, isModifier); + } + } + function visitor(node) { + if (!(node.transformFlags & 16777216 /* ContainsClassFields */) && !(node.transformFlags & 134234112 /* ContainsLexicalThisOrSuper */)) { + return node; + } + switch (node.kind) { + case 263 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 231 /* ClassExpression */: + return visitClassExpression(node); + case 175 /* ClassStaticBlockDeclaration */: + case 172 /* PropertyDeclaration */: + return Debug.fail("Use `classElementVisitor` instead."); + case 303 /* PropertyAssignment */: + return visitPropertyAssignment(node); + case 243 /* VariableStatement */: + return visitVariableStatement(node); + case 260 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 169 /* Parameter */: + return visitParameterDeclaration(node); + case 208 /* BindingElement */: + return visitBindingElement(node); + case 277 /* ExportAssignment */: + return visitExportAssignment(node); + case 81 /* PrivateIdentifier */: + return visitPrivateIdentifier(node); + case 211 /* PropertyAccessExpression */: + return visitPropertyAccessExpression(node); + case 212 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + return visitPreOrPostfixUnaryExpression( + node, + /*discarded*/ + false + ); + case 226 /* BinaryExpression */: + return visitBinaryExpression( + node, + /*discarded*/ + false + ); + case 217 /* ParenthesizedExpression */: + return visitParenthesizedExpression( + node, + /*discarded*/ + false + ); + case 213 /* CallExpression */: + return visitCallExpression(node); + case 244 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 215 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 248 /* ForStatement */: + return visitForStatement(node); + case 110 /* ThisKeyword */: + return visitThisExpression(node); + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + return setCurrentClassElementAnd( + /*classElement*/ + void 0, + fallbackVisitor, + node + ); + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: { + return setCurrentClassElementAnd( + node, + fallbackVisitor, + node + ); + } + default: + return fallbackVisitor(node); + } + } + function fallbackVisitor(node) { + return visitEachChild(node, visitor, context); + } + function discardedValueVisitor(node) { + switch (node.kind) { + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + return visitPreOrPostfixUnaryExpression( + node, + /*discarded*/ + true + ); + case 226 /* BinaryExpression */: + return visitBinaryExpression( + node, + /*discarded*/ + true + ); + case 356 /* CommaListExpression */: + return visitCommaListExpression( + node, + /*discarded*/ + true + ); + case 217 /* ParenthesizedExpression */: + return visitParenthesizedExpression( + node, + /*discarded*/ + true + ); + default: + return visitor(node); + } + } + function heritageClauseVisitor(node) { + switch (node.kind) { + case 298 /* HeritageClause */: + return visitEachChild(node, heritageClauseVisitor, context); + case 233 /* ExpressionWithTypeArguments */: + return visitExpressionWithTypeArgumentsInHeritageClause(node); + default: + return visitor(node); + } + } + function assignmentTargetVisitor(node) { + switch (node.kind) { + case 210 /* ObjectLiteralExpression */: + case 209 /* ArrayLiteralExpression */: + return visitAssignmentPattern(node); + default: + return visitor(node); + } + } + function classElementVisitor(node) { + switch (node.kind) { + case 176 /* Constructor */: + return setCurrentClassElementAnd( + node, + visitConstructorDeclaration, + node + ); + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + return setCurrentClassElementAnd( + node, + visitMethodOrAccessorDeclaration, + node + ); + case 172 /* PropertyDeclaration */: + return setCurrentClassElementAnd( + node, + visitPropertyDeclaration, + node + ); + case 175 /* ClassStaticBlockDeclaration */: + return setCurrentClassElementAnd( + node, + visitClassStaticBlockDeclaration, + node + ); + case 167 /* ComputedPropertyName */: + return visitComputedPropertyName(node); + case 240 /* SemicolonClassElement */: + return node; + default: + return isModifierLike(node) ? modifierVisitor(node) : visitor(node); + } + } + function propertyNameVisitor(node) { + switch (node.kind) { + case 167 /* ComputedPropertyName */: + return visitComputedPropertyName(node); + default: + return visitor(node); + } + } + function accessorFieldResultVisitor(node) { + switch (node.kind) { + case 172 /* PropertyDeclaration */: + return transformFieldInitializer(node); + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return classElementVisitor(node); + default: + Debug.assertMissingNode(node, "Expected node to either be a PropertyDeclaration, GetAccessorDeclaration, or SetAccessorDeclaration"); + break; + } + } + function visitPrivateIdentifier(node) { + if (!shouldTransformPrivateElementsOrClassStaticBlocks) { + return node; + } + if (isStatement(node.parent)) { + return node; + } + return setOriginalNode(factory2.createIdentifier(""), node); + } + function transformPrivateIdentifierInInExpression(node) { + const info = accessPrivateIdentifier2(node.left); + if (info) { + const receiver = visitNode(node.right, visitor, isExpression); + return setOriginalNode( + emitHelpers().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver), + node + ); + } + return visitEachChild(node, visitor, context); + } + function visitPropertyAssignment(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node); + } + return visitEachChild(node, visitor, context); + } + function visitVariableStatement(node) { + const savedPendingStatements = pendingStatements; + pendingStatements = []; + const visitedNode = visitEachChild(node, visitor, context); + const statement = some(pendingStatements) ? [visitedNode, ...pendingStatements] : visitedNode; + pendingStatements = savedPendingStatements; + return statement; + } + function visitVariableDeclaration(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node); + } + return visitEachChild(node, visitor, context); + } + function visitParameterDeclaration(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node); + } + return visitEachChild(node, visitor, context); + } + function visitBindingElement(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node); + } + return visitEachChild(node, visitor, context); + } + function visitExportAssignment(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation( + context, + node, + /*ignoreEmptyStringLiteral*/ + true, + node.isExportEquals ? "" : "default" + ); + } + return visitEachChild(node, visitor, context); + } + function injectPendingExpressions(expression) { + if (some(pendingExpressions)) { + if (isParenthesizedExpression(expression)) { + pendingExpressions.push(expression.expression); + expression = factory2.updateParenthesizedExpression(expression, factory2.inlineExpressions(pendingExpressions)); + } else { + pendingExpressions.push(expression); + expression = factory2.inlineExpressions(pendingExpressions); + } + pendingExpressions = void 0; + } + return expression; + } + function visitComputedPropertyName(node) { + const expression = visitNode(node.expression, visitor, isExpression); + return factory2.updateComputedPropertyName(node, injectPendingExpressions(expression)); + } + function visitConstructorDeclaration(node) { + if (currentClassContainer) { + return transformConstructor(node, currentClassContainer); + } + return fallbackVisitor(node); + } + function shouldTransformClassElementToWeakMap(node) { + if (shouldTransformPrivateElementsOrClassStaticBlocks) return true; + if (hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) return true; + return false; + } + function visitMethodOrAccessorDeclaration(node) { + Debug.assert(!hasDecorators(node)); + if (!isPrivateIdentifierClassElementDeclaration(node) || !shouldTransformClassElementToWeakMap(node)) { + return visitEachChild(node, classElementVisitor, context); + } + const info = accessPrivateIdentifier2(node.name); + Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + const functionName = getHoistedFunctionName(node); + if (functionName) { + getPendingExpressions().push( + factory2.createAssignment( + functionName, + factory2.createFunctionExpression( + filter(node.modifiers, (m) => isModifier(m) && !isStaticModifier(m) && !isAccessorModifier(m)), + node.asteriskToken, + functionName, + /*typeParameters*/ + void 0, + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + visitFunctionBody(node.body, visitor, context) + ) + ) + ); + } + return void 0; + } + function setCurrentClassElementAnd(classElement, visitor2, arg) { + if (classElement !== currentClassElement) { + const savedCurrentClassElement = currentClassElement; + currentClassElement = classElement; + const result = visitor2(arg); + currentClassElement = savedCurrentClassElement; + return result; + } + return visitor2(arg); + } + function getHoistedFunctionName(node) { + Debug.assert(isPrivateIdentifier(node.name)); + const info = accessPrivateIdentifier2(node.name); + Debug.assert(info, "Undeclared private name for property declaration."); + if (info.kind === "m" /* Method */) { + return info.methodName; + } + if (info.kind === "a" /* Accessor */) { + if (isGetAccessor(node)) { + return info.getterName; + } + if (isSetAccessor(node)) { + return info.setterName; + } + } + } + function tryGetClassThis() { + const lex = getClassLexicalEnvironment(); + return lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); + } + function transformAutoAccessor(node) { + const commentRange = getCommentRange(node); + const sourceMapRange = getSourceMapRange(node); + const name = node.name; + let getterName = name; + let setterName = name; + if (isComputedPropertyName(name) && !isSimpleInlineableExpression(name.expression)) { + const cacheAssignment = findComputedPropertyNameCacheAssignment(name); + if (cacheAssignment) { + getterName = factory2.updateComputedPropertyName(name, visitNode(name.expression, visitor, isExpression)); + setterName = factory2.updateComputedPropertyName(name, cacheAssignment.left); + } else { + const temp = factory2.createTempVariable(hoistVariableDeclaration); + setSourceMapRange(temp, name.expression); + const expression = visitNode(name.expression, visitor, isExpression); + const assignment = factory2.createAssignment(temp, expression); + setSourceMapRange(assignment, name.expression); + getterName = factory2.updateComputedPropertyName(name, assignment); + setterName = factory2.updateComputedPropertyName(name, temp); + } + } + const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const backingField = createAccessorPropertyBackingField(factory2, node, modifiers, node.initializer); + setOriginalNode(backingField, node); + setEmitFlags(backingField, 3072 /* NoComments */); + setSourceMapRange(backingField, sourceMapRange); + const receiver = isStatic(node) ? tryGetClassThis() ?? factory2.createThis() : factory2.createThis(); + const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName, receiver); + setOriginalNode(getter, node); + setCommentRange(getter, commentRange); + setSourceMapRange(getter, sourceMapRange); + const setterModifiers = factory2.createModifiersFromModifierFlags(modifiersToFlags(modifiers)); + const setter = createAccessorPropertySetRedirector(factory2, node, setterModifiers, setterName, receiver); + setOriginalNode(setter, node); + setEmitFlags(setter, 3072 /* NoComments */); + setSourceMapRange(setter, sourceMapRange); + return visitArray([backingField, getter, setter], accessorFieldResultVisitor, isClassElement); + } + function transformPrivateFieldInitializer(node) { + if (shouldTransformClassElementToWeakMap(node)) { + const info = accessPrivateIdentifier2(node.name); + Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + if (info.isStatic && !shouldTransformPrivateElementsOrClassStaticBlocks) { + const statement = transformPropertyOrClassStaticBlock(node, factory2.createThis()); + if (statement) { + return factory2.createClassStaticBlockDeclaration(factory2.createBlock( + [statement], + /*multiLine*/ + true + )); + } + } + return void 0; + } + if (shouldTransformInitializersUsingSet && !isStatic(node) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */) { + return factory2.updatePropertyDeclaration( + node, + visitNodes2(node.modifiers, visitor, isModifierLike), + node.name, + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ); + } + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node); + } + return factory2.updatePropertyDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + visitNode(node.name, propertyNameVisitor, isPropertyName), + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ); + } + function transformPublicFieldInitializer(node) { + if (shouldTransformInitializers && !isAutoAccessorPropertyDeclaration(node)) { + const expr = getPropertyNameExpressionIfNeeded( + node.name, + /*shouldHoist*/ + !!node.initializer || useDefineForClassFields + ); + if (expr) { + getPendingExpressions().push(...flattenCommaList(expr)); + } + if (isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks) { + const initializerStatement = transformPropertyOrClassStaticBlock(node, factory2.createThis()); + if (initializerStatement) { + const staticBlock = factory2.createClassStaticBlockDeclaration( + factory2.createBlock([initializerStatement]) + ); + setOriginalNode(staticBlock, node); + setCommentRange(staticBlock, node); + setCommentRange(initializerStatement, { pos: -1, end: -1 }); + setSyntheticLeadingComments(initializerStatement, void 0); + setSyntheticTrailingComments(initializerStatement, void 0); + return staticBlock; + } + } + return void 0; + } + return factory2.updatePropertyDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + visitNode(node.name, propertyNameVisitor, isPropertyName), + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ); + } + function transformFieldInitializer(node) { + Debug.assert(!hasDecorators(node), "Decorators should already have been transformed and elided."); + return isPrivateIdentifierClassElementDeclaration(node) ? transformPrivateFieldInitializer(node) : transformPublicFieldInitializer(node); + } + function shouldTransformAutoAccessorsInCurrentClass() { + return shouldTransformAutoAccessors === -1 /* True */ || shouldTransformAutoAccessors === 3 /* Maybe */ && !!(lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && !!(lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */); + } + function visitPropertyDeclaration(node) { + if (isAutoAccessorPropertyDeclaration(node) && (shouldTransformAutoAccessorsInCurrentClass() || hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */)) { + return transformAutoAccessor(node); + } + return transformFieldInitializer(node); + } + function shouldForceDynamicThis() { + return !!currentClassElement && hasStaticModifier(currentClassElement) && isAccessor(currentClassElement) && isAutoAccessorPropertyDeclaration(getOriginalNode(currentClassElement)); + } + function ensureDynamicThisIfNeeded(node) { + if (shouldForceDynamicThis()) { + const innerExpression = skipOuterExpressions(node); + if (innerExpression.kind === 110 /* ThisKeyword */) { + noSubstitution.add(innerExpression); + } + } + } + function createPrivateIdentifierAccess(info, receiver) { + receiver = visitNode(receiver, visitor, isExpression); + ensureDynamicThisIfNeeded(receiver); + return createPrivateIdentifierAccessHelper(info, receiver); + } + function createPrivateIdentifierAccessHelper(info, receiver) { + setCommentRange(receiver, moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return emitHelpers().createClassPrivateFieldGetHelper( + receiver, + info.brandCheckIdentifier, + info.kind, + info.getterName + ); + case "m" /* Method */: + return emitHelpers().createClassPrivateFieldGetHelper( + receiver, + info.brandCheckIdentifier, + info.kind, + info.methodName + ); + case "f" /* Field */: + return emitHelpers().createClassPrivateFieldGetHelper( + receiver, + info.brandCheckIdentifier, + info.kind, + info.isStatic ? info.variableName : void 0 + ); + case "untransformed": + return Debug.fail("Access helpers should not be created for untransformed private elements"); + default: + Debug.assertNever(info, "Unknown private element type"); + } + } + function visitPropertyAccessExpression(node) { + if (isPrivateIdentifier(node.name)) { + const privateIdentifierInfo = accessPrivateIdentifier2(node.name); + if (privateIdentifierInfo) { + return setTextRange( + setOriginalNode( + createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), + node + ), + node + ); + } + } + if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isIdentifier(node.name) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + if (facts & 1 /* ClassWasDecorated */) { + return visitInvalidSuperProperty(node); + } + if (classConstructor && superClassReference) { + const superProperty = factory2.createReflectGetCall( + superClassReference, + factory2.createStringLiteralFromNode(node.name), + classConstructor + ); + setOriginalNode(superProperty, node.expression); + setTextRange(superProperty, node.expression); + return superProperty; + } + } + return visitEachChild(node, visitor, context); + } + function visitElementAccessExpression(node) { + if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + if (facts & 1 /* ClassWasDecorated */) { + return visitInvalidSuperProperty(node); + } + if (classConstructor && superClassReference) { + const superProperty = factory2.createReflectGetCall( + superClassReference, + visitNode(node.argumentExpression, visitor, isExpression), + classConstructor + ); + setOriginalNode(superProperty, node.expression); + setTextRange(superProperty, node.expression); + return superProperty; + } + } + return visitEachChild(node, visitor, context); + } + function visitPreOrPostfixUnaryExpression(node, discarded) { + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) { + const operand = skipParentheses(node.operand); + if (isPrivateIdentifierPropertyAccessExpression(operand)) { + let info; + if (info = accessPrivateIdentifier2(operand.name)) { + const receiver = visitNode(operand.expression, visitor, isExpression); + ensureDynamicThisIfNeeded(receiver); + const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver); + let expression = createPrivateIdentifierAccess(info, readExpression); + const temp = isPrefixUnaryExpression(node) || discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration); + expression = expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, hoistVariableDeclaration, temp); + expression = createPrivateIdentifierAssignment( + info, + initializeExpression || readExpression, + expression, + 64 /* EqualsToken */ + ); + setOriginalNode(expression, node); + setTextRange(expression, node); + if (temp) { + expression = factory2.createComma(expression, temp); + setTextRange(expression, node); + } + return expression; + } + } else if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(operand) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + if (facts & 1 /* ClassWasDecorated */) { + const expression = visitInvalidSuperProperty(operand); + return isPrefixUnaryExpression(node) ? factory2.updatePrefixUnaryExpression(node, expression) : factory2.updatePostfixUnaryExpression(node, expression); + } + if (classConstructor && superClassReference) { + let setterName; + let getterName; + if (isPropertyAccessExpression(operand)) { + if (isIdentifier(operand.name)) { + getterName = setterName = factory2.createStringLiteralFromNode(operand.name); + } + } else { + if (isSimpleInlineableExpression(operand.argumentExpression)) { + getterName = setterName = operand.argumentExpression; + } else { + getterName = factory2.createTempVariable(hoistVariableDeclaration); + setterName = factory2.createAssignment(getterName, visitNode(operand.argumentExpression, visitor, isExpression)); + } + } + if (setterName && getterName) { + let expression = factory2.createReflectGetCall(superClassReference, getterName, classConstructor); + setTextRange(expression, operand); + const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration); + expression = expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, hoistVariableDeclaration, temp); + expression = factory2.createReflectSetCall(superClassReference, setterName, expression, classConstructor); + setOriginalNode(expression, node); + setTextRange(expression, node); + if (temp) { + expression = factory2.createComma(expression, temp); + setTextRange(expression, node); + } + return expression; + } + } + } + } + return visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return factory2.updateForStatement( + node, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.condition, visitor, isExpression), + visitNode(node.incrementor, discardedValueVisitor, isExpression), + visitIterationBody(node.statement, visitor, context) + ); + } + function visitExpressionStatement(node) { + return factory2.updateExpressionStatement( + node, + visitNode(node.expression, discardedValueVisitor, isExpression) + ); + } + function createCopiableReceiverExpr(receiver) { + const clone = nodeIsSynthesized(receiver) ? receiver : factory2.cloneNode(receiver); + if (receiver.kind === 110 /* ThisKeyword */ && noSubstitution.has(receiver)) { + noSubstitution.add(clone); + } + if (isSimpleInlineableExpression(receiver)) { + return { readExpression: clone, initializeExpression: void 0 }; + } + const readExpression = factory2.createTempVariable(hoistVariableDeclaration); + const initializeExpression = factory2.createAssignment(readExpression, clone); + return { readExpression, initializeExpression }; + } + function visitCallExpression(node) { + var _a; + if (isPrivateIdentifierPropertyAccessExpression(node.expression) && accessPrivateIdentifier2(node.expression.name)) { + const { thisArg, target } = factory2.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion); + if (isCallChain(node)) { + return factory2.updateCallChain( + node, + factory2.createPropertyAccessChain(visitNode(target, visitor, isExpression), node.questionDotToken, "call"), + /*questionDotToken*/ + void 0, + /*typeArguments*/ + void 0, + [visitNode(thisArg, visitor, isExpression), ...visitNodes2(node.arguments, visitor, isExpression)] + ); + } + return factory2.updateCallExpression( + node, + factory2.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "call"), + /*typeArguments*/ + void 0, + [visitNode(thisArg, visitor, isExpression), ...visitNodes2(node.arguments, visitor, isExpression)] + ); + } + if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.expression) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.classConstructor)) { + const invocation = factory2.createFunctionCallCall( + visitNode(node.expression, visitor, isExpression), + lexicalEnvironment.data.classConstructor, + visitNodes2(node.arguments, visitor, isExpression) + ); + setOriginalNode(invocation, node); + setTextRange(invocation, node); + return invocation; + } + return visitEachChild(node, visitor, context); + } + function visitTaggedTemplateExpression(node) { + var _a; + if (isPrivateIdentifierPropertyAccessExpression(node.tag) && accessPrivateIdentifier2(node.tag.name)) { + const { thisArg, target } = factory2.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion); + return factory2.updateTaggedTemplateExpression( + node, + factory2.createCallExpression( + factory2.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "bind"), + /*typeArguments*/ + void 0, + [visitNode(thisArg, visitor, isExpression)] + ), + /*typeArguments*/ + void 0, + visitNode(node.template, visitor, isTemplateLiteral) + ); + } + if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.tag) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.classConstructor)) { + const invocation = factory2.createFunctionBindCall( + visitNode(node.tag, visitor, isExpression), + lexicalEnvironment.data.classConstructor, + [] + ); + setOriginalNode(invocation, node); + setTextRange(invocation, node); + return factory2.updateTaggedTemplateExpression( + node, + invocation, + /*typeArguments*/ + void 0, + visitNode(node.template, visitor, isTemplateLiteral) + ); + } + return visitEachChild(node, visitor, context); + } + function transformClassStaticBlockDeclaration(node) { + if (lexicalEnvironment) { + lexicalEnvironmentMap.set(getOriginalNode(node), lexicalEnvironment); + } + if (shouldTransformPrivateElementsOrClassStaticBlocks) { + if (isClassThisAssignmentBlock(node)) { + const result = visitNode(node.body.statements[0].expression, visitor, isExpression); + if (isAssignmentExpression( + result, + /*excludeCompoundAssignment*/ + true + ) && result.left === result.right) { + return void 0; + } + return result; + } + if (isClassNamedEvaluationHelperBlock(node)) { + return visitNode(node.body.statements[0].expression, visitor, isExpression); + } + startLexicalEnvironment(); + let statements = setCurrentClassElementAnd( + node, + (statements2) => visitNodes2(statements2, visitor, isStatement), + node.body.statements + ); + statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + const iife = factory2.createImmediatelyInvokedArrowFunction(statements); + setOriginalNode(skipParentheses(iife.expression), node); + addEmitFlags(skipParentheses(iife.expression), 4 /* AdviseOnEmitNode */); + setOriginalNode(iife, node); + setTextRange(iife, node); + return iife; + } + } + function isAnonymousClassNeedingAssignedName(node) { + if (isClassExpression(node) && !node.name) { + const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); + if (some(staticPropertiesOrClassStaticBlocks, isClassNamedEvaluationHelperBlock)) { + return false; + } + const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || !!(getInternalEmitFlags(node) && 32 /* TransformPrivateStaticElements */)) && some(staticPropertiesOrClassStaticBlocks, (node2) => isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2)); + return hasTransformableStatics; + } + return false; + } + function visitBinaryExpression(node, discarded) { + if (isDestructuringAssignment(node)) { + const savedPendingExpressions = pendingExpressions; + pendingExpressions = void 0; + node = factory2.updateBinaryExpression( + node, + visitNode(node.left, assignmentTargetVisitor, isExpression), + node.operatorToken, + visitNode(node.right, visitor, isExpression) + ); + const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact([...pendingExpressions, node])) : node; + pendingExpressions = savedPendingExpressions; + return expr; + } + if (isAssignmentExpression(node)) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node); + Debug.assertNode(node, isAssignmentExpression); + } + const left = skipOuterExpressions(node.left, 8 /* PartiallyEmittedExpressions */ | 1 /* Parentheses */); + if (isPrivateIdentifierPropertyAccessExpression(left)) { + const info = accessPrivateIdentifier2(left.name); + if (info) { + return setTextRange( + setOriginalNode( + createPrivateIdentifierAssignment(info, left.expression, node.right, node.operatorToken.kind), + node + ), + node + ); + } + } else if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.left) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + if (facts & 1 /* ClassWasDecorated */) { + return factory2.updateBinaryExpression( + node, + visitInvalidSuperProperty(node.left), + node.operatorToken, + visitNode(node.right, visitor, isExpression) + ); + } + if (classConstructor && superClassReference) { + let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : isIdentifier(node.left.name) ? factory2.createStringLiteralFromNode(node.left.name) : void 0; + if (setterName) { + let expression = visitNode(node.right, visitor, isExpression); + if (isCompoundAssignment(node.operatorToken.kind)) { + let getterName = setterName; + if (!isSimpleInlineableExpression(setterName)) { + getterName = factory2.createTempVariable(hoistVariableDeclaration); + setterName = factory2.createAssignment(getterName, setterName); + } + const superPropertyGet = factory2.createReflectGetCall( + superClassReference, + getterName, + classConstructor + ); + setOriginalNode(superPropertyGet, node.left); + setTextRange(superPropertyGet, node.left); + expression = factory2.createBinaryExpression( + superPropertyGet, + getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), + expression + ); + setTextRange(expression, node); + } + const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration); + if (temp) { + expression = factory2.createAssignment(temp, expression); + setTextRange(temp, node); + } + expression = factory2.createReflectSetCall( + superClassReference, + setterName, + expression, + classConstructor + ); + setOriginalNode(expression, node); + setTextRange(expression, node); + if (temp) { + expression = factory2.createComma(expression, temp); + setTextRange(expression, node); + } + return expression; + } + } + } + } + if (isPrivateIdentifierInExpression(node)) { + return transformPrivateIdentifierInInExpression(node); + } + return visitEachChild(node, visitor, context); + } + function visitCommaListExpression(node, discarded) { + const elements = discarded ? visitCommaListElements(node.elements, discardedValueVisitor) : visitCommaListElements(node.elements, visitor, discardedValueVisitor); + return factory2.updateCommaListExpression(node, elements); + } + function visitParenthesizedExpression(node, discarded) { + const visitorFunc = discarded ? discardedValueVisitor : visitor; + const expression = visitNode(node.expression, visitorFunc, isExpression); + return factory2.updateParenthesizedExpression(node, expression); + } + function createPrivateIdentifierAssignment(info, receiver, right, operator) { + receiver = visitNode(receiver, visitor, isExpression); + right = visitNode(right, visitor, isExpression); + ensureDynamicThisIfNeeded(receiver); + if (isCompoundAssignment(operator)) { + const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver); + receiver = initializeExpression || readExpression; + right = factory2.createBinaryExpression( + createPrivateIdentifierAccessHelper(info, readExpression), + getNonAssignmentOperatorForCompoundAssignment(operator), + right + ); + } + setCommentRange(receiver, moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return emitHelpers().createClassPrivateFieldSetHelper( + receiver, + info.brandCheckIdentifier, + right, + info.kind, + info.setterName + ); + case "m" /* Method */: + return emitHelpers().createClassPrivateFieldSetHelper( + receiver, + info.brandCheckIdentifier, + right, + info.kind, + /*f*/ + void 0 + ); + case "f" /* Field */: + return emitHelpers().createClassPrivateFieldSetHelper( + receiver, + info.brandCheckIdentifier, + right, + info.kind, + info.isStatic ? info.variableName : void 0 + ); + case "untransformed": + return Debug.fail("Access helpers should not be created for untransformed private elements"); + default: + Debug.assertNever(info, "Unknown private element type"); + } + } + function getPrivateInstanceMethodsAndAccessors(node) { + return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName); + } + function getClassFacts(node) { + var _a; + let facts = 0 /* None */; + const original = getOriginalNode(node); + if (isClassLike(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { + facts |= 1 /* ClassWasDecorated */; + } + if (shouldTransformPrivateElementsOrClassStaticBlocks && (classHasClassThisAssignment(node) || classHasExplicitlyAssignedName(node))) { + facts |= 2 /* NeedsClassConstructorReference */; + } + let containsPublicInstanceFields = false; + let containsInitializedPublicInstanceFields = false; + let containsInstancePrivateElements = false; + let containsInstanceAutoAccessors = false; + for (const member of node.members) { + if (isStatic(member)) { + if (member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && shouldTransformPrivateElementsOrClassStaticBlocks) { + facts |= 2 /* NeedsClassConstructorReference */; + } else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === -1 /* True */ && !node.name && !((_a = node.emitNode) == null ? void 0 : _a.classThis)) { + facts |= 2 /* NeedsClassConstructorReference */; + } + if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) { + if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* ContainsLexicalThis */) { + facts |= 8 /* NeedsSubstitutionForThisInClassStaticField */; + if (!(facts & 1 /* ClassWasDecorated */)) { + facts |= 2 /* NeedsClassConstructorReference */; + } + } + if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728 /* ContainsLexicalSuper */) { + if (!(facts & 1 /* ClassWasDecorated */)) { + facts |= 2 /* NeedsClassConstructorReference */ | 4 /* NeedsClassSuperReference */; + } + } + } + } else if (!hasAbstractModifier(getOriginalNode(member))) { + if (isAutoAccessorPropertyDeclaration(member)) { + containsInstanceAutoAccessors = true; + containsInstancePrivateElements || (containsInstancePrivateElements = isPrivateIdentifierClassElementDeclaration(member)); + } else if (isPrivateIdentifierClassElementDeclaration(member)) { + containsInstancePrivateElements = true; + if (resolver.hasNodeCheckFlag(member, 262144 /* ContainsConstructorReference */)) { + facts |= 2 /* NeedsClassConstructorReference */; + } + } else if (isPropertyDeclaration(member)) { + containsPublicInstanceFields = true; + containsInitializedPublicInstanceFields || (containsInitializedPublicInstanceFields = !!member.initializer); + } + } + } + const willHoistInitializersToConstructor = shouldTransformInitializersUsingDefine && containsPublicInstanceFields || shouldTransformInitializersUsingSet && containsInitializedPublicInstanceFields || shouldTransformPrivateElementsOrClassStaticBlocks && containsInstancePrivateElements || shouldTransformPrivateElementsOrClassStaticBlocks && containsInstanceAutoAccessors && shouldTransformAutoAccessors === -1 /* True */; + if (willHoistInitializersToConstructor) { + facts |= 16 /* WillHoistInitializersToConstructor */; + } + return facts; + } + function visitExpressionWithTypeArgumentsInHeritageClause(node) { + var _a; + const facts = ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.facts) || 0 /* None */; + if (facts & 4 /* NeedsClassSuperReference */) { + const temp = factory2.createTempVariable( + hoistVariableDeclaration, + /*reservedInNestedScopes*/ + true + ); + getClassLexicalEnvironment().superClassReference = temp; + return factory2.updateExpressionWithTypeArguments( + node, + factory2.createAssignment( + temp, + visitNode(node.expression, visitor, isExpression) + ), + /*typeArguments*/ + void 0 + ); + } + return visitEachChild(node, visitor, context); + } + function visitInNewClassLexicalEnvironment(node, visitor2) { + var _a; + const savedCurrentClassContainer = currentClassContainer; + const savedPendingExpressions = pendingExpressions; + const savedLexicalEnvironment = lexicalEnvironment; + currentClassContainer = node; + pendingExpressions = void 0; + startClassLexicalEnvironment(); + const shouldAlwaysTransformPrivateStaticElements = getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */; + if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldAlwaysTransformPrivateStaticElements) { + const name = getNameOfDeclaration(node); + if (name && isIdentifier(name)) { + getPrivateIdentifierEnvironment().data.className = name; + } else if ((_a = node.emitNode) == null ? void 0 : _a.assignedName) { + if (isStringLiteral(node.emitNode.assignedName)) { + if (node.emitNode.assignedName.textSourceNode && isIdentifier(node.emitNode.assignedName.textSourceNode)) { + getPrivateIdentifierEnvironment().data.className = node.emitNode.assignedName.textSourceNode; + } else if (isIdentifierText(node.emitNode.assignedName.text, languageVersion)) { + const prefixName = factory2.createIdentifier(node.emitNode.assignedName.text); + getPrivateIdentifierEnvironment().data.className = prefixName; + } + } + } + } + if (shouldTransformPrivateElementsOrClassStaticBlocks) { + const privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + if (some(privateInstanceMethodsAndAccessors)) { + getPrivateIdentifierEnvironment().data.weakSetName = createHoistedVariableForClass( + "instances", + privateInstanceMethodsAndAccessors[0].name + ); + } + } + const facts = getClassFacts(node); + if (facts) { + getClassLexicalEnvironment().facts = facts; + } + if (facts & 8 /* NeedsSubstitutionForThisInClassStaticField */) { + enableSubstitutionForClassStaticThisOrSuperReference(); + } + const result = visitor2(node, facts); + endClassLexicalEnvironment(); + Debug.assert(lexicalEnvironment === savedLexicalEnvironment); + currentClassContainer = savedCurrentClassContainer; + pendingExpressions = savedPendingExpressions; + return result; + } + function visitClassDeclaration(node) { + return visitInNewClassLexicalEnvironment(node, visitClassDeclarationInNewClassLexicalEnvironment); + } + function visitClassDeclarationInNewClassLexicalEnvironment(node, facts) { + var _a, _b; + let pendingClassReferenceAssignment; + if (facts & 2 /* NeedsClassConstructorReference */) { + if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a = node.emitNode) == null ? void 0 : _a.classThis)) { + getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; + pendingClassReferenceAssignment = factory2.createAssignment(node.emitNode.classThis, factory2.getInternalName(node)); + } else { + const temp = factory2.createTempVariable( + hoistVariableDeclaration, + /*reservedInNestedScopes*/ + true + ); + getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp); + pendingClassReferenceAssignment = factory2.createAssignment(temp, factory2.getInternalName(node)); + } + } + if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { + getClassLexicalEnvironment().classThis = node.emitNode.classThis; + } + const isClassWithConstructorReference = resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */); + const isExport = hasSyntacticModifier(node, 32 /* Export */); + const isDefault = hasSyntacticModifier(node, 2048 /* Default */); + let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); + const { members, prologue } = transformClassMembers(node); + const statements = []; + if (pendingClassReferenceAssignment) { + getPendingExpressions().unshift(pendingClassReferenceAssignment); + } + if (some(pendingExpressions)) { + statements.push(factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions))); + } + if (shouldTransformInitializersUsingSet || shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) { + const staticProperties = getStaticPropertiesAndClassStaticBlock(node); + if (some(staticProperties)) { + addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory2.getInternalName(node)); + } + } + if (statements.length > 0 && isExport && isDefault) { + modifiers = visitNodes2(modifiers, (node2) => isExportOrDefaultModifier(node2) ? void 0 : node2, isModifier); + statements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ) + )); + } + const alias = getClassLexicalEnvironment().classConstructor; + if (isClassWithConstructorReference && alias) { + enableSubstitutionForClassAliases(); + classAliases[getOriginalNodeId(node)] = alias; + } + const classDecl = factory2.updateClassDeclaration( + node, + modifiers, + node.name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + statements.unshift(classDecl); + if (prologue) { + statements.unshift(factory2.createExpressionStatement(prologue)); + } + return statements; + } + function visitClassExpression(node) { + return visitInNewClassLexicalEnvironment(node, visitClassExpressionInNewClassLexicalEnvironment); + } + function visitClassExpressionInNewClassLexicalEnvironment(node, facts) { + var _a, _b, _c; + const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */); + const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); + const isClassWithConstructorReference = resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */); + const requiresBlockScopedVar = resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */); + let temp; + function createClassTempVar() { + var _a2; + if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) { + return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; + } + const temp2 = factory2.createTempVariable( + requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, + /*reservedInNestedScopes*/ + true + ); + getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp2); + return temp2; + } + if ((_a = node.emitNode) == null ? void 0 : _a.classThis) { + getClassLexicalEnvironment().classThis = node.emitNode.classThis; + } + if (facts & 2 /* NeedsClassConstructorReference */) { + temp ?? (temp = createClassTempVar()); + } + const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); + const { members, prologue } = transformClassMembers(node); + const classExpression = factory2.updateClassExpression( + node, + modifiers, + node.name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + const expressions = []; + if (prologue) { + expressions.push(prologue); + } + const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) && some(staticPropertiesOrClassStaticBlocks, (node2) => isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2)); + if (hasTransformableStatics || some(pendingExpressions)) { + if (isDecoratedClassDeclaration) { + Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); + if (some(pendingExpressions)) { + addRange(pendingStatements, map(pendingExpressions, factory2.createExpressionStatement)); + } + if (some(staticPropertiesOrClassStaticBlocks)) { + addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, ((_b = node.emitNode) == null ? void 0 : _b.classThis) ?? factory2.getInternalName(node)); + } + if (temp) { + expressions.push(factory2.createAssignment(temp, classExpression)); + } else if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_c = node.emitNode) == null ? void 0 : _c.classThis)) { + expressions.push(factory2.createAssignment(node.emitNode.classThis, classExpression)); + } else { + expressions.push(classExpression); + } + } else { + temp ?? (temp = createClassTempVar()); + if (isClassWithConstructorReference) { + enableSubstitutionForClassAliases(); + const alias = factory2.cloneNode(temp); + alias.emitNode.autoGenerate.flags &= ~8 /* ReservedInNestedScopes */; + classAliases[getOriginalNodeId(node)] = alias; + } + expressions.push(factory2.createAssignment(temp, classExpression)); + addRange(expressions, pendingExpressions); + addRange(expressions, generateInitializedPropertyExpressionsOrClassStaticBlock(staticPropertiesOrClassStaticBlocks, temp)); + expressions.push(factory2.cloneNode(temp)); + } + } else { + expressions.push(classExpression); + } + if (expressions.length > 1) { + addEmitFlags(classExpression, 131072 /* Indented */); + expressions.forEach(startOnNewLine); + } + return factory2.inlineExpressions(expressions); + } + function visitClassStaticBlockDeclaration(node) { + if (!shouldTransformPrivateElementsOrClassStaticBlocks) { + return visitEachChild(node, visitor, context); + } + return void 0; + } + function visitThisExpression(node) { + if (shouldTransformThisInStaticInitializers && currentClassElement && isClassStaticBlockDeclaration(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classThis, classConstructor } = lexicalEnvironment.data; + return classThis ?? classConstructor ?? node; + } + return node; + } + function transformClassMembers(node) { + const shouldTransformPrivateStaticElementsInClass = !!(getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */); + if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformPrivateStaticElementsInFile) { + for (const member of node.members) { + if (isPrivateIdentifierClassElementDeclaration(member)) { + if (shouldTransformClassElementToWeakMap(member)) { + addPrivateIdentifierToEnvironment(member, member.name, addPrivateIdentifierClassElementToEnvironment); + } else { + const privateEnv = getPrivateIdentifierEnvironment(); + setPrivateIdentifier(privateEnv, member.name, { kind: "untransformed" }); + } + } + } + if (shouldTransformPrivateElementsOrClassStaticBlocks) { + if (some(getPrivateInstanceMethodsAndAccessors(node))) { + createBrandCheckWeakSetForPrivateMethods(); + } + } + if (shouldTransformAutoAccessorsInCurrentClass()) { + for (const member of node.members) { + if (isAutoAccessorPropertyDeclaration(member)) { + const storageName = factory2.getGeneratedPrivateNameForNode( + member.name, + /*prefix*/ + void 0, + "_accessor_storage" + ); + if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformPrivateStaticElementsInClass && hasStaticModifier(member)) { + addPrivateIdentifierToEnvironment(member, storageName, addPrivateIdentifierPropertyDeclarationToEnvironment); + } else { + const privateEnv = getPrivateIdentifierEnvironment(); + setPrivateIdentifier(privateEnv, storageName, { kind: "untransformed" }); + } + } + } + } + } + let members = visitNodes2(node.members, classElementVisitor, isClassElement); + let syntheticConstructor; + if (!some(members, isConstructorDeclaration)) { + syntheticConstructor = transformConstructor( + /*constructor*/ + void 0, + node + ); + } + let prologue; + let syntheticStaticBlock; + if (!shouldTransformPrivateElementsOrClassStaticBlocks && some(pendingExpressions)) { + let statement = factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions)); + if (statement.transformFlags & 134234112 /* ContainsLexicalThisOrSuper */) { + const temp = factory2.createTempVariable(hoistVariableDeclaration); + const arrow = factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + /*parameters*/ + [], + /*type*/ + void 0, + /*equalsGreaterThanToken*/ + void 0, + factory2.createBlock([statement]) + ); + prologue = factory2.createAssignment(temp, arrow); + statement = factory2.createExpressionStatement(factory2.createCallExpression( + temp, + /*typeArguments*/ + void 0, + [] + )); + } + const block = factory2.createBlock([statement]); + syntheticStaticBlock = factory2.createClassStaticBlockDeclaration(block); + pendingExpressions = void 0; + } + if (syntheticConstructor || syntheticStaticBlock) { + let membersArray; + const classThisAssignmentBlock = find(members, isClassThisAssignmentBlock); + const classNamedEvaluationHelperBlock = find(members, isClassNamedEvaluationHelperBlock); + membersArray = append(membersArray, classThisAssignmentBlock); + membersArray = append(membersArray, classNamedEvaluationHelperBlock); + membersArray = append(membersArray, syntheticConstructor); + membersArray = append(membersArray, syntheticStaticBlock); + const remainingMembers = classThisAssignmentBlock || classNamedEvaluationHelperBlock ? filter(members, (member) => member !== classThisAssignmentBlock && member !== classNamedEvaluationHelperBlock) : members; + membersArray = addRange(membersArray, remainingMembers); + members = setTextRange( + factory2.createNodeArray(membersArray), + /*location*/ + node.members + ); + } + return { members, prologue }; + } + function createBrandCheckWeakSetForPrivateMethods() { + const { weakSetName } = getPrivateIdentifierEnvironment().data; + Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + getPendingExpressions().push( + factory2.createAssignment( + weakSetName, + factory2.createNewExpression( + factory2.createIdentifier("WeakSet"), + /*typeArguments*/ + void 0, + [] + ) + ) + ); + } + function transformConstructor(constructor, container) { + constructor = visitNode(constructor, visitor, isConstructorDeclaration); + if (!(lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) || !(lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */)) { + return constructor; + } + const extendsClauseElement = getEffectiveBaseTypeNode(container); + const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */); + const parameters = visitParameterList(constructor ? constructor.parameters : void 0, visitor, context); + const body = transformConstructorBody(container, constructor, isDerivedClass); + if (!body) { + return constructor; + } + if (constructor) { + Debug.assert(parameters); + return factory2.updateConstructorDeclaration( + constructor, + /*modifiers*/ + void 0, + parameters, + body + ); + } + return startOnNewLine( + setOriginalNode( + setTextRange( + factory2.createConstructorDeclaration( + /*modifiers*/ + void 0, + parameters ?? [], + body + ), + constructor || container + ), + constructor + ) + ); + } + function transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements, constructor) { + const superStatementIndex = superPath[superPathDepth]; + const superStatement = statementsIn[superStatementIndex]; + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); + statementOffset = superStatementIndex + 1; + if (isTryStatement(superStatement)) { + const tryBlockStatements = []; + transformConstructorBodyWorker( + tryBlockStatements, + superStatement.tryBlock.statements, + /*statementOffset*/ + 0, + superPath, + superPathDepth + 1, + initializerStatements, + constructor + ); + const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); + setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); + statementsOut.push(factory2.updateTryStatement( + superStatement, + factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), + visitNode(superStatement.catchClause, visitor, isCatchClause), + visitNode(superStatement.finallyBlock, visitor, isBlock) + )); + } else { + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1)); + while (statementOffset < statementsIn.length) { + const statement = statementsIn[statementOffset]; + if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { + statementOffset++; + } else { + break; + } + } + addRange(statementsOut, initializerStatements); + } + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset)); + } + function transformConstructorBody(node, constructor, isDerivedClass) { + var _a; + const instanceProperties = getProperties( + node, + /*requireInitializer*/ + false, + /*isStatic*/ + false + ); + let properties = instanceProperties; + if (!useDefineForClassFields) { + properties = filter(properties, (property) => !!property.initializer || isPrivateIdentifier(property.name) || hasAccessorModifier(property)); + } + const privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + const needsConstructorBody = some(properties) || some(privateMethodsAndAccessors); + if (!constructor && !needsConstructorBody) { + return visitFunctionBody( + /*node*/ + void 0, + visitor, + context + ); + } + resumeLexicalEnvironment(); + const needsSyntheticConstructor = !constructor && isDerivedClass; + let statementOffset = 0; + let statements = []; + const initializerStatements = []; + const receiver = factory2.createThis(); + addInstanceMethodStatements(initializerStatements, privateMethodsAndAccessors, receiver); + if (constructor) { + const parameterProperties = filter(instanceProperties, (prop) => isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); + const nonParameterProperties = filter(properties, (prop) => !isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); + addPropertyOrClassStaticBlockStatements(initializerStatements, parameterProperties, receiver); + addPropertyOrClassStaticBlockStatements(initializerStatements, nonParameterProperties, receiver); + } else { + addPropertyOrClassStaticBlockStatements(initializerStatements, properties, receiver); + } + if (constructor == null ? void 0 : constructor.body) { + statementOffset = factory2.copyPrologue( + constructor.body.statements, + statements, + /*ensureUseStrict*/ + false, + visitor + ); + const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, statementOffset); + if (superStatementIndices.length) { + transformConstructorBodyWorker( + statements, + constructor.body.statements, + statementOffset, + superStatementIndices, + /*superPathDepth*/ + 0, + initializerStatements, + constructor + ); + } else { + while (statementOffset < constructor.body.statements.length) { + const statement = constructor.body.statements[statementOffset]; + if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { + statementOffset++; + } else { + break; + } + } + addRange(statements, initializerStatements); + addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, statementOffset)); + } + } else { + if (needsSyntheticConstructor) { + statements.push( + factory2.createExpressionStatement( + factory2.createCallExpression( + factory2.createSuper(), + /*typeArguments*/ + void 0, + [factory2.createSpreadElement(factory2.createIdentifier("arguments"))] + ) + ) + ); + } + addRange(statements, initializerStatements); + } + statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (statements.length === 0 && !constructor) { + return void 0; + } + const multiLine = (constructor == null ? void 0 : constructor.body) && constructor.body.statements.length >= statements.length ? constructor.body.multiLine ?? statements.length > 0 : statements.length > 0; + return setTextRange( + factory2.createBlock( + setTextRange( + factory2.createNodeArray(statements), + /*location*/ + ((_a = constructor == null ? void 0 : constructor.body) == null ? void 0 : _a.statements) ?? node.members + ), + multiLine + ), + /*location*/ + constructor == null ? void 0 : constructor.body + ); + } + function addPropertyOrClassStaticBlockStatements(statements, properties, receiver) { + for (const property of properties) { + if (isStatic(property) && !shouldTransformPrivateElementsOrClassStaticBlocks) { + continue; + } + const statement = transformPropertyOrClassStaticBlock(property, receiver); + if (!statement) { + continue; + } + statements.push(statement); + } + } + function transformPropertyOrClassStaticBlock(property, receiver) { + const expression = isClassStaticBlockDeclaration(property) ? setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : transformProperty(property, receiver); + if (!expression) { + return void 0; + } + const statement = factory2.createExpressionStatement(expression); + setOriginalNode(statement, property); + addEmitFlags(statement, getEmitFlags(property) & 3072 /* NoComments */); + setCommentRange(statement, property); + const propertyOriginalNode = getOriginalNode(property); + if (isParameter(propertyOriginalNode)) { + setSourceMapRange(statement, propertyOriginalNode); + removeAllComments(statement); + } else { + setSourceMapRange(statement, moveRangePastModifiers(property)); + } + setSyntheticLeadingComments(expression, void 0); + setSyntheticTrailingComments(expression, void 0); + if (hasAccessorModifier(propertyOriginalNode)) { + addEmitFlags(statement, 3072 /* NoComments */); + } + return statement; + } + function generateInitializedPropertyExpressionsOrClassStaticBlock(propertiesOrClassStaticBlocks, receiver) { + const expressions = []; + for (const property of propertiesOrClassStaticBlocks) { + const expression = isClassStaticBlockDeclaration(property) ? setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : setCurrentClassElementAnd( + property, + () => transformProperty(property, receiver), + /*arg*/ + void 0 + ); + if (!expression) { + continue; + } + startOnNewLine(expression); + setOriginalNode(expression, property); + addEmitFlags(expression, getEmitFlags(property) & 3072 /* NoComments */); + setSourceMapRange(expression, moveRangePastModifiers(property)); + setCommentRange(expression, property); + expressions.push(expression); + } + return expressions; + } + function transformProperty(property, receiver) { + var _a; + const savedCurrentClassElement = currentClassElement; + const transformed = transformPropertyWorker(property, receiver); + if (transformed && hasStaticModifier(property) && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.facts)) { + setOriginalNode(transformed, property); + addEmitFlags(transformed, 4 /* AdviseOnEmitNode */); + setSourceMapRange(transformed, getSourceMapRange(property.name)); + lexicalEnvironmentMap.set(getOriginalNode(property), lexicalEnvironment); + } + currentClassElement = savedCurrentClassElement; + return transformed; + } + function transformPropertyWorker(property, receiver) { + const emitAssignment = !useDefineForClassFields; + if (isNamedEvaluation(property, isAnonymousClassNeedingAssignedName)) { + property = transformNamedEvaluation(context, property); + } + const propertyName = hasAccessorModifier(property) ? factory2.getGeneratedPrivateNameForNode(property.name) : isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) ? factory2.updateComputedPropertyName(property.name, factory2.getGeneratedNameForNode(property.name)) : property.name; + if (hasStaticModifier(property)) { + currentClassElement = property; + } + if (isPrivateIdentifier(propertyName) && shouldTransformClassElementToWeakMap(property)) { + const privateIdentifierInfo = accessPrivateIdentifier2(propertyName); + if (privateIdentifierInfo) { + if (privateIdentifierInfo.kind === "f" /* Field */) { + if (!privateIdentifierInfo.isStatic) { + return createPrivateInstanceFieldInitializer( + factory2, + receiver, + visitNode(property.initializer, visitor, isExpression), + privateIdentifierInfo.brandCheckIdentifier + ); + } else { + return createPrivateStaticFieldInitializer( + factory2, + privateIdentifierInfo.variableName, + visitNode(property.initializer, visitor, isExpression) + ); + } + } else { + return void 0; + } + } else { + Debug.fail("Undeclared private name for property declaration."); + } + } + if ((isPrivateIdentifier(propertyName) || hasStaticModifier(property)) && !property.initializer) { + return void 0; + } + const propertyOriginalNode = getOriginalNode(property); + if (hasSyntacticModifier(propertyOriginalNode, 64 /* Abstract */)) { + return void 0; + } + let initializer = visitNode(property.initializer, visitor, isExpression); + if (isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && isIdentifier(propertyName)) { + const localName = factory2.cloneNode(propertyName); + if (initializer) { + if (isParenthesizedExpression(initializer) && isCommaExpression(initializer.expression) && isCallToHelper(initializer.expression.left, "___runInitializers") && isVoidExpression(initializer.expression.right) && isNumericLiteral(initializer.expression.right.expression)) { + initializer = initializer.expression.left; + } + initializer = factory2.inlineExpressions([initializer, localName]); + } else { + initializer = localName; + } + setEmitFlags(propertyName, 3072 /* NoComments */ | 96 /* NoSourceMap */); + setSourceMapRange(localName, propertyOriginalNode.name); + setEmitFlags(localName, 3072 /* NoComments */); + } else { + initializer ?? (initializer = factory2.createVoidZero()); + } + if (emitAssignment || isPrivateIdentifier(propertyName)) { + const memberAccess = createMemberAccessForPropertyName( + factory2, + receiver, + propertyName, + /*location*/ + propertyName + ); + addEmitFlags(memberAccess, 1024 /* NoLeadingComments */); + const expression = factory2.createAssignment(memberAccess, initializer); + return expression; + } else { + const name = isComputedPropertyName(propertyName) ? propertyName.expression : isIdentifier(propertyName) ? factory2.createStringLiteral(unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; + const descriptor = factory2.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true }); + return factory2.createObjectDefinePropertyCall(receiver, name, descriptor); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassAliases */; + context.enableSubstitution(80 /* Identifier */); + classAliases = []; + } + } + function enableSubstitutionForClassStaticThisOrSuperReference() { + if ((enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */) === 0) { + enabledSubstitutions |= 2 /* ClassStaticThisOrSuperReference */; + context.enableSubstitution(110 /* ThisKeyword */); + context.enableEmitNotification(262 /* FunctionDeclaration */); + context.enableEmitNotification(218 /* FunctionExpression */); + context.enableEmitNotification(176 /* Constructor */); + context.enableEmitNotification(177 /* GetAccessor */); + context.enableEmitNotification(178 /* SetAccessor */); + context.enableEmitNotification(174 /* MethodDeclaration */); + context.enableEmitNotification(172 /* PropertyDeclaration */); + context.enableEmitNotification(167 /* ComputedPropertyName */); + } + } + function addInstanceMethodStatements(statements, methods, receiver) { + if (!shouldTransformPrivateElementsOrClassStaticBlocks || !some(methods)) { + return; + } + const { weakSetName } = getPrivateIdentifierEnvironment().data; + Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + statements.push( + factory2.createExpressionStatement( + createPrivateInstanceMethodInitializer(factory2, receiver, weakSetName) + ) + ); + } + function visitInvalidSuperProperty(node) { + return isPropertyAccessExpression(node) ? factory2.updatePropertyAccessExpression( + node, + factory2.createVoidZero(), + node.name + ) : factory2.updateElementAccessExpression( + node, + factory2.createVoidZero(), + visitNode(node.argumentExpression, visitor, isExpression) + ); + } + function getPropertyNameExpressionIfNeeded(name, shouldHoist) { + if (isComputedPropertyName(name)) { + const cacheAssignment = findComputedPropertyNameCacheAssignment(name); + const expression = visitNode(name.expression, visitor, isExpression); + const innerExpression = skipPartiallyEmittedExpressions(expression); + const inlinable = isSimpleInlineableExpression(innerExpression); + const alreadyTransformed = !!cacheAssignment || isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left); + if (!alreadyTransformed && !inlinable && shouldHoist) { + const generatedName = factory2.getGeneratedNameForNode(name); + if (resolver.hasNodeCheckFlag(name, 32768 /* BlockScopedBindingInLoop */)) { + addBlockScopedVariable(generatedName); + } else { + hoistVariableDeclaration(generatedName); + } + return factory2.createAssignment(generatedName, expression); + } + return inlinable || isIdentifier(innerExpression) ? void 0 : expression; + } + } + function startClassLexicalEnvironment() { + lexicalEnvironment = { previous: lexicalEnvironment, data: void 0 }; + } + function endClassLexicalEnvironment() { + lexicalEnvironment = lexicalEnvironment == null ? void 0 : lexicalEnvironment.previous; + } + function getClassLexicalEnvironment() { + Debug.assert(lexicalEnvironment); + return lexicalEnvironment.data ?? (lexicalEnvironment.data = { + facts: 0 /* None */, + classConstructor: void 0, + classThis: void 0, + superClassReference: void 0 + // privateIdentifierEnvironment: undefined, + }); + } + function getPrivateIdentifierEnvironment() { + Debug.assert(lexicalEnvironment); + return lexicalEnvironment.privateEnv ?? (lexicalEnvironment.privateEnv = newPrivateEnvironment({ + className: void 0, + weakSetName: void 0 + })); + } + function getPendingExpressions() { + return pendingExpressions ?? (pendingExpressions = []); + } + function addPrivateIdentifierClassElementToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo) { + if (isAutoAccessorPropertyDeclaration(node)) { + addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); + } else if (isPropertyDeclaration(node)) { + addPrivateIdentifierPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); + } else if (isMethodDeclaration(node)) { + addPrivateIdentifierMethodDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); + } else if (isGetAccessorDeclaration(node)) { + addPrivateIdentifierGetAccessorDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); + } else if (isSetAccessorDeclaration(node)) { + addPrivateIdentifierSetAccessorDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); + } + } + function addPrivateIdentifierPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) { + if (isStatic2) { + const brandCheckIdentifier = Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment"); + const variableName = createHoistedVariableForPrivateName(name); + setPrivateIdentifier(privateEnv, name, { + kind: "f" /* Field */, + isStatic: true, + brandCheckIdentifier, + variableName, + isValid + }); + } else { + const weakMapName = createHoistedVariableForPrivateName(name); + setPrivateIdentifier(privateEnv, name, { + kind: "f" /* Field */, + isStatic: false, + brandCheckIdentifier: weakMapName, + isValid + }); + getPendingExpressions().push(factory2.createAssignment( + weakMapName, + factory2.createNewExpression( + factory2.createIdentifier("WeakMap"), + /*typeArguments*/ + void 0, + [] + ) + )); + } + } + function addPrivateIdentifierMethodDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) { + const methodName = createHoistedVariableForPrivateName(name); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + setPrivateIdentifier(privateEnv, name, { + kind: "m" /* Method */, + methodName, + brandCheckIdentifier, + isStatic: isStatic2, + isValid + }); + } + function addPrivateIdentifierGetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, previousInfo) { + const getterName = createHoistedVariableForPrivateName(name, "_get"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + if ((previousInfo == null ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic === isStatic2 && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } else { + setPrivateIdentifier(privateEnv, name, { + kind: "a" /* Accessor */, + getterName, + setterName: void 0, + brandCheckIdentifier, + isStatic: isStatic2, + isValid + }); + } + } + function addPrivateIdentifierSetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, previousInfo) { + const setterName = createHoistedVariableForPrivateName(name, "_set"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + if ((previousInfo == null ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic === isStatic2 && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } else { + setPrivateIdentifier(privateEnv, name, { + kind: "a" /* Accessor */, + getterName: void 0, + setterName, + brandCheckIdentifier, + isStatic: isStatic2, + isValid + }); + } + } + function addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) { + const getterName = createHoistedVariableForPrivateName(name, "_get"); + const setterName = createHoistedVariableForPrivateName(name, "_set"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + setPrivateIdentifier(privateEnv, name, { + kind: "a" /* Accessor */, + getterName, + setterName, + brandCheckIdentifier, + isStatic: isStatic2, + isValid + }); + } + function addPrivateIdentifierToEnvironment(node, name, addDeclaration) { + const lex = getClassLexicalEnvironment(); + const privateEnv = getPrivateIdentifierEnvironment(); + const previousInfo = getPrivateIdentifier(privateEnv, name); + const isStatic2 = hasStaticModifier(node); + const isValid = !isReservedPrivateName(name) && previousInfo === void 0; + addDeclaration(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); + } + function createHoistedVariableForClass(name, node, suffix) { + const { className } = getPrivateIdentifierEnvironment().data; + const prefix = className ? { prefix: "_", node: className, suffix: "_" } : "_"; + const identifier = typeof name === "object" ? factory2.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */, prefix, suffix) : typeof name === "string" ? factory2.createUniqueName(name, 16 /* Optimistic */, prefix, suffix) : factory2.createTempVariable( + /*recordTempVariable*/ + void 0, + /*reservedInNestedScopes*/ + true, + prefix, + suffix + ); + if (resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */)) { + addBlockScopedVariable(identifier); + } else { + hoistVariableDeclaration(identifier); + } + return identifier; + } + function createHoistedVariableForPrivateName(name, suffix) { + const text = tryGetTextOfPropertyName(name); + return createHoistedVariableForClass((text == null ? void 0 : text.substring(1)) ?? name, name, suffix); + } + function accessPrivateIdentifier2(name) { + const info = accessPrivateIdentifier(lexicalEnvironment, name); + return (info == null ? void 0 : info.kind) === "untransformed" ? void 0 : info; + } + function wrapPrivateIdentifierForDestructuringTarget(node) { + const parameter = factory2.getGeneratedNameForNode(node); + const info = accessPrivateIdentifier2(node.name); + if (!info) { + return visitEachChild(node, visitor, context); + } + let receiver = node.expression; + if (isThisProperty(node) || isSuperProperty(node) || !isSimpleCopiableExpression(node.expression)) { + receiver = factory2.createTempVariable( + hoistVariableDeclaration, + /*reservedInNestedScopes*/ + true + ); + getPendingExpressions().push(factory2.createBinaryExpression(receiver, 64 /* EqualsToken */, visitNode(node.expression, visitor, isExpression))); + } + return factory2.createAssignmentTargetWrapper( + parameter, + createPrivateIdentifierAssignment( + info, + receiver, + parameter, + 64 /* EqualsToken */ + ) + ); + } + function visitDestructuringAssignmentTarget(node) { + if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) { + return visitAssignmentPattern(node); + } + if (isPrivateIdentifierPropertyAccessExpression(node)) { + return wrapPrivateIdentifierForDestructuringTarget(node); + } else if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { + const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + if (facts & 1 /* ClassWasDecorated */) { + return visitInvalidSuperProperty(node); + } else if (classConstructor && superClassReference) { + const name = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : isIdentifier(node.name) ? factory2.createStringLiteralFromNode(node.name) : void 0; + if (name) { + const temp = factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + return factory2.createAssignmentTargetWrapper( + temp, + factory2.createReflectSetCall( + superClassReference, + name, + temp, + classConstructor + ) + ); + } + } + } + return visitEachChild(node, visitor, context); + } + function visitAssignmentElement(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node); + } + if (isAssignmentExpression( + node, + /*excludeCompoundAssignment*/ + true + )) { + const left = visitDestructuringAssignmentTarget(node.left); + const right = visitNode(node.right, visitor, isExpression); + return factory2.updateBinaryExpression(node, left, node.operatorToken, right); + } + return visitDestructuringAssignmentTarget(node); + } + function visitAssignmentRestElement(node) { + if (isLeftHandSideExpression(node.expression)) { + const expression = visitDestructuringAssignmentTarget(node.expression); + return factory2.updateSpreadElement(node, expression); + } + return visitEachChild(node, visitor, context); + } + function visitArrayAssignmentElement(node) { + if (isArrayBindingOrAssignmentElement(node)) { + if (isSpreadElement(node)) return visitAssignmentRestElement(node); + if (!isOmittedExpression(node)) return visitAssignmentElement(node); + } + return visitEachChild(node, visitor, context); + } + function visitAssignmentProperty(node) { + const name = visitNode(node.name, visitor, isPropertyName); + if (isAssignmentExpression( + node.initializer, + /*excludeCompoundAssignment*/ + true + )) { + const assignmentElement = visitAssignmentElement(node.initializer); + return factory2.updatePropertyAssignment(node, name, assignmentElement); + } + if (isLeftHandSideExpression(node.initializer)) { + const assignmentElement = visitDestructuringAssignmentTarget(node.initializer); + return factory2.updatePropertyAssignment(node, name, assignmentElement); + } + return visitEachChild(node, visitor, context); + } + function visitShorthandAssignmentProperty(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node); + } + return visitEachChild(node, visitor, context); + } + function visitAssignmentRestProperty(node) { + if (isLeftHandSideExpression(node.expression)) { + const expression = visitDestructuringAssignmentTarget(node.expression); + return factory2.updateSpreadAssignment(node, expression); + } + return visitEachChild(node, visitor, context); + } + function visitObjectAssignmentElement(node) { + Debug.assertNode(node, isObjectBindingOrAssignmentElement); + if (isSpreadAssignment(node)) return visitAssignmentRestProperty(node); + if (isShorthandPropertyAssignment(node)) return visitShorthandAssignmentProperty(node); + if (isPropertyAssignment(node)) return visitAssignmentProperty(node); + return visitEachChild(node, visitor, context); + } + function visitAssignmentPattern(node) { + if (isArrayLiteralExpression(node)) { + return factory2.updateArrayLiteralExpression( + node, + visitNodes2(node.elements, visitArrayAssignmentElement, isExpression) + ); + } else { + return factory2.updateObjectLiteralExpression( + node, + visitNodes2(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike) + ); + } + } + function onEmitNode(hint, node, emitCallback) { + const original = getOriginalNode(node); + const lex = lexicalEnvironmentMap.get(original); + if (lex) { + const savedLexicalEnvironment = lexicalEnvironment; + const savedPreviousShouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; + lexicalEnvironment = lex; + previousShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis; + shouldSubstituteThisWithClassThis = !isClassStaticBlockDeclaration(original) || !(getInternalEmitFlags(original) & 32 /* TransformPrivateStaticElements */); + previousOnEmitNode(hint, node, emitCallback); + shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; + previousShouldSubstituteThisWithClassThis = savedPreviousShouldSubstituteThisWithClassThis; + lexicalEnvironment = savedLexicalEnvironment; + return; + } + switch (node.kind) { + case 218 /* FunctionExpression */: + if (isArrowFunction(original) || getEmitFlags(node) & 524288 /* AsyncFunctionBody */) { + break; + } + // falls through + case 262 /* FunctionDeclaration */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + case 172 /* PropertyDeclaration */: { + const savedLexicalEnvironment = lexicalEnvironment; + const savedPreviousShouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; + lexicalEnvironment = void 0; + previousShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis; + shouldSubstituteThisWithClassThis = false; + previousOnEmitNode(hint, node, emitCallback); + shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; + previousShouldSubstituteThisWithClassThis = savedPreviousShouldSubstituteThisWithClassThis; + lexicalEnvironment = savedLexicalEnvironment; + return; + } + case 167 /* ComputedPropertyName */: { + const savedLexicalEnvironment = lexicalEnvironment; + const savedShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis; + lexicalEnvironment = lexicalEnvironment == null ? void 0 : lexicalEnvironment.previous; + shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; + previousOnEmitNode(hint, node, emitCallback); + shouldSubstituteThisWithClassThis = savedShouldSubstituteThisWithClassThis; + lexicalEnvironment = savedLexicalEnvironment; + return; + } + } + previousOnEmitNode(hint, node, emitCallback); + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 80 /* Identifier */: + return substituteExpressionIdentifier(node); + case 110 /* ThisKeyword */: + return substituteThisExpression(node); + } + return node; + } + function substituteThisExpression(node) { + if (enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */ && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && !noSubstitution.has(node)) { + const { facts, classConstructor, classThis } = lexicalEnvironment.data; + const substituteThis = shouldSubstituteThisWithClassThis ? classThis ?? classConstructor : classConstructor; + if (substituteThis) { + return setTextRange( + setOriginalNode( + factory2.cloneNode(substituteThis), + node + ), + node + ); + } + if (facts & 1 /* ClassWasDecorated */ && legacyDecorators) { + return factory2.createParenthesizedExpression(factory2.createVoidZero()); + } + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1 /* ClassAliases */) { + if (resolver.hasNodeCheckFlag(node, 536870912 /* ConstructorReference */)) { + const declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + const classAlias = classAliases[declaration.id]; + if (classAlias) { + const clone = factory2.cloneNode(classAlias); + setSourceMapRange(clone, node); + setCommentRange(clone, node); + return clone; + } + } + } + } + return void 0; + } +} +function createPrivateStaticFieldInitializer(factory2, variableName, initializer) { + return factory2.createAssignment( + variableName, + factory2.createObjectLiteralExpression([ + factory2.createPropertyAssignment("value", initializer || factory2.createVoidZero()) + ]) + ); +} +function createPrivateInstanceFieldInitializer(factory2, receiver, initializer, weakMapName) { + return factory2.createCallExpression( + factory2.createPropertyAccessExpression(weakMapName, "set"), + /*typeArguments*/ + void 0, + [receiver, initializer || factory2.createVoidZero()] + ); +} +function createPrivateInstanceMethodInitializer(factory2, receiver, weakSetName) { + return factory2.createCallExpression( + factory2.createPropertyAccessExpression(weakSetName, "add"), + /*typeArguments*/ + void 0, + [receiver] + ); +} +function isReservedPrivateName(node) { + return !isGeneratedPrivateIdentifier(node) && node.escapedText === "#constructor"; +} +function isPrivateIdentifierInExpression(node) { + return isPrivateIdentifier(node.left) && node.operatorToken.kind === 103 /* InKeyword */; +} +function isStaticPropertyDeclaration2(node) { + return isPropertyDeclaration(node) && hasStaticModifier(node); +} +function isStaticPropertyDeclarationOrClassStaticBlock(node) { + return isClassStaticBlockDeclaration(node) || isStaticPropertyDeclaration2(node); +} + +// src/compiler/transformers/typeSerializer.ts +function createRuntimeTypeSerializer(context) { + const { + factory: factory2, + hoistVariableDeclaration + } = context; + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + const strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); + let currentLexicalScope; + let currentNameScope; + return { + serializeTypeNode: (serializerContext, node) => setSerializerContextAnd(serializerContext, serializeTypeNode, node), + serializeTypeOfNode: (serializerContext, node, container) => setSerializerContextAnd(serializerContext, serializeTypeOfNode, node, container), + serializeParameterTypesOfNode: (serializerContext, node, container) => setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container), + serializeReturnTypeOfNode: (serializerContext, node) => setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node) + }; + function setSerializerContextAnd(serializerContext, cb, node, arg) { + const savedCurrentLexicalScope = currentLexicalScope; + const savedCurrentNameScope = currentNameScope; + currentLexicalScope = serializerContext.currentLexicalScope; + currentNameScope = serializerContext.currentNameScope; + const result = arg === void 0 ? cb(node) : cb(node, arg); + currentLexicalScope = savedCurrentLexicalScope; + currentNameScope = savedCurrentNameScope; + return result; + } + function getAccessorTypeNode(node, container) { + const accessors = getAllAccessorDeclarations(container.members, node); + return accessors.setAccessor && getSetAccessorTypeAnnotationNode(accessors.setAccessor) || accessors.getAccessor && getEffectiveReturnTypeNode(accessors.getAccessor); + } + function serializeTypeOfNode(node, container) { + switch (node.kind) { + case 172 /* PropertyDeclaration */: + case 169 /* Parameter */: + return serializeTypeNode(node.type); + case 178 /* SetAccessor */: + case 177 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node, container)); + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 174 /* MethodDeclaration */: + return factory2.createIdentifier("Function"); + default: + return factory2.createVoidZero(); + } + } + function serializeParameterTypesOfNode(node, container) { + const valueDeclaration = isClassLike(node) ? getFirstConstructorWithBody(node) : isFunctionLike(node) && nodeIsPresent(node.body) ? node : void 0; + const expressions = []; + if (valueDeclaration) { + const parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + const numParameters = parameters.length; + for (let i = 0; i < numParameters; i++) { + const parameter = parameters[i]; + if (i === 0 && isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + } else { + expressions.push(serializeTypeOfNode(parameter, container)); + } + } + } + return factory2.createArrayLiteralExpression(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 177 /* GetAccessor */) { + const { setAccessor } = getAllAccessorDeclarations(container.members, node); + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + function serializeReturnTypeOfNode(node) { + if (isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } else if (isAsyncFunction(node)) { + return factory2.createIdentifier("Promise"); + } + return factory2.createVoidZero(); + } + function serializeTypeNode(node) { + if (node === void 0) { + return factory2.createIdentifier("Object"); + } + node = skipTypeParentheses(node); + switch (node.kind) { + case 116 /* VoidKeyword */: + case 157 /* UndefinedKeyword */: + case 146 /* NeverKeyword */: + return factory2.createVoidZero(); + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + return factory2.createIdentifier("Function"); + case 188 /* ArrayType */: + case 189 /* TupleType */: + return factory2.createIdentifier("Array"); + case 182 /* TypePredicate */: + return node.assertsModifier ? factory2.createVoidZero() : factory2.createIdentifier("Boolean"); + case 136 /* BooleanKeyword */: + return factory2.createIdentifier("Boolean"); + case 203 /* TemplateLiteralType */: + case 154 /* StringKeyword */: + return factory2.createIdentifier("String"); + case 151 /* ObjectKeyword */: + return factory2.createIdentifier("Object"); + case 201 /* LiteralType */: + return serializeLiteralOfLiteralTypeNode(node.literal); + case 150 /* NumberKeyword */: + return factory2.createIdentifier("Number"); + case 163 /* BigIntKeyword */: + return getGlobalConstructor("BigInt", 7 /* ES2020 */); + case 155 /* SymbolKeyword */: + return getGlobalConstructor("Symbol", 2 /* ES2015 */); + case 183 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 193 /* IntersectionType */: + return serializeUnionOrIntersectionConstituents( + node.types, + /*isIntersection*/ + true + ); + case 192 /* UnionType */: + return serializeUnionOrIntersectionConstituents( + node.types, + /*isIntersection*/ + false + ); + case 194 /* ConditionalType */: + return serializeUnionOrIntersectionConstituents( + [node.trueType, node.falseType], + /*isIntersection*/ + false + ); + case 198 /* TypeOperator */: + if (node.operator === 148 /* ReadonlyKeyword */) { + return serializeTypeNode(node.type); + } + break; + case 186 /* TypeQuery */: + case 199 /* IndexedAccessType */: + case 200 /* MappedType */: + case 187 /* TypeLiteral */: + case 133 /* AnyKeyword */: + case 159 /* UnknownKeyword */: + case 197 /* ThisType */: + case 205 /* ImportType */: + break; + // handle JSDoc types from an invalid parse + case 312 /* JSDocAllType */: + case 313 /* JSDocUnknownType */: + case 317 /* JSDocFunctionType */: + case 318 /* JSDocVariadicType */: + case 319 /* JSDocNamepathType */: + break; + case 314 /* JSDocNullableType */: + case 315 /* JSDocNonNullableType */: + case 316 /* JSDocOptionalType */: + return serializeTypeNode(node.type); + default: + return Debug.failBadSyntaxKind(node); + } + return factory2.createIdentifier("Object"); + } + function serializeLiteralOfLiteralTypeNode(node) { + switch (node.kind) { + case 11 /* StringLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + return factory2.createIdentifier("String"); + case 224 /* PrefixUnaryExpression */: { + const operand = node.operand; + switch (operand.kind) { + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + return serializeLiteralOfLiteralTypeNode(operand); + default: + return Debug.failBadSyntaxKind(operand); + } + } + case 9 /* NumericLiteral */: + return factory2.createIdentifier("Number"); + case 10 /* BigIntLiteral */: + return getGlobalConstructor("BigInt", 7 /* ES2020 */); + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + return factory2.createIdentifier("Boolean"); + case 106 /* NullKeyword */: + return factory2.createVoidZero(); + default: + return Debug.failBadSyntaxKind(node); + } + } + function serializeUnionOrIntersectionConstituents(types, isIntersection) { + let serializedType; + for (let typeNode of types) { + typeNode = skipTypeParentheses(typeNode); + if (typeNode.kind === 146 /* NeverKeyword */) { + if (isIntersection) return factory2.createVoidZero(); + continue; + } + if (typeNode.kind === 159 /* UnknownKeyword */) { + if (!isIntersection) return factory2.createIdentifier("Object"); + continue; + } + if (typeNode.kind === 133 /* AnyKeyword */) { + return factory2.createIdentifier("Object"); + } + if (!strictNullChecks && (isLiteralTypeNode(typeNode) && typeNode.literal.kind === 106 /* NullKeyword */ || typeNode.kind === 157 /* UndefinedKeyword */)) { + continue; + } + const serializedConstituent = serializeTypeNode(typeNode); + if (isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") { + return serializedConstituent; + } + if (serializedType) { + if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) { + return factory2.createIdentifier("Object"); + } + } else { + serializedType = serializedConstituent; + } + } + return serializedType ?? factory2.createVoidZero(); + } + function equateSerializedTypeNodes(left, right) { + return ( + // temp vars used in fallback + isGeneratedIdentifier(left) ? isGeneratedIdentifier(right) : ( + // entity names + isIdentifier(left) ? isIdentifier(right) && left.escapedText === right.escapedText : isPropertyAccessExpression(left) ? isPropertyAccessExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) && equateSerializedTypeNodes(left.name, right.name) : ( + // `void 0` + isVoidExpression(left) ? isVoidExpression(right) && isNumericLiteral(left.expression) && left.expression.text === "0" && isNumericLiteral(right.expression) && right.expression.text === "0" : ( + // `"undefined"` or `"function"` in `typeof` checks + isStringLiteral(left) ? isStringLiteral(right) && left.text === right.text : ( + // used in `typeof` checks for fallback + isTypeOfExpression(left) ? isTypeOfExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) : ( + // parens in `typeof` checks with temps + isParenthesizedExpression(left) ? isParenthesizedExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) : ( + // conditionals used in fallback + isConditionalExpression(left) ? isConditionalExpression(right) && equateSerializedTypeNodes(left.condition, right.condition) && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : ( + // logical binary and assignments used in fallback + isBinaryExpression(left) ? isBinaryExpression(right) && left.operatorToken.kind === right.operatorToken.kind && equateSerializedTypeNodes(left.left, right.left) && equateSerializedTypeNodes(left.right, right.right) : false + ) + ) + ) + ) + ) + ) + ) + ); + } + function serializeTypeReferenceNode(node) { + const kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope ?? currentLexicalScope); + switch (kind) { + case 0 /* Unknown */: + if (findAncestor(node, (n) => n.parent && isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n))) { + return factory2.createIdentifier("Object"); + } + const serialized = serializeEntityNameAsExpressionFallback(node.typeName); + const temp = factory2.createTempVariable(hoistVariableDeclaration); + return factory2.createConditionalExpression( + factory2.createTypeCheck(factory2.createAssignment(temp, serialized), "function"), + /*questionToken*/ + void 0, + temp, + /*colonToken*/ + void 0, + factory2.createIdentifier("Object") + ); + case 1 /* TypeWithConstructSignatureAndValue */: + return serializeEntityNameAsExpression(node.typeName); + case 2 /* VoidNullableOrNeverType */: + return factory2.createVoidZero(); + case 4 /* BigIntLikeType */: + return getGlobalConstructor("BigInt", 7 /* ES2020 */); + case 6 /* BooleanType */: + return factory2.createIdentifier("Boolean"); + case 3 /* NumberLikeType */: + return factory2.createIdentifier("Number"); + case 5 /* StringLikeType */: + return factory2.createIdentifier("String"); + case 7 /* ArrayLikeType */: + return factory2.createIdentifier("Array"); + case 8 /* ESSymbolType */: + return getGlobalConstructor("Symbol", 2 /* ES2015 */); + case 10 /* TypeWithCallSignature */: + return factory2.createIdentifier("Function"); + case 9 /* Promise */: + return factory2.createIdentifier("Promise"); + case 11 /* ObjectType */: + return factory2.createIdentifier("Object"); + default: + return Debug.assertNever(kind); + } + } + function createCheckedValue(left, right) { + return factory2.createLogicalAnd( + factory2.createStrictInequality(factory2.createTypeOfExpression(left), factory2.createStringLiteral("undefined")), + right + ); + } + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 80 /* Identifier */) { + const copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 80 /* Identifier */) { + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + const left = serializeEntityNameAsExpressionFallback(node.left); + const temp = factory2.createTempVariable(hoistVariableDeclaration); + return factory2.createLogicalAnd( + factory2.createLogicalAnd( + left.left, + factory2.createStrictInequality(factory2.createAssignment(temp, left.right), factory2.createVoidZero()) + ), + factory2.createPropertyAccessExpression(temp, node.right) + ); + } + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 80 /* Identifier */: + const name = setParent(setTextRange(parseNodeFactory.cloneNode(node), node), node.parent); + name.original = void 0; + setParent(name, getParseTreeNode(currentLexicalScope)); + return name; + case 166 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + function serializeQualifiedNameAsExpression(node) { + return factory2.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); + } + function getGlobalConstructorWithFallback(name) { + return factory2.createConditionalExpression( + factory2.createTypeCheck(factory2.createIdentifier(name), "function"), + /*questionToken*/ + void 0, + factory2.createIdentifier(name), + /*colonToken*/ + void 0, + factory2.createIdentifier("Object") + ); + } + function getGlobalConstructor(name, minLanguageVersion) { + return languageVersion < minLanguageVersion ? getGlobalConstructorWithFallback(name) : factory2.createIdentifier(name); + } +} + +// src/compiler/transformers/legacyDecorators.ts +function transformLegacyDecorators(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + hoistVariableDeclaration + } = context; + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + const previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + let classAliases; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + const visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function modifierVisitor(node) { + return isDecorator(node) ? void 0 : node; + } + function visitor(node) { + if (!(node.transformFlags & 33554432 /* ContainsDecorators */)) { + return node; + } + switch (node.kind) { + case 170 /* Decorator */: + return void 0; + case 263 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 231 /* ClassExpression */: + return visitClassExpression(node); + case 176 /* Constructor */: + return visitConstructorDeclaration(node); + case 174 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 178 /* SetAccessor */: + return visitSetAccessorDeclaration(node); + case 177 /* GetAccessor */: + return visitGetAccessorDeclaration(node); + case 172 /* PropertyDeclaration */: + return visitPropertyDeclaration(node); + case 169 /* Parameter */: + return visitParameterDeclaration(node); + default: + return visitEachChild(node, visitor, context); + } + } + function visitClassDeclaration(node) { + if (!(classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ + true, + node + ) || childIsDecorated( + /*useLegacyDecorators*/ + true, + node + ))) { + return visitEachChild(node, visitor, context); + } + const statements = classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ + true, + node + ) ? transformClassDeclarationWithClassDecorators(node, node.name) : transformClassDeclarationWithoutClassDecorators(node, node.name); + return singleOrMany(statements); + } + function decoratorContainsPrivateIdentifierInExpression(decorator) { + return !!(decorator.transformFlags & 536870912 /* ContainsPrivateIdentifierInExpression */); + } + function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) { + return some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression); + } + function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { + for (const member of node.members) { + if (!canHaveDecorators(member)) continue; + const allDecorators = getAllDecoratorsOfClassElement( + member, + node, + /*useLegacyDecorators*/ + true + ); + if (some(allDecorators == null ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) return true; + if (some(allDecorators == null ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) return true; + } + return false; + } + function transformDecoratorsOfClassElements(node, members) { + let decorationStatements = []; + addClassElementDecorationStatements( + decorationStatements, + node, + /*isStatic*/ + false + ); + addClassElementDecorationStatements( + decorationStatements, + node, + /*isStatic*/ + true + ); + if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { + members = setTextRange( + factory2.createNodeArray([ + ...members, + factory2.createClassStaticBlockDeclaration( + factory2.createBlock( + decorationStatements, + /*multiLine*/ + true + ) + ) + ]), + members + ); + decorationStatements = void 0; + } + return { decorationStatements, members }; + } + function transformClassDeclarationWithoutClassDecorators(node, name) { + const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); + let members = visitNodes2(node.members, visitor, isClassElement); + let decorationStatements = []; + ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members)); + const updated = factory2.updateClassDeclaration( + node, + modifiers, + name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + return addRange([updated], decorationStatements); + } + function transformClassDeclarationWithClassDecorators(node, name) { + const isExport = hasSyntacticModifier(node, 32 /* Export */); + const isDefault = hasSyntacticModifier(node, 2048 /* Default */); + const modifiers = visitNodes2(node.modifiers, (node2) => isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike); + const location = moveRangePastModifiers(node); + const classAlias = getClassAliasIfNeeded(node); + const declName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ) : factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ); + const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); + let members = visitNodes2(node.members, visitor, isClassElement); + let decorationStatements = []; + ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members)); + const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member) => isPropertyDeclaration(member) && hasSyntacticModifier(member, 256 /* Static */) || isClassStaticBlockDeclaration(member)); + if (assignClassAliasInStaticBlock) { + members = setTextRange( + factory2.createNodeArray([ + factory2.createClassStaticBlockDeclaration( + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment(classAlias, factory2.createThis()) + ) + ]) + ), + ...members + ]), + members + ); + } + const classExpression = factory2.createClassExpression( + modifiers, + name && isGeneratedIdentifier(name) ? void 0 : name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + setOriginalNode(classExpression, node); + setTextRange(classExpression, location); + const varInitializer = classAlias && !assignClassAliasInStaticBlock ? factory2.createAssignment(classAlias, classExpression) : classExpression; + const varDecl = factory2.createVariableDeclaration( + declName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + varInitializer + ); + setOriginalNode(varDecl, node); + const varDeclList = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); + const varStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + varDeclList + ); + setOriginalNode(varStatement, node); + setTextRange(varStatement, location); + setCommentRange(varStatement, node); + const statements = [varStatement]; + addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + if (isExport) { + if (isDefault) { + const exportStatement = factory2.createExportDefault(declName); + statements.push(exportStatement); + } else { + const exportStatement = factory2.createExternalModuleExport(factory2.getDeclarationName(node)); + statements.push(exportStatement); + } + } + return statements; + } + function visitClassExpression(node) { + return factory2.updateClassExpression( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + node.name, + /*typeParameters*/ + void 0, + visitNodes2(node.heritageClauses, visitor, isHeritageClause), + visitNodes2(node.members, visitor, isClassElement) + ); + } + function visitConstructorDeclaration(node) { + return factory2.updateConstructorDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + visitNodes2(node.parameters, visitor, isParameter), + visitNode(node.body, visitor, isBlock) + ); + } + function finishClassElement(updated, original) { + if (updated !== original) { + setCommentRange(updated, original); + setSourceMapRange(updated, moveRangePastModifiers(original)); + } + return updated; + } + function visitMethodDeclaration(node) { + return finishClassElement( + factory2.updateMethodDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + node.asteriskToken, + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + /*questionToken*/ + void 0, + /*typeParameters*/ + void 0, + visitNodes2(node.parameters, visitor, isParameter), + /*type*/ + void 0, + visitNode(node.body, visitor, isBlock) + ), + node + ); + } + function visitGetAccessorDeclaration(node) { + return finishClassElement( + factory2.updateGetAccessorDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + visitNodes2(node.parameters, visitor, isParameter), + /*type*/ + void 0, + visitNode(node.body, visitor, isBlock) + ), + node + ); + } + function visitSetAccessorDeclaration(node) { + return finishClassElement( + factory2.updateSetAccessorDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + visitNodes2(node.parameters, visitor, isParameter), + visitNode(node.body, visitor, isBlock) + ), + node + ); + } + function visitPropertyDeclaration(node) { + if (node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 128 /* Ambient */)) { + return void 0; + } + return finishClassElement( + factory2.updatePropertyDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifier), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ), + node + ); + } + function visitParameterDeclaration(node) { + const updated = factory2.updateParameterDeclaration( + node, + elideNodes(factory2, node.modifiers), + node.dotDotDotToken, + Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), + /*questionToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ); + if (updated !== node) { + setCommentRange(updated, node); + setTextRange(updated, moveRangePastModifiers(node)); + setSourceMapRange(updated, moveRangePastModifiers(node)); + setEmitFlags(updated.name, 64 /* NoTrailingSourceMap */); + } + return updated; + } + function isSyntheticMetadataDecorator(node) { + return isCallToHelper(node.expression, "___metadata"); + } + function transformAllDecoratorsOfDeclaration(allDecorators) { + if (!allDecorators) { + return void 0; + } + const { false: decorators, true: metadata } = groupBy(allDecorators.decorators, isSyntheticMetadataDecorator); + const decoratorExpressions = []; + addRange(decoratorExpressions, map(decorators, transformDecorator)); + addRange(decoratorExpressions, flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + addRange(decoratorExpressions, map(metadata, transformDecorator)); + return decoratorExpressions; + } + function addClassElementDecorationStatements(statements, node, isStatic2) { + addRange(statements, map(generateClassElementDecorationExpressions(node, isStatic2), (expr) => factory2.createExpressionStatement(expr))); + } + function isDecoratedClassElement(member, isStaticElement, parent) { + return nodeOrChildIsDecorated( + /*useLegacyDecorators*/ + true, + member, + parent + ) && isStaticElement === isStatic(member); + } + function getDecoratedClassElements(node, isStatic2) { + return filter(node.members, (m) => isDecoratedClassElement(m, isStatic2, node)); + } + function generateClassElementDecorationExpressions(node, isStatic2) { + const members = getDecoratedClassElements(node, isStatic2); + let expressions; + for (const member of members) { + expressions = append(expressions, generateClassElementDecorationExpression(node, member)); + } + return expressions; + } + function generateClassElementDecorationExpression(node, member) { + const allDecorators = getAllDecoratorsOfClassElement( + member, + node, + /*useLegacyDecorators*/ + true + ); + const decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return void 0; + } + const prefix = getClassMemberPrefix(node, member); + const memberName = getExpressionForPropertyName( + member, + /*generateNameForComputedPropertyName*/ + !hasSyntacticModifier(member, 128 /* Ambient */) + ); + const descriptor = isPropertyDeclaration(member) && !hasAccessorModifier(member) ? factory2.createVoidZero() : factory2.createNull(); + const helper = emitHelpers().createDecorateHelper( + decoratorExpressions, + prefix, + memberName, + descriptor + ); + setEmitFlags(helper, 3072 /* NoComments */); + setSourceMapRange(helper, moveRangePastModifiers(member)); + return helper; + } + function addConstructorDecorationStatement(statements, node) { + const expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(setOriginalNode(factory2.createExpressionStatement(expression), node)); + } + } + function generateConstructorDecorationExpression(node) { + const allDecorators = getAllDecoratorsOfClass( + node, + /*useLegacyDecorators*/ + true + ); + const decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return void 0; + } + const classAlias = classAliases && classAliases[getOriginalNodeId(node)]; + const localName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ) : factory2.getDeclarationName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ); + const decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); + const expression = factory2.createAssignment(localName, classAlias ? factory2.createAssignment(classAlias, decorate) : decorate); + setEmitFlags(expression, 3072 /* NoComments */); + setSourceMapRange(expression, moveRangePastModifiers(node)); + return expression; + } + function transformDecorator(decorator) { + return Debug.checkDefined(visitNode(decorator.expression, visitor, isExpression)); + } + function transformDecoratorsOfParameter(decorators, parameterOffset) { + let expressions; + if (decorators) { + expressions = []; + for (const decorator of decorators) { + const helper = emitHelpers().createParamHelper( + transformDecorator(decorator), + parameterOffset + ); + setTextRange(helper, decorator.expression); + setEmitFlags(helper, 3072 /* NoComments */); + expressions.push(helper); + } + } + return expressions; + } + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + const name = member.name; + if (isPrivateIdentifier(name)) { + return factory2.createIdentifier(""); + } else if (isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? factory2.getGeneratedNameForNode(name) : name.expression; + } else if (isIdentifier(name)) { + return factory2.createStringLiteral(idText(name)); + } else { + return factory2.cloneNode(name); + } + } + function enableSubstitutionForClassAliases() { + if (!classAliases) { + context.enableSubstitution(80 /* Identifier */); + classAliases = []; + } + } + function getClassAliasIfNeeded(node) { + if (resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */)) { + enableSubstitutionForClassAliases(); + const classAlias = factory2.createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? idText(node.name) : "default"); + classAliases[getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return factory2.createPropertyAccessExpression(factory2.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return isStatic(member) ? factory2.getDeclarationName(node) : getClassPrototype(node); + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 80 /* Identifier */: + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) ?? node; + } + function trySubstituteClassAlias(node) { + if (classAliases) { + if (resolver.hasNodeCheckFlag(node, 536870912 /* ConstructorReference */)) { + const declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + const classAlias = classAliases[declaration.id]; + if (classAlias) { + const clone = factory2.cloneNode(classAlias); + setSourceMapRange(clone, node); + setCommentRange(clone, node); + return clone; + } + } + } + } + return void 0; + } +} + +// src/compiler/transformers/esDecorators.ts +function transformESDecorators(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + startLexicalEnvironment, + endLexicalEnvironment, + hoistVariableDeclaration + } = context; + const languageVersion = getEmitScriptTarget(context.getCompilerOptions()); + let top; + let classInfo; + let classThis; + let classSuper; + let pendingExpressions; + let shouldTransformPrivateStaticElementsInFile; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + top = void 0; + shouldTransformPrivateStaticElementsInFile = false; + const visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + if (shouldTransformPrivateStaticElementsInFile) { + addInternalEmitFlags(visited, 32 /* TransformPrivateStaticElements */); + shouldTransformPrivateStaticElementsInFile = false; + } + return visited; + } + function updateState() { + classInfo = void 0; + classThis = void 0; + classSuper = void 0; + switch (top == null ? void 0 : top.kind) { + case "class": + classInfo = top.classInfo; + break; + case "class-element": + classInfo = top.next.classInfo; + classThis = top.classThis; + classSuper = top.classSuper; + break; + case "name": + const grandparent = top.next.next.next; + if ((grandparent == null ? void 0 : grandparent.kind) === "class-element") { + classInfo = grandparent.next.classInfo; + classThis = grandparent.classThis; + classSuper = grandparent.classSuper; + } + break; + } + } + function enterClass(classInfo2) { + top = { kind: "class", next: top, classInfo: classInfo2, savedPendingExpressions: pendingExpressions }; + pendingExpressions = void 0; + updateState(); + } + function exitClass() { + Debug.assert((top == null ? void 0 : top.kind) === "class", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class' but got '${top == null ? void 0 : top.kind}' instead.`); + pendingExpressions = top.savedPendingExpressions; + top = top.next; + updateState(); + } + function enterClassElement(node) { + var _a, _b; + Debug.assert((top == null ? void 0 : top.kind) === "class", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class' but got '${top == null ? void 0 : top.kind}' instead.`); + top = { kind: "class-element", next: top }; + if (isClassStaticBlockDeclaration(node) || isPropertyDeclaration(node) && hasStaticModifier(node)) { + top.classThis = (_a = top.next.classInfo) == null ? void 0 : _a.classThis; + top.classSuper = (_b = top.next.classInfo) == null ? void 0 : _b.classSuper; + } + updateState(); + } + function exitClassElement() { + var _a; + Debug.assert((top == null ? void 0 : top.kind) === "class-element", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class-element' but got '${top == null ? void 0 : top.kind}' instead.`); + Debug.assert(((_a = top.next) == null ? void 0 : _a.kind) === "class", "Incorrect value for top.next.kind.", () => { + var _a2; + return `Expected top.next.kind to be 'class' but got '${(_a2 = top.next) == null ? void 0 : _a2.kind}' instead.`; + }); + top = top.next; + updateState(); + } + function enterName() { + Debug.assert((top == null ? void 0 : top.kind) === "class-element", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class-element' but got '${top == null ? void 0 : top.kind}' instead.`); + top = { kind: "name", next: top }; + updateState(); + } + function exitName() { + Debug.assert((top == null ? void 0 : top.kind) === "name", "Incorrect value for top.kind.", () => `Expected top.kind to be 'name' but got '${top == null ? void 0 : top.kind}' instead.`); + top = top.next; + updateState(); + } + function enterOther() { + if ((top == null ? void 0 : top.kind) === "other") { + Debug.assert(!pendingExpressions); + top.depth++; + } else { + top = { kind: "other", next: top, depth: 0, savedPendingExpressions: pendingExpressions }; + pendingExpressions = void 0; + updateState(); + } + } + function exitOther() { + Debug.assert((top == null ? void 0 : top.kind) === "other", "Incorrect value for top.kind.", () => `Expected top.kind to be 'other' but got '${top == null ? void 0 : top.kind}' instead.`); + if (top.depth > 0) { + Debug.assert(!pendingExpressions); + top.depth--; + } else { + pendingExpressions = top.savedPendingExpressions; + top = top.next; + updateState(); + } + } + function shouldVisitNode(node) { + return !!(node.transformFlags & 33554432 /* ContainsDecorators */) || !!classThis && !!(node.transformFlags & 16384 /* ContainsLexicalThis */) || !!classThis && !!classSuper && !!(node.transformFlags & 134217728 /* ContainsLexicalSuper */); + } + function visitor(node) { + if (!shouldVisitNode(node)) { + return node; + } + switch (node.kind) { + case 170 /* Decorator */: + return Debug.fail("Use `modifierVisitor` instead."); + case 263 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 231 /* ClassExpression */: + return visitClassExpression(node); + case 176 /* Constructor */: + case 172 /* PropertyDeclaration */: + case 175 /* ClassStaticBlockDeclaration */: + return Debug.fail("Not supported outside of a class. Use 'classElementVisitor' instead."); + case 169 /* Parameter */: + return visitParameterDeclaration(node); + // Support NamedEvaluation to ensure the correct class name for class expressions. + case 226 /* BinaryExpression */: + return visitBinaryExpression( + node, + /*discarded*/ + false + ); + case 303 /* PropertyAssignment */: + return visitPropertyAssignment(node); + case 260 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 208 /* BindingElement */: + return visitBindingElement(node); + case 277 /* ExportAssignment */: + return visitExportAssignment(node); + case 110 /* ThisKeyword */: + return visitThisExpression(node); + case 248 /* ForStatement */: + return visitForStatement(node); + case 244 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 356 /* CommaListExpression */: + return visitCommaListExpression( + node, + /*discarded*/ + false + ); + case 217 /* ParenthesizedExpression */: + return visitParenthesizedExpression( + node, + /*discarded*/ + false + ); + case 355 /* PartiallyEmittedExpression */: + return visitPartiallyEmittedExpression( + node, + /*discarded*/ + false + ); + case 213 /* CallExpression */: + return visitCallExpression(node); + case 215 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + return visitPreOrPostfixUnaryExpression( + node, + /*discarded*/ + false + ); + case 211 /* PropertyAccessExpression */: + return visitPropertyAccessExpression(node); + case 212 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 167 /* ComputedPropertyName */: + return visitComputedPropertyName(node); + case 174 /* MethodDeclaration */: + // object literal methods and accessors + case 178 /* SetAccessor */: + case 177 /* GetAccessor */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: { + enterOther(); + const result = visitEachChild(node, fallbackVisitor, context); + exitOther(); + return result; + } + default: + return visitEachChild(node, fallbackVisitor, context); + } + } + function fallbackVisitor(node) { + switch (node.kind) { + case 170 /* Decorator */: + return void 0; + default: + return visitor(node); + } + } + function modifierVisitor(node) { + switch (node.kind) { + case 170 /* Decorator */: + return void 0; + default: + return node; + } + } + function classElementVisitor(node) { + switch (node.kind) { + case 176 /* Constructor */: + return visitConstructorDeclaration(node); + case 174 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 177 /* GetAccessor */: + return visitGetAccessorDeclaration(node); + case 178 /* SetAccessor */: + return visitSetAccessorDeclaration(node); + case 172 /* PropertyDeclaration */: + return visitPropertyDeclaration(node); + case 175 /* ClassStaticBlockDeclaration */: + return visitClassStaticBlockDeclaration(node); + default: + return visitor(node); + } + } + function discardedValueVisitor(node) { + switch (node.kind) { + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + return visitPreOrPostfixUnaryExpression( + node, + /*discarded*/ + true + ); + case 226 /* BinaryExpression */: + return visitBinaryExpression( + node, + /*discarded*/ + true + ); + case 356 /* CommaListExpression */: + return visitCommaListExpression( + node, + /*discarded*/ + true + ); + case 217 /* ParenthesizedExpression */: + return visitParenthesizedExpression( + node, + /*discarded*/ + true + ); + default: + return visitor(node); + } + } + function getHelperVariableName(node) { + let declarationName = node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name) : node.name && isPrivateIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name).slice(1) : node.name && isStringLiteral(node.name) && isIdentifierText(node.name.text, 99 /* ESNext */) ? node.name.text : isClassLike(node) ? "class" : "member"; + if (isGetAccessor(node)) declarationName = `get_${declarationName}`; + if (isSetAccessor(node)) declarationName = `set_${declarationName}`; + if (node.name && isPrivateIdentifier(node.name)) declarationName = `private_${declarationName}`; + if (isStatic(node)) declarationName = `static_${declarationName}`; + return "_" + declarationName; + } + function createHelperVariable(node, suffix) { + return factory2.createUniqueName(`${getHelperVariableName(node)}_${suffix}`, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */); + } + function createLet(name, initializer) { + return factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + initializer + ) + ], 1 /* Let */) + ); + } + function createClassInfo(node) { + const metadataReference = factory2.createUniqueName("_metadata", 16 /* Optimistic */ | 32 /* FileLevel */); + let instanceMethodExtraInitializersName; + let staticMethodExtraInitializersName; + let hasStaticInitializers = false; + let hasNonAmbientInstanceFields = false; + let hasStaticPrivateClassElements = false; + let classThis2; + let pendingStaticInitializers; + let pendingInstanceInitializers; + if (nodeIsDecorated( + /*useLegacyDecorators*/ + false, + node + )) { + const needsUniqueClassThis = some(node.members, (member) => (isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)); + classThis2 = factory2.createUniqueName( + "_classThis", + needsUniqueClassThis ? 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */ : 16 /* Optimistic */ | 32 /* FileLevel */ + ); + } + for (const member of node.members) { + if (isMethodOrAccessor(member) && nodeOrChildIsDecorated( + /*useLegacyDecorators*/ + false, + member, + node + )) { + if (hasStaticModifier(member)) { + if (!staticMethodExtraInitializersName) { + staticMethodExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */); + const initializer = emitHelpers().createRunInitializersHelper(classThis2 ?? factory2.createThis(), staticMethodExtraInitializersName); + setSourceMapRange(initializer, node.name ?? moveRangePastDecorators(node)); + pendingStaticInitializers ?? (pendingStaticInitializers = []); + pendingStaticInitializers.push(initializer); + } + } else { + if (!instanceMethodExtraInitializersName) { + instanceMethodExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */); + const initializer = emitHelpers().createRunInitializersHelper(factory2.createThis(), instanceMethodExtraInitializersName); + setSourceMapRange(initializer, node.name ?? moveRangePastDecorators(node)); + pendingInstanceInitializers ?? (pendingInstanceInitializers = []); + pendingInstanceInitializers.push(initializer); + } + instanceMethodExtraInitializersName ?? (instanceMethodExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */)); + } + } + if (isClassStaticBlockDeclaration(member)) { + if (!isClassNamedEvaluationHelperBlock(member)) { + hasStaticInitializers = true; + } + } else if (isPropertyDeclaration(member)) { + if (hasStaticModifier(member)) { + hasStaticInitializers || (hasStaticInitializers = !!member.initializer || hasDecorators(member)); + } else { + hasNonAmbientInstanceFields || (hasNonAmbientInstanceFields = !isAmbientPropertyDeclaration(member)); + } + } + if ((isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)) { + hasStaticPrivateClassElements = true; + } + if (staticMethodExtraInitializersName && instanceMethodExtraInitializersName && hasStaticInitializers && hasNonAmbientInstanceFields && hasStaticPrivateClassElements) { + break; + } + } + return { + class: node, + classThis: classThis2, + metadataReference, + instanceMethodExtraInitializersName, + staticMethodExtraInitializersName, + hasStaticInitializers, + hasNonAmbientInstanceFields, + hasStaticPrivateClassElements, + pendingStaticInitializers, + pendingInstanceInitializers + }; + } + function transformClassLike(node) { + startLexicalEnvironment(); + if (!classHasDeclaredOrExplicitlyAssignedName(node) && classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ + false, + node + )) { + node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, factory2.createStringLiteral("")); + } + const classReference = factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + false, + /*ignoreAssignedName*/ + true + ); + const classInfo2 = createClassInfo(node); + const classDefinitionStatements = []; + let leadingBlockStatements; + let trailingBlockStatements; + let syntheticConstructor; + let heritageClauses; + let shouldTransformPrivateStaticElementsInClass = false; + const classDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClass( + node, + /*useLegacyDecorators*/ + false + )); + if (classDecorators) { + classInfo2.classDecoratorsName = factory2.createUniqueName("_classDecorators", 16 /* Optimistic */ | 32 /* FileLevel */); + classInfo2.classDescriptorName = factory2.createUniqueName("_classDescriptor", 16 /* Optimistic */ | 32 /* FileLevel */); + classInfo2.classExtraInitializersName = factory2.createUniqueName("_classExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */); + Debug.assertIsDefined(classInfo2.classThis); + classDefinitionStatements.push( + createLet(classInfo2.classDecoratorsName, factory2.createArrayLiteralExpression(classDecorators)), + createLet(classInfo2.classDescriptorName), + createLet(classInfo2.classExtraInitializersName, factory2.createArrayLiteralExpression()), + createLet(classInfo2.classThis) + ); + if (classInfo2.hasStaticPrivateClassElements) { + shouldTransformPrivateStaticElementsInClass = true; + shouldTransformPrivateStaticElementsInFile = true; + } + } + const extendsClause = getHeritageClause(node.heritageClauses, 96 /* ExtendsKeyword */); + const extendsElement = extendsClause && firstOrUndefined(extendsClause.types); + const extendsExpression = extendsElement && visitNode(extendsElement.expression, visitor, isExpression); + if (extendsExpression) { + classInfo2.classSuper = factory2.createUniqueName("_classSuper", 16 /* Optimistic */ | 32 /* FileLevel */); + const unwrapped = skipOuterExpressions(extendsExpression); + const safeExtendsExpression = isClassExpression(unwrapped) && !unwrapped.name || isFunctionExpression(unwrapped) && !unwrapped.name || isArrowFunction(unwrapped) ? factory2.createComma(factory2.createNumericLiteral(0), extendsExpression) : extendsExpression; + classDefinitionStatements.push(createLet(classInfo2.classSuper, safeExtendsExpression)); + const updatedExtendsElement = factory2.updateExpressionWithTypeArguments( + extendsElement, + classInfo2.classSuper, + /*typeArguments*/ + void 0 + ); + const updatedExtendsClause = factory2.updateHeritageClause(extendsClause, [updatedExtendsElement]); + heritageClauses = factory2.createNodeArray([updatedExtendsClause]); + } + const renamedClassThis = classInfo2.classThis ?? factory2.createThis(); + enterClass(classInfo2); + leadingBlockStatements = append(leadingBlockStatements, createMetadata(classInfo2.metadataReference, classInfo2.classSuper)); + let members = node.members; + members = visitNodes2(members, (node2) => isConstructorDeclaration(node2) ? node2 : classElementVisitor(node2), isClassElement); + members = visitNodes2(members, (node2) => isConstructorDeclaration(node2) ? classElementVisitor(node2) : node2, isClassElement); + if (pendingExpressions) { + let outerThis; + for (let expression of pendingExpressions) { + expression = visitNode(expression, function thisVisitor(node2) { + if (!(node2.transformFlags & 16384 /* ContainsLexicalThis */)) { + return node2; + } + switch (node2.kind) { + case 110 /* ThisKeyword */: + if (!outerThis) { + outerThis = factory2.createUniqueName("_outerThis", 16 /* Optimistic */); + classDefinitionStatements.unshift(createLet(outerThis, factory2.createThis())); + } + return outerThis; + default: + return visitEachChild(node2, thisVisitor, context); + } + }, isExpression); + const statement = factory2.createExpressionStatement(expression); + leadingBlockStatements = append(leadingBlockStatements, statement); + } + pendingExpressions = void 0; + } + exitClass(); + if (some(classInfo2.pendingInstanceInitializers) && !getFirstConstructorWithBody(node)) { + const initializerStatements = prepareConstructor(node, classInfo2); + if (initializerStatements) { + const extendsClauseElement = getEffectiveBaseTypeNode(node); + const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */); + const constructorStatements = []; + if (isDerivedClass) { + const spreadArguments = factory2.createSpreadElement(factory2.createIdentifier("arguments")); + const superCall = factory2.createCallExpression( + factory2.createSuper(), + /*typeArguments*/ + void 0, + [spreadArguments] + ); + constructorStatements.push(factory2.createExpressionStatement(superCall)); + } + addRange(constructorStatements, initializerStatements); + const constructorBody = factory2.createBlock( + constructorStatements, + /*multiLine*/ + true + ); + syntheticConstructor = factory2.createConstructorDeclaration( + /*modifiers*/ + void 0, + [], + constructorBody + ); + } + } + if (classInfo2.staticMethodExtraInitializersName) { + classDefinitionStatements.push( + createLet(classInfo2.staticMethodExtraInitializersName, factory2.createArrayLiteralExpression()) + ); + } + if (classInfo2.instanceMethodExtraInitializersName) { + classDefinitionStatements.push( + createLet(classInfo2.instanceMethodExtraInitializersName, factory2.createArrayLiteralExpression()) + ); + } + if (classInfo2.memberInfos) { + forEachEntry(classInfo2.memberInfos, (memberInfo, member) => { + if (isStatic(member)) { + classDefinitionStatements.push(createLet(memberInfo.memberDecoratorsName)); + if (memberInfo.memberInitializersName) { + classDefinitionStatements.push(createLet(memberInfo.memberInitializersName, factory2.createArrayLiteralExpression())); + } + if (memberInfo.memberExtraInitializersName) { + classDefinitionStatements.push(createLet(memberInfo.memberExtraInitializersName, factory2.createArrayLiteralExpression())); + } + if (memberInfo.memberDescriptorName) { + classDefinitionStatements.push(createLet(memberInfo.memberDescriptorName)); + } + } + }); + } + if (classInfo2.memberInfos) { + forEachEntry(classInfo2.memberInfos, (memberInfo, member) => { + if (!isStatic(member)) { + classDefinitionStatements.push(createLet(memberInfo.memberDecoratorsName)); + if (memberInfo.memberInitializersName) { + classDefinitionStatements.push(createLet(memberInfo.memberInitializersName, factory2.createArrayLiteralExpression())); + } + if (memberInfo.memberExtraInitializersName) { + classDefinitionStatements.push(createLet(memberInfo.memberExtraInitializersName, factory2.createArrayLiteralExpression())); + } + if (memberInfo.memberDescriptorName) { + classDefinitionStatements.push(createLet(memberInfo.memberDescriptorName)); + } + } + }); + } + leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.staticNonFieldDecorationStatements); + leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.nonStaticNonFieldDecorationStatements); + leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.staticFieldDecorationStatements); + leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.nonStaticFieldDecorationStatements); + if (classInfo2.classDescriptorName && classInfo2.classDecoratorsName && classInfo2.classExtraInitializersName && classInfo2.classThis) { + leadingBlockStatements ?? (leadingBlockStatements = []); + const valueProperty = factory2.createPropertyAssignment("value", renamedClassThis); + const classDescriptor = factory2.createObjectLiteralExpression([valueProperty]); + const classDescriptorAssignment = factory2.createAssignment(classInfo2.classDescriptorName, classDescriptor); + const classNameReference = factory2.createPropertyAccessExpression(renamedClassThis, "name"); + const esDecorateHelper2 = emitHelpers().createESDecorateHelper( + factory2.createNull(), + classDescriptorAssignment, + classInfo2.classDecoratorsName, + { kind: "class", name: classNameReference, metadata: classInfo2.metadataReference }, + factory2.createNull(), + classInfo2.classExtraInitializersName + ); + const esDecorateStatement = factory2.createExpressionStatement(esDecorateHelper2); + setSourceMapRange(esDecorateStatement, moveRangePastDecorators(node)); + leadingBlockStatements.push(esDecorateStatement); + const classDescriptorValueReference = factory2.createPropertyAccessExpression(classInfo2.classDescriptorName, "value"); + const classThisAssignment = factory2.createAssignment(classInfo2.classThis, classDescriptorValueReference); + const classReferenceAssignment = factory2.createAssignment(classReference, classThisAssignment); + leadingBlockStatements.push(factory2.createExpressionStatement(classReferenceAssignment)); + } + leadingBlockStatements.push(createSymbolMetadata(renamedClassThis, classInfo2.metadataReference)); + if (some(classInfo2.pendingStaticInitializers)) { + for (const initializer of classInfo2.pendingStaticInitializers) { + const initializerStatement = factory2.createExpressionStatement(initializer); + setSourceMapRange(initializerStatement, getSourceMapRange(initializer)); + trailingBlockStatements = append(trailingBlockStatements, initializerStatement); + } + classInfo2.pendingStaticInitializers = void 0; + } + if (classInfo2.classExtraInitializersName) { + const runClassInitializersHelper = emitHelpers().createRunInitializersHelper(renamedClassThis, classInfo2.classExtraInitializersName); + const runClassInitializersStatement = factory2.createExpressionStatement(runClassInitializersHelper); + setSourceMapRange(runClassInitializersStatement, node.name ?? moveRangePastDecorators(node)); + trailingBlockStatements = append(trailingBlockStatements, runClassInitializersStatement); + } + if (leadingBlockStatements && trailingBlockStatements && !classInfo2.hasStaticInitializers) { + addRange(leadingBlockStatements, trailingBlockStatements); + trailingBlockStatements = void 0; + } + const leadingStaticBlock = leadingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock( + leadingBlockStatements, + /*multiLine*/ + true + )); + if (leadingStaticBlock && shouldTransformPrivateStaticElementsInClass) { + setInternalEmitFlags(leadingStaticBlock, 32 /* TransformPrivateStaticElements */); + } + const trailingStaticBlock = trailingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock( + trailingBlockStatements, + /*multiLine*/ + true + )); + if (leadingStaticBlock || syntheticConstructor || trailingStaticBlock) { + const newMembers = []; + const existingNamedEvaluationHelperBlockIndex = members.findIndex(isClassNamedEvaluationHelperBlock); + if (leadingStaticBlock) { + addRange(newMembers, members, 0, existingNamedEvaluationHelperBlockIndex + 1); + newMembers.push(leadingStaticBlock); + addRange(newMembers, members, existingNamedEvaluationHelperBlockIndex + 1); + } else { + addRange(newMembers, members); + } + if (syntheticConstructor) { + newMembers.push(syntheticConstructor); + } + if (trailingStaticBlock) { + newMembers.push(trailingStaticBlock); + } + members = setTextRange(factory2.createNodeArray(newMembers), members); + } + const lexicalEnvironment = endLexicalEnvironment(); + let classExpression; + if (classDecorators) { + classExpression = factory2.createClassExpression( + /*modifiers*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + if (classInfo2.classThis) { + classExpression = injectClassThisAssignmentIfMissing(factory2, classExpression, classInfo2.classThis); + } + const classReferenceDeclaration = factory2.createVariableDeclaration( + classReference, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + classExpression + ); + const classReferenceVarDeclList = factory2.createVariableDeclarationList([classReferenceDeclaration]); + const returnExpr = classInfo2.classThis ? factory2.createAssignment(classReference, classInfo2.classThis) : classReference; + classDefinitionStatements.push( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + classReferenceVarDeclList + ), + factory2.createReturnStatement(returnExpr) + ); + } else { + classExpression = factory2.createClassExpression( + /*modifiers*/ + void 0, + node.name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + classDefinitionStatements.push(factory2.createReturnStatement(classExpression)); + } + if (shouldTransformPrivateStaticElementsInClass) { + addInternalEmitFlags(classExpression, 32 /* TransformPrivateStaticElements */); + for (const member of classExpression.members) { + if ((isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)) { + addInternalEmitFlags(member, 32 /* TransformPrivateStaticElements */); + } + } + } + setOriginalNode(classExpression, node); + return factory2.createImmediatelyInvokedArrowFunction(factory2.mergeLexicalEnvironment(classDefinitionStatements, lexicalEnvironment)); + } + function isDecoratedClassLike(node) { + return classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ + false, + node + ) || childIsDecorated( + /*useLegacyDecorators*/ + false, + node + ); + } + function visitClassDeclaration(node) { + if (isDecoratedClassLike(node)) { + const statements = []; + const originalClass = getOriginalNode(node, isClassLike) ?? node; + const className = originalClass.name ? factory2.createStringLiteralFromNode(originalClass.name) : factory2.createStringLiteral("default"); + const isExport = hasSyntacticModifier(node, 32 /* Export */); + const isDefault = hasSyntacticModifier(node, 2048 /* Default */); + if (!node.name) { + node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, className); + } + if (isExport && isDefault) { + const iife = transformClassLike(node); + if (node.name) { + const varDecl = factory2.createVariableDeclaration( + factory2.getLocalName(node), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + iife + ); + setOriginalNode(varDecl, node); + const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); + const varStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + varDecls + ); + statements.push(varStatement); + const exportStatement = factory2.createExportDefault(factory2.getDeclarationName(node)); + setOriginalNode(exportStatement, node); + setCommentRange(exportStatement, getCommentRange(node)); + setSourceMapRange(exportStatement, moveRangePastDecorators(node)); + statements.push(exportStatement); + } else { + const exportStatement = factory2.createExportDefault(iife); + setOriginalNode(exportStatement, node); + setCommentRange(exportStatement, getCommentRange(node)); + setSourceMapRange(exportStatement, moveRangePastDecorators(node)); + statements.push(exportStatement); + } + } else { + Debug.assertIsDefined(node.name, "A class declaration that is not a default export must have a name."); + const iife = transformClassLike(node); + const modifierVisitorNoExport = isExport ? (node2) => isExportModifier(node2) ? void 0 : modifierVisitor(node2) : modifierVisitor; + const modifiers = visitNodes2(node.modifiers, modifierVisitorNoExport, isModifier); + const declName = factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ); + const varDecl = factory2.createVariableDeclaration( + declName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + iife + ); + setOriginalNode(varDecl, node); + const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); + const varStatement = factory2.createVariableStatement(modifiers, varDecls); + setOriginalNode(varStatement, node); + setCommentRange(varStatement, getCommentRange(node)); + statements.push(varStatement); + if (isExport) { + const exportStatement = factory2.createExternalModuleExport(declName); + setOriginalNode(exportStatement, node); + statements.push(exportStatement); + } + } + return singleOrMany(statements); + } else { + const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); + enterClass( + /*classInfo*/ + void 0 + ); + const members = visitNodes2(node.members, classElementVisitor, isClassElement); + exitClass(); + return factory2.updateClassDeclaration( + node, + modifiers, + node.name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + } + } + function visitClassExpression(node) { + if (isDecoratedClassLike(node)) { + const iife = transformClassLike(node); + setOriginalNode(iife, node); + return iife; + } else { + const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); + enterClass( + /*classInfo*/ + void 0 + ); + const members = visitNodes2(node.members, classElementVisitor, isClassElement); + exitClass(); + return factory2.updateClassExpression( + node, + modifiers, + node.name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + } + } + function prepareConstructor(_parent, classInfo2) { + if (some(classInfo2.pendingInstanceInitializers)) { + const statements = []; + statements.push( + factory2.createExpressionStatement( + factory2.inlineExpressions(classInfo2.pendingInstanceInitializers) + ) + ); + classInfo2.pendingInstanceInitializers = void 0; + return statements; + } + } + function transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements) { + const superStatementIndex = superPath[superPathDepth]; + const superStatement = statementsIn[superStatementIndex]; + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); + if (isTryStatement(superStatement)) { + const tryBlockStatements = []; + transformConstructorBodyWorker( + tryBlockStatements, + superStatement.tryBlock.statements, + /*statementOffset*/ + 0, + superPath, + superPathDepth + 1, + initializerStatements + ); + const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); + setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); + statementsOut.push(factory2.updateTryStatement( + superStatement, + factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), + visitNode(superStatement.catchClause, visitor, isCatchClause), + visitNode(superStatement.finallyBlock, visitor, isBlock) + )); + } else { + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1)); + addRange(statementsOut, initializerStatements); + } + addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1)); + } + function visitConstructorDeclaration(node) { + enterClassElement(node); + const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const parameters = visitNodes2(node.parameters, visitor, isParameter); + let body; + if (node.body && classInfo) { + const initializerStatements = prepareConstructor(classInfo.class, classInfo); + if (initializerStatements) { + const statements = []; + const nonPrologueStart = factory2.copyPrologue( + node.body.statements, + statements, + /*ensureUseStrict*/ + false, + visitor + ); + const superStatementIndices = findSuperStatementIndexPath(node.body.statements, nonPrologueStart); + if (superStatementIndices.length > 0) { + transformConstructorBodyWorker(statements, node.body.statements, nonPrologueStart, superStatementIndices, 0, initializerStatements); + } else { + addRange(statements, initializerStatements); + addRange(statements, visitNodes2(node.body.statements, visitor, isStatement)); + } + body = factory2.createBlock( + statements, + /*multiLine*/ + true + ); + setOriginalNode(body, node.body); + setTextRange(body, node.body); + } + } + body ?? (body = visitNode(node.body, visitor, isBlock)); + exitClassElement(); + return factory2.updateConstructorDeclaration(node, modifiers, parameters, body); + } + function finishClassElement(updated, original) { + if (updated !== original) { + setCommentRange(updated, original); + setSourceMapRange(updated, moveRangePastDecorators(original)); + } + return updated; + } + function partialTransformClassElement(member, classInfo2, createDescriptor) { + let referencedName; + let name; + let initializersName; + let extraInitializersName; + let thisArg; + let descriptorName; + if (!classInfo2) { + const modifiers2 = visitNodes2(member.modifiers, modifierVisitor, isModifier); + enterName(); + name = visitPropertyName(member.name); + exitName(); + return { modifiers: modifiers2, referencedName, name, initializersName, descriptorName, thisArg }; + } + const memberDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClassElement( + member, + classInfo2.class, + /*useLegacyDecorators*/ + false + )); + const modifiers = visitNodes2(member.modifiers, modifierVisitor, isModifier); + if (memberDecorators) { + const memberDecoratorsName = createHelperVariable(member, "decorators"); + const memberDecoratorsArray = factory2.createArrayLiteralExpression(memberDecorators); + const memberDecoratorsAssignment = factory2.createAssignment(memberDecoratorsName, memberDecoratorsArray); + const memberInfo = { memberDecoratorsName }; + classInfo2.memberInfos ?? (classInfo2.memberInfos = /* @__PURE__ */ new Map()); + classInfo2.memberInfos.set(member, memberInfo); + pendingExpressions ?? (pendingExpressions = []); + pendingExpressions.push(memberDecoratorsAssignment); + const statements = isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? classInfo2.staticNonFieldDecorationStatements ?? (classInfo2.staticNonFieldDecorationStatements = []) : classInfo2.nonStaticNonFieldDecorationStatements ?? (classInfo2.nonStaticNonFieldDecorationStatements = []) : isPropertyDeclaration(member) && !isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? classInfo2.staticFieldDecorationStatements ?? (classInfo2.staticFieldDecorationStatements = []) : classInfo2.nonStaticFieldDecorationStatements ?? (classInfo2.nonStaticFieldDecorationStatements = []) : Debug.fail(); + const kind = isGetAccessorDeclaration(member) ? "getter" : isSetAccessorDeclaration(member) ? "setter" : isMethodDeclaration(member) ? "method" : isAutoAccessorPropertyDeclaration(member) ? "accessor" : isPropertyDeclaration(member) ? "field" : Debug.fail(); + let propertyName; + if (isIdentifier(member.name) || isPrivateIdentifier(member.name)) { + propertyName = { computed: false, name: member.name }; + } else if (isPropertyNameLiteral(member.name)) { + propertyName = { computed: true, name: factory2.createStringLiteralFromNode(member.name) }; + } else { + const expression = member.name.expression; + if (isPropertyNameLiteral(expression) && !isIdentifier(expression)) { + propertyName = { computed: true, name: factory2.createStringLiteralFromNode(expression) }; + } else { + enterName(); + ({ referencedName, name } = visitReferencedPropertyName(member.name)); + propertyName = { computed: true, name: referencedName }; + exitName(); + } + } + const context2 = { + kind, + name: propertyName, + static: isStatic(member), + private: isPrivateIdentifier(member.name), + access: { + // 15.7.3 CreateDecoratorAccessObject (kind, name) + // 2. If _kind_ is ~field~, ~method~, ~accessor~, or ~getter~, then ... + get: isPropertyDeclaration(member) || isGetAccessorDeclaration(member) || isMethodDeclaration(member), + // 3. If _kind_ is ~field~, ~accessor~, or ~setter~, then ... + set: isPropertyDeclaration(member) || isSetAccessorDeclaration(member) + }, + metadata: classInfo2.metadataReference + }; + if (isMethodOrAccessor(member)) { + const methodExtraInitializersName = isStatic(member) ? classInfo2.staticMethodExtraInitializersName : classInfo2.instanceMethodExtraInitializersName; + Debug.assertIsDefined(methodExtraInitializersName); + let descriptor; + if (isPrivateIdentifierClassElementDeclaration(member) && createDescriptor) { + descriptor = createDescriptor(member, visitNodes2(modifiers, (node) => tryCast(node, isAsyncModifier), isModifier)); + memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor"); + descriptor = factory2.createAssignment(descriptorName, descriptor); + } + const esDecorateExpression = emitHelpers().createESDecorateHelper(factory2.createThis(), descriptor ?? factory2.createNull(), memberDecoratorsName, context2, factory2.createNull(), methodExtraInitializersName); + const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression); + setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member)); + statements.push(esDecorateStatement); + } else if (isPropertyDeclaration(member)) { + initializersName = memberInfo.memberInitializersName ?? (memberInfo.memberInitializersName = createHelperVariable(member, "initializers")); + extraInitializersName = memberInfo.memberExtraInitializersName ?? (memberInfo.memberExtraInitializersName = createHelperVariable(member, "extraInitializers")); + if (isStatic(member)) { + thisArg = classInfo2.classThis; + } + let descriptor; + if (isPrivateIdentifierClassElementDeclaration(member) && hasAccessorModifier(member) && createDescriptor) { + descriptor = createDescriptor( + member, + /*modifiers*/ + void 0 + ); + memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor"); + descriptor = factory2.createAssignment(descriptorName, descriptor); + } + const esDecorateExpression = emitHelpers().createESDecorateHelper( + isAutoAccessorPropertyDeclaration(member) ? factory2.createThis() : factory2.createNull(), + descriptor ?? factory2.createNull(), + memberDecoratorsName, + context2, + initializersName, + extraInitializersName + ); + const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression); + setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member)); + statements.push(esDecorateStatement); + } + } + if (name === void 0) { + enterName(); + name = visitPropertyName(member.name); + exitName(); + } + if (!some(modifiers) && (isMethodDeclaration(member) || isPropertyDeclaration(member))) { + setEmitFlags(name, 1024 /* NoLeadingComments */); + } + return { modifiers, referencedName, name, initializersName, extraInitializersName, descriptorName, thisArg }; + } + function visitMethodDeclaration(node) { + enterClassElement(node); + const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createMethodDescriptorObject); + if (descriptorName) { + exitClassElement(); + return finishClassElement(createMethodDescriptorForwarder(modifiers, name, descriptorName), node); + } else { + const parameters = visitNodes2(node.parameters, visitor, isParameter); + const body = visitNode(node.body, visitor, isBlock); + exitClassElement(); + return finishClassElement(factory2.updateMethodDeclaration( + node, + modifiers, + node.asteriskToken, + name, + /*questionToken*/ + void 0, + /*typeParameters*/ + void 0, + parameters, + /*type*/ + void 0, + body + ), node); + } + } + function visitGetAccessorDeclaration(node) { + enterClassElement(node); + const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createGetAccessorDescriptorObject); + if (descriptorName) { + exitClassElement(); + return finishClassElement(createGetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); + } else { + const parameters = visitNodes2(node.parameters, visitor, isParameter); + const body = visitNode(node.body, visitor, isBlock); + exitClassElement(); + return finishClassElement(factory2.updateGetAccessorDeclaration( + node, + modifiers, + name, + parameters, + /*type*/ + void 0, + body + ), node); + } + } + function visitSetAccessorDeclaration(node) { + enterClassElement(node); + const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createSetAccessorDescriptorObject); + if (descriptorName) { + exitClassElement(); + return finishClassElement(createSetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); + } else { + const parameters = visitNodes2(node.parameters, visitor, isParameter); + const body = visitNode(node.body, visitor, isBlock); + exitClassElement(); + return finishClassElement(factory2.updateSetAccessorDeclaration(node, modifiers, name, parameters, body), node); + } + } + function visitClassStaticBlockDeclaration(node) { + enterClassElement(node); + let result; + if (isClassNamedEvaluationHelperBlock(node)) { + result = visitEachChild(node, visitor, context); + } else if (isClassThisAssignmentBlock(node)) { + const savedClassThis = classThis; + classThis = void 0; + result = visitEachChild(node, visitor, context); + classThis = savedClassThis; + } else { + node = visitEachChild(node, visitor, context); + result = node; + if (classInfo) { + classInfo.hasStaticInitializers = true; + if (some(classInfo.pendingStaticInitializers)) { + const statements = []; + for (const initializer of classInfo.pendingStaticInitializers) { + const initializerStatement = factory2.createExpressionStatement(initializer); + setSourceMapRange(initializerStatement, getSourceMapRange(initializer)); + statements.push(initializerStatement); + } + const body = factory2.createBlock( + statements, + /*multiLine*/ + true + ); + const staticBlock = factory2.createClassStaticBlockDeclaration(body); + result = [staticBlock, result]; + classInfo.pendingStaticInitializers = void 0; + } + } + } + exitClassElement(); + return result; + } + function visitPropertyDeclaration(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + enterClassElement(node); + Debug.assert(!isAmbientPropertyDeclaration(node), "Not yet implemented."); + const { modifiers, name, initializersName, extraInitializersName, descriptorName, thisArg } = partialTransformClassElement(node, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : void 0); + startLexicalEnvironment(); + let initializer = visitNode(node.initializer, visitor, isExpression); + if (initializersName) { + initializer = emitHelpers().createRunInitializersHelper( + thisArg ?? factory2.createThis(), + initializersName, + initializer ?? factory2.createVoidZero() + ); + } + if (isStatic(node) && classInfo && initializer) { + classInfo.hasStaticInitializers = true; + } + const declarations = endLexicalEnvironment(); + if (some(declarations)) { + initializer = factory2.createImmediatelyInvokedArrowFunction([ + ...declarations, + factory2.createReturnStatement(initializer) + ]); + } + if (classInfo) { + if (isStatic(node)) { + initializer = injectPendingInitializers( + classInfo, + /*isStatic*/ + true, + initializer + ); + if (extraInitializersName) { + classInfo.pendingStaticInitializers ?? (classInfo.pendingStaticInitializers = []); + classInfo.pendingStaticInitializers.push( + emitHelpers().createRunInitializersHelper( + classInfo.classThis ?? factory2.createThis(), + extraInitializersName + ) + ); + } + } else { + initializer = injectPendingInitializers( + classInfo, + /*isStatic*/ + false, + initializer + ); + if (extraInitializersName) { + classInfo.pendingInstanceInitializers ?? (classInfo.pendingInstanceInitializers = []); + classInfo.pendingInstanceInitializers.push( + emitHelpers().createRunInitializersHelper( + factory2.createThis(), + extraInitializersName + ) + ); + } + } + } + exitClassElement(); + if (hasAccessorModifier(node) && descriptorName) { + const commentRange = getCommentRange(node); + const sourceMapRange = getSourceMapRange(node); + const name2 = node.name; + let getterName = name2; + let setterName = name2; + if (isComputedPropertyName(name2) && !isSimpleInlineableExpression(name2.expression)) { + const cacheAssignment = findComputedPropertyNameCacheAssignment(name2); + if (cacheAssignment) { + getterName = factory2.updateComputedPropertyName(name2, visitNode(name2.expression, visitor, isExpression)); + setterName = factory2.updateComputedPropertyName(name2, cacheAssignment.left); + } else { + const temp = factory2.createTempVariable(hoistVariableDeclaration); + setSourceMapRange(temp, name2.expression); + const expression = visitNode(name2.expression, visitor, isExpression); + const assignment = factory2.createAssignment(temp, expression); + setSourceMapRange(assignment, name2.expression); + getterName = factory2.updateComputedPropertyName(name2, assignment); + setterName = factory2.updateComputedPropertyName(name2, temp); + } + } + const modifiersWithoutAccessor = visitNodes2(modifiers, (node2) => node2.kind !== 129 /* AccessorKeyword */ ? node2 : void 0, isModifier); + const backingField = createAccessorPropertyBackingField(factory2, node, modifiersWithoutAccessor, initializer); + setOriginalNode(backingField, node); + setEmitFlags(backingField, 3072 /* NoComments */); + setSourceMapRange(backingField, sourceMapRange); + setSourceMapRange(backingField.name, node.name); + const getter = createGetAccessorDescriptorForwarder(modifiersWithoutAccessor, getterName, descriptorName); + setOriginalNode(getter, node); + setCommentRange(getter, commentRange); + setSourceMapRange(getter, sourceMapRange); + const setter = createSetAccessorDescriptorForwarder(modifiersWithoutAccessor, setterName, descriptorName); + setOriginalNode(setter, node); + setEmitFlags(setter, 3072 /* NoComments */); + setSourceMapRange(setter, sourceMapRange); + return [backingField, getter, setter]; + } + return finishClassElement(factory2.updatePropertyDeclaration( + node, + modifiers, + name, + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + initializer + ), node); + } + function visitThisExpression(node) { + return classThis ?? node; + } + function visitCallExpression(node) { + if (isSuperProperty(node.expression) && classThis) { + const expression = visitNode(node.expression, visitor, isExpression); + const argumentsList = visitNodes2(node.arguments, visitor, isExpression); + const invocation = factory2.createFunctionCallCall(expression, classThis, argumentsList); + setOriginalNode(invocation, node); + setTextRange(invocation, node); + return invocation; + } + return visitEachChild(node, visitor, context); + } + function visitTaggedTemplateExpression(node) { + if (isSuperProperty(node.tag) && classThis) { + const tag = visitNode(node.tag, visitor, isExpression); + const boundTag = factory2.createFunctionBindCall(tag, classThis, []); + setOriginalNode(boundTag, node); + setTextRange(boundTag, node); + const template = visitNode(node.template, visitor, isTemplateLiteral); + return factory2.updateTaggedTemplateExpression( + node, + boundTag, + /*typeArguments*/ + void 0, + template + ); + } + return visitEachChild(node, visitor, context); + } + function visitPropertyAccessExpression(node) { + if (isSuperProperty(node) && isIdentifier(node.name) && classThis && classSuper) { + const propertyName = factory2.createStringLiteralFromNode(node.name); + const superProperty = factory2.createReflectGetCall(classSuper, propertyName, classThis); + setOriginalNode(superProperty, node.expression); + setTextRange(superProperty, node.expression); + return superProperty; + } + return visitEachChild(node, visitor, context); + } + function visitElementAccessExpression(node) { + if (isSuperProperty(node) && classThis && classSuper) { + const propertyName = visitNode(node.argumentExpression, visitor, isExpression); + const superProperty = factory2.createReflectGetCall(classSuper, propertyName, classThis); + setOriginalNode(superProperty, node.expression); + setTextRange(superProperty, node.expression); + return superProperty; + } + return visitEachChild(node, visitor, context); + } + function visitParameterDeclaration(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + const updated = factory2.updateParameterDeclaration( + node, + /*modifiers*/ + void 0, + node.dotDotDotToken, + visitNode(node.name, visitor, isBindingName), + /*questionToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ); + if (updated !== node) { + setCommentRange(updated, node); + setTextRange(updated, moveRangePastModifiers(node)); + setSourceMapRange(updated, moveRangePastModifiers(node)); + setEmitFlags(updated.name, 64 /* NoTrailingSourceMap */); + } + return updated; + } + function isAnonymousClassNeedingAssignedName(node) { + return isClassExpression(node) && !node.name && isDecoratedClassLike(node); + } + function canIgnoreEmptyStringLiteralInAssignedName(node) { + const innerExpression = skipOuterExpressions(node); + return isClassExpression(innerExpression) && !innerExpression.name && !classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ + false, + innerExpression + ); + } + function visitForStatement(node) { + return factory2.updateForStatement( + node, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.condition, visitor, isExpression), + visitNode(node.incrementor, discardedValueVisitor, isExpression), + visitIterationBody(node.statement, visitor, context) + ); + } + function visitExpressionStatement(node) { + return visitEachChild(node, discardedValueVisitor, context); + } + function visitBinaryExpression(node, discarded) { + if (isDestructuringAssignment(node)) { + const left = visitAssignmentPattern(node.left); + const right = visitNode(node.right, visitor, isExpression); + return factory2.updateBinaryExpression(node, left, node.operatorToken, right); + } + if (isAssignmentExpression(node)) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); + return visitEachChild(node, visitor, context); + } + if (isSuperProperty(node.left) && classThis && classSuper) { + let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : isIdentifier(node.left.name) ? factory2.createStringLiteralFromNode(node.left.name) : void 0; + if (setterName) { + let expression = visitNode(node.right, visitor, isExpression); + if (isCompoundAssignment(node.operatorToken.kind)) { + let getterName = setterName; + if (!isSimpleInlineableExpression(setterName)) { + getterName = factory2.createTempVariable(hoistVariableDeclaration); + setterName = factory2.createAssignment(getterName, setterName); + } + const superPropertyGet = factory2.createReflectGetCall( + classSuper, + getterName, + classThis + ); + setOriginalNode(superPropertyGet, node.left); + setTextRange(superPropertyGet, node.left); + expression = factory2.createBinaryExpression( + superPropertyGet, + getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), + expression + ); + setTextRange(expression, node); + } + const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration); + if (temp) { + expression = factory2.createAssignment(temp, expression); + setTextRange(temp, node); + } + expression = factory2.createReflectSetCall( + classSuper, + setterName, + expression, + classThis + ); + setOriginalNode(expression, node); + setTextRange(expression, node); + if (temp) { + expression = factory2.createComma(expression, temp); + setTextRange(expression, node); + } + return expression; + } + } + } + if (node.operatorToken.kind === 28 /* CommaToken */) { + const left = visitNode(node.left, discardedValueVisitor, isExpression); + const right = visitNode(node.right, discarded ? discardedValueVisitor : visitor, isExpression); + return factory2.updateBinaryExpression(node, left, node.operatorToken, right); + } + return visitEachChild(node, visitor, context); + } + function visitPreOrPostfixUnaryExpression(node, discarded) { + if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) { + const operand = skipParentheses(node.operand); + if (isSuperProperty(operand) && classThis && classSuper) { + let setterName = isElementAccessExpression(operand) ? visitNode(operand.argumentExpression, visitor, isExpression) : isIdentifier(operand.name) ? factory2.createStringLiteralFromNode(operand.name) : void 0; + if (setterName) { + let getterName = setterName; + if (!isSimpleInlineableExpression(setterName)) { + getterName = factory2.createTempVariable(hoistVariableDeclaration); + setterName = factory2.createAssignment(getterName, setterName); + } + let expression = factory2.createReflectGetCall(classSuper, getterName, classThis); + setOriginalNode(expression, node); + setTextRange(expression, node); + const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration); + expression = expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, hoistVariableDeclaration, temp); + expression = factory2.createReflectSetCall(classSuper, setterName, expression, classThis); + setOriginalNode(expression, node); + setTextRange(expression, node); + if (temp) { + expression = factory2.createComma(expression, temp); + setTextRange(expression, node); + } + return expression; + } + } + } + return visitEachChild(node, visitor, context); + } + function visitCommaListExpression(node, discarded) { + const elements = discarded ? visitCommaListElements(node.elements, discardedValueVisitor) : visitCommaListElements(node.elements, visitor, discardedValueVisitor); + return factory2.updateCommaListExpression(node, elements); + } + function visitReferencedPropertyName(node) { + if (isPropertyNameLiteral(node) || isPrivateIdentifier(node)) { + const referencedName2 = factory2.createStringLiteralFromNode(node); + const name2 = visitNode(node, visitor, isPropertyName); + return { referencedName: referencedName2, name: name2 }; + } + if (isPropertyNameLiteral(node.expression) && !isIdentifier(node.expression)) { + const referencedName2 = factory2.createStringLiteralFromNode(node.expression); + const name2 = visitNode(node, visitor, isPropertyName); + return { referencedName: referencedName2, name: name2 }; + } + const referencedName = factory2.getGeneratedNameForNode(node); + hoistVariableDeclaration(referencedName); + const key = emitHelpers().createPropKeyHelper(visitNode(node.expression, visitor, isExpression)); + const assignment = factory2.createAssignment(referencedName, key); + const name = factory2.updateComputedPropertyName(node, injectPendingExpressions(assignment)); + return { referencedName, name }; + } + function visitPropertyName(node) { + if (isComputedPropertyName(node)) { + return visitComputedPropertyName(node); + } + return visitNode(node, visitor, isPropertyName); + } + function visitComputedPropertyName(node) { + let expression = visitNode(node.expression, visitor, isExpression); + if (!isSimpleInlineableExpression(expression)) { + expression = injectPendingExpressions(expression); + } + return factory2.updateComputedPropertyName(node, expression); + } + function visitPropertyAssignment(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + return visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + return visitEachChild(node, visitor, context); + } + function visitBindingElement(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + return visitEachChild(node, visitor, context); + } + function visitDestructuringAssignmentTarget(node) { + if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) { + return visitAssignmentPattern(node); + } + if (isSuperProperty(node) && classThis && classSuper) { + const propertyName = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : isIdentifier(node.name) ? factory2.createStringLiteralFromNode(node.name) : void 0; + if (propertyName) { + const paramName = factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const expression = factory2.createAssignmentTargetWrapper( + paramName, + factory2.createReflectSetCall( + classSuper, + propertyName, + paramName, + classThis + ) + ); + setOriginalNode(expression, node); + setTextRange(expression, node); + return expression; + } + } + return visitEachChild(node, visitor, context); + } + function visitAssignmentElement(node) { + if (isAssignmentExpression( + node, + /*excludeCompoundAssignment*/ + true + )) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); + } + const assignmentTarget = visitDestructuringAssignmentTarget(node.left); + const initializer = visitNode(node.right, visitor, isExpression); + return factory2.updateBinaryExpression(node, assignmentTarget, node.operatorToken, initializer); + } else { + return visitDestructuringAssignmentTarget(node); + } + } + function visitAssignmentRestElement(node) { + if (isLeftHandSideExpression(node.expression)) { + const expression = visitDestructuringAssignmentTarget(node.expression); + return factory2.updateSpreadElement(node, expression); + } + return visitEachChild(node, visitor, context); + } + function visitArrayAssignmentElement(node) { + Debug.assertNode(node, isArrayBindingOrAssignmentElement); + if (isSpreadElement(node)) return visitAssignmentRestElement(node); + if (!isOmittedExpression(node)) return visitAssignmentElement(node); + return visitEachChild(node, visitor, context); + } + function visitAssignmentProperty(node) { + const name = visitNode(node.name, visitor, isPropertyName); + if (isAssignmentExpression( + node.initializer, + /*excludeCompoundAssignment*/ + true + )) { + const assignmentElement = visitAssignmentElement(node.initializer); + return factory2.updatePropertyAssignment(node, name, assignmentElement); + } + if (isLeftHandSideExpression(node.initializer)) { + const assignmentElement = visitDestructuringAssignmentTarget(node.initializer); + return factory2.updatePropertyAssignment(node, name, assignmentElement); + } + return visitEachChild(node, visitor, context); + } + function visitShorthandAssignmentProperty(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.objectAssignmentInitializer)); + } + return visitEachChild(node, visitor, context); + } + function visitAssignmentRestProperty(node) { + if (isLeftHandSideExpression(node.expression)) { + const expression = visitDestructuringAssignmentTarget(node.expression); + return factory2.updateSpreadAssignment(node, expression); + } + return visitEachChild(node, visitor, context); + } + function visitObjectAssignmentElement(node) { + Debug.assertNode(node, isObjectBindingOrAssignmentElement); + if (isSpreadAssignment(node)) return visitAssignmentRestProperty(node); + if (isShorthandPropertyAssignment(node)) return visitShorthandAssignmentProperty(node); + if (isPropertyAssignment(node)) return visitAssignmentProperty(node); + return visitEachChild(node, visitor, context); + } + function visitAssignmentPattern(node) { + if (isArrayLiteralExpression(node)) { + const elements = visitNodes2(node.elements, visitArrayAssignmentElement, isExpression); + return factory2.updateArrayLiteralExpression(node, elements); + } else { + const properties = visitNodes2(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike); + return factory2.updateObjectLiteralExpression(node, properties); + } + } + function visitExportAssignment(node) { + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { + node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.expression)); + } + return visitEachChild(node, visitor, context); + } + function visitParenthesizedExpression(node, discarded) { + const visitorFunc = discarded ? discardedValueVisitor : visitor; + const expression = visitNode(node.expression, visitorFunc, isExpression); + return factory2.updateParenthesizedExpression(node, expression); + } + function visitPartiallyEmittedExpression(node, discarded) { + const visitorFunc = discarded ? discardedValueVisitor : visitor; + const expression = visitNode(node.expression, visitorFunc, isExpression); + return factory2.updatePartiallyEmittedExpression(node, expression); + } + function injectPendingExpressionsCommon(pendingExpressions2, expression) { + if (some(pendingExpressions2)) { + if (expression) { + if (isParenthesizedExpression(expression)) { + pendingExpressions2.push(expression.expression); + expression = factory2.updateParenthesizedExpression(expression, factory2.inlineExpressions(pendingExpressions2)); + } else { + pendingExpressions2.push(expression); + expression = factory2.inlineExpressions(pendingExpressions2); + } + } else { + expression = factory2.inlineExpressions(pendingExpressions2); + } + } + return expression; + } + function injectPendingExpressions(expression) { + const result = injectPendingExpressionsCommon(pendingExpressions, expression); + Debug.assertIsDefined(result); + if (result !== expression) { + pendingExpressions = void 0; + } + return result; + } + function injectPendingInitializers(classInfo2, isStatic2, expression) { + const result = injectPendingExpressionsCommon(isStatic2 ? classInfo2.pendingStaticInitializers : classInfo2.pendingInstanceInitializers, expression); + if (result !== expression) { + if (isStatic2) { + classInfo2.pendingStaticInitializers = void 0; + } else { + classInfo2.pendingInstanceInitializers = void 0; + } + } + return result; + } + function transformAllDecoratorsOfDeclaration(allDecorators) { + if (!allDecorators) { + return void 0; + } + const decoratorExpressions = []; + addRange(decoratorExpressions, map(allDecorators.decorators, transformDecorator)); + return decoratorExpressions; + } + function transformDecorator(decorator) { + const expression = visitNode(decorator.expression, visitor, isExpression); + setEmitFlags(expression, 3072 /* NoComments */); + const innerExpression = skipOuterExpressions(expression); + if (isAccessExpression(innerExpression)) { + const { target, thisArg } = factory2.createCallBinding( + expression, + hoistVariableDeclaration, + languageVersion, + /*cacheIdentifiers*/ + true + ); + return factory2.restoreOuterExpressions(expression, factory2.createFunctionBindCall(target, thisArg, [])); + } + return expression; + } + function createDescriptorMethod(original, name, modifiers, asteriskToken, kind, parameters, body) { + const func = factory2.createFunctionExpression( + modifiers, + asteriskToken, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + parameters, + /*type*/ + void 0, + body ?? factory2.createBlock([]) + ); + setOriginalNode(func, original); + setSourceMapRange(func, moveRangePastDecorators(original)); + setEmitFlags(func, 3072 /* NoComments */); + const prefix = kind === "get" || kind === "set" ? kind : void 0; + const functionName = factory2.createStringLiteralFromNode( + name, + /*isSingleQuote*/ + void 0 + ); + const namedFunction = emitHelpers().createSetFunctionNameHelper(func, functionName, prefix); + const method = factory2.createPropertyAssignment(factory2.createIdentifier(kind), namedFunction); + setOriginalNode(method, original); + setSourceMapRange(method, moveRangePastDecorators(original)); + setEmitFlags(method, 3072 /* NoComments */); + return method; + } + function createMethodDescriptorObject(node, modifiers) { + return factory2.createObjectLiteralExpression([ + createDescriptorMethod( + node, + node.name, + modifiers, + node.asteriskToken, + "value", + visitNodes2(node.parameters, visitor, isParameter), + visitNode(node.body, visitor, isBlock) + ) + ]); + } + function createGetAccessorDescriptorObject(node, modifiers) { + return factory2.createObjectLiteralExpression([ + createDescriptorMethod( + node, + node.name, + modifiers, + /*asteriskToken*/ + void 0, + "get", + [], + visitNode(node.body, visitor, isBlock) + ) + ]); + } + function createSetAccessorDescriptorObject(node, modifiers) { + return factory2.createObjectLiteralExpression([ + createDescriptorMethod( + node, + node.name, + modifiers, + /*asteriskToken*/ + void 0, + "set", + visitNodes2(node.parameters, visitor, isParameter), + visitNode(node.body, visitor, isBlock) + ) + ]); + } + function createAccessorPropertyDescriptorObject(node, modifiers) { + return factory2.createObjectLiteralExpression([ + createDescriptorMethod( + node, + node.name, + modifiers, + /*asteriskToken*/ + void 0, + "get", + [], + factory2.createBlock([ + factory2.createReturnStatement( + factory2.createPropertyAccessExpression( + factory2.createThis(), + factory2.getGeneratedPrivateNameForNode(node.name) + ) + ) + ]) + ), + createDescriptorMethod( + node, + node.name, + modifiers, + /*asteriskToken*/ + void 0, + "set", + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "value" + )], + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createPropertyAccessExpression( + factory2.createThis(), + factory2.getGeneratedPrivateNameForNode(node.name) + ), + factory2.createIdentifier("value") + ) + ) + ]) + ) + ]); + } + function createMethodDescriptorForwarder(modifiers, name, descriptorName) { + modifiers = visitNodes2(modifiers, (node) => isStaticModifier(node) ? node : void 0, isModifier); + return factory2.createGetAccessorDeclaration( + modifiers, + name, + [], + /*type*/ + void 0, + factory2.createBlock([ + factory2.createReturnStatement( + factory2.createPropertyAccessExpression( + descriptorName, + factory2.createIdentifier("value") + ) + ) + ]) + ); + } + function createGetAccessorDescriptorForwarder(modifiers, name, descriptorName) { + modifiers = visitNodes2(modifiers, (node) => isStaticModifier(node) ? node : void 0, isModifier); + return factory2.createGetAccessorDeclaration( + modifiers, + name, + [], + /*type*/ + void 0, + factory2.createBlock([ + factory2.createReturnStatement( + factory2.createFunctionCallCall( + factory2.createPropertyAccessExpression( + descriptorName, + factory2.createIdentifier("get") + ), + factory2.createThis(), + [] + ) + ) + ]) + ); + } + function createSetAccessorDescriptorForwarder(modifiers, name, descriptorName) { + modifiers = visitNodes2(modifiers, (node) => isStaticModifier(node) ? node : void 0, isModifier); + return factory2.createSetAccessorDeclaration( + modifiers, + name, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "value" + )], + factory2.createBlock([ + factory2.createReturnStatement( + factory2.createFunctionCallCall( + factory2.createPropertyAccessExpression( + descriptorName, + factory2.createIdentifier("set") + ), + factory2.createThis(), + [factory2.createIdentifier("value")] + ) + ) + ]) + ); + } + function createMetadata(name, classSuper2) { + const varDecl = factory2.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createConditionalExpression( + factory2.createLogicalAnd( + factory2.createTypeCheck(factory2.createIdentifier("Symbol"), "function"), + factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata") + ), + factory2.createToken(58 /* QuestionToken */), + factory2.createCallExpression( + factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "create"), + /*typeArguments*/ + void 0, + [classSuper2 ? createSymbolMetadataReference(classSuper2) : factory2.createNull()] + ), + factory2.createToken(59 /* ColonToken */), + factory2.createVoidZero() + ) + ); + return factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([varDecl], 2 /* Const */) + ); + } + function createSymbolMetadata(target, value) { + const defineProperty = factory2.createObjectDefinePropertyCall( + target, + factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata"), + factory2.createPropertyDescriptor( + { configurable: true, writable: true, enumerable: true, value }, + /*singleLine*/ + true + ) + ); + return setEmitFlags( + factory2.createIfStatement(value, factory2.createExpressionStatement(defineProperty)), + 1 /* SingleLine */ + ); + } + function createSymbolMetadataReference(classSuper2) { + return factory2.createBinaryExpression( + factory2.createElementAccessExpression( + classSuper2, + factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata") + ), + 61 /* QuestionQuestionToken */, + factory2.createNull() + ); + } +} + +// src/compiler/transformers/es2017.ts +function transformES2017(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + resumeLexicalEnvironment, + endLexicalEnvironment, + hoistVariableDeclaration + } = context; + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + let enabledSubstitutions = 0 /* None */; + let enclosingSuperContainerFlags = 0; + let enclosingFunctionParameterNames; + let capturedSuperProperties; + let hasSuperElementAccess; + let lexicalArgumentsBinding; + const substitutedSuperAccessors = []; + let contextFlags = 0 /* None */; + const previousOnEmitNode = context.onEmitNode; + const previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + setContextFlag(1 /* NonTopLevel */, false); + setContextFlag(2 /* HasLexicalThis */, !isEffectiveStrictModeSourceFile(node, compilerOptions)); + const visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function setContextFlag(flag, val) { + contextFlags = val ? contextFlags | flag : contextFlags & ~flag; + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inTopLevelContext() { + return !inContext(1 /* NonTopLevel */); + } + function inHasLexicalThisContext() { + return inContext(2 /* HasLexicalThis */); + } + function doWithContext(flags, cb, value) { + const contextFlagsToSet = flags & ~contextFlags; + if (contextFlagsToSet) { + setContextFlag( + contextFlagsToSet, + /*val*/ + true + ); + const result = cb(value); + setContextFlag( + contextFlagsToSet, + /*val*/ + false + ); + return result; + } + return cb(value); + } + function visitDefault(node) { + return visitEachChild(node, visitor, context); + } + function argumentsVisitor(node) { + switch (node.kind) { + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 176 /* Constructor */: + return node; + case 169 /* Parameter */: + case 208 /* BindingElement */: + case 260 /* VariableDeclaration */: + break; + case 80 /* Identifier */: + if (lexicalArgumentsBinding && resolver.isArgumentsLocalBinding(node)) { + return lexicalArgumentsBinding; + } + break; + } + return visitEachChild(node, argumentsVisitor, context); + } + function visitor(node) { + if ((node.transformFlags & 256 /* ContainsES2017 */) === 0) { + return lexicalArgumentsBinding ? argumentsVisitor(node) : node; + } + switch (node.kind) { + case 134 /* AsyncKeyword */: + return void 0; + case 223 /* AwaitExpression */: + return visitAwaitExpression(node); + case 174 /* MethodDeclaration */: + return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node); + case 262 /* FunctionDeclaration */: + return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node); + case 218 /* FunctionExpression */: + return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node); + case 219 /* ArrowFunction */: + return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node); + case 211 /* PropertyAccessExpression */: + if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 108 /* SuperKeyword */) { + capturedSuperProperties.add(node.name.escapedText); + } + return visitEachChild(node, visitor, context); + case 212 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 108 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return visitEachChild(node, visitor, context); + case 177 /* GetAccessor */: + return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitGetAccessorDeclaration, node); + case 178 /* SetAccessor */: + return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitSetAccessorDeclaration, node); + case 176 /* Constructor */: + return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitConstructorDeclaration, node); + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node); + default: + return visitEachChild(node, visitor, context); + } + } + function asyncBodyVisitor(node) { + if (isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 243 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 248 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 249 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 250 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 299 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 241 /* Block */: + case 255 /* SwitchStatement */: + case 269 /* CaseBlock */: + case 296 /* CaseClause */: + case 297 /* DefaultClause */: + case 258 /* TryStatement */: + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + case 245 /* IfStatement */: + case 254 /* WithStatement */: + case 256 /* LabeledStatement */: + return visitEachChild(node, asyncBodyVisitor, context); + default: + return Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + const catchClauseNames = /* @__PURE__ */ new Set(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + let catchClauseUnshadowedNames; + catchClauseNames.forEach((_, escapedName) => { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = new Set(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + const savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + const result = visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } else { + return visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + const expression = visitVariableDeclarationListWithCollidingNames( + node.declarationList, + /*hasReceiver*/ + false + ); + return expression ? factory2.createExpressionStatement(expression) : void 0; + } + return visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return factory2.updateForInStatement( + node, + isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames( + node.initializer, + /*hasReceiver*/ + true + ) : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + visitIterationBody(node.statement, asyncBodyVisitor, context) + ); + } + function visitForOfStatementInAsyncBody(node) { + return factory2.updateForOfStatement( + node, + visitNode(node.awaitModifier, visitor, isAwaitKeyword), + isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames( + node.initializer, + /*hasReceiver*/ + true + ) : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + visitIterationBody(node.statement, asyncBodyVisitor, context) + ); + } + function visitForStatementInAsyncBody(node) { + const initializer = node.initializer; + return factory2.updateForStatement( + node, + isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames( + initializer, + /*hasReceiver*/ + false + ) : visitNode(node.initializer, visitor, isForInitializer), + visitNode(node.condition, visitor, isExpression), + visitNode(node.incrementor, visitor, isExpression), + visitIterationBody(node.statement, asyncBodyVisitor, context) + ); + } + function visitAwaitExpression(node) { + if (inTopLevelContext()) { + return visitEachChild(node, visitor, context); + } + return setOriginalNode( + setTextRange( + factory2.createYieldExpression( + /*asteriskToken*/ + void 0, + visitNode(node.expression, visitor, isExpression) + ), + node + ), + node + ); + } + function visitConstructorDeclaration(node) { + const savedLexicalArgumentsBinding = lexicalArgumentsBinding; + lexicalArgumentsBinding = void 0; + const updated = factory2.updateConstructorDeclaration( + node, + visitNodes2(node.modifiers, visitor, isModifier), + visitParameterList(node.parameters, visitor, context), + transformMethodBody(node) + ); + lexicalArgumentsBinding = savedLexicalArgumentsBinding; + return updated; + } + function visitMethodDeclaration(node) { + let parameters; + const functionFlags = getFunctionFlags(node); + const savedLexicalArgumentsBinding = lexicalArgumentsBinding; + lexicalArgumentsBinding = void 0; + const updated = factory2.updateMethodDeclaration( + node, + visitNodes2(node.modifiers, visitor, isModifierLike), + node.asteriskToken, + node.name, + /*questionToken*/ + void 0, + /*typeParameters*/ + void 0, + parameters = functionFlags & 2 /* Async */ ? transformAsyncFunctionParameterList(node) : visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + functionFlags & 2 /* Async */ ? transformAsyncFunctionBody(node, parameters) : transformMethodBody(node) + ); + lexicalArgumentsBinding = savedLexicalArgumentsBinding; + return updated; + } + function visitGetAccessorDeclaration(node) { + const savedLexicalArgumentsBinding = lexicalArgumentsBinding; + lexicalArgumentsBinding = void 0; + const updated = factory2.updateGetAccessorDeclaration( + node, + visitNodes2(node.modifiers, visitor, isModifierLike), + node.name, + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + transformMethodBody(node) + ); + lexicalArgumentsBinding = savedLexicalArgumentsBinding; + return updated; + } + function visitSetAccessorDeclaration(node) { + const savedLexicalArgumentsBinding = lexicalArgumentsBinding; + lexicalArgumentsBinding = void 0; + const updated = factory2.updateSetAccessorDeclaration( + node, + visitNodes2(node.modifiers, visitor, isModifierLike), + node.name, + visitParameterList(node.parameters, visitor, context), + transformMethodBody(node) + ); + lexicalArgumentsBinding = savedLexicalArgumentsBinding; + return updated; + } + function visitFunctionDeclaration(node) { + let parameters; + const savedLexicalArgumentsBinding = lexicalArgumentsBinding; + lexicalArgumentsBinding = void 0; + const functionFlags = getFunctionFlags(node); + const updated = factory2.updateFunctionDeclaration( + node, + visitNodes2(node.modifiers, visitor, isModifierLike), + node.asteriskToken, + node.name, + /*typeParameters*/ + void 0, + parameters = functionFlags & 2 /* Async */ ? transformAsyncFunctionParameterList(node) : visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + functionFlags & 2 /* Async */ ? transformAsyncFunctionBody(node, parameters) : visitFunctionBody(node.body, visitor, context) + ); + lexicalArgumentsBinding = savedLexicalArgumentsBinding; + return updated; + } + function visitFunctionExpression(node) { + let parameters; + const savedLexicalArgumentsBinding = lexicalArgumentsBinding; + lexicalArgumentsBinding = void 0; + const functionFlags = getFunctionFlags(node); + const updated = factory2.updateFunctionExpression( + node, + visitNodes2(node.modifiers, visitor, isModifier), + node.asteriskToken, + node.name, + /*typeParameters*/ + void 0, + parameters = functionFlags & 2 /* Async */ ? transformAsyncFunctionParameterList(node) : visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + functionFlags & 2 /* Async */ ? transformAsyncFunctionBody(node, parameters) : visitFunctionBody(node.body, visitor, context) + ); + lexicalArgumentsBinding = savedLexicalArgumentsBinding; + return updated; + } + function visitArrowFunction(node) { + let parameters; + const functionFlags = getFunctionFlags(node); + return factory2.updateArrowFunction( + node, + visitNodes2(node.modifiers, visitor, isModifier), + /*typeParameters*/ + void 0, + parameters = functionFlags & 2 /* Async */ ? transformAsyncFunctionParameterList(node) : visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + node.equalsGreaterThanToken, + functionFlags & 2 /* Async */ ? transformAsyncFunctionBody(node, parameters) : visitFunctionBody(node.body, visitor, context) + ); + } + function recordDeclarationName({ name }, names) { + if (isIdentifier(name)) { + names.add(name.escapedText); + } else { + for (const element of name.elements) { + if (!isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return !!node && isVariableDeclarationList(node) && !(node.flags & 7 /* BlockScoped */) && node.declarations.some(collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + const variables = getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return visitNode(factory2.converters.convertToAssignmentElementTarget(node.declarations[0].name), visitor, isExpression); + } + return void 0; + } + return factory2.inlineExpressions(map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + forEach(node.declarations, hoistVariable); + } + function hoistVariable({ name }) { + if (isIdentifier(name)) { + hoistVariableDeclaration(name); + } else { + for (const element of name.elements) { + if (!isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + const converted = setSourceMapRange( + factory2.createAssignment( + factory2.converters.convertToAssignmentElementTarget(node.name), + node.initializer + ), + node + ); + return Debug.checkDefined(visitNode(converted, visitor, isExpression)); + } + function collidesWithParameterName({ name }) { + if (isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } else { + for (const element of name.elements) { + if (!isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } + function transformMethodBody(node) { + Debug.assertIsDefined(node.body); + const savedCapturedSuperProperties = capturedSuperProperties; + const savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = /* @__PURE__ */ new Set(); + hasSuperElementAccess = false; + let updated = visitFunctionBody(node.body, visitor, context); + const originalMethod = getOriginalNode(node, isFunctionLikeDeclaration); + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) && (getFunctionFlags(originalMethod) & 3 /* AsyncGenerator */) !== 3 /* AsyncGenerator */; + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + if (capturedSuperProperties.size) { + const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[getNodeId(variableStatement)] = true; + const statements = updated.statements.slice(); + insertStatementsAfterStandardPrologue(statements, [variableStatement]); + updated = factory2.updateBlock(updated, statements); + } + if (hasSuperElementAccess) { + if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) { + addEmitHelper(updated, advancedAsyncSuperHelper); + } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) { + addEmitHelper(updated, asyncSuperHelper); + } + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return updated; + } + function createCaptureArgumentsStatement() { + Debug.assert(lexicalArgumentsBinding); + const variable = factory2.createVariableDeclaration( + lexicalArgumentsBinding, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createIdentifier("arguments") + ); + const statement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + [variable] + ); + startOnNewLine(statement); + addEmitFlags(statement, 2097152 /* CustomPrologue */); + return statement; + } + function transformAsyncFunctionParameterList(node) { + if (isSimpleParameterList(node.parameters)) { + return visitParameterList(node.parameters, visitor, context); + } + const newParameters = []; + for (const parameter of node.parameters) { + if (parameter.initializer || parameter.dotDotDotToken) { + if (node.kind === 219 /* ArrowFunction */) { + const restParameter = factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + factory2.createToken(26 /* DotDotDotToken */), + factory2.createUniqueName("args", 8 /* ReservedInNestedScopes */) + ); + newParameters.push(restParameter); + } + break; + } + const newParameter = factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + factory2.getGeneratedNameForNode(parameter.name, 8 /* ReservedInNestedScopes */) + ); + newParameters.push(newParameter); + } + const newParametersArray = factory2.createNodeArray(newParameters); + setTextRange(newParametersArray, node.parameters); + return newParametersArray; + } + function transformAsyncFunctionBody(node, outerParameters) { + const innerParameters = !isSimpleParameterList(node.parameters) ? visitParameterList(node.parameters, visitor, context) : void 0; + resumeLexicalEnvironment(); + const original = getOriginalNode(node, isFunctionLike); + const nodeType = original.type; + const promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : void 0; + const isArrowFunction2 = node.kind === 219 /* ArrowFunction */; + const savedLexicalArgumentsBinding = lexicalArgumentsBinding; + const hasLexicalArguments = resolver.hasNodeCheckFlag(node, 512 /* CaptureArguments */); + const captureLexicalArguments = hasLexicalArguments && !lexicalArgumentsBinding; + if (captureLexicalArguments) { + lexicalArgumentsBinding = factory2.createUniqueName("arguments"); + } + let argumentsExpression; + if (innerParameters) { + if (isArrowFunction2) { + const parameterBindings = []; + Debug.assert(outerParameters.length <= node.parameters.length); + for (let i = 0; i < node.parameters.length; i++) { + Debug.assert(i < outerParameters.length); + const originalParameter = node.parameters[i]; + const outerParameter = outerParameters[i]; + Debug.assertNode(outerParameter.name, isIdentifier); + if (originalParameter.initializer || originalParameter.dotDotDotToken) { + Debug.assert(i === outerParameters.length - 1); + parameterBindings.push(factory2.createSpreadElement(outerParameter.name)); + break; + } + parameterBindings.push(outerParameter.name); + } + argumentsExpression = factory2.createArrayLiteralExpression(parameterBindings); + } else { + argumentsExpression = factory2.createIdentifier("arguments"); + } + } + const savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = /* @__PURE__ */ new Set(); + for (const parameter of node.parameters) { + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + const savedCapturedSuperProperties = capturedSuperProperties; + const savedHasSuperElementAccess = hasSuperElementAccess; + if (!isArrowFunction2) { + capturedSuperProperties = /* @__PURE__ */ new Set(); + hasSuperElementAccess = false; + } + const hasLexicalThis = inHasLexicalThisContext(); + let asyncBody = transformAsyncFunctionBodyWorker(node.body); + asyncBody = factory2.updateBlock(asyncBody, factory2.mergeLexicalEnvironment(asyncBody.statements, endLexicalEnvironment())); + let result; + if (!isArrowFunction2) { + const statements = []; + statements.push( + factory2.createReturnStatement( + emitHelpers().createAwaiterHelper( + hasLexicalThis, + argumentsExpression, + promiseConstructor, + innerParameters, + asyncBody + ) + ) + ); + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + if (capturedSuperProperties.size) { + const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[getNodeId(variableStatement)] = true; + insertStatementsAfterStandardPrologue(statements, [variableStatement]); + } + } + if (captureLexicalArguments) { + insertStatementsAfterStandardPrologue(statements, [createCaptureArgumentsStatement()]); + } + const block = factory2.createBlock( + statements, + /*multiLine*/ + true + ); + setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) { + addEmitHelper(block, advancedAsyncSuperHelper); + } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) { + addEmitHelper(block, asyncSuperHelper); + } + } + result = block; + } else { + result = emitHelpers().createAwaiterHelper( + hasLexicalThis, + argumentsExpression, + promiseConstructor, + innerParameters, + asyncBody + ); + if (captureLexicalArguments) { + const block = factory2.converters.convertToFunctionBlock(result); + result = factory2.updateBlock(block, factory2.mergeLexicalEnvironment(block.statements, [createCaptureArgumentsStatement()])); + } + } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + if (!isArrowFunction2) { + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + lexicalArgumentsBinding = savedLexicalArgumentsBinding; + } + return result; + } + function transformAsyncFunctionBodyWorker(body, start) { + if (isBlock(body)) { + return factory2.updateBlock(body, visitNodes2(body.statements, asyncBodyVisitor, isStatement, start)); + } else { + return factory2.converters.convertToFunctionBlock(Debug.checkDefined(visitNode(body, asyncBodyVisitor, isConciseBody))); + } + } + function getPromiseConstructor(type) { + const typeName = type && getEntityNameFromTypeNode(type); + if (typeName && isEntityName(typeName)) { + const serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === 1 /* TypeWithConstructSignatureAndValue */ || serializationKind === 0 /* Unknown */) { + return typeName; + } + } + return void 0; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + context.enableSubstitution(213 /* CallExpression */); + context.enableSubstitution(211 /* PropertyAccessExpression */); + context.enableSubstitution(212 /* ElementAccessExpression */); + context.enableEmitNotification(263 /* ClassDeclaration */); + context.enableEmitNotification(174 /* MethodDeclaration */); + context.enableEmitNotification(177 /* GetAccessor */); + context.enableEmitNotification(178 /* SetAccessor */); + context.enableEmitNotification(176 /* Constructor */); + context.enableEmitNotification(243 /* VariableStatement */); + } + } + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + const superContainerFlags = (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */) ? 128 /* MethodWithSuperPropertyAccessInAsync */ : 0) | (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) ? 256 /* MethodWithSuperPropertyAssignmentInAsync */ : 0); + if (superContainerFlags !== enclosingSuperContainerFlags) { + const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) { + const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 211 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 212 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 213 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 108 /* SuperKeyword */) { + return setTextRange( + factory2.createPropertyAccessExpression( + factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), + node.name + ), + node + ); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 108 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod( + node.argumentExpression, + node + ); + } + return node; + } + function substituteCallExpression(node) { + const expression = node.expression; + if (isSuperProperty(expression)) { + const argumentExpression = isPropertyAccessExpression(expression) ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression); + return factory2.createCallExpression( + factory2.createPropertyAccessExpression(argumentExpression, "call"), + /*typeArguments*/ + void 0, + [ + factory2.createThis(), + ...node.arguments + ] + ); + } + return node; + } + function isSuperContainer(node) { + const kind = node.kind; + return kind === 263 /* ClassDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { + return setTextRange( + factory2.createPropertyAccessExpression( + factory2.createCallExpression( + factory2.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), + /*typeArguments*/ + void 0, + [argumentExpression] + ), + "value" + ), + location + ); + } else { + return setTextRange( + factory2.createCallExpression( + factory2.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), + /*typeArguments*/ + void 0, + [argumentExpression] + ), + location + ); + } + } +} +function createSuperAccessVariableStatement(factory2, resolver, node, names) { + const hasBinding = resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */); + const accessors = []; + names.forEach((_, key) => { + const name = unescapeLeadingUnderscores(key); + const getterAndSetter = []; + getterAndSetter.push(factory2.createPropertyAssignment( + "get", + factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + /* parameters */ + [], + /*type*/ + void 0, + /*equalsGreaterThanToken*/ + void 0, + setEmitFlags( + factory2.createPropertyAccessExpression( + setEmitFlags( + factory2.createSuper(), + 8 /* NoSubstitution */ + ), + name + ), + 8 /* NoSubstitution */ + ) + ) + )); + if (hasBinding) { + getterAndSetter.push( + factory2.createPropertyAssignment( + "set", + factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + /* parameters */ + [ + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "v", + /*questionToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ) + ], + /*type*/ + void 0, + /*equalsGreaterThanToken*/ + void 0, + factory2.createAssignment( + setEmitFlags( + factory2.createPropertyAccessExpression( + setEmitFlags( + factory2.createSuper(), + 8 /* NoSubstitution */ + ), + name + ), + 8 /* NoSubstitution */ + ), + factory2.createIdentifier("v") + ) + ) + ) + ); + } + accessors.push( + factory2.createPropertyAssignment( + name, + factory2.createObjectLiteralExpression(getterAndSetter) + ) + ); + }); + return factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + [ + factory2.createVariableDeclaration( + factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createCallExpression( + factory2.createPropertyAccessExpression( + factory2.createIdentifier("Object"), + "create" + ), + /*typeArguments*/ + void 0, + [ + factory2.createNull(), + factory2.createObjectLiteralExpression( + accessors, + /*multiLine*/ + true + ) + ] + ) + ) + ], + 2 /* Const */ + ) + ); +} + +// src/compiler/transformers/es2018.ts +function transformES2018(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + resumeLexicalEnvironment, + endLexicalEnvironment, + hoistVariableDeclaration + } = context; + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + const previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + const previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + let exportedVariableStatement = false; + let enabledSubstitutions = 0 /* None */; + let enclosingFunctionFlags; + let parametersWithPrecedingObjectRestOrSpread; + let enclosingSuperContainerFlags = 0; + let hierarchyFacts = 0; + let currentSourceFile; + let taggedTemplateStringDeclarations; + let capturedSuperProperties; + let hasSuperElementAccess; + const substitutedSuperAccessors = []; + return chainBundle(context, transformSourceFile); + function affectsSubtree(excludeFacts, includeFacts) { + return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts); + } + function enterSubtree(excludeFacts, includeFacts) { + const ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */; + return ancestorFacts; + } + function exitSubtree(ancestorFacts) { + hierarchyFacts = ancestorFacts; + } + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = append( + taggedTemplateStringDeclarations, + factory2.createVariableDeclaration(temp) + ); + } + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + const visited = visitSourceFile(node); + addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = void 0; + taggedTemplateStringDeclarations = void 0; + return visited; + } + function visitor(node) { + return visitorWorker( + node, + /*expressionResultIsUnused*/ + false + ); + } + function visitorWithUnusedExpressionResult(node) { + return visitorWorker( + node, + /*expressionResultIsUnused*/ + true + ); + } + function visitorNoAsyncModifier(node) { + if (node.kind === 134 /* AsyncKeyword */) { + return void 0; + } + return node; + } + function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) { + if (affectsSubtree(excludeFacts, includeFacts)) { + const ancestorFacts = enterSubtree(excludeFacts, includeFacts); + const result = cb(value); + exitSubtree(ancestorFacts); + return result; + } + return cb(value); + } + function visitDefault(node) { + return visitEachChild(node, visitor, context); + } + function visitorWorker(node, expressionResultIsUnused2) { + if ((node.transformFlags & 128 /* ContainsES2018 */) === 0) { + return node; + } + switch (node.kind) { + case 223 /* AwaitExpression */: + return visitAwaitExpression(node); + case 229 /* YieldExpression */: + return visitYieldExpression(node); + case 253 /* ReturnStatement */: + return visitReturnStatement(node); + case 256 /* LabeledStatement */: + return visitLabeledStatement(node); + case 210 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 226 /* BinaryExpression */: + return visitBinaryExpression(node, expressionResultIsUnused2); + case 356 /* CommaListExpression */: + return visitCommaListExpression(node, expressionResultIsUnused2); + case 299 /* CatchClause */: + return visitCatchClause(node); + case 243 /* VariableStatement */: + return visitVariableStatement(node); + case 260 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + case 249 /* ForInStatement */: + return doWithHierarchyFacts( + visitDefault, + node, + 0 /* IterationStatementExcludes */, + 2 /* IterationStatementIncludes */ + ); + case 250 /* ForOfStatement */: + return visitForOfStatement( + node, + /*outermostLabeledStatement*/ + void 0 + ); + case 248 /* ForStatement */: + return doWithHierarchyFacts( + visitForStatement, + node, + 0 /* IterationStatementExcludes */, + 2 /* IterationStatementIncludes */ + ); + case 222 /* VoidExpression */: + return visitVoidExpression(node); + case 176 /* Constructor */: + return doWithHierarchyFacts( + visitConstructorDeclaration, + node, + 2 /* ClassOrFunctionExcludes */, + 1 /* ClassOrFunctionIncludes */ + ); + case 174 /* MethodDeclaration */: + return doWithHierarchyFacts( + visitMethodDeclaration, + node, + 2 /* ClassOrFunctionExcludes */, + 1 /* ClassOrFunctionIncludes */ + ); + case 177 /* GetAccessor */: + return doWithHierarchyFacts( + visitGetAccessorDeclaration, + node, + 2 /* ClassOrFunctionExcludes */, + 1 /* ClassOrFunctionIncludes */ + ); + case 178 /* SetAccessor */: + return doWithHierarchyFacts( + visitSetAccessorDeclaration, + node, + 2 /* ClassOrFunctionExcludes */, + 1 /* ClassOrFunctionIncludes */ + ); + case 262 /* FunctionDeclaration */: + return doWithHierarchyFacts( + visitFunctionDeclaration, + node, + 2 /* ClassOrFunctionExcludes */, + 1 /* ClassOrFunctionIncludes */ + ); + case 218 /* FunctionExpression */: + return doWithHierarchyFacts( + visitFunctionExpression, + node, + 2 /* ClassOrFunctionExcludes */, + 1 /* ClassOrFunctionIncludes */ + ); + case 219 /* ArrowFunction */: + return doWithHierarchyFacts( + visitArrowFunction, + node, + 2 /* ArrowFunctionExcludes */, + 0 /* ArrowFunctionIncludes */ + ); + case 169 /* Parameter */: + return visitParameter(node); + case 244 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 217 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, expressionResultIsUnused2); + case 215 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 211 /* PropertyAccessExpression */: + if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 108 /* SuperKeyword */) { + capturedSuperProperties.add(node.name.escapedText); + } + return visitEachChild(node, visitor, context); + case 212 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 108 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return visitEachChild(node, visitor, context); + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + return doWithHierarchyFacts( + visitDefault, + node, + 2 /* ClassOrFunctionExcludes */, + 1 /* ClassOrFunctionIncludes */ + ); + default: + return visitEachChild(node, visitor, context); + } + } + function visitAwaitExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return setOriginalNode( + setTextRange( + factory2.createYieldExpression( + /*asteriskToken*/ + void 0, + emitHelpers().createAwaitHelper(visitNode(node.expression, visitor, isExpression)) + ), + /*location*/ + node + ), + node + ); + } + return visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + const expression = visitNode(Debug.checkDefined(node.expression), visitor, isExpression); + return setOriginalNode( + setTextRange( + factory2.createYieldExpression( + /*asteriskToken*/ + void 0, + emitHelpers().createAwaitHelper( + factory2.updateYieldExpression( + node, + node.asteriskToken, + setTextRange( + emitHelpers().createAsyncDelegatorHelper( + setTextRange( + emitHelpers().createAsyncValuesHelper(expression), + expression + ) + ), + expression + ) + ) + ) + ), + node + ), + node + ); + } + return setOriginalNode( + setTextRange( + factory2.createYieldExpression( + /*asteriskToken*/ + void 0, + createDownlevelAwait( + node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero() + ) + ), + node + ), + node + ); + } + return visitEachChild(node, visitor, context); + } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return factory2.updateReturnStatement( + node, + createDownlevelAwait( + node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero() + ) + ); + } + return visitEachChild(node, visitor, context); + } + function visitLabeledStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */) { + const statement = unwrapInnermostStatementOfLabel(node); + if (statement.kind === 250 /* ForOfStatement */ && statement.awaitModifier) { + return visitForOfStatement(statement, node); + } + return factory2.restoreEnclosingLabel(visitNode(statement, visitor, isStatement, factory2.liftToBlock), node); + } + return visitEachChild(node, visitor, context); + } + function chunkObjectLiteralElements(elements) { + let chunkObject; + const objects = []; + for (const e of elements) { + if (e.kind === 305 /* SpreadAssignment */) { + if (chunkObject) { + objects.push(factory2.createObjectLiteralExpression(chunkObject)); + chunkObject = void 0; + } + const target = e.expression; + objects.push(visitNode(target, visitor, isExpression)); + } else { + chunkObject = append( + chunkObject, + e.kind === 303 /* PropertyAssignment */ ? factory2.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) : visitNode(e, visitor, isObjectLiteralElementLike) + ); + } + } + if (chunkObject) { + objects.push(factory2.createObjectLiteralExpression(chunkObject)); + } + return objects; + } + function visitObjectLiteralExpression(node) { + if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { + const objects = chunkObjectLiteralElements(node.properties); + if (objects.length && objects[0].kind !== 210 /* ObjectLiteralExpression */) { + objects.unshift(factory2.createObjectLiteralExpression()); + } + let expression = objects[0]; + if (objects.length > 1) { + for (let i = 1; i < objects.length; i++) { + expression = emitHelpers().createAssignHelper([expression, objects[i]]); + } + return expression; + } else { + return emitHelpers().createAssignHelper(objects); + } + } + return visitEachChild(node, visitor, context); + } + function visitExpressionStatement(node) { + return visitEachChild(node, visitorWithUnusedExpressionResult, context); + } + function visitParenthesizedExpression(node, expressionResultIsUnused2) { + return visitEachChild(node, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, context); + } + function visitSourceFile(node) { + const ancestorFacts = enterSubtree( + 2 /* SourceFileExcludes */, + isEffectiveStrictModeSourceFile(node, compilerOptions) ? 0 /* StrictModeSourceFileIncludes */ : 1 /* SourceFileIncludes */ + ); + exportedVariableStatement = false; + const visited = visitEachChild(node, visitor, context); + const statement = concatenate( + visited.statements, + taggedTemplateStringDeclarations && [ + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList(taggedTemplateStringDeclarations) + ) + ] + ); + const result = factory2.updateSourceFile(visited, setTextRange(factory2.createNodeArray(statement), node.statements)); + exitSubtree(ancestorFacts); + return result; + } + function visitTaggedTemplateExpression(node) { + return processTaggedTemplateExpression( + context, + node, + visitor, + currentSourceFile, + recordTaggedTemplateString, + 0 /* LiftRestriction */ + ); + } + function visitBinaryExpression(node, expressionResultIsUnused2) { + if (isDestructuringAssignment(node) && containsObjectRestOrSpread(node.left)) { + return flattenDestructuringAssignment( + node, + visitor, + context, + 1 /* ObjectRest */, + !expressionResultIsUnused2 + ); + } + if (node.operatorToken.kind === 28 /* CommaToken */) { + return factory2.updateBinaryExpression( + node, + visitNode(node.left, visitorWithUnusedExpressionResult, isExpression), + node.operatorToken, + visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression) + ); + } + return visitEachChild(node, visitor, context); + } + function visitCommaListExpression(node, expressionResultIsUnused2) { + if (expressionResultIsUnused2) { + return visitEachChild(node, visitorWithUnusedExpressionResult, context); + } + let result; + for (let i = 0; i < node.elements.length; i++) { + const element = node.elements[i]; + const visited = visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, isExpression); + if (result || visited !== element) { + result || (result = node.elements.slice(0, i)); + result.push(visited); + } + } + const elements = result ? setTextRange(factory2.createNodeArray(result), node.elements) : node.elements; + return factory2.updateCommaListExpression(node, elements); + } + function visitCatchClause(node) { + if (node.variableDeclaration && isBindingPattern(node.variableDeclaration.name) && node.variableDeclaration.name.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { + const name = factory2.getGeneratedNameForNode(node.variableDeclaration.name); + const updatedDecl = factory2.updateVariableDeclaration( + node.variableDeclaration, + node.variableDeclaration.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + name + ); + const visitedBindings = flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */); + let block = visitNode(node.block, visitor, isBlock); + if (some(visitedBindings)) { + block = factory2.updateBlock(block, [ + factory2.createVariableStatement( + /*modifiers*/ + void 0, + visitedBindings + ), + ...block.statements + ]); + } + return factory2.updateCatchClause( + node, + factory2.updateVariableDeclaration( + node.variableDeclaration, + name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ), + block + ); + } + return visitEachChild(node, visitor, context); + } + function visitVariableStatement(node) { + if (hasSyntacticModifier(node, 32 /* Export */)) { + const savedExportedVariableStatement = exportedVariableStatement; + exportedVariableStatement = true; + const visited = visitEachChild(node, visitor, context); + exportedVariableStatement = savedExportedVariableStatement; + return visited; + } + return visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + if (exportedVariableStatement) { + const savedExportedVariableStatement = exportedVariableStatement; + exportedVariableStatement = false; + const visited = visitVariableDeclarationWorker( + node, + /*exportedVariableStatement*/ + true + ); + exportedVariableStatement = savedExportedVariableStatement; + return visited; + } + return visitVariableDeclarationWorker( + node, + /*exportedVariableStatement*/ + false + ); + } + function visitVariableDeclarationWorker(node, exportedVariableStatement2) { + if (isBindingPattern(node.name) && node.name.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { + return flattenDestructuringBinding( + node, + visitor, + context, + 1 /* ObjectRest */, + /*rval*/ + void 0, + exportedVariableStatement2 + ); + } + return visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + return factory2.updateForStatement( + node, + visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), + visitNode(node.condition, visitor, isExpression), + visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), + visitIterationBody(node.statement, visitor, context) + ); + } + function visitVoidExpression(node) { + return visitEachChild(node, visitorWithUnusedExpressionResult, context); + } + function visitForOfStatement(node, outermostLabeledStatement) { + const ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); + if (node.initializer.transformFlags & 65536 /* ContainsObjectRestOrSpread */ || isAssignmentPattern(node.initializer) && containsObjectRestOrSpread(node.initializer)) { + node = transformForOfStatementWithObjectRest(node); + } + const result = node.awaitModifier ? transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : factory2.restoreEnclosingLabel(visitEachChild(node, visitor, context), outermostLabeledStatement); + exitSubtree(ancestorFacts); + return result; + } + function transformForOfStatementWithObjectRest(node) { + const initializerWithoutParens = skipParentheses(node.initializer); + if (isVariableDeclarationList(initializerWithoutParens) || isAssignmentPattern(initializerWithoutParens)) { + let bodyLocation; + let statementsLocation; + const temp = factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const statements = [createForOfBindingStatement(factory2, initializerWithoutParens, temp)]; + if (isBlock(node.statement)) { + addRange(statements, node.statement.statements); + bodyLocation = node.statement; + statementsLocation = node.statement.statements; + } else if (node.statement) { + append(statements, node.statement); + bodyLocation = node.statement; + statementsLocation = node.statement; + } + return factory2.updateForOfStatement( + node, + node.awaitModifier, + setTextRange( + factory2.createVariableDeclarationList( + [ + setTextRange(factory2.createVariableDeclaration(temp), node.initializer) + ], + 1 /* Let */ + ), + node.initializer + ), + node.expression, + setTextRange( + factory2.createBlock( + setTextRange(factory2.createNodeArray(statements), statementsLocation), + /*multiLine*/ + true + ), + bodyLocation + ) + ); + } + return node; + } + function convertForOfStatementHead(node, boundValue, nonUserCode) { + const value = factory2.createTempVariable(hoistVariableDeclaration); + const iteratorValueExpression = factory2.createAssignment(value, boundValue); + const iteratorValueStatement = factory2.createExpressionStatement(iteratorValueExpression); + setSourceMapRange(iteratorValueStatement, node.expression); + const exitNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createFalse()); + const exitNonUserCodeStatement = factory2.createExpressionStatement(exitNonUserCodeExpression); + setSourceMapRange(exitNonUserCodeStatement, node.expression); + const statements = [iteratorValueStatement, exitNonUserCodeStatement]; + const binding = createForOfBindingStatement(factory2, node.initializer, value); + statements.push(visitNode(binding, visitor, isStatement)); + let bodyLocation; + let statementsLocation; + const statement = visitIterationBody(node.statement, visitor, context); + if (isBlock(statement)) { + addRange(statements, statement.statements); + bodyLocation = statement; + statementsLocation = statement.statements; + } else { + statements.push(statement); + } + return setTextRange( + factory2.createBlock( + setTextRange(factory2.createNodeArray(statements), statementsLocation), + /*multiLine*/ + true + ), + bodyLocation + ); + } + function createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 /* Generator */ ? factory2.createYieldExpression( + /*asteriskToken*/ + void 0, + emitHelpers().createAwaitHelper(expression) + ) : factory2.createAwaitExpression(expression); + } + function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) { + const expression = visitNode(node.expression, visitor, isExpression); + const iterator = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const result = isIdentifier(expression) ? factory2.getGeneratedNameForNode(iterator) : factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const nonUserCode = factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const done = factory2.createTempVariable(hoistVariableDeclaration); + const errorRecord = factory2.createUniqueName("e"); + const catchVariable = factory2.getGeneratedNameForNode(errorRecord); + const returnMethod = factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const callValues = setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression); + const callNext = factory2.createCallExpression( + factory2.createPropertyAccessExpression(iterator, "next"), + /*typeArguments*/ + void 0, + [] + ); + const getDone = factory2.createPropertyAccessExpression(result, "done"); + const getValue = factory2.createPropertyAccessExpression(result, "value"); + const callReturn = factory2.createFunctionCallCall(returnMethod, iterator, []); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + const initializer = ancestorFacts & 2 /* IterationContainer */ ? factory2.inlineExpressions([factory2.createAssignment(errorRecord, factory2.createVoidZero()), callValues]) : callValues; + const forStatement = setEmitFlags( + setTextRange( + factory2.createForStatement( + /*initializer*/ + setEmitFlags( + setTextRange( + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + nonUserCode, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createTrue() + ), + setTextRange(factory2.createVariableDeclaration( + iterator, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + initializer + ), node.expression), + factory2.createVariableDeclaration(result) + ]), + node.expression + ), + 4194304 /* NoHoisting */ + ), + /*condition*/ + factory2.inlineExpressions([ + factory2.createAssignment(result, createDownlevelAwait(callNext)), + factory2.createAssignment(done, getDone), + factory2.createLogicalNot(done) + ]), + /*incrementor*/ + factory2.createAssignment(nonUserCode, factory2.createTrue()), + /*statement*/ + convertForOfStatementHead(node, getValue, nonUserCode) + ), + /*location*/ + node + ), + 512 /* NoTokenTrailingSourceMaps */ + ); + setOriginalNode(forStatement, node); + return factory2.createTryStatement( + factory2.createBlock([ + factory2.restoreEnclosingLabel( + forStatement, + outermostLabeledStatement + ) + ]), + factory2.createCatchClause( + factory2.createVariableDeclaration(catchVariable), + setEmitFlags( + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment( + errorRecord, + factory2.createObjectLiteralExpression([ + factory2.createPropertyAssignment("error", catchVariable) + ]) + ) + ) + ]), + 1 /* SingleLine */ + ) + ), + factory2.createBlock([ + factory2.createTryStatement( + /*tryBlock*/ + factory2.createBlock([ + setEmitFlags( + factory2.createIfStatement( + factory2.createLogicalAnd( + factory2.createLogicalAnd( + factory2.createLogicalNot(nonUserCode), + factory2.createLogicalNot(done) + ), + factory2.createAssignment( + returnMethod, + factory2.createPropertyAccessExpression(iterator, "return") + ) + ), + factory2.createExpressionStatement(createDownlevelAwait(callReturn)) + ), + 1 /* SingleLine */ + ) + ]), + /*catchClause*/ + void 0, + /*finallyBlock*/ + setEmitFlags( + factory2.createBlock([ + setEmitFlags( + factory2.createIfStatement( + errorRecord, + factory2.createThrowStatement( + factory2.createPropertyAccessExpression(errorRecord, "error") + ) + ), + 1 /* SingleLine */ + ) + ]), + 1 /* SingleLine */ + ) + ) + ]) + ); + } + function parameterVisitor(node) { + Debug.assertNode(node, isParameter); + return visitParameter(node); + } + function visitParameter(node) { + if (parametersWithPrecedingObjectRestOrSpread == null ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { + return factory2.updateParameterDeclaration( + node, + /*modifiers*/ + void 0, + node.dotDotDotToken, + isBindingPattern(node.name) ? factory2.getGeneratedNameForNode(node) : node.name, + /*questionToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ); + } + if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { + return factory2.updateParameterDeclaration( + node, + /*modifiers*/ + void 0, + node.dotDotDotToken, + factory2.getGeneratedNameForNode(node), + /*questionToken*/ + void 0, + /*type*/ + void 0, + visitNode(node.initializer, visitor, isExpression) + ); + } + return visitEachChild(node, visitor, context); + } + function collectParametersWithPrecedingObjectRestOrSpread(node) { + let parameters; + for (const parameter of node.parameters) { + if (parameters) { + parameters.add(parameter); + } else if (parameter.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { + parameters = /* @__PURE__ */ new Set(); + } + } + return parameters; + } + function visitConstructorDeclaration(node) { + const savedEnclosingFunctionFlags = enclosingFunctionFlags; + const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); + const updated = factory2.updateConstructorDeclaration( + node, + node.modifiers, + visitParameterList(node.parameters, parameterVisitor, context), + transformFunctionBody(node) + ); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; + return updated; + } + function visitGetAccessorDeclaration(node) { + const savedEnclosingFunctionFlags = enclosingFunctionFlags; + const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); + const updated = factory2.updateGetAccessorDeclaration( + node, + node.modifiers, + visitNode(node.name, visitor, isPropertyName), + visitParameterList(node.parameters, parameterVisitor, context), + /*type*/ + void 0, + transformFunctionBody(node) + ); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; + return updated; + } + function visitSetAccessorDeclaration(node) { + const savedEnclosingFunctionFlags = enclosingFunctionFlags; + const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); + const updated = factory2.updateSetAccessorDeclaration( + node, + node.modifiers, + visitNode(node.name, visitor, isPropertyName), + visitParameterList(node.parameters, parameterVisitor, context), + transformFunctionBody(node) + ); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; + return updated; + } + function visitMethodDeclaration(node) { + const savedEnclosingFunctionFlags = enclosingFunctionFlags; + const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); + const updated = factory2.updateMethodDeclaration( + node, + enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifierLike) : node.modifiers, + enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, + visitNode(node.name, visitor, isPropertyName), + visitNode( + /*node*/ + void 0, + visitor, + isQuestionToken + ), + /*typeParameters*/ + void 0, + enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionParameterList(node) : visitParameterList(node.parameters, parameterVisitor, context), + /*type*/ + void 0, + enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node) + ); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; + return updated; + } + function visitFunctionDeclaration(node) { + const savedEnclosingFunctionFlags = enclosingFunctionFlags; + const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); + const updated = factory2.updateFunctionDeclaration( + node, + enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifier) : node.modifiers, + enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, + node.name, + /*typeParameters*/ + void 0, + enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionParameterList(node) : visitParameterList(node.parameters, parameterVisitor, context), + /*type*/ + void 0, + enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node) + ); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; + return updated; + } + function visitArrowFunction(node) { + const savedEnclosingFunctionFlags = enclosingFunctionFlags; + const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); + const updated = factory2.updateArrowFunction( + node, + node.modifiers, + /*typeParameters*/ + void 0, + visitParameterList(node.parameters, parameterVisitor, context), + /*type*/ + void 0, + node.equalsGreaterThanToken, + transformFunctionBody(node) + ); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; + return updated; + } + function visitFunctionExpression(node) { + const savedEnclosingFunctionFlags = enclosingFunctionFlags; + const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); + const updated = factory2.updateFunctionExpression( + node, + enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifier) : node.modifiers, + enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, + node.name, + /*typeParameters*/ + void 0, + enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionParameterList(node) : visitParameterList(node.parameters, parameterVisitor, context), + /*type*/ + void 0, + enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node) + ); + enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; + return updated; + } + function transformAsyncGeneratorFunctionParameterList(node) { + if (isSimpleParameterList(node.parameters)) { + return visitParameterList(node.parameters, visitor, context); + } + const newParameters = []; + for (const parameter of node.parameters) { + if (parameter.initializer || parameter.dotDotDotToken) { + break; + } + const newParameter = factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + factory2.getGeneratedNameForNode(parameter.name, 8 /* ReservedInNestedScopes */) + ); + newParameters.push(newParameter); + } + const newParametersArray = factory2.createNodeArray(newParameters); + setTextRange(newParametersArray, node.parameters); + return newParametersArray; + } + function transformAsyncGeneratorFunctionBody(node) { + const innerParameters = !isSimpleParameterList(node.parameters) ? visitParameterList(node.parameters, visitor, context) : void 0; + resumeLexicalEnvironment(); + const savedCapturedSuperProperties = capturedSuperProperties; + const savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = /* @__PURE__ */ new Set(); + hasSuperElementAccess = false; + const outerStatements = []; + let asyncBody = factory2.updateBlock(node.body, visitNodes2(node.body.statements, visitor, isStatement)); + asyncBody = factory2.updateBlock(asyncBody, factory2.mergeLexicalEnvironment(asyncBody.statements, appendObjectRestAssignmentsIfNeeded(endLexicalEnvironment(), node))); + const returnStatement = factory2.createReturnStatement( + emitHelpers().createAsyncGeneratorHelper( + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + factory2.createToken(42 /* AsteriskToken */), + node.name && factory2.getGeneratedNameForNode(node.name), + /*typeParameters*/ + void 0, + innerParameters ?? [], + /*type*/ + void 0, + asyncBody + ), + !!(hierarchyFacts & 1 /* HasLexicalThis */) + ) + ); + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[getNodeId(variableStatement)] = true; + insertStatementsAfterStandardPrologue(outerStatements, [variableStatement]); + } + outerStatements.push(returnStatement); + const block = factory2.updateBlock(node.body, outerStatements); + if (emitSuperHelpers && hasSuperElementAccess) { + if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) { + addEmitHelper(block, advancedAsyncSuperHelper); + } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) { + addEmitHelper(block, asyncSuperHelper); + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return block; + } + function transformFunctionBody(node) { + resumeLexicalEnvironment(); + let statementOffset = 0; + const statements = []; + const body = visitNode(node.body, visitor, isConciseBody) ?? factory2.createBlock([]); + if (isBlock(body)) { + statementOffset = factory2.copyPrologue( + body.statements, + statements, + /*ensureUseStrict*/ + false, + visitor + ); + } + addRange(statements, appendObjectRestAssignmentsIfNeeded( + /*statements*/ + void 0, + node + )); + const leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || some(statements) || some(leadingStatements)) { + const block = factory2.converters.convertToFunctionBlock( + body, + /*multiLine*/ + true + ); + insertStatementsAfterStandardPrologue(statements, leadingStatements); + addRange(statements, block.statements.slice(statementOffset)); + return factory2.updateBlock(block, setTextRange(factory2.createNodeArray(statements), block.statements)); + } + return body; + } + function appendObjectRestAssignmentsIfNeeded(statements, node) { + let containsPrecedingObjectRestOrSpread = false; + for (const parameter of node.parameters) { + if (containsPrecedingObjectRestOrSpread) { + if (isBindingPattern(parameter.name)) { + if (parameter.name.elements.length > 0) { + const declarations = flattenDestructuringBinding( + parameter, + visitor, + context, + 0 /* All */, + factory2.getGeneratedNameForNode(parameter) + ); + if (some(declarations)) { + const declarationList = factory2.createVariableDeclarationList(declarations); + const statement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + declarationList + ); + setEmitFlags(statement, 2097152 /* CustomPrologue */); + statements = append(statements, statement); + } + } else if (parameter.initializer) { + const name = factory2.getGeneratedNameForNode(parameter); + const initializer = visitNode(parameter.initializer, visitor, isExpression); + const assignment = factory2.createAssignment(name, initializer); + const statement = factory2.createExpressionStatement(assignment); + setEmitFlags(statement, 2097152 /* CustomPrologue */); + statements = append(statements, statement); + } + } else if (parameter.initializer) { + const name = factory2.cloneNode(parameter.name); + setTextRange(name, parameter.name); + setEmitFlags(name, 96 /* NoSourceMap */); + const initializer = visitNode(parameter.initializer, visitor, isExpression); + addEmitFlags(initializer, 96 /* NoSourceMap */ | 3072 /* NoComments */); + const assignment = factory2.createAssignment(name, initializer); + setTextRange(assignment, parameter); + setEmitFlags(assignment, 3072 /* NoComments */); + const block = factory2.createBlock([factory2.createExpressionStatement(assignment)]); + setTextRange(block, parameter); + setEmitFlags(block, 1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */); + const typeCheck = factory2.createTypeCheck(factory2.cloneNode(parameter.name), "undefined"); + const statement = factory2.createIfStatement(typeCheck, block); + startOnNewLine(statement); + setTextRange(statement, parameter); + setEmitFlags(statement, 768 /* NoTokenSourceMaps */ | 64 /* NoTrailingSourceMap */ | 2097152 /* CustomPrologue */ | 3072 /* NoComments */); + statements = append(statements, statement); + } + } else if (parameter.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { + containsPrecedingObjectRestOrSpread = true; + const declarations = flattenDestructuringBinding( + parameter, + visitor, + context, + 1 /* ObjectRest */, + factory2.getGeneratedNameForNode(parameter), + /*hoistTempVariables*/ + false, + /*skipInitializer*/ + true + ); + if (some(declarations)) { + const declarationList = factory2.createVariableDeclarationList(declarations); + const statement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + declarationList + ); + setEmitFlags(statement, 2097152 /* CustomPrologue */); + statements = append(statements, statement); + } + } + } + return statements; + } + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) { + enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; + context.enableSubstitution(213 /* CallExpression */); + context.enableSubstitution(211 /* PropertyAccessExpression */); + context.enableSubstitution(212 /* ElementAccessExpression */); + context.enableEmitNotification(263 /* ClassDeclaration */); + context.enableEmitNotification(174 /* MethodDeclaration */); + context.enableEmitNotification(177 /* GetAccessor */); + context.enableEmitNotification(178 /* SetAccessor */); + context.enableEmitNotification(176 /* Constructor */); + context.enableEmitNotification(243 /* VariableStatement */); + } + } + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { + const superContainerFlags = (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */) ? 128 /* MethodWithSuperPropertyAccessInAsync */ : 0) | (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) ? 256 /* MethodWithSuperPropertyAssignmentInAsync */ : 0); + if (superContainerFlags !== enclosingSuperContainerFlags) { + const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = superContainerFlags; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + } else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) { + const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 211 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 212 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 213 /* CallExpression */: + return substituteCallExpression(node); + } + return node; + } + function substitutePropertyAccessExpression(node) { + if (node.expression.kind === 108 /* SuperKeyword */) { + return setTextRange( + factory2.createPropertyAccessExpression( + factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), + node.name + ), + node + ); + } + return node; + } + function substituteElementAccessExpression(node) { + if (node.expression.kind === 108 /* SuperKeyword */) { + return createSuperElementAccessInAsyncMethod( + node.argumentExpression, + node + ); + } + return node; + } + function substituteCallExpression(node) { + const expression = node.expression; + if (isSuperProperty(expression)) { + const argumentExpression = isPropertyAccessExpression(expression) ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression); + return factory2.createCallExpression( + factory2.createPropertyAccessExpression(argumentExpression, "call"), + /*typeArguments*/ + void 0, + [ + factory2.createThis(), + ...node.arguments + ] + ); + } + return node; + } + function isSuperContainer(node) { + const kind = node.kind; + return kind === 263 /* ClassDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; + } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { + if (enclosingSuperContainerFlags & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { + return setTextRange( + factory2.createPropertyAccessExpression( + factory2.createCallExpression( + factory2.createIdentifier("_superIndex"), + /*typeArguments*/ + void 0, + [argumentExpression] + ), + "value" + ), + location + ); + } else { + return setTextRange( + factory2.createCallExpression( + factory2.createIdentifier("_superIndex"), + /*typeArguments*/ + void 0, + [argumentExpression] + ), + location + ); + } + } +} + +// src/compiler/transformers/es2019.ts +function transformES2019(context) { + const factory2 = context.factory; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 64 /* ContainsES2019 */) === 0) { + return node; + } + switch (node.kind) { + case 299 /* CatchClause */: + return visitCatchClause(node); + default: + return visitEachChild(node, visitor, context); + } + } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return factory2.updateCatchClause( + node, + factory2.createVariableDeclaration(factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + )), + visitNode(node.block, visitor, isBlock) + ); + } + return visitEachChild(node, visitor, context); + } +} + +// src/compiler/transformers/es2020.ts +function transformES2020(context) { + const { + factory: factory2, + hoistVariableDeclaration + } = context; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 32 /* ContainsES2020 */) === 0) { + return node; + } + switch (node.kind) { + case 213 /* CallExpression */: { + const updated = visitNonOptionalCallExpression( + node, + /*captureThisArg*/ + false + ); + Debug.assertNotNode(updated, isSyntheticReference); + return updated; + } + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + if (isOptionalChain(node)) { + const updated = visitOptionalExpression( + node, + /*captureThisArg*/ + false, + /*isDelete*/ + false + ); + Debug.assertNotNode(updated, isSyntheticReference); + return updated; + } + return visitEachChild(node, visitor, context); + case 226 /* BinaryExpression */: + if (node.operatorToken.kind === 61 /* QuestionQuestionToken */) { + return transformNullishCoalescingExpression(node); + } + return visitEachChild(node, visitor, context); + case 220 /* DeleteExpression */: + return visitDeleteExpression(node); + default: + return visitEachChild(node, visitor, context); + } + } + function flattenChain(chain) { + Debug.assertNotNode(chain, isNonNullChain); + const links = [chain]; + while (!chain.questionDotToken && !isTaggedTemplateExpression(chain)) { + chain = cast(skipPartiallyEmittedExpressions(chain.expression), isOptionalChain); + Debug.assertNotNode(chain, isNonNullChain); + links.unshift(chain); + } + return { expression: chain.expression, chain: links }; + } + function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) { + const expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete); + if (isSyntheticReference(expression)) { + return factory2.createSyntheticReferenceExpression(factory2.updateParenthesizedExpression(node, expression.expression), expression.thisArg); + } + return factory2.updateParenthesizedExpression(node, expression); + } + function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) { + if (isOptionalChain(node)) { + return visitOptionalExpression(node, captureThisArg, isDelete); + } + let expression = visitNode(node.expression, visitor, isExpression); + Debug.assertNotNode(expression, isSyntheticReference); + let thisArg; + if (captureThisArg) { + if (!isSimpleCopiableExpression(expression)) { + thisArg = factory2.createTempVariable(hoistVariableDeclaration); + expression = factory2.createAssignment(thisArg, expression); + } else { + thisArg = expression; + } + } + expression = node.kind === 211 /* PropertyAccessExpression */ ? factory2.updatePropertyAccessExpression(node, expression, visitNode(node.name, visitor, isIdentifier)) : factory2.updateElementAccessExpression(node, expression, visitNode(node.argumentExpression, visitor, isExpression)); + return thisArg ? factory2.createSyntheticReferenceExpression(expression, thisArg) : expression; + } + function visitNonOptionalCallExpression(node, captureThisArg) { + if (isOptionalChain(node)) { + return visitOptionalExpression( + node, + captureThisArg, + /*isDelete*/ + false + ); + } + if (isParenthesizedExpression(node.expression) && isOptionalChain(skipParentheses(node.expression))) { + const expression = visitNonOptionalParenthesizedExpression( + node.expression, + /*captureThisArg*/ + true, + /*isDelete*/ + false + ); + const args = visitNodes2(node.arguments, visitor, isExpression); + if (isSyntheticReference(expression)) { + return setTextRange(factory2.createFunctionCallCall(expression.expression, expression.thisArg, args), node); + } + return factory2.updateCallExpression( + node, + expression, + /*typeArguments*/ + void 0, + args + ); + } + return visitEachChild(node, visitor, context); + } + function visitNonOptionalExpression(node, captureThisArg, isDelete) { + switch (node.kind) { + case 217 /* ParenthesizedExpression */: + return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); + case 213 /* CallExpression */: + return visitNonOptionalCallExpression(node, captureThisArg); + default: + return visitNode(node, visitor, isExpression); + } + } + function visitOptionalExpression(node, captureThisArg, isDelete) { + const { expression, chain } = flattenChain(node); + const left = visitNonOptionalExpression( + skipPartiallyEmittedExpressions(expression), + isCallChain(chain[0]), + /*isDelete*/ + false + ); + let leftThisArg = isSyntheticReference(left) ? left.thisArg : void 0; + let capturedLeft = isSyntheticReference(left) ? left.expression : left; + let leftExpression = factory2.restoreOuterExpressions(expression, capturedLeft, 8 /* PartiallyEmittedExpressions */); + if (!isSimpleCopiableExpression(capturedLeft)) { + capturedLeft = factory2.createTempVariable(hoistVariableDeclaration); + leftExpression = factory2.createAssignment(capturedLeft, leftExpression); + } + let rightExpression = capturedLeft; + let thisArg; + for (let i = 0; i < chain.length; i++) { + const segment = chain[i]; + switch (segment.kind) { + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + if (i === chain.length - 1 && captureThisArg) { + if (!isSimpleCopiableExpression(rightExpression)) { + thisArg = factory2.createTempVariable(hoistVariableDeclaration); + rightExpression = factory2.createAssignment(thisArg, rightExpression); + } else { + thisArg = rightExpression; + } + } + rightExpression = segment.kind === 211 /* PropertyAccessExpression */ ? factory2.createPropertyAccessExpression(rightExpression, visitNode(segment.name, visitor, isIdentifier)) : factory2.createElementAccessExpression(rightExpression, visitNode(segment.argumentExpression, visitor, isExpression)); + break; + case 213 /* CallExpression */: + if (i === 0 && leftThisArg) { + if (!isGeneratedIdentifier(leftThisArg)) { + leftThisArg = factory2.cloneNode(leftThisArg); + addEmitFlags(leftThisArg, 3072 /* NoComments */); + } + rightExpression = factory2.createFunctionCallCall( + rightExpression, + leftThisArg.kind === 108 /* SuperKeyword */ ? factory2.createThis() : leftThisArg, + visitNodes2(segment.arguments, visitor, isExpression) + ); + } else { + rightExpression = factory2.createCallExpression( + rightExpression, + /*typeArguments*/ + void 0, + visitNodes2(segment.arguments, visitor, isExpression) + ); + } + break; + } + setOriginalNode(rightExpression, segment); + } + const target = isDelete ? factory2.createConditionalExpression( + createNotNullCondition( + leftExpression, + capturedLeft, + /*invert*/ + true + ), + /*questionToken*/ + void 0, + factory2.createTrue(), + /*colonToken*/ + void 0, + factory2.createDeleteExpression(rightExpression) + ) : factory2.createConditionalExpression( + createNotNullCondition( + leftExpression, + capturedLeft, + /*invert*/ + true + ), + /*questionToken*/ + void 0, + factory2.createVoidZero(), + /*colonToken*/ + void 0, + rightExpression + ); + setTextRange(target, node); + return thisArg ? factory2.createSyntheticReferenceExpression(target, thisArg) : target; + } + function createNotNullCondition(left, right, invert) { + return factory2.createBinaryExpression( + factory2.createBinaryExpression( + left, + factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */), + factory2.createNull() + ), + factory2.createToken(invert ? 57 /* BarBarToken */ : 56 /* AmpersandAmpersandToken */), + factory2.createBinaryExpression( + right, + factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */), + factory2.createVoidZero() + ) + ); + } + function transformNullishCoalescingExpression(node) { + let left = visitNode(node.left, visitor, isExpression); + let right = left; + if (!isSimpleCopiableExpression(left)) { + right = factory2.createTempVariable(hoistVariableDeclaration); + left = factory2.createAssignment(right, left); + } + return setTextRange( + factory2.createConditionalExpression( + createNotNullCondition(left, right), + /*questionToken*/ + void 0, + right, + /*colonToken*/ + void 0, + visitNode(node.right, visitor, isExpression) + ), + node + ); + } + function visitDeleteExpression(node) { + return isOptionalChain(skipParentheses(node.expression)) ? setOriginalNode(visitNonOptionalExpression( + node.expression, + /*captureThisArg*/ + false, + /*isDelete*/ + true + ), node) : factory2.updateDeleteExpression(node, visitNode(node.expression, visitor, isExpression)); + } +} + +// src/compiler/transformers/es2021.ts +function transformES2021(context) { + const { + hoistVariableDeclaration, + factory: factory2 + } = context; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 16 /* ContainsES2021 */) === 0) { + return node; + } + if (isLogicalOrCoalescingAssignmentExpression(node)) { + return transformLogicalAssignment(node); + } + return visitEachChild(node, visitor, context); + } + function transformLogicalAssignment(binaryExpression) { + const operator = binaryExpression.operatorToken; + const nonAssignmentOperator = getNonAssignmentOperatorForCompoundAssignment(operator.kind); + let left = skipParentheses(visitNode(binaryExpression.left, visitor, isLeftHandSideExpression)); + let assignmentTarget = left; + const right = skipParentheses(visitNode(binaryExpression.right, visitor, isExpression)); + if (isAccessExpression(left)) { + const propertyAccessTargetSimpleCopiable = isSimpleCopiableExpression(left.expression); + const propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression : factory2.createTempVariable(hoistVariableDeclaration); + const propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory2.createAssignment( + propertyAccessTarget, + left.expression + ); + if (isPropertyAccessExpression(left)) { + assignmentTarget = factory2.createPropertyAccessExpression( + propertyAccessTarget, + left.name + ); + left = factory2.createPropertyAccessExpression( + propertyAccessTargetAssignment, + left.name + ); + } else { + const elementAccessArgumentSimpleCopiable = isSimpleCopiableExpression(left.argumentExpression); + const elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory2.createTempVariable(hoistVariableDeclaration); + assignmentTarget = factory2.createElementAccessExpression( + propertyAccessTarget, + elementAccessArgument + ); + left = factory2.createElementAccessExpression( + propertyAccessTargetAssignment, + elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory2.createAssignment( + elementAccessArgument, + left.argumentExpression + ) + ); + } + } + return factory2.createBinaryExpression( + left, + nonAssignmentOperator, + factory2.createParenthesizedExpression( + factory2.createAssignment( + assignmentTarget, + right + ) + ) + ); + } +} + +// src/compiler/transformers/esnext.ts +function transformESNext(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + hoistVariableDeclaration, + startLexicalEnvironment, + endLexicalEnvironment + } = context; + let exportBindings; + let exportVars; + let defaultExportBinding; + let exportEqualsBinding; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + const visited = visitNode(node, visitor, isSourceFile); + addEmitHelpers(visited, context.readEmitHelpers()); + exportVars = void 0; + exportBindings = void 0; + defaultExportBinding = void 0; + return visited; + } + function visitor(node) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + case 307 /* SourceFile */: + return visitSourceFile(node); + case 241 /* Block */: + return visitBlock(node); + case 248 /* ForStatement */: + return visitForStatement(node); + case 250 /* ForOfStatement */: + return visitForOfStatement(node); + case 255 /* SwitchStatement */: + return visitSwitchStatement(node); + default: + return visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + const usingKind = getUsingKindOfStatements(node.statements); + if (usingKind) { + startLexicalEnvironment(); + exportBindings = new IdentifierNameMap(); + exportVars = []; + const prologueCount = countPrologueStatements(node.statements); + const topLevelStatements = []; + addRange(topLevelStatements, visitArray(node.statements, visitor, isStatement, 0, prologueCount)); + let pos = prologueCount; + while (pos < node.statements.length) { + const statement = node.statements[pos]; + if (getUsingKind(statement) !== 0 /* None */) { + if (pos > prologueCount) { + addRange(topLevelStatements, visitNodes2(node.statements, visitor, isStatement, prologueCount, pos - prologueCount)); + } + break; + } + pos++; + } + Debug.assert(pos < node.statements.length, "Should have encountered at least one 'using' statement."); + const envBinding = createEnvBinding(); + const bodyStatements = transformUsingDeclarations(node.statements, pos, node.statements.length, envBinding, topLevelStatements); + if (exportBindings.size) { + append( + topLevelStatements, + factory2.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory2.createNamedExports(arrayFrom(exportBindings.values())) + ) + ); + } + addRange(topLevelStatements, endLexicalEnvironment()); + if (exportVars.length) { + topLevelStatements.push(factory2.createVariableStatement( + factory2.createModifiersFromModifierFlags(32 /* Export */), + factory2.createVariableDeclarationList( + exportVars, + 1 /* Let */ + ) + )); + } + addRange(topLevelStatements, createDownlevelUsingStatements(bodyStatements, envBinding, usingKind === 2 /* Async */)); + if (exportEqualsBinding) { + topLevelStatements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + true, + exportEqualsBinding + )); + } + return factory2.updateSourceFile(node, topLevelStatements); + } + return visitEachChild(node, visitor, context); + } + function visitBlock(node) { + const usingKind = getUsingKindOfStatements(node.statements); + if (usingKind) { + const prologueCount = countPrologueStatements(node.statements); + const envBinding = createEnvBinding(); + return factory2.updateBlock( + node, + [ + ...visitArray(node.statements, visitor, isStatement, 0, prologueCount), + ...createDownlevelUsingStatements( + transformUsingDeclarations( + node.statements, + prologueCount, + node.statements.length, + envBinding, + /*topLevelStatements*/ + void 0 + ), + envBinding, + usingKind === 2 /* Async */ + ) + ] + ); + } + return visitEachChild(node, visitor, context); + } + function visitForStatement(node) { + if (node.initializer && isUsingVariableDeclarationList(node.initializer)) { + return visitNode( + factory2.createBlock([ + factory2.createVariableStatement( + /*modifiers*/ + void 0, + node.initializer + ), + factory2.updateForStatement( + node, + /*initializer*/ + void 0, + node.condition, + node.incrementor, + node.statement + ) + ]), + visitor, + isStatement + ); + } + return visitEachChild(node, visitor, context); + } + function visitForOfStatement(node) { + if (isUsingVariableDeclarationList(node.initializer)) { + const forInitializer = node.initializer; + const forDecl = firstOrUndefined(forInitializer.declarations) || factory2.createVariableDeclaration(factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + )); + const isAwaitUsing = getUsingKindOfVariableDeclarationList(forInitializer) === 2 /* Async */; + const temp = factory2.getGeneratedNameForNode(forDecl.name); + const usingVar = factory2.updateVariableDeclaration( + forDecl, + forDecl.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + temp + ); + const usingVarList = factory2.createVariableDeclarationList([usingVar], isAwaitUsing ? 6 /* AwaitUsing */ : 4 /* Using */); + const usingVarStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + usingVarList + ); + return visitNode( + factory2.updateForOfStatement( + node, + node.awaitModifier, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration(temp) + ], 2 /* Const */), + node.expression, + isBlock(node.statement) ? factory2.updateBlock(node.statement, [ + usingVarStatement, + ...node.statement.statements + ]) : factory2.createBlock( + [ + usingVarStatement, + node.statement + ], + /*multiLine*/ + true + ) + ), + visitor, + isStatement + ); + } + return visitEachChild(node, visitor, context); + } + function visitCaseOrDefaultClause(node, envBinding) { + if (getUsingKindOfStatements(node.statements) !== 0 /* None */) { + if (isCaseClause(node)) { + return factory2.updateCaseClause( + node, + visitNode(node.expression, visitor, isExpression), + transformUsingDeclarations( + node.statements, + /*start*/ + 0, + node.statements.length, + envBinding, + /*topLevelStatements*/ + void 0 + ) + ); + } else { + return factory2.updateDefaultClause( + node, + transformUsingDeclarations( + node.statements, + /*start*/ + 0, + node.statements.length, + envBinding, + /*topLevelStatements*/ + void 0 + ) + ); + } + } + return visitEachChild(node, visitor, context); + } + function visitSwitchStatement(node) { + const usingKind = getUsingKindOfCaseOrDefaultClauses(node.caseBlock.clauses); + if (usingKind) { + const envBinding = createEnvBinding(); + return createDownlevelUsingStatements( + [ + factory2.updateSwitchStatement( + node, + visitNode(node.expression, visitor, isExpression), + factory2.updateCaseBlock( + node.caseBlock, + node.caseBlock.clauses.map((clause) => visitCaseOrDefaultClause(clause, envBinding)) + ) + ) + ], + envBinding, + usingKind === 2 /* Async */ + ); + } + return visitEachChild(node, visitor, context); + } + function transformUsingDeclarations(statementsIn, start, end, envBinding, topLevelStatements) { + const statements = []; + for (let i = start; i < end; i++) { + const statement = statementsIn[i]; + const usingKind = getUsingKind(statement); + if (usingKind) { + Debug.assertNode(statement, isVariableStatement); + const declarations = []; + for (let declaration of statement.declarationList.declarations) { + if (!isIdentifier(declaration.name)) { + declarations.length = 0; + break; + } + if (isNamedEvaluation(declaration)) { + declaration = transformNamedEvaluation(context, declaration); + } + const initializer = visitNode(declaration.initializer, visitor, isExpression) ?? factory2.createVoidZero(); + declarations.push(factory2.updateVariableDeclaration( + declaration, + declaration.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + emitHelpers().createAddDisposableResourceHelper( + envBinding, + initializer, + usingKind === 2 /* Async */ + ) + )); + } + if (declarations.length) { + const varList = factory2.createVariableDeclarationList(declarations, 2 /* Const */); + setOriginalNode(varList, statement.declarationList); + setTextRange(varList, statement.declarationList); + hoistOrAppendNode(factory2.updateVariableStatement( + statement, + /*modifiers*/ + void 0, + varList + )); + continue; + } + } + const result = visitor(statement); + if (isArray(result)) { + result.forEach(hoistOrAppendNode); + } else if (result) { + hoistOrAppendNode(result); + } + } + return statements; + function hoistOrAppendNode(node) { + Debug.assertNode(node, isStatement); + append(statements, hoist(node)); + } + function hoist(node) { + if (!topLevelStatements) return node; + switch (node.kind) { + case 272 /* ImportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 278 /* ExportDeclaration */: + case 262 /* FunctionDeclaration */: + return hoistImportOrExportOrHoistedDeclaration(node, topLevelStatements); + case 277 /* ExportAssignment */: + return hoistExportAssignment(node); + case 263 /* ClassDeclaration */: + return hoistClassDeclaration(node); + case 243 /* VariableStatement */: + return hoistVariableStatement(node); + } + return node; + } + } + function hoistImportOrExportOrHoistedDeclaration(node, topLevelStatements) { + topLevelStatements.push(node); + return void 0; + } + function hoistExportAssignment(node) { + return node.isExportEquals ? hoistExportEquals(node) : hoistExportDefault(node); + } + function hoistExportDefault(node) { + if (defaultExportBinding) { + return node; + } + defaultExportBinding = factory2.createUniqueName("_default", 8 /* ReservedInNestedScopes */ | 32 /* FileLevel */ | 16 /* Optimistic */); + hoistBindingIdentifier( + defaultExportBinding, + /*isExport*/ + true, + "default", + node + ); + let expression = node.expression; + let innerExpression = skipOuterExpressions(expression); + if (isNamedEvaluation(innerExpression)) { + innerExpression = transformNamedEvaluation( + context, + innerExpression, + /*ignoreEmptyStringLiteral*/ + false, + "default" + ); + expression = factory2.restoreOuterExpressions(expression, innerExpression); + } + const assignment = factory2.createAssignment(defaultExportBinding, expression); + return factory2.createExpressionStatement(assignment); + } + function hoistExportEquals(node) { + if (exportEqualsBinding) { + return node; + } + exportEqualsBinding = factory2.createUniqueName("_default", 8 /* ReservedInNestedScopes */ | 32 /* FileLevel */ | 16 /* Optimistic */); + hoistVariableDeclaration(exportEqualsBinding); + const assignment = factory2.createAssignment(exportEqualsBinding, node.expression); + return factory2.createExpressionStatement(assignment); + } + function hoistClassDeclaration(node) { + if (!node.name && defaultExportBinding) { + return node; + } + const isExported = hasSyntacticModifier(node, 32 /* Export */); + const isDefault = hasSyntacticModifier(node, 2048 /* Default */); + let expression = factory2.converters.convertToClassExpression(node); + if (node.name) { + hoistBindingIdentifier( + factory2.getLocalName(node), + isExported && !isDefault, + /*exportAlias*/ + void 0, + node + ); + expression = factory2.createAssignment(factory2.getDeclarationName(node), expression); + if (isNamedEvaluation(expression)) { + expression = transformNamedEvaluation( + context, + expression, + /*ignoreEmptyStringLiteral*/ + false + ); + } + setOriginalNode(expression, node); + setSourceMapRange(expression, node); + setCommentRange(expression, node); + } + if (isDefault && !defaultExportBinding) { + defaultExportBinding = factory2.createUniqueName("_default", 8 /* ReservedInNestedScopes */ | 32 /* FileLevel */ | 16 /* Optimistic */); + hoistBindingIdentifier( + defaultExportBinding, + /*isExport*/ + true, + "default", + node + ); + expression = factory2.createAssignment(defaultExportBinding, expression); + if (isNamedEvaluation(expression)) { + expression = transformNamedEvaluation( + context, + expression, + /*ignoreEmptyStringLiteral*/ + false, + "default" + ); + } + setOriginalNode(expression, node); + } + return factory2.createExpressionStatement(expression); + } + function hoistVariableStatement(node) { + let expressions; + const isExported = hasSyntacticModifier(node, 32 /* Export */); + for (const variable of node.declarationList.declarations) { + hoistBindingElement(variable, isExported, variable); + if (variable.initializer) { + expressions = append(expressions, hoistInitializedVariable(variable)); + } + } + if (expressions) { + const statement = factory2.createExpressionStatement(factory2.inlineExpressions(expressions)); + setOriginalNode(statement, node); + setCommentRange(statement, node); + setSourceMapRange(statement, node); + return statement; + } + return void 0; + } + function hoistInitializedVariable(node) { + Debug.assertIsDefined(node.initializer); + let target; + if (isIdentifier(node.name)) { + target = factory2.cloneNode(node.name); + setEmitFlags(target, getEmitFlags(target) & ~(32768 /* LocalName */ | 16384 /* ExportName */ | 65536 /* InternalName */)); + } else { + target = factory2.converters.convertToAssignmentPattern(node.name); + } + const assignment = factory2.createAssignment(target, node.initializer); + setOriginalNode(assignment, node); + setCommentRange(assignment, node); + setSourceMapRange(assignment, node); + return assignment; + } + function hoistBindingElement(node, isExportedDeclaration, original) { + if (isBindingPattern(node.name)) { + for (const element of node.name.elements) { + if (!isOmittedExpression(element)) { + hoistBindingElement(element, isExportedDeclaration, original); + } + } + } else { + hoistBindingIdentifier( + node.name, + isExportedDeclaration, + /*exportAlias*/ + void 0, + original + ); + } + } + function hoistBindingIdentifier(node, isExport, exportAlias, original) { + const name = isGeneratedIdentifier(node) ? node : factory2.cloneNode(node); + if (isExport) { + if (exportAlias === void 0 && !isLocalName(name)) { + const varDecl = factory2.createVariableDeclaration(name); + if (original) { + setOriginalNode(varDecl, original); + } + exportVars.push(varDecl); + return; + } + const localName = exportAlias !== void 0 ? name : void 0; + const exportName = exportAlias !== void 0 ? exportAlias : name; + const specifier = factory2.createExportSpecifier( + /*isTypeOnly*/ + false, + localName, + exportName + ); + if (original) { + setOriginalNode(specifier, original); + } + exportBindings.set(name, specifier); + } + hoistVariableDeclaration(name); + } + function createEnvBinding() { + return factory2.createUniqueName("env"); + } + function createDownlevelUsingStatements(bodyStatements, envBinding, async) { + const statements = []; + const envObject = factory2.createObjectLiteralExpression([ + factory2.createPropertyAssignment("stack", factory2.createArrayLiteralExpression()), + factory2.createPropertyAssignment("error", factory2.createVoidZero()), + factory2.createPropertyAssignment("hasError", factory2.createFalse()) + ]); + const envVar = factory2.createVariableDeclaration( + envBinding, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + envObject + ); + const envVarList = factory2.createVariableDeclarationList([envVar], 2 /* Const */); + const envVarStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + envVarList + ); + statements.push(envVarStatement); + const tryBlock = factory2.createBlock( + bodyStatements, + /*multiLine*/ + true + ); + const bodyCatchBinding = factory2.createUniqueName("e"); + const catchClause = factory2.createCatchClause( + bodyCatchBinding, + factory2.createBlock( + [ + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createPropertyAccessExpression(envBinding, "error"), + bodyCatchBinding + ) + ), + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createPropertyAccessExpression(envBinding, "hasError"), + factory2.createTrue() + ) + ) + ], + /*multiLine*/ + true + ) + ); + let finallyBlock; + if (async) { + const result = factory2.createUniqueName("result"); + finallyBlock = factory2.createBlock( + [ + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + result, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + emitHelpers().createDisposeResourcesHelper(envBinding) + ) + ], 2 /* Const */) + ), + factory2.createIfStatement(result, factory2.createExpressionStatement(factory2.createAwaitExpression(result))) + ], + /*multiLine*/ + true + ); + } else { + finallyBlock = factory2.createBlock( + [ + factory2.createExpressionStatement( + emitHelpers().createDisposeResourcesHelper(envBinding) + ) + ], + /*multiLine*/ + true + ); + } + const tryStatement = factory2.createTryStatement(tryBlock, catchClause, finallyBlock); + statements.push(tryStatement); + return statements; + } +} +function countPrologueStatements(statements) { + for (let i = 0; i < statements.length; i++) { + if (!isPrologueDirective(statements[i]) && !isCustomPrologue(statements[i])) { + return i; + } + } + return 0; +} +function isUsingVariableDeclarationList(node) { + return isVariableDeclarationList(node) && getUsingKindOfVariableDeclarationList(node) !== 0 /* None */; +} +function getUsingKindOfVariableDeclarationList(node) { + return (node.flags & 7 /* BlockScoped */) === 6 /* AwaitUsing */ ? 2 /* Async */ : (node.flags & 7 /* BlockScoped */) === 4 /* Using */ ? 1 /* Sync */ : 0 /* None */; +} +function getUsingKindOfVariableStatement(node) { + return getUsingKindOfVariableDeclarationList(node.declarationList); +} +function getUsingKind(statement) { + return isVariableStatement(statement) ? getUsingKindOfVariableStatement(statement) : 0 /* None */; +} +function getUsingKindOfStatements(statements) { + let result = 0 /* None */; + for (const statement of statements) { + const usingKind = getUsingKind(statement); + if (usingKind === 2 /* Async */) return 2 /* Async */; + if (usingKind > result) result = usingKind; + } + return result; +} +function getUsingKindOfCaseOrDefaultClauses(clauses) { + let result = 0 /* None */; + for (const clause of clauses) { + const usingKind = getUsingKindOfStatements(clause.statements); + if (usingKind === 2 /* Async */) return 2 /* Async */; + if (usingKind > result) result = usingKind; + } + return result; +} + +// src/compiler/transformers/jsx.ts +function transformJsx(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers + } = context; + const compilerOptions = context.getCompilerOptions(); + let currentSourceFile; + let currentFileState; + return chainBundle(context, transformSourceFile); + function getCurrentFileNameExpression() { + if (currentFileState.filenameDeclaration) { + return currentFileState.filenameDeclaration.name; + } + const declaration = factory2.createVariableDeclaration( + factory2.createUniqueName("_jsxFileName", 16 /* Optimistic */ | 32 /* FileLevel */), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createStringLiteral(currentSourceFile.fileName) + ); + currentFileState.filenameDeclaration = declaration; + return currentFileState.filenameDeclaration.name; + } + function getJsxFactoryCalleePrimitive(isStaticChildren) { + return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx"; + } + function getJsxFactoryCallee(isStaticChildren) { + const type = getJsxFactoryCalleePrimitive(isStaticChildren); + return getImplicitImportForName(type); + } + function getImplicitJsxFragmentReference() { + return getImplicitImportForName("Fragment"); + } + function getImplicitImportForName(name) { + var _a, _b; + const importSource = name === "createElement" ? currentFileState.importSpecifier : getJSXRuntimeImport(currentFileState.importSpecifier, compilerOptions); + const existing = (_b = (_a = currentFileState.utilizedImplicitRuntimeImports) == null ? void 0 : _a.get(importSource)) == null ? void 0 : _b.get(name); + if (existing) { + return existing.name; + } + if (!currentFileState.utilizedImplicitRuntimeImports) { + currentFileState.utilizedImplicitRuntimeImports = /* @__PURE__ */ new Map(); + } + let specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource); + if (!specifierSourceImports) { + specifierSourceImports = /* @__PURE__ */ new Map(); + currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports); + } + const generatedName = factory2.createUniqueName(`_${name}`, 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */); + const specifier = factory2.createImportSpecifier( + /*isTypeOnly*/ + false, + factory2.createIdentifier(name), + generatedName + ); + setIdentifierGeneratedImportReference(generatedName, specifier); + specifierSourceImports.set(name, specifier); + return generatedName; + } + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + currentFileState = {}; + currentFileState.importSpecifier = getJSXImplicitImportBase(compilerOptions, node); + let visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + let statements = visited.statements; + if (currentFileState.filenameDeclaration) { + statements = insertStatementAfterCustomPrologue(statements.slice(), factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([currentFileState.filenameDeclaration], 2 /* Const */) + )); + } + if (currentFileState.utilizedImplicitRuntimeImports) { + for (const [importSource, importSpecifiersMap] of arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries())) { + if (isExternalModule(node)) { + const importStatement = factory2.createImportDeclaration( + /*modifiers*/ + void 0, + factory2.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + factory2.createNamedImports(arrayFrom(importSpecifiersMap.values())) + ), + factory2.createStringLiteral(importSource), + /*attributes*/ + void 0 + ); + setParentRecursive( + importStatement, + /*incremental*/ + false + ); + statements = insertStatementAfterCustomPrologue(statements.slice(), importStatement); + } else if (isExternalOrCommonJsModule(node)) { + const requireStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + factory2.createObjectBindingPattern(arrayFrom(importSpecifiersMap.values(), (s) => factory2.createBindingElement( + /*dotDotDotToken*/ + void 0, + s.propertyName, + s.name + ))), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createCallExpression( + factory2.createIdentifier("require"), + /*typeArguments*/ + void 0, + [factory2.createStringLiteral(importSource)] + ) + ) + ], 2 /* Const */) + ); + setParentRecursive( + requireStatement, + /*incremental*/ + false + ); + statements = insertStatementAfterCustomPrologue(statements.slice(), requireStatement); + } else { + } + } + } + if (statements !== visited.statements) { + visited = factory2.updateSourceFile(visited, statements); + } + currentFileState = void 0; + return visited; + } + function visitor(node) { + if (node.transformFlags & 2 /* ContainsJsx */) { + return visitorWorker(node); + } else { + return node; + } + } + function visitorWorker(node) { + switch (node.kind) { + case 284 /* JsxElement */: + return visitJsxElement( + node, + /*isChild*/ + false + ); + case 285 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement( + node, + /*isChild*/ + false + ); + case 288 /* JsxFragment */: + return visitJsxFragment( + node, + /*isChild*/ + false + ); + case 294 /* JsxExpression */: + return visitJsxExpression(node); + default: + return visitEachChild(node, visitor, context); + } + } + function transformJsxChildToExpression(node) { + switch (node.kind) { + case 12 /* JsxText */: + return visitJsxText(node); + case 294 /* JsxExpression */: + return visitJsxExpression(node); + case 284 /* JsxElement */: + return visitJsxElement( + node, + /*isChild*/ + true + ); + case 285 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement( + node, + /*isChild*/ + true + ); + case 288 /* JsxFragment */: + return visitJsxFragment( + node, + /*isChild*/ + true + ); + default: + return Debug.failBadSyntaxKind(node); + } + } + function hasProto(obj) { + return obj.properties.some( + (p) => isPropertyAssignment(p) && (isIdentifier(p.name) && idText(p.name) === "__proto__" || isStringLiteral(p.name) && p.name.text === "__proto__") + ); + } + function hasKeyAfterPropsSpread(node) { + let spread = false; + for (const elem of node.attributes.properties) { + if (isJsxSpreadAttribute(elem) && (!isObjectLiteralExpression(elem.expression) || elem.expression.properties.some(isSpreadAssignment))) { + spread = true; + } else if (spread && isJsxAttribute(elem) && isIdentifier(elem.name) && elem.name.escapedText === "key") { + return true; + } + } + return false; + } + function shouldUseCreateElement(node) { + return currentFileState.importSpecifier === void 0 || hasKeyAfterPropsSpread(node); + } + function visitJsxElement(node, isChild) { + const tagTransform = shouldUseCreateElement(node.openingElement) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX; + return tagTransform( + node.openingElement, + node.children, + isChild, + /*location*/ + node + ); + } + function visitJsxSelfClosingElement(node, isChild) { + const tagTransform = shouldUseCreateElement(node) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX; + return tagTransform( + node, + /*children*/ + void 0, + isChild, + /*location*/ + node + ); + } + function visitJsxFragment(node, isChild) { + const tagTransform = currentFileState.importSpecifier === void 0 ? visitJsxOpeningFragmentCreateElement : visitJsxOpeningFragmentJSX; + return tagTransform( + node.openingFragment, + node.children, + isChild, + /*location*/ + node + ); + } + function convertJsxChildrenToChildrenPropObject(children) { + const prop = convertJsxChildrenToChildrenPropAssignment(children); + return prop && factory2.createObjectLiteralExpression([prop]); + } + function convertJsxChildrenToChildrenPropAssignment(children) { + const nonWhitespaceChildren = getSemanticJsxChildren(children); + if (length(nonWhitespaceChildren) === 1 && !nonWhitespaceChildren[0].dotDotDotToken) { + const result2 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result2 && factory2.createPropertyAssignment("children", result2); + } + const result = mapDefined(children, transformJsxChildToExpression); + return length(result) ? factory2.createPropertyAssignment("children", factory2.createArrayLiteralExpression(result)) : void 0; + } + function visitJsxOpeningLikeElementJSX(node, children, isChild, location) { + const tagName = getTagName(node); + const childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : void 0; + const keyAttr = find(node.attributes.properties, (p) => !!p.name && isIdentifier(p.name) && p.name.escapedText === "key"); + const attrs = keyAttr ? filter(node.attributes.properties, (p) => p !== keyAttr) : node.attributes.properties; + const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : factory2.createObjectLiteralExpression(childrenProp ? [childrenProp] : emptyArray); + return visitJsxOpeningLikeElementOrFragmentJSX( + tagName, + objectProperties, + keyAttr, + children || emptyArray, + isChild, + location + ); + } + function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) { + var _a; + const nonWhitespaceChildren = getSemanticJsxChildren(children); + const isStaticChildren = length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) == null ? void 0 : _a.dotDotDotToken); + const args = [tagName, objectProperties]; + if (keyAttr) { + args.push(transformJsxAttributeInitializer(keyAttr.initializer)); + } + if (compilerOptions.jsx === 5 /* ReactJSXDev */) { + const originalFile = getOriginalNode(currentSourceFile); + if (originalFile && isSourceFile(originalFile)) { + if (keyAttr === void 0) { + args.push(factory2.createVoidZero()); + } + args.push(isStaticChildren ? factory2.createTrue() : factory2.createFalse()); + const lineCol = getLineAndCharacterOfPosition(originalFile, location.pos); + args.push(factory2.createObjectLiteralExpression([ + factory2.createPropertyAssignment("fileName", getCurrentFileNameExpression()), + factory2.createPropertyAssignment("lineNumber", factory2.createNumericLiteral(lineCol.line + 1)), + factory2.createPropertyAssignment("columnNumber", factory2.createNumericLiteral(lineCol.character + 1)) + ])); + args.push(factory2.createThis()); + } + } + const element = setTextRange( + factory2.createCallExpression( + getJsxFactoryCallee(isStaticChildren), + /*typeArguments*/ + void 0, + args + ), + location + ); + if (isChild) { + startOnNewLine(element); + } + return element; + } + function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) { + const tagName = getTagName(node); + const attrs = node.attributes.properties; + const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs) : factory2.createNull(); + const callee = currentFileState.importSpecifier === void 0 ? createJsxFactoryExpression( + factory2, + context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), + compilerOptions.reactNamespace, + // TODO: GH#18217 + node + ) : getImplicitImportForName("createElement"); + const element = createExpressionForJsxElement( + factory2, + callee, + tagName, + objectProperties, + mapDefined(children, transformJsxChildToExpression), + location + ); + if (isChild) { + startOnNewLine(element); + } + return element; + } + function visitJsxOpeningFragmentJSX(_node, children, isChild, location) { + let childrenProps; + if (children && children.length) { + const result = convertJsxChildrenToChildrenPropObject(children); + if (result) { + childrenProps = result; + } + } + return visitJsxOpeningLikeElementOrFragmentJSX( + getImplicitJsxFragmentReference(), + childrenProps || factory2.createObjectLiteralExpression([]), + /*keyAttr*/ + void 0, + children, + isChild, + location + ); + } + function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) { + const element = createExpressionForJsxFragment( + factory2, + context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), + context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), + compilerOptions.reactNamespace, + // TODO: GH#18217 + mapDefined(children, transformJsxChildToExpression), + node, + location + ); + if (isChild) { + startOnNewLine(element); + } + return element; + } + function transformJsxSpreadAttributeToProps(node) { + if (isObjectLiteralExpression(node.expression) && !hasProto(node.expression)) { + return sameMap(node.expression.properties, (p) => Debug.checkDefined(visitNode(p, visitor, isObjectLiteralElementLike))); + } + return factory2.createSpreadAssignment(Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + } + function transformJsxAttributesToObjectProps(attrs, children) { + const target = getEmitScriptTarget(compilerOptions); + return target && target >= 5 /* ES2018 */ ? factory2.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : transformJsxAttributesToExpression(attrs, children); + } + function transformJsxAttributesToProps(attrs, children) { + const props = flatten(spanMap(attrs, isJsxSpreadAttribute, (attrs2, isSpread) => flatten(map(attrs2, (attr) => isSpread ? transformJsxSpreadAttributeToProps(attr) : transformJsxAttributeToObjectLiteralElement(attr))))); + if (children) { + props.push(children); + } + return props; + } + function transformJsxAttributesToExpression(attrs, children) { + const expressions = []; + let properties = []; + for (const attr of attrs) { + if (isJsxSpreadAttribute(attr)) { + if (isObjectLiteralExpression(attr.expression) && !hasProto(attr.expression)) { + for (const prop of attr.expression.properties) { + if (isSpreadAssignment(prop)) { + finishObjectLiteralIfNeeded(); + expressions.push(Debug.checkDefined(visitNode(prop.expression, visitor, isExpression))); + continue; + } + properties.push(Debug.checkDefined(visitNode(prop, visitor))); + } + continue; + } + finishObjectLiteralIfNeeded(); + expressions.push(Debug.checkDefined(visitNode(attr.expression, visitor, isExpression))); + continue; + } + properties.push(transformJsxAttributeToObjectLiteralElement(attr)); + } + if (children) { + properties.push(children); + } + finishObjectLiteralIfNeeded(); + if (expressions.length && !isObjectLiteralExpression(expressions[0])) { + expressions.unshift(factory2.createObjectLiteralExpression()); + } + return singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions); + function finishObjectLiteralIfNeeded() { + if (properties.length) { + expressions.push(factory2.createObjectLiteralExpression(properties)); + properties = []; + } + } + } + function transformJsxAttributeToObjectLiteralElement(node) { + const name = getAttributeName(node); + const expression = transformJsxAttributeInitializer(node.initializer); + return factory2.createPropertyAssignment(name, expression); + } + function transformJsxAttributeInitializer(node) { + if (node === void 0) { + return factory2.createTrue(); + } + if (node.kind === 11 /* StringLiteral */) { + const singleQuote = node.singleQuote !== void 0 ? node.singleQuote : !isStringDoubleQuoted(node, currentSourceFile); + const literal = factory2.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); + return setTextRange(literal, node); + } + if (node.kind === 294 /* JsxExpression */) { + if (node.expression === void 0) { + return factory2.createTrue(); + } + return Debug.checkDefined(visitNode(node.expression, visitor, isExpression)); + } + if (isJsxElement(node)) { + return visitJsxElement( + node, + /*isChild*/ + false + ); + } + if (isJsxSelfClosingElement(node)) { + return visitJsxSelfClosingElement( + node, + /*isChild*/ + false + ); + } + if (isJsxFragment(node)) { + return visitJsxFragment( + node, + /*isChild*/ + false + ); + } + return Debug.failBadSyntaxKind(node); + } + function visitJsxText(node) { + const fixed = fixupWhitespaceAndDecodeEntities(node.text); + return fixed === void 0 ? void 0 : factory2.createStringLiteral(fixed); + } + function fixupWhitespaceAndDecodeEntities(text) { + let acc; + let firstNonWhitespace = 0; + let lastNonWhitespace = -1; + for (let i = 0; i < text.length; i++) { + const c = text.charCodeAt(i); + if (isLineBreak(c)) { + if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) { + acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1)); + } + firstNonWhitespace = -1; + } else if (!isWhiteSpaceSingleLine(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + return firstNonWhitespace !== -1 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) : acc; + } + function addLineOfJsxText(acc, trimmedLine) { + const decoded = decodeEntities(trimmedLine); + return acc === void 0 ? decoded : acc + " " + decoded; + } + function decodeEntities(text) { + return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, (match, _all, _number, _digits, decimal, hex, word) => { + if (decimal) { + return utf16EncodeAsString(parseInt(decimal, 10)); + } else if (hex) { + return utf16EncodeAsString(parseInt(hex, 16)); + } else { + const ch = entities.get(word); + return ch ? utf16EncodeAsString(ch) : match; + } + }); + } + function tryDecodeEntities(text) { + const decoded = decodeEntities(text); + return decoded === text ? void 0 : decoded; + } + function getTagName(node) { + if (node.kind === 284 /* JsxElement */) { + return getTagName(node.openingElement); + } else { + const tagName = node.tagName; + if (isIdentifier(tagName) && isIntrinsicJsxName(tagName.escapedText)) { + return factory2.createStringLiteral(idText(tagName)); + } else if (isJsxNamespacedName(tagName)) { + return factory2.createStringLiteral(idText(tagName.namespace) + ":" + idText(tagName.name)); + } else { + return createExpressionFromEntityName(factory2, tagName); + } + } + } + function getAttributeName(node) { + const name = node.name; + if (isIdentifier(name)) { + const text = idText(name); + return /^[A-Z_]\w*$/i.test(text) ? name : factory2.createStringLiteral(text); + } + return factory2.createStringLiteral(idText(name.namespace) + ":" + idText(name.name)); + } + function visitJsxExpression(node) { + const expression = visitNode(node.expression, visitor, isExpression); + return node.dotDotDotToken ? factory2.createSpreadElement(expression) : expression; + } +} +var entities = new Map(Object.entries({ + quot: 34, + amp: 38, + apos: 39, + lt: 60, + gt: 62, + nbsp: 160, + iexcl: 161, + cent: 162, + pound: 163, + curren: 164, + yen: 165, + brvbar: 166, + sect: 167, + uml: 168, + copy: 169, + ordf: 170, + laquo: 171, + not: 172, + shy: 173, + reg: 174, + macr: 175, + deg: 176, + plusmn: 177, + sup2: 178, + sup3: 179, + acute: 180, + micro: 181, + para: 182, + middot: 183, + cedil: 184, + sup1: 185, + ordm: 186, + raquo: 187, + frac14: 188, + frac12: 189, + frac34: 190, + iquest: 191, + Agrave: 192, + Aacute: 193, + Acirc: 194, + Atilde: 195, + Auml: 196, + Aring: 197, + AElig: 198, + Ccedil: 199, + Egrave: 200, + Eacute: 201, + Ecirc: 202, + Euml: 203, + Igrave: 204, + Iacute: 205, + Icirc: 206, + Iuml: 207, + ETH: 208, + Ntilde: 209, + Ograve: 210, + Oacute: 211, + Ocirc: 212, + Otilde: 213, + Ouml: 214, + times: 215, + Oslash: 216, + Ugrave: 217, + Uacute: 218, + Ucirc: 219, + Uuml: 220, + Yacute: 221, + THORN: 222, + szlig: 223, + agrave: 224, + aacute: 225, + acirc: 226, + atilde: 227, + auml: 228, + aring: 229, + aelig: 230, + ccedil: 231, + egrave: 232, + eacute: 233, + ecirc: 234, + euml: 235, + igrave: 236, + iacute: 237, + icirc: 238, + iuml: 239, + eth: 240, + ntilde: 241, + ograve: 242, + oacute: 243, + ocirc: 244, + otilde: 245, + ouml: 246, + divide: 247, + oslash: 248, + ugrave: 249, + uacute: 250, + ucirc: 251, + uuml: 252, + yacute: 253, + thorn: 254, + yuml: 255, + OElig: 338, + oelig: 339, + Scaron: 352, + scaron: 353, + Yuml: 376, + fnof: 402, + circ: 710, + tilde: 732, + Alpha: 913, + Beta: 914, + Gamma: 915, + Delta: 916, + Epsilon: 917, + Zeta: 918, + Eta: 919, + Theta: 920, + Iota: 921, + Kappa: 922, + Lambda: 923, + Mu: 924, + Nu: 925, + Xi: 926, + Omicron: 927, + Pi: 928, + Rho: 929, + Sigma: 931, + Tau: 932, + Upsilon: 933, + Phi: 934, + Chi: 935, + Psi: 936, + Omega: 937, + alpha: 945, + beta: 946, + gamma: 947, + delta: 948, + epsilon: 949, + zeta: 950, + eta: 951, + theta: 952, + iota: 953, + kappa: 954, + lambda: 955, + mu: 956, + nu: 957, + xi: 958, + omicron: 959, + pi: 960, + rho: 961, + sigmaf: 962, + sigma: 963, + tau: 964, + upsilon: 965, + phi: 966, + chi: 967, + psi: 968, + omega: 969, + thetasym: 977, + upsih: 978, + piv: 982, + ensp: 8194, + emsp: 8195, + thinsp: 8201, + zwnj: 8204, + zwj: 8205, + lrm: 8206, + rlm: 8207, + ndash: 8211, + mdash: 8212, + lsquo: 8216, + rsquo: 8217, + sbquo: 8218, + ldquo: 8220, + rdquo: 8221, + bdquo: 8222, + dagger: 8224, + Dagger: 8225, + bull: 8226, + hellip: 8230, + permil: 8240, + prime: 8242, + Prime: 8243, + lsaquo: 8249, + rsaquo: 8250, + oline: 8254, + frasl: 8260, + euro: 8364, + image: 8465, + weierp: 8472, + real: 8476, + trade: 8482, + alefsym: 8501, + larr: 8592, + uarr: 8593, + rarr: 8594, + darr: 8595, + harr: 8596, + crarr: 8629, + lArr: 8656, + uArr: 8657, + rArr: 8658, + dArr: 8659, + hArr: 8660, + forall: 8704, + part: 8706, + exist: 8707, + empty: 8709, + nabla: 8711, + isin: 8712, + notin: 8713, + ni: 8715, + prod: 8719, + sum: 8721, + minus: 8722, + lowast: 8727, + radic: 8730, + prop: 8733, + infin: 8734, + ang: 8736, + and: 8743, + or: 8744, + cap: 8745, + cup: 8746, + int: 8747, + there4: 8756, + sim: 8764, + cong: 8773, + asymp: 8776, + ne: 8800, + equiv: 8801, + le: 8804, + ge: 8805, + sub: 8834, + sup: 8835, + nsub: 8836, + sube: 8838, + supe: 8839, + oplus: 8853, + otimes: 8855, + perp: 8869, + sdot: 8901, + lceil: 8968, + rceil: 8969, + lfloor: 8970, + rfloor: 8971, + lang: 9001, + rang: 9002, + loz: 9674, + spades: 9824, + clubs: 9827, + hearts: 9829, + diams: 9830 +})); + +// src/compiler/transformers/es2016.ts +function transformES2016(context) { + const { + factory: factory2, + hoistVariableDeclaration + } = context; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 512 /* ContainsES2016 */) === 0) { + return node; + } + switch (node.kind) { + case 226 /* BinaryExpression */: + return visitBinaryExpression(node); + default: + return visitEachChild(node, visitor, context); + } + } + function visitBinaryExpression(node) { + switch (node.operatorToken.kind) { + case 68 /* AsteriskAsteriskEqualsToken */: + return visitExponentiationAssignmentExpression(node); + case 43 /* AsteriskAsteriskToken */: + return visitExponentiationExpression(node); + default: + return visitEachChild(node, visitor, context); + } + } + function visitExponentiationAssignmentExpression(node) { + let target; + let value; + const left = visitNode(node.left, visitor, isExpression); + const right = visitNode(node.right, visitor, isExpression); + if (isElementAccessExpression(left)) { + const expressionTemp = factory2.createTempVariable(hoistVariableDeclaration); + const argumentExpressionTemp = factory2.createTempVariable(hoistVariableDeclaration); + target = setTextRange( + factory2.createElementAccessExpression( + setTextRange(factory2.createAssignment(expressionTemp, left.expression), left.expression), + setTextRange(factory2.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression) + ), + left + ); + value = setTextRange( + factory2.createElementAccessExpression( + expressionTemp, + argumentExpressionTemp + ), + left + ); + } else if (isPropertyAccessExpression(left)) { + const expressionTemp = factory2.createTempVariable(hoistVariableDeclaration); + target = setTextRange( + factory2.createPropertyAccessExpression( + setTextRange(factory2.createAssignment(expressionTemp, left.expression), left.expression), + left.name + ), + left + ); + value = setTextRange( + factory2.createPropertyAccessExpression( + expressionTemp, + left.name + ), + left + ); + } else { + target = left; + value = left; + } + return setTextRange( + factory2.createAssignment( + target, + setTextRange(factory2.createGlobalMethodCall("Math", "pow", [value, right]), node) + ), + node + ); + } + function visitExponentiationExpression(node) { + const left = visitNode(node.left, visitor, isExpression); + const right = visitNode(node.right, visitor, isExpression); + return setTextRange(factory2.createGlobalMethodCall("Math", "pow", [left, right]), node); + } +} + +// src/compiler/transformers/es2015.ts +function createSpreadSegment(kind, expression) { + return { kind, expression }; +} +function transformES2015(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + startLexicalEnvironment, + resumeLexicalEnvironment, + endLexicalEnvironment, + hoistVariableDeclaration + } = context; + const compilerOptions = context.getCompilerOptions(); + const resolver = context.getEmitResolver(); + const previousOnSubstituteNode = context.onSubstituteNode; + const previousOnEmitNode = context.onEmitNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + let currentSourceFile; + let currentText; + let hierarchyFacts; + let taggedTemplateStringDeclarations; + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = append( + taggedTemplateStringDeclarations, + factory2.createVariableDeclaration(temp) + ); + } + let convertedLoopState; + let enabledSubstitutions = 0 /* None */; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + currentText = node.text; + const visited = visitSourceFile(node); + addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = void 0; + currentText = void 0; + taggedTemplateStringDeclarations = void 0; + hierarchyFacts = 0 /* None */; + return visited; + } + function enterSubtree(excludeFacts, includeFacts) { + const ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 32767 /* AncestorFactsMask */; + return ancestorFacts; + } + function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -32768 /* SubtreeFactsMask */ | ancestorFacts; + } + function isReturnVoidStatementInConstructorWithCapturedSuper(node) { + return (hierarchyFacts & 8192 /* ConstructorWithSuperCall */) !== 0 && node.kind === 253 /* ReturnStatement */ && !node.expression; + } + function isOrMayContainReturnCompletion(node) { + return node.transformFlags & 4194304 /* ContainsHoistedDeclarationOrCompletion */ && (isReturnStatement(node) || isIfStatement(node) || isWithStatement(node) || isSwitchStatement(node) || isCaseBlock(node) || isCaseClause(node) || isDefaultClause(node) || isTryStatement(node) || isCatchClause(node) || isLabeledStatement(node) || isIterationStatement( + node, + /*lookInLabeledStatements*/ + false + ) || isBlock(node)); + } + function shouldVisitNode(node) { + return (node.transformFlags & 1024 /* ContainsES2015 */) !== 0 || convertedLoopState !== void 0 || hierarchyFacts & 8192 /* ConstructorWithSuperCall */ && isOrMayContainReturnCompletion(node) || isIterationStatement( + node, + /*lookInLabeledStatements*/ + false + ) && shouldConvertIterationStatement(node) || (getInternalEmitFlags(node) & 1 /* TypeScriptClassWrapper */) !== 0; + } + function visitor(node) { + return shouldVisitNode(node) ? visitorWorker( + node, + /*expressionResultIsUnused*/ + false + ) : node; + } + function visitorWithUnusedExpressionResult(node) { + return shouldVisitNode(node) ? visitorWorker( + node, + /*expressionResultIsUnused*/ + true + ) : node; + } + function classWrapperStatementVisitor(node) { + if (shouldVisitNode(node)) { + const original = getOriginalNode(node); + if (isPropertyDeclaration(original) && hasStaticModifier(original)) { + const ancestorFacts = enterSubtree( + 32670 /* StaticInitializerExcludes */, + 16449 /* StaticInitializerIncludes */ + ); + const result = visitorWorker( + node, + /*expressionResultIsUnused*/ + false + ); + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); + return result; + } + return visitorWorker( + node, + /*expressionResultIsUnused*/ + false + ); + } + return node; + } + function callExpressionVisitor(node) { + if (node.kind === 108 /* SuperKeyword */) { + return visitSuperKeyword( + node, + /*isExpressionOfCall*/ + true + ); + } + return visitor(node); + } + function visitorWorker(node, expressionResultIsUnused2) { + switch (node.kind) { + case 126 /* StaticKeyword */: + return void 0; + // elide static keyword + case 263 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 231 /* ClassExpression */: + return visitClassExpression(node); + case 169 /* Parameter */: + return visitParameter(node); + case 262 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 219 /* ArrowFunction */: + return visitArrowFunction(node); + case 218 /* FunctionExpression */: + return visitFunctionExpression(node); + case 260 /* VariableDeclaration */: + return visitVariableDeclaration(node); + case 80 /* Identifier */: + return visitIdentifier(node); + case 261 /* VariableDeclarationList */: + return visitVariableDeclarationList(node); + case 255 /* SwitchStatement */: + return visitSwitchStatement(node); + case 269 /* CaseBlock */: + return visitCaseBlock(node); + case 241 /* Block */: + return visitBlock( + node, + /*isFunctionBody*/ + false + ); + case 252 /* BreakStatement */: + case 251 /* ContinueStatement */: + return visitBreakOrContinueStatement(node); + case 256 /* LabeledStatement */: + return visitLabeledStatement(node); + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + return visitDoOrWhileStatement( + node, + /*outermostLabeledStatement*/ + void 0 + ); + case 248 /* ForStatement */: + return visitForStatement( + node, + /*outermostLabeledStatement*/ + void 0 + ); + case 249 /* ForInStatement */: + return visitForInStatement( + node, + /*outermostLabeledStatement*/ + void 0 + ); + case 250 /* ForOfStatement */: + return visitForOfStatement( + node, + /*outermostLabeledStatement*/ + void 0 + ); + case 244 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 210 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 299 /* CatchClause */: + return visitCatchClause(node); + case 304 /* ShorthandPropertyAssignment */: + return visitShorthandPropertyAssignment(node); + case 167 /* ComputedPropertyName */: + return visitComputedPropertyName(node); + case 209 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 213 /* CallExpression */: + return visitCallExpression(node); + case 214 /* NewExpression */: + return visitNewExpression(node); + case 217 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, expressionResultIsUnused2); + case 226 /* BinaryExpression */: + return visitBinaryExpression(node, expressionResultIsUnused2); + case 356 /* CommaListExpression */: + return visitCommaListExpression(node, expressionResultIsUnused2); + case 15 /* NoSubstitutionTemplateLiteral */: + case 16 /* TemplateHead */: + case 17 /* TemplateMiddle */: + case 18 /* TemplateTail */: + return visitTemplateLiteral(node); + case 11 /* StringLiteral */: + return visitStringLiteral(node); + case 9 /* NumericLiteral */: + return visitNumericLiteral(node); + case 215 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 228 /* TemplateExpression */: + return visitTemplateExpression(node); + case 229 /* YieldExpression */: + return visitYieldExpression(node); + case 230 /* SpreadElement */: + return visitSpreadElement(node); + case 108 /* SuperKeyword */: + return visitSuperKeyword( + node, + /*isExpressionOfCall*/ + false + ); + case 110 /* ThisKeyword */: + return visitThisKeyword(node); + case 236 /* MetaProperty */: + return visitMetaProperty(node); + case 174 /* MethodDeclaration */: + return visitMethodDeclaration(node); + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 243 /* VariableStatement */: + return visitVariableStatement(node); + case 253 /* ReturnStatement */: + return visitReturnStatement(node); + case 222 /* VoidExpression */: + return visitVoidExpression(node); + default: + return visitEachChild(node, visitor, context); + } + } + function visitSourceFile(node) { + const ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + const prologue = []; + const statements = []; + startLexicalEnvironment(); + const statementOffset = factory2.copyPrologue( + node.statements, + prologue, + /*ensureUseStrict*/ + false, + visitor + ); + addRange(statements, visitNodes2(node.statements, visitor, isStatement, statementOffset)); + if (taggedTemplateStringDeclarations) { + statements.push( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList(taggedTemplateStringDeclarations) + ) + ); + } + factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureThisForNodeIfNeeded(prologue, node); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return factory2.updateSourceFile( + node, + setTextRange(factory2.createNodeArray(concatenate(prologue, statements)), node.statements) + ); + } + function visitSwitchStatement(node) { + if (convertedLoopState !== void 0) { + const savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + const result = visitEachChild(node, visitor, context); + convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps; + return result; + } + return visitEachChild(node, visitor, context); + } + function visitCaseBlock(node) { + const ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + const updated = visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function returnCapturedThis(node) { + return setOriginalNode(factory2.createReturnStatement(createCapturedThis()), node); + } + function createCapturedThis() { + return factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */); + } + function visitReturnStatement(node) { + if (convertedLoopState) { + convertedLoopState.nonLocalJumps |= 8 /* Return */; + if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + node = returnCapturedThis(node); + } + return factory2.createReturnStatement( + factory2.createObjectLiteralExpression( + [ + factory2.createPropertyAssignment( + factory2.createIdentifier("value"), + node.expression ? Debug.checkDefined(visitNode(node.expression, visitor, isExpression)) : factory2.createVoidZero() + ) + ] + ) + ); + } else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { + return returnCapturedThis(node); + } + return visitEachChild(node, visitor, context); + } + function visitThisKeyword(node) { + hierarchyFacts |= 65536 /* LexicalThis */; + if (hierarchyFacts & 2 /* ArrowFunction */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) { + hierarchyFacts |= 131072 /* CapturedLexicalThis */; + } + if (convertedLoopState) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + convertedLoopState.containsLexicalThis = true; + return node; + } + return convertedLoopState.thisName || (convertedLoopState.thisName = factory2.createUniqueName("this")); + } + return node; + } + function visitVoidExpression(node) { + return visitEachChild(node, visitorWithUnusedExpressionResult, context); + } + function visitIdentifier(node) { + if (convertedLoopState) { + if (resolver.isArgumentsLocalBinding(node)) { + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory2.createUniqueName("arguments")); + } + } + if (node.flags & 256 /* IdentifierHasExtendedUnicodeEscape */) { + return setOriginalNode( + setTextRange( + factory2.createIdentifier(unescapeLeadingUnderscores(node.escapedText)), + node + ), + node + ); + } + return node; + } + function visitBreakOrContinueStatement(node) { + if (convertedLoopState) { + const jump = node.kind === 252 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + const canUseBreakOrContinue = node.label && convertedLoopState.labels && convertedLoopState.labels.get(idText(node.label)) || !node.label && convertedLoopState.allowedNonLabeledJumps & jump; + if (!canUseBreakOrContinue) { + let labelMarker; + const label = node.label; + if (!label) { + if (node.kind === 252 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + labelMarker = "break"; + } else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + labelMarker = "continue"; + } + } else { + if (node.kind === 252 /* BreakStatement */) { + labelMarker = `break-${label.escapedText}`; + setLabeledJump( + convertedLoopState, + /*isBreak*/ + true, + idText(label), + labelMarker + ); + } else { + labelMarker = `continue-${label.escapedText}`; + setLabeledJump( + convertedLoopState, + /*isBreak*/ + false, + idText(label), + labelMarker + ); + } + } + let returnExpression = factory2.createStringLiteral(labelMarker); + if (convertedLoopState.loopOutParameters.length) { + const outParams = convertedLoopState.loopOutParameters; + let expr; + for (let i = 0; i < outParams.length; i++) { + const copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */); + if (i === 0) { + expr = copyExpr; + } else { + expr = factory2.createBinaryExpression(expr, 28 /* CommaToken */, copyExpr); + } + } + returnExpression = factory2.createBinaryExpression(expr, 28 /* CommaToken */, returnExpression); + } + return factory2.createReturnStatement(returnExpression); + } + } + return visitEachChild(node, visitor, context); + } + function visitClassDeclaration(node) { + const variable = factory2.createVariableDeclaration( + factory2.getLocalName( + node, + /*allowComments*/ + true + ), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + transformClassLikeDeclarationToExpression(node) + ); + setOriginalNode(variable, node); + const statements = []; + const statement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([variable]) + ); + setOriginalNode(statement, node); + setTextRange(statement, node); + startOnNewLine(statement); + statements.push(statement); + if (hasSyntacticModifier(node, 32 /* Export */)) { + const exportStatement = hasSyntacticModifier(node, 2048 /* Default */) ? factory2.createExportDefault(factory2.getLocalName(node)) : factory2.createExternalModuleExport(factory2.getLocalName(node)); + setOriginalNode(exportStatement, statement); + statements.push(exportStatement); + } + return singleOrMany(statements); + } + function visitClassExpression(node) { + return transformClassLikeDeclarationToExpression(node); + } + function transformClassLikeDeclarationToExpression(node) { + if (node.name) { + enableSubstitutionsForBlockScopedBindings(); + } + const extendsClauseElement = getClassExtendsHeritageElement(node); + const classFunction = factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + extendsClauseElement ? [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + createSyntheticSuper() + )] : [], + /*type*/ + void 0, + transformClassBody(node, extendsClauseElement) + ); + setEmitFlags(classFunction, getEmitFlags(node) & 131072 /* Indented */ | 1048576 /* ReuseTempVariableScope */); + const inner = factory2.createPartiallyEmittedExpression(classFunction); + setTextRangeEnd(inner, node.end); + setEmitFlags(inner, 3072 /* NoComments */); + const outer = factory2.createPartiallyEmittedExpression(inner); + setTextRangeEnd(outer, skipTrivia(currentText, node.pos)); + setEmitFlags(outer, 3072 /* NoComments */); + const result = factory2.createParenthesizedExpression( + factory2.createCallExpression( + outer, + /*typeArguments*/ + void 0, + extendsClauseElement ? [Debug.checkDefined(visitNode(extendsClauseElement.expression, visitor, isExpression))] : [] + ) + ); + addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); + return result; + } + function transformClassBody(node, extendsClauseElement) { + const statements = []; + const name = factory2.getInternalName(node); + const constructorLikeName = isIdentifierANonContextualKeyword(name) ? factory2.getGeneratedNameForNode(name) : name; + startLexicalEnvironment(); + addExtendsHelperIfNeeded(statements, node, extendsClauseElement); + addConstructor(statements, node, constructorLikeName, extendsClauseElement); + addClassMembers(statements, node); + const closingBraceLocation = createTokenRange(skipTrivia(currentText, node.members.end), 20 /* CloseBraceToken */); + const outer = factory2.createPartiallyEmittedExpression(constructorLikeName); + setTextRangeEnd(outer, closingBraceLocation.end); + setEmitFlags(outer, 3072 /* NoComments */); + const statement = factory2.createReturnStatement(outer); + setTextRangePos(statement, closingBraceLocation.pos); + setEmitFlags(statement, 3072 /* NoComments */ | 768 /* NoTokenSourceMaps */); + statements.push(statement); + insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); + const block = factory2.createBlock( + setTextRange( + factory2.createNodeArray(statements), + /*location*/ + node.members + ), + /*multiLine*/ + true + ); + setEmitFlags(block, 3072 /* NoComments */); + return block; + } + function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { + if (extendsClauseElement) { + statements.push( + setTextRange( + factory2.createExpressionStatement( + emitHelpers().createExtendsHelper(factory2.getInternalName(node)) + ), + /*location*/ + extendsClauseElement + ) + ); + } + } + function addConstructor(statements, node, name, extendsClauseElement) { + const savedConvertedLoopState = convertedLoopState; + convertedLoopState = void 0; + const ancestorFacts = enterSubtree(32662 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + const constructor = getFirstConstructorWithBody(node); + const hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== void 0); + const constructorFunction = factory2.createFunctionDeclaration( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + name, + /*typeParameters*/ + void 0, + transformConstructorParameters(constructor, hasSynthesizedSuper), + /*type*/ + void 0, + transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) + ); + setTextRange(constructorFunction, constructor || node); + if (extendsClauseElement) { + setEmitFlags(constructorFunction, 16 /* CapturesThis */); + } + statements.push(constructorFunction); + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + } + function transformConstructorParameters(constructor, hasSynthesizedSuper) { + return visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : void 0, visitor, context) || []; + } + function createDefaultConstructorBody(node, isDerivedClass) { + const statements = []; + resumeLexicalEnvironment(); + factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (isDerivedClass) { + statements.push(factory2.createReturnStatement(createDefaultSuperCallOrThis())); + } + const statementsArray = factory2.createNodeArray(statements); + setTextRange(statementsArray, node.members); + const block = factory2.createBlock( + statementsArray, + /*multiLine*/ + true + ); + setTextRange(block, node); + setEmitFlags(block, 3072 /* NoComments */); + return block; + } + function isUninitializedVariableStatement(node) { + return isVariableStatement(node) && every(node.declarationList.declarations, (decl) => isIdentifier(decl.name) && !decl.initializer); + } + function containsSuperCall(node) { + if (isSuperCall(node)) { + return true; + } + if (!(node.transformFlags & 134217728 /* ContainsLexicalSuper */)) { + return false; + } + switch (node.kind) { + // stop at function boundaries + case 219 /* ArrowFunction */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 176 /* Constructor */: + case 175 /* ClassStaticBlockDeclaration */: + return false; + // only step into computed property names for class and object literal elements + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + case 172 /* PropertyDeclaration */: { + const named = node; + if (isComputedPropertyName(named.name)) { + return !!forEachChild(named.name, containsSuperCall); + } + return false; + } + } + return !!forEachChild(node, containsSuperCall); + } + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */; + if (!constructor) return createDefaultConstructorBody(node, isDerivedClass); + const prologue = []; + const statements = []; + resumeLexicalEnvironment(); + const standardPrologueEnd = factory2.copyStandardPrologue( + constructor.body.statements, + prologue, + /*statementOffset*/ + 0 + ); + if (hasSynthesizedSuper || containsSuperCall(constructor.body)) { + hierarchyFacts |= 8192 /* ConstructorWithSuperCall */; + } + addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, standardPrologueEnd)); + const mayReplaceThis = isDerivedClass || hierarchyFacts & 8192 /* ConstructorWithSuperCall */; + addDefaultValueAssignmentsIfNeeded2(prologue, constructor); + addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper); + insertCaptureNewTargetIfNeeded(prologue, constructor); + if (mayReplaceThis) { + insertCaptureThisForNode(prologue, constructor, createActualThis()); + } else { + insertCaptureThisForNodeIfNeeded(prologue, constructor); + } + factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + if (mayReplaceThis && !isSufficientlyCoveredByReturnStatements(constructor.body)) { + statements.push(factory2.createReturnStatement(createCapturedThis())); + } + const body = factory2.createBlock( + setTextRange( + factory2.createNodeArray( + [ + ...prologue, + ...statements + ] + ), + /*location*/ + constructor.body.statements + ), + /*multiLine*/ + true + ); + setTextRange(body, constructor.body); + return simplifyConstructor(body, constructor.body, hasSynthesizedSuper); + } + function isCapturedThis(node) { + return isGeneratedIdentifier(node) && idText(node) === "_this"; + } + function isSyntheticSuper(node) { + return isGeneratedIdentifier(node) && idText(node) === "_super"; + } + function isThisCapturingVariableStatement(node) { + return isVariableStatement(node) && node.declarationList.declarations.length === 1 && isThisCapturingVariableDeclaration(node.declarationList.declarations[0]); + } + function isThisCapturingVariableDeclaration(node) { + return isVariableDeclaration(node) && isCapturedThis(node.name) && !!node.initializer; + } + function isThisCapturingAssignment(node) { + return isAssignmentExpression( + node, + /*excludeCompoundAssignment*/ + true + ) && isCapturedThis(node.left); + } + function isTransformedSuperCall(node) { + return isCallExpression(node) && isPropertyAccessExpression(node.expression) && isSyntheticSuper(node.expression.expression) && isIdentifier(node.expression.name) && (idText(node.expression.name) === "call" || idText(node.expression.name) === "apply") && node.arguments.length >= 1 && node.arguments[0].kind === 110 /* ThisKeyword */; + } + function isTransformedSuperCallWithFallback(node) { + return isBinaryExpression(node) && node.operatorToken.kind === 57 /* BarBarToken */ && node.right.kind === 110 /* ThisKeyword */ && isTransformedSuperCall(node.left); + } + function isImplicitSuperCall(node) { + return isBinaryExpression(node) && node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ && isBinaryExpression(node.left) && node.left.operatorToken.kind === 38 /* ExclamationEqualsEqualsToken */ && isSyntheticSuper(node.left.left) && node.left.right.kind === 106 /* NullKeyword */ && isTransformedSuperCall(node.right) && idText(node.right.expression.name) === "apply"; + } + function isImplicitSuperCallWithFallback(node) { + return isBinaryExpression(node) && node.operatorToken.kind === 57 /* BarBarToken */ && node.right.kind === 110 /* ThisKeyword */ && isImplicitSuperCall(node.left); + } + function isThisCapturingTransformedSuperCallWithFallback(node) { + return isThisCapturingAssignment(node) && isTransformedSuperCallWithFallback(node.right); + } + function isThisCapturingImplicitSuperCallWithFallback(node) { + return isThisCapturingAssignment(node) && isImplicitSuperCallWithFallback(node.right); + } + function isTransformedSuperCallLike(node) { + return isTransformedSuperCall(node) || isTransformedSuperCallWithFallback(node) || isThisCapturingTransformedSuperCallWithFallback(node) || isImplicitSuperCall(node) || isImplicitSuperCallWithFallback(node) || isThisCapturingImplicitSuperCallWithFallback(node); + } + function simplifyConstructorInlineSuperInThisCaptureVariable(body) { + for (let i = 0; i < body.statements.length - 1; i++) { + const statement = body.statements[i]; + if (!isThisCapturingVariableStatement(statement)) { + continue; + } + const varDecl = statement.declarationList.declarations[0]; + if (varDecl.initializer.kind !== 110 /* ThisKeyword */) { + continue; + } + const thisCaptureStatementIndex = i; + let superCallIndex = i + 1; + while (superCallIndex < body.statements.length) { + const statement2 = body.statements[superCallIndex]; + if (isExpressionStatement(statement2)) { + if (isTransformedSuperCallLike(skipOuterExpressions(statement2.expression))) { + break; + } + } + if (isUninitializedVariableStatement(statement2)) { + superCallIndex++; + continue; + } + return body; + } + const following = body.statements[superCallIndex]; + let expression = following.expression; + if (isThisCapturingAssignment(expression)) { + expression = expression.right; + } + const newVarDecl = factory2.updateVariableDeclaration( + varDecl, + varDecl.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + expression + ); + const newDeclList = factory2.updateVariableDeclarationList(statement.declarationList, [newVarDecl]); + const newVarStatement = factory2.createVariableStatement(statement.modifiers, newDeclList); + setOriginalNode(newVarStatement, following); + setTextRange(newVarStatement, following); + const newStatements = factory2.createNodeArray([ + ...body.statements.slice(0, thisCaptureStatementIndex), + // copy statements preceding to `var _this` + ...body.statements.slice(thisCaptureStatementIndex + 1, superCallIndex), + // copy intervening temp variables + newVarStatement, + ...body.statements.slice(superCallIndex + 1) + // copy statements following `super.call(this, ...)` + ]); + setTextRange(newStatements, body.statements); + return factory2.updateBlock(body, newStatements); + } + return body; + } + function simplifyConstructorInlineSuperReturn(body, original) { + for (const statement of original.statements) { + if (statement.transformFlags & 134217728 /* ContainsLexicalSuper */ && !getSuperCallFromStatement(statement)) { + return body; + } + } + const canElideThisCapturingVariable = !(original.transformFlags & 16384 /* ContainsLexicalThis */) && !(hierarchyFacts & 65536 /* LexicalThis */) && !(hierarchyFacts & 131072 /* CapturedLexicalThis */); + for (let i = body.statements.length - 1; i > 0; i--) { + const statement = body.statements[i]; + if (isReturnStatement(statement) && statement.expression && isCapturedThis(statement.expression)) { + const preceding = body.statements[i - 1]; + let expression; + if (isExpressionStatement(preceding) && isThisCapturingTransformedSuperCallWithFallback(skipOuterExpressions(preceding.expression))) { + expression = preceding.expression; + } else if (canElideThisCapturingVariable && isThisCapturingVariableStatement(preceding)) { + const varDecl = preceding.declarationList.declarations[0]; + if (isTransformedSuperCallLike(skipOuterExpressions(varDecl.initializer))) { + expression = factory2.createAssignment( + createCapturedThis(), + varDecl.initializer + ); + } + } + if (!expression) { + break; + } + const newReturnStatement = factory2.createReturnStatement(expression); + setOriginalNode(newReturnStatement, preceding); + setTextRange(newReturnStatement, preceding); + const newStatements = factory2.createNodeArray([ + ...body.statements.slice(0, i - 1), + // copy all statements preceding `_super.call(this, ...)` + newReturnStatement, + ...body.statements.slice(i + 1) + // copy all statements following `return _this;` + ]); + setTextRange(newStatements, body.statements); + return factory2.updateBlock(body, newStatements); + } + } + return body; + } + function elideUnusedThisCaptureWorker(node) { + if (isThisCapturingVariableStatement(node)) { + const varDecl = node.declarationList.declarations[0]; + if (varDecl.initializer.kind === 110 /* ThisKeyword */) { + return void 0; + } + } else if (isThisCapturingAssignment(node)) { + return factory2.createPartiallyEmittedExpression(node.right, node); + } + switch (node.kind) { + // stop at function boundaries + case 219 /* ArrowFunction */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 176 /* Constructor */: + case 175 /* ClassStaticBlockDeclaration */: + return node; + // only step into computed property names for class and object literal elements + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + case 172 /* PropertyDeclaration */: { + const named = node; + if (isComputedPropertyName(named.name)) { + return factory2.replacePropertyName(named, visitEachChild( + named.name, + elideUnusedThisCaptureWorker, + /*context*/ + void 0 + )); + } + return node; + } + } + return visitEachChild( + node, + elideUnusedThisCaptureWorker, + /*context*/ + void 0 + ); + } + function simplifyConstructorElideUnusedThisCapture(body, original) { + if (original.transformFlags & 16384 /* ContainsLexicalThis */ || hierarchyFacts & 65536 /* LexicalThis */ || hierarchyFacts & 131072 /* CapturedLexicalThis */) { + return body; + } + for (const statement of original.statements) { + if (statement.transformFlags & 134217728 /* ContainsLexicalSuper */ && !getSuperCallFromStatement(statement)) { + return body; + } + } + return factory2.updateBlock(body, visitNodes2(body.statements, elideUnusedThisCaptureWorker, isStatement)); + } + function injectSuperPresenceCheckWorker(node) { + if (isTransformedSuperCall(node) && node.arguments.length === 2 && isIdentifier(node.arguments[1]) && idText(node.arguments[1]) === "arguments") { + return factory2.createLogicalAnd( + factory2.createStrictInequality( + createSyntheticSuper(), + factory2.createNull() + ), + node + ); + } + switch (node.kind) { + // stop at function boundaries + case 219 /* ArrowFunction */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 176 /* Constructor */: + case 175 /* ClassStaticBlockDeclaration */: + return node; + // only step into computed property names for class and object literal elements + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 174 /* MethodDeclaration */: + case 172 /* PropertyDeclaration */: { + const named = node; + if (isComputedPropertyName(named.name)) { + return factory2.replacePropertyName(named, visitEachChild( + named.name, + injectSuperPresenceCheckWorker, + /*context*/ + void 0 + )); + } + return node; + } + } + return visitEachChild( + node, + injectSuperPresenceCheckWorker, + /*context*/ + void 0 + ); + } + function complicateConstructorInjectSuperPresenceCheck(body) { + return factory2.updateBlock(body, visitNodes2(body.statements, injectSuperPresenceCheckWorker, isStatement)); + } + function simplifyConstructor(body, original, hasSynthesizedSuper) { + const inputBody = body; + body = simplifyConstructorInlineSuperInThisCaptureVariable(body); + body = simplifyConstructorInlineSuperReturn(body, original); + if (body !== inputBody) { + body = simplifyConstructorElideUnusedThisCapture(body, original); + } + if (hasSynthesizedSuper) { + body = complicateConstructorInjectSuperPresenceCheck(body); + } + return body; + } + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 253 /* ReturnStatement */) { + return true; + } else if (statement.kind === 245 /* IfStatement */) { + const ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } else if (statement.kind === 241 /* Block */) { + const lastStatement = lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function createActualThis() { + return setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */); + } + function createDefaultSuperCallOrThis() { + return factory2.createLogicalOr( + factory2.createLogicalAnd( + factory2.createStrictInequality( + createSyntheticSuper(), + factory2.createNull() + ), + factory2.createFunctionApplyCall( + createSyntheticSuper(), + createActualThis(), + factory2.createIdentifier("arguments") + ) + ), + createActualThis() + ); + } + function visitParameter(node) { + if (node.dotDotDotToken) { + return void 0; + } else if (isBindingPattern(node.name)) { + return setOriginalNode( + setTextRange( + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + factory2.getGeneratedNameForNode(node), + /*questionToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ), + /*location*/ + node + ), + /*original*/ + node + ); + } else if (node.initializer) { + return setOriginalNode( + setTextRange( + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + node.name, + /*questionToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ), + /*location*/ + node + ), + /*original*/ + node + ); + } else { + return node; + } + } + function hasDefaultValueOrBindingPattern(node) { + return node.initializer !== void 0 || isBindingPattern(node.name); + } + function addDefaultValueAssignmentsIfNeeded2(statements, node) { + if (!some(node.parameters, hasDefaultValueOrBindingPattern)) { + return false; + } + let added = false; + for (const parameter of node.parameters) { + const { name, initializer, dotDotDotToken } = parameter; + if (dotDotDotToken) { + continue; + } + if (isBindingPattern(name)) { + added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added; + } else if (initializer) { + insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + added = true; + } + } + return added; + } + function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { + if (name.elements.length > 0) { + insertStatementAfterCustomPrologue( + statements, + setEmitFlags( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + flattenDestructuringBinding( + parameter, + visitor, + context, + 0 /* All */, + factory2.getGeneratedNameForNode(parameter) + ) + ) + ), + 2097152 /* CustomPrologue */ + ) + ); + return true; + } else if (initializer) { + insertStatementAfterCustomPrologue( + statements, + setEmitFlags( + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.getGeneratedNameForNode(parameter), + Debug.checkDefined(visitNode(initializer, visitor, isExpression)) + ) + ), + 2097152 /* CustomPrologue */ + ) + ); + return true; + } + return false; + } + function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + initializer = Debug.checkDefined(visitNode(initializer, visitor, isExpression)); + const statement = factory2.createIfStatement( + factory2.createTypeCheck(factory2.cloneNode(name), "undefined"), + setEmitFlags( + setTextRange( + factory2.createBlock([ + factory2.createExpressionStatement( + setEmitFlags( + setTextRange( + factory2.createAssignment( + // TODO(rbuckton): Does this need to be parented? + setEmitFlags(setParent(setTextRange(factory2.cloneNode(name), name), name.parent), 96 /* NoSourceMap */), + setEmitFlags(initializer, 96 /* NoSourceMap */ | getEmitFlags(initializer) | 3072 /* NoComments */) + ), + parameter + ), + 3072 /* NoComments */ + ) + ) + ]), + parameter + ), + 1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */ + ) + ); + startOnNewLine(statement); + setTextRange(statement, parameter); + setEmitFlags(statement, 768 /* NoTokenSourceMaps */ | 64 /* NoTrailingSourceMap */ | 2097152 /* CustomPrologue */ | 3072 /* NoComments */); + insertStatementAfterCustomPrologue(statements, statement); + } + function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { + return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper); + } + function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + const prologueStatements = []; + const parameter = lastOrUndefined(node.parameters); + if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { + return false; + } + const declarationName = parameter.name.kind === 80 /* Identifier */ ? setParent(setTextRange(factory2.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + setEmitFlags(declarationName, 96 /* NoSourceMap */); + const expressionName = parameter.name.kind === 80 /* Identifier */ ? factory2.cloneNode(parameter.name) : declarationName; + const restIndex = node.parameters.length - 1; + const temp = factory2.createLoopVariable(); + prologueStatements.push( + setEmitFlags( + setTextRange( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + declarationName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createArrayLiteralExpression([]) + ) + ]) + ), + /*location*/ + parameter + ), + 2097152 /* CustomPrologue */ + ) + ); + const forStatement = factory2.createForStatement( + setTextRange( + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + temp, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createNumericLiteral(restIndex) + ) + ]), + parameter + ), + setTextRange( + factory2.createLessThan( + temp, + factory2.createPropertyAccessExpression(factory2.createIdentifier("arguments"), "length") + ), + parameter + ), + setTextRange(factory2.createPostfixIncrement(temp), parameter), + factory2.createBlock([ + startOnNewLine( + setTextRange( + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createElementAccessExpression( + expressionName, + restIndex === 0 ? temp : factory2.createSubtract(temp, factory2.createNumericLiteral(restIndex)) + ), + factory2.createElementAccessExpression(factory2.createIdentifier("arguments"), temp) + ) + ), + /*location*/ + parameter + ) + ) + ]) + ); + setEmitFlags(forStatement, 2097152 /* CustomPrologue */); + startOnNewLine(forStatement); + prologueStatements.push(forStatement); + if (parameter.name.kind !== 80 /* Identifier */) { + prologueStatements.push( + setEmitFlags( + setTextRange( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName) + ) + ), + parameter + ), + 2097152 /* CustomPrologue */ + ) + ); + } + insertStatementsAfterCustomPrologue(statements, prologueStatements); + return true; + } + function insertCaptureThisForNodeIfNeeded(statements, node) { + if (hierarchyFacts & 131072 /* CapturedLexicalThis */ && node.kind !== 219 /* ArrowFunction */) { + insertCaptureThisForNode(statements, node, factory2.createThis()); + return true; + } + return false; + } + function insertCaptureThisForNode(statements, node, initializer) { + enableSubstitutionsForCapturedThis(); + const captureThisStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + createCapturedThis(), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + initializer + ) + ]) + ); + setEmitFlags(captureThisStatement, 3072 /* NoComments */ | 2097152 /* CustomPrologue */); + setSourceMapRange(captureThisStatement, node); + insertStatementAfterCustomPrologue(statements, captureThisStatement); + } + function insertCaptureNewTargetIfNeeded(statements, node) { + if (hierarchyFacts & 32768 /* NewTarget */) { + let newTarget; + switch (node.kind) { + case 219 /* ArrowFunction */: + return statements; + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + newTarget = factory2.createVoidZero(); + break; + case 176 /* Constructor */: + newTarget = factory2.createPropertyAccessExpression( + setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), + "constructor" + ); + break; + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + newTarget = factory2.createConditionalExpression( + factory2.createLogicalAnd( + setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), + factory2.createBinaryExpression( + setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), + 104 /* InstanceOfKeyword */, + factory2.getLocalName(node) + ) + ), + /*questionToken*/ + void 0, + factory2.createPropertyAccessExpression( + setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), + "constructor" + ), + /*colonToken*/ + void 0, + factory2.createVoidZero() + ); + break; + default: + return Debug.failBadSyntaxKind(node); + } + const captureNewTargetStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + factory2.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + newTarget + ) + ]) + ); + setEmitFlags(captureNewTargetStatement, 3072 /* NoComments */ | 2097152 /* CustomPrologue */); + insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); + } + return statements; + } + function addClassMembers(statements, node) { + for (const member of node.members) { + switch (member.kind) { + case 240 /* SemicolonClassElement */: + statements.push(transformSemicolonClassElementToStatement(member)); + break; + case 174 /* MethodDeclaration */: + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); + break; + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + const accessors = getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); + } + break; + case 176 /* Constructor */: + case 175 /* ClassStaticBlockDeclaration */: + break; + default: + Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName); + break; + } + } + } + function transformSemicolonClassElementToStatement(member) { + return setTextRange(factory2.createEmptyStatement(), member); + } + function transformClassMethodDeclarationToStatement(receiver, member, container) { + const commentRange = getCommentRange(member); + const sourceMapRange = getSourceMapRange(member); + const memberFunction = transformFunctionLikeToExpression( + member, + /*location*/ + member, + /*name*/ + void 0, + container + ); + const propertyName = visitNode(member.name, visitor, isPropertyName); + Debug.assert(propertyName); + let e; + if (!isPrivateIdentifier(propertyName) && getUseDefineForClassFields(context.getCompilerOptions())) { + const name = isComputedPropertyName(propertyName) ? propertyName.expression : isIdentifier(propertyName) ? factory2.createStringLiteral(unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; + e = factory2.createObjectDefinePropertyCall(receiver, name, factory2.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true })); + } else { + const memberName = createMemberAccessForPropertyName( + factory2, + receiver, + propertyName, + /*location*/ + member.name + ); + e = factory2.createAssignment(memberName, memberFunction); + } + setEmitFlags(memberFunction, 3072 /* NoComments */); + setSourceMapRange(memberFunction, sourceMapRange); + const statement = setTextRange( + factory2.createExpressionStatement(e), + /*location*/ + member + ); + setOriginalNode(statement, member); + setCommentRange(statement, commentRange); + setEmitFlags(statement, 96 /* NoSourceMap */); + return statement; + } + function transformAccessorsToStatement(receiver, accessors, container) { + const statement = factory2.createExpressionStatement(transformAccessorsToExpression( + receiver, + accessors, + container, + /*startsOnNewLine*/ + false + )); + setEmitFlags(statement, 3072 /* NoComments */); + setSourceMapRange(statement, getSourceMapRange(accessors.firstAccessor)); + return statement; + } + function transformAccessorsToExpression(receiver, { firstAccessor, getAccessor, setAccessor }, container, startsOnNewLine) { + const target = setParent(setTextRange(factory2.cloneNode(receiver), receiver), receiver.parent); + setEmitFlags(target, 3072 /* NoComments */ | 64 /* NoTrailingSourceMap */); + setSourceMapRange(target, firstAccessor.name); + const visitedAccessorName = visitNode(firstAccessor.name, visitor, isPropertyName); + Debug.assert(visitedAccessorName); + if (isPrivateIdentifier(visitedAccessorName)) { + return Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015."); + } + const propertyName = createExpressionForPropertyName(factory2, visitedAccessorName); + setEmitFlags(propertyName, 3072 /* NoComments */ | 32 /* NoLeadingSourceMap */); + setSourceMapRange(propertyName, firstAccessor.name); + const properties = []; + if (getAccessor) { + const getterFunction = transformFunctionLikeToExpression( + getAccessor, + /*location*/ + void 0, + /*name*/ + void 0, + container + ); + setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + setEmitFlags(getterFunction, 1024 /* NoLeadingComments */); + const getter = factory2.createPropertyAssignment("get", getterFunction); + setCommentRange(getter, getCommentRange(getAccessor)); + properties.push(getter); + } + if (setAccessor) { + const setterFunction = transformFunctionLikeToExpression( + setAccessor, + /*location*/ + void 0, + /*name*/ + void 0, + container + ); + setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + setEmitFlags(setterFunction, 1024 /* NoLeadingComments */); + const setter = factory2.createPropertyAssignment("set", setterFunction); + setCommentRange(setter, getCommentRange(setAccessor)); + properties.push(setter); + } + properties.push( + factory2.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory2.createFalse() : factory2.createTrue()), + factory2.createPropertyAssignment("configurable", factory2.createTrue()) + ); + const call = factory2.createCallExpression( + factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ + void 0, + [ + target, + propertyName, + factory2.createObjectLiteralExpression( + properties, + /*multiLine*/ + true + ) + ] + ); + if (startsOnNewLine) { + startOnNewLine(call); + } + return call; + } + function visitArrowFunction(node) { + if (node.transformFlags & 16384 /* ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) { + hierarchyFacts |= 131072 /* CapturedLexicalThis */; + } + const savedConvertedLoopState = convertedLoopState; + convertedLoopState = void 0; + const ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + const func = factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + transformFunctionBody(node) + ); + setTextRange(func, node); + setOriginalNode(func, node); + setEmitFlags(func, 16 /* CapturesThis */); + exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return func; + } + function visitFunctionExpression(node) { + const ancestorFacts = getEmitFlags(node) & 524288 /* AsyncFunctionBody */ ? enterSubtree(32662 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) : enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */); + const savedConvertedLoopState = convertedLoopState; + convertedLoopState = void 0; + const parameters = visitParameterList(node.parameters, visitor, context); + const body = transformFunctionBody(node); + const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name; + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return factory2.updateFunctionExpression( + node, + /*modifiers*/ + void 0, + node.asteriskToken, + name, + /*typeParameters*/ + void 0, + parameters, + /*type*/ + void 0, + body + ); + } + function visitFunctionDeclaration(node) { + const savedConvertedLoopState = convertedLoopState; + convertedLoopState = void 0; + const ancestorFacts = enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */); + const parameters = visitParameterList(node.parameters, visitor, context); + const body = transformFunctionBody(node); + const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name; + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return factory2.updateFunctionDeclaration( + node, + visitNodes2(node.modifiers, visitor, isModifier), + node.asteriskToken, + name, + /*typeParameters*/ + void 0, + parameters, + /*type*/ + void 0, + body + ); + } + function transformFunctionLikeToExpression(node, location, name, container) { + const savedConvertedLoopState = convertedLoopState; + convertedLoopState = void 0; + const ancestorFacts = container && isClassLike(container) && !isStatic(node) ? enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) : enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */); + const parameters = visitParameterList(node.parameters, visitor, context); + const body = transformFunctionBody(node); + if (hierarchyFacts & 32768 /* NewTarget */ && !name && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */)) { + name = factory2.getGeneratedNameForNode(node); + } + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return setOriginalNode( + setTextRange( + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + node.asteriskToken, + name, + /*typeParameters*/ + void 0, + parameters, + /*type*/ + void 0, + body + ), + location + ), + /*original*/ + node + ); + } + function transformFunctionBody(node) { + let multiLine = false; + let singleLine = false; + let statementsLocation; + let closeBraceLocation; + const prologue = []; + const statements = []; + const body = node.body; + let statementOffset; + resumeLexicalEnvironment(); + if (isBlock(body)) { + statementOffset = factory2.copyStandardPrologue( + body.statements, + prologue, + 0, + /*ensureUseStrict*/ + false + ); + statementOffset = factory2.copyCustomPrologue(body.statements, statements, statementOffset, visitor, isHoistedFunction); + statementOffset = factory2.copyCustomPrologue(body.statements, statements, statementOffset, visitor, isHoistedVariableStatement); + } + multiLine = addDefaultValueAssignmentsIfNeeded2(statements, node) || multiLine; + multiLine = addRestParameterIfNeeded( + statements, + node, + /*inConstructorWithSynthesizedSuper*/ + false + ) || multiLine; + if (isBlock(body)) { + statementOffset = factory2.copyCustomPrologue(body.statements, statements, statementOffset, visitor); + statementsLocation = body.statements; + addRange(statements, visitNodes2(body.statements, visitor, isStatement, statementOffset)); + if (!multiLine && body.multiLine) { + multiLine = true; + } + } else { + Debug.assert(node.kind === 219 /* ArrowFunction */); + statementsLocation = moveRangeEnd(body, -1); + const equalsGreaterThanToken = node.equalsGreaterThanToken; + if (!nodeIsSynthesized(equalsGreaterThanToken) && !nodeIsSynthesized(body)) { + if (rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) { + singleLine = true; + } else { + multiLine = true; + } + } + const expression = visitNode(body, visitor, isExpression); + const returnStatement = factory2.createReturnStatement(expression); + setTextRange(returnStatement, body); + moveSyntheticComments(returnStatement, body); + setEmitFlags(returnStatement, 768 /* NoTokenSourceMaps */ | 64 /* NoTrailingSourceMap */ | 2048 /* NoTrailingComments */); + statements.push(returnStatement); + closeBraceLocation = body; + } + factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, node); + insertCaptureThisForNodeIfNeeded(prologue, node); + if (some(prologue)) { + multiLine = true; + } + statements.unshift(...prologue); + if (isBlock(body) && arrayIsEqualTo(statements, body.statements)) { + return body; + } + const block = factory2.createBlock(setTextRange(factory2.createNodeArray(statements), statementsLocation), multiLine); + setTextRange(block, node.body); + if (!multiLine && singleLine) { + setEmitFlags(block, 1 /* SingleLine */); + } + if (closeBraceLocation) { + setTokenSourceMapRange(block, 20 /* CloseBraceToken */, closeBraceLocation); + } + setOriginalNode(block, node.body); + return block; + } + function visitBlock(node, isFunctionBody) { + if (isFunctionBody) { + return visitEachChild(node, visitor, context); + } + const ancestorFacts = hierarchyFacts & 256 /* IterationStatement */ ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */) : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */); + const updated = visitEachChild(node, visitor, context); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function visitExpressionStatement(node) { + return visitEachChild(node, visitorWithUnusedExpressionResult, context); + } + function visitParenthesizedExpression(node, expressionResultIsUnused2) { + return visitEachChild(node, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, context); + } + function visitBinaryExpression(node, expressionResultIsUnused2) { + if (isDestructuringAssignment(node)) { + return flattenDestructuringAssignment( + node, + visitor, + context, + 0 /* All */, + !expressionResultIsUnused2 + ); + } + if (node.operatorToken.kind === 28 /* CommaToken */) { + return factory2.updateBinaryExpression( + node, + Debug.checkDefined(visitNode(node.left, visitorWithUnusedExpressionResult, isExpression)), + node.operatorToken, + Debug.checkDefined(visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression)) + ); + } + return visitEachChild(node, visitor, context); + } + function visitCommaListExpression(node, expressionResultIsUnused2) { + if (expressionResultIsUnused2) { + return visitEachChild(node, visitorWithUnusedExpressionResult, context); + } + let result; + for (let i = 0; i < node.elements.length; i++) { + const element = node.elements[i]; + const visited = visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, isExpression); + if (result || visited !== element) { + result || (result = node.elements.slice(0, i)); + Debug.assert(visited); + result.push(visited); + } + } + const elements = result ? setTextRange(factory2.createNodeArray(result), node.elements) : node.elements; + return factory2.updateCommaListExpression(node, elements); + } + function isVariableStatementOfTypeScriptClassWrapper(node) { + return node.declarationList.declarations.length === 1 && !!node.declarationList.declarations[0].initializer && !!(getInternalEmitFlags(node.declarationList.declarations[0].initializer) & 1 /* TypeScriptClassWrapper */); + } + function visitVariableStatement(node) { + const ancestorFacts = enterSubtree(0 /* None */, hasSyntacticModifier(node, 32 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); + let updated; + if (convertedLoopState && (node.declarationList.flags & 7 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) { + let assignments; + for (const decl of node.declarationList.declarations) { + hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl); + if (decl.initializer) { + let assignment; + if (isBindingPattern(decl.name)) { + assignment = flattenDestructuringAssignment( + decl, + visitor, + context, + 0 /* All */ + ); + } else { + assignment = factory2.createBinaryExpression(decl.name, 64 /* EqualsToken */, Debug.checkDefined(visitNode(decl.initializer, visitor, isExpression))); + setTextRange(assignment, decl); + } + assignments = append(assignments, assignment); + } + } + if (assignments) { + updated = setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(assignments)), node); + } else { + updated = void 0; + } + } else { + updated = visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function visitVariableDeclarationList(node) { + if (node.flags & 7 /* BlockScoped */ || node.transformFlags & 524288 /* ContainsBindingPattern */) { + if (node.flags & 7 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + const declarations = visitNodes2( + node.declarations, + node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList : visitVariableDeclaration, + isVariableDeclaration + ); + const declarationList = factory2.createVariableDeclarationList(declarations); + setOriginalNode(declarationList, node); + setTextRange(declarationList, node); + setCommentRange(declarationList, node); + if (node.transformFlags & 524288 /* ContainsBindingPattern */ && (isBindingPattern(node.declarations[0].name) || isBindingPattern(last(node.declarations).name))) { + setSourceMapRange(declarationList, getRangeUnion(declarations)); + } + return declarationList; + } + return visitEachChild(node, visitor, context); + } + function getRangeUnion(declarations) { + let pos = -1, end = -1; + for (const node of declarations) { + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return createRange(pos, end); + } + function shouldEmitExplicitInitializerForLetDeclaration(node) { + const isCapturedInFunction = resolver.hasNodeCheckFlag(node, 16384 /* CapturedBlockScopedBinding */); + const isDeclaredInLoop = resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */); + const emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || isCapturedInFunction && isDeclaredInLoop && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0; + const emitExplicitInitializer = !emittedAsTopLevel && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0 && (!resolver.isDeclarationWithCollidingName(node) || isDeclaredInLoop && !isCapturedInFunction && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0); + return emitExplicitInitializer; + } + function visitVariableDeclarationInLetDeclarationList(node) { + const name = node.name; + if (isBindingPattern(name)) { + return visitVariableDeclaration(node); + } + if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { + return factory2.updateVariableDeclaration( + node, + node.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createVoidZero() + ); + } + return visitEachChild(node, visitor, context); + } + function visitVariableDeclaration(node) { + const ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */); + let updated; + if (isBindingPattern(node.name)) { + updated = flattenDestructuringBinding( + node, + visitor, + context, + 0 /* All */, + /*rval*/ + void 0, + (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0 + ); + } else { + updated = visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function recordLabel(node) { + convertedLoopState.labels.set(idText(node.label), true); + } + function resetLabel(node) { + convertedLoopState.labels.set(idText(node.label), false); + } + function visitLabeledStatement(node) { + if (convertedLoopState && !convertedLoopState.labels) { + convertedLoopState.labels = /* @__PURE__ */ new Map(); + } + const statement = unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); + return isIterationStatement( + statement, + /*lookInLabeledStatements*/ + false + ) ? visitIterationStatement( + statement, + /*outermostLabeledStatement*/ + node + ) : factory2.restoreEnclosingLabel(visitNode(statement, visitor, isStatement, factory2.liftToBlock) ?? setTextRange(factory2.createEmptyStatement(), statement), node, convertedLoopState && resetLabel); + } + function visitIterationStatement(node, outermostLabeledStatement) { + switch (node.kind) { + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + return visitDoOrWhileStatement(node, outermostLabeledStatement); + case 248 /* ForStatement */: + return visitForStatement(node, outermostLabeledStatement); + case 249 /* ForInStatement */: + return visitForInStatement(node, outermostLabeledStatement); + case 250 /* ForOfStatement */: + return visitForOfStatement(node, outermostLabeledStatement); + } + } + function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) { + const ancestorFacts = enterSubtree(excludeFacts, includeFacts); + const updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function visitDoOrWhileStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts( + 0 /* DoOrWhileStatementExcludes */, + 1280 /* DoOrWhileStatementIncludes */, + node, + outermostLabeledStatement + ); + } + function visitForStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts( + 5056 /* ForStatementExcludes */, + 3328 /* ForStatementIncludes */, + node, + outermostLabeledStatement + ); + } + function visitEachChildOfForStatement2(node) { + return factory2.updateForStatement( + node, + visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), + visitNode(node.condition, visitor, isExpression), + visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), + Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock)) + ); + } + function visitForInStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts( + 3008 /* ForInOrForOfStatementExcludes */, + 5376 /* ForInOrForOfStatementIncludes */, + node, + outermostLabeledStatement + ); + } + function visitForOfStatement(node, outermostLabeledStatement) { + return visitIterationStatementWithFacts( + 3008 /* ForInOrForOfStatementExcludes */, + 5376 /* ForInOrForOfStatementIncludes */, + node, + outermostLabeledStatement, + compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray + ); + } + function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { + const statements = []; + const initializer = node.initializer; + if (isVariableDeclarationList(initializer)) { + if (node.initializer.flags & 7 /* BlockScoped */) { + enableSubstitutionsForBlockScopedBindings(); + } + const firstOriginalDeclaration = firstOrUndefined(initializer.declarations); + if (firstOriginalDeclaration && isBindingPattern(firstOriginalDeclaration.name)) { + const declarations = flattenDestructuringBinding( + firstOriginalDeclaration, + visitor, + context, + 0 /* All */, + boundValue + ); + const declarationList = setTextRange(factory2.createVariableDeclarationList(declarations), node.initializer); + setOriginalNode(declarationList, node.initializer); + setSourceMapRange(declarationList, createRange(declarations[0].pos, last(declarations).end)); + statements.push( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + declarationList + ) + ); + } else { + statements.push( + setTextRange( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + setOriginalNode( + setTextRange( + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + firstOriginalDeclaration ? firstOriginalDeclaration.name : factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + boundValue + ) + ]), + moveRangePos(initializer, -1) + ), + initializer + ) + ), + moveRangeEnd(initializer, -1) + ) + ); + } + } else { + const assignment = factory2.createAssignment(initializer, boundValue); + if (isDestructuringAssignment(assignment)) { + statements.push(factory2.createExpressionStatement(visitBinaryExpression( + assignment, + /*expressionResultIsUnused*/ + true + ))); + } else { + setTextRangeEnd(assignment, initializer.end); + statements.push(setTextRange(factory2.createExpressionStatement(Debug.checkDefined(visitNode(assignment, visitor, isExpression))), moveRangeEnd(initializer, -1))); + } + } + if (convertedLoopBodyStatements) { + return createSyntheticBlockForConvertedStatements(addRange(statements, convertedLoopBodyStatements)); + } else { + const statement = visitNode(node.statement, visitor, isStatement, factory2.liftToBlock); + Debug.assert(statement); + if (isBlock(statement)) { + return factory2.updateBlock(statement, setTextRange(factory2.createNodeArray(concatenate(statements, statement.statements)), statement.statements)); + } else { + statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); + } + } + } + function createSyntheticBlockForConvertedStatements(statements) { + return setEmitFlags( + factory2.createBlock( + factory2.createNodeArray(statements), + /*multiLine*/ + true + ), + 96 /* NoSourceMap */ | 768 /* NoTokenSourceMaps */ + ); + } + function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { + const expression = visitNode(node.expression, visitor, isExpression); + Debug.assert(expression); + const counter = factory2.createLoopVariable(); + const rhsReference = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + setEmitFlags(expression, 96 /* NoSourceMap */ | getEmitFlags(expression)); + const forStatement = setTextRange( + factory2.createForStatement( + /*initializer*/ + setEmitFlags( + setTextRange( + factory2.createVariableDeclarationList([ + setTextRange(factory2.createVariableDeclaration( + counter, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createNumericLiteral(0) + ), moveRangePos(node.expression, -1)), + setTextRange(factory2.createVariableDeclaration( + rhsReference, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + expression + ), node.expression) + ]), + node.expression + ), + 4194304 /* NoHoisting */ + ), + /*condition*/ + setTextRange( + factory2.createLessThan( + counter, + factory2.createPropertyAccessExpression(rhsReference, "length") + ), + node.expression + ), + /*incrementor*/ + setTextRange(factory2.createPostfixIncrement(counter), node.expression), + /*statement*/ + convertForOfStatementHead( + node, + factory2.createElementAccessExpression(rhsReference, counter), + convertedLoopBodyStatements + ) + ), + /*location*/ + node + ); + setEmitFlags(forStatement, 512 /* NoTokenTrailingSourceMaps */); + setTextRange(forStatement, node); + return factory2.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); + } + function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) { + const expression = visitNode(node.expression, visitor, isExpression); + Debug.assert(expression); + const iterator = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const result = isIdentifier(expression) ? factory2.getGeneratedNameForNode(iterator) : factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const errorRecord = factory2.createUniqueName("e"); + const catchVariable = factory2.getGeneratedNameForNode(errorRecord); + const returnMethod = factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const values = setTextRange(emitHelpers().createValuesHelper(expression), node.expression); + const next = factory2.createCallExpression( + factory2.createPropertyAccessExpression(iterator, "next"), + /*typeArguments*/ + void 0, + [] + ); + hoistVariableDeclaration(errorRecord); + hoistVariableDeclaration(returnMethod); + const initializer = ancestorFacts & 1024 /* IterationContainer */ ? factory2.inlineExpressions([factory2.createAssignment(errorRecord, factory2.createVoidZero()), values]) : values; + const forStatement = setEmitFlags( + setTextRange( + factory2.createForStatement( + /*initializer*/ + setEmitFlags( + setTextRange( + factory2.createVariableDeclarationList([ + setTextRange(factory2.createVariableDeclaration( + iterator, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + initializer + ), node.expression), + factory2.createVariableDeclaration( + result, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + next + ) + ]), + node.expression + ), + 4194304 /* NoHoisting */ + ), + /*condition*/ + factory2.createLogicalNot(factory2.createPropertyAccessExpression(result, "done")), + /*incrementor*/ + factory2.createAssignment(result, next), + /*statement*/ + convertForOfStatementHead( + node, + factory2.createPropertyAccessExpression(result, "value"), + convertedLoopBodyStatements + ) + ), + /*location*/ + node + ), + 512 /* NoTokenTrailingSourceMaps */ + ); + return factory2.createTryStatement( + factory2.createBlock([ + factory2.restoreEnclosingLabel( + forStatement, + outermostLabeledStatement, + convertedLoopState && resetLabel + ) + ]), + factory2.createCatchClause( + factory2.createVariableDeclaration(catchVariable), + setEmitFlags( + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment( + errorRecord, + factory2.createObjectLiteralExpression([ + factory2.createPropertyAssignment("error", catchVariable) + ]) + ) + ) + ]), + 1 /* SingleLine */ + ) + ), + factory2.createBlock([ + factory2.createTryStatement( + /*tryBlock*/ + factory2.createBlock([ + setEmitFlags( + factory2.createIfStatement( + factory2.createLogicalAnd( + factory2.createLogicalAnd( + result, + factory2.createLogicalNot( + factory2.createPropertyAccessExpression(result, "done") + ) + ), + factory2.createAssignment( + returnMethod, + factory2.createPropertyAccessExpression(iterator, "return") + ) + ), + factory2.createExpressionStatement( + factory2.createFunctionCallCall(returnMethod, iterator, []) + ) + ), + 1 /* SingleLine */ + ) + ]), + /*catchClause*/ + void 0, + /*finallyBlock*/ + setEmitFlags( + factory2.createBlock([ + setEmitFlags( + factory2.createIfStatement( + errorRecord, + factory2.createThrowStatement( + factory2.createPropertyAccessExpression(errorRecord, "error") + ) + ), + 1 /* SingleLine */ + ) + ]), + 1 /* SingleLine */ + ) + ) + ]) + ); + } + function visitObjectLiteralExpression(node) { + const properties = node.properties; + let numInitialProperties = -1, hasComputed = false; + for (let i = 0; i < properties.length; i++) { + const property = properties[i]; + if (property.transformFlags & 1048576 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */ || (hasComputed = Debug.checkDefined(property.name).kind === 167 /* ComputedPropertyName */)) { + numInitialProperties = i; + break; + } + } + if (numInitialProperties < 0) { + return visitEachChild(node, visitor, context); + } + const temp = factory2.createTempVariable(hoistVariableDeclaration); + const expressions = []; + const assignment = factory2.createAssignment( + temp, + setEmitFlags( + factory2.createObjectLiteralExpression( + visitNodes2(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties), + node.multiLine + ), + hasComputed ? 131072 /* Indented */ : 0 + ) + ); + if (node.multiLine) { + startOnNewLine(assignment); + } + expressions.push(assignment); + addObjectLiteralMembers(expressions, node, temp, numInitialProperties); + expressions.push(node.multiLine ? startOnNewLine(setParent(setTextRange(factory2.cloneNode(temp), temp), temp.parent)) : temp); + return factory2.inlineExpressions(expressions); + } + function shouldConvertPartOfIterationStatement(node) { + return resolver.hasNodeCheckFlag(node, 8192 /* ContainsCapturedBlockScopeBinding */); + } + function shouldConvertInitializerOfForStatement(node) { + return isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { + return resolver.hasNodeCheckFlag(node, 4096 /* LoopWithCapturedBlockScopedBinding */); + } + function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(node.name); + function visit(node2) { + if (node2.kind === 80 /* Identifier */) { + state.hoistedLocalVariables.push(node2); + } else { + for (const element of node2.elements) { + if (!isOmittedExpression(element)) { + visit(element.name); + } + } + } + } + } + function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) { + if (!shouldConvertIterationStatement(node)) { + let saveAllowedNonLabeledJumps; + if (convertedLoopState) { + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + const result = convert ? convert( + node, + outermostLabeledStatement, + /*convertedLoopBodyStatements*/ + void 0, + ancestorFacts + ) : factory2.restoreEnclosingLabel( + isForStatement(node) ? visitEachChildOfForStatement2(node) : visitEachChild(node, visitor, context), + outermostLabeledStatement, + convertedLoopState && resetLabel + ); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + return result; + } + const currentState = createConvertedLoopState(node); + const statements = []; + const outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + const initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : void 0; + const bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : void 0; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + let loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); + } else { + const clone = convertIterationStatementCore(node, initializerFunction, factory2.createBlock( + bodyFunction.part, + /*multiLine*/ + true + )); + loop = factory2.restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } else { + const clone = convertIterationStatementCore(node, initializerFunction, Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock))); + loop = factory2.restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 248 /* ForStatement */: + return convertForStatement(node, initializerFunction, convertedLoopBody); + case 249 /* ForInStatement */: + return convertForInStatement(node, convertedLoopBody); + case 250 /* ForOfStatement */: + return convertForOfStatement(node, convertedLoopBody); + case 246 /* DoStatement */: + return convertDoStatement(node, convertedLoopBody); + case 247 /* WhileStatement */: + return convertWhileStatement(node, convertedLoopBody); + default: + return Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + const shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + const shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return factory2.updateForStatement( + node, + visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitorWithUnusedExpressionResult, isForInitializer), + visitNode(shouldConvertCondition ? void 0 : node.condition, visitor, isExpression), + visitNode(shouldConvertIncrementor ? void 0 : node.incrementor, visitorWithUnusedExpressionResult, isExpression), + convertedLoopBody + ); + } + function convertForOfStatement(node, convertedLoopBody) { + return factory2.updateForOfStatement( + node, + /*awaitModifier*/ + void 0, + Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + convertedLoopBody + ); + } + function convertForInStatement(node, convertedLoopBody) { + return factory2.updateForInStatement( + node, + Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + convertedLoopBody + ); + } + function convertDoStatement(node, convertedLoopBody) { + return factory2.updateDoStatement( + node, + convertedLoopBody, + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)) + ); + } + function convertWhileStatement(node, convertedLoopBody) { + return factory2.updateWhileStatement( + node, + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + convertedLoopBody + ); + } + function createConvertedLoopState(node) { + let loopInitializer; + switch (node.kind) { + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + const initializer = node.initializer; + if (initializer && initializer.kind === 261 /* VariableDeclarationList */) { + loopInitializer = initializer; + } + break; + } + const loopParameters = []; + const loopOutParameters = []; + if (loopInitializer && getCombinedNodeFlags(loopInitializer) & 7 /* BlockScoped */) { + const hasCapturedBindingsInForHead = shouldConvertInitializerOfForStatement(node) || shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node); + for (const decl of loopInitializer.declarations) { + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead); + } + } + const currentState = { loopParameters, loopOutParameters }; + if (convertedLoopState) { + if (convertedLoopState.argumentsName) { + currentState.argumentsName = convertedLoopState.argumentsName; + } + if (convertedLoopState.thisName) { + currentState.thisName = convertedLoopState.thisName; + } + if (convertedLoopState.hoistedLocalVariables) { + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + } + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { + let extraVariableDeclarations; + if (state.argumentsName) { + if (outerState) { + outerState.argumentsName = state.argumentsName; + } else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push( + factory2.createVariableDeclaration( + state.argumentsName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createIdentifier("arguments") + ) + ); + } + } + if (state.thisName) { + if (outerState) { + outerState.thisName = state.thisName; + } else { + (extraVariableDeclarations || (extraVariableDeclarations = [])).push( + factory2.createVariableDeclaration( + state.thisName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createIdentifier("this") + ) + ); + } + } + if (state.hoistedLocalVariables) { + if (outerState) { + outerState.hoistedLocalVariables = state.hoistedLocalVariables; + } else { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (const identifier of state.hoistedLocalVariables) { + extraVariableDeclarations.push(factory2.createVariableDeclaration(identifier)); + } + } + } + if (state.loopOutParameters.length) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + for (const outParam of state.loopOutParameters) { + extraVariableDeclarations.push(factory2.createVariableDeclaration(outParam.outParamName)); + } + } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(factory2.createVariableDeclaration( + state.conditionVariable, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createFalse() + )); + } + if (extraVariableDeclarations) { + statements.push(factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList(extraVariableDeclarations) + )); + } + } + function createOutVariable(p) { + return factory2.createVariableDeclaration( + p.originalName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + p.outParamName + ); + } + function createFunctionForInitializerOfForStatement(node, currentState) { + const functionName = factory2.createUniqueName("_loop_init"); + const containsYield = (node.initializer.transformFlags & 1048576 /* ContainsYield */) !== 0; + let emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) emitFlags |= 16 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) emitFlags |= 524288 /* AsyncFunctionBody */; + const statements = []; + statements.push(factory2.createVariableStatement( + /*modifiers*/ + void 0, + node.initializer + )); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + const functionDeclaration = factory2.createVariableStatement( + /*modifiers*/ + void 0, + setEmitFlags( + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + functionName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + setEmitFlags( + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + containsYield ? factory2.createToken(42 /* AsteriskToken */) : void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + /*parameters*/ + void 0, + /*type*/ + void 0, + Debug.checkDefined(visitNode( + factory2.createBlock( + statements, + /*multiLine*/ + true + ), + visitor, + isBlock + )) + ), + emitFlags + ) + ) + ]), + 4194304 /* NoHoisting */ + ) + ); + const part = factory2.createVariableDeclarationList(map(currentState.loopOutParameters, createOutVariable)); + return { functionName, containsYield, functionDeclaration, part }; + } + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + const functionName = factory2.createUniqueName("_loop"); + startLexicalEnvironment(); + const statement = visitNode(node.statement, visitor, isStatement, factory2.liftToBlock); + const lexicalEnvironment = endLexicalEnvironment(); + const statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + currentState.conditionVariable = factory2.createUniqueName("inc"); + if (node.incrementor) { + statements.push(factory2.createIfStatement( + currentState.conditionVariable, + factory2.createExpressionStatement(Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression))), + factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue())) + )); + } else { + statements.push(factory2.createIfStatement( + factory2.createLogicalNot(currentState.conditionVariable), + factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue())) + )); + } + if (shouldConvertConditionOfForStatement(node)) { + statements.push(factory2.createIfStatement( + factory2.createPrefixUnaryExpression(54 /* ExclamationToken */, Debug.checkDefined(visitNode(node.condition, visitor, isExpression))), + Debug.checkDefined(visitNode(factory2.createBreakStatement(), visitor, isStatement)) + )); + } + } + Debug.assert(statement); + if (isBlock(statement)) { + addRange(statements, statement.statements); + } else { + statements.push(statement); + } + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + insertStatementsAfterStandardPrologue(statements, lexicalEnvironment); + const loopBody = factory2.createBlock( + statements, + /*multiLine*/ + true + ); + if (isBlock(statement)) setOriginalNode(loopBody, statement); + const containsYield = (node.statement.transformFlags & 1048576 /* ContainsYield */) !== 0; + let emitFlags = 1048576 /* ReuseTempVariableScope */; + if (currentState.containsLexicalThis) emitFlags |= 16 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) emitFlags |= 524288 /* AsyncFunctionBody */; + const functionDeclaration = factory2.createVariableStatement( + /*modifiers*/ + void 0, + setEmitFlags( + factory2.createVariableDeclarationList( + [ + factory2.createVariableDeclaration( + functionName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + setEmitFlags( + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + containsYield ? factory2.createToken(42 /* AsteriskToken */) : void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + currentState.loopParameters, + /*type*/ + void 0, + loopBody + ), + emitFlags + ) + ) + ] + ), + 4194304 /* NoHoisting */ + ) + ); + const part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName, containsYield, functionDeclaration, part }; + } + function copyOutParameter(outParam, copyDirection) { + const source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; + const target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; + return factory2.createBinaryExpression(target, 64 /* EqualsToken */, source); + } + function copyOutParameters(outParams, partFlags, copyDirection, statements) { + for (const outParam of outParams) { + if (outParam.flags & partFlags) { + statements.push(factory2.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } + } + } + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + const call = factory2.createCallExpression( + initFunctionExpressionName, + /*typeArguments*/ + void 0, + [] + ); + const callResult = containsYield ? factory2.createYieldExpression( + factory2.createToken(42 /* AsteriskToken */), + setEmitFlags(call, 8388608 /* Iterator */) + ) : call; + return factory2.createExpressionStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { + const statements = []; + const isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; + const call = factory2.createCallExpression( + loopFunctionExpressionName, + /*typeArguments*/ + void 0, + map(state.loopParameters, (p) => p.name) + ); + const callResult = containsYield ? factory2.createYieldExpression( + factory2.createToken(42 /* AsteriskToken */), + setEmitFlags(call, 8388608 /* Iterator */) + ) : call; + if (isSimpleLoop) { + statements.push(factory2.createExpressionStatement(callResult)); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + } else { + const loopResultName = factory2.createUniqueName("state"); + const stateVariable = factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + [factory2.createVariableDeclaration( + loopResultName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + callResult + )] + ) + ); + statements.push(stateVariable); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); + if (state.nonLocalJumps & 8 /* Return */) { + let returnStatement; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; + returnStatement = factory2.createReturnStatement(loopResultName); + } else { + returnStatement = factory2.createReturnStatement(factory2.createPropertyAccessExpression(loopResultName, "value")); + } + statements.push( + factory2.createIfStatement( + factory2.createTypeCheck(loopResultName, "object"), + returnStatement + ) + ); + } + if (state.nonLocalJumps & 2 /* Break */) { + statements.push( + factory2.createIfStatement( + factory2.createStrictEquality( + loopResultName, + factory2.createStringLiteral("break") + ), + factory2.createBreakStatement() + ) + ); + } + if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { + const caseClauses = []; + processLabeledJumps( + state.labeledNonLocalBreaks, + /*isBreak*/ + true, + loopResultName, + outerState, + caseClauses + ); + processLabeledJumps( + state.labeledNonLocalContinues, + /*isBreak*/ + false, + loopResultName, + outerState, + caseClauses + ); + statements.push( + factory2.createSwitchStatement( + loopResultName, + factory2.createCaseBlock(caseClauses) + ) + ); + } + } + return statements; + } + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = /* @__PURE__ */ new Map(); + } + state.labeledNonLocalBreaks.set(labelText, labelMarker); + } else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = /* @__PURE__ */ new Map(); + } + state.labeledNonLocalContinues.set(labelText, labelMarker); + } + } + function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) { + if (!table) { + return; + } + table.forEach((labelMarker, labelText) => { + const statements = []; + if (!outerLoop || outerLoop.labels && outerLoop.labels.get(labelText)) { + const label = factory2.createIdentifier(labelText); + statements.push(isBreak ? factory2.createBreakStatement(label) : factory2.createContinueStatement(label)); + } else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + statements.push(factory2.createReturnStatement(loopResultName)); + } + caseClauses.push(factory2.createCaseClause(factory2.createStringLiteral(labelMarker), statements)); + }); + } + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead) { + const name = decl.name; + if (isBindingPattern(name)) { + for (const element of name.elements) { + if (!isOmittedExpression(element)) { + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForHead); + } + } + } else { + loopParameters.push(factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + name + )); + const needsOutParam = resolver.hasNodeCheckFlag(decl, 65536 /* NeedsLoopOutParameter */); + if (needsOutParam || hasCapturedBindingsInForHead) { + const outParamName = factory2.createUniqueName("out_" + idText(name)); + let flags = 0 /* None */; + if (needsOutParam) { + flags |= 1 /* Body */; + } + if (isForStatement(container)) { + if (container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + if (container.condition && resolver.isBindingCapturedByNode(container.condition, decl) || container.incrementor && resolver.isBindingCapturedByNode(container.incrementor, decl)) { + flags |= 1 /* Body */; + } + } + loopOutParameters.push({ flags, originalName: name, outParamName }); + } + } + } + function addObjectLiteralMembers(expressions, node, receiver, start) { + const properties = node.properties; + const numProperties = properties.length; + for (let i = start; i < numProperties; i++) { + const property = properties[i]; + switch (property.kind) { + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + const accessors = getAllAccessorDeclarations(node.properties, property); + if (property === accessors.firstAccessor) { + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); + } + break; + case 174 /* MethodDeclaration */: + expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); + break; + case 303 /* PropertyAssignment */: + expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + case 304 /* ShorthandPropertyAssignment */: + expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); + break; + default: + Debug.failBadSyntaxKind(node); + break; + } + } + } + function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + const expression = factory2.createAssignment( + createMemberAccessForPropertyName( + factory2, + receiver, + Debug.checkDefined(visitNode(property.name, visitor, isPropertyName)) + ), + Debug.checkDefined(visitNode(property.initializer, visitor, isExpression)) + ); + setTextRange(expression, property); + if (startsOnNewLine) { + startOnNewLine(expression); + } + return expression; + } + function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { + const expression = factory2.createAssignment( + createMemberAccessForPropertyName( + factory2, + receiver, + Debug.checkDefined(visitNode(property.name, visitor, isPropertyName)) + ), + factory2.cloneNode(property.name) + ); + setTextRange(expression, property); + if (startsOnNewLine) { + startOnNewLine(expression); + } + return expression; + } + function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { + const expression = factory2.createAssignment( + createMemberAccessForPropertyName( + factory2, + receiver, + Debug.checkDefined(visitNode(method.name, visitor, isPropertyName)) + ), + transformFunctionLikeToExpression( + method, + /*location*/ + method, + /*name*/ + void 0, + container + ) + ); + setTextRange(expression, method); + if (startsOnNewLine) { + startOnNewLine(expression); + } + return expression; + } + function visitCatchClause(node) { + const ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */); + let updated; + Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); + if (isBindingPattern(node.variableDeclaration.name)) { + const temp = factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + const newVariableDeclaration = factory2.createVariableDeclaration(temp); + setTextRange(newVariableDeclaration, node.variableDeclaration); + const vars = flattenDestructuringBinding( + node.variableDeclaration, + visitor, + context, + 0 /* All */, + temp + ); + const list = factory2.createVariableDeclarationList(vars); + setTextRange(list, node.variableDeclaration); + const destructure = factory2.createVariableStatement( + /*modifiers*/ + void 0, + list + ); + updated = factory2.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); + } else { + updated = visitEachChild(node, visitor, context); + } + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return updated; + } + function addStatementToStartOfBlock(block, statement) { + const transformedStatements = visitNodes2(block.statements, visitor, isStatement); + return factory2.updateBlock(block, [statement, ...transformedStatements]); + } + function visitMethodDeclaration(node) { + Debug.assert(!isComputedPropertyName(node.name)); + const functionExpression = transformFunctionLikeToExpression( + node, + /*location*/ + moveRangePos(node, -1), + /*name*/ + void 0, + /*container*/ + void 0 + ); + setEmitFlags(functionExpression, 1024 /* NoLeadingComments */ | getEmitFlags(functionExpression)); + return setTextRange( + factory2.createPropertyAssignment( + node.name, + functionExpression + ), + /*location*/ + node + ); + } + function visitAccessorDeclaration(node) { + Debug.assert(!isComputedPropertyName(node.name)); + const savedConvertedLoopState = convertedLoopState; + convertedLoopState = void 0; + const ancestorFacts = enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */); + let updated; + const parameters = visitParameterList(node.parameters, visitor, context); + const body = transformFunctionBody(node); + if (node.kind === 177 /* GetAccessor */) { + updated = factory2.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); + } else { + updated = factory2.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); + } + exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); + convertedLoopState = savedConvertedLoopState; + return updated; + } + function visitShorthandPropertyAssignment(node) { + return setTextRange( + factory2.createPropertyAssignment( + node.name, + visitIdentifier(factory2.cloneNode(node.name)) + ), + /*location*/ + node + ); + } + function visitComputedPropertyName(node) { + return visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + return visitEachChild(node, visitor, context); + } + function visitArrayLiteralExpression(node) { + if (some(node.elements, isSpreadElement)) { + return transformAndSpreadElements( + node.elements, + /*isArgumentList*/ + false, + !!node.multiLine, + /*hasTrailingComma*/ + !!node.elements.hasTrailingComma + ); + } + return visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (getInternalEmitFlags(node) & 1 /* TypeScriptClassWrapper */) { + return visitTypeScriptClassWrapper(node); + } + const expression = skipOuterExpressions(node.expression); + if (expression.kind === 108 /* SuperKeyword */ || isSuperProperty(expression) || some(node.arguments, isSpreadElement)) { + return visitCallExpressionWithPotentialCapturedThisAssignment( + node, + /*assignToCapturedThis*/ + true + ); + } + return factory2.updateCallExpression( + node, + Debug.checkDefined(visitNode(node.expression, callExpressionVisitor, isExpression)), + /*typeArguments*/ + void 0, + visitNodes2(node.arguments, visitor, isExpression) + ); + } + function visitTypeScriptClassWrapper(node) { + const body = cast(cast(skipOuterExpressions(node.expression), isArrowFunction).body, isBlock); + const isVariableStatementWithInitializer = (stmt) => isVariableStatement(stmt) && !!first(stmt.declarationList.declarations).initializer; + const savedConvertedLoopState = convertedLoopState; + convertedLoopState = void 0; + const bodyStatements = visitNodes2(body.statements, classWrapperStatementVisitor, isStatement); + convertedLoopState = savedConvertedLoopState; + const classStatements = filter(bodyStatements, isVariableStatementWithInitializer); + const remainingStatements = filter(bodyStatements, (stmt) => !isVariableStatementWithInitializer(stmt)); + const varStatement = cast(first(classStatements), isVariableStatement); + const variable = varStatement.declarationList.declarations[0]; + const initializer = skipOuterExpressions(variable.initializer); + let aliasAssignment = tryCast(initializer, isAssignmentExpression); + if (!aliasAssignment && isBinaryExpression(initializer) && initializer.operatorToken.kind === 28 /* CommaToken */) { + aliasAssignment = tryCast(initializer.left, isAssignmentExpression); + } + const call = cast(aliasAssignment ? skipOuterExpressions(aliasAssignment.right) : initializer, isCallExpression); + const func = cast(skipOuterExpressions(call.expression), isFunctionExpression); + const funcStatements = func.body.statements; + let classBodyStart = 0; + let classBodyEnd = -1; + const statements = []; + if (aliasAssignment) { + const extendsCall = tryCast(funcStatements[classBodyStart], isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + statements.push( + factory2.createExpressionStatement( + factory2.createAssignment( + aliasAssignment.left, + cast(variable.name, isIdentifier) + ) + ) + ); + } + while (!isReturnStatement(elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + addRange(statements, funcStatements, classBodyEnd + 1); + } + const returnStatement = tryCast(elementAt(funcStatements, classBodyEnd), isReturnStatement); + for (const statement of remainingStatements) { + if (isReturnStatement(statement) && (returnStatement == null ? void 0 : returnStatement.expression) && !isIdentifier(returnStatement.expression)) { + statements.push(returnStatement); + } else { + statements.push(statement); + } + } + addRange( + statements, + classStatements, + /*start*/ + 1 + ); + return factory2.restoreOuterExpressions( + node.expression, + factory2.restoreOuterExpressions( + variable.initializer, + factory2.restoreOuterExpressions( + aliasAssignment && aliasAssignment.right, + factory2.updateCallExpression( + call, + factory2.restoreOuterExpressions( + call.expression, + factory2.updateFunctionExpression( + func, + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + func.parameters, + /*type*/ + void 0, + factory2.updateBlock( + func.body, + statements + ) + ) + ), + /*typeArguments*/ + void 0, + call.arguments + ) + ) + ) + ); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { + if (node.transformFlags & 32768 /* ContainsRestOrSpread */ || node.expression.kind === 108 /* SuperKeyword */ || isSuperProperty(skipOuterExpressions(node.expression))) { + const { target, thisArg } = factory2.createCallBinding(node.expression, hoistVariableDeclaration); + if (node.expression.kind === 108 /* SuperKeyword */) { + setEmitFlags(thisArg, 8 /* NoSubstitution */); + } + let resultingCall; + if (node.transformFlags & 32768 /* ContainsRestOrSpread */) { + resultingCall = factory2.createFunctionApplyCall( + Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), + node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), + transformAndSpreadElements( + node.arguments, + /*isArgumentList*/ + true, + /*multiLine*/ + false, + /*hasTrailingComma*/ + false + ) + ); + } else { + resultingCall = setTextRange( + factory2.createFunctionCallCall( + Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), + node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), + visitNodes2(node.arguments, visitor, isExpression) + ), + node + ); + } + if (node.expression.kind === 108 /* SuperKeyword */) { + const initializer = factory2.createLogicalOr( + resultingCall, + createActualThis() + ); + resultingCall = assignToCapturedThis ? factory2.createAssignment(createCapturedThis(), initializer) : initializer; + } + return setOriginalNode(resultingCall, node); + } + if (isSuperCall(node)) { + hierarchyFacts |= 131072 /* CapturedLexicalThis */; + } + return visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (some(node.arguments, isSpreadElement)) { + const { target, thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); + return factory2.createNewExpression( + factory2.createFunctionApplyCall( + Debug.checkDefined(visitNode(target, visitor, isExpression)), + thisArg, + transformAndSpreadElements( + factory2.createNodeArray([factory2.createVoidZero(), ...node.arguments]), + /*isArgumentList*/ + true, + /*multiLine*/ + false, + /*hasTrailingComma*/ + false + ) + ), + /*typeArguments*/ + void 0, + [] + ); + } + return visitEachChild(node, visitor, context); + } + function transformAndSpreadElements(elements, isArgumentList, multiLine, hasTrailingComma) { + const numElements = elements.length; + const segments = flatten( + // As we visit each element, we return one of two functions to use as the "key": + // - `visitSpanOfSpreads` for one or more contiguous `...` spread expressions, i.e. `...a, ...b` in `[1, 2, ...a, ...b]` + // - `visitSpanOfNonSpreads` for one or more contiguous non-spread elements, i.e. `1, 2`, in `[1, 2, ...a, ...b]` + spanMap(elements, partitionSpread, (partition, visitPartition, _start, end) => visitPartition(partition, multiLine, hasTrailingComma && end === numElements)) + ); + if (segments.length === 1) { + const firstSegment = segments[0]; + if (isArgumentList && !compilerOptions.downlevelIteration || isPackedArrayLiteral(firstSegment.expression) || isCallToHelper(firstSegment.expression, "___spreadArray")) { + return firstSegment.expression; + } + } + const helpers = emitHelpers(); + const startsWithSpread = segments[0].kind !== 0 /* None */; + let expression = startsWithSpread ? factory2.createArrayLiteralExpression() : segments[0].expression; + for (let i = startsWithSpread ? 0 : 1; i < segments.length; i++) { + const segment = segments[i]; + expression = helpers.createSpreadArrayHelper( + expression, + segment.expression, + segment.kind === 1 /* UnpackedSpread */ && !isArgumentList + ); + } + return expression; + } + function partitionSpread(node) { + return isSpreadElement(node) ? visitSpanOfSpreads : visitSpanOfNonSpreads; + } + function visitSpanOfSpreads(chunk) { + return map(chunk, visitExpressionOfSpread); + } + function visitExpressionOfSpread(node) { + Debug.assertNode(node, isSpreadElement); + let expression = visitNode(node.expression, visitor, isExpression); + Debug.assert(expression); + const isCallToReadHelper = isCallToHelper(expression, "___read"); + let kind = isCallToReadHelper || isPackedArrayLiteral(expression) ? 2 /* PackedSpread */ : 1 /* UnpackedSpread */; + if (compilerOptions.downlevelIteration && kind === 1 /* UnpackedSpread */ && !isArrayLiteralExpression(expression) && !isCallToReadHelper) { + expression = emitHelpers().createReadHelper( + expression, + /*count*/ + void 0 + ); + kind = 2 /* PackedSpread */; + } + return createSpreadSegment(kind, expression); + } + function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { + const expression = factory2.createArrayLiteralExpression( + visitNodes2(factory2.createNodeArray(chunk, hasTrailingComma), visitor, isExpression), + multiLine + ); + return createSpreadSegment(0 /* None */, expression); + } + function visitSpreadElement(node) { + return visitNode(node.expression, visitor, isExpression); + } + function visitTemplateLiteral(node) { + return setTextRange(factory2.createStringLiteral(node.text), node); + } + function visitStringLiteral(node) { + if (node.hasExtendedUnicodeEscape) { + return setTextRange(factory2.createStringLiteral(node.text), node); + } + return node; + } + function visitNumericLiteral(node) { + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + return setTextRange(factory2.createNumericLiteral(node.text), node); + } + return node; + } + function visitTaggedTemplateExpression(node) { + return processTaggedTemplateExpression( + context, + node, + visitor, + currentSourceFile, + recordTaggedTemplateString, + 1 /* All */ + ); + } + function visitTemplateExpression(node) { + let expression = factory2.createStringLiteral(node.head.text); + for (const span of node.templateSpans) { + const args = [Debug.checkDefined(visitNode(span.expression, visitor, isExpression))]; + if (span.literal.text.length > 0) { + args.push(factory2.createStringLiteral(span.literal.text)); + } + expression = factory2.createCallExpression( + factory2.createPropertyAccessExpression(expression, "concat"), + /*typeArguments*/ + void 0, + args + ); + } + return setTextRange(expression, node); + } + function createSyntheticSuper() { + return factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */); + } + function visitSuperKeyword(node, isExpressionOfCall) { + const expression = hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? factory2.createPropertyAccessExpression(setOriginalNode(createSyntheticSuper(), node), "prototype") : createSyntheticSuper(); + setOriginalNode(expression, node); + setCommentRange(expression, node); + setSourceMapRange(expression, node); + return expression; + } + function visitMetaProperty(node) { + if (node.keywordToken === 105 /* NewKeyword */ && node.name.escapedText === "target") { + hierarchyFacts |= 32768 /* NewTarget */; + return factory2.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */); + } + return node; + } + function onEmitNode(hint, node, emitCallback) { + if (enabledSubstitutions & 1 /* CapturedThis */ && isFunctionLike(node)) { + const ancestorFacts = enterSubtree( + 32670 /* FunctionExcludes */, + getEmitFlags(node) & 16 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */ + ); + previousOnEmitNode(hint, node, emitCallback); + exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + return; + } + previousOnEmitNode(hint, node, emitCallback); + } + function enableSubstitutionsForBlockScopedBindings() { + if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { + enabledSubstitutions |= 2 /* BlockScopedBindings */; + context.enableSubstitution(80 /* Identifier */); + } + } + function enableSubstitutionsForCapturedThis() { + if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { + enabledSubstitutions |= 1 /* CapturedThis */; + context.enableSubstitution(110 /* ThisKeyword */); + context.enableEmitNotification(176 /* Constructor */); + context.enableEmitNotification(174 /* MethodDeclaration */); + context.enableEmitNotification(177 /* GetAccessor */); + context.enableEmitNotification(178 /* SetAccessor */); + context.enableEmitNotification(219 /* ArrowFunction */); + context.enableEmitNotification(218 /* FunctionExpression */); + context.enableEmitNotification(262 /* FunctionDeclaration */); + } + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + if (isIdentifier(node)) { + return substituteIdentifier(node); + } + return node; + } + function substituteIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !isInternalName(node)) { + const original = getParseTreeNode(node, isIdentifier); + if (original && isNameOfDeclarationWithCollidingName(original)) { + return setTextRange(factory2.getGeneratedNameForNode(original), node); + } + } + return node; + } + function isNameOfDeclarationWithCollidingName(node) { + switch (node.parent.kind) { + case 208 /* BindingElement */: + case 263 /* ClassDeclaration */: + case 266 /* EnumDeclaration */: + case 260 /* VariableDeclaration */: + return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); + } + return false; + } + function substituteExpression(node) { + switch (node.kind) { + case 80 /* Identifier */: + return substituteExpressionIdentifier(node); + case 110 /* ThisKeyword */: + return substituteThisKeyword(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !isInternalName(node)) { + const declaration = resolver.getReferencedDeclarationWithCollidingName(node); + if (declaration && !(isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return setTextRange(factory2.getGeneratedNameForNode(getNameOfDeclaration(declaration)), node); + } + } + return node; + } + function isPartOfClassBody(declaration, node) { + let currentNode = getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + return false; + } + const blockScope = getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + return false; + } + if (isClassElement(currentNode) && currentNode.parent === declaration) { + return true; + } + currentNode = currentNode.parent; + } + return false; + } + function substituteThisKeyword(node) { + if (enabledSubstitutions & 1 /* CapturedThis */ && hierarchyFacts & 16 /* CapturesThis */) { + return setTextRange(createCapturedThis(), node); + } + return node; + } + function getClassMemberPrefix(node, member) { + return isStatic(member) ? factory2.getInternalName(node) : factory2.createPropertyAccessExpression(factory2.getInternalName(node), "prototype"); + } + function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { + if (!constructor || !hasExtendsClause) { + return false; + } + if (some(constructor.parameters)) { + return false; + } + const statement = firstOrUndefined(constructor.body.statements); + if (!statement || !nodeIsSynthesized(statement) || statement.kind !== 244 /* ExpressionStatement */) { + return false; + } + const statementExpression = statement.expression; + if (!nodeIsSynthesized(statementExpression) || statementExpression.kind !== 213 /* CallExpression */) { + return false; + } + const callTarget = statementExpression.expression; + if (!nodeIsSynthesized(callTarget) || callTarget.kind !== 108 /* SuperKeyword */) { + return false; + } + const callArgument = singleOrUndefined(statementExpression.arguments); + if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== 230 /* SpreadElement */) { + return false; + } + const expression = callArgument.expression; + return isIdentifier(expression) && expression.escapedText === "arguments"; + } +} + +// src/compiler/transformers/generators.ts +function getInstructionName(instruction) { + switch (instruction) { + case 2 /* Return */: + return "return"; + case 3 /* Break */: + return "break"; + case 4 /* Yield */: + return "yield"; + case 5 /* YieldStar */: + return "yield*"; + case 7 /* Endfinally */: + return "endfinally"; + default: + return void 0; + } +} +function transformGenerators(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + resumeLexicalEnvironment, + endLexicalEnvironment, + hoistFunctionDeclaration, + hoistVariableDeclaration + } = context; + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + const resolver = context.getEmitResolver(); + const previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + let renamedCatchVariables; + let renamedCatchVariableDeclarations; + let inGeneratorFunctionBody; + let inStatementContainingYield; + let blocks; + let blockOffsets; + let blockActions; + let blockStack; + let labelOffsets; + let labelExpressions; + let nextLabelId = 1; + let operations; + let operationArguments; + let operationLocations; + let state; + let blockIndex = 0; + let labelNumber = 0; + let labelNumbers; + let lastOperationWasAbrupt; + let lastOperationWasCompletion; + let clauses; + let statements; + let exceptionBlockStack; + let currentExceptionBlock; + let withBlockStack; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || (node.transformFlags & 2048 /* ContainsGenerator */) === 0) { + return node; + } + const visited = visitEachChild(node, visitor, context); + addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function visitor(node) { + const transformFlags = node.transformFlags; + if (inStatementContainingYield) { + return visitJavaScriptInStatementContainingYield(node); + } else if (inGeneratorFunctionBody) { + return visitJavaScriptInGeneratorFunctionBody(node); + } else if (isFunctionLikeDeclaration(node) && node.asteriskToken) { + return visitGenerator(node); + } else if (transformFlags & 2048 /* ContainsGenerator */) { + return visitEachChild(node, visitor, context); + } else { + return node; + } + } + function visitJavaScriptInStatementContainingYield(node) { + switch (node.kind) { + case 246 /* DoStatement */: + return visitDoStatement(node); + case 247 /* WhileStatement */: + return visitWhileStatement(node); + case 255 /* SwitchStatement */: + return visitSwitchStatement(node); + case 256 /* LabeledStatement */: + return visitLabeledStatement(node); + default: + return visitJavaScriptInGeneratorFunctionBody(node); + } + } + function visitJavaScriptInGeneratorFunctionBody(node) { + switch (node.kind) { + case 262 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 218 /* FunctionExpression */: + return visitFunctionExpression(node); + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return visitAccessorDeclaration(node); + case 243 /* VariableStatement */: + return visitVariableStatement(node); + case 248 /* ForStatement */: + return visitForStatement(node); + case 249 /* ForInStatement */: + return visitForInStatement(node); + case 252 /* BreakStatement */: + return visitBreakStatement(node); + case 251 /* ContinueStatement */: + return visitContinueStatement(node); + case 253 /* ReturnStatement */: + return visitReturnStatement(node); + default: + if (node.transformFlags & 1048576 /* ContainsYield */) { + return visitJavaScriptContainingYield(node); + } else if (node.transformFlags & (2048 /* ContainsGenerator */ | 4194304 /* ContainsHoistedDeclarationOrCompletion */)) { + return visitEachChild(node, visitor, context); + } else { + return node; + } + } + } + function visitJavaScriptContainingYield(node) { + switch (node.kind) { + case 226 /* BinaryExpression */: + return visitBinaryExpression(node); + case 356 /* CommaListExpression */: + return visitCommaListExpression(node); + case 227 /* ConditionalExpression */: + return visitConditionalExpression(node); + case 229 /* YieldExpression */: + return visitYieldExpression(node); + case 209 /* ArrayLiteralExpression */: + return visitArrayLiteralExpression(node); + case 210 /* ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 212 /* ElementAccessExpression */: + return visitElementAccessExpression(node); + case 213 /* CallExpression */: + return visitCallExpression(node); + case 214 /* NewExpression */: + return visitNewExpression(node); + default: + return visitEachChild(node, visitor, context); + } + } + function visitGenerator(node) { + switch (node.kind) { + case 262 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 218 /* FunctionExpression */: + return visitFunctionExpression(node); + default: + return Debug.failBadSyntaxKind(node); + } + } + function visitFunctionDeclaration(node) { + if (node.asteriskToken) { + node = setOriginalNode( + setTextRange( + factory2.createFunctionDeclaration( + node.modifiers, + /*asteriskToken*/ + void 0, + node.name, + /*typeParameters*/ + void 0, + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + transformGeneratorFunctionBody(node.body) + ), + /*location*/ + node + ), + node + ); + } else { + const savedInGeneratorFunctionBody = inGeneratorFunctionBody; + const savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + if (inGeneratorFunctionBody) { + hoistFunctionDeclaration(node); + return void 0; + } else { + return node; + } + } + function visitFunctionExpression(node) { + if (node.asteriskToken) { + node = setOriginalNode( + setTextRange( + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + node.name, + /*typeParameters*/ + void 0, + visitParameterList(node.parameters, visitor, context), + /*type*/ + void 0, + transformGeneratorFunctionBody(node.body) + ), + /*location*/ + node + ), + node + ); + } else { + const savedInGeneratorFunctionBody = inGeneratorFunctionBody; + const savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + } + return node; + } + function visitAccessorDeclaration(node) { + const savedInGeneratorFunctionBody = inGeneratorFunctionBody; + const savedInStatementContainingYield = inStatementContainingYield; + inGeneratorFunctionBody = false; + inStatementContainingYield = false; + node = visitEachChild(node, visitor, context); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + return node; + } + function transformGeneratorFunctionBody(body) { + const statements2 = []; + const savedInGeneratorFunctionBody = inGeneratorFunctionBody; + const savedInStatementContainingYield = inStatementContainingYield; + const savedBlocks = blocks; + const savedBlockOffsets = blockOffsets; + const savedBlockActions = blockActions; + const savedBlockStack = blockStack; + const savedLabelOffsets = labelOffsets; + const savedLabelExpressions = labelExpressions; + const savedNextLabelId = nextLabelId; + const savedOperations = operations; + const savedOperationArguments = operationArguments; + const savedOperationLocations = operationLocations; + const savedState = state; + inGeneratorFunctionBody = true; + inStatementContainingYield = false; + blocks = void 0; + blockOffsets = void 0; + blockActions = void 0; + blockStack = void 0; + labelOffsets = void 0; + labelExpressions = void 0; + nextLabelId = 1; + operations = void 0; + operationArguments = void 0; + operationLocations = void 0; + state = factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + resumeLexicalEnvironment(); + const statementOffset = factory2.copyPrologue( + body.statements, + statements2, + /*ensureUseStrict*/ + false, + visitor + ); + transformAndEmitStatements(body.statements, statementOffset); + const buildResult = build2(); + insertStatementsAfterStandardPrologue(statements2, endLexicalEnvironment()); + statements2.push(factory2.createReturnStatement(buildResult)); + inGeneratorFunctionBody = savedInGeneratorFunctionBody; + inStatementContainingYield = savedInStatementContainingYield; + blocks = savedBlocks; + blockOffsets = savedBlockOffsets; + blockActions = savedBlockActions; + blockStack = savedBlockStack; + labelOffsets = savedLabelOffsets; + labelExpressions = savedLabelExpressions; + nextLabelId = savedNextLabelId; + operations = savedOperations; + operationArguments = savedOperationArguments; + operationLocations = savedOperationLocations; + state = savedState; + return setTextRange(factory2.createBlock(statements2, body.multiLine), body); + } + function visitVariableStatement(node) { + if (node.transformFlags & 1048576 /* ContainsYield */) { + transformAndEmitVariableDeclarationList(node.declarationList); + return void 0; + } else { + if (getEmitFlags(node) & 2097152 /* CustomPrologue */) { + return node; + } + for (const variable of node.declarationList.declarations) { + hoistVariableDeclaration(variable.name); + } + const variables = getInitializedVariables(node.declarationList); + if (variables.length === 0) { + return void 0; + } + return setSourceMapRange( + factory2.createExpressionStatement( + factory2.inlineExpressions( + map(variables, transformInitializedVariable) + ) + ), + node + ); + } + } + function visitBinaryExpression(node) { + const assoc = getExpressionAssociativity(node); + switch (assoc) { + case 0 /* Left */: + return visitLeftAssociativeBinaryExpression(node); + case 1 /* Right */: + return visitRightAssociativeBinaryExpression(node); + default: + return Debug.assertNever(assoc); + } + } + function visitRightAssociativeBinaryExpression(node) { + const { left, right } = node; + if (containsYield(right)) { + let target; + switch (left.kind) { + case 211 /* PropertyAccessExpression */: + target = factory2.updatePropertyAccessExpression( + left, + cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))), + left.name + ); + break; + case 212 /* ElementAccessExpression */: + target = factory2.updateElementAccessExpression(left, cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))), cacheExpression(Debug.checkDefined(visitNode(left.argumentExpression, visitor, isExpression)))); + break; + default: + target = Debug.checkDefined(visitNode(left, visitor, isExpression)); + break; + } + const operator = node.operatorToken.kind; + if (isCompoundAssignment(operator)) { + return setTextRange( + factory2.createAssignment( + target, + setTextRange( + factory2.createBinaryExpression( + cacheExpression(target), + getNonAssignmentOperatorForCompoundAssignment(operator), + Debug.checkDefined(visitNode(right, visitor, isExpression)) + ), + node + ) + ), + node + ); + } else { + return factory2.updateBinaryExpression(node, target, node.operatorToken, Debug.checkDefined(visitNode(right, visitor, isExpression))); + } + } + return visitEachChild(node, visitor, context); + } + function visitLeftAssociativeBinaryExpression(node) { + if (containsYield(node.right)) { + if (isLogicalOperator(node.operatorToken.kind)) { + return visitLogicalBinaryExpression(node); + } else if (node.operatorToken.kind === 28 /* CommaToken */) { + return visitCommaExpression(node); + } + return factory2.updateBinaryExpression(node, cacheExpression(Debug.checkDefined(visitNode(node.left, visitor, isExpression))), node.operatorToken, Debug.checkDefined(visitNode(node.right, visitor, isExpression))); + } + return visitEachChild(node, visitor, context); + } + function visitCommaExpression(node) { + let pendingExpressions = []; + visit(node.left); + visit(node.right); + return factory2.inlineExpressions(pendingExpressions); + function visit(node2) { + if (isBinaryExpression(node2) && node2.operatorToken.kind === 28 /* CommaToken */) { + visit(node2.left); + visit(node2.right); + } else { + if (containsYield(node2) && pendingExpressions.length > 0) { + emitWorker(1 /* Statement */, [factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(Debug.checkDefined(visitNode(node2, visitor, isExpression))); + } + } + } + function visitCommaListExpression(node) { + let pendingExpressions = []; + for (const elem of node.elements) { + if (isBinaryExpression(elem) && elem.operatorToken.kind === 28 /* CommaToken */) { + pendingExpressions.push(visitCommaExpression(elem)); + } else { + if (containsYield(elem) && pendingExpressions.length > 0) { + emitWorker(1 /* Statement */, [factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions))]); + pendingExpressions = []; + } + pendingExpressions.push(Debug.checkDefined(visitNode(elem, visitor, isExpression))); + } + } + return factory2.inlineExpressions(pendingExpressions); + } + function visitLogicalBinaryExpression(node) { + const resultLabel = defineLabel(); + const resultLocal = declareLocal(); + emitAssignment( + resultLocal, + Debug.checkDefined(visitNode(node.left, visitor, isExpression)), + /*location*/ + node.left + ); + if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { + emitBreakWhenFalse( + resultLabel, + resultLocal, + /*location*/ + node.left + ); + } else { + emitBreakWhenTrue( + resultLabel, + resultLocal, + /*location*/ + node.left + ); + } + emitAssignment( + resultLocal, + Debug.checkDefined(visitNode(node.right, visitor, isExpression)), + /*location*/ + node.right + ); + markLabel(resultLabel); + return resultLocal; + } + function visitConditionalExpression(node) { + if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) { + const whenFalseLabel = defineLabel(); + const resultLabel = defineLabel(); + const resultLocal = declareLocal(); + emitBreakWhenFalse( + whenFalseLabel, + Debug.checkDefined(visitNode(node.condition, visitor, isExpression)), + /*location*/ + node.condition + ); + emitAssignment( + resultLocal, + Debug.checkDefined(visitNode(node.whenTrue, visitor, isExpression)), + /*location*/ + node.whenTrue + ); + emitBreak(resultLabel); + markLabel(whenFalseLabel); + emitAssignment( + resultLocal, + Debug.checkDefined(visitNode(node.whenFalse, visitor, isExpression)), + /*location*/ + node.whenFalse + ); + markLabel(resultLabel); + return resultLocal; + } + return visitEachChild(node, visitor, context); + } + function visitYieldExpression(node) { + const resumeLabel = defineLabel(); + const expression = visitNode(node.expression, visitor, isExpression); + if (node.asteriskToken) { + const iterator = (getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; + emitYieldStar( + iterator, + /*location*/ + node + ); + } else { + emitYield( + expression, + /*location*/ + node + ); + } + markLabel(resumeLabel); + return createGeneratorResume( + /*location*/ + node + ); + } + function visitArrayLiteralExpression(node) { + return visitElements( + node.elements, + /*leadingElement*/ + void 0, + /*location*/ + void 0, + node.multiLine + ); + } + function visitElements(elements, leadingElement, location, multiLine) { + const numInitialElements = countInitialNodesWithoutYield(elements); + let temp; + if (numInitialElements > 0) { + temp = declareLocal(); + const initialElements = visitNodes2(elements, visitor, isExpression, 0, numInitialElements); + emitAssignment( + temp, + factory2.createArrayLiteralExpression( + leadingElement ? [leadingElement, ...initialElements] : initialElements + ) + ); + leadingElement = void 0; + } + const expressions = reduceLeft(elements, reduceElement, [], numInitialElements); + return temp ? factory2.createArrayConcatCall(temp, [factory2.createArrayLiteralExpression(expressions, multiLine)]) : setTextRange( + factory2.createArrayLiteralExpression(leadingElement ? [leadingElement, ...expressions] : expressions, multiLine), + location + ); + function reduceElement(expressions2, element) { + if (containsYield(element) && expressions2.length > 0) { + const hasAssignedTemp = temp !== void 0; + if (!temp) { + temp = declareLocal(); + } + emitAssignment( + temp, + hasAssignedTemp ? factory2.createArrayConcatCall( + temp, + [factory2.createArrayLiteralExpression(expressions2, multiLine)] + ) : factory2.createArrayLiteralExpression( + leadingElement ? [leadingElement, ...expressions2] : expressions2, + multiLine + ) + ); + leadingElement = void 0; + expressions2 = []; + } + expressions2.push(Debug.checkDefined(visitNode(element, visitor, isExpression))); + return expressions2; + } + } + function visitObjectLiteralExpression(node) { + const properties = node.properties; + const multiLine = node.multiLine; + const numInitialProperties = countInitialNodesWithoutYield(properties); + const temp = declareLocal(); + emitAssignment( + temp, + factory2.createObjectLiteralExpression( + visitNodes2(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties), + multiLine + ) + ); + const expressions = reduceLeft(properties, reduceProperty, [], numInitialProperties); + expressions.push(multiLine ? startOnNewLine(setParent(setTextRange(factory2.cloneNode(temp), temp), temp.parent)) : temp); + return factory2.inlineExpressions(expressions); + function reduceProperty(expressions2, property) { + if (containsYield(property) && expressions2.length > 0) { + emitStatement(factory2.createExpressionStatement(factory2.inlineExpressions(expressions2))); + expressions2 = []; + } + const expression = createExpressionForObjectLiteralElementLike(factory2, node, property, temp); + const visited = visitNode(expression, visitor, isExpression); + if (visited) { + if (multiLine) { + startOnNewLine(visited); + } + expressions2.push(visited); + } + return expressions2; + } + } + function visitElementAccessExpression(node) { + if (containsYield(node.argumentExpression)) { + return factory2.updateElementAccessExpression(node, cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression))), Debug.checkDefined(visitNode(node.argumentExpression, visitor, isExpression))); + } + return visitEachChild(node, visitor, context); + } + function visitCallExpression(node) { + if (!isImportCall(node) && forEach(node.arguments, containsYield)) { + const { target, thisArg } = factory2.createCallBinding( + node.expression, + hoistVariableDeclaration, + languageVersion, + /*cacheIdentifiers*/ + true + ); + return setOriginalNode( + setTextRange( + factory2.createFunctionApplyCall( + cacheExpression(Debug.checkDefined(visitNode(target, visitor, isLeftHandSideExpression))), + thisArg, + visitElements(node.arguments) + ), + node + ), + node + ); + } + return visitEachChild(node, visitor, context); + } + function visitNewExpression(node) { + if (forEach(node.arguments, containsYield)) { + const { target, thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); + return setOriginalNode( + setTextRange( + factory2.createNewExpression( + factory2.createFunctionApplyCall( + cacheExpression(Debug.checkDefined(visitNode(target, visitor, isExpression))), + thisArg, + visitElements( + node.arguments, + /*leadingElement*/ + factory2.createVoidZero() + ) + ), + /*typeArguments*/ + void 0, + [] + ), + node + ), + node + ); + } + return visitEachChild(node, visitor, context); + } + function transformAndEmitStatements(statements2, start = 0) { + const numStatements = statements2.length; + for (let i = start; i < numStatements; i++) { + transformAndEmitStatement(statements2[i]); + } + } + function transformAndEmitEmbeddedStatement(node) { + if (isBlock(node)) { + transformAndEmitStatements(node.statements); + } else { + transformAndEmitStatement(node); + } + } + function transformAndEmitStatement(node) { + const savedInStatementContainingYield = inStatementContainingYield; + if (!inStatementContainingYield) { + inStatementContainingYield = containsYield(node); + } + transformAndEmitStatementWorker(node); + inStatementContainingYield = savedInStatementContainingYield; + } + function transformAndEmitStatementWorker(node) { + switch (node.kind) { + case 241 /* Block */: + return transformAndEmitBlock(node); + case 244 /* ExpressionStatement */: + return transformAndEmitExpressionStatement(node); + case 245 /* IfStatement */: + return transformAndEmitIfStatement(node); + case 246 /* DoStatement */: + return transformAndEmitDoStatement(node); + case 247 /* WhileStatement */: + return transformAndEmitWhileStatement(node); + case 248 /* ForStatement */: + return transformAndEmitForStatement(node); + case 249 /* ForInStatement */: + return transformAndEmitForInStatement(node); + case 251 /* ContinueStatement */: + return transformAndEmitContinueStatement(node); + case 252 /* BreakStatement */: + return transformAndEmitBreakStatement(node); + case 253 /* ReturnStatement */: + return transformAndEmitReturnStatement(node); + case 254 /* WithStatement */: + return transformAndEmitWithStatement(node); + case 255 /* SwitchStatement */: + return transformAndEmitSwitchStatement(node); + case 256 /* LabeledStatement */: + return transformAndEmitLabeledStatement(node); + case 257 /* ThrowStatement */: + return transformAndEmitThrowStatement(node); + case 258 /* TryStatement */: + return transformAndEmitTryStatement(node); + default: + return emitStatement(visitNode(node, visitor, isStatement)); + } + } + function transformAndEmitBlock(node) { + if (containsYield(node)) { + transformAndEmitStatements(node.statements); + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } + function transformAndEmitExpressionStatement(node) { + emitStatement(visitNode(node, visitor, isStatement)); + } + function transformAndEmitVariableDeclarationList(node) { + for (const variable of node.declarations) { + const name = factory2.cloneNode(variable.name); + setCommentRange(name, variable.name); + hoistVariableDeclaration(name); + } + const variables = getInitializedVariables(node); + const numVariables = variables.length; + let variablesWritten = 0; + let pendingExpressions = []; + while (variablesWritten < numVariables) { + for (let i = variablesWritten; i < numVariables; i++) { + const variable = variables[i]; + if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + break; + } + pendingExpressions.push(transformInitializedVariable(variable)); + } + if (pendingExpressions.length) { + emitStatement(factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions))); + variablesWritten += pendingExpressions.length; + pendingExpressions = []; + } + } + return void 0; + } + function transformInitializedVariable(node) { + return setSourceMapRange( + factory2.createAssignment( + setSourceMapRange(factory2.cloneNode(node.name), node.name), + Debug.checkDefined(visitNode(node.initializer, visitor, isExpression)) + ), + node + ); + } + function transformAndEmitIfStatement(node) { + if (containsYield(node)) { + if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + const endLabel = defineLabel(); + const elseLabel = node.elseStatement ? defineLabel() : void 0; + emitBreakWhenFalse( + node.elseStatement ? elseLabel : endLabel, + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + /*location*/ + node.expression + ); + transformAndEmitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + emitBreak(endLabel); + markLabel(elseLabel); + transformAndEmitEmbeddedStatement(node.elseStatement); + } + markLabel(endLabel); + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } + function transformAndEmitDoStatement(node) { + if (containsYield(node)) { + const conditionLabel = defineLabel(); + const loopLabel = defineLabel(); + beginLoopBlock( + /*continueLabel*/ + conditionLabel + ); + markLabel(loopLabel); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(conditionLabel); + emitBreakWhenTrue(loopLabel, Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + endLoopBlock(); + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } + function visitDoStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } else { + return visitEachChild(node, visitor, context); + } + } + function transformAndEmitWhileStatement(node) { + if (containsYield(node)) { + const loopLabel = defineLabel(); + const endLabel = beginLoopBlock(loopLabel); + markLabel(loopLabel); + emitBreakWhenFalse(endLabel, Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + transformAndEmitEmbeddedStatement(node.statement); + emitBreak(loopLabel); + endLoopBlock(); + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } + function visitWhileStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + node = visitEachChild(node, visitor, context); + endLoopBlock(); + return node; + } else { + return visitEachChild(node, visitor, context); + } + } + function transformAndEmitForStatement(node) { + if (containsYield(node)) { + const conditionLabel = defineLabel(); + const incrementLabel = defineLabel(); + const endLabel = beginLoopBlock(incrementLabel); + if (node.initializer) { + const initializer = node.initializer; + if (isVariableDeclarationList(initializer)) { + transformAndEmitVariableDeclarationList(initializer); + } else { + emitStatement( + setTextRange( + factory2.createExpressionStatement( + Debug.checkDefined(visitNode(initializer, visitor, isExpression)) + ), + initializer + ) + ); + } + } + markLabel(conditionLabel); + if (node.condition) { + emitBreakWhenFalse(endLabel, Debug.checkDefined(visitNode(node.condition, visitor, isExpression))); + } + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + if (node.incrementor) { + emitStatement( + setTextRange( + factory2.createExpressionStatement( + Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression)) + ), + node.incrementor + ) + ); + } + emitBreak(conditionLabel); + endLoopBlock(); + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } + function visitForStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + const initializer = node.initializer; + if (initializer && isVariableDeclarationList(initializer)) { + for (const variable of initializer.declarations) { + hoistVariableDeclaration(variable.name); + } + const variables = getInitializedVariables(initializer); + node = factory2.updateForStatement( + node, + variables.length > 0 ? factory2.inlineExpressions(map(variables, transformInitializedVariable)) : void 0, + visitNode(node.condition, visitor, isExpression), + visitNode(node.incrementor, visitor, isExpression), + visitIterationBody(node.statement, visitor, context) + ); + } else { + node = visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitForInStatement(node) { + if (containsYield(node)) { + const obj = declareLocal(); + const keysArray = declareLocal(); + const key = declareLocal(); + const keysIndex = factory2.createLoopVariable(); + const initializer = node.initializer; + hoistVariableDeclaration(keysIndex); + emitAssignment(obj, Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + emitAssignment(keysArray, factory2.createArrayLiteralExpression()); + emitStatement( + factory2.createForInStatement( + key, + obj, + factory2.createExpressionStatement( + factory2.createCallExpression( + factory2.createPropertyAccessExpression(keysArray, "push"), + /*typeArguments*/ + void 0, + [key] + ) + ) + ) + ); + emitAssignment(keysIndex, factory2.createNumericLiteral(0)); + const conditionLabel = defineLabel(); + const incrementLabel = defineLabel(); + const endLoopLabel = beginLoopBlock(incrementLabel); + markLabel(conditionLabel); + emitBreakWhenFalse(endLoopLabel, factory2.createLessThan(keysIndex, factory2.createPropertyAccessExpression(keysArray, "length"))); + emitAssignment(key, factory2.createElementAccessExpression(keysArray, keysIndex)); + emitBreakWhenFalse(incrementLabel, factory2.createBinaryExpression(key, 103 /* InKeyword */, obj)); + let variable; + if (isVariableDeclarationList(initializer)) { + for (const variable2 of initializer.declarations) { + hoistVariableDeclaration(variable2.name); + } + variable = factory2.cloneNode(initializer.declarations[0].name); + } else { + variable = Debug.checkDefined(visitNode(initializer, visitor, isExpression)); + Debug.assert(isLeftHandSideExpression(variable)); + } + emitAssignment(variable, key); + transformAndEmitEmbeddedStatement(node.statement); + markLabel(incrementLabel); + emitStatement(factory2.createExpressionStatement(factory2.createPostfixIncrement(keysIndex))); + emitBreak(conditionLabel); + endLoopBlock(); + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } + function visitForInStatement(node) { + if (inStatementContainingYield) { + beginScriptLoopBlock(); + } + const initializer = node.initializer; + if (isVariableDeclarationList(initializer)) { + for (const variable of initializer.declarations) { + hoistVariableDeclaration(variable.name); + } + node = factory2.updateForInStatement(node, initializer.declarations[0].name, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock))); + } else { + node = visitEachChild(node, visitor, context); + } + if (inStatementContainingYield) { + endLoopBlock(); + } + return node; + } + function transformAndEmitContinueStatement(node) { + const label = findContinueTarget(node.label ? idText(node.label) : void 0); + if (label > 0) { + emitBreak( + label, + /*location*/ + node + ); + } else { + emitStatement(node); + } + } + function visitContinueStatement(node) { + if (inStatementContainingYield) { + const label = findContinueTarget(node.label && idText(node.label)); + if (label > 0) { + return createInlineBreak( + label, + /*location*/ + node + ); + } + } + return visitEachChild(node, visitor, context); + } + function transformAndEmitBreakStatement(node) { + const label = findBreakTarget(node.label ? idText(node.label) : void 0); + if (label > 0) { + emitBreak( + label, + /*location*/ + node + ); + } else { + emitStatement(node); + } + } + function visitBreakStatement(node) { + if (inStatementContainingYield) { + const label = findBreakTarget(node.label && idText(node.label)); + if (label > 0) { + return createInlineBreak( + label, + /*location*/ + node + ); + } + } + return visitEachChild(node, visitor, context); + } + function transformAndEmitReturnStatement(node) { + emitReturn( + visitNode(node.expression, visitor, isExpression), + /*location*/ + node + ); + } + function visitReturnStatement(node) { + return createInlineReturn( + visitNode(node.expression, visitor, isExpression), + /*location*/ + node + ); + } + function transformAndEmitWithStatement(node) { + if (containsYield(node)) { + beginWithBlock(cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isExpression)))); + transformAndEmitEmbeddedStatement(node.statement); + endWithBlock(); + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } + function transformAndEmitSwitchStatement(node) { + if (containsYield(node.caseBlock)) { + const caseBlock = node.caseBlock; + const numClauses = caseBlock.clauses.length; + const endLabel = beginSwitchBlock(); + const expression = cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + const clauseLabels = []; + let defaultClauseIndex = -1; + for (let i = 0; i < numClauses; i++) { + const clause = caseBlock.clauses[i]; + clauseLabels.push(defineLabel()); + if (clause.kind === 297 /* DefaultClause */ && defaultClauseIndex === -1) { + defaultClauseIndex = i; + } + } + let clausesWritten = 0; + let pendingClauses = []; + while (clausesWritten < numClauses) { + let defaultClausesSkipped = 0; + for (let i = clausesWritten; i < numClauses; i++) { + const clause = caseBlock.clauses[i]; + if (clause.kind === 296 /* CaseClause */) { + if (containsYield(clause.expression) && pendingClauses.length > 0) { + break; + } + pendingClauses.push( + factory2.createCaseClause( + Debug.checkDefined(visitNode(clause.expression, visitor, isExpression)), + [ + createInlineBreak( + clauseLabels[i], + /*location*/ + clause.expression + ) + ] + ) + ); + } else { + defaultClausesSkipped++; + } + } + if (pendingClauses.length) { + emitStatement(factory2.createSwitchStatement(expression, factory2.createCaseBlock(pendingClauses))); + clausesWritten += pendingClauses.length; + pendingClauses = []; + } + if (defaultClausesSkipped > 0) { + clausesWritten += defaultClausesSkipped; + defaultClausesSkipped = 0; + } + } + if (defaultClauseIndex >= 0) { + emitBreak(clauseLabels[defaultClauseIndex]); + } else { + emitBreak(endLabel); + } + for (let i = 0; i < numClauses; i++) { + markLabel(clauseLabels[i]); + transformAndEmitStatements(caseBlock.clauses[i].statements); + } + endSwitchBlock(); + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } + function visitSwitchStatement(node) { + if (inStatementContainingYield) { + beginScriptSwitchBlock(); + } + node = visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endSwitchBlock(); + } + return node; + } + function transformAndEmitLabeledStatement(node) { + if (containsYield(node)) { + beginLabeledBlock(idText(node.label)); + transformAndEmitEmbeddedStatement(node.statement); + endLabeledBlock(); + } else { + emitStatement(visitNode(node, visitor, isStatement)); + } + } + function visitLabeledStatement(node) { + if (inStatementContainingYield) { + beginScriptLabeledBlock(idText(node.label)); + } + node = visitEachChild(node, visitor, context); + if (inStatementContainingYield) { + endLabeledBlock(); + } + return node; + } + function transformAndEmitThrowStatement(node) { + emitThrow( + Debug.checkDefined(visitNode(node.expression ?? factory2.createVoidZero(), visitor, isExpression)), + /*location*/ + node + ); + } + function transformAndEmitTryStatement(node) { + if (containsYield(node)) { + beginExceptionBlock(); + transformAndEmitEmbeddedStatement(node.tryBlock); + if (node.catchClause) { + beginCatchBlock(node.catchClause.variableDeclaration); + transformAndEmitEmbeddedStatement(node.catchClause.block); + } + if (node.finallyBlock) { + beginFinallyBlock(); + transformAndEmitEmbeddedStatement(node.finallyBlock); + } + endExceptionBlock(); + } else { + emitStatement(visitEachChild(node, visitor, context)); + } + } + function containsYield(node) { + return !!node && (node.transformFlags & 1048576 /* ContainsYield */) !== 0; + } + function countInitialNodesWithoutYield(nodes) { + const numNodes = nodes.length; + for (let i = 0; i < numNodes; i++) { + if (containsYield(nodes[i])) { + return i; + } + } + return -1; + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + if (isIdentifier(node)) { + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + if (!isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(idText(node))) { + const original = getOriginalNode(node); + if (isIdentifier(original) && original.parent) { + const declaration = resolver.getReferencedValueDeclaration(original); + if (declaration) { + const name = renamedCatchVariableDeclarations[getOriginalNodeId(declaration)]; + if (name) { + const clone = setParent(setTextRange(factory2.cloneNode(name), name), name.parent); + setSourceMapRange(clone, node); + setCommentRange(clone, node); + return clone; + } + } + } + } + return node; + } + function cacheExpression(node) { + if (isGeneratedIdentifier(node) || getEmitFlags(node) & 8192 /* HelperName */) { + return node; + } + const temp = factory2.createTempVariable(hoistVariableDeclaration); + emitAssignment( + temp, + node, + /*location*/ + node + ); + return temp; + } + function declareLocal(name) { + const temp = name ? factory2.createUniqueName(name) : factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + ); + hoistVariableDeclaration(temp); + return temp; + } + function defineLabel() { + if (!labelOffsets) { + labelOffsets = []; + } + const label = nextLabelId; + nextLabelId++; + labelOffsets[label] = -1; + return label; + } + function markLabel(label) { + Debug.assert(labelOffsets !== void 0, "No labels were defined."); + labelOffsets[label] = operations ? operations.length : 0; + } + function beginBlock(block) { + if (!blocks) { + blocks = []; + blockActions = []; + blockOffsets = []; + blockStack = []; + } + const index = blockActions.length; + blockActions[index] = 0 /* Open */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.push(block); + return index; + } + function endBlock() { + const block = peekBlock(); + if (block === void 0) return Debug.fail("beginBlock was never called."); + const index = blockActions.length; + blockActions[index] = 1 /* Close */; + blockOffsets[index] = operations ? operations.length : 0; + blocks[index] = block; + blockStack.pop(); + return block; + } + function peekBlock() { + return lastOrUndefined(blockStack); + } + function peekBlockKind() { + const block = peekBlock(); + return block && block.kind; + } + function beginWithBlock(expression) { + const startLabel = defineLabel(); + const endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 1 /* With */, + expression, + startLabel, + endLabel + }); + } + function endWithBlock() { + Debug.assert(peekBlockKind() === 1 /* With */); + const block = endBlock(); + markLabel(block.endLabel); + } + function beginExceptionBlock() { + const startLabel = defineLabel(); + const endLabel = defineLabel(); + markLabel(startLabel); + beginBlock({ + kind: 0 /* Exception */, + state: 0 /* Try */, + startLabel, + endLabel + }); + emitNop(); + return endLabel; + } + function beginCatchBlock(variable) { + Debug.assert(peekBlockKind() === 0 /* Exception */); + let name; + if (isGeneratedIdentifier(variable.name)) { + name = variable.name; + hoistVariableDeclaration(variable.name); + } else { + const text = idText(variable.name); + name = declareLocal(text); + if (!renamedCatchVariables) { + renamedCatchVariables = /* @__PURE__ */ new Map(); + renamedCatchVariableDeclarations = []; + context.enableSubstitution(80 /* Identifier */); + } + renamedCatchVariables.set(text, true); + renamedCatchVariableDeclarations[getOriginalNodeId(variable)] = name; + } + const exception = peekBlock(); + Debug.assert(exception.state < 1 /* Catch */); + const endLabel = exception.endLabel; + emitBreak(endLabel); + const catchLabel = defineLabel(); + markLabel(catchLabel); + exception.state = 1 /* Catch */; + exception.catchVariable = name; + exception.catchLabel = catchLabel; + emitAssignment(name, factory2.createCallExpression( + factory2.createPropertyAccessExpression(state, "sent"), + /*typeArguments*/ + void 0, + [] + )); + emitNop(); + } + function beginFinallyBlock() { + Debug.assert(peekBlockKind() === 0 /* Exception */); + const exception = peekBlock(); + Debug.assert(exception.state < 2 /* Finally */); + const endLabel = exception.endLabel; + emitBreak(endLabel); + const finallyLabel = defineLabel(); + markLabel(finallyLabel); + exception.state = 2 /* Finally */; + exception.finallyLabel = finallyLabel; + } + function endExceptionBlock() { + Debug.assert(peekBlockKind() === 0 /* Exception */); + const exception = endBlock(); + const state2 = exception.state; + if (state2 < 2 /* Finally */) { + emitBreak(exception.endLabel); + } else { + emitEndfinally(); + } + markLabel(exception.endLabel); + emitNop(); + exception.state = 3 /* Done */; + } + function beginScriptLoopBlock() { + beginBlock({ + kind: 3 /* Loop */, + isScript: true, + breakLabel: -1, + continueLabel: -1 + }); + } + function beginLoopBlock(continueLabel) { + const breakLabel = defineLabel(); + beginBlock({ + kind: 3 /* Loop */, + isScript: false, + breakLabel, + continueLabel + }); + return breakLabel; + } + function endLoopBlock() { + Debug.assert(peekBlockKind() === 3 /* Loop */); + const block = endBlock(); + const breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptSwitchBlock() { + beginBlock({ + kind: 2 /* Switch */, + isScript: true, + breakLabel: -1 + }); + } + function beginSwitchBlock() { + const breakLabel = defineLabel(); + beginBlock({ + kind: 2 /* Switch */, + isScript: false, + breakLabel + }); + return breakLabel; + } + function endSwitchBlock() { + Debug.assert(peekBlockKind() === 2 /* Switch */); + const block = endBlock(); + const breakLabel = block.breakLabel; + if (!block.isScript) { + markLabel(breakLabel); + } + } + function beginScriptLabeledBlock(labelText) { + beginBlock({ + kind: 4 /* Labeled */, + isScript: true, + labelText, + breakLabel: -1 + }); + } + function beginLabeledBlock(labelText) { + const breakLabel = defineLabel(); + beginBlock({ + kind: 4 /* Labeled */, + isScript: false, + labelText, + breakLabel + }); + } + function endLabeledBlock() { + Debug.assert(peekBlockKind() === 4 /* Labeled */); + const block = endBlock(); + if (!block.isScript) { + markLabel(block.breakLabel); + } + } + function supportsUnlabeledBreak(block) { + return block.kind === 2 /* Switch */ || block.kind === 3 /* Loop */; + } + function supportsLabeledBreakOrContinue(block) { + return block.kind === 4 /* Labeled */; + } + function supportsUnlabeledContinue(block) { + return block.kind === 3 /* Loop */; + } + function hasImmediateContainingLabeledBlock(labelText, start) { + for (let j = start; j >= 0; j--) { + const containingBlock = blockStack[j]; + if (supportsLabeledBreakOrContinue(containingBlock)) { + if (containingBlock.labelText === labelText) { + return true; + } + } else { + break; + } + } + return false; + } + function findBreakTarget(labelText) { + if (blockStack) { + if (labelText) { + for (let i = blockStack.length - 1; i >= 0; i--) { + const block = blockStack[i]; + if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + return block.breakLabel; + } else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.breakLabel; + } + } + } else { + for (let i = blockStack.length - 1; i >= 0; i--) { + const block = blockStack[i]; + if (supportsUnlabeledBreak(block)) { + return block.breakLabel; + } + } + } + } + return 0; + } + function findContinueTarget(labelText) { + if (blockStack) { + if (labelText) { + for (let i = blockStack.length - 1; i >= 0; i--) { + const block = blockStack[i]; + if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + return block.continueLabel; + } + } + } else { + for (let i = blockStack.length - 1; i >= 0; i--) { + const block = blockStack[i]; + if (supportsUnlabeledContinue(block)) { + return block.continueLabel; + } + } + } + } + return 0; + } + function createLabel(label) { + if (label !== void 0 && label > 0) { + if (labelExpressions === void 0) { + labelExpressions = []; + } + const expression = factory2.createNumericLiteral(Number.MAX_SAFE_INTEGER); + if (labelExpressions[label] === void 0) { + labelExpressions[label] = [expression]; + } else { + labelExpressions[label].push(expression); + } + return expression; + } + return factory2.createOmittedExpression(); + } + function createInstruction(instruction) { + const literal = factory2.createNumericLiteral(instruction); + addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction)); + return literal; + } + function createInlineBreak(label, location) { + Debug.assertLessThan(0, label, "Invalid label"); + return setTextRange( + factory2.createReturnStatement( + factory2.createArrayLiteralExpression([ + createInstruction(3 /* Break */), + createLabel(label) + ]) + ), + location + ); + } + function createInlineReturn(expression, location) { + return setTextRange( + factory2.createReturnStatement( + factory2.createArrayLiteralExpression( + expression ? [createInstruction(2 /* Return */), expression] : [createInstruction(2 /* Return */)] + ) + ), + location + ); + } + function createGeneratorResume(location) { + return setTextRange( + factory2.createCallExpression( + factory2.createPropertyAccessExpression(state, "sent"), + /*typeArguments*/ + void 0, + [] + ), + location + ); + } + function emitNop() { + emitWorker(0 /* Nop */); + } + function emitStatement(node) { + if (node) { + emitWorker(1 /* Statement */, [node]); + } else { + emitNop(); + } + } + function emitAssignment(left, right, location) { + emitWorker(2 /* Assign */, [left, right], location); + } + function emitBreak(label, location) { + emitWorker(3 /* Break */, [label], location); + } + function emitBreakWhenTrue(label, condition, location) { + emitWorker(4 /* BreakWhenTrue */, [label, condition], location); + } + function emitBreakWhenFalse(label, condition, location) { + emitWorker(5 /* BreakWhenFalse */, [label, condition], location); + } + function emitYieldStar(expression, location) { + emitWorker(7 /* YieldStar */, [expression], location); + } + function emitYield(expression, location) { + emitWorker(6 /* Yield */, [expression], location); + } + function emitReturn(expression, location) { + emitWorker(8 /* Return */, [expression], location); + } + function emitThrow(expression, location) { + emitWorker(9 /* Throw */, [expression], location); + } + function emitEndfinally() { + emitWorker(10 /* Endfinally */); + } + function emitWorker(code, args, location) { + if (operations === void 0) { + operations = []; + operationArguments = []; + operationLocations = []; + } + if (labelOffsets === void 0) { + markLabel(defineLabel()); + } + const operationIndex = operations.length; + operations[operationIndex] = code; + operationArguments[operationIndex] = args; + operationLocations[operationIndex] = location; + } + function build2() { + blockIndex = 0; + labelNumber = 0; + labelNumbers = void 0; + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + clauses = void 0; + statements = void 0; + exceptionBlockStack = void 0; + currentExceptionBlock = void 0; + withBlockStack = void 0; + const buildResult = buildStatements(); + return emitHelpers().createGeneratorHelper( + setEmitFlags( + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + state + )], + /*type*/ + void 0, + factory2.createBlock( + buildResult, + /*multiLine*/ + buildResult.length > 0 + ) + ), + 1048576 /* ReuseTempVariableScope */ + ) + ); + } + function buildStatements() { + if (operations) { + for (let operationIndex = 0; operationIndex < operations.length; operationIndex++) { + writeOperation(operationIndex); + } + flushFinalLabel(operations.length); + } else { + flushFinalLabel(0); + } + if (clauses) { + const labelExpression = factory2.createPropertyAccessExpression(state, "label"); + const switchStatement = factory2.createSwitchStatement(labelExpression, factory2.createCaseBlock(clauses)); + return [startOnNewLine(switchStatement)]; + } + if (statements) { + return statements; + } + return []; + } + function flushLabel() { + if (!statements) { + return; + } + appendLabel( + /*markLabelEnd*/ + !lastOperationWasAbrupt + ); + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + labelNumber++; + } + function flushFinalLabel(operationIndex) { + if (isFinalLabelReachable(operationIndex)) { + tryEnterLabel(operationIndex); + withBlockStack = void 0; + writeReturn( + /*expression*/ + void 0, + /*operationLocation*/ + void 0 + ); + } + if (statements && clauses) { + appendLabel( + /*markLabelEnd*/ + false + ); + } + updateLabelExpressions(); + } + function isFinalLabelReachable(operationIndex) { + if (!lastOperationWasCompletion) { + return true; + } + if (!labelOffsets || !labelExpressions) { + return false; + } + for (let label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + return true; + } + } + return false; + } + function appendLabel(markLabelEnd) { + if (!clauses) { + clauses = []; + } + if (statements) { + if (withBlockStack) { + for (let i = withBlockStack.length - 1; i >= 0; i--) { + const withBlock = withBlockStack[i]; + statements = [factory2.createWithStatement(withBlock.expression, factory2.createBlock(statements))]; + } + } + if (currentExceptionBlock) { + const { startLabel, catchLabel, finallyLabel, endLabel } = currentExceptionBlock; + statements.unshift( + factory2.createExpressionStatement( + factory2.createCallExpression( + factory2.createPropertyAccessExpression(factory2.createPropertyAccessExpression(state, "trys"), "push"), + /*typeArguments*/ + void 0, + [ + factory2.createArrayLiteralExpression([ + createLabel(startLabel), + createLabel(catchLabel), + createLabel(finallyLabel), + createLabel(endLabel) + ]) + ] + ) + ) + ); + currentExceptionBlock = void 0; + } + if (markLabelEnd) { + statements.push( + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createPropertyAccessExpression(state, "label"), + factory2.createNumericLiteral(labelNumber + 1) + ) + ) + ); + } + } + clauses.push( + factory2.createCaseClause( + factory2.createNumericLiteral(labelNumber), + statements || [] + ) + ); + statements = void 0; + } + function tryEnterLabel(operationIndex) { + if (!labelOffsets) { + return; + } + for (let label = 0; label < labelOffsets.length; label++) { + if (labelOffsets[label] === operationIndex) { + flushLabel(); + if (labelNumbers === void 0) { + labelNumbers = []; + } + if (labelNumbers[labelNumber] === void 0) { + labelNumbers[labelNumber] = [label]; + } else { + labelNumbers[labelNumber].push(label); + } + } + } + } + function updateLabelExpressions() { + if (labelExpressions !== void 0 && labelNumbers !== void 0) { + for (let labelNumber2 = 0; labelNumber2 < labelNumbers.length; labelNumber2++) { + const labels = labelNumbers[labelNumber2]; + if (labels !== void 0) { + for (const label of labels) { + const expressions = labelExpressions[label]; + if (expressions !== void 0) { + for (const expression of expressions) { + expression.text = String(labelNumber2); + } + } + } + } + } + } + } + function tryEnterOrLeaveBlock(operationIndex) { + if (blocks) { + for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) { + const block = blocks[blockIndex]; + const blockAction = blockActions[blockIndex]; + switch (block.kind) { + case 0 /* Exception */: + if (blockAction === 0 /* Open */) { + if (!exceptionBlockStack) { + exceptionBlockStack = []; + } + if (!statements) { + statements = []; + } + exceptionBlockStack.push(currentExceptionBlock); + currentExceptionBlock = block; + } else if (blockAction === 1 /* Close */) { + currentExceptionBlock = exceptionBlockStack.pop(); + } + break; + case 1 /* With */: + if (blockAction === 0 /* Open */) { + if (!withBlockStack) { + withBlockStack = []; + } + withBlockStack.push(block); + } else if (blockAction === 1 /* Close */) { + withBlockStack.pop(); + } + break; + } + } + } + } + function writeOperation(operationIndex) { + tryEnterLabel(operationIndex); + tryEnterOrLeaveBlock(operationIndex); + if (lastOperationWasAbrupt) { + return; + } + lastOperationWasAbrupt = false; + lastOperationWasCompletion = false; + const opcode = operations[operationIndex]; + if (opcode === 0 /* Nop */) { + return; + } else if (opcode === 10 /* Endfinally */) { + return writeEndfinally(); + } + const args = operationArguments[operationIndex]; + if (opcode === 1 /* Statement */) { + return writeStatement(args[0]); + } + const location = operationLocations[operationIndex]; + switch (opcode) { + case 2 /* Assign */: + return writeAssign(args[0], args[1], location); + case 3 /* Break */: + return writeBreak(args[0], location); + case 4 /* BreakWhenTrue */: + return writeBreakWhenTrue(args[0], args[1], location); + case 5 /* BreakWhenFalse */: + return writeBreakWhenFalse(args[0], args[1], location); + case 6 /* Yield */: + return writeYield(args[0], location); + case 7 /* YieldStar */: + return writeYieldStar(args[0], location); + case 8 /* Return */: + return writeReturn(args[0], location); + case 9 /* Throw */: + return writeThrow(args[0], location); + } + } + function writeStatement(statement) { + if (statement) { + if (!statements) { + statements = [statement]; + } else { + statements.push(statement); + } + } + } + function writeAssign(left, right, operationLocation) { + writeStatement(setTextRange(factory2.createExpressionStatement(factory2.createAssignment(left, right)), operationLocation)); + } + function writeThrow(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement(setTextRange(factory2.createThrowStatement(expression), operationLocation)); + } + function writeReturn(expression, operationLocation) { + lastOperationWasAbrupt = true; + lastOperationWasCompletion = true; + writeStatement( + setEmitFlags( + setTextRange( + factory2.createReturnStatement( + factory2.createArrayLiteralExpression( + expression ? [createInstruction(2 /* Return */), expression] : [createInstruction(2 /* Return */)] + ) + ), + operationLocation + ), + 768 /* NoTokenSourceMaps */ + ) + ); + } + function writeBreak(label, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement( + setEmitFlags( + setTextRange( + factory2.createReturnStatement( + factory2.createArrayLiteralExpression([ + createInstruction(3 /* Break */), + createLabel(label) + ]) + ), + operationLocation + ), + 768 /* NoTokenSourceMaps */ + ) + ); + } + function writeBreakWhenTrue(label, condition, operationLocation) { + writeStatement( + setEmitFlags( + factory2.createIfStatement( + condition, + setEmitFlags( + setTextRange( + factory2.createReturnStatement( + factory2.createArrayLiteralExpression([ + createInstruction(3 /* Break */), + createLabel(label) + ]) + ), + operationLocation + ), + 768 /* NoTokenSourceMaps */ + ) + ), + 1 /* SingleLine */ + ) + ); + } + function writeBreakWhenFalse(label, condition, operationLocation) { + writeStatement( + setEmitFlags( + factory2.createIfStatement( + factory2.createLogicalNot(condition), + setEmitFlags( + setTextRange( + factory2.createReturnStatement( + factory2.createArrayLiteralExpression([ + createInstruction(3 /* Break */), + createLabel(label) + ]) + ), + operationLocation + ), + 768 /* NoTokenSourceMaps */ + ) + ), + 1 /* SingleLine */ + ) + ); + } + function writeYield(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement( + setEmitFlags( + setTextRange( + factory2.createReturnStatement( + factory2.createArrayLiteralExpression( + expression ? [createInstruction(4 /* Yield */), expression] : [createInstruction(4 /* Yield */)] + ) + ), + operationLocation + ), + 768 /* NoTokenSourceMaps */ + ) + ); + } + function writeYieldStar(expression, operationLocation) { + lastOperationWasAbrupt = true; + writeStatement( + setEmitFlags( + setTextRange( + factory2.createReturnStatement( + factory2.createArrayLiteralExpression([ + createInstruction(5 /* YieldStar */), + expression + ]) + ), + operationLocation + ), + 768 /* NoTokenSourceMaps */ + ) + ); + } + function writeEndfinally() { + lastOperationWasAbrupt = true; + writeStatement( + factory2.createReturnStatement( + factory2.createArrayLiteralExpression([ + createInstruction(7 /* Endfinally */) + ]) + ) + ); + } +} + +// src/compiler/transformers/module/module.ts +function transformModule(context) { + function getTransformModuleDelegate(moduleKind2) { + switch (moduleKind2) { + case 2 /* AMD */: + return transformAMDModule; + case 3 /* UMD */: + return transformUMDModule; + default: + return transformCommonJSModule; + } + } + const { + factory: factory2, + getEmitHelperFactory: emitHelpers, + startLexicalEnvironment, + endLexicalEnvironment, + hoistVariableDeclaration + } = context; + const compilerOptions = context.getCompilerOptions(); + const resolver = context.getEmitResolver(); + const host = context.getEmitHost(); + const languageVersion = getEmitScriptTarget(compilerOptions); + const moduleKind = getEmitModuleKind(compilerOptions); + const previousOnSubstituteNode = context.onSubstituteNode; + const previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(213 /* CallExpression */); + context.enableSubstitution(215 /* TaggedTemplateExpression */); + context.enableSubstitution(80 /* Identifier */); + context.enableSubstitution(226 /* BinaryExpression */); + context.enableSubstitution(304 /* ShorthandPropertyAssignment */); + context.enableEmitNotification(307 /* SourceFile */); + const moduleInfoMap = []; + let currentSourceFile; + let currentModuleInfo; + let importsAndRequiresToRewriteOrShim; + const noSubstitution = []; + let needUMDDynamicImportHelper; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* ContainsDynamicImport */ || isJsonSourceFile(node) && hasJsonModuleEmitEnabled(compilerOptions) && compilerOptions.outFile)) { + return node; + } + currentSourceFile = node; + currentModuleInfo = collectExternalModuleInfo(context, node); + moduleInfoMap[getOriginalNodeId(node)] = currentModuleInfo; + if (compilerOptions.rewriteRelativeImportExtensions) { + forEachDynamicImportOrRequireCall( + node, + /*includeTypeSpaceImports*/ + false, + /*requireStringLiteralLikeArgument*/ + false, + (node2) => { + if (!isStringLiteralLike(node2.arguments[0]) || shouldRewriteModuleSpecifier(node2.arguments[0].text, compilerOptions)) { + importsAndRequiresToRewriteOrShim = append(importsAndRequiresToRewriteOrShim, node2); + } + } + ); + } + const transformModule2 = getTransformModuleDelegate(moduleKind); + const updated = transformModule2(node); + currentSourceFile = void 0; + currentModuleInfo = void 0; + needUMDDynamicImportHelper = false; + return updated; + } + function shouldEmitUnderscoreUnderscoreESModule() { + if (hasJSFileExtension(currentSourceFile.fileName) && currentSourceFile.commonJsModuleIndicator && (!currentSourceFile.externalModuleIndicator || currentSourceFile.externalModuleIndicator === true)) { + return false; + } + if (!currentModuleInfo.exportEquals && isExternalModule(currentSourceFile)) { + return true; + } + return false; + } + function transformCommonJSModule(node) { + startLexicalEnvironment(); + const statements = []; + const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || isExternalModule(currentSourceFile); + const statementOffset = factory2.copyPrologue(node.statements, statements, ensureUseStrict && !isJsonSourceFile(node), topLevelVisitor); + if (shouldEmitUnderscoreUnderscoreESModule()) { + append(statements, createUnderscoreUnderscoreESModule()); + } + if (some(currentModuleInfo.exportedNames)) { + const chunkSize = 50; + for (let i = 0; i < currentModuleInfo.exportedNames.length; i += chunkSize) { + append( + statements, + factory2.createExpressionStatement( + reduceLeft( + currentModuleInfo.exportedNames.slice(i, i + chunkSize), + (prev, nextId) => nextId.kind === 11 /* StringLiteral */ ? factory2.createAssignment(factory2.createElementAccessExpression(factory2.createIdentifier("exports"), factory2.createStringLiteral(nextId.text)), prev) : factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), + factory2.createVoidZero() + ) + ) + ); + } + } + for (const f of currentModuleInfo.exportedFunctions) { + appendExportsOfHoistedDeclaration(statements, f); + } + append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement)); + addRange(statements, visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset)); + addExportEqualsIfNeeded( + statements, + /*emitAsReturn*/ + false + ); + insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); + const updated = factory2.updateSourceFile(node, setTextRange(factory2.createNodeArray(statements), node.statements)); + addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + function transformAMDModule(node) { + const define = factory2.createIdentifier("define"); + const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions); + const jsonSourceFile = isJsonSourceFile(node) && node; + const { aliasedModuleNames, unaliasedModuleNames, importAliasNames } = collectAsynchronousDependencies( + node, + /*includeNonAmdDependencies*/ + true + ); + const updated = factory2.updateSourceFile( + node, + setTextRange( + factory2.createNodeArray([ + factory2.createExpressionStatement( + factory2.createCallExpression( + define, + /*typeArguments*/ + void 0, + [ + // Add the module name (if provided). + ...moduleName ? [moduleName] : [], + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + factory2.createArrayLiteralExpression( + jsonSourceFile ? emptyArray : [ + factory2.createStringLiteral("require"), + factory2.createStringLiteral("exports"), + ...aliasedModuleNames, + ...unaliasedModuleNames + ] + ), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + jsonSourceFile ? jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory2.createObjectLiteralExpression() : factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + [ + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "require" + ), + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "exports" + ), + ...importAliasNames + ], + /*type*/ + void 0, + transformAsynchronousModuleBody(node) + ) + ] + ) + ) + ]), + /*location*/ + node.statements + ) + ); + addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + function transformUMDModule(node) { + const { aliasedModuleNames, unaliasedModuleNames, importAliasNames } = collectAsynchronousDependencies( + node, + /*includeNonAmdDependencies*/ + false + ); + const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions); + const umdHeader = factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "factory" + )], + /*type*/ + void 0, + setTextRange( + factory2.createBlock( + [ + factory2.createIfStatement( + factory2.createLogicalAnd( + factory2.createTypeCheck(factory2.createIdentifier("module"), "object"), + factory2.createTypeCheck(factory2.createPropertyAccessExpression(factory2.createIdentifier("module"), "exports"), "object") + ), + factory2.createBlock([ + factory2.createVariableStatement( + /*modifiers*/ + void 0, + [ + factory2.createVariableDeclaration( + "v", + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createCallExpression( + factory2.createIdentifier("factory"), + /*typeArguments*/ + void 0, + [ + factory2.createIdentifier("require"), + factory2.createIdentifier("exports") + ] + ) + ) + ] + ), + setEmitFlags( + factory2.createIfStatement( + factory2.createStrictInequality( + factory2.createIdentifier("v"), + factory2.createIdentifier("undefined") + ), + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createPropertyAccessExpression(factory2.createIdentifier("module"), "exports"), + factory2.createIdentifier("v") + ) + ) + ), + 1 /* SingleLine */ + ) + ]), + factory2.createIfStatement( + factory2.createLogicalAnd( + factory2.createTypeCheck(factory2.createIdentifier("define"), "function"), + factory2.createPropertyAccessExpression(factory2.createIdentifier("define"), "amd") + ), + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createCallExpression( + factory2.createIdentifier("define"), + /*typeArguments*/ + void 0, + [ + // Add the module name (if provided). + ...moduleName ? [moduleName] : [], + factory2.createArrayLiteralExpression([ + factory2.createStringLiteral("require"), + factory2.createStringLiteral("exports"), + ...aliasedModuleNames, + ...unaliasedModuleNames + ]), + factory2.createIdentifier("factory") + ] + ) + ) + ]) + ) + ) + ], + /*multiLine*/ + true + ), + /*location*/ + void 0 + ) + ); + const updated = factory2.updateSourceFile( + node, + setTextRange( + factory2.createNodeArray([ + factory2.createExpressionStatement( + factory2.createCallExpression( + umdHeader, + /*typeArguments*/ + void 0, + [ + // Add the module body function argument: + // + // function (require, exports) ... + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + [ + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "require" + ), + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "exports" + ), + ...importAliasNames + ], + /*type*/ + void 0, + transformAsynchronousModuleBody(node) + ) + ] + ) + ) + ]), + /*location*/ + node.statements + ) + ); + addEmitHelpers(updated, context.readEmitHelpers()); + return updated; + } + function collectAsynchronousDependencies(node, includeNonAmdDependencies) { + const aliasedModuleNames = []; + const unaliasedModuleNames = []; + const importAliasNames = []; + for (const amdDependency of node.amdDependencies) { + if (amdDependency.name) { + aliasedModuleNames.push(factory2.createStringLiteral(amdDependency.path)); + importAliasNames.push(factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + amdDependency.name + )); + } else { + unaliasedModuleNames.push(factory2.createStringLiteral(amdDependency.path)); + } + } + for (const importNode of currentModuleInfo.externalImports) { + const externalModuleName = getExternalModuleNameLiteral(factory2, importNode, currentSourceFile, host, resolver, compilerOptions); + const importAliasName = getLocalNameForExternalImport(factory2, importNode, currentSourceFile); + if (externalModuleName) { + if (includeNonAmdDependencies && importAliasName) { + setEmitFlags(importAliasName, 8 /* NoSubstitution */); + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + importAliasName + )); + } else { + unaliasedModuleNames.push(externalModuleName); + } + } + } + return { aliasedModuleNames, unaliasedModuleNames, importAliasNames }; + } + function getAMDImportExpressionForImport(node) { + if (isImportEqualsDeclaration(node) || isExportDeclaration(node) || !getExternalModuleNameLiteral(factory2, node, currentSourceFile, host, resolver, compilerOptions)) { + return void 0; + } + const name = getLocalNameForExternalImport(factory2, node, currentSourceFile); + const expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return void 0; + } + return factory2.createExpressionStatement(factory2.createAssignment(name, expr)); + } + function transformAsynchronousModuleBody(node) { + startLexicalEnvironment(); + const statements = []; + const statementOffset = factory2.copyPrologue( + node.statements, + statements, + /*ensureUseStrict*/ + true, + topLevelVisitor + ); + if (shouldEmitUnderscoreUnderscoreESModule()) { + append(statements, createUnderscoreUnderscoreESModule()); + } + if (some(currentModuleInfo.exportedNames)) { + append( + statements, + factory2.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames, (prev, nextId) => nextId.kind === 11 /* StringLiteral */ ? factory2.createAssignment(factory2.createElementAccessExpression(factory2.createIdentifier("exports"), factory2.createStringLiteral(nextId.text)), prev) : factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), factory2.createVoidZero())) + ); + } + for (const f of currentModuleInfo.exportedFunctions) { + appendExportsOfHoistedDeclaration(statements, f); + } + append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement)); + if (moduleKind === 2 /* AMD */) { + addRange(statements, mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } + addRange(statements, visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset)); + addExportEqualsIfNeeded( + statements, + /*emitAsReturn*/ + true + ); + insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); + const body = factory2.createBlock( + statements, + /*multiLine*/ + true + ); + if (needUMDDynamicImportHelper) { + addEmitHelper(body, dynamicImportUMDHelper); + } + return body; + } + function addExportEqualsIfNeeded(statements, emitAsReturn) { + if (currentModuleInfo.exportEquals) { + const expressionResult = visitNode(currentModuleInfo.exportEquals.expression, visitor, isExpression); + if (expressionResult) { + if (emitAsReturn) { + const statement = factory2.createReturnStatement(expressionResult); + setTextRange(statement, currentModuleInfo.exportEquals); + setEmitFlags(statement, 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */); + statements.push(statement); + } else { + const statement = factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createPropertyAccessExpression( + factory2.createIdentifier("module"), + "exports" + ), + expressionResult + ) + ); + setTextRange(statement, currentModuleInfo.exportEquals); + setEmitFlags(statement, 3072 /* NoComments */); + statements.push(statement); + } + } + } + } + function topLevelVisitor(node) { + switch (node.kind) { + case 272 /* ImportDeclaration */: + return visitTopLevelImportDeclaration(node); + case 271 /* ImportEqualsDeclaration */: + return visitTopLevelImportEqualsDeclaration(node); + case 278 /* ExportDeclaration */: + return visitTopLevelExportDeclaration(node); + case 277 /* ExportAssignment */: + return visitTopLevelExportAssignment(node); + default: + return topLevelNestedVisitor(node); + } + } + function topLevelNestedVisitor(node) { + switch (node.kind) { + case 243 /* VariableStatement */: + return visitVariableStatement(node); + case 262 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 263 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 248 /* ForStatement */: + return visitForStatement( + node, + /*isTopLevel*/ + true + ); + case 249 /* ForInStatement */: + return visitForInStatement(node); + case 250 /* ForOfStatement */: + return visitForOfStatement(node); + case 246 /* DoStatement */: + return visitDoStatement(node); + case 247 /* WhileStatement */: + return visitWhileStatement(node); + case 256 /* LabeledStatement */: + return visitLabeledStatement(node); + case 254 /* WithStatement */: + return visitWithStatement(node); + case 245 /* IfStatement */: + return visitIfStatement(node); + case 255 /* SwitchStatement */: + return visitSwitchStatement(node); + case 269 /* CaseBlock */: + return visitCaseBlock(node); + case 296 /* CaseClause */: + return visitCaseClause(node); + case 297 /* DefaultClause */: + return visitDefaultClause(node); + case 258 /* TryStatement */: + return visitTryStatement(node); + case 299 /* CatchClause */: + return visitCatchClause(node); + case 241 /* Block */: + return visitBlock(node); + default: + return visitor(node); + } + } + function visitorWorker(node, valueIsDiscarded) { + if (!(node.transformFlags & (8388608 /* ContainsDynamicImport */ | 4096 /* ContainsDestructuringAssignment */ | 268435456 /* ContainsUpdateExpressionForIdentifier */)) && !(importsAndRequiresToRewriteOrShim == null ? void 0 : importsAndRequiresToRewriteOrShim.length)) { + return node; + } + switch (node.kind) { + case 248 /* ForStatement */: + return visitForStatement( + node, + /*isTopLevel*/ + false + ); + case 244 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 217 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, valueIsDiscarded); + case 355 /* PartiallyEmittedExpression */: + return visitPartiallyEmittedExpression(node, valueIsDiscarded); + case 213 /* CallExpression */: + const needsRewrite = node === firstOrUndefined(importsAndRequiresToRewriteOrShim); + if (needsRewrite) { + importsAndRequiresToRewriteOrShim.shift(); + } + if (isImportCall(node) && host.shouldTransformImportCall(currentSourceFile)) { + return visitImportCallExpression(node, needsRewrite); + } else if (needsRewrite) { + return shimOrRewriteImportOrRequireCall(node); + } + break; + case 226 /* BinaryExpression */: + if (isDestructuringAssignment(node)) { + return visitDestructuringAssignment(node, valueIsDiscarded); + } + break; + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + return visitPreOrPostfixUnaryExpression(node, valueIsDiscarded); + } + return visitEachChild(node, visitor, context); + } + function visitor(node) { + return visitorWorker( + node, + /*valueIsDiscarded*/ + false + ); + } + function discardedValueVisitor(node) { + return visitorWorker( + node, + /*valueIsDiscarded*/ + true + ); + } + function destructuringNeedsFlattening(node) { + if (isObjectLiteralExpression(node)) { + for (const elem of node.properties) { + switch (elem.kind) { + case 303 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 304 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 305 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return false; + default: + Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } else if (isArrayLiteralExpression(node)) { + for (const elem of node.elements) { + if (isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } else if (isIdentifier(node)) { + return length(getExports(node)) > (isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node, valueIsDiscarded) { + if (destructuringNeedsFlattening(node.left)) { + return flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !valueIsDiscarded, createAllExportExpressions); + } + return visitEachChild(node, visitor, context); + } + function visitForStatement(node, isTopLevel) { + if (isTopLevel && node.initializer && isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 7 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + false + ); + if (exportStatements) { + const statements = []; + const varDeclList = visitNode(node.initializer, discardedValueVisitor, isVariableDeclarationList); + const varStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + varDeclList + ); + statements.push(varStatement); + addRange(statements, exportStatements); + const condition = visitNode(node.condition, visitor, isExpression); + const incrementor = visitNode(node.incrementor, discardedValueVisitor, isExpression); + const body = visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context); + statements.push(factory2.updateForStatement( + node, + /*initializer*/ + void 0, + condition, + incrementor, + body + )); + return statements; + } + } + return factory2.updateForStatement( + node, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.condition, visitor, isExpression), + visitNode(node.incrementor, discardedValueVisitor, isExpression), + visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) + ); + } + function visitForInStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 7 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + if (some(exportStatements)) { + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + const body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + const mergedBody = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + return factory2.updateForInStatement(node, initializer, expression, mergedBody); + } + } + return factory2.updateForInStatement( + node, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitForOfStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 7 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + let body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + if (some(exportStatements)) { + body = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + } + return factory2.updateForOfStatement(node, node.awaitModifier, initializer, expression, body); + } + return factory2.updateForOfStatement( + node, + node.awaitModifier, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitDoStatement(node) { + return factory2.updateDoStatement( + node, + visitIterationBody(node.statement, topLevelNestedVisitor, context), + visitNode(node.expression, visitor, isExpression) + ); + } + function visitWhileStatement(node) { + return factory2.updateWhileStatement( + node, + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitLabeledStatement(node) { + return factory2.updateLabeledStatement( + node, + node.label, + visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ?? setTextRange(factory2.createEmptyStatement(), node.statement) + ); + } + function visitWithStatement(node) { + return factory2.updateWithStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ?? factory2.createBlock([]), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } + function visitSwitchStatement(node) { + return factory2.updateSwitchStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) + ); + } + function visitCaseBlock(node) { + return factory2.updateCaseBlock( + node, + visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) + ); + } + function visitCaseClause(node) { + return factory2.updateCaseClause( + node, + visitNode(node.expression, visitor, isExpression), + visitNodes2(node.statements, topLevelNestedVisitor, isStatement) + ); + } + function visitDefaultClause(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitTryStatement(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitCatchClause(node) { + return factory2.updateCatchClause( + node, + node.variableDeclaration, + Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) + ); + } + function visitBlock(node) { + node = visitEachChild(node, topLevelNestedVisitor, context); + return node; + } + function visitExpressionStatement(node) { + return factory2.updateExpressionStatement( + node, + visitNode(node.expression, discardedValueVisitor, isExpression) + ); + } + function visitParenthesizedExpression(node, valueIsDiscarded) { + return factory2.updateParenthesizedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression)); + } + function visitPartiallyEmittedExpression(node, valueIsDiscarded) { + return factory2.updatePartiallyEmittedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression)); + } + function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { + if ((node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) && !isDeclarationNameOfEnumOrNamespace(node.operand)) { + const exportedNames = getExports(node.operand); + if (exportedNames) { + let temp; + let expression = visitNode(node.operand, visitor, isExpression); + if (isPrefixUnaryExpression(node)) { + expression = factory2.updatePrefixUnaryExpression(node, expression); + } else { + expression = factory2.updatePostfixUnaryExpression(node, expression); + if (!valueIsDiscarded) { + temp = factory2.createTempVariable(hoistVariableDeclaration); + expression = factory2.createAssignment(temp, expression); + setTextRange(expression, node); + } + expression = factory2.createComma(expression, factory2.cloneNode(node.operand)); + setTextRange(expression, node); + } + for (const exportName of exportedNames) { + noSubstitution[getNodeId(expression)] = true; + expression = createExportExpression(exportName, expression); + setTextRange(expression, node); + } + if (temp) { + noSubstitution[getNodeId(expression)] = true; + expression = factory2.createComma(expression, temp); + setTextRange(expression, node); + } + return expression; + } + } + return visitEachChild(node, visitor, context); + } + function shimOrRewriteImportOrRequireCall(node) { + return factory2.updateCallExpression( + node, + node.expression, + /*typeArguments*/ + void 0, + visitNodes2(node.arguments, (arg) => { + if (arg === node.arguments[0]) { + return isStringLiteralLike(arg) ? rewriteModuleSpecifier(arg, compilerOptions) : emitHelpers().createRewriteRelativeImportExtensionsHelper(arg); + } + return visitor(arg); + }, isExpression) + ); + } + function visitImportCallExpression(node, rewriteOrShim) { + if (moduleKind === 0 /* None */ && languageVersion >= 7 /* ES2020 */) { + return visitEachChild(node, visitor, context); + } + const externalModuleName = getExternalModuleNameLiteral(factory2, node, currentSourceFile, host, resolver, compilerOptions); + const firstArgument = visitNode(firstOrUndefined(node.arguments), visitor, isExpression); + const argument = externalModuleName && (!firstArgument || !isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument && rewriteOrShim ? isStringLiteral(firstArgument) ? rewriteModuleSpecifier(firstArgument, compilerOptions) : emitHelpers().createRewriteRelativeImportExtensionsHelper(firstArgument) : firstArgument; + const containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + switch (compilerOptions.module) { + case 2 /* AMD */: + return createImportCallExpressionAMD(argument, containsLexicalThis); + case 3 /* UMD */: + return createImportCallExpressionUMD(argument ?? factory2.createVoidZero(), containsLexicalThis); + case 1 /* CommonJS */: + default: + return createImportCallExpressionCommonJS(argument); + } + } + function createImportCallExpressionUMD(arg, containsLexicalThis) { + needUMDDynamicImportHelper = true; + if (isSimpleCopiableExpression(arg)) { + const argClone = isGeneratedIdentifier(arg) ? arg : isStringLiteral(arg) ? factory2.createStringLiteralFromNode(arg) : setEmitFlags(setTextRange(factory2.cloneNode(arg), arg), 3072 /* NoComments */); + return factory2.createConditionalExpression( + /*condition*/ + factory2.createIdentifier("__syncRequire"), + /*questionToken*/ + void 0, + /*whenTrue*/ + createImportCallExpressionCommonJS(arg), + /*colonToken*/ + void 0, + /*whenFalse*/ + createImportCallExpressionAMD(argClone, containsLexicalThis) + ); + } else { + const temp = factory2.createTempVariable(hoistVariableDeclaration); + return factory2.createComma( + factory2.createAssignment(temp, arg), + factory2.createConditionalExpression( + /*condition*/ + factory2.createIdentifier("__syncRequire"), + /*questionToken*/ + void 0, + /*whenTrue*/ + createImportCallExpressionCommonJS( + temp, + /*isInlineable*/ + true + ), + /*colonToken*/ + void 0, + /*whenFalse*/ + createImportCallExpressionAMD(temp, containsLexicalThis) + ) + ); + } + } + function createImportCallExpressionAMD(arg, containsLexicalThis) { + const resolve = factory2.createUniqueName("resolve"); + const reject = factory2.createUniqueName("reject"); + const parameters = [ + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + /*name*/ + resolve + ), + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + /*name*/ + reject + ) + ]; + const body = factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createCallExpression( + factory2.createIdentifier("require"), + /*typeArguments*/ + void 0, + [factory2.createArrayLiteralExpression([arg || factory2.createOmittedExpression()]), resolve, reject] + ) + ) + ]); + let func; + if (languageVersion >= 2 /* ES2015 */) { + func = factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + parameters, + /*type*/ + void 0, + /*equalsGreaterThanToken*/ + void 0, + body + ); + } else { + func = factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + parameters, + /*type*/ + void 0, + body + ); + if (containsLexicalThis) { + setEmitFlags(func, 16 /* CapturesThis */); + } + } + const promise = factory2.createNewExpression( + factory2.createIdentifier("Promise"), + /*typeArguments*/ + void 0, + [func] + ); + if (getESModuleInterop(compilerOptions)) { + return factory2.createCallExpression( + factory2.createPropertyAccessExpression(promise, factory2.createIdentifier("then")), + /*typeArguments*/ + void 0, + [emitHelpers().createImportStarCallbackHelper()] + ); + } + return promise; + } + function createImportCallExpressionCommonJS(arg, isInlineable) { + const needSyncEval = arg && !isSimpleInlineableExpression(arg) && !isInlineable; + const promiseResolveCall = factory2.createCallExpression( + factory2.createPropertyAccessExpression(factory2.createIdentifier("Promise"), "resolve"), + /*typeArguments*/ + void 0, + /*argumentsArray*/ + needSyncEval ? languageVersion >= 2 /* ES2015 */ ? [ + factory2.createTemplateExpression(factory2.createTemplateHead(""), [ + factory2.createTemplateSpan(arg, factory2.createTemplateTail("")) + ]) + ] : [ + factory2.createCallExpression( + factory2.createPropertyAccessExpression(factory2.createStringLiteral(""), "concat"), + /*typeArguments*/ + void 0, + [arg] + ) + ] : [] + ); + let requireCall = factory2.createCallExpression( + factory2.createIdentifier("require"), + /*typeArguments*/ + void 0, + needSyncEval ? [factory2.createIdentifier("s")] : arg ? [arg] : [] + ); + if (getESModuleInterop(compilerOptions)) { + requireCall = emitHelpers().createImportStarHelper(requireCall); + } + const parameters = needSyncEval ? [ + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + /*name*/ + "s" + ) + ] : []; + let func; + if (languageVersion >= 2 /* ES2015 */) { + func = factory2.createArrowFunction( + /*modifiers*/ + void 0, + /*typeParameters*/ + void 0, + /*parameters*/ + parameters, + /*type*/ + void 0, + /*equalsGreaterThanToken*/ + void 0, + requireCall + ); + } else { + func = factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + /*parameters*/ + parameters, + /*type*/ + void 0, + factory2.createBlock([factory2.createReturnStatement(requireCall)]) + ); + } + const downleveledImport = factory2.createCallExpression( + factory2.createPropertyAccessExpression(promiseResolveCall, "then"), + /*typeArguments*/ + void 0, + [func] + ); + return downleveledImport; + } + function getHelperExpressionForExport(node, innerExpr) { + if (!getESModuleInterop(compilerOptions) || getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (getExportNeedsImportStarHelper(node)) { + return emitHelpers().createImportStarHelper(innerExpr); + } + return innerExpr; + } + function getHelperExpressionForImport(node, innerExpr) { + if (!getESModuleInterop(compilerOptions) || getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (getImportNeedsImportStarHelper(node)) { + return emitHelpers().createImportStarHelper(innerExpr); + } + if (getImportNeedsImportDefaultHelper(node)) { + return emitHelpers().createImportDefaultHelper(innerExpr); + } + return innerExpr; + } + function visitTopLevelImportDeclaration(node) { + let statements; + const namespaceDeclaration = getNamespaceDeclarationNode(node); + if (moduleKind !== 2 /* AMD */) { + if (!node.importClause) { + return setOriginalNode(setTextRange(factory2.createExpressionStatement(createRequireCall(node)), node), node); + } else { + const variables = []; + if (namespaceDeclaration && !isDefaultImport(node)) { + variables.push( + factory2.createVariableDeclaration( + factory2.cloneNode(namespaceDeclaration.name), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + getHelperExpressionForImport(node, createRequireCall(node)) + ) + ); + } else { + variables.push( + factory2.createVariableDeclaration( + factory2.getGeneratedNameForNode(node), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + getHelperExpressionForImport(node, createRequireCall(node)) + ) + ); + if (namespaceDeclaration && isDefaultImport(node)) { + variables.push( + factory2.createVariableDeclaration( + factory2.cloneNode(namespaceDeclaration.name), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.getGeneratedNameForNode(node) + ) + ); + } + } + statements = append( + statements, + setOriginalNode( + setTextRange( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + variables, + languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ + ) + ), + /*location*/ + node + ), + /*original*/ + node + ) + ); + } + } else if (namespaceDeclaration && isDefaultImport(node)) { + statements = append( + statements, + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + [ + setOriginalNode( + setTextRange( + factory2.createVariableDeclaration( + factory2.cloneNode(namespaceDeclaration.name), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.getGeneratedNameForNode(node) + ), + /*location*/ + node + ), + /*original*/ + node + ) + ], + languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ + ) + ) + ); + } + statements = appendExportsOfImportDeclaration(statements, node); + return singleOrMany(statements); + } + function createRequireCall(importNode) { + const moduleName = getExternalModuleNameLiteral(factory2, importNode, currentSourceFile, host, resolver, compilerOptions); + const args = []; + if (moduleName) { + args.push(rewriteModuleSpecifier(moduleName, compilerOptions)); + } + return factory2.createCallExpression( + factory2.createIdentifier("require"), + /*typeArguments*/ + void 0, + args + ); + } + function visitTopLevelImportEqualsDeclaration(node) { + Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + let statements; + if (moduleKind !== 2 /* AMD */) { + if (hasSyntacticModifier(node, 32 /* Export */)) { + statements = append( + statements, + setOriginalNode( + setTextRange( + factory2.createExpressionStatement( + createExportExpression( + node.name, + createRequireCall(node) + ) + ), + node + ), + node + ) + ); + } else { + statements = append( + statements, + setOriginalNode( + setTextRange( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + [ + factory2.createVariableDeclaration( + factory2.cloneNode(node.name), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + createRequireCall(node) + ) + ], + /*flags*/ + languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ + ) + ), + node + ), + node + ) + ); + } + } else { + if (hasSyntacticModifier(node, 32 /* Export */)) { + statements = append( + statements, + setOriginalNode( + setTextRange( + factory2.createExpressionStatement( + createExportExpression(factory2.getExportName(node), factory2.getLocalName(node)) + ), + node + ), + node + ) + ); + } + } + statements = appendExportsOfImportEqualsDeclaration(statements, node); + return singleOrMany(statements); + } + function visitTopLevelExportDeclaration(node) { + if (!node.moduleSpecifier) { + return void 0; + } + const generatedName = factory2.getGeneratedNameForNode(node); + if (node.exportClause && isNamedExports(node.exportClause)) { + const statements = []; + if (moduleKind !== 2 /* AMD */) { + statements.push( + setOriginalNode( + setTextRange( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + generatedName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + createRequireCall(node) + ) + ]) + ), + /*location*/ + node + ), + /* original */ + node + ) + ); + } + for (const specifier of node.exportClause.elements) { + const specifierName = specifier.propertyName || specifier.name; + const exportNeedsImportDefault = !!getESModuleInterop(compilerOptions) && !(getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */) && moduleExportNameIsDefault(specifierName); + const target = exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName; + const exportedValue = specifierName.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression(target, specifierName) : factory2.createPropertyAccessExpression(target, specifierName); + statements.push( + setOriginalNode( + setTextRange( + factory2.createExpressionStatement( + createExportExpression( + specifier.name.kind === 11 /* StringLiteral */ ? factory2.cloneNode(specifier.name) : factory2.getExportName(specifier), + exportedValue, + /*location*/ + void 0, + /*liveBinding*/ + true + ) + ), + specifier + ), + specifier + ) + ); + } + return singleOrMany(statements); + } else if (node.exportClause) { + const statements = []; + statements.push( + setOriginalNode( + setTextRange( + factory2.createExpressionStatement( + createExportExpression( + factory2.cloneNode(node.exportClause.name), + getHelperExpressionForExport( + node, + moduleKind !== 2 /* AMD */ ? createRequireCall(node) : isExportNamespaceAsDefaultDeclaration(node) ? generatedName : node.exportClause.name.kind === 11 /* StringLiteral */ ? generatedName : factory2.createIdentifier(idText(node.exportClause.name)) + ) + ) + ), + node + ), + node + ) + ); + return singleOrMany(statements); + } else { + return setOriginalNode( + setTextRange( + factory2.createExpressionStatement( + emitHelpers().createExportStarHelper(moduleKind !== 2 /* AMD */ ? createRequireCall(node) : generatedName) + ), + node + ), + node + ); + } + } + function visitTopLevelExportAssignment(node) { + if (node.isExportEquals) { + return void 0; + } + return createExportStatement( + factory2.createIdentifier("default"), + visitNode(node.expression, visitor, isExpression), + /*location*/ + node, + /*allowComments*/ + true + ); + } + function visitFunctionDeclaration(node) { + let statements; + if (hasSyntacticModifier(node, 32 /* Export */)) { + statements = append( + statements, + setOriginalNode( + setTextRange( + factory2.createFunctionDeclaration( + visitNodes2(node.modifiers, modifierVisitor, isModifier), + node.asteriskToken, + factory2.getDeclarationName( + node, + /*allowComments*/ + true, + /*allowSourceMaps*/ + true + ), + /*typeParameters*/ + void 0, + visitNodes2(node.parameters, visitor, isParameter), + /*type*/ + void 0, + visitEachChild(node.body, visitor, context) + ), + /*location*/ + node + ), + /*original*/ + node + ) + ); + } else { + statements = append(statements, visitEachChild(node, visitor, context)); + } + return singleOrMany(statements); + } + function visitClassDeclaration(node) { + let statements; + if (hasSyntacticModifier(node, 32 /* Export */)) { + statements = append( + statements, + setOriginalNode( + setTextRange( + factory2.createClassDeclaration( + visitNodes2(node.modifiers, modifierVisitor, isModifierLike), + factory2.getDeclarationName( + node, + /*allowComments*/ + true, + /*allowSourceMaps*/ + true + ), + /*typeParameters*/ + void 0, + visitNodes2(node.heritageClauses, visitor, isHeritageClause), + visitNodes2(node.members, visitor, isClassElement) + ), + node + ), + node + ) + ); + } else { + statements = append(statements, visitEachChild(node, visitor, context)); + } + statements = appendExportsOfHoistedDeclaration(statements, node); + return singleOrMany(statements); + } + function visitVariableStatement(node) { + let statements; + let variables; + let expressions; + if (hasSyntacticModifier(node, 32 /* Export */)) { + let modifiers; + let removeCommentsOnExpressions = false; + for (const variable of node.declarationList.declarations) { + if (isIdentifier(variable.name) && isLocalName(variable.name)) { + if (!modifiers) { + modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + } + if (variable.initializer) { + const updatedVariable = factory2.updateVariableDeclaration( + variable, + variable.name, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + createExportExpression( + variable.name, + visitNode(variable.initializer, visitor, isExpression) + ) + ); + variables = append(variables, updatedVariable); + } else { + variables = append(variables, variable); + } + } else if (variable.initializer) { + if (!isBindingPattern(variable.name) && (isArrowFunction(variable.initializer) || isFunctionExpression(variable.initializer) || isClassExpression(variable.initializer))) { + const expression = factory2.createAssignment( + setTextRange( + factory2.createPropertyAccessExpression( + factory2.createIdentifier("exports"), + variable.name + ), + /*location*/ + variable.name + ), + factory2.createIdentifier(getTextOfIdentifierOrLiteral(variable.name)) + ); + const updatedVariable = factory2.createVariableDeclaration( + variable.name, + variable.exclamationToken, + variable.type, + visitNode(variable.initializer, visitor, isExpression) + ); + variables = append(variables, updatedVariable); + expressions = append(expressions, expression); + removeCommentsOnExpressions = true; + } else { + expressions = append(expressions, transformInitializedVariable(variable)); + } + } + } + if (variables) { + statements = append(statements, factory2.updateVariableStatement(node, modifiers, factory2.updateVariableDeclarationList(node.declarationList, variables))); + } + if (expressions) { + const statement = setOriginalNode(setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node), node); + if (removeCommentsOnExpressions) { + removeAllComments(statement); + } + statements = append(statements, statement); + } + } else { + statements = append(statements, visitEachChild(node, visitor, context)); + } + statements = appendExportsOfVariableStatement(statements, node); + return singleOrMany(statements); + } + function createAllExportExpressions(name, value, location) { + const exportedNames = getExports(name); + if (exportedNames) { + let expression = isExportName(name) ? value : factory2.createAssignment(name, value); + for (const exportName of exportedNames) { + setEmitFlags(expression, 8 /* NoSubstitution */); + expression = createExportExpression( + exportName, + expression, + /*location*/ + location + ); + } + return expression; + } + return factory2.createAssignment(name, value); + } + function transformInitializedVariable(node) { + if (isBindingPattern(node.name)) { + return flattenDestructuringAssignment( + visitNode(node, visitor, isInitializedVariable), + visitor, + context, + 0 /* All */, + /*needsValue*/ + false, + createAllExportExpressions + ); + } else { + return factory2.createAssignment( + setTextRange( + factory2.createPropertyAccessExpression( + factory2.createIdentifier("exports"), + node.name + ), + /*location*/ + node.name + ), + node.initializer ? visitNode(node.initializer, visitor, isExpression) : factory2.createVoidZero() + ); + } + } + function appendExportsOfImportDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + const importClause = decl.importClause; + if (!importClause) { + return statements; + } + const seen = new IdentifierNameMap(); + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, seen, importClause); + } + const namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 274 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, seen, namedBindings); + break; + case 275 /* NamedImports */: + for (const importBinding of namedBindings.elements) { + statements = appendExportsOfDeclaration( + statements, + seen, + importBinding, + /*liveBinding*/ + true + ); + } + break; + } + } + return statements; + } + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, new IdentifierNameMap(), decl); + } + function appendExportsOfVariableStatement(statements, node) { + return appendExportsOfVariableDeclarationList( + statements, + node.declarationList, + /*isForInOrOfInitializer*/ + false + ); + } + function appendExportsOfVariableDeclarationList(statements, node, isForInOrOfInitializer) { + if (currentModuleInfo.exportEquals) { + return statements; + } + for (const decl of node.declarations) { + statements = appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer); + } + return statements; + } + function appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer) { + if (currentModuleInfo.exportEquals) { + return statements; + } + if (isBindingPattern(decl.name)) { + for (const element of decl.name.elements) { + if (!isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, isForInOrOfInitializer); + } + } + } else if (!isGeneratedIdentifier(decl.name) && (!isVariableDeclaration(decl) || decl.initializer || isForInOrOfInitializer)) { + statements = appendExportsOfDeclaration(statements, new IdentifierNameMap(), decl); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (currentModuleInfo.exportEquals) { + return statements; + } + const seen = new IdentifierNameMap(); + if (hasSyntacticModifier(decl, 32 /* Export */)) { + const exportName = hasSyntacticModifier(decl, 2048 /* Default */) ? factory2.createIdentifier("default") : factory2.getDeclarationName(decl); + statements = appendExportStatement( + statements, + seen, + exportName, + factory2.getLocalName(decl), + /*location*/ + decl + ); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, seen, decl); + } + return statements; + } + function appendExportsOfDeclaration(statements, seen, decl, liveBinding) { + const name = factory2.getDeclarationName(decl); + const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + for (const exportSpecifier of exportSpecifiers) { + statements = appendExportStatement( + statements, + seen, + exportSpecifier.name, + name, + /*location*/ + exportSpecifier.name, + /*allowComments*/ + void 0, + liveBinding + ); + } + } + return statements; + } + function appendExportStatement(statements, seen, exportName, expression, location, allowComments, liveBinding) { + if (exportName.kind !== 11 /* StringLiteral */) { + if (seen.has(exportName)) { + return statements; + } + seen.set(exportName, true); + } + statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); + return statements; + } + function createUnderscoreUnderscoreESModule() { + const statement = factory2.createExpressionStatement( + factory2.createCallExpression( + factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ + void 0, + [ + factory2.createIdentifier("exports"), + factory2.createStringLiteral("__esModule"), + factory2.createObjectLiteralExpression([ + factory2.createPropertyAssignment("value", factory2.createTrue()) + ]) + ] + ) + ); + setEmitFlags(statement, 2097152 /* CustomPrologue */); + return statement; + } + function createExportStatement(name, value, location, allowComments, liveBinding) { + const statement = setTextRange(factory2.createExpressionStatement(createExportExpression( + name, + value, + /*location*/ + void 0, + liveBinding + )), location); + startOnNewLine(statement); + if (!allowComments) { + setEmitFlags(statement, 3072 /* NoComments */); + } + return statement; + } + function createExportExpression(name, value, location, liveBinding) { + return setTextRange( + liveBinding ? factory2.createCallExpression( + factory2.createPropertyAccessExpression( + factory2.createIdentifier("Object"), + "defineProperty" + ), + /*typeArguments*/ + void 0, + [ + factory2.createIdentifier("exports"), + factory2.createStringLiteralFromNode(name), + factory2.createObjectLiteralExpression([ + factory2.createPropertyAssignment("enumerable", factory2.createTrue()), + factory2.createPropertyAssignment( + "get", + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + /*parameters*/ + [], + /*type*/ + void 0, + factory2.createBlock([factory2.createReturnStatement(value)]) + ) + ) + ]) + ] + ) : factory2.createAssignment( + name.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression( + factory2.createIdentifier("exports"), + factory2.cloneNode(name) + ) : factory2.createPropertyAccessExpression( + factory2.createIdentifier("exports"), + factory2.cloneNode(name) + ), + value + ), + location + ); + } + function modifierVisitor(node) { + switch (node.kind) { + case 95 /* ExportKeyword */: + case 90 /* DefaultKeyword */: + return void 0; + } + return node; + } + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 307 /* SourceFile */) { + currentSourceFile = node; + currentModuleInfo = moduleInfoMap[getOriginalNodeId(currentSourceFile)]; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = void 0; + currentModuleInfo = void 0; + } else { + previousOnEmitNode(hint, node, emitCallback); + } + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (node.id && noSubstitution[node.id]) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } else if (isShorthandPropertyAssignment(node)) { + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + const name = node.name; + const exportedOrImportedName = substituteExpressionIdentifier(name); + if (exportedOrImportedName !== name) { + if (node.objectAssignmentInitializer) { + const initializer = factory2.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer); + return setTextRange(factory2.createPropertyAssignment(name, initializer), node); + } + return setTextRange(factory2.createPropertyAssignment(name, exportedOrImportedName), node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 80 /* Identifier */: + return substituteExpressionIdentifier(node); + case 213 /* CallExpression */: + return substituteCallExpression(node); + case 215 /* TaggedTemplateExpression */: + return substituteTaggedTemplateExpression(node); + case 226 /* BinaryExpression */: + return substituteBinaryExpression(node); + } + return node; + } + function substituteCallExpression(node) { + if (isIdentifier(node.expression)) { + const expression = substituteExpressionIdentifier(node.expression); + noSubstitution[getNodeId(expression)] = true; + if (!isIdentifier(expression) && !(getEmitFlags(node.expression) & 8192 /* HelperName */)) { + return addInternalEmitFlags( + factory2.updateCallExpression( + node, + expression, + /*typeArguments*/ + void 0, + node.arguments + ), + 16 /* IndirectCall */ + ); + } + } + return node; + } + function substituteTaggedTemplateExpression(node) { + if (isIdentifier(node.tag)) { + const tag = substituteExpressionIdentifier(node.tag); + noSubstitution[getNodeId(tag)] = true; + if (!isIdentifier(tag) && !(getEmitFlags(node.tag) & 8192 /* HelperName */)) { + return addInternalEmitFlags( + factory2.updateTaggedTemplateExpression( + node, + tag, + /*typeArguments*/ + void 0, + node.template + ), + 16 /* IndirectCall */ + ); + } + } + return node; + } + function substituteExpressionIdentifier(node) { + var _a, _b; + if (getEmitFlags(node) & 8192 /* HelperName */) { + const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return factory2.createPropertyAccessExpression(externalHelpersModuleName, node); + } + return node; + } else if (!(isGeneratedIdentifier(node) && !(node.emitNode.autoGenerate.flags & 64 /* AllowNameSubstitution */)) && !isLocalName(node)) { + const exportContainer = resolver.getReferencedExportContainer(node, isExportName(node)); + if (exportContainer && exportContainer.kind === 307 /* SourceFile */) { + return setTextRange( + factory2.createPropertyAccessExpression( + factory2.createIdentifier("exports"), + factory2.cloneNode(node) + ), + /*location*/ + node + ); + } + const importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (isImportClause(importDeclaration)) { + return setTextRange( + factory2.createPropertyAccessExpression( + factory2.getGeneratedNameForNode(importDeclaration.parent), + factory2.createIdentifier("default") + ), + /*location*/ + node + ); + } else if (isImportSpecifier(importDeclaration)) { + const name = importDeclaration.propertyName || importDeclaration.name; + const target = factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration); + return setTextRange( + name.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression(target, factory2.cloneNode(name)) : factory2.createPropertyAccessExpression(target, factory2.cloneNode(name)), + /*location*/ + node + ); + } + } + } + return node; + } + function substituteBinaryExpression(node) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) && !isLocalName(node.left)) { + const exportedNames = getExports(node.left); + if (exportedNames) { + let expression = node; + for (const exportName of exportedNames) { + noSubstitution[getNodeId(expression)] = true; + expression = createExportExpression( + exportName, + expression, + /*location*/ + node + ); + } + return expression; + } + } + return node; + } + function getExports(name) { + if (!isGeneratedIdentifier(name)) { + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + return currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(importDeclaration)]; + } + const bindingsSet = /* @__PURE__ */ new Set(); + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + const bindings = currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(declaration)]; + if (bindings) { + for (const binding of bindings) { + bindingsSet.add(binding); + } + } + } + if (bindingsSet.size) { + return arrayFrom(bindingsSet); + } + } + } else if (isFileLevelReservedGeneratedIdentifier(name)) { + const exportSpecifiers = currentModuleInfo == null ? void 0 : currentModuleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + const exportedNames = []; + for (const exportSpecifier of exportSpecifiers) { + exportedNames.push(exportSpecifier.name); + } + return exportedNames; + } + } + } +} +var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: ` + var __syncRequire = typeof module === "object" && typeof module.exports === "object";` +}; + +// src/compiler/transformers/module/system.ts +function transformSystemModule(context) { + const { + factory: factory2, + startLexicalEnvironment, + endLexicalEnvironment, + hoistVariableDeclaration + } = context; + const compilerOptions = context.getCompilerOptions(); + const resolver = context.getEmitResolver(); + const host = context.getEmitHost(); + const previousOnSubstituteNode = context.onSubstituteNode; + const previousOnEmitNode = context.onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(80 /* Identifier */); + context.enableSubstitution(304 /* ShorthandPropertyAssignment */); + context.enableSubstitution(226 /* BinaryExpression */); + context.enableSubstitution(236 /* MetaProperty */); + context.enableEmitNotification(307 /* SourceFile */); + const moduleInfoMap = []; + const exportFunctionsMap = []; + const noSubstitutionMap = []; + const contextObjectMap = []; + let currentSourceFile; + let moduleInfo; + let exportFunction; + let contextObject; + let hoistedStatements; + let enclosingBlockScopedContainer; + let noSubstitution; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* ContainsDynamicImport */)) { + return node; + } + const id = getOriginalNodeId(node); + currentSourceFile = node; + enclosingBlockScopedContainer = node; + moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(context, node); + exportFunction = factory2.createUniqueName("exports"); + exportFunctionsMap[id] = exportFunction; + contextObject = contextObjectMap[id] = factory2.createUniqueName("context"); + const dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); + const moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); + const moduleBodyFunction = factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + [ + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + exportFunction + ), + factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + contextObject + ) + ], + /*type*/ + void 0, + moduleBodyBlock + ); + const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions); + const dependencies = factory2.createArrayLiteralExpression(map(dependencyGroups, (dependencyGroup) => dependencyGroup.name)); + const updated = setEmitFlags( + factory2.updateSourceFile( + node, + setTextRange( + factory2.createNodeArray([ + factory2.createExpressionStatement( + factory2.createCallExpression( + factory2.createPropertyAccessExpression(factory2.createIdentifier("System"), "register"), + /*typeArguments*/ + void 0, + moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction] + ) + ) + ]), + node.statements + ) + ), + 2048 /* NoTrailingComments */ + ); + if (!compilerOptions.outFile) { + moveEmitHelpers(updated, moduleBodyBlock, (helper) => !helper.scoped); + } + if (noSubstitution) { + noSubstitutionMap[id] = noSubstitution; + noSubstitution = void 0; + } + currentSourceFile = void 0; + moduleInfo = void 0; + exportFunction = void 0; + contextObject = void 0; + hoistedStatements = void 0; + enclosingBlockScopedContainer = void 0; + return updated; + } + function collectDependencyGroups(externalImports) { + const groupIndices = /* @__PURE__ */ new Map(); + const dependencyGroups = []; + for (const externalImport of externalImports) { + const externalModuleName = getExternalModuleNameLiteral(factory2, externalImport, currentSourceFile, host, resolver, compilerOptions); + if (externalModuleName) { + const text = externalModuleName.text; + const groupIndex = groupIndices.get(text); + if (groupIndex !== void 0) { + dependencyGroups[groupIndex].externalImports.push(externalImport); + } else { + groupIndices.set(text, dependencyGroups.length); + dependencyGroups.push({ + name: externalModuleName, + externalImports: [externalImport] + }); + } + } + } + return dependencyGroups; + } + function createSystemModuleBody(node, dependencyGroups) { + const statements = []; + startLexicalEnvironment(); + const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || isExternalModule(currentSourceFile); + const statementOffset = factory2.copyPrologue(node.statements, statements, ensureUseStrict, topLevelVisitor); + statements.push( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + "__moduleName", + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createLogicalAnd( + contextObject, + factory2.createPropertyAccessExpression(contextObject, "id") + ) + ) + ]) + ) + ); + visitNode(moduleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement); + const executeStatements = visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset); + addRange(statements, hoistedStatements); + insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); + const exportStarFunction = addExportStarIfNeeded(statements); + const modifiers = node.transformFlags & 2097152 /* ContainsAwait */ ? factory2.createModifiersFromModifierFlags(1024 /* Async */) : void 0; + const moduleObject = factory2.createObjectLiteralExpression( + [ + factory2.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + factory2.createPropertyAssignment( + "execute", + factory2.createFunctionExpression( + modifiers, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + /*parameters*/ + [], + /*type*/ + void 0, + factory2.createBlock( + executeStatements, + /*multiLine*/ + true + ) + ) + ) + ], + /*multiLine*/ + true + ); + statements.push(factory2.createReturnStatement(moduleObject)); + return factory2.createBlock( + statements, + /*multiLine*/ + true + ); + } + function addExportStarIfNeeded(statements) { + if (!moduleInfo.hasExportStarsToExportValues) { + return; + } + if (!some(moduleInfo.exportedNames) && moduleInfo.exportedFunctions.size === 0 && moduleInfo.exportSpecifiers.size === 0) { + let hasExportDeclarationWithExportClause = false; + for (const externalImport of moduleInfo.externalImports) { + if (externalImport.kind === 278 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + const exportStarFunction2 = createExportStarFunction( + /*localNames*/ + void 0 + ); + statements.push(exportStarFunction2); + return exportStarFunction2.name; + } + } + const exportedNames = []; + if (moduleInfo.exportedNames) { + for (const exportedLocalName of moduleInfo.exportedNames) { + if (moduleExportNameIsDefault(exportedLocalName)) { + continue; + } + exportedNames.push( + factory2.createPropertyAssignment( + factory2.createStringLiteralFromNode(exportedLocalName), + factory2.createTrue() + ) + ); + } + } + for (const f of moduleInfo.exportedFunctions) { + if (hasSyntacticModifier(f, 2048 /* Default */)) { + continue; + } + Debug.assert(!!f.name); + exportedNames.push( + factory2.createPropertyAssignment( + factory2.createStringLiteralFromNode(f.name), + factory2.createTrue() + ) + ); + } + const exportedNamesStorageRef = factory2.createUniqueName("exportedNames"); + statements.push( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + exportedNamesStorageRef, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createObjectLiteralExpression( + exportedNames, + /*multiLine*/ + true + ) + ) + ]) + ) + ); + const exportStarFunction = createExportStarFunction(exportedNamesStorageRef); + statements.push(exportStarFunction); + return exportStarFunction.name; + } + function createExportStarFunction(localNames) { + const exportStarFunction = factory2.createUniqueName("exportStar"); + const m = factory2.createIdentifier("m"); + const n = factory2.createIdentifier("n"); + const exports2 = factory2.createIdentifier("exports"); + let condition = factory2.createStrictInequality(n, factory2.createStringLiteral("default")); + if (localNames) { + condition = factory2.createLogicalAnd( + condition, + factory2.createLogicalNot( + factory2.createCallExpression( + factory2.createPropertyAccessExpression(localNames, "hasOwnProperty"), + /*typeArguments*/ + void 0, + [n] + ) + ) + ); + } + return factory2.createFunctionDeclaration( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + exportStarFunction, + /*typeParameters*/ + void 0, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + m + )], + /*type*/ + void 0, + factory2.createBlock( + [ + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration( + exports2, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createObjectLiteralExpression([]) + ) + ]) + ), + factory2.createForInStatement( + factory2.createVariableDeclarationList([ + factory2.createVariableDeclaration(n) + ]), + m, + factory2.createBlock([ + setEmitFlags( + factory2.createIfStatement( + condition, + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createElementAccessExpression(exports2, n), + factory2.createElementAccessExpression(m, n) + ) + ) + ), + 1 /* SingleLine */ + ) + ]) + ), + factory2.createExpressionStatement( + factory2.createCallExpression( + exportFunction, + /*typeArguments*/ + void 0, + [exports2] + ) + ) + ], + /*multiLine*/ + true + ) + ); + } + function createSettersArray(exportStarFunction, dependencyGroups) { + const setters = []; + for (const group2 of dependencyGroups) { + const localName = forEach(group2.externalImports, (i) => getLocalNameForExternalImport(factory2, i, currentSourceFile)); + const parameterName = localName ? factory2.getGeneratedNameForNode(localName) : factory2.createUniqueName(""); + const statements = []; + for (const entry of group2.externalImports) { + const importVariableName = getLocalNameForExternalImport(factory2, entry, currentSourceFile); + switch (entry.kind) { + case 272 /* ImportDeclaration */: + if (!entry.importClause) { + break; + } + // falls through + case 271 /* ImportEqualsDeclaration */: + Debug.assert(importVariableName !== void 0); + statements.push( + factory2.createExpressionStatement( + factory2.createAssignment(importVariableName, parameterName) + ) + ); + if (hasSyntacticModifier(entry, 32 /* Export */)) { + statements.push( + factory2.createExpressionStatement( + factory2.createCallExpression( + exportFunction, + /*typeArguments*/ + void 0, + [ + factory2.createStringLiteral(idText(importVariableName)), + parameterName + ] + ) + ) + ); + } + break; + case 278 /* ExportDeclaration */: + Debug.assert(importVariableName !== void 0); + if (entry.exportClause) { + if (isNamedExports(entry.exportClause)) { + const properties = []; + for (const e of entry.exportClause.elements) { + properties.push( + factory2.createPropertyAssignment( + factory2.createStringLiteral(moduleExportNameTextUnescaped(e.name)), + factory2.createElementAccessExpression( + parameterName, + factory2.createStringLiteral(moduleExportNameTextUnescaped(e.propertyName || e.name)) + ) + ) + ); + } + statements.push( + factory2.createExpressionStatement( + factory2.createCallExpression( + exportFunction, + /*typeArguments*/ + void 0, + [factory2.createObjectLiteralExpression( + properties, + /*multiLine*/ + true + )] + ) + ) + ); + } else { + statements.push( + factory2.createExpressionStatement( + factory2.createCallExpression( + exportFunction, + /*typeArguments*/ + void 0, + [ + factory2.createStringLiteral(moduleExportNameTextUnescaped(entry.exportClause.name)), + parameterName + ] + ) + ) + ); + } + } else { + statements.push( + factory2.createExpressionStatement( + factory2.createCallExpression( + exportStarFunction, + /*typeArguments*/ + void 0, + [parameterName] + ) + ) + ); + } + break; + } + } + setters.push( + factory2.createFunctionExpression( + /*modifiers*/ + void 0, + /*asteriskToken*/ + void 0, + /*name*/ + void 0, + /*typeParameters*/ + void 0, + [factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + parameterName + )], + /*type*/ + void 0, + factory2.createBlock( + statements, + /*multiLine*/ + true + ) + ) + ); + } + return factory2.createArrayLiteralExpression( + setters, + /*multiLine*/ + true + ); + } + function topLevelVisitor(node) { + switch (node.kind) { + case 272 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 271 /* ImportEqualsDeclaration */: + return visitImportEqualsDeclaration(node); + case 278 /* ExportDeclaration */: + return visitExportDeclaration(node); + case 277 /* ExportAssignment */: + return visitExportAssignment(node); + default: + return topLevelNestedVisitor(node); + } + } + function visitImportDeclaration(node) { + let statements; + if (node.importClause) { + hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); + } + return singleOrMany(appendExportsOfImportDeclaration(statements, node)); + } + function visitExportDeclaration(node) { + Debug.assertIsDefined(node); + return void 0; + } + function visitImportEqualsDeclaration(node) { + Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + let statements; + hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); + return singleOrMany(appendExportsOfImportEqualsDeclaration(statements, node)); + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + return void 0; + } + const expression = visitNode(node.expression, visitor, isExpression); + return createExportStatement( + factory2.createIdentifier("default"), + expression, + /*allowComments*/ + true + ); + } + function visitFunctionDeclaration(node) { + if (hasSyntacticModifier(node, 32 /* Export */)) { + hoistedStatements = append( + hoistedStatements, + factory2.updateFunctionDeclaration( + node, + visitNodes2(node.modifiers, modifierVisitor, isModifierLike), + node.asteriskToken, + factory2.getDeclarationName( + node, + /*allowComments*/ + true, + /*allowSourceMaps*/ + true + ), + /*typeParameters*/ + void 0, + visitNodes2(node.parameters, visitor, isParameter), + /*type*/ + void 0, + visitNode(node.body, visitor, isBlock) + ) + ); + } else { + hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context)); + } + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); + return void 0; + } + function visitClassDeclaration(node) { + let statements; + const name = factory2.getLocalName(node); + hoistVariableDeclaration(name); + statements = append( + statements, + setTextRange( + factory2.createExpressionStatement( + factory2.createAssignment( + name, + setTextRange( + factory2.createClassExpression( + visitNodes2(node.modifiers, modifierVisitor, isModifierLike), + node.name, + /*typeParameters*/ + void 0, + visitNodes2(node.heritageClauses, visitor, isHeritageClause), + visitNodes2(node.members, visitor, isClassElement) + ), + node + ) + ) + ), + node + ) + ); + statements = appendExportsOfHoistedDeclaration(statements, node); + return singleOrMany(statements); + } + function visitVariableStatement(node) { + if (!shouldHoistVariableDeclarationList(node.declarationList)) { + return visitNode(node, visitor, isStatement); + } + let statements; + if (isVarUsing(node.declarationList) || isVarAwaitUsing(node.declarationList)) { + const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifierLike); + const declarations = []; + for (const variable of node.declarationList.declarations) { + declarations.push(factory2.updateVariableDeclaration( + variable, + factory2.getGeneratedNameForNode(variable.name), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + transformInitializedVariable( + variable, + /*isExportedDeclaration*/ + false + ) + )); + } + const declarationList = factory2.updateVariableDeclarationList( + node.declarationList, + declarations + ); + statements = append(statements, factory2.updateVariableStatement(node, modifiers, declarationList)); + } else { + let expressions; + const isExportedDeclaration = hasSyntacticModifier(node, 32 /* Export */); + for (const variable of node.declarationList.declarations) { + if (variable.initializer) { + expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); + } else { + hoistBindingElement(variable); + } + } + if (expressions) { + statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node)); + } + } + statements = appendExportsOfVariableStatement( + statements, + node, + /*exportSelf*/ + false + ); + return singleOrMany(statements); + } + function hoistBindingElement(node) { + if (isBindingPattern(node.name)) { + for (const element of node.name.elements) { + if (!isOmittedExpression(element)) { + hoistBindingElement(element); + } + } + } else { + hoistVariableDeclaration(factory2.cloneNode(node.name)); + } + } + function shouldHoistVariableDeclarationList(node) { + return (getEmitFlags(node) & 4194304 /* NoHoisting */) === 0 && (enclosingBlockScopedContainer.kind === 307 /* SourceFile */ || (getOriginalNode(node).flags & 7 /* BlockScoped */) === 0); + } + function transformInitializedVariable(node, isExportedDeclaration) { + const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; + return isBindingPattern(node.name) ? flattenDestructuringAssignment( + node, + visitor, + context, + 0 /* All */, + /*needsValue*/ + false, + createAssignment + ) : node.initializer ? createAssignment(node.name, visitNode(node.initializer, visitor, isExpression)) : node.name; + } + function createExportedVariableAssignment(name, value, location) { + return createVariableAssignment( + name, + value, + location, + /*isExportedDeclaration*/ + true + ); + } + function createNonExportedVariableAssignment(name, value, location) { + return createVariableAssignment( + name, + value, + location, + /*isExportedDeclaration*/ + false + ); + } + function createVariableAssignment(name, value, location, isExportedDeclaration) { + hoistVariableDeclaration(factory2.cloneNode(name)); + return isExportedDeclaration ? createExportExpression(name, preventSubstitution(setTextRange(factory2.createAssignment(name, value), location))) : preventSubstitution(setTextRange(factory2.createAssignment(name, value), location)); + } + function appendExportsOfImportDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + const importClause = decl.importClause; + if (!importClause) { + return statements; + } + if (importClause.name) { + statements = appendExportsOfDeclaration(statements, importClause); + } + const namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 274 /* NamespaceImport */: + statements = appendExportsOfDeclaration(statements, namedBindings); + break; + case 275 /* NamedImports */: + for (const importBinding of namedBindings.elements) { + statements = appendExportsOfDeclaration(statements, importBinding); + } + break; + } + } + return statements; + } + function appendExportsOfImportEqualsDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + return appendExportsOfDeclaration(statements, decl); + } + function appendExportsOfVariableStatement(statements, node, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + for (const decl of node.declarationList.declarations) { + if (decl.initializer || exportSelf) { + statements = appendExportsOfBindingElement(statements, decl, exportSelf); + } + } + return statements; + } + function appendExportsOfBindingElement(statements, decl, exportSelf) { + if (moduleInfo.exportEquals) { + return statements; + } + if (isBindingPattern(decl.name)) { + for (const element of decl.name.elements) { + if (!isOmittedExpression(element)) { + statements = appendExportsOfBindingElement(statements, element, exportSelf); + } + } + } else if (!isGeneratedIdentifier(decl.name)) { + let excludeName; + if (exportSelf) { + statements = appendExportStatement(statements, decl.name, factory2.getLocalName(decl)); + excludeName = idText(decl.name); + } + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfHoistedDeclaration(statements, decl) { + if (moduleInfo.exportEquals) { + return statements; + } + let excludeName; + if (hasSyntacticModifier(decl, 32 /* Export */)) { + const exportName = hasSyntacticModifier(decl, 2048 /* Default */) ? factory2.createStringLiteral("default") : decl.name; + statements = appendExportStatement(statements, exportName, factory2.getLocalName(decl)); + excludeName = getTextOfIdentifierOrLiteral(exportName); + } + if (decl.name) { + statements = appendExportsOfDeclaration(statements, decl, excludeName); + } + return statements; + } + function appendExportsOfDeclaration(statements, decl, excludeName) { + if (moduleInfo.exportEquals) { + return statements; + } + const name = factory2.getDeclarationName(decl); + const exportSpecifiers = moduleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + for (const exportSpecifier of exportSpecifiers) { + if (moduleExportNameTextUnescaped(exportSpecifier.name) !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } + } + return statements; + } + function appendExportStatement(statements, exportName, expression, allowComments) { + statements = append(statements, createExportStatement(exportName, expression, allowComments)); + return statements; + } + function createExportStatement(name, value, allowComments) { + const statement = factory2.createExpressionStatement(createExportExpression(name, value)); + startOnNewLine(statement); + if (!allowComments) { + setEmitFlags(statement, 3072 /* NoComments */); + } + return statement; + } + function createExportExpression(name, value) { + const exportName = isIdentifier(name) ? factory2.createStringLiteralFromNode(name) : name; + setEmitFlags(value, getEmitFlags(value) | 3072 /* NoComments */); + return setCommentRange(factory2.createCallExpression( + exportFunction, + /*typeArguments*/ + void 0, + [exportName, value] + ), value); + } + function topLevelNestedVisitor(node) { + switch (node.kind) { + case 243 /* VariableStatement */: + return visitVariableStatement(node); + case 262 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 263 /* ClassDeclaration */: + return visitClassDeclaration(node); + case 248 /* ForStatement */: + return visitForStatement( + node, + /*isTopLevel*/ + true + ); + case 249 /* ForInStatement */: + return visitForInStatement(node); + case 250 /* ForOfStatement */: + return visitForOfStatement(node); + case 246 /* DoStatement */: + return visitDoStatement(node); + case 247 /* WhileStatement */: + return visitWhileStatement(node); + case 256 /* LabeledStatement */: + return visitLabeledStatement(node); + case 254 /* WithStatement */: + return visitWithStatement(node); + case 245 /* IfStatement */: + return visitIfStatement(node); + case 255 /* SwitchStatement */: + return visitSwitchStatement(node); + case 269 /* CaseBlock */: + return visitCaseBlock(node); + case 296 /* CaseClause */: + return visitCaseClause(node); + case 297 /* DefaultClause */: + return visitDefaultClause(node); + case 258 /* TryStatement */: + return visitTryStatement(node); + case 299 /* CatchClause */: + return visitCatchClause(node); + case 241 /* Block */: + return visitBlock(node); + default: + return visitor(node); + } + } + function visitForStatement(node, isTopLevel) { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = factory2.updateForStatement( + node, + visitNode(node.initializer, isTopLevel ? visitForInitializer : discardedValueVisitor, isForInitializer), + visitNode(node.condition, visitor, isExpression), + visitNode(node.incrementor, discardedValueVisitor, isExpression), + visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) + ); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForInStatement(node) { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = factory2.updateForInStatement( + node, + visitForInitializer(node.initializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitForOfStatement(node) { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = factory2.updateForOfStatement( + node, + node.awaitModifier, + visitForInitializer(node.initializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function shouldHoistForInitializer(node) { + return isVariableDeclarationList(node) && shouldHoistVariableDeclarationList(node); + } + function visitForInitializer(node) { + if (shouldHoistForInitializer(node)) { + let expressions; + for (const variable of node.declarations) { + expressions = append(expressions, transformInitializedVariable( + variable, + /*isExportedDeclaration*/ + false + )); + if (!variable.initializer) { + hoistBindingElement(variable); + } + } + return expressions ? factory2.inlineExpressions(expressions) : factory2.createOmittedExpression(); + } else { + return visitNode(node, discardedValueVisitor, isForInitializer); + } + } + function visitDoStatement(node) { + return factory2.updateDoStatement( + node, + visitIterationBody(node.statement, topLevelNestedVisitor, context), + visitNode(node.expression, visitor, isExpression) + ); + } + function visitWhileStatement(node) { + return factory2.updateWhileStatement( + node, + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitLabeledStatement(node) { + return factory2.updateLabeledStatement( + node, + node.label, + visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ?? factory2.createExpressionStatement(factory2.createIdentifier("")) + ); + } + function visitWithStatement(node) { + return factory2.updateWithStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ?? factory2.createBlock([]), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } + function visitSwitchStatement(node) { + return factory2.updateSwitchStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) + ); + } + function visitCaseBlock(node) { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = factory2.updateCaseBlock( + node, + visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) + ); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitCaseClause(node) { + return factory2.updateCaseClause( + node, + visitNode(node.expression, visitor, isExpression), + visitNodes2(node.statements, topLevelNestedVisitor, isStatement) + ); + } + function visitDefaultClause(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitTryStatement(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitCatchClause(node) { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = factory2.updateCatchClause( + node, + node.variableDeclaration, + Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) + ); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitBlock(node) { + const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; + enclosingBlockScopedContainer = node; + node = visitEachChild(node, topLevelNestedVisitor, context); + enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; + return node; + } + function visitorWorker(node, valueIsDiscarded) { + if (!(node.transformFlags & (4096 /* ContainsDestructuringAssignment */ | 8388608 /* ContainsDynamicImport */ | 268435456 /* ContainsUpdateExpressionForIdentifier */))) { + return node; + } + switch (node.kind) { + case 248 /* ForStatement */: + return visitForStatement( + node, + /*isTopLevel*/ + false + ); + case 244 /* ExpressionStatement */: + return visitExpressionStatement(node); + case 217 /* ParenthesizedExpression */: + return visitParenthesizedExpression(node, valueIsDiscarded); + case 355 /* PartiallyEmittedExpression */: + return visitPartiallyEmittedExpression(node, valueIsDiscarded); + case 226 /* BinaryExpression */: + if (isDestructuringAssignment(node)) { + return visitDestructuringAssignment(node, valueIsDiscarded); + } + break; + case 213 /* CallExpression */: + if (isImportCall(node)) { + return visitImportCallExpression(node); + } + break; + case 224 /* PrefixUnaryExpression */: + case 225 /* PostfixUnaryExpression */: + return visitPrefixOrPostfixUnaryExpression(node, valueIsDiscarded); + } + return visitEachChild(node, visitor, context); + } + function visitor(node) { + return visitorWorker( + node, + /*valueIsDiscarded*/ + false + ); + } + function discardedValueVisitor(node) { + return visitorWorker( + node, + /*valueIsDiscarded*/ + true + ); + } + function visitExpressionStatement(node) { + return factory2.updateExpressionStatement(node, visitNode(node.expression, discardedValueVisitor, isExpression)); + } + function visitParenthesizedExpression(node, valueIsDiscarded) { + return factory2.updateParenthesizedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression)); + } + function visitPartiallyEmittedExpression(node, valueIsDiscarded) { + return factory2.updatePartiallyEmittedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression)); + } + function visitImportCallExpression(node) { + const externalModuleName = getExternalModuleNameLiteral(factory2, node, currentSourceFile, host, resolver, compilerOptions); + const firstArgument = visitNode(firstOrUndefined(node.arguments), visitor, isExpression); + const argument = externalModuleName && (!firstArgument || !isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; + return factory2.createCallExpression( + factory2.createPropertyAccessExpression( + contextObject, + factory2.createIdentifier("import") + ), + /*typeArguments*/ + void 0, + argument ? [argument] : [] + ); + } + function visitDestructuringAssignment(node, valueIsDiscarded) { + if (hasExportedReferenceInDestructuringTarget(node.left)) { + return flattenDestructuringAssignment( + node, + visitor, + context, + 0 /* All */, + !valueIsDiscarded + ); + } + return visitEachChild(node, visitor, context); + } + function hasExportedReferenceInDestructuringTarget(node) { + if (isAssignmentExpression( + node, + /*excludeCompoundAssignment*/ + true + )) { + return hasExportedReferenceInDestructuringTarget(node.left); + } else if (isSpreadElement(node)) { + return hasExportedReferenceInDestructuringTarget(node.expression); + } else if (isObjectLiteralExpression(node)) { + return some(node.properties, hasExportedReferenceInDestructuringTarget); + } else if (isArrayLiteralExpression(node)) { + return some(node.elements, hasExportedReferenceInDestructuringTarget); + } else if (isShorthandPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.name); + } else if (isPropertyAssignment(node)) { + return hasExportedReferenceInDestructuringTarget(node.initializer); + } else if (isIdentifier(node)) { + const container = resolver.getReferencedExportContainer(node); + return container !== void 0 && container.kind === 307 /* SourceFile */; + } else { + return false; + } + } + function visitPrefixOrPostfixUnaryExpression(node, valueIsDiscarded) { + if ((node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) && !isDeclarationNameOfEnumOrNamespace(node.operand)) { + const exportedNames = getExports(node.operand); + if (exportedNames) { + let temp; + let expression = visitNode(node.operand, visitor, isExpression); + if (isPrefixUnaryExpression(node)) { + expression = factory2.updatePrefixUnaryExpression(node, expression); + } else { + expression = factory2.updatePostfixUnaryExpression(node, expression); + if (!valueIsDiscarded) { + temp = factory2.createTempVariable(hoistVariableDeclaration); + expression = factory2.createAssignment(temp, expression); + setTextRange(expression, node); + } + expression = factory2.createComma(expression, factory2.cloneNode(node.operand)); + setTextRange(expression, node); + } + for (const exportName of exportedNames) { + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + if (temp) { + expression = factory2.createComma(expression, temp); + setTextRange(expression, node); + } + return expression; + } + } + return visitEachChild(node, visitor, context); + } + function modifierVisitor(node) { + switch (node.kind) { + case 95 /* ExportKeyword */: + case 90 /* DefaultKeyword */: + return void 0; + } + return node; + } + function onEmitNode(hint, node, emitCallback) { + if (node.kind === 307 /* SourceFile */) { + const id = getOriginalNodeId(node); + currentSourceFile = node; + moduleInfo = moduleInfoMap[id]; + exportFunction = exportFunctionsMap[id]; + noSubstitution = noSubstitutionMap[id]; + contextObject = contextObjectMap[id]; + if (noSubstitution) { + delete noSubstitutionMap[id]; + } + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = void 0; + moduleInfo = void 0; + exportFunction = void 0; + contextObject = void 0; + noSubstitution = void 0; + } else { + previousOnEmitNode(hint, node, emitCallback); + } + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (isSubstitutionPrevented(node)) { + return node; + } + if (hint === 1 /* Expression */) { + return substituteExpression(node); + } else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + function substituteUnspecified(node) { + switch (node.kind) { + case 304 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var _a, _b; + const name = node.name; + if (!isGeneratedIdentifier(name) && !isLocalName(name)) { + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (isImportClause(importDeclaration)) { + return setTextRange( + factory2.createPropertyAssignment( + factory2.cloneNode(name), + factory2.createPropertyAccessExpression( + factory2.getGeneratedNameForNode(importDeclaration.parent), + factory2.createIdentifier("default") + ) + ), + /*location*/ + node + ); + } else if (isImportSpecifier(importDeclaration)) { + const importedName = importDeclaration.propertyName || importDeclaration.name; + const target = factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration); + return setTextRange( + factory2.createPropertyAssignment( + factory2.cloneNode(name), + importedName.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression(target, factory2.cloneNode(importedName)) : factory2.createPropertyAccessExpression(target, factory2.cloneNode(importedName)) + ), + /*location*/ + node + ); + } + } + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 80 /* Identifier */: + return substituteExpressionIdentifier(node); + case 226 /* BinaryExpression */: + return substituteBinaryExpression(node); + case 236 /* MetaProperty */: + return substituteMetaProperty(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var _a, _b; + if (getEmitFlags(node) & 8192 /* HelperName */) { + const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + return factory2.createPropertyAccessExpression(externalHelpersModuleName, node); + } + return node; + } + if (!isGeneratedIdentifier(node) && !isLocalName(node)) { + const importDeclaration = resolver.getReferencedImportDeclaration(node); + if (importDeclaration) { + if (isImportClause(importDeclaration)) { + return setTextRange( + factory2.createPropertyAccessExpression( + factory2.getGeneratedNameForNode(importDeclaration.parent), + factory2.createIdentifier("default") + ), + /*location*/ + node + ); + } else if (isImportSpecifier(importDeclaration)) { + const importedName = importDeclaration.propertyName || importDeclaration.name; + const target = factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration); + return setTextRange( + importedName.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression(target, factory2.cloneNode(importedName)) : factory2.createPropertyAccessExpression(target, factory2.cloneNode(importedName)), + /*location*/ + node + ); + } + } + } + return node; + } + function substituteBinaryExpression(node) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) && !isLocalName(node.left)) { + const exportedNames = getExports(node.left); + if (exportedNames) { + let expression = node; + for (const exportName of exportedNames) { + expression = createExportExpression(exportName, preventSubstitution(expression)); + } + return expression; + } + } + return node; + } + function substituteMetaProperty(node) { + if (isImportMeta(node)) { + return factory2.createPropertyAccessExpression(contextObject, factory2.createIdentifier("meta")); + } + return node; + } + function getExports(name) { + let exportedNames; + const valueDeclaration = getReferencedDeclaration(name); + if (valueDeclaration) { + const exportContainer = resolver.getReferencedExportContainer( + name, + /*prefixLocals*/ + false + ); + if (exportContainer && exportContainer.kind === 307 /* SourceFile */) { + exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); + } + exportedNames = addRange(exportedNames, moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); + } else if (isGeneratedIdentifier(name) && isFileLevelReservedGeneratedIdentifier(name)) { + const exportSpecifiers = moduleInfo == null ? void 0 : moduleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + const exportedNames2 = []; + for (const exportSpecifier of exportSpecifiers) { + exportedNames2.push(exportSpecifier.name); + } + return exportedNames2; + } + } + return exportedNames; + } + function getReferencedDeclaration(name) { + if (!isGeneratedIdentifier(name)) { + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) return importDeclaration; + const valueDeclaration = resolver.getReferencedValueDeclaration(name); + if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) return valueDeclaration; + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) return declaration; + } + } + return valueDeclaration; + } + } + function preventSubstitution(node) { + if (noSubstitution === void 0) noSubstitution = []; + noSubstitution[getNodeId(node)] = true; + return node; + } + function isSubstitutionPrevented(node) { + return noSubstitution && node.id && noSubstitution[node.id]; + } +} + +// src/compiler/transformers/module/esnextAnd2015.ts +function transformECMAScriptModule(context) { + const { + factory: factory2, + getEmitHelperFactory: emitHelpers + } = context; + const host = context.getEmitHost(); + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + const previousOnEmitNode = context.onEmitNode; + const previousOnSubstituteNode = context.onSubstituteNode; + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + context.enableEmitNotification(307 /* SourceFile */); + context.enableSubstitution(80 /* Identifier */); + const noSubstitution = /* @__PURE__ */ new Set(); + let importsAndRequiresToRewriteOrShim; + let helperNameSubstitutions; + let currentSourceFile; + let importRequireStatements; + return chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + if (isExternalModule(node) || getIsolatedModules(compilerOptions)) { + currentSourceFile = node; + importRequireStatements = void 0; + if (compilerOptions.rewriteRelativeImportExtensions && (currentSourceFile.flags & 4194304 /* PossiblyContainsDynamicImport */ || isInJSFile(node))) { + forEachDynamicImportOrRequireCall( + node, + /*includeTypeSpaceImports*/ + false, + /*requireStringLiteralLikeArgument*/ + false, + (node2) => { + if (!isStringLiteralLike(node2.arguments[0]) || shouldRewriteModuleSpecifier(node2.arguments[0].text, compilerOptions)) { + importsAndRequiresToRewriteOrShim = append(importsAndRequiresToRewriteOrShim, node2); + } + } + ); + } + let result = updateExternalModule(node); + addEmitHelpers(result, context.readEmitHelpers()); + currentSourceFile = void 0; + if (importRequireStatements) { + result = factory2.updateSourceFile( + result, + setTextRange(factory2.createNodeArray(insertStatementsAfterCustomPrologue(result.statements.slice(), importRequireStatements)), result.statements) + ); + } + if (!isExternalModule(node) || getEmitModuleKind(compilerOptions) === 200 /* Preserve */ || some(result.statements, isExternalModuleIndicator)) { + return result; + } + return factory2.updateSourceFile( + result, + setTextRange(factory2.createNodeArray([...result.statements, createEmptyExports(factory2)]), result.statements) + ); + } + return node; + } + function updateExternalModule(node) { + const externalHelpersImportDeclaration = createExternalHelpersImportDeclarationIfNeeded(factory2, emitHelpers(), node, compilerOptions); + if (externalHelpersImportDeclaration) { + const statements = []; + const statementOffset = factory2.copyPrologue(node.statements, statements); + addRange(statements, visitArray([externalHelpersImportDeclaration], visitor, isStatement)); + addRange(statements, visitNodes2(node.statements, visitor, isStatement, statementOffset)); + return factory2.updateSourceFile( + node, + setTextRange(factory2.createNodeArray(statements), node.statements) + ); + } else { + return visitEachChild(node, visitor, context); + } + } + function visitor(node) { + switch (node.kind) { + case 271 /* ImportEqualsDeclaration */: + return getEmitModuleKind(compilerOptions) >= 100 /* Node16 */ ? visitImportEqualsDeclaration(node) : void 0; + case 277 /* ExportAssignment */: + return visitExportAssignment(node); + case 278 /* ExportDeclaration */: + const exportDecl = node; + return visitExportDeclaration(exportDecl); + case 272 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 213 /* CallExpression */: + if (node === (importsAndRequiresToRewriteOrShim == null ? void 0 : importsAndRequiresToRewriteOrShim[0])) { + return visitImportOrRequireCall(importsAndRequiresToRewriteOrShim.shift()); + } + // fallthrough + default: + if ((importsAndRequiresToRewriteOrShim == null ? void 0 : importsAndRequiresToRewriteOrShim.length) && rangeContainsRange(node, importsAndRequiresToRewriteOrShim[0])) { + return visitEachChild(node, visitor, context); + } + } + return node; + } + function visitImportDeclaration(node) { + if (!compilerOptions.rewriteRelativeImportExtensions) { + return node; + } + const updatedModuleSpecifier = rewriteModuleSpecifier(node.moduleSpecifier, compilerOptions); + if (updatedModuleSpecifier === node.moduleSpecifier) { + return node; + } + return factory2.updateImportDeclaration( + node, + node.modifiers, + node.importClause, + updatedModuleSpecifier, + node.attributes + ); + } + function visitImportOrRequireCall(node) { + return factory2.updateCallExpression( + node, + node.expression, + node.typeArguments, + [ + isStringLiteralLike(node.arguments[0]) ? rewriteModuleSpecifier(node.arguments[0], compilerOptions) : emitHelpers().createRewriteRelativeImportExtensionsHelper(node.arguments[0]), + ...node.arguments.slice(1) + ] + ); + } + function createRequireCall(importNode) { + const moduleName = getExternalModuleNameLiteral(factory2, importNode, Debug.checkDefined(currentSourceFile), host, resolver, compilerOptions); + const args = []; + if (moduleName) { + args.push(rewriteModuleSpecifier(moduleName, compilerOptions)); + } + if (getEmitModuleKind(compilerOptions) === 200 /* Preserve */) { + return factory2.createCallExpression( + factory2.createIdentifier("require"), + /*typeArguments*/ + void 0, + args + ); + } + if (!importRequireStatements) { + const createRequireName = factory2.createUniqueName("_createRequire", 16 /* Optimistic */ | 32 /* FileLevel */); + const importStatement = factory2.createImportDeclaration( + /*modifiers*/ + void 0, + factory2.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + factory2.createNamedImports([ + factory2.createImportSpecifier( + /*isTypeOnly*/ + false, + factory2.createIdentifier("createRequire"), + createRequireName + ) + ]) + ), + factory2.createStringLiteral("module"), + /*attributes*/ + void 0 + ); + const requireHelperName = factory2.createUniqueName("__require", 16 /* Optimistic */ | 32 /* FileLevel */); + const requireStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + [ + factory2.createVariableDeclaration( + requireHelperName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + factory2.createCallExpression( + factory2.cloneNode(createRequireName), + /*typeArguments*/ + void 0, + [ + factory2.createPropertyAccessExpression(factory2.createMetaProperty(102 /* ImportKeyword */, factory2.createIdentifier("meta")), factory2.createIdentifier("url")) + ] + ) + ) + ], + /*flags*/ + languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ + ) + ); + importRequireStatements = [importStatement, requireStatement]; + } + const name = importRequireStatements[1].declarationList.declarations[0].name; + Debug.assertNode(name, isIdentifier); + return factory2.createCallExpression( + factory2.cloneNode(name), + /*typeArguments*/ + void 0, + args + ); + } + function visitImportEqualsDeclaration(node) { + Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + let statements; + statements = append( + statements, + setOriginalNode( + setTextRange( + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + [ + factory2.createVariableDeclaration( + factory2.cloneNode(node.name), + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + createRequireCall(node) + ) + ], + /*flags*/ + languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ + ) + ), + node + ), + node + ) + ); + statements = appendExportsOfImportEqualsDeclaration(statements, node); + return singleOrMany(statements); + } + function appendExportsOfImportEqualsDeclaration(statements, node) { + if (hasSyntacticModifier(node, 32 /* Export */)) { + statements = append( + statements, + factory2.createExportDeclaration( + /*modifiers*/ + void 0, + node.isTypeOnly, + factory2.createNamedExports([factory2.createExportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + idText(node.name) + )]) + ) + ); + } + return statements; + } + function visitExportAssignment(node) { + if (node.isExportEquals) { + if (getEmitModuleKind(compilerOptions) === 200 /* Preserve */) { + const statement = setOriginalNode( + factory2.createExpressionStatement( + factory2.createAssignment( + factory2.createPropertyAccessExpression( + factory2.createIdentifier("module"), + "exports" + ), + node.expression + ) + ), + node + ); + return statement; + } + return void 0; + } + return node; + } + function visitExportDeclaration(node) { + const updatedModuleSpecifier = rewriteModuleSpecifier(node.moduleSpecifier, compilerOptions); + if (compilerOptions.module !== void 0 && compilerOptions.module > 5 /* ES2015 */ || !node.exportClause || !isNamespaceExport(node.exportClause) || !node.moduleSpecifier) { + return !node.moduleSpecifier || updatedModuleSpecifier === node.moduleSpecifier ? node : factory2.updateExportDeclaration( + node, + node.modifiers, + node.isTypeOnly, + node.exportClause, + updatedModuleSpecifier, + node.attributes + ); + } + const oldIdentifier = node.exportClause.name; + const synthName = factory2.getGeneratedNameForNode(oldIdentifier); + const importDecl = factory2.createImportDeclaration( + /*modifiers*/ + void 0, + factory2.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + factory2.createNamespaceImport( + synthName + ) + ), + updatedModuleSpecifier, + node.attributes + ); + setOriginalNode(importDecl, node.exportClause); + const exportDecl = isExportNamespaceAsDefaultDeclaration(node) ? factory2.createExportDefault(synthName) : factory2.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory2.createNamedExports([factory2.createExportSpecifier( + /*isTypeOnly*/ + false, + synthName, + oldIdentifier + )]) + ); + setOriginalNode(exportDecl, node); + return [importDecl, exportDecl]; + } + function onEmitNode(hint, node, emitCallback) { + if (isSourceFile(node)) { + if ((isExternalModule(node) || getIsolatedModules(compilerOptions)) && compilerOptions.importHelpers) { + helperNameSubstitutions = /* @__PURE__ */ new Map(); + } + currentSourceFile = node; + previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = void 0; + helperNameSubstitutions = void 0; + } else { + previousOnEmitNode(hint, node, emitCallback); + } + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (node.id && noSubstitution.has(node.id)) { + return node; + } + if (isIdentifier(node) && getEmitFlags(node) & 8192 /* HelperName */) { + return substituteHelperName(node); + } + return node; + } + function substituteHelperName(node) { + const externalHelpersModuleName = currentSourceFile && getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + noSubstitution.add(getNodeId(node)); + return factory2.createPropertyAccessExpression(externalHelpersModuleName, node); + } + if (helperNameSubstitutions) { + const name = idText(node); + let substitution = helperNameSubstitutions.get(name); + if (!substitution) { + helperNameSubstitutions.set(name, substitution = factory2.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */)); + } + return substitution; + } + return node; + } +} + +// src/compiler/transformers/module/impliedNodeFormatDependent.ts +function transformImpliedNodeFormatDependentModule(context) { + const previousOnSubstituteNode = context.onSubstituteNode; + const previousOnEmitNode = context.onEmitNode; + const esmTransform = transformECMAScriptModule(context); + const esmOnSubstituteNode = context.onSubstituteNode; + const esmOnEmitNode = context.onEmitNode; + context.onSubstituteNode = previousOnSubstituteNode; + context.onEmitNode = previousOnEmitNode; + const cjsTransform = transformModule(context); + const cjsOnSubstituteNode = context.onSubstituteNode; + const cjsOnEmitNode = context.onEmitNode; + const getEmitModuleFormatOfFile = (file) => context.getEmitHost().getEmitModuleFormatOfFile(file); + context.onSubstituteNode = onSubstituteNode; + context.onEmitNode = onEmitNode; + context.enableSubstitution(307 /* SourceFile */); + context.enableEmitNotification(307 /* SourceFile */); + let currentSourceFile; + return transformSourceFileOrBundle; + function onSubstituteNode(hint, node) { + if (isSourceFile(node)) { + currentSourceFile = node; + return previousOnSubstituteNode(hint, node); + } else { + if (!currentSourceFile) { + return previousOnSubstituteNode(hint, node); + } + if (getEmitModuleFormatOfFile(currentSourceFile) >= 5 /* ES2015 */) { + return esmOnSubstituteNode(hint, node); + } + return cjsOnSubstituteNode(hint, node); + } + } + function onEmitNode(hint, node, emitCallback) { + if (isSourceFile(node)) { + currentSourceFile = node; + } + if (!currentSourceFile) { + return previousOnEmitNode(hint, node, emitCallback); + } + if (getEmitModuleFormatOfFile(currentSourceFile) >= 5 /* ES2015 */) { + return esmOnEmitNode(hint, node, emitCallback); + } + return cjsOnEmitNode(hint, node, emitCallback); + } + function getModuleTransformForFile(file) { + return getEmitModuleFormatOfFile(file) >= 5 /* ES2015 */ ? esmTransform : cjsTransform; + } + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + currentSourceFile = node; + const result = getModuleTransformForFile(node)(node); + currentSourceFile = void 0; + Debug.assert(isSourceFile(result)); + return result; + } + function transformSourceFileOrBundle(node) { + return node.kind === 307 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return context.factory.createBundle(map(node.sourceFiles, transformSourceFile)); + } +} + +// src/compiler/transformers/declarations/diagnostics.ts +function canProduceDiagnostics(node) { + return isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isBindingElement(node) || isSetAccessor(node) || isGetAccessor(node) || isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isParameter(node) || isTypeParameterDeclaration(node) || isExpressionWithTypeArguments(node) || isImportEqualsDeclaration(node) || isTypeAliasDeclaration(node) || isConstructorDeclaration(node) || isIndexSignatureDeclaration(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node) || isBinaryExpression(node) || isJSDocTypeAlias(node); +} +function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (isSetAccessor(node) || isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } else if (isMethodSignature(node) || isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + const diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== void 0 ? { + diagnosticMessage, + errorNode: node, + typeName: node.name + } : void 0; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (isStatic(node)) { + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } else if (node.parent.kind === 263 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } else { + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + const diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== void 0 ? { + diagnosticMessage, + errorNode: node, + typeName: node.name + } : void 0; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (isStatic(node)) { + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } else if (node.parent.kind === 263 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } else { + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } +} +function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node) || isBinaryExpression(node) || isBindingElement(node) || isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } else if (isSetAccessor(node) || isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } else if (isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } else if (isParameter(node)) { + if (isParameterPropertyDeclaration(node, node.parent) && hasSyntacticModifier(node.parent, 2 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } else if (isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } else if (isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } else if (isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } else if (isTypeAliasDeclaration(node) || isJSDocTypeAlias(node)) { + return getTypeAliasDeclarationVisibilityError; + } else { + return Debug.assertNever(node, `Attempted to set a declaration diagnostic context for unhandled node kind: ${Debug.formatSyntaxKind(node.kind)}`); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */) { + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } else if (node.kind === 172 /* PropertyDeclaration */ || node.kind === 211 /* PropertyAccessExpression */ || node.kind === 212 /* ElementAccessExpression */ || node.kind === 226 /* BinaryExpression */ || node.kind === 171 /* PropertySignature */ || node.kind === 169 /* Parameter */ && hasSyntacticModifier(node.parent, 2 /* Private */)) { + if (isStatic(node)) { + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } else if (node.parent.kind === 263 /* ClassDeclaration */ || node.kind === 169 /* Parameter */) { + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } else { + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== void 0 ? { + diagnosticMessage, + errorNode: node, + typeName: node.name + } : void 0; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + let diagnosticMessage; + if (node.kind === 178 /* SetAccessor */) { + if (isStatic(node)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } else { + if (isStatic(node)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage, + errorNode: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + let diagnosticMessage; + switch (node.kind) { + case 180 /* ConstructSignature */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 179 /* CallSignature */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 181 /* IndexSignature */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + if (isStatic(node)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } else if (node.parent.kind === 263 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 262 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + return Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + const diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== void 0 ? { + diagnosticMessage, + errorNode: node, + typeName: node.name + } : void 0; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 176 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 180 /* ConstructSignature */: + case 185 /* ConstructorType */: + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 179 /* CallSignature */: + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 181 /* IndexSignature */: + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + if (isStatic(node.parent)) { + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } else if (node.parent.parent.kind === 263 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } else { + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 262 /* FunctionDeclaration */: + case 184 /* FunctionType */: + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + case 178 /* SetAccessor */: + case 177 /* GetAccessor */: + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; + default: + return Debug.fail(`Unknown parent for parameter: ${Debug.formatSyntaxKind(node.parent.kind)}`); + } + } + function getTypeParameterConstraintVisibilityError() { + let diagnosticMessage; + switch (node.parent.kind) { + case 263 /* ClassDeclaration */: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 264 /* InterfaceDeclaration */: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 200 /* MappedType */: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; + break; + case 185 /* ConstructorType */: + case 180 /* ConstructSignature */: + diagnosticMessage = Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 179 /* CallSignature */: + diagnosticMessage = Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + if (isStatic(node.parent)) { + diagnosticMessage = Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } else if (node.parent.parent.kind === 263 /* ClassDeclaration */) { + diagnosticMessage = Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } else { + diagnosticMessage = Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 184 /* FunctionType */: + case 262 /* FunctionDeclaration */: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 195 /* InferType */: + diagnosticMessage = Diagnostics.Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1; + break; + case 265 /* TypeAliasDeclaration */: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + return Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + let diagnosticMessage; + if (isClassDeclaration(node.parent.parent)) { + diagnosticMessage = isHeritageClause(node.parent) && node.parent.token === 119 /* ImplementsKeyword */ ? Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : node.parent.parent.name ? Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 : Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0; + } else { + diagnosticMessage = Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage, + errorNode: node, + typeName: getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { + return { + diagnosticMessage: symbolAccessibilityResult.errorModuleName ? Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 : Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: isJSDocTypeAlias(node) ? Debug.checkDefined(node.typeExpression) : node.type, + typeName: isJSDocTypeAlias(node) ? getNameOfDeclaration(node) : node.name + }; + } +} +function createGetIsolatedDeclarationErrors(resolver) { + const relatedSuggestionByDeclarationKind = { + [219 /* ArrowFunction */]: Diagnostics.Add_a_return_type_to_the_function_expression, + [218 /* FunctionExpression */]: Diagnostics.Add_a_return_type_to_the_function_expression, + [174 /* MethodDeclaration */]: Diagnostics.Add_a_return_type_to_the_method, + [177 /* GetAccessor */]: Diagnostics.Add_a_return_type_to_the_get_accessor_declaration, + [178 /* SetAccessor */]: Diagnostics.Add_a_type_to_parameter_of_the_set_accessor_declaration, + [262 /* FunctionDeclaration */]: Diagnostics.Add_a_return_type_to_the_function_declaration, + [180 /* ConstructSignature */]: Diagnostics.Add_a_return_type_to_the_function_declaration, + [169 /* Parameter */]: Diagnostics.Add_a_type_annotation_to_the_parameter_0, + [260 /* VariableDeclaration */]: Diagnostics.Add_a_type_annotation_to_the_variable_0, + [172 /* PropertyDeclaration */]: Diagnostics.Add_a_type_annotation_to_the_property_0, + [171 /* PropertySignature */]: Diagnostics.Add_a_type_annotation_to_the_property_0, + [277 /* ExportAssignment */]: Diagnostics.Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it + }; + const errorByDeclarationKind = { + [218 /* FunctionExpression */]: Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, + [262 /* FunctionDeclaration */]: Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, + [219 /* ArrowFunction */]: Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, + [174 /* MethodDeclaration */]: Diagnostics.Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, + [180 /* ConstructSignature */]: Diagnostics.Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, + [177 /* GetAccessor */]: Diagnostics.At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations, + [178 /* SetAccessor */]: Diagnostics.At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations, + [169 /* Parameter */]: Diagnostics.Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations, + [260 /* VariableDeclaration */]: Diagnostics.Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations, + [172 /* PropertyDeclaration */]: Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations, + [171 /* PropertySignature */]: Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations, + [167 /* ComputedPropertyName */]: Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations, + [305 /* SpreadAssignment */]: Diagnostics.Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations, + [304 /* ShorthandPropertyAssignment */]: Diagnostics.Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations, + [209 /* ArrayLiteralExpression */]: Diagnostics.Only_const_arrays_can_be_inferred_with_isolatedDeclarations, + [277 /* ExportAssignment */]: Diagnostics.Default_exports_can_t_be_inferred_with_isolatedDeclarations, + [230 /* SpreadElement */]: Diagnostics.Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations + }; + return getDiagnostic; + function getDiagnostic(node) { + const heritageClause = findAncestor(node, isHeritageClause); + if (heritageClause) { + return createDiagnosticForNode(node, Diagnostics.Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations); + } + if ((isPartOfTypeNode(node) || isTypeQueryNode(node.parent)) && (isEntityName(node) || isEntityNameExpression(node))) { + return createEntityInTypeNodeError(node); + } + Debug.type(node); + switch (node.kind) { + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return createAccessorTypeError(node); + case 167 /* ComputedPropertyName */: + case 304 /* ShorthandPropertyAssignment */: + case 305 /* SpreadAssignment */: + return createObjectLiteralError(node); + case 209 /* ArrayLiteralExpression */: + case 230 /* SpreadElement */: + return createArrayLiteralError(node); + case 174 /* MethodDeclaration */: + case 180 /* ConstructSignature */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 262 /* FunctionDeclaration */: + return createReturnTypeError(node); + case 208 /* BindingElement */: + return createBindingElementError(node); + case 172 /* PropertyDeclaration */: + case 260 /* VariableDeclaration */: + return createVariableOrPropertyError(node); + case 169 /* Parameter */: + return createParameterError(node); + case 303 /* PropertyAssignment */: + return createExpressionError(node.initializer); + case 231 /* ClassExpression */: + return createClassExpressionError(node); + default: + assertType(node); + return createExpressionError(node); + } + } + function findNearestDeclaration(node) { + const result = findAncestor(node, (n) => isExportAssignment(n) || isStatement(n) || isVariableDeclaration(n) || isPropertyDeclaration(n) || isParameter(n)); + if (!result) return void 0; + if (isExportAssignment(result)) return result; + if (isReturnStatement(result)) { + return findAncestor(result, (n) => isFunctionLikeDeclaration(n) && !isConstructorDeclaration(n)); + } + return isStatement(result) ? void 0 : result; + } + function createAccessorTypeError(node) { + const { getAccessor, setAccessor } = getAllAccessorDeclarations(node.symbol.declarations, node); + const targetNode = (isSetAccessor(node) ? node.parameters[0] : node) ?? node; + const diag2 = createDiagnosticForNode(targetNode, errorByDeclarationKind[node.kind]); + if (setAccessor) { + addRelatedInfo(diag2, createDiagnosticForNode(setAccessor, relatedSuggestionByDeclarationKind[setAccessor.kind])); + } + if (getAccessor) { + addRelatedInfo(diag2, createDiagnosticForNode(getAccessor, relatedSuggestionByDeclarationKind[getAccessor.kind])); + } + return diag2; + } + function addParentDeclarationRelatedInfo(node, diag2) { + const parentDeclaration = findNearestDeclaration(node); + if (parentDeclaration) { + const targetStr = isExportAssignment(parentDeclaration) || !parentDeclaration.name ? "" : getTextOfNode( + parentDeclaration.name, + /*includeTrivia*/ + false + ); + addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr)); + } + return diag2; + } + function createObjectLiteralError(node) { + const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); + addParentDeclarationRelatedInfo(node, diag2); + return diag2; + } + function createArrayLiteralError(node) { + const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); + addParentDeclarationRelatedInfo(node, diag2); + return diag2; + } + function createReturnTypeError(node) { + const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); + addParentDeclarationRelatedInfo(node, diag2); + addRelatedInfo(diag2, createDiagnosticForNode(node, relatedSuggestionByDeclarationKind[node.kind])); + return diag2; + } + function createBindingElementError(node) { + return createDiagnosticForNode(node, Diagnostics.Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations); + } + function createVariableOrPropertyError(node) { + const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); + const targetStr = getTextOfNode( + node.name, + /*includeTrivia*/ + false + ); + addRelatedInfo(diag2, createDiagnosticForNode(node, relatedSuggestionByDeclarationKind[node.kind], targetStr)); + return diag2; + } + function createParameterError(node) { + if (isSetAccessor(node.parent)) { + return createAccessorTypeError(node.parent); + } + const addUndefined = resolver.requiresAddingImplicitUndefined(node, node.parent); + if (!addUndefined && node.initializer) { + return createExpressionError(node.initializer); + } + const message = addUndefined ? Diagnostics.Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_supported_with_isolatedDeclarations : errorByDeclarationKind[node.kind]; + const diag2 = createDiagnosticForNode(node, message); + const targetStr = getTextOfNode( + node.name, + /*includeTrivia*/ + false + ); + addRelatedInfo(diag2, createDiagnosticForNode(node, relatedSuggestionByDeclarationKind[node.kind], targetStr)); + return diag2; + } + function createClassExpressionError(node) { + return createExpressionError(node, Diagnostics.Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations); + } + function createEntityInTypeNodeError(node) { + const diag2 = createDiagnosticForNode(node, Diagnostics.Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations, getTextOfNode( + node, + /*includeTrivia*/ + false + )); + addParentDeclarationRelatedInfo(node, diag2); + return diag2; + } + function createExpressionError(node, diagnosticMessage) { + const parentDeclaration = findNearestDeclaration(node); + let diag2; + if (parentDeclaration) { + const targetStr = isExportAssignment(parentDeclaration) || !parentDeclaration.name ? "" : getTextOfNode( + parentDeclaration.name, + /*includeTrivia*/ + false + ); + const parent = findAncestor(node.parent, (n) => isExportAssignment(n) || (isStatement(n) ? "quit" : !isParenthesizedExpression(n) && !isTypeAssertionExpression(n) && !isAsExpression(n))); + if (parentDeclaration === parent) { + diag2 = createDiagnosticForNode(node, diagnosticMessage ?? errorByDeclarationKind[parentDeclaration.kind]); + addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr)); + } else { + diag2 = createDiagnosticForNode(node, diagnosticMessage ?? Diagnostics.Expression_type_can_t_be_inferred_with_isolatedDeclarations); + addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr)); + addRelatedInfo(diag2, createDiagnosticForNode(node, Diagnostics.Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit)); + } + } else { + diag2 = createDiagnosticForNode(node, diagnosticMessage ?? Diagnostics.Expression_type_can_t_be_inferred_with_isolatedDeclarations); + } + return diag2; + } +} + +// src/compiler/transformers/declarations.ts +function getDeclarationDiagnostics(host, resolver, file) { + const compilerOptions = host.getCompilerOptions(); + const files = filter(getSourceFilesToEmit(host, file), isSourceFileNotJson); + return contains(files, file) ? transformNodes( + resolver, + host, + factory, + compilerOptions, + [file], + [transformDeclarations], + /*allowDtsFiles*/ + false + ).diagnostics : void 0; +} +var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; +var declarationEmitInternalNodeBuilderFlags = 8 /* AllowUnresolvedNames */; +function transformDeclarations(context) { + const throwDiagnostic = () => Debug.fail("Diagnostic emitted without context"); + let getSymbolAccessibilityDiagnostic = throwDiagnostic; + let needsDeclare = true; + let isBundledEmit = false; + let resultHasExternalModuleIndicator = false; + let needsScopeFixMarker = false; + let resultHasScopeMarker = false; + let enclosingDeclaration; + let lateMarkedStatements; + let lateStatementReplacementMap; + let suppressNewDiagnosticContexts; + const { factory: factory2 } = context; + const host = context.getEmitHost(); + let restoreFallbackNode = () => void 0; + const symbolTracker = { + trackSymbol, + reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError, + reportCyclicStructureError, + reportPrivateInBaseOfClassExpression, + reportLikelyUnsafeImportRequiredError, + reportTruncationError, + moduleResolverHost: host, + reportNonlocalAugmentation, + reportNonSerializableProperty, + reportInferenceFallback, + pushErrorFallbackNode(node) { + const currentFallback = errorFallbackNode; + const currentRestore = restoreFallbackNode; + restoreFallbackNode = () => { + restoreFallbackNode = currentRestore; + errorFallbackNode = currentFallback; + }; + errorFallbackNode = node; + }, + popErrorFallbackNode() { + restoreFallbackNode(); + } + }; + let errorNameNode; + let errorFallbackNode; + let currentSourceFile; + let rawReferencedFiles; + let rawTypeReferenceDirectives; + let rawLibReferenceDirectives; + const resolver = context.getEmitResolver(); + const options = context.getCompilerOptions(); + const getIsolatedDeclarationError = createGetIsolatedDeclarationErrors(resolver); + const { stripInternal, isolatedDeclarations } = options; + return transformRoot; + function reportExpandoFunctionErrors(node) { + resolver.getPropertiesOfContainerFunction(node).forEach((p) => { + if (isExpandoPropertyDeclaration(p.valueDeclaration)) { + const errorTarget = isBinaryExpression(p.valueDeclaration) ? p.valueDeclaration.left : p.valueDeclaration; + context.addDiagnostic(createDiagnosticForNode( + errorTarget, + Diagnostics.Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations_Add_an_explicit_declaration_for_the_properties_assigned_to_this_function + )); + } + }); + } + function reportInferenceFallback(node) { + if (!isolatedDeclarations || isSourceFileJS(currentSourceFile)) return; + if (getSourceFileOfNode(node) !== currentSourceFile) return; + if (isVariableDeclaration(node) && resolver.isExpandoFunctionDeclaration(node)) { + reportExpandoFunctionErrors(node); + } else { + context.addDiagnostic(getIsolatedDeclarationError(node)); + } + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + if (symbolAccessibilityResult.aliasesToMakeVisible) { + if (!lateMarkedStatements) { + lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible; + } else { + for (const ref of symbolAccessibilityResult.aliasesToMakeVisible) { + pushIfUnique(lateMarkedStatements, ref); + } + } + } + } else if (symbolAccessibilityResult.accessibility !== 3 /* NotResolved */) { + const errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } else { + context.addDiagnostic(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + return true; + } + } + return false; + } + function trackSymbol(symbol, enclosingDeclaration2, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) return false; + const issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible( + symbol, + enclosingDeclaration2, + meaning, + /*shouldComputeAliasToMarkVisible*/ + true + )); + return issuedDiagnostic; + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic( + addRelatedInfo( + createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected, propertyName), + ...isVariableDeclaration((errorNameNode || errorFallbackNode).parent) ? [createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Add_a_type_annotation_to_the_variable_0, errorDeclarationNameWithFallback())] : [] + ) + ); + } + } + function errorDeclarationNameWithFallback() { + return errorNameNode ? declarationNameToString(errorNameNode) : errorFallbackNode && getNameOfDeclaration(errorFallbackNode) ? declarationNameToString(getNameOfDeclaration(errorFallbackNode)) : errorFallbackNode && isExportAssignment(errorFallbackNode) ? errorFallbackNode.isExportEquals ? "export=" : "default" : "(Missing)"; + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), "unique symbol")); + } + } + function reportCyclicStructureError() { + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary, errorDeclarationNameWithFallback())); + } + } + function reportInaccessibleThisError() { + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), "this")); + } + } + function reportLikelyUnsafeImportRequiredError(specifier) { + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), specifier)); + } + } + function reportTruncationError() { + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + } + } + function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { + var _a; + const primaryDeclaration = (_a = parentSymbol.declarations) == null ? void 0 : _a.find((d) => getSourceFileOfNode(d) === containingFile); + const augmentingDeclarations = filter(symbol.declarations, (d) => getSourceFileOfNode(d) !== containingFile); + if (primaryDeclaration && augmentingDeclarations) { + for (const augmentations of augmentingDeclarations) { + context.addDiagnostic(addRelatedInfo( + createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), + createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file) + )); + } + } + } + function reportNonSerializableProperty(propertyName) { + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName)); + } + } + function transformDeclarationsForJS(sourceFile) { + const oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = (s) => s.errorNode && canProduceDiagnostics(s.errorNode) ? createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : { + diagnosticMessage: s.errorModuleName ? Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, + errorNode: s.errorNode || sourceFile + }; + const result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); + getSymbolAccessibilityDiagnostic = oldDiag; + return result; + } + function transformRoot(node) { + if (node.kind === 307 /* SourceFile */ && node.isDeclarationFile) { + return node; + } + if (node.kind === 308 /* Bundle */) { + isBundledEmit = true; + rawReferencedFiles = []; + rawTypeReferenceDirectives = []; + rawLibReferenceDirectives = []; + let hasNoDefaultLib = false; + const bundle = factory2.createBundle( + map(node.sourceFiles, (sourceFile) => { + if (sourceFile.isDeclarationFile) return void 0; + hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = void 0; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = /* @__PURE__ */ new Map(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectFileReferences(sourceFile); + if (isExternalOrCommonJsModule(sourceFile) || isJsonSourceFile(sourceFile)) { + resultHasExternalModuleIndicator = false; + needsDeclare = false; + const statements = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement); + const newFile = factory2.updateSourceFile( + sourceFile, + [factory2.createModuleDeclaration( + [factory2.createModifier(138 /* DeclareKeyword */)], + factory2.createStringLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), + factory2.createModuleBlock(setTextRange(factory2.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)) + )], + /*isDeclarationFile*/ + true, + /*referencedFiles*/ + [], + /*typeReferences*/ + [], + /*hasNoDefaultLib*/ + false, + /*libReferences*/ + [] + ); + return newFile; + } + needsDeclare = true; + const updated = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement); + return factory2.updateSourceFile( + sourceFile, + transformAndReplaceLatePaintedStatements(updated), + /*isDeclarationFile*/ + true, + /*referencedFiles*/ + [], + /*typeReferences*/ + [], + /*hasNoDefaultLib*/ + false, + /*libReferences*/ + [] + ); + }) + ); + const outputFilePath2 = getDirectoryPath(normalizeSlashes(getOutputPathsFor( + node, + host, + /*forceDtsPaths*/ + true + ).declarationFilePath)); + bundle.syntheticFileReferences = getReferencedFiles(outputFilePath2); + bundle.syntheticTypeReferences = getTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib; + return bundle; + } + needsDeclare = true; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + lateMarkedStatements = void 0; + lateStatementReplacementMap = /* @__PURE__ */ new Map(); + rawReferencedFiles = []; + rawTypeReferenceDirectives = []; + rawLibReferenceDirectives = []; + collectFileReferences(currentSourceFile); + let combinedStatements; + if (isSourceFileJS(currentSourceFile)) { + combinedStatements = factory2.createNodeArray(transformDeclarationsForJS(node)); + } else { + const statements = visitNodes2(node.statements, visitDeclarationStatements, isStatement); + combinedStatements = setTextRange(factory2.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + if (isExternalModule(node) && (!resultHasExternalModuleIndicator || needsScopeFixMarker && !resultHasScopeMarker)) { + combinedStatements = setTextRange(factory2.createNodeArray([...combinedStatements, createEmptyExports(factory2)]), combinedStatements); + } + } + const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor( + node, + host, + /*forceDtsPaths*/ + true + ).declarationFilePath)); + return factory2.updateSourceFile( + node, + combinedStatements, + /*isDeclarationFile*/ + true, + getReferencedFiles(outputFilePath), + getTypeReferences(), + node.hasNoDefaultLib, + getLibReferences() + ); + function collectFileReferences(sourceFile) { + rawReferencedFiles = concatenate(rawReferencedFiles, map(sourceFile.referencedFiles, (f) => [sourceFile, f])); + rawTypeReferenceDirectives = concatenate(rawTypeReferenceDirectives, sourceFile.typeReferenceDirectives); + rawLibReferenceDirectives = concatenate(rawLibReferenceDirectives, sourceFile.libReferenceDirectives); + } + function copyFileReferenceAsSynthetic(ref) { + const newRef = { ...ref }; + newRef.pos = -1; + newRef.end = -1; + return newRef; + } + function getTypeReferences() { + return mapDefined(rawTypeReferenceDirectives, (ref) => { + if (!ref.preserve) return void 0; + return copyFileReferenceAsSynthetic(ref); + }); + } + function getLibReferences() { + return mapDefined(rawLibReferenceDirectives, (ref) => { + if (!ref.preserve) return void 0; + return copyFileReferenceAsSynthetic(ref); + }); + } + function getReferencedFiles(outputFilePath2) { + return mapDefined(rawReferencedFiles, ([sourceFile, ref]) => { + if (!ref.preserve) return void 0; + const file = host.getSourceFileFromReference(sourceFile, ref); + if (!file) { + return void 0; + } + let declFileName; + if (file.isDeclarationFile) { + declFileName = file.fileName; + } else { + if (isBundledEmit && contains(node.sourceFiles, file)) return; + const paths = getOutputPathsFor( + file, + host, + /*forceDtsPaths*/ + true + ); + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; + } + if (!declFileName) return void 0; + const fileName = getRelativePathToDirectoryOrUrl( + outputFilePath2, + declFileName, + host.getCurrentDirectory(), + host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ + false + ); + const newRef = copyFileReferenceAsSynthetic(ref); + newRef.fileName = fileName; + return newRef; + }); + } + } + function filterBindingPatternInitializers(name) { + if (name.kind === 80 /* Identifier */) { + return name; + } else { + if (name.kind === 207 /* ArrayBindingPattern */) { + return factory2.updateArrayBindingPattern(name, visitNodes2(name.elements, visitBindingElement, isArrayBindingElement)); + } else { + return factory2.updateObjectBindingPattern(name, visitNodes2(name.elements, visitBindingElement, isBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 232 /* OmittedExpression */) { + return elem; + } + if (elem.propertyName && isComputedPropertyName(elem.propertyName) && isEntityNameExpression(elem.propertyName.expression)) { + checkEntityNameVisibility(elem.propertyName.expression, enclosingDeclaration); + } + return factory2.updateBindingElement( + elem, + elem.dotDotDotToken, + elem.propertyName, + filterBindingPatternInitializers(elem.name), + /*initializer*/ + void 0 + ); + } + } + function ensureParameter(p, modifierMask) { + let oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p); + } + const newParam = factory2.updateParameterDeclaration( + p, + maskModifiers(factory2, p, modifierMask), + p.dotDotDotToken, + filterBindingPatternInitializers(p.name), + resolver.isOptionalParameter(p) ? p.questionToken || factory2.createToken(58 /* QuestionToken */) : void 0, + ensureType( + p, + /*ignorePrivate*/ + true + ), + // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p) + ); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && !!node.initializer && resolver.isLiteralConstDeclaration(getParseTreeNode(node)); + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + const unwrappedInitializer = unwrapParenthesizedExpression(node.initializer); + if (!isPrimitiveLiteralValue(unwrappedInitializer)) { + reportInferenceFallback(node); + } + return resolver.createLiteralConstValue(getParseTreeNode(node, canHaveLiteralInitializer), symbolTracker); + } + return void 0; + } + function ensureType(node, ignorePrivate) { + if (!ignorePrivate && hasEffectiveModifier(node, 2 /* Private */)) { + return; + } + if (shouldPrintWithInitializer(node)) { + return; + } + if (!isExportAssignment(node) && !isBindingElement(node) && node.type && (!isParameter(node) || !resolver.requiresAddingImplicitUndefined(node, enclosingDeclaration))) { + return visitNode(node.type, visitDeclarationSubtree, isTypeNode); + } + const oldErrorNameNode = errorNameNode; + errorNameNode = node.name; + let oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + if (canProduceDiagnostics(node)) { + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(node); + } + } + let typeNode; + if (hasInferredType(node)) { + typeNode = resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); + } else if (isFunctionLike(node)) { + typeNode = resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); + } else { + Debug.assertNever(node); + } + errorNameNode = oldErrorNameNode; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return typeNode ?? factory2.createKeywordTypeNode(133 /* AnyKeyword */); + } + function isDeclarationAndNotVisible(node) { + node = getParseTreeNode(node); + switch (node.kind) { + case 262 /* FunctionDeclaration */: + case 267 /* ModuleDeclaration */: + case 264 /* InterfaceDeclaration */: + case 263 /* ClassDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 266 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 260 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 271 /* ImportEqualsDeclaration */: + case 272 /* ImportDeclaration */: + case 278 /* ExportDeclaration */: + case 277 /* ExportAssignment */: + return false; + case 175 /* ClassStaticBlockDeclaration */: + return true; + } + return false; + } + function shouldEmitFunctionProperties(input) { + var _a; + if (input.body) { + return true; + } + const overloadSignatures = (_a = input.symbol.declarations) == null ? void 0 : _a.filter((decl) => isFunctionDeclaration(decl) && !decl.body); + return !overloadSignatures || overloadSignatures.indexOf(input) === overloadSignatures.length - 1; + } + function getBindingNameVisible(elem) { + if (isOmittedExpression(elem)) { + return false; + } + if (isBindingPattern(elem.name)) { + return some(elem.name.elements, getBindingNameVisible); + } else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (hasEffectiveModifier(node, 2 /* Private */)) { + return factory2.createNodeArray(); + } + const newParams = map(params, (p) => ensureParameter(p, modifierMask)); + if (!newParams) { + return factory2.createNodeArray(); + } + return factory2.createNodeArray(newParams, params.hasTrailingComma); + } + function updateAccessorParamsList(input, isPrivate) { + let newParams; + if (!isPrivate) { + const thisParameter = getThisParameter(input); + if (thisParameter) { + newParams = [ensureParameter(thisParameter)]; + } + } + if (isSetAccessorDeclaration(input)) { + let newValueParameter; + if (!isPrivate) { + const valueParameter = getSetAccessorValueParameter(input); + if (valueParameter) { + newValueParameter = ensureParameter(valueParameter); + } + } + if (!newValueParameter) { + newValueParameter = factory2.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "value" + ); + } + newParams = append(newParams, newValueParameter); + } + return factory2.createNodeArray(newParams || emptyArray); + } + function ensureTypeParams(node, params) { + return hasEffectiveModifier(node, 2 /* Private */) ? void 0 : visitNodes2(params, visitDeclarationSubtree, isTypeParameterDeclaration); + } + function isEnclosingDeclaration(node) { + return isSourceFile(node) || isTypeAliasDeclaration(node) || isModuleDeclaration(node) || isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionLike(node) || isIndexSignatureDeclaration(node) || isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration2) { + const visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration2); + handleSymbolAccessibilityError(visibilityResult); + } + function preserveJsDoc(updated, original) { + if (hasJSDocNodes(updated) && hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return setCommentRange(updated, getCommentRange(original)); + } + function rewriteModuleSpecifier2(parent, input) { + if (!input) return void 0; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 267 /* ModuleDeclaration */ && parent.kind !== 205 /* ImportType */; + if (isStringLiteralLike(input)) { + if (isBundledEmit) { + const newName = getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return factory2.createStringLiteral(newName); + } + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) return; + if (decl.moduleReference.kind === 283 /* ExternalModuleReference */) { + const specifier = getExternalModuleImportEqualsDeclarationExpression(decl); + return factory2.updateImportEqualsDeclaration( + decl, + decl.modifiers, + decl.isTypeOnly, + decl.name, + factory2.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier2(decl, specifier)) + ); + } else { + const oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + return factory2.updateImportDeclaration( + decl, + decl.modifiers, + decl.importClause, + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), + tryGetResolutionModeOverride(decl.attributes) + ); + } + const visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : void 0; + if (!decl.importClause.namedBindings) { + return visibleDefaultBinding && factory2.updateImportDeclaration( + decl, + decl.modifiers, + factory2.updateImportClause( + decl.importClause, + decl.importClause.isTypeOnly, + visibleDefaultBinding, + /*namedBindings*/ + void 0 + ), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), + tryGetResolutionModeOverride(decl.attributes) + ); + } + if (decl.importClause.namedBindings.kind === 274 /* NamespaceImport */) { + const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : ( + /*namedBindings*/ + void 0 + ); + return visibleDefaultBinding || namedBindings ? factory2.updateImportDeclaration( + decl, + decl.modifiers, + factory2.updateImportClause( + decl.importClause, + decl.importClause.isTypeOnly, + visibleDefaultBinding, + namedBindings + ), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), + tryGetResolutionModeOverride(decl.attributes) + ) : void 0; + } + const bindingList = mapDefined(decl.importClause.namedBindings.elements, (b) => resolver.isDeclarationVisible(b) ? b : void 0); + if (bindingList && bindingList.length || visibleDefaultBinding) { + return factory2.updateImportDeclaration( + decl, + decl.modifiers, + factory2.updateImportClause( + decl.importClause, + decl.importClause.isTypeOnly, + visibleDefaultBinding, + bindingList && bindingList.length ? factory2.updateNamedImports(decl.importClause.namedBindings, bindingList) : void 0 + ), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), + tryGetResolutionModeOverride(decl.attributes) + ); + } + if (resolver.isImportRequiredByAugmentation(decl)) { + if (isolatedDeclarations) { + context.addDiagnostic(createDiagnosticForNode(decl, Diagnostics.Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_supported_with_isolatedDeclarations)); + } + return factory2.updateImportDeclaration( + decl, + decl.modifiers, + /*importClause*/ + void 0, + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), + tryGetResolutionModeOverride(decl.attributes) + ); + } + } + function tryGetResolutionModeOverride(node) { + const mode = getResolutionModeOverride(node); + return node && mode !== void 0 ? node : void 0; + } + function transformAndReplaceLatePaintedStatements(statements) { + while (length(lateMarkedStatements)) { + const i = lateMarkedStatements.shift(); + if (!isLateVisibilityPaintedStatement(i)) { + return Debug.fail(`Late replaced statement was found which is not handled by the declaration transformer!: ${Debug.formatSyntaxKind(i.kind)}`); + } + const priorNeedsDeclare = needsDeclare; + needsDeclare = i.parent && isSourceFile(i.parent) && !(isExternalModule(i.parent) && isBundledEmit); + const result = transformTopLevelDeclaration(i); + needsDeclare = priorNeedsDeclare; + lateStatementReplacementMap.set(getOriginalNodeId(i), result); + } + return visitNodes2(statements, visitLateVisibilityMarkedStatements, isStatement); + function visitLateVisibilityMarkedStatements(statement) { + if (isLateVisibilityPaintedStatement(statement)) { + const key = getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + const result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result) { + if (isArray(result) ? some(result, needsScopeMarker) : needsScopeMarker(result)) { + needsScopeFixMarker = true; + } + if (isSourceFile(statement.parent) && (isArray(result) ? some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result))) { + resultHasExternalModuleIndicator = true; + } + } + return result; + } + } + return statement; + } + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) return; + if (isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) return; + if (hasDynamicName(input)) { + if (isolatedDeclarations) { + if (!resolver.isDefinitelyReferenceToGlobalSymbolObject(input.name.expression)) { + if (isClassDeclaration(input.parent) || isObjectLiteralExpression(input.parent)) { + context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations)); + return; + } else if ( + // Type declarations just need to double-check that the input computed name is an entity name expression + (isInterfaceDeclaration(input.parent) || isTypeLiteralNode(input.parent)) && !isEntityNameExpression(input.name.expression) + ) { + context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations)); + return; + } + } + } else if (!resolver.isLateBound(getParseTreeNode(input)) || !isEntityNameExpression(input.name.expression)) { + return; + } + } + } + if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return; + if (isSemicolonClassElement(input)) return; + let previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + const oldDiag = getSymbolAccessibilityDiagnostic; + const canProduceDiagnostic = canProduceDiagnostics(input); + const oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + let shouldEnterSuppressNewDiagnosticsContextContext = (input.kind === 187 /* TypeLiteral */ || input.kind === 200 /* MappedType */) && input.parent.kind !== 265 /* TypeAliasDeclaration */; + if (isMethodDeclaration(input) || isMethodSignature(input)) { + if (hasEffectiveModifier(input, 2 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; + return cleanup(factory2.createPropertyDeclaration( + ensureModifiers(input), + input.name, + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + )); + } + } + if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 233 /* ExpressionWithTypeArguments */: { + if (isEntityName(input.expression) || isEntityNameExpression(input.expression)) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + const node = visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(factory2.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); + } + case 183 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + const node = visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(factory2.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); + } + case 180 /* ConstructSignature */: + return cleanup(factory2.updateConstructSignature( + input, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input) + )); + case 176 /* Constructor */: { + const ctor = factory2.createConstructorDeclaration( + /*modifiers*/ + ensureModifiers(input), + updateParamsList(input, input.parameters, 0 /* None */), + /*body*/ + void 0 + ); + return cleanup(ctor); + } + case 174 /* MethodDeclaration */: { + if (isPrivateIdentifier(input.name)) { + return cleanup( + /*returnValue*/ + void 0 + ); + } + const sig = factory2.createMethodDeclaration( + ensureModifiers(input), + /*asteriskToken*/ + void 0, + input.name, + input.questionToken, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input), + /*body*/ + void 0 + ); + return cleanup(sig); + } + case 177 /* GetAccessor */: { + if (isPrivateIdentifier(input.name)) { + return cleanup( + /*returnValue*/ + void 0 + ); + } + return cleanup(factory2.updateGetAccessorDeclaration( + input, + ensureModifiers(input), + input.name, + updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)), + ensureType(input), + /*body*/ + void 0 + )); + } + case 178 /* SetAccessor */: { + if (isPrivateIdentifier(input.name)) { + return cleanup( + /*returnValue*/ + void 0 + ); + } + return cleanup(factory2.updateSetAccessorDeclaration( + input, + ensureModifiers(input), + input.name, + updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)), + /*body*/ + void 0 + )); + } + case 172 /* PropertyDeclaration */: + if (isPrivateIdentifier(input.name)) { + return cleanup( + /*returnValue*/ + void 0 + ); + } + return cleanup(factory2.updatePropertyDeclaration( + input, + ensureModifiers(input), + input.name, + input.questionToken, + ensureType(input), + ensureNoInitializer(input) + )); + case 171 /* PropertySignature */: + if (isPrivateIdentifier(input.name)) { + return cleanup( + /*returnValue*/ + void 0 + ); + } + return cleanup(factory2.updatePropertySignature( + input, + ensureModifiers(input), + input.name, + input.questionToken, + ensureType(input) + )); + case 173 /* MethodSignature */: { + if (isPrivateIdentifier(input.name)) { + return cleanup( + /*returnValue*/ + void 0 + ); + } + return cleanup(factory2.updateMethodSignature( + input, + ensureModifiers(input), + input.name, + input.questionToken, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input) + )); + } + case 179 /* CallSignature */: { + return cleanup( + factory2.updateCallSignature( + input, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input) + ) + ); + } + case 181 /* IndexSignature */: { + return cleanup(factory2.updateIndexSignature( + input, + ensureModifiers(input), + updateParamsList(input, input.parameters), + visitNode(input.type, visitDeclarationSubtree, isTypeNode) || factory2.createKeywordTypeNode(133 /* AnyKeyword */) + )); + } + case 260 /* VariableDeclaration */: { + if (isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; + return cleanup(factory2.updateVariableDeclaration( + input, + input.name, + /*exclamationToken*/ + void 0, + ensureType(input), + ensureNoInitializer(input) + )); + } + case 168 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(factory2.updateTypeParameterDeclaration( + input, + input.modifiers, + input.name, + /*constraint*/ + void 0, + /*defaultType*/ + void 0 + )); + } + return cleanup(visitEachChild(input, visitDeclarationSubtree, context)); + } + case 194 /* ConditionalType */: { + const checkType = visitNode(input.checkType, visitDeclarationSubtree, isTypeNode); + const extendsType = visitNode(input.extendsType, visitDeclarationSubtree, isTypeNode); + const oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + const trueType = visitNode(input.trueType, visitDeclarationSubtree, isTypeNode); + enclosingDeclaration = oldEnclosingDecl; + const falseType = visitNode(input.falseType, visitDeclarationSubtree, isTypeNode); + Debug.assert(checkType); + Debug.assert(extendsType); + Debug.assert(trueType); + Debug.assert(falseType); + return cleanup(factory2.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 184 /* FunctionType */: { + return cleanup(factory2.updateFunctionTypeNode( + input, + visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), + updateParamsList(input, input.parameters), + Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)) + )); + } + case 185 /* ConstructorType */: { + return cleanup(factory2.updateConstructorTypeNode( + input, + ensureModifiers(input), + visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), + updateParamsList(input, input.parameters), + Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)) + )); + } + case 205 /* ImportType */: { + if (!isLiteralImportTypeNode(input)) return cleanup(input); + return cleanup(factory2.updateImportTypeNode( + input, + factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier2(input, input.argument.literal)), + input.attributes, + input.qualifier, + visitNodes2(input.typeArguments, visitDeclarationSubtree, isTypeNode), + input.isTypeOf + )); + } + default: + Debug.assertNever(input, `Attempted to process unhandled node kind: ${Debug.formatSyntaxKind(input.kind)}`); + } + } + if (isTupleTypeNode(input) && getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === getLineAndCharacterOfPosition(currentSourceFile, input.end).line) { + setEmitFlags(input, 1 /* SingleLine */); + } + return cleanup(visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProduceDiagnostic && hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 174 /* MethodDeclaration */ && hasEffectiveModifier(node.parent, 2 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + return; + } + if (shouldStripInternal(input)) return; + switch (input.kind) { + case 278 /* ExportDeclaration */: { + if (isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + resultHasScopeMarker = true; + return factory2.updateExportDeclaration( + input, + input.modifiers, + input.isTypeOnly, + input.exportClause, + rewriteModuleSpecifier2(input, input.moduleSpecifier), + tryGetResolutionModeOverride(input.attributes) + ); + } + case 277 /* ExportAssignment */: { + if (isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + resultHasScopeMarker = true; + if (input.expression.kind === 80 /* Identifier */) { + return input; + } else { + const newId = factory2.createUniqueName("_default", 16 /* Optimistic */); + getSymbolAccessibilityDiagnostic = () => ({ + diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); + errorFallbackNode = input; + const type = ensureType(input); + const varDecl = factory2.createVariableDeclaration( + newId, + /*exclamationToken*/ + void 0, + type, + /*initializer*/ + void 0 + ); + errorFallbackNode = void 0; + const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */)); + preserveJsDoc(statement, input); + removeAllComments(input); + return [statement, factory2.updateExportAssignment(input, input.modifiers, newId)]; + } + } + } + const result = transformTopLevelDeclaration(input); + lateStatementReplacementMap.set(getOriginalNodeId(input), result); + return input; + } + function stripExportModifiers(statement) { + if (isImportEqualsDeclaration(statement) || hasEffectiveModifier(statement, 2048 /* Default */) || !canHaveModifiers(statement)) { + return statement; + } + const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(statement) & (131071 /* All */ ^ 32 /* Export */)); + return factory2.replaceModifiers(statement, modifiers); + } + function updateModuleDeclarationAndKeyword(node, modifiers, name, body) { + const updated = factory2.updateModuleDeclaration(node, modifiers, name, body); + if (isAmbientModule(updated) || updated.flags & 32 /* Namespace */) { + return updated; + } + const fixed = factory2.createModuleDeclaration( + updated.modifiers, + updated.name, + updated.body, + updated.flags | 32 /* Namespace */ + ); + setOriginalNode(fixed, updated); + setTextRange(fixed, updated); + return fixed; + } + function transformTopLevelDeclaration(input) { + if (lateMarkedStatements) { + while (orderedRemoveItem(lateMarkedStatements, input)) ; + } + if (shouldStripInternal(input)) return; + switch (input.kind) { + case 271 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } + case 272 /* ImportDeclaration */: { + return transformImportDeclaration(input); + } + } + if (isDeclaration(input) && isDeclarationAndNotVisible(input)) return; + if (isJSDocImportTag(input)) return; + if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return; + let previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + const canProdiceDiagnostic = canProduceDiagnostics(input); + const oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input); + } + const previousNeedsDeclare = needsDeclare; + switch (input.kind) { + case 265 /* TypeAliasDeclaration */: { + needsDeclare = false; + const clean2 = cleanup(factory2.updateTypeAliasDeclaration( + input, + ensureModifiers(input), + input.name, + visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), + Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)) + )); + needsDeclare = previousNeedsDeclare; + return clean2; + } + case 264 /* InterfaceDeclaration */: { + return cleanup(factory2.updateInterfaceDeclaration( + input, + ensureModifiers(input), + input.name, + ensureTypeParams(input, input.typeParameters), + transformHeritageClauses(input.heritageClauses), + visitNodes2(input.members, visitDeclarationSubtree, isTypeElement) + )); + } + case 262 /* FunctionDeclaration */: { + const clean2 = cleanup(factory2.updateFunctionDeclaration( + input, + ensureModifiers(input), + /*asteriskToken*/ + void 0, + input.name, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input), + /*body*/ + void 0 + )); + if (clean2 && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { + const props = resolver.getPropertiesOfContainerFunction(input); + if (isolatedDeclarations) { + reportExpandoFunctionErrors(input); + } + const fakespace = parseNodeFactory.createModuleDeclaration( + /*modifiers*/ + void 0, + clean2.name || factory2.createIdentifier("_default"), + factory2.createModuleBlock([]), + 32 /* Namespace */ + ); + setParent(fakespace, enclosingDeclaration); + fakespace.locals = createSymbolTable(props); + fakespace.symbol = props[0].parent; + const exportMappings = []; + let declarations = mapDefined(props, (p) => { + if (!isExpandoPropertyDeclaration(p.valueDeclaration)) { + return void 0; + } + const nameStr = unescapeLeadingUnderscores(p.escapedName); + if (!isIdentifierText(nameStr, 99 /* ESNext */)) { + return void 0; + } + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); + const type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags | 2 /* NoSyntacticPrinter */, symbolTracker); + getSymbolAccessibilityDiagnostic = oldDiag; + const isNonContextualKeywordName = isStringANonContextualKeyword(nameStr); + const name = isNonContextualKeywordName ? factory2.getGeneratedNameForNode(p.valueDeclaration) : factory2.createIdentifier(nameStr); + if (isNonContextualKeywordName) { + exportMappings.push([name, nameStr]); + } + const varDecl = factory2.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + type, + /*initializer*/ + void 0 + ); + return factory2.createVariableStatement(isNonContextualKeywordName ? void 0 : [factory2.createToken(95 /* ExportKeyword */)], factory2.createVariableDeclarationList([varDecl])); + }); + if (!exportMappings.length) { + declarations = mapDefined(declarations, (declaration) => factory2.replaceModifiers(declaration, 0 /* None */)); + } else { + declarations.push(factory2.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory2.createNamedExports(map(exportMappings, ([gen, exp]) => { + return factory2.createExportSpecifier( + /*isTypeOnly*/ + false, + gen, + exp + ); + })) + )); + } + const namespaceDecl = factory2.createModuleDeclaration(ensureModifiers(input), input.name, factory2.createModuleBlock(declarations), 32 /* Namespace */); + if (!hasEffectiveModifier(clean2, 2048 /* Default */)) { + return [clean2, namespaceDecl]; + } + const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(clean2) & ~2080 /* ExportDefault */ | 128 /* Ambient */); + const cleanDeclaration = factory2.updateFunctionDeclaration( + clean2, + modifiers, + /*asteriskToken*/ + void 0, + clean2.name, + clean2.typeParameters, + clean2.parameters, + clean2.type, + /*body*/ + void 0 + ); + const namespaceDeclaration = factory2.updateModuleDeclaration( + namespaceDecl, + modifiers, + namespaceDecl.name, + namespaceDecl.body + ); + const exportDefaultDeclaration = factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + namespaceDecl.name + ); + if (isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + resultHasScopeMarker = true; + return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration]; + } else { + return clean2; + } + } + case 267 /* ModuleDeclaration */: { + needsDeclare = false; + const inner = input.body; + if (inner && inner.kind === 268 /* ModuleBlock */) { + const oldNeedsScopeFix = needsScopeFixMarker; + const oldHasScopeFix = resultHasScopeMarker; + resultHasScopeMarker = false; + needsScopeFixMarker = false; + const statements = visitNodes2(inner.statements, visitDeclarationStatements, isStatement); + let lateStatements = transformAndReplaceLatePaintedStatements(statements); + if (input.flags & 33554432 /* Ambient */) { + needsScopeFixMarker = false; + } + if (!isGlobalScopeAugmentation(input) && !hasScopeMarker2(lateStatements) && !resultHasScopeMarker) { + if (needsScopeFixMarker) { + lateStatements = factory2.createNodeArray([...lateStatements, createEmptyExports(factory2)]); + } else { + lateStatements = visitNodes2(lateStatements, stripExportModifiers, isStatement); + } + } + const body = factory2.updateModuleBlock(inner, lateStatements); + needsDeclare = previousNeedsDeclare; + needsScopeFixMarker = oldNeedsScopeFix; + resultHasScopeMarker = oldHasScopeFix; + const mods = ensureModifiers(input); + return cleanup(updateModuleDeclarationAndKeyword( + input, + mods, + isExternalModuleAugmentation(input) ? rewriteModuleSpecifier2(input, input.name) : input.name, + body + )); + } else { + needsDeclare = previousNeedsDeclare; + const mods = ensureModifiers(input); + needsDeclare = false; + visitNode(inner, visitDeclarationStatements); + const id = getOriginalNodeId(inner); + const body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(updateModuleDeclarationAndKeyword( + input, + mods, + input.name, + body + )); + } + } + case 263 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; + const modifiers = factory2.createNodeArray(ensureModifiers(input)); + const typeParameters = ensureTypeParams(input, input.typeParameters); + const ctor = getFirstConstructorWithBody(input); + let parameterProperties; + if (ctor) { + const oldDiag2 = getSymbolAccessibilityDiagnostic; + parameterProperties = compact(flatMap(ctor.parameters, (param) => { + if (!hasSyntacticModifier(param, 31 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 80 /* Identifier */) { + return preserveJsDoc( + factory2.createPropertyDeclaration( + ensureModifiers(param), + param.name, + param.questionToken, + ensureType(param), + ensureNoInitializer(param) + ), + param + ); + } else { + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + let elems; + for (const elem of pattern.elements) { + if (isOmittedExpression(elem)) continue; + if (isBindingPattern(elem.name)) { + elems = concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(factory2.createPropertyDeclaration( + ensureModifiers(param), + elem.name, + /*questionOrExclamationToken*/ + void 0, + ensureType(elem), + /*initializer*/ + void 0 + )); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag2; + } + const hasPrivateIdentifier = some(input.members, (member) => !!member.name && isPrivateIdentifier(member.name)); + const privateIdentifier = hasPrivateIdentifier ? [ + factory2.createPropertyDeclaration( + /*modifiers*/ + void 0, + factory2.createPrivateIdentifier("#private"), + /*questionOrExclamationToken*/ + void 0, + /*type*/ + void 0, + /*initializer*/ + void 0 + ) + ] : void 0; + const lateIndexes = resolver.createLateBoundIndexSignatures(input, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); + const memberNodes = concatenate(concatenate(concatenate(privateIdentifier, lateIndexes), parameterProperties), visitNodes2(input.members, visitDeclarationSubtree, isClassElement)); + const members = factory2.createNodeArray(memberNodes); + const extendsClause = getEffectiveBaseTypeNode(input); + if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== 106 /* NullKeyword */) { + const oldId = input.name ? unescapeLeadingUnderscores(input.name.escapedText) : "default"; + const newId = factory2.createUniqueName(`${oldId}_base`, 16 /* Optimistic */); + getSymbolAccessibilityDiagnostic = () => ({ + diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause, + typeName: input.name + }); + const varDecl = factory2.createVariableDeclaration( + newId, + /*exclamationToken*/ + void 0, + resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker), + /*initializer*/ + void 0 + ); + const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */)); + const heritageClauses = factory2.createNodeArray(map(input.heritageClauses, (clause) => { + if (clause.token === 96 /* ExtendsKeyword */) { + const oldDiag2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + const newClause = factory2.updateHeritageClause(clause, map(clause.types, (t) => factory2.updateExpressionWithTypeArguments(t, newId, visitNodes2(t.typeArguments, visitDeclarationSubtree, isTypeNode)))); + getSymbolAccessibilityDiagnostic = oldDiag2; + return newClause; + } + return factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t) => isEntityNameExpression(t.expression) || t.expression.kind === 106 /* NullKeyword */)), visitDeclarationSubtree, isExpressionWithTypeArguments)); + })); + return [ + statement, + cleanup(factory2.updateClassDeclaration( + input, + modifiers, + input.name, + typeParameters, + heritageClauses, + members + )) + ]; + } else { + const heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(factory2.updateClassDeclaration( + input, + modifiers, + input.name, + typeParameters, + heritageClauses, + members + )); + } + } + case 243 /* VariableStatement */: { + return cleanup(transformVariableStatement(input)); + } + case 266 /* EnumDeclaration */: { + return cleanup(factory2.updateEnumDeclaration( + input, + factory2.createNodeArray(ensureModifiers(input)), + input.name, + factory2.createNodeArray(mapDefined(input.members, (m) => { + if (shouldStripInternal(m)) return; + const enumValue = resolver.getEnumMemberValue(m); + const constValue = enumValue == null ? void 0 : enumValue.value; + if (isolatedDeclarations && m.initializer && (enumValue == null ? void 0 : enumValue.hasExternalReferences) && // This will be its own compiler error instead, so don't report. + !isComputedPropertyName(m.name)) { + context.addDiagnostic(createDiagnosticForNode(m, Diagnostics.Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDeclarations)); + } + const newInitializer = constValue === void 0 ? void 0 : typeof constValue === "string" ? factory2.createStringLiteral(constValue) : constValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(-constValue)) : factory2.createNumericLiteral(constValue); + return preserveJsDoc(factory2.updateEnumMember(m, m.name, newInitializer), m); + })) + )); + } + } + return Debug.assertNever(input, `Unhandled top-level node in declaration emit: ${Debug.formatSyntaxKind(input.kind)}`); + function cleanup(node) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (input.kind === 267 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + } + if (node === input) { + return node; + } + errorFallbackNode = void 0; + errorNameNode = void 0; + return node && setOriginalNode(preserveJsDoc(node, input), input); + } + } + function transformVariableStatement(input) { + if (!forEach(input.declarationList.declarations, getBindingNameVisible)) return; + const nodes = visitNodes2(input.declarationList.declarations, visitDeclarationSubtree, isVariableDeclaration); + if (!length(nodes)) return; + const modifiers = factory2.createNodeArray(ensureModifiers(input)); + let declList; + if (isVarUsing(input.declarationList) || isVarAwaitUsing(input.declarationList)) { + declList = factory2.createVariableDeclarationList(nodes, 2 /* Const */); + setOriginalNode(declList, input.declarationList); + setTextRange(declList, input.declarationList); + setCommentRange(declList, input.declarationList); + } else { + declList = factory2.updateVariableDeclarationList(input.declarationList, nodes); + } + return factory2.updateVariableStatement(input, modifiers, declList); + } + function recreateBindingPattern(d) { + return flatten(mapDefined(d.elements, (e) => recreateBindingElement(e))); + } + function recreateBindingElement(e) { + if (e.kind === 232 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) return; + if (isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } else { + return factory2.createVariableDeclaration( + e.name, + /*exclamationToken*/ + void 0, + ensureType(e), + /*initializer*/ + void 0 + ); + } + } + } + function checkName(node) { + let oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + Debug.assert(hasDynamicName(node)); + const decl = node; + const entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = void 0; + } + function shouldStripInternal(node) { + return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile); + } + function isScopeMarker2(node) { + return isExportAssignment(node) || isExportDeclaration(node); + } + function hasScopeMarker2(statements) { + return some(statements, isScopeMarker2); + } + function ensureModifiers(node) { + const currentFlags = getEffectiveModifierFlags(node); + const newFlags = ensureModifierFlags(node); + if (currentFlags === newFlags) { + return visitArray(node.modifiers, (n) => tryCast(n, isModifier), isModifier); + } + return factory2.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node) { + let mask = 131071 /* All */ ^ (1 /* Public */ | 1024 /* Async */ | 16 /* Override */); + let additions = needsDeclare && !isAlwaysType(node) ? 128 /* Ambient */ : 0 /* None */; + const parentIsFile = node.parent.kind === 307 /* SourceFile */; + if (!parentIsFile || isBundledEmit && parentIsFile && isExternalModule(node.parent)) { + mask ^= 128 /* Ambient */; + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function transformHeritageClauses(nodes) { + return factory2.createNodeArray(filter( + map(nodes, (clause) => factory2.updateHeritageClause( + clause, + visitNodes2( + factory2.createNodeArray(filter(clause.types, (t) => { + return isEntityNameExpression(t.expression) || clause.token === 96 /* ExtendsKeyword */ && t.expression.kind === 106 /* NullKeyword */; + })), + visitDeclarationSubtree, + isExpressionWithTypeArguments + ) + )), + (clause) => clause.types && !!clause.types.length + )); + } +} +function isAlwaysType(node) { + if (node.kind === 264 /* InterfaceDeclaration */) { + return true; + } + return false; +} +function maskModifiers(factory2, node, modifierMask, modifierAdditions) { + return factory2.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); +} +function maskModifierFlags(node, modifierMask = 131071 /* All */ ^ 1 /* Public */, modifierAdditions = 0 /* None */) { + let flags = getEffectiveModifierFlags(node) & modifierMask | modifierAdditions; + if (flags & 2048 /* Default */ && !(flags & 32 /* Export */)) { + flags ^= 32 /* Export */; + } + if (flags & 2048 /* Default */ && flags & 128 /* Ambient */) { + flags ^= 128 /* Ambient */; + } + return flags; +} +function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + return !hasEffectiveModifier(node, 2 /* Private */); + case 169 /* Parameter */: + case 260 /* VariableDeclaration */: + return true; + } + return false; +} +function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 262 /* FunctionDeclaration */: + case 267 /* ModuleDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 264 /* InterfaceDeclaration */: + case 263 /* ClassDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 266 /* EnumDeclaration */: + case 243 /* VariableStatement */: + case 272 /* ImportDeclaration */: + case 278 /* ExportDeclaration */: + case 277 /* ExportAssignment */: + return true; + } + return false; +} +function isProcessedComponent(node) { + switch (node.kind) { + case 180 /* ConstructSignature */: + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 173 /* MethodSignature */: + case 179 /* CallSignature */: + case 181 /* IndexSignature */: + case 260 /* VariableDeclaration */: + case 168 /* TypeParameter */: + case 233 /* ExpressionWithTypeArguments */: + case 183 /* TypeReference */: + case 194 /* ConditionalType */: + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + case 205 /* ImportType */: + return true; + } + return false; +} + +// src/compiler/transformer.ts +function getModuleTransformer(moduleKind) { + switch (moduleKind) { + case 200 /* Preserve */: + return transformECMAScriptModule; + case 99 /* ESNext */: + case 7 /* ES2022 */: + case 6 /* ES2020 */: + case 5 /* ES2015 */: + case 100 /* Node16 */: + case 101 /* Node18 */: + case 199 /* NodeNext */: + case 1 /* CommonJS */: + return transformImpliedNodeFormatDependentModule; + case 4 /* System */: + return transformSystemModule; + default: + return transformModule; + } +} +var noTransformers = { scriptTransformers: emptyArray, declarationTransformers: emptyArray }; +function getTransformers(compilerOptions, customTransformers, emitOnly) { + return { + scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnly), + declarationTransformers: getDeclarationTransformers(customTransformers) + }; +} +function getScriptTransformers(compilerOptions, customTransformers, emitOnly) { + if (emitOnly) return emptyArray; + const languageVersion = getEmitScriptTarget(compilerOptions); + const moduleKind = getEmitModuleKind(compilerOptions); + const useDefineForClassFields = getUseDefineForClassFields(compilerOptions); + const transformers = []; + addRange(transformers, customTransformers && map(customTransformers.before, wrapScriptTransformerFactory)); + transformers.push(transformTypeScript); + if (compilerOptions.experimentalDecorators) { + transformers.push(transformLegacyDecorators); + } + if (getJSXTransformEnabled(compilerOptions)) { + transformers.push(transformJsx); + } + if (languageVersion < 99 /* ESNext */) { + transformers.push(transformESNext); + } + if (!compilerOptions.experimentalDecorators && (languageVersion < 99 /* ESNext */ || !useDefineForClassFields)) { + transformers.push(transformESDecorators); + } + transformers.push(transformClassFields); + if (languageVersion < 8 /* ES2021 */) { + transformers.push(transformES2021); + } + if (languageVersion < 7 /* ES2020 */) { + transformers.push(transformES2020); + } + if (languageVersion < 6 /* ES2019 */) { + transformers.push(transformES2019); + } + if (languageVersion < 5 /* ES2018 */) { + transformers.push(transformES2018); + } + if (languageVersion < 4 /* ES2017 */) { + transformers.push(transformES2017); + } + if (languageVersion < 3 /* ES2016 */) { + transformers.push(transformES2016); + } + if (languageVersion < 2 /* ES2015 */) { + transformers.push(transformES2015); + transformers.push(transformGenerators); + } + transformers.push(getModuleTransformer(moduleKind)); + addRange(transformers, customTransformers && map(customTransformers.after, wrapScriptTransformerFactory)); + return transformers; +} +function getDeclarationTransformers(customTransformers) { + const transformers = []; + transformers.push(transformDeclarations); + addRange(transformers, customTransformers && map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory)); + return transformers; +} +function wrapCustomTransformer(transformer) { + return (node) => isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); +} +function wrapCustomTransformerFactory(transformer, handleDefault) { + return (context) => { + const customTransformer = transformer(context); + return typeof customTransformer === "function" ? handleDefault(context, customTransformer) : wrapCustomTransformer(customTransformer); + }; +} +function wrapScriptTransformerFactory(transformer) { + return wrapCustomTransformerFactory(transformer, chainBundle); +} +function wrapDeclarationTransformerFactory(transformer) { + return wrapCustomTransformerFactory(transformer, (_, node) => node); +} +function noEmitSubstitution(_hint, node) { + return node; +} +function noEmitNotification(hint, node, callback) { + callback(hint, node); +} +function transformNodes(resolver, host, factory2, options, nodes, transformers, allowDtsFiles) { + var _a, _b; + const enabledSyntaxKindFeatures = new Array(358 /* Count */); + let lexicalEnvironmentVariableDeclarations; + let lexicalEnvironmentFunctionDeclarations; + let lexicalEnvironmentStatements; + let lexicalEnvironmentFlags = 0 /* None */; + let lexicalEnvironmentVariableDeclarationsStack = []; + let lexicalEnvironmentFunctionDeclarationsStack = []; + let lexicalEnvironmentStatementsStack = []; + let lexicalEnvironmentFlagsStack = []; + let lexicalEnvironmentStackOffset = 0; + let lexicalEnvironmentSuspended = false; + let blockScopedVariableDeclarationsStack = []; + let blockScopeStackOffset = 0; + let blockScopedVariableDeclarations; + let emitHelpers; + let onSubstituteNode = noEmitSubstitution; + let onEmitNode = noEmitNotification; + let state = 0 /* Uninitialized */; + const diagnostics = []; + const context = { + factory: factory2, + getCompilerOptions: () => options, + getEmitResolver: () => resolver, + // TODO: GH#18217 + getEmitHost: () => host, + // TODO: GH#18217 + getEmitHelperFactory: memoize(() => createEmitHelperFactory(context)), + startLexicalEnvironment, + suspendLexicalEnvironment, + resumeLexicalEnvironment, + endLexicalEnvironment, + setLexicalEnvironmentFlags, + getLexicalEnvironmentFlags, + hoistVariableDeclaration, + hoistFunctionDeclaration, + addInitializationStatement, + startBlockScope, + endBlockScope, + addBlockScopedVariable, + requestEmitHelper, + readEmitHelpers, + enableSubstitution, + enableEmitNotification, + isSubstitutionEnabled, + isEmitNotificationEnabled, + get onSubstituteNode() { + return onSubstituteNode; + }, + set onSubstituteNode(value) { + Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + Debug.assert(value !== void 0, "Value must not be 'undefined'"); + onSubstituteNode = value; + }, + get onEmitNode() { + return onEmitNode; + }, + set onEmitNode(value) { + Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); + Debug.assert(value !== void 0, "Value must not be 'undefined'"); + onEmitNode = value; + }, + addDiagnostic(diag2) { + diagnostics.push(diag2); + } + }; + for (const node of nodes) { + disposeEmitNodes(getSourceFileOfNode(getParseTreeNode(node))); + } + mark("beforeTransform"); + const transformersWithContext = transformers.map((t) => t(context)); + const transformation = (node) => { + for (const transform of transformersWithContext) { + node = transform(node); + } + return node; + }; + state = 1 /* Initialized */; + const transformed = []; + for (const node of nodes) { + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Emit, "transformNodes", node.kind === 307 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); + (_b = tracing) == null ? void 0 : _b.pop(); + } + state = 2 /* Completed */; + mark("afterTransform"); + measure("transformTime", "beforeTransform", "afterTransform"); + return { + transformed, + substituteNode, + emitNodeWithNotification, + isEmitNotificationEnabled, + dispose, + diagnostics + }; + function transformRoot(node) { + return node && (!isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; + } + function enableSubstitution(kind) { + Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; + } + function isSubstitutionEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 && (getEmitFlags(node) & 8 /* NoSubstitution */) === 0; + } + function substituteNode(hint, node) { + Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed."); + return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node; + } + function enableEmitNotification(kind) { + Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; + } + function isEmitNotificationEnabled(node) { + return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 || (getEmitFlags(node) & 4 /* AdviseOnEmitNode */) !== 0; + } + function emitNodeWithNotification(hint, node, emitCallback) { + Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed."); + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(hint, node, emitCallback); + } else { + emitCallback(hint, node); + } + } + } + function hoistVariableDeclaration(name) { + Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + const decl = setEmitFlags(factory2.createVariableDeclaration(name), 128 /* NoNestedSourceMaps */); + if (!lexicalEnvironmentVariableDeclarations) { + lexicalEnvironmentVariableDeclarations = [decl]; + } else { + lexicalEnvironmentVariableDeclarations.push(decl); + } + if (lexicalEnvironmentFlags & 1 /* InParameters */) { + lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */; + } + } + function hoistFunctionDeclaration(func) { + Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + setEmitFlags(func, 2097152 /* CustomPrologue */); + if (!lexicalEnvironmentFunctionDeclarations) { + lexicalEnvironmentFunctionDeclarations = [func]; + } else { + lexicalEnvironmentFunctionDeclarations.push(func); + } + } + function addInitializationStatement(node) { + Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + setEmitFlags(node, 2097152 /* CustomPrologue */); + if (!lexicalEnvironmentStatements) { + lexicalEnvironmentStatements = [node]; + } else { + lexicalEnvironmentStatements.push(node); + } + } + function startLexicalEnvironment() { + Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; + lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements; + lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags; + lexicalEnvironmentStackOffset++; + lexicalEnvironmentVariableDeclarations = void 0; + lexicalEnvironmentFunctionDeclarations = void 0; + lexicalEnvironmentStatements = void 0; + lexicalEnvironmentFlags = 0 /* None */; + } + function suspendLexicalEnvironment() { + Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended."); + lexicalEnvironmentSuspended = true; + } + function resumeLexicalEnvironment() { + Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended."); + lexicalEnvironmentSuspended = false; + } + function endLexicalEnvironment() { + Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); + let statements; + if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations || lexicalEnvironmentStatements) { + if (lexicalEnvironmentFunctionDeclarations) { + statements = [...lexicalEnvironmentFunctionDeclarations]; + } + if (lexicalEnvironmentVariableDeclarations) { + const statement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations) + ); + setEmitFlags(statement, 2097152 /* CustomPrologue */); + if (!statements) { + statements = [statement]; + } else { + statements.push(statement); + } + } + if (lexicalEnvironmentStatements) { + if (!statements) { + statements = [...lexicalEnvironmentStatements]; + } else { + statements = [...statements, ...lexicalEnvironmentStatements]; + } + } + } + lexicalEnvironmentStackOffset--; + lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset]; + if (lexicalEnvironmentStackOffset === 0) { + lexicalEnvironmentVariableDeclarationsStack = []; + lexicalEnvironmentFunctionDeclarationsStack = []; + lexicalEnvironmentStatementsStack = []; + lexicalEnvironmentFlagsStack = []; + } + return statements; + } + function setLexicalEnvironmentFlags(flags, value) { + lexicalEnvironmentFlags = value ? lexicalEnvironmentFlags | flags : lexicalEnvironmentFlags & ~flags; + } + function getLexicalEnvironmentFlags() { + return lexicalEnvironmentFlags; + } + function startBlockScope() { + Debug.assert(state > 0 /* Uninitialized */, "Cannot start a block scope during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot start a block scope after transformation has completed."); + blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations; + blockScopeStackOffset++; + blockScopedVariableDeclarations = void 0; + } + function endBlockScope() { + Debug.assert(state > 0 /* Uninitialized */, "Cannot end a block scope during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot end a block scope after transformation has completed."); + const statements = some(blockScopedVariableDeclarations) ? [ + factory2.createVariableStatement( + /*modifiers*/ + void 0, + factory2.createVariableDeclarationList( + blockScopedVariableDeclarations.map((identifier) => factory2.createVariableDeclaration(identifier)), + 1 /* Let */ + ) + ) + ] : void 0; + blockScopeStackOffset--; + blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; + if (blockScopeStackOffset === 0) { + blockScopedVariableDeclarationsStack = []; + } + return statements; + } + function addBlockScopedVariable(name) { + Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body."); + (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name); + } + function requestEmitHelper(helper) { + Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + if (helper.dependencies) { + for (const h of helper.dependencies) { + requestEmitHelper(h); + } + } + emitHelpers = append(emitHelpers, helper); + } + function readEmitHelpers() { + Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); + Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); + const helpers = emitHelpers; + emitHelpers = void 0; + return helpers; + } + function dispose() { + if (state < 3 /* Disposed */) { + for (const node of nodes) { + disposeEmitNodes(getSourceFileOfNode(getParseTreeNode(node))); + } + lexicalEnvironmentVariableDeclarations = void 0; + lexicalEnvironmentVariableDeclarationsStack = void 0; + lexicalEnvironmentFunctionDeclarations = void 0; + lexicalEnvironmentFunctionDeclarationsStack = void 0; + onSubstituteNode = void 0; + onEmitNode = void 0; + emitHelpers = void 0; + state = 3 /* Disposed */; + } + } +} +var nullTransformationContext = { + factory, + // eslint-disable-line object-shorthand + getCompilerOptions: () => ({}), + getEmitResolver: notImplemented, + getEmitHost: notImplemented, + getEmitHelperFactory: notImplemented, + startLexicalEnvironment: noop, + resumeLexicalEnvironment: noop, + suspendLexicalEnvironment: noop, + endLexicalEnvironment: returnUndefined, + setLexicalEnvironmentFlags: noop, + getLexicalEnvironmentFlags: () => 0, + hoistVariableDeclaration: noop, + hoistFunctionDeclaration: noop, + addInitializationStatement: noop, + startBlockScope: noop, + endBlockScope: returnUndefined, + addBlockScopedVariable: noop, + requestEmitHelper: noop, + readEmitHelpers: notImplemented, + enableSubstitution: noop, + enableEmitNotification: noop, + isSubstitutionEnabled: notImplemented, + isEmitNotificationEnabled: notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, + addDiagnostic: noop +}; + +// src/compiler/emitter.ts +var brackets = createBracketsMap(); +function isBuildInfoFile(file) { + return fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */); +} +function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit = false, onlyBuildInfo, includeBuildInfo) { + const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit); + const options = host.getCompilerOptions(); + if (!onlyBuildInfo) { + if (options.outFile) { + if (sourceFiles.length) { + const bundle = factory.createBundle(sourceFiles); + const result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle); + if (result) { + return result; + } + } + } else { + for (const sourceFile of sourceFiles) { + const result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile); + if (result) { + return result; + } + } + } + } + if (includeBuildInfo) { + const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options); + if (buildInfoPath) return action( + { buildInfoPath }, + /*sourceFileOrBundle*/ + void 0 + ); + } +} +function getTsBuildInfoEmitOutputFilePath(options) { + const configFile = options.configFilePath; + if (!canEmitTsBuildInfo(options)) return void 0; + if (options.tsBuildInfoFile) return options.tsBuildInfoFile; + const outPath = options.outFile; + let buildInfoExtensionLess; + if (outPath) { + buildInfoExtensionLess = removeFileExtension(outPath); + } else { + if (!configFile) return void 0; + const configFileExtensionLess = removeFileExtension(configFile); + buildInfoExtensionLess = options.outDir ? options.rootDir ? resolvePath(options.outDir, getRelativePathFromDirectory( + options.rootDir, + configFileExtensionLess, + /*ignoreCase*/ + true + )) : combinePaths(options.outDir, getBaseFileName(configFileExtensionLess)) : configFileExtensionLess; + } + return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */; +} +function canEmitTsBuildInfo(options) { + return isIncrementalCompilation(options) || !!options.tscBuild; +} +function getOutputPathsForBundle(options, forceDtsPaths) { + const outPath = options.outFile; + const jsFilePath = options.emitDeclarationOnly ? void 0 : outPath; + const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + const declarationFilePath = forceDtsPaths || getEmitDeclarations(options) ? removeFileExtension(outPath) + ".d.ts" /* Dts */ : void 0; + const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : void 0; + return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath }; +} +function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + const options = host.getCompilerOptions(); + if (sourceFile.kind === 308 /* Bundle */) { + return getOutputPathsForBundle(options, forceDtsPaths); + } else { + const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile.fileName, options)); + const isJsonFile = isJsonSourceFile(sourceFile); + const isJsonEmittedToSameLocation = isJsonFile && comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + const jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? void 0 : ownOutputFilePath; + const sourceMapFilePath = !jsFilePath || isJsonSourceFile(sourceFile) ? void 0 : getSourceMapFilePath(jsFilePath, options); + const declarationFilePath = forceDtsPaths || getEmitDeclarations(options) && !isJsonFile ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : void 0; + const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : void 0; + return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath }; + } +} +function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap && !options.inlineSourceMap ? jsFilePath + ".map" : void 0; +} +function getOutputExtension(fileName, options) { + return fileExtensionIs(fileName, ".json" /* Json */) ? ".json" /* Json */ : options.jsx === 1 /* Preserve */ && fileExtensionIsOneOf(fileName, [".jsx" /* Jsx */, ".tsx" /* Tsx */]) ? ".jsx" /* Jsx */ : fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".mjs" /* Mjs */]) ? ".mjs" /* Mjs */ : fileExtensionIsOneOf(fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]) ? ".cjs" /* Cjs */ : ".js" /* Js */; +} +function getOutputPathWithoutChangingExt(inputFileName, ignoreCase, outputDir, getCommonSourceDirectory2) { + return outputDir ? resolvePath( + outputDir, + getRelativePathFromDirectory(getCommonSourceDirectory2(), inputFileName, ignoreCase) + ) : inputFileName; +} +function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2 = () => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)) { + return getOutputDeclarationFileNameWorker(inputFileName, configFile.options, ignoreCase, getCommonSourceDirectory2); +} +function getOutputDeclarationFileNameWorker(inputFileName, options, ignoreCase, getCommonSourceDirectory2) { + return changeExtension( + getOutputPathWithoutChangingExt(inputFileName, ignoreCase, options.declarationDir || options.outDir, getCommonSourceDirectory2), + getDeclarationEmitExtensionForPath(inputFileName) + ); +} +function getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2 = () => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)) { + if (configFile.options.emitDeclarationOnly) return void 0; + const isJsonFile = fileExtensionIs(inputFileName, ".json" /* Json */); + const outputFileName = getOutputJSFileNameWorker(inputFileName, configFile.options, ignoreCase, getCommonSourceDirectory2); + return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ? outputFileName : void 0; +} +function getOutputJSFileNameWorker(inputFileName, options, ignoreCase, getCommonSourceDirectory2) { + return changeExtension( + getOutputPathWithoutChangingExt(inputFileName, ignoreCase, options.outDir, getCommonSourceDirectory2), + getOutputExtension(inputFileName, options) + ); +} +function createAddOutput() { + let outputs; + return { addOutput, getOutputs }; + function addOutput(path) { + if (path) { + (outputs || (outputs = [])).push(path); + } + } + function getOutputs() { + return outputs || emptyArray; + } +} +function getSingleOutputFileNames(configFile, addOutput) { + const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle( + configFile.options, + /*forceDtsPaths*/ + false + ); + addOutput(jsFilePath); + addOutput(sourceMapFilePath); + addOutput(declarationFilePath); + addOutput(declarationMapPath); +} +function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory2) { + if (isDeclarationFileName(inputFileName)) return; + const js = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); + addOutput(js); + if (fileExtensionIs(inputFileName, ".json" /* Json */)) return; + if (js && configFile.options.sourceMap) { + addOutput(`${js}.map`); + } + if (getEmitDeclarations(configFile.options)) { + const dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); + addOutput(dts); + if (configFile.options.declarationMap) { + addOutput(`${dts}.map`); + } + } +} +function getCommonSourceDirectory(options, emittedFiles, currentDirectory, getCanonicalFileName, checkSourceFilesBelongToPath) { + let commonSourceDirectory; + if (options.rootDir) { + commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory); + checkSourceFilesBelongToPath == null ? void 0 : checkSourceFilesBelongToPath(options.rootDir); + } else if (options.composite && options.configFilePath) { + commonSourceDirectory = getDirectoryPath(normalizeSlashes(options.configFilePath)); + checkSourceFilesBelongToPath == null ? void 0 : checkSourceFilesBelongToPath(commonSourceDirectory); + } else { + commonSourceDirectory = computeCommonSourceDirectoryOfFilenames(emittedFiles(), currentDirectory, getCanonicalFileName); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) { + commonSourceDirectory += directorySeparator; + } + return commonSourceDirectory; +} +function getCommonSourceDirectoryOfConfig({ options, fileNames }, ignoreCase) { + return getCommonSourceDirectory( + options, + () => filter(fileNames, (file) => !(options.noEmitForJsFiles && fileExtensionIsOneOf(file, supportedJSExtensionsFlat)) && !isDeclarationFileName(file)), + getDirectoryPath(normalizeSlashes(Debug.checkDefined(options.configFilePath))), + createGetCanonicalFileName(!ignoreCase) + ); +} +function getAllProjectOutputs(configFile, ignoreCase) { + const { addOutput, getOutputs } = createAddOutput(); + if (configFile.options.outFile) { + getSingleOutputFileNames(configFile, addOutput); + } else { + const getCommonSourceDirectory2 = memoize(() => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)); + for (const inputFileName of configFile.fileNames) { + getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory2); + } + } + addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options)); + return getOutputs(); +} +function getFirstProjectOutput(configFile, ignoreCase) { + if (configFile.options.outFile) { + const { jsFilePath, declarationFilePath } = getOutputPathsForBundle( + configFile.options, + /*forceDtsPaths*/ + false + ); + return Debug.checkDefined(jsFilePath || declarationFilePath, `project ${configFile.options.configFilePath} expected to have at least one output`); + } + const getCommonSourceDirectory2 = memoize(() => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)); + for (const inputFileName of configFile.fileNames) { + if (isDeclarationFileName(inputFileName)) continue; + const jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); + if (jsFilePath) return jsFilePath; + if (fileExtensionIs(inputFileName, ".json" /* Json */)) continue; + if (getEmitDeclarations(configFile.options)) { + return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); + } + } + const buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options); + if (buildInfoPath) return buildInfoPath; + return Debug.fail(`project ${configFile.options.configFilePath} expected to have at least one output`); +} +function emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) { + return !!forceDtsEmit && !!emitOnly; +} +function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, declarationTransformers }, emitOnly, onlyBuildInfo, forceDtsEmit, skipBuildInfo) { + var compilerOptions = host.getCompilerOptions(); + var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions) ? [] : void 0; + var emittedFilesList = compilerOptions.listEmittedFiles ? [] : void 0; + var emitterDiagnostics = createDiagnosticCollection(); + var newLine = getNewLineCharacter(compilerOptions); + var writer = createTextWriter(newLine); + var { enter, exit } = createTimer("printTime", "beforePrint", "afterPrint"); + var emitSkipped = false; + enter(); + forEachEmittedFile( + host, + emitSourceFileOrBundle, + getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), + forceDtsEmit, + onlyBuildInfo, + !targetSourceFile && !skipBuildInfo + ); + exit(); + return { + emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), + emittedFiles: emittedFilesList, + sourceMaps: sourceMapDataList + }; + function emitSourceFileOrBundle({ jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath }, sourceFileOrBundle) { + var _a, _b, _c, _d, _e, _f; + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Emit, "emitJsFileOrBundle", { jsFilePath }); + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + (_b = tracing) == null ? void 0 : _b.pop(); + (_c = tracing) == null ? void 0 : _c.push(tracing.Phase.Emit, "emitDeclarationFileOrBundle", { declarationFilePath }); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); + (_d = tracing) == null ? void 0 : _d.pop(); + (_e = tracing) == null ? void 0 : _e.push(tracing.Phase.Emit, "emitBuildInfo", { buildInfoPath }); + emitBuildInfo(buildInfoPath); + (_f = tracing) == null ? void 0 : _f.pop(); + } + function emitBuildInfo(buildInfoPath) { + if (!buildInfoPath || targetSourceFile) return; + if (host.isEmitBlocked(buildInfoPath)) { + emitSkipped = true; + return; + } + const buildInfo = host.getBuildInfo() || { version }; + writeFile( + host, + emitterDiagnostics, + buildInfoPath, + getBuildInfoText(buildInfo), + /*writeByteOrderMark*/ + false, + /*sourceFiles*/ + void 0, + { buildInfo } + ); + emittedFilesList == null ? void 0 : emittedFilesList.push(buildInfoPath); + } + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { + if (!sourceFileOrBundle || emitOnly || !jsFilePath) { + return; + } + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) { + emitSkipped = true; + return; + } + (isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : filter(sourceFileOrBundle.sourceFiles, isSourceFileNotJson)).forEach( + (sourceFile) => { + if (compilerOptions.noCheck || !canIncludeBindAndCheckDiagnostics(sourceFile, compilerOptions)) markLinkedReferences(sourceFile); + } + ); + const transform = transformNodes( + resolver, + host, + factory, + compilerOptions, + [sourceFileOrBundle], + scriptTransformers, + /*allowDtsFiles*/ + false + ); + const printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: compilerOptions.noEmitHelpers, + module: getEmitModuleKind(compilerOptions), + moduleResolution: getEmitModuleResolutionKind(compilerOptions), + target: getEmitScriptTarget(compilerOptions), + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + inlineSources: compilerOptions.inlineSources, + extendedDiagnostics: compilerOptions.extendedDiagnostics + }; + const printer = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: transform.emitNodeWithNotification, + isEmitNotificationEnabled: transform.isEmitNotificationEnabled, + substituteNode: transform.substituteNode + }); + Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, compilerOptions); + transform.dispose(); + if (emittedFilesList) { + emittedFilesList.push(jsFilePath); + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + } + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!sourceFileOrBundle || emitOnly === 0 /* Js */) return; + if (!declarationFilePath) { + if (emitOnly || compilerOptions.emitDeclarationOnly) emitSkipped = true; + return; + } + const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + const filesForEmit = forceDtsEmit ? sourceFiles : filter(sourceFiles, isSourceFileNotJson); + const inputListOrBundle = compilerOptions.outFile ? [factory.createBundle(filesForEmit)] : filesForEmit; + filesForEmit.forEach((sourceFile) => { + if (emitOnly && !getEmitDeclarations(compilerOptions) || compilerOptions.noCheck || emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) || !canIncludeBindAndCheckDiagnostics(sourceFile, compilerOptions)) { + collectLinkedAliases(sourceFile); + } + }); + const declarationTransform = transformNodes( + resolver, + host, + factory, + compilerOptions, + inputListOrBundle, + declarationTransformers, + /*allowDtsFiles*/ + false + ); + if (length(declarationTransform.diagnostics)) { + for (const diagnostic of declarationTransform.diagnostics) { + emitterDiagnostics.add(diagnostic); + } + } + const declBlocked = !!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || forceDtsEmit) { + Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + const printerOptions = { + removeComments: compilerOptions.removeComments, + newLine: compilerOptions.newLine, + noEmitHelpers: true, + module: compilerOptions.module, + moduleResolution: compilerOptions.moduleResolution, + target: compilerOptions.target, + sourceMap: emitOnly !== 2 /* BuilderSignature */ && compilerOptions.declarationMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + extendedDiagnostics: compilerOptions.extendedDiagnostics, + onlyPrintJsDocStyle: true, + omitBraceSourceMapPositions: true + }; + const declarationPrinter = createPrinter(printerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled, + substituteNode: declarationTransform.substituteNode + }); + const dtsWritten = printSourceFileOrBundle( + declarationFilePath, + declarationMapPath, + declarationTransform, + declarationPrinter, + { + sourceMap: printerOptions.sourceMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics + // Explicitly do not passthru either `inline` option + } + ); + if (emittedFilesList) { + if (dtsWritten) emittedFilesList.push(declarationFilePath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); + } + } + } + declarationTransform.dispose(); + } + function collectLinkedAliases(node) { + if (isExportAssignment(node)) { + if (node.expression.kind === 80 /* Identifier */) { + resolver.collectLinkedAliases( + node.expression, + /*setVisibility*/ + true + ); + } + return; + } else if (isExportSpecifier(node)) { + resolver.collectLinkedAliases( + node.propertyName || node.name, + /*setVisibility*/ + true + ); + return; + } + forEachChild(node, collectLinkedAliases); + } + function markLinkedReferences(file) { + if (isSourceFileJS(file)) return; + forEachChildRecursively(file, (n) => { + if (isImportEqualsDeclaration(n) && !(getSyntacticModifierFlags(n) & 32 /* Export */)) return "skip"; + if (isImportDeclaration(n)) return "skip"; + resolver.markLinkedReferences(n); + }); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { + const sourceFileOrBundle = transform.transformed[0]; + const bundle = sourceFileOrBundle.kind === 308 /* Bundle */ ? sourceFileOrBundle : void 0; + const sourceFile = sourceFileOrBundle.kind === 307 /* SourceFile */ ? sourceFileOrBundle : void 0; + const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; + let sourceMapGenerator; + if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { + sourceMapGenerator = createSourceMapGenerator( + host, + getBaseFileName(normalizeSlashes(jsFilePath)), + getSourceRoot(mapOptions), + getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), + mapOptions + ); + } + if (bundle) { + printer.writeBundle(bundle, writer, sourceMapGenerator); + } else { + printer.writeFile(sourceFile, writer, sourceMapGenerator); + } + let sourceMapUrlPos; + if (sourceMapGenerator) { + if (sourceMapDataList) { + sourceMapDataList.push({ + inputSourceFileNames: sourceMapGenerator.getSources(), + sourceMap: sourceMapGenerator.toJSON() + }); + } + const sourceMappingURL = getSourceMappingURL( + mapOptions, + sourceMapGenerator, + jsFilePath, + sourceMapFilePath, + sourceFile + ); + if (sourceMappingURL) { + if (!writer.isAtStartOfLine()) writer.rawWrite(newLine); + sourceMapUrlPos = writer.getTextPos(); + writer.writeComment(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); + } + if (sourceMapFilePath) { + const sourceMap = sourceMapGenerator.toString(); + writeFile( + host, + emitterDiagnostics, + sourceMapFilePath, + sourceMap, + /*writeByteOrderMark*/ + false, + sourceFiles + ); + } + } else { + writer.writeLine(); + } + const text = writer.getText(); + const data = { sourceMapUrlPos, diagnostics: transform.diagnostics }; + writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, data); + writer.clear(); + return !data.skippedDtsWrite; + } + function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { + return (mapOptions.sourceMap || mapOptions.inlineSourceMap) && (sourceFileOrBundle.kind !== 307 /* SourceFile */ || !fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + } + function getSourceRoot(mapOptions) { + const sourceRoot = normalizeSlashes(mapOptions.sourceRoot || ""); + return sourceRoot ? ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; + } + function getSourceMapDirectory(mapOptions, filePath, sourceFile) { + if (mapOptions.sourceRoot) return host.getCommonSourceDirectory(); + if (mapOptions.mapRoot) { + let sourceMapDir = normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (getRootLength(sourceMapDir) === 0) { + sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + } + return sourceMapDir; + } + return getDirectoryPath(normalizePath(filePath)); + } + function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) { + if (mapOptions.inlineSourceMap) { + const sourceMapText = sourceMapGenerator.toString(); + const base64SourceMapText = base64encode(sys, sourceMapText); + return `data:application/json;base64,${base64SourceMapText}`; + } + const sourceMapFile = getBaseFileName(normalizeSlashes(Debug.checkDefined(sourceMapFilePath))); + if (mapOptions.mapRoot) { + let sourceMapDir = normalizeSlashes(mapOptions.mapRoot); + if (sourceFile) { + sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir)); + } + if (getRootLength(sourceMapDir) === 0) { + sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + return encodeURI( + getRelativePathToDirectoryOrUrl( + getDirectoryPath(normalizePath(filePath)), + // get the relative sourceMapDir path based on jsFilePath + combinePaths(sourceMapDir, sourceMapFile), + // this is where user expects to see sourceMap + host.getCurrentDirectory(), + host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ + true + ) + ); + } else { + return encodeURI(combinePaths(sourceMapDir, sourceMapFile)); + } + } + return encodeURI(sourceMapFile); + } +} +function getBuildInfoText(buildInfo) { + return JSON.stringify(buildInfo); +} +function getBuildInfo(buildInfoFile, buildInfoText) { + return readJsonOrUndefined(buildInfoFile, buildInfoText); +} +var notImplementedResolver = { + hasGlobalName: notImplemented, + getReferencedExportContainer: notImplemented, + getReferencedImportDeclaration: notImplemented, + getReferencedDeclarationWithCollidingName: notImplemented, + isDeclarationWithCollidingName: notImplemented, + isValueAliasDeclaration: notImplemented, + isReferencedAliasDeclaration: notImplemented, + isTopLevelValueImportEqualsWithEntityName: notImplemented, + hasNodeCheckFlag: notImplemented, + isDeclarationVisible: notImplemented, + isLateBound: (_node) => false, + collectLinkedAliases: notImplemented, + markLinkedReferences: notImplemented, + isImplementationOfOverload: notImplemented, + requiresAddingImplicitUndefined: notImplemented, + isExpandoFunctionDeclaration: notImplemented, + getPropertiesOfContainerFunction: notImplemented, + createTypeOfDeclaration: notImplemented, + createReturnTypeOfSignatureDeclaration: notImplemented, + createTypeOfExpression: notImplemented, + createLiteralConstValue: notImplemented, + isSymbolAccessible: notImplemented, + isEntityNameVisible: notImplemented, + // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant + getConstantValue: notImplemented, + getEnumMemberValue: notImplemented, + getReferencedValueDeclaration: notImplemented, + getReferencedValueDeclarations: notImplemented, + getTypeReferenceSerializationKind: notImplemented, + isOptionalParameter: notImplemented, + isArgumentsLocalBinding: notImplemented, + getExternalModuleFileFromDeclaration: notImplemented, + isLiteralConstDeclaration: notImplemented, + getJsxFactoryEntity: notImplemented, + getJsxFragmentFactoryEntity: notImplemented, + isBindingCapturedByNode: notImplemented, + getDeclarationStatementsForSourceFile: notImplemented, + isImportRequiredByAugmentation: notImplemented, + isDefinitelyReferenceToGlobalSymbolObject: notImplemented, + createLateBoundIndexSignatures: notImplemented +}; +var createPrinterWithDefaults = /* @__PURE__ */ memoize(() => createPrinter({})); +var createPrinterWithRemoveComments = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true })); +var createPrinterWithRemoveCommentsNeverAsciiEscape = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true })); +var createPrinterWithRemoveCommentsOmitTrailingSemicolon = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true })); +function createPrinter(printerOptions = {}, handlers = {}) { + var { + hasGlobalName, + onEmitNode = noEmitNotification, + isEmitNotificationEnabled, + substituteNode = noEmitSubstitution, + onBeforeEmitNode, + onAfterEmitNode, + onBeforeEmitNodeArray, + onAfterEmitNodeArray, + onBeforeEmitToken, + onAfterEmitToken + } = handlers; + var extendedDiagnostics = !!printerOptions.extendedDiagnostics; + var omitBraceSourcePositions = !!printerOptions.omitBraceSourceMapPositions; + var newLine = getNewLineCharacter(printerOptions); + var moduleKind = getEmitModuleKind(printerOptions); + var bundledHelpers = /* @__PURE__ */ new Map(); + var currentSourceFile; + var nodeIdToGeneratedName; + var nodeIdToGeneratedPrivateName; + var autoGeneratedIdToGeneratedName; + var generatedNames; + var formattedNameTempFlagsStack; + var formattedNameTempFlags; + var privateNameTempFlagsStack; + var privateNameTempFlags; + var tempFlagsStack; + var tempFlags; + var reservedNamesStack; + var reservedNames; + var reservedPrivateNamesStack; + var reservedPrivateNames; + var preserveSourceNewlines = printerOptions.preserveSourceNewlines; + var nextListElementPos; + var writer; + var ownWriter; + var write = writeBase; + var isOwnFileEmit; + var sourceMapsDisabled = true; + var sourceMapGenerator; + var sourceMapSource; + var sourceMapSourceIndex = -1; + var mostRecentlyAddedSourceMapSource; + var mostRecentlyAddedSourceMapSourceIndex = -1; + var containerPos = -1; + var containerEnd = -1; + var declarationListContainerEnd = -1; + var currentLineMap; + var detachedCommentsInfo; + var hasWrittenComment = false; + var commentsDisabled = !!printerOptions.removeComments; + var lastSubstitution; + var currentParenthesizerRule; + var { enter: enterComment, exit: exitComment } = createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"); + var parenthesizer = factory.parenthesizer; + var typeArgumentParenthesizerRuleSelector = { + select: (index) => index === 0 ? parenthesizer.parenthesizeLeadingTypeArgument : void 0 + }; + var emitBinaryExpression = createEmitBinaryExpression(); + reset(); + return { + // public API + printNode, + printList, + printFile, + printBundle, + // internal API + writeNode, + writeList, + writeFile: writeFile2, + writeBundle + }; + function printNode(hint, node, sourceFile) { + switch (hint) { + case 0 /* SourceFile */: + Debug.assert(isSourceFile(node), "Expected a SourceFile node."); + break; + case 2 /* IdentifierName */: + Debug.assert(isIdentifier(node), "Expected an Identifier node."); + break; + case 1 /* Expression */: + Debug.assert(isExpression(node), "Expected an Expression node."); + break; + } + switch (node.kind) { + case 307 /* SourceFile */: + return printFile(node); + case 308 /* Bundle */: + return printBundle(node); + } + writeNode(hint, node, sourceFile, beginPrint()); + return endPrint(); + } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } + function printBundle(bundle) { + writeBundle( + bundle, + beginPrint(), + /*sourceMapGenerator*/ + void 0 + ); + return endPrint(); + } + function printFile(sourceFile) { + writeFile2( + sourceFile, + beginPrint(), + /*sourceMapGenerator*/ + void 0 + ); + return endPrint(); + } + function writeNode(hint, node, sourceFile, output) { + const previousWriter = writer; + setWriter( + output, + /*_sourceMapGenerator*/ + void 0 + ); + print(hint, node, sourceFile); + reset(); + writer = previousWriter; + } + function writeList(format, nodes, sourceFile, output) { + const previousWriter = writer; + setWriter( + output, + /*_sourceMapGenerator*/ + void 0 + ); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList( + /*parentNode*/ + void 0, + nodes, + format + ); + reset(); + writer = previousWriter; + } + function writeBundle(bundle, output, sourceMapGenerator2) { + isOwnFileEmit = false; + const previousWriter = writer; + setWriter(output, sourceMapGenerator2); + emitShebangIfNeeded(bundle); + emitPrologueDirectivesIfNeeded(bundle); + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (const sourceFile of bundle.sourceFiles) { + print(0 /* SourceFile */, sourceFile, sourceFile); + } + reset(); + writer = previousWriter; + } + function writeFile2(sourceFile, output, sourceMapGenerator2) { + isOwnFileEmit = true; + const previousWriter = writer; + setWriter(output, sourceMapGenerator2); + emitShebangIfNeeded(sourceFile); + emitPrologueDirectivesIfNeeded(sourceFile); + print(0 /* SourceFile */, sourceFile, sourceFile); + reset(); + writer = previousWriter; + } + function beginPrint() { + return ownWriter || (ownWriter = createTextWriter(newLine)); + } + function endPrint() { + const text = ownWriter.getText(); + ownWriter.clear(); + return text; + } + function print(hint, node, sourceFile) { + if (sourceFile) { + setSourceFile(sourceFile); + } + pipelineEmit( + hint, + node, + /*parenthesizerRule*/ + void 0 + ); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentLineMap = void 0; + detachedCommentsInfo = void 0; + if (sourceFile) { + setSourceMapSource(sourceFile); + } + } + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = getTrailingSemicolonDeferringWriter(_writer); + } + writer = _writer; + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; + } + function reset() { + nodeIdToGeneratedName = []; + nodeIdToGeneratedPrivateName = []; + autoGeneratedIdToGeneratedName = []; + generatedNames = /* @__PURE__ */ new Set(); + formattedNameTempFlagsStack = []; + formattedNameTempFlags = /* @__PURE__ */ new Map(); + privateNameTempFlagsStack = []; + privateNameTempFlags = 0 /* Auto */; + tempFlagsStack = []; + tempFlags = 0 /* Auto */; + reservedNamesStack = []; + reservedNames = void 0; + reservedPrivateNamesStack = []; + reservedPrivateNames = void 0; + currentSourceFile = void 0; + currentLineMap = void 0; + detachedCommentsInfo = void 0; + setWriter( + /*output*/ + void 0, + /*_sourceMapGenerator*/ + void 0 + ); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = getLineStarts(Debug.checkDefined(currentSourceFile))); + } + function emit(node, parenthesizerRule) { + if (node === void 0) return; + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); + } + function emitIdentifierName(node) { + if (node === void 0) return; + pipelineEmit( + 2 /* IdentifierName */, + node, + /*parenthesizerRule*/ + void 0 + ); + } + function emitExpression(node, parenthesizerRule) { + if (node === void 0) return; + pipelineEmit(1 /* Expression */, node, parenthesizerRule); + } + function emitJsxAttributeValue(node) { + pipelineEmit(isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + } + function beforeEmitNode(node) { + if (preserveSourceNewlines && getInternalEmitFlags(node) & 4 /* IgnoreSourceNewlines */) { + preserveSourceNewlines = false; + } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; + const pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); + pipelinePhase(emitHint, node); + currentParenthesizerRule = void 0; + } + function shouldEmitComments(node) { + return !commentsDisabled && !isSourceFile(node); + } + function shouldEmitSourceMaps(node) { + return !sourceMapsDisabled && !isSourceFile(node) && !isInJsonFile(node); + } + function getPipelinePhase(phase, emitHint, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Substitution */: + if (substituteNode !== noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } + return pipelineEmitWithSubstitution; + } + // falls through + case 2 /* Comments */: + if (shouldEmitComments(node)) { + return pipelineEmitWithComments; + } + // falls through + case 3 /* SourceMaps */: + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; + } + // falls through + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return Debug.assertNever(phase); + } + } + function getNextPipelinePhase(currentPhase, emitHint, node) { + return getPipelinePhase(currentPhase + 1, emitHint, node); + } + function pipelineEmitWithNotification(hint, node) { + const pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + const savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); + } else { + pipelineEmitWithHintWorker(hint, node); + } + onAfterEmitNode == null ? void 0 : onAfterEmitNode(node); + currentParenthesizerRule = void 0; + } + function pipelineEmitWithHintWorker(hint, node, allowSnippets = true) { + if (allowSnippets) { + const snippet = getSnippetElement(node); + if (snippet) { + return emitSnippetNode(hint, node, snippet); + } + } + if (hint === 0 /* SourceFile */) return emitSourceFile(cast(node, isSourceFile)); + if (hint === 2 /* IdentifierName */) return emitIdentifier(cast(node, isIdentifier)); + if (hint === 6 /* JsxAttributeValue */) return emitLiteral( + cast(node, isStringLiteral), + /*jsxAttributeEscape*/ + true + ); + if (hint === 3 /* MappedTypeParameter */) return emitMappedTypeParameter(cast(node, isTypeParameterDeclaration)); + if (hint === 7 /* ImportTypeNodeAttributes */) return emitImportTypeNodeAttributes(cast(node, isImportAttributes)); + if (hint === 5 /* EmbeddedStatement */) { + Debug.assertNode(node, isEmptyStatement); + return emitEmptyStatement( + /*isEmbeddedStatement*/ + true + ); + } + if (hint === 4 /* Unspecified */) { + switch (node.kind) { + // Pseudo-literals + case 16 /* TemplateHead */: + case 17 /* TemplateMiddle */: + case 18 /* TemplateTail */: + return emitLiteral( + node, + /*jsxAttributeEscape*/ + false + ); + // Identifiers + case 80 /* Identifier */: + return emitIdentifier(node); + // PrivateIdentifiers + case 81 /* PrivateIdentifier */: + return emitPrivateIdentifier(node); + // Parse tree nodes + // Names + case 166 /* QualifiedName */: + return emitQualifiedName(node); + case 167 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 168 /* TypeParameter */: + return emitTypeParameter(node); + case 169 /* Parameter */: + return emitParameter(node); + case 170 /* Decorator */: + return emitDecorator(node); + // Type members + case 171 /* PropertySignature */: + return emitPropertySignature(node); + case 172 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 173 /* MethodSignature */: + return emitMethodSignature(node); + case 174 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 175 /* ClassStaticBlockDeclaration */: + return emitClassStaticBlockDeclaration(node); + case 176 /* Constructor */: + return emitConstructor(node); + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 179 /* CallSignature */: + return emitCallSignature(node); + case 180 /* ConstructSignature */: + return emitConstructSignature(node); + case 181 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 182 /* TypePredicate */: + return emitTypePredicate(node); + case 183 /* TypeReference */: + return emitTypeReference(node); + case 184 /* FunctionType */: + return emitFunctionType(node); + case 185 /* ConstructorType */: + return emitConstructorType(node); + case 186 /* TypeQuery */: + return emitTypeQuery(node); + case 187 /* TypeLiteral */: + return emitTypeLiteral(node); + case 188 /* ArrayType */: + return emitArrayType(node); + case 189 /* TupleType */: + return emitTupleType(node); + case 190 /* OptionalType */: + return emitOptionalType(node); + // SyntaxKind.RestType is handled below + case 192 /* UnionType */: + return emitUnionType(node); + case 193 /* IntersectionType */: + return emitIntersectionType(node); + case 194 /* ConditionalType */: + return emitConditionalType(node); + case 195 /* InferType */: + return emitInferType(node); + case 196 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 233 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 197 /* ThisType */: + return emitThisType(); + case 198 /* TypeOperator */: + return emitTypeOperator(node); + case 199 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 200 /* MappedType */: + return emitMappedType(node); + case 201 /* LiteralType */: + return emitLiteralType(node); + case 202 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 203 /* TemplateLiteralType */: + return emitTemplateType(node); + case 204 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 205 /* ImportType */: + return emitImportTypeNode(node); + // Binding patterns + case 206 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 207 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 208 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 239 /* TemplateSpan */: + return emitTemplateSpan(node); + case 240 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 241 /* Block */: + return emitBlock(node); + case 243 /* VariableStatement */: + return emitVariableStatement(node); + case 242 /* EmptyStatement */: + return emitEmptyStatement( + /*isEmbeddedStatement*/ + false + ); + case 244 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 245 /* IfStatement */: + return emitIfStatement(node); + case 246 /* DoStatement */: + return emitDoStatement(node); + case 247 /* WhileStatement */: + return emitWhileStatement(node); + case 248 /* ForStatement */: + return emitForStatement(node); + case 249 /* ForInStatement */: + return emitForInStatement(node); + case 250 /* ForOfStatement */: + return emitForOfStatement(node); + case 251 /* ContinueStatement */: + return emitContinueStatement(node); + case 252 /* BreakStatement */: + return emitBreakStatement(node); + case 253 /* ReturnStatement */: + return emitReturnStatement(node); + case 254 /* WithStatement */: + return emitWithStatement(node); + case 255 /* SwitchStatement */: + return emitSwitchStatement(node); + case 256 /* LabeledStatement */: + return emitLabeledStatement(node); + case 257 /* ThrowStatement */: + return emitThrowStatement(node); + case 258 /* TryStatement */: + return emitTryStatement(node); + case 259 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 260 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 261 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 262 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 263 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 264 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 265 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 266 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 267 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 268 /* ModuleBlock */: + return emitModuleBlock(node); + case 269 /* CaseBlock */: + return emitCaseBlock(node); + case 270 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 271 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 272 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 273 /* ImportClause */: + return emitImportClause(node); + case 274 /* NamespaceImport */: + return emitNamespaceImport(node); + case 280 /* NamespaceExport */: + return emitNamespaceExport(node); + case 275 /* NamedImports */: + return emitNamedImports(node); + case 276 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 277 /* ExportAssignment */: + return emitExportAssignment(node); + case 278 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 279 /* NamedExports */: + return emitNamedExports(node); + case 281 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 300 /* ImportAttributes */: + return emitImportAttributes(node); + case 301 /* ImportAttribute */: + return emitImportAttribute(node); + case 282 /* MissingDeclaration */: + return; + // Module references + case 283 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 12 /* JsxText */: + return emitJsxText(node); + case 286 /* JsxOpeningElement */: + case 289 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 287 /* JsxClosingElement */: + case 290 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 291 /* JsxAttribute */: + return emitJsxAttribute(node); + case 292 /* JsxAttributes */: + return emitJsxAttributes(node); + case 293 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 294 /* JsxExpression */: + return emitJsxExpression(node); + case 295 /* JsxNamespacedName */: + return emitJsxNamespacedName(node); + // Clauses + case 296 /* CaseClause */: + return emitCaseClause(node); + case 297 /* DefaultClause */: + return emitDefaultClause(node); + case 298 /* HeritageClause */: + return emitHeritageClause(node); + case 299 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 303 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 304 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 305 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 306 /* EnumMember */: + return emitEnumMember(node); + // Top-level nodes + case 307 /* SourceFile */: + return emitSourceFile(node); + case 308 /* Bundle */: + return Debug.fail("Bundles should be printed using printBundle"); + // JSDoc nodes (only used in codefixes currently) + case 309 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 310 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 312 /* JSDocAllType */: + return writePunctuation("*"); + case 313 /* JSDocUnknownType */: + return writePunctuation("?"); + case 314 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 315 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 316 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 317 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 191 /* RestType */: + case 318 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 319 /* JSDocNamepathType */: + return; + case 320 /* JSDoc */: + return emitJSDoc(node); + case 322 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 323 /* JSDocSignature */: + return emitJSDocSignature(node); + case 327 /* JSDocTag */: + case 332 /* JSDocClassTag */: + case 337 /* JSDocOverrideTag */: + return emitJSDocSimpleTag(node); + case 328 /* JSDocAugmentsTag */: + case 329 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 330 /* JSDocAuthorTag */: + case 331 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 333 /* JSDocPublicTag */: + case 334 /* JSDocPrivateTag */: + case 335 /* JSDocProtectedTag */: + case 336 /* JSDocReadonlyTag */: + return; + case 338 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 339 /* JSDocOverloadTag */: + return emitJSDocOverloadTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 341 /* JSDocParameterTag */: + case 348 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 340 /* JSDocEnumTag */: + case 342 /* JSDocReturnTag */: + case 343 /* JSDocThisTag */: + case 344 /* JSDocTypeTag */: + case 349 /* JSDocThrowsTag */: + case 350 /* JSDocSatisfiesTag */: + return emitJSDocSimpleTypedTag(node); + case 345 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 346 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 347 /* JSDocSeeTag */: + return emitJSDocSeeTag(node); + case 351 /* JSDocImportTag */: + return emitJSDocImportTag(node); + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 353 /* NotEmittedStatement */: + case 354 /* NotEmittedTypeElement */: + return; + } + if (isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== noEmitSubstitution) { + const substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } + } + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 11 /* StringLiteral */: + case 14 /* RegularExpressionLiteral */: + case 15 /* NoSubstitutionTemplateLiteral */: + return emitLiteral( + node, + /*jsxAttributeEscape*/ + false + ); + // Identifiers + case 80 /* Identifier */: + return emitIdentifier(node); + case 81 /* PrivateIdentifier */: + return emitPrivateIdentifier(node); + // Expressions + case 209 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 210 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 211 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 212 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 213 /* CallExpression */: + return emitCallExpression(node); + case 214 /* NewExpression */: + return emitNewExpression(node); + case 215 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 216 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 217 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 218 /* FunctionExpression */: + return emitFunctionExpression(node); + case 219 /* ArrowFunction */: + return emitArrowFunction(node); + case 220 /* DeleteExpression */: + return emitDeleteExpression(node); + case 221 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 222 /* VoidExpression */: + return emitVoidExpression(node); + case 223 /* AwaitExpression */: + return emitAwaitExpression(node); + case 224 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 225 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 226 /* BinaryExpression */: + return emitBinaryExpression(node); + case 227 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 228 /* TemplateExpression */: + return emitTemplateExpression(node); + case 229 /* YieldExpression */: + return emitYieldExpression(node); + case 230 /* SpreadElement */: + return emitSpreadElement(node); + case 231 /* ClassExpression */: + return emitClassExpression(node); + case 232 /* OmittedExpression */: + return; + case 234 /* AsExpression */: + return emitAsExpression(node); + case 235 /* NonNullExpression */: + return emitNonNullExpression(node); + case 233 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 238 /* SatisfiesExpression */: + return emitSatisfiesExpression(node); + case 236 /* MetaProperty */: + return emitMetaProperty(node); + case 237 /* SyntheticExpression */: + return Debug.fail("SyntheticExpression should never be printed."); + case 282 /* MissingDeclaration */: + return; + // JSX + case 284 /* JsxElement */: + return emitJsxElement(node); + case 285 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 288 /* JsxFragment */: + return emitJsxFragment(node); + // Synthesized list + case 352 /* SyntaxList */: + return Debug.fail("SyntaxList should not be printed"); + // Transformation nodes + case 353 /* NotEmittedStatement */: + return; + case 355 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 356 /* CommaListExpression */: + return emitCommaList(node); + case 357 /* SyntheticReferenceExpression */: + return Debug.fail("SyntheticReferenceExpression should not be printed"); + } + } + if (isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); + if (isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); + Debug.fail(`Unhandled SyntaxKind: ${Debug.formatSyntaxKind(node.kind)}.`); + } + function emitMappedTypeParameter(node) { + emit(node.name); + writeSpace(); + writeKeyword("in"); + writeSpace(); + emit(node.constraint); + } + function pipelineEmitWithSubstitution(hint, node) { + const pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); + Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = void 0; + pipelinePhase(hint, node); + } + function emitHelpers(node) { + let helpersEmitted = false; + const bundle = node.kind === 308 /* Bundle */ ? node : void 0; + if (bundle && moduleKind === 0 /* None */) { + return; + } + const numNodes = bundle ? bundle.sourceFiles.length : 1; + for (let i = 0; i < numNodes; i++) { + const currentNode = bundle ? bundle.sourceFiles[i] : node; + const sourceFile = isSourceFile(currentNode) ? currentNode : currentSourceFile; + const shouldSkip = printerOptions.noEmitHelpers || !!sourceFile && hasRecordedExternalHelpers(sourceFile); + const shouldBundle = isSourceFile(currentNode) && !isOwnFileEmit; + const helpers = getSortedEmitHelpers(currentNode); + if (helpers) { + for (const helper of helpers) { + if (!helper.scoped) { + if (shouldSkip) continue; + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } else if (bundle) { + continue; + } + if (typeof helper.text === "string") { + writeLines(helper.text); + } else { + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); + } + helpersEmitted = true; + } + } + } + return helpersEmitted; + } + function getSortedEmitHelpers(node) { + const helpers = getEmitHelpers(node); + return helpers && toSorted(helpers, compareEmitHelpers); + } + function emitNumericOrBigIntLiteral(node) { + emitLiteral( + node, + /*jsxAttributeEscape*/ + false + ); + } + function emitLiteral(node, jsxAttributeEscape) { + const text = getLiteralTextOfNode( + node, + /*sourceFile*/ + void 0, + printerOptions.neverAsciiEscape, + jsxAttributeEscape + ); + if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 11 /* StringLiteral */ || isTemplateLiteralKind(node.kind))) { + writeLiteral(text); + } else { + writeStringLiteral(text); + } + } + function emitSnippetNode(hint, node, snippet) { + switch (snippet.kind) { + case 1 /* Placeholder */: + emitPlaceholder(hint, node, snippet); + break; + case 0 /* TabStop */: + emitTabStop(hint, node, snippet); + break; + } + } + function emitPlaceholder(hint, node, snippet) { + nonEscapingWrite(`\${${snippet.order}:`); + pipelineEmitWithHintWorker( + hint, + node, + /*allowSnippets*/ + false + ); + nonEscapingWrite(`}`); + } + function emitTabStop(hint, node, snippet) { + Debug.assert(node.kind === 242 /* EmptyStatement */, `A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.`); + Debug.assert(hint !== 5 /* EmbeddedStatement */, `A tab stop cannot be attached to an embedded statement.`); + nonEscapingWrite(`$${snippet.order}`); + } + function emitIdentifier(node) { + const writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode2( + node, + /*includeTrivia*/ + false + ), node.symbol); + emitList(node, getIdentifierTypeArguments(node), 53776 /* TypeParameters */); + } + function emitPrivateIdentifier(node) { + write(getTextOfNode2( + node, + /*includeTrivia*/ + false + )); + } + function emitQualifiedName(node) { + emitEntityName(node.left); + writePunctuation("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 80 /* Identifier */) { + emitExpression(node); + } else { + emit(node); + } + } + function emitComputedPropertyName(node) { + writePunctuation("["); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); + writePunctuation("]"); + } + function emitTypeParameter(node) { + emitModifierList(node, node.modifiers); + emit(node.name); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } + } + function emitParameter(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 317 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } else { + emitTypeAnnotation(node.type); + } + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitDecorator(decorator) { + writePunctuation("@"); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); + } + function emitPropertySignature(node) { + emitModifierList(node, node.modifiers); + emitNodeWithWriter(node.name, writeProperty); + emit(node.questionToken); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitPropertyDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + emit(node.name); + emit(node.questionToken); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); + writeTrailingSemicolon(); + } + function emitMethodSignature(node) { + emitModifierList(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emitSignatureAndBody(node, emitSignatureHead, emitEmptyFunctionBody); + } + function emitMethodDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + emit(node.asteriskToken); + emit(node.name); + emit(node.questionToken); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); + } + function emitClassStaticBlockDeclaration(node) { + writeKeyword("static"); + pushNameGenerationScope(node); + emitBlockFunctionBody(node.body); + popNameGenerationScope(node); + } + function emitConstructor(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("constructor"); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); + } + function emitAccessorDeclaration(node) { + const pos = emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + const token = node.kind === 177 /* GetAccessor */ ? 139 /* GetKeyword */ : 153 /* SetKeyword */; + emitTokenWithComment(token, pos, writeKeyword, node); + writeSpace(); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); + } + function emitCallSignature(node) { + emitSignatureAndBody(node, emitSignatureHead, emitEmptyFunctionBody); + } + function emitConstructSignature(node) { + writeKeyword("new"); + writeSpace(); + emitSignatureAndBody(node, emitSignatureHead, emitEmptyFunctionBody); + } + function emitIndexSignature(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + emitParametersForIndexSignature(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitTemplateTypeSpan(node) { + emit(node.type); + emit(node.literal); + } + function emitSemicolonClassElement() { + writeTrailingSemicolon(); + } + function emitTypePredicate(node) { + if (node.assertsModifier) { + emit(node.assertsModifier); + writeSpace(); + } + emit(node.parameterName); + if (node.type) { + writeSpace(); + writeKeyword("is"); + writeSpace(); + emit(node.type); + } + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + emitSignatureAndBody(node, emitFunctionTypeHead, emitFunctionTypeBody); + } + function emitFunctionTypeHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + } + function emitFunctionTypeBody(node) { + writeSpace(); + emit(node.type); + } + function emitJSDocFunctionType(node) { + writeKeyword("function"); + emitParameters(node, node.parameters); + writePunctuation(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + writePunctuation("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + writePunctuation("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + writePunctuation("="); + } + function emitConstructorType(node) { + emitModifierList(node, node.modifiers); + writeKeyword("new"); + writeSpace(); + emitSignatureAndBody(node, emitFunctionTypeHead, emitFunctionTypeBody); + } + function emitTypeQuery(node) { + writeKeyword("typeof"); + writeSpace(); + emit(node.exprName); + emitTypeArguments(node, node.typeArguments); + } + function emitTypeLiteral(node) { + pushNameGenerationScope(node); + forEach(node.members, generateMemberNames); + writePunctuation("{"); + const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); + writePunctuation("}"); + popNameGenerationScope(node); + } + function emitArrayType(node) { + emit(node.elementType, parenthesizer.parenthesizeNonArrayTypeOfPostfixType); + writePunctuation("["); + writePunctuation("]"); + } + function emitRestOrJSDocVariadicType(node) { + writePunctuation("..."); + emit(node.type); + } + function emitTupleType(node) { + emitTokenWithComment(23 /* OpenBracketToken */, node.pos, writePunctuation, node); + const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 528 /* SingleLineTupleTypeElements */ : 657 /* MultiLineTupleTypeElements */; + emitList(node, node.elements, flags | 524288 /* NoSpaceIfEmpty */, parenthesizer.parenthesizeElementTypeOfTupleType); + emitTokenWithComment(24 /* CloseBracketToken */, node.elements.end, writePunctuation, node); + } + function emitNamedTupleMember(node) { + emit(node.dotDotDotToken); + emit(node.name); + emit(node.questionToken); + emitTokenWithComment(59 /* ColonToken */, node.name.end, writePunctuation, node); + writeSpace(); + emit(node.type); + } + function emitOptionalType(node) { + emit(node.type, parenthesizer.parenthesizeTypeOfOptionalType); + writePunctuation("?"); + } + function emitUnionType(node) { + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeConstituentTypeOfUnionType); + } + function emitIntersectionType(node) { + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeConstituentTypeOfIntersectionType); + } + function emitConditionalType(node) { + emit(node.checkType, parenthesizer.parenthesizeCheckTypeOfConditionalType); + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.extendsType, parenthesizer.parenthesizeExtendsTypeOfConditionalType); + writeSpace(); + writePunctuation("?"); + writeSpace(); + emit(node.trueType); + writeSpace(); + writePunctuation(":"); + writeSpace(); + emit(node.falseType); + } + function emitInferType(node) { + writeKeyword("infer"); + writeSpace(); + emit(node.typeParameter); + } + function emitParenthesizedType(node) { + writePunctuation("("); + emit(node.type); + writePunctuation(")"); + } + function emitThisType() { + writeKeyword("this"); + } + function emitTypeOperator(node) { + writeTokenText(node.operator, writeKeyword); + writeSpace(); + const parenthesizerRule = node.operator === 148 /* ReadonlyKeyword */ ? parenthesizer.parenthesizeOperandOfReadonlyTypeOperator : parenthesizer.parenthesizeOperandOfTypeOperator; + emit(node.type, parenthesizerRule); + } + function emitIndexedAccessType(node) { + emit(node.objectType, parenthesizer.parenthesizeNonArrayTypeOfPostfixType); + writePunctuation("["); + emit(node.indexType); + writePunctuation("]"); + } + function emitMappedType(node) { + const emitFlags = getEmitFlags(node); + writePunctuation("{"); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } else { + writeLine(); + increaseIndent(); + } + if (node.readonlyToken) { + emit(node.readonlyToken); + if (node.readonlyToken.kind !== 148 /* ReadonlyKeyword */) { + writeKeyword("readonly"); + } + writeSpace(); + } + writePunctuation("["); + pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter); + if (node.nameType) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.nameType); + } + writePunctuation("]"); + if (node.questionToken) { + emit(node.questionToken); + if (node.questionToken.kind !== 58 /* QuestionToken */) { + writePunctuation("?"); + } + } + writePunctuation(":"); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } else { + writeLine(); + decreaseIndent(); + } + emitList(node, node.members, 2 /* PreserveLines */); + writePunctuation("}"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitTemplateType(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); + } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + if (node.attributes) { + writePunctuation(","); + writeSpace(); + pipelineEmit(7 /* ImportTypeNodeAttributes */, node.attributes); + } + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } + function emitObjectBindingPattern(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); + writePunctuation("}"); + } + function emitArrayBindingPattern(node) { + writePunctuation("["); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); + writePunctuation("]"); + } + function emitBindingElement(node) { + emit(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } + emit(node.name); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitArrayLiteralExpression(node) { + const elements = node.elements; + const preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitObjectLiteralExpression(node) { + pushNameGenerationScope(node); + forEach(node.properties, generateMemberNames); + const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + const preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + const allowTrailingComma = currentSourceFile && currentSourceFile.languageVersion >= 1 /* ES5 */ && !isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + popNameGenerationScope(node); + } + function emitPropertyAccessExpression(node) { + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + const token = node.questionDotToken || setTextRangePosEnd(factory.createToken(25 /* DotToken */), node.expression.end, node.name.pos); + const linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); + const linesAfterDot = getLinesBetweenNodes(node, token, node.name); + writeLinesAndIndent( + linesBeforeDot, + /*writeSpaceIfNotIndenting*/ + false + ); + const shouldEmitDotDot = token.kind !== 29 /* QuestionDotToken */ && mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); + if (shouldEmitDotDot) { + writePunctuation("."); + } + if (node.questionDotToken) { + emit(token); + } else { + emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node); + } + writeLinesAndIndent( + linesAfterDot, + /*writeSpaceIfNotIndenting*/ + false + ); + emit(node.name); + decreaseIndentIf(linesBeforeDot, linesAfterDot); + } + function mayNeedDotDotForPropertyAccess(expression) { + expression = skipPartiallyEmittedExpressions(expression); + if (isNumericLiteral(expression)) { + const text = getLiteralTextOfNode( + expression, + /*sourceFile*/ + void 0, + /*neverAsciiEscape*/ + true, + /*jsxAttributeEscape*/ + false + ); + return !(expression.numericLiteralFlags & 448 /* WithSpecifier */) && !text.includes(tokenToString(25 /* DotToken */)) && !text.includes(String.fromCharCode(69 /* E */)) && !text.includes(String.fromCharCode(101 /* e */)); + } else if (isAccessExpression(expression)) { + const constantValue = getConstantValue(expression); + return typeof constantValue === "number" && isFinite(constantValue) && constantValue >= 0 && Math.floor(constantValue) === constantValue; + } + } + function emitElementAccessExpression(node) { + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + emit(node.questionDotToken); + emitTokenWithComment(23 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitExpression(node.argumentExpression); + emitTokenWithComment(24 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + } + function emitCallExpression(node) { + const indirectCall = getInternalEmitFlags(node) & 16 /* IndirectCall */; + if (indirectCall) { + writePunctuation("("); + writeLiteral("0"); + writePunctuation(","); + writeSpace(); + } + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + if (indirectCall) { + writePunctuation(")"); + } + emit(node.questionDotToken); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitNewExpression(node) { + emitTokenWithComment(105 /* NewKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitTaggedTemplateExpression(node) { + const indirectCall = getInternalEmitFlags(node) & 16 /* IndirectCall */; + if (indirectCall) { + writePunctuation("("); + writeLiteral("0"); + writePunctuation(","); + writeSpace(); + } + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); + if (indirectCall) { + writePunctuation(")"); + } + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + writePunctuation("<"); + emit(node.type); + writePunctuation(">"); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitParenthesizedExpression(node) { + const openParenPos = emitTokenWithComment(21 /* OpenParenToken */, node.pos, writePunctuation, node); + const indented = writeLineSeparatorsAndIndentBefore(node.expression, node); + emitExpression( + node.expression, + /*parenthesizerRule*/ + void 0 + ); + writeLineSeparatorsAfter(node.expression, node); + decreaseIndentIf(indented); + emitTokenWithComment(22 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + } + function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitModifierList(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead, emitArrowFunctionBody); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitTypeAnnotation(node.type); + writeSpace(); + emit(node.equalsGreaterThanToken); + } + function emitArrowFunctionBody(node) { + if (isBlock(node.body)) { + emitBlockFunctionBody(node.body); + } else { + writeSpace(); + emitExpression(node.body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); + } + } + function emitDeleteExpression(node) { + emitTokenWithComment(91 /* DeleteKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitTypeOfExpression(node) { + emitTokenWithComment(114 /* TypeOfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitVoidExpression(node) { + emitTokenWithComment(116 /* VoidKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitAwaitExpression(node) { + emitTokenWithComment(135 /* AwaitKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator, writeOperator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + writeSpace(); + } + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function shouldEmitWhitespaceBeforeOperand(node) { + const operand = node.operand; + return operand.kind === 224 /* PrefixUnaryExpression */ && (node.operator === 40 /* PlusToken */ && (operand.operator === 40 /* PlusToken */ || operand.operator === 46 /* PlusPlusToken */) || node.operator === 41 /* MinusToken */ && (operand.operator === 41 /* MinusToken */ || operand.operator === 47 /* MinusMinusToken */)); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); + writeTokenText(node.operator, writeOperator); + } + function createEmitBinaryExpression() { + return createBinaryExpressionTrampoline( + onEnter, + onLeft, + onOperator, + onRight, + onExit, + /*foldState*/ + void 0 + ); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines; + state.containerPosStack[state.stackIndex] = containerPos; + state.containerEndStack[state.stackIndex] = containerEnd; + state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; + const emitComments2 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); + const emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); + onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(node); + if (emitComments2) emitCommentsBeforeNode(node); + if (emitSourceMaps) emitSourceMapsBeforeNode(node); + beforeEmitNode(node); + } else { + state = { + stackIndex: 0, + preserveSourceNewlinesStack: [void 0], + containerPosStack: [-1], + containerEndStack: [-1], + declarationListContainerEndStack: [-1], + shouldEmitCommentsStack: [false], + shouldEmitSourceMapsStack: [false] + }; + } + return state; + } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } + function onOperator(operatorToken, _state, node) { + const isCommaOperator = operatorToken.kind !== 28 /* CommaToken */; + const linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); + const linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(operatorToken.pos); + writeTokenNode(operatorToken, operatorToken.kind === 103 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition( + operatorToken.end, + /*prefixSpace*/ + true + ); + writeLinesAndIndent( + linesAfterOperator, + /*writeSpaceIfNotIndenting*/ + true + ); + } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } + function onExit(node, state) { + const linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + const linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); + if (state.stackIndex > 0) { + const savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex]; + const savedContainerPos = state.containerPosStack[state.stackIndex]; + const savedContainerEnd = state.containerEndStack[state.stackIndex]; + const savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; + const shouldEmitComments2 = state.shouldEmitCommentsStack[state.stackIndex]; + const shouldEmitSourceMaps2 = state.shouldEmitSourceMapsStack[state.stackIndex]; + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps2) emitSourceMapsAfterNode(node); + if (shouldEmitComments2) emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode == null ? void 0 : onAfterEmitNode(node); + state.stackIndex--; + } + } + function maybeEmitExpression(next, parent, side) { + const parenthesizerRule = side === "left" ? parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); + let pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithSubstitution) { + Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(cast(lastSubstitution, isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = void 0; + } + if (pipelinePhase === pipelineEmitWithComments || pipelinePhase === pipelineEmitWithSourceMaps || pipelinePhase === pipelineEmitWithHint) { + if (isBinaryExpression(next)) { + return next; + } + } + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); + } + } + function emitConditionalExpression(node) { + const linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken); + const linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); + const linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); + const linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); + writeLinesAndIndent( + linesBeforeQuestion, + /*writeSpaceIfNotIndenting*/ + true + ); + emit(node.questionToken); + writeLinesAndIndent( + linesAfterQuestion, + /*writeSpaceIfNotIndenting*/ + true + ); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); + decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); + writeLinesAndIndent( + linesBeforeColon, + /*writeSpaceIfNotIndenting*/ + true + ); + emit(node.colonToken); + writeLinesAndIndent( + linesAfterColon, + /*writeSpaceIfNotIndenting*/ + true + ); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); + decreaseIndentIf(linesBeforeColon, linesAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); + } + function emitYieldExpression(node) { + emitTokenWithComment(127 /* YieldKeyword */, node.pos, writeKeyword, node); + emit(node.asteriskToken); + emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsiAndDisallowedComma); + } + function emitSpreadElement(node) { + emitTokenWithComment(26 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitClassExpression(node) { + generateNameIfNeeded(node.name); + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression( + node.expression, + /*parenthesizerRule*/ + void 0 + ); + if (node.type) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + writeOperator("!"); + } + function emitSatisfiesExpression(node) { + emitExpression( + node.expression, + /*parenthesizerRule*/ + void 0 + ); + if (node.type) { + writeSpace(); + writeKeyword("satisfies"); + writeSpace(); + emit(node.type); + } + } + function emitMetaProperty(node) { + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); + emit(node.name); + } + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + function emitBlock(node) { + emitBlockStatements( + node, + /*forceSingleLine*/ + !node.multiLine && isEmptyBlock(node) + ); + } + function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment( + 19 /* OpenBraceToken */, + node.pos, + writePunctuation, + /*contextNode*/ + node + ); + const format = forceSingleLine || getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; + emitList(node, node.statements, format); + emitTokenWithComment( + 20 /* CloseBraceToken */, + node.statements.end, + writePunctuation, + /*contextNode*/ + node, + /*indentLeading*/ + !!(format & 1 /* MultiLine */) + ); + } + function emitVariableStatement(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + emit(node.declarationList); + writeTrailingSemicolon(); + } + function emitEmptyStatement(isEmbeddedStatement) { + if (isEmbeddedStatement) { + writePunctuation(";"); + } else { + writeTrailingSemicolon(); + } + } + function emitExpressionStatement(node) { + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); + if (!currentSourceFile || !isJsonSourceFile(currentSourceFile) || nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); + } + } + function emitIfStatement(node) { + const openParenPos = emitTokenWithComment(101 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.thenStatement); + if (node.elseStatement) { + writeLineOrSpace(node, node.thenStatement, node.elseStatement); + emitTokenWithComment(93 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 245 /* IfStatement */) { + writeSpace(); + emit(node.elseStatement); + } else { + emitEmbeddedStatement(node, node.elseStatement); + } + } + } + function emitWhileClause(node, startPos) { + const openParenPos = emitTokenWithComment(117 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } + function emitDoStatement(node) { + emitTokenWithComment(92 /* DoKeyword */, node.pos, writeKeyword, node); + emitEmbeddedStatement(node, node.statement); + if (isBlock(node.statement) && !preserveSourceNewlines) { + writeSpace(); + } else { + writeLineOrSpace(node, node.statement, node.expression); + } + emitWhileClause(node, node.statement.end); + writeTrailingSemicolon(); + } + function emitWhileStatement(node) { + emitWhileClause(node, node.pos); + emitEmbeddedStatement(node, node.statement); + } + function emitForStatement(node) { + const openParenPos = emitTokenWithComment(99 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + let pos = emitTokenWithComment( + 21 /* OpenParenToken */, + openParenPos, + writePunctuation, + /*contextNode*/ + node + ); + emitForBinding(node.initializer); + pos = emitTokenWithComment(27 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.condition); + pos = emitTokenWithComment(27 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.incrementor); + emitTokenWithComment(22 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForInStatement(node) { + const openParenPos = emitTokenWithComment(99 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(103 /* InKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForOfStatement(node) { + const openParenPos = emitTokenWithComment(99 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(165 /* OfKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForBinding(node) { + if (node !== void 0) { + if (node.kind === 261 /* VariableDeclarationList */) { + emit(node); + } else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + emitTokenWithComment(88 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitBreakStatement(node) { + emitTokenWithComment(83 /* BreakKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitTokenWithComment(token, pos, writer2, contextNode, indentLeading) { + const node = getParseTreeNode(contextNode); + const isSimilarNode = node && node.kind === contextNode.kind; + const startPos = pos; + if (isSimilarNode && currentSourceFile) { + pos = skipTrivia(currentSourceFile.text, pos); + } + if (isSimilarNode && contextNode.pos !== startPos) { + const needsIndent = indentLeading && currentSourceFile && !positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + if (!omitBraceSourcePositions && (token === 19 /* OpenBraceToken */ || token === 20 /* CloseBraceToken */)) { + pos = writeToken(token, pos, writer2, contextNode); + } else { + pos = writeTokenText(token, writer2, pos); + } + if (isSimilarNode && contextNode.end !== pos) { + const isJsxExprContext = contextNode.kind === 294 /* JsxExpression */; + emitTrailingCommentsOfPosition( + pos, + /*prefixSpace*/ + !isJsxExprContext, + /*forceNoNewline*/ + isJsxExprContext + ); + } + return pos; + } + function commentWillEmitNewLine(node) { + return node.kind === 2 /* SingleLineCommentTrivia */ || !!node.hasTrailingNewLine; + } + function willEmitLeadingNewLine(node) { + if (!currentSourceFile) return false; + const leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); + if (leadingCommentRanges) { + const parseNode = getParseTreeNode(node); + if (parseNode && isParenthesizedExpression(parseNode.parent)) { + return true; + } + } + if (some(leadingCommentRanges, commentWillEmitNewLine)) return true; + if (some(getSyntheticLeadingComments(node), commentWillEmitNewLine)) return true; + if (isPartiallyEmittedExpression(node)) { + if (node.pos !== node.expression.pos) { + if (some(getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine)) return true; + } + return willEmitLeadingNewLine(node.expression); + } + return false; + } + function parenthesizeExpressionForNoAsi(node) { + if (!commentsDisabled) { + switch (node.kind) { + case 355 /* PartiallyEmittedExpression */: + if (willEmitLeadingNewLine(node)) { + const parseNode = getParseTreeNode(node); + if (parseNode && isParenthesizedExpression(parseNode)) { + const parens = factory.createParenthesizedExpression(node.expression); + setOriginalNode(parens, node); + setTextRange(parens, parseNode); + return parens; + } + return factory.createParenthesizedExpression(node); + } + return factory.updatePartiallyEmittedExpression( + node, + parenthesizeExpressionForNoAsi(node.expression) + ); + case 211 /* PropertyAccessExpression */: + return factory.updatePropertyAccessExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.name + ); + case 212 /* ElementAccessExpression */: + return factory.updateElementAccessExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.argumentExpression + ); + case 213 /* CallExpression */: + return factory.updateCallExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.typeArguments, + node.arguments + ); + case 215 /* TaggedTemplateExpression */: + return factory.updateTaggedTemplateExpression( + node, + parenthesizeExpressionForNoAsi(node.tag), + node.typeArguments, + node.template + ); + case 225 /* PostfixUnaryExpression */: + return factory.updatePostfixUnaryExpression( + node, + parenthesizeExpressionForNoAsi(node.operand) + ); + case 226 /* BinaryExpression */: + return factory.updateBinaryExpression( + node, + parenthesizeExpressionForNoAsi(node.left), + node.operatorToken, + node.right + ); + case 227 /* ConditionalExpression */: + return factory.updateConditionalExpression( + node, + parenthesizeExpressionForNoAsi(node.condition), + node.questionToken, + node.whenTrue, + node.colonToken, + node.whenFalse + ); + case 234 /* AsExpression */: + return factory.updateAsExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.type + ); + case 238 /* SatisfiesExpression */: + return factory.updateSatisfiesExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.type + ); + case 235 /* NonNullExpression */: + return factory.updateNonNullExpression( + node, + parenthesizeExpressionForNoAsi(node.expression) + ); + } + } + return node; + } + function parenthesizeExpressionForNoAsiAndDisallowedComma(node) { + return parenthesizeExpressionForNoAsi(parenthesizer.parenthesizeExpressionForDisallowedComma(node)); + } + function emitReturnStatement(node) { + emitTokenWithComment( + 107 /* ReturnKeyword */, + node.pos, + writeKeyword, + /*contextNode*/ + node + ); + emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); + writeTrailingSemicolon(); + } + function emitWithStatement(node) { + const openParenPos = emitTokenWithComment(118 /* WithKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitSwitchStatement(node) { + const openParenPos = emitTokenWithComment(109 /* SwitchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node); + writeSpace(); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + emitTokenWithComment(59 /* ColonToken */, node.label.end, writePunctuation, node); + writeSpace(); + emit(node.statement); + } + function emitThrowStatement(node) { + emitTokenWithComment(111 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); + writeTrailingSemicolon(); + } + function emitTryStatement(node) { + emitTokenWithComment(113 /* TryKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emit(node.tryBlock); + if (node.catchClause) { + writeLineOrSpace(node, node.tryBlock, node.catchClause); + emit(node.catchClause); + } + if (node.finallyBlock) { + writeLineOrSpace(node, node.catchClause || node.tryBlock, node.finallyBlock); + emitTokenWithComment(98 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + writeSpace(); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(89 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); + } + function emitVariableDeclaration(node) { + var _a, _b, _c; + emit(node.name); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, ((_a = node.type) == null ? void 0 : _a.end) ?? ((_c = (_b = node.name.emitNode) == null ? void 0 : _b.typeNode) == null ? void 0 : _c.end) ?? node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitVariableDeclarationList(node) { + if (isVarAwaitUsing(node)) { + writeKeyword("await"); + writeSpace(); + writeKeyword("using"); + } else { + const head = isLet(node) ? "let" : isVarConst(node) ? "const" : isVarUsing(node) ? "using" : "var"; + writeKeyword(head); + } + writeSpace(); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("function"); + emit(node.asteriskToken); + writeSpace(); + emitIdentifierName(node.name); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); + } + function emitSignatureAndBody(node, emitSignatureHead2, emitBody) { + const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + forEach(node.parameters, generateNames); + emitSignatureHead2(node); + emitBody(node); + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitFunctionBody(node) { + const body = node.body; + if (body) { + emitBlockFunctionBody(body); + } else { + writeTrailingSemicolon(); + } + } + function emitEmptyFunctionBody(_node) { + writeTrailingSemicolon(); + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + if (getEmitFlags(body) & 1 /* SingleLine */) { + return true; + } + if (body.multiLine) { + return false; + } + if (!nodeIsSynthesized(body) && currentSourceFile && !rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (getLeadingLineTerminatorCount(body, firstOrUndefined(body.statements), 2 /* PreserveLines */) || getClosingLineTerminatorCount(body, lastOrUndefined(body.statements), 2 /* PreserveLines */, body.statements)) { + return false; + } + let previousStatement; + for (const statement of body.statements) { + if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(body) { + generateNames(body); + onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(body); + writeSpace(); + writePunctuation("{"); + increaseIndent(); + const emitBlockFunctionBody2 = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker; + emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody2); + decreaseIndent(); + writeToken(20 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + onAfterEmitNode == null ? void 0 : onAfterEmitNode(body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker( + body, + /*emitBlockFunctionBodyOnSingleLine*/ + true + ); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine2) { + const statementOffset = emitPrologueDirectives(body.statements); + const pos = writer.getTextPos(); + emitHelpers(body); + if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine2) { + decreaseIndent(); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); + increaseIndent(); + } else { + emitList( + body, + body.statements, + 1 /* MultiLineFunctionBodyStatements */, + /*parenthesizerRule*/ + void 0, + statementOffset + ); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + emitTokenWithComment(86 /* ClassKeyword */, moveRangePastModifiers(node).pos, writeKeyword, node); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } + const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); + writeSpace(); + writePunctuation("{"); + pushNameGenerationScope(node); + forEach(node.members, generateMemberNames); + emitList(node, node.members, 129 /* ClassMembers */); + popNameGenerationScope(node); + writePunctuation("}"); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitInterfaceDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("interface"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); + writeSpace(); + writePunctuation("{"); + pushNameGenerationScope(node); + forEach(node.members, generateMemberNames); + emitList(node, node.members, 129 /* InterfaceMembers */); + popNameGenerationScope(node); + writePunctuation("}"); + } + function emitTypeAliasDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("type"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + writeSpace(); + writePunctuation("="); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + } + function emitEnumDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("enum"); + writeSpace(); + emit(node.name); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 145 /* EnumMembers */); + writePunctuation("}"); + } + function emitModuleDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + if (~node.flags & 2048 /* GlobalAugmentation */) { + writeKeyword(node.flags & 32 /* Namespace */ ? "namespace" : "module"); + writeSpace(); + } + emit(node.name); + let body = node.body; + if (!body) return writeTrailingSemicolon(); + while (body && isModuleDeclaration(body)) { + writePunctuation("."); + emit(body.name); + body = body.body; + } + writeSpace(); + emit(body); + } + function emitModuleBlock(node) { + pushNameGenerationScope(node); + forEach(node.statements, generateNames); + emitBlockStatements( + node, + /*forceSingleLine*/ + isEmptyBlock(node) + ); + popNameGenerationScope(node); + } + function emitCaseBlock(node) { + emitTokenWithComment(19 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment( + 20 /* CloseBraceToken */, + node.clauses.end, + writePunctuation, + node, + /*indentLeading*/ + true + ); + } + function emitImportEqualsDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + emitTokenWithComment(102 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.isTypeOnly) { + emitTokenWithComment(156 /* TypeKeyword */, node.pos, writeKeyword, node); + writeSpace(); + } + emit(node.name); + writeSpace(); + emitTokenWithComment(64 /* EqualsToken */, node.name.end, writePunctuation, node); + writeSpace(); + emitModuleReference(node.moduleReference); + writeTrailingSemicolon(); + } + function emitModuleReference(node) { + if (node.kind === 80 /* Identifier */) { + emitExpression(node); + } else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + emitTokenWithComment(102 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.importClause) { + emit(node.importClause); + writeSpace(); + emitTokenWithComment(161 /* FromKeyword */, node.importClause.end, writeKeyword, node); + writeSpace(); + } + emitExpression(node.moduleSpecifier); + if (node.attributes) { + emitWithLeadingSpace(node.attributes); + } + writeTrailingSemicolon(); + } + function emitImportClause(node) { + if (node.isTypeOnly) { + emitTokenWithComment(156 /* TypeKeyword */, node.pos, writeKeyword, node); + writeSpace(); + } + emit(node.name); + if (node.name && node.namedBindings) { + emitTokenWithComment(28 /* CommaToken */, node.name.end, writePunctuation, node); + writeSpace(); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + const asPos = emitTokenWithComment(42 /* AsteriskToken */, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(130 /* AsKeyword */, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + const nextPos = emitTokenWithComment(95 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.isExportEquals) { + emitTokenWithComment(64 /* EqualsToken */, nextPos, writeOperator, node); + } else { + emitTokenWithComment(90 /* DefaultKeyword */, nextPos, writeKeyword, node); + } + writeSpace(); + emitExpression( + node.expression, + node.isExportEquals ? parenthesizer.getParenthesizeRightSideOfBinaryForOperator(64 /* EqualsToken */) : parenthesizer.parenthesizeExpressionOfExportDefault + ); + writeTrailingSemicolon(); + } + function emitExportDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + let nextPos = emitTokenWithComment(95 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.isTypeOnly) { + nextPos = emitTokenWithComment(156 /* TypeKeyword */, nextPos, writeKeyword, node); + writeSpace(); + } + if (node.exportClause) { + emit(node.exportClause); + } else { + nextPos = emitTokenWithComment(42 /* AsteriskToken */, nextPos, writePunctuation, node); + } + if (node.moduleSpecifier) { + writeSpace(); + const fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(161 /* FromKeyword */, fromPos, writeKeyword, node); + writeSpace(); + emitExpression(node.moduleSpecifier); + } + if (node.attributes) { + emitWithLeadingSpace(node.attributes); + } + writeTrailingSemicolon(); + } + function emitImportTypeNodeAttributes(node) { + writePunctuation("{"); + writeSpace(); + writeKeyword(node.token === 132 /* AssertKeyword */ ? "assert" : "with"); + writePunctuation(":"); + writeSpace(); + const elements = node.elements; + emitList(node, elements, 526226 /* ImportAttributes */); + writeSpace(); + writePunctuation("}"); + } + function emitImportAttributes(node) { + emitTokenWithComment(node.token, node.pos, writeKeyword, node); + writeSpace(); + const elements = node.elements; + emitList(node, elements, 526226 /* ImportAttributes */); + } + function emitImportAttribute(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + const value = node.value; + if ((getEmitFlags(value) & 1024 /* NoLeadingComments */) === 0) { + const commentRange = getCommentRange(value); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emit(value); + } + function emitNamespaceExportDeclaration(node) { + let nextPos = emitTokenWithComment(95 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(130 /* AsKeyword */, nextPos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(145 /* NamespaceKeyword */, nextPos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeTrailingSemicolon(); + } + function emitNamespaceExport(node) { + const asPos = emitTokenWithComment(42 /* AsteriskToken */, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(130 /* AsKeyword */, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); + writePunctuation("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.isTypeOnly) { + writeKeyword("type"); + writeSpace(); + } + if (node.propertyName) { + emit(node.propertyName); + writeSpace(); + emitTokenWithComment(130 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + writeSpace(); + } + emit(node.name); + } + function emitExternalModuleReference(node) { + writeKeyword("require"); + writePunctuation("("); + emitExpression(node.expression); + writePunctuation(")"); + } + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + writePunctuation("<"); + emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emit(node.attributes); + writePunctuation("/>"); + } + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { + writePunctuation("<"); + if (isJsxOpeningElement(node)) { + const indented = writeLineSeparatorsAndIndentBefore(node.tagName, node); + emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); + if (node.attributes.properties && node.attributes.properties.length > 0) { + writeSpace(); + } + emit(node.attributes); + writeLineSeparatorsAfter(node.attributes, node); + decreaseIndentIf(indented); + } + writePunctuation(">"); + } + function emitJsxText(node) { + writer.writeLiteral(node.text); + } + function emitJsxClosingElementOrFragment(node) { + writePunctuation(""); + } + function emitJsxAttributes(node) { + emitList(node, node.properties, 262656 /* JsxElementAttributes */); + } + function emitJsxAttribute(node) { + emit(node.name); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue); + } + function emitJsxSpreadAttribute(node) { + writePunctuation("{..."); + emitExpression(node.expression); + writePunctuation("}"); + } + function hasTrailingCommentsAtPosition(pos) { + let result = false; + forEachTrailingCommentRange((currentSourceFile == null ? void 0 : currentSourceFile.text) || "", pos + 1, () => result = true); + return result; + } + function hasLeadingCommentsAtPosition(pos) { + let result = false; + forEachLeadingCommentRange((currentSourceFile == null ? void 0 : currentSourceFile.text) || "", pos + 1, () => result = true); + return result; + } + function hasCommentsAtPosition(pos) { + return hasTrailingCommentsAtPosition(pos) || hasLeadingCommentsAtPosition(pos); + } + function emitJsxExpression(node) { + var _a; + if (node.expression || !commentsDisabled && !nodeIsSynthesized(node) && hasCommentsAtPosition(node.pos)) { + const isMultiline = currentSourceFile && !nodeIsSynthesized(node) && getLineAndCharacterOfPosition(currentSourceFile, node.pos).line !== getLineAndCharacterOfPosition(currentSourceFile, node.end).line; + if (isMultiline) { + writer.increaseIndent(); + } + const end = emitTokenWithComment(19 /* OpenBraceToken */, node.pos, writePunctuation, node); + emit(node.dotDotDotToken); + emitExpression(node.expression); + emitTokenWithComment(20 /* CloseBraceToken */, ((_a = node.expression) == null ? void 0 : _a.end) || end, writePunctuation, node); + if (isMultiline) { + writer.decreaseIndent(); + } + } + } + function emitJsxNamespacedName(node) { + emitIdentifierName(node.namespace); + writePunctuation(":"); + emitIdentifierName(node.name); + } + function emitJsxTagName(node) { + if (node.kind === 80 /* Identifier */) { + emitExpression(node); + } else { + emit(node); + } + } + function emitCaseClause(node) { + emitTokenWithComment(84 /* CaseKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); + } + function emitDefaultClause(node) { + const pos = emitTokenWithComment(90 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); + } + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { + const emitAsSingleStatement = statements.length === 1 && // treat synthesized nodes as located on the same line for emit purposes + (!currentSourceFile || nodeIsSynthesized(parentNode) || nodeIsSynthesized(statements[0]) || rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + let format = 163969 /* CaseOrDefaultClauseStatements */; + if (emitAsSingleStatement) { + writeToken(59 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeSpace(); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); + } else { + emitTokenWithComment(59 /* ColonToken */, colonPos, writePunctuation, parentNode); + } + emitList(parentNode, statements, format); + } + function emitHeritageClause(node) { + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); + emitList(node, node.types, 528 /* HeritageClauseTypes */); + } + function emitCatchClause(node) { + const openParenPos = emitTokenWithComment(85 /* CatchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.variableDeclaration) { + emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node); + emit(node.variableDeclaration); + emitTokenWithComment(22 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + writeSpace(); + } + emit(node.block); + } + function emitPropertyAssignment(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + const initializer = node.initializer; + if ((getEmitFlags(initializer) & 1024 /* NoLeadingComments */) === 0) { + const commentRange = getCommentRange(initializer); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + writeSpace(); + writePunctuation("="); + writeSpace(); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + } + function emitSpreadAssignment(node) { + if (node.expression) { + emitTokenWithComment(26 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + } + function emitEnumMember(node) { + emit(node.name); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + const text = getTextOfJSDocComment(node.comment); + if (text) { + const lines = text.split(/\r\n?|\n/); + for (const line of lines) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 344 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocSeeTag(tag) { + emitJSDocTagName(tag.tagName); + emit(tag.name); + emitJSDocComment(tag.comment); + } + function emitJSDocImportTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + if (tag.importClause) { + emit(tag.importClause); + writeSpace(); + emitTokenWithComment(161 /* FromKeyword */, tag.importClause.end, writeKeyword, tag); + writeSpace(); + } + emitExpression(tag.moduleSpecifier); + if (tag.attributes) { + emitWithLeadingSpace(tag.attributes); + } + emitJSDocComment(tag.comment); + } + function emitJSDocNameReference(node) { + writeSpace(); + writePunctuation("{"); + emit(node.name); + writePunctuation("}"); + } + function emitJSDocHeritageTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 309 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 322 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocOverloadTag(tag) { + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, factory.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, factory.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, factory.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + const text = getTextOfJSDocComment(comment); + if (text) { + writeSpace(); + write(text); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + function emitSourceFile(node) { + writeLine(); + const statements = node.statements; + const shouldEmitDetachedComment = statements.length === 0 || !isPrologueDirective(statements[0]) || nodeIsSynthesized(statements[0]); + if (shouldEmitDetachedComment) { + emitBodyWithDetachedComments(node, statements, emitSourceFileWorker); + return; + } + emitSourceFileWorker(node); + } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs2) { + if (hasNoDefaultLib) { + writeComment(`/// `); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + writeComment(`/// `); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (const dep of currentSourceFile.amdDependencies) { + if (dep.name) { + writeComment(`/// `); + } else { + writeComment(`/// `); + } + writeLine(); + } + } + function writeDirectives(kind, directives) { + for (const directive of directives) { + const resolutionMode = directive.resolutionMode ? `resolution-mode="${directive.resolutionMode === 99 /* ESNext */ ? "import" : "require"}" ` : ""; + const preserve = directive.preserve ? `preserve="true" ` : ""; + writeComment(`/// `); + writeLine(); + } + } + writeDirectives("path", files); + writeDirectives("types", types); + writeDirectives("lib", libs2); + } + function emitSourceFileWorker(node) { + const statements = node.statements; + pushNameGenerationScope(node); + forEach(node.statements, generateNames); + emitHelpers(node); + const index = findIndex(statements, (statement) => !isPrologueDirective(statement)); + emitTripleSlashDirectivesIfNeeded(node); + emitList( + node, + statements, + 1 /* MultiLine */, + /*parenthesizerRule*/ + void 0, + index === -1 ? statements.length : index + ); + popNameGenerationScope(node); + } + function emitPartiallyEmittedExpression(node) { + const emitFlags = getEmitFlags(node); + if (!(emitFlags & 1024 /* NoLeadingComments */) && node.pos !== node.expression.pos) { + emitTrailingCommentsOfPosition(node.expression.pos); + } + emitExpression(node.expression); + if (!(emitFlags & 2048 /* NoTrailingComments */) && node.end !== node.expression.end) { + emitLeadingCommentsOfPosition(node.expression.end); + } + } + function emitCommaList(node) { + emitExpressionList( + node, + node.elements, + 528 /* CommaListElements */, + /*parenthesizerRule*/ + void 0 + ); + } + function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives) { + let needsToSetSourceFile = !!sourceFile; + for (let i = 0; i < statements.length; i++) { + const statement = statements[i]; + if (isPrologueDirective(statement)) { + const shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true; + if (shouldEmitPrologueDirective) { + if (needsToSetSourceFile) { + needsToSetSourceFile = false; + setSourceFile(sourceFile); + } + writeLine(); + emit(statement); + if (seenPrologueDirectives) { + seenPrologueDirectives.add(statement.expression.text); + } + } + } else { + return i; + } + } + return statements.length; + } + function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) { + if (isSourceFile(sourceFileOrBundle)) { + emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle); + } else { + const seenPrologueDirectives = /* @__PURE__ */ new Set(); + for (const sourceFile of sourceFileOrBundle.sourceFiles) { + emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives); + } + setSourceFile(void 0); + } + } + function emitShebangIfNeeded(sourceFileOrBundle) { + if (isSourceFile(sourceFileOrBundle)) { + const shebang = getShebang(sourceFileOrBundle.text); + if (shebang) { + writeComment(shebang); + writeLine(); + return true; + } + } else { + for (const sourceFile of sourceFileOrBundle.sourceFiles) { + if (emitShebangIfNeeded(sourceFile)) { + return true; + } + } + } + } + function emitNodeWithWriter(node, writer2) { + if (!node) return; + const savedWrite = write; + write = writer2; + emit(node); + write = savedWrite; + } + function emitDecoratorsAndModifiers(node, modifiers, allowDecorators) { + if (modifiers == null ? void 0 : modifiers.length) { + if (every(modifiers, isModifier)) { + return emitModifierList(node, modifiers); + } + if (every(modifiers, isDecorator)) { + if (allowDecorators) { + return emitDecoratorList(node, modifiers); + } + return node.pos; + } + onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(modifiers); + let lastMode; + let mode; + let start = 0; + let pos = 0; + let lastModifier; + while (start < modifiers.length) { + while (pos < modifiers.length) { + lastModifier = modifiers[pos]; + mode = isDecorator(lastModifier) ? "decorators" : "modifiers"; + if (lastMode === void 0) { + lastMode = mode; + } else if (mode !== lastMode) { + break; + } + pos++; + } + const textRange = { pos: -1, end: -1 }; + if (start === 0) textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) textRange.end = modifiers.end; + if (lastMode === "modifiers" || allowDecorators) { + emitNodeListItems( + emit, + node, + modifiers, + lastMode === "modifiers" ? 2359808 /* Modifiers */ : 2146305 /* Decorators */, + /*parenthesizerRule*/ + void 0, + start, + pos - start, + /*hasTrailingComma*/ + false, + textRange + ); + } + start = pos; + lastMode = mode; + pos++; + } + onAfterEmitNodeArray == null ? void 0 : onAfterEmitNodeArray(modifiers); + if (lastModifier && !positionIsSynthesized(lastModifier.end)) { + return lastModifier.end; + } + } + return node.pos; + } + function emitModifierList(node, modifiers) { + emitList(node, modifiers, 2359808 /* Modifiers */); + const lastModifier = lastOrUndefined(modifiers); + return lastModifier && !positionIsSynthesized(lastModifier.end) ? lastModifier.end : node.pos; + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { + if (node) { + writeSpace(); + emitTokenWithComment(64 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + writeSpace(); + emitExpression(node, parenthesizerRule); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit2) { + if (node) { + prefixWriter(prefix); + emit2(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { + if (node) { + writeSpace(); + emitExpression(node, parenthesizerRule); + } + } + function emitWithTrailingSpace(node) { + if (node) { + emit(node); + writeSpace(); + } + } + function emitEmbeddedStatement(parent, node) { + if (isBlock(node) || getEmitFlags(parent) & 1 /* SingleLine */ || preserveSourceNewlines && !getLeadingLineTerminatorCount(parent, node, 0 /* None */)) { + writeSpace(); + emit(node); + } else { + writeLine(); + increaseIndent(); + if (isEmptyStatement(node)) { + pipelineEmit(5 /* EmbeddedStatement */, node); + } else { + emit(node); + } + decreaseIndent(); + } + } + function emitDecoratorList(parentNode, decorators) { + emitList(parentNode, decorators, 2146305 /* Decorators */); + const lastDecorator = lastOrUndefined(decorators); + return lastDecorator && !positionIsSynthesized(lastDecorator.end) ? lastDecorator.end : parentNode.pos; + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, typeArgumentParenthesizerRuleSelector); + } + function emitTypeParameters(parentNode, typeParameters) { + if (isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 53776 /* TypeParameters */ | (isArrowFunction(parentNode) ? 64 /* AllowTrailingComma */ : 0 /* None */)); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 2576 /* Parameters */); + } + function canEmitSimpleArrowHead(parentNode, parameters) { + const parameter = singleOrUndefined(parameters); + return parameter && parameter.pos === parentNode.pos && isArrowFunction(parentNode) && !parentNode.type && !some(parentNode.modifiers) && !some(parentNode.typeParameters) && !some(parameter.modifiers) && !parameter.dotDotDotToken && !parameter.questionToken && !parameter.type && !parameter.initializer && isIdentifier(parameter.name); + } + function emitParametersForArrow(parentNode, parameters) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); + } else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); + } + function writeDelimiter(format) { + switch (format & 60 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList( + emit, + parentNode, + children, + format | (parentNode && getEmitFlags(parentNode) & 2 /* MultiLine */ ? 65536 /* PreferNewLine */ : 0), + parenthesizerRule, + start, + count + ); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit2, parentNode, children, format, parenthesizerRule, start = 0, count = children ? children.length - start : 0) { + const isUndefined = children === void 0; + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { + return; + } + const isEmpty = children === void 0 || start >= children.length || count === 0; + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { + onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(children); + onAfterEmitNodeArray == null ? void 0 : onAfterEmitNodeArray(children); + return; + } + if (format & 15360 /* BracketsMask */) { + writePunctuation(getOpeningBracket(format)); + if (isEmpty && children) { + emitTrailingCommentsOfPosition( + children.pos, + /*prefixSpace*/ + true + ); + } + } + onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(children); + if (isEmpty) { + if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && (!parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile)))) { + writeLine(); + } else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { + writeSpace(); + } + } else { + emitNodeListItems(emit2, parentNode, children, format, parenthesizerRule, start, count, children.hasTrailingComma, children); + } + onAfterEmitNodeArray == null ? void 0 : onAfterEmitNodeArray(children); + if (format & 15360 /* BracketsMask */) { + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); + } + writePunctuation(getClosingBracket(format)); + } + } + function emitNodeListItems(emit2, parentNode, children, format, parenthesizerRule, start, count, hasTrailingComma, childrenTextRange) { + const mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; + let shouldEmitInterveningComments = mayEmitInterveningComments; + const leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start], format); + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); + shouldEmitInterveningComments = false; + } else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + if (format & 128 /* Indented */) { + increaseIndent(); + } + const emitListItem = getEmitListItem(emit2, parenthesizerRule); + let previousSibling; + let shouldDecreaseIndentAfterEmit = false; + for (let i = 0; i < count; i++) { + const child = children[start + i]; + if (format & 32 /* AsteriskDelimited */) { + writeLine(); + writeDelimiter(format); + } else if (previousSibling) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { + const previousSiblingEmitFlags = getEmitFlags(previousSibling); + if (!(previousSiblingEmitFlags & 2048 /* NoTrailingComments */)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + } + writeDelimiter(format); + const separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + if (shouldEmitInterveningComments && format & 60 /* DelimitersMask */ && !positionIsSynthesized(child.pos)) { + const commentRange = getCommentRange(child); + emitTrailingCommentsOfPosition( + commentRange.pos, + /*prefixSpace*/ + !!(format & 512 /* SpaceBetweenSiblings */), + /*forceNoNewline*/ + true + ); + } + writeLine(separatingLineTerminatorCount); + shouldEmitInterveningComments = false; + } else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { + writeSpace(); + } + } + if (shouldEmitInterveningComments) { + const commentRange = getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); + } else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + nextListElementPos = child.pos; + emitListItem(child, emit2, parenthesizerRule, i); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + const emitFlags = previousSibling ? getEmitFlags(previousSibling) : 0; + const skipTrailingComments = commentsDisabled || !!(emitFlags & 2048 /* NoTrailingComments */); + const emitTrailingComma = hasTrailingComma && format & 64 /* AllowTrailingComma */ && format & 16 /* CommaDelimited */; + if (emitTrailingComma) { + if (previousSibling && !skipTrailingComments) { + emitTokenWithComment(28 /* CommaToken */, previousSibling.end, writePunctuation, previousSibling); + } else { + writePunctuation(","); + } + } + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && format & 60 /* DelimitersMask */ && !skipTrailingComments) { + emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange == null ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); + } + if (format & 128 /* Indented */) { + decreaseIndent(); + } + const closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start + count - 1], format, childrenTextRange); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); + } else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) { + writeSpace(); + } + } + function writeLiteral(s) { + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + writer.writeStringLiteral(s); + } + function writeBase(s) { + writer.write(s); + } + function writeSymbol(s, sym) { + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + writer.writePunctuation(s); + } + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); + } + function writeKeyword(s) { + writer.writeKeyword(s); + } + function writeOperator(s) { + writer.writeOperator(s); + } + function writeParameter(s) { + writer.writeParameter(s); + } + function writeComment(s) { + writer.writeComment(s); + } + function writeSpace() { + writer.writeSpace(" "); + } + function writeProperty(s) { + writer.writeProperty(s); + } + function nonEscapingWrite(s) { + if (writer.nonEscapingWrite) { + writer.nonEscapingWrite(s); + } else { + writer.write(s); + } + } + function writeLine(count = 1) { + for (let i = 0; i < count; i++) { + writer.writeLine(i > 0); + } + } + function increaseIndent() { + writer.increaseIndent(); + } + function decreaseIndent() { + writer.decreaseIndent(); + } + function writeToken(token, pos, writer2, contextNode) { + return !sourceMapsDisabled ? emitTokenWithSourceMap(contextNode, token, writer2, pos, writeTokenText) : writeTokenText(token, writer2, pos); + } + function writeTokenNode(node, writer2) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writer2(tokenToString(node.kind)); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token, writer2, pos) { + const tokenString = tokenToString(token); + writer2(tokenString); + return pos < 0 ? pos : pos + tokenString.length; + } + function writeLineOrSpace(parentNode, prevChildNode, nextChildNode) { + if (getEmitFlags(parentNode) & 1 /* SingleLine */) { + writeSpace(); + } else if (preserveSourceNewlines) { + const lines = getLinesBetweenNodes(parentNode, prevChildNode, nextChildNode); + if (lines) { + writeLine(lines); + } else { + writeSpace(); + } + } else { + writeLine(); + } + } + function writeLines(text) { + const lines = text.split(/\r\n?|\n/); + const indentation = guessIndentation(lines); + for (const lineText of lines) { + const line = indentation ? lineText.slice(indentation) : lineText; + if (line.length) { + writeLine(); + write(line); + } + } + } + function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) { + if (lineCount) { + increaseIndent(); + writeLine(lineCount); + } else if (writeSpaceIfNotIndenting) { + writeSpace(); + } + } + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function getLeadingLineTerminatorCount(parentNode, firstChild, format) { + if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { + if (format & 65536 /* PreferNewLine */) { + return 1; + } + if (firstChild === void 0) { + return !parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + } + if (firstChild.pos === nextListElementPos) { + return 0; + } + if (firstChild.kind === 12 /* JsxText */) { + return 0; + } + if (currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(firstChild) && (!firstChild.parent || getOriginalNode(firstChild.parent) === getOriginalNode(parentNode))) { + if (preserveSourceNewlines) { + return getEffectiveLines( + (includeComments) => getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter( + firstChild.pos, + parentNode.pos, + currentSourceFile, + includeComments + ) + ); + } + return rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; + } + if (synthesizedNodeStartsOnNewLine(firstChild, format)) { + return 1; + } + } + return format & 1 /* MultiLine */ ? 1 : 0; + } + function getSeparatingLineTerminatorCount(previousNode, nextNode, format) { + if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { + if (previousNode === void 0 || nextNode === void 0) { + return 0; + } + if (nextNode.kind === 12 /* JsxText */) { + return 0; + } else if (currentSourceFile && !nodeIsSynthesized(previousNode) && !nodeIsSynthesized(nextNode)) { + if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { + return getEffectiveLines( + (includeComments) => getLinesBetweenRangeEndAndRangeStart( + previousNode, + nextNode, + currentSourceFile, + includeComments + ) + ); + } else if (!preserveSourceNewlines && originalNodesHaveSameParent(previousNode, nextNode)) { + return rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; + } + return format & 65536 /* PreferNewLine */ ? 1 : 0; + } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { + return 1; + } + } else if (getStartsOnNewLine(nextNode)) { + return 1; + } + return format & 1 /* MultiLine */ ? 1 : 0; + } + function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) { + if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { + if (format & 65536 /* PreferNewLine */) { + return 1; + } + if (lastChild === void 0) { + return !parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + } + if (currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { + if (preserveSourceNewlines) { + const end = childrenTextRange && !positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; + return getEffectiveLines( + (includeComments) => getLinesBetweenPositionAndNextNonWhitespaceCharacter( + end, + parentNode.end, + currentSourceFile, + includeComments + ) + ); + } + return rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; + } + if (synthesizedNodeStartsOnNewLine(lastChild, format)) { + return 1; + } + } + if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) { + return 1; + } + return 0; + } + function getEffectiveLines(getLineDifference) { + Debug.assert(!!preserveSourceNewlines); + const lines = getLineDifference( + /*includeComments*/ + true + ); + if (lines === 0) { + return getLineDifference( + /*includeComments*/ + false + ); + } + return lines; + } + function writeLineSeparatorsAndIndentBefore(node, parent) { + const leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, node, 0 /* None */); + if (leadingNewlines) { + writeLinesAndIndent( + leadingNewlines, + /*writeSpaceIfNotIndenting*/ + false + ); + } + return !!leadingNewlines; + } + function writeLineSeparatorsAfter(node, parent) { + const trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount( + parent, + node, + 0 /* None */, + /*childrenTextRange*/ + void 0 + ); + if (trailingNewlines) { + writeLine(trailingNewlines); + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (nodeIsSynthesized(node)) { + const startsOnNewLine = getStartsOnNewLine(node); + if (startsOnNewLine === void 0) { + return (format & 65536 /* PreferNewLine */) !== 0; + } + return startsOnNewLine; + } + return (format & 65536 /* PreferNewLine */) !== 0; + } + function getLinesBetweenNodes(parent, node1, node2) { + if (getEmitFlags(parent) & 262144 /* NoIndentation */) { + return 0; + } + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + if (getStartsOnNewLine(node2)) { + return 1; + } + if (currentSourceFile && !nodeIsSynthesized(parent) && !nodeIsSynthesized(node1) && !nodeIsSynthesized(node2)) { + if (preserveSourceNewlines) { + return getEffectiveLines( + (includeComments) => getLinesBetweenRangeEndAndRangeStart( + node1, + node2, + currentSourceFile, + includeComments + ) + ); + } + return rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1; + } + return 0; + } + function isEmptyBlock(block) { + return block.statements.length === 0 && (!currentSourceFile || rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile)); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 217 /* ParenthesizedExpression */ && nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode2(node, includeTrivia) { + if (isGeneratedIdentifier(node) || isGeneratedPrivateIdentifier(node)) { + return generateName(node); + } + if (isStringLiteral(node) && node.textSourceNode) { + return getTextOfNode2(node.textSourceNode, includeTrivia); + } + const sourceFile = currentSourceFile; + const canUseSourceFile = !!sourceFile && !!node.parent && !nodeIsSynthesized(node); + if (isMemberName(node)) { + if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { + return idText(node); + } + } else if (isJsxNamespacedName(node)) { + if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { + return getTextOfJsxNamespacedName(node); + } + } else { + Debug.assertNode(node, isLiteralExpression); + if (!canUseSourceFile) { + return node.text; + } + } + return getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node, sourceFile = currentSourceFile, neverAsciiEscape, jsxAttributeEscape) { + if (node.kind === 11 /* StringLiteral */ && node.textSourceNode) { + const textSourceNode = node.textSourceNode; + if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode) || isJsxNamespacedName(textSourceNode)) { + const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode2(textSourceNode); + return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; + } else { + return getLiteralTextOfNode(textSourceNode, getSourceFileOfNode(textSourceNode), neverAsciiEscape, jsxAttributeEscape); + } + } + const flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0) | (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0) | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0) | (printerOptions.target && printerOptions.target >= 8 /* ES2021 */ ? 8 /* AllowNumericSeparator */ : 0); + return getLiteralText(node, sourceFile, flags); + } + function pushNameGenerationScope(node) { + privateNameTempFlagsStack.push(privateNameTempFlags); + privateNameTempFlags = 0 /* Auto */; + reservedPrivateNamesStack.push(reservedPrivateNames); + if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { + return; + } + tempFlagsStack.push(tempFlags); + tempFlags = 0 /* Auto */; + formattedNameTempFlagsStack.push(formattedNameTempFlags); + formattedNameTempFlags = void 0; + reservedNamesStack.push(reservedNames); + } + function popNameGenerationScope(node) { + privateNameTempFlags = privateNameTempFlagsStack.pop(); + reservedPrivateNames = reservedPrivateNamesStack.pop(); + if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { + return; + } + tempFlags = tempFlagsStack.pop(); + formattedNameTempFlags = formattedNameTempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === lastOrUndefined(reservedNamesStack)) { + reservedNames = /* @__PURE__ */ new Set(); + } + reservedNames.add(name); + } + function reservePrivateNameInNestedScopes(name) { + if (!reservedPrivateNames || reservedPrivateNames === lastOrUndefined(reservedPrivateNamesStack)) { + reservedPrivateNames = /* @__PURE__ */ new Set(); + } + reservedPrivateNames.add(name); + } + function generateNames(node) { + if (!node) return; + switch (node.kind) { + case 241 /* Block */: + forEach(node.statements, generateNames); + break; + case 256 /* LabeledStatement */: + case 254 /* WithStatement */: + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + generateNames(node.statement); + break; + case 245 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 248 /* ForStatement */: + case 250 /* ForOfStatement */: + case 249 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 255 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 269 /* CaseBlock */: + forEach(node.clauses, generateNames); + break; + case 296 /* CaseClause */: + case 297 /* DefaultClause */: + forEach(node.statements, generateNames); + break; + case 258 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 299 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 243 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 261 /* VariableDeclarationList */: + forEach(node.declarations, generateNames); + break; + case 260 /* VariableDeclaration */: + case 169 /* Parameter */: + case 208 /* BindingElement */: + case 263 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 262 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { + forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 206 /* ObjectBindingPattern */: + case 207 /* ArrayBindingPattern */: + forEach(node.elements, generateNames); + break; + case 272 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 273 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 274 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 280 /* NamespaceExport */: + generateNameIfNeeded(node.name); + break; + case 275 /* NamedImports */: + forEach(node.elements, generateNames); + break; + case 276 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) return; + switch (node.kind) { + case 303 /* PropertyAssignment */: + case 304 /* ShorthandPropertyAssignment */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (isGeneratedIdentifier(name) || isGeneratedPrivateIdentifier(name)) { + generateName(name); + } else if (isBindingPattern(name)) { + generateNames(name); + } + } + } + function generateName(name) { + const autoGenerate = name.emitNode.autoGenerate; + if ((autoGenerate.flags & 7 /* KindMask */) === 4 /* Node */) { + return generateNameCached(getNodeForGeneratedName(name), isPrivateIdentifier(name), autoGenerate.flags, autoGenerate.prefix, autoGenerate.suffix); + } else { + const autoGenerateId = autoGenerate.id; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); + } + } + function generateNameCached(node, privateName, flags, prefix, suffix) { + const nodeId = getNodeId(node); + const cache = privateName ? nodeIdToGeneratedPrivateName : nodeIdToGeneratedName; + return cache[nodeId] || (cache[nodeId] = generateNameForNode(node, privateName, flags ?? 0 /* None */, formatGeneratedNamePart(prefix, generateName), formatGeneratedNamePart(suffix))); + } + function isUniqueName(name, privateName) { + return isFileLevelUniqueNameInCurrentFile(name, privateName) && !isReservedName(name, privateName) && !generatedNames.has(name); + } + function isReservedName(name, privateName) { + let set; + let stack; + if (privateName) { + set = reservedPrivateNames; + stack = reservedPrivateNamesStack; + } else { + set = reservedNames; + stack = reservedNamesStack; + } + if (set == null ? void 0 : set.has(name)) { + return true; + } + for (let i = stack.length - 1; i >= 0; i--) { + if (set === stack[i]) { + continue; + } + set = stack[i]; + if (set == null ? void 0 : set.has(name)) { + return true; + } + } + return false; + } + function isFileLevelUniqueNameInCurrentFile(name, _isPrivate) { + return currentSourceFile ? isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } + function isUniqueLocalName(name, container) { + for (let node = container; node && isNodeDescendantOf(node, container); node = node.nextContainer) { + if (canHaveLocals(node) && node.locals) { + const local = node.locals.get(escapeLeadingUnderscores(name)); + if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + return false; + } + } + } + return true; + } + function getTempFlags(formattedNameKey) { + switch (formattedNameKey) { + case "": + return tempFlags; + case "#": + return privateNameTempFlags; + default: + return (formattedNameTempFlags == null ? void 0 : formattedNameTempFlags.get(formattedNameKey)) ?? 0 /* Auto */; + } + } + function setTempFlags(formattedNameKey, flags) { + switch (formattedNameKey) { + case "": + tempFlags = flags; + break; + case "#": + privateNameTempFlags = flags; + break; + default: + formattedNameTempFlags ?? (formattedNameTempFlags = /* @__PURE__ */ new Map()); + formattedNameTempFlags.set(formattedNameKey, flags); + break; + } + } + function makeTempVariableName(flags, reservedInNestedScopes, privateName, prefix, suffix) { + if (prefix.length > 0 && prefix.charCodeAt(0) === 35 /* hash */) { + prefix = prefix.slice(1); + } + const key = formatGeneratedName(privateName, prefix, "", suffix); + let tempFlags2 = getTempFlags(key); + if (flags && !(tempFlags2 & flags)) { + const name = flags === 268435456 /* _i */ ? "_i" : "_n"; + const fullName = formatGeneratedName(privateName, prefix, name, suffix); + if (isUniqueName(fullName, privateName)) { + tempFlags2 |= flags; + if (privateName) { + reservePrivateNameInNestedScopes(fullName); + } else if (reservedInNestedScopes) { + reserveNameInNestedScopes(fullName); + } + setTempFlags(key, tempFlags2); + return fullName; + } + } + while (true) { + const count = tempFlags2 & 268435455 /* CountMask */; + tempFlags2++; + if (count !== 8 && count !== 13) { + const name = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); + const fullName = formatGeneratedName(privateName, prefix, name, suffix); + if (isUniqueName(fullName, privateName)) { + if (privateName) { + reservePrivateNameInNestedScopes(fullName); + } else if (reservedInNestedScopes) { + reserveNameInNestedScopes(fullName); + } + setTempFlags(key, tempFlags2); + return fullName; + } + } + } + } + function makeUniqueName(baseName, checkFn = isUniqueName, optimistic, scoped, privateName, prefix, suffix) { + if (baseName.length > 0 && baseName.charCodeAt(0) === 35 /* hash */) { + baseName = baseName.slice(1); + } + if (prefix.length > 0 && prefix.charCodeAt(0) === 35 /* hash */) { + prefix = prefix.slice(1); + } + if (optimistic) { + const fullName = formatGeneratedName(privateName, prefix, baseName, suffix); + if (checkFn(fullName, privateName)) { + if (privateName) { + reservePrivateNameInNestedScopes(fullName); + } else if (scoped) { + reserveNameInNestedScopes(fullName); + } else { + generatedNames.add(fullName); + } + return fullName; + } + } + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + let i = 1; + while (true) { + const fullName = formatGeneratedName(privateName, prefix, baseName + i, suffix); + if (checkFn(fullName, privateName)) { + if (privateName) { + reservePrivateNameInNestedScopes(fullName); + } else if (scoped) { + reserveNameInNestedScopes(fullName); + } else { + generatedNames.add(fullName); + } + return fullName; + } + i++; + } + } + function makeFileLevelOptimisticUniqueName(name) { + return makeUniqueName( + name, + isFileLevelUniqueNameInCurrentFile, + /*optimistic*/ + true, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForModuleOrEnum(node) { + const name = getTextOfNode2(node.name); + return isUniqueLocalName(name, tryCast(node, canHaveLocals)) ? name : makeUniqueName( + name, + isUniqueName, + /*optimistic*/ + false, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForImportOrExportDeclaration(node) { + const expr = getExternalModuleName(node); + const baseName = isStringLiteral(expr) ? makeIdentifierFromModuleName(expr.text) : "module"; + return makeUniqueName( + baseName, + isUniqueName, + /*optimistic*/ + false, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForExportDefault() { + return makeUniqueName( + "default", + isUniqueName, + /*optimistic*/ + false, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForClassExpression() { + return makeUniqueName( + "class", + isUniqueName, + /*optimistic*/ + false, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForMethodOrAccessor(node, privateName, prefix, suffix) { + if (isIdentifier(node.name)) { + return generateNameCached(node.name, privateName); + } + return makeTempVariableName( + 0 /* Auto */, + /*reservedInNestedScopes*/ + false, + privateName, + prefix, + suffix + ); + } + function generateNameForNode(node, privateName, flags, prefix, suffix) { + switch (node.kind) { + case 80 /* Identifier */: + case 81 /* PrivateIdentifier */: + return makeUniqueName( + getTextOfNode2(node), + isUniqueName, + !!(flags & 16 /* Optimistic */), + !!(flags & 8 /* ReservedInNestedScopes */), + privateName, + prefix, + suffix + ); + case 267 /* ModuleDeclaration */: + case 266 /* EnumDeclaration */: + Debug.assert(!prefix && !suffix && !privateName); + return generateNameForModuleOrEnum(node); + case 272 /* ImportDeclaration */: + case 278 /* ExportDeclaration */: + Debug.assert(!prefix && !suffix && !privateName); + return generateNameForImportOrExportDeclaration(node); + case 262 /* FunctionDeclaration */: + case 263 /* ClassDeclaration */: { + Debug.assert(!prefix && !suffix && !privateName); + const name = node.name; + if (name && !isGeneratedIdentifier(name)) { + return generateNameForNode( + name, + /*privateName*/ + false, + flags, + prefix, + suffix + ); + } + return generateNameForExportDefault(); + } + case 277 /* ExportAssignment */: + Debug.assert(!prefix && !suffix && !privateName); + return generateNameForExportDefault(); + case 231 /* ClassExpression */: + Debug.assert(!prefix && !suffix && !privateName); + return generateNameForClassExpression(); + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return generateNameForMethodOrAccessor(node, privateName, prefix, suffix); + case 167 /* ComputedPropertyName */: + return makeTempVariableName( + 0 /* Auto */, + /*reservedInNestedScopes*/ + true, + privateName, + prefix, + suffix + ); + default: + return makeTempVariableName( + 0 /* Auto */, + /*reservedInNestedScopes*/ + false, + privateName, + prefix, + suffix + ); + } + } + function makeName(name) { + const autoGenerate = name.emitNode.autoGenerate; + const prefix = formatGeneratedNamePart(autoGenerate.prefix, generateName); + const suffix = formatGeneratedNamePart(autoGenerate.suffix); + switch (autoGenerate.flags & 7 /* KindMask */) { + case 1 /* Auto */: + return makeTempVariableName(0 /* Auto */, !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), isPrivateIdentifier(name), prefix, suffix); + case 2 /* Loop */: + Debug.assertNode(name, isIdentifier); + return makeTempVariableName( + 268435456 /* _i */, + !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), + /*privateName*/ + false, + prefix, + suffix + ); + case 3 /* Unique */: + return makeUniqueName( + idText(name), + autoGenerate.flags & 32 /* FileLevel */ ? isFileLevelUniqueNameInCurrentFile : isUniqueName, + !!(autoGenerate.flags & 16 /* Optimistic */), + !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), + isPrivateIdentifier(name), + prefix, + suffix + ); + } + return Debug.fail(`Unsupported GeneratedIdentifierKind: ${Debug.formatEnum( + autoGenerate.flags & 7 /* KindMask */, + GeneratedIdentifierFlags, + /*isFlags*/ + true + )}.`); + } + function pipelineEmitWithComments(hint, node) { + const pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + const savedContainerPos = containerPos; + const savedContainerEnd = containerEnd; + const savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + const emitFlags = getEmitFlags(node); + const commentRange = getCommentRange(node); + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 4096 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + const emitFlags = getEmitFlags(node); + const commentRange = getCommentRange(node); + if (emitFlags & 4096 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + const typeNode = getTypeNode(node); + if (typeNode) { + emitTrailingCommentsOfNode(node, emitFlags, typeNode.pos, typeNode.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + } + function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { + enterComment(); + hasWrittenComment = false; + const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */) !== 0 || node.kind === 12 /* JsxText */; + const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0 || node.kind === 12 /* JsxText */; + if ((pos > 0 || end > 0) && pos !== end) { + if (!skipLeadingComments) { + emitLeadingComments( + pos, + /*isEmittedNode*/ + node.kind !== 353 /* NotEmittedStatement */ + ); + } + if (!skipLeadingComments || pos >= 0 && (emitFlags & 1024 /* NoLeadingComments */) !== 0) { + containerPos = pos; + } + if (!skipTrailingComments || end >= 0 && (emitFlags & 2048 /* NoTrailingComments */) !== 0) { + containerEnd = end; + if (node.kind === 261 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + forEach(getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + } + function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + enterComment(); + const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0 || node.kind === 12 /* JsxText */; + forEach(getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + if (!skipTrailingComments && node.kind !== 353 /* NotEmittedStatement */) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + const text = formatSynthesizedComment(comment); + const lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? computeLineStarts(text) : void 0; + writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ ? `/*${comment.text}*/` : `//${comment.text}`; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + const { pos, end } = detachedRange; + const emitFlags = getEmitFlags(node); + const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */) !== 0; + const skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 4096 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments( + detachedRange.end, + /*isEmittedNode*/ + true + ); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function originalNodesHaveSameParent(nodeA, nodeB) { + nodeA = getOriginalNode(nodeA); + return nodeA.parent && nodeA.parent === getOriginalNode(nodeB).parent; + } + function siblingNodePositionsAreComparable(previousNode, nextNode) { + if (nextNode.pos < previousNode.end) { + return false; + } + previousNode = getOriginalNode(previousNode); + nextNode = getOriginalNode(nextNode); + const parent = previousNode.parent; + if (!parent || parent !== nextNode.parent) { + return false; + } + const parentNodeArray = getContainingNodeArray(previousNode); + const prevNodeIndex = parentNodeArray == null ? void 0 : parentNodeArray.indexOf(previousNode); + return prevNodeIndex !== void 0 && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1; + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + if (pos === 0 && (currentSourceFile == null ? void 0 : currentSourceFile.isDeclarationFile)) { + forEachLeadingCommentToEmit(pos, emitNonTripleSlashLeadingComment); + } else { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + } else if (pos === 0) { + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function emitNonTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return isJSDocLikeText(text, pos) || isPinnedComment(text, pos); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) return; + if (!hasWrittenComment) { + emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + emitPos(commentPos); + writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments( + pos, + /*isEmittedNode*/ + true + ); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) return; + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace, forceNoNewline) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : forceNoNewline ? emitTrailingCommentOfPositionNoNewline : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPositionNoNewline(commentPos, commentEnd, kind) { + if (!currentSourceFile) return; + emitPos(commentPos); + writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!currentSourceFile) return; + emitPos(commentPos); + writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } else { + forEachLeadingCommentRange( + currentSourceFile.text, + pos, + cb, + /*state*/ + pos + ); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + if (currentSourceFile && (containerEnd === -1 || end !== containerEnd && end !== declarationListContainerEnd)) { + forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== void 0 && last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + if (!currentSourceFile) return; + const pos = last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } else { + detachedCommentsInfo = void 0; + } + forEachLeadingCommentRange( + currentSourceFile.text, + pos, + cb, + /*state*/ + pos + ); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + const currentDetachedCommentInfo = currentSourceFile && emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer2, commentPos, commentEnd, newLine2) { + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) return; + emitPos(commentPos); + writeCommentRange(text, lineMap, writer2, commentPos, commentEnd, newLine2); + emitPos(commentEnd); + } + function isTripleSlashComment(commentPos, commentEnd) { + return !!currentSourceFile && isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + function pipelineEmitWithSourceMaps(hint, node) { + const pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + const emitFlags = getEmitFlags(node); + const sourceMapRange = getSourceMapRange(node); + const source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 353 /* NotEmittedStatement */ && (emitFlags & 32 /* NoLeadingSourceMap */) === 0 && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + } + if (emitFlags & 128 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + } + } + function emitSourceMapsAfterNode(node) { + const emitFlags = getEmitFlags(node); + const sourceMapRange = getSourceMapRange(node); + if (emitFlags & 128 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; + } + if (node.kind !== 353 /* NotEmittedStatement */ && (emitFlags & 64 /* NoTrailingSourceMap */) === 0 && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); + } + } + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : skipTrivia(source.text, pos); + } + function emitPos(pos) { + if (sourceMapsDisabled || positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + const { line: sourceLine, character: sourceCharacter } = getLineAndCharacterOfPosition(sourceMapSource, pos); + sourceMapGenerator.addMapping( + writer.getLine(), + writer.getColumn(), + sourceMapSourceIndex, + sourceLine, + sourceCharacter, + /*nameIndex*/ + void 0 + ); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + const savedSourceMapSource = sourceMapSource; + const savedSourceMapSourceIndex = sourceMapSourceIndex; + setSourceMapSource(source); + emitPos(pos); + resetSourceMapSource(savedSourceMapSource, savedSourceMapSourceIndex); + } else { + emitPos(pos); + } + } + function emitTokenWithSourceMap(node, token, writer2, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && isInJsonFile(node)) { + return emitCallback(token, writer2, tokenPos); + } + const emitNode = node && node.emitNode; + const emitFlags = emitNode && emitNode.flags || 0 /* None */; + const range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + const source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 256 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer2, tokenPos); + if (range) tokenPos = range.end; + if ((emitFlags & 512 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (source === mostRecentlyAddedSourceMapSource) { + sourceMapSourceIndex = mostRecentlyAddedSourceMapSourceIndex; + return; + } + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + mostRecentlyAddedSourceMapSource = source; + mostRecentlyAddedSourceMapSourceIndex = sourceMapSourceIndex; + } + function resetSourceMapSource(source, sourceIndex) { + sourceMapSource = source; + sourceMapSourceIndex = sourceIndex; + } + function isJsonSourceMapSource(sourceFile) { + return fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } +} +function createBracketsMap() { + const brackets2 = []; + brackets2[1024 /* Braces */] = ["{", "}"]; + brackets2[2048 /* Parenthesis */] = ["(", ")"]; + brackets2[4096 /* AngleBrackets */] = ["<", ">"]; + brackets2[8192 /* SquareBrackets */] = ["[", "]"]; + return brackets2; +} +function getOpeningBracket(format) { + return brackets[format & 15360 /* BracketsMask */][0]; +} +function getClosingBracket(format) { + return brackets[format & 15360 /* BracketsMask */][1]; +} +function emitListItemNoParenthesizer(node, emit, _parenthesizerRule, _index) { + emit(node); +} +function emitListItemWithParenthesizerRuleSelector(node, emit, parenthesizerRuleSelector, index) { + emit(node, parenthesizerRuleSelector.select(index)); +} +function emitListItemWithParenthesizerRule(node, emit, parenthesizerRule, _index) { + emit(node, parenthesizerRule); +} +function getEmitListItem(emit, parenthesizerRule) { + return emit.length === 1 ? emitListItemNoParenthesizer : typeof parenthesizerRule === "object" ? emitListItemWithParenthesizerRuleSelector : emitListItemWithParenthesizerRule; +} + +// src/compiler/watchUtilities.ts +function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2) { + if (!host.getDirectories || !host.readDirectory) { + return void 0; + } + const cachedReadDirectoryResult = /* @__PURE__ */ new Map(); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + fileExists, + readFile: (path, encoding) => host.readFile(path, encoding), + directoryExists: host.directoryExists && directoryExists, + getDirectories, + readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile2, + addOrDeleteFileOrDirectory, + addOrDeleteFile, + clearCache, + realpath: host.realpath && realpath + }; + function toPath3(fileName) { + return toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(ensureTrailingDirectorySeparator(rootDirPath)); + } + function getCachedFileSystemEntriesForBaseDir(path) { + const entries = getCachedFileSystemEntries(getDirectoryPath(path)); + if (!entries) { + return entries; + } + if (!entries.sortedAndCanonicalizedFiles) { + entries.sortedAndCanonicalizedFiles = entries.files.map(getCanonicalFileName).sort(); + entries.sortedAndCanonicalizedDirectories = entries.directories.map(getCanonicalFileName).sort(); + } + return entries; + } + function getBaseNameOfFileName(fileName) { + return getBaseFileName(normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var _a; + if (!host.realpath || ensureTrailingDirectorySeparator(toPath3(host.realpath(rootDir))) === rootDirPath) { + const resultFromHost = { + files: map(host.readDirectory( + rootDir, + /*extensions*/ + void 0, + /*exclude*/ + void 0, + /*include*/ + ["*.*"] + ), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + if ((_a = host.directoryExists) == null ? void 0 : _a.call(host, rootDir)) { + cachedReadDirectoryResult.set(rootDirPath, false); + return false; + } + return void 0; + } + function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ensureTrailingDirectorySeparator(rootDirPath); + const cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } catch { + Debug.assert(!cachedReadDirectoryResult.has(ensureTrailingDirectorySeparator(rootDirPath))); + return void 0; + } + } + function hasEntry(entries, name) { + const index = binarySearch(entries, name, identity, compareStringsCaseSensitive); + return index >= 0; + } + function writeFile2(fileName, data, writeByteOrderMark) { + const path = toPath3(fileName); + const result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry( + result, + getBaseNameOfFileName(fileName), + /*fileExists*/ + true + ); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + const path = toPath3(fileName); + const result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.sortedAndCanonicalizedFiles, getCanonicalFileName(getBaseNameOfFileName(fileName))) || host.fileExists(fileName); + } + function directoryExists(dirPath) { + const path = toPath3(dirPath); + return cachedReadDirectoryResult.has(ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + const path = toPath3(dirPath); + const result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + const baseName = getBaseNameOfFileName(dirPath); + const canonicalizedBaseName = getCanonicalFileName(baseName); + const canonicalizedDirectories = result.sortedAndCanonicalizedDirectories; + if (insertSorted(canonicalizedDirectories, canonicalizedBaseName, compareStringsCaseSensitive)) { + result.directories.push(baseName); + } + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + const rootDirPath = toPath3(rootDir); + const result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + const rootDirPath = toPath3(rootDir); + const rootResult = tryReadDirectory(rootDir, rootDirPath); + let rootSymLinkResult; + if (rootResult !== void 0) { + return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames2, currentDirectory, depth, getFileSystemEntries, realpath); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + const path = toPath3(dir); + if (path === rootDirPath) { + return rootResult || getFileSystemEntriesFromHost(dir, path); + } + const result = tryReadDirectory(dir, path); + return result !== void 0 ? result || getFileSystemEntriesFromHost(dir, path) : emptyFileSystemEntries; + } + function getFileSystemEntriesFromHost(dir, path) { + if (rootSymLinkResult && path === rootDirPath) return rootSymLinkResult; + const result = { + files: map(host.readDirectory( + dir, + /*extensions*/ + void 0, + /*exclude*/ + void 0, + /*include*/ + ["*.*"] + ), getBaseNameOfFileName) || emptyArray, + directories: host.getDirectories(dir) || emptyArray + }; + if (path === rootDirPath) rootSymLinkResult = result; + return result; + } + } + function realpath(s) { + return host.realpath ? host.realpath(s) : s; + } + function clearFirstAncestorEntry(fileOrDirectoryPath) { + forEachAncestorDirectory( + getDirectoryPath(fileOrDirectoryPath), + (ancestor) => cachedReadDirectoryResult.delete(ensureTrailingDirectorySeparator(ancestor)) ? true : void 0 + ); + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + const existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult !== void 0) { + clearCache(); + return void 0; + } + const parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + clearFirstAncestorEntry(fileOrDirectoryPath); + return void 0; + } + if (!host.directoryExists) { + clearCache(); + return void 0; + } + const baseName = getBaseNameOfFileName(fileOrDirectory); + const fsQueryResult = { + fileExists: host.fileExists(fileOrDirectory), + directoryExists: host.directoryExists(fileOrDirectory) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.sortedAndCanonicalizedDirectories, getCanonicalFileName(baseName))) { + clearCache(); + } else { + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === 1 /* Changed */) { + return; + } + const parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === 0 /* Created */); + } else { + clearFirstAncestorEntry(filePath); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists2) { + const canonicalizedFiles = parentResult.sortedAndCanonicalizedFiles; + const canonicalizedBaseName = getCanonicalFileName(baseName); + if (fileExists2) { + if (insertSorted(canonicalizedFiles, canonicalizedBaseName, compareStringsCaseSensitive)) { + parentResult.files.push(baseName); + } + } else { + const sortedIndex = binarySearch(canonicalizedFiles, canonicalizedBaseName, identity, compareStringsCaseSensitive); + if (sortedIndex >= 0) { + canonicalizedFiles.splice(sortedIndex, 1); + const unsortedIndex = parentResult.files.findIndex((entry) => getCanonicalFileName(entry) === canonicalizedBaseName); + parentResult.files.splice(unsortedIndex, 1); + } + } + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } +} +function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath3) { + var _a; + const extendedConfigs = arrayToMap(((_a = options == null ? void 0 : options.configFile) == null ? void 0 : _a.extendedSourceFiles) || emptyArray, toPath3); + extendedConfigFilesMap.forEach((watcher, extendedConfigFilePath) => { + if (!extendedConfigs.has(extendedConfigFilePath)) { + watcher.projects.delete(projectPath); + watcher.close(); + } + }); + extendedConfigs.forEach((extendedConfigFileName, extendedConfigFilePath) => { + const existing = extendedConfigFilesMap.get(extendedConfigFilePath); + if (existing) { + existing.projects.add(projectPath); + } else { + extendedConfigFilesMap.set(extendedConfigFilePath, { + projects: /* @__PURE__ */ new Set([projectPath]), + watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), + close: () => { + const existing2 = extendedConfigFilesMap.get(extendedConfigFilePath); + if (!existing2 || existing2.projects.size !== 0) return; + existing2.watcher.close(); + extendedConfigFilesMap.delete(extendedConfigFilePath); + } + }); + } + }); +} +function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { + extendedConfigFilesMap.forEach((watcher) => { + if (watcher.projects.delete(projectPath)) watcher.close(); + }); +} +function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3) { + if (!extendedConfigCache.delete(extendedConfigFilePath)) return; + extendedConfigCache.forEach(({ extendedResult }, key) => { + var _a; + if ((_a = extendedResult.extendedSourceFiles) == null ? void 0 : _a.some((extendedFile) => toPath3(extendedFile) === extendedConfigFilePath)) { + cleanExtendedConfigCache(extendedConfigCache, key, toPath3); + } + }); +} +function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + mutateMap( + missingFileWatches, + program.getMissingFilePaths(), + { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: closeFileWatcher + } + ); +} +function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + if (wildcardDirectories) { + mutateMap( + existingWatchedForWildcards, + new Map(Object.entries(wildcardDirectories)), + { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + } + ); + } else { + clearMap(existingWatchedForWildcards, closeFileWatcherOf); + } + function createWildcardDirectoryWatcher(directory, flags) { + return { + watcher: watchDirectory(directory, flags), + flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } +} +function isIgnoredFileFromWildCardWatching({ + watchedDirPath, + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + options, + program, + extraFileExtensions, + currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + writeLog, + toPath: toPath3, + getScriptKind +}) { + const newPath = removeIgnoredPath(fileOrDirectoryPath); + if (!newPath) { + writeLog(`Project: ${configFileName} Detected ignored path: ${fileOrDirectory}`); + return true; + } + fileOrDirectoryPath = newPath; + if (fileOrDirectoryPath === watchedDirPath) return false; + if (hasExtension(fileOrDirectoryPath) && !(isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions) || isSupportedScriptKind())) { + writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return true; + } + if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames2, currentDirectory)) { + writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); + return true; + } + if (!program) return false; + if (options.outFile || options.outDir) return false; + if (isDeclarationFileName(fileOrDirectoryPath)) { + if (options.declarationDir) return false; + } else if (!fileExtensionIsOneOf(fileOrDirectoryPath, supportedJSExtensionsFlat)) { + return false; + } + const filePathWithoutExtension = removeFileExtension(fileOrDirectoryPath); + const realProgram = isArray(program) ? void 0 : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + const builderProgram = !realProgram && !isArray(program) ? program : void 0; + if (hasSourceFile(filePathWithoutExtension + ".ts" /* Ts */) || hasSourceFile(filePathWithoutExtension + ".tsx" /* Tsx */)) { + writeLog(`Project: ${configFileName} Detected output file: ${fileOrDirectory}`); + return true; + } + return false; + function hasSourceFile(file) { + return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? builderProgram.state.fileInfos.has(file) : !!find(program, (rootFile) => toPath3(rootFile) === file); + } + function isSupportedScriptKind() { + if (!getScriptKind) return false; + const scriptKind = getScriptKind(fileOrDirectory); + switch (scriptKind) { + case 3 /* TS */: + case 4 /* TSX */: + case 7 /* Deferred */: + case 5 /* External */: + return true; + case 1 /* JS */: + case 2 /* JSX */: + return getAllowJSCompilerOption(options); + case 6 /* JSON */: + return getResolveJsonModule(options); + case 0 /* Unknown */: + return false; + } + } +} +function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); +} +function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo) { + setSysLog(watchLogLevel === 2 /* Verbose */ ? log : noop); + const plainInvokeFactory = { + watchFile: (file, callback, pollingInterval, options) => host.watchFile(file, callback, pollingInterval, options), + watchDirectory: (directory, callback, flags, options) => host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options) + }; + const triggerInvokingFactory = watchLogLevel !== 0 /* None */ ? { + watchFile: createTriggerLoggingAddWatch("watchFile"), + watchDirectory: createTriggerLoggingAddWatch("watchDirectory") + } : void 0; + const factory2 = watchLogLevel === 2 /* Verbose */ ? { + watchFile: createFileWatcherWithLogging, + watchDirectory: createDirectoryWatcherWithLogging + } : triggerInvokingFactory || plainInvokeFactory; + const excludeWatcherFactory = watchLogLevel === 2 /* Verbose */ ? createExcludeWatcherWithLogging : returnNoopFileWatcher; + return { + watchFile: createExcludeHandlingAddWatch("watchFile"), + watchDirectory: createExcludeHandlingAddWatch("watchDirectory") + }; + function createExcludeHandlingAddWatch(key) { + return (file, cb, flags, options, detailInfo1, detailInfo2) => { + var _a; + return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( + /*thisArgs*/ + void 0, + file, + cb, + flags, + options, + detailInfo1, + detailInfo2 + ) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); + }; + } + function useCaseSensitiveFileNames2() { + return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); + } + function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { + log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); + return { + close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`) + }; + } + function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { + log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); + const watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2); + return { + close: () => { + log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); + watcher.close(); + } + }; + } + function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { + const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; + log(watchInfo); + const start = timestamp(); + const watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2); + const elapsed = timestamp() - start; + log(`Elapsed:: ${elapsed}ms ${watchInfo}`); + return { + close: () => { + const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; + log(watchInfo2); + const start2 = timestamp(); + watcher.close(); + const elapsed2 = timestamp() - start2; + log(`Elapsed:: ${elapsed2}ms ${watchInfo2}`); + } + }; + } + function createTriggerLoggingAddWatch(key) { + return (file, cb, flags, options, detailInfo1, detailInfo2) => plainInvokeFactory[key].call( + /*thisArgs*/ + void 0, + file, + (...args) => { + const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; + log(triggerredInfo); + const start = timestamp(); + cb.call( + /*thisArg*/ + void 0, + ...args + ); + const elapsed = timestamp() - start; + log(`Elapsed:: ${elapsed}ms ${triggerredInfo}`); + }, + flags, + options, + detailInfo1, + detailInfo2 + ); + } + function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2) { + return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo2 ? getDetailWatchInfo2(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; + } +} +function getFallbackOptions(options) { + const fallbackPolling = options == null ? void 0 : options.fallbackPolling; + return { + watchFile: fallbackPolling !== void 0 ? fallbackPolling : 1 /* PriorityPollingInterval */ + }; +} +function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); +} + +// src/compiler/program.ts +function findConfigFile(searchPath, fileExists, configName = "tsconfig.json") { + return forEachAncestorDirectory(searchPath, (ancestor) => { + const fileName = combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : void 0; + }); +} +function resolveTripleslashReference(moduleName, containingFile) { + const basePath = getDirectoryPath(containingFile); + const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName); + return normalizePath(referencedFileName); +} +function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { + let commonPathComponents; + const failed2 = forEach(fileNames, (sourceFile) => { + const sourcePathComponents = getNormalizedPathComponents(sourceFile, currentDirectory); + sourcePathComponents.pop(); + if (!commonPathComponents) { + commonPathComponents = sourcePathComponents; + return; + } + const n = Math.min(commonPathComponents.length, sourcePathComponents.length); + for (let i = 0; i < n; i++) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { + if (i === 0) { + return true; + } + commonPathComponents.length = i; + break; + } + } + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + if (failed2) { + return ""; + } + if (!commonPathComponents) { + return currentDirectory; + } + return getPathFromPathComponents(commonPathComponents); +} +function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); +} +function createGetSourceFile(readFile, setParentNodes) { + return (fileName, languageVersionOrOptions, onError) => { + let text; + try { + mark("beforeIORead"); + text = readFile(fileName); + mark("afterIORead"); + measure("I/O Read", "beforeIORead", "afterIORead"); + } catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== void 0 ? createSourceFile(fileName, text, languageVersionOrOptions, setParentNodes) : void 0; + }; +} +function createWriteFileMeasuringIO(actualWriteFile, createDirectory, directoryExists) { + return (fileName, data, writeByteOrderMark, onError) => { + try { + mark("beforeIOWrite"); + writeFileEnsuringDirectories( + fileName, + data, + writeByteOrderMark, + actualWriteFile, + createDirectory, + directoryExists + ); + mark("afterIOWrite"); + measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } catch (e) { + if (onError) { + onError(e.message); + } + } + }; +} +function createCompilerHostWorker(options, setParentNodes, system = sys) { + const existingDirectories = /* @__PURE__ */ new Map(); + const getCanonicalFileName = createGetCanonicalFileName(system.useCaseSensitiveFileNames); + function directoryExists(directoryPath) { + if (existingDirectories.has(directoryPath)) { + return true; + } + if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) { + existingDirectories.set(directoryPath, true); + return true; + } + return false; + } + function getDefaultLibLocation() { + return getDirectoryPath(normalizePath(system.getExecutingFilePath())); + } + const newLine = getNewLineCharacter(options); + const realpath = system.realpath && ((path) => system.realpath(path)); + const compilerHost = { + getSourceFile: createGetSourceFile((fileName) => compilerHost.readFile(fileName), setParentNodes), + getDefaultLibLocation, + getDefaultLibFileName: (options2) => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options2)), + writeFile: createWriteFileMeasuringIO( + (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark), + (path) => (compilerHost.createDirectory || system.createDirectory)(path), + (path) => directoryExists(path) + ), + getCurrentDirectory: memoize(() => system.getCurrentDirectory()), + useCaseSensitiveFileNames: () => system.useCaseSensitiveFileNames, + getCanonicalFileName, + getNewLine: () => newLine, + fileExists: (fileName) => system.fileExists(fileName), + readFile: (fileName) => system.readFile(fileName), + trace: (s) => system.write(s + newLine), + directoryExists: (directoryName) => system.directoryExists(directoryName), + getEnvironmentVariable: (name) => system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : "", + getDirectories: (path) => system.getDirectories(path), + realpath, + readDirectory: (path, extensions, include, exclude, depth) => system.readDirectory(path, extensions, include, exclude, depth), + createDirectory: (d) => system.createDirectory(d), + createHash: maybeBind(system, system.createHash) + }; + return compilerHost; +} +function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { + const originalReadFile = host.readFile; + const originalFileExists = host.fileExists; + const originalDirectoryExists = host.directoryExists; + const originalCreateDirectory = host.createDirectory; + const originalWriteFile = host.writeFile; + const readFileCache = /* @__PURE__ */ new Map(); + const fileExistsCache = /* @__PURE__ */ new Map(); + const directoryExistsCache = /* @__PURE__ */ new Map(); + const sourceFileCache = /* @__PURE__ */ new Map(); + const readFileWithCache = (fileName) => { + const key = toPath3(fileName); + const value = readFileCache.get(key); + if (value !== void 0) return value !== false ? value : void 0; + return setReadFileCache(key, fileName); + }; + const setReadFileCache = (key, fileName) => { + const newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue !== void 0 ? newValue : false); + return newValue; + }; + host.readFile = (fileName) => { + const key = toPath3(fileName); + const value = readFileCache.get(key); + if (value !== void 0) return value !== false ? value : void 0; + if (!fileExtensionIs(fileName, ".json" /* Json */) && !isBuildInfoFile(fileName)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + const getSourceFileWithCache = getSourceFile ? (fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => { + const key = toPath3(fileName); + const impliedNodeFormat = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions.impliedNodeFormat : void 0; + const forImpliedNodeFormat = sourceFileCache.get(impliedNodeFormat); + const value = forImpliedNodeFormat == null ? void 0 : forImpliedNodeFormat.get(key); + if (value) return value; + const sourceFile = getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile); + if (sourceFile && (isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(impliedNodeFormat, (forImpliedNodeFormat || /* @__PURE__ */ new Map()).set(key, sourceFile)); + } + return sourceFile; + } : void 0; + host.fileExists = (fileName) => { + const key = toPath3(fileName); + const value = fileExistsCache.get(key); + if (value !== void 0) return value; + const newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + if (originalWriteFile) { + host.writeFile = (fileName, data, ...rest) => { + const key = toPath3(fileName); + fileExistsCache.delete(key); + const value = readFileCache.get(key); + if (value !== void 0 && value !== data) { + readFileCache.delete(key); + sourceFileCache.forEach((map2) => map2.delete(key)); + } else if (getSourceFileWithCache) { + sourceFileCache.forEach((map2) => { + const sourceFile = map2.get(key); + if (sourceFile && sourceFile.text !== data) { + map2.delete(key); + } + }); + } + originalWriteFile.call(host, fileName, data, ...rest); + }; + } + if (originalDirectoryExists) { + host.directoryExists = (directory) => { + const key = toPath3(directory); + const value = directoryExistsCache.get(key); + if (value !== void 0) return value; + const newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + if (originalCreateDirectory) { + host.createDirectory = (directory) => { + const key = toPath3(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + } + return { + originalReadFile, + originalFileExists, + originalDirectoryExists, + originalCreateDirectory, + originalWriteFile, + getSourceFileWithCache, + readFileWithCache + }; +} +function formatDiagnostic(diagnostic, host) { + const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}${host.getNewLine()}`; + if (diagnostic.file) { + const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + const fileName = diagnostic.file.fileName; + const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), (fileName2) => host.getCanonicalFileName(fileName2)); + return `${relativeFileName}(${line + 1},${character + 1}): ` + errorMessage; + } + return errorMessage; +} +var gutterStyleSequence = "\x1B[7m"; +var gutterSeparator = " "; +var resetEscapeSequence = "\x1B[0m"; +var ellipsis = "..."; +var halfIndent = " "; +var indent = " "; +function getCategoryFormat(category) { + switch (category) { + case 1 /* Error */: + return "\x1B[91m" /* Red */; + case 0 /* Warning */: + return "\x1B[93m" /* Yellow */; + case 2 /* Suggestion */: + return Debug.fail("Should never get an Info diagnostic on the command line."); + case 3 /* Message */: + return "\x1B[94m" /* Blue */; + } +} +function formatColorAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; +} +function formatCodeSpan(file, start, length2, indent2, squiggleColor, host) { + const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); + const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length2); + const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; + const hasMoreThanFiveLines = lastLine - firstLine >= 4; + let gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + let context = ""; + for (let i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + context += indent2 + formatColorAndReset(ellipsis.padStart(gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + const lineStart = getPositionOfLineAndCharacter(file, i, 0); + const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + let lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.trimEnd(); + lineContent = lineContent.replace(/\t/g, " "); + context += indent2 + formatColorAndReset((i + 1 + "").padStart(gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + context += indent2 + formatColorAndReset("".padStart(gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + const lastCharForLine = i === lastLine ? lastLineChar : void 0; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } else { + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; +} +function formatLocation(file, start, host, color = formatColorAndReset) { + const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); + const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), (fileName) => host.getCanonicalFileName(fileName)) : file.fileName; + let output = ""; + output += color(relativeFileName, "\x1B[96m" /* Cyan */); + output += ":"; + output += color(`${firstLine + 1}`, "\x1B[93m" /* Yellow */); + output += ":"; + output += color(`${firstLineChar + 1}`, "\x1B[93m" /* Yellow */); + return output; +} +function formatDiagnosticsWithColorAndContext(diagnostics, host) { + let output = ""; + for (const diagnostic of diagnostics) { + if (diagnostic.file) { + const { file, start } = diagnostic; + output += formatLocation(file, start, host); + output += " - "; + } + output += formatColorAndReset(diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); + output += formatColorAndReset(` TS${diagnostic.code}: `, "\x1B[90m" /* Grey */); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file && diagnostic.code !== Diagnostics.File_appears_to_be_binary.code) { + output += host.getNewLine(); + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); + } + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (const { file, start, length: length2, messageText } of diagnostic.relatedInformation) { + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); + output += formatCodeSpan(file, start, length2, indent, "\x1B[96m" /* Cyan */, host); + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } + output += host.getNewLine(); + } + return output; +} +function flattenDiagnosticMessageText(diag2, newLine, indent2 = 0) { + if (isString(diag2)) { + return diag2; + } else if (diag2 === void 0) { + return ""; + } + let result = ""; + if (indent2) { + result += newLine; + for (let i = 0; i < indent2; i++) { + result += " "; + } + } + result += diag2.messageText; + indent2++; + if (diag2.next) { + for (const kid of diag2.next) { + result += flattenDiagnosticMessageText(kid, newLine, indent2); + } + } + return result; +} +function getModeForFileReference(ref, containingFileMode) { + return (isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode; +} +function isExclusivelyTypeOnlyImportOrExport(decl) { + var _a; + if (isExportDeclaration(decl)) { + return decl.isTypeOnly; + } + if ((_a = decl.importClause) == null ? void 0 : _a.isTypeOnly) { + return true; + } + return false; +} +function getModeForUsageLocation(file, usage, compilerOptions) { + return getModeForUsageLocationWorker(file, usage, compilerOptions); +} +function getModeForUsageLocationWorker(file, usage, compilerOptions) { + if (isImportDeclaration(usage.parent) || isExportDeclaration(usage.parent) || isJSDocImportTag(usage.parent)) { + const isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent); + if (isTypeOnly) { + const override = getResolutionModeOverride(usage.parent.attributes); + if (override) { + return override; + } + } + } + if (usage.parent.parent && isImportTypeNode(usage.parent.parent)) { + const override = getResolutionModeOverride(usage.parent.parent.attributes); + if (override) { + return override; + } + } + if (compilerOptions && importSyntaxAffectsModuleResolution(compilerOptions)) { + return getEmitSyntaxForUsageLocationWorker(file, usage, compilerOptions); + } +} +function getEmitSyntaxForUsageLocationWorker(file, usage, compilerOptions) { + var _a; + if (!compilerOptions) { + return void 0; + } + const exprParentParent = (_a = walkUpParenthesizedExpressions(usage.parent)) == null ? void 0 : _a.parent; + if (exprParentParent && isImportEqualsDeclaration(exprParentParent) || isRequireCall( + usage.parent, + /*requireStringLiteralLikeArgument*/ + false + )) { + return 1 /* CommonJS */; + } + if (isImportCall(walkUpParenthesizedExpressions(usage.parent))) { + return shouldTransformImportCallWorker(file, compilerOptions) ? 1 /* CommonJS */ : 99 /* ESNext */; + } + const fileEmitMode = getEmitModuleFormatOfFileWorker(file, compilerOptions); + return fileEmitMode === 1 /* CommonJS */ ? 1 /* CommonJS */ : emitModuleKindIsNonNodeESM(fileEmitMode) || fileEmitMode === 200 /* Preserve */ ? 99 /* ESNext */ : void 0; +} +function getResolutionModeOverride(node, grammarErrorOnNode) { + if (!node) return void 0; + if (length(node.elements) !== 1) { + grammarErrorOnNode == null ? void 0 : grammarErrorOnNode( + node, + node.token === 118 /* WithKeyword */ ? Diagnostics.Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require : Diagnostics.Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require + ); + return void 0; + } + const elem = node.elements[0]; + if (!isStringLiteralLike(elem.name)) return void 0; + if (elem.name.text !== "resolution-mode") { + grammarErrorOnNode == null ? void 0 : grammarErrorOnNode( + elem.name, + node.token === 118 /* WithKeyword */ ? Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_attributes : Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_assertions + ); + return void 0; + } + if (!isStringLiteralLike(elem.value)) return void 0; + if (elem.value.text !== "import" && elem.value.text !== "require") { + grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(elem.value, Diagnostics.resolution_mode_should_be_either_require_or_import); + return void 0; + } + return elem.value.text === "import" ? 99 /* ESNext */ : 1 /* CommonJS */; +} +var emptyResolution = { + resolvedModule: void 0, + resolvedTypeReferenceDirective: void 0 +}; +function getModuleResolutionName(literal) { + return literal.text; +} +var moduleResolutionNameAndModeGetter = { + getName: getModuleResolutionName, + getMode: (entry, file, compilerOptions) => getModeForUsageLocation(file, entry, compilerOptions) +}; +function createModuleResolutionLoader(containingFile, redirectedReference, options, host, cache) { + return { + nameAndMode: moduleResolutionNameAndModeGetter, + resolve: (moduleName, resolutionMode) => resolveModuleName( + moduleName, + containingFile, + options, + host, + cache, + redirectedReference, + resolutionMode + ) + }; +} +function getTypeReferenceResolutionName(entry) { + return !isString(entry) ? entry.fileName : entry; +} +var typeReferenceResolutionNameAndModeGetter = { + getName: getTypeReferenceResolutionName, + getMode: (entry, file, compilerOptions) => getModeForFileReference(entry, file && getDefaultResolutionModeForFileWorker(file, compilerOptions)) +}; +function createTypeReferenceResolutionLoader(containingFile, redirectedReference, options, host, cache) { + return { + nameAndMode: typeReferenceResolutionNameAndModeGetter, + resolve: (typeRef, resoluionMode) => resolveTypeReferenceDirective( + typeRef, + containingFile, + options, + host, + redirectedReference, + cache, + resoluionMode + ) + }; +} +function loadWithModeAwareCache(entries, containingFile, redirectedReference, options, containingSourceFile, host, resolutionCache, createLoader) { + if (entries.length === 0) return emptyArray; + const resolutions = []; + const cache = /* @__PURE__ */ new Map(); + const loader = createLoader(containingFile, redirectedReference, options, host, resolutionCache); + for (const entry of entries) { + const name = loader.nameAndMode.getName(entry); + const mode = loader.nameAndMode.getMode(entry, containingSourceFile, (redirectedReference == null ? void 0 : redirectedReference.commandLine.options) || options); + const key = createModeAwareCacheKey(name, mode); + let result = cache.get(key); + if (!result) { + cache.set(key, result = loader.resolve(name, mode)); + } + resolutions.push(result); + } + return resolutions; +} +var inferredTypesContainingFile = "__inferred type names__.ts"; +function getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName) { + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; + return combinePaths(containingDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); +} +function getLibraryNameFromLibFileName(libFileName) { + const components = libFileName.split("."); + let path = components[1]; + let i = 2; + while (components[i] && components[i] !== "d") { + path += (i === 2 ? "/" : "-") + components[i]; + i++; + } + return "@typescript/lib-" + path; +} +function isReferencedFile(reason) { + switch (reason == null ? void 0 : reason.kind) { + case 3 /* Import */: + case 4 /* ReferenceFile */: + case 5 /* TypeReferenceDirective */: + case 7 /* LibReferenceDirective */: + return true; + default: + return false; + } +} +function isReferenceFileLocation(location) { + return location.pos !== void 0; +} +function getReferencedFileLocation(program, ref) { + var _a, _b, _c, _d; + const file = Debug.checkDefined(program.getSourceFileByPath(ref.file)); + const { kind, index } = ref; + let pos, end, packageId; + switch (kind) { + case 3 /* Import */: + const importLiteral = getModuleNameStringLiteralAt(file, index); + packageId = (_b = (_a = program.getResolvedModuleFromModuleSpecifier(importLiteral, file)) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.packageId; + if (importLiteral.pos === -1) return { file, packageId, text: importLiteral.text }; + pos = skipTrivia(file.text, importLiteral.pos); + end = importLiteral.end; + break; + case 4 /* ReferenceFile */: + ({ pos, end } = file.referencedFiles[index]); + break; + case 5 /* TypeReferenceDirective */: + ({ pos, end } = file.typeReferenceDirectives[index]); + packageId = (_d = (_c = program.getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(file.typeReferenceDirectives[index], file)) == null ? void 0 : _c.resolvedTypeReferenceDirective) == null ? void 0 : _d.packageId; + break; + case 7 /* LibReferenceDirective */: + ({ pos, end } = file.libReferenceDirectives[index]); + break; + default: + return Debug.assertNever(kind); + } + return { file, pos, end, packageId }; +} +function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { + if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; + if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; + let seenResolvedRefs; + if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) return false; + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; + const missingPaths = program.getMissingFilePaths(); + if (missingPaths && forEachEntry(missingPaths, fileExists)) return false; + const currentOptions = program.getCompilerOptions(); + if (!compareDataObjects(currentOptions, newOptions)) return false; + if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) return false; + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; + return true; + function sourceFileNotUptoDate(sourceFile) { + return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolutions(sourceFile.path); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + return projectReferenceIsEqualTo(oldRef, newRef) && resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + } + function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { + if (oldResolvedRef) { + if (contains(seenResolvedRefs, oldResolvedRef)) return true; + const refPath2 = resolveProjectReferencePath(oldRef); + const newParsedCommandLine = getParsedCommandLine(refPath2); + if (!newParsedCommandLine) return false; + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) return false; + if (!arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + return !forEach( + oldResolvedRef.references, + (childResolvedRef, index) => !resolvedProjectReferenceUptoDate( + childResolvedRef, + oldResolvedRef.commandLine.projectReferences[index] + ) + ); + } + const refPath = resolveProjectReferencePath(oldRef); + return !getParsedCommandLine(refPath); + } +} +function getConfigFileParsingDiagnostics(configFileParseResult) { + return configFileParseResult.options.configFile ? [...configFileParseResult.options.configFile.parseDiagnostics, ...configFileParseResult.errors] : configFileParseResult.errors; +} +function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) { + const moduleResolution = getEmitModuleResolutionKind(options); + const shouldLookupFromPackageJson = 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */ || pathContainsNodeModules(fileName); + return fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".mjs" /* Mjs */]) ? 99 /* ESNext */ : fileExtensionIsOneOf(fileName, [".d.cts" /* Dcts */, ".cts" /* Cts */, ".cjs" /* Cjs */]) ? 1 /* CommonJS */ : shouldLookupFromPackageJson && fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */]) ? lookupFromPackageJson() : void 0; + function lookupFromPackageJson() { + const state = getTemporaryModuleResolutionState(packageJsonInfoCache, host, options); + const packageJsonLocations = []; + state.failedLookupLocations = packageJsonLocations; + state.affectingLocations = packageJsonLocations; + const packageJsonScope = getPackageScopeForPath(getDirectoryPath(fileName), state); + const impliedNodeFormat = (packageJsonScope == null ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? 99 /* ESNext */ : 1 /* CommonJS */; + return { impliedNodeFormat, packageJsonLocations, packageJsonScope }; + } +} +var plainJSErrors = /* @__PURE__ */ new Set([ + // binder errors + Diagnostics.Cannot_redeclare_block_scoped_variable_0.code, + Diagnostics.A_module_cannot_have_multiple_default_exports.code, + Diagnostics.Another_export_default_is_here.code, + Diagnostics.The_first_export_default_is_here.code, + Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module.code, + Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode.code, + Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here.code, + Diagnostics.constructor_is_a_reserved_word.code, + Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode.code, + Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode.code, + Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode.code, + Diagnostics.Invalid_use_of_0_in_strict_mode.code, + Diagnostics.A_label_is_not_allowed_here.code, + Diagnostics.with_statements_are_not_allowed_in_strict_mode.code, + // grammar errors + Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement.code, + Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement.code, + Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name.code, + Diagnostics.A_class_member_cannot_have_the_0_keyword.code, + Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name.code, + Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement.code, + Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, + Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, + Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement.code, + Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration.code, + Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context.code, + Diagnostics.A_destructuring_declaration_must_have_an_initializer.code, + Diagnostics.A_get_accessor_cannot_have_parameters.code, + Diagnostics.A_rest_element_cannot_contain_a_binding_pattern.code, + Diagnostics.A_rest_element_cannot_have_a_property_name.code, + Diagnostics.A_rest_element_cannot_have_an_initializer.code, + Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern.code, + Diagnostics.A_rest_parameter_cannot_have_an_initializer.code, + Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list.code, + Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma.code, + Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block.code, + Diagnostics.A_set_accessor_cannot_have_rest_parameter.code, + Diagnostics.A_set_accessor_must_have_exactly_one_parameter.code, + Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module.code, + Diagnostics.An_export_declaration_cannot_have_modifiers.code, + Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module.code, + Diagnostics.An_import_declaration_cannot_have_modifiers.code, + Diagnostics.An_object_member_cannot_be_declared_optional.code, + Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element.code, + Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable.code, + Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause.code, + Diagnostics.Catch_clause_variable_cannot_have_an_initializer.code, + Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator.code, + Diagnostics.Classes_can_only_extend_a_single_class.code, + Diagnostics.Classes_may_not_have_a_field_named_constructor.code, + Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code, + Diagnostics.Duplicate_label_0.code, + Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments.code, + Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block.code, + Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code, + Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code, + Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code, + Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names.code, + Diagnostics.Jump_target_cannot_cross_function_boundary.code, + Diagnostics.Line_terminator_not_permitted_before_arrow.code, + Diagnostics.Modifiers_cannot_appear_here.code, + Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement.code, + Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement.code, + Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code, + Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code, + Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier.code, + Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain.code, + Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async.code, + Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer.code, + Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer.code, + Diagnostics.Trailing_comma_not_allowed.code, + Diagnostics.Variable_declaration_list_cannot_be_empty.code, + Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses.code, + Diagnostics._0_expected.code, + Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2.code, + Diagnostics._0_list_cannot_be_empty.code, + Diagnostics._0_modifier_already_seen.code, + Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration.code, + Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element.code, + Diagnostics._0_modifier_cannot_appear_on_a_parameter.code, + Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code, + Diagnostics._0_modifier_cannot_be_used_here.code, + Diagnostics._0_modifier_must_precede_1_modifier.code, + Diagnostics._0_declarations_can_only_be_declared_inside_a_block.code, + Diagnostics._0_declarations_must_be_initialized.code, + Diagnostics.extends_clause_already_seen.code, + Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + Diagnostics.Class_constructor_may_not_be_a_generator.code, + Diagnostics.Class_constructor_may_not_be_an_accessor.code, + Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.Private_field_0_must_be_declared_in_an_enclosing_class.code, + // Type errors + Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value.code +]); +function shouldProgramCreateNewSourceFiles(program, newOptions) { + if (!program) return false; + return optionsHaveChanges(program.getCompilerOptions(), newOptions, sourceFileAffectingCompilerOptions); +} +function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics, typeScriptVersion2) { + return { + rootNames, + options, + host, + oldProgram, + configFileParsingDiagnostics, + typeScriptVersion: typeScriptVersion2 + }; +} +function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; + let _createProgramOptions = isArray(_rootNamesOrOptions) ? createCreateProgramOptions(_rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : _rootNamesOrOptions; + const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion: typeScriptVersion2, host: createProgramOptionsHost } = _createProgramOptions; + let { oldProgram } = _createProgramOptions; + _createProgramOptions = void 0; + _rootNamesOrOptions = void 0; + for (const option of commandLineOptionOfCustomType) { + if (hasProperty(options, option.name)) { + if (typeof options[option.name] === "string") { + throw new Error(`${option.name} is a string value; tsconfig JSON must be parsed with parseJsonSourceFileConfigFileContent or getParsedCommandLineOfConfigFile before passing to createProgram`); + } + } + } + const reportInvalidIgnoreDeprecations = memoize(() => createOptionValueDiagnostic("ignoreDeprecations", Diagnostics.Invalid_value_for_ignoreDeprecations)); + let processingDefaultLibFiles; + let processingOtherFiles; + let files; + let symlinks; + let typeChecker; + let classifiableNames; + let filesWithReferencesProcessed; + let cachedBindAndCheckDiagnosticsForFile; + let cachedDeclarationDiagnosticsForFile; + const programDiagnostics = createProgramDiagnostics(getCompilerOptionsObjectLiteralSyntax); + let automaticTypeDirectiveNames; + let automaticTypeDirectiveResolutions; + let resolvedLibReferences; + let resolvedLibProcessing; + let resolvedModules; + let resolvedModulesProcessing; + let resolvedTypeReferenceDirectiveNames; + let resolvedTypeReferenceDirectiveNamesProcessing; + let packageMap; + const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + let currentNodeModulesDepth = 0; + const modulesWithElidedImports = /* @__PURE__ */ new Map(); + const sourceFilesFoundSearchingNodeModules = /* @__PURE__ */ new Map(); + (_a = tracing) == null ? void 0 : _a.push( + tracing.Phase.Program, + "createProgram", + { configFilePath: options.configFilePath, rootDir: options.rootDir }, + /*separateBeginAndEnd*/ + true + ); + mark("beforeProgram"); + const host = createProgramOptionsHost || createCompilerHost(options); + const configParsingHost = parseConfigHostFromCompilerHostLike(host); + let skipDefaultLib = options.noLib; + const getDefaultLibraryFileName = memoize(() => host.getDefaultLibFileName(options)); + const defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : getDirectoryPath(getDefaultLibraryFileName()); + let skipVerifyCompilerOptions = false; + const currentDirectory = host.getCurrentDirectory(); + const supportedExtensions = getSupportedExtensions(options); + const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); + const hasEmitBlockingDiagnostics = /* @__PURE__ */ new Map(); + let _compilerOptionsObjectLiteralSyntax; + let _compilerOptionsPropertySyntax; + let moduleResolutionCache; + let actualResolveModuleNamesWorker; + const hasInvalidatedResolutions = host.hasInvalidatedResolutions || returnFalse; + if (host.resolveModuleNameLiterals) { + actualResolveModuleNamesWorker = host.resolveModuleNameLiterals.bind(host); + moduleResolutionCache = (_b = host.getModuleResolutionCache) == null ? void 0 : _b.call(host); + } else if (host.resolveModuleNames) { + actualResolveModuleNamesWorker = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile, reusedNames) => host.resolveModuleNames( + moduleNames.map(getModuleResolutionName), + containingFile, + reusedNames == null ? void 0 : reusedNames.map(getModuleResolutionName), + redirectedReference, + options2, + containingSourceFile + ).map( + (resolved) => resolved ? resolved.extension !== void 0 ? { resolvedModule: resolved } : ( + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + { resolvedModule: { ...resolved, extension: extensionFromPath(resolved.resolvedFileName) } } + ) : emptyResolution + ); + moduleResolutionCache = (_c = host.getModuleResolutionCache) == null ? void 0 : _c.call(host); + } else { + moduleResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); + actualResolveModuleNamesWorker = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( + moduleNames, + containingFile, + redirectedReference, + options2, + containingSourceFile, + host, + moduleResolutionCache, + createModuleResolutionLoader + ); + } + let actualResolveTypeReferenceDirectiveNamesWorker; + if (host.resolveTypeReferenceDirectiveReferences) { + actualResolveTypeReferenceDirectiveNamesWorker = host.resolveTypeReferenceDirectiveReferences.bind(host); + } else if (host.resolveTypeReferenceDirectives) { + actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => host.resolveTypeReferenceDirectives( + typeDirectiveNames.map(getTypeReferenceResolutionName), + containingFile, + redirectedReference, + options2, + containingSourceFile == null ? void 0 : containingSourceFile.impliedNodeFormat + ).map((resolvedTypeReferenceDirective) => ({ resolvedTypeReferenceDirective })); + } else { + const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache( + currentDirectory, + getCanonicalFileName, + /*options*/ + void 0, + moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), + moduleResolutionCache == null ? void 0 : moduleResolutionCache.optionsToRedirectsKey + ); + actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( + typeDirectiveNames, + containingFile, + redirectedReference, + options2, + containingSourceFile, + host, + typeReferenceDirectiveResolutionCache, + createTypeReferenceResolutionLoader + ); + } + const hasInvalidatedLibResolutions = host.hasInvalidatedLibResolutions || returnFalse; + let actualResolveLibrary; + if (host.resolveLibrary) { + actualResolveLibrary = host.resolveLibrary.bind(host); + } else { + const libraryResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + actualResolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache); + } + const packageIdToSourceFile = /* @__PURE__ */ new Map(); + let sourceFileToPackageName = /* @__PURE__ */ new Map(); + let redirectTargetsMap = createMultiMap(); + let usesUriStyleNodeCoreModules; + const filesByName = /* @__PURE__ */ new Map(); + let missingFileNames = /* @__PURE__ */ new Map(); + const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? /* @__PURE__ */ new Map() : void 0; + let resolvedProjectReferences; + let projectReferenceRedirects; + let mapFromFileToProjectReferenceRedirects; + let mapFromToProjectReferenceRedirectSource; + const useSourceOfProjectReferenceRedirect = !!((_d = host.useSourceOfProjectReferenceRedirect) == null ? void 0 : _d.call(host)) && !options.disableSourceOfProjectReferenceRedirect; + const { onProgramCreateComplete, fileExists, directoryExists } = updateHostForUseSourceOfProjectReferenceRedirect({ + compilerHost: host, + getSymlinkCache, + useSourceOfProjectReferenceRedirect, + toPath: toPath3, + getResolvedProjectReferences, + getSourceOfProjectReferenceRedirect, + forEachResolvedProjectReference: forEachResolvedProjectReference2 + }); + const readFile = host.readFile.bind(host); + (_e = tracing) == null ? void 0 : _e.push(tracing.Phase.Program, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); + (_f = tracing) == null ? void 0 : _f.pop(); + let structureIsReused; + (_g = tracing) == null ? void 0 : _g.push(tracing.Phase.Program, "tryReuseStructureFromOldProgram", {}); + structureIsReused = tryReuseStructureFromOldProgram(); + (_h = tracing) == null ? void 0 : _h.pop(); + if (structureIsReused !== 2 /* Completely */) { + processingDefaultLibFiles = []; + processingOtherFiles = []; + if (projectReferences) { + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + if (rootNames.length) { + resolvedProjectReferences == null ? void 0 : resolvedProjectReferences.forEach((parsedRef, index) => { + if (!parsedRef) return; + const out = parsedRef.commandLine.options.outFile; + if (useSourceOfProjectReferenceRedirect) { + if (out || getEmitModuleKind(parsedRef.commandLine.options) === 0 /* None */) { + for (const fileName of parsedRef.commandLine.fileNames) { + processProjectReferenceFile(fileName, { kind: 1 /* SourceFromProjectReference */, index }); + } + } + } else { + if (out) { + processProjectReferenceFile(changeExtension(out, ".d.ts"), { kind: 2 /* OutputFromProjectReference */, index }); + } else if (getEmitModuleKind(parsedRef.commandLine.options) === 0 /* None */) { + const getCommonSourceDirectory3 = memoize(() => getCommonSourceDirectoryOfConfig(parsedRef.commandLine, !host.useCaseSensitiveFileNames())); + for (const fileName of parsedRef.commandLine.fileNames) { + if (!isDeclarationFileName(fileName) && !fileExtensionIs(fileName, ".json" /* Json */)) { + processProjectReferenceFile(getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory3), { kind: 2 /* OutputFromProjectReference */, index }); + } + } + } + } + }); + } + } + (_i = tracing) == null ? void 0 : _i.push(tracing.Phase.Program, "processRootFiles", { count: rootNames.length }); + forEach(rootNames, (name, index) => processRootFile( + name, + /*isDefaultLib*/ + false, + /*ignoreNoDefaultLib*/ + false, + { kind: 0 /* RootFile */, index } + )); + (_j = tracing) == null ? void 0 : _j.pop(); + automaticTypeDirectiveNames ?? (automaticTypeDirectiveNames = rootNames.length ? getAutomaticTypeDirectiveNames(options, host) : emptyArray); + automaticTypeDirectiveResolutions = createModeAwareCache(); + if (automaticTypeDirectiveNames.length) { + (_k = tracing) == null ? void 0 : _k.push(tracing.Phase.Program, "processTypeReferences", { count: automaticTypeDirectiveNames.length }); + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; + const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile); + const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(automaticTypeDirectiveNames, containingFilename); + for (let i = 0; i < automaticTypeDirectiveNames.length; i++) { + automaticTypeDirectiveResolutions.set( + automaticTypeDirectiveNames[i], + /*mode*/ + void 0, + resolutions[i] + ); + processTypeReferenceDirective( + automaticTypeDirectiveNames[i], + /*mode*/ + void 0, + resolutions[i], + { + kind: 8 /* AutomaticTypeDirectiveFile */, + typeReference: automaticTypeDirectiveNames[i], + packageId: (_m = (_l = resolutions[i]) == null ? void 0 : _l.resolvedTypeReferenceDirective) == null ? void 0 : _m.packageId + } + ); + } + (_n = tracing) == null ? void 0 : _n.pop(); + } + if (rootNames.length && !skipDefaultLib) { + const defaultLibraryFileName = getDefaultLibraryFileName(); + if (!options.lib && defaultLibraryFileName) { + processRootFile( + defaultLibraryFileName, + /*isDefaultLib*/ + true, + /*ignoreNoDefaultLib*/ + false, + { kind: 6 /* LibFile */ } + ); + } else { + forEach(options.lib, (libFileName, index) => { + processRootFile( + pathForLibFile(libFileName), + /*isDefaultLib*/ + true, + /*ignoreNoDefaultLib*/ + false, + { kind: 6 /* LibFile */, index } + ); + }); + } + } + files = toSorted(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + processingDefaultLibFiles = void 0; + processingOtherFiles = void 0; + filesWithReferencesProcessed = void 0; + } + if (oldProgram && host.onReleaseOldSourceFile) { + const oldSourceFiles = oldProgram.getSourceFiles(); + for (const oldSourceFile of oldSourceFiles) { + const newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is + oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path), newFile); + } + } + if (!host.getParsedCommandLine) { + oldProgram.forEachResolvedProjectReference((resolvedProjectReference) => { + if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { + host.onReleaseOldSourceFile( + resolvedProjectReference.sourceFile, + oldProgram.getCompilerOptions(), + /*hasSourceFileByPath*/ + false, + /*newSourceFileByResolvedPath*/ + void 0 + ); + } + }); + } + } + if (oldProgram && host.onReleaseParsedCommandLine) { + forEachProjectReference( + oldProgram.getProjectReferences(), + oldProgram.getResolvedProjectReferences(), + (oldResolvedRef, parent, index) => { + const oldReference = (parent == null ? void 0 : parent.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index]; + const oldRefPath = resolveProjectReferencePath(oldReference); + if (!(projectReferenceRedirects == null ? void 0 : projectReferenceRedirects.has(toPath3(oldRefPath)))) { + host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); + } + } + ); + } + oldProgram = void 0; + resolvedLibProcessing = void 0; + resolvedModulesProcessing = void 0; + resolvedTypeReferenceDirectiveNamesProcessing = void 0; + const program = { + getRootFileNames: () => rootNames, + getSourceFile, + getSourceFileByPath, + getSourceFiles: () => files, + getMissingFilePaths: () => missingFileNames, + getModuleResolutionCache: () => moduleResolutionCache, + getFilesByNameMap: () => filesByName, + getCompilerOptions: () => options, + getSyntacticDiagnostics, + getOptionsDiagnostics, + getGlobalDiagnostics, + getSemanticDiagnostics, + getCachedSemanticDiagnostics, + getSuggestionDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics2, + getBindAndCheckDiagnostics, + getProgramDiagnostics, + getTypeChecker, + getClassifiableNames, + getCommonSourceDirectory: getCommonSourceDirectory2, + emit, + getCurrentDirectory: () => currentDirectory, + getNodeCount: () => getTypeChecker().getNodeCount(), + getIdentifierCount: () => getTypeChecker().getIdentifierCount(), + getSymbolCount: () => getTypeChecker().getSymbolCount(), + getTypeCount: () => getTypeChecker().getTypeCount(), + getInstantiationCount: () => getTypeChecker().getInstantiationCount(), + getRelationCacheSizes: () => getTypeChecker().getRelationCacheSizes(), + getFileProcessingDiagnostics: () => programDiagnostics.getFileProcessingDiagnostics(), + getAutomaticTypeDirectiveNames: () => automaticTypeDirectiveNames, + getAutomaticTypeDirectiveResolutions: () => automaticTypeDirectiveResolutions, + isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary, + getModeForUsageLocation: getModeForUsageLocation2, + getEmitSyntaxForUsageLocation, + getModeForResolutionAtIndex, + getSourceFileFromReference, + getLibFileFromReference, + sourceFileToPackageName, + redirectTargetsMap, + usesUriStyleNodeCoreModules, + resolvedModules, + resolvedTypeReferenceDirectiveNames, + resolvedLibReferences, + getProgramDiagnosticsContainer: () => programDiagnostics, + getResolvedModule, + getResolvedModuleFromModuleSpecifier, + getResolvedTypeReferenceDirective, + getResolvedTypeReferenceDirectiveFromTypeReferenceDirective, + forEachResolvedModule, + forEachResolvedTypeReferenceDirective, + getCurrentPackagesMap: () => packageMap, + typesPackageExists, + packageBundlesTypes, + isEmittedFile, + getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics2, + getProjectReferences, + getResolvedProjectReferences, + getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath, + forEachResolvedProjectReference: forEachResolvedProjectReference2, + isSourceOfProjectReferenceRedirect, + getRedirectReferenceForResolutionFromSourceOfProject, + getCompilerOptionsForFile, + getDefaultResolutionModeForFile: getDefaultResolutionModeForFile2, + getEmitModuleFormatOfFile, + getImpliedNodeFormatForEmit, + shouldTransformImportCall, + emitBuildInfo, + fileExists, + readFile, + directoryExists, + getSymlinkCache, + realpath: (_o = host.realpath) == null ? void 0 : _o.bind(host), + useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(), + getCanonicalFileName, + getFileIncludeReasons: () => programDiagnostics.getFileReasons(), + structureIsReused, + writeFile: writeFile2, + getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation) + }; + onProgramCreateComplete(); + if (!skipVerifyCompilerOptions) { + verifyCompilerOptions(); + } + mark("afterProgram"); + measure("Program", "beforeProgram", "afterProgram"); + (_p = tracing) == null ? void 0 : _p.pop(); + return program; + function getResolvedModule(file, moduleName, mode) { + var _a2; + return (_a2 = resolvedModules == null ? void 0 : resolvedModules.get(file.path)) == null ? void 0 : _a2.get(moduleName, mode); + } + function getResolvedModuleFromModuleSpecifier(moduleSpecifier, sourceFile) { + sourceFile ?? (sourceFile = getSourceFileOfNode(moduleSpecifier)); + Debug.assertIsDefined(sourceFile, "`moduleSpecifier` must have a `SourceFile` ancestor. Use `program.getResolvedModule` instead to provide the containing file and resolution mode."); + return getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation2(sourceFile, moduleSpecifier)); + } + function getResolvedTypeReferenceDirective(file, typeDirectiveName, mode) { + var _a2; + return (_a2 = resolvedTypeReferenceDirectiveNames == null ? void 0 : resolvedTypeReferenceDirectiveNames.get(file.path)) == null ? void 0 : _a2.get(typeDirectiveName, mode); + } + function getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(typeRef, sourceFile) { + return getResolvedTypeReferenceDirective( + sourceFile, + typeRef.fileName, + getModeForTypeReferenceDirectiveInFile(typeRef, sourceFile) + ); + } + function forEachResolvedModule(callback, file) { + forEachResolution(resolvedModules, callback, file); + } + function forEachResolvedTypeReferenceDirective(callback, file) { + forEachResolution(resolvedTypeReferenceDirectiveNames, callback, file); + } + function forEachResolution(resolutionCache, callback, file) { + var _a2; + if (file) (_a2 = resolutionCache == null ? void 0 : resolutionCache.get(file.path)) == null ? void 0 : _a2.forEach((resolution, name, mode) => callback(resolution, name, mode, file.path)); + else resolutionCache == null ? void 0 : resolutionCache.forEach((resolutions, filePath) => resolutions.forEach((resolution, name, mode) => callback(resolution, name, mode, filePath))); + } + function getPackagesMap() { + if (packageMap) return packageMap; + packageMap = /* @__PURE__ */ new Map(); + forEachResolvedModule(({ resolvedModule }) => { + if (resolvedModule == null ? void 0 : resolvedModule.packageId) packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); + }); + return packageMap; + } + function typesPackageExists(packageName) { + return getPackagesMap().has(getTypesPackageName(packageName)); + } + function packageBundlesTypes(packageName) { + return !!getPackagesMap().get(packageName); + } + function addResolutionDiagnostics(resolution) { + var _a2; + if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) return; + programDiagnostics.addFileProcessingDiagnostic({ + kind: 2 /* ResolutionDiagnostics */, + diagnostics: resolution.resolutionDiagnostics + }); + } + function addResolutionDiagnosticsFromResolutionOrCache(containingFile, name, resolution, mode) { + if (host.resolveModuleNameLiterals || !host.resolveModuleNames) return addResolutionDiagnostics(resolution); + if (!moduleResolutionCache || isExternalModuleNameRelative(name)) return; + const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); + const containingDir = getDirectoryPath(containingFileName); + const redirectedReference = getRedirectReferenceForResolution(containingFile); + const fromCache = moduleResolutionCache.getFromNonRelativeNameCache(name, mode, containingDir, redirectedReference); + if (fromCache) addResolutionDiagnostics(fromCache); + } + function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { + var _a2, _b2; + const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); + const redirectedReference = getRedirectReferenceForResolution(containingFile); + (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveModuleNamesWorker", { containingFileName }); + mark("beforeResolveModule"); + const result = actualResolveModuleNamesWorker( + moduleNames, + containingFileName, + redirectedReference, + options, + containingFile, + reusedNames + ); + mark("afterResolveModule"); + measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); + (_b2 = tracing) == null ? void 0 : _b2.pop(); + return result; + } + function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, reusedNames) { + var _a2, _b2; + const containingSourceFile = !isString(containingFile) ? containingFile : void 0; + const containingFileName = !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; + const redirectedReference = containingSourceFile && getRedirectReferenceForResolution(containingSourceFile); + (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName }); + mark("beforeResolveTypeReference"); + const result = actualResolveTypeReferenceDirectiveNamesWorker( + typeDirectiveNames, + containingFileName, + redirectedReference, + options, + containingSourceFile, + reusedNames + ); + mark("afterResolveTypeReference"); + measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); + (_b2 = tracing) == null ? void 0 : _b2.pop(); + return result; + } + function getRedirectReferenceForResolution(file) { + const redirect = getResolvedProjectReferenceToRedirect(file.originalFileName); + if (redirect || !isDeclarationFileName(file.originalFileName)) return redirect; + const resultFromDts = getRedirectReferenceForResolutionFromSourceOfProject(file.path); + if (resultFromDts) return resultFromDts; + if (!host.realpath || !options.preserveSymlinks || !file.originalFileName.includes(nodeModulesPathPart)) return void 0; + const realDeclarationPath = toPath3(host.realpath(file.originalFileName)); + return realDeclarationPath === file.path ? void 0 : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationPath); + } + function getRedirectReferenceForResolutionFromSourceOfProject(filePath) { + const source = getSourceOfProjectReferenceRedirect(filePath); + if (isString(source)) return getResolvedProjectReferenceToRedirect(source); + if (!source) return void 0; + return forEachResolvedProjectReference2((resolvedRef) => { + const out = resolvedRef.commandLine.options.outFile; + if (!out) return void 0; + return toPath3(out) === filePath ? resolvedRef : void 0; + }); + } + function compareDefaultLibFiles(a, b) { + return compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); + } + function getDefaultLibFilePriority(a) { + if (containsPath( + defaultLibraryPath, + a.fileName, + /*ignoreCase*/ + false + )) { + const basename = getBaseFileName(a.fileName); + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") return 0; + const name = removeSuffix(removePrefix(basename, "lib."), ".d.ts"); + const index = libs.indexOf(name); + if (index !== -1) return index + 1; + } + return libs.length + 2; + } + function toPath3(fileName) { + return toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCommonSourceDirectory2() { + let commonSourceDirectory = programDiagnostics.getCommonSourceDirectory(); + if (commonSourceDirectory !== void 0) { + return commonSourceDirectory; + } + const emittedFiles = filter(files, (file) => sourceFileMayBeEmitted(file, program)); + commonSourceDirectory = getCommonSourceDirectory( + options, + () => mapDefined(emittedFiles, (file) => file.isDeclarationFile ? void 0 : file.fileName), + currentDirectory, + getCanonicalFileName, + (commonSourceDirectory2) => checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory2) + ); + programDiagnostics.setCommonSourceDirectory(commonSourceDirectory); + return commonSourceDirectory; + } + function getClassifiableNames() { + var _a2; + if (!classifiableNames) { + getTypeChecker(); + classifiableNames = /* @__PURE__ */ new Set(); + for (const sourceFile of files) { + (_a2 = sourceFile.classifiableNames) == null ? void 0 : _a2.forEach((value) => classifiableNames.add(value)); + } + } + return classifiableNames; + } + function resolveModuleNamesReusingOldState(moduleNames, containingFile) { + return resolveNamesReusingOldState({ + entries: moduleNames, + containingFile, + containingSourceFile: containingFile, + redirectedReference: getRedirectReferenceForResolution(containingFile), + nameAndModeGetter: moduleResolutionNameAndModeGetter, + resolutionWorker: resolveModuleNamesWorker, + getResolutionFromOldProgram: (name, mode) => oldProgram == null ? void 0 : oldProgram.getResolvedModule(containingFile, name, mode), + getResolved: getResolvedModuleFromResolution, + canReuseResolutionsInFile: () => containingFile === (oldProgram == null ? void 0 : oldProgram.getSourceFile(containingFile.fileName)) && !hasInvalidatedResolutions(containingFile.path), + resolveToOwnAmbientModule: true + }); + } + function resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectiveNames, containingFile) { + const containingSourceFile = !isString(containingFile) ? containingFile : void 0; + return resolveNamesReusingOldState({ + entries: typeDirectiveNames, + containingFile, + containingSourceFile, + redirectedReference: containingSourceFile && getRedirectReferenceForResolution(containingSourceFile), + nameAndModeGetter: typeReferenceResolutionNameAndModeGetter, + resolutionWorker: resolveTypeReferenceDirectiveNamesWorker, + getResolutionFromOldProgram: (name, mode) => { + var _a2; + return containingSourceFile ? oldProgram == null ? void 0 : oldProgram.getResolvedTypeReferenceDirective(containingSourceFile, name, mode) : (_a2 = oldProgram == null ? void 0 : oldProgram.getAutomaticTypeDirectiveResolutions()) == null ? void 0 : _a2.get(name, mode); + }, + getResolved: getResolvedTypeReferenceDirectiveFromResolution, + canReuseResolutionsInFile: () => containingSourceFile ? containingSourceFile === (oldProgram == null ? void 0 : oldProgram.getSourceFile(containingSourceFile.fileName)) && !hasInvalidatedResolutions(containingSourceFile.path) : !hasInvalidatedResolutions(toPath3(containingFile)) + }); + } + function resolveNamesReusingOldState({ + entries, + containingFile, + containingSourceFile, + redirectedReference, + nameAndModeGetter, + resolutionWorker, + getResolutionFromOldProgram, + getResolved, + canReuseResolutionsInFile, + resolveToOwnAmbientModule + }) { + if (!entries.length) return emptyArray; + if (structureIsReused === 0 /* Not */ && (!resolveToOwnAmbientModule || !containingSourceFile.ambientModuleNames.length)) { + return resolutionWorker( + entries, + containingFile, + /*reusedNames*/ + void 0 + ); + } + let unknownEntries; + let unknownEntryIndices; + let result; + let reusedNames; + const reuseResolutions = canReuseResolutionsInFile(); + for (let i = 0; i < entries.length; i++) { + const entry = entries[i]; + if (reuseResolutions) { + const name = nameAndModeGetter.getName(entry); + const mode = nameAndModeGetter.getMode(entry, containingSourceFile, (redirectedReference == null ? void 0 : redirectedReference.commandLine.options) ?? options); + const oldResolution = getResolutionFromOldProgram(name, mode); + const oldResolved = oldResolution && getResolved(oldResolution); + if (oldResolved) { + if (isTraceEnabled(options, host)) { + trace( + host, + resolutionWorker === resolveModuleNamesWorker ? oldResolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : oldResolved.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2, + name, + containingSourceFile ? getNormalizedAbsolutePath(containingSourceFile.originalFileName, currentDirectory) : containingFile, + oldResolved.resolvedFileName, + oldResolved.packageId && packageIdToString(oldResolved.packageId) + ); + } + (result ?? (result = new Array(entries.length)))[i] = oldResolution; + (reusedNames ?? (reusedNames = [])).push(entry); + continue; + } + } + if (resolveToOwnAmbientModule) { + const name = nameAndModeGetter.getName(entry); + if (contains(containingSourceFile.ambientModuleNames, name)) { + if (isTraceEnabled(options, host)) { + trace( + host, + Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, + name, + getNormalizedAbsolutePath(containingSourceFile.originalFileName, currentDirectory) + ); + } + (result ?? (result = new Array(entries.length)))[i] = emptyResolution; + continue; + } + } + (unknownEntries ?? (unknownEntries = [])).push(entry); + (unknownEntryIndices ?? (unknownEntryIndices = [])).push(i); + } + if (!unknownEntries) return result; + const resolutions = resolutionWorker(unknownEntries, containingFile, reusedNames); + if (!result) return resolutions; + resolutions.forEach((resolution, index) => result[unknownEntryIndices[index]] = resolution); + return result; + } + function canReuseProjectReferences() { + return !forEachProjectReference( + oldProgram.getProjectReferences(), + oldProgram.getResolvedProjectReferences(), + (oldResolvedRef, parent, index) => { + const newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + const newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || !arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); + } else { + return newResolvedRef !== void 0; + } + }, + (oldProjectReferences, parent) => { + const newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences; + return !arrayIsEqualTo(oldProjectReferences, newReferences, projectReferenceIsEqualTo); + } + ); + } + function tryReuseStructureFromOldProgram() { + var _a2; + if (!oldProgram) { + return 0 /* Not */; + } + const oldOptions = oldProgram.getCompilerOptions(); + if (changesAffectModuleResolution(oldOptions, options)) { + return 0 /* Not */; + } + const oldRootNames = oldProgram.getRootFileNames(); + if (!arrayIsEqualTo(oldRootNames, rootNames)) { + return 0 /* Not */; + } + if (!canReuseProjectReferences()) { + return 0 /* Not */; + } + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + const newSourceFiles = []; + const modifiedSourceFiles = []; + structureIsReused = 2 /* Completely */; + if (forEachEntry(oldProgram.getMissingFilePaths(), (missingFileName) => host.fileExists(missingFileName))) { + return 0 /* Not */; + } + const oldSourceFiles = oldProgram.getSourceFiles(); + let SeenPackageName; + ((SeenPackageName2) => { + SeenPackageName2[SeenPackageName2["Exists"] = 0] = "Exists"; + SeenPackageName2[SeenPackageName2["Modified"] = 1] = "Modified"; + })(SeenPackageName || (SeenPackageName = {})); + const seenPackageNames = /* @__PURE__ */ new Map(); + for (const oldSourceFile of oldSourceFiles) { + const sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); + let newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath( + oldSourceFile.fileName, + oldSourceFile.resolvedPath, + sourceFileOptions, + /*onError*/ + void 0, + shouldCreateNewSourceFile + ) : host.getSourceFile( + oldSourceFile.fileName, + sourceFileOptions, + /*onError*/ + void 0, + shouldCreateNewSourceFile + ); + if (!newSourceFile) { + return 0 /* Not */; + } + newSourceFile.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0; + newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; + Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); + let fileChanged; + if (oldSourceFile.redirectInfo) { + if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { + return 0 /* Not */; + } + fileChanged = false; + newSourceFile = oldSourceFile; + } else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { + if (newSourceFile !== oldSourceFile) { + return 0 /* Not */; + } + fileChanged = false; + } else { + fileChanged = newSourceFile !== oldSourceFile; + } + newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; + const packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); + if (packageName !== void 0) { + const prevKind = seenPackageNames.get(packageName); + const newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */; + if (prevKind !== void 0 && newKind === 1 /* Modified */ || prevKind === 1 /* Modified */) { + return 0 /* Not */; + } + seenPackageNames.set(packageName, newKind); + } + if (fileChanged) { + if (oldSourceFile.impliedNodeFormat !== newSourceFile.impliedNodeFormat) { + structureIsReused = 1 /* SafeModules */; + } else if (!arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + structureIsReused = 1 /* SafeModules */; + } else if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + structureIsReused = 1 /* SafeModules */; + } else if (!arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + structureIsReused = 1 /* SafeModules */; + } else { + collectExternalModuleReferences(newSourceFile); + if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + structureIsReused = 1 /* SafeModules */; + } else if (!arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + structureIsReused = 1 /* SafeModules */; + } else if ((oldSourceFile.flags & 12582912 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 12582912 /* PermanentlySetIncrementalFlags */)) { + structureIsReused = 1 /* SafeModules */; + } else if (!arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + structureIsReused = 1 /* SafeModules */; + } + } + modifiedSourceFiles.push(newSourceFile); + } else if (hasInvalidatedResolutions(oldSourceFile.path)) { + structureIsReused = 1 /* SafeModules */; + modifiedSourceFiles.push(newSourceFile); + } + newSourceFiles.push(newSourceFile); + } + if (structureIsReused !== 2 /* Completely */) { + return structureIsReused; + } + for (const newSourceFile of modifiedSourceFiles) { + const moduleNames = getModuleNames(newSourceFile); + const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); + (resolvedModulesProcessing ?? (resolvedModulesProcessing = /* @__PURE__ */ new Map())).set(newSourceFile.path, resolutions); + const optionsForFile = getCompilerOptionsForFile(newSourceFile); + const resolutionsChanged = hasChangesInResolutions( + moduleNames, + resolutions, + (name) => oldProgram.getResolvedModule(newSourceFile, name.text, getModeForUsageLocationWorker(newSourceFile, name, optionsForFile)), + moduleResolutionIsEqualTo + ); + if (resolutionsChanged) structureIsReused = 1 /* SafeModules */; + const typesReferenceDirectives = newSourceFile.typeReferenceDirectives; + const typeReferenceResolutions = resolveTypeReferenceDirectiveNamesReusingOldState(typesReferenceDirectives, newSourceFile); + (resolvedTypeReferenceDirectiveNamesProcessing ?? (resolvedTypeReferenceDirectiveNamesProcessing = /* @__PURE__ */ new Map())).set(newSourceFile.path, typeReferenceResolutions); + const typeReferenceResolutionsChanged = hasChangesInResolutions( + typesReferenceDirectives, + typeReferenceResolutions, + (name) => oldProgram.getResolvedTypeReferenceDirective( + newSourceFile, + getTypeReferenceResolutionName(name), + getModeForTypeReferenceDirectiveInFile(name, newSourceFile) + ), + typeDirectiveIsEqualTo + ); + if (typeReferenceResolutionsChanged) structureIsReused = 1 /* SafeModules */; + } + if (structureIsReused !== 2 /* Completely */) { + return structureIsReused; + } + if (changesAffectingProgramStructure(oldOptions, options)) { + return 1 /* SafeModules */; + } + if (oldProgram.resolvedLibReferences && forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName) => pathForLibFileWorker(libFileName).actual !== resolution.actual)) { + return 1 /* SafeModules */; + } + if (host.hasChangedAutomaticTypeDirectiveNames) { + if (host.hasChangedAutomaticTypeDirectiveNames()) return 1 /* SafeModules */; + } else { + automaticTypeDirectiveNames = getAutomaticTypeDirectiveNames(options, host); + if (!arrayIsEqualTo(oldProgram.getAutomaticTypeDirectiveNames(), automaticTypeDirectiveNames)) return 1 /* SafeModules */; + } + missingFileNames = oldProgram.getMissingFilePaths(); + Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); + for (const newSourceFile of newSourceFiles) { + filesByName.set(newSourceFile.path, newSourceFile); + } + const oldFilesByNameMap = oldProgram.getFilesByNameMap(); + oldFilesByNameMap.forEach((oldFile, path) => { + if (!oldFile) { + filesByName.set(path, oldFile); + return; + } + if (oldFile.path === path) { + if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) { + sourceFilesFoundSearchingNodeModules.set(oldFile.path, true); + } + return; + } + filesByName.set(path, filesByName.get(oldFile.path)); + }); + const isConfigIdentical = oldOptions.configFile && oldOptions.configFile === options.configFile || !oldOptions.configFile && !options.configFile && !optionsHaveChanges(oldOptions, options, optionDeclarations); + programDiagnostics.reuseStateFromOldProgram(oldProgram.getProgramDiagnosticsContainer(), isConfigIdentical); + skipVerifyCompilerOptions = isConfigIdentical; + files = newSourceFiles; + automaticTypeDirectiveNames = oldProgram.getAutomaticTypeDirectiveNames(); + automaticTypeDirectiveResolutions = oldProgram.getAutomaticTypeDirectiveResolutions(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsMap = oldProgram.redirectTargetsMap; + usesUriStyleNodeCoreModules = oldProgram.usesUriStyleNodeCoreModules; + resolvedModules = oldProgram.resolvedModules; + resolvedTypeReferenceDirectiveNames = oldProgram.resolvedTypeReferenceDirectiveNames; + resolvedLibReferences = oldProgram.resolvedLibReferences; + packageMap = oldProgram.getCurrentPackagesMap(); + return 2 /* Completely */; + } + function getEmitHost(writeFileCallback) { + return { + getCanonicalFileName, + getCommonSourceDirectory: program.getCommonSourceDirectory, + getCompilerOptions: program.getCompilerOptions, + getCurrentDirectory: () => currentDirectory, + getSourceFile: program.getSourceFile, + getSourceFileByPath: program.getSourceFileByPath, + getSourceFiles: program.getSourceFiles, + isSourceFileFromExternalLibrary, + getResolvedProjectReferenceToRedirect, + getProjectReferenceRedirect, + isSourceOfProjectReferenceRedirect, + getSymlinkCache, + writeFile: writeFileCallback || writeFile2, + isEmitBlocked, + shouldTransformImportCall, + getEmitModuleFormatOfFile, + getDefaultResolutionModeForFile: getDefaultResolutionModeForFile2, + getModeForResolutionAtIndex, + readFile: (f) => host.readFile(f), + fileExists: (f) => { + const path = toPath3(f); + if (getSourceFileByPath(path)) return true; + if (missingFileNames.has(path)) return false; + return host.fileExists(f); + }, + realpath: maybeBind(host, host.realpath), + useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(), + getBuildInfo: () => { + var _a2; + return (_a2 = program.getBuildInfo) == null ? void 0 : _a2.call(program); + }, + getSourceFileFromReference: (file, ref) => program.getSourceFileFromReference(file, ref), + redirectTargetsMap, + getFileIncludeReasons: program.getFileIncludeReasons, + createHash: maybeBind(host, host.createHash), + getModuleResolutionCache: () => program.getModuleResolutionCache(), + trace: maybeBind(host, host.trace), + getGlobalTypingsCacheLocation: program.getGlobalTypingsCacheLocation + }; + } + function writeFile2(fileName, text, writeByteOrderMark, onError, sourceFiles, data) { + host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + } + function emitBuildInfo(writeFileCallback) { + var _a2, _b2; + (_a2 = tracing) == null ? void 0 : _a2.push( + tracing.Phase.Emit, + "emitBuildInfo", + {}, + /*separateBeginAndEnd*/ + true + ); + mark("beforeEmit"); + const emitResult = emitFiles( + notImplementedResolver, + getEmitHost(writeFileCallback), + /*targetSourceFile*/ + void 0, + /*transformers*/ + noTransformers, + /*emitOnly*/ + false, + /*onlyBuildInfo*/ + true + ); + mark("afterEmit"); + measure("Emit", "beforeEmit", "afterEmit"); + (_b2 = tracing) == null ? void 0 : _b2.pop(); + return emitResult; + } + function getResolvedProjectReferences() { + return resolvedProjectReferences; + } + function getProjectReferences() { + return projectReferences; + } + function isSourceFileFromExternalLibrary(file) { + return !!sourceFilesFoundSearchingNodeModules.get(file.path); + } + function isSourceFileDefaultLibrary(file) { + if (!file.isDeclarationFile) { + return false; + } + if (file.hasNoDefaultLib) { + return true; + } + if (options.noLib) { + return false; + } + const equalityComparer = host.useCaseSensitiveFileNames() ? equateStringsCaseSensitive : equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } else { + return some(options.lib, (libFileName) => { + const resolvedLib = resolvedLibReferences.get(libFileName); + return !!resolvedLib && equalityComparer(file.fileName, resolvedLib.actual); + }); + } + } + function getTypeChecker() { + return typeChecker || (typeChecker = createTypeChecker(program)); + } + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit, skipBuildInfo) { + var _a2, _b2; + (_a2 = tracing) == null ? void 0 : _a2.push( + tracing.Phase.Emit, + "emit", + { path: sourceFile == null ? void 0 : sourceFile.path }, + /*separateBeginAndEnd*/ + true + ); + const result = runWithCancellationToken( + () => emitWorker( + program, + sourceFile, + writeFileCallback, + cancellationToken, + emitOnly, + transformers, + forceDtsEmit, + skipBuildInfo + ) + ); + (_b2 = tracing) == null ? void 0 : _b2.pop(); + return result; + } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.has(toPath3(emitFileName)); + } + function emitWorker(program2, sourceFile, writeFileCallback, cancellationToken, emitOnly, customTransformers, forceDtsEmit, skipBuildInfo) { + if (!forceDtsEmit) { + const result = handleNoEmitOptions(program2, sourceFile, writeFileCallback, cancellationToken); + if (result) return result; + } + const typeChecker2 = getTypeChecker(); + const emitResolver = typeChecker2.getEmitResolver( + options.outFile ? void 0 : sourceFile, + cancellationToken, + emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) + ); + mark("beforeEmit"); + const emitResult = typeChecker2.runWithCancellationToken( + cancellationToken, + () => emitFiles( + emitResolver, + getEmitHost(writeFileCallback), + sourceFile, + getTransformers(options, customTransformers, emitOnly), + emitOnly, + /*onlyBuildInfo*/ + false, + forceDtsEmit, + skipBuildInfo + ) + ); + mark("afterEmit"); + measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; + } + function getSourceFile(fileName) { + return getSourceFileByPath(toPath3(fileName)); + } + function getSourceFileByPath(path) { + return filesByName.get(path) || void 0; + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return sortAndDeduplicateDiagnostics(getDiagnostics(sourceFile, cancellationToken)); + } + return sortAndDeduplicateDiagnostics(flatMap(program.getSourceFiles(), (sourceFile2) => { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + return getDiagnostics(sourceFile2, cancellationToken); + })); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken, nodesToCheck) { + return getDiagnosticsHelper( + sourceFile, + (sourceFile2, cancellationToken2) => getSemanticDiagnosticsForFile(sourceFile2, cancellationToken2, nodesToCheck), + cancellationToken + ); + } + function getCachedSemanticDiagnostics(sourceFile) { + return cachedBindAndCheckDiagnosticsForFile == null ? void 0 : cachedBindAndCheckDiagnosticsForFile.get(sourceFile.path); + } + function getBindAndCheckDiagnostics(sourceFile, cancellationToken) { + return getBindAndCheckDiagnosticsForFile( + sourceFile, + cancellationToken, + /*nodesToCheck*/ + void 0 + ); + } + function getProgramDiagnostics(sourceFile) { + var _a2; + if (skipTypeChecking(sourceFile, options, program)) { + return emptyArray; + } + const programDiagnosticsInFile = programDiagnostics.getCombinedDiagnostics(program).getDiagnostics(sourceFile.fileName); + if (!((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) { + return programDiagnosticsInFile; + } + return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, programDiagnosticsInFile).diagnostics; + } + function getDeclarationDiagnostics2(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + function getSyntacticDiagnosticsForFile(sourceFile) { + if (isSourceFileJS(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); + } + return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } catch (e) { + if (e instanceof OperationCanceledException) { + typeChecker = void 0; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken, nodesToCheck) { + return concatenate( + filterSemanticDiagnostics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken, nodesToCheck), options), + getProgramDiagnostics(sourceFile) + ); + } + function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken, nodesToCheck) { + if (nodesToCheck) { + return getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken, nodesToCheck); + } + let result = cachedBindAndCheckDiagnosticsForFile == null ? void 0 : cachedBindAndCheckDiagnosticsForFile.get(sourceFile.path); + if (!result) { + (cachedBindAndCheckDiagnosticsForFile ?? (cachedBindAndCheckDiagnosticsForFile = /* @__PURE__ */ new Map())).set( + sourceFile.path, + result = getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) + ); + } + return result; + } + function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken, nodesToCheck) { + return runWithCancellationToken(() => { + if (skipTypeChecking(sourceFile, options, program)) { + return emptyArray; + } + const typeChecker2 = getTypeChecker(); + Debug.assert(!!sourceFile.bindDiagnostics); + const isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; + const isPlainJs = isPlainJsFile(sourceFile, options.checkJs); + const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options); + let bindDiagnostics = sourceFile.bindDiagnostics; + let checkDiagnostics = typeChecker2.getDiagnostics(sourceFile, cancellationToken, nodesToCheck); + if (isPlainJs) { + bindDiagnostics = filter(bindDiagnostics, (d) => plainJSErrors.has(d.code)); + checkDiagnostics = filter(checkDiagnostics, (d) => plainJSErrors.has(d.code)); + } + return getMergedBindAndCheckDiagnostics( + sourceFile, + !isPlainJs, + !!nodesToCheck, + bindDiagnostics, + checkDiagnostics, + isCheckJs ? sourceFile.jsDocDiagnostics : void 0 + ); + }); + } + function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, partialCheck, ...allDiagnostics) { + var _a2; + const flatDiagnostics = flatten(allDiagnostics); + if (!includeBindAndCheckDiagnostics || !((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) { + return flatDiagnostics; + } + const { diagnostics, directives } = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics); + if (partialCheck) { + return diagnostics; + } + for (const errorExpectation of directives.getUnusedExpectations()) { + diagnostics.push(createDiagnosticForRange(sourceFile, errorExpectation.range, Diagnostics.Unused_ts_expect_error_directive)); + } + return diagnostics; + } + function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) { + const directives = createCommentDirectivesMap(sourceFile, commentDirectives); + const diagnostics = flatDiagnostics.filter((diagnostic) => markPrecedingCommentDirectiveLine(diagnostic, directives) === -1); + return { diagnostics, directives }; + } + function getSuggestionDiagnostics(sourceFile, cancellationToken) { + return runWithCancellationToken(() => { + return getTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + }); + } + function markPrecedingCommentDirectiveLine(diagnostic, directives) { + const { file, start } = diagnostic; + if (!file) { + return -1; + } + const lineStarts = getLineStarts(file); + let line = computeLineAndCharacterOfPosition(lineStarts, start).line - 1; + while (line >= 0) { + if (directives.markUsed(line)) { + return line; + } + const lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); + if (lineText !== "" && !/^\s*\/\/.*$/.test(lineText)) { + return -1; + } + line--; + } + return -1; + } + function getJSSyntacticDiagnosticsForFile(sourceFile) { + return runWithCancellationToken(() => { + const diagnostics = []; + walk(sourceFile, sourceFile); + forEachChildRecursively(sourceFile, walk, walkArray); + return diagnostics; + function walk(node, parent) { + switch (parent.kind) { + case 169 /* Parameter */: + case 172 /* PropertyDeclaration */: + case 174 /* MethodDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); + return "skip"; + } + // falls through + case 173 /* MethodSignature */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 219 /* ArrowFunction */: + case 260 /* VariableDeclaration */: + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + } + switch (node.kind) { + case 273 /* ImportClause */: + if (node.isTypeOnly) { + diagnostics.push(createDiagnosticForNode2(parent, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); + return "skip"; + } + break; + case 278 /* ExportDeclaration */: + if (node.isTypeOnly) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); + return "skip"; + } + break; + case 276 /* ImportSpecifier */: + case 281 /* ExportSpecifier */: + if (node.isTypeOnly) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, isImportSpecifier(node) ? "import...type" : "export...type")); + return "skip"; + } + break; + case 271 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.import_can_only_be_used_in_TypeScript_files)); + return "skip"; + case 277 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.export_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + break; + case 298 /* HeritageClause */: + const heritageClause = node; + if (heritageClause.token === 119 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + break; + case 264 /* InterfaceDeclaration */: + const interfaceKeyword = tokenToString(120 /* InterfaceKeyword */); + Debug.assertIsDefined(interfaceKeyword); + diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); + return "skip"; + case 267 /* ModuleDeclaration */: + const moduleKeyword = node.flags & 32 /* Namespace */ ? tokenToString(145 /* NamespaceKeyword */) : tokenToString(144 /* ModuleKeyword */); + Debug.assertIsDefined(moduleKeyword); + diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); + return "skip"; + case 265 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); + return "skip"; + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 262 /* FunctionDeclaration */: + if (!node.body) { + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Signature_declarations_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + return; + case 266 /* EnumDeclaration */: + const enumKeyword = Debug.checkDefined(tokenToString(94 /* EnumKeyword */)); + diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); + return "skip"; + case 235 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); + return "skip"; + case 234 /* AsExpression */: + diagnostics.push(createDiagnosticForNode2(node.type, Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); + return "skip"; + case 238 /* SatisfiesExpression */: + diagnostics.push(createDiagnosticForNode2(node.type, Diagnostics.Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files)); + return "skip"; + case 216 /* TypeAssertionExpression */: + Debug.fail(); + } + } + function walkArray(nodes, parent) { + if (canHaveIllegalDecorators(parent)) { + const decorator = find(parent.modifiers, isDecorator); + if (decorator) { + diagnostics.push(createDiagnosticForNode2(decorator, Diagnostics.Decorators_are_not_valid_here)); + } + } else if (canHaveDecorators(parent) && parent.modifiers) { + const decoratorIndex = findIndex(parent.modifiers, isDecorator); + if (decoratorIndex >= 0) { + if (isParameter(parent) && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode2(parent.modifiers[decoratorIndex], Diagnostics.Decorators_are_not_valid_here)); + } else if (isClassDeclaration(parent)) { + const exportIndex = findIndex(parent.modifiers, isExportModifier); + if (exportIndex >= 0) { + const defaultIndex = findIndex(parent.modifiers, isDefaultModifier); + if (decoratorIndex > exportIndex && defaultIndex >= 0 && decoratorIndex < defaultIndex) { + diagnostics.push(createDiagnosticForNode2(parent.modifiers[decoratorIndex], Diagnostics.Decorators_are_not_valid_here)); + } else if (exportIndex >= 0 && decoratorIndex < exportIndex) { + const trailingDecoratorIndex = findIndex(parent.modifiers, isDecorator, exportIndex); + if (trailingDecoratorIndex >= 0) { + diagnostics.push(addRelatedInfo( + createDiagnosticForNode2(parent.modifiers[trailingDecoratorIndex], Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export), + createDiagnosticForNode2(parent.modifiers[decoratorIndex], Diagnostics.Decorator_used_before_export_here) + )); + } + } + } + } + } + } + switch (parent.kind) { + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 174 /* MethodDeclaration */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 219 /* ArrowFunction */: + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + // falls through + case 243 /* VariableStatement */: + if (nodes === parent.modifiers) { + checkModifiers(parent.modifiers, parent.kind === 243 /* VariableStatement */); + return "skip"; + } + break; + case 172 /* PropertyDeclaration */: + if (nodes === parent.modifiers) { + for (const modifier of nodes) { + if (isModifier(modifier) && modifier.kind !== 126 /* StaticKeyword */ && modifier.kind !== 129 /* AccessorKeyword */) { + diagnostics.push(createDiagnosticForNode2(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); + } + } + return "skip"; + } + break; + case 169 /* Parameter */: + if (nodes === parent.modifiers && some(nodes, isModifier)) { + diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + break; + case 213 /* CallExpression */: + case 214 /* NewExpression */: + case 233 /* ExpressionWithTypeArguments */: + case 285 /* JsxSelfClosingElement */: + case 286 /* JsxOpeningElement */: + case 215 /* TaggedTemplateExpression */: + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); + return "skip"; + } + break; + } + } + function checkModifiers(modifiers, isConstValid) { + for (const modifier of modifiers) { + switch (modifier.kind) { + case 87 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // to report error, + // falls through + case 125 /* PublicKeyword */: + case 123 /* PrivateKeyword */: + case 124 /* ProtectedKeyword */: + case 148 /* ReadonlyKeyword */: + case 138 /* DeclareKeyword */: + case 128 /* AbstractKeyword */: + case 164 /* OverrideKeyword */: + case 103 /* InKeyword */: + case 147 /* OutKeyword */: + diagnostics.push(createDiagnosticForNode2(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 126 /* StaticKeyword */: + case 95 /* ExportKeyword */: + case 90 /* DefaultKeyword */: + case 129 /* AccessorKeyword */: + } + } + } + function createDiagnosticForNodeArray2(nodes, message, ...args) { + const start = nodes.pos; + return createFileDiagnostic(sourceFile, start, nodes.end - start, message, ...args); + } + function createDiagnosticForNode2(node, message, ...args) { + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args); + } + }); + } + function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + let result = cachedDeclarationDiagnosticsForFile == null ? void 0 : cachedDeclarationDiagnosticsForFile.get(sourceFile.path); + if (!result) { + (cachedDeclarationDiagnosticsForFile ?? (cachedDeclarationDiagnosticsForFile = /* @__PURE__ */ new Map())).set( + sourceFile.path, + result = getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) + ); + } + return result; + } + function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(() => { + const resolver = getTypeChecker().getEmitResolver(sourceFile, cancellationToken); + return getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile) || emptyArray; + }); + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.isDeclarationFile ? emptyArray : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + function getOptionsDiagnostics() { + return sortAndDeduplicateDiagnostics(concatenate( + programDiagnostics.getCombinedDiagnostics(program).getGlobalDiagnostics(), + getOptionsDiagnosticsOfConfigFile() + )); + } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) return emptyArray; + let diagnostics = programDiagnostics.getCombinedDiagnostics(program).getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference2((resolvedRef) => { + diagnostics = concatenate(diagnostics, programDiagnostics.getCombinedDiagnostics(program).getDiagnostics(resolvedRef.sourceFile.fileName)); + }); + return diagnostics; + } + function getGlobalDiagnostics() { + return rootNames.length ? sortAndDeduplicateDiagnostics(getTypeChecker().getGlobalDiagnostics().slice()) : emptyArray; + } + function getConfigFileParsingDiagnostics2() { + return configFileParsingDiagnostics || emptyArray; + } + function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason) { + processSourceFile( + normalizePath(fileName), + isDefaultLib, + ignoreNoDefaultLib, + /*packageId*/ + void 0, + reason + ); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.kind === 80 /* Identifier */ ? b.kind === 80 /* Identifier */ && a.escapedText === b.escapedText : b.kind === 11 /* StringLiteral */ && a.text === b.text; + } + function createSyntheticImport(text, file) { + const externalHelpersModuleReference = factory.createStringLiteral(text); + const importDecl = factory.createImportDeclaration( + /*modifiers*/ + void 0, + /*importClause*/ + void 0, + externalHelpersModuleReference + ); + addInternalEmitFlags(importDecl, 2 /* NeverApplyImportHelper */); + setParent(externalHelpersModuleReference, importDecl); + setParent(importDecl, file); + externalHelpersModuleReference.flags &= ~16 /* Synthesized */; + importDecl.flags &= ~16 /* Synthesized */; + return externalHelpersModuleReference; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + const isJavaScriptFile = isSourceFileJS(file); + const isExternalModuleFile = isExternalModule(file); + let imports; + let moduleAugmentations; + let ambientModules; + if (isJavaScriptFile || !file.isDeclarationFile && (getIsolatedModules(options) || isExternalModule(file))) { + if (options.importHelpers) { + imports = [createSyntheticImport(externalHelpersModuleNameText, file)]; + } + const jsxImport = getJSXRuntimeImport(getJSXImplicitImportBase(options, file), options); + if (jsxImport) { + (imports || (imports = [])).push(createSyntheticImport(jsxImport, file)); + } + } + for (const node of file.statements) { + collectModuleReferences( + node, + /*inAmbientModule*/ + false + ); + } + if (file.flags & 4194304 /* PossiblyContainsDynamicImport */ || isJavaScriptFile) { + forEachDynamicImportOrRequireCall( + file, + /*includeTypeSpaceImports*/ + true, + /*requireStringLiteralLikeArgument*/ + true, + (node, moduleSpecifier) => { + setParentRecursive( + node, + /*incremental*/ + false + ); + imports = append(imports, moduleSpecifier); + } + ); + } + file.imports = imports || emptyArray; + file.moduleAugmentations = moduleAugmentations || emptyArray; + file.ambientModuleNames = ambientModules || emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { + if (isAnyImportOrReExport(node)) { + const moduleNameExpr = getExternalModuleName(node); + if (moduleNameExpr && isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !isExternalModuleNameRelative(moduleNameExpr.text))) { + setParentRecursive( + node, + /*incremental*/ + false + ); + imports = append(imports, moduleNameExpr); + if (!usesUriStyleNodeCoreModules && currentNodeModulesDepth === 0 && !file.isDeclarationFile) { + if (startsWith(moduleNameExpr.text, "node:") && !exclusivelyPrefixedNodeCoreModules.has(moduleNameExpr.text)) { + usesUriStyleNodeCoreModules = true; + } else if (usesUriStyleNodeCoreModules === void 0 && unprefixedNodeCoreModules.has(moduleNameExpr.text)) { + usesUriStyleNodeCoreModules = false; + } + } + } + } else if (isModuleDeclaration(node)) { + if (isAmbientModule(node) && (inAmbientModule || hasSyntacticModifier(node, 128 /* Ambient */) || file.isDeclarationFile)) { + node.name.parent = node; + const nameText = getTextOfIdentifierOrLiteral(node.name); + if (isExternalModuleFile || inAmbientModule && !isExternalModuleNameRelative(nameText)) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); + } else if (!inAmbientModule) { + if (file.isDeclarationFile) { + (ambientModules || (ambientModules = [])).push(nameText); + } + const body = node.body; + if (body) { + for (const statement of body.statements) { + collectModuleReferences( + statement, + /*inAmbientModule*/ + true + ); + } + } + } + } + } + } + } + function getLibFileFromReference(ref) { + var _a2; + const libFileName = getLibFileNameFromLibReference(ref); + const actualFileName = libFileName && ((_a2 = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName)) == null ? void 0 : _a2.actual); + return actualFileName !== void 0 ? getSourceFile(actualFileName) : void 0; + } + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile2, fail, reason) { + if (hasExtension(fileName)) { + const canonicalFileName = host.getCanonicalFileName(fileName); + if (!options.allowNonTsExtensions && !forEach(flatten(supportedExtensionsWithJsonIfResolveJsonModule), (extension) => fileExtensionIs(canonicalFileName, extension))) { + if (fail) { + if (hasJSFileExtension(canonicalFileName)) { + fail(Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName); + } else { + fail(Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'"); + } + } + return void 0; + } + const sourceFile = getSourceFile2(fileName); + if (fail) { + if (!sourceFile) { + const redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } else { + fail(Diagnostics.File_0_not_found, fileName); + } + } else if (isReferencedFile(reason) && canonicalFileName === host.getCanonicalFileName(getSourceFileByPath(reason.file).fileName)) { + fail(Diagnostics.A_file_cannot_have_a_reference_to_itself); + } + } + return sourceFile; + } else { + const sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile2(fileName); + if (sourceFileNoExtension) return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(Diagnostics.File_0_not_found, fileName); + return void 0; + } + const sourceFileWithAddedExtension = forEach(supportedExtensions[0], (extension) => getSourceFile2(fileName + extension)); + if (fail && !sourceFileWithAddedExtension) fail(Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'"); + return sourceFileWithAddedExtension; + } + } + function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, reason) { + getSourceFileFromReferenceWorker( + fileName, + (fileName2) => findSourceFile(fileName2, isDefaultLib, ignoreNoDefaultLib, reason, packageId), + // TODO: GH#18217 + (diagnostic, ...args) => addFilePreprocessingFileExplainingDiagnostic( + /*file*/ + void 0, + reason, + diagnostic, + args + ), + reason + ); + } + function processProjectReferenceFile(fileName, reason) { + return processSourceFile( + fileName, + /*isDefaultLib*/ + false, + /*ignoreNoDefaultLib*/ + false, + /*packageId*/ + void 0, + reason + ); + } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason) { + const hasExistingReasonToReportErrorOn = !isReferencedFile(reason) && some(programDiagnostics.getFileReasons().get(existingFile.path), isReferencedFile); + if (hasExistingReasonToReportErrorOn) { + addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, [existingFile.fileName, fileName]); + } else { + addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]); + } + } + function createRedirectedSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { + var _a2; + const redirect = parseNodeFactory.createRedirectedSourceFile({ redirectTarget, unredirected }); + redirect.fileName = fileName; + redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; + redirect.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0; + redirect.packageJsonScope = sourceFileOptions.packageJsonScope; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + return redirect; + } + function findSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { + var _a2, _b2; + (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "findSourceFile", { + fileName, + isDefaultLib: isDefaultLib || void 0, + fileIncludeKind: FileIncludeKind[reason.kind] + }); + const result = findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId); + (_b2 = tracing) == null ? void 0 : _b2.pop(); + return result; + } + function getCreateSourceFileOptions(fileName, moduleResolutionCache2, host2, options2) { + const result = getImpliedNodeFormatForFileWorker(getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache2 == null ? void 0 : moduleResolutionCache2.getPackageJsonInfoCache(), host2, options2); + const languageVersion = getEmitScriptTarget(options2); + const setExternalModuleIndicator2 = getSetExternalModuleIndicator(options2); + return typeof result === "object" ? { ...result, languageVersion, setExternalModuleIndicator: setExternalModuleIndicator2, jsDocParsingMode: host2.jsDocParsingMode } : { languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator2, jsDocParsingMode: host2.jsDocParsingMode }; + } + function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { + var _a2; + const path = toPath3(fileName); + if (useSourceOfProjectReferenceRedirect) { + let source = getSourceOfProjectReferenceRedirect(path); + if (!source && host.realpath && options.preserveSymlinks && isDeclarationFileName(fileName) && fileName.includes(nodeModulesPathPart)) { + const realPath2 = toPath3(host.realpath(fileName)); + if (realPath2 !== path) source = getSourceOfProjectReferenceRedirect(realPath2); + } + if (source) { + const file2 = isString(source) ? findSourceFile(source, isDefaultLib, ignoreNoDefaultLib, reason, packageId) : void 0; + if (file2) addFileToFilesByName( + file2, + path, + fileName, + /*redirectedPath*/ + void 0 + ); + return file2; + } + } + const originalFileName = fileName; + if (filesByName.has(path)) { + const file2 = filesByName.get(path); + const addedReason = addFileIncludeReason( + file2 || void 0, + reason, + /*checkExisting*/ + true + ); + if (file2 && addedReason && !(options.forceConsistentCasingInFileNames === false)) { + const checkedName = file2.fileName; + const isRedirect = toPath3(checkedName) !== toPath3(fileName); + if (isRedirect) { + fileName = getProjectReferenceRedirect(fileName) || fileName; + } + const checkedAbsolutePath = getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory); + const inputAbsolutePath = getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory); + if (checkedAbsolutePath !== inputAbsolutePath) { + reportFileNamesDifferOnlyInCasingError(fileName, file2, reason); + } + } + if (file2 && sourceFilesFoundSearchingNodeModules.get(file2.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file2.path, false); + if (!options.noResolve) { + processReferencedFiles(file2, isDefaultLib); + processTypeReferenceDirectives(file2); + } + if (!options.noLib) { + processLibReferenceDirectives(file2); + } + modulesWithElidedImports.set(file2.path, false); + processImportedModules(file2); + } else if (file2 && modulesWithElidedImports.get(file2.path)) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { + modulesWithElidedImports.set(file2.path, false); + processImportedModules(file2); + } + } + return file2 || void 0; + } + let redirectedPath; + if (!useSourceOfProjectReferenceRedirect) { + const redirectProject = getProjectReferenceRedirectProject(fileName); + if (redirectProject) { + if (redirectProject.commandLine.options.outFile) { + return void 0; + } + const redirect = getProjectReferenceOutputName(redirectProject, fileName); + fileName = redirect; + redirectedPath = toPath3(redirect); + } + } + const sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options); + const file = host.getSourceFile( + fileName, + sourceFileOptions, + (hostErrorMessage) => addFilePreprocessingFileExplainingDiagnostic( + /*file*/ + void 0, + reason, + Diagnostics.Cannot_read_file_0_Colon_1, + [fileName, hostErrorMessage] + ), + shouldCreateNewSourceFile + ); + if (packageId) { + const packageIdKey = packageIdToString(packageId); + const fileFromPackageId = packageIdToSourceFile.get(packageIdKey); + if (fileFromPackageId) { + const dupFile = createRedirectedSourceFile(fileFromPackageId, file, fileName, path, toPath3(fileName), originalFileName, sourceFileOptions); + redirectTargetsMap.add(fileFromPackageId.path, fileName); + addFileToFilesByName(dupFile, path, fileName, redirectedPath); + addFileIncludeReason( + dupFile, + reason, + /*checkExisting*/ + false + ); + sourceFileToPackageName.set(path, packageIdToPackageName(packageId)); + processingOtherFiles.push(dupFile); + return dupFile; + } else if (file) { + packageIdToSourceFile.set(packageIdKey, file); + sourceFileToPackageName.set(path, packageIdToPackageName(packageId)); + } + } + addFileToFilesByName(file, path, fileName, redirectedPath); + if (file) { + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + file.fileName = fileName; + file.path = path; + file.resolvedPath = toPath3(fileName); + file.originalFileName = originalFileName; + file.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0; + file.packageJsonScope = sourceFileOptions.packageJsonScope; + addFileIncludeReason( + file, + reason, + /*checkExisting*/ + false + ); + if (host.useCaseSensitiveFileNames()) { + const pathLowerCase = toFileNameLowerCase(path); + const existingFile = filesByNameIgnoreCase.get(pathLowerCase); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason); + } else { + filesByNameIgnoreCase.set(pathLowerCase, file); + } + } + skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib && !ignoreNoDefaultLib; + if (!options.noResolve) { + processReferencedFiles(file, isDefaultLib); + processTypeReferenceDirectives(file); + } + if (!options.noLib) { + processLibReferenceDirectives(file); + } + processImportedModules(file); + if (isDefaultLib) { + processingDefaultLibFiles.push(file); + } else { + processingOtherFiles.push(file); + } + (filesWithReferencesProcessed ?? (filesWithReferencesProcessed = /* @__PURE__ */ new Set())).add(file.path); + } + return file; + } + function addFileIncludeReason(file, reason, checkExisting) { + if (file && (!checkExisting || !isReferencedFile(reason) || !(filesWithReferencesProcessed == null ? void 0 : filesWithReferencesProcessed.has(reason.file)))) { + programDiagnostics.getFileReasons().add(file.path, reason); + return true; + } + return false; + } + function addFileToFilesByName(file, path, fileName, redirectedPath) { + if (redirectedPath) { + updateFilesByNameMap(fileName, redirectedPath, file); + updateFilesByNameMap(fileName, path, file || false); + } else { + updateFilesByNameMap(fileName, path, file); + } + } + function updateFilesByNameMap(fileName, path, file) { + filesByName.set(path, file); + if (file !== void 0) missingFileNames.delete(path); + else missingFileNames.set(path, fileName); + } + function getProjectReferenceRedirect(fileName) { + const referencedProject = getProjectReferenceRedirectProject(fileName); + return referencedProject && getProjectReferenceOutputName(referencedProject, fileName); + } + function getProjectReferenceRedirectProject(fileName) { + if (!resolvedProjectReferences || !resolvedProjectReferences.length || isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".json" /* Json */)) { + return void 0; + } + return getResolvedProjectReferenceToRedirect(fileName); + } + function getProjectReferenceOutputName(referencedProject, fileName) { + const out = referencedProject.commandLine.options.outFile; + return out ? changeExtension(out, ".d.ts" /* Dts */) : getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames()); + } + function getResolvedProjectReferenceToRedirect(fileName) { + if (mapFromFileToProjectReferenceRedirects === void 0) { + mapFromFileToProjectReferenceRedirects = /* @__PURE__ */ new Map(); + forEachResolvedProjectReference2((referencedProject) => { + if (toPath3(options.configFilePath) !== referencedProject.sourceFile.path) { + referencedProject.commandLine.fileNames.forEach((f) => mapFromFileToProjectReferenceRedirects.set(toPath3(f), referencedProject.sourceFile.path)); + } + }); + } + const referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath3(fileName)); + return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath); + } + function forEachResolvedProjectReference2(cb) { + return forEachResolvedProjectReference(resolvedProjectReferences, cb); + } + function getSourceOfProjectReferenceRedirect(path) { + if (!isDeclarationFileName(path)) return void 0; + if (mapFromToProjectReferenceRedirectSource === void 0) { + mapFromToProjectReferenceRedirectSource = /* @__PURE__ */ new Map(); + forEachResolvedProjectReference2((resolvedRef) => { + const out = resolvedRef.commandLine.options.outFile; + if (out) { + const outputDts = changeExtension(out, ".d.ts" /* Dts */); + mapFromToProjectReferenceRedirectSource.set(toPath3(outputDts), true); + } else { + const getCommonSourceDirectory3 = memoize(() => getCommonSourceDirectoryOfConfig(resolvedRef.commandLine, !host.useCaseSensitiveFileNames())); + forEach(resolvedRef.commandLine.fileNames, (fileName) => { + if (!isDeclarationFileName(fileName) && !fileExtensionIs(fileName, ".json" /* Json */)) { + const outputDts = getOutputDeclarationFileName(fileName, resolvedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory3); + mapFromToProjectReferenceRedirectSource.set(toPath3(outputDts), fileName); + } + }); + } + }); + } + return mapFromToProjectReferenceRedirectSource.get(path); + } + function isSourceOfProjectReferenceRedirect(fileName) { + return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName); + } + function getResolvedProjectReferenceByPath(projectReferencePath) { + if (!projectReferenceRedirects) { + return void 0; + } + return projectReferenceRedirects.get(projectReferencePath) || void 0; + } + function processReferencedFiles(file, isDefaultLib) { + forEach(file.referencedFiles, (ref, index) => { + processSourceFile( + resolveTripleslashReference(ref.fileName, file.fileName), + isDefaultLib, + /*ignoreNoDefaultLib*/ + false, + /*packageId*/ + void 0, + { kind: 4 /* ReferenceFile */, file: file.path, index } + ); + }); + } + function processTypeReferenceDirectives(file) { + const typeDirectives = file.typeReferenceDirectives; + if (!typeDirectives.length) return; + const resolutions = (resolvedTypeReferenceDirectiveNamesProcessing == null ? void 0 : resolvedTypeReferenceDirectiveNamesProcessing.get(file.path)) || resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectives, file); + const resolutionsInFile = createModeAwareCache(); + (resolvedTypeReferenceDirectiveNames ?? (resolvedTypeReferenceDirectiveNames = /* @__PURE__ */ new Map())).set(file.path, resolutionsInFile); + for (let index = 0; index < typeDirectives.length; index++) { + const ref = file.typeReferenceDirectives[index]; + const resolvedTypeReferenceDirective = resolutions[index]; + const fileName = ref.fileName; + const mode = getModeForTypeReferenceDirectiveInFile(ref, file); + resolutionsInFile.set(fileName, mode, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: 5 /* TypeReferenceDirective */, file: file.path, index }); + } + } + function getCompilerOptionsForFile(file) { + var _a2; + return ((_a2 = getRedirectReferenceForResolution(file)) == null ? void 0 : _a2.commandLine.options) || options; + } + function processTypeReferenceDirective(typeReferenceDirective, mode, resolution, reason) { + var _a2, _b2; + (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolution.resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : void 0 }); + processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolution, reason); + (_b2 = tracing) == null ? void 0 : _b2.pop(); + } + function processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolution, reason) { + addResolutionDiagnostics(resolution); + const { resolvedTypeReferenceDirective } = resolution; + if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth++; + processSourceFile( + resolvedTypeReferenceDirective.resolvedFileName, + /*isDefaultLib*/ + false, + /*ignoreNoDefaultLib*/ + false, + resolvedTypeReferenceDirective.packageId, + reason + ); + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth--; + } else { + addFilePreprocessingFileExplainingDiagnostic( + /*file*/ + void 0, + reason, + Diagnostics.Cannot_find_type_definition_file_for_0, + [typeReferenceDirective] + ); + } + } + function pathForLibFile(libFileName) { + const existing = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName); + if (existing) return existing.actual; + const result = pathForLibFileWorker(libFileName); + (resolvedLibReferences ?? (resolvedLibReferences = /* @__PURE__ */ new Map())).set(libFileName, result); + return result.actual; + } + function pathForLibFileWorker(libFileName) { + var _a2, _b2, _c2, _d2, _e2; + const existing = resolvedLibProcessing == null ? void 0 : resolvedLibProcessing.get(libFileName); + if (existing) return existing; + if (options.libReplacement === false) { + const result2 = { + resolution: { + resolvedModule: void 0 + }, + actual: combinePaths(defaultLibraryPath, libFileName) + }; + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, result2); + return result2; + } + if (structureIsReused !== 0 /* Not */ && oldProgram && !hasInvalidatedLibResolutions(libFileName)) { + const oldResolution = (_a2 = oldProgram.resolvedLibReferences) == null ? void 0 : _a2.get(libFileName); + if (oldResolution) { + if (oldResolution.resolution && isTraceEnabled(options, host)) { + const libraryName2 = getLibraryNameFromLibFileName(libFileName); + const resolveFrom2 = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + trace( + host, + oldResolution.resolution.resolvedModule ? oldResolution.resolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, + libraryName2, + getNormalizedAbsolutePath(resolveFrom2, currentDirectory), + (_b2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _b2.resolvedFileName, + ((_c2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _c2.packageId) && packageIdToString(oldResolution.resolution.resolvedModule.packageId) + ); + } + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, oldResolution); + return oldResolution; + } + } + const libraryName = getLibraryNameFromLibFileName(libFileName); + const resolveFrom = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + (_d2 = tracing) == null ? void 0 : _d2.push(tracing.Phase.Program, "resolveLibrary", { resolveFrom }); + mark("beforeResolveLibrary"); + const resolution = actualResolveLibrary(libraryName, resolveFrom, options, libFileName); + mark("afterResolveLibrary"); + measure("ResolveLibrary", "beforeResolveLibrary", "afterResolveLibrary"); + (_e2 = tracing) == null ? void 0 : _e2.pop(); + const result = { + resolution, + actual: resolution.resolvedModule ? resolution.resolvedModule.resolvedFileName : combinePaths(defaultLibraryPath, libFileName) + }; + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, result); + return result; + } + function processLibReferenceDirectives(file) { + forEach(file.libReferenceDirectives, (libReference, index) => { + const libFileName = getLibFileNameFromLibReference(libReference); + if (libFileName) { + processRootFile( + pathForLibFile(libFileName), + /*isDefaultLib*/ + true, + /*ignoreNoDefaultLib*/ + true, + { kind: 7 /* LibReferenceDirective */, file: file.path, index } + ); + } else { + programDiagnostics.addFileProcessingDiagnostic({ + kind: 0 /* FilePreprocessingLibReferenceDiagnostic */, + reason: { kind: 7 /* LibReferenceDirective */, file: file.path, index } + }); + } + }); + } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } + function processImportedModules(file) { + collectExternalModuleReferences(file); + if (file.imports.length || file.moduleAugmentations.length) { + const moduleNames = getModuleNames(file); + const resolutions = (resolvedModulesProcessing == null ? void 0 : resolvedModulesProcessing.get(file.path)) || resolveModuleNamesReusingOldState(moduleNames, file); + Debug.assert(resolutions.length === moduleNames.length); + const optionsForFile = getCompilerOptionsForFile(file); + const resolutionsInFile = createModeAwareCache(); + (resolvedModules ?? (resolvedModules = /* @__PURE__ */ new Map())).set(file.path, resolutionsInFile); + for (let index = 0; index < moduleNames.length; index++) { + const resolution = resolutions[index].resolvedModule; + const moduleName = moduleNames[index].text; + const mode = getModeForUsageLocationWorker(file, moduleNames[index], optionsForFile); + resolutionsInFile.set(moduleName, mode, resolutions[index]); + addResolutionDiagnosticsFromResolutionOrCache(file, moduleName, resolutions[index], mode); + if (!resolution) { + continue; + } + const isFromNodeModulesSearch = resolution.isExternalLibraryImport; + const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension) && !getProjectReferenceRedirectProject(resolution.resolvedFileName); + const isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile && (!resolution.originalPath || pathContainsNodeModules(resolution.resolvedFileName)); + const resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + const elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + const shouldAddFile = resolvedFileName && !getResolutionDiagnostic(optionsForFile, resolution, file) && !optionsForFile.noResolve && index < file.imports.length && !elideImport && !(isJsFile && !getAllowJSCompilerOption(optionsForFile)) && (isInJSFile(file.imports[index]) || !(file.imports[index].flags & 16777216 /* JSDoc */)); + if (elideImport) { + modulesWithElidedImports.set(file.path, true); + } else if (shouldAddFile) { + findSourceFile( + resolvedFileName, + /*isDefaultLib*/ + false, + /*ignoreNoDefaultLib*/ + false, + { kind: 3 /* Import */, file: file.path, index }, + resolution.packageId + ); + } + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; + } + } + } + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + let allFilesBelongToPath = true; + const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (const sourceFile of sourceFiles) { + if (!sourceFile.isDeclarationFile) { + const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.addLazyConfigDiagnostic( + sourceFile, + Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, + sourceFile.fileName, + rootDirectory + ); + allFilesBelongToPath = false; + } + } + } + return allFilesBelongToPath; + } + function parseProjectReferenceConfigFile(ref) { + if (!projectReferenceRedirects) { + projectReferenceRedirects = /* @__PURE__ */ new Map(); + } + const refPath = resolveProjectReferencePath(ref); + const sourceFilePath = toPath3(refPath); + const fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== void 0) { + return fromCache || void 0; + } + let commandLine; + let sourceFile; + if (host.getParsedCommandLine) { + commandLine = host.getParsedCommandLine(refPath); + if (!commandLine) { + addFileToFilesByName( + /*file*/ + void 0, + sourceFilePath, + refPath, + /*redirectedPath*/ + void 0 + ); + projectReferenceRedirects.set(sourceFilePath, false); + return void 0; + } + sourceFile = Debug.checkDefined(commandLine.options.configFile); + Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath); + addFileToFilesByName( + sourceFile, + sourceFilePath, + refPath, + /*redirectedPath*/ + void 0 + ); + } else { + const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), currentDirectory); + sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + addFileToFilesByName( + sourceFile, + sourceFilePath, + refPath, + /*redirectedPath*/ + void 0 + ); + if (sourceFile === void 0) { + projectReferenceRedirects.set(sourceFilePath, false); + return void 0; + } + commandLine = parseJsonSourceFileConfigFileContent( + sourceFile, + configParsingHost, + basePath, + /*existingOptions*/ + void 0, + refPath + ); + } + sourceFile.fileName = refPath; + sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; + const resolvedRef = { commandLine, sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; + } + function verifyCompilerOptions() { + if (options.strictPropertyInitialization && !getStrictOptionValue(options, "strictNullChecks")) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); + } + if (options.exactOptionalPropertyTypes && !getStrictOptionValue(options, "strictNullChecks")) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "exactOptionalPropertyTypes", "strictNullChecks"); + } + if (options.isolatedModules || options.verbatimModuleSyntax) { + if (options.outFile) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", options.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules"); + } + } + if (options.isolatedDeclarations) { + if (getAllowJSCompilerOption(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "isolatedDeclarations"); + } + if (!getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "isolatedDeclarations", "declaration", "composite"); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); + } + if (options.mapRoot) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); + } + } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + if (options.incremental === false) { + createDiagnosticForOptionName(Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration"); + } + } + const outputFile = options.outFile; + if (!options.tsBuildInfoFile && options.incremental && !outputFile && !options.configFilePath) { + programDiagnostics.addConfigDiagnostic(createCompilerDiagnostic(Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); + } + verifyDeprecatedCompilerOptions(); + verifyProjectReferences(); + if (options.composite) { + const rootPaths = new Set(rootNames.map(toPath3)); + for (const file of files) { + if (sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) { + programDiagnostics.addLazyConfigDiagnostic( + file, + Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, + file.fileName, + options.configFilePath || "" + ); + } + } + } + if (options.paths) { + for (const key in options.paths) { + if (!hasProperty(options.paths, key)) { + continue; + } + if (!hasZeroOrOneAsteriskCharacter(key)) { + createDiagnosticForOptionPaths( + /*onKey*/ + true, + key, + Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, + key + ); + } + if (isArray(options.paths[key])) { + const len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths( + /*onKey*/ + false, + key, + Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, + key + ); + } + for (let i = 0; i < len; i++) { + const subst = options.paths[key][i]; + const typeOfSubst = typeof subst; + if (typeOfSubst === "string") { + if (!hasZeroOrOneAsteriskCharacter(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key); + } + if (!options.baseUrl && !pathIsRelative(subst) && !pathIsAbsolute(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, Diagnostics.Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash); + } + } else { + createDiagnosticForOptionPathKeyValue(key, i, Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); + } + } + } else { + createDiagnosticForOptionPaths( + /*onKey*/ + false, + key, + Diagnostics.Substitutions_for_pattern_0_should_be_an_array, + key + ); + } + } + } + if (!options.sourceMap && !options.inlineSourceMap) { + if (options.inlineSources) { + createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); + } + if (options.sourceRoot) { + createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); + } + } + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); + } + if (options.declarationDir) { + if (!getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); + } + if (outputFile) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", "outFile"); + } + } + if (options.declarationMap && !getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); + } + if (options.lib && options.noLib) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); + } + const languageVersion = getEmitScriptTarget(options); + const firstNonAmbientExternalModuleSourceFile = find(files, (f) => isExternalModule(f) && !f.isDeclarationFile); + if (options.isolatedModules || options.verbatimModuleSyntax) { + if (options.module === 0 /* None */ && languageVersion < 2 /* ES2015 */ && options.isolatedModules) { + createDiagnosticForOptionName(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); + } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled, options.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules", "preserveConstEnums"); + } + } else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === 0 /* None */) { + const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, typeof firstNonAmbientExternalModuleSourceFile.externalModuleIndicator === "boolean" ? firstNonAmbientExternalModuleSourceFile : firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.addConfigDiagnostic(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + if (outputFile && !options.emitDeclarationOnly) { + if (options.module && !(options.module === 2 /* AMD */ || options.module === 4 /* System */)) { + createDiagnosticForOptionName(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, "outFile", "module"); + } else if (options.module === void 0 && firstNonAmbientExternalModuleSourceFile) { + const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, typeof firstNonAmbientExternalModuleSourceFile.externalModuleIndicator === "boolean" ? firstNonAmbientExternalModuleSourceFile : firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.addConfigDiagnostic(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, "outFile")); + } + } + if (getResolveJsonModule(options)) { + if (getEmitModuleResolutionKind(options) === 1 /* Classic */) { + createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic, "resolveJsonModule"); + } else if (!hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd, "resolveJsonModule", "module"); + } + } + if (options.outDir || // there is --outDir specified + options.rootDir || // there is --rootDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot || // there is --mapRoot specified + getEmitDeclarations(options) && options.declarationDir) { + const dir = getCommonSourceDirectory2(); + if (options.outDir && dir === "" && files.some((file) => getRootLength(file.fileName) > 1)) { + createDiagnosticForOptionName(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (options.checkJs && !getAllowJSCompilerOption(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"); + } + if (options.emitDeclarationOnly) { + if (!getEmitDeclarations(options)) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); + } + } + if (options.emitDecoratorMetadata && !options.experimentalDecorators) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFactory", inverseJsxOptionMap.get("" + options.jsx)); + } + if (!parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } else if (options.reactNamespace && !isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + if (options.jsxFragmentFactory) { + if (!options.jsxFactory) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "jsxFragmentFactory", "jsxFactory"); + } + if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFragmentFactory", inverseJsxOptionMap.get("" + options.jsx)); + } + if (!parseIsolatedEntityName(options.jsxFragmentFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFragmentFactory", Diagnostics.Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFragmentFactory); + } + } + if (options.reactNamespace) { + if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "reactNamespace", inverseJsxOptionMap.get("" + options.jsx)); + } + } + if (options.jsxImportSource) { + if (options.jsx === 2 /* React */) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxImportSource", inverseJsxOptionMap.get("" + options.jsx)); + } + } + const moduleKind = getEmitModuleKind(options); + if (options.verbatimModuleSyntax) { + if (moduleKind === 2 /* AMD */ || moduleKind === 3 /* UMD */ || moduleKind === 4 /* System */) { + createDiagnosticForOptionName(Diagnostics.Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System, "verbatimModuleSyntax"); + } + } + if (options.allowImportingTsExtensions && !(options.noEmit || options.emitDeclarationOnly || options.rewriteRelativeImportExtensions)) { + createOptionValueDiagnostic("allowImportingTsExtensions", Diagnostics.Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set); + } + const moduleResolution = getEmitModuleResolutionKind(options); + if (options.resolvePackageJsonExports && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { + createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonExports"); + } + if (options.resolvePackageJsonImports && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { + createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonImports"); + } + if (options.customConditions && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { + createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "customConditions"); + } + if (moduleResolution === 100 /* Bundler */ && !emitModuleKindIsNonNodeESM(moduleKind) && moduleKind !== 200 /* Preserve */) { + createOptionValueDiagnostic("moduleResolution", Diagnostics.Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later, "bundler"); + } + if (ModuleKind[moduleKind] && (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) && !(3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */)) { + const moduleKindName = ModuleKind[moduleKind]; + const moduleResolutionName = ModuleResolutionKind[moduleKindName] ? moduleKindName : "Node16"; + createOptionValueDiagnostic("moduleResolution", Diagnostics.Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1, moduleResolutionName, moduleKindName); + } else if (ModuleResolutionKind[moduleResolution] && (3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */) && !(100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */)) { + const moduleResolutionName = ModuleResolutionKind[moduleResolution]; + createOptionValueDiagnostic("module", Diagnostics.Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1, moduleResolutionName, moduleResolutionName); + } + if (!options.noEmit && !options.suppressOutputPathCheck) { + const emitHost = getEmitHost(); + const emitFilesSeen = /* @__PURE__ */ new Set(); + forEachEmittedFile(emitHost, (emitFileNames) => { + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); + } + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); + }); + } + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + const emitFilePath = toPath3(emitFileName); + if (filesByName.has(emitFilePath)) { + let chain; + if (!options.configFilePath) { + chain = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig + ); + } + chain = chainDiagnosticMessages(chain, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, createCompilerDiagnosticFromMessageChain(chain)); + } + const emitFileKey = !host.useCaseSensitiveFileNames() ? toFileNameLowerCase(emitFilePath) : emitFilePath; + if (emitFilesSeen.has(emitFileKey)) { + blockEmittingOfFile(emitFileName, createCompilerDiagnostic(Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } else { + emitFilesSeen.add(emitFileKey); + } + } + } + } + function getIgnoreDeprecationsVersion() { + const ignoreDeprecations = options.ignoreDeprecations; + if (ignoreDeprecations) { + if (ignoreDeprecations === "5.0") { + return new Version(ignoreDeprecations); + } + reportInvalidIgnoreDeprecations(); + } + return Version.zero; + } + function checkDeprecations(deprecatedIn, removedIn, createDiagnostic, fn) { + const deprecatedInVersion = new Version(deprecatedIn); + const removedInVersion = new Version(removedIn); + const typescriptVersion = new Version(typeScriptVersion2 || versionMajorMinor); + const ignoreDeprecationsVersion = getIgnoreDeprecationsVersion(); + const mustBeRemoved = !(removedInVersion.compareTo(typescriptVersion) === 1 /* GreaterThan */); + const canBeSilenced = !mustBeRemoved && ignoreDeprecationsVersion.compareTo(deprecatedInVersion) === -1 /* LessThan */; + if (mustBeRemoved || canBeSilenced) { + fn((name, value, useInstead) => { + if (mustBeRemoved) { + if (value === void 0) { + createDiagnostic(name, value, useInstead, Diagnostics.Option_0_has_been_removed_Please_remove_it_from_your_configuration, name); + } else { + createDiagnostic(name, value, useInstead, Diagnostics.Option_0_1_has_been_removed_Please_remove_it_from_your_configuration, name, value); + } + } else { + if (value === void 0) { + createDiagnostic(name, value, useInstead, Diagnostics.Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprecations_Colon_2_to_silence_this_error, name, removedIn, deprecatedIn); + } else { + createDiagnostic(name, value, useInstead, Diagnostics.Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDeprecations_Colon_3_to_silence_this_error, name, value, removedIn, deprecatedIn); + } + } + }); + } + } + function verifyDeprecatedCompilerOptions() { + function createDiagnostic(name, value, useInstead, message, ...args) { + if (useInstead) { + const details = chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Use_0_instead, + useInstead + ); + const chain = chainDiagnosticMessages(details, message, ...args); + createDiagnosticForOption( + /*onKey*/ + !value, + name, + /*option2*/ + void 0, + chain + ); + } else { + createDiagnosticForOption( + /*onKey*/ + !value, + name, + /*option2*/ + void 0, + message, + ...args + ); + } + } + checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic) => { + if (options.target === 0 /* ES3 */) { + createDeprecatedDiagnostic("target", "ES3"); + } + if (options.noImplicitUseStrict) { + createDeprecatedDiagnostic("noImplicitUseStrict"); + } + if (options.keyofStringsOnly) { + createDeprecatedDiagnostic("keyofStringsOnly"); + } + if (options.suppressExcessPropertyErrors) { + createDeprecatedDiagnostic("suppressExcessPropertyErrors"); + } + if (options.suppressImplicitAnyIndexErrors) { + createDeprecatedDiagnostic("suppressImplicitAnyIndexErrors"); + } + if (options.noStrictGenericChecks) { + createDeprecatedDiagnostic("noStrictGenericChecks"); + } + if (options.charset) { + createDeprecatedDiagnostic("charset"); + } + if (options.out) { + createDeprecatedDiagnostic( + "out", + /*value*/ + void 0, + "outFile" + ); + } + if (options.importsNotUsedAsValues) { + createDeprecatedDiagnostic( + "importsNotUsedAsValues", + /*value*/ + void 0, + "verbatimModuleSyntax" + ); + } + if (options.preserveValueImports) { + createDeprecatedDiagnostic( + "preserveValueImports", + /*value*/ + void 0, + "verbatimModuleSyntax" + ); + } + }); + } + function verifyDeprecatedProjectReference(ref, parentFile, index) { + function createDiagnostic(_name, _value, _useInstead, message, ...args) { + createDiagnosticForReference(parentFile, index, message, ...args); + } + checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic) => { + if (ref.prepend) { + createDeprecatedDiagnostic("prepend"); + } + }); + } + function addFilePreprocessingFileExplainingDiagnostic(file, fileProcessingReason, diagnostic, args) { + programDiagnostics.addFileProcessingDiagnostic({ + kind: 1 /* FilePreprocessingFileExplainingDiagnostic */, + file: file && file.path, + fileProcessingReason, + diagnostic, + args + }); + } + function verifyProjectReferences() { + const buildInfoPath = !options.suppressOutputPathCheck ? getTsBuildInfoEmitOutputFilePath(options) : void 0; + forEachProjectReference( + projectReferences, + resolvedProjectReferences, + (resolvedRef, parent, index) => { + const ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; + const parentFile = parent && parent.sourceFile; + verifyDeprecatedProjectReference(ref, parentFile, index); + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, Diagnostics.File_0_not_found, ref.path); + return; + } + const options2 = resolvedRef.commandLine.options; + if (!options2.composite || options2.noEmit) { + const inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + if (!options2.composite) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + if (options2.noEmit) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path); + } + } + if (!parent && buildInfoPath && buildInfoPath === getTsBuildInfoEmitOutputFilePath(options2)) { + createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path); + hasEmitBlockingDiagnostics.set(toPath3(buildInfoPath), true); + } + } + ); + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, ...args) { + let needCompilerDiagnostic = true; + forEachOptionPathsSyntax((pathProp) => { + if (isObjectLiteralExpression(pathProp.initializer)) { + forEachPropertyAssignment(pathProp.initializer, key, (keyProps) => { + const initializer = keyProps.initializer; + if (isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.addConfigDiagnostic(createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, ...args)); + needCompilerDiagnostic = false; + } + }); + } + }); + if (needCompilerDiagnostic) { + createCompilerOptionsDiagnostic(message, ...args); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, ...args) { + let needCompilerDiagnostic = true; + forEachOptionPathsSyntax((pathProp) => { + if (isObjectLiteralExpression(pathProp.initializer) && createOptionDiagnosticInObjectLiteralSyntax( + pathProp.initializer, + onKey, + key, + /*key2*/ + void 0, + message, + ...args + )) { + needCompilerDiagnostic = false; + } + }); + if (needCompilerDiagnostic) { + createCompilerOptionsDiagnostic(message, ...args); + } + } + function forEachOptionPathsSyntax(callback) { + return forEachOptionsSyntaxByName(getCompilerOptionsObjectLiteralSyntax(), "paths", callback); + } + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption( + /*onKey*/ + true, + option1, + option2, + message, + option1, + option2, + option3 + ); + } + function createOptionValueDiagnostic(option1, message, ...args) { + createDiagnosticForOption( + /*onKey*/ + false, + option1, + /*option2*/ + void 0, + message, + ...args + ); + } + function createDiagnosticForReference(sourceFile, index, message, ...args) { + const referencesSyntax = forEachTsConfigPropArray(sourceFile || options.configFile, "references", (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.addConfigDiagnostic(createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, ...args)); + } else { + programDiagnostics.addConfigDiagnostic(createCompilerDiagnostic(message, ...args)); + } + } + function createDiagnosticForOption(onKey, option1, option2, message, ...args) { + const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + const needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, ...args); + if (needCompilerDiagnostic) { + createCompilerOptionsDiagnostic(message, ...args); + } + } + function createCompilerOptionsDiagnostic(message, ...args) { + const compilerOptionsProperty = getCompilerOptionsPropertySyntax(); + if (compilerOptionsProperty) { + if ("messageText" in message) { + programDiagnostics.addConfigDiagnostic(createDiagnosticForNodeFromMessageChain(options.configFile, compilerOptionsProperty.name, message)); + } else { + programDiagnostics.addConfigDiagnostic(createDiagnosticForNodeInSourceFile(options.configFile, compilerOptionsProperty.name, message, ...args)); + } + } else if ("messageText" in message) { + programDiagnostics.addConfigDiagnostic(createCompilerDiagnosticFromMessageChain(message)); + } else { + programDiagnostics.addConfigDiagnostic(createCompilerDiagnostic(message, ...args)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === void 0) { + const compilerOptionsProperty = getCompilerOptionsPropertySyntax(); + _compilerOptionsObjectLiteralSyntax = compilerOptionsProperty ? tryCast(compilerOptionsProperty.initializer, isObjectLiteralExpression) || false : false; + } + return _compilerOptionsObjectLiteralSyntax || void 0; + } + function getCompilerOptionsPropertySyntax() { + if (_compilerOptionsPropertySyntax === void 0) { + _compilerOptionsPropertySyntax = forEachPropertyAssignment( + getTsConfigObjectLiteralExpression(options.configFile), + "compilerOptions", + identity + ) || false; + } + return _compilerOptionsPropertySyntax || void 0; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, ...args) { + let needsCompilerDiagnostic = false; + forEachPropertyAssignment(objectLiteral, key1, (prop) => { + if ("messageText" in message) { + programDiagnostics.addConfigDiagnostic(createDiagnosticForNodeFromMessageChain(options.configFile, onKey ? prop.name : prop.initializer, message)); + } else { + programDiagnostics.addConfigDiagnostic(createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, ...args)); + } + needsCompilerDiagnostic = true; + }, key2); + return needsCompilerDiagnostic; + } + function blockEmittingOfFile(emitFileName, diag2) { + hasEmitBlockingDiagnostics.set(toPath3(emitFileName), true); + programDiagnostics.addConfigDiagnostic(diag2); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + const filePath = toPath3(file); + if (getSourceFileByPath(filePath)) { + return false; + } + const out = options.outFile; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, removeFileExtension(out) + ".d.ts" /* Dts */); + } + if (options.declarationDir && containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + if (options.outDir) { + return containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (fileExtensionIsOneOf(filePath, supportedJSExtensionsFlat) || isDeclarationFileName(filePath)) { + const filePathWithoutExtension = removeFileExtension(filePath); + return !!getSourceFileByPath(filePathWithoutExtension + ".ts" /* Ts */) || !!getSourceFileByPath(filePathWithoutExtension + ".tsx" /* Tsx */); + } + return false; + } + function isSameFile(file1, file2) { + return comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function getSymlinkCache() { + if (host.getSymlinkCache) { + return host.getSymlinkCache(); + } + if (!symlinks) { + symlinks = createSymlinkCache(currentDirectory, getCanonicalFileName); + } + if (files && !symlinks.hasProcessedResolutions()) { + symlinks.setSymlinksFromResolutions(forEachResolvedModule, forEachResolvedTypeReferenceDirective, automaticTypeDirectiveResolutions); + } + return symlinks; + } + function getModeForUsageLocation2(file, usage) { + return getModeForUsageLocationWorker(file, usage, getCompilerOptionsForFile(file)); + } + function getEmitSyntaxForUsageLocation(file, usage) { + return getEmitSyntaxForUsageLocationWorker(file, usage, getCompilerOptionsForFile(file)); + } + function getModeForResolutionAtIndex(file, index) { + return getModeForUsageLocation2(file, getModuleNameStringLiteralAt(file, index)); + } + function getDefaultResolutionModeForFile2(sourceFile) { + return getDefaultResolutionModeForFileWorker(sourceFile, getCompilerOptionsForFile(sourceFile)); + } + function getImpliedNodeFormatForEmit(sourceFile) { + return getImpliedNodeFormatForEmitWorker(sourceFile, getCompilerOptionsForFile(sourceFile)); + } + function getEmitModuleFormatOfFile(sourceFile) { + return getEmitModuleFormatOfFileWorker(sourceFile, getCompilerOptionsForFile(sourceFile)); + } + function shouldTransformImportCall(sourceFile) { + return shouldTransformImportCallWorker(sourceFile, getCompilerOptionsForFile(sourceFile)); + } + function getModeForTypeReferenceDirectiveInFile(ref, sourceFile) { + return ref.resolutionMode || getDefaultResolutionModeForFile2(sourceFile); + } +} +function shouldTransformImportCallWorker(sourceFile, options) { + const moduleKind = getEmitModuleKind(options); + if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */ || moduleKind === 200 /* Preserve */) { + return false; + } + return getEmitModuleFormatOfFileWorker(sourceFile, options) < 5 /* ES2015 */; +} +function getEmitModuleFormatOfFileWorker(sourceFile, options) { + return getImpliedNodeFormatForEmitWorker(sourceFile, options) ?? getEmitModuleKind(options); +} +function getImpliedNodeFormatForEmitWorker(sourceFile, options) { + var _a, _b; + const moduleKind = getEmitModuleKind(options); + if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { + return sourceFile.impliedNodeFormat; + } + if (sourceFile.impliedNodeFormat === 1 /* CommonJS */ && (((_a = sourceFile.packageJsonScope) == null ? void 0 : _a.contents.packageJsonContent.type) === "commonjs" || fileExtensionIsOneOf(sourceFile.fileName, [".cjs" /* Cjs */, ".cts" /* Cts */]))) { + return 1 /* CommonJS */; + } + if (sourceFile.impliedNodeFormat === 99 /* ESNext */ && (((_b = sourceFile.packageJsonScope) == null ? void 0 : _b.contents.packageJsonContent.type) === "module" || fileExtensionIsOneOf(sourceFile.fileName, [".mjs" /* Mjs */, ".mts" /* Mts */]))) { + return 99 /* ESNext */; + } + return void 0; +} +function getDefaultResolutionModeForFileWorker(sourceFile, options) { + return importSyntaxAffectsModuleResolution(options) ? getImpliedNodeFormatForEmitWorker(sourceFile, options) : void 0; +} +function updateHostForUseSourceOfProjectReferenceRedirect(host) { + let setOfDeclarationDirectories; + const originalFileExists = host.compilerHost.fileExists; + const originalDirectoryExists = host.compilerHost.directoryExists; + const originalGetDirectories = host.compilerHost.getDirectories; + const originalRealpath = host.compilerHost.realpath; + if (!host.useSourceOfProjectReferenceRedirect) return { onProgramCreateComplete: noop, fileExists }; + host.compilerHost.fileExists = fileExists; + let directoryExists; + if (originalDirectoryExists) { + directoryExists = host.compilerHost.directoryExists = (path) => { + if (originalDirectoryExists.call(host.compilerHost, path)) { + handleDirectoryCouldBeSymlink(path); + return true; + } + if (!host.getResolvedProjectReferences()) return false; + if (!setOfDeclarationDirectories) { + setOfDeclarationDirectories = /* @__PURE__ */ new Set(); + host.forEachResolvedProjectReference((ref) => { + const out = ref.commandLine.options.outFile; + if (out) { + setOfDeclarationDirectories.add(getDirectoryPath(host.toPath(out))); + } else { + const declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir; + if (declarationDir) { + setOfDeclarationDirectories.add(host.toPath(declarationDir)); + } + } + }); + } + return fileOrDirectoryExistsUsingSource( + path, + /*isFile*/ + false + ); + }; + } + if (originalGetDirectories) { + host.compilerHost.getDirectories = (path) => !host.getResolvedProjectReferences() || originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path) ? originalGetDirectories.call(host.compilerHost, path) : []; + } + if (originalRealpath) { + host.compilerHost.realpath = (s) => { + var _a; + return ((_a = host.getSymlinkCache().getSymlinkedFiles()) == null ? void 0 : _a.get(host.toPath(s))) || originalRealpath.call(host.compilerHost, s); + }; + } + return { onProgramCreateComplete, fileExists, directoryExists }; + function onProgramCreateComplete() { + host.compilerHost.fileExists = originalFileExists; + host.compilerHost.directoryExists = originalDirectoryExists; + host.compilerHost.getDirectories = originalGetDirectories; + } + function fileExists(file) { + if (originalFileExists.call(host.compilerHost, file)) return true; + if (!host.getResolvedProjectReferences()) return false; + if (!isDeclarationFileName(file)) return false; + return fileOrDirectoryExistsUsingSource( + file, + /*isFile*/ + true + ); + } + function fileExistsIfProjectReferenceDts(file) { + const source = host.getSourceOfProjectReferenceRedirect(host.toPath(file)); + return source !== void 0 ? isString(source) ? originalFileExists.call(host.compilerHost, source) : true : void 0; + } + function directoryExistsIfProjectReferenceDeclDir(dir) { + const dirPath = host.toPath(dir); + const dirPathWithTrailingDirectorySeparator = `${dirPath}${directorySeparator}`; + return forEachKey( + setOfDeclarationDirectories, + (declDirPath) => dirPath === declDirPath || // Any parent directory of declaration dir + startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) || // Any directory inside declaration dir + startsWith(dirPath, `${declDirPath}/`) + ); + } + function handleDirectoryCouldBeSymlink(directory) { + var _a; + if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory)) return; + if (!originalRealpath || !directory.includes(nodeModulesPathPart)) return; + const symlinkCache = host.getSymlinkCache(); + const directoryPath = ensureTrailingDirectorySeparator(host.toPath(directory)); + if ((_a = symlinkCache.getSymlinkedDirectories()) == null ? void 0 : _a.has(directoryPath)) return; + const real = normalizePath(originalRealpath.call(host.compilerHost, directory)); + let realPath2; + if (real === directory || (realPath2 = ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) { + symlinkCache.setSymlinkedDirectory(directoryPath, false); + return; + } + symlinkCache.setSymlinkedDirectory(directory, { + real: ensureTrailingDirectorySeparator(real), + realPath: realPath2 + }); + } + function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) { + var _a; + const fileOrDirectoryExistsUsingSource2 = isFile ? (file) => fileExistsIfProjectReferenceDts(file) : (dir) => directoryExistsIfProjectReferenceDeclDir(dir); + const result = fileOrDirectoryExistsUsingSource2(fileOrDirectory); + if (result !== void 0) return result; + const symlinkCache = host.getSymlinkCache(); + const symlinkedDirectories = symlinkCache.getSymlinkedDirectories(); + if (!symlinkedDirectories) return false; + const fileOrDirectoryPath = host.toPath(fileOrDirectory); + if (!fileOrDirectoryPath.includes(nodeModulesPathPart)) return false; + if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) == null ? void 0 : _a.has(fileOrDirectoryPath))) return true; + return firstDefinedIterator( + symlinkedDirectories.entries(), + ([directoryPath, symlinkedDirectory]) => { + if (!symlinkedDirectory || !startsWith(fileOrDirectoryPath, directoryPath)) return void 0; + const result2 = fileOrDirectoryExistsUsingSource2(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath)); + if (isFile && result2) { + const absolutePath = getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory()); + symlinkCache.setSymlinkedFile( + fileOrDirectoryPath, + `${symlinkedDirectory.real}${absolutePath.replace(new RegExp(directoryPath, "i"), "")}` + ); + } + return result2; + } + ) || false; + } +} +var emitSkippedWithNoDiagnostics = { diagnostics: emptyArray, sourceMaps: void 0, emittedFiles: void 0, emitSkipped: true }; +function handleNoEmitOptions(program, sourceFile, writeFile2, cancellationToken) { + const options = program.getCompilerOptions(); + if (options.noEmit) { + return sourceFile ? emitSkippedWithNoDiagnostics : program.emitBuildInfo(writeFile2, cancellationToken); + } + if (!options.noEmitOnError) return void 0; + let diagnostics = [ + ...program.getOptionsDiagnostics(cancellationToken), + ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), + ...program.getGlobalDiagnostics(cancellationToken), + ...program.getSemanticDiagnostics(sourceFile, cancellationToken) + ]; + if (diagnostics.length === 0 && getEmitDeclarations(program.getCompilerOptions())) { + diagnostics = program.getDeclarationDiagnostics( + /*sourceFile*/ + void 0, + cancellationToken + ); + } + if (!diagnostics.length) return void 0; + let emittedFiles; + if (!sourceFile) { + const emitResult = program.emitBuildInfo(writeFile2, cancellationToken); + if (emitResult.diagnostics) diagnostics = [...diagnostics, ...emitResult.diagnostics]; + emittedFiles = emitResult.emittedFiles; + } + return { diagnostics, sourceMaps: void 0, emittedFiles, emitSkipped: true }; +} +function filterSemanticDiagnostics(diagnostic, option) { + return filter(diagnostic, (d) => !d.skippedOn || !option[d.skippedOn]); +} +function parseConfigHostFromCompilerHostLike(host, directoryStructureHost = host) { + return { + fileExists: (f) => directoryStructureHost.fileExists(f), + readDirectory(root, extensions, excludes, includes, depth) { + Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); + }, + readFile: (f) => directoryStructureHost.readFile(f), + directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: maybeBind(directoryStructureHost, directoryStructureHost.realpath), + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: () => host.getCurrentDirectory(), + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined, + trace: host.trace ? (s) => host.trace(s) : void 0 + }; +} +function resolveProjectReferencePath(ref) { + return resolveConfigFileProjectName(ref.path); +} +function getResolutionDiagnostic(options, { extension }, { isDeclarationFile }) { + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + case ".mts" /* Mts */: + case ".d.mts" /* Dmts */: + case ".cts" /* Cts */: + case ".d.cts" /* Dcts */: + return void 0; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + case ".mjs" /* Mjs */: + case ".cjs" /* Cjs */: + return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); + default: + return needAllowArbitraryExtensions(); + } + function needJsx() { + return options.jsx ? void 0 : Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return getAllowJSCompilerOption(options) || !getStrictOptionValue(options, "noImplicitAny") ? void 0 : Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + function needResolveJsonModule() { + return getResolveJsonModule(options) ? void 0 : Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } + function needAllowArbitraryExtensions() { + return isDeclarationFile || options.allowArbitraryExtensions ? void 0 : Diagnostics.Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set; + } +} +function getModuleNames({ imports, moduleAugmentations }) { + const res = imports.map((i) => i); + for (const aug of moduleAugmentations) { + if (aug.kind === 11 /* StringLiteral */) { + res.push(aug); + } + } + return res; +} +function getModuleNameStringLiteralAt({ imports, moduleAugmentations }, index) { + if (index < imports.length) return imports[index]; + let augIndex = imports.length; + for (const aug of moduleAugmentations) { + if (aug.kind === 11 /* StringLiteral */) { + if (index === augIndex) return aug; + augIndex++; + } + } + Debug.fail("should never ask for module name at index higher than possible module name"); +} + +// src/compiler/programDiagnostics.ts +function createProgramDiagnostics(getCompilerOptionsObjectLiteralSyntax) { + let computedDiagnostics; + let fileReasons = createMultiMap(); + let fileProcessingDiagnostics; + let commonSourceDirectory; + let configDiagnostics; + let lazyConfigDiagnostics; + let fileReasonsToChain; + let reasonToRelatedInfo; + return { + addConfigDiagnostic(diag2) { + Debug.assert(computedDiagnostics === void 0, "Cannot modify program diagnostic state after requesting combined diagnostics"); + (configDiagnostics ?? (configDiagnostics = createDiagnosticCollection())).add(diag2); + }, + addLazyConfigDiagnostic(file, message, ...args) { + Debug.assert(computedDiagnostics === void 0, "Cannot modify program diagnostic state after requesting combined diagnostics"); + (lazyConfigDiagnostics ?? (lazyConfigDiagnostics = [])).push({ file, diagnostic: message, args }); + }, + addFileProcessingDiagnostic(diag2) { + Debug.assert(computedDiagnostics === void 0, "Cannot modify program diagnostic state after requesting combined diagnostics"); + (fileProcessingDiagnostics ?? (fileProcessingDiagnostics = [])).push(diag2); + }, + setCommonSourceDirectory(directory) { + commonSourceDirectory = directory; + }, + reuseStateFromOldProgram(oldProgramDiagnostics, isConfigIdentical) { + fileReasons = oldProgramDiagnostics.getFileReasons(); + fileProcessingDiagnostics = oldProgramDiagnostics.getFileProcessingDiagnostics(); + if (isConfigIdentical) { + commonSourceDirectory = oldProgramDiagnostics.getCommonSourceDirectory(); + configDiagnostics = oldProgramDiagnostics.getConfigDiagnostics(); + lazyConfigDiagnostics = oldProgramDiagnostics.getLazyConfigDiagnostics(); + } + }, + getFileProcessingDiagnostics() { + return fileProcessingDiagnostics; + }, + getFileReasons() { + return fileReasons; + }, + getCommonSourceDirectory() { + return commonSourceDirectory; + }, + getConfigDiagnostics() { + return configDiagnostics; + }, + getLazyConfigDiagnostics() { + return lazyConfigDiagnostics; + }, + getCombinedDiagnostics(program) { + if (computedDiagnostics) { + return computedDiagnostics; + } + computedDiagnostics = createDiagnosticCollection(); + configDiagnostics == null ? void 0 : configDiagnostics.getDiagnostics().forEach((d) => computedDiagnostics.add(d)); + fileProcessingDiagnostics == null ? void 0 : fileProcessingDiagnostics.forEach((diagnostic) => { + switch (diagnostic.kind) { + case 1 /* FilePreprocessingFileExplainingDiagnostic */: + return computedDiagnostics.add( + createDiagnosticExplainingFile( + program, + diagnostic.file && program.getSourceFileByPath(diagnostic.file), + diagnostic.fileProcessingReason, + diagnostic.diagnostic, + diagnostic.args || emptyArray + ) + ); + case 0 /* FilePreprocessingLibReferenceDiagnostic */: + return computedDiagnostics.add(filePreprocessingLibreferenceDiagnostic(program, diagnostic)); + case 2 /* ResolutionDiagnostics */: + return diagnostic.diagnostics.forEach((d) => computedDiagnostics.add(d)); + default: + Debug.assertNever(diagnostic); + } + }); + lazyConfigDiagnostics == null ? void 0 : lazyConfigDiagnostics.forEach( + ({ file, diagnostic, args }) => computedDiagnostics.add( + createDiagnosticExplainingFile( + program, + file, + /*fileProcessingReason*/ + void 0, + diagnostic, + args + ) + ) + ); + fileReasonsToChain = void 0; + reasonToRelatedInfo = void 0; + return computedDiagnostics; + } + }; + function filePreprocessingLibreferenceDiagnostic(program, { reason }) { + const { file, pos, end } = getReferencedFileLocation(program, reason); + const libReference = file.libReferenceDirectives[reason.index]; + const libName = getLibNameFromLibReference(libReference); + const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts"); + const suggestion = getSpellingSuggestion(unqualifiedLibName, libs, identity); + return createFileDiagnostic( + file, + Debug.checkDefined(pos), + Debug.checkDefined(end) - pos, + suggestion ? Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : Diagnostics.Cannot_find_lib_definition_for_0, + libName, + suggestion + ); + } + function createDiagnosticExplainingFile(program, file, fileProcessingReason, diagnostic, args) { + let seenReasons; + let fileIncludeReasons; + let relatedInfo; + let fileIncludeReasonDetails; + let redirectInfo; + let chain; + const reasons = file && fileReasons.get(file.path); + let locationReason = isReferencedFile(fileProcessingReason) ? fileProcessingReason : void 0; + let cachedChain = file && (fileReasonsToChain == null ? void 0 : fileReasonsToChain.get(file.path)); + if (cachedChain) { + if (cachedChain.fileIncludeReasonDetails) { + seenReasons = new Set(reasons); + reasons == null ? void 0 : reasons.forEach(populateRelatedInfo); + } else { + reasons == null ? void 0 : reasons.forEach(processReason); + } + redirectInfo = cachedChain.redirectInfo; + } else { + reasons == null ? void 0 : reasons.forEach(processReason); + redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file, program.getCompilerOptionsForFile(file)); + } + if (fileProcessingReason) processReason(fileProcessingReason); + const processedExtraReason = (seenReasons == null ? void 0 : seenReasons.size) !== (reasons == null ? void 0 : reasons.length); + if (locationReason && (seenReasons == null ? void 0 : seenReasons.size) === 1) seenReasons = void 0; + if (seenReasons && cachedChain) { + if (cachedChain.details && !processedExtraReason) { + chain = chainDiagnosticMessages(cachedChain.details, diagnostic, ...args ?? emptyArray); + } else if (cachedChain.fileIncludeReasonDetails) { + if (!processedExtraReason) { + if (!cachedFileIncludeDetailsHasProcessedExtraReason()) { + fileIncludeReasonDetails = cachedChain.fileIncludeReasonDetails; + } else { + fileIncludeReasons = cachedChain.fileIncludeReasonDetails.next.slice(0, reasons.length); + } + } else { + if (!cachedFileIncludeDetailsHasProcessedExtraReason()) { + fileIncludeReasons = [...cachedChain.fileIncludeReasonDetails.next, fileIncludeReasons[0]]; + } else { + fileIncludeReasons = append(cachedChain.fileIncludeReasonDetails.next.slice(0, reasons.length), fileIncludeReasons[0]); + } + } + } + } + if (!chain) { + if (!fileIncludeReasonDetails) fileIncludeReasonDetails = seenReasons && chainDiagnosticMessages(fileIncludeReasons, Diagnostics.The_file_is_in_the_program_because_Colon); + chain = chainDiagnosticMessages( + redirectInfo ? fileIncludeReasonDetails ? [fileIncludeReasonDetails, ...redirectInfo] : redirectInfo : fileIncludeReasonDetails, + diagnostic, + ...args || emptyArray + ); + } + if (file) { + if (cachedChain) { + if (!cachedChain.fileIncludeReasonDetails || !processedExtraReason && fileIncludeReasonDetails) { + cachedChain.fileIncludeReasonDetails = fileIncludeReasonDetails; + } + } else { + (fileReasonsToChain ?? (fileReasonsToChain = /* @__PURE__ */ new Map())).set(file.path, cachedChain = { fileIncludeReasonDetails, redirectInfo }); + } + if (!cachedChain.details && !processedExtraReason) cachedChain.details = chain.next; + } + const location = locationReason && getReferencedFileLocation(program, locationReason); + return location && isReferenceFileLocation(location) ? createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : createCompilerDiagnosticFromMessageChain(chain, relatedInfo); + function processReason(reason) { + if (seenReasons == null ? void 0 : seenReasons.has(reason)) return; + (seenReasons ?? (seenReasons = /* @__PURE__ */ new Set())).add(reason); + (fileIncludeReasons ?? (fileIncludeReasons = [])).push(fileIncludeReasonToDiagnostics(program, reason)); + populateRelatedInfo(reason); + } + function populateRelatedInfo(reason) { + if (!locationReason && isReferencedFile(reason)) { + locationReason = reason; + } else if (locationReason !== reason) { + relatedInfo = append(relatedInfo, getFileIncludeReasonToRelatedInformation(program, reason)); + } + } + function cachedFileIncludeDetailsHasProcessedExtraReason() { + var _a; + return ((_a = cachedChain.fileIncludeReasonDetails.next) == null ? void 0 : _a.length) !== (reasons == null ? void 0 : reasons.length); + } + } + function getFileIncludeReasonToRelatedInformation(program, reason) { + let relatedInfo = reasonToRelatedInfo == null ? void 0 : reasonToRelatedInfo.get(reason); + if (relatedInfo === void 0) (reasonToRelatedInfo ?? (reasonToRelatedInfo = /* @__PURE__ */ new Map())).set(reason, relatedInfo = fileIncludeReasonToRelatedInformation(program, reason) ?? false); + return relatedInfo || void 0; + } + function fileIncludeReasonToRelatedInformation(program, reason) { + if (isReferencedFile(reason)) { + const referenceLocation = getReferencedFileLocation(program, reason); + let message2; + switch (reason.kind) { + case 3 /* Import */: + message2 = Diagnostics.File_is_included_via_import_here; + break; + case 4 /* ReferenceFile */: + message2 = Diagnostics.File_is_included_via_reference_here; + break; + case 5 /* TypeReferenceDirective */: + message2 = Diagnostics.File_is_included_via_type_library_reference_here; + break; + case 7 /* LibReferenceDirective */: + message2 = Diagnostics.File_is_included_via_library_reference_here; + break; + default: + Debug.assertNever(reason); + } + return isReferenceFileLocation(referenceLocation) ? createFileDiagnostic( + referenceLocation.file, + referenceLocation.pos, + referenceLocation.end - referenceLocation.pos, + message2 + ) : void 0; + } + const currentDirectory = program.getCurrentDirectory(); + const rootNames = program.getRootFileNames(); + const options = program.getCompilerOptions(); + if (!options.configFile) return void 0; + let configFileNode; + let message; + switch (reason.kind) { + case 0 /* RootFile */: + if (!options.configFile.configFileSpecs) return void 0; + const fileName = getNormalizedAbsolutePath(rootNames[reason.index], currentDirectory); + const matchedByFiles = getMatchedFileSpec(program, fileName); + if (matchedByFiles) { + configFileNode = getTsConfigPropArrayElementValue(options.configFile, "files", matchedByFiles); + message = Diagnostics.File_is_matched_by_files_list_specified_here; + break; + } + const matchedByInclude = getMatchedIncludeSpec(program, fileName); + if (!matchedByInclude || !isString(matchedByInclude)) return void 0; + configFileNode = getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); + message = Diagnostics.File_is_matched_by_include_pattern_specified_here; + break; + case 1 /* SourceFromProjectReference */: + case 2 /* OutputFromProjectReference */: + const resolvedProjectReferences = program.getResolvedProjectReferences(); + const projectReferences = program.getProjectReferences(); + const referencedResolvedRef = Debug.checkDefined(resolvedProjectReferences == null ? void 0 : resolvedProjectReferences[reason.index]); + const referenceInfo = forEachProjectReference( + projectReferences, + resolvedProjectReferences, + (resolvedRef, parent, index2) => resolvedRef === referencedResolvedRef ? { sourceFile: (parent == null ? void 0 : parent.sourceFile) || options.configFile, index: index2 } : void 0 + ); + if (!referenceInfo) return void 0; + const { sourceFile, index } = referenceInfo; + const referencesSyntax = forEachTsConfigPropArray(sourceFile, "references", (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); + return referencesSyntax && referencesSyntax.elements.length > index ? createDiagnosticForNodeInSourceFile( + sourceFile, + referencesSyntax.elements[index], + reason.kind === 2 /* OutputFromProjectReference */ ? Diagnostics.File_is_output_from_referenced_project_specified_here : Diagnostics.File_is_source_from_referenced_project_specified_here + ) : void 0; + case 8 /* AutomaticTypeDirectiveFile */: + if (!options.types) return void 0; + configFileNode = getOptionsSyntaxByArrayElementValue(getCompilerOptionsObjectLiteralSyntax(), "types", reason.typeReference); + message = Diagnostics.File_is_entry_point_of_type_library_specified_here; + break; + case 6 /* LibFile */: + if (reason.index !== void 0) { + configFileNode = getOptionsSyntaxByArrayElementValue(getCompilerOptionsObjectLiteralSyntax(), "lib", options.lib[reason.index]); + message = Diagnostics.File_is_library_specified_here; + break; + } + const target = getNameOfScriptTarget(getEmitScriptTarget(options)); + configFileNode = target ? getOptionsSyntaxByValue(getCompilerOptionsObjectLiteralSyntax(), "target", target) : void 0; + message = Diagnostics.File_is_default_library_for_target_specified_here; + break; + default: + Debug.assertNever(reason); + } + return configFileNode && createDiagnosticForNodeInSourceFile( + options.configFile, + configFileNode, + message + ); + } +} + +// src/compiler/builderState.ts +var BuilderState; +((BuilderState2) => { + function createManyToManyPathMap() { + function create2(forward, reverse, deleted) { + const map2 = { + getKeys: (v) => reverse.get(v), + getValues: (k) => forward.get(k), + keys: () => forward.keys(), + size: () => forward.size, + deleteKey: (k) => { + (deleted || (deleted = /* @__PURE__ */ new Set())).add(k); + const set = forward.get(k); + if (!set) { + return false; + } + set.forEach((v) => deleteFromMultimap(reverse, v, k)); + forward.delete(k); + return true; + }, + set: (k, vSet) => { + deleted == null ? void 0 : deleted.delete(k); + const existingVSet = forward.get(k); + forward.set(k, vSet); + existingVSet == null ? void 0 : existingVSet.forEach((v) => { + if (!vSet.has(v)) { + deleteFromMultimap(reverse, v, k); + } + }); + vSet.forEach((v) => { + if (!(existingVSet == null ? void 0 : existingVSet.has(v))) { + addToMultimap(reverse, v, k); + } + }); + return map2; + } + }; + return map2; + } + return create2( + /* @__PURE__ */ new Map(), + /* @__PURE__ */ new Map(), + /*deleted*/ + void 0 + ); + } + BuilderState2.createManyToManyPathMap = createManyToManyPathMap; + function addToMultimap(map2, k, v) { + let set = map2.get(k); + if (!set) { + set = /* @__PURE__ */ new Set(); + map2.set(k, set); + } + set.add(v); + } + function deleteFromMultimap(map2, k, v) { + const set = map2.get(k); + if (set == null ? void 0 : set.delete(v)) { + if (!set.size) { + map2.delete(k); + } + return true; + } + return false; + } + function getReferencedFilesFromImportedModuleSymbol(symbol) { + return mapDefined(symbol.declarations, (declaration) => { + var _a; + return (_a = getSourceFileOfNode(declaration)) == null ? void 0 : _a.resolvedPath; + }); + } + function getReferencedFilesFromImportLiteral(checker, importName) { + const symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFilesFromImportedModuleSymbol(symbol); + } + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + let referencedFiles; + if (sourceFile.imports && sourceFile.imports.length > 0) { + const checker = program.getTypeChecker(); + for (const importName of sourceFile.imports) { + const declarationSourceFilePaths = getReferencedFilesFromImportLiteral(checker, importName); + declarationSourceFilePaths == null ? void 0 : declarationSourceFilePaths.forEach(addReferencedFile); + } + } + const sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (const referencedFile of sourceFile.referencedFiles) { + const referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + program.forEachResolvedTypeReferenceDirective(({ resolvedTypeReferenceDirective }) => { + if (!resolvedTypeReferenceDirective) { + return; + } + const fileName = resolvedTypeReferenceDirective.resolvedFileName; + const typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }, sourceFile); + if (sourceFile.moduleAugmentations.length) { + const checker = program.getTypeChecker(); + for (const moduleName of sourceFile.moduleAugmentations) { + if (!isStringLiteral(moduleName)) continue; + const symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) continue; + addReferenceFromAmbientModule(symbol); + } + } + for (const ambientModule of program.getTypeChecker().getAmbientModules()) { + if (ambientModule.declarations && ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + if (!symbol.declarations) { + return; + } + for (const declaration of symbol.declarations) { + const declarationSourceFile = getSourceFileOfNode(declaration); + if (declarationSourceFile && declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath) { + (referencedFiles || (referencedFiles = /* @__PURE__ */ new Set())).add(referencedPath); + } + } + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState2.canReuseOldState = canReuseOldState; + function createReferencedMap(options) { + return options.module !== 0 /* None */ && !options.outFile ? createManyToManyPathMap() : void 0; + } + BuilderState2.createReferencedMap = createReferencedMap; + function create(newProgram, oldState, disableUseFileVersionAsSignature) { + var _a, _b; + const fileInfos = /* @__PURE__ */ new Map(); + const options = newProgram.getCompilerOptions(); + const referencedMap = createReferencedMap(options); + const useOldState = canReuseOldState(referencedMap, oldState); + newProgram.getTypeChecker(); + for (const sourceFile of newProgram.getSourceFiles()) { + const version2 = Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); + const oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) == null ? void 0 : _a.get(sourceFile.resolvedPath) : void 0; + const signature = oldUncommittedSignature === void 0 ? useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) == null ? void 0 : _b.signature : void 0 : oldUncommittedSignature || void 0; + if (referencedMap) { + const newReferences = getReferencedFiles(newProgram, sourceFile, newProgram.getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.resolvedPath, newReferences); + } + } + fileInfos.set(sourceFile.resolvedPath, { + version: version2, + signature, + // No need to calculate affectsGlobalScope with --out since its not used at all + affectsGlobalScope: !options.outFile ? isFileAffectingGlobalScope(sourceFile) || void 0 : void 0, + impliedFormat: sourceFile.impliedNodeFormat + }); + } + return { + fileInfos, + referencedMap, + useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState + }; + } + BuilderState2.create = create; + function releaseCache2(state) { + state.allFilesExcludingDefaultLibraryFile = void 0; + state.allFileNames = void 0; + } + BuilderState2.releaseCache = releaseCache2; + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, host) { + var _a; + const result = getFilesAffectedByWithOldState( + state, + programOfThisState, + path, + cancellationToken, + host + ); + (_a = state.oldSignatures) == null ? void 0 : _a.clear(); + return result; + } + BuilderState2.getFilesAffectedBy = getFilesAffectedBy; + function getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, host) { + const sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, host)) { + return [sourceFile]; + } + return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, host); + } + BuilderState2.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState; + function updateSignatureOfFile(state, signature, path) { + state.fileInfos.get(path).signature = signature; + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */ new Set())).add(path); + } + BuilderState2.updateSignatureOfFile = updateSignatureOfFile; + function computeDtsSignature(programOfThisState, sourceFile, cancellationToken, host, onNewSignature) { + programOfThisState.emit( + sourceFile, + (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) => { + Debug.assert(isDeclarationFileName(fileName), `File extension for signature expected to be dts: Got:: ${fileName}`); + onNewSignature( + computeSignatureWithDiagnostics( + programOfThisState, + sourceFile, + text, + host, + data + ), + sourceFiles + ); + }, + cancellationToken, + 2 /* BuilderSignature */, + /*customTransformers*/ + void 0, + /*forceDtsEmit*/ + true + ); + } + BuilderState2.computeDtsSignature = computeDtsSignature; + function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, host, useFileVersionAsSignature = state.useFileVersionAsSignature) { + var _a; + if ((_a = state.hasCalledUpdateShapeSignature) == null ? void 0 : _a.has(sourceFile.resolvedPath)) return false; + const info = state.fileInfos.get(sourceFile.resolvedPath); + const prevSignature = info.signature; + let latestSignature; + if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { + computeDtsSignature(programOfThisState, sourceFile, cancellationToken, host, (signature) => { + latestSignature = signature; + if (host.storeSignatureInfo) (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 0 /* ComputedDts */); + }); + } + if (latestSignature === void 0) { + latestSignature = sourceFile.version; + if (host.storeSignatureInfo) (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 2 /* UsedVersion */); + } + (state.oldSignatures || (state.oldSignatures = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, prevSignature || false); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */ new Set())).add(sourceFile.resolvedPath); + info.signature = latestSignature; + return latestSignature !== prevSignature; + } + BuilderState2.updateShapeSignature = updateShapeSignature; + function getAllDependencies(state, programOfThisState, sourceFile) { + const compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions.outFile) { + return getAllFileNames(state, programOfThisState); + } + if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { + return getAllFileNames(state, programOfThisState); + } + const seenMap = /* @__PURE__ */ new Set(); + const queue = [sourceFile.resolvedPath]; + while (queue.length) { + const path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.add(path); + const references = state.referencedMap.getValues(path); + if (references) { + for (const key of references.keys()) { + queue.push(key); + } + } + } + } + return arrayFrom(mapDefinedIterator(seenMap.keys(), (path) => { + var _a; + return ((_a = programOfThisState.getSourceFileByPath(path)) == null ? void 0 : _a.fileName) ?? path; + })); + } + BuilderState2.getAllDependencies = getAllDependencies; + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + const sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === emptyArray ? emptyArray : sourceFiles.map((file) => file.fileName); + } + return state.allFileNames; + } + function getReferencedByPaths(state, referencedFilePath) { + const keys = state.referencedMap.getKeys(referencedFilePath); + return keys ? arrayFrom(keys.keys()) : []; + } + BuilderState2.getReferencedByPaths = getReferencedByPaths; + function containsOnlyAmbientModules(sourceFile) { + for (const statement of sourceFile.statements) { + if (!isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + function containsGlobalScopeAugmentation(sourceFile) { + return some(sourceFile.moduleAugmentations, (augmentation) => isGlobalScopeAugmentation(augmentation.parent)); + } + function isFileAffectingGlobalScope(sourceFile) { + return containsGlobalScopeAugmentation(sourceFile) || !isExternalOrCommonJsModule(sourceFile) && !isJsonSourceFile(sourceFile) && !containsOnlyAmbientModules(sourceFile); + } + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + let result; + if (firstSourceFile) addSourceFile(firstSourceFile); + for (const sourceFile of programOfThisState.getSourceFiles()) { + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + BuilderState2.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile; + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + const compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && compilerOptions.outFile) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cancellationToken, host) { + if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + const compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (getIsolatedModules(compilerOptions) || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + const seenFileNamesMap = /* @__PURE__ */ new Map(); + seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape); + const queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath); + while (queue.length > 0) { + const currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + const currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, host)) { + queue.push(...getReferencedByPaths(state, currentSourceFile.resolvedPath)); + } + } + } + return arrayFrom(mapDefinedIterator(seenFileNamesMap.values(), (value) => value)); + } +})(BuilderState || (BuilderState = {})); + +// src/compiler/builder.ts +function isBuilderProgramStateWithDefinedProgram(state) { + return state.program !== void 0; +} +function toBuilderProgramStateWithDefinedProgram(state) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + return state; +} +function getBuilderFileEmit(options) { + let result = 1 /* Js */; + if (options.sourceMap) result = result | 2 /* JsMap */; + if (options.inlineSourceMap) result = result | 4 /* JsInlineMap */; + if (getEmitDeclarations(options)) result = result | 24 /* Dts */; + if (options.declarationMap) result = result | 32 /* DtsMap */; + if (options.emitDeclarationOnly) result = result & 56 /* AllDts */; + return result; +} +function getPendingEmitKind(optionsOrEmitKind, oldOptionsOrEmitKind) { + const oldEmitKind = oldOptionsOrEmitKind && (isNumber(oldOptionsOrEmitKind) ? oldOptionsOrEmitKind : getBuilderFileEmit(oldOptionsOrEmitKind)); + const emitKind = isNumber(optionsOrEmitKind) ? optionsOrEmitKind : getBuilderFileEmit(optionsOrEmitKind); + if (oldEmitKind === emitKind) return 0 /* None */; + if (!oldEmitKind || !emitKind) return emitKind; + const diff = oldEmitKind ^ emitKind; + let result = 0 /* None */; + if (diff & 7 /* AllJs */) result = emitKind & 7 /* AllJs */; + if (diff & 8 /* DtsErrors */) result = result | emitKind & 8 /* DtsErrors */; + if (diff & 48 /* AllDtsEmit */) result = result | emitKind & 48 /* AllDtsEmit */; + return result; +} +function hasSameKeys(map1, map2) { + return map1 === map2 || map1 !== void 0 && map2 !== void 0 && map1.size === map2.size && !forEachKey(map1, (key) => !map2.has(key)); +} +function createBuilderProgramState(newProgram, oldState) { + var _a, _b; + const state = BuilderState.create( + newProgram, + oldState, + /*disableUseFileVersionAsSignature*/ + false + ); + state.program = newProgram; + const compilerOptions = newProgram.getCompilerOptions(); + state.compilerOptions = compilerOptions; + const outFilePath = compilerOptions.outFile; + state.semanticDiagnosticsPerFile = /* @__PURE__ */ new Map(); + if (outFilePath && compilerOptions.composite && (oldState == null ? void 0 : oldState.outSignature) && outFilePath === oldState.compilerOptions.outFile) { + state.outSignature = oldState.outSignature && getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldState.outSignature); + } + state.changedFilesSet = /* @__PURE__ */ new Set(); + state.latestChangedDtsFile = compilerOptions.composite ? oldState == null ? void 0 : oldState.latestChangedDtsFile : void 0; + state.checkPending = state.compilerOptions.noCheck ? true : void 0; + const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState); + const oldCompilerOptions = useOldState ? oldState.compilerOptions : void 0; + let canCopySemanticDiagnostics = useOldState && !compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + const canCopyEmitSignatures = compilerOptions.composite && (oldState == null ? void 0 : oldState.emitSignatures) && !outFilePath && !compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); + let canCopyEmitDiagnostics = true; + if (useOldState) { + (_a = oldState.changedFilesSet) == null ? void 0 : _a.forEach((value) => state.changedFilesSet.add(value)); + if (!outFilePath && ((_b = oldState.affectedFilesPendingEmit) == null ? void 0 : _b.size)) { + state.affectedFilesPendingEmit = new Map(oldState.affectedFilesPendingEmit); + state.seenAffectedFiles = /* @__PURE__ */ new Set(); + } + state.programEmitPending = oldState.programEmitPending; + if (outFilePath && state.changedFilesSet.size) { + canCopySemanticDiagnostics = false; + canCopyEmitDiagnostics = false; + } + state.hasErrorsFromOldState = oldState.hasErrors; + } else { + state.buildInfoEmitPending = isIncrementalCompilation(compilerOptions); + } + const referencedMap = state.referencedMap; + const oldReferencedMap = useOldState ? oldState.referencedMap : void 0; + const copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck; + const copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck; + state.fileInfos.forEach((info, sourceFilePath) => { + var _a2; + let oldInfo; + let newReferences; + if (!useOldState || // File wasn't present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || // versions dont match + oldInfo.version !== info.version || // Implied formats dont match + oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program + newReferences && forEachKey(newReferences, (path) => !state.fileInfos.has(path) && oldState.fileInfos.has(path))) { + addFileToChangeSet(sourceFilePath); + } else { + const sourceFile = newProgram.getSourceFileByPath(sourceFilePath); + const emitDiagnostics = canCopyEmitDiagnostics ? (_a2 = oldState.emitDiagnosticsPerFile) == null ? void 0 : _a2.get(sourceFilePath) : void 0; + if (emitDiagnostics) { + (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set( + sourceFilePath, + oldState.hasReusableDiagnostic ? convertToDiagnostics(emitDiagnostics, sourceFilePath, newProgram) : repopulateDiagnostics(emitDiagnostics, newProgram) + ); + } + if (canCopySemanticDiagnostics) { + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) return; + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) return; + const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set( + sourceFilePath, + oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, sourceFilePath, newProgram) : repopulateDiagnostics(diagnostics, newProgram) + ); + (state.semanticDiagnosticsFromOldState ?? (state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set())).add(sourceFilePath); + } + } + } + if (canCopyEmitSignatures) { + const oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); + if (oldEmitSignature) { + (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(sourceFilePath, getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldEmitSignature)); + } + } + }); + if (useOldState && forEachEntry(oldState.fileInfos, (info, sourceFilePath) => { + if (state.fileInfos.has(sourceFilePath)) return false; + if (info.affectsGlobalScope) return true; + state.buildInfoEmitPending = true; + return !!outFilePath; + })) { + BuilderState.getAllFilesExcludingDefaultLibraryFile( + state, + newProgram, + /*firstSourceFile*/ + void 0 + ).forEach((file) => addFileToChangeSet(file.resolvedPath)); + } else if (oldCompilerOptions) { + const pendingEmitKind = compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions) ? getBuilderFileEmit(compilerOptions) : getPendingEmitKind(compilerOptions, oldCompilerOptions); + if (pendingEmitKind !== 0 /* None */) { + if (!outFilePath) { + newProgram.getSourceFiles().forEach((f) => { + if (!state.changedFilesSet.has(f.resolvedPath)) { + addToAffectedFilesPendingEmit( + state, + f.resolvedPath, + pendingEmitKind + ); + } + }); + Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); + state.seenAffectedFiles = state.seenAffectedFiles || /* @__PURE__ */ new Set(); + } else if (!state.changedFilesSet.size) { + state.programEmitPending = state.programEmitPending ? state.programEmitPending | pendingEmitKind : pendingEmitKind; + } + state.buildInfoEmitPending = true; + } + } + if (useOldState && state.semanticDiagnosticsPerFile.size !== state.fileInfos.size && oldState.checkPending !== state.checkPending) state.buildInfoEmitPending = true; + return state; + function addFileToChangeSet(path) { + state.changedFilesSet.add(path); + if (outFilePath) { + canCopySemanticDiagnostics = false; + canCopyEmitDiagnostics = false; + state.semanticDiagnosticsFromOldState = void 0; + state.semanticDiagnosticsPerFile.clear(); + state.emitDiagnosticsPerFile = void 0; + } + state.buildInfoEmitPending = true; + state.programEmitPending = void 0; + } +} +function getEmitSignatureFromOldSignature(options, oldOptions, oldEmitSignature) { + return !!options.declarationMap === !!oldOptions.declarationMap ? ( + // Use same format of signature + oldEmitSignature + ) : ( + // Convert to different format + isString(oldEmitSignature) ? [oldEmitSignature] : oldEmitSignature[0] + ); +} +function repopulateDiagnostics(diagnostics, newProgram) { + if (!diagnostics.length) return diagnostics; + return sameMap(diagnostics, (diag2) => { + if (isString(diag2.messageText)) return diag2; + const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain) => { + var _a; + return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain); + }); + return repopulatedChain === diag2.messageText ? diag2 : { ...diag2, messageText: repopulatedChain }; + }); +} +function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo) { + const info = repopulateInfo(chain); + if (info === true) { + return { + ...createModeMismatchDetails(sourceFile), + next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo) + }; + } else if (info) { + return { + ...createModuleNotFoundChain(sourceFile, newProgram, info.moduleReference, info.mode, info.packageName || info.moduleReference), + next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo) + }; + } + const next = convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo); + return next === chain.next ? chain : { ...chain, next }; +} +function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) { + return sameMap(array, (chain) => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); +} +function convertToDiagnostics(diagnostics, diagnosticFilePath, newProgram) { + if (!diagnostics.length) return emptyArray; + let buildInfoDirectory; + return diagnostics.map((diagnostic) => { + const result = convertToDiagnosticRelatedInformation(diagnostic, diagnosticFilePath, newProgram, toPathInBuildInfoDirectory); + result.reportsUnnecessary = diagnostic.reportsUnnecessary; + result.reportsDeprecated = diagnostic.reportDeprecated; + result.source = diagnostic.source; + result.skippedOn = diagnostic.skippedOn; + const { relatedInformation } = diagnostic; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToDiagnosticRelatedInformation(r, diagnosticFilePath, newProgram, toPathInBuildInfoDirectory)) : [] : void 0; + return result; + }); + function toPathInBuildInfoDirectory(path) { + buildInfoDirectory ?? (buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()))); + return toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName); + } +} +function convertToDiagnosticRelatedInformation(diagnostic, diagnosticFilePath, newProgram, toPath3) { + const { file } = diagnostic; + const sourceFile = file !== false ? newProgram.getSourceFileByPath(file ? toPath3(file) : diagnosticFilePath) : void 0; + return { + ...diagnostic, + file: sourceFile, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, (chain) => chain.info) + }; +} +function releaseCache(state) { + BuilderState.releaseCache(state); + state.program = void 0; +} +function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath)); +} +function getNextAffectedFile(state, cancellationToken, host) { + var _a; + while (true) { + const { affectedFiles } = state; + if (affectedFiles) { + const seenAffectedFiles = state.seenAffectedFiles; + let affectedFilesIndex = state.affectedFilesIndex; + while (affectedFilesIndex < affectedFiles.length) { + const affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { + state.affectedFilesIndex = affectedFilesIndex; + addToAffectedFilesPendingEmit( + state, + affectedFile.resolvedPath, + getBuilderFileEmit(state.compilerOptions) + ); + handleDtsMayChangeOfAffectedFile( + state, + affectedFile, + cancellationToken, + host + ); + return affectedFile; + } + affectedFilesIndex++; + } + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = void 0; + (_a = state.oldSignatures) == null ? void 0 : _a.clear(); + state.affectedFiles = void 0; + } + const nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + return void 0; + } + const compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile) return state.program; + state.affectedFiles = BuilderState.getFilesAffectedByWithOldState( + state, + state.program, + nextKey.value, + cancellationToken, + host + ); + state.currentChangedFilePath = nextKey.value; + state.affectedFilesIndex = 0; + if (!state.seenAffectedFiles) state.seenAffectedFiles = /* @__PURE__ */ new Set(); + } +} +function clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles, isForDtsErrors) { + var _a, _b; + if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size) && !state.programEmitPending) return; + if (!emitOnlyDtsFiles && !isForDtsErrors) { + state.affectedFilesPendingEmit = void 0; + state.programEmitPending = void 0; + } + (_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.forEach((emitKind, path) => { + const pending = !isForDtsErrors ? emitKind & 7 /* AllJs */ : emitKind & (7 /* AllJs */ | 48 /* AllDtsEmit */); + if (!pending) state.affectedFilesPendingEmit.delete(path); + else state.affectedFilesPendingEmit.set(path, pending); + }); + if (state.programEmitPending) { + const pending = !isForDtsErrors ? state.programEmitPending & 7 /* AllJs */ : state.programEmitPending & (7 /* AllJs */ | 48 /* AllDtsEmit */); + if (!pending) state.programEmitPending = void 0; + else state.programEmitPending = pending; + } +} +function getPendingEmitKindWithSeen(optionsOrEmitKind, seenOldOptionsOrEmitKind, emitOnlyDtsFiles, isForDtsErrors) { + let pendingKind = getPendingEmitKind(optionsOrEmitKind, seenOldOptionsOrEmitKind); + if (emitOnlyDtsFiles) pendingKind = pendingKind & 56 /* AllDts */; + if (isForDtsErrors) pendingKind = pendingKind & 8 /* DtsErrors */; + return pendingKind; +} +function getBuilderFileEmitAllDts(isForDtsErrors) { + return !isForDtsErrors ? 56 /* AllDts */ : 8 /* DtsErrors */; +} +function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles, isForDtsErrors) { + var _a; + if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) return void 0; + return forEachEntry(state.affectedFilesPendingEmit, (emitKind, path) => { + var _a2; + const affectedFile = state.program.getSourceFileByPath(path); + if (!affectedFile || !sourceFileMayBeEmitted(affectedFile, state.program)) { + state.affectedFilesPendingEmit.delete(path); + return void 0; + } + const seenKind = (_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath); + const pendingKind = getPendingEmitKindWithSeen( + emitKind, + seenKind, + emitOnlyDtsFiles, + isForDtsErrors + ); + if (pendingKind) return { affectedFile, emitKind: pendingKind }; + }); +} +function getNextPendingEmitDiagnosticsFile(state, isForDtsErrors) { + var _a; + if (!((_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.size)) return void 0; + return forEachEntry(state.emitDiagnosticsPerFile, (diagnostics, path) => { + var _a2; + const affectedFile = state.program.getSourceFileByPath(path); + if (!affectedFile || !sourceFileMayBeEmitted(affectedFile, state.program)) { + state.emitDiagnosticsPerFile.delete(path); + return void 0; + } + const seenKind = ((_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath)) || 0 /* None */; + if (!(seenKind & getBuilderFileEmitAllDts(isForDtsErrors))) return { affectedFile, diagnostics, seenKind }; + }); +} +function removeDiagnosticsOfLibraryFiles(state) { + if (!state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + const options = state.program.getCompilerOptions(); + forEach(state.program.getSourceFiles(), (f) => state.program.isSourceFileDefaultLibrary(f) && !skipTypeCheckingIgnoringNoCheck(f, options, state.program) && removeSemanticDiagnosticsOf(state, f.resolvedPath)); + } +} +function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, host) { + removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { + removeDiagnosticsOfLibraryFiles(state); + BuilderState.updateShapeSignature( + state, + state.program, + affectedFile, + cancellationToken, + host + ); + return; + } + if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; + handleDtsMayChangeOfReferencingExportOfAffectedFile( + state, + affectedFile, + cancellationToken, + host + ); +} +function handleDtsMayChangeOf(state, path, invalidateJsFiles, cancellationToken, host) { + removeSemanticDiagnosticsOf(state, path); + if (!state.changedFilesSet.has(path)) { + const sourceFile = state.program.getSourceFileByPath(path); + if (sourceFile) { + BuilderState.updateShapeSignature( + state, + state.program, + sourceFile, + cancellationToken, + host, + /*useFileVersionAsSignature*/ + true + ); + if (invalidateJsFiles) { + addToAffectedFilesPendingEmit( + state, + path, + getBuilderFileEmit(state.compilerOptions) + ); + } else if (getEmitDeclarations(state.compilerOptions)) { + addToAffectedFilesPendingEmit( + state, + path, + state.compilerOptions.declarationMap ? 56 /* AllDts */ : 24 /* Dts */ + ); + } + } + } +} +function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return true; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; +} +function isChangedSignature(state, path) { + const oldSignature = Debug.checkDefined(state.oldSignatures).get(path) || void 0; + const newSignature = Debug.checkDefined(state.fileInfos.get(path)).signature; + return newSignature !== oldSignature; +} +function handleDtsMayChangeOfGlobalScope(state, filePath, invalidateJsFiles, cancellationToken, host) { + var _a; + if (!((_a = state.fileInfos.get(filePath)) == null ? void 0 : _a.affectsGlobalScope)) return false; + BuilderState.getAllFilesExcludingDefaultLibraryFile( + state, + state.program, + /*firstSourceFile*/ + void 0 + ).forEach( + (file) => handleDtsMayChangeOf( + state, + file.resolvedPath, + invalidateJsFiles, + cancellationToken, + host + ) + ); + removeDiagnosticsOfLibraryFiles(state); + return true; +} +function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, host) { + var _a, _b; + if (!state.referencedMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) return; + if (!isChangedSignature(state, affectedFile.resolvedPath)) return; + if (getIsolatedModules(state.compilerOptions)) { + const seenFileNamesMap = /* @__PURE__ */ new Map(); + seenFileNamesMap.set(affectedFile.resolvedPath, true); + const queue = BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath); + while (queue.length > 0) { + const currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + seenFileNamesMap.set(currentPath, true); + if (handleDtsMayChangeOfGlobalScope( + state, + currentPath, + /*invalidateJsFiles*/ + false, + cancellationToken, + host + )) return; + handleDtsMayChangeOf( + state, + currentPath, + /*invalidateJsFiles*/ + false, + cancellationToken, + host + ); + if (isChangedSignature(state, currentPath)) { + const currentSourceFile = state.program.getSourceFileByPath(currentPath); + queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); + } + } + } + } + const seenFileAndExportsOfFile = /* @__PURE__ */ new Set(); + const invalidateJsFiles = !!((_a = affectedFile.symbol) == null ? void 0 : _a.exports) && !!forEachEntry( + affectedFile.symbol.exports, + (exported) => { + if ((exported.flags & 128 /* ConstEnum */) !== 0) return true; + const aliased = skipAlias(exported, state.program.getTypeChecker()); + if (aliased === exported) return false; + return (aliased.flags & 128 /* ConstEnum */) !== 0 && some(aliased.declarations, (d) => getSourceFileOfNode(d) === affectedFile); + } + ); + (_b = state.referencedMap.getKeys(affectedFile.resolvedPath)) == null ? void 0 : _b.forEach((exportedFromPath) => { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, invalidateJsFiles, cancellationToken, host)) return true; + const references = state.referencedMap.getKeys(exportedFromPath); + return references && forEachKey(references, (filePath) => handleDtsMayChangeOfFileAndExportsOfFile( + state, + filePath, + invalidateJsFiles, + seenFileAndExportsOfFile, + cancellationToken, + host + )); + }); +} +function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, invalidateJsFiles, seenFileAndExportsOfFile, cancellationToken, host) { + var _a; + if (!tryAddToSet(seenFileAndExportsOfFile, filePath)) return void 0; + if (handleDtsMayChangeOfGlobalScope(state, filePath, invalidateJsFiles, cancellationToken, host)) return true; + handleDtsMayChangeOf(state, filePath, invalidateJsFiles, cancellationToken, host); + (_a = state.referencedMap.getKeys(filePath)) == null ? void 0 : _a.forEach( + (referencingFilePath) => handleDtsMayChangeOfFileAndExportsOfFile( + state, + referencingFilePath, + invalidateJsFiles, + seenFileAndExportsOfFile, + cancellationToken, + host + ) + ); + return void 0; +} +function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken, semanticDiagnosticsPerFile) { + if (state.compilerOptions.noCheck) return emptyArray; + return concatenate( + getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken, semanticDiagnosticsPerFile), + state.program.getProgramDiagnostics(sourceFile) + ); +} +function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken, semanticDiagnosticsPerFile) { + semanticDiagnosticsPerFile ?? (semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile); + const path = sourceFile.resolvedPath; + const cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return filterSemanticDiagnostics(cachedDiagnostics, state.compilerOptions); + } + const diagnostics = state.program.getBindAndCheckDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + state.buildInfoEmitPending = true; + return filterSemanticDiagnostics(diagnostics, state.compilerOptions); +} +function isIncrementalBundleEmitBuildInfo(info) { + var _a; + return !!((_a = info.options) == null ? void 0 : _a.outFile); +} +function isIncrementalBuildInfo(info) { + return !!info.fileNames; +} +function isNonIncrementalBuildInfo(info) { + return !isIncrementalBuildInfo(info) && !!info.root; +} +function ensureHasErrorsForState(state) { + if (state.hasErrors !== void 0) return; + if (isIncrementalCompilation(state.compilerOptions)) { + state.hasErrors = !some(state.program.getSourceFiles(), (f) => { + var _a, _b; + const bindAndCheckDiagnostics = state.semanticDiagnosticsPerFile.get(f.resolvedPath); + return bindAndCheckDiagnostics === void 0 || // Missing semantic diagnostics in cache will be encoded in buildInfo + !!bindAndCheckDiagnostics.length || // cached semantic diagnostics will be encoded in buildInfo + !!((_b = (_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.get(f.resolvedPath)) == null ? void 0 : _b.length); + }) && (hasSyntaxOrGlobalErrors(state) || some(state.program.getSourceFiles(), (f) => !!state.program.getProgramDiagnostics(f).length)); + } else { + state.hasErrors = some(state.program.getSourceFiles(), (f) => { + var _a, _b; + const bindAndCheckDiagnostics = state.semanticDiagnosticsPerFile.get(f.resolvedPath); + return !!(bindAndCheckDiagnostics == null ? void 0 : bindAndCheckDiagnostics.length) || // If has semantic diagnostics + !!((_b = (_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.get(f.resolvedPath)) == null ? void 0 : _b.length); + }) || hasSyntaxOrGlobalErrors(state); + } +} +function hasSyntaxOrGlobalErrors(state) { + return !!state.program.getConfigFileParsingDiagnostics().length || !!state.program.getSyntacticDiagnostics().length || !!state.program.getOptionsDiagnostics().length || !!state.program.getGlobalDiagnostics().length; +} +function getBuildInfoEmitPending(state) { + ensureHasErrorsForState(state); + return state.buildInfoEmitPending ?? (state.buildInfoEmitPending = !!state.hasErrorsFromOldState !== !!state.hasErrors); +} +function getBuildInfo2(state) { + var _a, _b; + const currentDirectory = state.program.getCurrentDirectory(); + const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); + const latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : void 0; + const fileNames = []; + const fileNameToFileId = /* @__PURE__ */ new Map(); + const rootFileNames = new Set(state.program.getRootFileNames().map((f) => toPath(f, currentDirectory, state.program.getCanonicalFileName))); + ensureHasErrorsForState(state); + if (!isIncrementalCompilation(state.compilerOptions)) { + const buildInfo2 = { + root: arrayFrom(rootFileNames, (r) => relativeToBuildInfo(r)), + errors: state.hasErrors ? true : void 0, + checkPending: state.checkPending, + version + }; + return buildInfo2; + } + const root = []; + if (state.compilerOptions.outFile) { + const fileInfos2 = arrayFrom(state.fileInfos.entries(), ([key, value]) => { + const fileId = toFileId(key); + tryAddRoot(key, fileId); + return value.impliedFormat ? { version: value.version, impliedFormat: value.impliedFormat, signature: void 0, affectsGlobalScope: void 0 } : value.version; + }); + const buildInfo2 = { + fileNames, + fileInfos: fileInfos2, + root, + resolvedRoot: toResolvedRoot(), + options: toIncrementalBuildInfoCompilerOptions(state.compilerOptions), + semanticDiagnosticsPerFile: !state.changedFilesSet.size ? toIncrementalBuildInfoDiagnostics() : void 0, + emitDiagnosticsPerFile: toIncrementalBuildInfoEmitDiagnostics(), + changeFileSet: toChangeFileSet(), + outSignature: state.outSignature, + latestChangedDtsFile, + pendingEmit: !state.programEmitPending ? void 0 : ( + // Pending is undefined or None is encoded as undefined + state.programEmitPending === getBuilderFileEmit(state.compilerOptions) ? false : ( + // Pending emit is same as deteremined by compilerOptions + state.programEmitPending + ) + ), + // Actual value + errors: state.hasErrors ? true : void 0, + checkPending: state.checkPending, + version + }; + return buildInfo2; + } + let fileIdsList; + let fileNamesToFileIdListId; + let emitSignatures; + const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value]) => { + var _a2, _b2; + const fileId = toFileId(key); + tryAddRoot(key, fileId); + Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); + const oldSignature = (_a2 = state.oldSignatures) == null ? void 0 : _a2.get(key); + const actualSignature = oldSignature !== void 0 ? oldSignature || void 0 : value.signature; + if (state.compilerOptions.composite) { + const file = state.program.getSourceFileByPath(key); + if (!isJsonSourceFile(file) && sourceFileMayBeEmitted(file, state.program)) { + const emitSignature = (_b2 = state.emitSignatures) == null ? void 0 : _b2.get(key); + if (emitSignature !== actualSignature) { + emitSignatures = append( + emitSignatures, + emitSignature === void 0 ? fileId : ( + // There is no emit, encode as false + // fileId, signature: emptyArray if signature only differs in dtsMap option than our own compilerOptions otherwise EmitSignature + [fileId, !isString(emitSignature) && emitSignature[0] === actualSignature ? emptyArray : emitSignature] + ) + ); + } + } + } + return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? ( + // If file version is same as signature, dont serialize signature + { version: value.version, signature: void 0, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } + ) : ( + // If file info only contains version and signature and both are same we can just write string + value.version + ) : actualSignature !== void 0 ? ( + // If signature is not same as version, encode signature in the fileInfo + oldSignature === void 0 ? ( + // If we havent computed signature, use fileInfo as is + value + ) : ( + // Serialize fileInfo with new updated signature + { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } + ) + ) : ( + // Signature of the FileInfo is undefined, serialize it as false + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } + ); + }); + let referencedMap; + if ((_a = state.referencedMap) == null ? void 0 : _a.size()) { + referencedMap = arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive).map((key) => [ + toFileId(key), + toFileIdListId(state.referencedMap.getValues(key)) + ]); + } + const semanticDiagnosticsPerFile = toIncrementalBuildInfoDiagnostics(); + let affectedFilesPendingEmit; + if ((_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.size) { + const fullEmitForOptions = getBuilderFileEmit(state.compilerOptions); + const seenFiles = /* @__PURE__ */ new Set(); + for (const path of arrayFrom(state.affectedFilesPendingEmit.keys()).sort(compareStringsCaseSensitive)) { + if (tryAddToSet(seenFiles, path)) { + const file = state.program.getSourceFileByPath(path); + if (!file || !sourceFileMayBeEmitted(file, state.program)) continue; + const fileId = toFileId(path), pendingEmit = state.affectedFilesPendingEmit.get(path); + affectedFilesPendingEmit = append( + affectedFilesPendingEmit, + pendingEmit === fullEmitForOptions ? fileId : ( + // Pending full emit per options + pendingEmit === 24 /* Dts */ ? [fileId] : ( + // Pending on Dts only + [fileId, pendingEmit] + ) + ) + // Anything else + ); + } + } + } + const buildInfo = { + fileNames, + fileIdsList, + fileInfos, + root, + resolvedRoot: toResolvedRoot(), + options: toIncrementalBuildInfoCompilerOptions(state.compilerOptions), + referencedMap, + semanticDiagnosticsPerFile, + emitDiagnosticsPerFile: toIncrementalBuildInfoEmitDiagnostics(), + changeFileSet: toChangeFileSet(), + affectedFilesPendingEmit, + emitSignatures, + latestChangedDtsFile, + errors: state.hasErrors ? true : void 0, + checkPending: state.checkPending, + version + }; + return buildInfo; + function relativeToBuildInfoEnsuringAbsolutePath(path) { + return relativeToBuildInfo(getNormalizedAbsolutePath(path, currentDirectory)); + } + function relativeToBuildInfo(path) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(buildInfoDirectory, path, state.program.getCanonicalFileName)); + } + function toFileId(path) { + let fileId = fileNameToFileId.get(path); + if (fileId === void 0) { + fileNames.push(relativeToBuildInfo(path)); + fileNameToFileId.set(path, fileId = fileNames.length); + } + return fileId; + } + function toFileIdListId(set) { + const fileIds = arrayFrom(set.keys(), toFileId).sort(compareValues); + const key = fileIds.join(); + let fileIdListId = fileNamesToFileIdListId == null ? void 0 : fileNamesToFileIdListId.get(key); + if (fileIdListId === void 0) { + fileIdsList = append(fileIdsList, fileIds); + (fileNamesToFileIdListId ?? (fileNamesToFileIdListId = /* @__PURE__ */ new Map())).set(key, fileIdListId = fileIdsList.length); + } + return fileIdListId; + } + function tryAddRoot(path, fileId) { + const file = state.program.getSourceFile(path); + if (!state.program.getFileIncludeReasons().get(file.path).some((r) => r.kind === 0 /* RootFile */)) return; + if (!root.length) return root.push(fileId); + const last2 = root[root.length - 1]; + const isLastStartEnd = isArray(last2); + if (isLastStartEnd && last2[1] === fileId - 1) return last2[1] = fileId; + if (isLastStartEnd || root.length === 1 || last2 !== fileId - 1) return root.push(fileId); + const lastButOne = root[root.length - 2]; + if (!isNumber(lastButOne) || lastButOne !== last2 - 1) return root.push(fileId); + root[root.length - 2] = [lastButOne, fileId]; + return root.length = root.length - 1; + } + function toResolvedRoot() { + let result; + rootFileNames.forEach((path) => { + const file = state.program.getSourceFileByPath(path); + if (file && path !== file.resolvedPath) { + result = append(result, [toFileId(file.resolvedPath), toFileId(path)]); + } + }); + return result; + } + function toIncrementalBuildInfoCompilerOptions(options) { + let result; + const { optionsNameMap } = getOptionsNameMap(); + for (const name of getOwnKeys(options).sort(compareStringsCaseSensitive)) { + const optionInfo = optionsNameMap.get(name.toLowerCase()); + if (optionInfo == null ? void 0 : optionInfo.affectsBuildInfo) { + (result || (result = {}))[name] = toReusableCompilerOptionValue( + optionInfo, + options[name] + ); + } + } + return result; + } + function toReusableCompilerOptionValue(option, value) { + if (option) { + Debug.assert(option.type !== "listOrElement"); + if (option.type === "list") { + const values = value; + if (option.element.isFilePath && values.length) { + return values.map(relativeToBuildInfoEnsuringAbsolutePath); + } + } else if (option.isFilePath) { + return relativeToBuildInfoEnsuringAbsolutePath(value); + } + } + return value; + } + function toIncrementalBuildInfoDiagnostics() { + let result; + state.fileInfos.forEach((_value, key) => { + const value = state.semanticDiagnosticsPerFile.get(key); + if (!value) { + if (!state.changedFilesSet.has(key)) result = append(result, toFileId(key)); + } else if (value.length) { + result = append(result, [ + toFileId(key), + toReusableDiagnostic(value, key) + ]); + } + }); + return result; + } + function toIncrementalBuildInfoEmitDiagnostics() { + var _a2; + let result; + if (!((_a2 = state.emitDiagnosticsPerFile) == null ? void 0 : _a2.size)) return result; + for (const key of arrayFrom(state.emitDiagnosticsPerFile.keys()).sort(compareStringsCaseSensitive)) { + const value = state.emitDiagnosticsPerFile.get(key); + result = append(result, [ + toFileId(key), + toReusableDiagnostic(value, key) + ]); + } + return result; + } + function toReusableDiagnostic(diagnostics, diagnosticFilePath) { + Debug.assert(!!diagnostics.length); + return diagnostics.map((diagnostic) => { + const result = toReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath); + result.reportsUnnecessary = diagnostic.reportsUnnecessary; + result.reportDeprecated = diagnostic.reportsDeprecated; + result.source = diagnostic.source; + result.skippedOn = diagnostic.skippedOn; + const { relatedInformation } = diagnostic; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => toReusableDiagnosticRelatedInformation(r, diagnosticFilePath)) : [] : void 0; + return result; + }); + } + function toReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath) { + const { file } = diagnostic; + return { + ...diagnostic, + file: file ? file.resolvedPath === diagnosticFilePath ? void 0 : relativeToBuildInfo(file.resolvedPath) : false, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : toReusableDiagnosticMessageChain(diagnostic.messageText) + }; + } + function toReusableDiagnosticMessageChain(chain) { + if (chain.repopulateInfo) { + return { + info: chain.repopulateInfo(), + next: toReusableDiagnosticMessageChainArray(chain.next) + }; + } + const next = toReusableDiagnosticMessageChainArray(chain.next); + return next === chain.next ? chain : { ...chain, next }; + } + function toReusableDiagnosticMessageChainArray(array) { + if (!array) return array; + return forEach(array, (chain, index) => { + const reusable = toReusableDiagnosticMessageChain(chain); + if (chain === reusable) return void 0; + const result = index > 0 ? array.slice(0, index - 1) : []; + result.push(reusable); + for (let i = index + 1; i < array.length; i++) { + result.push(toReusableDiagnosticMessageChain(array[i])); + } + return result; + }) || array; + } + function toChangeFileSet() { + let changeFileSet; + if (state.changedFilesSet.size) { + for (const path of arrayFrom(state.changedFilesSet.keys()).sort(compareStringsCaseSensitive)) { + changeFileSet = append(changeFileSet, toFileId(path)); + } + } + return changeFileSet; + } +} +function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + let host; + let newProgram; + let oldProgram; + if (newProgramOrRootNames === void 0) { + Debug.assert(hostOrOptions === void 0); + host = oldProgramOrHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram; + Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } else if (isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram; + newProgram = createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgramOrUndefined(), + configFileParsingDiagnostics, + projectReferences + }); + host = oldProgramOrHost; + } else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; + } + return { host, newProgram, oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || emptyArray }; +} +function getTextHandlingSourceMapForSignature(text, data) { + return (data == null ? void 0 : data.sourceMapUrlPos) !== void 0 ? text.substring(0, data.sourceMapUrlPos) : text; +} +function computeSignatureWithDiagnostics(program, sourceFile, text, host, data) { + var _a; + text = getTextHandlingSourceMapForSignature(text, data); + let sourceFileDirectory; + if ((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length) { + text += data.diagnostics.map((diagnostic) => `${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText2(diagnostic.messageText)}`).join("\n"); + } + return (host.createHash ?? generateDjb2Hash)(text); + function flattenDiagnosticMessageText2(diagnostic) { + return isString(diagnostic) ? diagnostic : diagnostic === void 0 ? "" : !diagnostic.next ? diagnostic.messageText : diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText2).join("\n"); + } + function locationInfo(diagnostic) { + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) return `(${diagnostic.start},${diagnostic.length})`; + if (sourceFileDirectory === void 0) sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath); + return `${ensurePathIsNonModuleName(getRelativePathFromDirectory( + sourceFileDirectory, + diagnostic.file.resolvedPath, + program.getCanonicalFileName + ))}(${diagnostic.start},${diagnostic.length})`; + } +} +function computeSignature(text, host, data) { + return (host.createHash ?? generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); +} +function createBuilderProgram(kind, { newProgram, host, oldProgram, configFileParsingDiagnostics }) { + let oldState = oldProgram && oldProgram.state; + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { + newProgram = void 0; + oldState = void 0; + return oldProgram; + } + const state = createBuilderProgramState(newProgram, oldState); + newProgram.getBuildInfo = () => getBuildInfo2(toBuilderProgramStateWithDefinedProgram(state)); + newProgram = void 0; + oldProgram = void 0; + oldState = void 0; + const builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics); + builderProgram.state = state; + builderProgram.hasChangedEmitSignature = () => !!state.hasChangedEmitSignature; + builderProgram.getAllDependencies = (sourceFile) => BuilderState.getAllDependencies( + state, + Debug.checkDefined(state.program), + sourceFile + ); + builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; + builderProgram.getDeclarationDiagnostics = getDeclarationDiagnostics2; + builderProgram.emit = emit; + builderProgram.releaseProgram = () => releaseCache(state); + if (kind === 0 /* SemanticDiagnosticsBuilderProgram */) { + builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } else if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { + builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + builderProgram.emitNextAffectedFile = emitNextAffectedFile; + builderProgram.emitBuildInfo = emitBuildInfo; + } else { + notImplemented(); + } + return builderProgram; + function emitBuildInfo(writeFile2, cancellationToken) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + if (getBuildInfoEmitPending(state)) { + const result = state.program.emitBuildInfo( + writeFile2 || maybeBind(host, host.writeFile), + cancellationToken + ); + state.buildInfoEmitPending = false; + return result; + } + return emitSkippedWithNoDiagnostics; + } + function emitNextAffectedFileOrDtsErrors(writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers, isForDtsErrors) { + var _a, _b, _c, _d; + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + let affected = getNextAffectedFile(state, cancellationToken, host); + const programEmitKind = getBuilderFileEmit(state.compilerOptions); + let emitKind = !isForDtsErrors ? emitOnlyDtsFiles ? programEmitKind & 56 /* AllDts */ : programEmitKind : 8 /* DtsErrors */; + if (!affected) { + if (!state.compilerOptions.outFile) { + const pendingAffectedFile = getNextAffectedFilePendingEmit( + state, + emitOnlyDtsFiles, + isForDtsErrors + ); + if (pendingAffectedFile) { + ({ affectedFile: affected, emitKind } = pendingAffectedFile); + } else { + const pendingForDiagnostics = getNextPendingEmitDiagnosticsFile( + state, + isForDtsErrors + ); + if (pendingForDiagnostics) { + (state.seenEmittedFiles ?? (state.seenEmittedFiles = /* @__PURE__ */ new Map())).set( + pendingForDiagnostics.affectedFile.resolvedPath, + pendingForDiagnostics.seenKind | getBuilderFileEmitAllDts(isForDtsErrors) + ); + return { + result: { emitSkipped: true, diagnostics: pendingForDiagnostics.diagnostics }, + affected: pendingForDiagnostics.affectedFile + }; + } + } + } else { + if (state.programEmitPending) { + emitKind = getPendingEmitKindWithSeen( + state.programEmitPending, + state.seenProgramEmit, + emitOnlyDtsFiles, + isForDtsErrors + ); + if (emitKind) affected = state.program; + } + if (!affected && ((_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.size)) { + const seenKind = state.seenProgramEmit || 0 /* None */; + if (!(seenKind & getBuilderFileEmitAllDts(isForDtsErrors))) { + state.seenProgramEmit = getBuilderFileEmitAllDts(isForDtsErrors) | seenKind; + const diagnostics = []; + state.emitDiagnosticsPerFile.forEach((d) => addRange(diagnostics, d)); + return { + result: { emitSkipped: true, diagnostics }, + affected: state.program + }; + } + } + } + if (!affected) { + if (isForDtsErrors || !getBuildInfoEmitPending(state)) return void 0; + const affected2 = state.program; + const result2 = affected2.emitBuildInfo( + writeFile2 || maybeBind(host, host.writeFile), + cancellationToken + ); + state.buildInfoEmitPending = false; + return { result: result2, affected: affected2 }; + } + } + let emitOnly; + if (emitKind & 7 /* AllJs */) emitOnly = 0 /* Js */; + if (emitKind & 56 /* AllDts */) emitOnly = emitOnly === void 0 ? 1 /* Dts */ : void 0; + const result = !isForDtsErrors ? state.program.emit( + affected === state.program ? void 0 : affected, + getWriteFileCallback(writeFile2, customTransformers), + cancellationToken, + emitOnly, + customTransformers, + /*forceDtsEmit*/ + void 0, + /*skipBuildInfo*/ + true + ) : { + emitSkipped: true, + diagnostics: state.program.getDeclarationDiagnostics( + affected === state.program ? void 0 : affected, + cancellationToken + ) + }; + if (affected !== state.program) { + const affectedSourceFile = affected; + state.seenAffectedFiles.add(affectedSourceFile.resolvedPath); + if (state.affectedFilesIndex !== void 0) state.affectedFilesIndex++; + state.buildInfoEmitPending = true; + const existing = ((_b = state.seenEmittedFiles) == null ? void 0 : _b.get(affectedSourceFile.resolvedPath)) || 0 /* None */; + (state.seenEmittedFiles ?? (state.seenEmittedFiles = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, emitKind | existing); + const existingPending = ((_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.get(affectedSourceFile.resolvedPath)) || programEmitKind; + const pendingKind = getPendingEmitKind(existingPending, emitKind | existing); + if (pendingKind) (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, pendingKind); + else (_d = state.affectedFilesPendingEmit) == null ? void 0 : _d.delete(affectedSourceFile.resolvedPath); + if (result.diagnostics.length) (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, result.diagnostics); + } else { + state.changedFilesSet.clear(); + state.programEmitPending = state.changedFilesSet.size ? getPendingEmitKind(programEmitKind, emitKind) : state.programEmitPending ? getPendingEmitKind(state.programEmitPending, emitKind) : void 0; + state.seenProgramEmit = emitKind | (state.seenProgramEmit || 0 /* None */); + setEmitDiagnosticsPerFile(result.diagnostics); + state.buildInfoEmitPending = true; + } + return { result, affected }; + } + function setEmitDiagnosticsPerFile(diagnostics) { + let emitDiagnosticsPerFile; + diagnostics.forEach((d) => { + if (!d.file) return; + let diagnostics2 = emitDiagnosticsPerFile == null ? void 0 : emitDiagnosticsPerFile.get(d.file.resolvedPath); + if (!diagnostics2) (emitDiagnosticsPerFile ?? (emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set(d.file.resolvedPath, diagnostics2 = []); + diagnostics2.push(d); + }); + if (emitDiagnosticsPerFile) state.emitDiagnosticsPerFile = emitDiagnosticsPerFile; + } + function emitNextAffectedFile(writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { + return emitNextAffectedFileOrDtsErrors( + writeFile2, + cancellationToken, + emitOnlyDtsFiles, + customTransformers, + /*isForDtsErrors*/ + false + ); + } + function getWriteFileCallback(writeFile2, customTransformers) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + if (!getEmitDeclarations(state.compilerOptions)) return writeFile2 || maybeBind(host, host.writeFile); + return (fileName, text, writeByteOrderMark, onError, sourceFiles, data) => { + var _a, _b, _c; + if (isDeclarationFileName(fileName)) { + if (!state.compilerOptions.outFile) { + Debug.assert((sourceFiles == null ? void 0 : sourceFiles.length) === 1); + let emitSignature; + if (!customTransformers) { + const file = sourceFiles[0]; + const info = state.fileInfos.get(file.resolvedPath); + if (info.signature === file.version) { + const signature = computeSignatureWithDiagnostics( + state.program, + file, + text, + host, + data + ); + if (!((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length)) emitSignature = signature; + if (signature !== file.version) { + if (host.storeSignatureInfo) (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(file.resolvedPath, 1 /* StoredSignatureAtEmit */); + if (state.affectedFiles) { + const existing = (_b = state.oldSignatures) == null ? void 0 : _b.get(file.resolvedPath); + if (existing === void 0) (state.oldSignatures ?? (state.oldSignatures = /* @__PURE__ */ new Map())).set(file.resolvedPath, info.signature || false); + info.signature = signature; + } else { + info.signature = signature; + } + } + } + } + if (state.compilerOptions.composite) { + const filePath = sourceFiles[0].resolvedPath; + emitSignature = handleNewSignature((_c = state.emitSignatures) == null ? void 0 : _c.get(filePath), emitSignature); + if (!emitSignature) return data.skippedDtsWrite = true; + (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(filePath, emitSignature); + } + } else if (state.compilerOptions.composite) { + const newSignature = handleNewSignature( + state.outSignature, + /*newSignature*/ + void 0 + ); + if (!newSignature) return data.skippedDtsWrite = true; + state.outSignature = newSignature; + } + } + if (writeFile2) writeFile2(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + else if (host.writeFile) host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + else state.program.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + function handleNewSignature(oldSignatureFormat, newSignature) { + const oldSignature = !oldSignatureFormat || isString(oldSignatureFormat) ? oldSignatureFormat : oldSignatureFormat[0]; + newSignature ?? (newSignature = computeSignature(text, host, data)); + if (newSignature === oldSignature) { + if (oldSignatureFormat === oldSignature) return void 0; + else if (data) data.differsOnlyInMap = true; + else data = { differsOnlyInMap: true }; + } else { + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; + } + return newSignature; + } + }; + } + function emit(targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + } + const result = handleNoEmitOptions(builderProgram, targetSourceFile, writeFile2, cancellationToken); + if (result) return result; + if (!targetSourceFile) { + if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { + let sourceMaps = []; + let emitSkipped = false; + let diagnostics; + let emittedFiles = []; + let affectedEmitResult; + while (affectedEmitResult = emitNextAffectedFile( + writeFile2, + cancellationToken, + emitOnlyDtsFiles, + customTransformers + )) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped, + diagnostics: diagnostics || emptyArray, + emittedFiles, + sourceMaps + }; + } else { + clearAffectedFilesPendingEmit( + state, + emitOnlyDtsFiles, + /*isForDtsErrors*/ + false + ); + } + } + const emitResult = state.program.emit( + targetSourceFile, + getWriteFileCallback(writeFile2, customTransformers), + cancellationToken, + emitOnlyDtsFiles, + customTransformers + ); + handleNonEmitBuilderWithEmitOrDtsErrors( + targetSourceFile, + emitOnlyDtsFiles, + /*isForDtsErrors*/ + false, + emitResult.diagnostics + ); + return emitResult; + } + function handleNonEmitBuilderWithEmitOrDtsErrors(targetSourceFile, emitOnlyDtsFiles, isForDtsErrors, diagnostics) { + if (!targetSourceFile && kind !== 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { + clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles, isForDtsErrors); + setEmitDiagnosticsPerFile(diagnostics); + } + } + function getDeclarationDiagnostics2(sourceFile, cancellationToken) { + var _a; + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + let affectedEmitResult; + let diagnostics; + while (affectedEmitResult = emitNextAffectedFileOrDtsErrors( + /*writeFile*/ + void 0, + cancellationToken, + /*emitOnlyDtsFiles*/ + void 0, + /*customTransformers*/ + void 0, + /*isForDtsErrors*/ + true + )) { + if (!sourceFile) diagnostics = addRange(diagnostics, affectedEmitResult.result.diagnostics); + } + return (!sourceFile ? diagnostics : (_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.get(sourceFile.resolvedPath)) || emptyArray; + } else { + const result = state.program.getDeclarationDiagnostics(sourceFile, cancellationToken); + handleNonEmitBuilderWithEmitOrDtsErrors( + sourceFile, + /*emitOnlyDtsFiles*/ + void 0, + /*isForDtsErrors*/ + true, + result + ); + return result; + } + } + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + while (true) { + const affected = getNextAffectedFile(state, cancellationToken, host); + let result; + if (!affected) { + if (state.checkPending && !state.compilerOptions.noCheck) { + state.checkPending = void 0; + state.buildInfoEmitPending = true; + } + return void 0; + } else if (affected !== state.program) { + const affectedSourceFile = affected; + if (!ignoreSourceFile || !ignoreSourceFile(affectedSourceFile)) { + result = getSemanticDiagnosticsOfFile(state, affectedSourceFile, cancellationToken); + } + state.seenAffectedFiles.add(affectedSourceFile.resolvedPath); + state.affectedFilesIndex++; + state.buildInfoEmitPending = true; + if (!result) continue; + } else { + let diagnostics; + const semanticDiagnosticsPerFile = /* @__PURE__ */ new Map(); + state.program.getSourceFiles().forEach( + (sourceFile) => diagnostics = addRange( + diagnostics, + getSemanticDiagnosticsOfFile( + state, + sourceFile, + cancellationToken, + semanticDiagnosticsPerFile + ) + ) + ); + state.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; + result = diagnostics || emptyArray; + state.changedFilesSet.clear(); + state.programEmitPending = getBuilderFileEmit(state.compilerOptions); + if (!state.compilerOptions.noCheck) state.checkPending = void 0; + state.buildInfoEmitPending = true; + } + return { result, affected }; + } + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + while (true) { + const affectedResult = getSemanticDiagnosticsOfNextAffectedFile(cancellationToken); + if (!affectedResult) break; + if (affectedResult.affected === state.program) return affectedResult.result; + } + let diagnostics; + for (const sourceFile2 of state.program.getSourceFiles()) { + diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile2, cancellationToken)); + } + if (state.checkPending && !state.compilerOptions.noCheck) { + state.checkPending = void 0; + state.buildInfoEmitPending = true; + } + return diagnostics || emptyArray; + } +} +function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) { + var _a, _b; + const existingKind = ((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.get(affectedFilePendingEmit)) || 0 /* None */; + (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedFilePendingEmit, existingKind | kind); + (_b = state.emitDiagnosticsPerFile) == null ? void 0 : _b.delete(affectedFilePendingEmit); +} +function toBuilderStateFileInfoForMultiEmit(fileInfo) { + return isString(fileInfo) ? { version: fileInfo, signature: fileInfo, affectsGlobalScope: void 0, impliedFormat: void 0 } : isString(fileInfo.signature) ? fileInfo : { version: fileInfo.version, signature: fileInfo.signature === false ? void 0 : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; +} +function toBuilderFileEmit(value, fullEmitForOptions) { + return isNumber(value) ? fullEmitForOptions : value[1] || 24 /* Dts */; +} +function toProgramEmitPending(value, options) { + return !value ? getBuilderFileEmit(options || {}) : value; +} +function createBuilderProgramUsingIncrementalBuildInfo(buildInfo, buildInfoPath, host) { + var _a, _b, _c, _d; + const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + let state; + const filePaths = (_a = buildInfo.fileNames) == null ? void 0 : _a.map(toPathInBuildInfoDirectory); + let filePathsSetList; + const latestChangedDtsFile = buildInfo.latestChangedDtsFile ? toAbsolutePath(buildInfo.latestChangedDtsFile) : void 0; + const fileInfos = /* @__PURE__ */ new Map(); + const changedFilesSet = new Set(map(buildInfo.changeFileSet, toFilePath)); + if (isIncrementalBundleEmitBuildInfo(buildInfo)) { + buildInfo.fileInfos.forEach((fileInfo, index) => { + const path = toFilePath(index + 1); + fileInfos.set(path, isString(fileInfo) ? { version: fileInfo, signature: void 0, affectsGlobalScope: void 0, impliedFormat: void 0 } : fileInfo); + }); + state = { + fileInfos, + compilerOptions: buildInfo.options ? convertToOptionsWithAbsolutePaths(buildInfo.options, toAbsolutePath) : {}, + semanticDiagnosticsPerFile: toPerFileSemanticDiagnostics(buildInfo.semanticDiagnosticsPerFile), + emitDiagnosticsPerFile: toPerFileEmitDiagnostics(buildInfo.emitDiagnosticsPerFile), + hasReusableDiagnostic: true, + changedFilesSet, + latestChangedDtsFile, + outSignature: buildInfo.outSignature, + programEmitPending: buildInfo.pendingEmit === void 0 ? void 0 : toProgramEmitPending(buildInfo.pendingEmit, buildInfo.options), + hasErrors: buildInfo.errors, + checkPending: buildInfo.checkPending + }; + } else { + filePathsSetList = (_b = buildInfo.fileIdsList) == null ? void 0 : _b.map((fileIds) => new Set(fileIds.map(toFilePath))); + const emitSignatures = ((_c = buildInfo.options) == null ? void 0 : _c.composite) && !buildInfo.options.outFile ? /* @__PURE__ */ new Map() : void 0; + buildInfo.fileInfos.forEach((fileInfo, index) => { + const path = toFilePath(index + 1); + const stateFileInfo = toBuilderStateFileInfoForMultiEmit(fileInfo); + fileInfos.set(path, stateFileInfo); + if (emitSignatures && stateFileInfo.signature) emitSignatures.set(path, stateFileInfo.signature); + }); + (_d = buildInfo.emitSignatures) == null ? void 0 : _d.forEach((value) => { + if (isNumber(value)) emitSignatures.delete(toFilePath(value)); + else { + const key = toFilePath(value[0]); + emitSignatures.set( + key, + !isString(value[1]) && !value[1].length ? ( + // File signature is emit signature but differs in map + [emitSignatures.get(key)] + ) : value[1] + ); + } + }); + const fullEmitForOptions = buildInfo.affectedFilesPendingEmit ? getBuilderFileEmit(buildInfo.options || {}) : void 0; + state = { + fileInfos, + compilerOptions: buildInfo.options ? convertToOptionsWithAbsolutePaths(buildInfo.options, toAbsolutePath) : {}, + referencedMap: toManyToManyPathMap(buildInfo.referencedMap, buildInfo.options ?? {}), + semanticDiagnosticsPerFile: toPerFileSemanticDiagnostics(buildInfo.semanticDiagnosticsPerFile), + emitDiagnosticsPerFile: toPerFileEmitDiagnostics(buildInfo.emitDiagnosticsPerFile), + hasReusableDiagnostic: true, + changedFilesSet, + affectedFilesPendingEmit: buildInfo.affectedFilesPendingEmit && arrayToMap(buildInfo.affectedFilesPendingEmit, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => toBuilderFileEmit(value, fullEmitForOptions)), + latestChangedDtsFile, + emitSignatures: (emitSignatures == null ? void 0 : emitSignatures.size) ? emitSignatures : void 0, + hasErrors: buildInfo.errors, + checkPending: buildInfo.checkPending + }; + } + return { + state, + getProgram: notImplemented, + getProgramOrUndefined: returnUndefined, + releaseProgram: noop, + getCompilerOptions: () => state.compilerOptions, + getSourceFile: notImplemented, + getSourceFiles: notImplemented, + getOptionsDiagnostics: notImplemented, + getGlobalDiagnostics: notImplemented, + getConfigFileParsingDiagnostics: notImplemented, + getSyntacticDiagnostics: notImplemented, + getDeclarationDiagnostics: notImplemented, + getSemanticDiagnostics: notImplemented, + emit: notImplemented, + getAllDependencies: notImplemented, + getCurrentDirectory: notImplemented, + emitNextAffectedFile: notImplemented, + getSemanticDiagnosticsOfNextAffectedFile: notImplemented, + emitBuildInfo: notImplemented, + close: noop, + hasChangedEmitSignature: returnFalse + }; + function toPathInBuildInfoDirectory(path) { + return toPath(path, buildInfoDirectory, getCanonicalFileName); + } + function toAbsolutePath(path) { + return getNormalizedAbsolutePath(path, buildInfoDirectory); + } + function toFilePath(fileId) { + return filePaths[fileId - 1]; + } + function toFilePathsSet(fileIdsListId) { + return filePathsSetList[fileIdsListId - 1]; + } + function toManyToManyPathMap(referenceMap, options) { + const map2 = BuilderState.createReferencedMap(options); + if (!map2 || !referenceMap) return map2; + referenceMap.forEach(([fileId, fileIdListId]) => map2.set(toFilePath(fileId), toFilePathsSet(fileIdListId))); + return map2; + } + function toPerFileSemanticDiagnostics(diagnostics) { + const semanticDiagnostics = new Map( + mapDefinedIterator( + fileInfos.keys(), + (key) => !changedFilesSet.has(key) ? [key, emptyArray] : void 0 + ) + ); + diagnostics == null ? void 0 : diagnostics.forEach((value) => { + if (isNumber(value)) semanticDiagnostics.delete(toFilePath(value)); + else semanticDiagnostics.set(toFilePath(value[0]), value[1]); + }); + return semanticDiagnostics; + } + function toPerFileEmitDiagnostics(diagnostics) { + return diagnostics && arrayToMap(diagnostics, (value) => toFilePath(value[0]), (value) => value[1]); + } +} +function getBuildInfoFileVersionMap(program, buildInfoPath, host) { + const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + const fileInfos = /* @__PURE__ */ new Map(); + let rootIndex = 0; + const roots = /* @__PURE__ */ new Map(); + const resolvedRoots = new Map(program.resolvedRoot); + program.fileInfos.forEach((fileInfo, index) => { + const path = toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); + const version2 = isString(fileInfo) ? fileInfo : fileInfo.version; + fileInfos.set(path, version2); + if (rootIndex < program.root.length) { + const current = program.root[rootIndex]; + const fileId = index + 1; + if (isArray(current)) { + if (current[0] <= fileId && fileId <= current[1]) { + addRoot(fileId, path); + if (current[1] === fileId) rootIndex++; + } + } else if (current === fileId) { + addRoot(fileId, path); + rootIndex++; + } + } + }); + return { fileInfos, roots }; + function addRoot(fileId, path) { + const root = resolvedRoots.get(fileId); + if (root) { + roots.set(toPath(program.fileNames[root - 1], buildInfoDirectory, getCanonicalFileName), path); + } else { + roots.set(path, void 0); + } + } +} +function getNonIncrementalBuildInfoRoots(buildInfo, buildInfoPath, host) { + if (!isNonIncrementalBuildInfo(buildInfo)) return void 0; + const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + return buildInfo.root.map((r) => toPath(r, buildInfoDirectory, getCanonicalFileName)); +} +function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { + return { + state: void 0, + getProgram, + getProgramOrUndefined: () => state.program, + releaseProgram: () => state.program = void 0, + getCompilerOptions: () => state.compilerOptions, + getSourceFile: (fileName) => getProgram().getSourceFile(fileName), + getSourceFiles: () => getProgram().getSourceFiles(), + getOptionsDiagnostics: (cancellationToken) => getProgram().getOptionsDiagnostics(cancellationToken), + getGlobalDiagnostics: (cancellationToken) => getProgram().getGlobalDiagnostics(cancellationToken), + getConfigFileParsingDiagnostics: () => configFileParsingDiagnostics, + getSyntacticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken), + getDeclarationDiagnostics: (sourceFile, cancellationToken) => getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken), + getSemanticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSemanticDiagnostics(sourceFile, cancellationToken), + emit: (sourceFile, writeFile2, cancellationToken, emitOnlyDts, customTransformers) => getProgram().emit(sourceFile, writeFile2, cancellationToken, emitOnlyDts, customTransformers), + emitBuildInfo: (writeFile2, cancellationToken) => getProgram().emitBuildInfo(writeFile2, cancellationToken), + getAllDependencies: notImplemented, + getCurrentDirectory: () => getProgram().getCurrentDirectory(), + close: noop + }; + function getProgram() { + return Debug.checkDefined(state.program); + } +} + +// src/compiler/builderPublic.ts +function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return createBuilderProgram( + 1 /* EmitAndSemanticDiagnosticsBuilderProgram */, + getBuilderCreationParameters( + newProgramOrRootNames, + hostOrOptions, + oldProgramOrHost, + configFileParsingDiagnosticsOrOldProgram, + configFileParsingDiagnostics, + projectReferences + ) + ); +} + +// src/compiler/resolutionCache.ts +function removeIgnoredPath(path) { + if (endsWith(path, "/node_modules/.staging")) { + return removeSuffix(path, "/.staging"); + } + return some(ignoredPaths, (searchPath) => path.includes(searchPath)) ? void 0 : path; +} +function perceivedOsRootLengthForWatching(pathComponents2, length2) { + if (length2 <= 1) return 1; + let indexAfterOsRoot = 1; + let isDosStyle = pathComponents2[0].search(/[a-z]:/i) === 0; + if (pathComponents2[0] !== directorySeparator && !isDosStyle && // Non dos style paths + pathComponents2[1].search(/[a-z]\$$/i) === 0) { + if (length2 === 2) return 2; + indexAfterOsRoot = 2; + isDosStyle = true; + } + if (isDosStyle && !pathComponents2[indexAfterOsRoot].match(/^users$/i)) { + return indexAfterOsRoot; + } + if (pathComponents2[indexAfterOsRoot].match(/^workspaces$/i)) { + return indexAfterOsRoot + 1; + } + return indexAfterOsRoot + 2; +} +function canWatchDirectoryOrFile(pathComponents2, length2) { + if (length2 === void 0) length2 = pathComponents2.length; + if (length2 <= 2) return false; + const perceivedOsRootLength = perceivedOsRootLengthForWatching(pathComponents2, length2); + return length2 > perceivedOsRootLength + 1; +} +function canWatchDirectoryOrFilePath(path) { + return canWatchDirectoryOrFile(getPathComponents(path)); +} +function canWatchAtTypes(atTypes) { + return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(getDirectoryPath(atTypes)); +} +function isInDirectoryPath(dirComponents, fileOrDirComponents) { + if (fileOrDirComponents.length < fileOrDirComponents.length) return false; + for (let i = 0; i < dirComponents.length; i++) { + if (fileOrDirComponents[i] !== dirComponents[i]) return false; + } + return true; +} +function canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(fileOrDirPath) { + return canWatchDirectoryOrFilePath(fileOrDirPath); +} +function canWatchAffectingLocation(filePath) { + return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(filePath); +} +function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, isRootWatchable, getCurrentDirectory, preferNonRecursiveWatch) { + const failedLookupPathComponents = getPathComponents(failedLookupLocationPath); + failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + const failedLookupComponents = getPathComponents(failedLookupLocation); + const perceivedOsRootLength = perceivedOsRootLengthForWatching(failedLookupPathComponents, failedLookupPathComponents.length); + if (failedLookupPathComponents.length <= perceivedOsRootLength + 1) return void 0; + const nodeModulesIndex = failedLookupPathComponents.indexOf("node_modules"); + if (nodeModulesIndex !== -1 && nodeModulesIndex + 1 <= perceivedOsRootLength + 1) return void 0; + const lastNodeModulesIndex = failedLookupPathComponents.lastIndexOf("node_modules"); + if (isRootWatchable && isInDirectoryPath(rootPathComponents, failedLookupPathComponents)) { + if (failedLookupPathComponents.length > rootPathComponents.length + 1) { + return getDirectoryOfFailedLookupWatch( + failedLookupComponents, + failedLookupPathComponents, + Math.max(rootPathComponents.length + 1, perceivedOsRootLength + 1), + lastNodeModulesIndex + ); + } else { + return { + dir: rootDir, + dirPath: rootPath, + nonRecursive: true + }; + } + } + return getDirectoryToWatchFromFailedLookupLocationDirectory( + failedLookupComponents, + failedLookupPathComponents, + failedLookupPathComponents.length - 1, + perceivedOsRootLength, + nodeModulesIndex, + rootPathComponents, + lastNodeModulesIndex, + preferNonRecursiveWatch + ); +} +function getDirectoryToWatchFromFailedLookupLocationDirectory(dirComponents, dirPathComponents, dirPathComponentsLength, perceivedOsRootLength, nodeModulesIndex, rootPathComponents, lastNodeModulesIndex, preferNonRecursiveWatch) { + if (nodeModulesIndex !== -1) { + return getDirectoryOfFailedLookupWatch( + dirComponents, + dirPathComponents, + nodeModulesIndex + 1, + lastNodeModulesIndex + ); + } + let nonRecursive = true; + let length2 = dirPathComponentsLength; + if (!preferNonRecursiveWatch) { + for (let i = 0; i < dirPathComponentsLength; i++) { + if (dirPathComponents[i] !== rootPathComponents[i]) { + nonRecursive = false; + length2 = Math.max(i + 1, perceivedOsRootLength + 1); + break; + } + } + } + return getDirectoryOfFailedLookupWatch( + dirComponents, + dirPathComponents, + length2, + lastNodeModulesIndex, + nonRecursive + ); +} +function getDirectoryOfFailedLookupWatch(dirComponents, dirPathComponents, length2, lastNodeModulesIndex, nonRecursive) { + let packageDirLength; + if (lastNodeModulesIndex !== -1 && lastNodeModulesIndex + 1 >= length2 && lastNodeModulesIndex + 2 < dirPathComponents.length) { + if (!startsWith(dirPathComponents[lastNodeModulesIndex + 1], "@")) { + packageDirLength = lastNodeModulesIndex + 2; + } else if (lastNodeModulesIndex + 3 < dirPathComponents.length) { + packageDirLength = lastNodeModulesIndex + 3; + } + } + return { + dir: getPathFromPathComponents(dirComponents, length2), + dirPath: getPathFromPathComponents(dirPathComponents, length2), + nonRecursive, + packageDir: packageDirLength !== void 0 ? getPathFromPathComponents(dirComponents, packageDirLength) : void 0, + packageDirPath: packageDirLength !== void 0 ? getPathFromPathComponents(dirPathComponents, packageDirLength) : void 0 + }; +} +function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath, rootPath, rootPathComponents, isRootWatchable, getCurrentDirectory, preferNonRecursiveWatch, filterCustomPath) { + const typeRootPathComponents = getPathComponents(typeRootPath); + if (isRootWatchable && isInDirectoryPath(rootPathComponents, typeRootPathComponents)) { + return rootPath; + } + typeRoot = isRootedDiskPath(typeRoot) ? normalizePath(typeRoot) : getNormalizedAbsolutePath(typeRoot, getCurrentDirectory()); + const toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory( + getPathComponents(typeRoot), + typeRootPathComponents, + typeRootPathComponents.length, + perceivedOsRootLengthForWatching(typeRootPathComponents, typeRootPathComponents.length), + typeRootPathComponents.indexOf("node_modules"), + rootPathComponents, + typeRootPathComponents.lastIndexOf("node_modules"), + preferNonRecursiveWatch + ); + return toWatch && filterCustomPath(toWatch.dirPath) ? toWatch.dirPath : void 0; +} +function getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory) { + const normalized = getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()); + return !isDiskPathRoot(normalized) ? removeTrailingDirectorySeparator(normalized) : normalized; +} +function getModuleResolutionHost(resolutionHost) { + var _a; + return ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; +} +function createModuleResolutionLoaderUsingGlobalCache(containingFile, redirectedReference, options, resolutionHost, moduleResolutionCache) { + return { + nameAndMode: moduleResolutionNameAndModeGetter, + resolve: (moduleName, resoluionMode) => resolveModuleNameUsingGlobalCache( + resolutionHost, + moduleResolutionCache, + moduleName, + containingFile, + options, + redirectedReference, + resoluionMode + ) + }; +} +function resolveModuleNameUsingGlobalCache(resolutionHost, moduleResolutionCache, moduleName, containingFile, compilerOptions, redirectedReference, mode) { + const host = getModuleResolutionHost(resolutionHost); + const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); + if (!resolutionHost.getGlobalTypingsCacheLocation) { + return primaryResult; + } + const globalCache = resolutionHost.getGlobalTypingsCacheLocation(); + if (globalCache !== void 0 && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) { + const { resolvedModule, failedLookupLocations, affectingLocations, resolutionDiagnostics } = loadModuleFromGlobalCache( + Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), + resolutionHost.projectName, + compilerOptions, + host, + globalCache, + moduleResolutionCache + ); + if (resolvedModule) { + primaryResult.resolvedModule = resolvedModule; + primaryResult.failedLookupLocations = updateResolutionField(primaryResult.failedLookupLocations, failedLookupLocations); + primaryResult.affectingLocations = updateResolutionField(primaryResult.affectingLocations, affectingLocations); + primaryResult.resolutionDiagnostics = updateResolutionField(primaryResult.resolutionDiagnostics, resolutionDiagnostics); + return primaryResult; + } + } + return primaryResult; +} +function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + let filesWithChangedSetOfUnresolvedImports; + let filesWithInvalidatedResolutions; + let filesWithInvalidatedNonRelativeUnresolvedImports; + const nonRelativeExternalModuleResolutions = /* @__PURE__ */ new Set(); + const resolutionsWithFailedLookups = /* @__PURE__ */ new Set(); + const resolutionsWithOnlyAffectingLocations = /* @__PURE__ */ new Set(); + const resolvedFileToResolution = /* @__PURE__ */ new Map(); + const impliedFormatPackageJsons = /* @__PURE__ */ new Map(); + let hasChangedAutomaticTypeDirectiveNames = false; + let affectingPathChecksForFile; + let affectingPathChecks; + let failedLookupChecks; + let startsWithPathChecks; + let isInDirectoryChecks; + let allModuleAndTypeResolutionsAreInvalidated = false; + const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory()); + const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + const resolvedModuleNames = /* @__PURE__ */ new Map(); + const moduleResolutionCache = createModuleResolutionCache( + getCurrentDirectory(), + resolutionHost.getCanonicalFileName, + resolutionHost.getCompilationSettings() + ); + const resolvedTypeReferenceDirectives = /* @__PURE__ */ new Map(); + const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache( + getCurrentDirectory(), + resolutionHost.getCanonicalFileName, + resolutionHost.getCompilationSettings(), + moduleResolutionCache.getPackageJsonInfoCache(), + moduleResolutionCache.optionsToRedirectsKey + ); + const resolvedLibraries = /* @__PURE__ */ new Map(); + const libraryResolutionCache = createModuleResolutionCache( + getCurrentDirectory(), + resolutionHost.getCanonicalFileName, + getOptionsForLibraryResolution(resolutionHost.getCompilationSettings()), + moduleResolutionCache.getPackageJsonInfoCache() + ); + const directoryWatchesOfFailedLookups = /* @__PURE__ */ new Map(); + const fileWatchesOfAffectingLocations = /* @__PURE__ */ new Map(); + const rootDir = getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory); + const rootPath = resolutionHost.toPath(rootDir); + const rootPathComponents = getPathComponents(rootPath); + const isRootWatchable = canWatchDirectoryOrFile(rootPathComponents); + const isSymlinkCache = /* @__PURE__ */ new Map(); + const packageDirWatchers = /* @__PURE__ */ new Map(); + const dirPathToSymlinkPackageRefCount = /* @__PURE__ */ new Map(); + const typeRootsWatches = /* @__PURE__ */ new Map(); + return { + rootDirForResolution, + resolvedModuleNames, + resolvedTypeReferenceDirectives, + resolvedLibraries, + resolvedFileToResolution, + resolutionsWithFailedLookups, + resolutionsWithOnlyAffectingLocations, + directoryWatchesOfFailedLookups, + fileWatchesOfAffectingLocations, + packageDirWatchers, + dirPathToSymlinkPackageRefCount, + watchFailedLookupLocationsOfExternalModuleResolutions, + getModuleResolutionCache: () => moduleResolutionCache, + startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution, + finishCachingPerDirectoryResolution, + resolveModuleNameLiterals, + resolveTypeReferenceDirectiveReferences, + resolveLibrary: resolveLibrary2, + resolveSingleModuleNameWithoutWatching, + removeResolutionsFromProjectReferenceRedirects, + removeResolutionsOfFile, + hasChangedAutomaticTypeDirectiveNames: () => hasChangedAutomaticTypeDirectiveNames, + invalidateResolutionOfFile, + invalidateResolutionsOfFailedLookupLocations, + setFilesWithInvalidatedNonRelativeUnresolvedImports, + createHasInvalidatedResolutions, + isFileWithInvalidatedNonRelativeUnresolvedImports, + updateTypeRootsWatch, + closeTypeRootsWatch, + clear: clear2, + onChangesAffectModuleResolution + }; + function clear2() { + clearMap(directoryWatchesOfFailedLookups, closeFileWatcherOf); + clearMap(fileWatchesOfAffectingLocations, closeFileWatcherOf); + isSymlinkCache.clear(); + packageDirWatchers.clear(); + dirPathToSymlinkPackageRefCount.clear(); + nonRelativeExternalModuleResolutions.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + resolvedFileToResolution.clear(); + resolutionsWithFailedLookups.clear(); + resolutionsWithOnlyAffectingLocations.clear(); + failedLookupChecks = void 0; + startsWithPathChecks = void 0; + isInDirectoryChecks = void 0; + affectingPathChecks = void 0; + affectingPathChecksForFile = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); + moduleResolutionCache.update(resolutionHost.getCompilationSettings()); + typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + libraryResolutionCache.clear(); + impliedFormatPackageJsons.clear(); + resolvedLibraries.clear(); + hasChangedAutomaticTypeDirectiveNames = false; + } + function onChangesAffectModuleResolution() { + allModuleAndTypeResolutionsAreInvalidated = true; + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + moduleResolutionCache.update(resolutionHost.getCompilationSettings()); + typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + const collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = void 0; + return collected; + } + function isFileWithInvalidatedNonRelativeUnresolvedImports(path) { + if (!filesWithInvalidatedNonRelativeUnresolvedImports) { + return false; + } + const value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); + return !!value && !!value.length; + } + function createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidatedLibResolutions) { + invalidateResolutionsOfFailedLookupLocations(); + const collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = void 0; + return { + hasInvalidatedResolutions: (path) => customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path), + hasInvalidatedLibResolutions: (libFileName) => { + var _a; + return customHasInvalidatedLibResolutions(libFileName) || !!((_a = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName)) == null ? void 0 : _a.isInvalidated); + } + }; + } + function startCachingPerDirectoryResolution() { + moduleResolutionCache.isReadonly = void 0; + typeReferenceDirectiveResolutionCache.isReadonly = void 0; + libraryResolutionCache.isReadonly = void 0; + moduleResolutionCache.getPackageJsonInfoCache().isReadonly = void 0; + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + libraryResolutionCache.clearAllExceptPackageJsonInfoCache(); + watchFailedLookupLocationOfNonRelativeModuleResolutions(); + isSymlinkCache.clear(); + } + function cleanupLibResolutionWatching(newProgram) { + resolvedLibraries.forEach((resolution, libFileName) => { + var _a; + if (!((_a = newProgram == null ? void 0 : newProgram.resolvedLibReferences) == null ? void 0 : _a.has(libFileName))) { + stopWatchFailedLookupLocationOfResolution( + resolution, + resolutionHost.toPath(getInferredLibraryNameResolveFrom(resolutionHost.getCompilationSettings(), getCurrentDirectory(), libFileName)), + getResolvedModuleFromResolution + ); + resolvedLibraries.delete(libFileName); + } + }); + } + function finishCachingPerDirectoryResolution(newProgram, oldProgram) { + filesWithInvalidatedNonRelativeUnresolvedImports = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; + watchFailedLookupLocationOfNonRelativeModuleResolutions(); + if (newProgram !== oldProgram) { + cleanupLibResolutionWatching(newProgram); + newProgram == null ? void 0 : newProgram.getSourceFiles().forEach((newFile) => { + var _a; + const expected = ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0; + const existing = impliedFormatPackageJsons.get(newFile.resolvedPath) ?? emptyArray; + for (let i = existing.length; i < expected; i++) { + createFileWatcherOfAffectingLocation( + newFile.packageJsonLocations[i], + /*forResolution*/ + false + ); + } + if (existing.length > expected) { + for (let i = expected; i < existing.length; i++) { + fileWatchesOfAffectingLocations.get(existing[i]).files--; + } + } + if (expected) impliedFormatPackageJsons.set(newFile.resolvedPath, newFile.packageJsonLocations); + else impliedFormatPackageJsons.delete(newFile.resolvedPath); + }); + impliedFormatPackageJsons.forEach((existing, path) => { + const newFile = newProgram == null ? void 0 : newProgram.getSourceFileByPath(path); + if (!newFile || newFile.resolvedPath !== path) { + existing.forEach((location) => fileWatchesOfAffectingLocations.get(location).files--); + impliedFormatPackageJsons.delete(path); + } + }); + } + directoryWatchesOfFailedLookups.forEach(closeDirectoryWatchesOfFailedLookup); + fileWatchesOfAffectingLocations.forEach(closeFileWatcherOfAffectingLocation); + packageDirWatchers.forEach(closePackageDirWatcher); + hasChangedAutomaticTypeDirectiveNames = false; + moduleResolutionCache.isReadonly = true; + typeReferenceDirectiveResolutionCache.isReadonly = true; + libraryResolutionCache.isReadonly = true; + moduleResolutionCache.getPackageJsonInfoCache().isReadonly = true; + isSymlinkCache.clear(); + } + function closePackageDirWatcher(watcher, packageDirPath) { + if (watcher.dirPathToWatcher.size === 0) { + packageDirWatchers.delete(packageDirPath); + } + } + function closeDirectoryWatchesOfFailedLookup(watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + } + function closeFileWatcherOfAffectingLocation(watcher, path) { + var _a; + if (watcher.files === 0 && watcher.resolutions === 0 && !((_a = watcher.symlinks) == null ? void 0 : _a.size)) { + fileWatchesOfAffectingLocations.delete(path); + watcher.watcher.close(); + } + } + function resolveNamesWithLocalCache({ + entries, + containingFile, + containingSourceFile, + redirectedReference, + options, + perFileCache, + reusedNames, + loader, + getResolutionWithResolvedFileName, + deferWatchingNonRelativeResolution, + shouldRetryResolution, + logChanges + }) { + const path = resolutionHost.toPath(containingFile); + const resolutionsInFile = perFileCache.get(path) || perFileCache.set(path, createModeAwareCache()).get(path); + const resolvedModules = []; + const hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + const program = resolutionHost.getCurrentProgram(); + const oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + const unmatchedRedirects = oldRedirect ? !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : !!redirectedReference; + const seenNamesInFile = createModeAwareCache(); + for (const entry of entries) { + const name = loader.nameAndMode.getName(entry); + const mode = loader.nameAndMode.getMode(entry, containingSourceFile, (redirectedReference == null ? void 0 : redirectedReference.commandLine.options) || options); + let resolution = resolutionsInFile.get(name, mode); + if (!seenNamesInFile.has(name, mode) && (allModuleAndTypeResolutionsAreInvalidated || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate + hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { + const existingResolution = resolution; + resolution = loader.resolve(name, mode); + if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { + resolutionHost.onDiscoveredSymlink(); + } + resolutionsInFile.set(name, mode, resolution); + if (resolution !== existingResolution) { + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName); + } + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + logChanges = false; + } + } else { + const host = getModuleResolutionHost(resolutionHost); + if (isTraceEnabled(options, host) && !seenNamesInFile.has(name, mode)) { + const resolved = getResolutionWithResolvedFileName(resolution); + trace( + host, + perFileCache === resolvedModuleNames ? (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved : (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved, + name, + containingFile, + resolved == null ? void 0 : resolved.resolvedFileName, + (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId) + ); + } + } + Debug.assert(resolution !== void 0 && !resolution.isInvalidated); + seenNamesInFile.set(name, mode, true); + resolvedModules.push(resolution); + } + reusedNames == null ? void 0 : reusedNames.forEach( + (entry) => seenNamesInFile.set( + loader.nameAndMode.getName(entry), + loader.nameAndMode.getMode(entry, containingSourceFile, (redirectedReference == null ? void 0 : redirectedReference.commandLine.options) || options), + true + ) + ); + if (resolutionsInFile.size() !== seenNamesInFile.size()) { + resolutionsInFile.forEach((resolution, name, mode) => { + if (!seenNamesInFile.has(name, mode)) { + stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName); + resolutionsInFile.delete(name, mode); + } + }); + } + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution) { + return false; + } + const oldResult = getResolutionWithResolvedFileName(oldResolution); + const newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { + return resolveNamesWithLocalCache({ + entries: typeDirectiveReferences, + containingFile, + containingSourceFile, + redirectedReference, + options, + reusedNames, + perFileCache: resolvedTypeReferenceDirectives, + loader: createTypeReferenceResolutionLoader( + containingFile, + redirectedReference, + options, + getModuleResolutionHost(resolutionHost), + typeReferenceDirectiveResolutionCache + ), + getResolutionWithResolvedFileName: getResolvedTypeReferenceDirectiveFromResolution, + shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0, + deferWatchingNonRelativeResolution: false + }); + } + function resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { + return resolveNamesWithLocalCache({ + entries: moduleLiterals, + containingFile, + containingSourceFile, + redirectedReference, + options, + reusedNames, + perFileCache: resolvedModuleNames, + loader: createModuleResolutionLoaderUsingGlobalCache( + containingFile, + redirectedReference, + options, + resolutionHost, + moduleResolutionCache + ), + getResolutionWithResolvedFileName: getResolvedModuleFromResolution, + shouldRetryResolution: (resolution) => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), + logChanges: logChangesWhenResolvingModule, + deferWatchingNonRelativeResolution: true + // Defer non relative resolution watch because we could be using ambient modules + }); + } + function resolveLibrary2(libraryName, resolveFrom, options, libFileName) { + const host = getModuleResolutionHost(resolutionHost); + let resolution = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName); + if (!resolution || resolution.isInvalidated) { + const existingResolution = resolution; + resolution = resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache); + const path = resolutionHost.toPath(resolveFrom); + watchFailedLookupLocationsOfExternalModuleResolutions( + libraryName, + resolution, + path, + getResolvedModuleFromResolution, + /*deferWatchingNonRelativeResolution*/ + false + ); + resolvedLibraries.set(libFileName, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModuleFromResolution); + } + } else { + if (isTraceEnabled(options, host)) { + const resolved = getResolvedModuleFromResolution(resolution); + trace( + host, + (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, + libraryName, + resolveFrom, + resolved == null ? void 0 : resolved.resolvedFileName, + (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId) + ); + } + } + return resolution; + } + function resolveSingleModuleNameWithoutWatching(moduleName, containingFile) { + var _a, _b; + const path = resolutionHost.toPath(containingFile); + const resolutionsInFile = resolvedModuleNames.get(path); + const resolution = resolutionsInFile == null ? void 0 : resolutionsInFile.get( + moduleName, + /*mode*/ + void 0 + ); + if (resolution && !resolution.isInvalidated) return resolution; + const data = (_a = resolutionHost.beforeResolveSingleModuleNameWithoutWatching) == null ? void 0 : _a.call(resolutionHost, moduleResolutionCache); + const host = getModuleResolutionHost(resolutionHost); + const result = resolveModuleName( + moduleName, + containingFile, + resolutionHost.getCompilationSettings(), + host, + moduleResolutionCache + ); + (_b = resolutionHost.afterResolveSingleModuleNameWithoutWatching) == null ? void 0 : _b.call(resolutionHost, moduleResolutionCache, moduleName, containingFile, result, data); + return result; + } + function isNodeModulesAtTypesDirectory(dirPath) { + return endsWith(dirPath, "/node_modules/@types"); + } + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution) { + (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath); + if (resolution.files.size !== 1) return; + if (!deferWatchingNonRelativeResolution || isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } else { + nonRelativeExternalModuleResolutions.add(resolution); + } + const resolved = getResolutionWithResolvedFileName(resolution); + if (resolved && resolved.resolvedFileName) { + const key = resolutionHost.toPath(resolved.resolvedFileName); + let resolutions = resolvedFileToResolution.get(key); + if (!resolutions) resolvedFileToResolution.set(key, resolutions = /* @__PURE__ */ new Set()); + resolutions.add(resolution); + } + } + function watchFailedLookupLocation(failedLookupLocation, setAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + isRootWatchable, + getCurrentDirectory, + resolutionHost.preferNonRecursiveWatch + ); + if (toWatch) { + const { dir, dirPath, nonRecursive, packageDir, packageDirPath } = toWatch; + if (dirPath === rootPath) { + Debug.assert(nonRecursive); + Debug.assert(!packageDir); + setAtRoot = true; + } else { + setDirectoryWatcher(dir, dirPath, packageDir, packageDirPath, nonRecursive); + } + } + return setAtRoot; + } + function watchFailedLookupLocationOfResolution(resolution) { + var _a; + Debug.assert(!!((_a = resolution.files) == null ? void 0 : _a.size)); + const { failedLookupLocations, affectingLocations, alternateResult } = resolution; + if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !alternateResult) return; + if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || alternateResult) resolutionsWithFailedLookups.add(resolution); + let setAtRoot = false; + if (failedLookupLocations) { + for (const failedLookupLocation of failedLookupLocations) { + setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot); + } + } + if (alternateResult) setAtRoot = watchFailedLookupLocation(alternateResult, setAtRoot); + if (setAtRoot) { + setDirectoryWatcher( + rootDir, + rootPath, + /*packageDir*/ + void 0, + /*packageDirPath*/ + void 0, + /*nonRecursive*/ + true + ); + } + watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !alternateResult); + } + function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { + var _a; + Debug.assert(!!((_a = resolution.files) == null ? void 0 : _a.size)); + const { affectingLocations } = resolution; + if (!(affectingLocations == null ? void 0 : affectingLocations.length)) return; + if (addToResolutionsWithOnlyAffectingLocations) resolutionsWithOnlyAffectingLocations.add(resolution); + for (const affectingLocation of affectingLocations) { + createFileWatcherOfAffectingLocation( + affectingLocation, + /*forResolution*/ + true + ); + } + } + function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { + const fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); + if (fileWatcher) { + if (forResolution) fileWatcher.resolutions++; + else fileWatcher.files++; + return; + } + let locationToWatch = affectingLocation; + let isSymlink = false; + let symlinkWatcher; + if (resolutionHost.realpath) { + locationToWatch = resolutionHost.realpath(affectingLocation); + if (affectingLocation !== locationToWatch) { + isSymlink = true; + symlinkWatcher = fileWatchesOfAffectingLocations.get(locationToWatch); + } + } + const resolutions = forResolution ? 1 : 0; + const files = forResolution ? 0 : 1; + if (!isSymlink || !symlinkWatcher) { + const watcher = { + watcher: canWatchAffectingLocation(resolutionHost.toPath(locationToWatch)) ? resolutionHost.watchAffectingFileLocation(locationToWatch, (fileName, eventKind) => { + cachedDirectoryStructureHost == null ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); + invalidateAffectingFileWatcher(locationToWatch, moduleResolutionCache.getPackageJsonInfoCache().getInternalMap()); + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + }) : noopFileWatcher, + resolutions: isSymlink ? 0 : resolutions, + files: isSymlink ? 0 : files, + symlinks: void 0 + }; + fileWatchesOfAffectingLocations.set(locationToWatch, watcher); + if (isSymlink) symlinkWatcher = watcher; + } + if (isSymlink) { + Debug.assert(!!symlinkWatcher); + const watcher = { + watcher: { + close: () => { + var _a; + const symlinkWatcher2 = fileWatchesOfAffectingLocations.get(locationToWatch); + if (((_a = symlinkWatcher2 == null ? void 0 : symlinkWatcher2.symlinks) == null ? void 0 : _a.delete(affectingLocation)) && !symlinkWatcher2.symlinks.size && !symlinkWatcher2.resolutions && !symlinkWatcher2.files) { + fileWatchesOfAffectingLocations.delete(locationToWatch); + symlinkWatcher2.watcher.close(); + } + } + }, + resolutions, + files, + symlinks: void 0 + }; + fileWatchesOfAffectingLocations.set(affectingLocation, watcher); + (symlinkWatcher.symlinks ?? (symlinkWatcher.symlinks = /* @__PURE__ */ new Set())).add(affectingLocation); + } + } + function invalidateAffectingFileWatcher(path, packageJsonMap) { + var _a; + const watcher = fileWatchesOfAffectingLocations.get(path); + if (watcher == null ? void 0 : watcher.resolutions) (affectingPathChecks ?? (affectingPathChecks = /* @__PURE__ */ new Set())).add(path); + if (watcher == null ? void 0 : watcher.files) (affectingPathChecksForFile ?? (affectingPathChecksForFile = /* @__PURE__ */ new Set())).add(path); + (_a = watcher == null ? void 0 : watcher.symlinks) == null ? void 0 : _a.forEach((path2) => invalidateAffectingFileWatcher(path2, packageJsonMap)); + packageJsonMap == null ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions() { + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfResolution); + nonRelativeExternalModuleResolutions.clear(); + } + function createDirectoryWatcherForPackageDir(dir, dirPath, packageDir, packageDirPath, nonRecursive) { + Debug.assert(!nonRecursive); + let isSymlink = isSymlinkCache.get(packageDirPath); + let packageDirWatcher = packageDirWatchers.get(packageDirPath); + if (isSymlink === void 0) { + const realPath2 = resolutionHost.realpath(packageDir); + isSymlink = realPath2 !== packageDir && resolutionHost.toPath(realPath2) !== packageDirPath; + isSymlinkCache.set(packageDirPath, isSymlink); + if (!packageDirWatcher) { + packageDirWatchers.set( + packageDirPath, + packageDirWatcher = { + dirPathToWatcher: /* @__PURE__ */ new Map(), + isSymlink + } + ); + } else if (packageDirWatcher.isSymlink !== isSymlink) { + packageDirWatcher.dirPathToWatcher.forEach((watcher) => { + removeDirectoryWatcher(packageDirWatcher.isSymlink ? packageDirPath : dirPath); + watcher.watcher = createDirPathToWatcher(); + }); + packageDirWatcher.isSymlink = isSymlink; + } + } else { + Debug.assertIsDefined(packageDirWatcher); + Debug.assert(isSymlink === packageDirWatcher.isSymlink); + } + const forDirPath = packageDirWatcher.dirPathToWatcher.get(dirPath); + if (forDirPath) { + forDirPath.refCount++; + } else { + packageDirWatcher.dirPathToWatcher.set(dirPath, { + watcher: createDirPathToWatcher(), + refCount: 1 + }); + if (isSymlink) dirPathToSymlinkPackageRefCount.set(dirPath, (dirPathToSymlinkPackageRefCount.get(dirPath) ?? 0) + 1); + } + function createDirPathToWatcher() { + return isSymlink ? createOrAddRefToDirectoryWatchOfFailedLookups(packageDir, packageDirPath, nonRecursive) : createOrAddRefToDirectoryWatchOfFailedLookups(dir, dirPath, nonRecursive); + } + } + function setDirectoryWatcher(dir, dirPath, packageDir, packageDirPath, nonRecursive) { + if (!packageDirPath || !resolutionHost.realpath) { + createOrAddRefToDirectoryWatchOfFailedLookups(dir, dirPath, nonRecursive); + } else { + createDirectoryWatcherForPackageDir(dir, dirPath, packageDir, packageDirPath, nonRecursive); + } + } + function createOrAddRefToDirectoryWatchOfFailedLookups(dir, dirPath, nonRecursive) { + let dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); + dirWatcher.refCount++; + } else { + directoryWatchesOfFailedLookups.set(dirPath, dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive }); + } + return dirWatcher; + } + function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + isRootWatchable, + getCurrentDirectory, + resolutionHost.preferNonRecursiveWatch + ); + if (toWatch) { + const { dirPath, packageDirPath } = toWatch; + if (dirPath === rootPath) { + removeAtRoot = true; + } else if (packageDirPath && resolutionHost.realpath) { + const packageDirWatcher = packageDirWatchers.get(packageDirPath); + const forDirPath = packageDirWatcher.dirPathToWatcher.get(dirPath); + forDirPath.refCount--; + if (forDirPath.refCount === 0) { + removeDirectoryWatcher(packageDirWatcher.isSymlink ? packageDirPath : dirPath); + packageDirWatcher.dirPathToWatcher.delete(dirPath); + if (packageDirWatcher.isSymlink) { + const refCount = dirPathToSymlinkPackageRefCount.get(dirPath) - 1; + if (refCount === 0) { + dirPathToSymlinkPackageRefCount.delete(dirPath); + } else { + dirPathToSymlinkPackageRefCount.set(dirPath, refCount); + } + } + } + } else { + removeDirectoryWatcher(dirPath); + } + } + return removeAtRoot; + } + function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { + Debug.checkDefined(resolution.files).delete(filePath); + if (resolution.files.size) return; + resolution.files = void 0; + const resolved = getResolutionWithResolvedFileName(resolution); + if (resolved && resolved.resolvedFileName) { + const key = resolutionHost.toPath(resolved.resolvedFileName); + const resolutions = resolvedFileToResolution.get(key); + if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) resolvedFileToResolution.delete(key); + } + const { failedLookupLocations, affectingLocations, alternateResult } = resolution; + if (resolutionsWithFailedLookups.delete(resolution)) { + let removeAtRoot = false; + if (failedLookupLocations) { + for (const failedLookupLocation of failedLookupLocations) { + removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot); + } + } + if (alternateResult) removeAtRoot = stopWatchFailedLookupLocation(alternateResult, removeAtRoot); + if (removeAtRoot) removeDirectoryWatcher(rootPath); + } else if (affectingLocations == null ? void 0 : affectingLocations.length) { + resolutionsWithOnlyAffectingLocations.delete(resolution); + } + if (affectingLocations) { + for (const affectingLocation of affectingLocations) { + const watcher = fileWatchesOfAffectingLocations.get(affectingLocation); + watcher.resolutions--; + } + } + } + function removeDirectoryWatcher(dirPath) { + const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + dirWatcher.refCount--; + } + function createDirectoryWatcher(directory, dirPath, nonRecursive) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, (fileOrDirectory) => { + const fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath); + }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) { + const resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach( + (resolution) => stopWatchFailedLookupLocationOfResolution( + resolution, + filePath, + getResolutionWithResolvedFileName + ) + ); + cache.delete(filePath); + } + } + function removeResolutionsFromProjectReferenceRedirects(filePath) { + if (!fileExtensionIs(filePath, ".json" /* Json */)) return; + const program = resolutionHost.getCurrentProgram(); + if (!program) return; + const resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) return; + resolvedProjectReference.commandLine.fileNames.forEach((f) => removeResolutionsOfFile(resolutionHost.toPath(f))); + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModuleFromResolution); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirectiveFromResolution); + } + function invalidateResolutions(resolutions, canInvalidate) { + if (!resolutions) return false; + let invalidated = false; + resolutions.forEach((resolution) => { + if (resolution.isInvalidated || !canInvalidate(resolution)) return; + resolution.isInvalidated = invalidated = true; + for (const containingFilePath of Debug.checkDefined(resolution.files)) { + (filesWithInvalidatedResolutions ?? (filesWithInvalidatedResolutions = /* @__PURE__ */ new Set())).add(containingFilePath); + hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || endsWith(containingFilePath, inferredTypesContainingFile); + } + }); + return invalidated; + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + const prevHasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + if (invalidateResolutions(resolvedFileToResolution.get(filePath), returnTrue) && hasChangedAutomaticTypeDirectiveNames && !prevHasChangedAutomaticTypeDirectiveNames) { + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + } + } + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { + Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === void 0); + filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; + } + function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + if (isCreatingWatchedDirectory) { + (isInDirectoryChecks || (isInDirectoryChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); + } else { + const updatedPath = removeIgnoredPath(fileOrDirectoryPath); + if (!updatedPath) return false; + fileOrDirectoryPath = updatedPath; + if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) { + return false; + } + const dirOfFileOrDirectory = getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); + } else { + if (isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + if (fileExtensionIs(fileOrDirectoryPath, ".map")) { + return false; + } + (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); + const packagePath = parseNodeModuleFromPath( + fileOrDirectoryPath, + /*isFolder*/ + true + ); + if (packagePath) (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); + } + } + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + } + function invalidatePackageJsonMap() { + const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); + } + } + function invalidateResolutionsOfFailedLookupLocations() { + var _a; + if (allModuleAndTypeResolutionsAreInvalidated) { + affectingPathChecksForFile = void 0; + invalidatePackageJsonMap(); + if (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks || affectingPathChecks) { + invalidateResolutions(resolvedLibraries, canInvalidateFailedLookupResolution); + } + failedLookupChecks = void 0; + startsWithPathChecks = void 0; + isInDirectoryChecks = void 0; + affectingPathChecks = void 0; + return true; + } + let invalidated = false; + if (affectingPathChecksForFile) { + (_a = resolutionHost.getCurrentProgram()) == null ? void 0 : _a.getSourceFiles().forEach((f) => { + if (some(f.packageJsonLocations, (location) => affectingPathChecksForFile.has(location))) { + (filesWithInvalidatedResolutions ?? (filesWithInvalidatedResolutions = /* @__PURE__ */ new Set())).add(f.path); + invalidated = true; + } + }); + affectingPathChecksForFile = void 0; + } + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) { + return invalidated; + } + invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; + invalidatePackageJsonMap(); + failedLookupChecks = void 0; + startsWithPathChecks = void 0; + isInDirectoryChecks = void 0; + invalidated = invalidateResolutions(resolutionsWithOnlyAffectingLocations, canInvalidatedFailedLookupResolutionWithAffectingLocation) || invalidated; + affectingPathChecks = void 0; + return invalidated; + } + function canInvalidateFailedLookupResolution(resolution) { + var _a; + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) return false; + return ((_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location)))) || !!resolution.alternateResult && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.alternateResult)); + } + function isInvalidatedFailedLookup(locationPath) { + return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], (fileOrDirectoryPath) => startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], (dirPath) => locationPath.length > dirPath.length && startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : void 0); + } + function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { + var _a; + return !!affectingPathChecks && ((_a = resolution.affectingLocations) == null ? void 0 : _a.some((location) => affectingPathChecks.has(location))); + } + function closeTypeRootsWatch() { + clearMap(typeRootsWatches, closeFileWatcher); + } + function createTypeRootsWatch(typeRoot) { + return canWatchTypeRootPath(typeRoot) ? resolutionHost.watchTypeRootsDirectory(typeRoot, (fileOrDirectory) => { + const fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + hasChangedAutomaticTypeDirectiveNames = true; + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + const dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot( + typeRoot, + resolutionHost.toPath(typeRoot), + rootPath, + rootPathComponents, + isRootWatchable, + getCurrentDirectory, + resolutionHost.preferNonRecursiveWatch, + (dirPath2) => directoryWatchesOfFailedLookups.has(dirPath2) || dirPathToSymlinkPackageRefCount.has(dirPath2) + ); + if (dirPath) { + scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath); + } + }, 1 /* Recursive */) : noopFileWatcher; + } + function updateTypeRootsWatch() { + const options = resolutionHost.getCompilationSettings(); + if (options.types) { + closeTypeRootsWatch(); + return; + } + const typeRoots = getEffectiveTypeRoots(options, { getCurrentDirectory }); + if (typeRoots) { + mutateMap( + typeRootsWatches, + new Set(typeRoots), + { + createNewValue: createTypeRootsWatch, + onDeleteValue: closeFileWatcher + } + ); + } else { + closeTypeRootsWatch(); + } + } + function canWatchTypeRootPath(typeRoot) { + if (resolutionHost.getCompilationSettings().typeRoots) return true; + return canWatchAtTypes(resolutionHost.toPath(typeRoot)); + } +} +function resolutionIsSymlink(resolution) { + var _a, _b; + return !!(((_a = resolution.resolvedModule) == null ? void 0 : _a.originalPath) || ((_b = resolution.resolvedTypeReferenceDirective) == null ? void 0 : _b.originalPath)); +} + +// src/compiler/watch.ts +var sysFormatDiagnosticsHost = sys ? { + getCurrentDirectory: () => sys.getCurrentDirectory(), + getNewLine: () => sys.newLine, + getCanonicalFileName: createGetCanonicalFileName(sys.useCaseSensitiveFileNames) +} : void 0; +function createDiagnosticReporter(system, pretty) { + const host = system === sys && sysFormatDiagnosticsHost ? sysFormatDiagnosticsHost : { + getCurrentDirectory: () => system.getCurrentDirectory(), + getNewLine: () => system.newLine, + getCanonicalFileName: createGetCanonicalFileName(system.useCaseSensitiveFileNames) + }; + if (!pretty) { + return (diagnostic) => system.write(formatDiagnostic(diagnostic, host)); + } + const diagnostics = new Array(1); + return (diagnostic) => { + diagnostics[0] = diagnostic; + system.write(formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = void 0; + }; +} +function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && contains(screenStartingMessageCodes, diagnostic.code)) { + system.clearScreen(); + return true; + } + return false; +} +var screenStartingMessageCodes = [ + Diagnostics.Starting_compilation_in_watch_mode.code, + Diagnostics.File_change_detected_Starting_incremental_compilation.code +]; +function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) { + return contains(screenStartingMessageCodes, diagnostic.code) ? newLine + newLine : newLine; +} +function getLocaleTimeString(system) { + return !system.now ? (/* @__PURE__ */ new Date()).toLocaleTimeString() : ( + // On some systems / builds of Node, there's a non-breaking space between the time and AM/PM. + // This branch is solely for testing, so just switch it to a normal space for baseline stability. + // See: + // - https://github.com/nodejs/node/issues/45171 + // - https://github.com/nodejs/node/issues/45753 + system.now().toLocaleTimeString("en-US", { timeZone: "UTC" }).replace("\u202F", " ") + ); +} +function createWatchStatusReporter(system, pretty) { + return pretty ? (diagnostic, newLine, options) => { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); + let output = `[${formatColorAndReset(getLocaleTimeString(system), "\x1B[90m" /* Grey */)}] `; + output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${newLine + newLine}`; + system.write(output); + } : (diagnostic, newLine, options) => { + let output = ""; + if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { + output += newLine; + } + output += `${getLocaleTimeString(system)} - `; + output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${getPlainDiagnosticFollowingNewLines(diagnostic, newLine)}`; + system.write(output); + }; +} +function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) { + const host = system; + host.onUnRecoverableConfigFileDiagnostic = (diagnostic) => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); + const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend); + host.onUnRecoverableConfigFileDiagnostic = void 0; + return result; +} +function getErrorCountForSummary(diagnostics) { + return countWhere(diagnostics, (diagnostic) => diagnostic.category === 1 /* Error */); +} +function getFilesInErrorForSummary(diagnostics) { + const filesInError = filter(diagnostics, (diagnostic) => diagnostic.category === 1 /* Error */).map( + (errorDiagnostic) => { + if (errorDiagnostic.file === void 0) return; + return `${errorDiagnostic.file.fileName}`; + } + ); + return filesInError.map((fileName) => { + if (fileName === void 0) { + return void 0; + } + const diagnosticForFileName = find(diagnostics, (diagnostic) => diagnostic.file !== void 0 && diagnostic.file.fileName === fileName); + if (diagnosticForFileName !== void 0) { + const { line } = getLineAndCharacterOfPosition(diagnosticForFileName.file, diagnosticForFileName.start); + return { + fileName, + line: line + 1 + }; + } + }); +} +function getWatchErrorSummaryDiagnosticMessage(errorCount) { + return errorCount === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes; +} +function prettyPathForFileError(error, cwd) { + const line = formatColorAndReset(":" + error.line, "\x1B[90m" /* Grey */); + if (pathIsAbsolute(error.fileName) && pathIsAbsolute(cwd)) { + return getRelativePathFromDirectory( + cwd, + error.fileName, + /*ignoreCase*/ + false + ) + line; + } + return error.fileName + line; +} +function getErrorSummaryText(errorCount, filesInError, newLine, host) { + if (errorCount === 0) return ""; + const nonNilFiles = filesInError.filter((fileInError) => fileInError !== void 0); + const distinctFileNamesWithLines = nonNilFiles.map((fileInError) => `${fileInError.fileName}:${fileInError.line}`).filter((value, index, self) => self.indexOf(value) === index); + const firstFileReference = nonNilFiles[0] && prettyPathForFileError(nonNilFiles[0], host.getCurrentDirectory()); + let messageAndArgs; + if (errorCount === 1) { + messageAndArgs = filesInError[0] !== void 0 ? [Diagnostics.Found_1_error_in_0, firstFileReference] : [Diagnostics.Found_1_error]; + } else { + messageAndArgs = distinctFileNamesWithLines.length === 0 ? [Diagnostics.Found_0_errors, errorCount] : distinctFileNamesWithLines.length === 1 ? [Diagnostics.Found_0_errors_in_the_same_file_starting_at_Colon_1, errorCount, firstFileReference] : [Diagnostics.Found_0_errors_in_1_files, errorCount, distinctFileNamesWithLines.length]; + } + const d = createCompilerDiagnostic(...messageAndArgs); + const suffix = distinctFileNamesWithLines.length > 1 ? createTabularErrorsDisplay(nonNilFiles, host) : ""; + return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}${suffix}`; +} +function createTabularErrorsDisplay(filesInError, host) { + const distinctFiles = filesInError.filter((value, index, self) => index === self.findIndex((file) => (file == null ? void 0 : file.fileName) === (value == null ? void 0 : value.fileName))); + if (distinctFiles.length === 0) return ""; + const numberLength = (num) => Math.log(num) * Math.LOG10E + 1; + const fileToErrorCount = distinctFiles.map((file) => [file, countWhere(filesInError, (fileInError) => fileInError.fileName === file.fileName)]); + const maxErrors = maxBy(fileToErrorCount, 0, (value) => value[1]); + const headerRow = Diagnostics.Errors_Files.message; + const leftColumnHeadingLength = headerRow.split(" ")[0].length; + const leftPaddingGoal = Math.max(leftColumnHeadingLength, numberLength(maxErrors)); + const headerPadding = Math.max(numberLength(maxErrors) - leftColumnHeadingLength, 0); + let tabularData = ""; + tabularData += " ".repeat(headerPadding) + headerRow + "\n"; + fileToErrorCount.forEach((row) => { + const [file, errorCount] = row; + const errorCountDigitsLength = Math.log(errorCount) * Math.LOG10E + 1 | 0; + const leftPadding = errorCountDigitsLength < leftPaddingGoal ? " ".repeat(leftPaddingGoal - errorCountDigitsLength) : ""; + const fileRef = prettyPathForFileError(file, host.getCurrentDirectory()); + tabularData += `${leftPadding}${errorCount} ${fileRef} +`; + }); + return tabularData; +} +function isBuilderProgram(program) { + return !!program.state; +} +function listFiles(program, write) { + const options = program.getCompilerOptions(); + if (options.explainFiles) { + explainFiles(isBuilderProgram(program) ? program.getProgram() : program, write); + } else if (options.listFiles || options.listFilesOnly) { + forEach(program.getSourceFiles(), (file) => { + write(file.fileName); + }); + } +} +function explainFiles(program, write) { + var _a, _b; + const reasons = program.getFileIncludeReasons(); + const relativeFileName = (fileName) => convertToRelativePath(fileName, program.getCurrentDirectory(), program.getCanonicalFileName); + for (const file of program.getSourceFiles()) { + write(`${toFileName(file, relativeFileName)}`); + (_a = reasons.get(file.path)) == null ? void 0 : _a.forEach((reason) => write(` ${fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText}`)); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, program.getCompilerOptionsForFile(file), relativeFileName)) == null ? void 0 : _b.forEach((d) => write(` ${d.messageText}`)); + } +} +function explainIfFileIsRedirectAndImpliedFormat(file, options, fileNameConvertor) { + var _a; + let result; + if (file.path !== file.resolvedPath) { + (result ?? (result = [])).push(chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.File_is_output_of_project_reference_source_0, + toFileName(file.originalFileName, fileNameConvertor) + )); + } + if (file.redirectInfo) { + (result ?? (result = [])).push(chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.File_redirects_to_file_0, + toFileName(file.redirectInfo.redirectTarget, fileNameConvertor) + )); + } + if (isExternalOrCommonJsModule(file)) { + switch (getImpliedNodeFormatForEmitWorker(file, options)) { + case 99 /* ESNext */: + if (file.packageJsonScope) { + (result ?? (result = [])).push(chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, + toFileName(last(file.packageJsonLocations), fileNameConvertor) + )); + } + break; + case 1 /* CommonJS */: + if (file.packageJsonScope) { + (result ?? (result = [])).push(chainDiagnosticMessages( + /*details*/ + void 0, + file.packageJsonScope.contents.packageJsonContent.type ? Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, + toFileName(last(file.packageJsonLocations), fileNameConvertor) + )); + } else if ((_a = file.packageJsonLocations) == null ? void 0 : _a.length) { + (result ?? (result = [])).push(chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found + )); + } + break; + } + } + return result; +} +function getMatchedFileSpec(program, fileName) { + var _a; + const configFile = program.getCompilerOptions().configFile; + if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedFilesSpec)) return void 0; + const filePath = program.getCanonicalFileName(fileName); + const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); + const index = findIndex(configFile.configFileSpecs.validatedFilesSpec, (fileSpec) => program.getCanonicalFileName(getNormalizedAbsolutePath(fileSpec, basePath)) === filePath); + return index !== -1 ? configFile.configFileSpecs.validatedFilesSpecBeforeSubstitution[index] : void 0; +} +function getMatchedIncludeSpec(program, fileName) { + var _a, _b; + const configFile = program.getCompilerOptions().configFile; + if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedIncludeSpecs)) return void 0; + if (configFile.configFileSpecs.isDefaultIncludeSpec) return true; + const isJsonFile = fileExtensionIs(fileName, ".json" /* Json */); + const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); + const useCaseSensitiveFileNames2 = program.useCaseSensitiveFileNames(); + const index = findIndex((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec) => { + if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) return false; + const pattern = getPatternFromSpec(includeSpec, basePath, "files"); + return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames2).test(fileName); + }); + return index !== -1 ? configFile.configFileSpecs.validatedIncludeSpecsBeforeSubstitution[index] : void 0; +} +function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { + var _a, _b; + const options = program.getCompilerOptions(); + if (isReferencedFile(reason)) { + const referenceLocation = getReferencedFileLocation(program, reason); + const referenceText = isReferenceFileLocation(referenceLocation) ? referenceLocation.file.text.substring(referenceLocation.pos, referenceLocation.end) : `"${referenceLocation.text}"`; + let message; + Debug.assert(isReferenceFileLocation(referenceLocation) || reason.kind === 3 /* Import */, "Only synthetic references are imports"); + switch (reason.kind) { + case 3 /* Import */: + if (isReferenceFileLocation(referenceLocation)) { + message = referenceLocation.packageId ? Diagnostics.Imported_via_0_from_file_1_with_packageId_2 : Diagnostics.Imported_via_0_from_file_1; + } else if (referenceLocation.text === externalHelpersModuleNameText) { + message = referenceLocation.packageId ? Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions : Diagnostics.Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions; + } else { + message = referenceLocation.packageId ? Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions : Diagnostics.Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions; + } + break; + case 4 /* ReferenceFile */: + Debug.assert(!referenceLocation.packageId); + message = Diagnostics.Referenced_via_0_from_file_1; + break; + case 5 /* TypeReferenceDirective */: + message = referenceLocation.packageId ? Diagnostics.Type_library_referenced_via_0_from_file_1_with_packageId_2 : Diagnostics.Type_library_referenced_via_0_from_file_1; + break; + case 7 /* LibReferenceDirective */: + Debug.assert(!referenceLocation.packageId); + message = Diagnostics.Library_referenced_via_0_from_file_1; + break; + default: + Debug.assertNever(reason); + } + return chainDiagnosticMessages( + /*details*/ + void 0, + message, + referenceText, + toFileName(referenceLocation.file, fileNameConvertor), + referenceLocation.packageId && packageIdToString(referenceLocation.packageId) + ); + } + switch (reason.kind) { + case 0 /* RootFile */: + if (!((_a = options.configFile) == null ? void 0 : _a.configFileSpecs)) return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Root_file_specified_for_compilation + ); + const fileName = getNormalizedAbsolutePath(program.getRootFileNames()[reason.index], program.getCurrentDirectory()); + const matchedByFiles = getMatchedFileSpec(program, fileName); + if (matchedByFiles) return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Part_of_files_list_in_tsconfig_json + ); + const matchedByInclude = getMatchedIncludeSpec(program, fileName); + return isString(matchedByInclude) ? chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Matched_by_include_pattern_0_in_1, + matchedByInclude, + toFileName(options.configFile, fileNameConvertor) + ) : ( + // Could be additional files specified as roots or matched by default include + chainDiagnosticMessages( + /*details*/ + void 0, + matchedByInclude ? Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : Diagnostics.Root_file_specified_for_compilation + ) + ); + case 1 /* SourceFromProjectReference */: + case 2 /* OutputFromProjectReference */: + const isOutput = reason.kind === 2 /* OutputFromProjectReference */; + const referencedResolvedRef = Debug.checkDefined((_b = program.getResolvedProjectReferences()) == null ? void 0 : _b[reason.index]); + return chainDiagnosticMessages( + /*details*/ + void 0, + options.outFile ? isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_1_specified : Diagnostics.Source_from_referenced_project_0_included_because_1_specified : isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none : Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none, + toFileName(referencedResolvedRef.sourceFile.fileName, fileNameConvertor), + options.outFile ? "--outFile" : "--out" + ); + case 8 /* AutomaticTypeDirectiveFile */: { + const messageAndArgs = options.types ? reason.packageId ? [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions, reason.typeReference] : reason.packageId ? [Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : [Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference]; + return chainDiagnosticMessages( + /*details*/ + void 0, + ...messageAndArgs + ); + } + case 6 /* LibFile */: { + if (reason.index !== void 0) return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Library_0_specified_in_compilerOptions, + options.lib[reason.index] + ); + const target = getNameOfScriptTarget(getEmitScriptTarget(options)); + const messageAndArgs = target ? [Diagnostics.Default_library_for_target_0, target] : [Diagnostics.Default_library]; + return chainDiagnosticMessages( + /*details*/ + void 0, + ...messageAndArgs + ); + } + default: + Debug.assertNever(reason); + } +} +function toFileName(file, fileNameConvertor) { + const fileName = isString(file) ? file : file.fileName; + return fileNameConvertor ? fileNameConvertor(fileName) : fileName; +} +function emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { + const options = program.getCompilerOptions(); + const allDiagnostics = program.getConfigFileParsingDiagnostics().slice(); + const configFileParsingDiagnosticsLength = allDiagnostics.length; + addRange(allDiagnostics, program.getSyntacticDiagnostics( + /*sourceFile*/ + void 0, + cancellationToken + )); + if (allDiagnostics.length === configFileParsingDiagnosticsLength) { + addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken)); + if (!options.listFilesOnly) { + addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (allDiagnostics.length === configFileParsingDiagnosticsLength) { + addRange(allDiagnostics, program.getSemanticDiagnostics( + /*sourceFile*/ + void 0, + cancellationToken + )); + } + if (options.noEmit && getEmitDeclarations(options) && allDiagnostics.length === configFileParsingDiagnosticsLength) { + addRange(allDiagnostics, program.getDeclarationDiagnostics( + /*sourceFile*/ + void 0, + cancellationToken + )); + } + } + } + const emitResult = options.listFilesOnly ? { emitSkipped: true, diagnostics: emptyArray } : program.emit( + /*targetSourceFile*/ + void 0, + writeFile2, + cancellationToken, + emitOnlyDtsFiles, + customTransformers + ); + addRange(allDiagnostics, emitResult.diagnostics); + const diagnostics = sortAndDeduplicateDiagnostics(allDiagnostics); + diagnostics.forEach(reportDiagnostic); + if (write) { + const currentDir = program.getCurrentDirectory(); + forEach(emitResult.emittedFiles, (file) => { + const filepath = getNormalizedAbsolutePath(file, currentDir); + write(`TSFILE: ${filepath}`); + }); + listFiles(program, write); + } + if (reportSummary) { + reportSummary(getErrorCountForSummary(diagnostics), getFilesInErrorForSummary(diagnostics)); + } + return { + emitResult, + diagnostics + }; +} +function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { + const { emitResult, diagnostics } = emitFilesAndReportErrors( + program, + reportDiagnostic, + write, + reportSummary, + writeFile2, + cancellationToken, + emitOnlyDtsFiles, + customTransformers + ); + if (emitResult.emitSkipped && diagnostics.length > 0) { + return 1 /* DiagnosticsPresent_OutputsSkipped */; + } else if (diagnostics.length > 0) { + return 2 /* DiagnosticsPresent_OutputsGenerated */; + } + return 0 /* Success */; +} +var noopFileWatcher = { close: noop }; +var returnNoopFileWatcher = () => noopFileWatcher; +function createWatchHost(system = sys, reportWatchStatus2) { + const onWatchStatusChange = reportWatchStatus2 || createWatchStatusReporter(system); + return { + onWatchStatusChange, + watchFile: maybeBind(system, system.watchFile) || returnNoopFileWatcher, + watchDirectory: maybeBind(system, system.watchDirectory) || returnNoopFileWatcher, + setTimeout: maybeBind(system, system.setTimeout) || noop, + clearTimeout: maybeBind(system, system.clearTimeout) || noop, + preferNonRecursiveWatch: system.preferNonRecursiveWatch + }; +} +var WatchType = { + ConfigFile: "Config file", + ExtendedConfigFile: "Extended config file", + SourceFile: "Source file", + MissingFile: "Missing file", + WildcardDirectory: "Wild card directory", + FailedLookupLocations: "Failed Lookup Locations", + AffectingFileLocation: "File location affecting resolution", + TypeRoots: "Type roots", + ConfigFileOfReferencedProject: "Config file of referened project", + ExtendedConfigOfReferencedProject: "Extended config file of referenced project", + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", + PackageJson: "package.json file", + ClosedScriptInfo: "Closed Script info", + ConfigFileForInferredRoot: "Config file for the inferred project root", + NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache", + MissingSourceMapFile: "Missing source map file", + NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", + MissingGeneratedFile: "Missing generated file", + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", + TypingInstallerLocationFile: "File location for typing installer", + TypingInstallerLocationDirectory: "Directory location for typing installer" +}; +function createWatchFactory(host, options) { + const watchLogLevel = host.trace ? options.extendedDiagnostics ? 2 /* Verbose */ : options.diagnostics ? 1 /* TriggerOnly */ : 0 /* None */ : 0 /* None */; + const writeLog = watchLogLevel !== 0 /* None */ ? (s) => host.trace(s) : noop; + const result = getWatchFactory(host, watchLogLevel, writeLog); + result.writeLog = writeLog; + return result; +} +function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost = host) { + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); + const compilerHost = { + getSourceFile: createGetSourceFile( + (fileName, encoding) => !encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding), + /*setParentNodes*/ + void 0 + ), + getDefaultLibLocation: maybeBind(host, host.getDefaultLibLocation), + getDefaultLibFileName: (options) => host.getDefaultLibFileName(options), + writeFile: createWriteFileMeasuringIO( + (path, data, writeByteOrderMark) => host.writeFile(path, data, writeByteOrderMark), + (path) => host.createDirectory(path), + (path) => host.directoryExists(path) + ), + getCurrentDirectory: memoize(() => host.getCurrentDirectory()), + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, + getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames2), + getNewLine: () => getNewLineCharacter(getCompilerOptions()), + fileExists: (f) => host.fileExists(f), + readFile: (f) => host.readFile(f), + trace: maybeBind(host, host.trace), + directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: maybeBind(host, host.realpath), + getEnvironmentVariable: maybeBind(host, host.getEnvironmentVariable) || (() => ""), + createHash: maybeBind(host, host.createHash), + readDirectory: maybeBind(host, host.readDirectory), + storeSignatureInfo: host.storeSignatureInfo, + jsDocParsingMode: host.jsDocParsingMode + }; + return compilerHost; +} +function getSourceFileVersionAsHashFromText(host, text) { + if (text.match(sourceMapCommentRegExpDontCareLineStart)) { + let lineEnd = text.length; + let lineStart = lineEnd; + for (let pos = lineEnd - 1; pos >= 0; pos--) { + const ch = text.charCodeAt(pos); + switch (ch) { + case 10 /* lineFeed */: + if (pos && text.charCodeAt(pos - 1) === 13 /* carriageReturn */) { + pos--; + } + // falls through + case 13 /* carriageReturn */: + break; + default: + if (ch < 127 /* maxAsciiCharacter */ || !isLineBreak(ch)) { + lineStart = pos; + continue; + } + break; + } + const line = text.substring(lineStart, lineEnd); + if (line.match(sourceMapCommentRegExp)) { + text = text.substring(0, lineStart); + break; + } else if (!line.match(whitespaceOrMapCommentRegExp)) { + break; + } + lineEnd = lineStart; + } + } + return (host.createHash || generateDjb2Hash)(text); +} +function setGetSourceFileAsHashVersioned(compilerHost) { + const originalGetSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = (...args) => { + const result = originalGetSourceFile.call(compilerHost, ...args); + if (result) { + result.version = getSourceFileVersionAsHashFromText(compilerHost, result.text); + } + return result; + }; +} +function createProgramHost(system, createProgram2) { + const getDefaultLibLocation = memoize(() => getDirectoryPath(normalizePath(system.getExecutingFilePath()))); + return { + useCaseSensitiveFileNames: () => system.useCaseSensitiveFileNames, + getNewLine: () => system.newLine, + getCurrentDirectory: memoize(() => system.getCurrentDirectory()), + getDefaultLibLocation, + getDefaultLibFileName: (options) => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)), + fileExists: (path) => system.fileExists(path), + readFile: (path, encoding) => system.readFile(path, encoding), + directoryExists: (path) => system.directoryExists(path), + getDirectories: (path) => system.getDirectories(path), + readDirectory: (path, extensions, exclude, include, depth) => system.readDirectory(path, extensions, exclude, include, depth), + realpath: maybeBind(system, system.realpath), + getEnvironmentVariable: maybeBind(system, system.getEnvironmentVariable), + trace: (s) => system.write(s + system.newLine), + createDirectory: (path) => system.createDirectory(path), + writeFile: (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark), + createHash: maybeBind(system, system.createHash), + createProgram: createProgram2 || createEmitAndSemanticDiagnosticsBuilderProgram, + storeSignatureInfo: system.storeSignatureInfo, + now: maybeBind(system, system.now) + }; +} +function createWatchCompilerHost(system = sys, createProgram2, reportDiagnostic, reportWatchStatus2) { + const write = (s) => system.write(s + system.newLine); + const result = createProgramHost(system, createProgram2); + copyProperties(result, createWatchHost(system, reportWatchStatus2)); + result.afterProgramCreate = (builderProgram) => { + const compilerOptions = builderProgram.getCompilerOptions(); + const newLine = getNewLineCharacter(compilerOptions); + emitFilesAndReportErrors( + builderProgram, + reportDiagnostic, + write, + (errorCount) => result.onWatchStatusChange( + createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), + newLine, + compilerOptions, + errorCount + ) + ); + }; + return result; +} +function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(1 /* DiagnosticsPresent_OutputsSkipped */); +} +function createWatchCompilerHostOfConfigFile({ + configFileName, + optionsToExtend, + watchOptionsToExtend, + extraFileExtensions, + system, + createProgram: createProgram2, + reportDiagnostic, + reportWatchStatus: reportWatchStatus2 +}) { + const diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + const host = createWatchCompilerHost(system, createProgram2, diagnosticReporter, reportWatchStatus2); + host.onUnRecoverableConfigFileDiagnostic = (diagnostic) => reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + host.watchOptionsToExtend = watchOptionsToExtend; + host.extraFileExtensions = extraFileExtensions; + return host; +} +function createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles, + options, + watchOptions, + projectReferences, + system, + createProgram: createProgram2, + reportDiagnostic, + reportWatchStatus: reportWatchStatus2 +}) { + const host = createWatchCompilerHost(system, createProgram2, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus2); + host.rootFiles = rootFiles; + host.options = options; + host.watchOptions = watchOptions; + host.projectReferences = projectReferences; + return host; +} +function performIncrementalCompilation(input) { + const system = input.system || sys; + const host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); + const builderProgram = createIncrementalProgram(input); + const exitStatus = emitFilesAndReportErrorsAndGetExitStatus( + builderProgram, + input.reportDiagnostic || createDiagnosticReporter(system), + (s) => host.trace && host.trace(s), + input.reportErrorSummary || input.options.pretty ? (errorCount, filesInError) => system.write(getErrorSummaryText(errorCount, filesInError, system.newLine, host)) : void 0 + ); + if (input.afterProgramEmitAndDiagnostics) input.afterProgramEmitAndDiagnostics(builderProgram); + return exitStatus; +} + +// src/compiler/watchPublic.ts +function readBuilderProgram(compilerOptions, host) { + const buildInfoPath = getTsBuildInfoEmitOutputFilePath(compilerOptions); + if (!buildInfoPath) return void 0; + let buildInfo; + if (host.getBuildInfo) { + buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); + } else { + const content = host.readFile(buildInfoPath); + if (!content) return void 0; + buildInfo = getBuildInfo(buildInfoPath, content); + } + if (!buildInfo || buildInfo.version !== version || !isIncrementalBuildInfo(buildInfo)) return void 0; + return createBuilderProgramUsingIncrementalBuildInfo(buildInfo, buildInfoPath, host); +} +function createIncrementalCompilerHost(options, system = sys) { + const host = createCompilerHostWorker( + options, + /*setParentNodes*/ + void 0, + system + ); + host.createHash = maybeBind(system, system.createHash); + host.storeSignatureInfo = system.storeSignatureInfo; + setGetSourceFileAsHashVersioned(host); + changeCompilerHostLikeToUseCache(host, (fileName) => toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName)); + return host; +} +function createIncrementalProgram({ + rootNames, + options, + configFileParsingDiagnostics, + projectReferences, + host, + createProgram: createProgram2 +}) { + host = host || createIncrementalCompilerHost(options); + createProgram2 = createProgram2 || createEmitAndSemanticDiagnosticsBuilderProgram; + const oldProgram = readBuilderProgram(options, host); + return createProgram2(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); +} +function createWatchProgram(host) { + let builderProgram; + let updateLevel; + let missingFilesMap; + let watchedWildcardDirectories; + let staleWatches = /* @__PURE__ */ new Map([[void 0, void 0]]); + let timerToUpdateProgram; + let timerToInvalidateFailedLookupResolutions; + let parsedConfigs; + let sharedExtendedConfigFileWatchers; + let extendedConfigCache = host.extendedConfigCache; + let reportFileChangeDetectedOnCreateProgram = false; + const sourceFilesCache = /* @__PURE__ */ new Map(); + let missingFilePathsRequestedForRelease; + let hasChangedCompilerOptions = false; + const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); + const currentDirectory = host.getCurrentDirectory(); + const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, watchOptionsToExtend, extraFileExtensions, createProgram: createProgram2 } = host; + let { rootFiles: rootFileNames, options: compilerOptions, watchOptions, projectReferences } = host; + let wildcardDirectories; + let configFileParsingDiagnostics; + let canConfigFileJsonReportNoInputFiles = false; + let hasChangedConfigFileParsingErrors = false; + const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames2); + const directoryStructureHost = cachedDirectoryStructureHost || host; + const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host, directoryStructureHost); + let newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } + reportWatchDiagnostic(Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName && !host.configFileParsingResult) { + newLine = getNewLineCharacter(optionsToExtendForConfigFile); + Debug.assert(!rootFileNames); + parseConfigFile2(); + newLine = updateNewLine(); + } + Debug.assert(compilerOptions); + Debug.assert(rootFileNames); + const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(host, compilerOptions); + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); + writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames2}`); + let configFileWatcher; + if (configFileName) { + configFileWatcher = watchFile2(configFileName, scheduleProgramReload, 2e3 /* High */, watchOptions, WatchType.ConfigFile); + } + const compilerHost = createCompilerHostFromProgramHost(host, () => compilerOptions, directoryStructureHost); + setGetSourceFileAsHashVersioned(compilerHost); + const getNewSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = (fileName, ...args) => getVersionedSourceFileByPath(fileName, toPath3(fileName), ...args); + compilerHost.getSourceFileByPath = getVersionedSourceFileByPath; + compilerHost.getNewLine = () => newLine; + compilerHost.fileExists = fileExists; + compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine; + compilerHost.toPath = toPath3; + compilerHost.getCompilationSettings = () => compilerOptions; + compilerHost.useSourceOfProjectReferenceRedirect = maybeBind(host, host.useSourceOfProjectReferenceRedirect); + compilerHost.preferNonRecursiveWatch = host.preferNonRecursiveWatch; + compilerHost.watchDirectoryOfFailedLookupLocation = (dir, cb, flags) => watchDirectory(dir, cb, flags, watchOptions, WatchType.FailedLookupLocations); + compilerHost.watchAffectingFileLocation = (file, cb) => watchFile2(file, cb, 2e3 /* High */, watchOptions, WatchType.AffectingFileLocation); + compilerHost.watchTypeRootsDirectory = (dir, cb, flags) => watchDirectory(dir, cb, flags, watchOptions, WatchType.TypeRoots); + compilerHost.getCachedDirectoryStructureHost = () => cachedDirectoryStructureHost; + compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations; + compilerHost.onInvalidatedResolution = scheduleProgramUpdate; + compilerHost.onChangedAutomaticTypeDirectiveNames = scheduleProgramUpdate; + compilerHost.fileIsOpen = returnFalse; + compilerHost.getCurrentProgram = getCurrentProgram; + compilerHost.writeLog = writeLog; + compilerHost.getParsedCommandLine = getParsedCommandLine; + const resolutionCache = createResolutionCache( + compilerHost, + configFileName ? getDirectoryPath(getNormalizedAbsolutePath(configFileName, currentDirectory)) : currentDirectory, + /*logChangesWhenResolvingModule*/ + false + ); + compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); + compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames); + if (!compilerHost.resolveModuleNameLiterals && !compilerHost.resolveModuleNames) { + compilerHost.resolveModuleNameLiterals = resolutionCache.resolveModuleNameLiterals.bind(resolutionCache); + } + compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); + compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); + if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) { + compilerHost.resolveTypeReferenceDirectiveReferences = resolutionCache.resolveTypeReferenceDirectiveReferences.bind(resolutionCache); + } + compilerHost.resolveLibrary = !host.resolveLibrary ? resolutionCache.resolveLibrary.bind(resolutionCache) : host.resolveLibrary.bind(host); + compilerHost.getModuleResolutionCache = host.resolveModuleNameLiterals || host.resolveModuleNames ? maybeBind(host, host.getModuleResolutionCache) : () => resolutionCache.getModuleResolutionCache(); + const userProvidedResolution = !!host.resolveModuleNameLiterals || !!host.resolveTypeReferenceDirectiveReferences || !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + const customHasInvalidatedResolutions = userProvidedResolution ? maybeBind(host, host.hasInvalidatedResolutions) || returnTrue : returnFalse; + const customHasInvalidLibResolutions = host.resolveLibrary ? maybeBind(host, host.hasInvalidatedLibResolutions) || returnTrue : returnFalse; + builderProgram = readBuilderProgram(compilerOptions, compilerHost); + synchronizeProgram(); + return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close, getResolutionCache } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames, close, getResolutionCache }; + function close() { + clearInvalidateResolutionsOfFailedLookupLocations(); + resolutionCache.clear(); + clearMap(sourceFilesCache, (value) => { + if (value && value.fileWatcher) { + value.fileWatcher.close(); + value.fileWatcher = void 0; + } + }); + if (configFileWatcher) { + configFileWatcher.close(); + configFileWatcher = void 0; + } + extendedConfigCache == null ? void 0 : extendedConfigCache.clear(); + extendedConfigCache = void 0; + if (sharedExtendedConfigFileWatchers) { + clearMap(sharedExtendedConfigFileWatchers, closeFileWatcherOf); + sharedExtendedConfigFileWatchers = void 0; + } + if (watchedWildcardDirectories) { + clearMap(watchedWildcardDirectories, closeFileWatcherOf); + watchedWildcardDirectories = void 0; + } + if (missingFilesMap) { + clearMap(missingFilesMap, closeFileWatcher); + missingFilesMap = void 0; + } + if (parsedConfigs) { + clearMap(parsedConfigs, (config) => { + var _a; + (_a = config.watcher) == null ? void 0 : _a.close(); + config.watcher = void 0; + if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); + config.watchedDirectories = void 0; + }); + parsedConfigs = void 0; + } + builderProgram = void 0; + } + function getResolutionCache() { + return resolutionCache; + } + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgramOrUndefined(); + } + function synchronizeProgram() { + writeLog(`Synchronizing program`); + Debug.assert(compilerOptions); + Debug.assert(rootFileNames); + clearInvalidateResolutionsOfFailedLookupLocations(); + const program = getCurrentBuilderProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.onChangesAffectModuleResolution(); + } + } + const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); + const { + originalReadFile, + originalFileExists, + originalDirectoryExists, + originalCreateDirectory, + originalWriteFile, + readFileWithCache + } = changeCompilerHostLikeToUseCache(compilerHost, toPath3); + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (hasChangedConfigFileParsingErrors) { + if (reportFileChangeDetectedOnCreateProgram) { + reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); + } + builderProgram = createProgram2( + /*rootNames*/ + void 0, + /*options*/ + void 0, + compilerHost, + builderProgram, + configFileParsingDiagnostics, + projectReferences + ); + hasChangedConfigFileParsingErrors = false; + } + } else { + if (reportFileChangeDetectedOnCreateProgram) { + reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); + } + createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions); + } + reportFileChangeDetectedOnCreateProgram = false; + if (host.afterProgramCreate && program !== builderProgram) { + host.afterProgramCreate(builderProgram); + } + compilerHost.readFile = originalReadFile; + compilerHost.fileExists = originalFileExists; + compilerHost.directoryExists = originalDirectoryExists; + compilerHost.createDirectory = originalCreateDirectory; + compilerHost.writeFile = originalWriteFile; + staleWatches == null ? void 0 : staleWatches.forEach((configFile, configPath) => { + if (!configPath) { + watchConfigFileWildCardDirectories(); + if (configFileName) updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); + } else { + const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); + if (config) watchReferencedProject(configFile, configPath, config); + } + }); + staleWatches = void 0; + return builderProgram; + } + function createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions) { + writeLog("CreatingProgramWith::"); + writeLog(` roots: ${JSON.stringify(rootFileNames)}`); + writeLog(` options: ${JSON.stringify(compilerOptions)}`); + if (projectReferences) writeLog(` projectReferences: ${JSON.stringify(projectReferences)}`); + const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); + hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolutions = hasInvalidatedResolutions; + compilerHost.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + const oldProgram = getCurrentProgram(); + builderProgram = createProgram2(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); + resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram); + updateMissingFilePathsWatch( + builderProgram.getProgram(), + missingFilesMap || (missingFilesMap = /* @__PURE__ */ new Map()), + watchMissingFilePath + ); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + for (const missingFilePath of missingFilePathsRequestedForRelease) { + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = void 0; + } + } + function updateRootFileNames(files) { + Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile); + } + function toPath3(fileName) { + return toPath(fileName, currentDirectory, getCanonicalFileName); + } + function isFileMissingOnHost(hostSourceFile) { + return typeof hostSourceFile === "boolean"; + } + function isFilePresenceUnknownOnHost(hostSourceFile) { + return typeof hostSourceFile.version === "boolean"; + } + function fileExists(fileName) { + const path = toPath3(fileName); + if (isFileMissingOnHost(sourceFilesCache.get(path))) { + return false; + } + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { + const hostSourceFile = sourceFilesCache.get(path); + if (isFileMissingOnHost(hostSourceFile)) { + return void 0; + } + const impliedNodeFormat = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions.impliedNodeFormat : void 0; + if (hostSourceFile === void 0 || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile) || hostSourceFile.sourceFile.impliedNodeFormat !== impliedNodeFormat) { + const sourceFile = getNewSourceFile(fileName, languageVersionOrOptions, onError); + if (hostSourceFile) { + if (sourceFile) { + hostSourceFile.sourceFile = sourceFile; + hostSourceFile.version = sourceFile.version; + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(path, fileName, onSourceFileChange, 250 /* Low */, watchOptions, WatchType.SourceFile); + } + } else { + if (hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher.close(); + } + sourceFilesCache.set(path, false); + } + } else { + if (sourceFile) { + const fileWatcher = watchFilePath(path, fileName, onSourceFileChange, 250 /* Low */, watchOptions, WatchType.SourceFile); + sourceFilesCache.set(path, { sourceFile, version: sourceFile.version, fileWatcher }); + } else { + sourceFilesCache.set(path, false); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + } + function nextSourceFileVersion(path) { + const hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== void 0) { + if (isFileMissingOnHost(hostSourceFile)) { + sourceFilesCache.set(path, { version: false }); + } else { + hostSourceFile.version = false; + } + } + } + function getSourceVersion(path, readFileWithCache) { + const hostSourceFile = sourceFilesCache.get(path); + if (!hostSourceFile) return void 0; + if (hostSourceFile.version) return hostSourceFile.version; + const text = readFileWithCache(path); + return text !== void 0 ? getSourceFileVersionAsHashFromText(compilerHost, text) : void 0; + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { + const hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); + if (hostSourceFileInfo !== void 0) { + if (isFileMissingOnHost(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); + } + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (!hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); + } + } + function hasChangedAutomaticTypeDirectiveNames() { + return resolutionCache.hasChangedAutomaticTypeDirectiveNames(); + } + function clearInvalidateResolutionsOfFailedLookupLocations() { + if (!timerToInvalidateFailedLookupResolutions) return false; + host.clearTimeout(timerToInvalidateFailedLookupResolutions); + timerToInvalidateFailedLookupResolutions = void 0; + return true; + } + function scheduleInvalidateResolutionsOfFailedLookupLocations() { + if (!host.setTimeout || !host.clearTimeout) { + return resolutionCache.invalidateResolutionsOfFailedLookupLocations(); + } + const pending = clearInvalidateResolutionsOfFailedLookupLocations(); + writeLog(`Scheduling invalidateFailedLookup${pending ? ", Cancelled earlier one" : ""}`); + timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250, "timerToInvalidateFailedLookupResolutions"); + } + function invalidateResolutionsOfFailedLookup() { + timerToInvalidateFailedLookupResolutions = void 0; + if (resolutionCache.invalidateResolutionsOfFailedLookupLocations()) { + scheduleProgramUpdate(); + } + } + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + writeLog("Scheduling update"); + timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250, "timerToUpdateProgram"); + } + function scheduleProgramReload() { + Debug.assert(!!configFileName); + updateLevel = 2 /* Full */; + scheduleProgramUpdate(); + } + function updateProgramWithWatchStatus() { + timerToUpdateProgram = void 0; + reportFileChangeDetectedOnCreateProgram = true; + updateProgram(); + } + function updateProgram() { + switch (updateLevel) { + case 1 /* RootNamesAndUpdate */: + reloadFileNamesFromConfigFile(); + break; + case 2 /* Full */: + reloadConfigFile(); + break; + default: + synchronizeProgram(); + break; + } + return getCurrentBuilderProgram(); + } + function reloadFileNamesFromConfigFile() { + writeLog("Reloading new file names and options"); + Debug.assert(compilerOptions); + Debug.assert(configFileName); + updateLevel = 0 /* Update */; + rootFileNames = getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions); + if (updateErrorForNoInputFiles( + rootFileNames, + getNormalizedAbsolutePath(configFileName, currentDirectory), + compilerOptions.configFile.configFileSpecs, + configFileParsingDiagnostics, + canConfigFileJsonReportNoInputFiles + )) { + hasChangedConfigFileParsingErrors = true; + } + synchronizeProgram(); + } + function reloadConfigFile() { + Debug.assert(configFileName); + writeLog(`Reloading config file: ${configFileName}`); + updateLevel = 0 /* Update */; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile2(); + hasChangedCompilerOptions = true; + (staleWatches ?? (staleWatches = /* @__PURE__ */ new Map())).set(void 0, void 0); + synchronizeProgram(); + } + function parseConfigFile2() { + Debug.assert(configFileName); + setConfigFileParsingResult( + getParsedCommandLineOfConfigFile( + configFileName, + optionsToExtendForConfigFile, + parseConfigFileHost, + extendedConfigCache || (extendedConfigCache = /* @__PURE__ */ new Map()), + watchOptionsToExtend, + extraFileExtensions + ) + ); + } + function setConfigFileParsingResult(configFileParseResult) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + watchOptions = configFileParseResult.watchOptions; + projectReferences = configFileParseResult.projectReferences; + wildcardDirectories = configFileParseResult.wildcardDirectories; + configFileParsingDiagnostics = getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = canJsonReportNoInputFiles(configFileParseResult.raw); + hasChangedConfigFileParsingErrors = true; + } + function getParsedCommandLine(configFileName2) { + const configPath = toPath3(configFileName2); + let config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); + if (config) { + if (!config.updateLevel) return config.parsedCommandLine; + if (config.parsedCommandLine && config.updateLevel === 1 /* RootNamesAndUpdate */ && !host.getParsedCommandLine) { + writeLog("Reloading new file names and options"); + Debug.assert(compilerOptions); + const fileNames = getFileNamesFromConfigSpecs( + config.parsedCommandLine.options.configFile.configFileSpecs, + getNormalizedAbsolutePath(getDirectoryPath(configFileName2), currentDirectory), + compilerOptions, + parseConfigFileHost + ); + config.parsedCommandLine = { ...config.parsedCommandLine, fileNames }; + config.updateLevel = void 0; + return config.parsedCommandLine; + } + } + writeLog(`Loading config file: ${configFileName2}`); + const parsedCommandLine = host.getParsedCommandLine ? host.getParsedCommandLine(configFileName2) : getParsedCommandLineFromConfigFileHost(configFileName2); + if (config) { + config.parsedCommandLine = parsedCommandLine; + config.updateLevel = void 0; + } else { + (parsedConfigs || (parsedConfigs = /* @__PURE__ */ new Map())).set(configPath, config = { parsedCommandLine }); + } + (staleWatches ?? (staleWatches = /* @__PURE__ */ new Map())).set(configPath, configFileName2); + return parsedCommandLine; + } + function getParsedCommandLineFromConfigFileHost(configFileName2) { + const onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop; + const parsedCommandLine = getParsedCommandLineOfConfigFile( + configFileName2, + /*optionsToExtend*/ + void 0, + parseConfigFileHost, + extendedConfigCache || (extendedConfigCache = /* @__PURE__ */ new Map()), + watchOptionsToExtend + ); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; + return parsedCommandLine; + } + function onReleaseParsedCommandLine(fileName) { + var _a; + const path = toPath3(fileName); + const config = parsedConfigs == null ? void 0 : parsedConfigs.get(path); + if (!config) return; + parsedConfigs.delete(path); + if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); + (_a = config.watcher) == null ? void 0 : _a.close(); + clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); + } + function watchFilePath(path, file, callback, pollingInterval, options, watchType) { + return watchFile2(file, (fileName, eventKind) => callback(fileName, eventKind, path), pollingInterval, options, watchType); + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + if (eventKind === 2 /* Deleted */ && sourceFilesCache.has(path)) { + resolutionCache.invalidateResolutionOfFile(path); + } + nextSourceFileVersion(path); + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchMissingFilePath(missingFilePath, missingFileName) { + return (parsedConfigs == null ? void 0 : parsedConfigs.has(missingFilePath)) ? noopFileWatcher : watchFilePath( + missingFilePath, + missingFileName, + onMissingFileChange, + 500 /* Medium */, + watchOptions, + WatchType.MissingFile + ); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === 0 /* Created */ && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + nextSourceFileVersion(missingFilePath); + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + updateWatchingWildcardDirectories( + watchedWildcardDirectories || (watchedWildcardDirectories = /* @__PURE__ */ new Map()), + wildcardDirectories, + watchWildcardDirectory + ); + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory( + directory, + (fileOrDirectory) => { + Debug.assert(configFileName); + Debug.assert(compilerOptions); + const fileOrDirectoryPath = toPath3(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath3(directory), + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + extraFileExtensions, + options: compilerOptions, + program: getCurrentBuilderProgram() || rootFileNames, + currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + writeLog, + toPath: toPath3 + })) return; + if (updateLevel !== 2 /* Full */) { + updateLevel = 1 /* RootNamesAndUpdate */; + scheduleProgramUpdate(); + } + }, + flags, + watchOptions, + WatchType.WildcardDirectory + ); + } + function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions2, watchType) { + updateSharedExtendedConfigFileWatcher( + forProjectPath, + options, + sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map()), + (extendedConfigFileName, extendedConfigFilePath) => watchFile2( + extendedConfigFileName, + (_fileName, eventKind) => { + var _a; + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + if (extendedConfigCache) cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3); + const projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a.projects; + if (!(projects == null ? void 0 : projects.size)) return; + projects.forEach((projectPath) => { + if (configFileName && toPath3(configFileName) === projectPath) { + updateLevel = 2 /* Full */; + } else { + const config = parsedConfigs == null ? void 0 : parsedConfigs.get(projectPath); + if (config) config.updateLevel = 2 /* Full */; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, + 2e3 /* High */, + watchOptions2, + watchType + ), + toPath3 + ); + } + function watchReferencedProject(configFileName2, configPath, commandLine) { + var _a, _b, _c, _d; + commandLine.watcher || (commandLine.watcher = watchFile2( + configFileName2, + (_fileName, eventKind) => { + updateCachedSystemWithFile(configFileName2, configPath, eventKind); + const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); + if (config) config.updateLevel = 2 /* Full */; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); + scheduleProgramUpdate(); + }, + 2e3 /* High */, + ((_a = commandLine.parsedCommandLine) == null ? void 0 : _a.watchOptions) || watchOptions, + WatchType.ConfigFileOfReferencedProject + )); + updateWatchingWildcardDirectories( + commandLine.watchedDirectories || (commandLine.watchedDirectories = /* @__PURE__ */ new Map()), + (_b = commandLine.parsedCommandLine) == null ? void 0 : _b.wildcardDirectories, + (directory, flags) => { + var _a2; + return watchDirectory( + directory, + (fileOrDirectory) => { + const fileOrDirectoryPath = toPath3(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); + if (!(config == null ? void 0 : config.parsedCommandLine)) return; + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath3(directory), + fileOrDirectory, + fileOrDirectoryPath, + configFileName: configFileName2, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + writeLog, + toPath: toPath3 + })) return; + if (config.updateLevel !== 2 /* Full */) { + config.updateLevel = 1 /* RootNamesAndUpdate */; + scheduleProgramUpdate(); + } + }, + flags, + ((_a2 = commandLine.parsedCommandLine) == null ? void 0 : _a2.watchOptions) || watchOptions, + WatchType.WildcardDirectoryOfReferencedProject + ); + } + ); + updateExtendedConfigFilesWatches( + configPath, + (_c = commandLine.parsedCommandLine) == null ? void 0 : _c.options, + ((_d = commandLine.parsedCommandLine) == null ? void 0 : _d.watchOptions) || watchOptions, + WatchType.ExtendedConfigOfReferencedProject + ); + } +} + +// src/compiler/tsbuild.ts +function resolveConfigFileProjectName(project) { + if (fileExtensionIs(project, ".json" /* Json */)) { + return project; + } + return combinePaths(project, "tsconfig.json"); +} + +// src/compiler/tsbuildPublic.ts +var minimumDate = /* @__PURE__ */ new Date(-864e13); +function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + const existingValue = configFileMap.get(resolved); + let newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.set(resolved, newValue); + } + return existingValue || newValue; +} +function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, () => /* @__PURE__ */ new Map()); +} +function getCurrentTime(host) { + return host.now ? host.now() : /* @__PURE__ */ new Date(); +} +function isCircularBuildOrder(buildOrder) { + return !!buildOrder && !!buildOrder.buildOrder; +} +function getBuildOrderFromAnyBuildOrder(anyBuildOrder) { + return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder; +} +function createBuilderStatusReporter(system, pretty) { + return (diagnostic) => { + let output = pretty ? `[${formatColorAndReset(getLocaleTimeString(system), "\x1B[90m" /* Grey */)}] ` : `${getLocaleTimeString(system)} - `; + output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${system.newLine + system.newLine}`; + system.write(output); + }; +} +function createSolutionBuilderHostBase(system, createProgram2, reportDiagnostic, reportSolutionBuilderStatus) { + const host = createProgramHost(system, createProgram2); + host.getModifiedTime = system.getModifiedTime ? (path) => system.getModifiedTime(path) : returnUndefined; + host.setModifiedTime = system.setModifiedTime ? (path, date) => system.setModifiedTime(path, date) : noop; + host.deleteFile = system.deleteFile ? (path) => system.deleteFile(path) : noop; + host.reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + host.now = maybeBind(system, system.now); + return host; +} +function createSolutionBuilderHost(system = sys, createProgram2, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary2) { + const host = createSolutionBuilderHostBase(system, createProgram2, reportDiagnostic, reportSolutionBuilderStatus); + host.reportErrorSummary = reportErrorSummary2; + return host; +} +function createSolutionBuilderWithWatchHost(system = sys, createProgram2, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus2) { + const host = createSolutionBuilderHostBase(system, createProgram2, reportDiagnostic, reportSolutionBuilderStatus); + const watchHost = createWatchHost(system, reportWatchStatus2); + copyProperties(host, watchHost); + return host; +} +function getCompilerOptionsOfBuildOptions(buildOptions) { + const result = {}; + commonOptionsWithBuild.forEach((option) => { + if (hasProperty(buildOptions, option.name)) result[option.name] = buildOptions[option.name]; + }); + result.tscBuild = true; + return result; +} +function createSolutionBuilder(host, rootNames, defaultOptions) { + return createSolutionBuilderWorker( + /*watch*/ + false, + host, + rootNames, + defaultOptions + ); +} +function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) { + return createSolutionBuilderWorker( + /*watch*/ + true, + host, + rootNames, + defaultOptions, + baseWatchOptions + ); +} +function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { + const host = hostOrHostWithWatch; + const hostWithWatch = hostOrHostWithWatch; + const baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + const compilerHost = createCompilerHostFromProgramHost(host, () => state.projectCompilerOptions); + setGetSourceFileAsHashVersioned(compilerHost); + compilerHost.getParsedCommandLine = (fileName) => parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); + compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); + compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); + compilerHost.resolveLibrary = maybeBind(host, host.resolveLibrary); + compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames); + compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); + compilerHost.getModuleResolutionCache = maybeBind(host, host.getModuleResolutionCache); + let moduleResolutionCache, typeReferenceDirectiveResolutionCache; + if (!compilerHost.resolveModuleNameLiterals && !compilerHost.resolveModuleNames) { + moduleResolutionCache = createModuleResolutionCache(compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName); + compilerHost.resolveModuleNameLiterals = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( + moduleNames, + containingFile, + redirectedReference, + options2, + containingSourceFile, + host, + moduleResolutionCache, + createModuleResolutionLoader + ); + compilerHost.getModuleResolutionCache = () => moduleResolutionCache; + } + if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) { + typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache( + compilerHost.getCurrentDirectory(), + compilerHost.getCanonicalFileName, + /*options*/ + void 0, + moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), + moduleResolutionCache == null ? void 0 : moduleResolutionCache.optionsToRedirectsKey + ); + compilerHost.resolveTypeReferenceDirectiveReferences = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( + typeDirectiveNames, + containingFile, + redirectedReference, + options2, + containingSourceFile, + host, + typeReferenceDirectiveResolutionCache, + createTypeReferenceResolutionLoader + ); + } + let libraryResolutionCache; + if (!compilerHost.resolveLibrary) { + libraryResolutionCache = createModuleResolutionCache( + compilerHost.getCurrentDirectory(), + compilerHost.getCanonicalFileName, + /*options*/ + void 0, + moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache() + ); + compilerHost.resolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary( + libraryName, + resolveFrom, + options2, + host, + libraryResolutionCache + ); + } + compilerHost.getBuildInfo = (fileName, configFilePath) => getBuildInfo3( + state, + fileName, + toResolvedConfigFilePath(state, configFilePath), + /*modifiedTime*/ + void 0 + ); + const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(hostWithWatch, options); + const state = { + host, + hostWithWatch, + parseConfigFileHost: parseConfigHostFromCompilerHostLike(host), + write: maybeBind(host, host.trace), + // State of solution + options, + baseCompilerOptions, + rootNames, + baseWatchOptions, + resolvedConfigFilePaths: /* @__PURE__ */ new Map(), + configFileCache: /* @__PURE__ */ new Map(), + projectStatus: /* @__PURE__ */ new Map(), + extendedConfigCache: /* @__PURE__ */ new Map(), + buildInfoCache: /* @__PURE__ */ new Map(), + outputTimeStamps: /* @__PURE__ */ new Map(), + builderPrograms: /* @__PURE__ */ new Map(), + diagnostics: /* @__PURE__ */ new Map(), + projectPendingBuild: /* @__PURE__ */ new Map(), + projectErrorsReported: /* @__PURE__ */ new Map(), + compilerHost, + moduleResolutionCache, + typeReferenceDirectiveResolutionCache, + libraryResolutionCache, + // Mutable state + buildOrder: void 0, + readFileWithCache: (f) => host.readFile(f), + projectCompilerOptions: baseCompilerOptions, + cache: void 0, + allProjectBuildPending: true, + needsSummary: true, + watchAllProjectsPending: watch, + // Watch state + watch, + allWatchedWildcardDirectories: /* @__PURE__ */ new Map(), + allWatchedInputFiles: /* @__PURE__ */ new Map(), + allWatchedConfigFiles: /* @__PURE__ */ new Map(), + allWatchedExtendedConfigFiles: /* @__PURE__ */ new Map(), + allWatchedPackageJsonFiles: /* @__PURE__ */ new Map(), + filesWatched: /* @__PURE__ */ new Map(), + lastCachedPackageJsonLookups: /* @__PURE__ */ new Map(), + timerToBuildInvalidatedProject: void 0, + reportFileChangeDetected: false, + watchFile: watchFile2, + watchDirectory, + writeLog + }; + return state; +} +function toPath2(state, fileName) { + return toPath(fileName, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName); +} +function toResolvedConfigFilePath(state, fileName) { + const { resolvedConfigFilePaths } = state; + const path = resolvedConfigFilePaths.get(fileName); + if (path !== void 0) return path; + const resolvedPath = toPath2(state, fileName); + resolvedConfigFilePaths.set(fileName, resolvedPath); + return resolvedPath; +} +function isParsedCommandLine(entry) { + return !!entry.options; +} +function getCachedParsedConfigFile(state, configFilePath) { + const value = state.configFileCache.get(configFilePath); + return value && isParsedCommandLine(value) ? value : void 0; +} +function parseConfigFile(state, configFileName, configFilePath) { + const { configFileCache } = state; + const value = configFileCache.get(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : void 0; + } + mark("SolutionBuilder::beforeConfigFileParsing"); + let diagnostic; + const { parseConfigFileHost, baseCompilerOptions, baseWatchOptions, extendedConfigCache, host } = state; + let parsed; + if (host.getParsedCommandLine) { + parsed = host.getParsedCommandLine(configFileName); + if (!parsed) diagnostic = createCompilerDiagnostic(Diagnostics.File_0_not_found, configFileName); + } else { + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = (d) => diagnostic = d; + parsed = getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop; + } + configFileCache.set(configFilePath, parsed || diagnostic); + mark("SolutionBuilder::afterConfigFileParsing"); + measure("SolutionBuilder::Config file parsing", "SolutionBuilder::beforeConfigFileParsing", "SolutionBuilder::afterConfigFileParsing"); + return parsed; +} +function resolveProjectName(state, name) { + return resolveConfigFileProjectName(resolvePath(state.compilerHost.getCurrentDirectory(), name)); +} +function createBuildOrder(state, roots) { + const temporaryMarks = /* @__PURE__ */ new Map(); + const permanentMarks = /* @__PURE__ */ new Map(); + const circularityReportStack = []; + let buildOrder; + let circularDiagnostics; + for (const root of roots) { + visit(root); + } + return circularDiagnostics ? { buildOrder: buildOrder || emptyArray, circularDiagnostics } : buildOrder || emptyArray; + function visit(configFileName, inCircularContext) { + const projPath = toResolvedConfigFilePath(state, configFileName); + if (permanentMarks.has(projPath)) return; + if (temporaryMarks.has(projPath)) { + if (!inCircularContext) { + (circularDiagnostics || (circularDiagnostics = [])).push( + createCompilerDiagnostic( + Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, + circularityReportStack.join("\r\n") + ) + ); + } + return; + } + temporaryMarks.set(projPath, true); + circularityReportStack.push(configFileName); + const parsed = parseConfigFile(state, configFileName, projPath); + if (parsed && parsed.projectReferences) { + for (const ref of parsed.projectReferences) { + const resolvedRefPath = resolveProjectName(state, ref.path); + visit(resolvedRefPath, inCircularContext || ref.circular); + } + } + circularityReportStack.pop(); + permanentMarks.set(projPath, true); + (buildOrder || (buildOrder = [])).push(configFileName); + } +} +function getBuildOrder(state) { + return state.buildOrder || createStateBuildOrder(state); +} +function createStateBuildOrder(state) { + const buildOrder = createBuildOrder(state, state.rootNames.map((f) => resolveProjectName(state, f))); + state.resolvedConfigFilePaths.clear(); + const currentProjects = new Set( + getBuildOrderFromAnyBuildOrder(buildOrder).map( + (resolved) => toResolvedConfigFilePath(state, resolved) + ) + ); + const noopOnDelete = { onDeleteValue: noop }; + mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete); + mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete); + mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete); + mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete); + mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete); + mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete); + mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete); + mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete); + mutateMapSkippingNewValues(state.lastCachedPackageJsonLookups, currentProjects, noopOnDelete); + if (state.watch) { + mutateMapSkippingNewValues( + state.allWatchedConfigFiles, + currentProjects, + { onDeleteValue: closeFileWatcher } + ); + state.allWatchedExtendedConfigFiles.forEach((watcher) => { + watcher.projects.forEach((project) => { + if (!currentProjects.has(project)) { + watcher.projects.delete(project); + } + }); + watcher.close(); + }); + mutateMapSkippingNewValues( + state.allWatchedWildcardDirectories, + currentProjects, + { onDeleteValue: (existingMap) => existingMap.forEach(closeFileWatcherOf) } + ); + mutateMapSkippingNewValues( + state.allWatchedInputFiles, + currentProjects, + { onDeleteValue: (existingMap) => existingMap.forEach(closeFileWatcher) } + ); + mutateMapSkippingNewValues( + state.allWatchedPackageJsonFiles, + currentProjects, + { onDeleteValue: (existingMap) => existingMap.forEach(closeFileWatcher) } + ); + } + return state.buildOrder = buildOrder; +} +function getBuildOrderFor(state, project, onlyReferences) { + const resolvedProject = project && resolveProjectName(state, project); + const buildOrderFromState = getBuildOrder(state); + if (isCircularBuildOrder(buildOrderFromState)) return buildOrderFromState; + if (resolvedProject) { + const projectPath = toResolvedConfigFilePath(state, resolvedProject); + const projectIndex = findIndex( + buildOrderFromState, + (configFileName) => toResolvedConfigFilePath(state, configFileName) === projectPath + ); + if (projectIndex === -1) return void 0; + } + const buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState; + Debug.assert(!isCircularBuildOrder(buildOrder)); + Debug.assert(!onlyReferences || resolvedProject !== void 0); + Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject); + return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder; +} +function enableCache(state) { + if (state.cache) { + disableCache(state); + } + const { compilerHost, host } = state; + const originalReadFileWithCache = state.readFileWithCache; + const originalGetSourceFile = compilerHost.getSourceFile; + const { + originalReadFile, + originalFileExists, + originalDirectoryExists, + originalCreateDirectory, + originalWriteFile, + getSourceFileWithCache, + readFileWithCache + } = changeCompilerHostLikeToUseCache( + host, + (fileName) => toPath2(state, fileName), + (...args) => originalGetSourceFile.call(compilerHost, ...args) + ); + state.readFileWithCache = readFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; + state.cache = { + originalReadFile, + originalFileExists, + originalDirectoryExists, + originalCreateDirectory, + originalWriteFile, + originalReadFileWithCache, + originalGetSourceFile + }; +} +function disableCache(state) { + if (!state.cache) return; + const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache } = state; + host.readFile = cache.originalReadFile; + host.fileExists = cache.originalFileExists; + host.directoryExists = cache.originalDirectoryExists; + host.createDirectory = cache.originalCreateDirectory; + host.writeFile = cache.originalWriteFile; + compilerHost.getSourceFile = cache.originalGetSourceFile; + state.readFileWithCache = cache.originalReadFileWithCache; + extendedConfigCache.clear(); + moduleResolutionCache == null ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache == null ? void 0 : typeReferenceDirectiveResolutionCache.clear(); + libraryResolutionCache == null ? void 0 : libraryResolutionCache.clear(); + state.cache = void 0; +} +function clearProjectStatus(state, resolved) { + state.projectStatus.delete(resolved); + state.diagnostics.delete(resolved); +} +function addProjToQueue({ projectPendingBuild }, proj, updateLevel) { + const value = projectPendingBuild.get(proj); + if (value === void 0) { + projectPendingBuild.set(proj, updateLevel); + } else if (value < updateLevel) { + projectPendingBuild.set(proj, updateLevel); + } +} +function setupInitialBuild(state, cancellationToken) { + if (!state.allProjectBuildPending) return; + state.allProjectBuildPending = false; + if (state.options.watch) reportWatchStatus(state, Diagnostics.Starting_compilation_in_watch_mode); + enableCache(state); + const buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state)); + buildOrder.forEach( + (configFileName) => state.projectPendingBuild.set( + toResolvedConfigFilePath(state, configFileName), + 0 /* Update */ + ) + ); + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } +} +function doneInvalidatedProject(state, projectPath) { + state.projectPendingBuild.delete(projectPath); + return state.diagnostics.has(projectPath) ? 1 /* DiagnosticsPresent_OutputsSkipped */ : 0 /* Success */; +} +function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) { + let updateOutputFileStampsPending = true; + return { + kind: 1 /* UpdateOutputFileStamps */, + project, + projectPath, + buildOrder, + getCompilerOptions: () => config.options, + getCurrentDirectory: () => state.compilerHost.getCurrentDirectory(), + updateOutputFileStatmps: () => { + updateOutputTimestamps(state, config, projectPath); + updateOutputFileStampsPending = false; + }, + done: () => { + if (updateOutputFileStampsPending) { + updateOutputTimestamps(state, config, projectPath); + } + mark("SolutionBuilder::Timestamps only updates"); + return doneInvalidatedProject(state, projectPath); + } + }; +} +function createBuildOrUpdateInvalidedProject(state, project, projectPath, projectIndex, config, status, buildOrder) { + let step = 0 /* CreateProgram */; + let program; + let buildResult; + return { + kind: 0 /* Build */, + project, + projectPath, + buildOrder, + getCompilerOptions: () => config.options, + getCurrentDirectory: () => state.compilerHost.getCurrentDirectory(), + getBuilderProgram: () => withProgramOrUndefined(identity), + getProgram: () => withProgramOrUndefined( + (program2) => program2.getProgramOrUndefined() + ), + getSourceFile: (fileName) => withProgramOrUndefined( + (program2) => program2.getSourceFile(fileName) + ), + getSourceFiles: () => withProgramOrEmptyArray( + (program2) => program2.getSourceFiles() + ), + getOptionsDiagnostics: (cancellationToken) => withProgramOrEmptyArray( + (program2) => program2.getOptionsDiagnostics(cancellationToken) + ), + getGlobalDiagnostics: (cancellationToken) => withProgramOrEmptyArray( + (program2) => program2.getGlobalDiagnostics(cancellationToken) + ), + getConfigFileParsingDiagnostics: () => withProgramOrEmptyArray( + (program2) => program2.getConfigFileParsingDiagnostics() + ), + getSyntacticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray( + (program2) => program2.getSyntacticDiagnostics(sourceFile, cancellationToken) + ), + getAllDependencies: (sourceFile) => withProgramOrEmptyArray( + (program2) => program2.getAllDependencies(sourceFile) + ), + getSemanticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray( + (program2) => program2.getSemanticDiagnostics(sourceFile, cancellationToken) + ), + getSemanticDiagnosticsOfNextAffectedFile: (cancellationToken, ignoreSourceFile) => withProgramOrUndefined( + (program2) => program2.getSemanticDiagnosticsOfNextAffectedFile && program2.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) + ), + emit: (targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) => { + if (targetSourceFile || emitOnlyDtsFiles) { + return withProgramOrUndefined( + (program2) => { + var _a, _b; + return program2.emit(targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project))); + } + ); + } + executeSteps(0 /* CreateProgram */, cancellationToken); + return emit(writeFile2, cancellationToken, customTransformers); + }, + done + }; + function done(cancellationToken, writeFile2, customTransformers) { + executeSteps(3 /* Done */, cancellationToken, writeFile2, customTransformers); + mark("SolutionBuilder::Projects built"); + return doneInvalidatedProject(state, projectPath); + } + function withProgramOrUndefined(action) { + executeSteps(0 /* CreateProgram */); + return program && action(program); + } + function withProgramOrEmptyArray(action) { + return withProgramOrUndefined(action) || emptyArray; + } + function createProgram2() { + var _a, _b, _c; + Debug.assert(program === void 0); + if (state.options.dry) { + reportStatus(state, Diagnostics.A_non_dry_build_would_build_project_0, project); + buildResult = 1 /* Success */; + step = 2 /* QueueReferencingProjects */; + return; + } + if (state.options.verbose) reportStatus(state, Diagnostics.Building_project_0, project); + if (config.fileNames.length === 0) { + reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); + buildResult = 0 /* None */; + step = 2 /* QueueReferencingProjects */; + return; + } + const { host, compilerHost } = state; + state.projectCompilerOptions = config.options; + (_a = state.moduleResolutionCache) == null ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) == null ? void 0 : _b.update(config.options); + program = host.createProgram( + config.fileNames, + config.options, + compilerHost, + getOldProgram(state, projectPath, config), + getConfigFileParsingDiagnostics(config), + config.projectReferences + ); + if (state.watch) { + const internalMap = (_c = state.moduleResolutionCache) == null ? void 0 : _c.getPackageJsonInfoCache().getInternalMap(); + state.lastCachedPackageJsonLookups.set( + projectPath, + internalMap && new Set(arrayFrom( + internalMap.values(), + (data) => state.host.realpath && (isPackageJsonInfo(data) || data.directoryExists) ? state.host.realpath(combinePaths(data.packageDirectory, "package.json")) : combinePaths(data.packageDirectory, "package.json") + )) + ); + state.builderPrograms.set(projectPath, program); + } + step++; + } + function emit(writeFileCallback, cancellationToken, customTransformers) { + var _a, _b, _c; + Debug.assertIsDefined(program); + Debug.assert(step === 1 /* Emit */); + const { host, compilerHost } = state; + const emittedOutputs = /* @__PURE__ */ new Map(); + const options = program.getCompilerOptions(); + const isIncremental = isIncrementalCompilation(options); + let outputTimeStampMap; + let now; + const { emitResult, diagnostics } = emitFilesAndReportErrors( + program, + (d) => host.reportDiagnostic(d), + state.write, + /*reportSummary*/ + void 0, + (name, text, writeByteOrderMark, onError, sourceFiles, data) => { + var _a2; + const path = toPath2(state, name); + emittedOutputs.set(toPath2(state, name), name); + if (data == null ? void 0 : data.buildInfo) { + now || (now = getCurrentTime(state.host)); + const isChangedSignature2 = (_a2 = program.hasChangedEmitSignature) == null ? void 0 : _a2.call(program); + const existing = getBuildInfoCacheEntry(state, name, projectPath); + if (existing) { + existing.buildInfo = data.buildInfo; + existing.modifiedTime = now; + if (isChangedSignature2) existing.latestChangedDtsTime = now; + } else { + state.buildInfoCache.set(projectPath, { + path: toPath2(state, name), + buildInfo: data.buildInfo, + modifiedTime: now, + latestChangedDtsTime: isChangedSignature2 ? now : void 0 + }); + } + } + const modifiedTime = (data == null ? void 0 : data.differsOnlyInMap) ? getModifiedTime(state.host, name) : void 0; + (writeFileCallback || compilerHost.writeFile)( + name, + text, + writeByteOrderMark, + onError, + sourceFiles, + data + ); + if (data == null ? void 0 : data.differsOnlyInMap) state.host.setModifiedTime(name, modifiedTime); + else if (!isIncremental && state.watch) { + (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); + } + }, + cancellationToken, + /*emitOnlyDtsFiles*/ + void 0, + customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project)) + ); + if ((!options.noEmitOnError || !diagnostics.length) && (emittedOutputs.size || status.type !== 8 /* OutOfDateBuildInfoWithErrors */)) { + updateOutputTimestampsWorker(state, config, projectPath, Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + } + state.projectErrorsReported.set(projectPath, true); + buildResult = ((_c = program.hasChangedEmitSignature) == null ? void 0 : _c.call(program)) ? 0 /* None */ : 2 /* DeclarationOutputUnchanged */; + if (!diagnostics.length) { + state.diagnostics.delete(projectPath); + state.projectStatus.set(projectPath, { + type: 1 /* UpToDate */, + oldestOutputFileName: firstOrUndefinedIterator(emittedOutputs.values()) ?? getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()) + }); + } else { + state.diagnostics.set(projectPath, diagnostics); + state.projectStatus.set(projectPath, { type: 0 /* Unbuildable */, reason: `it had errors` }); + buildResult |= 4 /* AnyErrors */; + } + afterProgramDone(state, program); + step = 2 /* QueueReferencingProjects */; + return emitResult; + } + function executeSteps(till, cancellationToken, writeFile2, customTransformers) { + while (step <= till && step < 3 /* Done */) { + const currentStep = step; + switch (step) { + case 0 /* CreateProgram */: + createProgram2(); + break; + case 1 /* Emit */: + emit(writeFile2, cancellationToken, customTransformers); + break; + case 2 /* QueueReferencingProjects */: + queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, Debug.checkDefined(buildResult)); + step++; + break; + // Should never be done + case 3 /* Done */: + default: + assertType(step); + } + Debug.assert(step > currentStep); + } + } +} +function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { + if (!state.projectPendingBuild.size) return void 0; + if (isCircularBuildOrder(buildOrder)) return void 0; + const { options, projectPendingBuild } = state; + for (let projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { + const project = buildOrder[projectIndex]; + const projectPath = toResolvedConfigFilePath(state, project); + const updateLevel = state.projectPendingBuild.get(projectPath); + if (updateLevel === void 0) continue; + if (reportQueue) { + reportQueue = false; + reportBuildQueue(state, buildOrder); + } + const config = parseConfigFile(state, project, projectPath); + if (!config) { + reportParseConfigFileDiagnostic(state, projectPath); + projectPendingBuild.delete(projectPath); + continue; + } + if (updateLevel === 2 /* Full */) { + watchConfigFile(state, project, projectPath, config); + watchExtendedConfigFiles(state, projectPath, config); + watchWildCardDirectories(state, project, projectPath, config); + watchInputFiles(state, project, projectPath, config); + watchPackageJsonFiles(state, project, projectPath, config); + } else if (updateLevel === 1 /* RootNamesAndUpdate */) { + config.fileNames = getFileNamesFromConfigSpecs(config.options.configFile.configFileSpecs, getDirectoryPath(project), config.options, state.parseConfigFileHost); + updateErrorForNoInputFiles( + config.fileNames, + project, + config.options.configFile.configFileSpecs, + config.errors, + canJsonReportNoInputFiles(config.raw) + ); + watchInputFiles(state, project, projectPath, config); + watchPackageJsonFiles(state, project, projectPath, config); + } + const status = getUpToDateStatus(state, config, projectPath); + if (!options.force) { + if (status.type === 1 /* UpToDate */) { + verboseReportProjectStatus(state, project, status); + reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); + projectPendingBuild.delete(projectPath); + if (options.dry) { + reportStatus(state, Diagnostics.Project_0_is_up_to_date, project); + } + continue; + } + if (status.type === 2 /* UpToDateWithUpstreamTypes */ || status.type === 15 /* UpToDateWithInputFileText */) { + reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); + return { + kind: 1 /* UpdateOutputFileStamps */, + status, + project, + projectPath, + projectIndex, + config + }; + } + } + if (status.type === 12 /* UpstreamBlocked */) { + verboseReportProjectStatus(state, project, status); + reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); + projectPendingBuild.delete(projectPath); + if (options.verbose) { + reportStatus( + state, + status.upstreamProjectBlocked ? Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built : Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, + project, + status.upstreamProjectName + ); + } + continue; + } + if (status.type === 16 /* ContainerOnly */) { + verboseReportProjectStatus(state, project, status); + reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); + projectPendingBuild.delete(projectPath); + continue; + } + return { + kind: 0 /* Build */, + status, + project, + projectPath, + projectIndex, + config + }; + } + return void 0; +} +function createInvalidatedProjectWithInfo(state, info, buildOrder) { + verboseReportProjectStatus(state, info.project, info.status); + return info.kind !== 1 /* UpdateOutputFileStamps */ ? createBuildOrUpdateInvalidedProject( + state, + info.project, + info.projectPath, + info.projectIndex, + info.config, + info.status, + buildOrder + ) : createUpdateOutputFileStampsProject( + state, + info.project, + info.projectPath, + info.config, + buildOrder + ); +} +function getNextInvalidatedProject(state, buildOrder, reportQueue) { + const info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); + if (!info) return info; + return createInvalidatedProjectWithInfo(state, info, buildOrder); +} +function getOldProgram({ options, builderPrograms, compilerHost }, proj, parsed) { + if (options.force) return void 0; + const value = builderPrograms.get(proj); + if (value) return value; + return readBuilderProgram(parsed.options, compilerHost); +} +function afterProgramDone(state, program) { + if (program) { + if (state.host.afterProgramEmitAndDiagnostics) { + state.host.afterProgramEmitAndDiagnostics(program); + } + program.releaseProgram(); + } + state.projectCompilerOptions = state.baseCompilerOptions; +} +function isFileWatcherWithModifiedTime(value) { + return !!value.watcher; +} +function getModifiedTime2(state, fileName) { + const path = toPath2(state, fileName); + const existing = state.filesWatched.get(path); + if (state.watch && !!existing) { + if (!isFileWatcherWithModifiedTime(existing)) return existing; + if (existing.modifiedTime) return existing.modifiedTime; + } + const result = getModifiedTime(state.host, fileName); + if (state.watch) { + if (existing) existing.modifiedTime = result; + else state.filesWatched.set(path, result); + } + return result; +} +function watchFile(state, file, callback, pollingInterval, options, watchType, project) { + const path = toPath2(state, file); + const existing = state.filesWatched.get(path); + if (existing && isFileWatcherWithModifiedTime(existing)) { + existing.callbacks.push(callback); + } else { + const watcher = state.watchFile( + file, + (fileName, eventKind, modifiedTime) => { + const existing2 = Debug.checkDefined(state.filesWatched.get(path)); + Debug.assert(isFileWatcherWithModifiedTime(existing2)); + existing2.modifiedTime = modifiedTime; + existing2.callbacks.forEach((cb) => cb(fileName, eventKind, modifiedTime)); + }, + pollingInterval, + options, + watchType, + project + ); + state.filesWatched.set(path, { callbacks: [callback], watcher, modifiedTime: existing }); + } + return { + close: () => { + const existing2 = Debug.checkDefined(state.filesWatched.get(path)); + Debug.assert(isFileWatcherWithModifiedTime(existing2)); + if (existing2.callbacks.length === 1) { + state.filesWatched.delete(path); + closeFileWatcherOf(existing2); + } else { + unorderedRemoveItem(existing2.callbacks, callback); + } + } + }; +} +function getOutputTimeStampMap(state, resolvedConfigFilePath) { + if (!state.watch) return void 0; + let result = state.outputTimeStamps.get(resolvedConfigFilePath); + if (!result) state.outputTimeStamps.set(resolvedConfigFilePath, result = /* @__PURE__ */ new Map()); + return result; +} +function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) { + const path = toPath2(state, buildInfoPath); + const existing = state.buildInfoCache.get(resolvedConfigPath); + return (existing == null ? void 0 : existing.path) === path ? existing : void 0; +} +function getBuildInfo3(state, buildInfoPath, resolvedConfigPath, modifiedTime) { + const path = toPath2(state, buildInfoPath); + const existing = state.buildInfoCache.get(resolvedConfigPath); + if (existing !== void 0 && existing.path === path) { + return existing.buildInfo || void 0; + } + const value = state.readFileWithCache(buildInfoPath); + const buildInfo = value ? getBuildInfo(buildInfoPath, value) : void 0; + state.buildInfoCache.set(resolvedConfigPath, { path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || missingFileModifiedTime }); + return buildInfo; +} +function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { + const tsconfigTime = getModifiedTime2(state, configFile); + if (oldestOutputFileTime < tsconfigTime) { + return { + type: 5 /* OutOfDateWithSelf */, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: configFile + }; + } +} +function getUpToDateStatusWorker(state, project, resolvedPath) { + var _a, _b, _c, _d, _e; + if (isSolutionConfig(project)) return { type: 16 /* ContainerOnly */ }; + let referenceStatuses; + const force = !!state.options.force; + if (project.projectReferences) { + state.projectStatus.set(resolvedPath, { type: 13 /* ComputingUpstream */ }); + for (const ref of project.projectReferences) { + const resolvedRef = resolveProjectReferencePath(ref); + const resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); + const resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath); + const refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); + if (refStatus.type === 13 /* ComputingUpstream */ || refStatus.type === 16 /* ContainerOnly */) { + continue; + } + if (state.options.stopBuildOnErrors && (refStatus.type === 0 /* Unbuildable */ || refStatus.type === 12 /* UpstreamBlocked */)) { + return { + type: 12 /* UpstreamBlocked */, + upstreamProjectName: ref.path, + upstreamProjectBlocked: refStatus.type === 12 /* UpstreamBlocked */ + }; + } + if (!force) (referenceStatuses || (referenceStatuses = [])).push({ ref, refStatus, resolvedRefPath, resolvedConfig }); + } + } + if (force) return { type: 17 /* ForceBuild */ }; + const { host } = state; + const buildInfoPath = getTsBuildInfoEmitOutputFilePath(project.options); + const isIncremental = isIncrementalCompilation(project.options); + let buildInfoCacheEntry = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); + const buildInfoTime = (buildInfoCacheEntry == null ? void 0 : buildInfoCacheEntry.modifiedTime) || getModifiedTime(host, buildInfoPath); + if (buildInfoTime === missingFileModifiedTime) { + if (!buildInfoCacheEntry) { + state.buildInfoCache.set(resolvedPath, { + path: toPath2(state, buildInfoPath), + buildInfo: false, + modifiedTime: buildInfoTime + }); + } + return { + type: 3 /* OutputMissing */, + missingOutputFileName: buildInfoPath + }; + } + const buildInfo = getBuildInfo3(state, buildInfoPath, resolvedPath, buildInfoTime); + if (!buildInfo) { + return { + type: 4 /* ErrorReadingFile */, + fileName: buildInfoPath + }; + } + const incrementalBuildInfo = isIncremental && isIncrementalBuildInfo(buildInfo) ? buildInfo : void 0; + if ((incrementalBuildInfo || !isIncremental) && buildInfo.version !== version) { + return { + type: 14 /* TsVersionOutputOfDate */, + version: buildInfo.version + }; + } + if (!project.options.noCheck && (buildInfo.errors || // TODO: syntax errors???? + buildInfo.checkPending)) { + return { + type: 8 /* OutOfDateBuildInfoWithErrors */, + buildInfoFile: buildInfoPath + }; + } + if (incrementalBuildInfo) { + if (!project.options.noCheck && (((_a = incrementalBuildInfo.changeFileSet) == null ? void 0 : _a.length) || ((_b = incrementalBuildInfo.semanticDiagnosticsPerFile) == null ? void 0 : _b.length) || getEmitDeclarations(project.options) && ((_c = incrementalBuildInfo.emitDiagnosticsPerFile) == null ? void 0 : _c.length))) { + return { + type: 8 /* OutOfDateBuildInfoWithErrors */, + buildInfoFile: buildInfoPath + }; + } + if (!project.options.noEmit && (((_d = incrementalBuildInfo.changeFileSet) == null ? void 0 : _d.length) || ((_e = incrementalBuildInfo.affectedFilesPendingEmit) == null ? void 0 : _e.length) || incrementalBuildInfo.pendingEmit !== void 0)) { + return { + type: 7 /* OutOfDateBuildInfoWithPendingEmit */, + buildInfoFile: buildInfoPath + }; + } + if ((!project.options.noEmit || project.options.noEmit && getEmitDeclarations(project.options)) && getPendingEmitKindWithSeen( + project.options, + incrementalBuildInfo.options || {}, + /*emitOnlyDtsFiles*/ + void 0, + !!project.options.noEmit + )) { + return { + type: 9 /* OutOfDateOptions */, + buildInfoFile: buildInfoPath + }; + } + } + let oldestOutputFileTime = buildInfoTime; + let oldestOutputFileName = buildInfoPath; + let newestInputFileName = void 0; + let newestInputFileTime = minimumDate; + let pseudoInputUpToDate = false; + const seenRoots = /* @__PURE__ */ new Set(); + let buildInfoVersionMap; + for (const inputFile of project.fileNames) { + const inputTime = getModifiedTime2(state, inputFile); + if (inputTime === missingFileModifiedTime) { + return { + type: 0 /* Unbuildable */, + reason: `${inputFile} does not exist` + }; + } + const inputPath = toPath2(state, inputFile); + if (buildInfoTime < inputTime) { + let version2; + let currentVersion; + if (incrementalBuildInfo) { + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(incrementalBuildInfo, buildInfoPath, host); + const resolvedInputPath = buildInfoVersionMap.roots.get(inputPath); + version2 = buildInfoVersionMap.fileInfos.get(resolvedInputPath ?? inputPath); + const text = version2 ? state.readFileWithCache(resolvedInputPath ?? inputFile) : void 0; + currentVersion = text !== void 0 ? getSourceFileVersionAsHashFromText(host, text) : void 0; + if (version2 && version2 === currentVersion) pseudoInputUpToDate = true; + } + if (!version2 || version2 !== currentVersion) { + return { + type: 5 /* OutOfDateWithSelf */, + outOfDateOutputFileName: buildInfoPath, + newerInputFileName: inputFile + }; + } + } + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + seenRoots.add(inputPath); + } + let existingRoot; + if (incrementalBuildInfo) { + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(incrementalBuildInfo, buildInfoPath, host); + existingRoot = forEachEntry( + buildInfoVersionMap.roots, + // File was root file when project was built but its not any more + (_resolved, existingRoot2) => !seenRoots.has(existingRoot2) ? existingRoot2 : void 0 + ); + } else { + existingRoot = forEach( + getNonIncrementalBuildInfoRoots(buildInfo, buildInfoPath, host), + (root) => !seenRoots.has(root) ? root : void 0 + ); + } + if (existingRoot) { + return { + type: 10 /* OutOfDateRoots */, + buildInfoFile: buildInfoPath, + inputFile: existingRoot + }; + } + if (!isIncremental) { + const outputs = getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); + const outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath); + for (const output of outputs) { + if (output === buildInfoPath) continue; + const path = toPath2(state, output); + let outputTime = outputTimeStampMap == null ? void 0 : outputTimeStampMap.get(path); + if (!outputTime) { + outputTime = getModifiedTime(state.host, output); + outputTimeStampMap == null ? void 0 : outputTimeStampMap.set(path, outputTime); + } + if (outputTime === missingFileModifiedTime) { + return { + type: 3 /* OutputMissing */, + missingOutputFileName: output + }; + } + if (outputTime < newestInputFileTime) { + return { + type: 5 /* OutOfDateWithSelf */, + outOfDateOutputFileName: output, + newerInputFileName: newestInputFileName + }; + } + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + } + } + let pseudoUpToDate = false; + if (referenceStatuses) { + for (const { ref, refStatus, resolvedConfig, resolvedRefPath } of referenceStatuses) { + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + if (hasSameBuildInfo(state, buildInfoCacheEntry ?? (buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath)), resolvedRefPath)) { + return { + type: 6 /* OutOfDateWithUpstream */, + outOfDateOutputFileName: buildInfoPath, + newerProjectName: ref.path + }; + } + const newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath); + if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + continue; + } + Debug.assert(oldestOutputFileName !== void 0, "Should have an oldest output filename here"); + return { + type: 6 /* OutOfDateWithUpstream */, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + const configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) return configStatus; + const extendedConfigStatus = forEach(project.options.configFile.extendedSourceFiles || emptyArray, (configFile) => checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName)); + if (extendedConfigStatus) return extendedConfigStatus; + const packageJsonLookups = state.lastCachedPackageJsonLookups.get(resolvedPath); + const dependentPackageFileStatus = packageJsonLookups && forEachKey( + packageJsonLookups, + (path) => checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName) + ); + if (dependentPackageFileStatus) return dependentPackageFileStatus; + return { + type: pseudoUpToDate ? 2 /* UpToDateWithUpstreamTypes */ : pseudoInputUpToDate ? 15 /* UpToDateWithInputFileText */ : 1 /* UpToDate */, + newestInputFileTime, + newestInputFileName, + oldestOutputFileName + }; +} +function hasSameBuildInfo(state, buildInfoCacheEntry, resolvedRefPath) { + const refBuildInfo = state.buildInfoCache.get(resolvedRefPath); + return refBuildInfo.path === buildInfoCacheEntry.path; +} +function getUpToDateStatus(state, project, resolvedPath) { + if (project === void 0) { + return { type: 0 /* Unbuildable */, reason: "config file deleted mid-build" }; + } + const prior = state.projectStatus.get(resolvedPath); + if (prior !== void 0) { + return prior; + } + mark("SolutionBuilder::beforeUpToDateCheck"); + const actual = getUpToDateStatusWorker(state, project, resolvedPath); + mark("SolutionBuilder::afterUpToDateCheck"); + measure("SolutionBuilder::Up-to-date check", "SolutionBuilder::beforeUpToDateCheck", "SolutionBuilder::afterUpToDateCheck"); + state.projectStatus.set(resolvedPath, actual); + return actual; +} +function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { + if (proj.options.noEmit) return; + let now; + const buildInfoPath = getTsBuildInfoEmitOutputFilePath(proj.options); + const isIncremental = isIncrementalCompilation(proj.options); + if (buildInfoPath && isIncremental) { + if (!(skipOutputs == null ? void 0 : skipOutputs.has(toPath2(state, buildInfoPath)))) { + if (!!state.options.verbose) reportStatus(state, verboseMessage, proj.options.configFilePath); + state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); + getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + } + state.outputTimeStamps.delete(projectPath); + return; + } + const { host } = state; + const outputs = getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); + const outputTimeStampMap = getOutputTimeStampMap(state, projectPath); + const modifiedOutputs = outputTimeStampMap ? /* @__PURE__ */ new Set() : void 0; + if (!skipOutputs || outputs.length !== skipOutputs.size) { + let reportVerbose = !!state.options.verbose; + for (const file of outputs) { + const path = toPath2(state, file); + if (skipOutputs == null ? void 0 : skipOutputs.has(path)) continue; + if (reportVerbose) { + reportVerbose = false; + reportStatus(state, verboseMessage, proj.options.configFilePath); + } + host.setModifiedTime(file, now || (now = getCurrentTime(state.host))); + if (file === buildInfoPath) getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + else if (outputTimeStampMap) { + outputTimeStampMap.set(path, now); + modifiedOutputs.add(path); + } + } + } + outputTimeStampMap == null ? void 0 : outputTimeStampMap.forEach((_value, key) => { + if (!(skipOutputs == null ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) outputTimeStampMap.delete(key); + }); +} +function getLatestChangedDtsTime(state, options, resolvedConfigPath) { + if (!options.composite) return void 0; + const entry = Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); + if (entry.latestChangedDtsTime !== void 0) return entry.latestChangedDtsTime || void 0; + const latestChangedDtsTime = entry.buildInfo && isIncrementalBuildInfo(entry.buildInfo) && entry.buildInfo.latestChangedDtsFile ? state.host.getModifiedTime(getNormalizedAbsolutePath(entry.buildInfo.latestChangedDtsFile, getDirectoryPath(entry.path))) : void 0; + entry.latestChangedDtsTime = latestChangedDtsTime || false; + return latestChangedDtsTime; +} +function updateOutputTimestamps(state, proj, resolvedPath) { + if (state.options.dry) { + return reportStatus(state, Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath); + } + updateOutputTimestampsWorker(state, proj, resolvedPath, Diagnostics.Updating_output_timestamps_of_project_0); + state.projectStatus.set(resolvedPath, { + type: 1 /* UpToDate */, + oldestOutputFileName: getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()) + }); +} +function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) { + if (state.options.stopBuildOnErrors && buildResult & 4 /* AnyErrors */) return; + if (!config.options.composite) return; + for (let index = projectIndex + 1; index < buildOrder.length; index++) { + const nextProject = buildOrder[index]; + const nextProjectPath = toResolvedConfigFilePath(state, nextProject); + if (state.projectPendingBuild.has(nextProjectPath)) continue; + const nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath); + if (!nextProjectConfig || !nextProjectConfig.projectReferences) continue; + for (const ref of nextProjectConfig.projectReferences) { + const resolvedRefPath = resolveProjectName(state, ref.path); + if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath) continue; + const status = state.projectStatus.get(nextProjectPath); + if (status) { + switch (status.type) { + case 1 /* UpToDate */: + if (buildResult & 2 /* DeclarationOutputUnchanged */) { + status.type = 2 /* UpToDateWithUpstreamTypes */; + break; + } + // falls through + case 15 /* UpToDateWithInputFileText */: + case 2 /* UpToDateWithUpstreamTypes */: + if (!(buildResult & 2 /* DeclarationOutputUnchanged */)) { + state.projectStatus.set(nextProjectPath, { + type: 6 /* OutOfDateWithUpstream */, + outOfDateOutputFileName: status.oldestOutputFileName, + newerProjectName: project + }); + } + break; + case 12 /* UpstreamBlocked */: + if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) { + clearProjectStatus(state, nextProjectPath); + } + break; + } + } + addProjToQueue(state, nextProjectPath, 0 /* Update */); + break; + } + } +} +function build(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences) { + mark("SolutionBuilder::beforeBuild"); + const result = buildWorker(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences); + mark("SolutionBuilder::afterBuild"); + measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild"); + return result; +} +function buildWorker(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences) { + const buildOrder = getBuildOrderFor(state, project, onlyReferences); + if (!buildOrder) return 3 /* InvalidProject_OutputsSkipped */; + setupInitialBuild(state, cancellationToken); + let reportQueue = true; + let successfulProjects = 0; + while (true) { + const invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); + if (!invalidatedProject) break; + reportQueue = false; + invalidatedProject.done(cancellationToken, writeFile2, getCustomTransformers == null ? void 0 : getCustomTransformers(invalidatedProject.project)); + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; + } + disableCache(state); + reportErrorSummary(state, buildOrder); + startWatching(state, buildOrder); + return isCircularBuildOrder(buildOrder) ? 4 /* ProjectReferenceCycle_OutputsSkipped */ : !buildOrder.some((p) => state.diagnostics.has(toResolvedConfigFilePath(state, p))) ? 0 /* Success */ : successfulProjects ? 2 /* DiagnosticsPresent_OutputsGenerated */ : 1 /* DiagnosticsPresent_OutputsSkipped */; +} +function clean(state, project, onlyReferences) { + mark("SolutionBuilder::beforeClean"); + const result = cleanWorker(state, project, onlyReferences); + mark("SolutionBuilder::afterClean"); + measure("SolutionBuilder::Clean", "SolutionBuilder::beforeClean", "SolutionBuilder::afterClean"); + return result; +} +function cleanWorker(state, project, onlyReferences) { + const buildOrder = getBuildOrderFor(state, project, onlyReferences); + if (!buildOrder) return 3 /* InvalidProject_OutputsSkipped */; + if (isCircularBuildOrder(buildOrder)) { + reportErrors(state, buildOrder.circularDiagnostics); + return 4 /* ProjectReferenceCycle_OutputsSkipped */; + } + const { options, host } = state; + const filesToDelete = options.dry ? [] : void 0; + for (const proj of buildOrder) { + const resolvedPath = toResolvedConfigFilePath(state, proj); + const parsed = parseConfigFile(state, proj, resolvedPath); + if (parsed === void 0) { + reportParseConfigFileDiagnostic(state, resolvedPath); + continue; + } + const outputs = getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); + if (!outputs.length) continue; + const inputFileNames = new Set(parsed.fileNames.map((f) => toPath2(state, f))); + for (const output of outputs) { + if (inputFileNames.has(toPath2(state, output))) continue; + if (host.fileExists(output)) { + if (filesToDelete) { + filesToDelete.push(output); + } else { + host.deleteFile(output); + invalidateProject(state, resolvedPath, 0 /* Update */); + } + } + } + } + if (filesToDelete) { + reportStatus(state, Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map((f) => `\r + * ${f}`).join("")); + } + return 0 /* Success */; +} +function invalidateProject(state, resolved, updateLevel) { + if (state.host.getParsedCommandLine && updateLevel === 1 /* RootNamesAndUpdate */) { + updateLevel = 2 /* Full */; + } + if (updateLevel === 2 /* Full */) { + state.configFileCache.delete(resolved); + state.buildOrder = void 0; + } + state.needsSummary = true; + clearProjectStatus(state, resolved); + addProjToQueue(state, resolved, updateLevel); + enableCache(state); +} +function invalidateProjectAndScheduleBuilds(state, resolvedPath, updateLevel) { + state.reportFileChangeDetected = true; + invalidateProject(state, resolvedPath, updateLevel); + scheduleBuildInvalidatedProject( + state, + 250, + /*changeDetected*/ + true + ); +} +function scheduleBuildInvalidatedProject(state, time, changeDetected) { + const { hostWithWatch } = state; + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (state.timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject); + } + state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, "timerToBuildInvalidatedProject", state, changeDetected); +} +function buildNextInvalidatedProject(_timeoutType, state, changeDetected) { + mark("SolutionBuilder::beforeBuild"); + const buildOrder = buildNextInvalidatedProjectWorker(state, changeDetected); + mark("SolutionBuilder::afterBuild"); + measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild"); + if (buildOrder) reportErrorSummary(state, buildOrder); +} +function buildNextInvalidatedProjectWorker(state, changeDetected) { + state.timerToBuildInvalidatedProject = void 0; + if (state.reportFileChangeDetected) { + state.reportFileChangeDetected = false; + state.projectErrorsReported.clear(); + reportWatchStatus(state, Diagnostics.File_change_detected_Starting_incremental_compilation); + } + let projectsBuilt = 0; + const buildOrder = getBuildOrder(state); + const invalidatedProject = getNextInvalidatedProject( + state, + buildOrder, + /*reportQueue*/ + false + ); + if (invalidatedProject) { + invalidatedProject.done(); + projectsBuilt++; + while (state.projectPendingBuild.size) { + if (state.timerToBuildInvalidatedProject) return; + const info = getNextInvalidatedProjectCreateInfo( + state, + buildOrder, + /*reportQueue*/ + false + ); + if (!info) break; + if (info.kind !== 1 /* UpdateOutputFileStamps */ && (changeDetected || projectsBuilt === 5)) { + scheduleBuildInvalidatedProject( + state, + 100, + /*changeDetected*/ + false + ); + return; + } + const project = createInvalidatedProjectWithInfo(state, info, buildOrder); + project.done(); + if (info.kind !== 1 /* UpdateOutputFileStamps */) projectsBuilt++; + } + } + disableCache(state); + return buildOrder; +} +function watchConfigFile(state, resolved, resolvedPath, parsed) { + if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; + state.allWatchedConfigFiles.set( + resolvedPath, + watchFile( + state, + resolved, + () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 2 /* Full */), + 2e3 /* High */, + parsed == null ? void 0 : parsed.watchOptions, + WatchType.ConfigFile, + resolved + ) + ); +} +function watchExtendedConfigFiles(state, resolvedPath, parsed) { + updateSharedExtendedConfigFileWatcher( + resolvedPath, + parsed == null ? void 0 : parsed.options, + state.allWatchedExtendedConfigFiles, + (extendedConfigFileName, extendedConfigFilePath) => watchFile( + state, + extendedConfigFileName, + () => { + var _a; + return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) == null ? void 0 : _a.projects.forEach((projectConfigFilePath) => invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, 2 /* Full */)); + }, + 2e3 /* High */, + parsed == null ? void 0 : parsed.watchOptions, + WatchType.ExtendedConfigFile + ), + (fileName) => toPath2(state, fileName) + ); +} +function watchWildCardDirectories(state, resolved, resolvedPath, parsed) { + if (!state.watch) return; + updateWatchingWildcardDirectories( + getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), + parsed.wildcardDirectories, + (dir, flags) => state.watchDirectory( + dir, + (fileOrDirectory) => { + var _a; + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath2(state, dir), + fileOrDirectory, + fileOrDirectoryPath: toPath2(state, fileOrDirectory), + configFileName: resolved, + currentDirectory: state.compilerHost.getCurrentDirectory(), + options: parsed.options, + program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) == null ? void 0 : _a.fileNames), + useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, + writeLog: (s) => state.writeLog(s), + toPath: (fileName) => toPath2(state, fileName) + })) return; + invalidateProjectAndScheduleBuilds(state, resolvedPath, 1 /* RootNamesAndUpdate */); + }, + flags, + parsed == null ? void 0 : parsed.watchOptions, + WatchType.WildcardDirectory, + resolved + ) + ); +} +function watchInputFiles(state, resolved, resolvedPath, parsed) { + if (!state.watch) return; + mutateMap( + getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), + new Set(parsed.fileNames), + { + createNewValue: (input) => watchFile( + state, + input, + () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */), + 250 /* Low */, + parsed == null ? void 0 : parsed.watchOptions, + WatchType.SourceFile, + resolved + ), + onDeleteValue: closeFileWatcher + } + ); +} +function watchPackageJsonFiles(state, resolved, resolvedPath, parsed) { + if (!state.watch || !state.lastCachedPackageJsonLookups) return; + mutateMap( + getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), + state.lastCachedPackageJsonLookups.get(resolvedPath), + { + createNewValue: (input) => watchFile( + state, + input, + () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */), + 2e3 /* High */, + parsed == null ? void 0 : parsed.watchOptions, + WatchType.PackageJson, + resolved + ), + onDeleteValue: closeFileWatcher + } + ); +} +function startWatching(state, buildOrder) { + if (!state.watchAllProjectsPending) return; + mark("SolutionBuilder::beforeWatcherCreation"); + state.watchAllProjectsPending = false; + for (const resolved of getBuildOrderFromAnyBuildOrder(buildOrder)) { + const resolvedPath = toResolvedConfigFilePath(state, resolved); + const cfg = parseConfigFile(state, resolved, resolvedPath); + watchConfigFile(state, resolved, resolvedPath, cfg); + watchExtendedConfigFiles(state, resolvedPath, cfg); + if (cfg) { + watchWildCardDirectories(state, resolved, resolvedPath, cfg); + watchInputFiles(state, resolved, resolvedPath, cfg); + watchPackageJsonFiles(state, resolved, resolvedPath, cfg); + } + } + mark("SolutionBuilder::afterWatcherCreation"); + measure("SolutionBuilder::Watcher creation", "SolutionBuilder::beforeWatcherCreation", "SolutionBuilder::afterWatcherCreation"); +} +function stopWatching(state) { + clearMap(state.allWatchedConfigFiles, closeFileWatcher); + clearMap(state.allWatchedExtendedConfigFiles, closeFileWatcherOf); + clearMap(state.allWatchedWildcardDirectories, (watchedWildcardDirectories) => clearMap(watchedWildcardDirectories, closeFileWatcherOf)); + clearMap(state.allWatchedInputFiles, (watchedWildcardDirectories) => clearMap(watchedWildcardDirectories, closeFileWatcher)); + clearMap(state.allWatchedPackageJsonFiles, (watchedPacageJsonFiles) => clearMap(watchedPacageJsonFiles, closeFileWatcher)); +} +function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { + const state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); + return { + build: (project, cancellationToken, writeFile2, getCustomTransformers) => build(state, project, cancellationToken, writeFile2, getCustomTransformers), + clean: (project) => clean(state, project), + buildReferences: (project, cancellationToken, writeFile2, getCustomTransformers) => build( + state, + project, + cancellationToken, + writeFile2, + getCustomTransformers, + /*onlyReferences*/ + true + ), + cleanReferences: (project) => clean( + state, + project, + /*onlyReferences*/ + true + ), + getNextInvalidatedProject: (cancellationToken) => { + setupInitialBuild(state, cancellationToken); + return getNextInvalidatedProject( + state, + getBuildOrder(state), + /*reportQueue*/ + false + ); + }, + getBuildOrder: () => getBuildOrder(state), + getUpToDateStatusOfProject: (project) => { + const configFileName = resolveProjectName(state, project); + const configFilePath = toResolvedConfigFilePath(state, configFileName); + return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); + }, + invalidateProject: (configFilePath, updateLevel) => invalidateProject(state, configFilePath, updateLevel || 0 /* Update */), + close: () => stopWatching(state) + }; +} +function relName(state, path) { + return convertToRelativePath(path, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName); +} +function reportStatus(state, message, ...args) { + state.host.reportSolutionBuilderStatus(createCompilerDiagnostic(message, ...args)); +} +function reportWatchStatus(state, message, ...args) { + var _a, _b; + (_b = (_a = state.hostWithWatch).onWatchStatusChange) == null ? void 0 : _b.call(_a, createCompilerDiagnostic(message, ...args), state.host.getNewLine(), state.baseCompilerOptions); +} +function reportErrors({ host }, errors) { + errors.forEach((err) => host.reportDiagnostic(err)); +} +function reportAndStoreErrors(state, proj, errors) { + reportErrors(state, errors); + state.projectErrorsReported.set(proj, true); + if (errors.length) { + state.diagnostics.set(proj, errors); + } +} +function reportParseConfigFileDiagnostic(state, proj) { + reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]); +} +function reportErrorSummary(state, buildOrder) { + if (!state.needsSummary) return; + state.needsSummary = false; + const canReportSummary = state.watch || !!state.host.reportErrorSummary; + const { diagnostics } = state; + let totalErrors = 0; + let filesInError = []; + if (isCircularBuildOrder(buildOrder)) { + reportBuildQueue(state, buildOrder.buildOrder); + reportErrors(state, buildOrder.circularDiagnostics); + if (canReportSummary) totalErrors += getErrorCountForSummary(buildOrder.circularDiagnostics); + if (canReportSummary) filesInError = [...filesInError, ...getFilesInErrorForSummary(buildOrder.circularDiagnostics)]; + } else { + buildOrder.forEach((project) => { + const projectPath = toResolvedConfigFilePath(state, project); + if (!state.projectErrorsReported.has(projectPath)) { + reportErrors(state, diagnostics.get(projectPath) || emptyArray); + } + }); + if (canReportSummary) diagnostics.forEach((singleProjectErrors) => totalErrors += getErrorCountForSummary(singleProjectErrors)); + if (canReportSummary) diagnostics.forEach((singleProjectErrors) => [...filesInError, ...getFilesInErrorForSummary(singleProjectErrors)]); + } + if (state.watch) { + reportWatchStatus(state, getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors); + } else if (state.host.reportErrorSummary) { + state.host.reportErrorSummary(totalErrors, filesInError); + } +} +function reportBuildQueue(state, buildQueue) { + if (state.options.verbose) { + reportStatus(state, Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map((s) => "\r\n * " + relName(state, s)).join("")); + } +} +function reportUpToDateStatus(state, configFileName, status) { + switch (status.type) { + case 5 /* OutOfDateWithSelf */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, + relName(state, configFileName), + relName(state, status.outOfDateOutputFileName), + relName(state, status.newerInputFileName) + ); + case 6 /* OutOfDateWithUpstream */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, + relName(state, configFileName), + relName(state, status.outOfDateOutputFileName), + relName(state, status.newerProjectName) + ); + case 3 /* OutputMissing */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, + relName(state, configFileName), + relName(state, status.missingOutputFileName) + ); + case 4 /* ErrorReadingFile */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_there_was_error_reading_file_1, + relName(state, configFileName), + relName(state, status.fileName) + ); + case 7 /* OutOfDateBuildInfoWithPendingEmit */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, + relName(state, configFileName), + relName(state, status.buildInfoFile) + ); + case 8 /* OutOfDateBuildInfoWithErrors */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors, + relName(state, configFileName), + relName(state, status.buildInfoFile) + ); + case 9 /* OutOfDateOptions */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions, + relName(state, configFileName), + relName(state, status.buildInfoFile) + ); + case 10 /* OutOfDateRoots */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_but_not_any_more, + relName(state, configFileName), + relName(state, status.buildInfoFile), + relName(state, status.inputFile) + ); + case 1 /* UpToDate */: + if (status.newestInputFileTime !== void 0) { + return reportStatus( + state, + Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, + relName(state, configFileName), + relName(state, status.newestInputFileName || ""), + relName(state, status.oldestOutputFileName || "") + ); + } + break; + case 2 /* UpToDateWithUpstreamTypes */: + return reportStatus( + state, + Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, + relName(state, configFileName) + ); + case 15 /* UpToDateWithInputFileText */: + return reportStatus( + state, + Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, + relName(state, configFileName) + ); + case 11 /* UpstreamOutOfDate */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, + relName(state, configFileName), + relName(state, status.upstreamProjectName) + ); + case 12 /* UpstreamBlocked */: + return reportStatus( + state, + status.upstreamProjectBlocked ? Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built : Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, + relName(state, configFileName), + relName(state, status.upstreamProjectName) + ); + case 0 /* Unbuildable */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_1, + relName(state, configFileName), + status.reason + ); + case 14 /* TsVersionOutputOfDate */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, + relName(state, configFileName), + status.version, + version + ); + case 17 /* ForceBuild */: + return reportStatus( + state, + Diagnostics.Project_0_is_being_forcibly_rebuilt, + relName(state, configFileName) + ); + case 16 /* ContainerOnly */: + // Don't report status on "solution" projects + // falls through + case 13 /* ComputingUpstream */: + break; + default: + assertType(status); + } +} +function verboseReportProjectStatus(state, configFileName, status) { + if (state.options.verbose) { + reportUpToDateStatus(state, configFileName, status); + } +} + +// src/compiler/executeCommandLine.ts +function countLines(program) { + const counts2 = getCountsMap(); + forEach(program.getSourceFiles(), (file) => { + const key = getCountKey(program, file); + const lineCount = getLineStarts(file).length; + counts2.set(key, counts2.get(key) + lineCount); + }); + return counts2; +} +function getCountsMap() { + const counts2 = /* @__PURE__ */ new Map(); + counts2.set("Library", 0); + counts2.set("Definitions", 0); + counts2.set("TypeScript", 0); + counts2.set("JavaScript", 0); + counts2.set("JSON", 0); + counts2.set("Other", 0); + return counts2; +} +function getCountKey(program, file) { + if (program.isSourceFileDefaultLibrary(file)) { + return "Library"; + } else if (file.isDeclarationFile) { + return "Definitions"; + } + const path = file.path; + if (fileExtensionIsOneOf(path, supportedTSExtensionsFlat)) { + return "TypeScript"; + } else if (fileExtensionIsOneOf(path, supportedJSExtensionsFlat)) { + return "JavaScript"; + } else if (fileExtensionIs(path, ".json" /* Json */)) { + return "JSON"; + } else { + return "Other"; + } +} +function updateReportDiagnostic(sys2, existing, options) { + return shouldBePretty(sys2, options) ? createDiagnosticReporter( + sys2, + /*pretty*/ + true + ) : existing; +} +function defaultIsPretty(sys2) { + return !!sys2.writeOutputIsTTY && sys2.writeOutputIsTTY() && !sys2.getEnvironmentVariable("NO_COLOR"); +} +function shouldBePretty(sys2, options) { + if (!options || typeof options.pretty === "undefined") { + return defaultIsPretty(sys2); + } + return options.pretty; +} +function getOptionsForHelp(commandLine) { + return !!commandLine.options.all ? toSorted(optionDeclarations.concat(tscBuildOption), (a, b) => compareStringsCaseInsensitive(a.name, b.name)) : filter(optionDeclarations.concat(tscBuildOption), (v) => !!v.showInSimplifiedHelpView); +} +function printVersion(sys2) { + sys2.write(getDiagnosticText(Diagnostics.Version_0, version) + sys2.newLine); +} +function createColors(sys2) { + const showColors = defaultIsPretty(sys2); + if (!showColors) { + return { + bold: (str) => str, + blue: (str) => str, + blueBackground: (str) => str, + brightWhite: (str) => str + }; + } + function bold(str) { + return `\x1B[1m${str}\x1B[22m`; + } + const isWindows = sys2.getEnvironmentVariable("OS") && sys2.getEnvironmentVariable("OS").toLowerCase().includes("windows"); + const isWindowsTerminal = sys2.getEnvironmentVariable("WT_SESSION"); + const isVSCode = sys2.getEnvironmentVariable("TERM_PROGRAM") && sys2.getEnvironmentVariable("TERM_PROGRAM") === "vscode"; + function blue(str) { + if (isWindows && !isWindowsTerminal && !isVSCode) { + return brightWhite(str); + } + return `\x1B[94m${str}\x1B[39m`; + } + const supportsRicherColors = sys2.getEnvironmentVariable("COLORTERM") === "truecolor" || sys2.getEnvironmentVariable("TERM") === "xterm-256color"; + function blueBackground(str) { + if (supportsRicherColors) { + return `\x1B[48;5;68m${str}\x1B[39;49m`; + } else { + return `\x1B[44m${str}\x1B[39;49m`; + } + } + function brightWhite(str) { + return `\x1B[97m${str}\x1B[39m`; + } + return { + bold, + blue, + brightWhite, + blueBackground + }; +} +function getDisplayNameTextOfOption(option) { + return `--${option.name}${option.shortName ? `, -${option.shortName}` : ""}`; +} +function generateOptionOutput(sys2, option, rightAlignOfLeft, leftAlignOfRight) { + var _a; + const text = []; + const colors = createColors(sys2); + const name = getDisplayNameTextOfOption(option); + const valueCandidates = getValueCandidate(option); + const defaultValueDescription = typeof option.defaultValueDescription === "object" ? getDiagnosticText(option.defaultValueDescription) : formatDefaultValue( + option.defaultValueDescription, + option.type === "list" || option.type === "listOrElement" ? option.element.type : option.type + ); + const terminalWidth = ((_a = sys2.getWidthOfTerminal) == null ? void 0 : _a.call(sys2)) ?? 0; + if (terminalWidth >= 80) { + let description = ""; + if (option.description) { + description = getDiagnosticText(option.description); + } + text.push(...getPrettyOutput( + name, + description, + rightAlignOfLeft, + leftAlignOfRight, + terminalWidth, + /*colorLeft*/ + true + ), sys2.newLine); + if (showAdditionalInfoOutput(valueCandidates, option)) { + if (valueCandidates) { + text.push(...getPrettyOutput( + valueCandidates.valueType, + valueCandidates.possibleValues, + rightAlignOfLeft, + leftAlignOfRight, + terminalWidth, + /*colorLeft*/ + false + ), sys2.newLine); + } + if (defaultValueDescription) { + text.push(...getPrettyOutput( + getDiagnosticText(Diagnostics.default_Colon), + defaultValueDescription, + rightAlignOfLeft, + leftAlignOfRight, + terminalWidth, + /*colorLeft*/ + false + ), sys2.newLine); + } + } + text.push(sys2.newLine); + } else { + text.push(colors.blue(name), sys2.newLine); + if (option.description) { + const description = getDiagnosticText(option.description); + text.push(description); + } + text.push(sys2.newLine); + if (showAdditionalInfoOutput(valueCandidates, option)) { + if (valueCandidates) { + text.push(`${valueCandidates.valueType} ${valueCandidates.possibleValues}`); + } + if (defaultValueDescription) { + if (valueCandidates) text.push(sys2.newLine); + const diagType = getDiagnosticText(Diagnostics.default_Colon); + text.push(`${diagType} ${defaultValueDescription}`); + } + text.push(sys2.newLine); + } + text.push(sys2.newLine); + } + return text; + function formatDefaultValue(defaultValue, type) { + return defaultValue !== void 0 && typeof type === "object" ? arrayFrom(type.entries()).filter(([, value]) => value === defaultValue).map(([name2]) => name2).join("/") : String(defaultValue); + } + function showAdditionalInfoOutput(valueCandidates2, option2) { + const ignoreValues = ["string"]; + const ignoredDescriptions = [void 0, "false", "n/a"]; + const defaultValueDescription2 = option2.defaultValueDescription; + if (option2.category === Diagnostics.Command_line_Options) return false; + if (contains(ignoreValues, valueCandidates2 == null ? void 0 : valueCandidates2.possibleValues) && contains(ignoredDescriptions, defaultValueDescription2)) { + return false; + } + return true; + } + function getPrettyOutput(left, right, rightAlignOfLeft2, leftAlignOfRight2, terminalWidth2, colorLeft) { + const res = []; + let isFirstLine = true; + let remainRight = right; + const rightCharacterNumber = terminalWidth2 - leftAlignOfRight2; + while (remainRight.length > 0) { + let curLeft = ""; + if (isFirstLine) { + curLeft = left.padStart(rightAlignOfLeft2); + curLeft = curLeft.padEnd(leftAlignOfRight2); + curLeft = colorLeft ? colors.blue(curLeft) : curLeft; + } else { + curLeft = "".padStart(leftAlignOfRight2); + } + const curRight = remainRight.substr(0, rightCharacterNumber); + remainRight = remainRight.slice(rightCharacterNumber); + res.push(`${curLeft}${curRight}`); + isFirstLine = false; + } + return res; + } + function getValueCandidate(option2) { + if (option2.type === "object") { + return void 0; + } + return { + valueType: getValueType(option2), + possibleValues: getPossibleValues(option2) + }; + function getValueType(option3) { + Debug.assert(option3.type !== "listOrElement"); + switch (option3.type) { + case "string": + case "number": + case "boolean": + return getDiagnosticText(Diagnostics.type_Colon); + case "list": + return getDiagnosticText(Diagnostics.one_or_more_Colon); + default: + return getDiagnosticText(Diagnostics.one_of_Colon); + } + } + function getPossibleValues(option3) { + let possibleValues; + switch (option3.type) { + case "string": + case "number": + case "boolean": + possibleValues = option3.type; + break; + case "list": + case "listOrElement": + possibleValues = getPossibleValues(option3.element); + break; + case "object": + possibleValues = ""; + break; + default: + const inverted = {}; + option3.type.forEach((value, name2) => { + var _a2; + if (!((_a2 = option3.deprecatedKeys) == null ? void 0 : _a2.has(name2))) { + (inverted[value] || (inverted[value] = [])).push(name2); + } + }); + return Object.entries(inverted).map(([, synonyms]) => synonyms.join("/")).join(", "); + } + return possibleValues; + } + } +} +function generateGroupOptionOutput(sys2, optionsList) { + let maxLength = 0; + for (const option of optionsList) { + const curLength = getDisplayNameTextOfOption(option).length; + maxLength = maxLength > curLength ? maxLength : curLength; + } + const rightAlignOfLeftPart = maxLength + 2; + const leftAlignOfRightPart = rightAlignOfLeftPart + 2; + let lines = []; + for (const option of optionsList) { + const tmp = generateOptionOutput(sys2, option, rightAlignOfLeftPart, leftAlignOfRightPart); + lines = [...lines, ...tmp]; + } + if (lines[lines.length - 2] !== sys2.newLine) { + lines.push(sys2.newLine); + } + return lines; +} +function generateSectionOptionsOutput(sys2, sectionName, options, subCategory, beforeOptionsDescription, afterOptionsDescription) { + let res = []; + res.push(createColors(sys2).bold(sectionName) + sys2.newLine + sys2.newLine); + if (beforeOptionsDescription) { + res.push(beforeOptionsDescription + sys2.newLine + sys2.newLine); + } + if (!subCategory) { + res = [...res, ...generateGroupOptionOutput(sys2, options)]; + if (afterOptionsDescription) { + res.push(afterOptionsDescription + sys2.newLine + sys2.newLine); + } + return res; + } + const categoryMap = /* @__PURE__ */ new Map(); + for (const option of options) { + if (!option.category) { + continue; + } + const curCategory = getDiagnosticText(option.category); + const optionsOfCurCategory = categoryMap.get(curCategory) ?? []; + optionsOfCurCategory.push(option); + categoryMap.set(curCategory, optionsOfCurCategory); + } + categoryMap.forEach((value, key) => { + res.push(`### ${key}${sys2.newLine}${sys2.newLine}`); + res = [...res, ...generateGroupOptionOutput(sys2, value)]; + }); + if (afterOptionsDescription) { + res.push(afterOptionsDescription + sys2.newLine + sys2.newLine); + } + return res; +} +function printEasyHelp(sys2, simpleOptions) { + const colors = createColors(sys2); + let output = [...getHeader(sys2, `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; + output.push(colors.bold(getDiagnosticText(Diagnostics.COMMON_COMMANDS)) + sys2.newLine + sys2.newLine); + example("tsc", Diagnostics.Compiles_the_current_project_tsconfig_json_in_the_working_directory); + example("tsc app.ts util.ts", Diagnostics.Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options); + example("tsc -b", Diagnostics.Build_a_composite_project_in_the_working_directory); + example("tsc --init", Diagnostics.Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory); + example("tsc -p ./path/to/tsconfig.json", Diagnostics.Compiles_the_TypeScript_project_located_at_the_specified_path); + example("tsc --help --all", Diagnostics.An_expanded_version_of_this_information_showing_all_possible_compiler_options); + example(["tsc --noEmit", "tsc --target esnext"], Diagnostics.Compiles_the_current_project_with_additional_settings); + const cliCommands = simpleOptions.filter((opt) => opt.isCommandLineOnly || opt.category === Diagnostics.Command_line_Options); + const configOpts = simpleOptions.filter((opt) => !contains(cliCommands, opt)); + output = [ + ...output, + ...generateSectionOptionsOutput( + sys2, + getDiagnosticText(Diagnostics.COMMAND_LINE_FLAGS), + cliCommands, + /*subCategory*/ + false, + /*beforeOptionsDescription*/ + void 0, + /*afterOptionsDescription*/ + void 0 + ), + ...generateSectionOptionsOutput( + sys2, + getDiagnosticText(Diagnostics.COMMON_COMPILER_OPTIONS), + configOpts, + /*subCategory*/ + false, + /*beforeOptionsDescription*/ + void 0, + formatMessage(Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc") + ) + ]; + for (const line of output) { + sys2.write(line); + } + function example(ex, desc) { + const examples = typeof ex === "string" ? [ex] : ex; + for (const example2 of examples) { + output.push(" " + colors.blue(example2) + sys2.newLine); + } + output.push(" " + getDiagnosticText(desc) + sys2.newLine + sys2.newLine); + } +} +function printAllHelp(sys2, compilerOptions, buildOptions, watchOptions) { + let output = [...getHeader(sys2, `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; + output = [...output, ...generateSectionOptionsOutput( + sys2, + getDiagnosticText(Diagnostics.ALL_COMPILER_OPTIONS), + compilerOptions, + /*subCategory*/ + true, + /*beforeOptionsDescription*/ + void 0, + formatMessage(Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc") + )]; + output = [...output, ...generateSectionOptionsOutput( + sys2, + getDiagnosticText(Diagnostics.WATCH_OPTIONS), + watchOptions, + /*subCategory*/ + false, + getDiagnosticText(Diagnostics.Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_config_watch_mode_with_Colon) + )]; + output = [...output, ...generateSectionOptionsOutput( + sys2, + getDiagnosticText(Diagnostics.BUILD_OPTIONS), + filter(buildOptions, (option) => option !== tscBuildOption), + /*subCategory*/ + false, + formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds") + )]; + for (const line of output) { + sys2.write(line); + } +} +function printBuildHelp(sys2, buildOptions) { + let output = [...getHeader(sys2, `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; + output = [...output, ...generateSectionOptionsOutput( + sys2, + getDiagnosticText(Diagnostics.BUILD_OPTIONS), + filter(buildOptions, (option) => option !== tscBuildOption), + /*subCategory*/ + false, + formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds") + )]; + for (const line of output) { + sys2.write(line); + } +} +function getHeader(sys2, message) { + var _a; + const colors = createColors(sys2); + const header = []; + const terminalWidth = ((_a = sys2.getWidthOfTerminal) == null ? void 0 : _a.call(sys2)) ?? 0; + const tsIconLength = 5; + const tsIconFirstLine = colors.blueBackground("".padStart(tsIconLength)); + const tsIconSecondLine = colors.blueBackground(colors.brightWhite("TS ".padStart(tsIconLength))); + if (terminalWidth >= message.length + tsIconLength) { + const rightAlign = terminalWidth > 120 ? 120 : terminalWidth; + const leftAlign = rightAlign - tsIconLength; + header.push(message.padEnd(leftAlign) + tsIconFirstLine + sys2.newLine); + header.push("".padStart(leftAlign) + tsIconSecondLine + sys2.newLine); + } else { + header.push(message + sys2.newLine); + header.push(sys2.newLine); + } + return header; +} +function printHelp(sys2, commandLine) { + if (!commandLine.options.all) { + printEasyHelp(sys2, getOptionsForHelp(commandLine)); + } else { + printAllHelp(sys2, getOptionsForHelp(commandLine), optionsForBuild, optionsForWatch); + } +} +function executeCommandLineWorker(sys2, cb, commandLine) { + let reportDiagnostic = createDiagnosticReporter(sys2); + let configFileName; + if (commandLine.options.locale) { + validateLocaleAndSetLanguage(commandLine.options.locale, sys2, commandLine.errors); + } + if (commandLine.errors.length > 0) { + commandLine.errors.forEach(reportDiagnostic); + return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + } + if (commandLine.options.init) { + writeConfigFile(sys2, reportDiagnostic, commandLine.options, commandLine.fileNames); + return sys2.exit(0 /* Success */); + } + if (commandLine.options.version) { + printVersion(sys2); + return sys2.exit(0 /* Success */); + } + if (commandLine.options.help || commandLine.options.all) { + printHelp(sys2, commandLine); + return sys2.exit(0 /* Success */); + } + if (commandLine.options.watch && commandLine.options.listFilesOnly) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "listFilesOnly")); + return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + } + if (commandLine.options.project) { + if (commandLine.fileNames.length !== 0) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line)); + return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + } + const fileOrDirectory = normalizePath(commandLine.options.project); + if (!fileOrDirectory || sys2.directoryExists(fileOrDirectory)) { + configFileName = combinePaths(fileOrDirectory, "tsconfig.json"); + if (!sys2.fileExists(configFileName)) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project)); + return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + } + } else { + configFileName = fileOrDirectory; + if (!sys2.fileExists(configFileName)) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project)); + return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + } + } + } else if (commandLine.fileNames.length === 0) { + const searchPath = normalizePath(sys2.getCurrentDirectory()); + configFileName = findConfigFile(searchPath, (fileName) => sys2.fileExists(fileName)); + } + if (commandLine.fileNames.length === 0 && !configFileName) { + if (commandLine.options.showConfig) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0, normalizePath(sys2.getCurrentDirectory()))); + } else { + printVersion(sys2); + printHelp(sys2, commandLine); + } + return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + } + const currentDirectory = sys2.getCurrentDirectory(); + const commandLineOptions = convertToOptionsWithAbsolutePaths( + commandLine.options, + (fileName) => getNormalizedAbsolutePath(fileName, currentDirectory) + ); + if (configFileName) { + const extendedConfigCache = /* @__PURE__ */ new Map(); + const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, extendedConfigCache, commandLine.watchOptions, sys2, reportDiagnostic); + if (commandLineOptions.showConfig) { + if (configParseResult.errors.length !== 0) { + reportDiagnostic = updateReportDiagnostic( + sys2, + reportDiagnostic, + configParseResult.options + ); + configParseResult.errors.forEach(reportDiagnostic); + return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + } + sys2.write(JSON.stringify(convertToTSConfig(configParseResult, configFileName, sys2), null, 4) + sys2.newLine); + return sys2.exit(0 /* Success */); + } + reportDiagnostic = updateReportDiagnostic( + sys2, + reportDiagnostic, + configParseResult.options + ); + if (isWatchSet(configParseResult.options)) { + if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return; + return createWatchOfConfigFile( + sys2, + cb, + reportDiagnostic, + configParseResult, + commandLineOptions, + commandLine.watchOptions, + extendedConfigCache + ); + } else if (isIncrementalCompilation(configParseResult.options)) { + performIncrementalCompilation2( + sys2, + cb, + reportDiagnostic, + configParseResult + ); + } else { + performCompilation( + sys2, + cb, + reportDiagnostic, + configParseResult + ); + } + } else { + if (commandLineOptions.showConfig) { + sys2.write(JSON.stringify(convertToTSConfig(commandLine, combinePaths(currentDirectory, "tsconfig.json"), sys2), null, 4) + sys2.newLine); + return sys2.exit(0 /* Success */); + } + reportDiagnostic = updateReportDiagnostic( + sys2, + reportDiagnostic, + commandLineOptions + ); + if (isWatchSet(commandLineOptions)) { + if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return; + return createWatchOfFilesAndCompilerOptions( + sys2, + cb, + reportDiagnostic, + commandLine.fileNames, + commandLineOptions, + commandLine.watchOptions + ); + } else if (isIncrementalCompilation(commandLineOptions)) { + performIncrementalCompilation2( + sys2, + cb, + reportDiagnostic, + { ...commandLine, options: commandLineOptions } + ); + } else { + performCompilation( + sys2, + cb, + reportDiagnostic, + { ...commandLine, options: commandLineOptions } + ); + } + } +} +function isBuildCommand(commandLineArgs) { + if (commandLineArgs.length > 0 && commandLineArgs[0].charCodeAt(0) === 45 /* minus */) { + const firstOption = commandLineArgs[0].slice(commandLineArgs[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); + return firstOption === tscBuildOption.name || firstOption === tscBuildOption.shortName; + } + return false; +} +function executeCommandLine(system, cb, commandLineArgs) { + if (isBuildCommand(commandLineArgs)) { + const { buildOptions, watchOptions, projects, errors } = parseBuildCommand(commandLineArgs); + if (buildOptions.generateCpuProfile && system.enableCPUProfiler) { + system.enableCPUProfiler(buildOptions.generateCpuProfile, () => performBuild( + system, + cb, + buildOptions, + watchOptions, + projects, + errors + )); + } else { + return performBuild( + system, + cb, + buildOptions, + watchOptions, + projects, + errors + ); + } + } + const commandLine = parseCommandLine(commandLineArgs, (path) => system.readFile(path)); + if (commandLine.options.generateCpuProfile && system.enableCPUProfiler) { + system.enableCPUProfiler(commandLine.options.generateCpuProfile, () => executeCommandLineWorker( + system, + cb, + commandLine + )); + } else { + return executeCommandLineWorker(system, cb, commandLine); + } +} +function reportWatchModeWithoutSysSupport(sys2, reportDiagnostic) { + if (!sys2.watchFile || !sys2.watchDirectory) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); + sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + return true; + } + return false; +} +var defaultJSDocParsingMode = 2 /* ParseForTypeErrors */; +function performBuild(sys2, cb, buildOptions, watchOptions, projects, errors) { + const reportDiagnostic = updateReportDiagnostic( + sys2, + createDiagnosticReporter(sys2), + buildOptions + ); + if (buildOptions.locale) { + validateLocaleAndSetLanguage(buildOptions.locale, sys2, errors); + } + if (errors.length > 0) { + errors.forEach(reportDiagnostic); + return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + } + if (buildOptions.help) { + printVersion(sys2); + printBuildHelp(sys2, buildOpts); + return sys2.exit(0 /* Success */); + } + if (projects.length === 0) { + printVersion(sys2); + printBuildHelp(sys2, buildOpts); + return sys2.exit(0 /* Success */); + } + if (!sys2.getModifiedTime || !sys2.setModifiedTime || buildOptions.clean && !sys2.deleteFile) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); + return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); + } + if (buildOptions.watch) { + if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return; + const buildHost2 = createSolutionBuilderWithWatchHost( + sys2, + /*createProgram*/ + void 0, + reportDiagnostic, + createBuilderStatusReporter(sys2, shouldBePretty(sys2, buildOptions)), + createWatchStatusReporter2(sys2, buildOptions) + ); + buildHost2.jsDocParsingMode = defaultJSDocParsingMode; + const solutionPerformance2 = enableSolutionPerformance(sys2, buildOptions); + updateSolutionBuilderHost(sys2, cb, buildHost2, solutionPerformance2); + const onWatchStatusChange = buildHost2.onWatchStatusChange; + let reportBuildStatistics = false; + buildHost2.onWatchStatusChange = (d, newLine, options, errorCount) => { + onWatchStatusChange == null ? void 0 : onWatchStatusChange(d, newLine, options, errorCount); + if (reportBuildStatistics && (d.code === Diagnostics.Found_0_errors_Watching_for_file_changes.code || d.code === Diagnostics.Found_1_error_Watching_for_file_changes.code)) { + reportSolutionBuilderTimes(builder2, solutionPerformance2); + } + }; + const builder2 = createSolutionBuilderWithWatch(buildHost2, projects, buildOptions, watchOptions); + builder2.build(); + reportSolutionBuilderTimes(builder2, solutionPerformance2); + reportBuildStatistics = true; + return builder2; + } + const buildHost = createSolutionBuilderHost( + sys2, + /*createProgram*/ + void 0, + reportDiagnostic, + createBuilderStatusReporter(sys2, shouldBePretty(sys2, buildOptions)), + createReportErrorSummary(sys2, buildOptions) + ); + buildHost.jsDocParsingMode = defaultJSDocParsingMode; + const solutionPerformance = enableSolutionPerformance(sys2, buildOptions); + updateSolutionBuilderHost(sys2, cb, buildHost, solutionPerformance); + const builder = createSolutionBuilder(buildHost, projects, buildOptions); + const exitStatus = buildOptions.clean ? builder.clean() : builder.build(); + reportSolutionBuilderTimes(builder, solutionPerformance); + dumpTracingLegend(); + return sys2.exit(exitStatus); +} +function createReportErrorSummary(sys2, options) { + return shouldBePretty(sys2, options) ? (errorCount, filesInError) => sys2.write(getErrorSummaryText(errorCount, filesInError, sys2.newLine, sys2)) : void 0; +} +function performCompilation(sys2, cb, reportDiagnostic, config) { + const { fileNames, options, projectReferences } = config; + const host = createCompilerHostWorker( + options, + /*setParentNodes*/ + void 0, + sys2 + ); + host.jsDocParsingMode = defaultJSDocParsingMode; + const currentDirectory = host.getCurrentDirectory(); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + changeCompilerHostLikeToUseCache(host, (fileName) => toPath(fileName, currentDirectory, getCanonicalFileName)); + enableStatisticsAndTracing( + sys2, + options, + /*isBuildMode*/ + false + ); + const programOptions = { + rootNames: fileNames, + options, + projectReferences, + host, + configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config) + }; + const program = createProgram(programOptions); + const exitStatus = emitFilesAndReportErrorsAndGetExitStatus( + program, + reportDiagnostic, + (s) => sys2.write(s + sys2.newLine), + createReportErrorSummary(sys2, options) + ); + reportStatistics( + sys2, + program, + /*solutionPerformance*/ + void 0 + ); + cb(program); + return sys2.exit(exitStatus); +} +function performIncrementalCompilation2(sys2, cb, reportDiagnostic, config) { + const { options, fileNames, projectReferences } = config; + enableStatisticsAndTracing( + sys2, + options, + /*isBuildMode*/ + false + ); + const host = createIncrementalCompilerHost(options, sys2); + host.jsDocParsingMode = defaultJSDocParsingMode; + const exitStatus = performIncrementalCompilation({ + host, + system: sys2, + rootNames: fileNames, + options, + configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config), + projectReferences, + reportDiagnostic, + reportErrorSummary: createReportErrorSummary(sys2, options), + afterProgramEmitAndDiagnostics: (builderProgram) => { + reportStatistics( + sys2, + builderProgram.getProgram(), + /*solutionPerformance*/ + void 0 + ); + cb(builderProgram); + } + }); + return sys2.exit(exitStatus); +} +function updateSolutionBuilderHost(sys2, cb, buildHost, solutionPerformance) { + updateCreateProgram( + sys2, + buildHost, + /*isBuildMode*/ + true + ); + buildHost.afterProgramEmitAndDiagnostics = (program) => { + reportStatistics(sys2, program.getProgram(), solutionPerformance); + cb(program); + }; +} +function updateCreateProgram(sys2, host, isBuildMode) { + const compileUsingBuilder = host.createProgram; + host.createProgram = (rootNames, options, host2, oldProgram, configFileParsingDiagnostics, projectReferences) => { + Debug.assert(rootNames !== void 0 || options === void 0 && !!oldProgram); + if (options !== void 0) { + enableStatisticsAndTracing(sys2, options, isBuildMode); + } + return compileUsingBuilder(rootNames, options, host2, oldProgram, configFileParsingDiagnostics, projectReferences); + }; +} +function updateWatchCompilationHost(sys2, cb, watchCompilerHost) { + watchCompilerHost.jsDocParsingMode = defaultJSDocParsingMode; + updateCreateProgram( + sys2, + watchCompilerHost, + /*isBuildMode*/ + false + ); + const emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; + watchCompilerHost.afterProgramCreate = (builderProgram) => { + emitFilesUsingBuilder(builderProgram); + reportStatistics( + sys2, + builderProgram.getProgram(), + /*solutionPerformance*/ + void 0 + ); + cb(builderProgram); + }; +} +function createWatchStatusReporter2(sys2, options) { + return createWatchStatusReporter(sys2, shouldBePretty(sys2, options)); +} +function createWatchOfConfigFile(system, cb, reportDiagnostic, configParseResult, optionsToExtend, watchOptionsToExtend, extendedConfigCache) { + const watchCompilerHost = createWatchCompilerHostOfConfigFile({ + configFileName: configParseResult.options.configFilePath, + optionsToExtend, + watchOptionsToExtend, + system, + reportDiagnostic, + reportWatchStatus: createWatchStatusReporter2(system, configParseResult.options) + }); + updateWatchCompilationHost(system, cb, watchCompilerHost); + watchCompilerHost.configFileParsingResult = configParseResult; + watchCompilerHost.extendedConfigCache = extendedConfigCache; + return createWatchProgram(watchCompilerHost); +} +function createWatchOfFilesAndCompilerOptions(system, cb, reportDiagnostic, rootFiles, options, watchOptions) { + const watchCompilerHost = createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles, + options, + watchOptions, + system, + reportDiagnostic, + reportWatchStatus: createWatchStatusReporter2(system, options) + }); + updateWatchCompilationHost(system, cb, watchCompilerHost); + return createWatchProgram(watchCompilerHost); +} +function enableSolutionPerformance(system, options) { + if (system === sys && options.extendedDiagnostics) { + enable(); + return createSolutionPerfomrance(); + } +} +function createSolutionPerfomrance() { + let statistics; + return { + addAggregateStatistic, + forEachAggregateStatistics: forEachAggreateStatistics, + clear: clear2 + }; + function addAggregateStatistic(s) { + const existing = statistics == null ? void 0 : statistics.get(s.name); + if (existing) { + if (existing.type === 2 /* memory */) existing.value = Math.max(existing.value, s.value); + else existing.value += s.value; + } else { + (statistics ?? (statistics = /* @__PURE__ */ new Map())).set(s.name, s); + } + } + function forEachAggreateStatistics(cb) { + statistics == null ? void 0 : statistics.forEach(cb); + } + function clear2() { + statistics = void 0; + } +} +function reportSolutionBuilderTimes(builder, solutionPerformance) { + if (!solutionPerformance) return; + if (!isEnabled()) { + sys.write(Diagnostics.Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found.message + "\n"); + return; + } + const statistics = []; + statistics.push( + { name: "Projects in scope", value: getBuildOrderFromAnyBuildOrder(builder.getBuildOrder()).length, type: 1 /* count */ } + ); + reportSolutionBuilderCountStatistic("SolutionBuilder::Projects built"); + reportSolutionBuilderCountStatistic("SolutionBuilder::Timestamps only updates"); + reportSolutionBuilderCountStatistic("SolutionBuilder::Bundles updated"); + solutionPerformance.forEachAggregateStatistics((s) => { + s.name = `Aggregate ${s.name}`; + statistics.push(s); + }); + forEachMeasure((name, duration) => { + if (isSolutionMarkOrMeasure(name)) statistics.push({ name: `${getNameFromSolutionBuilderMarkOrMeasure(name)} time`, value: duration, type: 0 /* time */ }); + }); + disable(); + enable(); + solutionPerformance.clear(); + reportAllStatistics(sys, statistics); + function reportSolutionBuilderCountStatistic(name) { + const value = getCount(name); + if (value) { + statistics.push({ name: getNameFromSolutionBuilderMarkOrMeasure(name), value, type: 1 /* count */ }); + } + } + function getNameFromSolutionBuilderMarkOrMeasure(name) { + return name.replace("SolutionBuilder::", ""); + } +} +function canReportDiagnostics(system, compilerOptions) { + return system === sys && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); +} +function canTrace(system, compilerOptions) { + return system === sys && compilerOptions.generateTrace; +} +function enableStatisticsAndTracing(system, compilerOptions, isBuildMode) { + if (canReportDiagnostics(system, compilerOptions)) { + enable(system); + } + if (canTrace(system, compilerOptions)) { + startTracing(isBuildMode ? "build" : "project", compilerOptions.generateTrace, compilerOptions.configFilePath); + } +} +function isSolutionMarkOrMeasure(name) { + return startsWith(name, "SolutionBuilder::"); +} +function reportStatistics(sys2, program, solutionPerformance) { + var _a; + const compilerOptions = program.getCompilerOptions(); + if (canTrace(sys2, compilerOptions)) { + (_a = tracing) == null ? void 0 : _a.stopTracing(); + } + let statistics; + if (canReportDiagnostics(sys2, compilerOptions)) { + statistics = []; + const memoryUsed = sys2.getMemoryUsage ? sys2.getMemoryUsage() : -1; + reportCountStatistic("Files", program.getSourceFiles().length); + const lineCounts = countLines(program); + if (compilerOptions.extendedDiagnostics) { + for (const [key, value] of lineCounts.entries()) { + reportCountStatistic("Lines of " + key, value); + } + } else { + reportCountStatistic("Lines", reduceLeftIterator(lineCounts.values(), (sum, count) => sum + count, 0)); + } + reportCountStatistic("Identifiers", program.getIdentifierCount()); + reportCountStatistic("Symbols", program.getSymbolCount()); + reportCountStatistic("Types", program.getTypeCount()); + reportCountStatistic("Instantiations", program.getInstantiationCount()); + if (memoryUsed >= 0) { + reportStatisticalValue( + { name: "Memory used", value: memoryUsed, type: 2 /* memory */ }, + /*aggregate*/ + true + ); + } + const isPerformanceEnabled = isEnabled(); + const programTime = isPerformanceEnabled ? getDuration("Program") : 0; + const bindTime = isPerformanceEnabled ? getDuration("Bind") : 0; + const checkTime = isPerformanceEnabled ? getDuration("Check") : 0; + const emitTime = isPerformanceEnabled ? getDuration("Emit") : 0; + if (compilerOptions.extendedDiagnostics) { + const caches = program.getRelationCacheSizes(); + reportCountStatistic("Assignability cache size", caches.assignable); + reportCountStatistic("Identity cache size", caches.identity); + reportCountStatistic("Subtype cache size", caches.subtype); + reportCountStatistic("Strict subtype cache size", caches.strictSubtype); + if (isPerformanceEnabled) { + forEachMeasure((name, duration) => { + if (!isSolutionMarkOrMeasure(name)) reportTimeStatistic( + `${name} time`, + duration, + /*aggregate*/ + true + ); + }); + } + } else if (isPerformanceEnabled) { + reportTimeStatistic( + "I/O read", + getDuration("I/O Read"), + /*aggregate*/ + true + ); + reportTimeStatistic( + "I/O write", + getDuration("I/O Write"), + /*aggregate*/ + true + ); + reportTimeStatistic( + "Parse time", + programTime, + /*aggregate*/ + true + ); + reportTimeStatistic( + "Bind time", + bindTime, + /*aggregate*/ + true + ); + reportTimeStatistic( + "Check time", + checkTime, + /*aggregate*/ + true + ); + reportTimeStatistic( + "Emit time", + emitTime, + /*aggregate*/ + true + ); + } + if (isPerformanceEnabled) { + reportTimeStatistic( + "Total time", + programTime + bindTime + checkTime + emitTime, + /*aggregate*/ + false + ); + } + reportAllStatistics(sys2, statistics); + if (!isPerformanceEnabled) { + sys2.write(Diagnostics.Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found.message + "\n"); + } else { + if (solutionPerformance) { + forEachMeasure((name) => { + if (!isSolutionMarkOrMeasure(name)) clearMeasures(name); + }); + forEachMark((name) => { + if (!isSolutionMarkOrMeasure(name)) clearMarks(name); + }); + } else { + disable(); + } + } + } + function reportStatisticalValue(s, aggregate) { + statistics.push(s); + if (aggregate) solutionPerformance == null ? void 0 : solutionPerformance.addAggregateStatistic(s); + } + function reportCountStatistic(name, count) { + reportStatisticalValue( + { name, value: count, type: 1 /* count */ }, + /*aggregate*/ + true + ); + } + function reportTimeStatistic(name, time, aggregate) { + reportStatisticalValue({ name, value: time, type: 0 /* time */ }, aggregate); + } +} +function reportAllStatistics(sys2, statistics) { + let nameSize = 0; + let valueSize = 0; + for (const s of statistics) { + if (s.name.length > nameSize) { + nameSize = s.name.length; + } + const value = statisticValue(s); + if (value.length > valueSize) { + valueSize = value.length; + } + } + for (const s of statistics) { + sys2.write(`${s.name}:`.padEnd(nameSize + 2) + statisticValue(s).toString().padStart(valueSize) + sys2.newLine); + } +} +function statisticValue(s) { + switch (s.type) { + case 1 /* count */: + return "" + s.value; + case 0 /* time */: + return (s.value / 1e3).toFixed(2) + "s"; + case 2 /* memory */: + return Math.round(s.value / 1e3) + "K"; + default: + Debug.assertNever(s.type); + } +} +function writeConfigFile(sys2, reportDiagnostic, options, fileNames) { + const currentDirectory = sys2.getCurrentDirectory(); + const file = normalizePath(combinePaths(currentDirectory, "tsconfig.json")); + if (sys2.fileExists(file)) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file)); + } else { + sys2.writeFile(file, generateTSConfig(options, fileNames, sys2.newLine)); + const output = [sys2.newLine, ...getHeader(sys2, "Created a new tsconfig.json with:")]; + output.push(getCompilerOptionsDiffValue(options, sys2.newLine) + sys2.newLine + sys2.newLine); + output.push(`You can learn more at https://aka.ms/tsconfig` + sys2.newLine); + for (const line of output) { + sys2.write(line); + } + } + return; +} + +// src/compiler/expressionToTypeNode.ts +function syntacticResult(type, reportFallback = true) { + return { type, reportFallback }; +} +var notImplemented2 = syntacticResult( + /*type*/ + void 0, + /*reportFallback*/ + false +); +var alreadyReported = syntacticResult( + /*type*/ + void 0, + /*reportFallback*/ + false +); +var failed = syntacticResult( + /*type*/ + void 0, + /*reportFallback*/ + true +); +function createSyntacticTypeNodeBuilder(options, resolver) { + const strictNullChecks = getStrictOptionValue(options, "strictNullChecks"); + return { + serializeTypeOfDeclaration, + serializeReturnTypeForSignature, + serializeTypeOfExpression, + serializeTypeOfAccessor, + tryReuseExistingTypeNode(context, existing) { + if (!resolver.canReuseTypeNode(context, existing)) { + return void 0; + } + return tryReuseExistingTypeNode(context, existing); + } + }; + function reuseNode(context, node, range = node) { + return node === void 0 ? void 0 : resolver.markNodeReuse(context, node.flags & 16 /* Synthesized */ ? node : factory.cloneNode(node), range ?? node); + } + function tryReuseExistingTypeNode(context, existing) { + const { finalizeBoundary, startRecoveryScope, hadError, markError } = resolver.createRecoveryBoundary(context); + const transformed = visitNode(existing, visitExistingNodeTreeSymbols, isTypeNode); + if (!finalizeBoundary()) { + return void 0; + } + context.approximateLength += existing.end - existing.pos; + return transformed; + function visitExistingNodeTreeSymbols(node) { + if (hadError()) return node; + const recover = startRecoveryScope(); + const onExitNewScope = isNewScopeNode(node) ? resolver.enterNewScope(context, node) : void 0; + const result = visitExistingNodeTreeSymbolsWorker(node); + onExitNewScope == null ? void 0 : onExitNewScope(); + if (hadError()) { + if (isTypeNode(node) && !isTypePredicateNode(node)) { + recover(); + return resolver.serializeExistingTypeNode(context, node); + } + return node; + } + return result ? resolver.markNodeReuse(context, result, node) : void 0; + } + function tryVisitSimpleTypeNode(node) { + const innerNode = skipTypeParentheses(node); + switch (innerNode.kind) { + case 183 /* TypeReference */: + return tryVisitTypeReference(innerNode); + case 186 /* TypeQuery */: + return tryVisitTypeQuery(innerNode); + case 199 /* IndexedAccessType */: + return tryVisitIndexedAccess(innerNode); + case 198 /* TypeOperator */: + const typeOperatorNode = innerNode; + if (typeOperatorNode.operator === 143 /* KeyOfKeyword */) { + return tryVisitKeyOf(typeOperatorNode); + } + } + return visitNode(node, visitExistingNodeTreeSymbols, isTypeNode); + } + function tryVisitIndexedAccess(node) { + const resultObjectType = tryVisitSimpleTypeNode(node.objectType); + if (resultObjectType === void 0) { + return void 0; + } + return factory.updateIndexedAccessTypeNode(node, resultObjectType, visitNode(node.indexType, visitExistingNodeTreeSymbols, isTypeNode)); + } + function tryVisitKeyOf(node) { + Debug.assertEqual(node.operator, 143 /* KeyOfKeyword */); + const type = tryVisitSimpleTypeNode(node.type); + if (type === void 0) { + return void 0; + } + return factory.updateTypeOperatorNode(node, type); + } + function tryVisitTypeQuery(node) { + const { introducesError, node: exprName } = resolver.trackExistingEntityName(context, node.exprName); + if (!introducesError) { + return factory.updateTypeQueryNode( + node, + exprName, + visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode) + ); + } + const serializedName = resolver.serializeTypeName( + context, + node.exprName, + /*isTypeOf*/ + true + ); + if (serializedName) { + return resolver.markNodeReuse(context, serializedName, node.exprName); + } + } + function tryVisitTypeReference(node) { + if (resolver.canReuseTypeNode(context, node)) { + const { introducesError, node: newName } = resolver.trackExistingEntityName(context, node.typeName); + const typeArguments = visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode); + if (!introducesError) { + const updated = factory.updateTypeReferenceNode( + node, + newName, + typeArguments + ); + return resolver.markNodeReuse(context, updated, node); + } else { + const serializedName = resolver.serializeTypeName( + context, + node.typeName, + /*isTypeOf*/ + false, + typeArguments + ); + if (serializedName) { + return resolver.markNodeReuse(context, serializedName, node.typeName); + } + } + } + } + function visitExistingNodeTreeSymbolsWorker(node) { + var _a; + if (isJSDocTypeExpression(node)) { + return visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode); + } + if (isJSDocAllType(node) || node.kind === 319 /* JSDocNamepathType */) { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + if (isJSDocUnknownType(node)) { + return factory.createKeywordTypeNode(159 /* UnknownKeyword */); + } + if (isJSDocNullableType(node)) { + return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createLiteralTypeNode(factory.createNull())]); + } + if (isJSDocOptionalType(node)) { + return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + } + if (isJSDocNonNullableType(node)) { + return visitNode(node.type, visitExistingNodeTreeSymbols); + } + if (isJSDocVariadicType(node)) { + return factory.createArrayTypeNode(visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); + } + if (isJSDocTypeLiteral(node)) { + return factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (t) => { + const name = visitNode(isIdentifier(t.name) ? t.name : t.name.right, visitExistingNodeTreeSymbols, isIdentifier); + const overrideTypeNode = resolver.getJsDocPropertyOverride(context, node, t); + return factory.createPropertySignature( + /*modifiers*/ + void 0, + name, + t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(58 /* QuestionToken */) : void 0, + overrideTypeNode || t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ); + })); + } + if (isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "") { + return setOriginalNode(factory.createKeywordTypeNode(133 /* AnyKeyword */), node); + } + if ((isExpressionWithTypeArguments(node) || isTypeReferenceNode(node)) && isJSDocIndexSignature(node)) { + return factory.createTypeLiteralNode([factory.createIndexSignature( + /*modifiers*/ + void 0, + [factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "x", + /*questionToken*/ + void 0, + visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols, isTypeNode) + )], + visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols, isTypeNode) + )]); + } + if (isJSDocFunctionType(node)) { + if (isJSDocConstructSignature(node)) { + let newTypeNode; + return factory.createConstructorTypeNode( + /*modifiers*/ + void 0, + visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), + mapDefined(node.parameters, (p, i) => p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, void 0) : factory.createParameterDeclaration( + /*modifiers*/ + void 0, + getEffectiveDotDotDotForParameter(p), + resolver.markNodeReuse(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), + factory.cloneNode(p.questionToken), + visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), + /*initializer*/ + void 0 + )), + visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ); + } else { + return factory.createFunctionTypeNode( + visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), + map(node.parameters, (p, i) => factory.createParameterDeclaration( + /*modifiers*/ + void 0, + getEffectiveDotDotDotForParameter(p), + resolver.markNodeReuse(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), + factory.cloneNode(p.questionToken), + visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), + /*initializer*/ + void 0 + )), + visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ); + } + } + if (isThisTypeNode(node)) { + if (resolver.canReuseTypeNode(context, node)) { + return node; + } + markError(); + return node; + } + if (isTypeParameterDeclaration(node)) { + const { node: newName } = resolver.trackExistingEntityName(context, node.name); + return factory.updateTypeParameterDeclaration( + node, + visitNodes2(node.modifiers, visitExistingNodeTreeSymbols, isModifier), + // resolver.markNodeReuse(context, typeParameterToName(getDeclaredTypeOfSymbol(getSymbolOfDeclaration(node)), context), node), + newName, + visitNode(node.constraint, visitExistingNodeTreeSymbols, isTypeNode), + visitNode(node.default, visitExistingNodeTreeSymbols, isTypeNode) + ); + } + if (isIndexedAccessTypeNode(node)) { + const result = tryVisitIndexedAccess(node); + if (!result) { + markError(); + return node; + } + return result; + } + if (isTypeReferenceNode(node)) { + const result = tryVisitTypeReference(node); + if (result) { + return result; + } + markError(); + return node; + } + if (isLiteralImportTypeNode(node)) { + if (((_a = node.attributes) == null ? void 0 : _a.token) === 132 /* AssertKeyword */) { + markError(); + return node; + } + if (!resolver.canReuseTypeNode(context, node)) { + return resolver.serializeExistingTypeNode(context, node); + } + const specifier = rewriteModuleSpecifier2(node, node.argument.literal); + const literal = specifier === node.argument.literal ? reuseNode(context, node.argument.literal) : specifier; + return factory.updateImportTypeNode( + node, + literal === node.argument.literal ? reuseNode(context, node.argument) : factory.createLiteralTypeNode(literal), + visitNode(node.attributes, visitExistingNodeTreeSymbols, isImportAttributes), + visitNode(node.qualifier, visitExistingNodeTreeSymbols, isEntityName), + visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode), + node.isTypeOf + ); + } + if (isNamedDeclaration(node) && node.name.kind === 167 /* ComputedPropertyName */ && !resolver.hasLateBindableName(node)) { + if (!hasDynamicName(node)) { + return visitEachChild2(node, visitExistingNodeTreeSymbols); + } + if (resolver.shouldRemoveDeclaration(context, node)) { + return void 0; + } + } + if (isFunctionLike(node) && !node.type || isPropertyDeclaration(node) && !node.type && !node.initializer || isPropertySignature(node) && !node.type && !node.initializer || isParameter(node) && !node.type && !node.initializer) { + let visited = visitEachChild2(node, visitExistingNodeTreeSymbols); + if (visited === node) { + visited = resolver.markNodeReuse(context, factory.cloneNode(node), node); + } + visited.type = factory.createKeywordTypeNode(133 /* AnyKeyword */); + if (isParameter(node)) { + visited.modifiers = void 0; + } + return visited; + } + if (isTypeQueryNode(node)) { + const result = tryVisitTypeQuery(node); + if (!result) { + markError(); + return node; + } + return result; + } + if (isComputedPropertyName(node) && isEntityNameExpression(node.expression)) { + const { node: result, introducesError } = resolver.trackExistingEntityName(context, node.expression); + if (!introducesError) { + return factory.updateComputedPropertyName(node, result); + } else { + const computedPropertyNameType = resolver.serializeTypeOfExpression(context, node.expression); + let literal; + if (isLiteralTypeNode(computedPropertyNameType)) { + literal = computedPropertyNameType.literal; + } else { + const evaluated = resolver.evaluateEntityNameExpression(node.expression); + const literalNode = typeof evaluated.value === "string" ? factory.createStringLiteral( + evaluated.value, + /*isSingleQuote*/ + void 0 + ) : typeof evaluated.value === "number" ? factory.createNumericLiteral( + evaluated.value, + /*numericLiteralFlags*/ + 0 + ) : void 0; + if (!literalNode) { + if (isImportTypeNode(computedPropertyNameType)) { + resolver.trackComputedName(context, node.expression); + } + return node; + } + literal = literalNode; + } + if (literal.kind === 11 /* StringLiteral */ && isIdentifierText(literal.text, getEmitScriptTarget(options))) { + return factory.createIdentifier(literal.text); + } + if (literal.kind === 9 /* NumericLiteral */ && !literal.text.startsWith("-")) { + return literal; + } + return factory.updateComputedPropertyName(node, literal); + } + } + if (isTypePredicateNode(node)) { + let parameterName; + if (isIdentifier(node.parameterName)) { + const { node: result, introducesError } = resolver.trackExistingEntityName(context, node.parameterName); + if (introducesError) markError(); + parameterName = result; + } else { + parameterName = factory.cloneNode(node.parameterName); + } + return factory.updateTypePredicateNode(node, factory.cloneNode(node.assertsModifier), parameterName, visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); + } + if (isTupleTypeNode(node) || isTypeLiteralNode(node) || isMappedTypeNode(node)) { + const visited = visitEachChild2(node, visitExistingNodeTreeSymbols); + const clone = resolver.markNodeReuse(context, visited === node ? factory.cloneNode(node) : visited, node); + const flags = getEmitFlags(clone); + setEmitFlags(clone, flags | (context.flags & 1024 /* MultilineObjectLiterals */ && isTypeLiteralNode(node) ? 0 : 1 /* SingleLine */)); + return clone; + } + if (isStringLiteral(node) && !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */) && !node.singleQuote) { + const clone = factory.cloneNode(node); + clone.singleQuote = true; + return clone; + } + if (isConditionalTypeNode(node)) { + const checkType = visitNode(node.checkType, visitExistingNodeTreeSymbols, isTypeNode); + const disposeScope = resolver.enterNewScope(context, node); + const extendType = visitNode(node.extendsType, visitExistingNodeTreeSymbols, isTypeNode); + const trueType = visitNode(node.trueType, visitExistingNodeTreeSymbols, isTypeNode); + disposeScope(); + const falseType = visitNode(node.falseType, visitExistingNodeTreeSymbols, isTypeNode); + return factory.updateConditionalTypeNode( + node, + checkType, + extendType, + trueType, + falseType + ); + } + if (isTypeOperatorNode(node)) { + if (node.operator === 158 /* UniqueKeyword */ && node.type.kind === 155 /* SymbolKeyword */) { + if (!resolver.canReuseTypeNode(context, node)) { + markError(); + return node; + } + } else if (node.operator === 143 /* KeyOfKeyword */) { + const result = tryVisitKeyOf(node); + if (!result) { + markError(); + return node; + } + return result; + } + } + return visitEachChild2(node, visitExistingNodeTreeSymbols); + function visitEachChild2(node2, visitor) { + const nonlocalNode = !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(node2); + return visitEachChild( + node2, + visitor, + /*context*/ + void 0, + nonlocalNode ? visitNodesWithoutCopyingPositions : void 0 + ); + } + function visitNodesWithoutCopyingPositions(nodes, visitor, test, start, count) { + let result = visitNodes2(nodes, visitor, test, start, count); + if (result) { + if (result.pos !== -1 || result.end !== -1) { + if (result === nodes) { + result = factory.createNodeArray(nodes.slice(), nodes.hasTrailingComma); + } + setTextRangePosEnd(result, -1, -1); + } + } + return result; + } + function getEffectiveDotDotDotForParameter(p) { + return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(26 /* DotDotDotToken */) : void 0); + } + function getNameForJSDocFunctionParameter(p, index) { + return p.name && isIdentifier(p.name) && p.name.escapedText === "this" ? "this" : getEffectiveDotDotDotForParameter(p) ? `args` : `arg${index}`; + } + function rewriteModuleSpecifier2(parent, lit) { + const newName = resolver.getModuleSpecifierOverride(context, parent, lit); + return newName ? setOriginalNode(factory.createStringLiteral(newName), lit) : lit; + } + } + } + function serializeExistingTypeNode(typeNode, context, addUndefined) { + if (!typeNode) return void 0; + let result; + if ((!addUndefined || canAddUndefined(typeNode)) && resolver.canReuseTypeNode(context, typeNode)) { + result = tryReuseExistingTypeNode(context, typeNode); + if (result !== void 0) { + result = addUndefinedIfNeeded( + result, + addUndefined, + /*owner*/ + void 0, + context + ); + } + } + return result; + } + function serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol, requiresAddingUndefined, useFallback = requiresAddingUndefined !== void 0) { + if (!declaredType) return void 0; + if (!resolver.canReuseTypeNodeAnnotation(context, node, declaredType, symbol, requiresAddingUndefined)) { + if (!requiresAddingUndefined || !resolver.canReuseTypeNodeAnnotation( + context, + node, + declaredType, + symbol, + /*requiresAddingUndefined*/ + false + )) { + return void 0; + } + } + let result; + if (!requiresAddingUndefined || canAddUndefined(declaredType)) { + result = serializeExistingTypeNode(declaredType, context, requiresAddingUndefined); + } + if (result !== void 0 || !useFallback) { + return result; + } + context.tracker.reportInferenceFallback(node); + return resolver.serializeExistingTypeNode(context, declaredType, requiresAddingUndefined) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + function serializeExistingTypeNodeWithFallback(typeNode, context, addUndefined, targetNode) { + if (!typeNode) return void 0; + const result = serializeExistingTypeNode(typeNode, context, addUndefined); + if (result !== void 0) { + return result; + } + context.tracker.reportInferenceFallback(targetNode ?? typeNode); + return resolver.serializeExistingTypeNode(context, typeNode, addUndefined) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + function serializeTypeOfAccessor(accessor, symbol, context) { + return typeFromAccessor(accessor, symbol, context) ?? inferAccessorType(accessor, resolver.getAllAccessorDeclarations(accessor), context, symbol); + } + function serializeTypeOfExpression(expr, context, addUndefined, preserveLiterals) { + const result = typeFromExpression( + expr, + context, + /*isConstContext*/ + false, + addUndefined, + preserveLiterals + ); + return result.type !== void 0 ? result.type : inferExpressionType(expr, context, result.reportFallback); + } + function serializeTypeOfDeclaration(node, symbol, context) { + switch (node.kind) { + case 169 /* Parameter */: + case 341 /* JSDocParameterTag */: + return typeFromParameter(node, symbol, context); + case 260 /* VariableDeclaration */: + return typeFromVariable(node, symbol, context); + case 171 /* PropertySignature */: + case 348 /* JSDocPropertyTag */: + case 172 /* PropertyDeclaration */: + return typeFromProperty(node, symbol, context); + case 208 /* BindingElement */: + return inferTypeOfDeclaration(node, symbol, context); + case 277 /* ExportAssignment */: + return serializeTypeOfExpression( + node.expression, + context, + /*addUndefined*/ + void 0, + /*preserveLiterals*/ + true + ); + case 211 /* PropertyAccessExpression */: + case 212 /* ElementAccessExpression */: + case 226 /* BinaryExpression */: + return typeFromExpandoProperty(node, symbol, context); + case 303 /* PropertyAssignment */: + case 304 /* ShorthandPropertyAssignment */: + return typeFromPropertyAssignment(node, symbol, context); + default: + Debug.assertNever(node, `Node needs to be an inferrable node, found ${Debug.formatSyntaxKind(node.kind)}`); + } + } + function typeFromPropertyAssignment(node, symbol, context) { + const typeAnnotation = getEffectiveTypeAnnotationNode(node); + let result; + if (typeAnnotation && resolver.canReuseTypeNodeAnnotation(context, node, typeAnnotation, symbol)) { + result = serializeExistingTypeNode(typeAnnotation, context); + } + if (!result && node.kind === 303 /* PropertyAssignment */) { + const initializer = node.initializer; + const assertionNode = isJSDocTypeAssertion(initializer) ? getJSDocTypeAssertionType(initializer) : initializer.kind === 234 /* AsExpression */ || initializer.kind === 216 /* TypeAssertionExpression */ ? initializer.type : void 0; + if (assertionNode && !isConstTypeReference(assertionNode) && resolver.canReuseTypeNodeAnnotation(context, node, assertionNode, symbol)) { + result = serializeExistingTypeNode(assertionNode, context); + } + } + return result ?? inferTypeOfDeclaration( + node, + symbol, + context, + /*reportFallback*/ + false + ); + } + function serializeReturnTypeForSignature(node, symbol, context) { + switch (node.kind) { + case 177 /* GetAccessor */: + return serializeTypeOfAccessor(node, symbol, context); + case 174 /* MethodDeclaration */: + case 262 /* FunctionDeclaration */: + case 180 /* ConstructSignature */: + case 173 /* MethodSignature */: + case 179 /* CallSignature */: + case 176 /* Constructor */: + case 178 /* SetAccessor */: + case 181 /* IndexSignature */: + case 184 /* FunctionType */: + case 185 /* ConstructorType */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 317 /* JSDocFunctionType */: + case 323 /* JSDocSignature */: + return createReturnFromSignature(node, symbol, context); + default: + Debug.assertNever(node, `Node needs to be an inferrable node, found ${Debug.formatSyntaxKind(node.kind)}`); + } + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 177 /* GetAccessor */ ? isInJSFile(accessor) && getJSDocType(accessor) || getEffectiveReturnTypeNode(accessor) : getEffectiveSetAccessorTypeAnnotationNode(accessor); + } + } + function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) { + let accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && node !== accessors.firstAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor); + } + if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + } + return accessorType; + } + function typeFromAccessor(node, symbol, context) { + const accessorDeclarations = resolver.getAllAccessorDeclarations(node); + const accessorType = getTypeAnnotationFromAllAccessorDeclarations(node, accessorDeclarations); + if (accessorType && !isTypePredicateNode(accessorType)) { + return withNewScope(context, node, () => serializeTypeAnnotationOfDeclaration(accessorType, context, node, symbol) ?? inferTypeOfDeclaration(node, symbol, context)); + } + if (accessorDeclarations.getAccessor) { + return withNewScope(context, accessorDeclarations.getAccessor, () => createReturnFromSignature(accessorDeclarations.getAccessor, symbol, context)); + } + return void 0; + } + function typeFromVariable(node, symbol, context) { + var _a; + const declaredType = getEffectiveTypeAnnotationNode(node); + let resultType = failed; + if (declaredType) { + resultType = syntacticResult(serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol)); + } else if (node.initializer && (((_a = symbol.declarations) == null ? void 0 : _a.length) === 1 || countWhere(symbol.declarations, isVariableDeclaration) === 1)) { + if (!resolver.isExpandoFunctionDeclaration(node) && !isContextuallyTyped(node)) { + resultType = typeFromExpression( + node.initializer, + context, + /*isConstContext*/ + void 0, + /*requiresAddingUndefined*/ + void 0, + isVarConstLike(node) + ); + } + } + return resultType.type !== void 0 ? resultType.type : inferTypeOfDeclaration(node, symbol, context, resultType.reportFallback); + } + function typeFromParameter(node, symbol, context) { + const parent = node.parent; + if (parent.kind === 178 /* SetAccessor */) { + return serializeTypeOfAccessor( + parent, + /*symbol*/ + void 0, + context + ); + } + const declaredType = getEffectiveTypeAnnotationNode(node); + const addUndefined = resolver.requiresAddingImplicitUndefined(node, symbol, context.enclosingDeclaration); + let resultType = failed; + if (declaredType) { + resultType = syntacticResult(serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol, addUndefined)); + } else if (isParameter(node) && node.initializer && isIdentifier(node.name) && !isContextuallyTyped(node)) { + resultType = typeFromExpression( + node.initializer, + context, + /*isConstContext*/ + void 0, + addUndefined + ); + } + return resultType.type !== void 0 ? resultType.type : inferTypeOfDeclaration(node, symbol, context, resultType.reportFallback); + } + function typeFromExpandoProperty(node, symbol, context) { + const declaredType = getEffectiveTypeAnnotationNode(node); + let result; + if (declaredType) { + result = serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol); + } + const oldSuppressReportInferenceFallback = context.suppressReportInferenceFallback; + context.suppressReportInferenceFallback = true; + const resultType = result ?? inferTypeOfDeclaration( + node, + symbol, + context, + /*reportFallback*/ + false + ); + context.suppressReportInferenceFallback = oldSuppressReportInferenceFallback; + return resultType; + } + function typeFromProperty(node, symbol, context) { + const declaredType = getEffectiveTypeAnnotationNode(node); + const requiresAddingUndefined = resolver.requiresAddingImplicitUndefined(node, symbol, context.enclosingDeclaration); + let resultType = failed; + if (declaredType) { + resultType = syntacticResult(serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol, requiresAddingUndefined)); + } else { + const initializer = isPropertyDeclaration(node) ? node.initializer : void 0; + if (initializer && !isContextuallyTyped(node)) { + const isReadonly = isDeclarationReadonly(node); + resultType = typeFromExpression( + initializer, + context, + /*isConstContext*/ + void 0, + requiresAddingUndefined, + isReadonly + ); + } + } + return resultType.type !== void 0 ? resultType.type : inferTypeOfDeclaration(node, symbol, context, resultType.reportFallback); + } + function inferTypeOfDeclaration(node, symbol, context, reportFallback = true) { + if (reportFallback) { + context.tracker.reportInferenceFallback(node); + } + if (context.noInferenceFallback === true) { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + return resolver.serializeTypeOfDeclaration(context, node, symbol); + } + function inferExpressionType(node, context, reportFallback = true, requiresAddingUndefined) { + Debug.assert(!requiresAddingUndefined); + if (reportFallback) { + context.tracker.reportInferenceFallback(node); + } + if (context.noInferenceFallback === true) { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + return resolver.serializeTypeOfExpression(context, node) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + function inferReturnTypeOfSignatureSignature(node, context, symbol, reportFallback) { + if (reportFallback) { + context.tracker.reportInferenceFallback(node); + } + if (context.noInferenceFallback === true) { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + return resolver.serializeReturnTypeForSignature(context, node, symbol) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + function inferAccessorType(node, allAccessors, context, symbol, reportFallback = true) { + if (node.kind === 177 /* GetAccessor */) { + return createReturnFromSignature(node, symbol, context, reportFallback); + } else { + if (reportFallback) { + context.tracker.reportInferenceFallback(node); + } + const result = allAccessors.getAccessor && createReturnFromSignature(allAccessors.getAccessor, symbol, context, reportFallback); + return result ?? resolver.serializeTypeOfDeclaration(context, node, symbol) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + } + function withNewScope(context, node, fn) { + const cleanup = resolver.enterNewScope(context, node); + const result = fn(); + cleanup(); + return result; + } + function typeFromTypeAssertion(expression, type, context, requiresAddingUndefined) { + if (isConstTypeReference(type)) { + return typeFromExpression( + expression, + context, + /*isConstContext*/ + true, + requiresAddingUndefined + ); + } + return syntacticResult(serializeExistingTypeNodeWithFallback(type, context, requiresAddingUndefined)); + } + function typeFromExpression(node, context, isConstContext = false, requiresAddingUndefined = false, preserveLiterals = false) { + switch (node.kind) { + case 217 /* ParenthesizedExpression */: + if (isJSDocTypeAssertion(node)) { + return typeFromTypeAssertion(node.expression, getJSDocTypeAssertionType(node), context, requiresAddingUndefined); + } + return typeFromExpression(node.expression, context, isConstContext, requiresAddingUndefined); + case 80 /* Identifier */: + if (resolver.isUndefinedIdentifierExpression(node)) { + return syntacticResult(createUndefinedTypeNode()); + } + break; + case 106 /* NullKeyword */: + if (strictNullChecks) { + return syntacticResult(addUndefinedIfNeeded(factory.createLiteralTypeNode(factory.createNull()), requiresAddingUndefined, node, context)); + } else { + return syntacticResult(factory.createKeywordTypeNode(133 /* AnyKeyword */)); + } + case 219 /* ArrowFunction */: + case 218 /* FunctionExpression */: + Debug.type(node); + return withNewScope(context, node, () => typeFromFunctionLikeExpression(node, context)); + case 216 /* TypeAssertionExpression */: + case 234 /* AsExpression */: + const asExpression = node; + return typeFromTypeAssertion(asExpression.expression, asExpression.type, context, requiresAddingUndefined); + case 224 /* PrefixUnaryExpression */: + const unaryExpression = node; + if (isPrimitiveLiteralValue(unaryExpression)) { + return typeFromPrimitiveLiteral( + unaryExpression.operator === 40 /* PlusToken */ ? unaryExpression.operand : unaryExpression, + unaryExpression.operand.kind === 10 /* BigIntLiteral */ ? 163 /* BigIntKeyword */ : 150 /* NumberKeyword */, + context, + isConstContext || preserveLiterals, + requiresAddingUndefined + ); + } + break; + case 209 /* ArrayLiteralExpression */: + return typeFromArrayLiteral(node, context, isConstContext, requiresAddingUndefined); + case 210 /* ObjectLiteralExpression */: + return typeFromObjectLiteral(node, context, isConstContext, requiresAddingUndefined); + case 231 /* ClassExpression */: + return syntacticResult(inferExpressionType( + node, + context, + /*reportFallback*/ + true, + requiresAddingUndefined + )); + case 228 /* TemplateExpression */: + if (!isConstContext && !preserveLiterals) { + return syntacticResult(factory.createKeywordTypeNode(154 /* StringKeyword */)); + } + break; + default: + let typeKind; + let primitiveNode = node; + switch (node.kind) { + case 9 /* NumericLiteral */: + typeKind = 150 /* NumberKeyword */; + break; + case 15 /* NoSubstitutionTemplateLiteral */: + primitiveNode = factory.createStringLiteral(node.text); + typeKind = 154 /* StringKeyword */; + break; + case 11 /* StringLiteral */: + typeKind = 154 /* StringKeyword */; + break; + case 10 /* BigIntLiteral */: + typeKind = 163 /* BigIntKeyword */; + break; + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + typeKind = 136 /* BooleanKeyword */; + break; + } + if (typeKind) { + return typeFromPrimitiveLiteral(primitiveNode, typeKind, context, isConstContext || preserveLiterals, requiresAddingUndefined); + } + } + return failed; + } + function typeFromFunctionLikeExpression(fnNode, context) { + const returnType = createReturnFromSignature( + fnNode, + /*symbol*/ + void 0, + context + ); + const typeParameters = reuseTypeParameters(fnNode.typeParameters, context); + const parameters = fnNode.parameters.map((p) => ensureParameter(p, context)); + return syntacticResult( + factory.createFunctionTypeNode( + typeParameters, + parameters, + returnType + ) + ); + } + function canGetTypeFromArrayLiteral(arrayLiteral, context, isConstContext) { + if (!isConstContext) { + context.tracker.reportInferenceFallback(arrayLiteral); + return false; + } + for (const element of arrayLiteral.elements) { + if (element.kind === 230 /* SpreadElement */) { + context.tracker.reportInferenceFallback(element); + return false; + } + } + return true; + } + function typeFromArrayLiteral(arrayLiteral, context, isConstContext, requiresAddingUndefined) { + if (!canGetTypeFromArrayLiteral(arrayLiteral, context, isConstContext)) { + if (requiresAddingUndefined || isDeclaration(walkUpParenthesizedExpressions(arrayLiteral).parent)) { + return alreadyReported; + } + return syntacticResult(inferExpressionType( + arrayLiteral, + context, + /*reportFallback*/ + false, + requiresAddingUndefined + )); + } + const oldNoInferenceFallback = context.noInferenceFallback; + context.noInferenceFallback = true; + const elementTypesInfo = []; + for (const element of arrayLiteral.elements) { + Debug.assert(element.kind !== 230 /* SpreadElement */); + if (element.kind === 232 /* OmittedExpression */) { + elementTypesInfo.push( + createUndefinedTypeNode() + ); + } else { + const expressionType = typeFromExpression(element, context, isConstContext); + const elementType = expressionType.type !== void 0 ? expressionType.type : inferExpressionType(element, context, expressionType.reportFallback); + elementTypesInfo.push(elementType); + } + } + const tupleType = factory.createTupleTypeNode(elementTypesInfo); + tupleType.emitNode = { flags: 1, autoGenerate: void 0, internalFlags: 0 }; + context.noInferenceFallback = oldNoInferenceFallback; + return notImplemented2; + } + function canGetTypeFromObjectLiteral(objectLiteral, context) { + let result = true; + for (const prop of objectLiteral.properties) { + if (prop.flags & 262144 /* ThisNodeHasError */) { + result = false; + break; + } + if (prop.kind === 304 /* ShorthandPropertyAssignment */ || prop.kind === 305 /* SpreadAssignment */) { + context.tracker.reportInferenceFallback(prop); + result = false; + } else if (prop.name.flags & 262144 /* ThisNodeHasError */) { + result = false; + break; + } else if (prop.name.kind === 81 /* PrivateIdentifier */) { + result = false; + } else if (prop.name.kind === 167 /* ComputedPropertyName */) { + const expression = prop.name.expression; + if (!isPrimitiveLiteralValue( + expression, + /*includeBigInt*/ + false + ) && !resolver.isDefinitelyReferenceToGlobalSymbolObject(expression)) { + context.tracker.reportInferenceFallback(prop.name); + result = false; + } + } + } + return result; + } + function typeFromObjectLiteral(objectLiteral, context, isConstContext, requiresAddingUndefined) { + if (!canGetTypeFromObjectLiteral(objectLiteral, context)) { + if (requiresAddingUndefined || isDeclaration(walkUpParenthesizedExpressions(objectLiteral).parent)) { + return alreadyReported; + } + return syntacticResult(inferExpressionType( + objectLiteral, + context, + /*reportFallback*/ + false, + requiresAddingUndefined + )); + } + const oldNoInferenceFallback = context.noInferenceFallback; + context.noInferenceFallback = true; + const properties = []; + const oldFlags = context.flags; + context.flags |= 4194304 /* InObjectTypeLiteral */; + for (const prop of objectLiteral.properties) { + Debug.assert(!isShorthandPropertyAssignment(prop) && !isSpreadAssignment(prop)); + const name = prop.name; + let newProp; + switch (prop.kind) { + case 174 /* MethodDeclaration */: + newProp = withNewScope(context, prop, () => typeFromObjectLiteralMethod(prop, name, context, isConstContext)); + break; + case 303 /* PropertyAssignment */: + newProp = typeFromObjectLiteralPropertyAssignment(prop, name, context, isConstContext); + break; + case 178 /* SetAccessor */: + case 177 /* GetAccessor */: + newProp = typeFromObjectLiteralAccessor(prop, name, context); + break; + } + if (newProp) { + setCommentRange(newProp, prop); + properties.push(newProp); + } + } + context.flags = oldFlags; + const typeNode = factory.createTypeLiteralNode(properties); + if (!(context.flags & 1024 /* MultilineObjectLiterals */)) { + setEmitFlags(typeNode, 1 /* SingleLine */); + } + context.noInferenceFallback = oldNoInferenceFallback; + return notImplemented2; + } + function typeFromObjectLiteralPropertyAssignment(prop, name, context, isConstContext) { + const modifiers = isConstContext ? [factory.createModifier(148 /* ReadonlyKeyword */)] : []; + const expressionResult = typeFromExpression(prop.initializer, context, isConstContext); + const typeNode = expressionResult.type !== void 0 ? expressionResult.type : inferTypeOfDeclaration( + prop, + /*symbol*/ + void 0, + context, + expressionResult.reportFallback + ); + return factory.createPropertySignature( + modifiers, + reuseNode(context, name), + /*questionToken*/ + void 0, + typeNode + ); + } + function ensureParameter(p, context) { + return factory.updateParameterDeclaration( + p, + [], + reuseNode(context, p.dotDotDotToken), + resolver.serializeNameOfParameter(context, p), + resolver.isOptionalParameter(p) ? factory.createToken(58 /* QuestionToken */) : void 0, + typeFromParameter( + p, + /*symbol*/ + void 0, + context + ), + // Ignore private param props, since this type is going straight back into a param + /*initializer*/ + void 0 + ); + } + function reuseTypeParameters(typeParameters, context) { + return typeParameters == null ? void 0 : typeParameters.map((tp) => { + var _a; + const { node: tpName } = resolver.trackExistingEntityName(context, tp.name); + return factory.updateTypeParameterDeclaration( + tp, + (_a = tp.modifiers) == null ? void 0 : _a.map((m) => reuseNode(context, m)), + tpName, + serializeExistingTypeNodeWithFallback(tp.constraint, context), + serializeExistingTypeNodeWithFallback(tp.default, context) + ); + }); + } + function typeFromObjectLiteralMethod(method, name, context, isConstContext) { + const returnType = createReturnFromSignature( + method, + /*symbol*/ + void 0, + context + ); + const typeParameters = reuseTypeParameters(method.typeParameters, context); + const parameters = method.parameters.map((p) => ensureParameter(p, context)); + if (isConstContext) { + return factory.createPropertySignature( + [factory.createModifier(148 /* ReadonlyKeyword */)], + reuseNode(context, name), + reuseNode(context, method.questionToken), + factory.createFunctionTypeNode( + typeParameters, + parameters, + returnType + ) + ); + } else { + if (isIdentifier(name) && name.escapedText === "new") { + name = factory.createStringLiteral("new"); + } + return factory.createMethodSignature( + [], + reuseNode(context, name), + reuseNode(context, method.questionToken), + typeParameters, + parameters, + returnType + ); + } + } + function typeFromObjectLiteralAccessor(accessor, name, context) { + const allAccessors = resolver.getAllAccessorDeclarations(accessor); + const getAccessorType = allAccessors.getAccessor && getTypeAnnotationFromAccessor(allAccessors.getAccessor); + const setAccessorType = allAccessors.setAccessor && getTypeAnnotationFromAccessor(allAccessors.setAccessor); + if (getAccessorType !== void 0 && setAccessorType !== void 0) { + return withNewScope(context, accessor, () => { + const parameters = accessor.parameters.map((p) => ensureParameter(p, context)); + if (isGetAccessor(accessor)) { + return factory.updateGetAccessorDeclaration( + accessor, + [], + reuseNode(context, name), + parameters, + serializeExistingTypeNodeWithFallback(getAccessorType, context), + /*body*/ + void 0 + ); + } else { + return factory.updateSetAccessorDeclaration( + accessor, + [], + reuseNode(context, name), + parameters, + /*body*/ + void 0 + ); + } + }); + } else if (allAccessors.firstAccessor === accessor) { + const foundType = getAccessorType ? withNewScope(context, allAccessors.getAccessor, () => serializeExistingTypeNodeWithFallback(getAccessorType, context)) : setAccessorType ? withNewScope(context, allAccessors.setAccessor, () => serializeExistingTypeNodeWithFallback(setAccessorType, context)) : void 0; + const propertyType = foundType ?? inferAccessorType( + accessor, + allAccessors, + context, + /*symbol*/ + void 0 + ); + const propertySignature = factory.createPropertySignature( + allAccessors.setAccessor === void 0 ? [factory.createModifier(148 /* ReadonlyKeyword */)] : [], + reuseNode(context, name), + /*questionToken*/ + void 0, + propertyType + ); + return propertySignature; + } + } + function createUndefinedTypeNode() { + if (strictNullChecks) { + return factory.createKeywordTypeNode(157 /* UndefinedKeyword */); + } else { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + } + function typeFromPrimitiveLiteral(node, baseType, context, preserveLiterals, requiresAddingUndefined) { + let result; + if (preserveLiterals) { + if (node.kind === 224 /* PrefixUnaryExpression */ && node.operator === 40 /* PlusToken */) { + result = factory.createLiteralTypeNode(reuseNode(context, node.operand)); + } + result = factory.createLiteralTypeNode(reuseNode(context, node)); + } else { + result = factory.createKeywordTypeNode(baseType); + } + return syntacticResult(addUndefinedIfNeeded(result, requiresAddingUndefined, node, context)); + } + function addUndefinedIfNeeded(node, addUndefined, owner, context) { + const parentDeclaration = owner && walkUpParenthesizedExpressions(owner).parent; + const optionalDeclaration = parentDeclaration && isDeclaration(parentDeclaration) && isOptionalDeclaration(parentDeclaration); + if (!strictNullChecks || !(addUndefined || optionalDeclaration)) return node; + if (!canAddUndefined(node)) { + context.tracker.reportInferenceFallback(node); + } + if (isUnionTypeNode(node)) { + return factory.createUnionTypeNode([...node.types, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + } + return factory.createUnionTypeNode([node, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + } + function canAddUndefined(node) { + if (!strictNullChecks) return true; + if (isKeyword(node.kind) || node.kind === 201 /* LiteralType */ || node.kind === 184 /* FunctionType */ || node.kind === 185 /* ConstructorType */ || node.kind === 188 /* ArrayType */ || node.kind === 189 /* TupleType */ || node.kind === 187 /* TypeLiteral */ || node.kind === 203 /* TemplateLiteralType */ || node.kind === 197 /* ThisType */) { + return true; + } + if (node.kind === 196 /* ParenthesizedType */) { + return canAddUndefined(node.type); + } + if (node.kind === 192 /* UnionType */ || node.kind === 193 /* IntersectionType */) { + return node.types.every(canAddUndefined); + } + return false; + } + function createReturnFromSignature(fn, symbol, context, reportFallback = true) { + let returnType = failed; + const returnTypeNode = isJSDocConstructSignature(fn) ? getEffectiveTypeAnnotationNode(fn.parameters[0]) : getEffectiveReturnTypeNode(fn); + if (returnTypeNode) { + returnType = syntacticResult(serializeTypeAnnotationOfDeclaration(returnTypeNode, context, fn, symbol)); + } else if (isValueSignatureDeclaration(fn)) { + returnType = typeFromSingleReturnExpression(fn, context); + } + return returnType.type !== void 0 ? returnType.type : inferReturnTypeOfSignatureSignature(fn, context, symbol, reportFallback && returnType.reportFallback && !returnTypeNode); + } + function typeFromSingleReturnExpression(declaration, context) { + let candidateExpr; + if (declaration && !nodeIsMissing(declaration.body)) { + const flags = getFunctionFlags(declaration); + if (flags & 3 /* AsyncGenerator */) return failed; + const body = declaration.body; + if (body && isBlock(body)) { + forEachReturnStatement(body, (s) => { + if (s.parent !== body) { + candidateExpr = void 0; + return true; + } + if (!candidateExpr) { + candidateExpr = s.expression; + } else { + candidateExpr = void 0; + return true; + } + }); + } else { + candidateExpr = body; + } + } + if (candidateExpr) { + if (isContextuallyTyped(candidateExpr)) { + const type = isJSDocTypeAssertion(candidateExpr) ? getJSDocTypeAssertionType(candidateExpr) : isAsExpression(candidateExpr) || isTypeAssertionExpression(candidateExpr) ? candidateExpr.type : void 0; + if (type && !isConstTypeReference(type)) { + return syntacticResult(serializeExistingTypeNode(type, context)); + } + } else { + return typeFromExpression(candidateExpr, context); + } + } + return failed; + } + function isContextuallyTyped(node) { + return findAncestor(node.parent, (n) => { + return isCallExpression(n) || !isFunctionLikeDeclaration(n) && !!getEffectiveTypeAnnotationNode(n) || isJsxElement(n) || isJsxExpression(n); + }); + } +} + +// src/tsc/tsc.ts +Debug.loggingHost = { + log(_level, s) { + sys.write(`${s || ""}${sys.newLine}`); + } +}; +if (Debug.isDebugging) { + Debug.enableDebugInfo(); +} +if (sys.tryEnableSourceMapsForHost && /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))) { + sys.tryEnableSourceMapsForHost(); +} +if (sys.setBlocking) { + sys.setBlocking(); +} +executeCommandLine(sys, noop, sys.args); +//# sourceMappingURL=_tsc.js.map diff --git a/node_modules/typescript/lib/_tsserver.js b/node_modules/typescript/lib/_tsserver.js new file mode 100644 index 00000000..39115c7f --- /dev/null +++ b/node_modules/typescript/lib/_tsserver.js @@ -0,0 +1,659 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// src/tsserver/server.ts +var import_os2 = __toESM(require("os")); + +// src/typescript/typescript.ts +var typescript_exports = {}; +__reExport(typescript_exports, require("./typescript.js")); + +// src/tsserver/nodeServer.ts +var import_child_process = __toESM(require("child_process")); +var import_fs = __toESM(require("fs")); +var import_net = __toESM(require("net")); +var import_os = __toESM(require("os")); +var import_readline = __toESM(require("readline")); + +// src/tsserver/common.ts +function getLogLevel(level) { + if (level) { + const l = level.toLowerCase(); + for (const name in typescript_exports.server.LogLevel) { + if (isNaN(+name) && l === name.toLowerCase()) { + return typescript_exports.server.LogLevel[name]; + } + } + } + return void 0; +} + +// src/tsserver/nodeServer.ts +function parseLoggingEnvironmentString(logEnvStr) { + if (!logEnvStr) { + return {}; + } + const logEnv = { logToFile: true }; + const args = logEnvStr.split(" "); + const len = args.length - 1; + for (let i = 0; i < len; i += 2) { + const option = args[i]; + const { value, extraPartCounter } = getEntireValue(i + 1); + i += extraPartCounter; + if (option && value) { + switch (option) { + case "-file": + logEnv.file = value; + break; + case "-level": + const level = getLogLevel(value); + logEnv.detailLevel = level !== void 0 ? level : typescript_exports.server.LogLevel.normal; + break; + case "-traceToConsole": + logEnv.traceToConsole = value.toLowerCase() === "true"; + break; + case "-logToFile": + logEnv.logToFile = value.toLowerCase() === "true"; + break; + } + } + } + return logEnv; + function getEntireValue(initialIndex) { + let pathStart = args[initialIndex]; + let extraPartCounter = 0; + if (pathStart.charCodeAt(0) === typescript_exports.CharacterCodes.doubleQuote && pathStart.charCodeAt(pathStart.length - 1) !== typescript_exports.CharacterCodes.doubleQuote) { + for (let i = initialIndex + 1; i < args.length; i++) { + pathStart += " "; + pathStart += args[i]; + extraPartCounter++; + if (pathStart.charCodeAt(pathStart.length - 1) === typescript_exports.CharacterCodes.doubleQuote) break; + } + } + return { value: (0, typescript_exports.stripQuotes)(pathStart), extraPartCounter }; + } +} +function parseServerMode() { + const mode = typescript_exports.server.findArgument("--serverMode"); + if (!mode) return void 0; + switch (mode.toLowerCase()) { + case "semantic": + return typescript_exports.LanguageServiceMode.Semantic; + case "partialsemantic": + return typescript_exports.LanguageServiceMode.PartialSemantic; + case "syntactic": + return typescript_exports.LanguageServiceMode.Syntactic; + default: + return mode; + } +} +function initializeNodeSystem() { + const sys4 = typescript_exports.Debug.checkDefined(typescript_exports.sys); + class Logger { + constructor(logFilename, traceToConsole, level) { + this.logFilename = logFilename; + this.traceToConsole = traceToConsole; + this.level = level; + this.seq = 0; + this.inGroup = false; + this.firstInGroup = true; + this.fd = -1; + if (this.logFilename) { + try { + this.fd = import_fs.default.openSync(this.logFilename, "w"); + } catch { + } + } + } + static padStringRight(str, padding) { + return (str + padding).slice(0, padding.length); + } + close() { + if (this.fd >= 0) { + import_fs.default.close(this.fd, typescript_exports.noop); + } + } + getLogFileName() { + return this.logFilename; + } + perftrc(s) { + this.msg(s, typescript_exports.server.Msg.Perf); + } + info(s) { + this.msg(s, typescript_exports.server.Msg.Info); + } + err(s) { + this.msg(s, typescript_exports.server.Msg.Err); + } + startGroup() { + this.inGroup = true; + this.firstInGroup = true; + } + endGroup() { + this.inGroup = false; + } + loggingEnabled() { + return !!this.logFilename || this.traceToConsole; + } + hasLevel(level) { + return this.loggingEnabled() && this.level >= level; + } + msg(s, type = typescript_exports.server.Msg.Err) { + if (!this.canWrite()) return; + s = `[${typescript_exports.server.nowString()}] ${s} +`; + if (!this.inGroup || this.firstInGroup) { + const prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); + s = prefix + s; + } + this.write(s, type); + if (!this.inGroup) { + this.seq++; + } + } + canWrite() { + return this.fd >= 0 || this.traceToConsole; + } + write(s, _type) { + if (this.fd >= 0) { + const buf = Buffer.from(s); + import_fs.default.writeSync( + this.fd, + buf, + 0, + buf.length, + /*position*/ + null + ); + } + if (this.traceToConsole) { + console.warn(s); + } + } + } + const libDirectory = (0, typescript_exports.getDirectoryPath)((0, typescript_exports.normalizePath)(sys4.getExecutingFilePath())); + const useWatchGuard = process.platform === "win32"; + const originalWatchDirectory = sys4.watchDirectory.bind(sys4); + const logger = createLogger(); + typescript_exports.Debug.loggingHost = { + log(level, s) { + switch (level) { + case typescript_exports.LogLevel.Error: + case typescript_exports.LogLevel.Warning: + return logger.msg(s, typescript_exports.server.Msg.Err); + case typescript_exports.LogLevel.Info: + case typescript_exports.LogLevel.Verbose: + return logger.msg(s, typescript_exports.server.Msg.Info); + } + } + }; + const pending = (0, typescript_exports.createQueue)(); + let canWrite = true; + if (useWatchGuard) { + const currentDrive = extractWatchDirectoryCacheKey( + sys4.resolvePath(sys4.getCurrentDirectory()), + /*currentDriveKey*/ + void 0 + ); + const statusCache = /* @__PURE__ */ new Map(); + sys4.watchDirectory = (path, callback, recursive, options) => { + const cacheKey = extractWatchDirectoryCacheKey(path, currentDrive); + let status = cacheKey && statusCache.get(cacheKey); + if (status === void 0) { + if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) { + logger.info(`${cacheKey} for path ${path} not found in cache...`); + } + try { + const args = [(0, typescript_exports.combinePaths)(libDirectory, "watchGuard.js"), path]; + if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) { + logger.info(`Starting ${process.execPath} with args:${typescript_exports.server.stringifyIndented(args)}`); + } + import_child_process.default.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } }); + status = true; + if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) { + logger.info(`WatchGuard for path ${path} returned: OK`); + } + } catch (e) { + status = false; + if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) { + logger.info(`WatchGuard for path ${path} returned: ${e.message}`); + } + } + if (cacheKey) { + statusCache.set(cacheKey, status); + } + } else if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) { + logger.info(`watchDirectory for ${path} uses cached drive information.`); + } + if (status) { + return watchDirectorySwallowingException(path, callback, recursive, options); + } else { + return typescript_exports.noopFileWatcher; + } + }; + } else { + sys4.watchDirectory = watchDirectorySwallowingException; + } + sys4.write = (s) => writeMessage(Buffer.from(s, "utf8")); + sys4.setTimeout = setTimeout; + sys4.clearTimeout = clearTimeout; + sys4.setImmediate = setImmediate; + sys4.clearImmediate = clearImmediate; + if (typeof global !== "undefined" && global.gc) { + sys4.gc = () => { + var _a; + return (_a = global.gc) == null ? void 0 : _a.call(global); + }; + } + const cancellationToken = createCancellationToken(sys4.args); + const localeStr = typescript_exports.server.findArgument("--locale"); + if (localeStr) { + (0, typescript_exports.validateLocaleAndSetLanguage)(localeStr, sys4); + } + const modeOrUnknown = parseServerMode(); + let serverMode; + let unknownServerMode; + if (modeOrUnknown !== void 0) { + if (typeof modeOrUnknown === "number") serverMode = modeOrUnknown; + else unknownServerMode = modeOrUnknown; + } + return { + args: process.argv, + logger, + cancellationToken, + serverMode, + unknownServerMode, + startSession: startNodeSession + }; + function createLogger() { + const cmdLineLogFileName = typescript_exports.server.findArgument("--logFile"); + const cmdLineVerbosity = getLogLevel(typescript_exports.server.findArgument("--logVerbosity")); + const envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); + const unsubstitutedLogFileName = cmdLineLogFileName ? (0, typescript_exports.stripQuotes)(cmdLineLogFileName) : envLogOptions.logToFile ? envLogOptions.file || libDirectory + "/.log" + process.pid.toString() : void 0; + const substitutedLogFileName = unsubstitutedLogFileName ? unsubstitutedLogFileName.replace("PID", process.pid.toString()) : void 0; + const logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel; + return new Logger(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity); + } + function writeMessage(buf) { + if (!canWrite) { + pending.enqueue(buf); + } else { + canWrite = false; + process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary); + } + } + function setCanWriteFlagAndWriteMessageIfNecessary() { + canWrite = true; + if (!pending.isEmpty()) { + writeMessage(pending.dequeue()); + } + } + function extractWatchDirectoryCacheKey(path, currentDriveKey) { + path = (0, typescript_exports.normalizeSlashes)(path); + if (isUNCPath(path)) { + const firstSlash = path.indexOf(typescript_exports.directorySeparator, 2); + return firstSlash !== -1 ? (0, typescript_exports.toFileNameLowerCase)(path.substring(0, firstSlash)) : path; + } + const rootLength = (0, typescript_exports.getRootLength)(path); + if (rootLength === 0) { + return currentDriveKey; + } + if (path.charCodeAt(1) === typescript_exports.CharacterCodes.colon && path.charCodeAt(2) === typescript_exports.CharacterCodes.slash) { + return (0, typescript_exports.toFileNameLowerCase)(path.charAt(0)); + } + if (path.charCodeAt(0) === typescript_exports.CharacterCodes.slash && path.charCodeAt(1) !== typescript_exports.CharacterCodes.slash) { + return currentDriveKey; + } + return void 0; + } + function isUNCPath(s) { + return s.length > 2 && s.charCodeAt(0) === typescript_exports.CharacterCodes.slash && s.charCodeAt(1) === typescript_exports.CharacterCodes.slash; + } + function watchDirectorySwallowingException(path, callback, recursive, options) { + try { + return originalWatchDirectory(path, callback, recursive, options); + } catch (e) { + logger.info(`Exception when creating directory watcher: ${e.message}`); + return typescript_exports.noopFileWatcher; + } + } +} +function parseEventPort(eventPortStr) { + const eventPort = eventPortStr === void 0 ? void 0 : parseInt(eventPortStr); + return eventPort !== void 0 && !isNaN(eventPort) ? eventPort : void 0; +} +function startNodeSession(options, logger, cancellationToken) { + const rl = import_readline.default.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: false + }); + const _NodeTypingsInstallerAdapter = class _NodeTypingsInstallerAdapter extends typescript_exports.server.TypingsInstallerAdapter { + constructor(telemetryEnabled2, logger2, host, globalTypingsCacheLocation, typingSafeListLocation2, typesMapLocation2, npmLocation2, validateDefaultNpmLocation2, event) { + super( + telemetryEnabled2, + logger2, + host, + globalTypingsCacheLocation, + event, + _NodeTypingsInstallerAdapter.maxActiveRequestCount + ); + this.typingSafeListLocation = typingSafeListLocation2; + this.typesMapLocation = typesMapLocation2; + this.npmLocation = npmLocation2; + this.validateDefaultNpmLocation = validateDefaultNpmLocation2; + } + createInstallerProcess() { + if (this.logger.hasLevel(typescript_exports.server.LogLevel.requestTime)) { + this.logger.info("Binding..."); + } + const args = [typescript_exports.server.Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation]; + if (this.telemetryEnabled) { + args.push(typescript_exports.server.Arguments.EnableTelemetry); + } + if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { + args.push(typescript_exports.server.Arguments.LogFile, (0, typescript_exports.combinePaths)((0, typescript_exports.getDirectoryPath)((0, typescript_exports.normalizeSlashes)(this.logger.getLogFileName())), `ti-${process.pid}.log`)); + } + if (this.typingSafeListLocation) { + args.push(typescript_exports.server.Arguments.TypingSafeListLocation, this.typingSafeListLocation); + } + if (this.typesMapLocation) { + args.push(typescript_exports.server.Arguments.TypesMapLocation, this.typesMapLocation); + } + if (this.npmLocation) { + args.push(typescript_exports.server.Arguments.NpmLocation, this.npmLocation); + } + if (this.validateDefaultNpmLocation) { + args.push(typescript_exports.server.Arguments.ValidateDefaultNpmLocation); + } + const execArgv = []; + for (const arg of process.execArgv) { + const match = /^--((?:debug|inspect)(?:-brk)?)(?:=(\d+))?$/.exec(arg); + if (match) { + const currentPort = match[2] !== void 0 ? +match[2] : match[1].charAt(0) === "d" ? 5858 : 9229; + execArgv.push(`--${match[1]}=${currentPort + 1}`); + break; + } + } + const typingsInstaller = (0, typescript_exports.combinePaths)((0, typescript_exports.getDirectoryPath)(typescript_exports.sys.getExecutingFilePath()), "typingsInstaller.js"); + this.installer = import_child_process.default.fork(typingsInstaller, args, { execArgv }); + this.installer.on("message", (m) => this.handleMessage(m)); + this.host.setImmediate(() => this.event({ pid: this.installer.pid }, "typingsInstallerPid")); + process.on("exit", () => { + this.installer.kill(); + }); + return this.installer; + } + }; + // This number is essentially arbitrary. Processing more than one typings request + // at a time makes sense, but having too many in the pipe results in a hang + // (see https://github.com/nodejs/node/issues/7657). + // It would be preferable to base our limit on the amount of space left in the + // buffer, but we have yet to find a way to retrieve that value. + _NodeTypingsInstallerAdapter.maxActiveRequestCount = 10; + let NodeTypingsInstallerAdapter = _NodeTypingsInstallerAdapter; + class IOSession extends typescript_exports.server.Session { + constructor() { + const event = (body, eventName) => { + this.event(body, eventName); + }; + const host = typescript_exports.sys; + const typingsInstaller = disableAutomaticTypingAcquisition ? void 0 : new NodeTypingsInstallerAdapter(telemetryEnabled, logger, host, getGlobalTypingsCacheLocation(), typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, event); + super({ + host, + cancellationToken, + ...options, + typingsInstaller, + byteLength: Buffer.byteLength, + hrtime: process.hrtime, + logger, + canUseEvents: true, + typesMapLocation + }); + this.eventPort = eventPort; + if (this.canUseEvents && this.eventPort) { + const s = import_net.default.connect({ port: this.eventPort }, () => { + this.eventSocket = s; + if (this.socketEventQueue) { + for (const event2 of this.socketEventQueue) { + this.writeToEventSocket(event2.body, event2.eventName); + } + this.socketEventQueue = void 0; + } + }); + } + this.constructed = true; + } + event(body, eventName) { + typescript_exports.Debug.assert(!!this.constructed, "Should only call `IOSession.prototype.event` on an initialized IOSession"); + if (this.canUseEvents && this.eventPort) { + if (!this.eventSocket) { + if (this.logger.hasLevel(typescript_exports.server.LogLevel.verbose)) { + this.logger.info(`eventPort: event "${eventName}" queued, but socket not yet initialized`); + } + (this.socketEventQueue || (this.socketEventQueue = [])).push({ body, eventName }); + return; + } else { + typescript_exports.Debug.assert(this.socketEventQueue === void 0); + this.writeToEventSocket(body, eventName); + } + } else { + super.event(body, eventName); + } + } + writeToEventSocket(body, eventName) { + this.eventSocket.write(typescript_exports.server.formatMessage(typescript_exports.server.toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8"); + } + exit() { + var _a; + this.logger.info("Exiting..."); + this.projectService.closeLog(); + (_a = typescript_exports.tracing) == null ? void 0 : _a.stopTracing(); + process.exit(0); + } + listen() { + rl.on("line", (input) => { + const message = input.trim(); + this.onMessage(message); + }); + rl.on("close", () => { + this.exit(); + }); + } + } + class IpcIOSession extends IOSession { + writeMessage(msg) { + const verboseLogging = logger.hasLevel(typescript_exports.server.LogLevel.verbose); + if (verboseLogging) { + const json = JSON.stringify(msg); + logger.info(`${msg.type}:${typescript_exports.server.indent(json)}`); + } + process.send(msg); + } + parseMessage(message) { + return message; + } + toStringMessage(message) { + return JSON.stringify(message, void 0, 2); + } + listen() { + process.on("message", (e) => { + this.onMessage(e); + }); + process.on("disconnect", () => { + this.exit(); + }); + } + } + const eventPort = parseEventPort(typescript_exports.server.findArgument("--eventPort")); + const typingSafeListLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypingSafeListLocation); + const typesMapLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypesMapLocation) || (0, typescript_exports.combinePaths)((0, typescript_exports.getDirectoryPath)(typescript_exports.sys.getExecutingFilePath()), "typesMap.json"); + const npmLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.NpmLocation); + const validateDefaultNpmLocation = typescript_exports.server.hasArgument(typescript_exports.server.Arguments.ValidateDefaultNpmLocation); + const disableAutomaticTypingAcquisition = typescript_exports.server.hasArgument("--disableAutomaticTypingAcquisition"); + const useNodeIpc = typescript_exports.server.hasArgument("--useNodeIpc"); + const telemetryEnabled = typescript_exports.server.hasArgument(typescript_exports.server.Arguments.EnableTelemetry); + const commandLineTraceDir = typescript_exports.server.findArgument("--traceDirectory"); + const traceDir = commandLineTraceDir ? (0, typescript_exports.stripQuotes)(commandLineTraceDir) : process.env.TSS_TRACE; + if (traceDir) { + (0, typescript_exports.startTracing)("server", traceDir); + } + const ioSession = useNodeIpc ? new IpcIOSession() : new IOSession(); + process.on("uncaughtException", (err) => { + ioSession.logError(err, "unknown"); + }); + process.noAsar = true; + ioSession.listen(); + function getGlobalTypingsCacheLocation() { + switch (process.platform) { + case "win32": { + const basePath = process.env.LOCALAPPDATA || process.env.APPDATA || import_os.default.homedir && import_os.default.homedir() || process.env.USERPROFILE || process.env.HOMEDRIVE && process.env.HOMEPATH && (0, typescript_exports.normalizeSlashes)(process.env.HOMEDRIVE + process.env.HOMEPATH) || import_os.default.tmpdir(); + return (0, typescript_exports.combinePaths)((0, typescript_exports.combinePaths)((0, typescript_exports.normalizeSlashes)(basePath), "Microsoft/TypeScript"), typescript_exports.versionMajorMinor); + } + case "openbsd": + case "freebsd": + case "netbsd": + case "darwin": + case "linux": + case "android": { + const cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin"); + return (0, typescript_exports.combinePaths)((0, typescript_exports.combinePaths)(cacheLocation, "typescript"), typescript_exports.versionMajorMinor); + } + default: + return typescript_exports.Debug.fail(`unsupported platform '${process.platform}'`); + } + } + function getNonWindowsCacheLocation(platformIsDarwin) { + if (process.env.XDG_CACHE_HOME) { + return process.env.XDG_CACHE_HOME; + } + const usersDir = platformIsDarwin ? "Users" : "home"; + const homePath = import_os.default.homedir && import_os.default.homedir() || process.env.HOME || (process.env.LOGNAME || process.env.USER) && `/${usersDir}/${process.env.LOGNAME || process.env.USER}` || import_os.default.tmpdir(); + const cacheFolder = platformIsDarwin ? "Library/Caches" : ".cache"; + return (0, typescript_exports.combinePaths)((0, typescript_exports.normalizeSlashes)(homePath), cacheFolder); + } +} +function pipeExists(name) { + return import_fs.default.existsSync(name); +} +function createCancellationToken(args) { + let cancellationPipeName; + for (let i = 0; i < args.length - 1; i++) { + if (args[i] === "--cancellationPipeName") { + cancellationPipeName = args[i + 1]; + break; + } + } + if (!cancellationPipeName) { + return typescript_exports.server.nullCancellationToken; + } + if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === "*") { + const namePrefix = cancellationPipeName.slice(0, -1); + if (namePrefix.length === 0 || namePrefix.includes("*")) { + throw new Error("Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'."); + } + let perRequestPipeName; + let currentRequestId; + return { + isCancellationRequested: () => perRequestPipeName !== void 0 && pipeExists(perRequestPipeName), + setRequest(requestId) { + currentRequestId = requestId; + perRequestPipeName = namePrefix + requestId; + }, + resetRequest(requestId) { + if (currentRequestId !== requestId) { + throw new Error(`Mismatched request id, expected ${currentRequestId}, actual ${requestId}`); + } + perRequestPipeName = void 0; + } + }; + } else { + return { + isCancellationRequested: () => pipeExists(cancellationPipeName), + setRequest: (_requestId) => void 0, + resetRequest: (_requestId) => void 0 + }; + } +} + +// src/tsserver/server.ts +function findArgumentStringArray(argName) { + const arg = typescript_exports.server.findArgument(argName); + if (arg === void 0) { + return typescript_exports.emptyArray; + } + return arg.split(",").filter((name) => name !== ""); +} +function start({ args, logger, cancellationToken, serverMode, unknownServerMode, startSession: startServer }, platform) { + logger.info(`Starting TS Server`); + logger.info(`Version: ${typescript_exports.version}`); + logger.info(`Arguments: ${args.join(" ")}`); + logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${typescript_exports.sys.useCaseSensitiveFileNames}`); + logger.info(`ServerMode: ${serverMode} hasUnknownServerMode: ${unknownServerMode}`); + typescript_exports.setStackTraceLimit(); + if (typescript_exports.Debug.isDebugging) { + typescript_exports.Debug.enableDebugInfo(); + } + if (typescript_exports.sys.tryEnableSourceMapsForHost && /^development$/i.test(typescript_exports.sys.getEnvironmentVariable("NODE_ENV"))) { + typescript_exports.sys.tryEnableSourceMapsForHost(); + } + console.log = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), typescript_exports.server.Msg.Info); + console.warn = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), typescript_exports.server.Msg.Err); + console.error = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), typescript_exports.server.Msg.Err); + startServer( + { + globalPlugins: findArgumentStringArray("--globalPlugins"), + pluginProbeLocations: findArgumentStringArray("--pluginProbeLocations"), + allowLocalPluginLoads: typescript_exports.server.hasArgument("--allowLocalPluginLoads"), + useSingleInferredProject: typescript_exports.server.hasArgument("--useSingleInferredProject"), + useInferredProjectPerProjectRoot: typescript_exports.server.hasArgument("--useInferredProjectPerProjectRoot"), + suppressDiagnosticEvents: typescript_exports.server.hasArgument("--suppressDiagnosticEvents"), + noGetErrOnBackgroundUpdate: typescript_exports.server.hasArgument("--noGetErrOnBackgroundUpdate"), + canUseWatchEvents: typescript_exports.server.hasArgument("--canUseWatchEvents"), + serverMode + }, + logger, + cancellationToken + ); +} +typescript_exports.setStackTraceLimit(); +start(initializeNodeSystem(), import_os2.default.platform()); +//# sourceMappingURL=_tsserver.js.map diff --git a/node_modules/typescript/lib/_typingsInstaller.js b/node_modules/typescript/lib/_typingsInstaller.js new file mode 100644 index 00000000..75f0e697 --- /dev/null +++ b/node_modules/typescript/lib/_typingsInstaller.js @@ -0,0 +1,222 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// src/typingsInstaller/nodeTypingsInstaller.ts +var import_child_process = require("child_process"); +var fs = __toESM(require("fs")); +var path = __toESM(require("path")); + +// src/typescript/typescript.ts +var typescript_exports = {}; +__reExport(typescript_exports, require("./typescript.js")); + +// src/typingsInstaller/nodeTypingsInstaller.ts +var FileLog = class { + constructor(logFile) { + this.logFile = logFile; + this.isEnabled = () => { + return typeof this.logFile === "string"; + }; + this.writeLine = (text) => { + if (typeof this.logFile !== "string") return; + try { + fs.appendFileSync(this.logFile, `[${typescript_exports.server.nowString()}] ${text}${typescript_exports.sys.newLine}`); + } catch { + this.logFile = void 0; + } + }; + } +}; +function getDefaultNPMLocation(processName, validateDefaultNpmLocation2, host) { + if (path.basename(processName).indexOf("node") === 0) { + const npmPath = path.join(path.dirname(process.argv[0]), "npm"); + if (!validateDefaultNpmLocation2) { + return npmPath; + } + if (host.fileExists(npmPath)) { + return `"${npmPath}"`; + } + } + return "npm"; +} +function loadTypesRegistryFile(typesRegistryFilePath, host, log2) { + if (!host.fileExists(typesRegistryFilePath)) { + if (log2.isEnabled()) { + log2.writeLine(`Types registry file '${typesRegistryFilePath}' does not exist`); + } + return /* @__PURE__ */ new Map(); + } + try { + const content = JSON.parse(host.readFile(typesRegistryFilePath)); + return new Map(Object.entries(content.entries)); + } catch (e) { + if (log2.isEnabled()) { + log2.writeLine(`Error when loading types registry file '${typesRegistryFilePath}': ${e.message}, ${e.stack}`); + } + return /* @__PURE__ */ new Map(); + } +} +var typesRegistryPackageName = "types-registry"; +function getTypesRegistryFileLocation(globalTypingsCacheLocation2) { + return (0, typescript_exports.combinePaths)((0, typescript_exports.normalizeSlashes)(globalTypingsCacheLocation2), `node_modules/${typesRegistryPackageName}/index.json`); +} +var NodeTypingsInstaller = class extends typescript_exports.server.typingsInstaller.TypingsInstaller { + constructor(globalTypingsCacheLocation2, typingSafeListLocation2, typesMapLocation2, npmLocation2, validateDefaultNpmLocation2, throttleLimit, log2) { + const libDirectory = (0, typescript_exports.getDirectoryPath)((0, typescript_exports.normalizePath)(typescript_exports.sys.getExecutingFilePath())); + super( + typescript_exports.sys, + globalTypingsCacheLocation2, + typingSafeListLocation2 ? (0, typescript_exports.toPath)(typingSafeListLocation2, "", (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)) : (0, typescript_exports.toPath)("typingSafeList.json", libDirectory, (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)), + typesMapLocation2 ? (0, typescript_exports.toPath)(typesMapLocation2, "", (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)) : (0, typescript_exports.toPath)("typesMap.json", libDirectory, (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)), + throttleLimit, + log2 + ); + this.npmPath = npmLocation2 !== void 0 ? npmLocation2 : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation2, this.installTypingHost); + if (this.npmPath.includes(" ") && this.npmPath[0] !== `"`) { + this.npmPath = `"${this.npmPath}"`; + } + if (this.log.isEnabled()) { + this.log.writeLine(`Process id: ${process.pid}`); + this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${typescript_exports.server.Arguments.NpmLocation}' ${npmLocation2 === void 0 ? "not " : ""} provided)`); + this.log.writeLine(`validateDefaultNpmLocation: ${validateDefaultNpmLocation2}`); + } + this.ensurePackageDirectoryExists(globalTypingsCacheLocation2); + try { + if (this.log.isEnabled()) { + this.log.writeLine(`Updating ${typesRegistryPackageName} npm package...`); + } + this.execSyncAndLog(`${this.npmPath} install --ignore-scripts ${typesRegistryPackageName}@${this.latestDistTag}`, { cwd: globalTypingsCacheLocation2 }); + if (this.log.isEnabled()) { + this.log.writeLine(`Updated ${typesRegistryPackageName} npm package`); + } + } catch (e) { + if (this.log.isEnabled()) { + this.log.writeLine(`Error updating ${typesRegistryPackageName} package: ${e.message}`); + } + this.delayedInitializationError = { + kind: "event::initializationFailed", + message: e.message, + stack: e.stack + }; + } + this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation2), this.installTypingHost, this.log); + } + handleRequest(req) { + if (this.delayedInitializationError) { + this.sendResponse(this.delayedInitializationError); + this.delayedInitializationError = void 0; + } + super.handleRequest(req); + } + sendResponse(response) { + if (this.log.isEnabled()) { + this.log.writeLine(`Sending response:${typescript_exports.server.stringifyIndented(response)}`); + } + process.send(response); + if (this.log.isEnabled()) { + this.log.writeLine(`Response has been sent.`); + } + } + installWorker(requestId, packageNames, cwd, onRequestCompleted) { + if (this.log.isEnabled()) { + this.log.writeLine(`#${requestId} with cwd: ${cwd} arguments: ${JSON.stringify(packageNames)}`); + } + const start = Date.now(); + const hasError = typescript_exports.server.typingsInstaller.installNpmPackages(this.npmPath, typescript_exports.version, packageNames, (command) => this.execSyncAndLog(command, { cwd })); + if (this.log.isEnabled()) { + this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms`); + } + onRequestCompleted(!hasError); + } + /** Returns 'true' in case of error. */ + execSyncAndLog(command, options) { + if (this.log.isEnabled()) { + this.log.writeLine(`Exec: ${command}`); + } + try { + const stdout = (0, import_child_process.execSync)(command, { ...options, encoding: "utf-8" }); + if (this.log.isEnabled()) { + this.log.writeLine(` Succeeded. stdout:${indent(typescript_exports.sys.newLine, stdout)}`); + } + return false; + } catch (error) { + const { stdout, stderr } = error; + this.log.writeLine(` Failed. stdout:${indent(typescript_exports.sys.newLine, stdout)}${typescript_exports.sys.newLine} stderr:${indent(typescript_exports.sys.newLine, stderr)}`); + return true; + } + } +}; +var logFilePath = typescript_exports.server.findArgument(typescript_exports.server.Arguments.LogFile); +var globalTypingsCacheLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.GlobalCacheLocation); +var typingSafeListLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypingSafeListLocation); +var typesMapLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypesMapLocation); +var npmLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.NpmLocation); +var validateDefaultNpmLocation = typescript_exports.server.hasArgument(typescript_exports.server.Arguments.ValidateDefaultNpmLocation); +var log = new FileLog(logFilePath); +if (log.isEnabled()) { + process.on("uncaughtException", (e) => { + log.writeLine(`Unhandled exception: ${e} at ${e.stack}`); + }); +} +process.on("disconnect", () => { + if (log.isEnabled()) { + log.writeLine(`Parent process has exited, shutting down...`); + } + process.exit(0); +}); +var installer; +process.on("message", (req) => { + installer ?? (installer = new NodeTypingsInstaller( + globalTypingsCacheLocation, + typingSafeListLocation, + typesMapLocation, + npmLocation, + validateDefaultNpmLocation, + /*throttleLimit*/ + 5, + log + )); + installer.handleRequest(req); +}); +function indent(newline, str) { + return str && str.length ? `${newline} ` + str.replace(/\r?\n/, `${newline} `) : ""; +} +//# sourceMappingURL=_typingsInstaller.js.map diff --git a/node_modules/typescript/lib/cs/diagnosticMessages.generated.json b/node_modules/typescript/lib/cs/diagnosticMessages.generated.json new file mode 100644 index 00000000..8d72fcca --- /dev/null +++ b/node_modules/typescript/lib/cs/diagnosticMessages.generated.json @@ -0,0 +1,2105 @@ +{ + "ALL_COMPILER_OPTIONS_6917": "VŠECHNY MOŽNOSTI KOMPILÁTORU", + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Modifikátor {0} nejde použít s deklarací import.", + "A_0_parameter_must_be_the_first_parameter_2680": "Parametr {0} musí být prvním parametrem.", + "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039": "Značka „@template“ jazyka JSDoc nemůže následovat po značce „@typedef“, „@callback“ nebo „@overload“.", + "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033": "Komentář JSDoc @typedef nemůže obsahovat více než jednu značku @type.", + "A_bigint_literal_cannot_be_used_as_a_property_name_1539": "Literál „bigint“ nelze použít jako název vlastnosti.", + "A_bigint_literal_cannot_use_exponential_notation_1352": "Literál typu bigint nemůže používat exponenciální notaci.", + "A_bigint_literal_must_be_an_integer_1353": "Literál typu bigint musí být celé číslo.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Parametr vzoru vazby nemůže být u podpisu implementace nepovinný.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Příkaz break se dá použít jenom uvnitř nadřazené iterace nebo příkazu switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Příkaz break může skočit jenom na popisek nadřazeného příkazu.", + "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522": "Třída znaků nesmí obsahovat vyhrazené dvojité interpunkční znaménko. Nechtěli jste ho uvést zpětným lomítkem?", + "A_character_class_range_must_not_be_bounded_by_another_character_class_1516": "Rozsah třídy znaků nesmí být ohraničen jinou třídou znaků.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Třída může implementovat jenom identifikátor nebo kvalifikovaný název s volitelnými argumenty typu.", + "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422": "Třída může implementovat jen typ objektu nebo průsečík typů objektů se staticky známými členy.", + "A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values_2863": "Třída nemůže rozšiřovat primitivní typ, jako je například „{0}“. Třídy můžou rozšiřovat pouze konstruovatelné hodnoty.", + "A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types_2864": "Třída nemůže implementovat primitivní typ, jako je například „{0}“. Může implementovat pouze jiné typy pojmenovaných objektů.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Deklarace třídy bez modifikátoru default musí mít název.", + "A_class_member_cannot_have_the_0_keyword_1248": "Člen třídy nemůže mít klíčové slovo {0}.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Výraz s čárkou není v názvu počítané vlastnosti povolený.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Název počítané vlastnosti nemůže odkazovat na parametr typu z jeho nadřazeného typu.", + "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166": "Název počítané vlastnosti v deklaraci vlastnosti třídy musí mít jednoduchý typ literálu nebo typ unique symbol.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Název počítané vlastnosti v přetížené metodě musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Název počítané vlastnosti v literálu typu musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Název počítané vlastnosti v ambientním kontextu musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Název počítané vlastnosti v rozhraní musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Název počítané vlastnosti musí být typu string, number, symbol nebo any.", + "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355": "Kontrolní výrazy const se dají použít jen pro odkazy na členy výčtu, řetězec, číslo, logickou hodnotu, pole nebo literály objektů.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Ke členu konstantního výčtu se dá získat přístup jenom pomocí řetězcového literálu.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254": "Inicializátor const v ambientním kontextu musí být řetězec, číselný literál nebo odkaz na výčet literálů.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Konstruktor nemůže obsahovat volání super, pokud jeho třída rozšiřuje null.", + "A_constructor_cannot_have_a_this_parameter_2681": "Konstruktor nemůže mít parametr this.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Příkaz continue se dá použít jenom uvnitř příkazu nadřazené iterace.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Příkaz continue může přejít jenom na popisek příkazu nadřazené iterace.", + "A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_f_2846": "Soubor deklarace nelze importovat bez hodnoty „import type“. Nechtěli jste místo toho importovat soubor implementace „{0}“?", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Modifikátor declare se nedá použít v kontextu, který už je ambientní.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekorátor může dekorovat jenom implementaci metody, ne přetížení.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Klauzule default nemůže být v příkazu switch víc než jednou.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "V modulu ve stylu ECMAScriptu se dá použít jenom výchozí export.", + "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258": "Výchozí export musí být na nejvyšší úrovni deklarace souboru nebo modulu.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Určitý kontrolní výraz přiřazení '!' není v tomto kontextu povolený.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Destrukturační deklarace musí obsahovat inicializátor.", + "A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_t_2712": "Volání dynamického importu v ES5 vyžaduje konstruktor „Promise“. Ujistěte se, že máte deklaraci konstruktoru „Promise“, nebo do možnosti „--lib“ přidejte „ES2015“.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Volání dynamického importu vrací hodnotu ‚Promise‘. Ujistěte se, že pro ni máte deklaraci, nebo do možnosti ‚--lib‘ přidejte ‚ES2015‘.", + "A_file_cannot_have_a_reference_to_itself_1006": "Soubor nemůže odkazovat sám na sebe.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Funkce, která vrací hodnotu never, nemůže mít dosažitelný koncový bod.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Funkce volaná klíčovým slovem new nemůže mít typ this, který je void.", + "A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value_2355": "Funkce, jejíž deklarovaný typ není „undefined“, „void“ ani „any“, musí vracet hodnotu.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Generátor nemůže mít anotaci typu void.", + "A_get_accessor_cannot_have_parameters_1054": "Přístupový objekt get nemůže obsahovat parametry.", + "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808": "Přístupový objekt get musí být alespoň tak přístupný jako metoda setter.", + "A_get_accessor_must_return_a_value_2378": "Přístupový objekt get musí vracet hodnotu.", + "A_label_is_not_allowed_here_1344": "Popisek se tady nepovoluje.", + "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Element popsané řazené kolekce členů se deklaroval jako nepovinný pomocí otazníku za názvem a před dvojtečkou, nikoli za typem.", + "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Element popsané řazené kolekce členů se deklaroval jako zbytek s třemi tečkami (...) před názvem, nikoli před typem.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Mapovaný typ nemůže deklarovat vlastnosti nebo metody.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Inicializátor členu v deklaraci výčtu nemůže odkazovat na členy deklarované až po výčtu, a to ani členy definované v jiných výčtech.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Třída mixin musí mít konstruktor s jediným parametrem rest typu any[].", + "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Třída mixin, která rozšiřuje proměnnou typu obsahující signaturu abstraktního konstruktu, musí být také deklarovaná jako abstract.", + "A_module_cannot_have_multiple_default_exports_2528": "Modul nemůže mít víc výchozích exportů.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklarace oboru názvů nemůže být v jiném souboru než třída nebo funkce, se kterou se slučuje.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklarace oboru názvů nemůže být umístěná před třídou nebo funkcí, se kterou se slučuje.", + "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235": "Deklarace oboru názvů je povolená pouze na nejvyšší úrovni oboru názvů nebo v modulu.", + "A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_key_1540": "Deklarace namespace by se neměla deklarovat pomocí klíčového slova module. Místo toho prosím použijte klíčové slovo namespace.", + "A_non_dry_build_would_build_project_0_6357": "Build bez příznaku -dry by vytvořil projekt {0}.", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Build bez příznaku -dry by odstranil následující soubory: {0}", + "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374": "Build bez příznaku -dry by aktualizoval časová razítka pro výstup projektu {0}.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Inicializátor parametru je povolený jenom v implementaci funkce nebo konstruktoru.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Vlastnost parametru se nedá deklarovat pomocí parametru rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Vlastnost parametru je povolená jenom v implementaci konstruktoru.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Vlastnost parametru se nedá deklarovat pomocí vzoru vazby.", + "A_promise_must_have_a_then_method_1059": "Příslib musí mít metodu then.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Vlastnost třídy, jejíž typ je unique symbol, musí být static a readonly.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Vlastnost rozhraní nebo literálu typu, jehož typ je unique symbol, musí být readonly.", + "A_required_element_cannot_follow_an_optional_element_1257": "Povinný element nemůže následovat po nepovinném elementu.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Povinný parametr nemůže následovat po nepovinném parametru.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Element rest nemůže obsahovat vzor vazby.", + "A_rest_element_cannot_follow_another_rest_element_1265": "Element rest nemůže následovat za jiným elementem rest.", + "A_rest_element_cannot_have_a_property_name_2566": "Element rest nemůže mít název vlastnosti.", + "A_rest_element_cannot_have_an_initializer_1186": "Element rest nemůže obsahovat inicializátor.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Element rest musí být ve vzoru destrukturalizace poslední.", + "A_rest_element_type_must_be_an_array_type_2574": "Typ elementu rest musí být typu pole.", + "A_rest_parameter_cannot_be_optional_1047": "Parametr rest nemůže být nepovinný.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Parametr rest nemůže obsahovat inicializátor.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Parametr rest musí být posledním v seznamu parametrů.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Parametr rest musí být typu pole.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Parametr rest nebo vzor vazby nesmí mít na konci čárku.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Příkaz return se dá použít jenom v těle funkce.", + "A_return_statement_cannot_be_used_inside_a_class_static_block_18041": "Příkaz return nejde použít uvnitř statického bloku třídy.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Řada záznamů, které mění mapování importů do umístění vyhledávání relativních vůči baseUrl.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Přístupový objekt set nemůže obsahovat anotaci návratového typu.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Přístupový objekt set nemůže obsahovat nepovinný parametr.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Přístupový objekt get nemůže obsahovat parametr rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Přístupový objekt set musí obsahovat přesně jeden parametr.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Parametr přístupového objektu set nemůže obsahovat inicializátor.", + "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556": "Argument rozprostření musí mít buď typ řazené kolekce členů, nebo musí být předán do parametru rest.", + "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401": "Volání super musí být příkaz na kořenové úrovni v konstruktoru odvozené třídy, který obsahuje inicializované vlastnosti, vlastnosti parametrů nebo privátní identifikátory.", + "A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_2376": "Volání super musí být prvním příkazem v konstruktoru, který odkazuje na super nebo toto, když odvozená třída obsahuje inicializované vlastnosti, vlastnosti parametrů nebo soukromé identifikátory.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Ochrana typu this není kompatibilní s ochranou typu založeného na parametru.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Typ this je k dispozici jenom v nestatických členech třídy nebo rozhraní.", + "A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimM_1287": "Modifikátor „export“ nejvyšší úrovně nelze použít pro deklarace hodnot v modulu CommonJS, když je povolený modifikátor „verbatimModuleSyntax“.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Soubor tsconfig.json je už v {0} definovaný.", + "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Člen řazené kolekce členů nemůže být volitelný a zbytek.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Typ řazené kolekce členů není možné indexovat zápornou hodnotou.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Výraz potvrzení typu se na levé straně výrazu umocnění nepovoluje. Zvažte možnost uzavření výrazu do závorek.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Vlastnost literálu typu nemůže mít inicializátor.", + "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Import, při kterém se importují jen typy, může určovat výchozí import nebo pojmenované vazby, ale ne obojí.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Predikát typu nemůže odkazovat na parametr rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Predikát typu nemůže odkazovat na element {0} ve vzoru vazby.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Predikát typu je povolený jenom na pozici návratového typu funkcí a metod.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Typ predikátu typu musí být přiřaditelný k typu jeho parametru.", + "A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_w_1272": "Typ odkazovaný v dekorovaném podpisu musí být importován pomocí import type nebo importu oboru názvů, pokud jsou povoleny elementy isolatedModules a emitDecoratorMetadata.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Proměnná, jejíž typ je unique symbol, musí být const.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Výraz yield je povolený jenom v těle generátoru.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "K abstraktní metodě {0} ve třídě {1} nejde získat přístup prostřednictvím výrazu super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Abstraktní metody se můžou vyskytovat jenom v abstraktní třídě.", + "Abstract_properties_can_only_appear_within_an_abstract_class_1253": "Abstraktní vlastnosti se můžou vyskytovat jenom v abstraktní třídě.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "K abstraktní vlastnosti {0} ve třídě {1} nelze získat přístup v konstruktoru.", + "Accessibility_modifier_already_seen_1028": "Modifikátor dostupnosti se už jednou vyskytl.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Přístupové objekty jsou dostupné, jenom když je cílem ECMAScript 5 a vyšší verze.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Přistupující objekty musí být abstraktní nebo neabstraktní.", + "Add_0_to_unresolved_variable_90008": "Přidat {0}. k nerozpoznané proměnné", + "Add_a_return_statement_95111": "Přidat příkaz return", + "Add_a_return_type_to_the_function_declaration_9031": "Přidejte návratový typ do deklarace funkce.", + "Add_a_return_type_to_the_function_expression_9030": "Přidejte návratový typ do výrazu funkce.", + "Add_a_return_type_to_the_get_accessor_declaration_9032": "Přidejte návratový typ do deklarace přistupujícího objektu get.", + "Add_a_return_type_to_the_method_9034": "Přidejte do metody návratový typ.", + "Add_a_type_annotation_to_the_parameter_0_9028": "Přidejte anotaci typu k parametru „{0}“.", + "Add_a_type_annotation_to_the_property_0_9029": "Přidejte anotaci typu k vlastnosti „{0}“.", + "Add_a_type_annotation_to_the_variable_0_9027": "Přidejte anotaci typu k proměnné „{0}“.", + "Add_a_type_to_parameter_of_the_set_accessor_declaration_9033": "Přidejte typ k parametru deklarace přistupujícího objektu set.", + "Add_all_missing_async_modifiers_95041": "Přidat všechny chybějící modifikátory async", + "Add_all_missing_attributes_95168": "Přidat všechny chybějící atributy", + "Add_all_missing_call_parentheses_95068": "Přidat všechny chybějící závorky volání", + "Add_all_missing_function_declarations_95157": "Přidat všechny chybějící deklarace funkcí", + "Add_all_missing_imports_95064": "Přidat všechny chybějící importy", + "Add_all_missing_members_95022": "Přidat všechny chybějící členy", + "Add_all_missing_override_modifiers_95162": "Přidat všechny chybějící modifikátory override", + "Add_all_missing_parameters_95190": "Přidejte všechny chybějící parametry.", + "Add_all_missing_properties_95166": "Přidat všechny chybějící importy", + "Add_all_missing_return_statement_95114": "Přidat všechny chybějící příkazy return", + "Add_all_missing_super_calls_95039": "Přidat všechna chybějící volání pomocí super", + "Add_all_missing_type_annotations_90067": "Přidejte všechny chybějící anotace typů.", + "Add_all_optional_parameters_95193": "Přidejte všechny volitelné parametry.", + "Add_annotation_of_type_0_90062": "Přidejte anotaci typu „{0}“.", + "Add_async_modifier_to_containing_function_90029": "Přidat modifikátor async do obsahující funkce", + "Add_await_95083": "Přidat await", + "Add_await_to_initializer_for_0_95084": "Přidat await do inicializátoru pro {0}", + "Add_await_to_initializers_95089": "Přidat await do inicializátorů", + "Add_braces_to_arrow_function_95059": "Přidat složené závorky k funkci šipky", + "Add_const_to_all_unresolved_variables_95082": "Přidat const ke všem nerozpoznaným proměnným", + "Add_const_to_unresolved_variable_95081": "Přidat const k nerozpoznané proměnné", + "Add_definite_assignment_assertion_to_property_0_95020": "Přidat kontrolní výraz jednoznačného přiřazení k vlastnosti {0}", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Přidat kontrolní výrazy jednoznačného přiřazení do všech neinicializovaných vlastností", + "Add_export_to_make_this_file_into_a_module_95097": "Přidat export {}, aby se tento soubor převedl na modul", + "Add_extends_constraint_2211": "Přidejte omezení extends.", + "Add_extends_constraint_to_all_type_parameters_2212": "Přidat omezení extends ke všem parametrům typu", + "Add_import_from_0_90057": "Přidat import z {0}", + "Add_index_signature_for_property_0_90017": "Přidat signaturu indexu pro vlastnost {0}", + "Add_initializer_to_property_0_95019": "Přidat inicializační výraz k vlastnosti {0}", + "Add_initializers_to_all_uninitialized_properties_95027": "Přidat inicializátory do všech neinicializovaných vlastností", + "Add_missing_attributes_95167": "Přidat chybějící atributy", + "Add_missing_call_parentheses_95067": "Přidat chybějící závorky volání", + "Add_missing_comma_for_object_member_completion_0_95187": "Přidejte chybějící čárku pro dokončování členů objektu „{0}“.", + "Add_missing_enum_member_0_95063": "Přidat chybějící člen výčtu {0}", + "Add_missing_function_declaration_0_95156": "Přidat chybějící deklaraci funkce {0}", + "Add_missing_new_operator_to_all_calls_95072": "Přidat chybějící operátor new ke všem voláním", + "Add_missing_new_operator_to_call_95071": "Přidat chybějící operátor new k volání", + "Add_missing_parameter_to_0_95188": "Přidejte chybějící parametr do „{0}“.", + "Add_missing_parameters_to_0_95189": "Přidejte chybějící parametry do „{0}“.", + "Add_missing_properties_95165": "Přidat chybějící vlastnosti", + "Add_missing_super_call_90001": "Přidat chybějící volání metody super()", + "Add_missing_typeof_95052": "Přidat chybějící typeof", + "Add_names_to_all_parameters_without_names_95073": "Přidat názvy do všech parametrů bez názvů", + "Add_optional_parameter_to_0_95191": "Přidejte volitelný parametr do „{0}“", + "Add_optional_parameters_to_0_95192": "Přidat volitelné parametry do {0}", + "Add_or_remove_braces_in_an_arrow_function_95058": "Přidat nebo odebrat složené závorky ve funkci šipky", + "Add_override_modifier_95160": "Přidat modifikátor override", + "Add_parameter_name_90034": "Přidat název parametru", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Přidat kvalifikátor do všech nerozpoznaných proměnných odpovídajících názvu členu", + "Add_resolution_mode_import_attribute_95196": "Přidat atribut importu resolution-mode", + "Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it_95197": "Přidat atribut importu resolution-mode do všech importů, při kterých se importuje pouze typ, které ho potřebují", + "Add_return_type_0_90063": "Přidejte návratový typ „{0}“", + "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035": "Chcete-li typ nastavit jako explicitní, přidejte do tohoto výrazu operátor „satisfies“ a kontrolní výraz typu („satisfies T as T“).", + "Add_satisfies_and_an_inline_type_assertion_with_0_90068": "Přidejte operátor „satisfies“ a kontrolní výraz vloženého typu s „{0}“.", + "Add_to_all_uncalled_decorators_95044": "Přidat () do všech nevolaných dekorátorů", + "Add_ts_ignore_to_all_error_messages_95042": "Přidat @ts-ignore do všech chybových zpráv", + "Add_undefined_to_a_type_when_accessed_using_an_index_6674": "Pokud k přístupu používáte index, přidejte k typu řetězec undefined.", + "Add_undefined_to_optional_property_type_95169": "Přidat hodnotu undefined do volitelného typu vlastnosti", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Přidat nedefinovaný typ do všech neinicializovaných vlastností", + "Add_undefined_type_to_property_0_95018": "Přidat typ undefined k vlastnosti {0}", + "Add_unknown_conversion_for_non_overlapping_types_95069": "Přidat převod unknown pro typy, které se nepřekrývají", + "Add_unknown_to_all_conversions_of_non_overlapping_types_95070": "Přidat unknown do všech převodů pro typy, které se nepřekrývají", + "Add_void_to_Promise_resolved_without_a_value_95143": "Přidat void k objektu Promise vyřešenému bez hodnoty", + "Add_void_to_all_Promises_resolved_without_a_value_95144": "Přidat void ke všem objektům Promise vyřešeným bez hodnoty", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Přidání souboru tsconfig.json vám pomůže uspořádat projekty, které obsahují jak soubory TypeScript, tak soubory JavaScript. Další informace najdete na adrese https://aka.ms/tsconfig.", + "All_declarations_of_0_must_have_identical_constraints_2838": "Všechny deklarace {0} musí mít identická omezení.", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Všechny deklarace {0} musí mít stejné modifikátory.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Všechny deklarace {0} musí mít stejné parametry typu.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Všechny deklarace abstraktní metody musí jít po sobě.", + "All_destructured_elements_are_unused_6198": "Žádný z destrukturovaných elementů se nepoužívá.", + "All_imports_in_import_declaration_are_unused_6192": "Žádné importy z deklarace importu se nepoužívají.", + "All_type_parameters_are_unused_6205": "Všechny parametry typů jsou nevyužité.", + "All_variables_are_unused_6199": "Žádná z proměnných se nepoužívá.", + "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600": "Povolte, aby se soubory JavaScriptu staly součástí programu. K získání informací o chybách v těchto souborech použít možnost checkJS.", + "Allow_accessing_UMD_globals_from_modules_6602": "Povolit přístup ke globálním proměnným UMD z modulů", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Povolte výchozí importy z modulů bez výchozího exportu. Nebude to mít vliv na generování kódu, jenom na kontrolu typů.", + "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601": "Pokud modul nemá výchozí export, povolte import X z Y.", + "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639": "Povolte import pomocných funkcí z knihovny tslib jednou za celý projekt místo jejich zahrnutí do každého souboru.", + "Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noE_6407": "Povolte, aby importy zahrnovaly přípony souborů TypeScriptu. Vyžaduje nastavení možnosti „--moduleResolution bundler“ a buď „--noEmit“, nebo „--emitDeclarationOnly“.", + "Allow_javascript_files_to_be_compiled_6102": "Povolí kompilaci souborů javascript.", + "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691": "Při řešení modulů povolit, aby se s více složkami zacházelo jako s jednou.", + "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261": "Název souboru {0}, který se už zahrnul, se od názvu souboru {1} liší jen ve velkých a malých písmenech.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Deklarace ambientního modulu nemůže uvádět relativní název modulu.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Ambientní moduly se nedají zanořovat do jiných modulů nebo oborů názvů.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Modul AMD nemůže obsahovat víc přiřazení názvů.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Abstraktní přístupový objekt nemůže mít implementaci.", + "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010": "Modifikátor přístupnosti se nedá použít spolu s privátním identifikátorem.", + "An_accessor_cannot_have_type_parameters_1094": "Přístupový objekt nemůže obsahovat parametry typu.", + "An_accessor_property_cannot_be_declared_optional_1276": "Vlastnost accessor nejde deklarovat jako volitelnou.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Deklarace ambientního modulu je povolená jenom na nejvyšší úrovni v souboru.", + "An_argument_for_0_was_not_provided_6210": "Neposkytl se argument pro {0}.", + "An_argument_matching_this_binding_pattern_was_not_provided_6211": "Neposkytl se argument, který by odpovídal tomuto vzoru vazby.", + "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356": "Aritmetický operand musí být typu any, number, bigint nebo typu výčtu.", + "An_arrow_function_cannot_have_a_this_parameter_2730": "Funkce šipky nemůže mít parametr this.", + "An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_2705": "Asynchronní funkce nebo metoda v ES5 vyžaduje konstruktor „Promise“. Ujistěte se, že máte deklaraci konstruktoru „Promise“, nebo do možnosti „--lib“ přidejte „ES2015“.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Asynchronní funkce nebo metoda musí vracet hodnotu ‚Promise‘. Přesvědčte se, že pro ni máte deklaraci, nebo zahrňte ‚ES2015‘ do možnosti ‚--lib‘.", + "An_async_iterator_must_have_a_next_method_2519": "Asynchronní iterátor musí mít metodu next().", + "An_element_access_expression_should_take_an_argument_1011": "Výraz přístupu k elementu by měl přijímat argument.", + "An_enum_member_cannot_be_named_with_a_private_identifier_18024": "Člen výčtu není možné pojmenovat privátním identifikátorem.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Člen výčtu nemůže mít číselný název.", + "An_enum_member_name_must_be_followed_by_a_or_1357": "Za názvem členu výčtu musí následovat znak čárky (,), rovnítka (=) nebo pravé složené závorky (}).", + "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928": "Rozšířená verze těchto informací, zobrazující všechny možné možnosti kompilátoru", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Přiřazení exportu se nedá použít v modulu s jinými exportovanými elementy.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Přiřazení exportu se nedá používat v oboru názvů.", + "An_export_assignment_cannot_have_modifiers_1120": "Přiřazení exportu nemůže mít modifikátory.", + "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231": "Přiřazení exportu musí být na nejvyšší úrovni deklarace souboru nebo modulu.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474": "Deklarace exportu se dá použít pouze na nejvyšší úrovni modulu.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233": "Deklarace exportu se dá použít pouze na nejvyšší úrovni oboru názvů nebo modulu.", + "An_export_declaration_cannot_have_modifiers_1193": "Deklarace exportu nemůže mít modifikátory.", + "An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolve_1283": "Když je povolená možnost verbatimModuleSyntax, musí deklarace „export =“ odkazovat na skutečnou hodnotu, ale „{0}“ se překládá na deklaraci „pouze typ“.", + "An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers__1282": "Deklarace „export =“ musí odkazovat na hodnotu, když je povolená možnost „verbatimModuleSyntax“, ale „{0}“ odkazuje jenom na typ.", + "An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_1285": "Když je povolená možnost verbatimModuleSyntax, musí „export default“ odkazovat na skutečnou hodnotu, ale „{0}“ se překládá na deklaraci „pouze typ“.", + "An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_1284": "Pokud je povolená možnost „verbatimModuleSyntax“, musí „export default“ odkazovat na hodnotu, ale „{0}“ odkazuje jenom na typ.", + "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345": "Není možné testovat pravdivost výrazu typu void.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Rozšířená řídicí hodnota Unicode musí být mezi 0x0 a 0x10FFFF (včetně).", + "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351": "Identifikátor nebo klíčové slovo nemůže následovat hned po číselném literálu.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Implementace se nedá deklarovat v ambientních kontextech.", + "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Alias importu se nemůže odkazovat na deklaraci, která se exportovala pomocí export type.", + "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Alias importu se nemůže odkazovat na deklaraci, která se importovala pomocí import type.", + "An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabl_1288": "Pokud je povolená možnost „verbatimModuleSyntax“, alias importu nelze přeložit na deklaraci typu nebo deklaraci „pouze typ“.", + "An_import_alias_cannot_use_import_type_1392": "Alias importu nemůže používat import type.", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473": "Deklarace importu se dá použít pouze na nejvyšší úrovni modulu.", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232": "Deklarace importu se dá použít pouze na nejvyšší úrovni oboru názvů nebo modulu.", + "An_import_declaration_cannot_have_modifiers_1191": "Deklarace importu nemůže mít modifikátory.", + "An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled_5097": "Když je povolená možnost „allowImportingTsExtensions“, může cesta importu končit pouze příponou „{0}“.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Signatura indexu indexu nemůže obsahovat parametr rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Signatura indexu nemůže mít na konci čárku.", + "An_index_signature_must_have_a_type_annotation_1021": "Signatura indexu musí mít anotaci typu.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Signatura indexu musí mít právě jeden parametr.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "V parametru signatury indexu nemůže být otazník.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "V parametru signatury indexu nemůže být modifikátor přístupnosti.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "V parametru signatury indexu nemůže být inicializátor.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "V parametru signatury indexu nemůže být anotace typu.", + "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Typ parametru signatury indexu nemůže být typ literálu nebo obecný typ. Místo toho zvažte použití namapovaného typu objektu.", + "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Typ parametru signatury indexu musí být řetězec, číslo, symbol nebo typ literálu šablony.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Po výrazu vytvoření instance nemůže následovat přístup k vlastnosti.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Rozhraní může rozšířit jenom identifikátor nebo kvalifikovaný název s volitelnými argumenty typu.", + "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Rozhraní může rozšiřovat jen typ objektu nebo průsečík typů objektů se staticky známými členy.", + "An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types_2840": "Rozhraní nemůže rozšiřovat primitivní typ, jako je například „{0}“. Může rozšiřovat pouze jiné typy pojmenovaných objektů.", + "An_interface_property_cannot_have_an_initializer_1246": "Vlastnost rozhraní nemůže mít inicializátor.", + "An_iterator_must_have_a_next_method_2489": "Iterátor musí mít metodu next().", + "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Při použití direktivy pragma @jsx s fragmenty JSX se vyžaduje direktiva pragma @jsxFrag.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Literál objektu nemůže obsahovat několik přístupových objektů get/set se stejným názvem.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117": "Literál objektu nemůže mít víc vlastností se stejným názvem.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Literál objektu nemůže obsahovat vlastnost a přístupový objekt se stejným názvem.", + "An_object_member_cannot_be_declared_optional_1162": "Člen objektu nemůže být deklarovaný jako nepovinný.", + "An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_han_2861": "Metoda „[Symbol.hasInstance]“ objektu musí vracet logickou hodnotu, aby ji bylo možné použít na pravé straně výrazu „instanceof“.", + "An_optional_chain_cannot_contain_private_identifiers_18030": "Nepovinný řetěz nemůže obsahovat privátní identifikátory.", + "An_optional_element_cannot_follow_a_rest_element_1266": "Element optional nemůže následovat za elementem rest.", + "An_outer_value_of_this_is_shadowed_by_this_container_2738": "Tento kontejner zakrývá vnější hodnotu this.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Signatura přetížení nemůže být deklarovaný jako generátor.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Unární výraz s operátorem {0} se na levé straně výrazu umocnění nepovoluje. Zvažte možnost uzavření výrazu do závorek.", + "Annotate_everything_with_types_from_JSDoc_95043": "Vše s typy z JSDoc opatřit poznámkami", + "Annotate_types_of_properties_expando_function_in_a_namespace_90071": "Přidejte anotace typů funkce expando ve vlastnostech v oboru názvů.", + "Annotate_with_type_from_JSDoc_95009": "Přidat poznámku s typem z JSDoc", + "Another_export_default_is_here_2753": "Další výchozí hodnota exportu je tady.", + "Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_t_1528": "Jakákoli vlastnost Unicode, která by mohla odpovídat více než jednomu znaku, je k dispozici pouze v případě, že je nastaven příznak Unicode Sets (v).", + "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518": "Cokoli, co by mohlo odpovídat více než jednomu znaku, je v negované třídě znaků neplatné.", + "Are_you_missing_a_semicolon_2734": "Nechybí středník?", + "Argument_expression_expected_1135": "Očekává se výraz argumentu.", + "Argument_for_0_option_must_be_Colon_1_6046": "Argument možnosti {0} musí být {1}.", + "Argument_of_dynamic_import_cannot_be_spread_element_1325": "Argument dynamického importu nemůže být element rozestření.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Argument typu {0} nejde přiřadit k parametru typu {1}.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379": "Argument typu {0} se nedá přiřadit k parametru typu {1} s hodnotou exactOptionalPropertyTypes: true. Zvažte možnost přidat hodnotu undefined do typů vlastností cíle.", + "Arguments_for_the_rest_parameter_0_were_not_provided_6236": "Nezadaly se argumenty pro parametr rest {0}.", + "Array_element_destructuring_pattern_expected_1181": "Očekával se destrukturační vzor elementu pole.", + "Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations_9018": "Pole s elementy spread nelze odvodit pomocí možnosti --isolatedDeclarations.", + "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775": "Kontrolní výrazy vyžadují, aby se všechny názvy v cíli volání deklarovaly s explicitní anotací typu.", + "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776": "Kontrolní výrazy vyžadují, aby cíl volání byl identifikátor, nebo kvalifikovaný název.", + "Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations__9023": "Přiřazování vlastností funkcím bez jejich deklarování není u s možností --isolatedDeclarations podporováno. Přidejte explicitní deklaraci pro vlastnosti přiřazené k této funkci.", + "Asterisk_Slash_expected_1010": "Očekával se znak */.", + "At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9009": "Minimálně jeden přistupující objekt musí mít explicitní anotaci typu s možností --isolatedDeclarations.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Rozšíření pro globální rozsah může být jenom přímo vnořené v externích modulech nebo deklaracích ambientního modulu.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Rozšíření pro globální rozsah by měla mít modifikátor declare, pokud se neobjeví v kontextu, který je už ambientní.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Automatické zjišťování pro psaní je povolené v projektu {0}. Spouští se speciální průchod řešení pro modul {1} prostřednictvím umístění mezipaměti {2}.", + "BUILD_OPTIONS_6919": "MOŽNOSTI SESTAVENÍ", + "Backwards_Compatibility_6253": "Zpětná kompatibilita", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Výrazy základní třídy nemůžou odkazovat na parametry typu třídy.", + "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509": "Návratový typ základního konstruktoru {0} není typ objektu ani průsečík typů objektů se staticky známými členy.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Všechny základní konstruktory musí mít stejný návratový typ.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Základní adresář pro překlad neabsolutních názvů modulů.", + "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737": "Když je cíl nastavený níže než ES2020, literály typu BigInt nejsou k dispozici.", + "Binary_digit_expected_1177": "Očekává se binární číslice.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Element vazby {0} má implicitně typ {1}.", + "Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations_9019": "Elementy vazeb nelze exportovat přímo s možností --isolatedDeclarations.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Proměnná bloku {0} se používá před vlastní deklarací.", + "Build_a_composite_project_in_the_working_directory_6925": "Sestavte složený projekt v pracovním adresáři.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636": "Sestavujte všechny projekty včetně těch, které se zdají aktuální.", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Sestavit jeden nebo více projektů a jejich závislosti, pokud jsou zastaralé", + "Build_option_0_requires_a_value_of_type_1_5073": "Možnost buildu {0} vyžaduje hodnotu typu {1}.", + "Building_project_0_6358": "Sestavuje se projekt {0}...", + "Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any_6720": "Instance integrovaných iterátorů jsou vytvářeny s typem „TReturn“ s hodnotou „undefined“ místo hodnoty „any“.", + "COMMAND_LINE_FLAGS_6921": "PŘÍZNAKY PŘÍKAZOVÉHO ŘÁDKU", + "COMMON_COMMANDS_6916": "BĚŽNÉ PŘÍKAZY", + "COMMON_COMPILER_OPTIONS_6920": "BĚŽNÉ PARAMETRY KOMPILÁTORU", + "Call_decorator_expression_90028": "Zavolat výraz dekorátoru", + "Call_signature_return_types_0_and_1_are_incompatible_2202": "Návratové typy signatury volání {0} a {1} nejsou kompatibilní.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Signatura volání s chybějící anotací návratového typu má implicitně návratový typ any.", + "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204": "Signatury volání bez argumentů mají nekompatibilní návratové typy {0} a {1}.", + "Can_only_convert_logical_AND_access_chains_95142": "Převést se dají jen logické řetězy přístupu AND.", + "Can_only_convert_named_export_95164": "Lze převést pouze pojmenovaný export ", + "Can_only_convert_property_with_modifier_95137": "Převést se dá jenom vlastnost s modifikátorem.", + "Can_only_convert_string_concatenations_and_string_literals_95154": "Převést lze pouze zřetězení řetězců a řetězcové literály.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "K {0}.{1} nelze získat přístup, protože {0} je typ, nikoli názvový prostor. Chtěli jste načíst typ vlastnosti {1} v {0} pomocí {0}[{1}]?", + "Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead_1281": "Když je povolena možnost „{0}“, nelze získat přístup k „{1}“ z jiného souboru bez kvalifikace. Místo toho použijte možnost „{2}“.", + "Cannot_access_ambient_const_enums_when_0_is_enabled_2748": "Když je povolená možnost „{0}“, nelze přistupovat k výčtům prostředí „const enum“.", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Typ konstruktoru {0} se nedá přiřadit k typu konstruktoru {1}.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Abstraktní typ konstruktoru nejde přiřadit neabstraktnímu typu konstruktoru.", + "Cannot_assign_to_0_because_it_is_a_class_2629": "Do {0} se nedá přiřazovat, protože je to třída.", + "Cannot_assign_to_0_because_it_is_a_constant_2588": "Nejde přiřadit k vlastnosti {0}, protože je konstantní.", + "Cannot_assign_to_0_because_it_is_a_function_2630": "Do {0} se nedá přiřazovat, protože je to funkce.", + "Cannot_assign_to_0_because_it_is_a_namespace_2631": "Do {0} se nedá přiřazovat, protože je to obor názvů.", + "Cannot_assign_to_0_because_it_is_a_read_only_property_2540": "Nejde přiřadit k vlastnosti {0}, protože je jen pro čtení.", + "Cannot_assign_to_0_because_it_is_an_enum_2628": "Do {0} se nedá přiřazovat, protože je to výčet.", + "Cannot_assign_to_0_because_it_is_an_import_2632": "Do {0} se nedá přiřazovat, protože je to import.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Nejde přiřadit k položce {0}, to není proměnná.", + "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803": "Není možné přiřazovat hodnoty do privátní metody {0}. Do privátních metod se nedá zapisovat.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Modul {0} se nedá rozšířit, protože se překládá do entity, která není modul.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Modul {0} se nedá rozšířit, protože se překládá na entitu, která není modul.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Moduly nejde kompilovat pomocí možnosti {0}, pokud příznak --module nemá hodnotu amd nebo system.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Nejde vytvořit instance abstraktní třídy.", + "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766": "Iterace se nedá delegovat na hodnotu, protože metoda next jejího iterátoru očekává typ {1}, ale obsahující generátor vždy pošle {0}.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "{0} se nedá exportovat. Z modulu je možné exportovat jenom místní deklarace.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Třída {0} se nedá rozšířit. Konstruktor třídy je označený jako privátní.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Nejde rozšířit rozhraní {0}. Měli jste na mysli 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081": "Soubor tsconfig.json nejde najít v aktuálním adresáři: {0}", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Soubor tsconfig.json nejde najít v zadaném adresáři: {0}", + "Cannot_find_global_type_0_2318": "Globální typ {0} se nenašel.", + "Cannot_find_global_value_0_2468": "Globální hodnota {0} se nenašla.", + "Cannot_find_lib_definition_for_0_2726": "Nepovedlo se najít definici knihovny pro {0}.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "Nepovedlo se najít definici knihovny pro {0}. Neměli jste na mysli spíš {1}?", + "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732": "Nepovedlo se najít modul {0}. Zvažte možnost importovat modul s příponou .json pomocí --resolveJsonModule.", + "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_t_2792": "Nepovedlo se najít modul „{0}“. Nechtěli jste nastavit možnost „moduleResolution“ na „nodenext“ nebo přidat do možnosti „paths“ aliasy?", + "Cannot_find_module_0_or_its_corresponding_type_declarations_2307": "Nepovedlo se najít modul {0} nebo jeho odpovídající deklarace typů.", + "Cannot_find_name_0_2304": "Název {0} se nenašel.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Nepovedlo se najít název {0}. Měli jste na mysli {1}?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Název {0} se nedá najít. Měli jste na mysli člena instance this.{0}?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Název {0} se nedá najít. Měli jste na mysli statický člen {1}.{0}?", + "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311": "Nelze najít název {0}. Nechtěli jste to napsat v asynchronní funkci?", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583": "Nepovedlo se najít název ‚{0}‘. Potřebujete změnit cílovou knihovnu? Zkuste změnit možnost kompilátoru ‚lib‘ na ‚{1}‘ nebo novější.", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584": "Nepovedlo se najít název ‚{0}‘. Potřebujete změnit cílovou knihovnu? Zkuste změnit možnost kompilátoru ‚lib‘ tak, aby obsahovala ‚dom‘.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2867": "Nepodařilo se najít název „{0}“. Potřebujete nainstalovat definice typů pro Bun? Zkuste použít „npm i --save-dev @types/bun“.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2868": "Nepodařilo se najít název „{0}“. Potřebujete nainstalovat definice typů pro Bun? Zkuste použít „npm i --save-dev @types/bun“ a pak do pole typů v tsconfig přidejte „bun“.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582": "Nepovedlo se najít název {0}. Potřebujete nainstalovat definice typů pro spouštěč testů? Zkuste npm i --save-dev @types/jest nebo npm i --save-dev @types/mocha.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593": "Nepovedlo se najít název ‚{0}‘. Potřebujete nainstalovat definice typů pro spouštěč testů? Zkuste ‚npm i --save-dev@ types/jest‘ nebo ‚npm i --save-dev @types/mocha‘ a pak do polí typů v tsconfig přidejte ‚jest‘ nebo ‚mocha‘.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581": "Nepovedlo se najít název {0}. Potřebujete nainstalovat definice typů pro jQuery? Zkuste npm i --save-dev @types/jquery.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592": "Nepovedlo se najít název ‚{0}‘. Potřebujete nainstalovat definice typů pro jQuery? Zkuste ‚npm i --save-dev @types/jquery` a pak pro pole typů v tsconfig přidejte ‚jquery‘.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Nepovedlo se najít název {0}. Potřebujete nainstalovat definice typů pro Node? Zkuste npm i --save-dev @types/node.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Nepovedlo se najít název ‚{0}‘. Potřebujete nainstalovat definice typů pro uzel? Zkuste ‚npm i --save-dev @types/node‘ a pak do pole typů v tsconfig přidejte ‚node‘.", + "Cannot_find_namespace_0_2503": "Nenašel se obor názvů {0}.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Obor názvů {0} nejde najít. Měli jste na mysli „{1}“?", + "Cannot_find_parameter_0_1225": "Nenašel se parametr {0}.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Nenašla se společná cesta podadresářů pro vstupní soubory.", + "Cannot_find_type_definition_file_for_0_2688": "Nejde najít soubor definice pro {0}.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Soubory deklarací typů nejde importovat. Zvažte možnost místo {1} naimportovat {0}.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Proměnnou {0} s vnějším oborem nejde inicializovat ve stejném oboru jako deklaraci {1} s oborem bloku.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Nejde vyvolat objekt, který může být null.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nejde vyvolat objekt, který může být null nebo nedefinovaný.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nejde vyvolat objekt, který může být nedefinovaný.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765": "Hodnota se nedá iterovat, protože metoda next jejího iterátoru očekává typ {1}, ale při destrukci pole se vždy pošle {0}.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Hodnota se nedá iterovat, protože metoda next jejího iterátoru očekává typ {1}, ale rozsah pole bude vždy posílat {0}.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Hodnota se nedá iterovat, protože metoda next jejího iterátoru očekává typ {1}, ale for-of bude vždy posílat {0}.", + "Cannot_move_statements_to_the_selected_file_95183": "Příkazy nelze přesunout do vybraného souboru.", + "Cannot_move_to_file_selected_file_is_invalid_95179": "Nelze přesunout do souboru, vybraný soubor je neplatný.", + "Cannot_read_file_0_5083": "Nejde přečíst soubor {0}.", + "Cannot_read_file_0_Colon_1_5012": "Nejde číst soubor {0}: {1}", + "Cannot_redeclare_block_scoped_variable_0_2451": "Nejde předeklarovat proměnnou bloku {0}.", + "Cannot_redeclare_exported_variable_0_2323": "Exportovanou proměnnou {0} není možné znovu deklarovat.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Nejde předeklarovat identifikátor {0} v klauzuli catch.", + "Cannot_start_a_function_call_in_a_type_annotation_1441": "Nejde spustit volání funkce v poznámce typu.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Pokud se nezadá příznak -jsx, nepůjde JSX použít.", + "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled_1269": "Když se povolená možnost „{0}“, nelze pro obor názvů typů nebo obor názvů „pouze typ“ použít „export import“.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Nejde používat importy, exporty nebo rozšíření modulu, pokud má příznak --module hodnotu none.", + "Cannot_use_namespace_0_as_a_type_2709": "Obor názvů {0} nejde použít jako typ.", + "Cannot_use_namespace_0_as_a_value_2708": "Obor názvů {0} nejde použít jako hodnotu.", + "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816": "Klíčové slovo „this“ nejde použít v inicializátoru statické vlastnosti dekorované třídy.", + "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377": "Soubor {0} se nedá zapsat, protože přepíše soubor .tsbuildinfo vygenerovaný odkazovaným projektem {1}.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Do souboru {0} se nedá zapisovat, protože by se přepsal více vstupními soubory.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Do souboru {0} se nedá zapisovat, protože by přepsal vstupní soubor.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Proměnná klauzule catch nemůže mít inicializátor.", + "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196": "Pokud se zadá typ proměnné klauzule catch, jeho anotace musí být any nebo unknown.", + "Change_0_to_1_90014": "Změnit {0} na {1}", + "Change_all_extended_interfaces_to_implements_95038": "Změnit všechna rozšířená rozhraní na implements", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Změnit všechny typy jsdoc-style na TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Změnit všechny typy jsdoc-style na TypeScript (a přidat | undefined do typů s možnou hodnotou null)", + "Change_extends_to_implements_90003": "Změnit extends na implements", + "Change_spelling_to_0_90022": "Změnit pravopis na {0}", + "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700": "Zkontrolujte vlastnosti třídy, které sice jsou deklarované, ale nejsou nastavené v konstruktoru.", + "Check_side_effect_imports_6806": "Zkontrolujte importy typu „side effect“.", + "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697": "Zkontrolujte, jestli argumenty metod bind, call a apply odpovídají původní funkci.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Kontroluje se, jestli je {0} nejdelší odpovídající předpona pro {1}–{2}.", + "Circular_definition_of_import_alias_0_2303": "Cyklická definice aliasu importu {0}", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Při překladu konfigurace se zjistila cykličnost: {0}.", + "Circularity_originates_in_type_at_this_location_2751": "Zdrojem cykličnosti je typ na tomto umístění.", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Třída {0} definuje členský přístupový objekt instance {1}, ale rozšířená třída {2} ho definuje jako členskou funkci instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Třída {0} definuje členskou funkci instance {1}, ale rozšířená třída {2} ji definuje jako členský přístupový objekt instance.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Třída {0} definuje vlastnost člena instance {1}, ale rozšířená třída {2} ji definuje jako členskou funkci instance.", + "Class_0_incorrectly_extends_base_class_1_2415": "Třída {0} nesprávně rozšiřuje základní třídu {1}.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Třída {0} nesprávně implementuje třídu {1}. Nechtěli jste rozšířit třídu {1} a dědit její členy jako podtřídu?", + "Class_0_incorrectly_implements_interface_1_2420": "Třída {0} nesprávně implementuje rozhraní {1}.", + "Class_0_used_before_its_declaration_2449": "Třída {0} se používá dříve, než se deklaruje.", + "Class_constructor_may_not_be_a_generator_1368": "Konstruktor třídy nemůže být generátor.", + "Class_constructor_may_not_be_an_accessor_1341": "Konstruktor třídy nemůže být přístupový objekt.", + "Class_declaration_cannot_implement_overload_list_for_0_2813": "Deklarace třídy nemůže implementovat seznam přetížení pro {0}.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklarace tříd nemůžou mít více než jednu značku ‚@augments‘ nebo ‚@extends‘.", + "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Dekorátory tříd se nedají použít se statickým privátním identifikátorem. Zvažte možnost odebrat experimentální dekorátor.", + "Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super_2855": "Pole třídy „{0}“ definované nadřazenou třídou není v podřízené třídě přístupné přes třídu typu super.", + "Class_name_cannot_be_0_2414": "Třída nemůže mít název {0}.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Když se cílí na ES5 s modulem {0}, název třídy nemůže být Object.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Statická strana třídy {0} nesprávně rozšiřuje statickou stranu základní třídy {1}.", + "Classes_can_only_extend_a_single_class_1174": "Třídy můžou rozšířit jenom jednu třídu.", + "Classes_may_not_have_a_field_named_constructor_18006": "Třídy nemůžou mít pole s názvem constructor.", + "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210": "Kód obsažený ve třídě se vyhodnocuje ve striktním režimu jazyka JavaScript, který toto použití {0} nepovoluje. Další informace najdete tady: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode", + "Command_line_Options_6171": "Možnosti příkazového řádku", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Zkompilujte projekt podle cesty k jeho konfiguračnímu souboru nebo do složky se souborem tsconfig.json.", + "Compiler_Diagnostics_6251": "Diagnostika kompilátoru", + "Compiler_option_0_cannot_be_given_an_empty_string_18051": "Možnost kompilátoru „{0}“ nemůže mít prázdný řetězec.", + "Compiler_option_0_expects_an_argument_6044": "Parametr kompilátoru {0} očekává argument.", + "Compiler_option_0_may_not_be_used_with_build_5094": "Možnost kompilátoru „--{0}“ se nesmí používat s „--build“.", + "Compiler_option_0_may_only_be_used_with_build_5093": "Možnost kompilátoru „--{0}“ se smí používat jenom s „--build“.", + "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124": "Možnost kompilátoru {0} hodnoty {1} je nestabilní. Ke ztlumení této chyby použijte noční TypeScript. Zkuste provést aktualizaci pomocí příkazu npm install -D typescript@next.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Parametr kompilátoru {0} vyžaduje hodnotu typu {1}.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Kompilátor si rezervuje název {0} při generování privátního identifikátoru pro nižší úroveň.", + "Compiles_the_TypeScript_project_located_at_the_specified_path_6927": "Zkompiluje projekt TypeScriptu umístěný v zadané cestě.", + "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923": "Zkompiluje aktuální projekt (tsconfig.json v pracovním adresáři).", + "Compiles_the_current_project_with_additional_settings_6929": "Zkompiluje aktuální projekt s dalšími nastaveními.", + "Completeness_6257": "Úplnost", + "Composite_projects_may_not_disable_declaration_emit_6304": "Složené projekty nemůžou zakázat generování deklarací.", + "Composite_projects_may_not_disable_incremental_compilation_6379": "Složené projekty nemůžou zakázat přírůstkovou kompilaci.", + "Computed_from_the_list_of_input_files_6911": "Vypočítáno ze seznamu vstupních souborů", + "Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedD_9014": "Počítané vlastnosti musí být číselné nebo řetězcové literály, proměnné nebo výrazy s tečkami s možností --isolatedDeclarations.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Názvy počítaných vlastností se ve výčtech nepovolují.", + "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038": "Názvy počítaných vlastností v literálech třídy nebo objektu nelze odvodit pomocí možnosti --isolatedDeclarations.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Ve výčtu, jehož členy mají hodnoty typu string, se nepovolují vypočítané hodnoty.", + "Concatenate_and_emit_output_to_single_file_6001": "Zřetězit a generovat výstup do jednoho souboru", + "Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports_6410": "Podmínky, které se mají nastavit kromě výchozích hodnot specifických pro překladač při překladu importů.", + "Conflicts_are_in_this_file_6201": "V tomto souboru se nacházejí konflikty.", + "Consider_adding_a_declare_modifier_to_this_class_6506": "Zvažte přidání modifikátoru „declare“ do této třídy.", + "Construct_signature_return_types_0_and_1_are_incompatible_2203": "Návratové typy signatury konstruktu {0} a {1} nejsou kompatibilní.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Podpis konstruktoru s chybějící anotací návratového typu má implicitně návratový typ any.", + "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205": "Signatury konstruktů bez argumentů mají nekompatibilní návratové typy {0} a {1}.", + "Constructor_implementation_is_missing_2390": "Chybí implementace konstruktoru.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Konstruktor třídy {0} je privátní a dostupný jenom v rámci deklarace třídy.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Konstruktor třídy {0} je chráněný a dostupný jenom v rámci deklarace třídy.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386": "Když se notace typu konstruktoru používá v typu sjednocení, musí být uzavřená do závorky.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388": "Když se notace typu konstruktoru používá v typu průniku, musí být uzavřená do závorky.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory odvozených tříd musí obsahovat volání příkazu super.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Není zadaný obsažený soubor a nedá se určit kořenový adresář – přeskakuje se vyhledávání ve složce node_modules.", + "Containing_function_is_not_an_arrow_function_95128": "Obsahující funkce není funkcí šipky.", + "Control_what_method_is_used_to_detect_module_format_JS_files_1475": "Určete, která metoda se používá k detekci souborů JS ve formátu modulu.", + "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352": "Převod typu {0} na typ {1} může být chyba, protože ani jeden z těchto typů se s tím druhým dostatečně nepřekrývá. Pokud je to záměr, převeďte nejdříve výraz na unknown.", + "Convert_0_to_1_in_0_95003": "Převést {0} na {1} v {0}", + "Convert_0_to_mapped_object_type_95055": "Převést {0} na typ mapovaného objektu", + "Convert_all_const_to_let_95102": "Převést všechny const na let", + "Convert_all_constructor_functions_to_classes_95045": "Převést všechny funkce konstruktoru na třídy", + "Convert_all_invalid_characters_to_HTML_entity_code_95101": "Převést všechny neplatné znaky na kód entity HTML", + "Convert_all_re_exported_types_to_type_only_exports_1365": "Převést všechny opětovně exportované typy na exporty, při kterých se exportují jen typy", + "Convert_all_require_to_import_95048": "Převést všechna volání require na import", + "Convert_all_to_async_functions_95066": "Převést vše na asynchronní funkce", + "Convert_all_to_bigint_numeric_literals_95092": "Převést vše na číselné literály bigint", + "Convert_all_to_default_imports_95035": "Převést vše na výchozí importy", + "Convert_all_type_literals_to_mapped_type_95021": "Převést všechny literály typů na namapovaný typ", + "Convert_all_typedef_to_TypeScript_types_95177": "Převeďte všechny typy typedef na typy TypeScript.", + "Convert_arrow_function_or_function_expression_95122": "Převést funkci šipky nebo výraz funkce", + "Convert_const_to_let_95093": "Převést const na let", + "Convert_default_export_to_named_export_95061": "Převést výchozí export na pojmenovaný export", + "Convert_function_declaration_0_to_arrow_function_95106": "Převést deklaraci funkce {0} na funkci šipky", + "Convert_function_expression_0_to_arrow_function_95105": "Převést výraz funkce {0} na funkci šipky", + "Convert_function_to_an_ES2015_class_95001": "Převést funkci na třídu ES2015", + "Convert_invalid_character_to_its_html_entity_code_95100": "Převést neplatný znak na jeho kód entity HTML", + "Convert_named_export_to_default_export_95062": "Převést pojmenovaný export na výchozí export", + "Convert_named_imports_to_default_import_95170": "Převést pojmenované importy na výchozí import", + "Convert_named_imports_to_namespace_import_95057": "Převést pojmenované importy na import oboru názvů", + "Convert_namespace_import_to_named_imports_95056": "Převést import oboru názvů na pojmenované importy", + "Convert_overload_list_to_single_signature_95118": "Převést seznam přetížení na jednu signaturu", + "Convert_parameters_to_destructured_object_95075": "Převést parametry na destrukturovaný objekt", + "Convert_require_to_import_95047": "Převést require na import", + "Convert_to_ES_module_95017": "Převést na modul ES", + "Convert_to_a_bigint_numeric_literal_95091": "Převést na číselný literál bigint", + "Convert_to_anonymous_function_95123": "Převést na anonymní funkci", + "Convert_to_arrow_function_95125": "Převést na funkci šipky", + "Convert_to_async_function_95065": "Převést na asynchronní funkci", + "Convert_to_default_import_95013": "Převést na výchozí import", + "Convert_to_named_function_95124": "Převést na pojmenovanou funkci", + "Convert_to_optional_chain_expression_95139": "Převést na nepovinný výraz řetězu.", + "Convert_to_template_string_95096": "Převést na řetězec šablony", + "Convert_to_type_only_export_1364": "Převést na export, při kterém se exportují jen typy", + "Convert_typedef_to_TypeScript_type_95176": "Převeďte typedef na typ TypeScript.", + "Corrupted_locale_file_0_6051": "Soubor národního prostředí {0} je poškozený.", + "Could_not_convert_to_anonymous_function_95153": "Nepovedlo se převést na anonymní funkci.", + "Could_not_convert_to_arrow_function_95151": "Nepovedlo se převést na funkci šipky.", + "Could_not_convert_to_named_function_95152": "Nepovedlo se převést na pojmenovanou funkci.", + "Could_not_determine_function_return_type_95150": "Nepovedlo se určit návratový typ funkce.", + "Could_not_find_a_containing_arrow_function_95127": "Nepovedlo se najít obsahující funkci šipky.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Nenašel se soubor deklarací pro modul {0}. {1} má implicitně typ any.", + "Could_not_find_convertible_access_expression_95140": "Nepovedlo se najít převoditelný výraz přístupu.", + "Could_not_find_export_statement_95129": "Nešlo najít příkaz export.", + "Could_not_find_import_clause_95131": "Nešlo najít klauzuli import.", + "Could_not_find_matching_access_expressions_95141": "Nepovedlo se najít odpovídající výrazy přístupu.", + "Could_not_find_name_0_Did_you_mean_1_2570": "Nepodařilo se najít název {0}. Měli jste na mysli {1}?", + "Could_not_find_namespace_import_or_named_imports_95132": "Nepovedlo se najít import oboru názvů nebo pojmenované importy.", + "Could_not_find_property_for_which_to_generate_accessor_95135": "Nepovedlo se najít vlastnost, pro kterou se má vygenerovat přístupový objekt.", + "Could_not_find_variable_to_inline_95185": "Nepodařilo se najít proměnnou, která se má vložit.", + "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Nepovedlo se přeložit cestu {0} s příponami {1}.", + "Could_not_write_file_0_Colon_1_5033": "Nedá se zapisovat do souboru {0}: {1}", + "Create_source_map_files_for_emitted_JavaScript_files_6694": "Vytvořte pro generované soubory JavaScriptu soubory sourcemap.", + "Create_sourcemaps_for_d_ts_files_6614": "Pro soubory d.ts vytvořte soubory sourcemap.", + "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926": "Vytvoří tsconfig.json doporučenými nastaveními v pracovním adresáři.", + "DIRECTORY_6038": "ADRESÁŘ", + "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537": "Desítkové řídicí sekvence a zpětné odkazy nejsou ve třídě znaků povoleny.", + "Decimals_with_leading_zeros_are_not_allowed_1489": "Desetinná čísla s úvodními nulami nejsou povolena.", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "Deklarace rozšiřuje deklaraci v jiném souboru. Toto není možné serializovat.", + "Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_support_9026": "Generování deklarace pro tento soubor vyžaduje zachování tohoto importu pro rozšíření. Toto není podporováno s možností --isolatedDeclarations.", + "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "Generování deklarací pro tento soubor vyžaduje, aby se použil privátní název {0}. Explicitní anotace typu může generování deklarací odblokovat.", + "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "Generování deklarací pro tento soubor vyžaduje, aby se použil privátní název {0} z modulu {1}. Explicitní anotace typu může generování deklarací odblokovat.", + "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_sup_9025": "Generování deklarace pro tento parametr vyžaduje implicitní přidání možnosti „undefined“ do jeho typu. Není podporováno s možností „--isolatedDeclarations“.", + "Declaration_expected_1146": "Očekává se deklarace.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Název deklarace je v konfliktu s integrovaným globálním identifikátorem {0}.", + "Declaration_or_statement_expected_1128": "Očekává se deklarace nebo příkaz.", + "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809": "Očekávala se deklarace nebo příkaz. Tento znak = následuje blok příkazů, takže pokud jste chtěli napsat destrukturační přiřazení, možná bude nutné uzavřít celé přiřazení do závorek.", + "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264": "Deklarace s kontrolními výrazy jednoznačného přiřazení musí mít také anotace typu.", + "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263": "Deklarace s inicializátory nemůžou mít také kontrolní výrazy jednoznačného přiřazení.", + "Declare_a_private_field_named_0_90053": "Deklarovat privátní pole s názvem {0}", + "Declare_method_0_90023": "Deklarovat metodu {0}", + "Declare_private_method_0_90038": "Deklarovat privátní metodu {0}", + "Declare_private_property_0_90035": "Deklarujte privátní vlastnost {0}.", + "Declare_property_0_90016": "Deklarovat vlastnost {0}", + "Declare_static_method_0_90024": "Deklarovat statickou metodu {0}", + "Declare_static_property_0_90027": "Deklarovat statickou vlastnost {0}", + "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270": "Návratový typ funkce dekoratéru {0} se nedá přiřadit k typu {1}.", + "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271": "Návratový typ funkce dekoratéru je {0}, ale očekává se, že bude void nebo any.", + "Decorator_used_before_export_here_1486": "Dekoratér je tu použit před možností „export“.", + "Decorators_are_not_valid_here_1206": "Dekorátory tady nejsou platné.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekorátory nejde použít na víc přístupových objektů get/set se stejným názvem.", + "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038": "Dekoratéry se nemůžou vyskytovat po „export“ nebo „export default“, pokud se taky vyskytují před možností „export“.", + "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436": "Dekoratéry musí předcházet název a všechna klíčová slova deklarace vlastností.", + "Default_catch_clause_variables_as_unknown_instead_of_any_6803": "Výchozí proměnné klauzule catch jako unknown namísto any.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Výchozí export modulu má nebo používá privátní název {0}.", + "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037": "Výchozí exporty nelze odvodit pomocí --isolatedDeclarations.", + "Default_library_1424": "Výchozí knihovna", + "Default_library_for_target_0_1425": "Výchozí knihovna pro cíl {0}", + "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Definice následujících identifikátorů je v konfliktu s definicemi v jiném souboru: {0}", + "Delete_all_unused_declarations_95024": "Odstranit všechny nepoužívané deklarace", + "Delete_all_unused_imports_95147": "Odstranit všechny nepoužívané importy", + "Delete_all_unused_param_tags_95172": "Odstranit všechny nepoužívané značky @param", + "Delete_the_outputs_of_all_projects_6365": "Odstraňte výstupy všech projektů.", + "Delete_unused_param_tag_0_95171": "Odstranit nepoužívanou značku @param {0}", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Zastaralé] Použijte místo toho --jsxFactory. Určí objekt vyvolaný pro createElement při cílení na generování JSX react.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Zastaralé] Použijte místo toho --outFile. Zřetězí a vygeneruje výstup do jednoho souboru.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Zastaralé] Použijte místo toho --skipLibCheck. Přeskočí kontrolu typů výchozích souborů deklarací knihovny.", + "Deprecated_setting_Use_outFile_instead_6677": "Nastavení je zastaralé. Místo něj použijte outFile.", + "Did_you_forget_to_use_await_2773": "Nezapomněli jste použít await?", + "Did_you_mean_0_1369": "Měli jste na mysli {0}?", + "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735": "Měli jste na mysli omezení {0} na typ new (...args: any[]) => {1}?", + "Did_you_mean_to_call_this_expression_6212": "Nechtěli jste zavolat tento výraz?", + "Did_you_mean_to_mark_this_function_as_async_1356": "Nechtěli jste označit tuto funkci jako async?", + "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312": "Neměli jste v úmyslu použít znak :? Znak = může následovat pouze po názvu vlastnosti, když je obsahující objekt literálu součástí vzoru destrukturalizace.", + "Did_you_mean_to_use_new_with_this_expression_6213": "Nechtěli jste u tohoto výrazu použít new?", + "Digit_expected_1124": "Očekává se číslice.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Adresář {0} neexistuje. Všechna vyhledávání v něm se přeskočí.", + "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270": "Adresář {0} neobsahuje package.json scope. Importy nebudou vyřešeny.", + "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669": "V generovaných souborech JavaScriptu zakažte přidávání direktiv „use strict“.", + "Disable_checking_for_this_file_90018": "Zakázat kontrolu tohoto souboru", + "Disable_emitting_comments_6688": "Zakázat generování komentářů.", + "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701": "Zakažte generování deklarací s příznakem „@internal“ v komentářích JSDoc.", + "Disable_emitting_files_from_a_compilation_6660": "Zakažte generování souborů z kompilace.", + "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662": "Zakažte generování souborů, pokud jsou při kontrole typů nahlášeny jakékoli chyby.", + "Disable_erasing_const_enum_declarations_in_generated_code_6682": "Zakažte v generovaném kódu mazání deklarací const enum.", + "Disable_error_reporting_for_unreachable_code_6603": "Zakažte hlášení chyb, pokud je kód nedosažitelný.", + "Disable_error_reporting_for_unused_labels_6604": "Zakažte hlášení chyb u nepoužitých popisků.", + "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805": "Zakažte úplnou kontrolu typů (budou hlášeny pouze kritické chyby analýzy a generování).", + "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661": "Zakázat v kompilovaném výstupu generování vlastních pomocných funkcí, jako je __extends.", + "Disable_including_any_library_files_including_the_default_lib_d_ts_6670": "Zakažte zahrnutí všech souborů knihoven, včetně výchozí lib.d.ts.", + "Disable_loading_referenced_projects_6235": "Zakažte načítání odkazovaných projektů.", + "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620": "Zakažte v odkazech na složené projekty místo deklaračních souborů používat preferované zdrojové soubory.", + "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702": "Zakažte při vytváření literálů objektů hlášení zbytečně velkého počtu chyb vlastností.", + "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683": "Zakažte překlad odkazů symlink na jejich skutečnou cestu (realpath). Toto nastavení koreluje se stejným příznakem uzlu.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Zakázat omezení velikosti v projektech JavaScriptu", + "Disable_solution_searching_for_this_project_6224": "Zakažte vyhledávání řešení pro tento projekt.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6673": "Zakáže striktní kontroly generických signatur v typech funkcí.", + "Disable_the_type_acquisition_for_JavaScript_projects_6625": "Zakázat v javascriptových projektech získávání typů", + "Disable_truncating_types_in_error_messages_6663": "Zakázat v chybových zprávách zkracování typů.", + "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221": "Zakažte možnost používat zdrojové soubory místo souborů deklarací z odkazovaných projektů.", + "Disable_wiping_the_console_in_watch_mode_6684": "Zakažte vymazání konzole v režimu sledování.", + "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616": "Při získávání typů se zakáže odvozování. Názvy souborů se vyhledají v projektu.", + "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672": "Zakázat import, require nebo zvětšování počtu souborů, které by typeScript měl přidat do projektu.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Zakažte odkazy na stejný soubor s nekonzistentně použitými malými a velkými písmeny.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Nepřidávat odkazy se třemi lomítky nebo importované moduly do seznamu kompilovaných souborů", + "Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript_6721": "Nepovolit konstruktory modulu runtime, které nejsou součástí ECMAScriptu", + "Do_not_emit_comments_to_output_6009": "Negenerovat komentáře pro výstup", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Negenerovat deklarace pro kód s anotací @internal", + "Do_not_emit_outputs_6010": "Negenerovat výstupy", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Negenerovat výstupy, pokud byly oznámeny chyby", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Negenerujte direktivy use strict ve výstupu modulu.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Nemazat deklarace konstantního výčtu v generovaném kódu", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Negenerovat v kompilovaném výstupu vlastní pomocné funkce jako __extends", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Nezahrnovat výchozí soubor knihovny (lib.d.ts)", + "Do_not_report_errors_on_unreachable_code_6077": "Neoznamují se chyby v nedosažitelném kódu.", + "Do_not_report_errors_on_unused_labels_6074": "Neoznamují se chyby v nepoužívaných popiscích.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Nepřekládat skutečnou cestu symbolických odkazů", + "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804": "Netransformujte ani nevynechávejte žádné importy nebo exporty, které nejsou označeny jako „pouze typ“, a zajistěte, aby byly zapsány ve formátu výstupního souboru podle nastavení „module“.", + "Do_not_truncate_error_messages_6165": "Nezkracovat chybové zprávy", + "Duplicate_function_implementation_2393": "Duplicitní implementace funkce", + "Duplicate_identifier_0_2300": "Duplicitní identifikátor {0}", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Duplicitní identifikátor {0}. Kompilátor si vyhrazuje název {1} v oboru nejvyšší úrovně pro daný modul.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Duplicitní identifikátor {0}. Kompilátor rezervuje název {1} v oboru nejvyšší úrovně modulu, který obsahuje asynchronní funkce.", + "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818": "Duplicitní identifikátor {0}. Kompilátor rezervuje název {1}, když se generují odkazy super ve statických inicializátorech.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Duplicitní identifikátor {0}. Kompilátor používá deklaraci {1} pro podporu asynchronních funkcí.", + "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804": "Duplicitní identifikátor {0}. Statické elementy a elementy instancí nemůžou sdílet stejný privátní název.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Duplicitní identifikátor arguments. Kompilátor pomocí identifikátoru arguments inicializuje parametry rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Duplicitní identifikátor _newTarget. Kompilátor používá deklaraci proměnné _newTarget k zachycení odkazu na metavlastnost new.target.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Duplicitní identifikátor _this. Kompilátor pomocí deklarace proměnné _this zaznamenává odkaz na příkaz this.", + "Duplicate_index_signature_for_type_0_2374": "Duplicitní signatura indexu pro typ {0}.", + "Duplicate_label_0_1114": "Duplicitní popisek {0}", + "Duplicate_property_0_2718": "Duplicitní vlastnost {0}.", + "Duplicate_regular_expression_flag_1500": "Duplikovaný příznak regulárního výrazu", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specifikátor dynamického importu musí být typu string, ale tady má typ {0}.", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Dynamické importy se podporují jen v případě, že příznak --module je nastavený na es2020, es2022, esnext, commonjs, amd, system, umd, node16, node18 nebo nodenext.", + "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments_1450": "Dynamické importy můžou jako argumenty přijímat jenom specifikátor modulu a volitelnou sadu atributů.", + "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_1324": "Dynamické importy podporují druhý argument, pouze pokud je možnost --module nastavena na esnext, node16, node18, nodenext nebo preserve.", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve_1293": "Když je možnost „module“ nastavená na „preserve“, v modulu CommonJS se nepovoluje syntaxe ESM.", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled_1286": "Když je povolená syntaxe „verbatimModuleSyntax“, není v modulu CommonJS povolená syntaxe ESM.", + "Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given_4125": "Každá deklarace „{0}.{1}“ se liší ve své hodnotě. Bylo očekáváno „{2}“, ale zadáno bylo „{3}“.", + "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Každý člen typu sjednocení {0} má signatury konstruktu, ale žádná z těchto signatur není kompatibilní s jinou signaturou.", + "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758": "Každý člen typu sjednocení {0} má signatury, ale žádná z těchto signatur není kompatibilní s jinou signaturou.", + "Editor_Support_6249": "Podpora editoru", + "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053": "Element má implicitně typ any, protože pomocí výrazu typu {0} není možné indexovat typ {1}.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element má implicitně typ any, protože indexový výraz není typu number.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Element má implicitně typ any, protože typ {0} nemá žádnou signaturu indexu.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052": "Element má implicitně typ any, protože typ {0} nemá žádnou signaturu indexu. Nechtěli jste zavolat {1}?", + "Emit_6246": "Generovat", + "Emit_ECMAScript_standard_compliant_class_fields_6712": "Generovat pole třídy ECMAScript-standard-compliant.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622": "Vygeneruje na začátku výstupních souborů značku pořadí bajtů ve formátu UTF-8.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Vygeneruje jediný soubor se zdrojovými mapováními namísto samostatného souboru.", + "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638": "Vygenerujte profil procesoru v8 spuštěného kompilátoru pro ladění.", + "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626": "Vygenerujte další JavaScript, aby se podpora importování modulů CommonJS ulehčila. Tím se za účelem kompatibility typů povolí „allowSyntheticDefaultImports“.", + "Emit_class_fields_with_Define_instead_of_Set_6222": "Vygenerujte pole třídy pomocí Define namísto Set.", + "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624": "Vygenerujte metadata o typu návrhu pro dekorované deklarace ve zdrojových souborech.", + "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621": "Generovat kompatibilnější kód, ale při iteraci použít režim s komentářem (verbose) a méně výkonný JavaScript.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Vygeneruje zdroj spolu se zdrojovými mapováními v jednom souboru. Vyžaduje, aby byla nastavená možnost --inlineSourceMap nebo --sourceMap.", + "Enable_all_strict_type_checking_options_6180": "Povolí všechny možnosti striktní kontroly typů.", + "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685": "Povolte ve výstupu TypeScriptu barvu a formátování, aby byly chyby kompilátoru čitelnější.", + "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611": "Povolte omezení, která v projektu TypeScriptu umožní používat odkazy na projekt.", + "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667": "Povolte hlášení chyb u cest kódu, které funkce výslovně nevrátí.", + "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665": "Povolte hlášení chyb u výrazů a deklarací s implicitním typem any.", + "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664": "Povolit hlášení chyb v příkazech switch v případě fallthrough.", + "Enable_error_reporting_in_type_checked_JavaScript_files_6609": "Povolit hlášení chyb v javascriptových souborech se zkontrolovanými typy.", + "Enable_error_reporting_when_local_variables_aren_t_read_6675": "Povolte hlášení chyb, když se místní proměnná nepřečte.", + "Enable_error_reporting_when_this_is_given_the_type_any_6668": "Povolte hlášení chyb, když má „this“ určený typ „any“.", + "Enable_experimental_support_for_legacy_experimental_decorators_6630": "Povolte experimentální podporu pro starší experimentální dekoratéry.", + "Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present_6264": "Povolte import souborů s libovolnou příponou za předpokladu, že je k dispozici soubor deklarace.", + "Enable_importing_json_files_6689": "Povolte importování souborů .json.", + "Enable_lib_replacement_6808": "Povolit nahrazení knihovny", + "Enable_project_compilation_6302": "Povolit kompilování projektu", + "Enable_strict_bind_call_and_apply_methods_on_functions_6214": "Povolte ve funkcích metody bind, call a apply.", + "Enable_strict_checking_of_function_types_6186": "Povolí striktní kontrolu typů funkcí.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Povolí striktní kontrolu inicializace vlastností ve třídách.", + "Enable_strict_null_checks_6113": "Povolte striktní kontroly hodnot null.", + "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074": "Povolte v konfiguračním souboru možnost experimentalDecorators.", + "Enable_the_jsx_flag_in_your_configuration_file_95088": "Povolte v konfiguračním souboru příznak --jsx.", + "Enable_tracing_of_the_name_resolution_process_6085": "Povolte trasování procesu překladu IP adres.", + "Enable_verbose_logging_6713": "Povolte podrobné protokolování.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Povolí interoperabilitu generování mezi moduly CommonJS a ES prostřednictvím vytváření objektů oboru názvů pro všechny importy. Implikuje allowSyntheticDefaultImports.", + "Enables_experimental_support_for_ES7_decorators_6065": "Povolí experimentální podporu pro dekorátory ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Povolí experimentální podporu pro generování metadat typu pro dekorátory.", + "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671": "Vynucuje použití indexovaných přístupových objektů pro klíče deklarované přes indexovaný typ.", + "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666": "Zajistěte označení přepisovaných členů v odvozených třídách modifikátorem override.", + "Ensure_that_casing_is_correct_in_imports_6637": "Při importu ověřovat správnost používání malých a velkých písmen.", + "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645": "Zajistit bezpečnou transpilaci všech souborů bez spoléhání na jiné importy.", + "Ensure_use_strict_is_always_emitted_6605": "Vždy zajistěte generování direktivy „use strict“.", + "Entering_conditional_exports_6413": "Vstup do podmíněných exportů", + "Entry_point_for_implicit_type_library_0_1420": "Vstupní bod pro knihovnu implicitních typů {0}", + "Entry_point_for_implicit_type_library_0_with_packageId_1_1421": "Vstupní bod pro knihovnu implicitních typů {0} s packageId {1}", + "Entry_point_of_type_library_0_specified_in_compilerOptions_1417": "Vstupní bod pro knihovnu typů {0} zadanou v compilerOptions", + "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418": "Vstupní bod pro knihovnu typů {0} zadanou v compilerOptions s packageId {1}", + "Enum_0_used_before_its_declaration_2450": "Výčet {0} se používá dříve, než se deklaruje.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Deklarace výčtu jdou sloučit jenom s oborem názvů nebo jinými deklaracemi výčtu.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Všechny deklarace výčtu musí být konstantní nebo nekonstantní.", + "Enum_member_expected_1132": "Očekává se člen výčtu.", + "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056": "Když je povolená možnost „isolatedModules“, musí mít člen výčtu následující po neliterálovém číselném členu inicializátor.", + "Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDecl_9020": "Inicializátory členů výčtu musí být počítatelné bez odkazů na externí symboly s možností „--isolatedDeclarations“.", + "Enum_member_must_have_initializer_1061": "Člen výčtu musí mít inicializátor.", + "Enum_name_cannot_be_0_2431": "Název výčtu nemůže být {0}.", + "Errors_Files_6041": "Soubory chyb", + "Escape_sequence_0_is_not_allowed_1488": "Řídicí sekvence „{0}“ není povolená.", + "Examples_Colon_0_6026": "Příklady: {0}", + "Excessive_complexity_comparing_types_0_and_1_2859": "Nadměrná složitost při porovnávání typů „{0}“ a „{1}“.", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Nadměrná hloubka zásobníku při porovnávání typů {0} a {1}", + "Exiting_conditional_exports_6416": "Opuštění podmíněných exportů.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Očekávané argumenty typu {0}–{1}; zadejte je se značkou @extends.", + "Expected_0_arguments_but_got_1_2554": "Očekával se tento počet argumentů: {0}. Počet předaných argumentů: {1}", + "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794": "Očekával se tento počet argumentů: {0}, ale byl přijat tento počet: {1}. Nezapomněli jste zahrnout void do argumentu typu pro objekt Promise?", + "Expected_0_type_arguments_but_got_1_2558": "Očekávaly se argumenty typu {0}, ale předaly se argumenty typu {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Očekávané argumenty typu {0}; zadejte je se značkou @extends.", + "Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_2810": "Očekával se 1 argument, ale bylo jich 0. New Promise() potřebuje pomocný parametr JSDoc k vytvoření resolve, který se dá volat bez argumentů.", + "Expected_a_Unicode_property_name_1523": "Byl očekáván název vlastnosti Unicode.", + "Expected_a_Unicode_property_name_or_value_1527": "Byl očekáván název nebo hodnota vlastnosti Unicode.", + "Expected_a_Unicode_property_value_1525": "Byla očekávána hodnota vlastnosti Unicode.", + "Expected_a_capturing_group_name_1514": "Byl očekáván název zachycující skupiny.", + "Expected_a_class_set_operand_1520": "Byl očekáván operand nastavení třídy.", + "Expected_at_least_0_arguments_but_got_1_2555": "Očekával se aspoň tento počet argumentů: {0}. Počet předaných argumentů: {1}", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Očekávala se odpovídající ukončující značka JSX pro {0}.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Pro fragment JSX se očekávala odpovídající uzavírací značka.", + "Expected_for_property_initializer_1442": "Pro inicializátor vlastnosti se očekával znak =.", + "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105": "Očekávaný typ pole {0} v souboru package.json byl {1}, získal se typ {2}.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Explicitně zadaný druh překladu modulu: {0}.", + "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Pokud není možnost target nastavená na es2016 nebo novější, nedají se hodnoty bigint umocnit.", + "Export_0_from_module_1_90059": "Exportovat {0} z modulu {1}", + "Export_all_referenced_locals_90060": "Exportovat všechny odkazované místní hodnoty", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Přiřazení exportu nelze použít, pokud jsou cílem moduly ECMAScript. Zkuste místo toho použít export default nebo jiný formát modulu.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Když má příznak --module hodnotu system, nepodporuje se přiřazení exportu.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Konflikty deklarace exportu s exportovanou deklarací {0}", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Deklarace exportu nejsou povolené v oboru názvů.", + "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276": "Specifikátor exportu {0} neexistuje v package.json scope na cestě {1}.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Alias exportovaného typu {0} má nebo používá privátní název {1}.", + "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084": "Alias exportovaného typu {0} má nebo používá privátní název {1} z modulu {2}.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Exportovaná proměnná {0} má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Exportovaná proměnná {0} má nebo používá název {1} z privátního modulu {2}.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Exportovaná proměnná {0} má nebo používá privátní název {1}.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Exporty a přiřazení exportů nejsou povolené v rozšířeních modulů.", + "Expression_expected_1109": "Očekával se výraz.", + "Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator_1497": "Výraz musí být uzavřen v závorkách, aby se mohl používat jako dekoratér.", + "Expression_or_comma_expected_1137": "Očekával se výraz nebo čárka.", + "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800": "Výraz vytvoří typ řazené kolekce členů, který se nedá reprezentovat, protože je příliš velký.", + "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590": "Výraz vytvoří typ sjednocení, který se nedá reprezentovat, protože je příliš složitý.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Výraz se přeloží na identifikátor _super, pomocí kterého kompilátor zaznamenává odkaz na základní třídu.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Výraz se vyhodnocuje na deklaraci proměnné _newTarget, kterou kompilátor používá k zachycení odkazu na metavlastnost new.target.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Výraz se přeloží na deklaraci proměnné _this, pomocí které kompilátor zaznamenává odkazy na příkaz this.", + "Expression_type_can_t_be_inferred_with_isolatedDeclarations_9013": "Typ výrazu nejde odvodit pomocí --isolatedDeclarations.", + "Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations_9021": "Klauzule Extends nemůže obsahovat výraz s možností „--isolatedDeclarations“.", + "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085": "Klauzule extends pro odvozený typ „{0}“ má nebo používá privátní název „{1}“.", + "Extract_base_class_to_variable_90064": "Extrahovat základní třídu do proměnné", + "Extract_binding_expressions_to_variable_90066": "Extrahujte výrazy s vazbami do proměnné", + "Extract_constant_95006": "Extrahovat konstantu", + "Extract_default_export_to_variable_90065": "Extrahovat výchozí export do proměnné", + "Extract_function_95005": "Extrahovat funkci", + "Extract_to_0_in_1_95004": "Extrahovat do {0} v {1}", + "Extract_to_0_in_1_scope_95008": "Extrahovat do {0} v oboru {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extrahovat do {0} v nadřazeném oboru", + "Extract_to_interface_95090": "Extrahovat do rozhraní", + "Extract_to_type_alias_95078": "Extrahovat do aliasu typu", + "Extract_to_typedef_95079": "Extrahovat do typedef", + "Extract_to_variable_and_replace_with_0_as_typeof_0_90069": "Extrahovat do proměnné a nahradit pomocí „{0} as typeof {0}“", + "Extract_type_95077": "Typ extrahování", + "FILE_6035": "SOUBOR", + "FILE_OR_DIRECTORY_6040": "SOUBOR NEBO ADRESÁŘ", + "Failed_to_find_peerDependency_0_6283": "Nepodařilo se najít peerDependency „{0}“.", + "Failed_to_resolve_under_condition_0_6415": "Nepodařilo se přeložit za podmínky „{0}“.", + "Fallthrough_case_in_switch_7029": "Případ Fallthrough v příkazu switch", + "File_0_does_not_exist_6096": "Soubor {0} neexistuje.", + "File_0_does_not_exist_according_to_earlier_cached_lookups_6240": "Podle dřívějších vyhledávání v mezipaměti soubor {0} neexistuje.", + "File_0_exists_according_to_earlier_cached_lookups_6239": "Podle dřívějších vyhledávání v mezipaměti soubor {0} existuje.", + "File_0_exists_use_it_as_a_name_resolution_result_6097": "Soubor „{0}“ existuje – použijte ho jako výsledek překladu IP adres.", + "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054": "Soubor {0} má nepodporovanou příponu. Jediné podporované přípony jsou {1}.", + "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504": "Soubor {0} je javascriptový soubor. Nechtěli jste povolit možnost allowJs?", + "File_0_is_not_a_module_2306": "Soubor {0} není modul.", + "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307": "Soubor {0} není uvedený na seznamu souborů projektu {1}. Projekty musí uvádět všechny soubory nebo používat vzor include.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Soubor {0} není pod kořenovým adresářem rootDir {1}. Očekává se, že rootDir bude obsahovat všechny zdrojové soubory.", + "File_0_not_found_6053": "Soubor {0} se nenašel.", + "File_Management_6245": "Správa souborů", + "File_appears_to_be_binary_1490": "Zdá se, že soubor je binární.", + "File_change_detected_Starting_incremental_compilation_6032": "Zjistila se změna souboru. Spouští se přírůstková kompilace...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Soubor je modul CommonJS, protože {0} nemá pole type", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Soubor je modul CommonJS, protože {0} má pole type, jehož hodnota není module", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Soubor je modul CommonJS, protože se nenašel package.json", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Soubor je modul ECMAScript, protože {0} má pole type s hodnotou module", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Soubor je modul CommonJS; může být převeden na modul ES.", + "File_is_default_library_for_target_specified_here_1426": "Soubor je výchozí knihovna pro cíl, který se zadal na tomto místě.", + "File_is_entry_point_of_type_library_specified_here_1419": "Soubor je vstupní bod knihovny typů, která se zadala na tomto místě.", + "File_is_included_via_import_here_1399": "Soubor se zahrnuje pomocí importu na tomto místě.", + "File_is_included_via_library_reference_here_1406": "Soubor se zahrnuje pomocí odkazu na knihovnu na tomto místě.", + "File_is_included_via_reference_here_1401": "Soubor se zahrnuje pomocí odkazu na tomto místě.", + "File_is_included_via_type_library_reference_here_1404": "Soubor se zahrnuje pomocí odkazu na knihovnu typů na tomto místě.", + "File_is_library_specified_here_1423": "Soubor je knihovna zadaná na tomto místě.", + "File_is_matched_by_files_list_specified_here_1410": "Soubor se srovnává se seznamem files zadaným na tomto místě.", + "File_is_matched_by_include_pattern_specified_here_1408": "Soubor se srovnává podle vzoru zahrnutí zadaného na tomto místě.", + "File_is_output_from_referenced_project_specified_here_1413": "Soubor je výstup z odkazovaného projektu zadaného na tomto místě.", + "File_is_output_of_project_reference_source_0_1428": "Soubor je výstup zdroje odkazů na projekt {0}.", + "File_is_source_from_referenced_project_specified_here_1416": "Soubor je zdroj z odkazovaného projektu zadaného na tomto místě.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Název souboru {0} se od už zahrnutého názvu souboru {1} liší jenom velikostí písmen.", + "File_name_0_has_a_1_extension_looking_up_2_instead_6262": "Název souboru „{0}“ má příponu „{1}“ – místo toho se hledá: „{2}“.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Název souboru {0} má příponu {1} – odstraňuje se", + "File_redirects_to_file_0_1429": "Soubor se přesměrovává na soubor {0}.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Specifikace souboru nemůže obsahovat nadřazený adresář (..), který se vyskytuje za rekurzivním zástupným znakem adresáře (**): {0}.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Specifikace souboru nemůže končit rekurzivním zástupným znakem adresáře (**): {0}.", + "Filters_results_from_the_include_option_6627": "Filtrovat výsledky možnosti „zahrnout“.", + "Fix_all_detected_spelling_errors_95026": "Opravit všechny zjištěné pravopisné chyby", + "Fix_all_expressions_possibly_missing_await_95085": "Opravit všechny výrazy, kde je možné, že chybí await", + "Fix_all_implicit_this_errors_95107": "Opravit všechny chyby implicit-'this'", + "Fix_all_incorrect_return_type_of_an_async_functions_90037": "Opravit všechny nesprávné návratové typy asynchronních funkcí", + "Fix_all_with_type_only_imports_95182": "Opravit vše s importy „type-only“", + "Found_0_errors_6217": "Našel se tento počet chyb: {0}.", + "Found_0_errors_Watching_for_file_changes_6194": "Byl nalezen tento počet chyb: {0}. Sledují se změny souborů.", + "Found_0_errors_in_1_files_6261": "V {1} souborech byly nalezeny chyby ({0}).", + "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260": "Ve stejném souboru byly nalezeny chyby ({0}). Začínají na: {1}", + "Found_1_error_6216": "Našla se 1 chyba.", + "Found_1_error_Watching_for_file_changes_6193": "Byla nalezena 1 chyba. Sledují se změny souborů.", + "Found_1_error_in_0_6259": "Našla se 1 chyba v {0}.", + "Found_package_json_at_0_6099": "Soubor package.json se našel v {0}.", + "Found_peerDependency_0_with_1_version_6282": "Nalezeno: peerDependency – „{0}“ s verzí „{1}“", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_1250": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl „ES5“.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definiti_1251": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl „ES5“. Definice tříd jsou automaticky ve striktním režimu.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_au_1252": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl „ES5“. Moduly jsou automaticky ve striktním režimu.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Výraz funkce s chybějící anotací návratového typu má implicitně návratový typ {0}.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Implementace funkce chybí nebo nenásleduje hned po deklaraci.", + "Function_implementation_name_must_be_0_2389": "Název implementace funkce musí být {0}.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Funkce implicitně obsahuje návratový typ any, protože neobsahuje anotaci návratového typu a odkazuje se na ni přímo nebo nepřímo v jednom z jejích návratových výrazů.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový příkaz return a návratový typ neobsahuje undefined.", + "Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9007": "Funkce musí mít explicitní anotaci návratového typu s možností „--isolatedDeclarations“.", + "Function_not_implemented_95159": "Funkce není implementovaná.", + "Function_overload_must_be_static_2387": "Přetížení funkce musí být statické.", + "Function_overload_must_not_be_static_2388": "Přetížení funkce nesmí být statické.", + "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385": "Když se notace typu funkce používá v typu sjednocení, musí být uzavřená do závorky.", + "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387": "Když se notace typu funkce používá v typu průniku, musí být uzavřená do závorky.", + "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014": "Typ funkce s chybějící anotací návratového typu má implicitně návratový typ {0}.", + "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814": "Funkce s těly se dá sloučit jenom s třídami, které jsou ambientní.", + "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612": "Vygenerujte ze souborů TypeScriptu a JavaScriptu projektu soubory d.ts.", + "Generate_get_and_set_accessors_95046": "Generovat přístupové objekty get a set", + "Generate_get_and_set_accessors_for_all_overriding_properties_95119": "Generovat přístupové objekty get a set pro všechny přepisující vlastnosti", + "Generates_a_CPU_profile_6223": "Vygeneruje profil procesoru.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Pro každý odpovídající soubor .d.ts vygeneruje sourcemap.", + "Generates_an_event_trace_and_a_list_of_types_6237": "Generuje trasování události a seznam typů.", + "Generates_corresponding_d_ts_file_6002": "Generuje odpovídající soubor .d.ts.", + "Generates_corresponding_map_file_6043": "Generuje odpovídající soubor .map.", + "Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation_7025": "Generátor má implicitně typ yield {0}. Zvažte možnost přidat anotaci návratového typu.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Generátory nejsou v ambientním kontextu povolené.", + "Generic_type_0_requires_1_type_argument_s_2314": "Obecný typ {0} vyžaduje argumenty typu {1}.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Obecný typ {0} vyžaduje konkrétní počet argumentů ({1} až {2}).", + "Global_module_exports_may_only_appear_at_top_level_1316": "Exporty globálního modulu se můžou objevit jenom na nejvyšší úrovni.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Exporty globálního modulu se můžou objevit jenom v souborech deklarací.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Exporty globálního modulu se můžou objevit jenom v souborech modulů.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Globální typ {0} musí být typu třída nebo rozhraní.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Globální typ {0} musí mít parametry typu {1}.", + "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384": "Opakované kompilace --incremental a --watch předpokládají, že změny v souboru budou mít vliv jen na soubory, které na něm přímo závisejí.", + "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606": "Opakované kompilace v projektech, které používají režimy „incremental“ a „watch“ předpokládají, že změny v souboru budou mít vliv pouze na soubory, které na daném souboru přímo závisejí.", + "Hexadecimal_digit_expected_1125": "Očekávala se šestnáctková číslice.", + "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262": "Očekával se identifikátor. {0} je vyhrazené slovo na nejvyšší úrovni modulu.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Očekával se identifikátor. Ve striktním režimu je {0} rezervované slovo.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Očekával se identifikátor. Ve striktním režimu je {0} rezervované slovo. Definice tříd jsou automaticky ve striktním režimu.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Očekával se identifikátor. Ve striktním režimu je {0} rezervované slovo. Moduly jsou automaticky ve striktním režimu.", + "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Očekává se identifikátor. {0} je rezervované slovo, které se tady nedá použít.", + "Identifier_expected_1003": "Očekával se identifikátor.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Očekává se identifikátor. __esModule je při transformaci modulů ECMAScript rezervované jako označení exportu.", + "Identifier_or_string_literal_expected_1478": "Očekává se identifikátor nebo řetězcový literál.", + "Identifier_string_literal_or_number_literal_expected_1496": "Očekával se identifikátor, řetězcový literál nebo číselný literál.", + "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Pokud balíček ‚{0}‘ ve skutečnosti zveřejňuje tento modul, zvažte možnost poslat žádost o přijetí změn, aby se připojila adresa ‚https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}‘", + "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Pokud balíček {0} skutečně zpřístupňuje tento modul, zkuste přidat nový soubor deklarace (.d.ts), který obsahuje declare module {1};", + "Ignore_this_error_message_90019": "Ignorovat tuto chybovou zprávu", + "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924": "Ignoruje se tsconfig.js, zkompiluje zadané soubory s výchozími možnostmi kompilátoru.", + "Implement_all_inherited_abstract_classes_95040": "Implementovat všechny zděděné abstraktní třídy", + "Implement_all_unimplemented_interfaces_95032": "Implementovat všechna neimplementovaná rozhraní", + "Implement_inherited_abstract_class_90007": "Implementovat zděděnou abstraktní třídu", + "Implement_interface_0_90006": "Implementovat rozhraní {0}", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Klauzule implements exportované třídy {0} má nebo používá privátní název {1}.", + "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731": "Implicitní převod symbol na string za běhu neproběhne úspěšně. Zvažte možnost zabalit tento výraz do String(...).", + "Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_w_2866": "Import „{0}“ je v konfliktu s globální hodnotou použitou v tomto souboru, proto se musí deklarovat s importem „type-only“, pokud je povolena možnost „isolatedModules“.", + "Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_2865": "Import „{0}“ je v konfliktu s lokální hodnotou, proto se musí deklarovat s importem „type-only“, pokud je povolena možnost „isolatedModules“.", + "Import_0_from_1_90013": "Importovat {0} z: {1}", + "Import_assertion_values_must_be_string_literal_expressions_2837": "Hodnoty kontrolních výrazů importu musí být výrazy formou řetězcových literálů.", + "Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2836": "V příkazech, které se kompilují na volání CommonJS „require“, se nepovolují kontrolní výrazy importu.", + "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2821": "Kontrolní výrazy importu jsou podporovány pouze v případě, že je možnost --module nastavena na esnext, node18, nodenext nebo preserve.", + "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822": "Kontrolní výrazy importu se nedají použít s importy nebo exporty, které jsou jenom typ.", + "Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880": "Kontrolní výrazy importu byly nahrazeny atributy importu. Místo assert použijte with.", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Přiřazení importu nelze použít, pokud jsou cílem moduly ECMAScript. Zkuste místo toho použít import * as ns from \"mod\", import {a} from \"mod\", import d from \"mod\" nebo jiný formát modulu.", + "Import_attribute_values_must_be_string_literal_expressions_2858": "Hodnoty atributů importu musí být výrazy formou řetězcových literálů.", + "Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2856": "V příkazech, které se kompilují na volání CommonJS „require“, se nepovolují atributy importu.", + "Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2823": "Atributy importu jsou podporovány pouze v případě, že je možnost --module nastavena na esnext, node18, nodenext nebo preserve.", + "Import_attributes_cannot_be_used_with_type_only_imports_or_exports_2857": "Atributy importu se nedají použít s importy nebo exporty „type-only“.", + "Import_declaration_0_is_using_private_name_1_4000": "Deklarace importu {0} používá privátní název {1}.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Deklarace importu je v konfliktu s místní deklarací {0}.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Deklarace importu v oboru názvů nemůžou odkazovat na modul.", + "Import_emit_helpers_from_tslib_6139": "Importovat pomocné rutiny pro generování z tslib", + "Import_may_be_converted_to_a_default_import_80003": "Import se může převést na výchozí import.", + "Import_name_cannot_be_0_2438": "Název importu nemůže být {0}.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Deklarace importu nebo exportu v deklaraci ambientního modulu nemůže odkazovat na modul pomocí jeho relativního názvu.", + "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271": "Specifikátor importu {0} neexistuje v package.json scope na cestě {1}.", + "Imported_via_0_from_file_1_1393": "Importováno přes {0} ze souboru {1}", + "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395": "Importováno přes {0} ze souboru {1}, aby se provedl import importHelpers tak, jak je to zadáno v compilerOptions", + "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397": "Importováno přes {0} ze souboru {1}, aby se provedl import výrobních funkcí jsx a jsxs", + "Imported_via_0_from_file_1_with_packageId_2_1394": "Importováno přes {0} ze souboru {1} s packageId {2}", + "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396": "Importováno přes {0} ze souboru {1} s packageId {2}, aby se provedl import importHelpers tak, jak je to zadáno v compilerOptions", + "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398": "Importováno přes {0} ze souboru {1} s packageId {2}, aby se provedl import výrobních funkcí jsx a jsxs", + "Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_mod_1543": "Import souboru JSON do modulu ECMAScript vyžaduje atribut importu type: \"json\", pokud je možnost module nastavená na {0}.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importy nejsou povolené v rozšířeních modulů. Zvažte jejich přesunutí do uzavírajícího externího modulu.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Inicializátor členu v deklaracích ambientního výčtu musí být konstantní výraz.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Ve výčtu s víc deklaracemi může být jenom u jedné deklarace vynechaný inicializátor u prvního elementu výčtu.", + "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635": "Zahrnout seznam souborů. Tato možnost, na rozdíl od možnosti „include“, nepodporuje vzory glob.", + "Include_modules_imported_with_json_extension_6197": "Zahrnout moduly importované s příponou .json", + "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644": "Do souborů sourcemap v generovaném JavaScriptu zahrňte zdrojový kód.", + "Include_sourcemap_files_inside_the_emitted_JavaScript_6643": "Zahrňte do generovaného JavaScriptu soubory sourcemap.", + "Includes_imports_of_types_referenced_by_0_90054": "Zahrnuje importy typů, na které odkazuje {0}", + "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914": "Včetně --watch, -w začne sledovat aktuální projekt ohledně změn souboru. Po nastavení můžete konfigurovat režim sledování pomocí:", + "Incomplete_quantifier_Digit_expected_1505": "Neúplný kvantifikátor Očekává se číslice.", + "Index_signature_for_type_0_is_missing_in_type_1_2329": "Signatura indexu pro typ {0} chybí v typu {1}.", + "Index_signature_in_type_0_only_permits_reading_2542": "Signatura indexu v typu {0} povoluje jen čtení.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Jednotlivé deklarace ve sloučené deklaraci {0} musí být všechny exportované nebo všechny místní.", + "Infer_all_types_from_usage_95023": "Odvodit všechny typy z použití", + "Infer_function_return_type_95148": "Odvodit návratový typ funkce", + "Infer_parameter_types_from_usage_95012": "Odvodit typy parametrů z využití", + "Infer_this_type_of_0_from_usage_95080": "Vyvodit typ this pro {0} z použití", + "Infer_type_of_0_from_usage_95011": "Odvodit typ {0} z využití", + "Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations_9022": "Odvozování z výrazů tříd není podporováno s možností „--isolatedDeclarations“.", + "Initialize_property_0_in_the_constructor_90020": "Inicializovat vlastnost {0} v konstruktoru", + "Initialize_static_property_0_90021": "Inicializovat statickou vlastnost {0}", + "Initializer_for_property_0_2811": "Inicializátor vlastnosti „{0}“", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Inicializátor instance členské proměnné {0} nemůže odkazovat na identifikátor {1} deklarovaný v konstruktoru.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicializátory nejsou povolené v ambientních kontextech.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializuje projekt TypeScript a vytvoří soubor tsconfig.json.", + "Inline_variable_95184": "Vložená proměnná", + "Insert_command_line_options_and_files_from_a_file_6030": "Vložte parametry příkazového řádku a soubory ze souboru.", + "Install_0_95014": "Nainstalovat {0}", + "Install_all_missing_types_packages_95033": "Nainstalovat všechny chybějící balíčky typů", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Rozhraní {0} nemůže současně rozšiřovat typ {1} i {2}.", + "Interface_0_incorrectly_extends_interface_1_2430": "Rozhraní {0} nesprávně rozšiřuje rozhraní {1}.", + "Interface_declaration_cannot_have_implements_clause_1176": "Deklarace rozhraní nemůže obsahovat klauzuli implements.", + "Interface_must_be_given_a_name_1438": "Rozhraní musí mít název.", + "Interface_name_cannot_be_0_2427": "Název rozhraní nemůže být {0}.", + "Interop_Constraints_6252": "Omezení spolupráce", + "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243": "Interpretujte volitelné typy vlastností jako zapsané, místo přidání „undefined“.", + "Invalid_character_1127": "Neplatný znak", + "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "Neplatný specifikátor importu {0} nemá žádná možná řešení.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Neplatný název modulu v rozšíření. Modul {0} se převede na netypový modul v {1}, který se nedá rozšířit.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "V rozšíření je neplatný název modulu, modul {0} se nedá najít.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Neplatný volitelný řetěz z nového výrazu. Chtěli jste volat {0}()?", + "Invalid_reference_directive_syntax_1084": "Neplatná syntaxe direktivy reference", + "Invalid_syntax_in_decorator_1498": "Neplatná syntaxe v dekoratéru", + "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Neplatné použití „{0}“. Nelze jej použít uvnitř statického bloku třídy.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Neplatné použití {0}. Moduly jsou automaticky ve striktním režimu.", + "Invalid_use_of_0_in_strict_mode_1100": "Neplatné použití {0} ve striktním režimu", + "Invalid_value_for_ignoreDeprecations_5103": "Neplatná hodnota pro možnost „--ignoreDeprecations“", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Neplatná hodnota pro jsxFactory. {0} není platný identifikátor nebo kvalifikovaný název.", + "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035": "Neplatná hodnota pro jsxFragmentFactory. {0} není platný identifikátor nebo kvalifikovaný název.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Neplatná hodnota --reactNamespace. {0} není platný identifikátor.", + "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796": "Pravděpodobně chybí čárka, která by oddělila tyto dva výrazy šablony. Tvoří výraz šablony se značkami, který se nedá vyvolat.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Typ prvku {0} není platný prvek JSX.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Typ instance {0} není platný prvek JSX.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Návratový typ {0} není platný prvek JSX.", + "Its_type_0_is_not_a_valid_JSX_element_type_18053": "Typ „{0}“ není platný typ elementu JSX.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Značka JSDoc @{0} {1} neodpovídá klauzuli extends {2}.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Značka JSDoc @{0} není připojená k třídě.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc ... se může nacházet jen v posledním parametru signatury.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Značka JSDoc @param má název {0}, ale neexistuje žádný parametr s tímto názvem.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Značka JSDoc @param má název {0}, ale žádný parametr s tímto názvem neexistuje. Musí odpovídat hodnotě arguments, pokud má typ pole.", + "JSDoc_typedef_may_be_converted_to_TypeScript_type_80009": "JSDoc typedef se dá převést na typ TypeScript.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Značka JSDoc @typedef by měla mít poznámku k typu nebo by za ní měly následovat značky @property nebo @member.", + "JSDoc_typedefs_may_be_converted_to_TypeScript_types_80010": "JSDoc typedef lze převádět na typy TypeScript.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Typy JSDoc se můžou používat jenom v dokumentačních komentářích.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Typy JSDoc se můžou přesunout na typy TypeScript.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Atributy JSX musí mít přiřazený neprázdný výraz.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Element JSX {0} nemá odpovídající uzavírací značku.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Třída elementu JSX nepodporuje atributy, protože nemá vlastnost {0}.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Element JSX má implicitně typ any, protože neexistuje žádné rozhraní JSX.{0}.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Element JSX má implicitně typ any, protože neexistuje globální typ JSX.Element.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Typ elementu JSX {0} nemá žádnou signaturu konstrukce nebo volání.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Elementy JSX nemůžou mít víc atributů se stejným názvem.", + "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007": "Výrazy JSX nemůžou používat operátor čárky. Nechtěli jste napsat pole?", + "JSX_expressions_must_have_one_parent_element_2657": "Výrazy JSX musí mít jeden nadřazený element.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Fragment JSX nemá odpovídající uzavírací značku.", + "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633": "Výrazy přístupu k vlastnosti JSX nemůžou obsahovat názvy oborů názvů JSX.", + "JSX_spread_child_must_be_an_array_type_2609": "Podřízený objekt JSX spread musí být typu pole.", + "JavaScript_Support_6247": "Podpora JavaScriptu", + "Jump_target_cannot_cross_function_boundary_1107": "Cíl odkazu nemůže překročit hranici funkce.", + "KIND_6034": "DRUH", + "Keywords_cannot_contain_escape_characters_1260": "Klíčová slova nemůžou obsahovat řídicí znaky.", + "LOCATION_6037": "UMÍSTĚNÍ", + "Language_and_Environment_6254": "Jazyk a prostředí", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Levá strana operátoru čárky se nepoužívá a nemá žádné vedlejší účinky.", + "Library_0_specified_in_compilerOptions_1422": "Knihovna {0} zadaná v compilerOptions", + "Library_referenced_via_0_from_file_1_1405": "Knihovna odkazovaná přes {0} ze souboru {1}", + "Line_break_not_permitted_here_1142": "Na tomto místě se konec řádku nepovoluje.", + "Line_terminator_not_permitted_before_arrow_1200": "Konec řádku před šipkou se nepovoluje.", + "List_of_file_name_suffixes_to_search_when_resolving_a_module_6931": "Seznam přípon názvů souborů, které se mají vyhledat při překladu modulu", + "List_of_folders_to_include_type_definitions_from_6161": "Seznam složek, ze kterých se zahrnou definice typů", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Seznam kořenových složek, jejichž kombinovaný obsah představuje strukturu projektu za běhu", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Načítá se {0} z kořenového adresáře {1}, umístění kandidáta {2}.", + "Loading_module_0_from_node_modules_folder_target_file_types_Colon_1_6098": "Načítá se modul „{0}“ ze složky node_modules. Cílové typy souborů: {1}.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1_6095": "Načítá se modul jako soubor/složka, umístění kandidátského modulu: „{0}“, cílové typy souborů: {1}.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Národní prostředí musí mít tvar nebo . Třeba {0} nebo {1}.", + "Log_paths_used_during_the_moduleResolution_process_6706": "Cesty protokolu používané v procesu moduleResolution.", + "Longest_matching_prefix_for_0_is_1_6108": "Nejdelší odpovídající předpona pro {0} je {1}.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Hledání ve složce node_modules, počáteční umístění {0}", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Nastavit všechna volání metody super() prvním příkazem v jejich konstruktoru", + "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Vytvořte klíč jenom ze zpětných řetězců místo z řetězců, čísel nebo symbolů (možnost ze starší verze).", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Nastavit volání metody super() jako první příkaz v konstruktoru", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Typu mapovaného objektu má implicitně typ šablony any.", + "Mark_array_literal_as_const_90070": "Označit literál pole jako const", + "Matched_0_condition_1_6403": "Odpovídá {0} podmínce {1}", + "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Porovnává se ve výchozím nastavení se vzorem zahrnutí **/*.", + "Matched_by_include_pattern_0_in_1_1407": "Porovnáváno podle vzoru zahrnutí {0} v {1}", + "Member_0_implicitly_has_an_1_type_7008": "Člen {0} má implicitně typ {1}.", + "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Člen {0} má implicitně typ {1}, ale je možné, že lepší typ by se vyvodil z použití.", + "Merge_conflict_marker_encountered_1185": "Zjistila se značka konfliktu sloučení.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Spojená deklarace {0} nemůže obsahovat výchozí deklaraci exportu. Zvažte namísto toho možnost přidat samostatnou deklaraci export default {0}.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Metavlastnost {0} je povolená jenom v těle deklarace funkce, výrazu funkce nebo konstruktoru.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Metoda {0} nemůže mít implementaci, protože je označená jako abstraktní.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Metoda {0} z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Metoda {0} z exportovaného rozhraní má nebo používá privátní název {1}.", + "Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9008": "Metoda musí mít explicitní anotaci návratového typu s možností „--isolatedDeclarations“.", + "Method_not_implemented_95158": "Metoda není implementovaná.", + "Modifiers_cannot_appear_here_1184": "Tady nejde použít modifikátory.", + "Module_0_can_only_be_default_imported_using_the_1_flag_1259": "Modul {0} se dá importovat podle výchozího nastavení jen pomocí příznaku {1}.", + "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471": "Modul {0} nejde importovat pomocí této konstrukce. Specifikátor se převede jenom na modul ES, který se nedá importovat s příkazem require. Místo toho použijte import ECMAScript.", + "Module_0_declares_1_locally_but_it_is_exported_as_2_2460": "Modul {0} deklaruje {1} místně, ale exportuje se jako {2}.", + "Module_0_declares_1_locally_but_it_is_not_exported_2459": "Modul {0} deklaruje {1} místně, ale neexportuje se.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340": "Modul {0} neodkazuje na typ, ale používá se tady jako typ. Měli jste na mysli typeof import('{0}')?", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Modul {0} neodkazuje na hodnotu, ale používá se tady jako hodnota.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Modul {0} už exportoval člena s názvem {1}. Zvažte možnost vyřešení nejednoznačnosti explicitním opakováním exportu.", + "Module_0_has_no_default_export_1192": "Modul {0} nemá žádný výchozí export.", + "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613": "Modul {0} nemá žádný výchozí export. Nechtěli jste místo toho použít import { {1} } from {0}?", + "Module_0_has_no_exported_member_1_2305": "V modulu {0} není žádný exportovaný člen {1}.", + "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614": "Modul {0} nemá žádný exportovaný člen {1}. Nechtěli jste místo toho použít import { {1} } from {0}?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Modul {0} je skrytý místní deklarací se stejným názvem.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Modul {0} používá export = a nedá se použít s možností export *.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Modul {0} se převedl jako lokálně deklarovaný ambientní modul v souboru {1}.", + "Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set_6263": "Modul „{0}“ byl přeložen na „{1}“, ale není nastavena možnost „--allowArbitraryExtensions“.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Modul {0} se přeložil na {1}, není ale nastavená možnost --jsx.", + "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042": "Modul {0} se přeložil na {1}, ale nepoužívá se --resolveJsonModule.", + "Module_declaration_names_may_only_use_or_quoted_strings_1443": "Názvy deklarací modulů můžou používat jenom řetězce v jednoduchých nebo dvojitých uvozovkách.", + "Module_name_0_matched_pattern_1_6092": "Název modulu {0}, odpovídající vzor {1}", + "Module_name_0_was_not_resolved_6090": "======== Název modulu {0} nebyl přeložen. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Název modulu {0} byl úspěšně přeložen na {1}. ========", + "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218": "======== Název modulu {0} se úspěšně přeložil na {1} s ID balíčku {2}. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Druh překladu modulu nebyl určen, použije se {0}.", + "Module_resolution_using_rootDirs_has_failed_6111": "Překlad modulu pomocí rootDirs se nepovedl.", + "Modules_6244": "Moduly", + "Move_labeled_tuple_element_modifiers_to_labels_95117": "Přesunout modifikátory elementu popsané řazené kolekce členů na popisky", + "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036": "Přesuňte výraz ve výchozím exportu do proměnné a přidejte k němu anotaci typu.", + "Move_to_a_new_file_95049": "Přesunout do nového souboru", + "Move_to_file_95178": "Přesunout do souboru", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Více po sobě jdoucích číselných oddělovačů se nepovoluje.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Víc implementací konstruktoru se nepovoluje.", + "NEWLINE_6061": "NOVÝ ŘÁDEK", + "Name_is_not_valid_95136": "Název není platný.", + "Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later_1503": "Pojmenované zachytávací skupiny jsou k dispozici jen při cílení na „ES2018“ nebo novější.", + "Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other_1515": "Pojmenované zachytávací skupiny se stejným názvem se musí navzájem vylučovat.", + "Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0_1544": "Pojmenované importy ze souboru JSON do modulu ECMAScript nejsou povolené, když je možnost module nastavená na {0}.", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Pojmenovaná vlastnost {0} není u typu {1} stejná jako u typu {2}.", + "Namespace_0_has_no_exported_member_1_2694": "Obor názvů {0} nemá žádný exportovaný člen {1}.", + "Namespace_must_be_given_a_name_1437": "Obor názvů musí mít název.", + "Namespace_name_cannot_be_0_2819": "Název oboru názvů nemůže být „{0}“.", + "Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to__1280": "Pokud je povolena možnost „{0}“, nejsou v souborech globálních skriptů povoleny obory názvů. Pokud tento soubor nemá být globálním skriptem, nastavte možnost „moduleDetection“ na hodnotu „force“ nebo přidejte prázdný příkaz „export {}“.", + "Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters_1433": "U parametrů „this“ nelze použít dekoratéry ani modifikátory.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Žádný základní konstruktor nemá zadaný počet argumentů typu.", + "No_constituent_of_type_0_is_callable_2755": "Žádný konstituent typu {0} se nedá zavolat.", + "No_constituent_of_type_0_is_constructable_2759": "Žádný konstituent typu {0} se nedá vytvořit.", + "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054": "V typu {1} se nenašla žádná signatura indexu s typem parametru {0}.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "V konfiguračním souboru {0} se nenašly žádné vstupy. Pro zahrnutí jsou zadané tyto cesty: {1} a pro vyloučení tyto cesty: {2}.", + "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608": "Funkce už není podporovaná. Ve starších verzích sloužila k ručnímu nastavení kódování textu při čtení souborů.", + "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575": "Žádné přetížení neočekává tento počet argumentů: {0}. Existují ale přetížení, která očekávají buď {1}, nebo tento počet argumentů: {2}", + "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743": "Žádné přetížení neočekává tento počet argumentů typů: {0}. Existují ale přetížení, která očekávají buď {1}, nebo tento počet argumentů typů: {2}", + "No_overload_matches_this_call_2769": "Žádné přetížení neodpovídá tomuto volání.", + "No_type_could_be_extracted_from_this_type_node_95134": "Z tohoto uzlu typů nešlo extrahovat žádný typ.", + "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004": "V oboru pro sdruženou vlastnost {0} neexistuje žádná hodnota. Buď nějakou deklarujte, nebo poskytněte inicializátor.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Neabstraktní třída „{0}“ neimplementuje zděděného abstraktního člena {1} ze třídy „{2}“.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_2654": "V neabstraktní třídě „{0}“ chybí implementace pro následující členy „{1}“: {2}.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more_2655": "V neabstraktní třídě {0} chybí implementace pro následující členy „{1}“: {2} a {3} další(ch).", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Výraz neabstraktní třídy neimplementuje zděděný abstraktní člen {0} z třídy {1}.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_2656": "Ve výrazu neabstraktní třídy chybí implementace pro následující členy „{0}“: {1}.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and__2650": "Ve výrazu neabstraktní třídy chybí implementace pro následující členy „{0}“: {1} a {2} další(ch).", + "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013": "Kontrolní výrazy jiné než null se dají používat jen v typescriptových souborech.", + "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090": "Nerelativní cesty nejsou povolené, pokud není nastavená hodnota baseUrl. Nezapomněli jste na úvodní znak „./“?", + "Non_simple_parameter_declared_here_1348": "Deklaroval se tady parametr, který není jednoduchý.", + "Not_all_code_paths_return_a_value_7030": "Ne všechny cesty kódu vracejí hodnotu.", + "Not_all_constituents_of_type_0_are_callable_2756": "Ne všichni konstituenti typu {0} se dají zavolat.", + "Not_all_constituents_of_type_0_are_constructable_2760": "Ne všichni konstituenti typu {0} se dají vytvořit.", + "Numbers_out_of_order_in_quantifier_1506": "Čísla ve kvantifikátoru jsou mimo pořadí.", + "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008": "Číselné literály s absolutními hodnotami, které se rovnají hodnotě 2^53 nebo větší, se nedají reprezentovat přesně jako celá čísla, protože jsou příliš velké.", + "Numeric_separators_are_not_allowed_here_6188": "Číselné oddělovače tady nejsou povolené.", + "Object_is_of_type_unknown_2571": "Objekt je typu Neznámý.", + "Object_is_possibly_null_2531": "Objekt je pravděpodobně null.", + "Object_is_possibly_null_or_undefined_2533": "Objekt je pravděpodobně null nebo undefined.", + "Object_is_possibly_undefined_2532": "Objekt je pravděpodobně undefined.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Literál objektu může specifikovat jenom známé vlastnosti a {0} v typu {1} neexistuje.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Literál objektu může určovat jenom známé vlastnosti, ale {0} v typu {1} neexistuje. Chtěli jste zapsat {2}?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Vlastnost {0} literálu objektu má implicitně typ {1}.", + "Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations_9016": "Objekty, které obsahují sdružené vlastnosti, nelze odvodit pomocí možnosti „--isolatedDeclarations“.", + "Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations_9015": "Objekty, které obsahují přiřazení rozprostření, se nedají odvodit pomocí možnosti „--isolatedDeclarations“.", + "Octal_digit_expected_1178": "Očekává se osmičková číslice.", + "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536": "Osmičkové řídicí sekvence a zpětné odkazy nejsou ve třídě znaků povoleny. Pokud to bylo zamýšleno jako řídicí sekvence, použijte místo toho syntaxi „{0}“.", + "Octal_escape_sequences_are_not_allowed_Use_the_syntax_0_1487": "Osmičkové řídicí sekvence nejsou povoleny. Použijte syntaxi „{0}“.", + "Octal_literals_are_not_allowed_Use_the_syntax_0_1121": "Osmičkové literály nejsou povoleny. Použijte syntaxi „{0}“.", + "One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value_4126": "Jedna hodnota z „{0}.{1}“ je řetězec „{2}“ a druhá hodnota se považuje za neznámou číselnou hodnotu.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "V příkazu for...in se povoluje deklarovat jenom jednu proměnnou.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "V příkazu for...of se povoluje deklarovat jenom jednu proměnnou.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Klíčovým slovem new se dá volat jenom funkce void.", + "Only_ambient_modules_can_use_quoted_names_1035": "Názvy v uvozovkách můžou mít jenom ambientní moduly.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Spolu s --{0} se podporují jenom moduly amd a system.", + "Only_const_arrays_can_be_inferred_with_isolatedDeclarations_9017": "Pomocí možnosti „--isolatedDeclarations“ lze odvodit pouze pole const.", + "Only_emit_d_ts_declaration_files_6014": "Bude vydávat jen soubory deklarací .d.ts.", + "Only_output_d_ts_files_and_not_JavaScript_files_6623": "Zahrňte do výstupu jenom soubory d.ts, nikoli soubory JavaScriptu.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Prostřednictvím klíčového slova super jsou přístupné jenom veřejné a chráněné metody základní třídy.", + "Operator_0_cannot_be_applied_to_type_1_2736": "Operátor {0} se nedá použít na typ {1}.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Operátor {0} nejde použít u typů {1} a {2}.", + "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519": "V rámci třídy znaků nelze kombinovat operátory. Místo toho je zabalte do vnořené třídy.", + "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619": "Při úpravách vyloučit projekt z kontroly odkazů ve více projektech.", + "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108": "Možnost „{0}={1}“ byla odebrána. Odeberte ji prosím z konfigurace.", + "Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDepr_5107": "Možnost „{0}={1}“ je zastaralá a v jazyce TypeScript {2} přestane fungovat. Tuto chybu můžete potlačit zadáním compilerOption '\"ignoreDeprecations\": \"{3}\"'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "Možnost {0} jde zadat jenom v souboru tsconfig.json nebo nastavit na příkazovém řádku na hodnotu false nebo null.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "Možnost {0} jde zadat jenom v souboru tsconfig.json nebo nastavit na příkazovém řádku na hodnotu null.", + "Option_0_can_only_be_specified_on_command_line_6266": "Možnost „{0}“ lze zadat pouze na příkazovém řádku.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Možnost {0} jde použít jenom při zadání možnosti --inlineSourceMap nebo možnosti --sourceMap.", + "Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler_5098": "Možnost „{0}“ se dá použít jenom v případě, že je možnost „moduleResolution“ nastavená na „node16“, „nodenext“ nebo „bundler“.", + "Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later_5095": "Možnost „{0}“ se dá použít jenom v případě, že je možnost „modul“ nastavená na „preserve“ nebo na „es2015“ a novější.", + "Option_0_cannot_be_specified_when_option_jsx_is_1_5089": "Když je možnost jsx nastavená na {1}, možnost {0} se nedá zadat.", + "Option_0_cannot_be_specified_with_option_1_5053": "Možnosti {0} a {1} nejde zadat zároveň.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Možnost {0} nejde zadat bez možnosti {1}.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Možnost {0} nejde zadat bez možnosti {1} nebo {2}.", + "Option_0_has_been_removed_Please_remove_it_from_your_configuration_5102": "Možnost „{0}“ byla odebrána. Odeberte ji prosím z konfigurace.", + "Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprec_5101": "Možnost „{0}“ je zastaralá a v jazyce TypeScript {1} přestane fungovat. Tuto chybu můžete potlačit zadáním compilerOption '\"ignoreDeprecations\": \"{2}\"'.", + "Option_0_is_redundant_and_cannot_be_specified_with_option_1_5104": "Možnost „{0}“ je redundantní a nelze ji zadat s možností „{1}“.", + "Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set_5096": "Možnost „allowImportingTsExtensions“ se dá použít jenom v případě, že je nastavená možnost „noEmit“ nebo „emitDeclarationOnly“.", + "Option_build_must_be_the_first_command_line_argument_6369": "Možnost --build musí být prvním argumentem příkazového řádku.", + "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074": "Možnost ‚--incremental‘ se dá zadat jen pomocí tsconfig, při generování do jednoho souboru nebo když se zadá možnost ‚--tsBuildInfoFile‘.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Možnost isolatedModules jde použít jenom v případě, že je poskytnutá možnost --module nebo že možnost target je ES2015 nebo vyšší verze.", + "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109": "Když je možnost „module“ nastavená na „{0}“, možnost „moduleResolution“ musí být nastavená na „{1}“ (nebo musí zůstat nezadaná).", + "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110": "Když je možnost „moduleResolution“ nastavená na „{1}“, možnost „module“ musí být nastavená na „{0}“.", + "Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled_5091": "Když je povolená možnost „{0}“, možnost „preserveConstEnums“ se nedá zakázat.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Možnost project se na příkazovém řádku nedá kombinovat se zdrojovým souborem.", + "Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic_5070": "Možnost „--resolveJsonModule“ se nedá zadat, pokud je možnost „moduleResolution“ nastavená na hodnotu „classic“.", + "Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd_5071": "Možnost „--resolveJsonModule“ se nedá zadat, pokud je možnost „module“ nastavená na „none“, „system“ nebo „umd“.", + "Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System_5105": "Možnost „verbatimModuleSyntax“ nejde použít, pokud je možnost „module“ nastavená na „UMD“, „AMD“ nebo „System“.", + "Options_0_and_1_cannot_be_combined_6370": "Možnosti {0} a {1} nejde kombinovat.", + "Options_Colon_6027": "Možnosti:", + "Output_Formatting_6256": "Formátování výstupu", + "Output_compiler_performance_information_after_building_6615": "Po sestavení generovat informace o výkonu kompilátoru.", + "Output_directory_for_generated_declaration_files_6166": "Výstupní adresář pro vygenerované soubory deklarace", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Výstupní soubor {0} se nesestavil ze zdrojového souboru {1}.", + "Output_from_referenced_project_0_included_because_1_specified_1411": "Výstup z odkazovaného projektu {0}, který se zahrnul, protože je zadané {1}", + "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412": "Výstup z odkazovaného projektu {0}, který se zahrnul, protože možnost --module se nastavila na none", + "Output_more_detailed_compiler_performance_information_after_building_6632": "Do výstupu po sestavení zahrňte podrobnější informace o výkonu kompilátoru.", + "Overload_0_of_1_2_gave_the_following_error_2772": "Přetížení {0} z {1}, {2}, vrátilo následující chybu.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Signatury přetížení musí být všechny abstraktní nebo neabstraktní.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Signatury přetížení musí být všechny ambientní nebo neambientní.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Signatury přetížení musí být všechny exportované nebo neexportované.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Signatury přetížení musí být všechny nepovinné nebo povinné.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Signatury přetížení musí být všechny veřejné, privátní nebo chráněné.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Parametr {0} nemůže odkazovat na identifikátor {1} deklarovaný za ním.", + "Parameter_0_cannot_reference_itself_2372": "Parametr {0} nemůže odkazovat sám na sebe.", + "Parameter_0_implicitly_has_an_1_type_7006": "Parametr {0} má implicitně typ {1}.", + "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Parametr {0} má implicitně typ {1}, ale je možné, že lepší typ by se vyvodil z použití.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Parametr {0} není na stejné pozici jako parametr {1}.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108": "Parametr {0} přístupového objektu má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107": "Parametr {0} přístupového objektu má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106": "Parametr {0} přístupového objektu má nebo používá privátní název {1}.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Parametr {0} signatury volání z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Parametr {0} signatury volání z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Parametr {0} konstruktoru z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Parametr {0} konstruktoru z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Parametr {0} konstruktoru z exportované třídy má nebo používá privátní název {1}.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Parametr {0} signatury konstruktoru z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Parametr {0} signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Parametr {0} exportované funkce má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Parametr {0} exportované funkce má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Parametr {0} exportované funkce má nebo používá privátní název {1}.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Parametr {0} signatury indexu z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Parametr {0} signatury indexu z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Parametr {0} metody z exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Parametr {0} metody z exportovaného rozhraní má nebo používá privátní název {1}.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Parametr {0} veřejné metody z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Parametr {0} veřejné metody z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Parametr {0} veřejné metody z exportované třídy má nebo používá privátní název {1}.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Parametr {0} veřejné statické metody z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Parametr {0} veřejné statické metody z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Parametr {0} veřejné statické metody z exportované třídy má nebo používá privátní název {1}.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Parametr nemůže obsahovat otazník a inicializátor.", + "Parameter_declaration_expected_1138": "Očekává se deklarace parametru.", + "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051": "Parametr má název, ale žádný typ. Měli jste na mysli {0}: {1}?", + "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012": "Modifikátory parametrů se dají používat jen v typescriptových souborech.", + "Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9011": "Parametr musí mít explicitní anotaci typu s možností „--isolatedDeclarations“.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Typ parametru veřejné metody setter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Typ parametru veřejné metody setter {0} z exportované třídy má nebo používá privátní název {1}.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Typ parametru veřejné statické metody setter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Typ parametru veřejné statické metody setter {0} z exportované třídy má nebo používá privátní název {1}.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Parsovat ve striktním režimu a generovat striktní používání pro každý zdrojový soubor", + "Part_of_files_list_in_tsconfig_json_1409": "Součást seznamu files v souboru tsconfig.json", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Vzor {0} může obsahovat nanejvýš jeden znak * (hvězdička).", + "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386": "Časování výkonu pro --diagnostics nebo --extendedDiagnostics nejsou v této relaci k dispozici. Nepovedlo se najít nativní implementace rozhraní Web Performance API.", + "Platform_specific_6912": "Specifická pro platformu", + "Prefix_0_with_an_underscore_90025": "Předpona {0} s podtržítkem", + "Prefix_all_incorrect_property_declarations_with_declare_95095": "Před všechny nesprávné deklarace vlastností přidejte declare.", + "Prefix_all_unused_declarations_with_where_possible_95025": "Přidat příponu _ ke všem nepoužívaným deklaracím tam, kde je to možné", + "Prefix_with_declare_95094": "Přidat předponu declare", + "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449": "Zachovejte nepoužívané importované hodnoty ve výstupu JavaScriptu, který by se jinak odebral.", + "Print_all_of_the_files_read_during_the_compilation_6653": "Vytiskněte si všechny soubory přečtené při kompilaci.", + "Print_files_read_during_the_compilation_including_why_it_was_included_6631": "Vytiskněte si soubory přečtené při kompilaci, včetně důvodu jejich zahrnutí.", + "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505": "Umožňuje vypsat názvy souborů a důvod, proč jsou součástí kompilace.", + "Print_names_of_files_part_of_the_compilation_6155": "Část kompilace, při které se vypisují názvy souborů", + "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "Vypsat názvy souborů, které jsou součástí kompilace, a pak ukončit zpracovávání", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Část kompilace, při které se vypisují názvy generovaných souborů", + "Print_the_compiler_s_version_6019": "Vytisknout verzi kompilátoru", + "Print_the_final_configuration_instead_of_building_1350": "Místo sestavení vypsat konečnou konfiguraci", + "Print_the_names_of_emitted_files_after_a_compilation_6652": "Po kompilaci vytiskněte názvy generovaných souborů.", + "Print_this_message_6017": "Vytisknout tuto zprávu", + "Private_accessor_was_defined_without_a_getter_2806": "Privátní přístupový objekt se definoval bez metody getter.", + "Private_field_0_must_be_declared_in_an_enclosing_class_1111": "Privátní pole „{0}“ musí být deklarované v nadřazené třídě.", + "Private_identifiers_are_not_allowed_in_variable_declarations_18029": "Privátní identifikátory se v deklaracích proměnných nepovolují.", + "Private_identifiers_are_not_allowed_outside_class_bodies_18016": "Privátní identifikátory se mimo těla tříd nepovolují.", + "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451": "Privátní identifikátory jsou povolené jenom v tělech třídy a smí se používat jenom jako součást deklarace člena třídy nebo přístupu k vlastnosti, případně na levé straně výrazu in.", + "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028": "Privátní identifikátory jsou dostupné jen při cílení na ECMAScript 2015 a novější.", + "Private_identifiers_cannot_be_used_as_parameters_18009": "Privátní identifikátory se nedají použít jako parametry.", + "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105": "K privátnímu nebo chráněnému členu {0} se nedá přistupovat v parametru typu.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Project '{0}' can't be built because its dependency '{1}' has errors", + "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Project '{0}' can't be built because its dependency '{1}' was not built", + "Project_0_is_being_forcibly_rebuilt_6388": "Projekt {0} se nuceně vytváří znovu.", + "Project_0_is_out_of_date_because_1_6420": "Projekt „{0}“ je zastaralý, protože {1}.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_6412": "Projekt „{0}“ je zastaralý, protože soubor buildinfo „{1}“ označuje, že soubor „{2}“ byl kořenovým souborem kompilace, ale už není.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419": "Projekt {0} je zastaralý, protože soubor buildinfo „{1}“ označuje, že program musí hlásit chyby.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "{0} projektu je zastaralý, protože soubor buildinfo {1} indikuje, že se některé změny nevygenerovaly.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions_6406": "Projekt „{0}“ je zastaralý, protože soubor buildinfo „{1}“ označuje, že došlo ke změně v možnosti „compilerOptions“.", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Projekt {0} je zastaralý, protože jeho závislost {1} je zastaralá.", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Projekt {0} je zastaralý, protože výstup {1} je starší než vstup {2}.", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Projekt {0} je zastaralý, protože výstupní soubor {1} neexistuje.", + "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Projekt {0} je zastaralý, protože jeho výstup se vygeneroval pomocí verze {1}, která se liší od aktuální verze {2}.", + "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401": "Projekt {0} je zastaralý, protože při čtení souboru {1} došlo k chybě.", + "Project_0_is_up_to_date_6361": "Projekt {0} je aktuální.", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Projekt {0} je aktuální, protože nejnovější vstup {1} je starší než výstup {2}.", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Projekt {0} je aktuální, ale musí aktualizovat časová razítka výstupních souborů, které jsou starší než vstupní soubory.", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Projekt {0} je aktualizovaný soubory .d.ts z jeho závislostí.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odkazy projektu nemůžou tvořit cyklický graf. Zjistil se cyklus: {0}", + "Projects_6255": "Projekty", + "Projects_in_this_build_Colon_0_6355": "Projekty v tomto sestavení: {0}", + "Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher_18045": "Vlastnosti s modifikátorem accessor jsou k dispozici jen při cílení na ECMAScript 2015 a vyšší.", + "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267": "Vlastnost {0} nemůže mít inicializátor, protože je označená jako abstraktní.", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "Vlastnost {0} pochází ze signatury indexu, proto je zapotřebí k ní přistupovat pomocí ['{0}'].", + "Property_0_does_not_exist_on_type_1_2339": "Vlastnost {0} v typu {1} neexistuje.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Vlastnost {0} v typu {1} neexistuje. Měli jste na mysli {2}?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "Vlastnost {0} v typu {1} neexistuje. Chtěli jste místo toho přistoupit ke statickému členu {2}?", + "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "Vlastnost ‚{0}‘ neexistuje u typu ‚{1}‘. Potřebujete změnit cílovou knihovnu? Zkuste změnit možnost kompilátoru ‚lib‘ na ‚{2}‘ nebo novější.", + "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812": "Vlastnost „{0}“ pro typ „{1}“ neexistuje. Zkuste změnit možnost kompilátoru „lib“, aby zahrnovala „dom“.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817": "Vlastnost „{0}“ nemá žádný inicializátor a není jednoznačně přiřazena ve statickém bloku třídy.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Vlastnost {0} nemá žádný inicializátor a není jednoznačně přiřazena v konstruktoru.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt get nemá anotaci návratového typu.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt set nemá anotaci parametrového typu.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048": "Vlastnost {0} má implicitně typ any, ale je možné, že lepší typ pro jeho přístupový objekt get by se vyvodil z použití.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049": "Vlastnost {0} má implicitně typ any, ale je možné, že lepší typ pro jeho přístupový objekt set by se vyvodil z použití.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Vlastnost {0} v typu {1} nejde přiřadit ke stejné vlastnosti v základním typu {2}.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Vlastnost {0} v typu {1} nejde přiřadit typu {2}.", + "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "Vlastnost {0} v typu {1} odkazuje na jiného člena, ke kterému není možné získat přístup z typu {2}.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Deklaruje se vlastnost {0}, ale její hodnota se vůbec nečte.", + "Property_0_is_incompatible_with_index_signature_2530": "Vlastnost {0} není kompatibilní se signaturou indexu.", + "Property_0_is_missing_in_type_1_2324": "Vlastnost {0} v typu {1} chybí.", + "Property_0_is_missing_in_type_1_but_required_in_type_2_2741": "Vlastnost {0} chybí v typu {1}, ale vyžaduje se v typu {2}.", + "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013": "Vlastnost {0} není přístupná mimo třídu {1}, protože má privátní identifikátor.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Vlastnost {0} je v typu {1} nepovinná, ale vyžaduje se v typu {2}.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Vlastnost {0} je privátní a dostupná jenom ve třídě {1}.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Vlastnost {0} je v typu {1} privátní, ale v typu {2} ne.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446": "Vlastnost {0} je chráněná a dá se k ní přistupovat jen přes instanci třídy {1}. Toto je instance třídy {2}.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Vlastnost {0} je chráněná a je dostupná jenom ve třídě {1} a jejích podtřídách.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Vlastnost {0} je chráněná, ale typ {1} není třída odvozená od {2}.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Vlastnost {0} je v typu {1} chráněná, ale v typu {2} veřejná.", + "Property_0_is_used_before_being_assigned_2565": "Vlastnost {0} je použitá před přiřazením.", + "Property_0_is_used_before_its_initialization_2729": "Vlastnost {0} se používá dříve, než se inicializuje.", + "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568": "Zdá se, že vlastnost {0} v typu {1} neexistuje. Měli jste na mysli {2}?", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Vlastnost {0} rozšířeného atributu JSX nejde přiřadit cílové vlastnosti.", + "Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected_4094": "Vlastnost „{0}“ exportovaného anonymního typu třídy nesmí být privátní ani chráněná.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Vlastnost {0} exportovaného rozhraní má nebo používá název {1} z privátního modulu {2}.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Vlastnost {0} exportovaného rozhraní má nebo používá privátní název {1}.", + "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411": "Vlastnost {0} typu {1} se nedá přiřadit k {2} typu indexu {3}.", + "Property_0_was_also_declared_here_2733": "Vlastnost {0} se deklarovala i tady.", + "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612": "Vlastnost {0} přepíše základní vlastnost v {1}. Pokud je to záměr, přidejte inicializátor. Jinak přidejte modifikátor declare nebo odeberte redundantní deklaraci.", + "Property_assignment_expected_1136": "Očekává se přiřazení vlastnosti.", + "Property_destructuring_pattern_expected_1180": "Očekává se vzor destruktoru vlastnosti.", + "Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9012": "Vlastnost musí mít explicitní anotaci typu s možností „--isolatedDeclarations“.", + "Property_or_signature_expected_1131": "Očekává se vlastnost nebo podpis.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Hodnota vlastnosti může být jenom řetězcový literál, číselný literál, true, false, null, literál objektu nebo literál pole.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_6179": "Při cílení na „ES5“ poskytněte plnou podporu iterovatelných proměnných v příkazu „for-of“, rozšíření a destrukturování.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Veřejná metoda {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Veřejná metoda {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Veřejná metoda {0} z exportované třídy má nebo používá privátní název {1}.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Veřejná vlastnost {0} exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Veřejná vlastnost {0} exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Veřejná vlastnost {0} exportované třídy má nebo používá privátní název {1}.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Veřejná statická metoda {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Veřejná statická metoda {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Veřejná statická metoda {0} z exportované třídy má nebo používá privátní název {1}.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Veřejná statická vlastnost {0} exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Veřejná statická vlastnost {0} exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Veřejná statická vlastnost {0} exportované třídy má nebo používá privátní název {1}.", + "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032": "Kvalifikovaný název {0} se nepovoluje bez @param {object} {1} na začátku.", + "Raise_an_error_when_a_function_parameter_isn_t_read_6676": "Když se parametr funkce nepřečte, nahlaste chybu.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Vyvolat chybu u výrazů a deklarací s implikovaným typem any", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Vyvolá chybu u výrazů this s implikovaným typem any.", + "Range_out_of_order_in_character_class_1517": "Rozsah ve třídě znaků je mimo pořadí.", + "Re_exporting_a_type_when_0_is_enabled_requires_using_export_type_1205": "Při opětovném exportu typu s povolenou možností „{0}“ je nutné použít možnost „export type“.", + "React_components_cannot_include_JSX_namespace_names_2639": "Komponenty React nemůžou obsahovat názvy oborů názvů JSX.", + "Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře", + "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617": "Snižte počet projektů, které TypeScript načítá automaticky.", + "Referenced_project_0_may_not_disable_emit_6310": "Odkazovaný projekt {0} nemůže zakazovat generování.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Odkazovaný projekt {0} musí mít nastavení \"composite\": true.", + "Referenced_via_0_from_file_1_1400": "Odkazováno přes {0} ze souboru {1}", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2834": "Relativní cesty importu vyžadují explicitní přípony souborů v importech ECMAScriptu, když „--moduleResolution“ je „node16“ nebo „nodenext“. Zvažte přidání přípony do cesty importu.", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2835": "Relativní cesty importu vyžadují explicitní přípony souborů v importech ECMAScriptu, když „--moduleResolution“ je „node16“ nebo „nodenext“. Měli jste na mysli „{0}“?", + "Remove_a_list_of_directories_from_the_watch_process_6628": "Odeberte z procesu sledování seznam adresářů.", + "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629": "Ze zpracování režimu sledování odeberte seznam souborů.", + "Remove_all_unnecessary_override_modifiers_95163": "Odebrat všechny nepotřebné modifikátory override", + "Remove_all_unnecessary_uses_of_await_95087": "Odebrat všechna nepotřebná použití výrazu await", + "Remove_all_unreachable_code_95051": "Odebrat veškerý nedosažitelný kód", + "Remove_all_unused_labels_95054": "Odebrat všechny nepoužívané popisky", + "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115": "Odeberte složené závorky ze všech těl funkcí šipek, u kterých dochází k problémům.", + "Remove_braces_from_arrow_function_95060": "Odebrat složené závorky z funkce šipky", + "Remove_braces_from_arrow_function_body_95112": "Odebrat složené závorky z těla funkce šipky", + "Remove_import_from_0_90005": "Odebrat import z {0}", + "Remove_override_modifier_95161": "Odebrat modifikátor override", + "Remove_parentheses_95126": "Odebrat závorky", + "Remove_template_tag_90011": "Odebrat značku šablonu", + "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618": "Odeberte limit 20 MB pro celkovou velikost zdrojového kódu souborů JavaScriptu na jazykovém serveru TypeScriptu.", + "Remove_type_from_import_declaration_from_0_90055": "Odebrat „type“ z deklarace importu z „{0}“", + "Remove_type_from_import_of_0_from_1_90056": "Odebrat „type“ z importu {0} z „{1}“", + "Remove_type_parameters_90012": "Odebrat parametry typů", + "Remove_unnecessary_await_95086": "Odebrat nepotřebné výrazy await", + "Remove_unreachable_code_95050": "Odebrat nedosažitelný kód", + "Remove_unused_declaration_for_Colon_0_90004": "Odebrat nepoužívané deklarace pro {0}", + "Remove_unused_declarations_for_Colon_0_90041": "Odebrat nepoužívané deklarace pro {0}", + "Remove_unused_destructuring_declaration_90039": "Odebrat nepoužívané destrukční deklarace", + "Remove_unused_label_95053": "Odebrat nepoužitý popisek", + "Remove_variable_statement_90010": "Odebrat příkaz proměnné", + "Rename_param_tag_name_0_to_1_95173": "Přejmenovat značku @param {0} na {1}", + "Replace_0_with_Promise_1_90036": "Místo {0} použijte Promise<{1}>", + "Replace_all_unused_infer_with_unknown_90031": "Nahradit všechny nepoužívané příkazy infer za unknown", + "Replace_import_with_0_95015": "Nahradí import použitím: {0}.", + "Replace_infer_0_with_unknown_90030": "Nahradit infer {0} za unknown", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Oznámí se chyba, když některé cesty kódu ve funkci nevracejí hodnotu.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Oznámí se chyby v případech fallthrough v příkazu switch.", + "Report_errors_in_js_files_8019": "Ohlásit chyby v souborech .js", + "Report_errors_on_unused_locals_6134": "Umožňuje nahlásit chyby u nevyužitých místních hodnot.", + "Report_errors_on_unused_parameters_6135": "Umožňuje nahlásit chyby u nevyužitých parametrů.", + "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719": "Vyžadujte u exportů dostatečnou anotaci, aby ostatní nástroje mohly triviálně generovat soubory deklarací.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717": "Vyžadovat, aby nedeklarované vlastnosti ze signatur indexů používaly přístupy k elementům", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Požadované parametry typu nemůžou být až za volitelnými parametry typu.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Překlad pro modul {0} se našel v mezipaměti umístění {1}.", + "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "Překlad pro direktivu odkazu na typ {0} se našel v mezipaměti umístění {1}.", + "Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_i_6277": "Překlad nerelativního názvu selhal; zkoušíme to se zakázanými moderními funkcemi překladu Node, abychom zjistili, jestli není potřeba aktualizovat konfiguraci knihovny npm.", + "Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_ne_6279": "Překlad nerelativního názvu selhal. Zkoušíme to s možností „--moduleResolution bundler“, abychom zjistili, jestli projekt nepotřebuje aktualizaci konfigurace.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "keyof překládejte jen na názvy vlastností s hodnotami typu string (ne čísla ani symboly).", + "Resolved_under_condition_0_6414": "Vyřešeno za podmínky „{0}“.", + "Resolving_in_0_mode_with_conditions_1_6402": "Řešení v režimu {0} s podmínkami {1}.", + "Resolving_module_0_from_1_6086": "======== Překládá se modul {0} z {1}. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Překládá se název modulu {0} relativní k základní adrese URL {1}–{2}.", + "Resolving_real_path_for_0_result_1_6130": "Překládá se skutečná cesta pro {0}, výsledek {1}.", + "Resolving_type_reference_directive_0_containing_file_1_6242": "======== Překládá se direktiva odkazu na typ {0} obsahující soubor {1}. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Překládá se direktiva reference typu {0}, obsažený soubor {1}, kořenový adresář {2}. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Překládá se direktiva reference typu {0}, obsažený soubor {1}, kořenový adresář není nastavený. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Překládá se direktiva reference typu {0}, obsažený soubor není nastavený, kořenový adresář {1}. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Překládá se direktiva reference typu {0}, obsažený soubor není nastavený, kořenový adresář není nastavený. ========", + "Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_no_6265": "Překlad direktivy odkazu na typ pro program, který zadává vlastní hodnoty typeRoot, s přeskočením vyhledávání ve složce „node_modules“.", + "Resolving_with_primary_search_path_0_6121": "Probíhá překlad pomocí primární cesty hledání {0}.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Parametr rest {0} implicitně obsahuje typ any[].", + "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047": "Parametr rest {0} má implicitně typ any[], ale je možné, že lepší typ by se vyvodil z použití.", + "Rest_types_may_only_be_created_from_object_types_2700": "Typy rest se dají vytvářet jenom z typů object.", + "Return_type_annotation_circularly_references_itself_2577": "Anotace návratového typu se cyklicky odkazuje sama na sebe.", + "Return_type_must_be_inferred_from_a_function_95149": "Návratový typ musí být odvozen z funkce.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Návratový typ signatury volání z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Návratový typ signatury volání z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Návratový typ signatury konstruktoru z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Návratový typ signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Návratový typ signatury konstruktoru musí jít přiřadit k typu instance třídy.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Návratový typ exportované funkce má nebo používá název {0} z externího modulu {1}, ale nedá se pojmenovat.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Návratový typ exportované funkce má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Návratový typ exportované funkce má nebo používá privátní název {0}.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Návratový typ signatury indexu z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Návratový typ signatury indexu z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Návratový typ metody z exportovaného rozhraní má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Návratový typ metody z exportovaného rozhraní má nebo používá privátní název {0}.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Návratový typ veřejné metody getter {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Návratový typ veřejné metody getter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Návratový typ veřejné metody getter {0} z exportované třídy má nebo používá privátní název {1}.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Návratový typ veřejné metody z exportované třídy má nebo používá název {0} z externího modulu {1}, ale nedá se pojmenovat.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Návratový typ veřejné metody z exportované třídy má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Návratový typ veřejné metody z exportované třídy má nebo používá privátní název {0}.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Návratový typ veřejné statické metody getter {0} z exportované třídy má nebo používá název {1} z externího modulu {2}, ale nedá se pojmenovat.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Návratový typ veřejné statické metody getter {0} z exportované třídy má nebo používá název {1} z privátního modulu {2}.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Návratový typ veřejné statické metody getter {0} z exportované třídy má nebo používá privátní název {1}.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Návratový typ veřejné statické metody z exportované třídy má nebo používá název {0} z externího modulu {1}, ale nedá se pojmenovat.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Návratový typ veřejné statické metody z exportované třídy má nebo používá název {0} z privátního modulu {1}.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Návratový typ veřejné statické metody z exportované třídy má nebo používá privátní název {0}.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395": "Opětovné použití překladu modulu {0} z {1} nalezeného v mezipaměti z umístění {2} se nevyřešilo.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393": "Opětovné použití překladu modulu {0} z {1} nalezeného v mezipaměti z umístění {2} bylo úspěšně vyřešeno na {3}.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394": "Opětovné použití překladu modulu {0} z {1} nalezeného v mezipaměti z umístění {2} bylo úspěšně vyřešeno na {3} s ID balíčku {4}.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389": "Opětovné použití překladu modulu {0} z {1} starého programu se nevyřešilo.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183": "Opětovné použití překladu modulu {0} z {1} starého programu bylo úspěšně vyřešeno na {2}.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184": "Opětovné použití překladu modulu {0} z {1} starého programu bylo úspěšně vyřešeno na {2} s ID balíčku {3}.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398": "Opětovné použití překladu direktivy typu reference {0} z {1} nalezeného v mezipaměti z umístění {2} se nevyřešilo.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396": "Opětovné použití překladu direktivy typu reference {0} z {1} nalezeného v mezipaměti z umístění {2} bylo úspěšně vyřešeno na {3}.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397": "Opětovné použití překladu direktivy typu reference {0} z {1} nalezeného v mezipaměti z umístění {2} bylo úspěšně vyřešeno na {3} s ID balíčku {4}.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392": "Opětovné použití překladu direktivy typu reference {0} z {1} starého programu se nevyřešilo.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390": "Opětovné použití překladu direktivy typu reference {0} z {1} starého programu bylo úspěšně vyřešeno na {2}.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391": "Opětovné použití překladu direktivy typu reference {0} z {1} starého programu bylo úspěšně vyřešeno na {2} s ID balíčku {3}.", + "Rewrite_all_as_indexed_access_types_95034": "Přepsat vše jako indexované typy přístupu", + "Rewrite_as_the_indexed_access_type_0_90026": "Přepsat jako indexovaný typ přístupu {0}", + "Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_i_6421": "Přepište přípony souborů .ts, .tsx, .mts a .cts v relativních cestách importu na jejich javascriptový ekvivalent ve výstupních souborech.", + "Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish_2869": "Pravý operand ?? je nedostupný, protože levý operand nemá nikdy hodnotu null.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Nedá se určit kořenový adresář, přeskakují se primární cesty hledání.", + "Root_file_specified_for_compilation_1427": "Kořenový soubor, který se zadal pro kompilaci", + "STRATEGY_6039": "STRATEGIE", + "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Uložte soubory .tsbuildinfo, aby byla možná přírůstková kompilace projektů.", + "Saw_non_matching_condition_0_6405": "Byla zjištěna neshodná podmínka {0}.", + "Scoped_package_detected_looking_in_0_6182": "Zjištěn balíček v oboru, hledání v: {0}", + "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418": "Vyhledávají se záložní rozšíření ve všech nadřazených adresářích „node_modules“: {0}.", + "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417": "Vyhledávají se upřednostňovaná rozšíření ve všech nadřazených adresářích „node_modules“: {0}.", + "Selection_is_not_a_valid_statement_or_statements_95155": "Výběr nepředstavuje platný příkaz (platné příkazy).", + "Selection_is_not_a_valid_type_node_95133": "Výběr není platným uzlem typů.", + "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705": "Nastavte verzi jazyka JavaScript pro generovaný JavaScript a zahrňte deklarace kompatibilních knihoven.", + "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654": "Nastavte jazyk posílání zpráv z TypeScriptu. Toto nastavení neovlivní generování.", + "Set_the_module_option_in_your_configuration_file_to_0_95099": "Nastavte možnost module v konfiguračním souboru na {0}.", + "Set_the_newline_character_for_emitting_files_6659": "Nastavte pro generované soubory znak nového řádku.", + "Set_the_target_option_in_your_configuration_file_to_0_95098": "Nastavte možnost target v konfiguračním souboru na {0}.", + "Setters_cannot_return_a_value_2408": "Metody setter nemůžou vracet hodnotu.", + "Show_all_compiler_options_6169": "Zobrazí všechny možnosti kompilátoru.", + "Show_diagnostic_information_6149": "Zobrazí diagnostické informace.", + "Show_verbose_diagnostic_information_6150": "Zobrazí podrobné diagnostické informace.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Zobrazit, co by se sestavilo (nebo odstranilo, pokud je zadaná možnost --clean)", + "Signature_0_must_be_a_type_predicate_1224": "Signatura {0} musí být predikát typu.", + "Signature_declarations_can_only_be_used_in_TypeScript_files_8017": "Deklarace signatur se dají používat jen v typescriptových souborech.", + "Skip_building_downstream_projects_on_error_in_upstream_project_6640": "Přeskočí vytváření podřízených projektů při chybě v nadřazeném projektu.", + "Skip_type_checking_all_d_ts_files_6693": "Přeskočte kontrolu typů ve všech souborech .d.ts.", + "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692": "Při kontrole typů vynechte soubory .d.ts zahrnuté do TypeScriptu.", + "Skip_type_checking_of_declaration_files_6012": "Přeskočit kontrolu typu souborů deklarace", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Skipping build of project '{0}' because its dependency '{1}' has errors", + "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382": "Skipping build of project '{0}' because its dependency '{1}' was not built", + "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164": "Přeskakuje se modul „{0}“, který vypadá jako absolutní identifikátor URI. Cílové typy souborů: {1}.", + "Source_from_referenced_project_0_included_because_1_specified_1414": "Zdroj z odkazovaného projektu {0}, který se zahrnul, protože je zadané {1}.", + "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415": "Zdroj z odkazovaného projektu {0}, který se zahrnul, protože možnost --module se nastavila na none.", + "Source_has_0_element_s_but_target_allows_only_1_2619": "Zdroj má následující počet elementů, ale cíl jich povoluje jen {1}: {0}", + "Source_has_0_element_s_but_target_requires_1_2618": "Zdroj má následující počet elementů, ale cíl jich vyžaduje {1}: {0}", + "Source_provides_no_match_for_required_element_at_position_0_in_target_2623": "Zdroj nenabízí v cíli pro element required na pozici {0} žádnou shodu.", + "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624": "Zdroj nenabízí v cíli pro element variadic na pozici {0} žádnou shodu.", + "Specify_ECMAScript_target_version_6015": "Zadejte cílovou verzi ECMAScriptu.", + "Specify_JSX_code_generation_6080": "Zadejte generování kódu JSX.", + "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679": "Zadejte soubor, který sloučí všechny výstupy do jediného souboru JavaScriptu. Pokud má „declaration“ pravdivou hodnotu,, určete soubor, který sloučí všechny výstupní soubory .d.ts.", + "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641": "Zadejte seznam vzorů glob, které odpovídají souborům zahrnutým do kompilace.", + "Specify_a_list_of_language_service_plugins_to_include_6681": "Zadejte seznam zahrnutých pluginů jazykových služeb.", + "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651": "Zadejte sadu souborů spojených deklaračních knihoven, které popisují cílové běhové prostředí.", + "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680": "Zadejte sadu položek, které se při importu znovu namapují na další nalezená místa.", + "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687": "Zadejte pole objektů, které určují cesty pro projekty. Používá se v odkazech na projekt.", + "Specify_an_output_folder_for_all_emitted_files_6678": "Zadejte výstupní složku pro všechny generované soubory.", + "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718": "Zadejte chování generování nebo kontroly pro importy, které se používají jen pro typy.", + "Specify_file_to_store_incremental_compilation_information_6380": "Zadejte soubor, do kterého se uloží informace o přírůstkové kompilaci.", + "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658": "Zadejte, jak TypeScript v daném specifikátoru modulu najde soubor.", + "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714": "Zadejte, jak sledovat adresáře v systémech, které nemají funkci rekurzivního sledování souborů.", + "Specify_how_the_TypeScript_watch_mode_works_6715": "Zadejte, jak má fungovat režim sledování TypeScriptu.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Zadejte soubory knihovny, které se mají zahrnout do kompilace.", + "Specify_module_code_generation_6016": "Určete generování kódu modulu.", + "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649": "Zadejte specifikátor modulu, který se použije k naimportování továrních funkcí JSX při použití „jsx: react-jsx“.", + "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710": "Zadejte více složek, které budou figurovat jako „node_modules/@types“.", + "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633": "Zadejte jednu nebo více cest nebo jeden či více odkazů na moduly uzlů se základními konfiguračními soubory, ze kterých se dědí nastavení.", + "Specify_options_for_automatic_acquisition_of_declaration_files_6709": "Zadejte možnosti automatického získávání deklaračních souborů.", + "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227": "Zadejte strategii pro vytvoření sledování načítání, když se ho nepovede vytvořit pomocí událostí souborového systému: FixedInterval (výchozí), PriorityInterval, DynamicPriority, FixedChunkSize", + "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226": "Zadejte strategii pro sledování adresáře na platformách, které nepodporují nativně rekurzivní sledování: UseFsEvents (výchozí), FixedPollingInterval, DynamicPriorityPolling, FixedChunkSizePolling", + "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225": "Zadejte strategii pro sledování souboru: FixedPollingInterval (výchozí), PriorityPollingInterval, DynamicPriorityPolling, FixedChunkSizePolling, UseFsEvents, UseFsEventsOnParentDirectory", + "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648": "Zadejte odkaz na fragment JSX, který se použije pro fragmenty při cíleném generování React JSX, např. „React.Fragment“ nebo „Fragment“.", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Zadejte funkci objektu pro vytváření JSX, která se použije při zaměření na generování JSX react, např. React.createElement nebo h.", + "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647": "Zadejte funkci objektu pro vytváření JSX použitou při cílení na generování React JSX, např. React.createElement nebo h.", + "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034": "Zadejte funkci objektu pro vytváření fragmentů JSX, která se použije při cílení na generování JSX react se zadanou možností kompilátoru jsxFactory, například Fragment.", + "Specify_the_base_directory_to_resolve_non_relative_module_names_6607": "Zadejte základní adresář, který se použije k řešení názvů modulů, které nejsou relativní.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Zdejte sekvenci konce řádku, která se má použít při generování souborů: CRLF (dos) nebo LF (unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Zadejte umístění, ve kterém by měl ladicí program najít soubory TypeScript namísto umístění zdroje.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655": "Zadejte umístění, ve kterém by měl ladicí program najít soubory mapy namísto generovaných umístění.", + "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656": "Zadejte maximální hloubku složky, která se použije pro kontrolu souborů JavaScriptu z node_modules. Platí pouze pro allowJs.", + "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238": "Zadejte specifikátor modulu, který se má použít k importu továrních funkcí ‚jsx‘ a ‚jsxs‘ např. z funkce react.", + "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686": "Zadejte objekt vyvolaný pro createElement. To platí pouze při cílení na generování JSX react.", + "Specify_the_output_directory_for_generated_declaration_files_6613": "Zadejte výstupní adresář pro generované deklarační soubory.", + "Specify_the_path_to_tsbuildinfo_incremental_compilation_file_6707": "Zadejte cestu pro soubor přírůstkové kompilace .tsbuildinfo.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Zadejte kořenový adresář vstupních souborů. Slouží ke kontrole struktury výstupního adresáře pomocí --outDir.", + "Specify_the_root_folder_within_your_source_files_6690": "Zadejte kořenovou složku se zdrojovými soubory.", + "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695": "Zadejte pro ladicí programy kořenovou cestu, kde najdou referenční zdrojový kód.", + "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711": "Zadejte názvy typů balíčků, které se zahrnou, i když na ně neodkazuje zdrojový soubor.", + "Specify_what_JSX_code_is_generated_6646": "Zadejte, jaký kód JSX se vygeneruje.", + "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634": "Zadejte, jak má sledovací proces postupovat, když systému dojdou nativní sledovací procesy souborů.", + "Specify_what_module_code_is_generated_6657": "Určete, pro jaký modul se kód generuje.", + "Split_all_invalid_type_only_imports_1367": "Rozdělit všechny neplatné importy, při kterých se importují jen typy", + "Split_into_two_separate_import_declarations_1366": "Rozdělit na dvě samostatné deklarace importu", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Operátor rozšíření ve výrazech new je dostupný jenom při cílení na verzi ECMAScript 5 a vyšší.", + "Spread_types_may_only_be_created_from_object_types_2698": "Typy spread se dají vytvářet jenom z typů object.", + "Starting_compilation_in_watch_mode_6031": "Spouští se kompilace v režimu sledování...", + "Statement_expected_1129": "Očekává se příkaz.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Příkazy se nepovolují v ambientních kontextech.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statické členy nemůžou odkazovat na parametry typu třídy.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Statická vlastnost {0} je v konfliktu s předdefinovanou vlastností Function.{0} funkce konstruktoru {1}.", + "String_literal_expected_1141": "Očekává se řetězcový literál.", + "String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es_18057": "Názvy importu a exportu řetězcového literálu se nepodporují, pokud je příznak „--module“ nastavený na „es2015“ nebo „es2020“.", + "String_literal_with_double_quotes_expected_1327": "Očekával se řetězcový literál s dvojitými uvozovkami.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stylizujte chyby a zprávy pomocí barev a kontextu (experimentální).", + "Subpattern_flags_must_be_present_when_there_is_a_minus_sign_1504": "V případě znaménka minus musí být uvedeny příznaky dílčích vzorů.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Deklarace následných vlastností musí obsahovat stejný typ. Vlastnost {0} musí být typu {1}, ale tady je typu {2}.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Deklarace následných proměnných musí obsahovat stejný typ. Proměnná {0} musí být typu {1}, ale tady je typu {2}.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Nahrazení {0} za vzor {1} má nesprávný typ, očekával se typ string, obdržený je {2}.", + "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062": "Nahrazení {0} ve vzoru {1} může obsahovat maximálně jeden znak * (hvězdička).", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Náhrady vzoru {0} by měly být pole.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Nahrazení vzoru {0} nesmí být prázdné pole.", + "Successfully_created_a_tsconfig_json_file_6071": "Soubor tsconfig.json se úspěšně vytvořil.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Volání pomocí super se nepovolují mimo konstruktory a ve funkcích vnořených v konstruktorech.", + "Suppress_excess_property_checks_for_object_literals_6072": "Potlačit nadměrné kontroly vlastností pro literály objektů", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Potlačit chyby noImplicitAny u objektů indexování bez signatur indexu", + "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703": "Při indexování objektů bez podpisů indexování potlačte chyby „noImplicitAny“.", + "Switch_each_misused_0_to_1_95138": "Přepnout každé chybně použité {0} na {1}", + "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704": "Synchronně volejte zpětná volání a aktualizujte stav sledování adresářů i u platforem, které nativně nepodporují rekurzivní sledování.", + "Syntax_Colon_0_6023": "Syntaxe: {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "Značka {0} očekává určitý minimální počet argumentů ({1}), ale objekt pro vytváření JSX {2} jich poskytuje maximálně {3}.", + "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "Označené výrazy šablony se v nepovinném řetězu nepovolují.", + "Target_allows_only_0_element_s_but_source_may_have_more_2621": "Cíl povoluje jen určitý počet elementů ({0}), ale zdroj jich může mít více.", + "Target_requires_0_element_s_but_source_may_have_fewer_2620": "Cíl vyžaduje určitý počet elementů ({0}), ale zdroj jich může mít méně.", + "Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1_2849": "Cílový podpis poskytuje příliš málo argumentů. Očekávalo se {0} nebo více, ale bylo obdrženo {1}.", + "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "Modifikátor {0} se dá používat jen v typescriptových souborech.", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Operátor {0} nejde použít u typu symbol.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Operátor {0} není u logických typů povolený. Můžete ale použít {1}.", + "The_0_property_of_an_async_iterator_must_be_a_method_2768": "Vlastnost {0} asynchronního iterátoru musí být metoda.", + "The_0_property_of_an_iterator_must_be_a_method_2767": "Vlastnost {0} iterátoru musí být metoda.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Typ Object se dá přiřadit jen k malému počtu dalších typů. Nechtěli jste místo toho použít typ any?", + "The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously_1502": "Příznaky Unicode (u) a Unicode Sets (v) nelze nastavit současně.", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_func_2496": "Funkce s šipkou v ES5 nemůže odkazovat na objekt „arguments“. Zvažte použití standardního výrazu funkce.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_sta_2522": "V ES5 se na objekt „arguments“ nedá odkazovat v asynchronní funkci nebo metodě. Zvažte možnost použít standardní funkci nebo metodu.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Tělo příkazu if nemůže být prázdný příkaz.", + "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793": "Volání by pro tuto implementaci proběhlo úspěšně, ale signatury implementace pro přetížení nejsou externě k dispozici.", + "The_character_set_of_the_input_files_6163": "Znaková sada vstupních souborů", + "The_containing_arrow_function_captures_the_global_value_of_this_7041": "Obsahující funkce šipky zachytává globální hodnotu pro this.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Text obsahující funkce nebo modulu je pro analýzu toku řízení příliš dlouhý.", + "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309": "Aktuální soubor je modul CommonJS a na nejvyšší úrovni nemůže používat await.", + "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479": "Aktuální soubor je modul CommonJS, jehož importy vytvoří volání require. Odkazovaný soubor je však modul ECMAScript a nelze ho importovat pomocí příkazu require. Raději zvažte vytvoření dynamického volání import(\"{0}\").", + "The_current_host_does_not_support_the_0_option_5001": "Aktuální hostitel nepodporuje možnost {0}.", + "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018": "Deklarace {0}, kterou jste pravděpodobně chtěli použít, je definovaná tady.", + "The_declaration_was_marked_as_deprecated_here_2798": "Deklarace se tady označila jako zastaralá.", + "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500": "Očekávaný typ pochází z vlastnosti {0}, která je deklarovaná tady v typu {1}.", + "The_expected_type_comes_from_the_return_type_of_this_signature_6502": "Očekávaný typ pochází z návratového typu této signatury.", + "The_expected_type_comes_from_this_index_signature_6501": "Očekávaný typ pochází z této signatury indexu.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Výraz přiřazení exportu musí být identifikátor nebo kvalifikovaný název v ambientním kontextu.", + "The_file_is_in_the_program_because_Colon_1430": "Soubor se nachází v programu, protože:", + "The_files_list_in_config_file_0_is_empty_18002": "Seznam files v konfiguračním souboru {0} je prázdný.", + "The_first_export_default_is_here_2752": "První výchozí nastavení exportu je tady.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "První parametr metody then příslibu musí být zpětné volání.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Globální typ JSX.{0} by neměl mít více než jednu vlastnost.", + "The_implementation_signature_is_declared_here_2750": "Signatura implementace se deklarovala tady.", + "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "Meta-vlastnost import.meta není povolena v souborech, které se sestaví do výstupu CommonJS.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "Metavlastnost import.meta se povoluje jen v případě, že možnost --module je nastavená na es2020, es2022, esnext, system, node16, node18 nebo nodenext.", + "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Odvozený typ {0} se nedá pojmenovat bez odkazu na {1}. Pravděpodobně to nebude přenosné. Vyžaduje se anotace typu.", + "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Odvozený typ {0} se odkazuje na typ s cyklickou strukturou, která se nedá triviálně serializovat. Musí se použít anotace typu.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Odvozený typ {0} odkazuje na nepřístupný typ {1}. Musí se použít anotace typu.", + "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056": "Odvozený typ tohoto uzlu přesahuje maximální délku, kterou kompilátor může serializovat. Je potřeba zadat explicitní anotaci typu.", + "The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_n_2850": "Inicializátor deklarace „using“ musí být buď objekt s metodou „[Symbol.dispose]()“, nebo musí mít hodnotu „null“ nebo „undefined“.", + "The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_2851": "Inicializátor deklarace „await using“ musí být buď objekt s metodou „[Symbol.asyncDispose]()“ nebo „[Symbol.dispose]5D;()“, nebo musí mít hodnotu „null“ nebo „undefined“.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "Průnik {0} se omezil na never, protože vlastnost {1} existuje v několika konstituentech a v některých z nich je privátní.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "Průnik {0} se omezil na never, protože vlastnost {1} má v některých konstituentech konfliktní typy.", + "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795": "Klíčové slovo intrinsic se dá použít jenom k deklaraci vnitřních typů poskytovaných kompilátorem.", + "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016": "Aby bylo možné použít fragmenty JSX s možností kompilátoru jsxFactory, je třeba zadat možnost kompilátoru jsxFragmentFactory.", + "The_last_overload_gave_the_following_error_2770": "Poslední přetížení vrátilo následující chybu.", + "The_last_overload_is_declared_here_2771": "Poslední přetížení je deklarované tady.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Levá strana příkazu for...in nemůže být destrukturačním vzorem.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493": "Levá strana příkazu „for...in“ nemůže být deklarace „using“.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494": "Levá strana příkazu „for...in“ nemůže být deklarace „await using“.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Levá strana příkazu for...in nemůže používat anotaci typu.", + "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780": "Levá strana příkazu for...in nemůže představovat přístup k nepovinné vlastnosti.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "Levá strana příkazu for..n musí být proměnná nebo přístup k vlastnosti.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Levá strana příkazu for...in musí být typu string nebo any.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Levá strana příkazu for...of nemůže používat anotaci typu.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781": "Levá strana příkazu for...of nemůže představovat přístup k nepovinné vlastnosti.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106": "Levá strana příkazu for...of nemůže být async.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "Levá strana příkazu for...of musí být proměnná nebo přístup k vlastnosti.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "Levá strana aritmetické operace musí mít typ any, number, bigint nebo být typu výčtu.", + "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "Levá strana výrazu přiřazení nemůže představovat přístup k nepovinné vlastnosti.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Levá strana výrazu přiřazení musí být proměnná nebo přístup k vlastnosti.", + "The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_2860": "Levá strana výrazu „instanceof“ musí být přiřaditelná k prvnímu argumentu metody „[Symbol.hasInstance]“ na pravé straně.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Levá strana výrazu instanceof musí být typu any, typem objektu nebo parametrem typu.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Národní prostředí, které se používá při zobrazování zpráv uživateli (třeba cs-CZ)", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Maximální hloubka závislostí pro vyhledávání pod node_modules a načítání javascriptových souborů", + "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "Operandem operátoru delete nemůže být privátní identifikátor.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Operandem operátoru delete nemůže být vlastnost určená jen pro čtení.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Operandem operátoru delete musí být odkaz na vlastnost.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "Operand operátoru delete musí být nepovinný.", + "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "Operandem operátoru inkrementace nebo dekrementace nemůže být přístup k nepovinné vlastnosti.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Operand operátoru inkrementace nebo dekrementace musí být proměnná nebo přístup k vlastnosti.", + "The_parser_expected_to_find_a_1_to_match_the_0_token_here_1007": "Parser očekával, že najde token {1}, který by odpovídal tokenu {0} tady.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209": "Kořen projektu je nejednoznačný, ale je vyžadován pro vyřešení položky {0} mapování exportu v souboru {1}. Pokud chcete zrušit dvojznačnost, zadejte možnost kompilátoru rootDir.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210": "Kořen projektu je nejednoznačný, ale je vyžadován pro vyřešení položky {0} mapování importu v souboru {1}. Pokud chcete zrušit dvojznačnost, zadejte možnost kompilátoru rootDir.", + "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014": "K vlastnosti {0} se nedá přistupovat v typu {1} v této třídě, protože ho překrývá jiný privátní identifikátor se stejným zápisem.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Návratový typ funkce dekorátoru parametru funkce musí být void nebo any.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Návratový typ funkce dekorátoru vlastnosti musí být void nebo any.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Návratový typ asynchronní funkce musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065": "Návratový typ asynchronní funkce nebo metody musí být globální typ Promise.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "Návratový typ asynchronní funkce nebo metody musí být globální typ Promise. Zamýšleli jste napsat Promise<{0}>?", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "Pravá strana příkazu for...in musí být typu any, typem objektu nebo parametrem typu, ale tady má typ {0}.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "Pravá strana aritmetické operace musí mít typ any, number, bigint nebo být typu výčtu.", + "The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_2359": "Pravá strana výrazu „instanceof“ musí být typ „any“, třída, funkce nebo jiný typ, který se dá přiřadit k typu rozhraní „Function“, nebo typu objektu s metodou „Symbol.hasInstance“.", + "The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression_2848": "Pravá strana výrazu „instanceof“ nesmí být výrazem vytvoření instance.", + "The_root_value_of_a_0_file_must_be_an_object_5092": "Kořenová hodnota souboru {0} musí být objekt.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0_1278": "Modul runtime vyvolá dekoratér s {1} argumenty, ale dekoratér očekává {0}.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0_1279": "Modul runtime vyvolá dekoratér s {1} argumenty, ale dekoratér očekává alespoň {0}.", + "The_shadowing_declaration_of_0_is_defined_here_18017": "Překrývající deklarace {0} je definovaná tady.", + "The_signature_0_of_1_is_deprecated_6387": "Signatura {0} pro {1} je zastaralá.", + "The_specified_path_does_not_exist_Colon_0_5058": "Zadaná cesta neexistuje: {0}", + "The_tag_was_first_specified_here_8034": "Značka se poprvé zadala tady.", + "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "Cíl přiřazení rest objektu nemůže představovat přístup k nepovinné vlastnosti.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Cílem přiřazení zbytku objektu musí být proměnná nebo přístup k vlastnosti.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Kontext this typu {0} se nedá přiřadit k možnosti this metody typu {1}.", + "The_this_types_of_each_signature_are_incompatible_2685": "Typy this jednotlivých signatur nejsou kompatibilní.", + "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104": "Typ {0} je readonly a nedá se přiřadit k neměnnému typu {1}.", + "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Pokud se v příkazu k exportu používá „export type“, nemůžete v pojmenovaném exportu použít modifikátor „type“.", + "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Pokud se v příkazu k importu používá „import type“, nemůžete v pojmenovaném importu použít modifikátor „type“.", + "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Typ deklarace funkce musí odpovídat její signatuře.", + "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Uzel tohoto typu nejde serializovat, protože nejde serializovat jeho vlastnost {0}.", + "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Typ vrácený metodou {0}() asynchronního iterátoru musí být příslib pro typ s vlastností value.", + "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Typ vrácený metodou {0}() iterátoru musí obsahovat vlastnost value.", + "The_types_of_0_are_incompatible_between_these_types_2200": "Typy {0} nejsou mezi těmito typy kompatibilní.", + "The_types_returned_by_0_are_incompatible_between_these_types_2201": "Typy vrácené metodou {0} nejsou mezi těmito typy kompatibilní.", + "The_value_0_cannot_be_used_here_18050": "Hodnota „{0}“ se tady nedá použít.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Deklarace proměnné příkazu for...in nemůže obsahovat inicializátor.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Deklarace proměnné příkazu for...of nemůže obsahovat inicializátor.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Příkaz with není podporovaný. Všechny symboly s blokem with budou typu any.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setti_6280": "V „{0}“ jsou typy, ale tento výsledek se v aktuálním nastavení „moduleResolution“ nepovedlo vyřešit. Zvažte aktualizaci na „node16“, „nodenext“ nebo „bundler“.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278": "V „{0}“ jsou typy, ale tento výsledek se při respektování pole „exports“ souboru package.json nepodařilo vyřešit. Knihovna „{1}“ bude pravděpodobně muset aktualizovat svůj soubor package.json nebo typings.", + "There_is_no_capturing_group_named_0_in_this_regular_expression_1532": "V tomto regulárním výrazu není žádná zachycující skupina s názvem „{0}“.", + "There_is_nothing_available_for_repetition_1507": "Není k dispozici nic pro opakování.", + "This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found_2874": "Tato značka JSX vyžaduje, aby objekt pro vytváření fragmentů {0} byl v oboru, ale nepovedlo se ho najít.", + "This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_fo_2875": "Tato značka JSX vyžaduje, aby existovala cesta k modulu {0}, ale žádná nebyla nalezena. Ujistěte se, že máte nainstalované typy pro příslušný balíček.", + "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "Vlastnost {0} této značky JSX očekává jeden podřízený objekt typu {1}, ale poskytlo se jich více.", + "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "Vlastnost {0} této značky JSX očekává typ {1}, který vyžaduje více podřízených objektů, ale zadal se jen jeden.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534": "Tento zpětný odkaz odkazuje na skupinu, která neexistuje. V tomto regulárním výrazu nejsou žádné zachytávací skupiny.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533": "Tento zpětný odkaz odkazuje na skupinu, která neexistuje. V tomto regulárním výrazu jsou pouze {0} zachytávací skupiny.", + "This_binary_expression_is_never_nullish_Are_you_missing_parentheses_2870": "Tento binární výraz nikdy nemá hodnotu null. Nechybí vám závorky?", + "This_character_cannot_be_escaped_in_a_regular_expression_1535": "Tento znak nelze uvozovat v regulárním výrazu.", + "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Toto porovnání se zdá být neúmyslné, protože typy {0} a {1} se nijak nepřekrývají.", + "This_condition_will_always_return_0_2845": "Tato podmínka vždy vrátí {0}.", + "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Tato podmínka vždy vrátí „{0}“, protože JavaScript porovnává objekty pomocí odkazu, nikoli hodnoty.", + "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Tato podmínka vždy vrátí hodnotu True, protože tato {0} je vždy definovaná.", + "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Tato podmínka vždy vrátí hodnotu True, protože tato funkce je vždy definována. Chtěli jste ji místo toho nazvat?", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Tato funkce konstruktoru se může převést na deklaraci třídy.", + "This_expression_is_always_nullish_2871": "Tento výraz má vždy hodnotu null.", + "This_expression_is_not_callable_2349": "Tento výraz se nedá zavolat.", + "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Tento výraz se nedá volat, protože je to přístupový objekt get. Nechtěli jste ho použít bez ()?", + "This_expression_is_not_constructable_2351": "Tento výraz se nedá vytvořit.", + "This_file_already_has_a_default_export_95130": "Tento soubor už má výchozí export.", + "This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_b_2878": "Přepsání této cesty importu není bezpečné, protože cesta se překládá na jiný projekt a relativní cesta mezi výstupními soubory projektů není stejná jako relativní cesta mezi příslušnými vstupními soubory.", + "This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_duri_2877": "Tento import používá k překladu na vstupní soubor TypeScript rozšíření {0}, ale během generování se nepřepíše, protože se nejedná o relativní cestu.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Toto je deklarace, která se rozšiřuje. Zvažte možnost přesunout rozšiřující deklaraci do stejného souboru.", + "This_kind_of_expression_is_always_falsy_2873": "Tento druh výrazu je vždy nepravdivý.", + "This_kind_of_expression_is_always_truthy_2872": "Tento druh výrazu je vždy pravdivý.", + "This_may_be_converted_to_an_async_function_80006": "Toto je možné převést na asynchronní funkci.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122": "Tento člen nemůže mít komentář JSDoc se značkou @override, protože není deklarovaný v základní třídě {0}.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123": "Tento člen nemůže mít komentář JSDoc se značkou @override, protože není deklarovaný v základní třídě {0}. Měli jste na mysli {1}?", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121": "Tento člen nemůže mít komentář JSDoc se značkou @override, protože třída {0}, která ho obsahuje, nerozšiřuje jinou třídu.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic_4128": "Tento člen nemůže mít komentář JSDoc se značkou @override, protože jeho název je dynamický.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113": "Tento člen nemůže mít modifikátor override, protože není deklarovaný v základní třídě {0}.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117": "Tento člen nemůže mít modifikátor override, protože není deklarovaný v základní třídě {0}. Měli jste na mysli {1}?", + "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112": "Tento člen nemůže mít modifikátor override, protože třída {0}, která ho obsahuje, nerozšiřuje jinou třídu.", + "This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic_4127": "Tento člen nemůže mít modifikátor override, protože jeho název je dynamický.", + "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119": "Tento člen musí mít komentář JSDoc se značkou @override, protože přepisuje člen v základní třídě {0}.", + "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114": "Tento člen musí mít modifikátor override, protože přepisuje člen v základní třídě {0}.", + "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116": "Tento člen musí mít modifikátor override, protože přepisuje abstraktní metodu, která je deklarovaná v základní třídě {0}.", + "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Na tento modul je možné se pomocí importů nebo exportů ECMAScript odkazovat jen tak, že se zapne příznak {0} a odkáže se na výchozí export.", + "This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag_2594": "Tento modul se deklaroval pomocí export =, a dá se použít jenom s výchozím importem při použití příznaku {0}.", + "This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2_6807": "Tato operace se dá zjednodušit. Tento posun je totožný s {0} {1} {2}.", + "This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation_7012": "Toto přetížení implicitně vrací typ „{0}“, protože postrádá anotaci návratového typu.", + "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394": "Tato signatura přetížení není kompatibilní se signaturou implementace.", + "This_parameter_is_not_allowed_with_use_strict_directive_1346": "Tento parametr se nepodporuje s direktivou use strict.", + "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120": "Tato vlastnost parametru musí mít komentář JSDoc se značkou @override, protože přepisuje člen v základní třídě {0}.", + "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115": "Tato vlastnost parametru musí mít modifikátor override, protože přepisuje člen v základní třídě {0}.", + "This_regular_expression_flag_cannot_be_toggled_within_a_subpattern_1509": "Tento příznak regulárního výrazu nelze přepnout v rámci dílčího vzoru.", + "This_regular_expression_flag_is_only_available_when_targeting_0_or_later_1501": "Tento příznak regulárního výrazu je k dispozici pouze při cílení na „{0}“ nebo novější.", + "This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolv_2876": "Přepsání této relativní cesty importu není bezpečné, protože cesta vypadá jako název souboru, ale ve skutečnosti se překládá na {0}.", + "This_spread_always_overwrites_this_property_2785": "Tento rozsah vždy přepíše tuto vlastnost.", + "This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled_1294": "Tato syntaxe není povolená, pokud je povolená možnost erasableSyntaxOnly.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060": "Tato syntaxe je vyhrazená pro soubory s příponou .mts nebo .cts. Přidejte koncovou čárku nebo explicitní omezení.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059": "Tato syntaxe je vyhrazená pro soubory s příponou .mts nebo .cts. Místo toho použijte výraz „as“.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Tato syntaxe vyžaduje importovanou podpůrnou aplikaci, ale modul {0} se nenašel.", + "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Tato syntaxe vyžaduje importovanou pomocnou rutinu s názvem {1}, která v {0} neexistuje. Zvažte možnost upgradovat verzi {0}.", + "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Tato syntaxe vyžaduje importovanou pomocnou rutinu s názvem {1} a parametry {2}, která není kompatibilní s tou v {0}. Zvažte upgrade verze {0}.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Tento parametr typu může potřebovat omezení extends {0}.", + "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Toto použití importu není platné. Volání import() se dají zapsat, ale musí mít závorky a nemůžou mít typové argumenty.", + "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482": "Pokud chcete tento soubor převést na modul ECMAScript, přidejte pole \"type\": \"module\" do {0}.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481": "Pokud chcete tento soubor převést na modul ECMAScript, změňte jeho příponu na {0}\" nebo přidejte pole \"type\": \"module\" do {1}.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480": "Pokud chcete tento soubor převést na modul ECMAScript, změňte jeho příponu na {0} nebo vytvořte místní soubor package.json s {\"type\": \"module\"}.", + "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483": "Pokud chcete tento soubor převést na modul ECMAScript, vytvořte místní soubor package.json s { \"type\": \"module\" }.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Výrazy await nejvyšší úrovně se povolují jen v případě, že možnost module je nastavená na es2022, esnext, system, node16, node18 nodenext nebo preserve a možnost target je nastavená na es2017 nebo vyšší.", + "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854": "Výrazy await using nejvyšší úrovně se povolují jen v případě, že možnost module je nastavená na es2022, esnext, system, node16, node18, nodenext nebo preserve a možnost target je nastavená na es2017 nebo vyšší.", + "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Deklarace nejvyšší úrovně v souborech .d.ts musí začínat modifikátorem declare, nebo export.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_nod_1432": "Smyčky for await nejvyšší úrovně se povolují jen v případě, že možnost module je nastavená na es2022, esnext, system, node16, node18, nodenext nebo preserve a možnost target je nastavená na es2017 nebo vyšší.", + "Trailing_comma_not_allowed_1009": "Čárka na konci není povolená.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpiluje každý soubor jako samostatný modul (podobné jako ts.transpileModule).", + "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Vyzkoušejte deklaraci npm i --save-dev @types/{1}, pokud existuje, nebo přidejte nový soubor deklarací (.d.ts) s deklarací declare module '{0}';.", + "Trying_other_entries_in_rootDirs_6110": "Zkoušejí se další položky v rootDirs.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Zkouší se nahrazení {0}, umístění modulu kandidáta: {1}.", + "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493": "Typ řazené kolekce členů {0} délky {1} nemá na indexu {2} žádný prvek.", + "Tuple_type_arguments_circularly_reference_themselves_4110": "Argumenty typů řazené kolekce členů cyklicky odkazují samy na sebe.", + "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802": "Typem {0} se dá iterovat, pouze když se použije příznak --downlevelIteration nebo s možností --target nastavenou na es2015 nebo vyšší.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Typ {0} se nedá použít jako typ indexu.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Typ {0} nejde použít k indexování typu {1}.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Typ {0} nevyhovuje omezení {1}.", + "Type_0_does_not_satisfy_the_expected_type_1_1360": "Typ {0} nevyhovuje očekávanému typu {1}.", + "Type_0_has_no_call_signatures_2757": "Typ {0} nemá žádné signatury volání.", + "Type_0_has_no_construct_signatures_2761": "Typ {0} nemá žádné signatury konstruktu.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Typ {0} nemá odpovídající signaturu indexu pro typ {1}.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Typ {0} nemá žádné vlastnosti společné s typem {1}.", + "Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable_2635": "U typu {0} nejsou žádné podpisy, pro které platí seznam argumentů obecného typu.", + "Type_0_is_generic_and_can_only_be_indexed_for_reading_2862": "Typ „{0}“ je obecný a lze ho indexovat pouze pro čtení.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "V typu {0} chybí následující vlastnosti z typu {1}: {2}", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "V typu {0} chybí následující vlastnosti z typu {1}: {2} a ještě {3}", + "Type_0_is_not_a_constructor_function_type_2507": "Typ {0} není typ funkce konstruktoru.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compa_1055": "Typ „{0}“ nepředstavuje platný návratový typ asynchronní funkce v ES5, protože neodkazuje na hodnotu konstruktoru kompatibilní s konstruktorem Promise.", + "Type_0_is_not_an_array_type_2461": "Typ {0} není typ pole.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Typ {0} není typem pole nebo řetězce.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ {0} není typem pole nebo řetězce, nebo nemá metodu [Symbol.iterator](), která vrací iterátor.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ {0} není typem pole, nebo nemá metodu [Symbol.iterator](), která vrací iterátor.", + "Type_0_is_not_assignable_to_type_1_2322": "Typ {0} nejde přiřadit typu {1}.", + "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820": "Typ {0} se nedá přiřadit k typu {1}. Měli jste na mysli {2}?", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Typ {0} se nedá přiřadit typu {1}. Existují dva různé typy s tímto názvem, ale nesouvisí spolu.", + "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636": "Typ {0} nelze přiřadit k typu {1}, jak je implikováno anotací odchylky.", + "Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values_18033": "Typ „{0}“ nelze přiřadit k typu „{1}“, jak je vyžadováno pro vypočítané hodnoty členů výčtu.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375": "Typ {0} se nedá přiřadit k typu {1} s hodnotou exactOptionalPropertyTypes: true. Zvažte možnost přidat hodnotu undefined do typů vlastností cíle.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "Typ {0} se nedá přiřadit k typu {1} s hodnotou exactOptionalPropertyTypes: true. Zvažte možnost přidat hodnotu undefined do typu cíle.", + "Type_0_is_not_comparable_to_type_1_2678": "Typ {0} se nedá porovnat s typem {1}.", + "Type_0_is_not_generic_2315": "Typ {0} není obecný.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "Typ {0} může představovat primitivní hodnotu, která není povolena jako pravý operand operátoru in.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Typ {0} musí mít metodu [Symbol.asyncIterator](), která vrací asynchronní iterátor.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Typ {0} musí mít metodu [Symbol.iterator](), která vrací iterátor.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Typ {0} neposkytuje žádnou shodu pro podpis {1}.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Typ {0} odkazuje rekurzivně sám na sebe jako na základní typ.", + "Type_Checking_6248": "Kontrola typů", + "Type_alias_0_circularly_references_itself_2456": "Alias typu {0} odkazuje cyklicky sám na sebe.", + "Type_alias_must_be_given_a_name_1439": "Alias typu musí mít název.", + "Type_alias_name_cannot_be_0_2457": "Název aliasu typu nemůže být {0}.", + "Type_aliases_can_only_be_used_in_TypeScript_files_8008": "Aliasy typů se dají používat jen v typescriptových souborech.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "V deklaraci konstruktoru se nemůže objevit anotace typu.", + "Type_annotations_can_only_be_used_in_TypeScript_files_8010": "Anotace typů se dají používat jen v typescriptových souborech.", + "Type_argument_expected_1140": "Očekává se argument typu.", + "Type_argument_list_cannot_be_empty_1099": "Seznam argumentů typu nemůže být prázdný.", + "Type_arguments_can_only_be_used_in_TypeScript_files_8011": "Argumenty typů se dají používat jen v typescriptových souborech.", + "Type_arguments_for_0_circularly_reference_themselves_4109": "Argumenty typů pro {0} se cyklicky odkazují samy na sebe.", + "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016": "Kontrolní výrazy typů se dají používat jen v typescriptových souborech.", + "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626": "Typ na pozici {0} ve zdroji není kompatibilní s typem na pozici {1} v cíli.", + "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627": "Typ na pozicích {0} až {1} ve zdroji není kompatibilní s typem na pozici {2} v cíli.", + "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039": "Typ obsahující privátní název „{0}“ nejde použít s možností --isolatedDeclarations.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Soubory deklarace typu, které se mají zahrnout do kompilace", + "Type_expected_1110": "Očekával se typ.", + "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456": "Kontrolní výrazy importu typů by měly mít přesně jeden klíč – resolution-mode – s hodnotou import nebo require.", + "Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1464": "Atributy importu typů by měly mít přesně jeden klíč – „resolution-mode“ – s hodnotou „import“ nebo „require“.", + "Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute_1542": "Import typu modulu ECMAScript z modulu CommonJS musí mít atribut resolution-mode.", + "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589": "Vytvoření instance typu je příliš hluboké a může být nekonečné.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Typ se přímo nebo nepřímo odkazuje ve zpětném volání jeho vlastní metody then při splnění.", + "Type_library_referenced_via_0_from_file_1_1402": "Knihovna typů, na kterou se odkazuje přes {0} ze souboru {1}", + "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Knihovna typů, na kterou se odkazuje přes {0} ze souboru {1} s packageId {2}", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Typ operandu await musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Typ hodnoty počítané vlastnosti je {0} a nedá se přiřadit do typu {1}.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Typ instance členské proměnné {0} nemůže odkazovat na identifikátor {1} deklarovaný v konstruktoru.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterovaných elementů yield* musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Typ vlastnosti {0} cyklicky odkazuje sám na sebe v mapovaném typu {1}.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu yield v asynchronním generátoru musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", + "Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribut_1541": "Import, při kterém se importuje pouze typ modulu ECMAScript z modulu CommonJS, musí mít atribut resolution-mode.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Typ pochází z tohoto importu. Import stylu oboru názvů není možné zavolat ani vytvořit a při běhu způsobí chybu. Zvažte možnost použít tady místo toho výchozí import nebo importovat require.", + "Type_parameter_0_has_a_circular_constraint_2313": "Parametr typu {0} má cyklické omezení.", + "Type_parameter_0_has_a_circular_default_2716": "Parametr typu {0} má cyklickou výchozí hodnotu.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Parametr typu {0} signatury volání z exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Parametr typu {0} signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Parametr typu {0} exportované třídy má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Parametr typu {0} exportované funkce má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Parametr typu {0} exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103": "Parametr typu {0} exportovaného typu namapovaného objektu typu má nebo používá privátní název {1}.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Parametr typu {0} exportovaného aliasu typu má nebo používá privátní název {1}.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Parametr typu {0} metody z exportovaného rozhraní má nebo používá privátní název {1}.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Parametr typu {0} veřejné metody z exportované třídy má nebo používá privátní název {1}.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Parametr typu {0} veřejné statické metody z exportované třídy má nebo používá privátní název {1}.", + "Type_parameter_declaration_expected_1139": "Očekává se deklarace parametru typu.", + "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004": "Deklarace parametrů typů se dají používat jen v typescriptových souborech.", + "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744": "Výchozí parametry typů se můžou odkazovat jen na dříve deklarované parametry typů.", + "Type_parameter_list_cannot_be_empty_1098": "Seznam parametrů typu nemůže být prázdný.", + "Type_parameter_name_cannot_be_0_2368": "Název parametru typu nemůže být {0}.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Parametry typu se nemůžou vyskytovat v deklaraci konstruktoru.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Predikát typu {0} nejde přiřadit {1}.", + "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799": "Typ tvoří typ řazené kolekce členů, který se nedá reprezentovat, protože je příliš velký.", + "Type_reference_directive_0_was_not_resolved_6120": "======== Direktiva odkazu na typ {0} se nepřeložila. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Direktiva odkazu na typ {0} se úspěšně přeložila na {1}, primární: {2}. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== Direktiva odkazu na typ {0} se úspěšně přeložila na {1} s ID balíčku {2}, primární: {3}. ========", + "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037": "Kontrolní výrazy typů se dají používat jen v typescriptových souborech.", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Typy se v deklaracích exportu v souborech JavaScriptu nemůžou vyskytovat.", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Typy mají samostatné deklarace privátní vlastnosti {0}.", + "Types_of_construct_signatures_are_incompatible_2419": "Typy signatur konstruktorů nejsou kompatibilní.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Typy parametrů {0} a {1} jsou nekompatibilní.", + "Types_of_property_0_are_incompatible_2326": "Typy vlastnosti {0} nejsou kompatibilní.", + "Unable_to_open_file_0_6050": "Soubor {0} nejde otevřít.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Když se podpis dekorátoru třídy volá jako výraz, nejde přeložit.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Když se podpis dekorátoru metody volá jako výraz, nejde přeložit.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Když se podpis dekorátoru parametru volá jako výraz, nejde přeložit.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Když se podpis dekorátoru vlastnosti volá jako výraz, nejde přeložit.", + "Undetermined_character_escape_1513": "Neurčený řídicí znak.", + "Unexpected_0_Did_you_mean_to_escape_it_with_backslash_1508": "Neočekáváno: „{0}“. Nechtěli jste ho uvést zpětným lomítkem?", + "Unexpected_end_of_text_1126": "Neočekávaný konec textu", + "Unexpected_keyword_or_identifier_1434": "Neočekávané klíčové slovo nebo identifikátor.", + "Unexpected_token_1012": "Neočekávaný token", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Neočekávaný token. Očekával se konstruktor, metoda, přístupový objekt nebo vlastnost.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Neočekávaný token. Očekával se název parametru typu bez složených závorek.", + "Unexpected_token_Did_you_mean_or_gt_1382": "Neočekávaný token. Měli jste na mysli {'>'} nebo >?", + "Unexpected_token_Did_you_mean_or_rbrace_1381": "Neočekávaný token. Měli jste na mysli {'}'} nebo }?", + "Unexpected_token_expected_1179": "Neočekávaný token. Očekává se znak {.", + "Unicode_escape_sequence_cannot_appear_here_17021": "Řídicí sekvence Unicode se tady nemůže vyskytovat.", + "Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_se_1538": "Řídicí sekvence Unicode jsou k dispozici pouze v případě, že je nastaven příznak Unicode (u) nebo Unicode Sets (v).", + "Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v__1530": "Výrazy hodnoty vlastnosti Unicode jsou k dispozici pouze v případě, že je nastaven příznak Unicode (u) nebo Unicode Sets (v).", + "Unknown_Unicode_property_name_1524": "Neznámý název vlastnosti Unicode.", + "Unknown_Unicode_property_name_or_value_1529": "Neznámý název nebo hodnota vlastnosti Unicode.", + "Unknown_Unicode_property_value_1526": "Neznámá hodnota vlastnosti Unicode.", + "Unknown_build_option_0_5072": "Neznámá možnost sestavení {0}", + "Unknown_build_option_0_Did_you_mean_1_5077": "Neznámá možnost sestavení {0}. Měli jste na mysli {1}?", + "Unknown_compiler_option_0_5023": "Neznámá možnost kompilátoru {0}", + "Unknown_compiler_option_0_Did_you_mean_1_5025": "Neznámá možnost kompilátoru {0}. Měli jste na mysli {1}?", + "Unknown_keyword_or_identifier_Did_you_mean_0_1435": "Neznámé klíčové slovo nebo identifikátor. Neměli jste na mysli „{0}“?", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Neznámá možnost excludes. Měli jste na mysli exclude?", + "Unknown_regular_expression_flag_1499": "Neznámý příznak regulárního výrazu.", + "Unknown_type_acquisition_option_0_17010": "Neznámá možnost získání typu {0}", + "Unknown_type_acquisition_option_0_Did_you_mean_1_17018": "Neznámá možnost získání typu {0}. Měli jste na mysli {1}?", + "Unknown_watch_option_0_5078": "Neznámá možnost sledování {0}", + "Unknown_watch_option_0_Did_you_mean_1_5079": "Neznámá možnost sledování {0}. Měli jste na mysli {1}?", + "Unreachable_code_detected_7027": "Zjistil se nedosažitelný kód.", + "Unterminated_Unicode_escape_sequence_1199": "Neukončená řídicí sekvence Unicode", + "Unterminated_quoted_string_in_response_file_0_6045": "Neukončený řetězec v uvozovkách v souboru odezvy {0}", + "Unterminated_regular_expression_literal_1161": "Neukončený literál regulárního výrazu", + "Unterminated_string_literal_1002": "Neukončený řetězcový literál", + "Unterminated_template_literal_1160": "Neukončený literál šablony", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Volání netypové funkce nemusí přijmout argumenty typu.", + "Unused_label_7028": "Nepoužívaný popisek", + "Unused_ts_expect_error_directive_2578": "Nepoužitá direktiva @ts-expect-error", + "Update_import_from_0_90058": "Aktualizovat import z: {0}", + "Update_modifiers_of_0_90061": "Aktualizujte modifikátory „{0}“", + "Updating_output_timestamps_of_project_0_6359": "Aktualizují se výstupní časová razítka projektu {0}...", + "Updating_unchanged_output_timestamps_of_project_0_6371": "Aktualizují se nezměněná výstupní časová razítka projektu {0}...", + "Use_0_95174": "Použít {0}", + "Use_0_instead_5106": "Místo toho použijte možnost „{0}“.", + "Use_Number_isNaN_in_all_conditions_95175": "Ve všech podmínkách použijte Number.isNaN.", + "Use_element_access_for_0_95145": "Použít přístup k elementům pro {0}", + "Use_element_access_for_all_undeclared_properties_95146": "Použít přístup k elementům pro všechny nedeklarované vlastnosti", + "Use_import_type_95180": "Použijte „import type“.", + "Use_synthetic_default_member_95016": "Použije syntetického výchozího člena.", + "Use_the_package_json_exports_field_when_resolving_package_imports_6408": "Při překladu importů balíčků použijte pole „exports“ souboru package.json.", + "Use_the_package_json_imports_field_when_resolving_imports_6409": "Při řešení importů použijte pole „imports“ v souboru package.json.", + "Use_type_0_95181": "Použijte „type {0}„.", + "Using_0_subpath_1_with_target_2_6404": "Používá se {0} dílčí cesta {1} s cílem {2}.", + "Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found_2879": "Použití fragmentů JSX vyžaduje, aby objekt pro vytváření fragmentů {0} byl v oboru, ale nepovedlo se ho najít.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Použití řetězce v příkazu for...of se podporuje jenom v ECMAScript 5 nebo vyšší verzi.", + "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Použití --build, -b způsobí, že se tsc bude chovat spíše jako orchestrátor sestavení než kompilátor. Pomocí této možnosti můžete aktivovat vytváření složených projektů, o kterých se můžete dozvědět více {0}", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", + "VERSION_6036": "VERZE", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Hodnota typu {0} nemá žádné vlastnosti společné s typem {1}. Chtěli jste ji volat?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Hodnota typu {0} se nedá volat. Nechtěli jste zahrnout new?", + "Variable_0_implicitly_has_an_1_type_7005": "Proměnná {0} má implicitně typ {1}.", + "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043": "Proměnná {0} má implicitně typ {1}, ale je možné, že lepší typ by se vyvodil z využití.", + "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046": "Proměnná {0} má na některých místech implicitně typ {1}, ale je možné, že lepší typ by se vyvodil z využití.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "V některých umístěních, kde se nedá určit typ proměnné, má proměnná {0} implicitně typ {1}.", + "Variable_0_is_used_before_being_assigned_2454": "Proměnná {0} je použitá před přiřazením.", + "Variable_declaration_expected_1134": "Očekává se deklarace proměnné.", + "Variable_declaration_list_cannot_be_empty_1123": "Seznam deklarací proměnných nemůže být prázdný.", + "Variable_declaration_not_allowed_at_this_location_1440": "Deklarace proměnné není v tomto umístění povolená.", + "Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9010": "Proměnná musí mít explicitní anotaci typu s možností --isolatedDeclarations.", + "Variables_with_multiple_declarations_cannot_be_inlined_95186": "Proměnné s více deklaracemi nemohou být vložené.", + "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625": "Element variadic na pozici {0} ve zdroji neodpovídá elementu na pozici {1} v cíli.", + "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637": "Poznámky Variance se podporují pouze u aliasů typů pro typy objektů, funkcí, konstruktorů a mapování.", + "Version_0_6029": "Verze {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file_95110": "Další informace o tomto souboru si můžete přečíst na https://aka.ms/tsconfig", + "WATCH_OPTIONS_6918": "MOŽNOSTI SLEDOVÁNÍ", + "Watch_and_Build_Modes_6250": "Režimy sledování a sestavování", + "Watch_input_files_6005": "Sledovat vstupní soubory", + "Watch_option_0_requires_a_value_of_type_1_5080": "Možnost sledování {0} vyžaduje hodnotu typu {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Pro {0} můžeme napsat typ jenom tak, že sem přidáme typ pro celý parametr.", + "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Při přiřazování funkcí zkontrolujte a zajistěte, aby parametry a vrácené hodnoty měly kompatibilní podtypy.", + "When_type_checking_take_into_account_null_and_undefined_6699": "Při kontrole typů berte v potaz i hodnoty „null“ a „undefined“.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Určuje, jestli se místo vymazání obrazovky má zachovat zastaralý výstup konzoly v režimu sledování.", + "Wrap_all_invalid_characters_in_an_expression_container_95109": "Zabalit všechny neplatné znaky do kontejneru výrazu", + "Wrap_all_invalid_decorator_expressions_in_parentheses_95195": "Uzavřít všechny neplatné výrazy dekoratéru do závorek", + "Wrap_all_object_literal_with_parentheses_95116": "Uzavřít všechny literály objektů do závorek", + "Wrap_all_unparented_JSX_in_JSX_fragment_95121": "Zabalit všechny JSX bez nadřazených položek ve fragmentu JSX", + "Wrap_in_JSX_fragment_95120": "Zabalit ve fragmentu JSX", + "Wrap_in_parentheses_95194": "Uzavřít do závorek", + "Wrap_invalid_character_in_an_expression_container_95108": "Zabalit neplatný znak do kontejneru výrazu", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Uzavřít následující kód, který by měl být literál objektu, do závorek", + "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Informace o všech možnostech kompilátoru najdete na {0}", + "You_cannot_rename_a_module_via_a_global_import_8031": "Přes globální import se modul nedá přejmenovat.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Nelze přejmenovat elementy definované ve složce node_modules.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Nelze přejmenovat elementy definované v jiné složce node_modules.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nejde přejmenovat elementy definované ve standardní knihovně TypeScriptu.", + "You_cannot_rename_this_element_8000": "Tento element nejde přejmenovat.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Objekt {0} přijímá málo argumentů k tomu, aby se dal použít jako dekoratér. Nechtěli jste ho nejprve volat a napsat @{0}()?", + "_0_and_1_index_signatures_are_incompatible_2330": "Signatury indexu {0} a {1} jsou nekompatibilní.", + "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Operace {0} a {1} se nedají kombinovat bez závorek.", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Položka {0} je zadána dvakrát. Atribut s názvem {0} se přepíše.", + "_0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17019": "„{0}“ na konci typu není platná syntaxe TypeScriptu. Nechtěli jste napsat „{1}“?", + "_0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17020": "„{0}“ na začátku typu není platná syntaxe TypeScriptu. Nechtěli jste napsat „{1}“?", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "{0} se dá importovat jen zapnutím příznaku esModuleInterop a pomocí výchozího importu.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "{0} se dá importovat jen pomocí výchozího importu.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "{0} se dá importovat jen pomocí volání require nebo zapnutím příznaku esModuleInterop a pomocí výchozího importu.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "{0} se dá importovat jen pomocí volání require nebo pomocí výchozího importu.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "{0} se dá importovat jen pomocí import {1} = require({2}) nebo výchozího importu.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "{0} se dá importovat jen pomocí import {1} = require({2}) nebo zapnutím příznaku esModuleInterop a pomocí výchozího importu.", + "_0_cannot_be_used_as_a_JSX_component_2786": "{0} se nedá použít jako součást JSX.", + "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "{0} se nedá používat jako hodnota, protože se exportovalo pomocí export type.", + "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "{0} se nedá používat jako hodnota, protože se importovalo pomocí import type.", + "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "Komponenty {0} nepřijímají text jako podřízené prvky. Text v JSX má typ string, ale očekávaný typ {1} je {2}.", + "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082": "Instanci {0} by bylo možné vytvořit s libovolným typem, který by nemusel souviset s {1}.", + "_0_declarations_can_only_be_declared_inside_a_block_1156": "Deklarace „{0}“ je možné deklarovat jenom uvnitř bloku.", + "_0_declarations_can_only_be_used_in_TypeScript_files_8006": "Deklarace {0} se dají používat jen v typescriptových souborech.", + "_0_declarations_may_not_have_binding_patterns_1492": "Deklarace „{0}“ nesmí mít vzory s vazbami.", + "_0_declarations_must_be_initialized_1155": "Deklarace „{0}“ se musejí inicializovat.", + "_0_expected_1005": "Očekával se: {0}.", + "_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is__18055": "„{0}“ má typ řetězce, ale pokud je povolená možnost isolatedModules, musí mít syntakticky rozpoznatelnou syntaxi řetězce.", + "_0_has_no_exported_member_named_1_Did_you_mean_2_2724": "{0} nemá žádný exportovaný člen s názvem {1}. Neměli jste na mysli {2}?", + "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050": "{0} má implicitně návratový typ {1}, ale je možné, že lepší typ by se vyvodil z využití.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "{0} obsahuje implicitně návratový typ any, protože neobsahuje anotaci návratového typu a přímo nebo nepřímo se odkazuje v jednom ze svých návratových výrazů.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "{0} má implicitně typ any, protože nemá anotaci typu a odkazuje se přímo nebo nepřímo v jeho vlastním inicializátoru.", + "_0_index_signatures_are_incompatible_2634": "Signatury indexu {0} jsou nekompatibilní.", + "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "{0} Typ indexu {1} se nedá přiřadit k {2} typu indexu {3}.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0} je primitivum, ale {1} je obálkový objekt. Pokud je to možné, použijte raději {0}.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "{0} je typ a nedá se importovat do javascriptových souborů. V poznámce typu JSDoc použijte {1}.", + "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled_1484": "„{0}“ je typ a musí se importovat pomocí importu „pouze typ“, pokud je povolená možnost verbatimModuleSyntax.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "{0} je nepoužívané přejmenování {1}. Chtěli jste ji použít jako poznámku typu?", + "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "{0} se dá přiřadit k omezení typu {1}, ale pro {1} se dala vytvořit instance s jiným podtypem omezení {2}.", + "_0_is_automatically_exported_here_18044": "{0} se sem automaticky exportuje.", + "_0_is_declared_but_its_value_is_never_read_6133": "Deklaruje se {0}, ale jeho hodnota se vůbec nečte.", + "_0_is_declared_but_never_used_6196": "{0} se nadeklarovalo, ale nepoužilo.", + "_0_is_declared_here_2728": "{0} je deklarované tady.", + "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611": "{0} je definované jako vlastnost ve třídě {1}, ale v {2} se tady přepisuje jako přístupový objekt.", + "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "{0} je definované jako přístupový objekt ve třídě {1}, ale v {2} se tady přepisuje jako vlastnost instance.", + "_0_is_deprecated_6385": "{0} je zastaralé.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "{0} není platnou metavlastností pro klíčové slovo {1}. Měli jste na mysli {2}?", + "_0_is_not_allowed_as_a_parameter_name_1390": "{0} není povolen jako název parametru.", + "_0_is_not_allowed_as_a_variable_declaration_name_1389": "{0} se nepovoluje jako název deklarace proměnné.", + "_0_is_of_type_unknown_18046": "„{0}“ je typ unknown", + "_0_is_possibly_null_18047": "„{0}“ je pravděpodobně typ null.", + "_0_is_possibly_null_or_undefined_18049": "„{0}“ je typ null nebo undefined", + "_0_is_possibly_undefined_18048": "„{0}“ je pravděpodobně typ undefined.", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Na {0} se přímo nebo nepřímo odkazuje ve vlastním základním výrazu.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Na {0} se odkazuje přímo nebo nepřímo v jeho vlastní anotaci typu.", + "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783": "{0} se zadalo více než jednou, proto se toto použití přepíše.", + "_0_list_cannot_be_empty_1097": "Seznam {0} nemůže být prázdný.", + "_0_modifier_already_seen_1030": "Modifikátor {0} se už jednou vyskytl.", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias_1274": "Modifikátor {0} se může vyskytovat jenom u parametru typu aliasu třídy, rozhraní nebo typu.", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class_1277": "Modifikátor „{0}“ se může vyskytovat jenom u parametru typu funkce, metody nebo třídy.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Modifikátor {0} se nemůže objevit v deklaraci konstruktoru.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Modifikátor {0} se nemůže objevit v elementu modulu nebo oboru názvů.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Modifikátor {0} se nemůže objevit v parametru.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Modifikátor {0} se nemůže objevit u člena typu.", + "_0_modifier_cannot_appear_on_a_type_parameter_1273": "Modifikátor {0} se nemůže objevit u parametru typu.", + "_0_modifier_cannot_appear_on_a_using_declaration_1491": "Modifikátor „{0}“ se nemůže vyskytovat v deklaraci „using“.", + "_0_modifier_cannot_appear_on_an_await_using_declaration_1495": "Modifikátor {0} se nemůže vyskytovat v deklaraci „await using“.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Modifikátor {0} se nemůže objevit v signatuře indexu.", + "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031": "Modifikátor {0} se nemůže objevit u elementů třídy tohoto typu.", + "_0_modifier_cannot_be_used_here_1042": "Modifikátor {0} tady nejde použít.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Modifikátor {0} nejde použít v ambientním kontextu.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Modifikátor {0} nejde použít s modifikátorem {1}.", + "_0_modifier_cannot_be_used_with_a_private_identifier_18019": "Modifikátor {0} se nedá použít s privátním identifikátorem.", + "_0_modifier_must_precede_1_modifier_1029": "Modifikátor {0} se musí vyskytovat před modifikátorem {1}.", + "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531": "Po „\\{0}“ musí následovat výraz s hodnotou vlastnosti Unicode uzavřený do složených závorek.", + "_0_needs_an_explicit_type_annotation_2782": "{0} vyžaduje explicitní anotaci typu.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "{0} jenom odkazuje na typ, ale tady se používá jako obor názvů.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "{0} odkazuje jenom na typ, ale používá se tady jako hodnota.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690": "{0} odkazuje jenom na typ, ale tady se používá jako hodnota. Nechtěli jste použít {1} v {0}?", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585": "‚{0}‘ odkazuje jen na typ, ale tady se používá jako hodnota. Potřebujete změnit cílovou knihovnu? Zkuste změnit možnost kompilátoru ‚lib‘ na es2015 nebo novější.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "{0} odkazuje na globální UMD, ale aktuální soubor je modul. Zvažte raději přidání importu.", + "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749": "{0} odkazuje na hodnotu, ale tady se používá jako typ. Měli jste na mysli typeof {0}?", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1291": "„{0}“ se překládá na typ a musí být v tomto souboru označen jako „pouze typ“, než se znovu exportuje, když je povolená možnost „{1}“. Zvažte možnost použít „import type“, kde se importuje „{0}“.", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1292": "„{0}“ se překládá na typ a musí být v tomto souboru označen jako „pouze typ“, než se znovu exportuje, když je povolená možnost „{1}“. Zvažte možnost použít „export type { {0} as default }“.", + "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimMo_1485": "„{0}“ se překládá na deklaraci „pouze typ“ a musí se exportovat pomocí importu „pouze typ“, když je povolena možnost „verbatimModuleSyntax“.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1289": "„{0}“ se překládá na deklaraci „pouze typ“ a musí být v tomto souboru označen jako „pouze typ“, než se znovu exportuje, když je povolená možnost „{1}“. Zvažte možnost použít „import type“, kde se importuje „{0}“.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1290": "„{0}“ se překládá na deklaraci „pouze typ“ a musí být v tomto souboru označen jako „pouze typ“, než se znovu exportuje, když je povolená možnost „{1}“. Zvažte možnost použít „export type { {0} as default }“.", + "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_1448": "Hodnota „{0}“ se překládá na deklaraci „pouze typ“ a musí se znovu exportovat pomocí zpětného exportu „pouze typ“, když je povoleno {1}.", + "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258": "Klíčové slovo {0} by mělo být nastaveno uvnitř objektu compilerOptions konfiguračního souboru JSON.", + "_0_tag_already_specified_1223": "Značka {0} se už specifikovala.", + "_0_was_also_declared_here_6203": "{0} se deklarovalo i tady.", + "_0_was_exported_here_1377": "{0} se exportovalo tady.", + "_0_was_imported_here_1376": "{0} se importovalo tady.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "{0} s chybějící anotací návratového typu má implicitně návratový typ {1}.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055": "{0} s chybějící anotací návratového typu má implicitně typ yield {1}.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Modifikátor abstract se může objevit jenom v deklaraci třídy, metody nebo vlastnosti.", + "accessor_modifier_can_only_appear_on_a_property_declaration_1275": "Modifikátor accessor se může objevit jenom v deklaraci vlastnosti.", + "and_here_6204": "a tady.", + "arguments_cannot_be_referenced_in_property_initializers_2815": "Na argumenty nejde odkazovat v inicializátorech vlastností.", + "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476": "auto: Považovat soubory s importy, exporty, import.meta, jsx (s jsx: react-jsx) nebo formátem esm (s modulem node16+) za moduly.", + "await_expression_cannot_be_used_inside_a_class_static_block_18037": "Výraz „await“ nelze použít uvnitř statického bloku třídy.", + "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375": "Výrazy await se tady povolují jen na nejvyšší úrovni souboru, když je daný soubor modul, ale tento soubor nemá žádné importy ani exporty. Zvažte možnost přidat export {}, aby se tento soubor převedl na modul.", + "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308": "Výrazy await se povolují jen v asynchronních funkcích na nejvyšší úrovni modulů.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Výrazy await nejdou použít v inicializátoru parametru.", + "await_has_no_effect_on_the_type_of_this_expression_80007": "Výraz await nemá žádný vliv na typ tohoto výrazu.", + "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853": "Příkazy „await using“ jsou povoleny jen na nejvyšší úrovni souboru, když je daný soubor modul, ale tento soubor nemá žádné importy ani exporty. Zvažte možnost přidat „export {}“, aby se tento soubor převedl na modul.", + "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852": "Výrazy „await“ se povolují jen v asynchronních funkcích na nejvyšší úrovni modulů.", + "await_using_statements_cannot_be_used_inside_a_class_static_block_18054": "Příkazy „await using“ nelze použít uvnitř statického bloku třídy.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Možnost baseUrl je nastavená na {0}, pomocí této hodnoty se přeloží název modulu {1}, který není relativní.", + "c_must_be_followed_by_an_ASCII_letter_1512": "Po „\\c“ musí následovat písmeno v ASCII.", + "can_only_be_used_at_the_start_of_a_file_18026": "#! se dá použít jen na začátku souboru.", + "case_or_default_expected_1130": "Očekává se case nebo default.", + "catch_or_finally_expected_1472": "Očekávalo se catch nebo finally.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Inicializátor člena výčtu const se vyhodnotil na nekonečnou hodnotu.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Inicializátor člena výčtu const se vyhodnotil na nepovolenou hodnotu NaN.", + "const_enum_member_initializers_must_be_constant_expressions_2474": "Inicializátory členů konstantního výčtu musí být konstantní výrazy.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Výčty const se dají použít jenom ve výrazech přístupu k vlastnosti nebo indexu nebo na pravé straně deklarace importu, přiřazení exportu nebo dotazu na typ.", + "constructor_cannot_be_used_as_a_parameter_property_name_2398": "constructor se nedá použít jako název vlastnosti parametru.", + "constructor_is_a_reserved_word_18012": "#constructor je rezervované slovo.", + "default_Colon_6903": "výchozí:", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Příkaz delete nejde volat u identifikátoru ve striktním režimu.", + "export_Asterisk_does_not_re_export_a_default_1195": "export * neprovádí opakovaný export výchozí hodnoty.", + "export_can_only_be_used_in_TypeScript_files_8003": "export = se dá používat jen v typescriptových souborech.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Modifikátor export se nedá použít u ambientních modulů a rozšíření modulů, protože jsou vždy viditelné.", + "extends_clause_already_seen_1172": "Klauzule extends se už jednou vyskytla.", + "extends_clause_must_precede_implements_clause_1173": "Klauzule extends se musí vyskytovat před klauzulí implements.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Klauzule extends exportované třídy {0} má nebo používá privátní název {1}.", + "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021": "Klauzule extends exportované třídy má nebo používá privátní název {0}.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Klauzule extends exportovaného rozhraní {0} má nebo používá privátní název {1}.", + "false_unless_composite_is_set_6906": "„false“, pokud není nastavené „composite“.", + "false_unless_strict_is_set_6905": "„false“, pokud není nastavená hodnota „strict“.", + "file_6025": "soubor", + "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431": "Smyčky for await se tady povolují jen na nejvyšší úrovni souboru, když je daný soubor modul, ale tento soubor nemá žádné importy ani exporty. Zvažte možnost přidat export {}, aby se tento soubor převedl na modul.", + "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103": "Smyčky for await se povolují jen v asynchronních funkcích na nejvyšší úrovni modulů.", + "for_await_loops_cannot_be_used_inside_a_class_static_block_18038": "Smyčky „for await“ nelze použít uvnitř statického bloku třídy.", + "get_and_set_accessors_cannot_declare_this_parameters_2784": "Přístupové objekty get a set nemůžou deklarovat parametry this.", + "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908": "[], pokud je zadáno „soubory“, jinak [\"**/*\"]5D;", + "implements_clause_already_seen_1175": "Klauzule implements se už jednou vyskytla.", + "implements_clauses_can_only_be_used_in_TypeScript_files_8005": "Klauzule implements se dají používat jen v typescriptových souborech.", + "import_can_only_be_used_in_TypeScript_files_8002": "import = se dá používat jen v typescriptových souborech.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Deklarace infer jsou povolené jenom v klauzuli extends podmíněného typu.", + "k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets_1510": "Po „\\k“ musí následovat název zachycující skupiny uzavřený do ostrých závorek.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Nepovoluje se používat let jako název v deklaracích let nebo const.", + "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010": "module === `AMD` or `UMD` or `System` or `ES6`, then `Classic`, Otherwise `Node`", + "module_system_or_esModuleInterop_6904": "module === \"system\" or esModuleInterop", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Výraz new s chybějící signaturou konstruktoru v cíli má implicitně typ any.", + "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907": "[\"node_modules\", \"bower_components\", \"jspm_packages\"] a hodnotu „outDir“, pokud je zadána.", + "one_of_Colon_6900": "jeden z:", + "one_or_more_Colon_6901": "1 nebo více:", + "options_6024": "možnosti", + "or_JSX_element_expected_1145": "Očekával se element { nebo JSX.", + "or_expected_1144": "Očekává se znak { nebo ;.", + "package_json_does_not_have_a_0_field_6100": "Soubor package.json neobsahuje pole {0}.", + "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "package.json nemá položku typesVersions, která by odpovídala verzi {0}.", + "package_json_had_a_falsy_0_field_6220": "Soubor package.json obsahoval neplatné pole {0}.", + "package_json_has_0_field_1_that_references_2_6101": "Soubor package.json má pole {0} {1}, které odkazuje na {2}.", + "package_json_has_a_peerDependencies_field_6281": "Soubor package.json má pole „peerDependencies“.", + "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209": "package.json má položku typesVersions {0}, která není platný rozsah semver.", + "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208": "package.json má položku typesVersions {0}, která odpovídá verzi kompilátoru {1}. Hledá se vzor, který bude odpovídat názvu modulu {2}.", + "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206": "package.json má pole typesVersions s mapováními cesty specifickými pro verzi.", + "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274": "package.json scope {0} implicitně mapuje specifikátor {1} na hodnotu null.", + "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275": "package.json scope {0} má neplatný typ pro cíl specifikátoru {1}.", + "package_json_scope_0_has_no_imports_defined_6273": "package.json scope {0} nemá definovány žádné importy.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Je zadaná možnost paths, hledá se vzor, který odpovídá názvu modulu {0}.", + "q_is_only_available_inside_character_class_1511": "„\\q“ je k dispozici pouze uvnitř třídy znaků.", + "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521": "Po „\\q“ musí následovat řetězcové alternativy uzavřené ve složených závorkách.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modifikátor readonly se může objevit jenom v deklaraci vlastnosti nebo signatuře indexu.", + "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Modifikátor typu readonly se povoluje jen pro typy literálů pole a řazené kolekce členů.", + "require_call_may_be_converted_to_an_import_80005": "Volání require se dá převést na import.", + "resolution_mode_can_only_be_set_for_type_only_imports_1454": "resolution-mode se dá nastavit pouze pro importy type-only.", + "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "resolution-mode je jediný platný klíč pro kontrolní výrazy importu typů.", + "resolution_mode_is_the_only_valid_key_for_type_import_attributes_1463": "„resolution-mode“ je jediný platný klíč pro atributy importu typů.", + "resolution_mode_should_be_either_require_or_import_1453": "resolution-mode by měl být buď require, nebo import.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Je nastavená možnost rootDirs, použije se k překladu relativního názvu modulu {0}.", + "super_can_only_be_referenced_in_a_derived_class_2335": "Na vlastnost super se dá odkazovat jenom v odvozené třídě.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Na možnost super je možné odkazovat jenom ve členech odvozených tříd nebo výrazů literálu objektu.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Na vlastnost super se nedá odkazovat v názvu počítané vlastnosti.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Na vlastnost super se nedá odkazovat v argumentech konstruktoru.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "Možnost super je povolená jenom ve členech výrazů literálu objektu, pokud je možnost target ES2015 nebo vyšší.", + "super_may_not_use_type_arguments_2754": "super nemůže používat argumenty typů.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Před přístupem k vlastnosti super v konstruktoru odvozené třídy se musí zavolat super.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Možnost super se musí volat před přístupem k this v konstruktoru odvozené třídy.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "Po vlastnosti super musí následovat seznam argumentů nebo přístup ke členu.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Přístup k vlastnostem pomocí super je povolený jenom v konstruktoru, členské funkci nebo členském přístupovém objektu odvozené třídy.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Na vlastnost this se nedá odkazovat v názvu počítaného prostředku.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Na vlastnost this se nedá odkazovat v modulu nebo těle oboru názvů.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Na vlastnost this se nedá odkazovat v inicializátoru statické vlastnosti.", + "this_cannot_be_referenced_in_current_location_2332": "Na vlastnost this se nedá odkazovat v aktuálním umístění.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "Možnost this má implicitně typ any, protože nemá anotaci typu.", + "true_for_ES2022_and_above_including_ESNext_6930": "„true“ pro ES2022 a vyšší, včetně ESNext.", + "true_if_composite_false_otherwise_6909": "„true“, pokud „composite“, „false“ jinak", + "true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false_6411": "Má hodnotu True, když „moduleResolution“ je „node16“, „nodenext“ nebo „bundler“; v opačném případě má hodnotu False.", + "tsc_Colon_The_TypeScript_Compiler_6922": "TSC: kompilátor TypeScriptu", + "type_Colon_6902": "typ:", + "unique_symbol_types_are_not_allowed_here_1335": "Typy unique symbol tady nejsou povolené.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Typy unique symbol jsou povolené jen u proměnných v příkazu proměnné.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Typy unique symbol nejde použít v deklaraci proměnné s názvem vazby.", + "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347": "Direktiva use strict se nedá použít se seznamem parametrů, které nejsou jednoduché.", + "use_strict_directive_used_here_1349": "Direktiva use strict se použila tady.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Příkazy with se ve funkčním bloku async nepovolují.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Příkazy with se ve striktním režimu nepovolují.", + "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057": "Implicitním výsledkem výrazu yield je typ any, protože v jeho obsahujícím generátoru chybí anotace návratového typu.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Výrazy yield nejde použít v inicializátoru parametru." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/de/diagnosticMessages.generated.json b/node_modules/typescript/lib/de/diagnosticMessages.generated.json new file mode 100644 index 00000000..76da00c7 --- /dev/null +++ b/node_modules/typescript/lib/de/diagnosticMessages.generated.json @@ -0,0 +1,2105 @@ +{ + "ALL_COMPILER_OPTIONS_6917": "ALLE COMPILEROPTIONEN", + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Ein Modifizierer \"{0}\" darf nicht mit einer Importdeklaration verwendet werden.", + "A_0_parameter_must_be_the_first_parameter_2680": "Ein \"{0}\"-Parameter muss der erste Parameter sein.", + "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039": "Ein JSDoc-Tag \"@template\" darf nicht auf ein \"@typedef\", \"@callback\" oder \"@overload\" folgen.", + "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033": "Ein JSDoc-Kommentar \"@typedef\" darf nicht mehrere @type-Tags enthalten.", + "A_bigint_literal_cannot_be_used_as_a_property_name_1539": "Ein \"bigint\"-Literal kann nicht als Eigenschaftenname verwendet werden.", + "A_bigint_literal_cannot_use_exponential_notation_1352": "Ein bigint-Literal kann keine exponentielle Notation verwenden.", + "A_bigint_literal_must_be_an_integer_1353": "Ein bigint-Literal muss eine ganze Zahl sein.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Ein Bindungsmusterparameter darf in einer Implementierungssignatur nicht optional sein.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Eine break-Anweisung darf nur in einer einschließenden iteration- oder switch-Anweisung verwendet werden.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Eine break-Anweisung kann nur zu einer Bezeichnung einer einschließenden Anweisung springen.", + "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522": "Eine Zeichenklasse darf kein reserviertes doppeltes Interpunktionszeichen enthalten. Wollten Sie mit einem umgekehrten Schrägstrich escapen?", + "A_character_class_range_must_not_be_bounded_by_another_character_class_1516": "Ein Zeichenklassenbereich darf nicht durch eine andere Zeichenklasse gebunden werden.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Eine Klasse kann nur einen Bezeichner/\"qualified-name\" mit optionalen Typargumenten implementieren.", + "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422": "Eine Klasse kann nur einen Objekttyp oder eine Schnittmenge von Objekttypen mit statisch bekannten Membern implementieren.", + "A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values_2863": "Eine Klasse kann einen primitiven Typ wie \"{0}\" nicht erweitern. Klassen können nur konstruierbare Werte erweitern.", + "A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types_2864": "Eine Klasse kann keinen primitiven Typ wie \"{0}\" implementieren. Es können nur andere benannte Objekttypen implementiert werden.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Eine Klassendeklaration ohne den default-Modifizierer muss einen Namen besitzen.", + "A_class_member_cannot_have_the_0_keyword_1248": "Ein Klassenmember darf nicht das Schlüsselwort \"{0}\" aufweisen.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Ein Kommaausdruck ist in einem berechneten Eigenschaftennamen unzulässig.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Ein berechneter Eigenschaftenname kann nicht aus seinem enthaltenden Typ auf einen Typparameter verweisen.", + "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166": "Ein berechneter Eigenschaftenname in einer Klasseneigenschaftsdeklaration muss einen einfachen Literaltyp oder den Typ \"unique symbol\" aufweisen.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Ein berechneter Eigenschaftenname in einer Methodenüberladung muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Ein berechneter Eigenschaftenname in einem Typliteral muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Ein berechneter Eigenschaftenname in einem Umgebungskontext muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Ein berechneter Eigenschaftenname in einer Schnittstelle muss auf einen Ausdruck verweisen, dessen Typ ein Literal oder ein \"unique symbol\"-Typ ist.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Ein berechneter Eigenschaftenname muss vom Typ \"string\", \"number\", \"symbol\" oder \"any\" sein.", + "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355": "Eine const-Assertion kann nur auf Verweise auf Enumerationsmember oder Zeichenfolgen-, Zahlen-, boolesche, Array- oder Objektliterale angewendet werden.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Auf einen const-Enumerationsmember kann nur mithilfe eines Zeichenfolgenliterals zugegriffen werden.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254": "Bei einem const-Initialisierer in einem Umgebungskontext muss es sich um ein Zeichenfolgen- oder um ein numerisches Literal oder um einen Verweis auf ein Enumerationsliteral handeln.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Ein Konstruktor darf keinen super-Aufruf enthalten, wenn seine Klasse \"null\" erweitert.", + "A_constructor_cannot_have_a_this_parameter_2681": "Ein Konstruktor darf keinen \"this\"-Parameter aufweisen.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Eine continue-Anweisung darf nur in einer einschließenden iteration-Anweisung verwendet werden.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Eine continue-Anweisung kann nur zu einer Bezeichnung einer einschließenden Iterationsanweisung springen.", + "A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_f_2846": "Eine Deklarationsdatei kann nicht ohne \"import type\" importiert werden. Wollten Sie stattdessen eine Implementierungsdatei \"{0}\" importieren?", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Ein declare-Modifizierer darf nicht in einem Kontext verwendet werden, der bereits ein Umgebungskontext ist.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Ein Decorator-Element kann nur für eine Methodenimplementierung und nicht für eine Überladung verwendet werden.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Eine default-Klausel darf nicht mehrmals in einer switch-Anweisung auftreten.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Ein Standardexport kann nur in einem Modul des Typs ECMAScript verwendet werden.", + "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258": "Ein Standardexport muss sich auf der obersten Ebene einer Datei- oder Moduldeklaration befinden.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Eine definitive Zuweisungsassertion \"!\" ist in diesem Kontext nicht zulässig.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Eine destrukturierende Deklaration muss einen Initialisierer besitzen.", + "A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_t_2712": "Ein dynamischer Importaufruf in ES5 erfordert den Konstruktor \"Promise\". Stellen Sie sicher, dass Sie über eine Deklaration für den Konstruktor \"Promise\" verfügen, oder schließen Sie \"ES2015\" in Ihre Option \"--lib\" ein.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Ein dynamischer Importaufruf gibt \"Promise\" zurück. Stellen Sie sicher, dass Sie über eine Deklaration für \"Promise\" verfügen, oder schließen Sie ES2015 in Ihre Option \"--lib\" ein.", + "A_file_cannot_have_a_reference_to_itself_1006": "Eine Datei darf keinen Verweis auf sich selbst enthalten.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Eine Funktion, die \"never\" zurückgibt, kann keinen erreichbaren Endpunkt besitzen.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Eine Funktion, die mit dem Schlüsselwort \"new\" aufgerufen wird, darf keinen \"this\"-Typ aufweisen, der \"void\" ist.", + "A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value_2355": "Eine Funktion, deren Typ weder als \"void\" noch als \"any\" deklariert ist, muss einen Wert zurückgeben.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Ein Generator darf keine void-Typanmerkung aufweisen.", + "A_get_accessor_cannot_have_parameters_1054": "Eine get-Zugriffsmethode darf keine Parameter haben.", + "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808": "Eine Get-Zugriffsmethode muss mindestens so zugänglich sein wie der Setter.", + "A_get_accessor_must_return_a_value_2378": "Eine get-Zugriffsmethode muss einen Wert zurückgeben.", + "A_label_is_not_allowed_here_1344": "Eine Bezeichnung ist hier nicht zulässig.", + "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Ein bezeichnetes Tupelelement wird optional mit einem Fragezeichen nach dem Namen und vor dem Doppelpunkt deklariert, nicht nach dem Typ.", + "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Ein bezeichnetes Tupelelement wird mit \"...\" vor dem Namen und nicht vor dem Typ als \"rest\" deklariert.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Ein zugeordneter Typ darf keine Eigenschaften oder Methoden deklarieren.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Ein Memberinitialisierer in einer Enumerationsdeklaration darf nicht auf Member verweisen, die anschließend deklariert werden (einschließlich Member, die in anderen Enumerationen definiert sind).", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Eine Mixin-Klasse benötigt einen Konstruktor mit einem einzelnen REST-Parameter des Typs \"any[]\".", + "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Eine Mixin-Klasse, die aus einer Typvariable mit einer abstrakten Konstruktsignatur erweitert wird, muss auch als \"abstract\" deklariert werden.", + "A_module_cannot_have_multiple_default_exports_2528": "Ein Modul darf nicht mehrere Standardexporte aufweisen.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Eine Namespacedeklaration darf sich nicht in einer anderen Datei als die Klasse oder Funktion befinden, mit der sie zusammengeführt wird.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Eine Namespacedeklaration darf nicht vor der Klasse oder Funktion positioniert werden, mit der sie zusammengeführt wird.", + "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235": "Eine Namespacedeklaration ist nur auf der obersten Ebene eines Namespaces oder Moduls zulässig.", + "A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_key_1540": "Eine Namespace-Deklaration darf nicht mit dem Schlüsselwort \"module\" deklariert werden. Verwenden Sie stattdessen das Schlüsselwort \"namespace\".", + "A_non_dry_build_would_build_project_0_6357": "Bei einem Build ohne das Flag \"-dry\" würde das Projekt \"{0}\" erstellt.", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Bei einem Build ohne das Flag \"-dry\" würden die folgenden Dateien gelöscht: {0}", + "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374": "Ein Build ohne das Flag \"-dry\" würde die Zeitstempel der Ausgabe von Projekt \"{0}\" aktualisieren.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Ein Parameterinitialisierer ist nur in einer Funktions- oder Konstruktorimplementierung zulässig.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Eine Parametereigenschaft darf nicht mithilfe eines rest-Parameters deklariert werden.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Eine Parametereigenschaft ist nur in einer Konstruktorimplementierung zulässig.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Eine Parametereigenschaft darf nicht mithilfe eines Bindungsmusters deklariert werden.", + "A_promise_must_have_a_then_method_1059": "Ein Zusage muss eine \"then\"-Methode aufweisen.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Eine Eigenschaft einer Klasse, deren Typ ein \"unique symbol\"-Typ ist, muss sowohl \"static\" als auch \"readonly\" sein.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Eine Eigenschaft einer Schnittstelle oder eines Typliterals, deren Typ ein \"unique symbol\"-Typ ist, muss \"readonly\" sein.", + "A_required_element_cannot_follow_an_optional_element_1257": "Ein erforderliches Element kann nicht auf ein optionales Element folgen.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Ein erforderlicher Parameter darf nicht auf einen optionalen Parameter folgen.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Ein rest-Element darf kein Bindungsmuster enthalten.", + "A_rest_element_cannot_follow_another_rest_element_1265": "Ein rest-Element darf nicht auf ein anderes rest-Element folgen.", + "A_rest_element_cannot_have_a_property_name_2566": "Ein rest-Element darf keinen Eigenschaftennamen aufweisen.", + "A_rest_element_cannot_have_an_initializer_1186": "Ein rest-Element darf keinen Initialisierer aufweisen.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Ein rest-Element muss das letzte Element in einem Destrukturierungsmuster sein.", + "A_rest_element_type_must_be_an_array_type_2574": "Ein rest-Elementtyp muss ein Arraytyp sein.", + "A_rest_parameter_cannot_be_optional_1047": "Ein rest-Parameter darf nicht optional sein.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Ein rest-Parameter darf keinen Initialisierer aufweisen.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Ein rest-Parameter muss in einer Parameterliste der letzte Eintrag sein.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Ein rest-Parameter muss ein Arraytyp sein.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Ein rest-Parameter oder ein Bindungsmuster dürfen kein nachgestelltes Komma aufweisen.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Eine return-Anweisung kann nur in einem Funktionstext verwendet werden.", + "A_return_statement_cannot_be_used_inside_a_class_static_block_18041": "Eine \"return\"-Anweisung kann nicht innerhalb eines statischen Klassenblocks verwendet werden.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Eine Reihe von Einträgen, die Importe zum Nachschlagen von Speicherorten in Bezug auf die \"baseUrl\" neu zuordnen.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Eine set-Zugriffsmethode darf keine Rückgabetypanmerkung aufweisen.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Eine set-Zugriffsmethode darf keinen optionalen Parameter aufweisen.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Eine set-Zugriffsmethode darf keinen rest-Parameter aufweisen.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Eine set-Zugriffsmethode muss genau einen Parameter aufweisen.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Ein set-Zugriffsmethodenparameter darf keinen Initialisierer aufweisen.", + "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556": "Ein Überfüllungsargument muss entweder einen Tupeltyp aufweisen oder an einen Restparameter übergeben werden.", + "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401": "Ein „super“ Aufruf muss eine Anweisung auf Stammebene innerhalb eines Konstruktors einer abgeleiteten Klasse sein, die initialisierte Eigenschaften, Parametereigenschaften oder private Bezeichner enthält.", + "A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_2376": "Ein „super“ Aufruf muss die erste Anweisung im Konstruktor sein, um auf „super“ oder „this“ zu verweisen, wenn eine abgeleitete Klasse initialisierte Eigenschaften, Parametereigenschaften oder private Bezeichner enthält.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Ein auf \"this\" basierender Typwächter ist nicht mit einem parameterbasierten Typwächter kompatibel.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Ein this-Typ ist nur in einem nicht statischen Member einer Klasse oder Schnittstelle verfügbar.", + "A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimM_1287": "Ein \"export\"-Modifizierer der obersten Ebene kann nicht für Wertdeklarationen in einem CommonJS-Modul verwendet werden, wenn \"verbatimModuleSyntax\" aktiviert ist.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Eine Datei \"tsconfig.json\" ist bereits definiert unter: \"{0}\".", + "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Ein Tupelelement kann nicht gleichzeitig als \"optional\" und als \"rest\" festgelegt werden.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Ein Tupeltyp kann nicht mit einem negativen Wert indiziert werden.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Typassertionsausdrücke sind in der linken Seite von Potenzierungsausdrücken nicht zulässig. Erwägen Sie, den Ausdruck in Klammern zu setzen.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Typliteraleigenschaften können keinen Initialisierer aufweisen.", + "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Ein reiner Typenimport kann einen Standardimport oder benannte Bindungen angeben, aber nicht beides.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Ein Typprädikat darf nicht auf einen rest-Parameter verweisen.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Ein Typprädikat darf nicht auf ein Element \"{0}\" in einem Bindungsmuster verweisen.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Ein Typprädikat ist nur an der Rückgabetypposition für Funktionen und Methoden zulässig.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Der Typ eines Typprädikats muss dem Typ seines Parameters zugewiesen werden können.", + "A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_w_1272": "Ein Typ, auf den in einer ergänzten Signatur verwiesen wird, muss mit „import type“ oder einem Namespaceimport importiert werden, wenn „isolatedModules“ und „emitDecoratorMetadata“ aktiviert sind.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Eine Variable, deren Typ ein \"unique symbol\"-Typ ist, muss \"const\" sein.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Ein yield-Ausdruck ist nur in einem Generatortext zulässig.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Auf die abstrakte Methode \"{0}\" in der Klasse \"{1}\" kann nicht über den super-Ausdruck zugegriffen werden.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Abstrakte Methoden können nur in einer abstrakten Klasse verwendet werden.", + "Abstract_properties_can_only_appear_within_an_abstract_class_1253": "Abstrakte Methoden können nur in einer abstrakten Klasse verwendet werden.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Auf die abstrakte Eigenschaft \"{0}\" in der Klasse \"{1}\" kann im Konstruktor nicht zugegriffen werden.", + "Accessibility_modifier_already_seen_1028": "Der Zugriffsmodifizierer ist bereits vorhanden.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Zugriffsmethoden sind nur verfügbar, wenn das Ziel ECMAScript 5 oder höher ist.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Beide Accessoren müssen abstrakt oder nicht abstrakt sein.", + "Add_0_to_unresolved_variable_90008": "Der nicht aufgelösten Variablen \"{0}.\" hinzufügen", + "Add_a_return_statement_95111": "return-Anweisung hinzufügen", + "Add_a_return_type_to_the_function_declaration_9031": "Fügen Sie der Funktionsdeklaration einen Rückgabetyp hinzu.", + "Add_a_return_type_to_the_function_expression_9030": "Fügen Sie dem Funktionsausdruck einen Rückgabetyp hinzu.", + "Add_a_return_type_to_the_get_accessor_declaration_9032": "Fügen Sie der get-Accessordeklaration einen Rückgabetyp hinzu.", + "Add_a_return_type_to_the_method_9034": "Der Methode einen Rückgabetyp hinzufügen", + "Add_a_type_annotation_to_the_parameter_0_9028": "Fügen Sie dem Parameter {0} eine Typanmerkung hinzu.", + "Add_a_type_annotation_to_the_property_0_9029": "Fügen Sie der Eigenschaft {0} eine Typanmerkung hinzu.", + "Add_a_type_annotation_to_the_variable_0_9027": "Fügen Sie der Variable {0} eine Typanmerkung hinzu.", + "Add_a_type_to_parameter_of_the_set_accessor_declaration_9033": "Fügen Sie dem Parameter der set-Accessordeklaration einen Typ hinzu.", + "Add_all_missing_async_modifiers_95041": "Alle fehlenden async-Modifizierer hinzufügen", + "Add_all_missing_attributes_95168": "Alle fehlenden Attribute hinzufügen", + "Add_all_missing_call_parentheses_95068": "Alle fehlenden Klammern in Aufrufen hinzufügen", + "Add_all_missing_function_declarations_95157": "Alle fehlenden Funktionsdeklarationen hinzufügen", + "Add_all_missing_imports_95064": "Alle fehlenden Importe hinzufügen", + "Add_all_missing_members_95022": "Alle fehlenden Member hinzufügen", + "Add_all_missing_override_modifiers_95162": "Alle fehlenden override-Modifizierer hinzufügen", + "Add_all_missing_parameters_95190": "Alle fehlenden Parameter hinzufügen", + "Add_all_missing_properties_95166": "Alle fehlenden Eigenschaften hinzufügen", + "Add_all_missing_return_statement_95114": "Alle fehlenden return-Anweisungen hinzufügen", + "Add_all_missing_super_calls_95039": "Alle fehlenden super-Aufrufe hinzufügen", + "Add_all_missing_type_annotations_90067": "Alle fehlenden Typanmerkungen hinzufügen", + "Add_all_optional_parameters_95193": "Alle optionalen Parameter hinzufügen", + "Add_annotation_of_type_0_90062": "Anmerkung vom Typ \"{0}\" hinzufügen", + "Add_async_modifier_to_containing_function_90029": "Async-Modifizierer zur enthaltenden Funktion hinzufügen", + "Add_await_95083": "\"await\" hinzufügen", + "Add_await_to_initializer_for_0_95084": "\"await\" zum Initialisierer für \"{0}\" hinzufügen", + "Add_await_to_initializers_95089": "\"await\" zu Initialisierern hinzufügen", + "Add_braces_to_arrow_function_95059": "Geschweifte Klammern zu Pfeilfunktion hinzufügen", + "Add_const_to_all_unresolved_variables_95082": "\"const\" zu allen nicht aufgelösten Variablen hinzufügen", + "Add_const_to_unresolved_variable_95081": "\"const\" zur nicht aufgelösten Variable hinzufügen", + "Add_definite_assignment_assertion_to_property_0_95020": "Definitive Zuweisungsassertion zu Eigenschaft \"{0}\" hinzufügen", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Allen nicht initialisierten Eigenschaften definitive Zuweisungsassertionen hinzufügen", + "Add_export_to_make_this_file_into_a_module_95097": "\"export {}\" hinzufügen, um diese Datei in ein Modul umzuwandeln", + "Add_extends_constraint_2211": "\"extends\"-Einschränkung hinzufügen", + "Add_extends_constraint_to_all_type_parameters_2212": "\"extends\"-Einschränkung zu allen Typparametern hinzufügen", + "Add_import_from_0_90057": "Import aus \"{0}\" hinzufügen", + "Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen", + "Add_initializer_to_property_0_95019": "Initialisierer zu Eigenschaft \"{0}\" hinzufügen", + "Add_initializers_to_all_uninitialized_properties_95027": "Allen nicht initialisierten Eigenschaften Initialisierer hinzufügen", + "Add_missing_attributes_95167": "Fehlende Attribute hinzufügen", + "Add_missing_call_parentheses_95067": "Fehlende Klammern in Aufrufen hinzufügen", + "Add_missing_comma_for_object_member_completion_0_95187": "Fügen Sie ein fehlendes Komma für die Vervollständigung von Objektmembern \"{0}\" hinzu.", + "Add_missing_enum_member_0_95063": "Fehlenden Enumerationsmember \"{0}\" hinzufügen", + "Add_missing_function_declaration_0_95156": "Fehlende Funktionsdeklaration \"{0}\" hinzufügen", + "Add_missing_new_operator_to_all_calls_95072": "Fehlenden new-Operator zu allen Aufrufen hinzufügen", + "Add_missing_new_operator_to_call_95071": "Fehlender new-Operator zum Aufruf hinzufügen", + "Add_missing_parameter_to_0_95188": "Fehlenden Parameter zu \"{0}\" hinzufügen", + "Add_missing_parameters_to_0_95189": "Fehlende Parameter zu \"{0}\" hinzufügen", + "Add_missing_properties_95165": "Fehlende Eigenschaften hinzufügen", + "Add_missing_super_call_90001": "Fehlenden super()-Aufruf hinzufügen", + "Add_missing_typeof_95052": "Fehlenden \"typeof\" hinzufügen", + "Add_names_to_all_parameters_without_names_95073": "Namen zu allen Parametern ohne Namen hinzufügen", + "Add_optional_parameter_to_0_95191": "Optionale Parameter zu \"{0}\" hinzufügen", + "Add_optional_parameters_to_0_95192": "Optionale Parameter zu \"{0}\" hinzufügen", + "Add_or_remove_braces_in_an_arrow_function_95058": "Geschweifte Klammern zu einer Pfeilfunktion hinzufügen oder daraus entfernen", + "Add_override_modifier_95160": "override-Modifizierer hinzufügen", + "Add_parameter_name_90034": "Parameternamen hinzufügen", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Allen nicht aufgelösten Variablen, die einem Membernamen entsprechen, Qualifizierer hinzufügen", + "Add_resolution_mode_import_attribute_95196": "Hinzufügen des Importattributs für den Auflösungsmodus (resolution-mode)", + "Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it_95197": "Hinzufügen des Importattributs für den Auflösungsmodus (resolution-mode) für alle reinen Typimporte, die dieses Attribut benötigen", + "Add_return_type_0_90063": "Rückgabetyp \"{0}\" hinzufügen", + "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035": "Fügen Sie diesem Ausdruck Erfüllungen und eine Typassertion hinzu (entspricht T als T), um den Typ explizit zu machen.", + "Add_satisfies_and_an_inline_type_assertion_with_0_90068": "Erfüllungen und eine Inlinetypassertion mit \"{0}\" hinzufügen", + "Add_to_all_uncalled_decorators_95044": "Allen nicht aufgerufenen Decorators \"()\" hinzufügen", + "Add_ts_ignore_to_all_error_messages_95042": "Allen Fehlermeldungen \"@ts-ignore\" hinzufügen", + "Add_undefined_to_a_type_when_accessed_using_an_index_6674": "Fügen Sie einem Typ „undefined“ hinzu, wenn über einen Index darauf zugegriffen wird.", + "Add_undefined_to_optional_property_type_95169": "„Undefined“ zum optionalen Eigenschaftstyp hinzufügen", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Allen nicht initialisierten Eigenschaften einen nicht definierten Typ hinzufügen", + "Add_undefined_type_to_property_0_95018": "undefined-Typ zu Eigenschaft \"{0}\" hinzufügen", + "Add_unknown_conversion_for_non_overlapping_types_95069": "Konvertierung \"unknown\" für Typen ohne Überschneidung hinzufügen", + "Add_unknown_to_all_conversions_of_non_overlapping_types_95070": "\"unknown\" zu allen Konvertierungen für Typen ohne Überschneidung hinzufügen", + "Add_void_to_Promise_resolved_without_a_value_95143": "\"Void\" zu ohne Wert aufgelöstem Promise hinzufügen", + "Add_void_to_all_Promises_resolved_without_a_value_95144": "\"Void\" allen ohne Wert aufgelösten Promises hinzufügen", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Das Hinzufügen einer \"tsconfig.json\"-Datei erleichtert die Organisation von Projekten, die sowohl TypeScript- als auch JavaScript-Dateien enthalten. Weitere Informationen finden Sie unter https://aka.ms/tsconfig.", + "All_declarations_of_0_must_have_identical_constraints_2838": "Alle Deklarationen von \"{0}\" müssen identische Modifizierer aufweisen.", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Alle Deklarationen von \"{0}\" müssen identische Modifizierer aufweisen.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Alle Deklarationen von \"{0}\" müssen identische Typparameter aufweisen.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Alle Deklarationen einer abstrakten Methode müssen aufeinanderfolgend sein.", + "All_destructured_elements_are_unused_6198": "Alle destrukturierten Elemente werden nicht verwendet.", + "All_imports_in_import_declaration_are_unused_6192": "Keiner der Importe in der Importdeklaration wird verwendet.", + "All_type_parameters_are_unused_6205": "Sämtliche Typparameter werden nicht verwendet.", + "All_variables_are_unused_6199": "Alle Variablen werden nicht verwendet.", + "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600": "Lassen Sie zu, dass JavaScript-Dateien Teil Ihres Programms werden. Verwenden Sie die Option „checkJS“, um Fehler aus diesen Dateien abzurufen.", + "Allow_accessing_UMD_globals_from_modules_6602": "Zugriff auf globale UMD-Bibliotheken aus Modulen zulassen", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Standardimporte von Modulen ohne Standardexport zulassen. Dies wirkt sich nicht auf die Codeausgabe aus, lediglich auf die Typprüfung.", + "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601": "\"Import x from y\" zulassen, wenn ein Modul keinen Standardexport hat.", + "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639": "Das Importieren von Hilfsfunktionen aus tslib einmal pro Projekt zulassen, anstatt sie pro Datei einzubeziehen.", + "Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noE_6407": "Importe dürfen TypeScript-Dateierweiterungen enthalten. Erfordert die Festlegung von \"--moduleResolution bundler\" und \"--noEmit\" oder \"--emitDeclarationOnly\".", + "Allow_javascript_files_to_be_compiled_6102": "Kompilierung von JavaScript-Dateien zulassen.", + "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691": "Lassen Sie zu, dass mehrere Ordner beim Auflösen von Modulen als ein Ordner behandelt werden.", + "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261": "Der bereits enthaltene Dateiname \"{0}\" unterscheidet sich vom Dateinamen \"{1}\" nur hinsichtlich der Groß-/Kleinschreibung.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Die Umgebungsmoduldeklaration darf keinen relativen Modulnamen angeben.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Umgebungsmodule dürfen nicht in andere Module oder Namespaces geschachtelt werden.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Ein AMD-Modul darf nicht mehrere Namenzuweisungen aufweisen.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Ein abstrakter Accessor kann keine Implementierung aufweisen.", + "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010": "Ein Zugriffsmodifizierer kann nicht mit einem privaten Bezeichner verwendet werden.", + "An_accessor_cannot_have_type_parameters_1094": "Eine Zugriffsmethode darf keine Typparameter aufweisen.", + "An_accessor_property_cannot_be_declared_optional_1276": "Eine Accessoreigenschaft kann nicht als optional deklariert werden.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Eine Umgebungsmoduldeklaration ist nur auf der obersten Ebene in einer Datei zulässig.", + "An_argument_for_0_was_not_provided_6210": "Für \"{0}\" wurde ein Argument nicht angegeben.", + "An_argument_matching_this_binding_pattern_was_not_provided_6211": "Es wurde kein Argument angegeben, das diesem Bindungsmuster entspricht.", + "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356": "Ein arithmetischer Operand muss vom Typ \"any\", \"number\" oder \"bigint\" oder ein Enumerationstyp sein.", + "An_arrow_function_cannot_have_a_this_parameter_2730": "Eine Pfeilfunktion darf keinen this-Parameter aufweisen.", + "An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_2705": "Eine Async-Funktion oder -Methode in ES5 erfordert den Konstruktor \"Promise\". Stellen Sie sicher, dass Sie über eine Deklaration für den Konstruktor \"Promise\" verfügen, oder schließen Sie \"ES2015\" in Ihre Option \"--lib\" ein.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Eine asynchrone Funktion oder Methode muss \"Promise\" zurückgeben. Stellen Sie sicher, dass Sie über eine Deklaration für \"Promise\" verfügen, oder schließen Sie ES2015 in Ihrer Option \"--lib\" ein.", + "An_async_iterator_must_have_a_next_method_2519": "Ein Async-Iterator muss eine \"next()\"-Async-Methode aufweisen.", + "An_element_access_expression_should_take_an_argument_1011": "Ein Ausdruck für einen Elementzugriff muss ein Argument verwenden.", + "An_enum_member_cannot_be_named_with_a_private_identifier_18024": "Ein Enumerationsmember kann nicht mit einem privaten Bezeichner benannt werden.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Ein Enumerationsmember darf keinen numerischen Namen besitzen.", + "An_enum_member_name_must_be_followed_by_a_or_1357": "Auf einen Namen eines Enumerationsmembers muss ein \",\", \"=\" oder \"}\" folgen.", + "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928": "Eine erweiterte Version dieser Informationen mit allen möglichen Compileroptionen", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Eine Exportzuweisung darf nicht in einem Modul mit anderen exportierten Elementen verwendet werden.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Eine Exportzuweisung darf nicht in einem Namespace verwendet werden.", + "An_export_assignment_cannot_have_modifiers_1120": "Eine Exportzuweisung darf keine Modifizierer besitzen.", + "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231": "Eine Exportzuweisung muss sich auf der obersten Ebene einer Datei- oder Moduldeklaration befinden.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474": "Eine Exportdeklaration kann nur auf der obersten Ebene eines Moduls verwendet werden.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233": "Eine Exportdeklaration kann nur auf der obersten Ebene eines Namespace oder Moduls verwendet werden.", + "An_export_declaration_cannot_have_modifiers_1193": "Eine Exportdeklaration darf keine Modifizierer besitzen.", + "An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolve_1283": "Eine \"export =\"-Deklaration muss auf einen reellen Wert verweisen, wenn \"verbatimModuleSyntax\" aktiviert ist, \"{0}\" wird jedoch in eine rein typbasierte Deklaration aufgelöst.", + "An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers__1282": "Eine \"export =\"-Deklaration muss auf einen Wert verweisen, wenn \"verbatimModuleSyntax\" aktiviert ist, \"{0}\" verweist jedoch auf einen Typ.", + "An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_1285": "\"export default\" muss auf einen reellen Wert verweisen, wenn \"verbatimModuleSyntax\" aktiviert ist, \"{0}\" wird jedoch in eine rein typbasierte Deklaration aufgelöst.", + "An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_1284": "Ein \"export default\" muss auf einen Wert verweisen, wenn \"verbatimModuleSyntax\" aktiviert ist, \"{0}\" verweist jedoch auf einen Typ.", + "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345": "Für einen Ausdruck vom Typ \"void\" kann nicht getestet werden, ob er wahr oder falsch ist.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Ein erweiterter Unicode-Escapewert muss zwischen 0x0 und 0x10FFFF (einschließlich) liegen.", + "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351": "Ein Bezeichner oder ein Schlüsselwort kann nicht direkt auf ein numerisches Literal folgen.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Eine Implementierung darf nicht in Umgebungskontexten deklariert werden.", + "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Ein Importalias kann nicht auf eine Deklaration verweisen, die mithilfe von \"export type\" exportiert wurde.", + "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Ein Importalias kann nicht auf eine Deklaration verweisen, die mithilfe von \"import type\" importiert wurde.", + "An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabl_1288": "Ein Importalias kann nicht in eine Typ- oder nur Typdeklaration aufgelöst werden, wenn \"verbatimModuleSyntax\" aktiviert ist.", + "An_import_alias_cannot_use_import_type_1392": "Ein Importalias kann \"import type\" nicht verwenden.", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473": "Eine Importdeklaration kann nur auf der obersten Ebene eines Moduls verwendet werden.", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232": "Eine Importdeklaration kann nur auf der obersten Ebene eines Namespace oder Moduls verwendet werden.", + "An_import_declaration_cannot_have_modifiers_1191": "Eine Importdeklaration darf keine Modifizierer besitzen.", + "An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled_5097": "Ein Importpfad kann nur mit einer \"{0}\"-Erweiterung enden, wenn \"allowImportingTsExtensions\" aktiviert ist.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Eine Indexsignatur darf keinen rest-Parameter besitzen.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Eine Indexsignatur darf kein nachstehendes Komma aufweisen.", + "An_index_signature_must_have_a_type_annotation_1021": "Eine Indexsignatur muss eine Typanmerkung besitzen.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Eine Indexsignatur muss genau einen Parameter besitzen.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Ein Indexsignaturparameter darf kein Fragezeichen aufweisen.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Ein Indexsignaturparameter darf keinen Zugriffsmodifizierer besitzen.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Ein Indexsignaturparameter darf keinen Initialisierer besitzen.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Ein Indexsignaturparameter muss eine Typanmerkung besitzen.", + "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Ein Indexsignaturparametertyp darf kein Literaltyp oder generischer Typ sein. Erwägen Sie stattdessen die Verwendung eines zugeordneten Objekttyps.", + "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Ein Parametertyp für die Indexsignatur muss \"string\", \"number\", \"symbol\" oder ein Vorlagenliteraltyp sein.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Auf einen Instanziierungsausdruck kann kein Eigenschaftenzugriff folgen.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Eine Schnittstelle kann nur einen Bezeichner/\"qualified-name\" mit optionalen Typargumenten erweitern.", + "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Eine Schnittstelle kann nur einen Objekttyp oder eine Schnittmenge von Objekttypen mit statisch bekannten Membern erweitern.", + "An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types_2840": "Eine Schnittstelle kann einen primitiven Typ wie \"{0}\" nicht erweitern. Es können nur andere benannte Objekttypen erweitert werden.", + "An_interface_property_cannot_have_an_initializer_1246": "Schnittstelleneigenschaften können keinen Initialisierer aufweisen.", + "An_iterator_must_have_a_next_method_2489": "Ein Iterator muss eine Methode \"next()\" besitzen.", + "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Bei Verwendung eines @jsx-Pragmas mit JSX-Fragmenten wird ein @jsxFrag-Pragma benötigt.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Ein Objektliteral darf nicht mehrere get-/set-Zugriffsmethoden mit dem gleichen Namen besitzen.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117": "Ein Objektliteral darf nicht über mehrere Eigenschaften mit demselben Namen verfügen.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Ein Objektliteral darf nicht eine Eigenschaft und eine Zugriffsmethode mit demselben Namen besitzen.", + "An_object_member_cannot_be_declared_optional_1162": "Ein Objektmember darf nicht als optional deklariert werden.", + "An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_han_2861": "Die Methode \"[Symbol.hasInstance]\" eines Objekts muss einen booleschen Wert zurückgeben, damit es auf der rechten Seite eines instanceof-Ausdrucks verwendet werden kann.", + "An_optional_chain_cannot_contain_private_identifiers_18030": "Eine optionale Kette kann keine privaten Bezeichner enthalten.", + "An_optional_element_cannot_follow_a_rest_element_1266": "Ein optionales Element darf nicht auf ein rest-Element folgen.", + "An_outer_value_of_this_is_shadowed_by_this_container_2738": "Ein äußerer Wert von \"this\" wird durch diesen Container verborgen.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Eine Überladungssignatur darf nicht als ein Generator deklariert werden.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Unäre Ausdrücke mit dem Operator \"{0}\" sind auf der linken Seite von Potenzierungsausdrücken nicht zulässig. Erwägen Sie, den Ausdruck in Klammern zu setzen.", + "Annotate_everything_with_types_from_JSDoc_95043": "Alle Funktionen mit Typen aus JSDoc kommentieren", + "Annotate_types_of_properties_expando_function_in_a_namespace_90071": "Erweiterungsfunktionstypen von Eigenschaften in einem Namespace mit Anmerkungen versehen", + "Annotate_with_type_from_JSDoc_95009": "Mit Typ aus JSDoc kommentieren", + "Another_export_default_is_here_2753": "Ein weiterer Exportstandardwert befindet sich hier.", + "Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_t_1528": "Jede Unicode-Eigenschaft, die möglicherweise mehr als ein einzelnes Zeichen enthalten würde, ist nur verfügbar, wenn das Flag \"Unicode Sets (v)\" festgelegt ist.", + "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518": "Alle Elemente, die möglicherweise mehr als einem einzelnen Zeichen entsprechen, sind innerhalb einer negierten Zeichenklasse ungültig.", + "Are_you_missing_a_semicolon_2734": "Fehlt ein Semikolon?", + "Argument_expression_expected_1135": "Es wurde ein Argumentausdruck erwartet.", + "Argument_for_0_option_must_be_Colon_1_6046": "Das Argument für die Option \"{0}\" muss \"{1}\" sein.", + "Argument_of_dynamic_import_cannot_be_spread_element_1325": "Das Argument des dynamischen Imports kann kein Überfüllungselement sein.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Das Argument vom Typ \"{0}\" kann dem Parameter vom Typ \"{1}\" nicht zugewiesen werden.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379": "Das Argument vom Typ „{0}“ kann dem Parameter vom Typ „{1}“ mit „exactOptionalPropertyTypes: true“ nicht zugewiesen werden. Erwägen Sie das Hinzufügen von „undefined“ zu den Typen der Zieleigenschaften.", + "Arguments_for_the_rest_parameter_0_were_not_provided_6236": "Es wurden keine Argumente für den rest-Parameter \"{0}\" angegeben.", + "Array_element_destructuring_pattern_expected_1181": "Ein Arrayelement-Destrukturierungsmuster wurde erwartet.", + "Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations_9018": "Arrays mit Verteilungselementen können nicht mit \"--isolatedDeclarations\" abgeleitet werden.", + "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775": "Assertionen erfordern, dass jeder Name im Aufrufziel mit einer expliziten Typanmerkung deklariert wird.", + "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776": "Assertionen erfordern, dass das Aufrufziel ein Bezeichner oder ein qualifizierter Name ist.", + "Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations__9023": "Das Zuweisen von Eigenschaften zu Funktionen ohne Deklaration wird mit \"--isolatedDeclarations\" nicht unterstützt. Fügen Sie eine explizite Deklaration für die Eigenschaften hinzu, die dieser Funktion zugewiesen sind.", + "Asterisk_Slash_expected_1010": "\"*/\" wurde erwartet.", + "At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9009": "Mindestens ein Accessor muss über eine explizite Typanmerkung mit „--isolatedDeclarations“ verfügen.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Erweiterungen für den globalen Bereich können nur in externen Modulen oder Umgebungsmoduldeklarationen direkt geschachtelt werden.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Erweiterungen für den globalen Bereich sollten den Modifizierer \"declare\" aufweisen, wenn sie nicht bereits in einem Umgebungskontext auftreten.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "In Projekt \"{0}\" ist die automatische Erkennung von Eingaben aktiviert. Es wird ein zusätzlicher Auflösungsdurchlauf für das Modul \"{1}\" unter Verwendung von Cachespeicherort \"{2}\" ausgeführt.", + "BUILD_OPTIONS_6919": "BUILDOPTIONEN", + "Backwards_Compatibility_6253": "Abwärtskompatibilität", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Basisklassenausdrücke können nicht auf Klassentypparameter verweisen.", + "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509": "Der Rückgabetyp \"{0}\" des Basiskonstruktors ist kein Objekttyp oder eine Schnittmenge von Objekttypen mit statisch bekannten Membern.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Basiskonstruktoren müssen alle den gleichen Rückgabetyp aufweisen.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Das Basisverzeichnis zum Auflösen nicht absoluter Modulnamen.", + "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737": "bigint-Literale sind nicht verfügbar, wenn die Zielversion niedriger ist als ES2020.", + "Binary_digit_expected_1177": "Es wurde eine Binärzahl erwartet.", + "Binding_element_0_implicitly_has_an_1_type_7031": "Das Bindungselement \"{0}\" weist implizit einen Typ \"{1}\" auf.", + "Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations_9019": "Bindungselemente können nicht direkt mit \"--isolatedDeclarations\" exportiert werden.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Die blockbezogene Variable \"{0}\" wurde vor ihrer Deklaration verwendet.", + "Build_a_composite_project_in_the_working_directory_6925": "Erstellen Sie ein zusammengesetztes Projekt im Arbeitsverzeichnis.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636": "Erstellen Sie alle Projekte, einschließlich der Projekte, die aktuell zu sein scheinen.", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Mindestens ein Projekt und die zugehörigen Abhängigkeiten erstellen, wenn veraltet", + "Build_option_0_requires_a_value_of_type_1_5073": "Die Buildoption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", + "Building_project_0_6358": "Projekt \"{0}\" wird erstellt...", + "Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any_6720": "Integrierte Iteratoren werden mit dem Typ \"TReturn\" vom Typ \"undefined\" anstelle von \"any\" instanziiert.", + "COMMAND_LINE_FLAGS_6921": "BEFEHLSZEILENFLAGS", + "COMMON_COMMANDS_6916": "ALLGEMEINE BEFEHLE", + "COMMON_COMPILER_OPTIONS_6920": "ALLGEMEINE COMPILEROPTIONEN", + "Call_decorator_expression_90028": "Decorator-Ausdruck aufrufen", + "Call_signature_return_types_0_and_1_are_incompatible_2202": "Die Rückgabetypen \"{0}\" und \"{1}\" der Aufrufsignatur sind nicht kompatibel.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Eine Aufrufsignatur ohne Rückgabetypanmerkung weist implizit einen any-Rückgabetyp auf.", + "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204": "Aufrufsignaturen ohne Argumente weisen inkompatible Rückgabetypen \"{0}\" und \"{1}\" auf.", + "Can_only_convert_logical_AND_access_chains_95142": "Es können nur Zugriffsketten mit logischem \"Und\" konvertiert werden.", + "Can_only_convert_named_export_95164": "Nur ein benannter Export kann konvertiert werden.", + "Can_only_convert_property_with_modifier_95137": "Die Eigenschaft kann nur mit einem Modifizierer konvertiert werden.", + "Can_only_convert_string_concatenations_and_string_literals_95154": "Nur Zeichenfolgenverkettungen und Zeichenfolgenliterale können konvertiert werden.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Der Zugriff auf \"{0}.{1}\" ist nicht möglich, da \"{0}\" ein Typ ist, aber kein Namespace. Wollten Sie den Typ der Eigenschaft \"{1}\" in \"{0}\" mit \"{0}[\"{1}\"]\" abrufen?", + "Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead_1281": "Auf \"{0}\" aus einer anderen Datei kann nicht ohne Qualifizierung zugegriffen werden, wenn \"{1}\" aktiviert ist. Verwenden Sie stattdessen \"{2}\".", + "Cannot_access_ambient_const_enums_when_0_is_enabled_2748": "Auf Umgebungskonstantenenumerationen kann nicht zugegriffen werden, wenn \"{0}\" aktiviert ist.", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Ein Konstruktortyp \"{0}\" kann nicht einem Konstruktortyp \"{1}\" zugewiesen werden.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Ein abstrakter Konstruktortyp kann nicht einem nicht abstrakten Konstruktortyp zugewiesen werden.", + "Cannot_assign_to_0_because_it_is_a_class_2629": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich um eine Klasse handelt.", + "Cannot_assign_to_0_because_it_is_a_constant_2588": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich um eine Konstante handelt.", + "Cannot_assign_to_0_because_it_is_a_function_2630": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich um eine Funktion handelt.", + "Cannot_assign_to_0_because_it_is_a_namespace_2631": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich um einen Namespace handelt.", + "Cannot_assign_to_0_because_it_is_a_read_only_property_2540": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich um eine schreibgeschützte Eigenschaft handelt.", + "Cannot_assign_to_0_because_it_is_an_enum_2628": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich um eine Enumeration handelt.", + "Cannot_assign_to_0_because_it_is_an_import_2632": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich um einen Import handelt.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Eine Zuweisung zu \"{0}\" ist nicht möglich, weil es sich nicht um eine Variable handelt.", + "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803": "Eine Zuweisung zur private Methode \"{0}\" ist nicht möglich. In private Methoden kann nicht geschrieben werden.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Das Modul \"{0}\" kann nicht erweitert werden, weil es in eine Nicht-Modulentität aufgelöst wird.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Das Modul \"{0}\" kann nicht mit Wertexporten vergrößert werden, da es zu einer Entität aufgelöst wird, die kein Modul darstellt.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Module können nur mithilfe der Option \"{0}\" kompiliert werden, wenn die Kennzeichnung \"-module\" den Wert \"amd\" oder \"system\" aufweist.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Eine Instanz der abstrakten Klasse kann nicht erstellt werden.", + "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766": "Die Iteration kann nicht an einen Wert delegiert werden, weil die next-Methode des zugehörigen Iterators den Typ \"{1}\" erwartet, aber der enthaltende Generator immer \"{0}\" sendet.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "\"{0}\" kann nicht exportiert werden. Nur lokale Deklarationen können aus einem Modul exportiert werden.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Eine Klasse \"{0}\" kann nicht erweitert werden. Der Klassenkonstruktor ist als privat markiert.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Eine Schnittstelle \"{0}\" kann nicht erweitert werden. Meinten Sie \"implements\"?", + "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081": "Im angegebenen Verzeichnis \"{0}\" wurde keine Datei \"tsconfig.json\" gefunden.", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Im angegebenen Verzeichnis \"{0}\" wurde keine \"tsconfig.json\"-Datei gefunden.", + "Cannot_find_global_type_0_2318": "Der globale Typ \"{0}\" wurde nicht gefunden.", + "Cannot_find_global_value_0_2468": "Der globale Wert \"{0}\" wurde nicht gefunden.", + "Cannot_find_lib_definition_for_0_2726": "Die Bibliotheksdefinition für \"{0}\" wurde nicht gefunden.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "Die Bibliotheksdefinition für \"{0}\" wurde nicht gefunden. Meinten Sie \"{1}\"?", + "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732": "Das Modul \"{0}\" wurde nicht gefunden. Erwägen Sie die Verwendung von \"--resolveJsonModule\" zum Importieren eines Moduls mit der Erweiterung \".json\".", + "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_t_2792": "Das Modul \"{0}\" wurde nicht gefunden. Möchten Sie die Option \"moduleResolution\" auf \"nodenext\" festlegen oder Aliase zur Option \"paths\" hinzufügen?", + "Cannot_find_module_0_or_its_corresponding_type_declarations_2307": "Das Modul \"{0}\" oder die zugehörigen Typdeklarationen wurden nicht gefunden.", + "Cannot_find_name_0_2304": "Der Name \"{0}\" wurde nicht gefunden.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie \"{1}\"?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie den Instanzmember \"this.{0}\"?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie den statischen Member \"{1}.{0}\"?", + "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311": "Der Name „{0}“ wurde nicht gefunden. Wollten Sie dies in eine asynchrone Funktion schreiben?", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Ihre Zielbibliothek ändern? Ändern Sie die Compileroption \"lib\" in \"{1}\" oder höher.", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Ihre Zielbibliothek ändern? Ändern Sie die Compileroption \"lib\" so ab, dass sie \"dom\" enthält.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2867": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für Bun installieren? Versuchen Sie es mit \"npm i --save-dev @types/bun\".", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2868": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für Bun installieren? Versuchen Sie es mit \"npm i --save-dev @types/bun\", und fügen Sie dann dem Typenfeld in Ihrer tsconfig-Datei \"bun\" hinzu.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für einen Test Runner installieren? Versuchen Sie es mit \"npm i --save-dev @types/jest\" oder \"npm i --save-dev @types/mocha\".", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für einen Test Runner installieren? Versuchen Sie es mit \"npm i --save-dev @types/jest\" oder \"npm i --save-dev @types/mocha\", und fügen Sie dann dem Typenfeld in Ihrer tsconfig-Datei \"jest\" oder \"mocha\" hinzu.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für jQuery installieren? Versuchen Sie es mit \"npm i --save-dev @types/jquery\".", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für jQuery installieren? Versuchen Sie es mit \"npm i --save-dev @types/jquery\", und fügen Sie dann dem Typenfeld in Ihrer tsconfig-Datei \"jquery\" hinzu.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für Node installieren? Versuchen Sie es mit \"npm i --save-dev @types/node\".", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für Node installieren? Versuchen Sie es mit \"npm i --save-dev @types/node\", und fügen Sie dann dem Typenfeld in Ihrer tsconfig-Datei \"node\" hinzu.", + "Cannot_find_namespace_0_2503": "Der Namespace \"{0}\" wurde nicht gefunden.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Namespace \"{0}\" wurde nicht gefunden. Meinten Sie \"{1}\"?", + "Cannot_find_parameter_0_1225": "Der Parameter \"{0}\" wurde nicht gefunden.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Das gemeinsame Unterverzeichnis für die Eingabedateien wurde nicht gefunden.", + "Cannot_find_type_definition_file_for_0_2688": "Die Typdefinitionsdatei für \"{0}\" wurde nicht gefunden.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Typdeklarationsdateien können nicht importiert werden. Importieren Sie ggf. \"{0}\" anstelle von \"{1}\".", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Die Variable \"{0}\" mit dem äußeren Bereich im gleichen Bereich wie die Deklaration \"{1}\" mit dem Blockbereich kann nicht initialisiert werden.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Ein Objekt, das möglicherweise NULL ist, kann nicht aufgerufen werden.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Ein Objekt, das möglicherweise NULL oder nicht definiert ist, kann nicht aufgerufen werden.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Ein Objekt, das möglicherweise nicht definiert ist, kann nicht aufgerufen werden.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765": "Der Wert kann nicht durchlaufen werden, weil die next-Methode des zugehörigen Iterators den Typ \"{1}\" erwartet, die Arraydestrukturierung aber immer \"{0}\" sendet.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Der Wert kann nicht durchlaufen werden, weil die next-Methode des zugehörigen Iterators den Typ \"{1}\" erwartet, die Arrayverteilung aber immer \"{0}\" sendet.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Der Wert kann nicht durchlaufen werden, weil die next-Methode des zugehörigen Iterators den Typ \"{1}\" erwartet, \"for-of\" aber immer \"{0}\" sendet.", + "Cannot_move_statements_to_the_selected_file_95183": "Anweisungen können nicht in die ausgewählte Datei verschoben werden.", + "Cannot_move_to_file_selected_file_is_invalid_95179": "Verschieben in Datei nicht möglich, die ausgewählte Datei ist ungültig", + "Cannot_read_file_0_5083": "Die Datei \"{0}\" kann nicht gelesen werden.", + "Cannot_read_file_0_Colon_1_5012": "Die Datei \"{0}\" kann nicht gelesen werden: {1}", + "Cannot_redeclare_block_scoped_variable_0_2451": "Die blockbezogene Variable \"{0}\" Blockbereich kann nicht erneut deklariert werden.", + "Cannot_redeclare_exported_variable_0_2323": "Die exportierte Variable \"{0}\" kann nicht erneut deklariert werden.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Der Bezeichner \"{0}\" in der Catch-Klausel kann nicht erneut deklariert werden.", + "Cannot_start_a_function_call_in_a_type_annotation_1441": "Kann in einer Typanmerkung keinen Funktionsaufruf starten.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "JSX kann nur verwendet werden, wenn das Flag \"-jsx\" angegeben wird.", + "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled_1269": "\"export import\" kann nicht für einen Typ oder einen reinen Typnamespace verwendet werden, wenn {0} aktiviert ist.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Es können keine imports-, exports- oder module-Erweiterungen verwendet werden, wenn \"-module\" den Wert \"none\" aufweist.", + "Cannot_use_namespace_0_as_a_type_2709": "Der Namespace \"{0}\" kann nicht als Typ verwendet werden.", + "Cannot_use_namespace_0_as_a_value_2708": "Der Namespace \"{0}\" kann nicht als Wert verwendet werden.", + "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816": "\"This\" kann nicht in einem statischen Eigenschafteninitialisierer einer ergänzten Klasse verwendet werden.", + "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377": "Die Datei \"{0}\" kann nicht geschrieben werden, weil hierdurch die TSBUILDINFO-Datei überschrieben wird, die durch das referenzierte Projekt \"{1}\" generiert wird.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Die Datei \"{0}\" kann nicht geschrieben werden, da sie durch mehrere Eingabedateien überschrieben würde.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Die Datei \"{0}\" kann nicht geschrieben werden, da sie eine Eingabedatei überschreiben würde.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Die Variable der Catch-Klausel darf keinen Initialisierer aufweisen.", + "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196": "Die Anmerkung des Variablentyps der catch-Klausel muss \"any\" oder \"unknown\" lauten, sofern angegeben.", + "Change_0_to_1_90014": "\"{0}\" in \"{1}\" ändern", + "Change_all_extended_interfaces_to_implements_95038": "Alle erweiterten Schnittstellen in \"implements\" ändern", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Alle jsdoc-style-Typen in TypeScript ändern", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Alle jsdoc-style-Typen in TypeScript ändern (und Nullable-Typen \"| undefined\" hinzufügen)", + "Change_extends_to_implements_90003": "\"extends\" in \"implements\" ändern", + "Change_spelling_to_0_90022": "Schreibweise in \"{0}\" ändern", + "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700": "Suchen Sie nach Klasseneigenschaften, die im Konstruktor deklariert, aber nicht festgelegt sind.", + "Check_side_effect_imports_6806": "Überprüfen Sie die Nebeneffektimporte.", + "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697": "Überprüfen Sie, ob die Argumente für die Methoden „bind“, „call“ und „apply“ mit der ursprünglichen Funktion übereinstimmen.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Es wird überprüft, ob \"{0}\" das längste übereinstimmende Präfix für \"{1}\"–\"{2}\" ist.", + "Circular_definition_of_import_alias_0_2303": "Zirkuläre Definition des Importalias \"{0}\".", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Eine Zirkularität wurde beim Auflösen der Konfiguration erkannt: {0}", + "Circularity_originates_in_type_at_this_location_2751": "Die Zirkularität stammt vom Typ an diesem Standort.", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "Die Klasse \"{0}\" definiert die Instanzmember-Zugriffsmethode \"{1}\", die erweiterte Klasse \"{2}\" definiert diesen jedoch als Instanzmemberfunktion.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "Die Klasse \"{0}\" definiert die Instanzmember-Zugriffsmethode \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Instanzmember-Zugriffsmethode.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Die Klasse \"{0}\" definiert die Instanzmembereigenschaft \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Instanzmemberfunktion.", + "Class_0_incorrectly_extends_base_class_1_2415": "Die Klasse \"{0}\" erweitert fälschlicherweise die Basisklasse \"{1}\".", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Die Klasse \"{0}\" implementiert fälschlicherweise die Klasse \"{1}\". Wollten Sie \"{1}\" erweitern und ihre Member als Unterklasse vererben?", + "Class_0_incorrectly_implements_interface_1_2420": "Die Klasse \"{0}\" implementiert fälschlicherweise die Schnittstelle \"{1}\".", + "Class_0_used_before_its_declaration_2449": "Klasse \"{0}\", die vor der Deklaration verwendet wurde.", + "Class_constructor_may_not_be_a_generator_1368": "Der Klassenkonstruktor darf kein Generator sein.", + "Class_constructor_may_not_be_an_accessor_1341": "Der Klassenkonstruktor darf kein Accessor sein.", + "Class_declaration_cannot_implement_overload_list_for_0_2813": "Die Klassendeklaration kann die Überladungsliste für \"{0}\" nicht implementieren.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Klassendeklarationen dürfen maximal ein \"@augments\"- oder \"@extends\"-Tag aufweisen.", + "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Decorator-Elemente von Klassen können nicht mit einem statischen privaten Bezeichner verwendet werden. Erwägen Sie, das experimentelle Decorator-Element zu entfernen.", + "Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super_2855": "Auf das von der übergeordneten Klasse definierte Klassenfeld \"{0}\" kann in der untergeordneten Klasse nicht über \"super\" zugegriffen werden.", + "Class_name_cannot_be_0_2414": "Der Klassenname darf nicht \"{0}\" sein.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Der Klassenname darf nicht \"Object\" lauten, wenn ES5 mit Modul \"{0}\" als Ziel verwendet wird.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Die statische Seite der Klasse \"{0}\" erweitert fälschlicherweise die statische Seite der Basisklasse \"{1}\".", + "Classes_can_only_extend_a_single_class_1174": "Klassen dürfen nur eine einzelne Klasse erweitern.", + "Classes_may_not_have_a_field_named_constructor_18006": "Klassen dürfen kein Feld mit dem Namen \"constructor\" aufweisen.", + "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210": "Code, der in einer Klasse enthalten ist, wird im Strict-Modus von JavaScript ausgewertet, der diese Verwendung von \"{0}\" nicht zulässt. Weitere Informationen finden Sie unter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.", + "Command_line_Options_6171": "Befehlszeilenoptionen", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Kompilieren Sie das dem Pfad zugewiesene Projekt zu dessen Konfigurationsdatei oder zu einem Ordner mit der Datei \"tsconfig.json\".", + "Compiler_Diagnostics_6251": "Compilerdiagnose", + "Compiler_option_0_cannot_be_given_an_empty_string_18051": "Die Compileroption \"{0}\" darf keine leere Zeichenfolge erhalten.", + "Compiler_option_0_expects_an_argument_6044": "Die Compileroption \"{0}\" erwartet ein Argument.", + "Compiler_option_0_may_not_be_used_with_build_5094": "Die Compileroption \"--{0}\" darf nicht mit \"--build\" verwendet werden.", + "Compiler_option_0_may_only_be_used_with_build_5093": "Die Compileroption \"--{0}\" darf nur mit \"--build\" verwendet werden.", + "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124": "Die Compileroption „{0}“ des Werts „{1}“ ist instabil. Verwenden Sie „Nightly TypeScript“, um diesen Fehler zu beheben. Versuchen Sie die Aktualisierung mit „npm install -D typescript@next“ durchzuführen.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Die Compileroption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Der Compiler reserviert den Namen \"{0}\", wenn er einen privaten Bezeichner für Vorgängerversionen ausgibt.", + "Compiles_the_TypeScript_project_located_at_the_specified_path_6927": "Kompiliert das sich am angegebenen Pfad befindliche TypeScript-Projekt.", + "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923": "Kompiliert das aktuelle Projekt (tsconfig.json im Arbeitsverzeichnis.)", + "Compiles_the_current_project_with_additional_settings_6929": "Kompiliert das aktuelle Projekt mit zusätzlichen Einstellungen.", + "Completeness_6257": "Vollständigkeit", + "Composite_projects_may_not_disable_declaration_emit_6304": "In zusammengesetzten Projekten kann die Deklarationsausgabe nicht deaktiviert werden.", + "Composite_projects_may_not_disable_incremental_compilation_6379": "Zusammengesetzte Projekte dürfen die inkrementelle Kompilierung nicht deaktivieren.", + "Computed_from_the_list_of_input_files_6911": "Aus der Liste der Eingabedateien berechnet", + "Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedD_9014": "Berechnete Eigenschaften müssen Zahlen- oder Zeichenfolgenliterale, Variablen oder gepunktete Ausdrücke mit \"--isolatedDeclarations\" sein.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Berechnete Eigenschaftennamen sind in Enumerationen unzulässig.", + "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038": "Berechnete Eigenschaftsnamen für Klassen- oder Objektliterale können nicht mit \"--isolatedDeclarations\" abgeleitet werden.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Berechnete Werte sind in einer Enumeration mit Membern mit Zeichenfolgenwerten nicht zulässig.", + "Concatenate_and_emit_output_to_single_file_6001": "Verketten und Ausgabe in einer Datei speichern.", + "Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports_6410": "Bedingungen, die zusätzlich zu den konfliktlöserspezifischen Standardwerten beim Auflösen von Importen festgelegt werden sollen.", + "Conflicts_are_in_this_file_6201": "In dieser Datei liegen Konflikte vor.", + "Consider_adding_a_declare_modifier_to_this_class_6506": "Erwägen Sie, dieser Klasse einen declare-Modifizierer hinzuzufügen.", + "Construct_signature_return_types_0_and_1_are_incompatible_2203": "Die Rückgabetypen \"{0}\" und \"{1}\" der Konstruktsignatur sind nicht kompatibel.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Eine Konstruktsignatur ohne Rückgabetypanmerkung weist implizit einen any-Rückgabetyp auf.", + "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205": "Konstruktsignaturen ohne Argumente weisen inkompatible Rückgabetypen \"{0}\" und \"{1}\" auf.", + "Constructor_implementation_is_missing_2390": "Die Konstruktorimplementierung fehlt.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Der Konstruktor der Klasse \"{0}\" ist privat. Auf ihn kann nur innerhalb der Klassendeklaration zugegriffen werden.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Der Konstruktor der Klasse \"{0}\" ist geschützt. Auf ihn kann nur innerhalb der Klassendeklaration zugegriffen werden.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386": "Die Typnotation des Konstruktors muss in Klammern gesetzt werden, wenn sie in einem Union-Typ verwendet wird.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388": "Die Typnotation des Konstruktors muss in Klammern gesetzt werden, wenn sie in einem Intersection-Typ verwendet wird.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktoren für abgeleitete Klassen müssen einen Aufruf \"super\" enthalten.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Die enthaltene Datei wird nicht angegeben, und das Stammverzeichnis kann nicht ermittelt werden. Die Suche im Ordner \"node_modules\" wird übersprungen.", + "Containing_function_is_not_an_arrow_function_95128": "Die enthaltende Funktion ist keine Pfeilfunktion.", + "Control_what_method_is_used_to_detect_module_format_JS_files_1475": "Steuern Sie, welche Methode zum Erkennen von JS-Dateien im Modulformat verwendet wird.", + "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352": "Die Konvertierung des Typs \"{0}\" in den Typ \"{1}\" kann ein Fehler sein, weil die Typen keine ausreichende Überschneidung aufweisen. Wenn dies beabsichtigt war, konvertieren Sie den Ausdruck zuerst in \"unknown\".", + "Convert_0_to_1_in_0_95003": "\"{0}\" in \"{1} in {0}\" konvertieren", + "Convert_0_to_mapped_object_type_95055": "\"{0}\" in zugeordneten Objekttyp konvertieren", + "Convert_all_const_to_let_95102": "Alle \"const\" in \"let\" konvertieren", + "Convert_all_constructor_functions_to_classes_95045": "Alle Konstruktorfunktionen in Klassen konvertieren", + "Convert_all_invalid_characters_to_HTML_entity_code_95101": "Alle ungültigen Zeichen in HTML-Entitätscode konvertieren", + "Convert_all_re_exported_types_to_type_only_exports_1365": "Alle erneut exportierten Typen in reine Typenexporte konvertieren", + "Convert_all_require_to_import_95048": "Alle Aufrufe von \"require\" in \"import\" konvertieren", + "Convert_all_to_async_functions_95066": "Alle in asynchrone Funktionen konvertieren", + "Convert_all_to_bigint_numeric_literals_95092": "Alle in numerische bigint-Literale konvertieren", + "Convert_all_to_default_imports_95035": "Alle in Standardimporte konvertieren", + "Convert_all_type_literals_to_mapped_type_95021": "Alle Typliterale in einen zugeordneten Typ konvertieren", + "Convert_all_typedef_to_TypeScript_types_95177": "Konvertieren Sie alle typedef in TypeScript-Typen.", + "Convert_arrow_function_or_function_expression_95122": "Pfeilfunktion oder Funktionsausdruck konvertieren", + "Convert_const_to_let_95093": "\"const\" in \"let\" konvertieren", + "Convert_default_export_to_named_export_95061": "Standardexport in benannten Export konvertieren", + "Convert_function_declaration_0_to_arrow_function_95106": "Funktionsdeklaration \"{0}\" in Pfeilfunktion konvertieren", + "Convert_function_expression_0_to_arrow_function_95105": "Funktionsausdruck \"{0}\" in Pfeilfunktion konvertieren", + "Convert_function_to_an_ES2015_class_95001": "Funktion in eine ES2015-Klasse konvertieren", + "Convert_invalid_character_to_its_html_entity_code_95100": "Ungültiges Zeichen in entsprechenden HTML-Entitätscode konvertieren", + "Convert_named_export_to_default_export_95062": "Benannten Export in Standardexport konvertieren", + "Convert_named_imports_to_default_import_95170": "Konvertieren benannter Importe in Standardimporte", + "Convert_named_imports_to_namespace_import_95057": "Benannte Importe in Namespaceimport konvertieren", + "Convert_namespace_import_to_named_imports_95056": "Namespaceimport in benannte Importe konvertieren", + "Convert_overload_list_to_single_signature_95118": "Überladungsliste in einzelne Signatur konvertieren", + "Convert_parameters_to_destructured_object_95075": "Parameter in destrukturiertes Objekt konvertieren", + "Convert_require_to_import_95047": "\"require\" in \"import\" konvertieren", + "Convert_to_ES_module_95017": "In ES-Modul konvertieren", + "Convert_to_a_bigint_numeric_literal_95091": "In numerisches bigint-Literal konvertieren", + "Convert_to_anonymous_function_95123": "In anonyme Funktion konvertieren", + "Convert_to_arrow_function_95125": "In Pfeilfunktion konvertieren", + "Convert_to_async_function_95065": "In asynchrone Funktion konvertieren", + "Convert_to_default_import_95013": "In Standardimport konvertieren", + "Convert_to_named_function_95124": "In benannte Funktion konvertieren", + "Convert_to_optional_chain_expression_95139": "In optionalen Kettenausdruck konvertieren", + "Convert_to_template_string_95096": "In Vorlagenzeichenfolge konvertieren", + "Convert_to_type_only_export_1364": "In reinen Typenexport konvertieren", + "Convert_typedef_to_TypeScript_type_95176": "Konvertieren Sie typedef in den TypeScript-Typ.", + "Corrupted_locale_file_0_6051": "Die Gebietsschemadatei \"{0}\" ist beschädigt.", + "Could_not_convert_to_anonymous_function_95153": "Die Konvertierung in eine anonyme Funktion ist nicht möglich.", + "Could_not_convert_to_arrow_function_95151": "Die Konvertierung in eine Pfeilfunktion ist nicht möglich.", + "Could_not_convert_to_named_function_95152": "Die Konvertierung in eine benannte Funktion ist nicht möglich.", + "Could_not_determine_function_return_type_95150": "Der Rückgabetyp der Funktion konnte nicht bestimmt werden.", + "Could_not_find_a_containing_arrow_function_95127": "Es wurde keine enthaltende Pfeilfunktion gefunden.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Es wurde keine Deklarationsdatei für das Modul \"{0}\" gefunden. \"{1}\" weist implizit den Typ \"any\" auf.", + "Could_not_find_convertible_access_expression_95140": "Kein konvertierbarer Zugriffsausdruck gefunden", + "Could_not_find_export_statement_95129": "Die Exportanweisung wurde nicht gefunden.", + "Could_not_find_import_clause_95131": "Die Importklausel wurde nicht gefunden.", + "Could_not_find_matching_access_expressions_95141": "Keine übereinstimmenden Zugriffsausdrücke gefunden", + "Could_not_find_name_0_Did_you_mean_1_2570": "Der Name \"{0}\" wurde nicht gefunden. Meinten Sie \"{1}\"?", + "Could_not_find_namespace_import_or_named_imports_95132": "Der Namespaceimport oder benannte Importe wurden nicht gefunden.", + "Could_not_find_property_for_which_to_generate_accessor_95135": "Die Eigenschaft, für die die Zugriffsmethode generiert werden soll, wurde nicht gefunden.", + "Could_not_find_variable_to_inline_95185": "Die Variable zum Inlinevorgang wurde nicht gefunden.", + "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Der Pfad \"{0}\" mit den Erweiterungen konnte nicht aufgelöst werden: {1}.", + "Could_not_write_file_0_Colon_1_5033": "Die Datei \"{0}\" konnte nicht geschrieben werden. {1}.", + "Create_source_map_files_for_emitted_JavaScript_files_6694": "Erstellen Sie Quellzuordnungsdateien für ausgegebene JavaScript-Dateien.", + "Create_sourcemaps_for_d_ts_files_6614": "Erstellen Sie Quellzuordnungen für d.ts-Dateien.", + "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926": "Erstellt eine tsconfig.json mit den empfohlenen Einstellungen im Arbeitsverzeichnis.", + "DIRECTORY_6038": "VERZEICHNIS", + "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537": "Dezimale Escapesequenzen und Rückvektoren sind in einer Zeichenklasse nicht zulässig.", + "Decimals_with_leading_zeros_are_not_allowed_1489": "Dezimalstellen mit führenden Nullen sind nicht zulässig.", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "Die Deklaration erweitert die Deklaration in einer anderen Datei. Dieser Vorgang kann nicht serialisiert werden.", + "Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_support_9026": "Die Deklarationsausgabe für diese Datei erfordert, dass dieser Import für Augmentationen beibehalten wird. Dies wird mit \"--isolatedDeclarations\" nicht unterstützt.", + "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "Zur Deklarationsausgabe für diese Datei muss der private Name \"{0}\" verwendet werden. Eine explizite Typanmerkung kann die Deklarationsausgabe freigeben.", + "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "Zur Deklarationsausgabe für diese Datei muss der private Name \"{0}\" aus dem Modul \"{1}\" verwendet werden. Eine explizite Typanmerkung kann die Deklarationsausgabe freigeben.", + "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_sup_9025": "Die Deklarationsausgabe für diesen Parameter erfordert das implizit undefinierte Hinzufügen zum Typ. Dies wird mit „--isolatedDeclarations“ nicht unterstützt.", + "Declaration_expected_1146": "Es wurde eine Deklaration erwartet.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Der Deklarationsname steht in Konflikt mit dem integrierten globalen Bezeichner \"{0}\".", + "Declaration_or_statement_expected_1128": "Es wurde eine Deklaration oder Anweisung erwartet.", + "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809": "Es wurde eine Deklaration oder Anweisung erwartet. Dieses Gleichheitszeichen (=) folgt auf einen Anweisungsblock. Wenn Sie daher eine Destrukturierungszuweisung schreiben möchten, müssen Sie möglicherweise die gesamte Zuweisung in runde Klammern einschließen.", + "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264": "Deklarationen mit definitiven Zuweisungsassertionen müssen auch Typanmerkungen aufweisen.", + "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263": "Deklarationen mit Initialisierern dürfen keine definitiven Zuweisungsassertionen aufweisen.", + "Declare_a_private_field_named_0_90053": "Deklarieren Sie ein privates Feld mit dem Namen \"{0}\".", + "Declare_method_0_90023": "Methode \"{0}\" deklarieren", + "Declare_private_method_0_90038": "Private Methode \"{0}\" deklarieren", + "Declare_private_property_0_90035": "Private Eigenschaft \"{0}\" deklarieren", + "Declare_property_0_90016": "Eigenschaft \"{0}\" deklarieren", + "Declare_static_method_0_90024": "Statische Methode \"{0}\" deklarieren", + "Declare_static_property_0_90027": "Statische Eigenschaft \"{0}\" deklarieren", + "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270": "Der Rückgabetyp der Decorator-Funktion „{0}“ kann dem Typ „{1}“ nicht zugewiesen werden.", + "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271": "Der Rückgabetyp der Decorator-Funktion ist „{0}“, es wird jedoch erwartet, dass er „void“ oder „any“ ist.", + "Decorator_used_before_export_here_1486": "Decorator, der hier vor \"export\" verwendet wird.", + "Decorators_are_not_valid_here_1206": "Decorators sind hier ungültig.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Decorators dürfen nicht auf mehrere get-/set-Zugriffsmethoden mit dem gleichen Namen angewendet werden.", + "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038": "Decorators dürfen nicht nach \"export\" oder \"export default\" angezeigt werden, wenn sie auch vor \"export\" angezeigt werden.", + "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436": "Vor dem Namen und allen Schlüsselwörtern von Eigenschaftendeklarationen müssen Decorator-Elemente stehen.", + "Default_catch_clause_variables_as_unknown_instead_of_any_6803": "Stellen Sie die Variablen der Catch-Klauseln standardmäßig als „unknown“ anstelle von „any“ ein.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Der Standardexport des Moduls besitzt oder verwendet den privaten Namen \"{0}\".", + "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037": "Standardexporte können nicht mit \"--isolatedDeclarations\" abgeleitet werden.", + "Default_library_1424": "Standardbibliothek", + "Default_library_for_target_0_1425": "Standardbibliothek für Ziel \"{0}\"", + "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Definitionen der folgenden Bezeichner stehen in Konflikt mit denen in einer anderen Datei: {0}", + "Delete_all_unused_declarations_95024": "Alle nicht verwendeten Deklarationen löschen", + "Delete_all_unused_imports_95147": "Alle nicht verwendeten Importe löschen", + "Delete_all_unused_param_tags_95172": "Alle nicht verwendeten \"@param\"-Tags löschen", + "Delete_the_outputs_of_all_projects_6365": "Löschen Sie die Ausgaben aller Projekte.", + "Delete_unused_param_tag_0_95171": "Nicht verwendete \"@param\"-Tag-\"{0}\" löschen", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Veraltet] Verwenden Sie stattdessen \"--jsxFactory\". Geben Sie das Objekt an, das für \"createElement\" aufgerufen wurde, wenn das Ziel die JSX-Ausgabe \"react\" ist.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Veraltet] Verwenden Sie stattdessen \"--outFile\". Verketten und Ausgeben in eine einzige Datei", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Veraltet] Verwenden Sie stattdessen \"--skipLibCheck\". Überspringen Sie die Typüberprüfung der Standardbibliothek-Deklarationsdateien.", + "Deprecated_setting_Use_outFile_instead_6677": "Veraltete Einstellung. Verwenden Sie stattdessen „outFile“.", + "Did_you_forget_to_use_await_2773": "Haben Sie vergessen, \"await\" zu verwenden?", + "Did_you_mean_0_1369": "Meinten Sie \"{0}\"?", + "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735": "Wollten Sie \"{0}\" auf den Typ \"new (...args: any[]) => {1}\" einschränken?", + "Did_you_mean_to_call_this_expression_6212": "Wollten Sie diesen Ausdruck aufrufen?", + "Did_you_mean_to_mark_this_function_as_async_1356": "Wollten Sie diese Funktion als \"async\" markieren?", + "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312": "Wollten Sie \":\" verwenden? Ein \"=\" kann nur dann auf einen Eigenschaftennamen folgen, wenn das enthaltende Objektliteral Teil eines Destrukturierungsmusters ist.", + "Did_you_mean_to_use_new_with_this_expression_6213": "Wollten Sie \"new\" mit diesem Ausdruck verwenden?", + "Digit_expected_1124": "Eine Ziffer wurde erwartet.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Das Verzeichnis \"{0}\" ist nicht vorhanden, Suchvorgänge darin werden übersprungen.", + "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270": "Das Verzeichnis \"{0}\" enthält keinen package.json-Bereich. Importe werden nicht aufgelöst.", + "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669": "Deaktivieren Sie das Hinzufügen von \"Use Strict\"-Direktiven in ausgesendeten JavaScript-Dateien.", + "Disable_checking_for_this_file_90018": "Überprüfung für diese Datei deaktivieren", + "Disable_emitting_comments_6688": "Deaktivieren Sie das Ausgeben von Kommentaren.", + "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701": "Deaktivieren Sie das Ausgeben von Deklarationen mit „@internal“ in ihren JSDoc-Kommentaren.", + "Disable_emitting_files_from_a_compilation_6660": "Deaktivieren Sie das Ausgeben von Dateien aus einer Kompilierung.", + "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662": "Deaktivieren Sie das Ausgeben von Dateien, wenn Typüberprüfungsfehler gemeldet werden.", + "Disable_erasing_const_enum_declarations_in_generated_code_6682": "Deaktivieren Sie das Löschen von „const enum“-Deklarationen in generiertem Code.", + "Disable_error_reporting_for_unreachable_code_6603": "Deaktivieren Sie die Fehlerberichterstattung für nicht erreichbaren Code.", + "Disable_error_reporting_for_unused_labels_6604": "Deaktivieren Sie die Fehlerberichterstattung für nicht verwendete Bezeichnungen.", + "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805": "Deaktivieren Sie die vollständige Typüberprüfung (nur kritische Analyse- und Ausgabefehler werden gemeldet).", + "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661": "Deaktivieren Sie das Generieren von benutzerdefinierten Hilfsfunktionen wie „__extends“ in der kompilierten Ausgabe.", + "Disable_including_any_library_files_including_the_default_lib_d_ts_6670": "Deaktivieren Sie das Einschließen von Bibliotheksdateien, einschließlich der Standarddatei \"lib.d.ts\".", + "Disable_loading_referenced_projects_6235": "Deaktivieren Sie das Laden referenzierter Projekte.", + "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620": "Deaktivieren Sie bevorzugte Quelldateien anstelle von Deklarationsdateien, wenn Sie auf zusammengesetzte Projekte verweisen.", + "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702": "Deaktivieren Sie die Meldung übermäßiger Eigenschaftsfehler während der Erstellung von Objektliteralen.", + "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683": "Deaktivieren Sie das Auflösen von symlinks in ihren Realpfad. Dies korreliert mit derselben Kennzeichnung im Knoten.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Größenbeschränkungen für JavaScript-Projekte deaktivieren.", + "Disable_solution_searching_for_this_project_6224": "Deaktivieren Sie die Projektmappensuche für dieses Projekt.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6673": "Deaktivieren Sie die strenge Überprüfung generischer Signaturen in Funktionstypen.", + "Disable_the_type_acquisition_for_JavaScript_projects_6625": "Typ-Akquisition für JavaScript-Projekte deaktivieren", + "Disable_truncating_types_in_error_messages_6663": "Deaktivieren Sie das Abschneiden von Typen in Fehlermeldungen.", + "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221": "Deaktivieren Sie die Verwendung von Quelldateien anstelle von Deklarationsdateien aus referenzierten Projekten.", + "Disable_wiping_the_console_in_watch_mode_6684": "Deaktivieren Sie das Zurücksetzen der Konsole im Überwachungsmodus.", + "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616": "Deaktiviert den Rückschluss für den Typabruf, indem Dateinamen in einem Projekt betrachtet werden.", + "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672": "Hiermit wird verhindert, dass „import“, „require“ oder „“ die Anzahl der Dateien erweitern, die TypeScript einem Projekt hinzufügen soll.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Verweise mit uneinheitlicher Groß-/Kleinschreibung auf die gleiche Datei nicht zulassen.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Fügen Sie keine Verweise mit dreifachen Schrägstrichen oder importierte Module zur Liste kompilierter Dateien hinzu.", + "Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript_6721": "Laufzeitkonstrukte, die nicht Teil von ECMAScript sind, nicht zulassen", + "Do_not_emit_comments_to_output_6009": "Kommentare nicht an die Ausgabe ausgeben.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Deklarationen für Code mit einer Anmerkung \"@internal\" nicht ausgeben.", + "Do_not_emit_outputs_6010": "Keine Ausgaben ausgeben.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Keine Ausgaben ausgeben, wenn Fehler gemeldet wurden.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Keine \"use strict\"-Direktiven in Modulausgabe ausgeben.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "const-Enumerationsdeklarationen im generierten Code nicht löschen.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Erstellen Sie keine benutzerdefinierten Hilfsfunktionen wie \"__extends\" in der kompilierten Ausgabe.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Beziehen Sie die Standardbibliotheksdatei (lib.d.ts) nicht ein.", + "Do_not_report_errors_on_unreachable_code_6077": "Fehler zu nicht erreichbarem Code nicht melden.", + "Do_not_report_errors_on_unused_labels_6074": "Fehler zu nicht verwendeten Bezeichnungen nicht melden.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Tatsächlichen Pfad von symbolischen Verknüpfungen nicht auflösen.", + "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804": "Sie sollten keine Importe oder Exporte transformieren oder ausblenden, die nicht als typgeschützt markiert sind. Stellen Sie sicher, dass sie basierend auf der Einstellung \"module\" im Format der Ausgabedatei geschrieben werden.", + "Do_not_truncate_error_messages_6165": "Kürzen Sie keine Fehlermeldungen.", + "Duplicate_function_implementation_2393": "Doppelte Funktionsimplementierung.", + "Duplicate_identifier_0_2300": "Doppelter Bezeichner \"{0}\".", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Doppelter Bezeichner \"{0}\". Der Compiler reserviert den Namen \"{1}\" im Bereich der obersten Ebene eines Moduls.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Doppelter Bezeichner \"{0}\". Der Compiler reserviert den Namen \"{1}\" im Bereich der obersten Ebene eines Moduls, das asynchrone Funktionen enthält.", + "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818": "Doppelter Bezeichner „{0}“. Der Compiler reserviert den Namen „{1}“ beim Ausgeben von „Super“-Verweisen in statischen Initialisierern.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Doppelter Bezeichner \"{0}\". Der Compiler verwendet die Deklaration \"{1}\", um asynchrone Funktionen zu unterstützen.", + "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804": "Doppelter Bezeichner \"{0}\". Statische Elemente und Instanzelemente dürfen nicht denselben privaten Namen aufweisen.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Doppelter Bezeichner \"arguments\". Der Compiler verwendet \"arguments\" zum Initialisieren der rest-Parameter.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Doppelter Bezeichner \"_newTarget\". Der Compiler verwendet die Variablendeklaration \"_newTarget\" zum Erfassen der Metaeigenschaftenreferenz \"new.target\".", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Doppelter Bezeichner \"_this\". Der Compiler verwendet die Variablendeklaration \"_this\" zum Erfassen des this-Verweises.", + "Duplicate_index_signature_for_type_0_2374": "Doppelte Indexsignatur für Typ \"{0}\".", + "Duplicate_label_0_1114": "Doppelte Bezeichnung \"{0}\".", + "Duplicate_property_0_2718": "Doppelte Eigenschaft: {0}", + "Duplicate_regular_expression_flag_1500": "Doppeltes Flag für reguläre Ausdrücke.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Der Spezifizierer des dynamischen Imports muss den Typ \"string\" aufweisen, hier ist er jedoch vom Typ \"{0}\".", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Dynamische Importe werden nur unterstützt, wenn das Flag „--module“ auf „es2020“, „es2022“, „esnext“, „commonjs“, „amd“, „system“, „umd“, „node16“, „node18“ oder „nodenext'.", + "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments_1450": "Dynamische Importe können nur einen Modulspezifizierer und ein optionales Set mit Attributen als Argumente akzeptieren.", + "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_1324": "Dynamische Importe unterstützen nur ein zweites Argument, wenn die Option „--module“ auf „esnext“, „node16“, „node18“, nodenext“ oder „preserve“ gesetzt ist.", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve_1293": "Die ESM-Syntax ist in einem CommonJS-Modul nicht zulässig, wenn \"module\" auf \"preserve\" festgelegt ist.", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled_1286": "Die ESM-Syntax ist in einem CommonJS-Modul nicht zulässig, wenn \"verbatimModuleSyntax\" aktiviert ist.", + "Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given_4125": "Jede Deklaration von \"{0}.{1}\" unterscheidet sich in ihrem Wert, wobei \"{2}\" erwartet, aber \"{3}\" angegeben wurde.", + "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Jeder Member des union-Typs \"{0}\" weist Konstruktsignaturen auf, aber keine dieser Signaturen ist miteinander kompatibel.", + "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758": "Jeder Member des union-Typs \"{0}\" weist Signaturen auf, aber keine dieser Signaturen ist miteinander kompatibel.", + "Editor_Support_6249": "Editor-Unterstützung", + "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053": "Das Element weist implizit einen Typ \"any\" auf, weil der Ausdruck vom Typ \"{0}\" nicht für den Indextyp \"{1}\" verwendet werden kann.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Das Element weist implizit einen Typ \"any\" auf, weil der Indexausdruck nicht vom Typ \"number\" ist.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "Das Element weist implizit einen Typ \"any\" auf, weil der Typ \"{0}\" keine Indexsignatur umfasst.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052": "Das Element weist implizit einen Typ \"any\" auf, weil der Typ \"{0}\" keine Indexsignatur umfasst. Wollten Sie \"{1}\" aufrufen?", + "Emit_6246": "Ausgeben", + "Emit_ECMAScript_standard_compliant_class_fields_6712": "Geben Sie ECMAScript-standardkonforme Klassenfelder aus.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622": "Geben Sie zu Beginn der Ausgabedateien eine UTF-8-Bytereihenfolge-Marke (BOM) aus.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Geben Sie eine einzelne Datei mit Quellzuordnungen anstelle einer separaten Datei aus.", + "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638": "Geben Sie ein v8-CPU-Profil der Compilerausführung zum Debuggen aus.", + "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626": "Geben Sie zusätzliches JavaScript aus, um die Unterstützung beim Importieren von CommonJS-Modulen zu vereinfachen. Dadurch wird „allowSyntheticDefaultImports“ für die Typkompatibilität aktiviert.", + "Emit_class_fields_with_Define_instead_of_Set_6222": "Geben Sie Klassenfelder mit \"Define\" anstelle von \"Set\" aus.", + "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624": "Geben Sie Entwurfstypmetadaten für ergänzte Deklarationen in Quelldateien aus.", + "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621": "Geben Sie mehr kompatibles, aber ausführliches und weniger leistungsfähiges JavaScript für die Iteration aus.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Geben Sie die Quelle zusammen mit den Quellzuordnungen innerhalb einer einzelnen Datei aus; hierfür muss \"--inlineSourceMap\" oder \"--sourceMap\" festgelegt sein.", + "Enable_all_strict_type_checking_options_6180": "Aktivieren Sie alle strengen Typüberprüfungsoptionen.", + "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685": "Aktivieren Sie Farbe und Formatierung in der TypeScript-Ausgabe, um Compilerfehler leichter zu lesen.", + "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611": "Aktivieren Sie Einschränkungen, die die Verwendung eines TypeScript-Projekts mit Projektverweisen ermöglichen.", + "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667": "Aktivieren Sie die Fehlerberichterstattung für Codepfade, die nicht explizit in einer Funktion zurückgegeben werden.", + "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665": "Aktivieren Sie die Fehlerberichterstattung für Ausdrücke und Deklarationen mit einem impliziten „any“-Typ.", + "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664": "Aktivieren Sie die Fehlerberichterstellung für Fallthroughfälle in Switch-Anweisungen.", + "Enable_error_reporting_in_type_checked_JavaScript_files_6609": "Aktivieren Sie die Fehlerberichterstattung in typgeprüften JavaScript-Dateien.", + "Enable_error_reporting_when_local_variables_aren_t_read_6675": "Aktivieren Sie die Fehlerberichterstattung, wenn lokale Variablen nicht gelesen werden.", + "Enable_error_reporting_when_this_is_given_the_type_any_6668": "Aktivieren Sie die Fehlerberichterstattung, wenn „this“ den Typ „any“ erhält.", + "Enable_experimental_support_for_legacy_experimental_decorators_6630": "Aktivieren Sie experimentelle Unterstützung für experimentelle Legacy-Decorators.", + "Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present_6264": "Hiermit wird das Importieren von Dateien mit beliebiger Erweiterung aktiviert, sofern eine Deklarationsdatei vorhanden ist.", + "Enable_importing_json_files_6689": "Aktivieren Sie das Importieren von JSON-Dateien.", + "Enable_lib_replacement_6808": "Libersetzung aktivieren.", + "Enable_project_compilation_6302": "Projektkompilierung aktivieren", + "Enable_strict_bind_call_and_apply_methods_on_functions_6214": "Aktivieren Sie die strict-Methoden \"bind\", \"call\" und \"apply\" für Funktionen.", + "Enable_strict_checking_of_function_types_6186": "Aktivieren Sie die strenge Überprüfung für Funktionstypen.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Aktivieren Sie die strenge Überprüfung der Eigenschafteninitialisierung in Klassen.", + "Enable_strict_null_checks_6113": "Strenge NULL-Überprüfungen aktivieren.", + "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074": "Aktivieren Sie die Option \"experimentalDecorators\" in Ihrer Konfigurationsdatei.", + "Enable_the_jsx_flag_in_your_configuration_file_95088": "Aktivieren Sie das Flag \"--jsx\" in Ihrer Konfigurationsdatei.", + "Enable_tracing_of_the_name_resolution_process_6085": "Ablaufverfolgung des Namensauflösungsvorgangs aktivieren.", + "Enable_verbose_logging_6713": "Aktivieren Sie die ausführliche Protokollierung.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Ermöglicht Ausgabeinteroperabilität zwischen CommonJS- und ES-Modulen durch die Erstellung von Namespaceobjekten für alle Importe. Impliziert \"AllowSyntheticDefaultImports\".", + "Enables_experimental_support_for_ES7_decorators_6065": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Decorators.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Ermöglicht experimentelle Unterstützung zum Ausgeben von Typmetadaten für Decorators.", + "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671": "Erzwingt die Verwendung indizierter Accessoren für Schlüssel, die mithilfe eines indizierten Typs deklariert wurden.", + "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666": "Stellen Sie sicher, dass überschreibende Member in abgeleiteten Klassen mit einem Überschreibungsmodifizierer markiert sind.", + "Ensure_that_casing_is_correct_in_imports_6637": "Stellen Sie sicher, dass die Groß-/Kleinschreibung beim Import korrekt ist.", + "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645": "Stellen Sie sicher, dass jede Datei sicher transpiliert werden kann, ohne dass andere Importe erforderlich sind.", + "Ensure_use_strict_is_always_emitted_6605": "Stellen Sie sicher, dass \"Use Strict\" immer ausgegeben wird.", + "Entering_conditional_exports_6413": "Bedingte Exporte werden eingegeben.", + "Entry_point_for_implicit_type_library_0_1420": "Einstiegspunkt für implizite Typbibliothek \"{0}\"", + "Entry_point_for_implicit_type_library_0_with_packageId_1_1421": "Einstiegspunkt für die implizite Typbibliothek \"{0}\" mit packageId \"{1}\"", + "Entry_point_of_type_library_0_specified_in_compilerOptions_1417": "Der in \"compilerOptions\" angegebene Einstiegspunkt der Typbibliothek \"{0}\"", + "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418": "Der in \"compilerOptions\" angegebene Einstiegspunkt der Typbibliothek \"{0}\" mit packageId \"{1}\"", + "Enum_0_used_before_its_declaration_2450": "Enumeration \"{0}\", die vor der Deklaration wurde.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enumerationsdeklarationen können nur mit Namespace- oder anderen Enumerationsdeklarationen zusammengeführt werden.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Enumerationsdeklarationen müssen alle konstant oder nicht konstant sein.", + "Enum_member_expected_1132": "Ein Enumerationsmember wurde erwartet.", + "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056": "Der Enumerationsmember, der auf ein nicht literales numerisches Element folgt, muss über einen Initialisierer verfügen, wenn \"isolatedModules\" aktiviert ist.", + "Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDecl_9020": "Enumerationsmemberinitialisierer müssen ohne Verweise auf externe Symbole mit \"--isolatedDeclarations\" berechenbar sein.", + "Enum_member_must_have_initializer_1061": "Ein Enumerationsmember muss einen Initialisierer aufweisen.", + "Enum_name_cannot_be_0_2431": "Der Enumerationsname darf nicht \"{0}\" sein.", + "Errors_Files_6041": "Fehlerdateien", + "Escape_sequence_0_is_not_allowed_1488": "Escapesequenz \"{0}\" ist nicht zulässig.", + "Examples_Colon_0_6026": "Beispiele: {0}", + "Excessive_complexity_comparing_types_0_and_1_2859": "Übermäßige Komplexität beim Vergleichen der Typen \"{0}\" und \"{1}\".", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Übermäßige Stapeltiefe beim Vergleichen der Typen \"{0}\" und \"{1}\".", + "Exiting_conditional_exports_6416": "Bedingte Exporte werden beendet.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} Typargumente erwartet; geben Sie diese mit einem @extends-Tag an.", + "Expected_0_arguments_but_got_1_2554": "{0} Argumente wurden erwartet, empfangen wurden aber {1}.", + "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794": "Es wurden {0} Argumente erwartet, aber {1} erhalten. Sollte \"void\" in Ihr Typargument in \"Promise\" eingeschlossen werden?", + "Expected_0_type_arguments_but_got_1_2558": "{0} Typenargumente wurden erwartet, empfangen wurden aber {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} Typargumente erwartet; geben Sie diese mit einem @extends-Tag an.", + "Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_2810": "1 Argument erwartet, aber 0 erhalten. „new Promise()“ benötigt einen JSDoc-Hinweis, um einen „resolve“ zu erzeugen, der ohne Argumente aufgerufen werden kann.", + "Expected_a_Unicode_property_name_1523": "Es wurde ein Unicode-Eigenschaftsname erwartet.", + "Expected_a_Unicode_property_name_or_value_1527": "Es wurde ein Unicode-Eigenschaftsname oder -wert erwartet.", + "Expected_a_Unicode_property_value_1525": "Es wurde ein Unicode-Eigenschaftswert erwartet.", + "Expected_a_capturing_group_name_1514": "Es wurde ein Name für die Erfassungsgruppe erwartet.", + "Expected_a_class_set_operand_1520": "Es wurde ein Klassensatzoperand erwartet.", + "Expected_at_least_0_arguments_but_got_1_2555": "Mindestens {0} Argumente wurden erwartet, empfangen wurden aber {1}.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Das entsprechende schließende JSX-Tag wurde für \"{0}\" erwartet.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Für das JSX-Fragment wurde das entsprechende schließende Tag erwartet.", + "Expected_for_property_initializer_1442": "Für den Eigenschafteninitialisierer wurde \"=\" erwartet.", + "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105": "Der erwartete Typ des Felds \"{0}\" in der Datei \"package.json\" lautet \"{1}\", empfangen wurde \"{2}\".", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Explizit angegebene Art der Modulauflösung: \"{0}\".", + "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Die Potenzierung kann für bigint-Werte nur durchgeführt werden, wenn die Option \"target\" auf \"es2016\" oder höher festgelegt ist.", + "Export_0_from_module_1_90059": "Exportieren von \"{0}\" aus Modul \"{1}\"", + "Export_all_referenced_locals_90060": "Alle referenzierten lokalen Elemente exportieren", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Die Exportzuweisung darf nicht verwendet werden, wenn das Ziel ECMAScript-Module sind. Verwenden Sie stattdessen ggf. \"export default\" oder ein anderes Modulformat.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Die Exportzuweisung wird nicht unterstützt, wenn das Flag \"-module\" den Wert \"system\" aufweist.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Die Exportdeklaration verursacht einen Konflikt mit der exportierten Deklaration von \"{0}\".", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Exportdeklarationen sind in einem Namespace unzulässig.", + "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276": "Der Exportspezifizierer \"{0}\" ist im package.json-Bereich beim Pfad \"{1}\" nicht vorhanden.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Der exportierte Typalias \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084": "Der exportierte Typalias \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\" aus dem Modul \"{2}\".", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Die exportierte Variable \"{0}\" besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Die exportierte Variable \"{0}\" besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "Die exportierte Variable \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Exporte und Exportzuweisungen sind in Modulerweiterungen unzulässig.", + "Expression_expected_1109": "Es wurde ein Ausdruck erwartet.", + "Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator_1497": "Der Ausdruck muss in Klammern eingeschlossen werden, damit er als Decorator verwendet werden kann.", + "Expression_or_comma_expected_1137": "Es wurde ein Ausdruck oder Komma erwartet.", + "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800": "Der Ausdruck erzeugt einen Tupeltyp, der für die Darstellung zu groß ist.", + "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590": "Der Ausdruck erzeugt einen union-Typ, der für die Darstellung zu komplex ist.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Der Ausdruck wird in \"_super\" aufgelöst. Damit erfasst der Compiler den Basisklassenverweis.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Der Ausdruck wird in die Variablendeklaration \"_newTarget\" aufgelöst, die der Compiler zum Erfassen der Metaeigenschaftenreferenz \"new.target\" verwendet.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Der Ausdruck wird in die Variablendeklaration \"_this\" aufgelöst, die der Compiler verwendet, um den this-Verweis zu erfassen.", + "Expression_type_can_t_be_inferred_with_isolatedDeclarations_9013": "Der Ausdruckstyp kann nicht mit \"--isolatedDeclarations\" abgeleitet werden.", + "Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations_9021": "Die Extends-Klausel darf keinen Ausdruck mit \"--isolatedDeclarations\" enthalten.", + "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085": "Die extends-Klausel für den abgeleiteten Typ \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Extract_base_class_to_variable_90064": "Basisklasse in Variable extrahieren", + "Extract_binding_expressions_to_variable_90066": "Extrahieren von Bindungsausdrücken in eine Variable", + "Extract_constant_95006": "Konstante extrahieren", + "Extract_default_export_to_variable_90065": "Standardexport in Variable extrahieren", + "Extract_function_95005": "Funktion extrahieren", + "Extract_to_0_in_1_95004": "Als {0} nach {1} extrahieren", + "Extract_to_0_in_1_scope_95008": "Als {0} in {1}-Bereich extrahieren", + "Extract_to_0_in_enclosing_scope_95007": "Als {0} in einschließenden Bereich extrahieren", + "Extract_to_interface_95090": "In Schnittstelle extrahieren", + "Extract_to_type_alias_95078": "In Typalias extrahieren", + "Extract_to_typedef_95079": "In TypeDef extrahieren", + "Extract_to_variable_and_replace_with_0_as_typeof_0_90069": "In Variable extrahieren und durch \"{0} as typeof {0}\" ersetzen", + "Extract_type_95077": "Typ extrahieren", + "FILE_6035": "DATEI", + "FILE_OR_DIRECTORY_6040": "DATEI ODER VERZEICHNIS", + "Failed_to_find_peerDependency_0_6283": "Fehler beim Suchen der peerDependency \"{0}\".", + "Failed_to_resolve_under_condition_0_6415": "Fehler beim Auflösen unter der Bedingung \"{0}\".", + "Fallthrough_case_in_switch_7029": "FallThrough-Fall in switch-Anweisung.", + "File_0_does_not_exist_6096": "Die Datei \"{0}\" ist nicht vorhanden.", + "File_0_does_not_exist_according_to_earlier_cached_lookups_6240": "Die Datei \"{0}\" ist gemäß früheren zwischengespeicherten Lookups nicht vorhanden.", + "File_0_exists_according_to_earlier_cached_lookups_6239": "Die Datei \"{0}\" ist gemäß früheren zwischengespeicherten Lookups vorhanden.", + "File_0_exists_use_it_as_a_name_resolution_result_6097": "Die Datei \"{0}\" ist vorhanden – sie wird als Ergebnis der Namensauflösung verwendet.", + "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054": "Die Datei \"{0}\" weist eine nicht unterstützte Erweiterung auf. Es werden nur die folgenden Erweiterungen unterstützt: {1}.", + "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504": "Die Datei \"{0}\" ist eine JavaScript-Datei. Wollten Sie die Option \"allowJs\" aktivieren?", + "File_0_is_not_a_module_2306": "Die Datei \"{0}\" ist kein Modul.", + "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307": "Die Datei \"{0}\" befindet sich nicht in der Dateiliste von Projekt \"{1}\". Projekte müssen alle Dateien auflisten oder ein include-Muster verwenden.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Datei \"{0}\" befindet sich nicht unter \"rootDir\" \"{1}\". \"rootDir\" muss alle Quelldateien enthalten.", + "File_0_not_found_6053": "Die Datei \"{0}\" wurde nicht gefunden.", + "File_Management_6245": "Dateiverwaltung", + "File_appears_to_be_binary_1490": "Die Datei scheint binär zu sein.", + "File_change_detected_Starting_incremental_compilation_6032": "Es wurde eine Dateiänderung erkannt. Die inkrementelle Kompilierung wird gestartet...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Die Datei ist ein CommonJS-Modul, da '{0}' nicht das Feld „Typ“ aufweist", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Die Datei ist ein CommonJS-Modul, da '{0}' das Feld „Typ“ aufweist, dessen Wert nicht „Modul“ ist", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Die Datei ist ein CommonJS-Modul, da „package.json“ nicht gefunden wurde", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Die Datei ist ein ECMAScript-Modul, da '{0}' das Feld „Typ“ mit dem Wert „Modul“ aufweist.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Die Datei ist ein CommonJS-Modul und kann möglicherweise in ein ES-Modul konvertiert werden.", + "File_is_default_library_for_target_specified_here_1426": "Die Datei ist die Standardbibliothek für das hier angegebene Ziel.", + "File_is_entry_point_of_type_library_specified_here_1419": "Die Datei ist ein Einstiegspunkt der hier angegebenen Typbibliothek.", + "File_is_included_via_import_here_1399": "Die Datei wird hier per Import eingeschlossen.", + "File_is_included_via_library_reference_here_1406": "Die Datei wird hier per Bibliotheksverweis eingeschlossen.", + "File_is_included_via_reference_here_1401": "Die Datei wird hier per Verweis eingeschlossen.", + "File_is_included_via_type_library_reference_here_1404": "Die Datei wird hier per Typbibliotheksverweis eingeschlossen.", + "File_is_library_specified_here_1423": "Die Datei ist die hier angegebene Bibliothek.", + "File_is_matched_by_files_list_specified_here_1410": "Die Datei wird mit der hier angegebenen Liste \"files\" abgeglichen.", + "File_is_matched_by_include_pattern_specified_here_1408": "Die Datei wird mit dem hier angegebenen include-Muster abgeglichen.", + "File_is_output_from_referenced_project_specified_here_1413": "Die Datei ist die Ausgabe des hier angegebenen referenzierten Projekts.", + "File_is_output_of_project_reference_source_0_1428": "Die Datei ist die Ausgabe der Projektverweisquelle \"{0}\".", + "File_is_source_from_referenced_project_specified_here_1416": "Die Datei ist die Quelle des hier angegebenen referenzierten Projekts.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Der Dateiname \"{0}\" unterscheidet sich vom bereits enthaltenen Dateinamen \"{1}\" nur hinsichtlich der Groß-/Kleinschreibung.", + "File_name_0_has_a_1_extension_looking_up_2_instead_6262": "Der Dateiname \"{0}\" hat eine \"{1}\"-Erweiterung. Stattdessen wird nach \"{2}\" gesucht.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Der Dateiname \"{0}\" weist eine Erweiterung \"{1}\" auf. Diese wird entfernt.", + "File_redirects_to_file_0_1429": "Die Datei leitet an die Datei \"{0}\" um.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Die Dateispezifikation darf kein übergeordnetes Verzeichnis (\"..\") enthalten, das nach einem rekursiven Verzeichnisplatzhalter (\"**\") angegeben wird: \"{0}\".", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Die Dateispezifikation darf nicht mit einem rekursiven Verzeichnisplatzhalter (\"**\") enden: \"{0}\".", + "Filters_results_from_the_include_option_6627": "Filtert Ergebnisse aus der Option \"include\".", + "Fix_all_detected_spelling_errors_95026": "Alle erkannten Rechtschreibfehler korrigieren", + "Fix_all_expressions_possibly_missing_await_95085": "Korrigieren Sie alle Ausdrücke, in denen \"await\" möglicherweise fehlt.", + "Fix_all_implicit_this_errors_95107": "Alle impliziten this-Fehler beheben", + "Fix_all_incorrect_return_type_of_an_async_functions_90037": "Alle falschen Rückgabetypen einer asynchronen Funktionen korrigieren", + "Fix_all_with_type_only_imports_95182": "Alle mit rein typbasierten Importen korrigieren", + "Found_0_errors_6217": "{0} Fehler gefunden.", + "Found_0_errors_Watching_for_file_changes_6194": "{0} Fehler gefunden. Es wird auf Dateiänderungen überwacht.", + "Found_0_errors_in_1_files_6261": "In {1} Dateien wurden {0} Fehler gefunden.", + "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260": "Es wurden {0} Fehler in derselben Datei gefunden, beginnend bei: {1}", + "Found_1_error_6216": "1 Fehler gefunden.", + "Found_1_error_Watching_for_file_changes_6193": "1 Fehler gefunden. Es wird auf Dateiänderungen überwacht.", + "Found_1_error_in_0_6259": "1 Fehler in {0} gefunden", + "Found_package_json_at_0_6099": "\"package.json\" wurde unter \"{0}\" gefunden.", + "Found_peerDependency_0_with_1_version_6282": "Es wurde eine peerDependency \"{0}\" mit Version \"{1}\" gefunden.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_1250": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES5\" ist.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definiti_1251": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES5\" ist. Klassendefinitionen befinden sich automatisch im Strict-Modus.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_au_1252": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES5\" ist. Module befinden sich automatisch im Strict-Modus.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "Ein Funktionsausdruck ohne Rückgabetypanmerkung weist implizit einen {0}-Rückgabetyp auf.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Die Funktionsimplementierung fehlt oder folgt nicht unmittelbar auf die Deklaration.", + "Function_implementation_name_must_be_0_2389": "Der Name der Funktionsimplementierung muss \"{0}\" lauten.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Die Funktion weist implizit den Typ \"any\" auf, weil keine Rückgabetypanmerkung vorhanden ist und darauf direkt oder indirekt in einem ihrer Rückgabeausdrücke verwiesen wird.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Der Funktion fehlt die abschließende return-Anweisung, und der Rückgabetyp enthält nicht \"undefined\".", + "Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9007": "Die Funktion muss eine explizite Rückgabetypanmerkung mit \"--isolatedDeclarations\" aufweisen.", + "Function_not_implemented_95159": "Die Funktion ist nicht implementiert.", + "Function_overload_must_be_static_2387": "Die Funktionsüberladung muss statisch sein.", + "Function_overload_must_not_be_static_2388": "Die Funktionsüberladung darf nicht statisch sein.", + "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385": "Die Notation des Funktionstyps muss in Klammern gesetzt werden, wenn sie in einem Union-Typ verwendet wird.", + "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387": "Die Notation des Funktionstyps muss in Klammern gesetzt werden, wenn sie in einem Intersection-Typ verwendet wird.", + "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014": "Ein Funktionstyp ohne Rückgabetypanmerkung weist implizit einen Rückgabetyp \"{0}\" auf.", + "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814": "Eine Funktion mit Textkörpern kann nur mit Umgebungsklassen zusammengeführt werden.", + "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612": "Generieren Sie .d.ts-Dateien aus TypeScript- und JavaScript-Dateien in Ihrem Projekt.", + "Generate_get_and_set_accessors_95046": "GET- und SET-Accessoren generieren", + "Generate_get_and_set_accessors_for_all_overriding_properties_95119": "get- und set-Zugriffsmethoden für alle überschreibenden Eigenschaften generieren", + "Generates_a_CPU_profile_6223": "Generiert ein CPU-Profil.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Generiert eine sourcemap für jede entsprechende .d.ts-Datei.", + "Generates_an_event_trace_and_a_list_of_types_6237": "Generiert eine Ereignisablaufverfolgung und eine Liste von Typen.", + "Generates_corresponding_d_ts_file_6002": "Generiert die entsprechende .d.ts-Datei.", + "Generates_corresponding_map_file_6043": "Generiert die entsprechende MAP-Datei.", + "Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation_7025": "Der Generator hat implizit den Yield-Typ '{0}'. Erwägen Sie die Angabe eines Rückgabetyps.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Generatoren sind in einem Umgebungskontext unzulässig.", + "Generic_type_0_requires_1_type_argument_s_2314": "Der generische Typ \"{0}\" erfordert {1} Typargument(e).", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Der generische Typ \"{0}\" benötigt zwischen {1} und {2} Typargumente.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Globale Modulexporte dürfen nur auf der obersten Ebene auftreten.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Globale Modulexporte dürfen nur in Deklarationsdateien auftreten.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Globale Modulexporte dürfen nur in Moduldateien auftreten.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Der globale Typ \"{0}\" muss eine Klassen- oder Schnittstellentyp sein.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Der globale Typ \"{0}\" muss {1} Typparameter aufweisen.", + "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384": "Legen Sie für Neukompilierungen in \"--incremental\" und \"--watch\" fest, dass sich Änderungen innerhalb einer Datei nur auf die direkt davon abhängigen Dateien auswirken.", + "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606": "Bei Neukompilierungen in Projekten, die die Modi „incremental“ und „watch“ verwenden, wird davon ausgegangen, dass Änderungen innerhalb einer Datei sich nur direkt auf Dateien auswirken.", + "Hexadecimal_digit_expected_1125": "Es wurde eine hexadezimale Zahl erwartet.", + "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262": "Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort auf der obersten Ebene eines Moduls.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Ein Bezeichner wird erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Es wurde ein Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus. Klassendefinitionen befinden sich automatisch im Strict-Modus.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Es wurde ein Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus. Module befinden sich automatisch im Strict-Modus.", + "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort, das hier nicht verwendet werden kann.", + "Identifier_expected_1003": "Es wurde ein Bezeichner erwartet.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Bezeichner erwartet. \"__esModule\" ist als exportierter Marker für die Umwandlung von ECMAScript-Modulen reserviert.", + "Identifier_or_string_literal_expected_1478": "Bezeichner oder Zeichenfolgenliteral erwartet.", + "Identifier_string_literal_or_number_literal_expected_1496": "Bezeichner, Zeichenfolgenliteral oder Zahlenliteral erwartet.", + "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Wenn das Paket \"{0}\" dieses Modul tatsächlich verfügbar macht, erwägen Sie, einen Pull Request zum Ändern von https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1} zu senden.", + "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Wenn das Paket \"{0}\" dieses Modul tatsächlich verfügbar macht, versuchen Sie, eine neue Deklarationsdatei (.d.ts) hinzuzufügen, die Declare-Modul \"{1}\" enthält.", + "Ignore_this_error_message_90019": "Diese Fehlermeldung ignorieren", + "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924": "Ignoriert tsconfig.json und kompiliert die angegebenen Dateien mit den Standardkompilieroptionen.", + "Implement_all_inherited_abstract_classes_95040": "Alle geerbten abstrakten Klassen implementieren", + "Implement_all_unimplemented_interfaces_95032": "Alle nicht implementierten Schnittstellen implementieren", + "Implement_inherited_abstract_class_90007": "Geerbte abstrakte Klasse implementieren", + "Implement_interface_0_90006": "Schnittstelle \"{0}\" implementieren", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Die implements-Klausel der exportierten Klasse \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731": "Die implizite Konvertierung von \"symbol\" in \"string\" führt zur Laufzeit zu einem Fehler. Erwägen Sie, diesen Ausdruck in \"String(...)\" einzuschließen.", + "Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_w_2866": "Import \"{0}\" steht in Konflikt mit dem in dieser Datei verwendeten globalen Wert. Er muss mit einem reinen Typimport deklariert werden, wenn \"isolatedModules\" aktiviert ist.", + "Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_2865": "Import \"{0}\" steht in Konflikt mit dem lokalen Wert. Er muss mit einem reinen Typimport deklariert werden, wenn \"isolatedModules\" aktiviert ist.", + "Import_0_from_1_90013": "\"{0}\" aus \"{1}\" importieren", + "Import_assertion_values_must_be_string_literal_expressions_2837": "Importassertionswerte müssen Zeichenfolgenliteralausdrücke sein.", + "Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2836": "Importassertionen sind für Anweisungen, die in \"require\"-Aufrufe von \"CommonJS\" kompilieren, nicht zulässig.", + "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2821": "Importassertionen werden nur unterstützt, wenn die Option „--module“ auf „esnext“, „node18“, „nodenext“ oder „preserve“ festgelegt ist.", + "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822": "Importassertionen können nicht mit rein typbasierten Importen oder Exporten verwendet werden.", + "Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880": "Importassertionen wurden durch Importattribute ersetzt. Verwenden Sie \"with\" anstelle von \"assert\".", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Die Importzuweisung kann nicht verwendet werden, wenn das Ziel ECMAScript-Module sind. Verwenden Sie stattdessen ggf. \"import * as ns from 'mod'\", \"import {a} from 'mod'\", \"import d from 'mod'\" oder ein anderes Modulformat.", + "Import_attribute_values_must_be_string_literal_expressions_2858": "Importattributwerte müssen Zeichenfolgenliteralausdrücke sein.", + "Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2856": "Importattribute sind für Anweisungen, die in \"require\"-Aufrufe von \"CommonJS\" kompiliert werden, nicht zulässig.", + "Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2823": "Importattribute werden nur unterstützt, wenn die Option „--module“ auf „esnext“, „node18“, „nodenext“ oder „preserve“ festgelegt ist.", + "Import_attributes_cannot_be_used_with_type_only_imports_or_exports_2857": "Importattribute können nicht mit rein typbasierten Importen oder Exporten verwendet werden.", + "Import_declaration_0_is_using_private_name_1_4000": "Die Importdeklaration \"{0}\" verwendet den privaten Namen \"{1}\".", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Die Importdeklaration verursacht einen Konflikt mit der lokalen Deklaration von \"{0}\".", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Importdeklarationen in einem Namespace dürfen nicht auf ein Modul verweisen.", + "Import_emit_helpers_from_tslib_6139": "Ausgabehilfsprogramme aus \"tslib\" importieren.", + "Import_may_be_converted_to_a_default_import_80003": "Der Import kann in einen Standardimport konvertiert werden.", + "Import_name_cannot_be_0_2438": "Der Importname darf nicht \"{0}\" sein.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Import- oder Exportdeklaration in einer Umgebungsmoduldeklaration dürfen nicht über den relativen Modulnamen auf ein Modul verweisen.", + "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271": "Der Importspezifizierer \"{0}\" ist im package.json-Bereich beim Pfad \"{1}\" nicht vorhanden.", + "Imported_via_0_from_file_1_1393": "Importiert über \"{0}\" aus der Datei \"{1}\"", + "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395": "Importiert über \"{0}\" aus der Datei \"{1}\" zum Importieren von \"importHelpers\", wie in \"compilerOptions\" angegeben", + "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397": "Importiert über \"{0}\" aus der Datei \"{1}\" zum Importieren der Factoryfunktionen \"jsx\" und \"jsxs\"", + "Imported_via_0_from_file_1_with_packageId_2_1394": "Importiert über \"{0}\" aus der Datei \"{1}\" mit packageId \"{2}\"", + "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396": "Importiert über \"{0}\" aus der Datei \"{1}\" mit packageId \"{2}\" zum Importieren von \"importHelpers\", wie in \"compilerOptions\" angegeben", + "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398": "Importiert über \"{0}\" aus der Datei \"{1}\" mit packageId \"{2}\" zum Importieren der Factoryfunktionen \"jsx\" und \"jsxs\"", + "Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_mod_1543": "\"Das Importieren einer JSON-Datei in ein ECMAScript-Modul erfordert ein Importattribut 'type: \"json\"', wenn 'module' auf '{0}' gesetzt ist.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importe sind in Modulerweiterungen unzulässig. Verschieben Sie diese ggf. in das einschließende externe Modul.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "In Umgebungsenumerationsdeklarationen muss der Memberinitialisierer ein konstanter Ausdruck sein.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In einer Enumeration mit mehreren Deklarationen kann nur eine Deklaration einen Initialisierer für das erste Enumerationselement ausgeben.", + "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635": "Schließen Sie eine Liste von Dateien ein. Dies unterstützt keine Globmuster im Gegensatz zu \"include\".", + "Include_modules_imported_with_json_extension_6197": "Importierte Module mit der Erweiterung \"JSON\" einschließen", + "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644": "Fügen Sie den Quellcode in die Quellzuordnungen innerhalb des ausgesendeten JavaScript-Codes ein.", + "Include_sourcemap_files_inside_the_emitted_JavaScript_6643": "Schließen Sie Quellzuordnungsdateien in das ausgegebene JavaScript ein.", + "Includes_imports_of_types_referenced_by_0_90054": "Schließt Importe von Typen ein, auf die von „{0}“ verwiesen wird", + "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914": "Bei Einschließung von --watch beginnt -w, das aktuelle Projekt auf Dateiänderungen zu überwachen. Einmal eingestellt, können Sie den Überwachungsmodus konfigurieren, und zwar mit:", + "Incomplete_quantifier_Digit_expected_1505": "Unvollständiger Quantifizierer. Eine Ziffer wurde erwartet.", + "Index_signature_for_type_0_is_missing_in_type_1_2329": "Die Indexsignatur für den Typ \"{0}\" fehlt im Typ \"{1}\".", + "Index_signature_in_type_0_only_permits_reading_2542": "Die Indexsignatur in Typ \"{0}\" lässt nur Lesevorgänge zu.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Einzelne Deklarationen in der gemergten Deklaration \"{0}\" müssen alle exportiert oder alle lokal sein.", + "Infer_all_types_from_usage_95023": "Alle Typen aus der Syntax ableiten", + "Infer_function_return_type_95148": "Funktionsrückgabetyp ableiten", + "Infer_parameter_types_from_usage_95012": "Parametertypen aus der Nutzung ableiten", + "Infer_this_type_of_0_from_usage_95080": "Typ \"this\" von \"{0}\" aus Syntax ableiten", + "Infer_type_of_0_from_usage_95011": "Typ von \"{0}\" aus der Nutzung ableiten", + "Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations_9022": "Der Rückschluss von Klassenausdrücken wird mit \"--isolatedDeclarations\" nicht unterstützt.", + "Initialize_property_0_in_the_constructor_90020": "Eigenschaft \"{0}\" im Konstruktor initialisieren", + "Initialize_static_property_0_90021": "Statische Eigenschaft \"{0}\" initialisieren", + "Initializer_for_property_0_2811": "Initialisierer für Eigenschaft \"{0}\"", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Der Initialisierer der Instanzmembervariablen \"{0}\" darf nicht auf den im Konstruktor deklarierten Bezeichner \"{1}\" verweisen.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Initialisierer sind in Umgebungskontexten unzulässig.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Initialisiert ein TypeScript-Projekt und erstellt eine Datei \"tsconfig.json\".", + "Inline_variable_95184": "Inlinevariable", + "Insert_command_line_options_and_files_from_a_file_6030": "Fügt Befehlszeilenoptionen und Dateien aus einer Datei ein.", + "Install_0_95014": "\"{0}\" installieren", + "Install_all_missing_types_packages_95033": "Alle fehlenden Typenpakete installieren", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "Die Schnittstelle \"{0}\" kann die Typen \"{1}\" und \"{2}\" nicht gleichzeitig erweitern.", + "Interface_0_incorrectly_extends_interface_1_2430": "Die Schnittstelle \"{0}\" erweitert fälschlicherweise die Schnittstelle \"{1}\".", + "Interface_declaration_cannot_have_implements_clause_1176": "Die Schnittstellendeklarationen darf keine implements-Klausel aufweisen.", + "Interface_must_be_given_a_name_1438": "Schnittstelle muss einen Namen erhalten.", + "Interface_name_cannot_be_0_2427": "Der Schnittstellenname darf nicht \"{0}\" sein.", + "Interop_Constraints_6252": "Interop-Einschränkungen", + "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243": "Interpretieren Sie optionale Eigenschaftstypen als geschrieben, statt 'nicht definiert' hinzuzufügen.", + "Invalid_character_1127": "Ungültiges Zeichen.", + "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "Der ungültige Importbezeichner \"{0}\" weist keine möglichen Auflösungen auf.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Ungültiger Modulname in Augmentation. Das Modul \"{0}\" wird in ein nicht typisiertes Modul in \"{1}\" aufgelöst, das nicht augmentiert werden kann.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Ungültiger Modulname in der Erweiterung. Das Modul \"{0}\" wurde nicht gefunden.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Ungültige optionale Kette aus neuem Ausdruck. Wollten Sie '{0}()' anrufen?", + "Invalid_reference_directive_syntax_1084": "Ungültige Syntax der reference-Direktive.", + "Invalid_syntax_in_decorator_1498": "Ungültige Syntax im Decorator.", + "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Ungültige Verwendung von \"{0}\". Es kann nicht innerhalb eines statischen Klassenblocks verwendet werden.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Ungültige Verwendung von \"{0}\". Module befinden sich automatisch im Strict-Modus.", + "Invalid_use_of_0_in_strict_mode_1100": "Ungültige Verwendung von \"{0}\" im Strict-Modus.", + "Invalid_value_for_ignoreDeprecations_5103": "Ungültiger Wert für \"--ignoreDeprecations\".", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Ungültiger Wert für \"jsxFactory\". \"{0}\" ist kein gültiger Bezeichner oder qualifizierter Name.", + "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035": "Ungültiger Wert für \"jsxFragmentFactory\". \"{0}\" ist kein gültiger Bezeichner oder qualifizierter Name.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Ungültiger Wert für \"-reactNamespace\". \"{0}\" ist kein gültiger Bezeichner.", + "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796": "Möglicherweise fehlt ein Komma, um diese beiden Vorlagenausdrücke zu trennen. Sie bilden einen Vorlagenausdruck mit Tags, der nicht aufgerufen werden kann.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Der zugehörige Elementtyp \"{0}\" ist kein gültiges JSX-Element.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Der zugehörige Instanztyp \"{0}\" ist kein gültiges JSX-Element.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Der Rückgabetyp \"{0}\" ist kein gültiges JSX-Element.", + "Its_type_0_is_not_a_valid_JSX_element_type_18053": "Der zugehörige Typ \"{0}\" ist kein gültiger JSX-Elementtyp.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc \"@{0} {1}\" entspricht nicht der Klausel \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc \"@{0}\" ist keiner Klassendeklaration zugeordnet.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "Das JSDoc-Tag \"...\" wird möglicherweise nur im letzten Parameter einer Signatur angezeigt.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Das JSDoc-Tag \"@param\" weist den Namen \"{0}\" auf, es gibt jedoch keinen Parameter dieses Namens.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Das JSDoc-Tag \"@param\" weist den Namen \"{0}\" auf, es ist jedoch kein Parameter dieses Namens vorhanden. Es läge eine Übereinstimmung mit \"arguments\" vor, wenn ein Arraytyp vorläge.", + "JSDoc_typedef_may_be_converted_to_TypeScript_type_80009": "JSDoc typedef kann in TypeScript-Typ konvertiert werden.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Das JSDoc-Tag \"@typedef\" muss entweder eine Typanmerkung aufweisen, oder die Tags \"@property\" oder \"@member\" müssen darauf folgen.", + "JSDoc_typedefs_may_be_converted_to_TypeScript_types_80010": "JSDoc typedefs können in TypeScript-Typen konvertiert werden.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc-Typen können nur innerhalb von Dokumentationskommentaren verwendet werden.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc-Typen können in TypeScript-Typen verschoben werden.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX-Attributen darf nur ein nicht leeres expression-Objekt zugewiesen werden.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Das JSX-Element \"{0}\" weist kein entsprechendes schließendes Tag auf.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Die JSX-Elementklasse unterstützt keine Attribute, weil sie keine Eigenschaft \"{0}\" aufweist.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "Das JSX-Element enthält implizit den Typ \"any\", weil keine Schnittstelle \"JSX.{0}\" vorhanden ist.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "Das JSX-Element enthält implizit den Typ \"any\", weil der globale Typ \"JSX.Element\" nicht vorhanden ist.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Der JSX-Elementtyp \"{0}\"weist keine Konstrukt- oder Aufrufsignaturen auf.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX-Elemente dürfen nicht mehrere Attribute mit dem gleichen Namen aufweisen.", + "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007": "JSX-Ausdrücke dürfen keinen Komma-Operator verwenden. Wollten Sie ein Array schreiben?", + "JSX_expressions_must_have_one_parent_element_2657": "JSX-Ausdrücke müssen ein übergeordnetes Element aufweisen.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Das JSX-Fragment weist kein entsprechendes schließendes Tag auf.", + "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633": "Ausdrücke für den Zugriff auf JSX-Eigenschaften dürfen keine JSX-Namespacenamen enthalten.", + "JSX_spread_child_must_be_an_array_type_2609": "Die untergeordnete JSX-Verteilung muss ein Arraytyp sein.", + "JavaScript_Support_6247": "JavaScript-Unterstützung", + "Jump_target_cannot_cross_function_boundary_1107": "Das Sprungziel darf die Funktionsgrenze nicht überschreiten.", + "KIND_6034": "ART", + "Keywords_cannot_contain_escape_characters_1260": "Schlüsselwörter können keine Escapezeichen enthalten.", + "LOCATION_6037": "SPEICHERORT", + "Language_and_Environment_6254": "Sprache und Umgebung", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Die linke Seite des Kommaoperators wird nicht verwendet besitzt keine Nebenwirkungen.", + "Library_0_specified_in_compilerOptions_1422": "In \"compilerOptions\" angegebene Bibliothek \"{0}\"", + "Library_referenced_via_0_from_file_1_1405": "Bibliothek, die über \"{0}\" aus der Datei \"{1}\" referenziert wird", + "Line_break_not_permitted_here_1142": "Ein Zeilenumbruch ist hier unzulässig.", + "Line_terminator_not_permitted_before_arrow_1200": "Das Zeilenabschlusszeichen ist vor dem Pfeil unzulässig.", + "List_of_file_name_suffixes_to_search_when_resolving_a_module_6931": "Liste der Dateinamensuffixe, die beim Auflösen eines Moduls gesucht werden sollen.", + "List_of_folders_to_include_type_definitions_from_6161": "Liste der Ordner, aus denen Typendefinitionen einbezogen werden sollen.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Liste der Stammordner, deren kombinierter Inhalt die Struktur des Projekts zur Laufzeit darstellt.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "\"{0}\" wird aus dem Stammverzeichnis \"{1}\" geladen. Speicherort des Kandidaten \"{2}\".", + "Loading_module_0_from_node_modules_folder_target_file_types_Colon_1_6098": "Modul \"{0}\" wird aus dem Ordner \"node_modules\" geladen, Zieldateitypen: {1}.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1_6095": "Modul wird als Datei/Ordner geladen, der Speicherort des Kandidatenmoduls ist \"{0}\", Zieldateitypen: {1}.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Für das Gebietsschema ist das Format oder - erforderlich, z. B. \"{0}\" oder \"{1}\".", + "Log_paths_used_during_the_moduleResolution_process_6706": "Protokollpfade, die während des „moduleResolution“-Prozesses verwendet werden.", + "Longest_matching_prefix_for_0_is_1_6108": "Das längste übereinstimmende Präfix für \"{0}\" ist \"{1}\".", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Die Suche erfolgt im Ordner \"node_modules\". Anfangsspeicherort \"{0}\".", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Alle \"super()\"-Aufrufe als erste Anweisung im entsprechenden Konstruktor festlegen", + "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Stellen Sie ein, dass keyof nur Zeichenfolgen, anstelle von Zeichenfolgen, Zahlen oder Symbolen zurückgibt. Legacy-Option.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "super()-Aufruf als erste Anweisung im Konstruktor festlegen", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Der zugeordnete Objekttyp weist implizit einen any-Vorlagentyp auf.", + "Mark_array_literal_as_const_90070": "Arrayliteral als \"const\" markieren", + "Matched_0_condition_1_6403": "Übereinstimmung mit \"{0}\" Bedingung \"{1}\".", + "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Standardmäßig zugeordnetes Includemuster „**/*“", + "Matched_by_include_pattern_0_in_1_1407": "Abgeglichen mit dem include-Muster \"{0}\" in \"{1}\"", + "Member_0_implicitly_has_an_1_type_7008": "Der Member \"{0}\" weist implizit den Typ \"{1}\" auf.", + "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Member \"{0}\" weist implizit einen Typ \"{1}\" auf, möglicherweise kann jedoch ein besserer Typ aus der Syntax abgeleitet werden.", + "Merge_conflict_marker_encountered_1185": "Mergekonfliktmarkierung", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Die gemergte Deklaration \"{0}\" darf keine Exportstandarddeklaration enthalten. Fügen Sie ggf. eine separate Deklaration \"export default {0}\" hinzu.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "Die Metaeigenschaft \"{0}\" ist nur im Text einer Funktionsdeklaration, eines Funktionsausdrucks oder eines Konstruktors zulässig.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Die Methode \"{0}\" darf keine Implementierung besitzen, weil sie als abstrakt markiert ist.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Die Methode \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Die Methode \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9008": "Die Methode muss eine explizite Rückgabetypanmerkung mit \"--isolatedDeclarations\" aufweisen.", + "Method_not_implemented_95158": "Die Methode ist nicht implementiert.", + "Modifiers_cannot_appear_here_1184": "Modifizierer dürfen hier nicht enthalten sein.", + "Module_0_can_only_be_default_imported_using_the_1_flag_1259": "Das Modul \"{0}\" kann nur mit dem Flag \"{1}\" als Standard importiert werden.", + "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471": "Das Modul \"{0}\" kann nicht mit diesem Konstrukt importiert werden. Der Spezifizierer wird nur in ein ES-Modul aufgelöst, das nicht mit \"require\" importiert werden kann. Verwenden Sie stattdessen einen ECMAScript-Import.", + "Module_0_declares_1_locally_but_it_is_exported_as_2_2460": "Das Modul \"{0}\" deklariert \"{1}\" lokal, der Export erfolgt jedoch als \"{2}\".", + "Module_0_declares_1_locally_but_it_is_not_exported_2459": "Das Modul \"{0}\" deklariert \"{1}\" lokal, es erfolgt jedoch kein Export.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340": "Das Modul \"{0}\" verweist nicht auf einen Typ, wird hier aber als Typ verwendet. Meinten Sie \"typeof import('{0}')\"?", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Das Modul \"{0}\" verweist nicht auf einen Wert, wird hier aber als Wert verwendet.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Das Modul \"{0}\" hat bereits einen Member mit dem Namen \"{1}\" exportiert. Erwägen Sie, ihn explizit erneut zu exportieren, um die Mehrdeutigkeit zu vermeiden.", + "Module_0_has_no_default_export_1192": "Das Modul \"{0}\" weist keinen Standardexport auf.", + "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613": "Das Modul \"{0}\" weist keinen Standardexport auf. Wollten Sie stattdessen \"import { {1} } from {0}\" verwenden?", + "Module_0_has_no_exported_member_1_2305": "Das Modul \"{0}\" weist keinen exportierten Member \"{1}\" auf.", + "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614": "Das Modul \"{0}\" umfasst keinen exportierten Member \"{1}\". Wollten Sie stattdessen \"import {1} from {0}\" verwenden?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Das Modul \"{0}\" wird durch eine lokale Deklaration mit dem gleichen Namen ausgeblendet.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Das Modul \"{0}\" verwendet \"export =\" und darf nicht mit \"export *\" verwendet werden.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Das Modul \"{0}\" wurde als lokal deklariertes Umgebungsmodul in der Datei \"{1}\" aufgelöst.", + "Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set_6263": "Das Modul \"{0}\" wurde in \"{1}\" aufgelöst, aber \"--allowArbitraryExtensions\" ist nicht festgelegt.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Das Modul \"{0}\" wurde zu \"{1}\" aufgelöst, aber \"--jsx\" wurde nicht festgelegt.", + "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042": "Das Modul \"{0}\" wurde in \"{1}\" aufgelöst, aber \"--resolveJsonModule\" wird nicht verwendet.", + "Module_declaration_names_may_only_use_or_quoted_strings_1443": "Namen der Moduldeklaration dürfen nur Zeichenfolgen enthalten, die von ' oder \" eingeschlossen werden.", + "Module_name_0_matched_pattern_1_6092": "Modulname \"{0}\", übereinstimmendes Muster \"{1}\".", + "Module_name_0_was_not_resolved_6090": "======== Der Modulname \"{0}\" wurde nicht aufgelöst. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Der Modulname \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. ========", + "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218": "======== Der Modulname \"{0}\" wurde erfolgreich in \"{1}\" mit Paket-ID \"{2}\" aufgelöst. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Die Art der Modulauflösung wird nicht angegeben. \"{0}\" wird verwendet.", + "Module_resolution_using_rootDirs_has_failed_6111": "Fehler bei der Modulauflösung mithilfe von \"rootDirs\".", + "Modules_6244": "Module", + "Move_labeled_tuple_element_modifiers_to_labels_95117": "Modifizierer für bezeichnete Tupelelemente in Bezeichnungen verschieben", + "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036": "Verschieben Sie den Ausdruck im Standardexport in eine Variable, und fügen Sie ihm eine Typanmerkung hinzu.", + "Move_to_a_new_file_95049": "In neue Datei verschieben", + "Move_to_file_95178": "In Datei verschieben", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Mehrere aufeinander folgende numerische Trennzeichen sind nicht zulässig.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Mehrere Konstruktorimplementierungen sind unzulässig.", + "NEWLINE_6061": "NEUE ZEILE", + "Name_is_not_valid_95136": "Der Name ist ungültig.", + "Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later_1503": "Benannte Erfassungsgruppen sind nur verfügbar, wenn das Ziel \"ES2018\" oder höher ist.", + "Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other_1515": "Benannte Erfassungsgruppen mit demselben Namen müssen sich gegenseitig ausschließen.", + "Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0_1544": "Benannte Importe aus einer JSON-Datei in ein ECMAScript-Modul sind nicht erlaubt, wenn 'module' auf '{0}'.", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Die benannte Eigenschaft \"{0}\" der Typen \"{1}\" und \"{2}\" ist nicht identisch.", + "Namespace_0_has_no_exported_member_1_2694": "Der Namespace \"{0}\" besitzt keinen exportierten Member \"{1}\".", + "Namespace_must_be_given_a_name_1437": "Namespace muss einen Namen erhalten.", + "Namespace_name_cannot_be_0_2819": "Namespacename darf nicht \"{0}\" sein.", + "Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to__1280": "Namespaces sind in globalen Skriptdateien nicht zulässig, wenn \"{0}\" aktiviert ist. Wenn diese Datei kein globales Skript sein soll, legen Sie \"moduleDetection\" auf \"force\" fest, oder fügen Sie eine leere \"export {}\"-Anweisung hinzu.", + "Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters_1433": "Weder Decorators noch Modifizierer können auf \"this\"-Parameter angewendet werden.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Kein Basiskonstruktor weist die angegebene Anzahl von Typargumenten auf.", + "No_constituent_of_type_0_is_callable_2755": "Es ist kein Bestandteil vom Typ \"{0}\" aufrufbar.", + "No_constituent_of_type_0_is_constructable_2759": "Es kann kein Bestandteil vom Typ \"{0}\" erstellt werden.", + "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054": "Für den Typ \"{1}\" wurde keine Indexsignatur mit einem Parameter vom Typ \"{0}\" gefunden.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "In der Konfigurationsdatei \"{0}\" wurden keine Eingaben gefunden. Als include-Pfade wurden \"{1}\", als exclude-Pfade wurden \"{2}\" angegeben.", + "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608": "Wird nicht mehr unterstützt. Legen Sie die Textcodierung für das Lesen von Dateien in früheren Versionen manuell fest.", + "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575": "Keine Überladung erwartet {0} Argumente, aber es sind Überladungen vorhanden, die entweder {1} oder {2} Argumente erwarten.", + "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743": "Keine Überladung erwartet {0} Typargumente, aber es sind Überladungen vorhanden, die entweder {1} oder {2} Typargumente erwarten.", + "No_overload_matches_this_call_2769": "Keine Überladung stimmt mit diesem Aufruf überein.", + "No_type_could_be_extracted_from_this_type_node_95134": "Aus diesem Typknoten konnte kein Typ extrahiert werden.", + "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004": "Im Bereich für die Kompakteigenschaft \"{0}\" ist kein Wert vorhanden. Deklarieren Sie entweder einen Wert, oder geben Sie einen Initialisierer an.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Die nicht abstrakte Klasse \"{0}\" implementiert nicht den geerbten abstrakten Member {1} aus der Klasse \"{2}\".", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_2654": "In der nicht abstrakten Klasse \"{0}\" fehlen Implementierungen für die folgenden Member von \"{1}\": {2}.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more_2655": "In der nicht abstrakten Klasse \"{0}\" fehlen Implementierungen für die folgenden Member von \"{1}\": {2} und {3} weitere.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Der nicht abstrakte Ausdruck implementiert nicht den geerbten abstrakten Member \"{0}\" aus der Klasse \"{1}\".", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_2656": "Im nicht abstrakten Klassenausdruck fehlen Implementierungen für die folgenden Member von \"{0}\": {1}.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and__2650": "Im nicht abstrakten Klassenausdruck fehlen Implementierungen für die folgenden Member von \"{0}\": {1} und {2} weitere.", + "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013": "Assertionen ungleich NULL können nur in TypeScript-Dateien verwendet werden.", + "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090": "Nicht relative Pfade sind nur zulässig, wenn \"baseUrl\" festgelegt wurde. Fehlt am Anfang die Zeichenfolge \"./\"?", + "Non_simple_parameter_declared_here_1348": "Hier wurde ein nicht einfacher Parameter deklariert.", + "Not_all_code_paths_return_a_value_7030": "Nicht alle Codepfade geben einen Wert zurück.", + "Not_all_constituents_of_type_0_are_callable_2756": "Nicht alle Bestandteile vom Typ \"{0}\" können aufgerufen werden.", + "Not_all_constituents_of_type_0_are_constructable_2760": "Nicht alle Bestandteile vom Typ \"{0}\" können erstellt werden.", + "Numbers_out_of_order_in_quantifier_1506": "Zahlen im Quantifizierer nicht in der richtigen Reihenfolge.", + "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008": "Numerische Literale mit absoluten Werten von 2^53 oder höher sind zu groß, um als ganze Zahlen genau dargestellt werden zu können.", + "Numeric_separators_are_not_allowed_here_6188": "Numerische Trennzeichen sind hier nicht zulässig.", + "Object_is_of_type_unknown_2571": "Das Objekt ist vom Typ \"Unbekannt\".", + "Object_is_possibly_null_2531": "Das Objekt ist möglicherweise \"NULL\".", + "Object_is_possibly_null_or_undefined_2533": "Das Objekt ist möglicherweise \"NULL\" oder \"nicht definiert\".", + "Object_is_possibly_undefined_2532": "Das Objekt ist möglicherweise \"nicht definiert\".", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Das Objektliteral kann nur bekannte Eigenschaften angeben, und \"{0}\" ist im Typ \"{1}\" nicht vorhanden.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Das Objektliteral gibt möglicherweise nur bekannte Eigenschaften an, \"{0}\" ist jedoch im Typ \"{1}\" nicht vorhanden. Wollten Sie \"{2}\" schreiben?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "Die Eigenschaft \"{0}\" des Objektliterals weist implizit den Typ \"{1}\" auf.", + "Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations_9016": "Objekte, die Kurzformeigenschaften enthalten, können nicht mit \"--isolatedDeclarations\" abgeleitet werden.", + "Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations_9015": "Objekte, die Verteilungszuweisungen enthalten, können nicht mit \"--isolatedDeclarations\" abgeleitet werden.", + "Octal_digit_expected_1178": "Es wurde eine Oktalzahl erwartet.", + "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536": "Oktale Escapesequenzen und Rückvektoren sind in einer Zeichenklasse nicht zulässig. Wenn dies als Escapesequenz vorgesehen war, verwenden Sie stattdessen die Syntax \"{0}\".", + "Octal_escape_sequences_are_not_allowed_Use_the_syntax_0_1487": "Oktale Escapesequenzen sind nicht zulässig. Verwenden Sie die Syntax \"{0}\".", + "Octal_literals_are_not_allowed_Use_the_syntax_0_1121": "Oktale Literale sind nicht zulässig. Verwenden Sie die Syntax \"{0}\".", + "One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value_4126": "Ein Wert von \"{0}.{1}\" ist die Zeichenfolge \"{2}\", und der andere Wert wird als unbekannter numerischer Wert angenommen.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "In einer for...in-Anweisung ist nur eine einzige Variablendeklaration zulässig.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "In einer for...of-Anweisung ist nur eine einzige Variablendeklaration zulässig.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Nur eine void-Funktion kann mit dem Schlüsselwort \"new\" aufgerufen werden.", + "Only_ambient_modules_can_use_quoted_names_1035": "Nur Umgebungsmodule dürfen Namen in Anführungszeichen verwenden.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Nur die Module \"amd\" und \"system\" werden in Verbindung mit --{0} unterstützt.", + "Only_const_arrays_can_be_inferred_with_isolatedDeclarations_9017": "Nur const-Arrays können mit \"--isolatedDeclarations\" abgeleitet werden.", + "Only_emit_d_ts_declaration_files_6014": "Geben Sie nur .d.ts-Deklarationsdateien aus.", + "Only_output_d_ts_files_and_not_JavaScript_files_6623": "Nur d.ts-Dateien und keine JavaScript-Dateien ausgeben.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Nur auf öffentliche und geschützte Methoden der Basisklasse kann über das Schlüsselwort \"super\" zugegriffen werden.", + "Operator_0_cannot_be_applied_to_type_1_2736": "Der Operator \"{0}\" kann nicht auf den Typ \"{1}\" angewendet werden.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Der Operator \"{0}\" darf nicht auf die Typen \"{1}\" und \"{2}\" angewendet werden.", + "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519": "Operatoren dürfen innerhalb einer Zeichenklasse nicht gemischt werden. Verpacken Sie ihn stattdessen in eine geschachtelte Klasse.", + "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619": "Deaktivieren Sie bei der Bearbeitung ein Projekt von der Überprüfung mehrerer Projektverweise.", + "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108": "Die Option \"{0}={1}\" wurde entfernt. Entfernen Sie sie aus Ihrer Konfiguration.", + "Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDepr_5107": "Die Option \"{0}={1}\" ist veraltet und funktioniert in TypeScript {2} nicht mehr. Geben Sie die compilerOption \"ignoreDeprecations\": \"{3}\" an, um diesen Fehler stumm zu schalten.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "Die Option \"{0}\" kann nur in der Datei \"tsconfig.json\" angegeben oder in der Befehlszeile auf FALSE oder NULL festgelegt werden.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "Die Option \"{0}\" kann nur in der Datei \"tsconfig.json\" angegeben oder in der Befehlszeile auf NULL festgelegt werden.", + "Option_0_can_only_be_specified_on_command_line_6266": "Die Option \"{0}\" kann nur in der Befehlszeile angegeben werden.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "Die Option \"{0}\" kann nur verwendet werden, wenn die Option \"-inlineSourceMap\" oder \"-sourceMap\" angegeben wird.", + "Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler_5098": "Die Option \"{0}\" kann nur verwendet werden, wenn \"moduleResolution\" auf \"node16\", \"nodenext\" oder \"bundler\" festgelegt ist.", + "Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later_5095": "Die Option \"{0}\" kann nur verwendet werden, wenn \"module\" auf \"preserve\" oder auf \"es2015\" oder höher festgelegt ist.", + "Option_0_cannot_be_specified_when_option_jsx_is_1_5089": "Die Option \"{0}\" kann nicht angegeben werden, wenn die Option \"jsx\" den Wert \"{1}\" aufweist.", + "Option_0_cannot_be_specified_with_option_1_5053": "Die Option \"{0}\" darf nicht zusammen mit der Option \"{1}\" angegeben werden.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Die Option \"{0}\" darf nicht ohne die Option \"{1}\" angegeben werden.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Die Option \"{0}\" kann nicht ohne die Option \"{1}\" oder \"{2}\" angegeben werden.", + "Option_0_has_been_removed_Please_remove_it_from_your_configuration_5102": "Die Option \"{0}\" wurde entfernt. Entfernen Sie sie aus Ihrer Konfiguration.", + "Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprec_5101": "Die Option \"{0}\" ist veraltet und funktioniert in TypeScript {1} nicht mehr. Geben Sie die compilerOption \"ignoreDeprecations\": \"{2}\" an, um diesen Fehler stumm zu schalten.", + "Option_0_is_redundant_and_cannot_be_specified_with_option_1_5104": "Die Option \"{0}\" ist redundant und darf nicht zusammen mit der Option \"{1}\" angegeben werden.", + "Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set_5096": "Die Option \"allowImportingTsExtensions\" kann nur verwendet werden, wenn entweder \"noEmit\" oder \"emitDeclarationOnly\" festgelegt ist.", + "Option_build_must_be_the_first_command_line_argument_6369": "Die Option \"--build\" muss das erste Befehlszeilenargument sein.", + "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074": "Die Option \"--incremental\" kann nur mit \"tsconfig\" und bei Ausgabe in eine einzelne Datei oder bei Festlegung der Option \"--tsBuildInfoFile\" angegeben werden.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Die Option \"isolatedModules\" kann nur verwendet werden, wenn entweder die Option \"--module\" angegeben ist oder die Option \"target\" den Wert \"ES2015\" oder höher aufweist.", + "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109": "Die Option \"moduleResolution\" muss auf \"{0}\" festgelegt werden (oder nicht angegeben werden), wenn die Option \"module\" auf \"{1}\" festgelegt ist.", + "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110": "Die Option \"module\" muss auf \"{0}\" festgelegt werden, wenn die Option \"moduleResolution\" auf \"{1}\" festgelegt ist.", + "Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled_5091": "Die Option \"preserveConstEnums\" kann nicht deaktiviert werden, wenn \"{0}\" aktiviert ist.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Die Option \"project\" darf nicht mit Quelldateien in einer Befehlszeile kombiniert werden.", + "Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic_5070": "Die Option \"--resolveJsonModule\" kann nicht angegeben werden, wenn \"moduleResolution\" auf \"classic\" festgelegt ist.", + "Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd_5071": "Die Option \"--resolveJsonModule\" kann nicht angegeben werden, wenn \"module\" auf \"none\", \"system\" oder \"umd\" festgelegt ist.", + "Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System_5105": "Die Option \"verbatimModuleSyntax\" kann nicht verwendet werden, wenn \"module\" auf \"UMD\", \"AMD\" oder \"System\" festgelegt ist.", + "Options_0_and_1_cannot_be_combined_6370": "Die Optionen \"{0}\" und \"{1}\" können nicht kombiniert werden.", + "Options_Colon_6027": "Optionen:", + "Output_Formatting_6256": "Ausgabeformatierung", + "Output_compiler_performance_information_after_building_6615": "Ausgabe Compiler-Leistungsinformationen nach dem Erstellen.", + "Output_directory_for_generated_declaration_files_6166": "Ausgabeverzeichnis für erstellte Deklarationsdateien.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Die Ausgabedatei \"{0}\" wurde nicht aus der Quelldatei \"{1}\" erstellt.", + "Output_from_referenced_project_0_included_because_1_specified_1411": "Ausgabe aus referenziertem Projekt \"{0}\" eingeschlossen, da \"{1}\" angegeben wurde", + "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412": "Ausgabe aus referenziertem Projekt \"{0}\" eingeschlossen, da \"--module\" als \"none\" angegeben wurde", + "Output_more_detailed_compiler_performance_information_after_building_6632": "Geben Sie ausführlichere Compilerleistungsinformationen nach der Erstellung aus.", + "Overload_0_of_1_2_gave_the_following_error_2772": "Die Überladung {0} von {1} ({2}) hat den folgenden Fehler verursacht.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Überladungssignaturen müssen alle abstrakt oder nicht abstrakt sein.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Überladungssignaturen müssen alle umgebend oder nicht umgebend sein.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Überladungssignaturen müssen alle exportiert oder nicht exportiert sein.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Überladungssignaturen müssen alle optional oder erforderlich sein.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Überladungssignaturen müssen alle öffentlich, privat oder geschützt sein.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Der Parameter \"{0}\" darf nicht auf den anschließend deklarierten Bezeichner \"{1}\" verweisen.", + "Parameter_0_cannot_reference_itself_2372": "Der Parameter \"{0}\" kann nicht auf sich selbst verweisen.", + "Parameter_0_implicitly_has_an_1_type_7006": "Der Parameter \"{0}\" weist implizit einen Typ \"{1}\" auf.", + "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Der Parameter \"{0}\" weist implizit einen Typ \"{1}\" auf, möglicherweise kann jedoch ein besserer Typ aus der Syntax abgeleitet werden.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Der Parameter \"{0}\" befindet sich nicht an der gleichen Position wie der Parameter \"{1}\".", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108": "Der Parameter \"{0}\" des Accessors besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107": "Der Parameter \"{0}\" des Accessors besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106": "Der Parameter \"{0}\" des Accessors besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Der Parameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Der Parameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Der Parameter \"{0}\" des Konstruktors aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Der Parameter \"{0}\" des Konstruktors aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Der Parameter \"{0}\" des Konstruktors aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Der Parameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Der Parameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Der Parameter \"{0}\" der exportierten Funktion besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Der Parameter \"{0}\" der exportierten Funktion besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Der Parameter \"{0}\" der exportierten Funktion besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Der Parameter \"{0}\" der Indexsignatur aus der exportierten Schnittstelle weist den Namen \"{1}\" aus dem privaten Modul \"{2}\" auf oder verwendet diesen.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Der Parameter \"{0}\" der Indexsignatur aus der exportierten Schnittstelle weist den privaten Namen \"{1}\" auf oder verwendet diesen.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Der Parameter \"{0}\" der Methode aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Der Parameter \"{0}\" der Methode aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Der Parameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Der Parameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Der Parameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Der Parameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Der Parameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Der Parameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Der Parameter darf kein Fragezeichen und keinen Initialisierer aufweisen.", + "Parameter_declaration_expected_1138": "Eine Parameterdeklaration wurde erwartet.", + "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051": "Der Parameter weist einen Namen, aber keinen Typ auf. Meinten Sie \"{0}: {1}\"?", + "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012": "Parametermodifizierer können nur in TypeScript-Dateien verwendet werden.", + "Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9011": "Der Parameter muss eine explizite Typanmerkung mit \"--isolatedDeclarations\" aufweisen.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Der Parametertyp des öffentlichen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Der Parametertyp des öffentlichen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Der Parametertyp des öffentlichen statischen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Der Parametertyp des öffentlichen statischen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Im Strict-Modus analysieren und \"use strict\" für jede Quelldatei ausgeben.", + "Part_of_files_list_in_tsconfig_json_1409": "Teil der Liste \"files\" in tsconfig.json", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Das Muster \"{0}\" darf höchstens ein Zeichen \"*\" aufweisen.", + "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386": "Leistungsdaten zum zeitlichen Ablauf sind für \"--diagnostics\" oder \"--extendedDiagnostics\" in dieser Sitzung nicht verfügbar. Eine native Implementierung der Webleistungs-API wurde nicht gefunden.", + "Platform_specific_6912": "Plattformspezifisch", + "Prefix_0_with_an_underscore_90025": "\"{0}\" einen Unterstrich voranstellen", + "Prefix_all_incorrect_property_declarations_with_declare_95095": "Verwenden Sie für alle falschen Eigenschaftendeklarationen das Präfix \"declare\".", + "Prefix_all_unused_declarations_with_where_possible_95025": "Alle nicht verwendeten Deklarationen nach Möglichkeit mit dem Präfix \"_\" versehen", + "Prefix_with_declare_95094": "Präfix \"declare\" voranstellen", + "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449": "Behalten Sie nicht verwendete importierte Werte in der JavaScript-Ausgabe bei, die andernfalls entfernt werden würden.", + "Print_all_of_the_files_read_during_the_compilation_6653": "Drucken Sie alle Dateien, die während der Kompilierung gelesen wurden.", + "Print_files_read_during_the_compilation_including_why_it_was_included_6631": "Während der Kompilierung gelesene Dateien drucken, einschließlich der Gründe für ihre Aufnahme.", + "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505": "Hiermit werden die Namen der Dateien und der Grund dafür ausgegeben, dass die Dateien in der Kompilierung enthalten sind.", + "Print_names_of_files_part_of_the_compilation_6155": "Drucknamen des Dateiteils der Kompilierung.", + "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "Hiermit werden Namen der Dateien ausgegeben, die Teil der Kompilierung sind. Anschließend wird die Verarbeitung beendet.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Drucknamen des generierten Dateiteils der Kompilierung.", + "Print_the_compiler_s_version_6019": "Die Version des Compilers ausgeben.", + "Print_the_final_configuration_instead_of_building_1350": "Hiermit wird anstelle eines Builds die endgültige Konfiguration ausgegeben.", + "Print_the_names_of_emitted_files_after_a_compilation_6652": "Drucken Sie die Namen der ausgegebenen Dateien nach einer Kompilierung.", + "Print_this_message_6017": "Diese Nachricht ausgeben.", + "Private_accessor_was_defined_without_a_getter_2806": "Die private Zugriffsmethode wurde ohne Getter definiert.", + "Private_field_0_must_be_declared_in_an_enclosing_class_1111": "Das private Feld \"{0}\" muss in einer einschließenden Klasse deklariert werden.", + "Private_identifiers_are_not_allowed_in_variable_declarations_18029": "Private Bezeichner sind in Variablendeklarationen nicht zulässig.", + "Private_identifiers_are_not_allowed_outside_class_bodies_18016": "Private Bezeichner sind außerhalb des Textes von Klassen nicht zulässig.", + "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451": "Private Bezeichner sind nur in Klassentexten zulässig und dürfen nur als Teil einer Klassenmitgliedsdeklaration, eines Eigenschaftszugriffs oder auf der linken Seite eines in-Ausdrucks verwendet werden.", + "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028": "Private Bezeichner sind nur verfügbar, wenn als Ziel ECMAScript 2015 oder höher verwendet wird.", + "Private_identifiers_cannot_be_used_as_parameters_18009": "Private Bezeichner können nicht als Parameter verwendet werden.", + "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105": "Für einen Typparameter kann nicht auf den privaten oder geschützten Member \"{0}\" zugegriffen werden.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Project '{0}' can't be built because its dependency '{1}' has errors", + "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Project '{0}' can't be built because its dependency '{1}' was not built", + "Project_0_is_being_forcibly_rebuilt_6388": "Die Neuerstellung des Projekts \"{0}\" wird erzwungen.", + "Project_0_is_out_of_date_because_1_6420": "Das Projekt \"{0}\" ist veraltet, da {1}.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_6412": "Das Projekt \"{0}\" ist veraltet, da die buildinfo-Datei \"{1}\" darauf hinweist, dass die Datei \"{2}\" die Stammdatei der Kompilierung war, es jetzt jedoch nicht mehr ist.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419": "Das Projekt \"{0}\" ist veraltet, da die Buildinfodatei \"{1}\" darauf hinweist, dass das Programm Fehler melden muss.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "Das Projekt \"{0}\" ist veraltet, da die Buildinfodatei \"{1}\" angibt, dass einige der Änderungen nicht ausgegeben wurden.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions_6406": "Das Projekt \"{0}\" ist veraltet, da die Buildinfodatei \"{1}\" auf eine Änderung in compilerOptions hinweist.", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Projekt \"{0}\" ist veraltet, weil die Abhängigkeit \"{1}\" veraltet ist.", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Das Projekt \"{0}\" ist veraltet, weil die Ausgabe \"{1}\" älter ist als die Eingabe \"{2}\"", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Projekt \"{0}\" ist veraltet, weil die Ausgabedatei \"{1}\" nicht vorhanden ist.", + "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Das Projekt \"{0}\" ist veraltet, weil die Ausgabe für das Projekt mit Version {1} generiert wurde, die sich von der aktuellen Version {2} unterscheidet.", + "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401": "Das Projekt \"{0}\" ist veraltet, weil beim Lesen der Datei \"{1}\" ein Fehler aufgetreten ist.", + "Project_0_is_up_to_date_6361": "Projekt \"{0}\" ist auf dem neuesten Stand.", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Projekt \"{0}\" ist auf dem neuesten Stand, weil die neueste Eingabe \"{1}\" älter ist als die Ausgabe \"{2}\".", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Das Projekt \"{0}\" ist aktuell, muss jedoch Zeitstempel von Ausgabedateien aktualisieren, die älter als Eingabedateien sind.", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Projekt \"{0}\" ist mit .d.ts-Dateien aus den zugehörigen Abhängigkeiten auf dem neuesten Stand.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Projektverweise dürfen keinen kreisförmigen Graphen bilden. Zyklus erkannt: {0}", + "Projects_6255": "Projekte", + "Projects_in_this_build_Colon_0_6355": "Projekte in diesem Build: {0}", + "Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher_18045": "Eigenschaften mit dem Accessormodifizierer sind nur für ECMAScript 2015 und höher verfügbar.", + "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267": "Die Eigenschaft \"{0}\" darf keinen Initialisierer aufweisen, weil sie als abstrakt markiert ist.", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "Die Eigenschaft \"{0}\" stammt aus einer Indexsignatur. Der Zugriff muss daher mit [\"{0}\"] erfolgen.", + "Property_0_does_not_exist_on_type_1_2339": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Die Eigenschaft \"{0}\" existiert nicht für Typ \"{1}\". Meinten Sie \"{2}\"?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden. Möchten Sie stattdessen auf den statischen Member \"{2}\" zugreifen?", + "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden. Müssen Sie Ihre Zielbibliothek ändern? Ändern Sie die Compileroption \"lib\" in \"{2}\" oder höher.", + "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden. Ändern Sie die Compileroption \"lib\" so, dass sie \"dom\" enthält.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817": "Die Eigenschaft \"{0}\" weist keinen Initialisierer auf und ist in einem statischen Klassenblock nicht definitiv zugewiesen.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Die Eigenschaft \"{0}\" weist keinen Initialisierer auf und ist im Konstruktor nicht definitiv zugewiesen.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem get-Accessor eine Parametertypanmerkung fehlt.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem set-Accessor eine Parametertypanmerkung fehlt.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, aber für den zugehörigen get-Accessor kann möglicherweise ein besserer Typ aus der Syntax abgeleitet werden.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, aber für den zugehörigen set-Accessor kann möglicherweise ein besserer Typ aus der Syntax abgeleitet werden.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann nicht der gleichen Eigenschaft in Basistyp \"{2}\" zugewiesen werden.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann dem Typ \"{2}\" nicht zugewiesen werden.", + "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "Die Eigenschaft \"{0}\" im Typ \"{1}\" verweist auf einen anderen Member, auf den nicht aus Typ \"{2}\" zugegriffen werden kann.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "Die Eigenschaft \"{0}\" ist deklariert, aber ihr Wert wird nie gelesen.", + "Property_0_is_incompatible_with_index_signature_2530": "Die Eigenschaft \"{0}\" ist nicht mit der Indexsignatur kompatibel.", + "Property_0_is_missing_in_type_1_2324": "Die Eigenschaft \"{0}\" fehlt im Typ \"{1}\".", + "Property_0_is_missing_in_type_1_but_required_in_type_2_2741": "Die Eigenschaft \"{0}\" fehlt im Typ \"{1}\", aber ist im Typ \"{2}\" erforderlich.", + "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013": "Auf die Eigenschaft \"{0}\" kann außerhalb der Klasse \"{1}\" nicht zugegriffen werden, weil sie einen privaten Bezeichner aufweist.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" optional, im Typ \"{2}\" aber erforderlich.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "Die Eigenschaft \"{0}\" ist privat. Auf sie kann nur innerhalb der Klasse \"{1}\" zugegriffen werden.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" privat, im Typ \"{2}\" hingegen nicht.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446": "Die Eigenschaft \"{0}\" ist geschützt und nur über eine Instanz der Klasse \"{1}\" zugänglich. Dies ist eine Instanz der Klasse \"{2}\".", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "Die Eigenschaft \"{0}\" ist geschützt. Auf sie kann nur innerhalb der Klasse \"{1}\" und ihrer Unterklassen zugegriffen werden.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "Die Eigenschaft \"{0}\" ist geschützt, Typ \"{1}\" ist aber keine von \"{2}\" abgeleitete Klasse.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" geschützt, im Typ \"{2}\" aber öffentlich.", + "Property_0_is_used_before_being_assigned_2565": "Die Eigenschaft \"{0}\" wird vor ihrer Zuweisung verwendet.", + "Property_0_is_used_before_its_initialization_2729": "Die Eigenschaft \"{0}\" wird vor ihrer Initialisierung verwendet.", + "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" möglicherweise nicht vorhanden. Meinten Sie \"{2}\"?", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Die Eigenschaft \"{0}\" des JSX-Verteilungsattributs kann nicht der Zieleigenschaft zugewiesen werden.", + "Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected_4094": "Die Eigenschaft \"{0}\" des exportierten anonymen Klassentyps ist unter Umständen nicht privat oder geschützt.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "Die Eigenschaft \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Die Eigenschaft \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411": "Die Eigenschaft \"{0}\" von Typ \"{1}\" kann nicht \"{2}\" Indextyp \"{3}\" zugewiesen werden.", + "Property_0_was_also_declared_here_2733": "Die Eigenschaft \"{0}\" wurde hier ebenfalls deklariert.", + "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612": "Die Eigenschaft \"{0}\" überschreibt die Basiseigenschaft in \"{1}\". Wenn dies beabsichtigt ist, fügen Sie einen Initialisierer hinzu. Andernfalls fügen Sie einen declare-Modifizierer hinzu, oder entfernen Sie die redundante Deklaration.", + "Property_assignment_expected_1136": "Die Zuweisung einer Eigenschaft wurde erwartet.", + "Property_destructuring_pattern_expected_1180": "Ein Eigenschaftendestrukturierungsmuster wurde erwartet.", + "Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9012": "Die Eigenschaft muss eine explizite Typanmerkung mit \"--isolatedDeclarations\" aufweisen.", + "Property_or_signature_expected_1131": "Eine Eigenschaft oder Signatur wurde erwartet.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Der Eigenschaftswert kann nur ein Zeichenfolgenliteral, ein numerisches Literal, \"true\", \"false\", \"NULL\", ein Objektliteral oder ein Arrayliteral sein.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_6179": "Bieten Sie vollständige Unterstützung für Iterablen in \"for-of\", Verteilung und Destrukturierung mit dem Ziel \"ES5\".", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Die öffentliche Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Die öffentliche Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Die öffentliche Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Die öffentliche Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Die öffentliche Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Die öffentliche Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Die öffentliche statische Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Die öffentliche statische Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Die öffentliche statische Methode \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Die öffentliche statische Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Die öffentliche statische Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Die öffentliche statische Eigenschaft \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032": "Der qualifizierte Name \"{0}\" ist ohne Voranstellung von \"@param {object} {1}\" nicht zulässig.", + "Raise_an_error_when_a_function_parameter_isn_t_read_6676": "Löst einen Fehler aus, wenn ein Funktionsparameter nicht gelesen wird.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Fehler für Ausdrücke und Deklarationen mit einem impliziten any-Typ auslösen.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Fehler für \"this\"-Ausdrücke mit einem impliziten any-Typ auslösen.", + "Range_out_of_order_in_character_class_1517": "Der Bereich in der Zeichenklasse liegt außerhalb der Reihenfolge.", + "Re_exporting_a_type_when_0_is_enabled_requires_using_export_type_1205": "Wenn \"{0}\" aktiviert ist, erfordert das erneute Exportieren eines Typs die Verwendung von \"export type\".", + "React_components_cannot_include_JSX_namespace_names_2639": "React-Komponenten dürfen keine JSX-Namespacenamen enthalten.", + "Redirect_output_structure_to_the_directory_6006": "Die Ausgabestruktur in das Verzeichnis umleiten.", + "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617": "Verringern Sie die Anzahl der Projekte, die von TypeScript automatisch geladen werden.", + "Referenced_project_0_may_not_disable_emit_6310": "Beim referenzierten Projekt \"{0}\" darf nicht die Ausgabe deaktiviert werden.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Das referenzierte Projekt \"{0}\" muss für die Einstellung \"composite\" den Wert TRUE aufweisen.", + "Referenced_via_0_from_file_1_1400": "Referenziert über \"{0}\" aus der Datei \"{1}\"", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2834": "Relative Importpfade erfordern explizite Dateierweiterungen in ECMAScript-Importen, wenn „--moduleResolution“ „node16“ oder „nodenext“ ist. Erwägen Sie, dem Importpfad eine Erweiterung hinzuzufügen.", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2835": "Relative Importpfade erfordern explizite Dateierweiterungen in ECMAScript-Importen, wenn „--moduleResolution“ „node16“ oder „nodenext“ ist. Meinten Sie \"{0}\"?", + "Remove_a_list_of_directories_from_the_watch_process_6628": "Entfernen Sie eine Liste von Verzeichnissen aus dem Überwachungsvorgang.", + "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629": "Entfernen Sie eine Liste von Dateien aus der Verarbeitung des Überwachungsmodus.", + "Remove_all_unnecessary_override_modifiers_95163": "Alle nicht benötigten override-Modifizierer entfernen", + "Remove_all_unnecessary_uses_of_await_95087": "Alle nicht benötigten Verwendungen von \"await\" entfernen", + "Remove_all_unreachable_code_95051": "Gesamten nicht erreichbaren Code entfernen", + "Remove_all_unused_labels_95054": "Alle nicht verwendeten Bezeichnungen entfernen", + "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115": "Entfernen Sie die geschweiften Klammern aus dem Text aller Pfeilfunktionen mit entsprechenden Problemen.", + "Remove_braces_from_arrow_function_95060": "Geschweifte Klammern aus Pfeilfunktion entfernen", + "Remove_braces_from_arrow_function_body_95112": "Geschweifte Klammern aus Pfeilfunktionstext entfernen", + "Remove_import_from_0_90005": "Import aus \"{0}\" entfernen", + "Remove_override_modifier_95161": "override-Modifizierer entfernen", + "Remove_parentheses_95126": "Klammern entfernen", + "Remove_template_tag_90011": "Vorlagentag entfernen", + "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618": "Entfernen Sie die Obergrenze von 20 MB für die Gesamtgröße des Quellcodes für JavaScript-Dateien auf dem TypeScript-Sprachserver.", + "Remove_type_from_import_declaration_from_0_90055": "„type“ aus Importdeklaration aus „{0}“ entfernen", + "Remove_type_from_import_of_0_from_1_90056": "„type“ aus Import von „{0}“ aus „{1}“ entfernen", + "Remove_type_parameters_90012": "Typparameter entfernen", + "Remove_unnecessary_await_95086": "Unnötige Vorkommen von \"await\" entfernen", + "Remove_unreachable_code_95050": "Nicht erreichbaren Code entfernen", + "Remove_unused_declaration_for_Colon_0_90004": "Nicht verwendete Deklaration für \"{0}\" entfernen", + "Remove_unused_declarations_for_Colon_0_90041": "Nicht verwendete Deklarationen für \"{0}\" entfernen", + "Remove_unused_destructuring_declaration_90039": "Nicht verwendete Destrukturierungsdeklaration entfernen", + "Remove_unused_label_95053": "Nicht verwendete Bezeichnung entfernen", + "Remove_variable_statement_90010": "Variablenanweisung entfernen", + "Rename_param_tag_name_0_to_1_95173": "Tagnamen \"@param\" \"{0}\" in \"{1}\" umbenennen", + "Replace_0_with_Promise_1_90036": "\"{0}\" durch \"Promise<{1}>\" ersetzen", + "Replace_all_unused_infer_with_unknown_90031": "Alle nicht verwendeten Vorkommen von \"infer\" durch \"unknown\" ersetzen", + "Replace_import_with_0_95015": "Ersetzen Sie den Import durch \"{0}\".", + "Replace_infer_0_with_unknown_90030": "\"infer {0}\" durch \"unknown\" ersetzen", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Fehler melden, wenn nicht alle Codepfade in der Funktion einen Wert zurückgeben.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Für FallTrough-Fälle in switch-Anweisung Fehler melden.", + "Report_errors_in_js_files_8019": "Fehler in .js-Dateien melden.", + "Report_errors_on_unused_locals_6134": "Fehler für nicht verwendete lokale Variablen melden.", + "Report_errors_on_unused_parameters_6135": "Fehler für nicht verwendete Parameter melden.", + "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719": "Fordern Sie eine ausreichende Anmerkung zu Exporten an, damit andere Tools Deklarationsdateien trivial generieren können.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717": "Nicht deklarierte Eigenschaften aus Indexsignaturen müssen Elementzugriffe verwenden.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Erforderliche Typparameter dürfen nicht auf optionale Typparameter folgen.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Die Auflösung für das Modul \"{0}\" wurde im Cache des Standorts \"{1}\" gefunden.", + "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "Die Auflösung für die Typreferenzanweisung \"{0}\" wurde im Cache des Standorts \"{1}\" gefunden.", + "Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_i_6277": "Fehler beim Auflösen des nicht relativen Namens. Es wird versucht, moderne Funktionen zur Knotenauflösung zu deaktivieren, um festzustellen, ob die npm-Bibliothek eine Konfigurationsaktualisierung erfordert.", + "Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_ne_6279": "Fehler beim Auflösen des nicht relativen Namens. Mit \"--moduleResolution bundler\" wird versucht festzustellen, ob das Projekt möglicherweise aktualisiert werden muss.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "\"keyof\" darf nur in Eigenschaftennamen mit Zeichenfolgenwert aufgelöst werden (keine Ziffern oder Symbole).", + "Resolved_under_condition_0_6414": "Aufgelöst unter Bedingung \"{0}\".", + "Resolving_in_0_mode_with_conditions_1_6402": "Wird im {0}-Modus mit Bedingungen \"{1}\" aufgelöst.", + "Resolving_module_0_from_1_6086": "======== Das Modul \"{0}\" aus \"{1}\" wird aufgelöst. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Der Modulname \"{0}\" relativ zur Basis-URL \"{1}\"–\"{2}\" wird aufgelöst.", + "Resolving_real_path_for_0_result_1_6130": "Der tatsächliche Pfad für \"{0}\" wird aufgelöst, Ergebnis \"{1}\".", + "Resolving_type_reference_directive_0_containing_file_1_6242": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die Datei \"{1}\" enthält. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die Datei \"{1}\" enthält. Das Stammverzeichnis ist \"{2}\". ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die Datei \"{1}\" enthält. Das Stammverzeichnis ist nicht festgelegt. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die nicht festgelegte Datei enthält. Das Stammverzeichnis ist \"{1}\". ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Die Typverweisdirektive \"{0}\" wird aufgelöst, die die nicht festgelegte Datei enthält. Das Stammverzeichnis ist nicht festgelegt. ========", + "Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_no_6265": "Die Typverweisdirektive für das Programm, das benutzerdefinierte typeRoots angibt, wird aufgelöst. Lookup im Ordner \"node_modules\" wird übersprungen.", + "Resolving_with_primary_search_path_0_6121": "Die Auflösung erfolgt mit dem primären Suchpfad \"{0}\".", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Der rest-parameter \"{0}\" weist implizit einen Typ \"any[]\" auf.", + "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047": "Der rest-Parameter \"{0}\" weist implizit einen Typ \"any[]\" auf, möglicherweise kann jedoch ein besserer Typ aus der Syntax abgeleitet werden.", + "Rest_types_may_only_be_created_from_object_types_2700": "Rest-Typen dürfen nur aus object-Typen erstellt werden.", + "Return_type_annotation_circularly_references_itself_2577": "Die Rückgabetypanmerkung verweist zirkulär auf sich selbst.", + "Return_type_must_be_inferred_from_a_function_95149": "Der Rückgabetyp muss aus einer Funktion abgeleitet werden.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Der Rückgabetyp der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Der Rückgabetyp der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Der Rückgabetyp der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Der Rückgabetyp der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Der Rückgabetyp der Konstruktorsignatur muss dem Instanztyp der Klasse zugewiesen werden können.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Der Rückgabetyp der exportierten Funktion besitzt oder verwendet den Namen \"{0}\" aus dem externen Modul \"{1}\", kann aber nicht benannt werden.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Der Rückgabetyp der exportierten Funktion besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Der Rückgabetyp der exportierten Funktion besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Der Rückgabetyp der Indexsignatur aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Der Rückgabetyp der Indexsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Der Rückgabetyp der Methode aus der exportierten Schnittstelle besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Der Rückgabetyp der Methode aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Der Rückgabetyp des öffentlichen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Der Rückgabetyp des öffentlichen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Der Rückgabetyp des öffentlichen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Der Rückgabetyp der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem externen Modul \"{1}\", kann aber nicht benannt werden.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Der Rückgabetyp der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Der Rückgabetyp der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{0}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Der Rückgabetyp des öffentlichen statischen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem externen Modul \"{2}\", kann aber nicht benannt werden.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Der Rückgabetyp des öffentlichen statischen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den Namen \"{1}\" aus dem privaten Modul \"{2}\".", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Der Rückgabetyp des öffentlichen statischen Getters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem externen Modul \"{1}\", kann aber nicht benannt werden.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den Namen \"{0}\" aus dem privaten Modul \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{0}\".", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395": "Die Auflösung des Moduls „{0}“ aus „{1}“ im Cache vom Speicherort „{2}“ wird wiederverwendet, sie wurde nicht aufgelöst.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393": "Die Auflösung des Moduls „{0}“ aus „{1}\" im Cache vom Speicherort „{2}“ wird wiederverwendet, sie wurde erfolgreich in „{3}“ aufgelöst.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394": "Die Auflösung des Moduls „{0}“ aus „{1}“ im Cache vom Speicherort „{2}“ wird wiederverwendet, sie wurde erfolgreich in „{3}“ mit der Paket-ID „{4}“ aufgelöst.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389": "Die Auflösung des Moduls „{0}“ aus „{1}“ des alten Programms wird wiederverwendet, sie wurde nicht aufgelöst.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183": "Die Auflösung des Moduls „{0}“ aus „{1}“ des alten Programms wird wiederverwendet, sie wurde erfolgreich in „{2}“ aufgelöst.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184": "Die Auflösung des Moduls „{0}“ aus „{1}“ des alten Programms wird wiederverwendet, sie wurde erfolgreich in „{2}“ mit der Paket-ID „{3}“ aufgelöst.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398": "Die Auflösung der Typverweisdirektive „{0}“ aus „{1}“ im Cache vom Speicherort „{2}“ wird wiederverwendet, sie wurde nicht aufgelöst.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396": "Die Auflösung der Typverweisdirektive „{0}“ aus „{1}“ im Cache vom Speicherort „{2}“ wird wiederverwendet, sie wurde erfolgreich in „{3}“ aufgelöst.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397": "Die Auflösung der Typverweisdirektive „{0}“ aus „{1}“ im Cache vom Speicherort „{2}“ wird wiederverwendet, sie wurde erfolgreich in „{3}“ mit der Paket-ID „{4}“ aufgelöst.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392": "Die Auflösung der Typverweisdirektive „{0}“ aus „{1}“ des alten Programms wird wiederverwendet, sie wurde nicht aufgelöst.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390": "Die Auflösung der Typverweisdirektive „{0}“ aus „{1}“ des alten Programms wird wiederverwendet, sie wurde erfolgreich in „{2}“ aufgelöst.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391": "Die Auflösung der Typverweisdirektive „{0}“ aus „{1}“ des alten Programms wird wiederverwendet, sie wurde erfolgreich in „{2}“ mit der Paket-ID „{3}“ aufgelöst.", + "Rewrite_all_as_indexed_access_types_95034": "Alle als indizierte Zugriffstypen neu schreiben", + "Rewrite_as_the_indexed_access_type_0_90026": "Als indizierten Zugriffstyp \"{0}\" neu schreiben", + "Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_i_6421": "Schreiben Sie die Dateiendungen '.ts', '.tsx', '.mts' und '.cts' in relativen Importpfaden in ihren JavaScript-Äquivalenten in den Ausgabedateien um.", + "Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish_2869": "Rechter Operand von ?? ist nicht erreichbar, weil der linke Operand nie \"NULLISH\" ist.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Das Stammverzeichnis kann nicht ermittelt werden. Die primären Suchpfade werden übersprungen.", + "Root_file_specified_for_compilation_1427": "Für die Kompilierung angegebene Stammdatei", + "STRATEGY_6039": "STRATEGIE", + "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Speichern Sie die .tsbuildinfo-Dateien, um eine inkrementelle Kompilierung von Projekten zuzulassen.", + "Saw_non_matching_condition_0_6405": "Die nicht übereinstimmende Bedingung \"{0}\" wurde angezeigt.", + "Scoped_package_detected_looking_in_0_6182": "Bereichsbezogenes Paket erkannt. In \"{0}\" wird gesucht", + "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418": "Alle node_modules-Vorgängerverzeichnisse werden nach Fallbackerweiterungen durchsucht: {0}.", + "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417": "Alle node_modules-Vorgängerverzeichnisse werden nach bevorzugten Erweiterungen durchsucht: {0}.", + "Selection_is_not_a_valid_statement_or_statements_95155": "Die Auswahl umfasst keine gültigen Anweisungen.", + "Selection_is_not_a_valid_type_node_95133": "Die Auswahl ist kein gültiger Typknoten.", + "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705": "Legen Sie die JavaScript-Sprachversion für das ausgegebene JavaScript fest, und schließen Sie kompatible Bibliotheksdeklarationen ein.", + "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654": "Legen Sie die Sprache des Messagings von TypeScript fest. Dies wirkt sich nicht auf die Ausgabe aus.", + "Set_the_module_option_in_your_configuration_file_to_0_95099": "Legen Sie die Option \"module\" in Ihrer Konfigurationsdatei auf \"{0}\" fest.", + "Set_the_newline_character_for_emitting_files_6659": "Legen Sie das Zeilenumbruchzeichen für Ausgabedateien fest.", + "Set_the_target_option_in_your_configuration_file_to_0_95098": "Legen Sie die Option \"target\" in Ihrer Konfigurationsdatei auf \"{0}\" fest.", + "Setters_cannot_return_a_value_2408": "Setter können keinen Wert zurückgeben.", + "Show_all_compiler_options_6169": "Alle Compileroptionen anzeigen.", + "Show_diagnostic_information_6149": "Diagnoseinformationen anzeigen.", + "Show_verbose_diagnostic_information_6150": "Ausführliche Diagnoseinformationen anzeigen.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Anzeigen, was erstellt würde (oder gelöscht würde, wenn mit \"--clean\" angegeben)", + "Signature_0_must_be_a_type_predicate_1224": "Die Signatur \"{0}\" muss ein Typprädikat sein.", + "Signature_declarations_can_only_be_used_in_TypeScript_files_8017": "Signaturdeklarationen können nur in TypeScript-Dateien verwendet werden.", + "Skip_building_downstream_projects_on_error_in_upstream_project_6640": "Überspringen Sie die Erstellung von Downstreamprojekten bei einem Fehler im Upstreamprojekt.", + "Skip_type_checking_all_d_ts_files_6693": "Überspringen Sie die Typüberprüfung aller .d.ts-Dateien.", + "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692": "Überspringen Sie die Typüberprüfung von .d.ts-Dateien, die in TypeScript enthalten sind.", + "Skip_type_checking_of_declaration_files_6012": "Überspringen Sie die Typüberprüfung von Deklarationsdateien.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Skipping build of project '{0}' because its dependency '{1}' has errors", + "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382": "Skipping build of project '{0}' because its dependency '{1}' was not built", + "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164": "Modul \"{0}\", das wie ein absoluter URI aussieht, wird übersprungen, Zieldateitypen: {1}.", + "Source_from_referenced_project_0_included_because_1_specified_1414": "Quelle aus referenziertem Projekt \"{0}\", da \"{1}\" angegeben wurde", + "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415": "Quelle aus referenziertem Projekt \"{0}\", da \"--module\" als \"none\" angegeben wurde", + "Source_has_0_element_s_but_target_allows_only_1_2619": "Die Quelle weist {0} Element(e) auf, aber das Ziel lässt nur {1} zu.", + "Source_has_0_element_s_but_target_requires_1_2618": "Die Quelle weist {0} Element(e) auf, aber das Ziel erfordert {1}.", + "Source_provides_no_match_for_required_element_at_position_0_in_target_2623": "Die Quelle weist keine Übereinstimmung für das erforderliche Element an Position {0} im Ziel auf.", + "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624": "Die Quelle weist keine Übereinstimmung für das variadic-Element an Position {0} im Ziel auf.", + "Specify_ECMAScript_target_version_6015": "Geben Sie die ECMAScript-Zielversion an.", + "Specify_JSX_code_generation_6080": "Geben Sie die JSX-Codegenerierung an.", + "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679": "Geben Sie eine Datei an, die alle Ausgaben in einer JavaScript-Datei bündelt. Wenn „declaration“ TRUE ist, wird auch eine Datei festgelegt, die alle „.d.ts“-Ausgaben bündelt.", + "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641": "Geben Sie eine Liste von Globmustern an, die mit Dateien übereinstimmen, die in die Kompilierung einbezogen werden sollen.", + "Specify_a_list_of_language_service_plugins_to_include_6681": "Geben Sie eine Liste der einzuschließenden Sprachdienst-Plug-Ins an.", + "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651": "Geben Sie einen Satz gebündelter Bibliotheksdeklarationsdateien an, die die Ziellaufzeitumgebung beschreiben.", + "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680": "Geben Sie einen Satz von Einträgen an, die Importe an zusätzliche Lookup-Speicherorte neu zuordnen.", + "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687": "Geben Sie ein Objektarray an, das Pfade für Projekte angibt. Wird in Projekt verweisen verwendet.", + "Specify_an_output_folder_for_all_emitted_files_6678": "Geben Sie einen Ausgabeordner für alle ausgegebenen Dateien an.", + "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718": "Geben Sie das Ausgabe-/Überprüfungsverhalten für Importe an, die nur für Typen verwendet werden.", + "Specify_file_to_store_incremental_compilation_information_6380": "Datei zum Speichern inkrementeller Kompilierungsinformationen angeben", + "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658": "Geben Sie an, wie TypeScript eine Datei aus einem angegebenen Modulspezifizierer sucht.", + "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714": "Geben Sie an, wie Verzeichnisse auf Systemen überwacht werden, für die eine rekursive Dateiüberwachungsfunktion fehlt.", + "Specify_how_the_TypeScript_watch_mode_works_6715": "Geben Sie an, wie der TypeScript-Überwachungsmodus funktioniert.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Geben Sie Bibliotheksdateien an, die in die Kompilierung eingeschlossen werden sollen.", + "Specify_module_code_generation_6016": "Geben Sie die Modulcodegenerierung an.", + "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649": "Geben Sie den Modulspezifizierer an, der zum Importieren der JSX-Factoryfunktionen verwendet wird, wenn Sie „jsx: react-jsx*“ verwenden.", + "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710": "Geben Sie mehrere Ordner an, die als „./node_modules/@types“ fungieren.", + "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633": "Geben Sie einen oder mehrere Pfad- oder Knotenmodulverweise auf Basiskonfigurationsdateien an, von denen Einstellungen geerbt werden.", + "Specify_options_for_automatic_acquisition_of_declaration_files_6709": "Geben Sie Optionen für den automatischen Erwerb von Deklarationsdateien an.", + "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227": "Geben Sie die Strategie zum Erstellen einer Abrufüberwachung an, wenn eine Erstellung mit Dateisystemereignissen nicht erfolgreich ist: \"FixedInterval\" (Standardwert), \"PriorityInterval\", \"DynamicPriority\", \"FixedChunkSize\".", + "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226": "Geben Sie die Strategie für die Verzeichnisüberwachung auf Plattformen an, die eine rekursive Überwachung nativ nicht unterstützen: \"UseFsEvents\" (Standardwert), \"FixedPollingInterval\", \"DynamicPriorityPolling\", \"FixedChunkSizePolling\".", + "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225": "Geben Sie die Strategie für die Dateiüberwachung an: \"FixedPollingInterval\" (Standardwert), \"PriorityPollingInterval\", \"DynamicPriorityPolling\", \"FixedChunkSizePolling\", \"UseFsEvents\", \"UseFsEventsOnParentDirectory\".", + "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648": "Geben Sie den JSX-Fragmentverweis an, der für Fragmente verwendet wird, wenn die React JSX-Ausgabe als Ziel verwendet wird, z. B. \"React.Fragment\" oder \"Fragment\".", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Geben Sie die JSX-Factoryfunktion an, die für eine react-JSX-Ausgabe verwendet werden soll, z. B. \"React.createElement\" oder \"h\".", + "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647": "Geben Sie die JSX-Factoryfunktion an, die verwendet wird, wenn Sie die JSX-Ausgabe „react“ als Ziel verwenden, z. B. „React.createElement“ oder „h“.", + "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034": "Geben Sie die jsxFragmentFactory-Funktion an, die bei Verwendung des JSX-Ausgabeziels \"react\" mit der Compileroption \"jsxFactory\" verwendet werden soll, z. B. \"Fragment\".", + "Specify_the_base_directory_to_resolve_non_relative_module_names_6607": "Geben Sie das Basisverzeichnis zum Auflösen nicht relativer Modulnamen an.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Geben Sie die Zeilenendesequenz an, die beim Ausgeben von Dateien verwendet werden soll: \"CRLF\" (DOS) oder \"LF\" (Unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Geben Sie den Speicherort an, an dem der Debugger TypeScript-Dateien ermitteln soll, anstatt Quellspeicherorte zu verwenden.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655": "Geben Sie den Speicherort an, an dem der Debugger Zuordnungsdateien ermitteln soll, anstatt generierte Speicherorte zu verwenden.", + "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656": "Geben Sie die maximale Ordnertiefe an, die zum Überprüfen von JavaScript-Dateien aus „node_modules“ verwendet wird. Gilt nur für „allowJs“.", + "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238": "Geben Sie den Modulspezifizierer an, aus dem die Factoryfunktionen \"jsx\" und \"jsxs\" importiert werden sollen, z. B. \"react\".", + "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686": "Geben Sie das Objekt an, das für „createElement“ aufgerufen wird. Dies gilt nur, wenn die JSX-Ausgabe „react“ als Ziel verwendet wird.", + "Specify_the_output_directory_for_generated_declaration_files_6613": "Geben Sie das Ausgabeverzeichnis für generierte Deklarationsdateien an.", + "Specify_the_path_to_tsbuildinfo_incremental_compilation_file_6707": "Geben Sie den Pfad zu inkrementelle Kompilierungsdateien .tsbuildinfo an.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Geben Sie das Stammverzeichnis der Eingabedateien an. Verwenden Sie diese Angabe, um die Ausgabeverzeichnisstruktur mithilfe von \"-outDir\" zu steuern.", + "Specify_the_root_folder_within_your_source_files_6690": "Geben Sie den Stammordner in den Quelldateien an.", + "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695": "Geben Sie den Stammpfad für Debugger an, um den Verweisquellcode zu suchen.", + "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711": "Geben Sie Typpaketnamen an, die eingeschlossen werden sollen, ohne in einer Quelldatei referenziert zu werden.", + "Specify_what_JSX_code_is_generated_6646": "Geben Sie an, welcher JSX-Code generiert wird.", + "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634": "Geben Sie an, welchen Ansatz der Watcher verwenden soll, wenn auf dem System keine nativen Dateiüberwachungen mehr vorhanden sind.", + "Specify_what_module_code_is_generated_6657": "Geben Sie an, welcher Modulcode generiert wird.", + "Split_all_invalid_type_only_imports_1367": "Alle ungültigen reinen Typenimporte teilen", + "Split_into_two_separate_import_declarations_1366": "In zwei separate Importdeklarationen teilen", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Der Verteilungsoperator in new-Ausdrücken ist nur verfügbar, wenn das Ziel ECMAScript 5 oder höher ist.", + "Spread_types_may_only_be_created_from_object_types_2698": "Spread-Typen dürfen nur aus object-Typen erstellt werden.", + "Starting_compilation_in_watch_mode_6031": "Kompilierung im Überwachungsmodus wird gestartet...", + "Statement_expected_1129": "Eine Anweisung wurde erwartet.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Anweisungen sind in Umgebungskontexten unzulässig.", + "Static_members_cannot_reference_class_type_parameters_2302": "Statische Member dürfen nicht auf Klassentypparameter verweisen.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "Die statische Eigenschaft \"{0}\" steht in Konflikt mit der integrierten Eigenschaft \"Function.{0}\" der Konstruktorfunktion \"{1}\".", + "String_literal_expected_1141": "Ein Zeichenfolgenliteral wurde erwartet.", + "String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es_18057": "Import- und Exportnamen von Zeichenfolgenliteralen werden nicht unterstützt, wenn das Flag \"--module\" auf \"es2015\" oder \"es2020\" festgelegt ist.", + "String_literal_with_double_quotes_expected_1327": "Ein Zeichenfolgenliteral mit doppelten Anführungszeichen wird erwartet.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Fehler und Nachrichten farbig und mit Kontext formatieren (experimentell).", + "Subpattern_flags_must_be_present_when_there_is_a_minus_sign_1504": "Subpatternkennzeichen müssen vorhanden sein, wenn ein Minuszeichen vorhanden ist.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Nachfolgende Eigenschaftendeklarationen müssen den gleichen Typ aufweisen. Die Eigenschaft \"{0}\" muss den Typ \"{1}\" aufweisen, ist hier aber vom Typ \"{2}\".", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Nachfolgende Variablendeklarationen müssen den gleichen Typ aufweisen. Die Variable \"{0}\" muss den Typ \"{1}\" aufweisen, ist hier aber vom Typ \"{2}\".", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Die Ersetzung \"{0}\" für das Muster \"{1}\" weist einen falschen Typ auf. Erwartet wurde \"string\", abgerufen wurde \"{2}\".", + "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062": "Die Ersetzung \"{0}\" im Muster \"{1}\" darf höchstens ein Zeichen \"*\" aufweisen.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Die Ersetzung für das Muster \"{0}\" muss ein Array sein.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Ersetzungen für das Muster \"{0}\" dürfen kein leeres Array sein.", + "Successfully_created_a_tsconfig_json_file_6071": "Eine Datei \"tsconfig.json\" wurde erfolgreich erstellt.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Aufrufe von \"super\" sind außerhalb von Konstruktoren oder in geschachtelten Funktionen innerhalb von Konstruktoren unzulässig.", + "Suppress_excess_property_checks_for_object_literals_6072": "Übermäßige Eigenschaftenüberprüfungen für Objektliterale unterdrücken.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "noImplicitAny-Fehler für die Indizierung von Objekten unterdrücken, denen Indexsignaturen fehlen.", + "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703": "Unterdrücken Sie „noImplicitAny“-Fehler beim Indizieren von Objekten ohne Indexsignaturen.", + "Switch_each_misused_0_to_1_95138": "Jedes falsch verwendete {0}-Element in \"{1}\" ändern", + "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704": "Rufen Sie Rückrufe synchron auf, und aktualisieren Sie den Status von Verzeichnisüberwachungen auf Plattformen, die rekursive Überwachung nicht nativ unterstützen.", + "Syntax_Colon_0_6023": "Syntax: {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "Das Tag \"{0}\" erwartet mindestens {1} Argumente, von der JSX-Factory \"{2}\" werden aber höchstens {3} bereitgestellt.", + "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "Mit Tags versehene Vorlagenausdrücke sind in einer optionalen Kette nicht zulässig.", + "Target_allows_only_0_element_s_but_source_may_have_more_2621": "Das Ziel erlaubt nur {0} Element(e), aber die Quelle kann mehr aufweisen.", + "Target_requires_0_element_s_but_source_may_have_fewer_2620": "Das Ziel erfordert {0} Element(e), aber die Quelle kann weniger aufweisen.", + "Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1_2849": "Die Zielsignatur stellt zu wenige Argumente bereit. Erwartete {0} oder mehr, erhielt aber {1}.", + "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "Der Modifizierer \"{0}\" kann nur in TypeScript-Dateien verwendet werden.", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Der Operator \"{0}\" darf nicht den Typ \"symbol\" angewendet werden.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "Der Operator \"{0}\" ist für boolesche Typen unzulässig. Verwenden Sie stattdessen ggf. \"{1}\".", + "The_0_property_of_an_async_iterator_must_be_a_method_2768": "Die Eigenschaft \"{0}\" eines asynchronen Iterators muss eine Methode sein.", + "The_0_property_of_an_iterator_must_be_a_method_2767": "Die Eigenschaft \"{0}\" eines Iterators muss eine Methode sein.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Der Typ \"Object\" kann nur wenigen anderen Typen zugewiesen werden. Wollten Sie stattdessen den Typ \"any\" verwenden?", + "The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously_1502": "Das Unicode-Flag (u) und das Unicode Sets-Flag (v) können nicht gleichzeitig festgelegt werden.", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_func_2496": "Auf das Objekt „arguments“ darf in einer Pfeilfunktion in ES5 nicht verwiesen werden. Verwenden Sie ggf. einen Standardfunktionsausdruck.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_sta_2522": "Auf das Objekt „arguments“ darf in einer asynchronen Funktion oder Methode in ES5 nicht verwiesen werden. Verwenden Sie ggf. eine Standardfunktion oder -methode.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Der Text einer \"if\"-Anweisung kann keine leere Anweisung sein.", + "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793": "Der Aufruf wäre für diese Implementierung erfolgreich, aber die Implementierungssignaturen von Überladungen sind nicht extern sichtbar.", + "The_character_set_of_the_input_files_6163": "Der Zeichensatz der Eingabedateien.", + "The_containing_arrow_function_captures_the_global_value_of_this_7041": "Die enthaltende Pfeilfunktion erfasst den globalen Wert von \"this\".", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Der beinhaltende Funktions- oder Modulkörper ist zu groß für eine Ablaufsteuerungsanalyse.", + "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309": "Die aktuelle Datei ist ein CommonJS-Modul und kann „await“ nicht auf der obersten Ebene verwenden.", + "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479": "Die aktuelle Datei ist ein CommonJS-Modul, dessen Importe \"require\"-Aufrufe generieren. Die Datei, auf die verwiesen wird, ist jedoch ein ECMAScript-Modul und kann nicht mit \"require\" importiert werden. Erwägen Sie stattdessen, einen dynamischen 'import(\"{0}\")'-Aufruf zu schreiben.", + "The_current_host_does_not_support_the_0_option_5001": "Der aktuelle Host unterstützt die Option \"{0}\" nicht.", + "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018": "Die Deklaration von \"{0}\", die Sie wahrscheinlich verwenden wollten, ist hier definiert.", + "The_declaration_was_marked_as_deprecated_here_2798": "Die Deklaration wurde hier als veraltet markiert.", + "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500": "Der erwartete Typ stammt aus der Eigenschaft \"{0}\", die hier für den Typ \"{1}\" deklariert wird.", + "The_expected_type_comes_from_the_return_type_of_this_signature_6502": "Der erwartete Typ stammt aus dem Rückgabetyp dieser Signatur.", + "The_expected_type_comes_from_this_index_signature_6501": "Der erwartete Typ stammt aus dieser Indexsignatur.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Der Ausdruck einer Exportzuweisung muss ein Bezeichner oder ein qualifizierter Name in einem Umgebungskontext sein.", + "The_file_is_in_the_program_because_Colon_1430": "Die Datei befindet sich aus folgenden Gründen im Programm:", + "The_files_list_in_config_file_0_is_empty_18002": "Die Liste \"files\" in der Konfigurationsdatei \"{0}\" ist leer.", + "The_first_export_default_is_here_2752": "Der erste Exportstandard befindet sich hier.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Der erste Parameter der \"then\"-Methode einer Zusage muss ein Rückruf sein.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Der globale Typ \"JSX.{0}\" darf nur eine Eigenschaft aufweisen.", + "The_implementation_signature_is_declared_here_2750": "Die Implementierungssignatur wird hier deklariert.", + "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "Die Meta-Eigenschaft „import.meta“ ist in Dateien, die in der CommonJS-Ausgabe erstellt werden, nicht zulässig.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "Die Meta-Eigenschaft „import.meta“ ist nur zulässig, wenn die Option „--module“ „es2020“, „es2022“, „esnext“, „system“, „node16“, „node18“ oder „nodenext“ ist.", + "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Der abgeleitete Typ von \"{0}\" kann nicht ohne einen Verweis auf \"{1}\" benannt werden. Eine Portierung ist wahrscheinlich nicht möglich. Eine Typanmerkung ist erforderlich.", + "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Der abgeleitete Typ von \"{0}\" verweist auf einen Typ mit zyklischer Struktur, die nicht trivial serialisiert werden kann. Es ist eine Typanmerkung erforderlich.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Der abgeleitete Typ von \"{0}\" verweist auf einen Typ \"{1}\", auf den nicht zugegriffen werden kann. Eine Typanmerkung ist erforderlich.", + "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056": "Der abgeleitete Typ dieses Knotens überschreitet die maximale Länge, die vom Compiler serialisiert wird. Eine explizite Typanmerkung ist erforderlich.", + "The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_n_2850": "Der Initialisierer einer „using“-Deklaration muss entweder ein Objekt mit der Methode „[Symbol.dispose]()“ sein oder „null“ oder „undefined“ sein.", + "The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_2851": "Der Initialisierer einer „await using“-Deklaration muss entweder ein Objekt mit der Methode „[Symbol.asyncDispose]()“ oder „[Symbol.dispose]5D;()“ sein oder „null“ oder „undefined“ sein.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "Die Schnittmenge \"{0}\" wurde auf \"niemals\" reduziert, weil die Eigenschaft \"{1}\" in mehreren Bestandteilen vorhanden und in einigen davon privat ist.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "Die Schnittmenge \"{0}\" wurde auf \"niemals\" reduziert, weil die Eigenschaft \"{1}\" in einigen Bestandteilen widersprüchliche Typen aufweist.", + "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795": "Das Schlüsselwort \"intrinsic\" darf nur zum Deklarieren von vom Compiler bereitgestellten intrinsischen Typen verwendet werden.", + "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016": "Um JSX-Fragmente mit der Compileroption \"jsxFactory\" zu verwenden, muss die Compileroption \"jsxFragmentFactory\" angegeben werden.", + "The_last_overload_gave_the_following_error_2770": "Die letzte Überladung hat den folgenden Fehler verursacht.", + "The_last_overload_is_declared_here_2771": "Die letzte Überladung wird hier deklariert.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Die linke Seite einer for...in-Anweisung darf kein Destrukturierungsmuster sein.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493": "Die linke Seite einer „for... in“-Anweisung darf keine „using“-Deklaration sein.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494": "Die linke Seite eines „for...in“-Anweisung darf keine „await using“-Deklaration sein.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Die linke Seite einer for...in-Anweisung darf keine Typanmerkung verwenden.", + "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780": "Die linke Seite einer for...in-Anweisung darf kein optionaler Eigenschaftenzugriff sein.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "Die linke Seite einer for...in-Anweisung muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "Die linke Seite einer for...in-Anweisung muss vom Typ \"string\" oder \"any\" sein.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Die linke Seite einer for...of-Anweisung darf keine Typanmerkung verwenden.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781": "Die linke Seite einer for...of-Anweisung darf kein optionaler Eigenschaftenzugriff sein.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106": "Die linke Seite einer „for...of“-Anweisung darf nicht „asynchron“ lauten.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "Die linke Seite einer for...of-Anweisung muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "Die linke Seite einer arithmetischen Operation muss den Typ \"any\", \"number\" oder \"bigint\" aufweisen oder ein Enumerationstyp sein.", + "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "Die linke Seite eines Zuweisungsausdrucks darf kein optionaler Eigenschaftenzugriff sein.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Die linke Seite eines Zuweisungsausdrucks muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_2860": "Die linke Seite eines „instanceof“-Ausdrucks muss dem ersten Argument der „[Symbol.hasInstance]“-Methode der rechten Seite zugewiesen werden können.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Die linke Seite eines instanceof-Ausdrucks muss den Typ \"any\" aufweisen oder ein Objekttyp bzw. ein Typparameter sein.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Das beim Anzeigen von Meldungen für den Benutzer verwendete Gebietsschema (z. B. \"de-de\").", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Die maximale Abhängigkeitstiefe, die unter \"node_modules\" durchsucht und für die JavaScript-Dateien geladen werden sollen.", + "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "Der Operand eines delete-Operators darf kein privater Bezeichner sein.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Der Operand eines delete-Operators darf keine schreibgeschützte Eigenschaft sein.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Der Operand eines delete-Operators muss ein Eigenschaftenverweis sein.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "Der Operand eines delete-Operators muss optional sein.", + "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "Der Operand eines Inkrement- oder Dekrementoperators darf kein optionaler Eigenschaftenzugriff sein.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Der Operand eines Inkrement- oder Dekrementoperators muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_parser_expected_to_find_a_1_to_match_the_0_token_here_1007": "Der Parser hat ein ein entsprechendes Element \"{1}\" zu dem hier vorhandenen Token \"{0}\" erwartet.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209": "Der Projektstamm ist mehrdeutig, wird aber benötigt, um den Exportzuordnungseintrag „{0}“ in der Datei „{1}“ aufzulösen. Geben Sie die Compiler-Option „rootDir“ an, um die Mehrdeutigkeit aufzuheben.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210": "Der Projektstamm ist mehrdeutig, wird aber benötigt, um den Importzuordnungseintrag „{0}“ in der Datei „{1}“ aufzulösen. Geben Sie die Compiler-Option „rootDir“ an, um die Mehrdeutigkeit aufzuheben.", + "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014": "Auf die Eigenschaft \"{0}\" kann für den Typ \"{1}\" nicht innerhalb dieser Klasse zugegriffen werden, weil sie von einem anderen privaten Bezeichner mit der gleichen Schreibweise verborgen wird.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Der Rückgabetyp einer Parameter-Decorator-Funktion muss \"void\" oder \"any\" sein.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Der Rückgabetyp einer Eigenschaften-Decorator-Funktion muss \"void\" oder \"any\" sein.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Der Rückgabetyp einer asynchronen Funktion muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065": "Der Rückgabetyp einer asynchronen Funktion oder Methode muss der globale Typ \"Promise\" sein.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "Der Rückgabetyp einer asynchronen Funktion oder Methode muss der globale Typ \"Promise\" sein. Wollten Sie eigentlich \"Promise<{0}>\" verwenden?", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "Die rechte Seite einer for...in-Anweisung muss den Typ \"any\" aufweisen oder ein Objekttyp bzw. ein Typparameter sein. Sie weist hier jedoch den Typ \"{0}\" auf.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "Die rechte Seite einer arithmetischen Operation muss den Typ \"any\", \"number\" oder \"bigint\" aufweisen oder ein Enumerationstyp sein.", + "The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_2359": "Die rechte Seite eines „instanceof“-Ausdrucks muss entweder vom Typ „any“, eine Klasse, eine Funktion oder ein anderer Typ, der dem Schnittstellentyp „Function“ zugewiesen werden kann, oder ein Objekttyp mit einer Symbol.hasInstance-Methode sein.", + "The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression_2848": "Die rechte Seite eines „instanceof“-Ausdrucks darf kein Instanziierungsausdruck sein.", + "The_root_value_of_a_0_file_must_be_an_object_5092": "Der Stammwert einer {0}-Datei muss ein Objekt sein.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0_1278": "Die Runtime ruft das Decorator-Element mit {1} Argumenten auf, aber das Decorator-Element erwartet {0}.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0_1279": "Die Runtime ruft das Decorator-Element mit {1}-Argumenten auf, aber das Decorator-Element erwartet mindestens {0}.", + "The_shadowing_declaration_of_0_is_defined_here_18017": "Die verbergende Deklaration von \"{0}\" ist hier definiert.", + "The_signature_0_of_1_is_deprecated_6387": "Die Signatur \"{0}\" von \"{1}\" ist veraltet.", + "The_specified_path_does_not_exist_Colon_0_5058": "Der angegebene Pfad \"{0}\" ist nicht vorhanden.", + "The_tag_was_first_specified_here_8034": "Das Tag wurde zuerst hier angegeben.", + "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "Das Ziel einer rest-Zuweisung für ein Objekt darf kein optionaler Eigenschaftenzugriff sein.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "Das Ziel einer REST-Zuweisung für ein Objekt muss eine Variable oder ein Eigenschaftenzugriff sein.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Der \"this\"-Kontext vom Typ \"{0}\" kann \"this\" vom Typ \"{1}\" der Methode nicht zugewiesen werden.", + "The_this_types_of_each_signature_are_incompatible_2685": "Die \"this\"-Typen jeder Signatur sind nicht kompatibel.", + "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104": "Der Typ \"{0}\" ist als \"readonly\" festgelegt und kann nicht dem änderbaren Typ \"{1}\" zugewiesen werden.", + "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Der \"Type\"-Modifizierer kann nicht für einen benannten Export verwendet werden, wenn \"Export-Typ\" auf seiner Export-Anweisung verwendet wird.", + "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Der \"Type\"-Modifizierer kann nicht für einen benannten Import verwendet werden, wenn der \"Import-Typ\" auf seiner Import-Anweisung verwendet wird.", + "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Der Typ einer Funktionsdeklaration muss mit der Signatur der Funktion übereinstimmen.", + "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Der Typ dieses Knotens kann nicht serialisiert werden, da seine Eigenschaft \"{0}\" nicht serialisiert werden kann.", + "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Der von der {0}()-Methode eines Async-Iterators zurückgegebene Typ muss eine Zusage für einen Typ mit einer value-Eigenschaft sein.", + "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Der von der {0}()-Methode eines Iterators zurückgegebene Typ muss eine value-Eigenschaft aufweisen.", + "The_types_of_0_are_incompatible_between_these_types_2200": "Die Typen von \"{0}\" sind zwischen diesen Typen nicht kompatibel.", + "The_types_returned_by_0_are_incompatible_between_these_types_2201": "Die von \"{0}\" zurückgegebenen Typen sind zwischen diesen Typen nicht kompatibel.", + "The_value_0_cannot_be_used_here_18050": "Der Wert \"{0}\" kann hier nicht verwendet werden.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "Die Variablendeklaration einer for...in-Anweisung darf keinen Initialisierer aufweisen.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "Die Variablendeklaration einer for...of-Anweisung darf keinen Initialisierer aufweisen.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Die with-Anweisung wird nicht unterstützt. Alle Symbole in einem with-Block weisen den Typ \"any\" auf.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setti_6280": "Es gibt Typen unter „{0}“, aber dieses Ergebnis konnte unter Ihrer aktuellen „moduleResolution“-Einstellung nicht aufgelöst werden. Erwägen Sie ein Update auf „node16“, „nodenext“ oder „bundler“.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278": "Es gibt Typen unter „{0}“, aber dieses Ergebnis konnte nicht aufgelöst werden, wenn package.json „Exporte“ beachtet wird. Die Bibliothek „{1}“ muss möglicherweise ihre package.json oder Eingaben aktualisieren.", + "There_is_no_capturing_group_named_0_in_this_regular_expression_1532": "In diesem regulären Ausdruck ist keine Erfassungsgruppe namens „{0}“ vorhanden.", + "There_is_nothing_available_for_repetition_1507": "Es ist nichts für Wiederholungen verfügbar.", + "This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found_2874": "Dieses JSX-Tag erfordert, dass '{0}' im Geltungsbereich ist, konnte jedoch nicht gefunden werden.", + "This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_fo_2875": "Für dieses JSX-Tag muss der Modulpfad '{0}' vorhanden sein, aber es wurde keiner gefunden. Stellen Sie sicher, dass die Typen für das entsprechende Paket installiert sind.", + "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "Die Eigenschaft \"{0}\" für dieses JSX-Tag erwartet ein einzelnes untergeordnetes Element vom Typ \"{1}\", aber es wurden mehrere untergeordnete Elemente angegeben.", + "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "Die Eigenschaft \"{0}\" für dieses JSX-Tag erwartet den Typ \"{1}\", der mehrere untergeordnete Elemente erfordert, aber es wurde nur ein untergeordnetes Elemente angegeben.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534": "Dieser Rückverweis bezieht sich auf eine Gruppe, die nicht vorhanden ist. Dieser reguläre Ausdruck enthält keine Erfassungsgruppen.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533": "Dieser Rückverweis bezieht sich auf eine Gruppe, die nicht vorhanden ist. In diesem regulären Ausdruck sind nur {0} Erfassungsgruppen vorhanden.", + "This_binary_expression_is_never_nullish_Are_you_missing_parentheses_2870": "Dieser binäre Ausdruck ist nie „NULLISH“. Fehlen Klammern?", + "This_character_cannot_be_escaped_in_a_regular_expression_1535": "Dieses Zeichen kann in einem regulären Ausdruck nicht mit Escapezeichen versehen werden.", + "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Dieser Vergleich scheint unbeabsichtigt zu sein, da die Typen \"{0}\" und \"{1}\" keine Überlappung aufweisen.", + "This_condition_will_always_return_0_2845": "Diese Bedingung gibt immer „{0}“ zurück.", + "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Diese Bedingung gibt immer „{0}“ zurück, da JavaScript Objekte nach Verweis und nicht nach Wert vergleicht.", + "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Diese Bedingung gibt immer TRUE zurück, weil diese '{0}' immer definiert ist.", + "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Diese Bedingung gibt immer TRUE zurück, weil diese Funktion immer definiert ist. Möchten Sie sie stattdessen aufrufen?", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Diese Konstruktorfunktion kann in eine Klassendeklaration konvertiert werden.", + "This_expression_is_always_nullish_2871": "Dieser Ausdruck ist immer „NULLISH“.", + "This_expression_is_not_callable_2349": "Dieser Ausdruck kann nicht aufgerufen werden.", + "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Dieser Ausdruck kann nicht aufgerufen werden, weil es sich um eine get-Zugriffsmethode handelt. Möchten Sie den Wert ohne \"()\" verwenden?", + "This_expression_is_not_constructable_2351": "Dieser Ausdruck kann nicht erstellt werden.", + "This_file_already_has_a_default_export_95130": "Diese Datei weist bereits einen Standardexport auf.", + "This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_b_2878": "Dieser Importpfad ist unsicher umzuschreiben, da er auf ein anderes Projekt verweist und der relative Pfad zwischen den Ausgabedateien der Projekte nicht derselbe ist wie der relative Pfad zwischen den Eingabedateien.", + "This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_duri_2877": "Dieser Import verwendet eine '{0}' Erweiterung, um auf eine TypeScript-Eingabedatei zu verweisen, wird jedoch beim Ausgeben nicht umgeschrieben, da es sich nicht um einen relativen Pfad handelt.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Dies ist die erweiterte Deklaration. Die erweiternde Deklaration sollte in dieselbe Datei verschoben werden.", + "This_kind_of_expression_is_always_falsy_2873": "Diese Art von Ausdruck ist immer „FALSY“.", + "This_kind_of_expression_is_always_truthy_2872": "Diese Art von Ausdruck ist immer „TRUTHY“.", + "This_may_be_converted_to_an_async_function_80006": "Es kann eine Konvertierung in ein asynchrone Funktion durchgeführt werden.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122": "Dieser Member kann keinen JSDoc-Kommentar mit einem \"@override\"-Tag haben, da er nicht in der Basisklasse \"{0}\" deklariert ist.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123": "Dieses Mitglied kann keinen JSDoc-Kommentar mit einem Override-Tag haben, da er nicht in der Basisklasse \"{0}\" deklariert ist. Meinten Sie \"{1}\"?", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121": "Dieses Mitglied kann keinen JSDoc-Kommentar mit einem Tag \"@override\" haben, da dessen enthaltende Klasse \"{0}\" keine andere Klasse erweitert.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic_4128": "Dieses Mitglied kann keinen JSDoc-Kommentar mit einem „@override“-Tag haben, da der Name dynamisch ist.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113": "Dieser Member kann keinen override-Modifizierer aufweisen, weil er nicht in der Basisklasse \"{0}\" deklariert ist.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117": "Dieser Member kann keinen override-Modifizierer aufweisen, weil er nicht in der Basisklasse \"{0}\" deklariert ist. Meinten Sie \"{1}\"?", + "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112": "Dieser Member kann keinen override-Modifizierer aufweisen, weil die Klasse \"{0}\", die diesen Member enthält, keine andere Klasse erweitert.", + "This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic_4127": "Dieser Member kann keinen override-Modifizierer aufweisen, da sein Name dynamisch ist.", + "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119": "Dieses Mitglied muss über einen JSDoc-Kommentar mit dem Tag \"@override\" verfügen, da er einen Member in der Basisklasse \"{0}\" überschreibt.", + "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114": "Dieser Member muss einen override-Modifizierer aufweisen, weil er einen Member in der Basisklasse \"{0}\" überschreibt.", + "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116": "Dieser Member muss einen override-Modifizierer aufweisen, weil er eine abstrakte Methode überschreibt, die in der Basisklasse \"{0}\" deklariert ist.", + "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Auf dieses Modul kann nur mit ECMAScript-Importen/-Exporten verwiesen werden, indem das Flag \"{0}\" aktiviert und auf den Standardexport verwiesen wird.", + "This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag_2594": "Dieses Modul wird mit „export =“ deklariert und kann nur bei Verwendung des Kennzeichnens „{0}“ mit einem Standardimport verwendet werden.", + "This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2_6807": "Dieser Vorgang kann vereinfacht werden. Diese Schicht ist identisch mit „{0} {1} {2}“.", + "This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation_7012": "Diese Überladung gibt implizit den Typ „{0}“ zurück, da keine Rückgabetypanmerkung vorhanden ist.", + "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394": "Diese Überladungssignatur ist nicht mit der zugehörigen Implementierungssignatur kompatibel.", + "This_parameter_is_not_allowed_with_use_strict_directive_1346": "Dieser Parameter ist mit der Direktive \"use strict\" nicht zugelassen.", + "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120": "Diese Parametereigenschaft muss über einen JSDoc-Kommentar mit einem \"@override\"-Tag verfügen, da sie ein Mitglied in der Basisklasse \"{0}\" überschreibt.", + "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115": "Diese Parametereigenschaft muss einen „override“-Modifizierer aufweisen, weil er einen Member in der Basisklasse \"{0}\" überschreibt.", + "This_regular_expression_flag_cannot_be_toggled_within_a_subpattern_1509": "Dieses Flag für reguläre Ausdrücke kann nicht innerhalb eines Untermusters umgeschaltet werden.", + "This_regular_expression_flag_is_only_available_when_targeting_0_or_later_1501": "Dieses Flag für reguläre Ausdrücke ist nur verfügbar, wenn es auf „{0}“ oder höher ausgerichtet ist.", + "This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolv_2876": "Dieser relative Importpfad ist unsicher umzuschreiben, da er wie ein Dateiname aussieht, aber tatsächlich auf \"{0}\" verweist.", + "This_spread_always_overwrites_this_property_2785": "Diese Eigenschaft wird immer durch diesen Spread-Operator überschrieben.", + "This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled_1294": "Diese Syntax ist nicht zulässig, wenn \"erasableSyntaxOnly\" aktiviert ist.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060": "Diese Syntax ist in Dateien mit der Erweiterung .mts oder .cts reserviert. Fügen Sie ein nachfolgendes Komma oder eine explizite Einschränkung hinzu.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059": "Diese Syntax ist in Dateien mit der Erweiterung \".mts\" oder \".cts\" reserviert. Verwenden Sie stattdessen einen „as“-Ausdruck.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Diese Syntax erfordert ein importiertes Hilfsprogramm, aber das Modul \"{0}\" wurde nicht gefunden.", + "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Diese Syntax erfordert ein importiertes Hilfsprogramm namens \"{1}\", das in \"{0}\" nicht vorhanden ist. Erwägen Sie ein Upgrade Ihrer Version von \"{0}\".", + "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Diese Syntax erfordert ein importiertes Hilfsprogramm mit dem Namen \"{1}\" mit {2} Parametern, die nicht mit der in \"{0}\" kompatibel ist. Erwägen Sie ein Upgrade Ihrer Version von \"{0}\".", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Für diesen Typparameter ist möglicherweise die Einschränkung \"extends {0}\" erforderlich.", + "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Diese Verwendung von „import“ ist ungültig. „import()“-Aufrufe können geschrieben werden, müssen jedoch Klammern aufweisen und dürfen keine Typargumente aufweisen.", + "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482": "Um diese Datei in ein ECMAScript-Modul zu konvertieren, fügen Sie das Feld \"type\": \"module\" zu \"{0}\" hinzu.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481": "Um diese Datei in ein ECMAScript-Modul zu konvertieren, ändern Sie die Dateierweiterung in \"{0}\", oder fügen Sie das Feld ''type': 'module'' zu \"{1}\" hinzu.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480": "Um diese Datei in ein ECMAScript-Modul zu konvertieren, ändern Sie ihre Dateierweiterung in '{0}', oder erstellen Sie eine lokale package.json-Datei mit `{ \"type\": \"module\" }`.", + "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483": "Um diese Datei in ein ECMAScript-Modul zu konvertieren, erstellen Sie eine lokale package.json-Datei mit `{ \"type\": \"module\" }`.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "„await“-Ausdrücke der obersten Ebene sind nur erlaubt, wenn die „module“-Option auf „es2022“, „esnext“, „system“, „node16“, „node18“, „nodenext“ oder „preserve“ gesetzt ist und die „target“-Option auf „es2017“ gesetzt ist oder höher.", + "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854": "„await using“-Deklarationen der obersten Ebene sind nur erlaubt, wenn die „module“-Option auf „es2022“, „esnext“, „system“, „node16“, „node18“, „nodenext“ oder „preserve“ und die „target“-Option auf „es2017“ oder höher gesetzt ist.", + "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Deklarationen der obersten Ebene in .d.ts-Dateien müssen entweder mit einem declare- oder einem export-Modifizierer beginnen.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_nod_1432": "„for await“-Schleifen der obersten Ebene sind nur erlaubt, wenn die „module“-Option auf „es2022“, „esnext“, „system“, „node16“, „node18“, „nodenext“ oder „preserve“ gesetzt ist und die „target“-Option auf „es2017“ gesetzt ist oder höher.", + "Trailing_comma_not_allowed_1009": "Ein nachgestelltes Komma ist unzulässig.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Jede Datei als separates Modul transpilieren (ähnlich wie bei \"ts.transpileModule\").", + "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Versuchen Sie es mit \"npm i --save-dev @types/{1}\", sofern vorhanden, oder fügen Sie eine neue Deklarationsdatei (.d.ts) hinzu, die \"declare module '{0}';\" enthält.", + "Trying_other_entries_in_rootDirs_6110": "Andere Einträge in \"rootDirs\" werden versucht.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Die Ersetzung \"{0}\" wird versucht. Speicherort des Kandidatenmoduls: \"{1}\".", + "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493": "Der Tupeltyp \"{0}\" der Länge {1} weist am Index \"{2}\" kein Element auf.", + "Tuple_type_arguments_circularly_reference_themselves_4110": "Tupeltypargumente verweisen zirkulär auf sich selbst.", + "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802": "Der Typ \"{0}\" kann nur durchlaufen werden, wenn das Flag \"--downlevelIteration\" verwendet wird oder \"--target\" den Wert \"es2015\" oder höher aufweist.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Der Typ \"{0}\" kann nicht als Indextyp verwendet werden.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Der Typ \"{0}\" kann nicht zum Indizieren von Typ \"{1}\" verwendet werden.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Der Typ \"{0}\" erfüllt die Einschränkung \"{1}\" nicht.", + "Type_0_does_not_satisfy_the_expected_type_1_1360": "Der Typ \"{0}\" erfüllt den erwarteten Typ \"{1}\" nicht.", + "Type_0_has_no_call_signatures_2757": "Der Typ \"{0}\" weist keine Aufrufsignaturen auf.", + "Type_0_has_no_construct_signatures_2761": "Der Typ \"{0}\" weist keine Konstruktsignaturen auf.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Der Typ \"{0}\" weist keine übereinstimmende Indexsignatur für den Typ \"{1}\" auf.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Der Typ \"{0}\" verfügt über keine gemeinsamen Eigenschaften mit Typ \"{1}\".", + "Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable_2635": "Der Typ „{0}“ weist keine Signaturen auf, für die die Liste „Typargument“ gilt.", + "Type_0_is_generic_and_can_only_be_indexed_for_reading_2862": "Der Typ „{0}“ ist generisch und kann nur zum Lesen indiziert werden.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "Im Typ \"{0}\" fehlen die folgenden Eigenschaften von Typ \"{1}\": \"{2}\".", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "Im Typ \"{0}\" fehlen die folgenden Eigenschaften von Typ \"{1}\": \"{2}\" und {3} weitere.", + "Type_0_is_not_a_constructor_function_type_2507": "Der Typ \"{0}\" ist kein Konstruktorfunktionstyp.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compa_1055": "Der Typ „{0}“ ist in ES5 kein gültiger Rückgabetyp einer asynchronen Funktion, weil er nicht auf einen Promise-kompatiblen Konstruktorwert verweist.", + "Type_0_is_not_an_array_type_2461": "Der Typ \"{0}\" ist kein Arraytyp.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Der Typ \"{0}\" ist kein Array- oder Zeichenfolgentyp.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ \"{0}\" ist kein Array-Typ oder Zeichenfolgentyp oder weist keine \"[Symbol.iterator]()\"-Methode auf, die einen Iterator zurückgibt.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ \"{0}\" ist kein Array-Typ oder weist keine \"[Symbol.iterator]()\"-Methode auf, die einen Iterator zurückgibt.", + "Type_0_is_not_assignable_to_type_1_2322": "Der Typ \"{0}\" kann dem Typ \"{1}\" nicht zugewiesen werden.", + "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820": "Typ \"{0}\" kann dem Typ \"{1}\" nicht zugewiesen werden. Meinten Sie \"{2}\"?", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Der Typ \"{0}\" kann dem Typ \"{1}\" nicht zugewiesen werden. Es sind zwei verschiedene Typen mit diesem Namen vorhanden, diese sind jedoch nicht verwandt.", + "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636": "Der Typ „{0}“ kann dem Typ „{1}“ nicht zugewiesen werden, wie in der Abweichungsanmerkung impliziert.", + "Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values_18033": "Der Typ „{0}“ kann nicht dem Typ „{1}“ zugewiesen werden, wie für berechnete Enumerationselementwerte erforderlich.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375": "Der Typ „{0}“ kann dem Typ „{1}“ mit „exactOptionalPropertyTypes: true“ nicht zugewiesen werden. Erwägen Sie das Hinzufügen von „undefined“ zu den Typen der Zieleigenschaften.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "Der Typ „{0}“ kann dem Typ „{1}“ mit „exactOptionalPropertyTypes: true“ nicht zugewiesen werden. Erwägen Sie das Hinzufügen von „undefined“ zum Typ des Ziels.", + "Type_0_is_not_comparable_to_type_1_2678": "Der Typ \"{0}\" kann nicht mit dem Typ \"{1}\" verglichen werden.", + "Type_0_is_not_generic_2315": "Der Typ \"{0}\" ist nicht generisch.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "Typ „{0}“ kann einen primitiven Wert darstellen, der als rechter Operand des „In“-Operators nicht zulässig ist.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Der Typ \"{0}\" muss eine Methode \"[Symbol.asyncIterator]()\" aufweisen, die einen async-Iterator zurückgibt.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Der Typ \"{0}\" muss eine Methode \"[Symbol.iterator]()\" aufweisen, die einen Iterator zurückgibt.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Der Typ \"{0}\" enthält keine Entsprechung für die Signatur \"{1}\".", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Der Typ \"{0}\" verweist rekursiv auf sich selbst als ein Basistyp.", + "Type_Checking_6248": "Typprüfung", + "Type_alias_0_circularly_references_itself_2456": "Der Typalias \"{0}\" verweist zirkulär auf sich selbst.", + "Type_alias_must_be_given_a_name_1439": "Typalias muss einen Namen erhalten.", + "Type_alias_name_cannot_be_0_2457": "Der Typaliasname darf nicht \"{0}\" sein.", + "Type_aliases_can_only_be_used_in_TypeScript_files_8008": "Typaliase können nur in TypeScript-Dateien verwendet werden.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Die Typanmerkung darf nicht für eine Konstruktordeklaration verwendet werden.", + "Type_annotations_can_only_be_used_in_TypeScript_files_8010": "Typanmerkungen können nur in TypeScript-Dateien verwendet werden.", + "Type_argument_expected_1140": "Ein Typargument wurde erwartet.", + "Type_argument_list_cannot_be_empty_1099": "Die Typargumentliste darf nicht leer sein.", + "Type_arguments_can_only_be_used_in_TypeScript_files_8011": "Typargumente können nur in TypeScript-Dateien verwendet werden.", + "Type_arguments_for_0_circularly_reference_themselves_4109": "Typargumente für \"{0}\" verweisen zirkulär auf sich selbst.", + "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016": "Typassertionsausdrücke können nur in TypeScript-Dateien verwendet werden.", + "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626": "Der Typ an Position {0} in der Quelle ist nicht mit dem Typ an Position {1} im Ziel kompatibel.", + "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627": "Der Typ an den Positionen {0} bis {1} in der Quelle ist nicht mit dem Typ an Position {2} im Ziel kompatibel.", + "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039": "Der Typ, der den privaten Namen „{0}“ enthält, kann nicht mit „--isolatedDeclarations“ verwendet werden.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Typdeklarationsdateien, die in die Kompilierung eingeschlossen werden sollen.", + "Type_expected_1110": "Es wurde ein Typ erwartet.", + "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456": "Typimportassertionen sollten über genau einen Schlüssel verfügen – „resolution-mode“ – mit dem Wert „import“ oder „require“.", + "Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1464": "Typimportattribute sollten über genau einen Schlüssel verfügen – „resolution-mode“ – mit dem Wert „import“ oder „require“.", + "Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute_1542": "Der Typimport eines ECMAScript-Moduls aus einem CommonJS-Modul muss ein Attribut für den Auflösungsmodus (resolution-mode) aufweisen.", + "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589": "Die Typinstanziierung ist übermäßig tief und möglicherweise unendlich.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Auf den Typ wird direkt oder indirekt im Erfüllungsrückruf der eigenen \"then\"-Methode verwiesen.", + "Type_library_referenced_via_0_from_file_1_1402": "Typbibliothek, die über \"{0}\" aus der Datei \"{1}\" referenziert wird", + "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Typbibliothek, die über \"{0}\" aus der Datei \"{1}\" mit packageId \"{2}\" referenziert wird", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Der Typ des \"await\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Der Typ des Werts der berechneten Eigenschaft lautet \"{0}\" und kann dem Typ \"{1}\" nicht zugewiesen werden.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Der Typ der Instanzmembervariablen „{0}“ darf nicht auf den im Konstruktor deklarierten Bezeichner „{1}“ verweisen.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Der Typ iterierter Elemente eines \"yield*\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Der Typ der Eigenschaft \"{0}\" verweist im zugeordneten Typ \"{1}\" auf sich selbst.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Der Typ eines \"yield\"-Operanden in einem asynchronen Generator muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", + "Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribut_1541": "Der reine Typimport eines ECMAScript-Moduls aus einem CommonJS-Modul muss ein Attribut für den Auflösungsmodus (resolution-mode) aufweisen.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Der Typ stammt aus diesem Import. Ein Import im Namespacestil kann nicht aufgerufen oder erstellt werden und verursacht zur Laufzeit einen Fehler. Erwägen Sie hier stattdessen die Verwendung eines Standardimports oder die den Import über \"require\".", + "Type_parameter_0_has_a_circular_constraint_2313": "Der Typparameter \"{0}\" weist eine zirkuläre Einschränkung auf.", + "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" besitzt einen zirkulären Standardwert.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Der Typparameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Der Typparameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Der Typparameter \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Der Typparameter \"{0}\" der exportierten Funktion besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Der Typparameter \"{0}\" der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103": "Der Typparameter \"{0}\" des exportierten zugeordneten Objekttyps verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Der Typparameter \"{0}\" des exportierten Typalias enthält oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Der Typparameter \"{0}\" der Methode aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Der Typparameter \"{0}\" der öffentlichen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Der Typparameter \"{0}\" der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", + "Type_parameter_declaration_expected_1139": "Eine Typparameterdeklaration wurde erwartet.", + "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004": "Typparameterdeklarationen können nur in TypeScript-Dateien verwendet werden.", + "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744": "Standardwerte für Typparameter können nur auf zuvor deklarierte Typparameter verweisen.", + "Type_parameter_list_cannot_be_empty_1098": "Die Typparameterliste darf nicht leer sein.", + "Type_parameter_name_cannot_be_0_2368": "Der Name des Typparameters darf nicht \"{0}\" sein.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Typparameter dürfen nicht für eine Konstruktordeklaration verwendet werden.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Das Typprädikat \"{0}\" kann \"{1}\" nicht zugewiesen werden.", + "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799": "Der Typ erzeugt einen Tupeltyp, der für die Darstellung zu groß ist.", + "Type_reference_directive_0_was_not_resolved_6120": "======== Die Typverweisdirektive \"{0}\" wurde nicht aufgelöst. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Die Typverweisdirektive \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. Primär: {2}. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== Die Typverweisdirektive \"{0}\" wurde erfolgreich in \"{1}\" mit Paket-ID \"{2}\" aufgelöst. Primär: {3}. ========", + "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037": "Typerfüllungsausdrücke können nur in TypeScript-Dateien verwendet werden.", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Typen können in Exportdeklarationen in JavaScript-Dateien nicht angezeigt werden.", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Typen weisen separate Deklarationen einer privaten Eigenschaft \"{0}\" auf.", + "Types_of_construct_signatures_are_incompatible_2419": "Die Typen der Konstruktsignaturen sind nicht kompatibel.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Die Typen der Parameter \"{0}\" und \"{1}\" sind nicht kompatibel.", + "Types_of_property_0_are_incompatible_2326": "Die Typen der Eigenschaft \"{0}\" sind nicht kompatibel.", + "Unable_to_open_file_0_6050": "Die Datei \"{0}\" kann nicht geöffnet werden.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Die Signatur des Klassen-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Die Signatur des Methoden-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Die Signatur des Parameter-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Die Signatur des Eigenschaften-Decorator-Elements kann nicht aufgelöst werden, wenn der Aufruf als Ausdruck erfolgt.", + "Undetermined_character_escape_1513": "Nicht definiertes ESC-zeichen.", + "Unexpected_0_Did_you_mean_to_escape_it_with_backslash_1508": "Unerwartete(s/r) „{0}“. Wollten Sie mit einem umgekehrten Schrägstrich escapen?", + "Unexpected_end_of_text_1126": "Unerwartetes Textende.", + "Unexpected_keyword_or_identifier_1434": "Unerwartetes Schlüsselwort oder Bezeichner.", + "Unexpected_token_1012": "Unerwartetes Token.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Unerwartetes Token. Ein Konstruktor, eine Methode, eine Zugriffsmethode oder eine Eigenschaft wurde erwartet.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Unerwartetes Token. Es wurde ein Typparametername ohne geschweifte Klammern erwartet.", + "Unexpected_token_Did_you_mean_or_gt_1382": "Unerwartetes Token. Meinten Sie \"{'>'}\" oder \">\"?", + "Unexpected_token_Did_you_mean_or_rbrace_1381": "Unerwartetes Token. Meinten Sie \"{'}'}\" oder \"}\"?", + "Unexpected_token_expected_1179": "Unerwartetes Token. \"{\" wurde erwartet.", + "Unicode_escape_sequence_cannot_appear_here_17021": "Die Unicode-Escapesequenz kann hier nicht angezeigt werden.", + "Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_se_1538": "Unicode-Escapesequenzen sind nur verfügbar, wenn das Unicode-Flag (u) oder das Unicode Sets-Flag (v) festgelegt ist.", + "Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v__1530": "Unicode-Eigenschaftswertausdrücke sind nur verfügbar, wenn das Unicode-Flag (u) oder das Unicode Sets-Flag (v) festgelegt ist.", + "Unknown_Unicode_property_name_1524": "Unbekannter Unicode-Eigenschaftsname.", + "Unknown_Unicode_property_name_or_value_1529": "Unbekannter Unicode-Eigenschaftsname oder -Wert.", + "Unknown_Unicode_property_value_1526": "Unbekannter Unicode-Eigenschaftswert.", + "Unknown_build_option_0_5072": "Unbekannte Buildoption \"{0}\".", + "Unknown_build_option_0_Did_you_mean_1_5077": "Unbekannte Buildoption \"{0}\". Meinten Sie \"{1}\"?", + "Unknown_compiler_option_0_5023": "Unbekannte Compileroption \"{0}\".", + "Unknown_compiler_option_0_Did_you_mean_1_5025": "Unbekannte Compileroption \"{0}\". Meinten Sie \"{1}\"?", + "Unknown_keyword_or_identifier_Did_you_mean_0_1435": "Unbekanntes Schlüsselwort oder Bezeichner. Meinten Sie \"{0}\"?", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Unbekannte Option \"exclude\". Meinten Sie \"exclude\"?", + "Unknown_regular_expression_flag_1499": "Unbekanntes Flag für reguläre Ausdrücke.", + "Unknown_type_acquisition_option_0_17010": "Unbekannte Option zur Typerfassung: {0}.", + "Unknown_type_acquisition_option_0_Did_you_mean_1_17018": "Unbekannte Typerfassungsoption \"{0}\". Meinten Sie \"{1}\"?", + "Unknown_watch_option_0_5078": "Unbekannte Überwachungsoption \"{0}\".", + "Unknown_watch_option_0_Did_you_mean_1_5079": "Unbekannte Überwachungsoption \"{0}\". Meinten Sie \"{1}\"?", + "Unreachable_code_detected_7027": "Es wurde unerreichbarer Code erkannt.", + "Unterminated_Unicode_escape_sequence_1199": "Nicht abgeschlossene Unicode-Escapesequenz.", + "Unterminated_quoted_string_in_response_file_0_6045": "Nicht abgeschlossene Zeichenfolge in Anführungszeichen in der Datei \"{0}\".", + "Unterminated_regular_expression_literal_1161": "Nicht abgeschlossenes reguläres Ausdrucksliteral.", + "Unterminated_string_literal_1002": "Nicht abgeschlossenes Zeichenfolgenliteral.", + "Unterminated_template_literal_1160": "Nicht abgeschlossenes Vorlagenliteral.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Nicht typisierte Funktionsaufrufe dürfen keine Typargumente annehmen.", + "Unused_label_7028": "Nicht verwendete Bezeichnung.", + "Unused_ts_expect_error_directive_2578": "Nicht verwendete @ts-expect-error-Direktive.", + "Update_import_from_0_90058": "Import von \"{0}\" aktualisieren", + "Update_modifiers_of_0_90061": "Modifizierer von „{0}“ aktualisieren", + "Updating_output_timestamps_of_project_0_6359": "Ausgabezeitstempel von Projekt \"{0}\" werden aktualisiert...", + "Updating_unchanged_output_timestamps_of_project_0_6371": "Unveränderte Ausgabezeitstempel von Projekt \"{0}\" werden aktualisiert...", + "Use_0_95174": "Verwenden Sie „{0}“.", + "Use_0_instead_5106": "Verwenden Sie stattdessen „{0}“.", + "Use_Number_isNaN_in_all_conditions_95175": "Verwenden Sie „Number.isNaN“ unter allen Bedingungen.", + "Use_element_access_for_0_95145": "Elementzugriff für \"{0}\" verwenden", + "Use_element_access_for_all_undeclared_properties_95146": "Elementzugriff für alle nicht deklarierten Eigenschaften verwenden", + "Use_import_type_95180": "„Importtyp“ verwenden", + "Use_synthetic_default_member_95016": "Verwenden Sie den synthetischen Member \"default\".", + "Use_the_package_json_exports_field_when_resolving_package_imports_6408": "Verwenden Sie das package.json-Feld „exports“, wenn Sie Paketimporte auflösen.", + "Use_the_package_json_imports_field_when_resolving_imports_6409": "Verwenden Sie das package.json-Feld „imports“, wenn Sie Importe auflösen.", + "Use_type_0_95181": "„Typ {0}“ verwenden", + "Using_0_subpath_1_with_target_2_6404": "Verwenden von \"{0}\" Unterpfad \"{1}\" mit Ziel \"{2}\".", + "Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found_2879": "Die Verwendung von JSX-Fragmenten erfordert, dass die Fragmentfabrik '{0}' im Geltungsbereich ist, aber sie konnte nicht gefunden werden.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Das Verwenden einer Zeichenfolge in einer for...of-Anweisung wird nur in ECMAScript 5 oder höher unterstützt.", + "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Bei Verwendung von --build wird tsc durch -b dazu veranlasst, sich eher wie ein Build-Orchestrator als ein Compiler zu verhalten. Damit wird der Aufbau von zusammengesetzten Projekten ausgelöst. Weitere Informationen dazu finden Sie unter {0}", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Compileroptionen der Projektverweisumleitung \"{0}\" werden verwendet.", + "VERSION_6036": "VERSION", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Der Wert des Typs \"{0}\" verfügt über keine gemeinsamen Eigenschaften mit dem Typ \"{1}\". Wollten Sie ihn aufrufen?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Der Wert des Typs \"{0}\" kann nicht aufgerufen werden. Wollten Sie \"new\" einschließen?", + "Variable_0_implicitly_has_an_1_type_7005": "Die Variable \"{0}\" weist implizit einen Typ \"{1}\" auf.", + "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043": "Die Variable \"{0}\" weist implizit einen Typ \"{1}\" auf, möglicherweise kann jedoch ein besserer Typ aus der Syntax abgeleitet werden.", + "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046": "Die Variable \"{0}\" weist an einigen Stellen implizit den Typ \"{1}\" auf, möglicherweise kann jedoch ein besserer Typ aus der Syntax abgeleitet werden.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "Die Variable \"{0}\" weist an manchen Stellen implizit den Typ \"{1}\" auf, an denen der Typ nicht ermittelt werden kann.", + "Variable_0_is_used_before_being_assigned_2454": "Die Variable \"{0}\" wird vor ihrer Zuweisung verwendet.", + "Variable_declaration_expected_1134": "Eine Variablendeklaration wurde erwartet.", + "Variable_declaration_list_cannot_be_empty_1123": "Die Variablendeklarationsliste darf nicht leer sein.", + "Variable_declaration_not_allowed_at_this_location_1440": "Variablendeklaration ist an dieser Stelle nicht zulässig.", + "Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9010": "Die Variable muss eine explizite Typanmerkung mit --isolatedDeclarations aufweisen.", + "Variables_with_multiple_declarations_cannot_be_inlined_95186": "Variablen mit mehreren Deklarationen können nicht inline verwendet werden.", + "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625": "Das variadic-Element an Position {0} in der Quelle stimmt nicht mit dem Element an Position {1} im Ziel überein.", + "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637": "Abweichungsanmerkungen werden nur in Typaliasnamen für Objekt-, Funktions-, Konstruktor- und zugeordnete Typen unterstützt.", + "Version_0_6029": "Version {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file_95110": "Besuchen Sie https://aka.ms/tsconfig, um mehr über diese Datei zu erfahren.", + "WATCH_OPTIONS_6918": "ÜBERWACHUNGSOPTIONEN", + "Watch_and_Build_Modes_6250": "Überwachungs- und Buildmodi", + "Watch_input_files_6005": "Eingabedateien überwachen.", + "Watch_option_0_requires_a_value_of_type_1_5080": "Die Überwachungsoption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Wir können nur einen Typ für „{0}“ schreiben, indem hier ein Typ für den gesamten Parameter hinzugefügt wird.", + "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Überprüfen Sie beim Zuweisen von Funktionen, ob Parameter und Rückgabewerte untertypkompatibel sind.", + "When_type_checking_take_into_account_null_and_undefined_6699": "Berücksichtigen Sie bei der Typüberprüfung „null“ und „undefined“.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Gibt an, ob eine veraltete Konsolenausgabe im Überwachungsmodus beibehalten wird, statt den Bildschirm zu löschen.", + "Wrap_all_invalid_characters_in_an_expression_container_95109": "Alle ungültigen Zeichen mit einem Ausdruckscontainer umschließen", + "Wrap_all_invalid_decorator_expressions_in_parentheses_95195": "Umschließen aller ungültigen Decoratorausdrücke in Klammern", + "Wrap_all_object_literal_with_parentheses_95116": "Gesamtes Objektliteral in Klammern einschließen", + "Wrap_all_unparented_JSX_in_JSX_fragment_95121": "Alle JSX ohne übergeordnetes Element mit JSX -Fragment umschließen", + "Wrap_in_JSX_fragment_95120": "Mit JSX-Fragment umschließen", + "Wrap_in_parentheses_95194": "Umschließen in Klammern", + "Wrap_invalid_character_in_an_expression_container_95108": "Ungültiges Zeichen mit Ausdruckscontainer umschließen", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Schließen Sie den folgenden Text, der ein Objektliteral darstellt, in Klammern ein.", + "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Informationen zu allen Compileroptionen finden Sie unter {0}", + "You_cannot_rename_a_module_via_a_global_import_8031": "Ein Modul kann nicht über einen globalen Import umbenannt werden.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Elemente, die in einem Ordner \"node_modules\" definiert sind, können nicht umbenannt werden.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Elemente, die in einem anderen Ordner \"node_modules\" definiert sind, können nicht umbenannt werden.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Sie können keine Elemente umbenennen, die in der TypeScript-Standardbibliothek definiert sind.", + "You_cannot_rename_this_element_8000": "Sie können dieses Element nicht umbenennen.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" akzeptiert zu wenige Argumente, um hier als Decorator verwendet zu werden. Wollten Sie es zuerst aufrufen und \"@{0}()\" schreiben?", + "_0_and_1_index_signatures_are_incompatible_2330": "Indexsignaturen \"{0}\" und \"{1}\" sind nicht kompatibel.", + "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Die Vorgänge \"{0}\" und \"{1}\" dürfen nicht ohne Klammern kombiniert werden.", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" ist zweimal angegeben. Das Attribut mit dem Namen \"{0}\" wird überschrieben.", + "_0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17019": "„{0}“ am Ende eines Typs ist keine gültige TypeScript-Syntax. Wollten Sie „{1}“ schreiben?", + "_0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17020": "„{0}“ am Anfang eines Typs ist keine gültige TypeScript-Syntax. Wollten Sie „{1}“ schreiben?", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "\"{0}\" kann nur importiert werden, indem das Flag \"esModuleInterop\" aktiviert und ein Standardimport verwendet wird.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "\"{0}\" kann nur mithilfe eines Standardimports importiert werden.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "\"{0}\" kann nur mit einem Aufruf von \"require\" oder durch Aktivieren des Flags \"esModuleInterop\" und Verwendung eines Standardimports importiert werden.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "\"{0}\" kann nur mit einem Aufruf von \"require\" oder durch Verwendung eines Standardimports importiert werden.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "\"{0}\" kann nur mit \"import {1} = require({2})\" oder über einen Standardimport importiert werden.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "\"{0}\" kann nur mit \"import {1} = require({2})\" oder durch Aktivieren des Flags \"esModuleInterop\" und Verwendung eines Standardimports importiert werden.", + "_0_cannot_be_used_as_a_JSX_component_2786": "\"{0}\" kann nicht als JSX-Komponente verwendet werden.", + "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "\"{0}\" kann nicht als Wert verwendet werden, weil der Export mit \"export type\" durchgeführt wurde.", + "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "\"{0}\" kann nicht als Wert verwendet werden, weil der Import mit \"import type\" durchgeführt wurde.", + "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "{0}-Komponenten akzeptieren Text nicht als untergeordnete Elemente. Der Text in der JSX weist den Typ \"string\" auf, aber für \"{1}\" wird der Typ \"{2}\" erwartet.", + "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082": "\"{0}\" konnte mit einem arbiträren Typ instanziiert werden, der mit \"{1}\" möglicherweise in keinem Zusammenhang steht.", + "_0_declarations_can_only_be_declared_inside_a_block_1156": "„{0}“-Deklarationen können nur innerhalb eines Blocks deklariert werden.", + "_0_declarations_can_only_be_used_in_TypeScript_files_8006": "{0}-Deklarationen können nur in TypeScript-Dateien verwendet werden.", + "_0_declarations_may_not_have_binding_patterns_1492": "„{0}“-Deklarationen dürfen keine Bindungsmuster aufweisen.", + "_0_declarations_must_be_initialized_1155": "„{0}“-Deklarationen müssen initialisiert werden.", + "_0_expected_1005": "\"{0}\" wurde erwartet.", + "_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is__18055": "„{0}“ hat einen Zeichenfolgentyp, muss aber syntaktisch erkennbare Zeichenfolgensyntax aufweisen, wenn „isolatedModules“ aktiviert ist.", + "_0_has_no_exported_member_named_1_Did_you_mean_2_2724": "\"{0}\" umfasst keinen exportierten Member namens \"{1}\". Meinten Sie \"{2}\"?", + "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050": "\"{0}\" weist implizit einen Rückgabetyp \"{1}\" auf, möglicherweise kann jedoch ein besserer Typ aus der Syntax abgeleitet werden.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "\"{0}\" weist implizit den Typ \"any\" auf, weil keine Rückgabetypanmerkung vorhanden ist und darauf direkt oder indirekt in einem der Rückgabeausdrücke des Objekts verwiesen wird.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "\"{0}\" weist implizit den Typ \"any\" auf, weil keine Typanmerkung vorhanden ist und darauf direkt oder indirekt im eigenen Initialisierer verwiesen wird.", + "_0_index_signatures_are_incompatible_2634": "\"{0}\" Indexsignaturen sind inkompatibel.", + "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "\"{0}\" Indextyp \"{1}\" kann nicht \"{2}\" Indextyp \"{3}\" zugewiesen werden.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "\"{0}\" ist ein primitiver Typ, aber \"{1}\" ist ein Wrapperobjekt. Verwenden Sie vorzugsweise \"{0}\", wenn möglich.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "\"{0}\" ist ein Typ und kann nicht in JavaScript-Dateien importiert werden. Verwenden Sie \"{1}\" in einer JSDoc-Typanmerkung.", + "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled_1484": "„{0}“ ist ein Typ und muss mit einem reinen Typimport importiert werden, wenn „verbatimModuleSyntax“ aktiviert ist.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "„{0}“ ist eine nicht verwendete Umbenennung von „{1}“. Wollten Sie sie als Typanmerkung verwenden?", + "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "\"{0}\" kann der Einschränkung vom Typ \"{1}\" zugewiesen werden, aber \"{1}\" könnte mit einem anderen Untertyp der Einschränkung \"{2}\" instanziiert werden.", + "_0_is_automatically_exported_here_18044": "\"{0}\" wird hier automatisch exportiert.", + "_0_is_declared_but_its_value_is_never_read_6133": "\"{0}\" ist deklariert, aber der zugehörige Wert wird nie gelesen.", + "_0_is_declared_but_never_used_6196": "\"{0}\" ist deklariert, wird aber nie verwendet.", + "_0_is_declared_here_2728": "\"{0}\" wird hier deklariert.", + "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611": "\"{0}\" ist als Eigenschaft in der Klasse \"{1}\" definiert, wird aber hier in \"{2}\" als Accessor überschrieben.", + "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "\"{0}\" ist als Accessor in der Klasse \"{1}\" definiert, wird aber hier in \"{2}\" als Instanzeigenschaft überschrieben.", + "_0_is_deprecated_6385": "\"{0}\" ist veraltet.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" ist keine gültige Metaeigenschaft für das Schlüsselwort \"{1}\". Meinten Sie \"{2}\"?", + "_0_is_not_allowed_as_a_parameter_name_1390": "\"{0}\" ist als Parametername nicht zulässig.", + "_0_is_not_allowed_as_a_variable_declaration_name_1389": "\"{0}\" ist als Name für Variablendeklarationen nicht zulässig.", + "_0_is_of_type_unknown_18046": "\"{0}\" ist vom Typ \"unbekannt\".", + "_0_is_possibly_null_18047": "\"{0}\" ist möglicherweise \"null\".", + "_0_is_possibly_null_or_undefined_18049": "\"{0}\" ist möglicherweise \"null\" oder \"nicht definiert\".", + "_0_is_possibly_undefined_18048": "\"{0}\" ist möglicherweise nicht \"nicht definiert\".", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Auf \"{0}\" wird direkt oder indirekt im eigenen Basisausdruck verwiesen.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Auf \"{0}\" wird direkt oder indirekt in der eigenen Typanmerkung verwiesen.", + "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783": "\"{0}\" wurde mehrmals angegeben, deshalb wird dieses Vorkommen überschrieben.", + "_0_list_cannot_be_empty_1097": "Die {0}-Liste darf nicht leer sein.", + "_0_modifier_already_seen_1030": "Der {0}-Modifizierer ist bereits vorhanden.", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias_1274": "Der Modifizierer „{0}“ kann nur für einen Typparameter einer Klasse, einer Schnittstelle oder eines Typalias verwendet werden.", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class_1277": "Der Modifizierer „{0}“ kann nur für einen Typparameter einer Funktion, Methode oder Klasse angezeigt werden.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Der Modifizierer \"{0}\" darf nicht für eine Konstruktordeklaration verwendet werden.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Der Modifizierer \"{0}\" darf nicht für ein Modul- oder Namespaceelement verwendet werden.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Der Modifizierer \"{0}\" darf nicht für einen Parameter verwendet werden.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Der Modifizierer \"{0}\" darf nicht für einen Typmember verwendet werden.", + "_0_modifier_cannot_appear_on_a_type_parameter_1273": "Der Modifizierer „{0}“ kann nicht für einen Typparameter verwendet werden", + "_0_modifier_cannot_appear_on_a_using_declaration_1491": "Der Modifizierer „{0}“ kann nicht in einer „using“-Deklaration angezeigt werden.", + "_0_modifier_cannot_appear_on_an_await_using_declaration_1495": "Der Modifizierer „{0}“ kann nicht in einer „await using“-Deklaration angezeigt werden.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Der Modifizierer \"{0}\" darf nicht für eine Indexsignatur verwendet werden.", + "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031": "Der Modifizierer \"{0}\" kann nicht für Klassenelemente dieser Art verwendet werden.", + "_0_modifier_cannot_be_used_here_1042": "Der Modifizierer \"{0}\" kann hier nicht verwendet werden.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Der Modifizierer \"{0}\" kann nicht in einem Umgebungskontext verwendet werden.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Der Modifizierer \"{0}\" darf nicht mit dem Modifizierer \"{1}\" verwendet werden.", + "_0_modifier_cannot_be_used_with_a_private_identifier_18019": "Der Modifizierer \"{0}\" kann nicht mit einem privaten Bezeichner verwendet werden.", + "_0_modifier_must_precede_1_modifier_1029": "Der Modifizierer \"{0}\" muss dem Modifizierer \"{1}\" vorangestellt sein.", + "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531": "Auf „\\{0}“ muss ein Unicode-Eigenschaftswertausdruck folgen, der in geschweifte Klammern eingeschlossen ist.", + "_0_needs_an_explicit_type_annotation_2782": "\"{0}\" erfordert eine explizite Typanmerkung.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "\"{0}\" bezieht sich nur auf einen Typ, wird hier jedoch als Namespace verwendet.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "\"{0}\" bezieht sich nur auf einen Typ, wird aber hier als Wert verwendet.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690": "\"{0}\" bezieht sich nur auf einen Typ, wird hier jedoch als Wert verwendet. Wollten Sie \"{1} in {0}\" verwenden?", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585": "\"{0}\" bezieht sich nur auf einen Typ, wird hier jedoch als Wert verwendet. Müssen Sie Ihre Zielbibliothek ändern? Ändern Sie die Compileroption \"lib\" in \"es2015\" oder höher.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "\"{0}\" bezieht sich auf eine globale UMD, die aktuelle Datei ist jedoch ein Modul. Ziehen Sie in Betracht, stattdessen einen Import hinzuzufügen.", + "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749": "\"{0}\" bezieht sich auf einen Wert, wird hier jedoch als Typ verwendet. Meinten Sie \"typeof {0}\"?", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1291": "„{0}“ wird in einen Typ aufgelöst und muss in dieser Datei als schreibgeschützt gekennzeichnet werden, bevor der Export erneut ausgeführt wird, wenn „{1}“ aktiviert ist. Verwenden Sie ggf. „import type“, wobei „{0}“ importiert wird.", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1292": "„{0}“ wird in einen Typ aufgelöst und muss in dieser Datei als schreibgeschützt gekennzeichnet werden, bevor der Export erneut ausgeführt wird, wenn „{1}“ aktiviert ist. Erwägen Sie die Verwendung von „export type { {0} as default }“.", + "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimMo_1485": "„{0}“ wird in eine schreibgeschützte Deklaration aufgelöst und muss mithilfe eines reinen Typimports importiert werden, wenn „verbatimModuleSyntax“ aktiviert ist.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1289": "„{0}“ wird in eine schreibgeschützte Deklaration aufgelöst und muss in dieser Datei als schreibgeschützt gekennzeichnet werden, bevor erneut exportiert wird, wenn „{1}“ aktiviert ist. Verwenden Sie ggf. „import type“, wobei „{0}“ importiert wird.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1290": "„{0}“ wird in eine schreibgeschützte Deklaration aufgelöst und muss in dieser Datei als schreibgeschützt gekennzeichnet werden, bevor erneut exportiert wird, wenn „{1}“ aktiviert ist. Erwägen Sie die Verwendung von „export type { {0} as default }“.", + "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_1448": "„{0}“ wird in eine reine Typdeklaration aufgelöst und muss mithilfe eines reinen Typreexports erneut exportiert werden, wenn „{1}“ aktiviert ist.", + "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258": "\"{0}\" sollte im CompilerOptions-Objekt der JSON-Konfigurationsdatei festgelegt werden.", + "_0_tag_already_specified_1223": "Das Tag \"{0}\" wurde bereits angegeben.", + "_0_was_also_declared_here_6203": "\"{0}\" wurde hier ebenfalls deklariert.", + "_0_was_exported_here_1377": "\"{0}\" wurde hier exportiert.", + "_0_was_imported_here_1376": "\"{0}\" wurde hier importiert.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "\"{0}\" ohne Rückgabetypanmerkung weist implizit einen Rückgabetyp \"{1}\" auf.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055": "\"{0}\" ohne Rückgabetypanmerkung weist implizit einen yield-Typ \"{1}\" auf.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Der Modifizierer \"abstract\" darf nur für eine Klassen-, Methoden- oder Eigenschaftendeklaration verwendet werden.", + "accessor_modifier_can_only_appear_on_a_property_declaration_1275": "Der Accessormodifizierer kann nur in einer Eigenschaftendeklaration angezeigt werden.", + "and_here_6204": "und hier.", + "arguments_cannot_be_referenced_in_property_initializers_2815": "Auf \"arguments\" kann in Eigenschaftsinitialisierern nicht verwiesen werden.", + "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476": "„auto“: Dateien mit imports, exports, import.meta, jsx (mit jsx: respond-jsx) oder esm-Format (mit module: node16+) als Module behandeln.", + "await_expression_cannot_be_used_inside_a_class_static_block_18037": "Der „await“-Ausdruck kann nicht innerhalb eines statischen Klassenblocks verwendet werden.", + "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375": "await-Ausdrücke sind nur auf der obersten Ebene einer Datei zulässig, wenn diese Datei ein Modul ist. Diese Datei enthält jedoch keinerlei Importe oder Exporte. Erwägen Sie das Hinzufügen eines leeren \"export {}\", um diese Datei als Modul zu definieren.", + "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308": "await-Ausdrücke sind nur innerhalb von asynchronen Funktionen und auf den obersten Modulebenen zulässig.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "await-Ausdrücke dürfen nicht in einem Parameterinitialisierer verwendet werden.", + "await_has_no_effect_on_the_type_of_this_expression_80007": "\"await\" hat keine Auswirkungen auf den Typ dieses Ausdrucks.", + "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853": "„await usuing“-Deklarationen sind nur auf der obersten Ebene einer Datei zulässig, wenn diese Datei ein Modul ist. Diese Datei enthält jedoch keinerlei Importe oder Exporte. Erwägen Sie das Hinzufügen eines leeren \"export {}\", um diese Datei als Modul zu definieren.", + "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852": "„await using“-Deklarationen sind nur innerhalb von asynchronen Funktionen und auf den obersten Modulebenen zulässig.", + "await_using_statements_cannot_be_used_inside_a_class_static_block_18054": "„await using“-Anweisungen können nicht innerhalb eines statischen Klassenblocks verwendet werden.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Die Option \"baseUrl\" ist auf \"{0}\" festgelegt. Dieser Wert wird verwendet, um den nicht relativen Modulnamen \"{1}\" aufzulösen.", + "c_must_be_followed_by_an_ASCII_letter_1512": "Auf „\\c“ muss ein ASCII-Buchstabe folgen.", + "can_only_be_used_at_the_start_of_a_file_18026": "\"#!\" kann nur am Anfang einer Datei verwendet werden.", + "case_or_default_expected_1130": "\"case\" oder \"default\" wurde erwartet.", + "catch_or_finally_expected_1472": "„catch“ oder „finally“ erwartet.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Der const-Enumerationsmemberinitialisierer wurde in einen unendlichen Wert ausgewertet.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Der const-Enumerationsmemberinitialisierer wurde in den unzulässigen Wert \"NaN\" ausgewertet.", + "const_enum_member_initializers_must_be_constant_expressions_2474": "Elementitialisierer für Konstantenenummeration müssen konstante Ausdrücke sein.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "const-Enumerationen können nur in Eigenschaften- bzw. Indexzugriffsausdrücken oder auf der rechten Seite einer Importdeklaration oder Exportzuweisung verwendet werden.", + "constructor_cannot_be_used_as_a_parameter_property_name_2398": "\"constructor\" kann nicht als Parametereigenschaftsname verwendet werden.", + "constructor_is_a_reserved_word_18012": "\"#constructor\" ist ein reserviertes Wort.", + "default_Colon_6903": "Standard:", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "\"delete\" kann für einen Bezeichner im Strict-Modus nicht aufgerufen werden.", + "export_Asterisk_does_not_re_export_a_default_1195": "Mit \"export *\" wird ein Standardwert nicht erneut exportiert.", + "export_can_only_be_used_in_TypeScript_files_8003": "\"export =\" kann nur in TypeScript-Dateien verwendet werden.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Der Modifizierer \"export\" kann nicht auf Umgebungsmodule und Modulerweiterungen angewendet werden, da diese immer sichtbar sind.", + "extends_clause_already_seen_1172": "Die extends-Klausel ist bereits vorhanden.", + "extends_clause_must_precede_implements_clause_1173": "Die extends-Klausel muss der implements-Klausel vorangestellt sein.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Die \"extends\"-Klausel der exportierten Klasse \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021": "Die extends-Klausel der exportierten Klasse besitzt oder verwendet den privaten Namen \"{0}\".", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Die \"extends\"-Klausel der exportierten Schnittstelle \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", + "false_unless_composite_is_set_6906": "'false', es sei denn 'composite' ist festgelegt", + "false_unless_strict_is_set_6905": "'false', es sei denn, 'strict' ist festgelegt", + "file_6025": "Datei", + "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431": "\"for await\"-Schleifen sind nur auf der obersten Ebene einer Datei zulässig, wenn diese Datei ein Modul ist. Diese Datei enthält jedoch keinerlei Importe oder Exporte. Erwägen Sie das Hinzufügen eines leeren \"export {}\", um diese Datei als Modul zu definieren.", + "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103": "\"for await\"-Schleifen sind nur innerhalb von asynchronen Funktionen und auf den obersten Modulebenen zulässig.", + "for_await_loops_cannot_be_used_inside_a_class_static_block_18038": "„For await“-Schleifen können nicht innerhalb eines statischen Klassenblocks verwendet werden.", + "get_and_set_accessors_cannot_declare_this_parameters_2784": "get- und set-Zugriffsmethoden können keine this-Parameter deklarieren.", + "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908": "'[]', wenn 'files' angegeben ist, andernfalls '[\"**/*\"]5D;'", + "implements_clause_already_seen_1175": "Die implements-Klausel ist bereits vorhanden.", + "implements_clauses_can_only_be_used_in_TypeScript_files_8005": "implements-Klauseln können nur in TypeScript-Dateien verwendet werden.", + "import_can_only_be_used_in_TypeScript_files_8002": "\"import... =\" kann nur in TypeScript-Dateien verwendet werden.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "infer-Deklarationen sind nur in der extends-Klausel eines bedingten Typs zulässig.", + "k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets_1510": "Auf „\\k“ muss ein Erfassungsgruppenname folgen, der in spitzen Klammern eingeschlossen ist.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "\"let\" darf nicht als Name in let- oder const-Deklarationen verwendet werden.", + "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010": "Modul === 'AMD' oder 'UMD' oder 'System' oder 'ES6', dann 'Klassisch', andernfalls 'Knoten'", + "module_system_or_esModuleInterop_6904": "Modul === \"System\" oder esModuleInterop", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "Der new-Ausdruck, in dessen Ziel eine Konstruktsignatur fehlt, weist implizit einen Typ \"any\" auf.", + "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907": "'[\"node_modules\",\"bower_components\",\"jspm_packages\"]', plus der Wert von 'outDir', wenn ein Wert angegeben ist.", + "one_of_Colon_6900": "eines von:", + "one_or_more_Colon_6901": "eins oder mehr:", + "options_6024": "Optionen", + "or_JSX_element_expected_1145": "'{' oder JSX-Element erwartet.", + "or_expected_1144": "\"{\" oder \";\" wurde erwartet.", + "package_json_does_not_have_a_0_field_6100": "\"package.json\" besitzt kein \"{0}\"-Feld.", + "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "\"package.json\" weist keinen Eintrag \"typesVersions\" auf, der mit der Version {0} übereinstimmt.", + "package_json_had_a_falsy_0_field_6220": "\"package.json\" enthielt ein \"falsy\" Feld \"{0}\".", + "package_json_has_0_field_1_that_references_2_6101": "\"package.json\" weist das {0}-Feld \"{1}\" auf, das auf \"{2}\" verweist.", + "package_json_has_a_peerDependencies_field_6281": "„package.json“ weist das Feld „peerDependencies“ auf.", + "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209": "\"package.json\" weist einen typesversion-Eintrag \"{0}\" auf, der kein gültiger semver-Bereich ist.", + "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208": "\"package.json\" weist einen typesVersions-Eintrag \"{0}\" auf, der der Compilerversion \"{1}\" entspricht. Es wird nach einem Muster gesucht, das dem Modulnamen \"{2}\" entspricht.", + "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206": "\"package.json\" weist ein Feld \"typesVersions\" mit versionsspezifischen Pfadzuordnungen auf.", + "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274": "Der package.json-Bereich \"{0}\" ordnet den Bezeichner \"{1}\" explizit NULL zu.", + "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275": "Der package.json-Bereich \"{0}\" weist einen ungültigen Typ für das Ziel des Spezifizierers \"{1}\" auf.", + "package_json_scope_0_has_no_imports_defined_6273": "Für package.jsim, Bereich \"{0}\" wurden keine Importe definiert.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Die Option \"paths\" wurde angegeben. Es wird nach einem Muster gesucht, das mit dem Modulnamen \"{0}\" übereinstimmt.", + "q_is_only_available_inside_character_class_1511": "„\\q“ ist nur innerhalb der Zeichenklasse verfügbar.", + "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521": "Auf „\\q“ müssen Zeichenfolgenalternativen folgen, die in geschweifte Klammern eingeschlossen sind.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Der Modifizierer \"readonly\" darf nur für eine Eigenschaftendeklaration oder Indexsignatur verwendet werden.", + "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Der Typmodifizierer \"readonly\" ist nur für Array- und Tupelliteraltypen zulässig.", + "require_call_may_be_converted_to_an_import_80005": "Der Aufruf von \"require\" kann in einen Aufruf von \"import\" konvertiert werden.", + "resolution_mode_can_only_be_set_for_type_only_imports_1454": "„resolution-mode“ kann nur für reine Typenimporte festgelegt werden.", + "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "„resolution-mode“ ist für Typimportassertionen der einzige gültige Schlüssel.", + "resolution_mode_is_the_only_valid_key_for_type_import_attributes_1463": "„resolution-mode“ ist für Typimportattribute der einzige gültige Schlüssel.", + "resolution_mode_should_be_either_require_or_import_1453": "„resolution-mode“ muss entweder auf „require“ oder „import“ festgelegt sein.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Die Option \"rootDirs\" wurde festgelegt. Sie wird zum Auflösen des relativen Modulnamens \"{0}\" verwendet.", + "super_can_only_be_referenced_in_a_derived_class_2335": "Auf \"super\" kann nur in einer abgeleiteten Klasse verwiesen werden.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Auf \"super\" kann nur in Membern abgeleiteter Klassen oder Objektliteralausdrücken verwiesen werden.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Auf \"super\" kann nicht in einem berechneten Eigenschaftennamen verwiesen werden.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Auf \"super\" kann nicht in Konstruktorargumenten verwiesen werden.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "\"super\" ist nur in Membern von Objektliteralausdrücken zulässig, wenn die Option \"target\" den Wert \"ES2015\" oder höher aufweist.", + "super_may_not_use_type_arguments_2754": "\"super\" darf keine Typargumente verwenden.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Vor dem Zugriff auf eine Eigenschaft von \"super\" im Konstruktor einer abgeleiteten Klasse muss \"super\" aufgerufen werden.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "\"super\" muss vor dem Zugreifen auf \"this\" im Konstruktor einer abgeleiteten Klasse aufgerufen werden.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "Auf \"super\" muss eine Argumentliste oder Memberzugriff folgen.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "Der Zugriff auf die super-Eigenschaft ist nur in einem Konstruktor, einer Memberfunktion oder einer Memberzugriffsmethode einer abgeleiteten Klasse zulässig.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Auf \"this\" kann nicht in einem berechneten Eigenschaftennamen verwiesen werden.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Auf \"this\" kann nicht in einem Modul- oder Namespacetext verwiesen werden.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Auf \"this\" kann nicht in einem statischen Eigenschafteninitialisierer verwiesen werden.", + "this_cannot_be_referenced_in_current_location_2332": "Auf \"this\" kann am aktuellen Speicherort nicht verwiesen werden.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "\"this\" weist implizit den Typ \"any\" auf, weil keine Typanmerkung vorhanden ist.", + "true_for_ES2022_and_above_including_ESNext_6930": "\"true\" für ES2022 und höher, einschließlich ESNext.", + "true_if_composite_false_otherwise_6909": "'true', wenn 'composite', andernfalls 'false'", + "true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false_6411": "„true“, wenn „moduleResolution“ „node16“, „nodenext“ oder „bundler“ ist; andernfalls „false“.", + "tsc_Colon_The_TypeScript_Compiler_6922": "tsc: Der TypeScript-Compiler", + "type_Colon_6902": "Typ:", + "unique_symbol_types_are_not_allowed_here_1335": "\"unique symbol\"-Typen sind hier nicht zulässig.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "\"unique symbol\"-Typen sind nur für Variablen in einer Variablenanweisung zulässig.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "\"unique symbol\"-Typen dürfen für eine Variablendeklaration mit einem Bindungsnamen nicht verwendet werden.", + "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347": "Eine Verwendung der Direktive \"use strict\" mit einer nicht einfachen Parameterliste ist nicht zugelassen.", + "use_strict_directive_used_here_1349": "Die Direktive \"use strict\" wird hier verwendet.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "with-Anweisungen sind in einem asynchronen Funktionsblock unzulässig.", + "with_statements_are_not_allowed_in_strict_mode_1101": "this-Anweisungen sind im Strict-Modus unzulässig.", + "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057": "Der Ausdruck \"yield\" führt implizit zu einem Typ \"any\", weil der enthaltende Generator keine Anmerkung vom Rückgabetyp umfasst.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "yield-Ausdrücke dürfen nicht in einem Parameterinitialisierer verwendet werden." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/es/diagnosticMessages.generated.json b/node_modules/typescript/lib/es/diagnosticMessages.generated.json new file mode 100644 index 00000000..767c4977 --- /dev/null +++ b/node_modules/typescript/lib/es/diagnosticMessages.generated.json @@ -0,0 +1,2105 @@ +{ + "ALL_COMPILER_OPTIONS_6917": "TODAS LAS OPCIONES DEL COMPILADOR", + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Un modificador '{0}' no se puede usar con una declaración de importación.", + "A_0_parameter_must_be_the_first_parameter_2680": "El parámetro \"{0}\" debe ser el primer parámetro.", + "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039": "Una etiqueta \"@template\" de JSDoc no puede seguir a una etiqueta \"@typedef\", \"@callback\" u \"@overload\"", + "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033": "Un comentario \"@typedef\" de JSDoc no puede contener varias etiquetas \"@type\".", + "A_bigint_literal_cannot_be_used_as_a_property_name_1539": "No se puede usar un literal 'bigint' como nombre de propiedad.", + "A_bigint_literal_cannot_use_exponential_notation_1352": "Un literal bigint no puede usar la notación exponencial.", + "A_bigint_literal_must_be_an_integer_1353": "Un literal bigint debe ser un entero.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Un parámetro de patrón de enlace no puede ser opcional en una signatura de implementación.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Una instrucción \"break\" solo se puede usar dentro de una iteración envolvente o en una instrucción switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Una instrucción \"break\" solo puede saltar a una etiqueta de una instrucción envolvente.", + "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522": "Una clase de caracteres no debe contener un signo de puntuación doble reservado. ¿Querías escaparlo con barra diagonal inversa?", + "A_character_class_range_must_not_be_bounded_by_another_character_class_1516": "Un rango de clases de caracteres no debe estar limitado por otra clase de caracteres.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Una clase solo puede implementar un identificador o nombre completo con argumentos de tipo opcional.", + "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422": "Una clase solo puede implementar un tipo de objeto o una intersección de tipos de objeto con miembros conocidos estáticamente.", + "A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values_2863": "Una clase no puede extender un tipo primitivo como '{0}'. Las clases solo pueden extender valores que se puedan construir.", + "A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types_2864": "Una clase no puede implementar un tipo primitivo como '{0}'. Solo puede implementar otros tipos de objeto con nombre.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Una declaración de clase sin el modificador \"default\" debe tener un nombre.", + "A_class_member_cannot_have_the_0_keyword_1248": "Un miembro de clase no puede tener la palabra clave '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "No se admite una expresión de coma en un nombre de propiedad calculada.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nombre de propiedad calculada no puede hacer referencia a un parámetro de tipo desde su tipo contenedor.", + "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166": "Un nombre de propiedad calculada de una declaración de propiedad de clase debe tener un tipo de literal simple o un tipo \"unique symbol\".", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nombre de propiedad calculada en una sobrecarga de método debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nombre de propiedad calculada en un literal de tipo debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nombre de propiedad calculada en un contexto de ambiente debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nombre de propiedad calculada en una interfaz debe hacer referencia a una expresión que sea de tipo literal o \"unique symbol\".", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nombre de propiedad calculada debe ser de tipo \"string\", \"number\", \"symbol\" o \"any\".", + "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355": "Las aserciones \"const\" solo pueden aplicarse a las referencias a miembros de enumeración o a literales de cadena, numéricos, booleanos, de matriz o de objeto.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Solo se puede acceder a un miembro de enumeración const mediante un literal de cadena.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254": "Un inicializador \"const\" en un contexto de ambiente debe ser un literal de cadena o numérico o bien una referencia de enumeración de literal.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Un constructor no puede contener una llamada a \"super\" si su clase extiende \"null\".", + "A_constructor_cannot_have_a_this_parameter_2681": "Un constructor no puede tener un parámetro 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Una instrucción \"continue\" solo se puede usar en una instrucción de iteración envolvente.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Una instrucción \"continue\" solo puede saltar a una etiqueta de una instrucción de iteración envolvente.", + "A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_f_2846": "No se puede importar un archivo de declaración sin 'import type'. ¿Quería importar un archivo de implementación '{0}' en su lugar?", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Un modificador \"declare\" no se puede usar en un contexto de ambiente.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Un decorador solo puede modificar la implementación de un método, no una sobrecarga.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Una cláusula \"default\" no puede aparecer más de una vez en una instrucción \"switch\".", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Solo se puede usar una exportación predeterminada en un módulo de estilo ECMAScript.", + "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258": "Una exportación predeterminada debe estar en el nivel superior de una declaración de módulo o archivo.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "En este contexto no se permite una aserción de asignación definitiva \"!\".", + "A_destructuring_declaration_must_have_an_initializer_1182": "Una declaración de desestructuración debe tener un inicializador.", + "A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_t_2712": "Una llamada de importación dinámica en ES5 requiere el constructor \"Promise\". Asegúrese de que tiene una declaración para el constructor \"Promise\" o incluya \"ES2015\" en su opción \"--lib\".", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Una llamada de importación dinámica devuelve un valor \"Promise\". Asegúrese de que tiene una declaración para \"Promise\" o incluya \"ES2015\" en la opción \"--lib\".", + "A_file_cannot_have_a_reference_to_itself_1006": "Un archivo no puede tener una referencia a sí mismo.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Una función que devuelve 'never' no puede tener un punto de conexión alcanzable.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Una función a la que se llama con la palabra clave 'new' no puede tener un tipo 'this' que sea 'void'.", + "A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value_2355": "Una función cuyo tipo declarado no es \"undefined\", \"void\" o \"any\" debe devolver un valor.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Un generador no puede tener una anotación de tipo \"void\".", + "A_get_accessor_cannot_have_parameters_1054": "Un descriptor de acceso \"get\" no puede tener parámetros.", + "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808": "Un descriptor de acceso get debe ser al menos tan accesible como el establecedor", + "A_get_accessor_must_return_a_value_2378": "Un descriptor de acceso \"get\" debe devolver un valor.", + "A_label_is_not_allowed_here_1344": "No se permite una etiqueta aquí.", + "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Un elemento de tupla etiquetado se declara como opcional con un signo de interrogación después del nombre y antes de los dos puntos, en lugar de después del tipo.", + "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Un elemento de tupla etiquetado se declara como rest con \"...\" delante del nombre, en lugar de delante del tipo.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Un tipo asignado no puede declarar propiedades ni métodos.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inicializador de miembro de una declaración de enumeración no puede hacer referencia a los miembros que se declaran después de este, incluidos aquellos definidos en otras enumeraciones.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una clase mixin debe tener un constructor con un solo parámetro rest de tipo \"any[]\"", + "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Una clase mixin que se extiende desde una variable de tipo que contiene una signatura de construcción abstracta debe declararse también como \"abstract\".", + "A_module_cannot_have_multiple_default_exports_2528": "Un módulo no puede tener varias exportaciones predeterminadas.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una declaración de espacio de nombres no puede estar en un archivo distinto de una clase o función con la que se combina.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una declaración de espacio de nombres no se puede situar antes que una clase o función con la que se combina.", + "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235": "Una declaración de espacio de nombres solo se permite en el nivel superior de un espacio de nombres o módulo.", + "A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_key_1540": "Una declaración \"namespace\" no debe declararse con la palabra clave \"module\". Use la palabra clave \"namespace\" en su lugar.", + "A_non_dry_build_would_build_project_0_6357": "Una compilación no -dry compilaría el proyecto \"{0}\"", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Una compilación no -dry eliminaría los archivos siguientes: {0}", + "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374": "Una compilación no -dry actualizaría las marcas de tiempo para la salida del proyecto \"{0}\".", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inicializador de parámetros solo se permite en una implementación de función o de constructor.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Una propiedad de parámetro no se puede declarar mediante un parámetro rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una propiedad de parámetro solo se permite en una implementación de constructor.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Una propiedad de parámetro podría no declararse mediante un patrón de enlace.", + "A_promise_must_have_a_then_method_1059": "Una promesa debe tener un método \"then\".", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Una propiedad de una clase cuyo tipo sea \"unique symbol\" debe ser \"static\" y \"readonly\".", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Una propiedad de una interfaz o un literal de tipo cuyo tipo sea \"unique symbol\" debe ser \"readonly\".", + "A_required_element_cannot_follow_an_optional_element_1257": "Un elemento obligatorio no puede seguir a un elemento opcional.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un parámetro obligatorio no puede seguir a un parámetro opcional.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un elemento rest no puede contener un patrón de enlace.", + "A_rest_element_cannot_follow_another_rest_element_1265": "Un elemento rest no puede seguir a otro elemento rest.", + "A_rest_element_cannot_have_a_property_name_2566": "Un elemento rest no puede tener un nombre de propiedad.", + "A_rest_element_cannot_have_an_initializer_1186": "Un elemento rest no puede tener un inicializador.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Un elemento rest debe ser el último en un patrón de desestructuración.", + "A_rest_element_type_must_be_an_array_type_2574": "Un tipo de elemento rest debe ser un tipo de matriz.", + "A_rest_parameter_cannot_be_optional_1047": "Un parámetro rest no puede ser opcional.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Un parámetro rest no puede tener un inicializador.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Un parámetro rest debe ser el último de una lista de parámetros.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Un parámetro rest debe ser de un tipo de matriz.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Un parámetro rest o un patrón de enlace no pueden finalizar con una coma.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Una instrucción \"return\" solo se puede usar en el cuerpo de una función.", + "A_return_statement_cannot_be_used_inside_a_class_static_block_18041": "Una instrucción 'return' no se puede usar dentro de un bloque estático de clase.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Serie de entradas que reasigna las importaciones a ubicaciones de búsqueda relativas a \"baseUrl\".", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Un descriptor de acceso \"set\" no puede tener una anotación de tipo de valor devuelto.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Un descriptor de acceso \"set\" no puede tener un parámetro opcional.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Un descriptor de acceso \"set\" no puede tener un parámetro rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Un descriptor de acceso \"set\" debe tener exactamente un parámetro.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Un parámetro de descriptor de acceso \"set\" no puede tener un inicializador.", + "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556": "Un argumento de difusión debe tener un tipo de tupla o se puede pasar a un parámetro \"rest\".", + "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401": "Una llamada \"super\" debe ser una instrucción de nivel raíz dentro de un constructor de una clase derivada que contiene propiedades inicializadas, propiedades de parámetros o identificadores privados.", + "A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_2376": "Una llamada \"super\" debe ser la primera instrucción del constructor para hacer referencia a \"super\" o \"this\" cuando una clase derivada contiene propiedades inicializadas, propiedades de parámetro o identificadores privados.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Una restricción de tipo basada en 'this' no es compatible con una restricción de tipo basada en un parámetro.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "El tipo \"this\" solo está disponible en un miembro no estático de una clase o interfaz.", + "A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimM_1287": "No se puede usar un modificador \"export\" de nivel superior en declaraciones de valor en un módulo CommonJS cuando \"verbatimModuleSyntax\" está habilitado.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Ya hay un archivo \"tsconfig.json\" definido en: '{0}'.", + "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Un miembro de tupla no puede ser tanto opcional como REST.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Un tipo de tupla no se puede indizar con un valor negativo.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "No se admite una expresión de aserción de tipo en el lado izquierdo de una expresión de exponenciación. Considere la posibilidad de incluir la expresión entre paréntesis.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Una propiedad de literal de tipo no puede tener un inicializador.", + "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Una importación solo de tipo puede especificar una importación predeterminada o enlaces con nombre, pero no ambos.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Un predicado de tipo no puede hacer referencia a un parámetro rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un predicado de tipo no puede hacer referencia al elemento '{0}' de un patrón de enlace.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "En las funciones y los métodos, un predicado de tipo solo se permite en la posición de tipo de valor devuelto.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "El tipo de un predicado de tipo debe poderse asignar al tipo de su parámetro.", + "A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_w_1272": "Un tipo al que se hace referencia en una firma representativo debe importarse con \"import type\" o una importación de espacio de nombres cuando están habilitados \"isolatedModules\" y \"emitDecoratorMetadata\".", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Una variable cuyo tipo sea \"unique symbol\" debe ser \"const\".", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Una expresión \"yield\" solo se permite en un cuerpo de generador.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "No se puede acceder al método abstracto '{0}' de la clase '{1}' mediante una expresión super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Los métodos abstractos solo pueden aparecer en una clase abstracta.", + "Abstract_properties_can_only_appear_within_an_abstract_class_1253": "Las propiedades abstractas solo pueden aparecer en una clase abstracta.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "No se puede acceder a la propiedad abstracta \"{0}\" de la clase \"{1}\" en el constructor.", + "Accessibility_modifier_already_seen_1028": "El modificador de accesibilidad ya se ha visto.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Los descriptores de acceso solo están disponibles cuando el destino es ECMAScript 5 y versiones posteriores.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Los descriptores de acceso deben ser los dos abstractos o los dos no abstractos.", + "Add_0_to_unresolved_variable_90008": "Agregar \"{0}.\" a una variable no resuelta", + "Add_a_return_statement_95111": "Agregar una instrucción \"return\"", + "Add_a_return_type_to_the_function_declaration_9031": "Agrega un tipo de valor devuelto a la declaración de función.", + "Add_a_return_type_to_the_function_expression_9030": "Agrega un tipo de valor devuelto a la expresión de función.", + "Add_a_return_type_to_the_get_accessor_declaration_9032": "Agregue un tipo de valor devuelto a la declaración de get accessor.", + "Add_a_return_type_to_the_method_9034": "Agregar un tipo de valor devuelto al método", + "Add_a_type_annotation_to_the_parameter_0_9028": "Agregue una anotación de tipo al parámetro {0}.", + "Add_a_type_annotation_to_the_property_0_9029": "Agregue una anotación de tipo a la propiedad {0}.", + "Add_a_type_annotation_to_the_variable_0_9027": "Agregue una anotación de tipo a la variable {0}.", + "Add_a_type_to_parameter_of_the_set_accessor_declaration_9033": "Agregue un tipo al parámetro de la declaración del set accessor.", + "Add_all_missing_async_modifiers_95041": "Agregar todos los modificadores \"async\" que faltan", + "Add_all_missing_attributes_95168": "Agregar todos los atributos que faltan", + "Add_all_missing_call_parentheses_95068": "Agregar todos los paréntesis de llamada que faltan", + "Add_all_missing_function_declarations_95157": "Agregar todas las declaraciones de función que faltan", + "Add_all_missing_imports_95064": "Agregar todas las importaciones que faltan", + "Add_all_missing_members_95022": "Agregar todos los miembros que faltan", + "Add_all_missing_override_modifiers_95162": "Agregar todos los modificadores \"override\" que faltan", + "Add_all_missing_parameters_95190": "Agregar todos los parámetros que faltan", + "Add_all_missing_properties_95166": "Agregar todas las propiedades que faltan", + "Add_all_missing_return_statement_95114": "Agregar todas las instrucciones \"return\" que faltan", + "Add_all_missing_super_calls_95039": "Agregar todas las llamadas a super que faltan", + "Add_all_missing_type_annotations_90067": "Agregar todas las anotaciones de tipo que faltan", + "Add_all_optional_parameters_95193": "Agregar todos los parámetros opcionales", + "Add_annotation_of_type_0_90062": "Agregar anotación de tipo '{0}'", + "Add_async_modifier_to_containing_function_90029": "Agregar el modificador async a la función contenedora", + "Add_await_95083": "Agregar \"await\"", + "Add_await_to_initializer_for_0_95084": "Agregar \"await\" al inicializador de \"{0}\"", + "Add_await_to_initializers_95089": "Agregar \"await\" a los inicializadores", + "Add_braces_to_arrow_function_95059": "Agregar llaves a la función de flecha", + "Add_const_to_all_unresolved_variables_95082": "Agregar \"const\" a todas las variables no resueltas", + "Add_const_to_unresolved_variable_95081": "Agregar \"const\" a la variable no resuelta", + "Add_definite_assignment_assertion_to_property_0_95020": "Agregar aserción de asignación definitiva a la propiedad \"{0}\"", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Agregar aserciones de asignación definitiva a todas las propiedades sin inicializar", + "Add_export_to_make_this_file_into_a_module_95097": "Agregar \"export {}\" para transformar este archivo en un módulo", + "Add_extends_constraint_2211": "Agregar restricción \"extends\".", + "Add_extends_constraint_to_all_type_parameters_2212": "Agregar restricción \"extends\" a todos los parámetros de tipo", + "Add_import_from_0_90057": "Agregar importación desde “{0}”", + "Add_index_signature_for_property_0_90017": "Agregar una signatura de índice para la propiedad \"{0}\"", + "Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"", + "Add_initializers_to_all_uninitialized_properties_95027": "Agregar inicializadores a todas las propiedades sin inicializar", + "Add_missing_attributes_95167": "Agregar los atributos que faltan", + "Add_missing_call_parentheses_95067": "Agregar los paréntesis de llamada que faltan", + "Add_missing_comma_for_object_member_completion_0_95187": "Agregue la coma que falta para el '{0}' de finalización del miembro del objeto.", + "Add_missing_enum_member_0_95063": "Agregar el miembro de enumeración \"{0}\" que falta", + "Add_missing_function_declaration_0_95156": "Agregar la declaración de función \"{0}\" que falta", + "Add_missing_new_operator_to_all_calls_95072": "Agregar el operador \"new\" que falta a todas las llamadas", + "Add_missing_new_operator_to_call_95071": "Agregar el operador \"new\" que falta a la llamada", + "Add_missing_parameter_to_0_95188": "Agregar parámetro que falta a '{0}'", + "Add_missing_parameters_to_0_95189": "Agregar parámetros que faltan a '{0}'", + "Add_missing_properties_95165": "Agregar propiedades que faltan", + "Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta", + "Add_missing_typeof_95052": "Agregar el elemento \"typeof\" que falta", + "Add_names_to_all_parameters_without_names_95073": "Agregar nombres a todos los parámetros sin nombres", + "Add_optional_parameter_to_0_95191": "Agregar parámetro opcional a \"{0}\"", + "Add_optional_parameters_to_0_95192": "Agregar parámetros opcionales a \"{0}\"", + "Add_or_remove_braces_in_an_arrow_function_95058": "Agregar o quitar llaves en una función de flecha", + "Add_override_modifier_95160": "Agregar el modificador \"override\"", + "Add_parameter_name_90034": "Agregar un nombre de parámetro", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Agregar un calificador a todas las variables no resueltas que coincidan con un nombre de miembro", + "Add_resolution_mode_import_attribute_95196": "Agregar atributo de importación \"resolution-mode\"", + "Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it_95197": "Agregar el atributo de importación \"resolution-mode\" a todas las importaciones de solo tipo que lo necesiten", + "Add_return_type_0_90063": "Agregar tipo de valor devuelto '{0}'", + "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035": "Agregue satisfacciones y una aserción de tipo a esta expresión (satisfacciones T como T) para que el tipo sea explícito.", + "Add_satisfies_and_an_inline_type_assertion_with_0_90068": "Agregar satisfacciones y una aserción de tipo insertado con '{0}'", + "Add_to_all_uncalled_decorators_95044": "Agregar \"()\" a todos los elementos Decorator a los que no se llama", + "Add_ts_ignore_to_all_error_messages_95042": "Agregar \"@ts-ignore\" a todos los mensajes de error", + "Add_undefined_to_a_type_when_accessed_using_an_index_6674": "Agregue \"indefinido\" a un tipo cuando se acceda mediante un índice.", + "Add_undefined_to_optional_property_type_95169": "Agregar 'undefined' al tipo de propiedad opcional", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Agregar un tipo no definido a todas las propiedades sin inicializar", + "Add_undefined_type_to_property_0_95018": "Agregar un tipo \"undefined\" a la propiedad \"{0}\"", + "Add_unknown_conversion_for_non_overlapping_types_95069": "Agregar una conversión \"unknown\" para los tipos que no se superponen", + "Add_unknown_to_all_conversions_of_non_overlapping_types_95070": "Agregar \"unknown\" a todas las conversiones de tipos que no se superponen", + "Add_void_to_Promise_resolved_without_a_value_95143": "Agregar \"void\" a la instancia de Promise resuelta sin un valor", + "Add_void_to_all_Promises_resolved_without_a_value_95144": "Agregar \"void\" a todas las instancias de Promise resueltas sin un valor", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Agregar un archivo tsconfig.json ayuda a organizar los proyectos que contienen archivos TypeScript y JavaScript. Más información en https://aka.ms/tsconfig.", + "All_declarations_of_0_must_have_identical_constraints_2838": "Todas las declaraciones de \"{0}\" deben tener delimitaciones idénticas.", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas las declaraciones de '{0}' deben tener modificadores idénticos.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas las declaraciones de '{0}' deben tener parámetros de tipo idénticos.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas las declaraciones de un método abstracto deben ser consecutivas.", + "All_destructured_elements_are_unused_6198": "Todos los elementos desestructurados están sin utilizar.", + "All_imports_in_import_declaration_are_unused_6192": "Todas las importaciones de la declaración de importación están sin utilizar.", + "All_type_parameters_are_unused_6205": "Ninguno de los parámetros de tipo se usa.", + "All_variables_are_unused_6199": "Todas las variables son no utilizadas.", + "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600": "Permita que los archivos JavaScript formen parte del programa. Use la opción \"checkJS\" para obtener errores de estos archivos.", + "Allow_accessing_UMD_globals_from_modules_6602": "Permite el acceso a las bibliotecas globales de UMD desde los módulos.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permitir las importaciones predeterminadas de los módulos sin exportación predeterminada. Esto no afecta a la emisión de código, solo a la comprobación de tipos.", + "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601": "Permita \"importar x desde y\" cuando un módulo no tiene una exportación predeterminada.", + "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639": "Permita la importación de funciones de ayuda desde tslib una vez por proyecto, en lugar de incluirlas por archivo.", + "Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noE_6407": "Permitir que las importaciones incluyan extensiones de archivo TypeScript. Requiere que se establezca \"--moduleResolution bundler\" y \"--noEmit\" o \"--emitDeclarationOnly\".", + "Allow_javascript_files_to_be_compiled_6102": "Permitir que se compilen los archivos de JavaScript.", + "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691": "Permita que varias carpetas se consideren como una al resolver módulos.", + "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261": "El nombre de archivo \"{0}\" ya incluido es diferente del nombre de archivo \"{1}\" solo en el uso de mayúsculas y minúsculas.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "La declaración de módulo de ambiente no puede especificar un nombre de módulo relativo.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Los módulos de ambiente no se pueden anidar en otros módulos o espacios de nombres.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Un módulo AMD no puede tener varias asignaciones de nombre.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Un descriptor de acceso abstracto no puede tener una implementación.", + "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010": "No se puede usar un modificador de accesibilidad con un identificador privado.", + "An_accessor_cannot_have_type_parameters_1094": "Un descriptor de acceso no puede tener parámetros de tipo.", + "An_accessor_property_cannot_be_declared_optional_1276": "Una propiedad 'accessor' no se puede declarar como opcional.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Una declaración de módulo de ambiente solo se permite en el nivel superior de un archivo.", + "An_argument_for_0_was_not_provided_6210": "No se proporcionó ningún argumento para \"{0}\".", + "An_argument_matching_this_binding_pattern_was_not_provided_6211": "No se proporcionó ningún argumento que coincida con este patrón de enlace.", + "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356": "Un operando aritmético debe ser de tipo \"any\", \"number\", \"bigint\" o un tipo de enumeración.", + "An_arrow_function_cannot_have_a_this_parameter_2730": "Una función de flecha no puede tener un parámetro \"this\".", + "An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_2705": "Una función o un método de asincronía en ES5 requiere el constructor \"Promise\". Asegúrese de que tiene una declaración para el constructor \"Promise\" o incluya \"ES2015\" en su opción \"--lib\".", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Una función o un método asincrónico debe devolver un \"Promise\". Asegúrese de que tiene una declaración \"Promise\" o incluya \"ES2015\" en la opción \"--lib\".", + "An_async_iterator_must_have_a_next_method_2519": "Un iterador de asincronía debe tener un método \"next()\".", + "An_element_access_expression_should_take_an_argument_1011": "Una expresión de acceso de elemento debe admitir un argumento.", + "An_enum_member_cannot_be_named_with_a_private_identifier_18024": "No se puede denominar un miembro de enumeración con un identificador privado.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Un miembro de enumeración no puede tener un nombre numérico.", + "An_enum_member_name_must_be_followed_by_a_or_1357": "El nombre de un miembro de enumeración debe ir seguido de \",\", \"=\" o \"}\".", + "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928": "Una versión expandida de esta información, que muestra todas las opciones posibles del compilador", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Una asignación de exportación no se puede usar en un módulo con otros elementos exportados.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Una asignación de exportación no se puede usar en espacios de nombres.", + "An_export_assignment_cannot_have_modifiers_1120": "Una asignación de exportación no puede tener modificadores.", + "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231": "Una asignación de exportación debe estar en el nivel superior de una declaración de módulo o archivo.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474": "Una declaración de exportación solo se puede usar en el nivel superior de un módulo.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233": "Una declaración de exportación solo se puede usar en el nivel superior de un espacio de nombres o módulo.", + "An_export_declaration_cannot_have_modifiers_1193": "Una declaración de exportación no puede tener modificadores.", + "An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolve_1283": "Una declaración \"export =\" debe hacer referencia a un valor real cuando \"verbatimModuleSyntax\" está habilitado, pero '{0}' se resuelve en una declaración de solo tipo.", + "An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers__1282": "Una declaración 'export =' debe hacer referencia a un valor cuando 'verbatimModuleSyntax' está habilitado, pero '{0}' solo hace referencia a un tipo.", + "An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_1285": "Una declaración \"export default\" debe hacer referencia a un valor real cuando \"verbatimModuleSyntax\" está habilitado, pero '{0}' se resuelve en una declaración de solo tipo.", + "An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_1284": "Una declaración 'export default' debe hacer referencia a un valor cuando 'verbatimModuleSyntax' está habilitado, pero '{0}' solo hace referencia a un tipo.", + "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345": "No se puede probar la veracidad de una expresión de tipo \"void\".", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Un valor de escape Unicode extendido debe estar entre 0x0 y 0x10FFFF, incluidos.", + "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351": "Un identificador o una palabra clave no puede seguir inmediatamente a un literal numérico.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Una implementación no se puede declarar en contextos de ambiente.", + "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Un alias de importación no puede hacer referencia a una declaración que se exportó mediante \"export type\".", + "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Un alias de importación no puede hacer referencia a una declaración que se importó mediante \"import type\".", + "An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabl_1288": "Un alias de importación no se puede resolver en una declaración de tipo o solo tipo cuando \"verbatimModuleSyntax\" está habilitado.", + "An_import_alias_cannot_use_import_type_1392": "Un alias de importación no puede usar \"import type\"", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473": "Una declaración de importación solo se puede usar en el nivel superior de un módulo.", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232": "Una declaración de importación solo se puede usar en el nivel superior de un espacio de nombres o módulo.", + "An_import_declaration_cannot_have_modifiers_1191": "Una declaración de importación no puede tener modificadores.", + "An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled_5097": "Una ruta de acceso de importación solo puede terminar con una extensión '{0}' cuando \"allowImportingTsExtensions\" está habilitado.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Una signatura de índice no puede tener un parámetro rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Una signatura de índice no puede finalizar con una coma.", + "An_index_signature_must_have_a_type_annotation_1021": "Una signatura de índice debe tener una anotación de tipo.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Una signatura de índice debe tener exactamente un parámetro.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un parámetro de signatura de índice no puede tener un signo de interrogación.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parámetro de signatura de índice no puede tener un modificador de accesibilidad.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parámetro de signatura de índice no puede tener un inicializador.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parámetro de signatura de índice debe tener una anotación de tipo.", + "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Un tipo de parámetro de signatura de índice no puede ser un tipo literal o un tipo genérico. Considere la posibilidad de usar, en su lugar, uno de los tipos de objeto asignados.", + "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "El tipo de parámetro de la signatura de índice debe ser \"string\", \"number\", \"symbol\" o un tipo literal de plantilla.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Una expresión de creación de una instancia no puede ir seguida de un acceso a una propiedad.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Una interfaz solo puede extender un identificador o nombre completo con argumentos de tipo opcional.", + "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Una interfaz solo puede extender un tipo de objeto o una intersección de tipos de objeto con miembros conocidos estáticamente.", + "An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types_2840": "Una interfaz no puede extender un tipo primitivo como '{0}'. Solo puede extender otros tipos de objeto con nombre.", + "An_interface_property_cannot_have_an_initializer_1246": "Una propiedad de interfaz no puede tener un inicializador.", + "An_iterator_must_have_a_next_method_2489": "Un iterador debe tener un método \"next()\".", + "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Se necesita una pragma @jsxFrag cuando se usa una pragma @jsx con fragmentos de JSX.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Un literal de objeto no puede tener varios descriptores de acceso get o set con el mismo nombre.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117": "Un literal de objeto no puede tener varias propiedades con el mismo nombre.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Un literal de objeto no puede tener una propiedad y un descriptor de acceso con el mismo nombre.", + "An_object_member_cannot_be_declared_optional_1162": "Un miembro de objeto no se puede declarar como opcional.", + "An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_han_2861": "El método '[Symbol.hasInstance]' de un objeto debe devolver un valor booleano para que se use en el lado derecho de una expresión \"instanceof\".", + "An_optional_chain_cannot_contain_private_identifiers_18030": "Una cadena opcional no puede contener identificadores privados.", + "An_optional_element_cannot_follow_a_rest_element_1266": "Un elemento opcional no puede seguir a un elemento rest.", + "An_outer_value_of_this_is_shadowed_by_this_container_2738": "Este contenedor reemplaza un valor externo de \"this\".", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Una signatura de sobrecarga no se puede declarar como generador.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "No se admite una expresión unaria con el operador '{0}' en el lado izquierdo de una expresión de exponenciación. Considere la posibilidad de incluir la expresión entre paréntesis.", + "Annotate_everything_with_types_from_JSDoc_95043": "Anotar todo con tipos de JSDoc", + "Annotate_types_of_properties_expando_function_in_a_namespace_90071": "Anotar tipos de propiedades de función expando en un espacio de nombres", + "Annotate_with_type_from_JSDoc_95009": "Anotar con tipo de JSDoc", + "Another_export_default_is_here_2753": "Aquí hay otro valor export default.", + "Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_t_1528": "Cualquier propiedad Unicode que posiblemente coincida con más de un carácter solo está disponible cuando se establece la marca Unicode Sets (v).", + "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518": "Todo lo que posiblemente coincida con más de un carácter no es válido dentro de una clase de caracteres negada.", + "Are_you_missing_a_semicolon_2734": "¿Falta un punto y coma?", + "Argument_expression_expected_1135": "Se esperaba una expresión de argumento.", + "Argument_for_0_option_must_be_Colon_1_6046": "El argumento para la opción \"{0}\" debe ser {1}.", + "Argument_of_dynamic_import_cannot_be_spread_element_1325": "El argumento de importación dinámica no puede ser un elemento de propagación.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "No se puede asignar un argumento de tipo \"{0}\" al parámetro de tipo \"{1}\".", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379": "El argumento de tipo '{0}' no se puede asignar al parámetro de tipo '{1}' con 'exactOptionalPropertyTypes: true'. Considere la posibilidad de agregar \"undefined\" a los tipos de propiedades del destino.", + "Arguments_for_the_rest_parameter_0_were_not_provided_6236": "No se proporcionaron argumentos para el parámetro rest \"{0}\".", + "Array_element_destructuring_pattern_expected_1181": "Se esperaba un patrón de desestructuración de elementos de matriz.", + "Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations_9018": "Las matrices con elementos spread no se pueden inferir con --isolatedDeclarations.", + "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775": "Las aserciones requieren que todos los nombres del destino de llamada se declaren con una anotación de tipo explícito.", + "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776": "Las aserciones requieren que el destino de llamada sea un identificador o un nombre calificado.", + "Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations__9023": "No se admite la asignación de propiedades a funciones sin declararlas con --isolatedDeclarations. Agregue una declaración explícita para las propiedades asignadas a esta función.", + "Asterisk_Slash_expected_1010": "Se esperaba \"*/\".", + "At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9009": "Al menos un descriptor de acceso debe tener una anotación de tipo explícita con --isolatedDeclarations.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Los aumentos del ámbito global solo pueden anidarse directamente en módulos externos o en declaraciones de módulos de ambiente.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Los aumentos del ámbito global deben tener el modificador 'declare', a menos que aparezcan en un contexto de ambiente.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "La detección automática de escritura está habilitada en el proyecto '{0}'. Se va a ejecutar un paso de resolución extra para el módulo '{1}' usando la ubicación de caché '{2}'.", + "BUILD_OPTIONS_6919": "OPCIONES DE COMPILACIÓN", + "Backwards_Compatibility_6253": "Compatibilidad con versiones anteriores", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Las expresiones de clase base no pueden hacer referencia a parámetros de tipo de clase.", + "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509": "El tipo de valor devuelto del constructor base \"{0}\" no es un tipo de objeto ni una intersección de tipos de objeto con miembros conocidos estáticamente.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Todos los constructores base deben tener el mismo tipo de valor devuelto.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Directorio base para resolver nombres de módulos no absolutos.", + "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737": "Los literales BigInt no están disponibles cuando el destino es anterior a ES2020.", + "Binary_digit_expected_1177": "Se esperaba un dígito binario.", + "Binding_element_0_implicitly_has_an_1_type_7031": "El elemento de enlace '{0}' tiene un tipo '{1}' implícito.", + "Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations_9019": "Los elementos de enlace no se pueden exportar directamente con --isolatedDeclarations.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Variable con ámbito de bloque '{0}' usada antes de su declaración.", + "Build_a_composite_project_in_the_working_directory_6925": "Compile un proyecto compuesto en el directorio de trabajo.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636": "Compilar todos los proyectos, incluidos los que aparecen actualizados.", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Generar uno o varios proyectos y sus dependencias, si no están actualizados", + "Build_option_0_requires_a_value_of_type_1_5073": "La opción de compilación \"{0}\" requiere un valor de tipo {1}.", + "Building_project_0_6358": "Compilando el proyecto \"{0}\"...", + "Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any_6720": "Se crea una instancia de los iteradores integrados con un tipo 'TReturn' de 'undefined' en lugar de 'any'.", + "COMMAND_LINE_FLAGS_6921": "MARCAS DE LÍNEA DE COMANDOS", + "COMMON_COMMANDS_6916": "COMANDOS COMUNES", + "COMMON_COMPILER_OPTIONS_6920": "OPCIONES COMUNES DEL COMPILADOR", + "Call_decorator_expression_90028": "Llamar a la expresión decorador", + "Call_signature_return_types_0_and_1_are_incompatible_2202": "Los tipos de valor devuelto de la signatura de llamada \"{0}\" y \"{1}\" son incompatibles.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La signatura de llamada, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto \"any\".", + "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204": "Las signaturas de llamada sin argumentos tienen los tipos de valor devuelto \"{0}\" y \"{1}\" no compatibles.", + "Can_only_convert_logical_AND_access_chains_95142": "Solo pueden convertirse las cadenas lógicas Y de acceso", + "Can_only_convert_named_export_95164": "Solo se pueden convertir exportaciones con nombre.", + "Can_only_convert_property_with_modifier_95137": "Solo se puede convertir la propiedad con el modificador", + "Can_only_convert_string_concatenations_and_string_literals_95154": "Solo se pueden convertir concatenaciones de cadenas y literales de cadena", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "No se puede acceder a \"{0}.{1}\" porque \"{0}\" es un tipo, no un espacio de nombres. ¿Su intención era recuperar el tipo de la propiedad \"{1}\" en \"{0}\" con \"{0}[\"{1}\"]\"?", + "Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead_1281": "No se puede obtener acceso a '{0}' desde otro archivo sin calificación cuando '{1}' está habilitado. Use \"{2}\" en su lugar.", + "Cannot_access_ambient_const_enums_when_0_is_enabled_2748": "No se puede tener acceso a las enumeraciones const de ambiente cuando '{0}' está habilitado.", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "No se puede asignar un tipo de constructor '{0}' a un tipo de constructor '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "No se puede asignar un tipo de constructor abstracto a uno no abstracto.", + "Cannot_assign_to_0_because_it_is_a_class_2629": "No se puede asignar a \"{0}\" porque es una clase.", + "Cannot_assign_to_0_because_it_is_a_constant_2588": "No se puede asignar a \"{0}\" porque es una constante.", + "Cannot_assign_to_0_because_it_is_a_function_2630": "No se puede asignar a \"{0}\" porque es una función.", + "Cannot_assign_to_0_because_it_is_a_namespace_2631": "No se puede asignar a \"{0}\" porque es un espacio de nombres.", + "Cannot_assign_to_0_because_it_is_a_read_only_property_2540": "No se puede asignar a \"{0}\" porque es una propiedad de solo lectura.", + "Cannot_assign_to_0_because_it_is_an_enum_2628": "No se puede asignar a '{0}' porque es una enumeración.", + "Cannot_assign_to_0_because_it_is_an_import_2632": "No se puede asignar a '{0}' porque es una importación.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "No se puede asignar a '{0}' porque no es una variable.", + "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803": "No se puede asignar al método privado \"{0}\". No se puede escribir en los métodos privados.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "No se puede aumentar el módulo '{0}' porque se resuelve como una entidad que no es un módulo.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "No se puede aumentar el módulo \"{0}\" con exportaciones de valores porque se resuelve como una entidad que no es un módulo.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "No se pueden compilar los módulos con la opción '{0}' a no ser que la marca \"--module\" sea \"amd\" o \"system\".", + "Cannot_create_an_instance_of_an_abstract_class_2511": "No se puede crear una instancia de una clase abstracta.", + "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766": "No se puede delegar la iteración en un valor porque el método \"next\" de su iterador espera el tipo \"{1}\", pero el generador que lo contiene siempre enviará \"{0}\".", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "No se puede exportar '{0}'. Solo se pueden exportar declaraciones locales desde un módulo.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "No se puede extender una clase '{0}'. El constructor de la clase está marcado como privado.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "No se puede extender una interfaz '{0}'. ¿Quiso decir 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081": "No se encuentra ningún archivo tsconfig.json en el directorio actual: {0}", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "No se encuentra ningún archivo tsconfig.json en el directorio especificado: \"{0}\".", + "Cannot_find_global_type_0_2318": "No se encuentra el tipo '{0}' global.", + "Cannot_find_global_value_0_2468": "No se encuentra el valor '{0}' global.", + "Cannot_find_lib_definition_for_0_2726": "No se encuentra la definición lib para \"{0}\".", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "No se encuentra la definición lib para \"{0}\". ¿Quiso decir \"{1}\"?", + "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732": "No se encuentra el módulo \"{0}\". Considere la posibilidad de usar \"--resolveJsonModule\" para importar el módulo con la extensión \".json\".", + "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_t_2792": "No se encuentra el módulo “{0}”. ¿Pretendía establecer la opción “moduleResolution” en “nodenext” o agregar alias a la opción “paths”?", + "Cannot_find_module_0_or_its_corresponding_type_declarations_2307": "No se encuentra el módulo \"{0}\" ni sus declaraciones de tipos correspondientes.", + "Cannot_find_name_0_2304": "No se encuentra el nombre '{0}'.", + "Cannot_find_name_0_Did_you_mean_1_2552": "No se encuentra el nombre \"{0}\". ¿Quería decir \"{1}\"?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "No se encuentra el nombre '{0}'. ¿Quería decir el miembro de instancia 'this.{0}'?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "No se encuentra el nombre '{0}'. ¿Quería decir el miembro estático '{1}.{0}'?", + "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311": "No se puede encontrar el nombre \"{0}\". ¿Ha querido escribir esto en una función asincrónica?", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583": "No se encuentra el nombre \"{0}\". ¿Necesita cambiar la biblioteca de destino? Pruebe a cambiar la opción del compilador \"lib\" a \"{1}\" o posterior.", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584": "No se encuentra el nombre \"{0}\". ¿Necesita cambiar la biblioteca de destino? Pruebe a cambiar la opción del compilador \"lib\" para incluir \"dom\".", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2867": "No se encuentra el nombre '{0}'. ¿Necesita instalar definiciones de tipo para Bun? Pruebe `npm i --save-dev @types/bun`.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2868": "No se encuentra el nombre '{0}'. ¿Necesita instalar definiciones de tipo para Bun? Pruebe \"npm i --save-dev @types/bun\" y agregue \"bun\" al campo de tipos de tsconfig.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582": "No se encuentra el nombre \"{0}\". ¿Necesita instalar definiciones de tipo para un ejecutor de pruebas? Pruebe \"npm i --save-dev @types/jest\" o \"npm i --save-dev @types/mocha\".", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593": "No se encuentra el nombre \"{0}\". ¿Necesita instalar definiciones de tipo para un test runner? Pruebe \"npm i --save-dev @types/jest\" o \"npm i --save-dev @types/mocha\" y, a continuación, agregue \"jest\" o \"mocha\" al campo de tipos del archivo tsconfig.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581": "No se encuentra el nombre \"{0}\". ¿Necesita instalar definiciones de tipo para jQuery? Pruebe \"npm i --save-dev @types/jquery\".", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592": "No se encuentra el nombre \"{0}\". ¿Necesita instalar definiciones de tipo para jQuery? Pruebe \"npm i --save-dev @types/jquery\" y, a continuación, agregue \"jquery\" al campo de tipos del archivo tsconfig.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "No se encuentra el nombre \"{0}\". ¿Necesita instalar definiciones de tipo para el nodo? Pruebe \"npm i --save-dev @types/node\".", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "No se encuentra el nombre \"{0}\". ¿Necesita instalar definiciones de tipo para el nodo? Pruebe \"npm i --save-dev @types/node\" y, a continuación, agregue \"node\" al campo de tipos del archivo tsconfig.", + "Cannot_find_namespace_0_2503": "No se encuentra el espacio de nombres '{0}'.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "No se encuentra el espacio de nombres \"{0}\". ¿Quería decir \"{1}\"?", + "Cannot_find_parameter_0_1225": "No se encuentra el parámetro '{0}'.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "No se encuentra la ruta de acceso de subdirectorio común para los archivos de entrada.", + "Cannot_find_type_definition_file_for_0_2688": "No se puede encontrar el archivo de definición de tipo para '{0}'.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "No se pueden importar archivos de declaración de tipos. Considere importar \"{0}\" en lugar de \"{1}\".", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "No se puede inicializar la variable '{0}' de ámbito externo en el mismo ámbito que la declaración '{1}' con ámbito de bloque.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "No se puede invocar un objeto que es posiblemente \"null\".", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "No se puede invocar un objeto que es posiblemente \"null\" o \"no definido\".", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "No se puede invocar un objeto que es posiblemente \"no definido\".", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765": "No se puede iterar el valor porque el método \"next\" de su iterador espera el tipo \"{1}\", pero la desestructuración de matriz siempre enviará \"{0}\".", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "No se puede iterar el valor porque el método \"next\" de su iterador espera el tipo \"{1}\", pero la propagación de matriz siempre enviará \"{0}\".", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "No se puede iterar el valor porque el método \"next\" de su iterador espera el tipo \"{1}\", pero for-of siempre enviará \"{0}\".", + "Cannot_move_statements_to_the_selected_file_95183": "No se pueden mover instrucciones al archivo seleccionado", + "Cannot_move_to_file_selected_file_is_invalid_95179": "No se puede mover al archivo, el archivo seleccionado no es válido", + "Cannot_read_file_0_5083": "No se puede leer el archivo \"{0}\".", + "Cannot_read_file_0_Colon_1_5012": "No se puede leer el archivo \"{0}\": {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "No se puede volver a declarar la variable con ámbito de bloque '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "No se puede volver a declarar la variable '{0}' exportada.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "No se puede volver a declarar el identificador \"{0}\" en la cláusula catch.", + "Cannot_start_a_function_call_in_a_type_annotation_1441": "No se puede iniciar una llamada de función en una anotación de tipo.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "JSX no se puede usar si no se proporciona la marca \"--jsx\".", + "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled_1269": "No se puede usar 'export import' en un tipo o espacio de nombres de solo tipo cuando '{0}' está habilitado.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "No se pueden usar importaciones, exportaciones o aumentos de módulos si el valor de \"--module\" es \"none\".", + "Cannot_use_namespace_0_as_a_type_2709": "No se puede utilizar el espacio de nombres '{0}' como un tipo.", + "Cannot_use_namespace_0_as_a_value_2708": "No se puede utilizar el espacio de nombres '{0}' como un valor.", + "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816": "No se puede usar 'this' en un inicializador de propiedad estática de una clase decorada.", + "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377": "No se puede escribir en el archivo \"{0}\" porque este sobrescribirá el archivo \".tsbuildinfo\" que el proyecto \"{1}\" al que se hace referencia ha generado.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "No se puede escribir en el archivo '{0}' porque se sobrescribiría con varios archivos de entrada.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "No se puede escribir en el archivo '{0}' porque sobrescribiría el archivo de entrada.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "La variable de la cláusula catch no puede tener un inicializador.", + "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196": "La anotación de tipo de variable de la cláusula catch debe ser \"any\" o \"unknown\" si se especifica.", + "Change_0_to_1_90014": "Cambiar \"{0}\" a \"{1}\"", + "Change_all_extended_interfaces_to_implements_95038": "Cambiar todas las interfaces mejoradas a \"implements\"", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Cambiar todos los tipos de jsdoc-style a TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Cambiar todos los tipos de jsdoc-style a TypeScript (y agregar \"| undefined\" a los tipos que aceptan valores NULL)", + "Change_extends_to_implements_90003": "Cambiar \"extends\" a \"implements\"", + "Change_spelling_to_0_90022": "Cambiar la ortografía a \"{0}\"", + "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700": "Compruebe las propiedades de clase declaradas pero no establecidas en el constructor.", + "Check_side_effect_imports_6806": "Compruebe las importaciones de efectos secundarios.", + "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697": "Compruebe que los argumentos de los métodos 'bind', 'call' y 'apply' coinciden con la función original.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Comprobando si '{0}' es el prefijo coincidente más largo para '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Definición circular del alias de importación '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Se detectó circularidad al resolver la configuración: {0}", + "Circularity_originates_in_type_at_this_location_2751": "La circularidad se origina en el tipo de esta ubicación.", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "La clase '{0}' define el descriptor de acceso del miembro de instancia como '{1}', pero la clase extendida '{2}' lo define como función miembro de instancia.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "La clase '{0}' define la función miembro de instancia como '{1}', pero la clase extendida '{2}' la define como descriptor de acceso de miembro de instancia.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La clase '{0}' define la propiedad de miembro de instancia como '{1}', pero la clase extendida '{2}' la define como función miembro de instancia.", + "Class_0_incorrectly_extends_base_class_1_2415": "La clase '{0}' extiende la clase base '{1}' de forma incorrecta.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La clase \"{0}\" no implementa correctamente la clase \"{1}\". ¿Pretendía extender \"{1}\" y heredar sus miembros como una subclase?", + "Class_0_incorrectly_implements_interface_1_2420": "La clase '{0}' implementa la interfaz '{1}' de forma incorrecta.", + "Class_0_used_before_its_declaration_2449": "Se ha usado la clase \"{0}\" antes de declararla.", + "Class_constructor_may_not_be_a_generator_1368": "El constructor de clase no puede ser un generador.", + "Class_constructor_may_not_be_an_accessor_1341": "El constructor de clase no puede ser un descriptor de acceso.", + "Class_declaration_cannot_implement_overload_list_for_0_2813": "La declaración de clase no puede implementar la lista de sobrecarga para '{0}'.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Las declaraciones de clase no pueden tener más de una etiqueta \"@augments\" o \"@extends\".", + "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Los elementos Decorator de una clase no se pueden usar con un identificador privado estático. Pruebe a quitar el elemento Decorator experimental.", + "Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super_2855": "El campo de clase '{0}' definido por la clase primaria no es accesible en la clase secundaria a través de super.", + "Class_name_cannot_be_0_2414": "El nombre de la clase no puede ser \"{0}\".", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "El nombre de clase no puede ser \"Object\" cuando el destino es ES5 con un módulo {0}.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "El lado estático de la clase '{0}' extiende el lado estático de la clase base '{1}' de forma incorrecta.", + "Classes_can_only_extend_a_single_class_1174": "Las clases solo pueden extender una clase única.", + "Classes_may_not_have_a_field_named_constructor_18006": "Las clases no pueden tener un campo denominado \"constructor\".", + "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210": "El código contenido en una clase se calcula en el modo STRICT de JavaScript que no permite este uso de '{0}'. Para obtener más información, consulte https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.", + "Command_line_Options_6171": "Opciones de la línea de comandos", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila el proyecto teniendo en cuenta la ruta de acceso a su archivo de configuración o a una carpeta con un archivo \"tsconfig.json\".", + "Compiler_Diagnostics_6251": "Diagnóstico del compilador", + "Compiler_option_0_cannot_be_given_an_empty_string_18051": "No se puede proporcionar una cadena vacía a la opción del compilador '{0}'.", + "Compiler_option_0_expects_an_argument_6044": "La opción '{0}' del compilador espera un argumento.", + "Compiler_option_0_may_not_be_used_with_build_5094": "La opción \"--{0}\" del compilador no se puede usar con \"--build\".", + "Compiler_option_0_may_only_be_used_with_build_5093": "La opción \"--{0}\" del compilador solo se puede usar con \"--build\".", + "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124": "La opción del compilador \"{0}\" del valor \"{1}\" es inestable. Use TypeScript nocturno para silenciar este error. Intente actualizar con \"npm install -D typescript@next\".", + "Compiler_option_0_requires_a_value_of_type_1_5024": "La opción '{0}' del compilador requiere un valor de tipo {1}.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "El compilador reserva el nombre \"{0}\" al emitir un identificador privado válido para versiones anteriores.", + "Compiles_the_TypeScript_project_located_at_the_specified_path_6927": "Compila el proyecto TypeScript ubicado en la ruta de acceso especificada.", + "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923": "Compila el proyecto actual (tsconfig.json en el directorio de trabajo).", + "Compiles_the_current_project_with_additional_settings_6929": "Compila el proyecto actual con opciones de configuración adicionales", + "Completeness_6257": "Integridad", + "Composite_projects_may_not_disable_declaration_emit_6304": "Los proyectos compuestos no pueden deshabilitar la emisión de declaración.", + "Composite_projects_may_not_disable_incremental_compilation_6379": "Los proyectos compuestos no pueden deshabilitar la compilación incremental.", + "Computed_from_the_list_of_input_files_6911": "Calculado a partir de la lista de archivos de entrada", + "Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedD_9014": "Las propiedades calculadas deben ser literales de número o cadena, variables o expresiones de puntos con --isolatedDeclarations.", + "Computed_property_names_are_not_allowed_in_enums_1164": "No se permiten nombres de propiedad calculada en las enumeraciones.", + "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038": "Los nombres de propiedad calculada en literales de clase u objeto no se pueden inferir con --isolatedDeclarations.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "No se permiten valores calculados en una enumeración que tiene miembros con valores de cadena.", + "Concatenate_and_emit_output_to_single_file_6001": "Concatenar y emitir la salida en un único archivo.", + "Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports_6410": "Condiciones que se establecerán además de los valores predeterminados específicos de la resolución al resolver las importaciones.", + "Conflicts_are_in_this_file_6201": "Hay conflictos en este archivo.", + "Consider_adding_a_declare_modifier_to_this_class_6506": "Considere agregar un modificador 'declare' a esta clase.", + "Construct_signature_return_types_0_and_1_are_incompatible_2203": "Los tipos de valor devuelto de la signatura de construcción \"{0}\" y \"{1}\" son incompatibles.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "La signatura de construcción, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto \"any\".", + "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205": "Las signaturas de construcción sin argumentos tienen los tipos de valor devuelto \"{0}\" y \"{1}\" no compatibles.", + "Constructor_implementation_is_missing_2390": "Falta la implementación del constructor.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "El constructor de la clase '{0}' es privado y solo es accesible desde la declaración de la clase.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "El constructor de la clase '{0}' está protegido y solo es accesible desde la declaración de la clase.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386": "La notación de tipo de constructor debe incluirse entre paréntesis cuando se use en un tipo de unión.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388": "La notación de tipo de constructor debe incluirse entre paréntesis cuando se use en un tipo de intersección.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Los constructores de las clases derivadas deben contener una llamada a \"super\".", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "El archivo contenedor no se ha especificado y no se puede determinar el directorio raíz. Se omitirá la búsqueda en la carpeta 'node_modules'.", + "Containing_function_is_not_an_arrow_function_95128": "La función contenedora no es una función de flecha", + "Control_what_method_is_used_to_detect_module_format_JS_files_1475": "Controlar qué método se usa para detectar archivos JS con formato de módulo.", + "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352": "La conversión del tipo \"{0}\" al tipo \"{1}\" puede ser un error, porque ninguno de los tipos se superpone suficientemente al otro. Si esto era intencionado, convierta primero la expresión en \"unknown\".", + "Convert_0_to_1_in_0_95003": "Convertir \"{0}\" a \"{1} en \"{0}\"", + "Convert_0_to_mapped_object_type_95055": "Convertir \"{0}\" en el tipo de objeto asignado", + "Convert_all_const_to_let_95102": "Convertir todo \"const\" en \"let\"", + "Convert_all_constructor_functions_to_classes_95045": "Convertir todas las funciones de constructor en clases", + "Convert_all_invalid_characters_to_HTML_entity_code_95101": "Convertir todos los caracteres no válidos al código de entidad HTML", + "Convert_all_re_exported_types_to_type_only_exports_1365": "Convertir todos los tipos reexportados en exportaciones solo de tipo", + "Convert_all_require_to_import_95048": "Convertir todas las repeticiones de \"require\" en \"import\"", + "Convert_all_to_async_functions_95066": "Convertir todo en funciones asincrónicas", + "Convert_all_to_bigint_numeric_literals_95092": "Convertir todo en literales numéricos bigint", + "Convert_all_to_default_imports_95035": "Convertir todo en importaciones predeterminadas", + "Convert_all_type_literals_to_mapped_type_95021": "Convertir todos los literales de tipo en un tipo asignado", + "Convert_all_typedef_to_TypeScript_types_95177": "Convertir typedef en todos los tipos TypeScript.", + "Convert_arrow_function_or_function_expression_95122": "Convertir una función de flecha o una expresión de función", + "Convert_const_to_let_95093": "Convertir \"const\" en \"let\"", + "Convert_default_export_to_named_export_95061": "Convertir una exportación predeterminada en exportación con nombre", + "Convert_function_declaration_0_to_arrow_function_95106": "Convertir la declaración de función \"{0}\" en función de flecha", + "Convert_function_expression_0_to_arrow_function_95105": "Convertir la expresión de función \"{0}\" en función de flecha", + "Convert_function_to_an_ES2015_class_95001": "Convertir la función en una clase ES2015", + "Convert_invalid_character_to_its_html_entity_code_95100": "Convertir un carácter no válido a su código de entidad HTML", + "Convert_named_export_to_default_export_95062": "Convertir una exportación con nombre en exportación predeterminada", + "Convert_named_imports_to_default_import_95170": "Convertir importaciones con nombre en importación predeterminada", + "Convert_named_imports_to_namespace_import_95057": "Convertir importaciones con nombre en una importación de espacio de nombres", + "Convert_namespace_import_to_named_imports_95056": "Convertir una importación de espacio de nombres en importaciones con nombre", + "Convert_overload_list_to_single_signature_95118": "Convertir lista de sobrecargas en firma única", + "Convert_parameters_to_destructured_object_95075": "Convertir los parámetros en un objeto desestructurado", + "Convert_require_to_import_95047": "Convertir \"require\" en \"import\"", + "Convert_to_ES_module_95017": "Convertir en módulo ES", + "Convert_to_a_bigint_numeric_literal_95091": "Convertir en un literal numérico bigint", + "Convert_to_anonymous_function_95123": "Convertir en función anónima", + "Convert_to_arrow_function_95125": "Convertir en función de flecha", + "Convert_to_async_function_95065": "Convertir en función asincrónica", + "Convert_to_default_import_95013": "Convertir en importación predeterminada", + "Convert_to_named_function_95124": "Convertir en función con nombre", + "Convert_to_optional_chain_expression_95139": "Convertir en expresión de cadena opcional", + "Convert_to_template_string_95096": "Convertir en cadena de plantilla", + "Convert_to_type_only_export_1364": "Convertir en exportación solo de tipo", + "Convert_typedef_to_TypeScript_type_95176": "Convertir typedef en tipo TypeScript.", + "Corrupted_locale_file_0_6051": "Archivo de configuración regional {0} dañado.", + "Could_not_convert_to_anonymous_function_95153": "No se puede convertir a una función anónima", + "Could_not_convert_to_arrow_function_95151": "No se puede convertir a una función de flecha", + "Could_not_convert_to_named_function_95152": "No se puede convertir a una función con nombre", + "Could_not_determine_function_return_type_95150": "No se puede determinar el tipo de valor devuelto de la función", + "Could_not_find_a_containing_arrow_function_95127": "No se pudo encontrar una función de flecha contenedora", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "No se encontró ningún archivo de declaración para el módulo '{0}'. '{1}' tiene un tipo \"any\" de forma implícita.", + "Could_not_find_convertible_access_expression_95140": "No se encontró la expresión de acceso convertible.", + "Could_not_find_export_statement_95129": "No se pudo encontrar la instrucción export", + "Could_not_find_import_clause_95131": "No se pudo encontrar la cláusula import", + "Could_not_find_matching_access_expressions_95141": "No se encontraron expresiones de acceso coincidentes.", + "Could_not_find_name_0_Did_you_mean_1_2570": "No se ha encontrado el nombre \"{0}\". ¿Quiso decir \"{1}\"?", + "Could_not_find_namespace_import_or_named_imports_95132": "No se pudo encontrar la importación del espacio de nombres ni las importaciones con nombre", + "Could_not_find_property_for_which_to_generate_accessor_95135": "No se pudo encontrar la propiedad para la que se debe generar el descriptor de acceso", + "Could_not_find_variable_to_inline_95185": "No se pudo encontrar la variable para insertar.", + "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "No se pudo resolver la ruta de acceso \"{0}\" con las extensiones: {1}.", + "Could_not_write_file_0_Colon_1_5033": "No se puede escribir en el archivo \"{0}\": \"{1}\".", + "Create_source_map_files_for_emitted_JavaScript_files_6694": "Cree archivos de mapa de origen para los archivos JavaScript emitidos.", + "Create_sourcemaps_for_d_ts_files_6614": "Cree mapas de origen para archivos d.ts.", + "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926": "Crea un archivo tsconfig.json con la configuración recomendada en el directorio de trabajo.", + "DIRECTORY_6038": "DIRECTORIO", + "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537": "No se permiten secuencias de escape decimales ni referencias inversas en una clase de caracteres.", + "Decimals_with_leading_zeros_are_not_allowed_1489": "No se permiten decimales con ceros iniciales.", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "La declaración aumenta una declaración en otro archivo. Esta operación no se puede serializar.", + "Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_support_9026": "La emisión de declaración para este archivo requiere conservar esta importación para aumentos. Esto no se admite con --isolatedDeclarations.", + "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "La emisión de declaración para este archivo requiere el uso del nombre privado \"{0}\". Una anotación de tipo explícito puede desbloquear la emisión de declaración.", + "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "La emisión de declaración para este archivo requiere el uso del nombre privado \"{0}\" del módulo \"{1}\". Una anotación de tipo explícito puede desbloquear la emisión de declaración.", + "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_sup_9025": "La emisión de declaración para este parámetro requiere agregar implícitamente un elemento no definido a su tipo. Esto no se admite con --isolatedDeclarations.", + "Declaration_expected_1146": "Se esperaba una declaración.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Conflictos entre nombres de declaración con el identificador global '{0}' integrado.", + "Declaration_or_statement_expected_1128": "Se esperaba una declaración o una instrucción.", + "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809": "Se esperaba una declaración o una instrucción. El elemento \"=\" sigue a un bloque de instrucciones por lo que, si pretendía escribir una asignación de desestructuración, puede que sea necesario incluir toda la asignación entre paréntesis.", + "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264": "Las declaraciones con aserciones de asignación definitiva deben tener también anotaciones de tipo.", + "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263": "Las declaraciones con inicializadores no pueden tener también aserciones de asignación definitiva.", + "Declare_a_private_field_named_0_90053": "Declare un campo privado denominado \"{0}\".", + "Declare_method_0_90023": "Declarar el método \"{0}\"", + "Declare_private_method_0_90038": "Declarar el método \"{0}\" privado", + "Declare_private_property_0_90035": "Declarar la propiedad \"{0}\" privada", + "Declare_property_0_90016": "Declarar la propiedad \"{0}\"", + "Declare_static_method_0_90024": "Declarar el método estático \"{0}\"", + "Declare_static_property_0_90027": "Declarar la propiedad estática \"{0}\"", + "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270": "El tipo de valor devuelto de la función Decorator \"{0}\" no se puede asignar al tipo \"{1}\".", + "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271": "El tipo de valor devuelto de la función Decorator es \"{0}\" pero se espera que sea \"void\" o \"any\".", + "Decorator_used_before_export_here_1486": "El elemento Decorator se usa antes de \"exportar\" aquí.", + "Decorators_are_not_valid_here_1206": "Los elementos Decorator no son válidos aquí.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "No se pueden aplicar elementos Decorator a varios descriptores de acceso get o set con el mismo nombre.", + "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038": "Los elementos Decorator no pueden aparecer después de \"export\" o \"export default\" si también aparecen antes de \"export\".", + "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436": "Los decoradores deben preceder al nombre y a todas las palabras clave de las declaraciones de propiedad.", + "Default_catch_clause_variables_as_unknown_instead_of_any_6803": "Variables de cláusula catch predeterminadas como \"unknown\" en lugar de \"any\".", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "La exportación predeterminada del módulo tiene o usa el nombre privado '{0}'.", + "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037": "Las exportaciones predeterminadas no se pueden inferir con --isolatedDeclarations.", + "Default_library_1424": "Biblioteca predeterminada", + "Default_library_for_target_0_1425": "Biblioteca predeterminada para el destino \"{0}\"", + "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Las definiciones de los identificadores siguientes entran en conflicto con las de otro archivo: {0}", + "Delete_all_unused_declarations_95024": "Eliminar todas las declaraciones sin usar", + "Delete_all_unused_imports_95147": "Eliminar todas las importaciones sin usar", + "Delete_all_unused_param_tags_95172": "Eliminar todas las etiquetas \"@param\" sin usar", + "Delete_the_outputs_of_all_projects_6365": "Eliminar las salidas de todos los proyectos.", + "Delete_unused_param_tag_0_95171": "Eliminar la etiqueta \"@param\" sin usar \"{0}\"", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[En desuso] Use \"--jsxFactory\" en su lugar. Especifique el objeto invocado para createElement cuando el destino sea la emisión de JSX \"react\"", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[En desuso] Use \"--outFile\" en su lugar. Concatena y emite la salida en un solo archivo.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[En desuso] Use \"--skipLibCheck\" en su lugar. Omite la comprobación de tipos de los archivos de declaración de biblioteca predeterminados.", + "Deprecated_setting_Use_outFile_instead_6677": "Valor en desuso. Use \"outFile\" en su lugar.", + "Did_you_forget_to_use_await_2773": "¿Olvidó usar \"await\"?", + "Did_you_mean_0_1369": "¿Quiso decir \"{0}\"?", + "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735": "¿Quiso decir que \"{0}\" se restrinja al tipo \"new (...args: any[]) => {1}\"?", + "Did_you_mean_to_call_this_expression_6212": "¿Pretendía llamar a esta expresión?", + "Did_you_mean_to_mark_this_function_as_async_1356": "¿Pretendía marcar esta función como \"async\"?", + "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312": "¿Pretendía usar \":\"? El símbolo \"=\" solo puede seguir a un nombre de propiedad cuando el literal de objeto contenedor forma parte de un patrón de desestructuración.", + "Did_you_mean_to_use_new_with_this_expression_6213": "¿Pretendía usar \"new\" con esta expresión?", + "Digit_expected_1124": "Se esperaba un dígito.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "El directorio \"{0}\" no existe, se omitirán todas las búsquedas en él.", + "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270": "El directorio \"{0}\" no tiene ningún ámbito que contenga package.json. Las importaciones no se resolverán.", + "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669": "Deshabilite la adición de directivas \"use strict\" en archivos JavaScript emitidos.", + "Disable_checking_for_this_file_90018": "Deshabilitar la comprobación para este archivo", + "Disable_emitting_comments_6688": "Deshabilite el poder escribir comentarios.", + "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701": "Deshabilite la emisión de declaraciones que tienen \"@internal\" en los comentarios de JSDoc.", + "Disable_emitting_files_from_a_compilation_6660": "Deshabilita la emisión de archivos de una compilación.", + "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662": "Deshabilite la emisión de archivos si se informa algún error de comprobación de tipos.", + "Disable_erasing_const_enum_declarations_in_generated_code_6682": "Deshabilite el borrado de declaraciones \"enumeración const\" en el código generado.", + "Disable_error_reporting_for_unreachable_code_6603": "Deshabilite los informes de errores para los códigos inaccesibles.", + "Disable_error_reporting_for_unused_labels_6604": "Deshabilite los informes de errores para etiquetas sin usar.", + "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805": "Deshabilitar la comprobación completa de tipos (solo se notificarán los errores críticos de análisis y emisión).", + "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661": "Deshabilite la generación de funciones auxiliares personalizadas como \"__extends\" en la salida compilada.", + "Disable_including_any_library_files_including_the_default_lib_d_ts_6670": "Deshabilite la inclusión de cualquier archivo de biblioteca, incluido el archivo predeterminado lib.d.ts.", + "Disable_loading_referenced_projects_6235": "Deshabilite la carga de proyectos a los que se hace referencia.", + "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620": "Deshabilite la preferencia de archivos de código fuente en lugar de archivos de declaración cuando haga referencia a proyectos compuestos.", + "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702": "Deshabilite la creación de informes de errores de exceso de propiedad durante la creación de literales de objetos.", + "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683": "Deshabilite la resolución de symlink a su realpath. Se corresponde con la misma marca en el nodo.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Deshabilitar los límites de tamaño de proyectos de JavaScript.", + "Disable_solution_searching_for_this_project_6224": "Deshabilite la búsqueda de la solución para este proyecto.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6673": "Deshabilite la comprobación estricta de firmas genéricas en tipos de función.", + "Disable_the_type_acquisition_for_JavaScript_projects_6625": "Deshabilitar el tipo de adquisición para proyectos de JavaScript", + "Disable_truncating_types_in_error_messages_6663": "Deshabilite los tipos truncados en los mensajes de error.", + "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221": "Deshabilite el uso de los archivos de código fuente en lugar de los archivos de declaración de los proyectos a los que se hace referencia.", + "Disable_wiping_the_console_in_watch_mode_6684": "Deshabilita la eliminación de la consola en modo inspección.", + "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616": "Deshabilite la inferencia para la adquisición de tipos consultando los nombres de los archivos de un proyecto.", + "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672": "No permita que ningún \"import\", \"require\" o \"\" amplíe el número de archivos que TypeScript debe agregar a un proyecto.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "No permitir referencias al mismo archivo con un uso incoherente de mayúsculas y minúsculas.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "No agregar módulos importados ni referencias con triple barra diagonal a la lista de archivos compilados.", + "Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript_6721": "No permitir construcciones en tiempo de ejecución que no formen parte de ECMAScript.", + "Do_not_emit_comments_to_output_6009": "No emitir comentarios en la salida.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "No emitir declaraciones para el código que tiene una anotación \"@internal\".", + "Do_not_emit_outputs_6010": "No emitir salidas.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "No emitir salidas si se informa de algún error.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "No emitir directivas 'use strict' en la salida del módulo.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "No borrar las declaraciones de enumeración const en el código generado.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones del asistente personalizadas como \"__extends\" en la salida compilada.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "No incluir el archivo de biblioteca predeterminado (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "No notificar los errores del código inaccesible.", + "Do_not_report_errors_on_unused_labels_6074": "No notificar los errores de las etiquetas no usadas.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "No resolver la ruta de acceso real de los vínculos simbólicos.", + "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804": "No transforme ni evite ninguna importación o exportación no marcada como solo de tipo, asegurándose de que se escriben en el formato del archivo de salida en función de la configuración \"module\".", + "Do_not_truncate_error_messages_6165": "No truncar los mensajes de error.", + "Duplicate_function_implementation_2393": "Implementación de función duplicada.", + "Duplicate_identifier_0_2300": "Identificador '{0}' duplicado.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificador '{0}' duplicado. El compilador se reserva el nombre '{1}' en el ámbito de nivel superior de un módulo.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Identificador '{0}' duplicado. El compilador reserva el nombre '{1}' en el ámbito de nivel superior de un módulo que contiene funciones asincrónicas.", + "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818": "Duplicar identificador \"{0}\". El compilador reserva el nombre \"{1}\" al emitir referencias \"super\" en inicializadores estáticos.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificador '{0}' duplicado. El compilador usa la declaración '{1}' para admitir funciones asincrónicas.", + "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804": "El identificador \"{0}\" está duplicado. Los elementos estáticos y de instancia no pueden compartir el mismo nombre privado.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificador \"arguments\" duplicado. El compilador usa \"arguments\" para inicializar parámetros rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Identificador duplicado \"_newTarget\". El compilador usa la declaración de variable \"_newTarget\" para capturar la referencia de la propiedad Meta \"new.target\".", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificador \"_this\" duplicado. El compilador usa la declaración de variable \"_this\" para capturar una referencia \"this\".", + "Duplicate_index_signature_for_type_0_2374": "Signatura de índice duplicada para el tipo \"{0}\".", + "Duplicate_label_0_1114": "Etiqueta \"{0}\" duplicada.", + "Duplicate_property_0_2718": "Propiedad \"{0}\" duplicada.", + "Duplicate_regular_expression_flag_1500": "Marca de expresión regular duplicada.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "El especificador de la importación dinámica debe ser de tipo \"string\", pero aquí tiene el tipo \"{0}\".", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Las importaciones dinámicas solo se admiten cuando la marca \"--módulo\" está establecida en \"es2020\", \"es2022\", \"esnext\", \"commonjs\", \"amd\", \"system\", \"umd\", \"node16\", \"node18\" o \"nodenext\".", + "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments_1450": "Las importaciones dinámicas solo pueden aceptar un especificador de módulo y un set de atributos opcional como argumentos", + "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_1324": "Las importaciones dinámicas solo admiten un segundo argumento cuando la opción \"--module\" está establecida en \"esnext\", \"node16\", \"node18\", \"nodenext\" o \"preserve\".", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve_1293": "No se permite la sintaxis ESM en un módulo CommonJS cuando \"module\" está establecido en \"preserve\".", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled_1286": "No se permite la sintaxis ESM en un módulo CommonJS cuando \"verbatimModuleSyntax\" está habilitado.", + "Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given_4125": "Cada declaración de \"{0}.{1}\" difiere en su valor, donde se esperaba '{2}' pero se proporcionó '{3}'.", + "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Cada miembro del tipo de unión \"{0}\" tiene signaturas de construcción, pero ninguna de ellas es compatible entre sí.", + "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758": "Cada miembro del tipo de unión \"{0}\" tiene signaturas, pero ninguna de ellas es compatible entre sí.", + "Editor_Support_6249": "Compatibilidad con el editor", + "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053": "El elemento tiene un tipo \"any\" de forma implícita porque la expresión de tipo \"{0}\" no se puede usar para indexar el tipo \"{1}\".", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "El elemento tiene un tipo 'any' implícito porque la expresión de índice no es de tipo 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "El elemento tiene un tipo \"any\" implícito porque el tipo '{0}' no tiene signatura de índice.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052": "El elemento tiene un tipo \"any\" implícito porque el tipo \"{0}\" no tiene ninguna signatura de índice. ¿Pretendía llamar a \"{1}\"?", + "Emit_6246": "Emitir", + "Emit_ECMAScript_standard_compliant_class_fields_6712": "Emita campos de clases compatibles con el estándar de ECMAScript.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622": "Emitir una marca BOM UTF-8 al principio de los archivos de salida.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir un solo archivo con mapas de origen en lugar de tener un archivo aparte.", + "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638": "Emita un perfil de CPU v8 de la ejecución del compilador para la depuración.", + "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626": "Emita un JavaScript adicional para facilitar la importación de módulos CommonJS. Esto habilita \"allowSyntheticDefaultImports\" para la compatibilidad de tipos.", + "Emit_class_fields_with_Define_instead_of_Set_6222": "Emita campos de clase con Define en lugar de Set.", + "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624": "Emita metadatos de tipo de diseño para las declaraciones decoradas en los archivos de origen.", + "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621": "Emita un JavaScript más compatible, pero más detallado y de menor rendimiento para la iteración.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir el origen junto a los mapas de origen en un solo archivo; requiere que se establezca \"--inlineSourceMap\" o \"--sourceMap\".", + "Enable_all_strict_type_checking_options_6180": "Habilitar todas las opciones de comprobación de tipos estricta.", + "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685": "Habilite el color y el formato en la salida de TypeScript para facilitar la lectura de los errores del compilador.", + "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611": "Habilite restricciones que permitan usar un proyecto TypeScript con referencias del proyecto.", + "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667": "Habilite el informe de errores para rutas de código que no devuelvan explícitamente una función.", + "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665": "Habilite el informe de errores para expresiones y declaraciones con un tipo \"any\" implícito.", + "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664": "Habilite los informes de errores para los casos de fallthrough en instrucciones switch.", + "Enable_error_reporting_in_type_checked_JavaScript_files_6609": "Habilite el informe de errores en los archivos JavaScript de comprobación de tipos.", + "Enable_error_reporting_when_local_variables_aren_t_read_6675": "Habilite el informe de errores cuando una variable local no se lea.", + "Enable_error_reporting_when_this_is_given_the_type_any_6668": "Habilite el informe de errores cuando a 'this' se le asigna el tipo 'any'.", + "Enable_experimental_support_for_legacy_experimental_decorators_6630": "Habilite la compatibilidad experimental con decoradores experimentales heredados.", + "Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present_6264": "Habilite la importación de archivos con cualquier extensión, siempre que haya un archivo de declaración presente.", + "Enable_importing_json_files_6689": "Habilite la importación de archivos .json.", + "Enable_lib_replacement_6808": "Habilite el reemplazo de bibliotecas.", + "Enable_project_compilation_6302": "Habilitar la compilación de proyecto", + "Enable_strict_bind_call_and_apply_methods_on_functions_6214": "Habilite los métodos estrictos \"bind\", \"call\" y \"apply\" en las funciones.", + "Enable_strict_checking_of_function_types_6186": "Habilite la comprobación estricta de los tipos de función.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite la comprobación estricta de inicialización de propiedades en las clases.", + "Enable_strict_null_checks_6113": "Habilitar comprobaciones estrictas de elementos nulos.", + "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074": "Habilite la opción \"experimentalDecorators\" en el archivo de configuración.", + "Enable_the_jsx_flag_in_your_configuration_file_95088": "Habilite la marca \"--jsx\" en el archivo de configuración.", + "Enable_tracing_of_the_name_resolution_process_6085": "Habilitar seguimiento del proceso de resolución de nombres.", + "Enable_verbose_logging_6713": "Habilitar el registro detallado.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Permite emitir interoperabilidad entre módulos CommonJS y ES mediante la creación de objetos de espacio de nombres para todas las importaciones. Implica \"allowSyntheticDefaultImports\".", + "Enables_experimental_support_for_ES7_decorators_6065": "Habilita la compatibilidad experimental con los elementos Decorator de ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita la compatibilidad experimental para emitir metadatos de tipo para los elementos Decorator.", + "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671": "Exige el uso de descriptores de acceso indexados para las claves declaradas mediante un tipo indexado.", + "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666": "Asegúrese de que al invalidar miembros en clases derivadas, estos están marcados con un modificador de invalidación.", + "Ensure_that_casing_is_correct_in_imports_6637": "Verifique el uso correcto de mayúsculas y minúsculas en las importaciones.", + "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645": "Asegúrese de que cada archivo pueda transpilarse con seguridad sin depender de otras importaciones.", + "Ensure_use_strict_is_always_emitted_6605": "Asegúrese de que siempre se emite \"use strict\".", + "Entering_conditional_exports_6413": "Entrando en exportaciones condicionales.", + "Entry_point_for_implicit_type_library_0_1420": "Punto de entrada para la biblioteca de tipos implícitos \"{0}\"", + "Entry_point_for_implicit_type_library_0_with_packageId_1_1421": "Punto de entrada para la biblioteca de tipos implícitos \"{0}\" con el valor packageId \"{1}\"", + "Entry_point_of_type_library_0_specified_in_compilerOptions_1417": "Punto de entrada de la biblioteca de tipos \"{0}\" que se especifica en compilerOptions", + "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418": "Punto de entrada de la biblioteca de tipos \"{0}\" que se especifica en compilerOptions con el valor packageId \"{1}\"", + "Enum_0_used_before_its_declaration_2450": "Se ha usado la enumeración \"{0}\" antes de declararla.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Las declaraciones de enumeración solo se pueden combinar con otras declaraciones de enumeración o de espacio de nombres.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Todas las declaraciones de enumeración deben ser de tipo const o no const.", + "Enum_member_expected_1132": "Se esperaba un miembro de enumeración.", + "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056": "El miembro de enumeración que sigue a un miembro numérico que no sea literal debe tener un inicializador cuando \"isolatedModules\" está habilitado.", + "Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDecl_9020": "Los inicializadores de miembros de enumeración deben poder calcularse sin referencias a símbolos externos con --isolatedDeclarations.", + "Enum_member_must_have_initializer_1061": "El miembro de enumeración debe tener un inicializador.", + "Enum_name_cannot_be_0_2431": "El nombre de la enumeración no puede ser \"{0}\".", + "Errors_Files_6041": "Archivos de errores", + "Escape_sequence_0_is_not_allowed_1488": "No se permite la secuencia de escape \"{0}\".", + "Examples_Colon_0_6026": "Ejemplos: {0}", + "Excessive_complexity_comparing_types_0_and_1_2859": "Complejidad excesiva al comparar los tipos '{0}' y '{1}'.", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profundidad excesiva de la pila al comparar los tipos '{0}' y '{1}'.", + "Exiting_conditional_exports_6416": "Saliendo de las exportaciones condicionales.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Se esperaban argumentos de tipo {0}-{1}; proporciónelos con una etiqueta \"@extends\".", + "Expected_0_arguments_but_got_1_2554": "Se esperaban {0} argumentos, pero se obtuvieron {1}.", + "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794": "Se esperaban {0} argumentos, pero se obtuvo un total de {1}. ¿Olvidó incluir \"void\" en el argumento de tipo para \"Promise\"?", + "Expected_0_type_arguments_but_got_1_2558": "Se esperaban {0} argumentos de tipo, pero se obtuvieron {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Se esperaban argumentos de tipo {0}; proporciónelos con una etiqueta \"@extends\".", + "Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_2810": "Se esperaba 1 argumento, pero se obtuvo 0. \"new Promise()\" necesita una pista de JSDoc para producir un \"resolve\" que pueda llamarse sin argumentos.", + "Expected_a_Unicode_property_name_1523": "Se esperaba un nombre de propiedad Unicode.", + "Expected_a_Unicode_property_name_or_value_1527": "Se esperaba un valor o un nombre de propiedad Unicode.", + "Expected_a_Unicode_property_value_1525": "Se esperaba un valor de propiedad Unicode.", + "Expected_a_capturing_group_name_1514": "Se esperaba un nombre de grupo de captura.", + "Expected_a_class_set_operand_1520": "Se esperaba un operando de conjunto de clases.", + "Expected_at_least_0_arguments_but_got_1_2555": "Se esperaban al menos {0} argumentos, pero se obtuvieron {1}.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Se esperaba la etiqueta de cierre JSX correspondiente de '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Se esperaba la etiqueta de cierre correspondiente para el fragmento de JSX.", + "Expected_for_property_initializer_1442": "Se esperaba '=' para el inicializador de propiedades.", + "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105": "Se esperaba que el tipo del campo \"{0}\" en \"package.json\" fuese \"{1}\", pero se obtuvo \"{2}\".", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Tipo de resolución de módulo especificado de forma explícita: '{0}'.", + "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "No se puede realizar la exponenciación en los valores \"bigint\", a menos que la opción \"target\" esté establecida en \"es2016\" o posterior.", + "Export_0_from_module_1_90059": "Exportar '{0}' desde el módulo '{1}'", + "Export_all_referenced_locals_90060": "Exportar todas las variables locales a las que se hace referencia", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "No se puede usar una asignación de exportación cuando se eligen módulos de ECMAScript como destino. Considere la posibilidad de usar \"export default\" u otro formato de módulo en su lugar.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "La asignación de exportación no es compatible cuando la marca \"--module\" es \"system\".", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La declaración de exportación está en conflicto con la declaración exportada de \"{0}\".", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "No se permiten declaraciones de exportación en un espacio de nombres.", + "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276": "El especificador de exportación \"{0}\" no existe en el ámbito package.json en la ruta de acceso \"{1}\".", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "El alias de tipo exportado '{0}' tiene o usa el nombre privado '{1}'.", + "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084": "El alias de tipo exportado \"{0}\" tiene o usa el nombre privado \"{1}\" del módulo {2}.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "La variable exportada '{0}' tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "La variable exportada '{0}' tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "La variable exportada '{0}' tiene o usa el nombre privado '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "En aumentos de módulos, no se admiten exportaciones ni asignaciones de exportación.", + "Expression_expected_1109": "Se esperaba una expresión.", + "Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator_1497": "La expresión debe ir entre paréntesis para usarse como un decorador.", + "Expression_or_comma_expected_1137": "Se esperaba una expresión o una coma.", + "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800": "La expresión genera un tipo de tupla demasiado grande para representarlo.", + "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590": "La expresión genera un tipo de unión demasiado complejo para representarlo.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "La expresión se resuelve en el valor \"_super\" que el compilador usa para capturar una referencia a la clase base.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "La expresión se resuelve en una declaración de variable \"_newTarget\" que el compilador usa para capturar la referencia de la propiedad Meta \"new.target\".", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "La expresión se resuelve en la declaración de variable \"_this\" que el compilador usa para capturar una referencia \"this\".", + "Expression_type_can_t_be_inferred_with_isolatedDeclarations_9013": "No se puede inferir el tipo de expresión con --isolatedDeclarations.", + "Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations_9021": "La cláusula Extends no puede contener una expresión con --isolatedDeclarations.", + "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085": "Extiende la cláusula para el tipo deducido '{0}', tiene o usa el nombre privado '{1}'.", + "Extract_base_class_to_variable_90064": "Extraer clase base en variable", + "Extract_binding_expressions_to_variable_90066": "Extraer expresiones de enlace en variable", + "Extract_constant_95006": "Extraer la constante", + "Extract_default_export_to_variable_90065": "Extraer exportación predeterminada a la variable", + "Extract_function_95005": "Extraer la función", + "Extract_to_0_in_1_95004": "Extraer a {0} en {1}", + "Extract_to_0_in_1_scope_95008": "Extraer a {0} en el ámbito {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extraer a {0} en el ámbito de inclusión", + "Extract_to_interface_95090": "Extraer a la interfaz", + "Extract_to_type_alias_95078": "Extraer al alias de tipo", + "Extract_to_typedef_95079": "Extraer a typedef", + "Extract_to_variable_and_replace_with_0_as_typeof_0_90069": "Extraer en variable y reemplazar por “{0} as typeof {0}”", + "Extract_type_95077": "Extraer el tipo", + "FILE_6035": "ARCHIVO", + "FILE_OR_DIRECTORY_6040": "ARCHIVO O DIRECTORIO", + "Failed_to_find_peerDependency_0_6283": "No se ha podido encontrar peerDependency “{0}”.", + "Failed_to_resolve_under_condition_0_6415": "No se pudo resolver en la condición “{0}”.", + "Fallthrough_case_in_switch_7029": "Caso de Fallthrough en instrucción switch.", + "File_0_does_not_exist_6096": "El archivo '{0}' no existe.", + "File_0_does_not_exist_according_to_earlier_cached_lookups_6240": "El archivo \"{0}\" no existe de acuerdo con las búsquedas en caché anteriores.", + "File_0_exists_according_to_earlier_cached_lookups_6239": "El archivo \"{0}\" existe de acuerdo con las búsquedas en caché anteriores.", + "File_0_exists_use_it_as_a_name_resolution_result_6097": "El archivo “{0}” existe. Utilícelo como resultado de resolución de nombres.", + "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054": "El archivo \"{0}\" tiene una extensión no compatible. Las únicas extensiones compatibles son {1}.", + "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504": "\"{0}\" es un archivo JavaScript. ¿Pretendía habilitar la opción \"allowJs\"?", + "File_0_is_not_a_module_2306": "El archivo '{0}' no es un módulo.", + "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307": "El archivo \"{0}\" no está en la lista de archivos del proyecto \"{1}\". Los proyectos deben enumerar todos los archivos o usar un patrón \"include\".", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "El archivo '{0}' no está en \"rootDir\" '{1}'. Se espera que \"rootDir\" contenga todos los archivos de origen.", + "File_0_not_found_6053": "Archivo '{0}' no encontrado.", + "File_Management_6245": "Administración de archivos", + "File_appears_to_be_binary_1490": "Parece que el archivo es binario.", + "File_change_detected_Starting_incremental_compilation_6032": "Se detectó un cambio de archivo. Iniciando la compilación incremental...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "El archivo es un módulo CommonJS porque “{0}” no tiene el campo “type”", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "El archivo es el módulo CommonJS porque “{0}” tiene el campo “type” cuyo valor no es “module”.", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "El archivo es un módulo CommonJS porque no se encontró “package.json”", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "El archivo es un módulo ECMAScript porque “{0}” tiene el campo “type” con el valor “module”", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "El archivo es un módulo CommonJS; se puede convertir en un módulo ES.", + "File_is_default_library_for_target_specified_here_1426": "El archivo es la biblioteca predeterminada para el destino que se especifica aquí.", + "File_is_entry_point_of_type_library_specified_here_1419": "El archivo es el punto de entrada de la biblioteca de tipos que se especifica aquí.", + "File_is_included_via_import_here_1399": "El archivo se incluye aquí a través de la importación.", + "File_is_included_via_library_reference_here_1406": "El archivo se incluye aquí a través de la referencia de la biblioteca.", + "File_is_included_via_reference_here_1401": "El archivo se incluye aquí a través de la referencia.", + "File_is_included_via_type_library_reference_here_1404": "El archivo se incluye aquí a través de la referencia de la biblioteca de tipos.", + "File_is_library_specified_here_1423": "El archivo es la biblioteca que se especifica aquí.", + "File_is_matched_by_files_list_specified_here_1410": "El archivo coincide con la lista de \"archivos\" que se especifica aquí.", + "File_is_matched_by_include_pattern_specified_here_1408": "El archivo coincide con el patrón de inclusión que se especifica aquí.", + "File_is_output_from_referenced_project_specified_here_1413": "El archivo es la salida del proyecto al que se hace referencia especificado aquí.", + "File_is_output_of_project_reference_source_0_1428": "El archivo es la salida del origen de referencia del proyecto \"{0}\".", + "File_is_source_from_referenced_project_specified_here_1416": "El archivo es el origen del proyecto al que se hace referencia especificado aquí.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "El nombre de archivo \"{0}\" es diferente del nombre de archivo \"{1}\" ya incluido solo en el uso de mayúsculas y minúsculas.", + "File_name_0_has_a_1_extension_looking_up_2_instead_6262": "El nombre de archivo “{0}” tiene una extensión de “{1}”. Buscando “{2}” en su lugar.", + "File_name_0_has_a_1_extension_stripping_it_6132": "El nombre de archivo \"{0}\" tiene una extensión \"{1}\" y se va a quitar.", + "File_redirects_to_file_0_1429": "El archivo redirecciona al archivo \"{0}\".", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La especificación del archivo no puede contener un directorio primario ('..') que aparezca después de un comodín de directorios recursivo ('**'): '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "La especificación de archivo no puede finalizar en un comodín de directorio recursivo ('**'): '{0}'.", + "Filters_results_from_the_include_option_6627": "Filtre resultados de la opción \"include\".", + "Fix_all_detected_spelling_errors_95026": "Corregir todos los errores ortográficos detectados", + "Fix_all_expressions_possibly_missing_await_95085": "Corregir todas las expresiones en las que posiblemente falte \"await\"", + "Fix_all_implicit_this_errors_95107": "Corregir todos los errores de \"this\" implícitos", + "Fix_all_incorrect_return_type_of_an_async_functions_90037": "Corregir todos los tipos de valor devuelto incorrectos de las funciones asincrónicas", + "Fix_all_with_type_only_imports_95182": "Corregir todo con importaciones de solo tipo", + "Found_0_errors_6217": "Se encontró {0} errores.", + "Found_0_errors_Watching_for_file_changes_6194": "Se encontraron {0} errores. Supervisando los cambios del archivo.", + "Found_0_errors_in_1_files_6261": "Se han encontrado {0} errores en {1} archivos.", + "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260": "Se han encontrado {0} errores en el mismo archivo, empezando por: {1}", + "Found_1_error_6216": "Se encontró 1 error.", + "Found_1_error_Watching_for_file_changes_6193": "Se encontró un error. Supervisando los cambios del archivo.", + "Found_1_error_in_0_6259": "Se ha encontrado 1 error en {0}", + "Found_package_json_at_0_6099": "Se encontró 'package.json' en '{0}'.", + "Found_peerDependency_0_with_1_version_6282": "Se encontró el “{0}” peerDependency con versión “{1}”.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_1250": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es “ES5”.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definiti_1251": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es “ES5”. Las definiciones de clase están en modo strict de forma automática.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_au_1252": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es “ES5”. Los módulos están en modo strict de forma automática.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "La expresión de función, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto '{0}'.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Falta la implementación de función o no sigue inmediatamente a la declaración.", + "Function_implementation_name_must_be_0_2389": "El nombre de la implementación de función debe ser '{0}'.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La función tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo de valor devuelto y se hace referencia a ella directa o indirectamente en una de sus expresiones return.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción \"return\" final en la función y el tipo de valor devuelto no incluye 'undefined'.", + "Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9007": "La función debe tener una anotación de tipo de valor devuelto explícita con --isolatedDeclarations.", + "Function_not_implemented_95159": "La función no está implementada.", + "Function_overload_must_be_static_2387": "La sobrecarga de función debe ser estática.", + "Function_overload_must_not_be_static_2388": "La sobrecarga de función no debe ser estática.", + "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385": "La notación de tipo de función debe incluirse entre paréntesis cuando se use en un tipo de unión.", + "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387": "La notación de tipo de función debe incluirse entre paréntesis cuando se use en un tipo de intersección.", + "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014": "El tipo de función, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto \"{0}\".", + "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814": "La función con cuerpos solo se puede combinar con clases que son ambientes.", + "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612": "Genere archivos .d.ts desde los archivos TypeScript y JavaScript del proyecto.", + "Generate_get_and_set_accessors_95046": "Generar los descriptores de acceso \"get\" y \"set\"", + "Generate_get_and_set_accessors_for_all_overriding_properties_95119": "Generar los descriptores de acceso \"get\" y \"set\" para todas las propiedades de reemplazo", + "Generates_a_CPU_profile_6223": "Genera un perfil de CPU.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Genera un mapa de origen para cada archivo \".d.ts\" correspondiente.", + "Generates_an_event_trace_and_a_list_of_types_6237": "Genera un seguimiento de eventos y una lista de tipos.", + "Generates_corresponding_d_ts_file_6002": "Genera el archivo \".d.ts\" correspondiente.", + "Generates_corresponding_map_file_6043": "Genera el archivo \".map\" correspondiente.", + "Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation_7025": "El generador tiene implícitamente el tipo de retorno \"{0}\". Considere la posibilidad de proporcionar una anotación de tipo de valor devuelto.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Los generadores no se permiten en un contexto de ambiente.", + "Generic_type_0_requires_1_type_argument_s_2314": "El tipo genérico '{0}' requiere los siguientes argumentos de tipo: {1}.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "El tipo genérico \"{0}\" requiere entre {1} y {2} argumentos de tipo.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Las exportaciones de módulos globales solo pueden aparecer en el nivel superior.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Las exportaciones de módulos globales solo pueden aparecer en archivos de declaración.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Las exportaciones de módulos globales solo pueden aparecer en archivos de módulo.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "El tipo global '{0}' debe ser un tipo de clase o de interfaz.", + "Global_type_0_must_have_1_type_parameter_s_2317": "El tipo global '{0}' debe tener los siguientes parámetros de tipo: {1}.", + "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384": "Al volver a compilar en \"--incremental\" y \"--watch\" se asume que los cambios en un archivo solo afectarán a los archivos que dependan de este directamente.", + "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606": "Hacer que las recompilaciones en los proyectos que utilizan el modo 'incremental' y 'inspección' supongan que los cambios dentro de un archivo sólo afectarán a los archivos que dependen directamente de él.", + "Hexadecimal_digit_expected_1125": "Se esperaba un dígito hexadecimal.", + "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262": "Se esperaba un identificador. \"{0}\" es una palabra reservada en el nivel superior de un módulo.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Se esperaba un identificador. \"{0}\" es una palabra reservada en modo strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Se esperaba un identificador. '{0}' es una palabra reservada en modo strict. Las definiciones de clase están en modo strict automáticamente.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Se esperaba un identificador. '{0}' es una palabra reservada en modo strict. Los módulos están en modo strict automáticamente.", + "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Se esperaba un identificador. \"{0}\" es una palabra reservada que no se puede usar aquí.", + "Identifier_expected_1003": "Se esperaba un identificador.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificador esperado. \"__esModule\" está reservado como marcador exportado al transformar módulos ECMAScript.", + "Identifier_or_string_literal_expected_1478": "Se esperaba un literal de cadena o identificador", + "Identifier_string_literal_or_number_literal_expected_1496": "Se esperaba un identificador, un literal de cadena o un literal de número.", + "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Si el paquete \"{0}\" expone realmente este módulo, considere la posibilidad de enviar una solicitud de incorporación de cambios para corregir \"https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}\".", + "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Si el paquete '{0}' realmente expone este módulo, intente agregar un nuevo archivo de declaración (.d.ts) que contenga 'declarar módulo '{1}';`", + "Ignore_this_error_message_90019": "Ignorar este mensaje de error", + "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924": "Ignora tsconfig.json y se compilan los archivos especificados con las opciones predeterminadas del compilador.", + "Implement_all_inherited_abstract_classes_95040": "Implementar todas las clases abstractas heredadas", + "Implement_all_unimplemented_interfaces_95032": "Implementar todas las interfaces no implementadas", + "Implement_inherited_abstract_class_90007": "Implementar clase abstracta heredada", + "Implement_interface_0_90006": "Implementar la interfaz \"{0}\"", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La cláusula implements de la clase '{0}' exportada tiene o usa el nombre privado '{1}'.", + "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731": "La conversión implícita de un elemento \"symbol\" en \"string\" dará un error en tiempo de ejecución. Considere la posibilidad de encapsular esta expresión en \"String (...)\".", + "Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_w_2866": "La importación “{0}” entra en conflicto con el valor global usado en este archivo, por lo que debe declararse con una importación de solo tipo cuando “isolatedModules” está habilitado.", + "Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_2865": "Importe los conflictos “{0}” con el valor local, por lo que deben declararse con una importación de solo tipo cuando “isolatedModules” está habilitado.", + "Import_0_from_1_90013": "Importar “{0}” desde “{1}”", + "Import_assertion_values_must_be_string_literal_expressions_2837": "Los valores de aserción de importación deben ser expresiones literales de cadena.", + "Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2836": "No se permiten aserciones de importación en instrucciones que se compilan en llamadas “require” de CommonJS.", + "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2821": "Las aserciones de importación solo se admiten cuando la opción \"--module\" está establecida en \"esnext\", \"node18\", \"nodenext\" o \"preserve\".", + "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822": "Las aserciones de importación no se pueden usar con importaciones o exportaciones de solo tipo.", + "Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880": "Las aserciones de importación se han reemplazado por atributos de importación. Use 'with' en lugar de 'assert'.", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "No se puede usar una asignación de importación cuando se eligen módulos de ECMAScript como destino. Considere la posibilidad de usar \"import * as ns from 'mod'\", \"import {a} from 'mod'\", \"import d from 'mod'\" u otro formato de módulo en su lugar.", + "Import_attribute_values_must_be_string_literal_expressions_2858": "Los valores de atributo de importación deben ser expresiones literales de cadena.", + "Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2856": "No se permiten atributos de importación en instrucciones que se compilan en llamadas “require” de CommonJS.", + "Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2823": "Los atributos de importación solo se admiten cuando la opción \"--module\" está establecida en \"esnext\", \"node18\", \"nodenext\" o \"preserve\".", + "Import_attributes_cannot_be_used_with_type_only_imports_or_exports_2857": "Los atributos de importación no se pueden usar con importaciones o exportaciones de solo tipo.", + "Import_declaration_0_is_using_private_name_1_4000": "La declaración de importación '{0}' usa el nombre privado '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La declaración de importación está en conflicto con la declaración local de \"{0}\".", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Las declaraciones de importación de un espacio de nombres no pueden hacer referencia a un módulo.", + "Import_emit_helpers_from_tslib_6139": "Importe asistentes de emisión de \"tslib\".", + "Import_may_be_converted_to_a_default_import_80003": "La importación puede convertirse a una importación predeterminada.", + "Import_name_cannot_be_0_2438": "El nombre de importación no puede ser \"{0}\".", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La declaración de importación o exportación de una declaración de módulo de ambiente no puede hacer referencia al módulo a través de su nombre relativo.", + "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271": "El especificador de importación \"{0}\" no existe en el ámbito package.json en la ruta de acceso \"{1}\".", + "Imported_via_0_from_file_1_1393": "Se importó mediante {0} desde el archivo \"{1}\".", + "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395": "Se importó mediante {0} desde el archivo \"{1}\" para importar \"importHelpers\" tal y como se especifica en compilerOptions.", + "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397": "Se importó mediante {0} desde el archivo \"{1}\" para importar las funciones de fábrica \"jsx\" y \"jsxs\".", + "Imported_via_0_from_file_1_with_packageId_2_1394": "Se importó mediante {0} desde el archivo \"{1}\" con el valor packageId \"{2}\".", + "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396": "Se importó mediante {0} desde el archivo \"{1}\" con el valor packageId \"{2}\" para importar \"importHelpers\" tal y como se especifica en compilerOptions.", + "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398": "Se importó mediante {0} desde el archivo \"{1}\" con el valor packageId \"{2}\" para importar las funciones de fábrica \"jsx\" y \"jsxs\".", + "Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_mod_1543": "La importación de un archivo JSON en un módulo ECMAScript requiere un atributo de importación \"type: \"json\"\" cuando \"module\" se establece en \"{0}\".", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "No se permiten importaciones en aumentos de módulos. Considere la posibilidad de moverlas al módulo externo envolvente.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "En las declaraciones de enumeración de ambiente, el inicializador de miembro debe ser una expresión constante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "En una enumeración con varias declaraciones, solo una declaración puede omitir un inicializador para el primer elemento de la enumeración.", + "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635": "Incluya una lista de archivos. Esto no admite patrones globales, contrario a \"include\".", + "Include_modules_imported_with_json_extension_6197": "Incluir módulos importados con la extensión \".json\"", + "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644": "Incluya el código fuente en los mapas de origen dentro del JavaScript emitido.", + "Include_sourcemap_files_inside_the_emitted_JavaScript_6643": "Incluir archivos de mapas de origen dentro del JavaScript emitido.", + "Includes_imports_of_types_referenced_by_0_90054": "Incluye importaciones de tipos a los que hace referencia \"{0}\"", + "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914": "Al incluir --watch, -w empezará a ver el proyecto actual por los cambios de archivo. Una vez establecido, puede configurar el modo de inspección con:", + "Incomplete_quantifier_Digit_expected_1505": "Cuantificador incompleto. Se esperaba un dígito.", + "Index_signature_for_type_0_is_missing_in_type_1_2329": "Falta la signatura de índice para el tipo \"{0}\" en el tipo \"{1}\".", + "Index_signature_in_type_0_only_permits_reading_2542": "La signatura de índice del tipo '{0}' solo permite lectura.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Las declaraciones individuales de la declaración '{0}' combinada deben ser todas exportadas o todas locales.", + "Infer_all_types_from_usage_95023": "Deducir todos los tipos del uso", + "Infer_function_return_type_95148": "Deducir el tipo de valor devuelto de función", + "Infer_parameter_types_from_usage_95012": "Deducir los tipos de parámetro del uso", + "Infer_this_type_of_0_from_usage_95080": "Inferir el tipo \"this\" de \"{0}\" a partir del uso", + "Infer_type_of_0_from_usage_95011": "Deducir el tipo de \"{0}\" del uso", + "Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations_9022": "La inferencia de expresiones de clase no se admite con --isolatedDeclarations.", + "Initialize_property_0_in_the_constructor_90020": "Inicializar la propiedad \"{0}\" en el constructor", + "Initialize_static_property_0_90021": "Inicializar la propiedad estática \"{0}\"", + "Initializer_for_property_0_2811": "Inicializador para la propiedad \"{0}\"", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "El inicializador de la variable miembro de instancia '{0}' no puede hacer referencia al identificador '{1}' declarado en el constructor.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "No se permiten inicializadores en los contextos de ambiente.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializa un proyecto de TypeScript y crea un archivo tsconfig.json.", + "Inline_variable_95184": "Variable insertada", + "Insert_command_line_options_and_files_from_a_file_6030": "Inserte opciones de la línea de comandos y archivos desde un archivo.", + "Install_0_95014": "Instalar \"{0}\"", + "Install_all_missing_types_packages_95033": "Instalar todos los paquetes de tipos que faltan", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "La interfaz '{0}' no puede extender los tipos '{1}' y '{2}' simultáneamente.", + "Interface_0_incorrectly_extends_interface_1_2430": "La interfaz '{0}' extiende la interfaz '{1}' de forma incorrecta.", + "Interface_declaration_cannot_have_implements_clause_1176": "La declaración de interfaz no puede tener una cláusula \"implements\".", + "Interface_must_be_given_a_name_1438": "Se debe asignar un nombre a la interfaz.", + "Interface_name_cannot_be_0_2427": "El nombre de la interfaz no puede ser \"{0}\".", + "Interop_Constraints_6252": "Restricciones de interoperabilidad", + "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243": "Interprete los tipos de propiedad opcionales como escritos en lugar de agregar \"undefined\".", + "Invalid_character_1127": "Carácter no válido.", + "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "El especificador de importación no válido \"{0}\" no tiene resoluciones posibles.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nombre de módulo no válido en el aumento. El módulo '{0}' se resuelve como un módulo sin tipo en '{1}', que no se puede aumentar.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nombre de módulo no válido en un aumento, no se encuentra el módulo '{0}'.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Cadena opcional no válida de la nueva expresión. ¿Quería llamar a \"{0}()\"?", + "Invalid_reference_directive_syntax_1084": "Sintaxis de la directiva \"reference\" no válida.", + "Invalid_syntax_in_decorator_1498": "Sintaxis no válida en Decorator.", + "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Uso no válido de '{0}'. No se puede usar dentro de un bloque estático de clase.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso de '{0}' no válido. Los módulos están en modo strict automáticamente.", + "Invalid_use_of_0_in_strict_mode_1100": "Uso no válido de '{0}' en modo strict.", + "Invalid_value_for_ignoreDeprecations_5103": "Valor no válido para “--ignoreDeprecations”.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valor no válido para \"jsxFactory\". \"{0}\" no es un nombre calificado o un identificador válido.", + "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035": "Valor no válido para \"jsxFactory\". \"{0}\" no es un nombre cualificado o un identificador válidos.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valor no válido para '--reactNamespace'. '{0}' no es un identificador válido.", + "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796": "Es probable que falte una coma para separar estas dos expresiones de plantilla. Forman una expresión de plantilla con etiquetas que no se puede invocar.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "El tipo de elemento \"{0}\" no es un elemento JSX válido.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "El tipo de instancia \"{0}\" no es un elemento JSX válido.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "El tipo de valor devuelto \"{0}\" no es un elemento JSX válido.", + "Its_type_0_is_not_a_valid_JSX_element_type_18053": "El tipo “{0}” no es un tipo de elemento JSX válido.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La etiqueta \"@{0} {1}\" de JSDoc no coincide con la cláusula \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "La etiqueta \"@{0}\" de JSDoc no está asociada a una clase.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "\"...\" de JSDoc solo puede aparecer en el último parámetro de una signatura.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "La etiqueta \"@param\" de JSDoc tiene el nombre \"{0}\", pero no hay ningún parámetro con ese nombre.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "La etiqueta de JSDoc \"@param\" tiene el nombre \"{0}\", pero no hay ningún parámetro con ese nombre. Coincidiría con \"arguments\" si tuviera un tipo de matriz.", + "JSDoc_typedef_may_be_converted_to_TypeScript_type_80009": "El typedef de JSDoc se puede convertir al tipo TypeScript.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La etiqueta \"@typedef\" de JSDoc debe tener una anotación de tipo o ir seguida de las etiquetas \"@property\" o \"@member\".", + "JSDoc_typedefs_may_be_converted_to_TypeScript_types_80010": "Las definiciones de tipos JSDoc se pueden convertir en tipos TypeScript.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Los tipos JSDoc solo se pueden usar en los comentarios de la documentación.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Los tipos de JSDoc pueden moverse a tipos de TypeScript.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "A los atributos JSX se les debe asignar únicamente un elemento \"expression\" que no esté vacío.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "El elemento JSX '{0}' no tiene la etiqueta de cierre correspondiente.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La clase de elemento JSX no admite atributos porque no tiene una propiedad \"{0}\".", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "El elemento JSX tiene el tipo \"any\" implícitamente porque no existe ninguna interfaz \"JSX.{0}\".", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "El elemento JSX tiene el tipo \"any\" implícitamente porque no existe el tipo global \"JSX.Element\".", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "El tipo de elemento JSX '{0}' no tiene ninguna signatura de construcción ni de llamada.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Los elementos JSX no pueden tener varios atributos con el mismo nombre.", + "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007": "Las expresiones JSX no pueden usar el operador de coma. ¿Pretendía escribir una matriz?", + "JSX_expressions_must_have_one_parent_element_2657": "Las expresiones JSX deben tener un elemento primario.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "El fragmento de JSX no tiene la etiqueta de cierre correspondiente.", + "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633": "Las expresiones de acceso a la propiedad JSX no pueden incluir nombres de espacios de nombres JSX", + "JSX_spread_child_must_be_an_array_type_2609": "El elemento secundario de propagación JSX debe ser de tipo matriz.", + "JavaScript_Support_6247": "Compatibilidad con JavaScript", + "Jump_target_cannot_cross_function_boundary_1107": "Un destino de salto no puede atravesar el límite de función.", + "KIND_6034": "TIPO", + "Keywords_cannot_contain_escape_characters_1260": "Las palabras clave no pueden contener caracteres de escape.", + "LOCATION_6037": "UBICACIÓN", + "Language_and_Environment_6254": "Lenguaje y ambiente", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "La parte izquierda del operador de coma no se usa y no tiene efectos secundarios.", + "Library_0_specified_in_compilerOptions_1422": "La biblioteca \"{0}\" se especifica en compilerOptions", + "Library_referenced_via_0_from_file_1_1405": "Biblioteca a la que se hace referencia mediante \"{0}\" desde el archivo \"{1}\"", + "Line_break_not_permitted_here_1142": "No se permite el salto de línea aquí.", + "Line_terminator_not_permitted_before_arrow_1200": "No se permite usar un terminador de línea antes de una flecha.", + "List_of_file_name_suffixes_to_search_when_resolving_a_module_6931": "Lista de sufijos de nombre de archivo para buscar al resolver un módulo.", + "List_of_folders_to_include_type_definitions_from_6161": "Lista de carpetas de donde se deben incluir las definiciones de tipos.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Lista de carpetas raíz cuyo contenido combinado representa la estructura del proyecto en tiempo de ejecución.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Cargando \"{0}\" del directorio raíz \"{1}\", ubicación candidata: \"{2}\"", + "Loading_module_0_from_node_modules_folder_target_file_types_Colon_1_6098": "Se cargará el módulo “{0}” de la carpeta “node_modules”, tipos de archivo de destino “{1}”.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1_6095": "Se cargará el módulo como archivo/carpeta, ubicación del módulo candidato “{0}”, tipos de archivo de destino “{1}”.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "La configuración regional debe tener el formato o -. Por ejemplo, '{0}' o '{1}'.", + "Log_paths_used_during_the_moduleResolution_process_6706": "Rutas de acceso de registro usadas durante el proceso \"moduleResolution\".", + "Longest_matching_prefix_for_0_is_1_6108": "El prefijo coincidente más largo para \"{0}\" es \"{1}\".", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Buscando en la carpeta \"node_modules\", ubicación inicial: \"{0}\".", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Convertir todas las llamadas a \"super()\" en la primera instrucción de su constructor", + "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Haga que keyof solo devuelva cadenas en lugar de cadenas, números o símbolos. Opción heredada.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Hacer que la llamada a \"super()\" sea la primera instrucción del constructor", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "El tipo de objeto asignado tiene implícitamente un tipo de plantilla \"any\".", + "Mark_array_literal_as_const_90070": "Marcar literal de matriz como const", + "Matched_0_condition_1_6403": "Coincidente con '{0}' condición '{1}'.", + "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "La coincidencia de forma predeterminada incluye el patrón '**/*'", + "Matched_by_include_pattern_0_in_1_1407": "Coincidencia con el patrón de inclusión \"{0}\" en \"{1}\"", + "Member_0_implicitly_has_an_1_type_7008": "El miembro '{0}' tiene un tipo '{1}' implícitamente.", + "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "El miembro \"{0}\" tiene un tipo \"{1}\" de forma implícita, pero se puede inferir un tipo más adecuado a partir del uso.", + "Merge_conflict_marker_encountered_1185": "Se encontró un marcador de conflicto de combinación.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La declaración combinada '{0}' no puede incluir una declaración de exportación predeterminada. Considere la posibilidad de agregar una declaración \"export default {0}\" independiente en su lugar.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "La propiedad Meta \"{0}\" solo se permite en el cuerpo de una declaración de función, una expresión de función o un constructor.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "El método '{0}' no puede tener ninguna implementación porque está marcado como abstracto.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "El método \"{0}\" de la interfaz exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "El método \"{0}\" de la interfaz exportada tiene o usa el nombre privado \"{1}\".", + "Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9008": "El método debe tener una anotación de tipo de valor devuelto explícita con --isolatedDeclarations.", + "Method_not_implemented_95158": "El método no está implementado.", + "Modifiers_cannot_appear_here_1184": "Los modificadores no pueden aparecer aquí.", + "Module_0_can_only_be_default_imported_using_the_1_flag_1259": "El módulo \"{0}\" solo puede importarse de forma predeterminada con la marca \"{1}\".", + "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471": "El módulo \"{0}\" no se puede importar con esta construcción. El especificador solo se resuelve en un módulo ES, que no se puede importar con \"require\". En su lugar, use una importación de ECMAScript.", + "Module_0_declares_1_locally_but_it_is_exported_as_2_2460": "El módulo \"{0}\" declara \"{1}\" localmente, pero se exporta como \"{2}\".", + "Module_0_declares_1_locally_but_it_is_not_exported_2459": "El módulo \"{0}\" declara \"{1}\" localmente, pero no se exporta.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340": "El módulo \"{0}\" no hace referencia a un tipo, pero aquí se usa como tipo. ¿Quiso decir \"typeof import('{0}')\"?", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "El módulo \"{0}\" no hace referencia a un valor, pero aquí se usa como valor.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "El módulo {0} ya ha exportado un miembro denominado '{1}'. Considere la posibilidad de volver a exportarlo de forma explícita para resolver la ambigüedad.", + "Module_0_has_no_default_export_1192": "El módulo '{0}' no tiene ninguna exportación predeterminada.", + "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613": "El módulo \"{0}\" no tiene ninguna exportación predeterminada. ¿Pretendía usar \"import { {1} } from {0}\" en su lugar?", + "Module_0_has_no_exported_member_1_2305": "El módulo '{0}' no tiene ningún miembro '{1}' exportado.", + "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614": "El módulo \"{0}\" no tiene ningún miembro \"{1}\" exportado. ¿Pretendía usar \"import {1} from {0}\" en su lugar?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "El módulo \"{0}\" está oculto por una declaración local con el mismo nombre.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "El módulo '{0}' usa \"export =\" y no se puede usar con \"export *\".", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "El módulo '{0}' se resolvió como un módulo de ambiente declarado localmente en el archivo '{1}'.", + "Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set_6263": "El módulo “{0}” se ha resuelto en “{1}”, pero “--allowArbitraryExtensions” no está establecido.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "El módulo '{0}' se resolvió en '{1}', pero \"--jsx\" no está establecido.", + "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042": "El módulo \"{0}\" se resolvió en \"{1}\", pero no se usa \"--resolveJsonModule\".", + "Module_declaration_names_may_only_use_or_quoted_strings_1443": "Los nombres de declaración de módulo solo pueden usar cadenas con las comillas \" o '.", + "Module_name_0_matched_pattern_1_6092": "Nombre del módulo: '{0}', patrón coincidente: '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== No se resolvió el nombre de módulo '{0}'. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== El nombre del módulo '{0}' se resolvió correctamente como '{1}'. ========", + "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218": "======== El nombre del módulo '{0}' se resolvió correctamente como \"{1}\" con el identificador de paquete \"{2}\". ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "No se ha especificado el tipo de resolución del módulo, se usará '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "No se pudo resolver el módulo con \"rootDirs\".", + "Modules_6244": "Módulos", + "Move_labeled_tuple_element_modifiers_to_labels_95117": "Mover modificadores de elemento de tupla etiquetados a etiquetas", + "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036": "Mueva la expresión de exportación predeterminada a una variable y agréguele una anotación de tipo.", + "Move_to_a_new_file_95049": "Mover a un nuevo archivo", + "Move_to_file_95178": "Mover a archivo", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "No se permiten varios separadores numéricos consecutivos.", + "Multiple_constructor_implementations_are_not_allowed_2392": "No se permiten varias implementaciones del constructor.", + "NEWLINE_6061": "NUEVA LÍNEA", + "Name_is_not_valid_95136": "El nombre no es válido", + "Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later_1503": "Los grupos de captura con nombre solo están disponibles cuando el destino es “ES2018” o posterior.", + "Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other_1515": "Los grupos de captura con nombre que tengan el mismo nombre deben ser mutuamente excluyentes entre sí.", + "Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0_1544": "No se permiten las importaciones con nombre de un archivo JSON en un módulo ECMAScript cuando \"module\" está establecido en \"{0}\".", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "La propiedad '{0}' con nombre de los tipos '{1}' y '{2}' no es idéntica en ambos.", + "Namespace_0_has_no_exported_member_1_2694": "El espacio de nombres '{0}' no tiene ningún miembro '{1}' exportado.", + "Namespace_must_be_given_a_name_1437": "Se debe asignar un nombre al espacio de nombres.", + "Namespace_name_cannot_be_0_2819": "El nombre de espacio no puede ser \"{0}\".", + "Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to__1280": "No se permiten espacios de nombres en archivos de script globales cuando “{0}” está habilitado. Si este archivo no está pensado para ser un script global, establezca “moduleDetection” en “force” o agregue una instrucción “export {}” vacía.", + "Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters_1433": "No se pueden aplicar modificadores ni decoradores a los parámetros “this”.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "No hay ningún constructor base con el número especificado de argumentos de tipo.", + "No_constituent_of_type_0_is_callable_2755": "No se puede llamar a ningún constituyente del tipo \"{0}\".", + "No_constituent_of_type_0_is_constructable_2759": "No se puede construir ningún constituyente del tipo \"{0}\".", + "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054": "No se encontró ninguna signatura de índice con un parámetro de tipo \"{0}\" en el tipo \"{1}\".", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "No se encontraron entradas en el archivo de configuración '{0}'. Las rutas 'include' especificadas fueron '{1}' y las rutas 'exclude' fueron '{2}'.", + "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608": "Ya no se admite. En versiones anteriores, establezca manualmente la codificación de texto para leer archivos.", + "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575": "Ninguna sobrecarga espera argumentos {0}, pero existen sobrecargas que esperan argumentos {1} o {2}.", + "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743": "Ninguna sobrecarga espera argumentos de tipo {0}, pero existen sobrecargas que esperan argumentos de tipo {1} o {2}.", + "No_overload_matches_this_call_2769": "Ninguna sobrecarga coincide con esta llamada.", + "No_type_could_be_extracted_from_this_type_node_95134": "No se pudo extraer ningún tipo de este nodo de tipo", + "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004": "No existe ningún valor en el ámbito para la propiedad abreviada \"{0}\". Declare uno o proporcione un inicializador.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La clase '{0}' no abstracta no implementa el miembro abstracto heredado '{1}' de la clase '{2}'.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_2654": "Faltan implementaciones para los siguientes miembros de “{0}” en la clase no abstracta: “{1}”: {2}.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more_2655": "Faltan implementaciones para los siguientes miembros de “{0}” en la clase no abstracta: “{1}”: {2} y {3} más.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Una expresión de clase no abstracta no implementa el miembro abstracto heredado '{0}' de la clase '{1}'.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_2656": "Faltan implementaciones para los siguientes miembros de “{0}” en la expresión de clase no abstracta: {1}.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and__2650": "Faltan implementaciones para los siguientes miembros de “{0}” en la expresión de clase no abstracta: {1} y {2} más.", + "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013": "Las aserciones no nulas solo se pueden usar en los archivos TypeScript.", + "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090": "No se permiten rutas de acceso no relativas si no se ha establecido \"baseUrl\". ¿Ha olvidado poner \"./\" al inicio?", + "Non_simple_parameter_declared_here_1348": "Se ha declarado un parámetro no simple aquí.", + "Not_all_code_paths_return_a_value_7030": "No todas las rutas de acceso de código devuelven un valor.", + "Not_all_constituents_of_type_0_are_callable_2756": "No se puede llamar a todos los constituyentes del tipo \"{0}\".", + "Not_all_constituents_of_type_0_are_constructable_2760": "No se pueden construir todos los constituyentes del tipo \"{0}\".", + "Numbers_out_of_order_in_quantifier_1506": "Números desordenado en el cuantificador.", + "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008": "Los literales numéricos con valores absolutos iguales a 2^53 o superiores son demasiado grandes para representarlos de forma precisa como enteros.", + "Numeric_separators_are_not_allowed_here_6188": "Aquí no se permiten separadores numéricos.", + "Object_is_of_type_unknown_2571": "El objeto es de tipo \"desconocido\".", + "Object_is_possibly_null_2531": "El objeto es posiblemente \"null\".", + "Object_is_possibly_null_or_undefined_2533": "El objeto es posiblemente \"null\" o \"undefined\".", + "Object_is_possibly_undefined_2532": "El objeto es posiblemente \"undefined\".", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "El literal de objeto solo puede especificar propiedades conocidas y '{0}' no existe en el tipo '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "El literal de objeto solo puede especificar propiedades conocidas, pero \"{0}\" no existe en el tipo \"{1}\". ¿Quería escribir \"{2}\"?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La propiedad '{0}' del literal de objeto tiene un tipo '{1}' implícitamente.", + "Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations_9016": "Los objetos que contienen propiedades abreviadas no se pueden inferir con --isolatedDeclarations.", + "Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations_9015": "Los objetos que contienen asignaciones de propagación no se pueden inferir con --isolatedDeclarations.", + "Octal_digit_expected_1178": "Se esperaba un dígito octal.", + "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536": "No se permiten secuencias de escape decimales ni referencias inversas en una clase de caracteres. Si la intención era una secuencia de escape, use la sintaxis “{0}” en su lugar.", + "Octal_escape_sequences_are_not_allowed_Use_the_syntax_0_1487": "No se permiten secuencias de escape octal. Use la sintaxis “{0}”.", + "Octal_literals_are_not_allowed_Use_the_syntax_0_1121": "No se permiten literales octal. Use la sintaxis “{0}”.", + "One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value_4126": "Un valor de “{0}.{1}” es la cadena “{2}” y se supone que el otro es un valor numérico desconocido.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "Solo se permite una declaración de variable en una instrucción \"for...in\".", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "Solo se permite una declaración de variable en una instrucción \"for...of\".", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Solo se puede llamar a una función void con la palabra clave \"new\".", + "Only_ambient_modules_can_use_quoted_names_1035": "Solo los módulos de ambiente pueden usar nombres entrecomillados.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Solo los módulos \"amd\" y \"system\" se admiten con --{0}.", + "Only_const_arrays_can_be_inferred_with_isolatedDeclarations_9017": "Solo se pueden inferir matrices const con --isolatedDeclarations.", + "Only_emit_d_ts_declaration_files_6014": "Solo deben emitirse archivos de declaración \".d.ts\".", + "Only_output_d_ts_files_and_not_JavaScript_files_6623": "Genere solo archivos d.ts y no archivos JavaScript.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Solo es posible tener acceso a los métodos públicos y protegidos de la clase base mediante la palabra clave \"super\".", + "Operator_0_cannot_be_applied_to_type_1_2736": "El operador \"{0}\" no se puede aplicar al tipo \"{1}\".", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "El operador '{0}' no se puede aplicar a los tipos '{1}' y '{2}'.", + "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519": "Los operadores no deben mezclarse dentro de una clase de caracteres. Envuelve en una clase anidada en su lugar.", + "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619": "Opte por excluir un proyecto de la comprobación de referencias de varios proyectos al editar.", + "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108": "Se ha quitado la opción “{0}={1}”. Elimínela de la configuración.", + "Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDepr_5107": "La opción “{0}={1}” está en desuso y dejará de funcionar en TypeScript {2}. Especifique compilerOption “'ignoreDeprecations': '{3}'” para silenciar este error.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "La opción \"{0}\" solo puede especificarse en el archivo \"tsconfig.json\" o establecerse en \"false\" o \"null\" en la línea de comandos.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "La opción \"{0}\" solo puede especificarse en el archivo \"tsconfig.json\" o establecerse en \"null\" en la línea de comandos.", + "Option_0_can_only_be_specified_on_command_line_6266": "La opción “{0}” solo se puede especificar en la línea de comandos.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "La opción '{0}' solo se puede usar cuando se proporciona '--inlineSourceMap' o '--sourceMap'.", + "Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler_5098": "La opción “{0}” solo se puede usar cuando “moduleResolution” está establecido en “node16”, “nodenext” o “bundler”.", + "Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later_5095": "La opción “{0}” solo se puede usar cuando “module” está establecido en “preserve” o en “es2015” o posterior.", + "Option_0_cannot_be_specified_when_option_jsx_is_1_5089": "No se puede especificar la opción \"{0}\" cuando la opción \"jsx\" es \"{1}\".", + "Option_0_cannot_be_specified_with_option_1_5053": "La opción '{0}' no se puede especificar con la opción '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "La opción '{0}' no se puede especificar sin la opción '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "La opción \"{0}\" no se puede especificar sin la opción \"{1}\" o la opción \"{2}\".", + "Option_0_has_been_removed_Please_remove_it_from_your_configuration_5102": "Se ha quitado la opción “{0}”. Elimínela de la configuración.", + "Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprec_5101": "La opción “{0}” está en desuso y dejará de funcionar en TypeScript {1}. Especifique compilerOption “'ignoreDeprecations': '{2}'” para silenciar este error.", + "Option_0_is_redundant_and_cannot_be_specified_with_option_1_5104": "La opción “{0}” es redundante y no se puede especificar con la opción “{1}”.", + "Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set_5096": "La opción “allowImportingTsExtensions” solo se puede usar cuando se establece “noEmit” o “emitDeclarationOnly”.", + "Option_build_must_be_the_first_command_line_argument_6369": "La opción \"--build\" debe ser el primer argumento de la línea de comandos.", + "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074": "La opción \"--incremental\" solo puede especificarse si se usa tsconfig, se emite en un solo archivo o se especifica la opción \"--tsBuildInfoFile\".", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "La opción \"isolatedModules\" solo se puede usar cuando se proporciona la opción \"--module\" o si la opción \"target\" es \"ES2015\" o una versión posterior.", + "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109": "La opción “moduleResolution” debe establecerse en “{0}” (o no se especificó) cuando la opción “module” está establecida en “{1}”.", + "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110": "La opción “module” debe establecerse en “{0}” cuando la opción “moduleResolution” esté establecida en “{1}”.", + "Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled_5091": "La opción “preserveConstEnums” no se puede deshabilitar cuando “{0}” está habilitado.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "La opción \"project\" no se puede combinar con archivos de origen en una línea de comandos.", + "Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic_5070": "No se puede especificar la opción “--resolveJsonModule” cuando “moduleResolution” está establecido en “classic”.", + "Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd_5071": "No se puede especificar la opción “--resolveJsonModule” cuando “module” esté establecido en “none”, “system” o “umd”.", + "Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System_5105": "La opción “verbatimModuleSyntax” no se puede usar cuando “module” está establecido en “UMD”, “AMD” o “System”.", + "Options_0_and_1_cannot_be_combined_6370": "\"{0}\" y \"{1}\" no se pueden combinar.", + "Options_Colon_6027": "Opciones:", + "Output_Formatting_6256": "Formato de salida", + "Output_compiler_performance_information_after_building_6615": "Información de rendimiento resultante del compilador después de la compilación.", + "Output_directory_for_generated_declaration_files_6166": "Directorio de salida para los archivos de declaración generados.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "El archivo de salida \"{0}\" no se compiló desde el archivo de origen \"{1}\".", + "Output_from_referenced_project_0_included_because_1_specified_1411": "La salida del proyecto \"{0}\" al que se hace referencia se ha incluido porque se ha especificado \"{1}\".", + "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412": "La salida del proyecto \"{0}\" al que se hace referencia se ha incluido porque \"--module\" se ha especificado como \"none\".", + "Output_more_detailed_compiler_performance_information_after_building_6632": "Produzca información más detallada del rendimiento resultante del compilador después de la compilación.", + "Overload_0_of_1_2_gave_the_following_error_2772": "La sobrecarga {0} de {1}, \"{2}\", dio el error siguiente.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Las signaturas de sobrecarga deben ser todas abstractas o no abstractas.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Las signaturas de sobrecarga deben ser todas de ambiente o de no ambiente.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Las signaturas de sobrecarga deben ser todas exportadas o no exportadas.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Las signaturas de sobrecarga deben ser todas opcionales u obligatorias.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Las signaturas de sobrecarga deben ser todas públicas, privadas o protegidas.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "El parámetro \"{0}\" no puede hacer referencia al identificador \"{1}\" declarado después de este.", + "Parameter_0_cannot_reference_itself_2372": "El parámetro \"{0}\" no puede hacer referencia a sí mismo.", + "Parameter_0_implicitly_has_an_1_type_7006": "El parámetro '{0}' tiene un tipo '{1}' implícitamente.", + "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "El parámetro \"{0}\" tiene un tipo \"{1}\" de forma implícita, pero se puede inferir un tipo más adecuado a partir del uso.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "El parámetro '{0}' no está en la misma posición que el parámetro '{1}'.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108": "El parámetro \"{0}\" del descriptor de acceso tiene o usa el nombre \"{1}\" del módulo \"{2}\" externo, pero no se puede nombrar.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107": "El parámetro \"{0}\" del descriptor de acceso tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106": "El parámetro \"{0}\" del descriptor de acceso tiene o usa el nombre privado \"{1}\".", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "El parámetro '{0}' de la signatura de llamada de una interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "El parámetro '{0}' de la signatura de llamada de una interfaz exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "El parámetro '{0}' del constructor de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "El parámetro '{0}' del constructor de la clase exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "El parámetro '{0}' del constructor de la clase exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "El parámetro '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "El parámetro '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "El parámetro '{0}' de la función exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "El parámetro '{0}' de la función exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "El parámetro '{0}' de la función exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "El parámetro \"{0}\" de la signatura de índice de la interfaz exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "El parámetro \"{0}\" de la signatura de índice de la interfaz exportada tiene o usa el nombre privado \"{1}\".", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "El parámetro '{0}' del método de la interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "El parámetro '{0}' del método de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "El parámetro '{0}' del método público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "El parámetro '{0}' del método público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "El parámetro '{0}' del método público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "El parámetro '{0}' del método estático público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "El parámetro '{0}' del método estático público de la clase exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "El parámetro '{0}' del método estático público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "El parámetro no puede tener un signo de interrogación y un inicializador.", + "Parameter_declaration_expected_1138": "Se espera una declaración de parámetros.", + "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051": "El parámetro tiene un nombre, pero no un tipo. ¿Pretendía usar \"{0}: {1}\"?", + "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012": "Los modificadores de parámetro solo se pueden usar en los archivos TypeScript.", + "Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9011": "El parámetro debe tener una anotación de tipo explícita con --isolatedDeclarations.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "El tipo de parámetro del establecedor público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "El tipo de parámetro del establecedor público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "El tipo de parámetro del establecedor estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "El tipo de parámetro del establecedor estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analiza en modo strict y emite \"use strict\" para cada archivo de código fuente.", + "Part_of_files_list_in_tsconfig_json_1409": "Parte de la lista de \"archivos\" de tsconfig.json", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "El patrón \"{0}\" puede tener un carácter '*' como máximo.", + "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386": "Los intervalos de rendimiento de \"--diagnostics\" o \"--extendedDiagnostics\" no están disponibles en esta sesión. No se encontró ninguna implementación nativa de la API de rendimiento web.", + "Platform_specific_6912": "Específico de plataforma", + "Prefix_0_with_an_underscore_90025": "Prefijo \"{0}\" con guion bajo", + "Prefix_all_incorrect_property_declarations_with_declare_95095": "Agregar el prefijo \"declare\" a todas las declaraciones de propiedad incorrectas", + "Prefix_all_unused_declarations_with_where_possible_95025": "Agregar \"_\" como prefijo a todas las declaraciones sin usar, cuando sea posible", + "Prefix_with_declare_95094": "Agregar el prefijo \"declare\"", + "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449": "Conserva los valores importados no usados en la salida de JavaScript que, de lo contrario, se quitarían.", + "Print_all_of_the_files_read_during_the_compilation_6653": "Imprima todos los archivos leídos durante la compilación.", + "Print_files_read_during_the_compilation_including_why_it_was_included_6631": "Imprima los archivos leídos durante la compilación, incluyendo la razón por la que se incluyó.", + "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505": "Imprima los nombres de los archivos y el motivo por el que forman parte de la compilación.", + "Print_names_of_files_part_of_the_compilation_6155": "Imprimir los nombres de los archivos que forman parte de la compilación.", + "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "Imprima los nombres de los archivos que forman parte de la compilación y, a continuación, detenga el procesamiento.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimir los nombres de los archivos generados que forman parte de la compilación.", + "Print_the_compiler_s_version_6019": "Imprima la versión del compilador.", + "Print_the_final_configuration_instead_of_building_1350": "Imprima la configuración final en lugar de compilar.", + "Print_the_names_of_emitted_files_after_a_compilation_6652": "Imprima los nombres de los archivos emitidos después de una compilación.", + "Print_this_message_6017": "Imprima este mensaje.", + "Private_accessor_was_defined_without_a_getter_2806": "El descriptor de acceso privado se ha definido sin un captador.", + "Private_field_0_must_be_declared_in_an_enclosing_class_1111": "El campo privado “{0}” debe declararse en una clase envolvente.", + "Private_identifiers_are_not_allowed_in_variable_declarations_18029": "No se permiten identificadores privados en las declaraciones de variables.", + "Private_identifiers_are_not_allowed_outside_class_bodies_18016": "No se permiten identificadores privados fuera de los cuerpos de clase.", + "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451": "Los identificadores privados solo están permitidos en cuerpos de clase y solo se pueden utilizan como parte de una declaración de un miembro de clase, acceso de propiedad o en la parte izquierda de una expresión \"in\".", + "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028": "Los identificadores privados solo están disponibles cuando el destino es ECMAScript 2015 y versiones posteriores.", + "Private_identifiers_cannot_be_used_as_parameters_18009": "Los identificadores privados no se pueden usar como parámetros.", + "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105": "No se puede acceder al miembro \"{0}\" privado o protegido en un parámetro de tipo.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Project '{0}' can't be built because its dependency '{1}' has errors", + "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Project '{0}' can't be built because its dependency '{1}' was not built", + "Project_0_is_being_forcibly_rebuilt_6388": "El proyecto \"{0}\" se está recompilando de manera forzada.", + "Project_0_is_out_of_date_because_1_6420": "El proyecto “{0}” no está actualizado porque {1}.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_6412": "El proyecto “{0}” no está actualizado porque el archivo buildinfo “{1}” indica que el archivo “{2}” era el archivo raíz de la compilación, pero ya no.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419": "El “{0}” del proyecto no está actualizado porque el archivo buildinfo “{1}” indica que el programa debe informar de errores.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "El proyecto \"{0}\" no está actualizado porque el archivo buildinfo \"{1}\" indica que algunos de los cambios no se emitieron", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions_6406": "El proyecto “{0}” no está actualizado porque el archivo buildinfo “{1}” indica que hay cambios en compilerOptions", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "El proyecto \"{0}\" está obsoleto porque su dependencia \"{1}\" no está actualizada", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "El proyecto \"{0}\" está obsoleto porque la salida \"{1}\" es anterior a la entrada \"{2}\"", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "El proyecto \"{0}\" está obsoleto porque el archivo de salida \"{1}\" no existe", + "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "El proyecto \"{0}\" está obsoleto porque su salida se generó con la versión \"{1}\", que es distinta a la versión actual \"{2}\".", + "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401": "El proyecto \"{0}\" no está actualizado porque se produjo un error al leer el archivo \"{1}\"", + "Project_0_is_up_to_date_6361": "El proyecto \"{0}\" está actualizado", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "El proyecto \"{0}\" está actualizado porque la entrada más reciente \"{1}\" es anterior a la salida \"{2}\"", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "El proyecto \"{0}\" está actualizado, pero debe actualizar las marcas de tiempo de los archivos de salida anteriores a los archivos de entrada", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "El proyecto \"{0}\" está actualizado con archivos .d.ts de sus dependencias", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Las referencias del proyecto no pueden formar un gráfico circular. Ciclo detectado: {0}", + "Projects_6255": "Proyectos", + "Projects_in_this_build_Colon_0_6355": "Proyectos de esta compilación: {0}", + "Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher_18045": "Las propiedades con el modificador 'accessor' solo están disponibles cuando el destino es ECMAScript 2015 y versiones posteriores.", + "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267": "La propiedad '{0}' no puede tener un mediador porque se marca como abstracto.", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "La propiedad \"{0}\" procede de una signatura de índice, por lo que debe accederse a ella con [\"{0}\"].", + "Property_0_does_not_exist_on_type_1_2339": "La propiedad '{0}' no existe en el tipo '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Quería decir \"{2}\"?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Pretendía acceder al miembro estático \"{2}\"?", + "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "No existe la propiedad \"{0}\" en el tipo \"{1}\". ¿Necesita cambiar la biblioteca de destino? Pruebe a cambiar la opción del compilador \"lib\" a \"{2}\" o posterior.", + "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812": "La propiedad \"{0}\" no existe en el tipo \"{1}\". Intente cambiar la opción del compilador \"lib\" para incluir \"dom\".", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817": "La propiedad '{0}' no tiene inicializador y no está asignada de forma definitiva en el bloque estático de clase.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propiedad \"{0}\" no tiene inicializador y no está asignada de forma definitiva en el constructor.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso get le falta una anotación de tipo de valor devuelto.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso set le falta una anotación de tipo de parámetro.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048": "La propiedad \"{0}\" tiene el tipo \"any\" de forma implícita, pero se puede inferir un tipo más adecuado para su descriptor de acceso get a partir del uso.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049": "La propiedad \"{0}\" tiene el tipo \"any\" de forma implícita, pero se puede inferir un tipo más adecuado para su descriptor de acceso set a partir del uso.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar a la misma propiedad del tipo base \"{2}\".", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar al tipo \"{2}\".", + "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "La propiedad \"{0}\" del tipo \"{1}\" hace referencia a un miembro distinto al que no se puede acceder desde el tipo \"{2}\".", + "Property_0_is_declared_but_its_value_is_never_read_6138": "La propiedad \"{0}\" se declara, pero su valor no se lee nunca.", + "Property_0_is_incompatible_with_index_signature_2530": "La propiedad '{0}' es incompatible con la signatura de índice.", + "Property_0_is_missing_in_type_1_2324": "Falta la propiedad '{0}' en el tipo '{1}'.", + "Property_0_is_missing_in_type_1_but_required_in_type_2_2741": "La propiedad \"{0}\" falta en el tipo \"{1}\", pero es obligatoria en el tipo \"{2}\".", + "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013": "No se puede acceder a la propiedad \"{0}\" fuera de la clase \"{1}\" porque tiene un identificador privado.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "La propiedad '{0}' es opcional en el tipo '{1}', pero obligatoria en el tipo '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "La propiedad '{0}' es privada y solo se puede acceder a ella en la clase '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "La propiedad '{0}' es privada en el tipo '{1}', pero no en el tipo '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446": "La propiedad \"{0}\" está protegida y solo puede accederse a ella a través de una instancia de la clase \"{1}\". Esta es una instancia de la clase \"{2}\".", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "La propiedad '{0}' está protegida y solo se puede acceder a ella en la clase '{1}' y las subclases de esta.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "La propiedad '{0}' está protegida, pero el tipo '{1}' no es una clase derivada de '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "La propiedad '{0}' está protegida en el tipo '{1}', pero es pública en el tipo '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "La propiedad \"{0}\" se usa antes de asignarla.", + "Property_0_is_used_before_its_initialization_2729": "La propiedad \"{0}\" se usa antes de su inicialización.", + "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Quería decir \"{2}\"?", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "La propiedad '{0}' del atributo spread de JSX no se puede asignar a la propiedad de destino.", + "Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected_4094": "La propiedad “{0}” del tipo de clase anónima exportada no puede ser privada ni estar protegida.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "La propiedad '{0}' de la interfaz exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "La propiedad '{0}' de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411": "La propiedad \"{0}\" de tipo \"{1}\" no se puede asignar al tipo de índice \"{2}\" \"{3}\".", + "Property_0_was_also_declared_here_2733": "La propiedad \"{0}\" también se ha declarado aquí.", + "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612": "La propiedad \"{0}\" sobrescribirá la propiedad base en \"{1}\" Si esto es intencionado, agregue un inicializador. De lo contrario, agregue un modificador \"declare\" o quite la declaración redundante.", + "Property_assignment_expected_1136": "Se esperaba una asignación de propiedad.", + "Property_destructuring_pattern_expected_1180": "Se esperaba un patrón de desestructuración de propiedad.", + "Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9012": "La propiedad debe tener una anotación de tipo explícita con --isolatedDeclarations.", + "Property_or_signature_expected_1131": "Se esperaba una propiedad o una signatura.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "El valor de la propiedad puede ser solo un literal de cadena, literal numérico, 'true', 'false', 'null', literal de objeto o literal de matriz.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_6179": "Proporcionar compatibilidad total con objetos iterables en “for-of”, propagaciones y desestructuraciones cuando el destino es “ES5”.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "El método público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo externo {2}, pero no puede tener nombre.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "El método público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "El método público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "La propiedad pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "La propiedad pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo '{2}' privado.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "La propiedad pública '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "El método estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo externo {2}, pero no puede tener nombre.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "El método estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo privado \"{2}\".", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "El método estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "La propiedad estática pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo {2} externo, pero no se puede nombrar.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "La propiedad estática pública '{0}' de la clase exportada tiene o usa el nombre '{1}' del módulo {2} privado.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "La propiedad estática pública '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", + "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032": "No se permite el nombre calificado \"{0}\" sin un elemento \"@param {object} {1}\" inicial.", + "Raise_an_error_when_a_function_parameter_isn_t_read_6676": "Genera un error cuando no se lee un parámetro de función.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Generar un error en las expresiones y las declaraciones con un tipo \"any\" implícito.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Generar un error en expresiones 'this' con un tipo 'any' implícito.", + "Range_out_of_order_in_character_class_1517": "Rango desordenado en la clase de caracteres.", + "Re_exporting_a_type_when_0_is_enabled_requires_using_export_type_1205": "Volver a exportar un tipo cuando “{0}” está habilitado requiere el uso de “export type”.", + "React_components_cannot_include_JSX_namespace_names_2639": "Los componentes de React no pueden incluir nombres de espacio de nombres JSX", + "Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.", + "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617": "Reduzca el número de proyectos cargados automáticamente por TypeScript.", + "Referenced_project_0_may_not_disable_emit_6310": "El proyecto \"{0}\" al que se hace referencia no puede deshabilitar la emisión.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "El proyecto \"{0}\" al que se hace referencia debe tener el valor \"composite\": true.", + "Referenced_via_0_from_file_1_1400": "Se hace referencia mediante \"{0}\" desde el archivo \"{1}\".", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2834": "Las rutas de acceso de importación relativas necesitan extensiones de archivo explícitas en las importaciones ECMAScript cuando “--moduleResolution” es “node16” o “nodenext”. Considere la posibilidad de agregar una extensión a la ruta de acceso de importación.", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2835": "Las rutas de acceso de importación relativas necesitan extensiones de archivo explícitas en las importaciones ECMAScript cuando “--moduleResolution” es “node16” o “nodenext”. ¿Quiso decir “{0}”?", + "Remove_a_list_of_directories_from_the_watch_process_6628": "Quite una lista de directorios del proceso de inspección.", + "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629": "Quite una lista de archivos del procesamiento del modo de inspección.", + "Remove_all_unnecessary_override_modifiers_95163": "Quitar todos los modificadores \"override\" innecesarios", + "Remove_all_unnecessary_uses_of_await_95087": "Quitar todos los usos innecesarios de \"await\"", + "Remove_all_unreachable_code_95051": "Quitar todo el código inaccesible", + "Remove_all_unused_labels_95054": "Quitar todas las etiquetas no utilizadas", + "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115": "Quitar las llaves de todos los cuerpos de función de flecha con problemas relevantes", + "Remove_braces_from_arrow_function_95060": "Quitar las llaves de la función de flecha", + "Remove_braces_from_arrow_function_body_95112": "Quitar las llaves del cuerpo de función de flecha", + "Remove_import_from_0_90005": "Quitar importación de \"{0}\"", + "Remove_override_modifier_95161": "Quitar el modificador \"override\"", + "Remove_parentheses_95126": "Quitar los paréntesis", + "Remove_template_tag_90011": "Quitar la etiqueta de plantilla", + "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618": "Elimine el límite de 20 MB del tamaño total del código fuente para los archivos JavaScript en el servidor de lenguaje TypeScript.", + "Remove_type_from_import_declaration_from_0_90055": "Quitar \"type\" de la declaración de importación de \"{0}\"", + "Remove_type_from_import_of_0_from_1_90056": "Quitar \"type\" de la importación de '{0}' de \"{1}\"", + "Remove_type_parameters_90012": "Quitar los parámetros de tipo", + "Remove_unnecessary_await_95086": "Quitar elementos \"await\" innecesarios", + "Remove_unreachable_code_95050": "Quitar el código inaccesible", + "Remove_unused_declaration_for_Colon_0_90004": "Quitar la declaración sin usar para \"{0}\"", + "Remove_unused_declarations_for_Colon_0_90041": "Quite las declaraciones sin usar para \"{0}\"", + "Remove_unused_destructuring_declaration_90039": "Quite la declaración de desestructuración no utilizada", + "Remove_unused_label_95053": "Quitar etiqueta no utilizada", + "Remove_variable_statement_90010": "Quitar la declaración de variable", + "Rename_param_tag_name_0_to_1_95173": "Cambiar el nombre de la etiqueta \"@param\" \"{0}\" a \"{1}\"", + "Replace_0_with_Promise_1_90036": "Reemplazar \"{0}\" por \"Promise<{1}>\"", + "Replace_all_unused_infer_with_unknown_90031": "Reemplazar todos los elementos \"infer\" sin usar por \"unknown\"", + "Replace_import_with_0_95015": "Reemplazar importación por \"{0}\".", + "Replace_infer_0_with_unknown_90030": "Reemplazar \"infer {0}\" por \"unknown\"", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Notificar errores de los casos de fallthrough en la instrucción switch.", + "Report_errors_in_js_files_8019": "Notifique los errores de los archivos .js.", + "Report_errors_on_unused_locals_6134": "Informe de errores sobre variables locales no usadas.", + "Report_errors_on_unused_parameters_6135": "Informe de errores sobre parámetros no usados.", + "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719": "Requiere una anotación suficiente en las exportaciones para que otras herramientas puedan generar archivos de declaración de forma trivial.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717": "Se requieren propiedades no declaradas de las signaturas de índice para usar los accesos de elemento.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Los parámetros de tipo requeridos pueden no seguir parámetros de tipo opcionales.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La resolución del módulo \"{0}\" se encontró en la memoria caché de la ubicación \"{1}\".", + "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "La resolución de la directiva de referencia de tipo \"{0}\" se encontró en la memoria caché de la ubicación \"{1}\".", + "Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_i_6277": "Error en la resolución del nombre no relativo; probando con las características modernas de resolución de nodos deshabilitadas para ver si la biblioteca npm necesita una actualización de la configuración.", + "Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_ne_6279": "Error en la resolución del nombre no relativo; intentando con “--moduleResolution bundler” para ver si el proyecto puede necesitar una actualización de la configuración.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolver \"keyof\" exclusivamente como nombres de propiedad con valores de cadena (sin números ni símbolos).", + "Resolved_under_condition_0_6414": "Resuelto bajo condición “{0}”.", + "Resolving_in_0_mode_with_conditions_1_6402": "Resolviendo en modo {0} con condiciones {1}.", + "Resolving_module_0_from_1_6086": "======== Resolviendo el módulo '{0}' de '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolviendo el nombre de módulo '{0}' relativo a la dirección URL base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Resolviendo la ruta de acceso real de \"{0}\", resultado: \"{1}\".", + "Resolving_type_reference_directive_0_containing_file_1_6242": "======== Resolviendo la directiva de referencia de tipo \"{0}\", archivo contenedor \"{1}\". ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor: '{1}', directorio raíz: '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor: '{1}', directorio raíz no establecido. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor no establecido, directorio raíz: '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Resolviendo la directiva de referencia de tipo '{0}', archivo contenedor no establecido, directorio raíz no establecido. ========", + "Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_no_6265": "Resolviendo la directiva de referencia de tipo para el programa que especifica typeRoots personalizado, omitiendo la búsqueda en la carpeta “node_modules”.", + "Resolving_with_primary_search_path_0_6121": "Resolviendo con la ruta de búsqueda principal \"{0}\".", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "El parámetro rest '{0}' tiene un tipo \"any[]\" implícitamente.", + "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047": "El parámetro rest \"{0}\" tiene un tipo \"any[]\" de forma implícita, pero se puede inferir un tipo más adecuado a partir del uso.", + "Rest_types_may_only_be_created_from_object_types_2700": "Los tipos rest solo se pueden crear a partir de tipos de objeto.", + "Return_type_annotation_circularly_references_itself_2577": "La anotación de tipo de valor devuelto se hace referencia a sí misma de forma circular.", + "Return_type_must_be_inferred_from_a_function_95149": "El tipo de valor devuelto debe inferirse de una función", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "El tipo de valor devuelto de la signatura de llamada de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "El tipo de valor devuelto de la signatura de llamada de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "El tipo de valor devuelto de la signatura de constructor de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "El tipo de valor devuelto de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "El tipo de valor devuelto de la signatura de constructor se debe poder asignar al tipo de instancia de la clase.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "El tipo de valor devuelto de la función exportada tiene o usa el nombre '{0}' del módulo {1} externo, pero no se puede nombrar.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "El tipo de valor devuelto de la función exportada tiene o usa el nombre '{0}' del módulo {1} privado.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "El tipo de valor devuelto de la función exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "El tipo de valor devuelto de la signatura de índice de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "El tipo de valor devuelto de la signatura de índice de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "El tipo de valor devuelto del método de la interfaz exportada tiene o usa el nombre '{0}' del módulo '{1}' privado.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "El tipo de valor devuelto del método de la interfaz exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "El tipo de valor devuelto del captador público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo {2} externo, pero no se puede nombrar.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "El tipo de valor devuelto del captador público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "El tipo de valor devuelto del captador público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "El tipo de valor devuelto del método público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} externo, pero no se puede nombrar.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "El tipo de valor devuelto del método público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} privado.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "El tipo de valor devuelto del método público de la clase exportada tiene o usa el nombre privado '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "El tipo de valor devuelto del captador estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo {2} externo, pero no se puede nombrar.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "El tipo de valor devuelto del captador estático público \"{0}\" de la clase exportada tiene o usa el nombre \"{1}\" del módulo \"{2}\" privado.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "El tipo de valor devuelto del captador estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} externo, pero no se puede nombrar.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre '{0}' del módulo {1} privado.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre privado '{0}'.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395": "La reutilización de la resolución del módulo \"{0}\" de \"{1}\" que se encuentra en la memoria caché desde la ubicación \"{2}\" no se resolvió.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393": "La reutilización de la resolución del módulo \"{0}\" de \"{1}\" que se encuentra en la memoria caché desde la ubicación \"{2}\" se resolvió correctamente en \"{3}\".", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394": "La reutilización de la resolución del módulo \"{0}\" de \"{1}\" que se encuentra en la memoria caché desde la ubicación \"{2}\" se resolvió correctamente en \"{3}\" con el identificador de paquete \"{4}\".", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389": "La reutilización de la resolución del módulo \"{0}\" del programa anterior \"{1}\" no se resolvió.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183": "La reutilización de la resolución del módulo \"{0}\" del programa anterior \"{1}\" se resolvió correctamente en \"{2}\".", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184": "La reutilización de la resolución del módulo \"{0}\" del programa anterior \"{1}\" se resolvió correctamente en \"{2}\" con el identificador del paquete \"{3}\".", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398": "La reutilización de la resolución de la directiva de referencia de tipo \"{0}\" de \"{1}\" que se encuentra en la memoria caché desde la ubicación \"{2}\" no se resolvió.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396": "La reutilización de la resolución de la directiva de referencia de tipo \"{0}\" de \"{1}\" que se encuentra en la memoria caché desde la ubicación \"{2}\" se resolvió correctamente en \"{3}\".", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397": "La reutilización de la resolución de la directiva de referencia de tipo \"{0}\" de \"{1}\" que se encuentra en la memoria caché desde la ubicación \"{2}\" se resolvió correctamente en \"{3}\" con el identificador del paquete \"{4}\".", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392": "La reutilización de la resolución de la directiva de referencia de tipo \"{0}\" de \"{1}\" del programa anterior no se resolvió.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390": "La reutilización de la resolución de la directiva de referencia de tipo \"{0}\" de \"{1}\" del programa anterior se resolvió correctamente en \"{2}\".", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391": "La reutilización de la resolución de la directiva de referencia de tipo \"{0}\" de \"{1}\" del programa anterior se resolvió correctamente en \"{2}\" con el identificador de paquete \"{3}\".", + "Rewrite_all_as_indexed_access_types_95034": "Reescribir todo como tipos de acceso indexados", + "Rewrite_as_the_indexed_access_type_0_90026": "Reescribir como tipo de acceso indexado \"{0}\"", + "Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_i_6421": "Vuelva a escribir las extensiones de archivo \".ts\", \".tsx\", \".mts\" y \".cts\" en rutas de acceso de importación relativas a su equivalente de JavaScript en los archivos de salida.", + "Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish_2869": "El operando derecho de ?? es inaccesible porque el operando izquierdo nunca es nulo.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "No se puede determinar el directorio raíz, se omitirán las rutas de búsqueda principales.", + "Root_file_specified_for_compilation_1427": "Archivo raíz especificado para la compilación", + "STRATEGY_6039": "ESTRATEGIA", + "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Guarde archivos .tsbuildinfo para permitir la compilación incremental de proyectos.", + "Saw_non_matching_condition_0_6405": "Se vio una condición no coincidente '{0}'.", + "Scoped_package_detected_looking_in_0_6182": "Se detectó un paquete con ámbito al buscar en \"{0}\"", + "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418": "Buscando extensiones de reserva en todos los directorios de node_modules antecesores: {0}.", + "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417": "Buscando extensiones preferidas en todos los directorios de node_modules antecesores: {0}.", + "Selection_is_not_a_valid_statement_or_statements_95155": "La selección no es una instrucción ni instrucciones válidas", + "Selection_is_not_a_valid_type_node_95133": "La selección no es un nodo de tipo válido", + "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705": "Establezca la versión del lenguaje de JavaScript para las JavaScript emitidas e incluya las declaraciones de bibliotecas compatibles.", + "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654": "Establezca el lenguaje de la mensajería de TypeScript. No afecta a la emisión.", + "Set_the_module_option_in_your_configuration_file_to_0_95099": "Establecer la opción \"module\" del archivo de configuración en \"{0}\"", + "Set_the_newline_character_for_emitting_files_6659": "Establezca el carácter de nueva línea para emitir archivos.", + "Set_the_target_option_in_your_configuration_file_to_0_95098": "Establecer la opción \"target\" del archivo de configuración en \"{0}\"", + "Setters_cannot_return_a_value_2408": "Los establecedores no pueden devolver un valor.", + "Show_all_compiler_options_6169": "Mostrar todas las opciones de compilador.", + "Show_diagnostic_information_6149": "Mostrar información de diagnóstico.", + "Show_verbose_diagnostic_information_6150": "Mostrar información de diagnóstico detallada.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Mostrar lo que podría compilarse (o eliminarse, si se especifica con \"--clean\")", + "Signature_0_must_be_a_type_predicate_1224": "La signatura '{0}' debe tener un predicado de tipo.", + "Signature_declarations_can_only_be_used_in_TypeScript_files_8017": "Las declaraciones de signatura solo se pueden usar en los archivos TypeScript.", + "Skip_building_downstream_projects_on_error_in_upstream_project_6640": "Omitir la compilación de proyectos que siguen en la cadena debido a un error en el proyecto ascendente.", + "Skip_type_checking_all_d_ts_files_6693": "Omita la comprobación de tipos de todos los archivos .d.ts.", + "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692": "Omita la comprobación de tipos de archivo .d.ts que se incluyen con TypeScript.", + "Skip_type_checking_of_declaration_files_6012": "Omita la comprobación de tipos de los archivos de declaración.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Skipping build of project '{0}' because its dependency '{1}' has errors", + "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382": "Skipping build of project '{0}' because its dependency '{1}' was not built", + "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164": "Omitiendo el módulo “{0}” que parece un URI absoluto, tipos de archivo de destino: {1}.", + "Source_from_referenced_project_0_included_because_1_specified_1414": "El origen del proyecto \"{0}\" al que se hace referencia se ha incluido porque se ha especificado \"{1}\".", + "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415": "El origen del proyecto \"{0}\" al que se hace referencia se ha incluido porque \"--module\" se ha especificado como \"none\".", + "Source_has_0_element_s_but_target_allows_only_1_2619": "El origen tiene {0} elemento(s), pero el destino solo permite {1}.", + "Source_has_0_element_s_but_target_requires_1_2618": "El origen tiene {0} elemento(s), pero el destino requiere {1}.", + "Source_provides_no_match_for_required_element_at_position_0_in_target_2623": "El origen no proporciona ninguna coincidencia para el elemento requerido en la posición {0} del destino.", + "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624": "El origen no proporciona ninguna coincidencia para el elemento variádico en la posición {0} del destino.", + "Specify_ECMAScript_target_version_6015": "Especifique la versión de destino de ECMAScript.", + "Specify_JSX_code_generation_6080": "Especifique la generación de código JSX.", + "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679": "Especifique un archivo que agrupe todas las salidas en un archivo JavaScript. Si 'declaración' es verdadera, también designa un archivo que agrupa toda la salida .d.ts.", + "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641": "Especifique una lista de patrones globales que coincidan con los archivos que se incluirán en la compilación.", + "Specify_a_list_of_language_service_plugins_to_include_6681": "Especifique una lista de complementos de servicio de lenguaje para incluirlos.", + "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651": "Especifique un conjunto de archivos de declaración de biblioteca agrupados que describan el entorno de tiempo de ejecución de destino.", + "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680": "Especifique un conjunto de entradas que reasignan las importaciones a ubicaciones de búsqueda adicionales.", + "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687": "Especifique una matriz de objetos que especifique las rutas de acceso a los proyectos. Usada en las referencias del proyecto.", + "Specify_an_output_folder_for_all_emitted_files_6678": "Especifique una carpeta de salida para todos los archivos emitidos.", + "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718": "Especificar el comportamiento de emisión o comprobación para las importaciones que solo se usan para los tipos.", + "Specify_file_to_store_incremental_compilation_information_6380": "Especificar un archivo para almacenar la información de compilación incremental", + "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658": "Especifique cómo busca TypeScript un archivo a partir del especificador de módulo que se le indique.", + "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714": "Especifique cómo se vigilan los directorios en los sistemas que carecen de la funcionalidad de vigilancia recursiva de archivos.", + "Specify_how_the_TypeScript_watch_mode_works_6715": "Especifique cómo funciona el modo de inspección de TypeScript.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Especifique los archivos de biblioteca que se van a incluir en la compilación.", + "Specify_module_code_generation_6016": "Especifique la generación de código del módulo.", + "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649": "Especifique el especificador de módulo que se usa para importar las funciones de fábrica de JSX cuando se usa \"jsx: react-jsx*\".", + "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710": "Especifique varias carpetas que actúen como \"./node_modules/@types\".", + "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633": "Especifique una o varias referencias de ruta o de módulo de nodo a los archivos de configuración base desde los que se herede la configuración.", + "Specify_options_for_automatic_acquisition_of_declaration_files_6709": "Especifique las opciones para la adquisición automática de los archivos de declaración.", + "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227": "Especifique la estrategia para crear una inspección de sondeo cuando no se pueda crear con eventos del sistema de archivos: \"FixedInterval\" (valor predeterminado), \"PriorityInterval\", \"DynamicPriority\", \"FixedChunkSize\".", + "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226": "Especifique la estrategia para inspeccionar el directorio en las plataformas que no admiten las inspecciones recursivas de forma nativa: \"UseFsEvents\" (valor predeterminado), \"FixedPollingInterval\", \"DynamicPriorityPolling\", \"FixedChunkSizePolling\".", + "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225": "Especifique la estrategia para inspeccionar el archivo: \"FixedPollingInterval\" (valor predeterminado), \"PriorityPollingInterval\", \"DynamicPriorityPolling\", \"FixedChunkSizePolling\", \"UseFsEvents\", \"UseFsEventsOnParentDirectory\".", + "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648": "Especifique la referencia de fragmento de JSX utilizada para los fragmentos cuando se dirige a la emisión de JSX de React, por ejemplo, \"React.Fragment\" o \"Fragment\".", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Especifique la función de generador JSX que se usará cuando el destino sea la emisión de JSX \"react\"; por ejemplo, \"React.createElement\" o \"h\".", + "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647": "Especifique la función de generador JSX que se usa al establecer como destino la emisión JSX de React; por ejemplo, \"React.createElement\" o \"h\".", + "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034": "Especifique la función de la fábrica de fragmentos de JSX que se va a usar cuando se especifique como destino la emisión de JSX \"react\" con la opción del compilador \"jsxFactory\", por ejemplo, \"fragmento\".", + "Specify_the_base_directory_to_resolve_non_relative_module_names_6607": "Especifique el directorio base para resolver nombres de módulos no relativos.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Especifique la secuencia de final de línea que debe usarse para emitir archivos: 'CRLF' (Dos) o 'LF' (Unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Especifique la ubicación donde el depurador debe colocar los archivos de TypeScript en lugar de sus ubicaciones de origen.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655": "Especifique la ubicación donde el depurador debe colocar los archivos de asignaciones en lugar de las ubicaciones generadas.", + "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656": "Especifique la profundidad máxima de carpeta usada para comprobar archivos JavaScript de \"node_modules\". Solo es compatible con \"allowJs\".", + "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238": "Especifique el especificador de módulo que se va a usar para importar las funciones de fábrica \"jsx\" y \"jsxs\"; por ejemplo, react", + "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686": "Especifique el objeto invocado para 'createElement'. Esto solo se aplica cuando el destino es la emisión JSX \"react\".", + "Specify_the_output_directory_for_generated_declaration_files_6613": "Especifique el directorio de salida para los archivos de declaración generados.", + "Specify_the_path_to_tsbuildinfo_incremental_compilation_file_6707": "Especifique la ruta de acceso para el archivo de compilación incremental .tsbuildinfo.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Especifique el directorio raíz de los archivos de entrada. Úselo para controlar la estructura del directorio de salida con --outDir.", + "Specify_the_root_folder_within_your_source_files_6690": "Especifique la carpeta raíz en los archivos de código fuente.", + "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695": "Especifique la ruta raíz para que los depuradores encuentren el código de origen de referencia.", + "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711": "Especifique los nombres de los paquetes de tipo que se incluyen sin ser referenciados en un archivo fuente.", + "Specify_what_JSX_code_is_generated_6646": "Especifique qué código de JSX se generará.", + "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634": "Especifique el enfoque que debe usar el monitor si el sistema agota los monitores de archivos nativos.", + "Specify_what_module_code_is_generated_6657": "Especifique qué código de módulo se generará.", + "Split_all_invalid_type_only_imports_1367": "Dividir todas las importaciones solo de tipo no válidas", + "Split_into_two_separate_import_declarations_1366": "Dividir en dos declaraciones de importación independientes", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "El operador spread de las expresiones \"new\" solo está disponible si el destino es ECMAScript 5 y versiones posteriores.", + "Spread_types_may_only_be_created_from_object_types_2698": "Los tipos spread solo se pueden crear a partir de tipos de objeto.", + "Starting_compilation_in_watch_mode_6031": "Iniciando la compilación en modo de inspección...", + "Statement_expected_1129": "Se esperaba una instrucción.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "No se permiten instrucciones en los contextos de ambiente.", + "Static_members_cannot_reference_class_type_parameters_2302": "Los miembros estáticos no pueden hacer referencia a parámetros de tipo de clase.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "La propiedad estática \"{0}\" está en conflicto con la propiedad integrada \"Function.{0}\" de la función de constructor \"{1}\".", + "String_literal_expected_1141": "Se esperaba un literal de cadena.", + "String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es_18057": "No se admiten los nombres de importación y exportación de literales de cadena cuando la marca “--module” está establecida en “es2015” o “es2020”.", + "String_literal_with_double_quotes_expected_1327": "Se esperaba un literal de cadena entre comillas dobles.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Use color y contexto para estilizar los errores y los mensajes (experimental).", + "Subpattern_flags_must_be_present_when_there_is_a_minus_sign_1504": "Las marcas de subpatrones deben estar presentes cuando hay un signo menos.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Las declaraciones de propiedad subsiguientes deben tener el mismo tipo. La propiedad \"{0}\" debe ser de tipo \"{1}\", pero aquí tiene el tipo \"{2}\".", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Las declaraciones de variable subsiguientes deben tener el mismo tipo. La variable '{0}' debe ser de tipo '{1}', pero aquí tiene el tipo '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "La sustitución '{0}' para el patrón '{1}' tiene un tipo incorrecto. Se esperaba 'string', pero se obtuvo '{2}'.", + "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062": "La sustitución \"{0}\" del patrón \"{1}\" puede tener un carácter \"*\" como máximo.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Las sustituciones para el patrón '{0}' deben ser una matriz.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Las sustituciones para el patrón '{0}' no deben ser una matriz vacía.", + "Successfully_created_a_tsconfig_json_file_6071": "Archivo tsconfig.json creado correctamente.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "No se permiten llamadas a \"super\" fuera de los constructores o en funciones anidadas dentro de estos.", + "Suppress_excess_property_checks_for_object_literals_6072": "Suprima las comprobaciones de propiedades en exceso de los literales de objeto.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Eliminar errores de noImplicitAny para los objetos de indexación a los que les falten firmas de índice.", + "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703": "Suprima los errores \"noImplicitAny\" al indexar objetos que carecen de firmas de índice.", + "Switch_each_misused_0_to_1_95138": "Cambie cada elemento \"{0}\" usado incorrectamente a \"{1}\"", + "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704": "Llame a las devoluciones de llamada de forma sincrónica y actualice el estado de los monitores de directorio en las plataformas que no admitan la supervisión recursiva de forma nativa.", + "Syntax_Colon_0_6023": "Sintaxis: {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "La etiqueta \"{0}\" espera al menos \"{1}\" argumentos, pero el generador de JSX \"{2}\" proporciona como máximo \"{3}\".", + "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "No se permiten expresiones de plantilla con etiquetas en una cadena opcional.", + "Target_allows_only_0_element_s_but_source_may_have_more_2621": "El destino solo permite {0} elemento(s), pero el origen puede tener más.", + "Target_requires_0_element_s_but_source_may_have_fewer_2620": "El destino requiere {0} elemento(s), pero el origen puede tener menos.", + "Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1_2849": "La firma de destino proporciona muy pocos argumentos. Se esperaba {0} o más, pero se obtuvo {1}.", + "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "El modificador \"{0}\" solo se puede usar en los archivos TypeScript.", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "El operador '{0}' no se puede aplicar al tipo \"symbol\".", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "No se permite usar el operador '{0}' para los tipos booleanos. Como alternativa, puede usar '{1}'.", + "The_0_property_of_an_async_iterator_must_be_a_method_2768": "La propiedad \"{0}\" de un iterador de asincronía debe ser un método.", + "The_0_property_of_an_iterator_must_be_a_method_2767": "La propiedad \"{0}\" de un iterador debe ser un método.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "El tipo 'Object' se puede asignar a muy pocos tipos. ¿Se refería a usar el tipo 'any' en realidad?", + "The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously_1502": "Las marcas Unicode (u) y Unicode Sets (v) no se pueden establecer simultáneamente.", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_func_2496": "No se puede hacer referencia al objeto “arguments” en una función de flecha en ES5 ni ES5. Considere la posibilidad de usar una expresión de función estándar.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_sta_2522": "No se puede hacer referencia al objeto “arguments” en una función o método asincrónico en ES5. Considere la posibilidad de usar un método o función estándar.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "El cuerpo de una instrucción \"if\" no puede ser la instrucción vacía.", + "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793": "La llamada se llevaría a cabo sin problemas en esta implementación, pero las signaturas de implementación de las sobrecargas no están visibles externamente.", + "The_character_set_of_the_input_files_6163": "Conjunto de caracteres de los archivos de entrada.", + "The_containing_arrow_function_captures_the_global_value_of_this_7041": "La función de flecha contenedora captura el valor global de \"this\".", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "El cuerpo de la función o del módulo contenedor es demasiado grande para realizar un análisis de flujo de control.", + "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309": "El archivo actual es un módulo CommonJS y no puede usar \"await\" en el nivel superior.", + "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479": "El archivo actual es un módulo CommonJS cuyas importaciones generarán llamadas \"require\"; sin embargo, el archivo al que se hace referencia es un módulo ECMAScript y no se puede importar con \"require\". Considere la posibilidad de escribir una llamada dinámica \"import(\"{0}\")\" en su lugar.", + "The_current_host_does_not_support_the_0_option_5001": "El host actual no admite la opción '{0}'.", + "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018": "La declaración de \"{0}\" que probablemente pretendía usar se define aquí", + "The_declaration_was_marked_as_deprecated_here_2798": "La declaración se ha marcado aquí como en desuso.", + "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500": "El tipo esperado procede de la propiedad \"{0}\", que se declara aquí en el tipo \"{1}\"", + "The_expected_type_comes_from_the_return_type_of_this_signature_6502": "El tipo esperado procede del tipo de valor devuelto de esta signatura.", + "The_expected_type_comes_from_this_index_signature_6501": "El tipo esperado procede de esta signatura de índice.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "La expresión de una asignación de exportación debe ser un identificador o un nombre completo en un contexto de ambiente.", + "The_file_is_in_the_program_because_Colon_1430": "El archivo está en el programa porque:", + "The_files_list_in_config_file_0_is_empty_18002": "La lista de archivos del archivo de configuración '{0}' está vacía.", + "The_first_export_default_is_here_2752": "El primer elemento export default está aquí.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "El primer parámetro del método \"then\" de una promesa debe ser una devolución de llamada.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "El tipo \"JSX.{0}\" global no puede tener más de una propiedad.", + "The_implementation_signature_is_declared_here_2750": "La signatura de implementación se declara aquí.", + "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "No se permite la metapropiedad \"import.meta\" en archivos que se compilarán en la salida de CommonJS.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "La metapropiedad \"import.meta\" solo se permite cuando la opción \"--módulo\" es \"es2020\", \"es2022\", \"esnext\", \"system\", \"node16\", \"node18\" o \"nodenext\".", + "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "No se puede asignar un nombre al tipo inferido de \"{0}\" sin una referencia a \"{1}\". Es probable que no sea portable. Se requiere una anotación de tipo.", + "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "El tipo deducido de \"{0}\" hace referencia a un tipo con una estructura cíclica que no se puede serializar trivialmente. Es necesaria una anotación de tipo.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "El tipo inferido de \"{0}\" hace referencia a un tipo \"{1}\" no accesible. Se requiere una anotación de tipo.", + "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056": "El tipo inferido de este nodo supera la longitud máxima que el compilador podrá serializar. Se necesita una anotación de tipo explícito.", + "The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_n_2850": "El inicializador de una declaración “using” debe ser un objeto con un método “[Symbol.dispose]()”, o ser “null” o “undefined”.", + "The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_2851": "El inicializador de una declaración “await using” debe ser un objeto con un método “[Symbol.asyncDispose]()” o “[Symbol.dispose]5D;()”, o ser “null” o “undefined”.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "La intersección \"{0}\" se redujo a \"never\" porque la propiedad \"{1}\" existe en varios constituyentes y es privada en algunos de ellos.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "La intersección \"{0}\" se redujo a \"never\" porque la propiedad \"{1}\" tiene tipos en conflicto en algunos constituyentes.", + "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795": "La palabra clave \"intrinsic\" solo se puede usar para declarar tipos intrínsecos proporcionados por el compilador.", + "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016": "Se debe proporcionar la opción del compilador \"jsxFragmentFactory\" para usar fragmentos de JSX con la opción del compilador \"jsxFactory\".", + "The_last_overload_gave_the_following_error_2770": "La última sobrecarga dio el error siguiente.", + "The_last_overload_is_declared_here_2771": "La última sobrecarga se declara aquí.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte izquierda de una instrucción \"for...in\" no puede ser un patrón de desestructuración.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493": "El lado izquierdo de un “for...in” no puede ser una declaración “using”.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494": "El lado izquierdo de una instrucción “for...in” no puede ser una declaración “await using”.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La parte izquierda de una instrucción \"for...in\" no puede usar una anotación de tipo.", + "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780": "La parte izquierda de una instrucción \"for...in\" no puede ser un acceso de propiedad opcional.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "La parte izquierda de una instrucción 'for...in' debe ser una variable o el acceso a una propiedad.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La parte izquierda de una instrucción \"for...in\" debe ser de tipo \"string\" o \"any\".", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "La parte izquierda de una instrucción \"for...of\" no puede usar una anotación de tipo.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781": "La parte izquierda de una instrucción \"for...of\" no puede ser un acceso de propiedad opcional.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106": "El lado izquierdo de una instrucción de \"para... de\" puede no ser \"async\".", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La parte izquierda de una instrucción 'for...of' debe ser una variable o el acceso a una propiedad.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "La parte izquierda de una operación aritmética debe ser de tipo \"any\", \"number\", \"bigint\" o un tipo de enumeración.", + "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "La parte izquierda de una expresión de asignación no puede ser un acceso de propiedad opcional.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La parte izquierda de una expresión de asignación debe ser una variable o el acceso a una propiedad.", + "The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_2860": "El lado izquierdo de una expresión “instanceof” debe poder asignarse al primer argumento del método “[Symbol.hasInstance]” del lado derecho.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La parte izquierda de una expresión \"instanceof\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Configuración regional utilizada para mostrar los mensajes al usuario (por ejemplo, \"es-es\")", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "La profundidad máxima de dependencia para buscar en node_modules y cargar los archivos de JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "El operando de un operador \"delete\" no puede ser un identificador privado.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "El operando de un operador \"delete\" no puede ser una propiedad de solo lectura.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "El operando de un operador \"delete\" debe ser una referencia de propiedad.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "El operando de un operador \"delete\" debe ser opcional.", + "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "El operando de un operador de incremento o decremento no puede ser un acceso de propiedad opcional.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "El operando de un operador de incremento o decremento debe ser una variable o el acceso a una propiedad.", + "The_parser_expected_to_find_a_1_to_match_the_0_token_here_1007": "El analizador esperaba encontrar un elemento \"{1}\" que coincidiera con el token \"{0}\" aquí.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209": "La raíz del proyecto es ambigua, pero es necesaria para resolver la entrada de asignación de exportación \"{0}\" en el archivo \"{1}\". Proporcione la opción del compilador \"rootDir\" para eliminar la ambigüedad.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210": "La raíz del proyecto es ambigua, pero es necesaria para resolver la entrada de asignación de importación \"{0}\" en el archivo \"{1}\". Proporcione la opción del compilador \"rootDir\" para eliminar la ambigüedad.", + "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014": "No se puede acceder a la propiedad \"{0}\" en el tipo \"{1}\" de esta clase porque se ha reemplazado por otro identificador privado con la misma ortografía.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "El tipo de valor devuelto de una función Decorator de parámetro debe ser \"void\" o \"any\".", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "El tipo de valor devuelto de una función Decorator de propiedad debe ser \"void\" o \"any\".", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "El tipo de valor devuelto de una función asincrónica debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065": "El tipo de valor devuelto de una función o un método asincrónicos debe ser el tipo Promise global.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "El tipo de valor devuelto de una función o un método asincrónicos debe ser el tipo Promise global. ¿Pretendía escribir \"Promise<{0}>\"?", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "La parte derecha de una instrucción \"for...in\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo, pero aquí tiene el tipo \"{0}\".", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "La parte derecha de una operación aritmética debe ser de tipo \"any\", \"number\", \"bigint\" o un tipo de enumeración.", + "The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_2359": "El lado derecho de una expresión “instanceof” debe ser de tipo “any”, una clase, función u otro tipo asignable al tipo de interfaz “Function”, o un tipo de objeto con un método “Symbol.hasInstance”.", + "The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression_2848": "El lado derecho de una expresión “instanceof” no debe ser una expresión de creación de instancias.", + "The_root_value_of_a_0_file_must_be_an_object_5092": "El valor raíz de un archivo \"{0}\" debe ser un objeto.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0_1278": "El runtime invocará el decorador con argumentos {1}, pero el decorador espera {0}.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0_1279": "El runtime invocará el decorador con argumentos {1}, pero el decorador espera al menos {0}.", + "The_shadowing_declaration_of_0_is_defined_here_18017": "La declaración que ensombrece a \"{0}\" se define aquí.", + "The_signature_0_of_1_is_deprecated_6387": "La signatura \"{0}\" de \"{1}\" está en desuso.", + "The_specified_path_does_not_exist_Colon_0_5058": "La ruta de acceso especificada no existe: \"{0}\".", + "The_tag_was_first_specified_here_8034": "La etiqueta se especificó aquí primero.", + "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "El destino de una asignación rest de objeto no puede ser un acceso de propiedad opcional.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "El destino de una asignación de reposo de objetos debe ser una variable o un acceso a propiedad.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "El contexto 'this' de tipo '{0}' no se puede asignar al contexto 'this' de tipo '{1}' del método.", + "The_this_types_of_each_signature_are_incompatible_2685": "Los tipos 'this' de cada signatura son incompatibles.", + "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104": "El tipo \"{0}\" es \"readonly\" y no se puede asignar al tipo mutable \"{1}\".", + "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "El modificador 'tipo' no se puede usar en una exportación con nombre cuando se usa 'exportar tipo' en su instrucción exportar.", + "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "El modificador 'tipo' no se puede usar en una importación con nombre cuando se usa 'exportar tipo' en su instrucción importar.", + "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "El tipo de una declaración de función debe coincidir con la signatura de la función.", + "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "No se ha podido serializar el tipo de este nodo porque su propiedad '{0}' no se puede serializar.", + "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "El tipo devuelto por el método \"{0}()\" de un iterador de asincronía debe ser una promesa para un tipo con una propiedad \"value\".", + "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "El tipo devuelto por el método \"{0}()\" de un iterador debe tener una propiedad \"value\".", + "The_types_of_0_are_incompatible_between_these_types_2200": "Los tipos de \"{0}\" son incompatibles entre estos tipos.", + "The_types_returned_by_0_are_incompatible_between_these_types_2201": "Los tipos que \"{0}\" devuelve son incompatibles entre estos tipos.", + "The_value_0_cannot_be_used_here_18050": "El valor \"{0}\" no se puede usar aquí.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "La declaración de variable de una instrucción \"for...in\" no puede tener un inicializador.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La declaración de variable de una instrucción \"for...of\" no puede tener un inicializador.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "No se admite la instrucción 'with'. Todos los símbolos de un bloque 'with' tendrán el tipo 'any'.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setti_6280": "Hay tipos en “{0}”, pero este resultado no se pudo resolver en la configuración actual de “moduleResolution”. Considere la posibilidad de actualizar a “node16”, “nodenext” o “bundler”.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278": "Hay tipos en “{0}”, pero este resultado no se pudo resolver al respetar \"exports\" de package.json. Es posible que la biblioteca “{1}” necesite actualizar sus package.json o tipos.", + "There_is_no_capturing_group_named_0_in_this_regular_expression_1532": "No hay ningún grupo de captura denominado “{0}” en esta expresión regular.", + "There_is_nothing_available_for_repetition_1507": "No hay nada disponible para la repetición.", + "This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found_2874": "Esta etiqueta JSX requiere que \"{0}\" esté en el ámbito, pero no se encontró.", + "This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_fo_2875": "Esta etiqueta JSX requiere que exista la ruta de acceso del módulo \"{0}\", pero no se encontró ninguna. Asegúrese de que tiene instalados los tipos para el paquete adecuado.", + "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "La propiedad \"{0}\" de esta etiqueta de JSX espera un solo elemento secundario de tipo \"{1}\", pero se han proporcionado varios elementos secundarios.", + "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "La propiedad \"{0}\" de esta etiqueta de JSX espera el tipo \"{1}\", que requiere varios elementos secundarios, pero solo se ha proporcionado un elemento secundario.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534": "Esta referencia inversa hace referencia a un grupo que no existe. No hay grupos de captura en esta expresión regular.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533": "Esta referencia inversa hace referencia a un grupo que no existe. Solo hay {0} grupos de captura en esta expresión regular.", + "This_binary_expression_is_never_nullish_Are_you_missing_parentheses_2870": "Esta expresión binaria nunca acepta valores NULL. ¿Faltan paréntesis?", + "This_character_cannot_be_escaped_in_a_regular_expression_1535": "Este carácter no se puede escapar en una expresión regular.", + "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Esta comparación parece no intencionada porque los tipos \"{0}\" y \"{1}\" no tienen superposición.", + "This_condition_will_always_return_0_2845": "Esta condición siempre devolverá \"{0}\".", + "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Esta condición siempre devolverá \"{0}\", ya que JavaScript compara objetos por referencia, no por valor.", + "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Esta condición devolverá siempre true porque siempre se define '{0}'.", + "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Esta condición siempre devolverá true, porque esta función se define siempre. ¿Pretendía llamarla en su lugar?", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Esta función de constructor puede convertirse en una declaración de clase.", + "This_expression_is_always_nullish_2871": "Esta expresión siempre acepta valores NULL.", + "This_expression_is_not_callable_2349": "No se puede llamar a esta expresión.", + "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "No se puede llamar a esta expresión porque es un descriptor de acceso \"get\". ¿Pretendía usarlo sin \"()\"?", + "This_expression_is_not_constructable_2351": "No se puede construir esta expresión.", + "This_file_already_has_a_default_export_95130": "Este archivo ya tiene una exportación predeterminada", + "This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_b_2878": "Esta ruta de acceso de importación no es segura de reescribir porque se resuelve en otro proyecto y la ruta de acceso relativa entre los archivos de salida de los proyectos no es la misma que la ruta de acceso relativa entre sus archivos de entrada.", + "This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_duri_2877": "Esta importación usa una extensión \"{0}\" para resolver en un archivo TypeScript de entrada, pero no se reescribe durante la emisión porque no es una ruta de acceso relativa.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Esta es la declaración que se está aumentando. Considere la posibilidad de mover la declaración en aumento al mismo archivo.", + "This_kind_of_expression_is_always_falsy_2873": "Este tipo de expresión siempre es falso.", + "This_kind_of_expression_is_always_truthy_2872": "Este tipo de expresión siempre es cierto.", + "This_may_be_converted_to_an_async_function_80006": "Puede convertirse en una función asincrónica.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122": "Este miembro no puede tener un comentario JSDoc con una etiqueta '@override' porque no se declara en la clase base '{0}'.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123": "Este miembro no puede tener un comentario JSDoc con una etiqueta 'override' porque no se declara en la clase base '{0}'. ¿Quería decir '{1}'?", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121": "Este miembro no puede tener un comentario JSDoc con una etiqueta '@override' porque su clase contenedora '{0}' no extiende otra clase.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic_4128": "Este miembro no puede tener un comentario JSDoc con una etiqueta '@override' porque su nombre es dinámico.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113": "Este miembro no puede tener un modificador \"override\" porque no está declarado en la clase base \"{0}\".", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117": "Este miembro no puede tener un modificador \"override\" porque no está declarado en la clase base \"{0}\". ¿Quizá quiso decir \"{1}\"?", + "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112": "Este miembro no puede tener un modificador \"override\" porque su clase contenedora \"{0}\" no extiende otra clase.", + "This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic_4127": "Este miembro no puede tener un modificador 'override' porque su nombre es dinámico.", + "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119": "Este miembro debe tener un comentario JSDoc con una etiqueta '@override' porque invalida un miembro de la clase base '{0}'.", + "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114": "Este miembro debe tener un modificador \"override\" porque reemplaza a un miembro en la clase base \"{0}\".", + "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116": "Este miembro debe tener un modificador \"override\" porque reemplaza a un método abstracto que se declara en la clase base \"{0}\".", + "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Solo se puede hacer referencia a este módulo con las importaciones o exportaciones de ECMAScript mediante la activación de la marca \"{0}\" y la referencia a su exportación predeterminada.", + "This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag_2594": "Este módulo se declara con \"export =\" y solo se puede usar con una importación predeterminada cuando se usa la marca \"{0}\".", + "This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2_6807": "Esta operación se puede simplificar. Este turno es idéntico a \"{0} {1} {2}\".", + "This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation_7012": "Esta sobrecarga devuelve implícitamente el tipo “{0}” porque carece de una anotación de tipo de valor devuelto.", + "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394": "Esta signatura de sobrecarga no es compatible con su signatura de implementación.", + "This_parameter_is_not_allowed_with_use_strict_directive_1346": "Este parámetro no se permite con la directiva \"use strict\".", + "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120": "Esta propiedad de parámetro debe tener un comentario JSDoc con una etiqueta '@override' porque invalida un miembro de la clase base '{0}'.", + "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115": "Esta propiedad de parámetro debe tener un modificador \"override\" porque reemplaza a un miembro en la clase base \"{0}\".", + "This_regular_expression_flag_cannot_be_toggled_within_a_subpattern_1509": "Esta marca de expresión regular no se puede alternar dentro de un subpatrón.", + "This_regular_expression_flag_is_only_available_when_targeting_0_or_later_1501": "Esta marca de expresión regular solo está disponible cuando el destino es “{0}” o posterior.", + "This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolv_2876": "Esta ruta de acceso de importación relativa no es segura de reescribir porque parece un nombre de archivo, pero realmente se resuelve en \"{0}\".", + "This_spread_always_overwrites_this_property_2785": "Este elemento de propagación siempre sobrescribe esta propiedad.", + "This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled_1294": "Esta sintaxis no se permite cuando \"erasableSyntaxOnly\" está habilitado.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060": "Esta sintaxis está reservada en archivos con la extensión .mts o .CTS. Agregue una coma o una restricción explícita al final.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059": "Esta sintaxis se reserva a archivos con la extensión .mts o .cts. En su lugar, use una expresión \"as\".", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere un asistente importado, pero no se puede encontrar el módulo \"{0}\".", + "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Esta sintaxis requiere una aplicación auxiliar importada denominada \"{1}\", que no existe en \"{0}\". Considere la posibilidad de actualizar la versión de \"{0}\".", + "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Esta sintaxis requiere un asistente importado denominado \"{1}\" con parámetros de {2}, que no es compatible con el de \"{0}\". Pruebe a actualizar la versión de \"{0}\".", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Este parámetro de tipo podría necesitar una restricción \"extends {0}\".", + "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Este uso de \"import\" no es válido. Se pueden escribir llamadas \"import()\", pero deben tener paréntesis y no pueden tener argumentos de tipo.", + "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482": "Para convertir este archivo en un módulo ECMAScript, agregue el campo `\"type\": \"module\"` a \"{0}\"'.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481": "Para convertir este archivo en un módulo ECMAScript, cambie su extensión de archivo a \"{0}\" o agregue el campo `\"type\": \"module\"` a \"{1}\".", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480": "Para convertir este archivo en un módulo ECMAScript, cambie su extensión de archivo a \"{0}\" o cree un archivo package.json local con '{ \"type\": \"module\" }'.", + "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483": "Para convertir este archivo en un módulo ECMAScript, cree un archivo package.json local con `{ \"type\": \"module\" }`.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Las expresiones \"await\" de nivel superior solo se permiten cuando la opción \"module\" está establecida en \"es2022\", \"esnext\", \"system\", \"node16\", \"node18\" \"nodenext\" o \"preserve\", y la opción \"target\" está establecida en \"es2017\" o superior.", + "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854": "Las declaraciones \"await using\" de nivel superior solo se permiten cuando la opción \"module\" está establecida en \"es2022\", \"esnext\", \"system\", \"node16\", \"node18\", \"nodenext\" o \"preserve\", y la opción \"target\" está establecida en \"es2017\" o superior.", + "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Las declaraciones de nivel superior de los archivos .d.ts deben comenzar con un modificador \"declare\" o \"export\".", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_nod_1432": "Los bucles \"for await\" de nivel superior solo se permiten cuando la opción \"module\" está establecida en \"es2022\", \"esnext\", \"system\", \"node16\", \"node18\", \"nodenext\" o \"preserve\", y la opción \"target\" está establecida en \"es2017\" o superior.", + "Trailing_comma_not_allowed_1009": "No se permite la coma final.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilar cada archivo como un módulo aparte (parecido a \"ts.transpileModule\").", + "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Pruebe \"npm i --save-dev @types/{1}\" si existe o agregue un nuevo archivo de declaración (.d.ts) que incluya \"declare module '{0}';\".", + "Trying_other_entries_in_rootDirs_6110": "Se probarán otras entradas de \"rootDirs\".", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Probando la sustitución '{0}', ubicación candidata para el módulo: '{1}'.", + "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493": "El tipo de tupla \"{0}\" de longitud \"{1}\" no tiene ningún elemento en el índice \"{2}\".", + "Tuple_type_arguments_circularly_reference_themselves_4110": "Los argumentos de tipo de tupla se hacen referencia a sí mismos de forma circular.", + "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802": "El tipo \"{0}\" solo puede iterarse cuando se usa la marca \"--downlevelIteration\" o con un valor \"--target\" de \"es2015\" o superior.", + "Type_0_cannot_be_used_as_an_index_type_2538": "El tipo '{0}' no se puede usar como tipo de índice.", + "Type_0_cannot_be_used_to_index_type_1_2536": "El tipo '{0}' no se puede usar para indexar el tipo '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "El tipo '{0}' no cumple la restricción '{1}'.", + "Type_0_does_not_satisfy_the_expected_type_1_1360": "El tipo \"{0}\" no satisface el tipo esperado \"{1}\".", + "Type_0_has_no_call_signatures_2757": "El tipo \"{0}\" no tiene signaturas de llamada.", + "Type_0_has_no_construct_signatures_2761": "El tipo \"{0}\" no tiene signaturas de construcción.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "El tipo '{0}' no tiene una signatura de índice correspondiente al tipo '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "El tipo \"{0}\" no tiene propiedades en común con el tipo \"{1}\".", + "Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable_2635": "El tipo \"{0}\" no tiene firmas para las que sea aplicable la lista de argumentos de tipo.", + "Type_0_is_generic_and_can_only_be_indexed_for_reading_2862": "El tipo “{0}” es genérico y solo se puede indizar para lectura.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "Al tipo \"{0}\" le faltan las propiedades siguientes del tipo \"{1}\": {2}", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "Al tipo \"{0}\" le faltan las propiedades siguientes del tipo \"{1}\": {2} y {3} más.", + "Type_0_is_not_a_constructor_function_type_2507": "El tipo '{0}' no es un tipo de función de constructor.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compa_1055": "El tipo “{0}” no es un tipo de valor devuelto válido para una función asincrónica en ES5, porque no hace referencia a un valor de constructor compatible con promesas.", + "Type_0_is_not_an_array_type_2461": "'{0}' no es un tipo de matriz.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "'{0}' no es un tipo de matriz o un tipo de cadena.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "El tipo \"{0}\" no es un tipo de matriz o un tipo de cadena o no tiene un método \"[Symbol.iterator]()\" que devuelve un iterador.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "El tipo \"{0}\" no es un tipo de matriz o no tiene un método \"[Symbol.iterator]()\" que devuelve un iterador.", + "Type_0_is_not_assignable_to_type_1_2322": "El tipo '{0}' no se puede asignar al tipo '{1}'.", + "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820": "El tipo '{0}' no se puede asignar al tipo '{1}'. ¿Quería decir \"{2}\"?", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "El tipo \"{0}\" no se puede asignar al tipo \"{1}\". Existen dos tipos distintos con este nombre, pero no están relacionados.", + "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636": "El tipo “{0}” no se puede asignar al tipo “{1}”, tal y como implica la anotación de desviación.", + "Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values_18033": "El tipo “{0}” no se puede asignar al tipo “{1}” según sea necesario para los valores de miembro de enumeración calculados.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375": "El tipo '{0}' no se puede asignar al tipo '{1}' con 'exactOptionalPropertyTypes: true'. Considere la posibilidad de agregar \"undefined\" a los tipos de propiedades del destino.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "El tipo '{0}' no se puede asignar al tipo '{1}' con 'exactOptionalPropertyTypes: true'. Considere la posibilidad de agregar \"undefined\" al tipo del destino.", + "Type_0_is_not_comparable_to_type_1_2678": "El tipo '{0}' no se puede comparar con el tipo '{1}'.", + "Type_0_is_not_generic_2315": "El tipo '{0}' no es genérico.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "El tipo \"{0}\" puede representar un valor primitivo, que no se permite como operando derecho del operador \"in\".", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "El tipo \"{0}\" debe tener un método \"[Symbol.asyncIterator]()\" que devuelve un iterador de asincronía.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "El tipo \"{0}\" debe tener un método \"[Symbol.iterator]()\" que devuelve un iterador.", + "Type_0_provides_no_match_for_the_signature_1_2658": "El tipo \"{0}\" no proporciona ninguna coincidencia para la signatura \"{1}\".", + "Type_0_recursively_references_itself_as_a_base_type_2310": "El tipo '{0}' se hace referencia a sí mismo de forma recursiva como tipo base.", + "Type_Checking_6248": "Comprobación de tipos", + "Type_alias_0_circularly_references_itself_2456": "El alias de tipo '{0}' se hace referencia a sí mismo de forma circular.", + "Type_alias_must_be_given_a_name_1439": "Se debe asignar un nombre al alias de tipo.", + "Type_alias_name_cannot_be_0_2457": "El nombre del alias de tipo no puede ser \"{0}\".", + "Type_aliases_can_only_be_used_in_TypeScript_files_8008": "Los alias de tipo solo se pueden usar en los archivos TypeScript.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Una anotación de tipo no puede aparecer en una declaración de constructor.", + "Type_annotations_can_only_be_used_in_TypeScript_files_8010": "Las anotaciones de tipo solo se pueden usar en los archivos TypeScript.", + "Type_argument_expected_1140": "Se esperaba un argumento de tipo.", + "Type_argument_list_cannot_be_empty_1099": "La lista de argumentos de tipo no puede estar vacía.", + "Type_arguments_can_only_be_used_in_TypeScript_files_8011": "Los argumentos de tipo solo se pueden usar en los archivos TypeScript.", + "Type_arguments_for_0_circularly_reference_themselves_4109": "Los argumentos de tipo de \"{0}\" se hacen referencia a sí mismos de forma circular.", + "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016": "Las expresiones de aserción de tipo solo se pueden usar en los archivos TypeScript.", + "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626": "El tipo en la posición {0} del origen no es compatible con el tipo en la posición {1} del destino.", + "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627": "El tipo en las posiciones {0} a {1} del origen no es compatible con el tipo en la posición {2} del destino.", + "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039": "El tipo que contiene el nombre privado “{0}” no se puede usar con --isolatedDeclarations.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Archivos de declaración de tipos que se incluirán en la compilación.", + "Type_expected_1110": "Se esperaba un tipo.", + "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456": "Las aserciones de importación de tipos deben tener exactamente una clave - \"resolution-mode\" - con el valor \"import\" o \"require\".", + "Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1464": "Los atributos de importación de tipos deben tener exactamente una clave, “resolution-mode”, con el valor “import” o “require”.", + "Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute_1542": "La importación de tipos de un módulo ECMAScript desde un módulo CommonJS debe tener un atributo \"resolution-mode\".", + "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589": "La creación de una instancia de tipo es excesivamente profunda y posiblemente infinita.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Se hace referencia al tipo directa o indirectamente en la devolución de llamada de entrega de su propio método \"then\".", + "Type_library_referenced_via_0_from_file_1_1402": "Biblioteca de tipos a la que se hace referencia mediante \"{0}\" desde el archivo \"{1}\"", + "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Biblioteca de tipos a la que se hace referencia mediante \"{0}\" desde el archivo \"{1}\" con el valor packageId \"{2}\"", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "El tipo de operando \"await\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "El tipo de valor de la propiedad calculada es \"{0}\", que no se puede asignar al tipo \"{1}\".", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "El tipo de variable miembro de instancia \"{0}\" no puede hacer referencia al identificador \"{1}\" declarado en el constructor.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "El tipo de elementos iterados de un operando \"yield*\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "El tipo de propiedad \"{0}\" hace referencia circular a sí misma en el tipo asignado \"{1}\".", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "El tipo de operando \"yield\" en un generador asincrónico debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", + "Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribut_1541": "La importación de solo tipo de un módulo ECMAScript desde un módulo CommonJS debe tener un atributo \"resolution-mode\".", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "El tipo se origina en esta importación. No se puede construir ni llamar a una importación de estilo de espacio de nombres y provocará un error en tiempo de ejecución. Considere la posibilidad de usar una importación predeterminada o require aquí en su lugar.", + "Type_parameter_0_has_a_circular_constraint_2313": "El parámetro de tipo '{0}' tiene una restricción circular.", + "Type_parameter_0_has_a_circular_default_2716": "El parámetro de tipo \"{0}\" tiene un valor circular predeterminado.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "El parámetro de tipo '{0}' de la signatura de llamada de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "El parámetro de tipo '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "El parámetro de tipo '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "El parámetro de tipo '{0}' de la función exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "El parámetro de tipo '{0}' de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103": "El parámetro de tipo \"{0}\" del tipo de objeto asignado exportado usa un nombre privado \"{1}\".", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "El parámetro de tipo '{0}' del alias del tipo exportado tiene o usa un nombre privado '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "El parámetro de tipo '{0}' del método de la interfaz exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "El parámetro de tipo '{0}' del método público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "El parámetro de tipo '{0}' del método estático público de la clase exportada tiene o usa el nombre privado '{1}'.", + "Type_parameter_declaration_expected_1139": "Se esperaba una declaración de parámetros de tipo.", + "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004": "Las declaraciones de parámetros de tipo solo se pueden usar en los archivos TypeScript.", + "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744": "Los valores predeterminados del parámetro de tipo solo pueden hacer referencia a parámetros de tipo declarados previamente.", + "Type_parameter_list_cannot_be_empty_1098": "La lista de parámetros de tipo no puede estar vacía.", + "Type_parameter_name_cannot_be_0_2368": "El nombre del parámetro de tipo no puede ser \"{0}\".", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Los parámetros de tipo no pueden aparecer en una declaración de constructor.", + "Type_predicate_0_is_not_assignable_to_1_1226": "El predicado de tipo '{0}' no se puede asignar a '{1}'.", + "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799": "El tipo genera un tipo de tupla demasiado grande para representarlo.", + "Type_reference_directive_0_was_not_resolved_6120": "======== No se resolvió la directiva de referencia de tipo '{0}'. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La directiva de referencia de tipo '{0}' se resolvió correctamente como '{1}', principal: {2}. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== La directiva de referencia de tipo \"{0}\" se resolvió correctamente como \"{1}\" con el identificador de paquete \"{2}\", principal: {3}. ========", + "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037": "Las expresiones de satisfacción de tipo solo se pueden usar en archivos TypeScript.", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Los tipos no pueden aparecer en declaraciones de exportación en archivos JavaScript.", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Los tipos tienen declaraciones independientes de una propiedad '{0}' privada.", + "Types_of_construct_signatures_are_incompatible_2419": "Los tipos de signaturas de construcción son incompatibles.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Los tipos de parámetros '{0}' y '{1}' no son compatibles.", + "Types_of_property_0_are_incompatible_2326": "Los tipos de propiedad '{0}' no son compatibles.", + "Unable_to_open_file_0_6050": "No se puede abrir el archivo '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "No se puede resolver la signatura de elemento Decorator de una clase cuando se llama como expresión.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "No se puede resolver la signatura de elemento Decorator de un método cuando se llama como expresión.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "No se puede resolver la signatura de elemento Decorator de un parámetro cuando se llama como expresión.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "No se puede resolver la signatura de elemento Decorator de una propiedad cuando se llama como expresión.", + "Undetermined_character_escape_1513": "Escape de caracteres no determinado.", + "Unexpected_0_Did_you_mean_to_escape_it_with_backslash_1508": "“{0}” inesperado. ¿Desea escaparlo con barra diagonal inversa?", + "Unexpected_end_of_text_1126": "Final de texto inesperado.", + "Unexpected_keyword_or_identifier_1434": "Identificador o palabra clave inesperados.", + "Unexpected_token_1012": "Token inesperado.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token inesperado. Se esperaba un constructor, un método, un descriptor de acceso o una propiedad.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Se esperaba un nombre de parámetro de tipo sin llaves.", + "Unexpected_token_Did_you_mean_or_gt_1382": "Token inesperado. ¿Pretendía usar \"{'>'}\" o \">\"?", + "Unexpected_token_Did_you_mean_or_rbrace_1381": "Token inesperado. ¿Pretendía usar \"{'}'}\" o \"}\"?", + "Unexpected_token_expected_1179": "Token inesperado. Se esperaba \"{\".", + "Unicode_escape_sequence_cannot_appear_here_17021": "La secuencia de escape Unicode no puede aparecer aquí.", + "Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_se_1538": "Las secuencias de escape Unicode solo están disponibles cuando se establecen las marcas Unicode (u) o Unicode Sets (v).", + "Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v__1530": "Las expresiones de valor de propiedad Unicode solo están disponibles cuando se establecen las marcas Unicode (u) o Unicode Sets (v).", + "Unknown_Unicode_property_name_1524": "Nombre de propiedad Unicode desconocido.", + "Unknown_Unicode_property_name_or_value_1529": "Nombre o valor de propiedad Unicode desconocido.", + "Unknown_Unicode_property_value_1526": "Valor de propiedad Unicode desconocido.", + "Unknown_build_option_0_5072": "Opción de compilación \"{0}\" desconocida.", + "Unknown_build_option_0_Did_you_mean_1_5077": "Opción de compilación \"{0}\" desconocida. ¿Pretendía usar \"{1}\"?", + "Unknown_compiler_option_0_5023": "Opción '{0}' del compilador desconocida.", + "Unknown_compiler_option_0_Did_you_mean_1_5025": "Opción del compilador \"{0}\" desconocida. ¿Pretendía usar \"{1}\"?", + "Unknown_keyword_or_identifier_Did_you_mean_0_1435": "Identificador o palabra clave desconocidos. ¿Quiso decir \"{0}\"?", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Opción 'excludes' desconocida. ¿Quería decir 'exclude'?", + "Unknown_regular_expression_flag_1499": "Marca de expresión regular desconocida.", + "Unknown_type_acquisition_option_0_17010": "Opción '{0}' de adquisición de tipos desconocida.", + "Unknown_type_acquisition_option_0_Did_you_mean_1_17018": "Opción de adquisición de tipos \"{0}\" desconocida. ¿Pretendía usar \"{1}\"?", + "Unknown_watch_option_0_5078": "Opción de inspección \"{0}\" desconocida.", + "Unknown_watch_option_0_Did_you_mean_1_5079": "Opción de inspección \"{0}\" desconocida. ¿Pretendía usar \"{1}\"?", + "Unreachable_code_detected_7027": "Se ha detectado código inaccesible.", + "Unterminated_Unicode_escape_sequence_1199": "Secuencia de escape Unicode sin terminar.", + "Unterminated_quoted_string_in_response_file_0_6045": "Cadena entrecomillada sin terminar en el archivo de respuesta '{0}'.", + "Unterminated_regular_expression_literal_1161": "Literal de expresión regular sin terminar.", + "Unterminated_string_literal_1002": "Literal de cadena sin terminar.", + "Unterminated_template_literal_1160": "Literal de plantilla sin terminar.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Las llamadas a función sin tipo no pueden aceptar argumentos de tipo.", + "Unused_label_7028": "Etiqueta no usada.", + "Unused_ts_expect_error_directive_2578": "Directiva \"@ts-expect-error\" no usada.", + "Update_import_from_0_90058": "Actualizar importación desde “{0}”", + "Update_modifiers_of_0_90061": "Actualizar modificadores de “{0}”", + "Updating_output_timestamps_of_project_0_6359": "Actualizando las marcas de hora de salida del proyecto \"{0}\"...", + "Updating_unchanged_output_timestamps_of_project_0_6371": "Actualizando las marcas de hora de salida no modificadas del proyecto \"{0}\"...", + "Use_0_95174": "Usar `{0}`.", + "Use_0_instead_5106": "Use “{0}” en su lugar.", + "Use_Number_isNaN_in_all_conditions_95175": "Use \"Number.isNaN\" en todas las condiciones.", + "Use_element_access_for_0_95145": "Usar acceso de elemento para \"{0}\"", + "Use_element_access_for_all_undeclared_properties_95146": "Use el acceso de elemento para todas las propiedades no declaradas.", + "Use_import_type_95180": "Usar “import type”", + "Use_synthetic_default_member_95016": "Use el miembro sintético \"default\".", + "Use_the_package_json_exports_field_when_resolving_package_imports_6408": "Use el campo “exports” de package.json al resolver las importaciones de paquetes.", + "Use_the_package_json_imports_field_when_resolving_imports_6409": "Use el campo “imports” de package.json al resolver importaciones.", + "Use_type_0_95181": "Usar “type {0}”", + "Using_0_subpath_1_with_target_2_6404": "Usando '{0}' subruta '{1}' con destino '{2}'.", + "Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found_2879": "El uso de fragmentos JSX requiere que el generador de fragmentos \"{0}\" esté en el ámbito, pero no se encontró.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "El uso de una cadena en una instrucción \"for...of\" solo se admite en ECMAScript 5 y versiones posteriores.", + "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Con --build, -b hará que tsc se comporte más como un orquestador de compilación que como un compilador. Se usa para desencadenar la compilación de proyectos compuestos, sobre los que puede obtener más información en {0}", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Uso de las opciones del compilador de redireccionamiento de la referencia del proyecto \"{0}\".", + "VERSION_6036": "VERSIÓN", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "El valor de tipo \"{0}\" no tiene propiedades en común con el tipo \"{1}\". ¿Realmente quiere llamarlo?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "No se puede llamar a un valor de tipo '{0}'. ¿Pretendía incluir \"new\"?", + "Variable_0_implicitly_has_an_1_type_7005": "La variable '{0}' tiene un tipo '{1}' implícitamente.", + "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043": "La variable \"{0}\" tiene un tipo \"{1}\" de forma implícita, pero se puede inferir un tipo más adecuado a partir del uso.", + "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046": "La variable \"{0}\" tiene un tipo \"{1}\" de forma implícita en algunas ubicaciones, pero se puede inferir un tipo más adecuado a partir del uso.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "La variable '{0}' tiene implícitamente el tipo '{1}' en algunos sitios donde no se puede determinar su tipo.", + "Variable_0_is_used_before_being_assigned_2454": "La variable '{0}' se usa antes de asignarla.", + "Variable_declaration_expected_1134": "Se esperaba una declaración de variable.", + "Variable_declaration_list_cannot_be_empty_1123": "La lista de declaraciones de variable no puede estar vacía.", + "Variable_declaration_not_allowed_at_this_location_1440": "No se permite una declaración de variable en esta ubicación.", + "Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9010": "La variable debe tener una anotación de tipo explícita con --isolatedDeclarations.", + "Variables_with_multiple_declarations_cannot_be_inlined_95186": "Las variables con varias declaraciones no se pueden insertar.", + "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625": "El elemento variádico en la posición {0} del origen no coincide con el elemento en la posición {1} del destino.", + "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637": "Las anotaciones de varianza solo se admiten en alias de tipo para los tipos objeto, función, constructor y asignado.", + "Version_0_6029": "Versión {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file_95110": "Visite https://aka.ms/tsconfig para obtener más información acerca de este archivo", + "WATCH_OPTIONS_6918": "OPCIONES DE INSPECCIÓN", + "Watch_and_Build_Modes_6250": "Modos de compilación e inspección", + "Watch_input_files_6005": "Inspeccionar archivos de entrada.", + "Watch_option_0_requires_a_value_of_type_1_5080": "La opción \"{0}\" de inspección requiere un valor de tipo {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Solo se puede escribir un tipo para '{0}' agregando aquí un tipo para todo el parámetro.", + "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Al asignar funciones, compruebe que efectivamente los parámetros y los valores devueltos son compatibles con el subtipo.", + "When_type_checking_take_into_account_null_and_undefined_6699": "Al comprobar tipos, tenga en cuenta \"null\" y \"undefined\".", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Si se debe mantener la salida de la consola no actualizada en el modo de inspección en lugar de borrar la pantalla.", + "Wrap_all_invalid_characters_in_an_expression_container_95109": "Encapsular todos los caracteres no válidos en un contenedor de expresiones", + "Wrap_all_invalid_decorator_expressions_in_parentheses_95195": "Incluir todas las expresiones de decorador no válidas entre paréntesis", + "Wrap_all_object_literal_with_parentheses_95116": "Encapsular todos los literales de objeto entre paréntesis", + "Wrap_all_unparented_JSX_in_JSX_fragment_95121": "Encapsular todos los JSX no primarios en el fragmento de JSX", + "Wrap_in_JSX_fragment_95120": "Ajustar en fragmento de JSX", + "Wrap_in_parentheses_95194": "Incluir entre paréntesis", + "Wrap_invalid_character_in_an_expression_container_95108": "Encapsular el carácter no válido en un contenedor de expresiones", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Encapsular el cuerpo siguiente entre paréntesis, lo cual debe ser un literal de objeto", + "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Puede obtener información sobre todas las opciones del compilador en {0}", + "You_cannot_rename_a_module_via_a_global_import_8031": "No se puede cambiar el nombre de un módulo mediante una importación global.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "No se puede cambiar el nombre de los elementos definidos en una carpeta 'node_modules'.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "No se puede cambiar el nombre de los elementos definidos en otra carpeta 'node_modules'.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "No se puede cambiar el nombre de elementos definidos en la biblioteca TypeScript estándar.", + "You_cannot_rename_this_element_8000": "No se puede cambiar el nombre a este elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" no acepta suficientes argumentos para utilizarse como decorador aquí. ¿Pretendía llamar primero y escribir \"@{0}()\"?", + "_0_and_1_index_signatures_are_incompatible_2330": "Las signaturas de índice \"{0}\" y \"{1}\" no son compatibles.", + "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Las operaciones \"{0}\" y \"{1}\" no se pueden mezclar sin paréntesis.", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" se especifica dos veces. El atributo denominado \"{0}\" se sobrescribirá.", + "_0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17019": "“{0}” al final de un tipo no es una sintaxis de TypeScript válida. ¿Pretendía escribir “{1}”?", + "_0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17020": "“{0}” al principio de un tipo no es una sintaxis de TypeScript válida. ¿Pretendía escribir “{1}”?", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "\"{0}\" solo se puede importar si se activa la marca \"esModuleInterop\" y se usa una importación predeterminada.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "\"{0}\" solo se puede importar si se usa una importación predeterminada.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "\"{0}\" solo se puede importar si se usa una llamada a \"require\" o bien se activa la marca \"esModuleInterop\" y se usa una importación predeterminada.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "\"{0}\" solo se puede importar si se usa una llamada a \"require\" o una importación predeterminada.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "\"{0}\" solo se puede importar si se usa \"import {1} = require({2})\" o una importación predeterminada.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "\"{0}\" solo se puede importar si se usa \"import {1} = require({2})\" o bien se activa la marca \"esModuleInterop\" y se usa una importación predeterminada.", + "_0_cannot_be_used_as_a_JSX_component_2786": "No se puede usar \"{0}\" como componente JSX.", + "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "No se puede usar \"{0}\" como valor porque se exportó mediante \"export type\".", + "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "No se puede usar \"{0}\" como valor porque se importó mediante \"import type\".", + "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "Los componentes \"{0}\" no aceptan el texto como elemento secundario. El texto de JSX tiene el tipo \"string\", pero el tipo que se esperaba de \"{1}\" es \"{2}\".", + "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082": "Puede crearse una instancia de \"{0}\" con un tipo arbitrario que podría no estar relacionado con \"{1}\".", + "_0_declarations_can_only_be_declared_inside_a_block_1156": "Las declaraciones “{0}” solo se pueden declarar dentro de un bloque.", + "_0_declarations_can_only_be_used_in_TypeScript_files_8006": "Las declaraciones \"{0}\" solo se pueden usar en los archivos TypeScript.", + "_0_declarations_may_not_have_binding_patterns_1492": "Las declaraciones “{0}” no pueden tener patrones de enlace.", + "_0_declarations_must_be_initialized_1155": "Las declaraciones “{0}” deben inicializarse.", + "_0_expected_1005": "Se esperaba '{0}'.", + "_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is__18055": "“{0}” tiene un tipo de cadena, pero debe tener sintaxis de cadena reconocible sintácticamente cuando “isolatedModules” está habilitado.", + "_0_has_no_exported_member_named_1_Did_you_mean_2_2724": "\"{0}\" no tiene ningún miembro exportado con el nombre \"{1}\". ¿Pretendía usar \"{2}\"?", + "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050": "\"{0}\" tiene un tipo de valor devuelto \"{1}\" de forma implícita, pero se puede inferir un tipo más adecuado a partir del uso.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo de valor devuelto y se hace referencia a este directa o indirectamente en una de sus expresiones return.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo y se hace referencia a este directa o indirectamente en su propio inicializador.", + "_0_index_signatures_are_incompatible_2634": "Las signaturas de índice \"{0}\" no son compatibles.", + "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "El tipo de índice \"{0}\"' \"{1}\" no se puede asignar al tipo de índice \"{2}\" \"{3}\".", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' es un elemento primitivo, pero '{1}' es un objeto contenedor. Use '{0}' preferentemente cuando sea posible.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' es un tipo y no se puede importar en archivos JavaScript. Use '{1}' en una anotación de tipo JSDoc.", + "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled_1484": "“{0}” es un tipo y debe importarse mediante una importación de solo tipo cuando “verbatimModuleSyntax” está habilitado.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}' es un cambio de nombre de '{1}' sin usar. ¿Quería usarlo como una anotación de tipo?", + "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "\"{0}\" puede asignarse a la restricción de tipo \"{1}\", pero no se pudo crear una instancia de \"{1}\" con un subtipo distinto de la restricción \"{2}\".", + "_0_is_automatically_exported_here_18044": "'{0}' se exporta automáticamente aquí.", + "_0_is_declared_but_its_value_is_never_read_6133": "Se declara \"{0}\", pero su valor no se lee nunca.", + "_0_is_declared_but_never_used_6196": "\"{0}\" se declara pero nunca se utiliza.", + "_0_is_declared_here_2728": "\"{0}\" se declara aquí.", + "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611": "\"{0}\" se define como propiedad en la clase \"{1}\", pero se reemplaza aquí en \"{2}\" como descriptor de acceso.", + "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "\"{0}\" se define como descriptor de acceso en la clase \"{1}\", pero se reemplaza aquí en \"{2}\" como propiedad de instancia.", + "_0_is_deprecated_6385": "\"{0}\" está en desuso.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" no es una propiedad Meta válida para la palabra clave \"{1}\". ¿Pretendía usar \"{2}\"?", + "_0_is_not_allowed_as_a_parameter_name_1390": "No se permite “{0}” como nombre de parámetro.", + "_0_is_not_allowed_as_a_variable_declaration_name_1389": "No se permite \"{0}\" como nombre de declaración de variable.", + "_0_is_of_type_unknown_18046": "\"{0}\" es de tipo \"unknown\".", + "_0_is_possibly_null_18047": "\"{0}\" es posiblemente \"null\".", + "_0_is_possibly_null_or_undefined_18049": "\"{0}\" es posiblemente \"null\" o \"undefined\".", + "_0_is_possibly_undefined_18048": "\"{0}\" es posiblemente \"undefined\".", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Se hace referencia a '{0}' directa o indirectamente en su propia expresión base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Se hace referencia a '{0}' directa o indirectamente en su propia anotación de tipo.", + "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783": "\"{0}\" se ha especificado más de una vez, por lo que se sobrescribirá este uso.", + "_0_list_cannot_be_empty_1097": "La lista '{0}' no puede estar vacía.", + "_0_modifier_already_seen_1030": "El modificador '{0}' ya se ha visto.", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias_1274": "El modificador “{0}” solo puede aparecer en un parámetro de tipo de una clase, interfaz o alias de tipo", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class_1277": "El modificador “{0}” solo puede aparecer en un parámetro de tipo de una función, método o clase", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "El modificador '{0}' no puede aparecer en una declaración de constructor.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "El modificador '{0}' no puede aparecer en un módulo o un elemento de espacio de nombres.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "El modificador '{0}' no puede aparecer en un parámetro.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "El modificador '{0}' no puede aparecer en un miembro de tipo.", + "_0_modifier_cannot_appear_on_a_type_parameter_1273": "El modificador “{0}” no puede aparecer en un parámetro de tipo", + "_0_modifier_cannot_appear_on_a_using_declaration_1491": "El modificador “{0}” no puede aparecer en una declaración “using”.", + "_0_modifier_cannot_appear_on_an_await_using_declaration_1495": "El modificador “{0}” no puede aparecer en una declaración “await using”.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "El modificador '{0}' no puede aparecer en una signatura de índice.", + "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031": "El modificador \"{0}\" no puede aparecer en elementos de clase de este tipo.", + "_0_modifier_cannot_be_used_here_1042": "El modificador '{0}' no se puede usar aquí.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "El modificador '{0}' no se puede usar en un contexto de ambiente.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "El modificador '{0}' no se puede usar con el modificador '{1}'.", + "_0_modifier_cannot_be_used_with_a_private_identifier_18019": "El modificador \"{0}\" no se puede usar con un identificador privado.", + "_0_modifier_must_precede_1_modifier_1029": "El modificador \"{0}\" debe preceder al modificador \"{1}\".", + "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531": "“\\{0}” debe ir seguido de una expresión de valor de propiedad Unicode entre llaves.", + "_0_needs_an_explicit_type_annotation_2782": "\"{0}\" necesita una anotación de tipo explícito.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' solo hace referencia a un tipo, pero aquí se usa como espacio de nombres.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' solo hace referencia a un tipo, pero aquí se usa como valor.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690": "\"{0}\" solo hace referencia a un tipo, pero aquí se usa como valor. ¿Pretendía usar \"{1} en {0}\"?", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585": "\"{0}\" solo hace referencia a un tipo, pero aquí se usa como valor. ¿Necesita cambiar la biblioteca de destino? Pruebe a cambiar la opción del compilador \"lib\" a es2015 o posterior.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' hace referencia a un elemento UMD global, pero el archivo actual es un módulo. Puede agregar una importación en su lugar.", + "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749": "\"{0}\" hace referencia a un valor, pero aquí se usa como tipo. ¿Quiso decir \"typeof {0}\"?", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1291": "“{0}” se resuelve en un tipo y debe marcarse como de solo tipo en este archivo antes de volver a exportar cuando “{1}” está habilitado. Considere la posibilidad de usar “import type” donde se importa “{0}”.", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1292": "“{0}” se resuelve en un tipo y debe marcarse como de solo tipo en este archivo antes de volver a exportar cuando “{1}” está habilitado. Considere la posibilidad de usar “export type { {0} as default }”.", + "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimMo_1485": "“{0}” se resuelve en una declaración de solo tipo y debe importarse mediante una importación de solo tipo cuando “verbatimModuleSyntax” está habilitado.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1289": "“{0}” se resuelve en una declaración de solo tipo y debe marcarse como de solo tipo en este archivo antes de volver a exportar cuando “{1}” está habilitado. Considere la posibilidad de usar “import type” donde se importa “{0}”.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1290": "“{0}” se resuelve en una declaración de solo tipo y debe marcarse como de solo tipo en este archivo antes de volver a exportar cuando “{1}” está habilitado. Considere la posibilidad de usar “export type { {0} as default }”.", + "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_1448": "“{0}” se resuelve como una declaración de solo tipo y debe volverse a exportar con un tipo de reexportación solo cuando esté habilitada la opción “{1}”.", + "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258": "\"{0}\" debe establecerse dentro del objeto \"compilerOptions\" del archivo .json de configuración", + "_0_tag_already_specified_1223": "La etiqueta '{0}' ya se ha especificado.", + "_0_was_also_declared_here_6203": "\"{0}\" también se ha declarado aquí.", + "_0_was_exported_here_1377": "\"{0}\" se ha exportado aquí.", + "_0_was_imported_here_1376": "\"{0}\" se ha importado aquí.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}' carece de una anotación de tipo de valor devuelto, pero tiene un tipo de valor devuelto '{1}' implícitamente.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055": "\"{0}\" carece de una anotación de tipo de valor devuelto, pero tiene un tipo yield \"{1}\" de forma implícita.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "El modificador 'abstract' solo puede aparecer en una declaración de propiedad, clase o método.", + "accessor_modifier_can_only_appear_on_a_property_declaration_1275": "El modificador 'accessor' solo puede aparecer en una declaración de propiedad.", + "and_here_6204": "y aquí.", + "arguments_cannot_be_referenced_in_property_initializers_2815": "no se puede hacer referencia a «arguments» en los inicializadores de propiedad.", + "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476": "\"auto\": trate los archivos con importaciones, exportaciones, import.meta, jsx (con jsx: react-jsx) o formato esm (con el módulo: node16+) como módulos.", + "await_expression_cannot_be_used_inside_a_class_static_block_18037": "La expresión “await” no se puede usar dentro de un bloque estático de clase.", + "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375": "Las expresiones \"await\" solo se permiten en el nivel superior de un archivo cuando el archivo es un módulo, pero este archivo no tiene importaciones ni exportaciones. Considere la posibilidad de agregar un elemento \"export {}\" vacío para convertir este archivo en módulo.", + "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308": "Las expresiones \"await\" solo se permiten en las funciones asincrónicas y en los niveles superiores de los módulos.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Las expresiones \"await\" no se pueden usar en un inicializador de parámetros.", + "await_has_no_effect_on_the_type_of_this_expression_80007": "\"await\" no tiene efecto en el tipo de esta expresión.", + "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853": "Las declaraciones “await using” solo se permiten en el nivel superior de un archivo cuando el archivo es un módulo, pero este archivo no tiene importaciones ni exportaciones. Considere la posibilidad de agregar un elemento \"export {}\" vacío para convertir este archivo en módulo.", + "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852": "Las declaraciones “await using” solo se permiten en las funciones asincrónicas y en los niveles superiores de los módulos.", + "await_using_statements_cannot_be_used_inside_a_class_static_block_18054": "Las instrucciones “await using” no se pueden usar dentro de un bloque estático de clase.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "La opción \"baseUrl\" está establecida en \"{0}\", se usará este valor para resolver el nombre de módulo no relativo \"{1}\".", + "c_must_be_followed_by_an_ASCII_letter_1512": "“\\c” debe ir seguido de una letra ASCII.", + "can_only_be_used_at_the_start_of_a_file_18026": "\"#!\" solo se puede usar al principio de un archivo.", + "case_or_default_expected_1130": "Se esperaba \"case\" o \"default\".", + "catch_or_finally_expected_1472": "se esperaba \"catch\" o \"finally\".", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor no finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor \"NaN\" no permitido.", + "const_enum_member_initializers_must_be_constant_expressions_2474": "Los inicializadores de miembro de enumeración const deben ser expresiones constantes.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Las enumeraciones \"const\" solo se pueden usar en expresiones de acceso de propiedad o índice, o en la parte derecha de una declaración de importación, una asignación de exportación o una consulta de tipo.", + "constructor_cannot_be_used_as_a_parameter_property_name_2398": "El elemento \"constructor\" no se puede usar como nombre de propiedad de parámetro.", + "constructor_is_a_reserved_word_18012": "\"#constructor\" es una palabra reservada.", + "default_Colon_6903": "predeterminadas:", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "No se puede llamar a \"delete\" en un identificador en modo strict.", + "export_Asterisk_does_not_re_export_a_default_1195": "\"export *\" no vuelve a exportar una exportación predeterminada.", + "export_can_only_be_used_in_TypeScript_files_8003": "\"export =\" solo se puede usar en los archivos TypeScript.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "El modificador 'export' no se puede aplicar a módulos de ambiente ni aumentos de módulos, porque siempre están visibles.", + "extends_clause_already_seen_1172": "La cláusula \"extends\" ya se ha visto.", + "extends_clause_must_precede_implements_clause_1173": "La cláusula \"extends\" debe preceder a la cláusula \"implements\".", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "La cláusula \"extends\" de la clase \"{0}\" exportada tiene o usa el nombre privado \"{1}\".", + "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021": "La cláusula \"extends\" de la clase exportada tiene o usa el nombre privado \"{0}\".", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "La cláusula \"extends\" de la interfaz \"{0}\" exportada tiene o usa el nombre privado \"{1}\".", + "false_unless_composite_is_set_6906": "\"false\", a menos que se establezca \"composite\"", + "false_unless_strict_is_set_6905": "\"false\", a menos que se establezca como \"strict\"", + "file_6025": "archivo", + "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431": "Los bucles \"for await\" solo se permiten en el nivel superior de un archivo cuando el archivo es un módulo, pero este archivo no tiene importaciones ni exportaciones. Considere la posibilidad de agregar un elemento \"export {}\" vacío para convertir este archivo en módulo.", + "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103": "Los bucles \"for await\" solo se permiten en las funciones asincrónicas y en los niveles superiores de los módulos.", + "for_await_loops_cannot_be_used_inside_a_class_static_block_18038": "Los bucles “for await” no se pueden usar dentro de un bloque estático de clase.", + "get_and_set_accessors_cannot_declare_this_parameters_2784": "Los descriptores de acceso \"get\" y \"set\" no pueden declarar parámetros \"this\".", + "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908": "\"[]\", si se especifica \"archivos\"; de lo contrario, \"[\"**/*\"]5D;\"", + "implements_clause_already_seen_1175": "La cláusula \"implements\" ya se ha visto.", + "implements_clauses_can_only_be_used_in_TypeScript_files_8005": "Las cláusulas \"implements\" solo se pueden usar en los archivos TypeScript.", + "import_can_only_be_used_in_TypeScript_files_8002": "\"import ... =\" solo se puede usar en los archivos TypeScript.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Las declaraciones \"infer\" solo se permiten en la cláusula \"extends\" de un tipo condicional.", + "k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets_1510": "“\\k” debe ir seguido de un nombre de grupo de captura entre corchetes angulares.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "No se permite usar \"let\" como nombre en las declaraciones \"let\" o \"const\".", + "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010": "módulo === \"AMD\" o \"UMD\" o \"System\" o \"ES6\", después, \"Classic\", de lo contrario \"Node\"", + "module_system_or_esModuleInterop_6904": "módulo === \"system\" o esModuleInterop", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "La expresión \"new\", a cuyo destino le falta una signatura de construcción, tiene implícitamente un tipo \"any\".", + "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907": "\"[\"node_modules\", \"bower_components\", \"jspm_packages\"]\", más el valor de \"outDir\", si se especifica uno.", + "one_of_Colon_6900": "uno de:", + "one_or_more_Colon_6901": "uno o más:", + "options_6024": "Opciones", + "or_JSX_element_expected_1145": "Se esperaba \"{\" o un elemento JSX.", + "or_expected_1144": "Se esperaba \"{\" o \";\".", + "package_json_does_not_have_a_0_field_6100": "\"package.json\" no tiene un campo \"{0}\".", + "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "El archivo \"package.json\" no tiene ninguna entrada \"typesVersions\" que coincida con la versión \"{0}\".", + "package_json_had_a_falsy_0_field_6220": "El archivo \"package.json\" tenía un campo \"{0}\" false.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' tiene el campo '{1}' de '{0}' que hace referencia a '{2}'.", + "package_json_has_a_peerDependencies_field_6281": "“package.json” tiene un campo “peerDependencies”.", + "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209": "El archivo \"package.json\" tiene una entrada \"typesVersions\" \"{0}\" que no es un intervalo de SemVer válido.", + "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208": "El archivo \"package.json\" tiene una entrada \"typesVersions\" \"{0}\" que coincide con la versión del compilador \"{1}\"; se busca un patrón que coincida con el nombre de módulo \"{2}\".", + "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206": "El archivo \"package.json\" tiene un campo \"typesVersions\" con asignaciones de ruta de acceso específicas de la versión.", + "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274": "El ámbito de búsqueda package.json scope \"{0}\" asigna explícitamente el especificador \"{1}\" a NULL.", + "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275": "El ámbito package.json \"{0}\" tiene un tipo no válido para el destino del especificador \"{1}\"", + "package_json_scope_0_has_no_imports_defined_6273": "El ámbito de package.json \"{0}\" no tiene importaciones definidas.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Se ha especificado la opción 'paths'. Se buscará un patrón que coincida con el nombre de módulo '{0}'.", + "q_is_only_available_inside_character_class_1511": "“\\q” solo está disponible dentro de la clase de caracteres.", + "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521": "“\\q” debe ir seguido de alternativas de cadena entre llaves.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "El modificador 'readonly' solo puede aparecer en una declaración de propiedad o una signatura de índice.", + "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "El modificador de tipo \"readonly\" solo se permite en los tipos literales de matriz y de tupla.", + "require_call_may_be_converted_to_an_import_80005": "La llamada a \"require\" puede convertirse en una importación.", + "resolution_mode_can_only_be_set_for_type_only_imports_1454": "\"resolution-mode\" solo se puede establecer para importaciones solamente de tipo.", + "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "\"resolution-mode\" es la única clave válida para las aserciones de importación de tipos.", + "resolution_mode_is_the_only_valid_key_for_type_import_attributes_1463": "“resolution-mode” es la única clave válida para los atributos de importación de tipos.", + "resolution_mode_should_be_either_require_or_import_1453": "\"modo de resolución\" debe ser \"requerir\" o \"importar\".", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Se ha establecido la opción \"rootDirs\". Se usará para resolver el nombre de módulo relativo \"{0}\".", + "super_can_only_be_referenced_in_a_derived_class_2335": "Solo se puede hacer referencia a \"super\" en una clase derivada.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Solo se puede hacer referencia a 'super' en miembros de clases derivadas o expresiones de literal de objeto.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "No se puede hacer referencia a \"super\" en un nombre de propiedad calculada.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "No se puede hacer referencia a \"super\" en argumentos de constructor.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' se permite únicamente en miembros de expresiones de literal de objeto cuando la opción 'target' es 'ES2015' o superior.", + "super_may_not_use_type_arguments_2754": "\"super\" no puede usar argumentos de tipo.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "Debe llamarse a \"super\" antes de acceder a una propiedad de \"super\" en el constructor de una clase derivada.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "Debe llamarse a 'super' antes de acceder a 'this' en el constructor de una clase derivada.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "\"super\" debe estar seguido de una lista de argumentos o un acceso a miembros.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "El acceso a la propiedad \"super\" se permite únicamente en un constructor, una función miembro o un descriptor de acceso de miembro de una clase derivada.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "No se puede hacer referencia a \"this\" en un nombre de propiedad calculada.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "No se puede hace referencia a \"this\" en el cuerpo de un módulo o de un espacio de nombres.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "No se puede hacer referencia a \"this\" en un inicializador de propiedad estática.", + "this_cannot_be_referenced_in_current_location_2332": "No se puede hacer referencia a \"this\" en la ubicación actual.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' tiene el tipo implícito 'any' porque no tiene una anotación de tipo.", + "true_for_ES2022_and_above_including_ESNext_6930": "\"true\" para ES2022 y versiones posteriores, incluido ESNext.", + "true_if_composite_false_otherwise_6909": "\"true\", si \"composite\"; \"false\", en caso contrario", + "true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false_6411": "“true” cuando “moduleResolution” es “node16”, “nodenext” o “bundler”; en caso contrario, “false”.", + "tsc_Colon_The_TypeScript_Compiler_6922": "tsc: el compilador de TypeScript", + "type_Colon_6902": "tipo:", + "unique_symbol_types_are_not_allowed_here_1335": "Aquí no se permiten tipos \"unique symbol\".", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Los tipos \"unique symbol\" se permiten solo en variables en una instrucción de variable.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Los tipos \"unique symbol\" no se pueden utilizar en una declaración de variable con un nombre de enlace.", + "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347": "La directiva \"use strict\" no se puede usar con una lista de parámetros no simples.", + "use_strict_directive_used_here_1349": "La directiva \"use strict\" se ha usado aquí.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "No se permiten instrucciones \"with\" en un bloque de funciones asincrónicas.", + "with_statements_are_not_allowed_in_strict_mode_1101": "No se permiten instrucciones \"with\" en modo strict.", + "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057": "La expresión \"yield\" da como resultado un tipo \"any\" de forma implícita porque el generador que la contiene no tiene una anotación de tipo de valor devuelto.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Las expresiones \"yield\" no se pueden usar en un inicializador de parámetros." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/fr/diagnosticMessages.generated.json b/node_modules/typescript/lib/fr/diagnosticMessages.generated.json new file mode 100644 index 00000000..4a35005c --- /dev/null +++ b/node_modules/typescript/lib/fr/diagnosticMessages.generated.json @@ -0,0 +1,2105 @@ +{ + "ALL_COMPILER_OPTIONS_6917": "TOUTES LES OPTIONS DU COMPILATEUR", + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Impossible d'utiliser un modificateur '{0}' avec une déclaration d'importation.", + "A_0_parameter_must_be_the_first_parameter_2680": "Un paramètre '{0}' doit être le premier paramètre.", + "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039": "Une balise JSDoc « @template » ne peut pas suivre une balise « @typedef », « @callback » ou « @overload »", + "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033": "Un commentaire JSDoc '@typedef' ne peut pas contenir plusieurs balises '@type'.", + "A_bigint_literal_cannot_be_used_as_a_property_name_1539": "Un littéral « bigint » ne peut pas être utilisé comme nom de propriété.", + "A_bigint_literal_cannot_use_exponential_notation_1352": "Un littéral bigint ne peut pas utiliser la notation exponentielle.", + "A_bigint_literal_must_be_an_integer_1353": "Un littéral bigint doit être un entier.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Un paramètre de modèle de liaison ne peut pas être facultatif dans une signature d'implémentation.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Une instruction 'break' peut être utilisée uniquement dans une itération englobante ou une instruction switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Une instruction 'break' peut accéder uniquement à une étiquette d'une instruction englobante.", + "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522": "Une classe de caractères ne doit pas contenir de ponctuation double réservée. Vouliez-vous procéder à son échappement avec une barre oblique inverse ?", + "A_character_class_range_must_not_be_bounded_by_another_character_class_1516": "Une plage de classes de caractères ne doit pas être liée par une autre classe de caractères.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Une classe peut uniquement implémenter un identificateur/nom qualifié avec des arguments de type facultatifs.", + "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422": "Une classe peut implémenter uniquement un type d'objet ou une intersection de types d'objet avec des membres connus de manière statique.", + "A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values_2863": "Une classe ne peut pas étendre un type primitif comme « {0} ». Les classes peuvent uniquement étendre des valeurs pouvant être construites.", + "A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types_2864": "Une classe ne peut pas implémenter un type primitif tel que « {0} ». Elle ne peut implémenter que d’autres types d’objets nommés.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "Une déclaration de classe sans modificateur 'default' doit porter un nom.", + "A_class_member_cannot_have_the_0_keyword_1248": "Un membre de classe ne peut pas avoir le mot clé '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Une expression avec virgule n'est pas autorisée dans un nom de propriété calculée.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nom de propriété calculée ne peut pas référencer un paramètre de type à partir de son type conteneur.", + "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166": "Un nom de propriété calculée dans une déclaration de propriété de classe doit avoir un type littéral simple ou un type 'unique symbol'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nom de propriété calculée dans une surcharge de méthode doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nom de propriété calculée dans un littéral de type doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nom de propriété calculée dans un contexte ambiant doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nom de propriété calculée dans une interface doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nom de propriété calculée doit être de type 'string', 'number', 'symbol' ou 'any'.", + "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355": "Une assertion 'const' peut uniquement être appliquée aux références à des membres enum, des littéraux de chaînes, des littéraux de nombres, des littéraux de valeurs booléennes, des littéraux de tableaux ou des littéraux d'objets.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Un membre d'enum const n'est accessible qu'à l'aide d'un littéral de chaîne.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254": "Un initialiseur 'const' dans un contexte ambiant doit être un littéral de chaîne ou un littéral numérique, ou une référence à un enum littéral.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Un constructeur ne peut pas contenir d'appel de 'super' quand sa classe étend 'null'.", + "A_constructor_cannot_have_a_this_parameter_2681": "Un constructeur ne peut pas avoir un paramètre 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Une instruction 'continue' peut uniquement être utilisée dans une instruction d'itération englobante.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Une instruction 'continue' peut accéder uniquement à une étiquette d'une instruction d'itération englobante.", + "A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_f_2846": "Nous ne pouvons pas importer un fichier de déclaration sans « import type ». Vouliez-vous importer un fichier d’implémentation « {0} » à la place ?", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Impossible d'utiliser un modificateur 'declare' dans un contexte ambiant déjà défini.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Un élément décoratif peut uniquement décorer une implémentation de méthode, pas une surcharge.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Une clause 'default' ne peut pas figurer plusieurs fois dans une instruction 'switch'.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Une exportation par défaut ne peut être utilisée que dans un module ECMAScript.", + "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258": "Une exportation par défaut doit se trouver au niveau supérieur d’une déclaration de fichier ou de module.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Une assertion d'affectation définie ' !' n'est pas autorisée dans ce contexte.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Une déclaration de déstructuration doit avoir un initialiseur.", + "A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_t_2712": "Un appel d’importation dynamique dans ES5 nécessite le constructeur « Promise ». Vérifiez que vous avez une déclaration pour le constructeur 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Un appel d'importation dynamique retourne 'Promise'. Vérifiez que vous avez une déclaration pour 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "A_file_cannot_have_a_reference_to_itself_1006": "Un fichier ne peut pas contenir une référence à lui-même.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Une fonction qui retourne 'never' ne peut pas avoir de point de terminaison accessible.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Une fonction appelée avec le mot clé 'new' ne peut pas avoir un type 'this' dont la valeur est 'void'.", + "A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value_2355": "Une fonction dont le type déclaré n'est ni « undefined », « void » ni « any » doit renvoyer une valeur.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Un générateur ne peut pas avoir d'annotation de type 'void'.", + "A_get_accessor_cannot_have_parameters_1054": "Un accesseur 'get' ne peut pas avoir de paramètres.", + "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808": "Un accesseur get doit être au moins aussi accessible que la méthode setter", + "A_get_accessor_must_return_a_value_2378": "Un accesseur 'get' doit retourner une valeur.", + "A_label_is_not_allowed_here_1344": "Étiquette non autorisée ici.", + "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Un élément de tuple étiqueté est déclaré facultatif avec un point d'interrogation après le nom et avant les deux points, plutôt qu'après le type.", + "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Un élément de tuple étiqueté est déclaré en tant que rest avec '...' avant le nom, plutôt qu'avant le type.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Un type mappé ne peut pas déclarer de propriétés ou de méthodes.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un initialiseur de membre dans une déclaration d'enum ne peut pas référencer des membres déclarés après lui, notamment des membres définis dans d'autres enums.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Une classe mixin doit avoir un constructeur avec un paramètre rest unique de type 'any[]'.", + "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Une classe mixin qui s'étend à partir d'une variable de type contenant une signature de construction abstraite doit également être déclarée 'abstract'.", + "A_module_cannot_have_multiple_default_exports_2528": "Un module ne peut pas avoir plusieurs exportations par défaut.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Une déclaration d'espace de noms ne peut pas se trouver dans un autre fichier que celui d'une classe ou d'une fonction avec laquelle elle est fusionnée.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Une déclaration d'espace de noms ne peut pas se trouver avant une classe ou une fonction avec laquelle elle est fusionnée.", + "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235": "Une déclaration d’espace de noms n’est autorisée qu’au niveau supérieur d’un espace de noms ou d’un module.", + "A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_key_1540": "Une déclaration d’« espace de noms » ne doit pas être déclarée à l’aide du mot clé « module ». Utilisez plutôt le mot clé « espace de noms ».", + "A_non_dry_build_would_build_project_0_6357": "Une build non-dry va générer le projet '{0}'", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Une build non-dry va supprimer les fichiers suivants : {0}", + "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374": "Une build non-dry va mettre à jour les horodatages de la sortie du projet '{0}'", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un initialiseur de paramètre est uniquement autorisé dans une implémentation de fonction ou de constructeur.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Impossible de déclarer une propriété de paramètre à l'aide d'un paramètre rest.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Une propriété de paramètre est uniquement autorisée dans une implémentation de constructeur.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Impossible de déclarer une propriété de paramètre à l'aide d'un modèle de liaison.", + "A_promise_must_have_a_then_method_1059": "Une promesse doit avoir une méthode 'then'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Une propriété d'une classe dont le type est un type 'unique symbol' doit être à la fois 'static' et 'readonly'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Une propriété d'une interface ou d'un littéral de type dont le type est un type 'unique symbol' doit être 'readonly'.", + "A_required_element_cannot_follow_an_optional_element_1257": "Un élément required ne peut pas suivre un élément optional.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un paramètre obligatoire ne peut pas suivre un paramètre optionnel.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un élément rest ne peut pas contenir de modèle de liaison.", + "A_rest_element_cannot_follow_another_rest_element_1265": "Un élément rest ne peut pas suivre un autre élément rest.", + "A_rest_element_cannot_have_a_property_name_2566": "Un élément rest ne peut pas avoir de nom de propriété.", + "A_rest_element_cannot_have_an_initializer_1186": "Un élément rest ne peut pas avoir d'initialiseur.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Un élément rest doit être le dernier dans un modèle de déstructuration.", + "A_rest_element_type_must_be_an_array_type_2574": "Un type d'élément rest doit être un type tableau.", + "A_rest_parameter_cannot_be_optional_1047": "Un paramètre rest ne peut pas être facultatif.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Un paramètre rest ne peut pas avoir d'initialiseur.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Un paramètre rest doit être le dernier dans une liste de paramètres.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Un paramètre rest doit être de type tableau.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Les modèles de liaison ou les paramètres rest ne doivent pas avoir de virgule de fin.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Une instruction 'return' peut être utilisée uniquement dans un corps de fonction.", + "A_return_statement_cannot_be_used_inside_a_class_static_block_18041": "Une instruction « return » ne peut pas être utilisée à l’intérieur d’un bloc statique de classe.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Série d'entrées qui remappent les importations aux emplacements de recherche en fonction de 'baseUrl'.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Un accesseur 'set' ne peut pas avoir d'annotation de type de retour.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Un accesseur 'set' ne peut pas avoir de paramètre optionnel.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Un accesseur 'set' ne peut pas avoir de paramètre rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Un accesseur 'set' doit avoir un seul paramètre.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Un paramètre d'accesseur 'set' ne peut pas avoir d'initialiseur.", + "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556": "Un argument d’engraissement doit soit avoir un type de tuple, soit être passé à un paramètre REST.", + "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401": "Un appel « super » doit être une instruction de niveau racine dans un constructeur d’une classe dérivée qui contient des propriétés initialisées, des propriétés de paramètre ou des identificateurs privés.", + "A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_2376": "Un appel 'super' doit être la première instruction du constructeur à faire référence à « super » ou « this » lorsqu’une classe dérivée contient des propriétés initialisées, des propriétés de paramètre ou des identificateurs privés.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Une protection de type basée sur 'this' n'est pas compatible avec une protection de type basée sur des paramètres.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Un type 'this' est disponible uniquement dans un membre non statique d'une classe ou d'une interface.", + "A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimM_1287": "Un modificateur « export » de niveau supérieur ne peut pas être utilisé sur des déclarations de valeur dans un module CommonJS quand « verbatimModuleSyntax » est activé.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Un fichier 'tsconfig.json' est déjà défini à l'emplacement '{0}'.", + "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Un membre de tuple ne peut pas être à la fois facultatif et rest.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Un type tuple ne peut pas être indexé avec une valeur négative.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Une expression d'assertion de type n'est pas autorisée dans la partie gauche d'une expression d'élévation à une puissance. Mettez l'expression entre parenthèses.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Une propriété de littéral de type ne peut pas avoir d'initialiseur.", + "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Une importation de type uniquement peut spécifier une importation par défaut ou des liaisons nommées, mais pas les deux.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Un prédicat de type ne peut pas référencer un paramètre rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un prédicat de type ne peut pas référencer un élément '{0}' dans un modèle de liaison.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Un prédicat de type est autorisé uniquement dans une position de type de retour pour les fonctions et les méthodes.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Le type d'un prédicat de type doit être assignable au type de son paramètre.", + "A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_w_1272": "Un type référencé dans une signature décorée doit être importé avec « import type » ou une importation d’espace de noms quand « isolatedModules » et « emitDecoratorMetadata » sont activés.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Une variable dont le type est un type 'unique symbol' doit être 'const'.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Une expression 'yield' est autorisée uniquement dans le corps d'un générateur.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "La méthode abstraite '{0}' de la classe '{1}' n'est pas accessible au moyen de l'expression super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Les méthodes abstraites peuvent uniquement apparaître dans une classe abstraite.", + "Abstract_properties_can_only_appear_within_an_abstract_class_1253": "Les propriétés abstraites peuvent uniquement apparaître dans une classe abstraite.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "La propriété abstraite '{0}' de la classe '{1}' n'est pas accessible dans le constructeur.", + "Accessibility_modifier_already_seen_1028": "Modificateur d'accessibilité déjà rencontré.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Les accesseurs sont uniquement disponibles quand EcmaScript 5 ou version supérieure est ciblé.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Les accesseurs doivent être abstraits ou non abstraits.", + "Add_0_to_unresolved_variable_90008": "Ajouter '{0}.' à la variable non résolue", + "Add_a_return_statement_95111": "Ajouter une instruction return", + "Add_a_return_type_to_the_function_declaration_9031": "Ajoutez un type de retour à la déclaration de fonction.", + "Add_a_return_type_to_the_function_expression_9030": "Ajoutez un type de retour à l’expression de fonction.", + "Add_a_return_type_to_the_get_accessor_declaration_9032": "Ajoutez un type de retour à la déclaration d’accesseur get.", + "Add_a_return_type_to_the_method_9034": "Ajouter un type de retour à la méthode", + "Add_a_type_annotation_to_the_parameter_0_9028": "Ajoutez une annotation de type au paramètre {0}.", + "Add_a_type_annotation_to_the_property_0_9029": "Ajoutez une annotation de type à la propriété {0}.", + "Add_a_type_annotation_to_the_variable_0_9027": "Ajoutez une annotation de type à la variable {0}.", + "Add_a_type_to_parameter_of_the_set_accessor_declaration_9033": "Ajoutez un type au paramètre de la déclaration d’accesseur set.", + "Add_all_missing_async_modifiers_95041": "Ajouter tous les modificateurs 'async' manquants", + "Add_all_missing_attributes_95168": "Ajouter tous les attributs manquants", + "Add_all_missing_call_parentheses_95068": "Ajouter toutes les parenthèses d'appel manquantes", + "Add_all_missing_function_declarations_95157": "Ajouter toutes les déclarations de fonction manquantes", + "Add_all_missing_imports_95064": "Ajouter toutes les importations manquantes", + "Add_all_missing_members_95022": "Ajouter tous les membres manquants", + "Add_all_missing_override_modifiers_95162": "Ajouter tous les modificateurs 'override' manquants", + "Add_all_missing_parameters_95190": "Ajouter tous les paramètres manquants", + "Add_all_missing_properties_95166": "Ajouter toutes les propriétés manquantes", + "Add_all_missing_return_statement_95114": "Ajouter toutes les instructions return manquantes", + "Add_all_missing_super_calls_95039": "Ajouter tous les appels super manquants", + "Add_all_missing_type_annotations_90067": "Ajouter toutes les annotations de type manquantes", + "Add_all_optional_parameters_95193": "Ajouter tous les paramètres optionnels", + "Add_annotation_of_type_0_90062": "Ajouter une annotation de type « {0} »", + "Add_async_modifier_to_containing_function_90029": "Ajouter le modificateur async dans la fonction conteneur", + "Add_await_95083": "Ajouter 'await'", + "Add_await_to_initializer_for_0_95084": "Ajouter 'await' à l'initialiseur pour '{0}'", + "Add_await_to_initializers_95089": "Ajouter 'await' aux initialiseurs", + "Add_braces_to_arrow_function_95059": "Ajouter des accolades à la fonction arrow", + "Add_const_to_all_unresolved_variables_95082": "Ajouter 'const' à toutes les variables non résolues", + "Add_const_to_unresolved_variable_95081": "Ajouter 'const' à la variable non résolue", + "Add_definite_assignment_assertion_to_property_0_95020": "Ajouter une assertion d'assignation définie à la propriété '{0}'", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Ajouter des assertions d'affectation définie à toutes les propriétés non initialisées", + "Add_export_to_make_this_file_into_a_module_95097": "Ajouter 'export {}' pour faire de ce fichier un module", + "Add_extends_constraint_2211": "Ajoutez la contrainte « extends ».", + "Add_extends_constraint_to_all_type_parameters_2212": "Ajouter la contrainte « extends » à tous les paramètres de type", + "Add_import_from_0_90057": "Ajouter l'importation de \"{0}\"", + "Add_index_signature_for_property_0_90017": "Ajouter une signature d'index pour la propriété '{0}'", + "Add_initializer_to_property_0_95019": "Ajouter un initialiseur à la propriété '{0}'", + "Add_initializers_to_all_uninitialized_properties_95027": "Ajouter des initialiseurs à toutes les propriétés non initialisées", + "Add_missing_attributes_95167": "Ajouter les attributs manquants", + "Add_missing_call_parentheses_95067": "Ajouter les parenthèses d'appel manquantes", + "Add_missing_comma_for_object_member_completion_0_95187": "Ajoutez une virgule manquante pour l’achèvement de membre d’objet « {0} ».", + "Add_missing_enum_member_0_95063": "Ajouter le membre enum manquant '{0}'", + "Add_missing_function_declaration_0_95156": "Ajouter la déclaration de fonction manquante '{0}'", + "Add_missing_new_operator_to_all_calls_95072": "Ajouter l'opérateur 'new' manquant à tous les appels", + "Add_missing_new_operator_to_call_95071": "Ajouter l'opérateur 'new' manquant à l'appel", + "Add_missing_parameter_to_0_95188": "Ajouter le paramètre manquant dans « {0} »", + "Add_missing_parameters_to_0_95189": "Ajouter les paramètres manquants dans « {0} »", + "Add_missing_properties_95165": "Ajouter des propriétés manquantes", + "Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'", + "Add_missing_typeof_95052": "Ajouter un 'typeof' manquant", + "Add_names_to_all_parameters_without_names_95073": "Ajouter des noms à tous les paramètres sans noms", + "Add_optional_parameter_to_0_95191": "Ajouter un paramètre optionnel à « {0} »", + "Add_optional_parameters_to_0_95192": "Ajouter des paramètres optionnels à '{0}'", + "Add_or_remove_braces_in_an_arrow_function_95058": "Ajouter ou supprimer les accolades dans une fonction arrow", + "Add_override_modifier_95160": "Ajouter un modificateur 'override'", + "Add_parameter_name_90034": "Ajouter un nom de paramètre", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Ajouter un qualificateur à toutes les variables non résolues correspondant à un nom de membre", + "Add_resolution_mode_import_attribute_95196": "Ajouter l'attribut d'importation « mode de résolution »", + "Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it_95197": "Ajoutez l'attribut d'importation « mode de résolution » à toutes les importations de type uniquement qui en ont besoin", + "Add_return_type_0_90063": "Ajouter le type de retour « {0} »", + "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035": "Ajoutez des satisfactions et une assertion de type à cette expression (satisfait T en tant que T) pour rendre le type explicite.", + "Add_satisfies_and_an_inline_type_assertion_with_0_90068": "Ajouter des satisfactions et une assertion de type inlined avec « {0} »", + "Add_to_all_uncalled_decorators_95044": "Ajouter '()' à tous les décorateurs non appelés", + "Add_ts_ignore_to_all_error_messages_95042": "Ajouter '@ts-ignore' à tous les messages d'erreur", + "Add_undefined_to_a_type_when_accessed_using_an_index_6674": "Ajoutez « undefined » à un type lorsque vous y accédez à l’aide d’un index.", + "Add_undefined_to_optional_property_type_95169": "Ajouter « undefined » à un type de propriété facultatif", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Ajouter un type non défini à toutes les propriétés non initialisées", + "Add_undefined_type_to_property_0_95018": "Ajouter un type 'undefined' à la propriété '{0}'", + "Add_unknown_conversion_for_non_overlapping_types_95069": "Ajouter une conversion 'unknown' pour les types qui ne se chevauchent pas", + "Add_unknown_to_all_conversions_of_non_overlapping_types_95070": "Ajouter 'unknown' à toutes les conversions de types qui ne se chevauchent pas", + "Add_void_to_Promise_resolved_without_a_value_95143": "Ajouter 'void' à un Promise résolu sans valeur", + "Add_void_to_all_Promises_resolved_without_a_value_95144": "Ajouter 'void' à toutes les promesses résolues sans valeur", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "L'ajout d'un fichier tsconfig.json permet d'organiser les projets qui contiennent des fichiers TypeScript et JavaScript. En savoir plus sur https://aka.ms/tsconfig.", + "All_declarations_of_0_must_have_identical_constraints_2838": "Toutes les déclarations de « {0} » doivent avoir des contraintes identiques.", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Toutes les déclarations de '{0}' doivent avoir des modificateurs identiques.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Toutes les déclarations de '{0}' doivent avoir des paramètres de type identiques.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Toutes les déclarations d'une méthode abstraite doivent être consécutives.", + "All_destructured_elements_are_unused_6198": "Tous les éléments déstructurés sont inutilisés.", + "All_imports_in_import_declaration_are_unused_6192": "Les importations de la déclaration d'importation ne sont pas toutes utilisées.", + "All_type_parameters_are_unused_6205": "Tous les paramètres de type sont inutilisés.", + "All_variables_are_unused_6199": "Toutes les variables sont inutilisées.", + "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600": "Autorisez les fichiers JavaScript à faire partie de votre programme. Utilisez l’option « checkJS » pour obtenir des erreurs à partir de ces fichiers.", + "Allow_accessing_UMD_globals_from_modules_6602": "Autorisez l'accès aux variables globales UMD à partir des modules.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Autorisez les importations par défaut à partir des modules sans exportation par défaut. Cela n'affecte pas l'émission du code, juste le contrôle de type.", + "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601": "Autoriser « importation de x à partir de y » quand un module n’a pas d’exportation par défaut.", + "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639": "Autorisez l’importation de fonctions d’assistance à partir de tslib une fois par projet, au lieu de les inclure par fichier.", + "Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noE_6407": "Autorisez les importations pour inclure des extensions de fichier TypeScript. Nécessite la définition de « --moduleResolution bundler » et de « --noEmit » ou « --emitDeclarationOnly ».", + "Allow_javascript_files_to_be_compiled_6102": "Autorisez la compilation des fichiers JavaScript.", + "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691": "Autorisez plusieurs dossiers à être considérés comme un seul lors de la résolution des modules.", + "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261": "Le nom de fichier déjà inclus '{0}' diffère du nom de fichier '{1}' uniquement par la casse.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Une déclaration de module ambiant ne peut pas spécifier un nom de module relatif.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Impossible d'imbriquer des modules ambiants dans d'autres modules ou espaces de noms.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Un module AMD ne peut pas avoir plusieurs affectations de nom.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Un accesseur abstrait ne peut pas avoir d'implémentation.", + "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010": "Un modificateur d'accessibilité ne peut pas être utilisé avec un identificateur privé.", + "An_accessor_cannot_have_type_parameters_1094": "Un accesseur ne peut pas avoir de paramètres de type.", + "An_accessor_property_cannot_be_declared_optional_1276": "Une propriété 'accessor' ne peut pas être déclarée comme facultative.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Une déclaration de module ambiant est uniquement autorisée au niveau supérieur dans un fichier.", + "An_argument_for_0_was_not_provided_6210": "Aucun argument pour '{0}' n'a été fourni.", + "An_argument_matching_this_binding_pattern_was_not_provided_6211": "Aucun argument correspondant à ce modèle de liaison n'a été fourni.", + "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356": "Un opérande arithmétique doit être de type 'any', 'number', 'bigint' ou un type enum.", + "An_arrow_function_cannot_have_a_this_parameter_2730": "Une fonction arrow ne peut pas avoir un paramètre 'this'.", + "An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_2705": "Une fonction ou méthode asynchrone dan ES5 nécessite le constructeur « Promise ». Vérifiez que vous avez une déclaration pour le constructeur 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Une fonction ou une méthode async doit retourner 'Promise'. Vérifiez que vous avez une déclaration pour 'Promise', ou incluez 'ES2015' dans votre option '--lib'.", + "An_async_iterator_must_have_a_next_method_2519": "Un itérateur asynchrone doit comporter une méthode 'next()'.", + "An_element_access_expression_should_take_an_argument_1011": "Une expression d'accès à un élément doit accepter un argument.", + "An_enum_member_cannot_be_named_with_a_private_identifier_18024": "Un membre enum ne peut pas être nommé avec un identificateur privé.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Un membre enum ne peut pas avoir un nom numérique.", + "An_enum_member_name_must_be_followed_by_a_or_1357": "Un nom de membre enum doit être suivi de ',', de '=' ou de '}'.", + "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928": "Version développée de ces informations, affichant toutes les options possibles du compilateur", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Impossible d'utiliser une assignation d'exportation dans un module comportant d'autres éléments exportés.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Une affectation d'exportation ne peut pas être utilisée dans un espace de noms.", + "An_export_assignment_cannot_have_modifiers_1120": "Une assignation d'exportation ne peut pas avoir de modificateurs.", + "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231": "Une affectation d’exportation doit se trouver au niveau supérieur d’une déclaration de fichier ou de module.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474": "Une déclaration d’exportation ne peut être utilisée qu’au niveau supérieur d’un module.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233": "Une déclaration d’exportation ne peut être utilisée qu’au niveau supérieur d’un espace de noms ou d’un module.", + "An_export_declaration_cannot_have_modifiers_1193": "Une déclaration d'exportation ne peut pas avoir de modificateurs.", + "An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolve_1283": "Une déclaration « export = » doit faire référence à une valeur réelle quand « verbatimModuleSyntax » est activé, mais « {0} » se résout en déclaration de type uniquement.", + "An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers__1282": "Une déclaration « export = » doit faire référence à une valeur quand « verbatimModuleSyntax » est activé, mais « {0} » fait uniquement référence à un type.", + "An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_1285": "Une « export default » doit faire référence à une valeur réelle quand « verbatimModuleSyntax » est activé, mais « {0} » se résout en déclaration de type uniquement.", + "An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_1284": "Une « export default » doit référencer une valeur quand « verbatimModuleSyntax » est activé, mais « {0} » fait uniquement référence à un type.", + "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345": "Impossible de tester une expression de type 'void' pour déterminer si elle a la valeur true.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Une valeur d'échappement Unicode étendue doit être comprise entre 0x0 et 0x10FFFF inclus.", + "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351": "Un identificateur ou un mot clé ne peut pas suivre immédiatement un littéral numérique.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Impossible de déclarer une implémentation dans des contextes ambiants.", + "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Un alias d'importation ne peut pas référencer une déclaration exportée à l'aide de 'export type'.", + "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Un alias d'importation ne peut pas référencer une déclaration importée à l'aide de 'import type'.", + "An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabl_1288": "Un alias d'importation ne peut pas être résolu en une déclaration de type ou de type uniquement lorsque « verbatimModuleSyntax » est activé.", + "An_import_alias_cannot_use_import_type_1392": "Un alias d'importation ne peut pas utiliser 'import type'", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473": "Une déclaration d’importation ne peut être utilisée qu’au niveau supérieur d’un module.", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232": "Une déclaration d’importation ne peut être utilisée qu’au niveau supérieur d’un espace de noms ou d’un module.", + "An_import_declaration_cannot_have_modifiers_1191": "Une déclaration d'importation ne peut pas avoir de modificateurs.", + "An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled_5097": "Un chemin d’importation ne peut se terminer que par une extension « {0} » lorsque « allowImportingTsExtensions » est activé.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Une signature d'index ne peut pas avoir de paramètre rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Une signature d'index ne peut pas avoir de virgule de fin.", + "An_index_signature_must_have_a_type_annotation_1021": "Une signature d'index doit avoir une annotation de type.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Une signature d'index doit avoir un seul paramètre.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un paramètre de signature d'index ne peut pas contenir de point d'interrogation.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un paramètre de signature d'index ne peut pas avoir de modificateur d'accessibilité.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un paramètre de signature d'index ne peut pas avoir d'initialiseur.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un paramètre de signature d'index doit avoir une annotation de type.", + "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Un type de paramètre de signature d’index ne peut pas être un type littéral ni générique. Envisagez plutôt d’utiliser un type d’objet mappé.", + "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Un type de paramètre de signature d’index doit être « string », « number », « symbol » ou un type littéral de modèle.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Une expression d’instanciation ne peut pas être suivie d’un accès à la propriété.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Une interface peut uniquement étendre un identificateur/nom qualifié avec des arguments de type facultatifs.", + "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Une interface peut étendre uniquement un type d'objet ou une intersection de types d'objet avec des membres connus de manière statique.", + "An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types_2840": "Une interface ne peut pas étendre un type primitif comme « {0} ». Elle peut uniquement étendre d’autres types d’objets nommés.", + "An_interface_property_cannot_have_an_initializer_1246": "Une propriété d'interface ne peut pas avoir d'initialiseur.", + "An_iterator_must_have_a_next_method_2489": "Un itérateur doit comporter une méthode 'next()'.", + "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Un pragma @jsxFrag est nécessaire quand un pragma @jsx est utilisé avec des fragments JSX.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Un littéral d'objet ne peut pas avoir plusieurs accesseurs get/set portant le même nom.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117": "Un littéral d’objet ne peut pas avoir plusieurs propriétés portant le même nom.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Un littéral d'objet ne peut pas avoir une propriété et un accesseur portant le même nom.", + "An_object_member_cannot_be_declared_optional_1162": "Impossible de déclarer un membre d'objet comme étant facultatif.", + "An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_han_2861": "La méthode « [Symbol.hasInstance] » d’un objet doit retourner une valeur booléenne pour qu’elle soit utilisée à droite d’une expression « instanceof ».", + "An_optional_chain_cannot_contain_private_identifiers_18030": "Une chaîne facultative ne peut pas contenir d'identificateurs privés.", + "An_optional_element_cannot_follow_a_rest_element_1266": "Un élément optional ne peut pas suivre un élément rest.", + "An_outer_value_of_this_is_shadowed_by_this_container_2738": "Une valeur externe de 'this' est mise en mémoire fantôme par ce conteneur.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Une signature de surcharge ne peut pas être déclarée en tant que générateur.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Une expression unaire avec l'opérateur '{0}' n'est pas autorisée dans la partie gauche d'une expression d'élévation à une puissance. Mettez l'expression entre parenthèses.", + "Annotate_everything_with_types_from_JSDoc_95043": "Annoter tout avec des types de JSDoc", + "Annotate_types_of_properties_expando_function_in_a_namespace_90071": "Annoter les types de fonction expando de propriétés dans un espace de noms", + "Annotate_with_type_from_JSDoc_95009": "Annoter avec le type de JSDoc", + "Another_export_default_is_here_2753": "Une autre valeur par défaut d'exportation se trouve ici.", + "Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_t_1528": "Les propriétés Unicode susceptibles de correspondre à plus d’un caractère unique ne sont disponibles que lorsque l’indicateur Unicode Sets (v) est défini.", + "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518": "Tout ce qui peut correspondre à plus d’un seul caractère n’est pas valide dans une classe de caractères négatif.", + "Are_you_missing_a_semicolon_2734": "Il vous manque un point-virgule ?", + "Argument_expression_expected_1135": "Expression d'argument attendue.", + "Argument_for_0_option_must_be_Colon_1_6046": "L'argument de l'option '{0}' doit être {1}.", + "Argument_of_dynamic_import_cannot_be_spread_element_1325": "L’argument de l’importation dynamique ne peut pas être un élément de propagation.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "L'argument de type '{0}' n'est pas attribuable au paramètre de type '{1}'.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379": "L'argument de type '{0}' n'est pas assignable au paramètre de type '{1}' avec 'exactOptionalPropertyTypes : true'. Pensez à ajouter 'undefined' aux types des propriétés de la cible.", + "Arguments_for_the_rest_parameter_0_were_not_provided_6236": "Les arguments du paramètre de reste '{0}' n'ont pas été fournis.", + "Array_element_destructuring_pattern_expected_1181": "Modèle de déstructuration d'élément de tableau attendu.", + "Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations_9018": "Les tableaux avec des éléments de diffusion ne peuvent pas être déduits avec --isolatedDeclarations.", + "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775": "Quand vous utilisez des assertions, chaque nom de la cible d'appel doit être déclaré à l'aide d'une annotation de type explicite.", + "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776": "Quand vous utilisez des assertions, la cible d'appel doit être un identificateur ou un nom qualifié.", + "Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations__9023": "L’affectation de propriétés à des fonctions sans les déclarer n’est pas prise en charge avec --isolatedDeclarations. Ajoutez une déclaration explicite pour les propriétés affectées à cette fonction.", + "Asterisk_Slash_expected_1010": "'.' attendu.", + "At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9009": "Au moins un accesseur doit avoir une annotation de type explicite avec --isolatedDeclarations.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Les augmentations de la portée globale ne peuvent être directement imbriquées que dans les modules externes ou les déclarations de modules ambiants.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Les augmentations de la portée globale doivent comporter un modificateur 'declare', sauf si elles apparaissent déjà dans un contexte ambiant.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "La détection automatique des typages est activée dans le projet '{0}'. Exécution de la passe de résolution supplémentaire pour le module '{1}' à l'aide de l'emplacement du cache '{2}'.", + "BUILD_OPTIONS_6919": "OPTIONS DE BUILD", + "Backwards_Compatibility_6253": "Rétrocompatibilité", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Les expressions de classe de base ne peuvent pas référencer les paramètres de type de classe.", + "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509": "Le type de retour '{0}' du constructeur de base n'est pas un type d'objet ou une intersection de types d'objet avec des membres connus de manière statique.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Les constructeurs de base doivent tous avoir le même type de retour.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Répertoire de base pour la résolution des noms de modules non absolus.", + "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737": "Les littéraux BigInt ne sont pas disponibles quand la version ciblée est antérieure à ES2020.", + "Binary_digit_expected_1177": "Chiffre binaire attendu.", + "Binding_element_0_implicitly_has_an_1_type_7031": "L'élément de liaison '{0}' possède implicitement un type '{1}'.", + "Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations_9019": "Les éléments de liaison ne peuvent pas être exportés directement avec --isolatedDeclarations.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "Variable de portée de bloc '{0}' utilisée avant sa déclaration.", + "Build_a_composite_project_in_the_working_directory_6925": "Générer un projet composite dans le répertoire de travail.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636": "Générer tous les projets, même ceux qui semblent être à jour.", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Générer un ou plusieurs projets et leurs dépendances (s'ils sont obsolètes)", + "Build_option_0_requires_a_value_of_type_1_5073": "L'option de build '{0}' nécessite une valeur de type {1}.", + "Building_project_0_6358": "Génération du projet '{0}'...", + "Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any_6720": "Les itérateurs intégrés sont instanciés avec un type « TReturn » « undefined » au lieu de « any ».", + "COMMAND_LINE_FLAGS_6921": "INDICATEURS DE LIGNE DE COMMANDE", + "COMMON_COMMANDS_6916": "COMMANDES COURANTES", + "COMMON_COMPILER_OPTIONS_6920": "OPTIONS COURANTES DU COMPILATEUR", + "Call_decorator_expression_90028": "Appeler l'expression de l'élément décoratif", + "Call_signature_return_types_0_and_1_are_incompatible_2202": "Les types de retour de signature d'appel '{0}' et '{1}' sont incompatibles.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La signature d'appel, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour 'any'.", + "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204": "Les signatures d'appel sans arguments ont des types de retour incompatibles : '{0}' et '{1}'.", + "Can_only_convert_logical_AND_access_chains_95142": "Conversion uniquement de chaînes logiques ET de chaînes d'accès", + "Can_only_convert_named_export_95164": "Peut uniquement convertir l’exportation nommée", + "Can_only_convert_property_with_modifier_95137": "La propriété peut uniquement être convertie avec un modificateur", + "Can_only_convert_string_concatenations_and_string_literals_95154": "Peut uniquement convertir des concaténations de chaînes et des littéraux de chaîne", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Impossible d'accéder à '{0}.{1}', car '{0}' est un type, mais pas un espace de noms. Voulez-vous plutôt récupérer le type de la propriété '{1}' dans '{0}' avec '{0}[\"{1}\"]' ?", + "Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead_1281": "Désolé... Nous ne pouvons pas accéder à « {0} » à partir d’un autre fichier sans qualification lorsque « {1} » est activé. Utilisez « {2} » à la place.", + "Cannot_access_ambient_const_enums_when_0_is_enabled_2748": "Impossible d’accéder aux enums const ambiants quand '{0}' est activé.", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Impossible d'assigner un type de constructeur '{0}' à un type de constructeur '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Impossible d'attribuer un type de constructeur abstrait à un type de constructeur non abstrait.", + "Cannot_assign_to_0_because_it_is_a_class_2629": "Impossible d'effectuer l'assignation à '{0}', car il s'agit d'une classe.", + "Cannot_assign_to_0_because_it_is_a_constant_2588": "Impossible d'effectuer une assignation à '{0}', car il s'agit d'une constante.", + "Cannot_assign_to_0_because_it_is_a_function_2630": "Impossible d'effectuer l'assignation à '{0}', car il s'agit d'une fonction.", + "Cannot_assign_to_0_because_it_is_a_namespace_2631": "Impossible d'effectuer l'assignation à '{0}', car il s'agit d'un espace de noms.", + "Cannot_assign_to_0_because_it_is_a_read_only_property_2540": "Impossible d'effectuer une assignation à '{0}', car il s'agit d'une propriété en lecture seule.", + "Cannot_assign_to_0_because_it_is_an_enum_2628": "Impossible d'effectuer l'assignation à '{0}', car il s'agit d'un enum.", + "Cannot_assign_to_0_because_it_is_an_import_2632": "Impossible d'effectuer l'assignation à '{0}', car il s'agit d'une importation.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Impossible d'effectuer une assignation à '{0}', car il ne s'agit pas d'une variable.", + "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803": "Impossible d'effectuer une assignation à la méthode privée '{0}'. Les méthodes privées ne sont pas accessibles en écriture.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Impossible d'augmenter le module '{0}', car il se résout en une entité non-module.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Impossible d'augmenter le module '{0}' avec des exportations de valeurs, car il se résout en une entité non-module.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Impossible de compiler des modules à l'aide de l'option '{0}' tant que l'indicateur '--module' n'a pas la valeur 'amd' ou 'system'.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Impossible de créer une instance d'une classe abstraite.", + "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766": "Impossible de déléguer l'itération à la valeur, car la méthode 'next' de son itérateur attend le type '{1}', mais le générateur conteneur envoie toujours '{0}'.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Impossible d'exporter '{0}'. Seules les déclarations locales peuvent être exportées à partir d'un module.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Impossible d'étendre une classe '{0}'. Le constructeur de classe est marqué comme étant privé.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Impossible d'étendre une interface '{0}'. Vouliez-vous dire 'implements' ?", + "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081": "Le fichier tsconfig.json est introuvable dans le répertoire actif : {0}.", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Le fichier tsconfig.json est introuvable dans le répertoire spécifié : '{0}'.", + "Cannot_find_global_type_0_2318": "Le type global '{0}' est introuvable.", + "Cannot_find_global_value_0_2468": "La valeur globale '{0}' est introuvable.", + "Cannot_find_lib_definition_for_0_2726": "Définition de bibliothèque introuvable pour '{0}'.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "Définition de bibliothèque introuvable pour '{0}'. Est-ce qu'il ne s'agit pas plutôt de '{1}' ?", + "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732": "Le module '{0}' est introuvable. Utilisez '--resolveJsonModule' pour importer le module avec l'extension '.json'.", + "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_t_2792": "Le module « {0} » est introuvable. Vouliez-vous définir l’option « moduleResolution » sur la valeur « node » ou ajouter des alias à l’option « paths » ?", + "Cannot_find_module_0_or_its_corresponding_type_declarations_2307": "Impossible de localiser le module '{0}' ou les déclarations de type correspondantes.", + "Cannot_find_name_0_2304": "Le nom '{0}' est introuvable.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Le nom '{0}' est introuvable. Est-ce qu'il ne s'agit pas plutôt de '{1}' ?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Le nom '{0}' est introuvable. Voulez-vous utiliser le membre d'instance 'this.{0}' ?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Le nom '{0}' est introuvable. Voulez-vous utiliser le membre statique '{1}.{0}' ?", + "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311": "Le nom « {0} » est introuvable. Voulez-vous écrire ceci dans une fonction asynchrone ?", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583": "Le nom '{0}' est introuvable. Devez-vous changer votre bibliothèque cible ? Essayez de changer l'option de compilateur 'lib' en '{1}' ou une version ultérieure.", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584": "Le nom '{0}' est introuvable. Devez-vous changer votre bibliothèque cible ? Essayez de remplacer l'option de compilateur 'lib' pour inclure 'dom'.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2867": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour Bun ? Essayez `npm i --save-dev @types/bun`.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2868": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour Bun ? Essayez `npm i --save-dev @types/bun`, puis ajoutez « bun » au champ types de votre fichier tsconfig.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour un exécuteur de tests ? Essayez 'npm i --save-dev @types/jest' ou 'npm i --save-dev @types/mocha'.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour un exécuteur de tests ? Essayez 'npm i --save-dev @types/jest' ou 'npm i --save-dev @types/mocha', puis ajoutez 'jest' ou 'mocha' au champ types de votre fichier tsconfig.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour jQuery ? Essayez 'npm i --save-dev @types/jquery'.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour jQuery ? Essayez 'npm i --save-dev @types/jquery', puis ajoutez 'jquery' au champ types de votre fichier tsconfig.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour node ? Essayez 'npm i --save-dev @types/node'.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour node ? Essayez 'npm i --save-dev @types/node', puis ajoutez 'node' au champ types de votre fichier tsconfig.", + "Cannot_find_namespace_0_2503": "L'espace de noms '{0}' est introuvable.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Impossible de trouver l'espace de noms '{0}'. Vouliez-vous dire '{1}'?", + "Cannot_find_parameter_0_1225": "Paramètre '{0}' introuvable.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Impossible de trouver le chemin d'accès au sous-répertoire commun pour les fichiers d'entrée.", + "Cannot_find_type_definition_file_for_0_2688": "Le fichier de définition de type est introuvable pour '{0}'.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Impossible d'importer les fichiers de déclaration de type. Importez '{0}' à la place de '{1}'.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Impossible d'initialiser la variable de portée externe '{0}' dans la même portée que celle de la déclaration de portée de bloc '{1}'.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Impossible d'appeler un objet qui a éventuellement une valeur 'null'.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Impossible d'appeler un objet qui a éventuellement une valeur 'null' ou 'undefined'.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Impossible d'appeler un objet qui a éventuellement une valeur 'undefined'.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765": "Impossible d'itérer la valeur, car la méthode 'next' de son itérateur attend le type '{1}', mais la déstructuration de tableau envoie toujours '{0}'.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Impossible d'itérer la valeur, car la méthode 'next' de son itérateur attend le type '{1}', mais la diffusion de tableau envoie toujours '{0}'.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Impossible d'itérer la valeur, car la méthode 'next' de son itérateur attend le type '{1}', mais la boucle for-of envoie toujours '{0}'.", + "Cannot_move_statements_to_the_selected_file_95183": "Désolé... Nous ne pouvons pas déplacer les instructions vers le fichier sélectionné", + "Cannot_move_to_file_selected_file_is_invalid_95179": "Désolé... Nous ne pouvons pas déplacer vers le fichier. Le fichier sélectionné n’est pas valide", + "Cannot_read_file_0_5083": "Impossible de lire le fichier '{0}'.", + "Cannot_read_file_0_Colon_1_5012": "Impossible de lire le fichier '{0}' : {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Impossible de redéclarer la variable de portée de bloc '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "Impossible de redéclarer la variable exportée '{0}'.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Impossible de redéclarer l'identificateur '{0}' dans la clause catch.", + "Cannot_start_a_function_call_in_a_type_annotation_1441": "Impossible de démarrer un appel de fonction dans une annotation de type.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Impossible d'utiliser JSX, sauf si l'indicateur '--jsx' est fourni.", + "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled_1269": "Désolé... Nous ne pouvons pas utiliser « export import » sur un type ou espace de noms de type uniquement lorsque l’indicateur « {0} » est activé.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Impossible d'utiliser des importations, des exportations ou des augmentations de module quand '--module' a la valeur 'none'.", + "Cannot_use_namespace_0_as_a_type_2709": "Impossible d'utiliser l'espace de noms '{0}' en tant que type.", + "Cannot_use_namespace_0_as_a_value_2708": "Impossible d'utiliser l'espace de noms '{0}' en tant que valeur.", + "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816": "Impossible d'utiliser « this » dans un initialiseur de propriété statique d'une classe décorée.", + "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377": "Impossible d'écrire le fichier '{0}', car il va remplacer le fichier '.tsbuildinfo' généré par le projet référencé '{1}'", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Impossible d'écrire le fichier '{0}', car il serait remplacé par plusieurs fichiers d'entrée.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Impossible d'écrire le fichier '{0}', car cela entraînerait le remplacement du fichier d'entrée.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Une variable de clause catch ne peut pas avoir d'initialiseur.", + "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196": "L'annotation de type de variable de la clause catch doit être 'any' ou 'unknown' si elle est spécifiée.", + "Change_0_to_1_90014": "Changer '{0}' en '{1}'", + "Change_all_extended_interfaces_to_implements_95038": "Remplacer toutes les interfaces étendues par 'implements'", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Remplacer tous les types jsdoc-style par TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Remplacer tous les types jsdoc-type par TypeScript (et ajouter '| undefined' aux types nullable)", + "Change_extends_to_implements_90003": "Changer 'extends' en 'implements'", + "Change_spelling_to_0_90022": "Changer l'orthographe en '{0}'", + "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700": "Recherchez les propriétés de classe déclarées mais non définies dans le constructeur.", + "Check_side_effect_imports_6806": "Vérifiez les importations d’effet secondaire.", + "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697": "Vérifiez que les arguments des méthodes « bind », « call » et « apply » correspondent à la fonction d’origine.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Vérification en cours pour déterminer si '{0}' est le préfixe correspondant le plus long pour '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Définition circulaire de l'alias d'importation '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Circularité détectée durant la résolution de la configuration : {0}", + "Circularity_originates_in_type_at_this_location_2751": "La circularité est issue du type à cet emplacement.", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "La classe '{0}' définit l'accesseur de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme fonction de membre d'instance.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "La classe '{0}' définit la fonction de membre d'instance '{1}', mais la classe étendue '{2}' la définit comme accesseur de membre d'instance.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La classe '{0}' définit la propriété de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme fonction de membre d'instance.", + "Class_0_incorrectly_extends_base_class_1_2415": "La classe '{0}' étend de manière incorrecte la classe de base '{1}'.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La classe '{0}' implémente de manière incorrecte la classe '{1}'. Voulez-vous vraiment étendre '{1}' et hériter de ses membres en tant que sous-classe ?", + "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implémente de manière incorrecte l'interface '{1}'.", + "Class_0_used_before_its_declaration_2449": "Classe '{0}' utilisée avant sa déclaration.", + "Class_constructor_may_not_be_a_generator_1368": "Le constructeur de classe ne peut pas être un générateur.", + "Class_constructor_may_not_be_an_accessor_1341": "Le constructeur de la classe ne peut pas être un accesseur.", + "Class_declaration_cannot_implement_overload_list_for_0_2813": "La déclaration de classe ne peut pas implémenter la liste de surcharge pour «{0}».", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Les déclarations de classes ne peuvent pas avoir plusieurs balises '@augments' ou '@extends'.", + "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Impossible d'utiliser des éléments décoratifs de classe avec un identificateur privé static. Supprimez l'élément décoratif expérimental.", + "Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super_2855": "Le champ de classe « {0} » défini par la classe parente n’est pas accessible dans la classe enfant via super.", + "Class_name_cannot_be_0_2414": "Le nom de la classe ne peut pas être '{0}'.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Le nom de la classe ne peut pas être 'Object' quand ES5 est ciblé avec le module {0}.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Le côté statique de la classe '{0}' étend de manière incorrecte le côté statique de la classe de base '{1}'.", + "Classes_can_only_extend_a_single_class_1174": "Les classes ne peuvent étendre qu'une seule classe.", + "Classes_may_not_have_a_field_named_constructor_18006": "Les classes n'ont peut-être pas de champ nommé 'constructor'.", + "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210": "Le code contenu dans une classe est évalué en mode strict JavaScript qui n’autorise pas l’utilisation de « {0} ». Pour plus d’informations, consultez https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.", + "Command_line_Options_6171": "Options de ligne de commande", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compilez le projet en fonction du chemin de son fichier config ou d'un dossier contenant 'tsconfig.json'.", + "Compiler_Diagnostics_6251": "Diagnostics du compilateur", + "Compiler_option_0_cannot_be_given_an_empty_string_18051": "L’option du compilateur « {0} » ne peut pas recevoir une chaîne vide.", + "Compiler_option_0_expects_an_argument_6044": "L'option de compilateur '{0}' attend an argument.", + "Compiler_option_0_may_not_be_used_with_build_5094": "L’option '--{0}' du compilateur ne peut pas être utilisée avec '--build'.", + "Compiler_option_0_may_only_be_used_with_build_5093": "Option du compilateur '--{0}' ne peut être utilisée qu’avec '--build'.", + "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124": "L’option de compilateur « {0} » de la valeur «{1}» est instable. Utilisez TypeScript nocturne pour désactiver cette erreur. Essayez de mettre à jour avec « npm install -D typescript@next ».", + "Compiler_option_0_requires_a_value_of_type_1_5024": "L'option de compilateur '{0}' exige une valeur de type {1}.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Le compilateur réserve le nom '{0}' quand il émet un identificateur privé pour une version antérieure.", + "Compiles_the_TypeScript_project_located_at_the_specified_path_6927": "Compile le projet TypeScript situé au chemin d’accès spécifié.", + "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923": "Compile le projet actif (tsconfig.json sur le répertoire de travail.)", + "Compiles_the_current_project_with_additional_settings_6929": "Compile le projet actif, avec des paramètres supplémentaires.", + "Completeness_6257": "Exhaustivité", + "Composite_projects_may_not_disable_declaration_emit_6304": "Les projets composites ne doivent pas désactiver l'émission de déclaration.", + "Composite_projects_may_not_disable_incremental_compilation_6379": "Les projets composites ne doivent pas désactiver la compilation incrémentielle.", + "Computed_from_the_list_of_input_files_6911": "Calculé à partir de la liste des fichiers d’entrée", + "Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedD_9014": "Les propriétés calculées doivent être des littéraux de chaîne ou de nombre, des variables ou des expressions en pointillé avec --isolatedDeclarations.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Les noms de propriétés calculées ne sont pas autorisés dans les enums.", + "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038": "Les noms de propriétés calculées sur des littéraux de classe ou d’objet ne peuvent pas être déduits avec --isolatedDeclarations.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Les valeurs calculées ne sont pas autorisées dans un enum avec des membres ayant une valeur de chaîne.", + "Concatenate_and_emit_output_to_single_file_6001": "Concaténer la sortie et l'émettre vers un seul fichier.", + "Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports_6410": "Conditions à définir en plus des valeurs par défaut spécifiques au résolveur lors de la résolution des importations.", + "Conflicts_are_in_this_file_6201": "Il existe des conflits dans ce fichier.", + "Consider_adding_a_declare_modifier_to_this_class_6506": "Envisagez d’ajouter un modificateur « declare » à cette classe.", + "Construct_signature_return_types_0_and_1_are_incompatible_2203": "Les types de retour de signature de construction '{0}' et '{1}' sont incompatibles.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "La signature de construction, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour 'any'.", + "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205": "Les signatures de construction sans arguments ont des types de retour incompatibles : '{0}' et '{1}'.", + "Constructor_implementation_is_missing_2390": "L'implémentation de constructeur est manquante.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Le constructeur de la classe '{0}' est privé et uniquement accessible dans la déclaration de classe.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Le constructeur de la classe '{0}' est protégé et uniquement accessible dans la déclaration de classe.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386": "La notation de type d'un constructeur doit être placée entre parenthèses quand elle est utilisée dans un type union.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388": "La notation de type d'un constructeur doit être placée entre parenthèses quand elle est utilisée dans un type intersection.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "Les constructeurs pour les classes dérivées doivent contenir un appel de 'super'.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Fichier conteneur non spécifié et répertoire racine impossible à déterminer. Recherche ignorée dans le dossier 'node_modules'.", + "Containing_function_is_not_an_arrow_function_95128": "La fonction conteneur n'est pas une fonction arrow", + "Control_what_method_is_used_to_detect_module_format_JS_files_1475": "Contrôlez la méthode utilisée pour détecter les fichiers JS au format module.", + "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352": "La conversion du type '{0}' en type '{1}' est peut-être une erreur, car aucun type ne chevauche suffisamment l'autre. Si cela est intentionnel, convertissez d'abord l'expression en 'unknown'.", + "Convert_0_to_1_in_0_95003": "Convertir '{0}' en '{1} dans {0}'", + "Convert_0_to_mapped_object_type_95055": "Convertir '{0}' en type d'objet mappé", + "Convert_all_const_to_let_95102": "Convertir tous les 'const' en 'let'", + "Convert_all_constructor_functions_to_classes_95045": "Convertir toutes les fonctions de constructeur en classes", + "Convert_all_invalid_characters_to_HTML_entity_code_95101": "Convertir tous les caractères non valides en code d'entité HTML", + "Convert_all_re_exported_types_to_type_only_exports_1365": "Convertir tous les types réexportés en exportations de types uniquement", + "Convert_all_require_to_import_95048": "Convertir tous les 'require' en 'import'", + "Convert_all_to_async_functions_95066": "Tout convertir en fonctions asynchrones", + "Convert_all_to_bigint_numeric_literals_95092": "Tout convertir en littéraux numériques bigint", + "Convert_all_to_default_imports_95035": "Convertir tout en importations par défaut", + "Convert_all_type_literals_to_mapped_type_95021": "Convertir tous les littéraux de type en type mappé", + "Convert_all_typedef_to_TypeScript_types_95177": "Convertissez tous les typedef en types TypeScript.", + "Convert_arrow_function_or_function_expression_95122": "Convertir une fonction arrow ou une expression de fonction", + "Convert_const_to_let_95093": "Convertir 'const' en 'let'", + "Convert_default_export_to_named_export_95061": "Convertir l'exportation par défaut en exportation nommée", + "Convert_function_declaration_0_to_arrow_function_95106": "Convertir la déclaration de fonction '{0}' en fonction arrow", + "Convert_function_expression_0_to_arrow_function_95105": "Convertir l'expression de fonction '{0}' en fonction arrow", + "Convert_function_to_an_ES2015_class_95001": "Convertir la fonction en classe ES2015", + "Convert_invalid_character_to_its_html_entity_code_95100": "Convertir un caractère non valide en son code d'entité html", + "Convert_named_export_to_default_export_95062": "Convertir l'exportation nommée en exportation par défaut", + "Convert_named_imports_to_default_import_95170": "Convertir les importations nommées en importation par défaut", + "Convert_named_imports_to_namespace_import_95057": "Convertir les importations nommées en importation d'espace de noms", + "Convert_namespace_import_to_named_imports_95056": "Convertir l'importation d'espace de noms en importations nommées", + "Convert_overload_list_to_single_signature_95118": "Convertir la liste de surcharge en une seule signature", + "Convert_parameters_to_destructured_object_95075": "Convertir les paramètres en objet déstructuré", + "Convert_require_to_import_95047": "Convertir 'require' en 'import'", + "Convert_to_ES_module_95017": "Convertir en module ES", + "Convert_to_a_bigint_numeric_literal_95091": "Convertir en littéral numérique bigint", + "Convert_to_anonymous_function_95123": "Convertir en fonction anonyme", + "Convert_to_arrow_function_95125": "Convertir en fonction arrow", + "Convert_to_async_function_95065": "Convertir en fonction asynchrone", + "Convert_to_default_import_95013": "Convertir en importation par défaut", + "Convert_to_named_function_95124": "Convertir en fonction nommée", + "Convert_to_optional_chain_expression_95139": "Convertir en expression de chaîne facultative", + "Convert_to_template_string_95096": "Convertir en chaîne de modèle", + "Convert_to_type_only_export_1364": "Convertir en exportation de type uniquement", + "Convert_typedef_to_TypeScript_type_95176": "Convertissez typedef en type TypeScript.", + "Corrupted_locale_file_0_6051": "Fichier de paramètres régionaux endommagé : {0}.", + "Could_not_convert_to_anonymous_function_95153": "Impossible de convertir en fonction anonyme", + "Could_not_convert_to_arrow_function_95151": "Impossible de convertir en fonction arrow", + "Could_not_convert_to_named_function_95152": "Impossible de convertir en fonction nommée", + "Could_not_determine_function_return_type_95150": "Impossible de déterminer le type de retour de la fonction", + "Could_not_find_a_containing_arrow_function_95127": "Fonction arrow conteneur introuvable", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Le fichier de déclaration du module '{0}' est introuvable. '{1}' a implicitement un type 'any'.", + "Could_not_find_convertible_access_expression_95140": "L'expression d'accès convertible est introuvable", + "Could_not_find_export_statement_95129": "Instruction export introuvable", + "Could_not_find_import_clause_95131": "Clause import introuvable", + "Could_not_find_matching_access_expressions_95141": "L'expression d'accès correspondante est introuvable", + "Could_not_find_name_0_Did_you_mean_1_2570": "Le nom «{0}» est introuvable. Voulez-vous dire «{1}» ?", + "Could_not_find_namespace_import_or_named_imports_95132": "Impossible de localiser l'importation d'espace de noms ou les importations nommées", + "Could_not_find_property_for_which_to_generate_accessor_95135": "Impossible de localiser la propriété dont l'accesseur doit être généré", + "Could_not_find_variable_to_inline_95185": "Désolé... Nous n’avons pas pu trouver de variable à intégrer.", + "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Impossible de résoudre le chemin '{0}' avec les extensions {1}.", + "Could_not_write_file_0_Colon_1_5033": "Impossible d'écrire le fichier '{0}' : {1}.", + "Create_source_map_files_for_emitted_JavaScript_files_6694": "Créez des fichiers de mappage source pour les fichiers JavaScript émis.", + "Create_sourcemaps_for_d_ts_files_6614": "Créez des mappage de source pour les fichiers d.ts.", + "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926": "Crée un tsconfig.json avec les paramètres recommandés dans le répertoire de travail.", + "DIRECTORY_6038": "RÉPERTOIRE", + "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537": "Les séquences d’échappement décimales et les références arrière ne sont pas autorisées dans une classe de caractères.", + "Decimals_with_leading_zeros_are_not_allowed_1489": "Les décimales avec des zéros de début ne sont pas autorisées.", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "Cette déclaration augmente la déclaration dans un autre fichier. Cette opération ne peut pas être sérialisée.", + "Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_support_9026": "L’émission de déclaration pour ce fichier nécessite la conservation de cette importation pour des augmentations. Cette opération n’est pas pris en charge avec --isolatedDeclarations.", + "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "L'émission de déclaration pour ce fichier nécessite l'utilisation du nom privé '{0}'. Une annotation de type explicite peut débloquer l'émission de déclaration.", + "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "L'émission de déclaration pour ce fichier nécessite l'utilisation du nom privé '{0}' à partir du module '{1}'. Une annotation de type explicite peut débloquer l'émission de déclaration.", + "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_sup_9025": "L’émission de déclaration pour ce paramètre nécessite l’ajout implicite de « non défini » à son type. Cette opération n’est pas pris en charge avec --isolatedDeclarations.", + "Declaration_expected_1146": "Déclaration attendue.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Le nom de la déclaration est en conflit avec l'identificateur global intégré '{0}'.", + "Declaration_or_statement_expected_1128": "Déclaration ou instruction attendue.", + "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809": "Une déclaration ou instruction est attendue. Ce '=' suit un bloc d’instructions. Si vous avez l’intention d'écrire une affectation de déstructuration, il est possible que vous deviez mettre l’ensemble de l’affectation entre parenthèses.", + "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264": "Les déclarations avec des assertions d'affectation définies doivent également avoir des annotations de type.", + "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263": "Les déclarations avec des initialiseurs ne peuvent pas avoir également des assertions d'affectation définies.", + "Declare_a_private_field_named_0_90053": "Déclarez un champ privé nommé '{0}'.", + "Declare_method_0_90023": "Déclarer la méthode '{0}'", + "Declare_private_method_0_90038": "Déclarer la méthode privée '{0}'", + "Declare_private_property_0_90035": "Déclarer la propriété privée '{0}'", + "Declare_property_0_90016": "Déclarer la propriété '{0}'", + "Declare_static_method_0_90024": "Déclarer la méthode statique '{0}'", + "Declare_static_property_0_90027": "Déclarer la propriété statique '{0}'", + "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270": "Le type de retour de la fonction de décorateur '{0}' n’est pas attribuable au type '{1}'.", + "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271": "Le type de retour de la fonction de décorateur est '{0}' mais doit être 'void' ou 'any'.", + "Decorator_used_before_export_here_1486": "Élément décoratif utilisé ci avant « export ».", + "Decorators_are_not_valid_here_1206": "Les éléments décoratifs ne sont pas valides ici.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Impossible d'appliquer des éléments décoratifs à plusieurs accesseurs get/set du même nom.", + "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038": "Les éléments décoratifs ne peuvent pas apparaître après « export » ou « export default » s’ils apparaissent également avant « export ».", + "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436": "Les éléments décoratifs doivent précéder le nom et tous les mots clés des déclarations de propriété.", + "Default_catch_clause_variables_as_unknown_instead_of_any_6803": "Les variables de clause catch par défaut sont « unknown » au lieu de « any ».", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'exportation par défaut du module a utilisé ou utilise le nom privé '{0}'.", + "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037": "Les exportations par défaut ne peuvent peut pas être déduites avec --isolatedDeclarations.", + "Default_library_1424": "Bibliothèque par défaut", + "Default_library_for_target_0_1425": "Bibliothèque par défaut pour la cible '{0}'", + "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Les définitions des identificateurs suivants sont en conflit avec celles d'un autre fichier : {0}", + "Delete_all_unused_declarations_95024": "Supprimer toutes les déclarations inutilisées", + "Delete_all_unused_imports_95147": "Supprimer toutes les importations inutilisées", + "Delete_all_unused_param_tags_95172": "Supprimer toutes les balises '@param' inutilisées", + "Delete_the_outputs_of_all_projects_6365": "Supprimer les sorties de tous les projets.", + "Delete_unused_param_tag_0_95171": "Supprimer la balise '@param' inutilisée '{0}'", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Déconseillé] Utilisez '--jsxFactory' à la place. Permet de spécifier l'objet appelé pour createElement durant le ciblage de 'react' pour l'émission JSX", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Déconseillé] Utilisez '--outFile' à la place. Permet de concaténer et d'émettre la sortie vers un seul fichier", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Déconseillé] Utilisez '--skipLibCheck' à la place. Permet d'ignorer le contrôle de type des fichiers de déclaration de la bibliothèque par défaut.", + "Deprecated_setting_Use_outFile_instead_6677": "Paramètre déconseillé. Utilisez « outFile » à la place.", + "Did_you_forget_to_use_await_2773": "Avez-vous oublié d'utiliser 'await' ?", + "Did_you_mean_0_1369": "Est-ce que vous avez voulu utiliser '{0}' ?", + "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735": "Est-ce que vous avez voulu que '{0}' soit contraint en tant que type 'new (...args: any[]) => {1}' ?", + "Did_you_mean_to_call_this_expression_6212": "Est-ce que vous avez voulu appeler cette expression ?", + "Did_you_mean_to_mark_this_function_as_async_1356": "Est-ce que vous avez voulu marquer cette fonction comme étant 'async' ?", + "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312": "Voulez-vous vraiment utiliser le signe ':' ? Le signe '=' peut suivre uniquement un nom de propriété quand le littéral d'objet conteneur fait partie d'un modèle de déstructuration.", + "Did_you_mean_to_use_new_with_this_expression_6213": "Est-ce que vous avez voulu utiliser 'new' avec cette expression ?", + "Digit_expected_1124": "Chiffre attendu", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Le répertoire '{0}' n'existe pas. Toutes les recherches associées sont ignorées.", + "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270": "Le répertoire « {0} » ne comporte pas d'étendue package.json comme contenant. Les importations ne seront pas résolues.", + "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669": "Désactivez l’ajout de directives « use strict » dans les fichiers JavaScript émis.", + "Disable_checking_for_this_file_90018": "Désactiver la vérification de ce fichier", + "Disable_emitting_comments_6688": "Désactivez les commentaires émettant.", + "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701": "Désactivez l’émission de déclarations qui ont « @internal » dans leurs commentaires JSDoc.", + "Disable_emitting_files_from_a_compilation_6660": "Désactivez l’émission des fichiers à partir d’une compilation.", + "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662": "Désactivez l’émission de fichiers si des erreurs de vérification de type sont signalées.", + "Disable_erasing_const_enum_declarations_in_generated_code_6682": "Désactivez l’effacement des déclarations « const enum » dans le code généré.", + "Disable_error_reporting_for_unreachable_code_6603": "Désactivez le rapport d’erreurs pour le code inaccessible.", + "Disable_error_reporting_for_unused_labels_6604": "Désactivez le rapport d’erreurs pour les étiquettes inutilisées.", + "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805": "Désactivez la vérification complète des types (seules les erreurs critiques d’analyse et d’émission sont signalées).", + "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661": "Désactiver la création de fonctions d'assistance personnalisées comme «__extends» dans la sortie compilée.", + "Disable_including_any_library_files_including_the_default_lib_d_ts_6670": "Désactivez l’inclusion des fichiers de bibliothèque, y compris la valeur par défaut de lib.d.ts.", + "Disable_loading_referenced_projects_6235": "Désactivez le chargement des projets référencés.", + "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620": "Désactiver la préférence des fichiers sources à la place des fichiers de déclaration lors du référencement des projets composites.", + "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702": "Désactivez le signalement d’erreurs de propriétés excessives lors de la création de littéraux d’objet.", + "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683": "Désactivez la résolution des liens symboliques vers leur chemin d’accès réel. Cela correspond au même indicateur dans le nœud.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Désactivez les limitations de taille sur les projets JavaScript.", + "Disable_solution_searching_for_this_project_6224": "Désactivez la recherche de solutions pour ce projet.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6673": "Désactivez la vérification stricte des signatures génériques dans les types de fonction.", + "Disable_the_type_acquisition_for_JavaScript_projects_6625": "Désactiver l’acquisition de type pour les projets JavaScript", + "Disable_truncating_types_in_error_messages_6663": "Désactivez les types tronqués dans les messages d’erreur.", + "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221": "Désactivez l'utilisation des fichiers sources à la place des fichiers de déclaration dans les projets référencés.", + "Disable_wiping_the_console_in_watch_mode_6684": "Désactiver la réinitialisation de la console en mode espion.", + "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616": "Désactive l’inférence pour l’acquisition de type en examinant des noms de fichiers dans un projet.", + "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672": "Interdire à « import », « require » ou « » d’étendre le nombre de fichiers que TypeScript doit ajouter à un projet.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Interdisez les références dont la casse est incohérente dans le même fichier.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "N'ajoutez pas de références avec trois barres obliques, ni de modules importés à la liste des fichiers compilés.", + "Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript_6721": "N’autorisez pas les constructions d’exécution qui ne font pas partie d’ECMAScript.", + "Do_not_emit_comments_to_output_6009": "Ne pas émettre de commentaires dans la sortie.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "N'émettez pas de déclarations pour du code ayant une annotation '@internal'.", + "Do_not_emit_outputs_6010": "N'émettez pas de sorties.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "N'émettez pas de sortie si des erreurs sont signalées.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "N'émettez pas de directives 'use strict' dans une sortie de module.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "N'effacez pas les déclarations d'enum const dans le code généré.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Ne générez pas de fonctions d'assistance personnalisées comme '__extends' dans la sortie compilée.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "N'incluez pas le fichier bibliothèque par défaut (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Ne signalez pas les erreurs pour le code inaccessible.", + "Do_not_report_errors_on_unused_labels_6074": "Ne signalez pas les erreurs pour les étiquettes inutilisées.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Ne pas résoudre le chemin réel des liens symboliques.", + "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804": "Ne transformez ou n’elidez pas les importations ou exportations non marquées en tant que type uniquement, en veillant à ce qu’elles soient écrites dans le format du fichier de sortie en fonction du paramètre « module ».", + "Do_not_truncate_error_messages_6165": "Ne tronquez pas les messages d'erreur.", + "Duplicate_function_implementation_2393": "Implémentation de fonction en double.", + "Duplicate_identifier_0_2300": "Identificateur '{0}' en double.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificateur '{0}' en double. Le compilateur réserve le nom '{1}' dans l'étendue de plus haut niveau d'un module.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "Identificateur '{0}' en double. Le compilateur réserve le nom '{1}' dans la portée de plus haut niveau d'un module contenant des fonctions async.", + "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818": "Identificateur en double «{0}». Le compilateur réserve le nom «{1}» lors de l’émission de références « super » dans les initialiseurs statiques.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificateur '{0}' en double. Le compilateur utilise la déclaration '{1}' pour prendre en charge les fonctions async.", + "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804": "Identificateur '{0}' dupliqué. Les éléments statiques et les éléments d'instance ne peuvent pas partager le même nom privé.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificateur dupliqué 'arguments'. Le compilateur utilise 'arguments' pour initialiser les paramètres rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Dupliquez l'identificateur '_newTarget'. Le compilateur utilise la déclaration de variable '_newTarget' pour capturer la référence de méta-propriété 'new.target'.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificateur dupliqué '_this'. Le compilateur utilise la déclaration de variable '_this' pour capturer la référence 'this'.", + "Duplicate_index_signature_for_type_0_2374": "Doublon de signature d’index pour le type « {0} ».", + "Duplicate_label_0_1114": "Étiquette '{0}' en double.", + "Duplicate_property_0_2718": "Propriété dupliquée '{0}'.", + "Duplicate_regular_expression_flag_1500": "L’indicateur d’expression régulière est dupliqué.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Le spécificateur de l'importation dynamique doit être de type 'string', mais ici il est de type '{0}'.", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Les importations dynamiques sont prises en charge uniquement lorsque l’indicateur « --module » est défini sur « es2020 », « es2022 », « esnext », « commonjs », « amd », « system », « umd », « node16 », « node18 » ou « nodenext ».", + "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments_1450": "Les importations dynamiques peuvent accepter uniquement un spécificateur de module et un ensemble facultatif d’attributs en tant qu’arguments", + "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_1324": "Les importations dynamiques prennent uniquement en charge un deuxième argument lorsque l’option « --module » est définie sur « esnext », « node16 », « node18 », « nodenext » ou « preserve ».", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve_1293": "La syntaxe ESM n’est pas autorisée dans un module CommonJS quand « module » a la valeur « preserve ».", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled_1286": "La syntaxe ESM n'est pas autorisée dans un module CommonJS lorsque « verbatimModuleSyntax » est activé.", + "Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given_4125": "Chaque déclaration de '{0}.{1}' diffère dans sa valeur, où '{2}' était attendu, mais '{3}' a été donné.", + "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Chaque membre du type union '{0}' a des signatures de construction, mais aucune de ces signatures n'est compatible avec les autres.", + "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758": "Chaque membre du type union '{0}' a des signatures, mais aucune de ces signatures n'est compatible avec les autres.", + "Editor_Support_6249": "Prise en charge de l’Éditeur", + "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053": "L'élément a implicitement un type 'any', car l'expression de type '{0}' ne peut pas être utilisée pour indexer le type '{1}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'élément possède implicitement un type 'any', car l'expression d'index n'est pas de type 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "L'élément a implicitement un type 'any', car le type '{0}' n'a aucune signature d'index.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052": "L'élément a implicitement un type 'any', car le type '{0}' n'a aucune signature d'index. Est-ce que vous avez voulu appeler '{1}' ?", + "Emit_6246": "Émet", + "Emit_ECMAScript_standard_compliant_class_fields_6712": "Émettez des champs de classe conformes à la norme ECMAScript.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622": "Émettez une marque d'ordre d'octet (BOM) UTF-8 au début des fichiers de sortie.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Émettez un seul fichier avec des mappages de sources au lieu d'avoir un fichier distinct.", + "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638": "Émettez un profil processeur V8 de l’exécution du compilateur pour le débogage.", + "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626": "Émettez un code JavaScript supplémentaire pour simplifier la prise en charge de l’importation des modules CommonJS. Cela permet à « allowSyntheticDefaultImports » d’être compatible avec le type.", + "Emit_class_fields_with_Define_instead_of_Set_6222": "Émettez des champs de classe avec Define à la place de Set.", + "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624": "Émettez des métadonnées de type conception pour les déclarations décorées dans les fichiers sources.", + "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621": "Émettez des JavaScript plus conformes, mais plus détaillés et moins performants pour l’itération.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Émettez la source aux côtés des mappages de sources dans un fichier unique. Nécessite la définition de '--inlineSourceMap' ou '--sourceMap'.", + "Enable_all_strict_type_checking_options_6180": "Activez toutes les options de contrôle de type strict.", + "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685": "Activer la couleur et la mise en forme dans la sortie de TypeScript pour faciliter la lecture des erreurs du compilateur.", + "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611": "Activez les contraintes qui autorisent l’utilisation d’un projet TypeScript avec des références de projet.", + "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667": "Activez le rapport d’erreurs pour les chemins de code qui ne sont pas explicitement renvoyés dans une fonction.", + "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665": "Activez le rapport d’erreurs pour les expressions et les déclarations avec un type « any » implicite.", + "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664": "Activez le rapport d’erreurs pour les cas échoués dans les instructions switch.", + "Enable_error_reporting_in_type_checked_JavaScript_files_6609": "Activez le rapport d’erreurs dans les fichiers JavaScript vérifiés par type.", + "Enable_error_reporting_when_local_variables_aren_t_read_6675": "Activez le rapport d’erreurs lorsque les variables locales ne sont pas lues.", + "Enable_error_reporting_when_this_is_given_the_type_any_6668": "Activez le rapport d’erreurs lorsque « this » reçoit le type « any ».", + "Enable_experimental_support_for_legacy_experimental_decorators_6630": "Activez la prise en charge expérimentale des éléments décoratifs expérimentaux hérités.", + "Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present_6264": "Activez l’importation de fichiers avec n’importe quelle extension, à condition qu’un fichier de déclaration soit présent.", + "Enable_importing_json_files_6689": "Activer l’importation des fichiers .json.", + "Enable_lib_replacement_6808": "Activez le remplacement de la bibliothèque.", + "Enable_project_compilation_6302": "Activer la compilation du projet", + "Enable_strict_bind_call_and_apply_methods_on_functions_6214": "Activez des méthodes 'bind', 'call' et 'apply' strictes sur les fonctions.", + "Enable_strict_checking_of_function_types_6186": "Activez la vérification stricte des types de fonction.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Activez la vérification stricte de l'initialisation des propriétés dans les classes.", + "Enable_strict_null_checks_6113": "Activez strict null checks.", + "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074": "Activer l'option 'experimentalDecorators' dans votre fichier config", + "Enable_the_jsx_flag_in_your_configuration_file_95088": "Activer l'indicateur '--jsx' dans votre fichier config", + "Enable_tracing_of_the_name_resolution_process_6085": "Activez le traçage du processus de résolution de noms.", + "Enable_verbose_logging_6713": "Activer la journalisation détaillée.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Active l'interopérabilité entre les modules CommonJS et ES via la création d'objets d'espace de noms pour toutes les importations. Implique 'allowSyntheticDefaultImports'.", + "Enables_experimental_support_for_ES7_decorators_6065": "Active la prise en charge expérimentale des éléments décoratifs ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Active la prise en charge expérimentale pour l'émission des métadonnées de type pour les éléments décoratifs.", + "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671": "Applique l’utilisation d’accesseurs indexés pour les clés déclarées à l’aide d’un type indexé.", + "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666": "Vérifiez que les membres de substitution dans les classes dérivées sont marqués avec un modificateur de remplacement.", + "Ensure_that_casing_is_correct_in_imports_6637": "Assurez-vous que la casse est correcte dans les importations.", + "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645": "Assurez-vous que chaque fichier peut être recompilé en toute sécurité sans s’appuyer sur d’autres importations.", + "Ensure_use_strict_is_always_emitted_6605": "Assurez-vous que « use strict » est toujours émis.", + "Entering_conditional_exports_6413": "Entrée dans des exportations conditionnelles.", + "Entry_point_for_implicit_type_library_0_1420": "Point d'entrée pour la bibliothèque de types implicites '{0}'", + "Entry_point_for_implicit_type_library_0_with_packageId_1_1421": "Point d'entrée pour la bibliothèque de types implicites '{0}' ayant le packageId '{1}'", + "Entry_point_of_type_library_0_specified_in_compilerOptions_1417": "Point d'entrée de la bibliothèque de types '{0}' spécifiée dans compilerOptions", + "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418": "Point d'entrée de la bibliothèque de types '{0}' spécifiée dans compilerOptions et ayant le packageId '{1}'", + "Enum_0_used_before_its_declaration_2450": "Enum '{0}' utilisé avant sa déclaration.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Les déclarations enum ne peuvent fusionner qu'avec des espaces de noms ou d'autres déclarations enum.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Les déclarations d'enum doivent toutes être const ou non const.", + "Enum_member_expected_1132": "Membre enum attendu.", + "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056": "Le membre Enum suivant un membre numérique non littéral doit avoir un initialiseur lorsque « isolatedModules » est activé.", + "Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDecl_9020": "Les initialiseurs de membre enum doivent être calculables sans référence à des symboles externes avec --isolatedDeclarations.", + "Enum_member_must_have_initializer_1061": "Un membre enum doit posséder un initialiseur.", + "Enum_name_cannot_be_0_2431": "Le nom d'enum ne peut pas être '{0}'.", + "Errors_Files_6041": "Fichiers d’erreurs", + "Escape_sequence_0_is_not_allowed_1488": "La séquence d’échappement « {0} » n’est pas autorisée.", + "Examples_Colon_0_6026": "Exemples : {0}", + "Excessive_complexity_comparing_types_0_and_1_2859": "Complexité excessive comparant les types « {0} » et « {1} ».", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profondeur excessive de la pile pour la comparaison des types '{0}' et '{1}'.", + "Exiting_conditional_exports_6416": "Sortie des exportations conditionnelles.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Arguments de type {0}-{1} attendus ; indiquez-les avec la balise '@extends'.", + "Expected_0_arguments_but_got_1_2554": "{0} arguments attendus, mais {1} reçus.", + "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794": "{0} arguments attendus, mais {1} reçus. Avez-vous oublié d'inclure 'void' dans votre argument de type pour 'Promise' ?", + "Expected_0_type_arguments_but_got_1_2558": "{0} arguments de type attendus, mais {1} reçus.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Arguments de type {0} attendus ; indiquez-les avec la balise '@extends'.", + "Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_2810": "1 argument attendu, mais 0 obtenu. 'new Promise()' a besoin d’un indicateur JSDoc pour produire un 'resolve' qui peut être appelé sans arguments.", + "Expected_a_Unicode_property_name_1523": "Le nom de propriété Unicode est attendu.", + "Expected_a_Unicode_property_name_or_value_1527": "Une valeur ou un nom de propriété Unicode est attendu.", + "Expected_a_Unicode_property_value_1525": "La valeur de propriété Unicode est attendue.", + "Expected_a_capturing_group_name_1514": "Le nom de groupe de capture est attendu.", + "Expected_a_class_set_operand_1520": "Une opérande de jeu de classes est attendue.", + "Expected_at_least_0_arguments_but_got_1_2555": "Au moins {0} arguments attendus, mais {1} reçus.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "Balise de fermeture JSX correspondante attendue pour '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Balise de fermeture correspondante attendue pour le fragment JSX.", + "Expected_for_property_initializer_1442": "« = » attendu pour l’initialiseur de propriété.", + "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105": "Le type attendu du champ '{0}' dans 'package.json' est censé être '{1}'. Obtention de '{2}'.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Spécification explicite du genre de résolution de module : '{0}'.", + "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Impossible d'effectuer l'élévation à une puissance sur des valeurs 'bigint' sauf si l'option 'target' a la valeur 'es2016' ou une valeur qui correspond à une version ultérieure.", + "Export_0_from_module_1_90059": "Exporter '{0}' à partir du module '{1}'", + "Export_all_referenced_locals_90060": "Exporter tous les variables locales référencées", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Vous ne pouvez pas utiliser l'assignation d'exportation pour cibler des modules ECMAScript. Utilisez 'export default' ou un autre format de module à la place.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "L'assignation d'exportation n'est pas prise en charge quand l'indicateur '--module' est 'system'.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La déclaration d'exportation est en conflit avec la déclaration exportée de '{0}'.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Les déclarations d'exportation ne sont pas autorisées dans un espace de noms.", + "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276": "Le spécificateur d’exportation « {0} » n’existe pas dans l’étendue package.json sur le chemin d’accès « {1} ».", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "L'alias de type exporté '{0}' possède ou utilise le nom privé '{1}'.", + "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084": "L'alias de type exporté '{0}' a ou utilise le nom privé '{1}' du module {2}.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "La variable exportée '{0}' possède ou utilise le nom '{1}' du module externe {2}, mais elle ne peut pas être nommée.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "La variable exportée '{0}' possède ou utilise le nom '{1}' du module privé '{2}'.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "La variable exportée '{0}' possède ou utilise le nom privé '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Les exportations et les assignations d'exportation ne sont pas autorisées dans les augmentations de module.", + "Expression_expected_1109": "Expression attendue.", + "Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator_1497": "L’expression doit être entre parenthèses pour être utilisée comme élément décoratif.", + "Expression_or_comma_expected_1137": "Expression ou virgule attendue.", + "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800": "L'expression produit un type de tuple trop grand pour être représenté.", + "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590": "L'expression produit un type union trop complexe à représenter.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "Expression résolue en '_super' et utilisée par le compilateur pour capturer la référence de classe de base.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "L'expression génère une déclaration de variable '_newTarget' que le compilateur utilise pour capturer la référence de méta-propriété 'new.target'.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Expression résolue en déclaration de variable '_this' et utilisée par le compilateur pour capturer la référence 'this'.", + "Expression_type_can_t_be_inferred_with_isolatedDeclarations_9013": "Le type d'expression ne peut pas être déduit avec --isolatedDeclarations.", + "Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations_9021": "La clause Extends ne peut pas contenir d’expression avec --isolatedDeclarations.", + "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085": "La clause Extends pour le type déduit « {0} » a ou utilise le nom privé « {1} ».", + "Extract_base_class_to_variable_90064": "Extraire la classe de base dans la variable", + "Extract_binding_expressions_to_variable_90066": "Extraire des expressions de liaison dans une variable", + "Extract_constant_95006": "Extraire la constante", + "Extract_default_export_to_variable_90065": "Extraire l’exportation par défaut vers la variable", + "Extract_function_95005": "Extraire la fonction", + "Extract_to_0_in_1_95004": "Extraire vers {0} dans {1}", + "Extract_to_0_in_1_scope_95008": "Extraire vers {0} dans la portée {1}", + "Extract_to_0_in_enclosing_scope_95007": "Extraire vers {0} dans la portée englobante", + "Extract_to_interface_95090": "Extraire vers l'interface", + "Extract_to_type_alias_95078": "Extraire vers l'alias de type", + "Extract_to_typedef_95079": "Extraire vers typedef", + "Extract_to_variable_and_replace_with_0_as_typeof_0_90069": "Extraire dans la variable et remplacer par '{0} en tant que typeof {0}'", + "Extract_type_95077": "Type d'extraction", + "FILE_6035": "FICHIER", + "FILE_OR_DIRECTORY_6040": "FICHIER OU RÉPERTOIRE", + "Failed_to_find_peerDependency_0_6283": "Échec de la recherche de peerDependency '{0}'.", + "Failed_to_resolve_under_condition_0_6415": "Échec de la résolution sous la condition «{0}».", + "Fallthrough_case_in_switch_7029": "Case avec fallthrough dans une instruction switch.", + "File_0_does_not_exist_6096": "Le fichier '{0}' n'existe pas.", + "File_0_does_not_exist_according_to_earlier_cached_lookups_6240": "Selon des recherches mises en cache antérieures, le fichier '{0}' n’existe pas.", + "File_0_exists_according_to_earlier_cached_lookups_6239": "Selon des recherches mises en cache antérieures, le fichier '{0}' existe.", + "File_0_exists_use_it_as_a_name_resolution_result_6097": "Le fichier '{0}' existe - utilisez-le comme résultat de résolution de nom.", + "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054": "Le fichier '{0}' a une extension non prise en charge. Les seules extensions prises en charge sont {1}.", + "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504": "Le fichier '{0}' est un fichier JavaScript. Est-ce que vous avez voulu activer l'option 'allowJs' ?", + "File_0_is_not_a_module_2306": "Le fichier '{0}' n'est pas un module.", + "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307": "Le fichier '{0}' ne figure pas dans la liste de fichiers du projet '{1}'. Les projets doivent lister tous les fichiers ou utiliser un modèle 'include'.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Le fichier '{0}' ne se trouve pas sous 'rootDir' '{1}'. 'rootDir' est supposé contenir tous les fichiers sources.", + "File_0_not_found_6053": "Fichier '{0}' introuvable.", + "File_Management_6245": "Gestion de fichiers", + "File_appears_to_be_binary_1490": "Le fichier semble être binaire.", + "File_change_detected_Starting_incremental_compilation_6032": "Modification de fichier détectée. Démarrage de la compilation incrémentielle...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Le fichier est un module CommonJS, car « {0} » n’a pas de champ « type »", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Le fichier est un module CommonJS, car « {0} » a un champ « type » dont la valeur n’est pas « module »", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Le fichier est un module CommonJS, car « package.json » est introuvable", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Le fichier est un module ECMAScript, car « {0} » a un champ « type » avec la valeur « module »", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Le fichier est un module CommonJS ; il peut être converti en module ES.", + "File_is_default_library_for_target_specified_here_1426": "Le fichier représente la bibliothèque par défaut de la cible spécifiée ici.", + "File_is_entry_point_of_type_library_specified_here_1419": "Le fichier représente le point d'entrée de la bibliothèque de types spécifiée ici.", + "File_is_included_via_import_here_1399": "Le fichier est inclus via une importation ici.", + "File_is_included_via_library_reference_here_1406": "Le fichier est inclus via une référence à la bibliothèque ici.", + "File_is_included_via_reference_here_1401": "Le fichier est inclus via une référence ici.", + "File_is_included_via_type_library_reference_here_1404": "Le fichier est inclus via une référence à la bibliothèque de types ici.", + "File_is_library_specified_here_1423": "Le fichier représente la bibliothèque spécifiée ici.", + "File_is_matched_by_files_list_specified_here_1410": "Le fichier correspond à la liste 'files' spécifiée ici.", + "File_is_matched_by_include_pattern_specified_here_1408": "Le fichier correspond au modèle include spécifié ici.", + "File_is_output_from_referenced_project_specified_here_1413": "Le fichier représente la sortie du projet référencé spécifié ici.", + "File_is_output_of_project_reference_source_0_1428": "Le fichier représente la sortie de la source de référence de projet '{0}'", + "File_is_source_from_referenced_project_specified_here_1416": "Le fichier représente la source du projet référencé spécifié ici.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Le nom de fichier '{0}' diffère du nom de fichier '{1}' déjà inclus uniquement par la casse.", + "File_name_0_has_a_1_extension_looking_up_2_instead_6262": "Le nom de fichier '{0}' a une extension '{1}' - recherche '{2}' à la place.", + "File_name_0_has_a_1_extension_stripping_it_6132": "Le nom de fichier '{0}' a une extension '{1}'. Suppression de l'extension.", + "File_redirects_to_file_0_1429": "Le fichier est redirigé vers le fichier '{0}'", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La spécification de fichier ne peut pas contenir un répertoire parent ('..') après un caractère générique de répertoire récursif ('**') : '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Une spécification de fichier ne peut pas se terminer par un caractère générique de répertoire récursif ('**') : '{0}'.", + "Filters_results_from_the_include_option_6627": "Filtre les résultats de l’option « inclure ».", + "Fix_all_detected_spelling_errors_95026": "Corriger toutes les fautes d'orthographe détectées", + "Fix_all_expressions_possibly_missing_await_95085": "Corriger toutes les expressions où il manque éventuellement 'await'", + "Fix_all_implicit_this_errors_95107": "Corriger toutes les erreurs implicites liées à 'this'", + "Fix_all_incorrect_return_type_of_an_async_functions_90037": "Corriger tous les types de retour incorrects des fonctions asynchrone", + "Fix_all_with_type_only_imports_95182": "Corriger tout avec des importations de type uniquement", + "Found_0_errors_6217": "{0} erreurs trouvées.", + "Found_0_errors_Watching_for_file_changes_6194": "{0} erreurs trouvées. Changements de fichier sous surveillance.", + "Found_0_errors_in_1_files_6261": "Erreurs {0} trouvées dans les fichiers {1} .", + "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260": "Erreurs {0} trouvées dans le même fichier, à partir de : {1}", + "Found_1_error_6216": "1 erreur trouvée.", + "Found_1_error_Watching_for_file_changes_6193": "1 erreur trouvée. Changements de fichier sous surveillance.", + "Found_1_error_in_0_6259": "1 erreur trouvée dans {0}", + "Found_package_json_at_0_6099": "'package.json' trouvé sur '{0}'.", + "Found_peerDependency_0_with_1_version_6282": "PeerDependency '{0}' trouvé avec '{1}' version.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_1250": "Les déclarations de fonction ne sont pas autorisées à l’intérieur des blocs en mode strict lors du ciblage de « ES5 ».", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definiti_1251": "Les déclarations de fonction ne sont pas autorisées à l’intérieur des blocs en mode strict lors du ciblage de « ES5 ». Les définitions de classe sont automatiquement en mode strict.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_au_1252": "Les déclarations de fonction ne sont pas autorisées à l’intérieur des blocs en mode strict lors du ciblage de « ES5 ». Les modules sont automatiquement en mode strict.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "L'expression de fonction, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour '{0}'.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "L'implémentation de fonction est manquante ou ne suit pas immédiatement la déclaration.", + "Function_implementation_name_must_be_0_2389": "Le nom de l'implémentation de fonction doit être '{0}'.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La fonction possède implicitement le type de retour 'any', car elle n'a pas d'annotation de type de retour, et est référencée directement ou indirectement dans l'une de ses expressions de retour.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "La fonction n'a pas d'instruction return de fin, et le type de retour n'inclut pas 'undefined'.", + "Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9007": "La fonction doit avoir une annotation de type de retour explicite avec --isolatedDeclarations.", + "Function_not_implemented_95159": "Fonction non implémentée.", + "Function_overload_must_be_static_2387": "La surcharge de fonction doit être statique.", + "Function_overload_must_not_be_static_2388": "La surcharge de fonction ne doit pas être statique.", + "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385": "La notation de type d'une fonction doit être placée entre parenthèses quand elle est utilisée dans un type union.", + "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387": "La notation de type d'une fonction doit être placée entre parenthèses quand elle est utilisée dans un type intersection.", + "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014": "Le type de fonction, qui n'a pas d'annotation de type de retour, a implicitement le type de retour '{0}'.", + "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814": "La fonction avec des corps ne peut fusionner qu’avec des classes qui sont ambiantes.", + "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612": "Générez des fichiers .d.ts à partir de fichiers TypeScript et JavaScript dans votre projet.", + "Generate_get_and_set_accessors_95046": "Générer les accesseurs 'get' et 'set'", + "Generate_get_and_set_accessors_for_all_overriding_properties_95119": "Générer des accesseurs 'get' et 'set' pour toutes les propriétés de remplacement", + "Generates_a_CPU_profile_6223": "Génère un profil de processeur.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Génère un mappage de source pour chaque fichier '.d.ts' correspondant.", + "Generates_an_event_trace_and_a_list_of_types_6237": "Génère une trace d'événement et une liste de types.", + "Generates_corresponding_d_ts_file_6002": "Génère le fichier '.d.ts' correspondant.", + "Generates_corresponding_map_file_6043": "Génère le fichier '.map' correspondant.", + "Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation_7025": "Le générateur a implicitement un type de rendement « {0} ». Envisagez de fournir une annotation de type de retour.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "Les générateurs ne sont pas autorisés dans un contexte ambiant.", + "Generic_type_0_requires_1_type_argument_s_2314": "Le type générique '{0}' exige {1} argument(s) de type.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Le type générique '{0}' nécessite entre {1} et {2} arguments de type.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Les exportations de modules globaux ne peuvent apparaître qu'au niveau supérieur.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Les exportations de modules globaux ne peuvent apparaître que dans les fichiers de déclaration.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Les exportations de modules globaux ne peuvent apparaître que dans les fichiers de module.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Le type global '{0}' doit être un type de classe ou d'interface.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Le type global '{0}' doit avoir {1} paramètre(s) de type.", + "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384": "Les recompilations dans '--incremental' et '--watch' supposent que les changements apportés à un fichier affectent uniquement les fichiers qui dépendent directement de ce fichier.", + "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606": "Les recompilations dans les projets qui utilisent le mode « incrémentiel » et « espion » supposent que les modifications au sein d’un fichier affectent uniquement les fichiers directement en fonction de celui-ci.", + "Hexadecimal_digit_expected_1125": "Chiffre hexadécimal attendu.", + "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262": "Identificateur attendu. '{0}' est un mot réservé au niveau supérieur d'un module.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "Identificateur attendu. '{0}' est un mot réservé en mode strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "Identificateur attendu. '{0}' est un mot réservé en mode strict. Les définitions de classe sont automatiquement en mode strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Identificateur attendu. '{0}' est un mot réservé en mode strict. Les modules sont automatiquement en mode strict.", + "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Identificateur attendu. '{0}' est un mot réservé qui ne peut pas être utilisé ici.", + "Identifier_expected_1003": "Identificateur attendu.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificateur attendu. '__esModule' est réservé en tant que marqueur exporté durant la transformation des modules ECMAScript.", + "Identifier_or_string_literal_expected_1478": "Identificateur ou littéral de chaîne attendu", + "Identifier_string_literal_or_number_literal_expected_1496": "Identificateur, littéral de chaîne ou littéral de nombre attendu.", + "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Si le package '{0}' expose réellement ce module, envoyez une demande de tirage (pull request) pour modifier 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'", + "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Si le package' {0} 'expose effectivement ce module, essayez d’ajouter un nouveau fichier de déclaration (. d. TS) contenant’declare module' {1} '; '", + "Ignore_this_error_message_90019": "Ignorer ce message d'erreur", + "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924": "Ignore tsconfig.json, compile les fichiers spécifiés avec les options du compilateur par défaut.", + "Implement_all_inherited_abstract_classes_95040": "Implémenter toutes les classes abstraites héritées", + "Implement_all_unimplemented_interfaces_95032": "Implémenter toutes les interfaces non implémentées", + "Implement_inherited_abstract_class_90007": "Implémenter la classe abstraite héritée", + "Implement_interface_0_90006": "Implémenter l'interface '{0}'", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La clause implements de la classe exportée '{0}' possède ou utilise le nom privé '{1}'.", + "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731": "La conversion implicite de 'symbol' en 'string' va échouer au moment de l'exécution. Incluez dans un wrapper cette expression en 'String(...)'.", + "Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_w_2866": "L’importation «{0}» est en conflit avec la valeur globale utilisée dans ce fichier. Elle doit donc être déclarée avec une importation de type uniquement lorsque ' isolatedModules ' est activé.", + "Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_2865": "L’importation '{0}' est en conflit avec la valeur locale. Elle doit donc être déclarée avec une importation de type uniquement lorsque 'isolatedModules' est activé.", + "Import_0_from_1_90013": "Importez '{0}' à partir de \"{1}\".", + "Import_assertion_values_must_be_string_literal_expressions_2837": "Les valeurs d’assertion d’importation doivent être des expressions littérales de chaîne.", + "Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2836": "Les assertions d’importation ne sont pas autorisées sur les instructions qui se compilent en appels CommonJS ' require'.", + "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2821": "Les assertions d’importation sont prises en charge uniquement lorsque l’option « --module » est définie sur « esnext », « node18 », « nodenext » ou « preserve ».", + "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822": "Les assertions d’importation ne peuvent pas être utilisées avec les importations ou exportations de type uniquement.", + "Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880": "Les assertions d’importation ont été remplacées par des attributs d’importation. Utilisez 'with' à la place de 'assert'.", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Vous ne pouvez pas utiliser l'assignation d'importation pour cibler des modules ECMAScript. Utilisez plutôt 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' ou un autre format de module.", + "Import_attribute_values_must_be_string_literal_expressions_2858": "Les valeurs d’attribut d’importation doivent être des expressions littérales de chaîne.", + "Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2856": "Les attributs d’importation ne sont pas autorisés sur les instructions qui se compilent en appels CommonJS ' require'.", + "Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2823": "Les attributs d’importation sont pris en charge uniquement lorsque l’option « --module » a la valeur « esnext », « node18 », « nodenext » ou « preserve ».", + "Import_attributes_cannot_be_used_with_type_only_imports_or_exports_2857": "Les attributs d’importation ne peuvent pas être utilisés avec des importations ou des exportations de type uniquement.", + "Import_declaration_0_is_using_private_name_1_4000": "La déclaration d'importation '{0}' utilise le nom privé '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La déclaration d'importation est en conflit avec la déclaration locale de '{0}'.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Les déclarations d'importation dans un espace de noms ne peuvent pas référencer un module.", + "Import_emit_helpers_from_tslib_6139": "Importer l'assistance à l'émission à partir de 'tslib'.", + "Import_may_be_converted_to_a_default_import_80003": "L'importation peut être convertie en importation par défaut.", + "Import_name_cannot_be_0_2438": "Le nom d'importation ne peut pas être '{0}'.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Une déclaration d'importation ou d'exportation dans une déclaration de module ambiant ne peut référencer un module au moyen d'un nom de module relatif.", + "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271": "Le spécificateur d’importation « {0} » n’existe pas dans l’étendue package.json sur le chemin d’accès « {1} ».", + "Imported_via_0_from_file_1_1393": "Importé(e) via {0} à partir du fichier '{1}'", + "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395": "Importé(e) via {0} à partir du fichier '{1}' pour importer 'importHelpers' comme indiqué dans compilerOptions", + "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397": "Importé(e) via {0} à partir du fichier '{1}' pour importer les fonctions de fabrique 'jsx' et 'jsxs'", + "Imported_via_0_from_file_1_with_packageId_2_1394": "Importé(e) via {0} à partir du fichier '{1}' ayant le packageId '{2}'", + "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396": "Importé(e) via {0} à partir du fichier '{1}' ayant le packageId '{2}' pour importer 'importHelpers' comme indiqué dans compilerOptions", + "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398": "Importé(e) via {0} à partir du fichier '{1}' ayant le packageId '{2}' pour importer les fonctions de fabrique 'jsx' et 'jsxs'", + "Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_mod_1543": "L'importation d'un fichier JSON dans un module ECMAScript nécessite un attribut d'importation « type : « json » » lorsque « module » est défini sur « {0} ».", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Les importations ne sont pas autorisées dans les augmentations de module. Déplacez-les vers le module externe englobant.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Dans les déclarations d'enums ambiants, l'initialiseur de membre doit être une expression constante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Dans un enum avec plusieurs déclarations, seule une déclaration peut omettre un initialiseur pour son premier élément d'enum.", + "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635": "Incluez une liste de fichiers. Cela ne prend pas en charge les modèles Glob, par opposition à « inclure ».", + "Include_modules_imported_with_json_extension_6197": "Inclure les modules importés avec l'extension '.json'", + "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644": "Incluez le code source dans les images sources à l’intérieur du Code JavaScript émis.", + "Include_sourcemap_files_inside_the_emitted_JavaScript_6643": "Incluez les fichiers sourcemap à l’intérieur du Code JavaScript émis.", + "Includes_imports_of_types_referenced_by_0_90054": "Inclut les importations de types référencés par « {0} »", + "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914": "En incluant --watch, -w commence à regarder le projet actuel pour les modifications apportées au fichier. Une fois défini, vous pouvez configurer le mode espion avec :", + "Incomplete_quantifier_Digit_expected_1505": "Quantificateur incomplet. Chiffre attendu.", + "Index_signature_for_type_0_is_missing_in_type_1_2329": "La signature d’index pour le type « {0} » est manquante dans le type « {1} ».", + "Index_signature_in_type_0_only_permits_reading_2542": "La signature d'index du type '{0}' autorise uniquement la lecture.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Les déclarations individuelles de la déclaration fusionnée '{0}' doivent toutes être exportées ou locales.", + "Infer_all_types_from_usage_95023": "Déduire tous les types de l'utilisation", + "Infer_function_return_type_95148": "Déduire le type de retour de la fonction", + "Infer_parameter_types_from_usage_95012": "Déduire les types des paramètres à partir de l'utilisation", + "Infer_this_type_of_0_from_usage_95080": "Déduire le type 'this' de '{0}' à partir de l'utilisation", + "Infer_type_of_0_from_usage_95011": "Déduire le type de '{0}' à partir de l'utilisation", + "Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations_9022": "L’inférence des expressions de classe n’est pas prise en charge avec --isolatedDeclarations.", + "Initialize_property_0_in_the_constructor_90020": "Initialiser la propriété '{0}' dans le constructeur", + "Initialize_static_property_0_90021": "Initialiser la propriété statique '{0}'", + "Initializer_for_property_0_2811": "Initialiseur de la propriété '{0}'", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'initialiseur de la variable membre d'instance '{0}' ne peut pas référencer l'identificateur '{1}' déclaré dans le constructeur.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Les initialiseurs ne sont pas autorisés dans les contextes ambiants.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Initialise un projet TypeScript et crée un fichier tsconfig.json.", + "Inline_variable_95184": "Variable inline", + "Insert_command_line_options_and_files_from_a_file_6030": "Insérer les options de ligne de commande et les fichiers à partir d'un fichier texte.", + "Install_0_95014": "Installer '{0}'", + "Install_all_missing_types_packages_95033": "Installer tous les packages de types manquants", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "L'interface '{0}' ne peut pas étendre simultanément les types '{1}' et '{2}'.", + "Interface_0_incorrectly_extends_interface_1_2430": "L'interface '{0}' étend de manière incorrecte l'interface '{1}'.", + "Interface_declaration_cannot_have_implements_clause_1176": "Une déclaration d'interface ne peut pas avoir de clause 'implements'.", + "Interface_must_be_given_a_name_1438": "Un nom doit être attribué à l’interface.", + "Interface_name_cannot_be_0_2427": "Le nom de l'interface ne peut pas être '{0}'.", + "Interop_Constraints_6252": "Contraintes d’interopérabilité", + "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243": "Interpréter les types de propriétés facultatifs comme écrits, plutôt que d’ajouter « undefined ».", + "Invalid_character_1127": "Caractère non valide.", + "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "Le spécificateur d’importation non valide « {0} » n’a aucune résolution possible.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nom de module non valide dans l'augmentation. Le module '{0}' est résolu en module non typé à l'emplacement '{1}', ce qui empêche toute augmentation.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nom de module non valide dans l'augmentation. Le module '{0}' est introuvable.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Chaîne facultative non valide à partir de la nouvelle expression. Voulez-vous appeler '{0}()' ?", + "Invalid_reference_directive_syntax_1084": "Syntaxe de directive 'reference' non valide.", + "Invalid_syntax_in_decorator_1498": "Syntaxe non valide dans l’élément décoratif.", + "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Utilisation non valide de « {0} ». Il ne peut pas être utilisé à l’intérieur d’un bloc statique de classe.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Utilisation non valide de '{0}'. Les modules sont automatiquement en mode strict.", + "Invalid_use_of_0_in_strict_mode_1100": "Utilisation non valide de '{0}' en mode strict.", + "Invalid_value_for_ignoreDeprecations_5103": "Valeur non valide pour '--ignoreDeprecations'.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valeur non valide pour 'jsxFactory'. '{0}' n'est pas un identificateur valide ou un nom qualifié.", + "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035": "Valeur non valide pour 'jsxFragmentFactory'. '{0}' n'est pas un identificateur valide ou un nom qualifié.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valeur non valide pour '--reactNamespace'. '{0}' n'est pas un identificateur valide.", + "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796": "Il manque probablement une virgule pour séparer ces deux expressions de modèle. Elles forment une expression de modèle étiquetée qui ne peut pas être appelée.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Son type d'élément '{0}' n'est pas un élément JSX valide.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Son type d'instance '{0}' n'est pas un élément JSX valide.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Son type de retour '{0}' n'est pas un élément JSX valide.", + "Its_type_0_is_not_a_valid_JSX_element_type_18053": "Son type '{0}' n’est pas un type d’élément JSX valide.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La balise JSDoc '@{0} {1}' ne correspond pas à la clause 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "La balise JSDoc '@{0}' n'est pas attachée à une classe.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' peut apparaître uniquement dans le dernier paramètre d'une signature.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "La balise JSDoc '@param' se nomme '{0}', mais il n'existe aucun paramètre portant ce nom.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "La balise JSDoc '@param' se nomme '{0}', mais il n'existe aucun paramètre portant ce nom. Elle doit correspondre à 'arguments', si elle est de type tableau.", + "JSDoc_typedef_may_be_converted_to_TypeScript_type_80009": "Le typedef JSDoc peut être converti en type TypeScript.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La balise JSDoc '@typedef' doit avoir une annotation de type ou être suivie des balises '@property' ou '@member'.", + "JSDoc_typedefs_may_be_converted_to_TypeScript_types_80010": "Les typedefs JSDoc peuvent être convertis en types TypeScript.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Les types JSDoc peuvent uniquement être utilisés dans les commentaires de la documentation.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Les types JSDoc peuvent être déplacés vers les types TypeScript.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Les attributs JSX doivent uniquement être attribués à une 'expression' non vide.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "L'élément JSX '{0}' n'a pas de balise de fermeture correspondante.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La classe de l'élément JSX ne prend pas en charge les attributs, car elle n'a pas de propriété '{0}'.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "L'élément JSX a implicitement le type 'any', car il n'existe aucune interface 'JSX.{0}'.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "L'élément JSX a implicitement le type 'any', car le type global 'JSX.Element' n'existe pas.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Le type '{0}' de l'élément JSX n'a pas de signatures de construction ou d'appel.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Les éléments JSX ne peuvent pas avoir plusieurs attributs du même nom.", + "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007": "Les expressions JSX ne peuvent pas utiliser l'opérateur virgule. Est-ce que vous avez voulu écrire un tableau ?", + "JSX_expressions_must_have_one_parent_element_2657": "Les expressions JSX doivent avoir un élément parent.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Le fragment JSX n'a pas de balise de fermeture correspondante.", + "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633": "Les expressions d'accès aux propriétés JSX ne peuvent pas inclure de noms d'espaces de noms JSX", + "JSX_spread_child_must_be_an_array_type_2609": "L'enfant spread JSX doit être un type de tableau.", + "JavaScript_Support_6247": "Prise en charge de JavaScript", + "Jump_target_cannot_cross_function_boundary_1107": "La cible du saut ne peut pas traverser une limite de fonction.", + "KIND_6034": "GENRE", + "Keywords_cannot_contain_escape_characters_1260": "Les mots clés ne peuvent pas contenir de caractères d'échappement.", + "LOCATION_6037": "EMPLACEMENT", + "Language_and_Environment_6254": "Langage et Environnement", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Le côté gauche de l'opérateur virgule n'est pas utilisé, et n'a aucun effet secondaire.", + "Library_0_specified_in_compilerOptions_1422": "Bibliothèque '{0}' spécifiée dans compilerOptions", + "Library_referenced_via_0_from_file_1_1405": "Bibliothèque référencée via '{0}' à partir du fichier '{1}'", + "Line_break_not_permitted_here_1142": "Saut de ligne non autorisé ici.", + "Line_terminator_not_permitted_before_arrow_1200": "Marque de fin de ligne non autorisée devant une flèche.", + "List_of_file_name_suffixes_to_search_when_resolving_a_module_6931": "Liste des suffixes de nom de fichier à rechercher lors de la résolution d’un module.", + "List_of_folders_to_include_type_definitions_from_6161": "Liste des dossiers à partir desquels inclure les définitions de type.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Liste des dossiers racines dont le contenu combiné représente la structure du projet au moment de l'exécution.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Chargement de '{0}' à partir du répertoire racine '{1}', emplacement candidat '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_types_Colon_1_6098": "Chargement du module «{0}» à partir du dossier « node_modules », types de fichiers cibles : {1}.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1_6095": "Chargement du module en tant que fichier/dossier, emplacement du module candidat '{0}', types de fichiers cibles : {1}.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Les paramètres régionaux doivent être sous la forme ou -. Par exemple, '{0}' ou '{1}'.", + "Log_paths_used_during_the_moduleResolution_process_6706": "Chemins d’accès de journal utilisés pendant le processus « moduleResolution ».", + "Longest_matching_prefix_for_0_is_1_6108": "Le préfixe correspondant le plus long pour '{0}' est '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Recherche dans le dossier 'node_modules', emplacement initial '{0}'.", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Faire de tous les appels 'super()' la première instruction dans leur constructeur", + "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Faites en sorte que keyof retourne uniquement des chaînes au lieu de chaînes, de nombres ou de symboles. Option héritée.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Faire de l'appel à 'super()' la première instruction du constructeur", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Le type d'objet mappé a implicitement un type de modèle 'any'.", + "Mark_array_literal_as_const_90070": "Marquer le littéral du tableau comme const", + "Matched_0_condition_1_6403": "Condition '{0}' correspondant à '{1}'.", + "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Mise en correspondance par défaut du modèle include '**/*'", + "Matched_by_include_pattern_0_in_1_1407": "Correspond au modèle include '{0}' dans '{1}'", + "Member_0_implicitly_has_an_1_type_7008": "Le membre '{0}' possède implicitement un type '{1}'.", + "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Le membre '{0}' a implicitement un type '{1}', mais il est possible de déduire un meilleur type à partir de l'utilisation.", + "Merge_conflict_marker_encountered_1185": "Marqueur de conflit de fusion rencontré.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La déclaration fusionnée '{0}' ne peut pas inclure de déclaration d'exportation par défaut. Ajoutez plutôt une déclaration 'export default {0}' distincte.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "La méta-propriété '{0}' n'est autorisée que dans le corps d'une déclaration de fonction, d'une expression de fonction ou d'un constructeur.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "La méthode '{0}' ne peut pas avoir d'implémentation, car elle est marquée comme étant abstraite.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "La méthode '{0}' de l'interface exportée comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "La méthode '{0}' de l'interface exportée comporte ou utilise le nom privé '{1}'.", + "Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9008": "La méthode doit avoir une annotation de type de retour explicite avec --isolatedDeclarations.", + "Method_not_implemented_95158": "Méthode non implémentée.", + "Modifiers_cannot_appear_here_1184": "Les modificateurs ne peuvent pas apparaître ici.", + "Module_0_can_only_be_default_imported_using_the_1_flag_1259": "Le module '{0}' peut uniquement être importé par défaut à l'aide de l'indicateur '{1}'", + "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471": "Le module '{0}' ne peut pas être importé à l'aide de cette construction. Le spécificateur se résout uniquement en un module ES, qui ne peut pas être importé avec 'require'. Utilisez plutôt une importation ECMAScript.", + "Module_0_declares_1_locally_but_it_is_exported_as_2_2460": "Le module '{0}' déclare '{1}' localement, mais il est exporté en tant que '{2}'.", + "Module_0_declares_1_locally_but_it_is_not_exported_2459": "Le module '{0}' déclare '{1}' localement, mais il n'est pas exporté.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340": "Le module '{0}' ne fait pas référence à un type, mais il est utilisé ici en tant que type. Est-ce que vous avez voulu utiliser 'typeof import('{0}')' ?", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Le module '{0}' ne fait pas référence à une valeur, mais est utilisé en tant que valeur ici.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Le module {0} a déjà exporté un membre nommé '{1}'. Effectuez une réexportation explicite pour lever l'ambiguïté.", + "Module_0_has_no_default_export_1192": "Le module '{0}' n'a pas d'exportation par défaut.", + "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613": "Le module '{0}' n'a aucune exportation par défaut. Est-ce que vous avez voulu utiliser 'import { {1} } from {0}' à la place ?", + "Module_0_has_no_exported_member_1_2305": "Le module '{0}' n'a aucun membre exporté '{1}'.", + "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614": "Le module '{0}' n'a aucun membre exporté '{1}'. Est-ce que vous avez voulu utiliser 'import {1} from {0}' à la place ?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Le module '{0}' est masqué par une déclaration locale portant le même nom.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Le module '{0}' utilise 'export =' et ne peut pas être utilisé avec 'export *'.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Le module '{0}' a été résolu en tant que module ambiant déclaré localement dans le fichier '{1}'.", + "Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set_6263": "Le module «{0}» a été résolu en «{1}», mais « --allowArbitraryExtensions » n’est pas défini.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Le module '{0}' a été résolu en '{1}' mais '--jsx' n'est pas défini.", + "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042": "Le module '{0}' a été résolu en '{1}' mais '--resolveJsonModule' n'est pas utilisé.", + "Module_declaration_names_may_only_use_or_quoted_strings_1443": "Les noms de déclaration de module ne peuvent utiliser que des chaînes entre guillemets.", + "Module_name_0_matched_pattern_1_6092": "Nom de module '{0}', modèle correspondant '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== Le nom de module '{0}' n'a pas été résolu. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Le nom de module '{0}' a été correctement résolu en '{1}'. ========", + "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218": "======== Le nom de module '{0}' a été correctement résolu en '{1}' avec l'ID de package '{2}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Le genre de résolution de module n'est pas spécifié. Utilisation de '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "Échec de la résolution de module à l'aide de 'rootDirs'.", + "Modules_6244": "Modules", + "Move_labeled_tuple_element_modifiers_to_labels_95117": "Déplacer les modificateurs d'élément de tuple étiqueté vers les étiquettes", + "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036": "Déplacez l’expression dans l’exportation par défaut vers une variable et ajoutez-y une annotation de type.", + "Move_to_a_new_file_95049": "Déplacer vers un nouveau fichier", + "Move_to_file_95178": "Déplacer vers le fichier", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Les séparateurs numériques consécutifs multiples ne sont pas autorisés.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Les implémentations de plusieurs constructeurs ne sont pas autorisées.", + "NEWLINE_6061": "NOUVELLE LIGNE", + "Name_is_not_valid_95136": "Le nom n'est pas valide", + "Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later_1503": "Les groupes de capture nommés sont disponibles uniquement lorsque vous ciblez « ES2018 » ou une version ultérieure.", + "Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other_1515": "Les groupes de capture nommés portant le même nom doivent s’excluent mutuellement les uns des autres.", + "Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0_1544": "Les importations nommées d'un fichier JSON dans un module ECMAScript ne sont pas autorisées lorsque « module » est défini sur '{0}'.", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "La propriété nommée '{0}' des types '{1}' et '{2}' n'est pas identique.", + "Namespace_0_has_no_exported_member_1_2694": "L'espace de noms '{0}' n'a aucun membre exporté '{1}'.", + "Namespace_must_be_given_a_name_1437": "Un nom doit être attribué à l’espace de noms.", + "Namespace_name_cannot_be_0_2819": "L’espace de noms ne peut pas être «{0}».", + "Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to__1280": "Les espaces de noms ne sont pas autorisés dans les fichiers de script globaux lorsque «{0}» est activé. Si ce fichier n’est pas destiné à être un script global, définissez 'moduleDetection' sur 'force' ou ajoutez une instruction 'export {}' vide.", + "Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters_1433": "Ni les décorateurs ni les modificateurs ne peuvent être appliqués aux paramètres « this ».", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Aucun constructeur de base n'a le nombre spécifié d'arguments de type.", + "No_constituent_of_type_0_is_callable_2755": "Aucun constituant de type '{0}' ne peut être appelé.", + "No_constituent_of_type_0_is_constructable_2759": "Aucun constituant de type '{0}' ne peut être construit.", + "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054": "Aucune signature d'index avec un paramètre de type '{0}' n'a été localisée sur le type '{1}'.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Aucune entrée dans le fichier config '{0}'. Les chemins 'include' spécifiés étaient '{1}' et les chemins 'exclude' étaient '{2}'.", + "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608": "Plus prise en charge. Dans les premières versions, définissez manuellement l’encodage de texte pour la lecture des fichiers.", + "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575": "Aucune surcharge n'attend {0} arguments, mais il existe des surcharges qui attendent {1} ou {2} arguments.", + "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743": "Aucune surcharge n'attend {0} arguments de type, mais il existe des surcharges qui attendent {1} ou {2} arguments de type.", + "No_overload_matches_this_call_2769": "Aucune surcharge ne correspond à cet appel.", + "No_type_could_be_extracted_from_this_type_node_95134": "Aucun type n'a pu être extrait de ce nœud de type", + "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004": "Il n'existe aucune valeur dans l'étendue de la propriété raccourcie '{0}'. Vous devez en déclarez une, ou fournir un initialiseur.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La classe non abstraite « {0} » n'implémente pas le membre abstrait « {1} » hérité de la classe « {2} ».", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_2654": "Les implémentations de la classe non abstraite '{0}' sont manquantes pour les membres suivants de '{1}' : {2}.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more_2655": "Les implémentations de la classe non abstraite '{0}' sont manquantes pour les membres suivants de '{1}' : {2} et {3} plus encore.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'expression de classe non abstraite '{0}' n'implémente pas le membre abstrait hérité '{0}' de la classe '{1}'.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_2656": "Les implémentations de l’expression de classe non abstraite sont manquantes pour les membres suivants de '{0}' : {1}.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and__2650": "Il manque des implémentations d’expression de classe non abstraite pour les membres suivants de '{0}' : {1} et {2} plus.", + "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013": "Les assertions non null peuvent uniquement être utilisées dans les fichiers TypeScript.", + "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090": "Les chemins non relatifs ne sont pas autorisés quand 'baseUrl' n'est pas défini. Avez-vous oublié './' au début ?", + "Non_simple_parameter_declared_here_1348": "Paramètre non simple déclaré ici.", + "Not_all_code_paths_return_a_value_7030": "Les chemins du code ne retournent pas tous une valeur.", + "Not_all_constituents_of_type_0_are_callable_2756": "Tous les constituants de type '{0}' ne peuvent pas être appelés.", + "Not_all_constituents_of_type_0_are_constructable_2760": "Tous les constituants de type '{0}' ne peuvent pas être construits.", + "Numbers_out_of_order_in_quantifier_1506": "Nombres incommandants dans le quantificateur.", + "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008": "Les littéraux numériques ayant des valeurs absolues égales ou supérieures à 2^53 sont trop grands pour être représentés avec précision sous forme d'entiers.", + "Numeric_separators_are_not_allowed_here_6188": "Les séparateurs numériques ne sont pas autorisés ici.", + "Object_is_of_type_unknown_2571": "L'objet est de type 'unknown'.", + "Object_is_possibly_null_2531": "L'objet a peut-être la valeur 'null'.", + "Object_is_possibly_null_or_undefined_2533": "L'objet a peut-être la valeur 'null' ou 'undefined'.", + "Object_is_possibly_undefined_2532": "L'objet a peut-être la valeur 'undefined'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Un littéral d'objet peut uniquement spécifier des propriétés connues, et '{0}' n'existe pas dans le type '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Un littéral d'objet peut uniquement spécifier des propriétés connues, mais '{0}' n'existe pas dans le type '{1}'. Est-ce que vous avez voulu écrire '{2}' ?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La propriété '{0}' du littéral d'objet possède implicitement un type '{1}'.", + "Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations_9016": "Les objets qui contiennent des propriétés raccourcies ne peuvent pas être déduits avec --isolatedDeclarations.", + "Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations_9015": "Les objets qui contiennent des affectations de propagation ne peuvent pas être déduits avec --isolatedDeclarations.", + "Octal_digit_expected_1178": "Chiffre octal attendu.", + "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536": "Les séquences d’échappement octales et les références arrière ne sont pas autorisées dans une classe de caractères. S’il s’agissait d’une séquence d’échappement, utilisez la syntaxe '{0}' à la place.", + "Octal_escape_sequences_are_not_allowed_Use_the_syntax_0_1487": "Les séquences d’échappement octales ne sont pas autorisées. Utilisez la syntaxe '{0}'.", + "Octal_literals_are_not_allowed_Use_the_syntax_0_1121": "Les littéraux octaux ne sont pas autorisés. Utilisez la syntaxe '{0}'.", + "One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value_4126": "Une valeur de '{0}.{1}' est la chaîne '{2}', et l’autre est supposé être une valeur numérique inconnue.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "Une seule déclaration de variable est autorisée dans une instruction 'for...in'.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "Seule une déclaration de variable unique est autorisée dans une instruction 'for...of'.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Seule une fonction void peut être appelée avec le mot clé 'new'.", + "Only_ambient_modules_can_use_quoted_names_1035": "Seuls les modules ambiants peuvent utiliser des noms entre guillemets.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Seuls les modules 'amd' et 'system' sont pris en charge avec --{0}.", + "Only_const_arrays_can_be_inferred_with_isolatedDeclarations_9017": "Seuls les tableaux const peuvent être déduits avec --isolatedDeclarations.", + "Only_emit_d_ts_declaration_files_6014": "Émettez uniquement les fichiers de déclaration '.d.ts'.", + "Only_output_d_ts_files_and_not_JavaScript_files_6623": "Sortie uniquement des fichiers d.ts et non des fichiers JavaScript.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Seules les méthodes publiques et protégées de la classe de base sont accessibles par le biais du mot clé 'super'.", + "Operator_0_cannot_be_applied_to_type_1_2736": "Impossible d'appliquer l'opérateur '{0}' au type '{1}'.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Impossible d'appliquer l'opérateur '{0}' aux types '{1}' et '{2}'.", + "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519": "Les opérateurs ne doivent pas être mixtes dans une classe de caractères. Encapsulez-le dans une classe imbriqué à la place.", + "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619": "Choisir un projet en dehors de la vérification des références multiprojets lors de l’édition.", + "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108": "L’option '{0}={1}' a été supprimée. Supprimez-le de votre configuration.", + "Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDepr_5107": "L’option '{0}={1}' est déconseillée et cessera de fonctionner dans TypeScript {2}. Spécifiez compilerOption « ignoreDeprecations » : «{3}« » pour désactiver cette erreur.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "Vous pouvez spécifier l'option '{0}' uniquement dans le fichier 'tsconfig.json', ou lui affecter la valeur 'false' ou 'null' sur la ligne de commande.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "Vous pouvez spécifier l'option '{0}' uniquement dans le fichier 'tsconfig.json', ou lui affecter la valeur 'null' sur la ligne de commande.", + "Option_0_can_only_be_specified_on_command_line_6266": "L’option '{0}' ne peut être spécifiée que sur la ligne de commande.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "L'option '{0}' peut être utilisée uniquement quand l'option '--inlineSourceMap' ou l'option '--sourceMap' est spécifiée.", + "Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler_5098": "L’option '{0}' ne peut être utilisée que lorsque 'moduleResolution' a la valeur 'node16', 'nodenext' ou 'bundler'.", + "Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later_5095": "L’option '{0}' ne peut être utilisée que lorsque 'module' a la valeur 'preserve' ou 'es2015' ou version ultérieure.", + "Option_0_cannot_be_specified_when_option_jsx_is_1_5089": "Impossible de spécifier l'option '{0}' quand l'option 'jsx' a la valeur '{1}'.", + "Option_0_cannot_be_specified_with_option_1_5053": "Impossible de spécifier l'option '{0}' avec l'option '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Impossible de spécifier l'option '{0}' sans spécifier l'option '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Impossible de spécifier l'option '{0}' sans spécifier l'option '{1}' ou l'option '{2}'.", + "Option_0_has_been_removed_Please_remove_it_from_your_configuration_5102": "L’option «{0}» a été supprimée. Supprimez-le de votre configuration.", + "Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprec_5101": "L’option '{0}' est déconseillée et cessera de fonctionner dans TypeScript {1}. Spécifiez compilerOption « ignoreDeprecations » : «{2}« » pour désactiver cette erreur.", + "Option_0_is_redundant_and_cannot_be_specified_with_option_1_5104": "L’option '{0}' est redondante et ne peut pas être spécifiée avec l’option '{1}'.", + "Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set_5096": "L’option 'allowImportingTsExtensions' ne peut être utilisée que lorsque 'noEmit' ou 'emitDeclarationOnly' est défini.", + "Option_build_must_be_the_first_command_line_argument_6369": "L'option '--build' doit être le premier argument de ligne de commande.", + "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074": "L'option '--incremental' peut uniquement être spécifiée à l'aide de tsconfig, en cas d'émission vers un seul fichier ou quand l'option '--tsBuildInfoFile' est spécifiée.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'option 'isolatedModules' peut être utilisée seulement quand l'option '--module' est spécifiée, ou quand l'option 'target' a la valeur 'ES2015' ou une version supérieure.", + "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109": "L’option 'moduleResolution' doit avoir la valeur '{0}' (ou laisser non spécifiée) lorsque l’option 'module' a la valeur '{1}'.", + "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110": "L’option 'module' doit être définie sur '{0}' quand l’option 'moduleResolution' a la valeur '{1}'.", + "Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled_5091": "L’option 'preserveConstEnums' ne peut pas être désactivée quand '{0}' est activé.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Impossible d'associer l'option 'project' à des fichiers sources sur une ligne de commande.", + "Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic_5070": "Impossible de spécifier l’option '--resolveJsonModule' quand 'moduleResolution' a la valeur 'classic'.", + "Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd_5071": "Impossible de spécifier l’option '--resolveJsonModule' quand 'module' a la valeur 'none', 'system' ou 'umd'.", + "Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System_5105": "L’option 'verbatimModuleSyntax' ne peut pas être utilisée quand 'module' a la valeur 'UMD', 'AMD' ou 'System'.", + "Options_0_and_1_cannot_be_combined_6370": "Impossible de combiner les options '{0}' et '{1}'.", + "Options_Colon_6027": "Options :", + "Output_Formatting_6256": "Mise en forme de sortie", + "Output_compiler_performance_information_after_building_6615": "Informations de performances du compilateur de sortie après la génération.", + "Output_directory_for_generated_declaration_files_6166": "Répertoire de sortie pour les fichiers de déclaration générés.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Le fichier de sortie '{0}' n'a pas été créé à partir du fichier source '{1}'.", + "Output_from_referenced_project_0_included_because_1_specified_1411": "Sortie du projet référencé '{0}' incluse, car '{1}' est spécifié", + "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412": "Sortie du projet référencé '{0}' incluse, car '--module' est spécifié en tant que 'none'", + "Output_more_detailed_compiler_performance_information_after_building_6632": "Affichez des informations plus détaillées sur les performances du compilateur après la génération.", + "Overload_0_of_1_2_gave_the_following_error_2772": "La surcharge {0} sur {1}, '{2}', a généré l'erreur suivante.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Les signatures de surcharge doivent toutes être abstraites ou non abstraites.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Les signatures de surcharge doivent toutes être ambiantes ou non ambiantes.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Les signatures de surcharge doivent toutes être exportées ou non exportées.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Les signatures de surcharge doivent toutes être facultatives ou requises.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Les signatures de surcharge doivent toutes être publiques, privées ou protégées.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Le paramètre '{0}' ne peut pas référencer l'identificateur '{1}' déclaré après lui.", + "Parameter_0_cannot_reference_itself_2372": "Le paramètre '{0}' ne peut pas se référencer lui-même.", + "Parameter_0_implicitly_has_an_1_type_7006": "Le paramètre '{0}' possède implicitement un type '{1}'.", + "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Le paramètre '{0}' a implicitement un type '{1}', mais il est possible de déduire un meilleur type à partir de l'utilisation.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Le paramètre '{0}' n'est pas à la même position que le paramètre '{1}'.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108": "Le paramètre '{0}' de l'accesseur comporte ou utilise le nom '{1}' du module externe '{2}' mais ne peut pas être nommé.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107": "Le paramètre '{0}' de l'accesseur comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106": "Le paramètre '{0}' de l'accesseur comporte ou utilise le nom privé '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Le paramètre '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Le paramètre '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Le paramètre '{0}' du constructeur de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Le paramètre '{0}' du constructeur de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Le paramètre '{0}' du constructeur de la classe exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Le paramètre '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Le paramètre '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Le paramètre '{0}' de la fonction exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Le paramètre '{0}' de la fonction exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Le paramètre '{0}' de la fonction exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Le paramètre '{0}' de la signature d'index de l'interface exportée a ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Le paramètre '{0}' de la signature d'index de l'interface exportée a ou utilise le nom privé '{1}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Le paramètre '{0}' de la méthode de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Le paramètre '{0}' de la méthode de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Le paramètre '{0}' de la méthode publique de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Le paramètre '{0}' de la méthode publique de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Le paramètre '{0}' de la méthode publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Le paramètre '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Le paramètre '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Le paramètre '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Un paramètre ne peut pas contenir de point d'interrogation et d'initialiseur.", + "Parameter_declaration_expected_1138": "Déclaration de paramètre attendue.", + "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051": "Le paramètre a un nom mais aucun type. Est-ce que vous avez voulu utiliser '{0} : {1}' ?", + "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012": "Les modificateurs de paramètres peuvent uniquement être utilisées dans les fichiers TypeScript.", + "Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9011": "Le paramètre doit avoir une annotation de type explicite avec --isolatedDeclarations.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analyser en mode strict et émettre \"use strict\" pour chaque fichier source.", + "Part_of_files_list_in_tsconfig_json_1409": "Partie de la liste 'files' dans tsconfig.json", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Le modèle '{0}' ne peut avoir qu'un seul caractère '*' au maximum.", + "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386": "Les minutages de performances pour '--diagnostics' ou '--extendedDiagnostics' ne sont pas disponibles dans cette session. Une implémentation native de l'API de performances web est introuvable.", + "Platform_specific_6912": "Spécifique à la plateforme", + "Prefix_0_with_an_underscore_90025": "Faire précéder '{0}' d'un trait de soulignement", + "Prefix_all_incorrect_property_declarations_with_declare_95095": "Faire commencer toutes les déclarations de propriété incorrectes par 'declare'", + "Prefix_all_unused_declarations_with_where_possible_95025": "Préfixer toutes les déclarations inutilisées avec '_' si possible", + "Prefix_with_declare_95094": "Faire commencer par 'declare'", + "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449": "Conservez les valeurs importées inutilisées dans la sortie JavaScript qui seraient normalement supprimées.", + "Print_all_of_the_files_read_during_the_compilation_6653": "Imprimez tous les fichiers lus pendant la compilation.", + "Print_files_read_during_the_compilation_including_why_it_was_included_6631": "Fichiers d’impression lus pendant la compilation, notamment la raison de l’inclusion.", + "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505": "Affiche les noms des fichiers et la raison pour laquelle ils font partie de la compilation.", + "Print_names_of_files_part_of_the_compilation_6155": "Imprimez les noms des fichiers faisant partie de la compilation.", + "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "Affichez les noms des fichiers qui font partie de la compilation, puis arrêtez le traitement.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimez les noms des fichiers générés faisant partie de la compilation.", + "Print_the_compiler_s_version_6019": "Affichez la version du compilateur.", + "Print_the_final_configuration_instead_of_building_1350": "Affichez la configuration finale au lieu d'effectuer la génération.", + "Print_the_names_of_emitted_files_after_a_compilation_6652": "Imprimez les noms des fichiers émis après une compilation.", + "Print_this_message_6017": "Imprimez ce message.", + "Private_accessor_was_defined_without_a_getter_2806": "L'accesseur privé a été défini sans getter.", + "Private_field_0_must_be_declared_in_an_enclosing_class_1111": "Le champ privé '{0}' doit être déclaré dans une classe englobante.", + "Private_identifiers_are_not_allowed_in_variable_declarations_18029": "Les identificateurs privés ne sont pas autorisés dans les déclarations de variable.", + "Private_identifiers_are_not_allowed_outside_class_bodies_18016": "Les identificateurs privés ne sont pas autorisés en dehors des corps de classe.", + "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451": "Les identificateurs privés ne sont autorisés que dans les corps de classe et ne peuvent être utilisés que dans le cadre d’une déclaration de membre de classe, d’accès à une propriété ou de la partie gauche d’une expression ’in'", + "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028": "Les identificateurs privés sont disponibles uniquement durant le ciblage d'ECMAScript 2015 et version ultérieure.", + "Private_identifiers_cannot_be_used_as_parameters_18009": "Les identificateurs privés ne peuvent pas être utilisés en tant que paramètres.", + "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105": "Le membre privé ou protégé '{0}' n'est pas accessible sur un paramètre de type.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Project '{0}' can't be built because its dependency '{1}' has errors", + "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Project '{0}' can't be built because its dependency '{1}' was not built", + "Project_0_is_being_forcibly_rebuilt_6388": "Le projet « {0} » est en cours de régénération forcée", + "Project_0_is_out_of_date_because_1_6420": "Le projet '{0}' est obsolète car {1}.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_6412": "Le projet «{0}» est obsolète, car le fichier buildinfo «{1}» indique que le fichier «{2}» était un fichier racine de compilation, mais pas plus.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419": "Le projet «{0}» est obsolète, car le fichier buildinfo «{1}» indique que le programme doit signaler des erreurs.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "Le projet « {0} » est obsolète, car le fichier buildinfo « {1} » indique que certaines modifications n’ont pas été émises", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions_6406": "Le projet '{0}' est obsolète, car le fichier buildinfo '{1}' indique qu’il y a un changement dans compilerOptions", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Le projet '{0}' est obsolète car sa dépendance '{1}' est obsolète", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Le projet '{0}' est obsolète car la sortie (« {1} ») est antérieure à l'entrée « {2} »", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Le projet '{0}' est obsolète car le fichier de sortie '{1}' n'existe pas", + "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Le projet '{0}' est obsolète, car sa sortie a été générée avec la version '{1}', qui diffère de la version actuelle '{2}'", + "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401": "Le projet « {0} » est obsolète car une erreur s'est produite lors de la lecture du fichier « {1} »", + "Project_0_is_up_to_date_6361": "Le projet '{0}' est à jour", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Le projet « {0} » est à jour car l'entrée la plus récente (« {1} ») est antérieure à la sortie (« {2} »)", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Project « {0} » est à jour, mais doit mettre à jour les horodatages des fichiers de sortie plus anciens que les fichiers d’entrée", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Le projet '{0}' est à jour avec les fichiers .d.ts de ses dépendances", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Les références de projet ne peuvent pas former un graphe circulaire. Cycle détecté : {0}", + "Projects_6255": "Projets", + "Projects_in_this_build_Colon_0_6355": "Projets dans cette build : {0}", + "Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher_18045": "Les propriétés avec le modificateur 'accessor' ne sont disponibles que pour le ciblage d’ECMAScript 2015 et versions ultérieures.", + "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267": "La propriété « {0} » ne peut pas avoir d’initialiseur, car elle est marquée comme abstraite.", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "La propriété '{0}' est issue d'une signature d'index, elle doit donc faire l'objet d'un accès avec ['{0}'].", + "Property_0_does_not_exist_on_type_1_2339": "La propriété '{0}' n'existe pas sur le type '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propriété '{0}' n'existe pas sur le type '{1}'. Est-ce qu'il ne s'agit pas plutôt de '{2}' ?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "La propriété '{0}' n'existe pas sur le type '{1}'. Ne vouliez-vous pas plutôt accéder au membre statique '{2}' ?", + "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "La propriété '{0}' n'existe pas sur le type '{1}'. Devez-vous changer votre bibliothèque cible ? Essayez de changer l'option de compilateur 'lib' en '{2}' ou une version ultérieure.", + "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812": "La propriété '{0}' n’existe pas sur le type '{1}'. Essayez de modifier l’option de compileur 'lib' pour inclure 'dom'.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817": "La propriété « {0} » n'a aucun initialiseur et n'est pas définitivement assignée dans un bloc statique de classe.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propriété '{0}' n'a aucun initialiseur et n'est pas définitivement assignée dans le constructeur.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propriété '{0}' a implicitement le type 'any', car son accesseur get ne dispose pas d'une annotation de type de retour.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propriété '{0}' a implicitement le type 'any', car son accesseur set ne dispose pas d'une annotation de type de paramètre.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048": "La propriété '{0}' a implicitement le type 'any', mais il est possible de déduire un meilleur type pour son accesseur get à partir de l'utilisation.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049": "La propriété '{0}' a implicitement le type 'any', mais il est possible de déduire un meilleur type pour son accesseur set à partir de l'utilisation.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Impossible d'assigner la propriété '{0}' du type '{1}' à la même propriété du type de base '{2}'.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propriété '{0}' du type '{1}' ne peut pas être assignée au type '{2}'.", + "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "La propriété '{0}' du type '{1}' fait référence à un membre distinct, qui n'est pas accessible à partir du type '{2}'.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "La propriété '{0}' est déclarée mais sa valeur n'est jamais lue.", + "Property_0_is_incompatible_with_index_signature_2530": "La propriété '{0}' est incompatible avec la signature d'index.", + "Property_0_is_missing_in_type_1_2324": "La propriété '{0}' est manquante dans le type '{1}'.", + "Property_0_is_missing_in_type_1_but_required_in_type_2_2741": "La propriété '{0}' est absente du type '{1}' mais obligatoire dans le type '{2}'.", + "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013": "La propriété '{0}' n'est pas accessible en dehors de la classe '{1}', car elle a un identificateur privé.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "La propriété '{0}' est facultative dans le type '{1}', mais obligatoire dans le type '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "La propriété '{0}' est privée et uniquement accessible dans la classe '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "La propriété '{0}' est privée dans le type '{1}', mais pas dans le type '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446": "La propriété '{0}' est protégée et uniquement accessible via une instance de la classe '{1}'. Ceci est une instance de la classe '{2}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "La propriété '{0}' est protégée et uniquement accessible dans la classe '{1}' et ses sous-classes.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "La propriété '{0}' est protégée, mais le type '{1}' n'est pas une classe dérivée de '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "La propriété '{0}' est protégée dans le type '{1}', mais publique dans le type '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "La propriété '{0}' est utilisée avant d'être assignée.", + "Property_0_is_used_before_its_initialization_2729": "La propriété '{0}' est utilisée avant son initialisation.", + "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568": "La propriété «{0}» n'existe pas sur le type «{1}». Est-ce qu'il ne s'agit pas plutôt de «{2}»?", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "Impossible d'assigner la propriété '{0}' de l'attribut spread JSX à la propriété cible.", + "Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected_4094": "La propriété '{0}' du type de classe anonyme exporté ne peut pas être privée ou protégée.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "La propriété '{0}' de l'interface exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "La propriété '{0}' de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411": "La propriété « {0} » de type « {1} » ne peut pas être attribuée au type d’index « {2} », « {3} ».", + "Property_0_was_also_declared_here_2733": "La propriété '{0}' a également été déclarée ici.", + "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612": "La propriété '{0}' va remplacer la propriété de base dans '{1}'. Si cela est intentionnel, ajoutez un initialiseur. Sinon, ajoutez un modificateur 'declare', ou supprimez la déclaration redondante.", + "Property_assignment_expected_1136": "Assignation de propriété attendue.", + "Property_destructuring_pattern_expected_1180": "Modèle de déstructuration de propriété attendu.", + "Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9012": "La propriété doit avoir une annotation de type explicite avec --isolatedDeclarations.", + "Property_or_signature_expected_1131": "Propriété ou signature attendue.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "La valeur de la propriété peut être uniquement un littéral de chaîne, un littéral numérique, 'true', 'false', 'null', un littéral d'objet ou un littéral de tableau.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_6179": "Fournissez une prise en charge complète des itérables dans 'for-of', la propagation et la destruction lors du ciblage de 'ES5'.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "La méthode publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module externe {2} mais ne peut pas être nommée.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "La méthode publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "La méthode publique '{0}' de la classe exportée comporte ou utilise le nom privé '{1}'.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "La propriété publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais elle ne peut pas être nommée.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "La propriété publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "La propriété publique '{0}' de la classe exportée possède ou utilise le type privé '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "La méthode statique publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module externe {2} mais ne peut pas être nommée.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "La méthode statique publique '{0}' de la classe exportée comporte ou utilise le nom '{1}' du module privé '{2}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "La méthode statique publique '{0}' de la classe exportée comporte ou utilise le nom privé '{1}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "La propriété statique publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module externe {2}, mais elle ne peut pas être nommée.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "La propriété statique publique '{0}' de la classe exportée possède ou utilise le nom '{1}' du module privé '{2}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "La propriété statique publique '{0}' de la classe exportée possède ou utilise le type privé '{1}'.", + "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032": "Le nom qualifié '{0}' n'est pas autorisé si '@param {object} {1}' n'est pas placé au début.", + "Raise_an_error_when_a_function_parameter_isn_t_read_6676": "Déclencher une erreur quand un paramètre de fonction n’est pas lu.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Lever une erreur sur les expressions et les déclarations ayant un type 'any' implicite.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Déclenche une erreur sur les expressions 'this' avec un type 'any' implicite.", + "Range_out_of_order_in_character_class_1517": "Plage dans l’ordre dans la classe de caractères.", + "Re_exporting_a_type_when_0_is_enabled_requires_using_export_type_1205": "La réexportation d’un type lorsque «{0}» est activé nécessite l’utilisation de « type d’exportation ».", + "React_components_cannot_include_JSX_namespace_names_2639": "Les composants React ne peuvent pas inclure de noms d’espace de noms JSX", + "Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.", + "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617": "Réduisez le nombre de projets chargés automatiquement par TypeScript.", + "Referenced_project_0_may_not_disable_emit_6310": "Le projet référencé '{0}' ne doit pas désactiver l'émission.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Le projet référencé '{0}' doit avoir le paramètre \"composite\" avec la valeur true.", + "Referenced_via_0_from_file_1_1400": "Référencé(e) via '{0}' à partir du fichier '{1}'", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2834": "Les chemins d’importation relatifs ont besoin d’extensions de fichier explicites dans les importations ECMAScript lorsque '--moduleResolution' est 'node16' ou 'nodenext'. Envisagez d’ajouter une extension au chemin d’importation.", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2835": "Les chemins d’importation relatifs ont besoin d’extensions de fichier explicites dans les importations ECMAScript lorsque '--moduleResolution' est 'node16' ou 'nodenext'. Est-ce que vous avez voulu utiliser '{0}' ?", + "Remove_a_list_of_directories_from_the_watch_process_6628": "Supprimez une liste de répertoires du processus d’observation.", + "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629": "Supprimez une liste de fichiers du traitement du mode espion.", + "Remove_all_unnecessary_override_modifiers_95163": "Supprimer tous les modificateurs 'override' inutiles", + "Remove_all_unnecessary_uses_of_await_95087": "Supprimer toutes les utilisations non nécessaires de 'await'", + "Remove_all_unreachable_code_95051": "Supprimer tout le code inaccessible", + "Remove_all_unused_labels_95054": "Supprimer toutes les étiquettes inutilisées", + "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115": "Supprimer les accolades de tous les corps de fonction arrow présentant des problèmes pertinents", + "Remove_braces_from_arrow_function_95060": "Supprimer les accolades de la fonction arrow", + "Remove_braces_from_arrow_function_body_95112": "Supprimer les accolades du corps de fonction arrow", + "Remove_import_from_0_90005": "Supprimer l'importation de '{0}'", + "Remove_override_modifier_95161": "Supprimer un modificateur 'override'", + "Remove_parentheses_95126": "Supprimer les parenthèses", + "Remove_template_tag_90011": "Supprimer la balise template", + "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618": "Supprimez la limite de 20 Mo sur la taille totale du code source pour les fichiers JavaScript dans le serveur de langage TypeScript.", + "Remove_type_from_import_declaration_from_0_90055": "Supprimer 'type' de la déclaration d’importation de « {0} »", + "Remove_type_from_import_of_0_from_1_90056": "Supprimer 'type' de l’importation de « {0} » de «{1}»", + "Remove_type_parameters_90012": "Supprimer les paramètres de type", + "Remove_unnecessary_await_95086": "Supprimer toute utilisation non nécessaire de 'await'", + "Remove_unreachable_code_95050": "Supprimer le code inaccessible", + "Remove_unused_declaration_for_Colon_0_90004": "Supprimer la déclaration inutilisée pour : '{0}'", + "Remove_unused_declarations_for_Colon_0_90041": "Supprimer les déclarations inutilisées pour '{0}'", + "Remove_unused_destructuring_declaration_90039": "Supprimer la déclaration de déstructuration inutilisée", + "Remove_unused_label_95053": "Supprimer l'étiquette inutilisée", + "Remove_variable_statement_90010": "Supprimer l'instruction de variable", + "Rename_param_tag_name_0_to_1_95173": "Renommez le nom de balise '@param' '{0}' en '{1}'", + "Replace_0_with_Promise_1_90036": "Remplacer '{0}' par 'Promise<{1}>'", + "Replace_all_unused_infer_with_unknown_90031": "Remplacer tous les 'infer' inutilisés par 'unknown'", + "Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.", + "Replace_infer_0_with_unknown_90030": "Remplacer 'infer {0}' par 'unknown'", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins du code de la fonction ne retournent pas tous une valeur.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.", + "Report_errors_in_js_files_8019": "Signalez les erreurs dans les fichiers .js.", + "Report_errors_on_unused_locals_6134": "Signaler les erreurs sur les variables locales inutilisées.", + "Report_errors_on_unused_parameters_6135": "Signaler les erreurs sur les paramètres inutilisés.", + "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719": "Exiger une annotation suffisante sur les exportations afin que d’autres outils puissent générer de manière triviale des fichiers de déclaration.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717": "Les propriétés non déclarées sont imposées à partir des signatures d'index pour permettre l'utilisation des accès aux éléments.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Les paramètres de type obligatoires ne peuvent pas être placés à la suite des paramètres de type optionnels.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La résolution du module '{0}' a été trouvée dans le cache à l'emplacement '{1}'.", + "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "La résolution de la directive de référence de type '{0}' a été trouvée dans le cache à l'emplacement '{1}'.", + "Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_i_6277": "Échec de la résolution du nom non relatif ; tentative avec les fonctionnalités de résolution de nœud modernes désactivées pour voir si la bibliothèque npm a besoin d’une mise à jour de configuration.", + "Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_ne_6279": "Échec de la résolution du nom non relatif ; en essayant avec '--moduleResolution bundler' pour voir si le projet peut avoir besoin d’une mise à jour de configuration.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Résoudre 'keyof' en noms de propriétés de valeur chaîne uniquement (aucun nombre ou symbole).", + "Resolved_under_condition_0_6414": "Résolu sous la condition '{0}'.", + "Resolving_in_0_mode_with_conditions_1_6402": "Résolution en mode {0} avec des conditions {1}.", + "Resolving_module_0_from_1_6086": "======== Résolution du module '{0}' à partir de '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Résolution du nom de module '{0}' par rapport à l'URL de base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Résolution du chemin réel pour '{0}', résultat '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_6242": "======== Résolution de la directive de référence de type '{0}', fichier conteneur '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Résolution de la directive de référence de type '{0}', fichier conteneur '{1}', répertoire racine '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Résolution de la directive de référence de type '{0}', fichier conteneur '{1}', répertoire racine non défini. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Résolution de la directive de référence de type '{0}', fichier conteneur non défini, répertoire racine '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Résolution de la directive de référence de type '{0}', fichier conteneur non défini, répertoire racine non défini. ========", + "Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_no_6265": "Résolution de la directive de référence de type pour le programme qui spécifie des typesRoots personnalisés, en ignorant la recherche dans le dossier « node_modules ».", + "Resolving_with_primary_search_path_0_6121": "Résolution à l'aide du chemin de recherche primaire '{0}'.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Le paramètre rest '{0}' possède implicitement un type 'any[]'.", + "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047": "Le paramètre Rest '{0}' a implicitement un type 'any[]', mais il est possible de déduire un meilleur type à partir de l'utilisation.", + "Rest_types_may_only_be_created_from_object_types_2700": "Vous ne pouvez créer des types Rest qu'à partir de types d'objet.", + "Return_type_annotation_circularly_references_itself_2577": "L'annotation de type de retour se référence de manière circulaire.", + "Return_type_must_be_inferred_from_a_function_95149": "Le type de retour doit être déduit d'une fonction", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Le type de retour de la signature d'appel de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Le type de retour de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Le type de retour de la signature de constructeur de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Le type de retour de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Le type de retour de la signature de constructeur doit pouvoir être assigné au type d'instance de la classe.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Le type de retour de la fonction exportée possède ou utilise le nom '{0}' du module externe {1}, mais il ne peut pas être nommé.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Le type de retour de la fonction exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Le type de retour de la fonction exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Le type de retour de la signature d'index de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Le type de retour de la signature d'index de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Le type de retour de la méthode de l'interface exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Le type de retour de la méthode de l'interface exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Le type de retour de la méthode publique de la classe exportée possède ou utilise le nom '{0}' du module externe {1}, mais il ne peut pas être nommé.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Le type de retour de la méthode publique de la classe exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Le type de retour de la méthode publique de la classe exportée possède ou utilise le nom privé '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module externe {2}, mais il ne peut pas être nommé.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom '{1}' du module privé '{2}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Le type de retour du getter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom '{0}' du module externe {1}, mais il ne peut pas être nommé.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom '{0}' du module privé '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{0}'.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395": "En réutilisant la résolution du module « {0} » à partir de « {1} » trouvée dans le cache de l’emplacement « {2} », l’erreur n’a pas été résolue.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393": "En réutilisant la résolution du module « {0} » à partir de « {1} » trouvée dans le cache de l’emplacement « {2} », l’erreur a été résolue dans « {3} ».", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394": "En réutilisant la résolution du module « {0} » à partir de « {1} » trouvée dans le cache de l’emplacement « {2} », l’erreur a été résolue dans « {3} » avec l’ID de package « {4} ».", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389": "En réutilisant la résolution du module « {0} » à partir de « {1} » de l’ancien programme, l’erreur n’a pas été résolue.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183": "En réutilisant la résolution du module « {0} » à partir de « {1} » de l’ancien programme, l’erreur a été résolue dans « {2} ».", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184": "En réutilisant la résolution du module « {0} » à partir de « {1} » de l’ancien programme, l’erreur a été résolue dans « {2} avec l’ID de package « {3} ».", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398": "En réutilisant la résolution de la directive de référence de type « {0} » à partir de « {1} » trouvée dans le cache de l’emplacement « {2} », l’erreur n’a pas été résolue.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396": "En réutilisant la résolution de la directive de référence de type « {0} » à partir de « {1} » trouvée dans le cache de l’emplacement « {2} », l’erreur a été résolue dans « {3} ».", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397": "En réutilisant la résolution de la directive de référence de type « {0} » à partir de « {1} » trouvée dans le cache de l’emplacement « {2} », l’erreur a été résolue dans « {3} » avec l’ID de package « {4} ».", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392": "En réutilisant la résolution de la directive de référence de type « {0} » à partir de « {1} » de l’ancien programme, l’erreur n’a pas été résolue.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390": "En réutilisant la résolution de la directive de référence de type « {0} » à partir de « {1} » de l’ancien programme, l’erreur a été résolue dans « {2} ».", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391": "En réutilisant la résolution de la directive de référence de type « {0} » à partir de « {1} » de l’ancien programme, l’erreur a été résolue dans « {2} » avec l’ID de package « {3} ».", + "Rewrite_all_as_indexed_access_types_95034": "Réécrire tout comme types d'accès indexés", + "Rewrite_as_the_indexed_access_type_0_90026": "Réécrire en tant que type d'accès indexé '{0}'", + "Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_i_6421": "Réécrivez les extensions de fichier « .ts », « .tsx », « .mts » et « .cts » dans les chemins d'importation relatifs vers leur équivalent JavaScript dans les fichiers de sortie.", + "Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish_2869": "Opérande droit de ?? est inaccessible, car l’opérande de gauche n’est jamais nullish.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Impossible de déterminer le répertoire racine, chemins de recherche primaires ignorés.", + "Root_file_specified_for_compilation_1427": "Fichier racine spécifié pour la compilation", + "STRATEGY_6039": "STRATÉGIE", + "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Enregistrez les fichiers .tsbuildinfo pour permettre la compilation incrémentielle des projets.", + "Saw_non_matching_condition_0_6405": "Condition non correspondante '{0}' visible.", + "Scoped_package_detected_looking_in_0_6182": "Package de portée détecté. Recherche dans '{0}'", + "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418": "Recherche d’extensions de secours dans tous les répertoires node_modules ancêtres : {0}.", + "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417": "Recherche d’extensions préférées dans tous les répertoires node_modules ancêtres : {0}.", + "Selection_is_not_a_valid_statement_or_statements_95155": "La sélection ne correspond pas à une ou des instructions valides", + "Selection_is_not_a_valid_type_node_95133": "La sélection n'est pas un nœud de type valide", + "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705": "Définissez la version du langage JavaScript pour JavaScript émis et incluez des déclarations de bibliothèque compatibles.", + "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654": "Définissez la langue de la messagerie à partir de TypeScript. Cela n’affecte pas l’émission.", + "Set_the_module_option_in_your_configuration_file_to_0_95099": "Affecter à l'option 'module' de votre fichier config la valeur '{0}'", + "Set_the_newline_character_for_emitting_files_6659": "Définissez le caractère de nouvelle ligne pour l’émission de fichiers.", + "Set_the_target_option_in_your_configuration_file_to_0_95098": "Affecter à l'option 'target' de votre fichier config la valeur '{0}'", + "Setters_cannot_return_a_value_2408": "Les méthodes setter ne peuvent pas retourner de valeur.", + "Show_all_compiler_options_6169": "Affichez toutes les options du compilateur.", + "Show_diagnostic_information_6149": "Affichez les informations de diagnostic.", + "Show_verbose_diagnostic_information_6150": "Affichez les informations de diagnostic détaillées.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Montrer ce qui serait généré (ou supprimé si '--clean' est spécifié)", + "Signature_0_must_be_a_type_predicate_1224": "La signature '{0}' doit être un prédicat de type.", + "Signature_declarations_can_only_be_used_in_TypeScript_files_8017": "Les déclarations de signature peuvent uniquement être utilisées dans les fichiers TypeScript.", + "Skip_building_downstream_projects_on_error_in_upstream_project_6640": "Ignorer la génération de projets en aval en cas d’erreur dans le projet en amont.", + "Skip_type_checking_all_d_ts_files_6693": "Ignorer la vérification de type dans tous les fichiers .d.ts.", + "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692": "Ignorer la vérification de type des fichiers .d.ts inclus dans TypeScript.", + "Skip_type_checking_of_declaration_files_6012": "Ignorer le contrôle de type des fichiers de déclaration.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Skipping build of project '{0}' because its dependency '{1}' has errors", + "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382": "Skipping build of project '{0}' because its dependency '{1}' was not built", + "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164": "Le module '{0}' qui ressemble à un URI absolu, types de fichiers cibles : {1}.", + "Source_from_referenced_project_0_included_because_1_specified_1414": "Source du projet référencé '{0}' incluse, car '{1}' est spécifié", + "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415": "Source du projet référencé '{0}' incluse, car '--module' est spécifié en tant que 'none'", + "Source_has_0_element_s_but_target_allows_only_1_2619": "La source a {0} élément(s) mais la cible n'en autorise que {1}.", + "Source_has_0_element_s_but_target_requires_1_2618": "La source a {0} élément(s) mais la cible en nécessite {1}.", + "Source_provides_no_match_for_required_element_at_position_0_in_target_2623": "La source ne fournit aucune correspondance pour l'élément obligatoire situé à la position {0} dans la cible.", + "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624": "La source ne fournit aucune correspondance pour l'élément variadique situé à la position {0} dans la cible.", + "Specify_ECMAScript_target_version_6015": "Spécifiez la version cible ECMAScript.", + "Specify_JSX_code_generation_6080": "Spécifiez la génération de code JSX.", + "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679": "Spécifiez un fichier qui regroupe toutes les sorties dans un fichier JavaScript. Si « declaration » a la valeur true, désigne également un fichier qui regroupe toutes les sorties .d.ts.", + "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641": "Spécifiez une liste de modèles glob qui correspondent aux fichiers à inclure dans la compilation.", + "Specify_a_list_of_language_service_plugins_to_include_6681": "Spécifiez une liste de plug-ins de service de langage à ajouter.", + "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651": "Spécifiez un ensemble de fichiers de déclaration de bibliothèque groupée qui décrivent l’environnement d’exécution cible.", + "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680": "Spécifiez un ensemble d’entrées qui re-mappent les importations à d’autres emplacements de recherche.", + "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687": "Spécifiez un tableau d’objets qui spécifient les chemins d’accès pour les projets. Utilisé dans les références de projet.", + "Specify_an_output_folder_for_all_emitted_files_6678": "Spécifiez un dossier de sortie pour tous les fichiers émis.", + "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718": "Spécifier le comportement d'émission/de vérification des importations utilisées uniquement pour les types.", + "Specify_file_to_store_incremental_compilation_information_6380": "Spécifier le fichier de stockage des informations de compilation incrémentielle", + "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658": "Spécifiez comment TypeScript recherche un fichier à partir d’un spécificateur de module donné.", + "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714": "Spécifiez la façon dont les répertoires sont surveillés sur les systèmes qui ne disposent pas de fonctionnalités récursives de surveillance des fichiers.", + "Specify_how_the_TypeScript_watch_mode_works_6715": "Spécifiez le fonctionnement du mode espion TypeScript.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Spécifiez les fichiers bibliothèques à inclure dans la compilation.", + "Specify_module_code_generation_6016": "Spécifier la génération de code de module.", + "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649": "Spécifiez le spécificateur de module utilisé pour importer les fonctions de fabrique JSX lors de l’utilisation de « jsx: react-jsx* ».", + "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710": "Spécifiez plusieurs dossiers qui agissent comme « ./node_modules/@types ».", + "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633": "Spécifiez une ou plusieurs références de module de chemin d’accès ou de nœud aux fichiers de configuration de base dont les paramètres sont hérités.", + "Specify_options_for_automatic_acquisition_of_declaration_files_6709": "Spécifiez les options d’acquisition automatique des fichiers de déclaration.", + "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227": "Spécifiez la stratégie en cas d'échec de la création d'une surveillance de l'interrogation à l'aide des événements liés au système de fichiers : 'FixedInterval' (par défaut), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'.", + "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226": "Spécifiez la stratégie de surveillance des répertoires sur les plateformes qui ne prennent pas en charge la surveillance récursive en mode natif : 'UseFsEvents' (par défaut), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'.", + "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225": "Spécifiez la stratégie de surveillance des fichiers : 'FixedPollingInterval' (par défaut), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'.", + "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648": "Spécifiez la référence de fragment JSX utilisée pour les fragments lors du ciblage de l’émission de réaction JSX par exemple « React.Fragment » ou « Fragment ».", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Spécifiez la fonction de fabrique JSX à utiliser pour le ciblage d'une émission JSX 'react', par exemple 'React.createElement' ou 'h'.", + "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647": "Spécifiez la fonction de fabrique JSX à utiliser pour le ciblage d'une émission JSX « react », par exemple « React.createElement » ou « h ».", + "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034": "Spécifiez la fonction de fabrique de fragments JSX à utiliser durant le ciblage de l'émission JSX 'react' avec l'option de compilateur 'jsxFactory', par exemple 'Fragment'.", + "Specify_the_base_directory_to_resolve_non_relative_module_names_6607": "Spécifiez le répertoire de base pour résoudre les noms de modules non relatifs.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Spécifiez la séquence de fin de ligne à utiliser durant l'émission des fichiers : 'CRLF' (Dos) ou 'LF' (Unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Spécifiez l'emplacement dans lequel le débogueur doit localiser les fichiers TypeScript au lieu des emplacements sources.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655": "Spécifiez l'emplacement dans lequel le débogueur doit localiser les fichiers de mappage au lieu des emplacements générés.", + "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656": "Spécifiez la profondeur maximale de dossier utilisée pour la vérification des fichiers JavaScript à partir de « node_modules ». Applicable uniquement à l’aide de « allowJs ».", + "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238": "Spécifiez le spécificateur de module à utiliser pour importer les fonctions de fabrique 'jsx' et 'jsxs' à partir de react, par exemple", + "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686": "Spécifiez l’objet appelé pour « createElement ». Ceci s’applique uniquement quand le ciblage de l’émission de JSX « react » est actif.", + "Specify_the_output_directory_for_generated_declaration_files_6613": "Spécifiez le répertoire de sortie pour les fichiers de déclaration générés.", + "Specify_the_path_to_tsbuildinfo_incremental_compilation_file_6707": "Spécifiez le chemin d’accès au fichier de compilation incrémentielle .incrémentielle .", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Spécifiez le répertoire racine des fichiers d'entrée. Contrôlez la structure des répertoires de sortie avec --outDir.", + "Specify_the_root_folder_within_your_source_files_6690": "Spécifiez le dossier racine dans vos fichiers sources.", + "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695": "Spécifiez le chemin d’accès racine des débogueurs pour trouver le code source de référence.", + "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711": "Spécifiez les noms de packages de types à inclure sans être référencés dans un fichier source.", + "Specify_what_JSX_code_is_generated_6646": "Spécifiez le code JSX généré.", + "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634": "Spécifiez l’approche que l’observateur doit utiliser si le système manque d’observateurs de fichiers natifs.", + "Specify_what_module_code_is_generated_6657": "Spécifiez le code de module généré.", + "Split_all_invalid_type_only_imports_1367": "Diviser toutes les importations de type uniquement non valides", + "Split_into_two_separate_import_declarations_1366": "Diviser en deux déclarations import distinctes", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "L'opérateur spread dans les expressions 'new' est disponible uniquement quand ECMAScript 5 ou version supérieure est ciblé.", + "Spread_types_may_only_be_created_from_object_types_2698": "Vous ne pouvez créer des types Spread qu'à partir de types d'objet.", + "Starting_compilation_in_watch_mode_6031": "Démarrage de la compilation en mode espion...", + "Statement_expected_1129": "Instruction attendue.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Les instructions ne sont pas autorisées dans les contextes ambiants.", + "Static_members_cannot_reference_class_type_parameters_2302": "Les membres statiques ne peuvent pas référencer des paramètres de type de classe.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "La propriété statique '{0}' est en conflit avec la propriété intégrée 'Function.{0}' de la fonction constructeur '{1}'.", + "String_literal_expected_1141": "Littéral de chaîne attendu.", + "String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es_18057": "Les noms d’importation et d’exportation de littéral de chaîne ne sont pas pris en charge lorsque l’indicateur « --module » a la valeur « es2015 » ou « es2020 ».", + "String_literal_with_double_quotes_expected_1327": "Littéral de chaîne avec guillemets doubles attendu.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stylisez les erreurs et les messages avec de la couleur et du contexte (expérimental).", + "Subpattern_flags_must_be_present_when_there_is_a_minus_sign_1504": "Les indicateurs de sous-modèle doivent être présents lorsqu’il existe un signe moins.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Les prochaines déclarations de propriétés doivent avoir le même type. La propriété '{0}' doit avoir le type '{1}', mais elle a ici le type '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Les déclarations de variable ultérieures doivent avoir le même type. La variable '{0}' doit être de type '{1}', mais elle a ici le type '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Le type de la substitution '{0}' du modèle '{1}' est incorrect. Attente de 'string'. Obtention de '{2}'.", + "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062": "La substitution '{0}' dans le modèle '{1}' ne peut avoir qu'un seul caractère '*' au maximum.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Les substitutions du modèle '{0}' doivent correspondre à un tableau.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Les substitutions du modèle '{0}' ne doivent pas correspondre à un tableau vide.", + "Successfully_created_a_tsconfig_json_file_6071": "Un fichier tsconfig.json a été créé.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Les appels de 'super' ne sont pas autorisés hors des constructeurs ou dans des fonctions imbriquées dans des constructeurs.", + "Suppress_excess_property_checks_for_object_literals_6072": "Supprimez les vérifications des propriétés en trop pour les littéraux d'objet.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Supprimer les erreurs noImplicitAny pour les objets d'indexation auxquels il manque des signatures d'index.", + "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703": "Supprimez les erreurs « noImplicitAny » lors de l’indexation d’objets qui n’ont pas de signatures d’index.", + "Switch_each_misused_0_to_1_95138": "Remplacer chaque utilisation incorrecte de '{0}' par '{1}'", + "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704": "Appelez les rappels de façon synchrone, et mettez à jour l'état des observateurs de répertoire sur les plateformes qui ne prennent pas en charge la surveillance récursive en mode natif.", + "Syntax_Colon_0_6023": "Syntaxe : {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "La balise '{0}' attend au moins '{1}' arguments, mais la fabrique JSX '{2}' en fournit au maximum '{3}'.", + "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "Les expressions de modèle étiquetées ne sont pas autorisées dans une chaîne facultative.", + "Target_allows_only_0_element_s_but_source_may_have_more_2621": "La cible autorise uniquement {0} élément(s) mais la source peut en avoir plus.", + "Target_requires_0_element_s_but_source_may_have_fewer_2620": "La cible nécessite {0} élément(s) mais la source peut en avoir moins.", + "Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1_2849": "La signature cible offre trop peu d’arguments. {0} ou plus sont attendus, mais {1} ont été reçus.", + "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "Le modificateur '{0}' peut uniquement être utilisé dans les fichiers TypeScript.", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Impossible d'appliquer l'opérateur '{0}' au type 'symbol'.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "L'opérateur '{0}' n'est pas autorisé pour les types booléens. Utilisez '{1}' à la place.", + "The_0_property_of_an_async_iterator_must_be_a_method_2768": "La propriété '{0}' d'un itérateur asynchrone doit être une méthode.", + "The_0_property_of_an_iterator_must_be_a_method_2767": "La propriété '{0}' d'un itérateur doit être une méthode.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Le type 'Object' peut être assigné à très peu d'autres types. Souhaitez-vous utiliser le type 'any' à la place ?", + "The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously_1502": "L’indicateur Unicode (u) et l’indicateur Unicode Sets (v) ne peuvent pas être définis simultanément.", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_func_2496": "Désolé... Nous ne pouvons pas référencer l’objet « arguments » dans une fonction arrow d’ES5. Utilisez plutôt une expression de fonction standard.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_sta_2522": "L’objet « arguments » ne peut pas être référencé dans une fonction ou méthode asynchrone dans ES5. Utilisez une fonction ou méthode standard.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Le corps d'une instruction 'if' ne peut pas être l'instruction vide.", + "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793": "L'appel aurait pu réussir sur cette implémentation, mais les signatures de surcharges de l'implémentation ne sont pas visibles en externe.", + "The_character_set_of_the_input_files_6163": "Jeu de caractères des fichiers d'entrée.", + "The_containing_arrow_function_captures_the_global_value_of_this_7041": "La fonction arrow conteneur capture la valeur globale de 'this'.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Le corps de la fonction ou du module conteneur est trop grand pour l'analyse du flux de contrôle.", + "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309": "Le fichier actuel est un module CommonJS et ne peut pas utiliser 'await' au niveau supérieur.", + "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479": "Le fichier actuel est un module CommonJS dont les importations produiront des appels 'require' ; cependant, le fichier référencé est un module ECMAScript et ne peut pas être importé avec 'require'. Envisagez d'écrire un appel dynamique 'import(\"{0}\")' à la place.", + "The_current_host_does_not_support_the_0_option_5001": "L'hôte actuel ne prend pas en charge l'option '{0}'.", + "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018": "La déclaration de '{0}' que vous aviez probablement l'intention d'utiliser est définie ici", + "The_declaration_was_marked_as_deprecated_here_2798": "La déclaration a été marquée ici comme étant dépréciée.", + "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500": "Le type attendu provient de la propriété '{0}', qui est déclarée ici sur le type '{1}'", + "The_expected_type_comes_from_the_return_type_of_this_signature_6502": "Le type attendu provient du type de retour de cette signature.", + "The_expected_type_comes_from_this_index_signature_6501": "Le type attendu provient de cette signature d'index.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "L'expression d'une assignation d'exportation doit être un identificateur ou un nom qualifié dans un contexte ambiant.", + "The_file_is_in_the_program_because_Colon_1430": "Le fichier est dans le programme pour la ou les raisons suivantes :", + "The_files_list_in_config_file_0_is_empty_18002": "La liste 'files' du fichier config '{0}' est vide.", + "The_first_export_default_is_here_2752": "La première valeur par défaut d'exportation se trouve ici.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Le premier paramètre de la méthode 'then' d'une promesse doit être un rappel.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Le type global 'JSX.{0}' ne peut pas avoir plusieurs propriétés.", + "The_implementation_signature_is_declared_here_2750": "La signature d'implémentation est déclarée ici.", + "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "La métapropriété « import.meta » n’est pas autorisée dans les fichiers qui seront intégrés dans la sortie CommonJS.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "La méta-propriété « import.meta » est autorisée uniquement lorsque l’option « --module » est « es2020 », « es2022 », « esnext », « system », « node16 », « node18 » ou « nodenext ».", + "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Le type déduit de '{0}' ne peut pas être nommé sans référence à '{1}'. Cela n'est probablement pas portable. Une annotation de type est nécessaire.", + "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Le type déduit de '{0}' référence un type avec une structure cyclique qui ne peut pas être sérialisée de manière triviale. Une annotation de type est nécessaire.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Le type déduit de '{0}' référence un type '{1}' inaccessible. Une annotation de type est nécessaire.", + "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056": "Le type déduit de ce nœud dépasse la longueur maximale que le compilateur va sérialiser. Une annotation de type explicite est nécessaire.", + "The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_n_2850": "L’initialiseur d’une déclaration « using » doit être un objet avec une méthode « [Symbol.dispose]() », ou avoir la valeur « null » ou « undefined ».", + "The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_2851": "L’initialiseur d’une déclaration « await using » doit être un objet avec une méthode « [Symbol.asyncDispose]() » ou « [Symbol.dispose]5D;() », ou avoir la valeur « null » ou « undefined ».", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "L'intersection '{0}' a été réduite à 'never', car la propriété '{1}' existe dans plusieurs constituants et est privée dans certains d'entre eux.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "L'intersection '{0}' a été réduite à 'never', car la propriété '{1}' a des types en conflit dans certains constituants.", + "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795": "Le mot clé 'intrinsic' peut uniquement être utilisé pour déclarer les types intrinsèques fournis par le compilateur.", + "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016": "L'option de compilateur 'jsxFragmentFactory' doit être fournie pour permettre l'utilisation des fragments JSX avec l'option de compilateur 'jsxFactory'.", + "The_last_overload_gave_the_following_error_2770": "La dernière surcharge a généré l'erreur suivante.", + "The_last_overload_is_declared_here_2771": "La dernière surcharge est déclarée ici.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La partie gauche d'une instruction 'for...in' ne peut pas être un modèle de déstructuration.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493": "La partie gauche d’une instruction « for...in » ne peut pas être une déclaration « using ».", + "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494": "La partie gauche d’une instruction « for...in » ne peut pas être une déclaration « await using ».", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La partie gauche d'une instruction 'for...in' ne peut pas utiliser d'annotation de type.", + "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780": "La partie gauche d'une instruction 'for...in' ne doit pas être un accès à une propriété facultative.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "La partie gauche d'une instruction 'for...in' doit être un accès à une variable ou une propriété.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La partie gauche d'une instruction 'for...in' doit être de type 'string' ou 'any'.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "La partie gauche d'une instruction 'for...of' ne peut pas utiliser d'annotation de type.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781": "La partie gauche d'une instruction 'for...of' ne doit pas être un accès à une propriété facultative.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106": "Il est possible que le côté gauche d’une instruction « for...of » ne soit pas « async ».", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La partie gauche d'une instruction 'for...of' doit être un accès à une variable ou une propriété.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "La partie gauche d'une opération arithmétique doit être de type 'any', 'number', 'bigint' ou un type enum.", + "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "La partie gauche d'une expression d'assignation ne doit pas être un accès à une propriété facultative.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La partie gauche d'une expression d'assignation doit être un accès à une variable ou une propriété.", + "The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_2860": "La partie gauche d’une expression « instanceof » doit pouvoir être assignée au premier argument de la méthode « [Symbol.hasInstance] » du côté droit.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La partie gauche d'une expression 'instanceof' doit être de type 'any', un type d'objet ou un paramètre de type.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Paramètres régionaux utilisés pour afficher les messages à l'utilisateur (exemple : 'fr-fr')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Profondeur de dépendance maximale pour la recherche sous node_modules et le chargement de fichiers JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "L'opérande d'un opérateur 'delete' ne peut pas être un identificateur privé.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "L'opérande d'un opérateur 'delete' ne peut pas être une propriété en lecture seule.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "L'opérande d'un opérateur 'delete' doit être une référence de propriété.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "L'opérande d'un opérateur 'delete' doit être facultatif.", + "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "L'opérande d'un opérateur d'incrémentation ou de décrémentation ne doit pas être un accès à une propriété facultative.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "L'opérande d'un opérateur d'incrémentation ou de décrémentation doit être un accès à une variable ou une propriété.", + "The_parser_expected_to_find_a_1_to_match_the_0_token_here_1007": "L'analyseur s'attendait à trouver '{1}' pour correspondre au jeton '{0}' ici.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209": "La racine du projet est ambiguë, mais elle est nécessaire pour résoudre l’entrée de carte d’exportation '{0}' dans le fichier '{1}'. Fournissez l’option de compilateur « rootDir » pour lever l’ambiguïté.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210": "La racine du projet est ambiguë, mais elle est nécessaire pour résoudre l’entrée de carte d’importation «{0}» dans le fichier «{1}». Fournissez l’option de compilateur « rootDir » pour lever l’ambiguïté.", + "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014": "La propriété '{0}' n'est pas accessible sur le type '{1}' dans cette classe, car elle est mise en mémoire fantôme par un autre identificateur privé ayant la même orthographe.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Le type de retour d'une fonction d'élément décoratif de paramètre doit être 'void' ou 'any'.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Le type de retour d'une fonction d'élément décoratif de propriété doit être 'void' ou 'any'.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Le type de retour d'une fonction asynchrone doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065": "Le type de retour d'une fonction ou d'une méthode async doit être le type Promise global.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "Le type de retour d'une fonction ou d'une méthode asynchrone doit être le type global Promise. Vouliez-vous vraiment écrire 'Promise<{0}>' ?", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "La partie droite d'une instruction 'for...in' doit être de type 'any', un type d'objet ou un paramètre de type, mais elle a le type '{0}' ici.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "La partie droite d'une opération arithmétique doit être de type 'any', 'number', 'bigint' ou un type enum.", + "The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_2359": "La partie droite d’une expression « instanceof » doit être de type « any », une classe, une fonction ou un autre type pouvant être affecté au type d’interface « Function », ou un type d’objet avec une méthode « Symbol.hasInstance ».", + "The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression_2848": "La partie droite d’une expression « instanceof » ne doit pas être une expression d’instanciation.", + "The_root_value_of_a_0_file_must_be_an_object_5092": "La valeur racine d'un fichier '{0}' doit être un objet.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0_1278": "Le runtime appellera l’élément décoratif avec des arguments {1}, mais l’élément décoratif attend {0}.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0_1279": "Le runtime appellera l’élément décoratif avec des arguments {1}, mais l’élément décoratif attend au moins {0}.", + "The_shadowing_declaration_of_0_is_defined_here_18017": "La déclaration avec mise en mémoire fantôme de '{0}' est définie ici", + "The_signature_0_of_1_is_deprecated_6387": "La signature '{0}' de '{1}' est dépréciée.", + "The_specified_path_does_not_exist_Colon_0_5058": "Le chemin spécifié n'existe pas : '{0}'.", + "The_tag_was_first_specified_here_8034": "La balise a d'abord été spécifiée ici.", + "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "La cible d'une assignation rest d'objet ne doit pas être un accès à une propriété facultative.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "La cible de l'assignation du reste d'un objet doit être un accès à une variable ou une propriété.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Le contexte 'this' de type '{0}' n'est pas assignable au contexte 'this' de type '{1}' de la méthode.", + "The_this_types_of_each_signature_are_incompatible_2685": "Les types 'this' de chaque signature sont incompatibles.", + "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104": "Le type '{0}' est 'readonly' et ne peut pas être assigné au type modifiable '{1}'.", + "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Le ’type’ de modificateur ne peut pas être utilisé sur une importation nommée quand le ’type’ d’exportation est utilisé dans son instruction import.", + "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Le ’type’ de modificateur ne peut pas être utilisé sur une importation nommée quand le ’type’ d’importation est utilisé dans son instruction import.", + "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Le type d'une déclaration de fonction doit correspondre à la signature de la fonction.", + "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Impossible de sérialiser le type de ce nœud, car sa propriété «{0}» ne peut pas être sérialisée.", + "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Le type retourné par la méthode '{0}()' d'un itérateur asynchrone doit être une promesse pour un type ayant une propriété 'value'.", + "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Le type retourné par la méthode '{0}()' d'un itérateur doit avoir une propriété 'value'.", + "The_types_of_0_are_incompatible_between_these_types_2200": "Les types de '{0}' sont incompatibles entre eux.", + "The_types_returned_by_0_are_incompatible_between_these_types_2201": "Les types retournés par '{0}' sont incompatibles entre eux.", + "The_value_0_cannot_be_used_here_18050": "La valeur '{0}' ne peut pas être utilisée ici.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "La déclaration de variable d'une instruction 'for...in' ne peut pas avoir d'initialiseur.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La déclaration de variable d'une instruction 'for...of' ne peut pas avoir d'initialiseur.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "L'instruction 'with' n'est pas prise en charge. Tous les symboles d'un bloc 'with' ont le type 'any'.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setti_6280": "Il existe des types sur « {0} », mais ce résultat n’a pas pu être résolu sous votre paramètre « moduleResolution » actuel. Envisagez la mise à jour vers « node16 », « nodenext » ou « bundler ».", + "There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278": "Il existe des types sur « {0} », mais ce résultat n’a pas pu être résolu lors du respect des « exports » package.json. La bibliothèque « {1} » devra peut-être mettre à jour son package.json ou ses typages.", + "There_is_no_capturing_group_named_0_in_this_regular_expression_1532": "Il n’existe aucun groupe de capture nommé « {0} » dans cette expression régulière.", + "There_is_nothing_available_for_repetition_1507": "Aucun élément n’est disponible pour la répétition.", + "This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found_2874": "Cette balise JSX nécessite que « {0} » soit dans la portée, mais elle n'a pas pu être trouvée.", + "This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_fo_2875": "Cette balise JSX nécessite que le chemin du module '{0}' existe, mais aucun n'a pu être trouvé. Assurez-vous que les types pour le package approprié sont installés.", + "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "La propriété '{0}' de cette balise JSX attend un seul enfant de type '{1}', mais plusieurs enfants ont été fournis.", + "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "La propriété '{0}' de cette balise JSX attend le type '{1}', qui nécessite plusieurs enfants, mais un seul enfant a été fourni.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534": "Cette référence arrière fait référence à un groupe qui n’existe pas. Il n’y a aucun groupe de capture dans cette expression régulière.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533": "Cette référence arrière fait référence à un groupe qui n’existe pas. Il n’y a que {0} groupes de capture dans cette expression régulière.", + "This_binary_expression_is_never_nullish_Are_you_missing_parentheses_2870": "Cette expression binaire n’est jamais nulle. Avez-vous des parenthèses manquantes ?", + "This_character_cannot_be_escaped_in_a_regular_expression_1535": "Ce caractère ne peut pas être placé dans une séquence d’échappement d’expression régulière.", + "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Cette comparaison semble involontaire, car les types '{0}' et '{1}' n’ont pas de chevauchement.", + "This_condition_will_always_return_0_2845": "Cette condition retourne toujours '{0}'.", + "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Cette condition retourne toujours '{0}', car JavaScript compare les objets par référence, et non par valeur.", + "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Cette condition retourne toujours true, car cette « {0} » est toujours définie.", + "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Cette condition retourne toujours true, car cette fonction est toujours définie. Est-ce que vous avez voulu l'appeler à la place ?", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Cette fonction constructeur peut être convertie en déclaration de classe.", + "This_expression_is_always_nullish_2871": "Cette expression est toujours nulle.", + "This_expression_is_not_callable_2349": "Impossible d'appeler cette expression.", + "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Impossible d'appeler cette expression, car il s'agit d'un accesseur 'get'. Voulez-vous vraiment l'utiliser sans '()' ?", + "This_expression_is_not_constructable_2351": "Impossible de construire cette expression.", + "This_file_already_has_a_default_export_95130": "Ce fichier a déjà une exportation par défaut", + "This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_b_2878": "Ce chemin d'importation n'est pas sûr à réécrire car il renvoie à un autre projet et le chemin relatif entre les fichiers de sortie des projets n'est pas le même que le chemin relatif entre ses fichiers d'entrée.", + "This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_duri_2877": "Cette importation utilise une extension '{0}' pour résoudre un fichier TypeScript d'entrée, mais ne sera pas réécrite pendant l'émission car il ne s'agit pas d'un chemin relatif.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Ceci est la déclaration augmentée. Pensez à déplacer la déclaration d'augmentation dans le même fichier.", + "This_kind_of_expression_is_always_falsy_2873": "Ce genre d’expression est toujours fausse.", + "This_kind_of_expression_is_always_truthy_2872": "Ce genre d’expression est toujours vrai.", + "This_may_be_converted_to_an_async_function_80006": "Ceci peut être converti en fonction asynchrone.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122": "Ce membre ne peut pas avoir de commentaire JSDoc avec une balise '@override' car il n'est pas déclaré dans la classe de base '{0}'.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123": "Ce membre ne peut pas avoir de commentaire JSDoc avec une balise 'override' car il n'est pas déclaré dans la classe de base '{0}'. Vouliez-vous dire '{1}' ?", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121": "Ce membre ne peut pas avoir de commentaire JSDoc avec une balise '@override' car sa classe conteneur '{0}' n'étend pas une autre classe.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic_4128": "Ce membre ne peut pas avoir de commentaire JSDoc avec une balise « @override », car son nom est dynamique.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113": "Ce membre ne peut pas avoir de modificateur 'override', car il n'est pas déclaré dans la classe de base '{0}'.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117": "Ce membre ne peut pas avoir de modificateur 'override', car il n'est pas déclaré dans la classe de base '{0}'. Vouliez-vous dire '{1}'?", + "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112": "Ce membre ne peut pas avoir de modificateur 'override', car sa classe conteneur '{0}' n'étend pas une autre classe.", + "This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic_4127": "Ce membre ne peut pas avoir de modificateur 'override', car son nom est dynamique.", + "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119": "Ce membre doit avoir un commentaire JSDoc avec une balise '@override' car il remplace un membre de la classe de base '{0}'.", + "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114": "Ce membre doit avoir un modificateur 'override', car il se substitue à un membre de la classe de base '{0}'.", + "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116": "Ce membre doit avoir un modificateur 'override', car il se substitue à une méthode abstraite déclarée dans la classe de base '{0}'.", + "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Vous pouvez référencer ce module uniquement avec les importations/exportations ECMAScript en activant l'indicateur '{0}' et en référençant son exportation par défaut.", + "This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag_2594": "Ce module est déclaré avec 'export =', et ne peut être utilisé qu’avec une importation par défaut lors de l’utilisation de l’indicateur '{0}'.", + "This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2_6807": "Cette opération peut être simplifiée. Ce shift est identique à '{0} {1} {2}'.", + "This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation_7012": "Cette surcharge retourne implicitement le type « {0} », car elle n’a pas d’annotation de type de retour.", + "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394": "Cette signature de surcharge n'est pas compatible avec sa signature d'implémentation.", + "This_parameter_is_not_allowed_with_use_strict_directive_1346": "Ce paramètre n'est pas autorisé avec la directive 'use strict'.", + "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120": "Cette propriété de paramètre doit avoir un commentaire JSDoc avec une balise '@override' car elle remplace un membre dans la classe de base '{0}'.", + "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115": "Cette propriété de paramètre doit avoir un modificateur 'override', car il se substitue à un membre de la classe de base '{0}'.", + "This_regular_expression_flag_cannot_be_toggled_within_a_subpattern_1509": "Cet indicateur d’expression régulière ne peut pas être activé/désactivé dans un sous-modèle.", + "This_regular_expression_flag_is_only_available_when_targeting_0_or_later_1501": "Cet indicateur d’expression régulière n’est disponible que lors du ciblage de « {0} » ou d’une version ultérieure.", + "This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolv_2876": "Ce chemin d'importation relatif n'est pas sûr à réécrire car il ressemble à un nom de fichier, mais se résout en réalité en « {0} ».", + "This_spread_always_overwrites_this_property_2785": "Cette diffusion écrase toujours cette propriété.", + "This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled_1294": "Cette syntaxe n’est pas autorisée quand 'erasableSyntaxOnly' est activé.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060": "Cette syntaxe est réservée dans les fichiers avec l’extension .mts ou .cts. Veuillez ajouter une virgule de fin ou une contrainte explicite.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059": "Cette syntaxe est réservée dans les fichiers avec l’extension .mts ou .cts. Utilisez une expression « as »à la place.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Cette syntaxe nécessite une application d'assistance importée, mais le module '{0}' est introuvable.", + "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Cette syntaxe nécessite une assistance importée nommée '{1}' mais qui n'existe pas dans '{0}'. Effectuez une mise à niveau de votre version de '{0}'.", + "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Cette syntaxe nécessite un composant d'assistance importé nommé '{1}' avec {2} paramètres, ce qui n'est pas compatible avec celui qui se trouve dans '{0}'. Effectuez une mise à niveau de votre version de '{0}'.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Ce paramètre de type nécessite peut-être une contrainte « extends {0}».", + "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Cette utilisation de « import » n’est pas valide. Les appels « import() » peuvent être écrits, mais ils doivent avoir des parenthèses et ne peuvent pas avoir d’arguments de type.", + "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482": "Pour convertir ce fichier en module ECMAScript, ajoutez le champ `\"type\" : \"module\"` à '{0}'.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481": "Pour convertir ce fichier en module ECMAScript, changez son extension de fichier en '{0}', ou ajoutez le champ `\"type\" : \"module\"` à '{1}'.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480": "Pour convertir ce fichier en module ECMAScript, changez son extension de fichier en '{0}' ou créez un fichier package.json local avec `{ \"type\": \"module\" }`.", + "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483": "Pour convertir ce fichier en module ECMAScript, créez un fichier package.json local avec `{ \"type\": \"module\" }`.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Les expressions « await » de niveau supérieur sont autorisées uniquement lorsque l’option « module » est définie sur « es2022 », « esnext », « system », « node16 », « node18 », « nodenext » ou « preserve », et que l’option « target » a la valeur « es2017 » ou une valeur supérieure.", + "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854": "Les instructions « await using » de niveau supérieur sont autorisées uniquement lorsque l’option « module » a la valeur « es2022 », « esnext », « system », « node16 », « node18 », « nodenext » ou « preserve », et que l’option « target » a la valeur « es2017 » ou une valeur supérieure.", + "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Les déclarations de niveau supérieur dans les fichiers .d.ts doivent commencer par un modificateur 'declare' ou 'export'.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_nod_1432": "Les boucles « for await » de niveau supérieur sont autorisées uniquement lorsque l’option « module » a la valeur « es2022 », « esnext », « system », « node16 », « node18 », « nodenext » ou « preserve », et que l’option « target » a la valeur « es2017 » ou une valeur supérieure.", + "Trailing_comma_not_allowed_1009": "Virgule de fin non autorisée.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilez chaque fichier sous forme de module distinct (semblable à 'ts.transpileModule').", + "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Essayez 'npm i --save-dev @types/{1}' s'il existe, ou ajoutez un nouveau fichier de déclaration (.d.ts) contenant 'declare module '{0}';'", + "Trying_other_entries_in_rootDirs_6110": "Essai avec d'autres entrées dans 'rootDirs'.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Essai avec la substitution '{0}', emplacement de module candidat : '{1}'.", + "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493": "Le type tuple '{0}' de longueur '{1}' n'a aucun élément à l'index '{2}'.", + "Tuple_type_arguments_circularly_reference_themselves_4110": "Les arguments de type tuple se référencent de manière circulaire.", + "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802": "Le type '{0}' peut être itéré uniquement à l'aide de l'indicateur '--downlevelIteration' ou avec un '--target' dont la valeur est 'es2015' ou une version ultérieure.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Impossible d'utiliser le type '{0}' comme type d'index.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Le type '{0}' ne peut pas être utilisé pour indexer le type '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Le type '{0}' ne satisfait pas la contrainte '{1}'.", + "Type_0_does_not_satisfy_the_expected_type_1_1360": "Le type '{0}' ne satisfait pas le type attendu '{1}'.", + "Type_0_has_no_call_signatures_2757": "Le type '{0}' n'a aucune signature d'appel.", + "Type_0_has_no_construct_signatures_2761": "Le type '{0}' n'a aucune signature de construction.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Le type '{0}' n'a aucune signature d'index correspondant au type '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Le type '{0}' n'a aucune propriété en commun avec le type '{1}'.", + "Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable_2635": "Le type '{0}' n’a aucune signature pour laquelle la liste d’arguments de type est applicable.", + "Type_0_is_generic_and_can_only_be_indexed_for_reading_2862": "Le type « {0} » est générique et ne peut être indexé que pour la lecture.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "Le type '{0}' n'a pas les propriétés suivantes du type '{1}': {2}", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "Le type '{0}' n'a pas les propriétés suivantes du type '{1}': {2} et de {3} autres.", + "Type_0_is_not_a_constructor_function_type_2507": "Le type '{0}' n'est pas un type de fonction constructeur.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compa_1055": "Le type « {0} » n’est pas un type de retour de fonction asynchrone valide dans ES5, car il ne fait pas référence à une valeur de constructeur compatible avec une promesse.", + "Type_0_is_not_an_array_type_2461": "Le type '{0}' n'est pas un type de tableau.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Le type '{0}' n'est pas un type de tableau ou un type de chaîne.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Le type '{0}' n'est pas un type tableau ou un type chaîne, ou n'a pas de méthode '[Symbol.iterator]()' qui retourne un itérateur.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Le type '{0}' n'est pas un type tableau ou n'a pas de méthode '[Symbol.iterator]()' qui retourne un itérateur.", + "Type_0_is_not_assignable_to_type_1_2322": "Impossible d'assigner le type '{0}' au type '{1}'.", + "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820": "Le type '{0}' ne peut pas être attribué au type '{1}'. Voulez-vous dire '{2}'?", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Impossible d'assigner le type '{0}' au type '{1}'. Il existe deux types distincts portant ce nom, mais ils ne sont pas liés.", + "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636": "Le type «{0}» n’est pas assignable au type «{1}» comme implicite par l’annotation de variance.", + "Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values_18033": "Le type « {0} » n’est pas attribuable au type « {1} » comme requis pour les valeurs de membre enum calculées.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375": "Le type '{0}' n'est pas assignable au type '{1}' avec 'exactOptionalPropertyTypes : true'. Pensez à ajouter 'undefined' aux types des propriétés de la cible.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "Le type '{0}' n'est pas assignable au type '{1}' avec 'exactOptionalPropertyTypes : true'. Pensez à ajouter 'undefined' au type de la cible.", + "Type_0_is_not_comparable_to_type_1_2678": "Le type '{0}' n'est pas comparable au type '{1}'.", + "Type_0_is_not_generic_2315": "Le type '{0}' n'est pas générique.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "Le type '{0}' peut représenter une valeur primitive, ce qui n’est pas autorisé en tant qu’opérande droit de l’opérateur 'in'.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Le type '{0}' doit avoir une méthode '[Symbol.asyncIterator]()' qui retourne un itérateur asynchrone.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Le type '{0}' doit avoir une méthode '[Symbol.iterator]()' qui retourne un itérateur.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Le type '{0}' ne fournit aucune correspondance pour la signature '{1}'.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Le type '{0}' fait référence à lui-même de manière récursive en tant que type de base.", + "Type_Checking_6248": "Vérification du type", + "Type_alias_0_circularly_references_itself_2456": "L'alias de type '{0}' fait référence à lui-même de manière circulaire.", + "Type_alias_must_be_given_a_name_1439": "Un nom doit être attribué à l’alias de type.", + "Type_alias_name_cannot_be_0_2457": "Le nom de l'alias de type ne peut pas être '{0}'.", + "Type_aliases_can_only_be_used_in_TypeScript_files_8008": "Les alias de type peuvent uniquement être utilisés dans les fichiers TypeScript.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "Une annotation de type ne peut pas apparaître sur une déclaration de constructeur.", + "Type_annotations_can_only_be_used_in_TypeScript_files_8010": "Les annotations de type peuvent uniquement être utilisées dans les fichiers TypeScript.", + "Type_argument_expected_1140": "Argument de type attendu.", + "Type_argument_list_cannot_be_empty_1099": "La liste des arguments de type ne peut pas être vide.", + "Type_arguments_can_only_be_used_in_TypeScript_files_8011": "Les arguments de type peuvent uniquement être utilisés dans les fichiers TypeScript.", + "Type_arguments_for_0_circularly_reference_themselves_4109": "Les arguments de type pour '{0}' se référencent de manière circulaire.", + "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016": "Les expressions d'assertion de type peuvent uniquement être utilisées dans les fichiers TypeScript.", + "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626": "Le type situé à la position {0} dans la source n'est pas compatible avec le type situé à la position {1} dans la cible.", + "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627": "Le type situé aux positions allant de {0} à {1} dans la source n'est pas compatible avec le type situé à la position {2} dans la cible.", + "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039": "Le type contenant le nom privé « {0} » ne peut pas être utilisé avec --isolatedDeclarations.", + "Type_declaration_files_to_be_included_in_compilation_6124": "Fichiers de déclaration de type à inclure dans la compilation.", + "Type_expected_1110": "Type attendu.", + "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456": "Les assertions d’importation de type doivent avoir exactement une clé ( « mode résolution » ) avec la valeur « import » ou « require ».", + "Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1464": "Les attributs d’importation de type doivent avoir exactement une clé ( « resolution-mode » ) avec une valeur « import » ou « require ».", + "Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute_1542": "L'importation de type d'un module ECMAScript à partir d'un module CommonJS doit avoir un attribut « resolution-mode ».", + "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589": "L'instanciation de type est trop profonde et éventuellement infinie.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Le type est directement ou indirectement référencé dans le rappel d'exécution de sa propre méthode 'then'.", + "Type_library_referenced_via_0_from_file_1_1402": "Bibliothèque de types référencée via '{0}' à partir du fichier '{1}'", + "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Bibliothèque de types référencée via '{0}' à partir du fichier '{1}' ayant le packageId '{2}'", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Le type d'un opérande 'await' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Le type de la valeur de la propriété calculée est '{0}'. Il ne peut pas être assigné au type '{1}'.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Le type de variable membre d’instance '{0}' ne peut pas référencer l’identificateur '{1}' déclaré dans le constructeur.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Le type des éléments itérés d'un opérande 'yield*' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Le type de la propriété '{0}' se référence de façon circulaire dans le type mappé '{1}'.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Le type d'un opérande 'yield' dans un générateur asynchrone doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", + "Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribut_1541": "L'importation de type uniquement d'un module ECMAScript à partir d'un module CommonJS doit avoir un attribut « mode de résolution ».", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Le type provient de cette importation. Impossible d'appeler ou de construire une importation de style d'espace de noms, ce qui va entraîner un échec au moment de l'exécution. À la place, utilisez ici une importation par défaut ou une importation avec require.", + "Type_parameter_0_has_a_circular_constraint_2313": "Le paramètre de type '{0}' possède une contrainte circulaire.", + "Type_parameter_0_has_a_circular_default_2716": "Le paramètre de type '{0}' a une valeur par défaut circulaire.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Le paramètre de type '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Le paramètre de type '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Le paramètre de type '{0}' de la classe exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Le paramètre de type '{0}' de la fonction exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Le paramètre de type '{0}' de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103": "Le paramètre de type '{0}' du type d'objet mappé exporté utilise le nom privé '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Le paramètre de type '{0}' de l'alias du type exporté contient ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Le paramètre de type '{0}' de la méthode de l'interface exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Le paramètre de type '{0}' de la méthode publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Le paramètre de type '{0}' de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{1}'.", + "Type_parameter_declaration_expected_1139": "Déclaration du paramètre de type attendue.", + "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004": "Les déclarations de paramètre de type peuvent uniquement être utilisées dans les fichiers TypeScript.", + "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744": "Les valeurs par défaut des paramètres de type peuvent uniquement référencer des paramètres de type déclarés.", + "Type_parameter_list_cannot_be_empty_1098": "La liste des paramètres de type ne peut pas être vide.", + "Type_parameter_name_cannot_be_0_2368": "Le nom du paramètre de type ne peut pas être '{0}'.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "Les paramètres de type ne peuvent pas apparaître sur une déclaration de constructeur.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Impossible d'assigner le prédicat de type '{0}' à '{1}'.", + "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799": "Le type produit un type de tuple trop grand pour être représenté.", + "Type_reference_directive_0_was_not_resolved_6120": "======== La directive de référence de type '{0}' n'a pas été résolue. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La directive de référence de type '{0}' a été correctement résolue en '{1}', primaire : {2}. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== La directive de référence de type '{0}' a été correctement résolue en '{1}' avec l'ID de package '{2}', primaire : {3}. ========", + "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037": "Les expressions de satisfaction de type peuvent uniquement être utilisées dans les fichiers TypeScript.", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Les types ne peuvent pas apparaître dans les déclarations d’exportation dans les fichiers JavaScript.", + "Types_have_separate_declarations_of_a_private_property_0_2442": "Les types ont des déclarations distinctes d'une propriété privée '{0}'.", + "Types_of_construct_signatures_are_incompatible_2419": "Les types de signature de construction sont incompatibles.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "Les types des paramètres '{0}' et '{1}' sont incompatibles.", + "Types_of_property_0_are_incompatible_2326": "Les types de la propriété '{0}' sont incompatibles.", + "Unable_to_open_file_0_6050": "Impossible d'ouvrir le fichier '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Impossible de résoudre la signature d'un élément décoratif de classe quand il est appelé en tant qu'expression.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Impossible de résoudre la signature d'un élément décoratif de méthode quand il est appelé en tant qu'expression.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Impossible de résoudre la signature d'un élément décoratif de paramètre quand il est appelé en tant qu'expression.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Impossible de résoudre la signature d'un élément décoratif de propriété quand il est appelé en tant qu'expression.", + "Undetermined_character_escape_1513": "L’échappement de caractère n’est pas déterminé.", + "Unexpected_0_Did_you_mean_to_escape_it_with_backslash_1508": "« {0} » est inattendu. Vouliez-vous procéder à son échappement avec une barre oblique inverse ?", + "Unexpected_end_of_text_1126": "Fin de texte inattendue.", + "Unexpected_keyword_or_identifier_1434": "Mot clé ou identificateur inattendu.", + "Unexpected_token_1012": "Jeton inattendu.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Jeton inattendu. Un constructeur, une méthode, un accesseur ou une propriété est attendu.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Jeton inattendu. Un nom de paramètre de type est attendu sans accolades.", + "Unexpected_token_Did_you_mean_or_gt_1382": "Jeton inattendu. Est-ce que vous avez voulu utiliser '{'>'}' ou '>' ?", + "Unexpected_token_Did_you_mean_or_rbrace_1381": "Jeton inattendu. Est-ce que vous avez voulu utiliser '{'}'}' ou '}' ?", + "Unexpected_token_expected_1179": "Jeton inattendu. '{' est attendu.", + "Unicode_escape_sequence_cannot_appear_here_17021": "La séquence d’échappement Unicode ne peut pas apparaître ici.", + "Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_se_1538": "Les séquences d’échappement Unicode ne sont disponibles que lorsque l’indicateur Unicode (u) ou l’indicateur Unicode Sets (v) est défini.", + "Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v__1530": "Les expressions de valeur de propriété Unicode ne sont disponibles que lorsque l’indicateur Unicode (u) ou l’indicateur Unicode Sets (v) est défini.", + "Unknown_Unicode_property_name_1524": "Le nom de propriété Unicode est inconnu.", + "Unknown_Unicode_property_name_or_value_1529": "Une valeur ou un nom de propriété Unicode est inconnu.", + "Unknown_Unicode_property_value_1526": "La valeur de propriété Unicode est inconnue.", + "Unknown_build_option_0_5072": "Option de build inconnue : '{0}'.", + "Unknown_build_option_0_Did_you_mean_1_5077": "Option de build inconnue : '{0}'. Est-ce que vous avez voulu utiliser '{1}' ?", + "Unknown_compiler_option_0_5023": "Option de compilateur '{0}' inconnue.", + "Unknown_compiler_option_0_Did_you_mean_1_5025": "Option de compilateur inconnue : '{0}'. Est-ce que vous avez voulu utiliser '{1}' ?", + "Unknown_keyword_or_identifier_Did_you_mean_0_1435": "Mot clé ou identificateur inconnu. Souhaitiez-vous utiliser «{0}» ?", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "Option 'excludes' inconnue. Voulez-vous utiliser 'exclude' ?", + "Unknown_regular_expression_flag_1499": "L’indicateur d’expression régulière est inconnu.", + "Unknown_type_acquisition_option_0_17010": "Option d'acquisition de type inconnue '{0}'.", + "Unknown_type_acquisition_option_0_Did_you_mean_1_17018": "Option d'acquisition de type inconnue : '{0}'. Est-ce que vous avez voulu utiliser '{1}' ?", + "Unknown_watch_option_0_5078": "Option de surveillance inconnue : '{0}'.", + "Unknown_watch_option_0_Did_you_mean_1_5079": "Option de surveillance inconnue : '{0}'. Est-ce que vous avez voulu utiliser '{1}' ?", + "Unreachable_code_detected_7027": "Code inatteignable détecté.", + "Unterminated_Unicode_escape_sequence_1199": "Séquence d'échappement Unicode inachevée.", + "Unterminated_quoted_string_in_response_file_0_6045": "Chaîne entre guillemets inachevée dans le fichier réponse '{0}'.", + "Unterminated_regular_expression_literal_1161": "Littéral d'expression régulière inachevé.", + "Unterminated_string_literal_1002": "Littéral de chaîne inachevé.", + "Unterminated_template_literal_1160": "Littéral de modèle inachevé.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Les appels de fonctions non typées ne peuvent pas accepter d'arguments de type.", + "Unused_label_7028": "Étiquette inutilisée.", + "Unused_ts_expect_error_directive_2578": "Directive '@ts-expect-error' inutilisée.", + "Update_import_from_0_90058": "Mettre à jour l’importation à partir de \"{0}\"", + "Update_modifiers_of_0_90061": "Mettre à jour les modificateurs de « {0} »", + "Updating_output_timestamps_of_project_0_6359": "Mise à jour des horodatages de sortie du projet '{0}'...", + "Updating_unchanged_output_timestamps_of_project_0_6371": "Mise à jour des horodatages de sortie inchangés du projet '{0}'...", + "Use_0_95174": "Utilisez `{0}`.", + "Use_0_instead_5106": "Utilisez « {0} » à la place.", + "Use_Number_isNaN_in_all_conditions_95175": "Utilisez 'Number.isNaN' dans toutes les conditions.", + "Use_element_access_for_0_95145": "Utiliser l'accès à l'élément pour '{0}'", + "Use_element_access_for_all_undeclared_properties_95146": "L'accès à l'élément est utilisé pour toutes les propriétés non déclarées.", + "Use_import_type_95180": "Utiliser « import type »", + "Use_synthetic_default_member_95016": "Utilisez un membre 'default' synthétique.", + "Use_the_package_json_exports_field_when_resolving_package_imports_6408": "Utilisez le champ « exports » package.json lors de la résolution des importations de package.", + "Use_the_package_json_imports_field_when_resolving_imports_6409": "Utilisez le champ « imports » package.json lors de la résolution des importations.", + "Use_type_0_95181": "Utiliser « type {0} »", + "Using_0_subpath_1_with_target_2_6404": "Utilisation de '{0}' de sous-chemin '{1}' avec la cible '{2}'.", + "Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found_2879": "L'utilisation de fragments JSX nécessite que la fabrique de fragments '{0}' soit dans la portée, mais elle n'a pas pu être trouvée.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'utilisation d'une chaîne dans une instruction 'for...of' est prise en charge uniquement dans ECMAScript 5 et version supérieure.", + "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "L’utilisation de--build,-b fera en sorte que tsc se comporte plus comme une build orchestrateur qu’un compilateur. Utilisé pour déclencher la génération de projets composites sur lesquels vous pouvez obtenir des informations supplémentaires sur {0}", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Utilisation des options de compilateur de la redirection de référence de projet : '{0}'.", + "VERSION_6036": "VERSION", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "La valeur de type '{0}' n'a aucune propriété en commun avec le type '{1}'. Voulez-vous vraiment l'appeler ?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "La valeur de type '{0}' ne peut pas être appelée. Voulez-vous inclure 'new' ?", + "Variable_0_implicitly_has_an_1_type_7005": "La variable '{0}' possède implicitement un type '{1}'.", + "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043": "La variable '{0}' a implicitement un type '{1}', mais il est possible de déduire un meilleur type à partir de l'utilisation.", + "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046": "La variable '{0}' a implicitement le type '{1}' à certains emplacements, mais il est possible de déduire un meilleur type à partir de l'utilisation.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "La variable '{0}' a implicitement le type '{1}' dans certains emplacements où son type ne peut pas être déterminé.", + "Variable_0_is_used_before_being_assigned_2454": "La variable '{0}' est utilisée avant d'être assignée.", + "Variable_declaration_expected_1134": "Déclaration de variable attendue.", + "Variable_declaration_list_cannot_be_empty_1123": "La liste des déclarations de variable ne peut pas être vide.", + "Variable_declaration_not_allowed_at_this_location_1440": "Déclaration de variable non autorisée à cet emplacement.", + "Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9010": "La variable doit avoir une annotation de type explicite avec --isolatedDeclarations.", + "Variables_with_multiple_declarations_cannot_be_inlined_95186": "Les variables avec plusieurs déclarations ne peuvent pas être inlined.", + "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625": "L'élément variadique situé à la position {0} dans la source ne correspond pas à l'élément situé à la position {1} dans la cible.", + "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637": "Les annotations de variance sont uniquement prises en charge dans les alias de type pour les types objet, fonction, constructeur et mappé.", + "Version_0_6029": "Version {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file_95110": "Visitez https://aka.ms/tsconfig pour en savoir plus sur ce fichier", + "WATCH_OPTIONS_6918": "OPTIONS D’OBSERVATION", + "Watch_and_Build_Modes_6250": "Modes d’Observation et de Génération", + "Watch_input_files_6005": "Fichiers d'entrée d'espion.", + "Watch_option_0_requires_a_value_of_type_1_5080": "L'option de surveillance '{0}' nécessite une valeur de type {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Nous ne pouvons écrire un type pour « {0} » qu’en ajoutant un type pour l’ensemble du paramètre ici.", + "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Lors de l’attribution de fonctions, vérifiez que les paramètres et les valeurs de retour sont compatibles avec le sous-type.", + "When_type_checking_take_into_account_null_and_undefined_6699": "Lors de la vérification de type, prenez en compte « null » et « undefined ».", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Garder la sortie de console obsolète en mode espion au lieu d'effacer l'écran.", + "Wrap_all_invalid_characters_in_an_expression_container_95109": "Inclure dans un wrapper tous les caractères non valides au sein d'un conteneur d'expressions", + "Wrap_all_invalid_decorator_expressions_in_parentheses_95195": "Mettre toutes les expressions de décorateurs non valides entre parenthèses", + "Wrap_all_object_literal_with_parentheses_95116": "Placer tous les littéraux d'objet entre parenthèses", + "Wrap_all_unparented_JSX_in_JSX_fragment_95121": "Inclure dans un wrapper tous les JSX non apparentés au sein d'un fragment JSX", + "Wrap_in_JSX_fragment_95120": "Inclure dans un wrapper au sein d'un fragment JSX", + "Wrap_in_parentheses_95194": "Mettre entre parenthèses", + "Wrap_invalid_character_in_an_expression_container_95108": "Inclure dans un wrapper un caractère non valide au sein d'un conteneur d'expressions", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Placer le corps suivant entre parenthèses pour indiquer qu'il s'agit d'un littéral d'objet", + "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Vous pouvez en savoir plus sur toutes les options du compilateur sur {0}", + "You_cannot_rename_a_module_via_a_global_import_8031": "Vous ne pouvez pas renommer un module via une importation globale.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Vous ne pouvez pas renommer les éléments définis dans un dossier « node_modules ».", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Vous ne pouvez pas renommer les éléments définis dans un autre dossier « node_modules ».", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Vous ne pouvez pas renommer des éléments définis dans la bibliothèque TypeScript standard.", + "You_cannot_rename_this_element_8000": "Vous ne pouvez pas renommer cet élément.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accepte trop peu d'arguments pour pouvoir être utilisé ici en tant qu'élément décoratif. Voulez-vous vraiment l'appeler d'abord et écrire '@{0}()' ?", + "_0_and_1_index_signatures_are_incompatible_2330": "Les signatures d'index « {0} » et « {1} » sont incompatibles.", + "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Les opérations '{0}' et '{1}' ne peuvent pas être mélangées sans parenthèses.", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' spécifié deux fois. L'attribut nommé '{0}' va être remplacé.", + "_0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17019": "« {0} » à la fin d’un type n’est pas une syntaxe TypeScript valide. Vouliez-vous écrire « {1} » ?", + "_0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17020": "« {0} » au début d’un type n’est pas une syntaxe TypeScript valide. Vouliez-vous écrire « {1} » ?", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}' peut uniquement être importé via l'activation de l'indicateur 'esModuleInterop' et l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}' peut uniquement être importé via l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}' peut uniquement être importé à l'aide d'un appel 'require' ou via l'activation de l'indicateur 'esModuleInterop' et l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}' peut uniquement être importé à l'aide d'un appel 'require' ou via l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}' peut uniquement être importé à l'aide de 'import {1} = require({2})' ou via l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}' peut uniquement être importé à l'aide de 'import {1} = require({2})' ou via l'activation de l'indicateur 'esModuleInterop' et l'utilisation d'une importation par défaut.", + "_0_cannot_be_used_as_a_JSX_component_2786": "Impossible d'utiliser '{0}' comme composant JSX.", + "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "'{0}' ne peut pas être utilisé en tant que valeur, car il a été exporté à l'aide de 'export type'.", + "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "'{0}' ne peut pas être utilisé en tant que valeur, car il a été importé à l'aide de 'import type'.", + "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "Les composants '{0}' n'acceptent pas du texte en tant qu'éléments enfants. Le texte dans JSX a le type 'string', mais le type attendu de '{1}' est '{2}'.", + "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082": "'{0}' a pu être instancié avec un type arbitraire qui n'est peut-être pas lié à '{1}'.", + "_0_declarations_can_only_be_declared_inside_a_block_1156": "Les déclarations « {0} » ne peuvent être déclarées que dans un bloc.", + "_0_declarations_can_only_be_used_in_TypeScript_files_8006": "Les déclarations '{0}' peuvent uniquement être utilisées dans les fichiers TypeScript.", + "_0_declarations_may_not_have_binding_patterns_1492": "Les déclarations « {0} » ne peuvent pas avoir de modèles de liaison.", + "_0_declarations_must_be_initialized_1155": "Les déclarations « {0} » doivent être initialisées.", + "_0_expected_1005": "'{0}' attendu.", + "_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is__18055": "« {0} » a un type de chaîne, mais doit avoir une syntaxe de chaîne syntaxiquement reconnaissable quand « isolatedModules » est activé.", + "_0_has_no_exported_member_named_1_Did_you_mean_2_2724": "'{0}' n'a aucun membre exporté nommé '{1}'. Est-ce que vous pensiez à '{2}' ?", + "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050": "'{0}' a implicitement un type de retour '{1}', mais il est possible de déduire un meilleur type à partir de l'utilisation.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' possède implicitement le type de retour 'any', car il n'a pas d'annotation de type de retour, et est référencé directement ou indirectement dans l'une de ses expressions de retour.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' a implicitement le type 'any', car il n'a pas d'annotation de type et est référencé directement ou indirectement dans son propre initialiseur.", + "_0_index_signatures_are_incompatible_2634": "Les signatures d'index « {0} » sont incompatibles.", + "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "Le type d’index « {0} », « {1} », ne peut pas être attribué au type d’index « {2} », « {3} ».", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' est une primitive, mais '{1}' est un objet wrapper. Si possible, utilisez '{0}' de préférence.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' est un type qui ne peut pas être importé dans des fichiers JavaScript. Utilisez '{1}' dans une annotation de type JSDoc.", + "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled_1484": "« {0} » est un type et doit être importé en utilisant une importation de type uniquement quand « verbatimModuleSyntax » est activé.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "« {0} » est un changement de nom inutilisé de « {1} ». Souhaitiez-vous l’utiliser comme annotation de type?", + "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}' peut être assigné à la contrainte de type '{1}', mais '{1}' a pu être instancié avec un autre sous-type de contrainte '{2}'.", + "_0_is_automatically_exported_here_18044": "'{0}' est automatiquement exporté ici.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' est déclaré mais sa valeur n'est jamais lue.", + "_0_is_declared_but_never_used_6196": "'{0}' est déclaré mais n'est jamais utilisé.", + "_0_is_declared_here_2728": "'{0}' est déclaré ici.", + "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611": "'{0}' est défini en tant que propriété dans la classe '{1}', mais il est remplacé ici dans '{2}' en tant qu'accesseur.", + "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}' est défini en tant qu'accesseur dans la classe '{1}', mais il est remplacé ici dans '{2}' en tant que propriété d'instance.", + "_0_is_deprecated_6385": "'{0}' est déprécié.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' n'est pas une métapropriété valide pour le mot clé '{1}'. Est-ce qu'il ne s'agit pas plutôt de '{2}' ?", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}' n'est pas autorisé comme nom de paramètre.", + "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}' n'est pas autorisé en tant que nom de déclaration de variable.", + "_0_is_of_type_unknown_18046": "'{0}' est de type 'unknown'.", + "_0_is_possibly_null_18047": "'{0}' est peut-être 'null'.", + "_0_is_possibly_null_or_undefined_18049": "'{0}' est peut-être 'null' ou 'undefined'.", + "_0_is_possibly_undefined_18048": "'{0}' est peut-être 'non défini'.", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' est référencé directement ou indirectement dans sa propre expression de base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' est référencé directement ou indirectement dans sa propre annotation de type.", + "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783": "'{0}' est spécifié plusieurs fois. Cette utilisation va donc être remplacée.", + "_0_list_cannot_be_empty_1097": "La liste '{0}' ne peut pas être vide.", + "_0_modifier_already_seen_1030": "Modificateur '{0}' déjà rencontré.", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias_1274": "Le modificateur «{0}» ne peut apparaître que sur un paramètre de type d’une classe, d’une interface ou d’un alias de type", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class_1277": "Le modificateur « {0} » ne peut apparaître que sur un paramètre de type d’une fonction, d’une méthode ou d’une classe", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Le modificateur '{0}' ne peut pas apparaître sur une déclaration de constructeur.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Le modificateur '{0}' ne peut pas apparaître dans un élément de module ou d'espace de noms.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Le modificateur '{0}' ne peut pas apparaître dans un paramètre.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Le modificateur '{0}' ne peut pas apparaître dans un membre de type.", + "_0_modifier_cannot_appear_on_a_type_parameter_1273": "Le modificateur «{0}» ne peut pas apparaître sur un paramètre de type", + "_0_modifier_cannot_appear_on_a_using_declaration_1491": "Le modificateur « {0} » ne peut pas apparaître dans une déclaration « using ».", + "_0_modifier_cannot_appear_on_an_await_using_declaration_1495": "Le modificateur « {0} » ne peut pas apparaître dans une déclaration « await using ».", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Le modificateur '{0}' ne peut pas apparaître dans une signature d'index.", + "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031": "Le modificateur '{0}' ne peut pas apparaître sur les éléments de classe de ce genre.", + "_0_modifier_cannot_be_used_here_1042": "Impossible d'utiliser le modificateur '{0}' ici.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Impossible d'utiliser le modificateur '{0}' dans un contexte ambiant.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Impossible d'utiliser les modificateurs '{0}' et '{1}' ensemble.", + "_0_modifier_cannot_be_used_with_a_private_identifier_18019": "Le modificateur '{0}' ne peut pas être utilisé avec un identificateur privé.", + "_0_modifier_must_precede_1_modifier_1029": "Le modificateur '{0}' doit précéder le modificateur '{1}'.", + "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531": "« \\{0} » doit être suivi d’une expression de valeur de propriété Unicode entre accolades.", + "_0_needs_an_explicit_type_annotation_2782": "'{0}' a besoin d'une annotation de type explicite.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' référence uniquement un type mais s'utilise en tant qu'espace de noms ici.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' fait uniquement référence à un type mais s'utilise en tant que valeur ici.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690": "'{0}' fait uniquement référence à un type, mais il est utilisé ici en tant que valeur. Voulez-vous vraiment utiliser '{1} dans {0}' ?", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585": "'{0}' fait uniquement référence à un type, mais il est utilisé ici en tant que valeur. Devez-vous changer votre bibliothèque cible ? Essayez de remplacer l'option de compilateur 'lib' par es2015 ou une version ultérieure.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' fait référence à une variable globale UMD, mais le fichier actuel est un module. Ajoutez une importation à la place.", + "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749": "'{0}' fait référence à une valeur, mais il est utilisé ici en tant que type. Est-ce que vous avez voulu utiliser 'typeof {0}' ?", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1291": "« {0} » se résout en type et doit être marquée en tant que type uniquement dans ce fichier avant la réexportation lorsque « {1} » est activé. Envisagez d’utiliser « import type » où « {0} » est importé.", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1292": "« {0} » se résout en type et doit être marquée en tant que type uniquement dans ce fichier avant la réexportation lorsque « {1} » est activé. Envisagez d’utiliser « export type {{0} as default } ».", + "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimMo_1485": "« {0} » se résout en une déclaration de type uniquement et doit être importé en utilisant une importation de type uniquement quand « verbatimModuleSyntax » est activé.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1289": "« {0} » se résout en déclaration de type uniquement et doit être marquée en tant que type uniquement dans ce fichier avant la réexportation lorsque « {1} » est activé. Envisagez d’utiliser « import type » où « {0} » est importé.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1290": "« {0} » se résout en déclaration de type uniquement et doit être marquée en tant que type uniquement dans ce fichier avant la réexportation lorsque « {1} » est activé. Envisagez d’utiliser « export type {{0} as default } ».", + "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_1448": "« {0} » doit être résolu en déclaration de type unique et doit être réexporté en utilisant une réexportation de type unique lorsque l’option {1} est activée.", + "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258": "'{0}' doit être défini dans l'objet 'compilerOptions' du fichier de configuration json", + "_0_tag_already_specified_1223": "La balise '{0}' est déjà spécifiée.", + "_0_was_also_declared_here_6203": "'{0}' a également été déclaré ici.", + "_0_was_exported_here_1377": "'{0}' a été exporté ici.", + "_0_was_imported_here_1376": "'{0}' a été importé ici.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}', qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour '{1}'.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055": "'{0}', qui n'a pas d'annotation de type de retour, a implicitement le type de retour '{1}'.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Le modificateur 'abstract' peut apparaître uniquement dans une déclaration de classe, de méthode ou de propriété.", + "accessor_modifier_can_only_appear_on_a_property_declaration_1275": "Le modificateur 'accessor' ne peut apparaître que sur une déclaration de propriété.", + "and_here_6204": "et ici.", + "arguments_cannot_be_referenced_in_property_initializers_2815": "Les « arguments » ne peuvent pas être référencés dans les initialiseurs de propriété.", + "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476": "« auto » : traitez les fichiers avec des importations, des exportations, import.meta, jsx (avec jsx: react-jsx) ou un format esm (avec module : node16+) en tant que modules.", + "await_expression_cannot_be_used_inside_a_class_static_block_18037": "L’expression « await » à l’intérieur d’un bloc statique de classe.", + "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375": "Les expressions 'await' sont uniquement autorisées au niveau supérieur d'un fichier quand celui-ci est un module, mais le fichier actuel n'a pas d'importations ou d'exportations. Ajoutez un 'export {}' vide pour faire de ce fichier un module.", + "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308": "Les expressions 'await' sont autorisées uniquement dans les fonctions asynchrones et aux niveaux supérieurs des modules.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Impossible d'utiliser des expressions 'await' dans un initialiseur de paramètre.", + "await_has_no_effect_on_the_type_of_this_expression_80007": "'await' n'a aucun effet sur le type de cette expression.", + "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853": "Les instructions « await using » sont uniquement autorisées au niveau supérieur d’un fichier quand celui-ci est un module, mais le fichier actuel n’a aucune importation ou exportation. Envisagez d’ajouter un « export {} » vide pour faire de ce fichier un module.", + "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852": "Les expressions « await using » sont autorisées uniquement dans les fonctions asynchrones et aux niveaux supérieurs des modules.", + "await_using_statements_cannot_be_used_inside_a_class_static_block_18054": "Des instructions « await using » ne peuvent pas être utilisées à l’intérieur d’un bloc statique de classe.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "L'option 'baseUrl' a la valeur '{0}'. Utilisation de cette valeur pour la résolution du nom de module non relatif '{1}'.", + "c_must_be_followed_by_an_ASCII_letter_1512": "'\\c' doit être suivi d’une lettre ASCII.", + "can_only_be_used_at_the_start_of_a_file_18026": "'#!' peut uniquement être utilisé au début d'un fichier.", + "case_or_default_expected_1130": "'case' ou 'default' attendu.", + "catch_or_finally_expected_1472": "« Catch » ou « finally » attendu.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'initialiseur de membre enum 'const' donne une valeur non finie.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'initialiseur de membre enum 'const' donne une valeur non autorisée 'NaN'.", + "const_enum_member_initializers_must_be_constant_expressions_2474": "Les initialiseurs de membre enum const doivent être des expressions constantes.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Les enums 'const' ne peuvent être utilisés que dans les expressions d'accès à une propriété ou un index, ou dans la partie droite d'une déclaration d'importation, d'une assignation d'exportation ou d'une requête de type.", + "constructor_cannot_be_used_as_a_parameter_property_name_2398": "'constructor' ne peut pas être utilisé en tant que nom de propriété de paramètre.", + "constructor_is_a_reserved_word_18012": "'#constructor' est un mot réservé.", + "default_Colon_6903": "Par défaut :", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' ne peut pas être appelé dans un identificateur en mode strict.", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *' ne réexporte pas d'exportations par défaut.", + "export_can_only_be_used_in_TypeScript_files_8003": "'export =' peut uniquement être utilisé dans les fichiers TypeScript.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Impossible d'appliquer le modificateur 'export' aux modules ambients et aux augmentations de module, car ils sont toujours visibles.", + "extends_clause_already_seen_1172": "Clause 'extends' déjà rencontrée.", + "extends_clause_must_precede_implements_clause_1173": "La clause 'extends' doit précéder la clause 'implements'.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "La clause 'extends' de la classe exportée '{0}' comporte ou utilise le nom privé '{1}'.", + "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021": "La clause 'extends' de la classe exportée comporte ou utilise le nom privé '{0}'.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "La clause 'extends' de l'interface exportée '{0}' comporte ou utilise le nom privé '{1}'.", + "false_unless_composite_is_set_6906": "« false », sauf si « composite » est défini", + "false_unless_strict_is_set_6905": "« false », sauf si « strict » est défini", + "file_6025": "fichier", + "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431": "Les boucles 'for await' sont uniquement autorisées au niveau supérieur d'un fichier quand celui-ci est un module, mais le fichier actuel n'a aucune importation ou exportation. Ajoutez un 'export {}' vide pour faire de ce fichier un module.", + "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103": "Les boucles 'for await' sont autorisées uniquement dans les fonctions asynchrones et aux niveaux supérieurs des modules.", + "for_await_loops_cannot_be_used_inside_a_class_static_block_18038": "Les boucles « for await » ne peuvent pas être utilisées à l’intérieur d’un bloc statique de classe.", + "get_and_set_accessors_cannot_declare_this_parameters_2784": "Les accesseurs 'get' et 'set' ne peuvent pas déclarer les paramètres 'this'.", + "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908": "«[]» si « files » est spécifié, sinon « [\"**/*\"]5D; »", + "implements_clause_already_seen_1175": "Clause 'implements' déjà rencontrée.", + "implements_clauses_can_only_be_used_in_TypeScript_files_8005": "Les clauses 'implements' peuvent uniquement être utilisées dans les fichiers TypeScript.", + "import_can_only_be_used_in_TypeScript_files_8002": "'import ... =' peut uniquement être utilisé dans les fichiers TypeScript.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Les déclarations 'infer' sont uniquement autorisées dans la clause 'extends' d’un type conditionnel.", + "k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets_1510": "« \\k » doit être suivi d’un nom de groupe de capture placé entre crochets angulaires.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' ne peut pas être utilisé comme nom dans les déclarations 'let' ou 'const'.", + "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010": "module === « AMD » ou « UMD » ou « System » ou « ES6 », puis « Classic », sinon « Node »", + "module_system_or_esModuleInterop_6904": "module === « system » ou esModuleInterop", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "L'expression 'new', dont la cible ne dispose pas d'une signature de construction, possède implicitement un type 'any'.", + "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907": "« [ « node_modules », « bower_components », « jspm_packages »] », plus la valeur de « outDir » si elle est spécifiée.", + "one_of_Colon_6900": "L'un de :", + "one_or_more_Colon_6901": "un ou plusieurs :", + "options_6024": "options", + "or_JSX_element_expected_1145": "'{' ou élément JSX attendu.", + "or_expected_1144": "'{' ou ';' attendu.", + "package_json_does_not_have_a_0_field_6100": "'package.json' n'a aucun champ '{0}'.", + "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json' n'a aucune entrée 'typesVersions' qui correspond à la version '{0}'.", + "package_json_had_a_falsy_0_field_6220": "'package.json' a un champ '{0}' erroné.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' a un champ '{0}' '{1}' qui fait référence à '{2}'.", + "package_json_has_a_peerDependencies_field_6281": "« package.json » a un champ « peerDependencies ».", + "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209": "'package.json' a une entrée 'typesVersions' '{0}' qui n'est pas une plage SemVer valide.", + "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208": "'package.json' a une entrée 'typesVersions' '{0}' qui correspond à la version de compilateur '{1}'. Recherche d'un modèle correspondant au nom de module '{2}'.", + "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206": "'package.json' a un champ 'typesVersions' avec des mappages de chemins spécifiques à la version.", + "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274": "L’étendue package.json « {0} » mappe explicitement le spécificateur « {1} » sur la valeur null.", + "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275": "L’étendue package.json « {0} » a un type non valide pour la cible du spécificateur « {1} »", + "package_json_scope_0_has_no_imports_defined_6273": "L’étendue package.json « {0} » ne comporte aucune importation définie.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "L'option 'paths' est spécifiée. Recherche d'un modèle correspondant au nom de module '{0}'.", + "q_is_only_available_inside_character_class_1511": "« \\q » n’est disponible que dans la classe de caractères.", + "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521": "« \\q » doit être suivi d’alternatives de chaîne entre accolades.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Le modificateur 'readonly' peut apparaître uniquement dans une déclaration de propriété ou une signature d'index.", + "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Le modificateur de type 'readonly' est uniquement autorisé sur les types littéraux de tableau et de tuple.", + "require_call_may_be_converted_to_an_import_80005": "L'appel de 'require' peut être converti en import.", + "resolution_mode_can_only_be_set_for_type_only_imports_1454": "« mode résolution » ne peut être défini que pour les importations de type uniquement.", + "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "« mode résolution » est la seule clé valide pour les assertions d’importation de type.", + "resolution_mode_is_the_only_valid_key_for_type_import_attributes_1463": "« resolution-mode » est la seule clé valide pour les attributs d’importation de type.", + "resolution_mode_should_be_either_require_or_import_1453": "'resolution-mode' doit être 'require' ou 'import'.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'option 'rootDirs' est définie. Utilisation de celle-ci pour la résolution du nom de module relatif '{0}'.", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' ne peut être référencé que dans une classe dérivée.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' ne peut être référencé que dans les membres des classes dérivées ou les expressions littérales d'objet.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Impossible de référencer 'super' dans un nom de propriété calculée.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Impossible de référencer 'super' dans des arguments de constructeur.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' est uniquement autorisé dans les membres des expressions littérales d'objet quand l'option 'target' a la valeur 'ES2015' ou une valeur supérieure.", + "super_may_not_use_type_arguments_2754": "'super' ne peut pas utiliser d'arguments de type.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "'super' doit être appelé avant d'accéder à une propriété de 'super' dans le constructeur d'une classe dérivée.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "'super' doit être appelé avant d'accéder à 'this' dans le constructeur d'une classe dérivée.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' doit être suivi d'une liste d'arguments ou d'un accès au membre.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "L'accès aux propriétés 'super' est autorisé uniquement dans un constructeur, une fonction membre ou un accesseur membre d'une classe dérivée.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Impossible de référencer 'this' dans un nom de propriété calculée.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Impossible de référencer 'this' dans le corps d'un module ou d'un espace de noms.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Impossible de référencer 'this' dans un initialiseur de propriété statique.", + "this_cannot_be_referenced_in_current_location_2332": "Impossible de référencer 'this' dans l'emplacement actuel.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' possède implicitement le type 'any', car il n'a pas d'annotation de type.", + "true_for_ES2022_and_above_including_ESNext_6930": "'true’ pour ES2022 et versions ultérieures, y compris ESNext.", + "true_if_composite_false_otherwise_6909": "« true » si « composite », « false » sinon", + "true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false_6411": "« true » quand « moduleResolution » a la valeur « node16 », « nodenext » ou « bundler » ; sinon « false ».", + "tsc_Colon_The_TypeScript_Compiler_6922": "tsc : compilateur TypeScript", + "type_Colon_6902": "type :", + "unique_symbol_types_are_not_allowed_here_1335": "Les types 'unique symbol' ne sont pas autorisés ici.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Les types 'unique symbol' sont uniquement autorisés sur les variables d'une déclaration de variable.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Les types 'unique symbol' ne peuvent pas être utilisés dans une déclaration de variable avec un nom de liaison.", + "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347": "La directive 'use strict' ne peut pas être utilisée avec une liste de paramètres non simple.", + "use_strict_directive_used_here_1349": "directive 'use strict' utilisée ici.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Les instructions 'with' ne sont pas autorisées dans un bloc de fonctions async.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Les instructions 'with' ne sont pas autorisées en mode strict.", + "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057": "L'expression 'yield' génère implicitement un type 'any', car le générateur qui la contient n'a pas d'annotation de type de retour.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Impossible d'utiliser des expressions 'yield' dans un initialiseur de paramètre." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/it/diagnosticMessages.generated.json b/node_modules/typescript/lib/it/diagnosticMessages.generated.json new file mode 100644 index 00000000..8c2621aa --- /dev/null +++ b/node_modules/typescript/lib/it/diagnosticMessages.generated.json @@ -0,0 +1,2105 @@ +{ + "ALL_COMPILER_OPTIONS_6917": "TUTTE LE OPZIONI DEL COMPILATORE", + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "Non è possibile usare un modificatore '{0}' con una dichiarazione di importazione.", + "A_0_parameter_must_be_the_first_parameter_2680": "Il primo parametro deve essere '{0}'.", + "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039": "Un tag '@template' di JSDoc non può seguire un tag '@typedef', '@callback' o '@overload'", + "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033": "Un commento '@typedef' di JSDoc non può contenere più tag '@type'.", + "A_bigint_literal_cannot_be_used_as_a_property_name_1539": "Non è possibile usare un valore letterale 'bigint' come nome per la proprietà.", + "A_bigint_literal_cannot_use_exponential_notation_1352": "Un valore letterale bigint non può usare la notazione esponenziale.", + "A_bigint_literal_must_be_an_integer_1353": "Un valore letterale bigint deve essere un numero intero.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "Un parametro del criterio di binding non può essere facoltativo in una firma di implementazione.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "Un'istruzione 'break' può essere usata solo all'interno di un'iterazione di inclusione o di un'istruzione switch.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "Un'istruzione 'break' può solo passare a un'etichetta di un'istruzione di inclusione.", + "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522": "Una classe di caratteri non deve contenere un segno di punteggiatura doppio riservato. La barra rovesciata stava per un carattere escape?", + "A_character_class_range_must_not_be_bounded_by_another_character_class_1516": "Un intervallo di classi di caratteri non deve essere delimitato da un'altra classe di caratteri.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "Una classe può implementare solo un identificatore/nome qualificato con argomenti tipo facoltativi.", + "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422": "Una classe può implementare solo un tipo di oggetto o un'intersezione di tipi di oggetto con membri noti in modo statico.", + "A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values_2863": "Una classe non può estendere un elemento di tipo primitivo come '{0}'. Le classi possono estendere solo valori costruibili.", + "A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types_2864": "Una classe non può implementare un tipo primitivo come '{0}'. Può implementare solo altri tipi di oggetto denominati.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "È necessario assegnare un nome a una dichiarazione di classe senza modificatore 'default'.", + "A_class_member_cannot_have_the_0_keyword_1248": "Un membro di classe non può contenere la parola chiave '{0}'.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Non sono consentite espressioni con virgole in un nome di proprietà calcolato.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nome di proprietà calcolato non può fare riferimento a un parametro di tipo dal tipo che lo contiene.", + "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166": "Un nome di proprietà calcolato in una dichiarazione di proprietà di classe deve avere un tipo di valore letterale semplice o un tipo 'unique symbol'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nome di proprietà calcolato in un overload di metodo deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nome di proprietà calcolato in un valore letterale di tipo deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nome di proprietà calcolato in un contesto di ambiente deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nome di proprietà calcolato in un'interfaccia deve fare riferimento a un'espressione il cui tipo è un tipo di valore letterale o un tipo 'unique symbol'.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nome di proprietà calcolato deve essere di tipo 'string', 'number', 'symbol' o 'any'.", + "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355": "Le asserzioni 'const' possono essere applicate solo a riferimenti a membri di enumerazione oppure a valori letterali stringa, numerico, booleano, di oggetto o matrice.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "È possibile accedere a un membro di enumerazione const solo tramite un valore letterale stringa.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254": "Un inizializzatore 'const' in un contesto di ambiente deve essere un valore letterale numerico o stringa oppure un riferimento a un'enumerazione di valori letterali.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Un costruttore non può contenere una chiamata 'super' quando la relativa classe estende 'null'.", + "A_constructor_cannot_have_a_this_parameter_2681": "Un costruttore non può contenere un parametro 'this'.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Un'istruzione 'continue' può essere usata solo all'interno di un'istruzione di iterazione di inclusione.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Un'istruzione 'continue' può solo passare a un'etichetta di un'istruzione di iterazione di inclusione.", + "A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_f_2846": "Non è possibile importare un file di dichiarazione senza 'import type'. Si intendeva importare un file di implementazione '{0}'?", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Non è possibile usare un modificatore 'declare' in un contesto già di ambiente.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Un elemento Decorator può solo decorare un'implementazione del metodo e non un overload.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Una clausola 'default' non può essere specificata più volte in un'istruzione 'switch'.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "È possibile usare un'esportazione predefinita solo in un modulo di tipo ECMAScript.", + "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258": "Un'esportazione predefinita deve essere al livello principale di una dichiarazione di file o di modulo.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "In questo contesto non sono consentite asserzioni di assegnazione definite '!'.", + "A_destructuring_declaration_must_have_an_initializer_1182": "Una dichiarazione di destrutturazione deve includere un inizializzatore.", + "A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_t_2712": "Con una chiamata di importazione dinamica in ES5 è necessario il costruttore 'Promise'. Assicurarsi che sia presente una dichiarazione per il costruttore 'Promise' oppure includere 'ES2015' nell'opzione '--lib'.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Una chiamata di importazione dinamica restituisce un costruttore 'Promise'. Assicurarsi che sia presente una dichiarazione per 'Promise' oppure includere 'ES2015' nell'opzione '--lib'.", + "A_file_cannot_have_a_reference_to_itself_1006": "Un file non può contenere un riferimento a se stesso.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "Una funzione che restituisce 'never' non può includere un punto finale raggiungibile.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "Una funzione chiamata con la parola chiave 'new' non può contenere un tipo 'this' con valore 'void'.", + "A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value_2355": "Una funzione il cui tipo dichiarato non è 'undefined', 'void' o 'any' deve restituire un valore.", + "A_generator_cannot_have_a_void_type_annotation_2505": "Un generatore non può contenere un'annotazione di tipo 'void'.", + "A_get_accessor_cannot_have_parameters_1054": "Una funzione di accesso 'get' non può contenere parametri.", + "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808": "Una funzione di accesso get deve essere accessibile almeno come setter", + "A_get_accessor_must_return_a_value_2378": "Una funzione di accesso 'get' deve restituire un valore.", + "A_label_is_not_allowed_here_1344": "In questo punto non sono consentite etichette.", + "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Un elemento tupla con etichetta è dichiarato come facoltativo con un punto interrogativo dopo il nome e prima dei due punti, anziché dopo il tipo.", + "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Un elemento tupla con etichetta è dichiarato come inattivo con '...' prima del nome, anziché prima del tipo.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Un tipo di cui è stato eseguito il mapping non può dichiarare proprietà o metodi.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inizializzatore di membro in una dichiarazione di enumerazione non può fare riferimento a membri dichiarati successivamente, inclusi quelli definiti in altre enumerazioni.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una classe mixin deve includere un costruttore con un unico parametro REST di tipo 'any[]'.", + "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Una classe mixin estesa da una variabile di tipo contenente una firma del costrutto astratta deve essere dichiarata anche come 'abstract'.", + "A_module_cannot_have_multiple_default_exports_2528": "Un modulo non può includere più esportazioni predefinite.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una dichiarazione di spazio dei nomi non può essere presente in un file diverso rispetto a una classe o funzione con cui è stato eseguito il merge.", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una dichiarazione di spazio dei nomi non può essere specificata prima di una classe o funzione con cui è stato eseguito il merge.", + "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235": "Una dichiarazione di spazio dei nomi è consentita solo al livello superiore di uno spazio dei nomi o di un modulo.", + "A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_key_1540": "Una dichiarazione 'namespace' non deve essere dichiarata usando la parola chiave 'module'. Usare invece la parola chiave 'namespace'.", + "A_non_dry_build_would_build_project_0_6357": "Se si esegue una compilazione senza flag -dry, verrà compilato il progetto '{0}'", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Se si esegue una compilazione senza flag -dry, i file seguenti verranno eliminati: {0}", + "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374": "Se si esegue una compilazione non di prova, i timestamp dell'output del progetto '{0}' verranno aggiornati", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inizializzatore di parametro è consentito solo in un'implementazione di funzione o costruttore.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Non è possibile dichiarare una proprietà di parametro usando un parametro REST.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una proprietà di parametro è consentita solo in un'implementazione di costruttore.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Non è possibile dichiarare una proprietà di parametro con un modello di associazione.", + "A_promise_must_have_a_then_method_1059": "Una promessa deve contenere un metodo 'then'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Una proprietà di una classe il cui tipo è un tipo 'unique symbol' deve essere sia 'static' che 'readonly'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Una proprietà di un'interfaccia o di un valore letterale di tipo il cui tipo è un tipo 'unique symbol' deve essere 'readonly'.", + "A_required_element_cannot_follow_an_optional_element_1257": "Non è possibile specificare un elemento obbligatorio dopo un elemento facoltativo.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un parametro obbligatorio non può seguire un parametro facoltativo.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un elemento rest non può contenere un criterio di binding.", + "A_rest_element_cannot_follow_another_rest_element_1265": "Non è possibile specificare un elemento REST dopo un altro elemento REST.", + "A_rest_element_cannot_have_a_property_name_2566": "Un elemento rest non può contenere un nome proprietà.", + "A_rest_element_cannot_have_an_initializer_1186": "Un elemento rest non può includere un inizializzatore.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Un elemento rest deve essere l'ultimo di un criterio di destrutturazione.", + "A_rest_element_type_must_be_an_array_type_2574": "Un tipo di elemento rest deve essere un tipo di matrice.", + "A_rest_parameter_cannot_be_optional_1047": "Un parametro rest non può essere facoltativo.", + "A_rest_parameter_cannot_have_an_initializer_1048": "Un parametro rest non può contenere un inizializzatore.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "Un parametro rest deve essere l'ultimo di un elenco di parametri.", + "A_rest_parameter_must_be_of_an_array_type_2370": "Un parametro rest deve essere di un tipo di matrice.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Un modello di associazione o un parametro REST non può contenere una virgola finale.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "Un'istruzione 'return' può essere usata solo all'interno di un corpo di funzione.", + "A_return_statement_cannot_be_used_inside_a_class_static_block_18041": "Non è possibile usare un'istruzione 'return' all'interno di un blocco statico di classe.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "Serie di voci che ripetono il mapping delle importazioni a percorsi di ricerca relativi al valore di 'baseUrl'.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "Una funzione di accesso 'set' non può contenere un'annotazione di tipo restituito.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "Una funzione di accesso 'set' non può contenere un parametro facoltativo.", + "A_set_accessor_cannot_have_rest_parameter_1053": "Una funzione di accesso 'set' non può contenere il parametro rest.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "Una funzione di accesso 'set' deve contenere un solo parametro.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "Un parametro della funzione di accesso 'set' non può contenere un inizializzatore.", + "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556": "Un argomento spread deve avere un tipo di tupla o essere passato a un parametro rest.", + "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401": "Una chiamata 'super' deve essere un'istruzione a livello radice all'interno di un costruttore di una classe derivata che contiene proprietà inizializzate, proprietà dei parametri o identificatori privati.", + "A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_2376": "Una chiamata 'super' deve essere la prima istruzione del costruttore a fare riferimento a 'super' o 'this' quando una classe derivata contiene proprietà inizializzate, proprietà di parametri o identificatori privati.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "Un guard di tipo basato su 'this' non è compatibile con uno basato su parametri.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Un tipo 'this' è disponibile solo in un membro non statico di una classe o di interfaccia.", + "A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimM_1287": "Non è possibile usare un modificatore 'export' di primo livello nelle dichiarazioni di valori in un modulo CommonJS quando è abilitato 'verbatimModuleSyntax'.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Un file 'tsconfig.json' è già definito in: '{0}'.", + "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Un membro di tupla non può essere sia facoltativo che inattivo.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Un tipo di tupla non può essere indicizzato con un valore negativo.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Nella parte sinistra di un'espressione di elevamento a potenza non è consentita un'espressione di asserzione tipi. Provare a racchiudere l'espressione tra parentesi.", + "A_type_literal_property_cannot_have_an_initializer_1247": "Una proprietà di valore letterale di tipo non può contenere un inizializzatore.", + "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Un'importazione solo di tipi può specificare un'importazione predefinita o binding denominati, ma non entrambi.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "Un predicato di tipo non può fare riferimento a un parametro rest.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un predicato di tipo non può fare riferimento all'elemento '{0}' in un criterio di binding.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Un predicato di tipo è consentito solo nella posizione del tipo restituito per le funzioni e i metodi.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Il tipo di un predicato di tipo deve essere assegnabile al tipo del relativo parametro.", + "A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_w_1272": "Un tipo a cui viene fatto riferimento in una firma decorata deve essere importato con 'import type' o un'importazione dello spazio dei nomi quando sono abilitati 'isolatedModules' e 'emitDecoratorMetadata'.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Una variabile il cui tipo è un tipo 'unique symbol' deve essere 'const'.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Un'espressione 'yield' è consentita solo nel corpo di un generatore.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Non è possibile accedere al metodo astratto '{0}' nella classe '{1}' tramite l'espressione super.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "I metodi astratti possono essere inclusi solo in una classe astratta.", + "Abstract_properties_can_only_appear_within_an_abstract_class_1253": "Le proprietà astratte possono essere incluse solo in una classe astratta.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Non è possibile accedere alla proprietà astratta '{0}' nella classe '{1}' nel costruttore.", + "Accessibility_modifier_already_seen_1028": "Il modificatore di accessibilità è già presente.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Le funzioni di accesso sono disponibili solo se destinate a ECMAScript 5 e versioni successive.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "Le funzioni di accesso devono essere tutte astratte o tutte non astratte.", + "Add_0_to_unresolved_variable_90008": "Aggiungere '{0}.' alla variabile non risolta", + "Add_a_return_statement_95111": "Aggiungere un'istruzione return", + "Add_a_return_type_to_the_function_declaration_9031": "Aggiungere un elemento di tipo restituito alla dichiarazione di funzione.", + "Add_a_return_type_to_the_function_expression_9030": "Aggiungere un elemento di tipo restituito all'espressione della funzione.", + "Add_a_return_type_to_the_get_accessor_declaration_9032": "Aggiungere un tipo restituito alla dichiarazione della funzione di accesso get.", + "Add_a_return_type_to_the_method_9034": "Aggiungere un tipo restituito al metodo", + "Add_a_type_annotation_to_the_parameter_0_9028": "Aggiungere un'annotazione di tipo al parametro {0}.", + "Add_a_type_annotation_to_the_property_0_9029": "Aggiungere un'annotazione di tipo alla proprietà {0}.", + "Add_a_type_annotation_to_the_variable_0_9027": "Aggiungere un'annotazione di tipo alla variabile {0}.", + "Add_a_type_to_parameter_of_the_set_accessor_declaration_9033": "Aggiunge un tipo al parametro della dichiarazione della funzione di accesso set.", + "Add_all_missing_async_modifiers_95041": "Aggiungere tutti i modificatori 'async' mancanti", + "Add_all_missing_attributes_95168": "Aggiungi tutti gli attributi mancanti", + "Add_all_missing_call_parentheses_95068": "Aggiungere tutte le parentesi mancanti nelle chiamate", + "Add_all_missing_function_declarations_95157": "Aggiungere tutte le dichiarazioni di funzione mancanti", + "Add_all_missing_imports_95064": "Aggiungere tutte le importazioni mancanti", + "Add_all_missing_members_95022": "Aggiungere tutti i membri mancanti", + "Add_all_missing_override_modifiers_95162": "Aggiungere tutti i modificatori 'override' mancanti", + "Add_all_missing_parameters_95190": "Aggiungere tutti i parametri mancanti", + "Add_all_missing_properties_95166": "Aggiunge tutte le proprietà mancanti", + "Add_all_missing_return_statement_95114": "Aggiungere tutte le istruzioni return mancanti", + "Add_all_missing_super_calls_95039": "Aggiungere tutte le chiamate a super mancanti", + "Add_all_missing_type_annotations_90067": "Aggiungere tutte le annotazioni di tipo mancante", + "Add_all_optional_parameters_95193": "Aggiungere tutti i parametri facoltativi", + "Add_annotation_of_type_0_90062": "Aggiungere annotazione di tipo '{0}'", + "Add_async_modifier_to_containing_function_90029": "Aggiungere il modificatore async alla funzione contenitore", + "Add_await_95083": "Aggiungere 'await'", + "Add_await_to_initializer_for_0_95084": "Aggiungere 'await' all'inizializzatore per '{0}'", + "Add_await_to_initializers_95089": "Aggiungere 'await' agli inizializzatori", + "Add_braces_to_arrow_function_95059": "Aggiungere le parentesi graffe alla funzione arrow", + "Add_const_to_all_unresolved_variables_95082": "Aggiungere 'const' a tutte le variabili non risolte", + "Add_const_to_unresolved_variable_95081": "Aggiungere 'const' alla variabile non risolta", + "Add_definite_assignment_assertion_to_property_0_95020": "Aggiungere l'asserzione di assegnazione definita alla proprietà '{0}'", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Aggiungere le asserzioni di assegnazione definite a tutte le proprietà non inizializzate", + "Add_export_to_make_this_file_into_a_module_95097": "Aggiungere 'export {}' per trasformare questo file in un modulo", + "Add_extends_constraint_2211": "Aggiungere il vincolo 'extends'.", + "Add_extends_constraint_to_all_type_parameters_2212": "Aggiungere il vincolo `extends` a tutti i parametri di tipo", + "Add_import_from_0_90057": "Aggiungere l'importazione da \"{0}\"", + "Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'", + "Add_initializer_to_property_0_95019": "Aggiungere l'inizializzatore alla proprietà '{0}'", + "Add_initializers_to_all_uninitialized_properties_95027": "Aggiungere gli inizializzatori a tutte le proprietà non inizializzate", + "Add_missing_attributes_95167": "Aggiungi attributi mancanti", + "Add_missing_call_parentheses_95067": "Aggiungere le parentesi mancanti nelle chiamate", + "Add_missing_comma_for_object_member_completion_0_95187": "Aggiungere la virgola mancante per il completamento dei membri dell'oggetto '{0}'.", + "Add_missing_enum_member_0_95063": "Aggiungere il membro di enumerazione mancante '{0}'", + "Add_missing_function_declaration_0_95156": "Aggiungere la dichiarazione di funzione mancante '{0}'", + "Add_missing_new_operator_to_all_calls_95072": "Aggiungere l'operatore mancante 'new' a tutte le chiamate", + "Add_missing_new_operator_to_call_95071": "Aggiungere l'operatore mancante 'new' alla chiamata", + "Add_missing_parameter_to_0_95188": "Aggiungere il parametro mancante a '{0}'", + "Add_missing_parameters_to_0_95189": "Aggiungere i parametri mancanti a '{0}'", + "Add_missing_properties_95165": "Aggiunge le proprietà mancanti", + "Add_missing_super_call_90001": "Aggiungere la chiamata mancante a 'super()'", + "Add_missing_typeof_95052": "Aggiungere l'elemento 'typeof' mancante", + "Add_names_to_all_parameters_without_names_95073": "Aggiungere i nomi a tutti i parametri senza nomi", + "Add_optional_parameter_to_0_95191": "Aggiungere i parametri facoltativi a '{0}'", + "Add_optional_parameters_to_0_95192": "Aggiungi i parametri facoltativi a '{0}'", + "Add_or_remove_braces_in_an_arrow_function_95058": "Aggiungere o rimuovere le parentesi graffe in una funzione arrow", + "Add_override_modifier_95160": "Aggiungere il modificatore 'override'", + "Add_parameter_name_90034": "Aggiungere il nome del parametro", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Aggiungere il qualificatore a tutte le variabili non risolte corrispondenti a un nome di membro", + "Add_resolution_mode_import_attribute_95196": "Aggiungi attributo di importazione 'resolution-mode'", + "Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it_95197": "Aggiungi l'attributo di importazione 'resolution-mode' a tutte le importazioni solo tipo che lo richiedono", + "Add_return_type_0_90063": "Aggiungere '{0}' del tipo restituito", + "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035": "Aggiungere soddisfa e un'asserzione di tipo a questa espressione (soddisfa T come T) per rendere il tipo esplicito.", + "Add_satisfies_and_an_inline_type_assertion_with_0_90068": "Aggiungere soddisfa e un'asserzione di tipo inline con '{0}'", + "Add_to_all_uncalled_decorators_95044": "Aggiungere '()' a tutti gli elementi Decorator non chiamati", + "Add_ts_ignore_to_all_error_messages_95042": "Aggiungere '@ts-ignore' a tutti i messaggi di errore", + "Add_undefined_to_a_type_when_accessed_using_an_index_6674": "Aggiunge 'undefined' a un tipo quando l'accesso viene eseguito tramite un indice.", + "Add_undefined_to_optional_property_type_95169": "Aggiungi 'undefined' al tipo di proprietà facoltativo", + "Add_undefined_type_to_all_uninitialized_properties_95029": "Aggiungere il tipo non definito a tutte le proprietà non inizializzate", + "Add_undefined_type_to_property_0_95018": "Aggiungere il tipo 'undefined' alla proprietà '{0}'", + "Add_unknown_conversion_for_non_overlapping_types_95069": "Aggiungere la conversione 'unknown' per i tipi non sovrapposti", + "Add_unknown_to_all_conversions_of_non_overlapping_types_95070": "Aggiungere 'unknown' a tutte le conversioni di tipi non sovrapposti", + "Add_void_to_Promise_resolved_without_a_value_95143": "Aggiungere 'void' all'elemento Promise risolto senza un valore", + "Add_void_to_all_Promises_resolved_without_a_value_95144": "Aggiungere 'void' a tutti gli elementi Promise risolti senza un valore", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Aggiungere un file tsconfig.json per organizzare più facilmente progetti che contengono sia file TypeScript che JavaScript. Per altre informazioni, vedere https://aka.ms/tsconfig.", + "All_declarations_of_0_must_have_identical_constraints_2838": "Tutte le dichiarazioni di '{0}' devono avere vincoli identici.", + "All_declarations_of_0_must_have_identical_modifiers_2687": "Tutte le dichiarazioni di '{0}' devono contenere modificatori identici.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tutte le dichiarazioni di '{0}' devono contenere parametri di tipo identici.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Tutte le dichiarazioni di un metodo astratto devono essere consecutive.", + "All_destructured_elements_are_unused_6198": "Tutti gli elementi destrutturati sono inutilizzati.", + "All_imports_in_import_declaration_are_unused_6192": "Tutte le importazioni nella dichiarazione di importazione sono inutilizzate.", + "All_type_parameters_are_unused_6205": "Tutti i parametri di tipo sono inutilizzati.", + "All_variables_are_unused_6199": "Tutte le variabili sono inutilizzate.", + "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600": "Consente l'uso di file JavaScript nel programma. Usare l'opzione 'checkJS' per ottenere gli errori da questi file.", + "Allow_accessing_UMD_globals_from_modules_6602": "Consentire l'accesso alle istruzioni globali UMD dai moduli.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Consente di eseguire importazioni predefinite da moduli senza esportazione predefinita. Non influisce sulla creazione del codice ma solo sul controllo dei tipi.", + "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601": "Consente 'import x from y' quando un modulo non contiene un'esportazione predefinita.", + "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639": "Consente di eseguire una volta per progetto l'importazione di funzioni helper da tslib, invece di includerle per ogni file.", + "Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noE_6407": "Consentire alle importazioni di includere le estensioni di file TypeScript. Richiede l'impostazione di '--moduleResolution bundler' e '--noEmit' o '--emitDeclarationOnly'.", + "Allow_javascript_files_to_be_compiled_6102": "Consente la compilazione di file JavaScript.", + "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691": "Consente che più cartelle vengano considerate come una sola durante la risoluzione dei moduli.", + "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261": "Il nome file già incluso '{0}' differisce da quello '{1}' solo per l'uso di maiuscole/minuscole.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Non è possibile specificare il nome di modulo relativo nella dichiarazione di modulo di ambiente.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "I moduli di ambiente non possono essere annidati in altri moduli o spazi dei nomi.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Un modulo AMD non può includere più assegnazioni di nome.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "Una funzione di accesso astratta non può contenere un'implementazione.", + "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010": "Non è possibile usare un modificatore di accessibilità con un identificatore privato.", + "An_accessor_cannot_have_type_parameters_1094": "Una funzione di accesso non può contenere parametri di tipo.", + "An_accessor_property_cannot_be_declared_optional_1276": "Una proprietà 'accessor' non può essere dichiarata facoltativa.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Una dichiarazione di modulo di ambiente è consentita solo al primo livello in un file.", + "An_argument_for_0_was_not_provided_6210": "Non è stato specificato alcun argomento per '{0}'.", + "An_argument_matching_this_binding_pattern_was_not_provided_6211": "Non è stato specificato alcun argomento corrispondente a questo modello di associazione.", + "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356": "Un operando aritmetico deve essere di tipo 'any', 'number', 'bigint' o un tipo enumerazione.", + "An_arrow_function_cannot_have_a_this_parameter_2730": "Una funzione arrow non può contenere un parametro 'this'.", + "An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_2705": "Con una funzione o un metodo asincrono in ES5 è necessario il costruttore 'Promise'. Assicurarsi che sia presente una dichiarazione per il costruttore 'Promise' oppure includere 'ES2015' nell'opzione '--lib'.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Un metodo o una funzione asincrona deve restituire un costruttore 'Promise'. Assicurarsi che sia presente una dichiarazione per 'Promise' oppure includere 'ES2015' nell'opzione '--lib'.", + "An_async_iterator_must_have_a_next_method_2519": "Un iteratore asincrono deve contenere un metodo 'next()'.", + "An_element_access_expression_should_take_an_argument_1011": "Un'espressione di accesso a elementi deve accettare un argomento.", + "An_enum_member_cannot_be_named_with_a_private_identifier_18024": "Non è possibile assegnare un nome con un identificatore privato a un membro di enumerazione.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Il nome di un membro di enumerazione non può essere numerico.", + "An_enum_member_name_must_be_followed_by_a_or_1357": "Il nome di un membro di enumerazione deve essere seguito da ',', '=' o '}'.", + "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928": "Versione espansa di queste informazioni, che mostra tutte le opzioni possibili del compilatore", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Non è possibile usare un'assegnazione di esportazione in un modulo con altri elementi esportati.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Non è possibile usare un'assegnazione di esportazione in uno spazio dei nomi.", + "An_export_assignment_cannot_have_modifiers_1120": "Un'assegnazione di esportazione non può contenere modificatori.", + "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231": "Un'assegnazione di esportazione deve essere al primo livello di una dichiarazione di file o di modulo.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474": "Una dichiarazione di esportazione può essere usata solo al livello superiore di un modulo.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233": "Una dichiarazione di esportazione può essere usata solo al livello superiore di uno spazio dei nomi o di un modulo.", + "An_export_declaration_cannot_have_modifiers_1193": "Una dichiarazione di esportazione non può contenere modificatori.", + "An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolve_1283": "Quando 'verbatimModuleSyntax' è abilitato, la dichiarazione 'export =' deve fare riferimento a un valore reale, ma '{0}' viene risolto in una dichiarazione type-only.", + "An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers__1282": "Quando 'verbatimModuleSyntax' è abilitato, la dichiarazione 'export =' deve fare riferimento a un valore, ma '{0}' fa riferimento solo a un tipo.", + "An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_1285": "Quando 'verbatimModuleSyntax' è abilitato, 'export default' deve fare riferimento a un valore reale, ma '{0}' viene risolto in una dichiarazione type-only.", + "An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_1284": "Quando 'verbatimModuleSyntax' è abilitato, 'export default' deve fare riferimento a un valore, ma '{0}' fa riferimento solo a un tipo.", + "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345": "Non è possibile testare la veridicità di un'espressione di tipo 'void'.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Un valore di escape Unicode avanzato deve essere compreso tra 0x0 e 0x10FFFF inclusi.", + "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351": "Non è possibile specificare un identificatore o una parola chiave subito dopo un valore letterale numerico.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Non è possibile dichiarare un'implementazione in contesti di ambiente.", + "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Un alias di importazione non può fare riferimento a una dichiarazione esportata con 'export type'.", + "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Un alias di importazione non può fare riferimento a una dichiarazione importata con 'import type'.", + "An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabl_1288": "Un alias di importazione non può essere risolto in una dichiarazione type o type-only quando è abilitato 'verbatimModuleSyntax'.", + "An_import_alias_cannot_use_import_type_1392": "Un alias di importazione non può usare 'import type'", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473": "Una dichiarazione di importazione può essere usata solo al livello superiore di un modulo.", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232": "Una dichiarazione di importazione può essere usata solo al livello superiore di uno spazio dei nomi o di un modulo.", + "An_import_declaration_cannot_have_modifiers_1191": "Una dichiarazione di importazione non può contenere modificatori.", + "An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled_5097": "Un percorso di importazione può terminare con un'estensione '{0}' solo quando 'allowImportingTsExtensions' è abilitato.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "Una firma dell'indice non può contenere un parametro rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Una firma dell'indice non può contenere una virgola finale.", + "An_index_signature_must_have_a_type_annotation_1021": "Una firma dell'indice deve contenere un'annotazione di tipo.", + "An_index_signature_must_have_exactly_one_parameter_1096": "Una firma dell'indice deve contenere un solo parametro.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un parametro della firma dell'indice non può contenere un punto interrogativo.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parametro della firma dell'indice non può contenere un modificatore di accessibilità.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parametro della firma dell'indice non può contenere un inizializzatore.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parametro della firma dell'indice deve contenere un'annotazione di tipo.", + "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Un tipo di parametro della firma dell'indice non può essere un tipo di valore letterale o un tipo generico. Considerare l'utilizzo di un tipo di oggetto con mapping.", + "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Un tipo di parametro della firma dell'indice deve essere 'stringa', 'numero', 'simbolo' o un tipo di valore letterale del modello.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Un'espressione di creazione di un'istanza non può essere seguita da un accesso a proprietà.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Un'interfaccia può estendere solo un identificatore/nome qualificato con argomenti tipo facoltativi.", + "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Un'interfaccia può estendere solo un tipo di oggetto o un'intersezione di tipi di oggetto con membri noti in modo statico.", + "An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types_2840": "Un'interfaccia non può estendere un elemento di tipo primitivo come '{0}'. Può estendere solo altri tipi di oggetto denominati.", + "An_interface_property_cannot_have_an_initializer_1246": "Una proprietà di interfaccia non può contenere un inizializzatore.", + "An_iterator_must_have_a_next_method_2489": "Un iteratore deve contenere un metodo 'next()'.", + "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Quando si usa un'istruzione @jsx con frammenti JSX, è necessaria un'istruzione pragma @jsxFrag.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "Un valore letterale di oggetto non può contenere più funzioni di accesso get/set con lo stesso nome.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117": "Un valore letterale di oggetto non può contenere più proprietà con lo stesso nome.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "Un valore letterale di oggetto non può contenere proprietà e funzioni di accesso con lo stesso nome.", + "An_object_member_cannot_be_declared_optional_1162": "Un membro di oggetto non può essere dichiarato come facoltativo.", + "An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_han_2861": "Il metodo '[Symbol.hasInstance]' di un oggetto deve restituire un valore booleano da utilizzare a destra di un'espressione 'instanceof'.", + "An_optional_chain_cannot_contain_private_identifiers_18030": "Una catena facoltativa non può contenere identificatori privati.", + "An_optional_element_cannot_follow_a_rest_element_1266": "Non è possibile specificare un elemento facoltativo dopo un elemento REST.", + "An_outer_value_of_this_is_shadowed_by_this_container_2738": "Un valore esterno di 'this' è nascosto da questo contenitore.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Non è possibile dichiarare come generatore una firma di overload.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Nella parte sinistra di un'espressione di elevamento a potenza non è consentita un'espressione unaria con l'operatore '{0}'. Provare a racchiudere l'espressione tra parentesi.", + "Annotate_everything_with_types_from_JSDoc_95043": "Annotare tutto con tipi di JSDoc", + "Annotate_types_of_properties_expando_function_in_a_namespace_90071": "Annotare tipi di proprietà funzione expando in uno spazio dei nomi", + "Annotate_with_type_from_JSDoc_95009": "Annotare con tipo di JSDoc", + "Another_export_default_is_here_2753": "In questo punto è presente un'altra impostazione predefinita per l'esportazione.", + "Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_t_1528": "Qualsiasi proprietà Unicode che potrebbe corrispondere a più di un singolo carattere è disponibile solo quando è impostato il flag Unicode Sets (v).", + "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518": "Qualsiasi elemento che potrebbe corrispondere a più di un singolo carattere non è valido all'interno di una classe di caratteri negati.", + "Are_you_missing_a_semicolon_2734": "Manca un punto e virgola?", + "Argument_expression_expected_1135": "È prevista l'espressione di argomento.", + "Argument_for_0_option_must_be_Colon_1_6046": "L'argomento per l'opzione '{0}' deve essere {1}.", + "Argument_of_dynamic_import_cannot_be_spread_element_1325": "L'argomento dell'importazione dinamica non può essere l'elemento spread.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "L'argomento di tipo '{0}' non è assegnabile al parametro di tipo '{1}'.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379": "L'argomento di tipo '{0}' non può essere assegnato al parametro di tipo '{1}' con 'exactOptionalPropertyTypes: true'. Provare ad aggiungere 'undefined' ai tipi di proprietà di destinazione.", + "Arguments_for_the_rest_parameter_0_were_not_provided_6236": "Gli argomenti per il parametro REST '{0}' non sono stati specificati.", + "Array_element_destructuring_pattern_expected_1181": "È previsto il criterio di destrutturazione dell'elemento della matrice.", + "Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations_9018": "Non è possibile dedurre matrici con elementi estesi con --isolatedDeclarations.", + "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775": "Con le asserzioni ogni nome nella destinazione di chiamata deve essere dichiarato con un'annotazione di tipo esplicita.", + "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776": "Con le asserzioni la destinazione di chiamata deve essere un identificatore o un nome completo.", + "Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations__9023": "L'assegnazione di proprietà a funzioni senza dichiararle non è supportata con --isolatedDeclarations. Aggiungere una dichiarazione esplicita per le proprietà assegnate a questa funzione.", + "Asterisk_Slash_expected_1010": "È previsto '*/'.", + "At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9009": "Almeno una funzione di accesso deve avere un'annotazione di tipo esplicita con --isolatedDeclarations.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Gli aumenti per l'ambito globale possono solo essere direttamente annidati in dichiarazioni di modulo di ambiente o moduli esterni.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "Gli aumenti per l'ambito globale devono contenere il modificatore 'declare', a meno che non siano già presenti in un contesto di ambiente.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "Il rilevamento automatico per le defizioni di tipi è abilitato nel progetto '{0}'. Verrà eseguito il passaggio di risoluzione aggiuntivo per il modulo '{1}' usando il percorso della cache '{2}'.", + "BUILD_OPTIONS_6919": "OPZIONI DI COMPILAZIONE", + "Backwards_Compatibility_6253": "Compatibilità con le versioni precedenti", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "Le espressioni di classi di base non possono fare riferimento a parametri di tipo classe.", + "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509": "Il tipo restituito '{0}' del costruttore di base non è un tipo di oggetto o un'intersezione di tipi di oggetto con membri noti in modo statico.", + "Base_constructors_must_all_have_the_same_return_type_2510": "Il tipo restituito deve essere identico per tutti i costruttori di base.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "Directory di base per risolvere i nomi di modulo non assoluti.", + "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737": "I valori letterali bigint non sono disponibili quando la destinazione è precedente a ES2020.", + "Binary_digit_expected_1177": "È prevista una cifra binaria.", + "Binding_element_0_implicitly_has_an_1_type_7031": "L'elemento di binding '{0}' contiene implicitamente un tipo '{1}'.", + "Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations_9019": "Non è possibile esportare direttamente gli elementi di binding con --isolatedDeclarations.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "La variabile con ambito blocco '{0}' è stata usata prima di essere stata dichiarata.", + "Build_a_composite_project_in_the_working_directory_6925": "Compila un progetto composito nella directory di lavoro.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636": "Compilare tutti i progetti, anche quelli che sembrano aggiornati.", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "Compilare uno o più progetti e le relative dipendenze, se non aggiornate", + "Build_option_0_requires_a_value_of_type_1_5073": "Con l'opzione di compilazione '{0}' è richiesto un valore di tipo {1}.", + "Building_project_0_6358": "Compilazione del progetto '{0}'...", + "Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any_6720": "Per gli enumeratori predefiniti viene creata un'istanza con un tipo 'TReturn' di tipo 'undefined' invece di 'any'.", + "COMMAND_LINE_FLAGS_6921": "FLAG DELLA RIGA DI COMANDO", + "COMMON_COMMANDS_6916": "COMANDI COMUNI", + "COMMON_COMPILER_OPTIONS_6920": "OPZIONI COMUNI DEL COMPILATORE", + "Call_decorator_expression_90028": "Chiamare l'espressione Decorator", + "Call_signature_return_types_0_and_1_are_incompatible_2202": "I tipi restituiti delle firme di chiamata '{0}' e '{1}' sono incompatibili.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La firma di chiamata, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito 'any'.", + "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204": "Le firme di chiamata senza argomenti contengono i tipi restituiti incompatibili '{0}' e '{1}'.", + "Can_only_convert_logical_AND_access_chains_95142": "È possibile convertire solo catene di accesso AND logiche", + "Can_only_convert_named_export_95164": "È possibile solo convertire l'esportazione denominata", + "Can_only_convert_property_with_modifier_95137": "È possibile convertire solo la proprietà con il modificatore", + "Can_only_convert_string_concatenations_and_string_literals_95154": "È possibile convertire solo concatenazioni di stringhe e valori letterali stringa", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Non è possibile accedere a '{0}.{1}' perché '{0}' è un tipo ma non uno spazio dei nomi. Si intendeva recuperare il tipo della proprietà '{1}' in '{0}' con '{0}[\"{1}\"]'?", + "Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead_1281": "Non è possibile accedere '{0}' da un altro file senza qualifica quando '{1}' è abilitato. In alternativa, usare '{2}'.", + "Cannot_access_ambient_const_enums_when_0_is_enabled_2748": "Non è possibile accedere alle enumerazioni const di Ambient quando '{0}' è abilitato.", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "Non è possibile assegnare un tipo di costruttore '{0}' a un tipo di costruttore '{1}'.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "Non è possibile assegnare un tipo di costruttore astratto a un tipo di costruttore non astratto.", + "Cannot_assign_to_0_because_it_is_a_class_2629": "Non è possibile assegnare a '{0}' perché è una classe.", + "Cannot_assign_to_0_because_it_is_a_constant_2588": "Non è possibile assegnare a '{0}' perché è una costante.", + "Cannot_assign_to_0_because_it_is_a_function_2630": "Non è possibile assegnare a '{0}' perché è una funzione.", + "Cannot_assign_to_0_because_it_is_a_namespace_2631": "Non è possibile assegnare a '{0}' perché è uno spazio dei nomi.", + "Cannot_assign_to_0_because_it_is_a_read_only_property_2540": "Non è possibile assegnare a '{0}' perché è una proprietà di sola lettura.", + "Cannot_assign_to_0_because_it_is_an_enum_2628": "Non è possibile assegnare a '{0}' perché è un'enumerazione.", + "Cannot_assign_to_0_because_it_is_an_import_2632": "Non è possibile assegnare a '{0}' perché è una direttiva import.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "Non è possibile assegnare a '{0}' perché non è una variabile.", + "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803": "Non è possibile assegnare al metodo privato '{0}'. I metodi privati non sono scrivibili.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "Non è possibile aumentare il modulo '{0}' perché viene risolto in un'entità non modulo.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "Non è possibile aumentare il modulo '{0}' con le esportazioni dei valori perché viene risolto in un'entità non modulo.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "Non è possibile compilare moduli con l'opzione '{0}' a meno che il flag '--module' non sia impostato su 'amd' o 'system'.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "Non è possibile creare un'istanza di una classe astratta.", + "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766": "Non è possibile delegare l'iterazione al valore perché il metodo 'next' del relativo iteratore prevede il tipo '{1}', ma il generatore che la contiene invierà sempre '{0}'.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "Non è possibile esportare '{0}'. Da un modulo è possibile esportare solo dichiarazioni locali.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "Non è possibile estendere una classe '{0}'. Il costruttore di classe è contrassegnato come privato.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "Non è possibile estendere un'interfaccia '{0}'. Si intendeva usare 'implements'?", + "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081": "Non è possibile trovare alcun file tsconfig.json nella directory corrente: {0}.", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "Non è stato trovato alcun file tsconfig.json nella directory specificata '{0}'.", + "Cannot_find_global_type_0_2318": "Il tipo globale '{0}' non è stato trovato.", + "Cannot_find_global_value_0_2468": "Il valore globale '{0}' non è stato trovato.", + "Cannot_find_lib_definition_for_0_2726": "La definizione della libreria per '{0}' non è stata trovata.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "La definizione della libreria per '{0}' non è stata trovata. Si intendeva '{1}'?", + "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732": "Non è possibile trovare il modulo '{0}'. Provare a usare '--resolveJsonModule' per importare il modulo con estensione '.json'.", + "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_t_2792": "Non è possibile trovare il modulo '{0}'. Si intendeva impostare l'opzione 'moduleResolution' su 'nodenext' o aggiungere alias all'opzione 'paths'?", + "Cannot_find_module_0_or_its_corresponding_type_declarations_2307": "Non è possibile trovare il modulo '{0}' o le relative dichiarazioni di tipo corrispondenti.", + "Cannot_find_name_0_2304": "Il nome '{0}' non è stato trovato.", + "Cannot_find_name_0_Did_you_mean_1_2552": "Il nome '{0}' non è stato trovato. Si intendeva '{1}'?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "Il nome '{0}' non è stato trovato. Si intendeva il membro di istanza 'this.{0}'?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "Il nome '{0}' non è stato trovato. Si intendeva il membro statico '{1}.{0}'?", + "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311": "Impossibile trovare il nome '{0}'. Si intendeva scrivere questo elemento in una funzione asincrona?", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583": "Non è possibile trovare il nome '{0}'. È necessario modificare la libreria di destinazione? Provare a impostare l'opzione 'lib' del compilatore su '{1}' o versioni successive.", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584": "Non è possibile trovare il nome '{0}'. È necessario modificare la libreria di destinazione? Provare a modificare l'opzione 'lib' del compilatore in modo che includa 'dom'.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2867": "Il nome '{0}' non è stato trovato. È necessario installare le definizioni per il tipo di installazione per l'elemento Bun? Provare con `npm i --save-dev @types/bun`.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2868": "Il nome '{0}' non è stato trovato. È necessario installare le definizioni per il tipo di installazione per l'elemento Bun? Provare con `npm i --save-dev @types/bun` quindi aggiungere 'bun' al campo Tipi in tsconfig.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582": "Non è possibile trovare il nome '{0}'. È necessario installare le definizioni di tipo per un test runner? Provare con `npm i --save-dev @types/jest` o `npm i --save-dev @types/mocha`.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593": "Non è possibile trovare il nome '{0}'. È necessario installare le definizioni di tipo per un test runner? Provare con `npm i --save-dev @types/jest` o `npm i --save-dev @types/mocha` e quindi aggiungere 'jest' o 'mocha' al campo types in tsconfig.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581": "Non è possibile trovare il nome '{0}'. È necessario installare le definizioni di tipo per jQuery? Provare con `npm i --save-dev @types/jquery`.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592": "Non è possibile trovare il nome '{0}'. È necessario installare le definizioni di tipo per jQuery? Provare con `npm i --save-dev @types/jquery` e quindi aggiungere 'jquery' al campo types in tsconfig.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Non è possibile trovare il nome '{0}'. È necessario installare le definizioni di tipo per il nodo? Provare con `npm i --save-dev @types/node`.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Non è possibile trovare il nome '{0}'. È necessario installare le definizioni di tipo per il nodo? Provare con `npm i --save-dev @types/node` e quindi aggiungere 'node' al campo types in tsconfig.", + "Cannot_find_namespace_0_2503": "Lo spazio dei nomi '{0}' non è stato trovato.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Il nome '{0}' non è stato trovato. Intendevi '{1}'?", + "Cannot_find_parameter_0_1225": "Il parametro '{0}' non è stato trovato.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Il percorso della sottodirectory comune per i file di input non è stato trovato.", + "Cannot_find_type_definition_file_for_0_2688": "Il file di definizione del tipo per '{0}' non è stato trovato.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Non è possibile importare file di dichiarazione di tipo. Provare a importare '{0}' invece di '{1}'.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Non è possibile inizializzare la variabile con ambito esterna '{0}' nello stesso ambito della dichiarazione con ambito del blocco '{1}'.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Non è possibile richiamare un oggetto che è probabilmente 'null'.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Non è possibile richiamare un oggetto che è probabilmente 'null' o 'undefined'.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Non è possibile richiamare un oggetto che è probabilmente 'undefined'.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765": "Non è possibile eseguire l'iterazione del valore perché il metodo 'next' del relativo iteratore prevede il tipo '{1}', ma la destrutturazione della matrice invierà sempre '{0}'.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Non è possibile eseguire l'iterazione del valore perché il metodo 'next' del relativo iteratore prevede il tipo '{1}', ma l'estensione della matrice invierà sempre '{0}'.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Non è possibile eseguire l'iterazione del valore perché il metodo 'next' del relativo iteratore prevede il tipo '{1}', ma for-of invierà sempre '{0}'.", + "Cannot_move_statements_to_the_selected_file_95183": "Non è possibile spostare istruzioni nel file selezionato", + "Cannot_move_to_file_selected_file_is_invalid_95179": "Non è possibile passare al file. Il file selezionato non è valido", + "Cannot_read_file_0_5083": "Non è possibile leggere il file '{0}'.", + "Cannot_read_file_0_Colon_1_5012": "Non è possibile leggere il file '{0}': {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "Non è possibile dichiarare di nuovo la variabile con ambito blocco '{0}'.", + "Cannot_redeclare_exported_variable_0_2323": "Non è possibile dichiarare di nuovo la variabile esportata '{0}'.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "Non è possibile dichiarare di nuovo l'identificatore '{0}' nella clausola catch.", + "Cannot_start_a_function_call_in_a_type_annotation_1441": "Non è possibile avviare una chiamata di funzione in un'annotazione di tipo.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "Non è possibile usare JSX a meno che non sia specificato il flag '--jsx'.", + "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled_1269": "Non è possibile usare 'export import' in uno spazio dei nomi type o type-only quando '{0}' è abilitato.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "Non è possibile usare importazioni, esportazioni o aumenti del modulo quando il valore di '--module' è 'none'.", + "Cannot_use_namespace_0_as_a_type_2709": "Non è possibile usare lo spazio dei nomi '{0}' come tipo.", + "Cannot_use_namespace_0_as_a_value_2708": "Non è possibile usare lo spazio dei nomi '{0}' come valore.", + "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816": "Non è possibile usare 'this' in un inizializzatore di proprietà statica di una classe decorata.", + "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377": "Non è possibile scrivere il file '{0}' perché sovrascriverà il file '.tsbuildinfo' generato dal progetto di riferimento '{1}'", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "Non è possibile scrivere il file '{0}' perché verrebbe sovrascritto da più file di input.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Non è possibile scrivere il file '{0}' perché sovrascriverebbe il file di input.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "La variabile della clausola catch non può contenere un inizializzatore.", + "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196": "Se specificata, l'annotazione del tipo di variabile della clausola catch deve essere 'any' o 'unknown'.", + "Change_0_to_1_90014": "Modificare '{0}' in '{1}'", + "Change_all_extended_interfaces_to_implements_95038": "Cambiare tutte le interfacce estese in 'implements'", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "Cambiare tutti i tipi in stile jsdoc in TypeScript", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "Cambiare tutti i tipi in stile jsdoc in TypeScript (e aggiungere '| undefined' ai tipi nullable)", + "Change_extends_to_implements_90003": "Cambiare 'extends' in 'implements'", + "Change_spelling_to_0_90022": "Modificare l'ortografia in '{0}'", + "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700": "Verifica la presenza di proprietà di classe dichiarate ma non impostate nel costruttore.", + "Check_side_effect_imports_6806": "Controllare le importazioni di effetti collaterali.", + "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697": "Verifica che gli argomenti per i metodi 'bind', 'call', and 'apply' corrispondano alla funzione originale.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Verrà verificato se '{0}' è il prefisso di corrispondenza più lungo per '{1}' - '{2}'.", + "Circular_definition_of_import_alias_0_2303": "Definizione circolare dell'alias di importazione '{0}'.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "È stata rilevata una circolarità durante la risoluzione della configurazione: {0}", + "Circularity_originates_in_type_at_this_location_2751": "La circolarità ha origine nel tipo in questa posizione.", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "La classe '{0}' definisce '{1}' come funzione di accesso di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di membro di istanza.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "La classe '{0}' definisce '{1}' come funzione di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di accesso di membro di istanza.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La classe '{0}' definisce '{1}' come proprietà di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di membro di istanza.", + "Class_0_incorrectly_extends_base_class_1_2415": "La classe '{0}' estende in modo errato la classe di base '{1}'.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La classe '{0}' implementa in modo errato la classe '{1}'. Si intendeva estendere '{1}' ed ereditarne i membri come sottoclasse?", + "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implementa in modo errato l'interfaccia '{1}'.", + "Class_0_used_before_its_declaration_2449": "La classe '{0}' è stata usata prima di essere stata dichiarata.", + "Class_constructor_may_not_be_a_generator_1368": "Il costruttore di classe non può essere un generatore.", + "Class_constructor_may_not_be_an_accessor_1341": "Il costruttore di classe non può essere una funzione di accesso.", + "Class_declaration_cannot_implement_overload_list_for_0_2813": "La dichiarazione classe non può implementare l'elenco di overload per '{0}'.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Le dichiarazioni di classe non possono contenere più di un tag '@augments' o '@extends'.", + "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Non è possibile elementi Decorator di classe con l'identificatore privato statico. Provare a rimuovere l'elemento Decorator sperimentale.", + "Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super_2855": "Il campo della classe '{0}' definito dalla classe padre non è accessibile nella classe figlio tramite super.", + "Class_name_cannot_be_0_2414": "Il nome della classe non può essere '{0}'.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "Il nome della classe non può essere 'Object' quando la destinazione è ES5 con il modulo {0}.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Il lato statico '{0}' della classe estende in modo errato il lato statico '{1}' della classe di base.", + "Classes_can_only_extend_a_single_class_1174": "Le classi possono estendere solo un'unica classe.", + "Classes_may_not_have_a_field_named_constructor_18006": "Le classi non possono includere un campo denominato 'constructor'.", + "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210": "Il codice contenuto in una classe viene valutato in modalità strict JavaScript, che non consente l'uso di '{0}'. Per altre informazioni, vedere https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.", + "Command_line_Options_6171": "Opzioni della riga di comando", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila il progetto in base al percorso del file di configurazione o della cartella contenente un file 'tsconfig.json'.", + "Compiler_Diagnostics_6251": "Diagnostica compilatore", + "Compiler_option_0_cannot_be_given_an_empty_string_18051": "Non è possibile specificare una stringa vuota per l'opzione del compilatore '{0}'.", + "Compiler_option_0_expects_an_argument_6044": "Con l'opzione '{0}' del compilatore è previsto un argomento.", + "Compiler_option_0_may_not_be_used_with_build_5094": "L'opzione del compilatore '--{0}' potrebbe non essere usata con '--build'.", + "Compiler_option_0_may_only_be_used_with_build_5093": "L'opzione del compilatore '--{0}' potrebbe essere usata solo con '--build'.", + "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124": "L'opzione del compilatore '{0}' del valore '{1}' è instabile. Usare TypeScript notturno per disattivare l'errore. Provare ad eseguire l'aggiornamento con 'npm install -D typescript@next'.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "Con l'opzione '{0}' del compilatore è richiesto un valore di tipo {1}.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Il compilatore riserva il nome '{0}' quando si crea l'identificatore privato per browser meno recenti.", + "Compiles_the_TypeScript_project_located_at_the_specified_path_6927": "Compila il progetto TypeScript presente nel percorso specificato.", + "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923": "Compila il progetto corrente (tsconfig.json nella directory di lavoro).", + "Compiles_the_current_project_with_additional_settings_6929": "Compila il progetto corrente con impostazioni aggiuntive.", + "Completeness_6257": "Completezza", + "Composite_projects_may_not_disable_declaration_emit_6304": "I progetti compositi non possono disabilitare la creazione di dichiarazioni.", + "Composite_projects_may_not_disable_incremental_compilation_6379": "I progetti compositi non possono disabilitare la compilazione incrementale.", + "Computed_from_the_list_of_input_files_6911": "Calcolato dall'elenco dei file di input", + "Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedD_9014": "Le proprietà calcolate devono essere valori letterali numerici o stringa, variabili o espressioni con punti con --isolatedDeclarations.", + "Computed_property_names_are_not_allowed_in_enums_1164": "I nomi di proprietà calcolati non sono consentiti nelle enumerazioni.", + "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038": "Non è possibile dedurre i nomi di proprietà calcolati nei valori letterali di classe o oggetto con --isolatedDeclarations.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "In un'enumerazione con membri con valore stringa non sono consentiti valori calcolati.", + "Concatenate_and_emit_output_to_single_file_6001": "Concatena e crea l'output in un singolo file.", + "Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports_6410": "Condizioni da impostare in aggiunta alle impostazioni predefinite specifiche del resolver durante la risoluzione delle importazioni.", + "Conflicts_are_in_this_file_6201": "I conflitti si trovano in questo file.", + "Consider_adding_a_declare_modifier_to_this_class_6506": "Provare ad aggiungere un modificatore \"declare\" a questa classe.", + "Construct_signature_return_types_0_and_1_are_incompatible_2203": "I tipi restituiti delle firme del costrutto '{0}' e '{1}' sono incompatibili.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "La firma del costrutto, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito 'any'.", + "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205": "Le firme di costrutto senza argomenti contengono i tipi restituiti incompatibili '{0}' e '{1}'.", + "Constructor_implementation_is_missing_2390": "Manca l'implementazione di costruttore.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Il costruttore della classe '{0}' è privato e accessibile solo all'interno della dichiarazione di classe.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "Il costruttore della classe '{0}' è protetto e accessibile solo all'interno della dichiarazione di classe.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386": "La notazione del tipo di costruttore deve essere racchiusa tra parentesi quando viene usata in un tipo di unione.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388": "La notazione del tipo di costruttore deve essere racchiusa tra parentesi quando viene usata in un tipo di intersezione.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "I costruttori di classi derivate devono contenere una chiamata 'super'.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Il file contenitore non è specificato e non è possibile determinare la directory radice. La ricerca nella cartella 'node_modules' verrà ignorata.", + "Containing_function_is_not_an_arrow_function_95128": "La funzione contenitore non è una funzione arrow", + "Control_what_method_is_used_to_detect_module_format_JS_files_1475": "Controllare il metodo usato per rilevare i file JS in formato modulo.", + "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352": "La conversione del tipo '{0}' nel tipo '{1}' può essere un errore perché nessuno dei due tipi si sovrappone sufficientemente all'altro. Se questa opzione è intenzionale, convertire prima l'espressione in 'unknown'.", + "Convert_0_to_1_in_0_95003": "Convertire '{0}' in '{1} in {0}'", + "Convert_0_to_mapped_object_type_95055": "Convertire '{0}' nel tipo di oggetto con mapping", + "Convert_all_const_to_let_95102": "Convertire ogni 'const' in 'let'", + "Convert_all_constructor_functions_to_classes_95045": "Convertire tutte le funzioni di costruttore in classi", + "Convert_all_invalid_characters_to_HTML_entity_code_95101": "Convertire tutti i caratteri non validi nel codice entità HTML", + "Convert_all_re_exported_types_to_type_only_exports_1365": "Convertire tutti i tipi riesportati in esportazioni solo di tipi", + "Convert_all_require_to_import_95048": "Convertire tutte le occorrenze di 'require' in 'import'", + "Convert_all_to_async_functions_95066": "Convertire tutto in funzioni asincrone", + "Convert_all_to_bigint_numeric_literals_95092": "Convertire tutto in valori letterali numerici bigint", + "Convert_all_to_default_imports_95035": "Convertire tutte le impostazioni predefinite", + "Convert_all_type_literals_to_mapped_type_95021": "Convertire tutti i valori letterali di tipo nel tipo di cui è stato eseguito il mapping", + "Convert_all_typedef_to_TypeScript_types_95177": "Convertire tutti gli elementi typedef in tipi TypeScript.", + "Convert_arrow_function_or_function_expression_95122": "Convertire la funzione arrow o l'espressione di funzione", + "Convert_const_to_let_95093": "Convertire 'const' in 'let'", + "Convert_default_export_to_named_export_95061": "Convertire l'esportazione predefinita nell'esportazione denominata", + "Convert_function_declaration_0_to_arrow_function_95106": "Convertire la dichiarazione di funzione '{0}' nella funzione arrow", + "Convert_function_expression_0_to_arrow_function_95105": "Convertire l'espressione di funzione '{0}' nella funzione arrow", + "Convert_function_to_an_ES2015_class_95001": "Converti la funzione in una classe ES2015", + "Convert_invalid_character_to_its_html_entity_code_95100": "Convertire il carattere non valido nel relativo codice entità HTML", + "Convert_named_export_to_default_export_95062": "Convertire l'esportazione denominata nell'esportazione predefinita", + "Convert_named_imports_to_default_import_95170": "Converti importazioni denominate nell'importazione predefinita", + "Convert_named_imports_to_namespace_import_95057": "Convertire le importazioni denominate in importazione spazi dei nomi", + "Convert_namespace_import_to_named_imports_95056": "Convertire l'importazione spazi dei nomi in importazioni denominate", + "Convert_overload_list_to_single_signature_95118": "Convertire l'elenco di overload in una firma singola", + "Convert_parameters_to_destructured_object_95075": "Convertire i parametri nell'oggetto destrutturato", + "Convert_require_to_import_95047": "Convertire 'require' in 'import'", + "Convert_to_ES_module_95017": "Converti nel modulo ES6", + "Convert_to_a_bigint_numeric_literal_95091": "Convertire in un valore letterale numerico bigint", + "Convert_to_anonymous_function_95123": "Convertire nella funzione anonima", + "Convert_to_arrow_function_95125": "Convertire nella funzione arrow", + "Convert_to_async_function_95065": "Convertire nella funzione asincrona", + "Convert_to_default_import_95013": "Convertire nell'importazione predefinita", + "Convert_to_named_function_95124": "Convertire nella funzione denominata", + "Convert_to_optional_chain_expression_95139": "Convertire nell'espressione di catena facoltativa", + "Convert_to_template_string_95096": "Convertire nella stringa di modello", + "Convert_to_type_only_export_1364": "Convertire nell'esportazione solo di tipi", + "Convert_typedef_to_TypeScript_type_95176": "Convertire typedef in tipo TypeScript.", + "Corrupted_locale_file_0_6051": "Il file delle impostazioni locali {0} è danneggiato.", + "Could_not_convert_to_anonymous_function_95153": "Non è stato possibile convertire nella funzione anonima", + "Could_not_convert_to_arrow_function_95151": "Non è stato possibile convertire nella funzione arrow", + "Could_not_convert_to_named_function_95152": "Non è stato possibile convertire nella funzione denominata", + "Could_not_determine_function_return_type_95150": "Non è stato possibile determinare il tipo restituito dalla funzione", + "Could_not_find_a_containing_arrow_function_95127": "Non è stato possibile trovare una funzione arrow contenitore", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Non è stato trovato alcun file di dichiarazione per il modulo '{0}'. A '{1}' è assegnato implicitamente un tipo 'any'.", + "Could_not_find_convertible_access_expression_95140": "Non è stato possibile trovare l'espressione di accesso convertibile", + "Could_not_find_export_statement_95129": "Non è stato possibile trovare l'istruzione di esportazione", + "Could_not_find_import_clause_95131": "Non è stato possibile trovare la clausola di importazione", + "Could_not_find_matching_access_expressions_95141": "Non è stato possibile trovare espressioni di accesso corrispondenti", + "Could_not_find_name_0_Did_you_mean_1_2570": "Non è stato possibile trovare il nome '{0}'. Si intendeva '{1}'?", + "Could_not_find_namespace_import_or_named_imports_95132": "Non è stato possibile trovare l'importazione spazi dei nomi o importazioni denominate", + "Could_not_find_property_for_which_to_generate_accessor_95135": "Non è stato possibile trovare la proprietà per cui generare la funzione di accesso", + "Could_not_find_variable_to_inline_95185": "Non è possibile trovare la variabile per inline.", + "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Non è stato possibile risolvere il percorso '{0}' con le estensioni: {1}.", + "Could_not_write_file_0_Colon_1_5033": "Non è stato possibile scrivere il file '{0}': {1}.", + "Create_source_map_files_for_emitted_JavaScript_files_6694": "Crea file di mapping di origine per i file JavaScript creati.", + "Create_sourcemaps_for_d_ts_files_6614": "Crea mapping di origine per i file d.ts.", + "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926": "Crea un file tsconfig.jscon le impostazioni consigliate nella directory di lavoro.", + "DIRECTORY_6038": "DIRECTORY", + "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537": "Le sequenze di escape e i backreference decimali non sono consentiti in una classe di caratteri.", + "Decimals_with_leading_zeros_are_not_allowed_1489": "I decimali con zeri iniziali non sono consentiti.", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "La dichiarazione causa un aumento di una dichiarazione in un altro file. Questa operazione non è serializzabile.", + "Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_support_9026": "La creazione della dichiarazione per questo file richiede il mantenimento dell'importazione per gli aumenti. Funzionalità non supportata con --isolatedDeclarations.", + "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "Per la creazione della dichiarazione per questo file è necessario usare il nome privato '{0}'. Un'annotazione di tipo esplicita può sbloccare la creazione della dichiarazione.", + "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "Per la creazione della dichiarazione per questo file è necessario usare il nome privato '{0}' dal modulo '{1}'. Un'annotazione di tipo esplicita può sbloccare la creazione della dichiarazione.", + "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_sup_9025": "La creazione di dichiarazioni per questo parametro richiede l'aggiunta implicita di elementi non definiti al relativo tipo. Funzionalità non supportata con --isolatedDeclarations.", + "Declaration_expected_1146": "È prevista la dichiarazione.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Il nome della dichiarazione è in conflitto con l'identificatore globale predefinito '{0}'.", + "Declaration_or_statement_expected_1128": "È prevista la dichiarazione o l'istruzione.", + "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809": "Dichiarazione o istruzione prevista. Questo carattere '=' segue un blocco di istruzioni, di conseguenza se si intende scrivere un'assegnazione di destrutturazione, potrebbe essere necessario racchiudere l'intera assegnazione tra parentesi.", + "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264": "Le dichiarazioni con asserzioni di assegnazione definite devono includere anche annotazioni di tipo.", + "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263": "Le dichiarazioni con inizializzatori non possono includere anche asserzioni di assegnazione definite.", + "Declare_a_private_field_named_0_90053": "Dichiarare un campo privato denominato '{0}'.", + "Declare_method_0_90023": "Dichiarare il metodo '{0}'", + "Declare_private_method_0_90038": "Dichiarare il metodo privato '{0}'", + "Declare_private_property_0_90035": "Dichiarare la proprietà privata '{0}'", + "Declare_property_0_90016": "Dichiarare la proprietà '{0}'", + "Declare_static_method_0_90024": "Dichiarare il metodo statico '{0}'", + "Declare_static_property_0_90027": "Dichiarare la proprietà statica '{0}'", + "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270": "Il tipo restituito della funzione Decorator '{0}' non è assegnabile al tipo '{1}'.", + "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271": "Il tipo restituito della funzione Decorator è '{0}' ma è previsto 'void' o 'any'.", + "Decorator_used_before_export_here_1486": "Elemento Decorator usato prima di 'export'.", + "Decorators_are_not_valid_here_1206": "In questo punto le espressioni Decorator non sono valide.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Non è possibile applicare le espressioni Decorator a più funzioni di accesso get/set con lo stesso nome.", + "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038": "Gli elementi Decorator non possono essere visualizzati dopo 'export' o 'export default' se vengono visualizzati anche prima di 'export'.", + "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436": "Gli elementi Decorator devono precedere il nome e tutte le parole chiave delle dichiarazioni di proprietà.", + "Default_catch_clause_variables_as_unknown_instead_of_any_6803": "Le variabili della clausola catch predefinite sono 'unknown' anziché 'any'.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'esportazione predefinita del modulo contiene o usa il nome privato '{0}'.", + "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037": "Non è possibile dedurre le esportazioni predefinite con --isolatedDeclarations.", + "Default_library_1424": "Libreria predefinita", + "Default_library_for_target_0_1425": "Libreria predefinita per la destinazione '{0}'", + "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Le definizioni degli identificatori seguenti sono in conflitto con quelle di un altro file: {0}", + "Delete_all_unused_declarations_95024": "Eliminare tutte le dichiarazioni non usate", + "Delete_all_unused_imports_95147": "Eliminare tutte le direttive import non usate", + "Delete_all_unused_param_tags_95172": "Eliminare tutti i tag '@param' inutilizzati", + "Delete_the_outputs_of_all_projects_6365": "Eliminare gli output di tutti i progetti.", + "Delete_unused_param_tag_0_95171": "Eliminare il tag '@param' '{0}' inutilizzato", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Deprecata] In alternativa, usare '--jsxFactory'. Specifica l'oggetto richiamato per createElement quando la destinazione è la creazione JSX 'react'", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Deprecata] In alternativa, usare '--outFile'. Concatena e crea l'output in un singolo file", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Deprecata] In alternativa, usare '--skipLibCheck'. Ignora il controllo del tipo dei file di dichiarazione delle librerie predefinite.", + "Deprecated_setting_Use_outFile_instead_6677": "Impostazione deprecata. In alternativa, usare 'outFile'.", + "Did_you_forget_to_use_await_2773": "Si è omesso di usare 'await'?", + "Did_you_mean_0_1369": "Si intendeva '{0}'?", + "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735": "Si intendeva che '{0}' fosse vincolato al tipo 'new (...args: any[]) => {1}'?", + "Did_you_mean_to_call_this_expression_6212": "Si intendeva chiamare questa espressione?", + "Did_you_mean_to_mark_this_function_as_async_1356": "Si intendeva contrassegnare questa funzione come 'async'?", + "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312": "Si intendeva usare i due punti (':')? È possibile usare il carattere '=' dopo un nome di proprietà, solo quando il valore letterale di oggetto che lo contiene fa parte di un criterio di destrutturazione.", + "Did_you_mean_to_use_new_with_this_expression_6213": "Si intende usare 'new' con questa espressione?", + "Digit_expected_1124": "È prevista la cifra.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "La directory '{0}' non esiste. Tutte le ricerche che la interessano verranno ignorate.", + "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270": "La directory ' {0}' non contiene alcun ambito package.json. Non sarà possibile risolvere le importazioni.", + "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669": "Disabilita l'aggiunta di direttive `use strict` nei file JavaScript generati.", + "Disable_checking_for_this_file_90018": "Disabilitare la verifica per questo file", + "Disable_emitting_comments_6688": "Disabilita la creazione di commenti.", + "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701": "Disabilita la creazione di dichiarazioni che contengono '@internal' nei commenti JSDoc.", + "Disable_emitting_files_from_a_compilation_6660": "Disabilita la creazione di file da una compilazione.", + "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662": "Disabilita la creazione di file se vengono restituiti errori di controllo del tipo.", + "Disable_erasing_const_enum_declarations_in_generated_code_6682": "Disabilita la cancellazione delle dichiarazioni 'const enum' nel codice generato.", + "Disable_error_reporting_for_unreachable_code_6603": "Disabilita la segnalazione errori per il codice non raggiungibile.", + "Disable_error_reporting_for_unused_labels_6604": "Disabilita la segnalazione errori per le etichette non usate.", + "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805": "Disabilitare il controllo completo dei tipi (verranno segnalati solo errori critici di creazione e analisi).", + "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661": "Disabilita la generazione di funzioni helper personalizzate come '__extends' nell'output compilato.", + "Disable_including_any_library_files_including_the_default_lib_d_ts_6670": "Disabilita l'inclusione di tutti i file di libreria, incluso il file lib.d.ts predefinito.", + "Disable_loading_referenced_projects_6235": "Disabilitare il caricamento dei progetti cui viene fatto riferimento.", + "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620": "Disabilita la preferenza per i file di origine invece dei file di dichiarazione quando si fa riferimento a progetti compositi.", + "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702": "Disabilita la segnalazione errori di proprietà in eccesso durante la creazione di valori letterali dell'oggetto.", + "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683": "Disabilita la risoluzione dei collegamenti simbolici nei relativi realpath. È correlato allo stesso flag presente nel nodo.", + "Disable_size_limitations_on_JavaScript_projects_6162": "Disabilita le dimensioni relative alle dimensioni per i progetti JavaScript.", + "Disable_solution_searching_for_this_project_6224": "Disabilitare la ricerca della soluzione per questo progetto.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6673": "Disabilitare il controllo tassativo delle firme generiche nei tipi funzione.", + "Disable_the_type_acquisition_for_JavaScript_projects_6625": "Disabilita l'acquisizione del tipo per i progetti JavaScript", + "Disable_truncating_types_in_error_messages_6663": "Disabilita il troncamento dei tipi nei messaggi di errore.", + "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221": "Disabilitare l'uso di file di origine invece dei file di dichiarazione dai progetti a cui si fa riferimento.", + "Disable_wiping_the_console_in_watch_mode_6684": "Disabilita la cancellazione della console in modalità espressione di controllo.", + "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616": "Disabilita l'inferenza per l'acquisizione del tipo esaminando i nomi di file in un progetto.", + "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672": "Non consente a direttive 'import's, 'require's o '' di espandere il numero di file che TypeScript deve aggiungere a un progetto.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Non consente riferimenti allo stesso file in cui le maiuscole/minuscole vengono usate in modo incoerente.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "Non aggiunge riferimenti con tripla barra (////) o moduli importati all'elenco di file compilati.", + "Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript_6721": "Non consentire costrutti di runtime che non fanno parte di ECMAScript.", + "Do_not_emit_comments_to_output_6009": "Non crea commenti nell'output.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "Non crea dichiarazioni per codice che contiene un'annotazione '@internal'.", + "Do_not_emit_outputs_6010": "Non crea output.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Non crea output se sono stati restituiti errori.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "Non crea direttive 'use strict' nell'output del modulo.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Non cancella le dichiarazioni di enumerazione const nel codice generato.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Non genera funzioni di supporto personalizzate, come '__extends', nell'output compilato.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "Non include il file di libreria predefinito (lib.d.ts).", + "Do_not_report_errors_on_unreachable_code_6077": "Non segnala gli errori in caso di codice non raggiungibile.", + "Do_not_report_errors_on_unused_labels_6074": "Non segnala gli errori in caso di etichette non usate.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "Non risolvere il percorso reale di collegamenti simbolici.", + "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804": "Non trasformare o eliminare importazioni o esportazioni non contrassegnate come type-only, in modo che vengano scritte nel formato del file di output in base all'impostazione 'module'.", + "Do_not_truncate_error_messages_6165": "Non tronca i messaggi di errore.", + "Duplicate_function_implementation_2393": "Implementazione di funzione duplicata.", + "Duplicate_identifier_0_2300": "Identificatore '{0}' duplicato.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "Identificatore '{0}' duplicato. Il compilatore riserva il nome '{1}' nell'ambito di primo livello di un modulo.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "L'identificatore '{0}' è duplicato. Il compilatore riserva il nome '{1}' nell'ambito di primo livello di un modulo che contiene funzioni asincrone.", + "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818": "L'identificatore '{0}' è duplicato. Il compilatore riserva il nome '{1}' durante la creazione dei riferimenti 'super' negli inizializzatori statici.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "Identificatore '{0}' duplicato. Il compilatore usa la dichiarazione '{1}' per supportare le funzioni asincrone.", + "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804": "L'identificatore '{0}' è duplicato. Gli elementi statici e di istanza non possono condividere lo stesso nome privato.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "Identificatore 'arguments' duplicato. Il compilatore usa 'arguments' per inizializzare i parametri rest.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "Identificatore '_newTarget' duplicato. Il compilatore usa la dichiarazione di variabile '_newTarget' per acquisire il riferimento alla metaproprietà 'new.target'.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "Identificatore '_this' duplicato. Il compilatore usa la dichiarazione di variabile '_this' per acquisire il riferimento 'this'.", + "Duplicate_index_signature_for_type_0_2374": "Firma dell'indice duplicata per il tipo '{0}'.", + "Duplicate_label_0_1114": "Etichetta '{0}' duplicata.", + "Duplicate_property_0_2718": "La proprietà '{0}' è duplicata.", + "Duplicate_regular_expression_flag_1500": "Flag di espressione regolare duplicato.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "L'identificatore dell'importazione dinamica deve essere di tipo 'string', ma il tipo specificato qui è '{0}'.", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Le importazioni dinamiche sono supportate solo quando il flag '--module' è impostato su 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node16', 'node18' o 'nodenext'.", + "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments_1450": "Le importazioni dinamiche possono accettare come argomenti solo un identificatore di modulo e un set di attributi facoltativi", + "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_1324": "Le importazioni dinamiche supportano un secondo argomento solo quando l'opzione '--module' è impostata su 'esnext', 'node16', 'node18', 'nodenext' o 'preserve'.", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve_1293": "Sintassi ESM non consentita in un modulo CommonJS quando 'module' è impostato su 'preserve'.", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled_1286": "Sintassi ESM non consentita in un modulo CommonJS quando 'verbatimModuleSyntax' è abilitato.", + "Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given_4125": "Il valore di ogni dichiarazione di '{0}.{1}' è diverso, dove '{2}' è previsto mentre '{3}' è specificato.", + "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Ogni membro del tipo di unione '{0}' contiene firme di costrutto, ma nessuna di tali firme è compatibile con le altre.", + "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758": "Ogni membro del tipo di unione '{0}' contiene firme, ma nessuna di tali firme è compatibile con le altre.", + "Editor_Support_6249": "Supporto Editor", + "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053": "L'elemento contiene implicitamente un tipo 'any' perché non è possibile usare l'espressione di tipo '{0}' per indicizzare il tipo '{1}'.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'elemento contiene implicitamente un tipo 'any' perché l'espressione di indice non è di tipo 'number'.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "L'elemento contiene implicitamente un tipo 'any' perché al tipo '{0}' non è assegnata alcuna firma dell'indice.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052": "L'elemento contiene implicitamente un tipo 'any' perché al tipo '{0}' non è assegnata alcuna firma dell'indice. Si intendeva chiamare '{1}'?", + "Emit_6246": "Crea", + "Emit_ECMAScript_standard_compliant_class_fields_6712": "Crea campi di classe conformi allo standard ECMAScript.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622": "Crea un BOM (Byte Order Mark) UTF-8 all'inizio dei file di output.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Crea un unico file con i mapping di origine invece di file separati.", + "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638": "Crea un profilo CPU v8 dell'esecuzione del compilatore per il debug.", + "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626": "Crea codice JavaScript aggiuntivo per semplificare il supporto per l'importazione di moduli CommonJS. Abilita 'allowSyntheticDefaultImports' per la compatibilità dei tipi.", + "Emit_class_fields_with_Define_instead_of_Set_6222": "Creare i campi della classe con Define invece di Set.", + "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624": "Crea metadati di tipo progettazione per le dichiarazioni decorate nei file di origine.", + "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621": "Crea codice JavaScript più conforme, ma dettagliato e meno efficiente per l'iterazione.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Crea l'origine unitamente ai mapping di origine all'interno di un unico file. Richiede l'impostazione di '--inlineSourceMap' o '--sourceMap'.", + "Enable_all_strict_type_checking_options_6180": "Abilita tutte le opzioni per i controlli del tipo strict.", + "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685": "Abilita il colore e la formattazione nell'output TypeScript per agevolare la lettura degli errori del compilatore.", + "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611": "Abilita i vincoli che consentono l'uso di un progetto TypeScript con riferimenti al progetto.", + "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667": "Abilita la segnalazione errori per i percorsi di codice che non vengono restituiti in modo esplicito in una funzione.", + "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665": "Abilita la segnalazione errori per espressioni e dichiarazioni con un tipo implicito 'any'.", + "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664": "Abilita la segnalazione errori per i casi di fallthrough nelle istruzioni switch.", + "Enable_error_reporting_in_type_checked_JavaScript_files_6609": "Abilita la segnalazione errori nei file JavaScript con controllo del tipo.", + "Enable_error_reporting_when_local_variables_aren_t_read_6675": "Abilita la segnalazione errori quando variabili locali non vengono lette.", + "Enable_error_reporting_when_this_is_given_the_type_any_6668": "Abilita la segnalazione errori quando a 'this' viene assegnato il tipo 'any'.", + "Enable_experimental_support_for_legacy_experimental_decorators_6630": "Abilitare il supporto sperimentale per gli elementi Decorator sperimentali legacy.", + "Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present_6264": "Abilitare l'importazione di file con qualsiasi estensione, purché sia presente un file di dichiarazione.", + "Enable_importing_json_files_6689": "Abilita l'importazione di file .json.", + "Enable_lib_replacement_6808": "Abilita sostituzione librerie.", + "Enable_project_compilation_6302": "Abilitare la compilazione dei progetti", + "Enable_strict_bind_call_and_apply_methods_on_functions_6214": "Abilitare i metodi strict 'bind', 'call' e 'apply' nelle funzioni.", + "Enable_strict_checking_of_function_types_6186": "Abilita il controllo tassativo dei tipi funzione.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "Abilitare il controllo tassativo dell'inizializzazione delle proprietà nelle classi.", + "Enable_strict_null_checks_6113": "Abilita i controlli strict Null.", + "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074": "Abilitare l'opzione 'experimentalDecorators' nel file di configurazione", + "Enable_the_jsx_flag_in_your_configuration_file_95088": "Abilitare il flag '--jsx' nel file di configurazione", + "Enable_tracing_of_the_name_resolution_process_6085": "Abilita la traccia del processo di risoluzione dei nomi.", + "Enable_verbose_logging_6713": "Abilitare la registrazione dettagliata.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Abilita l'interoperabilità di creazione tra moduli ES e CommonJS tramite la creazione di oggetti spazio dei nomi per tutte le importazioni. Implica 'allowSyntheticDefaultImports'.", + "Enables_experimental_support_for_ES7_decorators_6065": "Abilita il supporto sperimentale per le espressioni Decorator di ES7.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Abilita il supporto sperimentale per la creazione dei metadati dei tipi per le espressioni Decorator.", + "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671": "Impone l'uso di funzioni di accesso indicizzate per le chiavi dichiarate con un tipo indicizzato.", + "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666": "Si assicura che i membri di override nelle classi derivate siano contrassegnati con un modificatore override.", + "Ensure_that_casing_is_correct_in_imports_6637": "Si assicura che l'uso di maiuscole e minuscole sia corretto nelle direttive import.", + "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645": "Si assicura che sia possibile eseguire il transpile di ogni file in modo sicuro senza basarsi su altre direttive import.", + "Ensure_use_strict_is_always_emitted_6605": "Si assicura che la direttiva 'use strict' venga sempre creata.", + "Entering_conditional_exports_6413": "Immissione di esportazioni condizionali.", + "Entry_point_for_implicit_type_library_0_1420": "Punto di ingresso per la libreria dei tipi impliciti '{0}'", + "Entry_point_for_implicit_type_library_0_with_packageId_1_1421": "Punto di ingresso per la libreria dei tipi impliciti '{0}' con packageId '{1}'", + "Entry_point_of_type_library_0_specified_in_compilerOptions_1417": "Punto di ingresso della libreria dei tipi '{0}' specificata in compilerOptions", + "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418": "Punto di ingresso della libreria dei tipi '{0}' specificata in compilerOptions con packageId '{1}'", + "Enum_0_used_before_its_declaration_2450": "L'enumerazione '{0}' è stata usata prima di essere stata dichiarata.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "È possibile unire dichiarazioni di enumerazione solo con lo spazio dei nomi o altre dichiarazioni di enumerazione.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Le dichiarazioni di enumerazione devono essere tutte const o tutte non const.", + "Enum_member_expected_1132": "È previsto il membro di enumerazione.", + "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056": "Il membro di enumerazione che segue un membro numerico non letterale deve avere un inizializzatore quando 'isolatedModules' è abilitato.", + "Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDecl_9020": "Gli inizializzatori di membri di enumerazione devono essere calcolabili senza riferimenti a simboli esterni con --isolatedDeclarations.", + "Enum_member_must_have_initializer_1061": "Il membro di enumerazione deve contenere l'inizializzatore.", + "Enum_name_cannot_be_0_2431": "Il nome dell'enumerazione non può essere '{0}'.", + "Errors_Files_6041": "File di errori", + "Escape_sequence_0_is_not_allowed_1488": "Sequenza di escape '{0}' non consentita.", + "Examples_Colon_0_6026": "Esempi: {0}", + "Excessive_complexity_comparing_types_0_and_1_2859": "Complessità eccessiva rispetto ai tipi '{0}' e '{1}'.", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "La profondità dello stack per il confronto dei tipi '{0}' e '{1}' è eccessiva.", + "Exiting_conditional_exports_6416": "Chiusura di esportazioni condizionali.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Sono previsti argomento tipo {0}-{1}. Per specificarli, usare un tag '@extends'.", + "Expected_0_arguments_but_got_1_2554": "Sono previsti {0} argomenti, ma ne sono stati ottenuti {1}.", + "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794": "Sono previsti {0} argomenti, ma ne sono stati ottenuti {1}. Si è dimenticato di includere 'void' nell'argomento di tipo per 'Promise'?", + "Expected_0_type_arguments_but_got_1_2558": "Sono previsti {0} argomenti tipo, ma ne sono stati ottenuti {1}.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Sono previsti {0} argomenti tipo. Per specificarli, usare un tag '@extends'.", + "Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_2810": "Previsto 1 argomento, ma ottenuto 0. 'new Promise()' richiede un hint JSDoc per produrre un elemento 'resolve' che possa essere chiamato senza argomenti.", + "Expected_a_Unicode_property_name_1523": "È previsto un nome per la proprietà Unicode.", + "Expected_a_Unicode_property_name_or_value_1527": "È previsto un nome o un valore per la proprietà Unicode.", + "Expected_a_Unicode_property_value_1525": "È previsto un valore per la proprietà Unicode.", + "Expected_a_capturing_group_name_1514": "È previsto un nome per il gruppo di acquisizione.", + "Expected_a_class_set_operand_1520": "È previsto un operando del set di classi.", + "Expected_at_least_0_arguments_but_got_1_2555": "Sono previsti almeno {0} argomenti, ma ne sono stati ottenuti {1}.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "È previsto il tag di chiusura JSX corrispondente per '{0}'.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "È previsto il tag di chiusura corrispondente per il frammento JSX.", + "Expected_for_property_initializer_1442": "È previsto '=' per l'inizializzatore di proprietà.", + "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105": "Il tipo previsto del campo '{0}' in 'package.json' è '{1}', ma è stato ottenuto '{2}'.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Il tipo di risoluzione del modulo '{0}' è stato specificato in modo esplicito.", + "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Non è possibile usare l'elevamento a potenza su valori 'bigint' a meno che l'opzione 'target' non sia impostata su 'es2016' o versioni successive.", + "Export_0_from_module_1_90059": "Esporta '{0}' dal modulo '{1}'", + "Export_all_referenced_locals_90060": "Esporta tutte le variabili locali di riferimento", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Non è possibile usare l'assegnazione di esportazione se destinata a moduli ECMAScript. Provare a usare 'export default' o un altro formato di modulo.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "L'assegnazione dell'esportazione non è supportata quando il valore del flag '--module' è 'system'.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La dichiarazione di esportazione è in conflitto con la dichiarazione esportata di '{0}'.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "Le dichiarazioni di esportazione non sono consentite in uno spazio dei nomi.", + "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276": "L'identificatore di esportazione '{0}' non esiste nell'ambito package.json al percorso '{1}'.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "L'alias di tipo esportato '{0}' contiene o usa il nome privato '{1}'.", + "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084": "L'alias di tipo esportato '{0}' contiene o usa il nome privato '{1}' del modulo {2}.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "La variabile esportata '{0}' contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominata.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "La variabile esportata '{0}' contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "La variabile esportata '{0}' contiene o usa il nome privato '{1}'.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Le esportazioni e le assegnazioni di esportazioni non sono consentite negli aumenti del modulo.", + "Expression_expected_1109": "È prevista l'espressione.", + "Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator_1497": "L'espressione deve essere racchiusa tra parentesi per poter essere usata come elemento Decorator.", + "Expression_or_comma_expected_1137": "È prevista l'espressione o la virgola.", + "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800": "L'espressione produce un tipo di tupla troppo grande da rappresentare.", + "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590": "L'espressione produce un tipo di unione troppo complesso da rappresentare.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "L'espressione viene risolta in '_super', che è usato dal compilatore per acquisire il riferimento della classe di base.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "L'espressione viene risolta nella dichiarazione di variabile '_newTarget', che è usata dal compilatore per acquisire il riferimento alla metaproprietà 'new.target'.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "L'espressione viene risolta nella dichiarazione di variabile '_this', che è usata dal compilatore per acquisire il riferimento 'this'.", + "Expression_type_can_t_be_inferred_with_isolatedDeclarations_9013": "Non è possibile dedurre il tipo di espressione con --isolatedDeclarations.", + "Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations_9021": "La clausola Extends non può contenere un'espressione con --isolatedDeclarations.", + "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085": "La clausola Extends del tipo dedotto '{0}' contiene o usa il nome privato '{1}'.", + "Extract_base_class_to_variable_90064": "Estrarre la classe di base nella variabile", + "Extract_binding_expressions_to_variable_90066": "Estrarre le espressioni di associazione nella variabile", + "Extract_constant_95006": "Estrarre la costante", + "Extract_default_export_to_variable_90065": "Estrarre l'esportazione predefinita nella variabile", + "Extract_function_95005": "Estrarre la funzione", + "Extract_to_0_in_1_95004": "Estrarre in {0} in {1}", + "Extract_to_0_in_1_scope_95008": "Estrarre in {0} nell'ambito {1}", + "Extract_to_0_in_enclosing_scope_95007": "Estrarre in {0} nell'ambito che lo contiene", + "Extract_to_interface_95090": "Estrarre nell'interfaccia", + "Extract_to_type_alias_95078": "Estrarre nell'alias di tipo", + "Extract_to_typedef_95079": "Estrarre in typedef", + "Extract_to_variable_and_replace_with_0_as_typeof_0_90069": "Estrarre nella variabile e sostituire con '{0} come typeof {0}'", + "Extract_type_95077": "Estrarre il tipo", + "FILE_6035": "FILE", + "FILE_OR_DIRECTORY_6040": "FILE O DIRECTORY", + "Failed_to_find_peerDependency_0_6283": "Impossibile trovare peerDependency '{0}'.", + "Failed_to_resolve_under_condition_0_6415": "Impossibile risolvere in base alla condizione '{0}'.", + "Fallthrough_case_in_switch_7029": "Caso di fallthrough in switch.", + "File_0_does_not_exist_6096": "Il file '{0}' non esiste.", + "File_0_does_not_exist_according_to_earlier_cached_lookups_6240": "Il file '{0}' non esiste in base alle ricerche precedenti memorizzate nella cache.", + "File_0_exists_according_to_earlier_cached_lookups_6239": "Il file '{0}' esiste già in base alle ricerche precedenti memorizzate nella cache.", + "File_0_exists_use_it_as_a_name_resolution_result_6097": "Il file '{0}' esiste. Usarlo come risultato per la risoluzione dei nomi.", + "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054": "L'estensione del file '{0}' non è supportata. Le uniche estensioni supportate sono {1}.", + "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504": "Il file '{0}' è un file JavaScript. Si intendeva abilitare l'opzione 'allowJs'?", + "File_0_is_not_a_module_2306": "Il file '{0}' non è un modulo.", + "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307": "Il file '{0}' non è incluso nell'elenco file del progetto '{1}'. I progetti devono elencare tutti i file o usare un criterio 'include'.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Il file '{0}' non si trova in 'rootDir' '{1}'. 'rootDir' deve contenere tutti i file di origine.", + "File_0_not_found_6053": "Il file '{0}' non è stato trovato.", + "File_Management_6245": "Gestione dei file", + "File_appears_to_be_binary_1490": "Il file sembra essere binario.", + "File_change_detected_Starting_incremental_compilation_6032": "È stata rilevata una modifica ai file. Verrà avviata la compilazione incrementale...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Il file è un modulo CommonJS perché '{0}' non contiene il campo \"type\"", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Il file è un modulo CommonJS perché '{0}' contiene il campo \"type\" il cui valore non è \"module\"", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Il file è un modulo CommonJS perché 'package.json' non è stato trovato", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Il file è un modulo ECMAScript perché '{0}' contiene il campo \"type\" con valore \"module\"", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Il file è un modulo CommonJS e può essere convertito in un modulo ES6.", + "File_is_default_library_for_target_specified_here_1426": "Il file è la libreria predefinita per la destinazione specificata in questo punto.", + "File_is_entry_point_of_type_library_specified_here_1419": "Il file è il punto di ingresso della libreria dei tipi specificata in questo punto.", + "File_is_included_via_import_here_1399": "Il file viene incluso tramite importazione in questo punto.", + "File_is_included_via_library_reference_here_1406": "Il file viene incluso tramite il riferimento alla libreria in questo punto.", + "File_is_included_via_reference_here_1401": "Il file viene incluso tramite riferimento in questo punto.", + "File_is_included_via_type_library_reference_here_1404": "Il file viene incluso tramite il riferimento alla libreria dei tipi in questo punto.", + "File_is_library_specified_here_1423": "Il file è la libreria specificata in questo punto.", + "File_is_matched_by_files_list_specified_here_1410": "Per la corrispondenza del file viene usato l'elenco 'files' specificato in questo punto.", + "File_is_matched_by_include_pattern_specified_here_1408": "Per la corrispondenza del file viene usato il criterio di inclusione specificato in questo punto.", + "File_is_output_from_referenced_project_specified_here_1413": "Il file corrisponde all'output del progetto di riferimento specificato in questo punto.", + "File_is_output_of_project_reference_source_0_1428": "Il file corrisponde all'origine '{0}' del riferimento al progetto", + "File_is_source_from_referenced_project_specified_here_1416": "Il file è l'origine del progetto di riferimento specificato in questo punto.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Il nome file '{0}' differisce da quello già incluso '{1}' solo per l'uso di maiuscole/minuscole.", + "File_name_0_has_a_1_extension_looking_up_2_instead_6262": "Il nome file '{0}' ha un'estensione '{1}' - eseguire invece la ricerca di '{2}'.", + "File_name_0_has_a_1_extension_stripping_it_6132": "L'estensione del nome file '{0}' è '{1}' e verrà rimossa.", + "File_redirects_to_file_0_1429": "Il file viene reindirizzato al file '{0}'", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La specifica del file non può contenere una directory padre ('..') inserita dopo un carattere jolly ('**') di directory ricorsiva: '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "La specifica del file non può terminare con caratteri jolly ('**') di directory ricorsiva: '{0}'.", + "Filters_results_from_the_include_option_6627": "Filtra i risultati dall'opzione `include`.", + "Fix_all_detected_spelling_errors_95026": "Correggere tutti gli errori di ortografia rilevati", + "Fix_all_expressions_possibly_missing_await_95085": "Correggere tutte le espressioni in cui potrebbe mancare 'await'", + "Fix_all_implicit_this_errors_95107": "Correggere tutti gli errori relativi a 'this' implicito", + "Fix_all_incorrect_return_type_of_an_async_functions_90037": "Correggere tutti i tipi restituiti non corretti di una funzione asincrona", + "Fix_all_with_type_only_imports_95182": "Correggere tutto con importazioni type-only", + "Found_0_errors_6217": "Sono stati trovati {0} errori.", + "Found_0_errors_Watching_for_file_changes_6194": "Sono stati trovati {0} errori. Verranno individuate le modifiche ai file.", + "Found_0_errors_in_1_files_6261": "Sono stati trovati {0} errori nei file {1}.", + "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260": "Sono stati trovati {0} errori nello stesso file, a partire da: {1}", + "Found_1_error_6216": "È stato trovato 1 errore.", + "Found_1_error_Watching_for_file_changes_6193": "È stato trovato 1 errore. Verranno individuate le modifiche ai file.", + "Found_1_error_in_0_6259": "È stato trovato 1 errore in {0}", + "Found_package_json_at_0_6099": "Il file 'package.json' è stato trovato in '{0}'.", + "Found_peerDependency_0_with_1_version_6282": "Trovato l'elemento peerDependency '{0}' con versione '{1}'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_1250": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES5'.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definiti_1251": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES5'. Le definizioni di classe sono impostate automaticamente nella modalità strict.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_au_1252": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES5'. I moduli sono impostati automaticamente nella modalità strict.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "L'espressione di funzione, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito '{0}'.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "L'implementazione di funzione manca o non segue immediatamente la dichiarazione.", + "Function_implementation_name_must_be_0_2389": "Il nome dell'implementazione di funzione deve essere '{0}'.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La funzione contiene implicitamente il tipo restituito 'any', perché non contiene un'annotazione di tipo restituito e viene usata come riferimento diretto o indiretto in una delle relative espressioni restituite.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Nella funzione manca l'istruzione return finale e il tipo restituito non include 'undefined'.", + "Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9007": "La funzione deve avere un'annotazione di tipo restituito esplicita con --isolatedDeclarations.", + "Function_not_implemented_95159": "Funzione non implementata.", + "Function_overload_must_be_static_2387": "L'overload della funzione deve essere statico.", + "Function_overload_must_not_be_static_2388": "L'overload della funzione non deve essere statico.", + "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385": "La notazione del tipo di funzione deve essere racchiusa tra parentesi quando viene usata in un tipo di unione.", + "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387": "La notazione del tipo di funzione deve essere racchiusa tra parentesi quando viene usata in un tipo di intersezione.", + "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014": "Il tipo di funzione, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito '{0}'.", + "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814": "La funzione con corpi può essere unita solo a classi di tipo ambient.", + "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612": "Genera file .d.ts da file TypeScript e JavaScript nel progetto.", + "Generate_get_and_set_accessors_95046": "Generare le funzioni di accesso 'get' e 'set'", + "Generate_get_and_set_accessors_for_all_overriding_properties_95119": "Generare le funzioni di accesso 'get' e 'set' per tutte le proprietà di sostituzione", + "Generates_a_CPU_profile_6223": "Genera un profilo CPU.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Genera un mapping di origine per ogni file '.d.ts' corrispondente.", + "Generates_an_event_trace_and_a_list_of_types_6237": "Genera una traccia eventi e un elenco di tipi.", + "Generates_corresponding_d_ts_file_6002": "Genera il file '.d.ts' corrispondente.", + "Generates_corresponding_map_file_6043": "Genera il file '.map' corrispondente.", + "Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation_7025": "Il generatore ha implicitamente il tipo yield \"{0}\". Provare a specificare un'annotazione di tipo restituito.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "I generatori non sono consentiti in un contesto di ambiente.", + "Generic_type_0_requires_1_type_argument_s_2314": "Il tipo generico '{0}' richiede {1} argomento/i di tipo.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "Il tipo generico '{0}' richiede tra {1} e {2} argomenti tipo.", + "Global_module_exports_may_only_appear_at_top_level_1316": "Le esportazioni di moduli globali possono essere usate solo al primo livello.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "Le esportazioni di moduli globali possono essere usate solo in file di dichiarazione.", + "Global_module_exports_may_only_appear_in_module_files_1314": "Le esportazioni di moduli globali possono essere usate solo in file di modulo.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "Il tipo globale '{0}' deve un tipo di classe o di interfaccia.", + "Global_type_0_must_have_1_type_parameter_s_2317": "Il tipo globale '{0}' deve contenere {1} parametro/i di tipo.", + "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384": "Impostare le ricompilazioni in '--incremental' e '--watch' in modo che le modifiche all'interno di un file interessino solo i file che dipendono direttamente da esso.", + "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606": "Imposta le ricompilazioni in progetti che usano la modalità 'incremental' e 'watch' in modo che le modifiche all'interno di un file interessino solo i file che dipendono direttamente da esso.", + "Hexadecimal_digit_expected_1125": "È prevista la cifra esadecimale.", + "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262": "È previsto un identificatore. '{0}' è una parola riservata al livello principale di un modulo.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict. Le definizioni di classe sono automaticamente impostate sulla modalità strict.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict. I moduli vengono impostati automaticamente in modalità strict.", + "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "È previsto un identificatore. '{0}' è una parola riservata che non può essere usata in questo punto.", + "Identifier_expected_1003": "È previsto l'identificatore.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "È previsto un identificatore. '__esModule' è riservato come marcatore esportato durante la trasformazione di moduli ECMAScript.", + "Identifier_or_string_literal_expected_1478": "Previsto identificatore o valore letterale stringa.", + "Identifier_string_literal_or_number_literal_expected_1496": "Identificatore, valore letterale stringa o valore letterale numerico previsti.", + "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Se il pacchetto '{0}' espone effettivamente questo modulo, provare a inviare una richiesta pull per modificare 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'", + "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Se il pacchetto ' {0}' espone effettivamente il modulo, provare ad aggiungere un nuovo file di dichiarazione (.d.ts) contenente ' Dichiara modulo' {1}';'", + "Ignore_this_error_message_90019": "Ignorare questo messaggio di errore", + "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924": "Il file tsconfig.json verrà ignorato. I file specificati verranno compilati con le opzioni predefinite del compilatore.", + "Implement_all_inherited_abstract_classes_95040": "Implementare tutte le classi astratte ereditate", + "Implement_all_unimplemented_interfaces_95032": "Implementare tutte le interfacce non implementate", + "Implement_inherited_abstract_class_90007": "Implementare la classe astratta ereditata", + "Implement_interface_0_90006": "Implementare l'interfaccia '{0}'", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La clausola implements della classe esportata '{0}' contiene o usa il nome privato '{1}'.", + "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731": "La conversione implicita di un valore 'symbol' in 'string' non riuscirà in fase di esecuzione. Provare a eseguire il wrapping di questa espressione in 'String(...)'.", + "Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_w_2866": "L'importazione '{0}' è in conflitto con il valore globale usato in questo file, quindi deve essere dichiarata con un'importazione type-only quando 'isolatedModules' è abilitato.", + "Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_2865": "L'importazione '{0}' è in conflitto con il valore locale, quindi deve essere dichiarata con un'importazione type-only quando 'isolatedModules' è abilitato.", + "Import_0_from_1_90013": "Importare '{0}' da \"{1}\".", + "Import_assertion_values_must_be_string_literal_expressions_2837": "I valori di asserzione di importazione devono essere espressioni letterali delle stringhe.", + "Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2836": "Le asserzioni di importazione non sono consentite nelle istruzioni che compilano nelle chiamate 'require' di CommonJS.", + "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2821": "Le asserzioni di importazione sono supportate solo quando l'opzione '--module' è impostata su 'esnext', 'node18', 'nodenext' o 'preserve'.", + "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822": "Non è possibile usare asserzioni di importazione con importazioni o esportazioni di solo tipo.", + "Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880": "Le asserzioni di importazione sono state sostituite dagli attributi di importazione. Usare 'with' invece di 'assert'.", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Non è possibile usare l'assegnazione di importazione se destinata a moduli ECMAScript. Provare a usare 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' o un altro formato di modulo.", + "Import_attribute_values_must_be_string_literal_expressions_2858": "I valori degli attributi di importazione devono essere espressioni letterali delle stringhe.", + "Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2856": "Gli attributi di importazione non sono consentiti nelle istruzioni che compilano nelle chiamate 'require' di CommonJS.", + "Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2823": "Gli attributi di importazione sono supportati solo quando l'opzione '--module' è impostata su 'esnext', 'node18', 'nodenext' o 'preserve'.", + "Import_attributes_cannot_be_used_with_type_only_imports_or_exports_2857": "Non è possibile usare attributi di importazione con importazioni o esportazioni type-only.", + "Import_declaration_0_is_using_private_name_1_4000": "La dichiarazione di importazione '{0}' usa il nome privato '{1}'.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La dichiarazione di importazione è in conflitto con la dichiarazione locale di '{0}'.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Le dichiarazioni di importazione in uno spazio dei nomi non possono far riferimento a un modulo.", + "Import_emit_helpers_from_tslib_6139": "Importa gli helper di creazione da 'tslib'.", + "Import_may_be_converted_to_a_default_import_80003": "L'importazione può essere convertita in un'importazione predefinita.", + "Import_name_cannot_be_0_2438": "Il nome dell'importazione non può essere '{0}'.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La dichiarazione di importazione o esportazione in una dichiarazione di modulo di ambiente non può fare riferimento al modulo tramite il nome di modulo relativo.", + "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271": "L'identificatore di importazione ' {0}' non esiste nell’ambito package.json al percorso ' {1}'.", + "Imported_via_0_from_file_1_1393": "Importato tramite {0} dal file '{1}'", + "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395": "Importato tramite {0} dal file '{1}' per importare 'importHelpers' come specificato in compilerOptions", + "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397": "Importato tramite {0} dal file '{1}' per importare le funzioni di factory 'jsx' e 'jsxs'", + "Imported_via_0_from_file_1_with_packageId_2_1394": "Importato tramite {0} dal file '{1}' con packageId '{2}'", + "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396": "Importato tramite {0} dal file '{1}' con packageId '{2}' per importare 'importHelpers' come specificato in compilerOptions", + "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398": "Importato tramite {0} dal file '{1}' con packageId '{2}' per importare le funzioni di factory 'jsx' e 'jsxs'", + "Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_mod_1543": "L'importazione di un file JSON in un modulo ECMAScript richiede un attributo di importazione \"type: \"json\"\" quando \"module\" è impostato su \"{0}\".", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Le importazioni non sono consentite negli aumenti di modulo. Provare a spostarle nel modulo esterno di inclusione.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Nelle dichiarazioni di enumerazione dell'ambiente l'inizializzatore di membro deve essere un'espressione costante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In un'enumerazione con più dichiarazioni solo una di queste può omettere un inizializzatore per il primo elemento dell'enumerazione.", + "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635": "Include un elenco di file. A differenza di `include`, i criteri GLOB non sono supportati.", + "Include_modules_imported_with_json_extension_6197": "Includere i moduli importati con estensione '.json'", + "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644": "Include il codice sorgente nei mapping di origine all'interno del codice JavaScript creato.", + "Include_sourcemap_files_inside_the_emitted_JavaScript_6643": "Include i file dei mapping di origine all'interno del codice JavaScript creato.", + "Includes_imports_of_types_referenced_by_0_90054": "Include importazioni di tipi a cui fa riferimento '{0}'", + "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914": "Se si include --watch, l'opzione -w consentirà di iniziare a controllare il progetto corrente per individuare modifiche ai file. Dopo l'impostazione, è possibile configurare la modalità espressione di controllo con:", + "Incomplete_quantifier_Digit_expected_1505": "Quantificatore incompleto. Numero previsto.", + "Index_signature_for_type_0_is_missing_in_type_1_2329": "La firma dell'indice per il tipo '{0}' manca nel tipo '{1}'.", + "Index_signature_in_type_0_only_permits_reading_2542": "La firma dell'indice nel tipo '{0}' consente solo la lettura.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Le singole dichiarazioni della dichiarazione sottoposta a merge '{0}' devono essere tutte esportate o tutte locali.", + "Infer_all_types_from_usage_95023": "Derivare tutti i tipi dall'utilizzo", + "Infer_function_return_type_95148": "Dedurre il tipo restituito della funzione", + "Infer_parameter_types_from_usage_95012": "Derivare i tipi di parametro dall'utilizzo", + "Infer_this_type_of_0_from_usage_95080": "Derivare il tipo 'this' di '{0}' dall'utilizzo", + "Infer_type_of_0_from_usage_95011": "Derivare il tipo di '{0}' dall'utilizzo", + "Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations_9022": "L'inferenza dalle espressioni di classe non è supportata con --isolatedDeclarations.", + "Initialize_property_0_in_the_constructor_90020": "Inizializzare la proprietà '{0}' nel costruttore", + "Initialize_static_property_0_90021": "Inizializzare la proprietà statica '{0}'", + "Initializer_for_property_0_2811": "Inizializzatore per la proprietà '{0}'", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'inizializzatore della variabile del membro di istanza '{0}' non può fare riferimento all'identificatore '{1}' dichiarato nel costruttore.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "Gli inizializzatori non sono consentiti in contesti di ambiente.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inizializza un progetto TypeScript e crea un file tsconfig.json.", + "Inline_variable_95184": "Variabile inline", + "Insert_command_line_options_and_files_from_a_file_6030": "Inserisce i file e le opzioni della riga di comando da un file.", + "Install_0_95014": "Installare '{0}'", + "Install_all_missing_types_packages_95033": "Installare tutti i pacchetti di tipi mancanti", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "L'interfaccia '{0}' non può estendere simultaneamente i tipi '{1}' e '{2}'.", + "Interface_0_incorrectly_extends_interface_1_2430": "L'interfaccia '{0}' estende in modo errato l'interfaccia '{1}'.", + "Interface_declaration_cannot_have_implements_clause_1176": "La dichiarazione di interfaccia non può avere una clausola 'implements'.", + "Interface_must_be_given_a_name_1438": "È necessario assegnare un nome all'interfaccia.", + "Interface_name_cannot_be_0_2427": "Il nome dell'interfaccia non può essere '{0}'.", + "Interop_Constraints_6252": "Vincoli interoperabilità", + "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243": "Interpreta i tipi di proprietà facoltativi scritti, invece di aggiungere 'undefined'.", + "Invalid_character_1127": "Carattere non valido.", + "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "L'identificatore di importazione non è valido ' {0}' non contiene risoluzioni possibili.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Il nome di modulo nell'aumento non è valido. Il modulo '{0}' viene risolto in un modulo non tipizzato in '{1}', che non può essere aumentato.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Il nome di modulo nell'aumento non è valido. Il modulo '{0}' non è stato trovato.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Catena facoltativa non valida dalla nuova espressione. Si intendeva chiamare '{0}()'?", + "Invalid_reference_directive_syntax_1084": "La sintassi della direttiva 'reference' non è valida.", + "Invalid_syntax_in_decorator_1498": "Sintassi non valida nell'elemento Decorator.", + "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Uso non valido di '{0}'. Non può essere usato all'interno di un blocco statico di classe.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso non valido di '{0}'. I moduli vengono impostati automaticamente in modalità strict.", + "Invalid_use_of_0_in_strict_mode_1100": "Uso non valido di '{0}' in modalità strict.", + "Invalid_value_for_ignoreDeprecations_5103": "Valore non valido per '--ignoreDeprecations'.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Il valore non è valido per 'jsxFactory'. '{0}' non è un identificatore o un nome qualificato valido.", + "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035": "Il valore non è valido per 'jsxFragmentFactory'. '{0}' non è un identificatore o un nome qualificato valido.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Il valore di '--reactNamespace' non è valido. '{0}' non è un identificatore valido", + "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796": "È probabile che manchi una virgola per separare queste due espressioni di modello. Costituiscono un'espressione di modello con tag che non può essere richiamata.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Il relativo tipo di elemento '{0}' non è un elemento JSX valido.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Il relativo tipo di istanza '{0}' non è un elemento JSX valido.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Il relativo tipo restituito '{0}' non è un elemento JSX valido.", + "Its_type_0_is_not_a_valid_JSX_element_type_18053": "Il relativo tipo '{0}' non è un tipo di elemento JSX valido.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Il tag '@{0} {1}' di JSDoc non corrisponde alla clausola 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Il tag '@{0}' di JSDoc non è collegato a una classe.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' può essere presente solo nell'ultimo parametro di una firma.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Il nome del tag '@param' di JSDoc è '{0}', ma non esiste alcun parametro con questo nome.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "Il nome del tag '@param' di JSDoc è '{0}', ma non esiste alcun parametro con questo nome. Se contenesse un tipo matrice, corrisponderebbe ad 'arguments'.", + "JSDoc_typedef_may_be_converted_to_TypeScript_type_80009": "Il typedef di JSDoc può essere convertito nel tipo TypeScript.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Il tag '@typedef' di JSDoc deve contenere un'annotazione di tipo o essere seguito dal tag '@property' o '@member'.", + "JSDoc_typedefs_may_be_converted_to_TypeScript_types_80010": "I typedef di JSDoc possono essere convertiti nel tipo TypeScript.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "I tipi JSDoc possono essere usati solo nei commenti della documentazione.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "I tipi JSDoc possono essere convertiti in tipi TypeScript.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Agli attributi JSX deve essere assegnato solo un elemento 'expression' non vuoto.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "Per l'elemento JSX '{0}' non esiste alcun tag di chiusura corrispondente.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La classe dell'elemento JSX non supporta gli attributi perché non contiene una proprietà '{0}'.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "L'elemento JSX contiene implicitamente il tipo 'any' perché non esiste alcuna interfaccia 'JSX.{0}'.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "L'elemento JSX contiene implicitamente il tipo 'any' perché il tipo globale 'JSX.Element' non esiste.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "Il tipo '{0}' dell'elemento JSX non contiene firme di costrutto o chiamata.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "Gli elementi JSX non possono contenere più attributi con lo stesso nome.", + "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007": "Nelle espressioni JSX non si può usare l'operatore virgola. Si intendeva scrivere una matrice?", + "JSX_expressions_must_have_one_parent_element_2657": "Le espressioni JSX devono contenere un solo elemento padre.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "Per il frammento JSX non esiste alcun tag di chiusura corrispondente.", + "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633": "Le espressioni di accesso alla proprietà JSX non possono includere nomi dello spazio dei nomi JSX", + "JSX_spread_child_must_be_an_array_type_2609": "L'elemento figlio dell'attributo spread JSX deve essere un tipo di matrice.", + "JavaScript_Support_6247": "Supporto JavaScript", + "Jump_target_cannot_cross_function_boundary_1107": "La destinazione di collegamento non può oltrepassare il limite della funzione.", + "KIND_6034": "TIPOLOGIA", + "Keywords_cannot_contain_escape_characters_1260": "Le parole chiave non possono contenere caratteri di escape.", + "LOCATION_6037": "PERCORSO", + "Language_and_Environment_6254": "Linguaggio e ambiente", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "Il lato sinistro dell'operatore virgola non è usato e non ha effetti collaterali.", + "Library_0_specified_in_compilerOptions_1422": "Libreria '{0}' specificata in compilerOptions", + "Library_referenced_via_0_from_file_1_1405": "Libreria a cui viene fatto riferimento tramite '{0}' dal file '{1}'", + "Line_break_not_permitted_here_1142": "L'interruzione di riga non è consentita in questo punto.", + "Line_terminator_not_permitted_before_arrow_1200": "Il terminatore di riga non è consentito prima di arrow.", + "List_of_file_name_suffixes_to_search_when_resolving_a_module_6931": "Elenco dei suffissi dei nomi di file da cercare durante la risoluzione di un modulo.", + "List_of_folders_to_include_type_definitions_from_6161": "Elenco di cartelle da cui includere le definizioni di tipo.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "Elenco delle cartelle radice il cui contenuto combinato rappresenta la struttura del progetto in fase di esecuzione.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "Verrà eseguito il caricamento di '{0}' dalla directory radice '{1}'. Percorso candidato: '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_types_Colon_1_6098": "Verrà eseguito il caricamento del modulo '{0}' dalla cartella 'node_modules'. Tipi di file di destinazione: {1}.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1_6095": "Verrà eseguito il caricamento del modulo come file/cartella. Percorso candidato del modulo: '{0}'. Tipi di file di destinazione: {1}.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Le impostazioni locali devono essere nel formato o -, ad esempio, '{0}' o '{1}'.", + "Log_paths_used_during_the_moduleResolution_process_6706": "Registra i percorsi usati durante il processo 'moduleResolution'.", + "Longest_matching_prefix_for_0_is_1_6108": "Il prefisso di corrispondenza più lungo per '{0}' è '{1}'.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "Verrà eseguita la ricerca nella cartella 'node_modules'. Percorso iniziale: '{0}'.", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "Impostare tutte le chiamate a 'super()' come prima istruzione nel costruttore", + "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Imposta keyof in modo che restituisca solo stringhe invece di stringhe, numeri o simboli. Opzione legacy.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Impostare la chiamata a 'super()' come prima istruzione nel costruttore", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Il tipo di oggetto con mapping contiene implicitamente un tipo di modello 'any'.", + "Mark_array_literal_as_const_90070": "Contrassegnare il valore letterale della matrice come const", + "Matched_0_condition_1_6403": "Corrispondenza tra '{0}' condizione '{1}'.", + "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Corrispondente per impostazione predefinita al criterio di inclusione '**/*'", + "Matched_by_include_pattern_0_in_1_1407": "Corrispondenza tramite criterio di inclusione '{0}' in '{1}'", + "Member_0_implicitly_has_an_1_type_7008": "Il membro '{0}' contiene implicitamente un tipo '{1}'.", + "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Il membro '{0}' include implicitamente un tipo '{1}', ma è possibile dedurre un tipo migliore dall'utilizzo.", + "Merge_conflict_marker_encountered_1185": "È stato rilevato un indicatore di conflitti di merge.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La dichiarazione '{0}' sottoposta a merge non può includere una dichiarazione di esportazione predefinita. Provare ad aggiungere una dichiarazione 'export default {0}' distinta.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "La metaproprietà '{0}' è consentita solo nel corpo di una dichiarazione di funzione, di un'espressione di funzione o di un costruttore.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "Il metodo '{0}' non può includere un'implementazione perché è contrassegnato come astratto.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "Il metodo '{0}' dell'interfaccia esportata ha o usa il nome '{1}' del modulo privato '{2}'.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "Il metodo '{0}' dell'interfaccia esportata ha o usa il nome privato '{1}'.", + "Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9008": "Il metodo deve avere un'annotazione di tipo restituito esplicita con --isolatedDeclarations.", + "Method_not_implemented_95158": "Metodo non implementato.", + "Modifiers_cannot_appear_here_1184": "In questo punto non è possibile usare modificatori.", + "Module_0_can_only_be_default_imported_using_the_1_flag_1259": "Il modulo '{0}' può essere importato come predefinito solo con il flag '{1}'", + "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471": "Non è possibile importare il modulo '{0}' utilizzando questo costrutto. L'identificatore può essere solo risolto in un modulo ES, che non può essere importato con 'require'. Usare invece un'importazione ECMAScript.", + "Module_0_declares_1_locally_but_it_is_exported_as_2_2460": "Il modulo '{0}' dichiara '{1}' in locale, ma viene esportato come '{2}'.", + "Module_0_declares_1_locally_but_it_is_not_exported_2459": "Il modulo '{0}' dichiara '{1}' in locale, ma non viene esportato.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340": "Il modulo '{0}' non fa riferimento a un tipo, ma viene usato come tipo in questo punto. Si intendeva 'typeof import('{0}')'?", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "Il modulo '{0}' non fa riferimento a un valore, ma qui viene usato come valore.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "Il modulo {0} ha già esportato un membro denominato '{1}'. Per risolvere l'ambiguità, provare a esportarlo di nuovo in modo esplicito.", + "Module_0_has_no_default_export_1192": "Per il modulo '{0}' non esistono esportazioni predefinite.", + "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613": "Non esiste alcuna esportazione predefinita per il modulo '{0}'. Si intendeva usare 'import { {1} } from {0}'?", + "Module_0_has_no_exported_member_1_2305": "Il modulo '{0}' non contiene un membro esportato '{1}'.", + "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614": "Non esiste alcun membro esportato '{1}' per il modulo '{0}'. Si intendeva usare 'import {1} from {0}'?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "Il modulo '{0}' è nascosto da una dichiarazione locale con lo stesso nome.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Il modulo '{0}' usa 'export =' e non può essere usato con 'export *'.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Il modulo '{0}' è stato risolto come modulo di ambiente dichiarato in locale nel file '{1}'.", + "Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set_6263": "Il modulo '{0}' è stato risolto in '{1}', ma '--allowArbitraryExtensions' non è impostato.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Il modulo '{0}' è stato risolto in '{1}', ma '--jsx' non è impostato.", + "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042": "Il modulo '{0}' è stato risolto in '{1}', ma '--resolveJsonModule' non viene usato.", + "Module_declaration_names_may_only_use_or_quoted_strings_1443": "I nomi delle dichiarazioni di modulo possono usare solo stringhe racchiuse tra virgolette.", + "Module_name_0_matched_pattern_1_6092": "Nome del modulo: '{0}'. Criterio corrispondente: '{1}'.", + "Module_name_0_was_not_resolved_6090": "======== Il nome del modulo '{0}' non è stato risolto. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== Il nome del modulo '{0}' è stato risolto in '{1}'. ========", + "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218": "======== Il nome del modulo '{0}' è stato risolto in '{1}' con ID pacchetto '{2}'. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "Il tipo di risoluzione del modulo non è specificato. Verrà usato '{0}'.", + "Module_resolution_using_rootDirs_has_failed_6111": "La risoluzione del modulo con 'rootDirs' non è riuscita.", + "Modules_6244": "Moduli", + "Move_labeled_tuple_element_modifiers_to_labels_95117": "Spostare i modificatori di elemento tupla con etichetta nelle etichette", + "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036": "Spostare l'espressione nell'esportazione predefinita in una variabile e aggiungervi un'annotazione di tipo.", + "Move_to_a_new_file_95049": "Passare a un nuovo file", + "Move_to_file_95178": "Spostare nel file", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Non sono consentiti più separatori numerici consecutivi.", + "Multiple_constructor_implementations_are_not_allowed_2392": "Non è possibile usare più implementazioni di costruttore.", + "NEWLINE_6061": "NUOVA RIGA", + "Name_is_not_valid_95136": "Nome non valido.", + "Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later_1503": "I gruppi di acquisizione denominati sono disponibili solo se destinati a 'ES2018' o versioni successive.", + "Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other_1515": "I gruppi di acquisizione denominati con lo stesso nome devono escludersi a vicenda.", + "Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0_1544": "Le importazioni denominate da un file JSON in un modulo ECMAScript non sono consentite quando \"module\" è impostato su \"{0}\".", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Le proprietà denominate '{0}' dei tipi '{1}' e '{2}' non sono identiche.", + "Namespace_0_has_no_exported_member_1_2694": "Lo spazio dei nomi '{0}' non contiene un membro esportato '{1}'.", + "Namespace_must_be_given_a_name_1437": "È necessario assegnare un nome allo spazio dei nomi.", + "Namespace_name_cannot_be_0_2819": "Lo spazio dei nomi non può essere '{0}'.", + "Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to__1280": "Gli spazi dei nomi non sono consentiti nei file di script globali quando '{0}' è abilitato. Se questo file non deve essere uno script globale, impostare 'moduleDetection' su 'force' o aggiungere un'istruzione 'export {}' vuota.", + "Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters_1433": "Non è possibile applicare né elementi Decorator né modificatori ai parametri 'this'.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "Nessun costruttore di base contiene il numero specificato di argomenti tipo.", + "No_constituent_of_type_0_is_callable_2755": "Non è possibile chiamare nessun costituente di tipo '{0}'.", + "No_constituent_of_type_0_is_constructable_2759": "Non è possibile costruire nessun costituente di tipo '{0}'.", + "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054": "Non è stata trovata alcuna firma dell'indice con un parametro di tipo '{0}' nel tipo '{1}'.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Non sono stati trovati input nel file config '{0}'. Percorsi 'include' specificati: '{1}'. Percorsi 'exclude' specificati: '{2}'.", + "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608": "Non più supportato. Nelle versioni precedenti imposta manualmente la codifica del testo per la lettura dei file.", + "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575": "Nessun overload prevede {0} argomenti, ma esistono overload che prevedono {1} o {2} argomenti.", + "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743": "Nessun overload prevede {0} argomenti di tipo, ma esistono overload che prevedono {1} o {2} argomenti di tipo.", + "No_overload_matches_this_call_2769": "Nessun overload corrisponde a questa chiamata.", + "No_type_could_be_extracted_from_this_type_node_95134": "Non è stato possibile estrarre il tipo da questo nodo di tipo", + "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004": "Non esiste alcun valore nell'ambito per la proprietà a sintassi abbreviata '{0}'. Dichiararne uno o specificare un inizializzatore.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La classe non astratta '{0}' non implementa il membro astratto ereditato {1} della classe '{2}'.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_2654": "Nella classe non astratta '{0}' mancano implementazioni per i seguenti membri di '{1}': {2}.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more_2655": "Nella classe non astratta '{0}' mancano implementazioni per i seguenti membri di '{1}': {2} e altri {3}.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'espressione di classe non astratta non implementa il membro astratto ereditato '{0}' dalla classe '{1}'.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_2656": "Nell'espressione di classe non astratta mancano implementazioni per i seguenti membri di '{0}': {1}.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and__2650": "Nell'espressione di classe non astratta mancano implementazioni per i seguenti membri di '{0}': {1} e altri {2}.", + "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013": "Le asserzioni non Null possono essere usate solo in file TypeScript.", + "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090": "I percorsi non relativi non sono consentiti quando 'baseUrl' non è impostato. Si è dimenticato di aggiungere './' all'inizio?", + "Non_simple_parameter_declared_here_1348": "In questo punto è dichiarato un parametro non semplice.", + "Not_all_code_paths_return_a_value_7030": "Non tutti i percorsi del codice restituiscono un valore.", + "Not_all_constituents_of_type_0_are_callable_2756": "Non tutti i costituenti di tipo '{0}' possono essere chiamati.", + "Not_all_constituents_of_type_0_are_constructable_2760": "Non tutti i costituenti di tipo '{0}' possono essere costruiti.", + "Numbers_out_of_order_in_quantifier_1506": "Numeri non in ordine nel quantificatore.", + "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008": "I valori letterali numerici con valori assoluti uguali o maggiori di 2^53 sono troppo grandi per essere rappresentati in modo corretto come numeri interi.", + "Numeric_separators_are_not_allowed_here_6188": "I separatori numerici non sono consentiti in questa posizione.", + "Object_is_of_type_unknown_2571": "L'oggetto è di tipo 'unknown'.", + "Object_is_possibly_null_2531": "L'oggetto è probabilmente 'null'.", + "Object_is_possibly_null_or_undefined_2533": "L'oggetto è probabilmente 'null' o 'undefined'.", + "Object_is_possibly_undefined_2532": "L'oggetto è probabilmente 'undefined'.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "Il valore letterale di oggetto può specificare solo proprietà note e '{0}' non esiste nel tipo '{1}'.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "Il valore letterale dell'oggetto può specificare solo proprietà note, ma '{0}' non esiste nel tipo '{1}'. Si intendeva scrivere '{2}'?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La proprietà '{0}' del valore letterale di oggetto contiene implicitamente un tipo '{1}'.", + "Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations_9016": "Gli oggetti che contengono proprietà a sintassi abbreviata non possono essere dedotti con --isolatedDeclarations.", + "Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations_9015": "Gli oggetti che contengono assegnazioni di estensione non possono essere dedotti con --isolatedDeclarations.", + "Octal_digit_expected_1178": "È prevista la cifra ottale.", + "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536": "Le sequenze di escape e i backreference ottali non sono consentiti in una classe di caratteri. Se è stata utilizzata come sequenza di escape, usare la sintassi '{0}'.", + "Octal_escape_sequences_are_not_allowed_Use_the_syntax_0_1487": "Le sequenze di escape ottali non sono consentite. Usare la sintassi '{0}'.", + "Octal_literals_are_not_allowed_Use_the_syntax_0_1121": "I valori letterali ottali non sono consentiti. Usare la sintassi '{0}'.", + "One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value_4126": "Un valore di '{0}.{1}' è la stringa '{2}' e si presuppone che l'altro sia un valore numerico sconosciuto.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "In un'istruzione 'for...in' è consentita solo una singola dichiarazione di variabile.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "In un'istruzione 'for...of' è consentita solo una singola dichiarazione di variabile.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Con la parola chiave 'new' può essere chiamata solo una funzione void.", + "Only_ambient_modules_can_use_quoted_names_1035": "I nomi delimitati si possono usare solo nei moduli di ambiente.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "Unitamente a --{0} sono supportati solo i moduli 'amd' e 'system'.", + "Only_const_arrays_can_be_inferred_with_isolatedDeclarations_9017": "È possibile dedurre solo matrici const con --isolatedDeclarations.", + "Only_emit_d_ts_declaration_files_6014": "Creare solo i file di dichiarazione '.d.ts'.", + "Only_output_d_ts_files_and_not_JavaScript_files_6623": "Restituisce solo file d.ts e non file JavaScript.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Con la parola chiave 'super' è possibile accedere solo ai metodi pubblico e protetto della classe di base.", + "Operator_0_cannot_be_applied_to_type_1_2736": "Non è possibile applicare l'operatore '{0}' al tipo '{1}'.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Non è possibile applicare l'operatore '{0}' ai tipi '{1}' e '{2}'.", + "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519": "Gli operatori non devono essere misti all'interno di una classe di caratteri. Eseguire il wrapping in una classe annidata.", + "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619": "Esclude un progetto dal controllo dei riferimenti a più progetti durante la modifica.", + "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108": "L'opzione '{0}={1}' è stata rimossa. Rimuovere l'elemento dalla configurazione.", + "Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDepr_5107": "L'opzione '{0}={1}' è deprecata e non funzionerà più in TypeScript {2}. Per disattivare l'errore, specificare compilerOption '\"ignoreDeprecations\": \"{3}\"'.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "L'opzione '{0}' può essere specificata solo nel file 'tsconfig.json' oppure impostata su 'false' o 'null' sulla riga di comando.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "L'opzione '{0}' può essere specificata solo nel file 'tsconfig.json' oppure impostata su 'null' sulla riga di comando.", + "Option_0_can_only_be_specified_on_command_line_6266": "L'opzione '{0}' può essere specificata solo nella riga di comando.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "L'opzione '{0}' può essere usata solo quando si specifica l'opzione '--inlineSourceMap' o '--sourceMap'.", + "Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler_5098": "L'opzione '{0}' può essere usata solo quando 'moduleResolution' è impostato su 'node16', 'nodenext' o 'bundler'.", + "Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later_5095": "L'opzione '{0}' può essere usata solo quando 'module' è impostato su 'preserve' o 'es2015' o versione successiva.", + "Option_0_cannot_be_specified_when_option_jsx_is_1_5089": "Non è possibile specificare l'opzione '{0}' quando l'opzione 'jsx' è '{1}'.", + "Option_0_cannot_be_specified_with_option_1_5053": "Non è possibile specificare l'opzione '{0}' insieme all'opzione '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "Non è possibile specificare l'opzione '{0}' senza l'opzione '{1}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "Non è possibile specificare l'opzione '{0}' senza l'opzione'{1}' o '{2}'.", + "Option_0_has_been_removed_Please_remove_it_from_your_configuration_5102": "L'opzione '{0}' è stata rimossa. Rimuovere l'elemento dalla configurazione.", + "Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprec_5101": "L'opzione '{0}' è deprecata e non funzionerà più in TypeScript {1}. Per disattivare l'errore, specificare compilerOption '\"ignoreDeprecations\": \"{2}\"'.", + "Option_0_is_redundant_and_cannot_be_specified_with_option_1_5104": "L'opzione '{0}' è ridondante e non può essere specificata con l'opzione'{1}'.", + "Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set_5096": "L'opzione 'allowImportingTsExtensions' può essere usata solo quando è impostato 'noEmit' o 'emitDeclarationOnly'.", + "Option_build_must_be_the_first_command_line_argument_6369": "L'opzione '--build' deve essere il primo argomento della riga di comando.", + "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074": "È possibile specificare l'opzione '--incremental' solo se si usa tsconfig, si crea un singolo file o si specifica l'opzione '--tsBuildInfoFile'.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'opzione 'isolatedModules' può essere usata solo quando si specifica l'opzione '--module' oppure il valore dell'opzione 'target' è 'ES2015' o maggiore.", + "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109": "L'opzione 'moduleResolution' deve essere impostata su '{0}' (o rimanere non specificata) quando l'opzione 'module' è impostata su '{1}'.", + "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110": "L'opzione 'module' deve essere impostata su '{0}' quando l'opzione 'moduleResolution' è impostata su '{1}'.", + "Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled_5091": "Non è possibile disabilitare l'opzione 'preserveConstEnums' quando '{0}' è abilitato.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Non è possibile combinare l'opzione 'project' con file di origine in una riga di comando.", + "Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic_5070": "Non è possibile specificare l'opzione '--resolveJsonModule' quando 'moduleResolution' è impostato su 'classic'.", + "Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd_5071": "Non è possibile specificare l'opzione '--resolveJsonModule' quando 'module' è impostato su 'none', 'system' o 'umd'.", + "Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System_5105": "Non è possibile usare l'opzione 'verbatimModuleSyntax' quando 'module' è impostato su 'UMD', 'AMD' o 'System'.", + "Options_0_and_1_cannot_be_combined_6370": "Non è possibile combinare le opzioni '{0}' e '{1}'.", + "Options_Colon_6027": "Opzioni:", + "Output_Formatting_6256": "Formattazione dell'output", + "Output_compiler_performance_information_after_building_6615": "Restituisce informazioni sulle prestazioni del compilatore dopo la compilazione.", + "Output_directory_for_generated_declaration_files_6166": "Directory di output per i file di dichiarazione generati.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "Il file di output '{0}' non è stato compilato dal file di origine '{1}'.", + "Output_from_referenced_project_0_included_because_1_specified_1411": "L'output del progetto di riferimento '{0}' è incluso perché è stato specificato '{1}'", + "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412": "L'output del progetto di riferimento '{0}' è incluso perché il valore specificato per '--module' è 'none'", + "Output_more_detailed_compiler_performance_information_after_building_6632": "Restituisce informazioni più dettagliate sulle prestazioni del compilatore dopo la compilazione.", + "Overload_0_of_1_2_gave_the_following_error_2772": "L'overload {0} di {1},'{2}', ha restituito l'errore seguente.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Le firme di overload devono essere tutte astratte o tutte non astratte.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Le firme di overload devono essere tutte di ambiente o non di ambiente.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Le firme di overload devono essere tutte esportate o tutte non esportate.", + "Overload_signatures_must_all_be_optional_or_required_2386": "Le firme di overload devono essere tutte facoltative o obbligatorie.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "Le firme di overload devono essere tutte pubbliche, private o protette.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Il parametro '{0}' non può fare riferimento all'identificatore '{1}' dichiarato dopo di esso.", + "Parameter_0_cannot_reference_itself_2372": "Il parametro '{0}' non può fare riferimento a se stesso.", + "Parameter_0_implicitly_has_an_1_type_7006": "Il parametro '{0}' contiene implicitamente un tipo '{1}'.", + "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Il parametro '{0}' include implicitamente un tipo '{1}', ma è possibile dedurre un tipo migliore dall'utilizzo.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Il parametro '{0}' non si trova nella stessa posizione del parametro '{1}'.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108": "Il parametro '{0}' della funzione di accesso contiene o usa il nome '{1}' del modulo esterno {2}, ma non può essere rinominato.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107": "Il parametro '{0}' della funzione di accesso contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106": "Il parametro '{0}' della funzione di accesso contiene o usa il nome privato '{1}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Il parametro '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Il parametro '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Il parametro '{0}' del costruttore della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Il parametro '{0}' del costruttore della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Il parametro '{0}' del costruttore della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Il parametro '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Il parametro '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Il parametro '{0}' della funzione esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Il parametro '{0}' della funzione esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Il parametro '{0}' della funzione esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Il parametro '{0}' della firma dell'indice dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Il parametro '{0}' della firma dell'indice dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Il parametro '{0}' del metodo dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Il parametro '{0}' del metodo dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Il parametro '{0}' del metodo pubblico della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Il parametro '{0}' del metodo pubblico della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Il parametro '{0}' del metodo pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Il parametro '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Il parametro '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Il parametro '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "Il parametro non può contenere il punto interrogativo e l'inizializzatore.", + "Parameter_declaration_expected_1138": "È prevista la dichiarazione di parametro.", + "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051": "Il parametro include un nome ma non un tipo. Si intendeva '{0}: {1}'?", + "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012": "I modificatori di parametro possono esere usati solo in file TypeScript.", + "Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9011": "Il parametro deve avere un'annotazione di tipo esplicito con --isolatedDeclarations.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Il tipo di parametro del setter pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Il tipo di parametro del setter pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Il tipo di parametro del setter statico pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Il tipo di parametro del setter statico pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Esegue l'analisi in modalità strict e crea la direttiva \"use strict\" per ogni file di origine.", + "Part_of_files_list_in_tsconfig_json_1409": "Parte dell'elenco 'files' in tsconfig.json", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Il criterio '{0}' deve contenere al massimo un carattere '*'.", + "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386": "Gli intervalli delle prestazioni per '--Diagnostics' o '--extendedDiagnostics' non sono disponibili in questa sessione. Non è stato possibile trovare un'implementazione nativa dell'API Prestazioni Web.", + "Platform_specific_6912": "Specifico della piattaforma", + "Prefix_0_with_an_underscore_90025": "Anteporre un carattere di sottolineatura a '{0}'", + "Prefix_all_incorrect_property_declarations_with_declare_95095": "Aggiungere 'declare' come prefisso a tutte le dichiarazioni di proprietà non corrette", + "Prefix_all_unused_declarations_with_where_possible_95025": "Aggiungere a tutte le dichiarazioni non usate il prefisso '_', laddove possibile", + "Prefix_with_declare_95094": "Aggiungere il prefisso 'declare'", + "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449": "Conserva i valori importati non usati nell'output JavaScript che altrimenti verrebbe rimosso.", + "Print_all_of_the_files_read_during_the_compilation_6653": "Stampa tutti i file letti durante la compilazione.", + "Print_files_read_during_the_compilation_including_why_it_was_included_6631": "Stampa i file letti durante la compilazione e indica il motivo per cui sono stati inclusi.", + "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505": "Stampa i nomi dei file e il motivo per cui fanno parte della compilazione.", + "Print_names_of_files_part_of_the_compilation_6155": "Stampa i nomi dei file che fanno parte della compilazione.", + "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "Stampa i nomi dei file che fanno parte della compilazione, quindi arresta l'elaborazione.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "Stampa i nomi dei file generati che fanno parte della compilazione.", + "Print_the_compiler_s_version_6019": "Stampa la versione del compilatore.", + "Print_the_final_configuration_instead_of_building_1350": "Stampa la configurazione finale invece di eseguire la compilazione.", + "Print_the_names_of_emitted_files_after_a_compilation_6652": "Stampa i nomi dei file creati al termine di una compilazione.", + "Print_this_message_6017": "Stampa questo messaggio.", + "Private_accessor_was_defined_without_a_getter_2806": "La funzione di accesso privata è stata definita senza un getter.", + "Private_field_0_must_be_declared_in_an_enclosing_class_1111": "Il campo privato '{0}' deve essere dichiarato in una classe di inclusione.", + "Private_identifiers_are_not_allowed_in_variable_declarations_18029": "Gli identificatori privati non sono consentiti nelle dichiarazioni di variabili.", + "Private_identifiers_are_not_allowed_outside_class_bodies_18016": "Gli identificatori privati non sono consentiti all'esterno del corpo della classe.", + "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451": "Gli identificatori privati sono consentiti solo nei corpi di classe e possono essere usati solo come parte di una dichiarazione di un membro della classe, dell'accesso alle proprietà o sulla parte sinistra di un'espressione 'in'.", + "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028": "Gli identificatori privati sono disponibili solo se destinati a ECMAScript 2015 e versioni successive.", + "Private_identifiers_cannot_be_used_as_parameters_18009": "Non è possibile usare gli identificatori privati come parametri.", + "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105": "Non è possibile accedere al membro privato o protetto '{0}' in un parametro di tipo.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Project '{0}' can't be built because its dependency '{1}' has errors", + "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Project '{0}' can't be built because its dependency '{1}' was not built", + "Project_0_is_being_forcibly_rebuilt_6388": "Il progetto '{0}' è stato ricompilato forzatamente", + "Project_0_is_out_of_date_because_1_6420": "Il progetto '{0}' non è aggiornato perché {1}.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_6412": "Il progetto '{0}' non è aggiornato perché il file buildinfo '{1}' indica che il file '{2}' era un file radice di compilazione ma non più aggiornato.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419": "Il progetto '{0}' non è aggiornato perché il file buildinfo '{1}' indica che il programma deve segnalare errori.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "Il '{0}' del progetto non è aggiornato perché il file buildinfo '{1}' indica che alcune modifiche non sono state generate", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions_6406": "Il progetto '{0}' non è aggiornato perché il file buildinfo '{1}' indica che è presente una modifica in compilerOptions", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Il progetto '{0}' non è aggiornato perché la dipendenza '{1}' non è aggiornata", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Il progetto '{0}' non è aggiornato perché l'output '{1}' è meno recente dell'input '{2}'", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Il progetto '{0}' non è aggiornato perché il file di output '{1}' non esiste", + "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Il progetto '{0}' non è aggiornato perché l'output per il progetto è stato generato con la versione '{1}' che non corrisponde alla versione corrente '{2}'", + "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401": "Il progetto '{0}' non è aggiornato perché si è verificato un errore durante la lettura del file '{1}'", + "Project_0_is_up_to_date_6361": "Il progetto '{0}' è aggiornato", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Il progetto '{0}' è aggiornato perché l'input più recente '{1}' è meno recente dell'output '{2}'", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Project '{0}' è aggiornato ma deve aggiornare i timestamp dei file di output precedenti ai file di input", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Il progetto '{0}' è aggiornato con i file con estensione d.ts delle relative dipendenze", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "I riferimenti al progetto non possono formare un grafico circolare. Ciclo rilevato: {0}", + "Projects_6255": "Progetti", + "Projects_in_this_build_Colon_0_6355": "Progetti in questa compilazione: {0}", + "Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher_18045": "Le proprietà con il modificatore 'funzione di accesso' sono disponibili solo quando la destinazione è ECMAScript 2015 e versioni successive.", + "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267": "La proprietà '{0}' non può includere un inizializzatore perché è contrassegnata come astratta.", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "La proprietà '{0}' deriva da una firma dell'indice, quindi è necessario accedervi con ['{0}'].", + "Property_0_does_not_exist_on_type_1_2339": "La proprietà '{0}' non esiste nel tipo '{1}'.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La proprietà '{0}' non esiste nel tipo '{1}'. Si intendeva '{2}'?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "La proprietà '{0}' non esiste nel tipo '{1}'. Si intendeva accedere al membro statico '{2}'?", + "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "La proprietà '{0}' non esiste nel tipo '{1}'. È necessario modificare la libreria di destinazione? Provare a impostare l'opzione 'lib' del compilatore su '{2}' o versioni successive.", + "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812": "La proprietà '{0}' non esiste nel tipo '{1}'. Provare a modificare l'opzione del compilatore 'lib' per includere 'dom'.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817": "La proprietà '{0}' non include alcun inizializzatore e non viene assolutamente assegnata in un blocco statico di classe.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La proprietà '{0}' non include alcun inizializzatore e non viene assolutamente assegnata nel costruttore.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso get manca un'annotazione di tipo restituito.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso set manca un'annotazione di tipo di parametro.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048": "La proprietà '{0}' contiene implicitamente il tipo 'any', ma è possibile dedurre un tipo migliore per la funzione di accesso get dall'utilizzo.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049": "La proprietà '{0}' contiene implicitamente il tipo 'any', ma è possibile dedurre un tipo migliore per la funzione di accesso set dall'utilizzo.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La proprietà '{0}' nel tipo '{1}' non è assegnabile alla stessa proprietà nel tipo di base '{2}'.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La proprietà '{0}' nel tipo '{1}' non è assegnabile al tipo '{2}'.", + "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "La proprietà '{0}' nel tipo '{1}' fa riferimento a un membro diverso a cui non è possibile accedere dall'interno del tipo '{2}'.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "La proprietà '{0}' è dichiarata, ma il suo valore non viene mai letto.", + "Property_0_is_incompatible_with_index_signature_2530": "La proprietà '{0}' non è compatibile con la firma dell'indice.", + "Property_0_is_missing_in_type_1_2324": "Nel tipo '{1}' manca la proprietà '{0}'.", + "Property_0_is_missing_in_type_1_but_required_in_type_2_2741": "La proprietà '{0}' manca nel tipo '{1}', ma è obbligatoria nel tipo '{2}'.", + "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013": "La proprietà '{0}' non è accessibile all'esterno della classe '{1}' perché contiene un identificatore privato.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "La proprietà '{0}' è facoltativa nel tipo '{1}', ma obbligatoria nel tipo '{2}'.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "La proprietà '{0}' è privata e accessibile solo all'interno della classe '{1}'.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "La proprietà '{0}' è privata nel tipo '{1}', ma non nel tipo '{2}'.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446": "La proprietà '{0}' è protetta e accessibile solo tramite un'istanza della classe '{1}'. Si tratta di un'istanza della classe '{2}'.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "La proprietà '{0}' è protetta e accessibile solo all'interno della classe '{1}' e delle relative sottoclassi.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "La proprietà '{0}' è protetta, ma il tipo '{1}' non è una classe derivata da '{2}'.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "La proprietà '{0}' è protetta nel tipo '{1}', ma è pubblica non nel tipo '{2}'.", + "Property_0_is_used_before_being_assigned_2565": "La proprietà '{0}' viene usata prima dell'assegnazione.", + "Property_0_is_used_before_its_initialization_2729": "La proprietà '{0}' viene usata prima della relativa inizializzazione.", + "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568": "La proprietà '{0}' potrebbe non esistere nel tipo '{1}'. Si intendeva '{2}'?", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "La proprietà '{0}' dell'attributo spread JSX non è assegnabile alla proprietà di destinazione.", + "Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected_4094": "La proprietà '{0}' del tipo di classe anonima esportata potrebbe essere non privata o protetta.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "La proprietà '{0}' dell'interfaccia esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "La proprietà '{0}' dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411": "La proprietà '{0}' del tipo '{1}' non è assegnabile al tipo di indice '{2}' '{3}'.", + "Property_0_was_also_declared_here_2733": "In questo punto è dichiarata anche la proprietà '{0}'.", + "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612": "La proprietà '{0}' sovrascriverà la proprietà di base in '{1}'. Se questo comportamento è intenzionale, aggiungere un inizializzatore; in caso contrario, aggiungere un modificatore 'declare' o rimuovere la dichiarazione ridondante.", + "Property_assignment_expected_1136": "È prevista l'assegnazione di proprietà.", + "Property_destructuring_pattern_expected_1180": "È previsto il criterio di destrutturazione della proprietà.", + "Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9012": "La proprietà deve avere un'annotazione di tipo esplicito con --isolatedDeclarations.", + "Property_or_signature_expected_1131": "È prevista la proprietà o la firma.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Il valore della proprietà può essere solo un valore letterale stringa, un valore letterale numerico, 'true', 'false', 'null', un valore letterale di oggetto o un valore letterale di matrice.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_6179": "Fornisce supporto completo per elementi iterabili in 'for-of', estensione e destrutturazione quando la destinazione è 'ES5'.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Il metodo pubblico '{0}' della classe esportata ha o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Il metodo pubblico '{0}' della classe esportata ha o usa il nome '{1}' del modulo privato '{2}'.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Il metodo pubblico '{0}' della classe esportata ha o usa il nome privato '{1}'.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "La proprietà pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominata.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "La proprietà pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "La proprietà pubblica '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Il metodo statico pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominato.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Il metodo statico pubblico '{0}' della classe esportata ha o usa il nome '{1}' del modulo privato '{2}'.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Il metodo statico pubblico '{0}' della classe esportata ha o usa il nome privato '{1}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "La proprietà statica pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2} ma non può essere rinominata.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "La proprietà statica pubblica '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "La proprietà statica pubblica '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032": "Il nome completo '{0}' non è consentito se non si specifica un parametro '@param {object} {1}' iniziale.", + "Raise_an_error_when_a_function_parameter_isn_t_read_6676": "Genera un errore quando un parametro di funzione non viene letto.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Genera un errore in caso di espressioni o dichiarazioni con tipo 'any' implicito.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Genera un errore in caso di espressioni 'this con un tipo 'any' implicito.", + "Range_out_of_order_in_character_class_1517": "Intervallo non in ordine nella classe di caratteri.", + "Re_exporting_a_type_when_0_is_enabled_requires_using_export_type_1205": "Riesportare un tipo quando '{0}' è abilitato richiede l'uso di 'export type'.", + "React_components_cannot_include_JSX_namespace_names_2639": "I componenti React non possono includere nomi di spazio dei nomi JSX", + "Redirect_output_structure_to_the_directory_6006": "Reindirizza la struttura di output alla directory.", + "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617": "Riduce il numero di progetti caricati automaticamente da TypeScript.", + "Referenced_project_0_may_not_disable_emit_6310": "Il progetto di riferimento '{0}' non può disabilitare la creazione.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Il progetto di riferimento '{0}' deve includere l'impostazione \"composite\": true.", + "Referenced_via_0_from_file_1_1400": "Riferimento tramite '{0}' dal file '{1}'", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2834": "I percorsi di importazione relativi necessitano di estensioni di file esplicite nelle importazioni ECMAScript quando '--moduleResolution' è 'node16' o 'nodenext'. Provare ad aggiungere un'estensione al percorso di importazione.", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2835": "I percorsi di importazione relativi necessitano di estensioni di file esplicite nelle importazioni ECMAScript quando '--moduleResolution' è 'node16' o 'nodenext'. Si intendeva '{0}'?", + "Remove_a_list_of_directories_from_the_watch_process_6628": "Rimuove un elenco di directory dal processo dell'espressione di controllo.", + "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629": "Rimuove un elenco di file dall'elaborazione della modalità espressione di controllo.", + "Remove_all_unnecessary_override_modifiers_95163": "Rimuovere tutti i modificatori 'override' non necessari", + "Remove_all_unnecessary_uses_of_await_95087": "Rimuovere tutti gli utilizzi non necessari di 'await'", + "Remove_all_unreachable_code_95051": "Rimuovere tutto il codice non eseguibile", + "Remove_all_unused_labels_95054": "Rimuovere tutte le etichette inutilizzate", + "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115": "Rimuovere le parentesi graffe da tutti i corpi della funzione arrow con problemi specifici", + "Remove_braces_from_arrow_function_95060": "Rimuovere le parentesi graffe dalla funzione arrow", + "Remove_braces_from_arrow_function_body_95112": "Rimuovere le parentesi graffe dal corpo della funzione arrow", + "Remove_import_from_0_90005": "Rimuovere l'importazione da '{0}'", + "Remove_override_modifier_95161": "Rimuovere il modificatore 'override'", + "Remove_parentheses_95126": "Rimuovere le parentesi", + "Remove_template_tag_90011": "Rimuovere il tag template", + "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618": "Rimuove il limite di 20 MB per le dimensioni totali del codice sorgente relativo ai file JavaScript nel server di linguaggio TypeScript.", + "Remove_type_from_import_declaration_from_0_90055": "Rimuovi 'type' dalla dichiarazione di importazione da \"{0}\"", + "Remove_type_from_import_of_0_from_1_90056": "Rimuovi 'type' dall'importazione di '{0}' da \"{1}\"", + "Remove_type_parameters_90012": "Rimuovere i parametri di tipo", + "Remove_unnecessary_await_95086": "Rimuovere l'elemento 'await' non necessario", + "Remove_unreachable_code_95050": "Rimuovere il codice non eseguibile", + "Remove_unused_declaration_for_Colon_0_90004": "Rimuovere la dichiarazione inutilizzata per: '{0}'", + "Remove_unused_declarations_for_Colon_0_90041": "Rimuovere le dichiarazioni inutilizzate per: '{0}'", + "Remove_unused_destructuring_declaration_90039": "Rimuovere la dichiarazione di destrutturazione inutilizzata", + "Remove_unused_label_95053": "Rimuovere l'etichetta inutilizzata", + "Remove_variable_statement_90010": "Rimuovere l'istruzione di variabile", + "Rename_param_tag_name_0_to_1_95173": "Cambiane il nome '{0}' del tag '@param' in '{1}'", + "Replace_0_with_Promise_1_90036": "Sostituire '{0}' con 'Promise<{1}>'", + "Replace_all_unused_infer_with_unknown_90031": "Sostituire tutti gli elementi 'infer' inutilizzati con 'unknown'", + "Replace_import_with_0_95015": "Sostituire l'importazione con '{0}'.", + "Replace_infer_0_with_unknown_90030": "Sostituire 'infer {0}' con 'unknown'", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Segnala l'errore quando non tutti i percorsi del codice nella funzione restituiscono un valore.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Segnala errori per i casi di fallthrough nell'istruzione switch.", + "Report_errors_in_js_files_8019": "Segnala gli errori presenti nei file con estensione js.", + "Report_errors_on_unused_locals_6134": "Segnala errori relativi a variabili locali non usate.", + "Report_errors_on_unused_parameters_6135": "Segnala errori relativi a parametri non usati.", + "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719": "Richiede un'annotazione sufficiente sulle esportazioni in modo che altri strumenti possano generare in modo semplice i file di dichiarazione.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717": "Richiedere alle proprietà non dichiarate da firme dell'indice di usare gli accessi agli elementi.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "I parametri di tipo obbligatori potrebbero non seguire i parametri di tipo facoltativi.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La risoluzione per il modulo '{0}' è stata trovata nella cache dal percorso '{1}'.", + "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "La risoluzione per la direttiva '{0}' del riferimento al tipo è stata trovata nella cache dal percorso '{1}'.", + "Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_i_6277": "Risoluzione del nome non relativo non riuscita; il tentativo di utilizzare le funzionalità moderne di risoluzione dei nodi è disabilitato per verificare se è necessario aggiornare la configurazione della libreria npm.", + "Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_ne_6279": "Risoluzione del nome non relativo non riuscita; è in corso un tentativo con '--moduleResolution bundler' per verificare se il progetto potrebbe richiedere l'aggiornamento della configurazione.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Risolvere 'keyof' solo in nomi di proprietà con valori stringa (senza numeri o simboli).", + "Resolved_under_condition_0_6414": "Risolto nella condizione '{0}'.", + "Resolving_in_0_mode_with_conditions_1_6402": "Risoluzione in modalità {0} con condizioni {1}.", + "Resolving_module_0_from_1_6086": "======== Risoluzione del modulo '{0}' da '{1}'. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Verrà eseguita la risoluzione del nome del modulo '{0}' relativo all'URL di base '{1}' - '{2}'.", + "Resolving_real_path_for_0_result_1_6130": "Risoluzione del percorso reale per '{0}'. Risultato: '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_6242": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file '{1}' con directory radice '{2}'. ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file '{1}' e directory radice non impostata. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file non impostato con directory radice '{1}'. ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== Risoluzione della direttiva '{0}' del riferimento al tipo contenente il file non impostato con directory radice non impostata. ========", + "Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_no_6265": "Risoluzione della direttiva di riferimento al tipo per il programma che specifica typeRoot personalizzati. La ricerca nella cartella 'node_modules' verrà ignorata.", + "Resolving_with_primary_search_path_0_6121": "La risoluzione verrà eseguita con il percorso di ricerca primaria '{0}'.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Il parametro rest '{0}' contiene implicitamente un tipo 'any[]'.", + "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047": "Il parametro rest '{0}' contiene implicitamente un tipo 'any[]', ma è possibile dedurre un tipo migliore dall'utilizzo.", + "Rest_types_may_only_be_created_from_object_types_2700": "È possibile creare tipi rest solo da tipi di oggetto.", + "Return_type_annotation_circularly_references_itself_2577": "L'annotazione di tipo restituito contiene un riferimento circolare a se stessa.", + "Return_type_must_be_inferred_from_a_function_95149": "Il tipo restituito deve essere dedotto da una funzione", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "Il tipo restituito della firma di chiamata dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "Il tipo restituito della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "Il tipo restituito della firma del costruttore dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "Il tipo restituito della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "Il tipo restituito della firma del costruttore deve essere assegnabile al tipo di istanza della classe.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "Il tipo restituito della funzione esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "Il tipo restituito della funzione esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "Il tipo restituito della funzione esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "Il tipo restituito della firma dell'indice dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Il tipo restituito della firma dell'indice dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Il tipo restituito del metodo dell'interfaccia esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Il tipo restituito del metodo dell'interfaccia esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Il tipo restituito del getter pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno {2}, ma non può essere rinominato.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Il tipo restituito del getter pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Il tipo restituito del getter pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome privato '{0}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno '{2}', ma non può essere rinominato.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Il tipo restituito del getter statico pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome privato '{0}'.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395": "Il riutilizzo della risoluzione del modulo '{0}' da '{1}' che è stato trovato nella cache dal percorso '{2}' non è stato risolto.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393": "Il riutilizzo della risoluzione del modulo '{0}' da '{1}' che è stato trovato nella cache dal percorso '{2}' è stato risolto in '{3}'.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394": "Il riutilizzo della risoluzione del modulo '{0}' da '{1}' è stato trovato nella cache dal percorso '{2}'. È stato risolto correttamente in '{3}' con ID pacchetto '{4}'.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389": "Il riutilizzo della risoluzione del modulo '{0}' da '{1}' del programma precedente non è stato risolto.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183": "Il riutilizzo della risoluzione del modulo '{0}' da '{1}' del programma precedente è stato risolto in '{2}'.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184": "Il riutilizzo della risoluzione del modulo '{0}' da '{1}' del programma precedente è stato risolto in '{2}' con l'ID pacchetto '{3}'.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398": "Il riutilizzo della risoluzione della direttiva per il tipo di riferimento '{0}' da '{1}' che è stato trovato nella cache dal percorso '{2}' non è stato risolto.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396": "Il riutilizzo della risoluzione della direttiva per il tipo di riferimento '{0}' da '{1}' che è stato trovato nella cache dal percorso '{2}' è stato risolto in '{3}'.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397": "Il riutilizzo della risoluzione della direttiva per il tipo di riferimento '{0}' da '{1}' che è stato trovato nella cache dal percorso '{2}' è stato risolto in '{3}' con ID pacchetto '{4}'.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392": "Il riutilizzo della risoluzione della direttiva riferimento di tipo '{0}' da '{1}' del programma precedente non è stato risolto.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390": "Il riutilizzo della risoluzione della direttiva riferimento di tipo '{0}' da '{1}' del programma precedente è stato risolto correttamente in '{2}'.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391": "Il riutilizzo della risoluzione della direttiva per il tipo di riferimento '{0}' da '{1}' del programma precedente è stato risolto in '{2}' con l'ID pacchetto '{3}'.", + "Rewrite_all_as_indexed_access_types_95034": "Riscrivere tutti come tipi di accesso indicizzati", + "Rewrite_as_the_indexed_access_type_0_90026": "Riscrivere come tipo di accesso indicizzato '{0}'", + "Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_i_6421": "Riscrivere le estensioni di file \".ts\", \".tsx\", \".mts\" e \".cts\" nei percorsi di importazione relativi dell'equivalente JavaScript nei file di output.", + "Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish_2869": "L'operando destro di ?? non è raggiungibile perché l'operando sinistro non è mai nullish.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Non è possibile determinare la directory radice. I percorsi di ricerca primaria verranno ignorati.", + "Root_file_specified_for_compilation_1427": "File radice specificato per la compilazione", + "STRATEGY_6039": "STRATEGIA", + "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Salva i file .tsbuildinfo per consentire la compilazione incrementale dei progetti.", + "Saw_non_matching_condition_0_6405": "Visualizzata la condizione di corrispondenza '{0}'.", + "Scoped_package_detected_looking_in_0_6182": "Il pacchetto con ambito è stato rilevato. Verrà eseguita una ricerca in '{0}'", + "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418": "Ricerca di estensioni di fallback in tutte le directory node_modules predecessori: {0}.", + "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417": "Ricerca di estensioni preferite in tutte le directory node_modules predecessori: {0}.", + "Selection_is_not_a_valid_statement_or_statements_95155": "La selezione non corrisponde a una o più istruzioni valide", + "Selection_is_not_a_valid_type_node_95133": "La selezione non corrisponde a un nodo di tipo valido", + "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705": "Imposta la versione del linguaggio JavaScript per il codice JavaScript creato e include le dichiarazioni di libreria compatibili.", + "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654": "Imposta la lingua della messaggistica da TypeScript. Non influisce sulla creazione.", + "Set_the_module_option_in_your_configuration_file_to_0_95099": "Impostare l'opzione 'module' nel file di configurazione su '{0}'", + "Set_the_newline_character_for_emitting_files_6659": "Imposta il carattere di nuova riga per la creazione di file.", + "Set_the_target_option_in_your_configuration_file_to_0_95098": "Impostare l'opzione 'target' nel file di configurazione su '{0}'", + "Setters_cannot_return_a_value_2408": "I setter non possono restituire un valore.", + "Show_all_compiler_options_6169": "Mostra tutte le opzioni del compilatore.", + "Show_diagnostic_information_6149": "Mostra le informazioni di diagnostica.", + "Show_verbose_diagnostic_information_6150": "Mostra le informazioni di diagnostica dettagliate.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Mostra gli elementi che vengono compilati (o eliminati, se specificati con l'opzione '--clean')", + "Signature_0_must_be_a_type_predicate_1224": "La firma '{0}' deve essere un predicato di tipo.", + "Signature_declarations_can_only_be_used_in_TypeScript_files_8017": "Le dichiarazioni firma possono essere usate solo in file TypeScript.", + "Skip_building_downstream_projects_on_error_in_upstream_project_6640": "Ignorare la compilazione di progetti downstream in base a un errore nel progetto upstream.", + "Skip_type_checking_all_d_ts_files_6693": "Ignora il controllo del tipo di tutti i file .d.ts.", + "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692": "Ignora il controllo dei tipi dei file .d.ts inclusi con TypeScript.", + "Skip_type_checking_of_declaration_files_6012": "Ignora il controllo del tipo dei file di dichiarazione.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Skipping build of project '{0}' because its dependency '{1}' has errors", + "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382": "Skipping build of project '{0}' because its dependency '{1}' was not built", + "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164": "Vine ignorato il modulo '{0}' che sembra un URI assoluto, tipi di file di destinazione: {1}.", + "Source_from_referenced_project_0_included_because_1_specified_1414": "L'origine del progetto di riferimento '{0}' è inclusa perché è stato specificato '{1}'", + "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415": "L'origine del progetto di riferimento '{0}' è inclusa perché il valore specificato per '--module' è 'none'", + "Source_has_0_element_s_but_target_allows_only_1_2619": "L'origine contiene {0} elemento/i ma la destinazione ne consente solo {1}.", + "Source_has_0_element_s_but_target_requires_1_2618": "L'origine contiene {0} elemento/i ma la destinazione ne richiede {1}.", + "Source_provides_no_match_for_required_element_at_position_0_in_target_2623": "L'origine non fornisce alcuna corrispondenza per l'elemento obbligatorio alla posizione {0} nella destinazione.", + "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624": "L'origine non fornisce alcuna corrispondenza per l'elemento variadic alla posizione {0} nella destinazione.", + "Specify_ECMAScript_target_version_6015": "Specifica la versione di destinazione di ECMAScript.", + "Specify_JSX_code_generation_6080": "Specifica la generazione del codice JSX.", + "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679": "Consente di specificare un file che aggrega tutti gli output in un unico file JavaScript. Se 'declaration' è true, designa anche un file che aggrega tutto l'output dei file .d.ts.", + "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641": "Consente di specificare un elenco di criteri GLOB che corrispondono ai file da includere nella compilazione.", + "Specify_a_list_of_language_service_plugins_to_include_6681": "Consente di specificare un elenco di plug-in da includere del servizio di linguaggio.", + "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651": "Consente di specificare un set di file di dichiarazione della libreria aggregati che descrivono l'ambiente di runtime di destinazione.", + "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680": "Consente di specificare un set di voci che eseguono di nuovo il mapping delle direttive import nei percorsi di ricerca aggiuntivi.", + "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687": "Consente di specificare un array di oggetti che indicano percorsi per i progetti. Usato nei riferimenti dei progetti.", + "Specify_an_output_folder_for_all_emitted_files_6678": "Consente di specificare una cartella di output per tutti i file creati.", + "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718": "Specificare il comportamento di creazione/controllo per le importazioni usate solo per i tipi.", + "Specify_file_to_store_incremental_compilation_information_6380": "Specificare il file per l'archiviazione delle informazioni di compilazione incrementale", + "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658": "Consente di specificare in che modo TypeScript cerca un file da un identificatore di modulo specifico.", + "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714": "Consente di specifica la modalità di controllo delle directory nei sistemi in cui non sono presenti funzionalità ricorsive di controllo dei file.", + "Specify_how_the_TypeScript_watch_mode_works_6715": "Consente di specificare il funzionamento della modalità espressione di controllo TypeScript.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "Specificare i file di libreria da includere nella compilazione.", + "Specify_module_code_generation_6016": "Specifica la generazione del codice del modulo.", + "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649": "Specifica l'identificatore di modulo usato per importare funzioni factory JSX quando si usa 'jsx: react-jsx*'.", + "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710": "Consente di specificare più cartelle che fungono da './node_modules/@types'.", + "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633": "Consente di specificare uno o più percorsi o riferimenti al modulo del nodo ai file di configurazione di base da cui vengono ereditate le impostazioni.", + "Specify_options_for_automatic_acquisition_of_declaration_files_6709": "Consente di specificare le opzioni per l'acquisizione automatica dei file di dichiarazione.", + "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227": "Specifica la strategia per la creazione di un'espressione di controllo di polling quando non viene creata con eventi del file system: 'FixedInterval' (impostazione predefinita), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'.", + "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226": "Specifica la strategia per il controllo della directory in piattaforme che non supportano il controllo ricorsivo in modo nativo: 'UseFsEvents' (impostazione predefinita), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'.", + "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225": "Specifica la strategia per il controllo del file: 'FixedPollingInterval' (impostazione predefinita), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'.", + "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648": "Consente di specificare il riferimento al fragmento JSX usato per i frammenti quando la destinazione è la creazione JSX React, ad esempio 'React.Fragment' o 'Fragment'.", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Consente di specificare la funzione della factory JSX da usare quando la destinazione è la creazione JSX 'react', ad esempio 'React.createElement' o 'h'.", + "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647": "Consente di specificare la funzione della factory JSX da usare quando la destinazione è la creazione JSX React, ad esempio 'React.createElement' o 'h'.", + "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034": "Specificare la funzione della factory di frammenti JSX da usare quando la destinazione è la creazione JSX 'react' quando è specificata l'opzione del compilatore 'jsxFactory', ad esempio 'Fragment'.", + "Specify_the_base_directory_to_resolve_non_relative_module_names_6607": "Specificare la directory di base per risolvere i nomi di modulo non relativi.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Specifica la sequenza di fine riga da usare per la creazione dei file, ovvero 'CRLF' (in DOS) o 'LF' (in UNIX).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "Specifica il percorso in cui il debugger deve trovare i file TypeScript invece dei percorsi di origine.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655": "Specifica il percorso in cui il debugger deve trovare i file map invece dei percorsi generati.", + "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656": "Consente di specificare la profondità massima della cartella utilizzata per il controllo dei file JavaScript da 'node_modules'. Applicabile solo con 'allowJs'.", + "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238": "Specificare l'identificatore di modulo da usare da cui importare le funzioni di factory 'jsx' e 'jsxs', ad esempio react", + "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686": "Consente di specificare l'oggetto richiamato per 'createElement'. Si applica quando la destinazione è la creazione JSX `react`.", + "Specify_the_output_directory_for_generated_declaration_files_6613": "Consente di specificare la directory di output per i file di dichiarazione generati.", + "Specify_the_path_to_tsbuildinfo_incremental_compilation_file_6707": "Consente di specificare il percorso per il file di compilazione incrementale .tsbuildinfo.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Specifica la directory radice dei file di input. Usare per controllare la struttura della directory di output con --outDir.", + "Specify_the_root_folder_within_your_source_files_6690": "Consente di specificare la cartella radice nei file di origine.", + "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695": "Consente di specificare il percorso radice per consentire ai debugger di trovare il codice sorgente di riferimento.", + "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711": "Consente di specificare i tipi di nomi dei pacchetti da includere senza farvi riferimento in un file di origine.", + "Specify_what_JSX_code_is_generated_6646": "Consente di specificare il codice JSX generato.", + "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634": "Consente di specificare l'approccio che il watcher deve adottare se il sistema esaurisce i watcher di file nativi.", + "Specify_what_module_code_is_generated_6657": "Consente di specificare il codice del modulo generato.", + "Split_all_invalid_type_only_imports_1367": "Dividere tutte le importazioni solo di tipi non valide", + "Split_into_two_separate_import_declarations_1366": "Dividere in due dichiarazioni di importazione separate", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "L'operatore Spread in espressioni 'new' è disponibile solo se destinato a ECMAScript 5 e versioni successive.", + "Spread_types_may_only_be_created_from_object_types_2698": "È possibile creare tipi spread solo da tipi di oggetto.", + "Starting_compilation_in_watch_mode_6031": "Avvio della compilazione in modalità espressione di controllo...", + "Statement_expected_1129": "È prevista l'istruzione.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "Le istruzioni non sono consentite in contesti di ambiente.", + "Static_members_cannot_reference_class_type_parameters_2302": "I membri statici non possono fare riferimento a parametri di tipo classe.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "La proprietà statica '{0}' è in conflitto con la proprietà predefinita 'Function.{0}' della funzione del costruttore '{1}'.", + "String_literal_expected_1141": "È previsto un valore letterale stringa.", + "String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es_18057": "I nomi di importazione ed esportazione di valori letterali stringa non sono supportati quando il flag '--module' è impostato su 'es2015' o 'es2020'.", + "String_literal_with_double_quotes_expected_1327": "È previsto un valore letterale stringa con virgolette doppie.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Applica stili a errori e messaggi usando colore e contesto (sperimentale).", + "Subpattern_flags_must_be_present_when_there_is_a_minus_sign_1504": "Quando è presente un segno meno, devono essere presenti flag di criteri secondari.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Le dichiarazioni di proprietà successive devono essere dello stesso tipo. La proprietà '{0}' deve essere di tipo '{1}', ma qui è di tipo '{2}'.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Le dichiarazioni di variabili successive devono essere dello stesso tipo. La variabile '{0}' deve essere di tipo '{1}', mentre è di tipo '{2}'.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Il tipo della sostituzione '{0}' per il criterio '{1}' non è corretto. È previsto 'string', ma è stato ottenuto '{2}'.", + "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062": "La sostituzione '{0}' nel criterio '{1}' può contenere al massimo un carattere '*'.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "Le sostituzioni per il criterio '{0}' devono essere una matrice.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "Le sostituzioni per il criterio '{0}' non devono essere una matrice vuota.", + "Successfully_created_a_tsconfig_json_file_6071": "La creazione di un file tsconfig.json è riuscita.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "Le chiamate super non sono consentite all'esterno di costruttori o nelle funzioni annidate all'interno di costruttori.", + "Suppress_excess_property_checks_for_object_literals_6072": "Elimina i controlli delle proprietà in eccesso per i valori letterali di oggetto.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Non visualizza gli errori noImplicitAny per gli oggetti di indicizzazione in cui mancano le firme dell'indice.", + "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703": "Disabilita gli errori 'noImplicitAny' durante l'indicizzazione di oggetti in cui mancano le firme dell'indice.", + "Switch_each_misused_0_to_1_95138": "Cambiare ogni '{0}' non usato correttamente in '{1}'", + "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704": "Chiama in modo sincrono i callback e aggiorna lo stato dei watcher di directory in piattaforme che non supportano il controllo ricorsivo in modo nativo.", + "Syntax_Colon_0_6023": "Sintassi: {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "Con il tag '{0}' sono previsti almeno '{1}' argomenti, ma la factory JSX '{2}' ne fornisce al massimo '{3}'.", + "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "Le espressioni di modello con tag non sono consentite in una catena facoltativa.", + "Target_allows_only_0_element_s_but_source_may_have_more_2621": "La destinazione consente solo {0} elemento/i ma l'origine potrebbe contenerne di più.", + "Target_requires_0_element_s_but_source_may_have_fewer_2620": "La destinazione richiede {0} elemento/i ma l'origine potrebbe contenerne di meno.", + "Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1_2849": "La firma di destinazione fornisce un numero insufficiente di argomenti. {0} o più elementi previsti, ma {1} effettivi.", + "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "Il modificatore '{0}' può essere usato solo in file TypeScript.", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "Non è possibile applicare l'operatore '{0}' al tipo 'symbol'.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "L'operatore '{0}' non è consentito per i tipi booleani. Provare a usare '{1}'.", + "The_0_property_of_an_async_iterator_must_be_a_method_2768": "La proprietà '{0}' di un iteratore asincrono deve essere un metodo.", + "The_0_property_of_an_iterator_must_be_a_method_2767": "La proprietà '{0}' di un iteratore deve essere un metodo.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "Il tipo 'Object' può essere assegnato a un numero molto limitato di altri tipi. Si intendeva usare il tipo 'any'?", + "The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously_1502": "Non è possibile impostare contemporaneamente i flag Unicode (u) e Unicode Sets (v).", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_func_2496": "Non è possibile fare riferimento all'oggetto 'arguments' in una funzione arrow in ES5. Provare a usare un'espressione di funzione standard.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_sta_2522": "Non è possibile fare riferimento all'oggetto 'arguments' in un metodo o una funzione asincrona in ES5. Provare a usare un metodo o una funzione standard.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Il corpo di un'istruzione 'if' non può essere l'istruzione vuota.", + "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793": "La chiamata sarebbe riuscita rispetto a questa implementazione, ma le firme di implementazione degli overload non sono visibili esternamente.", + "The_character_set_of_the_input_files_6163": "Set di caratteri dei file di input.", + "The_containing_arrow_function_captures_the_global_value_of_this_7041": "La funzione arrow contenitore acquisisce il valore globale di 'this'.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Il corpo del modulo o la funzione che contiene è troppo grande per l'analisi del flusso di controllo.", + "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309": "Il file corrente è un modulo CommonJS e non può usare 'await' al livello principale.", + "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479": "Il file corrente è un modulo CommonJS le cui importazioni genereranno chiamate 'require'. Tuttavia, il file a cui si fa riferimento è un modulo ECMAScript e non può essere importato con 'require'. Provare a scrivere una chiamata 'import(\"{0}\")' dinamica.", + "The_current_host_does_not_support_the_0_option_5001": "L'host corrente non supporta l'opzione '{0}'.", + "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018": "La dichiarazione di '{0}' che probabilmente si intende usare viene definita in questo punto", + "The_declaration_was_marked_as_deprecated_here_2798": "La dichiarazione è stata contrassegnata come deprecata in questo punto.", + "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500": "Il tipo previsto proviene dalla proprietà '{0}', dichiarata in questo punto nel tipo '{1}'", + "The_expected_type_comes_from_the_return_type_of_this_signature_6502": "Il tipo previsto proviene dal tipo restituito di questa firma.", + "The_expected_type_comes_from_this_index_signature_6501": "Il tipo previsto proviene da questa firma dell'indice.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "L'espressione di un'assegnazione di esportazione deve essere un identificatore o un nome completo in un contesto di ambiente.", + "The_file_is_in_the_program_because_Colon_1430": "Motivo per cui il file è presente nel programma:", + "The_files_list_in_config_file_0_is_empty_18002": "L'elenco 'files' nel file config '{0}' è vuoto.", + "The_first_export_default_is_here_2752": "In questo punto è presente il valore predefinito per la prima esportazione.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Il primo parametro del metodo 'then' di una promessa deve essere un callback.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Il tipo globale 'JSX.{0}' non può contenere più di una proprietà.", + "The_implementation_signature_is_declared_here_2750": "In questo punto viene dichiarata la firma di implementazione.", + "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "La metaproprietà' Import. meta ' non è consentita per i file che vengono compilati nell'output di CommonJS.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "La metaproprietà 'import.meta' è consentita solo quando l'opzione '--module' è 'es2020', 'es2022', 'esnext', 'system', 'node16', 'node18' o 'nodenext'.", + "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Non è possibile assegnare un nome al tipo derivato di '{0}' senza un riferimento a '{1}'. È probabile che non sia portabile. È necessaria un'annotazione di tipo.", + "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Il tipo dedotto di '{0}' fa riferimento a un tipo con una struttura ciclica che non può essere facilmente serializzata. È necessaria un'annotazione di tipo.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Il tipo dedotto di '{0}' fa riferimento a un tipo '{1}' non accessibile. È necessaria un'annotazione di tipo.", + "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056": "Il tipo dedotto di questo nodo supera la lunghezza massima serializzata dal compilatore. È necessaria un'annotazione di tipo esplicita.", + "The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_n_2850": "L'inizializzatore di una dichiarazione 'using' deve essere un oggetto con un metodo '[Symbol.dispose]()' oppure essere 'null' o 'undefined'.", + "The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_2851": "L'inizializzatore di una dichiarazione 'await using' deve essere un oggetto con un metodo '[Symbol.asyncDispose]()' o '[Symbol.dispose]5D;()' oppure essere 'null' o 'undefined'.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "L'intersezione '{0}' è stata ridotta a 'never' perché la proprietà '{1}' esiste in più costituenti ed è privata in alcuni.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "L'intersezione '{0}' è stata ridotta a 'never' perché in alcuni costituenti della proprietà '{1}' sono presenti tipi in conflitto.", + "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795": "La parola chiave 'intrinsic' può essere usata solo per dichiarare tipi intrinseci forniti dal compilatore.", + "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016": "Per usare frammenti JSX con l'opzione del compilatore 'jsxFactory', è necessario specificare l'opzione del compilatore 'jsxFragmentFactory'.", + "The_last_overload_gave_the_following_error_2770": "L'ultimo overload ha restituito l'errore seguente.", + "The_last_overload_is_declared_here_2771": "In questo punto viene dichiarato l'ultimo overload.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte sinistra di un'espressione 'for...in' non può essere un criterio di destrutturazione.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493": "La parte sinistra di un'istruzione 'for...in' non può essere una dichiarazione 'using'.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494": "La parte sinistra di un'istruzione 'for...in' non può essere una dichiarazione 'await using'.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Nella parte sinistra di un'espressione 'for...in' non è possibile usare un'annotazione di tipo.", + "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780": "La parte sinistra di un'istruzione 'for...in' non può essere un accesso a proprietà facoltativo.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "La parte sinistra di un'istruzione 'for...in' deve essere una variabile o un accesso a proprietà.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La parte sinistra di un'espressione 'for...in' deve essere di tipo 'string' o 'any'.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "Nella parte sinistra di un'espressione 'for...of' non è possibile usare un'annotazione di tipo.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781": "La parte sinistra di un'istruzione 'for...of' non può essere un accesso a proprietà facoltativo.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106": "La parte sinistra di un'istruzione 'for...of' non può essere 'async'.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La parte sinistra di un'istruzione 'for...of' deve essere una variabile o un accesso a proprietà.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "La parte sinistra di un'operazione aritmetica deve essere di tipo 'any', 'number', 'bigint' o un tipo enumerazione.", + "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "La parte sinistra di un'espressione di assegnazione non può essere un accesso a proprietà facoltativo.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La parte sinistra di un'espressione di assegnazione deve essere una variabile o un accesso a proprietà.", + "The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_2860": "La parte sinistra di un'espressione 'instanceof' deve essere assegnabile al primo argomento del metodo '[Symbol.hasInstance]' della parte destra.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La parte sinistra di un'espressione 'instanceof' deve essere di tipo 'any' oppure essere un tipo di oggetto o un parametro di tipo.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Impostazioni locali usate per la visualizzazione di messaggi all'utente, ad esempio 'it-it'", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Profondità massima delle dipendenze per la ricerca in node_modules e il caricamento dei file JavaScript.", + "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "L'operando di un operatore 'delete' non può essere un identificatore privato.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "L'operando di un operatore 'delete' non può essere una proprietà di sola lettura.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "L'operando di un operatore 'delete' deve essere un riferimento a proprietà.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "L'operando di un operatore 'delete' deve essere facoltativo.", + "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "L'operando di un operatore di incremento o decremento non può essere un accesso a proprietà facoltativo.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "L'operando di un operatore di incremento o decremento deve essere una variabile o un accesso a proprietà.", + "The_parser_expected_to_find_a_1_to_match_the_0_token_here_1007": "In questo punto il parser dovrebbe trovare un simbolo '{1}' abbinato al token '{0}'.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209": "La radice del progetto è ambigua, ma è necessaria per risolvere i '{0}' delle voci della mappa di esportazione nel file '{1}'. Specificare l'opzione del compilatore 'rootDir' per disambiguare.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210": "La radice del progetto è ambigua, ma è necessaria per risolvere i '{0}' delle voci della mappa di importazione nel file '{1}'. Specificare l'opzione del compilatore 'rootDir' per disambiguare.", + "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014": "Non è possibile accedere alla proprietà '{0}' nel tipo '{1}' all'interno di questa classe perché è nascosta da un altro identificatore privato con la stessa ortografia.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Il tipo restituito di una funzione di espressione Decorator del parametro deve essere 'void' o 'any'.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Il tipo restituito di una funzione di espressione Decorator della proprietà deve essere 'void' o 'any'.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Il tipo restituito di una funzione asincrona deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065": "Il tipo restituito di un metodo o una funzione asincrona deve essere il tipo globale Promise.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "Il tipo restituito di un metodo o una funzione asincrona deve essere il tipo globale Promise. Si intendeva scrivere 'Promise<{0}>'?", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "La parte destra di un'istruzione 'for...in' deve essere di tipo 'any' oppure essere un tipo di oggetto o un parametro di tipo, ma in questo caso il tipo è '{0}'.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "La parte destra di un'operazione aritmetica deve essere di tipo 'any', 'number', 'bigint' o un tipo enumerazione.", + "The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_2359": "La parte destra di un'espressione 'instanceof' deve essere di tipo 'any', una classe, una funzione o un altro tipo assegnabile al tipo di interfaccia 'Function' oppure un tipo di oggetto con un metodo 'Symbol.hasInstance'.", + "The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression_2848": "La parte destra di un'espressione 'instanceof' non deve essere un'espressione di creazione di un'istanza.", + "The_root_value_of_a_0_file_must_be_an_object_5092": "Il valore radice di un file '{0}' deve essere un oggetto.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0_1278": "Il runtime richiamerà l'elemento Decorator con {1} argomenti, ma l'elemento Decorator ne prevede {0}.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0_1279": "Il runtime richiamerà l'elemento Decorator con {1} argomenti, ma l'elemento Decorator ne prevede almeno {0}.", + "The_shadowing_declaration_of_0_is_defined_here_18017": "La dichiarazione di oscuramento di '{0}' viene definita in questo punto", + "The_signature_0_of_1_is_deprecated_6387": "La firma '{0}' di '{1}' è deprecata.", + "The_specified_path_does_not_exist_Colon_0_5058": "Il percorso specificato non esiste: '{0}'.", + "The_tag_was_first_specified_here_8034": "Il tag è stato specificato per la prima volta in questo punto.", + "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "La destinazione di un'assegnazione rest di oggetto non può essere un accesso a proprietà facoltativo.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "La destinazione di un'assegnazione REST di oggetto deve essere una variabile o un accesso a proprietà.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Il contesto 'this' del tipo '{0}' non è assegnabile a quello 'this' di tipo '{1}' del metodo.", + "The_this_types_of_each_signature_are_incompatible_2685": "I tipi 'this' delle singole firme non sono compatibili.", + "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104": "Il tipo '{0}' è 'readonly' e non può essere assegnato al tipo modificabile '{1}'.", + "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Impossibile utilizzare il modificatore 'tipo' in un'esportazione denominata quando 'tipo di esportazione' viene usato nell'istruzione di esportazione.", + "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Impossibile utilizzare il modificatore 'tipo' in un'importazione denominata quando 'tipo di importazione' viene usato nella relativa istruzione di importazione.", + "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Il tipo di una dichiarazione di funzione deve corrispondere alla firma della funzione.", + "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Impossibile serializzare questo tipo di nodo perché la sua proprietà '{0}' non può essere serializzata.", + "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Il tipo restituito dal metodo '{0}()' di un iteratore asincrono deve essere una promessa per un tipo con una proprietà 'value'.", + "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Il tipo restituito dal metodo '{0}()' di un iteratore deve contenere una proprietà 'value'.", + "The_types_of_0_are_incompatible_between_these_types_2200": "I tipi di '{0}' sono incompatibili tra questi tipi.", + "The_types_returned_by_0_are_incompatible_between_these_types_2201": "I tipi restituiti da '{0}' sono incompatibili tra questi tipi.", + "The_value_0_cannot_be_used_here_18050": "Non è possibile usare qui il valore '{0}'.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "La dichiarazione di variabile di un'istruzione 'for...in' non può contenere un inizializzatore.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La dichiarazione di variabile di un'istruzione 'for...of' non può contenere un inizializzatore.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "L'istruzione 'with' non è supportata. Il tipo di tutti i simboli in un blocco 'with' è 'any'.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setti_6280": "Sono presenti tipi in '{0}', ma non è stato possibile risolvere questo risultato con l'impostazione 'moduleResolution' corrente. Provare a eseguire l'aggiornamento a 'node16', 'nodenext' o 'bundler'.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278": "Esistono tipi in '{0}', ma non è stato possibile risolvere questo risultato quando si rispettano le \"esportazioni\" del file package.json. Potrebbe essere necessario aggiornare i file package.json o typings della libreria '{1}'.", + "There_is_no_capturing_group_named_0_in_this_regular_expression_1532": "Non è presente alcun gruppo di acquisizione denominato '{0}' in questa espressione regolare.", + "There_is_nothing_available_for_repetition_1507": "Nessun elemento disponibile per la ripetizione.", + "This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found_2874": "Questo tag JSX richiede che \"{0}\" sia incluso nell'ambito, ma non è stato trovato.", + "This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_fo_2875": "Questo tag JSX richiede che il percorso del modulo \"{0}\" esista, ma non è stato trovato alcun tag. Assicurarsi di avere i tipi per il pacchetto appropriato installati.", + "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "Con la proprietà '{0}' del tag JSX è previsto un singolo elemento figlio di tipo '{1}', ma sono stati specificati più elementi figlio.", + "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "Con la proprietà '{0}' del tag JSX è previsto il tipo '{1}' che richiede più elementi figlio, ma è stato specificato un singolo elemento figlio.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534": "Questo backreference fa riferimento a un gruppo che non esiste. Non sono presenti gruppi di acquisizione in questa espressione regolare.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533": "Questo backreference fa riferimento a un gruppo che non esiste. Sono presenti solo {0} gruppi di acquisizione in questa espressione regolare.", + "This_binary_expression_is_never_nullish_Are_you_missing_parentheses_2870": "Questa espressione binaria non è mai nullish. Mancano le parentesi?", + "This_character_cannot_be_escaped_in_a_regular_expression_1535": "Il carattere non può essere preceduto da un carattere di escape in un'espressione regolare.", + "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Questo confronto sembra non intenzionale perché i tipi '{0}' e '{1}' non presentano alcuna sovrapposizione.", + "This_condition_will_always_return_0_2845": "Questa condizione restituirà sempre '{0}'.", + "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Questa condizione restituirà sempre '{0}' perché JavaScript confronta gli oggetti per riferimento, non per valore.", + "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Questa condizione restituirà sempre true perché questo elemento '{0}' è sempre definito.", + "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Questa condizione restituirà sempre true perché questa funzione è sempre definita. Si intendeva chiamarla?", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Questa funzione del costruttore può essere convertita in una dichiarazione di classe.", + "This_expression_is_always_nullish_2871": "Questa espressione è sempre nullish.", + "This_expression_is_not_callable_2349": "Questa espressione non può essere chiamata.", + "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Non è possibile chiamare questa espressione perché è una funzione di accesso 'get'. Si intendeva usarla senza '()'?", + "This_expression_is_not_constructable_2351": "Questa espressione non può essere costruita.", + "This_file_already_has_a_default_export_95130": "Per questo file esiste già un'esportazione predefinita", + "This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_b_2878": "Questo percorso di importazione non è sicuro da riscrivere, perché viene risolto in un altro progetto e il percorso relativo tra i file di output dei progetti non corrisponde al percorso relativo tra i file di input.", + "This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_duri_2877": "Questa importazione usa un'estensione \"{0}\" per la risoluzione in un file TypeScript di input, ma non verrà riscritta durante la creazione perché non è un percorso relativo.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Questa è la dichiarazione che verrà aumentata. Provare a spostare la dichiarazione che causa l'aumento nello stesso file.", + "This_kind_of_expression_is_always_falsy_2873": "Questo tipo di espressione è sempre falso.", + "This_kind_of_expression_is_always_truthy_2872": "Questo tipo di espressione è sempre veritiero.", + "This_may_be_converted_to_an_async_function_80006": "Può essere convertita in una funzione asincrona.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122": "Questo membro non può avere un commento JSDoc con un tag '@override' perché non è dichiarato nella classe di base '{0}'.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123": "Questo membro non può avere un commento JSDoc con un tag 'override' perché non è dichiarato nella classe di base '{0}'. Intendevi '{1}'?", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121": "Questo membro non può avere un commento JSDoc con un tag '@override' perché la classe che lo contiene '{0}' non estende un'altra classe.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic_4128": "Questo membro non può avere un commento JSDoc con un tag '@override' perché il suo nome è dinamico.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113": "Questo membro non può includere un modificatore 'override' perché non è dichiarato nella classe di base '{0}'.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117": "Questo membro non può includere un modificatore 'override' perché non è dichiarato nella classe di base '{0}'. Forse intendevi '{1}'?", + "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112": "Questo membro non può includere un modificatore 'override' perché la classe '{0}', che lo contiene, non estende un'altra classe.", + "This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic_4127": "Questo membro non può avere un modificatore 'override' perché il nome è dinamico.", + "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119": "Questo membro deve avere un commento JSDoc con un tag '@override' perché sostituisce un membro nella classe di base '{0}'.", + "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114": "Questo membro deve includere un modificatore 'override' perché sovrascrive un membro nella classe di base '{0}'.", + "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116": "Questo membro deve includere un modificatore 'override' perché esegue l'override di un metodo astratto dichiarato nella classe di base '{0}'.", + "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "È possibile fare riferimento a questo modulo solo con importazioni/esportazioni ECMAScript attivando il flag '{0}' e facendo riferimento alla relativa esportazione predefinita.", + "This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag_2594": "Il modulo viene dichiarato con 'export =' e può essere usato solo con un'importazione predefinita quando si usa il flag '{0}'.", + "This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2_6807": "Questa operazione può essere semplificata. Questo turno è identico a '{0} {1} {2}'.", + "This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation_7012": "Questo overload restituisce implicitamente il tipo '{0}' perché manca un'annotazione di tipo restituito.", + "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394": "Questa firma di overload non è compatibile con la relativa firma di implementazione.", + "This_parameter_is_not_allowed_with_use_strict_directive_1346": "Questo parametro non è consentito con la direttiva 'use strict'.", + "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120": "Questa proprietà di parametro deve avere un commento JSDoc con un tag '@override' perché sostituisce un membro nella classe di base '{0}'.", + "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115": "Questa proprietà parametro deve includere un modificatore 'override' perché sovrascrive un membro nella classe di base '{0}'.", + "This_regular_expression_flag_cannot_be_toggled_within_a_subpattern_1509": "Non è possibile attivare/disattivare questo flag di espressione regolare all'interno di un criterio secondario.", + "This_regular_expression_flag_is_only_available_when_targeting_0_or_later_1501": "Questo flag di espressione regolare è disponibile solo quando la destinazione è '{0}' o versioni successive.", + "This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolv_2876": "Questo percorso di importazione relativo non è sicuro da riscrivere perché sembra un nome di file, ma in realtà si risolve in \"{0}\".", + "This_spread_always_overwrites_this_property_2785": "Questo spread sovrascrive sempre questa proprietà.", + "This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled_1294": "Questa sintassi non è consentita quando 'erasableSyntaxOnly' è abilitato.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060": "Questa sintassi è riservata ai file con estensione MTS o CTS. Aggiungere una virgola finale o un vincolo esplicito.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059": "Questa sintassi è riservata ai file con estensione mts o cts. Utilizzare un'espressione 'as'.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Con questa sintassi è richiesto un helper importato, ma il modulo '{0}' non è stato trovato.", + "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Con questa sintassi è richiesto un helper importato denominato '{1}', che non esiste in '{0}'. Provare ad aggiornare la versione di '{0}'.", + "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Con questa sintassi è richiesto un helper importato denominato '{1}' con {2} parametri, che non è compatibile con quello presente in '{0}'. Provare ad aggiornare la versione di '{0}'.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Questo parametro di tipo potrebbe richiedere un vincolo `extends {0}`.", + "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Questo uso di 'import' non è valido. le chiamate 'import()' possono essere scritte, ma devono avere parentesi e non possono avere argomenti di tipo.", + "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482": "Per convertire questo file in un modulo ECMAScript, aggiungere il campo '\"type\": \"module\"' a '{0}'.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481": "Per convertire il file in un modulo ECMAScript, modificarne l'estensione in '{0}' oppure aggiungere il campo '\"type\": \"module\"' a '{1}'.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480": "Per convertire questo file in un modulo ECMAScript, modificarne l'estensione in '{0}' o creare un file package.json locale con '{ \"type\": \"module\" }'.", + "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483": "Per convertire questo file in un modulo ECMAScript, creare un file package.json locale con '{ \"type\": \"module\" }'.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Le espressioni 'await' di primo livello sono consentite solo quando l'opzione 'module' è impostata su 'es2022', 'esnext', 'system', 'node16', 'node18', 'nodenext', o 'preserve' e l'opzione 'target' è impostata su 'es2017' o versione successiva.", + "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854": "Le istruzioni 'await using' di primo livello sono consentite solo quando l'opzione 'module' è impostata su 'es2022', 'esnext', 'system', 'node16', 'node18', 'nodenext' o 'preserve' e l'opzione 'target' è impostata su 'es2017' o versione successiva.", + "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Le dichiarazioni di primo livello nei file con estensione d.ts devono iniziare con un modificatore 'declare' o 'export'.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_nod_1432": "I cicli 'for await' di primo livello sono consentiti solo quando l'opzione 'module' è impostata su 'es2022', 'esnext', 'system', 'node16', 'node18', 'nodenext' o 'preserve' e l'opzione 'target' è impostata su 'es2017' o versione successiva.", + "Trailing_comma_not_allowed_1009": "La virgola finale non è consentita.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Esegue il transpile di ogni file in un modulo separato (simile a 'ts.transpileModule').", + "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Provare con `npm i --save-dev @types/{1}` se esiste oppure aggiungere un nuovo file di dichiarazione con estensione d.ts contenente `declare module '{0}';`", + "Trying_other_entries_in_rootDirs_6110": "Verrà effettuato un tentativo con altre voci in 'rootDirs'.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "Verrà effettuato un tentativo con la sostituzione '{0}'. Percorso candidato del modulo: '{1}'.", + "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493": "Il tipo di tupla '{0}' con lunghezza '{1}' non contiene elementi alla posizione di indice '{2}'.", + "Tuple_type_arguments_circularly_reference_themselves_4110": "Gli argomenti tipo di tupla contengono un riferimento circolare a se stessi.", + "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802": "Il tipo '{0}' può essere iterato solo quando si usa il flag '--downlevelIteration' o quando '--target' è impostato su 'es2015' o un valore superiore.", + "Type_0_cannot_be_used_as_an_index_type_2538": "Non è possibile usare il tipo '{0}' come tipo di indice.", + "Type_0_cannot_be_used_to_index_type_1_2536": "Non è possibile usare il tipo '{0}' per indicizzare il tipo '{1}'.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "Il tipo '{0}' non soddisfa il vincolo '{1}'.", + "Type_0_does_not_satisfy_the_expected_type_1_1360": "Il tipo '{0}' non soddisfa il tipo previsto '{1}'.", + "Type_0_has_no_call_signatures_2757": "Il tipo '{0}' non contiene firme di chiamata.", + "Type_0_has_no_construct_signatures_2761": "Il tipo '{0}' non contiene firme del costrutto.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "Nel tipo '{0}' non esiste alcuna firma dell'indice corrispondente per il tipo '{1}'.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "Il tipo '{0}' non ha proprietà in comune con il tipo '{1}'.", + "Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable_2635": "Il tipo '{0}' non ha firme per cui è applicabile l'elenco degli argomenti tipo.", + "Type_0_is_generic_and_can_only_be_indexed_for_reading_2862": "Il tipo '{0}' è generico e può essere indicizzato solo per la lettura.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "Nel tipo '{0}' mancano le proprietà seguenti del tipo '{1}': {2}", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "Nel tipo '{0}' mancano le proprietà seguenti del tipo '{1}': {2} e altre {3}.", + "Type_0_is_not_a_constructor_function_type_2507": "Il tipo '{0}' non è un tipo di funzione del costruttore.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compa_1055": "Il tipo '{0}' non è un tipo restituito di funzione asincrona valido in ES5 perché non fa riferimento a un valore di costruttore compatibile con Promise.", + "Type_0_is_not_an_array_type_2461": "Il tipo '{0}' non è un tipo matrice.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "Il tipo '{0}' non è un tipo matrice o stringa.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Il tipo '{0}' non è un tipo matrice o stringa oppure non contiene un metodo '[Symbol.iterator]()' che restituisce un iteratore.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Il tipo '{0}' non è un tipo matrice oppure non contiene un metodo '[Symbol.iterator]()' che restituisce un iteratore.", + "Type_0_is_not_assignable_to_type_1_2322": "Il tipo '{0}' non è assegnabile al tipo '{1}'.", + "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820": "Il tipo '{0}' non è assegnabile al tipo '{1}'. Si intendeva '{2}'?", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Il tipo '{0}' non è assegnabile al tipo '{1}'. Sono presenti due tipi diversi con questo nome, che però non sono correlati.", + "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636": "Il tipo '{0}' non può essere assegnato al tipo '{1}' come indicato dall'annotazione di varianza.", + "Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values_18033": "Il tipo '{0}' non è assegnabile al tipo '{1}' come richiesto per i valori dei membri di enumerazione calcolati.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375": "L'argomento di tipo '{0}' non può essere assegnato al tipo '{1}' con 'exactOptionalPropertyTypes: true'. Provare ad aggiungere 'undefined' ai tipi di proprietà di destinazione.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "L'argomento di tipo '{0}' non può essere assegnato al tipo '{1}' con 'exactOptionalPropertyTypes: true'. Provare ad aggiungere 'undefined' al tipo di destinazione.", + "Type_0_is_not_comparable_to_type_1_2678": "Il tipo '{0}' non è confrontabile con il tipo '{1}'.", + "Type_0_is_not_generic_2315": "Il tipo '{0}' non è generico.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "Il tipo '{0}' può rappresentare un valore primitivo, che non è consentito come operando destro dell'operatore 'in'.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Il tipo '{0}' deve contenere un metodo '[Symbol.asyncIterator]()' che restituisce un iteratore asincrono.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Il tipo '{0}' deve contenere un metodo '[Symbol.iterator]()' che restituisce un iteratore.", + "Type_0_provides_no_match_for_the_signature_1_2658": "Il tipo '{0}' non fornisce corrispondenze per la firma '{1}'.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Il tipo '{0}' fa riferimento a se stesso in modo ricorsivo come tipo di base.", + "Type_Checking_6248": "Controllo del tipo", + "Type_alias_0_circularly_references_itself_2456": "L'alias di tipo '{0}' contiene un riferimento circolare a se stesso.", + "Type_alias_must_be_given_a_name_1439": "È necessario assegnare un nome all'alias del tipo.", + "Type_alias_name_cannot_be_0_2457": "Il nome dell'alias di tipo non può essere '{0}'.", + "Type_aliases_can_only_be_used_in_TypeScript_files_8008": "Gli alias di tipo possono esere usati solo in file TypeScript.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "L'annotazione di tipo non può essere inclusa in una dichiarazione di costruttore.", + "Type_annotations_can_only_be_used_in_TypeScript_files_8010": "Le annotazioni tipo possono essere usate solo in file TypeScript.", + "Type_argument_expected_1140": "È previsto l'argomento tipo.", + "Type_argument_list_cannot_be_empty_1099": "L'elenco degli argomenti tipo non può essere vuoto.", + "Type_arguments_can_only_be_used_in_TypeScript_files_8011": "Gli argomenti tipo possono essere usati solo in file TypeScript.", + "Type_arguments_for_0_circularly_reference_themselves_4109": "Gli argomenti tipo per '{0}' contengono un riferimento circolare a se stessi.", + "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016": "Le espressioni di asserzione di tipo possono essere usate solo in file TypeScript.", + "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626": "Il tipo alla posizione {0} nell'origine non è compatibile con il tipo alla posizione {1} nella destinazione.", + "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627": "Il tipo alle posizioni dalla {0} alla {1} nell'origine non è compatibile con il tipo alla posizione {2} nella destinazione.", + "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039": "Non è possibile usare il tipo contenente il nome privato '{0}' con --isolatedDeclarations.", + "Type_declaration_files_to_be_included_in_compilation_6124": "File della dichiarazione di tipo da includere nella compilazione.", + "Type_expected_1110": "È previsto il tipo.", + "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456": "L’importazione dei tipi di asserzione deve contenere esattamente una chiave, 'resolution-mode', con valore 'import' o 'require'.", + "Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1464": "Gli attributi di importazione di tipi devono contenere esattamente una chiave 'resolution-mode', con valore 'import' o 'require'.", + "Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute_1542": "L'importazione del tipo di un modulo ECMAScript da un modulo CommonJS deve avere un attributo 'resolution-mode'.", + "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589": "La creazione di un'istanza di tipo presenta troppi livelli ed è probabilmente infinita.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "Il tipo viene usato come riferimento diretto o indiretto nel callback di fulfillment del relativo metodo 'then'.", + "Type_library_referenced_via_0_from_file_1_1402": "Libreria dei tipi a cui viene fatto riferimento tramite '{0}' dal file '{1}'", + "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Libreria dei tipi a cui viene fatto riferimento tramite '{0}' dal file '{1}' con packageId '{2}'", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Il tipo dell'operando 'await' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Il tipo del valore della proprietà calcolata è '{0}', che non è assegnabile al tipo '{1}'.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Il tipo di variabile del membro di istanza '{0}' non può fare riferimento all'identificatore '{1}' dichiarato nel costruttore.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Il tipo di elementi iterati di un operando 'yield*' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Il tipo di proprietà '{0}' contiene un riferimento circolare a se stesso nel tipo con mapping '{1}'.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Il tipo dell'operando 'yield' in un generatore asincrono deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", + "Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribut_1541": "L'importazione solo tipo di un modulo ECMAScript da un modulo CommonJS deve avere un attributo 'resolution-mode'.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Il tipo è originato in corrispondenza di questa importazione. Non è possibile chiamare o costruire un'importazione di tipo spazio dei nomi e verrà restituito un errore in fase di esecuzione. Provare a usare un'importazione predefinita o un'importazione di require in questo punto.", + "Type_parameter_0_has_a_circular_constraint_2313": "Il parametro di tipo '{0}' contiene un vincolo circolare.", + "Type_parameter_0_has_a_circular_default_2716": "Il parametro di tipo '{0}' contiene un'impostazione predefinita circolare.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Il parametro di tipo '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Il parametro di tipo '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Il parametro di tipo '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "Il parametro di tipo '{0}' della funzione esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "Il parametro di tipo '{0}' dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103": "Il parametro di tipo '{0}' del tipo di oggetto con mapping esportato usa il nome privato '{1}'.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "Il parametro di tipo '{0}' dell'alias di tipo esportato contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "Il parametro di tipo '{0}' del metodo dell'interfaccia esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "Il parametro di tipo '{0}' del metodo pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "Il parametro di tipo '{0}' del metodo statico pubblico della classe esportata contiene o usa il nome privato '{1}'.", + "Type_parameter_declaration_expected_1139": "È prevista la dichiarazione di parametro di tipo.", + "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004": "Le dichiarazioni di parametro di tipo possono essere usate solo in file TypeScript.", + "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744": "Le impostazioni predefinite del parametro di tipo possono fare riferimento solo a parametri di tipo dichiarati in precedenza.", + "Type_parameter_list_cannot_be_empty_1098": "L'elenco dei parametri di tipo non può essere vuoto.", + "Type_parameter_name_cannot_be_0_2368": "Il nome del parametro di tipo non può essere '{0}'.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "I parametri di tipo non possono essere inclusi in una dichiarazione di costruttore.", + "Type_predicate_0_is_not_assignable_to_1_1226": "Il predicato di tipo '{0}' non è assegnabile a '{1}'.", + "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799": "Il tipo produce un tipo di tupla troppo grande da rappresentare.", + "Type_reference_directive_0_was_not_resolved_6120": "======== La direttiva '{0}' del riferimento al tipo non è stata risolta. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La direttiva '{0}' del riferimento al tipo è stata risolta in '{1}'. Primaria: {2}. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== La direttiva '{0}' del riferimento al tipo è stata risolta in '{1}' con ID pacchetto ID '{2}'. Primaria: {3}. ========", + "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037": "Le espressioni di soddisfazione del tipo possono essere usate solo nei file TypeScript.", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "I tipi non possono essere visualizzati nelle dichiarazioni di esportazione nei file JavaScript.", + "Types_have_separate_declarations_of_a_private_property_0_2442": "I tipi contengono dichiarazioni separate di una proprietà privata '{0}'.", + "Types_of_construct_signatures_are_incompatible_2419": "I tipi delle firme del costrutto sono incompatibili.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "I tipi dei parametri '{0}' e '{1}' sono incompatibili.", + "Types_of_property_0_are_incompatible_2326": "I tipi della proprietà '{0}' sono incompatibili.", + "Unable_to_open_file_0_6050": "Non è possibile aprire il file '{0}'.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "Non è possibile risolvere la firma dell'espressione Decorator della classe quando è chiamata come espressione.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "Non è possibile risolvere la firma dell'espressione Decorator del metodo quando è chiamata come espressione.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "Non è possibile risolvere la firma dell'espressione Decorator del parametro quando è chiamata come espressione.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "Non è possibile risolvere la firma dell'espressione Decorator della proprietà quando è chiamata come espressione.", + "Undetermined_character_escape_1513": "Carattere di escape indeterminato.", + "Unexpected_0_Did_you_mean_to_escape_it_with_backslash_1508": "'{0}' imprevisto. La barra rovesciata stava per un carattere escape?", + "Unexpected_end_of_text_1126": "Fine del testo imprevista.", + "Unexpected_keyword_or_identifier_1434": "Parola chiave o identificatore imprevisti.", + "Unexpected_token_1012": "Token imprevisto.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token imprevisto. È previsto un costruttore, un metodo, una funzione di accesso o una proprietà.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token imprevisto. Sono previsti nomi di parametro senza parentesi graffe.", + "Unexpected_token_Did_you_mean_or_gt_1382": "Token imprevisto. Si intendeva `{'>'}` o `>`?", + "Unexpected_token_Did_you_mean_or_rbrace_1381": "Token imprevisto. Si intendeva `{'}'}` o `}`?", + "Unexpected_token_expected_1179": "Token imprevisto. È previsto '{'.", + "Unicode_escape_sequence_cannot_appear_here_17021": "La sequenza di escape Unicode non può essere visualizzata qui.", + "Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_se_1538": "Le sequenze di escape Unicode sono disponibili solo quando è impostato il flag Unicode (u) o Unicode Sets (v).", + "Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v__1530": "Le espressioni valore della proprietà sono disponibili solo quando è impostato il flag Unicode (u) o Unicode Sets (v).", + "Unknown_Unicode_property_name_1524": "Nome della proprietà Unicode sconosciuto.", + "Unknown_Unicode_property_name_or_value_1529": "Nome o valore della proprietà Unicode sconosciuto.", + "Unknown_Unicode_property_value_1526": "Valore della proprietà Unicode sconosciuto.", + "Unknown_build_option_0_5072": "L'opzione di compilazione '{0}' è sconosciuta.", + "Unknown_build_option_0_Did_you_mean_1_5077": "L'opzione di compilazione '{0}' è sconosciuta. Si intendeva '{1}'?", + "Unknown_compiler_option_0_5023": "Opzione del compilatore sconosciuta: '{0}'.", + "Unknown_compiler_option_0_Did_you_mean_1_5025": "L'opzione '{0}' del compilatore è sconosciuta. Si intendeva '{1}'?", + "Unknown_keyword_or_identifier_Did_you_mean_0_1435": "Parola chiave o identificatore sconosciuti. Intendevi '{0}'?", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "L'opzione 'excludes' è sconosciuta. Si intendeva 'exclude'?", + "Unknown_regular_expression_flag_1499": "Flag di espressione regolare sconosciuto.", + "Unknown_type_acquisition_option_0_17010": "L'opzione '{0}' relativa all'acquisizione del tipo è sconosciuta.", + "Unknown_type_acquisition_option_0_Did_you_mean_1_17018": "L'opzione di acquisizione del tipo '{0}' è sconosciuta. Si intendeva '{1}'?", + "Unknown_watch_option_0_5078": "L'opzione '{0}' dell'espressione di controllo è sconosciuta.", + "Unknown_watch_option_0_Did_you_mean_1_5079": "L'opzione '{0}' dell'espressione di controllo è sconosciuta. Si intendeva '{1}'?", + "Unreachable_code_detected_7027": "È stato rilevato codice non raggiungibile.", + "Unterminated_Unicode_escape_sequence_1199": "Sequenza di escape Unicode senza terminazione.", + "Unterminated_quoted_string_in_response_file_0_6045": "Stringa tra virgolette senza terminazione nel file di risposta '{0}'.", + "Unterminated_regular_expression_literal_1161": "Valore letterale di espressione regolare senza terminazione.", + "Unterminated_string_literal_1002": "Valore letterale stringa senza terminazione.", + "Unterminated_template_literal_1160": "Valore letterale di modello senza terminazione.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "Le chiamate di funzione non tipizzate potrebbero non accettare argomenti tipo.", + "Unused_label_7028": "Etichetta non usata.", + "Unused_ts_expect_error_directive_2578": "Direttiva '@ts-expect-error' non usata.", + "Update_import_from_0_90058": "Aggiornare l'importazione da \"{0}\"", + "Update_modifiers_of_0_90061": "Aggiornare i modificatori di '{0}'", + "Updating_output_timestamps_of_project_0_6359": "Aggiornamento dei timestamp di output del progetto '{0}'...", + "Updating_unchanged_output_timestamps_of_project_0_6371": "Aggiornamento dei timestamp di output non modificati del progetto '{0}'...", + "Use_0_95174": "Usa `{0}`.", + "Use_0_instead_5106": "Usare '{0}'.", + "Use_Number_isNaN_in_all_conditions_95175": "Usare 'Number.isNaN' in tutte le condizioni.", + "Use_element_access_for_0_95145": "Usare l'accesso agli elementi per '{0}'", + "Use_element_access_for_all_undeclared_properties_95146": "Usare l'accesso agli elementi per tutte le proprietà non dichiarate.", + "Use_import_type_95180": "Usare 'import type'", + "Use_synthetic_default_member_95016": "Usare il membro 'default' sintetico.", + "Use_the_package_json_exports_field_when_resolving_package_imports_6408": "Usare il campo 'exports' del file package.json per risolvere le importazioni.", + "Use_the_package_json_imports_field_when_resolving_imports_6409": "Usare il campo 'imports' del file package.json per risolvere le importazioni.", + "Use_type_0_95181": "Usare 'type {0}'", + "Using_0_subpath_1_with_target_2_6404": "Utilizzo di '{0}' sottotracciato '{1}' con destinazione '{2}'.", + "Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found_2879": "L'uso di frammenti JSX richiede che la factory di frammenti \"{0}\" sia nell'ambito, ma non è stata trovata.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'uso di una stringa in un'istruzione 'for...of' è supportato solo in ECMAScript 5 e versioni successive.", + "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Se si usa --build, l'opzione -b modificherà il comportamento di tsc in modo che sia più simile a un agente di orchestrazione di compilazione che a un compilatore. Viene usata per attivare la compilazione di progetti compositi. Per altre informazioni, vedere {0}", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", + "VERSION_6036": "VERSIONE", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Il valore di tipo '{0}' non ha proprietà in comune con il tipo '{1}'. Si intendeva chiamarlo?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Il valore di tipo '{0}' non è chiamabile. Si intendeva includere 'new'?", + "Variable_0_implicitly_has_an_1_type_7005": "La variabile '{0}' contiene implicitamente un tipo '{1}'.", + "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043": "La variabile '{0}' include implicitamente un tipo '{1}', ma è possibile dedurre un tipo migliore dall'utilizzo.", + "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046": "La variabile '{0}' include implicitamente il tipo '{1}' in alcuni punti, ma è possibile dedurre un tipo migliore dall'utilizzo.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "La variabile '{0}' contiene implicitamente il tipo '{1}' in alcune posizioni in cui non è possibile determinarne il tipo.", + "Variable_0_is_used_before_being_assigned_2454": "La variabile '{0}' viene usata prima dell'assegnazione.", + "Variable_declaration_expected_1134": "È prevista la dichiarazione di variabile.", + "Variable_declaration_list_cannot_be_empty_1123": "L'elenco delle dichiarazioni di variabile non può essere vuoto.", + "Variable_declaration_not_allowed_at_this_location_1440": "Dichiarazione di variabile non consentita in questa posizione.", + "Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9010": "La variabile deve avere un'annotazione di tipo esplicito con --isolatedDeclarations.", + "Variables_with_multiple_declarations_cannot_be_inlined_95186": "Le variabili con più dichiarazioni non possono essere impostate come inline.", + "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625": "L'elemento variadic alla posizione {0} nell'origine non corrisponde all'elemento alla posizione {1} nella destinazione.", + "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637": "Le annotazioni di varianza sono supportate solo negli alias di tipo per oggetti, funzioni, costruttori e tipi mappati.", + "Version_0_6029": "Versione {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file_95110": "Per altre informazioni su questo file, visitare https://aka.ms/tsconfig", + "WATCH_OPTIONS_6918": "OPZIONI DELL'ESPRESSIONE DI CONTROLLO", + "Watch_and_Build_Modes_6250": "Modalità di espressione di controllo e compilazione", + "Watch_input_files_6005": "Controlla i file di input.", + "Watch_option_0_requires_a_value_of_type_1_5080": "Con l'opzione '{0}' dell'espressione di controllo è richiesto un valore di tipo {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "È possibile solo scrivere un tipo per '{0}' aggiungendo qui un tipo per l'intero parametro.", + "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Durante l'assegnazione di funzioni verifica che i parametri e i valori restituiti siano compatibili con il sottotipo.", + "When_type_checking_take_into_account_null_and_undefined_6699": "Durante il controllo del tipo prende in considerazione 'null' e 'undefined'.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Indica se mantenere l'output della console obsoleto in modalità espressione di controllo invece di pulire lo schermo.", + "Wrap_all_invalid_characters_in_an_expression_container_95109": "Eseguire il wrapping di tutti i caratteri non validi in un contenitore di espressioni", + "Wrap_all_invalid_decorator_expressions_in_parentheses_95195": "Eseguire il wrapping di tutte le espressioni Decorator non valide tra parentesi", + "Wrap_all_object_literal_with_parentheses_95116": "Racchiudere tra parentesi tutti i valori letterali di oggetto", + "Wrap_all_unparented_JSX_in_JSX_fragment_95121": "Esegue il wrapping di JSX senza parentesi nel frammento JSX", + "Wrap_in_JSX_fragment_95120": "Esegui il wrapping nel frammento JSX", + "Wrap_in_parentheses_95194": "Eseguire il wrapping tra parentesi", + "Wrap_invalid_character_in_an_expression_container_95108": "Eseguire il wrapping del carattere non valido in un contenitore di espressioni", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Racchiudere tra parentesi il corpo seguente che deve essere un valore letterale di oggetto", + "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Per informazioni su tutte le opzioni del compilatore, vedere {0}", + "You_cannot_rename_a_module_via_a_global_import_8031": "Non è possibile rinominare un modulo tramite un'importazione globale.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Non è possibile rinominare gli elementi definiti in una cartella 'node_modules'.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Non è possibile rinominare gli elementi definiti in un'altra cartella 'node_modules'.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Non è possibile rinominare elementi definiti nella libreria TypeScript standard.", + "You_cannot_rename_this_element_8000": "Non è possibile rinominare questo elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accetta un numero troppo ridotto di argomenti da usare come espressione Decorator in questo punto. Si intendeva chiamarlo prima e scrivere '@{0}()'?", + "_0_and_1_index_signatures_are_incompatible_2330": "Le firme dell'indice '{0}' e '{1}' non sono compatibili.", + "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Non è possibile combinare le operazioni '{0}' e '{1}' senza parentesi.", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Gli attributi '{0}' sono stati specificati due volte. L'attributo denominato '{0}' verrà sovrascritto.", + "_0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17019": "'{0}' alla fine di un tipo non è una sintassi TypeScript valida. Si intendeva scrivere '{1}'?", + "_0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17020": "'{0}' all'inizio di un tipo non è una sintassi TypeScript valida. Si intendeva scrivere '{1}'?", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}' può essere importato solo attivando il flag 'esModuleInterop' e usando un'importazione predefinita.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}' può essere importato solo usando un'importazione predefinita.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}' può essere importato solo usando una chiamata 'require' o attivando il flag 'esModuleInterop' e usando un'importazione predefinita.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}' può essere importato solo usando una chiamata 'require' o usando un'importazione predefinita.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}' può essere importato solo usando 'import {1} = require({2})' o un'importazione predefinita.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}' può essere importato solo usando 'import {1} = require({2})' o attivando il flag 'esModuleInterop' e usando un'importazione predefinita.", + "_0_cannot_be_used_as_a_JSX_component_2786": "Non è possibile usare '{0}' come componente JSX.", + "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "Non è possibile usare '{0}' come valore perché è stato esportato con 'export type'.", + "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "Non è possibile usare '{0}' come valore perché è stato importato con 'import type'.", + "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "I componenti di '{0}' non accettano testo come elementi figlio. Il tipo di testo in JSX è 'string ', ma il tipo previsto di '{1}' è '{2}'.", + "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082": "Non è stato possibile creare un'istanza di '{0}' con un tipo arbitrario che potrebbe non essere correlato a '{1}'.", + "_0_declarations_can_only_be_declared_inside_a_block_1156": "Le dichiarazioni '{0}' possono essere dichiarate solo all'interno di un blocco.", + "_0_declarations_can_only_be_used_in_TypeScript_files_8006": "Le dichiarazioni '{0}' possono essere usate solo in file TypeScript.", + "_0_declarations_may_not_have_binding_patterns_1492": "'{0}' dichiarazioni non possono avere criteri di associazione.", + "_0_declarations_must_be_initialized_1155": "Le dichiarazioni '{0}' devono essere inizializzate.", + "_0_expected_1005": "È previsto '{0}'.", + "_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is__18055": "'{0}' ha un tipo stringa, ma deve avere una sintassi di stringa riconoscibile sintatticamente quando è abilitato 'isolatedModules'.", + "_0_has_no_exported_member_named_1_Did_you_mean_2_2724": "In '{0}' non è presente alcun membro esportato denominato '{1}'. Si intendeva '{2}'?", + "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050": "'{0}' include implicitamente un tipo restituito '{1}', ma è possibile dedurre un tipo migliore dall'utilizzo.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' contiene implicitamente il tipo restituito 'any', perché non contiene un'annotazione di tipo restituito e viene usato come riferimento diretto o indiretto in una delle relative espressioni restituite.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' contiene implicitamente il tipo 'any', perché non contiene un'annotazione di tipo e viene usato come riferimento diretto o indiretto nel relativo inizializzatore.", + "_0_index_signatures_are_incompatible_2634": "Le firme dell'indice '{0}' non sono compatibili.", + "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "Il tipo di indice '{0}' '{1}' non è assegnabile al tipo di indice '{2}' '{3}'.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' è una primitiva, ma '{1}' è un oggetto wrapper. Quando possibile, preferire '{0}'.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' è un tipo e non può essere importato nei file JavaScript. Usare '{1}' in un'annotazione di tipo JSDoc.", + "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled_1484": "'{0}' è un tipo e deve essere importato usando un'importazione solo di tipi quando 'verbatimModuleSyntax' è abilitato.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}' è una ridenominazione inutilizzata di '{1}'. Si intendeva utilizzarla come annotazione di tipo?", + "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}' è assegnabile al vincolo di tipo '{1}', ma è possibile creare un'istanza di '{1}' con un sottotipo diverso del vincolo '{2}'.", + "_0_is_automatically_exported_here_18044": "'{0}' viene esportato automaticamente qui.", + "_0_is_declared_but_its_value_is_never_read_6133": "L'elemento '{0}' è dichiarato, ma il suo valore non viene mai letto.", + "_0_is_declared_but_never_used_6196": "La variabile '{0}' è dichiarata, ma non viene mai usata.", + "_0_is_declared_here_2728": "In questo punto viene dichiarato '{0}'.", + "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611": "'{0}' è definito come proprietà nella classe '{1}', ma in questo punto ne viene eseguito l'override in '{2}' come funzione di accesso.", + "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}' è definito come funzione di accesso nella classe '{1}', ma in questo punto ne viene eseguito l'override in '{2}' come proprietà di istanza.", + "_0_is_deprecated_6385": "'{0}' è deprecato.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' non è una metaproprietà valida per la parola chiave '{1}'. Si intendeva '{2}'?", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}' non è un nome di parametro consentito.", + "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}' non è consentito come nome di una dichiarazione di variabile.", + "_0_is_of_type_unknown_18046": "'{0}' è di tipo 'unknown'.", + "_0_is_possibly_null_18047": "'{0}' è probabilmente 'null'.", + "_0_is_possibly_null_or_undefined_18049": "'{0}' è probabilmente 'null' o 'undefined'.", + "_0_is_possibly_undefined_18048": "'{0}' è probabilmente 'undefined'.", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' viene usato come riferimento diretto o indiretto nella relativa espressione di base.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' viene usato come riferimento diretto o indiretto nella relativa annotazione di tipo.", + "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783": "'{0}' è specificato più di una volta, quindi il relativo utilizzo verrà sovrascritto.", + "_0_list_cannot_be_empty_1097": "L'elenco '{0}' non può essere vuoto.", + "_0_modifier_already_seen_1030": "Il modificatore '{0}' è già presente.", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias_1274": "Il modificatore '{0}' può essere presente solo in un parametro di tipo di una classe, un'interfaccia o un alias di tipo", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class_1277": "Il modificatore '{0}' può essere presente solo in un parametro di tipo di una funzione, un metodo o una classe", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "Il modificatore '{0}' non può essere incluso in una dichiarazione di costruttore.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "Il modificatore '{0}' non può essere incluso in un elemento modulo o spazio dei nomi.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "Il modificatore '{0}' non può essere incluso in un parametro.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "Il modificatore '{0}' non può essere incluso in un membro di tipo.", + "_0_modifier_cannot_appear_on_a_type_parameter_1273": "Il modificatore '{0}' non può essere incluso in un parametro di tipo.", + "_0_modifier_cannot_appear_on_a_using_declaration_1491": "Il modificatore '{0}' non può essere incluso in una dichiarazione 'using'.", + "_0_modifier_cannot_appear_on_an_await_using_declaration_1495": "Il modificatore '{0}' non può essere incluso in una dichiarazione 'await using'.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "Il modificatore '{0}' non può essere incluso in una firma dell'indice.", + "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031": "Il modificatore '{0}' non può essere incluso in elementi di classe di questo tipo.", + "_0_modifier_cannot_be_used_here_1042": "Non è possibile usare il modificatore '{0}' in questo punto.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "Non è possibile usare il modificatore '{0}' in un contesto di ambiente.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "Non è possibile usare il modificatore '{0}' con il modificatore '{1}'.", + "_0_modifier_cannot_be_used_with_a_private_identifier_18019": "Non è possibile usare il modificatore '{0}' con un identificatore privato.", + "_0_modifier_must_precede_1_modifier_1029": "Il modificatore '{0}' deve precedere il modificatore '{1}'.", + "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531": "'\\{0}' deve essere seguito da un'espressione del valore di proprietà Unicode racchiusa tra parentesi graffe.", + "_0_needs_an_explicit_type_annotation_2782": "'{0}' richiede un'annotazione di tipo esplicita.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' fa riferimento solo a un tipo, ma qui viene usato come spazio dei nomi.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' fa riferimento solo a un tipo, ma qui viene usato come valore.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690": "'{0}' fa riferimento solo a un tipo, ma qui viene usato come valore. Si intendeva usare '{1} in {0}'?", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585": "'{0}' si riferisce solo a un tipo, ma in questo punto viene usato come valore. È necessario modificare la libreria di destinazione? Provare a impostare l'opzione 'lib' del compilatore su es2015 o versioni successive.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' fa riferimento a un istruzione globale UMD, ma il file corrente è un modulo. Provare ad aggiungere un'importazione.", + "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749": "'{0}' fa riferimento a un valore, ma qui viene usato come tipo. Si intendeva 'typeof {0}'?", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1291": "'{0}' si risolve in un tipo e deve essere contrassegnato come solo di tipi in questo file prima di eseguire nuovamente l'esportazione quando '{1}' è abilitato. Provare a usare 'import type' in cui viene importato '{0}'.", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1292": "'{0}' si risolve in un tipo e deve essere contrassegnato come solo di tipi in questo file prima di eseguire nuovamente l'esportazione quando '{1}' è abilitato. Provare a usare 'export type {{0} as default }'.", + "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimMo_1485": "'{0}' si risolve in una dichiarazione solo di tipi e deve essere importato usando un'importazione solo di tipi quando 'verbatimModuleSyntax' è abilitato.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1289": "'{0}' si risolve in una dichiarazione solo di tipi e deve essere contrassegnato come solo di tipi in questo file prima di eseguire nuovamente l'esportazione quando '{1}' è abilitato. Provare a usare 'import type' in cui viene importato '{0}'.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1290": "'{0}' si risolve in una dichiarazione solo di tipi e deve essere contrassegnato come solo di tipi in questo file prima di eseguire nuovamente l'esportazione quando '{1}' è abilitato. Provare a usare 'export type {{0} as default }'.", + "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_1448": "'{0}' si risolve in una dichiarazione solo di tipi e deve essere riesportato usando una riesportazione solo di tipi quando '{1}' è abilitato.", + "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258": "' {0}' deve essere impostato all'interno dell'oggetto 'compilerOptions' del file JSON di configurazione", + "_0_tag_already_specified_1223": "Il tag '{0}' è già specificato.", + "_0_was_also_declared_here_6203": "In questo punto viene dichiarato anche '{0}'.", + "_0_was_exported_here_1377": "In questo punto è stato esportato '{0}'.", + "_0_was_imported_here_1376": "In questo punto è stato importato '{0}'.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}', in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito '{1}'.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055": "'{0}', in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo yield '{1}'.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "Il modificatore 'abstract' può essere incluso solo in una dichiarazione di classe, metodo o proprietà.", + "accessor_modifier_can_only_appear_on_a_property_declaration_1275": "Il modificatore 'accessor' può essere visualizzato solo in una dichiarazione di proprietà.", + "and_here_6204": "e in questo punto.", + "arguments_cannot_be_referenced_in_property_initializers_2815": "impossibile fare riferimento agli 'argomenti' negli inizializzatori di proprietà.", + "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476": "\"auto\": considera i file con importazioni, esportazioni, import.meta, jsx (con jsx: react-jsx) o il formato esm (con modulo: node16+) come moduli.", + "await_expression_cannot_be_used_inside_a_class_static_block_18037": "Non è possibile usare l'espressione 'await' all'interno di un blocco statico di classe.", + "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375": "Le espressioni 'await' sono consentite solo al primo livello di un file quando il file è un modulo, ma questo file non contiene importazioni o esportazioni. Provare ad aggiungere un elemento 'export {}' vuoto per trasformare il file in un modulo.", + "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308": "Le espressioni 'await' sono consentite solo all'interno di funzioni asincrone e al primo livello di moduli.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "Non è possibile usare le espressioni 'await' in un inizializzatore di parametri.", + "await_has_no_effect_on_the_type_of_this_expression_80007": "'await' non ha alcun effetto sul tipo di questa espressione.", + "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853": "Le istruzioni 'await using' sono consentite solo al primo livello di un file quando il file è un modulo, ma questo file non contiene importazioni o esportazioni. Provare ad aggiungere un elemento 'export {}' vuoto per trasformare il file in un modulo.", + "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852": "Le istruzioni 'await using' sono consentite solo all'interno di funzioni asincrone e al primo livello di moduli.", + "await_using_statements_cannot_be_used_inside_a_class_static_block_18054": "Non è possibile usare le istruzioni 'await using' all'interno di un blocco statico di classe.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "L'opzione 'baseUrl' è impostata su '{0}'. Verrà usato questo valore per risolvere il nome del modulo non relativo '{1}'.", + "c_must_be_followed_by_an_ASCII_letter_1512": "'\\c' deve essere seguito da una lettera ASCII.", + "can_only_be_used_at_the_start_of_a_file_18026": "'#!' può essere usato solo all'inizio di un file.", + "case_or_default_expected_1130": "È previsto 'case' o 'default'.", + "catch_or_finally_expected_1472": "È previsto 'catch' o 'finally'.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'inizializzatore del membro di enumerazione 'const' è stato valutato come valore non finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'inizializzatore del membro di enumerazione 'const' è stato valutato come valore non consentito 'NaN'.", + "const_enum_member_initializers_must_be_constant_expressions_2474": "gli inizializzatori di membro di enumerazione const devono essere espressioni costanti.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Le enumerazioni 'const' possono essere usate solo in espressioni di accesso a proprietà o indice oppure nella parte destra di un'assegnazione di esportazione, di una dichiarazione di importazione o di una query su tipo.", + "constructor_cannot_be_used_as_a_parameter_property_name_2398": "Non è possibile usare 'constructor' come nome di proprietà di un parametro.", + "constructor_is_a_reserved_word_18012": "'#constructor' è una parola riservata.", + "default_Colon_6903": "impostazione predefinita:", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Non è possibile chiamare 'delete' su un identificatore in modalità strict.", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *' non consente di riesportare esportazioni predefinite.", + "export_can_only_be_used_in_TypeScript_files_8003": "'export =' può essere usato solo in file TypeScript.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Non è possibile applicare il modificatore 'export' a moduli di ambiente e aumenti di modulo perché sono sempre visibili.", + "extends_clause_already_seen_1172": "La clausola 'extends' è già presente.", + "extends_clause_must_precede_implements_clause_1173": "La clausola 'extends' deve precedere la clausola 'implements'.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "La clausola 'extends' della classe esportata '{0}' contiene o usa il nome privato '{1}'.", + "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021": "La clausola 'extends' della classe esportata contiene o usa il nome privato '{0}'.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "La clausola 'extends' dell'interfaccia esportata '{0}' contiene o usa il nome privato '{1}'.", + "false_unless_composite_is_set_6906": "`false`, a meno che non sia impostato `composite`", + "false_unless_strict_is_set_6905": "`false`, a meno che non sia impostato `strict`", + "file_6025": "file", + "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431": "I cicli 'for await' sono consentiti solo al primo livello di un file quando il file è un modulo, ma questo file non contiene importazioni o esportazioni. Provare ad aggiungere un elemento 'export {}' vuoto per trasformare il file in un modulo.", + "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103": "I cicli 'for await' sono consentiti solo all'interno di funzioni asincrone e al primo livello di moduli.", + "for_await_loops_cannot_be_used_inside_a_class_static_block_18038": "Non è possibile usare i cicli 'for await' all'interno di un blocco statico di classe.", + "get_and_set_accessors_cannot_declare_this_parameters_2784": "Le funzioni di accesso 'get' e 'set' non possono dichiarare parametri 'this'.", + "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908": "`[]` se è specificato `files`; in caso contrario, `[\"**/*\"]5D;`", + "implements_clause_already_seen_1175": "La clausola 'implements' è già presente.", + "implements_clauses_can_only_be_used_in_TypeScript_files_8005": "Le clausole 'implements' possono essere usate solo in file TypeScript.", + "import_can_only_be_used_in_TypeScript_files_8002": "'import ... =' può essere usato solo in file TypeScript.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "Le dichiarazioni 'infer' sono consentite solo nella clausola 'extends' di un tipo condizionale.", + "k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets_1510": "'\\k' deve essere seguito da un nome di gruppo di acquisizione racchiuso tra parentesi acute.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "Non è consentito usare 'let' come nome in dichiarazioni 'let' o 'const'.", + "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010": "module === `AMD` o `UMD` o `System` o `ES6`, quindi `Classic`; in caso contrario `Node`", + "module_system_or_esModuleInterop_6904": "module === \"system\" o esModuleInterop", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "L'espressione 'new', nella cui destinazione manca una firma del costrutto, contiene implicitamente un tipo 'any'.", + "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907": "`[\"node_modules\", \"bower_components\", \"jspm_packages\"]`, nonché il valore di `outDir` se ne è specificato uno.", + "one_of_Colon_6900": "uno di:", + "one_or_more_Colon_6901": "uno o più:", + "options_6024": "opzioni", + "or_JSX_element_expected_1145": "Previsto elemento '{' o JSX.", + "or_expected_1144": "È previsto '{' o ';'.", + "package_json_does_not_have_a_0_field_6100": "Il file 'package.json' non contiene un campo '{0}'.", + "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json' non contiene alcuna voce di 'typesVersions' corrispondente alla versione '{0}'.", + "package_json_had_a_falsy_0_field_6220": "'package.json' contiene un campo '{0}' falso.", + "package_json_has_0_field_1_that_references_2_6101": "Il file 'package.json' contiene il campo '{1}' di '{0}' che fa riferimento a '{2}'.", + "package_json_has_a_peerDependencies_field_6281": "'package.json' contiene un campo 'peerDependencies'.", + "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209": "'package.json' contiene una voce '{0}' di 'typesVersions' che non corrisponde a un intervallo semver valido.", + "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208": "'package.json' contiene una voce '{0}' di 'typesVersions' che corrisponde alla versione '{1}' del compilatore. Verrà cercato un criterio per la corrispondenza con il nome di modulo '{2}'.", + "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206": "'package.json' contiene un campo 'typesVersions' con mapping tra percorsi specifici della versione.", + "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274": "L’ambito package.json '{0}' esegue esplicitamente il mapping dell'identificatore ' {1}' su null.", + "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275": "L'ambito package.json '{0}' contiene un tipo non valido per la destinazione dell'identificatore '{1}'", + "package_json_scope_0_has_no_imports_defined_6273": "L'ambito package.json '{0}' non ha importazioni definite.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "È specificata l'opzione 'paths'. Verrà cercato un criterio per la corrispondenza con il nome del modulo '{0}'.", + "q_is_only_available_inside_character_class_1511": "'\\q' è disponibile solo all'interno della classe di caratteri.", + "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521": "'\\q' deve essere seguito da stringhe alternative racchiuse tra parentesi graffe.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Il modificatore 'readonly' può essere incluso solo in una dichiarazione di proprietà o una firma dell'indice.", + "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Il modificatore di tipo 'readonly' è consentito solo in tipi di valore letterale matrice e tupla.", + "require_call_may_be_converted_to_an_import_80005": "La chiamata a 'require' può essere convertita in un'importazione.", + "resolution_mode_can_only_be_set_for_type_only_imports_1454": "'resolution-mode' può essere impostata solo per le importazioni di tipo.", + "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "'resolution-mode' è l'unica chiave valida per l’importazione dei tipi di asserzioni.", + "resolution_mode_is_the_only_valid_key_for_type_import_attributes_1463": "'resolution-mode' è l'unica chiave valida per gli attributi di importazione di tipi.", + "resolution_mode_should_be_either_require_or_import_1453": "'resolution-mode' deve essere 'require' o 'import'.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'opzione 'rootDirs' è impostata e verrà usata per risolvere il nome del modulo relativo '{0}'.", + "super_can_only_be_referenced_in_a_derived_class_2335": "È possibile fare riferimento a 'super' solo in una classe derivata.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "È possibile fare riferimento a 'super' solo in membri di classi derivate o espressioni letterali di oggetto.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "Non è possibile fare riferimento a 'super' in un nome di proprietà calcolato.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "Non è possibile fare riferimento a 'super' in argomenti del costruttore.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "'super' è consentito solo in membri di espressioni letterali di oggetto quando il valore dell'opzione 'target' è 'ES2015' o superiore.", + "super_may_not_use_type_arguments_2754": "'super' non può usare argomenti di tipo.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "È necessario chiamare 'super' prima di accedere a una proprietà di 'super' nel costruttore di una classe derivata.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "È necessario chiamare 'super' prima di accedere a 'this' nel costruttore di una classe derivata.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' deve essere seguito da un elenco di argomento o da un accesso membro.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "L'accesso alla proprietà 'super' è consentito solo in un costruttore, in una funzione membro o in una funzione di accesso di membro di una classe derivata.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "Non è possibile fare riferimento a 'this' in un nome di proprietà calcolato.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "Non è possibile fare riferimento a 'this' nel corpo di un modulo o di uno spazio dei nomi.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "Non è possibile fare riferimento a 'this' in un inizializzatore di proprietà statica.", + "this_cannot_be_referenced_in_current_location_2332": "Non è possibile fare riferimento a 'this' nella posizione corrente.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' contiene implicitamente il tipo 'any' perché non include un'annotazione di tipo.", + "true_for_ES2022_and_above_including_ESNext_6930": "'true' per ES2022 e versioni successive, incluso ESNext.", + "true_if_composite_false_otherwise_6909": "`true` se è `composite`; in caso contrario, `false`", + "true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false_6411": "'true' quando 'moduleResolution' è 'node16', 'nodenext' o 'bundler'; in caso contrario, 'false'.", + "tsc_Colon_The_TypeScript_Compiler_6922": "tsc: il compilatore TypeScript", + "type_Colon_6902": "tipo:", + "unique_symbol_types_are_not_allowed_here_1335": "I tipi 'unique symbol' non sono consentiti in questo punto.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "I tipi 'unique symbol' sono consentiti solo nelle variabili in un'istruzione di variabile.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Non è possibile usare i tipi 'unique symbol' in una dichiarazione di variabile con nome di binding.", + "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347": "Non è possibile usare la direttiva 'use strict' con un elenco di parametri non semplice.", + "use_strict_directive_used_here_1349": "In questo punto è stata usata la direttiva 'use strict'.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "Le istruzioni 'with' non sono consentite in un blocco di funzione asincrona.", + "with_statements_are_not_allowed_in_strict_mode_1101": "Le istruzioni 'with' non sono consentite in modalità strict.", + "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057": "Con l'espressione 'yield' viene restituito implicitamente un tipo 'any' perché per il generatore che lo contiene non è presente un'annotazione di tipo restituito.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Non è possibile usare le espressioni 'yield' in un inizializzatore di parametri." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/ja/diagnosticMessages.generated.json b/node_modules/typescript/lib/ja/diagnosticMessages.generated.json new file mode 100644 index 00000000..80b3172c --- /dev/null +++ b/node_modules/typescript/lib/ja/diagnosticMessages.generated.json @@ -0,0 +1,2105 @@ +{ + "ALL_COMPILER_OPTIONS_6917": "すべてのコンパイラ オプション", + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 修飾子とインポート宣言は同時に使用できません。", + "A_0_parameter_must_be_the_first_parameter_2680": "'{0}' パラメーターは最初のパラメーターである必要があります。", + "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039": "JSDoc '@template' タグが '@typedef'、'@callback'、または '@overload' タグの後にない可能性があります", + "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033": "JSDoc '@typedef' コメントに複数の '@type' タグを含めることはできません。", + "A_bigint_literal_cannot_be_used_as_a_property_name_1539": "'bigint' リテラルをプロパティ名として使用することはできません。", + "A_bigint_literal_cannot_use_exponential_notation_1352": "bigint リテラルでは指数表記を使用できません。", + "A_bigint_literal_must_be_an_integer_1353": "bigint リテラルは整数である必要があります。", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "実装シグネチャでバインド パターン パラメーターを省略可能にすることはできません。", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' ステートメントは外側のイテレーションまたは switch ステートメント内でのみ使用できます。", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' ステートメントは、外側のステートメントのラベルにのみ移動できます。", + "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522": "予約された二重句読点を文字クラスに含めることはできません。バックスラッシュを使用してエスケープするつもりでしたか?", + "A_character_class_range_must_not_be_bounded_by_another_character_class_1516": "文字クラスの範囲を別の文字クラスでバインドすることはできません。", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "クラスで実装できるのは、オプションの型引数を指定した識別子/完全修飾名のみです。", + "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422": "クラスで実装できるのは、オブジェクト型または静的な既知のメンバーを持つオブジェクト型の積集合のみです。", + "A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values_2863": "クラスが '{0}' のようなプリミティブ型を拡張することはできません。クラスは、コンストラクト可能な値のみを拡張できます。", + "A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types_2864": "クラスが '{0}' のようなプリミティブ型を実装することはできません。実装できるのは、その他の名前付きオブジェクト型のみです。", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "'default' の修飾子がないクラス宣言には名前が必要です。", + "A_class_member_cannot_have_the_0_keyword_1248": "クラス メンバーに '{0}' キーワードを指定することはできません。", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "コンマ式は計算されたプロパティ名では使用できません。", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "計算されたプロパティ名は、型パラメーターをそれを含む型から参照することはできません。", + "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166": "クラス プロパティ宣言内の計算されたプロパティ名には、単純なリテラル型または 'unique symbol' 型が必要です。", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "メソッド オーバーロード内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "型リテラル内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "環境コンテキスト内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "インターフェイス内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "計算されたプロパティ名は 'string' 型、'number' 型、'symbol' 型、または 'any' 型のいずれかでなければなりません。", + "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355": "'const' アサーションは、列挙型メンバーへの参照、文字列、数値、ブール値、配列、オブジェクト リテラルにのみ適用できます。", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const 列挙型メンバーは、文字列リテラルを使用してのみアクセスできます。", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254": "環境コンテキストの 'const' 初期化子は、文字列または数値リテラル、もしくはリテラル列挙型の参照である必要があります。", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "コンストラクターのクラスが 'null' を拡張する場合、そのコンストラクターに 'super' の呼び出しを含めることはできません。", + "A_constructor_cannot_have_a_this_parameter_2681": "コンストラクターに 'this' パラメーターを指定することはできません。", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' ステートメントは外側のイテレーション内でのみ使用できます。", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' ステートメントは、外側のイテレーション ステートメントのラベルにのみ移動できます。", + "A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_f_2846": "宣言ファイルを 'import type' なしでインポートすることはできません。代わりに実装ファイルト '{0}' をインポートするつもりでしたか?", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "'declare' 修飾子は、環境コンテキストでは使用できません。", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "デコレーターが装飾できるのは、オーバーロードではなく、メソッドの実装のみです。", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' 句を 'switch' ステートメントで複数回使用することはできません。", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "既定のエクスポートは、ECMAScript スタイルのモジュールでのみ使用できます。", + "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258": "既定のエクスポートは、ファイルまたはモジュールの宣言のトップレベルにある必要があります。", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "限定代入アサーション '!' は、このコンテキストで許可されていません。", + "A_destructuring_declaration_must_have_an_initializer_1182": "非構造化宣言には初期化子が必要です。", + "A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_t_2712": "ES5 の動的インポート呼び出しには、'Promise' コンストラクターが必要です。'Promise' コンストラクターの宣言があることを確認するか、'--lib' オプションに 'ES2015' を組み込んでください。", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "動的インポート呼び出しは 'Promise' を返します。'Promise' の宣言があること、または '--lib' オプションに 'ES2015' を含めていることをご確認ください。", + "A_file_cannot_have_a_reference_to_itself_1006": "ファイルにそれ自体への参照を含めることはできません。", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "'never' を返す関数には、到達可能なエンド ポイントがありません。", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "'new' キーワードで呼び出される関数に、'void' である 'this' 型を使用することはできません。", + "A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value_2355": "宣言された型が 'undefined'、'void'、または 'any' でない関数は、値を返す必要があります。", + "A_generator_cannot_have_a_void_type_annotation_2505": "ジェネレーターに 'void' 型の注釈を指定することはできません。", + "A_get_accessor_cannot_have_parameters_1054": "'get' アクセサーにパラメーターを指定することはできません。", + "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808": "get アクセサーは、少なくともセッターと同程度にアクセス可能である必要があります", + "A_get_accessor_must_return_a_value_2378": "'get' アクセサーは値を返す必要があります。", + "A_label_is_not_allowed_here_1344": "A ラベルはここでは使用できません。", + "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "ラベル付きのタプル要素を optional として宣言するには、型の後ではなく名前の後とコロンの前に疑問符を付けます。", + "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "ラベル付きのタプル要素を rest として宣言するには、型の前ではなく名前の前に '...' を付けます。", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "マップされた型では、プロパティまたはメソッドを宣言しない場合があります。", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "列挙型宣言のメンバー初期化子は、他の列挙型で定義されたメンバーを含め、その後で宣言されたメンバーを参照できません。", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin クラスには、型 'any[]' の単一の rest パラメーターを持つコンストラクターが必要です。", + "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "抽象コンストラクト シグネチャを含む型変数から拡張される mixin クラスも、'abstract' として宣言する必要があります。", + "A_module_cannot_have_multiple_default_exports_2528": "モジュールに複数の既定のエクスポートを含めることはできません。", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "名前空間宣言は、それとマージするクラスや関数と異なるファイルに配置できません。", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "名前空間宣言は、それとマージするクラスや関数より前に配置できません。", + "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235": "名前空間宣言は、名前空間またはモジュールの最上位レベルでのみ許可されます。", + "A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_key_1540": "'namespace' 宣言を 'module' キーワードを使用して宣言することはできません。代わりに 'namespace' キーワードを使用してください。", + "A_non_dry_build_would_build_project_0_6357": "非 -dry ビルドを実行した場合、プロジェクト '{0}' がビルドされます", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "非 -dry ビルドを実行した場合、次のファイルが削除されます: {0}", + "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374": "non-dry build では、プロジェクト '{0}' の出力のタイムスタンプが更新されます", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "パラメーター初期化子は、関数またはコンストラクターの実装でのみ指定できます。", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "パラメーター プロパティは、rest パラメーターを使用して宣言することはできません。", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "パラメーター プロパティは、コンストラクターの実装でのみ指定できます。", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "パラメーター プロパティは、バインド パターンを使用して宣言することはできません。", + "A_promise_must_have_a_then_method_1059": "Promise には 'then' メソッドが必要です。", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "型が 'unique symbol' 型のクラスのプロパティは、'static' と 'readonly' の両方である必要があります。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "型が 'unique symbol' 型のインターフェイスまたは型リテラルのプロパティは、'readonly' である必要があります。", + "A_required_element_cannot_follow_an_optional_element_1257": "必須要素を省略可能な要素の後に指定することはできません。", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必須パラメーターを省略可能なパラメーターの後に指定することはできません。", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 要素にバインド パターンを含めることはできません。", + "A_rest_element_cannot_follow_another_rest_element_1265": "rest 要素を別の rest 要素の後に指定することはできません。", + "A_rest_element_cannot_have_a_property_name_2566": "rest 要素にプロパティ名を指定することはできません。", + "A_rest_element_cannot_have_an_initializer_1186": "rest 要素に初期化子を指定することはできません。", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "rest 要素は非構造化パターンの最後に指定する必要があります。", + "A_rest_element_type_must_be_an_array_type_2574": "rest 要素型は配列型である必要があります。", + "A_rest_parameter_cannot_be_optional_1047": "rest パラメーターを省略可能にすることはできません。", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest パラメーターに初期化子を指定することはできません。", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest パラメーターはパラメーター リストの最後に指定する必要があります。", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest パラメーターは配列型でなければなりません。", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest パラメーターまたはバインド パターンに末尾のコンマがない可能性があります。", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' ステートメントは、関数本体でのみ使用できます。", + "A_return_statement_cannot_be_used_inside_a_class_static_block_18041": "'return' ステートメントの使用が無効です。クラスの静的ブロック内では使用できません。", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "'baseUrl' の相対的な場所を検索するためにインポートを再マップする一連のエントリ。", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' アクセサーに、戻り値の型の注釈を指定することはできません。", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' アクセサーに、省略可能パラメーターを指定することはできません。", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' アクセサーに rest パラメーターを指定することはできません。", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' アクセサーにはパラメーターを 1 つだけ指定しなければなりません。", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' アクセサーのパラメーターに初期化子を含めることはできません。", + "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556": "spread 引数には、組の種類を指定するか、rest パラメーターに渡す必要があります。", + "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401": "'super' の呼び出しは、初期化されたプロパティ、パラメーターのプロパティ、private 識別子が派生クラスに含まれている場合は、コンストラクターのルートレベルのステートメントである必要があります。", + "A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_2376": "'super' の呼び出しは、初期化されたプロパティ、パラメーターのプロパティ、private 識別子が派生クラスに含まれている場合は、'super' や 'this' を参照するコンストラクターの最初のステートメントである必要があります。", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "'this' ベース型のガードはパラメーター ベース型のガードとは互換性がありません。", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 型はクラスまたはインターフェイスの静的でないメンバーでのみ使用できます。", + "A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimM_1287": "'verbatimModuleSyntax' が有効である場合、CommonJS モジュール内の値宣言でトップレベルの 'export' 修飾子を使用することはできません。", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' ファイルは既に '{0}' で定義されています。", + "A_tuple_member_cannot_be_both_optional_and_rest_5085": "タプル メンバーを optional と rest の両方に指定することはできません。", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "タプル型に負の値のインデックスを指定することはできません。", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "累乗式の左辺で型アサーション式を使用することはできません。式を括弧で囲むことを検討してください。", + "A_type_literal_property_cannot_have_an_initializer_1247": "型リテラル プロパティに初期化子を使用することはできません。", + "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "型のみのインポートでは既定のインポートまたは名前付きバインドを指定できますが、両方を指定することはできません。", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "型の述語は rest パラメーターを参照できません。", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "型の述語は、バインド パターン内の要素 '{0}' を参照できません。", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "型の述語は、関数およびメソッドの戻り値の型の位置でのみ使用できます。", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "type 述語の型はそのパラメーターの型に割り当て可能である必要があります。", + "A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_w_1272": "'isolatedModules' と 'emitDecoratorMetadata' が有効になっている場合は、装飾された署名で参照される型を 'import type' または名前空間インポートでインポートする必要があります。", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "型が 'unique symbol' 型の変数は、'const' である必要があります。", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "'yield' 式は、ジェネレーター本文でのみ使用できます。", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "クラス '{1}' の抽象メソッド '{0}' には super 式を介してアクセスできません。", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象メソッドは抽象クラス内でのみ使用できます。", + "Abstract_properties_can_only_appear_within_an_abstract_class_1253": "抽象プロパティは抽象クラス内でのみ使用できます。", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "コンストラクター内でクラス '{1}' の抽象プロパティ '{0}' にアクセスできません。", + "Accessibility_modifier_already_seen_1028": "アクセシビリティ修飾子は既に存在します。", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "アクセサーは ECMAScript 5 以上をターゲットにする場合にのみ使用できます。", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "アクセサーはどちらも抽象または非抽象である必要があります。", + "Add_0_to_unresolved_variable_90008": "'{0}' を未解決の変数に追加します", + "Add_a_return_statement_95111": "return ステートメントを追加する", + "Add_a_return_type_to_the_function_declaration_9031": "関数宣言に戻り値の型を追加してください。", + "Add_a_return_type_to_the_function_expression_9030": "関数式に戻り値の型を追加してください。", + "Add_a_return_type_to_the_get_accessor_declaration_9032": "get アクセサー宣言に戻り値の型を追加してください。", + "Add_a_return_type_to_the_method_9034": "メソッドに戻り値の型を追加してください", + "Add_a_type_annotation_to_the_parameter_0_9028": "パラメーター {0} に型注釈を追加してください。", + "Add_a_type_annotation_to_the_property_0_9029": "プロパティ {0} に型注釈を追加してください。", + "Add_a_type_annotation_to_the_variable_0_9027": "変数 {0} に型注釈を追加してください。", + "Add_a_type_to_parameter_of_the_set_accessor_declaration_9033": "set アクセサー宣言のパラメーターに型を追加してください。", + "Add_all_missing_async_modifiers_95041": "不足しているすべての 'async' 修飾子を追加します", + "Add_all_missing_attributes_95168": "不足しているすべての属性を追加する", + "Add_all_missing_call_parentheses_95068": "見つからない呼び出しのかっこをすべて追加します", + "Add_all_missing_function_declarations_95157": "不足しているすべての関数宣言を追加します", + "Add_all_missing_imports_95064": "不足しているすべてのインポートを追加する", + "Add_all_missing_members_95022": "不足しているすべてのメンバーを追加します", + "Add_all_missing_override_modifiers_95162": "不足しているすべての 'override' 修飾子を追加する", + "Add_all_missing_parameters_95190": "不足しているすべてのプロパティを追加してください", + "Add_all_missing_properties_95166": "不足しているすべてのプロパティを追加する", + "Add_all_missing_return_statement_95114": "不足しているすべての return ステートメントを追加する", + "Add_all_missing_super_calls_95039": "不足しているすべての super の呼び出しを追加します", + "Add_all_missing_type_annotations_90067": "不足しているすべての型注釈を追加してください", + "Add_all_optional_parameters_95193": "すべてのオプション パラメーターを追加してください", + "Add_annotation_of_type_0_90062": "型 '{0}' の注釈を追加してください", + "Add_async_modifier_to_containing_function_90029": "含まれている関数に async 修飾子を追加します", + "Add_await_95083": "'await' を追加する", + "Add_await_to_initializer_for_0_95084": "'{0}' の初期化子に 'await' を追加する", + "Add_await_to_initializers_95089": "初期化子に 'await' を追加する", + "Add_braces_to_arrow_function_95059": "アロー関数に中かっこを追加します", + "Add_const_to_all_unresolved_variables_95082": "すべての未解決の変数に 'const' を追加する", + "Add_const_to_unresolved_variable_95081": "未解決の変数に 'const' を追加する", + "Add_definite_assignment_assertion_to_property_0_95020": "プロパティ '{0}' に限定代入アサーションを追加します", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "初期化されていないすべてのプロパティに限定代入アサーションを追加します", + "Add_export_to_make_this_file_into_a_module_95097": "'export {}' を追加して、このファイルをモジュールにする", + "Add_extends_constraint_2211": "'extends' 制約を追加します。", + "Add_extends_constraint_to_all_type_parameters_2212": "すべての型パラメーターに 'extends' 制約を追加する", + "Add_import_from_0_90057": "\"{0}\" からのインポートの追加", + "Add_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加する", + "Add_initializer_to_property_0_95019": "プロパティ '{0}' に初期化子を追加します", + "Add_initializers_to_all_uninitialized_properties_95027": "初期化されていないすべてのプロパティに初期化子を追加します", + "Add_missing_attributes_95167": "不足している属性の追加", + "Add_missing_call_parentheses_95067": "見つからない呼び出しのかっこを追加します", + "Add_missing_comma_for_object_member_completion_0_95187": "オブジェクト メンバー補完 '{0}' に不足しているコンマを追加してください。", + "Add_missing_enum_member_0_95063": "不足している列挙型メンバー '{0}' を追加する", + "Add_missing_function_declaration_0_95156": "不足している関数宣言 '{0}' を追加します", + "Add_missing_new_operator_to_all_calls_95072": "不足している 'new' 演算子をすべての呼び出しに追加する", + "Add_missing_new_operator_to_call_95071": "不足している 'new' 演算子を呼び出しに追加する", + "Add_missing_parameter_to_0_95188": "'{0}' に不足しているパラメーターを追加してください", + "Add_missing_parameters_to_0_95189": "'{0}' に不足しているパラメーターを追加してください", + "Add_missing_properties_95165": "不足しているすべてのプロパティの追加", + "Add_missing_super_call_90001": "欠落している 'super()' 呼び出しを追加する", + "Add_missing_typeof_95052": "不足している 'typeof' を追加します", + "Add_names_to_all_parameters_without_names_95073": "名前のないすべてのパラメーターに名前を追加する", + "Add_optional_parameter_to_0_95191": "オプション パラメーターを '{0}' に追加してください", + "Add_optional_parameters_to_0_95192": "省略可能なパラメーターを '{0}' に追加する", + "Add_or_remove_braces_in_an_arrow_function_95058": "アロー関数内の中かっこを追加または削除します", + "Add_override_modifier_95160": "'override' 修飾子を追加する", + "Add_parameter_name_90034": "パラメーター名を追加する", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "メンバー名と一致するすべての未解決の変数に修飾子を追加します", + "Add_resolution_mode_import_attribute_95196": "'resolution-mode' インポート属性を追加する", + "Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it_95197": "'resolution-mode' インポート属性を、必要とするすべての型のみのインポートに追加する", + "Add_return_type_0_90063": "戻り値の型 '{0}' を追加してください", + "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035": "型を明示的にするには、この式に satisfies と型アサーションを追加してください (satisfies T as T)。", + "Add_satisfies_and_an_inline_type_assertion_with_0_90068": "'{0}' を使用して satisfies とインライン型のアサーションを追加してください", + "Add_to_all_uncalled_decorators_95044": "呼び出されていないすべてのデコレーターに '()' を追加します", + "Add_ts_ignore_to_all_error_messages_95042": "すべてのエラー メッセージに '@ts-ignore' を追加します", + "Add_undefined_to_a_type_when_accessed_using_an_index_6674": "インデックスを使用してアクセスした場合は、'undefined' を型に追加します。", + "Add_undefined_to_optional_property_type_95169": "省略可能なプロパティ型に 'undefined' を追加します", + "Add_undefined_type_to_all_uninitialized_properties_95029": "初期化されていないすべてのプロパティに未定義の型を追加します", + "Add_undefined_type_to_property_0_95018": "プロパティ '{0}' に '未定義' の型を追加します", + "Add_unknown_conversion_for_non_overlapping_types_95069": "重複していない型に対して 'unknown' 変換を追加する", + "Add_unknown_to_all_conversions_of_non_overlapping_types_95070": "重複していない型のすべての変換に 'unknown' を追加する", + "Add_void_to_Promise_resolved_without_a_value_95143": "値なしで解決された Promise に 'void' を追加します", + "Add_void_to_all_Promises_resolved_without_a_value_95144": "値なしで解決されたすべての Promise に 'void' を追加します", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json ファイルを追加すると、TypeScript ファイルと JavaScript ファイルの両方を含むプロジェクトを整理できます。詳細については、https://aka.ms/tsconfig をご覧ください。", + "All_declarations_of_0_must_have_identical_constraints_2838": "'{0}' のすべての宣言には、同一の制約が必要です。", + "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' のすべての宣言には、同一の修飾子が必要です。", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' のすべての宣言には、同一の型パラメーターがある必要があります。", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象メソッドの宣言はすべて連続している必要があります。", + "All_destructured_elements_are_unused_6198": "非構造化要素はいずれも使用されていません。", + "All_imports_in_import_declaration_are_unused_6192": "インポート宣言内のインポートはすべて未使用です。", + "All_type_parameters_are_unused_6205": "すべての型パラメーターが使用されていません。", + "All_variables_are_unused_6199": "すべての変数は未使用です。", + "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600": "JavaScript ファイルをプログラムの一部として使用することを許可します。'checkJS' オプションを使用して、これらのファイルからエラーを取得してください。", + "Allow_accessing_UMD_globals_from_modules_6602": "モジュールから UMD グローバルへのアクセスを許可します。", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "既定のエクスポートがないモジュールからの既定のインポートを許可します。これは、型チェックのみのため、コード生成には影響を与えません。", + "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601": "モジュールに既定のエクスポートがない場合は、'import x from y' を許可します。", + "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639": "tslib からヘルパー関数をファイルごとに含めるのではなく、プロジェクトごとに 1 回インポートすることを許可します。", + "Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noE_6407": "TypeScript ファイル拡張子を含めるインポートを許可してください。'--moduleResolution bundler' と '--noEmit' または '--emitDeclarationOnly' のいずれかを設定する必要があります。", + "Allow_javascript_files_to_be_compiled_6102": "javascript ファイルのコンパイルを許可します。", + "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691": "モジュールを解決するときに複数のフォルダーを 1 つのフォルダーとして処理することを許可します。", + "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261": "既に含まれているファイル名 '{0}' は、ファイル名 '{1}' と大文字と小文字の指定だけが異なります。", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "アンビエント モジュール宣言では、相対モジュール名を指定できません。", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "アンビエント モジュールを、他のモジュールまたは名前空間内の入れ子にすることはできません。", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を代入することはできません。", + "An_abstract_accessor_cannot_have_an_implementation_1318": "抽象アクセサーに実装を含めることはできません。", + "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010": "アクセシビリティ修飾子を private 識別子と共に使用することはできません。", + "An_accessor_cannot_have_type_parameters_1094": "アクセサーに型パラメーターを指定することはできません。", + "An_accessor_property_cannot_be_declared_optional_1276": "'accessor' プロパティはオプションとして宣言できません。", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "アンビエント モジュール宣言は、ファイルの最上位にのみ使用できます。", + "An_argument_for_0_was_not_provided_6210": "'{0}' の引数が指定されていません。", + "An_argument_matching_this_binding_pattern_was_not_provided_6211": "このバインド パターンに一致する引数が指定されていません。", + "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356": "算術オペランドは 'any' 型、'number' 型、’bigint' 型、列挙型のいずれかである必要があります。", + "An_arrow_function_cannot_have_a_this_parameter_2730": "アロー関数に 'this' パラメーターを指定することはできません。", + "An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_2705": "ES5 の非同期の関数またはメソッドには、'Promise' コンストラクターが必要です。'Promise' コンストラクターの宣言があることを確認するか、'--lib' オプションに 'ES2015' を組み込んでください。", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "非同期関数またはメソッドは 'Promise' を返す必要があります。'Promise' の宣言があること、または '--lib' オプションに 'ES2015' を含めていることを確認してください。", + "An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。", + "An_element_access_expression_should_take_an_argument_1011": "要素アクセス式では、引数を取る必要があります。", + "An_enum_member_cannot_be_named_with_a_private_identifier_18024": "private 識別子を使用して列挙型メンバーに名前を付けることはできません。", + "An_enum_member_cannot_have_a_numeric_name_2452": "列挙型メンバーに数値名を含めることはできません。", + "An_enum_member_name_must_be_followed_by_a_or_1357": "列挙型メンバー名の後には、','、'='、'}' のいずれかを指定する必要があります。", + "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928": "使用可能なすべてのコンパイラ オプションを示す、この情報の拡張バージョン", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの代入は、エクスポートされた他の要素を含むモジュールでは使用できません。", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの代入は、名前空間では使用できません。", + "An_export_assignment_cannot_have_modifiers_1120": "エクスポートの代入に修飾子を指定することはできません。", + "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231": "エクスポートの割り当ては、ファイルまたはモジュールの宣言のトップレベルにある必要があります。", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474": "エクスポート宣言は、モジュールの最上位レベルでのみ使用できます。", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233": "エクスポート宣言は、名前空間またはモジュールの最上位レベルでのみ使用できます。", + "An_export_declaration_cannot_have_modifiers_1193": "エクスポート宣言に修飾子を指定することはできません。", + "An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolve_1283": "'verbatimModuleSyntax' が有効である場合、 'export =' 宣言は実際の値を参照する必要がありますが、'{0}' は型のみの宣言に解決されます。", + "An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers__1282": "'verbatimModuleSyntax' が有効である場合、'export =' 宣言は値を参照する必要がありますが、'{0}' は型のみを参照しています。", + "An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_1285": "'verbatimModuleSyntax' が有効である場合、'export default' は実際の値を参照する必要がありますが、'{0}' は型のみの宣言に解決されます。", + "An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_1284": "'verbatimModuleSyntax' が有効である場合、'export default' は値を参照する必要がありますが、'{0}' は型のみを参照しています。", + "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345": "'void' 型の式は、真実性をテストできません。", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "拡張された Unicode エスケープ値は 0x0 と 0x10FFFF の間 (両端を含む) でなければなりません。", + "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351": "識別子またはキーワードを数値リテラルのすぐ後に指定することはできません。", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "実装は環境コンテキストでは宣言できません。", + "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "インポート エイリアスは、'export type' を使用してエクスポートされた宣言を参照できません。", + "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "インポート エイリアスは、'import type' を使用してインポートされた宣言を参照できません。", + "An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabl_1288": "'verbatimModuleSyntax' が有効である場合、インポート エイリアスを型または型のみの宣言に解決することはできません。", + "An_import_alias_cannot_use_import_type_1392": "インポート エイリアスで 'import type' を使用することはできません", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473": "インポート宣言は、モジュールの最上位レベルでのみ使用できます。", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232": "インポート宣言は、名前空間またはモジュールの最上位レベルでのみ使用できます。", + "An_import_declaration_cannot_have_modifiers_1191": "インポート宣言に修飾子を指定することはできません。", + "An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled_5097": "'allowImportingTsExtensions' が有効である場合、インポート パスの末尾には '{0}' 拡張子のみを指定できます。", + "An_index_signature_cannot_have_a_rest_parameter_1017": "インデックス シグネチャに rest パラメーターを指定することはできません。", + "An_index_signature_cannot_have_a_trailing_comma_1025": "インデックス シグネチャの末尾にコンマを指定することはできません。", + "An_index_signature_must_have_a_type_annotation_1021": "インデックス シグネチャには型の注釈が必要です。", + "An_index_signature_must_have_exactly_one_parameter_1096": "インデックス シグネチャには、パラメーターを 1 つだけ指定しなければなりません。", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "インデックス シグネチャのパラメーターに疑問符を指定することはできません。", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "インデックス シグネチャのパラメーターにアクセシビリティ修飾子を指定することはできません。", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "インデックス シグネチャのパラメーターに初期化子を指定することはできません。", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "インデックス シグネチャのパラメーターには型の注釈が必要です。", + "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "インデックス シグネチャ パラメーターの型をリテラル型またはジェネリック型にすることはできません。代わりに、マップされたオブジェクト型の使用を検討してください。", + "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "インデックス シグネチャ パラメーター型は、'string'、'number'、'symbol'、またはテンプレート リテラルの型である必要があります。", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "インスタンス化式の後にプロパティ アクセスを続けることはできません。", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "インターフェイスが拡張するのは、オプションの型引数が指定された識別子/完全修飾名のみです。", + "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "インターフェイスが拡張できるのは、オブジェクト型または静的な既知のメンバーを持つオブジェクト型の積集合のみです。", + "An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types_2840": "インターフェイスが '{0}' のようなプリミティブ型を拡張することはできません。拡張できるのは、その他の名前付きオブジェクト型のみです。", + "An_interface_property_cannot_have_an_initializer_1246": "インターフェイス プロパティに初期化子を使用することはできません。", + "An_iterator_must_have_a_next_method_2489": "反復子には 'next()' メソッドが必要です。", + "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "@jsx pragma を JSX フラグメントで使用する場合は、@jsxFrag pragma が必要です。", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "オブジェクト リテラルに同じ名前の複数の get/set アクセサーを指定することはできません。", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117": "オブジェクト リテラルに同じ名前の複数のプロパティを指定することはできません。", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "オブジェクト リテラルには、同じ名前のプロパティおよびアクセサーを指定することはできません。", + "An_object_member_cannot_be_declared_optional_1162": "オブジェクト メンバーを省略可能として宣言することはできません。", + "An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_han_2861": "オブジェクトの '[Symbol.hasInstance]' メソッドを 'instanceof' 式の右側で使用するには、このメソッドがブール値を返す必要があります。", + "An_optional_chain_cannot_contain_private_identifiers_18030": "省略可能なチェーンには、pirvate 識別子を含めることはできません。", + "An_optional_element_cannot_follow_a_rest_element_1266": "省略可能な要素を rest 要素の後に指定することはできません。", + "An_outer_value_of_this_is_shadowed_by_this_container_2738": "'this' の外部値がこのコンテナーによってシャドウされています。", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "オーバーロード シグネチャをジェネレーターとして宣言することはできません。", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "累乗式の左辺で '{0}' 演算子を含む単項式を使用することはできません。式を括弧で囲むことを検討してください。", + "Annotate_everything_with_types_from_JSDoc_95043": "すべてに JSDoc の型で注釈を付けます", + "Annotate_types_of_properties_expando_function_in_a_namespace_90071": "名前空間内のプロパティ expando 関数の型に注釈を付けてください", + "Annotate_with_type_from_JSDoc_95009": "JSDoc の型で注釈を付けます", + "Another_export_default_is_here_2753": "別のエクスポートの既定値がここにあります。", + "Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_t_1528": "複数の文字と一致する可能性のある Unicode プロパティは、Unicode Sets (v) フラグが設定されている場合にのみ使用できます。", + "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518": "複数の文字と一致する可能性のあるものはすべて、負数化された文字クラス内では無効です。", + "Are_you_missing_a_semicolon_2734": "セミコロンを忘れていませんか?", + "Argument_expression_expected_1135": "引数式が必要です。", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' オプションの引数は {1} である必要があります。", + "Argument_of_dynamic_import_cannot_be_spread_element_1325": "動的インポートの引数にスプレッド要素は指定できません。", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "型 '{0}' の引数を型 '{1}' のパラメーターに割り当てることはできません。", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379": "型 '{0}' の引数を、'exactOptionalPropertyTypes: true' が指定されている型 '{1}' のパラメーターに割り当てることはできません。ターゲットのプロパティの型に 'undefined' を追加することを検討してください。", + "Arguments_for_the_rest_parameter_0_were_not_provided_6236": "rest パラメーター '{0}' の引数が指定されませんでした。", + "Array_element_destructuring_pattern_expected_1181": "配列要素の非構造化パターンが必要です。", + "Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations_9018": "spread 要素を含む配列を --isolatedDeclarations と共に推論することはできません。", + "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775": "アサーションでは、呼び出し先のすべての名前が明示的な型の注釈で宣言されている必要があります。", + "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776": "アサーションでは、呼び出し先が識別子または修飾名である必要があります。", + "Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations__9023": "宣言せずに関数にプロパティを割り当てることは、--isolatedDeclarations ではサポートされていません。この関数に割り当てられたプロパティに明示的な宣言を追加してください。", + "Asterisk_Slash_expected_1010": "'*/' が必要です。", + "At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9009": "少なくとも 1 つのアクセサーに、--isolatedDeclarations を含む明示的な型の注釈が必要です。", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "グローバル スコープの拡張を直接入れ子にできるのは、外部モジュールまたは環境モジュールの宣言内のみです。", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "グローバル スコープの拡張は、環境コンテキストに既にある場合を除いて、'declare' 修飾子を使用する必要があります。", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "プロジェクト '{0}' で型指定の自動検出が有効になっています。キャッシュの場所 '{2}' を使用して、モジュール '{1}' に対して追加の解決パスを実行しています。", + "BUILD_OPTIONS_6919": "ビルド オプション", + "Backwards_Compatibility_6253": "下位互換性", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "基底クラスの式ではクラスの型パラメーターを参照することはできません。", + "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509": "基底コンストラクターの戻り値の型 '{0}' が、オブジェクト型または静的な既知のメンバーを持つオブジェクト型の積集合ではありません。", + "Base_constructors_must_all_have_the_same_return_type_2510": "既定コンストラクターの戻り値の型は、すべて同じである必要があります。", + "Base_directory_to_resolve_non_absolute_module_names_6083": "相対モジュール名を解決するためのベース ディレクトリ。", + "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737": "ターゲットが ES2020 未満の場合、bigint リテラルは使用できません。", + "Binary_digit_expected_1177": "2 進の数字が必要です。", + "Binding_element_0_implicitly_has_an_1_type_7031": "バインド要素 '{0}' には暗黙的に '{1}' 型が含まれます。", + "Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations_9019": "バインド要素を --isolatedDeclarations と共に直接エクスポートすることはできません。", + "Block_scoped_variable_0_used_before_its_declaration_2448": "ブロック スコープの変数 '{0}' が、宣言の前に使用されています。", + "Build_a_composite_project_in_the_working_directory_6925": "作業ディレクトリに複合プロジェクトを作成します。", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636": "最新の状態であると思われるものを含むすべてのプロジェクトをビルドします。", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "最新でない場合は、1 つ以上のプロジェクトとその依存関係をビルドします", + "Build_option_0_requires_a_value_of_type_1_5073": "ビルド オプション '{0}' には型 {1} の値が必要です。", + "Building_project_0_6358": "プロジェクト \"{0}\" をビルドしています...", + "Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any_6720": "組み込みの反復子は、'any' の代わりに 'undefined' の 'TReturn' 型を使用してインスタンス化されます。", + "COMMAND_LINE_FLAGS_6921": "コマンドライン フラグ", + "COMMON_COMMANDS_6916": "一般的なコマンド", + "COMMON_COMPILER_OPTIONS_6920": "一般的なコンパイラ オプション", + "Call_decorator_expression_90028": "デコレーター式を呼び出す", + "Call_signature_return_types_0_and_1_are_incompatible_2202": "呼び出しシグネチャの戻り値の型 '{0}' と '{1}' には互換性がありません。", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "戻り値の型の注釈がない呼び出しシグネチャの戻り値の型は、暗黙的に 'any' になります。", + "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204": "引数なしの呼び出しシグネチャに、互換性のない戻り値の型 '{0}' と '{1}' が含まれています。", + "Can_only_convert_logical_AND_access_chains_95142": "論理 AND のアクセス チェーンのみを変換できます", + "Can_only_convert_named_export_95164": "名前付きエクスポートのみを変換できます", + "Can_only_convert_property_with_modifier_95137": "修飾子を伴うプロパティの変換のみ可能です", + "Can_only_convert_string_concatenations_and_string_literals_95154": "文字列の連結と文字列リテラルのみを変換できます", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}.{1}' にアクセスできません。'{0}' は型で、名前空間ではありません。'{0}[\"{1}\"]' で '{0}' のプロパティ '{1}' の型を取得するつもりでしたか?", + "Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead_1281": "'{1}' が有効である場合、修飾しないで別のファイルから '{0}' にアクセスすることはできません。代わりに '{2}' を使用してください。", + "Cannot_access_ambient_const_enums_when_0_is_enabled_2748": "'{0}' が有効である場合、アンビエント const 列挙型にアクセスすることはできません。", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "'{0}' コンストラクター型を '{1}' コンストラクター型に割り当てることができません。", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "抽象コンストラクター型を非抽象コンストラクター型に割り当てることはできません。", + "Cannot_assign_to_0_because_it_is_a_class_2629": "クラスであるため、'{0}' に割り当てることはできません。", + "Cannot_assign_to_0_because_it_is_a_constant_2588": "定数であるため、'{0}' に代入することはできません。", + "Cannot_assign_to_0_because_it_is_a_function_2630": "関数であるため、'{0}' に割り当てることはできません。", + "Cannot_assign_to_0_because_it_is_a_namespace_2631": "名前空間であるため、'{0}' に割り当てることはできません。", + "Cannot_assign_to_0_because_it_is_a_read_only_property_2540": "読み取り専用プロパティであるため、'{0}' に代入することはできません。", + "Cannot_assign_to_0_because_it_is_an_enum_2628": "列挙型であるため、'{0}' に割り当てることはできません。", + "Cannot_assign_to_0_because_it_is_an_import_2632": "インポートであるため、'{0}' に割り当てることはできません。", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "変数ではないため、'{0}' に割り当てられません。", + "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803": "プライベート メソッド '{0}' に割り当てることはできません。プライベート メソッドは書き込み可能ではありません。", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "モジュール '{0}' は、モジュール以外のエンティティに解決するので拡張できません。", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "モジュール '{0}' は、モジュール以外のエンティティに解決するため、値のエクスポートで拡張できません。", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "'--module' フラグが 'amd' か 'system' でない限り、オプション '{0}' を使用してモジュールをコンパイルできません。", + "Cannot_create_an_instance_of_an_abstract_class_2511": "抽象クラスのインスタンスは作成できません。", + "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766": "反復子の 'next' メソッドには型 '{1}' が必要なため、値に反復をデリゲートすることはできませんが、含まれるジェネレーターは常に '{0}' を送信します。", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "'{0}' をエクスポートできません。モジュールからエクスポートできるのはローカル宣言のみです。", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "クラス '{0}' を拡張できません。Class コンストラクターがプライベートに設定されています。", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "インターフェイス '{0}' を拡張できません。'implements' ですか?", + "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081": "現在のディレクトリに tsconfig.json ファイルが見つかりません: {0}。", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "指定されたディレクトリに tsconfig.json ファイルが見つかりません: '{0}'。", + "Cannot_find_global_type_0_2318": "グローバル型 '{0}' が見つかりません。", + "Cannot_find_global_value_0_2468": "グローバル値 '{0}' が見つかりません。", + "Cannot_find_lib_definition_for_0_2726": "'{0}' のライブラリ定義が見つかりません。", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "'{0}' のライブラリ定義が見つかりません。'{1}' ですか?", + "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732": "モジュール '{0}' が見つかりません。'--resolveJsonModule' を使用して '.json' 拡張子を持つモジュールをインポートすることをご検討ください。", + "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_t_2792": "モジュール '{0}' が見つかりません。'moduleResolution' オプションを 'nodenext' に設定するか、'paths' オプションにエイリアスを追加するつもりでしたか?", + "Cannot_find_module_0_or_its_corresponding_type_declarations_2307": "モジュール '{0}' またはそれに対応する型宣言が見つかりません。", + "Cannot_find_name_0_2304": "名前 '{0}' が見つかりません。", + "Cannot_find_name_0_Did_you_mean_1_2552": "'{0}' という名前は見つかりません。'{1}' ですか?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "名前 '{0}' が見つかりません。インスタンス メンバー 'this.{0}' ですか?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "名前 '{0}' が見つかりません。静的メンバー '{1}.{0}' ですか?", + "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311": "名前 '{0}' が見つかりません。これを非同期関数に書き込むということですか?", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583": "名前 '{0}' が見つかりません。ターゲット ライブラリを変更する必要がありますか? 'lib' コンパイラ オプションを '{1}' 以降に変更してみてください。", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584": "名前 '{0}' が見つかりません。ターゲット ライブラリを変更しますか? 'lib' コンパイラ オプションが 'dom' を含むように変更してみてください。", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2867": "名前 '{0}' が見つかりません。Bun の型定義をインストールする必要がありますか?'npm i --save-dev @types/bun' をお試しください。", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2868": "名前 '{0}' が見つかりません。Bun の型定義をインストールする必要がありますか?'npm i --save-dev @types/bun' を試してから、tsconfig 内の型フィールドに 'bun' を追加してください。", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582": "名前 '{0}' が見つかりません。テスト ランナーの型定義をインストールする必要がありますか? `npm i --save-dev @types/jest` または `npm i --save-dev @types/mocha` をお試しください。", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593": "名前 '{0}' が見つかりません。テスト ランナーの型定義をインストールする必要がありますか? `npm i --save-dev @types/jest` または `npm i --save-dev @types/mocha` を試してから、tsconfig の型フィールドに 'jest' または 'mocha' を追加してください。", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581": "名前 '{0}' が見つかりません。jQuery の型定義をインストールする必要がありますか? `npm i --save-dev @types/jquery` をお試しください。", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592": "名前 '{0}' が見つかりません。jQuery の型定義をインストールする必要がありますか? `npm i --save-dev @types/jquery` を試してから、tsconfig の型フィールドに 'jquery' を追加してみてください。", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "名前 '{0}' が見つかりません。ノードの型定義をインストールする必要がありますか? `npm i --save-dev @types/node` をお試しください。", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "名前 '{0}' が見つかりません。ノードの型定義をインストールする必要がありますか? `npm i --save-dev @types/node` を試してから、tsconfig の型フィールドに 'node' を追加してみてください。", + "Cannot_find_namespace_0_2503": "名前空間 '{0}' が見つかりません。", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "'{0}' という名前空間は見つかりません。'{1}' ですか?", + "Cannot_find_parameter_0_1225": "パラメーター '{0}' が見つかりません。", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "入力ファイルの共通サブディレクトリ パスが見つかりません。", + "Cannot_find_type_definition_file_for_0_2688": "'{0}' の型定義ファイルが見つかりません。", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "型宣言ファイルをインポートできません。'{1}' の代わりに '{0}' をインポートすることを検討してください。", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "ブロック スコープ宣言 '{1}' と同じスコープ内の外部スコープ変数 '{0}' を初期化できません。", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null' または 'undefined' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'undefined' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765": "反復子の 'next' メソッドは型 '{1}' を予期するため、値を反復処理できませんが、配列の非構造化は常に '{0}' を送信します。", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "反復子の 'next' メソッドは型 '{1}' を予期するため、値を反復処理できませんが、配列展開は常に '{0}' を送信します。", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "反復子の 'next' メソッドは型 '{1}' を予期するため、値を反復処理できませんが、for-of は常に '{0}' を送信します。", + "Cannot_move_statements_to_the_selected_file_95183": "選択したファイルにステートメントを移動できません", + "Cannot_move_to_file_selected_file_is_invalid_95179": "ファイルに移動できません。選択したファイルは無効です", + "Cannot_read_file_0_5083": "ファイル '{0}' を読み取れません。", + "Cannot_read_file_0_Colon_1_5012": "ファイル '{0}' を読み取れません: {1}。", + "Cannot_redeclare_block_scoped_variable_0_2451": "ブロック スコープの変数 '{0}' を再宣言することはできません。", + "Cannot_redeclare_exported_variable_0_2323": "エクスポートされた変数 '{0}' を再び宣言できません。", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "catch 句で識別子 '{0}' を再宣言することはできません。", + "Cannot_start_a_function_call_in_a_type_annotation_1441": "型の注釈で関数呼び出しを開始することはできません。", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "'--jsx' フラグが指定されていないと、JSX を使用できません。", + "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled_1269": "'{0}' が有効である場合、型または型のみの名前空間で 'export import' を使用することはできません。", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "'--module' が 'none' である場合、インポート、エクスポート、モジュール拡張は使用できません。", + "Cannot_use_namespace_0_as_a_type_2709": "名前空間 '{0}' を型として使用することはできません。", + "Cannot_use_namespace_0_as_a_value_2708": "名前空間 '{0}' を値として使用することはできません。", + "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816": "デコレートされたクラスの静的プロパティ初期化子で 'this' を使用できません。", + "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377": "ファイル '{0}' は、参照先のプロジェクト '{1}' によって生成された '.tsbuildinfo' ファイルを上書きするため、書き込めません", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "複数の入力ファイルで上書きされることになるため、ファイル '{0}' を書き込めません。", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "入力ファイルを上書きすることになるため、ファイル '{0}' を書き込めません。", + "Catch_clause_variable_cannot_have_an_initializer_1197": "catch 句の変数に初期化子を指定することはできません。", + "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196": "Catch 句の変数型の注釈を指定する場合は、'any' または 'unknown' にする必要があります。", + "Change_0_to_1_90014": "'{0}' を '{1}' に変更する", + "Change_all_extended_interfaces_to_implements_95038": "拡張されたすべてのインターフェイスを 'implements' に変更します", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "jsdoc スタイルのすべての型を TypeScript に変更します", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "jsdoc スタイルのすべての型を TypeScript に変更します (さらに、'| undefined' を null 許容型に追加します)", + "Change_extends_to_implements_90003": "'extends' を 'implements' に変更する", + "Change_spelling_to_0_90022": "スペルを '{0}' に変更する", + "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700": "宣言されているものの、コンストラクターで設定されていないクラス プロパティを確認します。", + "Check_side_effect_imports_6806": "副作用のインポートを確認してください。", + "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697": "'bind'、'call'、'apply' のメソッドの引数が元の関数と一致することを確認します。", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}' が '{1}' - '{2}' の最長一致のプレフィックスであるかを確認しています。", + "Circular_definition_of_import_alias_0_2303": "インポート エイリアス '{0}' の循環定義です。", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "構成: {0} の解決中に循環が検出されました", + "Circularity_originates_in_type_at_this_location_2751": "この位置の型で循環が発生しています。", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "クラス '{0}' で定義されたインスタンス メンバー アクセサー '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー関数として定義されています。", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "クラス '{0}' で定義されたインスタンス メンバー関数 '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー アクセサーとして定義されています。", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "クラス '{0}' で定義されたインスタンス メンバー プロパティ '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー関数として定義されています。", + "Class_0_incorrectly_extends_base_class_1_2415": "クラス '{0}' は基底クラス '{1}' を正しく拡張していません。", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "クラス '{0}' はクラス '{1}' を正しく実装していません。'{1}' を拡張し、そのメンバーをサブクラスとして継承しますか?", + "Class_0_incorrectly_implements_interface_1_2420": "クラス '{0}' はインターフェイス '{1}' を正しく実装していません。", + "Class_0_used_before_its_declaration_2449": "クラス '{0}' は宣言の前に使用されました。", + "Class_constructor_may_not_be_a_generator_1368": "クラス コンストラクターをジェネレーターにすることはできません。", + "Class_constructor_may_not_be_an_accessor_1341": "クラス コンストラクターをアクセサーにすることはできません。", + "Class_declaration_cannot_implement_overload_list_for_0_2813": "クラスの宣言では '{0}' のオーバーロード リストを実装できません。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "クラスの宣言で複数の '@augments' または '@extends' タグを含めることはできません。", + "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "クラス デコレーターは、静的プライベート識別子と共に使用することはできません。試験段階のデコレーターを削除することをご検討ください。", + "Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super_2855": "親クラスによって定義されたクラス フィールド '{0}' は、super を介して子クラスでアクセスすることはできません。", + "Class_name_cannot_be_0_2414": "クラス名を '{0}' にすることはできません。", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "モジュール {0} を使用して ES5 をターゲットとするときに、クラス名を 'オブジェクト' にすることはできません。", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "クラス側の静的な '{0}' が基底クラス側の静的な '{1}' を正しく拡張していません。", + "Classes_can_only_extend_a_single_class_1174": "クラスで拡張できるクラスは 1 つのみです。", + "Classes_may_not_have_a_field_named_constructor_18006": "クラスに 'constructor' という名前のフィールドを含めることはできません。", + "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210": "クラスに含まれるコードは JavaScript の厳格モードで評価されます。このモードでは、'{0}' の使用は許可されません。詳細については、「https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode」を参照してください。", + "Command_line_Options_6171": "コマンド ライン オプション", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "構成ファイルか、'tsconfig.json' を含むフォルダーにパスが指定されたプロジェクトをコンパイルします。", + "Compiler_Diagnostics_6251": "コンパイラの診断", + "Compiler_option_0_cannot_be_given_an_empty_string_18051": "コンパイラ オプション '{0}' に空の文字列を指定することはできません。", + "Compiler_option_0_expects_an_argument_6044": "コンパイラ オプション '{0}' には引数が必要です。", + "Compiler_option_0_may_not_be_used_with_build_5094": "コンパイラオプション '--{0} ' は '--build ' と共に使用できない場合があります。", + "Compiler_option_0_may_only_be_used_with_build_5093": "コンパイラ オプション '--{0} ' は '--build ' とのみ使用できる場合があります。", + "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124": "値 '{1}' のコンパイラ オプション '{0}' が不安定です。夜間 TypeScript を使用して、このエラーを無効にします。'npm install -D typescript@next' を使用して更新してみてください。", + "Compiler_option_0_requires_a_value_of_type_1_5024": "コンパイラ オプション '{0}' には {1} の型の値が必要です。", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "private 識別子を下位レベルに生成するときに、コンパイラは名前 '{0}' を予約します。", + "Compiles_the_TypeScript_project_located_at_the_specified_path_6927": "指定されたパスにある TypeScript プロジェクトをコンパイルします。", + "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923": "現在のプロジェクト (作業ディレクトリ内の tsconfig.json) のコンパイル", + "Compiles_the_current_project_with_additional_settings_6929": "追加の設定を使用して、現在のプロジェクトをコンパイルします。", + "Completeness_6257": "完全", + "Composite_projects_may_not_disable_declaration_emit_6304": "複合プロジェクトで宣言の生成を無効にすることはできません。", + "Composite_projects_may_not_disable_incremental_compilation_6379": "複合プロジェクトではインクリメンタル コンパイルを無効にできません。", + "Computed_from_the_list_of_input_files_6911": "入力ファイルのリストから計算されます。", + "Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedD_9014": "計算されるプロパティは、数値または文字列リテラル、変数、または --isolatedDeclarations を含むドット付き式である必要があります。", + "Computed_property_names_are_not_allowed_in_enums_1164": "計算されたプロパティ名は列挙型では使用できません。", + "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038": "クラスまたはオブジェクト リテラル上の計算されたプロパティ名を --isolatedDeclarations と共に推論することはできません。", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "文字列値のメンバーを持つ列挙型では、計算値は許可されません。", + "Concatenate_and_emit_output_to_single_file_6001": "出力を連結して 1 つのファイルを生成します。", + "Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports_6410": "インポートを解決するときに、リゾルバー固有の既定値に加えて設定する条件です。", + "Conflicts_are_in_this_file_6201": "このファイル内に競合があります。", + "Consider_adding_a_declare_modifier_to_this_class_6506": "このクラスに 'declare' 修飾子を追加することを検討してください。", + "Construct_signature_return_types_0_and_1_are_incompatible_2203": "コンストラクト シグネチャの戻り値の型 '{0}' と '{1}' には互換性がありません。", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "戻り値の型の注釈がないコンストラクト シグネチャの戻り値の型は、暗黙的に 'any' になります。", + "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205": "引数のないコンストラクト シグネチャには、互換性のない戻り値の型 '{0}' と '{1}' が含まれています。", + "Constructor_implementation_is_missing_2390": "コンストラクターの実装がありません。", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "クラス '{0}' のコンストラクターはプライベートであり、クラス宣言内でのみアクセス可能です。", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "クラス '{0}' のコンストラクターは保護されており、クラス宣言内でのみアクセス可能です。", + "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386": "共用体型で使用する場合、コンストラクターの型の表記はかっこで囲む必要があります。", + "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388": "交差型で使用する場合、コンストラクターの型の表記はかっこで囲む必要があります。", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生クラスのコンストラクターには 'super' の呼び出しを含める必要があります。", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "包含するファイルが指定されていないため、ルート ディレクトリを決定できません。'node_modules' フォルダーのルックアップをスキップします。", + "Containing_function_is_not_an_arrow_function_95128": "含まれている関数はアロー関数ではありません", + "Control_what_method_is_used_to_detect_module_format_JS_files_1475": "モジュール形式の JS ファイルを検出するために使用するメソッドを制御します。", + "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352": "型 '{0}' から型 '{1}' への変換は、互いに十分に重複できないため間違っている可能性があります。意図的にそうする場合は、まず式を 'unknown' に変換してください。", + "Convert_0_to_1_in_0_95003": "'{0}' を '{0} の {1}' に変換します", + "Convert_0_to_mapped_object_type_95055": "'{0}' をマップされたオブジェクト型に変換する", + "Convert_all_const_to_let_95102": "すべての 'const' を 'let' に変換する", + "Convert_all_constructor_functions_to_classes_95045": "すべてのコンストラクター関数をクラスに変換します", + "Convert_all_invalid_characters_to_HTML_entity_code_95101": "すべての無効な文字を HTML エンティティ コードに変換する", + "Convert_all_re_exported_types_to_type_only_exports_1365": "すべての再エクスポートされた型を、型のみのエクスポートに変換する", + "Convert_all_require_to_import_95048": "'require' をすべて 'import' に変換", + "Convert_all_to_async_functions_95066": "すべてを非同期関数に変換する", + "Convert_all_to_bigint_numeric_literals_95092": "すべてを bigint 数値リテラルに変換する", + "Convert_all_to_default_imports_95035": "すべてを既定のインポートに変換します", + "Convert_all_type_literals_to_mapped_type_95021": "すべての型リテラルをマップされた型に変換します", + "Convert_all_typedef_to_TypeScript_types_95177": "すべての typedef を TypeScript 型に変換してください。", + "Convert_arrow_function_or_function_expression_95122": "アロー関数または関数式を変換する", + "Convert_const_to_let_95093": "'const' を 'let' に変換する", + "Convert_default_export_to_named_export_95061": "既定のエクスポートを名前付きエクスポートに変換する", + "Convert_function_declaration_0_to_arrow_function_95106": "関数宣言 '{0}' をアロー関数に変換する", + "Convert_function_expression_0_to_arrow_function_95105": "関数の式 '{0}' をアロー関数に変換する", + "Convert_function_to_an_ES2015_class_95001": "関数を ES2015 クラスに変換します", + "Convert_invalid_character_to_its_html_entity_code_95100": "無効な文字をその html エンティティ コードに変換する", + "Convert_named_export_to_default_export_95062": "名前付きエクスポートを既定のエクスポートに変換する", + "Convert_named_imports_to_default_import_95170": "名前付きインポートを既定のインポートに変換する", + "Convert_named_imports_to_namespace_import_95057": "名前付きインポートを名前空間インポートに変換します", + "Convert_namespace_import_to_named_imports_95056": "名前空間インポートを名前付きインポートに変換します", + "Convert_overload_list_to_single_signature_95118": "オーバーロード リストを単一のシグネチャに変換する", + "Convert_parameters_to_destructured_object_95075": "パラメーターを非構造化オブジェクトに変換する", + "Convert_require_to_import_95047": "'require' を 'import' に変換", + "Convert_to_ES_module_95017": "ES モジュールに変換する", + "Convert_to_a_bigint_numeric_literal_95091": "bigint 数値リテラルに変換する", + "Convert_to_anonymous_function_95123": "匿名関数に変換する", + "Convert_to_arrow_function_95125": "アロー関数に変換する", + "Convert_to_async_function_95065": "非同期関数に変換する", + "Convert_to_default_import_95013": "既定のインポートに変換する", + "Convert_to_named_function_95124": "名前付き関数に変換する", + "Convert_to_optional_chain_expression_95139": "オプションのチェーン式に変換します", + "Convert_to_template_string_95096": "テンプレート文字列に変換する", + "Convert_to_type_only_export_1364": "型のみのエクスポートに変換する", + "Convert_typedef_to_TypeScript_type_95176": "typedef を TypeScript 型に変換してください。", + "Corrupted_locale_file_0_6051": "ロケール ファイル {0} は破損しています。", + "Could_not_convert_to_anonymous_function_95153": "匿名関数に変換できませんでした", + "Could_not_convert_to_arrow_function_95151": "アロー関数に変換できませんでした", + "Could_not_convert_to_named_function_95152": "名前付き関数に変換できませんでした", + "Could_not_determine_function_return_type_95150": "関数の戻り値の型を特定できませんでした", + "Could_not_find_a_containing_arrow_function_95127": "含まれているアロー関数が見つかりませんでした", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "モジュール '{0}' の宣言ファイルが見つかりませんでした。'{1}' は暗黙的に 'any' 型になります。", + "Could_not_find_convertible_access_expression_95140": "変換可能なアクセス式が見つかりませんでした", + "Could_not_find_export_statement_95129": "export ステートメントが見つかりませんでした", + "Could_not_find_import_clause_95131": "インポート句が見つかりませんでした", + "Could_not_find_matching_access_expressions_95141": "一致するアクセス式が見つかりませんでした", + "Could_not_find_name_0_Did_you_mean_1_2570": "名前 '{0}' が見つかりませんでした。'{1}' ですか?", + "Could_not_find_namespace_import_or_named_imports_95132": "名前空間のインポートまたは名前付きインポートが見つかりませんでした", + "Could_not_find_property_for_which_to_generate_accessor_95135": "アクセサーを生成するプロパティが見つかりませんでした", + "Could_not_find_variable_to_inline_95185": "インライン化する変数が見つかりませんでした。", + "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "次の拡張子を持つパス '{0}' を解決できませんでした: {1}。", + "Could_not_write_file_0_Colon_1_5033": "ファイル '{0}' を書き込めませんでした: '{1}'。", + "Create_source_map_files_for_emitted_JavaScript_files_6694": "生成された JavaScript ファイルのソース マップ ファイルを作成します。", + "Create_sourcemaps_for_d_ts_files_6614": "d.ts ファイルのソースマップを作成します。", + "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926": "作業ディレクトリの推奨設定を使用して tsconfig.json を作成します。", + "DIRECTORY_6038": "ディレクトリ", + "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537": "文字クラスでは、10 進数のエスケープ シーケンスと前方参照を使用することはできません。", + "Decimals_with_leading_zeros_are_not_allowed_1489": "先頭が 0 の 10 進数を使用することはできません。", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "この宣言は別のファイル内の宣言を拡張します。この操作はシリアル化できません。", + "Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_support_9026": "このファイルの宣言を生成するには、拡張のためにこのインポートを保持する必要があります。これは --isolatedDeclarations ではサポートされていません。", + "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "このファイルの宣言の生成では、プライベート名 '{0}' を使用する必要があります。明示的な型の注釈では、宣言の生成のブロックを解除できます。", + "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "このファイルの宣言の生成では、モジュール '{1}' からのプライベート名 '{0}' を使用する必要があります。明示的な型の注釈では、宣言の生成のブロックを解除できます。", + "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_sup_9025": "このパラメーターの宣言を生成するには、その型に未定義の値を暗黙的に追加する必要があります。これは --isolatedDeclarations ではサポートされていません。", + "Declaration_expected_1146": "宣言が必要です。", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "宣言名が組み込みのグローバル識別子 '{0}' と競合しています。", + "Declaration_or_statement_expected_1128": "宣言またはステートメントが必要です。", + "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809": "宣言またはステートメントが必要です。この '=' はステートメントのブロックに続くため、非構造化割り当てを作成する場合は、割り当て全体をかっこで囲む必要があります。", + "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264": "明確な代入アサーションを使った宣言には、型の注釈も指定する必要があります。", + "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263": "初期化子を使った宣言に明確な代入アサーションを含めることはできません。", + "Declare_a_private_field_named_0_90053": "'{0}' という名前のプライベート フィールドを宣言します。", + "Declare_method_0_90023": "メソッド '{0}' を宣言する", + "Declare_private_method_0_90038": "プライベート メソッド '{0}' を宣言する", + "Declare_private_property_0_90035": "プライベート プロパティ '{0}' を宣言します", + "Declare_property_0_90016": "プロパティ '{0}' を宣言する", + "Declare_static_method_0_90024": "静的メソッド '{0}' を宣言する", + "Declare_static_property_0_90027": "静的プロパティ '{0}' を宣言する", + "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270": "デコレーター関数の戻り値の型 '{0}' は、型 '{1}' に割り当てられません。", + "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271": "デコレーター関数の戻り値の型は '{0}' ですが、\"void\" または \"any\" である必要があります。", + "Decorator_used_before_export_here_1486": "ここで 'export' の前にデコレーターが使用されています。", + "Decorators_are_not_valid_here_1206": "デコレーターはここでは無効です。", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "デコレーターを同じ名前の複数の get/set アクセサーに適用することはできません。", + "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038": "デコレーターが 'export' の前に使用されている場合は、'export' または 'export default' の後にデコレーターを使用することはできません。", + "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436": "デコレーターは、プロパティ宣言の名前とすべてのキーワードの前に置く必要があります。", + "Default_catch_clause_variables_as_unknown_instead_of_any_6803": "既定の catch 句の変数は '任意' ではなく '不明' です。", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "モジュールの既定エクスポートがプライベート名 '{0}' を持っているか、使用しています。", + "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037": "既定のエクスポートを --isolatedDeclarations と共に推論することはできません。", + "Default_library_1424": "既定のライブラリ", + "Default_library_for_target_0_1425": "ターゲット '{0}' の既定のライブラリ", + "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "次の識別子の定義が、別のファイル内の定義と競合しています: {0}", + "Delete_all_unused_declarations_95024": "未使用の宣言をすべて削除します", + "Delete_all_unused_imports_95147": "未使用の import をすべて削除します", + "Delete_all_unused_param_tags_95172": "未使用の '@param' タグをすべて削除します", + "Delete_the_outputs_of_all_projects_6365": "すべてのプロジェクトの出力を削除します。", + "Delete_unused_param_tag_0_95171": "未使用の '@param' タグ '{0}' を削除します", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[非推奨] 代わりに '--jsxFactory' を使います。'react' JSX 発行を対象とするときに、createElement に対して呼び出されたオブジェクトを指定します", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[非推奨] 代わりに '--outFile' を使います。出力を連結して 1 つのファイルを生成します", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[非推奨] 代わりに '--skipLibCheck' を使います。既定のライブラリ宣言ファイルの型チェックをスキップします。", + "Deprecated_setting_Use_outFile_instead_6677": "非推奨の設定です。代わりに 'outFile' をお使いください。", + "Did_you_forget_to_use_await_2773": "'await' を使用することを忘れていませんか?", + "Did_you_mean_0_1369": "'{0}' を意図していましたか?", + "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735": "'{0}' が型 'new (...args: any[]) => {1}' に制約されることを意図していましたか?", + "Did_you_mean_to_call_this_expression_6212": "この式を呼び出すことを意図していましたか?", + "Did_you_mean_to_mark_this_function_as_async_1356": "この関数を 'async' とマークすることを意図していましたか?", + "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312": "':' を使用するつもりでしたか? 含まれるオブジェクト リテラルが非構造化パターンの一部である場合、'=' はプロパティ名の後にのみ使用することができます。", + "Did_you_mean_to_use_new_with_this_expression_6213": "この式で 'new' を使用することを意図していましたか?", + "Digit_expected_1124": "数値が必要です", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "ディレクトリ '{0}' は存在していません。ディレクトリ内のすべての参照をスキップしています。", + "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270": "ディレクトリ '{0}' には package.json のスコープが含まれません。インポートは解決されません。", + "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669": "生成された JavaScript ファイルでの 'use strict' ディレクティブの追加を無効にします。", + "Disable_checking_for_this_file_90018": "このファイルのチェックを無効にする", + "Disable_emitting_comments_6688": "コメントの生成を無効にします。", + "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701": "JSDoc コメントに '@internal' を含む宣言の生成を無効にします。", + "Disable_emitting_files_from_a_compilation_6660": "コンパイルからのファイルの出力を無効にします。", + "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662": "型チェック エラーが報告された場合は、ファイルの生成を無効にします。", + "Disable_erasing_const_enum_declarations_in_generated_code_6682": "生成されたコード内で 'const 列挙型' 宣言の消去を無効にします。", + "Disable_error_reporting_for_unreachable_code_6603": "到達できないコードのエラー報告を無効にします。", + "Disable_error_reporting_for_unused_labels_6604": "未使用のラベルのエラー報告を無効にします。", + "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805": "完全な型チェックを無効にしてください (重大な解析エラーと生成エラーのみが報告されます)。", + "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661": "コンパイルされた出力での '__extends' などのカスタム ヘルパー関数の生成を無効にします。", + "Disable_including_any_library_files_including_the_default_lib_d_ts_6670": "既定の lib.d.ts を含むすべてのライブラリ ファイルを含めることを無効にします。", + "Disable_loading_referenced_projects_6235": "参照されているプロジェクトの読み込みを無効にします。", + "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620": "複合プロジェクトを参照するときに宣言ファイルではなくソース ファイルを優先することを無効にします。", + "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702": "オブジェクト リテラルの作成時に余分なプロパティ エラーの報告を無効にします。", + "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683": "symlink を realpath に解決できないようにします。これは、ノードの同じフラグに関連しています。", + "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript プロジェクトのサイズ制限を無効にします。", + "Disable_solution_searching_for_this_project_6224": "このプロジェクトのソリューション検索を無効にします。", + "Disable_strict_checking_of_generic_signatures_in_function_types_6673": "関数型の汎用シグネチャに対する厳密なチェックを無効にします。", + "Disable_the_type_acquisition_for_JavaScript_projects_6625": "JavaScript プロジェクトの型の取得を無効にする", + "Disable_truncating_types_in_error_messages_6663": "エラー メッセージ内の型の切り捨てを無効にします。", + "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221": "参照先のプロジェクトの宣言ファイルの代わりにソース ファイルを使用することを無効にします。", + "Disable_wiping_the_console_in_watch_mode_6684": "ウォッチ モードでのコンソールのワイプを無効にします。", + "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616": "プロジェクト内のファイル名の参照による型取得の推論を無効にします。", + "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672": "'import'、'require'、'' を使用して TypeScript がプロジェクトに追加するファイルの数を増やすことを無効にします。", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "同じファイルへの大文字小文字の異なる参照を許可しない。", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "トリプルスラッシュの参照やインポートしたモジュールをコンパイルされたファイルのリストに追加しないでください。", + "Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript_6721": "ECMAScript の一部ではないランタイム コンストラクトを許可しません。", + "Do_not_emit_comments_to_output_6009": "コメントを出力しないでください。", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "'@internal' の注釈を含むコードの宣言を生成しないでください。", + "Do_not_emit_outputs_6010": "出力しないでください。", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "エラーが報告される場合は、出力しないでください。", + "Do_not_emit_use_strict_directives_in_module_output_6112": "モジュール出力で 'use strict' ディレクティブを生成しません。", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "生成されたコード内で const 列挙型宣言を消去しないでください。", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "コンパイルされた出力で '__extends' などのカスタム ヘルパー関数を生成しないでください。", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "既定のライブラリ ファイル (lib.d.ts) を含めないでください。", + "Do_not_report_errors_on_unreachable_code_6077": "到達できないコードに関するエラーを報告しない。", + "Do_not_report_errors_on_unused_labels_6074": "未使用のラベルに関するエラーを報告しない。", + "Do_not_resolve_the_real_path_of_symlinks_6013": "symlink の実際のパスを解決しません。", + "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804": "型のみとしてマークされていないインポートまたはエクスポートを変換または削除せずに、'module' 設定に基づいて出力ファイルの形式で書き込まれていることを確認してください。", + "Do_not_truncate_error_messages_6165": "エラー メッセージを切り捨てないでください。", + "Duplicate_function_implementation_2393": "関数の実装が重複しています。", + "Duplicate_identifier_0_2300": "識別子 '{0}' が重複しています。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "識別子 '{0}' が重複しています。コンパイラは、モジュールの最上位のスコープに名前 '{1}' を予約します。", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "識別子 '{0}' が重複しています。コンパイラは非同期関数を含むモジュールの最上位のスコープに名前 '{1}' を予約します。", + "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818": "識別子 '{0}' が重複しています。静的初期化子で 'super' 参照を出力するときに、コンパイラは名前 '{1}' を予約します。", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "識別子 '{0}' が重複しています。コンパイラは宣言 '{1}' を使用して非同期関数をサポートします。", + "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804": "識別子 '{0}' が重複しています。静的要素とインスタンス要素は、同じプライベート名を共有できません。", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "識別子 'arguments' が重複しています。コンパイラは 'arguments' を使用して rest パラメーターを初期化します。", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "識別子 '_newTarget' が重複しています。コンパイラは変数宣言 '_newTarget' を使用して、'new.target' メタプロパティの参照をキャプチャします。", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "識別子 '_this' が重複しています。コンパイラは変数宣言 '_this' を使用して '_this' の参照をキャプチャします。", + "Duplicate_index_signature_for_type_0_2374": "型 '{0}' のインデックス シグネチャが重複しています。", + "Duplicate_label_0_1114": "ラベル '{0}' が重複しています。", + "Duplicate_property_0_2718": "プロパティ '{0}' が重複しています。", + "Duplicate_regular_expression_flag_1500": "正規表現フラグが重複しています。", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動的インポートの指定子の型は 'string' である必要がありますが、ここでは型 '{0}' が指定されています。", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "動的インポートは、'--module' フラグが 'es2020'、'es2022'、'esnext'、'commonjs'、'amd'、'system'、'umd'、'node16'、'node18'、または 'nodenext' に設定されている場合にのみサポートされます。", + "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments_1450": "動的インポートでは、引数として、モジュール指定子とオプションの属性セットのみを受け取ることができます", + "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_1324": "動的インポートは、'--module' オプションが 'esnext'、'node16'、'node18'、'nodenext'、または 'preserve' に設定されている場合にのみ、2 番目の引数をサポートします。", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve_1293": "'module' が 'preserve' に設定されている場合、CommonJS モジュールでは ESM 構文を使用できません。", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled_1286": "'verbatimModuleSyntax' が有効である場合、CommonJS モジュールで ESM 構文は許可されません。", + "Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given_4125": "'{0}.{1}' の各宣言の値が異なります。'{2}' が必要ですが、'{3}' が指定されました。", + "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "共用体型 '{0}' の各メンバーにはコンストラクト シグネチャがありますが、これらのシグネチャはいずれも相互に互換性がありません。", + "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758": "共用体型 '{0}' の各メンバーにはシグネチャがありますが、これらのシグネチャはいずれも相互に互換性がありません。", + "Editor_Support_6249": "エディター サポート", + "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053": "型 '{0}' の式を使用して型 '{1}' にインデックスを付けることはできないため、要素は暗黙的に 'any' 型になります。", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "インデックス式が型 'number' ではないため、要素に 'any' 型が暗黙的に指定されます。", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "型 '{0}' にはインデックス シグネチャがないため、要素は暗黙的に 'any' 型になります。", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052": "型 '{0}' にはインデックス シグネチャがないため、要素は暗黙的に 'any' 型になります。'{1}' を呼び出すことを意図していましたか?", + "Emit_6246": "生成", + "Emit_ECMAScript_standard_compliant_class_fields_6712": "ECMAScript 標準準拠クラス フィールドを生成します。", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622": "出力ファイルの最初に UTF-8 バイト順マーク(BOM) を生成します。", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "個々のファイルを持つ代わりに、複数のソース マップを含む単一ファイルを生成します。", + "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638": "デバッグのために実行するコンパイラの v8 CPU プロファイルを生成します。", + "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626": "CommonJS モジュールのインポートをサポートしやすくするために追加の JavaScript を生成します。これにより、互換性のある型に対して 'allowSyntheticDefaultImports' を使用できるようになります。", + "Emit_class_fields_with_Define_instead_of_Set_6222": "Set ではなく Define を使用して、クラスのフィールドを生成します。", + "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624": "ソース ファイル内の修飾された宣言に対してデザイン型メタデータを生成します。", + "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621": "イテレーションのために、準拠性が高いものの、冗長でパフォーマンスが低い JavaScript を生成します。", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "単一ファイル内でソースマップと共にソースを生成します。'--inlineSourceMap' または '--sourceMap' を設定する必要があります。", + "Enable_all_strict_type_checking_options_6180": "厳密な型チェックのオプションをすべて有効にします。", + "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685": "TypeScript の出力で色と書式設定を有効にして、コンパイラ エラーを読みやすくします。", + "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611": "プロジェクト参照での TypeScript プロジェクトの使用を許可する制約を有効にします。", + "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667": "関数で明示的に返されないコードパスのエラー報告を有効にします。", + "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665": "暗黙的な 'any' 型を含む式と宣言に関するエラー報告を有効にします。", + "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664": "switch ステートメントに case のフォールスルーがある場合のエラー報告を有効にします。", + "Enable_error_reporting_in_type_checked_JavaScript_files_6609": "型チェックされた JavaScript ファイルでのエラー報告を有効にします。", + "Enable_error_reporting_when_local_variables_aren_t_read_6675": "ローカル変数が読み取られていない場合にエラー報告を有効にします。", + "Enable_error_reporting_when_this_is_given_the_type_any_6668": "'this' に 'any' 型が指定されている場合は、エラー報告を有効にします。", + "Enable_experimental_support_for_legacy_experimental_decorators_6630": "従来の実験的なデコレーターの実験的なサポートを有効にしてください。", + "Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present_6264": "宣言ファイルが存在する場合、拡張子を持つファイルのインポートを有効にしてください。", + "Enable_importing_json_files_6689": ".json ファイルのインポートを有効にします。", + "Enable_lib_replacement_6808": "lib 置換を有効にします。", + "Enable_project_compilation_6302": "プロジェクトのコンパイルを有効にします", + "Enable_strict_bind_call_and_apply_methods_on_functions_6214": "厳格な 'bind'、'call'、'apply' メソッドを関数で有効にします。", + "Enable_strict_checking_of_function_types_6186": "関数の型の厳密なチェックを有効にします。", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "クラス内のプロパティの初期化の厳密なチェックを有効にします。", + "Enable_strict_null_checks_6113": "厳格な null チェックを有効にします。", + "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074": "構成ファイルで 'experimentalDecorators' オプションを有効にする", + "Enable_the_jsx_flag_in_your_configuration_file_95088": "構成ファイルで '--jsx' フラグを有効にする", + "Enable_tracing_of_the_name_resolution_process_6085": "名前解決の処理のトレースを有効にします。", + "Enable_verbose_logging_6713": "詳細ログを有効にします。", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "すべてのインポートの名前空間オブジェクトを作成して、CommonJS と ES モジュール間の生成の相互運用性を有効にします。'allowSyntheticDefaultImports' を暗黙のうちに表します。", + "Enables_experimental_support_for_ES7_decorators_6065": "ES7 デコレーター用の実験的なサポートを有効にします。", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "デコレーター用の型メタデータを発行するための実験的なサポートを有効にします。", + "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671": "インデックス付きの型を使用して宣言されたキーに対してインデックス付きアクセサーの使用を強制します。", + "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666": "派生クラスのオーバーライドするメンバーが override 修飾子でマークされていることを確認します。", + "Ensure_that_casing_is_correct_in_imports_6637": "インポートの大文字と小文字の指定が正しいことを確認します。", + "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645": "各ファイルが他のインポートに依存しないで安全にトランスパイルできることを確認します。", + "Ensure_use_strict_is_always_emitted_6605": "'use strict' が常に生成されることを確認します。", + "Entering_conditional_exports_6413": "条件付きエクスポートを入力しています。", + "Entry_point_for_implicit_type_library_0_1420": "暗黙的なタイプ ライブラリ '{0}' のエントリ ポイント", + "Entry_point_for_implicit_type_library_0_with_packageId_1_1421": "packageId が '{1}' の暗黙的なタイプ ライブラリ '{0}' のエントリ ポイント", + "Entry_point_of_type_library_0_specified_in_compilerOptions_1417": "compilerOptions で指定されたタイプ ライブラリ '{0}' のエントリ ポイント", + "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418": "compilerOptions で指定された packageId が '{1}' のタイプ ライブラリ '{0}' のエントリ ポイント", + "Enum_0_used_before_its_declaration_2450": "列挙型 '{0}' は宣言の前に使用されました。", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "列挙型の宣言は、名前空間または他の列挙型の宣言とのみマージできます。", + "Enum_declarations_must_all_be_const_or_non_const_2473": "列挙型宣言は、すべてが定数、またはすべてが非定数でなければなりません。", + "Enum_member_expected_1132": "列挙型メンバーが必要です。", + "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056": "'isolatedModules' が有効である場合、非リテラル数値メンバーの後に続く列挙型メンバーには初期化子が必要です。", + "Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDecl_9020": "列挙型メンバー初期化子は、--isolatedDeclarations を含む外部シンボルへの参照なしで計算可能である必要があります。", + "Enum_member_must_have_initializer_1061": "列挙型メンバーには初期化子が必要です。", + "Enum_name_cannot_be_0_2431": "列挙型の名前を '{0}' にすることはできません。", + "Errors_Files_6041": "エラーの発生したファイル", + "Escape_sequence_0_is_not_allowed_1488": "エスケープ シーケンス '{0}' は許可されていません。", + "Examples_Colon_0_6026": "例: {0}", + "Excessive_complexity_comparing_types_0_and_1_2859": "型 '{0}' と '{1}' の比較が複雑すぎます。", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "型 '{0}' と '{1}' を比較するスタックが深すぎます。", + "Exiting_conditional_exports_6416": "条件付きエクスポートを終了しています。", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} 型の引数が必要です。'@extends' タグで指定してください。", + "Expected_0_arguments_but_got_1_2554": "{0} 個の引数が必要ですが、{1} 個指定されました。", + "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794": "{0} 引数が必要ですが、{1} が指定されました。'Promise' の型引数に 'void' を含めましたか?", + "Expected_0_type_arguments_but_got_1_2558": "{0} 個の型引数が必要ですが、{1} 個が指定されました。", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} 型の引数が必要です。'@extends' タグで指定してください。", + "Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_2810": "1 個の引数が必要ですが、0 個しかありませんでした。'new Promise()' では、引数なしで呼び出すことができる 'resolve' を生成するための JSDoc ヒントが必要です。", + "Expected_a_Unicode_property_name_1523": "Unicode プロパティ名が必要です。", + "Expected_a_Unicode_property_name_or_value_1527": "Unicode プロパティ名または値が必要です。", + "Expected_a_Unicode_property_value_1525": "Unicode プロパティ値が必要です。", + "Expected_a_capturing_group_name_1514": "キャプチャ グループ名が必要です。", + "Expected_a_class_set_operand_1520": "クラス セット オペランドが必要でした。", + "Expected_at_least_0_arguments_but_got_1_2555": "最低でも {0} 個の引数が必要ですが、{1} 個指定されました。", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}' の対応する JSX 終了タグが必要です。", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX フラグメントの対応する終了タグが必要です。", + "Expected_for_property_initializer_1442": "プロパティ初期化子には '=' を期待しています。", + "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105": "'package.json' の '{0}' フィールドの型は '{1}' であるべきですが、'{2}' を取得しました。", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "明示的に指定されたモジュール解決の種類 '{0}'。", + "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "'target' オプションが 'es2016' 以降に設定されている場合を除き、'bigint' 値に対して累乗を実行することはできません。", + "Export_0_from_module_1_90059": "'{0}' をモジュール '{1}' からエクスポートする", + "Export_all_referenced_locals_90060": "参照されているすべてのローカルをエクスポートする", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート代入を使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "代入のエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "エクスポート宣言が、'{0}' のエクスポートされた宣言と競合しています。", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "エクスポート宣言は名前空間でサポートされません。", + "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276": "エクスポート指定子 '{0}' がパス '{1}' の package.json のスコープに存在しません。", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "エクスポートされた型のエイリアス '{0}' にプライベート名 '{1}' が付いているか、その名前を使用しています。", + "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084": "エクスポートされた型エイリアス '{0}' がモジュール {2} のプライベート名 '{1}' を持っているか、使用しています。", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "エクスポートされた変数 '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "エクスポートされた変数 '{0}' がプライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "エクスポートされた変数 '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの代入はモジュールの拡張では許可されていません。", + "Expression_expected_1109": "式が必要です。", + "Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator_1497": "式をデコレーターとして使用するには、かっこで囲む必要があります。", + "Expression_or_comma_expected_1137": "式またはコンマが必要です。", + "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800": "式では大きすぎて表すことができないタプル型を生成します。", + "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590": "式は、複雑すぎて表現できない共用体型を生成します。", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "式は、コンパイラが基底クラスの参照をキャプチャするために使用する '_super' に解決されます。", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "式は、コンパイラが 'new.target' メタプロパティの参照をキャプチャするために使用する変数宣言 '_newTarget' に解決されます。", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "式は、コンパイラが 'this' の参照をキャプチャするために使用する変数宣言 '_this' に解決されます。", + "Expression_type_can_t_be_inferred_with_isolatedDeclarations_9013": "式の型を --isolatedDeclarations と共に推論することはできません。", + "Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations_9021": "extends 句に --isolatedDeclarations を含む式を含めることはできません。", + "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085": "推論された型 '{0}' の extends 句がプライベート名 '{1}' を持っているか、使用しています。", + "Extract_base_class_to_variable_90064": "基底クラスを変数に抽出する", + "Extract_binding_expressions_to_variable_90066": "バインド式を変数に抽出してください", + "Extract_constant_95006": "定数の抽出", + "Extract_default_export_to_variable_90065": "変数への既定のエクスポートを抽出する", + "Extract_function_95005": "関数の抽出", + "Extract_to_0_in_1_95004": "{1} 内の {0} に抽出する", + "Extract_to_0_in_1_scope_95008": "{1} スコープ内の {0} に抽出する", + "Extract_to_0_in_enclosing_scope_95007": "外側のスコープ内の {0} に抽出する", + "Extract_to_interface_95090": "インターフェイスに抽出する", + "Extract_to_type_alias_95078": "型のエイリアスに抽出する", + "Extract_to_typedef_95079": "typedef に抽出する", + "Extract_to_variable_and_replace_with_0_as_typeof_0_90069": "変数に抽出し、'{0} as typeof {0}' で置き換えます", + "Extract_type_95077": "Extract 型", + "FILE_6035": "ファイル", + "FILE_OR_DIRECTORY_6040": "ファイルまたはディレクトリ", + "Failed_to_find_peerDependency_0_6283": "peerDependency '{0}' が見つかりませんでした。", + "Failed_to_resolve_under_condition_0_6415": "条件 '{0}' で解決できませんでした。", + "Fallthrough_case_in_switch_7029": "switch に case のフォールスルーがあります。", + "File_0_does_not_exist_6096": "ファイル '{0}' が存在しません。", + "File_0_does_not_exist_according_to_earlier_cached_lookups_6240": "以前にキャッシュされた検索によるとファイル '{0}' は存在しません。", + "File_0_exists_according_to_earlier_cached_lookups_6239": "以前にキャッシュされた参照によるとファイル ' {0} ' は、存在します。", + "File_0_exists_use_it_as_a_name_resolution_result_6097": "ファイル '{0}' が存在します。名前解決の結果として使用します。", + "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054": "ファイル '{0}' はサポートされていない拡張子を含んでいます。サポートされている拡張子は {1} のみです。", + "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504": "ファイル '{0}' は JavaScript ファイルです。'allowJs' オプションを有効にするつもりでしたか?", + "File_0_is_not_a_module_2306": "ファイル '{0}' はモジュールではありません。", + "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307": "ファイル '{0}' がプロジェクト '{1}' のファイル リストに含まれていません。プロジェクトではすべてのファイルをリストするか、'include' パターンを使用する必要があります。", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "ファイル '{0}' が 'rootDir' '{1}' の下にありません。'rootDir' にすべてにソース ファイルが含まれている必要があります。", + "File_0_not_found_6053": "ファイル '{0}' が見つかりません。", + "File_Management_6245": "ファイルの管理", + "File_appears_to_be_binary_1490": "ファイルはバイナリのようです。", + "File_change_detected_Starting_incremental_compilation_6032": "ファイルの変更が検出されました。インクリメンタル コンパイルを開始しています...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "'{0}' にはフィールド \"type\" がないため、ファイルは CommonJS モジュールです", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "'{0}' にフィールド \"type\" があり、値が \"module\" ではないため、ファイルは CommonJS モジュールです。", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "\"package.json\" が見つからなかったため、ファイルは CommonJS モジュールです", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "'{0}' には値 \"module\" のフィールド \"type\" があるため、ファイルは ECMAScript モジュールです。", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "ファイルは CommonJS モジュールです。ES モジュールに変換される可能性があります。", + "File_is_default_library_for_target_specified_here_1426": "ファイルはこちらで指定されたターゲットの既定のライブラリです。", + "File_is_entry_point_of_type_library_specified_here_1419": "ファイルはこちらで指定されたタイプ ライブラリのエントリ ポイントです。", + "File_is_included_via_import_here_1399": "ファイルはインポートによってこちらに追加されます。", + "File_is_included_via_library_reference_here_1406": "ファイルはライブラリ参照によってこちらにインクルードされます。", + "File_is_included_via_reference_here_1401": "ファイルは参照によってこちらにインクルードされます。", + "File_is_included_via_type_library_reference_here_1404": "ファイルはタイプ ライブラリ参照によってこちらにインクルードされます。", + "File_is_library_specified_here_1423": "ファイルはこちらで指定されたライブラリです。", + "File_is_matched_by_files_list_specified_here_1410": "ファイルはこちらで指定された 'files' リストに一致します。", + "File_is_matched_by_include_pattern_specified_here_1408": "ファイルはこちらで指定されたインクルード パターンに一致します。", + "File_is_output_from_referenced_project_specified_here_1413": "ファイルはこちらで指定された参照先プロジェクトからの出力です。", + "File_is_output_of_project_reference_source_0_1428": "ファイルはプロジェクト参照ソース '{0}' の出力です", + "File_is_source_from_referenced_project_specified_here_1416": "ファイルはこちらで指定された参照先プロジェクトのソースです。", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "ファイル名 '{0}' は、既に含まれているファイル名 '{1}' と大文字と小文字の指定だけが異なります。", + "File_name_0_has_a_1_extension_looking_up_2_instead_6262": "ファイル名 '{0}' の拡張子は '{1}' です。代わりに '{2}' を検索しています。", + "File_name_0_has_a_1_extension_stripping_it_6132": "ファイル名 '{0}' に '{1}' 拡張子が使われています - 削除しています。", + "File_redirects_to_file_0_1429": "ファイルはファイル '{0}' にリダイレクトされます", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "ファイルの指定で再帰ディレクトリのワイルドカード ('**') の後に親ディレクトリ ('..') を指定することはできません: '{0}'。", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "ファイルの指定の末尾を再帰的なディレクトリのワイルドカード ('**') にすることはできません: '{0}'。", + "Filters_results_from_the_include_option_6627": "'include' オプションからの結果をフィルター処理します。", + "Fix_all_detected_spelling_errors_95026": "検出されたすべてのスペル ミスを修正します", + "Fix_all_expressions_possibly_missing_await_95085": "'await' が不足している可能性があるすべての式を修正する", + "Fix_all_implicit_this_errors_95107": "すべての暗黙的な 'this' エラーを修正する", + "Fix_all_incorrect_return_type_of_an_async_functions_90037": "非同期関数の無効な戻り値の型をすべて修正します", + "Fix_all_with_type_only_imports_95182": "型のみのインポートを使用してすべてを修正する", + "Found_0_errors_6217": "{0} 件のエラーが見つかりました。", + "Found_0_errors_Watching_for_file_changes_6194": "{0} 件のエラーが見つかりました。ファイルの変更をモニタリングしています。", + "Found_0_errors_in_1_files_6261": "{1} ファイルに {0} 件のエラーが見つかりました。", + "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260": "同じファイル内に {0} 件のエラーが見つかりました。{1} から開始します", + "Found_1_error_6216": "1 件のエラーが見つかりました。", + "Found_1_error_Watching_for_file_changes_6193": "1 件のエラーが見つかりました。ファイルの変更をモニタリングしています。", + "Found_1_error_in_0_6259": "{0} で 1 件のエラーが見つかりました", + "Found_package_json_at_0_6099": "'{0}' で 'package.json' が見つかりました。", + "Found_peerDependency_0_with_1_version_6282": "'{1}' バージョンの peerDependency '{0}' が見つかりました。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_1250": "'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definiti_1251": "'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。クラス定義は自動的に厳格モードになります。", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_au_1252": "'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。モジュールは自動的に厳格モードになります。", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "戻り値の型の注釈がない関数式の戻り値の型は、暗黙的に '{0}' になります。", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "関数の実装がないか、宣言の直後に指定されていません。", + "Function_implementation_name_must_be_0_2389": "関数の実装名は '{0}' でなければなりません。", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "関数は、戻り値の型の注釈がなく、いずれかの return 式で直接的にまたは間接的に参照されているため、戻り値の型は暗黙的に 'any' になります。", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "関数に終了の return ステートメントがないため、戻り値の型には 'undefined' が含まれません。", + "Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9007": "関数には、--isolatedDeclarations を含む明示的な戻り値の型の注釈が必要です。", + "Function_not_implemented_95159": "関数が実装されていません。", + "Function_overload_must_be_static_2387": "関数のオーバーロードは静的でなければなりません。", + "Function_overload_must_not_be_static_2388": "関数のオーバーロードは静的にはできせん。", + "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385": "共用体型で使用する場合、関数の型の表記はかっこで囲む必要があります。", + "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387": "交差型で使用する場合、関数の型の表記はかっこで囲む必要があります。", + "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014": "戻り値の型の注釈がない関数型の戻り値の型は、暗黙的に '{0}' になります。", + "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814": "本文を持つ関数は、アンビエントであるクラスとのみ結合できます。", + "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612": "プロジェクト内の TypeScript ファイルおよび JavaScript ファイルから、.d.ts ファイルを生成します。", + "Generate_get_and_set_accessors_95046": "'get' および 'set' アクセサーの生成", + "Generate_get_and_set_accessors_for_all_overriding_properties_95119": "すべてのオーバーライドするプロパティに対して 'get' および 'set' アクセサーを生成します", + "Generates_a_CPU_profile_6223": "CPU プロファイルを生成します。", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "対応する各 '.d.ts' ファイルにソースマップを生成します。", + "Generates_an_event_trace_and_a_list_of_types_6237": "イベント トレースと型のリストを生成します。", + "Generates_corresponding_d_ts_file_6002": "対応する '.d.ts' ファイルを生成します。", + "Generates_corresponding_map_file_6043": "対応する '.map' ファイルを生成します。", + "Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation_7025": "ジェネレーターは暗黙的に yield 型 '{0}' を持っています。戻り値の型の注釈を指定することを検討してください。", + "Generators_are_not_allowed_in_an_ambient_context_1221": "ジェネレーターは環境コンテキストでは使用できません。", + "Generic_type_0_requires_1_type_argument_s_2314": "ジェネリック型 '{0}' には {1} 個の型引数が必要です。", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "ジェネリック型 '{0}' には、{1} 個から {2} 個までの型引数が必要です。", + "Global_module_exports_may_only_appear_at_top_level_1316": "グローバル モジュールのエクスポートは最上位レベルにのみ出現可能です。", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "グローバル モジュールのエクスポートは宣言ファイルにのみ出現可能です。", + "Global_module_exports_may_only_appear_in_module_files_1314": "グローバル モジュールのエクスポートはモジュール ファイルにのみ出現可能です。", + "Global_type_0_must_be_a_class_or_interface_type_2316": "グローバル型 '{0}' はクラス型またはインターフェイス型でなければなりません。", + "Global_type_0_must_have_1_type_parameter_s_2317": "グローバル型 '{0}' には {1} 個の型パラメーターが必要です。", + "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384": "'--incremental' と '--watch' での再コンパイルは、ファイル内の変更がそのファイルに直接依存しているファイルにのみ影響することを想定しています。", + "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606": "'incremental' と 'watch' モードを使用するプロジェクト内での再コンパイルは、ファイル内の変更がそれに直接依存しているファイルにのみ影響することを想定しています。", + "Hexadecimal_digit_expected_1125": "16 進の数字が必要です。", + "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262": "識別子が必要です。'{0}' は、モジュールの最上位レベルでの予約語です。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "識別子が必要です。'{0}' は厳格モードの予約語です。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "識別子が必要です。'{0}' は厳格モードの予約語です。クラス定義は自動的に厳格モードになります。", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "識別子が必要です。'{0}' は、厳格モードの予約語です。モジュールは自動的に厳格モードになります。", + "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "識別子が予期されていました。'{0}' は、ここでは使用できない予約語です。", + "Identifier_expected_1003": "識別子が必要です。", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "識別子が必要です。'__esModule' は、ECMAScript モジュールを変換するときのエクスポート済みマーカーとして予約されています。", + "Identifier_or_string_literal_expected_1478": "識別子または文字列リテラルが必要です。", + "Identifier_string_literal_or_number_literal_expected_1496": "識別子、文字列リテラル、または数値リテラルが必要です。", + "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "'{0}' パッケージが実際にこのモジュールを公開する場合は、pull request を送信して 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}' を修正することを検討してください", + "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "'{0}' パッケージが実際にこのモジュールを公開する場合は、'declare module '{1}';' を含む新しい宣言 (d.ts) ファイルを追加してみてください。", + "Ignore_this_error_message_90019": "このエラー メッセージを無視する", + "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924": "tsconfig.json を無視し、既定のコンパイラ オプションを使用して指定されたファイルをコンパイルします。", + "Implement_all_inherited_abstract_classes_95040": "継承されたすべての抽象クラスを実装します", + "Implement_all_unimplemented_interfaces_95032": "実装されていないすべてのインターフェイスを実装します", + "Implement_inherited_abstract_class_90007": "継承抽象クラスを実装する", + "Implement_interface_0_90006": "インターフェイス '{0}' を実装する", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "エクスポートされたクラス '{0}' の Implements 句がプライベート名 '{1}' を持っているか、使用しています。", + "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731": "'symbol ' から 'string' への暗黙の変換は、実行時に失敗します。この式を 'String(...)' でラップすることを検討してください。", + "Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_w_2866": "インポート '{0}' は、このファイルで使用されているグローバル値と競合するため、'isolatedModules' が有効な場合は、型のみのインポートで宣言する必要があります。", + "Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_2865": "インポート '{0}' は、グローバル値と競合するため、'isolatedModules' が有効な場合は、型のみのインポートで宣言する必要があります。", + "Import_0_from_1_90013": "\"{1}\" から `{0}` をインポートします。", + "Import_assertion_values_must_be_string_literal_expressions_2837": "インポート アサーションの値は、文字列リテラル式である必要があります。", + "Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2836": "インポート アサーションは、commonjs 'require' 呼び出しにコンパイルするステートメントでは許可されません。", + "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2821": "インポート アサーションは、'--module' オプションが 'esnext'、'node18'、'nodenext' または 'preserve' に設定されている場合にのみサポートされます。", + "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822": "インポート アサーションは、型のみのインポートまたはエクスポートでは使用できません。", + "Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880": "インポート アサーションはインポート属性に置き換えられました。'assert' ではなく 'with' を使用してください。", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート代入を使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。", + "Import_attribute_values_must_be_string_literal_expressions_2858": "インポート 属性の値は、文字列リテラル式である必要があります。", + "Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2856": "インポート属性は、commonjs 'require' 呼び出しにコンパイルするステートメントでは許可されません。", + "Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2823": "インポート属性は、'--module' オプションが 'esnext'、'node18'、'nodenext' または 'preserve' に設定されている場合にのみサポートされます。", + "Import_attributes_cannot_be_used_with_type_only_imports_or_exports_2857": "インポート属性は、型のみのインポートまたはエクスポートでは使用できません。", + "Import_declaration_0_is_using_private_name_1_4000": "インポート宣言 '{0}' がプライベート名 '{1}' を使用しています。", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "インポート宣言が、'{0}' のローカル宣言と競合しています。", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "名前空間内のインポート宣言は、モジュールを参照できません。", + "Import_emit_helpers_from_tslib_6139": "生成ヘルパーを 'tslib' からインポートします。", + "Import_may_be_converted_to_a_default_import_80003": "インポートは既定のインポートに変換される可能性があります。", + "Import_name_cannot_be_0_2438": "インポート名を '{0}' にすることはできません。", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "アンビエント モジュール宣言内のインポート宣言またはエクスポート宣言は、相対モジュール名を通してモジュールを参照することはできません。", + "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271": "インポート指定子 '{0}' がパス '{1}' の package.json のスコープに存在しません。", + "Imported_via_0_from_file_1_1393": "ファイル '{1}' から {0} を介してインポートされました", + "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395": "compilerOptions で指定された 'importHelpers' をインポートするため、ファイル '{1}' から {0} を介してインポートされました", + "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397": "'jsx' および 'jsxs' ファクトリ関数をインポートするため、ファイル '{1}' から {0} を介してインポートされました", + "Imported_via_0_from_file_1_with_packageId_2_1394": "packageId が '{2}' のファイル '{1}' から {0} を介してインポートされました", + "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396": "compilerOptions で指定されているように 'importHelpers' をインポートするため、packageId が '{2}' のファイル '{1}' から {0} を介してインポートされました", + "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398": "'jsx' および 'jsxs' ファクトリ関数をインポートするため、packageId が '{2}' のファイル '{1}' から {0} を介してインポートされました", + "Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_mod_1543": "ECMAScript モジュールに JSON ファイルをインポートするには、'module' が '{0}' に設定されている場合、'type: \"json\"' インポート属性が必要です。", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "インポートはモジュールの拡張では許可されていません。外側の外部モジュールに移動することを検討してください。", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "アンビエント列挙型の宣言では、メンバー初期化子は定数式である必要があります。", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "複数の宣言がある列挙型で、最初の列挙要素の初期化子を省略できる宣言は 1 つのみです。", + "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635": "ファイルの一覧を含めます。これは、'include' ではなく、glob パターンをサポートしていません。", + "Include_modules_imported_with_json_extension_6197": "'.json' 拡張子付きのインポートされたモジュールを含める", + "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644": "生成された JavaScript 内のソースマップにソース コードを含めます。", + "Include_sourcemap_files_inside_the_emitted_JavaScript_6643": "出力された JavaScript 内にソースマップ ファイルを含めます。", + "Includes_imports_of_types_referenced_by_0_90054": "'{0}' によって参照される型のインポートを含む", + "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914": "--watch を含めると、ファイルの変更について現在のプロジェクトの監視が開始されます。設定が完了すると、次の操作を使用してウォッチ モードを構成できます。", + "Incomplete_quantifier_Digit_expected_1505": "不完全な量指定子です。数値が必要です。", + "Index_signature_for_type_0_is_missing_in_type_1_2329": "型 '{0}' is missing in type '{1}' のインデックス シグネチャがありません。", + "Index_signature_in_type_0_only_permits_reading_2542": "型 '{0}' のインデックス シグネチャは、読み取りのみを許可します。", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "マージされた宣言 '{0}' の個々の宣言はすべてエクスポートされるか、すべてローカルであるかのどちらかである必要があります。", + "Infer_all_types_from_usage_95023": "使用法からすべての型を推論します", + "Infer_function_return_type_95148": "関数の戻り値の型を推論します", + "Infer_parameter_types_from_usage_95012": "使用状況からパラメーターの型を推論する", + "Infer_this_type_of_0_from_usage_95080": "使い方から '{0}' の 'this' 型を推論する", + "Infer_type_of_0_from_usage_95011": "使用状況から '{0}' の型を推論する", + "Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations_9022": "クラス式からの推論は、--isolatedDeclarations ではサポートされていません。", + "Initialize_property_0_in_the_constructor_90020": "コンストラクターのプロパティ '{0}' を初期化する", + "Initialize_static_property_0_90021": "静的プロパティ '{0}' を初期化する", + "Initializer_for_property_0_2811": "プロパティ ' {0} ' の初期化子。", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "インスタンス メンバー変数 '{0}' の初期化子はコンストラクターで宣言された識別子 '{1}' を参照できません。", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "初期化子は環境コンテキストでは使用できません。", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "TypeScript プロジェクトを初期化して、tsconfig.json ファイルを作成します。", + "Inline_variable_95184": "インライン変数", + "Insert_command_line_options_and_files_from_a_file_6030": "コマンド ライン オプションとファイルをファイルから挿入します。", + "Install_0_95014": "'{0}' のインストール", + "Install_all_missing_types_packages_95033": "不足しているすべての型のパッケージをインストールします", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "インターフェイス '{0}' で型 '{1}' と型 '{2}' を同時には拡張できません。", + "Interface_0_incorrectly_extends_interface_1_2430": "インターフェイス '{0}' はインターフェイス '{1}' を正しく拡張していません。", + "Interface_declaration_cannot_have_implements_clause_1176": "インターフェイス宣言に 'implements' 句を指定することはできません。", + "Interface_must_be_given_a_name_1438": "インターフェイスに名前を指定する必要があります。", + "Interface_name_cannot_be_0_2427": "インターフェイス名を '{0}' にすることはできません。", + "Interop_Constraints_6252": "制約の相互運用", + "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243": "'undefined' を追加するのではなく、省略可能なプロパティ型を記述済みとして解釈します。", + "Invalid_character_1127": "無効な文字です。", + "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "無効なインポート指定子 '{0}' には解決策がありません。", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "拡張のモジュール名が無効です。モジュール '{0}' は '{1}' の型指定のないモジュールに解決されるため、拡張されません。", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "拡張のモジュール名が無効です。モジュール '{0}' が見つかりません。", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "新しい式の省略可能なチェーンが無効です。'{0}()' の呼び出しを意図していましたか?", + "Invalid_reference_directive_syntax_1084": "無効な 'reference' ディレクティブ構文です。", + "Invalid_syntax_in_decorator_1498": "デコレーターの構文が無効です。", + "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "'{0}' の使用が無効です。クラスの静的ブロック内では使用できません。", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}' の使用方法が無効です。モジュールは自動的に厳格モードになります。", + "Invalid_use_of_0_in_strict_mode_1100": "厳格モードでは '{0}' の使用は無効です。", + "Invalid_value_for_ignoreDeprecations_5103": "'--ignoreDeprecations' の値が無効です。", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' の値が無効です。'{0}' が有効な識別子または修飾名ではありません。", + "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035": "'jsxFragmentFactory' の値が無効です。'{0}' は有効な識別子でも修飾名でもありません。", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' の値が無効です。'{0}' は有効な識別子ではありません。", + "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796": "これら 2 つのテンプレート式を区切るコンマが不足している可能性があります。タグ付きテンプレート式を形成しており、呼び出すことができません。", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "その要素の型 '{0}' は有効な JSX 要素ではありません。", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "そのインスタンスの型 '{0}' は、有効な JSX 要素ではありません。", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "その戻り値の型 '{0}' は、有効な JSX 要素ではありません。", + "Its_type_0_is_not_a_valid_JSX_element_type_18053": "その型 '{0}' は有効な JSX 要素ではありません。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}' が 'extends {2}' 句と一致しません。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}' はクラスにアタッチされていません。", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' は、シグネチャの最後のパラメーターにのみ使用できます。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' タグの名前は '{0}' ですが、その名前のパラメーターはありません。", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc '@param' タグに名前 '{0}' が指定されていますが、その名前のパラメーターはありません。配列型があった場合は、'arguments' と一致したはずです。", + "JSDoc_typedef_may_be_converted_to_TypeScript_type_80009": "JSDoc typedef は TypeScript 型に変換できます。", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' タグには、型の注釈を指定するか、後に '@property' タグや '@member' タグを付ける必要があります。", + "JSDoc_typedefs_may_be_converted_to_TypeScript_types_80010": "JSDoc typedef は TypeScript 型に変換できます。", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc の種類は、ドキュメント コメント内でのみ使用できます。", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc の種類は TypeScript の種類に移行される可能性があります。", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX 属性は、空ではない '式' にのみ割り当てる必要があります。", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 要素 '{0}' には対応する終了タグがありません。", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 要素クラスは '{0}' プロパティを含まないため、属性をサポートしません。", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "インターフェイス 'JSX.{0}' が存在しないため、暗黙的に JSX 要素の型は 'any' になります。", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "グローバル型 'JSX.Element' が存在しないため、JSX 要素は暗黙的に型 'any' になります。", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 要素型 '{0}' にはコンストラクトも呼び出しシグネチャも含まれていません。", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 要素に同じ名前の複数の属性を指定することはできません。", + "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007": "JSX 式では、コンマ演算子を使用できません。配列を作成するつもりでしたか?", + "JSX_expressions_must_have_one_parent_element_2657": "JSX 式には 1 つの親要素が必要です。", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX フラグメントには対応する終了タグがありません。", + "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633": "JSX プロパティ アクセス式に JSX 名前空間の名前を含めることはできません", + "JSX_spread_child_must_be_an_array_type_2609": "JSX スプレッドの子は、配列型でなければなりません。", + "JavaScript_Support_6247": "JavaScript サポート", + "Jump_target_cannot_cross_function_boundary_1107": "ジャンプ先は関数の境界を越えることはできません。", + "KIND_6034": "種類", + "Keywords_cannot_contain_escape_characters_1260": "キーワードにエスケープ文字を含めることはできません。", + "LOCATION_6037": "場所", + "Language_and_Environment_6254": "言語と環境", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "コンマ演算子の左側が使用されていないため、副作用はありません。", + "Library_0_specified_in_compilerOptions_1422": "compilerOptions でライブラリ '{0}' が指定されました", + "Library_referenced_via_0_from_file_1_1405": "ファイル '{1}' から '{0}' を介してライブラリが参照されました", + "Line_break_not_permitted_here_1142": "ここで改行することはできません。", + "Line_terminator_not_permitted_before_arrow_1200": "行の終端記号をアローの前で使用することはできません。", + "List_of_file_name_suffixes_to_search_when_resolving_a_module_6931": "モジュールを解決するときに検索するファイル名サフィックスのリスト。", + "List_of_folders_to_include_type_definitions_from_6161": "含める型定義の元のフォルダーの一覧。", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "結合されたコンテンツがランタイムでのプロジェクトの構成を表すルート フォルダーの一覧。", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "ルート ディレクトリ '{1}' から '{0}' を読み込んでいます。候補の場所は '{2}' です。", + "Loading_module_0_from_node_modules_folder_target_file_types_Colon_1_6098": "'node_modules' フォルダーからモジュール '{0}' を読み込んでいます。対象のファイルの種類は {1} です。", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1_6095": "ファイル / フォルダーとしてモジュールを読み込んでいます。候補のモジュールの場所は '{0}'、対象のファイルの種類は {1} です。", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "ロケールは または - の形式で指定する必要があります (例: '{0}'、'{1}')。", + "Log_paths_used_during_the_moduleResolution_process_6706": "'moduleResolution' の処理中に使用されたログ パス。", + "Longest_matching_prefix_for_0_is_1_6108": "'{0}' の一致する最長プレフィックスは '{1}' です。", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' フォルダーを検索しています。最初の場所は '{0}' です。", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "すべての 'super()' 呼び出しをそのコンストラクターの最初のステートメントにします", + "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "keyof により、文字列、数字、記号の代わりに、文字列のみが返されるようにします。レガシ オプションです。", + "Make_super_call_the_first_statement_in_the_constructor_90002": "'super()' 呼び出しをコンストラクター内の最初のステートメントにする", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "マップされたオブジェクト型のテンプレートの型は暗黙的に 'any' になります。", + "Mark_array_literal_as_const_90070": "配列リテラルを const としてマークする", + "Matched_0_condition_1_6403": "'{0}' 条件 '{1}' と一致しました。", + "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "既定で一致するインクルード パターン '**/*'", + "Matched_by_include_pattern_0_in_1_1407": "'{1}' のインクルード パターン '{0}' に一致しています", + "Member_0_implicitly_has_an_1_type_7008": "メンバー '{0}' の型は暗黙的に '{1}' になります。", + "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "メンバー '{0}' の型は暗黙的に '{1}' ですが、使い方からより良い型を推論する場合があります。", + "Merge_conflict_marker_encountered_1185": "マージ競合マーカーが検出されました。", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "マージされた宣言 '{0}' に既定のエクスポート宣言を含めることはできません。代わりに、'export default {0}' 宣言を別個に追加することを検討してください。", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "メタプロパティ '{0}' は、関数の宣言の本文、関数の式、またはコンストラクターでのみ許可されています。", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "メソッド '{0}' は abstract に指定されているため、実装を含めることができません。", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "エクスポートされたインターフェイスのメソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "エクスポートされたインターフェイスのメソッド '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9008": "メソッドには、--isolatedDeclarations を含む明示的な戻り値の型の注釈が必要です。", + "Method_not_implemented_95158": "メソッドが実装されていません。", + "Modifiers_cannot_appear_here_1184": "ここで修飾子を使用することはできません。", + "Module_0_can_only_be_default_imported_using_the_1_flag_1259": "モジュール '{0}' は、'{1}' フラグを使用して既定でのみインポートできます", + "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471": "モジュール '{0}' はこのコンストラクトではインポートできません。指定子は ES モジュールに解決されるだけであるため、'require' でインポートすることはできません。代わりに ECMAScript インポートを使用してください。", + "Module_0_declares_1_locally_but_it_is_exported_as_2_2460": "モジュール '{0}' は '{1}' をローカルで宣言していますが、これは '{2}' としてエクスポートされています。", + "Module_0_declares_1_locally_but_it_is_not_exported_2459": "モジュール '{0}' は '{1}' をローカルで宣言していますが、これはエクスポートされていません。", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340": "モジュール '{0}' は型を参照していませんが、ここでは型として使用されています。'typeof import('{0}')' を意図していましたか?", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "モジュール '{0}' は値を参照していませんが、ここでは値として使用されています。", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "モジュール {0} は既に '{1}' という名前のメンバーをエクスポートしています。あいまいさを解決するため、明示的にもう一度エクスポートすることを検討してください。", + "Module_0_has_no_default_export_1192": "モジュール '{0}' に既定エクスポートがありません。", + "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613": "モジュール '{0}' には既定のエクスポートがありません。'import { {1} } from {0}' を使用するつもりでしたか?", + "Module_0_has_no_exported_member_1_2305": "モジュール '{0}' にエクスポートされたメンバー '{1}' がありません。", + "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614": "モジュール '{0}' にはエクスポートされたメンバー '{1}' がありません。'import {1} from {0}' を使用するつもりでしたか?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "モジュール '{0}' は同じ名前のローカル宣言によって非表示になっています。", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "モジュール '{0}' には 'export =' が使用されているため、'export *' は併用できません。", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "モジュール '{0}' は、ファイル '{1}' のローカルで宣言されたアンビエント モジュールとして解決されました。", + "Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set_6263": "モジュール '{0}' は '{1}' に解決されましたが、'--allowArbitraryExtensions' が設定されていません。", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "モジュール '{0}' は '{1}' に解決されましたが、'--jsx' が設定されていません。", + "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042": "モジュール '{0}' は '{1}' に解決されましたが、'--resolveJsonModule' が使用されていません。", + "Module_declaration_names_may_only_use_or_quoted_strings_1443": "モジュール宣言名で使用できるのは、' または \"引用符で囲まれた文字列のみです。", + "Module_name_0_matched_pattern_1_6092": "モジュール名 '{0}'、照合されたパターン '{1}'。", + "Module_name_0_was_not_resolved_6090": "======== モジュール名 '{0}' が解決されませんでした。========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== モジュール名 '{0}' が正常に '{1}' に解決されました。========", + "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218": "======== モジュール名 '{0}' が正常に '{1}' に解決されました (パッケージ ID '{2}')。========", + "Module_resolution_kind_is_not_specified_using_0_6088": "モジュール解決の種類が '{0}' を使用して指定されていません。", + "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' を使用したモジュール解決が失敗しました。", + "Modules_6244": "モジュール", + "Move_labeled_tuple_element_modifiers_to_labels_95117": "ラベル付きのタプル要素の修飾子をラベルに移動する", + "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036": "既定のエクスポートで式を変数に移動し、それに型注釈を追加します。", + "Move_to_a_new_file_95049": "新しいファイルへ移動します", + "Move_to_file_95178": "ファイルに移動", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "複数の連続した数値区切り記号を指定することはできません。", + "Multiple_constructor_implementations_are_not_allowed_2392": "コンストラクターを複数実装することはできません。", + "NEWLINE_6061": "改行", + "Name_is_not_valid_95136": "名前が無効です", + "Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later_1503": "名前付きキャプチャ グループは、'ES2018' 以降をターゲットにする場合にのみ使用できます。", + "Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other_1515": "同じ名前の名前の名前付きキャプチャ グループは、相互に排他的である必要があります。", + "Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0_1544": "'module' が '{0}' に設定されている場合、JSON ファイルから ECMAScript モジュールへの名前付きインポートは許可されません。", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "'{1}' 型および '{2}' 型の名前付きプロパティ '{0}' が一致しません。", + "Namespace_0_has_no_exported_member_1_2694": "名前空間 '{0}' にエクスポートされたメンバー '{1}' がありません。", + "Namespace_must_be_given_a_name_1437": "名前空間に名前を指定する必要があります。", + "Namespace_name_cannot_be_0_2819": "名前空間名を '{0}' にすることはできません。", + "Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to__1280": "'{0}' が有効になっている場合、グローバル スクリプト ファイルでは名前空間を使用できません。このファイルがグローバル スクリプトを意図していない場合は、'moduleDetection' を 'force' に設定するか、空の 'export {}' ステートメントを追加してください。", + "Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters_1433": "デコレーターも修飾子も 'this' パラメーターに適用できません。", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "指定した数の型引数を持つ基底コンストラクターは存在しません。", + "No_constituent_of_type_0_is_callable_2755": "型 '{0}' の構成要素は呼び出し可能ではありません。", + "No_constituent_of_type_0_is_constructable_2759": "型 '{0}' の構成要素はコンストラクト可能ではありません。", + "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054": "型 '{0}' のパラメーターを持つインデックス シグネチャが型 '{1}' に見つかりませんでした。", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "構成ファイル '{0}' で入力が見つかりませんでした。指定された 'include' パスは '{1}' で、'exclude' パスは '{2}' でした。", + "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608": "サポートされていません。初期のバージョンの場合は、ファイルを読み取るためにテキストのエンコードを手動で設定してください。", + "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575": "{0} 引数を予期するオーバーロードはありませんが、{1} または {2} 引数のいずれかを予期するオーバーロードは存在します。", + "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743": "{0} 型の引数を予期するオーバーロードはありませんが、{1} または {2} 型の引数のいずれかを予期するオーバーロードは存在します。", + "No_overload_matches_this_call_2769": "この呼び出しに一致するオーバーロードはありません。", + "No_type_could_be_extracted_from_this_type_node_95134": "この型ノードからは型を抽出できませんでした", + "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004": "短縮形のプロパティ '{0}' のスコープには値がありません。値を宣言するか、または初期化子を指定してください。", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "非抽象クラス '{0}' は、クラス '{2}' からの継承抽象メンバー '{1}' を実装しません。", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_2654": "非抽象クラス '{0}' には、'{1}' の次のメンバーの実装がありません: {2}。", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more_2655": "非抽象クラス '{0}' には、'{1}' の次のメンバーの実装がありません: {2} およびその他 {3}。", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象クラスの式はクラス '{1}' からの継承抽象メンバー '{0}' を実装しません。", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_2656": "非抽象クラス式に、'{0}' の次のメンバーの実装がありません: {1}。", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and__2650": "非抽象クラス式に、'{0}' の次のメンバーの実装がありません: {1} およびその他 {2}。", + "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013": "non-null アサーションは、TypeScript ファイルでのみ使用できます。", + "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090": "'baseUrl' が設定されていない場合、非相対パスは許可されません。先頭に './' が使用されていることをご確認ください。", + "Non_simple_parameter_declared_here_1348": "ここでは複雑なパラメーターが宣言されています。", + "Not_all_code_paths_return_a_value_7030": "一部のコード パスは値を返しません。", + "Not_all_constituents_of_type_0_are_callable_2756": "型 '{0}' のすべての構成要素が呼び出し可能なわけではありません。", + "Not_all_constituents_of_type_0_are_constructable_2760": "型 '{0}' のすべての構成要素がコンストラクト可能なわけではありません。", + "Numbers_out_of_order_in_quantifier_1506": "量指定子の数値が順不同です。", + "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008": "絶対値が 2^53 以上の数値リテラルは大きすぎるため、整数として正確に表現できません。", + "Numeric_separators_are_not_allowed_here_6188": "数値の区切り記号は、ここでは使用できません。", + "Object_is_of_type_unknown_2571": "オブジェクト型は 'unknown' です。", + "Object_is_possibly_null_2531": "オブジェクトは 'null' である可能性があります。", + "Object_is_possibly_null_or_undefined_2533": "オブジェクトは 'null' か 'undefined' である可能性があります。", + "Object_is_possibly_undefined_2532": "オブジェクトは 'undefined' である可能性があります。", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "オブジェクト リテラルは既知のプロパティのみ指定できます。'{0}' は型 '{1}' に存在しません。", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "オブジェクト リテラルで指定できるのは既知のプロパティのみですが、'{0}' は型 '{1}' に存在しません。書こうとしたのは '{2}' ですか?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "オブジェクト リテラルのプロパティ '{0}' の型は暗黙的に '{1}' になります。", + "Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations_9016": "短縮形プロパティを含むオブジェクトは、--isolatedDeclarations では推論できません。", + "Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations_9015": "スプレッド割り当てを含むオブジェクトを --isolatedDeclarations と共に推論することはできません。", + "Octal_digit_expected_1178": "8 進の数字が必要です。", + "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536": "文字クラスでは、8 進数のエスケープ シーケンスと前方参照を使用することはできません。これがエスケープ シーケンスとして意図されていた場合は、代わりに構文 '{0}' を使用してください。", + "Octal_escape_sequences_are_not_allowed_Use_the_syntax_0_1487": "8 進数のエスケープ シーケンスは使用できません。構文 '{0}' を使用してください。", + "Octal_literals_are_not_allowed_Use_the_syntax_0_1121": "8 進数リテラルは使用できません。構文 '{0}' を使用してください。", + "One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value_4126": "'{0}.{1}' の 1 つの値は文字列 '{2}' で、もう一方の値は不明な数値であると見なされます。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' ステートメントで使用できる変数宣言は 1 つのみです。", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' ステートメントで使用できる変数宣言は 1 つのみです。", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "'new' キーワードを指定して呼び出せるのは void 関数のみです。", + "Only_ambient_modules_can_use_quoted_names_1035": "引用符付きの名前を使用できるのはアンビエント モジュールのみです。", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "--{0} と共にサポートされるのは 'amd' モジュールと 'system' モジュールのみです。", + "Only_const_arrays_can_be_inferred_with_isolatedDeclarations_9017": "--isolatedDeclarations を使用して推論できるのは const 配列のみです。", + "Only_emit_d_ts_declaration_files_6014": "'.d.ts' 宣言ファイルのみを生成します。", + "Only_output_d_ts_files_and_not_JavaScript_files_6623": "出力の d.ts ファイルのみで、JavaScript ファイルは対象ではありません。", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "'super' キーワードを使用してアクセスできるのは、基底クラスのパブリック メソッドと保護されたメソッドのみです。", + "Operator_0_cannot_be_applied_to_type_1_2736": "演算子 '{0}' は型 '{1}' に適用できません。", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "演算子 '{0}' を型 '{1}' および '{2}' に適用することはできません。", + "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519": "演算子は文字クラス内で混在してはなりません。入れ子になったクラスでラップしてください。", + "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619": "編集時に複数プロジェクト参照のチェックからプロジェクトをオプトアウトします。", + "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108": "オプション '{0}={1}' が削除されました。構成から削除してください。", + "Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDepr_5107": "オプション '{0}={1}' は非推奨であり、TypeScript {2} で機能しなくなります。compilerOption '\"ignoreDeprecations\": \"{3}\"' を指定して、このエラーを無音にします。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "オプション '{0}' は、'tsconfig.json' ファイルで指定することか、コマンド ラインで 'false' または 'null' に設定することしかできません。", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "オプション '{0}' は、'tsconfig.json' ファイルで指定することか、コマンド ラインで 'null' に設定することしかできません。", + "Option_0_can_only_be_specified_on_command_line_6266": "オプション '{0}' はコマンド ラインでのみ指定できます。", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "オプション '{0} を使用できるのは、オプション '--inlineSourceMap' またはオプション '--sourceMap' のいずれかを指定した場合のみです。", + "Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler_5098": "オプション '{0}' は、'moduleResolution' が 'node16'、'nodenext'、または 'bundler' に設定されている場合にのみ使用できます。", + "Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later_5095": "オプション '{0}' は、'module' が 'preserve' または 'es2015' 以降に設定されている場合にのみ使用できます。", + "Option_0_cannot_be_specified_when_option_jsx_is_1_5089": "オプション 'jsx' が '{1}' の場合、オプション '{0}' を指定することはできません。", + "Option_0_cannot_be_specified_with_option_1_5053": "オプション '{0}' をオプション '{1}' とともに指定することはできません。", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "オプション '{1}' を指定せずに、オプション '{0}' を指定することはできません。", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "オプション '{1}' またはオプション '{2}' を指定せずに、オプション '{0}' を指定することはできません。", + "Option_0_has_been_removed_Please_remove_it_from_your_configuration_5102": "オプション '{0}' が削除されました。構成から削除してください。", + "Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprec_5101": "オプション '{0}' は非推奨であり、TypeScript {1} で機能しなくなります。compilerOption '\"ignoreDeprecations\": \"{2}\"' を指定して、このエラーを無音にします。", + "Option_0_is_redundant_and_cannot_be_specified_with_option_1_5104": "オプション '{0}' は冗長であり、オプション '{1}' とともに指定することができません。", + "Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set_5096": "オプション 'allowImportingTsExtensions' は、'noEmit' または 'emitDeclarationOnly' が設定されている場合にのみ使用できます。", + "Option_build_must_be_the_first_command_line_argument_6369": "オプション '--build' は最初のコマンド ライン引数である必要があります。", + "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074": "オプション '--incremental' は、tsconfig を使用して指定して単一ファイルに出力するか、オプション '--tsBuildInfoFile' が指定された場合にのみ指定することができます。", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "オプション 'isolatedModules' は、オプション '--module' が指定されているか、オプション 'target' が 'ES2015' 以上であるかのいずれかの場合でのみ使用できます。", + "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109": "オプション 'module' が '{1}' に設定されている場合は、オプション 'moduleResolution' を '{0}' (または未指定のままに) に設定する必要があります。", + "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110": "オプション 'moduleResolution' が '{1}' に設定されている場合は、オプション 'module' を '{0}' に設定する必要があります。", + "Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled_5091": "'{0}' が有効になっている場合、オプション 'preserveConstEnums' を無効にすることはできません。", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "オプション 'project' をコマンド ライン上でソース ファイルと一緒に指定することはできません。", + "Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic_5070": "'moduleResolution' が 'classic' に設定されている場合、オプション '--resolveJsonModule' を指定できません。", + "Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd_5071": "'module' が 'none'、'system'、または 'umd' に設定されている場合、オプション '--resolveJsonModule' を指定することはできません。", + "Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System_5105": "'module' が 'UMD'、'AMD'、または 'System' に設定されている場合、オプション 'verbatimModuleSyntax' は使用できません。", + "Options_0_and_1_cannot_be_combined_6370": "オプション '{0}' と '{1}' を組み合わせることはできません。", + "Options_Colon_6027": "オプション:", + "Output_Formatting_6256": "出力データ形式", + "Output_compiler_performance_information_after_building_6615": "ビルド後にコンパイラのパフォーマンス情報を出力します。", + "Output_directory_for_generated_declaration_files_6166": "生成された宣言ファイルの出力ディレクトリ。", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "出力ファイル '{0}' はソース ファイル '{1}' からビルドされていません。", + "Output_from_referenced_project_0_included_because_1_specified_1411": "'{1}' が指定されたため、参照先プロジェクト '{0}' から出力がインクルードされました", + "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412": "'--module' が 'none' として指定されたため、参照先プロジェクト '{0}' から出力がインクルードされました", + "Output_more_detailed_compiler_performance_information_after_building_6632": "ビルド後により詳しいコンパイラのパフォーマンス情報を出力します。", + "Overload_0_of_1_2_gave_the_following_error_2772": "{1} 中 {0} のオーバーロード, '{2}' により、次のエラーが発生しました。", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "オーバーロードのシグネチャはすべてが抽象または非抽象である必要があります。", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "オーバーロードのシグネチャは、すべてアンビエントであるか、すべてアンビエントでないかのどちらかである必要があります。", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "オーバーロードのシグネチャはすべてがエクスポート済みであるか、またはエクスポート済みでない必要があります。", + "Overload_signatures_must_all_be_optional_or_required_2386": "オーバーロードのシグネチャは、すべて省略可能であるか、すべて必須であるかのどちらかである必要があります。", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "オーバーロードのシグネチャはすべて、public、private、または protected でなければなりません。", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "パラメーター '{0}' はその後で宣言された識別子 '{1}' を参照できません。", + "Parameter_0_cannot_reference_itself_2372": "パラメーター '{0}' は、それ自体を参照できません。", + "Parameter_0_implicitly_has_an_1_type_7006": "パラメーター '{0}' の型は暗黙的に '{1}' になります。", + "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "パラメーター '{0}' の型は暗黙的に '{1}' になっていますが、使い方からより良い型を推論できます。", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "パラメーター '{0}' がパラメーター '{1}' と同じ位置にありません。", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108": "アクセサーのパラメーター '{0}' が外部モジュール '{2}' からの名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107": "アクセサーのパラメーター '{0}' が、プライベート モジュール '{2}' からの名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106": "アクセサーのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "エクスポートされた関数のパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "エクスポートされた関数のパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "エクスポートされた関数のパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "エクスポートされたインターフェイスのインデックス シグネチャのパラメーター '{0}' で、プライベート モジュール '{2}' の名前 '{1}' が指定されているか使用されています。", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "エクスポートされたインターフェイスのインデックス シグネチャのパラメーター '{0}' で、プライベート名 '{1}' が指定されているか使用されています。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_cannot_have_question_mark_and_initializer_1015": "パラメーターに疑問符および初期化子を指定することはできません。", + "Parameter_declaration_expected_1138": "パラメーター宣言が必要です。", + "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051": "パラメーターに名前はありますが、型がありません。'{0}: {1}' を意図していましたか?", + "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012": "パラメーター修飾子は TypeScript ファイルでのみ使用できます。", + "Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9011": "パラメーターには、--isolatedDeclarations を含む明示的な型注釈が必要です。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート名 '{1}' を持っているか、使用しています。", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "厳格モードで解析してソース ファイルごとに \"use strict\" を生成します。", + "Part_of_files_list_in_tsconfig_json_1409": "tsconfig.json の 'files' リストの一部", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "パターン '{0}' に使用できる '*' 文字は最大で 1 つです。", + "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386": "'--diagnostics' または '--extendedDiagnostics' のパフォーマンスのタイミングは、このセッションでは使用できません。Web パフォーマンス API のネイティブ実装が見つかりませんでした。", + "Platform_specific_6912": "プラットフォーム固有", + "Prefix_0_with_an_underscore_90025": "アンダースコアを含むプレフィックス '{0}'", + "Prefix_all_incorrect_property_declarations_with_declare_95095": "すべての正しくないプロパティ宣言の前に 'declare' を付ける", + "Prefix_all_unused_declarations_with_where_possible_95025": "可能な場合は、使用されていないすべての宣言にプレフィックスとして '_' を付けます", + "Prefix_with_declare_95094": "'declare' を前に付ける", + "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449": "さもなければ削除されてしまう JavaScript のアウトプット中の使われていないインポートされた値を保持します。", + "Print_all_of_the_files_read_during_the_compilation_6653": "コンパイル時に読み取られたすべてのファイルを出力します。", + "Print_files_read_during_the_compilation_including_why_it_was_included_6631": "コンパイル時に読み取られたファイルを、それが含まれる理由と共に出力します。", + "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505": "ファイルの名前と、それらがコンパイルに含まれている理由を書き出します。", + "Print_names_of_files_part_of_the_compilation_6155": "コンパイルの一環としてファイルの名前を書き出します。", + "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "コンパイルの一部であるファイルの名前を出力してから、処理を停止します。", + "Print_names_of_generated_files_part_of_the_compilation_6154": "コンパイルの一環として生成されたファイル名を書き出します。", + "Print_the_compiler_s_version_6019": "コンパイラのバージョンを表示します。", + "Print_the_final_configuration_instead_of_building_1350": "ビルドを実行するのではなく、最終的な構成を出力します。", + "Print_the_names_of_emitted_files_after_a_compilation_6652": "コンパイル後に生成されたファイルの名前を出力します。", + "Print_this_message_6017": "このメッセージを表示します。", + "Private_accessor_was_defined_without_a_getter_2806": "ゲッターなしでプライベート アクセサーが定義されました。", + "Private_field_0_must_be_declared_in_an_enclosing_class_1111": "プライベート フィールド '{0}' は、エンクロージング クラスで宣言する必要があります。", + "Private_identifiers_are_not_allowed_in_variable_declarations_18029": "変数宣言では、private 識別子は許可されていません。", + "Private_identifiers_are_not_allowed_outside_class_bodies_18016": "private 識別子は、クラス本体の外では許可されていません。", + "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451": "プライベート識別子はクラス本体でのみ許可され、クラス メンバー宣言、プロパティ アクセス、または 'in' 式の左側でのみ使用できます", + "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028": "private 識別子は ECMAScript 2015 以上をターゲットにする場合にのみ使用できます。", + "Private_identifiers_cannot_be_used_as_parameters_18009": "private 識別子はパラメーターとして使用できません。", + "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105": "private または protected メンバー '{0}' には、型パラメーターではアクセスできません。", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Project '{0}' can't be built because its dependency '{1}' has errors", + "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Project '{0}' can't be built because its dependency '{1}' was not built", + "Project_0_is_being_forcibly_rebuilt_6388": "プロジェクト '{0}' が強制的にリビルドされています", + "Project_0_is_out_of_date_because_1_6420": "{1}のため、プロジェクト '{0}' は古くなっています。", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_6412": "buildinfo ファイル '{1}' は、ファイル '{2}' がコンパイルのルート ファイルでしたが、それ以上はないことを示しているため、プロジェクト '{0}' は最新ではありません。", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419": "buildinfo ファイル '{1}' はプログラムがエラーを報告する必要があることを示しているため、プロジェクト '{0}' は最新ではありません。", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "buildinfo ファイルの '{1}' により、一部の変更が生成されなかったことが示されているため、プロジェクトの '{0}' は最新ではありません", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions_6406": "buildinfo ファイル '{1}' は compilerOptions に変更があることを示しているため、プロジェクト '{0}' は最新ではありません", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "プロジェクト '{0}' はその依存関係 '{1}' が古いため最新の状態ではありません", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "プロジェクト '{0}' は出力 '{1}' が入力 '{2}' より古いため最新の状態ではありません", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "プロジェクト '{0}' は出力ファイル '{1}' が存在しないため最新の状態ではありません", + "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "プロジェクト '{0}' の出力が現在のバージョン '{2}' と異なるバージョン '{1}' で生成されているため、このプロジェクトは最新の状態ではありません", + "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401": "ファイル '{1}' の読み取り中にエラーが発生したため、プロジェクト '{0}' は最新ではありません", + "Project_0_is_up_to_date_6361": "プロジェクト '{0}' は最新の状態です", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "プロジェクト '{0}' は最新の入力 '{1}' が出力 '{2}' より古いため最新の状態です", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "プロジェクト '{0}' は最新ですが、入力ファイルよりも古い出力ファイルのタイムスタンプを更新する必要があります", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "プロジェクト '{0}' はその依存関係からの .d.ts ファイルで最新の状態です", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "プロジェクト参照が円グラフを形成できません。循環が検出されました: {0}", + "Projects_6255": "プロジェクト", + "Projects_in_this_build_Colon_0_6355": "このビルドのプロジェクト: {0}", + "Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher_18045": "'accessor' 修飾子を持つプロパティは、ECMAScript 2015 以降を対象とする場合にのみ使用できます。", + "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267": "メソッド '{0}' は abstract に指定されているため、初期化子を含めることができません。", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "プロパティ '{0}' はインデックス シグネチャに基づいているため、['{0}'] を使用してアクセスする必要があります。", + "Property_0_does_not_exist_on_type_1_2339": "プロパティ '{0}' は型 '{1}' に存在しません。", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "プロパティ '{0}' は型 '{1}' に存在していません。'{2}' ですか?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "プロパティ '{0}' は型 '{1}' には存在しません。代わりに静的メンバー '{2}' にアクセスしようとしていましたか?", + "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "プロパティ '{0}' が型 '{1}' に存在しません。ターゲット ライブラリを変更する必要がありますか? 'lib' コンパイラ オプションを '{2}' 以降に変更してみてください。", + "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812": "プロパティ ' {0} ' は型 ' {1} ' に存在しません。' lib ' コンパイラ オプションを ' dom ' を含むように変更してみてください。", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817": "プロパティ '{0}' に初期化子がなく、クラスの静的ブロックで明確に割り当てられていません。", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "プロパティ '{0}' に初期化子がなく、コンストラクターで明確に割り当てられていません。", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。get アクセサーには戻り値の型の注釈がないためです。", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。set アクセサーにはパラメーター型の注釈がないためです。", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048": "プロパティ '{0}' の型は暗黙的に 'any' ですが、その get アクセサーのために、使い方からより良い型を推論する場合があります。", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049": "プロパティ '{0}' の型は暗黙的に 'any' になっていますが、その set アクセサーのより良い型を使い方から推論できます。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "型 '{1}' のプロパティ '{0}' を基本データ型 '{2}' の同じプロパティに割り当てることはできません。", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "型 '{1}' のプロパティ '{0}' を型 '{2}' に割り当てることはできません。", + "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "型 '{1}' のプロパティ '{0}' は、型 '{2}' 内からアクセスできない別のメンバーを参照しています。", + "Property_0_is_declared_but_its_value_is_never_read_6138": "プロパティ '{0}' が宣言されていますが、その値が読み取られることはありません。", + "Property_0_is_incompatible_with_index_signature_2530": "プロパティ '{0}' はインデックス シグネチャと互換性がありません。", + "Property_0_is_missing_in_type_1_2324": "型 '{1}' にプロパティ '{0}' がありません。", + "Property_0_is_missing_in_type_1_but_required_in_type_2_2741": "プロパティ '{0}' は型 '{1}' にありませんが、型 '{2}' では必須です。", + "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013": "プロパティ '{0}' には private 識別子が指定されているため、クラス '{1}' の外部ではアクセスできません。", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "プロパティ '{0}' は型 '{1}' では省略可能ですが、型 '{2}' では必須です。", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "プロパティ '{0}' はプライベートで、クラス '{1}' 内でのみアクセスできます。", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "プロパティ '{0}' は型 '{1}' ではプライベートですが、型 '{2}' ではプライベートではありません。", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446": "プロパティ '{0}' は保護されており、クラス '{1}' のインスタンスを通じてのみアクセスできます。これは、クラス '{2}' のインスタンスです。", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "プロパティ '{0}' は保護されているため、クラス '{1}' とそのサブクラス内でのみアクセスできます。", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "プロパティ '{0}' は保護されていますが、型 '{1}' は '{2}' から派生したクラスではありません。", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "プロパティ '{0}' は型 '{1}' では保護されていますが、型 '{2}' ではパブリックです。", + "Property_0_is_used_before_being_assigned_2565": "プロパティ '{0}' は割り当てられる前に使用されています。", + "Property_0_is_used_before_its_initialization_2729": "プロパティ '{0}' が初期化前に使用されています。", + "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568": "プロパティ '{0}' は型 '{1}' に存在していない可能性があります。'{2}' ですか?", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX のスプレッド属性のプロパティ '{0}' をターゲット プロパティに割り当てることはできません。", + "Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected_4094": "エクスポートされた匿名クラス型のプロパティ '{0}' は、プライベートでないか保護されていない可能性があります。", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411": "型 '{1}' のプロパティ '{0}' は'{2}' インデックス型 '{3}' に割り当てることはできません。", + "Property_0_was_also_declared_here_2733": "ここではプロパティ '{0}' も宣言されています。", + "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612": "プロパティ '{0}' は、'{1}' の基底プロパティを上書きします。これが意図的である場合は初期化子を追加してください。そうでなければ、'declare' 修飾子を追加するか、冗長な宣言を削除してください。", + "Property_assignment_expected_1136": "プロパティの代入が必要です。", + "Property_destructuring_pattern_expected_1180": "プロパティの非構造化パターンが必要です。", + "Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9012": "プロパティには、--isolatedDeclarations を含む明示的な型注釈が必要です。", + "Property_or_signature_expected_1131": "プロパティまたはシグネチャが必要です。", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "プロパティ値には、文字列リテラル、数値リテラル、'true'、'false'、'null'、オブジェクト リテラルまたは配列リテラルのみ使用できます。", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_6179": "'for-of'、spread、destructuring で 'ES5' を対象とする場合は、iterables を完全にサポートします。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "エクスポートされたクラスのパブリック メソッド '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "エクスポートされたクラスのパブリック メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "エクスポートされたクラスのパブリック メソッド '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "エクスポートされたクラスのパブリック プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "エクスポートされたクラスのパブリック静的メソッド '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032": "先頭に '@param {object} {1}' がない場合、修飾名 '{0}' は許可されません。", + "Raise_an_error_when_a_function_parameter_isn_t_read_6676": "関数パラメーターが読み取られていないときに、エラーを発生させます。", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "暗黙的な 'any' 型を含む式と宣言に関するエラーを発生させます。", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "暗黙的な 'any' 型を持つ 'this' 式でエラーが発生します。", + "Range_out_of_order_in_character_class_1517": "文字クラスの順序が正しくありません。", + "Re_exporting_a_type_when_0_is_enabled_requires_using_export_type_1205": "'{0}' が有効な場合に型を再エクスポートするには、'export type' を使用する必要があります。", + "React_components_cannot_include_JSX_namespace_names_2639": "React コンポーネントに JSX 名前空間名を含めることはできません", + "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", + "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617": "TypeScript によって自動的に読み込まれるプロジェクトの数を減らします。", + "Referenced_project_0_may_not_disable_emit_6310": "参照されたプロジェクト '{0}' は、生成を無効にできません。", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "参照されているプロジェクト '{0}' には、設定 \"composite\": true が必要です。", + "Referenced_via_0_from_file_1_1400": "ファイル '{1}' から '{0}' を介して参照されています", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2834": "相対インポート パスでは、'--moduleResolution' が 'node16' または 'nodenext' である場合、ECMAScript インポートに明示的なファイル拡張子が必要です。インポート パスに拡張機能を追加することを検討してください。", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2835": "相対インポート パスでは、'--moduleResolution' が 'node16' または 'nodenext' である場合、ECMAScript インポートに明示的なファイル拡張子が必要です。'{0}' を意図していましたか?", + "Remove_a_list_of_directories_from_the_watch_process_6628": "ウォッチ プロセスからディレクトリの一覧を削除します。", + "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629": "ウォッチ モードの処理からファイルの一覧を削除します。", + "Remove_all_unnecessary_override_modifiers_95163": "不要な 'override' 修飾子をすべて削除", + "Remove_all_unnecessary_uses_of_await_95087": "不要な 'await' の使用をすべて削除する", + "Remove_all_unreachable_code_95051": "到達できないコードをすべて削除します", + "Remove_all_unused_labels_95054": "すべての未使用のラベルを削除します", + "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115": "関連する問題のあるすべてのアロー関数本体から中かっこを削除します", + "Remove_braces_from_arrow_function_95060": "アロー関数から中かっこを削除します", + "Remove_braces_from_arrow_function_body_95112": "アロー関数本体から中かっこを削除します", + "Remove_import_from_0_90005": "'{0}' からのインポートを削除", + "Remove_override_modifier_95161": "'override ' 修飾子の削除", + "Remove_parentheses_95126": "かっこの削除", + "Remove_template_tag_90011": "テンプレート タグを削除する", + "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618": "TypeScript 言語サーバーの JavaScript ファイルのソース コードの合計サイズについて 20 MB の上限を削除します。", + "Remove_type_from_import_declaration_from_0_90055": "\"{0}\" からインポート宣言から `type` を削除します", + "Remove_type_from_import_of_0_from_1_90056": "\"{1}\" から `{0}` のインポートから `type` を削除します", + "Remove_type_parameters_90012": "型パラメーターを削除する", + "Remove_unnecessary_await_95086": "不要な 'await' を削除する", + "Remove_unreachable_code_95050": "到達できないコードを削除します", + "Remove_unused_declaration_for_Colon_0_90004": "'{0}' に対する使用されていない宣言を削除する", + "Remove_unused_declarations_for_Colon_0_90041": "'{0}' に対する使用されていない宣言を削除してください", + "Remove_unused_destructuring_declaration_90039": "使用されていない非構造化宣言を削除してください", + "Remove_unused_label_95053": "未使用のラベルを削除します", + "Remove_variable_statement_90010": "変数のステートメントを削除します", + "Rename_param_tag_name_0_to_1_95173": "'@param' タグ名の名前を '{0}' から '{1}' に変更します", + "Replace_0_with_Promise_1_90036": "'{0}' を 'Promise<{1}>' に置き換える", + "Replace_all_unused_infer_with_unknown_90031": "未使用の 'infer' をすべて 'unknown' に置き換える", + "Replace_import_with_0_95015": "インポートを '{0}' に置換します。", + "Replace_infer_0_with_unknown_90030": "'infer {0}' を 'unknown' に置き換える", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "関数の一部のコード パスが値を返さない場合にエラーを報告します。", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch ステートメントに case のフォールスルーがある場合にエラーを報告します。", + "Report_errors_in_js_files_8019": ".js ファイルのエラーを報告します。", + "Report_errors_on_unused_locals_6134": "使用されていないローカルに関するエラーを報告します。", + "Report_errors_on_unused_parameters_6135": "使用されていないパラメーターに関するエラーを報告します。", + "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719": "他のツールが宣言ファイルを簡単に生成できるように、エクスポートに十分な注釈を必要とします。", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717": "要素アクセスを使用するには、インデックス シグネチャからの宣言されていないプロパティが必要です。", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必須の型パラメーターの後に、オプションの型パラメーターを続けることはできません。", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "モジュール '{0}' の解決が場所 '{1}' のキャッシュに見つかりました。", + "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "種類参照指令 '{0}' の解決策は、場所 '{1}' のキャッシュには見つかりませんでした。", + "Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_i_6277": "非相対名の解決に失敗しました。npm ライブラリで構成の更新が必要かどうかを確認するために、最新のノード解決機能を無効にしています。", + "Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_ne_6279": "非相対名の解決に失敗しました。'--moduleResolution bundler' を使用して、プロジェクトで構成の更新が必要かどうかを確認しています。", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'keyof' を文字列値のプロパティ名のみに解決します (数字または記号なし)。", + "Resolved_under_condition_0_6414": "条件 '{0}' で解決されました。", + "Resolving_in_0_mode_with_conditions_1_6402": "条件 {1} を使用して {0} モードで解決しています。", + "Resolving_module_0_from_1_6086": "======== '{1}' からモジュール '{0}' を解決しています。========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "ベース URL '{1}' - '{2}' に相対するモジュール名 '{0}' を解決しています。", + "Resolving_real_path_for_0_result_1_6130": "'{0}' の実際のパスを解決しています。結果は '{1}' です。", + "Resolving_type_reference_directive_0_containing_file_1_6242": "======== ファイル '{1}' のある種類参照指令 '{0}' の解決 ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイル '{1}'、ルート ディレクトリ '{2}'。========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイル '{1}'、ルート ディレクトリは未設定。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイルは未設定、ルート ディレクトリ '{1}'。========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 型参照ディレクティブ '{0}' を解決しています。それを含むファイルは未設定、ルート ディレクトリは未設定。========", + "Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_no_6265": "カスタム typeRoots を指定するプログラムの型参照ディレクティブを解決しています。'node_modules' フォルダーでの参照をスキップします。", + "Resolving_with_primary_search_path_0_6121": "プライマリ検索パス '{0}' で解決しています。", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest パラメーター '{0}' の型は暗黙的に 'any[]' になります。", + "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047": "rest パラメーター '{0}' の型は暗黙的に 'any[]' 型ですが、使い方からより良い型を推論する場合があります。", + "Rest_types_may_only_be_created_from_object_types_2700": "rest 型はオブジェクトの種類からのみ作成できます。", + "Return_type_annotation_circularly_references_itself_2577": "戻り値の型の注釈は、それ自身を循環参照します。", + "Return_type_must_be_inferred_from_a_function_95149": "戻り値の型は関数から推論される必要があります", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "コンストラクター シグネチャの戻り値の型は、クラスのインスタンス型に割り当て可能でなければなりません。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "エクスポートされた関数の戻り値の型が外部モジュール {1} の名前 '{0}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "エクスポートされた関数の戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "エクスポートされた関数の戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を持っているか、使用しています。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "エクスポートされたクラスのパブリック メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を持っているか、使用しています。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395": "場所 '{2}' のキャッシュにあった '{1}' からモジュール '{0}' の解決策を再利用しましたが、解決できませんでした。", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393": "場所 '{2}' のキャッシュにあった '{1}' からモジュール '{0}' の解決策を再利用すると、'{3}' に正常に解決されました。", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394": "場所 '{2}' からキャッシュにあった '{1}' からモジュール '{0}' の解決策を再利用すると、パッケージ ID '{4}' の '{3}' に正常に解決されました。", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389": "古いプログラムの '{1}' からモジュール '{0}' の解決策を再利用しようとしましたが、解決されませんでした。", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183": "古いプログラムの '{1}' からモジュール '{0}' の解決策を再利用すると、'{2}' に正常に解決されました。", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184": "古いプログラムの '{1}' からモジュール '{0}' の解決策を再利用すると、パッケージ ID '{3}' の '{2}' に正常に解決されました。", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398": "場所 '{2}' からキャッシュにあった '{1}' からタイプ リファレンス ディレクティブ '{0}' の解決策を再利用しましたが、解決できませんでした。", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396": "場所 '{2}' からキャッシュにあった '{1}' からタイプ リファレンス ディレクティブ '{0}' の解決策を再利用すると、'{3}' に正常に解決されました。", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397": "場所 '{2}' からキャッシュにあった '{1}' からタイプ リファレンス ディレクティブ '{0}' の解決策を再利用すると、パッケージ ID '{4}' の '{3}' に正常に解決されました。", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392": "古いプログラムの '{1}' からタイプ リファレンス ディレクティブ '{0}' の解決策を再利用しましたが、解決できませんでした。", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390": "古いプログラムの '{1}' からタイプ リファレンス ディレクティブ '{0}' の解決策を再利用すると、'{2}' に正常に解決されました。", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391": "古いプログラムの '{1}' からタイプ リファレンス ディレクティブ '{0}' の解決策を再利用すると、パッケージ ID '{3}' の '{2}' に正常に解決されました。", + "Rewrite_all_as_indexed_access_types_95034": "すべてをインデックス付きアクセス型として書き換えます", + "Rewrite_as_the_indexed_access_type_0_90026": "インデックス付きのアクセスの種類 '{0}' として書き換える", + "Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_i_6421": "相対インポート パスの '.ts'、'.tsx'、'.mts'、および '.cts' ファイル拡張子を、出力ファイルの JavaScript と同等の拡張子に書き換えます。", + "Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish_2869": "?? の右オペランド左オペランドが NULL 値になることがないため、到達できません。", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "ルート ディレクトリを決定できません。プライマリ検索パスをスキップします。", + "Root_file_specified_for_compilation_1427": "コンパイル用に指定されたルート ファイル", + "STRATEGY_6039": "戦略", + "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "プロジェクトのインクリメンタル コンパイルを可能にするには、.tsbuildinfo ファイルを保存します。", + "Saw_non_matching_condition_0_6405": "一致しない条件 '{0}' がありました。", + "Scoped_package_detected_looking_in_0_6182": "'{0}' 内を検索して、スコープ パッケージが検出されました", + "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418": "すべての先祖 node_modules ディレクトリでフォールバック拡張子を検索しています: {0}。", + "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417": "すべての先祖 node_modules ディレクトリで優先する拡張子を検索しています: {0}。", + "Selection_is_not_a_valid_statement_or_statements_95155": "選択内容は有効なステートメントではありません", + "Selection_is_not_a_valid_type_node_95133": "選択は有効な型ノードではありません", + "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705": "生成された JavaScript の JavaScript 言語バージョンを設定し、互換性のあるライブラリ宣言を含めます。", + "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654": "TypeScript からのメッセージの言語を設定します。これは生成には影響を与えません。", + "Set_the_module_option_in_your_configuration_file_to_0_95099": "構成ファイルの 'module' オプションを '{0}' に設定する", + "Set_the_newline_character_for_emitting_files_6659": "ファイルを生成するための改行文字を設定します。", + "Set_the_target_option_in_your_configuration_file_to_0_95098": "構成ファイルの 'target' オプションを '{0}' に設定する", + "Setters_cannot_return_a_value_2408": "セッターは値を返せません。", + "Show_all_compiler_options_6169": "コンパイラ オプションをすべて表示します。", + "Show_diagnostic_information_6149": "診断情報を表示します。", + "Show_verbose_diagnostic_information_6150": "詳細な診断情報を表示します。", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "ビルドされる (または '--clean' で指定される場合は、削除される) 内容を表示する", + "Signature_0_must_be_a_type_predicate_1224": "シグネチャ '{0}' は型の述語である必要があります。", + "Signature_declarations_can_only_be_used_in_TypeScript_files_8017": "署名宣言は TypeScript ファイルでのみ使用できます。", + "Skip_building_downstream_projects_on_error_in_upstream_project_6640": "アップストリーム プロジェクトのエラー時にダウンストリーム プロジェクトのビルドをスキップします。", + "Skip_type_checking_all_d_ts_files_6693": "すべての .d.ts ファイルについて型チェックをスキップします。", + "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692": "TypeScript に含まれている .d.ts ファイルの型チェックをスキップします。", + "Skip_type_checking_of_declaration_files_6012": "宣言ファイルの型チェックをスキップします。", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Skipping build of project '{0}' because its dependency '{1}' has errors", + "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382": "Skipping build of project '{0}' because its dependency '{1}' was not built", + "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164": "絶対 URI のように見えるモジュール '{0}' をスキップしています。ターゲット ファイルの種類: {1}。", + "Source_from_referenced_project_0_included_because_1_specified_1414": "'{1}' が指定されたため、参照先プロジェクト '{0}' からソースがインクルードされました", + "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415": "'--module' が 'none' として指定されたため、参照先プロジェクト '{0}' からソースがインクルードされました", + "Source_has_0_element_s_but_target_allows_only_1_2619": "ソースには {0} 個の要素がありますが、ターゲットで使用できるのは {1} 個のみです。", + "Source_has_0_element_s_but_target_requires_1_2618": "ソースには {0} 個の要素が含まれていますが、ターゲットには {1} 個が必要です。", + "Source_provides_no_match_for_required_element_at_position_0_in_target_2623": "ソースには、ターゲットの位置 {0} にある必須要素と一致するものがありません。", + "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624": "ソースには、ターゲットの位置 {0} にある可変個引数要素と一致するものがありません。", + "Specify_ECMAScript_target_version_6015": "ECMAScript ターゲット バージョンを指定します。", + "Specify_JSX_code_generation_6080": "JSX コードの生成を指定します。", + "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679": "1 つの JavaScript ファイルにすべての出力をバンドルするファイルを指定します。'declaration' が true の場合は、すべての .d.ts 出力をバンドルするファイルも指定します。", + "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641": "コンパイルに含めるファイルに一致する glob パターンの一覧を指定します。", + "Specify_a_list_of_language_service_plugins_to_include_6681": "含める言語サービス プラグインの一覧を指定します。", + "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651": "ターゲットのランタイム環境を記述する、バンドルされたライブラリ宣言ファイルのセットを指定します。", + "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680": "追加の検索場所にインポートを再マップするエントリのセットを指定します。", + "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687": "プロジェクトのパスを指定するオブジェクトの配列を指定します。プロジェクトの参照で使用されます。", + "Specify_an_output_folder_for_all_emitted_files_6678": "すべての生成されたファイルに対して出力フォルダーを指定します。", + "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718": "型にのみ使用されるインポートの生成または確認動作を指定します。", + "Specify_file_to_store_incremental_compilation_information_6380": "増分コンパイル情報を格納するファイルを指定する", + "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658": "TypeScript を使用して、指定されたモジュール指定子でファイルを検索する方法を指定します。", + "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714": "再帰的なファイル ウォッチ機能を持たないシステムでディレクトリをウォッチするための方法を指定します。", + "Specify_how_the_TypeScript_watch_mode_works_6715": "TypeScript ウォッチ モードの動作方法を指定します。", + "Specify_library_files_to_be_included_in_the_compilation_6079": "コンパイルに含めるライブラリ ファイルを指定します。", + "Specify_module_code_generation_6016": "モジュール コードの生成を指定します。", + "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649": "'jsx: react-jsx*' を使用するときに JSX ファクトリ関数のインポートに使用するモジュール指定子を指定します。", + "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710": "'./node_modules/@types' のように動作する複数のフォルダーを指定します。", + "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633": "設定の継承元となる基本構成ファイルへのパスまたはノード モジュール参照を 1 つまたは複数指定します。", + "Specify_options_for_automatic_acquisition_of_declaration_files_6709": "宣言ファイルの自動取得に関するオプションを指定します。", + "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227": "ファイル システムのイベントを使用して作成できなかった場合に、ポーリング監視を作成する方法を指定します: 'FixedInterval' (既定)、'PriorityInterval'、'DynamicPriority'、'FixedChunkSize'。", + "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226": "再帰的な監視をネイティブでサポートしていないプラットフォーム上のディレクトリを監視する方法を指定します: 'UseFsEvents' (既定)、'FixedPollingInterval'、'DynamicPriorityPolling'、'FixedChunkSizePolling'。", + "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225": "ファイルの監視方法を指定します: 'FixedPollingInterval' (既定)、'PriorityPollingInterval'、'DynamicPriorityPolling'、'FixedChunkSizePolling'、'UseFsEvents'、'UseFsEventsOnParentDirectory'。", + "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648": "React JSX 発行を対象とするときにフラグメントに使用される JSX フラグメント参照を指定します ('React.Fragment' や 'Fragment' など)。", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "'react' JSX 発行 ('React.createElement' や 'h') などを対象とするときに使用する JSX ファクトリ関数を指定します。", + "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647": "React JSX 発行を対象とするときに使用される JSX ファクトリ関数を指定します ('React.createElement' や 'h' など)。", + "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034": "'jsxFactory' コンパイラ オプションを指定して 'react' JSX 生成をターゲットにするときに使用する JSX フラグメント ファクトリ関数を指定します (例: 'Fragment')。", + "Specify_the_base_directory_to_resolve_non_relative_module_names_6607": "非相対モジュール名を解決するための基本ディレクトリを指定します。", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "ファイルの生成時に使用する行シーケンスの末尾を指定します: 'CRLF' (dos) または 'LF' (unix)。", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "デバッガーがソースの場所の代わりに TypeScript ファイルを検索する必要のある場所を指定します。", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655": "デバッガーが、生成された場所の代わりにマップ ファイルを検索する必要のある場所を指定します。", + "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656": "'node_modules' で JavaScript ファイルを確認するために使用するフォルダーの深さの最大値を指定します。'allowJs' にのみ適用可能です。", + "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238": "'jsx' と 'jsxs' のファクトリ関数をインポートするために使用されるモジュール指定子を指定します。例: react", + "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686": "'createElement' に対して呼び出されたオブジェクトを指定します。これは、'react' JSX 発行を対象とする場合にのみ適用されます。", + "Specify_the_output_directory_for_generated_declaration_files_6613": "生成された宣言ファイルの出力ディレクトリを指定します。", + "Specify_the_path_to_tsbuildinfo_incremental_compilation_file_6707": ".tsbuildinfo 増分コンパイル ファイルへのパスを指定します。", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "入力ファイルのルート ディレクトリを指定します。--outDir とともに、出力ディレクトリ構造の制御に使用します。", + "Specify_the_root_folder_within_your_source_files_6690": "ソース ファイル内のルート フォルダーを指定します。", + "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695": "デバッガーのルート パスを指定して、参照ソース コードを検索します。", + "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711": "ソース ファイルに参照されずに含める型のパッケージ名を指定します。", + "Specify_what_JSX_code_is_generated_6646": "生成済みの JSX コードを指定します。", + "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634": "システムがネイティブ ファイル ウォッチャーを使い果たした場合に、ウォッチャーが使用するアプローチを指定します。", + "Specify_what_module_code_is_generated_6657": "生成済みのモジュール コードを指定します。", + "Split_all_invalid_type_only_imports_1367": "無効な型のみのインポートをすべて分割する", + "Split_into_two_separate_import_declarations_1366": "2 つの別個のインポート宣言に分割する", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' 式のスプレッド演算子は ECMAScript 5 以上をターゲットにする場合にのみ使用できます。", + "Spread_types_may_only_be_created_from_object_types_2698": "spread 型はオブジェクトの種類からのみ作成できます。", + "Starting_compilation_in_watch_mode_6031": "ウォッチ モードでのコンパイルを開始しています...", + "Statement_expected_1129": "ステートメントが必要です。", + "Statements_are_not_allowed_in_ambient_contexts_1036": "ステートメントは環境コンテキストでは使用できません。", + "Static_members_cannot_reference_class_type_parameters_2302": "静的メンバーはクラスの型パラメーターを参照できません。", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "静的プロパティ '{0}' がコンストラクター関数 '{1}' のビルトイン プロパティ 'Function.{0}' と競合しています。", + "String_literal_expected_1141": "文字列リテラルが必要です。", + "String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es_18057": "'--module' フラグが 'es2015' または 'es2020' に設定されている場合、文字列リテラルのインポートおよびエクスポート名はサポートされません。", + "String_literal_with_double_quotes_expected_1327": "二重引用符を含む文字列リテラルが必要です。", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "色とコンテキストを使用してエラーとメッセージにスタイルを適用します (試験的)。", + "Subpattern_flags_must_be_present_when_there_is_a_minus_sign_1504": "マイナス記号がある場合は、サブパターン フラグが存在する必要があります。", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "後続のプロパティ宣言は同じ型でなければなりません。プロパティ '{0}' の型は '{1}' である必要がありますが、ここでは型が '{2}' になっています。", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "後続の変数宣言は同じ型でなければなりません。変数 '{0}' の型は '{1}' である必要がありますが、'{2}' になっています。", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "パターン '{1}' の代入 '{0}' の型が正しくありません。必要な型は 'string' ですが、'{2}' を取得しました。", + "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062": "パターン '{1}' の置換 '{0}' に使用できる '*' 文字は 1 文字だけです。", + "Substitutions_for_pattern_0_should_be_an_array_5063": "パターン '{0}' への代入は配列でなければなりません。", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "パターン '{0}' への代入を空の配列にすることはできません。", + "Successfully_created_a_tsconfig_json_file_6071": "tsconfig.json ファイルが正常に作成されました。", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "super の呼び出しは、コンストラクターの外部、またはコンストラクター内の入れ子になった関数では使用できません。", + "Suppress_excess_property_checks_for_object_literals_6072": "オブジェクト リテラルの過剰なプロパティ確認を抑制します。", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "インデックス シグニチャのないオブジェクトにインデックスを作成するため、noImplicitAny エラーを抑制します。", + "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703": "インデックス シグネチャのないオブジェクトにインデックスを作成する際、'noImplicitAny' エラーを表示しません。", + "Switch_each_misused_0_to_1_95138": "誤用されている各 '{0}' を '{1}' に切り替えてください", + "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704": "再帰的なウォッチをネイティブでサポートしていないプラットフォーム上で、同期的にコールバックを呼び出してディレクトリ ウォッチャーの状態を更新します。", + "Syntax_Colon_0_6023": "構文: {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "タグ '{0}' には少なくとも '{1}' 個の引数が必要ですが、JSX ファクトリ '{2}' で提供されるのは最大 '{3}' 個です。", + "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "タグ付きテンプレート式は、省略可能なチェーンでは許可されていません。", + "Target_allows_only_0_element_s_but_source_may_have_more_2621": "ターゲットには {0} 個の要素のみを使用できますが、ソースにはそれより多くを指定できます。", + "Target_requires_0_element_s_but_source_may_have_fewer_2620": "ターゲットには {0} 個の要素が必要ですが、ソースに指定する数はそれより少なくても構いません。", + "Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1_2849": "ターゲット署名の引数が少なすぎます。{0} 以上が必要ですが、{1} でした。", + "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "'{0}' 修飾子は TypeScript ファイルでのみ使用できます。", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "'{0}' 演算子を 'symbol' 型に適用することはできません。", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "'{0}' 演算子はブール型には使用できません。代わりに '{1}' を使用してください。", + "The_0_property_of_an_async_iterator_must_be_a_method_2768": "非同期反復子の '{0}' プロパティはメソッドである必要があります。", + "The_0_property_of_an_iterator_must_be_a_method_2767": "反復子の '{0}' プロパティはメソッドである必要があります。", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' 型を割り当てることができるその他の型はごく少数です。代わりの候補には 'any' 型があります。", + "The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously_1502": "Unicode (u) フラグと Unicode Sets (v) フラグを同時に設定することはできません。", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_func_2496": "'arguments' オブジェクトは、ES5 のアロー関数で参照することはできません。標準の関数式の使用を考慮してください。", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_sta_2522": "'arguments' オブジェクトは、ES5 の非同期関数またはメソッドで参照することはできません。標準の関数またはメソッドを使用することを検討してください。", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' ステートメントの本文を空のステートメントにすることはできません。", + "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793": "呼び出しはこの実装に対して成功した可能性がありますが、オーバーロードの実装シグネチャは外部からは参照できません。", + "The_character_set_of_the_input_files_6163": "入力ファイルの文字セット。", + "The_containing_arrow_function_captures_the_global_value_of_this_7041": "含まれているアロー関数は、'this' のグローバル値をキャプチャします。", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "含まれている関数またはモジュールの本体は、制御フロー解析には大きすぎます。", + "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309": "現在のファイルは CommonJS モジュールであり、最上位レベルでは 'await' を使用できません。", + "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479": "現在のファイルは CommonJS モジュールであり、このインポートでは 'require' 呼び出しが生成されますが、参照ファイルは ECMAScript モジュールであるため、'require' ではインポートできません。代わりに動的な 'import(\"{0}\")' 呼び出しを記述することを検討してください。", + "The_current_host_does_not_support_the_0_option_5001": "現在のホストは '{0}' オプションをサポートしていません。", + "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018": "使用するつもりだったと思われる '{0}' の宣言はここで定義されています", + "The_declaration_was_marked_as_deprecated_here_2798": "この宣言はここで非推奨とマークされました。", + "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500": "予期された型は、型 '{1}' に対してここで宣言されたプロパティ '{0}' から取得されています", + "The_expected_type_comes_from_the_return_type_of_this_signature_6502": "予期された型は、このシグネチャの戻り値の型に基づいています。", + "The_expected_type_comes_from_this_index_signature_6501": "予期された型は、このインデックス シグネチャに基づいています。", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの代入の式は、環境コンテキストの識別子または修飾名にする必要があります。", + "The_file_is_in_the_program_because_Colon_1430": "ファイルがプログラム内に存在します。理由:", + "The_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。", + "The_first_export_default_is_here_2752": "最初のエクスポートの既定値はここにあります。", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。", + "The_implementation_signature_is_declared_here_2750": "実装シグネチャはここで宣言されています。", + "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "'import.meta' メタプロパティは、CommonJS 出力にビルドするファイルでは許可されていません。", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "'import.meta' メタプロパティは、'--module' オプションが 'es2020'、'es2022'、'esnext'、'system'、'node16'、'node18'、または 'nodenext' である場合にのみ許可されます。", + "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}' の推論された型には、'{1}' への参照なしで名前を付けることはできません。これは、移植性がない可能性があります。型の注釈が必要です。", + "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "'{0}' の推論された型は、循環構造を持つ型を参照しています。この型のシリアル化は自明ではありません。型の注釈が必要です。", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' の推定型はアクセス不可能な '{1}' 型を参照します。型の注釈が必要です。", + "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056": "このノードの推定型は、コンパイラがシリアル化する最大長を超えています。明示的な型の注釈が必要です。", + "The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_n_2850": "'using' 宣言の初期化子は、'[Symbol.dispose]()' メソッドを持つオブジェクトであるか、'null' または 'undefined' である必要があります。", + "The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_2851": "'await using' 宣言の初期化子は、'[Symbol.asyncDispose]()' または '[Symbol.dispose]5D;()' メソッドを持つオブジェクトであるか、'null' または 'undefined' である必要があります。", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "交差 '{0}' は 'なし' に縮小されました。プロパティ '{1}' が複数の構成要素に存在し、一部ではプライベートであるためです。", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "交差 '{0}' は 'なし' に縮小されました。一部の構成要素でプロパティ '{1}' の型が競合しているためです。", + "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795": "'組み込み' キーワードは、コンパイラが提供する組み込み型を宣言する場合にのみ使用できます。", + "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016": "'jsxFactory' コンパイラ オプションで JSX フラグメントを使用するには、'jsxFragmentFactory' コンパイラ オプションを指定する必要があります。", + "The_last_overload_gave_the_following_error_2770": "前回のオーバーロードにより、次のエラーが発生しました。", + "The_last_overload_is_declared_here_2771": "前回のオーバーロードはここで宣言されています。", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' ステートメントの左側を非構造化パターンにすることはできません。", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493": "'for...in' ステートメントの左側を 'using' 宣言にすることはできません。", + "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494": "'for...in' ステートメントの左側を 'await using' 宣言にすることはできません。", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' ステートメントの左側で型の注釈を使用することはできません。", + "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780": "'for...in' ステートメントの左辺には、省略可能なプロパティ アクセスを指定できません。", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' ステートメントの左側は、変数またはプロパティ アクセスである必要があります。", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' ステートメントの左側の型は 'string' または 'any' でなければなりません。", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' ステートメントの左側で型の注釈を使用することはできません。", + "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781": "'for...of' ステートメントの左辺には、省略可能なプロパティ アクセスを指定できません。", + "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106": "'for...of' ステートメントの左辺には、'async' を指定できません。", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' ステートメントの左側は、変数またはプロパティ アクセスである必要があります。", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "算術演算の左辺には、'any' 型、'number' 型、'bigint' 型、または列挙型を指定する必要があります。", + "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "代入式の左辺には、省略可能なプロパティ アクセスを指定できません。", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "代入式の左側は、変数またはプロパティ アクセスである必要があります。", + "The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_2860": "'instanceof' 式の左側は、右側の '[Symbol.hasInstance]' メソッドの最初の引数に割り当て可能である必要があります。", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' 式の左辺には、'any' 型、オブジェクト型、または型パラメーターを指定してください。", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "ユーザーにメッセージを表示するときに使用するロケール (例: 'en-us')", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "node_modules の下を検索して JavaScript ファイルを読み込む依存関係の最大深度です。", + "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "'delete' 演算子のオペランドには、private 識別子を指定できません。", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "'delete' 演算子のオペランドには、読み取り専用のプロパティを指定できません。", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "'delete' 演算子のオペランドはプロパティ参照である必要があります。", + "The_operand_of_a_delete_operator_must_be_optional_2790": "'delete' 演算子のオペランドはオプションである必要があります。", + "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "インクリメント演算子またはデクリメント演算子のオペランドには、省略可能なプロパティ アクセスを指定することはできません。", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "インクリメントまたはデクリメント演算子のオペランドは、変数またはプロパティ アクセスである必要があります。", + "The_parser_expected_to_find_a_1_to_match_the_0_token_here_1007": "パーサーは、ここで '{0}' トークンに一致する '{1}' を予期していました。", + "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209": "プロジェクト ルートはあいまいですが、ファイル '{1}' のエクスポート マップ エントリ '{0}' を解決するために必要です。あいまいさを解消するには、'rootDir' コンパイラ オプションを指定します。", + "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210": "プロジェクト ルートはあいまいですが、ファイル '{1}' のインポート マップ エントリ '{0}' を解決するために必要です。あいまいさを解消するには、'rootDir' コンパイラ オプションを指定します。", + "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014": "同じスペルの別の private 識別子によってシャドウされているため、このクラス内の型 '{1}' ではプロパティ '{0}' にアクセスできません。", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "パラメーター デコレーター関数の戻り値の型は、'void' か 'any' である必要があります。", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "プロパティ デコレーター関数の戻り値の型は、'void' か 'any' である必要があります。", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "非同期関数の戻り値の型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065": "非同期関数または非同期メソッドの戻り値の型は、グローバル Promise 型である必要があります。", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "非同期関数または非同期メソッドの戻り値の型は、グローバル Promise 型である必要があります。'Promise<{0}>' と書き込むつもりでしたか?", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "'for...in' ステートメントの右側には、'any' 型、オブジェクト型、型パラメーターを指定する必要がありますが、ここでは型 '{0}' が指定されています。", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "算術演算の右辺には、'any' 型、'number' 型、'bigint' 型、または列挙型を指定する必要があります。", + "The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_2359": "'instanceof' 式の右側には、型 'any'、クラス、関数、または 'Function' インターフェイス型に割り当て可能なその他の型、または 'Symbol.hasInstance' メソッドを持つオブジェクト型のいずれかを指定する必要があります。", + "The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression_2848": "'instanceof' 式の右側をインスタンス化式にすることはできません。", + "The_root_value_of_a_0_file_must_be_an_object_5092": "'{0}' ファイルのルート値はオブジェクトである必要があります。", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0_1278": "このランタイムは {1} 引数を指定してデコレーターを呼び出しますが、デコレーターには {0} が必要です。", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0_1279": "このランタイムは {1} 引数を指定してデコレーターを呼び出しますが、デコレーターには少なくとも {0} が必要です。", + "The_shadowing_declaration_of_0_is_defined_here_18017": "'{0}' のシャドウ宣言はここで定義されています", + "The_signature_0_of_1_is_deprecated_6387": "'{1}' のシグネチャ '{0}' は非推奨です。", + "The_specified_path_does_not_exist_Colon_0_5058": "指定されたパスがありません: '{0}'。", + "The_tag_was_first_specified_here_8034": "このタグは最初にこちらで指定されました。", + "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "オブジェクト rest の代入先を、省略可能なプロパティ アクセスにすることはできません。", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の代入の対象は、変数またはプロパティ アクセスである必要があります。", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "型 '{0}' の 'this' コンテキストを型 '{1}' のメソッドの 'this' に割り当てることはできません。", + "The_this_types_of_each_signature_are_incompatible_2685": "各シグネチャの 'this' 型に互換性がありません。", + "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104": "型 '{0}' は 'readonly' であるため、変更可能な型 '{1}' に代入することはできません。", + "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "名前付きエクスポートで、export ステートメントに 'export type' が使用されている場合、'type' 修飾子は使用できません。", + "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "名前付きインポートで、import ステートメントに 'import type' が使用されている場合、'type' 修飾子は使用できません。", + "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "関数の宣言の型は、関数のシグネチャと一致する必要があります。", + "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "このノードの種類は、そのプロパティ '{0}' をシリアル化できないため、シリアル化できません。", + "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "非同期反復子の '{0}()' メソッドによって返される型は、'value' プロパティを持つ型に対する promise である必要があります。", + "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "反復子の '{0}()' メソッドによって返される型には 'value' プロパティが必要です。", + "The_types_of_0_are_incompatible_between_these_types_2200": "'{0}' の型は、これらの型同士で互換性がありません。", + "The_types_returned_by_0_are_incompatible_between_these_types_2201": "'{0}' によって返された型は、これらの型同士で互換性がありません。", + "The_value_0_cannot_be_used_here_18050": "値 '{0}' はここでは使用できません。", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' ステートメントの変数宣言に初期化子を指定することはできません。", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' ステートメントの変数宣言に初期化子を指定することはできません。", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' ステートメントはサポートされていません。'with' ブロック内のすべてのシンボルの型は 'any' になります。", + "There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setti_6280": "'{0}' に型がありますが、現在の 'moduleResolution' 設定ではこの結果を解決できませんでした。'node16'、'nodenext'、または 'bundler' への更新を検討してください。", + "There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278": "'{0}' に型がありますが、package.json \"exports\" を尊重しながらこの結果を解決できませんでした。'{1}' ライブラリの package.json または入力を更新する必要がある場合があります。", + "There_is_no_capturing_group_named_0_in_this_regular_expression_1532": "この正規表現には '{0}' という名前のキャプチャ グループはありません。", + "There_is_nothing_available_for_repetition_1507": "繰り返しに使用できるものがありません。", + "This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found_2874": "この JSX タグでは '{0}' がスコープ内に存在する必要がありますが、見つかりませんでした。", + "This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_fo_2875": "この JSX タグにはモジュール パス '{0}' が存在する必要がありますが、見つかりませんでした。適切なパッケージの種類がインストールされていることを確認してください。", + "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "この JSX タグの '{0}' prop は型 '{1}' の単一の子を予期しますが、複数の子が指定されました。", + "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "この JSX タグの '{0}' prop は複数の子を必要とする型 '{1}' を予期しますが、単一の子が指定されました。", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534": "この前方参照は、存在しないグループを参照しています。この正規表現にはキャプチャ グループがありません。", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533": "この前方参照は、存在しないグループを参照しています。この正規表現には {0} キャプチャ グループのみがあります。", + "This_binary_expression_is_never_nullish_Are_you_missing_parentheses_2870": "このバイナリ式が NULL 値になることはありません。かっこを忘れていませんか?", + "This_character_cannot_be_escaped_in_a_regular_expression_1535": "この文字を正規表現内でエスケープすることはできません。", + "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "'{0}' 型と '{1}' 型が重複していないため、この比較は意図したとおりに表示されない可能性があります。", + "This_condition_will_always_return_0_2845": "この条件は常に '{0}' を返します。", + "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "JavaScript が値ではなく参照でオブジェクトを比較するため、この条件は常に '{0}' を返します。", + "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "'{0}' が常に定義されているため、この条件は常に true を返します。", + "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "この関数は常に定義されているため、この条件は常に true を返します。代わりにこれを呼び出すことを意図していましたか?", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "このコンストラクター関数はクラス宣言に変換される可能性があります。", + "This_expression_is_always_nullish_2871": "この式は常に null です。", + "This_expression_is_not_callable_2349": "この式は呼び出し可能ではありません。", + "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "この式は 'get' アクセサーであるため、呼び出すことができません。'()' なしで使用しますか?", + "This_expression_is_not_constructable_2351": "この式はコンストラクト可能ではありません。", + "This_file_already_has_a_default_export_95130": "このファイルには、既に既定のエクスポートがあります", + "This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_b_2878": "このインポート パスは別のプロジェクトに解決され、プロジェクトの出力ファイル間の相対パスが入力ファイル間の相対パスと同じではないため、書き換えは安全ではありません。", + "This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_duri_2877": "このインポートでは、'{0}' 拡張子を使用して入力 TypeScript ファイルに解決されますが、生成中に書き換えられるのは相対パスではないためです。", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "これは拡張される宣言です。拡張する側の宣言を同じファイルに移動することを検討してください。", + "This_kind_of_expression_is_always_falsy_2873": "この種の式は常に false です。", + "This_kind_of_expression_is_always_truthy_2872": "この種の式は常に true です。", + "This_may_be_converted_to_an_async_function_80006": "これは非同期関数に変換できます。", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122": "このメンバーは、基底クラス '{0}' で宣言されていないため、このメンバーに '@override' タグを含む JSDoc コメントを指定することはできません。", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123": "このメンバーは、基底クラス '{0}' で宣言されていないため、このメンバーに 'override' タグを含む JSDoc コメントを指定することはできません。'{1}' ということですか?", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121": "このメンバーを含んでいるクラス '{0}' が別のクラスを拡張していないため、このメンバーに '@override' タグを含む JSDoc コメントを指定することはできません。", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic_4128": "このメンバーの名前は動的であるため、'@override' タグが含まれた JSDoc コメントを保持することはできません。", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113": "このメンバーは、基底クラス '{0}' で宣言されていないため、'override' 修飾子を指定することはできません。", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117": "このメンバーは、基底クラス '{0}' で宣言されていないため、'override' 修飾子を指定することはできません。'{1}' ということですか?", + "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112": "このメンバーを含んでいるクラス '{0}' が別のクラスを拡張していないため、このメンバーに 'override' 修飾子を指定することはできません。", + "This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic_4127": "名前が動的であるため、このメンバーに 'override' 修飾子を指定することはできません。", + "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119": "このメンバーには、基底クラス '{0}' のメンバーをオーバーライドするため、'@override' タグを含む JSDoc コメントが必要です。", + "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114": "このメンバーは、基底クラス '{0}' のメンバーをオーバーライドするため、'override' 修飾子を指定する必要があります。", + "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116": "このメンバーは、基底クラス '{0}' で宣言された抽象メソッドをオーバーライドするため、'override' 修飾子を指定する必要があります。", + "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "このモジュールは、'{0}' フラグをオンにして既定のエクスポートを参照することにより、ECMAScript のインポートまたはエクスポートのみを使用して参照できます。", + "This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag_2594": "このモジュールは、'export =' を使用して宣言されており、'{0}' フラグを使用する場合は既定のインポートでのみ使用できます。", + "This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2_6807": "この操作は簡略化できます。このシフトは '{0} {1} {2}' と同じです。", + "This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation_7012": "このオーバーロードは、戻り値の型の注釈がないため、型 '{0}' を暗黙的に返します。", + "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394": "このオーバーロード シグネチャには、実装シグネチャとの互換性はありません。", + "This_parameter_is_not_allowed_with_use_strict_directive_1346": "このパラメーターは、'use strict' ディレクティブと共に使用することはできません。", + "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120": "このパラメーター プロパティには、基底クラス '{0}' のメンバーをオーバーライドするため、'@override' タグを含む JSDoc コメントが必要です。", + "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115": "このメンバーは、基底クラス '{0}' のメンバーをオーバーライドするため、パラメーター プロパティに 'override' 修飾子がある必要があります。", + "This_regular_expression_flag_cannot_be_toggled_within_a_subpattern_1509": "この正規表現フラグをサブパターン内で切り替えることはできません。", + "This_regular_expression_flag_is_only_available_when_targeting_0_or_later_1501": "この正規表現フラグは、'{0}' 以降をターゲットにする場合にのみ使用できます。", + "This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolv_2876": "この相対インポート パスは、ファイル名のようですが、実際には \"{0}\" に解決されるため、書き換えは安全ではありません。", + "This_spread_always_overwrites_this_property_2785": "このスプレッドは、常にこのプロパティを上書きします。", + "This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled_1294": "'erasableSyntaxOnly' が有効な場合、この構文は使用できません。", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060": "この構文は、拡張子が .mts または .cts のファイルで予約されています。末尾のコンマまたは明示的な制約を追加します。", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059": "この構文は、拡張子が .mts または .cts のファイルで予約されています。代わりに `as` 式を使用してください。", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "この構文にはインポートされたヘルパーが必要ですが、モジュール '{0}' が見つかりません。", + "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "この構文には、'{1}' という名前のインポートされたヘルパーが必要ですが、'{0}' には存在しません。'{0}' のバージョンのアップグレードを検討してください。", + "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "この構文には、{2} パラメーターを持つ '{1}' という名前のインポートされたヘルパーが必要ですが、'{0}' にあるものと互換性がありません。'{0}' のバージョンをアップグレードすることをご検討ください。", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "この型パラメーターには 'extends {0}' 制約が必要な場合があります。", + "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "この 'import' の使用は無効です。'import()' 呼び出しは書き込むことができますが、かっこが必要であり、型引数を指定することはできません。", + "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482": "このファイルを ECMAScript モジュールに変換するには、フィールド '\"type\": \"module\"' を '{0}' に追加します。", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481": "このファイルを ECMAScript モジュールに変換するには、ファイル拡張子を '{0}' に変更するか、フィールド '\"type\": \"module\"' を '{1}' に追加します。", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480": "このファイルを ECMAScript モジュールに変換するには、ファイル拡張子を '{0}' に変更するか、'{ \"type\": \"module\" }' を含むローカルの package.json ファイルを作成します。", + "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483": "このファイルを ECMAScript モジュールに変換するには、'{ \"type\": \"module\" }' を含むローカルの package.json ファイルを作成します。", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "トップレベルの 'await' 式は、'module' オプションが 'es2022'、'esnext'、'system'、'node16'、'node18'、'nodenext'、または 'preserve' に設定されていて、'target' オプションが 'es2017' 以上に設定されている場合にのみ許可されています。", + "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854": "トップレベルの 'await using' ステートメントは、'module' オプションが 'es2022'、'esnext'、'system'、'node16'、'node18'、'nodenext'、または 'preserve' に設定されていて、'target' オプションが 'es2017' 以上に設定されている場合にのみ許可されています。", + "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": ".d.ts ファイルのトップレベルの宣言は、'declare' または 'export' 修飾子で始める必要があります。", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_nod_1432": "トップレベルの 'for await' ループは、'module' オプションが 'es2022'、'esnext'、'system'、'node16'、'node18'、'nodenext'、または 'preserve' に設定されていて、'target' オプションが 'es2017' 以上に設定されている場合にのみ許可されています。", + "Trailing_comma_not_allowed_1009": "末尾にコンマは使用できません。", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "個々のモジュールとして各ファイルをトランスパイルします ('ts.transpileModule' に類似)。", + "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "存在する場合は `npm i --save-dev @types/{1}` を試すか、`declare module '{0}';` を含む新しい宣言 (.d.ts) ファイルを追加します", + "Trying_other_entries_in_rootDirs_6110": "'rootDirs' の他のエントリを試しています。", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "代入 '{0}' を試しています。候補のモジュールの場所: '{1}'。", + "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493": "長さ '{1}' のタプル型 '{0}' にインデックス '{2}' の要素がありません。", + "Tuple_type_arguments_circularly_reference_themselves_4110": "タプル型の引数は、それ自体を循環参照します。", + "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802": "'{0}' の種類は、'--downlevelIteration' フラグを使用している場合、または 'es2015' 以降の '--target' を使用している場合にのみ反復処理できます。", + "Type_0_cannot_be_used_as_an_index_type_2538": "型 '{0}' はインデックスの型として使用できません。", + "Type_0_cannot_be_used_to_index_type_1_2536": "型 '{0}' はインデックスの種類 '{1}' に使用できません。", + "Type_0_does_not_satisfy_the_constraint_1_2344": "型 '{0}' は制約 '{1}' を満たしていません。", + "Type_0_does_not_satisfy_the_expected_type_1_1360": "型 '{0}' は想定された型 '{1}' を満たしていません。", + "Type_0_has_no_call_signatures_2757": "型 '{0}' には呼び出しシグネチャがありません。", + "Type_0_has_no_construct_signatures_2761": "型 '{0}' にはコンストラクト シグネチャがありません。", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "型 '{0}' には型 '{1}' と一致するインデックス シグネチャがありません。", + "Type_0_has_no_properties_in_common_with_type_1_2559": "型 '{0}' には型 '{1}' と共通のプロパティがありません。", + "Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable_2635": "型 '{0}' には、型引数リストを適用できるシグネチャがありません。", + "Type_0_is_generic_and_can_only_be_indexed_for_reading_2862": "型 '{0}' は汎用であり、読み取り専用にしかインデックスを作成できません。", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "型 '{0}' には 型 '{1}' からの次のプロパティがありません: {2}", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "型 '{0}' には 型 '{1}' からの次のプロパティがありません: {2}、{3} など。", + "Type_0_is_not_a_constructor_function_type_2507": "型 '{0}' はコンストラクター関数型ではありません。", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compa_1055": "型 '{0}' は Promise と互換性のあるコンストラクター値を参照しないため、ES5 において有効な非同期関数の戻り値の型ではありません。", + "Type_0_is_not_an_array_type_2461": "型 '{0}' は配列型ではありません。", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "型 '{0}' は配列型でも文字列型でもありません。", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "型 '{0}' は、配列型でも文字列型でもないか、反復子を返す '[Symbol.iterator]()' メソッドを持っていません。", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "型 '{0}' は、配列型ではないか、反復子を返す '[Symbol.iterator]()' メソッドを持っていません。", + "Type_0_is_not_assignable_to_type_1_2322": "型 '{0}' を型 '{1}' に割り当てることはできません。", + "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820": "型 '{0}' を型 '{1}' に割り当てることはできません。'{2}' でよろしいですか?", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "型 '{0}' は型 '{1}' に割り当てられません。同じ名前で 2 つの異なる型が存在しますが、これは関連していません。", + "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636": "型 '{0}' は、差異注釈によって暗黙的に示されているように、型 '{1}' に割り当てできません。", + "Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values_18033": "型 '{0}' は、計算された列挙型メンバーの要求どおりに型 '{1}' に割り当てることはできません。", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375": "型 '{0}' を、'exactOptionalPropertyTypes: true' が指定されている型 '{1}' に割り当てることはできません。ターゲットのプロパティの型に 'undefined' を追加することを検討してください。", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "型 '{0}' を、'exactOptionalPropertyTypes: true' が指定されている型 '{1}' に割り当てることはできません。ターゲットの型に 'undefined' を追加することを検討してください。", + "Type_0_is_not_comparable_to_type_1_2678": "型 '{0}' は型 '{1}' と比較できません。", + "Type_0_is_not_generic_2315": "型 '{0}' はジェネリックではありません。", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "型 '{0}' は、'in' 演算子の右オペランドとして許可されていないプリミティブ値を表す場合があります。", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "型 '{0}' には、非同期反復子を返す '[Symbol.asyncIterator]()' メソッドが必要です。", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "型 '{0}' には、反復子を返す '[Symbol.iterator]()' メソッドが必要です。", + "Type_0_provides_no_match_for_the_signature_1_2658": "型 '{0}' にはシグネチャ '{1}' に一致するものがありません。", + "Type_0_recursively_references_itself_as_a_base_type_2310": "型 '{0}' が、基本型としてそれ自体を再帰的に参照しています。", + "Type_Checking_6248": "種類を確認中", + "Type_alias_0_circularly_references_itself_2456": "型のエイリアス '{0}' が自身を循環参照しています。", + "Type_alias_must_be_given_a_name_1439": "型のエイリアスには名前を指定する必要があります。", + "Type_alias_name_cannot_be_0_2457": "型のエイリアス名を '{0}' にすることはできません。", + "Type_aliases_can_only_be_used_in_TypeScript_files_8008": "型のエイリアスは、TypeScript ファイルでのみ使用できます。", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "型の注釈はコンストラクター宣言では使用できません。", + "Type_annotations_can_only_be_used_in_TypeScript_files_8010": "型の注釈は、TypeScript ファイルでのみ使用できます。", + "Type_argument_expected_1140": "型引数が必要です。", + "Type_argument_list_cannot_be_empty_1099": "型引数リストを空にすることはできません。", + "Type_arguments_can_only_be_used_in_TypeScript_files_8011": "型引数は TypeScript ファイルでのみ使用できます。", + "Type_arguments_for_0_circularly_reference_themselves_4109": "'{0}' の型引数はそれ自体を循環参照します。", + "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016": "型アサーション式は TypeScript ファイルでのみ使用できます。", + "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626": "ソースの位置 {0} にある型は、ターゲットの位置 {1} にある型と互換性がありません。", + "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627": "ソースの位置 {0} から {1} にある型は、ターゲットの位置 {2} にある型と互換性がありません。", + "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039": "プライベート名 '{0}' を含む型は、--isolatedDeclarations と一緒には使用できません。", + "Type_declaration_files_to_be_included_in_compilation_6124": "コンパイルに含む型宣言ファイル。", + "Type_expected_1110": "型が必要です。", + "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456": "型インポート アサーションには、キー `resolution-mode` が 1 つだけ必要です。値は `import` または `require` です。", + "Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1464": "型インポート属性には、キー 'resolution-mode' が 1 つだけ必要です。値は 'import' または 'require' です。", + "Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute_1542": "CommonJS モジュールからの ECMAScript モジュールの型のインポートには、'resolution-mode' 属性が必要です。", + "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589": "型のインスタンス化は非常に深く、無限である可能性があります。", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "型は、それ自身の 'then' メソッドのフルフィルメント コールバック内で直接または間接的に参照されます。", + "Type_library_referenced_via_0_from_file_1_1402": "ファイル '{1}' から '{0}' を介して参照されたタイプ ライブラリ", + "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "packageId が '{2}' のファイル '{1}' から '{0}' を介して参照されたタイプ ライブラリ", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "計算されたプロパティの値の型は '{0}' です。これは、型 '{1}' に代入することはできません。", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "インスタンス メンバー変数 '{0}' の型は、コンストラクターで宣言された識別子 '{1}' を参照できません。", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' オペランドの反復要素の型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "マップされた型 '{1}' で、プロパティ '{0}' の型によってそれ自体が循環参照されています。", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同期ジェネレーター内の 'yield' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", + "Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribut_1541": "CommonJS モジュールからの ECMAScript モジュールの型のみのインポートには、'resolution-mode' 属性が必要です。", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "型はこのインポートで生成されます。名前空間スタイルのインポートは、呼び出すこともコンストラクトすることもできず、実行時にエラーが発生します。代わりに、ここで既定のインポートまたはインポートの require を使用することを検討してください。", + "Type_parameter_0_has_a_circular_constraint_2313": "型パラメーター '{0}' に循環制約があります。", + "Type_parameter_0_has_a_circular_default_2716": "型パラメーター '{0}' に循環既定値があります。", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "エクスポートされたインターフェイスの呼び出しシグネチャの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "エクスポートされたインターフェイスのコンストラクター シグネチャの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "エクスポートされたクラスの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "エクスポートされた関数の型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "エクスポートされたインターフェイスの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103": "エクスポートされたマップ済みのオブジェクト型の型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "エクスポートした型のエイリアスの型パラメーター '{0}' にプライベート名 '{1}' が指定されているか、これを使用しています。", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "エクスポートされたインターフェイスのメソッドの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "エクスポートされたクラスのパブリック メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "エクスポートされたクラスのパブリック静的メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_declaration_expected_1139": "型パラメーターの宣言が必要です。", + "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004": "型パラメーターの宣言は TypeScript ファイルでのみ使用できます。", + "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744": "型パラメーターの既定値は、以前に宣言された型パラメーターのみを参照できます。", + "Type_parameter_list_cannot_be_empty_1098": "型パラメーター リストを空にすることはできません。", + "Type_parameter_name_cannot_be_0_2368": "型パラメーター名を '{0}' にすることはできません。", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "型パラメーターはコンストラクター宣言では使用できません。", + "Type_predicate_0_is_not_assignable_to_1_1226": "型の述語 '{0}' を '{1}' に割り当てることはできません。", + "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799": "型では大きすぎて表すことができないタプル型を生成します。", + "Type_reference_directive_0_was_not_resolved_6120": "======== 型参照ディレクティブ '{0}' が解決されませんでした。========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 型参照ディレクティブ '{0}' が正常に '{1}' に解決されました。プライマリ: {2}。========", + "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== 型参照ディレクティブ '{0}' が正常に '{1}' に解決されました (パッケージ ID '{2}'、プライマリ: {3})。========", + "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037": "型充足式は TypeScript ファイルでのみ使用できます。", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "JavaScript ファイルのエクスポート宣言に型を含めることはできません。", + "Types_have_separate_declarations_of_a_private_property_0_2442": "複数の型に、プライベート プロパティ '{0}' の異なる宣言が含まれています。", + "Types_of_construct_signatures_are_incompatible_2419": "コンストラクト シグネチャの型に互換性がありません。", + "Types_of_parameters_0_and_1_are_incompatible_2328": "パラメーター '{0}' および '{1}' は型に互換性がありません。", + "Types_of_property_0_are_incompatible_2326": "プロパティ '{0}' の型に互換性がありません。", + "Unable_to_open_file_0_6050": "ファイル '{0}' を開くことができません。", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "式として呼び出される場合、クラス デコレーターのシグネチャを解決できません。", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "式として呼び出される場合、メソッド デコレーターのシグネチャを解決できません。", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "式として呼び出される場合、パラメーター デコレーターのシグネチャを解決できません。", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "式として呼び出される場合、プロパティ デコレーターのシグネチャを解決できません。", + "Undetermined_character_escape_1513": "文字エスケープが不明です。", + "Unexpected_0_Did_you_mean_to_escape_it_with_backslash_1508": "予期しない '{0}' です。バックスラッシュを使用してエスケープするつもりでしたか?", + "Unexpected_end_of_text_1126": "予期しないテキストの末尾です。", + "Unexpected_keyword_or_identifier_1434": "予期しないキーワードまたは識別子です。", + "Unexpected_token_1012": "予期しないトークンです。", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "予期しないトークンです。コンストラクター、メソッド、アクセサー、またはプロパティが必要です。", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "予期しないトークンです。型パラメーター名には、中かっこを含めることはできません。", + "Unexpected_token_Did_you_mean_or_gt_1382": "予期しないトークンです。`{'>'}` または `>` を意図していましたか?", + "Unexpected_token_Did_you_mean_or_rbrace_1381": "予期しないトークンです。`{'}'}` または `}` を意図していましたか?", + "Unexpected_token_expected_1179": "予期しないトークンです。'{' が必要です。", + "Unicode_escape_sequence_cannot_appear_here_17021": "Unicode エスケープ シーケンスはここでは使用できません。", + "Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_se_1538": "Unicode エスケープ シーケンスは、Unicode (u) フラグまたは Unicode Sets (v) フラグが設定されている場合にのみ使用できます。", + "Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v__1530": "Unicode プロパティ値式は、Unicode (u) フラグまたは Unicode Sets (v) フラグが設定されている場合にのみ使用できます。", + "Unknown_Unicode_property_name_1524": "Unicode プロパティ名が不明です。", + "Unknown_Unicode_property_name_or_value_1529": "Unicode プロパティ名または値が不明です。", + "Unknown_Unicode_property_value_1526": "Unicode プロパティ値が不明です。", + "Unknown_build_option_0_5072": "'{0}' は不明なビルド オプションです。", + "Unknown_build_option_0_Did_you_mean_1_5077": "'{0}' は不明なビルド オプションです。'{1}' を意図していましたか?", + "Unknown_compiler_option_0_5023": "コンパイラ オプション '{0}' が不明です。", + "Unknown_compiler_option_0_Did_you_mean_1_5025": "'{0}' は不明なコンパイラ オプションです。'{1}' を意図していましたか?", + "Unknown_keyword_or_identifier_Did_you_mean_0_1435": "不明なキーワードまたは識別子。'{0}' を意味していましたか?", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "不明なオプション 'excludes' です。'exclude' ですか?", + "Unknown_regular_expression_flag_1499": "正規表現フラグが不明です。", + "Unknown_type_acquisition_option_0_17010": "不明な型の取得オプション '{0}'。", + "Unknown_type_acquisition_option_0_Did_you_mean_1_17018": "'{0}' は不明な型の取得オプションです。'{1}' を意図していましたか?", + "Unknown_watch_option_0_5078": "'{0}' は不明な監視オプションです。", + "Unknown_watch_option_0_Did_you_mean_1_5079": "'{0}' は不明な監視オプションです。'{1}' を意図していましたか?", + "Unreachable_code_detected_7027": "到達できないコードが検出されました。", + "Unterminated_Unicode_escape_sequence_1199": "未終了の Unicode エスケープ シーケンスです。", + "Unterminated_quoted_string_in_response_file_0_6045": "応答ファイル '{0}' の文字列の終了引用符がありません。", + "Unterminated_regular_expression_literal_1161": "未終了の正規表現リテラルです。", + "Unterminated_string_literal_1002": "未終了の文字列リテラルです。", + "Unterminated_template_literal_1160": "未終了のテンプレート リテラルです。", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "型指定のない関数の呼び出しで型引数を使用することはできません。", + "Unused_label_7028": "未使用のラベル。", + "Unused_ts_expect_error_directive_2578": "'@ts-expect-error' ディレクティブが使用されていません。", + "Update_import_from_0_90058": "\"{0}\" からのインポートの更新", + "Update_modifiers_of_0_90061": "'{0}' の修飾子を更新してください", + "Updating_output_timestamps_of_project_0_6359": "プロジェクト '{0}' の出力タイムスタンプを更新しています...", + "Updating_unchanged_output_timestamps_of_project_0_6371": "プロジェクト '{0}' の変更されていない出力タイムスタンプを更新しています...", + "Use_0_95174": "\"{0}\" を使用します。", + "Use_0_instead_5106": "代わりに '{0}' を使用してください。", + "Use_Number_isNaN_in_all_conditions_95175": "すべての条件で 'Number.isNaN' を使用します。", + "Use_element_access_for_0_95145": "'{0}' に要素アクセスを使用する", + "Use_element_access_for_all_undeclared_properties_95146": "宣言されていないすべてのプロパティに対して要素アクセスを使用します。", + "Use_import_type_95180": "'import type' を使用してください", + "Use_synthetic_default_member_95016": "合成 'default' メンバーを使用します。", + "Use_the_package_json_exports_field_when_resolving_package_imports_6408": "パッケージのインポートを解決する場合、package.json の 'exports' フィールドを使用してください。", + "Use_the_package_json_imports_field_when_resolving_imports_6409": "インポートを解決するときに、package.json の 'imports' フィールドを使用してください。", + "Use_type_0_95181": "'type {0}' を使用してください", + "Using_0_subpath_1_with_target_2_6404": "'{0}' サブパス '{1}' をターゲット '{2}' と共に使用しています。", + "Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found_2879": "JSX フラグメントを使用するには、フラグメント ファクトリ '{0}' がスコープ内に存在する必要がありますが、見つかりませんでした。", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' ステートメントでの文字列の使用は ECMAScript 5 以上でのみサポートされています。", + "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "--build を使用すると、-b は tsc をコンパイラというよりビルド オーケストレーターのように動作させます。これは、複合プロジェクトのビルドをトリガーするために使用されます。詳細については、{0} を参照してください。", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", + "VERSION_6036": "バージョン", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "型 '{0}' の値には、型 '{1}' と共通のプロパティがありません。呼び出しますか?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "型 '{0}' の値は呼び出せません。'new' を含めますか?", + "Variable_0_implicitly_has_an_1_type_7005": "変数 '{0}' の型は暗黙的に '{1}' になります。", + "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043": "変数 '{0}' の型は暗黙的に '{1}' になっていますが、使い方からより良い型を推論できます。", + "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046": "場所によっては、変数 '{0}' の型に '{1}' が暗黙的に指定されていますが、使い方からより良い型を推論できます。", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "変数 '{0}' は、型を決定できない一部の場所では、暗黙のうちに '{1}' 型になります。", + "Variable_0_is_used_before_being_assigned_2454": "変数 '{0}' は割り当てられる前に使用されています。", + "Variable_declaration_expected_1134": "変数の宣言が必要です。", + "Variable_declaration_list_cannot_be_empty_1123": "変数宣言リストを空にすることはできません。", + "Variable_declaration_not_allowed_at_this_location_1440": "変数の宣言はこの場所では許可されていません。", + "Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9010": "変数には、--isolatedDeclarations を含む明示的な型注釈が必要です。", + "Variables_with_multiple_declarations_cannot_be_inlined_95186": "複数の宣言を含む変数をインライン化することはできません。", + "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625": "ソースの位置 {0} にある可変個引数要素は、ターゲットの位置 {1} にある要素と一致しません。", + "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637": "分散注釈は、オブジェクト、関数、コンストラクター、およびマップされた型の型エイリアスでのみサポートされています。", + "Version_0_6029": "バージョン {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file_95110": "このファイルの詳細については、https://aka.ms/tsconfig をご覧ください", + "WATCH_OPTIONS_6918": "ウォッチ オプション", + "Watch_and_Build_Modes_6250": "ウォッチ モードとビルド モード", + "Watch_input_files_6005": "入力ファイルを監視します。", + "Watch_option_0_requires_a_value_of_type_1_5080": "監視オプション '{0}' には型 {1} の値が必要です。", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "ここにパラメーター全体の型を追加することによってのみ、'{0}' の型を書き込むことができます。", + "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "関数を割り当てる際、パラメーターと戻り値が互換性のあるサブタイプであることを確認します。", + "When_type_checking_take_into_account_null_and_undefined_6699": "型チェックを行うときは、'null' と 'undefined' が考慮されます。", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "画面をクリアする代わりに、古くなったコンソール出力をウォッチ モードで保持するかどうか。", + "Wrap_all_invalid_characters_in_an_expression_container_95109": "式のコンテナー内のすべての無効な文字をラップする", + "Wrap_all_invalid_decorator_expressions_in_parentheses_95195": "無効なデコレーター式をすべてかっこで囲む", + "Wrap_all_object_literal_with_parentheses_95116": "すべてのオブジェクト リテラルをかっこで囲みます", + "Wrap_all_unparented_JSX_in_JSX_fragment_95121": "親の設定が解除されたすべての JSX を JSX フラグメントでラップする", + "Wrap_in_JSX_fragment_95120": "JSX フラグメントでラップする", + "Wrap_in_parentheses_95194": "かっこで囲む", + "Wrap_invalid_character_in_an_expression_container_95108": "式のコンテナー内の無効な文字をラップする", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "次の本体をかっこで囲みます。これはオブジェクト リテラルです", + "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "コンパイラ オプションの詳細については、{0} をご覧ください。", + "You_cannot_rename_a_module_via_a_global_import_8031": "グローバル インポートを使用してモジュールの名前を変更することはできません。", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "'node_modules' フォルダーで定義されている要素の名前を変更することはできません。", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "別の 'node_modules' フォルダーで定義されている要素の名前を変更することはできません。", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "標準の TypeScript ライブラリで定義された要素の名前を変更することはできません。", + "You_cannot_rename_this_element_8000": "この要素の名前を変更することはできません。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' は受け入れる引数が少なすぎるので、ここでデコレーターとして使用することができません。最初にこれを呼び出してから、'@{0}()' を書き込むつもりでしたか?", + "_0_and_1_index_signatures_are_incompatible_2330": "'{0}' および '{1}' インデックス シグネチャに互換性がありません。", + "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "'{0}' および '{1}' 演算をかっこなしで混在させることはできません。", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' は 2 回指定されています。'{0}' という名前の属性は上書きされます。", + "_0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17019": "型の末尾にある '{0}' は、有効な TypeScript 構文ではありません。'{1}' を書き込むつもりでしたか?", + "_0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17020": "型の先頭にある '{0}' は、有効な TypeScript 構文ではありません。'{1}' を書き込むつもりでしたか?", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}' をインポートするには、'esModuleInterop' フラグをオンにして既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}' をインポートするには、既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}' をインポートするには、'require' 呼び出しを使用するか、'esModuleInterop' フラグをオンにして既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}' をインポートするには、'require' 呼び出しを使用するか、既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}' をインポートするには、'import {1} = require({2})' または既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}' をインポートするには、'import {1} = require ({2})' を使用するか、'esModuleInterop' フラグをオンにして既定のインポートを使用する必要があります。", + "_0_cannot_be_used_as_a_JSX_component_2786": "'{0}' を JSX コンポーネントとして使用することはできません。", + "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "'export type' を使用してエクスポートされたため、'{0}' は値として使用できません。", + "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "'import type' を使用してインポートされたため、'{0}' は値として使用できません。", + "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "'{0}' コンポーネントには、テキストを子要素として指定できません。JSX のテキストには 'string' 型が含まれていますが、'{1}' の予期された型は '{2}' です。", + "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082": "'{1}' に関連しない可能性のある任意の型で '{0}' をインスタンス化できます。", + "_0_declarations_can_only_be_declared_inside_a_block_1156": "'{0}' 宣言は、ブロック内でのみ宣言できます。", + "_0_declarations_can_only_be_used_in_TypeScript_files_8006": "'{0}' 宣言は TypeScript ファイルでのみ使用できます。", + "_0_declarations_may_not_have_binding_patterns_1492": "'{0}' 宣言はバインド パターンを持っていない可能性があります。", + "_0_declarations_must_be_initialized_1155": "'{0}' 宣言は初期化する必要があります。", + "_0_expected_1005": "'{0}' が必要です。", + "_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is__18055": "'{0}' には文字列型がありますが、'isolatedModules' が有効である場合、構文的に認識可能な文字列構文が必要です。", + "_0_has_no_exported_member_named_1_Did_you_mean_2_2724": "'{1}' という名前のエクスポートされたメンバーが '{0}' に含まれていません。候補: '{2}'", + "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050": "'{0}' の戻り値の型は暗黙的に '{1}' になっていますが、使い方からより良い型を推論できます。", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "'{0}' は、戻り値の型の注釈がなく、いずれかの return 式で直接的にまたは間接的に参照されているため、戻り値の型は暗黙的に 'any' になります。", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' には型の注釈がなく、直接または間接的に初期化子で参照されているため、暗黙的に 'any' 型が含まれています。", + "_0_index_signatures_are_incompatible_2634": "'{0}' インデックス シグネチャに互換性がありません。", + "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "'{0}'インデックス型'{1}' を '{2}'インデックス型'{3}' に割り当てることはできません。", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' はプリミティブですが、'{1}' はラッパー オブジェクトです。できれば '{0}' をご使用ください。", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' は型であるため、JavaScript ファイルにインポートできません。JSDoc 型の注釈で '{1}' を使用します。", + "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled_1484": "'{0}' は型であり、'verbatimModuleSyntax' が有効であるときは、型のみのインポートを使用してインポートされる必要があります。", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}' は、'{1}' の未使用の名前変更です。型の注釈として使用するつもりでしたか?", + "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}' は型 '{1}' の制約に代入できますが、'{1}' は制約 '{2}' の別のサブタイプでインスタンス化できることがあります。", + "_0_is_automatically_exported_here_18044": "`{0}` は自動的にここにエクスポートされます。", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' が宣言されていますが、その値が読み取られることはありません。", + "_0_is_declared_but_never_used_6196": "'{0}' は宣言されましたが使用されませんでした。", + "_0_is_declared_here_2728": "'{0}' はここで宣言されています。", + "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611": "'{0}' はクラス '{1}' でプロパティとして定義されていますが、ここでは '{2}' でアクセサーとしてオーバーライドされています。", + "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}' はクラス '{1}' でアクセサーとして定義されていますが、ここではインスタンス プロパティとして '{2}' でオーバーライドされています。", + "_0_is_deprecated_6385": "'{0}' は非推奨です。", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' はキーワード '{1}' に関するメタプロパティとして無効です。候補: '{2}'。", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}' はパラメーター名として使用できません。", + "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}' は変数宣言の名前として使用できません。", + "_0_is_of_type_unknown_18046": "'{0}''は 'unknown' 型です。", + "_0_is_possibly_null_18047": "'{0}' は 'null' の可能性があります。", + "_0_is_possibly_null_or_undefined_18049": "'{0}' は 'null' か 'undefined' の可能性があります。", + "_0_is_possibly_undefined_18048": "'{0}' は 'undefined' の可能性があります。", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' はそれ自身のベース式内で直接または間接的に参照されます。", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' はそれ自身の型の注釈内で直接または間接的に参照されます。", + "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783": "'{0}' が複数回指定されているため、ここでの使用は上書きされます。", + "_0_list_cannot_be_empty_1097": "'{0}' のリストを空にすることはできません。", + "_0_modifier_already_seen_1030": "'{0}' 修飾子は既に存在します。", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias_1274": "'{0}' 修飾子は、クラス、インターフェイス、または型エイリアスの型パラメーターでのみ使用できます", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class_1277": "'{0}' 修飾子は、関数、メソッド、またはクラスの型パラメーターでのみ使用できます", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "'{0}' 修飾子はコンストラクター宣言では使用できません。", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "'{0}' 修飾子は、モジュールまたは名前空間の要素では使用できません。", + "_0_modifier_cannot_appear_on_a_parameter_1090": "'{0}' 修飾子はパラメーターでは使用できません。", + "_0_modifier_cannot_appear_on_a_type_member_1070": "'{0}' 修飾子は型メンバーでは使用できません。", + "_0_modifier_cannot_appear_on_a_type_parameter_1273": "'{0}' 修飾子は型パラメーターでは表示できません。", + "_0_modifier_cannot_appear_on_a_using_declaration_1491": "'{0}' 修飾子を 'using' 宣言で使用することはできません。", + "_0_modifier_cannot_appear_on_an_await_using_declaration_1495": "'{0}' 修飾子を 'await using' 宣言で使用することはできません。", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "'{0}' 修飾子はインデックス シグネチャでは使用できません。", + "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031": "'{0}' 修飾子はこの種類のクラス要素では使用できません。", + "_0_modifier_cannot_be_used_here_1042": "'{0}' 修飾子はここでは使用できません。", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "'{0}' 修飾子は環境コンテキストでは使用できません。", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 修飾子と '{1}' 修飾子は同時に使用できません。", + "_0_modifier_cannot_be_used_with_a_private_identifier_18019": "'{0}' 修飾子を private 識別子とともに使用することはできません。", + "_0_modifier_must_precede_1_modifier_1029": "'{0}' 修飾子は '{1}' 修飾子の前に指定する必要があります。", + "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531": "'\\{0}' の後には、中かっこで囲まれた Unicode プロパティ値式を指定する必要があります。", + "_0_needs_an_explicit_type_annotation_2782": "'{0}' には、明示的な型の注釈が必要です。", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' は型のみを参照しますが、ここで名前空間として使用されています。", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' は型のみを参照しますが、ここで値として使用されています。", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690": "'{0}' は型を参照しているだけですが、こちらでは値として使用されています。'{0} 内の {1}' を使用しますか?", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585": "'{0}' は型のみを参照しますが、ここでは値として使用されています。ターゲット ライブラリを変更しますか? 'lib' コンパイラ オプションを es2015 以降に変更してみてください。", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' は UMD グローバルを参照していますが、現在のファイルはモジュールです。代わりにインポートを追加することを考慮してください。", + "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749": "'{0}' は値を参照していますが、ここでは型として使用されています。'typeof {0}' を意図していましたか?", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1291": "'{0}' は型に解決され、'{1}' が有効であるときに再エクスポートする前に、このファイル内で型のみとしてマークする必要があります。'{0}' がインポートされる場所で 'import type' を使用することを検討してください。", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1292": "'{0}' は型に解決され、'{1}' が有効であるときに再エクスポートする前に、このファイル内で型のみとしてマークする必要があります。'export type { {0} as default }' を使用することを検討してください。", + "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimMo_1485": "'{0}' は型のみの宣言に解決されるため、'verbatimModuleSyntax' が有効であるときは、型のみのインポートを使用してインポートされる必要があります。", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1289": "'{0}' は型のみの宣言に解決され、'{1}' が有効であるときに再エクスポートする前に、このファイル内で型のみとしてマークする必要があります。'{0}' がインポートされる場所で 'import type' を使用することを検討してください。", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1290": "'{0}' は型のみの宣言に解決され、'{1}' が有効であるときに再エクスポートする前に、このファイル内で型のみとしてマークする必要があります。'export type { {0} as default }' を使用することを検討してください。", + "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_1448": "\"{0}\" は型のみの宣言に解決されるため、'{1}' が有効であるときは、型のみの再エクスポートを使用して再エクスポートされる必要があります。", + "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258": "config json ファイル の 'compilerOptions' オブジェクト内に '{0}' を設定する必要があります。", + "_0_tag_already_specified_1223": "'{0}' タグは既に指定されています。", + "_0_was_also_declared_here_6203": "ここでは '{0}' も宣言されました。", + "_0_was_exported_here_1377": "ここでは '{0} ' がエクスポートされました。", + "_0_was_imported_here_1376": "ここでは '{0}' がインポートされました。", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "'{0}' には戻り値の型の注釈がないため、戻り値の型は暗黙的に '{1}' になります。", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055": "'{0}' には戻り値の型の注釈がないため、yield 型は暗黙的に '{1}' になります。", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 修飾子は、クラス宣言、メソッド宣言、またはプロパティ宣言のみに使用できます。", + "accessor_modifier_can_only_appear_on_a_property_declaration_1275": "'accessor' 修飾子は、プロパティ宣言でのみ使用できます。", + "and_here_6204": "およびここで。", + "arguments_cannot_be_referenced_in_property_initializers_2815": "プロパティ初期化子で 'arguments' を参照することはできません。", + "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476": "\"auto\": インポート、エクスポート、import.meta、jsx (jsx: react-jsx を使用)、または esm 形式 (モジュール: node16+) でファイルをモジュールとして扱います。", + "await_expression_cannot_be_used_inside_a_class_static_block_18037": "'await' 式はクラスの静的ブロック内では使用できません。", + "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375": "ファイルがモジュールの場合、'await' 式はそのファイルのトップ レベルでのみ使用できますが、このファイルにはインポートもエクスポートも含まれていません。空の 'export {}' を追加して、このファイルをモジュールにすることを検討してください。", + "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308": "'await' 式は、非同期関数内と、モジュールのトップ レベルでのみ許可されます。", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 式は、パラメーター初期化子では使用できません。", + "await_has_no_effect_on_the_type_of_this_expression_80007": "'await' は、この式の型に対しては効果がありません。", + "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853": "'await using' ステートメントは、ファイルがモジュールである場合、そのファイルのトップ レベルでのみ使用できますが、このファイルにはインポートもエクスポートも含まれていません。空の 'export {}' を追加して、このファイルをモジュールにすることを検討してください。", + "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852": "'await using' ステートメントは、非同期関数内と、モジュールのトップ レベルでのみ許可されます。", + "await_using_statements_cannot_be_used_inside_a_class_static_block_18054": "'await using' ステートメントをクラスの静的ブロック内で使用することはできません。", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' オプションは '{0}' に設定され、この値を使用して非相対モジュール名 '{1}' を解決します。", + "c_must_be_followed_by_an_ASCII_letter_1512": "'\\c' の後には ASCII 文字が続く必要があります。", + "can_only_be_used_at_the_start_of_a_file_18026": "'#!' は、ファイルの先頭でのみ使用できます。", + "case_or_default_expected_1130": "'case' または 'default' が必要です。", + "catch_or_finally_expected_1472": "'catch' または 'finally' が必要です。", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列挙型メンバーの初期化子が、無限値に評価されました。", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列挙型メンバーの初期化子が、許可されない値 'NaN' に評価されました。", + "const_enum_member_initializers_must_be_constant_expressions_2474": "const 列挙型メンバー初期化子は定数式である必要があります。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの代入の右辺、型のクエリにのみ使用できます。", + "constructor_cannot_be_used_as_a_parameter_property_name_2398": "'constructor' をパラメーターのプロパティ名として使用することはできません。", + "constructor_is_a_reserved_word_18012": "'#constructor' は予約語です。", + "default_Colon_6903": "既定:", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "厳格モードでは 'delete' を識別子で呼び出すことはできません。", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *' では既定のものは再エクスポートされません。", + "export_can_only_be_used_in_TypeScript_files_8003": "'export =' は、TypeScript ファイルでのみ使用できます。", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "環境モジュールとモジュール拡張は常に表示されるので、これらに 'export' 修飾子を適用することはできません。", + "extends_clause_already_seen_1172": "'extends' 句は既に存在します。", + "extends_clause_must_precede_implements_clause_1173": "extends' 句は 'implements' 句の前に指定しなければなりません。", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "エクスポートされたクラス '{0}' の 'extends' 句がプライベート名 '{1}' を持っているか、使用しています。", + "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021": "エクスポートされたクラスの 'extends' 句がプライベート名 '{0}' を持っているか、使用しています。", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "エクスポートされたインターフェイス '{0}' の 'extends' 句がプライベート名 '{1}' を持っているか、使用しています。", + "false_unless_composite_is_set_6906": "'composite' が設定されていない場合は 'false'", + "false_unless_strict_is_set_6905": "'strict' が設定されている場合を除き、' false '", + "file_6025": "ファイル", + "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431": "ファイルがモジュールの場合、'for await' ループはそのファイルのトップ レベルでのみ使用できますが、このファイルにはインポートもエクスポートも含まれていません。空の 'export {}' を追加して、このファイルをモジュールにすることを検討してください。", + "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103": "'for await' ループは、非同期関数内と、モジュールのトップ レベルでのみ許可されます。", + "for_await_loops_cannot_be_used_inside_a_class_static_block_18038": "'for await' ループは、クラスの静的ブロック内では使用できません。", + "get_and_set_accessors_cannot_declare_this_parameters_2784": "'get' および 'set' アクセサーでは 'this' パラメーターを宣言できません。", + "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908": "'files' が指定されている場合は '[]'、それ以外の場合は '[\"**/*\"]5D;'", + "implements_clause_already_seen_1175": "'implements' 句は既に存在します。", + "implements_clauses_can_only_be_used_in_TypeScript_files_8005": "'implements' 句は、TypeScript ファイルでのみ使用できます。", + "import_can_only_be_used_in_TypeScript_files_8002": "'import ... =' は、TypeScript ファイルでのみ使用できます。", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "'infer' 宣言は、条件付き型の 'extends' 句でのみ許可されます。", + "k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets_1510": "'\\k' の後には、山かっこで囲まれたキャプチャ グループ名を指定する必要があります。", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let' は、'let' 宣言または 'const' 宣言で名前として使用することはできません。", + "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010": "モジュール === 'AMD'、'UMD'、'System'、'ES6'、'Classic'、それ以外の場合は 'Node'", + "module_system_or_esModuleInterop_6904": "module === \"system\" or esModuleInterop", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "ターゲットにコンストラクト シグネチャがない 'new' 式の型は、暗黙的に 'any' になります。", + "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907": "`[\"node_modules\", \"bower_components\", \"jspm_packages\"]`' と、指定されている場合は 'outDir' の値を加算します。", + "one_of_Colon_6900": "次のいずれか:", + "one_or_more_Colon_6901": "1 つ以上", + "options_6024": "オプション", + "or_JSX_element_expected_1145": "'{' または JSX 要素が必要です。", + "or_expected_1144": "'{' または ';' が必要です。", + "package_json_does_not_have_a_0_field_6100": "'package.json' に '{0}' フィールドがありません。", + "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json' には、バージョン '{0}' と一致する 'typesVersions' エントリがありません。", + "package_json_had_a_falsy_0_field_6220": "'package.json' には、false に評価される '{0}' フィールドが含まれています。", + "package_json_has_0_field_1_that_references_2_6101": "'package.json' に '{2}' を参照する '{0}' フィールド '{1}' があります。", + "package_json_has_a_peerDependencies_field_6281": "'package.json' に 'peerDependencies' フィールドがあります。", + "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209": "'package.json' には、有効な semver の範囲ではない 'typesVersions' エントリ '{0}' が含まれています。", + "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208": "'package.json' には、コンパイラ バージョン '{1}' に一致する 'typesVersions' エントリ '{0}' が含まれていて、モジュール名 '{2}' に一致するパターンを探しています。", + "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206": "'package.json' には、バージョン固有のパス マッピングを含む 'typesVersions' フィールドが含まれています。", + "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274": "package.json のスコープ '{0}' は、指定子 '{1}' を明示的に null にマッピングします。", + "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275": "package.json のスコープ '{0}' は、指定子 '{1}' のターゲットに無効な型です。", + "package_json_scope_0_has_no_imports_defined_6273": "package.json のスコープ '{0}' にはインポートが定義されていません。", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' オプションが指定され、モジュール名 '{0}' と一致するパターンを検索します。", + "q_is_only_available_inside_character_class_1511": "'\\q' は文字クラス内でのみ使用できます。", + "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521": "'\\q' の後には、中かっこで囲まれた代替文字列を指定する必要があります。", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾子はプロパティ宣言またはインデックス シグネチャのみに使用できます。", + "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "'readonly' 型の修飾子は、配列およびタプル リテラル型でのみ使用できます。", + "require_call_may_be_converted_to_an_import_80005": "'require' の呼び出しはインポートに変換される可能性があります。", + "resolution_mode_can_only_be_set_for_type_only_imports_1454": "`resolution-mode` は、型のみのインポートに対してのみ設定できます。", + "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "`resolution-mode` は、型インポート アサーションの唯一の有効なキーです。", + "resolution_mode_is_the_only_valid_key_for_type_import_attributes_1463": "'resolution-mode' が、型インポート属性の唯一の有効なキーです。", + "resolution_mode_should_be_either_require_or_import_1453": "\"resolution-mode\" は \"require\" または \"import\" のいずれかにする必要があります。", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' オプションが設定され、このオプションを使用して相対モジュール名 '{0}' を解決します。", + "super_can_only_be_referenced_in_a_derived_class_2335": "'super' は、派生クラスでのみ参照できます。", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' は、派生クラスのメンバーまたはオブジェクトのリテラル式のメンバーでのみ参照されます。", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super' は、計算されたプロパティ名では参照できません。", + "super_cannot_be_referenced_in_constructor_arguments_2336": "'super' はコンストラクター引数では参照できません。", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "オプション 'target' が 'ES2015' 以降の場合、'super' はオブジェクトのリテラル式のメンバーでのみ使用できます。", + "super_may_not_use_type_arguments_2754": "'super' では型引数を使用できません。", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "派生クラスのコンストラクター内の 'super' のプロパティにアクセスする前に、'super' を呼び出す必要があります。", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "派生クラスのコンストラクター内の 'this' にアクセスする前に、'super' を呼び出す必要があります。", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' の後には、引数リストまたはメンバー アクセスが必要です。", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "'super' プロパティ アクセスはコンストラクター、メンバー関数、または派生クラスのメンバー アクセサーでのみ許可されます。", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this' は、計算されたプロパティ名では参照できません。", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this' はモジュール本体内または名前空間本体内では参照できません。", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "'this' は、静的プロパティ初期化子では参照できません。", + "this_cannot_be_referenced_in_current_location_2332": "'this' は現在の場所では参照できません。", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this' は型として注釈を持たないため、暗黙的に型 'any' になります。", + "true_for_ES2022_and_above_including_ESNext_6930": "ESNext を含む ES2022 以降の場合は 'true' です。", + "true_if_composite_false_otherwise_6909": "'composite' の場合は 'true'、それ以外の場合は 'false'", + "true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false_6411": "'moduleResolution' が 'node16'、'nodenext'、または 'bundler' である場合は 'true'、それ以外の場合は 'false' です。", + "tsc_Colon_The_TypeScript_Compiler_6922": "tsc: TypeScript コンパイラ", + "type_Colon_6902": "種類:", + "unique_symbol_types_are_not_allowed_here_1335": "'unique symbol' 型はここでは許可されていません。", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'unique symbol' 型は変数ステートメントの変数でのみ許可されています。", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' 型は、バインディング名を持つ変数の宣言では使用できません。", + "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347": "'use strict' ディレクティブは、複雑なパラメーター リストでは使用できません。", + "use_strict_directive_used_here_1349": "'use strict' ディレクティブがここで使用されています。", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' 式は、非同期関数ブロックでは使用できません。", + "with_statements_are_not_allowed_in_strict_mode_1101": "厳格モードでは 'with' ステートメントは使用できません。", + "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057": "'yield' 式は、それを含むジェネレーターに戻り値の型の注釈がないため、暗黙的に 'any' 型になります。", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 式は、パラメーター初期化子では使用できません。" +} \ No newline at end of file diff --git a/node_modules/typescript/lib/ko/diagnosticMessages.generated.json b/node_modules/typescript/lib/ko/diagnosticMessages.generated.json new file mode 100644 index 00000000..f443e044 --- /dev/null +++ b/node_modules/typescript/lib/ko/diagnosticMessages.generated.json @@ -0,0 +1,2105 @@ +{ + "ALL_COMPILER_OPTIONS_6917": "모든 컴파일러 옵션", + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 한정자는 가져오기 선언에서 사용할 수 없습니다.", + "A_0_parameter_must_be_the_first_parameter_2680": "'{0}' 매개 변수는 첫 번째 매개 변수여야 합니다.", + "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039": "JSDoc '@template' 태그는 '@typedef', '@callback' 또는 '@overload' 태그 다음에 올 수 없습니다.", + "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033": "JSDoc '@typedef' 주석에 여러 '@type' 태그를 포함하지 못할 수 있습니다.", + "A_bigint_literal_cannot_be_used_as_a_property_name_1539": "'bigint' 리터럴은 속성 이름으로 사용할 수 없습니다.", + "A_bigint_literal_cannot_use_exponential_notation_1352": "bigint 리터럴에는 지수 표기법을 사용할 수 없습니다.", + "A_bigint_literal_must_be_an_integer_1353": "bigint 리터럴은 정수여야 합니다.", + "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "바인딩 패턴 매개 변수는 구현 서명에서 선택 사항이 될 수 없습니다.", + "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' 문은 이 문을 둘러싼 반복문 또는 switch 문 내에서만 사용할 수 있습니다.", + "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' 문은 이 문을 둘러싼 문의 레이블로만 이동할 수 있습니다.", + "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522": "문자 클래스는 예약된 이중 문장 부호를 포함해서는 안됩니다. 백슬래시로 이스케이프하려고 하셨나요?", + "A_character_class_range_must_not_be_bounded_by_another_character_class_1516": "문자 클래스 범위는 다른 문자 클래스에 의해 바인딩되어서는 안 됩니다.", + "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "클래스는 선택적 형식 인수가 포함된 식별자/정규화된 이름만 구현할 수 있습니다.", + "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422": "클래스는 개체 형식 또는 정적으로 알려진 멤버가 포함된 개체 형식의 교집합만 구현할 수 있습니다.", + "A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values_2863": "클래스는 '{0}' 같은 기본 형식을 확장할 수 없습니다. 클래스는 생성 가능한 값만 확장할 수 있습니다.", + "A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types_2864": "클래스는 '{0}' 같은 기본 형식을 구현할 수 없습니다. 다른 명명된 개체 형식만 구현할 수 있습니다.", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "'default' 한정자를 사용하지 않는 클래스 선언에는 이름이 있어야 합니다.", + "A_class_member_cannot_have_the_0_keyword_1248": "클래스 멤버에는 '{0}' 키워드를 사용할 수 없습니다.", + "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "쉼표 식은 컴퓨팅된 속성 이름에 사용할 수 없습니다.", + "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "계산된 속성 이름에서는 포함하는 형식의 형식 매개 변수를 참조할 수 없습니다.", + "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166": "클래스 속성 선언의 계산된 속성 이름에는 간단한 리터럴 형식 또는 '고유 기호' 형식이 있어야 합니다.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "메서드 오버로드의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "리터럴 형식의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "앰비언트 컨텍스트의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "인터페이스의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "계산된 속성 이름은 'string', 'number', 'symbol' 또는 'any' 형식이어야 합니다.", + "A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array__1355": "'const' 어설션은 열거형 멤버나 문자열, 숫자, 부울, 배열 또는 개체 리터럴에 대한 참조에만 적용할 수 있습니다.", + "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const 열거형 멤버는 문자열 리터럴을 통해서만 액세스할 수 있습니다.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254": "앰비언트 컨텍스트의 'const' 이니셜라이저는 문자열, 숫자 리터럴 또는 리터럴 열거형 참조여야 합니다.", + "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "생성자는 해당 클래스가 'null'을 확장하는 경우 'super' 호출을 포함할 수 없습니다.", + "A_constructor_cannot_have_a_this_parameter_2681": "생성자에는 'this' 매개 변수를 사용할 수 없습니다.", + "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' 문은 이 문을 둘러싼 반복문 내에서만 사용할 수 있습니다.", + "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' 문은 이 문을 둘러싼 반복문의 레이블로만 이동할 수 있습니다.", + "A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_f_2846": "'import type'이 없으면 선언 파일을 가져올 수 없습니다. 대신 '{0}' 구현 파일을 가져오시겠습니까?", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "'declare' 한정자는 이미 존재하는 앰비언트 컨텍스트에서 사용할 수 없습니다.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "데코레이터는 오버로드가 아니라 메서드 구현만 데코레이팅할 수 있습니다.", + "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' 절은 'switch' 문에 두 번 이상 나올 수 없습니다.", + "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "기본 내보내기는 ECMAScript 스타일 모듈에서만 사용할 수 있습니다.", + "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258": "기본 내보내기 수준은 파일 또는 모듈 선언의 최상위 수준에 있어야 합니다.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "이 컨텍스트에서는 한정된 할당 어설션 '!'가 허용되지 않습니다.", + "A_destructuring_declaration_must_have_an_initializer_1182": "구조 파괴 선언에 이니셜라이저가 있어야 합니다.", + "A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_t_2712": "ES5의 동적 가져오기 호출에 'Promise' 생성자가 필요합니다. 'Promise' 생성자에 대한 선언이 있거나 '--lib' 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "동적 가져오기 호출은 'Promise'를 반환합니다. 'Promise'에 대한 선언이 있거나 '--lib' 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "A_file_cannot_have_a_reference_to_itself_1006": "파일은 자신에 대한 참조를 포함할 수 없습니다.", + "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "'never'를 반환하는 함수에는 연결 가능한 끝점이 있을 수 없습니다.", + "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679": "'new' 키워드로 호출한 함수에는 'void'인 'this' 형식을 사용할 수 없습니다.", + "A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value_2355": "선언된 형식이 'undefined', 'void' 또는 'any'가 아닌 함수는 값을 반환해야 합니다.", + "A_generator_cannot_have_a_void_type_annotation_2505": "생성기에는 'void' 형식 주석을 사용할 수 없습니다.", + "A_get_accessor_cannot_have_parameters_1054": "'get' 접근자에는 매개 변수를 사용할 수 없습니다.", + "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808": "get 접근자는 최소한 setter의 액세스 가능 수준과 같아야 합니다.", + "A_get_accessor_must_return_a_value_2378": "'get' 접근자는 값을 반환해야 합니다.", + "A_label_is_not_allowed_here_1344": "여기서는 레이블을 사용할 수 없습니다.", + "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "레이블이 지정된 튜플 요소는 형식 뒤가 아니라 이름 뒤이면서 콜론 앞에 물음표를 사용하여 optional로 선언됩니다.", + "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "레이블이 지정된 튜플 요소는 형식 앞이 아니라 이름 앞에 '...'을 사용하여 rest로 선언됩니다.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "매핑된 형식은 속성 또는 메서드를 선언할 수 없습니다.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "열거형 선언의 멤버 이니셜라이저는 그 뒤에 선언된 멤버와 다른 열거형에 정의된 멤버를 참조할 수 없습니다.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin 클래스에는 'any[]' 형식의 rest 매개 변수 하나를 사용하는 생성자가 있어야 합니다.", + "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "추상 구문 시그니처를 포함하는 형식 변수에서 확장되는 mixin 클래스는 'abstract'로도 선언되어야 합니다.", + "A_module_cannot_have_multiple_default_exports_2528": "모듈에는 기본 내보내기가 여러 개 있을 수 없습니다.", + "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수와 다른 파일에 있을 수 없습니다,", + "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수 앞에 있을 수 없습니다.", + "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235": "네임스페이스 선언은 네임스페이스 또는 모듈의 최상위 수준에서만 허용됩니다.", + "A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_key_1540": "'module' 키워드를 사용하여 'namespace' 선언을 선언하면 안 됩니다. 대신 'namespace' 키워드를 사용하세요.", + "A_non_dry_build_would_build_project_0_6357": "-dry가 아닌 빌드는 프로젝트 '{0}'을(를) 빌드합니다.", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "-dry가 아닌 빌드는 다음 파일을 삭제합니다. {0}", + "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374": "DRY가 아닌 빌드는 '{0}' 프로젝트의 출력 타임스탬프를 업데이트합니다.", + "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "매개 변수 이니셜라이저는 함수 또는 생성자 구현에서만 허용됩니다.", + "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "rest 매개 변수를 사용하여 매개 변수 속성을 선언할 수 없습니다.", + "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "매개 변수 속성은 생성자 구현에서만 허용됩니다.", + "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "바인딩 패턴을 사용하여 매개 변수 속성을 선언할 수 없습니다.", + "A_promise_must_have_a_then_method_1059": "프라미스에는 'then' 메서드가 있어야 합니다.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "형식이 'unique symbol' 형식인 클래스의 속성은 'static'과 'readonly' 둘 다여야 합니다.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "형식이 'unique symbol' 형식인 인터페이스 또는 형식 리터럴의 속성은 'readonly'여야 합니다.", + "A_required_element_cannot_follow_an_optional_element_1257": "필수 요소는 선택적 요소 뒤에 올 수 없습니다.", + "A_required_parameter_cannot_follow_an_optional_parameter_1016": "필수 매개 변수는 선택적 매개 변수 뒤에 올 수 없습니다.", + "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 요소에는 바인딩 패턴이 포함될 수 없습니다.", + "A_rest_element_cannot_follow_another_rest_element_1265": "rest 요소는 다른 rest 요소 뒤에 올 수 없습니다.", + "A_rest_element_cannot_have_a_property_name_2566": "rest 요소에는 속성 이름을 사용할 수 없습니다.", + "A_rest_element_cannot_have_an_initializer_1186": "rest 요소에는 이니셜라이저를 사용할 수 없습니다.", + "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "rest 요소는 배열 구조 파괴 패턴의 마지막 요소여야 합니다.", + "A_rest_element_type_must_be_an_array_type_2574": "rest 요소 형식은 배열 형식이어야 합니다.", + "A_rest_parameter_cannot_be_optional_1047": "rest 매개 변수는 선택 사항이 될 수 없습니다.", + "A_rest_parameter_cannot_have_an_initializer_1048": "rest 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", + "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 매개 변수는 매개 변수 목록 마지막에 있어야 합니다.", + "A_rest_parameter_must_be_of_an_array_type_2370": "rest 매개 변수는 배열 형식이어야 합니다.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표가 없을 수 있습니다.", + "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' 문은 함수 본문 내에서만 사용할 수 있습니다.", + "A_return_statement_cannot_be_used_inside_a_class_static_block_18041": "'return' 문은 클래스 정적 블록 내에서 사용할 수 없습니다.", + "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "가져오기를 'baseUrl'에 상대적인 조회 위치로 다시 매핑하는 일련의 항목입니다.", + "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' 접근자에는 반환 형식 주석을 사용할 수 없습니다.", + "A_set_accessor_cannot_have_an_optional_parameter_1051": "'set' 접근자에는 선택적 매개 변수를 사용할 수 없습니다.", + "A_set_accessor_cannot_have_rest_parameter_1053": "'set' 접근자에는 rest 매개 변수를 사용할 수 없습니다.", + "A_set_accessor_must_have_exactly_one_parameter_1049": "'set' 접근자에는 매개 변수를 하나만 사용해야 합니다.", + "A_set_accessor_parameter_cannot_have_an_initializer_1052": "'set' 접근자 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", + "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556": "확산 인수는 튜플 유형을 가지거나 나머지 매개 변수로 전달되어야 합니다.", + "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401": "'super' 호출은 초기화된 속성, 매개 변수 속성 또는 개인 식별자를 포함하는 파생 클래스의 생성자 내에서 루트 수준 문이어야 합니다.", + "A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_2376": "파생 클래스에 초기화된 속성, 매개 변수 속성 또는 개인 식별자가 포함된 경우 'super' 호출은 '수퍼' 또는 'this'를 참조하는 생성자의 첫 번째 명령문이어야 합니다.", + "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518": "'this' 기반 형식 가드는 매개 변수 기반 형식 가드와 호환되지 않습니다.", + "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 형식은 클래스 또는 인터페이스의 비정적 멤버에서만 사용할 수 있습니다.", + "A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimM_1287": "'verbatimModuleSyntax'를 사용하도록 설정한 경우 CommonJS 모듈의 값 선언에 최상위 'export' 한정자를 사용할 수 없습니다.", + "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' 파일이 이미 '{0}'에 정의되어 있습니다.", + "A_tuple_member_cannot_be_both_optional_and_rest_5085": "튜플 멤버는 optional이면서 rest일 수 없습니다.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "튜플 형식은 음수 값으로 인덱싱할 수 없습니다.", + "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "지수 식의 왼쪽에는 type assertion expression을 사용할 수 없습니다. 식을 괄호로 묶는 것이 좋습니다.", + "A_type_literal_property_cannot_have_an_initializer_1247": "형식 리터럴 속성에는 이니셜라이저를 사용할 수 없습니다.", + "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "형식 전용 가져오기는 기본 가져오기 또는 명명된 바인딩을 지정할 수 있지만, 둘 다 지정할 수는 없습니다.", + "A_type_predicate_cannot_reference_a_rest_parameter_1229": "형식 조건자는 rest 매개 변수를 참조할 수 없습니다.", + "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "형식 조건자는 바인딩 패턴에서 '{0}' 요소를 참조할 수 없습니다.", + "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "형식 조건자는 함수 및 메서드의 반환 형식 위치에서만 사용할 수 있습니다.", + "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "형식 조건자의 형식을 해당 매개 변수의 형식에 할당할 수 있어야 합니다.", + "A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_w_1272": "데코레이팅된 서명에서 참조하는 유형은 'isolatedModules' 및 'emitDecoratorMetadata'가 활성화된 경우 '가져오기 유형' 또는 네임스페이스 가져오기를 사용하여 가져와야 합니다.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "형식이 'unique symbol' 형식인 변수는 'const'여야 합니다.", + "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "'yield' 식은 생성기 본문에서만 사용할 수 있습니다.", + "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "super 식을 통해 '{1}' 클래스의 추상 메서드 '{0}'에 액세스할 수 없습니다.", + "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "추상 메서드는 추상 클래스 내에서만 사용할 수 있습니다.", + "Abstract_properties_can_only_appear_within_an_abstract_class_1253": "추상 속성은 추상 클래스 내에만 나타날 수 있습니다.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "생성자에서 '{1}' 클래스의 추상 속성 '{0}'에 액세스할 수 없습니다.", + "Accessibility_modifier_already_seen_1028": "액세스 가능성 한정자가 이미 있습니다.", + "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "접근자는 ECMAScript 5 이상을 대상으로 지정할 때만 사용할 수 있습니다.", + "Accessors_must_both_be_abstract_or_non_abstract_2676": "접근자는 모두 추상이거나 비추상이어야 합니다.", + "Add_0_to_unresolved_variable_90008": "확인되지 않은 변수에 '{0}.' 추가", + "Add_a_return_statement_95111": "return 문 추가", + "Add_a_return_type_to_the_function_declaration_9031": "함수 선언에 반환 형식을 추가합니다.", + "Add_a_return_type_to_the_function_expression_9030": "함수 식에 반환 형식을 추가합니다.", + "Add_a_return_type_to_the_get_accessor_declaration_9032": "get 접근자 선언에 반환 형식을 추가합니다.", + "Add_a_return_type_to_the_method_9034": "메서드에 반환 형식 추가", + "Add_a_type_annotation_to_the_parameter_0_9028": "{0} 매개 변수에 형식 주석을 추가합니다.", + "Add_a_type_annotation_to_the_property_0_9029": "{0} 속성에 형식 주석을 추가합니다.", + "Add_a_type_annotation_to_the_variable_0_9027": "{0} 변수에 형식 주석을 추가합니다.", + "Add_a_type_to_parameter_of_the_set_accessor_declaration_9033": "set 접근자 선언의 매개 변수에 형식을 추가합니다.", + "Add_all_missing_async_modifiers_95041": "누락된 모든 'async' 한정자 추가", + "Add_all_missing_attributes_95168": "누락된 특성 모두 추가", + "Add_all_missing_call_parentheses_95068": "누락된 호출 괄호 모두 추가", + "Add_all_missing_function_declarations_95157": "누락된 함수 선언 모두 추가", + "Add_all_missing_imports_95064": "누락된 모든 가져오기 추가", + "Add_all_missing_members_95022": "누락된 모든 멤버 추가", + "Add_all_missing_override_modifiers_95162": "누락된 모든 'override' 한정자 추가", + "Add_all_missing_parameters_95190": "누락된 매개 변수 모두 추가", + "Add_all_missing_properties_95166": "누락된 모든 속성 추가", + "Add_all_missing_return_statement_95114": "누락된 모든 return 문 추가", + "Add_all_missing_super_calls_95039": "누락된 모든 super 호출 추가", + "Add_all_missing_type_annotations_90067": "누락된 모든 형식 주석 추가", + "Add_all_optional_parameters_95193": "모든 선택적 매개 변수 추가", + "Add_annotation_of_type_0_90062": "'{0}' 형식의 주석 추가", + "Add_async_modifier_to_containing_function_90029": "포함된 함수에 async 한정자 추가", + "Add_await_95083": "'await' 추가", + "Add_await_to_initializer_for_0_95084": "'{0}'의 이니셜라이저에 'await' 추가", + "Add_await_to_initializers_95089": "이니셜라이저에 'await' 추가", + "Add_braces_to_arrow_function_95059": "화살표 함수에 중괄호 추가", + "Add_const_to_all_unresolved_variables_95082": "확인되지 않은 모든 변수에 'const' 추가", + "Add_const_to_unresolved_variable_95081": "확인되지 않은 변수에 'const' 추가", + "Add_definite_assignment_assertion_to_property_0_95020": "'{0}' 속성에 한정된 할당 어설션 추가", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "초기화되지 않은 모든 속성에 한정된 할당 어설션 추가", + "Add_export_to_make_this_file_into_a_module_95097": "'export {}'를 추가하여 이 파일을 모듈로 만들기", + "Add_extends_constraint_2211": "`extends` 제약 조건을 추가합니다.", + "Add_extends_constraint_to_all_type_parameters_2212": "모든 형식 매개 변수에 `extends` 제약 조건 추가", + "Add_import_from_0_90057": "\"{0}\"에서 가져오기 추가", + "Add_index_signature_for_property_0_90017": "'{0}' 속성에 대해 인덱스 시그니처 추가", + "Add_initializer_to_property_0_95019": "'{0}' 속성에 이니셜라이저 추가", + "Add_initializers_to_all_uninitialized_properties_95027": "초기화되지 않은 모든 속성에 이니셜라이저 추가", + "Add_missing_attributes_95167": "누락된 특성 추가", + "Add_missing_call_parentheses_95067": "누락된 호출 괄호 추가", + "Add_missing_comma_for_object_member_completion_0_95187": "개체 멤버 완료 '{0}'에 대한 누락된 쉼표 추가", + "Add_missing_enum_member_0_95063": "누락된 열거형 멤버 '{0}' 추가", + "Add_missing_function_declaration_0_95156": "누락된 함수 선언 '{0}' 추가", + "Add_missing_new_operator_to_all_calls_95072": "모든 호출에 누락된 'new' 연산자 추가", + "Add_missing_new_operator_to_call_95071": "호출에 누락된 'new' 연산자 추가", + "Add_missing_parameter_to_0_95188": "'{0}'에 누락된 매개 변수 추가", + "Add_missing_parameters_to_0_95189": "'{0}'에 누락된 매개 변수 추가", + "Add_missing_properties_95165": "누락된 속성 추가", + "Add_missing_super_call_90001": "누락된 'super()' 호출 추가", + "Add_missing_typeof_95052": "누락된 'typeof' 추가", + "Add_names_to_all_parameters_without_names_95073": "이름이 없는 모든 매개 변수에 이름 추가", + "Add_optional_parameter_to_0_95191": "'{0}'에 선택적 매개 변수 추가", + "Add_optional_parameters_to_0_95192": "'{0}'에 선택적 매개 변수 추가", + "Add_or_remove_braces_in_an_arrow_function_95058": "화살표 함수에 중괄호 추가 또는 제거", + "Add_override_modifier_95160": "'override' 한정자 추가", + "Add_parameter_name_90034": "매개 변수 이름 추가", + "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "멤버 이름과 일치하는 모든 확인되지 않은 변수에 한정자 추가", + "Add_resolution_mode_import_attribute_95196": "'resolution-mode' 가져오기 특성 추가", + "Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it_95197": "필요한 모든 형식 전용 가져오기에 'resolution-mode' 가져오기 특성을 추가합니다.", + "Add_return_type_0_90063": "반환 형식 '{0}' 추가", + "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035": "이 식에 충족 및 형식 어설션을 추가하여(T를 T로 충족) 형식을 명시적으로 만듭니다.", + "Add_satisfies_and_an_inline_type_assertion_with_0_90068": "'{0}'을(를) 사용하여 충족 및 인라인 형식 어설션 추가", + "Add_to_all_uncalled_decorators_95044": "호출되지 않는 모든 데코레이터에 '()' 추가", + "Add_ts_ignore_to_all_error_messages_95042": "모든 오류 메시지에 '@ts-ignore' 추가", + "Add_undefined_to_a_type_when_accessed_using_an_index_6674": "인덱스를 사용하여 액세스할 때 유형에 'undefined'를 추가합니다.", + "Add_undefined_to_optional_property_type_95169": "선택적 속성 유형에 'undefined' 추가", + "Add_undefined_type_to_all_uninitialized_properties_95029": "초기화되지 않은 모든 속성에 정의되지 않은 형식 추가", + "Add_undefined_type_to_property_0_95018": "'{0}' 속성에 '정의되지 않은' 형식 추가", + "Add_unknown_conversion_for_non_overlapping_types_95069": "겹치지 않는 형식에 대해 'unknown' 변환 추가", + "Add_unknown_to_all_conversions_of_non_overlapping_types_95070": "겹치지 않는 형식의 모든 변환에 'unknown' 추가", + "Add_void_to_Promise_resolved_without_a_value_95143": "값 없이 확인된 Promise에 'void' 추가", + "Add_void_to_all_Promises_resolved_without_a_value_95144": "값 없이 확인된 모든 Promise에 'void' 추가", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json 파일을 추가하면 TypeScript 파일과 JavaScript 파일이 둘 다 포함된 프로젝트를 정리하는 데 도움이 됩니다. 자세한 내용은 https://aka.ms/tsconfig를 참조하세요.", + "All_declarations_of_0_must_have_identical_constraints_2838": "'{0}'의 모든 선언에는 동일한 제약 조건이 있어야 합니다.", + "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}'의 모든 선언에는 동일한 한정자가 있어야 합니다.", + "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}'의 모든 선언에는 동일한 형식 매개 변수가 있어야 합니다.", + "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "추상 메서드의 모든 선언은 연속적이어야 합니다.", + "All_destructured_elements_are_unused_6198": "구조 파괴된 요소가 모두 사용되지 않습니다.", + "All_imports_in_import_declaration_are_unused_6192": "가져오기 선언의 모든 가져오기가 사용되지 않습니다.", + "All_type_parameters_are_unused_6205": "모든 형식 매개 변수가 사용되지 않습니다.", + "All_variables_are_unused_6199": "모든 변수가 사용되지 않습니다.", + "Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these__6600": "JavaScript 파일이 프로그램의 일부가 되도록 허용합니다. 이러한 파일에서 오류를 가져오려면 'checkJS' 옵션을 사용하세요.", + "Allow_accessing_UMD_globals_from_modules_6602": "모듈에서 UMD 전역에 대한 액세스를 허용합니다.", + "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "기본 내보내기가 없는 모듈에서 기본 가져오기를 허용합니다. 여기서는 코드 내보내기에는 영향을 주지 않고 형식 검사만 합니다.", + "Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export_6601": "모듈에 기본 내보내기가 없을 때 'y에서 x 가져오기'를 허용합니다.", + "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639": "tslib에서 도우미 함수를 파일별로 포함하는 대신 프로젝트당 한 번씩 가져오도록 허용합니다.", + "Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noE_6407": "가져오기에서 TypeScript 파일 확장자를 포함하도록 허용합니다. '--moduleResolution bundler'와 '--noEmit' 또는 '--emitDeclarationOnly'를 설정해야 합니다.", + "Allow_javascript_files_to_be_compiled_6102": "Javascript 파일을 컴파일하도록 허용합니다.", + "Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules_6691": "모듈을 확인할 때 여러 폴더가 하나로 처리되도록 허용합니다.", + "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261": "이미 포함된 '{0}' 파일 이름은 '{1}' 파일 이름과 대/소문자만 다릅니다.", + "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "앰비언트 모듈 선언은 상대적 모듈 이름을 지정할 수 없습니다.", + "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "앰비언트 모듈은 다른 모듈 또는 네임스페이스에 중첩될 수 없습니다.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD 모듈에는 여러 이름이 할당될 수 없습니다.", + "An_abstract_accessor_cannot_have_an_implementation_1318": "추상 접근자는 구현이 있을 수 없습니다.", + "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010": "접근성 한정자는 프라이빗 식별자와 함께 사용할 수 없습니다.", + "An_accessor_cannot_have_type_parameters_1094": "접근자에는 형식 매개 변수를 사용할 수 없습니다.", + "An_accessor_property_cannot_be_declared_optional_1276": "'accessor' 속성은 선택 사항으로 선언할 수 없습니다.", + "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "앰비언트 모듈 선언은 파일의 최상위에서만 사용할 수 있습니다.", + "An_argument_for_0_was_not_provided_6210": "'{0}'의 인수가 제공되지 않았습니다.", + "An_argument_matching_this_binding_pattern_was_not_provided_6211": "이 바인딩 패턴과 일치하는 인수가 제공되지 않았습니다.", + "An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356": "산술 피연산자는 'any', 'number', 'bigint' 또는 열거형 형식이어야 합니다.", + "An_arrow_function_cannot_have_a_this_parameter_2730": "화살표 함수에는 'this' 매개 변수를 사용할 수 없습니다.", + "An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_2705": "ES5의 비동기 함수 또는 메서드에 'Promise' 생성자가 필요합니다. 'Promise' 생성자에 대한 선언이 있거나 '--lib' 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "비동기 함수 또는 메서드는 'Promise'를 반환해야 합니다. 'Promise'에 대한 선언이 있거나 '--lib' 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "An_async_iterator_must_have_a_next_method_2519": "비동기 반복기에는 'next()' 메서드가 있어야 합니다.", + "An_element_access_expression_should_take_an_argument_1011": "요소 액세스 식은 인수를 사용해야 합니다.", + "An_enum_member_cannot_be_named_with_a_private_identifier_18024": "프라이빗 식별자를 사용하여 열거형 멤버 이름을 지정할 수 없습니다.", + "An_enum_member_cannot_have_a_numeric_name_2452": "열거형 멤버는 숫자 이름을 가질 수 없습니다.", + "An_enum_member_name_must_be_followed_by_a_or_1357": "열거형 멤버 이름 뒤에는 ',', '=' 또는 '}'가 와야 합니다.", + "An_expanded_version_of_this_information_showing_all_possible_compiler_options_6928": "가능한 모든 컴파일러 옵션을 보여 주는 이 정보의 확장된 버전", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "내보내기 할당은 다른 내보낸 요소가 있는 모듈에서 사용될 수 없습니다.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "내보내기 할당은 네임스페이스에서 사용될 수 없습니다.", + "An_export_assignment_cannot_have_modifiers_1120": "내보내기 할당에는 한정자를 사용할 수 없습니다.", + "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231": "내보내기 할당은 파일 또는 모듈 선언의 최상위 수준에 있어야 합니다.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474": "내보내기 선언은 모듈의 최상위 수준에서만 사용할 수 있습니다.", + "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233": "내보내기 선언은 네임스페이스 또는 모듈의 최상위 수준에서만 사용할 수 있습니다.", + "An_export_declaration_cannot_have_modifiers_1193": "내보내기 선언에는 한정자를 사용할 수 없습니다.", + "An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolve_1283": "'verbatimModuleSyntax'를 사용하는 경우 'export =' 선언은 실제 값을 참조해야 하지만 '{0}'은(는) 형식 전용 선언으로 확인됩니다.", + "An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers__1282": "'verbatimModuleSyntax'를 사용하는 경우 'export =' 선언은 값을 참조해야 하지만 '{0}'은(는) 형식만 참조합니다.", + "An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_1285": "'verbatimModuleSyntax'가 사용하도록 설정되어 있지만 '{0}'이(가) 형식 전용 선언으로 확인되는 경우 'export default'는 실제 값을 참조해야 합니다.", + "An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_1284": "'verbatimModuleSyntax'가 사용하도록 설정된 경우 'export default'는 값을 참조해야 하지만 '{0}'은(는) 형식만 참조합니다.", + "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345": "'void' 형식 식의 truthiness를 테스트할 수 없습니다.", + "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "확장된 유니코드 이스케이프 값은 0x0과 0x10FFFF(포함) 사이여야 합니다.", + "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351": "식별자 또는 키워드는 숫자 리터럴 바로 뒤에 올 수 없습니다.", + "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "앰비언트 컨텍스트에서는 구현을 선언할 수 없습니다.", + "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "가져오기 별칭은 '내보내기 형식'을 사용하여 내보낸 선언을 참조할 수 없습니다.", + "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "가져오기 별칭은 '가져오기 형식'을 사용하여 가져온 선언을 참조할 수 없습니다.", + "An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabl_1288": "'verbatimModuleSyntax'를 사용하도록 설정한 경우 가져오기 별칭을 형식 또는 형식 전용 선언으로 확인할 수 없습니다.", + "An_import_alias_cannot_use_import_type_1392": "가져오기 별칭은 'import type'을 사용할 수 없습니다.", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473": "가져오기 선언은 모듈의 최상위 수준에서만 사용할 수 있습니다.", + "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232": "가져오기 선언은 네임스페이스 또는 모듈의 최상위 수준에서만 사용할 수 있습니다.", + "An_import_declaration_cannot_have_modifiers_1191": "가져오기 선언에는 한정자를 사용할 수 없습니다.", + "An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled_5097": "가져오기 경로는 'allowImportingTsExtensions'가 사용하도록 설정된 경우에만 '{0}' 확장으로 끝날 수 있습니다.", + "An_index_signature_cannot_have_a_rest_parameter_1017": "인덱스 시그니처에는 rest 매개 변수를 사용할 수 없습니다.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "인덱스 시그니처에는 후행 쉼표를 사용할 수 없습니다.", + "An_index_signature_must_have_a_type_annotation_1021": "인덱스 시그니처에는 형식 주석을 사용할 수 없습니다.", + "An_index_signature_must_have_exactly_one_parameter_1096": "인덱스 시그니처에는 한 개의 매개 변수만 사용할 수 있습니다.", + "An_index_signature_parameter_cannot_have_a_question_mark_1019": "인덱스 시그니처 매개 변수에는 물음표를 사용할 수 없습니다.", + "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "인덱스 시그니처 매개 변수에는 액세스 가능성 한정자를 사용할 수 없습니다.", + "An_index_signature_parameter_cannot_have_an_initializer_1020": "인덱스 시그니처 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", + "An_index_signature_parameter_must_have_a_type_annotation_1022": "인덱스 시그니처 매개 변수에는 형식 주석을 사용할 수 없습니다.", + "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "인덱스 시그니처 매개 변수 형식은 리터럴 유형이나 제네릭 형식일 수 없습니다. 대신 매핑된 개체 형식을 사용하세요.", + "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "인덱스 시그니처 매개 변수 형식은 'string', 'number', 'symbol' 또는 템플릿 리터럴 형식이어야 합니다.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "인스턴스화 식 뒤에 속성 액세스가 있을 수 없습니다.", + "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "인터페이스는 선택적 형식 인수가 포함된 식별자/정규화된 이름만 확장할 수 있습니다.", + "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "인터페이스는 개체 형식 또는 정적으로 알려진 멤버가 포함된 개체 형식의 교집합만 확장할 수 있습니다.", + "An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types_2840": "인터페이스는 '{0}' 같은 기본 형식을 확장할 수 없습니다. 다른 명명된 개체 형식만 확장할 수 있습니다.", + "An_interface_property_cannot_have_an_initializer_1246": "인터페이스 속성에는 이니셜라이저를 사용할 수 없습니다.", + "An_iterator_must_have_a_next_method_2489": "반복기에는 'next()' 메서드가 있어야 합니다.", + "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "@jsx pragma를 JSX 조각과 함께 사용하는 경우에는 @jsxFrag pragma가 필요합니다.", + "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118": "개체 리터럴에 이름이 같은 여러 개의 get/set 접근자를 사용할 수 없습니다.", + "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117": "개체 리터럴은 이름이 같은 여러 속성을 가질 수 없습니다.", + "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119": "개체 리터럴에 이름이 같은 속성과 접근자를 사용할 수 없습니다.", + "An_object_member_cannot_be_declared_optional_1162": "개체 멤버는 선택적으로 선언될 수 없습니다.", + "An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_han_2861": "개체의 '[Symbol.hasInstance]' 메서드는 'instanceof' 식의 오른쪽에서 사용할 부울 값을 반환해야 합니다.", + "An_optional_chain_cannot_contain_private_identifiers_18030": "선택적 체인에는 프라이빗 식별자를 사용할 수 없습니다.", + "An_optional_element_cannot_follow_a_rest_element_1266": "선택적 요소는 rest 요소 뒤에 올 수 없습니다.", + "An_outer_value_of_this_is_shadowed_by_this_container_2738": "'this'의 외부 값은 이 컨테이너에서 섀도 처리됩니다.", + "An_overload_signature_cannot_be_declared_as_a_generator_1222": "오버로드 시그니처는 생성기로 선언할 수 없습니다.", + "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "지수 식의 왼쪽에는 '{0}' 연산자가 있는 단항 식을 사용할 수 없습니다. 식을 괄호로 묶는 것이 좋습니다.", + "Annotate_everything_with_types_from_JSDoc_95043": "JSDoc의 형식을 사용하여 모든 항목에 주석 달기", + "Annotate_types_of_properties_expando_function_in_a_namespace_90071": "네임스페이스의 속성 expando 함수 형식에 주석 달기", + "Annotate_with_type_from_JSDoc_95009": "JSDoc의 형식을 사용하여 주석 추가", + "Another_export_default_is_here_2753": "다른 내보내기 기본값은 여기에 있습니다.", + "Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_t_1528": "단일 문자 이상과 일치할 수 있는 유니코드 속성은 유니코드 집합(v) 플래그가 설정된 경우에만 사용할 수 있습니다.", + "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518": "단일 문자보다 더 일치할 수 있는 모든 항목은 부정된 문자 클래스 내에서 유효하지 않습니다.", + "Are_you_missing_a_semicolon_2734": "세미콜론이 없습니까?", + "Argument_expression_expected_1135": "인수 식이 필요합니다.", + "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' 옵션의 인수는 {1}이어야(여야) 합니다.", + "Argument_of_dynamic_import_cannot_be_spread_element_1325": "동적 가져오기의 인수는 spread 요소일 수 없습니다.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "'{0}' 형식의 인수는 '{1}' 형식의 매개 변수에 할당될 수 없습니다.", + "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379": "'{0}' 유형의 인수는 'exactOptionalPropertyTypes: true'가 있는 '{1}' 유형의 매개 변수에 할당할 수 없습니다. 대상 속성의 유형에 'undefined'를 추가하는 것을 고려하세요.", + "Arguments_for_the_rest_parameter_0_were_not_provided_6236": "REST 매개 변수 '{0}'에 대한 인수가 제공되지 않았습니다.", + "Array_element_destructuring_pattern_expected_1181": "배열 요소 구조 파괴 패턴이 필요합니다.", + "Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations_9018": "분산 요소가 있는 배열은 --isolatedDeclarations로 유추할 수 없습니다.", + "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775": "어설션에서 호출 대상의 모든 이름은 명시적 형식 주석을 사용하여 선언해야 합니다.", + "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776": "어설션에서 호출 대상은 식별자 또는 정규화된 이름이어야 합니다.", + "Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations__9023": "함수를 선언하지 않고 함수에 속성을 할당하는 것은 --isolatedDeclarations에서 지원되지 않습니다. 이 함수에 할당된 속성에 대한 명시적 선언을 추가합니다.", + "Asterisk_Slash_expected_1010": "'*/'가 필요합니다.", + "At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9009": "하나 이상의 접근자에 --isolatedDeclarations를 사용하는 명시적 형식 주석이 있어야 합니다.", + "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "전역 범위에 대한 확대는 외부 모듈 또는 앰비언트 모듈 선언에만 직접 중첩될 수 있습니다.", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "전역 범위에 대한 확대는 이미 존재하는 앰비언트 컨텍스트에 표시되지 않는 한 'declare' 한정자를 포함해야 합니다.", + "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "프로젝트 '{0}'에서 입력에 대한 자동 검색을 사용하도록 설정되었습니다. '{2}' 캐시 위치를 사용하여 모듈 '{1}'에 대해 추가 해결 패스를 실행합니다.", + "BUILD_OPTIONS_6919": "빌드 옵션", + "Backwards_Compatibility_6253": "이전 버전과의 호환성", + "Base_class_expressions_cannot_reference_class_type_parameters_2562": "기본 클래스 식에서 클래스 형식 매개 변수를 참조할 수 없습니다.", + "Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509": "기본 생성자 반환 형식 '{0}'은(는) 개체 형식 또는 정적으로 알려진 멤버가 포함된 개체 형식의 교집합이 아닙니다.", + "Base_constructors_must_all_have_the_same_return_type_2510": "기본 생성자는 모두 반환 형식이 같아야 합니다.", + "Base_directory_to_resolve_non_absolute_module_names_6083": "비추상 모듈 이름을 확인할 기본 디렉터리입니다.", + "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737": "ES2020 미만을 대상으로 할 경우 bigint 리터럴을 사용할 수 없습니다.", + "Binary_digit_expected_1177": "이진수가 있어야 합니다.", + "Binding_element_0_implicitly_has_an_1_type_7031": "바인딩 요소 '{0}'에 암시적으로 '{1}' 형식이 있습니다.", + "Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations_9019": "바인딩 요소는 --isolatedDeclarations를 사용하여 직접 내보낼 수 없습니다.", + "Block_scoped_variable_0_used_before_its_declaration_2448": "선언 전에 사용된 블록 범위 변수 '{0}'입니다.", + "Build_a_composite_project_in_the_working_directory_6925": "작업 디렉터리에서 복합 프로젝트를 빌드합니다.", + "Build_all_projects_including_those_that_appear_to_be_up_to_date_6636": "최신으로 보이는 프로젝트를 포함하여 모든 프로젝트를 빌드합니다.", + "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364": "최신 상태가 아닌 경우, 하나 이상의 프로젝트 및 해당 종속성 빌드", + "Build_option_0_requires_a_value_of_type_1_5073": "빌드 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", + "Building_project_0_6358": "'{0}' 프로젝트를 빌드하는 중...", + "Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any_6720": "기본 제공 반복기는 'any' 대신 'undefined'의 'TReturn' 형식으로 인스턴스화됩니다.", + "COMMAND_LINE_FLAGS_6921": "명령줄 플래그", + "COMMON_COMMANDS_6916": "일반 명령", + "COMMON_COMPILER_OPTIONS_6920": "일반 컴파일러 옵션", + "Call_decorator_expression_90028": "데코레이터 식 호출", + "Call_signature_return_types_0_and_1_are_incompatible_2202": "호출 시그니처 반환 형식 '{0}' 및 '{1}'이(가) 호환되지 않습니다.", + "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "반환 형식 주석이 없는 호출 시그니처에는 암시적으로 'any' 반환 형식이 포함됩니다.", + "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204": "인수가 없는 호출 시그니처의 반환 형식 '{0}' 및 '{1}'이(가) 호환되지 않습니다.", + "Can_only_convert_logical_AND_access_chains_95142": "논리적 AND 액세스 체인만 변환할 수 있습니다.", + "Can_only_convert_named_export_95164": "명명된 내보내기만 변환할 수 있습니다.", + "Can_only_convert_property_with_modifier_95137": "한정자만 사용하여 속성을 변환할 수 있습니다.", + "Can_only_convert_string_concatenations_and_string_literals_95154": "문자열 연결 및 문자열 리터럴만 변환할 수 있습니다.", + "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}'이(가) 네임스페이스가 아니라 형식이므로 '{0}.{1}'에 액세스할 수 없습니다. '{0}'에서 '{0}[\"{1}\"]'과(와) 함께 '{1}' 속성의 형식을 검색하려고 했나요?", + "Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead_1281": "'{1}'을(를) 사용하도록 설정한 경우 한정 없이 다른 파일에서 '{0}'에 액세스할 수 없습니다. 대신 '{2}'을(를) 사용하세요.", + "Cannot_access_ambient_const_enums_when_0_is_enabled_2748": "'{0}'이(가) 사용하도록 설정된 경우 앰비언트 const 열거형에 액세스할 수 없습니다.", + "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672": "'{0}' 생성자 형식을 '{1}' 생성자 형식에 할당할 수 없습니다.", + "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517": "추상 생성자 형식을 비추상 생성자 형식에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_a_class_2629": "클래스이므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_a_constant_2588": "상수이므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_a_function_2630": "함수이므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_a_namespace_2631": "네임스페이스이므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_a_read_only_property_2540": "읽기 전용 속성이므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_an_enum_2628": "열거형이므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_an_import_2632": "가져오기이므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_0_because_it_is_not_a_variable_2539": "변수가 아니므로 '{0}'에 할당할 수 없습니다.", + "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803": "프라이빗 메서드 '{0}'에 할당할 수 없습니다. 프라이빗 메서드에는 쓸 수 없습니다.", + "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671": "'{0}' 모듈은 모듈이 아닌 엔터티로 확인되므로 확대할 수 없습니다.", + "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649": "모듈이 아닌 엔터티로 확인되기 때문에 값 내보내기로 모듈 '{0}'을(를) 확대할 수 없습니다.", + "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131": "'--module' 플래그가 'amd' 또는 'system'이 아닌 경우 '{0}' 옵션을 사용하여 모듈을 컴파일할 수 없습니다.", + "Cannot_create_an_instance_of_an_abstract_class_2511": "추상 클래스의 인스턴스를 만들 수 없습니다.", + "Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_co_2766": "반복기의 'next' 메서드에 '{1}' 형식이 필요하지만 포함 생성기는 항상 '{0}'을(를) 전송하므로 값에 반복을 위임할 수 없습니다.", + "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661": "'{0}'을(를) 내보낼 수 없습니다. 지역 선언만 모듈에서 내보낼 수 있습니다.", + "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675": "'{0}' 클래스를 확장할 수 없습니다. 클래스 생성자가 private로 표시되어 있습니다.", + "Cannot_extend_an_interface_0_Did_you_mean_implements_2689": "인터페이스 '{0}'을(를) 확장할 수 없습니다. 'implements'를 확장하시겠습니까?", + "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081": "현재 디렉터리에서 tsconfig.json 파일을 찾을 수 없습니다. {0}.", + "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057": "지정된 디렉터리에서 tsconfig.json 파일을 찾을 수 없습니다. '{0}'.", + "Cannot_find_global_type_0_2318": "전역 형식 '{0}'을(를) 찾을 수 없습니다.", + "Cannot_find_global_value_0_2468": "전역 값 '{0}'을(를) 찾을 수 없습니다.", + "Cannot_find_lib_definition_for_0_2726": "'{0}'에 대한 라이브러리 정의를 찾을 수 없습니다.", + "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727": "'{0}'에 대한 라이브러리 정의를 찾을 수 없습니다. '{1}'이(가) 아닌지 확인하세요.", + "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732": "'{0}' 모듈을 찾을 수 없습니다. '--resolveJsonModule'을 사용하여 '. json' 확장명이 포함된 모듈을 가져오는 것이 좋습니다.", + "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_t_2792": "'{0}' 모듈을 찾을 수 없습니다. 'moduleResolution' 옵션을 'nodenext'로 설정하거나 'paths' 옵션에 별칭을 추가하려고 하셨나요?", + "Cannot_find_module_0_or_its_corresponding_type_declarations_2307": "'{0}' 모듈 또는 해당 형식 선언을 찾을 수 없습니다.", + "Cannot_find_name_0_2304": "'{0}' 이름을 찾을 수 없습니다.", + "Cannot_find_name_0_Did_you_mean_1_2552": "'{0}' 이름을 찾을 수 없습니다. '{1}'을(를) 사용하시겠습니까?", + "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663": "'{0}' 이름을 찾을 수 없습니다. 인스턴스 멤버 'this.{0}'을(를) 사용하시겠습니까?", + "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "'{0}' 이름을 찾을 수 없습니다. 정적 멤버 '{1}.{0}'을(를) 사용하시겠습니까?", + "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311": "이름 '{0}' 찾을 수 없습니다. 비동기 함수에 쓰려고 했나요?", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583": "'{0}' 이름을 찾을 수 없습니다. 대상 라이브러리를 변경하려는 경우 'lib' 컴파일러 옵션을 '{1}' 이상으로 변경해 보세요.", + "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584": "'{0}' 이름을 찾을 수 없습니다. 대상 라이브러리를 변경하려는 경우 'dom'을 포함하도록 'lib' 컴파일러 옵션을 변경해 보세요.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2867": "'{0}' 이름을 찾을 수 없습니다. Bun에 대한 형식 정의를 설치해야 하나요? 'npm i --save-dev @types/bun'을 사용해 보세요.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2868": "'{0}' 이름을 찾을 수 없습니다. Bun에 대한 형식 정의를 설치해야 하나요? 'npm i --save-dev @types/bun'을 시도한 다음 tsconfig의 형식 필드에 'bun'을 추가합니다.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582": "'{0}' 이름을 찾을 수 없습니다. 테스트 실행기의 형식 정의를 설치하려는 경우 'npm i --save-dev @types/jest' 또는 'npm i --save-dev @types/mocha'를 시도합니다.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593": "'{0}' 이름을 찾을 수 없습니다. 테스트 실행기의 형식 정의를 설치하려는 경우 'npm i --save-dev @types/jest' 또는 'npm i --save-dev @types/mocha'를 시도한 다음, tsconfig의 형식 필드에 'jest' 또는 'mocha'를 추가하세요.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581": "'{0}' 이름을 찾을 수 없습니다. jQuery의 형식 정의를 설치하려는 경우 'npm i --save-dev @types/jquery'를 시도합니다.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592": "'{0}' 이름을 찾을 수 없습니다. jQuery의 형식 정의를 설치하려는 경우 'npm i --save-dev @types/jquery'를 시도한 다음, tsconfig의 형식 필드에 'jquery'를 추가하세요.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "'{0}' 이름을 찾을 수 없습니다. 노드의 형식 정의를 설치하려는 경우 'npm i --save-dev @types/node'를 시도합니다.", + "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "'{0}' 이름을 찾을 수 없습니다. 노드의 형식 정의를 설치하려는 경우 'npm i --save-dev @types/node'를 시도한 다음, tsconfig의 형식 필드에 'node'를 추가하세요.", + "Cannot_find_namespace_0_2503": "'{0}' 네임스페이스를 찾을 수 없습니다.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "네임스페이스 '{0}'을(를) 찾을 수 없습니다. '{1}'을(를) 의미했나요?", + "Cannot_find_parameter_0_1225": "'{0}' 매개 변수를 찾을 수 없습니다.", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "입력 파일의 공용 하위 디렉터리 경로를 찾을 수 없습니다.", + "Cannot_find_type_definition_file_for_0_2688": "'{0}'에 대한 형식 정의 파일을 찾을 수 없습니다.", + "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "형식 선언 파일을 가져올 수 없습니다. '{1}' 대신 '{0}'을(를) 가져오세요.", + "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "블록 범위 선언 '{1}'과(와) 동일한 범위 내에서 외부 범위 변수 '{0}'을(를) 초기화할 수 없습니다.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null'일 수 있는 개체를 호출할 수 없습니다.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null'이거나 '정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring__2765": "반복기의 'next' 메서드에 '{1}' 형식이 필요하지만 배열 구조 파괴는 항상 '{0}'을(를) 전송하므로 값을 반복할 수 없습니다.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "반복기의 'next' 메서드에 '{1}' 형식이 필요하지만 배열 spread는 항상 '{0}'을(를) 전송하므로 값을 반복할 수 없습니다.", + "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "반복기의 'next' 메서드에 '{1}' 형식이 필요하지만 for-of는 항상 '{0}'을(를) 전송하므로 값을 반복할 수 없습니다.", + "Cannot_move_statements_to_the_selected_file_95183": "문을 선택한 파일로 이동할 수 없습니다.", + "Cannot_move_to_file_selected_file_is_invalid_95179": "파일로 이동할 수 없습니다. 선택한 파일이 유효하지 않습니다.", + "Cannot_read_file_0_5083": "'{0}' 파일을 읽을 수 없습니다.", + "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", + "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", + "Cannot_redeclare_exported_variable_0_2323": "내보낸 변수 '{0}'을(를) 다시 선언할 수 없습니다.", + "Cannot_redeclare_identifier_0_in_catch_clause_2492": "catch 절에서 식별자 '{0}'을(를) 다시 선언할 수 없습니다.", + "Cannot_start_a_function_call_in_a_type_annotation_1441": "형식 주석에서 함수 호출을 시작할 수 없습니다.", + "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004": "'--jsx' 플래그를 제공하지 않으면 JSX를 사용할 수 없습니다.", + "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled_1269": "'{0}'을(를) 사용하도록 설정한 경우 형식 또는 형식 전용 네임스페이스에서 'export import'를 사용할 수 없습니다.", + "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148": "'--module'이 'none'인 경우 가져오기, 내보내기 또는 모듈 확대를 사용할 수 없습니다.", + "Cannot_use_namespace_0_as_a_type_2709": "'{0}' 네임스페이스를 형식으로 사용할 수 없습니다.", + "Cannot_use_namespace_0_as_a_value_2708": "'{0}' 네임스페이스를 값으로 사용할 수 없습니다.", + "Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class_2816": "데코레이팅된 클래스의 정적 속성 이니셜라이저에서는 'this'를 사용할 수 없습니다.", + "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377": "참조된 프로젝트 '{1}'에서 생성된 '.tsbuildinfo' 파일을 덮어쓰므로 '{0}' 파일을 쓸 수 없습니다.", + "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056": "'{0}' 파일은 여러 입력 파일로 덮어쓰이므로 쓸 수 없습니다.", + "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "'{0}' 파일은 입력 파일을 덮어쓰므로 쓸 수 없습니다.", + "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 절 변수에 이니셜라이저를 사용할 수 없습니다.", + "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196": "지정한 경우 catch 절 변수 형식 주석은 'any' 또는 'unknown'이어야 합니다.", + "Change_0_to_1_90014": "'{0}'을(를) '{1}'(으)로 변경", + "Change_all_extended_interfaces_to_implements_95038": "확장된 모든 인터페이스를 'implements'로 변경", + "Change_all_jsdoc_style_types_to_TypeScript_95030": "모든 jsdoc-style 형식을 TypeScript로 변경", + "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031": "모든 jsdoc-style 형식을 TypeScript로 변경(그리고 nullable 형식에 '| undefined' 추가)", + "Change_extends_to_implements_90003": "'extends'를 'implements'로 변경", + "Change_spelling_to_0_90022": "맞춤법을 '{0}'(으)로 변경", + "Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor_6700": "선언되었지만 생성자에 설정되지 않은 클래스 속성을 확인합니다.", + "Check_side_effect_imports_6806": "부작용 가져오기를 확인합니다.", + "Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function_6697": "'bind', 'call' 및 'apply' 메서드에 대한 인수가 원래 함수와 일치하는지 확인하세요.", + "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}'이(가) '{1}' - '{2}'에 대해 일치하는 가장 긴 접두사인지 확인하는 중입니다.", + "Circular_definition_of_import_alias_0_2303": "가져오기 별칭 '{0}'의 순환 정의입니다.", + "Circularity_detected_while_resolving_configuration_Colon_0_18000": "구성을 확인하는 동안 순환이 검색되었습니다. {0}", + "Circularity_originates_in_type_at_this_location_2751": "순환이 이 위치의 형식에서 시작됩니다.", + "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426": "'{0}' 클래스는 인스턴스 멤버 접근자 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 접근자를 인스턴스 멤버 함수로 정의합니다.", + "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423": "'{0}' 클래스가 인스턴스 멤버 함수 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 함수를 인스턴스 멤버 접근자로 정의합니다.", + "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "'{0}' 클래스가 인스턴스 멤버 속성 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 속성을 인스턴스 멤버 함수로 정의합니다.", + "Class_0_incorrectly_extends_base_class_1_2415": "'{0}' 클래스가 기본 클래스 '{1}'을(를) 잘못 확장합니다.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "'{0}' 클래스가 '{1}' 클래스를 잘못 구현합니다. '{1}'을(를) 확장하고 이 클래스의 멤버를 하위 클래스로 상속하시겠습니까?", + "Class_0_incorrectly_implements_interface_1_2420": "'{0}' 클래스가 '{1}' 인터페이스를 잘못 구현합니다.", + "Class_0_used_before_its_declaration_2449": "선언 전에 사용된 '{0}' 클래스입니다.", + "Class_constructor_may_not_be_a_generator_1368": "클래스 생성자는 생성기가 아닐 수 있습니다.", + "Class_constructor_may_not_be_an_accessor_1341": "클래스 생성자는 접근자가 아닐 수 있습니다.", + "Class_declaration_cannot_implement_overload_list_for_0_2813": "클래스 선언에서 '{0}'에 대한 오버로드 목록을 구현할 수 없습니다.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "클래스 선언은 '@augments' 또는 '@extends' 태그를 둘 이상 가질 수 없습니다.", + "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "클래스 데코레이터는 정적 프라이빗 식별자와 함께 사용할 수 없습니다. 실험적 데코레이터를 제거하는 것이 좋습니다.", + "Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super_2855": "부모 클래스에서 정의한 '{0}' 클래스 필드는 super를 통해 자식 클래스에서 액세스할 수 없습니다.", + "Class_name_cannot_be_0_2414": "클래스 이름은 '{0}'일 수 없습니다.", + "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725": "{0} 모듈을 사용하는 ES5를 대상으로 하는 경우 클래스 이름은 'Object'일 수 없습니다.", + "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "클래스 정적 측면 '{0}'이(가) 기본 클래스 정적 측면 '{1}'을(를) 잘못 확장합니다.", + "Classes_can_only_extend_a_single_class_1174": "클래스는 단일 클래스만 확장할 수 있습니다.", + "Classes_may_not_have_a_field_named_constructor_18006": "클래스에는 'constructor' 필드를 사용할 수 없습니다.", + "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210": "클래스에 포함된 코드는 '{0}'의 사용을 허용하지 않는 JavaScript의 strict 모드로 평가됩니다. 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode를 참조하세요.", + "Command_line_Options_6171": "명령줄 옵션", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "구성 파일에 대한 경로 또는 'tsconfig.json'이 포함된 폴더에 대한 경로를 고려하여 프로젝트를 컴파일합니다.", + "Compiler_Diagnostics_6251": "컴파일러 진단", + "Compiler_option_0_cannot_be_given_an_empty_string_18051": "'{0}' 컴파일러 옵션에는 빈 문자열을 지정할 수 없습니다.", + "Compiler_option_0_expects_an_argument_6044": "컴파일러 옵션 '{0}'에는 인수가 필요합니다.", + "Compiler_option_0_may_not_be_used_with_build_5094": "컴파일러 옵션 '--{0}'은(는) '-빌드'에서 사용되지 않을 수 있습니다.", + "Compiler_option_0_may_only_be_used_with_build_5093": "컴파일러 옵션 '--{0}'은(는) '-빌드'에서만 사용할 수 있습니다.", + "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124": "값 '{1}'의 컴파일러 옵션 '{0}'이(가) 불안정합니다. 야간 TypeScript를 사용하여 이 오류를 차단하세요. 'npm install -D typescript@next'로 업데이트해 보세요.", + "Compiler_option_0_requires_a_value_of_type_1_5024": "컴파일러 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "컴파일러는 프라이빗 식별자 하위 수준을 내보낼 때 '{0}' 이름을 예약합니다.", + "Compiles_the_TypeScript_project_located_at_the_specified_path_6927": "지정된 경로에 있는 TypeScript 프로젝트를 컴파일합니다.", + "Compiles_the_current_project_tsconfig_json_in_the_working_directory_6923": "현재 프로젝트(작업 디렉터리의 tsconfig.json)를 컴파일합니다.", + "Compiles_the_current_project_with_additional_settings_6929": "추가 설정을 사용하여 현재 프로젝트를 컴파일합니다.", + "Completeness_6257": "완성도", + "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 비활성화할 수 없습니다.", + "Composite_projects_may_not_disable_incremental_compilation_6379": "복합 프로젝트는 증분 컴파일을 비활성화할 수 없습니다.", + "Computed_from_the_list_of_input_files_6911": "입력 파일 목록에서 컴퓨팅됨", + "Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedD_9014": "계산된 속성은 --isolatedDeclarations가 있는 숫자 또는 문자열 리터럴, 변수 또는 점선 식이어야 합니다.", + "Computed_property_names_are_not_allowed_in_enums_1164": "컴퓨팅된 속성 이름은 열거형에 사용할 수 없습니다.", + "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038": "클래스 또는 개체 리터럴의 계산된 속성 이름은 --isolatedDeclarations로 유추할 수 없습니다.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "계산된 값은 문자열 값 멤버가 포함된 열거형에서 허용되지 않습니다.", + "Concatenate_and_emit_output_to_single_file_6001": "출력을 연결하고 단일 파일로 내보냅니다.", + "Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports_6410": "가져오기를 확인할 때 확인자별 기본값 외에 설정할 조건입니다.", + "Conflicts_are_in_this_file_6201": "이 파일에 충돌이 있습니다.", + "Consider_adding_a_declare_modifier_to_this_class_6506": "이 클래스에 'declare' 한정자를 추가하는 것이 좋습니다.", + "Construct_signature_return_types_0_and_1_are_incompatible_2203": "구문 시그니처 반환 형식 '{0}' 및 '{1}'이(가) 호환되지 않습니다.", + "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "반환 형식 주석이 없는 구문 시그니처에는 암시적으로 'any' 반환 형식이 포함됩니다.", + "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205": "인수가 없는 구문 시그니처의 반환 형식 '{0}' 및 '{1}'이(가) 호환되지 않습니다.", + "Constructor_implementation_is_missing_2390": "생성자 구현이 없습니다.", + "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "'{0}' 클래스의 생성자는 private이며 클래스 선언 내에서만 액세스할 수 있습니다.", + "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674": "'{0}' 클래스의 생성자는 protected이며 클래스 선언 내에서만 액세스할 수 있습니다.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386": "공용 구조체 형식에 사용되는 경우 생성자 형식 표기법을 괄호로 묶어야 합니다.", + "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388": "교집합 형식에 사용되는 경우 생성자 형식 표기법을 괄호로 묶어야 합니다.", + "Constructors_for_derived_classes_must_contain_a_super_call_2377": "파생 클래스의 생성자는 'super' 호출을 포함해야 합니다.", + "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "포함 파일이 지정되지 않았고 루트 디렉터리를 확인할 수 없어 'node_modules' 폴더 조회를 건너뜁니다.", + "Containing_function_is_not_an_arrow_function_95128": "포함 함수가 화살표 함수가 아닙니다.", + "Control_what_method_is_used_to_detect_module_format_JS_files_1475": "모듈 형식의 JS 파일을 감지하는 데 사용되는 방법을 제어합니다.", + "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352": "'{0}' 형식을 '{1}' 형식으로 변환한 작업은 실수일 수 있습니다. 두 형식이 서로 충분히 겹치지 않기 때문입니다. 의도적으로 변환한 경우에는 먼저 'unknown'으로 식을 변환합니다.", + "Convert_0_to_1_in_0_95003": "'{0}'을(를) '{0}의 {1}'(으)로 변환", + "Convert_0_to_mapped_object_type_95055": "'{0}'을(를) 매핑된 개체 형식으로 변환", + "Convert_all_const_to_let_95102": "모든 'const'를 'let'으로 변환", + "Convert_all_constructor_functions_to_classes_95045": "모든 생성자 함수를 클래스로 변환", + "Convert_all_invalid_characters_to_HTML_entity_code_95101": "모든 잘못된 문자를 HTML 엔터티 코드로 변환", + "Convert_all_re_exported_types_to_type_only_exports_1365": "다시 내보낸 모든 형식을 형식 전용 내보내기로 변환", + "Convert_all_require_to_import_95048": "모든 'require'를 'import'로 변환", + "Convert_all_to_async_functions_95066": "모두 비동기 함수로 변환", + "Convert_all_to_bigint_numeric_literals_95092": "모두 bigint 숫자 리터럴로 변환", + "Convert_all_to_default_imports_95035": "모든 항목을 기본 가져오기로 변환", + "Convert_all_type_literals_to_mapped_type_95021": "모든 형식 리터럴을 매핑된 형식으로 변환", + "Convert_all_typedef_to_TypeScript_types_95177": "모든 typedef를 TypeScript 형식으로 변환합니다.", + "Convert_arrow_function_or_function_expression_95122": "화살표 함수 또는 함수 식 변환", + "Convert_const_to_let_95093": "'const'를 'let'으로 변환", + "Convert_default_export_to_named_export_95061": "기본 내보내기를 명명된 내보내기로 변환", + "Convert_function_declaration_0_to_arrow_function_95106": "함수 선언 '{0}'을(를) 화살표 함수로 변환", + "Convert_function_expression_0_to_arrow_function_95105": "함수 식 '{0}'을(를) 화살표 함수로 변환", + "Convert_function_to_an_ES2015_class_95001": "함수를 ES2015 클래스로 변환", + "Convert_invalid_character_to_its_html_entity_code_95100": "잘못된 문자를 html 엔터티 코드로 변환", + "Convert_named_export_to_default_export_95062": "명명된 내보내기를 기본 내보내기로 변환", + "Convert_named_imports_to_default_import_95170": "명명된 가져오기를 기본 가져오기로 변환", + "Convert_named_imports_to_namespace_import_95057": "명명된 가져오기를 네임스페이스 가져오기로 변환", + "Convert_namespace_import_to_named_imports_95056": "네임스페이스 가져오기를 명명된 가져오기로 변환", + "Convert_overload_list_to_single_signature_95118": "오버로드 목록을 단일 시그니처로 변환", + "Convert_parameters_to_destructured_object_95075": "매개 변수를 구조 파괴 개체로 변환", + "Convert_require_to_import_95047": "'require'를 'import'로 변환", + "Convert_to_ES_module_95017": "ES 모듈로 변환", + "Convert_to_a_bigint_numeric_literal_95091": "bigint 숫자 리터럴로 변환", + "Convert_to_anonymous_function_95123": "익명 함수로 변환", + "Convert_to_arrow_function_95125": "화살표 함수로 변환", + "Convert_to_async_function_95065": "비동기 함수로 변환", + "Convert_to_default_import_95013": "기본 가져오기로 변환", + "Convert_to_named_function_95124": "명명된 함수로 변환", + "Convert_to_optional_chain_expression_95139": "선택적 체인 식으로 변환합니다.", + "Convert_to_template_string_95096": "템플릿 문자열로 변환", + "Convert_to_type_only_export_1364": "형식 전용 내보내기로 변환", + "Convert_typedef_to_TypeScript_type_95176": "typedef를 TypeScript 형식으로 변환합니다.", + "Corrupted_locale_file_0_6051": "로캘 파일 {0}이(가) 손상되었습니다.", + "Could_not_convert_to_anonymous_function_95153": "익명 함수로 변환할 수 없습니다.", + "Could_not_convert_to_arrow_function_95151": "화살표 함수로 변환할 수 없습니다.", + "Could_not_convert_to_named_function_95152": "명명된 함수로 변환할 수 없습니다.", + "Could_not_determine_function_return_type_95150": "함수 반환 형식을 확인할 수 없습니다.", + "Could_not_find_a_containing_arrow_function_95127": "포함하는 화살표 함수를 찾을 수 없습니다.", + "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "모듈 '{0}'에 대한 선언 파일을 찾을 수 없습니다. '{1}'에는 암시적으로 'any' 형식이 포함됩니다.", + "Could_not_find_convertible_access_expression_95140": "변환 가능한 액세스 식을 찾을 수 없습니다.", + "Could_not_find_export_statement_95129": "export 문을 찾을 수 없습니다.", + "Could_not_find_import_clause_95131": "import 절을 찾을 수 없습니다.", + "Could_not_find_matching_access_expressions_95141": "일치하는 액세스 식을 찾을 수 없습니다.", + "Could_not_find_name_0_Did_you_mean_1_2570": "'{0}' 이름을 찾을 수 없습니다. '{1}'을(를) 사용하시겠습니까?", + "Could_not_find_namespace_import_or_named_imports_95132": "네임스페이스 가져오기 또는 명명된 가져오기를 찾을 수 없습니다.", + "Could_not_find_property_for_which_to_generate_accessor_95135": "접근자를 생성할 속성을 찾을 수 없습니다.", + "Could_not_find_variable_to_inline_95185": "인라인할 변수를 찾을 수 없습니다.", + "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "{1} 확장이 포함된 '{0}' 경로를 확인할 수 없습니다.", + "Could_not_write_file_0_Colon_1_5033": "'{0}' 파일을 쓸 수 없습니다. '{1}'.", + "Create_source_map_files_for_emitted_JavaScript_files_6694": "내보낸 JavaScript 파일의 소스 맵 파일을 만듭니다.", + "Create_sourcemaps_for_d_ts_files_6614": "d.ts 파일의 sourcemap을 만듭니다.", + "Creates_a_tsconfig_json_with_the_recommended_settings_in_the_working_directory_6926": "작업 디렉터리에 권장되는 설정을 사용하여 tsconfig.json을 만듭니다.", + "DIRECTORY_6038": "디렉터리", + "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537": "문자 클래스에서는 10진수 이스케이프 시퀀스 및 역참조를 사용할 수 없습니다.", + "Decimals_with_leading_zeros_are_not_allowed_1489": "앞에 0이 있는 10진수는 허용되지 않습니다.", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "선언이 다른 파일의 선언을 확대합니다. 이 작업은 직렬화할 수 없습니다.", + "Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_support_9026": "이 파일에 대한 선언 내보내기에서는 확대를 위해 이 가져오기를 유지해야 합니다. 이는 --isolatedDeclarations에서는 지원되지 않습니다.", + "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "이 파일의 선언 내보내기에는 프라이빗 이름 '{0}'을(를) 사용해야 합니다. 명시적 형식 주석은 선언 내보내기를 차단 해제할 수 있습니다.", + "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "이 파일의 선언 내보내기에는 '{1}' 모듈의 프라이빗 이름 '{0}'을(를) 사용해야 합니다. 명시적 형식 주석은 선언 내보내기를 차단 해제할 수 있습니다.", + "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_sup_9025": "이 매개 변수에 대한 선언 내보내기를 사용하려면 정의되지 않은 형식을 암시적으로 추가해야 합니다. 이는 --isolatedDeclarations에서는 지원되지 않습니다.", + "Declaration_expected_1146": "선언이 필요합니다.", + "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "선언 이름이 기본 제공 전역 ID '{0}'과(와) 충돌합니다.", + "Declaration_or_statement_expected_1128": "선언 또는 문이 필요합니다.", + "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809": "선언 또는 문이 필요합니다. 이 '='은 문 블록을 따르므로 구조 파괴 할당을 작성하려는 경우 전체 할당을 괄호로 묶어야 할 수 있습니다.", + "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264": "한정된 할당 어설션이 포함된 선언에는 형식 주석도 있어야 합니다.", + "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263": "이니셜라이저가 포함된 선언에는 한정적 할당 어설션을 사용할 수 없습니다.", + "Declare_a_private_field_named_0_90053": "'{0}'(이)라는 프라이빗 필드를 선언합니다.", + "Declare_method_0_90023": "'{0}' 메서드 선언", + "Declare_private_method_0_90038": "프라이빗 메서드 '{0}' 선언", + "Declare_private_property_0_90035": "'{0}' 프라이빗 속성 선언", + "Declare_property_0_90016": "'{0}' 속성 선언", + "Declare_static_method_0_90024": "'{0}' 정적 메서드 선언", + "Declare_static_property_0_90027": "'{0}' 정적 속성 선언", + "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270": "데코레이터 함수 반환 유형 '{0}'은(는) '{1}' 유형에 할당할 수 없습니다.", + "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271": "데코레이터 함수 반환 유형은 '{0}'이지만 'void' 또는 'any'여야 합니다.", + "Decorator_used_before_export_here_1486": "여기에서 'export' 앞에 데코레이터를 사용했습니다.", + "Decorators_are_not_valid_here_1206": "데코레이터는 여기에 사용할 수 없습니다.", + "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "동일한 이름의 여러 get/set 접근자에 데코레이터를 적용할 수 없습니다.", + "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038": "'export' 앞에도 데코레이터가 나타나면 'export' 또는 'export default' 뒤에 나타나지 않을 수 있습니다.", + "Decorators_must_precede_the_name_and_all_keywords_of_property_declarations_1436": "데코레이터는 속성 선언의 이름 및 모든 키워드 앞에 와야 합니다.", + "Default_catch_clause_variables_as_unknown_instead_of_any_6803": "기본 catch 절 변수는 'any' 대신 'unknown'입니다.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "모듈의 기본 내보내기에서 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037": "기본 내보내기는 --isolatedDeclarations로 유추할 수 없습니다.", + "Default_library_1424": "기본 라이브러리", + "Default_library_for_target_0_1425": "대상 '{0}'의 기본 라이브러리", + "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "{0} 식별자의 정의가 다른 파일의 정의와 충돌합니다.", + "Delete_all_unused_declarations_95024": "사용하지 않는 선언 모두 삭제", + "Delete_all_unused_imports_95147": "사용하지 않는 가져오기 모두 삭제", + "Delete_all_unused_param_tags_95172": "사용하지 않은 '@param' 태그 모두 삭제", + "Delete_the_outputs_of_all_projects_6365": "모든 프로젝트의 출력을 삭제합니다.", + "Delete_unused_param_tag_0_95171": "사용하지 않는 '@param' 태그 '{0}' 삭제", + "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[사용되지 않음] 대신 '--jsxFactory'를 사용합니다. 'react' JSX 내보내기를 대상으로 할 경우 createElement에 대해 호출되는 개체를 지정합니다.", + "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[사용되지 않음] 대신 '--outFile'을 사용합니다. 출력을 연결하고 단일 파일로 내보냅니다.", + "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[사용되지 않음] 대신 '--skipLibCheck'를 사용합니다. 기본 라이브러리 선언 파일의 형식 검사를 건너뜁니다.", + "Deprecated_setting_Use_outFile_instead_6677": "더 이상 사용되지 않는 설정입니다. 대신 'outFile'을 사용하세요.", + "Did_you_forget_to_use_await_2773": "'await' 사용을 잊으셨습니까?", + "Did_you_mean_0_1369": "'{0}'을(를) 사용하시겠습니까?", + "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735": "'{0}'을(를) 'new (...args: any[]) => {1}' 형식으로 제한하시겠습니까?", + "Did_you_mean_to_call_this_expression_6212": "이 식을 호출하시겠습니까?", + "Did_you_mean_to_mark_this_function_as_async_1356": "이 함수를 'async'로 표시하시겠습니까?", + "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312": "':'을 사용하려고 하셨습니까? '='은 포함하는 개체 리터럴이 구조 파괴 패턴에 속하는 경우에만 속성 이름 뒤에 올 수 있습니다.", + "Did_you_mean_to_use_new_with_this_expression_6213": "이 식에서 'new'를 사용하시겠습니까?", + "Digit_expected_1124": "숫자가 필요합니다.", + "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "'{0}' 디렉터리가 없으므로 이 디렉터리에서 모든 조회를 건너뜁니다.", + "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270": "디렉터리 '{0}'에는 포함하는 package.json 범위가 없습니다. 가져오기가 확인되지 않습니다.", + "Disable_adding_use_strict_directives_in_emitted_JavaScript_files_6669": "내보낸 JavaScript 파일에서 'use strict' 지시문을 추가하지 않도록 설정합니다.", + "Disable_checking_for_this_file_90018": "이 파일 확인을 사용하지 않도록 설정", + "Disable_emitting_comments_6688": "주석 내보내기 사용 안 함", + "Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments_6701": "JSDoc 주석에 '@internal'이 있는 선언을 내보내는 것을 비활성화합니다.", + "Disable_emitting_files_from_a_compilation_6660": "컴파일에서 파일을 내보내지 않도록 설정합니다.", + "Disable_emitting_files_if_any_type_checking_errors_are_reported_6662": "형식 검사 오류가 보고되면 파일을 내보내지 않도록 설정합니다.", + "Disable_erasing_const_enum_declarations_in_generated_code_6682": "생성된 코드에서 'const enum' 선언 지우기를 비활성화합니다.", + "Disable_error_reporting_for_unreachable_code_6603": "연결할 수 없는 코드에 대한 오류 보고를 사용하지 않습니다.", + "Disable_error_reporting_for_unused_labels_6604": "사용하지 않은 레이블에 대한 오류 보고를 사용하지 않습니다.", + "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805": "전체 형식 검사를 사용하지 않도록 설정합니다(중요한 구문 분석 및 내보내기 오류만 보고됨).", + "Disable_generating_custom_helper_functions_like_extends_in_compiled_output_6661": "컴파일된 출력에서 ​​'__extents'와 같은 사용자 지정 도우미 함수 생성을 비활성화합니다.", + "Disable_including_any_library_files_including_the_default_lib_d_ts_6670": "기본 lib.d.ts를 비롯하여 모든 라이브러리 파일을 포함하지 않도록 설정합니다.", + "Disable_loading_referenced_projects_6235": "참조된 프로젝트 로드를 사용하지 않습니다.", + "Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects_6620": "복합 프로젝트를 참조할 때 선언 파일 대신 선호하는 소스 파일을 비활성화합니다.", + "Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals_6702": "개체 리터럴을 만드는 동안에는 초과 속성 오류에 대한 보고를 사용하지 않습니다.", + "Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node_6683": "실제 경로의 symlink를 확인하지 않도록 설정합니다. 이는 노드의 동일한 플래그와 상관 관계가 있습니다.", + "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript 프로젝트에 대한 크기 제한을 사용하지 않도록 설정합니다.", + "Disable_solution_searching_for_this_project_6224": "이 프로젝트를 검색하는 솔루션을 사용하지 않도록 설정합니다.", + "Disable_strict_checking_of_generic_signatures_in_function_types_6673": "함수 형식의 제네릭 시그니처에 대한 엄격한 검사를 사용하지 않도록 설정합니다.", + "Disable_the_type_acquisition_for_JavaScript_projects_6625": "JavaScript 프로젝트의 형식 인식을 사용하지 않습니다.", + "Disable_truncating_types_in_error_messages_6663": "오류 메시지에서 잘림 유형을 사용하지 않도록 설정합니다.", + "Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects_6221": "참조된 프로젝트의 선언 파일 대신 소스 파일을 사용하지 않도록 설정합니다.", + "Disable_wiping_the_console_in_watch_mode_6684": "시계 모드에서 콘솔 초기화를 비활성화합니다.", + "Disables_inference_for_type_acquisition_by_looking_at_filenames_in_a_project_6616": "프로젝트에서 파일 이름을 확인하여 형식 인식에 대한 유추를 사용하지 않습니다.", + "Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add__6672": "TypeScript가 프로젝트에 추가해야 하는 파일 수를 확장하는 '가져오기', '요구' 또는 ''를 허용하지 않습니다.", + "Disallow_inconsistently_cased_references_to_the_same_file_6078": "동일한 파일에 대해 대/소문자를 일관되지 않게 사용한 참조를 허용하지 않습니다.", + "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159": "컴파일된 파일 목록에 삼중 슬래시 참조 또는 가져온 모듈을 추가하지 않습니다.", + "Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript_6721": "ECMAScript의 일부가 아닌 런타임 구문을 허용하지 않습니다.", + "Do_not_emit_comments_to_output_6009": "주석을 출력에 내보내지 마세요.", + "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056": "'@internal' 주석이 있는 코드에 대한 선언을 내보내지 마세요.", + "Do_not_emit_outputs_6010": "출력을 내보내지 않습니다.", + "Do_not_emit_outputs_if_any_errors_were_reported_6008": "오류가 보고되면 출력을 내보내지 않습니다.", + "Do_not_emit_use_strict_directives_in_module_output_6112": "'use strict' 지시문을 모듈 출력에 내보내지 마세요.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "생성된 코드에서 const 열거형 선언을 지우지 마세요.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "컴파일된 출력에서 '__extends'와 같은 사용자 지정 도우미 함수를 생성하지 않습니다.", + "Do_not_include_the_default_library_file_lib_d_ts_6158": "기본 라이브러리 파일(lib.d.ts)을 포함하지 않습니다.", + "Do_not_report_errors_on_unreachable_code_6077": "접근할 수 없는 코드에 대한 오류를 보고하지 않습니다.", + "Do_not_report_errors_on_unused_labels_6074": "사용되지 않는 레이블에 대한 오류를 보고하지 않습니다.", + "Do_not_resolve_the_real_path_of_symlinks_6013": "symlink의 실제 경로를 확인하지 마세요.", + "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804": "'module' 설정에 따라 출력 파일의 형식으로 작성되도록 형식 전용으로 표시되지 않은 가져오기 또는 내보내기를 변환하거나 생략하지 마세요.", + "Do_not_truncate_error_messages_6165": "오류 메시지를 자르지 않습니다.", + "Duplicate_function_implementation_2393": "중복된 함수 구현입니다.", + "Duplicate_identifier_0_2300": "'{0}' 식별자가 중복되었습니다.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441": "'{0}' 식별자가 중복되었습니다. 컴파일러는 모듈의 최상위 범위에 이름 '{1}'을(를) 예약합니다.", + "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529": "'{0}' 식별자가 중복되었습니다. 컴파일러는 비동기 함수를 포함하는 모듈의 최상위 범위에 '{1}' 이름을 예약합니다.", + "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818": "중복 식별자 '{0}'입니다. 컴파일러는 정적 이니셜라이저에서 'super' 참조를 내보낸 경우 '{1}' 이름을 예약합니다.", + "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520": "중복 식별자 '{0}'입니다. 컴파일러는 '{1}' 선언을 사용하여 비동기 함수를 지원합니다.", + "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804": "'{0}' 식별자가 중복되었습니다. 정적 요소와 인스턴스 요소는 같은 프라이빗 이름을 공유할 수 없습니다.", + "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396": "중복 식별자 'arguments'입니다. 컴파일러는 'arguments'를 사용해서 rest 매개 변수를 초기화합니다.", + "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543": "'_newTarget' 식별자가 중복되었습니다. 컴파일러는 변수 선언 '_newTarget'을 사용하여 'new.target' 메타 속성 참조를 캡처합니다.", + "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399": "중복 식별자 '_this'입니다. 컴파일러는 변수 선언 '_this'를 사용해서 'this' 참조를 캡처합니다.", + "Duplicate_index_signature_for_type_0_2374": "'{0}' 형식에 대한 인덱스 시그니처가 중복되었습니다.", + "Duplicate_label_0_1114": "중복된 레이블 '{0}'입니다.", + "Duplicate_property_0_2718": "중복 속성 '{0}'입니다.", + "Duplicate_regular_expression_flag_1500": "중복된 정규식 플래그입니다.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "동적 가져오기의 지정자는 'string' 형식이어야 하지만 여기에서 형식은 '{0}'입니다.", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "동적 가져오기는 '--module' 플래그가 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node16', 'node18' 또는 'nodenext'로 설정된 경우에만 지원됩니다.", + "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments_1450": "동적 가져오기는 모듈 지정자와 선택적 특성 집합만 인수로 허용할 수 있습니다.", + "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_node18_1324": "동적 가져오기는 '--module' 옵션이 'esnext', 'node16', 'node18', 'nodenext' 또는 'preserve'로 설정된 경우에만 두 번째 인수를 지원합니다.", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve_1293": "'module'이 'preserve'로 설정된 경우 CommonJS 모듈에서는 ESM 구문을 사용할 수 없습니다.", + "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled_1286": "'verbatimModuleSyntax'를 사용하도록 설정한 경우 CommonJS 모듈에서는 ESM 구문을 사용할 수 없습니다.", + "Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given_4125": "'{0}.{1}'의 각 선언 값이 다릅니다. 여기서 '{2}'이(가) 필요한데 '{3}'이(가) 제공되었습니다.", + "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "공용 구조체 형식 '{0}'의 각 멤버에 구문 시그니처가 있지만, 해당 시그니처는 서로 호환되지 않습니다.", + "Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_2758": "공용 구조체 형식 '{0}'의 각 멤버에 시그니처가 있지만, 해당 시그니처는 서로 호환되지 않습니다.", + "Editor_Support_6249": "편집기 지원", + "Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1_7053": "'{0}' 형식의 식을 '{1}' 인덱스 형식에 사용할 수 없으므로 요소에 암시적으로 'any' 형식이 있습니다.", + "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "인덱스 식이 'number' 형식이 아니므로 요소에 암시적으로 'any' 형식이 있습니다.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "'{0}' 형식에 인덱스 시그니처가 없으므로 요소에 암시적으로 'any' 형식이 있습니다.", + "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_Did_you_mean_to_call_1_7052": "'{0}' 형식에 인덱스 시그니처가 없으므로 요소에 암시적으로 'any' 형식이 있습니다. '{1}'을(를) 호출하시겠습니까?", + "Emit_6246": "방출", + "Emit_ECMAScript_standard_compliant_class_fields_6712": "ECMAScript 표준 규격 클래스 필드를 내보냅니다.", + "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6622": "출력 파일의 시작에서 UTF-8 BOM(바이트 순서 표시)을 내보냅니다.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "별도의 파일을 사용하는 대신 소스 맵과 함께 단일 파일을 내보냅니다.", + "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638": "디버깅을 위해 실행된 컴파일러의 v8 CPU 프로필을 내보냅니다.", + "Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheti_6626": "CommonJS 모듈 가져오기 지원을 쉽게 하기 위해 추가 JavaScript를 내보냅니다. 이것은 유형 호환성을 위해 'allowSyntheticDefaultImports'를 활성화합니다.", + "Emit_class_fields_with_Define_instead_of_Set_6222": "Set 대신 Define을 사용하여 클래스 필드를 내보냅니다.", + "Emit_design_type_metadata_for_decorated_declarations_in_source_files_6624": "소스 파일에서 데코레이트된 선언의 디자인 형식 메타데이터를 내보냅니다.", + "Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration_6621": "반복을 위해 규격에 더 맞지만 장황하고 성능이 떨어지는 JavaScript를 내보냅니다.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "단일 파일 내에서 소스 맵과 함께 소스를 내보냅니다. '--inlineSourceMap' 또는 '--sourceMap'을 설정해야 합니다.", + "Enable_all_strict_type_checking_options_6180": "엄격한 형식 검사 옵션을 모두 사용하도록 설정합니다.", + "Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read_6685": "컴파일러 오류를 더 쉽게 읽을 수 있도록 TypeScript의 출력에서 ​​색상 및 서식을 활성화합니다.", + "Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references_6611": "TypeScript 프로젝트를 프로젝트 참조와 함께 사용할 수 있는 제약 조건을 사용합니다.", + "Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function_6667": "함수에서 명시적으로 반환되지 않은 코드 경로에 대한 오류 보고를 사용합니다.", + "Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type_6665": "암시적 '모든' 유형의 표현식 및 선언에 대한 오류 보고를 활성화합니다.", + "Enable_error_reporting_for_fallthrough_cases_in_switch_statements_6664": "switch 문에서 폴스루 사례에 대한 오류 보고를 활성화합니다.", + "Enable_error_reporting_in_type_checked_JavaScript_files_6609": "형식이 확인된 JavaScript 파일에서 오류 보고를 사용하도록 설정합니다.", + "Enable_error_reporting_when_local_variables_aren_t_read_6675": "지역 변수를 읽지 않을 때 오류 보고를 활성화합니다.", + "Enable_error_reporting_when_this_is_given_the_type_any_6668": "'this'에 'any' 유형이 지정되면 오류 보고를 활성화합니다.", + "Enable_experimental_support_for_legacy_experimental_decorators_6630": "레거시 실험적 데코레이터에 대해 실험적 지원을 사용하도록 설정합니다.", + "Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present_6264": "선언 파일이 있는 경우 확장자가 있는 파일 가져오기를 사용하도록 설정합니다.", + "Enable_importing_json_files_6689": ".json 파일 가져오기를 활성화합니다.", + "Enable_lib_replacement_6808": "라이브러리 바꾸기를 사용하도록 설정합니다.", + "Enable_project_compilation_6302": "프로젝트 컴파일을 사용하도록 설정", + "Enable_strict_bind_call_and_apply_methods_on_functions_6214": "함수에서 strict 'bind', 'call' 및 'apply' 메서드를 사용하도록 설정합니다.", + "Enable_strict_checking_of_function_types_6186": "함수 형식에 대한 엄격한 검사를 사용하도록 설정합니다.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "클래스의 속성 초기화에 대해 엄격한 검사를 사용하도록 설정합니다.", + "Enable_strict_null_checks_6113": "엄격한 null 검사를 사용하도록 설정하세요.", + "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074": "구성 파일에서 'experimentalDecorators' 옵션을 사용하도록 설정합니다.", + "Enable_the_jsx_flag_in_your_configuration_file_95088": "구성 파일에서 '--jsx' 플래그를 사용하도록 설정합니다.", + "Enable_tracing_of_the_name_resolution_process_6085": "이름 확인 프로세스 추적을 사용하도록 설정하세요.", + "Enable_verbose_logging_6713": "자세한 로깅을 활성화합니다.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "모든 가져오기에 대한 네임스페이스 개체를 만들어 CommonJS 및 ES 모듈 간의 내보내기 상호 운용성을 사용하도록 설정합니다. 'allowSyntheticDefaultImports'를 의미합니다.", + "Enables_experimental_support_for_ES7_decorators_6065": "ES7 데코레이터에 대해 실험적 지원을 사용합니다.", + "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "데코레이터에 대한 형식 메타데이터를 내보내기 위해 실험적 지원을 사용합니다.", + "Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type_6671": "인덱싱된 형식을 사용하여 선언된 키에 대해 인덱싱된 접근자를 사용합니다.", + "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6666": "파생 클래스의 멤버 재정의가 재정의 한정자로 표시되어 있는지 확인합니다.", + "Ensure_that_casing_is_correct_in_imports_6637": "가져오기에서 대/소문자가 올바른지 확인합니다.", + "Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports_6645": "다른 가져오기를 사용하지 않고 각 파일을 안전하게 변환할 수 있는지 확인합니다.", + "Ensure_use_strict_is_always_emitted_6605": "'use strict'를 항상 내보내고 있는지 확인합니다.", + "Entering_conditional_exports_6413": "조건부 내보내기가 시작됩니다.", + "Entry_point_for_implicit_type_library_0_1420": "암시적 형식 라이브러리 '{0}'의 진입점", + "Entry_point_for_implicit_type_library_0_with_packageId_1_1421": "packageId가 '{1}'인 암시적 형식 라이브러리 '{0}'의 진입점", + "Entry_point_of_type_library_0_specified_in_compilerOptions_1417": "compilerOptions에 지정된 형식 라이브러리 '{0}'의 진입점", + "Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1_1418": "packageId가 '{1}'인 compilerOptions에 지정된 형식 라이브러리 '{0}'의 진입점", + "Enum_0_used_before_its_declaration_2450": "선언 전에 사용된 '{0}' 열거형입니다.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "열거형 선언은 네임스페이스 또는 다른 열거형 선언과만 병합할 수 있습니다.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "열거형 선언은 모두 const 또는 비const여야 합니다.", + "Enum_member_expected_1132": "열거형 멤버가 필요합니다.", + "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056": "'isolatedModules'를 사용하도록 설정한 경우 리터럴이 아닌 숫자 멤버 다음에 오는 열거형 멤버에는 이니셜라이저가 있어야 합니다.", + "Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDecl_9020": "열거형 멤버 이니셜라이저는 --isolatedDeclarations를 사용하여 외부 기호에 대한 참조 없이 계산할 수 있어야 합니다.", + "Enum_member_must_have_initializer_1061": "열거형 멤버에는 이니셜라이저가 있어야 합니다.", + "Enum_name_cannot_be_0_2431": "열거형 이름은 '{0}'일 수 없습니다.", + "Errors_Files_6041": "오류 파일", + "Escape_sequence_0_is_not_allowed_1488": "이스케이프 시퀀스 '{0}'은(는) 허용되지 않습니다.", + "Examples_Colon_0_6026": "예: {0}", + "Excessive_complexity_comparing_types_0_and_1_2859": "'{0}' 및 '{1}' 형식을 비교하는 데 과도한 복잡성이 있습니다.", + "Excessive_stack_depth_comparing_types_0_and_1_2321": "'{0}' 및 '{1}' 형식을 비교하는 스택 깊이가 과도합니다.", + "Exiting_conditional_exports_6416": "조건부 내보내기가 종료됩니다.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "'@extends' 태그로 제공하는 예상되는 {0}-{1} 형식 인수입니다.", + "Expected_0_arguments_but_got_1_2554": "{0}개의 인수가 필요한데 {1}개를 가져왔습니다.", + "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794": "{0}개 인수가 필요한데 {1}개를 가져왔습니다. 'void'를 'Promise'의 형식 인수에 포함하는 것을 잊으셨습니까?", + "Expected_0_type_arguments_but_got_1_2558": "{0}개의 형식 인수가 필요한데 {1}개를 가져왔습니다.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "'@extends' 태그로 제공하는 예상되는 {0} 형식 인수입니다.", + "Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_2810": "1개의 인수가 필요하지만 0이 있습니다. 'new Promise()'는 인수 없이 호출할 수 있는 'resolve'를 생성하기 위해 JSDoc 힌트가 필요합니다.", + "Expected_a_Unicode_property_name_1523": "유니코드 속성 이름이 필요합니다.", + "Expected_a_Unicode_property_name_or_value_1527": "유니코드 속성 이름 또는 값이 필요합니다.", + "Expected_a_Unicode_property_value_1525": "유니코드 속성 값이 필요합니다.", + "Expected_a_capturing_group_name_1514": "캡처 그룹 이름이 필요합니다.", + "Expected_a_class_set_operand_1520": "클래스 집합 피연산자가 필요합니다.", + "Expected_at_least_0_arguments_but_got_1_2555": "최소 {0}개의 인수가 필요한데 {1}개를 가져왔습니다.", + "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}'에 해당하는 JSX 닫는 태그가 필요합니다.", + "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "JSX 조각에 닫는 태그가 필요합니다.", + "Expected_for_property_initializer_1442": "속성 이니셜라이저에는 '='가 필요합니다.", + "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105": "'package.json'의 '{0}' 필드에 '{1}' 형식이 필요한데 '{2}'을(를) 얻었습니다.", + "Explicitly_specified_module_resolution_kind_Colon_0_6087": "명시적으로 지정된 모듈 확인 종류 '{0}'입니다.", + "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "'target' 옵션이 'es2016' 이상으로 설정되어 있지 않으면 'bigint' 값에 지수화를 수행할 수 없습니다.", + "Export_0_from_module_1_90059": "'{0}'을(를) '{1}' 모듈에서 내보냅니다.", + "Export_all_referenced_locals_90060": "참조된 모든 로컬 내보내기", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript 모듈을 대상으로 하는 경우 내보내기 할당을 사용할 수 없습니다. 대신 'export default'나 다른 모듈 형식의 사용을 고려하세요.", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "'--module' 플래그가 'system'이면 내보내기 할당은 지원되지 않습니다.", + "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "내보내기 선언이 '{0}'의 내보낸 선언과 충돌합니다.", + "Export_declarations_are_not_permitted_in_a_namespace_1194": "네임스페이스에서는 내보내기 선언이 허용되지 않습니다.", + "Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6276": "내보내기 지정자 '{0}'이(가) '{1}' 경로의 package.json 범위에 없습니다.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "내보낸 형식 별칭 '{0}'은(는) '{1}' 프라이빗 이름을 포함하거나 사용 중입니다.", + "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084": "내보낸 형식 별칭 '{0}'이(가) 모듈 {2}의 프라이빗 이름 '{1}'을(를) 포함하거나 사용하고 있습니다.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "내보낸 변수 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "내보낸 변수 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "내보낸 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "내보내기 및 내보내기 할당는 모듈 확대에서 허용되지 않습니다.", + "Expression_expected_1109": "식이 필요합니다.", + "Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator_1497": "식을 데코레이터로 사용하려면 괄호로 묶어야 합니다.", + "Expression_or_comma_expected_1137": "식 또는 쉼표가 필요합니다.", + "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800": "식이 너무 커서 표시할 수 없는 튜플 형식을 생성합니다.", + "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590": "식에서는 너무 복잡해서 표시할 수 없는 공용 구조체 형식을 생성합니다.", + "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "컴파일러가 기본 클래스 참조를 캡처하기 위해 사용하는 '_super'로 식이 확인됩니다.", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "컴파일러가 'new.target' 메타 속성 참조를 캡처하기 위해 사용하는 변수 선언 '_newTarget'으로 식이 확인됩니다.", + "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "컴파일러가 'this' 참조를 캡처하기 위해 사용하는 변수 선언 '_this'로 식이 확인됩니다.", + "Expression_type_can_t_be_inferred_with_isolatedDeclarations_9013": "식 형식은 --isolatedDeclarations로 유추할 수 없습니다.", + "Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations_9021": "Extends 절에는 --isolatedDeclarations가 있는 식을 포함할 수 없습니다.", + "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085": "유추된 형식 '{0}'에 대한 extends 절이 '{1}' 비공개 이름을 가지고 있거나 사용 중입니다.", + "Extract_base_class_to_variable_90064": "변수에 기본 클래스 추출", + "Extract_binding_expressions_to_variable_90066": "변수에 바인딩 식 추출", + "Extract_constant_95006": "상수 추출", + "Extract_default_export_to_variable_90065": "변수로 기본 내보내기 추출", + "Extract_function_95005": "함수 추출", + "Extract_to_0_in_1_95004": "{1}의 {0}(으)로 추출", + "Extract_to_0_in_1_scope_95008": "{1} 범위의 {0}(으)로 추출", + "Extract_to_0_in_enclosing_scope_95007": "바깥쪽 범위의 {0}(으)로 추출", + "Extract_to_interface_95090": "인터페이스로 추출", + "Extract_to_type_alias_95078": "형식 별칭으로 추출", + "Extract_to_typedef_95079": "Typedef로 추출", + "Extract_to_variable_and_replace_with_0_as_typeof_0_90069": "변수로 추출하고 '{0} as typeof {0}'(으)로 바꾸기", + "Extract_type_95077": "형식 추출", + "FILE_6035": "파일", + "FILE_OR_DIRECTORY_6040": "파일 또는 디렉터리", + "Failed_to_find_peerDependency_0_6283": "peerDependency '{0}'을(를) 찾지 못했습니다.", + "Failed_to_resolve_under_condition_0_6415": "조건 '{0}'에서 확인하지 못했습니다.", + "Fallthrough_case_in_switch_7029": "switch에 Fallthrough case가 있습니다.", + "File_0_does_not_exist_6096": "'{0}' 파일이 없습니다.", + "File_0_does_not_exist_according_to_earlier_cached_lookups_6240": "이전 캐시된 검색에 따라 '{0}' 파일이 존재하지 않습니다.", + "File_0_exists_according_to_earlier_cached_lookups_6239": "파일 '{0}'은(는) 이전 캐시된 검색에 따라 존재합니다.", + "File_0_exists_use_it_as_a_name_resolution_result_6097": "'{0}' 파일이 있습니다. 이 파일을 이름 확인 결과로 사용하세요.", + "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' 파일의 확장명이 지원되지 않습니다. 지원되는 확장명은 {1}뿐입니다.", + "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504": "'{0}' 파일은 JavaScript 파일입니다. 'allowJs' 옵션을 사용하도록 설정하시겠습니까?", + "File_0_is_not_a_module_2306": "'{0}' 파일은 모듈이 아닙니다.", + "File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_includ_6307": "'{0}' 파일이 '{1}' 프로젝트의 파일 목록에 나열되지 않습니다. 프로젝트는 모든 파일을 나열하거나 'include' 패턴을 사용해야 합니다.", + "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' 파일이 'rootDir' '{1}' 아래에 있지 않습니다. 'rootDir'에는 모든 소스 파일이 포함되어 있어야 합니다.", + "File_0_not_found_6053": "파일 '{0}'을(를) 찾을 수 없습니다.", + "File_Management_6245": "파일 관리", + "File_appears_to_be_binary_1490": "파일이 이진 파일인 것 같습니다.", + "File_change_detected_Starting_incremental_compilation_6032": "파일 변경이 검색되었습니다. 증분 컴파일을 시작하는 중...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "'{0}'에 \"type\" 필드가 없으므로 파일이 CommonJS 모듈입니다.", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "'{0}'에 값이 \"module\"이 아닌 \"type\" 필드가 있으므로 파일이 CommonJS 모듈입니다.", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "'package.json'을 찾을 수 없으므로 파일이 CommonJS 모듈입니다.", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "'{0}'에 값이 \"module\"인 \"type\" 필드가 있으므로 파일이 ECMAScript 모듈입니다.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "파일이 CommonJS 모듈입니다. ES 모듈로 변환될 수 있습니다.", + "File_is_default_library_for_target_specified_here_1426": "파일은 여기에 지정된 대상의 기본 라이브러리입니다.", + "File_is_entry_point_of_type_library_specified_here_1419": "파일은 여기에 지정된 형식 라이브러리의 진입점입니다.", + "File_is_included_via_import_here_1399": "파일은 여기에 가져오기를 통해 포함됩니다.", + "File_is_included_via_library_reference_here_1406": "파일은 여기에 라이브러리 참조를 통해 포함됩니다.", + "File_is_included_via_reference_here_1401": "파일은 여기에 참조를 통해 포함됩니다.", + "File_is_included_via_type_library_reference_here_1404": "파일은 여기에 형식 라이브러리 참조를 통해 포함됩니다.", + "File_is_library_specified_here_1423": "파일은 여기에 지정된 라이브러리입니다.", + "File_is_matched_by_files_list_specified_here_1410": "파일은 여기에 지정된 'files' 목록으로 일치됩니다.", + "File_is_matched_by_include_pattern_specified_here_1408": "파일은 여기에 지정된 포함 패턴으로 일치됩니다.", + "File_is_output_from_referenced_project_specified_here_1413": "파일은 여기에 지정된 참조 프로젝트의 출력입니다.", + "File_is_output_of_project_reference_source_0_1428": "파일은 프로젝트 참조 소스 '{0}'의 출력입니다.", + "File_is_source_from_referenced_project_specified_here_1416": "파일은 여기에 지정된 참조된 프로젝트의 소스입니다.", + "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "'{0}' 파일 이름은 이미 포함된 '{1}' 파일 이름과 대/소문자만 다릅니다.", + "File_name_0_has_a_1_extension_looking_up_2_instead_6262": "파일 이름 '{0}'에는 '{1}' 확장명이 있습니다. 대신 '{2}'을(를) 조회합니다.", + "File_name_0_has_a_1_extension_stripping_it_6132": "파일 이름 '{0}'에 '{1}' 확장명이 있어 제거하는 중입니다.", + "File_redirects_to_file_0_1429": "파일은 '{0}' 파일로 리디렉션됩니다.", + "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "파일 사양은 재귀 디렉터리 와일드카드('**') 뒤에 나타나는 부모 디렉터리('..')를 포함할 수 없습니다. '{0}'.", + "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "파일 사양은 재귀 디렉터리 와일드카드('**')로 끝날 수 없습니다. '{0}'.", + "Filters_results_from_the_include_option_6627": "'include' 옵션의 결과를 필터링합니다.", + "Fix_all_detected_spelling_errors_95026": "검색된 맞춤법 오류 모두 수정", + "Fix_all_expressions_possibly_missing_await_95085": "'await'가 누락되었을 수 있는 모든 식 수정", + "Fix_all_implicit_this_errors_95107": "모든 암시적 'this' 오류 수정", + "Fix_all_incorrect_return_type_of_an_async_functions_90037": "비동기 함수의 모든 잘못된 반환 형식 수정", + "Fix_all_with_type_only_imports_95182": "형식 전용 가져오기를 사용하여 모두 수정", + "Found_0_errors_6217": "{0}개 오류가 발견되었습니다.", + "Found_0_errors_Watching_for_file_changes_6194": "{0}개 오류가 발견되었습니다. 파일이 변경되었는지 확인하는 중입니다.", + "Found_0_errors_in_1_files_6261": "{1} 파일에서 {0} 오류를 찾았습니다.", + "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260": "{1}에서 시작하는 동일한 파일에서 {0}개의 오류를 찾았습니다.", + "Found_1_error_6216": "1개 오류가 발견되었습니다.", + "Found_1_error_Watching_for_file_changes_6193": "1개 오류가 발견되었습니다. 파일이 변경되었는지 확인하는 중입니다.", + "Found_1_error_in_0_6259": "{0}에서 1개의 오류를 찾았습니다.", + "Found_package_json_at_0_6099": "'{0}'에서 'package.json'을 찾았습니다.", + "Found_peerDependency_0_with_1_version_6282": "'{1}' 버전이 있는 peerDependency '{0}'을(를) 찾았습니다.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_1250": "'ES5'를 대상으로 하는 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definiti_1251": "'ES5'를 대상으로 하는 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다. 클래스 정의는 자동으로 strict 모드가 됩니다.", + "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_au_1252": "'ES5'를 대상으로 하는 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다. 모듈은 자동으로 strict 모드가 됩니다.", + "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011": "반환 형식 주석이 없는 함수 식에는 암시적으로 '{0}' 반환 형식이 포함됩니다.", + "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "함수 구현이 없거나 선언 바로 다음에 나오지 않습니다.", + "Function_implementation_name_must_be_0_2389": "함수 구현 이름이 '{0}'이어야 합니다.", + "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "반환 형식 주석이 없고 반환 식 중 하나에서 직간접적으로 참조되므로 함수에는 암시적으로 반환 형식 'any'가 포함됩니다.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "함수에 끝 return 문이 없으며 반환 형식에 'undefined'가 포함되지 않습니다.", + "Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9007": "함수에는 --isolatedDeclarations가 있는 명시적 반환 형식 주석이 있어야 합니다.", + "Function_not_implemented_95159": "함수가 구현되지 않았습니다.", + "Function_overload_must_be_static_2387": "함수 오버로드는 정적이어야 합니다.", + "Function_overload_must_not_be_static_2388": "함수 오버로드는 정적이 아니어야 합니다.", + "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385": "공용 구조체 형식에 사용되는 경우 함수 형식 표기법을 괄호로 묶어야 합니다.", + "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387": "교집합 형식에 사용되는 경우 함수 형식 표기법을 괄호로 묶어야 합니다.", + "Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014": "반환 형식 주석이 없는 함수 형식에는 암시적으로 '{0}' 반환 형식이 포함됩니다.", + "Function_with_bodies_can_only_merge_with_classes_that_are_ambient_2814": "본문이 있는 함수는 앰비언트 클래스하고만 병합할 수 있습니다.", + "Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project_6612": "프로젝트의 TypeScript 및 JavaScript 파일에서 .d.ts 파일을 생성합니다.", + "Generate_get_and_set_accessors_95046": "'get' 및 'set' 접근자 생성", + "Generate_get_and_set_accessors_for_all_overriding_properties_95119": "모든 재정의 속성에 대한 'get' 및 'set' 접근자를 생성합니다.", + "Generates_a_CPU_profile_6223": "CPU 프로필을 생성합니다.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "해당하는 각 '.d.ts' 파일에 sourcemap을 생성합니다.", + "Generates_an_event_trace_and_a_list_of_types_6237": "이벤트 추적 및 형식 목록을 생성합니다.", + "Generates_corresponding_d_ts_file_6002": "해당 '.d.ts' 파일을 생성합니다.", + "Generates_corresponding_map_file_6043": "해당 '.map' 파일을 생성합니다.", + "Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation_7025": "생성기에 암시적으로 '{0}' yield 형식이 있습니다. 반환 형식 주석을 제공하는 것이 좋습니다.", + "Generators_are_not_allowed_in_an_ambient_context_1221": "생성기는 앰비언트 컨텍스트에서 사용할 수 없습니다.", + "Generic_type_0_requires_1_type_argument_s_2314": "'{0}' 제네릭 형식에 {1} 형식 인수가 필요합니다.", + "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "제네릭 형식 '{0}'에 {1} 및 {2} 사이의 형식 인수가 필요합니다.", + "Global_module_exports_may_only_appear_at_top_level_1316": "전역 모듈 내보내기는 최상위 수준에만 나올 수 있습니다.", + "Global_module_exports_may_only_appear_in_declaration_files_1315": "전역 모듈 내보내기는 선언 파일에만 나올 수 있습니다.", + "Global_module_exports_may_only_appear_in_module_files_1314": "전역 모듈 내보내기는 모듈 파일에만 나올 수 있습니다.", + "Global_type_0_must_be_a_class_or_interface_type_2316": "전역 형식 '{0}'은 클래스 또는 인터페이스 형식이어야 합니다.", + "Global_type_0_must_have_1_type_parameter_s_2317": "전역 형식 '{0}'에는 {1} 형식 매개 변수를 사용해야 합니다.", + "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384": "'--incremental' 및 '--watch'의 다시 컴파일에서 파일 내 변경 내용은 파일에 따라 직접 파일에만 영향을 준다고 가정하도록 합니다.", + "Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_wi_6606": "'증분' 및 '감시' 모드를 사용하는 프로젝트에서 재컴파일하면 파일 내의 변경 사항이 해당 파일에 직접적으로 영향을 미치는 파일에만 영향을 미친다고 가정합니다.", + "Hexadecimal_digit_expected_1125": "16진수가 필요합니다.", + "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262": "식별자가 필요합니다. '{0}'은(는) 모듈의 최상위 수준에 있는 예약어입니다.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다. 클래스 정의는 자동으로 strict 모드가 됩니다.", + "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다. 모듈은 자동으로 strict 모드가 됩니다.", + "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "식별자가 필요합니다. '{0}'은(는) 여기에서 사용할 수 없는 예약어입니다.", + "Identifier_expected_1003": "식별자가 필요합니다.", + "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "식별자가 필요합니다. '__esModule'은 ECMAScript 모듈을 변환할 때 내보낸 표식으로 예약되어 있습니다.", + "Identifier_or_string_literal_expected_1478": "식별자 또는 문자열 리터럴이 필요합니다.", + "Identifier_string_literal_or_number_literal_expected_1496": "식별자, 문자열 리터럴 또는 숫자 리터럴이 필요합니다.", + "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "'{0}' 패키지가 이 모듈을 실제로 공개하는 경우 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}' 수정을 위한 끌어오기 요청을 보내는 것이 좋습니다.", + "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "'{0}' 패키지가 실제로 이 모듈을 노출하는 경우 'declare module {1}';'이(가) 포함된 새 선언(.d.ts) 파일을 추가해 보세요.", + "Ignore_this_error_message_90019": "이 오류 메시지 무시", + "Ignoring_tsconfig_json_compiles_the_specified_files_with_default_compiler_options_6924": "tsconfig.json을 무시하고 기본 컴파일러 옵션을 사용하여 지정된 파일을 컴파일합니다.", + "Implement_all_inherited_abstract_classes_95040": "상속된 추상 클래스 모두 구현", + "Implement_all_unimplemented_interfaces_95032": "구현되지 않은 인터페이스 모두 구현", + "Implement_inherited_abstract_class_90007": "상속된 추상 클래스 구현", + "Implement_interface_0_90006": "'{0}' 인터페이스 구현", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "내보낸 클래스 '{0}'의 Implements 절이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731": "런타임에는 'symbol'을 'string'으로 암시적으로 변환할 수 없습니다. 이 식을 'String(...)'으로 래핑하는 것이 좋습니다.", + "Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_w_2866": "'{0}' 가져오기는 이 파일에 사용된 전역 값과 충돌하므로 'isolatedModules'를 사용하도록 설정한 경우 형식 전용 가져오기를 사용하여 선언해야 합니다.", + "Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_2865": "'{0}' 가져오기는 로컬 값과 충돌하므로 'isolatedModules'를 사용하도록 설정한 경우 형식 전용 가져오기를 사용하여 선언해야 합니다.", + "Import_0_from_1_90013": "\"{1}\"에서 '{0}'을(를) 가져옵니다.", + "Import_assertion_values_must_be_string_literal_expressions_2837": "가져오기 어설션 값은 문자열 리터럴 ㅁ이이어야 합니다.", + "Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2836": "CommonJS 'require' 호출로 컴파일되는 문에서는 가져오기 어설션을 사용할 수 없습니다.", + "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2821": "가져오기 어설션은 '--module' 옵션이 'esnext', 'node18', 'nodenext' 또는 'preserve'로 설정된 경우에만 지원됩니다.", + "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822": "가져오기 어설션은 형식 전용 가져오기 또는 내보내기에서 사용할 수 없습니다.", + "Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880": "가져오기 어설션이 가져오기 특성으로 바뀌었습니다. 'assert' 대신 'with'를 사용합니다.", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript 모듈을 대상으로 하는 경우 할당 가져오기를 사용할 수 없습니다. 대신 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' 또는 다른 모듈 형식 사용을 고려하세요.", + "Import_attribute_values_must_be_string_literal_expressions_2858": "가져오기 특성 값은 문자열 리터럴 식이어야 합니다.", + "Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls_2856": "CommonJS 'require' 호출로 컴파일되는 문에서는 가져오기 특성을 사용할 수 없습니다.", + "Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_node18_nodenext_or_pres_2823": "가져오기 특성은 '--module' 옵션이 'esnext', 'node18', 'nodenext' 또는 'preserve'로 설정된 경우에만 지원됩니다.", + "Import_attributes_cannot_be_used_with_type_only_imports_or_exports_2857": "가져오기 특성은 형식 전용 가져오기 또는 내보내기에서 사용할 수 없습니다.", + "Import_declaration_0_is_using_private_name_1_4000": "가져오기 선언 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 사용하고 있습니다.", + "Import_declaration_conflicts_with_local_declaration_of_0_2440": "가져오기 선언이 '{0}'의 로컬 선언과 충돌합니다.", + "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "네임스페이스의 가져오기 선언은 모듈을 참조할 수 없습니다.", + "Import_emit_helpers_from_tslib_6139": "'tslib'에서 내보내기 도우미를 가져오세요.", + "Import_may_be_converted_to_a_default_import_80003": "가져오기가 기본 가져오기로 변환될 수 있습니다.", + "Import_name_cannot_be_0_2438": "가져오기 이름은 '{0}'일 수 없습니다.", + "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "앰비언트 모듈 선언의 가져오기 또는 내보내기 선언은 상대적 모듈 이름을 통해 모듈을 참조할 수 없습니다.", + "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271": "가져오기 지정자 '{0}'이(가) '{1}' 경로의 package.json 범위에 없습니다.", + "Imported_via_0_from_file_1_1393": "'{1}' 파일에서 {0}을(를) 통해 가져왔습니다.", + "Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions_1395": "compilerOptions에 지정된 대로 'importHelpers'를 가져오기 위해 '{1}' 파일에서 {0}을(를) 통해 가져왔습니다.", + "Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions_1397": "'jsx' 및 'jsxs' 팩터리 함수를 가져오기 위해 '{1}' 파일에서 {0}을(를) 통해 가져왔습니다.", + "Imported_via_0_from_file_1_with_packageId_2_1394": "packageId가 '{2}'인 '{1}' 파일에서 {0}을(를) 통해 가져왔습니다.", + "Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions_1396": "compilerOptions에 지정된 대로 'importHelpers'를 가져오기 위해 packageId가 '{2}'인 '{1}' 파일에서 {0}을(를) 통해 가져왔습니다.", + "Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions_1398": "'jsx' 및 'jsxs' 팩터리 함수를 가져오기 위해 packageId가 '{2}'인 '{1}' 파일에서 {0}을(를) 통해 가져왔습니다.", + "Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_mod_1543": "'module'이 '{0}'(으)로 설정된 경우 JSON 파일을 ECMAScript 모듈로 가져오려면 'type: \"json\"' 가져오기 특성이 필요합니다.", + "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "가져오기는 모듈 확대에서 허용되지 않습니다. 내보내기를 바깥쪽 외부 모듈로 이동하세요.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "앰비언트 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "다중 선언이 포함된 열거형에서는 하나의 선언만 첫 번째 열거형 요소에 대한 이니셜라이저를 생략할 수 있습니다.", + "Include_a_list_of_files_This_does_not_support_glob_patterns_as_opposed_to_include_6635": "파일 목록을 포함합니다. 이는 'include'가 아닌 GLOB 패턴을 지원하지 않습니다.", + "Include_modules_imported_with_json_extension_6197": "'.json' 확장을 사용하여 가져온 모듈을 포함합니다.", + "Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript_6644": "내보낸 JavaScript 내 sourcemap에 소스 코드를 포함합니다.", + "Include_sourcemap_files_inside_the_emitted_JavaScript_6643": "내보낸 JavaScript 내에 sourcemap 파일을 포함합니다.", + "Includes_imports_of_types_referenced_by_0_90054": "'{0}'에서 참조하는 유형의 가져오기를 포함합니다.", + "Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_conf_6914": "--watch를 포함하면 -w는 파일 변경 내용에 대한 현재 프로젝트 감시를 시작합니다. 설정되면 다음을 사용하여 조사식 모드를 구성할 수 있습니다.", + "Incomplete_quantifier_Digit_expected_1505": "불완전한 수량자입니다. 숫자가 필요합니다.", + "Index_signature_for_type_0_is_missing_in_type_1_2329": "'{1}' 형식에 인덱스 시그니처 유형 '{0}'이(가) 없습니다.", + "Index_signature_in_type_0_only_permits_reading_2542": "'{0}' 형식의 인덱스 시그니처는 읽기만 허용됩니다.", + "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "병합된 선언 '{0}'의 개별 선언은 모두 내보내 졌거나 모두 로컬이어야 합니다.", + "Infer_all_types_from_usage_95023": "사용량에서 모든 형식 유추", + "Infer_function_return_type_95148": "함수 반환 형식 유추", + "Infer_parameter_types_from_usage_95012": "사용량에서 매개 변수 형식 유추", + "Infer_this_type_of_0_from_usage_95080": "사용량에서 '{0}'의 'this' 형식 유추", + "Infer_type_of_0_from_usage_95011": "사용량에서 '{0}'의 형식 유추", + "Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations_9022": "--isolatedDeclarations에서는 클래스 식의 유추가 지원되지 않습니다.", + "Initialize_property_0_in_the_constructor_90020": "생성자에서 속성 '{0}' 초기화", + "Initialize_static_property_0_90021": "정적 속성 '{0}' 초기화", + "Initializer_for_property_0_2811": "'{0}' 속성에 대한 이니셜라이저", + "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "인스턴스 멤버 변수 '{0}'의 이니셜라이저는 생성자에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", + "Initializers_are_not_allowed_in_ambient_contexts_1039": "앰비언트 컨텍스트에서는 이니셜라이저가 허용되지 않습니다.", + "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "TypeScript 프로젝트를 초기화하고 tsconfig.json 파일을 만듭니다.", + "Inline_variable_95184": "인라인 변수", + "Insert_command_line_options_and_files_from_a_file_6030": "파일에서 명령줄 옵션 및 파일을 삽입합니다.", + "Install_0_95014": "'{0}' 설치", + "Install_all_missing_types_packages_95033": "누락된 형식 패키지 모두 설치", + "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320": "'{0}' 인터페이스는 '{1}' 및 '{2}' 형식을 동시에 확장할 수 없습니다.", + "Interface_0_incorrectly_extends_interface_1_2430": "'{0}' 인터페이스가 '{1}' 인터페이스를 잘못 확장합니다.", + "Interface_declaration_cannot_have_implements_clause_1176": "인터페이스 선언에는 'implements' 절을 사용할 수 없습니다.", + "Interface_must_be_given_a_name_1438": "인터페이스에 이름을 지정해야 합니다.", + "Interface_name_cannot_be_0_2427": "인터페이스 이름은 '{0}'일 수 없습니다.", + "Interop_Constraints_6252": "Interop 제약 조건", + "Interpret_optional_property_types_as_written_rather_than_adding_undefined_6243": "'undefined'를 추가하는 대신 선택적 속성 형식을 작성된 것으로 해석합니다.", + "Invalid_character_1127": "잘못된 문자입니다.", + "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "잘못된 가져오기 지정자 '{0}'에는 가능한 해결 방법이 없습니다.", + "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "확대의 모듈 이름이 잘못되었습니다. '{1}'에서 '{0}' 모듈이 형식화되지 않은 모듈로 확인되어 확대할 수 없습니다.", + "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "확대의 모듈 이름이 잘못되었습니다. '{0}' 모듈을 찾을 수 없습니다.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "새 식의 선택적 체인이 잘못되었습니다. '{0}()'을 호출하시겠습니까?", + "Invalid_reference_directive_syntax_1084": "'reference' 지시문 구문이 잘못되었습니다.", + "Invalid_syntax_in_decorator_1498": "데코레이터의 구문이 잘못되었습니다.", + "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "'{0}'을(를) 잘못 사용했습니다. 해당 항목은 클래스 정적 블록 내에서 사용할 수 없습니다.", + "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}'을(를) 잘못 사용했습니다. 모듈은 자동으로 strict 모드가 됩니다.", + "Invalid_use_of_0_in_strict_mode_1100": "strict 모드에서 '{0}'을(를) 잘못 사용했습니다.", + "Invalid_value_for_ignoreDeprecations_5103": "'--ignoreDeprecations'의 값이 잘못되었습니다.", + "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory'에 대한 값이 잘못되었습니다. '{0}'이(가) 올바른 식별자 또는 정규화된 이름이 아닙니다.", + "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035": "'jsxFragmentFactory'의 값이 잘못되었습니다. '{0}'은(는) 올바른 식별자 또는 정규화된 이름이 아닙니다.", + "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace'의 값이 잘못되었습니다. '{0}'은(는) 올바른 식별자가 아닙니다.", + "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796": "두 템플릿 식을 구분할 쉼표가 없는 것 같습니다. 이 두 템플릿 식은 태그가 지정된 호출 불가능한 하나의 템플릿 식을 구성합니다.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "해당 요소 형식 '{0}'은(는) 유효한 JSX 요소가 아닙니다.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "해당 인스턴스 형식 '{0}'은(는) 유효한 JSX 요소가 아닙니다.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "해당 반환 형식 '{0}'은(는) 유효한 JSX 요소가 아닙니다.", + "Its_type_0_is_not_a_valid_JSX_element_type_18053": "해당 '{0}' 형식은 올바른 JSX 요소 형식이 아닙니다.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}'이(가) 'extends {2}' 절과 일치하지 않습니다.", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}'이(가) 클래스에 연결되어 있지 않습니다.", + "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...'은 시그니처의 마지막 매개 변수에만 나타날 수 있습니다.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' 태그의 이름이 '{0}'인데 해당 이름의 매개 변수가 없습니다.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029": "JSDoc '@param' 태그에 '{0}' 이름이 있지만, 해당 이름의 매개 변수가 없습니다. 배열 형식이 있는 경우 '인수'를 일치시킵니다.", + "JSDoc_typedef_may_be_converted_to_TypeScript_type_80009": "JSDoc typedef를 TypeScript 형식으로 변환할 수 있습니다.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' 태그는 형식 주석을 포함하거나, '@property' 또는 '@member' 태그 앞에 와야 합니다.", + "JSDoc_typedefs_may_be_converted_to_TypeScript_types_80010": "JSDoc typedef를 TypeScript 형식으로 변환할 수 있습니다.", + "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 유형은 문서 주석 내에서만 사용될 수 있습니다.", + "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 형식이 TypeScript 형식으로 이동될 수 있습니다.", + "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX 특성에는 비어 있지 않은 '식'만 할당할 수 있습니다.", + "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 요소 '{0}'에 닫는 태그가 없습니다.", + "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 요소 클래스는 '{0}' 속성이 없으므로 특성을 지원하지 않습니다.", + "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026": "'JSX.{0}' 인터페이스가 없으므로 JSX 요소는 암시적으로 'any' 형식입니다.", + "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602": "전역 형식 'JSX.Element'가 없으므로 JSX 요소는 암시적으로 'any' 형식입니다.", + "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604": "JSX 요소 형식 '{0}'에 구문 또는 호출 시그니처가 없습니다.", + "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 요소에 이름이 같은 특성을 여러 개 사용할 수 없습니다.", + "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007": "JSX 식은 쉼표 연산자를 사용할 수 없습니다. 배열을 작성하시겠습니까?", + "JSX_expressions_must_have_one_parent_element_2657": "JSX 식에는 부모 요소가 하나 있어야 합니다.", + "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 조각에 닫는 태그가 없습니다.", + "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633": "JSX 속성 액세스 식은 JSX 네임스페이스 이름을 포함할 수 없습니다.", + "JSX_spread_child_must_be_an_array_type_2609": "JSX 분배 자식은 배열 형식이어야 합니다.", + "JavaScript_Support_6247": "JavaScript 지원", + "Jump_target_cannot_cross_function_boundary_1107": "점프 대상은 함수 경계를 벗어날 수 없습니다.", + "KIND_6034": "KIND", + "Keywords_cannot_contain_escape_characters_1260": "키워드에는 이스케이프 문자를 사용할 수 없습니다.", + "LOCATION_6037": "위치", + "Language_and_Environment_6254": "언어 및 환경", + "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695": "쉼표 연산자의 왼쪽은 사용되지 않으며 이로 인해 의도하지 않은 결과가 발생하지 않습니다.", + "Library_0_specified_in_compilerOptions_1422": "compilerOptions에 '{0}' 라이브러리가 지정되었습니다.", + "Library_referenced_via_0_from_file_1_1405": "'{1}' 파일에서 '{0}'을(를) 통해 라이브러리가 참조되었습니다.", + "Line_break_not_permitted_here_1142": "여기서는 줄 바꿈이 허용되지 않습니다.", + "Line_terminator_not_permitted_before_arrow_1200": "줄 마침 표시는 화살표 앞에 사용할 수 없습니다.", + "List_of_file_name_suffixes_to_search_when_resolving_a_module_6931": "모듈을 확인할 때 검색할 파일 이름 접미사 목록입니다.", + "List_of_folders_to_include_type_definitions_from_6161": "포함할 형식 정의가 있는 폴더의 목록입니다.", + "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "런타임에 프로젝트의 구조를 나타내는 결합된 콘텐츠가 있는 루트 폴더의 목록입니다.", + "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "루트 디렉터리 '{1}'에서 '{0}'을(를) 로드하고 있습니다. 후보 위치: '{2}'.", + "Loading_module_0_from_node_modules_folder_target_file_types_Colon_1_6098": "'node_modules' 폴더에서 '{0}' 모듈을 로드하고 있습니다. 대상 파일 형식은 '{1}'입니다.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1_6095": "모듈을 파일/폴더로 로드하고 있습니다. 후보 모듈 위치는 '{0}', 대상 파일 형식은 '{1}'입니다.", + "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "로캘이 또는 - 형식이어야 합니다. 예를 들어 '{0}' 또는 '{1}'입니다.", + "Log_paths_used_during_the_moduleResolution_process_6706": "'moduleResolution' 프로세스 동안 사용된 로그 경로입니다.", + "Longest_matching_prefix_for_0_is_1_6108": "'{0}'에 대해 일치하는 가장 긴 접두사는 '{1}'입니다.", + "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' 폴더에서 찾고 있습니다. 초기 위치: '{0}'.", + "Make_all_super_calls_the_first_statement_in_their_constructor_95036": "모든 'super()' 호출을 생성자의 첫 번째 문으로 만들기", + "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "keyof가 문자열, 숫자 또는 기호 대신 문자열만 반환하도록 합니다. 레거시 옵션입니다.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "생성자의 첫 번째 문을 'super()'로 호출", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "매핑된 개체 형식에는 'any' 템플릿 형식이 암시적으로 포함됩니다.", + "Mark_array_literal_as_const_90070": "배열 리터럴을 const로 표시", + "Matched_0_condition_1_6403": "'{0}' 조건 '{1}'과(와) 일치합니다.", + "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "기본적으로 일치되는 포함 패턴 '**/*'", + "Matched_by_include_pattern_0_in_1_1407": "'{1}'의 포함 패턴 '{0}'(으)로 일치되었습니다.", + "Member_0_implicitly_has_an_1_type_7008": "'{0}' 멤버에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "'{0}' 멤버는 암시적으로 '{1}' 형식이지만, 사용량에서 더 나은 형식을 유추할 수 있습니다.", + "Merge_conflict_marker_encountered_1185": "병합 충돌 표식을 발견했습니다.", + "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "병합된 선언 '{0}'에는 기본 내보내기 선언을 포함할 수 없습니다. 대신 별도의 'export default {0}' 선언을 추가하세요.", + "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "메타 속성 '{0}'은(는) 함수 선언, 함수 식 또는 생성기의 본문에서만 사용할 수 있습니다.", + "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "'{0}' 메서드는 abstract로 표시되어 있으므로 구현이 있을 수 없습니다.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "내보낸 인터페이스의 '{0}' 메서드가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "내보낸 인터페이스의 '{0}' 메서드가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9008": "메서드에는 --isolatedDeclarations가 있는 명시적 반환 형식 주석이 있어야 합니다.", + "Method_not_implemented_95158": "메서드가 구현되지 않았습니다.", + "Modifiers_cannot_appear_here_1184": "한정자를 여기에 표시할 수 없습니다.", + "Module_0_can_only_be_default_imported_using_the_1_flag_1259": "'{0}' 모듈은 '{1}' 플래그를 사용하는 가져온 기본값이어야만 합니다.", + "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471": "이 구문을 사용하여 '{0}' 모듈을 가져올 수 없습니다. 지정자는 'require'로 가져올 수 없는 ES 모듈로만 확인됩니다. ECMAScript 가져오기를 대신 사용하세요.", + "Module_0_declares_1_locally_but_it_is_exported_as_2_2460": "'{0}' 모듈은 '{1}'을(를) 로컬로 선언하지만, 모듈을 '{2}'(으)로 내보냅니다.", + "Module_0_declares_1_locally_but_it_is_not_exported_2459": "'{0}' 모듈은 '{1}'을(를) 로컬로 선언하지만, 모듈을 내보내지 않습니다.", + "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340": "모듈 '{0}'은(는) 형식을 참조하지 않지만, 여기에서 형식으로 사용됩니다. 'typeof 가져오기('{0}')'를 사용하시겠습니까?", + "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "모듈 '{0}'은(는) 값을 참조하지 않지만, 여기에서 값으로 사용됩니다.", + "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "{0} 모듈에서 '{1}'(이)라는 멤버를 이미 내보냈습니다. 모호성을 해결하려면 명시적으로 다시 내보내는 것이 좋습니다.", + "Module_0_has_no_default_export_1192": "모듈 '{0}'에는 기본 내보내기가 없습니다.", + "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613": "'{0}' 모듈에 기본 내보내기가 없습니다. 대신 '{0}에서 { {1} } 가져오기'를 사용하시겠습니까?", + "Module_0_has_no_exported_member_1_2305": "'{0}' 모듈에 내보낸 멤버 '{1}'이(가) 없습니다.", + "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614": "'{0}' 모듈에 내보낸 멤버 '{1}'이(가) 없습니다. 대신 '{0}에서 {1} 가져오기'를 사용하시겠습니까?", + "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "'{0}' 모듈은 이름이 같은 로컬 선언으로 숨겨집니다.", + "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "모듈 '{0}'은(는) 'export ='을 사용하며 'export *'와 함께 사용할 수 없습니다.", + "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "'{0}' 모듈은 '{1}'에서 지역으로 선언된 앰비언트 모듈로 확인되었습니다.", + "Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set_6263": "'{0}' 모듈이 '{1}'(으)로 확인되었지만 '--allowArbitraryExtensions'가 설정되지 않았습니다.", + "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "모듈 '{0}'이(가) '{1}'(으)로 확인되었지만 '--jsx'가 설정되지 않았습니다.", + "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042": "'{0}' 모듈이 '{1}'(으)로 확인되었지만 '--resolveJsonModule'이 사용되지 않았습니다.", + "Module_declaration_names_may_only_use_or_quoted_strings_1443": "모듈 선언 이름에는 ' 또는 \" 인용 문자열만 사용할 수 있습니다.", + "Module_name_0_matched_pattern_1_6092": "모듈 이름: '{0}', 일치하는 패턴: '{1}'", + "Module_name_0_was_not_resolved_6090": "======== 모듈 이름 '{0}'이(가) 확인되지 않았습니다. ========", + "Module_name_0_was_successfully_resolved_to_1_6089": "======== 모듈 이름 '{0}'이(가) '{1}'(으)로 확인되었습니다. ========", + "Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2_6218": "======== 모듈 이름 '{0}'이(가) 패키지 ID가 '{2}'인 '{1}'(으)로 확인되었습니다. ========", + "Module_resolution_kind_is_not_specified_using_0_6088": "모듈 확인 종류가 지정되지 않았습니다. '{0}'을(를) 사용합니다.", + "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs'를 사용한 모듈 확인에 실패했습니다.", + "Modules_6244": "모듈", + "Move_labeled_tuple_element_modifiers_to_labels_95117": "레이블이 지정된 튜플 요소 한정자를 레이블로 이동", + "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036": "기본 내보내기에서 식을 변수로 이동하고 형식 주석을 추가합니다.", + "Move_to_a_new_file_95049": "새 파일로 이동", + "Move_to_file_95178": "파일로 이동", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "여러 개의 연속된 숫자 구분 기호는 허용되지 않습니다.", + "Multiple_constructor_implementations_are_not_allowed_2392": "여러 생성자 구현은 허용되지 않습니다.", + "NEWLINE_6061": "줄 바꿈", + "Name_is_not_valid_95136": "이름이 잘못되었습니다.", + "Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later_1503": "명명된 캡처 그룹은 'ES2018' 이상을 대상으로 하는 경우에만 사용할 수 있습니다.", + "Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other_1515": "이름이 같은 명명된 캡처 그룹은 상호 배타적이어야 합니다.", + "Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0_1544": "'module'이 '{0}'(으)로 설정된 경우 JSON 파일에서 ECMAScript 모듈로 명명된 가져오기를 사용할 수 없습니다.", + "Named_property_0_of_types_1_and_2_are_not_identical_2319": "명명된 속성 '{0}'의 형식 '{1}' 및 '{2}'이(가) 동일하지 않습니다.", + "Namespace_0_has_no_exported_member_1_2694": "'{0}' 네임스페이스에 내보낸 멤버 '{1}'이(가) 없습니다.", + "Namespace_must_be_given_a_name_1437": "네임스페이스에 이름을 지정해야 합니다.", + "Namespace_name_cannot_be_0_2819": "네임스페이스 이름은 '{0}'일 수 없습니다.", + "Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to__1280": "'{0}'이(가) 사용하도록 설정된 경우 전역 스크립트 파일에서는 네임스페이스를 사용할 수 없습니다. 이 파일이 전역 스크립트가 아닌 경우 'moduleDetection'을 'force'로 설정하거나 빈 'export {}' 문을 추가합니다.", + "Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters_1433": "데코레이터와 한정자를 'this' 매개 변수에 적용할 수 없습니다.", + "No_base_constructor_has_the_specified_number_of_type_arguments_2508": "기본 생성자에 지정된 수의 형식 인수가 없습니다.", + "No_constituent_of_type_0_is_callable_2755": "'{0}' 형식의 구성원을 호출할 수 없습니다.", + "No_constituent_of_type_0_is_constructable_2759": "'{0}' 형식의 구성원을 생성할 수 없습니다.", + "No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1_7054": "'{1}' 형식에서 '{0}' 형식의 매개 변수가 포함된 인덱스 시그니처를 찾을 수 없습니다.", + "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "'{0}' 구성 파일에서 입력을 찾을 수 없습니다. 지정된 '포함' 경로는 '{1}'이고 '제외' 경로는 '{2}'이었습니다.", + "No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files_6608": "더 이상 지원되지 않습니다. 초기 버전에서는 파일을 읽기 위한 텍스트 인코딩을 수동으로 설정합니다.", + "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575": "오버로드에 {0} 인수가 필요하지 않지만, {1} 또는 {2} 인수가 필요한 오버로드가 있습니다.", + "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743": "오버로드에 {0} 형식 인수가 필요하지 않지만, {1} 또는 {2} 형식 인수가 필요한 오버로드가 있습니다.", + "No_overload_matches_this_call_2769": "이 호출과 일치하는 오버로드가 없습니다.", + "No_type_could_be_extracted_from_this_type_node_95134": "이 형식 노드에서 형식을 추출할 수 없습니다.", + "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004": "줄임 속성 '{0}'의 범위에 값이 없습니다. 값을 선언하거나 이니셜라이저를 제공합니다.", + "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "'{0}' 비추상 클래스는 '{2}' 클래스에서 상속된 추상 멤버 '{1}'을(를) 구현하지 않습니다.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_2654": "비추상 클래스 '{0}'에 '{1}'의 다음 멤버에 대한 구현이 없습니다. {2}.", + "Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more_2655": "비추상 클래스 '{0}'에 '{1}'의 다음 멤버에 대한 구현이 없습니다. {2} 및 {3} 등.", + "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "비추상 클래스 식은 '{1}' 클래스에서 상속된 추상 멤버 '{0}'을(를) 구현하지 않습니다.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_2656": "비추상 클래스 식에 '{0}'의 다음 멤버에 대한 구현이 없습니다. {1}.", + "Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and__2650": "비추상 클래스 식에 '{0}'의 다음 멤버에 대한 구현이 없습니다. {1} 및 {2} 등.", + "Non_null_assertions_can_only_be_used_in_TypeScript_files_8013": "null이 아닌 어설션은 TypeScript 파일에서만 사용할 수 있습니다.", + "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090": "'baseUrl'이 설정되지 않은 경우 상대 경로가 아닌 경로는 허용되지 않습니다. 선행 './'를 잊으셨습니까?", + "Non_simple_parameter_declared_here_1348": "여기서 단순하지 않은 매개 변수가 선언되었습니다.", + "Not_all_code_paths_return_a_value_7030": "일부 코드 경로가 값을 반환하지 않습니다.", + "Not_all_constituents_of_type_0_are_callable_2756": "'{0}' 형식의 일부 구성원을 호출할 수 없습니다.", + "Not_all_constituents_of_type_0_are_constructable_2760": "'{0}' 형식의 일부 구성원을 생성할 수 없습니다.", + "Numbers_out_of_order_in_quantifier_1506": "수량자의 숫자가 순서를 벗어났습니다.", + "Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accur_80008": "절대값이 2^53보다 크거나 같은 숫자 리터럴은 너무 커서 정수로 정확하게 표시할 수 없습니다.", + "Numeric_separators_are_not_allowed_here_6188": "숫자 구분 기호는 여기에서 허용되지 않습니다.", + "Object_is_of_type_unknown_2571": "개체가 '알 수 없는' 형식입니다.", + "Object_is_possibly_null_2531": "개체가 'null'인 것 같습니다.", + "Object_is_possibly_null_or_undefined_2533": "개체가 'null' 또는 'undefined'인 것 같습니다.", + "Object_is_possibly_undefined_2532": "개체가 'undefined'인 것 같습니다.", + "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353": "개체 리터럴은 알려진 속성만 지정할 수 있으며 '{1}' 형식에 '{0}'이(가) 없습니다.", + "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561": "개체 리터럴은 알려진 속성만 지정할 수 있지만 '{1}' 형식에 '{0}'이(가) 없습니다. '{2}'을(를) 쓰려고 했습니까?", + "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "개체 리터럴의 '{0}' 속성에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations_9016": "약식 속성이 포함된 개체는 --isolatedDeclarations를 사용하여 유추할 수 없습니다.", + "Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations_9015": "분산 할당이 포함된 개체는 --isolatedDeclarations를 사용하여 유추할 수 없습니다.", + "Octal_digit_expected_1178": "8진수가 있어야 합니다.", + "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536": "문자 클래스에서는 8진수 이스케이프 시퀀스 및 역참조를 사용할 수 없습니다. 이 시퀀스가 이스케이프 시퀀스로 의도된 경우 대신 '{0}' 구문을 사용합니다.", + "Octal_escape_sequences_are_not_allowed_Use_the_syntax_0_1487": "8진수 이스케이프 시퀀스는 허용되지 않습니다. '{0}' 구문을 사용합니다.", + "Octal_literals_are_not_allowed_Use_the_syntax_0_1121": "8진수 리터럴은 허용되지 않습니다. '{0}' 구문을 사용합니다.", + "One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value_4126": "'{0}.{1}'의 한 값은 '{2}' 문자열이며, 다른 값은 알 수 없는 숫자 값으로 간주됩니다.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' 문에는 단일 변수 선언만 허용됩니다.", + "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' 문에는 단일 변수 선언만 허용됩니다.", + "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "void 함수만 'new' 키워드로 호출할 수 있습니다.", + "Only_ambient_modules_can_use_quoted_names_1035": "앰비언트 모듈만 따옴표가 붙은 이름을 사용할 수 있습니다.", + "Only_amd_and_system_modules_are_supported_alongside_0_6082": "'amd' 및 'system' 모듈만 --{0}과(와) 함께 사용할 수 있습니다.", + "Only_const_arrays_can_be_inferred_with_isolatedDeclarations_9017": "const 배열만 --isolatedDeclarations를 사용하여 유추할 수 있습니다.", + "Only_emit_d_ts_declaration_files_6014": "'.d.ts' 선언 파일만 내보냅니다.", + "Only_output_d_ts_files_and_not_JavaScript_files_6623": "JavaScript 파일은 출력하지 않고 d.ts 파일만 출력합니다.", + "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "기본 클래스의 공용 및 보호된 메서드만 'super' 키워드를 통해 액세스할 수 있습니다.", + "Operator_0_cannot_be_applied_to_type_1_2736": "'{0}' 연산자는 '{1}' 형식에 적용할 수 없습니다.", + "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "'{0}' 연산자를 '{1}' 및 '{2}' 형식에 적용할 수 없습니다.", + "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519": "연산자는 문자 클래스 내에서 혼합될 수 없습니다. 대신 중첩 클래스에서 래핑합니다.", + "Opt_a_project_out_of_multi_project_reference_checking_when_editing_6619": "편집할 때 다중 프로젝트 참조 검사에서 프로젝트를 옵트아웃합니다.", + "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108": "'{0}={1}' 옵션이 제거되었습니다. 구성에서 제거하세요.", + "Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDepr_5107": "'{0}={1}' 옵션은 더 이상 사용되지 않으며 TypeScript {2}에서 작동하지 않습니다. 이 오류를 무시하려면 compilerOption '\"ignoreDeprecations\": \"{3}\"'을(를) 지정합니다.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230": "'{0}' 옵션은 'tsconfig. json' 파일에만 지정하거나 명령줄에서 'false' 또는 'null'로 설정할 수 있습니다.", + "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064": "'{0}' 옵션은 'tsconfig. json' 파일에만 지정하거나 명령줄에서 'null'로 설정할 수 있습니다.", + "Option_0_can_only_be_specified_on_command_line_6266": "'{0}' 옵션은 명령줄에서만 지정할 수 있습니다.", + "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "'{0}' 옵션은 '--inlineSourceMap' 옵션 또는 '--sourceMap' 옵션이 제공되는 경우에만 사용할 수 있습니다.", + "Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler_5098": "'moduleResolution'이 'node16', 'nodenext' 또는 'bundler'로 설정된 경우에만 '{0}' 옵션을 사용할 수 있습니다.", + "Option_0_can_only_be_used_when_module_is_set_to_preserve_or_to_es2015_or_later_5095": "'{0}' 옵션은 'module'이 'preserve' 또는 'es2015' 이상으로 설정된 경우에만 사용할 수 있습니다.", + "Option_0_cannot_be_specified_when_option_jsx_is_1_5089": "'jsx' 옵션이 '{1}'인 경우 '{0}' 옵션을 지정할 수 없습니다.", + "Option_0_cannot_be_specified_with_option_1_5053": "'{0}' 옵션은 '{1}' 옵션과 함께 지정할 수 없습니다.", + "Option_0_cannot_be_specified_without_specifying_option_1_5052": "'{1}' 옵션을 지정하지 않고 '{0}' 옵션을 지정할 수 없습니다.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "'{1}' 또는 '{2}' 옵션을 지정하지 않고 '{0}' 옵션을 지정할 수 없습니다.", + "Option_0_has_been_removed_Please_remove_it_from_your_configuration_5102": "‘{0}’ 옵션이 제거되었습니다. 구성에서 제거하세요.", + "Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprec_5101": "'{0}’ 옵션은 더 이상 사용되지 않으며 TypeScript {1}에서 작동하지 않습니다. 이 오류를 무시하려면 compilerOption '\"ignoreDeprecations\": \"{2}\"'을(를) 지정합니다.", + "Option_0_is_redundant_and_cannot_be_specified_with_option_1_5104": "'{0}' 옵션은 중복되므로 '{1}' 옵션으로 지정할 수 없습니다.", + "Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set_5096": "'allowImportingTsExtensions' 옵션은 'noEmit' 또는 'emitDeclarationOnly'가 설정된 경우에만 사용할 수 있습니다.", + "Option_build_must_be_the_first_command_line_argument_6369": "'--build' 옵션은 첫 번째 명령줄 인수여야 합니다.", + "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074": "'--incremental' 옵션은 tsconfig를 사용하거나 단일 파일로 내보내서 지정하거나 '--tsBuildInfoFile' 옵션을 지정할 때만 지정할 수 있습니다.", + "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' 옵션은 '--module' 옵션을 지정하거나 'target' 옵션이 'ES2015' 이상인 경우에만 사용할 수 있습니다.", + "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109": "'module' 옵션이 ‘{1}'(으)로 설정된 경우 'moduleResolution' 옵션을 '{0}'(또는 지정되지 않은 상태로 두어야 함)(으)로 설정해야 합니다.", + "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110": "'moduleResolution' 옵션이 '{1}'으(로) 설정된 경우 'module' 옵션을 '{0}'(으)로 설정해야 합니다.", + "Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled_5091": "'{0}'이(가) 사용하도록 설정된 경우 'preserveConstEnums' 옵션을 사용하지 않도록 설정할 수 없습니다.", + "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "명령줄에서 'project' 옵션을 원본 파일과 혼합하여 사용할 수 없습니다.", + "Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic_5070": "'moduleResolution'이 'classic'으로 설정된 경우 '--resolveJsonModule' 옵션을 지정할 수 없습니다.", + "Option_resolveJsonModule_cannot_be_specified_when_module_is_set_to_none_system_or_umd_5071": "'module'이 'none', 'system' 또는 'umd'로 설정된 경우 '--resolveJsonModule' 옵션을 지정할 수 없습니다.", + "Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System_5105": "'module'이 'UMD', 'AMD' 또는 'System'으로 설정된 경우 'verbatimModuleSyntax' 옵션을 사용할 수 없습니다.", + "Options_0_and_1_cannot_be_combined_6370": "'{0}' 및 '{1}' 옵션은 조합할 수 없습니다.", + "Options_Colon_6027": "옵션:", + "Output_Formatting_6256": "출력 서식 지정", + "Output_compiler_performance_information_after_building_6615": "빌드 후 컴파일러 성능 정보를 출력합니다.", + "Output_directory_for_generated_declaration_files_6166": "생성된 선언 파일의 출력 디렉터리입니다.", + "Output_file_0_has_not_been_built_from_source_file_1_6305": "출력 파일 '{0}'이(가) 소스 파일 '{1}'에서 빌드되지 않았습니다.", + "Output_from_referenced_project_0_included_because_1_specified_1411": "'{1}'이(가) 지정되었기 때문에 참조된 프로젝트 '{0}'의 출력이 포함됩니다.", + "Output_from_referenced_project_0_included_because_module_is_specified_as_none_1412": "'--module'이 'none'으로 지정되었기 때문에 참조된 프로젝트 '{0}'의 출력이 포함됩니다.", + "Output_more_detailed_compiler_performance_information_after_building_6632": "빌드 후 더 자세한 컴파일러 성능 정보를 출력합니다.", + "Overload_0_of_1_2_gave_the_following_error_2772": "오버로드 {0}/{1}('{2}')에서 다음 오류가 발생했습니다.", + "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "오버로드 시그니처는 모두 추상이거나 비추상이어야 합니다.", + "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "오버로드 시그니처는 모두 앰비언트이거나 앰비언트가 아니어야 합니다.", + "Overload_signatures_must_all_be_exported_or_non_exported_2383": "오버로드 시그니처는 모두 내보내거나 모두 내보내지 않아야 합니다.", + "Overload_signatures_must_all_be_optional_or_required_2386": "오버로드 시그니처는 모두 선택 사항이거나 필수 사항이어야 합니다.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "오버로드 시그니처는 모두 퍼블릭, 프라이빗 또는 보호된 상태여야 합니다.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "매개 변수 '{0}'은(는) 이 매개 변수 뒤에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", + "Parameter_0_cannot_reference_itself_2372": "매개 변수 '{0}'은(는) 자신을 참조할 수 없습니다.", + "Parameter_0_implicitly_has_an_1_type_7006": "'{0}' 매개 변수에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "'{0}' 매개 변수는 암시적으로 '{1}' 형식이지만, 사용량에서 더 나은 형식을 유추할 수 있습니다.", + "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "'{0}' 매개 변수는 '{1}' 매개 변수와 같은 위치에 있지 않습니다.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4108": "접근자의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2_4107": "접근자의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_accessor_has_or_is_using_private_name_1_4106": "접근자의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "내보낸 함수의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "내보낸 함수의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "내보낸 함수의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_cannot_have_question_mark_and_initializer_1015": "매개 변수에 물음표와 이니셜라이저를 사용할 수 없습니다.", + "Parameter_declaration_expected_1138": "매개 변수 선언이 필요합니다.", + "Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051": "매개 변수에 이름이 있지만 형식이 없습니다. '{0}: {1}'을(를) 사용하시겠습니까?", + "Parameter_modifiers_can_only_be_used_in_TypeScript_files_8012": "매개 변수 한정자는 TypeScript 파일에서만 사용할 수 있습니다.", + "Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9011": "매개 변수에는 --isolatedDeclarations가 있는 명시적 형식 주석이 있어야 합니다.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 프라이빗 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 프라이빗 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "strict 모드에서 구문 분석하고 각 소스 파일에 대해 \"use strict\"를 내보냅니다.", + "Part_of_files_list_in_tsconfig_json_1409": "tsconfig.json의 'files' 목록의 일부", + "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "'{0}' 패턴에는 '*' 문자를 최대 하나만 사용할 수 있습니다.", + "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386": "이 세션에서는 '--diagnostics' 또는 '--extendedDiagnostics'에 대해 성능 타이밍을 사용할 수 없습니다. Web Performance API의 네이티브 구현을 찾을 수 없습니다.", + "Platform_specific_6912": "플랫폼별", + "Prefix_0_with_an_underscore_90025": "'{0}' 앞에 밑줄 추가", + "Prefix_all_incorrect_property_declarations_with_declare_95095": "모든 잘못된 속성 선언에 'declare'를 접두사로 추가", + "Prefix_all_unused_declarations_with_where_possible_95025": "가능한 경우 사용하지 않는 모든 선언에 '_'을 접두사로 추가", + "Prefix_with_declare_95094": "'declare'를 접두사로 추가", + "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449": "JavaScript 출력에서 사용되지 않는 가져온 값을 유지합니다. 그렇지 않으면 제거됩니다.", + "Print_all_of_the_files_read_during_the_compilation_6653": "컴파일 중에 읽은 모든 파일을 출력합니다.", + "Print_files_read_during_the_compilation_including_why_it_was_included_6631": "컴파일 중에 읽은 파일을 포함 이유와 함께 출력합니다.", + "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505": "파일의 이름과 해당 파일이 컴파일에 포함된 이유를 출력합니다.", + "Print_names_of_files_part_of_the_compilation_6155": "컴파일의 일부인 파일의 이름을 인쇄합니다.", + "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "컴파일에 포함된 파일의 이름을 인쇄한 다음, 처리를 중지합니다.", + "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", + "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", + "Print_the_final_configuration_instead_of_building_1350": "빌드 대신 최종 구성을 인쇄합니다.", + "Print_the_names_of_emitted_files_after_a_compilation_6652": "컴파일 후 내보낸 파일의 이름을 출력합니다.", + "Print_this_message_6017": "이 메시지를 출력합니다.", + "Private_accessor_was_defined_without_a_getter_2806": "프라이빗 접근자가 getter 없이 정의되었습니다.", + "Private_field_0_must_be_declared_in_an_enclosing_class_1111": "'{0}' 프라이빗 필드는 외부 클래스에서 선언되어야 합니다.", + "Private_identifiers_are_not_allowed_in_variable_declarations_18029": "변수 선언에서 프라이빗 식별자를 사용할 수 없습니다.", + "Private_identifiers_are_not_allowed_outside_class_bodies_18016": "클래스 본문 외부에서 프라이빗 식별자를 사용할 수 없습니다.", + "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451": "비공개 식별자는 클래스 본문에서만 허용되며 클래스 멤버 선언의 일부, 속성 액세스 또는 'in' 식의 왼쪽에서만 사용할 수 있습니다.", + "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028": "프라이빗 식별자는 ECMAScript 2015 이상을 대상으로 지정할 때만 사용할 수 있습니다.", + "Private_identifiers_cannot_be_used_as_parameters_18009": "프라이빗 식별자는 매개 변수로 사용할 수 없습니다.", + "Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter_4105": "형식 매개 변수에서 프라이빗 또는 보호된 멤버 '{0}'에 액세스할 수 없습니다.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Project '{0}' can't be built because its dependency '{1}' has errors", + "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Project '{0}' can't be built because its dependency '{1}' was not built", + "Project_0_is_being_forcibly_rebuilt_6388": "'{0}' 프로젝트가 강제로 재구축되고 있습니다.", + "Project_0_is_out_of_date_because_1_6420": "{1} 때문에 ' {0}' 프로젝트가 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_6412": "'{1}' buildinfo 파일이 '{2}' 파일이 컴파일의 루트 파일이었지만 더 이상 아님을 나타내므로 '{0}' 프로젝트는 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419": "'{1}' buildinfo 파일은 프로그램에서 오류를 보고해야 함을 나타내기 때문에 '{0}' 프로젝트는 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "buildinfo 파일 '{1}'이(가) 일부 변경 내용이 내보내지지 않았음을 나타내므로 프로젝트 '{0}'은(는) 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions_6406": "'{1}' buildinfo 파일이 compilerOptions에 변경이 있음을 나타내므로 '{0}' 프로젝트는 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "'{1}' 종속성이 최신 상태가 아니기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "출력 '{1}'이(가) 최신 입력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "'{1}' 출력 파일이 존재하지 않기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "'{0}' 프로젝트의 출력이 현재 버전 '{2}'과(와) 다른 '{1}' 버전으로 생성되었기 때문에 이 프로젝트가 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401": "'{1}' 파일을 읽는 동안 오류가 발생하여 프로젝트 '{0}'이(가) 만료되었습니다.", + "Project_0_is_up_to_date_6361": "'{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "최신 입력 '{1}'이(가) 출력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "프로젝트 '{0}'이(가) 최신 상태이지만 입력 파일보다 오래된 출력 파일의 타임스탬프를 업데이트해야 합니다.", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "'{0}' 프로젝트는 종속성에 .d.ts 파일이 있는 최신 상태입니다.", + "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}", + "Projects_6255": "프로젝트", + "Projects_in_this_build_Colon_0_6355": "이 빌드의 프로젝트: {0}", + "Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher_18045": "'accessor' 한정자가 있는 속성은 ECMAScript 2015 이상을 대상으로 하는 경우에만 사용할 수 있습니다.", + "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267": "'{0}' 속성은 추상으로 표시되어 있으므로 이니셜라이저를 사용할 수 없습니다.", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "'{0}' 속성은 인덱스 시그니처에서 가져오는 것이므로 ['{0}']을(를) 사용하여 액세스해야 합니다.", + "Property_0_does_not_exist_on_type_1_2339": "'{1}' 형식에 '{0}' 속성이 없습니다.", + "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' 속성이 '{1}' 형식에 없습니다. '{2}'을(를) 사용하시겠습니까?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "'{0}' 속성이 '{1}' 형식에 없습니다. 대신 정적 멤버 '{2}'에 액세스하려고 하셨습니까?", + "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "'{0}' 속성이 '{1}' 형식에 없습니다. 대상 라이브러리를 변경해야 하는 경우 'lib' 컴파일러 옵션을 '{2}' 이상으로 변경해 보세요.", + "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812": "속성 '{0}'(은)는 '{1}'에 없습니다. 'lib' 컴파일러 옵션을 변경하여 'dom'을 포함하세요.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_a_class_static_block_2817": "'{0}' 속성에 이니셜라이저가 없으며 클래스 정적 블록에 확실히 할당되지 않았습니다.", + "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "속성 '{0}'은(는) 이니셜라이저가 없고 생성자에 할당되어 있지 않습니다.", + "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' 속성에는 해당 get 접근자에 반환 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' 속성에는 해당 set 접근자에 매개 변수 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048": "'{0}' 속성은 암시적으로 'any' 형식이지만, 사용량에서 get 접근자의 더 나은 형식을 유추할 수 있습니다.", + "Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049": "'{0}' 속성은 암시적으로 'any' 형식이지만, 사용량에서 set 접근자의 더 나은 형식을 유추할 수 있습니다.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "'{1}' 형식의 '{0}' 속성을 기본 형식 '{2}'의 동일한 속성에 할당할 수 없습니다.", + "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' 형식의 '{0}' 속성을 '{2}' 형식에 할당할 수 없습니다.", + "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "'{1}' 형식의 '{0}' 속성이 '{2}' 형식 내에서 액세스할 수 없는 다른 멤버를 참조합니다.", + "Property_0_is_declared_but_its_value_is_never_read_6138": "속성 '{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", + "Property_0_is_incompatible_with_index_signature_2530": "'{0}' 속성이 인덱스 시그니처와 호환되지 않습니다.", + "Property_0_is_missing_in_type_1_2324": "'{0}' 속성이 '{1}' 형식에 없습니다.", + "Property_0_is_missing_in_type_1_but_required_in_type_2_2741": "'{0}' 속성이 '{1}' 형식에 없지만 '{2}' 형식에서 필수입니다.", + "Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier_18013": "'{0}' 속성은 프라이빗 식별자를 포함하기 때문에 '{1}' 클래스 외부에서 액세스할 수 없습니다.", + "Property_0_is_optional_in_type_1_but_required_in_type_2_2327": "'{0}' 속성은 '{1}' 형식에서 선택적이지만 '{2}' 형식에서는 필수입니다.", + "Property_0_is_private_and_only_accessible_within_class_1_2341": "'{0}' 속성은 private이며 '{1}' 클래스 내에서만 액세스할 수 있습니다.", + "Property_0_is_private_in_type_1_but_not_in_type_2_2325": "'{0}' 속성은 '{1}' 형식에서 private이지만 '{2}' 형식에서는 그렇지 않습니다.", + "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446": "'{0}' 속성은 보호되며 '{1}' 클래스의 인스턴스를 통해서만 액세스할 수 있습니다. 이는 '{2}' 클래스의 인스턴스입니다.", + "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445": "'{0}' 속성은 보호된 속성이며 '{1}' 클래스 및 해당 하위 클래스 내에서만 액세스할 수 있습니다.", + "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443": "'{0}' 속성은 보호된 속성이지만 '{1}' 형식은 '{2}'에서 파생된 클래스가 아닙니다.", + "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "'{0}' 속성은 '{1}' 형식에서는 보호된 속성이지만 '{2}' 형식에서는 공용입니다.", + "Property_0_is_used_before_being_assigned_2565": "'{0}' 속성이 할당되기 전에 사용되었습니다.", + "Property_0_is_used_before_its_initialization_2729": "초기화하기 전에 '{0}' 속성이 사용됩니다.", + "Property_0_may_not_exist_on_type_1_Did_you_mean_2_2568": "'{0}' 속성이 '{1}' 형식에 없을 수 있습니다. '{2}'을(를) 사용하시겠습니까?", + "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX 분배 특성의 '{0}' 속성을 대상 속성에 할당할 수 없습니다.", + "Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected_4094": "내보낸 익명 클래스 형식의 '{0}' 속성은 비공개이거나 보호됨이 아닐 수 있습니다.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "내보낸 인터페이스의 '{0}' 속성이 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "내보낸 인터페이스의 '{0}' 속성이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Property_0_of_type_1_is_not_assignable_to_2_index_type_3_2411": "'{0}' 형식의 '{1}' 속성을 '{2}' 인덱스 유형 '{3}'에 할당할 수 없습니다.", + "Property_0_was_also_declared_here_2733": "여기서도 '{0}' 속성이 선언되었습니다.", + "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612": "'{0}' 속성은 '{1}'의 기본 속성을 덮어씁니다. 의도적인 경우 이니셜라이저를 추가합니다. 그렇지 않으면 'declare' 한정자를 추가하거나 중복 선언을 제거합니다.", + "Property_assignment_expected_1136": "속성 할당이 필요합니다.", + "Property_destructuring_pattern_expected_1180": "속성 구조 파괴 패턴이 필요합니다.", + "Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9012": "속성에는 --isolatedDeclarations가 있는 명시적 형식 주석이 있어야 합니다.", + "Property_or_signature_expected_1131": "속성 또는 서명이 필요합니다.", + "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "속성 값은 문자열 리터럴, 숫자 리터럴, 'true', 'false', 'null', 개체 리터럴 또는 배열 리터럴이어야 합니다.", + "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_6179": "'ES5'를 대상으로 할 경우 'for-of', 분산 및 파괴의 반복 가능한 개체를 완벽히 지원합니다.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "내보낸 클래스의 공용 메서드 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "내보낸 클래스의 공용 메서드 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "내보낸 클래스의 공용 메서드의 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "내보낸 클래스의 공용 속성 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "내보낸 클래스의 공용 속성 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "내보낸 클래스의 공용 속성 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "내보낸 클래스의 공용 정적 메서드 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "내보낸 클래스에 있는 공용 정적 메서드 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "내보낸 클래스의 공용 정적 메서드 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "내보낸 클래스에 있는 공용 정적 속성 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032": "정규화된 이름 '{0}'은(는) 선행 '@param {object} {1}'과(와) 함께 사용해야 합니다.", + "Raise_an_error_when_a_function_parameter_isn_t_read_6676": "함수 매개 변수를 읽지 않으면 오류가 발생합니다.", + "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "암시된 'any' 형식이 있는 식 및 선언에서 오류를 발생합니다.", + "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.", + "Range_out_of_order_in_character_class_1517": "문자 클래스의 범위가 순서를 벗어났습니다.", + "Re_exporting_a_type_when_0_is_enabled_requires_using_export_type_1205": "'{0}'을 사용하도록 설정한 경우 형식을 다시 내보내려면 'export type'을 사용해야 합니다.", + "React_components_cannot_include_JSX_namespace_names_2639": "React 구성 요소에는 JSX 네임스페이스 이름을 포함할 수 없습니다.", + "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", + "Reduce_the_number_of_projects_loaded_automatically_by_TypeScript_6617": "TypeScript에서 자동으로 로드되는 프로젝트 수를 줄입니다.", + "Referenced_project_0_may_not_disable_emit_6310": "참조된 프로젝트 '{0}'은(는) 내보내기를 사용하지 않도록 설정할 수 없습니다.", + "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "참조되는 프로젝트 '{0}'에는 \"composite\": true 설정이 있어야 합니다.", + "Referenced_via_0_from_file_1_1400": "'{1}' 파일에서 '{0}'을(를) 통해 참조되었습니다.", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2834": "'--moduleResolution'이 'node16' 또는 'nodenext'인 경우 상대 가져오기 경로에는 ECMAScript 가져오기의 명시적 파일 확장자가 필요합니다. 가져오기 경로에 확장자를 추가하는 것을 고려하세요.", + "Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_n_2835": "'--moduleResolution'이 'node16' 또는 'nodenext'인 경우 상대 가져오기 경로에는 ECMAScript 가져오기의 명시적 파일 확장자가 필요합니다. '{0}'을(를) 사용하시겠습니까?", + "Remove_a_list_of_directories_from_the_watch_process_6628": "감시 프로세스에서 디렉터리 목록을 제거합니다.", + "Remove_a_list_of_files_from_the_watch_mode_s_processing_6629": "감시 모드의 처리에서 파일 목록을 제거합니다.", + "Remove_all_unnecessary_override_modifiers_95163": "불필요한 'override' 한정자 모두 제거", + "Remove_all_unnecessary_uses_of_await_95087": "불필요한 'await' 사용 모두 제거", + "Remove_all_unreachable_code_95051": "접근할 수 없는 코드 모두 제거", + "Remove_all_unused_labels_95054": "사용되지 않는 레이블 모두 제거", + "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115": "관련 문제가 있는 모든 화살표 함수 본문에서 중괄호 제거", + "Remove_braces_from_arrow_function_95060": "화살표 함수에서 중괄호 제거", + "Remove_braces_from_arrow_function_body_95112": "화살표 함수 본문에서 중괄호 제거", + "Remove_import_from_0_90005": "'{0}'에서 가져오기 제거", + "Remove_override_modifier_95161": "'override' 한정자 제거", + "Remove_parentheses_95126": "괄호 제거", + "Remove_template_tag_90011": "템플릿 태그 제거", + "Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server_6618": "TypeScript 언어 서버에서 JavaScript 파일의 총 소스 코드 크기에 적용되는 20MB 제한을 제거합니다.", + "Remove_type_from_import_declaration_from_0_90055": "\"{0}\"의 가져오기 선언에서 '형식' 제거", + "Remove_type_from_import_of_0_from_1_90056": "\"{1}\"의 '{0}' 가져오기에서 '형식' 제거", + "Remove_type_parameters_90012": "형식 매개 변수 제거", + "Remove_unnecessary_await_95086": "불필요한 'await' 제거", + "Remove_unreachable_code_95050": "접근할 수 없는 코드 제거", + "Remove_unused_declaration_for_Colon_0_90004": "'{0}'의 사용되지 않는 선언 제거", + "Remove_unused_declarations_for_Colon_0_90041": "'{0}'의 사용되지 않는 선언 제거", + "Remove_unused_destructuring_declaration_90039": "사용되지 않는 구조 파괴 선언 제거", + "Remove_unused_label_95053": "사용되지 않는 레이블 제거", + "Remove_variable_statement_90010": "변수 문 제거", + "Rename_param_tag_name_0_to_1_95173": "'@param' 태그 이름 '{0}'의 이름을 '{1}'(으)로 바꿉니다.", + "Replace_0_with_Promise_1_90036": "'{0}'을(를) 'Promise<{1}>'(으)로 바꾸기", + "Replace_all_unused_infer_with_unknown_90031": "사용되지 않은 모든 'infer'를 'unknown'으로 바꾸기", + "Replace_import_with_0_95015": "가져오기를 '{0}'(으)로 바꿉니다.", + "Replace_infer_0_with_unknown_90030": "'infer {0}'을(를) 'unknown'으로 바꾸기", + "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "함수의 일부 코드 경로가 값을 반환하지 않는 경우 오류를 보고합니다.", + "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch 문의 fallthrough case에 대한 오류를 보고합니다.", + "Report_errors_in_js_files_8019": ".js 파일의 오류를 보고합니다.", + "Report_errors_on_unused_locals_6134": "사용되지 않은 로컬 항목에 대한 오류를 보고합니다.", + "Report_errors_on_unused_parameters_6135": "사용되지 않은 매개 변수에 대한 오류를 보고합니다.", + "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719": "다른 도구가 선언 파일을 간단하게 생성할 수 있도록 내보내기에서 충분한 주석이 필요합니다.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717": "요소 액세스를 사용하려면 인덱스 시그니처의 선언되지 않은 속성이 필요합니다.", + "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "필수 형식 매개 변수는 선택적 형식 매개 변수 다음에 올 수 없습니다.", + "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' 모듈에 대한 해결을 '{1}' 위치의 캐시에서 찾았습니다.", + "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "'{1}' 위치의 캐시에서 형식 참조 지시어 '{0}'에 대한 해상도가 발견되었습니다.", + "Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_i_6277": "상대 이름이 아닌 이름을 확인하지 못했습니다. 최신 노드 확인 기능을 사용하지 않도록 설정하여 npm 라이브러리에 구성 업데이트가 필요한지 확인합니다.", + "Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_ne_6279": "상대 이름이 아닌 이름을 확인하지 못했습니다. '--moduleResolution bundler'를 사용하여 프로젝트에 구성 업데이트가 필요한지 확인하려고 합니다.", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "문자열 값 속성 이름에 대해서만 'keyof'를 확인합니다(숫자나 기호 아님).", + "Resolved_under_condition_0_6414": "조건 '{0}'에서 확인되었습니다.", + "Resolving_in_0_mode_with_conditions_1_6402": "조건이 {1}인 {0} 모드에서 확인하는 중입니다.", + "Resolving_module_0_from_1_6086": "======== '{1}'에서 '{0}' 모듈을 확인하는 중입니다. ========", + "Resolving_module_name_0_relative_to_base_url_1_2_6094": "기본 URL '{1}' - '{2}'을(를) 기준으로 모듈 이름 '{0}'을(를) 확인하는 중입니다.", + "Resolving_real_path_for_0_result_1_6130": "'{0}'의 실제 경로를 확인하는 중입니다. 결과: '{1}'.", + "Resolving_type_reference_directive_0_containing_file_1_6242": "======== 파일 '{1}'을(를) 포함하는 형식 참조 지시어 '{0}'을(를) 확인하는 중입니다.' ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: '{1}', 루트 디렉터리: '{2}' ========", + "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: '{1}', 루트 디렉터리: 설정되지 않음 ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: 설정되지 않음, 루트 디렉터리: '{1}' ========", + "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128": "======== 형식 참조 지시문 '{0}'을(를) 확인하는 중입니다. 포함 파일: 설정되지 않음, 루트 디렉터리: 설정되지 않음 ========", + "Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_no_6265": "사용자 지정 typeRoots를 지정하는 프로그램에 대한 형식 참조 지시문을 확인합니다. 'node_modules' 폴더에서 조회를 건너뜁니다.", + "Resolving_with_primary_search_path_0_6121": "기본 검색 경로 '{0}'을(를) 사용하여 확인하는 중입니다.", + "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest 매개 변수 '{0}'에는 암시적으로 'any[]' 형식이 포함됩니다.", + "Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047": "Rest 매개 변수 '{0}'은(는) 암시적으로 'any[]' 형식이지만, 사용량에서 더 나은 형식을 유추할 수 있습니다.", + "Rest_types_may_only_be_created_from_object_types_2700": "rest 유형은 개체 형식에서만 만들 수 있습니다.", + "Return_type_annotation_circularly_references_itself_2577": "반환 형식 주석이 자신을 순환 참조합니다.", + "Return_type_must_be_inferred_from_a_function_95149": "반환 형식은 함수에서 유추되어야 합니다.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "생성자 시그니처의 반환 형식을 클래스의 인스턴스 형식에 할당할 수 있어야 합니다.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "내보낸 함수의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "내보낸 함수의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "내보낸 함수의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "내보낸 인터페이스에 있는 메서드의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "내보낸 인터페이스에 있는 메서드의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 외부 모듈 {2}의 이름 '{1}'을(를) 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 프라이빗 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 외부 모듈 {2}의 이름 '{1}'을(를) 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 프라이빗 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_not_resolved_6395": "'{1}'에서 '{0}' 모듈의 해결 방법을 '{2}위치 '의 캐시에 다시 사용하는 중이었으므로 해결되지 않았습니다.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6393": "위치 '{2}'의 캐시에 있는 '{1}'에서 '{0}' 모듈의 해결 방법을 다시 사용하는 중입니다. '{3}'(으)로 해결되었습니다.", + "Reusing_resolution_of_module_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_6394": "위치 '{2}'의 캐시에 있는 '{1}'에서 '{0}' 모듈의 해결 방법을 다시 사용하는 중입니다. 패키지 ID가 '{4}'인 '{3}'(으)로 해결되었습니다.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389": "이전 프로그램의 '{1}'에서 '{0}' 모듈의 해결 방법을 다시 사용하는 중이었으므로 확인되지 않았습니다.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_6183": "이전 프로그램의 '{1}'에서 '{0}' 모듈의 해결 방법을 다시 사용 중이므로 '{2}'(으)로 해결되었습니다.", + "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package__6184": "이전 프로그램의 '{1}'에서 '{0}' 모듈의 해결 방법을 다시 사용 중이며 패키지 ID가 '{3}'인 '{2}'(으)로 해결되었습니다.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398": "위치 '{2}'의 캐시에 있는 '{1}'에서 형식 참조 지시문 '{0}'의 해결 방법을 다시 사용하는 중이며 해결되지 않았습니다.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396": "위치 '{2}'의 캐시에 있는 '{1}'에서 형식 참조 지시문 '{0}'의 해결 방법을 다시 사용하는 중입니다. '{3}'(으)로 해결되었습니다.", + "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397": "위치 '{2}'의 캐시에 있는 '{1}'에서 형식 참조 지시문 '{0}'의 해결 방법을 다시 사용하는 중입니다. 패키지 ID가 '{4}'인 '{3}'(으)로 해결되었습니다.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved_6392": "이전 프로그램의 '{1}'에서 형식 참조 지시문 '{0}'의 해결 방법을 다시 사용 중이므로 해결되지 않았습니다.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390": "이전 프로그램의 '{1}'에서 형식 참조 지시문 '{0}'의 해결 방법을 다시 사용 중이며 '{2}'(으)로 해결되었습니다.", + "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6391": "이전 프로그램의 '{1}'에서 형식 참조 지시문 '{0}'의 해결 방법을 다시 사용 중이며 패키지 ID가 '{3}'인 '{2}'(으)로 해결되었습니다.", + "Rewrite_all_as_indexed_access_types_95034": "인덱싱된 액세스 형식으로 모두 다시 작성", + "Rewrite_as_the_indexed_access_type_0_90026": "인덱싱된 액세스 형식 '{0}'(으)로 다시 작성", + "Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_i_6421": "출력 파일의 해당 JavaScript에 해당하는 상대 가져오기 경로에서 '.ts', '.tsx', '.mts' 및 '.cts' 파일 확장자를 다시 작성합니다.", + "Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish_2869": "??의 오른쪽 피연산자는 왼쪽 피연산자가 nullish가 되지 않으므로 연결할 수 없습니다.", + "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "루트 디렉터리를 확인할 수 없어 기본 검색 경로를 건너뜁니다.", + "Root_file_specified_for_compilation_1427": "컴파일을 위해 지정된 루트 파일", + "STRATEGY_6039": "전략", + "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "프로젝트의 증분 컴파일을 허용하도록 .tsbuildinfo 파일을 저장합니다.", + "Saw_non_matching_condition_0_6405": "비일치 조건 '{0}'을(를) 확인했습니다.", + "Scoped_package_detected_looking_in_0_6182": "범위가 지정된 패키지가 검색되었습니다. '{0}'에서 찾습니다.", + "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418": "대체 확장에 대한 모든 상위 node_modules 디렉터리 검색: {0}.", + "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417": "기본 설정 확장에 대한 모든 상위 node_modules 디렉터리 검색: {0}.", + "Selection_is_not_a_valid_statement_or_statements_95155": "선택 항목이 유효한 하나의 문 또는 여러 문이 아닙니다.", + "Selection_is_not_a_valid_type_node_95133": "선택 영역이 유효한 형식 노드가 아닙니다.", + "Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declaratio_6705": "내보낸 JavaScript의 JavaScript 언어 버전을 설정하고 호환되는 라이브러리 선언을 포함합니다.", + "Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit_6654": "TypeScript에서 메시지 언어를 설정합니다. 이는 내보내기에 영향을 주지 않습니다.", + "Set_the_module_option_in_your_configuration_file_to_0_95099": "구성 파일의 'module' 옵션을 '{0}'(으)로 설정", + "Set_the_newline_character_for_emitting_files_6659": "파일을 내보내기 위한 줄 바꿈 문자를 설정합니다.", + "Set_the_target_option_in_your_configuration_file_to_0_95098": "구성 파일의 'target' 옵션을 '{0}'(으)로 설정", + "Setters_cannot_return_a_value_2408": "Setter가 값을 반환할 수 없습니다.", + "Show_all_compiler_options_6169": "모든 컴파일러 옵션을 표시합니다.", + "Show_diagnostic_information_6149": "진단 정보를 표시합니다.", + "Show_verbose_diagnostic_information_6150": "자세한 진단 정보를 표시합니다.", + "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "빌드될 항목 표시(또는 '--clean'으로 지정된 경우 삭제될 항목 표시)", + "Signature_0_must_be_a_type_predicate_1224": "'{0}' 시그니처는 형식 조건자여야 합니다.", + "Signature_declarations_can_only_be_used_in_TypeScript_files_8017": "서명 선언은 TypeScript 파일에서만 사용할 수 있습니다.", + "Skip_building_downstream_projects_on_error_in_upstream_project_6640": "업스트림 프로젝트에서 오류 발생 시 다운스트림 프로젝트 빌드를 건너뜁니다.", + "Skip_type_checking_all_d_ts_files_6693": "모든 .d.ts 파일의 형식 검사를 건너뜁니다.", + "Skip_type_checking_d_ts_files_that_are_included_with_TypeScript_6692": "TypeScript에 포함된 .d.ts 파일의 형식 검사를 건너뜁니다.", + "Skip_type_checking_of_declaration_files_6012": "선언 파일 형식 검사를 건너뜁니다.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Skipping build of project '{0}' because its dependency '{1}' has errors", + "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382": "Skipping build of project '{0}' because its dependency '{1}' was not built", + "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164": "절대 URI처럼 보이는 '{0}' 모듈을 건너뛰는 중입니다. 대상 파일 형식은 {1}입니다.", + "Source_from_referenced_project_0_included_because_1_specified_1414": "'{1}'이(가) 지정되었기 때문에 참조된 프로젝트 '{0}'의 소스가 포함됩니다.", + "Source_from_referenced_project_0_included_because_module_is_specified_as_none_1415": "'--module'이 'none'으로 지정되었기 때문에 참조된 프로젝트 '{0}'의 소스가 포함됩니다.", + "Source_has_0_element_s_but_target_allows_only_1_2619": "소스에 {0}개 요소가 있지만, 대상에서 {1}개만 허용합니다.", + "Source_has_0_element_s_but_target_requires_1_2618": "소스에 {0}개 요소가 있지만, 대상에 {1}개가 필요합니다.", + "Source_provides_no_match_for_required_element_at_position_0_in_target_2623": "소스가 대상에 있는 {0} 위치의 필수 요소와 일치하는 항목을 제공하지 않습니다.", + "Source_provides_no_match_for_variadic_element_at_position_0_in_target_2624": "소스가 대상에 있는 {0} 위치의 가변 인자 요소와 일치하는 항목을 제공하지 않습니다.", + "Specify_ECMAScript_target_version_6015": "ECMAScript 대상 버전을 지정합니다.", + "Specify_JSX_code_generation_6080": "JSX 코드 생성을 지정합니다.", + "Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designa_6679": "모든 출력을 하나의 JavaScript 파일로 묶는 파일을 지정하세요. 'declaration'이 true이면 모든 .d.ts 출력을 묶는 파일도 지정합니다.", + "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641": "컴파일에 포함할 파일과 일치하는 GLOB 패턴 목록을 지정합니다.", + "Specify_a_list_of_language_service_plugins_to_include_6681": "포함할 언어 서비스 플러그 인 목록을 지정합니다.", + "Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment_6651": "대상 런타임 환경을 설명하는 번들 라이브러리 선언 파일 세트를 지정합니다.", + "Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations_6680": "추가 검색 위치로 가져오기를 다시 매핑할 항목 집합을 지정합니다.", + "Specify_an_array_of_objects_that_specify_paths_for_projects_Used_in_project_references_6687": "프로젝트의 경로를 지정하는 개체 배열을 지정합니다. 프로젝트 참조에 사용됩니다.", + "Specify_an_output_folder_for_all_emitted_files_6678": "내보낸 모든 파일의 출력 폴더를 지정합니다.", + "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718": "유형에만 사용되는 가져오기에 대한 방출/확인 동작을 지정합니다.", + "Specify_file_to_store_incremental_compilation_information_6380": "증분 컴파일 정보를 저장할 파일 지정", + "Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier_6658": "TypeScript가 지정된 모듈 지정자에서 파일을 검색하는 방법을 지정합니다.", + "Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality_6714": "재귀 파일 감시 기능이 없는 시스템에서 디렉터리를 감시하는 방법을 지정합니다.", + "Specify_how_the_TypeScript_watch_mode_works_6715": "TypeScript 감시 모드의 작동 방식을 지정합니다.", + "Specify_library_files_to_be_included_in_the_compilation_6079": "컴파일에 포함할 라이브러리 파일을 지정합니다.", + "Specify_module_code_generation_6016": "모듈 코드 생성을 지정합니다.", + "Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Ast_6649": "'jsx: react-jsx*'를 사용할 때 JSX 팩토리 함수를 가져오기 위해 사용되는 모듈 지정자를 지정합니다.", + "Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types_6710": "'./node_modules/@types'와 같은 역할을 하는 여러 폴더를 지정합니다.", + "Specify_one_or_more_path_or_node_module_references_to_base_configuration_files_from_which_settings_a_6633": "설정이 상속되는 기본 구성 파일에 대한 하나 이상의 경로 또는 노드 모듈 참조를 지정합니다.", + "Specify_options_for_automatic_acquisition_of_declaration_files_6709": "선언 파일의 자동 인식 옵션을 지정합니다.", + "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227": "파일 시스템 이벤트를 사용하여 만들지 못할 경우 폴링 조사식을 만들기 위한 전략 지정: 'FixedInterval'(기본값), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'.", + "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226": "기본적으로 재귀 감시를 지원하지 않는 플랫폼에서 디렉터리를 감시하기 위한 전략 지정: 'UseFsEvents'(기본값), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'.", + "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225": "파일을 감시하기 위한 전략 지정: 'FixedPollingInterval'(기본값), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'.", + "Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragme_6648": "React JSX 내보내기를 대상으로 할 때 조각에 사용되는 JSX 조각 참조를 지정합니다(예: 'React.Fragment' 또는 'Fragment').", + "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "'react' JSX 내보내기를 대상으로 하는 경우 사용할 JSX 팩터리 함수를 지정합니다(예: 'React.createElement' 또는 'h').", + "Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h_6647": "React JSX 방출을 대상으로 할 때 사용되는 JSX 팩토리 함수를 지정하세요. 'React.createElement' 또는 'h'.", + "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034": "'JsxFactory' 컴파일러 옵션이 지정된 상태로 'react' JSX 내보내기를 대상으로 설정할 때 사용할 JSX 조각 팩터리 함수를 지정합니다(예: 'Fragment').", + "Specify_the_base_directory_to_resolve_non_relative_module_names_6607": "상대적이지 않은 모듈 이름을 확인할 기본 디렉터리를 지정합니다.", + "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "파일을 내보낼 때 사용할 줄 시퀀스의 끝 지정: 'CRLF'(dos) 또는 'LF'(unix).", + "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "소스 위치 대신 디버거가 TypeScript 파일을 찾아야 하는 위치를 지정하세요.", + "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6655": "생성된 위치 대신 디버거가 맵 파일을 찾아야 하는 위치를 지정하세요.", + "Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicabl_6656": "'node_modules'에서 JavaScript 파일을 확인하는 데 사용되는 최대 폴더 깊이를 지정합니다. 'allowJs'에만 적용 가능합니다.", + "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238": "'jsx' 및 'jsxs' 팩터리 함수를 가져오는 데 사용할 모듈 지정자를 지정합니다(예: react).", + "Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit_6686": "'createElement'에 대해 호출된 개체를 지정합니다. '반응' JSX 방출을 대상으로 할 때만 적용됩니다.", + "Specify_the_output_directory_for_generated_declaration_files_6613": "생성된 선언 파일의 출력 디렉터리를 지정합니다.", + "Specify_the_path_to_tsbuildinfo_incremental_compilation_file_6707": ".tsbuildinfo 증분 컴파일 파일의 경로를 지정합니다.", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "입력 파일의 루트 디렉터리를 지정하세요. --outDir이 포함된 출력 디렉터리 구조를 제어하는 데 사용됩니다.", + "Specify_the_root_folder_within_your_source_files_6690": "소스 파일 내에서 루트 폴더를 지정합니다.", + "Specify_the_root_path_for_debuggers_to_find_the_reference_source_code_6695": "디버거의 루트 경로를 지정하여 참조 소스 코드를 찾습니다.", + "Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file_6711": "소스 파일에서 참조하지 않고 포함할 형식 패키지 이름을 지정합니다.", + "Specify_what_JSX_code_is_generated_6646": "생성되는 JSX 코드를 지정합니다.", + "Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers_6634": "시스템에 원시 파일 감시자가 부족한 경우 감시자가 사용해야 하는 접근 방법을 지정합니다.", + "Specify_what_module_code_is_generated_6657": "생성되는 모듈 코드를 지정합니다.", + "Split_all_invalid_type_only_imports_1367": "잘못된 형식 전용 가져오기 모두 분할", + "Split_into_two_separate_import_declarations_1366": "두 개의 개별 가져오기 선언으로 분할", + "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' 식에서 Spread 연산자는 ECMAScript 5 이상을 대상으로 하는 경우에만 사용할 수 있습니다.", + "Spread_types_may_only_be_created_from_object_types_2698": "spread 유형은 개체 형식에서만 만들 수 있습니다.", + "Starting_compilation_in_watch_mode_6031": "감시 모드에서 컴파일을 시작하는 중...", + "Statement_expected_1129": "문이 필요합니다.", + "Statements_are_not_allowed_in_ambient_contexts_1036": "앰비언트 컨텍스트에서는 문이 허용되지 않습니다.", + "Static_members_cannot_reference_class_type_parameters_2302": "정적 멤버는 클래스 형식 매개 변수를 참조할 수 없습니다.", + "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699": "정적 속성 '{0}'이(가) 생성자 함수 '{1}'의 기본 제공 속성 'Function.{0}'과(와) 충돌합니다.", + "String_literal_expected_1141": "문자열 리터럴이 필요합니다.", + "String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es_18057": "'--module' 플래그가 'es2015' 또는 'es2020'으로 설정된 경우 문자열 리터럴 가져오기 및 내보내기 이름은 지원되지 않습니다.", + "String_literal_with_double_quotes_expected_1327": "큰따옴표로 묶은 문자열 리터럴이 필요합니다.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "색과 컨텍스트를 사용하여 오류 및 메시지를 스타일화합니다(실험적).", + "Subpattern_flags_must_be_present_when_there_is_a_minus_sign_1504": "en 대시가 있는 경우 하위 패턴 플래그가 있어야 합니다.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "후속 속성 선언에 같은 형식이 있어야 합니다. '{0}' 속성이 '{1}' 형식이어야 하는데 여기에는 '{2}' 형식이 있습니다.", + "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "후속 변수 선언에 같은 형식이 있어야 합니다. '{0}' 변수가 '{1}' 형식이어야 하는데 여기에는 '{2}' 형식이 있습니다.", + "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "'{1}' 패턴에 대한 '{0}' 대체의 형식이 잘못되었습니다. 'string'이 필요한데 '{2}'을(를) 얻었습니다.", + "Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character_5062": "'{1}' 패턴의 '{0}' 대체에는 '*' 문자를 최대 하나만 사용할 수 있습니다.", + "Substitutions_for_pattern_0_should_be_an_array_5063": "'{0}' 패턴에 대한 대체는 배열이 되어야 합니다.", + "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066": "패턴 '{0}'에 대한 대체에는 배열이 비어 있지 않아야 합니다.", + "Successfully_created_a_tsconfig_json_file_6071": "tsconfig.json 파일을 만들었습니다.", + "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "생성자 밖이나 생성자 내부에 중첩된 함수에서는 Super 호출이 허용되지 않습니다.", + "Suppress_excess_property_checks_for_object_literals_6072": "개체 리터럴에 대한 초과 속성 검사를 생략합니다.", + "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "인덱스 시그니처가 없는 개체 인덱싱에 대한 noImplicitAny 오류를 표시하지 않습니다.", + "Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures_6703": "인덱스 서명이 없는 개체를 인덱싱할 때 'noImplicitAny' 오류를 억제합니다.", + "Switch_each_misused_0_to_1_95138": "잘못 사용된 각 '{0}'을(를) '{1}'(으)로 전환", + "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6704": "기본적으로 재귀 감시를 지원하지 않는 플랫폼에서 동기적으로 콜백을 호출하고 디렉터리 감시자의 상태를 업데이트합니다.", + "Syntax_Colon_0_6023": "구문: {0}", + "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229": "'{0}' 태그는 '{1}'개 이상의 인수가 필요한데 JSX 팩터리 '{2}'이(가) 최대 '{3}'개를 제공합니다.", + "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358": "태그가 지정된 템플릿 식은 선택적 체인에서 사용할 수 없습니다.", + "Target_allows_only_0_element_s_but_source_may_have_more_2621": "대상에서 {0}개 요소만 허용하지만, 소스에 더 많이 있을 수 있습니다.", + "Target_requires_0_element_s_but_source_may_have_fewer_2620": "대상에 {0}개 요소가 필요하지만, 소스에 더 적게 있을 수 있습니다.", + "Target_signature_provides_too_few_arguments_Expected_0_or_more_but_got_1_2849": "대상 서명이 너무 적은 인수를 제공합니다. {0} 이상이 필요하지만 {1}을(를) 받았습니다.", + "The_0_modifier_can_only_be_used_in_TypeScript_files_8009": "'{0}' 한정자는 TypeScript 파일에서만 사용할 수 있습니다.", + "The_0_operator_cannot_be_applied_to_type_symbol_2469": "'{0}' 연산자는 'symbol' 유형에 적용될 수 없습니다.", + "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447": "'{0}' 연산자는 부울 형식에 사용할 수 없습니다. 대신 '{1}'을(를) 사용하세요.", + "The_0_property_of_an_async_iterator_must_be_a_method_2768": "비동기 반복기의 '{0}' 속성은 메서드여야 합니다.", + "The_0_property_of_an_iterator_must_be_a_method_2767": "반복기의 '{0}' 속성은 메서드여야 합니다.", + "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696": "'Object' 형식은 할당할 수 있는 다른 형식이 거의 없습니다. 대신 'any' 형식을 사용할까요?", + "The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously_1502": "유니코드(u) 플래그와 유니코드 집합(v) 플래그를 동시에 설정할 수 없습니다.", + "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_func_2496": "'arguments' 개체는 ES5의 화살표 함수에서 참조할 수 없습니다. 표준 함수 식을 사용해 보세요.", + "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_sta_2522": "'arguments' 개체는 ES5의 비동기 함수 또는 메서드에서 참조할 수 없습니다. 표준 함수 또는 메서드를 사용해 보세요.", + "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' 문의 본문이 빈 문이면 안 됩니다.", + "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793": "이 구현에 대한 호출이 성공하겠지만, 오버로드의 구현 시그니처는 외부에 표시되지 않습니다.", + "The_character_set_of_the_input_files_6163": "입력 파일의 문자 집합입니다.", + "The_containing_arrow_function_captures_the_global_value_of_this_7041": "포함하는 화살표 함수는 'this'의 전역 값을 캡처합니다.", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "제어 흐름 분석에 대해 포함된 함수 또는 모듈 본문이 너무 큽니다.", + "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309": "현재 파일은 CommonJS 모듈이며 최상위 수준에서 'await'를 사용할 수 없습니다.", + "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479": "현재 파일은 가져오기에서 'require' 호출을 생성하는 CommonJS 모듈입니다. 그러나 참조된 파일은 ECMAScript 모듈이며 'require'로 가져올 수 없습니다. 대신 동적 'import(\"{0}\")' 호출을 작성하는 것이 좋습니다.", + "The_current_host_does_not_support_the_0_option_5001": "현재 호스트가 '{0}' 옵션을 지원하지 않습니다.", + "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018": "사용하려는 '{0}'의 선언이 여기서 정의됩니다.", + "The_declaration_was_marked_as_deprecated_here_2798": "선언이 여기에 사용되지 않음으로 표시되었습니다.", + "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500": "필요한 형식은 여기에서 '{1}' 형식에 선언된 '{0}' 속성에서 가져옵니다.", + "The_expected_type_comes_from_the_return_type_of_this_signature_6502": "필요한 형식은 이 시그니처의 반환 형식에서 가져옵니다.", + "The_expected_type_comes_from_this_index_signature_6501": "필요한 형식은 이 인덱스 시그니처에서 가져옵니다.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "내보내기 할당의 식은 앰비언트 컨텍스트의 식별자 또는 정규화된 이름이어야 합니다.", + "The_file_is_in_the_program_because_Colon_1430": "파일은 다음과 같은 이유로 프로그램에 있습니다.", + "The_files_list_in_config_file_0_is_empty_18002": "'{0}' 구성 파일의 '파일' 목록이 비어 있습니다.", + "The_first_export_default_is_here_2752": "첫 번째 내보내기 기본값은 여기에 있습니다.", + "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "프라미스에서 'then' 메서드의 첫 번째 매개 변수는 콜백이어야 합니다.", + "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "전역 형식 'JSX.{0}'에 속성이 둘 이상 있을 수 없습니다.", + "The_implementation_signature_is_declared_here_2750": "여기에서는 구현 시그니처가 선언됩니다.", + "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "'import.meta' 메타 속성은 CommonJS 출력으로 빌드될 파일에서 허용되지 않습니다.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "'import.meta' 메타 속성은 '--module' 옵션이 'es2020', 'es2022', 'esnext', 'system', 'node16', 'node18' 또는 'nodenext'인 경우에만 허용됩니다.", + "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}'의 유추된 형식 이름을 지정하려면 '{1}'에 대한 참조가 있어야 합니다. 이식하지 못할 수 있습니다. 형식 주석이 필요합니다.", + "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "'{0}'의 유추된 형식이 일반적으로 직렬화될 수 없는 순환 구조가 있는 형식을 참조합니다. 형식 주석이 필요합니다.", + "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}'의 유추 형식이 액세스할 수 없는 '{1}' 형식을 참조합니다. 형식 주석이 필요합니다.", + "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056": "이 노드의 유추된 형식이 컴파일러가 직렬화할 최대 길이를 초과합니다. 명시적 형식 주석이 필요합니다.", + "The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_n_2850": "'using' 선언의 이니셜라이저는 '[Symbol.dispose]()' 메서드가 있는 개체이거나 'null' 또는 'undefined'여야 합니다.", + "The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_2851": "'await using' 선언의 이니셜라이저는 '[Symbol.asyncDispose]()' 또는 '[Symbol.dispose]5D;()' 메서드가 있는 개체이거나 'null' 또는 'undefined'여야 합니다.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "속성 '{1}'이(가) 여러 구성원에 있고 일부 구성원에서는 프라이빗 상태이므로 교집합 '{0}'이(가) 'never'로 감소했습니다.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "일부 구성원에 속성 '{1}'에 충돌하는 형식이 있으므로 교집합 '{0}'이(가) 'never'로 감소했습니다.", + "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795": "'내장' 키워드는 컴파일러에서 제공하는 내장 형식을 선언하는 데에만 사용할 수 있습니다.", + "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016": "'JsxFactory' 컴파일러 옵션과 함께 JSX 조각을 사용하려면 'jsxFragmentFactory' 컴파일러 옵션을 제공해야 합니다.", + "The_last_overload_gave_the_following_error_2770": "마지막 오버로드에서 다음 오류가 발생했습니다.", + "The_last_overload_is_declared_here_2771": "여기서 마지막 오버로드가 선언됩니다.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 문의 왼쪽에는 구조 파괴 패턴을 사용할 수 없습니다.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration_1493": "'for... in' 문의 왼쪽은 'using' 선언일 수 없습니다.", + "The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration_1494": "'for... in' 문의 왼쪽은 'await using' 선언일 수 없습니다.", + "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 문의 왼쪽에는 형식 주석을 사용할 수 없습니다.", + "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780": "'for...in' 문의 왼쪽은 선택적 속성 액세스일 수 없습니다.", + "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406": "'for...in' 문의 왼쪽은 변수 또는 속성 액세스여야 합니다.", + "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' 문의 왼쪽은 'string' 또는 'any' 형식이어야 합니다.", + "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' 문의 왼쪽에는 형식 주석을 사용할 수 없습니다.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781": "'for...of' 문의 왼쪽은 선택적 속성 액세스일 수 없습니다.", + "The_left_hand_side_of_a_for_of_statement_may_not_be_async_1106": "'for...of' 문의 왼쪽은 'async'일 수 없습니다.", + "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' 문의 왼쪽은 변수 또는 속성 액세스여야 합니다.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "산술 연산의 왼쪽은 'any', 'number', 'bigint' 또는 열거형 형식이어야 합니다.", + "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "할당 식의 왼쪽은 선택적 속성 액세스일 수 없습니다.", + "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "할당 식의 왼쪽은 변수 또는 속성 액세스여야 합니다.", + "The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_2860": "'instanceof' 식의 왼쪽은 오른쪽 '[Symbol.hasInstance]' 메서드의 첫 번째 인수에 할당할 수 있어야 합니다.", + "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' 식 왼쪽은 'any' 형식, 개체 형식 또는 형식 매개 변수여야 합니다.", + "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "사용자에게 메시지를 표시할 때 사용되는 로캘입니다(예: 'en-us').", + "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "node_modules에서 검색하고 JavaScript 파일을 로드할 최대 종속성 깊이입니다.", + "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "'delete' 연산자의 피연산자는 프라이빗 식별자일 수 없습니다.", + "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "'delete' 연산자의 피연산자는 읽기 전용 속성일 수 없습니다.", + "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "'delete' 연산자의 피연산자는 속성 참조여야 합니다.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "'delete' 연산자의 피연산자는 선택 사항이어야 합니다.", + "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "증분 또는 감소 연산자의 피연산자는 선택적 속성 액세스일 수 없습니다.", + "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "증가 또는 감소 연산자의 피연산자는 변수 또는 속성 액세스여야 합니다.", + "The_parser_expected_to_find_a_1_to_match_the_0_token_here_1007": "여기서 파서는 '{0}' 토큰과 일치하는 '{1}'을(를) 찾아야 합니다.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209": "프로젝트 루트가 모호하지만 '{1}' 파일에서 '{0}' 내보내기 맵 항목을 확인하는 데 필요합니다. 명확하게 하려면 `rootDir` 컴파일러 옵션을 제공하세요.", + "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210": "프로젝트 루트가 모호하지만 '{1}' 파일에서 '{0}' 가져오기 맵 항목을 확인하는 데 필요합니다. 명확하게 하려면 `rootDir` 컴파일러 옵션을 제공하세요.", + "The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_priv_18014": "철자가 동일한 다른 프라이빗 식별자에서 섀도 처리되기 때문에 이 클래스 내의 '{1}' 형식에서 '{0}' 속성에 액세스할 수 없습니다.", + "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "매개 변수 데코레이터 함수의 반환 형식은 'void' 또는 'any'여야 합니다.", + "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "속성 데코레이터 함수의 반환 형식은 'void' 또는 'any'여야 합니다.", + "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "비동기 함수의 반환 형식은 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1065": "비동기 함수 또는 메서드의 반환 형식은 전역 Promise 형식이어야 합니다.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "비동기 함수 또는 메서드의 반환 형식은 전역 Promise 형식이어야 합니다. 'Promise<{0}>'을(를) 쓰려고 했습니까?", + "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "'for...in' 문 오른쪽은 'any' 형식, 개체 형식 또는 형식 매개 변수여야 하는데, 여기에 '{0}' 형식이 있습니다.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "산술 연산 오른쪽은 'any', 'number', 'bigint' 또는 열거형 형식이어야 합니다.", + "The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_2359": "'instanceof' 식의 오른쪽은 'any' 형식, 클래스, 함수 또는 'Function' 인터페이스 형식에 할당할 수 있는 다른 형식이거나 'Symbol.hasInstance' 메서드가 있는 개체 형식이어야 합니다.", + "The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression_2848": "'instanceof' 식의 오른쪽은 인스턴스화 식이 아니어야 합니다.", + "The_root_value_of_a_0_file_must_be_an_object_5092": "'{0}' 파일의 루트 값은 개체여야 합니다.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0_1278": "런타임에서는 {1} 인수를 사용하여 데코레이터를 호출하지만 데코레이터에는 {0}이(가) 필요합니다.", + "The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0_1279": "런타임에서는 {1} 인수를 사용하여 데코레이터를 호출하지만 데코레이터에는 {0} 이상이 필요합니다.", + "The_shadowing_declaration_of_0_is_defined_here_18017": "여기서는 '{0}'의 섀도 선언이 정의됩니다.", + "The_signature_0_of_1_is_deprecated_6387": "'{1}'의 시그니처 '{0}'은(는) 사용되지 않습니다.", + "The_specified_path_does_not_exist_Colon_0_5058": "지정된 경로가 없습니다. '{0}'.", + "The_tag_was_first_specified_here_8034": "태그가 처음에 여기에 지정되었습니다.", + "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "개체 rest 할당의 대상은 선택적 속성 액세스일 수 없습니다.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "개체 rest 할당의 대상은 변수 또는 속성 액세스여야 합니다.", + "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "'{0}' 형식의 'this' 컨텍스트를 메서드의 '{1}' 형식 'this'에 할당할 수 없습니다.", + "The_this_types_of_each_signature_are_incompatible_2685": "각 시그니처의 'this' 형식이 호환되지 않습니다.", + "The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1_4104": "'{0}' 형식은 'readonly'이며 변경 가능한 형식 '{1}'에 할당할 수 없습니다.", + "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "export 문에 'export type'이 사용될 때 명명된 내보내기에서 'type' 한정자를 사용할 수 없습니다.", + "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "import 문에 'import type'이 사용되는 경우 'type' 수정자는 명명된 가져오기에 사용할 수 없습니다.", + "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "함수 선언의 형식은 함수의 시그니처와 일치해야 합니다.", + "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "속성 '{0}'을(를) 직렬화할 수 없기 때문에 이 노드의 유형을 직렬화할 수 없습니다.", + "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "비동기 반복기의 '{0}()' 메서드에서 반환하는 형식은 'value' 속성이 있는 형식에 대한 프라미스여야 합니다.", + "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "반복기의 '{0}()' 메서드에 의해 반환되는 형식에는 'value' 속성이 있어야 합니다.", + "The_types_of_0_are_incompatible_between_these_types_2200": "'{0}'의 형식은 해당 형식 간에 호환되지 않습니다.", + "The_types_returned_by_0_are_incompatible_between_these_types_2201": "'{0}'에서 반환되는 형식은 해당 형식 간에 호환되지 않습니다.", + "The_value_0_cannot_be_used_here_18050": "여기서는 '{0}' 값을 사용할 수 없습니다.", + "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' 문의 변수 선언에 이니셜라이저가 포함될 수 없습니다.", + "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "'for...of' 문의 변수 선언에 이니셜라이저가 포함될 수 없습니다.", + "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' 문은 지원되지 않습니다. 'with' 블록의 모든 기호가 'any' 형식이 됩니다.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setti_6280": "'{0}'에 형식이 있지만 현재 'moduleResolution' 설정에서 이 결과를 확인할 수 없습니다. 'node16', 'nodenext' 또는 'bundler'로 업데이트하는 것이 좋습니다.", + "There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278": "'{0}'에 형식이 있지만 package.json \"내보내기\"를 준수할 때 이 결과를 확인할 수 없습니다. '{1}' 라이브러리는 package.json 또는 입력을 업데이트해야 할 수 있습니다.", + "There_is_no_capturing_group_named_0_in_this_regular_expression_1532": "이 정규식에는 이름이 '{0}'인 캡처 그룹이 없습니다.", + "There_is_nothing_available_for_repetition_1507": "반복에 사용할 수 있는 항목이 없습니다.", + "This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found_2874": "이 JSX 태그를 사용하려면 '{0}'이(가) 범위에 있어야 하지만 찾을 수 없습니다.", + "This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_fo_2875": "이 JSX 태그를 사용하려면 모듈 경로 '{0}'이(가) 있어야 하지만 찾을 수 없습니다. 적절한 패키지에 대해 형식이 설치되어 있는지 확인합니다.", + "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "이 JSX 태그의 '{0}' 속성에는 '{1}' 형식의 자식 하나가 필요하지만, 여러 자식이 제공되었습니다.", + "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "이 JSX 태그의 '{0}' 속성에는 여러 자식이 있어야 하는 '{1}' 형식이 필요하지만, 단일 자식만 제공되었습니다.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534": "이 역참조는 존재하지 않는 그룹을 참조합니다. 이 정규식에는 캡처 그룹이 없습니다.", + "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533": "이 역참조는 존재하지 않는 그룹을 참조합니다. 이 정규식에는 {0} 캡처 그룹만 있습니다.", + "This_binary_expression_is_never_nullish_Are_you_missing_parentheses_2870": "이 이진 식은 nullish가 되지 않습니다. 괄호가 누락되었나요?", + "This_character_cannot_be_escaped_in_a_regular_expression_1535": "이 문자는 정규식에서 이스케이프할 수 없습니다.", + "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "'{0}'이(가) '{1}'과(와) 겹치지 않으므로 이 비교는 의도하지 않은 것 같습니다.", + "This_condition_will_always_return_0_2845": "이 조건은 항상 '{0}'을(를) 반환합니다.", + "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "JavaScript는 값이 아닌 참조로 개체를 비교하므로 이 조건은 항상 '{0}'을(를) 반환합니다.", + "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "이 '{0}'(은)는 항상 정의되어 있으므로 이 조건은 항상 true를 반환합니다.", + "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "함수가 항상 정의되므로 이 조건은 항상 true를 반환합니다. 대신 호출하시겠어요?", + "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "이 생성자 함수는 클래스 선언으로 변환될 수 있습니다.", + "This_expression_is_always_nullish_2871": "이 식은 항상 nullish입니다.", + "This_expression_is_not_callable_2349": "이 식은 호출할 수 없습니다.", + "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "이 식은 'get' 접근자이므로 호출할 수 없습니다. '()' 없이 사용하시겠습니까?", + "This_expression_is_not_constructable_2351": "이 식은 생성할 수 없습니다.", + "This_file_already_has_a_default_export_95130": "이 파일에 이미 기본 내보내기가 있습니다.", + "This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_b_2878": "이 가져오기 경로는 다른 프로젝트로 확인되고 프로젝트의 출력 파일 간의 상대 경로가 입력 파일 간의 상대 경로와 동일하지 않으므로 다시 쓰기에는 안전하지 않습니다.", + "This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_duri_2877": "이 가져오기는 '{0}' 확장을 사용하여 입력 TypeScript 파일로 확인하지만 상대 경로가 아니므로 내보내는 동안 다시 작성되지 않습니다.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "확대되는 선언입니다. 확대하는 선언을 같은 파일로 이동하는 것이 좋습니다.", + "This_kind_of_expression_is_always_falsy_2873": "이러한 종류의 식은 항상 거짓입니다.", + "This_kind_of_expression_is_always_truthy_2872": "이러한 종류의 식은 항상 사실입니다.", + "This_may_be_converted_to_an_async_function_80006": "비동기 함수로 변환될 수 있습니다.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122": "이 멤버는 기본 클래스 '{0}'에서 선언되지 않았기 때문에 'override' 태그가 있는 JSDoc 주석을 가질 수 없습니다.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123": "이 멤버는 기본 클래스 '{0}'에서 선언되지 않았기 때문에 'override' 태그가 있는 JSDoc 주석을 가질 수 없습니다. ‘{1}’을(를) 의미했나요?", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121": "이 멤버는 포함하는 클래스 '{0}'이(가) 다른 클래스를 확장하지 않기 때문에 '@override' 태그가 있는 JSDoc 주석을 가질 수 없습니다.", + "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_name_is_dynamic_4128": "이 멤버는 이름이 동적이기 때문에 '@override' 태그가 포함된 JSDoc 주석을 가질 수 없습니다.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113": "이 멤버는 기본 클래스 '{0}'에 선언되지 않았으므로 'override' 한정자를 포함할 수 없습니다.", + "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you__4117": "이 멤버는 기본 클래스 '{0}'에 선언되지 않았으므로 'override' 한정자를 포함할 수 없습니다. '{1}'였습니까?", + "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112": "이 멤버는 포함하는 클래스 '{0}'이(가) 다른 클래스를 확장하지 않으므로 'override' 한정자를 포함할 수 없습니다.", + "This_member_cannot_have_an_override_modifier_because_its_name_is_dynamic_4127": "이름이 동적이므로 이 멤버에는 'override' 한정자를 사용할 수 없습니다.", + "This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_4119": "이 멤버는 기본 클래스 '{0}'의 멤버를 재정의하므로 '@override' 태그가 있는 JSDoc 주석이 있어야 합니다.", + "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114": "이 멤버는 기본 클래스 '{0}'의 멤버를 재정의하므로 'override' 한정자를 포함해야 합니다.", + "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116": "이 멤버는 기본 클래스 '{0}'에 선언된 추상 메서드를 재정의하므로 'override' 한정자를 포함해야 합니다.", + "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "이 모듈은 '{0}' 플래그를 켜고 기본 내보내기를 참조하여 ECMAScript 가져오기/내보내기를 통해서만 참조할 수 있습니다.", + "This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag_2594": "이 모듈은 'export ='를 사용하여 선언되었으며 '{0}' 플래그를 사용하는 경우에만 기본 가져오기와 함께 사용할 수 있습니다.", + "This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2_6807": "이 작업은 간소화할 수 있습니다. 이 교대 근무는 '{0} {1} {2}'(와)과 동일합니다.", + "This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation_7012": "이 오버로드는 반환 형식 주석이 없으므로 '{0}' 형식을 암시적으로 반환합니다.", + "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394": "이 오버로드 시그니처는 해당 구현 시그니처와 호환되지 않습니다.", + "This_parameter_is_not_allowed_with_use_strict_directive_1346": "이 매개 변수는 'use strict' 지시문에서 사용할 수 없습니다.", + "This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_4120": "이 매개변수 속성은 기본 클래스 '{0}'의 멤버를 재정의하므로 '@override' 태그가 있는 JSDoc 주석이 있어야 합니다.", + "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115": "이 매개 변수 속성은 기본 클래스 '{0}'의 멤버를 재정의하므로 'override' 한정자를 포함해야 합니다.", + "This_regular_expression_flag_cannot_be_toggled_within_a_subpattern_1509": "이 정규식 플래그는 하위 패턴 내에서 토글할 수 없습니다.", + "This_regular_expression_flag_is_only_available_when_targeting_0_or_later_1501": "이 정규식 플래그는 '{0}' 이상을 대상으로 하는 경우에만 사용할 수 있습니다.", + "This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolv_2876": "이 상대 가져오기 경로는 파일 이름처럼 보이지만 실제로는 \"{0}\"(으)로 확인되므로 다시 작성하는 것이 안전하지 않습니다.", + "This_spread_always_overwrites_this_property_2785": "이 스프레드는 항상 이 속성을 덮어씁니다.", + "This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled_1294": "'erasableSyntaxOnly'를 사용하도록 설정한 경우에는 이 구문을 사용할 수 없습니다.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060": "이 구문은 확장자가 .mts 또는 .cts인 파일에 예약되어 있습니다. 후행 쉼표 또는 명시적 제약 조건을 추가합니다.", + "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059": "이 구문은 확장자가 .mts 또는 .cts인 파일에 예약되어 있습니다. 대신 'as' 식을 사용하세요.", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "이 구문에는 가져온 도우미가 필요하지만 '{0}' 모듈을 찾을 수 없습니다.", + "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "이 구문에는 '{0}'에 없는 '{1}'(이)라는 가져온 도우미가 필요합니다. '{0}'의 버전을 업그레이드하는 것이 좋습니다.", + "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "이 구문에는 {2} 매개 변수가 포함된 '{1}'(이)라는 가져온 도우미가 필요하지만, 이 도우미는 '{0}'에 있는 도우미와 호환되지 않습니다. '{0}' 버전을 업그레이드하는 것이 좋습니다.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "이 형식 매개 변수에는 `extends {0}` 제약 조건이 필요할 수 있습니다.", + "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "이 '가져오기' 사용은 유효하지 않습니다. 'import()' 호출을 작성할 수 있지만 괄호가 있어야 하며 유형 인수를 가질 수 없습니다.", + "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482": "이 파일을 ECMAScript 모듈로 변환하려면 `\"type\": \"module\"` 필드를 '{0}'에 추가하세요.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481": "이 파일을 ECMAScript 모듈로 변환하려면 파일 확장명을 '{0}'(으)로 변경하거나 `\"type\": \"module\"` 필드를 '{1}'에 추가하세요.", + "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480": "이 파일을 ECMAScript 모듈로 변환하려면 파일 확장명을 '{0}'(으)로 변경하거나 `{ \"type\": \"module\" }`을 사용하여 로컬 package.json 파일을 만드세요.", + "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483": "이 파일을 ECMAScript 모듈로 변환하려면 `{ \"type\": \"module\" }`을 사용하여 로컬 package.json 파일을 만드세요.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "최상위 'await' 식은 'module' 옵션이 'es2022', 'esnext', 'system', 'node16', 'node18', 'nodenext' 또는 'preserve'로 설정되고 'target' 옵션이 'es2017' 이상으로 설정된 경우에만 허용됩니다.", + "Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_sys_2854": "최상위 'await using' 문은 'module' 옵션이 'es2022', 'esnext', 'system', 'node16', 'node18', 'nodenext' 또는 'preserve'로 설정되고 'target' 옵션이 'es2017' 이상으로 설정된 경우에만 허용됩니다.", + "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": ".d.ts 파일의 최상위 수준 선언은 'declare' 또는 'export' 한정자로 시작해야 합니다.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_nod_1432": "최상위 'for await' 루프는 'module' 옵션이 'es2022', 'esnext', 'system', 'node16', 'node18', 'nodenext' 또는 'preserve'로 설정되고 'target' 옵션이 'es2017' 이상으로 설정된 경우에만 허용됩니다.", + "Trailing_comma_not_allowed_1009": "후행 쉼표는 허용되지 않습니다.", + "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "각 파일을 별도 모듈로 변환 컴파일합니다('ts.transpileModule'과 유사).", + "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "해당 항목이 있는 경우 'npm i --save-dev @types/{1}'을(를) 시도하거나, 'declare module '{0}';'을(를) 포함하는 새 선언(.d.ts) 파일 추가", + "Trying_other_entries_in_rootDirs_6110": "'rootDirs'의 다른 항목을 시도하는 중입니다.", + "Trying_substitution_0_candidate_module_location_Colon_1_6093": "'{0}' 대체를 시도하는 중입니다. 후보 모듈 위치: '{1}'.", + "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493": "길이가 '{1}'인 튜플 형식 '{0}'의 인덱스 '{2}'에 요소가 없습니다.", + "Tuple_type_arguments_circularly_reference_themselves_4110": "튜플 형식 인수가 자신을 순환 참조합니다.", + "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802": "'{0}' 형식은 '--downlevelIteration' 플래그 또는 'es2015' 이상의 '--target'을 사용하는 경우에만 반복할 수 있습니다.", + "Type_0_cannot_be_used_as_an_index_type_2538": "'{0}' 형식을 인덱스 형식으로 사용할 수 없습니다.", + "Type_0_cannot_be_used_to_index_type_1_2536": "'{0}' 형식을 인덱스 형식 '{1}'에 사용할 수 없습니다.", + "Type_0_does_not_satisfy_the_constraint_1_2344": "'{0}' 형식이 '{1}' 제약 조건을 만족하지 않습니다.", + "Type_0_does_not_satisfy_the_expected_type_1_1360": "형식 '{0}'이(가) 필요한 형식 '{1}'을(를) 충족하지 않습니다.", + "Type_0_has_no_call_signatures_2757": "'{0}' 형식에 호출 시그니처가 없습니다.", + "Type_0_has_no_construct_signatures_2761": "'{0}' 형식에 구문 시그니처가 없습니다.", + "Type_0_has_no_matching_index_signature_for_type_1_2537": "'{0}' 형식에 '{1}' 형식에 대한 일치하는 인덱스 시그니처가 없습니다.", + "Type_0_has_no_properties_in_common_with_type_1_2559": "'{0}' 유형에 '{1}' 유형과 공통적인 속성이 없습니다.", + "Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable_2635": "유형 '{0}'에는 유형 인수 목록을 적용할 수 있는 서명이 없습니다.", + "Type_0_is_generic_and_can_only_be_indexed_for_reading_2862": "'{0}' 형식은 제네릭이며 읽기용으로만 인덱싱할 수 있습니다.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "'{0}' 형식에 '{1}' 형식의 {2} 속성이 없습니다.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "'{0}' 형식에 '{1}' 형식의 {2} 외 {3}개 속성이 없습니다.", + "Type_0_is_not_a_constructor_function_type_2507": "'{0}' 형식은 생성자 함수 형식이 아닙니다.", + "Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compa_1055": "'{0}' 형식은 Promise 호환 생성자 값을 참조하지 않으므로 ES5에서 유효한 비동기 함수 반환 형식이 아닙니다.", + "Type_0_is_not_an_array_type_2461": "'{0}' 형식은 배열 형식이 아닙니다.", + "Type_0_is_not_an_array_type_or_a_string_type_2495": "'{0}' 형식은 배열 형식 또는 문자열 형식이 아닙니다.", + "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "'{0}' 형식은 배열 형식 또는 문자열 형식이 아니거나, 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 없습니다.", + "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "'{0}' 형식은 배열 형식이 아니거나 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 없습니다.", + "Type_0_is_not_assignable_to_type_1_2322": "'{0}' 형식은 '{1}' 형식에 할당할 수 없습니다.", + "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820": "'{0}' 형식은 '{1}' 형식에 할당할 수 없습니다. '{2}'을(를) 의미했나요?", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "'{0}' 형식을 '{1}' 형식에 할당할 수 없습니다. 이름이 같은 2개의 서로 다른 형식이 있지만 서로 관련은 없습니다.", + "Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation_2636": "'{0}' 형식은 가변성 주석에 암시된 대로 '{1}' 형식에 할당할 수 없습니다.", + "Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values_18033": "'{0}' 형식은 계산 열거형 멤버 값에 필요하므로 '{1}' 형식에 할당할 수 없습니다.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375": "'{0}' 유형은 'exactOptionalPropertyTypes: true'가 있는 '{1}' 유형에 할당할 수 없습니다. 대상 속성의 유형에 'undefined'를 추가하는 것을 고려하세요.", + "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "'{0}' 유형은 'exactOptionalPropertyTypes: true'가 있는 '{1}' 유형에 할당할 수 없습니다. 대상 유형에 'undefined'를 추가하는 것을 고려하세요.", + "Type_0_is_not_comparable_to_type_1_2678": "'{0}' 형식을 '{1}' 형식과 비교할 수 없습니다.", + "Type_0_is_not_generic_2315": "'{0}' 형식이 제네릭이 아닙니다.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "형식 '{0}'은(는) 'in' 연산자의 오른쪽 피연산자로 허용되지 않는 기본 값을 나타낼 수 있습니다.", + "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "'{0}' 형식에는 비동기 반복기를 반환하는 '[Symbol.asyncIterator]()' 메서드가 있어야 합니다.", + "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "'{0}' 형식에는 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 있어야 합니다.", + "Type_0_provides_no_match_for_the_signature_1_2658": "'{0}' 형식에서 '{1}' 시그니처에 대한 일치하는 항목을 제공하지 않습니다.", + "Type_0_recursively_references_itself_as_a_base_type_2310": "Type '{0}' 형식은 자기 자신을 기본 형식으로 재귀적으로 참조합니다.", + "Type_Checking_6248": "형식 검사", + "Type_alias_0_circularly_references_itself_2456": "'{0}' 형식 별칭은 순환적으로 자신을 참조합니다.", + "Type_alias_must_be_given_a_name_1439": "형식 별칭에 이름을 지정해야 합니다.", + "Type_alias_name_cannot_be_0_2457": "형식 별칭 이름은 '{0}'일 수 없습니다.", + "Type_aliases_can_only_be_used_in_TypeScript_files_8008": "형식 별칭은 TypeScript 파일에서만 사용할 수 있습니다.", + "Type_annotation_cannot_appear_on_a_constructor_declaration_1093": "형식 주석은 생성자 선언에 표시될 수 없습니다.", + "Type_annotations_can_only_be_used_in_TypeScript_files_8010": "형식 주석은 TypeScript 파일에서만 사용할 수 있습니다.", + "Type_argument_expected_1140": "형식 인수가 필요합니다.", + "Type_argument_list_cannot_be_empty_1099": "형식 인수 목록은 비워 둘 수 없습니다.", + "Type_arguments_can_only_be_used_in_TypeScript_files_8011": "형식 인수는 TypeScript 파일에서만 사용할 수 있습니다.", + "Type_arguments_for_0_circularly_reference_themselves_4109": "'{0}'의 형식 인수가 자신을 순환 참조합니다.", + "Type_assertion_expressions_can_only_be_used_in_TypeScript_files_8016": "형식 어설션 식은 TypeScript 파일에서만 사용할 수 있습니다.", + "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626": "소스의 {0} 위치에 있는 형식이 대상의 {1} 위치에 있는 형식과 호환되지 않습니다.", + "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627": "소스의 {0}~{1} 위치에 있는 형식이 대상의 {2} 위치에 있는 형식과 호환되지 않습니다.", + "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039": "'{0}' 프라이빗 이름이 포함된 형식은 --isolatedDeclarations와 함께 사용할 수 없습니다.", + "Type_declaration_files_to_be_included_in_compilation_6124": "컴파일에 포함할 선언 파일을 입력하세요.", + "Type_expected_1110": "형식이 필요합니다.", + "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456": "유형 가져오기 어설션에는 값이 '가져오기' 또는 '요구'인 정확히 하나의 키('resolution-mode')가 있어야 합니다.", + "Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1464": "형식 가져오기 특성에는 값이 'import' 또는 'require'인 키 'resolution-mode'가 정확히 하나 있어야 합니다.", + "Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute_1542": "CommonJS 모듈에서 ECMAScript 모듈의 형식 가져오기에는 'resolution-mode' 특성이 있어야 합니다.", + "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589": "형식 인스턴스화는 깊이가 매우 깊으며 무한할 수도 있습니다.", + "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062": "형식은 자체 'then' 메서드의 처리 콜백에서 직간접적으로 참조됩니다.", + "Type_library_referenced_via_0_from_file_1_1402": "'{1}' 파일에서 '{0}'을(를) 통해 형식 라이브러리가 참조되었습니다.", + "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "packageId가 '{2}'인 '{1}' 파일에서 '{0}'을(를) 통해 형식 라이브러리가 참조되었습니다.", + "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "계산된 속성 값의 형식은 '{1}' 형식에 할당할 수 없는 '{0}'입니다.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "인스턴스 멤버 변수 '{0}'의 형식은 생성자에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", + "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*'의 반복되는 요소 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "'{0}' 속성의 형식은 매핑된 형식 '{1}'에서 순환적으로 자신을 참조합니다.", + "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "비동기 생성기에 있는 'yield' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", + "Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribut_1541": "CommonJS 모듈에서 ECMAScript 모듈의 형식 전용 가져오기에는 'resolution-mode' 특성이 있어야 합니다.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "형식이 이 가져오기에서 시작됩니다. 네임스페이스 스타일 가져오기는 호출하거나 생성할 수 없으며, 런타임에 오류를 초래합니다. 여기서는 대신 기본 가져오기 또는 가져오기 require를 사용하는 것이 좋습니다.", + "Type_parameter_0_has_a_circular_constraint_2313": "형식 매개 변수 '{0}'에 순환 제약 조건이 있습니다.", + "Type_parameter_0_has_a_circular_default_2716": "형식 매개 변수 '{0}'에 순환 기본값이 있습니다.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "내보낸 인터페이스에 있는 호출 시그니처의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "내보낸 인터페이스에 있는 생성자 시그니처의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "내보낸 클래스의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "내보낸 함수의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "내보낸 인터페이스의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103": "내보낸 매핑된 개체 형식의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 사용 중입니다.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "내보낸 형식 별칭의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "내보낸 인터페이스에 있는 메서드의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "내보낸 클래스에 있는 공용 메서드의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "내보낸 클래스에 있는 공용 정적 메서드의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_declaration_expected_1139": "형식 매개 변수 선언이 필요합니다.", + "Type_parameter_declarations_can_only_be_used_in_TypeScript_files_8004": "형식 매개 변수 선언은 TypeScript 파일에서만 사용할 수 있습니다.", + "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744": "형식 매개 변수 기본값은 이전에 선언된 형식 매개 변수만 참조할 수 있습니다.", + "Type_parameter_list_cannot_be_empty_1098": "형식 매개 변수 목록은 비워 둘 수 없습니다.", + "Type_parameter_name_cannot_be_0_2368": "형식 매개 변수 이름은 '{0}'일 수 없습니다.", + "Type_parameters_cannot_appear_on_a_constructor_declaration_1092": "형식 매개 변수는 생성자 선언에 표시될 수 없습니다.", + "Type_predicate_0_is_not_assignable_to_1_1226": "형식 조건자 '{0}'을(를) '{1}'에 할당할 수 없습니다.", + "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799": "형식이 너무 커서 표시할 수 없는 튜플 형식을 생성합니다.", + "Type_reference_directive_0_was_not_resolved_6120": "======== 형식 참조 지시문 '{0}'이(가) 확인되지 않았습니다. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 형식 참조 지시문 '{0}'이(가) '{1}'(으)로 확인되었습니다. 주: {2}. ========", + "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== 형식 참조 지시문 '{0}'이(가) 패키지 ID가 '{2}'인 '{1}'(으)로 확인되었습니다. 주: {3}. ========", + "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037": "형식 만족 식은 TypeScript 파일에서만 사용할 수 있습니다.", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "유형은 JavaScript 파일의 내보내기 선언에 나타날 수 없습니다.", + "Types_have_separate_declarations_of_a_private_property_0_2442": "형식에 별도의 프라이빗 속성 '{0}' 선언이 있습니다.", + "Types_of_construct_signatures_are_incompatible_2419": "구문 시그니처 형식이 호환되지 않습니다.", + "Types_of_parameters_0_and_1_are_incompatible_2328": "'{0}' 및 '{1}' 매개 변수의 형식이 호환되지 않습니다.", + "Types_of_property_0_are_incompatible_2326": "'{0}' 속성의 형식이 호환되지 않습니다.", + "Unable_to_open_file_0_6050": "'{0}' 파일을 열 수 없습니다.", + "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238": "식으로 호출된 경우 클래스 데코레이터의 서명을 확인할 수 없습니다.", + "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241": "식으로 호출된 경우 메서드 데코레이터의 서명을 확인할 수 없습니다.", + "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239": "식으로 호출된 경우 매개 변수 데코레이터의 서명을 확인할 수 없습니다.", + "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240": "식으로 호출된 경우 속성 데코레이터의 서명을 확인할 수 없습니다.", + "Undetermined_character_escape_1513": "결정되지 않은 문자 이스케이프입니다.", + "Unexpected_0_Did_you_mean_to_escape_it_with_backslash_1508": "예기치 않은 '{0}'입니다. 백슬래시로 이스케이프하려고 하셨나요?", + "Unexpected_end_of_text_1126": "예기치 않은 텍스트 끝입니다.", + "Unexpected_keyword_or_identifier_1434": "예기치 않은 키워드 또는 식별자입니다.", + "Unexpected_token_1012": "예기치 않은 토큰입니다.", + "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "예기치 않은 토큰입니다. 생성자, 메서드, 접근자 또는 속성이 필요합니다.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "예기치 않은 토큰입니다. 중괄호가 없는 형식 매개 변수 이름이 필요합니다.", + "Unexpected_token_Did_you_mean_or_gt_1382": "예기치 않은 토큰입니다. '{'>'}' 또는 '>'를 사용하시겠습니까?", + "Unexpected_token_Did_you_mean_or_rbrace_1381": "예기치 않은 토큰입니다. '{'}'}' 또는 '}'를 사용하시겠습니까?", + "Unexpected_token_expected_1179": "예기치 않은 토큰입니다. '{'가 있어야 합니다.", + "Unicode_escape_sequence_cannot_appear_here_17021": "유니코드 이스케이프 시퀀스는 여기에 나타날 수 없습니다.", + "Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_se_1538": "유니코드 이스케이프 시퀀스는 유니코드(u) 플래그 또는 유니코드 집합(v) 플래그가 설정된 경우에만 사용할 수 있습니다.", + "Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v__1530": "유니코드 속성 값 식은 유니코드(u) 플래그 또는 유니코드 집합(v) 플래그가 설정된 경우에만 사용할 수 있습니다.", + "Unknown_Unicode_property_name_1524": "알 수 없는 유니코드 속성 이름입니다.", + "Unknown_Unicode_property_name_or_value_1529": "알 수 없는 유니코드 속성 이름 또는 값입니다.", + "Unknown_Unicode_property_value_1526": "알 수 없는 유니코드 속성 값입니다.", + "Unknown_build_option_0_5072": "알 수 없는 빌드 옵션 '{0}'입니다.", + "Unknown_build_option_0_Did_you_mean_1_5077": "알 수 없는 빌드 옵션 '{0}'입니다. '{1}'을(를) 사용하시겠습니까?", + "Unknown_compiler_option_0_5023": "알 수 없는 컴파일러 옵션 '{0}'입니다.", + "Unknown_compiler_option_0_Did_you_mean_1_5025": "알 수 없는 컴파일러 옵션 '{0}'입니다. '{1}'을(를) 사용하시겠습니까?", + "Unknown_keyword_or_identifier_Did_you_mean_0_1435": "알 수 없는 키워드 또는 식별자입니다. '{0}'을(를) 의미했나요?", + "Unknown_option_excludes_Did_you_mean_exclude_6114": "알 수 없는 옵션 'excludes'입니다. 'exclude'를 사용하시겠습니까?", + "Unknown_regular_expression_flag_1499": "알 수 없는 정규식 플래그입니다.", + "Unknown_type_acquisition_option_0_17010": "알 수 없는 형식 인식 옵션 '{0}'입니다.", + "Unknown_type_acquisition_option_0_Did_you_mean_1_17018": "알 수 없는 형식 인식 옵션 '{0}'입니다. '{1}'을(를) 사용하시겠습니까?", + "Unknown_watch_option_0_5078": "알 수 없는 조사식 옵션 '{0}'입니다.", + "Unknown_watch_option_0_Did_you_mean_1_5079": "알 수 없는 조사식 옵션 '{0}'입니다. '{1}'을(를) 사용하시겠습니까?", + "Unreachable_code_detected_7027": "접근할 수 없는 코드가 있습니다.", + "Unterminated_Unicode_escape_sequence_1199": "종결되지 않은 유니코드 이스케이프 시퀀스입니다.", + "Unterminated_quoted_string_in_response_file_0_6045": "응답 파일 '{0}'의 종결되지 않은 따옴표 붙은 문자열입니다.", + "Unterminated_regular_expression_literal_1161": "종결되지 않은 정규식 리터럴입니다.", + "Unterminated_string_literal_1002": "종결되지 않은 문자열 리터럴입니다.", + "Unterminated_template_literal_1160": "종결되지 않은 템플릿 리터럴입니다.", + "Untyped_function_calls_may_not_accept_type_arguments_2347": "형식화되지 않은 함수 호출에는 형식 인수를 사용할 수 없습니다.", + "Unused_label_7028": "사용되지 않는 레이블입니다.", + "Unused_ts_expect_error_directive_2578": "사용되지 않는 '@ts-expect-error' 지시문입니다.", + "Update_import_from_0_90058": "\"{0}\"에서 가져오기 업데이트", + "Update_modifiers_of_0_90061": "'{0}'의 한정자 업데이트", + "Updating_output_timestamps_of_project_0_6359": "'{0}' 프로젝트의 출력 타임스탬프를 업데이트하는 중...", + "Updating_unchanged_output_timestamps_of_project_0_6371": "'{0}' 프로젝트의 변경되지 않은 출력 타임스탬프를 업데이트하는 중...", + "Use_0_95174": "`{0}`을(를) 사용합니다.", + "Use_0_instead_5106": "대신 '{0}'을(를) 사용하세요.", + "Use_Number_isNaN_in_all_conditions_95175": "모든 조건에서 'Number.isNaN'을 사용합니다.", + "Use_element_access_for_0_95145": "'{0}'에 요소 액세스 사용", + "Use_element_access_for_all_undeclared_properties_95146": "선언되지 않은 모든 속성에 요소 액세스를 사용합니다.", + "Use_import_type_95180": "'import type' 사용", + "Use_synthetic_default_member_95016": "가상 '기본' 멤버를 사용합니다.", + "Use_the_package_json_exports_field_when_resolving_package_imports_6408": "패키지 가져오기를 확인할 때 package.json 'exports' 필드를 사용합니다.", + "Use_the_package_json_imports_field_when_resolving_imports_6409": "가져오기를 확인할 때 package.json 'imports' 필드를 사용합니다.", + "Use_type_0_95181": "'형식 {0}' 사용", + "Using_0_subpath_1_with_target_2_6404": "'{0}' 하위 경로 '{1}'과(와) 대상 '{2}'을(를) 사용하는 중입니다.", + "Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found_2879": "JSX 조각을 사용하려면 조각 팩터리 '{0}'이(가) 범위에 있어야 하지만 찾을 수 없습니다.", + "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "ECMAScript 5 이상에서만 'for...of' 문에서 문자열을 사용할 수 있습니다.", + "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "--build를 사용하면 -b가 tsc로 하여금 컴파일러보다 빌드 오케스트레이터처럼 작동하도록 합니다. 이 항목은 {0}에서 더 자세히 알아볼 수 있는 복합 프로젝트를 구축하는 데 사용됩니다.", + "Using_compiler_options_of_project_reference_redirect_0_6215": "프로젝트 참조 리디렉션 '{0}'의 컴파일러 옵션을 사용 중입니다.", + "VERSION_6036": "버전", + "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "'{0}' 형식의 값에 '{1}' 형식과 공통된 속성이 없습니다. 속성을 호출하려고 했습니까?", + "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "'{0}' 형식의 값은 호출할 수 없습니다. 'new'를 포함하려고 했습니까?", + "Variable_0_implicitly_has_an_1_type_7005": "'{0}' 변수에는 암시적으로 '{1}' 형식이 포함됩니다.", + "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043": "'{0}' 변수는 암시적으로 '{1}' 형식이지만, 사용량에서 더 나은 형식을 유추할 수 있습니다.", + "Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046": "'{0}' 변수는 몇몇 위치에서 암시적으로 '{1}' 형식이지만, 사용량에서 더 나은 형식을 유추할 수 있습니다.", + "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034": "'{0}' 변수는 형식을 확인할 수 없는 경우 일부 위치에서 암시적으로 '{1}' 형식입니다.", + "Variable_0_is_used_before_being_assigned_2454": "'{0}' 변수가 할당되기 전에 사용되었습니다.", + "Variable_declaration_expected_1134": "변수 선언이 필요합니다.", + "Variable_declaration_list_cannot_be_empty_1123": "변수 선언 목록은 비워 둘 수 없습니다.", + "Variable_declaration_not_allowed_at_this_location_1440": "이 위치에서는 변수 선언을 사용할 수 없습니다.", + "Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9010": "변수에는 --isolatedDeclarations가 있는 명시적 형식 주석이 있어야 합니다.", + "Variables_with_multiple_declarations_cannot_be_inlined_95186": "선언이 여러 개 있는 변수는 인라인 처리할 수 없습니다.", + "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625": "소스의 {0} 위치에 있는 가변 인자 요소가 대상의 {1} 위치에 있는 요소와 일치하지 않습니다.", + "Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_t_2637": "차이 주석은 개체, 함수, 생성자 및 매핑된 형식의 형식 별칭에서만 지원됩니다.", + "Version_0_6029": "버전 {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file_95110": "이 파일에 대해 자세히 알아보려면 https://aka.ms/tsconfig을 방문하세요.", + "WATCH_OPTIONS_6918": "조사식 옵션", + "Watch_and_Build_Modes_6250": "시청 및 빌드 모드", + "Watch_input_files_6005": "조사식 입력 파일입니다.", + "Watch_option_0_requires_a_value_of_type_1_5080": "조사식 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "여기에서 전체 매개 변수에 대한 형식을 추가하여 '{0}'에 대한 형식만 작성할 수 있습니다.", + "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "함수를 할당할 때 매개 변수와 반환 값이 하위 형식과 호환되는지 확인합니다.", + "When_type_checking_take_into_account_null_and_undefined_6699": "유형 검사 시 'null' 및 'undefined'를 고려하세요.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "화면을 지우지 않고, 감시 모드의 오래된 콘솔 출력을 유지할지 여부입니다.", + "Wrap_all_invalid_characters_in_an_expression_container_95109": "식 컨테이너에서 모든 잘못된 문자 래핑", + "Wrap_all_invalid_decorator_expressions_in_parentheses_95195": "잘못된 데코레이터 식을 모두 괄호로 래핑합니다.", + "Wrap_all_object_literal_with_parentheses_95116": "괄호를 사용하여 모든 개체 리터럴 래핑", + "Wrap_all_unparented_JSX_in_JSX_fragment_95121": "JSX 조각에서 부모가 지정되지 않은 모든 JSX 래핑", + "Wrap_in_JSX_fragment_95120": "JSX 조각에서 래핑", + "Wrap_in_parentheses_95194": "괄호로 래핑", + "Wrap_invalid_character_in_an_expression_container_95108": "식 컨테이너에서 잘못된 문자 래핑", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "괄호를 사용하여 개체 리터럴이어야 하는 다음 본문 래핑", + "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "{0}에서 모든 컴파일러 옵션에 대해 알아볼 수 있습니다.", + "You_cannot_rename_a_module_via_a_global_import_8031": "전역 가져오기를 통해 모듈 이름을 바꿀 수 없습니다.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "'node_modules' 폴더에 정의된 요소의 이름은 변경할 수 없습니다.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "다른 'node_modules' 폴더에 정의된 요소의 이름은 변경할 수 없습니다.", + "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "표준 TypeScript 라이브러리에 정의된 요소의 이름을 바꿀 수 없습니다.", + "You_cannot_rename_this_element_8000": "이 요소의 이름을 바꿀 수 없습니다.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}'이(가) 여기에서 decorator로 사용할 인수를 너무 적게 허용합니다. 먼저 이를 호출하고 '@{0}()'을(를) 작성하시겠습니까?", + "_0_and_1_index_signatures_are_incompatible_2330": "'{0}' 및 '{1}' 인덱스 시그니처가 호환되지 않습니다.", + "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "'{0}' 및 '{1}' 작업은 괄호 없이 혼합해서 사용할 수 없습니다.", + "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}'이(가) 두 번 지정되었습니다. 이름이 '{0}'인 특성을 덮어씁니다.", + "_0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17019": "형식의 끝에 있는 '{0}'은(는) 올바른 TypeScript 구문이 아닙니다. '{1}'을(를) 쓰려고 하셨나요?", + "_0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1_17020": "형식의 시작 부분에 있는 '{0}'은(는) 올바른 TypeScript 구문이 아닙니다. '{1}'을(를) 쓰려고 하셨나요?", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}'은(는) 'esModuleInterop' 플래그를 설정하고 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}'은(는) 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}'은(는) 'require' 호출을 사용하거나 'esModuleInterop' 플래그를 설정하고 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}'은(는) 'require' 호출을 사용하거나 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}'은(는) 'import {1} = require({2})' 또는 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}'은(는) 'import {1} = require({2})'를 사용하거나 'esModuleInterop' 플래그를 설정하고 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_cannot_be_used_as_a_JSX_component_2786": "'{0}'은(는) JSX 구성 요소로 사용할 수 없습니다.", + "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "'{0}'은(는) 'export type'을 사용하여 내보냈으므로 값으로 사용할 수 없습니다.", + "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "'{0}'은(는) 'import type'을 사용하여 가져왔으므로 값으로 사용할 수 없습니다.", + "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "'{0}' 구성 요소는 텍스트를 자식 요소로 수락하지 않습니다. JSX의 텍스트는 'string' 형식이지만, '{1}'의 필요한 형식은 '{2}'입니다.", + "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082": "'{0}'은(는) '{1}'과(와) 관련되지 않은 임의의 형식으로 인스턴스화할 수 있습니다.", + "_0_declarations_can_only_be_declared_inside_a_block_1156": "'{0}' 선언은 블록 내에서만 선언할 수 있습니다.", + "_0_declarations_can_only_be_used_in_TypeScript_files_8006": "'{0}' 선언은 TypeScript 파일에서만 사용할 수 있습니다.", + "_0_declarations_may_not_have_binding_patterns_1492": "'{0}' 선언에는 바인딩 패턴이 없을 수 있습니다.", + "_0_declarations_must_be_initialized_1155": "'{0}' 선언을 초기화해야 합니다.", + "_0_expected_1005": "'{0}'이(가) 필요합니다.", + "_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is__18055": "'{0}'에는 문자열 형식이 있지만 'isolatedModules'를 사용하도록 설정한 경우 구문으로 인식할 수 있는 문자열 구문이 있어야 합니다.", + "_0_has_no_exported_member_named_1_Did_you_mean_2_2724": "'{0}'에 내보낸 멤버 '{1}'이(가) 없습니다. '{2}'이(가) 아닌지 확인하세요.", + "_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050": "'{0}'은(는) 암시적으로 '{1}' 반환 형식이지만, 사용량에서 더 나은 형식을 유추할 수 있습니다.", + "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023": "반환 형식 주석이 없고 반환 식 중 하나에서 직간접적으로 참조되므로 '{0}'에는 암시적으로 'any' 반환 형식이 포함됩니다.", + "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}'은(는) 형식 주석이 없고 자체 이니셜라이저에서 직간접적으로 참조되므로 암시적으로 'any' 형식입니다.", + "_0_index_signatures_are_incompatible_2634": "'{0}' 인덱스 시그니처가 호환되지 않습니다.", + "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "'{0}' 인덱스 유형 '{1}'을(를) '{2}' 인텍스 유형 '{3}'에 할당할 수 없습니다.", + "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0}'은(는) 기본 개체이지만 '{1}'은(는) 래퍼 개체입니다. 가능한 경우 '{0}'을(를) 사용하세요.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}'은(는) 유형이며 JavaScript 파일로 가져올 수 없습니다. JSDoc 유형 주석에서 '{1}'을(를) 사용하세요.", + "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled_1484": "'{0}'은(는) 형식이며 'verbatimModuleSyntax'를 사용하도록 설정한 경우 형식 전용 가져오기를 사용하여 가져와야 합니다.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}'은(는) '{1}'의 사용되지 않는 이름 변경입니다. 형식 주석으로 사용하려고 했습니까?", + "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}'은(는) '{1}' 형식의 제약 조건에 할당할 수 있지만, '{1}'은(는) '{2}' 제약 조건의 다른 하위 형식으로 인스턴스화할 수 있습니다.", + "_0_is_automatically_exported_here_18044": "'{0}'은(는) 여기에서 자동으로 내보내집니다.", + "_0_is_declared_but_its_value_is_never_read_6133": "'{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", + "_0_is_declared_but_never_used_6196": "'{0}'이(가) 선언되었지만 사용되지 않았습니다.", + "_0_is_declared_here_2728": "여기서는 '{0}'이(가) 선언됩니다.", + "_0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor_2611": "'{0}'은(는) '{1}' 클래스의 속성으로 정의되지만, '{2}'에서 접근자로 재정의됩니다.", + "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}'은(는) '{1}' 클래스의 접근자로 정의되지만, '{2}'에서 인스턴스 속성으로 재정의됩니다.", + "_0_is_deprecated_6385": "'{0}'은(는) 사용되지 않습니다.", + "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}'은(는) '{1}' 키워드에 대한 올바른 메타 속성이 아닙니다. '{2}'을(를) 사용하시겠습니까?", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}'은(는) 매개 변수 이름으로 사용할 수 없습니다.", + "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}'은(는) 변수 선언 이름으로 사용할 수 없습니다.", + "_0_is_of_type_unknown_18046": "'{0}'은(는) 'unknown' 형식입니다.", + "_0_is_possibly_null_18047": "'{0}'은(는) 'null'일 수 있습니다.", + "_0_is_possibly_null_or_undefined_18049": "'{0}'은(는) 'null' 또는 'undefined'일 수 있습니다.", + "_0_is_possibly_undefined_18048": "'{0}'은(는) 'undefined'일 수 있습니다.", + "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}'은(는) 자체 기본 식에서 직간접적으로 참조됩니다.", + "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}'은(는) 자체 형식 주석에서 직간접적으로 참조됩니다.", + "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783": "'{0}'이(가) 두 번 이상 지정되어 이 사용량을 덮어씁니다.", + "_0_list_cannot_be_empty_1097": "'{0}' 목록은 비워 둘 수 없습니다.", + "_0_modifier_already_seen_1030": "'{0}' 한정자가 이미 있습니다.", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias_1274": "'{0}' 한정자는 클래스, 인터페이스 또는 형식 별칭의 형식 매개 변수에만 나타날 수 있습니다.", + "_0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class_1277": "'{0}' 한정자는 함수, 메서드 또는 클래스의 형식 매개 변수에만 나타날 수 있습니다.", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "'{0}' 한정자는 생성자 선언에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "'{0}' 한정자는 모듈 또는 네임스페이스 요소에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_a_parameter_1090": "{0}' 한정자는 매개 변수에 표시될 수 없습니다.", + "_0_modifier_cannot_appear_on_a_type_member_1070": "'{0}' 한정자는 형식 멤버에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_a_type_parameter_1273": "'{0}' 한정자는 형식 매개 변수에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_a_using_declaration_1491": "'{0}' 한정자는 'using' 선언에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_an_await_using_declaration_1495": "'{0}' 한정자는 'await using' 선언에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "'{0}' 한정자는 인덱스 시니그처에 나타날 수 없습니다.", + "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031": "이 종류의 클래스 요소에는 '{0}' 한정자를 표시할 수 없습니다.", + "_0_modifier_cannot_be_used_here_1042": "'{0}' 한정자는 여기에 사용할 수 없습니다.", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "'{0}' 한정자는 앰비언트 컨텍스트에서 사용할 수 없습니다.", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 한정자는 '{1}' 한정자와 함께 사용할 수 없습니다.", + "_0_modifier_cannot_be_used_with_a_private_identifier_18019": "'{0}' 한정자는 프라이빗 식별자와 함께 사용할 수 없습니다.", + "_0_modifier_must_precede_1_modifier_1029": "'{0}' 한정자는 '{1}' 한정자 앞에 와야 합니다.", + "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531": "'\\{0}' 뒤에는 중괄호로 묶인 유니코드 속성 값 식이 와야 합니다.", + "_0_needs_an_explicit_type_annotation_2782": "'{0}'에는 명시적 형식 주석이 필요합니다.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}'은(는) 형식만 참조하지만, 여기서는 네임스페이스로 사용되고 있습니다.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}'은(는) 형식만 참조하지만, 여기서는 값으로 사용되고 있습니다.", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690": "'{0}'은(는) 형식만 참조하는데 여기에서 값으로 사용되고 있습니다. '{0}에서 {1}'을(를) 사용하려고 하셨습니까?", + "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585": "'{0}'은(는) 형식만 참조하지만, 여기서는 값으로 사용되고 있습니다. 대상 라이브러리를 변경하려는 경우 'lib' 컴파일러 옵션을 es2015 이상으로 변경해 보세요.", + "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}'은(는) UMD 전역을 참조하지만 현재 파일은 모듈입니다. 대신 가져오기를 추가해 보세요.", + "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749": "'{0}'은(는) 값을 참조하지만, 여기서는 형식으로 사용되고 있습니다. 'typeof {0}'을(를) 사용하시겠습니까?", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1291": "'{0}'은(는) 형식으로 확인되며 '{1}'이(가) 사용하도록 설정된 경우 다시 내보내기 전에 이 파일에서 형식 전용으로 표시되어야 합니다. '{0}'을(를) 가져오는 'import type'을 사용해 보세요.", + "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1292": "'{0}'은(는) 형식으로 확인되며 '{1}'이(가) 사용하도록 설정된 경우 다시 내보내기 전에 이 파일에서 형식 전용으로 표시되어야 합니다. 'export type {기본값 {0}}'을(를) 사용해 보세요.", + "_0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimMo_1485": "'{0}'은(는) 형식 전용 선언으로 확인되며 'verbatimModuleSyntax'를 사용하도록 설정한 경우 형식 전용 가져오기를 사용하여 가져와야 합니다.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1289": "'{0}'은(는) 형식 전용 선언으로 확인되며 '{1}'이(가) 사용하도록 설정된 경우 다시 내보내기 전에 이 파일에서 형식 전용으로 표시되어야 합니다. '{0}'을(를) 가져오는 'import type'을 사용해 보세요.", + "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1290": "'{0}'은(는) 형식 전용 선언으로 확인되며 '{1}'이(가) 사용하도록 설정된 경우 다시 내보내기 전에 이 파일에서 형식 전용으로 표시되어야 합니다. 'export type {기본값 {0}}'을(를) 사용해 보세요.", + "_0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_1448": "'{0}'은(는) 형식 전용 선언으로 확인되며, '{1}'을(를) 사용하도록 설정한 경우 형식 전용 다시 내보내기를 사용하여 다시 내보내야 합니다.", + "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258": "'{0}'은(는) 구성 json 파일의 'compilerOptions' 개체 내에 설정해야 합니다.", + "_0_tag_already_specified_1223": "'{0}' 태그가 이미 지정되었습니다.", + "_0_was_also_declared_here_6203": "여기서도 '{0}'이(가) 선언되었습니다.", + "_0_was_exported_here_1377": "여기서는 '{0}'을(를) 내보냈습니다.", + "_0_was_imported_here_1376": "여기서는 '{0}'을(를) 가져왔습니다.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "반환 형식 주석이 없는 '{0}'에는 암시적으로 '{1}' 반환 형식이 포함됩니다.", + "_0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type_7055": "반환 형식 주석이 없는 '{0}'에는 암시적으로 '{1}' yield 형식이 포함됩니다.", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 한정자는 클래스, 메서드 또는 속성 선언에만 나타날 수 있습니다.", + "accessor_modifier_can_only_appear_on_a_property_declaration_1275": "'accessor' 한정자는 속성 선언에만 나타날 수 있습니다.", + "and_here_6204": "및 여기.", + "arguments_cannot_be_referenced_in_property_initializers_2815": "'arguments'는 속성 이니셜라이저에서 참조할 수 없습니다.", + "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476": "\"auto\": 가져오기, 내보내기, import.meta, jsx(jsx: react-jsx 포함) 또는 esm 형식(모듈: node16+ 포함)이 있는 파일을 모듈로 처리합니다.", + "await_expression_cannot_be_used_inside_a_class_static_block_18037": "'await' 식은 클래스 정적 블록 내에서 사용할 수 없습니다.", + "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375": "'await' 식은 파일이 모듈일 경우 해당 파일의 최상위 수준에서만 사용할 수 있지만, 이 파일에는 가져오기 또는 내보내기가 없습니다. 빈 'export {}'를 추가하여 이 파일을 모듈로 만드는 것이 좋습니다.", + "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308": "'await' 식은 비동기 함수 내부 및 모듈의 최상위 수준에서만 사용할 수 있습니다.", + "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 식은 매개 변수 이니셜라이저에서 사용할 수 없습니다.", + "await_has_no_effect_on_the_type_of_this_expression_80007": "'await'는 이 식의 형식에 영향을 주지 않습니다.", + "await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_th_2853": "'await using' 문은 파일이 모듈일 경우 해당 파일의 최상위에서만 사용할 수 있지만, 이 파일에는 가져오기 또는 내보내기가 없습니다. 빈 'export {}'를 추가하여 이 파일을 모듈로 만드는 것이 좋습니다.", + "await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_2852": "'await using' 문은 비동기 함수 내부 및 모듈의 최상위 수준에서만 사용할 수 있습니다.", + "await_using_statements_cannot_be_used_inside_a_class_static_block_18054": "'await using' 문은 클래스 정적 블록 내에서 사용할 수 없습니다.", + "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' 옵션이 '{0}'(으)로 설정되어 있습니다. 상대적이지 않은 모듈 이름 '{1}'을(를) 확인하려면 이 값을 사용합니다.", + "c_must_be_followed_by_an_ASCII_letter_1512": "'\\c' 뒤에는 ASCII 문자가 와야 합니다.", + "can_only_be_used_at_the_start_of_a_file_18026": "'#!'는 파일의 시작 부분에서만 사용할 수 있습니다.", + "case_or_default_expected_1130": "'case' 또는 'default'가 필요합니다.", + "catch_or_finally_expected_1472": "'catch' 또는 'finally'가 필요합니다.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 열거형 멤버 이니셜라이저가 무한 값에 대해 평가되었습니다.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 열거형 멤버 이니셜라이저가 허용되지 않은 'NaN' 값에 대해 평가되었습니다.", + "const_enum_member_initializers_must_be_constant_expressions_2474": "const 열거형 멤버 이니셜라이저는 상수 식이어야 합니다.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성이나 인덱스 액세스 식, 또는 내보내기 할당이나 가져오기 선언의 오른쪽, 또는 형식 쿼리에서만 사용할 수 있습니다.", + "constructor_cannot_be_used_as_a_parameter_property_name_2398": "'constructor'는 매개 변수 속성 이름으로 사용할 수 없습니다.", + "constructor_is_a_reserved_word_18012": "'#constructor'는 예약어입니다.", + "default_Colon_6903": "기본값:", + "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *'는 기본값을 다시 내보내지 않습니다.", + "export_can_only_be_used_in_TypeScript_files_8003": "'export ='는 TypeScript 파일에서만 사용할 수 있습니다.", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "앰비언트 모듈 및 모듈 확대는 항상 표시되므로 'export' 한정자를 적용할 수 없습니다.", + "extends_clause_already_seen_1172": "'extends' 절이 이미 있습니다.", + "extends_clause_must_precede_implements_clause_1173": "'extends' 절은 'implements' 절 앞에 와야 합니다.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "내보낸 클래스 '{0}'의 Extends 절이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021": "내보낸 클래스의 'extends' 절이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "내보낸 인터페이스 '{0}'의 Extends 절이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "false_unless_composite_is_set_6906": "'composite'가 설정되지 않은 한 'false'입니다.", + "false_unless_strict_is_set_6905": "'strict'가 설정되지 않은 한 'false'입니다.", + "file_6025": "파일", + "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431": "'for await' 루프는 파일이 모듈일 경우 해당 파일의 최상위에서만 사용할 수 있지만, 이 파일에는 가져오기 또는 내보내기가 없습니다. 빈 'export {}'를 추가하여 이 파일을 모듈로 만드는 것이 좋습니다.", + "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103": "'for await' 루프는 비동기 함수 내부 및 모듈의 최상위에서만 사용할 수 있습니다.", + "for_await_loops_cannot_be_used_inside_a_class_static_block_18038": "'for await' 루프는 클래스 정적 블록 내에서 사용할 수 없습니다.", + "get_and_set_accessors_cannot_declare_this_parameters_2784": "'get' 및 'set' 접근자는 'this' 매개 변수를 선언할 수 없습니다.", + "if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk_6908": "'files'를 지정하면 '[]'이고, 그렇지 않으면 '[\"**/*\"]5D;'", + "implements_clause_already_seen_1175": "'implements' 절이 이미 있습니다.", + "implements_clauses_can_only_be_used_in_TypeScript_files_8005": "'implements' 절은 TypeScript 파일에서만 사용할 수 있습니다.", + "import_can_only_be_used_in_TypeScript_files_8002": "'import ... ='는 TypeScript 파일에서만 사용할 수 있습니다.", + "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338": "'infer' 선언은 조건 형식의 'extends' 절에서만 사용할 수 있습니다.", + "k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets_1510": "'\\k' 뒤에는 꺾쇠 괄호로 묶인 캡처 그룹 이름이 와야 합니다.", + "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480": "'let'은 'let' 또는 'const' 선언에서 이름으로 사용할 수 없습니다.", + "module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node_69010": "모듈 === 'AMD' 또는 'UMD' 또는 'System' 또는 'ES6', 'Classic', 그렇지 않으면 'Node'", + "module_system_or_esModuleInterop_6904": "모듈 === \"system\" 또는 esModuleInterop", + "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009": "대상에 구문 시그니처가 없는 'new' 식에는 암시적으로 'any' 형식이 포함됩니다.", + "node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified_6907": "'[\"node_modules\", \"bower_components\", \"jspm_packages\"]', 지정한 경우 'outDir' 값이 추가됩니다.", + "one_of_Colon_6900": "다음 중 하나:", + "one_or_more_Colon_6901": "하나 이상:", + "options_6024": "옵션", + "or_JSX_element_expected_1145": "'{' 또는 JSX 요소가 필요합니다.", + "or_expected_1144": "'{' 또는 ';'이(가) 필요합니다.", + "package_json_does_not_have_a_0_field_6100": "'package.json'에는 '{0}' 필드가 없습니다.", + "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json'에 '{0}' 버전과 일치하는 'typesVersions' 항목이 없습니다.", + "package_json_had_a_falsy_0_field_6220": "'package.json'에 false로 평가되는 '{0}' 필드가 있습니다.", + "package_json_has_0_field_1_that_references_2_6101": "'package.json'에 '{2}'을(를) 참조하는 '{0}' 필드 '{1}'이(가) 있습니다.", + "package_json_has_a_peerDependencies_field_6281": "'package.json'에 'peerDependencies' 필드가 있습니다.", + "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209": "'package.json'에 유효한 semver 범위가 아닌 'typesVersions' 항목 '{0}'이(가) 있습니다.", + "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208": "모듈 이름 '{2}'과(와) 일치하는 패턴을 검색하는 컴파일러 버전 '{1}'과(와) 일치하는 'typesVersions' 항목 '{0}'이(가) 'package.json'에 있습니다.", + "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206": "'package.json'에 버전별 경로 매핑이 포함된 'typesVersions' 필드가 있습니다.", + "package_json_scope_0_explicitly_maps_specifier_1_to_null_6274": "package.json 범위 '{0}'은(는) 명시적으로 '{1}' 지정자를 null에 매핑합니다.", + "package_json_scope_0_has_invalid_type_for_target_of_specifier_1_6275": "package.json 범위 '{0}'에 '{1}' 지정자의 대상 유형이 잘못되었습니다.", + "package_json_scope_0_has_no_imports_defined_6273": "package.json 범위 '{0}'에 정의된 가져오기가 없습니다.", + "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 옵션이 지정되었습니다. 모듈 이름 '{0}'과(와) 일치하는 패턴을 찾는 중입니다.", + "q_is_only_available_inside_character_class_1511": "'\\q'는 문자 클래스 내에서만 사용할 수 있습니다.", + "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521": "'\\q' 뒤에는 중괄호로 묶인 문자열 대체가 와야 합니다.", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 한정자는 속성 선언 또는 인덱스 시그니처에만 나타날 수 있습니다.", + "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "'readonly' 형식 한정자는 배열 및 튜플 리터럴 형식에서만 사용할 수 있습니다.", + "require_call_may_be_converted_to_an_import_80005": "'require' 호출이 가져오기로 변환될 수 있습니다.", + "resolution_mode_can_only_be_set_for_type_only_imports_1454": "'resolution-mode'는 유형 전용 가져오기에만 설정할 수 있습니다.", + "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "'resolution-mode'는 유형 가져오기 어설션에 유효한 유일한 키입니다.", + "resolution_mode_is_the_only_valid_key_for_type_import_attributes_1463": "'resolution-mode'는 형식 가져오기 특성에 사용할 수 있는 유일한 키입니다.", + "resolution_mode_should_be_either_require_or_import_1453": "'해상도 모드'는 '요구' 또는 '가져오기'여야 합니다.", + "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 옵션이 설정되어 있습니다. 상대 모듈 이름 '{0}'을(를) 확인하려면 이 옵션을 사용합니다.", + "super_can_only_be_referenced_in_a_derived_class_2335": "파생 클래스에서만 'super'를 참조할 수 있습니다.", + "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "파생 클래스 또는 개체 리터럴 식의 멤버에서만 'super'를 참조할 수 있습니다.", + "super_cannot_be_referenced_in_a_computed_property_name_2466": "'super'는 계산된 속성 이름에서 참조할 수 없습니다.", + "super_cannot_be_referenced_in_constructor_arguments_2336": "super'는 생성자 인수에서 참조할 수 없습니다.", + "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659": "옵션 'target'이 'ES2015' 이상인 경우 개체 리터럴 식의 멤버에서만 'super'를 사용할 수 있습니다.", + "super_may_not_use_type_arguments_2754": "'super'는 형식 인수를 사용할 수 없습니다.", + "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011": "파생 클래스의 생성자에서 'super'의 속성에 액세스하기 전에 'super'를 호출해야 합니다.", + "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009": "파생 클래스의 생성자에서 'this'에 액세스하기 전에 'super'를 호출해야 합니다.", + "super_must_be_followed_by_an_argument_list_or_member_access_1034": "'super' 다음에는 인수 목록 또는 멤버 액세스가 와야 합니다.", + "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338": "'super' 속성 액세스는 생성자, 멤버 함수 또는 파생 클래스의 멤버 접근자에서만 허용됩니다.", + "this_cannot_be_referenced_in_a_computed_property_name_2465": "'this'는 계산된 속성 이름에서 참조할 수 없습니다.", + "this_cannot_be_referenced_in_a_module_or_namespace_body_2331": "'this'는 모듈 또는 네임스페이스 본문에서 참조될 수 없습니다.", + "this_cannot_be_referenced_in_a_static_property_initializer_2334": "정적 속성 이니셜라이저에서 'this'를 참조할 수 없습니다.", + "this_cannot_be_referenced_in_current_location_2332": "현재 위치에서 'this'를 참조할 수 없습니다.", + "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683": "'this'에는 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "true_for_ES2022_and_above_including_ESNext_6930": "ESNext를 포함하여 ES2022 이상의 경우 'true'입니다.", + "true_if_composite_false_otherwise_6909": "'composite'이면 'true'이고, 그렇지 않으면 'false'입니다.", + "true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false_6411": "'moduleResolution'이 'node16', 'nodenext' 또는 'bundler'인 경우 'true'입니다. 그렇지 않으면 'false'입니다.", + "tsc_Colon_The_TypeScript_Compiler_6922": "tsc: TypeScript 컴파일러", + "type_Colon_6902": "형식:", + "unique_symbol_types_are_not_allowed_here_1335": "여기에서 'unique symbol' 형식은 허용되지 않습니다.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'unique symbol' 형식은 변수 문의 변수에만 허용됩니다.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' 형식은 바인딩 이름과 함께 변수 선언에 사용할 수 없습니다.", + "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347": "'use strict' 지시문은 단순하지 않은 매개 변수 목록에서 사용할 수 없습니다.", + "use_strict_directive_used_here_1349": "여기서는 'use strict' 지시문이 사용됩니다.", + "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' 문은 비동기 함수 블록에서 사용할 수 없습니다.", + "with_statements_are_not_allowed_in_strict_mode_1101": "'with' 문은 strict 모드에서 사용할 수 없습니다.", + "yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057": "'yield' 식은 포함하는 생성기에 반환 형식 주석이 없으므로 암시적으로 'any' 형식으로 생성됩니다.", + "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 식은 매개 변수 이니셜라이저에서 사용할 수 없습니다." +} \ No newline at end of file diff --git a/node_modules/typescript/lib/lib.d.ts b/node_modules/typescript/lib/lib.d.ts new file mode 100644 index 00000000..b6bb44b2 --- /dev/null +++ b/node_modules/typescript/lib/lib.d.ts @@ -0,0 +1,22 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +/// +/// +/// +/// diff --git a/node_modules/typescript/lib/lib.decorators.d.ts b/node_modules/typescript/lib/lib.decorators.d.ts new file mode 100644 index 00000000..5ad7216a --- /dev/null +++ b/node_modules/typescript/lib/lib.decorators.d.ts @@ -0,0 +1,384 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +/** + * The decorator context types provided to class element decorators. + */ +type ClassMemberDecoratorContext = + | ClassMethodDecoratorContext + | ClassGetterDecoratorContext + | ClassSetterDecoratorContext + | ClassFieldDecoratorContext + | ClassAccessorDecoratorContext; + +/** + * The decorator context types provided to any decorator. + */ +type DecoratorContext = + | ClassDecoratorContext + | ClassMemberDecoratorContext; + +type DecoratorMetadataObject = Record & object; + +type DecoratorMetadata = typeof globalThis extends { Symbol: { readonly metadata: symbol; }; } ? DecoratorMetadataObject : DecoratorMetadataObject | undefined; + +/** + * Context provided to a class decorator. + * @template Class The type of the decorated class associated with this context. + */ +interface ClassDecoratorContext< + Class extends abstract new (...args: any) => any = abstract new (...args: any) => any, +> { + /** The kind of element that was decorated. */ + readonly kind: "class"; + + /** The name of the decorated class. */ + readonly name: string | undefined; + + /** + * Adds a callback to be invoked after the class definition has been finalized. + * + * @example + * ```ts + * function customElement(name: string): ClassDecoratorFunction { + * return (target, context) => { + * context.addInitializer(function () { + * customElements.define(name, this); + * }); + * } + * } + * + * @customElement("my-element") + * class MyElement {} + * ``` + */ + addInitializer(initializer: (this: Class) => void): void; + + readonly metadata: DecoratorMetadata; +} + +/** + * Context provided to a class method decorator. + * @template This The type on which the class element will be defined. For a static class element, this will be + * the type of the constructor. For a non-static class element, this will be the type of the instance. + * @template Value The type of the decorated class method. + */ +interface ClassMethodDecoratorContext< + This = unknown, + Value extends (this: This, ...args: any) => any = (this: This, ...args: any) => any, +> { + /** The kind of class element that was decorated. */ + readonly kind: "method"; + + /** The name of the decorated class element. */ + readonly name: string | symbol; + + /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ + readonly static: boolean; + + /** A value indicating whether the class element has a private name. */ + readonly private: boolean; + + /** An object that can be used to access the current value of the class element at runtime. */ + readonly access: { + /** + * Determines whether an object has a property with the same name as the decorated element. + */ + has(object: This): boolean; + /** + * Gets the current value of the method from the provided object. + * + * @example + * let fn = context.access.get(instance); + */ + get(object: This): Value; + }; + + /** + * Adds a callback to be invoked either after static methods are defined but before + * static initializers are run (when decorating a `static` element), or before instance + * initializers are run (when decorating a non-`static` element). + * + * @example + * ```ts + * const bound: ClassMethodDecoratorFunction = (value, context) { + * if (context.private) throw new TypeError("Not supported on private methods."); + * context.addInitializer(function () { + * this[context.name] = this[context.name].bind(this); + * }); + * } + * + * class C { + * message = "Hello"; + * + * @bound + * m() { + * console.log(this.message); + * } + * } + * ``` + */ + addInitializer(initializer: (this: This) => void): void; + + readonly metadata: DecoratorMetadata; +} + +/** + * Context provided to a class getter decorator. + * @template This The type on which the class element will be defined. For a static class element, this will be + * the type of the constructor. For a non-static class element, this will be the type of the instance. + * @template Value The property type of the decorated class getter. + */ +interface ClassGetterDecoratorContext< + This = unknown, + Value = unknown, +> { + /** The kind of class element that was decorated. */ + readonly kind: "getter"; + + /** The name of the decorated class element. */ + readonly name: string | symbol; + + /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ + readonly static: boolean; + + /** A value indicating whether the class element has a private name. */ + readonly private: boolean; + + /** An object that can be used to access the current value of the class element at runtime. */ + readonly access: { + /** + * Determines whether an object has a property with the same name as the decorated element. + */ + has(object: This): boolean; + /** + * Invokes the getter on the provided object. + * + * @example + * let value = context.access.get(instance); + */ + get(object: This): Value; + }; + + /** + * Adds a callback to be invoked either after static methods are defined but before + * static initializers are run (when decorating a `static` element), or before instance + * initializers are run (when decorating a non-`static` element). + */ + addInitializer(initializer: (this: This) => void): void; + + readonly metadata: DecoratorMetadata; +} + +/** + * Context provided to a class setter decorator. + * @template This The type on which the class element will be defined. For a static class element, this will be + * the type of the constructor. For a non-static class element, this will be the type of the instance. + * @template Value The type of the decorated class setter. + */ +interface ClassSetterDecoratorContext< + This = unknown, + Value = unknown, +> { + /** The kind of class element that was decorated. */ + readonly kind: "setter"; + + /** The name of the decorated class element. */ + readonly name: string | symbol; + + /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ + readonly static: boolean; + + /** A value indicating whether the class element has a private name. */ + readonly private: boolean; + + /** An object that can be used to access the current value of the class element at runtime. */ + readonly access: { + /** + * Determines whether an object has a property with the same name as the decorated element. + */ + has(object: This): boolean; + /** + * Invokes the setter on the provided object. + * + * @example + * context.access.set(instance, value); + */ + set(object: This, value: Value): void; + }; + + /** + * Adds a callback to be invoked either after static methods are defined but before + * static initializers are run (when decorating a `static` element), or before instance + * initializers are run (when decorating a non-`static` element). + */ + addInitializer(initializer: (this: This) => void): void; + + readonly metadata: DecoratorMetadata; +} + +/** + * Context provided to a class `accessor` field decorator. + * @template This The type on which the class element will be defined. For a static class element, this will be + * the type of the constructor. For a non-static class element, this will be the type of the instance. + * @template Value The type of decorated class field. + */ +interface ClassAccessorDecoratorContext< + This = unknown, + Value = unknown, +> { + /** The kind of class element that was decorated. */ + readonly kind: "accessor"; + + /** The name of the decorated class element. */ + readonly name: string | symbol; + + /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ + readonly static: boolean; + + /** A value indicating whether the class element has a private name. */ + readonly private: boolean; + + /** An object that can be used to access the current value of the class element at runtime. */ + readonly access: { + /** + * Determines whether an object has a property with the same name as the decorated element. + */ + has(object: This): boolean; + + /** + * Invokes the getter on the provided object. + * + * @example + * let value = context.access.get(instance); + */ + get(object: This): Value; + + /** + * Invokes the setter on the provided object. + * + * @example + * context.access.set(instance, value); + */ + set(object: This, value: Value): void; + }; + + /** + * Adds a callback to be invoked immediately after the auto `accessor` being + * decorated is initialized (regardless if the `accessor` is `static` or not). + */ + addInitializer(initializer: (this: This) => void): void; + + readonly metadata: DecoratorMetadata; +} + +/** + * Describes the target provided to class `accessor` field decorators. + * @template This The `this` type to which the target applies. + * @template Value The property type for the class `accessor` field. + */ +interface ClassAccessorDecoratorTarget { + /** + * Invokes the getter that was defined prior to decorator application. + * + * @example + * let value = target.get.call(instance); + */ + get(this: This): Value; + + /** + * Invokes the setter that was defined prior to decorator application. + * + * @example + * target.set.call(instance, value); + */ + set(this: This, value: Value): void; +} + +/** + * Describes the allowed return value from a class `accessor` field decorator. + * @template This The `this` type to which the target applies. + * @template Value The property type for the class `accessor` field. + */ +interface ClassAccessorDecoratorResult { + /** + * An optional replacement getter function. If not provided, the existing getter function is used instead. + */ + get?(this: This): Value; + + /** + * An optional replacement setter function. If not provided, the existing setter function is used instead. + */ + set?(this: This, value: Value): void; + + /** + * An optional initializer mutator that is invoked when the underlying field initializer is evaluated. + * @param value The incoming initializer value. + * @returns The replacement initializer value. + */ + init?(this: This, value: Value): Value; +} + +/** + * Context provided to a class field decorator. + * @template This The type on which the class element will be defined. For a static class element, this will be + * the type of the constructor. For a non-static class element, this will be the type of the instance. + * @template Value The type of the decorated class field. + */ +interface ClassFieldDecoratorContext< + This = unknown, + Value = unknown, +> { + /** The kind of class element that was decorated. */ + readonly kind: "field"; + + /** The name of the decorated class element. */ + readonly name: string | symbol; + + /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ + readonly static: boolean; + + /** A value indicating whether the class element has a private name. */ + readonly private: boolean; + + /** An object that can be used to access the current value of the class element at runtime. */ + readonly access: { + /** + * Determines whether an object has a property with the same name as the decorated element. + */ + has(object: This): boolean; + + /** + * Gets the value of the field on the provided object. + */ + get(object: This): Value; + + /** + * Sets the value of the field on the provided object. + */ + set(object: This, value: Value): void; + }; + + /** + * Adds a callback to be invoked immediately after the field being decorated + * is initialized (regardless if the field is `static` or not). + */ + addInitializer(initializer: (this: This) => void): void; + + readonly metadata: DecoratorMetadata; +} diff --git a/node_modules/typescript/lib/lib.decorators.legacy.d.ts b/node_modules/typescript/lib/lib.decorators.legacy.d.ts new file mode 100644 index 00000000..26fbcb52 --- /dev/null +++ b/node_modules/typescript/lib/lib.decorators.legacy.d.ts @@ -0,0 +1,22 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +declare type ClassDecorator = (target: TFunction) => TFunction | void; +declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; +declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; +declare type ParameterDecorator = (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) => void; diff --git a/node_modules/typescript/lib/lib.dom.asynciterable.d.ts b/node_modules/typescript/lib/lib.dom.asynciterable.d.ts new file mode 100644 index 00000000..98b96b81 --- /dev/null +++ b/node_modules/typescript/lib/lib.dom.asynciterable.d.ts @@ -0,0 +1,41 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +///////////////////////////// +/// Window Async Iterable APIs +///////////////////////////// + +interface FileSystemDirectoryHandleAsyncIterator extends AsyncIteratorObject { + [Symbol.asyncIterator](): FileSystemDirectoryHandleAsyncIterator; +} + +interface FileSystemDirectoryHandle { + [Symbol.asyncIterator](): FileSystemDirectoryHandleAsyncIterator<[string, FileSystemHandle]>; + entries(): FileSystemDirectoryHandleAsyncIterator<[string, FileSystemHandle]>; + keys(): FileSystemDirectoryHandleAsyncIterator; + values(): FileSystemDirectoryHandleAsyncIterator; +} + +interface ReadableStreamAsyncIterator extends AsyncIteratorObject { + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; +} + +interface ReadableStream { + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; +} diff --git a/node_modules/typescript/lib/lib.dom.d.ts b/node_modules/typescript/lib/lib.dom.d.ts new file mode 100644 index 00000000..edf900a5 --- /dev/null +++ b/node_modules/typescript/lib/lib.dom.d.ts @@ -0,0 +1,29610 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +///////////////////////////// +/// Window APIs +///////////////////////////// + +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; + signal?: AbortSignal; +} + +interface AddressErrors { + addressLine?: string; + city?: string; + country?: string; + dependentLocality?: string; + organization?: string; + phone?: string; + postalCode?: string; + recipient?: string; + region?: string; + sortingCode?: string; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface Algorithm { + name: string; +} + +interface AnalyserOptions extends AudioNodeOptions { + fftSize?: number; + maxDecibels?: number; + minDecibels?: number; + smoothingTimeConstant?: number; +} + +interface AnimationEventInit extends EventInit { + animationName?: string; + elapsedTime?: number; + pseudoElement?: string; +} + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: CSSNumberish | null; + timelineTime?: CSSNumberish | null; +} + +interface AssignedNodesOptions { + flatten?: boolean; +} + +interface AudioBufferOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface AudioBufferSourceOptions { + buffer?: AudioBuffer | null; + detune?: number; + loop?: boolean; + loopEnd?: number; + loopStart?: number; + playbackRate?: number; +} + +interface AudioConfiguration { + bitrate?: number; + channels?: string; + contentType: string; + samplerate?: number; + spatialRendering?: boolean; +} + +interface AudioContextOptions { + latencyHint?: AudioContextLatencyCategory | number; + sampleRate?: number; +} + +interface AudioDataCopyToOptions { + format?: AudioSampleFormat; + frameCount?: number; + frameOffset?: number; + planeIndex: number; +} + +interface AudioDataInit { + data: BufferSource; + format: AudioSampleFormat; + numberOfChannels: number; + numberOfFrames: number; + sampleRate: number; + timestamp: number; + transfer?: ArrayBuffer[]; +} + +interface AudioDecoderConfig { + codec: string; + description?: BufferSource; + numberOfChannels: number; + sampleRate: number; +} + +interface AudioDecoderInit { + error: WebCodecsErrorCallback; + output: AudioDataOutputCallback; +} + +interface AudioDecoderSupport { + config?: AudioDecoderConfig; + supported?: boolean; +} + +interface AudioEncoderConfig { + bitrate?: number; + bitrateMode?: BitrateMode; + codec: string; + numberOfChannels: number; + opus?: OpusEncoderConfig; + sampleRate: number; +} + +interface AudioEncoderInit { + error: WebCodecsErrorCallback; + output: EncodedAudioChunkOutputCallback; +} + +interface AudioEncoderSupport { + config?: AudioEncoderConfig; + supported?: boolean; +} + +interface AudioNodeOptions { + channelCount?: number; + channelCountMode?: ChannelCountMode; + channelInterpretation?: ChannelInterpretation; +} + +interface AudioProcessingEventInit extends EventInit { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +interface AudioTimestamp { + contextTime?: number; + performanceTime?: DOMHighResTimeStamp; +} + +interface AudioWorkletNodeOptions extends AudioNodeOptions { + numberOfInputs?: number; + numberOfOutputs?: number; + outputChannelCount?: number[]; + parameterData?: Record; + processorOptions?: any; +} + +interface AuthenticationExtensionsClientInputs { + appid?: string; + credProps?: boolean; + hmacCreateSecret?: boolean; + minPinLength?: boolean; + prf?: AuthenticationExtensionsPRFInputs; +} + +interface AuthenticationExtensionsClientInputsJSON { +} + +interface AuthenticationExtensionsClientOutputs { + appid?: boolean; + credProps?: CredentialPropertiesOutput; + hmacCreateSecret?: boolean; + prf?: AuthenticationExtensionsPRFOutputs; +} + +interface AuthenticationExtensionsPRFInputs { + eval?: AuthenticationExtensionsPRFValues; + evalByCredential?: Record; +} + +interface AuthenticationExtensionsPRFOutputs { + enabled?: boolean; + results?: AuthenticationExtensionsPRFValues; +} + +interface AuthenticationExtensionsPRFValues { + first: BufferSource; + second?: BufferSource; +} + +interface AuthenticatorSelectionCriteria { + authenticatorAttachment?: AuthenticatorAttachment; + requireResidentKey?: boolean; + residentKey?: ResidentKeyRequirement; + userVerification?: UserVerificationRequirement; +} + +interface AvcEncoderConfig { + format?: AvcBitstreamFormat; +} + +interface BiquadFilterOptions extends AudioNodeOptions { + Q?: number; + detune?: number; + frequency?: number; + gain?: number; + type?: BiquadFilterType; +} + +interface BlobEventInit { + data: Blob; + timecode?: DOMHighResTimeStamp; +} + +interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +interface CSSMatrixComponentOptions { + is2D?: boolean; +} + +interface CSSNumericType { + angle?: number; + flex?: number; + frequency?: number; + length?: number; + percent?: number; + percentHint?: CSSNumericBaseType; + resolution?: number; + time?: number; +} + +interface CSSStyleSheetInit { + baseURL?: string; + disabled?: boolean; + media?: MediaList | string; +} + +interface CacheQueryOptions { + ignoreMethod?: boolean; + ignoreSearch?: boolean; + ignoreVary?: boolean; +} + +interface CanvasRenderingContext2DSettings { + alpha?: boolean; + colorSpace?: PredefinedColorSpace; + desynchronized?: boolean; + willReadFrequently?: boolean; +} + +interface CaretPositionFromPointOptions { + shadowRoots?: ShadowRoot[]; +} + +interface ChannelMergerOptions extends AudioNodeOptions { + numberOfInputs?: number; +} + +interface ChannelSplitterOptions extends AudioNodeOptions { + numberOfOutputs?: number; +} + +interface CheckVisibilityOptions { + checkOpacity?: boolean; + checkVisibilityCSS?: boolean; + contentVisibilityAuto?: boolean; + opacityProperty?: boolean; + visibilityProperty?: boolean; +} + +interface ClientQueryOptions { + includeUncontrolled?: boolean; + type?: ClientTypes; +} + +interface ClipboardEventInit extends EventInit { + clipboardData?: DataTransfer | null; +} + +interface ClipboardItemOptions { + presentationStyle?: PresentationStyle; +} + +interface CloseEventInit extends EventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} + +interface CompositionEventInit extends UIEventInit { + data?: string; +} + +interface ComputedEffectTiming extends EffectTiming { + activeDuration?: CSSNumberish; + currentIteration?: number | null; + endTime?: CSSNumberish; + localTime?: CSSNumberish | null; + progress?: number | null; + startTime?: CSSNumberish; +} + +interface ComputedKeyframe { + composite: CompositeOperationOrAuto; + computedOffset: number; + easing: string; + offset: number | null; + [property: string]: string | number | null | undefined; +} + +interface ConstantSourceOptions { + offset?: number; +} + +interface ConstrainBooleanParameters { + exact?: boolean; + ideal?: boolean; +} + +interface ConstrainDOMStringParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface ConstrainDoubleRange extends DoubleRange { + exact?: number; + ideal?: number; +} + +interface ConstrainULongRange extends ULongRange { + exact?: number; + ideal?: number; +} + +interface ContentVisibilityAutoStateChangeEventInit extends EventInit { + skipped?: boolean; +} + +interface ConvolverOptions extends AudioNodeOptions { + buffer?: AudioBuffer | null; + disableNormalization?: boolean; +} + +interface CredentialCreationOptions { + publicKey?: PublicKeyCredentialCreationOptions; + signal?: AbortSignal; +} + +interface CredentialPropertiesOutput { + rk?: boolean; +} + +interface CredentialRequestOptions { + mediation?: CredentialMediationRequirement; + publicKey?: PublicKeyCredentialRequestOptions; + signal?: AbortSignal; +} + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +interface CustomEventInit extends EventInit { + detail?: T; +} + +interface DOMMatrix2DInit { + a?: number; + b?: number; + c?: number; + d?: number; + e?: number; + f?: number; + m11?: number; + m12?: number; + m21?: number; + m22?: number; + m41?: number; + m42?: number; +} + +interface DOMMatrixInit extends DOMMatrix2DInit { + is2D?: boolean; + m13?: number; + m14?: number; + m23?: number; + m24?: number; + m31?: number; + m32?: number; + m33?: number; + m34?: number; + m43?: number; + m44?: number; +} + +interface DOMPointInit { + w?: number; + x?: number; + y?: number; + z?: number; +} + +interface DOMQuadInit { + p1?: DOMPointInit; + p2?: DOMPointInit; + p3?: DOMPointInit; + p4?: DOMPointInit; +} + +interface DOMRectInit { + height?: number; + width?: number; + x?: number; + y?: number; +} + +interface DelayOptions extends AudioNodeOptions { + delayTime?: number; + maxDelayTime?: number; +} + +interface DeviceMotionEventAccelerationInit { + x?: number | null; + y?: number | null; + z?: number | null; +} + +interface DeviceMotionEventInit extends EventInit { + acceleration?: DeviceMotionEventAccelerationInit; + accelerationIncludingGravity?: DeviceMotionEventAccelerationInit; + interval?: number; + rotationRate?: DeviceMotionEventRotationRateInit; +} + +interface DeviceMotionEventRotationRateInit { + alpha?: number | null; + beta?: number | null; + gamma?: number | null; +} + +interface DeviceOrientationEventInit extends EventInit { + absolute?: boolean; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; +} + +interface DisplayMediaStreamOptions { + audio?: boolean | MediaTrackConstraints; + video?: boolean | MediaTrackConstraints; +} + +interface DocumentTimelineOptions { + originTime?: DOMHighResTimeStamp; +} + +interface DoubleRange { + max?: number; + min?: number; +} + +interface DragEventInit extends MouseEventInit { + dataTransfer?: DataTransfer | null; +} + +interface DynamicsCompressorOptions extends AudioNodeOptions { + attack?: number; + knee?: number; + ratio?: number; + release?: number; + threshold?: number; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; +} + +interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + +interface EffectTiming { + delay?: number; + direction?: PlaybackDirection; + duration?: number | CSSNumericValue | string; + easing?: string; + endDelay?: number; + fill?: FillMode; + iterationStart?: number; + iterations?: number; + playbackRate?: number; +} + +interface ElementCreationOptions { + is?: string; +} + +interface ElementDefinitionOptions { + extends?: string; +} + +interface EncodedAudioChunkInit { + data: AllowSharedBufferSource; + duration?: number; + timestamp: number; + transfer?: ArrayBuffer[]; + type: EncodedAudioChunkType; +} + +interface EncodedAudioChunkMetadata { + decoderConfig?: AudioDecoderConfig; +} + +interface EncodedVideoChunkInit { + data: AllowSharedBufferSource; + duration?: number; + timestamp: number; + type: EncodedVideoChunkType; +} + +interface EncodedVideoChunkMetadata { + decoderConfig?: VideoDecoderConfig; +} + +interface ErrorEventInit extends EventInit { + colno?: number; + error?: any; + filename?: string; + lineno?: number; + message?: string; +} + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + capture?: boolean; +} + +interface EventModifierInit extends UIEventInit { + altKey?: boolean; + ctrlKey?: boolean; + metaKey?: boolean; + modifierAltGraph?: boolean; + modifierCapsLock?: boolean; + modifierFn?: boolean; + modifierFnLock?: boolean; + modifierHyper?: boolean; + modifierNumLock?: boolean; + modifierScrollLock?: boolean; + modifierSuper?: boolean; + modifierSymbol?: boolean; + modifierSymbolLock?: boolean; + shiftKey?: boolean; +} + +interface EventSourceInit { + withCredentials?: boolean; +} + +interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +interface FileSystemCreateWritableOptions { + keepExistingData?: boolean; +} + +interface FileSystemFlags { + create?: boolean; + exclusive?: boolean; +} + +interface FileSystemGetDirectoryOptions { + create?: boolean; +} + +interface FileSystemGetFileOptions { + create?: boolean; +} + +interface FileSystemRemoveOptions { + recursive?: boolean; +} + +interface FocusEventInit extends UIEventInit { + relatedTarget?: EventTarget | null; +} + +interface FocusOptions { + preventScroll?: boolean; +} + +interface FontFaceDescriptors { + ascentOverride?: string; + descentOverride?: string; + display?: FontDisplay; + featureSettings?: string; + lineGapOverride?: string; + stretch?: string; + style?: string; + unicodeRange?: string; + weight?: string; +} + +interface FontFaceSetLoadEventInit extends EventInit { + fontfaces?: FontFace[]; +} + +interface FormDataEventInit extends EventInit { + formData: FormData; +} + +interface FullscreenOptions { + navigationUI?: FullscreenNavigationUI; +} + +interface GainOptions extends AudioNodeOptions { + gain?: number; +} + +interface GamepadEffectParameters { + duration?: number; + leftTrigger?: number; + rightTrigger?: number; + startDelay?: number; + strongMagnitude?: number; + weakMagnitude?: number; +} + +interface GamepadEventInit extends EventInit { + gamepad: Gamepad; +} + +interface GetAnimationsOptions { + subtree?: boolean; +} + +interface GetHTMLOptions { + serializableShadowRoots?: boolean; + shadowRoots?: ShadowRoot[]; +} + +interface GetNotificationOptions { + tag?: string; +} + +interface GetRootNodeOptions { + composed?: boolean; +} + +interface HashChangeEventInit extends EventInit { + newURL?: string; + oldURL?: string; +} + +interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + +interface IDBDatabaseInfo { + name?: string; + version?: number; +} + +interface IDBIndexParameters { + multiEntry?: boolean; + unique?: boolean; +} + +interface IDBObjectStoreParameters { + autoIncrement?: boolean; + keyPath?: string | string[] | null; +} + +interface IDBTransactionOptions { + durability?: IDBTransactionDurability; +} + +interface IDBVersionChangeEventInit extends EventInit { + newVersion?: number | null; + oldVersion?: number; +} + +interface IIRFilterOptions extends AudioNodeOptions { + feedback: number[]; + feedforward: number[]; +} + +interface IdleRequestOptions { + timeout?: number; +} + +interface ImageBitmapOptions { + colorSpaceConversion?: ColorSpaceConversion; + imageOrientation?: ImageOrientation; + premultiplyAlpha?: PremultiplyAlpha; + resizeHeight?: number; + resizeQuality?: ResizeQuality; + resizeWidth?: number; +} + +interface ImageBitmapRenderingContextSettings { + alpha?: boolean; +} + +interface ImageDataSettings { + colorSpace?: PredefinedColorSpace; +} + +interface ImageDecodeOptions { + completeFramesOnly?: boolean; + frameIndex?: number; +} + +interface ImageDecodeResult { + complete: boolean; + image: VideoFrame; +} + +interface ImageDecoderInit { + colorSpaceConversion?: ColorSpaceConversion; + data: ImageBufferSource; + desiredHeight?: number; + desiredWidth?: number; + preferAnimation?: boolean; + transfer?: ArrayBuffer[]; + type: string; +} + +interface ImageEncodeOptions { + quality?: number; + type?: string; +} + +interface InputEventInit extends UIEventInit { + data?: string | null; + dataTransfer?: DataTransfer | null; + inputType?: string; + isComposing?: boolean; + targetRanges?: StaticRange[]; +} + +interface IntersectionObserverInit { + root?: Element | Document | null; + rootMargin?: string; + threshold?: number | number[]; +} + +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + +interface KeyAlgorithm { + name: string; +} + +interface KeyboardEventInit extends EventModifierInit { + /** @deprecated */ + charCode?: number; + code?: string; + isComposing?: boolean; + key?: string; + /** @deprecated */ + keyCode?: number; + location?: number; + repeat?: boolean; +} + +interface Keyframe { + composite?: CompositeOperationOrAuto; + easing?: string; + offset?: number | null; + [property: string]: string | number | null | undefined; +} + +interface KeyframeAnimationOptions extends KeyframeEffectOptions { + id?: string; + timeline?: AnimationTimeline | null; +} + +interface KeyframeEffectOptions extends EffectTiming { + composite?: CompositeOperation; + iterationComposite?: IterationCompositeOperation; + pseudoElement?: string | null; +} + +interface LockInfo { + clientId?: string; + mode?: LockMode; + name?: string; +} + +interface LockManagerSnapshot { + held?: LockInfo[]; + pending?: LockInfo[]; +} + +interface LockOptions { + ifAvailable?: boolean; + mode?: LockMode; + signal?: AbortSignal; + steal?: boolean; +} + +interface MIDIConnectionEventInit extends EventInit { + port?: MIDIPort; +} + +interface MIDIMessageEventInit extends EventInit { + data?: Uint8Array; +} + +interface MIDIOptions { + software?: boolean; + sysex?: boolean; +} + +interface MediaCapabilitiesDecodingInfo extends MediaCapabilitiesInfo { + configuration?: MediaDecodingConfiguration; +} + +interface MediaCapabilitiesEncodingInfo extends MediaCapabilitiesInfo { + configuration?: MediaEncodingConfiguration; +} + +interface MediaCapabilitiesInfo { + powerEfficient: boolean; + smooth: boolean; + supported: boolean; +} + +interface MediaConfiguration { + audio?: AudioConfiguration; + video?: VideoConfiguration; +} + +interface MediaDecodingConfiguration extends MediaConfiguration { + type: MediaDecodingType; +} + +interface MediaElementAudioSourceOptions { + mediaElement: HTMLMediaElement; +} + +interface MediaEncodingConfiguration extends MediaConfiguration { + type: MediaEncodingType; +} + +interface MediaEncryptedEventInit extends EventInit { + initData?: ArrayBuffer | null; + initDataType?: string; +} + +interface MediaImage { + sizes?: string; + src: string; + type?: string; +} + +interface MediaKeyMessageEventInit extends EventInit { + message: ArrayBuffer; + messageType: MediaKeyMessageType; +} + +interface MediaKeySystemConfiguration { + audioCapabilities?: MediaKeySystemMediaCapability[]; + distinctiveIdentifier?: MediaKeysRequirement; + initDataTypes?: string[]; + label?: string; + persistentState?: MediaKeysRequirement; + sessionTypes?: string[]; + videoCapabilities?: MediaKeySystemMediaCapability[]; +} + +interface MediaKeySystemMediaCapability { + contentType?: string; + encryptionScheme?: string | null; + robustness?: string; +} + +interface MediaKeysPolicy { + minHdcpVersion?: string; +} + +interface MediaMetadataInit { + album?: string; + artist?: string; + artwork?: MediaImage[]; + title?: string; +} + +interface MediaPositionState { + duration?: number; + playbackRate?: number; + position?: number; +} + +interface MediaQueryListEventInit extends EventInit { + matches?: boolean; + media?: string; +} + +interface MediaRecorderOptions { + audioBitsPerSecond?: number; + bitsPerSecond?: number; + mimeType?: string; + videoBitsPerSecond?: number; +} + +interface MediaSessionActionDetails { + action: MediaSessionAction; + fastSeek?: boolean; + seekOffset?: number; + seekTime?: number; +} + +interface MediaStreamAudioSourceOptions { + mediaStream: MediaStream; +} + +interface MediaStreamConstraints { + audio?: boolean | MediaTrackConstraints; + peerIdentity?: string; + preferCurrentTab?: boolean; + video?: boolean | MediaTrackConstraints; +} + +interface MediaStreamTrackEventInit extends EventInit { + track: MediaStreamTrack; +} + +interface MediaTrackCapabilities { + aspectRatio?: DoubleRange; + autoGainControl?: boolean[]; + backgroundBlur?: boolean[]; + channelCount?: ULongRange; + deviceId?: string; + displaySurface?: string; + echoCancellation?: boolean[]; + facingMode?: string[]; + frameRate?: DoubleRange; + groupId?: string; + height?: ULongRange; + noiseSuppression?: boolean[]; + sampleRate?: ULongRange; + sampleSize?: ULongRange; + width?: ULongRange; +} + +interface MediaTrackConstraintSet { + aspectRatio?: ConstrainDouble; + autoGainControl?: ConstrainBoolean; + backgroundBlur?: ConstrainBoolean; + channelCount?: ConstrainULong; + deviceId?: ConstrainDOMString; + displaySurface?: ConstrainDOMString; + echoCancellation?: ConstrainBoolean; + facingMode?: ConstrainDOMString; + frameRate?: ConstrainDouble; + groupId?: ConstrainDOMString; + height?: ConstrainULong; + noiseSuppression?: ConstrainBoolean; + sampleRate?: ConstrainULong; + sampleSize?: ConstrainULong; + width?: ConstrainULong; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackSettings { + aspectRatio?: number; + autoGainControl?: boolean; + backgroundBlur?: boolean; + channelCount?: number; + deviceId?: string; + displaySurface?: string; + echoCancellation?: boolean; + facingMode?: string; + frameRate?: number; + groupId?: string; + height?: number; + noiseSuppression?: boolean; + sampleRate?: number; + sampleSize?: number; + width?: number; +} + +interface MediaTrackSupportedConstraints { + aspectRatio?: boolean; + autoGainControl?: boolean; + backgroundBlur?: boolean; + channelCount?: boolean; + deviceId?: boolean; + displaySurface?: boolean; + echoCancellation?: boolean; + facingMode?: boolean; + frameRate?: boolean; + groupId?: boolean; + height?: boolean; + noiseSuppression?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + width?: boolean; +} + +interface MessageEventInit extends EventInit { + data?: T; + lastEventId?: string; + origin?: string; + ports?: MessagePort[]; + source?: MessageEventSource | null; +} + +interface MouseEventInit extends EventModifierInit { + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + movementX?: number; + movementY?: number; + relatedTarget?: EventTarget | null; + screenX?: number; + screenY?: number; +} + +interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string; +} + +interface MutationObserverInit { + /** Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed and attributes is true or omitted. */ + attributeFilter?: string[]; + /** Set to true if attributes is true or omitted and target's attribute value before the mutation needs to be recorded. */ + attributeOldValue?: boolean; + /** Set to true if mutations to target's attributes are to be observed. Can be omitted if attributeOldValue or attributeFilter is specified. */ + attributes?: boolean; + /** Set to true if mutations to target's data are to be observed. Can be omitted if characterDataOldValue is specified. */ + characterData?: boolean; + /** Set to true if characterData is set to true or omitted and target's data before the mutation needs to be recorded. */ + characterDataOldValue?: boolean; + /** Set to true if mutations to target's children are to be observed. */ + childList?: boolean; + /** Set to true if mutations to not just target, but also target's descendants are to be observed. */ + subtree?: boolean; +} + +interface NavigationPreloadState { + enabled?: boolean; + headerValue?: string; +} + +interface NotificationOptions { + badge?: string; + body?: string; + data?: any; + dir?: NotificationDirection; + icon?: string; + lang?: string; + requireInteraction?: boolean; + silent?: boolean | null; + tag?: string; +} + +interface OfflineAudioCompletionEventInit extends EventInit { + renderedBuffer: AudioBuffer; +} + +interface OfflineAudioContextOptions { + length: number; + numberOfChannels?: number; + sampleRate: number; +} + +interface OptionalEffectTiming { + delay?: number; + direction?: PlaybackDirection; + duration?: number | string; + easing?: string; + endDelay?: number; + fill?: FillMode; + iterationStart?: number; + iterations?: number; + playbackRate?: number; +} + +interface OpusEncoderConfig { + complexity?: number; + format?: OpusBitstreamFormat; + frameDuration?: number; + packetlossperc?: number; + usedtx?: boolean; + useinbandfec?: boolean; +} + +interface OscillatorOptions extends AudioNodeOptions { + detune?: number; + frequency?: number; + periodicWave?: PeriodicWave; + type?: OscillatorType; +} + +interface PageRevealEventInit extends EventInit { + viewTransition?: ViewTransition | null; +} + +interface PageSwapEventInit extends EventInit { + activation?: NavigationActivation | null; + viewTransition?: ViewTransition | null; +} + +interface PageTransitionEventInit extends EventInit { + persisted?: boolean; +} + +interface PannerOptions extends AudioNodeOptions { + coneInnerAngle?: number; + coneOuterAngle?: number; + coneOuterGain?: number; + distanceModel?: DistanceModelType; + maxDistance?: number; + orientationX?: number; + orientationY?: number; + orientationZ?: number; + panningModel?: PanningModelType; + positionX?: number; + positionY?: number; + positionZ?: number; + refDistance?: number; + rolloffFactor?: number; +} + +interface PayerErrors { + email?: string; + name?: string; + phone?: string; +} + +interface PaymentCurrencyAmount { + currency: string; + value: string; +} + +interface PaymentDetailsBase { + displayItems?: PaymentItem[]; + modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; +} + +interface PaymentDetailsInit extends PaymentDetailsBase { + id?: string; + total: PaymentItem; +} + +interface PaymentDetailsModifier { + additionalDisplayItems?: PaymentItem[]; + data?: any; + supportedMethods: string; + total?: PaymentItem; +} + +interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; + paymentMethodErrors?: any; + shippingAddressErrors?: AddressErrors; + total?: PaymentItem; +} + +interface PaymentItem { + amount: PaymentCurrencyAmount; + label: string; + pending?: boolean; +} + +interface PaymentMethodChangeEventInit extends PaymentRequestUpdateEventInit { + methodDetails?: any; + methodName?: string; +} + +interface PaymentMethodData { + data?: any; + supportedMethods: string; +} + +interface PaymentOptions { + requestPayerEmail?: boolean; + requestPayerName?: boolean; + requestPayerPhone?: boolean; + requestShipping?: boolean; + shippingType?: PaymentShippingType; +} + +interface PaymentRequestUpdateEventInit extends EventInit { +} + +interface PaymentShippingOption { + amount: PaymentCurrencyAmount; + id: string; + label: string; + selected?: boolean; +} + +interface PaymentValidationErrors { + error?: string; + payer?: PayerErrors; + shippingAddress?: AddressErrors; +} + +interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; +} + +interface PerformanceMarkOptions { + detail?: any; + startTime?: DOMHighResTimeStamp; +} + +interface PerformanceMeasureOptions { + detail?: any; + duration?: DOMHighResTimeStamp; + end?: string | DOMHighResTimeStamp; + start?: string | DOMHighResTimeStamp; +} + +interface PerformanceObserverInit { + buffered?: boolean; + entryTypes?: string[]; + type?: string; +} + +interface PeriodicWaveConstraints { + disableNormalization?: boolean; +} + +interface PeriodicWaveOptions extends PeriodicWaveConstraints { + imag?: number[] | Float32Array; + real?: number[] | Float32Array; +} + +interface PermissionDescriptor { + name: PermissionName; +} + +interface PictureInPictureEventInit extends EventInit { + pictureInPictureWindow: PictureInPictureWindow; +} + +interface PlaneLayout { + offset: number; + stride: number; +} + +interface PointerEventInit extends MouseEventInit { + altitudeAngle?: number; + azimuthAngle?: number; + coalescedEvents?: PointerEvent[]; + height?: number; + isPrimary?: boolean; + pointerId?: number; + pointerType?: string; + predictedEvents?: PointerEvent[]; + pressure?: number; + tangentialPressure?: number; + tiltX?: number; + tiltY?: number; + twist?: number; + width?: number; +} + +interface PointerLockOptions { + unadjustedMovement?: boolean; +} + +interface PopStateEventInit extends EventInit { + state?: any; +} + +interface PositionOptions { + enableHighAccuracy?: boolean; + maximumAge?: number; + timeout?: number; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface PromiseRejectionEventInit extends EventInit { + promise: Promise; + reason?: any; +} + +interface PropertyDefinition { + inherits: boolean; + initialValue?: string; + name: string; + syntax?: string; +} + +interface PropertyIndexedKeyframes { + composite?: CompositeOperationOrAuto | CompositeOperationOrAuto[]; + easing?: string | string[]; + offset?: number | (number | null)[]; + [property: string]: string | string[] | number | null | (number | null)[] | undefined; +} + +interface PublicKeyCredentialCreationOptions { + attestation?: AttestationConveyancePreference; + authenticatorSelection?: AuthenticatorSelectionCriteria; + challenge: BufferSource; + excludeCredentials?: PublicKeyCredentialDescriptor[]; + extensions?: AuthenticationExtensionsClientInputs; + pubKeyCredParams: PublicKeyCredentialParameters[]; + rp: PublicKeyCredentialRpEntity; + timeout?: number; + user: PublicKeyCredentialUserEntity; +} + +interface PublicKeyCredentialCreationOptionsJSON { + attestation?: string; + authenticatorSelection?: AuthenticatorSelectionCriteria; + challenge: Base64URLString; + excludeCredentials?: PublicKeyCredentialDescriptorJSON[]; + extensions?: AuthenticationExtensionsClientInputsJSON; + hints?: string[]; + pubKeyCredParams: PublicKeyCredentialParameters[]; + rp: PublicKeyCredentialRpEntity; + timeout?: number; + user: PublicKeyCredentialUserEntityJSON; +} + +interface PublicKeyCredentialDescriptor { + id: BufferSource; + transports?: AuthenticatorTransport[]; + type: PublicKeyCredentialType; +} + +interface PublicKeyCredentialDescriptorJSON { + id: Base64URLString; + transports?: string[]; + type: string; +} + +interface PublicKeyCredentialEntity { + name: string; +} + +interface PublicKeyCredentialParameters { + alg: COSEAlgorithmIdentifier; + type: PublicKeyCredentialType; +} + +interface PublicKeyCredentialRequestOptions { + allowCredentials?: PublicKeyCredentialDescriptor[]; + challenge: BufferSource; + extensions?: AuthenticationExtensionsClientInputs; + rpId?: string; + timeout?: number; + userVerification?: UserVerificationRequirement; +} + +interface PublicKeyCredentialRequestOptionsJSON { + allowCredentials?: PublicKeyCredentialDescriptorJSON[]; + challenge: Base64URLString; + extensions?: AuthenticationExtensionsClientInputsJSON; + hints?: string[]; + rpId?: string; + timeout?: number; + userVerification?: string; +} + +interface PublicKeyCredentialRpEntity extends PublicKeyCredentialEntity { + id?: string; +} + +interface PublicKeyCredentialUserEntity extends PublicKeyCredentialEntity { + displayName: string; + id: BufferSource; +} + +interface PublicKeyCredentialUserEntityJSON { + displayName: string; + id: Base64URLString; + name: string; +} + +interface PushSubscriptionJSON { + endpoint?: string; + expirationTime?: EpochTimeStamp | null; + keys?: Record; +} + +interface PushSubscriptionOptionsInit { + applicationServerKey?: BufferSource | string | null; + userVisibleOnly?: boolean; +} + +interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; +} + +interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number; +} + +interface RTCAnswerOptions extends RTCOfferAnswerOptions { +} + +interface RTCCertificateExpiration { + expires?: number; +} + +interface RTCConfiguration { + bundlePolicy?: RTCBundlePolicy; + certificates?: RTCCertificate[]; + iceCandidatePoolSize?: number; + iceServers?: RTCIceServer[]; + iceTransportPolicy?: RTCIceTransportPolicy; + rtcpMuxPolicy?: RTCRtcpMuxPolicy; +} + +interface RTCDTMFToneChangeEventInit extends EventInit { + tone?: string; +} + +interface RTCDataChannelEventInit extends EventInit { + channel: RTCDataChannel; +} + +interface RTCDataChannelInit { + id?: number; + maxPacketLifeTime?: number; + maxRetransmits?: number; + negotiated?: boolean; + ordered?: boolean; + protocol?: string; +} + +interface RTCDtlsFingerprint { + algorithm?: string; + value?: string; +} + +interface RTCEncodedAudioFrameMetadata { + contributingSources?: number[]; + payloadType?: number; + sequenceNumber?: number; + synchronizationSource?: number; +} + +interface RTCEncodedVideoFrameMetadata { + contributingSources?: number[]; + dependencies?: number[]; + frameId?: number; + height?: number; + payloadType?: number; + spatialIndex?: number; + synchronizationSource?: number; + temporalIndex?: number; + timestamp?: number; + width?: number; +} + +interface RTCErrorEventInit extends EventInit { + error: RTCError; +} + +interface RTCErrorInit { + errorDetail: RTCErrorDetailType; + httpRequestStatusCode?: number; + receivedAlert?: number; + sctpCauseCode?: number; + sdpLineNumber?: number; + sentAlert?: number; +} + +interface RTCIceCandidateInit { + candidate?: string; + sdpMLineIndex?: number | null; + sdpMid?: string | null; + usernameFragment?: string | null; +} + +interface RTCIceCandidatePairStats extends RTCStats { + availableIncomingBitrate?: number; + availableOutgoingBitrate?: number; + bytesDiscardedOnSend?: number; + bytesReceived?: number; + bytesSent?: number; + consentRequestsSent?: number; + currentRoundTripTime?: number; + lastPacketReceivedTimestamp?: DOMHighResTimeStamp; + lastPacketSentTimestamp?: DOMHighResTimeStamp; + localCandidateId: string; + nominated?: boolean; + packetsDiscardedOnSend?: number; + packetsReceived?: number; + packetsSent?: number; + remoteCandidateId: string; + requestsReceived?: number; + requestsSent?: number; + responsesReceived?: number; + responsesSent?: number; + state: RTCStatsIceCandidatePairState; + totalRoundTripTime?: number; + transportId: string; +} + +interface RTCIceServer { + credential?: string; + urls: string | string[]; + username?: string; +} + +interface RTCInboundRtpStreamStats extends RTCReceivedRtpStreamStats { + audioLevel?: number; + bytesReceived?: number; + concealedSamples?: number; + concealmentEvents?: number; + decoderImplementation?: string; + estimatedPlayoutTimestamp?: DOMHighResTimeStamp; + fecBytesReceived?: number; + fecPacketsDiscarded?: number; + fecPacketsReceived?: number; + fecSsrc?: number; + firCount?: number; + frameHeight?: number; + frameWidth?: number; + framesAssembledFromMultiplePackets?: number; + framesDecoded?: number; + framesDropped?: number; + framesPerSecond?: number; + framesReceived?: number; + framesRendered?: number; + freezeCount?: number; + headerBytesReceived?: number; + insertedSamplesForDeceleration?: number; + jitterBufferDelay?: number; + jitterBufferEmittedCount?: number; + jitterBufferMinimumDelay?: number; + jitterBufferTargetDelay?: number; + keyFramesDecoded?: number; + lastPacketReceivedTimestamp?: DOMHighResTimeStamp; + mid?: string; + nackCount?: number; + packetsDiscarded?: number; + pauseCount?: number; + playoutId?: string; + pliCount?: number; + qpSum?: number; + remoteId?: string; + removedSamplesForAcceleration?: number; + retransmittedBytesReceived?: number; + retransmittedPacketsReceived?: number; + rtxSsrc?: number; + silentConcealedSamples?: number; + totalAssemblyTime?: number; + totalAudioEnergy?: number; + totalDecodeTime?: number; + totalFreezesDuration?: number; + totalInterFrameDelay?: number; + totalPausesDuration?: number; + totalProcessingDelay?: number; + totalSamplesDuration?: number; + totalSamplesReceived?: number; + totalSquaredInterFrameDelay?: number; + trackIdentifier: string; +} + +interface RTCLocalSessionDescriptionInit { + sdp?: string; + type?: RTCSdpType; +} + +interface RTCOfferAnswerOptions { +} + +interface RTCOfferOptions extends RTCOfferAnswerOptions { + iceRestart?: boolean; + offerToReceiveAudio?: boolean; + offerToReceiveVideo?: boolean; +} + +interface RTCOutboundRtpStreamStats extends RTCSentRtpStreamStats { + active?: boolean; + firCount?: number; + frameHeight?: number; + frameWidth?: number; + framesEncoded?: number; + framesPerSecond?: number; + framesSent?: number; + headerBytesSent?: number; + hugeFramesSent?: number; + keyFramesEncoded?: number; + mediaSourceId?: string; + mid?: string; + nackCount?: number; + pliCount?: number; + qpSum?: number; + qualityLimitationDurations?: Record; + qualityLimitationReason?: RTCQualityLimitationReason; + qualityLimitationResolutionChanges?: number; + remoteId?: string; + retransmittedBytesSent?: number; + retransmittedPacketsSent?: number; + rid?: string; + rtxSsrc?: number; + scalabilityMode?: string; + targetBitrate?: number; + totalEncodeTime?: number; + totalEncodedBytesTarget?: number; + totalPacketSendDelay?: number; +} + +interface RTCPeerConnectionIceErrorEventInit extends EventInit { + address?: string | null; + errorCode: number; + errorText?: string; + port?: number | null; + url?: string; +} + +interface RTCPeerConnectionIceEventInit extends EventInit { + candidate?: RTCIceCandidate | null; + url?: string | null; +} + +interface RTCReceivedRtpStreamStats extends RTCRtpStreamStats { + jitter?: number; + packetsLost?: number; + packetsReceived?: number; +} + +interface RTCRtcpParameters { + cname?: string; + reducedSize?: boolean; +} + +interface RTCRtpCapabilities { + codecs: RTCRtpCodec[]; + headerExtensions: RTCRtpHeaderExtensionCapability[]; +} + +interface RTCRtpCodec { + channels?: number; + clockRate: number; + mimeType: string; + sdpFmtpLine?: string; +} + +interface RTCRtpCodecParameters extends RTCRtpCodec { + payloadType: number; +} + +interface RTCRtpCodingParameters { + rid?: string; +} + +interface RTCRtpContributingSource { + audioLevel?: number; + rtpTimestamp: number; + source: number; + timestamp: DOMHighResTimeStamp; +} + +interface RTCRtpEncodingParameters extends RTCRtpCodingParameters { + active?: boolean; + maxBitrate?: number; + maxFramerate?: number; + networkPriority?: RTCPriorityType; + priority?: RTCPriorityType; + scaleResolutionDownBy?: number; +} + +interface RTCRtpHeaderExtensionCapability { + uri: string; +} + +interface RTCRtpHeaderExtensionParameters { + encrypted?: boolean; + id: number; + uri: string; +} + +interface RTCRtpParameters { + codecs: RTCRtpCodecParameters[]; + headerExtensions: RTCRtpHeaderExtensionParameters[]; + rtcp: RTCRtcpParameters; +} + +interface RTCRtpReceiveParameters extends RTCRtpParameters { +} + +interface RTCRtpSendParameters extends RTCRtpParameters { + degradationPreference?: RTCDegradationPreference; + encodings: RTCRtpEncodingParameters[]; + transactionId: string; +} + +interface RTCRtpStreamStats extends RTCStats { + codecId?: string; + kind: string; + ssrc: number; + transportId?: string; +} + +interface RTCRtpSynchronizationSource extends RTCRtpContributingSource { +} + +interface RTCRtpTransceiverInit { + direction?: RTCRtpTransceiverDirection; + sendEncodings?: RTCRtpEncodingParameters[]; + streams?: MediaStream[]; +} + +interface RTCSentRtpStreamStats extends RTCRtpStreamStats { + bytesSent?: number; + packetsSent?: number; +} + +interface RTCSessionDescriptionInit { + sdp?: string; + type: RTCSdpType; +} + +interface RTCSetParameterOptions { +} + +interface RTCStats { + id: string; + timestamp: DOMHighResTimeStamp; + type: RTCStatsType; +} + +interface RTCTrackEventInit extends EventInit { + receiver: RTCRtpReceiver; + streams?: MediaStream[]; + track: MediaStreamTrack; + transceiver: RTCRtpTransceiver; +} + +interface RTCTransportStats extends RTCStats { + bytesReceived?: number; + bytesSent?: number; + dtlsCipher?: string; + dtlsRole?: RTCDtlsRole; + dtlsState: RTCDtlsTransportState; + iceLocalUsernameFragment?: string; + iceRole?: RTCIceRole; + iceState?: RTCIceTransportState; + localCertificateId?: string; + packetsReceived?: number; + packetsSent?: number; + remoteCertificateId?: string; + selectedCandidatePairChanges?: number; + selectedCandidatePairId?: string; + srtpCipher?: string; + tlsVersion?: string; +} + +interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; +} + +interface ReadableStreamIteratorOptions { + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. The lock will be released if the async iterator's return() method is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's return() method will also cancel the stream. To prevent this, use the stream's values() method, passing true for the preventCancel option. + */ + preventCancel?: boolean; +} + +interface ReadableStreamReadDoneResult { + done: true; + value?: T; +} + +interface ReadableStreamReadValueResult { + done: false; + value: T; +} + +interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream; +} + +interface RegistrationOptions { + scope?: string; + type?: WorkerType; + updateViaCache?: ServiceWorkerUpdateViaCache; +} + +interface ReportingObserverOptions { + buffered?: boolean; + types?: string[]; +} + +interface RequestInit { + /** A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /** A string indicating how the request will interact with the browser's cache to set request's cache. */ + cache?: RequestCache; + /** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */ + credentials?: RequestCredentials; + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /** A boolean to set request's keepalive. */ + keepalive?: boolean; + /** A string to set request's method. */ + method?: string; + /** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */ + mode?: RequestMode; + priority?: RequestPriority; + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: RequestRedirect; + /** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */ + referrer?: string; + /** A referrer policy to set request's referrerPolicy. */ + referrerPolicy?: ReferrerPolicy; + /** An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; + /** Can only be null. Used to disassociate request from any Window. */ + window?: null; +} + +interface ResizeObserverOptions { + box?: ResizeObserverBoxOptions; +} + +interface ResponseInit { + headers?: HeadersInit; + status?: number; + statusText?: string; +} + +interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + +interface SVGBoundingBoxOptions { + clipped?: boolean; + fill?: boolean; + markers?: boolean; + stroke?: boolean; +} + +interface ScrollIntoViewOptions extends ScrollOptions { + block?: ScrollLogicalPosition; + inline?: ScrollLogicalPosition; +} + +interface ScrollOptions { + behavior?: ScrollBehavior; +} + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +interface SecurityPolicyViolationEventInit extends EventInit { + blockedURI?: string; + columnNumber?: number; + disposition?: SecurityPolicyViolationEventDisposition; + documentURI?: string; + effectiveDirective?: string; + lineNumber?: number; + originalPolicy?: string; + referrer?: string; + sample?: string; + sourceFile?: string; + statusCode?: number; + violatedDirective?: string; +} + +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: ShadowRootMode; + serializable?: boolean; + slotAssignment?: SlotAssignmentMode; +} + +interface ShareData { + files?: File[]; + text?: string; + title?: string; + url?: string; +} + +interface SpeechSynthesisErrorEventInit extends SpeechSynthesisEventInit { + error: SpeechSynthesisErrorCode; +} + +interface SpeechSynthesisEventInit extends EventInit { + charIndex?: number; + charLength?: number; + elapsedTime?: number; + name?: string; + utterance: SpeechSynthesisUtterance; +} + +interface StaticRangeInit { + endContainer: Node; + endOffset: number; + startContainer: Node; + startOffset: number; +} + +interface StereoPannerOptions extends AudioNodeOptions { + pan?: number; +} + +interface StorageEstimate { + quota?: number; + usage?: number; +} + +interface StorageEventInit extends EventInit { + key?: string | null; + newValue?: string | null; + oldValue?: string | null; + storageArea?: Storage | null; + url?: string; +} + +interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean; + signal?: AbortSignal; +} + +interface StructuredSerializeOptions { + transfer?: Transferable[]; +} + +interface SubmitEventInit extends EventInit { + submitter?: HTMLElement | null; +} + +interface TextDecodeOptions { + stream?: boolean; +} + +interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + +interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} + +interface ToggleEventInit extends EventInit { + newState?: string; + oldState?: string; +} + +interface TouchEventInit extends EventModifierInit { + changedTouches?: Touch[]; + targetTouches?: Touch[]; + touches?: Touch[]; +} + +interface TouchInit { + altitudeAngle?: number; + azimuthAngle?: number; + clientX?: number; + clientY?: number; + force?: number; + identifier: number; + pageX?: number; + pageY?: number; + radiusX?: number; + radiusY?: number; + rotationAngle?: number; + screenX?: number; + screenY?: number; + target: EventTarget; + touchType?: TouchType; +} + +interface TrackEventInit extends EventInit { + track?: TextTrack | null; +} + +interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; +} + +interface TransitionEventInit extends EventInit { + elapsedTime?: number; + propertyName?: string; + pseudoElement?: string; +} + +interface UIEventInit extends EventInit { + detail?: number; + view?: Window | null; + /** @deprecated */ + which?: number; +} + +interface ULongRange { + max?: number; + min?: number; +} + +interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableByteStreamController) => void | PromiseLike; + start?: (controller: ReadableByteStreamController) => any; + type: "bytes"; +} + +interface UnderlyingDefaultSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableStreamDefaultController) => void | PromiseLike; + start?: (controller: ReadableStreamDefaultController) => any; + type?: undefined; +} + +interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; +} + +interface UnderlyingSource { + autoAllocateChunkSize?: number; + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: ReadableStreamType; +} + +interface ValidityStateFlags { + badInput?: boolean; + customError?: boolean; + patternMismatch?: boolean; + rangeOverflow?: boolean; + rangeUnderflow?: boolean; + stepMismatch?: boolean; + tooLong?: boolean; + tooShort?: boolean; + typeMismatch?: boolean; + valueMissing?: boolean; +} + +interface VideoColorSpaceInit { + fullRange?: boolean | null; + matrix?: VideoMatrixCoefficients | null; + primaries?: VideoColorPrimaries | null; + transfer?: VideoTransferCharacteristics | null; +} + +interface VideoConfiguration { + bitrate: number; + colorGamut?: ColorGamut; + contentType: string; + framerate: number; + hasAlphaChannel?: boolean; + hdrMetadataType?: HdrMetadataType; + height: number; + scalabilityMode?: string; + transferFunction?: TransferFunction; + width: number; +} + +interface VideoDecoderConfig { + codec: string; + codedHeight?: number; + codedWidth?: number; + colorSpace?: VideoColorSpaceInit; + description?: AllowSharedBufferSource; + displayAspectHeight?: number; + displayAspectWidth?: number; + hardwareAcceleration?: HardwareAcceleration; + optimizeForLatency?: boolean; +} + +interface VideoDecoderInit { + error: WebCodecsErrorCallback; + output: VideoFrameOutputCallback; +} + +interface VideoDecoderSupport { + config?: VideoDecoderConfig; + supported?: boolean; +} + +interface VideoEncoderConfig { + alpha?: AlphaOption; + avc?: AvcEncoderConfig; + bitrate?: number; + bitrateMode?: VideoEncoderBitrateMode; + codec: string; + contentHint?: string; + displayHeight?: number; + displayWidth?: number; + framerate?: number; + hardwareAcceleration?: HardwareAcceleration; + height: number; + latencyMode?: LatencyMode; + scalabilityMode?: string; + width: number; +} + +interface VideoEncoderEncodeOptions { + avc?: VideoEncoderEncodeOptionsForAvc; + keyFrame?: boolean; +} + +interface VideoEncoderEncodeOptionsForAvc { + quantizer?: number | null; +} + +interface VideoEncoderInit { + error: WebCodecsErrorCallback; + output: EncodedVideoChunkOutputCallback; +} + +interface VideoEncoderSupport { + config?: VideoEncoderConfig; + supported?: boolean; +} + +interface VideoFrameBufferInit { + codedHeight: number; + codedWidth: number; + colorSpace?: VideoColorSpaceInit; + displayHeight?: number; + displayWidth?: number; + duration?: number; + format: VideoPixelFormat; + layout?: PlaneLayout[]; + timestamp: number; + visibleRect?: DOMRectInit; +} + +interface VideoFrameCallbackMetadata { + captureTime?: DOMHighResTimeStamp; + expectedDisplayTime: DOMHighResTimeStamp; + height: number; + mediaTime: number; + presentationTime: DOMHighResTimeStamp; + presentedFrames: number; + processingDuration?: number; + receiveTime?: DOMHighResTimeStamp; + rtpTimestamp?: number; + width: number; +} + +interface VideoFrameCopyToOptions { + colorSpace?: PredefinedColorSpace; + format?: VideoPixelFormat; + layout?: PlaneLayout[]; + rect?: DOMRectInit; +} + +interface VideoFrameInit { + alpha?: AlphaOption; + displayHeight?: number; + displayWidth?: number; + duration?: number; + timestamp?: number; + visibleRect?: DOMRectInit; +} + +interface WaveShaperOptions extends AudioNodeOptions { + curve?: number[] | Float32Array; + oversample?: OverSampleType; +} + +interface WebGLContextAttributes { + alpha?: boolean; + antialias?: boolean; + depth?: boolean; + desynchronized?: boolean; + failIfMajorPerformanceCaveat?: boolean; + powerPreference?: WebGLPowerPreference; + premultipliedAlpha?: boolean; + preserveDrawingBuffer?: boolean; + stencil?: boolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WebTransportCloseInfo { + closeCode?: number; + reason?: string; +} + +interface WebTransportErrorOptions { + source?: WebTransportErrorSource; + streamErrorCode?: number | null; +} + +interface WebTransportHash { + algorithm?: string; + value?: BufferSource; +} + +interface WebTransportOptions { + allowPooling?: boolean; + congestionControl?: WebTransportCongestionControl; + requireUnreliable?: boolean; + serverCertificateHashes?: WebTransportHash[]; +} + +interface WebTransportSendStreamOptions { + sendOrder?: number; +} + +interface WheelEventInit extends MouseEventInit { + deltaMode?: number; + deltaX?: number; + deltaY?: number; + deltaZ?: number; +} + +interface WindowPostMessageOptions extends StructuredSerializeOptions { + targetOrigin?: string; +} + +interface WorkerOptions { + credentials?: RequestCredentials; + name?: string; + type?: WorkerType; +} + +interface WorkletOptions { + credentials?: RequestCredentials; +} + +interface WriteParams { + data?: BufferSource | Blob | string | null; + position?: number | null; + size?: number | null; + type: WriteCommandType; +} + +type NodeFilter = ((node: Node) => number) | { acceptNode(node: Node): number; }; + +declare var NodeFilter: { + readonly FILTER_ACCEPT: 1; + readonly FILTER_REJECT: 2; + readonly FILTER_SKIP: 3; + readonly SHOW_ALL: 0xFFFFFFFF; + readonly SHOW_ELEMENT: 0x1; + readonly SHOW_ATTRIBUTE: 0x2; + readonly SHOW_TEXT: 0x4; + readonly SHOW_CDATA_SECTION: 0x8; + readonly SHOW_ENTITY_REFERENCE: 0x10; + readonly SHOW_ENTITY: 0x20; + readonly SHOW_PROCESSING_INSTRUCTION: 0x40; + readonly SHOW_COMMENT: 0x80; + readonly SHOW_DOCUMENT: 0x100; + readonly SHOW_DOCUMENT_TYPE: 0x200; + readonly SHOW_DOCUMENT_FRAGMENT: 0x400; + readonly SHOW_NOTATION: 0x800; +}; + +type XPathNSResolver = ((prefix: string | null) => string | null) | { lookupNamespaceURI(prefix: string | null): string | null; }; + +/** + * The ANGLE_instanced_arrays extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ANGLE_instanced_arrays) + */ +interface ANGLE_instanced_arrays { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ANGLE_instanced_arrays/drawArraysInstancedANGLE) */ + drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ANGLE_instanced_arrays/drawElementsInstancedANGLE) */ + drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ANGLE_instanced_arrays/vertexAttribDivisorANGLE) */ + vertexAttribDivisorANGLE(index: GLuint, divisor: GLuint): void; + readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: 0x88FE; +} + +interface ARIAMixin { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaAtomic) */ + ariaAtomic: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaAutoComplete) */ + ariaAutoComplete: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaBrailleLabel) */ + ariaBrailleLabel: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaBrailleRoleDescription) */ + ariaBrailleRoleDescription: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaBusy) */ + ariaBusy: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaChecked) */ + ariaChecked: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColCount) */ + ariaColCount: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColIndex) */ + ariaColIndex: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColIndexText) */ + ariaColIndexText: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColSpan) */ + ariaColSpan: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaCurrent) */ + ariaCurrent: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaDescription) */ + ariaDescription: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaDisabled) */ + ariaDisabled: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaExpanded) */ + ariaExpanded: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaHasPopup) */ + ariaHasPopup: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaHidden) */ + ariaHidden: string | null; + ariaInvalid: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaKeyShortcuts) */ + ariaKeyShortcuts: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaLabel) */ + ariaLabel: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaLevel) */ + ariaLevel: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaLive) */ + ariaLive: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaModal) */ + ariaModal: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaMultiLine) */ + ariaMultiLine: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaMultiSelectable) */ + ariaMultiSelectable: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaOrientation) */ + ariaOrientation: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaPlaceholder) */ + ariaPlaceholder: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaPosInSet) */ + ariaPosInSet: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaPressed) */ + ariaPressed: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaReadOnly) */ + ariaReadOnly: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRelevant) */ + ariaRelevant: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRequired) */ + ariaRequired: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRoleDescription) */ + ariaRoleDescription: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowCount) */ + ariaRowCount: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowIndex) */ + ariaRowIndex: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowIndexText) */ + ariaRowIndexText: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowSpan) */ + ariaRowSpan: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaSelected) */ + ariaSelected: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaSetSize) */ + ariaSetSize: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaSort) */ + ariaSort: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaValueMax) */ + ariaValueMax: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaValueMin) */ + ariaValueMin: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaValueNow) */ + ariaValueNow: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaValueText) */ + ariaValueText: string | null; + role: string | null; +} + +/** + * A controller object that allows you to abort one or more DOM requests as and when desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) + */ +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": Event; +} + +/** + * A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) + */ +interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + readonly aborted: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + onabort: ((this: AbortSignal, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + readonly reason: any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + abort(reason?: any): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) */ + any(signals: AbortSignal[]): AbortSignal; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + timeout(milliseconds: number): AbortSignal; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange) */ +interface AbstractRange { + /** + * Returns true if range is collapsed, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/collapsed) + */ + readonly collapsed: boolean; + /** + * Returns range's end node. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/endContainer) + */ + readonly endContainer: Node; + /** + * Returns range's end offset. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/endOffset) + */ + readonly endOffset: number; + /** + * Returns range's start node. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/startContainer) + */ + readonly startContainer: Node; + /** + * Returns range's start offset. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/startOffset) + */ + readonly startOffset: number; +} + +declare var AbstractRange: { + prototype: AbstractRange; + new(): AbstractRange; +}; + +interface AbstractWorkerEventMap { + "error": ErrorEvent; +} + +interface AbstractWorker { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorker/error_event) */ + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +/** + * A node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode) + */ +interface AnalyserNode extends AudioNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/fftSize) */ + fftSize: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/frequencyBinCount) */ + readonly frequencyBinCount: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/maxDecibels) */ + maxDecibels: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/minDecibels) */ + minDecibels: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/smoothingTimeConstant) */ + smoothingTimeConstant: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/getByteFrequencyData) */ + getByteFrequencyData(array: Uint8Array): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/getByteTimeDomainData) */ + getByteTimeDomainData(array: Uint8Array): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/getFloatFrequencyData) */ + getFloatFrequencyData(array: Float32Array): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/getFloatTimeDomainData) */ + getFloatTimeDomainData(array: Float32Array): void; +} + +declare var AnalyserNode: { + prototype: AnalyserNode; + new(context: BaseAudioContext, options?: AnalyserOptions): AnalyserNode; +}; + +interface Animatable { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animate) */ + animate(keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeAnimationOptions): Animation; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAnimations) */ + getAnimations(options?: GetAnimationsOptions): Animation[]; +} + +interface AnimationEventMap { + "cancel": AnimationPlaybackEvent; + "finish": AnimationPlaybackEvent; + "remove": AnimationPlaybackEvent; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation) */ +interface Animation extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/currentTime) */ + currentTime: CSSNumberish | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/effect) */ + effect: AnimationEffect | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/finished) */ + readonly finished: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/id) */ + id: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/cancel_event) */ + oncancel: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/finish_event) */ + onfinish: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/remove_event) */ + onremove: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/pending) */ + readonly pending: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/playState) */ + readonly playState: AnimationPlayState; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/playbackRate) */ + playbackRate: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/ready) */ + readonly ready: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/replaceState) */ + readonly replaceState: AnimationReplaceState; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/startTime) */ + startTime: CSSNumberish | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/timeline) */ + timeline: AnimationTimeline | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/cancel) */ + cancel(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/commitStyles) */ + commitStyles(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/finish) */ + finish(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/pause) */ + pause(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/persist) */ + persist(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/play) */ + play(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/reverse) */ + reverse(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/updatePlaybackRate) */ + updatePlaybackRate(playbackRate: number): void; + addEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffect | null, timeline?: AnimationTimeline | null): Animation; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEffect) */ +interface AnimationEffect { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEffect/getComputedTiming) */ + getComputedTiming(): ComputedEffectTiming; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEffect/getTiming) */ + getTiming(): EffectTiming; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEffect/updateTiming) */ + updateTiming(timing?: OptionalEffectTiming): void; +} + +declare var AnimationEffect: { + prototype: AnimationEffect; + new(): AnimationEffect; +}; + +/** + * Events providing information related to animations. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEvent) + */ +interface AnimationEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEvent/animationName) */ + readonly animationName: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEvent/elapsedTime) */ + readonly elapsedTime: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEvent/pseudoElement) */ + readonly pseudoElement: string; +} + +declare var AnimationEvent: { + prototype: AnimationEvent; + new(type: string, animationEventInitDict?: AnimationEventInit): AnimationEvent; +}; + +interface AnimationFrameProvider { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/cancelAnimationFrame) */ + cancelAnimationFrame(handle: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/requestAnimationFrame) */ + requestAnimationFrame(callback: FrameRequestCallback): number; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationPlaybackEvent) */ +interface AnimationPlaybackEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationPlaybackEvent/currentTime) */ + readonly currentTime: CSSNumberish | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationPlaybackEvent/timelineTime) */ + readonly timelineTime: CSSNumberish | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationTimeline) */ +interface AnimationTimeline { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationTimeline/currentTime) */ + readonly currentTime: CSSNumberish | null; +} + +declare var AnimationTimeline: { + prototype: AnimationTimeline; + new(): AnimationTimeline; +}; + +/** + * A DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr) + */ +interface Attr extends Node { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/localName) */ + readonly localName: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/namespaceURI) */ + readonly namespaceURI: string | null; + readonly ownerDocument: Document; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/ownerElement) */ + readonly ownerElement: Element | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/prefix) */ + readonly prefix: string | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/specified) + */ + readonly specified: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/value) */ + value: string; +} + +declare var Attr: { + prototype: Attr; + new(): Attr; +}; + +/** + * A short audio asset residing in memory, created from an audio file using the AudioContext.decodeAudioData() method, or from raw data using AudioContext.createBuffer(). Once put into an AudioBuffer, the audio can then be played by being passed into an AudioBufferSourceNode. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer) + */ +interface AudioBuffer { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/duration) */ + readonly duration: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/length) */ + readonly length: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/numberOfChannels) */ + readonly numberOfChannels: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/sampleRate) */ + readonly sampleRate: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/copyFromChannel) */ + copyFromChannel(destination: Float32Array, channelNumber: number, bufferOffset?: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/copyToChannel) */ + copyToChannel(source: Float32Array, channelNumber: number, bufferOffset?: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/getChannelData) */ + getChannelData(channel: number): Float32Array; +} + +declare var AudioBuffer: { + prototype: AudioBuffer; + new(options: AudioBufferOptions): AudioBuffer; +}; + +/** + * An AudioScheduledSourceNode which represents an audio source consisting of in-memory audio data, stored in an AudioBuffer. It's especially useful for playing back audio which has particularly stringent timing accuracy requirements, such as for sounds that must match a specific rhythm and can be kept in memory rather than being played from disk or the network. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode) + */ +interface AudioBufferSourceNode extends AudioScheduledSourceNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/buffer) */ + buffer: AudioBuffer | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/detune) */ + readonly detune: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/loop) */ + loop: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/loopEnd) */ + loopEnd: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/loopStart) */ + loopStart: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/playbackRate) */ + readonly playbackRate: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/start) */ + start(when?: number, offset?: number, duration?: number): void; + addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioBufferSourceNode: { + prototype: AudioBufferSourceNode; + new(context: BaseAudioContext, options?: AudioBufferSourceOptions): AudioBufferSourceNode; +}; + +/** + * An audio-processing graph built from audio modules linked together, each represented by an AudioNode. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext) + */ +interface AudioContext extends BaseAudioContext { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/baseLatency) */ + readonly baseLatency: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/outputLatency) */ + readonly outputLatency: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/close) */ + close(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/createMediaElementSource) */ + createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/createMediaStreamDestination) */ + createMediaStreamDestination(): MediaStreamAudioDestinationNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/createMediaStreamSource) */ + createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/getOutputTimestamp) */ + getOutputTimestamp(): AudioTimestamp; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/resume) */ + resume(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/suspend) */ + suspend(): Promise; + addEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioContext: { + prototype: AudioContext; + new(contextOptions?: AudioContextOptions): AudioContext; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData) */ +interface AudioData { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/duration) */ + readonly duration: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/format) */ + readonly format: AudioSampleFormat | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/numberOfChannels) */ + readonly numberOfChannels: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/numberOfFrames) */ + readonly numberOfFrames: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/sampleRate) */ + readonly sampleRate: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/timestamp) */ + readonly timestamp: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/allocationSize) */ + allocationSize(options: AudioDataCopyToOptions): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/clone) */ + clone(): AudioData; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/copyTo) */ + copyTo(destination: AllowSharedBufferSource, options: AudioDataCopyToOptions): void; +} + +declare var AudioData: { + prototype: AudioData; + new(init: AudioDataInit): AudioData; +}; + +interface AudioDecoderEventMap { + "dequeue": Event; +} + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder) + */ +interface AudioDecoder extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/decodeQueueSize) */ + readonly decodeQueueSize: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/dequeue_event) */ + ondequeue: ((this: AudioDecoder, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/state) */ + readonly state: CodecState; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/configure) */ + configure(config: AudioDecoderConfig): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/decode) */ + decode(chunk: EncodedAudioChunk): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/flush) */ + flush(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/reset) */ + reset(): void; + addEventListener(type: K, listener: (this: AudioDecoder, ev: AudioDecoderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioDecoder, ev: AudioDecoderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioDecoder: { + prototype: AudioDecoder; + new(init: AudioDecoderInit): AudioDecoder; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/isConfigSupported_static) */ + isConfigSupported(config: AudioDecoderConfig): Promise; +}; + +/** + * AudioDestinationNode has no output (as it is the output, no more AudioNode can be linked after it in the audio graph) and one input. The number of channels in the input must be between 0 and the maxChannelCount value or an exception is raised. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDestinationNode) + */ +interface AudioDestinationNode extends AudioNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDestinationNode/maxChannelCount) */ + readonly maxChannelCount: number; +} + +declare var AudioDestinationNode: { + prototype: AudioDestinationNode; + new(): AudioDestinationNode; +}; + +interface AudioEncoderEventMap { + "dequeue": Event; +} + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder) + */ +interface AudioEncoder extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/encodeQueueSize) */ + readonly encodeQueueSize: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/dequeue_event) */ + ondequeue: ((this: AudioEncoder, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/state) */ + readonly state: CodecState; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/configure) */ + configure(config: AudioEncoderConfig): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/encode) */ + encode(data: AudioData): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/flush) */ + flush(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/reset) */ + reset(): void; + addEventListener(type: K, listener: (this: AudioEncoder, ev: AudioEncoderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioEncoder, ev: AudioEncoderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioEncoder: { + prototype: AudioEncoder; + new(init: AudioEncoderInit): AudioEncoder; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/isConfigSupported_static) */ + isConfigSupported(config: AudioEncoderConfig): Promise; +}; + +/** + * The position and orientation of the unique person listening to the audio scene, and is used in audio spatialization. All PannerNodes spatialize in relation to the AudioListener stored in the BaseAudioContext.listener attribute. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener) + */ +interface AudioListener { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/forwardX) */ + readonly forwardX: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/forwardY) */ + readonly forwardY: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/forwardZ) */ + readonly forwardZ: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/positionX) */ + readonly positionX: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/positionY) */ + readonly positionY: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/positionZ) */ + readonly positionZ: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/upX) */ + readonly upX: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/upY) */ + readonly upY: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/upZ) */ + readonly upZ: AudioParam; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/setOrientation) + */ + setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioListener/setPosition) + */ + setPosition(x: number, y: number, z: number): void; +} + +declare var AudioListener: { + prototype: AudioListener; + new(): AudioListener; +}; + +/** + * A generic interface for representing an audio processing module. Examples include: + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioNode) + */ +interface AudioNode extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioNode/channelCount) */ + channelCount: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioNode/channelCountMode) */ + channelCountMode: ChannelCountMode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioNode/channelInterpretation) */ + channelInterpretation: ChannelInterpretation; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioNode/context) */ + readonly context: BaseAudioContext; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioNode/numberOfInputs) */ + readonly numberOfInputs: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioNode/numberOfOutputs) */ + readonly numberOfOutputs: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioNode/connect) */ + connect(destinationNode: AudioNode, output?: number, input?: number): AudioNode; + connect(destinationParam: AudioParam, output?: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioNode/disconnect) */ + disconnect(): void; + disconnect(output: number): void; + disconnect(destinationNode: AudioNode): void; + disconnect(destinationNode: AudioNode, output: number): void; + disconnect(destinationNode: AudioNode, output: number, input: number): void; + disconnect(destinationParam: AudioParam): void; + disconnect(destinationParam: AudioParam, output: number): void; +} + +declare var AudioNode: { + prototype: AudioNode; + new(): AudioNode; +}; + +/** + * The Web Audio API's AudioParam interface represents an audio-related parameter, usually a parameter of an AudioNode (such as GainNode.gain). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam) + */ +interface AudioParam { + automationRate: AutomationRate; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/defaultValue) */ + readonly defaultValue: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/maxValue) */ + readonly maxValue: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/minValue) */ + readonly minValue: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/value) */ + value: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/cancelAndHoldAtTime) */ + cancelAndHoldAtTime(cancelTime: number): AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/cancelScheduledValues) */ + cancelScheduledValues(cancelTime: number): AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/exponentialRampToValueAtTime) */ + exponentialRampToValueAtTime(value: number, endTime: number): AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/linearRampToValueAtTime) */ + linearRampToValueAtTime(value: number, endTime: number): AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/setTargetAtTime) */ + setTargetAtTime(target: number, startTime: number, timeConstant: number): AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/setValueAtTime) */ + setValueAtTime(value: number, startTime: number): AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/setValueCurveAtTime) */ + setValueCurveAtTime(values: number[] | Float32Array, startTime: number, duration: number): AudioParam; +} + +declare var AudioParam: { + prototype: AudioParam; + new(): AudioParam; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParamMap) */ +interface AudioParamMap { + forEach(callbackfn: (value: AudioParam, key: string, parent: AudioParamMap) => void, thisArg?: any): void; +} + +declare var AudioParamMap: { + prototype: AudioParamMap; + new(): AudioParamMap; +}; + +/** + * The Web Audio API events that occur when a ScriptProcessorNode input buffer is ready to be processed. + * @deprecated As of the August 29 2014 Web Audio API spec publication, this feature has been marked as deprecated, and is soon to be replaced by AudioWorklet. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioProcessingEvent) + */ +interface AudioProcessingEvent extends Event { + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioProcessingEvent/inputBuffer) + */ + readonly inputBuffer: AudioBuffer; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioProcessingEvent/outputBuffer) + */ + readonly outputBuffer: AudioBuffer; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioProcessingEvent/playbackTime) + */ + readonly playbackTime: number; +} + +/** @deprecated */ +declare var AudioProcessingEvent: { + prototype: AudioProcessingEvent; + new(type: string, eventInitDict: AudioProcessingEventInit): AudioProcessingEvent; +}; + +interface AudioScheduledSourceNodeEventMap { + "ended": Event; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioScheduledSourceNode) */ +interface AudioScheduledSourceNode extends AudioNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioScheduledSourceNode/ended_event) */ + onended: ((this: AudioScheduledSourceNode, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioScheduledSourceNode/start) */ + start(when?: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioScheduledSourceNode/stop) */ + stop(when?: number): void; + addEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioScheduledSourceNode: { + prototype: AudioScheduledSourceNode; + new(): AudioScheduledSourceNode; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioWorklet) + */ +interface AudioWorklet extends Worklet { +} + +declare var AudioWorklet: { + prototype: AudioWorklet; + new(): AudioWorklet; +}; + +interface AudioWorkletNodeEventMap { + "processorerror": ErrorEvent; +} + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioWorkletNode) + */ +interface AudioWorkletNode extends AudioNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioWorkletNode/processorerror_event) */ + onprocessorerror: ((this: AudioWorkletNode, ev: ErrorEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioWorkletNode/parameters) */ + readonly parameters: AudioParamMap; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioWorkletNode/port) */ + readonly port: MessagePort; + addEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioWorkletNode: { + prototype: AudioWorkletNode; + new(context: BaseAudioContext, name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAssertionResponse) + */ +interface AuthenticatorAssertionResponse extends AuthenticatorResponse { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAssertionResponse/authenticatorData) */ + readonly authenticatorData: ArrayBuffer; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAssertionResponse/signature) */ + readonly signature: ArrayBuffer; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAssertionResponse/userHandle) */ + readonly userHandle: ArrayBuffer | null; +} + +declare var AuthenticatorAssertionResponse: { + prototype: AuthenticatorAssertionResponse; + new(): AuthenticatorAssertionResponse; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAttestationResponse) + */ +interface AuthenticatorAttestationResponse extends AuthenticatorResponse { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAttestationResponse/attestationObject) */ + readonly attestationObject: ArrayBuffer; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAttestationResponse/getAuthenticatorData) */ + getAuthenticatorData(): ArrayBuffer; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAttestationResponse/getPublicKey) */ + getPublicKey(): ArrayBuffer | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAttestationResponse/getPublicKeyAlgorithm) */ + getPublicKeyAlgorithm(): COSEAlgorithmIdentifier; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorAttestationResponse/getTransports) */ + getTransports(): string[]; +} + +declare var AuthenticatorAttestationResponse: { + prototype: AuthenticatorAttestationResponse; + new(): AuthenticatorAttestationResponse; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorResponse) + */ +interface AuthenticatorResponse { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AuthenticatorResponse/clientDataJSON) */ + readonly clientDataJSON: ArrayBuffer; +} + +declare var AuthenticatorResponse: { + prototype: AuthenticatorResponse; + new(): AuthenticatorResponse; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BarProp) */ +interface BarProp { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BarProp/visible) */ + readonly visible: boolean; +} + +declare var BarProp: { + prototype: BarProp; + new(): BarProp; +}; + +interface BaseAudioContextEventMap { + "statechange": Event; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext) */ +interface BaseAudioContext extends EventTarget { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/audioWorklet) + */ + readonly audioWorklet: AudioWorklet; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/currentTime) */ + readonly currentTime: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/destination) */ + readonly destination: AudioDestinationNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/listener) */ + readonly listener: AudioListener; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/statechange_event) */ + onstatechange: ((this: BaseAudioContext, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/sampleRate) */ + readonly sampleRate: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/state) */ + readonly state: AudioContextState; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createAnalyser) */ + createAnalyser(): AnalyserNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createBiquadFilter) */ + createBiquadFilter(): BiquadFilterNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createBuffer) */ + createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createBufferSource) */ + createBufferSource(): AudioBufferSourceNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createChannelMerger) */ + createChannelMerger(numberOfInputs?: number): ChannelMergerNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createChannelSplitter) */ + createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createConstantSource) */ + createConstantSource(): ConstantSourceNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createConvolver) */ + createConvolver(): ConvolverNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createDelay) */ + createDelay(maxDelayTime?: number): DelayNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createDynamicsCompressor) */ + createDynamicsCompressor(): DynamicsCompressorNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createGain) */ + createGain(): GainNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createIIRFilter) */ + createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createOscillator) */ + createOscillator(): OscillatorNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createPanner) */ + createPanner(): PannerNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createPeriodicWave) */ + createPeriodicWave(real: number[] | Float32Array, imag: number[] | Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createScriptProcessor) + */ + createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createStereoPanner) */ + createStereoPanner(): StereoPannerNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createWaveShaper) */ + createWaveShaper(): WaveShaperNode; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/decodeAudioData) */ + decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback | null, errorCallback?: DecodeErrorCallback | null): Promise; + addEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var BaseAudioContext: { + prototype: BaseAudioContext; + new(): BaseAudioContext; +}; + +/** + * The beforeunload event is fired when the window, the document and its resources are about to be unloaded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BeforeUnloadEvent) + */ +interface BeforeUnloadEvent extends Event { + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BeforeUnloadEvent/returnValue) + */ + returnValue: any; +} + +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new(): BeforeUnloadEvent; +}; + +/** + * A simple low-order filter, and is created using the AudioContext.createBiquadFilter() method. It is an AudioNode that can represent different kinds of filters, tone control devices, and graphic equalizers. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BiquadFilterNode) + */ +interface BiquadFilterNode extends AudioNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BiquadFilterNode/Q) */ + readonly Q: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BiquadFilterNode/detune) */ + readonly detune: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BiquadFilterNode/frequency) */ + readonly frequency: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BiquadFilterNode/gain) */ + readonly gain: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BiquadFilterNode/type) */ + type: BiquadFilterType; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BiquadFilterNode/getFrequencyResponse) */ + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; +} + +declare var BiquadFilterNode: { + prototype: BiquadFilterNode; + new(context: BaseAudioContext, options?: BiquadFilterOptions): BiquadFilterNode; +}; + +/** + * A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) + */ +interface Blob { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + readonly size: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) */ + bytes(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, contentType?: string): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; +} + +declare var Blob: { + prototype: Blob; + new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BlobEvent) */ +interface BlobEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BlobEvent/data) */ + readonly data: Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BlobEvent/timecode) */ + readonly timecode: DOMHighResTimeStamp; +} + +declare var BlobEvent: { + prototype: BlobEvent; + new(type: string, eventInitDict: BlobEventInit): BlobEvent; +}; + +interface Body { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + readonly body: ReadableStream | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + readonly bodyUsed: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise; +} + +interface BroadcastChannelEventMap { + "message": MessageEvent; + "messageerror": MessageEvent; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel) */ +interface BroadcastChannel extends EventTarget { + /** + * Returns the channel name (as passed to the constructor). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/name) + */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/message_event) */ + onmessage: ((this: BroadcastChannel, ev: MessageEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/messageerror_event) */ + onmessageerror: ((this: BroadcastChannel, ev: MessageEvent) => any) | null; + /** + * Closes the BroadcastChannel object, opening it up to garbage collection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/close) + */ + close(): void; + /** + * Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/postMessage) + */ + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +/** + * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) + */ +interface ByteLengthQueuingStrategy extends QueuingStrategy { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + readonly highWaterMark: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + readonly size: QueuingStrategySize; +} + +declare var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; +}; + +/** + * A CDATA section that can be used within XML to include extended portions of unescaped text. The symbols < and & don’t need escaping as they normally do when inside a CDATA section. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CDATASection) + */ +interface CDATASection extends Text { +} + +declare var CDATASection: { + prototype: CDATASection; + new(): CDATASection; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSAnimation) */ +interface CSSAnimation extends Animation { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSAnimation/animationName) */ + readonly animationName: string; + addEventListener(type: K, listener: (this: CSSAnimation, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: CSSAnimation, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var CSSAnimation: { + prototype: CSSAnimation; + new(): CSSAnimation; +}; + +/** + * A single condition CSS at-rule, which consists of a condition and a statement block. It is a child of CSSGroupingRule. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSConditionRule) + */ +interface CSSConditionRule extends CSSGroupingRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSConditionRule/conditionText) */ + readonly conditionText: string; +} + +declare var CSSConditionRule: { + prototype: CSSConditionRule; + new(): CSSConditionRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSContainerRule) */ +interface CSSContainerRule extends CSSConditionRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSContainerRule/containerName) */ + readonly containerName: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSContainerRule/containerQuery) */ + readonly containerQuery: string; +} + +declare var CSSContainerRule: { + prototype: CSSContainerRule; + new(): CSSContainerRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule) */ +interface CSSCounterStyleRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/additiveSymbols) */ + additiveSymbols: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/fallback) */ + fallback: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/name) */ + name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/negative) */ + negative: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/pad) */ + pad: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/prefix) */ + prefix: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/range) */ + range: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/speakAs) */ + speakAs: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/suffix) */ + suffix: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/symbols) */ + symbols: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSCounterStyleRule/system) */ + system: string; +} + +declare var CSSCounterStyleRule: { + prototype: CSSCounterStyleRule; + new(): CSSCounterStyleRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSFontFaceRule) */ +interface CSSFontFaceRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSFontFaceRule/style) */ + get style(): CSSStyleDeclaration; + set style(cssText: string); +} + +declare var CSSFontFaceRule: { + prototype: CSSFontFaceRule; + new(): CSSFontFaceRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSFontFeatureValuesRule) */ +interface CSSFontFeatureValuesRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSFontFeatureValuesRule/fontFamily) */ + fontFamily: string; +} + +declare var CSSFontFeatureValuesRule: { + prototype: CSSFontFeatureValuesRule; + new(): CSSFontFeatureValuesRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSFontPaletteValuesRule) */ +interface CSSFontPaletteValuesRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSFontPaletteValuesRule/basePalette) */ + readonly basePalette: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSFontPaletteValuesRule/fontFamily) */ + readonly fontFamily: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSFontPaletteValuesRule/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSFontPaletteValuesRule/overrideColors) */ + readonly overrideColors: string; +} + +declare var CSSFontPaletteValuesRule: { + prototype: CSSFontPaletteValuesRule; + new(): CSSFontPaletteValuesRule; +}; + +/** + * Any CSS at-rule that contains other rules nested within it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSGroupingRule) + */ +interface CSSGroupingRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSGroupingRule/cssRules) */ + readonly cssRules: CSSRuleList; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSGroupingRule/deleteRule) */ + deleteRule(index: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSGroupingRule/insertRule) */ + insertRule(rule: string, index?: number): number; +} + +declare var CSSGroupingRule: { + prototype: CSSGroupingRule; + new(): CSSGroupingRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImageValue) */ +interface CSSImageValue extends CSSStyleValue { +} + +declare var CSSImageValue: { + prototype: CSSImageValue; + new(): CSSImageValue; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule) */ +interface CSSImportRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule/href) */ + readonly href: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule/layerName) */ + readonly layerName: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule/media) */ + get media(): MediaList; + set media(mediaText: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule/styleSheet) */ + readonly styleSheet: CSSStyleSheet | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule/supportsText) */ + readonly supportsText: string | null; +} + +declare var CSSImportRule: { + prototype: CSSImportRule; + new(): CSSImportRule; +}; + +/** + * An object representing a set of style for a given keyframe. It corresponds to the contains of a single keyframe of a @keyframes at-rule. It implements the CSSRule interface with a type value of 8 (CSSRule.KEYFRAME_RULE). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframeRule) + */ +interface CSSKeyframeRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframeRule/keyText) */ + keyText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframeRule/style) */ + get style(): CSSStyleDeclaration; + set style(cssText: string); +} + +declare var CSSKeyframeRule: { + prototype: CSSKeyframeRule; + new(): CSSKeyframeRule; +}; + +/** + * An object representing a complete set of keyframes for a CSS animation. It corresponds to the contains of a whole @keyframes at-rule. It implements the CSSRule interface with a type value of 7 (CSSRule.KEYFRAMES_RULE). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule) + */ +interface CSSKeyframesRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule/cssRules) */ + readonly cssRules: CSSRuleList; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule/length) */ + readonly length: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule/name) */ + name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule/appendRule) */ + appendRule(rule: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule/deleteRule) */ + deleteRule(select: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule/findRule) */ + findRule(select: string): CSSKeyframeRule | null; + [index: number]: CSSKeyframeRule; +} + +declare var CSSKeyframesRule: { + prototype: CSSKeyframesRule; + new(): CSSKeyframesRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeywordValue) */ +interface CSSKeywordValue extends CSSStyleValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeywordValue/value) */ + value: string; +} + +declare var CSSKeywordValue: { + prototype: CSSKeywordValue; + new(value: string): CSSKeywordValue; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSLayerBlockRule) */ +interface CSSLayerBlockRule extends CSSGroupingRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSLayerBlockRule/name) */ + readonly name: string; +} + +declare var CSSLayerBlockRule: { + prototype: CSSLayerBlockRule; + new(): CSSLayerBlockRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSLayerStatementRule) */ +interface CSSLayerStatementRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSLayerStatementRule/nameList) */ + readonly nameList: ReadonlyArray; +} + +declare var CSSLayerStatementRule: { + prototype: CSSLayerStatementRule; + new(): CSSLayerStatementRule; +}; + +interface CSSMathClamp extends CSSMathValue { + readonly lower: CSSNumericValue; + readonly upper: CSSNumericValue; + readonly value: CSSNumericValue; +} + +declare var CSSMathClamp: { + prototype: CSSMathClamp; + new(lower: CSSNumberish, value: CSSNumberish, upper: CSSNumberish): CSSMathClamp; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathInvert) */ +interface CSSMathInvert extends CSSMathValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathInvert/value) */ + readonly value: CSSNumericValue; +} + +declare var CSSMathInvert: { + prototype: CSSMathInvert; + new(arg: CSSNumberish): CSSMathInvert; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathMax) */ +interface CSSMathMax extends CSSMathValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathMax/values) */ + readonly values: CSSNumericArray; +} + +declare var CSSMathMax: { + prototype: CSSMathMax; + new(...args: CSSNumberish[]): CSSMathMax; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathMin) */ +interface CSSMathMin extends CSSMathValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathMin/values) */ + readonly values: CSSNumericArray; +} + +declare var CSSMathMin: { + prototype: CSSMathMin; + new(...args: CSSNumberish[]): CSSMathMin; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathNegate) */ +interface CSSMathNegate extends CSSMathValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathNegate/value) */ + readonly value: CSSNumericValue; +} + +declare var CSSMathNegate: { + prototype: CSSMathNegate; + new(arg: CSSNumberish): CSSMathNegate; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathProduct) */ +interface CSSMathProduct extends CSSMathValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathProduct/values) */ + readonly values: CSSNumericArray; +} + +declare var CSSMathProduct: { + prototype: CSSMathProduct; + new(...args: CSSNumberish[]): CSSMathProduct; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathSum) */ +interface CSSMathSum extends CSSMathValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathSum/values) */ + readonly values: CSSNumericArray; +} + +declare var CSSMathSum: { + prototype: CSSMathSum; + new(...args: CSSNumberish[]): CSSMathSum; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathValue) */ +interface CSSMathValue extends CSSNumericValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathValue/operator) */ + readonly operator: CSSMathOperator; +} + +declare var CSSMathValue: { + prototype: CSSMathValue; + new(): CSSMathValue; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMatrixComponent) */ +interface CSSMatrixComponent extends CSSTransformComponent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMatrixComponent/matrix) */ + matrix: DOMMatrix; +} + +declare var CSSMatrixComponent: { + prototype: CSSMatrixComponent; + new(matrix: DOMMatrixReadOnly, options?: CSSMatrixComponentOptions): CSSMatrixComponent; +}; + +/** + * A single CSS @media rule. It implements the CSSConditionRule interface, and therefore the CSSGroupingRule and the CSSRule interface with a type value of 4 (CSSRule.MEDIA_RULE). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMediaRule) + */ +interface CSSMediaRule extends CSSConditionRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMediaRule/media) */ + get media(): MediaList; + set media(mediaText: string); +} + +declare var CSSMediaRule: { + prototype: CSSMediaRule; + new(): CSSMediaRule; +}; + +/** + * An object representing a single CSS @namespace at-rule. It implements the CSSRule interface, with a type value of 10 (CSSRule.NAMESPACE_RULE). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNamespaceRule) + */ +interface CSSNamespaceRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNamespaceRule/namespaceURI) */ + readonly namespaceURI: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNamespaceRule/prefix) */ + readonly prefix: string; +} + +declare var CSSNamespaceRule: { + prototype: CSSNamespaceRule; + new(): CSSNamespaceRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNestedDeclarations) */ +interface CSSNestedDeclarations extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNestedDeclarations/style) */ + get style(): CSSStyleDeclaration; + set style(cssText: string); +} + +declare var CSSNestedDeclarations: { + prototype: CSSNestedDeclarations; + new(): CSSNestedDeclarations; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericArray) */ +interface CSSNumericArray { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericArray/length) */ + readonly length: number; + forEach(callbackfn: (value: CSSNumericValue, key: number, parent: CSSNumericArray) => void, thisArg?: any): void; + [index: number]: CSSNumericValue; +} + +declare var CSSNumericArray: { + prototype: CSSNumericArray; + new(): CSSNumericArray; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue) */ +interface CSSNumericValue extends CSSStyleValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/add) */ + add(...values: CSSNumberish[]): CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/div) */ + div(...values: CSSNumberish[]): CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/equals) */ + equals(...value: CSSNumberish[]): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/max) */ + max(...values: CSSNumberish[]): CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/min) */ + min(...values: CSSNumberish[]): CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/mul) */ + mul(...values: CSSNumberish[]): CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/sub) */ + sub(...values: CSSNumberish[]): CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/to) */ + to(unit: string): CSSUnitValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/toSum) */ + toSum(...units: string[]): CSSMathSum; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/type) */ + type(): CSSNumericType; +} + +declare var CSSNumericValue: { + prototype: CSSNumericValue; + new(): CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSNumericValue/parse_static) */ + parse(cssText: string): CSSNumericValue; +}; + +/** + * CSSPageRule is an interface representing a single CSS @page rule. It implements the CSSRule interface with a type value of 6 (CSSRule.PAGE_RULE). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPageRule) + */ +interface CSSPageRule extends CSSGroupingRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPageRule/selectorText) */ + selectorText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPageRule/style) */ + get style(): CSSStyleDeclaration; + set style(cssText: string); +} + +declare var CSSPageRule: { + prototype: CSSPageRule; + new(): CSSPageRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPerspective) */ +interface CSSPerspective extends CSSTransformComponent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPerspective/length) */ + length: CSSPerspectiveValue; +} + +declare var CSSPerspective: { + prototype: CSSPerspective; + new(length: CSSPerspectiveValue): CSSPerspective; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPropertyRule) */ +interface CSSPropertyRule extends CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPropertyRule/inherits) */ + readonly inherits: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPropertyRule/initialValue) */ + readonly initialValue: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPropertyRule/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPropertyRule/syntax) */ + readonly syntax: string; +} + +declare var CSSPropertyRule: { + prototype: CSSPropertyRule; + new(): CSSPropertyRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRotate) */ +interface CSSRotate extends CSSTransformComponent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRotate/angle) */ + angle: CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRotate/x) */ + x: CSSNumberish; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRotate/y) */ + y: CSSNumberish; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRotate/z) */ + z: CSSNumberish; +} + +declare var CSSRotate: { + prototype: CSSRotate; + new(angle: CSSNumericValue): CSSRotate; + new(x: CSSNumberish, y: CSSNumberish, z: CSSNumberish, angle: CSSNumericValue): CSSRotate; +}; + +/** + * A single CSS rule. There are several types of rules, listed in the Type constants section below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRule) + */ +interface CSSRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRule/cssText) */ + cssText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRule/parentRule) */ + readonly parentRule: CSSRule | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRule/parentStyleSheet) */ + readonly parentStyleSheet: CSSStyleSheet | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRule/type) + */ + readonly type: number; + readonly STYLE_RULE: 1; + readonly CHARSET_RULE: 2; + readonly IMPORT_RULE: 3; + readonly MEDIA_RULE: 4; + readonly FONT_FACE_RULE: 5; + readonly PAGE_RULE: 6; + readonly NAMESPACE_RULE: 10; + readonly KEYFRAMES_RULE: 7; + readonly KEYFRAME_RULE: 8; + readonly SUPPORTS_RULE: 12; + readonly COUNTER_STYLE_RULE: 11; + readonly FONT_FEATURE_VALUES_RULE: 14; +} + +declare var CSSRule: { + prototype: CSSRule; + new(): CSSRule; + readonly STYLE_RULE: 1; + readonly CHARSET_RULE: 2; + readonly IMPORT_RULE: 3; + readonly MEDIA_RULE: 4; + readonly FONT_FACE_RULE: 5; + readonly PAGE_RULE: 6; + readonly NAMESPACE_RULE: 10; + readonly KEYFRAMES_RULE: 7; + readonly KEYFRAME_RULE: 8; + readonly SUPPORTS_RULE: 12; + readonly COUNTER_STYLE_RULE: 11; + readonly FONT_FEATURE_VALUES_RULE: 14; +}; + +/** + * A CSSRuleList is an (indirect-modify only) array-like object containing an ordered collection of CSSRule objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRuleList) + */ +interface CSSRuleList { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRuleList/length) */ + readonly length: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSRuleList/item) */ + item(index: number): CSSRule | null; + [index: number]: CSSRule; +} + +declare var CSSRuleList: { + prototype: CSSRuleList; + new(): CSSRuleList; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSScale) */ +interface CSSScale extends CSSTransformComponent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSScale/x) */ + x: CSSNumberish; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSScale/y) */ + y: CSSNumberish; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSScale/z) */ + z: CSSNumberish; +} + +declare var CSSScale: { + prototype: CSSScale; + new(x: CSSNumberish, y: CSSNumberish, z?: CSSNumberish): CSSScale; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSScopeRule) */ +interface CSSScopeRule extends CSSGroupingRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSScopeRule/end) */ + readonly end: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSScopeRule/start) */ + readonly start: string | null; +} + +declare var CSSScopeRule: { + prototype: CSSScopeRule; + new(): CSSScopeRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSSkew) */ +interface CSSSkew extends CSSTransformComponent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSSkew/ax) */ + ax: CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSSkew/ay) */ + ay: CSSNumericValue; +} + +declare var CSSSkew: { + prototype: CSSSkew; + new(ax: CSSNumericValue, ay: CSSNumericValue): CSSSkew; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSSkewX) */ +interface CSSSkewX extends CSSTransformComponent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSSkewX/ax) */ + ax: CSSNumericValue; +} + +declare var CSSSkewX: { + prototype: CSSSkewX; + new(ax: CSSNumericValue): CSSSkewX; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSSkewY) */ +interface CSSSkewY extends CSSTransformComponent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSSkewY/ay) */ + ay: CSSNumericValue; +} + +declare var CSSSkewY: { + prototype: CSSSkewY; + new(ay: CSSNumericValue): CSSSkewY; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStartingStyleRule) */ +interface CSSStartingStyleRule extends CSSGroupingRule { +} + +declare var CSSStartingStyleRule: { + prototype: CSSStartingStyleRule; + new(): CSSStartingStyleRule; +}; + +/** + * An object that is a CSS declaration block, and exposes style information and various style-related methods and properties. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration) + */ +interface CSSStyleDeclaration { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/accent-color) */ + accentColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/align-content) */ + alignContent: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/align-items) */ + alignItems: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/align-self) */ + alignSelf: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/alignment-baseline) */ + alignmentBaseline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/all) */ + all: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation) */ + animation: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-composition) */ + animationComposition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-delay) */ + animationDelay: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-direction) */ + animationDirection: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-duration) */ + animationDuration: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-fill-mode) */ + animationFillMode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-iteration-count) */ + animationIterationCount: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-name) */ + animationName: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-play-state) */ + animationPlayState: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-timing-function) */ + animationTimingFunction: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/appearance) */ + appearance: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/aspect-ratio) */ + aspectRatio: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/backdrop-filter) */ + backdropFilter: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/backface-visibility) */ + backfaceVisibility: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background) */ + background: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-attachment) */ + backgroundAttachment: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-blend-mode) */ + backgroundBlendMode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-clip) */ + backgroundClip: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-color) */ + backgroundColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-image) */ + backgroundImage: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-origin) */ + backgroundOrigin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-position) */ + backgroundPosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-position-x) */ + backgroundPositionX: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-position-y) */ + backgroundPositionY: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-repeat) */ + backgroundRepeat: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-size) */ + backgroundSize: string; + baselineShift: string; + baselineSource: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/block-size) */ + blockSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border) */ + border: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block) */ + borderBlock: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-color) */ + borderBlockColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-end) */ + borderBlockEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-end-color) */ + borderBlockEndColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-end-style) */ + borderBlockEndStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-end-width) */ + borderBlockEndWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-start) */ + borderBlockStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-start-color) */ + borderBlockStartColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-start-style) */ + borderBlockStartStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-start-width) */ + borderBlockStartWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-style) */ + borderBlockStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-block-width) */ + borderBlockWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-bottom) */ + borderBottom: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-bottom-color) */ + borderBottomColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-bottom-left-radius) */ + borderBottomLeftRadius: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-bottom-right-radius) */ + borderBottomRightRadius: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-bottom-style) */ + borderBottomStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-bottom-width) */ + borderBottomWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-collapse) */ + borderCollapse: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-color) */ + borderColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-end-end-radius) */ + borderEndEndRadius: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-end-start-radius) */ + borderEndStartRadius: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-image) */ + borderImage: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-image-outset) */ + borderImageOutset: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-image-repeat) */ + borderImageRepeat: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-image-slice) */ + borderImageSlice: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-image-source) */ + borderImageSource: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-image-width) */ + borderImageWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline) */ + borderInline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-color) */ + borderInlineColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-end) */ + borderInlineEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-end-color) */ + borderInlineEndColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-end-style) */ + borderInlineEndStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-end-width) */ + borderInlineEndWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-start) */ + borderInlineStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-start-color) */ + borderInlineStartColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-start-style) */ + borderInlineStartStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-start-width) */ + borderInlineStartWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-style) */ + borderInlineStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-inline-width) */ + borderInlineWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-left) */ + borderLeft: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-left-color) */ + borderLeftColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-left-style) */ + borderLeftStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-left-width) */ + borderLeftWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-radius) */ + borderRadius: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-right) */ + borderRight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-right-color) */ + borderRightColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-right-style) */ + borderRightStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-right-width) */ + borderRightWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-spacing) */ + borderSpacing: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-start-end-radius) */ + borderStartEndRadius: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-start-start-radius) */ + borderStartStartRadius: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-style) */ + borderStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-top) */ + borderTop: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-top-color) */ + borderTopColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-top-left-radius) */ + borderTopLeftRadius: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-top-right-radius) */ + borderTopRightRadius: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-top-style) */ + borderTopStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-top-width) */ + borderTopWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-width) */ + borderWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/bottom) */ + bottom: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-decoration-break) */ + boxDecorationBreak: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-shadow) */ + boxShadow: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-sizing) */ + boxSizing: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/break-after) */ + breakAfter: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/break-before) */ + breakBefore: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/break-inside) */ + breakInside: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/caption-side) */ + captionSide: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/caret-color) */ + caretColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/clear) */ + clear: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/clip) + */ + clip: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/clip-path) */ + clipPath: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/clip-rule) */ + clipRule: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/color) */ + color: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/color-interpolation) */ + colorInterpolation: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/color-interpolation-filters) */ + colorInterpolationFilters: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/color-scheme) */ + colorScheme: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/column-count) */ + columnCount: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/column-fill) */ + columnFill: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/column-gap) */ + columnGap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/column-rule) */ + columnRule: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/column-rule-color) */ + columnRuleColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/column-rule-style) */ + columnRuleStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/column-rule-width) */ + columnRuleWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/column-span) */ + columnSpan: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/column-width) */ + columnWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/columns) */ + columns: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain) */ + contain: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain-intrinsic-block-size) */ + containIntrinsicBlockSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain-intrinsic-height) */ + containIntrinsicHeight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain-intrinsic-inline-size) */ + containIntrinsicInlineSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain-intrinsic-size) */ + containIntrinsicSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain-intrinsic-width) */ + containIntrinsicWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/container) */ + container: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/container-name) */ + containerName: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/container-type) */ + containerType: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/content) */ + content: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/content-visibility) */ + contentVisibility: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/counter-increment) */ + counterIncrement: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/counter-reset) */ + counterReset: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/counter-set) */ + counterSet: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration/cssFloat) */ + cssFloat: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration/cssText) */ + cssText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/cursor) */ + cursor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/cx) */ + cx: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/cy) */ + cy: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/d) */ + d: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/direction) */ + direction: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/display) */ + display: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/dominant-baseline) */ + dominantBaseline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/empty-cells) */ + emptyCells: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/fill) */ + fill: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/fill-opacity) */ + fillOpacity: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/fill-rule) */ + fillRule: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/filter) */ + filter: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex) */ + flex: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-basis) */ + flexBasis: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-direction) */ + flexDirection: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-flow) */ + flexFlow: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-grow) */ + flexGrow: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-shrink) */ + flexShrink: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-wrap) */ + flexWrap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/float) */ + float: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flood-color) */ + floodColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flood-opacity) */ + floodOpacity: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font) */ + font: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-family) */ + fontFamily: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-feature-settings) */ + fontFeatureSettings: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-kerning) */ + fontKerning: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-optical-sizing) */ + fontOpticalSizing: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-palette) */ + fontPalette: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-size) */ + fontSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-size-adjust) */ + fontSizeAdjust: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-stretch) */ + fontStretch: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-style) */ + fontStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-synthesis) */ + fontSynthesis: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-synthesis-small-caps) */ + fontSynthesisSmallCaps: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-synthesis-style) */ + fontSynthesisStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-synthesis-weight) */ + fontSynthesisWeight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-variant) */ + fontVariant: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-variant-alternates) */ + fontVariantAlternates: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-variant-caps) */ + fontVariantCaps: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-variant-east-asian) */ + fontVariantEastAsian: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-variant-ligatures) */ + fontVariantLigatures: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-variant-numeric) */ + fontVariantNumeric: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-variant-position) */ + fontVariantPosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-variation-settings) */ + fontVariationSettings: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/font-weight) */ + fontWeight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/forced-color-adjust) */ + forcedColorAdjust: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/gap) */ + gap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid) */ + grid: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-area) */ + gridArea: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-auto-columns) */ + gridAutoColumns: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-auto-flow) */ + gridAutoFlow: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-auto-rows) */ + gridAutoRows: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-column) */ + gridColumn: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-column-end) */ + gridColumnEnd: string; + /** @deprecated This is a legacy alias of `columnGap`. */ + gridColumnGap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-column-start) */ + gridColumnStart: string; + /** @deprecated This is a legacy alias of `gap`. */ + gridGap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-row) */ + gridRow: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-row-end) */ + gridRowEnd: string; + /** @deprecated This is a legacy alias of `rowGap`. */ + gridRowGap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-row-start) */ + gridRowStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-template) */ + gridTemplate: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-template-areas) */ + gridTemplateAreas: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-template-columns) */ + gridTemplateColumns: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/grid-template-rows) */ + gridTemplateRows: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/height) */ + height: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/hyphenate-character) */ + hyphenateCharacter: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/hyphens) */ + hyphens: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/image-orientation) + */ + imageOrientation: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/image-rendering) */ + imageRendering: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/inline-size) */ + inlineSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/inset) */ + inset: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/inset-block) */ + insetBlock: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/inset-block-end) */ + insetBlockEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/inset-block-start) */ + insetBlockStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/inset-inline) */ + insetInline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/inset-inline-end) */ + insetInlineEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/inset-inline-start) */ + insetInlineStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/isolation) */ + isolation: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/justify-content) */ + justifyContent: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/justify-items) */ + justifyItems: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/justify-self) */ + justifySelf: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/left) */ + left: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration/length) */ + readonly length: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/letter-spacing) */ + letterSpacing: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/lighting-color) */ + lightingColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/line-break) */ + lineBreak: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/line-height) */ + lineHeight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/list-style) */ + listStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/list-style-image) */ + listStyleImage: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/list-style-position) */ + listStylePosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/list-style-type) */ + listStyleType: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin) */ + margin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-block) */ + marginBlock: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-block-end) */ + marginBlockEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-block-start) */ + marginBlockStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-bottom) */ + marginBottom: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-inline) */ + marginInline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-inline-end) */ + marginInlineEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-inline-start) */ + marginInlineStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-left) */ + marginLeft: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-right) */ + marginRight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-top) */ + marginTop: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/marker) */ + marker: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/marker-end) */ + markerEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/marker-mid) */ + markerMid: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/marker-start) */ + markerStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask) */ + mask: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-clip) */ + maskClip: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-composite) */ + maskComposite: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-image) */ + maskImage: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-mode) */ + maskMode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-origin) */ + maskOrigin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-position) */ + maskPosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-repeat) */ + maskRepeat: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-size) */ + maskSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-type) */ + maskType: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/math-depth) */ + mathDepth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/math-style) */ + mathStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/max-block-size) */ + maxBlockSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/max-height) */ + maxHeight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/max-inline-size) */ + maxInlineSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/max-width) */ + maxWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/min-block-size) */ + minBlockSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/min-height) */ + minHeight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/min-inline-size) */ + minInlineSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/min-width) */ + minWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mix-blend-mode) */ + mixBlendMode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/object-fit) */ + objectFit: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/object-position) */ + objectPosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/offset) */ + offset: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/offset-anchor) */ + offsetAnchor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/offset-distance) */ + offsetDistance: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/offset-path) */ + offsetPath: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/offset-position) */ + offsetPosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/offset-rotate) */ + offsetRotate: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/opacity) */ + opacity: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/order) */ + order: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/orphans) */ + orphans: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/outline) */ + outline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/outline-color) */ + outlineColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/outline-offset) */ + outlineOffset: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/outline-style) */ + outlineStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/outline-width) */ + outlineWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overflow) */ + overflow: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overflow-anchor) */ + overflowAnchor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overflow-clip-margin) */ + overflowClipMargin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overflow-wrap) */ + overflowWrap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overflow-x) */ + overflowX: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overflow-y) */ + overflowY: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overscroll-behavior) */ + overscrollBehavior: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overscroll-behavior-block) */ + overscrollBehaviorBlock: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overscroll-behavior-inline) */ + overscrollBehaviorInline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overscroll-behavior-x) */ + overscrollBehaviorX: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overscroll-behavior-y) */ + overscrollBehaviorY: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding) */ + padding: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-block) */ + paddingBlock: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-block-end) */ + paddingBlockEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-block-start) */ + paddingBlockStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-bottom) */ + paddingBottom: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-inline) */ + paddingInline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-inline-end) */ + paddingInlineEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-inline-start) */ + paddingInlineStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-left) */ + paddingLeft: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-right) */ + paddingRight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/padding-top) */ + paddingTop: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page) */ + page: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-after) + */ + pageBreakAfter: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-before) + */ + pageBreakBefore: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-inside) + */ + pageBreakInside: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/paint-order) */ + paintOrder: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration/parentRule) */ + readonly parentRule: CSSRule | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/perspective) */ + perspective: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/perspective-origin) */ + perspectiveOrigin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/place-content) */ + placeContent: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/place-items) */ + placeItems: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/place-self) */ + placeSelf: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/pointer-events) */ + pointerEvents: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/position) */ + position: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/print-color-adjust) */ + printColorAdjust: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/quotes) */ + quotes: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/r) */ + r: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/resize) */ + resize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/right) */ + right: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/rotate) */ + rotate: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/row-gap) */ + rowGap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/ruby-align) */ + rubyAlign: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/ruby-position) */ + rubyPosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/rx) */ + rx: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/ry) */ + ry: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scale) */ + scale: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-behavior) */ + scrollBehavior: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin) */ + scrollMargin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-block) */ + scrollMarginBlock: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-block-end) */ + scrollMarginBlockEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-block-start) */ + scrollMarginBlockStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-bottom) */ + scrollMarginBottom: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-inline) */ + scrollMarginInline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-inline-end) */ + scrollMarginInlineEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-inline-start) */ + scrollMarginInlineStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-left) */ + scrollMarginLeft: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-right) */ + scrollMarginRight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-margin-top) */ + scrollMarginTop: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding) */ + scrollPadding: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-block) */ + scrollPaddingBlock: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-block-end) */ + scrollPaddingBlockEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-block-start) */ + scrollPaddingBlockStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-bottom) */ + scrollPaddingBottom: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-inline) */ + scrollPaddingInline: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-inline-end) */ + scrollPaddingInlineEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-inline-start) */ + scrollPaddingInlineStart: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-left) */ + scrollPaddingLeft: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-right) */ + scrollPaddingRight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-padding-top) */ + scrollPaddingTop: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-snap-align) */ + scrollSnapAlign: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-snap-stop) */ + scrollSnapStop: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scroll-snap-type) */ + scrollSnapType: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scrollbar-color) */ + scrollbarColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scrollbar-gutter) */ + scrollbarGutter: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scrollbar-width) */ + scrollbarWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/shape-image-threshold) */ + shapeImageThreshold: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/shape-margin) */ + shapeMargin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/shape-outside) */ + shapeOutside: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/shape-rendering) */ + shapeRendering: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stop-color) */ + stopColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stop-opacity) */ + stopOpacity: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke) */ + stroke: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-dasharray) */ + strokeDasharray: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-dashoffset) */ + strokeDashoffset: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-linecap) */ + strokeLinecap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-linejoin) */ + strokeLinejoin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-miterlimit) */ + strokeMiterlimit: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-opacity) */ + strokeOpacity: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-width) */ + strokeWidth: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/tab-size) */ + tabSize: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/table-layout) */ + tableLayout: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-align) */ + textAlign: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-align-last) */ + textAlignLast: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-anchor) */ + textAnchor: string; + textBox: string; + textBoxEdge: string; + textBoxTrim: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-combine-upright) */ + textCombineUpright: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-decoration) */ + textDecoration: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-decoration-color) */ + textDecorationColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-decoration-line) */ + textDecorationLine: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-decoration-skip-ink) */ + textDecorationSkipInk: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-decoration-style) */ + textDecorationStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-decoration-thickness) */ + textDecorationThickness: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-emphasis) */ + textEmphasis: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-emphasis-color) */ + textEmphasisColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-emphasis-position) */ + textEmphasisPosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-emphasis-style) */ + textEmphasisStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-indent) */ + textIndent: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-orientation) */ + textOrientation: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-overflow) */ + textOverflow: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-rendering) */ + textRendering: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-shadow) */ + textShadow: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-transform) */ + textTransform: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-underline-offset) */ + textUnderlineOffset: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-underline-position) */ + textUnderlinePosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-wrap) */ + textWrap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-wrap-mode) */ + textWrapMode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-wrap-style) */ + textWrapStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/top) */ + top: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/touch-action) */ + touchAction: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transform) */ + transform: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transform-box) */ + transformBox: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transform-origin) */ + transformOrigin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transform-style) */ + transformStyle: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition) */ + transition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition-behavior) */ + transitionBehavior: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition-delay) */ + transitionDelay: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition-duration) */ + transitionDuration: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition-property) */ + transitionProperty: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition-timing-function) */ + transitionTimingFunction: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/translate) */ + translate: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/unicode-bidi) */ + unicodeBidi: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/user-select) */ + userSelect: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/vector-effect) */ + vectorEffect: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/vertical-align) */ + verticalAlign: string; + viewTransitionClass: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/view-transition-name) */ + viewTransitionName: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/visibility) */ + visibility: string; + /** + * @deprecated This is a legacy alias of `alignContent`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/align-content) + */ + webkitAlignContent: string; + /** + * @deprecated This is a legacy alias of `alignItems`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/align-items) + */ + webkitAlignItems: string; + /** + * @deprecated This is a legacy alias of `alignSelf`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/align-self) + */ + webkitAlignSelf: string; + /** + * @deprecated This is a legacy alias of `animation`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation) + */ + webkitAnimation: string; + /** + * @deprecated This is a legacy alias of `animationDelay`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-delay) + */ + webkitAnimationDelay: string; + /** + * @deprecated This is a legacy alias of `animationDirection`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-direction) + */ + webkitAnimationDirection: string; + /** + * @deprecated This is a legacy alias of `animationDuration`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-duration) + */ + webkitAnimationDuration: string; + /** + * @deprecated This is a legacy alias of `animationFillMode`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-fill-mode) + */ + webkitAnimationFillMode: string; + /** + * @deprecated This is a legacy alias of `animationIterationCount`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-iteration-count) + */ + webkitAnimationIterationCount: string; + /** + * @deprecated This is a legacy alias of `animationName`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-name) + */ + webkitAnimationName: string; + /** + * @deprecated This is a legacy alias of `animationPlayState`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-play-state) + */ + webkitAnimationPlayState: string; + /** + * @deprecated This is a legacy alias of `animationTimingFunction`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/animation-timing-function) + */ + webkitAnimationTimingFunction: string; + /** + * @deprecated This is a legacy alias of `appearance`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/appearance) + */ + webkitAppearance: string; + /** + * @deprecated This is a legacy alias of `backfaceVisibility`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/backface-visibility) + */ + webkitBackfaceVisibility: string; + /** + * @deprecated This is a legacy alias of `backgroundClip`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-clip) + */ + webkitBackgroundClip: string; + /** + * @deprecated This is a legacy alias of `backgroundOrigin`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-origin) + */ + webkitBackgroundOrigin: string; + /** + * @deprecated This is a legacy alias of `backgroundSize`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/background-size) + */ + webkitBackgroundSize: string; + /** + * @deprecated This is a legacy alias of `borderBottomLeftRadius`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-bottom-left-radius) + */ + webkitBorderBottomLeftRadius: string; + /** + * @deprecated This is a legacy alias of `borderBottomRightRadius`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-bottom-right-radius) + */ + webkitBorderBottomRightRadius: string; + /** + * @deprecated This is a legacy alias of `borderRadius`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-radius) + */ + webkitBorderRadius: string; + /** + * @deprecated This is a legacy alias of `borderTopLeftRadius`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-top-left-radius) + */ + webkitBorderTopLeftRadius: string; + /** + * @deprecated This is a legacy alias of `borderTopRightRadius`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/border-top-right-radius) + */ + webkitBorderTopRightRadius: string; + /** + * @deprecated This is a legacy alias of `boxAlign`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-align) + */ + webkitBoxAlign: string; + /** + * @deprecated This is a legacy alias of `boxFlex`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-flex) + */ + webkitBoxFlex: string; + /** + * @deprecated This is a legacy alias of `boxOrdinalGroup`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-ordinal-group) + */ + webkitBoxOrdinalGroup: string; + /** + * @deprecated This is a legacy alias of `boxOrient`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-orient) + */ + webkitBoxOrient: string; + /** + * @deprecated This is a legacy alias of `boxPack`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-pack) + */ + webkitBoxPack: string; + /** + * @deprecated This is a legacy alias of `boxShadow`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-shadow) + */ + webkitBoxShadow: string; + /** + * @deprecated This is a legacy alias of `boxSizing`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/box-sizing) + */ + webkitBoxSizing: string; + /** + * @deprecated This is a legacy alias of `filter`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/filter) + */ + webkitFilter: string; + /** + * @deprecated This is a legacy alias of `flex`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex) + */ + webkitFlex: string; + /** + * @deprecated This is a legacy alias of `flexBasis`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-basis) + */ + webkitFlexBasis: string; + /** + * @deprecated This is a legacy alias of `flexDirection`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-direction) + */ + webkitFlexDirection: string; + /** + * @deprecated This is a legacy alias of `flexFlow`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-flow) + */ + webkitFlexFlow: string; + /** + * @deprecated This is a legacy alias of `flexGrow`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-grow) + */ + webkitFlexGrow: string; + /** + * @deprecated This is a legacy alias of `flexShrink`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-shrink) + */ + webkitFlexShrink: string; + /** + * @deprecated This is a legacy alias of `flexWrap`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/flex-wrap) + */ + webkitFlexWrap: string; + /** + * @deprecated This is a legacy alias of `justifyContent`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/justify-content) + */ + webkitJustifyContent: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/-webkit-line-clamp) */ + webkitLineClamp: string; + /** + * @deprecated This is a legacy alias of `mask`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask) + */ + webkitMask: string; + /** + * @deprecated This is a legacy alias of `maskBorder`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-border) + */ + webkitMaskBoxImage: string; + /** + * @deprecated This is a legacy alias of `maskBorderOutset`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-border-outset) + */ + webkitMaskBoxImageOutset: string; + /** + * @deprecated This is a legacy alias of `maskBorderRepeat`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-border-repeat) + */ + webkitMaskBoxImageRepeat: string; + /** + * @deprecated This is a legacy alias of `maskBorderSlice`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-border-slice) + */ + webkitMaskBoxImageSlice: string; + /** + * @deprecated This is a legacy alias of `maskBorderSource`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-border-source) + */ + webkitMaskBoxImageSource: string; + /** + * @deprecated This is a legacy alias of `maskBorderWidth`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-border-width) + */ + webkitMaskBoxImageWidth: string; + /** + * @deprecated This is a legacy alias of `maskClip`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-clip) + */ + webkitMaskClip: string; + /** + * @deprecated This is a legacy alias of `maskComposite`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-composite) + */ + webkitMaskComposite: string; + /** + * @deprecated This is a legacy alias of `maskImage`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-image) + */ + webkitMaskImage: string; + /** + * @deprecated This is a legacy alias of `maskOrigin`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-origin) + */ + webkitMaskOrigin: string; + /** + * @deprecated This is a legacy alias of `maskPosition`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-position) + */ + webkitMaskPosition: string; + /** + * @deprecated This is a legacy alias of `maskRepeat`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-repeat) + */ + webkitMaskRepeat: string; + /** + * @deprecated This is a legacy alias of `maskSize`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask-size) + */ + webkitMaskSize: string; + /** + * @deprecated This is a legacy alias of `order`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/order) + */ + webkitOrder: string; + /** + * @deprecated This is a legacy alias of `perspective`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/perspective) + */ + webkitPerspective: string; + /** + * @deprecated This is a legacy alias of `perspectiveOrigin`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/perspective-origin) + */ + webkitPerspectiveOrigin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/-webkit-text-fill-color) */ + webkitTextFillColor: string; + /** + * @deprecated This is a legacy alias of `textSizeAdjust`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-size-adjust) + */ + webkitTextSizeAdjust: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/-webkit-text-stroke) */ + webkitTextStroke: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/-webkit-text-stroke-color) */ + webkitTextStrokeColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/-webkit-text-stroke-width) */ + webkitTextStrokeWidth: string; + /** + * @deprecated This is a legacy alias of `transform`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transform) + */ + webkitTransform: string; + /** + * @deprecated This is a legacy alias of `transformOrigin`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transform-origin) + */ + webkitTransformOrigin: string; + /** + * @deprecated This is a legacy alias of `transformStyle`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transform-style) + */ + webkitTransformStyle: string; + /** + * @deprecated This is a legacy alias of `transition`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition) + */ + webkitTransition: string; + /** + * @deprecated This is a legacy alias of `transitionDelay`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition-delay) + */ + webkitTransitionDelay: string; + /** + * @deprecated This is a legacy alias of `transitionDuration`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition-duration) + */ + webkitTransitionDuration: string; + /** + * @deprecated This is a legacy alias of `transitionProperty`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition-property) + */ + webkitTransitionProperty: string; + /** + * @deprecated This is a legacy alias of `transitionTimingFunction`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/transition-timing-function) + */ + webkitTransitionTimingFunction: string; + /** + * @deprecated This is a legacy alias of `userSelect`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/user-select) + */ + webkitUserSelect: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/white-space) */ + whiteSpace: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/white-space-collapse) */ + whiteSpaceCollapse: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/widows) */ + widows: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/width) */ + width: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/will-change) */ + willChange: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/word-break) */ + wordBreak: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/word-spacing) */ + wordSpacing: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/overflow-wrap) + */ + wordWrap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/writing-mode) */ + writingMode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/x) */ + x: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/y) */ + y: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/z-index) */ + zIndex: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/zoom) */ + zoom: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration/getPropertyPriority) */ + getPropertyPriority(property: string): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration/getPropertyValue) */ + getPropertyValue(property: string): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration/item) */ + item(index: number): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration/removeProperty) */ + removeProperty(property: string): string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleDeclaration/setProperty) */ + setProperty(property: string, value: string | null, priority?: string): void; + [index: number]: string; +} + +declare var CSSStyleDeclaration: { + prototype: CSSStyleDeclaration; + new(): CSSStyleDeclaration; +}; + +/** + * CSSStyleRule represents a single CSS style rule. It implements the CSSRule interface with a type value of 1 (CSSRule.STYLE_RULE). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleRule) + */ +interface CSSStyleRule extends CSSGroupingRule { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleRule/selectorText) */ + selectorText: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleRule/style) */ + get style(): CSSStyleDeclaration; + set style(cssText: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleRule/styleMap) */ + readonly styleMap: StylePropertyMap; +} + +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new(): CSSStyleRule; +}; + +/** + * A single CSS style sheet. It inherits properties and methods from its parent, StyleSheet. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet) + */ +interface CSSStyleSheet extends StyleSheet { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet/cssRules) */ + readonly cssRules: CSSRuleList; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet/ownerRule) */ + readonly ownerRule: CSSRule | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet/rules) + */ + readonly rules: CSSRuleList; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet/addRule) + */ + addRule(selector?: string, style?: string, index?: number): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet/deleteRule) */ + deleteRule(index: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet/insertRule) */ + insertRule(rule: string, index?: number): number; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet/removeRule) + */ + removeRule(index?: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet/replace) */ + replace(text: string): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleSheet/replaceSync) */ + replaceSync(text: string): void; +} + +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new(options?: CSSStyleSheetInit): CSSStyleSheet; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleValue) */ +interface CSSStyleValue { + toString(): string; +} + +declare var CSSStyleValue: { + prototype: CSSStyleValue; + new(): CSSStyleValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleValue/parse_static) */ + parse(property: string, cssText: string): CSSStyleValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSStyleValue/parseAll_static) */ + parseAll(property: string, cssText: string): CSSStyleValue[]; +}; + +/** + * An object representing a single CSS @supports at-rule. It implements the CSSConditionRule interface, and therefore the CSSRule and CSSGroupingRule interfaces with a type value of 12 (CSSRule.SUPPORTS_RULE). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSSupportsRule) + */ +interface CSSSupportsRule extends CSSConditionRule { +} + +declare var CSSSupportsRule: { + prototype: CSSSupportsRule; + new(): CSSSupportsRule; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTransformComponent) */ +interface CSSTransformComponent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTransformComponent/is2D) */ + is2D: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTransformComponent/toMatrix) */ + toMatrix(): DOMMatrix; + toString(): string; +} + +declare var CSSTransformComponent: { + prototype: CSSTransformComponent; + new(): CSSTransformComponent; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTransformValue) */ +interface CSSTransformValue extends CSSStyleValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTransformValue/is2D) */ + readonly is2D: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTransformValue/length) */ + readonly length: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTransformValue/toMatrix) */ + toMatrix(): DOMMatrix; + forEach(callbackfn: (value: CSSTransformComponent, key: number, parent: CSSTransformValue) => void, thisArg?: any): void; + [index: number]: CSSTransformComponent; +} + +declare var CSSTransformValue: { + prototype: CSSTransformValue; + new(transforms: CSSTransformComponent[]): CSSTransformValue; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTransition) */ +interface CSSTransition extends Animation { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTransition/transitionProperty) */ + readonly transitionProperty: string; + addEventListener(type: K, listener: (this: CSSTransition, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: CSSTransition, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var CSSTransition: { + prototype: CSSTransition; + new(): CSSTransition; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTranslate) */ +interface CSSTranslate extends CSSTransformComponent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTranslate/x) */ + x: CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTranslate/y) */ + y: CSSNumericValue; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSTranslate/z) */ + z: CSSNumericValue; +} + +declare var CSSTranslate: { + prototype: CSSTranslate; + new(x: CSSNumericValue, y: CSSNumericValue, z?: CSSNumericValue): CSSTranslate; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSUnitValue) */ +interface CSSUnitValue extends CSSNumericValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSUnitValue/unit) */ + readonly unit: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSUnitValue/value) */ + value: number; +} + +declare var CSSUnitValue: { + prototype: CSSUnitValue; + new(value: number, unit: string): CSSUnitValue; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSUnparsedValue) */ +interface CSSUnparsedValue extends CSSStyleValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSUnparsedValue/length) */ + readonly length: number; + forEach(callbackfn: (value: CSSUnparsedSegment, key: number, parent: CSSUnparsedValue) => void, thisArg?: any): void; + [index: number]: CSSUnparsedSegment; +} + +declare var CSSUnparsedValue: { + prototype: CSSUnparsedValue; + new(members: CSSUnparsedSegment[]): CSSUnparsedValue; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSVariableReferenceValue) */ +interface CSSVariableReferenceValue { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSVariableReferenceValue/fallback) */ + readonly fallback: CSSUnparsedValue | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSVariableReferenceValue/variable) */ + variable: string; +} + +declare var CSSVariableReferenceValue: { + prototype: CSSVariableReferenceValue; + new(variable: string, fallback?: CSSUnparsedValue | null): CSSVariableReferenceValue; +}; + +interface CSSViewTransitionRule extends CSSRule { + readonly navigation: string; + readonly types: ReadonlyArray; +} + +declare var CSSViewTransitionRule: { + prototype: CSSViewTransitionRule; + new(): CSSViewTransitionRule; +}; + +/** + * Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache) + */ +interface Cache { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/add) */ + add(request: RequestInfo | URL): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/addAll) */ + addAll(requests: RequestInfo[]): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/delete) */ + delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/keys) */ + keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/match) */ + match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/matchAll) */ + matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/put) */ + put(request: RequestInfo | URL, response: Response): Promise; +} + +declare var Cache: { + prototype: Cache; + new(): Cache; +}; + +/** + * The storage for Cache objects. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage) + */ +interface CacheStorage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/delete) */ + delete(cacheName: string): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/has) */ + has(cacheName: string): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/keys) */ + keys(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/match) */ + match(request: RequestInfo | URL, options?: MultiCacheQueryOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; +} + +declare var CacheStorage: { + prototype: CacheStorage; + new(): CacheStorage; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasCaptureMediaStreamTrack) */ +interface CanvasCaptureMediaStreamTrack extends MediaStreamTrack { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasCaptureMediaStreamTrack/canvas) */ + readonly canvas: HTMLCanvasElement; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasCaptureMediaStreamTrack/requestFrame) */ + requestFrame(): void; + addEventListener(type: K, listener: (this: CanvasCaptureMediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: CanvasCaptureMediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var CanvasCaptureMediaStreamTrack: { + prototype: CanvasCaptureMediaStreamTrack; + new(): CanvasCaptureMediaStreamTrack; +}; + +interface CanvasCompositing { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/globalAlpha) */ + globalAlpha: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation) */ + globalCompositeOperation: GlobalCompositeOperation; +} + +interface CanvasDrawImage { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/drawImage) */ + drawImage(image: CanvasImageSource, dx: number, dy: number): void; + drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void; + drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; +} + +interface CanvasDrawPath { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/beginPath) */ + beginPath(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/clip) */ + clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/fill) */ + fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/isPointInPath) */ + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/isPointInStroke) */ + isPointInStroke(x: number, y: number): boolean; + isPointInStroke(path: Path2D, x: number, y: number): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/stroke) */ + stroke(): void; + stroke(path: Path2D): void; +} + +interface CanvasFillStrokeStyles { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/fillStyle) */ + fillStyle: string | CanvasGradient | CanvasPattern; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/strokeStyle) */ + strokeStyle: string | CanvasGradient | CanvasPattern; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/createConicGradient) */ + createConicGradient(startAngle: number, x: number, y: number): CanvasGradient; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/createLinearGradient) */ + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/createPattern) */ + createPattern(image: CanvasImageSource, repetition: string | null): CanvasPattern | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/createRadialGradient) */ + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; +} + +interface CanvasFilters { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/filter) */ + filter: string; +} + +/** + * An opaque object describing a gradient. It is returned by the methods CanvasRenderingContext2D.createLinearGradient() or CanvasRenderingContext2D.createRadialGradient(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasGradient) + */ +interface CanvasGradient { + /** + * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end. + * + * Throws an "IndexSizeError" DOMException if the offset is out of range. Throws a "SyntaxError" DOMException if the color cannot be parsed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasGradient/addColorStop) + */ + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasImageData { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/createImageData) */ + createImageData(sw: number, sh: number, settings?: ImageDataSettings): ImageData; + createImageData(imagedata: ImageData): ImageData; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/getImageData) */ + getImageData(sx: number, sy: number, sw: number, sh: number, settings?: ImageDataSettings): ImageData; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/putImageData) */ + putImageData(imagedata: ImageData, dx: number, dy: number): void; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void; +} + +interface CanvasImageSmoothing { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled) */ + imageSmoothingEnabled: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/imageSmoothingQuality) */ + imageSmoothingQuality: ImageSmoothingQuality; +} + +interface CanvasPath { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/arc) */ + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/arcTo) */ + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/bezierCurveTo) */ + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/closePath) */ + closePath(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/ellipse) */ + ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/lineTo) */ + lineTo(x: number, y: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/moveTo) */ + moveTo(x: number, y: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/quadraticCurveTo) */ + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/rect) */ + rect(x: number, y: number, w: number, h: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/roundRect) */ + roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | (number | DOMPointInit)[]): void; +} + +interface CanvasPathDrawingStyles { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/lineCap) */ + lineCap: CanvasLineCap; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/lineDashOffset) */ + lineDashOffset: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/lineJoin) */ + lineJoin: CanvasLineJoin; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/lineWidth) */ + lineWidth: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/miterLimit) */ + miterLimit: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/getLineDash) */ + getLineDash(): number[]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash) */ + setLineDash(segments: number[]): void; +} + +/** + * An opaque object describing a pattern, based on an image, a canvas, or a video, created by the CanvasRenderingContext2D.createPattern() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasPattern) + */ +interface CanvasPattern { + /** + * Sets the transformation matrix that will be used when rendering the pattern during a fill or stroke painting operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasPattern/setTransform) + */ + setTransform(transform?: DOMMatrix2DInit): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + +interface CanvasRect { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/clearRect) */ + clearRect(x: number, y: number, w: number, h: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/fillRect) */ + fillRect(x: number, y: number, w: number, h: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/strokeRect) */ + strokeRect(x: number, y: number, w: number, h: number): void; +} + +/** + * The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a element. It is used for drawing shapes, text, images, and other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D) + */ +interface CanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasSettings, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform, CanvasUserInterface { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/canvas) */ + readonly canvas: HTMLCanvasElement; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + +interface CanvasSettings { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/getContextAttributes) */ + getContextAttributes(): CanvasRenderingContext2DSettings; +} + +interface CanvasShadowStyles { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/shadowBlur) */ + shadowBlur: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/shadowColor) */ + shadowColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/shadowOffsetX) */ + shadowOffsetX: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/shadowOffsetY) */ + shadowOffsetY: number; +} + +interface CanvasState { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/isContextLost) */ + isContextLost(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/reset) */ + reset(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/restore) */ + restore(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/save) */ + save(): void; +} + +interface CanvasText { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/fillText) */ + fillText(text: string, x: number, y: number, maxWidth?: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/measureText) */ + measureText(text: string): TextMetrics; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/strokeText) */ + strokeText(text: string, x: number, y: number, maxWidth?: number): void; +} + +interface CanvasTextDrawingStyles { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/direction) */ + direction: CanvasDirection; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/font) */ + font: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/fontKerning) */ + fontKerning: CanvasFontKerning; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/fontStretch) */ + fontStretch: CanvasFontStretch; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/fontVariantCaps) */ + fontVariantCaps: CanvasFontVariantCaps; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/letterSpacing) */ + letterSpacing: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/textAlign) */ + textAlign: CanvasTextAlign; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/textBaseline) */ + textBaseline: CanvasTextBaseline; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/textRendering) */ + textRendering: CanvasTextRendering; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/wordSpacing) */ + wordSpacing: string; +} + +interface CanvasTransform { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/getTransform) */ + getTransform(): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/resetTransform) */ + resetTransform(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/rotate) */ + rotate(angle: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/scale) */ + scale(x: number, y: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setTransform) */ + setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void; + setTransform(transform?: DOMMatrix2DInit): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/transform) */ + transform(a: number, b: number, c: number, d: number, e: number, f: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/translate) */ + translate(x: number, y: number): void; +} + +interface CanvasUserInterface { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/drawFocusIfNeeded) */ + drawFocusIfNeeded(element: Element): void; + drawFocusIfNeeded(path: Path2D, element: Element): void; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CaretPosition) */ +interface CaretPosition { + readonly offset: number; + readonly offsetNode: Node; + getClientRect(): DOMRect | null; +} + +declare var CaretPosition: { + prototype: CaretPosition; + new(): CaretPosition; +}; + +/** + * The ChannelMergerNode interface, often used in conjunction with its opposite, ChannelSplitterNode, reunites different mono inputs into a single output. Each input is used to fill a channel of the output. This is useful for accessing each channels separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ChannelMergerNode) + */ +interface ChannelMergerNode extends AudioNode { +} + +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(context: BaseAudioContext, options?: ChannelMergerOptions): ChannelMergerNode; +}; + +/** + * The ChannelSplitterNode interface, often used in conjunction with its opposite, ChannelMergerNode, separates the different channels of an audio source into a set of mono outputs. This is useful for accessing each channel separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ChannelSplitterNode) + */ +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(context: BaseAudioContext, options?: ChannelSplitterOptions): ChannelSplitterNode; +}; + +/** + * The CharacterData abstract interface represents a Node object that contains characters. This is an abstract interface, meaning there aren't any object of type CharacterData: it is implemented by other interfaces, like Text, Comment, or ProcessingInstruction which aren't abstract. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData) + */ +interface CharacterData extends Node, ChildNode, NonDocumentTypeChildNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/data) */ + data: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/length) */ + readonly length: number; + readonly ownerDocument: Document; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/appendData) */ + appendData(data: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/deleteData) */ + deleteData(offset: number, count: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/insertData) */ + insertData(offset: number, data: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/replaceData) */ + replaceData(offset: number, count: number, data: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/substringData) */ + substringData(offset: number, count: number): string; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +}; + +interface ChildNode extends Node { + /** + * Inserts nodes just after node, while replacing strings in nodes with equivalent Text nodes. + * + * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/after) + */ + after(...nodes: (Node | string)[]): void; + /** + * Inserts nodes just before node, while replacing strings in nodes with equivalent Text nodes. + * + * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/before) + */ + before(...nodes: (Node | string)[]): void; + /** + * Removes node. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/remove) + */ + remove(): void; + /** + * Replaces node with nodes, while replacing strings in nodes with equivalent Text nodes. + * + * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/replaceWith) + */ + replaceWith(...nodes: (Node | string)[]): void; +} + +/** @deprecated */ +interface ClientRect extends DOMRect { +} + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clipboard) + */ +interface Clipboard extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clipboard/read) */ + read(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clipboard/readText) */ + readText(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clipboard/write) */ + write(data: ClipboardItems): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Clipboard/writeText) */ + writeText(data: string): Promise; +} + +declare var Clipboard: { + prototype: Clipboard; + new(): Clipboard; +}; + +/** + * Events providing information related to modification of the clipboard, that is cut, copy, and paste events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardEvent) + */ +interface ClipboardEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardEvent/clipboardData) */ + readonly clipboardData: DataTransfer | null; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardItem) + */ +interface ClipboardItem { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardItem/presentationStyle) */ + readonly presentationStyle: PresentationStyle; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardItem/types) */ + readonly types: ReadonlyArray; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardItem/getType) */ + getType(type: string): Promise; +} + +declare var ClipboardItem: { + prototype: ClipboardItem; + new(items: Record>, options?: ClipboardItemOptions): ClipboardItem; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardItem/supports_static) */ + supports(type: string): boolean; +}; + +/** + * A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) + */ +interface CloseEvent extends Event { + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(type: string, eventInitDict?: CloseEventInit): CloseEvent; +}; + +/** + * Textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Comment) + */ +interface Comment extends CharacterData { +} + +declare var Comment: { + prototype: Comment; + new(data?: string): Comment; +}; + +/** + * The DOM CompositionEvent represents events that occur due to the user indirectly entering text. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompositionEvent) + */ +interface CompositionEvent extends UIEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompositionEvent/data) */ + readonly data: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompositionEvent/initCompositionEvent) + */ + initCompositionEvent(typeArg: string, bubblesArg?: boolean, cancelableArg?: boolean, viewArg?: WindowProxy | null, dataArg?: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(type: string, eventInitDict?: CompositionEventInit): CompositionEvent; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ +interface CompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; +} + +declare var CompressionStream: { + prototype: CompressionStream; + new(format: CompressionFormat): CompressionStream; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) */ +interface ConstantSourceNode extends AudioScheduledSourceNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode/offset) */ + readonly offset: AudioParam; + addEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ConstantSourceNode: { + prototype: ConstantSourceNode; + new(context: BaseAudioContext, options?: ConstantSourceOptions): ConstantSourceNode; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContentVisibilityAutoStateChangeEvent) */ +interface ContentVisibilityAutoStateChangeEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContentVisibilityAutoStateChangeEvent/skipped) */ + readonly skipped: boolean; +} + +declare var ContentVisibilityAutoStateChangeEvent: { + prototype: ContentVisibilityAutoStateChangeEvent; + new(type: string, eventInitDict?: ContentVisibilityAutoStateChangeEventInit): ContentVisibilityAutoStateChangeEvent; +}; + +/** + * An AudioNode that performs a Linear Convolution on a given AudioBuffer, often used to achieve a reverb effect. A ConvolverNode always has exactly one input and one output. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ConvolverNode) + */ +interface ConvolverNode extends AudioNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ConvolverNode/buffer) */ + buffer: AudioBuffer | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ConvolverNode/normalize) */ + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(context: BaseAudioContext, options?: ConvolverOptions): ConvolverNode; +}; + +/** + * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) + */ +interface CountQueuingStrategy extends QueuingStrategy { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + readonly highWaterMark: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + readonly size: QueuingStrategySize; +} + +declare var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Credential) + */ +interface Credential { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Credential/id) */ + readonly id: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Credential/type) */ + readonly type: string; +} + +declare var Credential: { + prototype: Credential; + new(): Credential; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CredentialsContainer) + */ +interface CredentialsContainer { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CredentialsContainer/create) */ + create(options?: CredentialCreationOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CredentialsContainer/get) */ + get(options?: CredentialRequestOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CredentialsContainer/preventSilentAccess) */ + preventSilentAccess(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CredentialsContainer/store) */ + store(credential: Credential): Promise; +} + +declare var CredentialsContainer: { + prototype: CredentialsContainer; + new(): CredentialsContainer; +}; + +/** + * Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto) + */ +interface Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + readonly subtle: SubtleCrypto; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues(array: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): `${string}-${string}-${string}-${string}-${string}`; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + +/** + * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) + */ +interface CryptoKey { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: KeyAlgorithm; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: KeyType; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: KeyUsage[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry) */ +interface CustomElementRegistry { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/define) */ + define(name: string, constructor: CustomElementConstructor, options?: ElementDefinitionOptions): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/get) */ + get(name: string): CustomElementConstructor | undefined; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/getName) */ + getName(constructor: CustomElementConstructor): string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/upgrade) */ + upgrade(root: Node): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/whenDefined) */ + whenDefined(name: string): Promise; +} + +declare var CustomElementRegistry: { + prototype: CustomElementRegistry; + new(): CustomElementRegistry; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ +interface CustomEvent extends Event { + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + readonly detail: T; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/initCustomEvent) + */ + initCustomEvent(type: string, bubbles?: boolean, cancelable?: boolean, detail?: T): void; +} + +declare var CustomEvent: { + prototype: CustomEvent; + new(type: string, eventInitDict?: CustomEventInit): CustomEvent; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomStateSet) */ +interface CustomStateSet { + forEach(callbackfn: (value: string, key: string, parent: CustomStateSet) => void, thisArg?: any): void; +} + +declare var CustomStateSet: { + prototype: CustomStateSet; + new(): CustomStateSet; +}; + +/** + * An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) + */ +interface DOMException extends Error { + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; +} + +declare var DOMException: { + prototype: DOMException; + new(message?: string, name?: string): DOMException; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; +}; + +/** + * An object providing methods which are not dependent on any particular document. Such an object is returned by the Document.implementation property. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMImplementation) + */ +interface DOMImplementation { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMImplementation/createDocument) */ + createDocument(namespace: string | null, qualifiedName: string | null, doctype?: DocumentType | null): XMLDocument; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMImplementation/createDocumentType) */ + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMImplementation/createHTMLDocument) */ + createHTMLDocument(title?: string): Document; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMImplementation/hasFeature) + */ + hasFeature(...args: any[]): true; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix) */ +interface DOMMatrix extends DOMMatrixReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + a: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + b: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + c: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + d: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + e: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + f: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m11: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m12: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m13: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m14: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m21: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m22: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m23: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m24: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m31: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m32: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m33: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m34: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m41: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m42: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m43: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ + m44: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/invertSelf) */ + invertSelf(): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/multiplySelf) */ + multiplySelf(other?: DOMMatrixInit): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/preMultiplySelf) */ + preMultiplySelf(other?: DOMMatrixInit): DOMMatrix; + rotateAxisAngleSelf(x?: number, y?: number, z?: number, angle?: number): DOMMatrix; + rotateFromVectorSelf(x?: number, y?: number): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/rotateSelf) */ + rotateSelf(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix; + scale3dSelf(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + scaleSelf(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/setMatrixValue) */ + setMatrixValue(transformList: string): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/skewXSelf) */ + skewXSelf(sx?: number): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/skewYSelf) */ + skewYSelf(sy?: number): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/translateSelf) */ + translateSelf(tx?: number, ty?: number, tz?: number): DOMMatrix; +} + +declare var DOMMatrix: { + prototype: DOMMatrix; + new(init?: string | number[]): DOMMatrix; + fromFloat32Array(array32: Float32Array): DOMMatrix; + fromFloat64Array(array64: Float64Array): DOMMatrix; + fromMatrix(other?: DOMMatrixInit): DOMMatrix; +}; + +type SVGMatrix = DOMMatrix; +declare var SVGMatrix: typeof DOMMatrix; + +type WebKitCSSMatrix = DOMMatrix; +declare var WebKitCSSMatrix: typeof DOMMatrix; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly) */ +interface DOMMatrixReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly a: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly b: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly c: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly d: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly e: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly f: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/is2D) */ + readonly is2D: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/isIdentity) */ + readonly isIdentity: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m11: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m12: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m13: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m14: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m21: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m22: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m23: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m24: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m31: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m32: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m33: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m34: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m41: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m42: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m43: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ + readonly m44: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/flipX) */ + flipX(): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/flipY) */ + flipY(): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/inverse) */ + inverse(): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/multiply) */ + multiply(other?: DOMMatrixInit): DOMMatrix; + rotate(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix; + rotateAxisAngle(x?: number, y?: number, z?: number, angle?: number): DOMMatrix; + rotateFromVector(x?: number, y?: number): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/scale) */ + scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix; + /** @deprecated */ + scaleNonUniform(scaleX?: number, scaleY?: number): DOMMatrix; + skewX(sx?: number): DOMMatrix; + skewY(sy?: number): DOMMatrix; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/toFloat32Array) */ + toFloat32Array(): Float32Array; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/toFloat64Array) */ + toFloat64Array(): Float64Array; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/toJSON) */ + toJSON(): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/transformPoint) */ + transformPoint(point?: DOMPointInit): DOMPoint; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/translate) */ + translate(tx?: number, ty?: number, tz?: number): DOMMatrix; + toString(): string; +} + +declare var DOMMatrixReadOnly: { + prototype: DOMMatrixReadOnly; + new(init?: string | number[]): DOMMatrixReadOnly; + fromFloat32Array(array32: Float32Array): DOMMatrixReadOnly; + fromFloat64Array(array64: Float64Array): DOMMatrixReadOnly; + fromMatrix(other?: DOMMatrixInit): DOMMatrixReadOnly; +}; + +/** + * Provides the ability to parse XML or HTML source code from a string into a DOM Document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMParser) + */ +interface DOMParser { + /** + * Parses string using either the HTML or XML parser, according to type, and returns the resulting Document. type can be "text/html" (which will invoke the HTML parser), or any of "text/xml", "application/xml", "application/xhtml+xml", or "image/svg+xml" (which will invoke the XML parser). + * + * For the XML parser, if string cannot be parsed, then the returned Document will contain elements describing the resulting error. + * + * Note that script elements are not evaluated during parsing, and the resulting document's encoding will always be UTF-8. + * + * Values other than the above for type will cause a TypeError exception to be thrown. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMParser/parseFromString) + */ + parseFromString(string: string, type: DOMParserSupportedType): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPoint) */ +interface DOMPoint extends DOMPointReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPoint/w) */ + w: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPoint/x) */ + x: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPoint/y) */ + y: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPoint/z) */ + z: number; +} + +declare var DOMPoint: { + prototype: DOMPoint; + new(x?: number, y?: number, z?: number, w?: number): DOMPoint; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPoint/fromPoint_static) */ + fromPoint(other?: DOMPointInit): DOMPoint; +}; + +type SVGPoint = DOMPoint; +declare var SVGPoint: typeof DOMPoint; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly) */ +interface DOMPointReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/w) */ + readonly w: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/x) */ + readonly x: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/y) */ + readonly y: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/z) */ + readonly z: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/matrixTransform) */ + matrixTransform(matrix?: DOMMatrixInit): DOMPoint; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/toJSON) */ + toJSON(): any; +} + +declare var DOMPointReadOnly: { + prototype: DOMPointReadOnly; + new(x?: number, y?: number, z?: number, w?: number): DOMPointReadOnly; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/fromPoint_static) */ + fromPoint(other?: DOMPointInit): DOMPointReadOnly; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad) */ +interface DOMQuad { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/p1) */ + readonly p1: DOMPoint; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/p2) */ + readonly p2: DOMPoint; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/p3) */ + readonly p3: DOMPoint; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/p4) */ + readonly p4: DOMPoint; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/getBounds) */ + getBounds(): DOMRect; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/toJSON) */ + toJSON(): any; +} + +declare var DOMQuad: { + prototype: DOMQuad; + new(p1?: DOMPointInit, p2?: DOMPointInit, p3?: DOMPointInit, p4?: DOMPointInit): DOMQuad; + fromQuad(other?: DOMQuadInit): DOMQuad; + fromRect(other?: DOMRectInit): DOMQuad; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRect) */ +interface DOMRect extends DOMRectReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRect/height) */ + height: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRect/width) */ + width: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRect/x) */ + x: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRect/y) */ + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new(x?: number, y?: number, width?: number, height?: number): DOMRect; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRect/fromRect_static) */ + fromRect(other?: DOMRectInit): DOMRect; +}; + +type SVGRect = DOMRect; +declare var SVGRect: typeof DOMRect; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectList) */ +interface DOMRectList { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectList/length) */ + readonly length: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectList/item) */ + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + +declare var DOMRectList: { + prototype: DOMRectList; + new(): DOMRectList; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly) */ +interface DOMRectReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/bottom) */ + readonly bottom: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/height) */ + readonly height: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/left) */ + readonly left: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/right) */ + readonly right: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/top) */ + readonly top: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/width) */ + readonly width: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/x) */ + readonly x: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/y) */ + readonly y: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/toJSON) */ + toJSON(): any; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new(x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRectReadOnly/fromRect_static) */ + fromRect(other?: DOMRectInit): DOMRectReadOnly; +}; + +/** + * A type returned by some APIs which contains a list of DOMString (strings). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMStringList) + */ +interface DOMStringList { + /** + * Returns the number of strings in strings. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMStringList/length) + */ + readonly length: number; + /** + * Returns true if strings contains string, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMStringList/contains) + */ + contains(string: string): boolean; + /** + * Returns the string with index index from strings. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMStringList/item) + */ + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +}; + +/** + * Used by the dataset HTML attribute to represent data for custom attributes added to elements. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMStringMap) + */ +interface DOMStringMap { + [name: string]: string | undefined; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +}; + +/** + * A set of space-separated tokens. Such a set is returned by Element.classList, HTMLLinkElement.relList, HTMLAnchorElement.relList, HTMLAreaElement.relList, HTMLIframeElement.sandbox, or HTMLOutputElement.htmlFor. It is indexed beginning with 0 as with JavaScript Array objects. DOMTokenList is always case-sensitive. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList) + */ +interface DOMTokenList { + /** + * Returns the number of tokens. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList/length) + */ + readonly length: number; + /** + * Returns the associated set as string. + * + * Can be set, to change the associated attribute. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList/value) + */ + value: string; + toString(): string; + /** + * Adds all arguments passed, except those already present. + * + * Throws a "SyntaxError" DOMException if one of the arguments is the empty string. + * + * Throws an "InvalidCharacterError" DOMException if one of the arguments contains any ASCII whitespace. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList/add) + */ + add(...tokens: string[]): void; + /** + * Returns true if token is present, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList/contains) + */ + contains(token: string): boolean; + /** + * Returns the token with index index. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList/item) + */ + item(index: number): string | null; + /** + * Removes arguments passed, if they are present. + * + * Throws a "SyntaxError" DOMException if one of the arguments is the empty string. + * + * Throws an "InvalidCharacterError" DOMException if one of the arguments contains any ASCII whitespace. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList/remove) + */ + remove(...tokens: string[]): void; + /** + * Replaces token with newToken. + * + * Returns true if token was replaced with newToken, and false otherwise. + * + * Throws a "SyntaxError" DOMException if one of the arguments is the empty string. + * + * Throws an "InvalidCharacterError" DOMException if one of the arguments contains any ASCII whitespace. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList/replace) + */ + replace(token: string, newToken: string): boolean; + /** + * Returns true if token is in the associated attribute's supported tokens. Returns false otherwise. + * + * Throws a TypeError if the associated attribute has no supported tokens defined. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList/supports) + */ + supports(token: string): boolean; + /** + * If force is not given, "toggles" token, removing it if it's present and adding it if it's not present. If force is true, adds token (same as add()). If force is false, removes token (same as remove()). + * + * Returns true if token is now present, and false otherwise. + * + * Throws a "SyntaxError" DOMException if token is empty. + * + * Throws an "InvalidCharacterError" DOMException if token contains any spaces. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMTokenList/toggle) + */ + toggle(token: string, force?: boolean): boolean; + forEach(callbackfn: (value: string, key: number, parent: DOMTokenList) => void, thisArg?: any): void; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +}; + +/** + * Used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types. For more information about drag and drop, see HTML Drag and Drop API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer) + */ +interface DataTransfer { + /** + * Returns the kind of operation that is currently selected. If the kind of operation isn't one of those that is allowed by the effectAllowed attribute, then the operation will fail. + * + * Can be set, to change the selected operation. + * + * The possible values are "none", "copy", "link", and "move". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/dropEffect) + */ + dropEffect: "none" | "copy" | "link" | "move"; + /** + * Returns the kinds of operations that are to be allowed. + * + * Can be set (during the dragstart event), to change the allowed operations. + * + * The possible values are "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", and "uninitialized", + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/effectAllowed) + */ + effectAllowed: "none" | "copy" | "copyLink" | "copyMove" | "link" | "linkMove" | "move" | "all" | "uninitialized"; + /** + * Returns a FileList of the files being dragged, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/files) + */ + readonly files: FileList; + /** + * Returns a DataTransferItemList object, with the drag data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/items) + */ + readonly items: DataTransferItemList; + /** + * Returns a frozen array listing the formats that were set in the dragstart event. In addition, if any files are being dragged, then one of the types will be the string "Files". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/types) + */ + readonly types: ReadonlyArray; + /** + * Removes the data of the specified formats. Removes all data if the argument is omitted. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/clearData) + */ + clearData(format?: string): void; + /** + * Returns the specified data. If there is no such data, returns the empty string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/getData) + */ + getData(format: string): string; + /** + * Adds the specified data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/setData) + */ + setData(format: string, data: string): void; + /** + * Uses the given element to update the drag feedback, replacing any previously specified feedback. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/setDragImage) + */ + setDragImage(image: Element, x: number, y: number): void; +} + +declare var DataTransfer: { + prototype: DataTransfer; + new(): DataTransfer; +}; + +/** + * One drag data item. During a drag operation, each drag event has a dataTransfer property which contains a list of drag data items. Each item in the list is a DataTransferItem object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItem) + */ +interface DataTransferItem { + /** + * Returns the drag data item kind, one of: "string", "file". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItem/kind) + */ + readonly kind: string; + /** + * Returns the drag data item type string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItem/type) + */ + readonly type: string; + /** + * Returns a File object, if the drag data item kind is File. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItem/getAsFile) + */ + getAsFile(): File | null; + /** + * Invokes the callback with the string data as the argument, if the drag data item kind is text. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItem/getAsString) + */ + getAsString(callback: FunctionStringCallback | null): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItem/webkitGetAsEntry) */ + webkitGetAsEntry(): FileSystemEntry | null; +} + +declare var DataTransferItem: { + prototype: DataTransferItem; + new(): DataTransferItem; +}; + +/** + * A list of DataTransferItem objects representing items being dragged. During a drag operation, each DragEvent has a dataTransfer property and that property is a DataTransferItemList. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItemList) + */ +interface DataTransferItemList { + /** + * Returns the number of items in the drag data store. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItemList/length) + */ + readonly length: number; + /** + * Adds a new entry for the given data to the drag data store. If the data is plain text then a type string has to be provided also. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItemList/add) + */ + add(data: string, type: string): DataTransferItem | null; + add(data: File): DataTransferItem | null; + /** + * Removes all the entries in the drag data store. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItemList/clear) + */ + clear(): void; + /** + * Removes the indexth entry in the drag data store. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransferItemList/remove) + */ + remove(index: number): void; + [index: number]: DataTransferItem; +} + +declare var DataTransferItemList: { + prototype: DataTransferItemList; + new(): DataTransferItemList; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ +interface DecompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; +} + +declare var DecompressionStream: { + prototype: DecompressionStream; + new(format: CompressionFormat): DecompressionStream; +}; + +/** + * A delay-line; an AudioNode audio-processing module that causes a delay between the arrival of an input data and its propagation to the output. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DelayNode) + */ +interface DelayNode extends AudioNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DelayNode/delayTime) */ + readonly delayTime: AudioParam; +} + +declare var DelayNode: { + prototype: DelayNode; + new(context: BaseAudioContext, options?: DelayOptions): DelayNode; +}; + +/** + * The DeviceMotionEvent provides web developers with information about the speed of changes for the device's position and orientation. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent) + */ +interface DeviceMotionEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent/acceleration) */ + readonly acceleration: DeviceMotionEventAcceleration | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent/accelerationIncludingGravity) */ + readonly accelerationIncludingGravity: DeviceMotionEventAcceleration | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent/interval) */ + readonly interval: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEvent/rotationRate) */ + readonly rotationRate: DeviceMotionEventRotationRate | null; +} + +declare var DeviceMotionEvent: { + prototype: DeviceMotionEvent; + new(type: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEventAcceleration) + */ +interface DeviceMotionEventAcceleration { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEventAcceleration/x) */ + readonly x: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEventAcceleration/y) */ + readonly y: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEventAcceleration/z) */ + readonly z: number | null; +} + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEventRotationRate) + */ +interface DeviceMotionEventRotationRate { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEventRotationRate/alpha) */ + readonly alpha: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEventRotationRate/beta) */ + readonly beta: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceMotionEventRotationRate/gamma) */ + readonly gamma: number | null; +} + +/** + * The DeviceOrientationEvent provides web developers with information from the physical orientation of the device running the web page. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent) + */ +interface DeviceOrientationEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent/absolute) */ + readonly absolute: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent/alpha) */ + readonly alpha: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent/beta) */ + readonly beta: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DeviceOrientationEvent/gamma) */ + readonly gamma: number | null; +} + +declare var DeviceOrientationEvent: { + prototype: DeviceOrientationEvent; + new(type: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; +}; + +interface DocumentEventMap extends GlobalEventHandlersEventMap { + "DOMContentLoaded": Event; + "fullscreenchange": Event; + "fullscreenerror": Event; + "pointerlockchange": Event; + "pointerlockerror": Event; + "readystatechange": Event; + "visibilitychange": Event; +} + +/** + * Any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document) + */ +interface Document extends Node, DocumentOrShadowRoot, FontFaceSource, GlobalEventHandlers, NonElementParentNode, ParentNode, XPathEvaluatorBase { + /** + * Sets or gets the URL for the current document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/URL) + */ + readonly URL: string; + /** + * Sets or gets the color of all active links in the document. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/alinkColor) + */ + alinkColor: string; + /** + * Returns a reference to the collection of elements contained by the object. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/all) + */ + readonly all: HTMLAllCollection; + /** + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/anchors) + */ + readonly anchors: HTMLCollectionOf; + /** + * Retrieves a collection of all applet objects in the document. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/applets) + */ + readonly applets: HTMLCollection; + /** + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/bgColor) + */ + bgColor: string; + /** + * Specifies the beginning and end of the document body. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/body) + */ + body: HTMLElement; + /** + * Returns document's encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/characterSet) + */ + readonly characterSet: string; + /** + * Gets or sets the character set used to encode the object. + * @deprecated This is a legacy alias of `characterSet`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/characterSet) + */ + readonly charset: string; + /** + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/compatMode) + */ + readonly compatMode: string; + /** + * Returns document's content type. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/contentType) + */ + readonly contentType: string; + /** + * Returns the HTTP cookies that apply to the Document. If there are no cookies or cookies can't be applied to this resource, the empty string will be returned. + * + * Can be set, to add a new cookie to the element's set of HTTP cookies. + * + * If the contents are sandboxed into a unique origin (e.g. in an iframe with the sandbox attribute), a "SecurityError" DOMException will be thrown on getting and setting. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/cookie) + */ + cookie: string; + /** + * Returns the script element, or the SVG script element, that is currently executing, as long as the element represents a classic script. In the case of reentrant script execution, returns the one that most recently started executing amongst those that have not yet finished executing. + * + * Returns null if the Document is not currently executing a script or SVG script element (e.g., because the running script is an event handler, or a timeout), or if the currently executing script or SVG script element represents a module script. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/currentScript) + */ + readonly currentScript: HTMLOrSVGScriptElement | null; + /** + * Returns the Window object of the active document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/defaultView) + */ + readonly defaultView: (WindowProxy & typeof globalThis) | null; + /** + * Sets or gets a value that indicates whether the document can be edited. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/designMode) + */ + designMode: string; + /** + * Sets or retrieves a value that indicates the reading order of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/dir) + */ + dir: string; + /** + * Gets an object representing the document type declaration associated with the current document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/doctype) + */ + readonly doctype: DocumentType | null; + /** + * Gets a reference to the root node of the document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/documentElement) + */ + readonly documentElement: HTMLElement; + /** + * Returns document's URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/documentURI) + */ + readonly documentURI: string; + /** + * Sets or gets the security domain of the document. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/domain) + */ + domain: string; + /** + * Retrieves a collection of all embed objects in the document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/embeds) + */ + readonly embeds: HTMLCollectionOf; + /** + * Sets or gets the foreground (text) color of the document. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/fgColor) + */ + fgColor: string; + /** + * Retrieves a collection, in source order, of all form objects in the document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/forms) + */ + readonly forms: HTMLCollectionOf; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/fragmentDirective) */ + readonly fragmentDirective: FragmentDirective; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/fullscreen) + */ + readonly fullscreen: boolean; + /** + * Returns true if document has the ability to display elements fullscreen and fullscreen is supported, or false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/fullscreenEnabled) + */ + readonly fullscreenEnabled: boolean; + /** + * Returns the head element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/head) + */ + readonly head: HTMLHeadElement; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/hidden) */ + readonly hidden: boolean; + /** + * Retrieves a collection, in source order, of img objects in the document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/images) + */ + readonly images: HTMLCollectionOf; + /** + * Gets the implementation object of the current document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/implementation) + */ + readonly implementation: DOMImplementation; + /** + * Returns the character encoding used to create the webpage that is loaded into the document object. + * @deprecated This is a legacy alias of `characterSet`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/characterSet) + */ + readonly inputEncoding: string; + /** + * Gets the date that the page was last modified, if the page supplies one. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/lastModified) + */ + readonly lastModified: string; + /** + * Sets or gets the color of the document links. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/linkColor) + */ + linkColor: string; + /** + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/links) + */ + readonly links: HTMLCollectionOf; + /** + * Contains information about the current URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/location) + */ + get location(): Location; + set location(href: string); + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/fullscreenchange_event) */ + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/fullscreenerror_event) */ + onfullscreenerror: ((this: Document, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/pointerlockchange_event) */ + onpointerlockchange: ((this: Document, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/pointerlockerror_event) */ + onpointerlockerror: ((this: Document, ev: Event) => any) | null; + /** + * Fires when the state of the object has changed. + * @param ev The event + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/readystatechange_event) + */ + onreadystatechange: ((this: Document, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/visibilitychange_event) */ + onvisibilitychange: ((this: Document, ev: Event) => any) | null; + readonly ownerDocument: null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/pictureInPictureEnabled) */ + readonly pictureInPictureEnabled: boolean; + /** + * Return an HTMLCollection of the embed elements in the Document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/plugins) + */ + readonly plugins: HTMLCollectionOf; + /** + * Retrieves a value that indicates the current state of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/readyState) + */ + readonly readyState: DocumentReadyState; + /** + * Gets the URL of the location that referred the user to the current page. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/referrer) + */ + readonly referrer: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/rootElement) + */ + readonly rootElement: SVGSVGElement | null; + /** + * Retrieves a collection of all script objects in the document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/scripts) + */ + readonly scripts: HTMLCollectionOf; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/scrollingElement) */ + readonly scrollingElement: Element | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/timeline) */ + readonly timeline: DocumentTimeline; + /** + * Contains the title of the document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/title) + */ + title: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/visibilityState) */ + readonly visibilityState: DocumentVisibilityState; + /** + * Sets or gets the color of the links that the user has visited. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/vlinkColor) + */ + vlinkColor: string; + /** + * Moves node from another document and returns it. + * + * If node is a document, throws a "NotSupportedError" DOMException or, if node is a shadow root, throws a "HierarchyRequestError" DOMException. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/adoptNode) + */ + adoptNode(node: T): T; + /** @deprecated */ + captureEvents(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/caretPositionFromPoint) */ + caretPositionFromPoint(x: number, y: number, options?: CaretPositionFromPointOptions): CaretPosition | null; + /** @deprecated */ + caretRangeFromPoint(x: number, y: number): Range | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/clear) + */ + clear(): void; + /** + * Closes an output stream and forces the sent data to display. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/close) + */ + close(): void; + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createAttribute) + */ + createAttribute(localName: string): Attr; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createAttributeNS) */ + createAttributeNS(namespace: string | null, qualifiedName: string): Attr; + /** + * Returns a CDATASection node whose data is data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createCDATASection) + */ + createCDATASection(data: string): CDATASection; + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createComment) + */ + createComment(data: string): Comment; + /** + * Creates a new document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createDocumentFragment) + */ + createDocumentFragment(): DocumentFragment; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElement) + */ + createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; + /** @deprecated */ + createElement(tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; + createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; + /** + * Returns an element with namespace namespace. Its namespace prefix will be everything before ":" (U+003E) in qualifiedName or null. Its local name will be everything after ":" (U+003E) in qualifiedName or qualifiedName. + * + * If localName does not match the Name production an "InvalidCharacterError" DOMException will be thrown. + * + * If one of the following conditions is true a "NamespaceError" DOMException will be thrown: + * + * localName does not match the QName production. + * Namespace prefix is not null and namespace is the empty string. + * Namespace prefix is "xml" and namespace is not the XML namespace. + * qualifiedName or namespace prefix is "xmlns" and namespace is not the XMLNS namespace. + * namespace is the XMLNS namespace and neither qualifiedName nor namespace prefix is "xmlns". + * + * When supplied, options's is can be used to create a customized built-in element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElementNS) + */ + createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: K): SVGElementTagNameMap[K]; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; + createElementNS(namespaceURI: "http://www.w3.org/1998/Math/MathML", qualifiedName: K): MathMLElementTagNameMap[K]; + createElementNS(namespaceURI: "http://www.w3.org/1998/Math/MathML", qualifiedName: string): MathMLElement; + createElementNS(namespaceURI: string | null, qualifiedName: string, options?: ElementCreationOptions): Element; + createElementNS(namespace: string | null, qualifiedName: string, options?: string | ElementCreationOptions): Element; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createEvent) + */ + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "BlobEvent"): BlobEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "ContentVisibilityAutoStateChangeEvent"): ContentVisibilityAutoStateChangeEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FontFaceSetLoadEvent"): FontFaceSetLoadEvent; + createEvent(eventInterface: "FormDataEvent"): FormDataEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "InputEvent"): InputEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "MIDIConnectionEvent"): MIDIConnectionEvent; + createEvent(eventInterface: "MIDIMessageEvent"): MIDIMessageEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "PageRevealEvent"): PageRevealEvent; + createEvent(eventInterface: "PageSwapEvent"): PageSwapEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentMethodChangeEvent"): PaymentMethodChangeEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PictureInPictureEvent"): PictureInPictureEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "PromiseRejectionEvent"): PromiseRejectionEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDataChannelEvent"): RTCDataChannelEvent; + createEvent(eventInterface: "RTCErrorEvent"): RTCErrorEvent; + createEvent(eventInterface: "RTCPeerConnectionIceErrorEvent"): RTCPeerConnectionIceErrorEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCTrackEvent"): RTCTrackEvent; + createEvent(eventInterface: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + createEvent(eventInterface: "SpeechSynthesisErrorEvent"): SpeechSynthesisErrorEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "SubmitEvent"): SubmitEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "ToggleEvent"): ToggleEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; + /** + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createNodeIterator) + */ + createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter | null): NodeIterator; + /** + * Returns a ProcessingInstruction node whose target is target and data is data. If target does not match the Name production an "InvalidCharacterError" DOMException will be thrown. If data contains "?>" an "InvalidCharacterError" DOMException will be thrown. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction) + */ + createProcessingInstruction(target: string, data: string): ProcessingInstruction; + /** + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createRange) + */ + createRange(): Range; + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createTextNode) + */ + createTextNode(data: string): Text; + /** + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createTreeWalker) + */ + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter | null): TreeWalker; + /** + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/execCommand) + */ + execCommand(commandId: string, showUI?: boolean, value?: string): boolean; + /** + * Stops document's fullscreen element from being displayed fullscreen and resolves promise when done. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/exitFullscreen) + */ + exitFullscreen(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/exitPictureInPicture) */ + exitPictureInPicture(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/exitPointerLock) */ + exitPointerLock(): void; + /** + * Returns a reference to the first object with the specified value of the ID attribute. + * @param elementId String that specifies the ID value. + */ + getElementById(elementId: string): HTMLElement | null; + /** + * Returns a HTMLCollection of the elements in the object on which the method was invoked (a document or an element) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/getElementsByClassName) + */ + getElementsByClassName(classNames: string): HTMLCollectionOf; + /** + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/getElementsByName) + */ + getElementsByName(elementName: string): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/getElementsByTagName) + */ + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + /** @deprecated */ + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: string): HTMLCollectionOf; + /** + * If namespace and localName are "*" returns a HTMLCollection of all descendant elements. + * + * If only namespace is "*" returns a HTMLCollection of all descendant elements whose local name is localName. + * + * If only localName is "*" returns a HTMLCollection of all descendant elements whose namespace is namespace. + * + * Otherwise, returns a HTMLCollection of all descendant elements whose namespace is namespace and local name is localName. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/getElementsByTagNameNS) + */ + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1998/Math/MathML", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespace: string | null, localName: string): HTMLCollectionOf; + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/getSelection) + */ + getSelection(): Selection | null; + /** + * Gets a value indicating whether the object currently has focus. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/hasFocus) + */ + hasFocus(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/hasStorageAccess) */ + hasStorageAccess(): Promise; + /** + * Returns a copy of node. If deep is true, the copy also includes the node's descendants. + * + * If node is a document or a shadow root, throws a "NotSupportedError" DOMException. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/importNode) + */ + importNode(node: T, subtree?: boolean): T; + /** + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/open) + */ + open(unused1?: string, unused2?: string): Document; + open(url: string | URL, name: string, features: string): WindowProxy | null; + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/queryCommandEnabled) + */ + queryCommandEnabled(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + * @deprecated + */ + queryCommandIndeterm(commandId: string): boolean; + /** + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/queryCommandState) + */ + queryCommandState(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/queryCommandSupported) + */ + queryCommandSupported(commandId: string): boolean; + /** + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + * @deprecated + */ + queryCommandValue(commandId: string): string; + /** @deprecated */ + releaseEvents(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/requestStorageAccess) */ + requestStorageAccess(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/startViewTransition) */ + startViewTransition(callbackOptions?: ViewTransitionUpdateCallback): ViewTransition; + /** + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/write) + */ + write(...text: string[]): void; + /** + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/writeln) + */ + writeln(...text: string[]): void; + addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Document: { + prototype: Document; + new(): Document; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/parseHTMLUnsafe_static) */ + parseHTMLUnsafe(html: string): Document; +}; + +/** + * A minimal document object that has no parent. It is used as a lightweight version of Document that stores a segment of a document structure comprised of nodes just like a standard document. The key difference is that because the document fragment isn't part of the active document tree structure, changes made to the fragment don't affect the document, cause reflow, or incur any performance impact that can occur when changes are made. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentFragment) + */ +interface DocumentFragment extends Node, NonElementParentNode, ParentNode { + readonly ownerDocument: Document; + getElementById(elementId: string): HTMLElement | null; +} + +declare var DocumentFragment: { + prototype: DocumentFragment; + new(): DocumentFragment; +}; + +interface DocumentOrShadowRoot { + /** + * Returns the deepest element in the document through which or to which key events are being routed. This is, roughly speaking, the focused element in the document. + * + * For the purposes of this API, when a child browsing context is focused, its container is focused in the parent browsing context. For example, if the user moves the focus to a text control in an iframe, the iframe is the element returned by the activeElement API in the iframe's node document. + * + * Similarly, when the focused element is in a different node tree than documentOrShadowRoot, the element returned will be the host that's located in the same node tree as documentOrShadowRoot if documentOrShadowRoot is a shadow-including inclusive ancestor of the focused element, and null if not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/activeElement) + */ + readonly activeElement: Element | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/adoptedStyleSheets) */ + adoptedStyleSheets: CSSStyleSheet[]; + /** + * Returns document's fullscreen element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/fullscreenElement) + */ + readonly fullscreenElement: Element | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/pictureInPictureElement) */ + readonly pictureInPictureElement: Element | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/pointerLockElement) */ + readonly pointerLockElement: Element | null; + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/styleSheets) + */ + readonly styleSheets: StyleSheetList; + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/getAnimations) */ + getAnimations(): Animation[]; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentTimeline) */ +interface DocumentTimeline extends AnimationTimeline { +} + +declare var DocumentTimeline: { + prototype: DocumentTimeline; + new(options?: DocumentTimelineOptions): DocumentTimeline; +}; + +/** + * A Node containing a doctype. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentType) + */ +interface DocumentType extends Node, ChildNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentType/name) */ + readonly name: string; + readonly ownerDocument: Document; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentType/publicId) */ + readonly publicId: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DocumentType/systemId) */ + readonly systemId: string; +} + +declare var DocumentType: { + prototype: DocumentType; + new(): DocumentType; +}; + +/** + * A DOM event that represents a drag and drop interaction. The user initiates a drag by placing a pointer device (such as a mouse) on the touch surface and then dragging the pointer to a new location (such as another DOM element). Applications are free to interpret a drag and drop interaction in an application-specific way. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DragEvent) + */ +interface DragEvent extends MouseEvent { + /** + * Returns the DataTransfer object for the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DragEvent/dataTransfer) + */ + readonly dataTransfer: DataTransfer | null; +} + +declare var DragEvent: { + prototype: DragEvent; + new(type: string, eventInitDict?: DragEventInit): DragEvent; +}; + +/** + * Inherits properties from its parent, AudioNode. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DynamicsCompressorNode) + */ +interface DynamicsCompressorNode extends AudioNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DynamicsCompressorNode/attack) */ + readonly attack: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DynamicsCompressorNode/knee) */ + readonly knee: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DynamicsCompressorNode/ratio) */ + readonly ratio: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DynamicsCompressorNode/reduction) */ + readonly reduction: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DynamicsCompressorNode/release) */ + readonly release: AudioParam; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DynamicsCompressorNode/threshold) */ + readonly threshold: AudioParam; +} + +declare var DynamicsCompressorNode: { + prototype: DynamicsCompressorNode; + new(context: BaseAudioContext, options?: DynamicsCompressorOptions): DynamicsCompressorNode; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_blend_minmax) */ +interface EXT_blend_minmax { + readonly MIN_EXT: 0x8007; + readonly MAX_EXT: 0x8008; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_color_buffer_float) */ +interface EXT_color_buffer_float { +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_color_buffer_half_float) */ +interface EXT_color_buffer_half_float { + readonly RGBA16F_EXT: 0x881A; + readonly RGB16F_EXT: 0x881B; + readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: 0x8211; + readonly UNSIGNED_NORMALIZED_EXT: 0x8C17; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_float_blend) */ +interface EXT_float_blend { +} + +/** + * The EXT_frag_depth extension is part of the WebGL API and enables to set a depth value of a fragment from within the fragment shader. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_frag_depth) + */ +interface EXT_frag_depth { +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_sRGB) */ +interface EXT_sRGB { + readonly SRGB_EXT: 0x8C40; + readonly SRGB_ALPHA_EXT: 0x8C42; + readonly SRGB8_ALPHA8_EXT: 0x8C43; + readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: 0x8210; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_shader_texture_lod) */ +interface EXT_shader_texture_lod { +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_texture_compression_bptc) */ +interface EXT_texture_compression_bptc { + readonly COMPRESSED_RGBA_BPTC_UNORM_EXT: 0x8E8C; + readonly COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT: 0x8E8D; + readonly COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT: 0x8E8E; + readonly COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT: 0x8E8F; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_texture_compression_rgtc) */ +interface EXT_texture_compression_rgtc { + readonly COMPRESSED_RED_RGTC1_EXT: 0x8DBB; + readonly COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8DBC; + readonly COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8DBD; + readonly COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8DBE; +} + +/** + * The EXT_texture_filter_anisotropic extension is part of the WebGL API and exposes two constants for anisotropic filtering (AF). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_texture_filter_anisotropic) + */ +interface EXT_texture_filter_anisotropic { + readonly TEXTURE_MAX_ANISOTROPY_EXT: 0x84FE; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: 0x84FF; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EXT_texture_norm16) */ +interface EXT_texture_norm16 { + readonly R16_EXT: 0x822A; + readonly RG16_EXT: 0x822C; + readonly RGB16_EXT: 0x8054; + readonly RGBA16_EXT: 0x805B; + readonly R16_SNORM_EXT: 0x8F98; + readonly RG16_SNORM_EXT: 0x8F99; + readonly RGB16_SNORM_EXT: 0x8F9A; + readonly RGBA16_SNORM_EXT: 0x8F9B; +} + +interface ElementEventMap { + "fullscreenchange": Event; + "fullscreenerror": Event; +} + +/** + * Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element) + */ +interface Element extends Node, ARIAMixin, Animatable, ChildNode, NonDocumentTypeChildNode, ParentNode, Slottable { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/attributes) */ + readonly attributes: NamedNodeMap; + /** + * Allows for manipulation of element's class content attribute as a set of whitespace-separated tokens through a DOMTokenList object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/classList) + */ + get classList(): DOMTokenList; + set classList(value: string); + /** + * Returns the value of element's class content attribute. Can be set to change it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/className) + */ + className: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/clientHeight) */ + readonly clientHeight: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/clientLeft) */ + readonly clientLeft: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/clientTop) */ + readonly clientTop: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/clientWidth) */ + readonly clientWidth: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/currentCSSZoom) */ + readonly currentCSSZoom: number; + /** + * Returns the value of element's id content attribute. Can be set to change it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/id) + */ + id: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/innerHTML) */ + innerHTML: string; + /** + * Returns the local name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/localName) + */ + readonly localName: string; + /** + * Returns the namespace. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/namespaceURI) + */ + readonly namespaceURI: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/fullscreenchange_event) */ + onfullscreenchange: ((this: Element, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/fullscreenerror_event) */ + onfullscreenerror: ((this: Element, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/outerHTML) */ + outerHTML: string; + readonly ownerDocument: Document; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/part) */ + get part(): DOMTokenList; + set part(value: string); + /** + * Returns the namespace prefix. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/prefix) + */ + readonly prefix: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/scrollHeight) */ + readonly scrollHeight: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/scrollLeft) */ + scrollLeft: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/scrollTop) */ + scrollTop: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/scrollWidth) */ + readonly scrollWidth: number; + /** + * Returns element's shadow root, if any, and if shadow root's mode is "open", and null otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/shadowRoot) + */ + readonly shadowRoot: ShadowRoot | null; + /** + * Returns the value of element's slot content attribute. Can be set to change it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/slot) + */ + slot: string; + /** + * Returns the HTML-uppercased qualified name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/tagName) + */ + readonly tagName: string; + /** + * Creates a shadow root for element and returns it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/attachShadow) + */ + attachShadow(init: ShadowRootInit): ShadowRoot; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/checkVisibility) */ + checkVisibility(options?: CheckVisibilityOptions): boolean; + /** + * Returns the first (starting at element) inclusive ancestor that matches selectors, and null otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/closest) + */ + closest(selector: K): HTMLElementTagNameMap[K] | null; + closest(selector: K): SVGElementTagNameMap[K] | null; + closest(selector: K): MathMLElementTagNameMap[K] | null; + closest(selectors: string): E | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/computedStyleMap) */ + computedStyleMap(): StylePropertyMapReadOnly; + /** + * Returns element's first attribute whose qualified name is qualifiedName, and null if there is no such attribute otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttribute) + */ + getAttribute(qualifiedName: string): string | null; + /** + * Returns element's attribute whose namespace is namespace and local name is localName, and null if there is no such attribute otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttributeNS) + */ + getAttributeNS(namespace: string | null, localName: string): string | null; + /** + * Returns the qualified names of all element's attributes. Can contain duplicates. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttributeNames) + */ + getAttributeNames(): string[]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttributeNode) */ + getAttributeNode(qualifiedName: string): Attr | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAttributeNodeNS) */ + getAttributeNodeNS(namespace: string | null, localName: string): Attr | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getBoundingClientRect) */ + getBoundingClientRect(): DOMRect; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getClientRects) */ + getClientRects(): DOMRectList; + /** + * Returns a HTMLCollection of the elements in the object on which the method was invoked (a document or an element) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getElementsByClassName) + */ + getElementsByClassName(classNames: string): HTMLCollectionOf; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getElementsByTagName) */ + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + /** @deprecated */ + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: string): HTMLCollectionOf; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getElementsByTagNameNS) */ + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1998/Math/MathML", localName: string): HTMLCollectionOf; + getElementsByTagNameNS(namespace: string | null, localName: string): HTMLCollectionOf; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getHTML) */ + getHTML(options?: GetHTMLOptions): string; + /** + * Returns true if element has an attribute whose qualified name is qualifiedName, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/hasAttribute) + */ + hasAttribute(qualifiedName: string): boolean; + /** + * Returns true if element has an attribute whose namespace is namespace and local name is localName. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/hasAttributeNS) + */ + hasAttributeNS(namespace: string | null, localName: string): boolean; + /** + * Returns true if element has attributes, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/hasAttributes) + */ + hasAttributes(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/hasPointerCapture) */ + hasPointerCapture(pointerId: number): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/insertAdjacentElement) */ + insertAdjacentElement(where: InsertPosition, element: Element): Element | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/insertAdjacentHTML) */ + insertAdjacentHTML(position: InsertPosition, string: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/insertAdjacentText) */ + insertAdjacentText(where: InsertPosition, data: string): void; + /** + * Returns true if matching selectors against element's root yields element, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/matches) + */ + matches(selectors: string): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/releasePointerCapture) */ + releasePointerCapture(pointerId: number): void; + /** + * Removes element's first attribute whose qualified name is qualifiedName. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/removeAttribute) + */ + removeAttribute(qualifiedName: string): void; + /** + * Removes element's attribute whose namespace is namespace and local name is localName. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/removeAttributeNS) + */ + removeAttributeNS(namespace: string | null, localName: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/removeAttributeNode) */ + removeAttributeNode(attr: Attr): Attr; + /** + * Displays element fullscreen and resolves promise when done. + * + * When supplied, options's navigationUI member indicates whether showing navigation UI while in fullscreen is preferred or not. If set to "show", navigation simplicity is preferred over screen space, and if set to "hide", more screen space is preferred. User agents are always free to honor user preference over the application's. The default value "auto" indicates no application preference. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/requestFullscreen) + */ + requestFullscreen(options?: FullscreenOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/requestPointerLock) */ + requestPointerLock(options?: PointerLockOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/scroll) */ + scroll(options?: ScrollToOptions): void; + scroll(x: number, y: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/scrollBy) */ + scrollBy(options?: ScrollToOptions): void; + scrollBy(x: number, y: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/scrollIntoView) */ + scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/scrollTo) */ + scrollTo(options?: ScrollToOptions): void; + scrollTo(x: number, y: number): void; + /** + * Sets the value of element's first attribute whose qualified name is qualifiedName to value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setAttribute) + */ + setAttribute(qualifiedName: string, value: string): void; + /** + * Sets the value of element's attribute whose namespace is namespace and local name is localName to value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setAttributeNS) + */ + setAttributeNS(namespace: string | null, qualifiedName: string, value: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setAttributeNode) */ + setAttributeNode(attr: Attr): Attr | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setAttributeNodeNS) */ + setAttributeNodeNS(attr: Attr): Attr | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setHTMLUnsafe) */ + setHTMLUnsafe(html: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/setPointerCapture) */ + setPointerCapture(pointerId: number): void; + /** + * If force is not given, "toggles" qualifiedName, removing it if it is present and adding it if it is not present. If force is true, adds qualifiedName. If force is false, removes qualifiedName. + * + * Returns true if qualifiedName is now present, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/toggleAttribute) + */ + toggleAttribute(qualifiedName: string, force?: boolean): boolean; + /** + * @deprecated This is a legacy alias of `matches`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/matches) + */ + webkitMatchesSelector(selectors: string): boolean; + addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var Element: { + prototype: Element; + new(): Element; +}; + +interface ElementCSSInlineStyle { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/attributeStyleMap) */ + readonly attributeStyleMap: StylePropertyMap; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/style) */ + get style(): CSSStyleDeclaration; + set style(cssText: string); +} + +interface ElementContentEditable { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/contentEditable) */ + contentEditable: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/enterKeyHint) */ + enterKeyHint: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/inputMode) */ + inputMode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/isContentEditable) */ + readonly isContentEditable: boolean; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals) */ +interface ElementInternals extends ARIAMixin { + /** + * Returns the form owner of internals's target element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/form) + */ + readonly form: HTMLFormElement | null; + /** + * Returns a NodeList of all the label elements that internals's target element is associated with. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/labels) + */ + readonly labels: NodeList; + /** + * Returns the ShadowRoot for internals's target element, if the target element is a shadow host, or null otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/shadowRoot) + */ + readonly shadowRoot: ShadowRoot | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/states) */ + readonly states: CustomStateSet; + /** + * Returns the error message that would be shown to the user if internals's target element was to be checked for validity. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/validationMessage) + */ + readonly validationMessage: string; + /** + * Returns the ValidityState object for internals's target element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/validity) + */ + readonly validity: ValidityState; + /** + * Returns true if internals's target element will be validated when the form is submitted; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/willValidate) + */ + readonly willValidate: boolean; + /** + * Returns true if internals's target element has no validity problems; false otherwise. Fires an invalid event at the element in the latter case. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/checkValidity) + */ + checkValidity(): boolean; + /** + * Returns true if internals's target element has no validity problems; otherwise, returns false, fires an invalid event at the element, and (if the event isn't canceled) reports the problem to the user. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/reportValidity) + */ + reportValidity(): boolean; + /** + * Sets both the state and submission value of internals's target element to value. + * + * If value is null, the element won't participate in form submission. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/setFormValue) + */ + setFormValue(value: File | string | FormData | null, state?: File | string | FormData | null): void; + /** + * Marks internals's target element as suffering from the constraints indicated by the flags argument, and sets the element's validation message to message. If anchor is specified, the user agent might use it to indicate problems with the constraints of internals's target element when the form owner is validated interactively or reportValidity() is called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ElementInternals/setValidity) + */ + setValidity(flags?: ValidityStateFlags, message?: string, anchor?: HTMLElement): void; +} + +declare var ElementInternals: { + prototype: ElementInternals; + new(): ElementInternals; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk) */ +interface EncodedAudioChunk { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/byteLength) */ + readonly byteLength: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/duration) */ + readonly duration: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/timestamp) */ + readonly timestamp: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/type) */ + readonly type: EncodedAudioChunkType; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/copyTo) */ + copyTo(destination: AllowSharedBufferSource): void; +} + +declare var EncodedAudioChunk: { + prototype: EncodedAudioChunk; + new(init: EncodedAudioChunkInit): EncodedAudioChunk; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk) */ +interface EncodedVideoChunk { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk/byteLength) */ + readonly byteLength: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk/duration) */ + readonly duration: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk/timestamp) */ + readonly timestamp: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk/type) */ + readonly type: EncodedVideoChunkType; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk/copyTo) */ + copyTo(destination: AllowSharedBufferSource): void; +} + +declare var EncodedVideoChunk: { + prototype: EncodedVideoChunk; + new(init: EncodedVideoChunkInit): EncodedVideoChunk; +}; + +/** + * Events providing information related to errors in scripts or in files. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) + */ +interface ErrorEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + readonly colno: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + readonly error: any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + readonly filename: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + readonly lineno: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + readonly message: string; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent; +}; + +/** + * An event which takes place in the DOM. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) + */ +interface Event { + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + readonly bubbles: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + cancelBubble: boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + readonly cancelable: boolean; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + readonly composed: boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + readonly currentTarget: EventTarget | null; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + readonly defaultPrevented: boolean; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + readonly eventPhase: number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + readonly isTrusted: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + returnValue: boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + readonly srcElement: EventTarget | null; + /** + * Returns the object to which event is dispatched (its target). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) + */ + readonly target: EventTarget | null; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + readonly timeStamp: DOMHighResTimeStamp; + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + readonly type: string; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/initEvent) + */ + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + readonly NONE: 0; + readonly CAPTURING_PHASE: 1; + readonly AT_TARGET: 2; + readonly BUBBLING_PHASE: 3; +} + +declare var Event: { + prototype: Event; + new(type: string, eventInitDict?: EventInit): Event; + readonly NONE: 0; + readonly CAPTURING_PHASE: 1; + readonly AT_TARGET: 2; + readonly BUBBLING_PHASE: 3; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventCounts) */ +interface EventCounts { + forEach(callbackfn: (value: number, key: string, parent: EventCounts) => void, thisArg?: any): void; +} + +declare var EventCounts: { + prototype: EventCounts; + new(): EventCounts; +}; + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +interface EventSourceEventMap { + "error": Event; + "message": MessageEvent; + "open": Event; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ +interface EventSource extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + onerror: ((this: EventSource, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + onmessage: ((this: EventSource, ev: MessageEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + onopen: ((this: EventSource, ev: Event) => any) | null; + /** + * Returns the state of this EventSource object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + readonly readyState: number; + /** + * Returns the URL providing the event stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + readonly url: string; + /** + * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + readonly withCredentials: boolean; + /** + * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + readonly CONNECTING: 0; + readonly OPEN: 1; + readonly CLOSED: 2; + addEventListener(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: (this: EventSource, event: MessageEvent) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: (this: EventSource, event: MessageEvent) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string | URL, eventSourceInitDict?: EventSourceInit): EventSource; + readonly CONNECTING: 0; + readonly OPEN: 1; + readonly CLOSED: 2; +}; + +/** + * EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) + */ +interface EventTarget { + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: AddEventListenerOptions | boolean): void; + /** + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: Event): boolean; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +}; + +/** @deprecated */ +interface External { + /** @deprecated */ + AddSearchProvider(): void; + /** @deprecated */ + IsSearchProviderInstalled(): void; +} + +/** @deprecated */ +declare var External: { + prototype: External; + new(): External; +}; + +/** + * Provides information about files and allows JavaScript in a web page to access their content. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) + */ +interface File extends Blob { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/webkitRelativePath) */ + readonly webkitRelativePath: string; +} + +declare var File: { + prototype: File; + new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File; +}; + +/** + * An object of this type is returned by the files property of the HTML element; this lets you access the list of files selected with the element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileList) + */ +interface FileList { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileList/length) */ + readonly length: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileList/item) */ + item(index: number): File | null; + [index: number]: File; +} + +declare var FileList: { + prototype: FileList; + new(): FileList; +}; + +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +/** + * Lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader) + */ +interface FileReader extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/error) */ + readonly error: DOMException | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/abort_event) */ + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/error_event) */ + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/load_event) */ + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/loadend_event) */ + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/loadstart_event) */ + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/progress_event) */ + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/readyState) */ + readonly readyState: typeof FileReader.EMPTY | typeof FileReader.LOADING | typeof FileReader.DONE; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/result) */ + readonly result: string | ArrayBuffer | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/abort) */ + abort(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/readAsArrayBuffer) */ + readAsArrayBuffer(blob: Blob): void; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/readAsBinaryString) + */ + readAsBinaryString(blob: Blob): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/readAsDataURL) */ + readAsDataURL(blob: Blob): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileReader/readAsText) */ + readAsText(blob: Blob, encoding?: string): void; + readonly EMPTY: 0; + readonly LOADING: 1; + readonly DONE: 2; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; + readonly EMPTY: 0; + readonly LOADING: 1; + readonly DONE: 2; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystem) */ +interface FileSystem { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystem/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystem/root) */ + readonly root: FileSystemDirectoryEntry; +} + +declare var FileSystem: { + prototype: FileSystem; + new(): FileSystem; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryEntry) */ +interface FileSystemDirectoryEntry extends FileSystemEntry { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryEntry/createReader) */ + createReader(): FileSystemDirectoryReader; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryEntry/getDirectory) */ + getDirectory(path?: string | null, options?: FileSystemFlags, successCallback?: FileSystemEntryCallback, errorCallback?: ErrorCallback): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryEntry/getFile) */ + getFile(path?: string | null, options?: FileSystemFlags, successCallback?: FileSystemEntryCallback, errorCallback?: ErrorCallback): void; +} + +declare var FileSystemDirectoryEntry: { + prototype: FileSystemDirectoryEntry; + new(): FileSystemDirectoryEntry; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryHandle) + */ +interface FileSystemDirectoryHandle extends FileSystemHandle { + readonly kind: "directory"; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryHandle/getDirectoryHandle) */ + getDirectoryHandle(name: string, options?: FileSystemGetDirectoryOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryHandle/getFileHandle) */ + getFileHandle(name: string, options?: FileSystemGetFileOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryHandle/removeEntry) */ + removeEntry(name: string, options?: FileSystemRemoveOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryHandle/resolve) */ + resolve(possibleDescendant: FileSystemHandle): Promise; +} + +declare var FileSystemDirectoryHandle: { + prototype: FileSystemDirectoryHandle; + new(): FileSystemDirectoryHandle; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryReader) */ +interface FileSystemDirectoryReader { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemDirectoryReader/readEntries) */ + readEntries(successCallback: FileSystemEntriesCallback, errorCallback?: ErrorCallback): void; +} + +declare var FileSystemDirectoryReader: { + prototype: FileSystemDirectoryReader; + new(): FileSystemDirectoryReader; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemEntry) */ +interface FileSystemEntry { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemEntry/filesystem) */ + readonly filesystem: FileSystem; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemEntry/fullPath) */ + readonly fullPath: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemEntry/isDirectory) */ + readonly isDirectory: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemEntry/isFile) */ + readonly isFile: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemEntry/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemEntry/getParent) */ + getParent(successCallback?: FileSystemEntryCallback, errorCallback?: ErrorCallback): void; +} + +declare var FileSystemEntry: { + prototype: FileSystemEntry; + new(): FileSystemEntry; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemFileEntry) */ +interface FileSystemFileEntry extends FileSystemEntry { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemFileEntry/file) */ + file(successCallback: FileCallback, errorCallback?: ErrorCallback): void; +} + +declare var FileSystemFileEntry: { + prototype: FileSystemFileEntry; + new(): FileSystemFileEntry; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemFileHandle) + */ +interface FileSystemFileHandle extends FileSystemHandle { + readonly kind: "file"; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemFileHandle/createWritable) */ + createWritable(options?: FileSystemCreateWritableOptions): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemFileHandle/getFile) */ + getFile(): Promise; +} + +declare var FileSystemFileHandle: { + prototype: FileSystemFileHandle; + new(): FileSystemFileHandle; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemHandle) + */ +interface FileSystemHandle { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemHandle/kind) */ + readonly kind: FileSystemHandleKind; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemHandle/name) */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemHandle/isSameEntry) */ + isSameEntry(other: FileSystemHandle): Promise; +} + +declare var FileSystemHandle: { + prototype: FileSystemHandle; + new(): FileSystemHandle; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemWritableFileStream) + */ +interface FileSystemWritableFileStream extends WritableStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemWritableFileStream/seek) */ + seek(position: number): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemWritableFileStream/truncate) */ + truncate(size: number): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FileSystemWritableFileStream/write) */ + write(data: FileSystemWriteChunkType): Promise; +} + +declare var FileSystemWritableFileStream: { + prototype: FileSystemWritableFileStream; + new(): FileSystemWritableFileStream; +}; + +/** + * Focus-related events like focus, blur, focusin, or focusout. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FocusEvent) + */ +interface FocusEvent extends UIEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FocusEvent/relatedTarget) */ + readonly relatedTarget: EventTarget | null; +} + +declare var FocusEvent: { + prototype: FocusEvent; + new(type: string, eventInitDict?: FocusEventInit): FocusEvent; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace) */ +interface FontFace { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/ascentOverride) */ + ascentOverride: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/descentOverride) */ + descentOverride: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/display) */ + display: FontDisplay; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/family) */ + family: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/featureSettings) */ + featureSettings: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/lineGapOverride) */ + lineGapOverride: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/loaded) */ + readonly loaded: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/status) */ + readonly status: FontFaceLoadStatus; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/stretch) */ + stretch: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/style) */ + style: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/unicodeRange) */ + unicodeRange: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/weight) */ + weight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFace/load) */ + load(): Promise; +} + +declare var FontFace: { + prototype: FontFace; + new(family: string, source: string | BufferSource, descriptors?: FontFaceDescriptors): FontFace; +}; + +interface FontFaceSetEventMap { + "loading": FontFaceSetLoadEvent; + "loadingdone": FontFaceSetLoadEvent; + "loadingerror": FontFaceSetLoadEvent; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet) */ +interface FontFaceSet extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/loading_event) */ + onloading: ((this: FontFaceSet, ev: FontFaceSetLoadEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/loadingdone_event) */ + onloadingdone: ((this: FontFaceSet, ev: FontFaceSetLoadEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/loadingerror_event) */ + onloadingerror: ((this: FontFaceSet, ev: FontFaceSetLoadEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/ready) */ + readonly ready: Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/status) */ + readonly status: FontFaceSetLoadStatus; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/check) */ + check(font: string, text?: string): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/load) */ + load(font: string, text?: string): Promise; + forEach(callbackfn: (value: FontFace, key: FontFace, parent: FontFaceSet) => void, thisArg?: any): void; + addEventListener(type: K, listener: (this: FontFaceSet, ev: FontFaceSetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FontFaceSet, ev: FontFaceSetEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var FontFaceSet: { + prototype: FontFaceSet; + new(): FontFaceSet; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSetLoadEvent) */ +interface FontFaceSetLoadEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSetLoadEvent/fontfaces) */ + readonly fontfaces: ReadonlyArray; +} + +declare var FontFaceSetLoadEvent: { + prototype: FontFaceSetLoadEvent; + new(type: string, eventInitDict?: FontFaceSetLoadEventInit): FontFaceSetLoadEvent; +}; + +interface FontFaceSource { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/fonts) */ + readonly fonts: FontFaceSet; +} + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) + */ +interface FormData { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ + append(name: string, value: string | Blob): void; + append(name: string, value: string): void; + append(name: string, blobValue: Blob, filename?: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) */ + delete(name: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) */ + get(name: string): FormDataEntryValue | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) */ + getAll(name: string): FormDataEntryValue[]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ + has(name: string): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ + set(name: string, value: string | Blob): void; + set(name: string, value: string): void; + set(name: string, blobValue: Blob, filename?: string): void; + forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void; +} + +declare var FormData: { + prototype: FormData; + new(form?: HTMLFormElement, submitter?: HTMLElement | null): FormData; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormDataEvent) */ +interface FormDataEvent extends Event { + /** + * Returns a FormData object representing names and values of elements associated to the target form. Operations on the FormData object will affect form data to be submitted. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormDataEvent/formData) + */ + readonly formData: FormData; +} + +declare var FormDataEvent: { + prototype: FormDataEvent; + new(type: string, eventInitDict: FormDataEventInit): FormDataEvent; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FragmentDirective) */ +interface FragmentDirective { +} + +declare var FragmentDirective: { + prototype: FragmentDirective; + new(): FragmentDirective; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GPUError) + */ +interface GPUError { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GPUError/message) */ + readonly message: string; +} + +/** + * A change in volume. It is an AudioNode audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. A GainNode always has exactly one input and one output, both with the same number of channels. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GainNode) + */ +interface GainNode extends AudioNode { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GainNode/gain) */ + readonly gain: AudioParam; +} + +declare var GainNode: { + prototype: GainNode; + new(context: BaseAudioContext, options?: GainOptions): GainNode; +}; + +/** + * This Gamepad API interface defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Gamepad) + */ +interface Gamepad { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Gamepad/axes) */ + readonly axes: ReadonlyArray; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Gamepad/buttons) */ + readonly buttons: ReadonlyArray; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Gamepad/connected) */ + readonly connected: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Gamepad/id) */ + readonly id: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Gamepad/index) */ + readonly index: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Gamepad/mapping) */ + readonly mapping: GamepadMappingType; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Gamepad/timestamp) */ + readonly timestamp: DOMHighResTimeStamp; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Gamepad/vibrationActuator) */ + readonly vibrationActuator: GamepadHapticActuator; +} + +declare var Gamepad: { + prototype: Gamepad; + new(): Gamepad; +}; + +/** + * An individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadButton) + */ +interface GamepadButton { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadButton/pressed) */ + readonly pressed: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadButton/touched) */ + readonly touched: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadButton/value) */ + readonly value: number; +} + +declare var GamepadButton: { + prototype: GamepadButton; + new(): GamepadButton; +}; + +/** + * This Gamepad API interface contains references to gamepads connected to the system, which is what the gamepad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadEvent) + */ +interface GamepadEvent extends Event { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadEvent/gamepad) */ + readonly gamepad: Gamepad; +} + +declare var GamepadEvent: { + prototype: GamepadEvent; + new(type: string, eventInitDict: GamepadEventInit): GamepadEvent; +}; + +/** + * This Gamepad API interface represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadHapticActuator) + */ +interface GamepadHapticActuator { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadHapticActuator/playEffect) */ + playEffect(type: GamepadHapticEffectType, params?: GamepadEffectParameters): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadHapticActuator/reset) */ + reset(): Promise; +} + +declare var GamepadHapticActuator: { + prototype: GamepadHapticActuator; + new(): GamepadHapticActuator; +}; + +interface GenericTransformStream { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream/readable) */ + readonly readable: ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream/writable) */ + readonly writable: WritableStream; +} + +/** + * An object able to programmatically obtain the position of the device. It gives Web content access to the location of the device. This allows a Web site or app to offer customized results based on the user's location. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Geolocation) + */ +interface Geolocation { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Geolocation/clearWatch) */ + clearWatch(watchId: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Geolocation/getCurrentPosition) */ + getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback | null, options?: PositionOptions): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Geolocation/watchPosition) */ + watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback | null, options?: PositionOptions): number; +} + +declare var Geolocation: { + prototype: Geolocation; + new(): Geolocation; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationCoordinates) + */ +interface GeolocationCoordinates { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationCoordinates/accuracy) */ + readonly accuracy: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationCoordinates/altitude) */ + readonly altitude: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationCoordinates/altitudeAccuracy) */ + readonly altitudeAccuracy: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationCoordinates/heading) */ + readonly heading: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationCoordinates/latitude) */ + readonly latitude: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationCoordinates/longitude) */ + readonly longitude: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationCoordinates/speed) */ + readonly speed: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationCoordinates/toJSON) */ + toJSON(): any; +} + +declare var GeolocationCoordinates: { + prototype: GeolocationCoordinates; + new(): GeolocationCoordinates; +}; + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPosition) + */ +interface GeolocationPosition { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPosition/coords) */ + readonly coords: GeolocationCoordinates; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPosition/timestamp) */ + readonly timestamp: EpochTimeStamp; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPosition/toJSON) */ + toJSON(): any; +} + +declare var GeolocationPosition: { + prototype: GeolocationPosition; + new(): GeolocationPosition; +}; + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPositionError) */ +interface GeolocationPositionError { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPositionError/code) */ + readonly code: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GeolocationPositionError/message) */ + readonly message: string; + readonly PERMISSION_DENIED: 1; + readonly POSITION_UNAVAILABLE: 2; + readonly TIMEOUT: 3; +} + +declare var GeolocationPositionError: { + prototype: GeolocationPositionError; + new(): GeolocationPositionError; + readonly PERMISSION_DENIED: 1; + readonly POSITION_UNAVAILABLE: 2; + readonly TIMEOUT: 3; +}; + +interface GlobalEventHandlersEventMap { + "abort": UIEvent; + "animationcancel": AnimationEvent; + "animationend": AnimationEvent; + "animationiteration": AnimationEvent; + "animationstart": AnimationEvent; + "auxclick": MouseEvent; + "beforeinput": InputEvent; + "beforetoggle": Event; + "blur": FocusEvent; + "cancel": Event; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "close": Event; + "compositionend": CompositionEvent; + "compositionstart": CompositionEvent; + "compositionupdate": CompositionEvent; + "contextlost": Event; + "contextmenu": MouseEvent; + "contextrestored": Event; + "copy": ClipboardEvent; + "cuechange": Event; + "cut": ClipboardEvent; + "dblclick": MouseEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": Event; + "error": ErrorEvent; + "focus": FocusEvent; + "focusin": FocusEvent; + "focusout": FocusEvent; + "formdata": FormDataEvent; + "gotpointercapture": PointerEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadstart": Event; + "lostpointercapture": PointerEvent; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "paste": ClipboardEvent; + "pause": Event; + "play": Event; + "playing": Event; + "pointercancel": PointerEvent; + "pointerdown": PointerEvent; + "pointerenter": PointerEvent; + "pointerleave": PointerEvent; + "pointermove": PointerEvent; + "pointerout": PointerEvent; + "pointerover": PointerEvent; + "pointerup": PointerEvent; + "progress": ProgressEvent; + "ratechange": Event; + "reset": Event; + "resize": UIEvent; + "scroll": Event; + "scrollend": Event; + "securitypolicyviolation": SecurityPolicyViolationEvent; + "seeked": Event; + "seeking": Event; + "select": Event; + "selectionchange": Event; + "selectstart": Event; + "slotchange": Event; + "stalled": Event; + "submit": SubmitEvent; + "suspend": Event; + "timeupdate": Event; + "toggle": Event; + "touchcancel": TouchEvent; + "touchend": TouchEvent; + "touchmove": TouchEvent; + "touchstart": TouchEvent; + "transitioncancel": TransitionEvent; + "transitionend": TransitionEvent; + "transitionrun": TransitionEvent; + "transitionstart": TransitionEvent; + "volumechange": Event; + "waiting": Event; + "webkitanimationend": Event; + "webkitanimationiteration": Event; + "webkitanimationstart": Event; + "webkittransitionend": Event; + "wheel": WheelEvent; +} + +interface GlobalEventHandlers { + /** + * Fires when the user aborts the download. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/abort_event) + */ + onabort: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationcancel_event) */ + onanimationcancel: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationend_event) */ + onanimationend: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationiteration_event) */ + onanimationiteration: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationstart_event) */ + onanimationstart: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/auxclick_event) */ + onauxclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/beforeinput_event) */ + onbeforeinput: ((this: GlobalEventHandlers, ev: InputEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/beforetoggle_event) */ + onbeforetoggle: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/blur_event) + */ + onblur: ((this: GlobalEventHandlers, ev: FocusEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDialogElement/cancel_event) */ + oncancel: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/canplay_event) + */ + oncanplay: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/canplaythrough_event) */ + oncanplaythrough: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/change_event) + */ + onchange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/click_event) + */ + onclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDialogElement/close_event) */ + onclose: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement/contextlost_event) */ + oncontextlost: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/contextmenu_event) + */ + oncontextmenu: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement/contextrestored_event) */ + oncontextrestored: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/copy_event) */ + oncopy: ((this: GlobalEventHandlers, ev: ClipboardEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTrackElement/cuechange_event) */ + oncuechange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/cut_event) */ + oncut: ((this: GlobalEventHandlers, ev: ClipboardEvent) => any) | null; + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/dblclick_event) + */ + ondblclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/drag_event) + */ + ondrag: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragend_event) + */ + ondragend: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragenter_event) + */ + ondragenter: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragleave_event) + */ + ondragleave: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragover_event) + */ + ondragover: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragstart_event) + */ + ondragstart: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/drop_event) */ + ondrop: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/durationchange_event) + */ + ondurationchange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/emptied_event) + */ + onemptied: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the end of playback is reached. + * @param ev The event + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/ended_event) + */ + onended: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when an error occurs during object loading. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/error_event) + */ + onerror: OnErrorEventHandler; + /** + * Fires when the object receives focus. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/focus_event) + */ + onfocus: ((this: GlobalEventHandlers, ev: FocusEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/formdata_event) */ + onformdata: ((this: GlobalEventHandlers, ev: FormDataEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/gotpointercapture_event) */ + ongotpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/input_event) */ + oninput: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/invalid_event) */ + oninvalid: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/keydown_event) + */ + onkeydown: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null; + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/keypress_event) + */ + onkeypress: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/keyup_event) + */ + onkeyup: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null; + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGElement/load_event) + */ + onload: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/loadeddata_event) + */ + onloadeddata: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/loadedmetadata_event) + */ + onloadedmetadata: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/loadstart_event) + */ + onloadstart: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/lostpointercapture_event) */ + onlostpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mousedown_event) + */ + onmousedown: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseenter_event) */ + onmouseenter: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseleave_event) */ + onmouseleave: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mousemove_event) + */ + onmousemove: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseout_event) + */ + onmouseout: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseover_event) + */ + onmouseover: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseup_event) + */ + onmouseup: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/paste_event) */ + onpaste: ((this: GlobalEventHandlers, ev: ClipboardEvent) => any) | null; + /** + * Occurs when playback is paused. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/pause_event) + */ + onpause: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the play method is requested. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/play_event) + */ + onplay: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/playing_event) + */ + onplaying: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointercancel_event) */ + onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerdown_event) */ + onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerenter_event) */ + onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerleave_event) */ + onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointermove_event) */ + onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerout_event) */ + onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerover_event) */ + onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerup_event) */ + onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/progress_event) + */ + onprogress: ((this: GlobalEventHandlers, ev: ProgressEvent) => any) | null; + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/ratechange_event) + */ + onratechange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user resets a form. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/reset_event) + */ + onreset: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement/resize_event) */ + onresize: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/scroll_event) + */ + onscroll: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/scrollend_event) */ + onscrollend: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/securitypolicyviolation_event) */ + onsecuritypolicyviolation: ((this: GlobalEventHandlers, ev: SecurityPolicyViolationEvent) => any) | null; + /** + * Occurs when the seek operation ends. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/seeked_event) + */ + onseeked: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the current playback position is moved. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/seeking_event) + */ + onseeking: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the current selection changes. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/select_event) + */ + onselect: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event) */ + onselectionchange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/selectstart_event) */ + onselectstart: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSlotElement/slotchange_event) */ + onslotchange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the download has stopped. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/stalled_event) + */ + onstalled: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/submit_event) */ + onsubmit: ((this: GlobalEventHandlers, ev: SubmitEvent) => any) | null; + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/suspend_event) + */ + onsuspend: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs to indicate the current playback position. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/timeupdate_event) + */ + ontimeupdate: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/toggle_event) */ + ontoggle: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/touchcancel_event) */ + ontouchcancel?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/touchend_event) */ + ontouchend?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/touchmove_event) */ + ontouchmove?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/touchstart_event) */ + ontouchstart?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/transitioncancel_event) */ + ontransitioncancel: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/transitionend_event) */ + ontransitionend: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/transitionrun_event) */ + ontransitionrun: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/transitionstart_event) */ + ontransitionstart: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/volumechange_event) + */ + onvolumechange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/waiting_event) + */ + onwaiting: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * @deprecated This is a legacy alias of `onanimationend`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationend_event) + */ + onwebkitanimationend: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * @deprecated This is a legacy alias of `onanimationiteration`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationiteration_event) + */ + onwebkitanimationiteration: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * @deprecated This is a legacy alias of `onanimationstart`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationstart_event) + */ + onwebkitanimationstart: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * @deprecated This is a legacy alias of `ontransitionend`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/transitionend_event) + */ + onwebkittransitionend: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/wheel_event) */ + onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; + addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAllCollection) */ +interface HTMLAllCollection { + /** + * Returns the number of elements in the collection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAllCollection/length) + */ + readonly length: number; + /** + * Returns the item with index index from the collection (determined by tree order). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAllCollection/item) + */ + item(nameOrIndex?: string): HTMLCollection | Element | null; + /** + * Returns the item with ID or name name from the collection. + * + * If there are multiple matching items, then an HTMLCollection object containing all those elements is returned. + * + * Only button, form, iframe, input, map, meta, object, select, and textarea elements can have a name for the purpose of this method; their name is given by the value of their name attribute. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAllCollection/namedItem) + */ + namedItem(name: string): HTMLCollection | Element | null; + [index: number]: Element; +} + +declare var HTMLAllCollection: { + prototype: HTMLAllCollection; + new(): HTMLAllCollection; +}; + +/** + * Hyperlink elements and provides special properties and methods (beyond those of the regular HTMLElement object interface that they inherit from) for manipulating the layout and presentation of such elements. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement) + */ +interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { + /** + * Sets or retrieves the character set used to encode the object. + * @deprecated + */ + charset: string; + /** + * Sets or retrieves the coordinates of the object. + * @deprecated + */ + coords: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/download) */ + download: string; + /** + * Sets or retrieves the language code of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/hreflang) + */ + hreflang: string; + /** + * Sets or retrieves the shape of the object. + * @deprecated + */ + name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/ping) */ + ping: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/referrerPolicy) */ + referrerPolicy: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/rel) + */ + rel: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/relList) */ + get relList(): DOMTokenList; + set relList(value: string); + /** + * Sets or retrieves the relationship between the object and the destination of the link. + * @deprecated + */ + rev: string; + /** + * Sets or retrieves the shape of the object. + * @deprecated + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/target) + */ + target: string; + /** + * Retrieves or sets the text of the object as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/text) + */ + text: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAnchorElement/type) */ + type: string; + addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new(): HTMLAnchorElement; +}; + +/** + * Provides special properties and methods (beyond those of the regular object HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of elements. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement) + */ +interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { + /** + * Sets or retrieves a text alternative to the graphic. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement/alt) + */ + alt: string; + /** + * Sets or retrieves the coordinates of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement/coords) + */ + coords: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement/download) */ + download: string; + /** + * Sets or gets whether clicks in this region cause action. + * @deprecated + */ + noHref: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement/ping) */ + ping: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement/referrerPolicy) */ + referrerPolicy: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement/rel) */ + rel: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement/relList) */ + get relList(): DOMTokenList; + set relList(value: string); + /** + * Sets or retrieves the shape of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement/shape) + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLAreaElement/target) + */ + target: string; + addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new(): HTMLAreaElement; +}; + +/** + * Provides access to the properties of